From 5284fefcdeef6a3a1279552706b74cdee723eccd Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 20 Sep 2016 11:12:53 +1000 Subject: [PATCH 001/897] If a dependent layer is redrawn, then also redraw child layer --- src/core/qgsvectorlayer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index e811bb7def15..e657d2dee2f7 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -4139,6 +4139,7 @@ bool QgsVectorLayer::setDependencies( const QSet& oDeps ) disconnect( lyr, SIGNAL( featureDeleted( QgsFeatureId ) ), this, SIGNAL( dataChanged() ) ); disconnect( lyr, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SIGNAL( dataChanged() ) ); disconnect( lyr, SIGNAL( dataChanged() ), this, SIGNAL( dataChanged() ) ); + disconnect( lyr, SIGNAL( repaintRequested() ), this, SLOT( triggerRepaint() ) ); } // assign new dependencies @@ -4158,6 +4159,7 @@ bool QgsVectorLayer::setDependencies( const QSet& oDeps ) connect( lyr, SIGNAL( featureDeleted( QgsFeatureId ) ), this, SIGNAL( dataChanged() ) ); connect( lyr, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SIGNAL( dataChanged() ) ); connect( lyr, SIGNAL( dataChanged() ), this, SIGNAL( dataChanged() ) ); + connect( lyr, SIGNAL( repaintRequested() ), this, SLOT( triggerRepaint() ) ); } // if new layers are present, emit a data change From a50ce7d4fd675af8e11dba50be130956c8cb939a Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Tue, 27 Sep 2016 15:41:04 +0200 Subject: [PATCH 002/897] No need to decode a str --- python/pyplugin_installer/installer.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/pyplugin_installer/installer.py b/python/pyplugin_installer/installer.py index f646579193dd..3996c66ae775 100644 --- a/python/pyplugin_installer/installer.py +++ b/python/pyplugin_installer/installer.py @@ -444,7 +444,6 @@ def editRepository(self, reposName): """ edit repository connection """ if not reposName: return - reposName = reposName.decode('utf-8') checkState = {False: Qt.Unchecked, True: Qt.Checked} dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow()) dlg.editName.setText(reposName) From 31a1c239039c31cb12a5815287b22c425d3ee0b1 Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Mon, 26 Sep 2016 13:51:37 +0200 Subject: [PATCH 003/897] Add auto-discovery of relations for PostgresQL Fixed the add relation functionnality: the table is sorted. When the code was setting the sorted column, the row was sorted and the other columns it was setting were set on the wrong row. --- python/core/qgsrelation.sip | 15 +++ python/core/qgsrelationmanager.sip | 10 ++ python/core/qgsvectordataprovider.sip | 9 ++ src/app/CMakeLists.txt | 2 + src/app/qgsdiscoverrelationsdlg.cpp | 61 +++++++++ src/app/qgsdiscoverrelationsdlg.h | 53 ++++++++ src/app/qgsrelationmanagerdialog.cpp | 16 ++- src/app/qgsrelationmanagerdialog.h | 1 + src/core/qgsrelation.cpp | 15 +++ src/core/qgsrelation.h | 17 +++ src/core/qgsrelationmanager.cpp | 26 ++++ src/core/qgsrelationmanager.h | 10 ++ src/core/qgsvectordataprovider.cpp | 5 + src/core/qgsvectordataprovider.h | 10 ++ .../postgres/qgspostgresprovider.cpp | 79 ++++++++++++ src/providers/postgres/qgspostgresprovider.h | 7 ++ src/ui/qgsdiscoverrelationsdlgbase.ui | 117 ++++++++++++++++++ src/ui/qgsrelationmanagerdialogbase.ui | 11 ++ .../src/python/test_qgsrelationeditwidget.py | 39 ++++-- 19 files changed, 495 insertions(+), 8 deletions(-) create mode 100644 src/app/qgsdiscoverrelationsdlg.cpp create mode 100644 src/app/qgsdiscoverrelationsdlg.h create mode 100644 src/ui/qgsdiscoverrelationsdlgbase.ui diff --git a/python/core/qgsrelation.sip b/python/core/qgsrelation.sip index ea4a1f5dc866..cc347aa2a3bf 100644 --- a/python/core/qgsrelation.sip +++ b/python/core/qgsrelation.sip @@ -171,6 +171,12 @@ class QgsRelation */ QString id() const; + /** + * Generate a (project-wide) unique id for this relation + * @note added in QGIS 3.0 + */ + void generateId(); + /** * Access the referencing (child) layer's id * This is the layer which has the field(s) which point to another layer @@ -241,6 +247,15 @@ class QgsRelation */ bool isValid() const; + /** + * Compares the two QgsRelation, ignoring the name and the ID. + * + * @param other The other relation + * @return true if they are similar + * @note added in QGIS 3.0 + */ + bool hasEqualDefinition( const QgsRelation& other ) const; + protected: /** * Updates the validity status of this relation. diff --git a/python/core/qgsrelationmanager.sip b/python/core/qgsrelationmanager.sip index c77d16766599..4704694fe124 100644 --- a/python/core/qgsrelationmanager.sip +++ b/python/core/qgsrelationmanager.sip @@ -90,6 +90,16 @@ class QgsRelationManager : QObject */ QList referencedRelations( QgsVectorLayer *layer = 0 ) const; + /** + * Discover all the relations available from the current layers. + * + * @param existingRelations the existing relations to filter them out + * @param layers the current layers + * @return the list of discovered relations + * @note added in QGIS 3.0 + */ + static QList discoverRelations( const QList& existingRelations, const QList& layers ); + signals: /** This signal is emitted when the relations were loaded after reading a project */ void relationsLoaded(); diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 90185af66017..b9c62809c024 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -371,6 +371,15 @@ class QgsVectorDataProvider : QgsDataProvider */ virtual QSet dependencies() const; + /** + * Discover the available relations with the given layers. + * @param self the layer using this data provider. + * @param layers the other layers. + * @return the list of N-1 relations from this provider. + * @note added in QGIS 3.0 + */ + virtual QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const; + signals: /** Signals an error in this provider */ void raiseError( const QString& msg ); diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 26a59169ae59..81142ddb1190 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -28,6 +28,7 @@ SET(QGIS_APP_SRCS qgsdecorationscalebardialog.cpp qgsdecorationgrid.cpp qgsdecorationgriddialog.cpp + qgsdiscoverrelationsdlg.cpp qgsdxfexportdialog.cpp qgsformannotationdialog.cpp qgsguivectorlayertools.cpp @@ -207,6 +208,7 @@ SET (QGIS_APP_MOC_HDRS qgsdecorationgriddialog.h qgsdelattrdialog.h qgsdiagramproperties.h + qgsdiscoverrelationsdlg.h qgsdisplayangle.h qgsdxfexportdialog.h qgsfeatureaction.h diff --git a/src/app/qgsdiscoverrelationsdlg.cpp b/src/app/qgsdiscoverrelationsdlg.cpp new file mode 100644 index 000000000000..a524867f3f01 --- /dev/null +++ b/src/app/qgsdiscoverrelationsdlg.cpp @@ -0,0 +1,61 @@ +/*************************************************************************** + qgsdiscoverrelationsdlg.cpp + --------------------- + begin : September 2016 + copyright : (C) 2016 by Patrick Valsecchi + email : patrick dot valsecchi at camptocamp dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgsdiscoverrelationsdlg.h" +#include "qgsvectorlayer.h" +#include "qgsrelationmanager.h" + +#include + +QgsDiscoverRelationsDlg::QgsDiscoverRelationsDlg( const QList& existingRelations, const QList& layers, QWidget *parent ) + : QDialog( parent ) + , mLayers( layers ) +{ + setupUi( this ); + + mButtonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + connect( mRelationsTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsDiscoverRelationsDlg::onSelectionChanged ); + + mFoundRelations = QgsRelationManager::discoverRelations( existingRelations, layers ); + Q_FOREACH ( const QgsRelation& relation, mFoundRelations ) addRelation( relation ); + + mRelationsTable->resizeColumnsToContents(); + +} + +void QgsDiscoverRelationsDlg::addRelation( const QgsRelation &rel ) +{ + const int row = mRelationsTable->rowCount(); + mRelationsTable->insertRow( row ); + mRelationsTable->setItem( row, 0, new QTableWidgetItem( rel.name() ) ); + mRelationsTable->setItem( row, 1, new QTableWidgetItem( rel.referencingLayer()->name() ) ); + mRelationsTable->setItem( row, 2, new QTableWidgetItem( rel.fieldPairs().at( 0 ).referencingField() ) ); + mRelationsTable->setItem( row, 3, new QTableWidgetItem( rel.referencedLayer()->name() ) ); + mRelationsTable->setItem( row, 4, new QTableWidgetItem( rel.fieldPairs().at( 0 ).referencedField() ) ); +} + +QList QgsDiscoverRelationsDlg::relations() const +{ + QList result; + Q_FOREACH ( const QModelIndex& row, mRelationsTable->selectionModel()->selectedRows() ) + { + result.append( mFoundRelations.at( row.row() ) ); + } + return result; +} + +void QgsDiscoverRelationsDlg::onSelectionChanged() +{ + mButtonBox->button( QDialogButtonBox::Ok )->setEnabled( mRelationsTable->selectionModel()->hasSelection() ); +} \ No newline at end of file diff --git a/src/app/qgsdiscoverrelationsdlg.h b/src/app/qgsdiscoverrelationsdlg.h new file mode 100644 index 000000000000..b890b524e12c --- /dev/null +++ b/src/app/qgsdiscoverrelationsdlg.h @@ -0,0 +1,53 @@ +/*************************************************************************** + qgsdiscoverrelationsdlg.h + --------------------- + begin : September 2016 + copyright : (C) 2016 by Patrick Valsecchi + email : patrick dot valsecchi at camptocamp dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSDISCOVERRELATIONSDLG_H +#define QGSDISCOVERRELATIONSDLG_H + +#include +#include "ui_qgsdiscoverrelationsdlgbase.h" +#include "qgsrelation.h" + +class QgsRelationManager; +class QgsVectorLayer; + +/** + * Shows the list of relations discovered from the providers. + * + * The user can select some of them to add them to his project. + */ +class APP_EXPORT QgsDiscoverRelationsDlg : public QDialog, private Ui::QgsDiscoverRelationsDlgBase +{ + Q_OBJECT + + public: + explicit QgsDiscoverRelationsDlg( const QList& existingRelations, const QList& layers, QWidget *parent = nullptr ); + + /** + * Get the selected relations. + */ + QList relations() const; + + private slots: + void onSelectionChanged(); + + private: + QList mLayers; + QList mFoundRelations; + + void addRelation( const QgsRelation &rel ); + +}; + +#endif // QGSDISCOVERRELATIONSDLG_H diff --git a/src/app/qgsrelationmanagerdialog.cpp b/src/app/qgsrelationmanagerdialog.cpp index a7c78d6b69df..04314ada37cc 100644 --- a/src/app/qgsrelationmanagerdialog.cpp +++ b/src/app/qgsrelationmanagerdialog.cpp @@ -13,6 +13,7 @@ * * ***************************************************************************/ +#include "qgsdiscoverrelationsdlg.h" #include "qgsrelationadddlg.h" #include "qgsrelationmanagerdialog.h" #include "qgsrelationmanager.h" @@ -46,6 +47,7 @@ void QgsRelationManagerDialog::setLayers( const QList< QgsVectorLayer* >& layers void QgsRelationManagerDialog::addRelation( const QgsRelation &rel ) { + mRelationsTable->setSortingEnabled( false ); int row = mRelationsTable->rowCount(); mRelationsTable->insertRow( row ); @@ -54,7 +56,6 @@ void QgsRelationManagerDialog::addRelation( const QgsRelation &rel ) item->setData( Qt::UserRole, QVariant::fromValue( rel ) ); mRelationsTable->setItem( row, 0, item ); - item = new QTableWidgetItem( rel.referencingLayer()->name() ); item->setFlags( Qt::ItemIsEditable ); mRelationsTable->setItem( row, 1, item ); @@ -74,6 +75,7 @@ void QgsRelationManagerDialog::addRelation( const QgsRelation &rel ) item = new QTableWidgetItem( rel.id() ); item->setFlags( Qt::ItemIsEditable ); mRelationsTable->setItem( row, 5, item ); + mRelationsTable->setSortingEnabled( true ); } void QgsRelationManagerDialog::on_mBtnAddRelation_clicked() @@ -118,6 +120,18 @@ void QgsRelationManagerDialog::on_mBtnAddRelation_clicked() } } +void QgsRelationManagerDialog::on_mBtnDiscoverRelations_clicked() +{ + QgsDiscoverRelationsDlg discoverDlg( relations(), mLayers, this ); + if ( discoverDlg.exec() ) + { + Q_FOREACH ( const QgsRelation& relation, discoverDlg.relations() ) + { + addRelation( relation ); + } + } +} + void QgsRelationManagerDialog::on_mBtnRemoveRelation_clicked() { if ( mRelationsTable->currentIndex().isValid() ) diff --git a/src/app/qgsrelationmanagerdialog.h b/src/app/qgsrelationmanagerdialog.h index 8032beaa811a..cf7ad5917f8a 100644 --- a/src/app/qgsrelationmanagerdialog.h +++ b/src/app/qgsrelationmanagerdialog.h @@ -39,6 +39,7 @@ class APP_EXPORT QgsRelationManagerDialog : public QWidget, private Ui::QgsRelat public slots: void on_mBtnAddRelation_clicked(); + void on_mBtnDiscoverRelations_clicked(); void on_mBtnRemoveRelation_clicked(); private: diff --git a/src/core/qgsrelation.cpp b/src/core/qgsrelation.cpp index 49150eaf69da..42c77cfe31b2 100644 --- a/src/core/qgsrelation.cpp +++ b/src/core/qgsrelation.cpp @@ -248,6 +248,16 @@ QString QgsRelation::id() const return mRelationId; } +void QgsRelation::generateId() +{ + mRelationId = QString( "%1_%2_%3_%4" ) + .arg( referencingLayerId(), + mFieldPairs.at( 0 ).referencingField(), + referencedLayerId(), + mFieldPairs.at( 0 ).referencedField() ); + updateRelationStatus(); +} + QString QgsRelation::referencingLayerId() const { return mReferencingLayerId; @@ -301,6 +311,11 @@ bool QgsRelation::isValid() const return mValid; } +bool QgsRelation::hasEqualDefinition( const QgsRelation& other ) const +{ + return mReferencedLayerId == other.mReferencedLayerId && mReferencingLayerId == other.mReferencingLayerId && mFieldPairs == other.mFieldPairs; +} + void QgsRelation::updateRelationStatus() { const QMap& mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); diff --git a/src/core/qgsrelation.h b/src/core/qgsrelation.h index 94223e0adb92..7b2d9885c9de 100644 --- a/src/core/qgsrelation.h +++ b/src/core/qgsrelation.h @@ -57,6 +57,8 @@ class CORE_EXPORT QgsRelation QString referencingField() const { return first; } //! Get the name of the referenced (parent) field QString referencedField() const { return second; } + + bool operator==( const FieldPair& other ) const { return first == other.first && second == other.second; } }; /** @@ -210,6 +212,12 @@ class CORE_EXPORT QgsRelation */ QString id() const; + /** + * Generate a (project-wide) unique id for this relation + * @note added in QGIS 3.0 + */ + void generateId(); + /** * Access the referencing (child) layer's id * This is the layer which has the field(s) which point to another layer @@ -272,6 +280,15 @@ class CORE_EXPORT QgsRelation */ bool isValid() const; + /** + * Compares the two QgsRelation, ignoring the name and the ID. + * + * @param other The other relation + * @return true if they are similar + * @note added in QGIS 3.0 + */ + bool hasEqualDefinition( const QgsRelation& other ) const; + protected: /** * Updates the validity status of this relation. diff --git a/src/core/qgsrelationmanager.cpp b/src/core/qgsrelationmanager.cpp index bfd95abdd77c..dcafe4167e33 100644 --- a/src/core/qgsrelationmanager.cpp +++ b/src/core/qgsrelationmanager.cpp @@ -19,6 +19,7 @@ #include "qgslogger.h" #include "qgsmaplayerregistry.h" #include "qgsproject.h" +#include "qgsvectordataprovider.h" #include "qgsvectorlayer.h" QgsRelationManager::QgsRelationManager( QgsProject* project ) @@ -217,3 +218,28 @@ void QgsRelationManager::layersRemoved( const QStringList& layers ) emit changed(); } } + +static bool hasRelationWithEqualDefinition( const QList& existingRelations, const QgsRelation& relation ) +{ + Q_FOREACH ( const QgsRelation& cur, existingRelations ) + { + if ( cur.hasEqualDefinition( relation ) ) return true; + } + return false; +} + +QList QgsRelationManager::discoverRelations( const QList& existingRelations, const QList& layers ) +{ + QList result; + Q_FOREACH ( const QgsVectorLayer* layer, layers ) + { + Q_FOREACH ( const QgsRelation& relation, layer->dataProvider()->discoverRelations( layer, layers ) ) + { + if ( !hasRelationWithEqualDefinition( existingRelations, relation ) ) + { + result.append( relation ); + } + } + } + return result; +} diff --git a/src/core/qgsrelationmanager.h b/src/core/qgsrelationmanager.h index ff4d3c41c274..30450c6686d3 100644 --- a/src/core/qgsrelationmanager.h +++ b/src/core/qgsrelationmanager.h @@ -117,6 +117,16 @@ class CORE_EXPORT QgsRelationManager : public QObject */ QList referencedRelations( QgsVectorLayer *layer = nullptr ) const; + /** + * Discover all the relations available from the current layers. + * + * @param existingRelations the existing relations to filter them out + * @param layers the current layers + * @return the list of discovered relations + * @note added in QGIS 3.0 + */ + static QList discoverRelations( const QList& existingRelations, const QList& layers ); + signals: /** This signal is emitted when the relations were loaded after reading a project */ void relationsLoaded(); diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 38d1ddb31fd1..4e9d98fedfb8 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -718,3 +718,8 @@ QgsGeometry* QgsVectorDataProvider::convertToProviderType( const QgsGeometry& ge } QStringList QgsVectorDataProvider::smEncodings; + +QList QgsVectorDataProvider::discoverRelations( const QgsVectorLayer*, const QList& ) const +{ + return QList(); +} \ No newline at end of file diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index 7d092d5e6a7e..2addd3ac4c9e 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -28,6 +28,7 @@ class QTextCodec; #include "qgsfeature.h" #include "qgsaggregatecalculator.h" #include "qgsmaplayerdependency.h" +#include "qgsrelation.h" typedef QList QgsAttributeList; typedef QSet QgsAttributeIds; @@ -433,6 +434,15 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ virtual QSet dependencies() const; + /** + * Discover the available relations with the given layers. + * @param self the layer using this data provider. + * @param layers the other layers. + * @return the list of N-1 relations from this provider. + * @note added in QGIS 3.0 + */ + virtual QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const; + signals: /** Signals an error in this provider */ void raiseError( const QString& msg ); diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 4bfcb11403f0..08d862c58e11 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include @@ -3907,6 +3908,84 @@ QVariant QgsPostgresProvider::convertValue( QVariant::Type type, QVariant::Type } } +QList QgsPostgresProvider::searchLayers( const QList& layers, const QString& connectionInfo, const QString& schema, const QString& tableName ) +{ + QList result; + Q_FOREACH ( QgsVectorLayer* layer, layers ) + { + const QgsPostgresProvider* pgProvider = qobject_cast( layer->dataProvider() ); + if ( pgProvider && + pgProvider->mUri.connectionInfo( false ) == connectionInfo && pgProvider->mSchemaName == schema && pgProvider->mTableName == tableName ) + { + result.append( layer ); + } + } + return result; +} + +QList QgsPostgresProvider::discoverRelations( const QgsVectorLayer* self, const QList& layers ) const +{ + QList result; + QString sql( + "SELECT RC.CONSTRAINT_NAME, KCU1.COLUMN_NAME, KCU2.CONSTRAINT_SCHEMA, KCU2.TABLE_NAME, KCU2.COLUMN_NAME, KCU1.ORDINAL_POSITION " + "FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC " + "INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 " + "ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME " + "INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 " + "ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME " + "AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION " + "WHERE KCU1.CONSTRAINT_SCHEMA=" + QgsPostgresConn::quotedValue( mSchemaName ) + " AND KCU1.TABLE_NAME=" + QgsPostgresConn::quotedValue( mTableName ) + + "ORDER BY KCU1.ORDINAL_POSITION" + ); + QgsPostgresResult sqlResult( connectionRO()->PQexec( sql ) ); + if ( sqlResult.PQresultStatus() != PGRES_TUPLES_OK ) + { + QgsLogger::warning( "Error getting the foreign keys of " + mTableName ); + return result; + } + + int nbFound = 0; + for ( int row = 0; row < sqlResult.PQntuples(); ++row ) + { + const QString name = sqlResult.PQgetvalue( row, 0 ); + const QString fkColumn = sqlResult.PQgetvalue( row, 1 ); + const QString refSchema = sqlResult.PQgetvalue( row, 2 ); + const QString refTable = sqlResult.PQgetvalue( row, 3 ); + const QString refColumn = sqlResult.PQgetvalue( row, 4 ); + const QString position = sqlResult.PQgetvalue( row, 5 ); + if ( position == "1" ) + { // first reference field => try to find if we have layers for the referenced table + const QList foundLayers = searchLayers( layers, mUri.connectionInfo( false ), refSchema, refTable ); + Q_FOREACH ( const QgsVectorLayer* foundLayer, foundLayers ) + { + QgsRelation relation; + relation.setRelationName( name ); + relation.setReferencingLayer( self->id() ); + relation.setReferencedLayer( foundLayer->id() ); + relation.addFieldPair( fkColumn, refColumn ); + relation.generateId(); + if ( relation.isValid() ) + { + result.append( relation ); + ++nbFound; + } + else + { + QgsLogger::warning( "Invalid relation for " + name ); + } + } + } + else + { // multi reference field => add the field pair to all the referenced layers found + for ( int i = 0; i < nbFound; ++i ) + { + result[result.size() - 1 - i].addFieldPair( fkColumn, refColumn ); + } + } + } + return result; +} + /** * Class factory to return a pointer to a newly created * QgsPostgresProvider object diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index 2322033b1458..4f6ba8cb863d 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -258,6 +258,8 @@ class QgsPostgresProvider : public QgsVectorDataProvider */ static QVariant convertValue( QVariant::Type type, QVariant::Type subType, const QString& value ); + virtual QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const override; + signals: /** * This is emitted whenever the worker thread has fully calculated the @@ -340,6 +342,11 @@ class QgsPostgresProvider : public QgsVectorDataProvider */ QgsPostgresPrimaryKeyType pkType( const QgsField& fld ) const; + /** + * Search all the layers using the given table. + */ + static QList searchLayers( const QList& layers, const QString& connectionInfo, const QString& schema, const QString& tableName ); + QgsFields mAttributeFields; QString mDataComment; diff --git a/src/ui/qgsdiscoverrelationsdlgbase.ui b/src/ui/qgsdiscoverrelationsdlgbase.ui new file mode 100644 index 000000000000..285a15f5a8a7 --- /dev/null +++ b/src/ui/qgsdiscoverrelationsdlgbase.ui @@ -0,0 +1,117 @@ + + + QgsDiscoverRelationsDlgBase + + + + 0 + 0 + 700 + 267 + + + + Discover relations + + + + + + QAbstractItemView::NoEditTriggers + + + QAbstractItemView::MultiSelection + + + QAbstractItemView::SelectRows + + + true + + + true + + + false + + + true + + + + Name + + + + + Referencing Layer + + + + + Referencing Field + + + + + Referenced Layer + + + + + Referenced Field + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + mButtonBox + + + + + mButtonBox + accepted() + QgsDiscoverRelationsDlgBase + accept() + + + 248 + 254 + + + 157 + 274 + + + + + mButtonBox + rejected() + QgsDiscoverRelationsDlgBase + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/src/ui/qgsrelationmanagerdialogbase.ui b/src/ui/qgsrelationmanagerdialogbase.ui index f9f22c4add04..894f5af3c94d 100644 --- a/src/ui/qgsrelationmanagerdialogbase.ui +++ b/src/ui/qgsrelationmanagerdialogbase.ui @@ -83,6 +83,17 @@ + + + + Discover Relations + + + + :/images/themes/default/symbologyAdd.svg:/images/themes/default/symbologyAdd.svg + + + diff --git a/tests/src/python/test_qgsrelationeditwidget.py b/tests/src/python/test_qgsrelationeditwidget.py index 245b7345b794..b6e1c84f97f5 100644 --- a/tests/src/python/test_qgsrelationeditwidget.py +++ b/tests/src/python/test_qgsrelationeditwidget.py @@ -53,15 +53,15 @@ def setUpClass(cls): if 'QGIS_PGTEST_DB' in os.environ: cls.dbconn = os.environ['QGIS_PGTEST_DB'] # Create test layer - cls.vl_b = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."books" sql=', 'test', 'postgres') - cls.vl_a = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."authors" sql=', 'test', 'postgres') - cls.vl_link = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."books_authors" sql=', 'test', 'postgres') + cls.vl_b = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."books" sql=', 'books', 'postgres') + cls.vl_a = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."authors" sql=', 'authors', 'postgres') + cls.vl_link = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."books_authors" sql=', 'books_authors', 'postgres') QgsMapLayerRegistry.instance().addMapLayer(cls.vl_b) QgsMapLayerRegistry.instance().addMapLayer(cls.vl_a) QgsMapLayerRegistry.instance().addMapLayer(cls.vl_link) - relMgr = QgsProject.instance().relationManager() + cls.relMgr = QgsProject.instance().relationManager() cls.rel_a = QgsRelation() cls.rel_a.setReferencingLayer(cls.vl_link.id()) @@ -69,7 +69,7 @@ def setUpClass(cls): cls.rel_a.addFieldPair('fk_author', 'pk') cls.rel_a.setRelationId('rel_a') assert(cls.rel_a.isValid()) - relMgr.addRelation(cls.rel_a) + cls.relMgr.addRelation(cls.rel_a) cls.rel_b = QgsRelation() cls.rel_b.setReferencingLayer(cls.vl_link.id()) @@ -77,7 +77,7 @@ def setUpClass(cls): cls.rel_b.addFieldPair('fk_book', 'pk') cls.rel_b.setRelationId('rel_b') assert(cls.rel_b.isValid()) - relMgr.addRelation(cls.rel_b) + cls.relMgr.addRelation(cls.rel_b) # Our mock QgsVectorLayerTools, that allow injecting data where user input is expected cls.vltools = VlTools() @@ -125,7 +125,7 @@ def test_list(self): self.assertEqual(self.table_view.model().rowCount(), 4) - @unittest.expectedFailure(os.environ['QT_VERSION'] == '4' and os.environ['TRAVIS_OS_NAME'] == 'linux') # It's probably not related to this variables at all, but that's the closest we can get to the real source of this problem at the moment... + @unittest.expectedFailure(os.environ.get('QT_VERSION', '5') == '4' and os.environ.get('TRAVIS_OS_NAME', '') == 'linux') # It's probably not related to this variables at all, but that's the closest we can get to the real source of this problem at the moment... def test_add_feature(self): """ Check if a new related feature is added @@ -201,6 +201,31 @@ def test_unlink_feature(self): self.assertEqual(2, self.table_view.model().rowCount()) + def test_discover_relations(self): + """ + Test the automatic discovery of relations + """ + relations = self.relMgr.discoverRelations([], [self.vl_a, self.vl_b, self.vl_link]) + relations = {r.name(): r for r in relations} + self.assertEqual({'books_authors_fk_book_fkey', 'books_authors_fk_author_fkey'}, set(relations.keys())) + + ba2b = relations['books_authors_fk_book_fkey'] + self.assertTrue(ba2b.isValid()) + self.assertEqual('books_authors', ba2b.referencingLayer().name()) + self.assertEqual('books', ba2b.referencedLayer().name()) + self.assertEqual([0], ba2b.referencingFields()) + self.assertEqual([0], ba2b.referencedFields()) + + ba2a = relations['books_authors_fk_author_fkey'] + self.assertTrue(ba2a.isValid()) + self.assertEqual('books_authors', ba2a.referencingLayer().name()) + self.assertEqual('authors', ba2a.referencedLayer().name()) + self.assertEqual([1], ba2a.referencingFields()) + self.assertEqual([0], ba2a.referencedFields()) + + self.assertEqual([], self.relMgr.discoverRelations([self.rel_a, self.rel_b], [self.vl_a, self.vl_b, self.vl_link])) + self.assertEqual(1, len(self.relMgr.discoverRelations([], [self.vl_a, self.vl_link]))) + def startTransaction(self): """ Start a new transaction and set all layers into transaction mode. From 4feeab85a5efe5148af8308f91e1ba17a9b356a6 Mon Sep 17 00:00:00 2001 From: rldhont Date: Thu, 15 Sep 2016 11:15:11 +0200 Subject: [PATCH 004/897] [Processing][Rscripts] Use temp script filename The build RScript is stored in the User folder, so the script is erased at each RAlgorithm execute. Server side or for debugging this could be a problem. So processing_script.r will be stored in temp folder. --- python/plugins/processing/algs/r/RUtils.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/r/RUtils.py b/python/plugins/processing/algs/r/RUtils.py index 3fee8f5dffd5..d5c44cb7222c 100644 --- a/python/plugins/processing/algs/r/RUtils.py +++ b/python/plugins/processing/algs/r/RUtils.py @@ -45,6 +45,8 @@ class RUtils(object): R_USE64 = 'R_USE64' R_LIBS_USER = 'R_LIBS_USER' + rscriptfilename = userFolder() + os.sep + 'processing_script.r' + @staticmethod def RFolder(): folder = ProcessingConfig.getSetting(RUtils.R_FOLDER) @@ -108,7 +110,7 @@ def createRScriptFromRCommands(commands): @staticmethod def getRScriptFilename(): - return userFolder() + os.sep + 'processing_script.r' + return RUtils.rscriptfilename @staticmethod def getConsoleOutputFilename(): @@ -116,6 +118,9 @@ def getConsoleOutputFilename(): @staticmethod def executeRAlgorithm(alg, progress): + # generate new R script file name in a temp folder + RUtils.rscriptfilename = getTempFilenameInTempFolder('processing_script.r') + # run commands RUtils.verboseCommands = alg.getVerboseCommands() RUtils.createRScriptFromRCommands(alg.getFullSetOfRCommands()) if isWindows(): From ecba25430331bd64307d286752538ecf23701b25 Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Wed, 28 Sep 2016 10:32:04 +0200 Subject: [PATCH 005/897] Add relation discovery for SpatiaLite --- .../spatialite/qgsspatialiteprovider.cpp | 75 +++++++++++++++++++ .../spatialite/qgsspatialiteprovider.h | 7 ++ tests/src/python/test_provider_spatialite.py | 37 ++++++++- 3 files changed, 118 insertions(+), 1 deletion(-) diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index 48352dde0777..e63e68ad6cff 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -31,6 +31,7 @@ email : a.furieri@lqt.it #include "qgsspatialitefeatureiterator.h" #include +#include #include #include @@ -5264,6 +5265,80 @@ QgsAttributeList QgsSpatiaLiteProvider::pkAttributeIndexes() const return mPrimaryKeyAttrs; } +QList QgsSpatiaLiteProvider::searchLayers( const QList& layers, const QString& connectionInfo, const QString& tableName ) +{ + QList result; + Q_FOREACH ( QgsVectorLayer* layer, layers ) + { + const QgsSpatiaLiteProvider* slProvider = qobject_cast( layer->dataProvider() ); + if ( slProvider && slProvider->mSqlitePath == connectionInfo && slProvider->mTableName == tableName ) + { + result.append( layer ); + } + } + return result; +} + + +QList QgsSpatiaLiteProvider::discoverRelations( const QgsVectorLayer* self, const QList& layers ) const +{ + QList output; + const QString sql = QString( "PRAGMA foreign_key_list(%1)" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mTableName ) ); + char **results; + int rows; + int columns; + char *errMsg = nullptr; + int ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); + if ( ret == SQLITE_OK ) + { + int nbFound = 0; + for ( int row = 1; row <= rows; ++row ) + { + const QString name = "fk_" + mTableName + "_" + QString::fromUtf8( results[row * columns + 0] ); + const QString position = QString::fromUtf8( results[row * columns + 1] ); + const QString refTable = QString::fromUtf8( results[row * columns + 2] ); + const QString fkColumn = QString::fromUtf8( results[row * columns + 3] ); + const QString refColumn = QString::fromUtf8( results[row * columns + 4] ); + if ( position == "0" ) + { // first reference field => try to find if we have layers for the referenced table + const QList foundLayers = searchLayers( layers, mSqlitePath, refTable ); + Q_FOREACH ( const QgsVectorLayer* foundLayer, foundLayers ) + { + QgsRelation relation; + relation.setRelationName( name ); + relation.setReferencingLayer( self->id() ); + relation.setReferencedLayer( foundLayer->id() ); + relation.addFieldPair( fkColumn, refColumn ); + relation.generateId(); + if ( relation.isValid() ) + { + output.append( relation ); + ++nbFound; + } + else + { + QgsLogger::warning( "Invalid relation for " + name ); + } + } + } + else + { // multi reference field => add the field pair to all the referenced layers found + for ( int i = 0; i < nbFound; ++i ) + { + output[output.size() - 1 - i].addFieldPair( fkColumn, refColumn ); + } + } + } + sqlite3_free_table( results ); + } + else + { + QgsLogger::warning( QString( "SQLite error discovering relations: %1" ).arg( errMsg ) ); + sqlite3_free( errMsg ); + } + return output; +} + // --------------------------------------------------------------------------- QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QString& sldStyle, diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 7d1134d446f0..cc214094922d 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -209,6 +209,8 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider void invalidateConnections( const QString& connection ) override; + QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const override; + // static functions static void convertToGeosWKB( const unsigned char *blob, int blob_size, unsigned char **wkb, int *geom_size ); @@ -291,6 +293,11 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider //! get SpatiaLite version string QString spatialiteVersion(); + /** + * Search all the layers using the given table. + */ + static QList searchLayers( const QList& layers, const QString& connectionInfo, const QString& tableName ); + QgsFields mAttributeFields; //! Flag indicating if the layer data source is a valid SpatiaLite layer diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index 781677509913..6cf54085f350 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -19,7 +19,7 @@ import shutil import tempfile -from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry +from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -123,6 +123,18 @@ def setUpClass(cls): sql += "VALUES (1, '[\"toto\",\"tutu\"]', '[1,-2,724562]', '[1.0, -232567.22]', GeomFromText('POLYGON((0 0,1 0,1 1,0 1,0 0))', 4326))" cur.execute(sql) + # 2 tables with relations + sql = "PRAGMA foreign_keys = ON;" + cur.execute(sql) + sql = "CREATE TABLE test_relation_a(artistid INTEGER PRIMARY KEY, artistname TEXT);" + cur.execute(sql) + sql = "SELECT AddGeometryColumn('test_relation_a', 'Geometry', 4326, 'POLYGON', 'XY')" + cur.execute(sql) + sql = "CREATE TABLE test_relation_b(trackid INTEGER, trackname TEXT, trackartist INTEGER, FOREIGN KEY(trackartist) REFERENCES test_relation_a(artistid));" + cur.execute(sql) + sql = "SELECT AddGeometryColumn('test_relation_b', 'Geometry', 4326, 'POLYGON', 'XY')" + cur.execute(sql) + cur.execute("COMMIT") con.close() @@ -347,6 +359,29 @@ def test_arrays(self): self.assertEqual(read_back['ints'], new_f['ints']) self.assertEqual(read_back['reals'], new_f['reals']) + def test_discover_relation(self): + artist = QgsVectorLayer("dbname=%s table=test_relation_a (geometry)" % self.dbname, "test_relation_a", "spatialite") + self.assertTrue(artist.isValid()) + track = QgsVectorLayer("dbname=%s table=test_relation_b (geometry)" % self.dbname, "test_relation_b", "spatialite") + self.assertTrue(track.isValid()) + QgsMapLayerRegistry.instance().addMapLayer(artist) + QgsMapLayerRegistry.instance().addMapLayer(track) + try: + relMgr = QgsProject.instance().relationManager() + relations = relMgr.discoverRelations([], [artist, track]) + relations = {r.name(): r for r in relations} + self.assertEqual({'fk_test_relation_b_0'}, set(relations.keys())) + + a2t = relations['fk_test_relation_b_0'] + self.assertTrue(a2t.isValid()) + self.assertEqual('test_relation_b', a2t.referencingLayer().name()) + self.assertEqual('test_relation_a', a2t.referencedLayer().name()) + self.assertEqual([2], a2t.referencingFields()) + self.assertEqual([0], a2t.referencedFields()) + finally: + QgsMapLayerRegistry.instance().removeMapLayer(track.id()) + QgsMapLayerRegistry.instance().removeMapLayer(artist.id()) + # This test would fail. It would require turning on WAL def XXXXXtestLocking(self): From 613cc1b6aadddc9a1212b190abd1d82f436c9d46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Wed, 28 Sep 2016 16:41:12 +0200 Subject: [PATCH 006/897] [processing] [FEATURE] SplitWithLines Rename algorithm SplitLinesWithLines to SplitWithLines Accept polygon as input, too Use only selected lines to split with (if processing is set to use selection only) Issue log message if trying to split multi geometries Update help --- python/plugins/processing/algs/help/qgis.yaml | 4 +- .../algs/qgis/QGISAlgorithmProvider.py | 4 +- .../algs/qgis/SplitLinesWithLines.py | 141 -------------- .../processing/algs/qgis/SplitWithLines.py | 173 ++++++++++++++++++ 4 files changed, 177 insertions(+), 145 deletions(-) delete mode 100644 python/plugins/processing/algs/qgis/SplitLinesWithLines.py create mode 100644 python/plugins/processing/algs/qgis/SplitWithLines.py diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index 4236004391aa..c1428d5037b1 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -457,8 +457,8 @@ qgis:snappointstogrid: > This algorithm modifies the position of points in a vector layer, so they fall in the coordinates of a grid. -qgis:splitlineswithlines: > - This algorithm split the lines in a line layer using the lines in another line layer to define the breaking points. Intersection between geometries in both layers are considered as split points. +qgis:splitwithlines: > + This algorithm splits the lines or polygons in one layer using the lines in another layer to define the breaking points. Intersection between geometries in both layers are considered as split points. qgis:splitvectorlayer: > This algorithm takes a vector layer and an attribute and generates a set of vector layers in an outut folder. Each of the layers created in that folder contains all features from the input layer with the same value for the specified attribute. diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index a4e1d3994037..b481ca795d34 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -138,7 +138,7 @@ from .SelectByExpression import SelectByExpression from .SelectByAttributeSum import SelectByAttributeSum from .HypsometricCurves import HypsometricCurves -from .SplitLinesWithLines import SplitLinesWithLines +from .SplitWithLines import SplitWithLines from .FieldsMapper import FieldsMapper from .Datasources2Vrt import Datasources2Vrt from .CheckValidity import CheckValidity @@ -205,7 +205,7 @@ def __init__(self): PostGISExecuteSQL(), ImportIntoPostGIS(), SetVectorStyle(), SetRasterStyle(), SelectByExpression(), HypsometricCurves(), - SplitLinesWithLines(), CreateConstantRaster(), + SplitWithLines(), CreateConstantRaster(), FieldsMapper(), SelectByAttributeSum(), Datasources2Vrt(), CheckValidity(), OrientedMinimumBoundingBox(), Smooth(), ReverseLineDirection(), SpatialIndex(), DefineProjection(), diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py deleted file mode 100644 index b2f266461499..000000000000 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - SplitLines.py - --------------------- - Date : November 2014 - Revised : February 2016 - Copyright : (C) 2014 by Bernhard Ströbl - Email : bernhard dot stroebl at jena dot de -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Bernhard Ströbl' -__date__ = 'November 2014' -__copyright__ = '(C) 2014, Bernhard Ströbl' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterVector -from processing.core.outputs import OutputVector -from processing.core.ProcessingLog import ProcessingLog -from processing.tools import dataobjects -from processing.tools import vector - - -class SplitLinesWithLines(GeoAlgorithm): - - INPUT_A = 'INPUT_A' - INPUT_B = 'INPUT_B' - - OUTPUT = 'OUTPUT' - - def defineCharacteristics(self): - self.name, self.i18n_name = self.trAlgorithm('Split lines with lines') - self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') - self.addParameter(ParameterVector(self.INPUT_A, - self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE])) - self.addParameter(ParameterVector(self.INPUT_B, - self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) - - self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'), datatype=[dataobjects.TYPE_VECTOR_LINE])) - - def processAlgorithm(self, progress): - layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) - layerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B)) - - sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B) - fieldList = layerA.fields() - - writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, - QgsWkbTypes.LineString, layerA.crs()) - - spatialIndex = vector.spatialindex(layerB) - - outFeat = QgsFeature() - features = vector.features(layerA) - total = 100.0 / float(len(features)) - - for current, inFeatA in enumerate(features): - inGeom = inFeatA.geometry() - attrsA = inFeatA.attributes() - outFeat.setAttributes(attrsA) - inLines = [inGeom] - lines = spatialIndex.intersects(inGeom.boundingBox()) - - if len(lines) > 0: # hasIntersections - splittingLines = [] - - for i in lines: - request = QgsFeatureRequest().setFilterFid(i) - inFeatB = next(layerB.getFeatures(request)) - # check if trying to self-intersect - if sameLayer: - if inFeatA.id() == inFeatB.id(): - continue - - splitGeom = inFeatB.geometry() - - if inGeom.intersects(splitGeom): - splittingLines.append(splitGeom) - - if len(splittingLines) > 0: - for splitGeom in splittingLines: - splitterPList = vector.extractPoints(splitGeom) - outLines = [] - - while len(inLines) > 0: - inGeom = inLines.pop() - inPoints = vector.extractPoints(inGeom) - - if inGeom.intersects(splitGeom): - try: - result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) - except: - ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, - self.tr('Geometry exception while splitting')) - result = 1 - - # splitGeometry: If there are several intersections - # between geometry and splitLine, only the first one is considered. - if result == 0: # split occurred - - if inPoints == vector.extractPoints(inGeom): - # bug in splitGeometry: sometimes it returns 0 but - # the geometry is unchanged - outLines.append(inGeom) - else: - inLines.append(inGeom) - - for aNewGeom in newGeometries: - inLines.append(aNewGeom) - else: - outLines.append(inGeom) - else: - outLines.append(inGeom) - - inLines = outLines - - for aLine in inLines: - if len(aLine.asPolyline()) > 2 or \ - (len(aLine.asPolyline()) == 2 and - aLine.asPolyline()[0] != aLine.asPolyline()[1]): - # sometimes splitting results in lines of zero length - outFeat.setGeometry(aLine) - writer.addFeature(outFeat) - - progress.setPercentage(int(current * total)) - - del writer diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py new file mode 100644 index 000000000000..eb0f741b505b --- /dev/null +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + SplitWithLines.py + --------------------- + Date : November 2014 + Revised : September 2016 + Copyright : (C) 2014 by Bernhard Ströbl + Email : bernhard dot stroebl at jena dot de +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Bernhard Ströbl' +__date__ = 'November 2014' +__copyright__ = '(C) 2014, Bernhard Ströbl' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.outputs import OutputVector +from processing.core.ProcessingLog import ProcessingLog +from processing.tools import dataobjects +from processing.tools import vector + + +class SplitWithLines(GeoAlgorithm): + + INPUT_A = 'INPUT_A' + INPUT_B = 'INPUT_B' + + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Split with lines') + self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') + self.addParameter(ParameterVector(self.INPUT_A, + self.tr('Input layer, single geometries only'), [dataobjects.TYPE_VECTOR_POLYGON, + dataobjects.TYPE_VECTOR_LINE])) + self.addParameter(ParameterVector(self.INPUT_B, + self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) + + self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'))) + + def processAlgorithm(self, progress): + layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) + splitLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B)) + + sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B) + fieldList = layerA.fields() + + writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, + layerA.wkbType(), layerA.crs()) + + spatialIndex = vector.spatialindex(splitLayer) + splitGeoms = {} + + for aSplitFeature in vector.features(splitLayer): + splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry() + # honor the case that user has selection on split layer and has setting "use selection" + + outFeat = QgsFeature() + features = vector.features(layerA) + total = 100.0 / float(len(features)) + allowedWkbTypes = [2, #WkbLineString + 3, # WkbPolygon + -2147483646, #WkbLineString25D + -2147483645] # WkbPolygon25D + # MultiGeometries are not allowed because the result of a splitted ring is not clearly defined: + # 1) add both parts as new features + # 2) store one part as a new feature and the other one as ring of the multi geometry + # 2a) which part is which, seems arbitrary + + multiGeoms = 0 # how many multi geometries were encountered + + for current, inFeatA in enumerate(features): + inGeom = inFeatA.geometry() + + if allowedWkbTypes.count(inGeom.wkbType()) == 0: + multiGeoms += 1 + else: + attrsA = inFeatA.attributes() + outFeat.setAttributes(attrsA) + inGeoms = [inGeom] + lines = spatialIndex.intersects(inGeom.boundingBox()) + + if len(lines) > 0: # has intersection of bounding boxes + splittingLines = [] + + for i in lines: + try: + splitGeom = splitGeoms[i] + except: + continue + + # check if trying to self-intersect + if sameLayer: + if inFeatA.id() == i: + continue + + if inGeom.intersects(splitGeom): + splittingLines.append(splitGeom) + + if len(splittingLines) > 0: + for splitGeom in splittingLines: + splitterPList = vector.extractPoints(splitGeom) + outGeoms = [] + + while len(inGeoms) > 0: + inGeom = inGeoms.pop() + inPoints = vector.extractPoints(inGeom) + + if inGeom.intersects(splitGeom): + try: + result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) + except: + ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, + self.tr('Geometry exception while splitting')) + result = 1 + + # splitGeometry: If there are several intersections + # between geometry and splitLine, only the first one is considered. + if result == 0: # split occurred + + if inPoints == vector.extractPoints(inGeom): + # bug in splitGeometry: sometimes it returns 0 but + # the geometry is unchanged + outGeoms.append(inGeom) + else: + inGeoms.append(inGeom) + + for aNewGeom in newGeometries: + inGeoms.append(aNewGeom) + else: + outGeoms.append(inGeom) + else: + outGeoms.append(inGeom) + + inGeoms = outGeoms + + for aGeom in inGeoms: + passed = True + + if aGeom.wkbType == 2 or aGeom.wkbType == -2147483646: + passed = len(aGeom.asPolyline()) > 2 + + if not passed: + passed = (len(aGeom.asPolyline()) == 2 and + aGeom.asPolyline()[0] != aGeom.asPolyline()[1]) + # sometimes splitting results in lines of zero length + + if passed: + outFeat.setGeometry(aGeom) + writer.addFeature(outFeat) + + progress.setPercentage(int(current * total)) + + if multiGeoms > 0: + ProcessingLog.addToLog(ProcessingLog.LOG_INFO, + self.tr('Feature geometry error: %s input features ignored due to multi-geometry.') % str(multiGeoms)) + + del writer From 977acf4b9e8e4db7ad465a908ee03683d85610d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 10:17:43 +0200 Subject: [PATCH 007/897] [processing] update test for splitwithlines --- .../expected/polys_split_with_lines.gfs | 32 ++++++++++ .../expected/polys_split_with_lines.gml | 59 +++++++++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 26 ++++++-- 3 files changed, 113 insertions(+), 4 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs new file mode 100644 index 000000000000..3c0084954b0f --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs @@ -0,0 +1,32 @@ + + + polygons_split_with_lines + polygons_split_with_lines + + 3 + EPSG:4326 + + 6 + -1.00000 + 10.00000 + -3.00000 + 6.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml new file mode 100644 index 000000000000..88e8941cf772 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml @@ -0,0 +1,59 @@ + + + + + -1-3 + 106 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.12346 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0.00000 + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.12300 + + + + + 6,-3 7,-2 9,-2 9,0 10,1 10,-3 6,-3 + ASDF + 0 + + + + + 7,-2 6,-3 6,1 10,1 9,0 7,0 7,-2 + ASDF + 0 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 2 + 3.33000 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 4af0ce4ce768..36fdf516375b 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -191,9 +191,9 @@ tests: name: expected/basic_statistics_string.html type: file - # Split lines with lines considers two cases - # case 1: two different layers - - algorithm: qgis:splitlineswithlines + # Split with lines considers three cases + # case 1: two different line layers + - algorithm: qgis:splitwithlines name: Split lines with lines params: INPUT_A: @@ -211,7 +211,7 @@ tests: precision: 7 # case 2 split line layer with iself - - algorithm: qgis:splitlineswithlines + - algorithm: qgis:splitwithlines name: Split lines with same lines params: INPUT_A: @@ -227,6 +227,24 @@ tests: compare: geometry: precision: 7 + + # case 3 split polygon layer with lines + - algorithm: qgis:splitwithlines + name: Split lines with same lines + params: + INPUT_A: + name: polys.gml + type: vector + INPUT_B: + name: lines.gml + type: vector + results: + OUTPUT: + name: expected/polys_split_with_lines.gml + type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:addautoincrementalfield name: Add autoincremental field From 5c975b5f8e67600d462a178e3f3b5b0d89e17dae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 11:17:02 +0200 Subject: [PATCH 008/897] [BUG] Prevent division by zero --- python/plugins/processing/algs/qgis/SplitWithLines.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index eb0f741b505b..c3ed7328e493 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -72,7 +72,12 @@ def processAlgorithm(self, progress): outFeat = QgsFeature() features = vector.features(layerA) - total = 100.0 / float(len(features)) + + if len(features) == 0: + total = 100 + else: + total = 100.0 / float(len(features)) + allowedWkbTypes = [2, #WkbLineString 3, # WkbPolygon -2147483646, #WkbLineString25D From 4bf5190761c93973a336e072c51c93f86a5fe805 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 11:41:44 +0200 Subject: [PATCH 009/897] Speed up algorithm --- python/plugins/processing/algs/qgis/SplitWithLines.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index c3ed7328e493..7fc7cb33411a 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -65,8 +65,10 @@ def processAlgorithm(self, progress): spatialIndex = vector.spatialindex(splitLayer) splitGeoms = {} + request = QgsFeatureRequest() + request.setSubsetOfAttributes([]) - for aSplitFeature in vector.features(splitLayer): + for aSplitFeature in vector.features(splitLayer, request): splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry() # honor the case that user has selection on split layer and has setting "use selection" From 49ae0206f4e3373edd76568b4f9fe5d8f8bdae64 Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Thu, 29 Sep 2016 11:47:32 +0200 Subject: [PATCH 010/897] [Server 3.0] Tests reliability + new auth test - Local server searches for a free port before binding - Server tests now ignore attributes order - Updated reference docs - Renamed projects ("+" -> "_") - Added a smoke test for auth manager and WMS/WFS providers --- tests/src/python/CMakeLists.txt | 1 + tests/src/python/qgis_wrapped_server.py | 46 ++- tests/src/python/test_authmanager_endpoint.py | 180 ++++++++++ tests/src/python/test_offline_editing_wfs.py | 7 +- tests/src/python/test_qgsserver.py | 57 ++- tests/src/python/test_qgsserver_wfst.py | 7 +- .../testdata/qgis_server/getcapabilities.txt | 16 +- .../qgis_server/getcapabilities_inspire.txt | 16 +- .../qgis_server/getprojectsettings.txt | 21 +- .../{test+project.qgs => test_project.qgs} | 336 ++++++++++-------- ...t_inspire.qgs => test_project_inspire.qgs} | 0 ...t+project_wfs.qgs => test_project_wfs.qgs} | 0 12 files changed, 488 insertions(+), 199 deletions(-) create mode 100644 tests/src/python/test_authmanager_endpoint.py rename tests/testdata/qgis_server/{test+project.qgs => test_project.qgs} (68%) rename tests/testdata/qgis_server/{test+project_inspire.qgs => test_project_inspire.qgs} (100%) rename tests/testdata/qgis_server/{test+project_wfs.qgs => test_project_wfs.qgs} (100%) diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 646ac90c48d5..d268f8c072e5 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -150,4 +150,5 @@ IF (WITH_SERVER) ADD_PYTHON_TEST(PyQgsServerAccessControl test_qgsserver_accesscontrol.py) ADD_PYTHON_TEST(PyQgsServerWFST test_qgsserver_wfst.py) ADD_PYTHON_TEST(PyQgsOfflineEditingWFS test_offline_editing_wfs.py) + ADD_PYTHON_TEST(PyQgsAuthManagerEnpointTest test_authmanager_endpoint.py) ENDIF (WITH_SERVER) diff --git a/tests/src/python/qgis_wrapped_server.py b/tests/src/python/qgis_wrapped_server.py index 04328c008604..4d033d0f1a64 100644 --- a/tests/src/python/qgis_wrapped_server.py +++ b/tests/src/python/qgis_wrapped_server.py @@ -5,6 +5,13 @@ This script launches a QGIS Server listening on port 8081 or on the port specified on the environment variable QGIS_SERVER_DEFAULT_PORT +For testing purposes, HTTP Basic can be enabled by setting the following +environment variables: + + * QGIS_SERVER_HTTP_BASIC_AUTH (default not set, set to anything to enable) + * QGIS_SERVER_USERNAME (default ="username") + * QGIS_SERVER_PASSWORD (default ="password") + .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -22,6 +29,8 @@ import os +import sys +import signal import urllib.parse from http.server import BaseHTTPRequestHandler, HTTPServer from qgis.core import QgsApplication @@ -36,11 +45,35 @@ qgs_server = QgsServer() +if os.environ.get('QGIS_SERVER_HTTP_BASIC_AUTH') is not None: + from qgis.server import QgsServerFilter + import base64 + + class HTTPBasicFilter(QgsServerFilter): + + def responseComplete(self): + request = self.serverInterface().requestHandler() + if self.serverInterface().getEnv('HTTP_AUTHORIZATION'): + username, password = base64.b64decode(self.serverInterface().getEnv('HTTP_AUTHORIZATION')[6:]).split(b':') + if (username.decode('utf-8') == os.environ.get('QGIS_SERVER_USERNAME', 'username') + and password.decode('utf-8') == os.environ.get('QGIS_SERVER_PASSWORD', 'password')): + return + # No auth ... + request.clearHeaders() + request.setHeader('Status', '401 Authorization required') + request.setHeader('WWW-Authenticate', 'Basic realm="QGIS Server"') + request.clearBody() + request.appendBody(b'

Authorization required

') + + filter = HTTPBasicFilter(qgs_server.serverInterface()) + qgs_server.serverInterface().registerFilter(filter) + + class Handler(BaseHTTPRequestHandler): def do_GET(self): # CGI vars: - for k, v in list(self.headers.items()): + for k, v in self.headers.items(): qgs_server.putenv('HTTP_%s' % k.replace(' ', '-').replace('-', '_').replace(' ', '-').upper(), v) qgs_server.putenv('SERVER_PORT', str(self.server.server_port)) qgs_server.putenv('SERVER_NAME', self.server.server_name) @@ -52,7 +85,7 @@ def do_GET(self): self.send_response(int(headers_dict['Status'].split(' ')[0])) except: self.send_response(200) - for k, v in list(headers_dict.items()): + for k, v in headers_dict.items(): self.send_header(k, v) self.end_headers() self.wfile.write(body) @@ -71,5 +104,12 @@ def do_POST(self): server = HTTPServer(('localhost', QGIS_SERVER_DEFAULT_PORT), Handler) print('Starting server on localhost:%s, use to stop' % QGIS_SERVER_DEFAULT_PORT) + + def signal_handler(signal, frame): + global qgs_app + print("\nExiting QGIS...") + qgs_app.exitQgis() + sys.exit(0) + + signal.signal(signal.SIGINT, signal_handler) server.serve_forever() - qgs_app.exitQgis() diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_endpoint.py new file mode 100644 index 000000000000..50d712b67734 --- /dev/null +++ b/tests/src/python/test_authmanager_endpoint.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +""" +Tests for auth manager WMS/WFS using QGIS Server through HTTP Basic +enabled qgis_wrapped_server.py. + +This is an integration test for QGIS Desktop Auth Manager WFS and WMS provider +and QGIS Server WFS/WMS that check if QGIS can use a stored auth manager auth +configuration to access an HTTP Basic protected endpoint. + + +From build dir, run: ctest -R PyQgsAuthManagerEnpointTest -V + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +import os +import sys +import subprocess +import tempfile +import random +import string +import urllib + +__author__ = 'Alessandro Pasotti' +__date__ = '18/09/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +from time import sleep +from urllib.parse import quote +from shutil import rmtree + +from utilities import unitTestDataPath +from qgis.core import ( + QgsAuthManager, + QgsAuthMethodConfig, + QgsVectorLayer, + QgsRasterLayer, +) +from qgis.testing import ( + start_app, + unittest, +) + +try: + QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT = os.environ['QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT'] +except: + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("", 0)) + QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT = s.getsockname()[1] + s.close() + +QGIS_AUTH_DB_DIR_PATH = tempfile.mkdtemp() + +os.environ['QGIS_AUTH_DB_DIR_PATH'] = QGIS_AUTH_DB_DIR_PATH + +qgis_app = start_app() + + +class TestAuthManager(unittest.TestCase): + + @classmethod + def setUpClass(cls): + """Run before all tests: + Creates an auth configuration""" + cls.port = QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT + # Clean env just to be sure + env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] + for ev in env_vars: + try: + del os.environ[ev] + except KeyError: + pass + cls.testdata_path = unitTestDataPath('qgis_server') + '/' + cls.project_path = quote(cls.testdata_path + "test_project.qgs") + # Enable auth + #os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE + authm = QgsAuthManager.instance() + assert (authm.setMasterPassword('masterpassword', True)) + cls.auth_config = QgsAuthMethodConfig('Basic') + cls.auth_config.setName('test_auth_config') + cls.username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6)) + cls.password = cls.username[::-1] # reversed + cls.auth_config.setConfig('username', cls.username) + cls.auth_config.setConfig('password', cls.password) + assert (authm.storeAuthenticationConfig(cls.auth_config)[0]) + + os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1' + os.environ['QGIS_SERVER_USERNAME'] = cls.username + os.environ['QGIS_SERVER_PASSWORD'] = cls.password + os.environ['QGIS_SERVER_DEFAULT_PORT'] = str(cls.port) + server_path = os.path.dirname(os.path.realpath(__file__)) + \ + '/qgis_wrapped_server.py' + cls.server = subprocess.Popen([sys.executable, server_path], + env=os.environ) + sleep(2) + + @classmethod + def tearDownClass(cls): + """Run after all tests""" + cls.server.terminate() + rmtree(QGIS_AUTH_DB_DIR_PATH) + del cls.server + + def setUp(self): + """Run before each test.""" + pass + + def tearDown(self): + """Run after each test.""" + pass + + @classmethod + def _getWFSLayer(cls, type_name, layer_name=None, authcfg=None): + """ + WFS layer factory + """ + if layer_name is None: + layer_name = 'wfs_' + type_name + parms = { + 'srsname': 'EPSG:4326', + 'typename': type_name, + 'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path), + 'version': 'auto', + 'table': '', + } + if authcfg is not None: + parms.update({'authcfg': authcfg}) + uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())]) + wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS') + return wfs_layer + + @classmethod + def _getWMSLayer(cls, layers, layer_name=None, authcfg=None): + """ + WMS layer factory + """ + if layer_name is None: + layer_name = 'wms_' + layers.replace(',', '') + parms = { + 'crs': 'EPSG:4326', + 'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path), + 'format': 'image/png', + # This is needed because of a really wierd implementation in QGIS Server, that + # replaces _ in the the real layer name with spaces + 'layers': urllib.parse.quote(layers).replace('_', ' '), + 'styles': '', + #'sql': '', + } + if authcfg is not None: + parms.update({'authcfg': authcfg}) + uri = '&'.join([("%s=%s" % (k, v.replace('=', '%3D'))) for k, v in list(parms.items())]) + wms_layer = QgsRasterLayer(uri, layer_name, 'wms') + return wms_layer + + def testValidAuthAccess(self): + """ + Access the HTTP Basic protected layer with valid credentials + """ + wfs_layer = self._getWFSLayer('testlayer_èé', authcfg=self.auth_config.id()) + self.assertTrue(wfs_layer.isValid()) + wms_layer = self._getWMSLayer('testlayer_èé', authcfg=self.auth_config.id()) + self.assertTrue(wms_layer.isValid()) + + def testInvalidAuthAccess(self): + """ + Access the HTTP Basic protected layer with no credentials + """ + wfs_layer = self._getWFSLayer('testlayer_èé') + self.assertFalse(wfs_layer.isValid()) + wms_layer = self._getWMSLayer('testlayer_èé') + self.assertFalse(wms_layer.isValid()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/src/python/test_offline_editing_wfs.py b/tests/src/python/test_offline_editing_wfs.py index 62c2072bb0f5..3477581a77d7 100644 --- a/tests/src/python/test_offline_editing_wfs.py +++ b/tests/src/python/test_offline_editing_wfs.py @@ -45,10 +45,15 @@ from offlineditingtestbase import OfflineTestBase + try: QGIS_SERVER_WFST_DEFAULT_PORT = os.environ['QGIS_SERVER_WFST_DEFAULT_PORT'] except: - QGIS_SERVER_WFST_DEFAULT_PORT = 8081 + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("", 0)) + QGIS_SERVER_WFST_DEFAULT_PORT = s.getsockname()[1] + s.close() qgis_app = start_app() diff --git a/tests/src/python/test_qgsserver.py b/tests/src/python/test_qgsserver.py index bff4426d9126..460859d2ee8c 100644 --- a/tests/src/python/test_qgsserver.py +++ b/tests/src/python/test_qgsserver.py @@ -30,11 +30,37 @@ # Also strip all multi-attribute tags (Qt5 attr order is random) # FIXME: this is a temporary workaround to make the test pass, a more # robust implementation must check for attributes too -RE_STRIP_UNCHECKABLE = b']*>|]*>|]*>|]*>|MAP=[^"]+|Content-Length: \d+|]*>|]*>|]*>|]*>|]*>|]*>|]*>|]*>' +#RE_STRIP_UNCHECKABLE = b']*>|]*>|]*>|]*>|MAP=[^"]+|Content-Length: \d+|]*>|]*>|]*>|]*>|]*>|]*>|]*>|]*>' +RE_STRIP_UNCHECKABLE = b'MAP=[^"]+|Content-Length: \d+' +RE_ATTRIBUTES = b'[^>\s]+=[^>\s]+' class TestQgsServer(unittest.TestCase): + def assertXMLEqual(self, response, expected, msg=''): + """Compare XML line by line and sorted attributes""" + response_lines = response.splitlines() + expected_lines = expected.splitlines() + line_no = 1 + for expected_line in expected_lines: + expected_line = expected_line.strip() + response_line = response_lines[line_no - 1].strip() + # Compare tag + try: + self.assertEqual(re.findall(b'<([^>\s]+)[ >]', expected_line)[0], + re.findall(b'<([^>\s]+)[ >]', response_line)[0], msg=msg + "\nTag mismatch on line %s: %s != %s" % (line_no, expected_line, response_line)) + except IndexError: + self.assertEqual(expected_line, response_line, msg=msg + "\nTag line mismatch %s: %s != %s" % (line_no, expected_line, response_line)) + #print("---->%s\t%s == %s" % (line_no, expected_line, response_line)) + # Compare attributes + if re.match(RE_ATTRIBUTES, expected_line): # has attrs + expected_attrs = re.findall(RE_ATTRIBUTES, expected_line) + expected_attrs.sort() + response_attrs = re.findall(RE_ATTRIBUTES, response_line) + response_attrs.sort() + self.assertEqual(expected_attrs, response_attrs, msg=msg + "\nXML attributes differ at line {0}: {1} != {2}".format(line_no, expected_attrs, response_attrs)) + line_no += 1 + @classmethod def setUpClass(cls): cls.app = QgsApplication([], False) @@ -170,7 +196,7 @@ def responseComplete(self): # WMS tests def wms_request_compare(self, request, extra=None, reference_file=None): - project = self.testdata_path + "test+project.qgs" + project = self.testdata_path + "test_project.qgs" assert os.path.exists(project), "Project file not found: " + project query_string = 'MAP=%s&SERVICE=WMS&VERSION=1.3&REQUEST=%s' % (urllib.parse.quote(project), request) @@ -202,7 +228,7 @@ def wms_request_compare(self, request, extra=None, reference_file=None): if int(osgeo.gdal.VersionInfo()[:1]) < 2: expected = expected.replace(b'typeName="Integer64" precision="0" length="10" editType="TextEdit" type="qlonglong"', b'typeName="Integer" precision="0" length="10" editType="TextEdit" type="int"') - self.assertEqual(response, expected, msg="request %s failed.\n Query: %s\n Expected:\n%s\n\n Response:\n%s" % (query_string, request, expected.decode('utf-8'), response.decode('utf-8'))) + self.assertXMLEqual(response, expected, msg="request %s failed.\n Query: %s\n Expected:\n%s\n\n Response:\n%s" % (query_string, request, expected.decode('utf-8'), response.decode('utf-8'))) def test_project_wms(self): """Test some WMS request""" @@ -239,7 +265,7 @@ def test_project_wms(self): def wms_inspire_request_compare(self, request): """WMS INSPIRE tests""" - project = self.testdata_path + "test+project_inspire.qgs" + project = self.testdata_path + "test_project_inspire.qgs" assert os.path.exists(project), "Project file not found: " + project query_string = 'MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (urllib.parse.quote(project), request) @@ -259,7 +285,7 @@ def wms_inspire_request_compare(self, request): """ response = re.sub(RE_STRIP_UNCHECKABLE, b'', response) expected = re.sub(RE_STRIP_UNCHECKABLE, b'', expected) - self.assertEqual(response, expected, msg="request %s failed.\n Query: %s\n Expected:\n%s\n\n Response:\n%s" % (query_string, request, expected.decode('utf-8'), response.decode('utf-8'))) + self.assertXMLEqual(response, expected, msg="request %s failed.\n Query: %s\n Expected:\n%s\n\n Response:\n%s" % (query_string, request, expected.decode('utf-8'), response.decode('utf-8'))) def test_project_wms_inspire(self): """Test some WMS request""" @@ -268,7 +294,7 @@ def test_project_wms_inspire(self): # WFS tests def wfs_request_compare(self, request): - project = self.testdata_path + "test+project_wfs.qgs" + project = self.testdata_path + "test_project_wfs.qgs" assert os.path.exists(project), "Project file not found: " + project query_string = 'MAP=%s&SERVICE=WFS&VERSION=1.0.0&REQUEST=%s' % (urllib.parse.quote(project), request) @@ -294,7 +320,7 @@ def wfs_request_compare(self, request): if int(osgeo.gdal.VersionInfo()[:1]) < 2: expected = expected.replace(b'', b'') - self.assertEqual(response, expected, msg="request %s failed.\n Query: %s\n Expected:\n%s\n\n Response:\n%s" % (query_string, request, expected.decode('utf-8'), response.decode('utf-8'))) + self.assertXMLEqual(response, expected, msg="request %s failed.\n Query: %s\n Expected:\n%s\n\n Response:\n%s" % (query_string, request, expected.decode('utf-8'), response.decode('utf-8'))) def test_project_wfs(self): """Test some WFS request""" @@ -302,7 +328,7 @@ def test_project_wfs(self): self.wfs_request_compare(request) def wfs_getfeature_compare(self, requestid, request): - project = self.testdata_path + "test+project_wfs.qgs" + project = self.testdata_path + "test_project_wfs.qgs" assert os.path.exists(project), "Project file not found: " + project query_string = 'MAP=%s&SERVICE=WFS&VERSION=1.0.0&REQUEST=%s' % (urllib.parse.quote(project), request) @@ -333,8 +359,8 @@ def result_compare(self, file_name, error_msg_header, header, body): """ response = re.sub(RE_STRIP_UNCHECKABLE, b'', response) expected = re.sub(RE_STRIP_UNCHECKABLE, b'', expected) - self.assertEqual(response, expected, msg="%s\n Expected:\n%s\n\n Response:\n%s" - % (error_msg_header, + self.assertXMLEqual(response, expected, msg="%s\n Expected:\n%s\n\n Response:\n%s" + % (error_msg_header, str(expected, errors='replace'), str(response, errors='replace'))) @@ -349,7 +375,7 @@ def test_getfeature(self): self.wfs_getfeature_compare(id, req) def wfs_getfeature_post_compare(self, requestid, request): - project = self.testdata_path + "test+project_wfs.qgs" + project = self.testdata_path + "test_project_wfs.qgs" assert os.path.exists(project), "Project file not found: " + project query_string = 'MAP={}'.format(urllib.parse.quote(project)) @@ -365,7 +391,6 @@ def wfs_getfeature_post_compare(self, requestid, request): header, body, ) - @unittest.skip def test_getfeature_post(self): template = """ @@ -392,20 +417,20 @@ def test_getfeature_post(self): for id, req in tests: self.wfs_getfeature_post_compare(id, req) - @unittest.skip def test_getLegendGraphics(self): """Test that does not return an exception but an image""" parms = { - 'MAP': self.testdata_path + "test%2Bproject.qgs", + 'MAP': self.testdata_path + "test_project.qgs", 'SERVICE': 'WMS', - 'VERSION': '1.0.0', + 'VERSION': '1.3.0', 'REQUEST': 'GetLegendGraphic', 'FORMAT': 'image/png', #'WIDTH': '20', # optional #'HEIGHT': '20', # optional - 'LAYER': 'testlayer+èé', + 'LAYER': 'testlayer%20èé', } qs = '&'.join(["%s=%s" % (k, v) for k, v in parms.items()]) + print(qs) h, r = self.server.handleRequest(qs) self.assertEqual(-1, h.find(b'Content-Type: text/xml; charset=utf-8'), "Header: %s\nResponse:\n%s" % (h, r)) self.assertNotEqual(-1, h.find(b'Content-Type: image/png'), "Header: %s\nResponse:\n%s" % (h, r)) diff --git a/tests/src/python/test_qgsserver_wfst.py b/tests/src/python/test_qgsserver_wfst.py index 4997c3a9981e..7462f828c49d 100644 --- a/tests/src/python/test_qgsserver_wfst.py +++ b/tests/src/python/test_qgsserver_wfst.py @@ -1,3 +1,4 @@ + # -*- coding: utf-8 -*- """ Tests for WFS-T provider using QGIS Server through qgis_wrapped_server.py. @@ -58,7 +59,11 @@ try: QGIS_SERVER_WFST_DEFAULT_PORT = os.environ['QGIS_SERVER_WFST_DEFAULT_PORT'] except: - QGIS_SERVER_WFST_DEFAULT_PORT = 8081 + import socket + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("", 0)) + QGIS_SERVER_WFST_DEFAULT_PORT = s.getsockname()[1] + s.close() qgis_app = start_app() diff --git a/tests/testdata/qgis_server/getcapabilities.txt b/tests/testdata/qgis_server/getcapabilities.txt index e170cbda76cd..94fdf5c247d9 100644 --- a/tests/testdata/qgis_server/getcapabilities.txt +++ b/tests/testdata/qgis_server/getcapabilities.txt @@ -2,7 +2,7 @@ Content-Length: 5590 Content-Type: text/xml; charset=utf-8 - + WMS QGIS TestProject @@ -30,7 +30,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -45,7 +45,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -59,7 +59,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -70,7 +70,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -80,7 +80,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -90,7 +90,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -131,7 +131,7 @@ Content-Type: text/xml; charset=utf-8 default image/png - + diff --git a/tests/testdata/qgis_server/getcapabilities_inspire.txt b/tests/testdata/qgis_server/getcapabilities_inspire.txt index da2f31dbcc88..2186a71be3f1 100644 --- a/tests/testdata/qgis_server/getcapabilities_inspire.txt +++ b/tests/testdata/qgis_server/getcapabilities_inspire.txt @@ -2,7 +2,7 @@ Content-Length: 7368 Content-Type: text/xml; charset=utf-8 - + WMS QGIS TestProject @@ -30,7 +30,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -45,7 +45,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -59,7 +59,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -70,7 +70,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -80,7 +80,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -90,7 +90,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -152,7 +152,7 @@ Content-Type: text/xml; charset=utf-8 default image/png - + diff --git a/tests/testdata/qgis_server/getprojectsettings.txt b/tests/testdata/qgis_server/getprojectsettings.txt index 6a018cfb84ff..bc96a7b9f27c 100644 --- a/tests/testdata/qgis_server/getprojectsettings.txt +++ b/tests/testdata/qgis_server/getprojectsettings.txt @@ -2,7 +2,7 @@ Content-Length: 6685 Content-Type: text/xml; charset=utf-8 - + WMS QGIS TestProject @@ -30,7 +30,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -45,7 +45,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -59,7 +59,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -70,7 +70,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -80,7 +80,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -90,7 +90,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -102,7 +102,7 @@ Content-Type: text/xml; charset=utf-8 - + @@ -112,6 +112,9 @@ Content-Type: text/xml; charset=utf-8 text/xml + + + QGIS Test Project QGIS Test Project @@ -145,7 +148,7 @@ Content-Type: text/xml; charset=utf-8 default image/png - + testlayer èé diff --git a/tests/testdata/qgis_server/test+project.qgs b/tests/testdata/qgis_server/test_project.qgs similarity index 68% rename from tests/testdata/qgis_server/test+project.qgs rename to tests/testdata/qgis_server/test_project.qgs index 896980a27870..5ef2de9216ba 100644 --- a/tests/testdata/qgis_server/test+project.qgs +++ b/tests/testdata/qgis_server/test_project.qgs @@ -1,11 +1,11 @@ - + QGIS Test Project - + - + @@ -13,10 +13,10 @@ degrees - 8.20315414376310059 - 44.9012858326611024 - 8.204164917965862 - 44.90154911342418131 + 8.20202108826836884 + 44.9009031607650968 + 8.20606418507941449 + 44.90195628381741244 0 1 @@ -34,7 +34,7 @@ 0 - + @@ -43,14 +43,14 @@ - + - + testlayer20150528120452665 ./testlayer.shp A test vector layer @@ -72,70 +72,65 @@ ogr + "name" - - - - - - - - + + - - + + - - + + - + - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + - - - - + + + + - - + + - - - - + + + + @@ -286,51 +281,73 @@ 0 0 0 - - - - + name + + + + + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - + . - - - + + + - + . 0 - + . 0 generatedlayout @@ -339,106 +356,119 @@ - - "name" - - - - + + + +proj=longlat +datum=WGS84 +no_defs + EPSG:4326 + 3452 + 1 + + + meters + m2 + + + false + 8.20315414376310059 44.901236559338642 8.204164917965862 44.90159838674664172 - + + + + + true + 255 + + + None + elpaso@itopen.it + 90 + + 8 + + + QGIS TestProject + + + + testlayer20150528120452665 + + + testlayer20150528120452665 + + + testlayer20150528120452665 + + - - - - - 90 - Some UTF8 text èòù + conditions unknown + + + true - - - - - QGIS TestProject - 4 - - +proj=longlat +datum=WGS84 +no_defs - 1 - EPSG:4326 - 3452 - - - false - - false - - off - current_layer - - 0 - 2 + current_layer + + + off + 0 + - - - + + + + Alessandro Pasotti QGIS dev team - - - - true - elpaso@itopen.it - - WGS84 - + + + + + false + + + + + + 2 true D - - - - - - Alessandro Pasotti - - false - - - - true - - 255 - - - - - 255 - 255 - 255 - 255 0 + 255 255 + 255 255 + 255 + 255 + + WGS84 + + Some UTF8 text èòù + + testlayer20150528120452665 + + + true + false diff --git a/tests/testdata/qgis_server/test+project_inspire.qgs b/tests/testdata/qgis_server/test_project_inspire.qgs similarity index 100% rename from tests/testdata/qgis_server/test+project_inspire.qgs rename to tests/testdata/qgis_server/test_project_inspire.qgs diff --git a/tests/testdata/qgis_server/test+project_wfs.qgs b/tests/testdata/qgis_server/test_project_wfs.qgs similarity index 100% rename from tests/testdata/qgis_server/test+project_wfs.qgs rename to tests/testdata/qgis_server/test_project_wfs.qgs From 874d52fa9c4d2c8cdc0bb74d39b317d421573bf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 13:10:21 +0200 Subject: [PATCH 011/897] check if geometry is multipart without wkb types --- .../processing/algs/qgis/SplitWithLines.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 7fc7cb33411a..93df1adcd3d1 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -80,22 +80,17 @@ def processAlgorithm(self, progress): else: total = 100.0 / float(len(features)) - allowedWkbTypes = [2, #WkbLineString - 3, # WkbPolygon - -2147483646, #WkbLineString25D - -2147483645] # WkbPolygon25D - # MultiGeometries are not allowed because the result of a splitted ring is not clearly defined: - # 1) add both parts as new features - # 2) store one part as a new feature and the other one as ring of the multi geometry - # 2a) which part is which, seems arbitrary - multiGeoms = 0 # how many multi geometries were encountered for current, inFeatA in enumerate(features): inGeom = inFeatA.geometry() - if allowedWkbTypes.count(inGeom.wkbType()) == 0: + if inGeom.isMultipart(): multiGeoms += 1 + # MultiGeometries are not allowed because the result of a splitted part cannot be clearly defined: + # 1) add both new parts as new features + # 2) store one part as a new feature and the other one as part of the multi geometry + # 2a) which part should be which, seems arbitrary else: attrsA = inFeatA.attributes() outFeat.setAttributes(attrsA) From 6b2799414a3b6434818adc859d3f1363029eb579 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Thu, 29 Sep 2016 13:43:10 +0200 Subject: [PATCH 012/897] nodetool: use exact intersect when picking features (fixes #15294) --- src/app/nodetool/qgsmaptoolnodetool.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/app/nodetool/qgsmaptoolnodetool.cpp b/src/app/nodetool/qgsmaptoolnodetool.cpp index 0bdb77eca844..99f6590735ce 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.cpp +++ b/src/app/nodetool/qgsmaptoolnodetool.cpp @@ -202,6 +202,7 @@ QgsFeature QgsMapToolNodeTool::getFeatureAtPoint( QgsMapMouseEvent* e ) QgsFeatureRequest request; request.setFilterRect( QgsRectangle( e->mapPoint().x(), e->mapPoint().y(), e->mapPoint().x(), e->mapPoint().y() ) ); + request.setFlags( QgsFeatureRequest::ExactIntersect ); QgsFeatureIterator features = vlayer->getFeatures( request ); features.nextFeature( feature ); From 19585ee1aa4da08c438f7b5f364fba0f800522bf Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Thu, 29 Sep 2016 14:06:45 +0200 Subject: [PATCH 013/897] [Server 3.0] Typo in test name and removed obsolete comments --- tests/src/python/CMakeLists.txt | 2 +- tests/src/python/test_authmanager_endpoint.py | 2 +- tests/src/python/test_qgsserver.py | 4 ---- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index d268f8c072e5..8e66b7d5d195 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -150,5 +150,5 @@ IF (WITH_SERVER) ADD_PYTHON_TEST(PyQgsServerAccessControl test_qgsserver_accesscontrol.py) ADD_PYTHON_TEST(PyQgsServerWFST test_qgsserver_wfst.py) ADD_PYTHON_TEST(PyQgsOfflineEditingWFS test_offline_editing_wfs.py) - ADD_PYTHON_TEST(PyQgsAuthManagerEnpointTest test_authmanager_endpoint.py) + ADD_PYTHON_TEST(PyQgsAuthManagerEndpointTest test_authmanager_endpoint.py) ENDIF (WITH_SERVER) diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_endpoint.py index 50d712b67734..85bc68fddcef 100644 --- a/tests/src/python/test_authmanager_endpoint.py +++ b/tests/src/python/test_authmanager_endpoint.py @@ -8,7 +8,7 @@ configuration to access an HTTP Basic protected endpoint. -From build dir, run: ctest -R PyQgsAuthManagerEnpointTest -V +From build dir, run: ctest -R PyQgsAuthManagerEndpointTest -V .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/tests/src/python/test_qgsserver.py b/tests/src/python/test_qgsserver.py index 460859d2ee8c..e06b9ad5b413 100644 --- a/tests/src/python/test_qgsserver.py +++ b/tests/src/python/test_qgsserver.py @@ -27,10 +27,6 @@ import osgeo.gdal # Strip path and content length because path may vary -# Also strip all multi-attribute tags (Qt5 attr order is random) -# FIXME: this is a temporary workaround to make the test pass, a more -# robust implementation must check for attributes too -#RE_STRIP_UNCHECKABLE = b']*>|]*>|]*>|]*>|MAP=[^"]+|Content-Length: \d+|]*>|]*>|]*>|]*>|]*>|]*>|]*>|]*>' RE_STRIP_UNCHECKABLE = b'MAP=[^"]+|Content-Length: \d+' RE_ATTRIBUTES = b'[^>\s]+=[^>\s]+' From 84981ee1f274c1eea8663cdaa9b7ccb93cb526f6 Mon Sep 17 00:00:00 2001 From: Bas Couwenberg Date: Thu, 29 Sep 2016 14:44:36 +0200 Subject: [PATCH 014/897] Move icons to subdirectory. --- debian/{ => icons}/qbrowser-icon128x128.png | Bin debian/{ => icons}/qbrowser-icon16x16.png | Bin debian/{ => icons}/qbrowser-icon192x192.png | Bin debian/{ => icons}/qbrowser-icon22x22.png | Bin debian/{ => icons}/qbrowser-icon24x24.png | Bin debian/{ => icons}/qbrowser-icon256x256.png | Bin debian/{ => icons}/qbrowser-icon32x32.png | Bin debian/{ => icons}/qbrowser-icon36x36.png | Bin debian/{ => icons}/qbrowser-icon42x42.png | Bin debian/{ => icons}/qbrowser-icon48x48.png | Bin debian/{ => icons}/qbrowser-icon512x512.png | Bin debian/{ => icons}/qbrowser-icon64x64.png | Bin debian/{ => icons}/qbrowser-icon72x72.png | Bin debian/{ => icons}/qbrowser-icon80x80.png | Bin debian/{ => icons}/qbrowser-icon8x8.png | Bin debian/{ => icons}/qbrowser-icon96x96.png | Bin debian/{ => icons}/qgis-icon128x128.png | Bin debian/{ => icons}/qgis-icon16x16.png | Bin debian/{ => icons}/qgis-icon192x192.png | Bin debian/{ => icons}/qgis-icon22x22.png | Bin debian/{ => icons}/qgis-icon24x24.png | Bin debian/{ => icons}/qgis-icon256x256.png | Bin debian/{ => icons}/qgis-icon32x32.png | Bin debian/{ => icons}/qgis-icon36x36.png | Bin debian/{ => icons}/qgis-icon42x42.png | Bin debian/{ => icons}/qgis-icon48x48.png | Bin debian/{ => icons}/qgis-icon512x512.png | Bin debian/{ => icons}/qgis-icon64x64.png | Bin debian/{ => icons}/qgis-icon72x72.png | Bin debian/{ => icons}/qgis-icon80x80.png | Bin debian/{ => icons}/qgis-icon8x8.png | Bin debian/{ => icons}/qgis-icon96x96.png | Bin debian/{ => icons}/qgis-mime-icon128x128.png | Bin debian/{ => icons}/qgis-mime-icon16x16.png | Bin debian/{ => icons}/qgis-mime-icon192x192.png | Bin debian/{ => icons}/qgis-mime-icon22x22.png | Bin debian/{ => icons}/qgis-mime-icon24x24.png | Bin debian/{ => icons}/qgis-mime-icon256x256.png | Bin debian/{ => icons}/qgis-mime-icon32x32.png | Bin debian/{ => icons}/qgis-mime-icon36x36.png | Bin debian/{ => icons}/qgis-mime-icon42x42.png | Bin debian/{ => icons}/qgis-mime-icon48x48.png | Bin debian/{ => icons}/qgis-mime-icon512x512.png | Bin debian/{ => icons}/qgis-mime-icon64x64.png | Bin debian/{ => icons}/qgis-mime-icon72x72.png | Bin debian/{ => icons}/qgis-mime-icon80x80.png | Bin debian/{ => icons}/qgis-mime-icon8x8.png | Bin debian/{ => icons}/qgis-mime-icon96x96.png | Bin debian/{ => icons}/qgis-qgs128x128.png | Bin debian/{ => icons}/qgis-qgs16x16.png | Bin debian/{ => icons}/qgis-qgs192x192.png | Bin debian/{ => icons}/qgis-qgs22x22.png | Bin debian/{ => icons}/qgis-qgs24x24.png | Bin debian/{ => icons}/qgis-qgs256x256.png | Bin debian/{ => icons}/qgis-qgs32x32.png | Bin debian/{ => icons}/qgis-qgs36x36.png | Bin debian/{ => icons}/qgis-qgs42x42.png | Bin debian/{ => icons}/qgis-qgs48x48.png | Bin debian/{ => icons}/qgis-qgs512x512.png | Bin debian/{ => icons}/qgis-qgs64x64.png | Bin debian/{ => icons}/qgis-qgs72x72.png | Bin debian/{ => icons}/qgis-qgs80x80.png | Bin debian/{ => icons}/qgis-qgs8x8.png | Bin debian/{ => icons}/qgis-qgs96x96.png | Bin debian/{ => icons}/qgis-qlr128x128.png | Bin debian/{ => icons}/qgis-qlr16x16.png | Bin debian/{ => icons}/qgis-qlr192x192.png | Bin debian/{ => icons}/qgis-qlr22x22.png | Bin debian/{ => icons}/qgis-qlr24x24.png | Bin debian/{ => icons}/qgis-qlr256x256.png | Bin debian/{ => icons}/qgis-qlr32x32.png | Bin debian/{ => icons}/qgis-qlr36x36.png | Bin debian/{ => icons}/qgis-qlr42x42.png | Bin debian/{ => icons}/qgis-qlr48x48.png | Bin debian/{ => icons}/qgis-qlr512x512.png | Bin debian/{ => icons}/qgis-qlr64x64.png | Bin debian/{ => icons}/qgis-qlr72x72.png | Bin debian/{ => icons}/qgis-qlr80x80.png | Bin debian/{ => icons}/qgis-qlr8x8.png | Bin debian/{ => icons}/qgis-qlr96x96.png | Bin debian/{ => icons}/qgis-qml128x128.png | Bin debian/{ => icons}/qgis-qml16x16.png | Bin debian/{ => icons}/qgis-qml192x192.png | Bin debian/{ => icons}/qgis-qml22x22.png | Bin debian/{ => icons}/qgis-qml24x24.png | Bin debian/{ => icons}/qgis-qml256x256.png | Bin debian/{ => icons}/qgis-qml32x32.png | Bin debian/{ => icons}/qgis-qml36x36.png | Bin debian/{ => icons}/qgis-qml42x42.png | Bin debian/{ => icons}/qgis-qml48x48.png | Bin debian/{ => icons}/qgis-qml512x512.png | Bin debian/{ => icons}/qgis-qml64x64.png | Bin debian/{ => icons}/qgis-qml72x72.png | Bin debian/{ => icons}/qgis-qml80x80.png | Bin debian/{ => icons}/qgis-qml8x8.png | Bin debian/{ => icons}/qgis-qml96x96.png | Bin debian/{ => icons}/qgis-qpt128x128.png | Bin debian/{ => icons}/qgis-qpt16x16.png | Bin debian/{ => icons}/qgis-qpt192x192.png | Bin debian/{ => icons}/qgis-qpt22x22.png | Bin debian/{ => icons}/qgis-qpt24x24.png | Bin debian/{ => icons}/qgis-qpt256x256.png | Bin debian/{ => icons}/qgis-qpt32x32.png | Bin debian/{ => icons}/qgis-qpt36x36.png | Bin debian/{ => icons}/qgis-qpt42x42.png | Bin debian/{ => icons}/qgis-qpt48x48.png | Bin debian/{ => icons}/qgis-qpt512x512.png | Bin debian/{ => icons}/qgis-qpt64x64.png | Bin debian/{ => icons}/qgis-qpt72x72.png | Bin debian/{ => icons}/qgis-qpt80x80.png | Bin debian/{ => icons}/qgis-qpt8x8.png | Bin debian/{ => icons}/qgis-qpt96x96.png | Bin debian/rules | 8 ++++---- 113 files changed, 4 insertions(+), 4 deletions(-) rename debian/{ => icons}/qbrowser-icon128x128.png (100%) rename debian/{ => icons}/qbrowser-icon16x16.png (100%) rename debian/{ => icons}/qbrowser-icon192x192.png (100%) rename debian/{ => icons}/qbrowser-icon22x22.png (100%) rename debian/{ => icons}/qbrowser-icon24x24.png (100%) rename debian/{ => icons}/qbrowser-icon256x256.png (100%) rename debian/{ => icons}/qbrowser-icon32x32.png (100%) rename debian/{ => icons}/qbrowser-icon36x36.png (100%) rename debian/{ => icons}/qbrowser-icon42x42.png (100%) rename debian/{ => icons}/qbrowser-icon48x48.png (100%) rename debian/{ => icons}/qbrowser-icon512x512.png (100%) rename debian/{ => icons}/qbrowser-icon64x64.png (100%) rename debian/{ => icons}/qbrowser-icon72x72.png (100%) rename debian/{ => icons}/qbrowser-icon80x80.png (100%) rename debian/{ => icons}/qbrowser-icon8x8.png (100%) rename debian/{ => icons}/qbrowser-icon96x96.png (100%) rename debian/{ => icons}/qgis-icon128x128.png (100%) rename debian/{ => icons}/qgis-icon16x16.png (100%) rename debian/{ => icons}/qgis-icon192x192.png (100%) rename debian/{ => icons}/qgis-icon22x22.png (100%) rename debian/{ => icons}/qgis-icon24x24.png (100%) rename debian/{ => icons}/qgis-icon256x256.png (100%) rename debian/{ => icons}/qgis-icon32x32.png (100%) rename debian/{ => icons}/qgis-icon36x36.png (100%) rename debian/{ => icons}/qgis-icon42x42.png (100%) rename debian/{ => icons}/qgis-icon48x48.png (100%) rename debian/{ => icons}/qgis-icon512x512.png (100%) rename debian/{ => icons}/qgis-icon64x64.png (100%) rename debian/{ => icons}/qgis-icon72x72.png (100%) rename debian/{ => icons}/qgis-icon80x80.png (100%) rename debian/{ => icons}/qgis-icon8x8.png (100%) rename debian/{ => icons}/qgis-icon96x96.png (100%) rename debian/{ => icons}/qgis-mime-icon128x128.png (100%) rename debian/{ => icons}/qgis-mime-icon16x16.png (100%) rename debian/{ => icons}/qgis-mime-icon192x192.png (100%) rename debian/{ => icons}/qgis-mime-icon22x22.png (100%) rename debian/{ => icons}/qgis-mime-icon24x24.png (100%) rename debian/{ => icons}/qgis-mime-icon256x256.png (100%) rename debian/{ => icons}/qgis-mime-icon32x32.png (100%) rename debian/{ => icons}/qgis-mime-icon36x36.png (100%) rename debian/{ => icons}/qgis-mime-icon42x42.png (100%) rename debian/{ => icons}/qgis-mime-icon48x48.png (100%) rename debian/{ => icons}/qgis-mime-icon512x512.png (100%) rename debian/{ => icons}/qgis-mime-icon64x64.png (100%) rename debian/{ => icons}/qgis-mime-icon72x72.png (100%) rename debian/{ => icons}/qgis-mime-icon80x80.png (100%) rename debian/{ => icons}/qgis-mime-icon8x8.png (100%) rename debian/{ => icons}/qgis-mime-icon96x96.png (100%) rename debian/{ => icons}/qgis-qgs128x128.png (100%) rename debian/{ => icons}/qgis-qgs16x16.png (100%) rename debian/{ => icons}/qgis-qgs192x192.png (100%) rename debian/{ => icons}/qgis-qgs22x22.png (100%) rename debian/{ => icons}/qgis-qgs24x24.png (100%) rename debian/{ => icons}/qgis-qgs256x256.png (100%) rename debian/{ => icons}/qgis-qgs32x32.png (100%) rename debian/{ => icons}/qgis-qgs36x36.png (100%) rename debian/{ => icons}/qgis-qgs42x42.png (100%) rename debian/{ => icons}/qgis-qgs48x48.png (100%) rename debian/{ => icons}/qgis-qgs512x512.png (100%) rename debian/{ => icons}/qgis-qgs64x64.png (100%) rename debian/{ => icons}/qgis-qgs72x72.png (100%) rename debian/{ => icons}/qgis-qgs80x80.png (100%) rename debian/{ => icons}/qgis-qgs8x8.png (100%) rename debian/{ => icons}/qgis-qgs96x96.png (100%) rename debian/{ => icons}/qgis-qlr128x128.png (100%) rename debian/{ => icons}/qgis-qlr16x16.png (100%) rename debian/{ => icons}/qgis-qlr192x192.png (100%) rename debian/{ => icons}/qgis-qlr22x22.png (100%) rename debian/{ => icons}/qgis-qlr24x24.png (100%) rename debian/{ => icons}/qgis-qlr256x256.png (100%) rename debian/{ => icons}/qgis-qlr32x32.png (100%) rename debian/{ => icons}/qgis-qlr36x36.png (100%) rename debian/{ => icons}/qgis-qlr42x42.png (100%) rename debian/{ => icons}/qgis-qlr48x48.png (100%) rename debian/{ => icons}/qgis-qlr512x512.png (100%) rename debian/{ => icons}/qgis-qlr64x64.png (100%) rename debian/{ => icons}/qgis-qlr72x72.png (100%) rename debian/{ => icons}/qgis-qlr80x80.png (100%) rename debian/{ => icons}/qgis-qlr8x8.png (100%) rename debian/{ => icons}/qgis-qlr96x96.png (100%) rename debian/{ => icons}/qgis-qml128x128.png (100%) rename debian/{ => icons}/qgis-qml16x16.png (100%) rename debian/{ => icons}/qgis-qml192x192.png (100%) rename debian/{ => icons}/qgis-qml22x22.png (100%) rename debian/{ => icons}/qgis-qml24x24.png (100%) rename debian/{ => icons}/qgis-qml256x256.png (100%) rename debian/{ => icons}/qgis-qml32x32.png (100%) rename debian/{ => icons}/qgis-qml36x36.png (100%) rename debian/{ => icons}/qgis-qml42x42.png (100%) rename debian/{ => icons}/qgis-qml48x48.png (100%) rename debian/{ => icons}/qgis-qml512x512.png (100%) rename debian/{ => icons}/qgis-qml64x64.png (100%) rename debian/{ => icons}/qgis-qml72x72.png (100%) rename debian/{ => icons}/qgis-qml80x80.png (100%) rename debian/{ => icons}/qgis-qml8x8.png (100%) rename debian/{ => icons}/qgis-qml96x96.png (100%) rename debian/{ => icons}/qgis-qpt128x128.png (100%) rename debian/{ => icons}/qgis-qpt16x16.png (100%) rename debian/{ => icons}/qgis-qpt192x192.png (100%) rename debian/{ => icons}/qgis-qpt22x22.png (100%) rename debian/{ => icons}/qgis-qpt24x24.png (100%) rename debian/{ => icons}/qgis-qpt256x256.png (100%) rename debian/{ => icons}/qgis-qpt32x32.png (100%) rename debian/{ => icons}/qgis-qpt36x36.png (100%) rename debian/{ => icons}/qgis-qpt42x42.png (100%) rename debian/{ => icons}/qgis-qpt48x48.png (100%) rename debian/{ => icons}/qgis-qpt512x512.png (100%) rename debian/{ => icons}/qgis-qpt64x64.png (100%) rename debian/{ => icons}/qgis-qpt72x72.png (100%) rename debian/{ => icons}/qgis-qpt80x80.png (100%) rename debian/{ => icons}/qgis-qpt8x8.png (100%) rename debian/{ => icons}/qgis-qpt96x96.png (100%) diff --git a/debian/qbrowser-icon128x128.png b/debian/icons/qbrowser-icon128x128.png similarity index 100% rename from debian/qbrowser-icon128x128.png rename to debian/icons/qbrowser-icon128x128.png diff --git a/debian/qbrowser-icon16x16.png b/debian/icons/qbrowser-icon16x16.png similarity index 100% rename from debian/qbrowser-icon16x16.png rename to debian/icons/qbrowser-icon16x16.png diff --git a/debian/qbrowser-icon192x192.png b/debian/icons/qbrowser-icon192x192.png similarity index 100% rename from debian/qbrowser-icon192x192.png rename to debian/icons/qbrowser-icon192x192.png diff --git a/debian/qbrowser-icon22x22.png b/debian/icons/qbrowser-icon22x22.png similarity index 100% rename from debian/qbrowser-icon22x22.png rename to debian/icons/qbrowser-icon22x22.png diff --git a/debian/qbrowser-icon24x24.png b/debian/icons/qbrowser-icon24x24.png similarity index 100% rename from debian/qbrowser-icon24x24.png rename to debian/icons/qbrowser-icon24x24.png diff --git a/debian/qbrowser-icon256x256.png b/debian/icons/qbrowser-icon256x256.png similarity index 100% rename from debian/qbrowser-icon256x256.png rename to debian/icons/qbrowser-icon256x256.png diff --git a/debian/qbrowser-icon32x32.png b/debian/icons/qbrowser-icon32x32.png similarity index 100% rename from debian/qbrowser-icon32x32.png rename to debian/icons/qbrowser-icon32x32.png diff --git a/debian/qbrowser-icon36x36.png b/debian/icons/qbrowser-icon36x36.png similarity index 100% rename from debian/qbrowser-icon36x36.png rename to debian/icons/qbrowser-icon36x36.png diff --git a/debian/qbrowser-icon42x42.png b/debian/icons/qbrowser-icon42x42.png similarity index 100% rename from debian/qbrowser-icon42x42.png rename to debian/icons/qbrowser-icon42x42.png diff --git a/debian/qbrowser-icon48x48.png b/debian/icons/qbrowser-icon48x48.png similarity index 100% rename from debian/qbrowser-icon48x48.png rename to debian/icons/qbrowser-icon48x48.png diff --git a/debian/qbrowser-icon512x512.png b/debian/icons/qbrowser-icon512x512.png similarity index 100% rename from debian/qbrowser-icon512x512.png rename to debian/icons/qbrowser-icon512x512.png diff --git a/debian/qbrowser-icon64x64.png b/debian/icons/qbrowser-icon64x64.png similarity index 100% rename from debian/qbrowser-icon64x64.png rename to debian/icons/qbrowser-icon64x64.png diff --git a/debian/qbrowser-icon72x72.png b/debian/icons/qbrowser-icon72x72.png similarity index 100% rename from debian/qbrowser-icon72x72.png rename to debian/icons/qbrowser-icon72x72.png diff --git a/debian/qbrowser-icon80x80.png b/debian/icons/qbrowser-icon80x80.png similarity index 100% rename from debian/qbrowser-icon80x80.png rename to debian/icons/qbrowser-icon80x80.png diff --git a/debian/qbrowser-icon8x8.png b/debian/icons/qbrowser-icon8x8.png similarity index 100% rename from debian/qbrowser-icon8x8.png rename to debian/icons/qbrowser-icon8x8.png diff --git a/debian/qbrowser-icon96x96.png b/debian/icons/qbrowser-icon96x96.png similarity index 100% rename from debian/qbrowser-icon96x96.png rename to debian/icons/qbrowser-icon96x96.png diff --git a/debian/qgis-icon128x128.png b/debian/icons/qgis-icon128x128.png similarity index 100% rename from debian/qgis-icon128x128.png rename to debian/icons/qgis-icon128x128.png diff --git a/debian/qgis-icon16x16.png b/debian/icons/qgis-icon16x16.png similarity index 100% rename from debian/qgis-icon16x16.png rename to debian/icons/qgis-icon16x16.png diff --git a/debian/qgis-icon192x192.png b/debian/icons/qgis-icon192x192.png similarity index 100% rename from debian/qgis-icon192x192.png rename to debian/icons/qgis-icon192x192.png diff --git a/debian/qgis-icon22x22.png b/debian/icons/qgis-icon22x22.png similarity index 100% rename from debian/qgis-icon22x22.png rename to debian/icons/qgis-icon22x22.png diff --git a/debian/qgis-icon24x24.png b/debian/icons/qgis-icon24x24.png similarity index 100% rename from debian/qgis-icon24x24.png rename to debian/icons/qgis-icon24x24.png diff --git a/debian/qgis-icon256x256.png b/debian/icons/qgis-icon256x256.png similarity index 100% rename from debian/qgis-icon256x256.png rename to debian/icons/qgis-icon256x256.png diff --git a/debian/qgis-icon32x32.png b/debian/icons/qgis-icon32x32.png similarity index 100% rename from debian/qgis-icon32x32.png rename to debian/icons/qgis-icon32x32.png diff --git a/debian/qgis-icon36x36.png b/debian/icons/qgis-icon36x36.png similarity index 100% rename from debian/qgis-icon36x36.png rename to debian/icons/qgis-icon36x36.png diff --git a/debian/qgis-icon42x42.png b/debian/icons/qgis-icon42x42.png similarity index 100% rename from debian/qgis-icon42x42.png rename to debian/icons/qgis-icon42x42.png diff --git a/debian/qgis-icon48x48.png b/debian/icons/qgis-icon48x48.png similarity index 100% rename from debian/qgis-icon48x48.png rename to debian/icons/qgis-icon48x48.png diff --git a/debian/qgis-icon512x512.png b/debian/icons/qgis-icon512x512.png similarity index 100% rename from debian/qgis-icon512x512.png rename to debian/icons/qgis-icon512x512.png diff --git a/debian/qgis-icon64x64.png b/debian/icons/qgis-icon64x64.png similarity index 100% rename from debian/qgis-icon64x64.png rename to debian/icons/qgis-icon64x64.png diff --git a/debian/qgis-icon72x72.png b/debian/icons/qgis-icon72x72.png similarity index 100% rename from debian/qgis-icon72x72.png rename to debian/icons/qgis-icon72x72.png diff --git a/debian/qgis-icon80x80.png b/debian/icons/qgis-icon80x80.png similarity index 100% rename from debian/qgis-icon80x80.png rename to debian/icons/qgis-icon80x80.png diff --git a/debian/qgis-icon8x8.png b/debian/icons/qgis-icon8x8.png similarity index 100% rename from debian/qgis-icon8x8.png rename to debian/icons/qgis-icon8x8.png diff --git a/debian/qgis-icon96x96.png b/debian/icons/qgis-icon96x96.png similarity index 100% rename from debian/qgis-icon96x96.png rename to debian/icons/qgis-icon96x96.png diff --git a/debian/qgis-mime-icon128x128.png b/debian/icons/qgis-mime-icon128x128.png similarity index 100% rename from debian/qgis-mime-icon128x128.png rename to debian/icons/qgis-mime-icon128x128.png diff --git a/debian/qgis-mime-icon16x16.png b/debian/icons/qgis-mime-icon16x16.png similarity index 100% rename from debian/qgis-mime-icon16x16.png rename to debian/icons/qgis-mime-icon16x16.png diff --git a/debian/qgis-mime-icon192x192.png b/debian/icons/qgis-mime-icon192x192.png similarity index 100% rename from debian/qgis-mime-icon192x192.png rename to debian/icons/qgis-mime-icon192x192.png diff --git a/debian/qgis-mime-icon22x22.png b/debian/icons/qgis-mime-icon22x22.png similarity index 100% rename from debian/qgis-mime-icon22x22.png rename to debian/icons/qgis-mime-icon22x22.png diff --git a/debian/qgis-mime-icon24x24.png b/debian/icons/qgis-mime-icon24x24.png similarity index 100% rename from debian/qgis-mime-icon24x24.png rename to debian/icons/qgis-mime-icon24x24.png diff --git a/debian/qgis-mime-icon256x256.png b/debian/icons/qgis-mime-icon256x256.png similarity index 100% rename from debian/qgis-mime-icon256x256.png rename to debian/icons/qgis-mime-icon256x256.png diff --git a/debian/qgis-mime-icon32x32.png b/debian/icons/qgis-mime-icon32x32.png similarity index 100% rename from debian/qgis-mime-icon32x32.png rename to debian/icons/qgis-mime-icon32x32.png diff --git a/debian/qgis-mime-icon36x36.png b/debian/icons/qgis-mime-icon36x36.png similarity index 100% rename from debian/qgis-mime-icon36x36.png rename to debian/icons/qgis-mime-icon36x36.png diff --git a/debian/qgis-mime-icon42x42.png b/debian/icons/qgis-mime-icon42x42.png similarity index 100% rename from debian/qgis-mime-icon42x42.png rename to debian/icons/qgis-mime-icon42x42.png diff --git a/debian/qgis-mime-icon48x48.png b/debian/icons/qgis-mime-icon48x48.png similarity index 100% rename from debian/qgis-mime-icon48x48.png rename to debian/icons/qgis-mime-icon48x48.png diff --git a/debian/qgis-mime-icon512x512.png b/debian/icons/qgis-mime-icon512x512.png similarity index 100% rename from debian/qgis-mime-icon512x512.png rename to debian/icons/qgis-mime-icon512x512.png diff --git a/debian/qgis-mime-icon64x64.png b/debian/icons/qgis-mime-icon64x64.png similarity index 100% rename from debian/qgis-mime-icon64x64.png rename to debian/icons/qgis-mime-icon64x64.png diff --git a/debian/qgis-mime-icon72x72.png b/debian/icons/qgis-mime-icon72x72.png similarity index 100% rename from debian/qgis-mime-icon72x72.png rename to debian/icons/qgis-mime-icon72x72.png diff --git a/debian/qgis-mime-icon80x80.png b/debian/icons/qgis-mime-icon80x80.png similarity index 100% rename from debian/qgis-mime-icon80x80.png rename to debian/icons/qgis-mime-icon80x80.png diff --git a/debian/qgis-mime-icon8x8.png b/debian/icons/qgis-mime-icon8x8.png similarity index 100% rename from debian/qgis-mime-icon8x8.png rename to debian/icons/qgis-mime-icon8x8.png diff --git a/debian/qgis-mime-icon96x96.png b/debian/icons/qgis-mime-icon96x96.png similarity index 100% rename from debian/qgis-mime-icon96x96.png rename to debian/icons/qgis-mime-icon96x96.png diff --git a/debian/qgis-qgs128x128.png b/debian/icons/qgis-qgs128x128.png similarity index 100% rename from debian/qgis-qgs128x128.png rename to debian/icons/qgis-qgs128x128.png diff --git a/debian/qgis-qgs16x16.png b/debian/icons/qgis-qgs16x16.png similarity index 100% rename from debian/qgis-qgs16x16.png rename to debian/icons/qgis-qgs16x16.png diff --git a/debian/qgis-qgs192x192.png b/debian/icons/qgis-qgs192x192.png similarity index 100% rename from debian/qgis-qgs192x192.png rename to debian/icons/qgis-qgs192x192.png diff --git a/debian/qgis-qgs22x22.png b/debian/icons/qgis-qgs22x22.png similarity index 100% rename from debian/qgis-qgs22x22.png rename to debian/icons/qgis-qgs22x22.png diff --git a/debian/qgis-qgs24x24.png b/debian/icons/qgis-qgs24x24.png similarity index 100% rename from debian/qgis-qgs24x24.png rename to debian/icons/qgis-qgs24x24.png diff --git a/debian/qgis-qgs256x256.png b/debian/icons/qgis-qgs256x256.png similarity index 100% rename from debian/qgis-qgs256x256.png rename to debian/icons/qgis-qgs256x256.png diff --git a/debian/qgis-qgs32x32.png b/debian/icons/qgis-qgs32x32.png similarity index 100% rename from debian/qgis-qgs32x32.png rename to debian/icons/qgis-qgs32x32.png diff --git a/debian/qgis-qgs36x36.png b/debian/icons/qgis-qgs36x36.png similarity index 100% rename from debian/qgis-qgs36x36.png rename to debian/icons/qgis-qgs36x36.png diff --git a/debian/qgis-qgs42x42.png b/debian/icons/qgis-qgs42x42.png similarity index 100% rename from debian/qgis-qgs42x42.png rename to debian/icons/qgis-qgs42x42.png diff --git a/debian/qgis-qgs48x48.png b/debian/icons/qgis-qgs48x48.png similarity index 100% rename from debian/qgis-qgs48x48.png rename to debian/icons/qgis-qgs48x48.png diff --git a/debian/qgis-qgs512x512.png b/debian/icons/qgis-qgs512x512.png similarity index 100% rename from debian/qgis-qgs512x512.png rename to debian/icons/qgis-qgs512x512.png diff --git a/debian/qgis-qgs64x64.png b/debian/icons/qgis-qgs64x64.png similarity index 100% rename from debian/qgis-qgs64x64.png rename to debian/icons/qgis-qgs64x64.png diff --git a/debian/qgis-qgs72x72.png b/debian/icons/qgis-qgs72x72.png similarity index 100% rename from debian/qgis-qgs72x72.png rename to debian/icons/qgis-qgs72x72.png diff --git a/debian/qgis-qgs80x80.png b/debian/icons/qgis-qgs80x80.png similarity index 100% rename from debian/qgis-qgs80x80.png rename to debian/icons/qgis-qgs80x80.png diff --git a/debian/qgis-qgs8x8.png b/debian/icons/qgis-qgs8x8.png similarity index 100% rename from debian/qgis-qgs8x8.png rename to debian/icons/qgis-qgs8x8.png diff --git a/debian/qgis-qgs96x96.png b/debian/icons/qgis-qgs96x96.png similarity index 100% rename from debian/qgis-qgs96x96.png rename to debian/icons/qgis-qgs96x96.png diff --git a/debian/qgis-qlr128x128.png b/debian/icons/qgis-qlr128x128.png similarity index 100% rename from debian/qgis-qlr128x128.png rename to debian/icons/qgis-qlr128x128.png diff --git a/debian/qgis-qlr16x16.png b/debian/icons/qgis-qlr16x16.png similarity index 100% rename from debian/qgis-qlr16x16.png rename to debian/icons/qgis-qlr16x16.png diff --git a/debian/qgis-qlr192x192.png b/debian/icons/qgis-qlr192x192.png similarity index 100% rename from debian/qgis-qlr192x192.png rename to debian/icons/qgis-qlr192x192.png diff --git a/debian/qgis-qlr22x22.png b/debian/icons/qgis-qlr22x22.png similarity index 100% rename from debian/qgis-qlr22x22.png rename to debian/icons/qgis-qlr22x22.png diff --git a/debian/qgis-qlr24x24.png b/debian/icons/qgis-qlr24x24.png similarity index 100% rename from debian/qgis-qlr24x24.png rename to debian/icons/qgis-qlr24x24.png diff --git a/debian/qgis-qlr256x256.png b/debian/icons/qgis-qlr256x256.png similarity index 100% rename from debian/qgis-qlr256x256.png rename to debian/icons/qgis-qlr256x256.png diff --git a/debian/qgis-qlr32x32.png b/debian/icons/qgis-qlr32x32.png similarity index 100% rename from debian/qgis-qlr32x32.png rename to debian/icons/qgis-qlr32x32.png diff --git a/debian/qgis-qlr36x36.png b/debian/icons/qgis-qlr36x36.png similarity index 100% rename from debian/qgis-qlr36x36.png rename to debian/icons/qgis-qlr36x36.png diff --git a/debian/qgis-qlr42x42.png b/debian/icons/qgis-qlr42x42.png similarity index 100% rename from debian/qgis-qlr42x42.png rename to debian/icons/qgis-qlr42x42.png diff --git a/debian/qgis-qlr48x48.png b/debian/icons/qgis-qlr48x48.png similarity index 100% rename from debian/qgis-qlr48x48.png rename to debian/icons/qgis-qlr48x48.png diff --git a/debian/qgis-qlr512x512.png b/debian/icons/qgis-qlr512x512.png similarity index 100% rename from debian/qgis-qlr512x512.png rename to debian/icons/qgis-qlr512x512.png diff --git a/debian/qgis-qlr64x64.png b/debian/icons/qgis-qlr64x64.png similarity index 100% rename from debian/qgis-qlr64x64.png rename to debian/icons/qgis-qlr64x64.png diff --git a/debian/qgis-qlr72x72.png b/debian/icons/qgis-qlr72x72.png similarity index 100% rename from debian/qgis-qlr72x72.png rename to debian/icons/qgis-qlr72x72.png diff --git a/debian/qgis-qlr80x80.png b/debian/icons/qgis-qlr80x80.png similarity index 100% rename from debian/qgis-qlr80x80.png rename to debian/icons/qgis-qlr80x80.png diff --git a/debian/qgis-qlr8x8.png b/debian/icons/qgis-qlr8x8.png similarity index 100% rename from debian/qgis-qlr8x8.png rename to debian/icons/qgis-qlr8x8.png diff --git a/debian/qgis-qlr96x96.png b/debian/icons/qgis-qlr96x96.png similarity index 100% rename from debian/qgis-qlr96x96.png rename to debian/icons/qgis-qlr96x96.png diff --git a/debian/qgis-qml128x128.png b/debian/icons/qgis-qml128x128.png similarity index 100% rename from debian/qgis-qml128x128.png rename to debian/icons/qgis-qml128x128.png diff --git a/debian/qgis-qml16x16.png b/debian/icons/qgis-qml16x16.png similarity index 100% rename from debian/qgis-qml16x16.png rename to debian/icons/qgis-qml16x16.png diff --git a/debian/qgis-qml192x192.png b/debian/icons/qgis-qml192x192.png similarity index 100% rename from debian/qgis-qml192x192.png rename to debian/icons/qgis-qml192x192.png diff --git a/debian/qgis-qml22x22.png b/debian/icons/qgis-qml22x22.png similarity index 100% rename from debian/qgis-qml22x22.png rename to debian/icons/qgis-qml22x22.png diff --git a/debian/qgis-qml24x24.png b/debian/icons/qgis-qml24x24.png similarity index 100% rename from debian/qgis-qml24x24.png rename to debian/icons/qgis-qml24x24.png diff --git a/debian/qgis-qml256x256.png b/debian/icons/qgis-qml256x256.png similarity index 100% rename from debian/qgis-qml256x256.png rename to debian/icons/qgis-qml256x256.png diff --git a/debian/qgis-qml32x32.png b/debian/icons/qgis-qml32x32.png similarity index 100% rename from debian/qgis-qml32x32.png rename to debian/icons/qgis-qml32x32.png diff --git a/debian/qgis-qml36x36.png b/debian/icons/qgis-qml36x36.png similarity index 100% rename from debian/qgis-qml36x36.png rename to debian/icons/qgis-qml36x36.png diff --git a/debian/qgis-qml42x42.png b/debian/icons/qgis-qml42x42.png similarity index 100% rename from debian/qgis-qml42x42.png rename to debian/icons/qgis-qml42x42.png diff --git a/debian/qgis-qml48x48.png b/debian/icons/qgis-qml48x48.png similarity index 100% rename from debian/qgis-qml48x48.png rename to debian/icons/qgis-qml48x48.png diff --git a/debian/qgis-qml512x512.png b/debian/icons/qgis-qml512x512.png similarity index 100% rename from debian/qgis-qml512x512.png rename to debian/icons/qgis-qml512x512.png diff --git a/debian/qgis-qml64x64.png b/debian/icons/qgis-qml64x64.png similarity index 100% rename from debian/qgis-qml64x64.png rename to debian/icons/qgis-qml64x64.png diff --git a/debian/qgis-qml72x72.png b/debian/icons/qgis-qml72x72.png similarity index 100% rename from debian/qgis-qml72x72.png rename to debian/icons/qgis-qml72x72.png diff --git a/debian/qgis-qml80x80.png b/debian/icons/qgis-qml80x80.png similarity index 100% rename from debian/qgis-qml80x80.png rename to debian/icons/qgis-qml80x80.png diff --git a/debian/qgis-qml8x8.png b/debian/icons/qgis-qml8x8.png similarity index 100% rename from debian/qgis-qml8x8.png rename to debian/icons/qgis-qml8x8.png diff --git a/debian/qgis-qml96x96.png b/debian/icons/qgis-qml96x96.png similarity index 100% rename from debian/qgis-qml96x96.png rename to debian/icons/qgis-qml96x96.png diff --git a/debian/qgis-qpt128x128.png b/debian/icons/qgis-qpt128x128.png similarity index 100% rename from debian/qgis-qpt128x128.png rename to debian/icons/qgis-qpt128x128.png diff --git a/debian/qgis-qpt16x16.png b/debian/icons/qgis-qpt16x16.png similarity index 100% rename from debian/qgis-qpt16x16.png rename to debian/icons/qgis-qpt16x16.png diff --git a/debian/qgis-qpt192x192.png b/debian/icons/qgis-qpt192x192.png similarity index 100% rename from debian/qgis-qpt192x192.png rename to debian/icons/qgis-qpt192x192.png diff --git a/debian/qgis-qpt22x22.png b/debian/icons/qgis-qpt22x22.png similarity index 100% rename from debian/qgis-qpt22x22.png rename to debian/icons/qgis-qpt22x22.png diff --git a/debian/qgis-qpt24x24.png b/debian/icons/qgis-qpt24x24.png similarity index 100% rename from debian/qgis-qpt24x24.png rename to debian/icons/qgis-qpt24x24.png diff --git a/debian/qgis-qpt256x256.png b/debian/icons/qgis-qpt256x256.png similarity index 100% rename from debian/qgis-qpt256x256.png rename to debian/icons/qgis-qpt256x256.png diff --git a/debian/qgis-qpt32x32.png b/debian/icons/qgis-qpt32x32.png similarity index 100% rename from debian/qgis-qpt32x32.png rename to debian/icons/qgis-qpt32x32.png diff --git a/debian/qgis-qpt36x36.png b/debian/icons/qgis-qpt36x36.png similarity index 100% rename from debian/qgis-qpt36x36.png rename to debian/icons/qgis-qpt36x36.png diff --git a/debian/qgis-qpt42x42.png b/debian/icons/qgis-qpt42x42.png similarity index 100% rename from debian/qgis-qpt42x42.png rename to debian/icons/qgis-qpt42x42.png diff --git a/debian/qgis-qpt48x48.png b/debian/icons/qgis-qpt48x48.png similarity index 100% rename from debian/qgis-qpt48x48.png rename to debian/icons/qgis-qpt48x48.png diff --git a/debian/qgis-qpt512x512.png b/debian/icons/qgis-qpt512x512.png similarity index 100% rename from debian/qgis-qpt512x512.png rename to debian/icons/qgis-qpt512x512.png diff --git a/debian/qgis-qpt64x64.png b/debian/icons/qgis-qpt64x64.png similarity index 100% rename from debian/qgis-qpt64x64.png rename to debian/icons/qgis-qpt64x64.png diff --git a/debian/qgis-qpt72x72.png b/debian/icons/qgis-qpt72x72.png similarity index 100% rename from debian/qgis-qpt72x72.png rename to debian/icons/qgis-qpt72x72.png diff --git a/debian/qgis-qpt80x80.png b/debian/icons/qgis-qpt80x80.png similarity index 100% rename from debian/qgis-qpt80x80.png rename to debian/icons/qgis-qpt80x80.png diff --git a/debian/qgis-qpt8x8.png b/debian/icons/qgis-qpt8x8.png similarity index 100% rename from debian/qgis-qpt8x8.png rename to debian/icons/qgis-qpt8x8.png diff --git a/debian/qgis-qpt96x96.png b/debian/icons/qgis-qpt96x96.png similarity index 100% rename from debian/qgis-qpt96x96.png rename to debian/icons/qgis-qpt96x96.png diff --git a/debian/rules b/debian/rules index 0a2da33b40b3..88f229a85183 100755 --- a/debian/rules +++ b/debian/rules @@ -311,7 +311,7 @@ override_dh_auto_install: # Install MIME type icon for size in 8x8 16x16 22x22 24x24 32x32 36x36 42x42 48x48 64x64 72x72 80x80 96x96 128x128; do \ install -o root -g root -d $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/mimetypes ; \ - install -o root -g root -m 644 $(CURDIR)/debian/qgis-mime-icon$${size}.png $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/mimetypes/qgis-mime.png ; \ + install -o root -g root -m 644 $(CURDIR)/debian/icons/qgis-mime-icon$${size}.png $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/mimetypes/qgis-mime.png ; \ done # Install QGIS file formats icons @@ -319,7 +319,7 @@ override_dh_auto_install: for size in 8x8 16x16 22x22 24x24 32x32 36x36 42x42 48x48 64x64 72x72 80x80 96x96 128x128 192x192 256x256 512x512; do \ install -o root -g root -d $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/mimetypes ; \ install -o root -g root -m 644 \ - $(CURDIR)/debian/qgis-$${file_type}$${size}.png \ + $(CURDIR)/debian/icons/qgis-$${file_type}$${size}.png \ $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/mimetypes/qgis-$${file_type}.png ; \ done ; \ done @@ -327,8 +327,8 @@ override_dh_auto_install: # Install application icon for size in 8x8 16x16 22x22 24x24 32x32 36x36 42x42 48x48 64x64 72x72 80x80 96x96 128x128 192x192 256x256 512x512; do \ install -o root -g root -d $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/apps ; \ - install -o root -g root -m 644 $(CURDIR)/debian/qgis-icon$${size}.png $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/apps/qgis.png ; \ - install -o root -g root -m 644 $(CURDIR)/debian/qbrowser-icon$${size}.png $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/apps/qbrowser.png ; \ + install -o root -g root -m 644 $(CURDIR)/debian/icons/qgis-icon$${size}.png $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/apps/qgis.png ; \ + install -o root -g root -m 644 $(CURDIR)/debian/icons/qbrowser-icon$${size}.png $(CURDIR)/debian/tmp/usr/share/icons/hicolor/$${size}/apps/qbrowser.png ; \ done install -o root -g root -d $(CURDIR)/debian/tmp/usr/share/icons/hicolor/scalable/apps From 378e848c28a012d40fb823eebced291ac71c42f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 16:12:54 +0200 Subject: [PATCH 015/897] Renew test result --- .../expected/polys_split_with_lines.gfs | 14 +++++-- .../expected/polys_split_with_lines.gml | 38 +++++++++++-------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs index 3c0084954b0f..a477b60cc5b8 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs @@ -1,17 +1,23 @@ - polygons_split_with_lines - polygons_split_with_lines + polys_split_with_lines + polys_split_with_lines 3 - EPSG:4326 + GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]] - 6 + 7 -1.00000 10.00000 -3.00000 6.00000 + + fid + fid + String + 7 + name name diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml index 88e8941cf772..24aaec68b7ca 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml @@ -12,48 +12,54 @@ - + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 aaaaa 33 - 44.12346 - + 44.123456 + - + 5,5 6,4 4,4 5,5 Aaaaa -33 - 0.00000 - + 0 + - + 2,5 2,6 3,6 3,5 2,5 bbaaa - 0.12300 - + 0.123 + - + 6,-3 7,-2 9,-2 9,0 10,1 10,-3 6,-3 ASDF 0 - + - + 7,-2 6,-3 6,1 10,1 9,0 7,0 7,-2 ASDF 0 - + - + + 120 + -100291.43213 + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 elim 2 - 3.33000 - + 3.33 + From 36e276f993d5620740d23941ab58aea8d549c6b5 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 15 Aug 2016 12:04:17 +1000 Subject: [PATCH 016/897] [FEATURE] Point cluster renderer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Groups nearby points into a single rendered marker symbol. QgsPointDisplacementRenderer has been split into a new pure virtual QgsPointDistanceRenderer base class which handles the detection of clusters and grouping of points. The new cluster renderer reuses this base class to avoid code duplication. Additionally, some improvements have been made to the displacement renderer, specifically: - points are now assigned to the group which is "nearest" them, rather then just assigning them first group within the search distance. In some cases this was assigning features to a more distant cluster, resulting in less predictable cluster patterns - individual points are now correctly shown in their own selection state Lots of code cleanup + documentation too. Sponsored by: - Andreas Neumann - Qtibia Engineering (Tudor Barascu) - Karl-Magnus Jönsson - Geonesia (Nicolas Ponzo) - Plus numerous additional anonymous backers whose generous contributions are also highly valued! --- doc/api_break.dox | 6 + python/core/core.sip | 2 + .../symbology-ng/qgspointclusterrenderer.sip | 45 ++ .../qgspointdisplacementrenderer.sip | 173 +++---- .../symbology-ng/qgspointdistancerenderer.sip | 197 ++++++++ python/core/symbology-ng/qgsrenderer.sip | 2 + src/core/CMakeLists.txt | 4 + .../qgscategorizedsymbolrenderer.cpp | 8 +- .../qgsgraduatedsymbolrenderer.cpp | 8 +- .../symbology-ng/qgspointclusterrenderer.cpp | 203 ++++++++ .../symbology-ng/qgspointclusterrenderer.h | 67 +++ .../qgspointdisplacementrenderer.cpp | 450 ++---------------- .../qgspointdisplacementrenderer.h | 238 +++------ .../symbology-ng/qgspointdistancerenderer.cpp | 411 ++++++++++++++++ .../symbology-ng/qgspointdistancerenderer.h | 280 +++++++++++ src/core/symbology-ng/qgsrendererregistry.cpp | 8 + .../symbology-ng/qgsrulebasedrenderer.cpp | 8 +- .../symbology-ng/qgssinglesymbolrenderer.cpp | 8 +- src/gui/CMakeLists.txt | 2 + .../qgspointclusterrendererwidget.cpp | 231 +++++++++ .../qgspointclusterrendererwidget.h | 56 +++ .../qgspointdisplacementrendererwidget.cpp | 2 +- .../qgsrendererpropertiesdialog.cpp | 2 + .../qgspointdisplacementrendererwidgetbase.ui | 25 +- .../qgspointclusterrendererwidgetbase.ui | 125 +++++ 25 files changed, 1826 insertions(+), 735 deletions(-) create mode 100644 python/core/symbology-ng/qgspointclusterrenderer.sip create mode 100644 python/core/symbology-ng/qgspointdistancerenderer.sip create mode 100644 src/core/symbology-ng/qgspointclusterrenderer.cpp create mode 100644 src/core/symbology-ng/qgspointclusterrenderer.h create mode 100644 src/core/symbology-ng/qgspointdistancerenderer.cpp create mode 100644 src/core/symbology-ng/qgspointdistancerenderer.h create mode 100644 src/gui/symbology-ng/qgspointclusterrendererwidget.cpp create mode 100644 src/gui/symbology-ng/qgspointclusterrendererwidget.h create mode 100644 src/ui/symbollayer/qgspointclusterrendererwidgetbase.ui diff --git a/doc/api_break.dox b/doc/api_break.dox index 503f4d391c67..49608af1ff1a 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1084,6 +1084,12 @@ be used instead of a null pointer if no transformation is required.
  • createMapRenderer(): default implementation (which called plugin's draw() method) has been removed. Plugin layers must implement createMapRenderer().
  • +\subsection qgis_api_break_3_0_QgsPointDisplacementRenderer QgsPointDisplacementRenderer + +
      +
    • The deprecated method setDisplacementGroups() has been removed. This method has had no effect since QGIS 2.4
    • +
    + \subsection qgis_api_break_3_0_QgsPointLocator QgsPointLocator
      diff --git a/python/core/core.sip b/python/core/core.sip index 0479d51b1682..f7f9a1215a06 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -294,7 +294,9 @@ %Include symbology-ng/qgsinvertedpolygonrenderer.sip %Include symbology-ng/qgslegendsymbolitem.sip %Include symbology-ng/qgsnullsymbolrenderer.sip +%Include symbology-ng/qgspointclusterrenderer.sip %Include symbology-ng/qgspointdisplacementrenderer.sip +%Include symbology-ng/qgspointdistancerenderer.sip %Include symbology-ng/qgsrenderer.sip %Include symbology-ng/qgsrendererregistry.sip %Include symbology-ng/qgsrulebasedrenderer.sip diff --git a/python/core/symbology-ng/qgspointclusterrenderer.sip b/python/core/symbology-ng/qgspointclusterrenderer.sip new file mode 100644 index 000000000000..8a645063d643 --- /dev/null +++ b/python/core/symbology-ng/qgspointclusterrenderer.sip @@ -0,0 +1,45 @@ +/** \class QgsPointClusterRenderer + * \ingroup core + * A renderer that automatically clusters points with the same geographic position. + * \note added in QGIS 3.0 +*/ +class QgsPointClusterRenderer : QgsPointDistanceRenderer +{ +%TypeHeaderCode +#include +%End + public: + + QgsPointClusterRenderer(); + + virtual QgsPointClusterRenderer* clone() const /Factory/; + virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); + void stopRender( QgsRenderContext& context ); + QDomElement save( QDomDocument& doc ); + + //! Create a renderer from XML element + static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; + + /** Returns the symbol used for rendering clustered groups (but not ownership of the symbol). + * @see setClusterSymbol() + */ + QgsMarkerSymbol* clusterSymbol(); + + /** Sets the symbol for rendering clustered groups. + * @param symbol new cluster symbol. Ownership is transferred to the renderer. + * @see clusterSymbol() + */ + void setClusterSymbol( QgsMarkerSymbol* symbol /Transfer/ ); + + /** Creates a QgsPointDisplacementRenderer from an existing renderer. + * @note added in 2.5 + * @returns a new renderer if the conversion was possible, otherwise nullptr. + */ + static QgsPointClusterRenderer* convertFromRenderer( const QgsFeatureRenderer *renderer ) /Factory/; + + private: + QgsPointClusterRenderer( const QgsPointClusterRenderer & ); + QgsPointClusterRenderer & operator=( const QgsPointClusterRenderer & ); + + void drawGroup( QPointF centerPoint, QgsRenderContext& context, const QgsPointDistanceRenderer::ClusteredGroup& group ); +}; diff --git a/python/core/symbology-ng/qgspointdisplacementrenderer.sip b/python/core/symbology-ng/qgspointdisplacementrenderer.sip index d179ca1a61bc..6a458901135c 100644 --- a/python/core/symbology-ng/qgspointdisplacementrenderer.sip +++ b/python/core/symbology-ng/qgspointdisplacementrenderer.sip @@ -1,4 +1,8 @@ -class QgsPointDisplacementRenderer : QgsFeatureRenderer +/** \class QgsPointDisplacementRenderer + * \ingroup core + * A renderer that automatically displaces points with the same geographic location. +*/ +class QgsPointDisplacementRenderer : QgsPointDistanceRenderer { %TypeHeaderCode #include @@ -13,88 +17,56 @@ class QgsPointDisplacementRenderer : QgsFeatureRenderer ConcentricRings /*!< Place points in concentric rings around group*/ }; - QgsPointDisplacementRenderer( const QString& labelAttributeName = "" ); - ~QgsPointDisplacementRenderer(); - - virtual QgsPointDisplacementRenderer* clone() const /Factory/; - - virtual void toSld( QDomDocument& doc, QDomElement &element ) const; - - /** Reimplemented from QgsFeatureRenderer*/ - bool renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer = -1, bool selected = false, bool drawVertexMarker = false ); - - /** Partial proxy that will call this method on the embedded renderer. */ - virtual QList usedAttributes(); - /** Proxy that will call this method on the embedded renderer. */ - virtual QgsFeatureRenderer::Capabilities capabilities(); - /** Proxy that will call this method on the embedded renderer. - @note available in python as symbols2 - */ - virtual QgsSymbolList symbols( QgsRenderContext& context ); - /** Proxy that will call this method on the embedded renderer. - @note available in python as symbolForFeature2 + /** Constructor for QgsPointDisplacementRenderer. + * @param labelAttributeName optional attribute name for labeling points */ - virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ); - /** Proxy that will call this method on the embedded renderer. - @note available in python as originalSymbolForFeature2 - */ - virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ); - /** Proxy that will call this method on the embedded renderer. - @note available in python as symbolsForFeature2 - */ - virtual QgsSymbolList symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ); - /** Proxy that will call this method on the embedded renderer. - @note available in python as originalSymbolsForFeature2 - */ - virtual QgsSymbolList originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ); - /** Proxy that will call this method on the embedded renderer. - @note available in python as willRenderFeature2 - */ - virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ); + QgsPointDisplacementRenderer( const QString& labelAttributeName = QString() ); + virtual QgsPointDisplacementRenderer* clone() const /Factory/; virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); - void stopRender( QgsRenderContext& context ); - - //! create a renderer from XML element - static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; QDomElement save( QDomDocument& doc ); - QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ); - - //! @note not available in python bindings - // QgsLegendSymbolList legendSymbolItems(); - - void setLabelAttributeName( const QString& name ); - QString labelAttributeName() const; - - void setEmbeddedRenderer( QgsFeatureRenderer* r /Transfer/ ); - const QgsFeatureRenderer* embeddedRenderer() const; - - virtual void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ); - - virtual bool legendSymbolItemsCheckable() const; - virtual bool legendSymbolItemChecked( const QString& key ); - virtual void checkLegendSymbolItem( const QString& key, bool state = true ); + //! Create a renderer from XML element + static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; - void setLabelFont( const QFont& f ); - QFont labelFont() const; + /** Sets the line width for the displacement group circle. + * @param width line width in mm + * @see circleWidth() + * @see setCircleColor() + */ + void setCircleWidth( double width ); - void setCircleWidth( double w ); + /** Returns the line width for the displacement group circle in mm. + * @see setCircleWidth() + * @see circleColor() + */ double circleWidth() const; - void setCircleColor( const QColor& c ); + /** Sets the color used for drawing the displacement group circle. + * @param color circle color + * @see circleColor() + * @see setCircleWidth() + */ + void setCircleColor( const QColor& color ); + + /** Returns the color used for drawing the displacement group circle. + * @see setCircleColor() + * @see circleWidth() + */ QColor circleColor() const; - void setLabelColor( const QColor& c ); - QColor labelColor() const; + /** Sets a factor for increasing the ring size of displacement groups. + * @param distance addition factor + * @see circleRadiusAddition() + */ + void setCircleRadiusAddition( double distance ); - void setCircleRadiusAddition( double d ); + /** Returns the factor for increasing the ring size of displacement groups. + * @see setCircleRadiusAddition() + */ double circleRadiusAddition() const; - void setMaxLabelScaleDenominator( double d ); - double maxLabelScaleDenominator() const; - /** Returns the placement method used for dispersing the points. * @see setPlacement() * @note added in QGIS 2.12 @@ -108,62 +80,27 @@ class QgsPointDisplacementRenderer : QgsFeatureRenderer */ void setPlacement( Placement placement ); - /** Returns the symbol for the center of a displacement group (but _not_ ownership of the symbol)*/ + /** Returns the symbol for the center of a displacement group (but not ownership of the symbol). + * @see setCenterSymbol() + */ QgsMarkerSymbol* centerSymbol(); - /** Sets the center symbol (takes ownership)*/ - void setCenterSymbol( QgsMarkerSymbol* symbol /Transfer/ ); - - /** Sets the tolerance distance for grouping points. Units are specified using - * setToleranceUnit(). - * @param t tolerance distance - * @see tolerance() - * @see setToleranceUnit() - */ - void setTolerance( double t ); - - /** Returns the tolerance distance for grouping points. Units are retrieved using - * toleranceUnit(). - * @see setTolerance() - * @see toleranceUnit() - */ - double tolerance() const; - /** Sets the units for the tolerance distance. - * @param unit tolerance distance units - * @see setTolerance() - * @see toleranceUnit() - * @note added in QGIS 2.12 - */ - void setToleranceUnit( QgsUnitTypes::RenderUnit unit ); - - /** Returns the units for the tolerance distance. - * @see tolerance() - * @see setToleranceUnit() - * @note added in QGIS 2.12 - */ - QgsUnitTypes::RenderUnit toleranceUnit() const; - - /** Sets the map unit scale object for the distance tolerance. This is only used if the - * toleranceUnit() is set to QgsSymbol::MapUnit. - * @param scale scale for distance tolerance - * @see toleranceMapUnitScale() - * @see setToleranceUnit() - */ - void setToleranceMapUnitScale( const QgsMapUnitScale& scale ); + /** Sets the center symbol for a displacement group. + * @param symbol new center symbol. Ownership is transferred to the renderer. + * @see centerSymbol() + */ + void setCenterSymbol( QgsMarkerSymbol* symbol /Transfer/ ); - /** Returns the map unit scale object for the distance tolerance. This is only used if the - * toleranceUnit() is set to QgsSymbol::MapUnit. - * @see setToleranceMapUnitScale() - * @see toleranceUnit() + /** Creates a QgsPointDisplacementRenderer from an existing renderer. + * @note added in 2.5 + * @returns a new renderer if the conversion was possible, otherwise nullptr. */ - const QgsMapUnitScale& toleranceMapUnitScale() const; - - //! creates a QgsPointDisplacementRenderer from an existing renderer. - //! @note added in 2.5 - //! @returns a new renderer if the conversion was possible, otherwise 0. - static QgsPointDisplacementRenderer* convertFromRenderer(const QgsFeatureRenderer *renderer ) /Factory/; + static QgsPointDisplacementRenderer* convertFromRenderer( const QgsFeatureRenderer *renderer ) /Factory/; private: QgsPointDisplacementRenderer( const QgsPointDisplacementRenderer & ); QgsPointDisplacementRenderer & operator=( const QgsPointDisplacementRenderer & ); + + void drawGroup( QPointF centerPoint, QgsRenderContext& context, const QgsPointDistanceRenderer::ClusteredGroup& group ); + }; diff --git a/python/core/symbology-ng/qgspointdistancerenderer.sip b/python/core/symbology-ng/qgspointdistancerenderer.sip new file mode 100644 index 000000000000..b01693725589 --- /dev/null +++ b/python/core/symbology-ng/qgspointdistancerenderer.sip @@ -0,0 +1,197 @@ +/** \class QgsPointDistanceRenderer + * \ingroup core + * An abstract base class for distance based point renderers (eg clusterer and displacement renderers). + * QgsPointDistanceRenderer handles calculation of point clusters using a distance based threshold. + * Subclasses must implement drawGroup() to handle the rendering of individual point clusters + * in the desired style. + * \note added in QGIS 3.0 + */ + +class QgsPointDistanceRenderer : QgsFeatureRenderer +{ +%TypeHeaderCode +#include +%End + + public: + + //! Contains properties for a feature within a clustered group. + struct GroupedFeature + { + /** Constructor for GroupedFeature. + * @param feature feature + * @param symbol base symbol for rendering feature + * @param isSelected set to true if feature is selected and should be rendered in a selected state + * @param label optional label text, or empty string for no label + */ + GroupedFeature( const QgsFeature& feature, QgsMarkerSymbol* symbol, bool isSelected, const QString& label = QString() ); + + //! Feature + QgsFeature feature; + + //! Base symbol for rendering feature + QgsMarkerSymbol* symbol; + + //! True if feature is selected and should be rendered in a selected state + bool isSelected; + + //! Optional label text + QString label; + }; + + //! A group of clustered points (ie features within the distance tolerance). + typedef QList< QgsPointDistanceRenderer::GroupedFeature > ClusteredGroup; + + /** Constructor for QgsPointDistanceRenderer. + * @param rendererName name of renderer for registry + * @param labelAttributeName optional attribute for labeling points + */ + QgsPointDistanceRenderer( const QString& rendererName, const QString& labelAttributeName = QString() ); + + virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const; + bool renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer = -1, bool selected = false, bool drawVertexMarker = false ); + virtual QList usedAttributes(); + virtual Capabilities capabilities(); + virtual QgsSymbolList symbols( QgsRenderContext& context ); + virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ); + virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ); + virtual QgsSymbolList symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ); + virtual QgsSymbolList originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ); + virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ); + virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); + void stopRender( QgsRenderContext& context ); + QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ); + //QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ); + void setEmbeddedRenderer( QgsFeatureRenderer* r /Transfer/ ); + const QgsFeatureRenderer* embeddedRenderer() const; + void setLegendSymbolItem( const QString& key, QgsSymbol* symbol /Transfer/ ); + bool legendSymbolItemsCheckable() const; + bool legendSymbolItemChecked( const QString& key ); + void checkLegendSymbolItem( const QString& key, bool state ); + + /** Sets the attribute name for labeling points. + * @param name attribute name, or empty string to avoid labeling features by the renderer + * @see labelAttributeName() + * @see setLabelFont() + * @see setLabelColor() + * @see setMaxLabelScaleDenominator() + */ + void setLabelAttributeName( const QString& name ); + + /** Returns the attribute name used for labeling points, or an empty string if no labeling + * will be done by the renderer. + * @see setLabelAttributeName() + * @see labelFont() + * @see maxLabelScaleDenominator() + * @see labelColor() + */ + QString labelAttributeName() const; + + /** Sets the font used for labeling points. + * @param font label font + * @see labelFont() + * @see setLabelAttributeName() + * @see setLabelColor() + */ + void setLabelFont( const QFont& font ); + + /** Returns the font used for labeling points. + * @see setLabelFont() + * @see labelAttributeName() + * @see labelColor() + */ + QFont labelFont() const; + + /** Sets the maximum scale at which points should be labeled by the renderer. + * @param denominator maximum scale denominator + * @see maxLabelScaleDenominator() + * @see setLabelAttributeName() + */ + void setMaxLabelScaleDenominator( double denominator ); + + /** Returns the denominator for the maximum scale at which points should be labeled by the renderer. + * @see setMaxLabelScaleDenominator() + * @see labelAttributeName() + */ + double maxLabelScaleDenominator() const; + + /** Sets the color to use for for labeling points. + * @param color label color + * @see labelColor() + * @see setLabelAttributeName() + * @see setLabelFont() + */ + void setLabelColor( const QColor& color ); + + /** Returns the color used for for labeling points. + * @see setLabelColor() + * @see labelAttributeName() + * @see labelFont() + */ + QColor labelColor() const; + + /** Sets the tolerance distance for grouping points. Units are specified using + * setToleranceUnit(). + * @param distance tolerance distance + * @see tolerance() + * @see setToleranceUnit() + */ + void setTolerance( double distance ); + + /** Returns the tolerance distance for grouping points. Units are retrieved using + * toleranceUnit(). + * @see setTolerance() + * @see toleranceUnit() + */ + double tolerance() const; + + /** Sets the units for the tolerance distance. + * @param unit tolerance distance units + * @see setTolerance() + * @see toleranceUnit() + * @note added in QGIS 2.12 + */ + void setToleranceUnit( QgsUnitTypes::RenderUnit unit ); + + /** Returns the units for the tolerance distance. + * @see tolerance() + * @see setToleranceUnit() + * @note added in QGIS 2.12 + */ + QgsUnitTypes::RenderUnit toleranceUnit() const; + + /** Sets the map unit scale object for the distance tolerance. This is only used if the + * toleranceUnit() is set to QgsUnitTypes::RenderMapUnits. + * @param scale scale for distance tolerance + * @see toleranceMapUnitScale() + * @see setToleranceUnit() + */ + void setToleranceMapUnitScale( const QgsMapUnitScale& scale ); + + /** Returns the map unit scale object for the distance tolerance. This is only used if the + * toleranceUnit() is set to QgsUnitTypes::RenderMapUnits. + * @see setToleranceMapUnitScale() + * @see toleranceUnit() + */ + const QgsMapUnitScale& toleranceMapUnitScale() const; + + protected: + + /** Renders the labels for a group. + * @param centerPoint center point of group + * @param context destination render context + * @param labelShifts displacement for individual label positions + * @param group group of clustered features to label + */ + void drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const QgsPointDistanceRenderer::ClusteredGroup& group ); + + private: + + /** Draws a group of clustered points. + * @param centerPoint central point (geographic centroid) of all points contained within the cluster + * @param context destination render context + * @param group contents of group + */ + virtual void drawGroup( QPointF centerPoint, QgsRenderContext& context, const QgsPointDistanceRenderer::ClusteredGroup& group ) = 0; + +}; diff --git a/python/core/symbology-ng/qgsrenderer.sip b/python/core/symbology-ng/qgsrenderer.sip index cf7efe932183..bf0cdd6b25e4 100644 --- a/python/core/symbology-ng/qgsrenderer.sip +++ b/python/core/symbology-ng/qgsrenderer.sip @@ -46,6 +46,8 @@ class QgsFeatureRenderer sipType = sipType_QgsHeatmapRenderer; else if (sipCpp->type() == "invertedPolygonRenderer") sipType = sipType_QgsInvertedPolygonRenderer; + else if (sipCpp->type() == "pointCluster") + sipType = sipType_QgsPointClusterRenderer; else if (sipCpp->type() == "pointDisplacement") sipType = sipType_QgsPointDisplacementRenderer; else if (sipCpp->type() == "25dRenderer") diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 6fbfc39d0935..71df5008a935 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -30,7 +30,9 @@ SET(QGIS_CORE_SRCS symbology-ng/qgslinesymbollayer.cpp symbology-ng/qgsmarkersymbollayer.cpp symbology-ng/qgsnullsymbolrenderer.cpp + symbology-ng/qgspointclusterrenderer.cpp symbology-ng/qgspointdisplacementrenderer.cpp + symbology-ng/qgspointdistancerenderer.cpp symbology-ng/qgsrenderer.cpp symbology-ng/qgsrendererregistry.cpp symbology-ng/qgsrulebasedrenderer.cpp @@ -802,7 +804,9 @@ SET(QGIS_CORE_HDRS symbology-ng/qgslegendsymbolitem.h symbology-ng/qgslinesymbollayer.h symbology-ng/qgsmarkersymbollayer.h + symbology-ng/qgspointclusterrenderer.h symbology-ng/qgspointdisplacementrenderer.h + symbology-ng/qgspointdistancerenderer.h symbology-ng/qgsrenderer.h symbology-ng/qgsrendererregistry.h symbology-ng/qgsrulebasedrenderer.h diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp index 6cf7fa994f3b..3a9e2ed8062f 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp @@ -940,11 +940,11 @@ QgsCategorizedSymbolRenderer* QgsCategorizedSymbolRenderer::convertFromRenderer( { r = dynamic_cast( renderer->clone() ); } - else if ( renderer->type() == "pointDisplacement" ) + else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) { - const QgsPointDisplacementRenderer* pointDisplacementRenderer = dynamic_cast( renderer ); - if ( pointDisplacementRenderer ) - r = convertFromRenderer( pointDisplacementRenderer->embeddedRenderer() ); + const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast( renderer ); + if ( pointDistanceRenderer ) + r = convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } else if ( renderer->type() == "invertedPolygonRenderer" ) { diff --git a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp index 949b7572bfc7..d03c26ffa4bf 100644 --- a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp @@ -1614,11 +1614,11 @@ QgsGraduatedSymbolRenderer* QgsGraduatedSymbolRenderer::convertFromRenderer( con { r = dynamic_cast( renderer->clone() ); } - else if ( renderer->type() == "pointDisplacement" ) + else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) { - const QgsPointDisplacementRenderer* pointDisplacementRenderer = dynamic_cast( renderer ); - if ( pointDisplacementRenderer ) - r = convertFromRenderer( pointDisplacementRenderer->embeddedRenderer() ); + const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast( renderer ); + if ( pointDistanceRenderer ) + r = convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } else if ( renderer->type() == "invertedPolygonRenderer" ) { diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp new file mode 100644 index 000000000000..fe3d685e1313 --- /dev/null +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -0,0 +1,203 @@ +/*************************************************************************** + qgspointclusterrenderer.cpp + --------------------------- + begin : February 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgspointclusterrenderer.h" +#include "qgssymbollayerutils.h" +#include "qgspainteffectregistry.h" +#include "qgspainteffect.h" +#include + +#ifndef M_SQRT2 +#define M_SQRT2 1.41421356237309504880 +#endif + +QgsPointClusterRenderer::QgsPointClusterRenderer() + : QgsPointDistanceRenderer( "pointCluster" ) +{ + mClusterSymbol.reset( new QgsMarkerSymbol() ); +} + +QgsPointClusterRenderer* QgsPointClusterRenderer::clone() const +{ + QgsPointClusterRenderer* r = new QgsPointClusterRenderer(); + if ( mRenderer ) + r->setEmbeddedRenderer( mRenderer->clone() ); + r->setLabelFont( mLabelFont ); + r->setLabelColor( mLabelColor ); + r->setMaxLabelScaleDenominator( mMaxLabelScaleDenominator ); + r->setTolerance( mTolerance ); + r->setToleranceUnit( mToleranceUnit ); + r->setToleranceMapUnitScale( mToleranceMapUnitScale ); + if ( mClusterSymbol ) + { + r->setClusterSymbol( mClusterSymbol->clone() ); + } + copyRendererData( r ); + return r; +} + +void QgsPointClusterRenderer::drawGroup( QPointF centerPoint, QgsRenderContext& context, const ClusteredGroup& group ) +{ + if ( group.size() > 1 ) + { + //scan through symbols to check color, eg if all clustered symbols are same color + QColor groupColor; + ClusteredGroup::const_iterator groupIt = group.constBegin(); + for ( ; groupIt != group.constEnd(); ++groupIt ) + { + if ( !groupIt->symbol ) + continue; + + if ( !groupColor.isValid() ) + { + groupColor = groupIt->symbol->color(); + } + else + { + if ( groupColor != groupIt->symbol->color() ) + { + groupColor = QColor(); + break; + } + } + } + + if ( groupColor.isValid() ) + { + context.expressionContext().lastScope()->setVariable( "cluster_color", QgsSymbolLayerUtils::encodeColor( groupColor ) ); + } + else + { + //mixed colors + context.expressionContext().lastScope()->setVariable( "cluster_color", "" ); + } + + //multiple clustered symbols, so draw just the cluster symbol + context.expressionContext().lastScope()->setVariable( "cluster_size", group.size() ); + mClusterSymbol->renderPoint( centerPoint, &( group.at( 0 ).feature ), context, -1, false ); + } + else + { + //single isolated symbol, draw it untouched + QgsMarkerSymbol* symbol = group.at( 0 ).symbol; + symbol->renderPoint( centerPoint, &( group.at( 0 ).feature ), context, -1, group.at( 0 ).isSelected ); + } +} + +void QgsPointClusterRenderer::startRender( QgsRenderContext& context, const QgsFields& fields ) +{ + if ( mClusterSymbol ) + { + mClusterSymbol->startRender( context, fields ); + } + QgsPointDistanceRenderer::startRender( context, fields ); +} + +void QgsPointClusterRenderer::stopRender( QgsRenderContext& context ) +{ + QgsPointDistanceRenderer::stopRender( context ); + if ( mClusterSymbol ) + { + mClusterSymbol->stopRender( context ); + } +} + +QgsFeatureRenderer* QgsPointClusterRenderer::create( QDomElement& symbologyElem ) +{ + QgsPointClusterRenderer* r = new QgsPointClusterRenderer(); + r->setTolerance( symbologyElem.attribute( "tolerance", "0.00001" ).toDouble() ); + r->setToleranceUnit( QgsUnitTypes::decodeRenderUnit( symbologyElem.attribute( "toleranceUnit", "MapUnit" ) ) ); + r->setToleranceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( symbologyElem.attribute( "toleranceUnitScale" ) ) ); + + //look for an embedded renderer + QDomElement embeddedRendererElem = symbologyElem.firstChildElement( "renderer-v2" ); + if ( !embeddedRendererElem.isNull() ) + { + r->setEmbeddedRenderer( QgsFeatureRenderer::load( embeddedRendererElem ) ); + } + + //center symbol + QDomElement centerSymbolElem = symbologyElem.firstChildElement( "symbol" ); + if ( !centerSymbolElem.isNull() ) + { + r->setClusterSymbol( QgsSymbolLayerUtils::loadSymbol( centerSymbolElem ) ); + } + return r; +} + +QgsMarkerSymbol* QgsPointClusterRenderer::clusterSymbol() +{ + return mClusterSymbol.data(); +} + +QDomElement QgsPointClusterRenderer::save( QDomDocument& doc ) +{ + QDomElement rendererElement = doc.createElement( RENDERER_TAG_NAME ); + rendererElement.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); + rendererElement.setAttribute( "type", "pointCluster" ); + rendererElement.setAttribute( "tolerance", QString::number( mTolerance ) ); + rendererElement.setAttribute( "toleranceUnit", QgsUnitTypes::encodeUnit( mToleranceUnit ) ); + rendererElement.setAttribute( "toleranceUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( mToleranceMapUnitScale ) ); + + if ( mRenderer ) + { + QDomElement embeddedRendererElem = mRenderer->save( doc ); + rendererElement.appendChild( embeddedRendererElem ); + } + if ( mClusterSymbol ) + { + QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( "centerSymbol", mClusterSymbol.data(), doc ); + rendererElement.appendChild( centerSymbolElem ); + } + + if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) + mPaintEffect->saveProperties( doc, rendererElement ); + + if ( !mOrderBy.isEmpty() ) + { + QDomElement orderBy = doc.createElement( "orderby" ); + mOrderBy.save( orderBy ); + rendererElement.appendChild( orderBy ); + } + rendererElement.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + + return rendererElement; +} + +void QgsPointClusterRenderer::setClusterSymbol( QgsMarkerSymbol* symbol ) +{ + mClusterSymbol.reset( symbol ); +} + +QgsPointClusterRenderer* QgsPointClusterRenderer::convertFromRenderer( const QgsFeatureRenderer* renderer ) +{ + if ( renderer->type() == "pointCluster" ) + { + return dynamic_cast( renderer->clone() ); + } + + if ( renderer->type() == "singleSymbol" || + renderer->type() == "categorizedSymbol" || + renderer->type() == "graduatedSymbol" || + renderer->type() == "RuleRenderer" ) + { + QgsPointClusterRenderer* pointRenderer = new QgsPointClusterRenderer(); + pointRenderer->setEmbeddedRenderer( renderer->clone() ); + return pointRenderer; + } + return nullptr; +} diff --git a/src/core/symbology-ng/qgspointclusterrenderer.h b/src/core/symbology-ng/qgspointclusterrenderer.h new file mode 100644 index 000000000000..e188db0f9893 --- /dev/null +++ b/src/core/symbology-ng/qgspointclusterrenderer.h @@ -0,0 +1,67 @@ +/*************************************************************************** + qgspointclusterrenderer.h + ------------------------- + begin : February 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSPOINTCLUSTERRENDERER_H +#define QGSPOINTCLUSTERRENDERER_H + +#include "qgspointdistancerenderer.h" + +/** \class QgsPointClusterRenderer + * \ingroup core + * A renderer that automatically clusters points with the same geographic position. + * \note added in QGIS 3.0 +*/ +class CORE_EXPORT QgsPointClusterRenderer: public QgsPointDistanceRenderer +{ + public: + + QgsPointClusterRenderer(); + + QgsPointClusterRenderer* clone() const override; + virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; + void stopRender( QgsRenderContext& context ) override; + QDomElement save( QDomDocument& doc ) override; + + //! Creates a renderer from XML element + static QgsFeatureRenderer* create( QDomElement& symbologyElem ); + + /** Returns the symbol used for rendering clustered groups (but not ownership of the symbol). + * @see setClusterSymbol() + */ + QgsMarkerSymbol* clusterSymbol(); + + /** Sets the symbol for rendering clustered groups. + * @param symbol new cluster symbol. Ownership is transferred to the renderer. + * @see clusterSymbol() + */ + void setClusterSymbol( QgsMarkerSymbol* symbol ); + + /** Creates a QgsPointClusterRenderer from an existing renderer. + * @returns a new renderer if the conversion was possible, otherwise nullptr. + */ + static QgsPointClusterRenderer* convertFromRenderer( const QgsFeatureRenderer* renderer ); + + private: + + //! Symbol for point clusters + QScopedPointer< QgsMarkerSymbol > mClusterSymbol; + + void drawGroup( QPointF centerPoint, QgsRenderContext& context, const QgsPointDistanceRenderer::ClusteredGroup& group ) override; + +}; + +#endif // QGSPOINTCLUSTERRENDERER_H diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index a1f07596f894..df2ed204cf0b 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -16,24 +16,12 @@ ***************************************************************************/ #include "qgspointdisplacementrenderer.h" -#include "qgsgeometry.h" -#include "qgslogger.h" -#include "qgsspatialindex.h" -#include "qgssymbol.h" #include "qgssymbollayerutils.h" -#include "qgsvectorlayer.h" -#include "qgssinglesymbolrenderer.h" -#include "qgspainteffect.h" -#include "qgspainteffectregistry.h" #include "qgsfontutils.h" -#include "qgsmultipoint.h" -#include "qgspointv2.h" -#include "qgsunittypes.h" -#include "qgswkbptr.h" +#include "qgspainteffectregistry.h" +#include "qgspainteffect.h" -#include #include - #include #ifndef M_SQRT2 @@ -41,27 +29,13 @@ #endif QgsPointDisplacementRenderer::QgsPointDisplacementRenderer( const QString& labelAttributeName ) - : QgsFeatureRenderer( "pointDisplacement" ) - , mLabelAttributeName( labelAttributeName ) - , mLabelIndex( -1 ) - , mTolerance( 3 ) - , mToleranceUnit( QgsUnitTypes::RenderMillimeters ) + : QgsPointDistanceRenderer( "pointDisplacement", labelAttributeName ) , mPlacement( Ring ) , mCircleWidth( 0.4 ) , mCircleColor( QColor( 125, 125, 125 ) ) , mCircleRadiusAddition( 0 ) - , mMaxLabelScaleDenominator( -1 ) - , mSpatialIndex( nullptr ) -{ - mRenderer = QgsFeatureRenderer::defaultRenderer( QgsWkbTypes::PointGeometry ); - mCenterSymbol = new QgsMarkerSymbol(); //the symbol for the center of a displacement group - mDrawLabels = true; -} - -QgsPointDisplacementRenderer::~QgsPointDisplacementRenderer() { - delete mCenterSymbol; - delete mRenderer; + mCenterSymbol.reset( new QgsMarkerSymbol() ); } QgsPointDisplacementRenderer* QgsPointDisplacementRenderer::clone() const @@ -87,98 +61,14 @@ QgsPointDisplacementRenderer* QgsPointDisplacementRenderer::clone() const return r; } -void QgsPointDisplacementRenderer::toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props ) const -{ - mRenderer->toSld( doc, element, props ); -} - - -bool QgsPointDisplacementRenderer::renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer, bool selected, bool drawVertexMarker ) -{ - Q_UNUSED( drawVertexMarker ); - Q_UNUSED( context ); - Q_UNUSED( layer ); - - //check, if there is already a point at that position - if ( !feature.hasGeometry() ) - return false; - - QgsSymbol* symbol = firstSymbolForFeature( mRenderer, feature, context ); - - //if the feature has no symbol (eg, no matching rule in a rule-based renderer), skip it - if ( !symbol ) - return false; - - //point position in screen coords - QgsGeometry geom = feature.geometry(); - QgsWkbTypes::Type geomType = geom.wkbType(); - if ( QgsWkbTypes::flatType( geomType ) != QgsWkbTypes::Point ) - { - //can only render point type - return false; - } - - if ( selected ) - mSelectedFeatures.insert( feature.id() ); - - double searchDistance = mTolerance * QgsSymbolLayerUtils::mapUnitScaleFactor( context, mToleranceUnit, mToleranceMapUnitScale ); - QList intersectList = mSpatialIndex->intersects( searchRect( feature.geometry().asPoint(), searchDistance ) ); - if ( intersectList.empty() ) - { - mSpatialIndex->insertFeature( feature ); - // create new group - DisplacementGroup newGroup; - newGroup.insert( feature.id(), qMakePair( feature, symbol ) ); - mDisplacementGroups.push_back( newGroup ); - // add to group index - mGroupIndex.insert( feature.id(), mDisplacementGroups.count() - 1 ); - return true; - } - - //go through all the displacement group maps and search an entry where the id equals the result of the spatial search - QgsFeatureId existingEntry = intersectList.at( 0 ); - - int groupIdx = mGroupIndex[ existingEntry ]; - DisplacementGroup& group = mDisplacementGroups[groupIdx]; - - // add to a group - group.insert( feature.id(), qMakePair( feature, symbol ) ); - // add to group index - mGroupIndex.insert( feature.id(), groupIdx ); - return true; -} - -void QgsPointDisplacementRenderer::drawGroup( const DisplacementGroup& group, QgsRenderContext& context ) +void QgsPointDisplacementRenderer::drawGroup( QPointF centerPoint, QgsRenderContext& context, const ClusteredGroup& group ) { - const QgsFeature& feature = group.begin().value().first; - bool selected = mSelectedFeatures.contains( feature.id() ); // maybe we should highlight individual features instead of the whole group? - - - - //get list of labels and symbols - QStringList labelAttributeList; - QList< QgsMarkerSymbol* > symbolList; - QgsFeatureList featureList; - - QgsMultiPointV2* groupMultiPoint = new QgsMultiPointV2(); - for ( DisplacementGroup::const_iterator attIt = group.constBegin(); attIt != group.constEnd(); ++attIt ) - { - labelAttributeList << ( mDrawLabels ? getLabel( attIt.value().first ) : QString() ); - symbolList << dynamic_cast( attIt.value().second ); - featureList << attIt.value().first; - groupMultiPoint->addGeometry( attIt.value().first.geometry().geometry()->clone() ); - } - - //calculate centroid of all points, this will be center of group - QgsGeometry groupGeom( groupMultiPoint ); - QgsGeometry centroid = groupGeom.centroid(); - QPointF pt = _getPoint( context, *static_cast( centroid.geometry() ) ); - //calculate max diagonal size from all symbols in group double diagonal = 0; - Q_FOREACH ( QgsMarkerSymbol* symbol, symbolList ) + + Q_FOREACH ( const GroupedFeature& feature, group ) { - if ( symbol ) + if ( QgsMarkerSymbol* symbol = feature.symbol ) { diagonal = qMax( diagonal, QgsSymbolLayerUtils::convertToPainterUnits( context, M_SQRT2 * symbol->size(), @@ -186,205 +76,51 @@ void QgsPointDisplacementRenderer::drawGroup( const DisplacementGroup& group, Qg } } - QgsSymbolRenderContext symbolContext( context, QgsUnitTypes::RenderMillimeters, 1.0, selected ); + QgsSymbolRenderContext symbolContext( context, QgsUnitTypes::RenderMillimeters, 1.0, false ); QList symbolPositions; QList labelPositions; double circleRadius = -1.0; - calculateSymbolAndLabelPositions( symbolContext, pt, symbolList.size(), diagonal, symbolPositions, labelPositions, circleRadius ); + calculateSymbolAndLabelPositions( symbolContext, centerPoint, group.size(), diagonal, symbolPositions, labelPositions, circleRadius ); - //draw Circle + //draw circle if ( circleRadius > 0 ) - drawCircle( circleRadius, symbolContext, pt, symbolList.size() ); + drawCircle( circleRadius, symbolContext, centerPoint, group.size() ); //draw mid point - if ( labelAttributeList.size() > 1 ) + if ( group.size() > 1 ) { + QgsFeature firstFeature = group.at( 0 ).feature; if ( mCenterSymbol ) { - mCenterSymbol->renderPoint( pt, &feature, context, -1, selected ); + mCenterSymbol->renderPoint( centerPoint, &firstFeature, context, -1, false ); } else { - context.painter()->drawRect( QRectF( pt.x() - symbolContext.outputLineWidth( 1 ), pt.y() - symbolContext.outputLineWidth( 1 ), symbolContext.outputLineWidth( 2 ), symbolContext.outputLineWidth( 2 ) ) ); + context.painter()->drawRect( QRectF( centerPoint.x() - symbolContext.outputLineWidth( 1 ), centerPoint.y() - symbolContext.outputLineWidth( 1 ), symbolContext.outputLineWidth( 2 ), symbolContext.outputLineWidth( 2 ) ) ); } } //draw symbols on the circle - drawSymbols( featureList, context, symbolList, symbolPositions, selected ); + drawSymbols( group, context, symbolPositions ); //and also the labels - drawLabels( pt, symbolContext, labelPositions, labelAttributeList ); -} - -void QgsPointDisplacementRenderer::setEmbeddedRenderer( QgsFeatureRenderer* r ) -{ - delete mRenderer; - mRenderer = r; -} - -const QgsFeatureRenderer* QgsPointDisplacementRenderer::embeddedRenderer() const -{ - return mRenderer; -} - -void QgsPointDisplacementRenderer::setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) -{ - if ( !mRenderer ) - return; - - mRenderer->setLegendSymbolItem( key, symbol ); -} - -bool QgsPointDisplacementRenderer::legendSymbolItemsCheckable() const -{ - if ( !mRenderer ) - return false; - - return mRenderer->legendSymbolItemsCheckable(); -} - -bool QgsPointDisplacementRenderer::legendSymbolItemChecked( const QString& key ) -{ - if ( !mRenderer ) - return false; - - return mRenderer->legendSymbolItemChecked( key ); -} - -void QgsPointDisplacementRenderer::checkLegendSymbolItem( const QString& key, bool state ) -{ - if ( !mRenderer ) - return; - - return mRenderer->checkLegendSymbolItem( key, state ); -} - -QList QgsPointDisplacementRenderer::usedAttributes() -{ - QList attributeList; - if ( !mLabelAttributeName.isEmpty() ) - { - attributeList.push_back( mLabelAttributeName ); - } - if ( mRenderer ) - { - attributeList += mRenderer->usedAttributes(); - } - return attributeList; -} - -QgsFeatureRenderer::Capabilities QgsPointDisplacementRenderer::capabilities() -{ - if ( !mRenderer ) - { - return 0; - } - return mRenderer->capabilities(); -} - -QgsSymbolList QgsPointDisplacementRenderer::symbols( QgsRenderContext& context ) -{ - if ( !mRenderer ) - { - return QgsSymbolList(); - } - return mRenderer->symbols( context ); -} - -QgsSymbol* QgsPointDisplacementRenderer::symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) -{ - if ( !mRenderer ) - { - return nullptr; - } - return mRenderer->symbolForFeature( feature, context ); -} - -QgsSymbol* QgsPointDisplacementRenderer::originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ) -{ - if ( !mRenderer ) - return nullptr; - return mRenderer->originalSymbolForFeature( feat, context ); -} - -QgsSymbolList QgsPointDisplacementRenderer::symbolsForFeature( QgsFeature& feature, QgsRenderContext& context ) -{ - if ( !mRenderer ) - { - return QgsSymbolList(); - } - return mRenderer->symbolsForFeature( feature, context ); -} - -QgsSymbolList QgsPointDisplacementRenderer::originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) -{ - if ( !mRenderer ) - return QgsSymbolList(); - return mRenderer->originalSymbolsForFeature( feat, context ); -} - -bool QgsPointDisplacementRenderer::willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) -{ - if ( !mRenderer ) - { - return false; - } - return mRenderer->willRenderFeature( feat, context ); + drawLabels( centerPoint, symbolContext, labelPositions, group ); } void QgsPointDisplacementRenderer::startRender( QgsRenderContext& context, const QgsFields& fields ) { - mRenderer->startRender( context, fields ); - - mDisplacementGroups.clear(); - mGroupIndex.clear(); - mSpatialIndex = new QgsSpatialIndex; - mSelectedFeatures.clear(); - - if ( mLabelAttributeName.isEmpty() ) - { - mLabelIndex = -1; - } - else - { - mLabelIndex = fields.fieldNameIndex( mLabelAttributeName ); - } - - if ( mMaxLabelScaleDenominator > 0 && context.rendererScale() > mMaxLabelScaleDenominator ) - { - mDrawLabels = false; - } - else - { - mDrawLabels = true; - } - if ( mCenterSymbol ) { mCenterSymbol->startRender( context, fields ); } - return; + + QgsPointDistanceRenderer::startRender( context, fields ); } void QgsPointDisplacementRenderer::stopRender( QgsRenderContext& context ) { - QgsDebugMsg( "QgsPointDisplacementRenderer::stopRender" ); - - //printInfoDisplacementGroups(); //just for debugging - - Q_FOREACH ( const DisplacementGroup& group, mDisplacementGroups ) - { - drawGroup( group, context ); - } - - mDisplacementGroups.clear(); - mGroupIndex.clear(); - delete mSpatialIndex; - mSpatialIndex = nullptr; - mSelectedFeatures.clear(); - - mRenderer->stopRender( context ); + QgsPointDistanceRenderer::stopRender( context ); if ( mCenterSymbol ) { mCenterSymbol->stopRender( context ); @@ -427,6 +163,11 @@ QgsFeatureRenderer* QgsPointDisplacementRenderer::create( QDomElement& symbology return r; } +QgsMarkerSymbol* QgsPointDisplacementRenderer::centerSymbol() +{ + return mCenterSymbol.data(); +} + QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) { QDomElement rendererElement = doc.createElement( RENDERER_TAG_NAME ); @@ -451,7 +192,7 @@ QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) } if ( mCenterSymbol ) { - QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( "centerSymbol", mCenterSymbol, doc ); + QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( "centerSymbol", mCenterSymbol.data(), doc ); rendererElement.appendChild( centerSymbolElem ); } @@ -469,64 +210,11 @@ QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) return rendererElement; } -QgsLegendSymbologyList QgsPointDisplacementRenderer::legendSymbologyItems( QSize iconSize ) -{ - if ( mRenderer ) - { - return mRenderer->legendSymbologyItems( iconSize ); - } - return QgsLegendSymbologyList(); -} - -QgsLegendSymbolList QgsPointDisplacementRenderer::legendSymbolItems( double scaleDenominator, const QString& rule ) -{ - if ( mRenderer ) - { - return mRenderer->legendSymbolItems( scaleDenominator, rule ); - } - return QgsLegendSymbolList(); -} - - -QgsRectangle QgsPointDisplacementRenderer::searchRect( const QgsPoint& p, double distance ) const -{ - return QgsRectangle( p.x() - distance, p.y() - distance, p.x() + distance, p.y() + distance ); -} - -void QgsPointDisplacementRenderer::printInfoDisplacementGroups() -{ - int nGroups = mDisplacementGroups.size(); - QgsDebugMsg( "number of displacement groups:" + QString::number( nGroups ) ); - for ( int i = 0; i < nGroups; ++i ) - { - QgsDebugMsg( "***************displacement group " + QString::number( i ) ); - DisplacementGroup::const_iterator it = mDisplacementGroups.at( i ).constBegin(); - for ( ; it != mDisplacementGroups.at( i ).constEnd(); ++it ) - { - QgsDebugMsg( FID_TO_STRING( it.key() ) ); - } - } -} - -QString QgsPointDisplacementRenderer::getLabel( const QgsFeature& f ) -{ - QString attribute; - QgsAttributes attrs = f.attributes(); - if ( mLabelIndex >= 0 && mLabelIndex < attrs.count() ) - { - attribute = attrs.at( mLabelIndex ).toString(); - } - return attribute; -} - void QgsPointDisplacementRenderer::setCenterSymbol( QgsMarkerSymbol* symbol ) { - delete mCenterSymbol; - mCenterSymbol = symbol; + mCenterSymbol.reset( symbol ); } - - void QgsPointDisplacementRenderer::calculateSymbolAndLabelPositions( QgsSymbolRenderContext& symbolContext, QPointF centerPoint, int nPosition, double symbolDiagonal, QList& symbolPositions, QList& labelShifts, double& circleRadius ) const { @@ -620,86 +308,20 @@ void QgsPointDisplacementRenderer::drawCircle( double radiusPainterUnits, QgsSym p->drawArc( QRectF( centerPoint.x() - radiusPainterUnits, centerPoint.y() - radiusPainterUnits, 2 * radiusPainterUnits, 2 * radiusPainterUnits ), 0, 5760 ); } -void QgsPointDisplacementRenderer::drawSymbols( const QgsFeatureList& features, QgsRenderContext& context, - const QList< QgsMarkerSymbol* >& symbolList, const QList& symbolPositions, bool selected ) +void QgsPointDisplacementRenderer::drawSymbols( const ClusteredGroup& group, QgsRenderContext& context, const QList& symbolPositions ) { QList::const_iterator symbolPosIt = symbolPositions.constBegin(); - QList::const_iterator symbolIt = symbolList.constBegin(); - QgsFeatureList::const_iterator featIt = features.constBegin(); - for ( ; symbolPosIt != symbolPositions.constEnd() && symbolIt != symbolList.constEnd() && featIt != features.constEnd(); - ++symbolPosIt, ++symbolIt, ++featIt ) + ClusteredGroup::const_iterator groupIt = group.constBegin(); + for ( ; symbolPosIt != symbolPositions.constEnd() && groupIt != group.constEnd(); + ++symbolPosIt, ++groupIt ) { - if ( *symbolIt ) - { - context.expressionContext().setFeature( *featIt ); - ( *symbolIt )->startRender( context ); - ( *symbolIt )->renderPoint( *symbolPosIt, &( *featIt ), context, -1, selected ); - ( *symbolIt )->stopRender( context ); - } + context.expressionContext().setFeature( groupIt->feature ); + groupIt->symbol->startRender( context ); + groupIt->symbol->renderPoint( *symbolPosIt, &( groupIt->feature ), context, -1, groupIt->isSelected ); + groupIt->symbol->stopRender( context ); } } -void QgsPointDisplacementRenderer::drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const QStringList& labelList ) -{ - QPainter* p = context.renderContext().painter(); - if ( !p ) - { - return; - } - - QPen labelPen( mLabelColor ); - p->setPen( labelPen ); - - //scale font (for printing) - QFont pixelSizeFont = mLabelFont; - pixelSizeFont.setPixelSize( context.outputLineWidth( mLabelFont.pointSizeF() * 0.3527 ) ); - QFont scaledFont = pixelSizeFont; - scaledFont.setPixelSize( pixelSizeFont.pixelSize() * context.renderContext().rasterScaleFactor() ); - p->setFont( scaledFont ); - - QFontMetricsF fontMetrics( pixelSizeFont ); - QPointF currentLabelShift; //considers the signs to determine the label position - - QList::const_iterator labelPosIt = labelShifts.constBegin(); - QStringList::const_iterator text_it = labelList.constBegin(); - - for ( ; labelPosIt != labelShifts.constEnd() && text_it != labelList.constEnd(); ++labelPosIt, ++text_it ) - { - currentLabelShift = *labelPosIt; - if ( currentLabelShift.x() < 0 ) - { - currentLabelShift.setX( currentLabelShift.x() - fontMetrics.width( *text_it ) ); - } - if ( currentLabelShift.y() > 0 ) - { - currentLabelShift.setY( currentLabelShift.y() + fontMetrics.ascent() ); - } - - QPointF drawingPoint( centerPoint + currentLabelShift ); - p->save(); - p->translate( drawingPoint.x(), drawingPoint.y() ); - p->scale( 1.0 / context.renderContext().rasterScaleFactor(), 1.0 / context.renderContext().rasterScaleFactor() ); - p->drawText( QPointF( 0, 0 ), *text_it ); - p->restore(); - } -} - -QgsSymbol* QgsPointDisplacementRenderer::firstSymbolForFeature( QgsFeatureRenderer* r, QgsFeature& f, QgsRenderContext &context ) -{ - if ( !r ) - { - return nullptr; - } - - QgsSymbolList symbolList = r->symbolsForFeature( f, context ); - if ( symbolList.size() < 1 ) - { - return nullptr; - } - - return symbolList.at( 0 ); -} - QgsPointDisplacementRenderer* QgsPointDisplacementRenderer::convertFromRenderer( const QgsFeatureRenderer* renderer ) { if ( renderer->type() == "pointDisplacement" ) diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.h b/src/core/symbology-ng/qgspointdisplacementrenderer.h index b4799b2bf16b..fec85bb40907 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.h +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.h @@ -18,18 +18,13 @@ #ifndef QGSPOINTDISPLACEMENTRENDERER_H #define QGSPOINTDISPLACEMENTRENDERER_H -#include "qgsfeature.h" -#include "qgssymbol.h" -#include "qgsrenderer.h" -#include -#include +#include "qgspointdistancerenderer.h" -class QgsSpatialIndex; - -/** \ingroup core - * A renderer that automatically displaces points with the same position +/** \class QgsPointDisplacementRenderer + * \ingroup core + * A renderer that automatically displaces points with the same geographic location. */ -class CORE_EXPORT QgsPointDisplacementRenderer: public QgsFeatureRenderer +class CORE_EXPORT QgsPointDisplacementRenderer: public QgsPointDistanceRenderer { public: @@ -41,88 +36,56 @@ class CORE_EXPORT QgsPointDisplacementRenderer: public QgsFeatureRenderer ConcentricRings /*!< Place points in concentric rings around group*/ }; - QgsPointDisplacementRenderer( const QString& labelAttributeName = "" ); - ~QgsPointDisplacementRenderer(); - - QgsPointDisplacementRenderer* clone() const override; - - virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const override; - - /** Reimplemented from QgsFeatureRenderer*/ - bool renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer = -1, bool selected = false, bool drawVertexMarker = false ) override; - - /** Partial proxy that will call this method on the embedded renderer. */ - virtual QList usedAttributes() override; - /** Proxy that will call this method on the embedded renderer. */ - virtual Capabilities capabilities() override; - /** Proxy that will call this method on the embedded renderer. - @note available in python as symbols2 - */ - virtual QgsSymbolList symbols( QgsRenderContext& context ) override; - /** Proxy that will call this method on the embedded renderer. - @note available in python as symbolForFeature2 + /** Constructor for QgsPointDisplacementRenderer. + * @param labelAttributeName optional attribute name for labeling points */ - virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; - /** Proxy that will call this method on the embedded renderer. - @note available in python as originalSymbolForFeature2 - */ - virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ) override; - /** Proxy that will call this method on the embedded renderer. - @note available in python as symbolsForFeature2 - */ - virtual QgsSymbolList symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; - /** Proxy that will call this method on the embedded renderer. - @note available in python as originalSymbolsForFeature2 - */ - virtual QgsSymbolList originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; - /** Proxy that will call this method on the embedded renderer. - @note available in python as willRenderFeature2 - */ - virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; + QgsPointDisplacementRenderer( const QString& labelAttributeName = QString() ); + QgsPointDisplacementRenderer* clone() const override; virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; - void stopRender( QgsRenderContext& context ) override; - - //! create a renderer from XML element - static QgsFeatureRenderer* create( QDomElement& symbologyElem ); QDomElement save( QDomDocument& doc ) override; - QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ) override; - - //! @note not available in python bindings - QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; - - void setLabelAttributeName( const QString& name ) { mLabelAttributeName = name; } - QString labelAttributeName() const { return mLabelAttributeName; } - - void setEmbeddedRenderer( QgsFeatureRenderer* r ) override; - const QgsFeatureRenderer* embeddedRenderer() const override; - - virtual void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) override; - - virtual bool legendSymbolItemsCheckable() const override; - virtual bool legendSymbolItemChecked( const QString& key ) override; - virtual void checkLegendSymbolItem( const QString& key, bool state = true ) override; + //! Create a renderer from XML element + static QgsFeatureRenderer* create( QDomElement& symbologyElem ); - void setLabelFont( const QFont& f ) { mLabelFont = f; } - QFont labelFont() const { return mLabelFont;} + /** Sets the line width for the displacement group circle. + * @param width line width in mm + * @see circleWidth() + * @see setCircleColor() + */ + void setCircleWidth( double width ) { mCircleWidth = width; } - void setCircleWidth( double w ) { mCircleWidth = w; } + /** Returns the line width for the displacement group circle in mm. + * @see setCircleWidth() + * @see circleColor() + */ double circleWidth() const { return mCircleWidth; } - void setCircleColor( const QColor& c ) { mCircleColor = c; } + /** Sets the color used for drawing the displacement group circle. + * @param color circle color + * @see circleColor() + * @see setCircleWidth() + */ + void setCircleColor( const QColor& color ) { mCircleColor = color; } + + /** Returns the color used for drawing the displacement group circle. + * @see setCircleColor() + * @see circleWidth() + */ QColor circleColor() const { return mCircleColor; } - void setLabelColor( const QColor& c ) { mLabelColor = c;} - QColor labelColor() const { return mLabelColor; } + /** Sets a factor for increasing the ring size of displacement groups. + * @param distance addition factor + * @see circleRadiusAddition() + */ + void setCircleRadiusAddition( double distance ) { mCircleRadiusAddition = distance; } - void setCircleRadiusAddition( double d ) { mCircleRadiusAddition = d; } + /** Returns the factor for increasing the ring size of displacement groups. + * @see setCircleRadiusAddition() + */ double circleRadiusAddition() const { return mCircleRadiusAddition; } - void setMaxLabelScaleDenominator( double d ) { mMaxLabelScaleDenominator = d; } - double maxLabelScaleDenominator() const { return mMaxLabelScaleDenominator; } - /** Returns the placement method used for dispersing the points. * @see setPlacement() * @note added in QGIS 2.12 @@ -136,125 +99,44 @@ class CORE_EXPORT QgsPointDisplacementRenderer: public QgsFeatureRenderer */ void setPlacement( Placement placement ) { mPlacement = placement; } - /** Returns the symbol for the center of a displacement group (but _not_ ownership of the symbol)*/ - QgsMarkerSymbol* centerSymbol() { return mCenterSymbol;} - /** Sets the center symbol (takes ownership)*/ - void setCenterSymbol( QgsMarkerSymbol* symbol ); - - /** Sets the tolerance distance for grouping points. Units are specified using - * setToleranceUnit(). - * @param t tolerance distance - * @see tolerance() - * @see setToleranceUnit() - */ - void setTolerance( double t ) { mTolerance = t; } - - /** Returns the tolerance distance for grouping points. Units are retrieved using - * toleranceUnit(). - * @see setTolerance() - * @see toleranceUnit() - */ - double tolerance() const { return mTolerance; } - - /** Sets the units for the tolerance distance. - * @param unit tolerance distance units - * @see setTolerance() - * @see toleranceUnit() - * @note added in QGIS 2.12 - */ - void setToleranceUnit( QgsUnitTypes::RenderUnit unit ) { mToleranceUnit = unit; } - - /** Returns the units for the tolerance distance. - * @see tolerance() - * @see setToleranceUnit() - * @note added in QGIS 2.12 - */ - QgsUnitTypes::RenderUnit toleranceUnit() const { return mToleranceUnit; } + /** Returns the symbol for the center of a displacement group (but not ownership of the symbol). + * @see setCenterSymbol() + */ + QgsMarkerSymbol* centerSymbol(); - /** Sets the map unit scale object for the distance tolerance. This is only used if the - * toleranceUnit() is set to QgsUnitTypes::MapUnit. - * @param scale scale for distance tolerance - * @see toleranceMapUnitScale() - * @see setToleranceUnit() - */ - void setToleranceMapUnitScale( const QgsMapUnitScale& scale ) { mToleranceMapUnitScale = scale; } + /** Sets the center symbol for a displacement group. + * @param symbol new center symbol. Ownership is transferred to the renderer. + * @see centerSymbol() + */ + void setCenterSymbol( QgsMarkerSymbol* symbol ); - /** Returns the map unit scale object for the distance tolerance. This is only used if the - * toleranceUnit() is set to QgsUnitTypes::MapUnit. - * @see setToleranceMapUnitScale() - * @see toleranceUnit() + /** Creates a QgsPointDisplacementRenderer from an existing renderer. + * @note added in 2.5 + * @returns a new renderer if the conversion was possible, otherwise nullptr. */ - const QgsMapUnitScale& toleranceMapUnitScale() const { return mToleranceMapUnitScale; } - - //! creates a QgsPointDisplacementRenderer from an existing renderer. - //! @note added in 2.5 - //! @returns a new renderer if the conversion was possible, otherwise 0. static QgsPointDisplacementRenderer* convertFromRenderer( const QgsFeatureRenderer *renderer ); private: - /** Embedded renderer. Like This, it is possible to use a classification together with point displacement*/ - QgsFeatureRenderer* mRenderer; - - /** Attribute name for labeling. Empty string means no labelling will be done*/ - QString mLabelAttributeName; - /** Label attribute index (or -1 if none). This index is not stored, it is requested in the startRender() method*/ - int mLabelIndex; - - /** Center symbol for a displacement group*/ - QgsMarkerSymbol* mCenterSymbol; - - /** Tolerance. Points that are closer together are considered as equal*/ - double mTolerance; - QgsUnitTypes::RenderUnit mToleranceUnit; - QgsMapUnitScale mToleranceMapUnitScale; + //! Center symbol for a displacement group + QScopedPointer< QgsMarkerSymbol > mCenterSymbol; + //! Displacement placement mode Placement mPlacement; - /** Font that is passed to the renderer*/ - QFont mLabelFont; - QColor mLabelColor; - /** Line width for the circle*/ + //! Line width for the circle double mCircleWidth; - /** Color to draw the circle*/ + //! Color to draw the circle QColor mCircleColor; - /** Addition to the default circle radius*/ + //! Addition to the default circle radius double mCircleRadiusAddition; - /** Is set internally from startRender() depending on scale denominator*/ - bool mDrawLabels; - /** Maximum scale denominator for label display. Negative number means no scale limitation*/ - double mMaxLabelScaleDenominator; - - typedef QMap > DisplacementGroup; - /** Groups of features that have the same position*/ - QList mDisplacementGroups; - /** Mapping from feature ID to its group index*/ - QMap mGroupIndex; - /** Spatial index for fast lookup of close points*/ - QgsSpatialIndex* mSpatialIndex; - /** Keeps track which features are selected */ - QSet mSelectedFeatures; - - /** Creates a search rectangle with specified distance tolerance */ - QgsRectangle searchRect( const QgsPoint& p, double distance ) const; - /** This is a debugging function to check the entries in the displacement groups*/ - void printInfoDisplacementGroups(); - - /** Returns the label for a feature (using mLabelAttributeName as attribute field)*/ - QString getLabel( const QgsFeature& f ); - //rendering methods - void renderPoint( const QPointF& point, QgsSymbolRenderContext& context, const QList& symbols, - const QStringList& labels ); + virtual void drawGroup( QPointF centerPoint, QgsRenderContext& context, const QgsPointDistanceRenderer::ClusteredGroup& group ) override; //helper functions void calculateSymbolAndLabelPositions( QgsSymbolRenderContext &symbolContext, QPointF centerPoint, int nPosition, double symbolDiagonal, QList& symbolPositions, QList& labelShifts , double &circleRadius ) const; - void drawGroup( const DisplacementGroup& group, QgsRenderContext& context ); void drawCircle( double radiusPainterUnits, QgsSymbolRenderContext& context, QPointF centerPoint, int nSymbols ); - void drawSymbols( const QgsFeatureList& features, QgsRenderContext& context, const QList< QgsMarkerSymbol* >& symbolList, const QList& symbolPositions, bool selected = false ); - void drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const QStringList& labelList ); - /** Returns first symbol for feature or 0 if none*/ - QgsSymbol* firstSymbolForFeature( QgsFeatureRenderer* r, QgsFeature& f, QgsRenderContext& context ); + void drawSymbols( const ClusteredGroup& group, QgsRenderContext& context, const QList& symbolPositions ); }; #endif // QGSPOINTDISPLACEMENTRENDERER_H diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp new file mode 100644 index 000000000000..3e61d6c31813 --- /dev/null +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -0,0 +1,411 @@ +/*************************************************************************** + qgspointdistancerenderer.cpp + ---------------------------- + begin : January 26, 2010 + copyright : (C) 2010 by Marco Hugentobler + email : marco at hugis dot net + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgspointdistancerenderer.h" +#include "qgsgeometry.h" +#include "qgssymbollayerutils.h" +#include "qgsspatialindex.h" +#include "qgsmultipoint.h" +#include "qgslogger.h" + +#include +#include + +#include + +#ifndef M_SQRT2 +#define M_SQRT2 1.41421356237309504880 +#endif + +QgsPointDistanceRenderer::QgsPointDistanceRenderer( const QString& rendererName, const QString& labelAttributeName ) + : QgsFeatureRenderer( rendererName ) + , mLabelAttributeName( labelAttributeName ) + , mLabelIndex( -1 ) + , mTolerance( 3 ) + , mToleranceUnit( QgsUnitTypes::RenderMillimeters ) + , mDrawLabels( true ) + , mMaxLabelScaleDenominator( -1 ) + , mSpatialIndex( nullptr ) +{ + mRenderer.reset( QgsFeatureRenderer::defaultRenderer( QgsWkbTypes::PointGeometry ) ); +} + +void QgsPointDistanceRenderer::toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props ) const +{ + mRenderer->toSld( doc, element, props ); +} + + +bool QgsPointDistanceRenderer::renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer, bool selected, bool drawVertexMarker ) +{ + Q_UNUSED( drawVertexMarker ); + Q_UNUSED( context ); + Q_UNUSED( layer ); + + //check if there is already a point at that position + if ( !feature.hasGeometry() ) + return false; + + QgsMarkerSymbol* symbol = firstSymbolForFeature( feature, context ); + + //if the feature has no symbol (eg, no matching rule in a rule-based renderer), skip it + if ( !symbol ) + return false; + + //point position in screen coords + QgsGeometry geom = feature.geometry(); + QgsWkbTypes::Type geomType = geom.wkbType(); + if ( QgsWkbTypes::flatType( geomType ) != QgsWkbTypes::Point ) + { + //can only render point type + return false; + } + + QString label; + if ( mDrawLabels ) + { + label = getLabel( feature ); + } + + double searchDistance = mTolerance * QgsSymbolLayerUtils::mapUnitScaleFactor( context, mToleranceUnit, mToleranceMapUnitScale ); + QgsPoint point = feature.geometry().asPoint(); + QList intersectList = mSpatialIndex->intersects( searchRect( point, searchDistance ) ); + if ( intersectList.empty() ) + { + mSpatialIndex->insertFeature( feature ); + // create new group + ClusteredGroup newGroup; + newGroup << GroupedFeature( feature, symbol, selected, label ); + mClusteredGroups.push_back( newGroup ); + // add to group index + mGroupIndex.insert( feature.id(), mClusteredGroups.count() - 1 ); + mGroupLocations.insert( feature.id(), point ); + } + else + { + // find group with closest location to this point (may be more than one within search tolerance) + QgsFeatureId minDistFeatureId = intersectList.at( 0 ); + double minDist = mGroupLocations.value( minDistFeatureId ).distance( point ); + for ( int i = 1; i < intersectList.count(); ++i ) + { + QgsFeatureId candidateId = intersectList.at( i ); + double newDist = mGroupLocations.value( candidateId ).distance( point ); + if ( newDist < minDist ) + { + minDist = newDist; + minDistFeatureId = candidateId; + } + } + + int groupIdx = mGroupIndex[ minDistFeatureId ]; + ClusteredGroup& group = mClusteredGroups[groupIdx]; + + // add to a group + group << GroupedFeature( feature, symbol, selected, label ); + // add to group index + mGroupIndex.insert( feature.id(), groupIdx ); + } + + return true; +} + +void QgsPointDistanceRenderer::drawGroup( const ClusteredGroup& group, QgsRenderContext& context ) +{ + //calculate centroid of all points, this will be center of group + QgsMultiPointV2* groupMultiPoint = new QgsMultiPointV2(); + Q_FOREACH ( const GroupedFeature& f, group ) + { + groupMultiPoint->addGeometry( f.feature.geometry().geometry()->clone() ); + } + QgsGeometry groupGeom( groupMultiPoint ); + QgsGeometry centroid = groupGeom.centroid(); + QPointF pt = _getPoint( context, *static_cast( centroid.geometry() ) ); + + drawGroup( pt, context, group ); +} + +void QgsPointDistanceRenderer::setEmbeddedRenderer( QgsFeatureRenderer* r ) +{ + mRenderer.reset( r ); +} + +const QgsFeatureRenderer*QgsPointDistanceRenderer::embeddedRenderer() const +{ + return mRenderer.data(); +} + +void QgsPointDistanceRenderer::setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) +{ + if ( !mRenderer ) + return; + + mRenderer->setLegendSymbolItem( key, symbol ); +} + +bool QgsPointDistanceRenderer::legendSymbolItemsCheckable() const +{ + if ( !mRenderer ) + return false; + + return mRenderer->legendSymbolItemsCheckable(); +} + +bool QgsPointDistanceRenderer::legendSymbolItemChecked( const QString& key ) +{ + if ( !mRenderer ) + return false; + + return mRenderer->legendSymbolItemChecked( key ); +} + +void QgsPointDistanceRenderer::checkLegendSymbolItem( const QString& key, bool state ) +{ + if ( !mRenderer ) + return; + + return mRenderer->checkLegendSymbolItem( key, state ); +} + +QList QgsPointDistanceRenderer::usedAttributes() +{ + QList attributeList; + if ( !mLabelAttributeName.isEmpty() ) + { + attributeList.push_back( mLabelAttributeName ); + } + if ( mRenderer ) + { + attributeList += mRenderer->usedAttributes(); + } + return attributeList; +} + +QgsFeatureRenderer::Capabilities QgsPointDistanceRenderer::capabilities() +{ + if ( !mRenderer ) + { + return 0; + } + return mRenderer->capabilities(); +} + +QgsSymbolList QgsPointDistanceRenderer::symbols( QgsRenderContext& context ) +{ + if ( !mRenderer ) + { + return QgsSymbolList(); + } + return mRenderer->symbols( context ); +} + +QgsSymbol* QgsPointDistanceRenderer::symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) +{ + if ( !mRenderer ) + { + return nullptr; + } + return mRenderer->symbolForFeature( feature, context ); +} + +QgsSymbol* QgsPointDistanceRenderer::originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ) +{ + if ( !mRenderer ) + return nullptr; + return mRenderer->originalSymbolForFeature( feat, context ); +} + +QgsSymbolList QgsPointDistanceRenderer::symbolsForFeature( QgsFeature& feature, QgsRenderContext& context ) +{ + if ( !mRenderer ) + { + return QgsSymbolList(); + } + return mRenderer->symbolsForFeature( feature, context ); +} + +QgsSymbolList QgsPointDistanceRenderer::originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) +{ + if ( !mRenderer ) + return QgsSymbolList(); + return mRenderer->originalSymbolsForFeature( feat, context ); +} + +bool QgsPointDistanceRenderer::willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) +{ + if ( !mRenderer ) + { + return false; + } + return mRenderer->willRenderFeature( feat, context ); +} + + +void QgsPointDistanceRenderer::startRender( QgsRenderContext& context, const QgsFields& fields ) +{ + mRenderer->startRender( context, fields ); + + mClusteredGroups.clear(); + mGroupIndex.clear(); + mGroupLocations.clear(); + mSpatialIndex = new QgsSpatialIndex; + + if ( mLabelAttributeName.isEmpty() ) + { + mLabelIndex = -1; + } + else + { + mLabelIndex = fields.fieldNameIndex( mLabelAttributeName ); + } + + if ( mMaxLabelScaleDenominator > 0 && context.rendererScale() > mMaxLabelScaleDenominator ) + { + mDrawLabels = false; + } + else + { + mDrawLabels = true; + } +} + +void QgsPointDistanceRenderer::stopRender( QgsRenderContext& context ) +{ + //printInfoDisplacementGroups(); //just for debugging + + Q_FOREACH ( const ClusteredGroup& group, mClusteredGroups ) + { + drawGroup( group, context ); + } + + mClusteredGroups.clear(); + mGroupIndex.clear(); + mGroupLocations.clear(); + delete mSpatialIndex; + mSpatialIndex = nullptr; + + mRenderer->stopRender( context ); +} + +QgsLegendSymbologyList QgsPointDistanceRenderer::legendSymbologyItems( QSize iconSize ) +{ + if ( mRenderer ) + { + return mRenderer->legendSymbologyItems( iconSize ); + } + return QgsLegendSymbologyList(); +} + +QgsLegendSymbolList QgsPointDistanceRenderer::legendSymbolItems( double scaleDenominator, const QString& rule ) +{ + if ( mRenderer ) + { + return mRenderer->legendSymbolItems( scaleDenominator, rule ); + } + return QgsLegendSymbolList(); +} + + +QgsRectangle QgsPointDistanceRenderer::searchRect( const QgsPoint& p, double distance ) const +{ + return QgsRectangle( p.x() - distance, p.y() - distance, p.x() + distance, p.y() + distance ); +} + +void QgsPointDistanceRenderer::printGroupInfo() const +{ + int nGroups = mClusteredGroups.size(); + QgsDebugMsg( "number of displacement groups:" + QString::number( nGroups ) ); + for ( int i = 0; i < nGroups; ++i ) + { + QgsDebugMsg( "***************displacement group " + QString::number( i ) ); + Q_FOREACH ( const GroupedFeature& feature, mClusteredGroups.at( i ) ) + { + QgsDebugMsg( FID_TO_STRING( feature.feature.id() ) ); + } + } +} + +QString QgsPointDistanceRenderer::getLabel( const QgsFeature& feature ) const +{ + QString attribute; + QgsAttributes attrs = feature.attributes(); + if ( mLabelIndex >= 0 && mLabelIndex < attrs.count() ) + { + attribute = attrs.at( mLabelIndex ).toString(); + } + return attribute; +} + +void QgsPointDistanceRenderer::drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const ClusteredGroup& group ) +{ + QPainter* p = context.renderContext().painter(); + if ( !p ) + { + return; + } + + QPen labelPen( mLabelColor ); + p->setPen( labelPen ); + + //scale font (for printing) + QFont pixelSizeFont = mLabelFont; + pixelSizeFont.setPixelSize( context.outputLineWidth( mLabelFont.pointSizeF() * 0.3527 ) ); + QFont scaledFont = pixelSizeFont; + scaledFont.setPixelSize( pixelSizeFont.pixelSize() * context.renderContext().rasterScaleFactor() ); + p->setFont( scaledFont ); + + QFontMetricsF fontMetrics( pixelSizeFont ); + QPointF currentLabelShift; //considers the signs to determine the label position + + QList::const_iterator labelPosIt = labelShifts.constBegin(); + ClusteredGroup::const_iterator groupIt = group.constBegin(); + + for ( ; labelPosIt != labelShifts.constEnd() && groupIt != group.constEnd(); ++labelPosIt, ++groupIt ) + { + currentLabelShift = *labelPosIt; + if ( currentLabelShift.x() < 0 ) + { + currentLabelShift.setX( currentLabelShift.x() - fontMetrics.width( groupIt->label ) ); + } + if ( currentLabelShift.y() > 0 ) + { + currentLabelShift.setY( currentLabelShift.y() + fontMetrics.ascent() ); + } + + QPointF drawingPoint( centerPoint + currentLabelShift ); + p->save(); + p->translate( drawingPoint.x(), drawingPoint.y() ); + p->scale( 1.0 / context.renderContext().rasterScaleFactor(), 1.0 / context.renderContext().rasterScaleFactor() ); + p->drawText( QPointF( 0, 0 ), groupIt->label ); + p->restore(); + } +} + +QgsMarkerSymbol* QgsPointDistanceRenderer::firstSymbolForFeature( QgsFeature& feature, QgsRenderContext &context ) +{ + if ( !mRenderer ) + { + return nullptr; + } + + QgsSymbolList symbolList = mRenderer->symbolsForFeature( feature, context ); + if ( symbolList.isEmpty() ) + { + return nullptr; + } + + return dynamic_cast< QgsMarkerSymbol* >( symbolList.at( 0 ) ); +} diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h new file mode 100644 index 000000000000..dc04143e9177 --- /dev/null +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -0,0 +1,280 @@ +/*************************************************************************** + qgspointdistancerenderer.cpp + ---------------------------- + begin : January 26, 2010 + copyright : (C) 2010 by Marco Hugentobler + email : marco at hugis dot net + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSPOINTDISTANCERENDERER_H +#define QGSPOINTDISTANCERENDERER_H + +#include "qgsrenderer.h" +#include + +class QgsSpatialIndex; + +/** \class QgsPointDistanceRenderer + * \ingroup core + * An abstract base class for distance based point renderers (eg clusterer and displacement renderers). + * QgsPointDistanceRenderer handles calculation of point clusters using a distance based threshold. + * Subclasses must implement drawGroup() to handle the rendering of individual point clusters + * in the desired style. + * \note added in QGIS 3.0 + */ + +class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer +{ + public: + + //! Contains properties for a feature within a clustered group. + struct GroupedFeature + { + /** Constructor for GroupedFeature. + * @param feature feature + * @param symbol base symbol for rendering feature + * @param isSelected set to true if feature is selected and should be rendered in a selected state + * @param label optional label text, or empty string for no label + */ + GroupedFeature( const QgsFeature& feature, QgsMarkerSymbol* symbol, bool isSelected, const QString& label = QString() ) + : feature( feature ) + , symbol( symbol ) + , isSelected( isSelected ) + , label( label ) + {} + + //! Feature + QgsFeature feature; + + //! Base symbol for rendering feature + QgsMarkerSymbol* symbol; + + //! True if feature is selected and should be rendered in a selected state + bool isSelected; + + //! Optional label text + QString label; + }; + + //! A group of clustered points (ie features within the distance tolerance). + typedef QList< GroupedFeature > ClusteredGroup; + + /** Constructor for QgsPointDistanceRenderer. + * @param rendererName name of renderer for registry + * @param labelAttributeName optional attribute for labeling points + */ + QgsPointDistanceRenderer( const QString& rendererName, const QString& labelAttributeName = QString() ); + + virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const override; + bool renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer = -1, bool selected = false, bool drawVertexMarker = false ) override; + virtual QList usedAttributes() override; + virtual Capabilities capabilities() override; + virtual QgsSymbolList symbols( QgsRenderContext& context ) override; + virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; + virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ) override; + virtual QgsSymbolList symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; + virtual QgsSymbolList originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; + virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; + virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; + void stopRender( QgsRenderContext& context ) override; + QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ) override; + QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; + void setEmbeddedRenderer( QgsFeatureRenderer* r ) override; + const QgsFeatureRenderer* embeddedRenderer() const override; + void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) override; + bool legendSymbolItemsCheckable() const override; + bool legendSymbolItemChecked( const QString& key ) override; + void checkLegendSymbolItem( const QString& key, bool state ) override; + + /** Sets the attribute name for labeling points. + * @param name attribute name, or empty string to avoid labeling features by the renderer + * @see labelAttributeName() + * @see setLabelFont() + * @see setLabelColor() + * @see setMaxLabelScaleDenominator() + */ + void setLabelAttributeName( const QString& name ) { mLabelAttributeName = name; } + + /** Returns the attribute name used for labeling points, or an empty string if no labeling + * will be done by the renderer. + * @see setLabelAttributeName() + * @see labelFont() + * @see maxLabelScaleDenominator() + * @see labelColor() + */ + QString labelAttributeName() const { return mLabelAttributeName; } + + /** Sets the font used for labeling points. + * @param font label font + * @see labelFont() + * @see setLabelAttributeName() + * @see setLabelColor() + */ + void setLabelFont( const QFont& font ) { mLabelFont = font; } + + /** Returns the font used for labeling points. + * @see setLabelFont() + * @see labelAttributeName() + * @see labelColor() + */ + QFont labelFont() const { return mLabelFont;} + + /** Sets the maximum scale at which points should be labeled by the renderer. + * @param denominator maximum scale denominator + * @see maxLabelScaleDenominator() + * @see setLabelAttributeName() + */ + void setMaxLabelScaleDenominator( double denominator ) { mMaxLabelScaleDenominator = denominator; } + + /** Returns the denominator for the maximum scale at which points should be labeled by the renderer. + * @see setMaxLabelScaleDenominator() + * @see labelAttributeName() + */ + double maxLabelScaleDenominator() const { return mMaxLabelScaleDenominator; } + + /** Sets the color to use for for labeling points. + * @param color label color + * @see labelColor() + * @see setLabelAttributeName() + * @see setLabelFont() + */ + void setLabelColor( const QColor& color ) { mLabelColor = color;} + + /** Returns the color used for for labeling points. + * @see setLabelColor() + * @see labelAttributeName() + * @see labelFont() + */ + QColor labelColor() const { return mLabelColor; } + + /** Sets the tolerance distance for grouping points. Units are specified using + * setToleranceUnit(). + * @param distance tolerance distance + * @see tolerance() + * @see setToleranceUnit() + */ + void setTolerance( double distance ) { mTolerance = distance; } + + /** Returns the tolerance distance for grouping points. Units are retrieved using + * toleranceUnit(). + * @see setTolerance() + * @see toleranceUnit() + */ + double tolerance() const { return mTolerance; } + + /** Sets the units for the tolerance distance. + * @param unit tolerance distance units + * @see setTolerance() + * @see toleranceUnit() + * @note added in QGIS 2.12 + */ + void setToleranceUnit( QgsUnitTypes::RenderUnit unit ) { mToleranceUnit = unit; } + + /** Returns the units for the tolerance distance. + * @see tolerance() + * @see setToleranceUnit() + * @note added in QGIS 2.12 + */ + QgsUnitTypes::RenderUnit toleranceUnit() const { return mToleranceUnit; } + + /** Sets the map unit scale object for the distance tolerance. This is only used if the + * toleranceUnit() is set to QgsUnitTypes::RenderMapUnits. + * @param scale scale for distance tolerance + * @see toleranceMapUnitScale() + * @see setToleranceUnit() + */ + void setToleranceMapUnitScale( const QgsMapUnitScale& scale ) { mToleranceMapUnitScale = scale; } + + /** Returns the map unit scale object for the distance tolerance. This is only used if the + * toleranceUnit() is set to QgsUnitTypes::RenderMapUnits. + * @see setToleranceMapUnitScale() + * @see toleranceUnit() + */ + const QgsMapUnitScale& toleranceMapUnitScale() const { return mToleranceMapUnitScale; } + + protected: + + //! Embedded base renderer. This can be used for rendering individual, isolated points. + QScopedPointer< QgsFeatureRenderer > mRenderer; + + //! Attribute name for labeling. An empty string indicates that no labels should be rendered. + QString mLabelAttributeName; + + //! Label attribute index (or -1 if none). This index is not stored, it is requested in the startRender() method. + int mLabelIndex; + + //! Distance tolerance. Points that are closer together than this distance are considered clustered. + double mTolerance; + //! Unit for distance tolerance. + QgsUnitTypes::RenderUnit mToleranceUnit; + //! Map unit scale for distance tolerance. + QgsMapUnitScale mToleranceMapUnitScale; + + //! Label font. + QFont mLabelFont; + //! Label text color. + QColor mLabelColor; + //! Whether labels should be drawn for points. This is set internally from startRender() depending on scale denominator. + bool mDrawLabels; + //! Maximum scale denominator for label display. A negative number indicatese no scale limitation. + double mMaxLabelScaleDenominator; + + //! Groups of features that are considered clustered together. + QList mClusteredGroups; + + //! Mapping of feature ID to the feature's group index. + QMap mGroupIndex; + + //! Mapping of feature ID to approximate group location + QMap mGroupLocations; + + //! Spatial index for fast lookup of nearby points. + QgsSpatialIndex* mSpatialIndex; + + /** Renders the labels for a group. + * @param centerPoint center point of group + * @param context destination render context + * @param labelShifts displacement for individual label positions + * @param group group of clustered features to label + */ + void drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const ClusteredGroup& group ); + + private: + + /** Draws a group of clustered points. + * @param centerPoint central point (geographic centroid) of all points contained within the cluster + * @param context destination render context + * @param group contents of group + */ + virtual void drawGroup( QPointF centerPoint, QgsRenderContext& context, const ClusteredGroup& group ) = 0; + + //! Creates a search rectangle with specified distance tolerance. + QgsRectangle searchRect( const QgsPoint& p, double distance ) const; + + //! Debugging function to check the entries in the clustered groups + void printGroupInfo() const; + + //! Returns the label text for a feature (using mLabelAttributeName as attribute field) + QString getLabel( const QgsFeature& feature ) const; + + //! Internal group rendering helper + void drawGroup( const ClusteredGroup& group, QgsRenderContext& context ); + + /** Returns first symbol from the embedded renderer for a feature or nullptr if none + * @param feature source feature + * @param context target render context + */ + QgsMarkerSymbol* firstSymbolForFeature( QgsFeature& feature, QgsRenderContext& context ); + +}; + +#endif // QGSPOINTDISTANCERENDERER_H diff --git a/src/core/symbology-ng/qgsrendererregistry.cpp b/src/core/symbology-ng/qgsrendererregistry.cpp index 61f5abd34064..b7245729fb7d 100644 --- a/src/core/symbology-ng/qgsrendererregistry.cpp +++ b/src/core/symbology-ng/qgsrendererregistry.cpp @@ -20,6 +20,7 @@ #include "qgsgraduatedsymbolrenderer.h" #include "qgsrulebasedrenderer.h" #include "qgspointdisplacementrenderer.h" +#include "qgspointclusterrenderer.h" #include "qgsinvertedpolygonrenderer.h" #include "qgsheatmaprenderer.h" #include "qgs25drenderer.h" @@ -58,6 +59,13 @@ QgsRendererRegistry::QgsRendererRegistry() nullptr, QgsRendererAbstractMetadata::PointLayer ) ); + addRenderer( new QgsRendererMetadata( "pointCluster", + QObject::tr( "Point cluster" ), + QgsPointClusterRenderer::create, + QIcon(), + nullptr, + QgsRendererAbstractMetadata::PointLayer ) ); + addRenderer( new QgsRendererMetadata( "invertedPolygonRenderer", QObject::tr( "Inverted polygons" ), QgsInvertedPolygonRenderer::create, diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.cpp b/src/core/symbology-ng/qgsrulebasedrenderer.cpp index fd57db883b57..ec50e51184ff 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.cpp +++ b/src/core/symbology-ng/qgsrulebasedrenderer.cpp @@ -1329,11 +1329,11 @@ QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatur r = new QgsRuleBasedRenderer( rootrule ); } - else if ( renderer->type() == "pointDisplacement" ) + else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) { - const QgsPointDisplacementRenderer* pointDisplacementRenderer = dynamic_cast( renderer ); - if ( pointDisplacementRenderer ) - r = convertFromRenderer( pointDisplacementRenderer->embeddedRenderer() ); + const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast( renderer ); + if ( pointDistanceRenderer ) + return convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } else if ( renderer->type() == "invertedPolygonRenderer" ) { diff --git a/src/core/symbology-ng/qgssinglesymbolrenderer.cpp b/src/core/symbology-ng/qgssinglesymbolrenderer.cpp index 70342a123add..fce4b14e356f 100644 --- a/src/core/symbology-ng/qgssinglesymbolrenderer.cpp +++ b/src/core/symbology-ng/qgssinglesymbolrenderer.cpp @@ -351,11 +351,11 @@ QgsSingleSymbolRenderer* QgsSingleSymbolRenderer::convertFromRenderer( const Qgs { r = dynamic_cast( renderer->clone() ); } - else if ( renderer->type() == "pointDisplacement" ) + else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) { - const QgsPointDisplacementRenderer* pointDisplacementRenderer = dynamic_cast( renderer ); - if ( pointDisplacementRenderer ) - r = convertFromRenderer( pointDisplacementRenderer->embeddedRenderer() ); + const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast( renderer ); + if ( pointDistanceRenderer ) + r = convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } else if ( renderer->type() == "invertedPolygonRenderer" ) { diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index ae347d96d9eb..cc93d6cbe702 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -27,6 +27,7 @@ SET(QGIS_GUI_SRCS symbology-ng/qgslayerpropertieswidget.cpp symbology-ng/qgsnullsymbolrendererwidget.cpp symbology-ng/qgspenstylecombobox.cpp + symbology-ng/qgspointclusterrendererwidget.cpp symbology-ng/qgspointdisplacementrendererwidget.cpp symbology-ng/qgsrendererpropertiesdialog.cpp symbology-ng/qgsrendererwidget.cpp @@ -491,6 +492,7 @@ SET(QGIS_GUI_MOC_HDRS symbology-ng/qgslayerpropertieswidget.h symbology-ng/qgsnullsymbolrendererwidget.h symbology-ng/qgspenstylecombobox.h + symbology-ng/qgspointclusterrendererwidget.h symbology-ng/qgspointdisplacementrendererwidget.h symbology-ng/qgsrendererpropertiesdialog.h symbology-ng/qgsrendererwidget.h diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp new file mode 100644 index 000000000000..1abf2811f97e --- /dev/null +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp @@ -0,0 +1,231 @@ +/*************************************************************************** + qgspointclusterrendererwidget.cpp + --------------------------------- + begin : February 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgspointclusterrendererwidget.h" +#include "qgspointclusterrenderer.h" +#include "qgsrendererregistry.h" +#include "qgsfield.h" +#include "qgsstyle.h" +#include "qgssymbolselectordialog.h" +#include "qgssymbollayerutils.h" +#include "qgsvectorlayer.h" +#include "qgisgui.h" + +QgsRendererWidget* QgsPointClusterRendererWidget::create( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ) +{ + return new QgsPointClusterRendererWidget( layer, style, renderer ); +} + +QgsPointClusterRendererWidget::QgsPointClusterRendererWidget( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ) + : QgsRendererWidget( layer, style ) + , mRenderer( nullptr ) +{ + if ( !layer ) + { + return; + } + + //the renderer only applies to point vector layers + if ( QgsWkbTypes::flatType( layer->wkbType() ) != QgsWkbTypes::Point ) + { + //setup blank dialog + mRenderer = nullptr; + setupBlankUi( layer->name() ); + return; + } + setupUi( this ); + mDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + + if ( renderer ) + { + mRenderer = QgsPointClusterRenderer::convertFromRenderer( renderer ); + } + if ( !mRenderer ) + { + mRenderer = new QgsPointClusterRenderer(); + } + + blockAllSignals( true ); + + //insert possible renderer types + QStringList rendererList = QgsRendererRegistry::instance()->renderersList( QgsRendererAbstractMetadata::PointLayer ); + QStringList::const_iterator it = rendererList.constBegin(); + for ( ; it != rendererList.constEnd(); ++it ) + { + if ( *it != "pointDisplacement" && *it != "pointCluster" && *it != "heatmapRenderer" ) + { + QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( *it ); + mRendererComboBox->addItem( m->icon(), m->visibleName(), *it ); + } + } + + mDistanceSpinBox->setValue( mRenderer->tolerance() ); + mDistanceUnitWidget->setUnit( mRenderer->toleranceUnit() ); + mDistanceUnitWidget->setMapUnitScale( mRenderer->toleranceMapUnitScale() ); + + blockAllSignals( false ); + + //set the appropriate renderer dialog + if ( mRenderer->embeddedRenderer() ) + { + QString rendererName = mRenderer->embeddedRenderer()->type(); + int rendererIndex = mRendererComboBox->findData( rendererName ); + if ( rendererIndex != -1 ) + { + mRendererComboBox->setCurrentIndex( rendererIndex ); + on_mRendererComboBox_currentIndexChanged( rendererIndex ); + } + } + + updateCenterIcon(); +} + +QgsPointClusterRendererWidget::~QgsPointClusterRendererWidget() +{ + delete mRenderer; +} + +QgsFeatureRenderer* QgsPointClusterRendererWidget::renderer() +{ + return mRenderer; +} + +void QgsPointClusterRendererWidget::setMapCanvas( QgsMapCanvas* canvas ) +{ + QgsRendererWidget::setMapCanvas( canvas ); + if ( mDistanceUnitWidget ) + mDistanceUnitWidget->setMapCanvas( canvas ); +} + +void QgsPointClusterRendererWidget::on_mRendererComboBox_currentIndexChanged( int index ) +{ + QString rendererId = mRendererComboBox->itemData( index ).toString(); + QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( rendererId ); + if ( m ) + { + // unfortunately renderer conversion is only available through the creation of a widget... + QgsRendererWidget* tempRenderWidget = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); + mRenderer->setEmbeddedRenderer( tempRenderWidget->renderer()->clone() ); + delete tempRenderWidget; + } + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::on_mRendererSettingsButton_clicked() +{ + if ( !mRenderer ) + return; + + QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( mRenderer->embeddedRenderer()->type() ); + if ( m ) + { + QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); + w->setMapCanvas( mMapCanvas ); + connect( w, SIGNAL( widgetChanged() ), this, SLOT( updateRendererFromWidget() ) ); + w->setDockMode( this->dockMode() ); + openPanel( w ); + } +} + +void QgsPointClusterRendererWidget::on_mDistanceSpinBox_valueChanged( double d ) +{ + if ( mRenderer ) + { + mRenderer->setTolerance( d ); + } + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::on_mDistanceUnitWidget_changed() +{ + if ( mRenderer ) + { + mRenderer->setToleranceUnit( mDistanceUnitWidget->unit() ); + mRenderer->setToleranceMapUnitScale( mDistanceUnitWidget->getMapUnitScale() ); + } + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::blockAllSignals( bool block ) +{ + mRendererComboBox->blockSignals( block ); + mCenterSymbolPushButton->blockSignals( block ); + mDistanceSpinBox->blockSignals( block ); + mDistanceUnitWidget->blockSignals( block ); +} + +void QgsPointClusterRendererWidget::on_mCenterSymbolPushButton_clicked() +{ + if ( !mRenderer || !mRenderer->clusterSymbol() ) + { + return; + } + QgsMarkerSymbol* markerSymbol = mRenderer->clusterSymbol()->clone(); + QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); + dlg->setDockMode( this->dockMode() ); + dlg->setMapCanvas( mMapCanvas ); + + connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateCenterSymbolFromWidget() ) ); + connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); + openPanel( dlg ); +} + +void QgsPointClusterRendererWidget::updateCenterSymbolFromWidget() +{ + QgsSymbolSelectorWidget* dlg = qobject_cast( sender() ); + QgsSymbol* symbol = dlg->symbol()->clone(); + mRenderer->setClusterSymbol( static_cast< QgsMarkerSymbol* >( symbol ) ); + updateCenterIcon(); + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::cleanUpSymbolSelector( QgsPanelWidget *container ) +{ + if ( container ) + { + QgsSymbolSelectorWidget* dlg = qobject_cast( container ); + delete dlg->symbol(); + } +} + +void QgsPointClusterRendererWidget::updateRendererFromWidget() +{ + QgsRendererWidget* w = qobject_cast( sender() ); + if ( !w ) + return; + + mRenderer->setEmbeddedRenderer( w->renderer()->clone() ); + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::updateCenterIcon() +{ + QgsMarkerSymbol* symbol = mRenderer->clusterSymbol(); + if ( !symbol ) + { + return; + } + QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, mCenterSymbolPushButton->iconSize() ); + mCenterSymbolPushButton->setIcon( icon ); +} + +void QgsPointClusterRendererWidget::setupBlankUi( const QString& layerName ) +{ + QGridLayout* layout = new QGridLayout( this ); + QLabel* label = new QLabel( tr( "The point cluster renderer only applies to (single) point layers. \n'%1' is not a point layer and cannot be displayed by the point cluster renderer" ).arg( layerName ), this ); + layout->addWidget( label ); +} diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.h b/src/gui/symbology-ng/qgspointclusterrendererwidget.h new file mode 100644 index 000000000000..940fbaf4f4fa --- /dev/null +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.h @@ -0,0 +1,56 @@ +/*************************************************************************** + qgspointclusterrendererwidget.h + ------------------------------- + begin : February 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSPOINTCLUSTERRENDERERWIDGET_H +#define QGSPOINTCLUSTERRENDERERWIDGET_H + +#include "ui_qgspointclusterrendererwidgetbase.h" +#include "qgsrendererwidget.h" + +class QgsPointClusterRenderer; + +class GUI_EXPORT QgsPointClusterRendererWidget: public QgsRendererWidget, private Ui::QgsPointClusterRendererWidgetBase +{ + Q_OBJECT + public: + static QgsRendererWidget* create( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); + QgsPointClusterRendererWidget( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); + ~QgsPointClusterRendererWidget(); + + QgsFeatureRenderer* renderer() override; + void setMapCanvas( QgsMapCanvas* canvas ) override; + + private: + QgsPointClusterRenderer* mRenderer; + + void blockAllSignals( bool block ); + void updateCenterIcon(); + void setupBlankUi( const QString& layerName ); + + private slots: + + void on_mRendererComboBox_currentIndexChanged( int index ); + void on_mDistanceSpinBox_valueChanged( double d ); + void on_mDistanceUnitWidget_changed(); + void on_mCenterSymbolPushButton_clicked(); + void on_mRendererSettingsButton_clicked(); + void updateCenterSymbolFromWidget(); + void cleanUpSymbolSelector( QgsPanelWidget* container ); + void updateRendererFromWidget(); +}; + +#endif // QGSPOINTCLUSTERRENDERERWIDGET_H diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index c6c70478e85e..efddd17b1715 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -90,7 +90,7 @@ QgsPointDisplacementRendererWidget::QgsPointDisplacementRendererWidget( QgsVecto QStringList::const_iterator it = rendererList.constBegin(); for ( ; it != rendererList.constEnd(); ++it ) { - if ( *it != "pointDisplacement" ) + if ( *it != "pointDisplacement" && *it != "pointCluster" && *it != "heatmapRenderer" ) { QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( *it ); mRendererComboBox->addItem( m->icon(), m->visibleName(), *it ); diff --git a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp index 851708fc3271..662228923049 100644 --- a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp +++ b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp @@ -23,6 +23,7 @@ #include "qgsgraduatedsymbolrendererwidget.h" #include "qgsrulebasedrendererwidget.h" #include "qgspointdisplacementrendererwidget.h" +#include "qgspointclusterrendererwidget.h" #include "qgsinvertedpolygonrendererwidget.h" #include "qgsheatmaprendererwidget.h" #include "qgs25drendererwidget.h" @@ -73,6 +74,7 @@ static void _initRendererWidgetFunctions() _initRenderer( "graduatedSymbol", QgsGraduatedSymbolRendererWidget::create, "rendererGraduatedSymbol.svg" ); _initRenderer( "RuleRenderer", QgsRuleBasedRendererWidget::create, "rendererRuleBasedSymbol.svg" ); _initRenderer( "pointDisplacement", QgsPointDisplacementRendererWidget::create, "rendererPointDisplacementSymbol.svg" ); + _initRenderer( "pointCluster", QgsPointClusterRendererWidget::create, "rendererPointDisplacementSymbol.svg" ); _initRenderer( "invertedPolygonRenderer", QgsInvertedPolygonRendererWidget::create, "rendererInvertedSymbol.svg" ); _initRenderer( "heatmapRenderer", QgsHeatmapRendererWidget::create, "rendererHeatmapSymbol.svg" ); _initRenderer( "25dRenderer", Qgs25DRendererWidget::create, "renderer25dSymbol.svg" ); diff --git a/src/ui/qgspointdisplacementrendererwidgetbase.ui b/src/ui/qgspointdisplacementrendererwidgetbase.ui index 468fb7a7fb7d..b2c0736abd4e 100644 --- a/src/ui/qgspointdisplacementrendererwidgetbase.ui +++ b/src/ui/qgspointdisplacementrendererwidgetbase.ui @@ -14,7 +14,16 @@ Form - + + 0 + + + 0 + + + 0 + + 0 @@ -218,7 +227,7 @@ - Point distance tolerance + Distance @@ -256,12 +265,6 @@ - - QgsColorButton - QToolButton -
      qgscolorbutton.h
      - 1 -
      QgsDoubleSpinBox QDoubleSpinBox @@ -273,6 +276,12 @@
      qgsunitselectionwidget.h
      1
      + + QgsColorButton + QToolButton +
      qgscolorbutton.h
      + 1 +
      QgsCollapsibleGroupBoxBasic QGroupBox diff --git a/src/ui/symbollayer/qgspointclusterrendererwidgetbase.ui b/src/ui/symbollayer/qgspointclusterrendererwidgetbase.ui new file mode 100644 index 000000000000..e93debe9256a --- /dev/null +++ b/src/ui/symbollayer/qgspointclusterrendererwidgetbase.ui @@ -0,0 +1,125 @@ + + + QgsPointClusterRendererWidgetBase + + + + 0 + 0 + 381 + 492 + + + + Form + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + Distance + + + + + + + Renderer settings... + + + + + + + + + 7 + + + 999999999.000000000000000 + + + + + + + Qt::StrongFocus + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Renderer + + + + + + + Cluster symbol + + + + + + + + QgsDoubleSpinBox + QDoubleSpinBox +
      qgsdoublespinbox.h
      +
      + + QgsUnitSelectionWidget + QWidget +
      qgsunitselectionwidget.h
      + 1 +
      +
      + + mCenterSymbolPushButton + mRendererComboBox + mRendererSettingsButton + mDistanceSpinBox + mDistanceUnitWidget + + + +
      From 3aeef8d0158487b00b6a4d5e3b0a86903d8eb58f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 7 Sep 2016 16:06:16 +1000 Subject: [PATCH 017/897] Use group centroid for nearest group test --- src/core/symbology-ng/qgspointdistancerenderer.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index 3e61d6c31813..c27269a7ae4f 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -114,6 +114,11 @@ bool QgsPointDistanceRenderer::renderFeature( QgsFeature& feature, QgsRenderCont int groupIdx = mGroupIndex[ minDistFeatureId ]; ClusteredGroup& group = mClusteredGroups[groupIdx]; + // calculate new centroid of group + QgsPoint oldCenter = mGroupLocations.value( minDistFeatureId ); + mGroupLocations[ minDistFeatureId ] = QgsPoint(( oldCenter.x() * group.size() + point.x() ) / ( group.size() + 1.0 ), + ( oldCenter.y() * group.size() + point.y() ) / ( group.size() + 1.0 ) ); + // add to a group group << GroupedFeature( feature, symbol, selected, label ); // add to group index From 3f590f00355dbd325fc930032973a1a4c3612f14 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 09:39:44 +1000 Subject: [PATCH 018/897] Make distance based renderers much faster when filters are present --- python/core/symbology-ng/qgspointdistancerenderer.sip | 1 + src/core/symbology-ng/qgspointdistancerenderer.cpp | 8 ++++++++ src/core/symbology-ng/qgspointdistancerenderer.h | 1 + 3 files changed, 10 insertions(+) diff --git a/python/core/symbology-ng/qgspointdistancerenderer.sip b/python/core/symbology-ng/qgspointdistancerenderer.sip index b01693725589..d5913597a962 100644 --- a/python/core/symbology-ng/qgspointdistancerenderer.sip +++ b/python/core/symbology-ng/qgspointdistancerenderer.sip @@ -68,6 +68,7 @@ class QgsPointDistanceRenderer : QgsFeatureRenderer bool legendSymbolItemsCheckable() const; bool legendSymbolItemChecked( const QString& key ); void checkLegendSymbolItem( const QString& key, bool state ); + virtual QString filter( const QgsFields& fields = QgsFields() ); /** Sets the attribute name for labeling points. * @param name attribute name, or empty string to avoid labeling features by the renderer diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index c27269a7ae4f..e23c836ab47e 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -185,6 +185,14 @@ void QgsPointDistanceRenderer::checkLegendSymbolItem( const QString& key, bool s return mRenderer->checkLegendSymbolItem( key, state ); } +QString QgsPointDistanceRenderer::filter( const QgsFields& fields ) +{ + if ( !mRenderer ) + return QgsFeatureRenderer::filter( fields ); + else + return mRenderer->filter( fields ); +} + QList QgsPointDistanceRenderer::usedAttributes() { QList attributeList; diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index dc04143e9177..673b658b36da 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -94,6 +94,7 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer bool legendSymbolItemsCheckable() const override; bool legendSymbolItemChecked( const QString& key ) override; void checkLegendSymbolItem( const QString& key, bool state ) override; + virtual QString filter( const QgsFields& fields = QgsFields() ) override; /** Sets the attribute name for labeling points. * @param name attribute name, or empty string to avoid labeling features by the renderer From d27e55630bbff5b412a8c80f85ce7b3b62911dd5 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 10:20:22 +1000 Subject: [PATCH 019/897] Keep as many settings as possible when changing between displacement and cluster renderer --- .../symbology-ng/qgspointclusterrenderer.cpp | 28 +++++++++++++++---- .../qgspointdisplacementrenderer.cpp | 28 +++++++++++++++---- 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index fe3d685e1313..5a658b9f7571 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -16,6 +16,7 @@ ***************************************************************************/ #include "qgspointclusterrenderer.h" +#include "qgspointdisplacementrenderer.h" #include "qgssymbollayerutils.h" #include "qgspainteffectregistry.h" #include "qgspainteffect.h" @@ -189,15 +190,30 @@ QgsPointClusterRenderer* QgsPointClusterRenderer::convertFromRenderer( const Qgs { return dynamic_cast( renderer->clone() ); } - - if ( renderer->type() == "singleSymbol" || - renderer->type() == "categorizedSymbol" || - renderer->type() == "graduatedSymbol" || - renderer->type() == "RuleRenderer" ) + else if ( renderer->type() == "singleSymbol" || + renderer->type() == "categorizedSymbol" || + renderer->type() == "graduatedSymbol" || + renderer->type() == "RuleRenderer" ) { QgsPointClusterRenderer* pointRenderer = new QgsPointClusterRenderer(); pointRenderer->setEmbeddedRenderer( renderer->clone() ); return pointRenderer; } - return nullptr; + else if ( renderer->type() == "pointDisplacement" ) + { + QgsPointClusterRenderer* pointRenderer = new QgsPointClusterRenderer(); + const QgsPointDisplacementRenderer* displacementRenderer = static_cast< const QgsPointDisplacementRenderer* >( renderer ); + if ( displacementRenderer->embeddedRenderer() ) + pointRenderer->setEmbeddedRenderer( displacementRenderer->embeddedRenderer()->clone() ); + pointRenderer->setTolerance( displacementRenderer->tolerance() ); + pointRenderer->setToleranceUnit( displacementRenderer->toleranceUnit() ); + pointRenderer->setToleranceMapUnitScale( displacementRenderer->toleranceMapUnitScale() ); + if ( const_cast< QgsPointDisplacementRenderer* >( displacementRenderer )->centerSymbol() ) + pointRenderer->setClusterSymbol( const_cast< QgsPointDisplacementRenderer* >( displacementRenderer )->centerSymbol()->clone() ); + return pointRenderer; + } + else + { + return nullptr; + } } diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index df2ed204cf0b..298738d5dbbb 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -20,6 +20,7 @@ #include "qgsfontutils.h" #include "qgspainteffectregistry.h" #include "qgspainteffect.h" +#include "qgspointclusterrenderer.h" #include #include @@ -328,15 +329,30 @@ QgsPointDisplacementRenderer* QgsPointDisplacementRenderer::convertFromRenderer( { return dynamic_cast( renderer->clone() ); } - - if ( renderer->type() == "singleSymbol" || - renderer->type() == "categorizedSymbol" || - renderer->type() == "graduatedSymbol" || - renderer->type() == "RuleRenderer" ) + else if ( renderer->type() == "singleSymbol" || + renderer->type() == "categorizedSymbol" || + renderer->type() == "graduatedSymbol" || + renderer->type() == "RuleRenderer" ) { QgsPointDisplacementRenderer* pointRenderer = new QgsPointDisplacementRenderer(); pointRenderer->setEmbeddedRenderer( renderer->clone() ); return pointRenderer; } - return nullptr; + else if ( renderer->type() == "pointCluster" ) + { + QgsPointDisplacementRenderer* pointRenderer = new QgsPointDisplacementRenderer(); + const QgsPointClusterRenderer* clusterRenderer = static_cast< const QgsPointClusterRenderer* >( renderer ); + if ( clusterRenderer->embeddedRenderer() ) + pointRenderer->setEmbeddedRenderer( clusterRenderer->embeddedRenderer()->clone() ); + pointRenderer->setTolerance( clusterRenderer->tolerance() ); + pointRenderer->setToleranceUnit( clusterRenderer->toleranceUnit() ); + pointRenderer->setToleranceMapUnitScale( clusterRenderer->toleranceMapUnitScale() ); + if ( const_cast< QgsPointClusterRenderer* >( clusterRenderer )->clusterSymbol() ) + pointRenderer->setCenterSymbol( const_cast< QgsPointClusterRenderer* >( clusterRenderer )->clusterSymbol()->clone() ); + return pointRenderer; + } + else + { + return nullptr; + } } From 3253cdc2fba8310bd71bc8b4f6de5c14e5128723 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 8 Sep 2016 06:07:07 +1000 Subject: [PATCH 020/897] Unit tests for displacement and cluster renderer --- tests/src/python/CMakeLists.txt | 2 + .../python/test_qgspointclusterrenderer.py | 167 +++++++++++++++ .../test_qgspointdisplacementrenderer.py | 190 ++++++++++++++++++ .../expected_cluster_cluster.png | Bin 0 -> 2819 bytes .../expected_cluster_no_cluster.png | Bin 0 -> 2560 bytes .../expected_displacement_cluster.png | Bin 0 -> 7553 bytes .../expected_displacement_no_cluster.png | Bin 0 -> 2560 bytes 7 files changed, 359 insertions(+) create mode 100644 tests/src/python/test_qgspointclusterrenderer.py create mode 100644 tests/src/python/test_qgspointdisplacementrenderer.py create mode 100644 tests/testdata/control_images/cluster_renderer/expected_cluster_cluster/expected_cluster_cluster.png create mode 100644 tests/testdata/control_images/cluster_renderer/expected_cluster_no_cluster/expected_cluster_no_cluster.png create mode 100644 tests/testdata/control_images/displacement_renderer/expected_displacement_cluster/expected_displacement_cluster.png create mode 100644 tests/testdata/control_images/displacement_renderer/expected_displacement_no_cluster/expected_displacement_no_cluster.png diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 8e66b7d5d195..1c7a12dd01f1 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -69,6 +69,8 @@ ADD_PYTHON_TEST(PyQgsPalLabelingComposer test_qgspallabeling_composer.py) ADD_PYTHON_TEST(PyQgsPalLabelingPlacement test_qgspallabeling_placement.py) ADD_PYTHON_TEST(PyQgsPanelWidget test_qgspanelwidget.py) ADD_PYTHON_TEST(PyQgsPoint test_qgspoint.py) +ADD_PYTHON_TEST(PyQgsPointClusterRenderer test_qgspointclusterrenderer.py) +ADD_PYTHON_TEST(PyQgsPointDisplacementRenderer test_qgspointdisplacementrenderer.py) ADD_PYTHON_TEST(PyQgsRangeWidgets test_qgsrangewidgets.py) ADD_PYTHON_TEST(PyQgsRasterFileWriter test_qgsrasterfilewriter.py) ADD_PYTHON_TEST(PyQgsRasterLayer test_qgsrasterlayer.py) diff --git a/tests/src/python/test_qgspointclusterrenderer.py b/tests/src/python/test_qgspointclusterrenderer.py new file mode 100644 index 000000000000..20d404f8c9ef --- /dev/null +++ b/tests/src/python/test_qgspointclusterrenderer.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + test_qgspointclusterrenderer.py + ----------------------------- + Date : September 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'September 2016' +__copyright__ = '(C) 2016, Nyall Dawson' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import os + +from qgis.PyQt.QtCore import QSize +from qgis.PyQt.QtGui import QColor +from qgis.PyQt.QtXml import (QDomDocument, QDomElement) + +from qgis.core import (QgsVectorLayer, + QgsMapLayerRegistry, + QgsRectangle, + QgsMultiRenderChecker, + QgsPointClusterRenderer, + QgsFontUtils, + QgsUnitTypes, + QgsMapUnitScale, + QgsMarkerSymbol, + QgsSingleSymbolRenderer, + QgsPointDisplacementRenderer, + QgsMapSettings + ) +from qgis.testing import start_app, unittest +from utilities import (unitTestDataPath) + +# Convenience instances in case you may need them +# not used in this test +start_app() +TEST_DATA_DIR = unitTestDataPath() + + +class TestQgsPointClusterRenderer(unittest.TestCase): + + def setUp(self): + myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') + self.layer = QgsVectorLayer(myShpFile, 'Points', 'ogr') + QgsMapLayerRegistry.instance().addMapLayer(self.layer) + + self.renderer = QgsPointClusterRenderer() + sym1 = QgsMarkerSymbol.createSimple({'color': '#ff00ff', 'size': '3', 'outline_style': 'no'}) + renderer = QgsSingleSymbolRenderer(sym1) + self.renderer.setEmbeddedRenderer(renderer) + self.renderer.setClusterSymbol(QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'})) + self.layer.setRenderer(self.renderer) + + rendered_layers = [self.layer.id()] + self.mapsettings = QgsMapSettings() + self.mapsettings.setOutputSize(QSize(400, 400)) + self.mapsettings.setOutputDpi(96) + self.mapsettings.setExtent(QgsRectangle(-123, 18, -70, 52)) + self.mapsettings.setLayers(rendered_layers) + + def tearDown(self): + QgsMapLayerRegistry.instance().removeAllMapLayers() + + def _setProperties(self, r): + """ set properties for a renderer for testing with _checkProperties""" + r.setTolerance(5) + r.setToleranceUnit(QgsUnitTypes.RenderMapUnits) + r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15)) + m = QgsMarkerSymbol() + m.setColor(QColor(0, 255, 0)) + r.setClusterSymbol(m) + sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'}) + renderer = QgsSingleSymbolRenderer(sym1) + r.setEmbeddedRenderer(renderer) + + def _checkProperties(self, r): + """ test properties of renderer against expected""" + self.assertEqual(r.tolerance(), 5) + self.assertEqual(r.toleranceUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(r.toleranceMapUnitScale(), QgsMapUnitScale(5, 15)) + self.assertEqual(r.clusterSymbol().color(), QColor(0, 255, 0)) + self.assertEqual(r.embeddedRenderer().symbol().color().name(), '#fdbf6f') + + def testGettersSetters(self): + """ test getters and setters """ + r = QgsPointClusterRenderer() + self._setProperties(r) + self._checkProperties(r) + + def testClone(self): + """ test cloning renderer """ + r = QgsPointClusterRenderer() + self._setProperties(r) + c = r.clone() + self._checkProperties(c) + + def testSaveCreate(self): + """ test saving and recreating from XML """ + r = QgsPointClusterRenderer() + self._setProperties(r) + doc = QDomDocument("testdoc") + elem = r.save(doc) + c = QgsPointClusterRenderer.create(elem) + self._checkProperties(c) + + def testConvert(self): + """ test renderer conversion """ + + # same type, should clone + r = QgsPointClusterRenderer() + self._setProperties(r) + c = QgsPointClusterRenderer.convertFromRenderer(r) + self._checkProperties(c) + + # test conversion from displacement renderer + r = QgsPointDisplacementRenderer() + r.setTolerance(5) + r.setToleranceUnit(QgsUnitTypes.RenderMapUnits) + r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15)) + m = QgsMarkerSymbol() + m.setColor(QColor(0, 255, 0)) + r.setCenterSymbol(m) + sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'}) + renderer = QgsSingleSymbolRenderer(sym1) + r.setEmbeddedRenderer(renderer) + + # want to keep as many settings as possible when converting between cluster and displacement renderer + d = QgsPointClusterRenderer.convertFromRenderer(r) + self.assertEqual(d.tolerance(), 5) + self.assertEqual(d.toleranceUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(d.toleranceMapUnitScale(), QgsMapUnitScale(5, 15)) + self.assertEqual(d.clusterSymbol().color(), QColor(0, 255, 0)) + self.assertEqual(d.embeddedRenderer().symbol().color().name(), '#fdbf6f') + + def testRenderNoCluster(self): + self.layer.renderer().setTolerance(1) + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(self.mapsettings) + renderchecker.setControlPathPrefix('cluster_renderer') + renderchecker.setControlName('expected_cluster_no_cluster') + self.assertTrue(renderchecker.runTest('cluster_no_cluster')) + + def testRenderWithin(self): + self.layer.renderer().setTolerance(10) + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(self.mapsettings) + renderchecker.setControlPathPrefix('cluster_renderer') + renderchecker.setControlName('expected_cluster_cluster') + self.assertTrue(renderchecker.runTest('expected_cluster_cluster')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/src/python/test_qgspointdisplacementrenderer.py b/tests/src/python/test_qgspointdisplacementrenderer.py new file mode 100644 index 000000000000..ec5a43141cde --- /dev/null +++ b/tests/src/python/test_qgspointdisplacementrenderer.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + test_qgspointdisplacementrenderer.py + ----------------------------- + Date : September 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'September 2016' +__copyright__ = '(C) 2016, Nyall Dawson' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +import os + +from qgis.PyQt.QtGui import QColor +from qgis.PyQt.QtCore import QSize +from qgis.PyQt.QtXml import (QDomDocument, QDomElement) + +from qgis.core import (QgsVectorLayer, + QgsMapLayerRegistry, + QgsRectangle, + QgsMultiRenderChecker, + QgsPointDisplacementRenderer, + QgsFontUtils, + QgsUnitTypes, + QgsMapUnitScale, + QgsMarkerSymbol, + QgsSingleSymbolRenderer, + QgsPointClusterRenderer, + QgsMapSettings + ) +from qgis.testing import start_app, unittest +from utilities import (unitTestDataPath) + +# Convenience instances in case you may need them +# not used in this test +start_app() +TEST_DATA_DIR = unitTestDataPath() + + +class TestQgsPointDisplacementRenderer(unittest.TestCase): + + def setUp(self): + myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp') + self.layer = QgsVectorLayer(myShpFile, 'Points', 'ogr') + QgsMapLayerRegistry.instance().addMapLayer(self.layer) + + self.renderer = QgsPointDisplacementRenderer() + sym1 = QgsMarkerSymbol.createSimple({'color': '#ff00ff', 'size': '3', 'outline_style': 'no'}) + renderer = QgsSingleSymbolRenderer(sym1) + self.renderer.setEmbeddedRenderer(renderer) + self.renderer.setCircleRadiusAddition(2) + self.renderer.setCircleWidth(1) + self.renderer.setCircleColor(QColor(0, 0, 0)) + self.renderer.setCenterSymbol(QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'})) + self.layer.setRenderer(self.renderer) + + rendered_layers = [self.layer.id()] + self.mapsettings = QgsMapSettings() + self.mapsettings.setOutputSize(QSize(400, 400)) + self.mapsettings.setOutputDpi(96) + self.mapsettings.setExtent(QgsRectangle(-123, 18, -70, 52)) + self.mapsettings.setLayers(rendered_layers) + + def tearDown(self): + QgsMapLayerRegistry.instance().removeAllMapLayers() + + def _setProperties(self, r): + """ set properties for a renderer for testing with _checkProperties""" + r.setLabelAttributeName('name') + f = QgsFontUtils.getStandardTestFont('Bold Oblique', 14) + r.setLabelFont(f) + r.setMaxLabelScaleDenominator(50000) + r.setLabelColor(QColor(255, 0, 0)) + r.setTolerance(5) + r.setToleranceUnit(QgsUnitTypes.RenderMapUnits) + r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15)) + r.setCircleWidth(15) + r.setCircleColor(QColor(0, 255, 0)) + r.setCircleRadiusAddition(2.5) + r.setPlacement(QgsPointDisplacementRenderer.ConcentricRings) + m = QgsMarkerSymbol() + m.setColor(QColor(0, 255, 0)) + r.setCenterSymbol(m) + sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'}) + renderer = QgsSingleSymbolRenderer(sym1) + r.setEmbeddedRenderer(renderer) + + def _checkProperties(self, r): + """ test properties of renderer against expected""" + self.assertEqual(r.labelAttributeName(), 'name') + f = QgsFontUtils.getStandardTestFont('Bold Oblique', 14) + self.assertEqual(r.labelFont().styleName(), f.styleName()) + self.assertEqual(r.maxLabelScaleDenominator(), 50000) + self.assertEqual(r.labelColor(), QColor(255, 0, 0)) + self.assertEqual(r.tolerance(), 5) + self.assertEqual(r.toleranceUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(r.toleranceMapUnitScale(), QgsMapUnitScale(5, 15)) + self.assertEqual(r.circleWidth(), 15) + self.assertEqual(r.circleColor(), QColor(0, 255, 0)) + self.assertEqual(r.circleRadiusAddition(), 2.5) + self.assertEqual(r.placement(), QgsPointDisplacementRenderer.ConcentricRings) + self.assertEqual(r.centerSymbol().color(), QColor(0, 255, 0)) + self.assertEqual(r.embeddedRenderer().symbol().color().name(), '#fdbf6f') + + def testGettersSetters(self): + """ test getters and setters """ + r = QgsPointDisplacementRenderer() + self._setProperties(r) + self._checkProperties(r) + + def testClone(self): + """ test cloning renderer """ + r = QgsPointDisplacementRenderer() + self._setProperties(r) + c = r.clone() + self._checkProperties(c) + + def testSaveCreate(self): + """ test saving and recreating from XML """ + r = QgsPointDisplacementRenderer() + self._setProperties(r) + doc = QDomDocument("testdoc") + elem = r.save(doc) + c = QgsPointDisplacementRenderer.create(elem) + self._checkProperties(c) + + def testConvert(self): + """ test renderer conversion """ + + # same type, should clone + r = QgsPointDisplacementRenderer() + self._setProperties(r) + c = QgsPointDisplacementRenderer.convertFromRenderer(r) + self._checkProperties(c) + + # test conversion from cluster renderer + r = QgsPointClusterRenderer() + r.setTolerance(5) + r.setToleranceUnit(QgsUnitTypes.RenderMapUnits) + r.setToleranceMapUnitScale(QgsMapUnitScale(5, 15)) + m = QgsMarkerSymbol() + m.setColor(QColor(0, 255, 0)) + r.setClusterSymbol(m) + sym1 = QgsMarkerSymbol.createSimple({'color': '#fdbf6f'}) + renderer = QgsSingleSymbolRenderer(sym1) + r.setEmbeddedRenderer(renderer) + + # want to keep as many settings as possible when converting between cluster and displacement renderer + d = QgsPointDisplacementRenderer.convertFromRenderer(r) + self.assertEqual(d.tolerance(), 5) + self.assertEqual(d.toleranceUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(d.toleranceMapUnitScale(), QgsMapUnitScale(5, 15)) + self.assertEqual(d.centerSymbol().color(), QColor(0, 255, 0)) + self.assertEqual(d.embeddedRenderer().symbol().color().name(), '#fdbf6f') + + def testRenderNoCluster(self): + self.layer.renderer().setTolerance(1) + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(self.mapsettings) + renderchecker.setControlPathPrefix('displacement_renderer') + renderchecker.setControlName('expected_displacement_no_cluster') + self.assertTrue(renderchecker.runTest('displacement_no_cluster')) + + def testRenderWithin(self): + self.layer.renderer().setTolerance(10) + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(self.mapsettings) + renderchecker.setControlPathPrefix('displacement_renderer') + renderchecker.setControlName('expected_displacement_cluster') + self.assertTrue(renderchecker.runTest('expected_displacement_cluster')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/testdata/control_images/cluster_renderer/expected_cluster_cluster/expected_cluster_cluster.png b/tests/testdata/control_images/cluster_renderer/expected_cluster_cluster/expected_cluster_cluster.png new file mode 100644 index 0000000000000000000000000000000000000000..2d05b72653f48dca7191fb9bdd3c54f8df308fac GIT binary patch literal 2819 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 aUx2wE>>er)TdfJkRmjf9316`LDC18nq_c+r literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/cluster_renderer/expected_cluster_no_cluster/expected_cluster_no_cluster.png b/tests/testdata/control_images/cluster_renderer/expected_cluster_no_cluster/expected_cluster_no_cluster.png new file mode 100644 index 0000000000000000000000000000000000000000..edb92ca9429f5c9a2c04f4dad6d7e650585d9767 GIT binary patch literal 2560 zcmcImXH*mE8lFIwB&@W^B1K3<+>3ySNEHYPgb)+~0i{U?DN-~b7D{4tMMNYP7Fnb> z8%uMgV>~FmND(Ok1OW+B7AaYbA^Sz|x%ckgvp?>+_nvv@%*-=0-}`>g_s;W7f}M?} zn5euc1VLg}WTHI;!ScZ_ixdIKRwCU997KE$SrQ?>V9TyAx(yK2DY8oh1bv$z*kSsu z?Zp5@L|PrTK)gk5fiQA90d2p4$C9jw1jlp33#0oS zMlN9?g|n;oC$p1Ai7`K@ch7bljf$bG-;z^xF!P?)ns_VvvX?gshG~1e zoagGZ?(Ntin4_J4BX2r2QbIz5Ph!ySfdXW8%g6PDiL1$v%gq78S~#2+t=$#l$>9wO zmxI(LW6LUGUCj~QcSuQB(^pQfjvX-aiB`c}*y;H!8^16G-ITQf|!dUaw`=Tn9iC@t0iqCXMoy9(%7sBoPhi{tiA zytIk5ZR#<~B&y)lAVS-b586rkOEXmI+RD>>*N>9BAWGR9hcS0aWjJ8SJuGV=7kBC! z97{F~@+h#??Avp|A=txBSO@_BULjOcE3TQWTEt4Vm9^?W&P>02$8Uu;$;t25s8 z2h&1*k2D@ia~0b=6Q?1ibp4xyO!FCHl^@~`ja!C9+kq!R)plxECPmSZba39WA-NhP zmi$sXQVP##W4^MW&8hR$jLf&e;18s?xWgs$?X?8AAUxy5*UM6r5)GR|&q)L=B7a3w z$Z?$1S*}i*%`LM4$Yad)J@UHBZ^|r`kw|p1D^*j;O(!CvVY1BP8YLcH zsQznv{Pgv zcYnp+l4mk{wc#ViXRCR`n=+u98f2JZ`$En+&8xydMr3{*F<(Ajeo1vEZU4vV^W~ks zDT>CbevhOOyw@wnY1rpY6|4p{BGyv_j(WIOJWk;z8P7&%hE!C?!^g{5IBxc{`Am0D zj}lJy5_tPWiX!6!ftq1#`#qT{bNZDf1JXX1Y0ZETJp1jd+>BOM>*sO7xUlc+W-c`> zxWQ3_%KoOaCD9W5k2Ob-nJb}8^B0+a+p6M~XfV5z3_0G2{)3+5cMrwo`aNt|C=V^T zXraN?Onew#8{!tklhP|1r zy~Jd{7lsEVI>sVwjIIj_jH9gX>lk>39`SXh`_p0_ELkCUZbWnBn7m}ZnEhI4YN)!H z-@XSqAhB?fA_+zi%I-g2F8rmPARv_>;3z>5gg|)h?2myPTgEboD{8T<$nYxDq`2l; z44&bf8bk!Dw(hdf8Z{Na&8Wvj&T{D-+Pl#S&uDS@s(1YA`LQP6$yW0_P#is)>?d%V zEPv|RpuYz8>wK~#Az*Yk-U57y|0l=&V%xyH@h*VHsbU;C_k2pzqi!oAaSNxY zXUTdpEPSpJ22aqvOM0T&7nt?hhqFGC3cje^Xzd%ojL9yiKN~Grvh2%$-AjMbV*eTZr7eK+L8|FgnCH0D V)Y}#f5Ad%BSy|W+e>U@?{|<+JIClU5 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/displacement_renderer/expected_displacement_cluster/expected_displacement_cluster.png b/tests/testdata/control_images/displacement_renderer/expected_displacement_cluster/expected_displacement_cluster.png new file mode 100644 index 0000000000000000000000000000000000000000..c77e051dab12938910f148090a8ae26f81cb98a2 GIT binary patch literal 7553 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 aC|#YFY$TsT85ov=)So_Au6pwF-G2d4zcf$) literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/displacement_renderer/expected_displacement_no_cluster/expected_displacement_no_cluster.png b/tests/testdata/control_images/displacement_renderer/expected_displacement_no_cluster/expected_displacement_no_cluster.png new file mode 100644 index 0000000000000000000000000000000000000000..edb92ca9429f5c9a2c04f4dad6d7e650585d9767 GIT binary patch literal 2560 zcmcImXH*mE8lFIwB&@W^B1K3<+>3ySNEHYPgb)+~0i{U?DN-~b7D{4tMMNYP7Fnb> z8%uMgV>~FmND(Ok1OW+B7AaYbA^Sz|x%ckgvp?>+_nvv@%*-=0-}`>g_s;W7f}M?} zn5euc1VLg}WTHI;!ScZ_ixdIKRwCU997KE$SrQ?>V9TyAx(yK2DY8oh1bv$z*kSsu z?Zp5@L|PrTK)gk5fiQA90d2p4$C9jw1jlp33#0oS zMlN9?g|n;oC$p1Ai7`K@ch7bljf$bG-;z^xF!P?)ns_VvvX?gshG~1e zoagGZ?(Ntin4_J4BX2r2QbIz5Ph!ySfdXW8%g6PDiL1$v%gq78S~#2+t=$#l$>9wO zmxI(LW6LUGUCj~QcSuQB(^pQfjvX-aiB`c}*y;H!8^16G-ITQf|!dUaw`=Tn9iC@t0iqCXMoy9(%7sBoPhi{tiA zytIk5ZR#<~B&y)lAVS-b586rkOEXmI+RD>>*N>9BAWGR9hcS0aWjJ8SJuGV=7kBC! z97{F~@+h#??Avp|A=txBSO@_BULjOcE3TQWTEt4Vm9^?W&P>02$8Uu;$;t25s8 z2h&1*k2D@ia~0b=6Q?1ibp4xyO!FCHl^@~`ja!C9+kq!R)plxECPmSZba39WA-NhP zmi$sXQVP##W4^MW&8hR$jLf&e;18s?xWgs$?X?8AAUxy5*UM6r5)GR|&q)L=B7a3w z$Z?$1S*}i*%`LM4$Yad)J@UHBZ^|r`kw|p1D^*j;O(!CvVY1BP8YLcH zsQznv{Pgv zcYnp+l4mk{wc#ViXRCR`n=+u98f2JZ`$En+&8xydMr3{*F<(Ajeo1vEZU4vV^W~ks zDT>CbevhOOyw@wnY1rpY6|4p{BGyv_j(WIOJWk;z8P7&%hE!C?!^g{5IBxc{`Am0D zj}lJy5_tPWiX!6!ftq1#`#qT{bNZDf1JXX1Y0ZETJp1jd+>BOM>*sO7xUlc+W-c`> zxWQ3_%KoOaCD9W5k2Ob-nJb}8^B0+a+p6M~XfV5z3_0G2{)3+5cMrwo`aNt|C=V^T zXraN?Onew#8{!tklhP|1r zy~Jd{7lsEVI>sVwjIIj_jH9gX>lk>39`SXh`_p0_ELkCUZbWnBn7m}ZnEhI4YN)!H z-@XSqAhB?fA_+zi%I-g2F8rmPARv_>;3z>5gg|)h?2myPTgEboD{8T<$nYxDq`2l; z44&bf8bk!Dw(hdf8Z{Na&8Wvj&T{D-+Pl#S&uDS@s(1YA`LQP6$yW0_P#is)>?d%V zEPv|RpuYz8>wK~#Az*Yk-U57y|0l=&V%xyH@h*VHsbU;C_k2pzqi!oAaSNxY zXUTdpEPSpJ22aqvOM0T&7nt?hhqFGC3cje^Xzd%ojL9yiKN~Grvh2%$-AjMbV*eTZr7eK+L8|FgnCH0D V)Y}#f5Ad%BSy|W+e>U@?{|<+JIClU5 literal 0 HcmV?d00001 From 7acb07f21884775ff6b136f2a5685de995160741 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 11:17:17 +1000 Subject: [PATCH 021/897] Make sure all attributes are fetched for distance based renderers --- python/core/symbology-ng/qgspointclusterrenderer.sip | 1 + python/core/symbology-ng/qgspointdisplacementrenderer.sip | 1 + src/core/symbology-ng/qgspointclusterrenderer.cpp | 8 ++++++++ src/core/symbology-ng/qgspointclusterrenderer.h | 1 + src/core/symbology-ng/qgspointdisplacementrenderer.cpp | 8 ++++++++ src/core/symbology-ng/qgspointdisplacementrenderer.h | 1 + 6 files changed, 20 insertions(+) diff --git a/python/core/symbology-ng/qgspointclusterrenderer.sip b/python/core/symbology-ng/qgspointclusterrenderer.sip index 8a645063d643..57e6a5308852 100644 --- a/python/core/symbology-ng/qgspointclusterrenderer.sip +++ b/python/core/symbology-ng/qgspointclusterrenderer.sip @@ -16,6 +16,7 @@ class QgsPointClusterRenderer : QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); void stopRender( QgsRenderContext& context ); QDomElement save( QDomDocument& doc ); + virtual QList usedAttributes(); //! Create a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; diff --git a/python/core/symbology-ng/qgspointdisplacementrenderer.sip b/python/core/symbology-ng/qgspointdisplacementrenderer.sip index 6a458901135c..966c3f6d17f4 100644 --- a/python/core/symbology-ng/qgspointdisplacementrenderer.sip +++ b/python/core/symbology-ng/qgspointdisplacementrenderer.sip @@ -26,6 +26,7 @@ class QgsPointDisplacementRenderer : QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); void stopRender( QgsRenderContext& context ); QDomElement save( QDomDocument& doc ); + virtual QList usedAttributes(); //! Create a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index 5a658b9f7571..7a5868a3f8f8 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -179,6 +179,14 @@ QDomElement QgsPointClusterRenderer::save( QDomDocument& doc ) return rendererElement; } +QList QgsPointClusterRenderer::usedAttributes() +{ + QList attr = QgsPointDistanceRenderer::usedAttributes(); + if ( mClusterSymbol ) + attr.append( mClusterSymbol->usedAttributes().toList() ); + return attr; +} + void QgsPointClusterRenderer::setClusterSymbol( QgsMarkerSymbol* symbol ) { mClusterSymbol.reset( symbol ); diff --git a/src/core/symbology-ng/qgspointclusterrenderer.h b/src/core/symbology-ng/qgspointclusterrenderer.h index e188db0f9893..575f03b1ad05 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.h +++ b/src/core/symbology-ng/qgspointclusterrenderer.h @@ -35,6 +35,7 @@ class CORE_EXPORT QgsPointClusterRenderer: public QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; QDomElement save( QDomDocument& doc ) override; + virtual QList usedAttributes() override; //! Creates a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ); diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index 298738d5dbbb..abe2c041a967 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -211,6 +211,14 @@ QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) return rendererElement; } +QList QgsPointDisplacementRenderer::usedAttributes() +{ + QList attr = QgsPointDistanceRenderer::usedAttributes(); + if ( mCenterSymbol ) + attr.append( mCenterSymbol->usedAttributes().toList() ); + return attr; +} + void QgsPointDisplacementRenderer::setCenterSymbol( QgsMarkerSymbol* symbol ) { mCenterSymbol.reset( symbol ); diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.h b/src/core/symbology-ng/qgspointdisplacementrenderer.h index fec85bb40907..f5a4f66d46fe 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.h +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.h @@ -45,6 +45,7 @@ class CORE_EXPORT QgsPointDisplacementRenderer: public QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; QDomElement save( QDomDocument& doc ) override; + virtual QList usedAttributes() override; //! Create a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ); From 1725182909db4df07bf6990e452ca2613d196fd0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 11:40:48 +1000 Subject: [PATCH 022/897] Make @cluster_size, @cluster_color usable in displacement renderer too --- .../symbology-ng/qgspointclusterrenderer.cpp | 34 -------------- .../qgspointdisplacementrenderer.cpp | 3 +- .../symbology-ng/qgspointdistancerenderer.cpp | 44 +++++++++++++++++++ .../symbology-ng/qgspointdistancerenderer.h | 6 +++ .../python/test_qgspointclusterrenderer.py | 21 ++++++++- .../test_qgspointdisplacementrenderer.py | 20 ++++++++- 6 files changed, 91 insertions(+), 37 deletions(-) diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index 7a5868a3f8f8..9f734be3a16c 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -55,40 +55,6 @@ void QgsPointClusterRenderer::drawGroup( QPointF centerPoint, QgsRenderContext& { if ( group.size() > 1 ) { - //scan through symbols to check color, eg if all clustered symbols are same color - QColor groupColor; - ClusteredGroup::const_iterator groupIt = group.constBegin(); - for ( ; groupIt != group.constEnd(); ++groupIt ) - { - if ( !groupIt->symbol ) - continue; - - if ( !groupColor.isValid() ) - { - groupColor = groupIt->symbol->color(); - } - else - { - if ( groupColor != groupIt->symbol->color() ) - { - groupColor = QColor(); - break; - } - } - } - - if ( groupColor.isValid() ) - { - context.expressionContext().lastScope()->setVariable( "cluster_color", QgsSymbolLayerUtils::encodeColor( groupColor ) ); - } - else - { - //mixed colors - context.expressionContext().lastScope()->setVariable( "cluster_color", "" ); - } - - //multiple clustered symbols, so draw just the cluster symbol - context.expressionContext().lastScope()->setVariable( "cluster_size", group.size() ); mClusterSymbol->renderPoint( centerPoint, &( group.at( 0 ).feature ), context, -1, false ); } else diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index abe2c041a967..66ff374a871e 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -64,6 +64,7 @@ QgsPointDisplacementRenderer* QgsPointDisplacementRenderer::clone() const void QgsPointDisplacementRenderer::drawGroup( QPointF centerPoint, QgsRenderContext& context, const ClusteredGroup& group ) { + //calculate max diagonal size from all symbols in group double diagonal = 0; @@ -88,9 +89,9 @@ void QgsPointDisplacementRenderer::drawGroup( QPointF centerPoint, QgsRenderCont if ( circleRadius > 0 ) drawCircle( circleRadius, symbolContext, centerPoint, group.size() ); - //draw mid point if ( group.size() > 1 ) { + //draw mid point QgsFeature firstFeature = group.at( 0 ).feature; if ( mCenterSymbol ) { diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index e23c836ab47e..f35c3368c51c 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -140,7 +140,9 @@ void QgsPointDistanceRenderer::drawGroup( const ClusteredGroup& group, QgsRender QgsGeometry centroid = groupGeom.centroid(); QPointF pt = _getPoint( context, *static_cast( centroid.geometry() ) ); + context.expressionContext().appendScope( createGroupScope( group ) ); drawGroup( pt, context, group ); + delete context.expressionContext().popScope(); } void QgsPointDistanceRenderer::setEmbeddedRenderer( QgsFeatureRenderer* r ) @@ -407,6 +409,48 @@ void QgsPointDistanceRenderer::drawLabels( QPointF centerPoint, QgsSymbolRenderC } } +QgsExpressionContextScope* QgsPointDistanceRenderer::createGroupScope( const ClusteredGroup& group ) const +{ + QgsExpressionContextScope* clusterScope = new QgsExpressionContextScope(); + if ( group.size() > 1 ) + { + //scan through symbols to check color, eg if all clustered symbols are same color + QColor groupColor; + ClusteredGroup::const_iterator groupIt = group.constBegin(); + for ( ; groupIt != group.constEnd(); ++groupIt ) + { + if ( !groupIt->symbol ) + continue; + + if ( !groupColor.isValid() ) + { + groupColor = groupIt->symbol->color(); + } + else + { + if ( groupColor != groupIt->symbol->color() ) + { + groupColor = QColor(); + break; + } + } + } + + if ( groupColor.isValid() ) + { + clusterScope->setVariable( "cluster_color", QgsSymbolLayerUtils::encodeColor( groupColor ) ); + } + else + { + //mixed colors + clusterScope->setVariable( "cluster_color", "" ); + } + + clusterScope->setVariable( "cluster_size", group.size() ); + } + return clusterScope; +} + QgsMarkerSymbol* QgsPointDistanceRenderer::firstSymbolForFeature( QgsFeature& feature, QgsRenderContext &context ) { if ( !mRenderer ) diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index 673b658b36da..81eb7b773c3f 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -276,6 +276,12 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer */ QgsMarkerSymbol* firstSymbolForFeature( QgsFeature& feature, QgsRenderContext& context ); + /** Creates an expression context scope for a clustered group, with variables reflecting the group's properties. + * @param group clustered group + * @returns new expression context scope + */ + QgsExpressionContextScope* createGroupScope( const ClusteredGroup& group ) const; + }; #endif // QGSPOINTDISTANCERENDERER_H diff --git a/tests/src/python/test_qgspointclusterrenderer.py b/tests/src/python/test_qgspointclusterrenderer.py index 20d404f8c9ef..6ae986493ad1 100644 --- a/tests/src/python/test_qgspointclusterrenderer.py +++ b/tests/src/python/test_qgspointclusterrenderer.py @@ -40,7 +40,8 @@ QgsMarkerSymbol, QgsSingleSymbolRenderer, QgsPointDisplacementRenderer, - QgsMapSettings + QgsMapSettings, + QgsDataDefined ) from qgis.testing import start_app, unittest from utilities import (unitTestDataPath) @@ -162,6 +163,24 @@ def testRenderWithin(self): renderchecker.setControlName('expected_cluster_cluster') self.assertTrue(renderchecker.runTest('expected_cluster_cluster')) + def testRenderVariables(self): + """ test rendering with expression variables in marker """ + self.layer.renderer().setTolerance(10) + + old_marker = self.layer.renderer().clusterSymbol().clone() + + new_marker = QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'}) + new_marker.symbolLayer(0).setDataDefinedProperty('color', QgsDataDefined('@cluster_color')) + new_marker.symbolLayer(0).setDataDefinedProperty('size', QgsDataDefined('@cluster_size*2')) + self.layer.renderer().setClusterSymbol(new_marker) + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(self.mapsettings) + renderchecker.setControlPathPrefix('cluster_renderer') + renderchecker.setControlName('expected_cluster_variables') + result = renderchecker.runTest('expected_cluster_variables') + self.layer.renderer().setClusterSymbol(old_marker) + self.assertTrue(result) + if __name__ == '__main__': unittest.main() diff --git a/tests/src/python/test_qgspointdisplacementrenderer.py b/tests/src/python/test_qgspointdisplacementrenderer.py index ec5a43141cde..b5637cadb7f8 100644 --- a/tests/src/python/test_qgspointdisplacementrenderer.py +++ b/tests/src/python/test_qgspointdisplacementrenderer.py @@ -42,7 +42,8 @@ QgsMarkerSymbol, QgsSingleSymbolRenderer, QgsPointClusterRenderer, - QgsMapSettings + QgsMapSettings, + QgsDataDefined ) from qgis.testing import start_app, unittest from utilities import (unitTestDataPath) @@ -185,6 +186,23 @@ def testRenderWithin(self): renderchecker.setControlName('expected_displacement_cluster') self.assertTrue(renderchecker.runTest('expected_displacement_cluster')) + def testRenderVariables(self): + """ test rendering with expression variables in marker """ + self.layer.renderer().setTolerance(10) + + old_marker = self.layer.renderer().centerSymbol().clone() + + new_marker = QgsMarkerSymbol.createSimple({'color': '#ffff00', 'size': '3', 'outline_style': 'no'}) + new_marker.symbolLayer(0).setDataDefinedProperty('color', QgsDataDefined('@cluster_color')) + new_marker.symbolLayer(0).setDataDefinedProperty('size', QgsDataDefined('@cluster_size*2')) + self.layer.renderer().setCenterSymbol(new_marker) + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(self.mapsettings) + renderchecker.setControlPathPrefix('displacement_renderer') + renderchecker.setControlName('expected_displacement_variables') + result = renderchecker.runTest('expected_displacement_variables') + self.layer.renderer().setCenterSymbol(old_marker) + self.assertTrue(result) if __name__ == '__main__': unittest.main() From 962a4e975f2c8211f83d784ed627afe33bcfdb77 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 13:51:14 +1000 Subject: [PATCH 023/897] Expose renderer variables to users --- python/core/qgsexpressioncontext.sip | 4 ++++ .../symbology-ng/qgslayerpropertieswidget.sip | 8 ++++++++ python/gui/symbology-ng/qgsrendererwidget.sip | 12 ++++++++++++ .../gui/symbology-ng/qgssymbollayerwidget.sip | 8 ++++++++ .../symbology-ng/qgssymbolselectordialog.sip | 16 ++++++++++++++++ .../gui/symbology-ng/qgssymbolslistwidget.sip | 6 ++++++ src/core/qgsexpression.cpp | 4 ++++ src/core/qgsexpressioncontext.cpp | 2 ++ src/core/qgsexpressioncontext.h | 4 ++++ .../symbology-ng/qgspointdistancerenderer.cpp | 6 +++--- .../qgscategorizedsymbolrendererwidget.cpp | 3 +++ .../qgsgraduatedsymbolrendererwidget.cpp | 2 ++ .../qgsinvertedpolygonrendererwidget.cpp | 1 + .../symbology-ng/qgslayerpropertieswidget.cpp | 10 ++++++++++ .../symbology-ng/qgslayerpropertieswidget.h | 11 ++++++++++- .../qgspointclusterrendererwidget.cpp | 12 ++++++++++++ .../qgspointdisplacementrendererwidget.cpp | 13 +++++++++++++ src/gui/symbology-ng/qgsrendererwidget.cpp | 14 ++++++++++++++ src/gui/symbology-ng/qgsrendererwidget.h | 19 +++++++++++++++++++ .../qgsrulebasedrendererwidget.cpp | 2 ++ src/gui/symbology-ng/qgssymbollayerwidget.cpp | 15 ++++++++++++++- src/gui/symbology-ng/qgssymbollayerwidget.h | 9 +++++++++ .../symbology-ng/qgssymbolselectordialog.cpp | 12 ++++++++++++ .../symbology-ng/qgssymbolselectordialog.h | 17 +++++++++++++++++ src/gui/symbology-ng/qgssymbolslistwidget.cpp | 11 +++++++++++ src/gui/symbology-ng/qgssymbolslistwidget.h | 7 +++++++ 26 files changed, 223 insertions(+), 5 deletions(-) diff --git a/python/core/qgsexpressioncontext.sip b/python/core/qgsexpressioncontext.sip index 98bf7514614f..f2712123675d 100644 --- a/python/core/qgsexpressioncontext.sip +++ b/python/core/qgsexpressioncontext.sip @@ -457,6 +457,10 @@ class QgsExpressionContext static const QString EXPR_GEOMETRY_PART_COUNT; //! Inbuilt variable name for geometry part number variable static const QString EXPR_GEOMETRY_PART_NUM; + //! Inbuilt variable name for cluster size variable + static const QString EXPR_CLUSTER_SIZE; + //! Inbuilt variable name for cluster color variable + static const QString EXPR_CLUSTER_COLOR; }; /** \ingroup core diff --git a/python/gui/symbology-ng/qgslayerpropertieswidget.sip b/python/gui/symbology-ng/qgslayerpropertieswidget.sip index ce4df812e6ef..a6f418e257a0 100644 --- a/python/gui/symbology-ng/qgslayerpropertieswidget.sip +++ b/python/gui/symbology-ng/qgslayerpropertieswidget.sip @@ -15,6 +15,13 @@ class QgsLayerPropertiesWidget : QgsPanelWidget */ QgsExpressionContext* expressionContext() const; + /** Sets a list of additional expression context scopes to show as available within the layer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -33,6 +40,7 @@ class QgsLayerPropertiesWidget : QgsPanelWidget * be kept alive for the lifetime of the properties widget. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context ); diff --git a/python/gui/symbology-ng/qgsrendererwidget.sip b/python/gui/symbology-ng/qgsrendererwidget.sip index b974a11b820d..4a256e77abb5 100644 --- a/python/gui/symbology-ng/qgsrendererwidget.sip +++ b/python/gui/symbology-ng/qgsrendererwidget.sip @@ -29,6 +29,12 @@ class QgsRendererWidget : QgsPanelWidget */ const QgsMapCanvas* mapCanvas() const; + /** Sets a list of additional expression context scopes to show as available within the renderer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 */ @@ -118,6 +124,12 @@ class QgsDataDefinedValueDialog : QDialog */ const QgsVectorLayer* vectorLayer() const; + /** Sets a list of additional expression context scopes to show as available for the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + public slots: void dataDefinedChanged(); diff --git a/python/gui/symbology-ng/qgssymbollayerwidget.sip b/python/gui/symbology-ng/qgssymbollayerwidget.sip index ad1febe4db17..dcf34eed6093 100644 --- a/python/gui/symbology-ng/qgssymbollayerwidget.sip +++ b/python/gui/symbology-ng/qgssymbollayerwidget.sip @@ -19,6 +19,13 @@ class QgsSymbolLayerWidget : QWidget */ QgsExpressionContext* expressionContext() const; + /** Sets a list of additional expression context scopes to show as available within the layer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -47,6 +54,7 @@ class QgsSymbolLayerWidget : QWidget * be kept alive for the lifetime of the layer widget. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context ); diff --git a/python/gui/symbology-ng/qgssymbolselectordialog.sip b/python/gui/symbology-ng/qgssymbolselectordialog.sip index 68a78ebd21e7..150b16e9dcf0 100644 --- a/python/gui/symbology-ng/qgssymbolselectordialog.sip +++ b/python/gui/symbology-ng/qgssymbolselectordialog.sip @@ -16,6 +16,7 @@ class QgsSymbolSelectorWidget : QgsPanelWidget * @param context expression context pointer. Ownership is transferred to the dialog. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context /Transfer/ ); @@ -27,6 +28,13 @@ class QgsSymbolSelectorWidget : QgsPanelWidget */ QgsExpressionContext* expressionContext() const; + /** Sets a list of additional expression context scopes to show as available for the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -106,6 +114,7 @@ class QgsSymbolSelectorDialog : QDialog * @param context expression context pointer. Ownership is transferred to the dialog. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context /Transfer/ ); @@ -117,6 +126,13 @@ class QgsSymbolSelectorDialog : QDialog */ QgsExpressionContext* expressionContext() const; + /** Sets a list of additional expression context scopes to show as available within the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas diff --git a/python/gui/symbology-ng/qgssymbolslistwidget.sip b/python/gui/symbology-ng/qgssymbolslistwidget.sip index 671cde6b6112..22786f9fe62f 100644 --- a/python/gui/symbology-ng/qgssymbolslistwidget.sip +++ b/python/gui/symbology-ng/qgssymbolslistwidget.sip @@ -14,6 +14,12 @@ class QgsSymbolsListWidget : QWidget */ QgsExpressionContext* expressionContext() const; + /** Sets a list of additional expression context scopes to show as available within the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 18c8ac873eaf..ef6828aa7030 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -5094,6 +5094,10 @@ void QgsExpression::initVariableHelp() gVariableHelpTexts.insert( "symbol_color", QCoreApplication::translate( "symbol_color", "Color of symbol used to render the feature." ) ); gVariableHelpTexts.insert( "symbol_angle", QCoreApplication::translate( "symbol_angle", "Angle of symbol used to render the feature (valid for marker symbols only)." ) ); + + //cluster variables + gVariableHelpTexts.insert( "cluster_color", QCoreApplication::translate( "cluster_color", "Color of symbols within a cluster, or NULL if symbols have mixed colors." ) ); + gVariableHelpTexts.insert( "cluster_size", QCoreApplication::translate( "cluster_size", "Number of symbols contained within a cluster." ) ); } QString QgsExpression::variableHelpText( const QString &variableName, bool showValue, const QVariant &value ) diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index e8c2cd5b1d8d..d9e886217a3a 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -40,6 +40,8 @@ const QString QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT( "geometry_part_cou const QString QgsExpressionContext::EXPR_GEOMETRY_PART_NUM( "geometry_part_num" ); const QString QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT( "geometry_point_count" ); const QString QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM( "geometry_point_num" ); +const QString QgsExpressionContext::EXPR_CLUSTER_SIZE( "cluster_size" ); +const QString QgsExpressionContext::EXPR_CLUSTER_COLOR( "cluster_color" ); // // QgsExpressionContextScope diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index dfb8e4b1ed72..c7d33787e10d 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -503,6 +503,10 @@ class CORE_EXPORT QgsExpressionContext static const QString EXPR_GEOMETRY_POINT_COUNT; //! Inbuilt variable name for point number variable static const QString EXPR_GEOMETRY_POINT_NUM; + //! Inbuilt variable name for cluster size variable + static const QString EXPR_CLUSTER_SIZE; + //! Inbuilt variable name for cluster color variable + static const QString EXPR_CLUSTER_COLOR; private: diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index f35c3368c51c..d9106b8f648d 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -438,15 +438,15 @@ QgsExpressionContextScope* QgsPointDistanceRenderer::createGroupScope( const Clu if ( groupColor.isValid() ) { - clusterScope->setVariable( "cluster_color", QgsSymbolLayerUtils::encodeColor( groupColor ) ); + clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, QgsSymbolLayerUtils::encodeColor( groupColor ) ); } else { //mixed colors - clusterScope->setVariable( "cluster_color", "" ); + clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); } - clusterScope->setVariable( "cluster_size", group.size() ); + clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, group.size() ); } return clusterScope; } diff --git a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp index 4675dd16bf9d..29a6dc1cbef2 100644 --- a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp @@ -528,6 +528,7 @@ void QgsCategorizedSymbolRendererWidget::changeSelectedSymbols() QgsSymbol* newSymbol = mCategorizedSymbol->clone(); QgsSymbolSelectorDialog dlg( newSymbol, mStyle, mLayer, this ); dlg.setMapCanvas( mMapCanvas ); + dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); if ( !dlg.exec() ) { delete newSymbol; @@ -550,6 +551,7 @@ void QgsCategorizedSymbolRendererWidget::changeCategorizedSymbol() QgsSymbol* newSymbol = mCategorizedSymbol->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( newSymbol, mStyle, mLayer, nullptr ); dlg->setMapCanvas( mMapCanvas ); + dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); @@ -594,6 +596,7 @@ void QgsCategorizedSymbolRendererWidget::changeCategorySymbol() QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( symbol, mStyle, mLayer, nullptr ); dlg->setMapCanvas( mMapCanvas ); + dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); openPanel( dlg ); diff --git a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp index 2684acd82be5..4f924069f405 100644 --- a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp @@ -830,6 +830,7 @@ void QgsGraduatedSymbolRendererWidget::changeGraduatedSymbol() QgsSymbol* newSymbol = mGraduatedSymbol->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( newSymbol, mStyle, mLayer, nullptr ); dlg->setMapCanvas( mMapCanvas ); + dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( accepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); @@ -908,6 +909,7 @@ void QgsGraduatedSymbolRendererWidget::changeRangeSymbol( int rangeIdx ) QgsSymbol* newSymbol = mRenderer->ranges()[rangeIdx].symbol()->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( newSymbol, mStyle, mLayer, nullptr ); dlg->setMapCanvas( mMapCanvas ); + dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( accepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); diff --git a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp index 8ed510d88f87..5772f827d97f 100644 --- a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp @@ -126,6 +126,7 @@ void QgsInvertedPolygonRendererWidget::on_mRendererComboBox_currentIndexChanged( mEmbeddedRendererWidget.reset( m->createRendererWidget( mLayer, mStyle, const_cast( mRenderer->embeddedRenderer() )->clone() ) ); connect( mEmbeddedRendererWidget.data(), SIGNAL( widgetChanged() ), this, SIGNAL( widgetChanged() ) ); mEmbeddedRendererWidget->setMapCanvas( mMapCanvas ); + mEmbeddedRendererWidget->setAdditionalExpressionContextScopes( mAdditionalScopes ); if ( layout()->count() > 2 ) { diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp index 082b59d32bee..3f61edef08db 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp @@ -126,6 +126,15 @@ QgsLayerPropertiesWidget::QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const mEffectWidget->setPaintEffect( mLayer->paintEffect() ); } +void QgsLayerPropertiesWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mAdditionalScopes = scopes; + + QgsSymbolLayerWidget* w = dynamic_cast< QgsSymbolLayerWidget* >( stackedWidget->currentWidget() ); + if ( w ) + w->setAdditionalExpressionContextScopes( mAdditionalScopes ); +} + void QgsLayerPropertiesWidget::setMapCanvas( QgsMapCanvas *canvas ) { mMapCanvas = canvas; @@ -191,6 +200,7 @@ void QgsLayerPropertiesWidget::updateSymbolLayerWidget( QgsSymbolLayer* layer ) if ( w ) { w->setExpressionContext( mPresetExpressionContext ); + w->setAdditionalExpressionContextScopes( mAdditionalScopes ); if ( mMapCanvas ) w->setMapCanvas( mMapCanvas ); w->setSymbolLayer( layer ); diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.h b/src/gui/symbology-ng/qgslayerpropertieswidget.h index 2ec321872d76..23a788093fac 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.h +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.h @@ -17,6 +17,7 @@ #define QGSLAYERPROPERTIESWIDGET_H #include "ui_widget_layerproperties.h" +#include "qgsexpressioncontext.h" class QgsSymbol; class QgsSymbolLayer; @@ -24,7 +25,6 @@ class QgsSymbolLayerWidget; class QgsVectorLayer; class QgsMapCanvas; class QgsPanelWidget; -class QgsExpressionContext; class SymbolLayerItem; @@ -49,6 +49,13 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L */ QgsExpressionContext* expressionContext() const { return mPresetExpressionContext; } + /** Sets a list of additional expression context scopes to show as available within the layer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -74,6 +81,7 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L * be kept alive for the lifetime of the properties widget. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context ); @@ -96,6 +104,7 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L private: QgsExpressionContext* mPresetExpressionContext; + QList< QgsExpressionContextScope > mAdditionalScopes; QgsMapCanvas* mMapCanvas; }; diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp index 1abf2811f97e..42ec01d8e291 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp @@ -135,6 +135,12 @@ void QgsPointClusterRendererWidget::on_mRendererSettingsButton_clicked() { QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); w->setMapCanvas( mMapCanvas ); + QgsExpressionContextScope scope; + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + scopes << scope; + w->setAdditionalExpressionContextScopes( scopes ); connect( w, SIGNAL( widgetChanged() ), this, SLOT( updateRendererFromWidget() ) ); w->setDockMode( this->dockMode() ); openPanel( w ); @@ -178,6 +184,12 @@ void QgsPointClusterRendererWidget::on_mCenterSymbolPushButton_clicked() QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); dlg->setDockMode( this->dockMode() ); dlg->setMapCanvas( mMapCanvas ); + QgsExpressionContextScope scope; + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + scopes << scope; + dlg->setAdditionalExpressionContextScopes( scopes ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateCenterSymbolFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index efddd17b1715..8ec7a9e6164c 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -214,6 +214,12 @@ void QgsPointDisplacementRendererWidget::on_mRendererSettingsButton_clicked() { QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); w->setMapCanvas( mMapCanvas ); + QgsExpressionContextScope scope; + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + scopes << scope; + w->setAdditionalExpressionContextScopes( scopes ); connect( w, SIGNAL( widgetChanged() ), this, SLOT( updateRendererFromWidget() ) ); openPanel( w ); } @@ -351,6 +357,13 @@ void QgsPointDisplacementRendererWidget::on_mCenterSymbolPushButton_clicked() QgsMarkerSymbol* markerSymbol = mRenderer->centerSymbol()->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); dlg->setMapCanvas( mMapCanvas ); + + QgsExpressionContextScope scope; + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); + scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + scopes << scope; + dlg->setAdditionalExpressionContextScopes( scopes ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateCenterSymbolFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); openPanel( dlg ); diff --git a/src/gui/symbology-ng/qgsrendererwidget.cpp b/src/gui/symbology-ng/qgsrendererwidget.cpp index 8aaa16a042f9..efdfbf86348a 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrendererwidget.cpp @@ -172,6 +172,7 @@ void QgsRendererWidget::changeSymbolWidth() QgsDataDefinedWidthDialog dlg( symbolList, mLayer ); dlg.setMapCanvas( mMapCanvas ); + dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); if ( QDialog::Accepted == dlg.exec() ) { @@ -200,6 +201,7 @@ void QgsRendererWidget::changeSymbolSize() QgsDataDefinedSizeDialog dlg( symbolList, mLayer ); dlg.setMapCanvas( mMapCanvas ); + dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); if ( QDialog::Accepted == dlg.exec() ) { @@ -228,6 +230,7 @@ void QgsRendererWidget::changeSymbolAngle() QgsDataDefinedRotationDialog dlg( symbolList, mLayer ); dlg.setMapCanvas( mMapCanvas ); + dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); if ( QDialog::Accepted == dlg.exec() ) { @@ -269,6 +272,11 @@ const QgsMapCanvas* QgsRendererWidget::mapCanvas() const return mMapCanvas; } +void QgsRendererWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mAdditionalScopes = scopes; +} + void QgsRendererWidget::applyChanges() { apply(); @@ -325,6 +333,12 @@ QgsExpressionContext QgsDataDefinedValueDialog::createExpressionContext() const if ( vectorLayer() ) expContext << QgsExpressionContextUtils::layerScope( vectorLayer() ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mAdditionalScopes ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + return expContext; } diff --git a/src/gui/symbology-ng/qgsrendererwidget.h b/src/gui/symbology-ng/qgsrendererwidget.h index 57b8564cd094..9f1c3128cd55 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.h +++ b/src/gui/symbology-ng/qgsrendererwidget.h @@ -65,6 +65,12 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget */ const QgsMapCanvas* mapCanvas() const; + /** Sets a list of additional expression context scopes to show as available within the renderer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 */ @@ -91,6 +97,9 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget QAction* mPasteAction; QgsMapCanvas* mMapCanvas; + //! List of additional expression context scopes to add to default expression context + QList< QgsExpressionContextScope > mAdditionalScopes; + /** Subclasses may provide the capability of changing multiple symbols at once by implementing the following two methods and by connecting the slot contextMenuViewCategories(const QPoint&)*/ virtual QList selectedSymbols() { return QList(); } @@ -121,6 +130,7 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget */ virtual void apply(); + }; @@ -170,6 +180,12 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD */ const QgsVectorLayer* vectorLayer() const { return mLayer; } + /** Sets a list of additional expression context scopes to show as available for the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ) { mAdditionalScopes = scopes; } + public slots: void dataDefinedChanged(); @@ -181,6 +197,9 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD */ void init( const QString& description ); // needed in children ctor to call virtual + //! List of additional scopes to add to default expression context + QList< QgsExpressionContextScope > mAdditionalScopes; + private: QgsDataDefined symbolDataDefined() const; diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp index 8facf023746b..c8929fc47b7e 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp @@ -261,6 +261,7 @@ void QgsRuleBasedRendererWidget::refineRuleCategoriesGui() w->setPanelTitle( tr( "Add categories to rules" ) ); connect( w, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( refineRuleCategoriesAccepted( QgsPanelWidget* ) ) ); w->setMapCanvas( mMapCanvas ); + w->setAdditionalExpressionContextScopes( mAdditionalScopes ); openPanel( w ); } @@ -270,6 +271,7 @@ void QgsRuleBasedRendererWidget::refineRuleRangesGui() w->setPanelTitle( tr( "Add ranges to rules" ) ); connect( w, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( refineRuleRangesAccepted( QgsPanelWidget* ) ) ); w->setMapCanvas( mMapCanvas ); + w->setAdditionalExpressionContextScopes( mAdditionalScopes ); openPanel( w ); } diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.cpp b/src/gui/symbology-ng/qgssymbollayerwidget.cpp index d799c47ae601..ad18f6856784 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgssymbollayerwidget.cpp @@ -84,15 +84,28 @@ QgsExpressionContext QgsSymbolLayerWidget::createExpressionContext() const expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, 1, true ) ); expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, 1, true ) ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mAdditionalScopes ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + //TODO - show actual value expContext.setOriginalValueVariable( QVariant() ); + expContext.setHighlightedVariables( QStringList() << QgsExpressionContext::EXPR_ORIGINAL_VALUE << QgsExpressionContext::EXPR_SYMBOL_COLOR << QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT << QgsExpressionContext::EXPR_GEOMETRY_PART_NUM - << QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT << QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM ); + << QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT << QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM + << QgsExpressionContext::EXPR_CLUSTER_COLOR << QgsExpressionContext::EXPR_CLUSTER_SIZE ); return expContext; } +void QgsSymbolLayerWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mAdditionalScopes = scopes; +} + void QgsSymbolLayerWidget::setMapCanvas( QgsMapCanvas *canvas ) { mMapCanvas = canvas; diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.h b/src/gui/symbology-ng/qgssymbollayerwidget.h index a8ef6c4b7031..ab104109c064 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.h +++ b/src/gui/symbology-ng/qgssymbollayerwidget.h @@ -53,6 +53,13 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC */ QgsExpressionContext* expressionContext() const { return mPresetExpressionContext; } + /** Sets a list of additional expression context scopes to show as available within the layer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -81,6 +88,7 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC * be kept alive for the lifetime of the layer widget. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context ) { mPresetExpressionContext = context; } @@ -96,6 +104,7 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC const QgsVectorLayer* mVectorLayer; QgsMapCanvas* mMapCanvas; + QList< QgsExpressionContextScope > mAdditionalScopes; signals: /** diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.cpp b/src/gui/symbology-ng/qgssymbolselectordialog.cpp index 996894b55670..f996f3980fc6 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.cpp +++ b/src/gui/symbology-ng/qgssymbolselectordialog.cpp @@ -286,6 +286,11 @@ void QgsSymbolSelectorWidget::setExpressionContext( QgsExpressionContext *contex updatePreview(); } +void QgsSymbolSelectorWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mAdditionalScopes = scopes; +} + void QgsSymbolSelectorWidget::setMapCanvas( QgsMapCanvas *canvas ) { mMapCanvas = canvas; @@ -416,6 +421,7 @@ void QgsSymbolSelectorWidget::layerChanged() QgsLayerPropertiesWidget *layerProp = new QgsLayerPropertiesWidget( currentItem->layer(), parent->symbol(), mVectorLayer ); layerProp->setDockMode( this->dockMode() ); layerProp->setExpressionContext( mPresetExpressionContext.data() ); + layerProp->setAdditionalExpressionContextScopes( mAdditionalScopes ); layerProp->setMapCanvas( mMapCanvas ); setWidget( layerProp ); connect( layerProp, SIGNAL( changed() ), mDataDefineRestorer.data(), SLOT( restore() ) ); @@ -433,6 +439,7 @@ void QgsSymbolSelectorWidget::layerChanged() // Now populate symbols of that type using the symbols list widget: QgsSymbolsListWidget *symbolsList = new QgsSymbolsListWidget( currentItem->symbol(), mStyle, mAdvancedMenu, this, mVectorLayer ); symbolsList->setExpressionContext( mPresetExpressionContext.data() ); + symbolsList->setAdditionalExpressionContextScopes( mAdditionalScopes ); symbolsList->setMapCanvas( mMapCanvas ); setWidget( symbolsList ); @@ -711,6 +718,11 @@ void QgsSymbolSelectorDialog::setExpressionContext( QgsExpressionContext *contex mSelectorWidget->setExpressionContext( context ); } +void QgsSymbolSelectorDialog::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mSelectorWidget->setAdditionalExpressionContextScopes( scopes ); +} + QgsExpressionContext *QgsSymbolSelectorDialog::expressionContext() const { return mSelectorWidget->expressionContext(); diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.h b/src/gui/symbology-ng/qgssymbolselectordialog.h index 478db8c41179..8df7d28b9940 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.h +++ b/src/gui/symbology-ng/qgssymbolselectordialog.h @@ -104,6 +104,7 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs * @param context expression context pointer. Ownership is transferred to the dialog. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context ); @@ -115,6 +116,13 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs */ QgsExpressionContext* expressionContext() const { return mPresetExpressionContext.data(); } + /** Sets a list of additional expression context scopes to show as available for the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -245,6 +253,7 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs private: QScopedPointer mDataDefineRestorer; QScopedPointer< QgsExpressionContext > mPresetExpressionContext; + QList< QgsExpressionContextScope > mAdditionalScopes; QgsMapCanvas* mMapCanvas; }; @@ -269,9 +278,17 @@ class GUI_EXPORT QgsSymbolSelectorDialog : public QDialog * @param context expression context pointer. Ownership is transferred to the dialog. * @note added in QGIS 2.12 * @see expressionContext() + * @see setAdditionalExpressionContextScopes() */ void setExpressionContext( QgsExpressionContext* context ); + /** Sets a list of additional expression context scopes to show as available within the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Returns the expression context used for the dialog, if set. This expression context is used for * evaluating data defined symbol properties and for populating based expression widgets in * the dialog. diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index 87ad4a722f8b..48d7fd747435 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -130,6 +130,11 @@ QgsSymbolsListWidget::~QgsSymbolsListWidget() btnAdvanced->menu()->removeAction( mClipFeaturesAction ); } +void QgsSymbolsListWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mAdditionalScopes = scopes; +} + void QgsSymbolsListWidget::setMapCanvas( QgsMapCanvas* canvas ) { mMapCanvas = canvas; @@ -448,6 +453,12 @@ QgsExpressionContext QgsSymbolsListWidget::createExpressionContext() const expContext << QgsExpressionContextUtils::layerScope( layer() ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mAdditionalScopes ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + return expContext; } diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.h b/src/gui/symbology-ng/qgssymbolslistwidget.h index 3fce618feb85..78096c7db144 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.h +++ b/src/gui/symbology-ng/qgssymbolslistwidget.h @@ -46,6 +46,12 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW */ QgsExpressionContext* expressionContext() const { return mPresetExpressionContext; } + /** Sets a list of additional expression context scopes to show as available within the symbol. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @note added in QGIS 3.0 + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current * map scale and other properties from the canvas. * @param canvas map canvas @@ -120,6 +126,7 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW void populateGroups( const QString& parent = "", const QString& prepend = "" ); QgsExpressionContext* mPresetExpressionContext; + QList< QgsExpressionContextScope > mAdditionalScopes; QgsExpressionContext createExpressionContext() const override; }; From d32008a31d10262b59e3bc94fce979643c9c5f22 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 14:07:02 +1000 Subject: [PATCH 024/897] Icon for cluster renderer --- images/images.qrc | 1 + .../default/rendererPointClusterSymbol.svg | 88 +++++++++++++++++++ .../qgsrendererpropertiesdialog.cpp | 2 +- 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 images/themes/default/rendererPointClusterSymbol.svg diff --git a/images/images.qrc b/images/images.qrc index f97bb7405244..f3c4e148bbac 100644 --- a/images/images.qrc +++ b/images/images.qrc @@ -573,6 +573,7 @@ themes/default/dependencies.svg themes/default/mIconClearText.svg themes/default/mIconClearTextHover.svg + themes/default/rendererPointClusterSymbol.svg qgis_tips/symbol_levels.png diff --git a/images/themes/default/rendererPointClusterSymbol.svg b/images/themes/default/rendererPointClusterSymbol.svg new file mode 100644 index 000000000000..2aa195221fe1 --- /dev/null +++ b/images/themes/default/rendererPointClusterSymbol.svg @@ -0,0 +1,88 @@ + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp index 662228923049..a277ab3e5272 100644 --- a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp +++ b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp @@ -74,7 +74,7 @@ static void _initRendererWidgetFunctions() _initRenderer( "graduatedSymbol", QgsGraduatedSymbolRendererWidget::create, "rendererGraduatedSymbol.svg" ); _initRenderer( "RuleRenderer", QgsRuleBasedRendererWidget::create, "rendererRuleBasedSymbol.svg" ); _initRenderer( "pointDisplacement", QgsPointDisplacementRendererWidget::create, "rendererPointDisplacementSymbol.svg" ); - _initRenderer( "pointCluster", QgsPointClusterRendererWidget::create, "rendererPointDisplacementSymbol.svg" ); + _initRenderer( "pointCluster", QgsPointClusterRendererWidget::create, "rendererPointClusterSymbol.svg" ); _initRenderer( "invertedPolygonRenderer", QgsInvertedPolygonRendererWidget::create, "rendererInvertedSymbol.svg" ); _initRenderer( "heatmapRenderer", QgsHeatmapRendererWidget::create, "rendererHeatmapSymbol.svg" ); _initRenderer( "25dRenderer", Qgs25DRendererWidget::create, "renderer25dSymbol.svg" ); From c1bff163842363d6cd0440820e1b670bfada3ef9 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 14:07:17 +1000 Subject: [PATCH 025/897] Fix panel titles --- src/gui/symbology-ng/qgspointclusterrendererwidget.cpp | 2 ++ src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp index 42ec01d8e291..d91b0b47f7e4 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp @@ -134,6 +134,7 @@ void QgsPointClusterRendererWidget::on_mRendererSettingsButton_clicked() if ( m ) { QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); + w->setPanelTitle( tr( "Renderer settings" ) ); w->setMapCanvas( mMapCanvas ); QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); @@ -182,6 +183,7 @@ void QgsPointClusterRendererWidget::on_mCenterSymbolPushButton_clicked() } QgsMarkerSymbol* markerSymbol = mRenderer->clusterSymbol()->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); + dlg->setPanelTitle( tr( "Cluster symbol" ) ); dlg->setDockMode( this->dockMode() ); dlg->setMapCanvas( mMapCanvas ); QgsExpressionContextScope scope; diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index 8ec7a9e6164c..8d77f2c0f9c5 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -213,6 +213,7 @@ void QgsPointDisplacementRendererWidget::on_mRendererSettingsButton_clicked() if ( m ) { QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); + w->setPanelTitle( tr( "Renderer settings" ) ); w->setMapCanvas( mMapCanvas ); QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); @@ -357,6 +358,7 @@ void QgsPointDisplacementRendererWidget::on_mCenterSymbolPushButton_clicked() QgsMarkerSymbol* markerSymbol = mRenderer->centerSymbol()->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); dlg->setMapCanvas( mMapCanvas ); + dlg->setPanelTitle( tr( "Center symbol" ) ); QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); From 1c611cc26d0f947966d9d89f02c2f1612be276c7 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 14:07:25 +1000 Subject: [PATCH 026/897] Better default cluster symbol --- src/core/symbology-ng/qgspointclusterrenderer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index 9f734be3a16c..beea5de71421 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -30,6 +30,8 @@ QgsPointClusterRenderer::QgsPointClusterRenderer() : QgsPointDistanceRenderer( "pointCluster" ) { mClusterSymbol.reset( new QgsMarkerSymbol() ); + mClusterSymbol->setSize( 4 ); + mClusterSymbol->setColor( QColor( 245, 75, 80 ) ); } QgsPointClusterRenderer* QgsPointClusterRenderer::clone() const From fbdc93fb2e23f27b20525cb6848482ceea03841c Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 14:07:33 +1000 Subject: [PATCH 027/897] Add missing test images --- .../expected_cluster_variables.png | Bin 0 -> 3535 bytes .../expected_displacement_variables.png | Bin 0 -> 7643 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/testdata/control_images/cluster_renderer/expected_cluster_variables/expected_cluster_variables.png create mode 100644 tests/testdata/control_images/displacement_renderer/expected_displacement_variables/expected_displacement_variables.png diff --git a/tests/testdata/control_images/cluster_renderer/expected_cluster_variables/expected_cluster_variables.png b/tests/testdata/control_images/cluster_renderer/expected_cluster_variables/expected_cluster_variables.png new file mode 100644 index 0000000000000000000000000000000000000000..8a7e3270bf8ec4a7813b0976bb179c84d4cd62af GIT binary patch literal 3535 zcmcIncTkhtwhs`2s94~Das)-{86t2D5DsXBcqlYwxx8nmyn5Tfg

      {Su{w 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 literal 0 HcmV?d00001 From fd0c5ef950952985562c3901a80212771479e0dc Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 12 Sep 2016 16:11:05 +1000 Subject: [PATCH 028/897] Refactor symbol/renderer widgets to use QgsSymbolWidgetContext instead of individually setting map canvas, expression context, etc Will make it more easy in future to add additional parameters to the widget context --- doc/api_break.dox | 41 +++++++++ python/gui/gui.sip | 1 + .../symbology-ng/qgsheatmaprendererwidget.sip | 2 +- .../qgsinvertedpolygonrendererwidget.sip | 2 +- .../symbology-ng/qgslayerpropertieswidget.sip | 35 ++------ .../qgspointdisplacementrendererwidget.sip | 2 +- python/gui/symbology-ng/qgsrendererwidget.sip | 48 ++++------ .../qgsrulebasedrendererwidget.sip | 13 ++- .../qgssinglesymbolrendererwidget.sip | 2 +- .../gui/symbology-ng/qgssymbollayerwidget.sip | 45 ++-------- .../symbology-ng/qgssymbolselectordialog.sip | 70 ++++----------- .../gui/symbology-ng/qgssymbolslistwidget.sip | 41 ++------- .../symbology-ng/qgssymbolwidgetcontext.sip | 61 +++++++++++++ src/app/composer/qgscomposerarrowwidget.cpp | 4 +- src/app/composer/qgscomposerpolygonwidget.cpp | 4 +- .../composer/qgscomposerpolylinewidget.cpp | 4 +- src/app/composer/qgscomposershapewidget.cpp | 4 +- src/app/composer/qgscompositionwidget.cpp | 4 +- src/app/qgisapp.cpp | 4 +- src/app/qgsapplayertreeviewmenuprovider.cpp | 8 +- src/gui/CMakeLists.txt | 3 + .../qgscategorizedsymbolrendererwidget.cpp | 21 +++-- .../qgsgraduatedsymbolrendererwidget.cpp | 18 ++-- .../symbology-ng/qgsheatmaprendererwidget.cpp | 20 +++-- .../symbology-ng/qgsheatmaprendererwidget.h | 2 +- .../qgsinvertedpolygonrendererwidget.cpp | 9 +- .../qgsinvertedpolygonrendererwidget.h | 3 +- .../symbology-ng/qgslayerpropertieswidget.cpp | 36 ++------ .../symbology-ng/qgslayerpropertieswidget.h | 42 +++------ .../qgspointclusterrendererwidget.cpp | 23 +++-- .../qgspointclusterrendererwidget.h | 2 +- .../qgspointdisplacementrendererwidget.cpp | 25 ++++-- .../qgspointdisplacementrendererwidget.h | 2 +- .../qgsrendererpropertiesdialog.cpp | 12 ++- src/gui/symbology-ng/qgsrendererwidget.cpp | 43 ++++----- src/gui/symbology-ng/qgsrendererwidget.h | 60 +++++-------- .../qgsrulebasedrendererwidget.cpp | 54 +++++++----- .../symbology-ng/qgsrulebasedrendererwidget.h | 8 +- .../qgssinglesymbolrendererwidget.cpp | 6 +- .../qgssinglesymbolrendererwidget.h | 2 +- src/gui/symbology-ng/qgssymbollayerwidget.cpp | 29 +++---- src/gui/symbology-ng/qgssymbollayerwidget.h | 57 +++--------- .../symbology-ng/qgssymbolselectordialog.cpp | 57 ++++-------- .../symbology-ng/qgssymbolselectordialog.h | 77 ++++------------ src/gui/symbology-ng/qgssymbolslistwidget.cpp | 40 ++++----- src/gui/symbology-ng/qgssymbolslistwidget.h | 46 +++------- .../symbology-ng/qgssymbolwidgetcontext.cpp | 77 ++++++++++++++++ src/gui/symbology-ng/qgssymbolwidgetcontext.h | 87 +++++++++++++++++++ 48 files changed, 643 insertions(+), 613 deletions(-) create mode 100644 python/gui/symbology-ng/qgssymbolwidgetcontext.sip create mode 100644 src/gui/symbology-ng/qgssymbolwidgetcontext.cpp create mode 100644 src/gui/symbology-ng/qgssymbolwidgetcontext.h diff --git a/doc/api_break.dox b/doc/api_break.dox index 49608af1ff1a..d77ac8a2f456 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -850,6 +850,12 @@ plugins calling this method will need to be updated.

    • labelsWithinRect() was removed. Use takeResults() and methods of QgsLabelingResults.
    +\subsection qgis_api_break_3_0_QgsLayerPropertiesWidget QgsLayerPropertiesWidget + +
      +
    • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
    • +
    + \subsection qgis_api_break_3_0_QgsLayerTreeGroup QgsLayerTreeGroup
      @@ -1176,6 +1182,20 @@ be returned instead of a null pointer if no transformation is required.
    • setCoordinateTransform() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required.
    +\subsection qgis_api_break_3_0_QgsRendererWidget QgsRendererWidget + +
      +
    • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
    • +
    + +\subsection qgis_api_break_3_0_QgsRendererRulePropsWidget QgsRendererRulePropsWidget + +
      +
    • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
    • +
    + + + \subsection qgis_api_break_3_0_QgsRubberBand QgsRubberBand
      @@ -1263,6 +1283,13 @@ the variant which takes QgsSymbolRenderContext instead.
    • expression() was removed. Use getDataDefinedProperty or evaluateDataDefinedProperty instead.
    +\subsection qgis_api_break_3_0_QgsSymbolLayerWidget QgsSymbolLayerWidget + +
      +
    • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
    • +
    + + \subsection qgis_api_break_3_0_QgsSymbolRenderContext QgsSymbolRenderContext (renamed from QgsSymbolV2RenderContext)
      @@ -1291,6 +1318,20 @@ than an integer value
    • saveSymbol() was removed.
    +\subsection qgis_api_break_3_0_QgsSymbolSelectorDialog QgsSymbolSelectorDialog + +
      +
    • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
    • +
    + +\subsection qgis_api_break_3_0_QgsSymbolsListWidget QgsSymbolsListWidget + +
      +
    • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
    • +
    + + + \subsection qgis_api_break_3_0_QgsTolerance QgsTolerance
      diff --git a/python/gui/gui.sip b/python/gui/gui.sip index 27b73be6bd65..722351716aec 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -249,6 +249,7 @@ %Include symbology-ng/qgssymbollevelsdialog.sip %Include symbology-ng/qgssymbolslistwidget.sip %Include symbology-ng/qgssymbolselectordialog.sip +%Include symbology-ng/qgssymbolwidgetcontext.sip %Include symbology-ng/qgsvectorfieldsymbollayerwidget.sip %Include effects/qgseffectdrawmodecombobox.sip diff --git a/python/gui/symbology-ng/qgsheatmaprendererwidget.sip b/python/gui/symbology-ng/qgsheatmaprendererwidget.sip index 1af48979a43f..c14918255d02 100644 --- a/python/gui/symbology-ng/qgsheatmaprendererwidget.sip +++ b/python/gui/symbology-ng/qgsheatmaprendererwidget.sip @@ -21,5 +21,5 @@ class QgsHeatmapRendererWidget : QgsRendererWidget /** @returns the current feature renderer */ virtual QgsFeatureRenderer* renderer(); - void setMapCanvas( QgsMapCanvas* canvas ); + virtual void setContext( const QgsSymbolWidgetContext& context ); }; diff --git a/python/gui/symbology-ng/qgsinvertedpolygonrendererwidget.sip b/python/gui/symbology-ng/qgsinvertedpolygonrendererwidget.sip index 0069aaf06e4a..349da1cfa347 100644 --- a/python/gui/symbology-ng/qgsinvertedpolygonrendererwidget.sip +++ b/python/gui/symbology-ng/qgsinvertedpolygonrendererwidget.sip @@ -20,5 +20,5 @@ class QgsInvertedPolygonRendererWidget : QgsRendererWidget /** @returns the current feature renderer */ virtual QgsFeatureRenderer* renderer(); - void setMapCanvas( QgsMapCanvas* canvas ); + virtual void setContext( const QgsSymbolWidgetContext& context ); }; diff --git a/python/gui/symbology-ng/qgslayerpropertieswidget.sip b/python/gui/symbology-ng/qgslayerpropertieswidget.sip index a6f418e257a0..9b0b9609aa83 100644 --- a/python/gui/symbology-ng/qgslayerpropertieswidget.sip +++ b/python/gui/symbology-ng/qgslayerpropertieswidget.sip @@ -7,43 +7,24 @@ class QgsLayerPropertiesWidget : QgsPanelWidget public: QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const QgsSymbol* symbol, const QgsVectorLayer* vl, QWidget* parent /TransferThis/ = NULL ); - /** Returns the expression context used for the widget, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the properties widget. - * @note added in QGIS 2.12 - * @see setExpressionContext() + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() + * @note added in QGIS 3.0 */ - QgsExpressionContext* expressionContext() const; + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets a list of additional expression context scopes to show as available within the layer. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + QgsSymbolWidgetContext context() const; - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); public slots: void layerTypeChanged(); void emitSignalChanged(); - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the properties widget. - * @param context expression context pointer. Ownership is not transferred and the object must - * be kept alive for the lifetime of the properties widget. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context ); - signals: void changed(); void changeLayer( QgsSymbolLayer* ); diff --git a/python/gui/symbology-ng/qgspointdisplacementrendererwidget.sip b/python/gui/symbology-ng/qgspointdisplacementrendererwidget.sip index 6a4106ceb962..457adb9f10e5 100644 --- a/python/gui/symbology-ng/qgspointdisplacementrendererwidget.sip +++ b/python/gui/symbology-ng/qgspointdisplacementrendererwidget.sip @@ -9,5 +9,5 @@ class QgsPointDisplacementRendererWidget: QgsRendererWidget ~QgsPointDisplacementRendererWidget(); QgsFeatureRenderer* renderer(); - void setMapCanvas( QgsMapCanvas* canvas ); + void setContext( const QgsSymbolWidgetContext& context ); }; diff --git a/python/gui/symbology-ng/qgsrendererwidget.sip b/python/gui/symbology-ng/qgsrendererwidget.sip index 4a256e77abb5..6da12f174376 100644 --- a/python/gui/symbology-ng/qgsrendererwidget.sip +++ b/python/gui/symbology-ng/qgsrendererwidget.sip @@ -15,25 +15,18 @@ class QgsRendererWidget : QgsPanelWidget //! show a dialog with renderer's symbol level settings void showSymbolLevelsDialog( QgsFeatureRenderer* r ); - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); - - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets a list of additional expression context scopes to show as available within the renderer. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() * @note added in QGIS 3.0 */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 @@ -105,31 +98,24 @@ class QgsDataDefinedValueDialog : QDialog QgsDataDefinedValueDialog( const QList& symbolList, QgsVectorLayer * layer, const QString & label ); virtual ~QgsDataDefinedValueDialog(); - /** Sets the map canvas associated with the dialog. This allows the dialog to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() + * @note added in QGIS 3.0 */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 */ const QgsVectorLayer* vectorLayer() const; - /** Sets a list of additional expression context scopes to show as available for the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context - * @note added in QGIS 3.0 - */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); - public slots: void dataDefinedChanged(); diff --git a/python/gui/symbology-ng/qgsrulebasedrendererwidget.sip b/python/gui/symbology-ng/qgsrulebasedrendererwidget.sip index 5673726dad19..75f069dd3baa 100644 --- a/python/gui/symbology-ng/qgsrulebasedrendererwidget.sip +++ b/python/gui/symbology-ng/qgsrulebasedrendererwidget.sip @@ -109,7 +109,15 @@ class QgsRendererRulePropsWidget: QgsPanelWidget %End public: - QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent /TransferThis/ = 0, QgsMapCanvas* mapCanvas = 0 ); + /** + * Widget to edit the details of a rule based renderer rule. + * @param rule The rule to edit. + * @param layer The layer used to pull layer related information. + * @param style The active QGIS style. + * @param parent The parent widget. + * @param context the symbol widget context + */ + QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent /TransferThis/ = 0, const QgsSymbolWidgetContext& context= QgsSymbolWidgetContext() ); ~QgsRendererRulePropsWidget(); QgsRuleBasedRenderer::Rule* rule(); @@ -129,7 +137,8 @@ class QgsRendererRulePropsDialog : QDialog %End public: - QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent /TransferThis/ = 0, QgsMapCanvas* mapCanvas = 0 ); + + QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent /TransferThis/ = 0, const QgsSymbolWidgetContext& context = QgsSymbolWidgetContext() ); ~QgsRendererRulePropsDialog(); QgsRuleBasedRenderer::Rule* rule(); diff --git a/python/gui/symbology-ng/qgssinglesymbolrendererwidget.sip b/python/gui/symbology-ng/qgssinglesymbolrendererwidget.sip index 0800a94de47c..329d90ac65a2 100644 --- a/python/gui/symbology-ng/qgssinglesymbolrendererwidget.sip +++ b/python/gui/symbology-ng/qgssinglesymbolrendererwidget.sip @@ -11,7 +11,7 @@ class QgsSingleSymbolRendererWidget : QgsRendererWidget virtual QgsFeatureRenderer* renderer(); - virtual void setMapCanvas( QgsMapCanvas* canvas ); + virtual void setContext( const QgsSymbolWidgetContext& context ); virtual void setDockMode( bool dockMode ); diff --git a/python/gui/symbology-ng/qgssymbollayerwidget.sip b/python/gui/symbology-ng/qgssymbollayerwidget.sip index dcf34eed6093..3cb73e39217f 100644 --- a/python/gui/symbology-ng/qgssymbollayerwidget.sip +++ b/python/gui/symbology-ng/qgssymbollayerwidget.sip @@ -11,53 +11,24 @@ class QgsSymbolLayerWidget : QWidget virtual void setSymbolLayer( QgsSymbolLayer* layer ) = 0; virtual QgsSymbolLayer* symbolLayer() = 0; - /** Returns the expression context used for the widget, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const; - - /** Sets a list of additional expression context scopes to show as available within the layer. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); - - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 */ const QgsVectorLayer* vectorLayer() const; - public slots: - - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @param context expression context pointer. Ownership is not transferred and the object must - * be kept alive for the lifetime of the layer widget. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context ); - protected: void registerDataDefinedButton( QgsDataDefinedButton* button, const QString& propertyName, QgsDataDefinedButton::DataType type, const QString& description ); diff --git a/python/gui/symbology-ng/qgssymbolselectordialog.sip b/python/gui/symbology-ng/qgssymbolselectordialog.sip index 150b16e9dcf0..ec0a04ebd7cf 100644 --- a/python/gui/symbology-ng/qgssymbolselectordialog.sip +++ b/python/gui/symbology-ng/qgssymbolselectordialog.sip @@ -10,37 +10,18 @@ class QgsSymbolSelectorWidget : QgsPanelWidget //! return menu for "advanced" button - create it if doesn't exist and show the advanced button QMenu* advancedMenu(); - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @param context expression context pointer. Ownership is transferred to the dialog. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context /Transfer/ ); - - /** Returns the expression context used for the dialog, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the dialog. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const; - - /** Sets a list of additional expression context scopes to show as available for the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - void setMapCanvas( QgsMapCanvas* canvas ); + QgsSymbolWidgetContext context() const; /** * @brief Return the symbol that is currently active in the widget. Can be null. @@ -108,37 +89,18 @@ class QgsSymbolSelectorDialog : QDialog //! return menu for "advanced" button - create it if doesn't exist and show the advanced button QMenu* advancedMenu(); - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @param context expression context pointer. Ownership is transferred to the dialog. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context /Transfer/ ); - - /** Returns the expression context used for the dialog, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the dialog. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const; - - /** Sets a list of additional expression context scopes to show as available within the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - void setMapCanvas( QgsMapCanvas* canvas ); + QgsSymbolWidgetContext context() const; QgsSymbol* symbol(); protected: diff --git a/python/gui/symbology-ng/qgssymbolslistwidget.sip b/python/gui/symbology-ng/qgssymbolslistwidget.sip index 22786f9fe62f..7bf1f727fe85 100644 --- a/python/gui/symbology-ng/qgssymbolslistwidget.sip +++ b/python/gui/symbology-ng/qgssymbolslistwidget.sip @@ -6,33 +6,18 @@ class QgsSymbolsListWidget : QWidget public: QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, QMenu* menu, QWidget* parent /TransferThis/ = 0, const QgsVectorLayer * layer = 0 ); - /** Returns the expression context used for the widget, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the list widget. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const; - - /** Sets a list of additional expression context scopes to show as available within the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); - - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 @@ -41,16 +26,6 @@ class QgsSymbolsListWidget : QWidget public slots: - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the properties widget. - * @param context expression context pointer. Ownership is not transferred and the object must - * be kept alive for the lifetime of the properties widget. - * @note added in QGIS 2.12 - * @see expressionContext() - */ - void setExpressionContext( QgsExpressionContext* context ); - void setSymbolFromStyle( const QModelIndex & index ); void setSymbolColor( const QColor& color ); void setMarkerAngle( double angle ); diff --git a/python/gui/symbology-ng/qgssymbolwidgetcontext.sip b/python/gui/symbology-ng/qgssymbolwidgetcontext.sip new file mode 100644 index 000000000000..dd270bf100ba --- /dev/null +++ b/python/gui/symbology-ng/qgssymbolwidgetcontext.sip @@ -0,0 +1,61 @@ + +/** \ingroup gui + * \class QgsSymbolWidgetContext + * Contains settings which reflect the context in which a symbol (or renderer) widget is shown, eg the + * map canvas and relevant expression contexts. + * + * \note added in QGIS 3.0 + */ + class QgsSymbolWidgetContext +{ +%TypeHeaderCode +#include +%End + public: + + QgsSymbolWidgetContext(); + + QgsSymbolWidgetContext( const QgsSymbolWidgetContext& other ); + + //QgsSymbolWidgetContext& operator=( const QgsSymbolWidgetContext& other ); + + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current + * map scale and other properties from the canvas. + * @param canvas map canvas + * @see mapCanvas() + */ + void setMapCanvas( QgsMapCanvas* canvas ); + + /** Returns the map canvas associated with the widget. + * @see setMapCanvas() + */ + QgsMapCanvas* mapCanvas() const; + + /** Sets the optional expression context used for the widget. This expression context is used for + * evaluating data defined symbol properties and for populating based expression widgets in + * the layer widget. + * @param context expression context pointer. Ownership is not transferred. + * @see expressionContext() + * @see setAdditionalExpressionContextScopes() + */ + void setExpressionContext( QgsExpressionContext* context ); + + /** Returns the expression context used for the widget, if set. This expression context is used for + * evaluating data defined symbol properties and for populating based expression widgets in + * the layer widget. + * @see setExpressionContext() + */ + QgsExpressionContext* expressionContext() const; + + /** Sets a list of additional expression context scopes to show as available within the layer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + + /** Returns the list of additional expression context scopes to show as available within the layer. + * @see setAdditionalExpressionContextScopes() + */ + QList< QgsExpressionContextScope > additionalExpressionContextScopes() const; +}; + diff --git a/src/app/composer/qgscomposerarrowwidget.cpp b/src/app/composer/qgscomposerarrowwidget.cpp index 58882af78f7a..47effd16247d 100644 --- a/src/app/composer/qgscomposerarrowwidget.cpp +++ b/src/app/composer/qgscomposerarrowwidget.cpp @@ -312,7 +312,9 @@ void QgsComposerArrowWidget::on_mLineStyleButton_clicked() QgsLineSymbol* newSymbol = mArrow->lineSymbol()->clone(); QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), nullptr, this ); QgsExpressionContext context = mArrow->createExpressionContext(); - d.setExpressionContext( &context ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d.setContext( symbolContext ); if ( d.exec() == QDialog::Accepted ) { diff --git a/src/app/composer/qgscomposerpolygonwidget.cpp b/src/app/composer/qgscomposerpolygonwidget.cpp index 25ef3e40e52d..8a0832814a84 100644 --- a/src/app/composer/qgscomposerpolygonwidget.cpp +++ b/src/app/composer/qgscomposerpolygonwidget.cpp @@ -64,7 +64,9 @@ void QgsComposerPolygonWidget::on_mPolygonStyleButton_clicked() QgsExpressionContext context = mComposerPolygon->createExpressionContext(); QgsSymbolSelectorDialog d( newSymbol.data(), QgsStyle::defaultStyle(), coverageLayer, this ); - d.setExpressionContext( &context ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d.setContext( symbolContext ); if ( d.exec() == QDialog::Accepted ) { diff --git a/src/app/composer/qgscomposerpolylinewidget.cpp b/src/app/composer/qgscomposerpolylinewidget.cpp index da9c71b552de..f16bef6c8233 100644 --- a/src/app/composer/qgscomposerpolylinewidget.cpp +++ b/src/app/composer/qgscomposerpolylinewidget.cpp @@ -56,7 +56,9 @@ void QgsComposerPolylineWidget::on_mLineStyleButton_clicked() QgsExpressionContext context = mComposerPolyline->createExpressionContext(); QgsSymbolSelectorDialog d( newSymbol.data(), QgsStyle::defaultStyle(), nullptr, this ); - d.setExpressionContext( &context ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d.setContext( symbolContext ); if ( d.exec() == QDialog::Accepted ) { diff --git a/src/app/composer/qgscomposershapewidget.cpp b/src/app/composer/qgscomposershapewidget.cpp index 148ab3bbec5c..fc9770413e46 100644 --- a/src/app/composer/qgscomposershapewidget.cpp +++ b/src/app/composer/qgscomposershapewidget.cpp @@ -110,7 +110,9 @@ void QgsComposerShapeWidget::on_mShapeStyleButton_clicked() QgsFillSymbol* newSymbol = mComposerShape->shapeStyleSymbol()->clone(); QgsExpressionContext context = mComposerShape->createExpressionContext(); QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), coverageLayer, this ); - d.setExpressionContext( &context ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d.setContext( symbolContext ); if ( d.exec() == QDialog::Accepted ) { diff --git a/src/app/composer/qgscompositionwidget.cpp b/src/app/composer/qgscompositionwidget.cpp index 4cb55d112468..536e6978fb02 100644 --- a/src/app/composer/qgscompositionwidget.cpp +++ b/src/app/composer/qgscompositionwidget.cpp @@ -573,7 +573,9 @@ void QgsCompositionWidget::on_mPageStyleButton_clicked() } QgsExpressionContext context = mComposition->createExpressionContext(); QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), coverageLayer, this ); - d.setExpressionContext( &context ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d.setContext( symbolContext ); if ( d.exec() == QDialog::Accepted ) { diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index d819e35817fb..5a48125514db 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -449,7 +449,9 @@ void QgisApp::layerTreeViewDoubleClicked( const QModelIndex& index ) QScopedPointer< QgsSymbol > symbol( originalSymbol->clone() ); QgsVectorLayer* vlayer = qobject_cast( node->layerNode()->layer() ); QgsSymbolSelectorDialog dlg( symbol.data(), QgsStyle::defaultStyle(), vlayer, this ); - dlg.setMapCanvas( mMapCanvas ); + QgsSymbolWidgetContext context; + context.setMapCanvas( mMapCanvas ); + dlg.setContext( context ); if ( dlg.exec() ) { node->setSymbol( symbol.take() ); diff --git a/src/app/qgsapplayertreeviewmenuprovider.cpp b/src/app/qgsapplayertreeviewmenuprovider.cpp index b04b78a0eb53..6d78dab0b48f 100644 --- a/src/app/qgsapplayertreeviewmenuprovider.cpp +++ b/src/app/qgsapplayertreeviewmenuprovider.cpp @@ -495,7 +495,9 @@ void QgsAppLayerTreeViewMenuProvider::editVectorSymbol() QScopedPointer< QgsSymbol > symbol( singleRenderer->symbol() ? singleRenderer->symbol()->clone() : nullptr ); QgsSymbolSelectorDialog dlg( symbol.data(), QgsStyle::defaultStyle(), layer, mView->window() ); dlg.setWindowTitle( tr( "Symbol selector" ) ); - dlg.setMapCanvas( mCanvas ); + QgsSymbolWidgetContext context; + context.setMapCanvas( mCanvas ); + dlg.setContext( context ); if ( dlg.exec() ) { singleRenderer->setSymbol( symbol.take() ); @@ -570,7 +572,9 @@ void QgsAppLayerTreeViewMenuProvider::editSymbolLegendNodeSymbol() QgsVectorLayer* vlayer = qobject_cast( node->layerNode()->layer() ); QgsSymbolSelectorDialog dlg( symbol.data(), QgsStyle::defaultStyle(), vlayer, mView->window() ); dlg.setWindowTitle( tr( "Symbol selector" ) ); - dlg.setMapCanvas( mCanvas ); + QgsSymbolWidgetContext context; + context.setMapCanvas( mCanvas ); + dlg.setContext( context ); if ( dlg.exec() ) { node->setSymbol( symbol.take() ); diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index cc93d6cbe702..1fa7da8522c2 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -43,6 +43,7 @@ SET(QGIS_GUI_SRCS symbology-ng/qgssymbollevelsdialog.cpp symbology-ng/qgssymbolslistwidget.cpp symbology-ng/qgssymbolselectordialog.cpp + symbology-ng/qgssymbolwidgetcontext.cpp symbology-ng/qgsvectorfieldsymbollayerwidget.cpp effects/qgseffectdrawmodecombobox.cpp @@ -707,6 +708,8 @@ SET(QGIS_GUI_HDRS layertree/qgslayertreeembeddedwidgetregistry.h raster/qgsrasterrendererwidget.h + + symbology-ng/qgssymbolwidgetcontext.h ) IF (WITH_QTWEBKIT) diff --git a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp index 29a6dc1cbef2..a57dc4b268cc 100644 --- a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp @@ -527,8 +527,7 @@ void QgsCategorizedSymbolRendererWidget::changeSelectedSymbols() { QgsSymbol* newSymbol = mCategorizedSymbol->clone(); QgsSymbolSelectorDialog dlg( newSymbol, mStyle, mLayer, this ); - dlg.setMapCanvas( mMapCanvas ); - dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg.setContext( context() ); if ( !dlg.exec() ) { delete newSymbol; @@ -550,8 +549,7 @@ void QgsCategorizedSymbolRendererWidget::changeCategorizedSymbol() { QgsSymbol* newSymbol = mCategorizedSymbol->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( newSymbol, mStyle, mLayer, nullptr ); - dlg->setMapCanvas( mMapCanvas ); - dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg->setContext( mContext ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); @@ -595,8 +593,7 @@ void QgsCategorizedSymbolRendererWidget::changeCategorySymbol() } QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( symbol, mStyle, mLayer, nullptr ); - dlg->setMapCanvas( mMapCanvas ); - dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg->setContext( mContext ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); openPanel( dlg ); @@ -1045,10 +1042,10 @@ QgsExpressionContext QgsCategorizedSymbolRendererWidget::createExpressionContext << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mapCanvas() ) + if ( mContext.mapCanvas() ) { - expContext << QgsExpressionContextUtils::mapSettingsScope( mapCanvas()->mapSettings() ) - << new QgsExpressionContextScope( mapCanvas()->expressionContextScope() ); + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -1058,5 +1055,11 @@ QgsExpressionContext QgsCategorizedSymbolRendererWidget::createExpressionContext if ( vectorLayer() ) expContext << QgsExpressionContextUtils::layerScope( vectorLayer() ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + return expContext; } diff --git a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp index 4f924069f405..a1de567c6fc7 100644 --- a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp @@ -396,10 +396,10 @@ QgsExpressionContext QgsGraduatedSymbolRendererWidget::createExpressionContext() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mapCanvas() ) + if ( mContext.mapCanvas() ) { - expContext << QgsExpressionContextUtils::mapSettingsScope( mapCanvas()->mapSettings() ) - << new QgsExpressionContextScope( mapCanvas()->expressionContextScope() ); + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -409,6 +409,12 @@ QgsExpressionContext QgsGraduatedSymbolRendererWidget::createExpressionContext() if ( vectorLayer() ) expContext << QgsExpressionContextUtils::layerScope( vectorLayer() ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + return expContext; } @@ -829,8 +835,7 @@ void QgsGraduatedSymbolRendererWidget::changeGraduatedSymbol() { QgsSymbol* newSymbol = mGraduatedSymbol->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( newSymbol, mStyle, mLayer, nullptr ); - dlg->setMapCanvas( mMapCanvas ); - dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg->setContext( mContext ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( accepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); @@ -908,8 +913,7 @@ void QgsGraduatedSymbolRendererWidget::changeRangeSymbol( int rangeIdx ) { QgsSymbol* newSymbol = mRenderer->ranges()[rangeIdx].symbol()->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( newSymbol, mStyle, mLayer, nullptr ); - dlg->setMapCanvas( mMapCanvas ); - dlg->setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg->setContext( mContext ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolsFromWidget() ) ); connect( dlg, SIGNAL( accepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); diff --git a/src/gui/symbology-ng/qgsheatmaprendererwidget.cpp b/src/gui/symbology-ng/qgsheatmaprendererwidget.cpp index 7b96939109ab..9efd6882b728 100644 --- a/src/gui/symbology-ng/qgsheatmaprendererwidget.cpp +++ b/src/gui/symbology-ng/qgsheatmaprendererwidget.cpp @@ -39,10 +39,10 @@ QgsExpressionContext QgsHeatmapRendererWidget::createExpressionContext() const << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mapCanvas() ) + if ( mContext.mapCanvas() ) { - expContext << QgsExpressionContextUtils::mapSettingsScope( mapCanvas()->mapSettings() ) - << new QgsExpressionContextScope( mapCanvas()->expressionContextScope() ); + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -52,6 +52,12 @@ QgsExpressionContext QgsHeatmapRendererWidget::createExpressionContext() const if ( vectorLayer() ) expContext << QgsExpressionContextUtils::layerScope( vectorLayer() ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + return expContext; } @@ -128,11 +134,11 @@ QgsFeatureRenderer* QgsHeatmapRendererWidget::renderer() return mRenderer; } -void QgsHeatmapRendererWidget::setMapCanvas( QgsMapCanvas* canvas ) +void QgsHeatmapRendererWidget::setContext( const QgsSymbolWidgetContext& context ) { - QgsRendererWidget::setMapCanvas( canvas ); - if ( mRadiusUnitWidget ) - mRadiusUnitWidget->setMapCanvas( canvas ); + QgsRendererWidget::setContext( context ); + if ( context.mapCanvas() ) + mRadiusUnitWidget->setMapCanvas( context.mapCanvas() ); } void QgsHeatmapRendererWidget::applyColorRamp() diff --git a/src/gui/symbology-ng/qgsheatmaprendererwidget.h b/src/gui/symbology-ng/qgsheatmaprendererwidget.h index 2b1703280fcc..cce959a500ee 100644 --- a/src/gui/symbology-ng/qgsheatmaprendererwidget.h +++ b/src/gui/symbology-ng/qgsheatmaprendererwidget.h @@ -46,7 +46,7 @@ class GUI_EXPORT QgsHeatmapRendererWidget : public QgsRendererWidget, private Ui /** @returns the current feature renderer */ virtual QgsFeatureRenderer* renderer() override; - void setMapCanvas( QgsMapCanvas* canvas ) override; + virtual void setContext( const QgsSymbolWidgetContext& context ) override; private: QgsHeatmapRenderer* mRenderer; diff --git a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp index 5772f827d97f..c60b9c3feb67 100644 --- a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp @@ -110,11 +110,11 @@ QgsFeatureRenderer* QgsInvertedPolygonRendererWidget::renderer() return mRenderer.data(); } -void QgsInvertedPolygonRendererWidget::setMapCanvas( QgsMapCanvas* canvas ) +void QgsInvertedPolygonRendererWidget::setContext( const QgsSymbolWidgetContext& context ) { - QgsRendererWidget::setMapCanvas( canvas ); + QgsRendererWidget::setContext( context ); if ( mEmbeddedRendererWidget ) - mEmbeddedRendererWidget->setMapCanvas( canvas ); + mEmbeddedRendererWidget->setContext( context ); } void QgsInvertedPolygonRendererWidget::on_mRendererComboBox_currentIndexChanged( int index ) @@ -125,8 +125,7 @@ void QgsInvertedPolygonRendererWidget::on_mRendererComboBox_currentIndexChanged( { mEmbeddedRendererWidget.reset( m->createRendererWidget( mLayer, mStyle, const_cast( mRenderer->embeddedRenderer() )->clone() ) ); connect( mEmbeddedRendererWidget.data(), SIGNAL( widgetChanged() ), this, SIGNAL( widgetChanged() ) ); - mEmbeddedRendererWidget->setMapCanvas( mMapCanvas ); - mEmbeddedRendererWidget->setAdditionalExpressionContextScopes( mAdditionalScopes ); + mEmbeddedRendererWidget->setContext( mContext ); if ( layout()->count() > 2 ) { diff --git a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h index 749d92d75e1c..526ac40a3283 100644 --- a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h +++ b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h @@ -47,7 +47,8 @@ class GUI_EXPORT QgsInvertedPolygonRendererWidget : public QgsRendererWidget, pr /** @returns the current feature renderer */ virtual QgsFeatureRenderer* renderer() override; - void setMapCanvas( QgsMapCanvas* canvas ) override; + + void setContext( const QgsSymbolWidgetContext& context ) override; protected: /** The mask renderer */ diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp index 3f61edef08db..9d4d1cef8a97 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp @@ -88,14 +88,11 @@ static void _initWidgetFunctions() QgsLayerPropertiesWidget::QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const QgsSymbol* symbol, const QgsVectorLayer* vl, QWidget* parent ) : QgsPanelWidget( parent ) - , mPresetExpressionContext( nullptr ) - , mMapCanvas( nullptr ) + , mLayer( layer ) + , mSymbol( symbol ) + , mVectorLayer( vl ) { - mLayer = layer; - mSymbol = symbol; - mVectorLayer = vl; - setupUi( this ); // initialize the sub-widgets // XXX Should this thing be here this way? Initialize all the widgets just for the sake of one layer? @@ -126,21 +123,18 @@ QgsLayerPropertiesWidget::QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const mEffectWidget->setPaintEffect( mLayer->paintEffect() ); } -void QgsLayerPropertiesWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +void QgsLayerPropertiesWidget::setContext( const QgsSymbolWidgetContext& context ) { - mAdditionalScopes = scopes; + mContext = context; QgsSymbolLayerWidget* w = dynamic_cast< QgsSymbolLayerWidget* >( stackedWidget->currentWidget() ); if ( w ) - w->setAdditionalExpressionContextScopes( mAdditionalScopes ); + w->setContext( mContext ); } -void QgsLayerPropertiesWidget::setMapCanvas( QgsMapCanvas *canvas ) +QgsSymbolWidgetContext QgsLayerPropertiesWidget::context() const { - mMapCanvas = canvas; - QgsSymbolLayerWidget* w = dynamic_cast< QgsSymbolLayerWidget* >( stackedWidget->currentWidget() ); - if ( w ) - w->setMapCanvas( mMapCanvas ); + return mContext; } void QgsLayerPropertiesWidget::setDockMode( bool dockMode ) @@ -149,15 +143,6 @@ void QgsLayerPropertiesWidget::setDockMode( bool dockMode ) mEffectWidget->setDockMode( this->dockMode() ); } -void QgsLayerPropertiesWidget::setExpressionContext( QgsExpressionContext *context ) -{ - mPresetExpressionContext = context; - - QgsSymbolLayerWidget* w = dynamic_cast< QgsSymbolLayerWidget* >( stackedWidget->currentWidget() ); - if ( w ) - w->setExpressionContext( mPresetExpressionContext ); -} - void QgsLayerPropertiesWidget::populateLayerTypes() { QStringList symbolLayerIds = QgsSymbolLayerRegistry::instance()->symbolLayersForType( mSymbol->type() ); @@ -199,10 +184,7 @@ void QgsLayerPropertiesWidget::updateSymbolLayerWidget( QgsSymbolLayer* layer ) QgsSymbolLayerWidget* w = am->createSymbolLayerWidget( mVectorLayer ); if ( w ) { - w->setExpressionContext( mPresetExpressionContext ); - w->setAdditionalExpressionContextScopes( mAdditionalScopes ); - if ( mMapCanvas ) - w->setMapCanvas( mMapCanvas ); + w->setContext( mContext ); w->setSymbolLayer( layer ); stackedWidget->addWidget( w ); stackedWidget->setCurrentWidget( w ); diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.h b/src/gui/symbology-ng/qgslayerpropertieswidget.h index 23a788093fac..545b7c586f80 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.h +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.h @@ -18,6 +18,7 @@ #include "ui_widget_layerproperties.h" #include "qgsexpressioncontext.h" +#include "qgssymbolwidgetcontext.h" class QgsSymbol; class QgsSymbolLayer; @@ -41,27 +42,18 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L public: QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const QgsSymbol* symbol, const QgsVectorLayer* vl, QWidget* parent = nullptr ); - /** Returns the expression context used for the widget, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the properties widget. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const { return mPresetExpressionContext; } - - /** Sets a list of additional expression context scopes to show as available within the layer. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); + QgsSymbolWidgetContext context() const; /** * Set the widget in dock mode which tells the widget to emit panel @@ -74,17 +66,6 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L void layerTypeChanged(); void emitSignalChanged(); - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the properties widget. - * @param context expression context pointer. Ownership is not transferred and the object must - * be kept alive for the lifetime of the properties widget. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context ); - signals: void changed(); void changeLayer( QgsSymbolLayer* ); @@ -103,9 +84,8 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L void reloadLayer(); private: - QgsExpressionContext* mPresetExpressionContext; - QList< QgsExpressionContextScope > mAdditionalScopes; - QgsMapCanvas* mMapCanvas; + + QgsSymbolWidgetContext mContext; }; diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp index d91b0b47f7e4..ca90de09828b 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp @@ -104,11 +104,11 @@ QgsFeatureRenderer* QgsPointClusterRendererWidget::renderer() return mRenderer; } -void QgsPointClusterRendererWidget::setMapCanvas( QgsMapCanvas* canvas ) +void QgsPointClusterRendererWidget::setContext( const QgsSymbolWidgetContext& context ) { - QgsRendererWidget::setMapCanvas( canvas ); + QgsRendererWidget::setContext( context ); if ( mDistanceUnitWidget ) - mDistanceUnitWidget->setMapCanvas( canvas ); + mDistanceUnitWidget->setMapCanvas( context.mapCanvas() ); } void QgsPointClusterRendererWidget::on_mRendererComboBox_currentIndexChanged( int index ) @@ -135,13 +135,15 @@ void QgsPointClusterRendererWidget::on_mRendererSettingsButton_clicked() { QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); w->setPanelTitle( tr( "Renderer settings" ) ); - w->setMapCanvas( mMapCanvas ); + QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); - QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + QList< QgsExpressionContextScope > scopes = mContext.additionalExpressionContextScopes(); scopes << scope; - w->setAdditionalExpressionContextScopes( scopes ); + QgsSymbolWidgetContext context = mContext; + context.setAdditionalExpressionContextScopes( scopes ); + w->setContext( context ); connect( w, SIGNAL( widgetChanged() ), this, SLOT( updateRendererFromWidget() ) ); w->setDockMode( this->dockMode() ); openPanel( w ); @@ -185,13 +187,16 @@ void QgsPointClusterRendererWidget::on_mCenterSymbolPushButton_clicked() QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); dlg->setPanelTitle( tr( "Cluster symbol" ) ); dlg->setDockMode( this->dockMode() ); - dlg->setMapCanvas( mMapCanvas ); + + QgsSymbolWidgetContext context = mContext; QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); - QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + QList< QgsExpressionContextScope > scopes = context.additionalExpressionContextScopes(); scopes << scope; - dlg->setAdditionalExpressionContextScopes( scopes ); + context.setAdditionalExpressionContextScopes( scopes ); + + dlg->setContext( context ); connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateCenterSymbolFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.h b/src/gui/symbology-ng/qgspointclusterrendererwidget.h index 940fbaf4f4fa..983e8e1099aa 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.h +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.h @@ -32,7 +32,7 @@ class GUI_EXPORT QgsPointClusterRendererWidget: public QgsRendererWidget, privat ~QgsPointClusterRendererWidget(); QgsFeatureRenderer* renderer() override; - void setMapCanvas( QgsMapCanvas* canvas ) override; + void setContext( const QgsSymbolWidgetContext& context ) override; private: QgsPointClusterRenderer* mRenderer; diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index 8d77f2c0f9c5..42a1df451898 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -158,11 +158,11 @@ QgsFeatureRenderer* QgsPointDisplacementRendererWidget::renderer() return mRenderer; } -void QgsPointDisplacementRendererWidget::setMapCanvas( QgsMapCanvas* canvas ) +void QgsPointDisplacementRendererWidget::setContext( const QgsSymbolWidgetContext& context ) { - QgsRendererWidget::setMapCanvas( canvas ); + QgsRendererWidget::setContext( context ); if ( mDistanceUnitWidget ) - mDistanceUnitWidget->setMapCanvas( canvas ); + mDistanceUnitWidget->setMapCanvas( context.mapCanvas() ); } void QgsPointDisplacementRendererWidget::on_mLabelFieldComboBox_currentIndexChanged( const QString& text ) @@ -214,13 +214,17 @@ void QgsPointDisplacementRendererWidget::on_mRendererSettingsButton_clicked() { QgsRendererWidget* w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); w->setPanelTitle( tr( "Renderer settings" ) ); - w->setMapCanvas( mMapCanvas ); + + QgsSymbolWidgetContext context = mContext; + QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); - QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + QList< QgsExpressionContextScope > scopes = context.additionalExpressionContextScopes(); scopes << scope; - w->setAdditionalExpressionContextScopes( scopes ); + context.setAdditionalExpressionContextScopes( scopes ); + w->setContext( context ); + connect( w, SIGNAL( widgetChanged() ), this, SLOT( updateRendererFromWidget() ) ); openPanel( w ); } @@ -357,15 +361,18 @@ void QgsPointDisplacementRendererWidget::on_mCenterSymbolPushButton_clicked() } QgsMarkerSymbol* markerSymbol = mRenderer->centerSymbol()->clone(); QgsSymbolSelectorWidget* dlg = new QgsSymbolSelectorWidget( markerSymbol, QgsStyle::defaultStyle(), mLayer, this ); - dlg->setMapCanvas( mMapCanvas ); dlg->setPanelTitle( tr( "Center symbol" ) ); + QgsSymbolWidgetContext context = mContext; + QgsExpressionContextScope scope; scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); - QList< QgsExpressionContextScope > scopes = mAdditionalScopes; + QList< QgsExpressionContextScope > scopes = context.additionalExpressionContextScopes(); scopes << scope; - dlg->setAdditionalExpressionContextScopes( scopes ); + context.setAdditionalExpressionContextScopes( scopes ); + dlg->setContext( context ); + connect( dlg, SIGNAL( widgetChanged() ), this, SLOT( updateCenterSymbolFromWidget() ) ); connect( dlg, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); openPanel( dlg ); diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.h b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.h index 9f30357577d7..801f55032713 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.h +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.h @@ -35,7 +35,7 @@ class GUI_EXPORT QgsPointDisplacementRendererWidget: public QgsRendererWidget, p ~QgsPointDisplacementRendererWidget(); QgsFeatureRenderer* renderer() override; - void setMapCanvas( QgsMapCanvas* canvas ) override; + void setContext( const QgsSymbolWidgetContext& context ) override; private: QgsPointDisplacementRenderer* mRenderer; diff --git a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp index a277ab3e5272..841976f59294 100644 --- a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp +++ b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp @@ -191,7 +191,11 @@ void QgsRendererPropertiesDialog::setMapCanvas( QgsMapCanvas* canvas ) { mMapCanvas = canvas; if ( mActiveWidget ) - mActiveWidget->setMapCanvas( mMapCanvas ); + { + QgsSymbolWidgetContext context; + context.setMapCanvas( mMapCanvas ); + mActiveWidget->setContext( context ); + } } void QgsRendererPropertiesDialog::setDockMode( bool dockMode ) @@ -248,7 +252,11 @@ void QgsRendererPropertiesDialog::rendererChanged() if ( mActiveWidget->renderer() ) { if ( mMapCanvas ) - mActiveWidget->setMapCanvas( mMapCanvas ); + { + QgsSymbolWidgetContext context; + context.setMapCanvas( mMapCanvas ); + mActiveWidget->setContext( context ); + } changeOrderBy( mActiveWidget->renderer()->orderBy(), mActiveWidget->renderer()->orderByEnabled() ); connect( mActiveWidget, SIGNAL( layerVariablesChanged() ), this, SIGNAL( layerVariablesChanged() ) ); } diff --git a/src/gui/symbology-ng/qgsrendererwidget.cpp b/src/gui/symbology-ng/qgsrendererwidget.cpp index efdfbf86348a..95288e1cbb25 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrendererwidget.cpp @@ -30,7 +30,6 @@ QgsRendererWidget::QgsRendererWidget( QgsVectorLayer* layer, QgsStyle* style ) : QgsPanelWidget() , mLayer( layer ) , mStyle( style ) - , mMapCanvas( nullptr ) { contextMenu = new QMenu( tr( "Renderer Options" ), this ); @@ -171,8 +170,8 @@ void QgsRendererWidget::changeSymbolWidth() } QgsDataDefinedWidthDialog dlg( symbolList, mLayer ); - dlg.setMapCanvas( mMapCanvas ); - dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); + + dlg.setContext( mContext ); if ( QDialog::Accepted == dlg.exec() ) { @@ -200,8 +199,7 @@ void QgsRendererWidget::changeSymbolSize() } QgsDataDefinedSizeDialog dlg( symbolList, mLayer ); - dlg.setMapCanvas( mMapCanvas ); - dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg.setContext( mContext ); if ( QDialog::Accepted == dlg.exec() ) { @@ -229,8 +227,7 @@ void QgsRendererWidget::changeSymbolAngle() } QgsDataDefinedRotationDialog dlg( symbolList, mLayer ); - dlg.setMapCanvas( mMapCanvas ); - dlg.setAdditionalExpressionContextScopes( mAdditionalScopes ); + dlg.setContext( mContext ); if ( QDialog::Accepted == dlg.exec() ) { @@ -262,19 +259,14 @@ void QgsRendererWidget::showSymbolLevelsDialog( QgsFeatureRenderer* r ) } } -void QgsRendererWidget::setMapCanvas( QgsMapCanvas *canvas ) -{ - mMapCanvas = canvas; -} - -const QgsMapCanvas* QgsRendererWidget::mapCanvas() const +void QgsRendererWidget::setContext( const QgsSymbolWidgetContext& context ) { - return mMapCanvas; + mContext = context; } -void QgsRendererWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +QgsSymbolWidgetContext QgsRendererWidget::context() const { - mAdditionalScopes = scopes; + return mContext; } void QgsRendererWidget::applyChanges() @@ -289,7 +281,6 @@ void QgsRendererWidget::applyChanges() QgsDataDefinedValueDialog::QgsDataDefinedValueDialog( const QList& symbolList, QgsVectorLayer * layer, const QString & label ) : mSymbolList( symbolList ) , mLayer( layer ) - , mMapCanvas( nullptr ) { setupUi( this ); setWindowFlags( Qt::WindowStaysOnTopHint ); @@ -299,19 +290,19 @@ QgsDataDefinedValueDialog::QgsDataDefinedValueDialog( const QList& s } -void QgsDataDefinedValueDialog::setMapCanvas( QgsMapCanvas *canvas ) +void QgsDataDefinedValueDialog::setContext( const QgsSymbolWidgetContext& context ) { - mMapCanvas = canvas; + mContext = context; Q_FOREACH ( QgsDataDefinedButton* ddButton, findChildren() ) { if ( ddButton->assistant() ) - ddButton->assistant()->setMapCanvas( mMapCanvas ); + ddButton->assistant()->setMapCanvas( context.mapCanvas() ); } } -const QgsMapCanvas *QgsDataDefinedValueDialog::mapCanvas() const +QgsSymbolWidgetContext QgsDataDefinedValueDialog::context() const { - return mMapCanvas; + return mContext; } QgsExpressionContext QgsDataDefinedValueDialog::createExpressionContext() const @@ -320,10 +311,10 @@ QgsExpressionContext QgsDataDefinedValueDialog::createExpressionContext() const expContext << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mapCanvas() ) + if ( mContext.mapCanvas() ) { - expContext << QgsExpressionContextUtils::mapSettingsScope( mapCanvas()->mapSettings() ) - << new QgsExpressionContextScope( mapCanvas()->expressionContextScope() ); + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -334,7 +325,7 @@ QgsExpressionContext QgsDataDefinedValueDialog::createExpressionContext() const expContext << QgsExpressionContextUtils::layerScope( vectorLayer() ); // additional scopes - Q_FOREACH ( const QgsExpressionContextScope& scope, mAdditionalScopes ) + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) { expContext.appendScope( new QgsExpressionContextScope( scope ) ); } diff --git a/src/gui/symbology-ng/qgsrendererwidget.h b/src/gui/symbology-ng/qgsrendererwidget.h index 9f1c3128cd55..aa92910d9fa4 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.h +++ b/src/gui/symbology-ng/qgsrendererwidget.h @@ -20,6 +20,7 @@ #include #include "qgssymbol.h" #include "qgspanelwidget.h" +#include "qgssymbolwidgetcontext.h" class QgsVectorLayer; class QgsStyle; @@ -51,25 +52,18 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget //! show a dialog with renderer's symbol level settings void showSymbolLevelsDialog( QgsFeatureRenderer* r ); - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); - - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Sets the context in which the renderer widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + virtual void setContext( const QgsSymbolWidgetContext& context ); - /** Sets a list of additional expression context scopes to show as available within the renderer. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Returns the context in which the renderer widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() * @note added in QGIS 3.0 */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 @@ -95,10 +89,9 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget QMenu* contextMenu; QAction* mCopyAction; QAction* mPasteAction; - QgsMapCanvas* mMapCanvas; - //! List of additional expression context scopes to add to default expression context - QList< QgsExpressionContextScope > mAdditionalScopes; + //! Context in which widget is shown + QgsSymbolWidgetContext mContext; /** Subclasses may provide the capability of changing multiple symbols at once by implementing the following two methods and by connecting the slot contextMenuViewCategories(const QPoint&)*/ @@ -161,31 +154,24 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD QgsDataDefinedValueDialog( const QList& symbolList, QgsVectorLayer * layer, const QString & label ); virtual ~QgsDataDefinedValueDialog() {} - /** Sets the map canvas associated with the dialog. This allows the dialog to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() + * @note added in QGIS 3.0 */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 */ const QgsVectorLayer* vectorLayer() const { return mLayer; } - /** Sets a list of additional expression context scopes to show as available for the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context - * @note added in QGIS 3.0 - */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ) { mAdditionalScopes = scopes; } - public slots: void dataDefinedChanged(); @@ -197,9 +183,6 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD */ void init( const QString& description ); // needed in children ctor to call virtual - //! List of additional scopes to add to default expression context - QList< QgsExpressionContextScope > mAdditionalScopes; - private: QgsDataDefined symbolDataDefined() const; @@ -209,7 +192,8 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD QList mSymbolList; QgsVectorLayer* mLayer; - QgsMapCanvas* mMapCanvas; + + QgsSymbolWidgetContext mContext; QgsExpressionContext createExpressionContext() const override; }; diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp index c8929fc47b7e..8d747ef28475 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp @@ -179,7 +179,7 @@ void QgsRuleBasedRendererWidget::editRule( const QModelIndex& index ) QgsRuleBasedRenderer::Rule* rule = mModel->ruleForIndex( index ); - QgsRendererRulePropsWidget* widget = new QgsRendererRulePropsWidget( rule, mLayer, mStyle, this, mMapCanvas ); + QgsRendererRulePropsWidget* widget = new QgsRendererRulePropsWidget( rule, mLayer, mStyle, this, mContext ); widget->setDockMode( true ); widget->setPanelTitle( tr( "Edit rule" ) ); connect( widget, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( ruleWidgetPanelAccepted( QgsPanelWidget* ) ) ); @@ -260,8 +260,7 @@ void QgsRuleBasedRendererWidget::refineRuleCategoriesGui() QgsCategorizedSymbolRendererWidget* w = new QgsCategorizedSymbolRendererWidget( mLayer, mStyle, nullptr ); w->setPanelTitle( tr( "Add categories to rules" ) ); connect( w, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( refineRuleCategoriesAccepted( QgsPanelWidget* ) ) ); - w->setMapCanvas( mMapCanvas ); - w->setAdditionalExpressionContextScopes( mAdditionalScopes ); + w->setContext( mContext ); openPanel( w ); } @@ -270,8 +269,7 @@ void QgsRuleBasedRendererWidget::refineRuleRangesGui() QgsGraduatedSymbolRendererWidget* w = new QgsGraduatedSymbolRendererWidget( mLayer, mStyle, nullptr ); w->setPanelTitle( tr( "Add ranges to rules" ) ); connect( w, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( refineRuleRangesAccepted( QgsPanelWidget* ) ) ); - w->setMapCanvas( mMapCanvas ); - w->setAdditionalExpressionContextScopes( mAdditionalScopes ); + w->setContext( mContext ); openPanel( w ); } @@ -528,16 +526,21 @@ void QgsRuleBasedRendererWidget::countFeatures() context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mMapCanvas ) + if ( mContext.mapCanvas() ) { - context << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) - << new QgsExpressionContextScope( mMapCanvas->expressionContextScope() ); + context << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { context << QgsExpressionContextUtils::mapSettingsScope( QgsMapSettings() ); } context << QgsExpressionContextUtils::layerScope( mLayer ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + context.appendScope( new QgsExpressionContextScope( scope ) ); + } renderContext.setExpressionContext( context ); req.setExpressionContext( context ); @@ -608,13 +611,13 @@ void QgsRuleBasedRendererWidget::selectedRulesChanged() /////////// -QgsRendererRulePropsWidget::QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent , QgsMapCanvas* mapCanvas ) +QgsRendererRulePropsWidget::QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent, const QgsSymbolWidgetContext& context ) : QgsPanelWidget( parent ) , mRule( rule ) , mLayer( layer ) , mSymbolSelector( nullptr ) , mSymbol( nullptr ) - , mMapCanvas( mapCanvas ) + , mContext( context ) { setupUi( this ); layout()->setMargin( 0 ); @@ -635,7 +638,7 @@ QgsRendererRulePropsWidget::QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Ru if ( rule->scaleMaxDenom() > 0 ) mScaleRangeWidget->setMinimumScale( 1.0 / rule->scaleMaxDenom() ); } - mScaleRangeWidget->setMapCanvas( mMapCanvas ); + mScaleRangeWidget->setMapCanvas( mContext.mapCanvas() ); if ( mRule->symbol() ) { @@ -649,7 +652,7 @@ QgsRendererRulePropsWidget::QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Ru } mSymbolSelector = new QgsSymbolSelectorWidget( mSymbol, style, mLayer, this ); - mSymbolSelector->setMapCanvas( mMapCanvas ); + mSymbolSelector->setContext( mContext ); connect( mSymbolSelector, SIGNAL( widgetChanged() ), this, SIGNAL( widgetChanged() ) ); connect( mSymbolSelector, SIGNAL( showPanel( QgsPanelWidget* ) ), this, SLOT( openPanel( QgsPanelWidget* ) ) ); @@ -672,7 +675,7 @@ QgsRendererRulePropsWidget::~QgsRendererRulePropsWidget() } -QgsRendererRulePropsDialog::QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule *rule, QgsVectorLayer *layer, QgsStyle *style, QWidget *parent, QgsMapCanvas *mapCanvas ) +QgsRendererRulePropsDialog::QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule *rule, QgsVectorLayer *layer, QgsStyle *style, QWidget *parent, const QgsSymbolWidgetContext& context ) : QDialog( parent ) { @@ -682,7 +685,7 @@ QgsRendererRulePropsDialog::QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Ru this->setLayout( new QVBoxLayout() ); buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel ); - mPropsWidget = new QgsRendererRulePropsWidget( rule, layer, style, this, mapCanvas ); + mPropsWidget = new QgsRendererRulePropsWidget( rule, layer, style, this, context ); this->layout()->addWidget( mPropsWidget ); this->layout()->addWidget( buttonBox ); @@ -722,10 +725,10 @@ void QgsRendererRulePropsWidget::buildExpression() context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mMapCanvas ) + if ( mContext.mapCanvas() ) { - context << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) - << new QgsExpressionContextScope( mMapCanvas->expressionContextScope() ); + context << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -733,6 +736,12 @@ void QgsRendererRulePropsWidget::buildExpression() } context << QgsExpressionContextUtils::layerScope( mLayer ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + context.appendScope( new QgsExpressionContextScope( scope ) ); + } + QgsExpressionBuilderDialog dlg( mLayer, editFilter->text(), this, "generic", context ); if ( dlg.exec() ) @@ -752,16 +761,21 @@ void QgsRendererRulePropsWidget::testFilter() context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mMapCanvas ) + if ( mContext.mapCanvas() ) { - context << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) - << new QgsExpressionContextScope( mMapCanvas->expressionContextScope() ); + context << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { context << QgsExpressionContextUtils::mapSettingsScope( QgsMapSettings() ); } context << QgsExpressionContextUtils::layerScope( mLayer ); + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + context.appendScope( new QgsExpressionContextScope( scope ) ); + } if ( !filter.prepare( &context ) ) { diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.h b/src/gui/symbology-ng/qgsrulebasedrendererwidget.h index 28c86ffdf123..acbd9587cfa5 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.h +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.h @@ -189,9 +189,9 @@ class GUI_EXPORT QgsRendererRulePropsWidget : public QgsPanelWidget, private Ui: * @param layer The layer used to pull layer related information. * @param style The active QGIS style. * @param parent The parent widget. - * @param mapCanvas The map canvas object. + * @param context the symbol widget context */ - QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent = nullptr, QgsMapCanvas* mapCanvas = nullptr ); + QgsRendererRulePropsWidget( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent = nullptr, const QgsSymbolWidgetContext& context = QgsSymbolWidgetContext() ); ~QgsRendererRulePropsWidget(); /** @@ -229,7 +229,7 @@ class GUI_EXPORT QgsRendererRulePropsWidget : public QgsPanelWidget, private Ui: QgsSymbolSelectorWidget* mSymbolSelector; QgsSymbol* mSymbol; // a clone of original symbol - QgsMapCanvas* mMapCanvas; + QgsSymbolWidgetContext mContext; }; /** \ingroup gui @@ -240,7 +240,7 @@ class GUI_EXPORT QgsRendererRulePropsDialog : public QDialog Q_OBJECT public: - QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent = nullptr, QgsMapCanvas* mapCanvas = nullptr ); + QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent = nullptr, const QgsSymbolWidgetContext& context = QgsSymbolWidgetContext() ); ~QgsRendererRulePropsDialog(); QgsRuleBasedRenderer::Rule* rule() { return mPropsWidget->rule(); } diff --git a/src/gui/symbology-ng/qgssinglesymbolrendererwidget.cpp b/src/gui/symbology-ng/qgssinglesymbolrendererwidget.cpp index cb231b52ad4d..e11cc5b7c719 100644 --- a/src/gui/symbology-ng/qgssinglesymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgssinglesymbolrendererwidget.cpp @@ -80,11 +80,11 @@ QgsFeatureRenderer* QgsSingleSymbolRendererWidget::renderer() return mRenderer; } -void QgsSingleSymbolRendererWidget::setMapCanvas( QgsMapCanvas* canvas ) +void QgsSingleSymbolRendererWidget::setContext( const QgsSymbolWidgetContext& context ) { - QgsRendererWidget::setMapCanvas( canvas ); + QgsRendererWidget::setContext( context ); if ( mSelector ) - mSelector->setMapCanvas( canvas ); + mSelector->setContext( context ); } void QgsSingleSymbolRendererWidget::setDockMode( bool dockMode ) diff --git a/src/gui/symbology-ng/qgssinglesymbolrendererwidget.h b/src/gui/symbology-ng/qgssinglesymbolrendererwidget.h index 22834dc13df7..586e102c0fe0 100644 --- a/src/gui/symbology-ng/qgssinglesymbolrendererwidget.h +++ b/src/gui/symbology-ng/qgssinglesymbolrendererwidget.h @@ -37,7 +37,7 @@ class GUI_EXPORT QgsSingleSymbolRendererWidget : public QgsRendererWidget virtual QgsFeatureRenderer* renderer() override; - virtual void setMapCanvas( QgsMapCanvas* canvas ) override; + virtual void setContext( const QgsSymbolWidgetContext& context ) override; /** * Set the widget in dock mode which tells the widget to emit panel diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.cpp b/src/gui/symbology-ng/qgssymbollayerwidget.cpp index ad18f6856784..d42460459b0c 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgssymbollayerwidget.cpp @@ -51,18 +51,18 @@ QgsExpressionContext QgsSymbolLayerWidget::createExpressionContext() const { - if ( expressionContext() ) - return *expressionContext(); + if ( mContext.expressionContext() ) + return *mContext.expressionContext(); QgsExpressionContext expContext; expContext << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mapCanvas() ) + if ( mContext.mapCanvas() ) { - expContext << QgsExpressionContextUtils::mapSettingsScope( mapCanvas()->mapSettings() ) - << new QgsExpressionContextScope( mapCanvas()->expressionContextScope() ); + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -85,7 +85,7 @@ QgsExpressionContext QgsSymbolLayerWidget::createExpressionContext() const expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, 1, true ) ); // additional scopes - Q_FOREACH ( const QgsExpressionContextScope& scope, mAdditionalScopes ) + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) { expContext.appendScope( new QgsExpressionContextScope( scope ) ); } @@ -101,28 +101,23 @@ QgsExpressionContext QgsSymbolLayerWidget::createExpressionContext() const return expContext; } -void QgsSymbolLayerWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +void QgsSymbolLayerWidget::setContext( const QgsSymbolWidgetContext& context ) { - mAdditionalScopes = scopes; -} - -void QgsSymbolLayerWidget::setMapCanvas( QgsMapCanvas *canvas ) -{ - mMapCanvas = canvas; + mContext = context; Q_FOREACH ( QgsUnitSelectionWidget* unitWidget, findChildren() ) { - unitWidget->setMapCanvas( mMapCanvas ); + unitWidget->setMapCanvas( mContext.mapCanvas() ); } Q_FOREACH ( QgsDataDefinedButton* ddButton, findChildren() ) { if ( ddButton->assistant() ) - ddButton->assistant()->setMapCanvas( mMapCanvas ); + ddButton->assistant()->setMapCanvas( mContext.mapCanvas() ); } } -const QgsMapCanvas* QgsSymbolLayerWidget::mapCanvas() const +QgsSymbolWidgetContext QgsSymbolLayerWidget::context() const { - return mMapCanvas; + return mContext; } void QgsSymbolLayerWidget::registerDataDefinedButton( QgsDataDefinedButton * button, const QString & propertyName, QgsDataDefinedButton::DataType type, const QString & description ) diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.h b/src/gui/symbology-ng/qgssymbollayerwidget.h index ab104109c064..732f2926fcb4 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.h +++ b/src/gui/symbology-ng/qgssymbollayerwidget.h @@ -17,8 +17,8 @@ #ifndef QGSSYMBOLLAYERWIDGET_H #define QGSSYMBOLLAYERWIDGET_H -#include - +#include "qgsdatadefinedbutton.h" +#include "qgssymbolwidgetcontext.h" #include #include @@ -36,7 +36,6 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC public: QgsSymbolLayerWidget( QWidget* parent, const QgsVectorLayer* vl = nullptr ) : QWidget( parent ) - , mPresetExpressionContext( nullptr ) , mVectorLayer( vl ) , mMapCanvas( nullptr ) {} @@ -45,66 +44,33 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC virtual void setSymbolLayer( QgsSymbolLayer* layer ) = 0; virtual QgsSymbolLayer* symbolLayer() = 0; - /** Returns the expression context used for the widget, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const { return mPresetExpressionContext; } - - /** Sets a list of additional expression context scopes to show as available within the layer. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); - - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 */ const QgsVectorLayer* vectorLayer() const { return mVectorLayer; } - public slots: - - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @param context expression context pointer. Ownership is not transferred and the object must - * be kept alive for the lifetime of the layer widget. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context ) { mPresetExpressionContext = context; } - protected: void registerDataDefinedButton( QgsDataDefinedButton* button, const QString& propertyName, QgsDataDefinedButton::DataType type, const QString& description ); QgsExpressionContext createExpressionContext() const override; - //! Optional preset expression context - QgsExpressionContext* mPresetExpressionContext; - private: const QgsVectorLayer* mVectorLayer; QgsMapCanvas* mMapCanvas; - QList< QgsExpressionContextScope > mAdditionalScopes; signals: /** @@ -122,6 +88,9 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC protected slots: void updateDataDefinedProperty(); + + private: + QgsSymbolWidgetContext mContext; }; /////////// diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.cpp b/src/gui/symbology-ng/qgssymbolselectordialog.cpp index f996f3980fc6..5d2a3d2b1d98 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.cpp +++ b/src/gui/symbology-ng/qgssymbolselectordialog.cpp @@ -212,7 +212,6 @@ QgsSymbolSelectorWidget::QgsSymbolSelectorWidget( QgsSymbol* symbol, QgsStyle* s : QgsPanelWidget( parent ) , mAdvancedMenu( nullptr ) , mVectorLayer( vl ) - , mMapCanvas( nullptr ) { #ifdef Q_OS_MAC setWindowModality( Qt::WindowModal ); @@ -279,30 +278,26 @@ QMenu* QgsSymbolSelectorWidget::advancedMenu() return mAdvancedMenu; } -void QgsSymbolSelectorWidget::setExpressionContext( QgsExpressionContext *context ) +void QgsSymbolSelectorWidget::setContext( const QgsSymbolWidgetContext& context ) { - mPresetExpressionContext.reset( context ); - layerChanged(); - updatePreview(); -} - -void QgsSymbolSelectorWidget::setAdditionalExpressionContextScopes( const QList& scopes ) -{ - mAdditionalScopes = scopes; -} - -void QgsSymbolSelectorWidget::setMapCanvas( QgsMapCanvas *canvas ) -{ - mMapCanvas = canvas; + mContext = context; QWidget* widget = stackedWidget->currentWidget(); QgsLayerPropertiesWidget* layerProp = dynamic_cast< QgsLayerPropertiesWidget* >( widget ); QgsSymbolsListWidget* listWidget = dynamic_cast< QgsSymbolsListWidget* >( widget ); if ( layerProp ) - layerProp->setMapCanvas( canvas ); + layerProp->setContext( context ); if ( listWidget ) - listWidget->setMapCanvas( canvas ); + listWidget->setContext( context ); + + layerChanged(); + updatePreview(); +} + +QgsSymbolWidgetContext QgsSymbolSelectorWidget::context() const +{ + return mContext; } void QgsSymbolSelectorWidget::loadSymbol( QgsSymbol* symbol, SymbolLayerItem* parent ) @@ -364,7 +359,7 @@ void QgsSymbolSelectorWidget::updateUi() void QgsSymbolSelectorWidget::updatePreview() { - QImage preview = mSymbol->bigSymbolPreviewImage( mPresetExpressionContext.data() ); + QImage preview = mSymbol->bigSymbolPreviewImage( mContext.expressionContext() ); lblPreview->setPixmap( QPixmap::fromImage( preview ) ); // Hope this is a appropriate place emit symbolModified(); @@ -420,9 +415,7 @@ void QgsSymbolSelectorWidget::layerChanged() mDataDefineRestorer.reset( new DataDefinedRestorer( parent->symbol(), currentItem->layer() ) ); QgsLayerPropertiesWidget *layerProp = new QgsLayerPropertiesWidget( currentItem->layer(), parent->symbol(), mVectorLayer ); layerProp->setDockMode( this->dockMode() ); - layerProp->setExpressionContext( mPresetExpressionContext.data() ); - layerProp->setAdditionalExpressionContextScopes( mAdditionalScopes ); - layerProp->setMapCanvas( mMapCanvas ); + layerProp->setContext( mContext ); setWidget( layerProp ); connect( layerProp, SIGNAL( changed() ), mDataDefineRestorer.data(), SLOT( restore() ) ); connect( layerProp, SIGNAL( changed() ), this, SLOT( updateLayerPreview() ) ); @@ -438,9 +431,7 @@ void QgsSymbolSelectorWidget::layerChanged() currentItem->symbol()->setLayer( mVectorLayer ); // Now populate symbols of that type using the symbols list widget: QgsSymbolsListWidget *symbolsList = new QgsSymbolsListWidget( currentItem->symbol(), mStyle, mAdvancedMenu, this, mVectorLayer ); - symbolsList->setExpressionContext( mPresetExpressionContext.data() ); - symbolsList->setAdditionalExpressionContextScopes( mAdditionalScopes ); - symbolsList->setMapCanvas( mMapCanvas ); + symbolsList->setContext( mContext ); setWidget( symbolsList ); connect( symbolsList, SIGNAL( changed() ), this, SLOT( symbolChanged() ) ); @@ -713,24 +704,14 @@ QMenu *QgsSymbolSelectorDialog::advancedMenu() return mSelectorWidget->advancedMenu(); } -void QgsSymbolSelectorDialog::setExpressionContext( QgsExpressionContext *context ) -{ - mSelectorWidget->setExpressionContext( context ); -} - -void QgsSymbolSelectorDialog::setAdditionalExpressionContextScopes( const QList& scopes ) -{ - mSelectorWidget->setAdditionalExpressionContextScopes( scopes ); -} - -QgsExpressionContext *QgsSymbolSelectorDialog::expressionContext() const +void QgsSymbolSelectorDialog::setContext( const QgsSymbolWidgetContext& context ) { - return mSelectorWidget->expressionContext(); + mContext = context; } -void QgsSymbolSelectorDialog::setMapCanvas( QgsMapCanvas *canvas ) +QgsSymbolWidgetContext QgsSymbolSelectorDialog::context() const { - mSelectorWidget->setMapCanvas( canvas ); + return mContext; } QgsSymbol *QgsSymbolSelectorDialog::symbol() diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.h b/src/gui/symbology-ng/qgssymbolselectordialog.h index 8df7d28b9940..0a9680896e1f 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.h +++ b/src/gui/symbology-ng/qgssymbolselectordialog.h @@ -22,6 +22,7 @@ #include "qgsdatadefined.h" #include "qgspanelwidget.h" +#include "qgssymbolwidgetcontext.h" #include #include @@ -98,37 +99,18 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs //! return menu for "advanced" button - create it if doesn't exist and show the advanced button QMenu* advancedMenu(); - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @param context expression context pointer. Ownership is transferred to the dialog. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context ); - - /** Returns the expression context used for the dialog, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the dialog. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const { return mPresetExpressionContext.data(); } - - /** Sets a list of additional expression context scopes to show as available for the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - void setMapCanvas( QgsMapCanvas* canvas ); + QgsSymbolWidgetContext context() const; /** * @brief Return the symbol that is currently active in the widget. Can be null. @@ -252,10 +234,7 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs private: QScopedPointer mDataDefineRestorer; - QScopedPointer< QgsExpressionContext > mPresetExpressionContext; - QList< QgsExpressionContextScope > mAdditionalScopes; - - QgsMapCanvas* mMapCanvas; + QgsSymbolWidgetContext mContext; }; /** \ingroup gui @@ -272,37 +251,18 @@ class GUI_EXPORT QgsSymbolSelectorDialog : public QDialog //! return menu for "advanced" button - create it if doesn't exist and show the advanced button QMenu* advancedMenu(); - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the layer widget. - * @param context expression context pointer. Ownership is transferred to the dialog. - * @note added in QGIS 2.12 - * @see expressionContext() - * @see setAdditionalExpressionContextScopes() - */ - void setExpressionContext( QgsExpressionContext* context ); - - /** Sets a list of additional expression context scopes to show as available within the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 - * @see setExpressionContext() */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Returns the expression context used for the dialog, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the dialog. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const; - - /** Sets the map canvas associated with the dialog. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - void setMapCanvas( QgsMapCanvas* canvas ); + QgsSymbolWidgetContext context() const; /** * @brief Return the symbol that is currently active in the widget. Can be null. @@ -360,6 +320,7 @@ class GUI_EXPORT QgsSymbolSelectorDialog : public QDialog private: QgsSymbolSelectorWidget* mSelectorWidget; QDialogButtonBox* mButtonBox; + QgsSymbolWidgetContext mContext; }; #endif diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index 48d7fd747435..389fe874f430 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -49,7 +49,6 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, , mClipFeaturesAction( nullptr ) , mLayer( layer ) , mMapCanvas( nullptr ) - , mPresetExpressionContext( nullptr ) { setupUi( this ); @@ -130,33 +129,23 @@ QgsSymbolsListWidget::~QgsSymbolsListWidget() btnAdvanced->menu()->removeAction( mClipFeaturesAction ); } -void QgsSymbolsListWidget::setAdditionalExpressionContextScopes( const QList& scopes ) +void QgsSymbolsListWidget::setContext( const QgsSymbolWidgetContext& context ) { - mAdditionalScopes = scopes; -} - -void QgsSymbolsListWidget::setMapCanvas( QgsMapCanvas* canvas ) -{ - mMapCanvas = canvas; + mContext = context; Q_FOREACH ( QgsUnitSelectionWidget* unitWidget, findChildren() ) { - unitWidget->setMapCanvas( canvas ); + unitWidget->setMapCanvas( mContext.mapCanvas() ); } Q_FOREACH ( QgsDataDefinedButton* ddButton, findChildren() ) { if ( ddButton->assistant() ) - ddButton->assistant()->setMapCanvas( mMapCanvas ); + ddButton->assistant()->setMapCanvas( mContext.mapCanvas() ); } } -const QgsMapCanvas*QgsSymbolsListWidget::mapCanvas() const +QgsSymbolWidgetContext QgsSymbolsListWidget::context() const { - return mMapCanvas; -} - -void QgsSymbolsListWidget::setExpressionContext( QgsExpressionContext *context ) -{ - mPresetExpressionContext = context; + return mContext; } void QgsSymbolsListWidget::populateGroups( const QString& parent, const QString& prepend ) @@ -432,8 +421,8 @@ void QgsSymbolsListWidget::updateSymbolColor() QgsExpressionContext QgsSymbolsListWidget::createExpressionContext() const { - if ( expressionContext() ) - return QgsExpressionContext( *expressionContext() ); + if ( mContext.expressionContext() ) + return QgsExpressionContext( *mContext.expressionContext() ); //otherwise create a default symbol context QgsExpressionContext expContext; @@ -441,10 +430,10 @@ QgsExpressionContext QgsSymbolsListWidget::createExpressionContext() const << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ); - if ( mapCanvas() ) + if ( mContext.mapCanvas() ) { - expContext << QgsExpressionContextUtils::mapSettingsScope( mapCanvas()->mapSettings() ) - << new QgsExpressionContextScope( mapCanvas()->expressionContextScope() ); + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); } else { @@ -454,11 +443,16 @@ QgsExpressionContext QgsSymbolsListWidget::createExpressionContext() const expContext << QgsExpressionContextUtils::layerScope( layer() ); // additional scopes - Q_FOREACH ( const QgsExpressionContextScope& scope, mAdditionalScopes ) + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) { expContext.appendScope( new QgsExpressionContextScope( scope ) ); } + expContext.setHighlightedVariables( QStringList() << QgsExpressionContext::EXPR_ORIGINAL_VALUE << QgsExpressionContext::EXPR_SYMBOL_COLOR + << QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT << QgsExpressionContext::EXPR_GEOMETRY_PART_NUM + << QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT << QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM + << QgsExpressionContext::EXPR_CLUSTER_COLOR << QgsExpressionContext::EXPR_CLUSTER_SIZE ); + return expContext; } diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.h b/src/gui/symbology-ng/qgssymbolslistwidget.h index 78096c7db144..dd8809364014 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.h +++ b/src/gui/symbology-ng/qgssymbolslistwidget.h @@ -18,6 +18,8 @@ #include "ui_widget_symbolslist.h" +#include "qgssymbolwidgetcontext.h" + #include class QgsSymbol; @@ -38,33 +40,18 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW //! Destructor virtual ~QgsSymbolsListWidget(); - /** Returns the expression context used for the widget, if set. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the list widget. - * @note added in QGIS 2.12 - * @see setExpressionContext() - */ - QgsExpressionContext* expressionContext() const { return mPresetExpressionContext; } - - /** Sets a list of additional expression context scopes to show as available within the symbol. - * @param scopes list of additional scopes which will be added in order to the end of the default expression context + /** Sets the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @param context symbol widget context + * @see context() * @note added in QGIS 3.0 */ - void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); - - /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current - * map scale and other properties from the canvas. - * @param canvas map canvas - * @see mapCanvas() - * @note added in QGIS 2.12 - */ - virtual void setMapCanvas( QgsMapCanvas* canvas ); + void setContext( const QgsSymbolWidgetContext& context ); - /** Returns the map canvas associated with the widget. - * @see setMapCanvas - * @note added in QGIS 2.12 + /** Returns the context in which the symbol widget is shown, eg the associated map canvas and expression contexts. + * @see setContext() + * @note added in QGIS 3.0 */ - const QgsMapCanvas* mapCanvas() const; + QgsSymbolWidgetContext context() const; /** Returns the vector layer associated with the widget. * @note added in QGIS 2.12 @@ -73,16 +60,6 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW public slots: - /** Sets the optional expression context used for the widget. This expression context is used for - * evaluating data defined symbol properties and for populating based expression widgets in - * the properties widget. - * @param context expression context pointer. Ownership is not transferred and the object must - * be kept alive for the lifetime of the properties widget. - * @note added in QGIS 2.12 - * @see expressionContext() - */ - void setExpressionContext( QgsExpressionContext* context ); - void setSymbolFromStyle( const QModelIndex & index ); void setSymbolColor( const QColor& color ); void setMarkerAngle( double angle ); @@ -125,8 +102,7 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW /** Recursive function to create the group tree in the widget */ void populateGroups( const QString& parent = "", const QString& prepend = "" ); - QgsExpressionContext* mPresetExpressionContext; - QList< QgsExpressionContextScope > mAdditionalScopes; + QgsSymbolWidgetContext mContext; QgsExpressionContext createExpressionContext() const override; }; diff --git a/src/gui/symbology-ng/qgssymbolwidgetcontext.cpp b/src/gui/symbology-ng/qgssymbolwidgetcontext.cpp new file mode 100644 index 000000000000..a0419149c064 --- /dev/null +++ b/src/gui/symbology-ng/qgssymbolwidgetcontext.cpp @@ -0,0 +1,77 @@ +/*************************************************************************** + qgssymbolwidgetcontext.cpp + -------------------------- + begin : September 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgssymbolwidgetcontext.h" + +QgsSymbolWidgetContext::QgsSymbolWidgetContext() + : mMapCanvas( nullptr ) +{} + +QgsSymbolWidgetContext::QgsSymbolWidgetContext( const QgsSymbolWidgetContext& other ) + : mMapCanvas( other.mMapCanvas ) + , mAdditionalScopes( other.mAdditionalScopes ) +{ + if ( other.mExpressionContext ) + { + mExpressionContext.reset( new QgsExpressionContext( *other.mExpressionContext ) ); + } +} + +QgsSymbolWidgetContext& QgsSymbolWidgetContext::operator=( const QgsSymbolWidgetContext & other ) +{ + mMapCanvas = other.mMapCanvas; + mAdditionalScopes = other.mAdditionalScopes; + if ( other.mExpressionContext ) + { + mExpressionContext.reset( new QgsExpressionContext( *other.mExpressionContext ) ); + } + else + { + mExpressionContext.reset(); + } + return *this; +} + +void QgsSymbolWidgetContext::setMapCanvas( QgsMapCanvas* canvas ) +{ + mMapCanvas = canvas; +} + +QgsMapCanvas* QgsSymbolWidgetContext::mapCanvas() const +{ + return mMapCanvas; +} + +void QgsSymbolWidgetContext::setExpressionContext( QgsExpressionContext* context ) +{ + if ( context ) + mExpressionContext.reset( new QgsExpressionContext( *context ) ); + else + mExpressionContext.reset(); +} + +QgsExpressionContext* QgsSymbolWidgetContext::expressionContext() const +{ + return mExpressionContext.data(); +} + +void QgsSymbolWidgetContext::setAdditionalExpressionContextScopes( const QList& scopes ) +{ + mAdditionalScopes = scopes; +} + +QList QgsSymbolWidgetContext::additionalExpressionContextScopes() const +{ + return mAdditionalScopes; +} diff --git a/src/gui/symbology-ng/qgssymbolwidgetcontext.h b/src/gui/symbology-ng/qgssymbolwidgetcontext.h new file mode 100644 index 000000000000..a2458c44be6f --- /dev/null +++ b/src/gui/symbology-ng/qgssymbolwidgetcontext.h @@ -0,0 +1,87 @@ +/*************************************************************************** + qgssymbolwidgetcontext.h + ------------------------ + begin : September 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSSYMBOLWIDGETCONTEXT_H +#define QGSSYMBOLWIDGETCONTEXT_H + +#include "qgsexpressioncontext.h" + +class QgsMapCanvas; + + +/** \ingroup gui + * \class QgsSymbolWidgetContext + * Contains settings which reflect the context in which a symbol (or renderer) widget is shown, eg the + * map canvas and relevant expression contexts. + * + * \note added in QGIS 3.0 + */ +class GUI_EXPORT QgsSymbolWidgetContext +{ + public: + + QgsSymbolWidgetContext(); + + QgsSymbolWidgetContext( const QgsSymbolWidgetContext& other ); + + QgsSymbolWidgetContext& operator=( const QgsSymbolWidgetContext& other ); + + /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current + * map scale and other properties from the canvas. + * @param canvas map canvas + * @see mapCanvas() + */ + void setMapCanvas( QgsMapCanvas* canvas ); + + /** Returns the map canvas associated with the widget. + * @see setMapCanvas() + */ + QgsMapCanvas* mapCanvas() const; + + /** Sets the optional expression context used for the widget. This expression context is used for + * evaluating data defined symbol properties and for populating based expression widgets in + * the layer widget. + * @param context expression context pointer. Ownership is not transferred. + * @see expressionContext() + * @see setAdditionalExpressionContextScopes() + */ + void setExpressionContext( QgsExpressionContext* context ); + + /** Returns the expression context used for the widget, if set. This expression context is used for + * evaluating data defined symbol properties and for populating based expression widgets in + * the layer widget. + * @see setExpressionContext() + */ + QgsExpressionContext* expressionContext() const; + + /** Sets a list of additional expression context scopes to show as available within the layer. + * @param scopes list of additional scopes which will be added in order to the end of the default expression context + * @see setExpressionContext() + */ + void setAdditionalExpressionContextScopes( const QList< QgsExpressionContextScope >& scopes ); + + /** Returns the list of additional expression context scopes to show as available within the layer. + * @see setAdditionalExpressionContextScopes() + */ + QList< QgsExpressionContextScope > additionalExpressionContextScopes() const; + + private: + + QgsMapCanvas* mMapCanvas; + QScopedPointer< QgsExpressionContext > mExpressionContext; + QList< QgsExpressionContextScope > mAdditionalScopes; + +}; + +#endif // QGSSYMBOLWIDGETCONTEXT_H From c671bad77346aa8daea827bf4941665ecbe6dfa6 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 19 Sep 2016 13:16:43 +1000 Subject: [PATCH 029/897] Better default cluster symbol --- src/core/symbology-ng/qgspointclusterrenderer.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index beea5de71421..5bd0f11a85d6 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -20,6 +20,8 @@ #include "qgssymbollayerutils.h" #include "qgspainteffectregistry.h" #include "qgspainteffect.h" +#include "qgsmarkersymbollayer.h" +#include "qgsdatadefined.h" #include #ifndef M_SQRT2 @@ -32,6 +34,14 @@ QgsPointClusterRenderer::QgsPointClusterRenderer() mClusterSymbol.reset( new QgsMarkerSymbol() ); mClusterSymbol->setSize( 4 ); mClusterSymbol->setColor( QColor( 245, 75, 80 ) ); + + QgsFontMarkerSymbolLayer* fm = new QgsFontMarkerSymbolLayer(); + fm->setFontFamily( QFont().defaultFamily() ); + fm->setColor( QColor( 255, 255, 255 ) ); + fm->setSize( 3.2 ); + fm->setOffset( QPointF( 0, -0.4 ) ); + fm->setDataDefinedProperty( "char", new QgsDataDefined( true, true, "@cluster_size" ) ); + mClusterSymbol->insertSymbolLayer( 1, fm ); } QgsPointClusterRenderer* QgsPointClusterRenderer::clone() const From 3dcc69a41aaa6bf02e65c289b621987f45f6f418 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 19 Sep 2016 13:38:24 +1000 Subject: [PATCH 030/897] Fix point distance renderer handling of crs transform --- .../symbology-ng/qgspointdistancerenderer.cpp | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index d9106b8f648d..739250edee4e 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -81,19 +81,27 @@ bool QgsPointDistanceRenderer::renderFeature( QgsFeature& feature, QgsRenderCont label = getLabel( feature ); } + QgsCoordinateTransform xform = context.coordinateTransform(); + QgsFeature transformedFeature = feature; + if ( xform.isValid() ) + { + geom.transform( xform ); + transformedFeature.setGeometry( geom ); + } + double searchDistance = mTolerance * QgsSymbolLayerUtils::mapUnitScaleFactor( context, mToleranceUnit, mToleranceMapUnitScale ); - QgsPoint point = feature.geometry().asPoint(); + QgsPoint point = transformedFeature.geometry().asPoint(); QList intersectList = mSpatialIndex->intersects( searchRect( point, searchDistance ) ); if ( intersectList.empty() ) { - mSpatialIndex->insertFeature( feature ); + mSpatialIndex->insertFeature( transformedFeature ); // create new group ClusteredGroup newGroup; - newGroup << GroupedFeature( feature, symbol, selected, label ); + newGroup << GroupedFeature( transformedFeature, symbol, selected, label ); mClusteredGroups.push_back( newGroup ); // add to group index - mGroupIndex.insert( feature.id(), mClusteredGroups.count() - 1 ); - mGroupLocations.insert( feature.id(), point ); + mGroupIndex.insert( transformedFeature.id(), mClusteredGroups.count() - 1 ); + mGroupLocations.insert( transformedFeature.id(), point ); } else { @@ -120,9 +128,9 @@ bool QgsPointDistanceRenderer::renderFeature( QgsFeature& feature, QgsRenderCont ( oldCenter.y() * group.size() + point.y() ) / ( group.size() + 1.0 ) ); // add to a group - group << GroupedFeature( feature, symbol, selected, label ); + group << GroupedFeature( transformedFeature, symbol, selected, label ); // add to group index - mGroupIndex.insert( feature.id(), groupIdx ); + mGroupIndex.insert( transformedFeature.id(), groupIdx ); } return true; @@ -138,7 +146,8 @@ void QgsPointDistanceRenderer::drawGroup( const ClusteredGroup& group, QgsRender } QgsGeometry groupGeom( groupMultiPoint ); QgsGeometry centroid = groupGeom.centroid(); - QPointF pt = _getPoint( context, *static_cast( centroid.geometry() ) ); + QPointF pt = centroid.asQPointF(); + context.mapToPixel().transformInPlace( pt.rx(), pt.ry() ); context.expressionContext().appendScope( createGroupScope( group ) ); drawGroup( pt, context, group ); From ca7b504e5c08b7506c0cb91e156b76e29bf28563 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 29 Sep 2016 08:56:07 +1000 Subject: [PATCH 031/897] Fix Travis warnings and missing docs/sip --- .../symbology-ng/qgspointdistancerenderer.sip | 1 + python/gui/gui.sip | 1 + .../qgspointclusterrendererwidget.sip | 33 +++++++++++++++++++ .../symbology-ng/qgspointdistancerenderer.cpp | 2 ++ .../symbology-ng/qgspointdistancerenderer.h | 1 + .../qgspointclusterrendererwidget.h | 20 +++++++++++ .../symbology-ng/qgsrulebasedrendererwidget.h | 9 +++++ src/gui/symbology-ng/qgssymbolwidgetcontext.h | 3 ++ 8 files changed, 70 insertions(+) create mode 100644 python/gui/symbology-ng/qgspointclusterrendererwidget.sip diff --git a/python/core/symbology-ng/qgspointdistancerenderer.sip b/python/core/symbology-ng/qgspointdistancerenderer.sip index d5913597a962..c2bead6b27be 100644 --- a/python/core/symbology-ng/qgspointdistancerenderer.sip +++ b/python/core/symbology-ng/qgspointdistancerenderer.sip @@ -183,6 +183,7 @@ class QgsPointDistanceRenderer : QgsFeatureRenderer * @param context destination render context * @param labelShifts displacement for individual label positions * @param group group of clustered features to label + * @note may not be available in Python bindings on some platforms */ void drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const QgsPointDistanceRenderer::ClusteredGroup& group ); diff --git a/python/gui/gui.sip b/python/gui/gui.sip index 722351716aec..ca8e6a4575f3 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -234,6 +234,7 @@ %Include symbology-ng/qgslayerpropertieswidget.sip %Include symbology-ng/qgsnullsymbolrendererwidget.sip %Include symbology-ng/qgspenstylecombobox.sip +%Include symbology-ng/qgspointclusterrendererwidget.sip %Include symbology-ng/qgspointdisplacementrendererwidget.sip %Include symbology-ng/qgsrendererpropertiesdialog.sip %Include symbology-ng/qgsrendererwidget.sip diff --git a/python/gui/symbology-ng/qgspointclusterrendererwidget.sip b/python/gui/symbology-ng/qgspointclusterrendererwidget.sip new file mode 100644 index 000000000000..44ddcedb6012 --- /dev/null +++ b/python/gui/symbology-ng/qgspointclusterrendererwidget.sip @@ -0,0 +1,33 @@ +/** \class QgsPointClusterRendererWidget + * \ingroup gui + * A widget which allows configuration of the properties for a QgsPointClusterRenderer. + * \note added in QGIS 3.0 + */ + +class QgsPointClusterRendererWidget: QgsRendererWidget +{ +%TypeHeaderCode +#include +%End + public: + + /** Returns a new QgsPointClusterRendererWidget. + * @param layer associated vector layer + * @param style style collection + * @param renderer source QgsPointClusterRenderer renderer + * @returns new QgsRendererWidget + */ + static QgsRendererWidget* create( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ) /Factory/; + + /** Constructor for QgsPointClusterRendererWidget. + * @param layer associated vector layer + * @param style style collection + * @param renderer source QgsPointClusterRenderer renderer + */ + QgsPointClusterRendererWidget( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); + + ~QgsPointClusterRendererWidget(); + + QgsFeatureRenderer* renderer(); + void setContext( const QgsSymbolWidgetContext& context ); +}; diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index 739250edee4e..fd247444d76c 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -350,6 +350,7 @@ QgsRectangle QgsPointDistanceRenderer::searchRect( const QgsPoint& p, double dis void QgsPointDistanceRenderer::printGroupInfo() const { +#ifdef QGISDEBUG int nGroups = mClusteredGroups.size(); QgsDebugMsg( "number of displacement groups:" + QString::number( nGroups ) ); for ( int i = 0; i < nGroups; ++i ) @@ -360,6 +361,7 @@ void QgsPointDistanceRenderer::printGroupInfo() const QgsDebugMsg( FID_TO_STRING( feature.feature.id() ) ); } } +#endif } QString QgsPointDistanceRenderer::getLabel( const QgsFeature& feature ) const diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index 81eb7b773c3f..0dc136274688 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -246,6 +246,7 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer * @param context destination render context * @param labelShifts displacement for individual label positions * @param group group of clustered features to label + * @note may not be available in Python bindings on some platforms */ void drawLabels( QPointF centerPoint, QgsSymbolRenderContext& context, const QList& labelShifts, const ClusteredGroup& group ); diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.h b/src/gui/symbology-ng/qgspointclusterrendererwidget.h index 983e8e1099aa..aab4aabfc491 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.h +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.h @@ -23,12 +23,32 @@ class QgsPointClusterRenderer; +/** \class QgsPointClusterRendererWidget + * \ingroup gui + * A widget which allows configuration of the properties for a QgsPointClusterRenderer. + * \note added in QGIS 3.0 + */ + class GUI_EXPORT QgsPointClusterRendererWidget: public QgsRendererWidget, private Ui::QgsPointClusterRendererWidgetBase { Q_OBJECT public: + + /** Returns a new QgsPointClusterRendererWidget. + * @param layer associated vector layer + * @param style style collection + * @param renderer source QgsPointClusterRenderer renderer + * @returns new QgsRendererWidget + */ static QgsRendererWidget* create( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); + + /** Constructor for QgsPointClusterRendererWidget. + * @param layer associated vector layer + * @param style style collection + * @param renderer source QgsPointClusterRenderer renderer + */ QgsPointClusterRendererWidget( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); + ~QgsPointClusterRendererWidget(); QgsFeatureRenderer* renderer() override; diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.h b/src/gui/symbology-ng/qgsrulebasedrendererwidget.h index acbd9587cfa5..9ec7b6447246 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.h +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.h @@ -240,7 +240,16 @@ class GUI_EXPORT QgsRendererRulePropsDialog : public QDialog Q_OBJECT public: + + /** Constructor for QgsRendererRulePropsDialog + * @param rule associated rule based renderer rule + * @param layer source vector layer + * @param style style collection + * @param parent parent widget + * @param context symbol widget context + */ QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Rule* rule, QgsVectorLayer* layer, QgsStyle* style, QWidget* parent = nullptr, const QgsSymbolWidgetContext& context = QgsSymbolWidgetContext() ); + ~QgsRendererRulePropsDialog(); QgsRuleBasedRenderer::Rule* rule() { return mPropsWidget->rule(); } diff --git a/src/gui/symbology-ng/qgssymbolwidgetcontext.h b/src/gui/symbology-ng/qgssymbolwidgetcontext.h index a2458c44be6f..57f9afc656f3 100644 --- a/src/gui/symbology-ng/qgssymbolwidgetcontext.h +++ b/src/gui/symbology-ng/qgssymbolwidgetcontext.h @@ -33,6 +33,9 @@ class GUI_EXPORT QgsSymbolWidgetContext QgsSymbolWidgetContext(); + /** Copy constructor. + * @param other source QgsSymbolWidgetContext + */ QgsSymbolWidgetContext( const QgsSymbolWidgetContext& other ); QgsSymbolWidgetContext& operator=( const QgsSymbolWidgetContext& other ); From 168688c88920ecba31c1c98899de068590e145e7 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 30 Sep 2016 14:32:19 +1000 Subject: [PATCH 032/897] Don't draw empty labels for displacement renderer Is inefficient and also causes QThreadPool crash on exit in python test (related to creation of QFontMetrics in a thread?) --- src/core/symbology-ng/qgspointdisplacementrenderer.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index 66ff374a871e..74b7676341b0 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -106,7 +106,10 @@ void QgsPointDisplacementRenderer::drawGroup( QPointF centerPoint, QgsRenderCont //draw symbols on the circle drawSymbols( group, context, symbolPositions ); //and also the labels - drawLabels( centerPoint, symbolContext, labelPositions, group ); + if ( mLabelIndex >= 0 ) + { + drawLabels( centerPoint, symbolContext, labelPositions, group ); + } } From 38a811b377cf7d0d50e2c76346eadfdd8ef87956 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 30 Sep 2016 15:54:31 +1000 Subject: [PATCH 033/897] [composer] Fix save world file does not work (fix #15268) --- src/gui/qgscomposeritemcombobox.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/qgscomposeritemcombobox.cpp b/src/gui/qgscomposeritemcombobox.cpp index f74dc54ae27c..b7c4acb5837c 100644 --- a/src/gui/qgscomposeritemcombobox.cpp +++ b/src/gui/qgscomposeritemcombobox.cpp @@ -23,7 +23,7 @@ QgsComposerItemComboBox::QgsComposerItemComboBox( QWidget *parent, QgsCompositio setComposition( composition ); setModelColumn( QgsComposerModel::ItemId ); - connect( this, SIGNAL( activated( int ) ), this, SLOT( indexChanged( int ) ) ); + connect( this, SIGNAL( currentIndexChanged( int ) ), this, SLOT( indexChanged( int ) ) ); connect( mProxyModel, SIGNAL( rowsInserted( QModelIndex, int, int ) ), this, SLOT( rowsChanged() ) ); connect( mProxyModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( rowsChanged() ) ); } From a251b913f5f83d9ba2ca641860c64e4bbc81e363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 30 Sep 2016 08:23:57 +0200 Subject: [PATCH 034/897] [TEST] resurrect SplitLinesWithLines.py to pass test --- .../algs/qgis/SplitLinesWithLines.py | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 python/plugins/processing/algs/qgis/SplitLinesWithLines.py diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py new file mode 100644 index 000000000000..27732c2c20cb --- /dev/null +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + DEPRECATED, replaced by SplitWithLines.py + --------------------- + Date : November 2014 + Revised : February 2016 + Copyright : (C) 2014 by Bernhard Ströbl + Email : bernhard dot stroebl at jena dot de +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Bernhard Ströbl' +__date__ = 'November 2014' +__copyright__ = '(C) 2014, Bernhard Ströbl' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.outputs import OutputVector +from processing.core.ProcessingLog import ProcessingLog +from processing.tools import dataobjects +from processing.tools import vector + + +class SplitLinesWithLines(GeoAlgorithm): + + INPUT_A = 'INPUT_A' + INPUT_B = 'INPUT_B' + + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Split lines with lines') + self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') + self.addParameter(ParameterVector(self.INPUT_A, + self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE])) + self.addParameter(ParameterVector(self.INPUT_B, + self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) + + self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'), datatype=[dataobjects.TYPE_VECTOR_LINE])) + + def processAlgorithm(self, progress): + layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) + layerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B)) + + sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B) + fieldList = layerA.fields() + + writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, + QgsWkbTypes.LineString, layerA.crs()) + + spatialIndex = vector.spatialindex(layerB) + + outFeat = QgsFeature() + features = vector.features(layerA) + total = 100.0 / float(len(features)) + + for current, inFeatA in enumerate(features): + inGeom = inFeatA.geometry() + attrsA = inFeatA.attributes() + outFeat.setAttributes(attrsA) + inLines = [inGeom] + lines = spatialIndex.intersects(inGeom.boundingBox()) + + if len(lines) > 0: # hasIntersections + splittingLines = [] + + for i in lines: + request = QgsFeatureRequest().setFilterFid(i) + inFeatB = next(layerB.getFeatures(request)) + # check if trying to self-intersect + if sameLayer: + if inFeatA.id() == inFeatB.id(): + continue + + splitGeom = inFeatB.geometry() + + if inGeom.intersects(splitGeom): + splittingLines.append(splitGeom) + + if len(splittingLines) > 0: + for splitGeom in splittingLines: + splitterPList = vector.extractPoints(splitGeom) + outLines = [] + + while len(inLines) > 0: + inGeom = inLines.pop() + inPoints = vector.extractPoints(inGeom) + + if inGeom.intersects(splitGeom): + try: + result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) + except: + ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, + self.tr('Geometry exception while splitting')) + result = 1 + + # splitGeometry: If there are several intersections + # between geometry and splitLine, only the first one is considered. + if result == 0: # split occurred + + if inPoints == vector.extractPoints(inGeom): + # bug in splitGeometry: sometimes it returns 0 but + # the geometry is unchanged + outLines.append(inGeom) + else: + inLines.append(inGeom) + + for aNewGeom in newGeometries: + inLines.append(aNewGeom) + else: + outLines.append(inGeom) + else: + outLines.append(inGeom) + + inLines = outLines + + for aLine in inLines: + if len(aLine.asPolyline()) > 2 or \ + (len(aLine.asPolyline()) == 2 and + aLine.asPolyline()[0] != aLine.asPolyline()[1]): + # sometimes splitting results in lines of zero length + outFeat.setGeometry(aLine) + writer.addFeature(outFeat) + + progress.setPercentage(int(current * total)) + + del writer From 87039204b0b8eb6e2091af87d5b371769fb82d87 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 30 Sep 2016 14:09:09 +0700 Subject: [PATCH 035/897] [expression] make wordwrap work with complex scripts (Indic, Arabic, etc) --- src/core/qgsexpression.cpp | 29 ++++++++++++++++++++-------- tests/src/core/testqgsexpression.cpp | 11 ++++++----- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index ef6828aa7030..8c283a485bf5 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1125,10 +1125,23 @@ static QVariant fcnWordwrap( const QVariantList& values, const QgsExpressionCont if ( !str.isEmpty() && wrap != 0 ) { QString newstr; - QString delimiterstr; - if ( values.length() == 3 ) delimiterstr = getStringValue( values.at( 2 ), parent ); - if ( delimiterstr.isEmpty() ) delimiterstr = ' '; - int delimiterlength = delimiterstr.length(); + QRegExp rx; + QString customdelimiter = getStringValue( values.at( 2 ), parent ); + int delimiterlength; + + if ( customdelimiter.length() > 0 ) + { + rx.setPatternSyntax( QRegExp::FixedString ); + rx.setPattern( customdelimiter ); + delimiterlength = customdelimiter.length(); + } + else + { + // \x200B is a ZERO-WIDTH SPACE, needed for worwrap to support a number of complex scripts (Indic, Arabic, etc.) + rx.setPattern( "[\\s\\x200B]" ); + delimiterlength = 1; + } + QStringList lines = str.split( '\n' ); int strlength, strcurrent, strhit, lasthit; @@ -1147,17 +1160,17 @@ static QVariant fcnWordwrap( const QVariantList& values, const QgsExpressionCont if ( wrap > 0 ) { //first try to locate delimiter backwards - strhit = lines[i].lastIndexOf( delimiterstr, strcurrent + wrap ); + strhit = lines[i].lastIndexOf( rx, strcurrent + wrap ); if ( strhit == lasthit || strhit == -1 ) { //if no new backward delimiter found, try to locate forward - strhit = lines[i].indexOf( delimiterstr, strcurrent + qAbs( wrap ) ); + strhit = lines[i].indexOf( rx, strcurrent + qAbs( wrap ) ); } lasthit = strhit; } else { - strhit = lines[i].indexOf( delimiterstr, strcurrent + qAbs( wrap ) ); + strhit = lines[i].indexOf( rx, strcurrent + qAbs( wrap ) ); } if ( strhit > -1 ) { @@ -3469,7 +3482,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( "hamming_distance", 2, fcnHamming, "Fuzzy Matching" ) << new StaticFunction( "soundex", 1, fcnSoundex, "Fuzzy Matching" ) << new StaticFunction( "char", 1, fcnChar, "String" ) - << new StaticFunction( "wordwrap", ParameterList() << Parameter( "text" ) << Parameter( "length" ) << Parameter( "delimiter", true, " " ), fcnWordwrap, "String" ) + << new StaticFunction( "wordwrap", ParameterList() << Parameter( "text" ) << Parameter( "length" ) << Parameter( "delimiter", true, "" ), fcnWordwrap, "String" ) << new StaticFunction( "length", 1, fcnLength, "String" ) << new StaticFunction( "replace", 3, fcnReplace, "String" ) << new StaticFunction( "regexp_replace", 3, fcnRegexpReplace, "String" ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 692cfe86b4da..11b7f41a6c94 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -329,7 +329,7 @@ class TestQgsExpression: public QObject QTest::newRow( "named params non optional omitted" ) << "clamp( min:=1, max:=2)" << true << "" << QVariant(); QTest::newRow( "optional parameters specified" ) << "wordwrap( 'testxstring', 5, 'x')" << false << "wordwrap('testxstring', 5, 'x')" << QVariant( "test\nstring" ); QTest::newRow( "optional parameters specified named" ) << "wordwrap( text:='testxstring', length:=5, delimiter:='x')" << false << "wordwrap('testxstring', 5, 'x')" << QVariant( "test\nstring" ); - QTest::newRow( "optional parameters unspecified" ) << "wordwrap( text:='test string', length:=5 )" << false << "wordwrap('test string', 5, ' ')" << QVariant( "test\nstring" ); + QTest::newRow( "optional parameters unspecified" ) << "wordwrap( text:='test string', length:=5 )" << false << "wordwrap('test string', 5, '')" << QVariant( "test\nstring" ); QTest::newRow( "named params dupe explicit 3" ) << "wordwrap( 'test string', 5, length:=6 )" << true << "" << QVariant(); QTest::newRow( "named params dupe explicit 4" ) << "wordwrap( text:='test string', length:=5, length:=6 )" << true << "" << QVariant(); } @@ -837,10 +837,11 @@ class TestQgsExpression: public QObject QTest::newRow( "trim empty string" ) << "trim('')" << false << QVariant( "" ); QTest::newRow( "char" ) << "char(81)" << false << QVariant( "Q" ); QTest::newRow( "wordwrap" ) << "wordwrap('university of qgis',13)" << false << QVariant( "university of\nqgis" ); - QTest::newRow( "wordwrap" ) << "wordwrap('university of qgis',13,' ')" << false << QVariant( "university of\nqgis" ); - QTest::newRow( "wordwrap" ) << "wordwrap('university of qgis',-3)" << false << QVariant( "university\nof qgis" ); - QTest::newRow( "wordwrap" ) << "wordwrap('university of qgis',-3,' ')" << false << QVariant( "university\nof qgis" ); - QTest::newRow( "wordwrap" ) << "wordwrap('university of qgis\nsupports many multiline',-5,' ')" << false << QVariant( "university\nof qgis\nsupports\nmany multiline" ); + QTest::newRow( "wordwrap with custom delimiter" ) << "wordwrap('university of qgis',13,' ')" << false << QVariant( "university of\nqgis" ); + QTest::newRow( "wordwrap with negative length" ) << "wordwrap('university of qgis',-3)" << false << QVariant( "university\nof qgis" ); + QTest::newRow( "wordwrap with negative length, custom delimiter" ) << "wordwrap('university of qgis',-3,' ')" << false << QVariant( "university\nof qgis" ); + QTest::newRow( "wordwrap on multi line" ) << "wordwrap('university of qgis\nsupports many multiline',-5,' ')" << false << QVariant( "university\nof qgis\nsupports\nmany multiline" ); + QTest::newRow( "wordwrap on zero-space width" ) << "wordwrap('test\u200Bzero-width space',4)" << false << QVariant( "test\nzero-width\nspace" ); QTest::newRow( "format" ) << "format('%1 %2 %3 %1', 'One', 'Two', 'Three')" << false << QVariant( "One Two Three One" ); QTest::newRow( "concat" ) << "concat('a', 'b', 'c', 'd')" << false << QVariant( "abcd" ); QTest::newRow( "concat function single" ) << "concat('a')" << false << QVariant( "a" ); From f47a7320d1c42c4c4c8611f0167a6b8bc0992742 Mon Sep 17 00:00:00 2001 From: rldhont Date: Wed, 28 Sep 2016 10:08:47 +0200 Subject: [PATCH 036/897] [BUGFIX] Expression in like escape % and _ The Expression LIKE binary operator does not care about escape % and _ char. No-one has already open an issue about it but in the OGC element PropertyIsLike the user can defined is own wild and single char. This mean that QGIS has to escape % and _ if they are not used as wild and single char. --- resources/function_help/json/ILIKE | 24 +++++++++++++--------- resources/function_help/json/LIKE | 19 +++++++++++------- src/core/qgsexpression.cpp | 30 +++++++++++++++++++++++++--- tests/src/core/testqgsexpression.cpp | 8 ++++++-- 4 files changed, 60 insertions(+), 21 deletions(-) diff --git a/resources/function_help/json/ILIKE b/resources/function_help/json/ILIKE index 26968df4ef70..a17e8bf642db 100644 --- a/resources/function_help/json/ILIKE +++ b/resources/function_help/json/ILIKE @@ -3,16 +3,22 @@ "type": "operator", "description": "Returns 1 if the first parameter matches case-insensitive the supplied pattern. LIKE can be used instead of ILIKE to make the match case-sensitive. Works with numbers also.", "arguments": [ - {"arg":"string/number","description":"string to search"}, - {"arg":"pattern","description":"pattern to find"} + {"arg":"string/number","description":"string to search"}, + {"arg":"pattern","description":"pattern to find, you can use '%' as a wildcard, '_' as a single char and '\\\\' to escape."} ], "examples": [ - { "expression":"'A' ILIKE 'A'", "returns":"1"}, - { "expression":"'A' ILIKE 'a'", "returns":"1"}, - { "expression":"'A' ILIKE 'B'", "returns":"0"}, - { "expression":"'ABC' ILIKE 'b'", "returns":"0"}, - { "expression":"'ABC' ILIKE 'B'", "returns":"0"}, - { "expression":"'ABC' ILIKE '%b%'", "returns":"1"}, - { "expression":"'ABC' ILIKE '%B%'", "returns":"1"} + { "expression":"'A' ILIKE 'A'", "returns":"1"}, + { "expression":"'A' ILIKE 'a'", "returns":"1"}, + { "expression":"'A' ILIKE 'B'", "returns":"0"}, + { "expression":"'ABC' ILIKE 'b'", "returns":"0"}, + { "expression":"'ABC' ILIKE 'B'", "returns":"0"}, + { "expression":"'ABC' ILIKE '_b_'", "returns":"1"}, + { "expression":"'ABC' ILIKE '_B_'", "returns":"1"}, + { "expression":"'ABCD' ILIKE '_b_'", "returns":"0"}, + { "expression":"'ABCD' ILIKE '_B_'", "returns":"0"}, + { "expression":"'ABCD' ILIKE '_b%'", "returns":"1"}, + { "expression":"'ABCD' ILIKE '_B%'", "returns":"1"}, + { "expression":"'ABCD' ILIKE '%b%'", "returns":"1"}, + { "expression":"'ABCD' ILIKE '%B%'", "returns":"1"} ] } diff --git a/resources/function_help/json/LIKE b/resources/function_help/json/LIKE index 2dba3f8ed8ce..2ff339b96a37 100644 --- a/resources/function_help/json/LIKE +++ b/resources/function_help/json/LIKE @@ -3,14 +3,19 @@ "type": "operator", "description": "Returns 1 if the first parameter matches the supplied pattern. Works with numbers also.", "arguments": [ - {"arg":"string/number","description":"value"}, - {"arg":"pattern","description":"pattern to compare value with"} + {"arg":"string/number","description":"value"}, + {"arg":"pattern","description":"pattern to compare value with, you can use '%' as a wildcard, '_' as a single char and '\\\\' to escape."} ], "examples": [ - { "expression":"'A' LIKE 'A'", "returns":"1"}, - { "expression":"'A' LIKE 'a'", "returns":"0"}, - { "expression":"'A' LIKE 'B'", "returns":"0"}, - { "expression":"'ABC' LIKE 'B'", "returns":"0"}, - { "expression":"'ABC' LIKE '%B%'", "returns":"1"} + { "expression":"'A' LIKE 'A'", "returns":"1"}, + { "expression":"'A' LIKE 'a'", "returns":"0"}, + { "expression":"'A' LIKE 'B'", "returns":"0"}, + { "expression":"'ABC' LIKE 'B'", "returns":"0"}, + { "expression":"'ABC' LIKE '_B_'", "returns":"1"}, + { "expression":"'ABCD' LIKE '_B_'", "returns":"0"}, + { "expression":"'ABCD' LIKE '_B%'", "returns":"1"}, + { "expression":"'ABCD' LIKE '%B%'", "returns":"1"}, + { "expression":"'1%' LIKE '1\\\\%'", "returns":"1"}, + { "expression":"'1_' LIKE '1\\\\%'", "returns":"0"} ] } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index ef6828aa7030..0fec026ea038 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -4318,9 +4318,33 @@ QVariant QgsExpression::NodeBinaryOperator::eval( QgsExpression *parent, const Q if ( mOp == boLike || mOp == boILike || mOp == boNotLike || mOp == boNotILike ) // change from LIKE syntax to regexp { QString esc_regexp = QRegExp::escape( regexp ); - // XXX escape % and _ ??? - esc_regexp.replace( '%', ".*" ); - esc_regexp.replace( '_', '.' ); + // manage escape % and _ + if ( esc_regexp.startsWith( '%' ) ) + { + esc_regexp.replace( 0, 1, ".*" ); + } + QRegExp rx( "[^\\\\](%)" ); + int pos = 0; + while (( pos = rx.indexIn( esc_regexp, pos ) ) != -1 ) + { + esc_regexp.replace( pos + 1, 1, ".*" ); + pos += 1; + } + rx.setPattern( "\\\\%" ); + esc_regexp.replace( rx, "%" ); + if ( esc_regexp.startsWith( '_' ) ) + { + esc_regexp.replace( 0, 1, "." ); + } + rx.setPattern( "[^\\\\](_)" ); + pos = 0; + while (( pos = rx.indexIn( esc_regexp, pos ) ) != -1 ) + { + esc_regexp.replace( pos + 1, 1, '.' ); + pos += 1; + } + rx.setPattern( "\\\\_" ); + esc_regexp.replace( rx, "_" ); matches = QRegExp( esc_regexp, mOp == boLike || mOp == boNotLike ? Qt::CaseSensitive : Qt::CaseInsensitive ).exactMatch( str ); } else diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 692cfe86b4da..ad2524a309da 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -490,9 +490,13 @@ class TestQgsExpression: public QObject // regexp, like QTest::newRow( "like 1" ) << "'hello' like '%ll_'" << false << QVariant( 1 ); - QTest::newRow( "like 2" ) << "'hello' like 'lo'" << false << QVariant( 0 ); - QTest::newRow( "like 3" ) << "'hello' like '%LO'" << false << QVariant( 0 ); + QTest::newRow( "like 2" ) << "'hello' like '_el%'" << false << QVariant( 1 ); + QTest::newRow( "like 3" ) << "'hello' like 'lo'" << false << QVariant( 0 ); + QTest::newRow( "like 4" ) << "'hello' like '%LO'" << false << QVariant( 0 ); QTest::newRow( "ilike" ) << "'hello' ilike '%LO'" << false << QVariant( 1 ); + // the \\\\ is like \\ in the interface + QTest::newRow( "like escape 1" ) << "'1%' like '1\\\\%'" << false << QVariant( 1 ); + QTest::newRow( "like escape 2" ) << "'1_' like '1\\\\%'" << false << QVariant( 0 ); QTest::newRow( "regexp 1" ) << "'hello' ~ 'll'" << false << QVariant( 1 ); QTest::newRow( "regexp 2" ) << "'hello' ~ '^ll'" << false << QVariant( 0 ); QTest::newRow( "regexp 3" ) << "'hello' ~ 'llo$'" << false << QVariant( 1 ); From 19378c22802668f592f0ffc268451c5a946371af Mon Sep 17 00:00:00 2001 From: julienmalik Date: Fri, 30 Sep 2016 14:40:02 +0200 Subject: [PATCH 037/897] CDash submissions should be done with https now --- CTestConfig.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CTestConfig.cmake b/CTestConfig.cmake index c592023da5f6..63d849a6550a 100644 --- a/CTestConfig.cmake +++ b/CTestConfig.cmake @@ -7,7 +7,7 @@ set(CTEST_PROJECT_NAME "QGIS") set(CTEST_NIGHTLY_START_TIME "20:00:00 CEST") -set(CTEST_DROP_METHOD "http") +set(CTEST_DROP_METHOD "https") set(CTEST_DROP_SITE "dash.orfeo-toolbox.org") set(CTEST_DROP_LOCATION "/submit.php?project=QGIS") set(CTEST_DROP_SITE_CDASH TRUE) From f85b5fc91e7f3b2d9a7fc4f16020356c127f2429 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Fri, 30 Sep 2016 16:14:45 +0200 Subject: [PATCH 038/897] debian packaging: add ca-certificates as build dependency for dash upload (followup 19378c2) --- debian/control.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debian/control.in b/debian/control.in index bf052718670b..ac0580e3e2bc 100644 --- a/debian/control.in +++ b/debian/control.in @@ -49,7 +49,7 @@ Build-Depends: pyqt5.qsci-dev, python3-nose2, python3-gdal, python3-yaml, python3-mock, python3-psycopg2, python3-future, python3-termcolor, #oracle# oracle-instantclient12.1-devel, - locales + locales, ca-certificates Build-Conflicts: libqgis-dev, qgis-dev #sid stretch xenial#Standards-Version: 3.9.7 #jessie#Standards-Version: 3.9.6 From 52fc535c77fbbea9adcafc16631c6f8440d17606 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 00:54:53 +0200 Subject: [PATCH 039/897] update INSTALL --- INSTALL | 17 ++++++----------- debian/rules | 2 +- doc/INSTALL.html | 32 ++++++-------------------------- doc/linux.t2t | 11 +++-------- 4 files changed, 16 insertions(+), 46 deletions(-) diff --git a/INSTALL b/INSTALL index 735f3a044212..d9627fdd3d20 100644 --- a/INSTALL +++ b/INSTALL @@ -1,10 +1,10 @@ QGIS Building QGIS from source - step by step -Wednesday September 21, 2016 +Saturday October 01, 2016 -Last Updated: Wednesday September 21, 2016 -Last Change : Wednesday July 27, 2016 +Last Updated: Saturday October 01, 2016 +Last Change : Saturday October 01, 2016 1. Introduction @@ -181,14 +181,9 @@ Now update your local sources database: =============================== || Distribution | install command for packages | - | wheezy | ``apt-get install bison cmake doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal1-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python python-dev python-gdal python-mock python-nose2 python-psycopg2 python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | jessie | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | stretch | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | precise | ``apt-get install bison cmake doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python python-gdal python-mock python-psycopg2 python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | trusty | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python-all python-all-dev python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | wily | ``apt-get install bison cmake cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | xenial | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | sid | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | sid | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | (extracted from the control.in file in debian/) diff --git a/debian/rules b/debian/rules index 88f229a85183..b92a1de53290 100755 --- a/debian/rules +++ b/debian/rules @@ -41,7 +41,7 @@ endif QT_PLUGINS_DIR = usr/lib/$(DEB_BUILD_MULTIARCH)/qt5/plugins -ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"jessie stretch trusty xenial")) +ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"stretch xenial")) DISTRIBUTION := sid endif diff --git a/doc/INSTALL.html b/doc/INSTALL.html index 46d326d50cb4..d7d1d663dd62 100644 --- a/doc/INSTALL.html +++ b/doc/INSTALL.html @@ -77,13 +77,13 @@

      -Last Updated: Wednesday September 21, 2016 -Last Change : Wednesday July 27, 2016 +Last Updated: Saturday October 01, 2016 +Last Change : Saturday October 01, 2016

      @@ -312,36 +312,16 @@

      3.3. Install build dependencies

      install command for packages -wheezy -apt-get install bison cmake doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal1-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python python-dev python-gdal python-mock python-nose2 python-psycopg2 python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui - - -jessie -apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui - - stretch -apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui - - -precise -apt-get install bison cmake doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python python-gdal python-mock python-psycopg2 python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui - - -trusty -apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python-all python-all-dev python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui - - -wily -apt-get install bison cmake cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui xenial -apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui sid -apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui diff --git a/doc/linux.t2t b/doc/linux.t2t index 182d2600c6a8..cc6751dbb1bf 100644 --- a/doc/linux.t2t +++ b/doc/linux.t2t @@ -44,14 +44,9 @@ sudo apt-get update == Install build dependencies == || Distribution | install command for packages | -| wheezy | ``apt-get install bison cmake doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal1-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python python-dev python-gdal python-mock python-nose2 python-psycopg2 python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| jessie | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| stretch | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| precise | ``apt-get install bison cmake doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python python-gdal python-mock python-psycopg2 python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| trusty | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools python-all python-all-dev python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| wily | ``apt-get install bison cmake cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqtwebkit-dev libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| xenial | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| sid | ``apt-get install bison cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libopenscenegraph-dev libosgearth-dev libpq-dev libproj-dev libqca2-dev libqca2-plugin-ossl libqjson-dev libqscintilla2-dev libqt4-dev libqt4-opengl-dev libqt4-sql-sqlite libqwt5-qt4-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt4-dev-tools pyqt4.qsci-dev python-all python-all-dev python-future python-gdal python-mock python-nose2 python-psycopg2 python-pyspatialite python-qscintilla2 python-qt4 python-qt4-dev python-qt4-sql python-sip python-sip-dev python-yaml qt4-dev-tools qt4-doc-html spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| sid | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | (extracted from the control.in file in ``debian/``) From a07a57e608669258c1ecd03bd85d48c43cb067e8 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 1 Oct 2016 14:29:43 +1000 Subject: [PATCH 040/897] Add new script to handle multiple render results from a dash results page in an interactive way Allows generation and tweaking of mask images while previewing the result --- scripts/parse_dash_results.py | 357 ++++++++++++++++++++++++++++++++++ 1 file changed, 357 insertions(+) create mode 100755 scripts/parse_dash_results.py diff --git a/scripts/parse_dash_results.py b/scripts/parse_dash_results.py new file mode 100755 index 000000000000..ec907dbc266f --- /dev/null +++ b/scripts/parse_dash_results.py @@ -0,0 +1,357 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +****************************3*********************************************** + parse_dash_results.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Nyall Dawson' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import os +import sys +import argparse +import urllib +import re +from bs4 import BeautifulSoup +from PyQt5.QtGui import ( + QImage, QColor, qRed, qBlue, qGreen, qAlpha, qRgb, QPixmap) +from PyQt5.QtWidgets import (QDialog, + QApplication, + QLabel, + QVBoxLayout, + QHBoxLayout, + QGridLayout, + QPushButton, + QDoubleSpinBox, + QMessageBox) +import struct +import glob + +dash_url = 'http://dash.orfeo-toolbox.org' + + +def error(msg): + print(msg) + sys.exit(1) + + +def colorDiff(c1, c2): + redDiff = abs(qRed(c1) - qRed(c2)) + greenDiff = abs(qGreen(c1) - qGreen(c2)) + blueDiff = abs(qBlue(c1) - qBlue(c2)) + alphaDiff = abs(qAlpha(c1) - qAlpha(c2)) + return max(redDiff, greenDiff, blueDiff, alphaDiff) + + +def imageFromPath(path): + if (path[:7] == 'http://' or path[:7] == 'file://'): + # fetch remote image + data = urllib.request.urlopen(path).read() + image = QImage() + image.loadFromData(data) + else: + image = QImage(path) + return image + + +class ResultHandler(QDialog): + + def __init__(self, parent=None): + super(ResultHandler, self).__init__() + self.setWindowTitle('Dash results') + self.control_label = QLabel() + self.rendered_label = QLabel() + self.diff_label = QLabel() + + self.mask_label = QLabel() + self.new_mask_label = QLabel() + + grid = QGridLayout() + self.test_name_label = QLabel() + grid.addWidget(self.test_name_label, 0, 0) + grid.addWidget(QLabel('Control'), 1, 0) + grid.addWidget(QLabel('Rendered'), 1, 1) + grid.addWidget(QLabel('Difference'), 1, 2) + grid.addWidget(self.control_label, 2, 0) + grid.addWidget(self.rendered_label, 2, 1) + grid.addWidget(self.diff_label, 2, 2) + grid.addWidget(QLabel('Current Mask'), 3, 0) + grid.addWidget(QLabel('New Mask'), 3, 1) + grid.addWidget(self.mask_label, 4, 0) + grid.addWidget(self.new_mask_label, 4, 1) + + v_layout = QVBoxLayout() + v_layout.addLayout(grid, 1) + + next_image_button = QPushButton() + next_image_button.setText('Skip') + next_image_button.pressed.connect(self.load_next) + + self.overload_spin = QDoubleSpinBox() + self.overload_spin.setMinimum(1) + self.overload_spin.setMaximum(255) + self.overload_spin.setValue(1) + + preview_mask_button = QPushButton() + preview_mask_button.setText('Preview New Mask') + preview_mask_button.pressed.connect(self.preview_mask) + + save_mask_button = QPushButton() + save_mask_button.setText('Save New Mask') + save_mask_button.pressed.connect(self.save_mask) + + button_layout = QHBoxLayout() + button_layout.addWidget(next_image_button) + button_layout.addWidget(QLabel('Mask diff multiplier:')) + button_layout.addWidget(self.overload_spin) + button_layout.addWidget(preview_mask_button) + button_layout.addWidget(save_mask_button) + button_layout.addStretch() + v_layout.addLayout(button_layout) + self.setLayout(v_layout) + + def closeEvent(self, event): + self.reject() + + def parse_url(self, url): + print('Fetching dash results from: {}'.format(url)) + page = urllib.request.urlopen(url) + soup = BeautifulSoup(page, "lxml") + + # build up list of rendered images + measurement_img = [img for img in soup.find_all('img') if + img.get('alt') and img.get('alt').startswith('Rendered Image')] + + images = {} + for img in measurement_img: + m = re.search('Rendered Image (.*?)\s', img.get('alt')) + test_name = m.group(1) + rendered_image = img.get('src') + images[test_name] = '{}/{}'.format(dash_url, rendered_image) + + print('found images:\n{}'.format(images)) + self.images = images + self.load_next() + + def load_next(self): + if not self.images: + # all done + self.accept() + + test_name, rendered_image = self.images.popitem() + self.test_name_label.setText(test_name) + control_image = self.get_control_image_path(test_name) + if not control_image: + self.load_next() + return + + self.mask_image_path = control_image[:-4] + '_mask.png' + self.load_images(control_image, rendered_image, self.mask_image_path) + + def load_images(self, control_image_path, rendered_image_path, mask_image_path): + self.control_image = imageFromPath(control_image_path) + if not self.control_image: + error('Could not read control image {}'.format(control_image_path)) + + self.rendered_image = imageFromPath(rendered_image_path) + if not self.rendered_image: + error( + 'Could not read rendered image {}'.format(rendered_image_path)) + if not self.rendered_image.width() == self.control_image.width() or not self.rendered_image.height() == self.control_image.height(): + print( + 'Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(self.control_image.width(), + self.control_image.height( + ), + self.rendered_image.width( + ), + self.rendered_image.height())) + + max_width = min( + self.rendered_image.width(), self.control_image.width()) + max_height = min( + self.rendered_image.height(), self.control_image.height()) + + # read current mask, if it exist + self.mask_image = imageFromPath(mask_image_path) + if self.mask_image.isNull(): + print( + 'Mask image does not exist, creating {}'.format(mask_image_path)) + self.mask_image = QImage( + self.control_image.width(), self.control_image.height(), QImage.Format_ARGB32) + self.mask_image.fill(QColor(0, 0, 0)) + + self.diff_image = self.create_diff_image( + self.control_image, self.rendered_image, self.mask_image) + if not self.diff_image: + self.load_next() + return + + self.control_label.setPixmap(QPixmap.fromImage(self.control_image)) + self.rendered_label.setPixmap(QPixmap.fromImage(self.rendered_image)) + self.mask_label.setPixmap(QPixmap.fromImage(self.mask_image)) + self.diff_label.setPixmap(QPixmap.fromImage(self.diff_image)) + self.preview_mask() + + def preview_mask(self): + self.new_mask_image = self.create_mask( + self.control_image, self.rendered_image, self.mask_image, self.overload_spin.value()) + self.new_mask_label.setPixmap(QPixmap.fromImage(self.new_mask_image)) + + def save_mask(self): + self.new_mask_image.save(self.mask_image_path, "png") + self.load_next() + + def create_mask(self, control_image, rendered_image, mask_image, overload=1): + max_width = min(rendered_image.width(), control_image.width()) + max_height = min(rendered_image.height(), control_image.height()) + + new_mask_image = QImage( + control_image.width(), control_image.height(), QImage.Format_ARGB32) + new_mask_image.fill(QColor(0, 0, 0)) + + # loop through pixels in rendered image and compare + mismatch_count = 0 + linebytes = max_width * 4 + for y in range(max_height): + control_scanline = control_image.constScanLine( + y).asstring(linebytes) + rendered_scanline = rendered_image.constScanLine( + y).asstring(linebytes) + mask_scanline = mask_image.scanLine(y).asstring(linebytes) + + for x in range(max_width): + currentTolerance = qRed( + struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) + + if currentTolerance == 255: + # ignore pixel + new_mask_image.setPixel( + x, y, qRgb(currentTolerance, currentTolerance, currentTolerance)) + continue + + expected_rgb = struct.unpack( + 'I', control_scanline[x * 4:x * 4 + 4])[0] + rendered_rgb = struct.unpack( + 'I', rendered_scanline[x * 4:x * 4 + 4])[0] + difference = min( + 255, colorDiff(expected_rgb, rendered_rgb) * overload) + + if difference > currentTolerance: + # update mask image + new_mask_image.setPixel( + x, y, qRgb(difference, difference, difference)) + mismatch_count += 1 + else: + new_mask_image.setPixel( + x, y, qRgb(currentTolerance, currentTolerance, currentTolerance)) + return new_mask_image + + def get_control_image_path(self, test_name): + if os.path.isfile(test_name): + return path + + # else try and find matching test image + script_folder = os.path.dirname(os.path.realpath(sys.argv[0])) + control_images_folder = os.path.join( + script_folder, '../tests/testdata/control_images') + + matching_control_images = [x[0] + for x in os.walk(control_images_folder) if test_name in x[0]] + if len(matching_control_images) > 1: + QMessageBox.warning( + self, 'Result', 'Found multiple matching control images for {}'.format(test_name)) + return None + elif len(matching_control_images) == 0: + QMessageBox.warning( + self, 'Result', 'No matching control images found for {}'.format(test_name)) + return None + + found_control_image_path = matching_control_images[0] + + # check for a single matching expected image + images = glob.glob(os.path.join(found_control_image_path, '*.png')) + filtered_images = [i for i in images if not i[-9:] == '_mask.png'] + if len(filtered_images) > 1: + error( + 'Found multiple matching control images for {}'.format(test_name)) + elif len(filtered_images) == 0: + error('No matching control images found for {}'.format(test_name)) + + found_image = filtered_images[0] + print('Found matching control image: {}'.format(found_image)) + return found_image + + def create_diff_image(self, control_image, rendered_image, mask_image): + # loop through pixels in rendered image and compare + mismatch_count = 0 + max_width = min(rendered_image.width(), control_image.width()) + max_height = min(rendered_image.height(), control_image.height()) + linebytes = max_width * 4 + + diff_image = QImage( + control_image.width(), control_image.height(), QImage.Format_ARGB32) + diff_image.fill(QColor(152, 219, 249)) + + for y in range(max_height): + control_scanline = control_image.constScanLine( + y).asstring(linebytes) + rendered_scanline = rendered_image.constScanLine( + y).asstring(linebytes) + mask_scanline = mask_image.scanLine(y).asstring(linebytes) + + for x in range(max_width): + currentTolerance = qRed( + struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) + + if currentTolerance == 255: + # ignore pixel + continue + + expected_rgb = struct.unpack( + 'I', control_scanline[x * 4:x * 4 + 4])[0] + rendered_rgb = struct.unpack( + 'I', rendered_scanline[x * 4:x * 4 + 4])[0] + difference = colorDiff(expected_rgb, rendered_rgb) + + if difference > currentTolerance: + # update mask image + diff_image.setPixel(x, y, qRgb(255, 0, 0)) + mismatch_count += 1 + + if mismatch_count: + return diff_image + else: + print('No mismatches') + return None + + +def main(): + app = QApplication(sys.argv) + + parser = argparse.ArgumentParser() + parser.add_argument('dash_url') + args = parser.parse_args() + + w = ResultHandler() + w.parse_url(args.dash_url) + w.exec() + +if __name__ == '__main__': + main() From 37951baf450d11621d20cb8ac83174e29a207803 Mon Sep 17 00:00:00 2001 From: rldhont Date: Sat, 1 Oct 2016 08:35:56 +0200 Subject: [PATCH 041/897] [Processing] Uses os.path.join instead of + os.sep + (#3552) --- .../processing/algs/grass/GrassUtils.py | 21 ++++++++----------- .../processing/algs/grass7/Grass7Utils.py | 18 +++++++--------- .../algs/lidar/fusion/FusionUtils.py | 2 +- .../processing/algs/otb/OTBAlgorithm.py | 2 +- python/plugins/processing/algs/r/RUtils.py | 8 +++---- .../plugins/processing/algs/saga/SagaUtils.py | 8 +++---- 6 files changed, 25 insertions(+), 34 deletions(-) diff --git a/python/plugins/processing/algs/grass/GrassUtils.py b/python/plugins/processing/algs/grass/GrassUtils.py index 409551134f6f..4673b12b2e86 100644 --- a/python/plugins/processing/algs/grass/GrassUtils.py +++ b/python/plugins/processing/algs/grass/GrassUtils.py @@ -65,7 +65,7 @@ def grassBatchJobFilename(): GRASS_BATCH_JOB and then call GRASS and let it do the work ''' filename = 'grass_batch_job.sh' - batchfile = userFolder() + os.sep + filename + batchfile = os.path.join(userFolder(), filename) return batchfile @staticmethod @@ -74,7 +74,7 @@ def grassScriptFilename(): GRASS and then uses grass commands ''' filename = 'grass_script.bat' - filename = userFolder() + os.sep + filename + filename = os.path.join(userFolder(), filename) return filename @staticmethod @@ -132,7 +132,7 @@ def createGrassScript(commands): shell = GrassUtils.grassWinShell() script = GrassUtils.grassScriptFilename() - gisrc = userFolder() + os.sep + 'processing.gisrc' + gisrc = os.path.join(userFolder(), 'processing.gisrc') encoding = locale.getpreferredencoding() # Temporary gisrc file @@ -150,12 +150,10 @@ def createGrassScript(commands): output.write('set HOME=' + os.path.expanduser('~') + '\n') output.write('set GISRC=' + gisrc + '\n') output.write('set GRASS_SH=' + shell + '\\bin\\sh.exe\n') - output.write('set PATH=' + shell + os.sep + 'bin;' + shell + os.sep - + 'lib;' + '%PATH%\n') + output.write('set PATH=' + os.path.join(shell, 'bin') + ';' + os.path.join(shell, 'lib') + ';' + '%PATH%\n') output.write('set WINGISBASE=' + folder + '\n') output.write('set GISBASE=' + folder + '\n') - output.write('set GRASS_PROJSHARE=' + folder + os.sep + 'share' - + os.sep + 'proj' + '\n') + output.write('set GRASS_PROJSHARE=' + os.path.join(folder, 'share', 'proj') + '\n') output.write('set GRASS_MESSAGE_FORMAT=gui\n') # Replacement code for etc/Init.bat @@ -257,7 +255,7 @@ def prepareGrassExecution(commands): GrassUtils.createGrassScript(commands) command = ['cmd.exe', '/C ', GrassUtils.grassScriptFilename()] else: - gisrc = userFolder() + os.sep + 'processing.gisrc' + gisrc = os.path.join(userFolder(), 'processing.gisrc') env['GISRC'] = gisrc env['GRASS_MESSAGE_FORMAT'] = 'gui' env['GRASS_BATCH_JOB'] = GrassUtils.grassBatchJobFilename() @@ -267,11 +265,10 @@ def prepareGrassExecution(commands): os.chmod(GrassUtils.grassBatchJobFilename(), stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE) if isMac(): - command = GrassUtils.grassPath() + os.sep + 'grass.sh ' \ - + GrassUtils.grassMapsetFolder() + '/PERMANENT' + command = os.path.join(GrassUtils.grassPath(), 'grass.sh') + ' ' \ + + os.path.join(GrassUtils.grassMapsetFolder(), 'PERMANENT') else: - command = 'grass64 ' + GrassUtils.grassMapsetFolder() \ - + '/PERMANENT' + command = 'grass64 ' + os.path.join(GrassUtils.grassMapsetFolder(), 'PERMANENT') return command, env diff --git a/python/plugins/processing/algs/grass7/Grass7Utils.py b/python/plugins/processing/algs/grass7/Grass7Utils.py index 779b005a4493..30c1553f622a 100644 --- a/python/plugins/processing/algs/grass7/Grass7Utils.py +++ b/python/plugins/processing/algs/grass7/Grass7Utils.py @@ -62,7 +62,7 @@ def grassBatchJobFilename(): GRASS_BATCH_JOB and then call GRASS and let it do the work ''' filename = 'grass7_batch_job.sh' - batchfile = userFolder() + os.sep + filename + batchfile = os.path.join(userFolder(), filename) return batchfile @staticmethod @@ -71,7 +71,7 @@ def grassScriptFilename(): GRASS and then uses grass commands ''' filename = 'grass7_script.bat' - filename = userFolder() + os.sep + filename + filename = os.path.join(userFolder(), filename) return filename @staticmethod @@ -133,8 +133,7 @@ def createGrass7Script(commands): output.write('set GISRC=' + gisrc + '\n') output.write('set WINGISBASE=' + folder + '\n') output.write('set GISBASE=' + folder + '\n') - output.write('set GRASS_PROJSHARE=' + folder + os.sep + 'share' - + os.sep + 'proj' + '\n') + output.write('set GRASS_PROJSHARE=' + os.path.join(folder, 'share', 'proj') + '\n') output.write('set GRASS_MESSAGE_FORMAT=plain\n') # Replacement code for etc/Init.bat @@ -236,7 +235,7 @@ def prepareGrass7Execution(commands): Grass7Utils.createGrass7Script(commands) command = ['cmd.exe', '/C ', Grass7Utils.grassScriptFilename()] else: - gisrc = userFolder() + os.sep + 'processing.gisrc7' + gisrc = os.path.join(userFolder(), 'processing.gisrc7') env['GISRC'] = gisrc env['GRASS_MESSAGE_FORMAT'] = 'plain' env['GRASS_BATCH_JOB'] = Grass7Utils.grassBatchJobFilename() @@ -245,12 +244,11 @@ def prepareGrass7Execution(commands): Grass7Utils.createGrass7BatchJobFileFromGrass7Commands(commands) os.chmod(Grass7Utils.grassBatchJobFilename(), stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE) - if isMac() and os.path.exists(Grass7Utils.grassPath() + os.sep + '*grass.sh*'): - command = Grass7Utils.grassPath() + os.sep + '*grass.sh* ' \ - + Grass7Utils.grassMapsetFolder() + '/PERMANENT' + if isMac() and os.path.exists(os.path.join(Grass7Utils.grassPath(), '*grass.sh*')): + command = os.path.join(Grass7Utils.grassPath(), '*grass.sh*') + ' ' \ + + os.path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT') else: - command = 'grass70 ' + Grass7Utils.grassMapsetFolder() \ - + '/PERMANENT' + command = 'grass70 ' + os.path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT') return command, env diff --git a/python/plugins/processing/algs/lidar/fusion/FusionUtils.py b/python/plugins/processing/algs/lidar/fusion/FusionUtils.py index 97b8b3f5aea5..2e04c842eefe 100644 --- a/python/plugins/processing/algs/lidar/fusion/FusionUtils.py +++ b/python/plugins/processing/algs/lidar/fusion/FusionUtils.py @@ -49,7 +49,7 @@ def FusionPath(): @staticmethod def tempFileListFilepath(): filename = 'fusion_files_list.txt' - filepath = userFolder() + os.sep + filename + filepath = os.path.join(userFolder(), filename) return filepath @staticmethod diff --git a/python/plugins/processing/algs/otb/OTBAlgorithm.py b/python/plugins/processing/algs/otb/OTBAlgorithm.py index a10acd15d8d0..dd9c484f1ccc 100644 --- a/python/plugins/processing/algs/otb/OTBAlgorithm.py +++ b/python/plugins/processing/algs/otb/OTBAlgorithm.py @@ -179,7 +179,7 @@ def processAlgorithm(self, progress): path = OTBUtils.otbPath() commands = [] - commands.append(path + os.sep + self.cliName) + commands.append(os.path.join(path, self.cliName)) self.roiVectors = {} self.roiRasters = {} diff --git a/python/plugins/processing/algs/r/RUtils.py b/python/plugins/processing/algs/r/RUtils.py index d5c44cb7222c..db8f0a085da4 100644 --- a/python/plugins/processing/algs/r/RUtils.py +++ b/python/plugins/processing/algs/r/RUtils.py @@ -45,7 +45,7 @@ class RUtils(object): R_USE64 = 'R_USE64' R_LIBS_USER = 'R_LIBS_USER' - rscriptfilename = userFolder() + os.sep + 'processing_script.r' + rscriptfilename = os.path.join(userFolder(), 'processing_script.r') @staticmethod def RFolder(): @@ -129,8 +129,7 @@ def executeRAlgorithm(alg, progress): else: execDir = 'i386' command = [ - RUtils.RFolder() + os.sep + 'bin' + os.sep + execDir + os.sep - + 'R.exe', + os.path.join(RUtils.RFolder(), 'bin', execDir, 'R.exe'), 'CMD', 'BATCH', '--vanilla', @@ -208,8 +207,7 @@ def checkRIsInstalled(ignoreRegistrySettings=False): execDir = 'x64' else: execDir = 'i386' - command = [RUtils.RFolder() + os.sep + 'bin' + os.sep + execDir - + os.sep + 'R.exe', '--version'] + command = [os.path.join(RUtils.RFolder(), 'bin', execDir, 'R.exe'), '--version'] else: command = ['R --version'] proc = subprocess.Popen( diff --git a/python/plugins/processing/algs/saga/SagaUtils.py b/python/plugins/processing/algs/saga/SagaUtils.py index 4913c226a367..970bf07a07ca 100644 --- a/python/plugins/processing/algs/saga/SagaUtils.py +++ b/python/plugins/processing/algs/saga/SagaUtils.py @@ -48,7 +48,7 @@ def sagaBatchJobFilename(): else: filename = 'saga_batch_job.sh' - batchfile = userFolder() + os.sep + filename + batchfile = os.path.join(userFolder(), filename) return batchfile @@ -88,12 +88,10 @@ def createSagaBatchJobFileFromSagaCommands(commands): fout = open(sagaBatchJobFilename(), 'w') if isWindows(): fout.write('set SAGA=' + sagaPath() + '\n') - fout.write('set SAGA_MLB=' + sagaPath() + os.sep - + 'modules' + '\n') + fout.write('set SAGA_MLB=' + os.path.join(sagaPath(), 'modules') + '\n') fout.write('PATH=%PATH%;%SAGA%;%SAGA_MLB%\n') elif isMac(): - fout.write('export SAGA_MLB=' + sagaPath() - + '/../lib/saga\n') + fout.write('export SAGA_MLB=' + os.path.join(sagaPath(), '../lib/saga') + '\n') fout.write('export PATH=' + sagaPath() + ':$PATH\n') else: pass From 437d785c7251a50eb44063502e61a55afd5660db Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 10:19:01 +0200 Subject: [PATCH 042/897] debian packaging: reorder build dependencies and add python3-pyqt5.qtsvg --- debian/control.in | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/debian/control.in b/debian/control.in index ac0580e3e2bc..2659e4d0a8e7 100644 --- a/debian/control.in +++ b/debian/control.in @@ -13,26 +13,23 @@ Build-Depends: libexpat1-dev, libfcgi-dev, #sid stretch jessie trusty xenial# libgdal-dev (>= 1.10.1-0~), - libgeos-dev (>= 3.0.0), #jessie trusty# libgsl0-dev, #sid stretch xenial# libgsl-dev, + libgeos-dev (>= 3.0.0), libpq-dev, libproj-dev, - qtbase5-dev, - libqca-qt5-2-dev, - libqwt-qt5-dev, libspatialite-dev, libsqlite3-dev, libspatialindex-dev, + qtbase5-dev, qttools5-dev-tools, qttools5-dev, qtscript5-dev, qtpositioning5-dev, + libqt5svg5-dev, libqt5xmlpatterns5-dev, libqt5webkit5-dev, libqt5opengl5-dev, libqt5sql5-sqlite, libqt5scintilla2-dev, + libqwt-qt5-dev, libqca-qt5-2-dev, + python3-dev, python3-all-dev, python3-sip, python3-sip-dev, + pyqt5-dev-tools, pyqt5-dev, pyqt5.qsci-dev, + python3-pyqt5, python3-pyqt5.qsci, python3-pyqt5.qtsql, python3-pyqt5.qtsvg, + python3-gdal, + python3-nose2, python3-yaml, python3-mock, python3-psycopg2, python3-future, python3-termcolor, pkg-config, - pyqt5-dev, - python3-dev, - python3-all-dev, - python3-sip, - python3-sip-dev, - python3-pyqt5, -#sid# libosgearth-dev, - qttools5-dev-tools, git, txt2tags, doxygen, @@ -41,13 +38,7 @@ Build-Depends: graphviz, xvfb, xauth, xfonts-base, xfonts-100dpi, xfonts-75dpi, xfonts-scalable, - libqt5svg5-dev, libqt5xmlpatterns5-dev, - pyqt5.qsci-dev, - libqt5webkit5-dev, qttools5-dev, qtscript5-dev, - libqt5scintilla2-dev, pyqt5-dev-tools, python3-pyqt5.qtsql, qtpositioning5-dev, libqt5opengl5-dev, libqt5sql5-sqlite, - python3-pyqt5.qsci, - pyqt5.qsci-dev, python3-nose2, - python3-gdal, python3-yaml, python3-mock, python3-psycopg2, python3-future, python3-termcolor, +#sid# libosgearth-dev, #oracle# oracle-instantclient12.1-devel, locales, ca-certificates Build-Conflicts: libqgis-dev, qgis-dev From f4cb295e65cf7e27758d22fe37e456bb59567fce Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 11:23:26 +0200 Subject: [PATCH 043/897] server sip sync --- doc/api_break.dox | 1 + python/server/qgsaccesscontrolfilter.sip | 53 +++++++++---- python/server/qgscapabilitiescache.sip | 23 ++++-- python/server/qgsmapserviceexception.sip | 2 +- python/server/qgsrequesthandler.sip | 60 +++++++++++++++ python/server/qgsserverfilter.sip | 5 +- python/server/qgsserverinterface.sip | 97 ++++++++++++++++++------ src/server/qgsaccesscontrolfilter.h | 3 + src/server/qgscapabilitiescache.h | 3 +- src/server/qgsrequesthandler.h | 33 +++++++- src/server/qgsserverinterface.h | 20 +++-- src/server/qgsserverinterfaceimpl.h | 2 +- 12 files changed, 244 insertions(+), 58 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index d77ac8a2f456..1392a289391d 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -172,6 +172,7 @@ This page tries to maintain a list with incompatible changes that happened in pr QgsVectorLayerrendererV2renderer QgsVectorLayerEditUtilsdeleteVertexV2deleteVertex QgsComposerSymbolItemsymbolV2symbol +QgsServerInterfacecapabiblitiesCachecapabilitiesCache \subsection qgis_api_break_3_0_removed_classes Removed Classes diff --git a/python/server/qgsaccesscontrolfilter.sip b/python/server/qgsaccesscontrolfilter.sip index 0e5f9b3480c7..cda43ceed8b1 100644 --- a/python/server/qgsaccesscontrolfilter.sip +++ b/python/server/qgsaccesscontrolfilter.sip @@ -18,15 +18,16 @@ ***************************************************************************/ /** + * \ingroup server * \class QgsAccessControlFilter - * \brief Class defining access control interface for QGIS Server. + * \brief Class defining access control interface for QGIS Server plugins. * * Security can define any (or none) of the following method: - * * layerFilterExpression() - * * layerFilterSubsetString() - * * layerPermissions() - * * authorizedLayerAttributes() - * * allowToEdit() + * * layerFilterExpression() - To get an additional expression filter (WMS/GetMap, WMS/GetFeatureInfo, WFS/GetFeature) + * * layerFilterSQL() - To get an additional SQL filter (WMS/GetMap, WMS/GetFeatureInfo, WFS/GetFeature) for layer that support SQL + * * layerPermissions() - To give the general layer permissins (read / update / insert / delete) + * * authorizedLayerAttributes() - Tho filter the attributes (WMS/GetFeatureInfo, WFS/GetFeature) + * * allowToEdit() - (all WFS-T requests) * * cacheKey() */ @@ -39,7 +40,7 @@ class QgsAccessControlFilter public: /** Constructor * QgsServerInterface passed to plugins constructors - * and must be passed to QgsAccessControlPlugin instances. + * and must be passed to QgsAccessControlFilter instances. */ QgsAccessControlFilter( const QgsServerInterface* serverInterface ); /** Destructor */ @@ -56,18 +57,42 @@ class QgsAccessControlFilter /** Return the QgsServerInterface instance*/ const QgsServerInterface* serverInterface() const; - /** Return an additional expression filter */ + + /** Return an additional expression filter + * @param layer the layer to control + * @return the filter expression + */ virtual QString layerFilterExpression( const QgsVectorLayer* layer ) const; - /** Return an additional the subset string (typically SQL) filter. - Faster than the layerFilterExpression but not supported on all the type of layer */ + + /** Return an additional subset string (typically SQL) filter + * @param layer the layer to control + * @return the subset string + */ virtual QString layerFilterSubsetString( const QgsVectorLayer* layer ) const; - /** Return the layer permissions */ + + /** Return the layer permissions + * @param layer the layer to control + * @return the permission to use on the layer + */ virtual LayerPermissions layerPermissions( const QgsMapLayer* layer ) const; - /** Return the authorized layer attributes */ + + /** Return the authorized layer attributes + * @param layer the layer to control + * @param attributes the current list of visible attribute + * @return the new list of visible attributes + */ virtual QStringList authorizedLayerAttributes( const QgsVectorLayer* layer, const QStringList& attributes ) const; - /** Are we authorize to modify the following geometry */ + + /** Are we authorized to modify the following geometry + * @param layer the layer to control + * @param feature the concerned feature + * @return true if we are allowed to edit + */ virtual bool allowToEdit( const QgsVectorLayer* layer, const QgsFeature& feature ) const; - /** Cache key to used to create the capabilities cache, "" for no cache, shouldn't any contains "-", default to "" */ + + /** Cache key to used to create the capabilities cache + * @return the cache key, "" for no cache + */ virtual QString cacheKey() const; }; diff --git a/python/server/qgscapabilitiescache.sip b/python/server/qgscapabilitiescache.sip index fe54f64134ed..8ec5fab8ac42 100644 --- a/python/server/qgscapabilitiescache.sip +++ b/python/server/qgscapabilitiescache.sip @@ -15,10 +15,9 @@ * * ***************************************************************************/ -/** -* \class QgsCapabilitiesCache -* \brief A cache for capabilities xml documents (by configuration file path) -*/ +/** \ingroup server + * A cache for capabilities xml documents (by configuration file path) + */ class QgsCapabilitiesCache: QObject { %TypeHeaderCode @@ -26,10 +25,18 @@ class QgsCapabilitiesCache: QObject %End public: - /** Returns cached capabilities document (or 0 if document for configuration file not in cache)*/ - const QDomDocument* searchCapabilitiesDocument( const QString& configFilePath, const QString& version ); - /** Inserts new capabilities document (creates a copy of the document, does not take ownership)*/ - void insertCapabilitiesDocument( const QString& configFilePath, const QString& version, const QDomDocument* doc ); + /** Returns cached capabilities document (or 0 if document for configuration file not in cache) + * @param configFilePath the progect file path + * @param key key used to separate different version in different cache + */ + const QDomDocument* searchCapabilitiesDocument( const QString& configFilePath, const QString& key ); + + /** Inserts new capabilities document (creates a copy of the document, does not take ownership) + * @param configFilePath the project file path + * @param key key used to separate different version in different cache + * @param doc the DOM document + */ + void insertCapabilitiesDocument( const QString& configFilePath, const QString& key, const QDomDocument* doc ); /** Remove capabilities document * @param path the project file path diff --git a/python/server/qgsmapserviceexception.sip b/python/server/qgsmapserviceexception.sip index 4d0b512ca1c5..0c1c208b7ff0 100644 --- a/python/server/qgsmapserviceexception.sip +++ b/python/server/qgsmapserviceexception.sip @@ -16,7 +16,7 @@ ***************************************************************************/ -/** +/** \ingroup server * \class QgsMapServiceException * \brief Exception class for WMS service exceptions. * diff --git a/python/server/qgsrequesthandler.sip b/python/server/qgsrequesthandler.sip index 15064071285e..71eaab397256 100644 --- a/python/server/qgsrequesthandler.sip +++ b/python/server/qgsrequesthandler.sip @@ -26,46 +26,106 @@ class QgsRequestHandler public: + /** Parses the input and creates a request neutral Parameter/Value map + * @note not available in Python bindings + */ + // virtual void parseInput() = 0; + + /** Sends the map image back to the client + * @note not available in Python bindings + */ + // virtual void setGetMapResponse( const QString& service, QImage* img, int imageQuality ) = 0; + + //! @note not available in Python bindings + // virtual void setGetCapabilitiesResponse( const QDomDocument& doc ) = 0; + + //! @note not available in Python bindings + // virtual void setGetFeatureInfoResponse( const QDomDocument& infoDoc, const QString& infoFormat ) = 0; + /** Allow plugins to return a QgsMapServiceException*/ virtual void setServiceException( QgsMapServiceException ex /Transfer/ ) = 0; + + //! @note not available in Python bindings + // virtual void setXmlResponse( const QDomDocument& doc ) = 0; + + //! @note not available in Python bindings + // virtual void setXmlResponse( const QDomDocument& doc, const QString& mimeType ) = 0; + + //! @note not available in Python bindings + // virtual void setGetPrintResponse( QByteArray* b ) = 0; + + //! @note not available in Python bindings + // virtual bool startGetFeatureResponse( QByteArray* ba, const QString& infoFormat ) = 0; + + //! @note not available in Python bindings + // virtual void setGetFeatureResponse( QByteArray* ba ) = 0; + + //! @note not available in Python bindings + virtual void endGetFeatureResponse( QByteArray* ba ) = 0; + + //! @note not available in Python bindings + virtual void setGetCoverageResponse( QByteArray* ba ) = 0; + virtual void setDefaultHeaders(); + /** Set an HTTP header*/ virtual void setHeader( const QString &name, const QString &value ) = 0; + /** Remove an HTTP header*/ virtual int removeHeader( const QString &name ) = 0; + /** Delete all HTTP headers*/ virtual void clearHeaders() = 0; + /** Append the bytestream to response body*/ virtual void appendBody( const QByteArray &body ) = 0; + /** Clears the response body*/ virtual void clearBody() = 0; + /** Return the response body*/ virtual QByteArray body(); + /** Set the info format string such as "text/xml"*/ virtual void setInfoFormat( const QString &format ) = 0; + /** Check whether there is any header set or the body is not empty*/ virtual bool responseReady() const = 0; + /** Send out HTTP headers and flush output buffer*/ virtual void sendResponse() = 0; + /** Pointer to last raised exception*/ virtual bool exceptionRaised() const = 0; + /** Return a copy of the parsed parameters as a key-value pair, to modify * a parameter setParameter( const QString &key, const QString &value) * and removeParameter(const QString &key) must be used */ QMap parameterMap(); + /** Set a request parameter*/ virtual void setParameter( const QString &key, const QString &value ) = 0; + /** Remove a request parameter*/ virtual int removeParameter( const QString &key ) = 0; + /** Return a request parameter*/ virtual QString parameter( const QString &key ) const = 0; + /** Return the requested format string*/ QString format() const; + /** Return the mime type for the response*/ QString infoFormat() const; + /** Return true if the HTTP headers were already sent to the client*/ bool headersSent(); + + + //! @note not available in Python bindings + // virtual QPair getResponse() = 0; + private: /** Parses the input and creates a request neutral Parameter/Value map*/ virtual void parseInput() = 0; diff --git a/python/server/qgsserverfilter.sip b/python/server/qgsserverfilter.sip index 76d6a6f7426b..f13834de6751 100644 --- a/python/server/qgsserverfilter.sip +++ b/python/server/qgsserverfilter.sip @@ -1,6 +1,6 @@ /*************************************************************************** qgsserverfilter.h - Server I/O filters class for Qgis Mapserver for use by plugins + Server I/O filters class for QGIS Server for use by plugins ------------------- begin : 2014-09-10 copyright : (C) 2014 by Alessandro Pasotti @@ -17,8 +17,9 @@ ***************************************************************************/ /** + * \ingroup server * \class QgsServerFilter - * \brief Class defining I/O filters for Qgis Mapserver and + * \brief Class defining I/O filters for QGIS Server and * implemented in plugins. * * Filters can define any (or none) of the following hooks: diff --git a/python/server/qgsserverinterface.sip b/python/server/qgsserverinterface.sip index 3033cdfe4b53..cc6551017f62 100644 --- a/python/server/qgsserverinterface.sip +++ b/python/server/qgsserverinterface.sip @@ -18,14 +18,17 @@ ***************************************************************************/ /** - * \class QgsServerInterface - * \brief Class defining the interface made available to server plugins. + * \ingroup server + * QgsServerInterface + * Class defining interfaces exposed by QGIS Server and + * made available to plugins. * * This class provides methods to access the request handler and * the capabilties cache. A method to read the environment * variables set in the main FCGI loop is also available. * Plugins can add listeners (instances of QgsServerFilter) with * a certain priority through the registerFilter( QgsServerFilter* , int) method. + * */ @@ -40,39 +43,89 @@ class QgsServerInterface %End public: - /** Returns the current request handler*/ + /** + * Set the request handler + * @param requestHandler request handler + * @note not available in Python bindings + */ + // virtual void setRequestHandler( QgsRequestHandler* requestHandler ) = 0; + + /** + * Clear the request handler + * + * @note not available in python bindings + */ + // virtual void clearRequestHandler() = 0; + + /** + * Get pointer to the capabiblities cache + * @return QgsCapabilitiesCache + */ + virtual QgsCapabilitiesCache* capabilitiesCache() = 0 /KeepReference/; + + /** + * Get pointer to the request handler + * @return QgsRequestHandler + */ virtual QgsRequestHandler* requestHandler() = 0 /KeepReference/; - /** Returns the capabilities cache*/ - virtual QgsCapabilitiesCache* capabiblitiesCache() = 0 /KeepReference/; - // Tansfer ownership to avoid garbage collector to call dtor - /** Register a filter with the given priority. The filter's requestReady() - * and responseReady() methods will be called from the loop*/ + + /** + * Register a QgsServerFilter + * @param filter the QgsServerFilter to add + * @param priority an optional priority for the filter order + */ virtual void registerFilter( QgsServerFilter* filter /Transfer/, int priority = 0 ) = 0; - /** Set the filters map */ + + /** + * Set the filters map + * @param filters the QgsServerFiltersMap + */ virtual void setFilters( QgsServerFiltersMap* filters /Transfer/) = 0; - /** Register a security module with the given priority.*/ + + /** + * Return the list of current QgsServerFilter + * @return QgsServerFiltersMap list of QgsServerFilter + */ + virtual QgsServerFiltersMap filters() = 0; + + /** Register an access control filter + * @param accessControl the access control to register + * @param priority the priority used to order them + */ virtual void registerAccessControl( QgsAccessControlFilter* accessControl /Transfer/, int priority = 0 ) = 0; + /** Gets the registred access control filters */ virtual const QgsAccessControl* accessControls() const = 0; - /** Return an environment variable set by FCGI*/ + + //! Return an enrironment variable, used to pass environment variables to python virtual QString getEnv(const QString& name ) const = 0; - // Commented because of problems with typedef QgsServerFiltersMap, provided - // methods to alter the filters map into QgsRequestHandler API - virtual QgsServerFiltersMap filters() = 0; - /** Returns the configFilePath as seen by the server, this value is only - * available after requestReady has been called.*/ + + /** + * Return the configuration file path + * @return QString containing the configuration file path + */ virtual QString configFilePath() = 0; - /** Set the config file path */ + + /** + * Set the configuration file path + * @param configFilePath QString with the configuration file path + */ virtual void setConfigFilePath( const QString& configFilePath) = 0; - /** Remove entry from config cache */ + + /** + * Remove entry from config cache + * @param path the path of the file to remove + */ virtual void removeConfigCacheEntry( const QString& path ) = 0; - /** Remove entry from layer cache */ - virtual void removeProjectLayers( const QString& path ) = 0; + /** + * Remove entries from layer cache + * @param path the path of the project which own the layers to be removed + */ + virtual void removeProjectLayers( const QString& path ) = 0; -private: + private: /** Constructor */ QgsServerInterface(); - }; diff --git a/src/server/qgsaccesscontrolfilter.h b/src/server/qgsaccesscontrolfilter.h index 2dbb7bd65d00..72dfd2f56432 100644 --- a/src/server/qgsaccesscontrolfilter.h +++ b/src/server/qgsaccesscontrolfilter.h @@ -1,6 +1,8 @@ /*************************************************************************** qgsaccesscontrolfilter.h ------------------------ + Access control interface for Qgis Server plugins + begin : 2015-05-19 copyright : (C) 2015 by Stéphane Brunner email : stephane dot brunner at camptocamp dot org @@ -40,6 +42,7 @@ class QgsFeature; * * layerPermissions() - To give the general layer permissins (read / update / insert / delete) * * authorizedLayerAttributes() - Tho filter the attributes (WMS/GetFeatureInfo, WFS/GetFeature) * * allowToEdit() - (all WFS-T requests) + * * cacheKey() */ class SERVER_EXPORT QgsAccessControlFilter { diff --git a/src/server/qgscapabilitiescache.h b/src/server/qgscapabilitiescache.h index 199832f4ed17..c82217ae0068 100644 --- a/src/server/qgscapabilitiescache.h +++ b/src/server/qgscapabilitiescache.h @@ -24,7 +24,8 @@ #include /** \ingroup server - * A cache for capabilities xml documents (by configuration file path)*/ + * A cache for capabilities xml documents (by configuration file path) + */ class SERVER_EXPORT QgsCapabilitiesCache : public QObject { Q_OBJECT diff --git a/src/server/qgsrequesthandler.h b/src/server/qgsrequesthandler.h index ee1ff47d9e7f..2bef3970122a 100644 --- a/src/server/qgsrequesthandler.h +++ b/src/server/qgsrequesthandler.h @@ -59,69 +59,98 @@ class QgsRequestHandler * @note not available in Python bindings */ virtual void parseInput() = 0; + /** Sends the map image back to the client * @note not available in Python bindings */ virtual void setGetMapResponse( const QString& service, QImage* img, int imageQuality ) = 0; + //! @note not available in Python bindings virtual void setGetCapabilitiesResponse( const QDomDocument& doc ) = 0; - //! @note not availabe in Python bindings + + //! @note not available in Python bindings virtual void setGetFeatureInfoResponse( const QDomDocument& infoDoc, const QString& infoFormat ) = 0; + /** Allow plugins to return a QgsMapServiceException*/ virtual void setServiceException( QgsMapServiceException ex ) = 0; + //! @note not available in Python bindings virtual void setXmlResponse( const QDomDocument& doc ) = 0; + //! @note not available in Python bindings virtual void setXmlResponse( const QDomDocument& doc, const QString& mimeType ) = 0; + //! @note not available in Python bindings virtual void setGetPrintResponse( QByteArray* b ) = 0; + //! @note not available in Python bindings virtual bool startGetFeatureResponse( QByteArray* ba, const QString& infoFormat ) = 0; + //! @note not available in Python bindings virtual void setGetFeatureResponse( QByteArray* ba ) = 0; //! @note not available in Python bindings virtual void endGetFeatureResponse( QByteArray* ba ) = 0; + //! @note not available in Python bindings virtual void setGetCoverageResponse( QByteArray* ba ) = 0; + virtual void setDefaultHeaders() {} + /** Set an HTTP header*/ virtual void setHeader( const QString &name, const QString &value ) = 0; + /** Remove an HTTP header*/ virtual int removeHeader( const QString &name ) = 0; + /** Delete all HTTP headers*/ virtual void clearHeaders() = 0; + /** Append the bytestream to response body*/ virtual void appendBody( const QByteArray &body ) = 0; + /** Clears the response body*/ virtual void clearBody() = 0; + /** Return the response body*/ virtual QByteArray body() { return mBody; } + /** Set the info format string such as "text/xml"*/ virtual void setInfoFormat( const QString &format ) = 0; + /** Check whether there is any header set or the body is not empty*/ virtual bool responseReady() const = 0; + /** Send out HTTP headers and flush output buffer*/ virtual void sendResponse() = 0; + /** Pointer to last raised exception*/ virtual bool exceptionRaised() const = 0; + /** Return a copy of the parsed parameters as a key-value pair, to modify * a parameter setParameter( const QString &key, const QString &value) * and removeParameter(const QString &key) must be used */ QMap parameterMap() { return mParameterMap; } + /** Set a request parameter*/ virtual void setParameter( const QString &key, const QString &value ) = 0; + /** Remove a request parameter*/ virtual int removeParameter( const QString &key ) = 0; + /** Return a request parameter*/ virtual QString parameter( const QString &key ) const = 0; + /** Return the requested format string*/ QString format() const { return mFormat; } + /** Return the mime type for the response*/ QString infoFormat() const { return mInfoFormat; } + /** Return true if the HTTP headers were already sent to the client*/ bool headersSent() { return mHeadersSent; } + #ifdef HAVE_SERVER_PYTHON_PLUGINS /** Allow core services to call plugin hooks through sendResponse() * @note not available in Python bindings @@ -129,7 +158,7 @@ class QgsRequestHandler virtual void setPluginFilters( QgsServerFiltersMap pluginFilters ) = 0; #endif - //! @note not availabe in Python bindings + //! @note not available in Python bindings virtual QPair getResponse() = 0; protected: diff --git a/src/server/qgsserverinterface.h b/src/server/qgsserverinterface.h index 2a50d4f9ea54..228bd7a2ccaa 100644 --- a/src/server/qgsserverinterface.h +++ b/src/server/qgsserverinterface.h @@ -1,7 +1,8 @@ /*************************************************************************** - qgsseerversinterface.h - Interface class for exposing functions in QGIS Server for use by plugins - ------------------- + qgsserverinterface.h + + Class defining the interface made available to QGIS Server plugins. + ------------------- begin : 2014-09-10 copyright : (C) 2014 by Alessandro Pasotti email : a dot pasotti at itopen dot it @@ -32,6 +33,12 @@ * Class defining interfaces exposed by QGIS Server and * made available to plugins. * + * This class provides methods to access the request handler and + * the capabilties cache. A method to read the environment + * variables set in the main FCGI loop is also available. + * Plugins can add listeners (instances of QgsServerFilter) with + * a certain priority through the registerFilter( QgsServerFilter* , int) method. + * */ class SERVER_EXPORT QgsServerInterface { @@ -62,7 +69,7 @@ class SERVER_EXPORT QgsServerInterface * Get pointer to the capabiblities cache * @return QgsCapabilitiesCache */ - virtual QgsCapabilitiesCache* capabiblitiesCache() = 0; + virtual QgsCapabilitiesCache* capabilitiesCache() = 0; /** * Get pointer to the request handler @@ -88,11 +95,13 @@ class SERVER_EXPORT QgsServerInterface * @return QgsServerFiltersMap list of QgsServerFilter */ virtual QgsServerFiltersMap filters() = 0; + /** Register an access control filter * @param accessControl the access control to register * @param priority the priority used to order them */ virtual void registerAccessControl( QgsAccessControlFilter* accessControl, int priority = 0 ) = 0; + /** Gets the registred access control filters */ virtual const QgsAccessControl* accessControls() const = 0; @@ -123,9 +132,6 @@ class SERVER_EXPORT QgsServerInterface */ virtual void removeProjectLayers( const QString& path ) = 0; - - - private: QString mConfigFilePath; }; diff --git a/src/server/qgsserverinterfaceimpl.h b/src/server/qgsserverinterfaceimpl.h index 899e4ee93a7b..92e58b5bf317 100644 --- a/src/server/qgsserverinterfaceimpl.h +++ b/src/server/qgsserverinterfaceimpl.h @@ -46,7 +46,7 @@ class QgsServerInterfaceImpl : public QgsServerInterface void setRequestHandler( QgsRequestHandler* requestHandler ) override; void clearRequestHandler() override; - QgsCapabilitiesCache* capabiblitiesCache() override { return mCapabilitiesCache; } + QgsCapabilitiesCache* capabilitiesCache() override { return mCapabilitiesCache; } //! Return the QgsRequestHandler, to be used only in server plugins QgsRequestHandler* requestHandler() override { return mRequestHandler; } void registerFilter( QgsServerFilter *filter, int priority = 0 ) override; From 00942744f7507b389803f30df75944981103c094 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 11:27:07 +0200 Subject: [PATCH 044/897] debian packaging: add libqca-qt5-2-plugins build dependency --- debian/control.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/debian/control.in b/debian/control.in index 2659e4d0a8e7..c9269be601e5 100644 --- a/debian/control.in +++ b/debian/control.in @@ -23,7 +23,7 @@ Build-Depends: libspatialindex-dev, qtbase5-dev, qttools5-dev-tools, qttools5-dev, qtscript5-dev, qtpositioning5-dev, libqt5svg5-dev, libqt5xmlpatterns5-dev, libqt5webkit5-dev, libqt5opengl5-dev, libqt5sql5-sqlite, libqt5scintilla2-dev, - libqwt-qt5-dev, libqca-qt5-2-dev, + libqwt-qt5-dev, libqca-qt5-2-dev, libqca-qt5-2-plugins, python3-dev, python3-all-dev, python3-sip, python3-sip-dev, pyqt5-dev-tools, pyqt5-dev, pyqt5.qsci-dev, python3-pyqt5, python3-pyqt5.qsci, python3-pyqt5.qtsql, python3-pyqt5.qtsvg, From 50b04c5cd9bf64329e6728b9885c17a7dcf47c58 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 13:23:10 +0200 Subject: [PATCH 045/897] only include server bindings in sip coverage tests if they are built --- doc/CMakeLists.txt | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 3d4b61f1fe2b..5c8edeffe46c 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -75,15 +75,21 @@ IF(WITH_APIDOC) ${CMAKE_SOURCE_DIR}/src/analysis/raster ${CMAKE_SOURCE_DIR}/src/analysis/vector ${CMAKE_SOURCE_DIR}/src/plugins - ${CMAKE_SOURCE_DIR}/src/server/qgsserver.h - ${CMAKE_SOURCE_DIR}/src/server/qgscapabilitiescache.h - ${CMAKE_SOURCE_DIR}/src/server/qgsmapserviceexception.h - ${CMAKE_SOURCE_DIR}/src/server/qgsrequesthandler.h - ${CMAKE_SOURCE_DIR}/src/server/qgsserverfilter.h - ${CMAKE_SOURCE_DIR}/src/server/qgsaccesscontrolfilter.h - ${CMAKE_SOURCE_DIR}/src/server/qgsserverinterface.h ) + IF(WITH_SERVER_PLUGINS) + SET(DOXYGEN_INPUT + ${DOXYGEN_INPUT} + ${CMAKE_SOURCE_DIR}/src/server/qgsserver.h + ${CMAKE_SOURCE_DIR}/src/server/qgscapabilitiescache.h + ${CMAKE_SOURCE_DIR}/src/server/qgsmapserviceexception.h + ${CMAKE_SOURCE_DIR}/src/server/qgsrequesthandler.h + ${CMAKE_SOURCE_DIR}/src/server/qgsserverfilter.h + ${CMAKE_SOURCE_DIR}/src/server/qgsaccesscontrolfilter.h + ${CMAKE_SOURCE_DIR}/src/server/qgsserverinterface.h + ) + ENDIF(WITH_SERVER_PLUGINS) + SET(DOXYGEN_FILE_PATTERNS *.h *.cpp *.dox) SET(DOXYGEN_FILES) From 4b868389099cd9894d10c9ce74191016d3d0de31 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 13:42:26 +0200 Subject: [PATCH 046/897] debian packaging: re-enable server --- debian/control.in | 52 +++++++++++++++++------------------ debian/python-qgis.install.in | 2 +- debian/rules | 19 ++----------- 3 files changed, 29 insertions(+), 44 deletions(-) diff --git a/debian/control.in b/debian/control.in index c9269be601e5..322a4f5ba7bb 100644 --- a/debian/control.in +++ b/debian/control.in @@ -185,17 +185,17 @@ Description: QGIS custom widgets for Qt Designer . This package contains a library to use specific QGIS widgets in Qt Designer. -#server#Package: libqgis-server{QGIS_ABI} -#server#Architecture: any -#server#Depends: -#server# ${shlibs:Depends}, -#server# ${misc:Depends} -#server#Description: QGIS - shared server library -#server# QGIS is a Geographic Information System (GIS) which manages, analyzes and -#server# display databases of geographic information. -#server# . -#server# This package contains the shared server library. -#server# +Package: libqgis-server{QGIS_ABI} +Architecture: any +Depends: + ${shlibs:Depends}, + ${misc:Depends} +Description: QGIS - shared server library + QGIS is a Geographic Information System (GIS) which manages, analyzes and + display databases of geographic information. + . + This package contains the shared server library. + Package: libqgis-dev Architecture: any Section: libdevel @@ -405,21 +405,21 @@ Description: collection of data providers to QGIS - architecture-independent fil . This package contains architecture-independent files for the QGIS providers. -#server#Package: qgis-server -#server#Architecture: any -#server#Depends: -#server# qgis-providers (= ${binary:Version}), -#server# ${shlibs:Depends}, -#server# ${misc:Depends} -#server#Conflicts: qgis-mapserver -#server#Provides: qgis-mapserver -#server#Replaces: qgis-mapserver -#server#Description: QGIS server providing various OGC services -#server# QGIS is a Geographic Information System (GIS) which manages, analyzes and -#server# display databases of geographic information. -#server# . -#server# This package contains the QGIS server. -#server# +Package: qgis-server +Architecture: any +Depends: + qgis-providers (= ${binary:Version}), + ${shlibs:Depends}, + ${misc:Depends} +Conflicts: qgis-mapserver +Provides: qgis-mapserver +Replaces: qgis-mapserver +Description: QGIS server providing various OGC services + QGIS is a Geographic Information System (GIS) which manages, analyzes and + display databases of geographic information. + . + This package contains the QGIS server. + Package: qgis-api-doc Architecture: all Section: doc diff --git a/debian/python-qgis.install.in b/debian/python-qgis.install.in index a52ae5cf401f..3c1a11dd3f07 100644 --- a/debian/python-qgis.install.in +++ b/debian/python-qgis.install.in @@ -7,4 +7,4 @@ usr/lib/python*/*-packages/qgis/networkanalysis/* usr/lib/python*/*-packages/qgis/PyQt/* usr/lib/python*/*-packages/qgis/testing/* usr/lib/python*/*-packages/pyspatialite/* -#server#usr/lib/python*/*-packages/qgis/server/* +usr/lib/python*/*-packages/qgis/server/* diff --git a/debian/rules b/debian/rules index b92a1de53290..84b4b5f8324c 100755 --- a/debian/rules +++ b/debian/rules @@ -34,11 +34,6 @@ ifneq (,$(findstring -oracle,$(DISTRIBUTION))) WITH_ORACLE=1 endif -ifneq (,$(findstring -server,$(DISTRIBUTION))) - DISTRIBUTION := $(subst -oracle,,$(DISTRIBUTION)) - WITH_SERVER=1 -endif - QT_PLUGINS_DIR = usr/lib/$(DEB_BUILD_MULTIARCH)/qt5/plugins ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"stretch xenial")) @@ -83,8 +78,8 @@ CMAKE_OPTS := \ -DWITH_INTERNAL_NOSE2=FALSE \ -DWITH_INTERNAL_SIX=FALSE \ -DWITH_GLOBE=FALSE \ - -DWITH_SERVER=FALSE \ - -DWITH_SERVER_PLUGINS=FALSE \ + -DWITH_SERVER=TRUE \ + -DWITH_SERVER_PLUGINS=TRUE \ -DWITH_QWTPOLAR=FALSE \ -DWITH_QSPATIALITE=TRUE \ -DWITH_PYSPATIALITE=TRUE \ @@ -113,12 +108,6 @@ ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) endif -ifeq (,$(findstring $(DISTRIBUTION),"stretch sid xenial")) - CMAKE_OPTS += -DWITH_INTERNAL_FUTURE=TRUE -else - CMAKE_OPTS += -DWITH_INTERNAL_FUTURE=FALSE -endif - ifneq (,$(WITH_GLOBE)) CMAKE_OPTS += -DWITH_GLOBE=TRUE endif @@ -207,10 +196,6 @@ ifneq (,$(WITH_ORACLE)) CONTROL_EXPRESSIONS += oracle endif -ifneq (,$(WITH_SERVER)) - CONTROL_EXPRESSIONS += server -endif - define gentemplate $(2): $(1) sed -r \ From 9a261cfbbce90774df2dfc77278dc95613cfce29 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 19 Sep 2016 14:12:15 +0200 Subject: [PATCH 047/897] QgsFields::fieldNameIndex also matches field alias This method is also doing case insensitive "fuzzy" matching now, this just adds yet another level of tolerance. This changes the expressions to also take the alias into account if no matches have been found. --- src/core/qgsfield.cpp | 10 ++++++++-- src/core/qgsfield.h | 30 +++++++++++++++++++++++++----- tests/src/core/testqgsfields.cpp | 6 ++++++ 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index f3eed7805561..4363fb0f093b 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -481,9 +481,9 @@ int QgsFields::fieldOriginIndex( int fieldIdx ) const return d->fields[fieldIdx].originIndex; } -int QgsFields::indexFromName( const QString &name ) const +int QgsFields::indexFromName( const QString &fieldName ) const { - return d->nameToIndex.value( name, -1 ); + return d->nameToIndex.value( fieldName, -1 ); } QList QgsFields::toList() const @@ -605,6 +605,12 @@ int QgsFields::fieldNameIndex( const QString& fieldName ) const return idx; } + for ( int idx = 0; idx < count(); ++idx ) + { + if ( QString::compare( d->fields[idx].field.alias(), fieldName, Qt::CaseInsensitive ) == 0 ) + return idx; + } + return -1; } diff --git a/src/core/qgsfield.h b/src/core/qgsfield.h index 3937bb1aabe9..7dbe3d3505fe 100644 --- a/src/core/qgsfield.h +++ b/src/core/qgsfield.h @@ -365,12 +365,32 @@ class CORE_EXPORT QgsFields //! Get field's origin index (its meaning is specific to each type of origin) int fieldOriginIndex( int fieldIdx ) const; - //! Look up field's index from name. Returns -1 on error - int indexFromName( const QString& name ) const; + /** + * Look up field's index from the field name. + * This method takes is case sensitive and only matches the data source + * name of the field. + * + * @param fieldName The name of the field. + * + * @return The field index if found or -1 in case it cannot be found. + * @see fieldNameIndex For a more tolerant alternative. + */ + int indexFromName( const QString& fieldName ) const; - //! Look up field's index from name - //! also looks up case-insensitive if there is no match otherwise - //! @note added in 2.4 + /** + * Look up field's index from the field name. + * This method matches in the following order: + * + * 1. The exact field name taking case sensitivity into account + * 2. Looks for the field name by case insensitive comparison + * 3. The field alias (case insensitive) + * + * @param fieldName The name to look for. + * + * @return The field index if found or -1 in case it cannot be found. + * @see indexFromName For a more performant and precise but less tolerant alternative. + * @note added in 2.4 + */ int fieldNameIndex( const QString& fieldName ) const; //! Utility function to get list of attribute indexes diff --git a/tests/src/core/testqgsfields.cpp b/tests/src/core/testqgsfields.cpp index e205ede76ad2..221008715e18 100644 --- a/tests/src/core/testqgsfields.cpp +++ b/tests/src/core/testqgsfields.cpp @@ -330,6 +330,7 @@ void TestQgsFields::indexFromName() { QgsFields fields; QgsField field( QString( "testfield" ) ); + field.setAlias( "testfieldAlias" ); fields.append( field ); QgsField field2( QString( "testfield2" ) ); fields.append( field2 ); @@ -351,6 +352,11 @@ void TestQgsFields::indexFromName() QgsField sameNameDifferentCase( QString( "teStFielD" ) ); fields.append( sameNameDifferentCase ); QCOMPARE( fields.fieldNameIndex( QString( "teStFielD" ) ), 3 ); + + //test that the alias is only matched with fieldNameIndex + QCOMPARE( fields.indexFromName( "testfieldAlias" ), -1 ); + QCOMPARE( fields.fieldNameIndex( "testfieldAlias" ), 0 ); + QCOMPARE( fields.fieldNameIndex( "testfieldalias" ), 0 ); } void TestQgsFields::toList() From b6779f63ff9133a4eb3ac0c392f32f044551fc8c Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 22 Sep 2016 07:57:13 +0200 Subject: [PATCH 048/897] Rename QgsFields::fieldNameIndex() to lookupField() To have two clearly different names for tolerant/intolerant index lookup --- doc/api_break.dox | 2 + python/core/core.sip | 1 + python/core/qgsexpression.sip | 7 + python/core/qgsfield.sip | 221 ----------- python/core/qgsfields.sip | 239 ++++++++++++ python/core/qgsvectorlayer.sip | 3 - src/analysis/vector/qgsgeometryanalyzer.cpp | 2 +- src/analysis/vector/qgsoverlayanalyzer.cpp | 2 +- src/app/ogr/qgsvectorlayersaveasdialog.h | 2 +- src/app/qgisapp.cpp | 2 +- src/app/qgisappinterface.cpp | 2 +- src/app/qgsaddattrdialog.h | 2 +- src/app/qgsattributetabledialog.cpp | 6 +- src/app/qgsclipboard.cpp | 2 +- src/app/qgsclipboard.h | 2 +- src/app/qgsdelattrdialog.cpp | 2 +- src/app/qgsdiagramproperties.cpp | 4 +- src/app/qgsdxfexportdialog.cpp | 2 +- src/app/qgsfieldcalculator.h | 2 +- src/app/qgsfieldsproperties.cpp | 2 +- src/app/qgsidentifyresultsdialog.cpp | 2 +- src/app/qgsidentifyresultsdialog.h | 2 +- src/app/qgslabelpropertydialog.cpp | 4 +- src/app/qgsmaptooladdfeature.cpp | 2 +- src/app/qgsmaptoolfeatureaction.cpp | 2 +- src/app/qgsmaptoolidentifyaction.cpp | 2 +- src/app/qgsmaptoollabel.cpp | 12 +- src/app/qgsmergeattributesdialog.cpp | 2 +- src/app/qgsmergeattributesdialog.h | 2 +- src/app/qgsstatisticalsummarydockwidget.cpp | 2 +- src/core/CMakeLists.txt | 2 + src/core/composer/qgsatlascomposition.cpp | 2 +- .../composer/qgscomposerattributetablev2.cpp | 6 +- src/core/qgsaggregatecalculator.cpp | 2 +- src/core/qgsattributetableconfig.cpp | 4 +- src/core/qgsdatadefined.cpp | 2 +- src/core/qgsdiagramrenderer.h | 2 +- src/core/qgseditformconfig.cpp | 2 +- src/core/qgseditformconfig_p.h | 2 +- src/core/qgsexpression.cpp | 24 +- src/core/qgsexpression.h | 29 +- src/core/qgsexpressioncontext.cpp | 2 +- src/core/qgsexpressionfieldbuffer.h | 2 +- src/core/qgsfeature.cpp | 4 +- src/core/qgsfeature.h | 2 +- src/core/qgsfeature_p.h | 2 +- src/core/qgsfeaturerequest.cpp | 4 +- src/core/qgsfeaturestore.h | 2 +- src/core/qgsfield.cpp | 330 +---------------- src/core/qgsfield.h | 287 --------------- src/core/qgsfield_p.h | 33 -- src/core/qgsfields.cpp | 346 ++++++++++++++++++ src/core/qgsfields.h | 314 ++++++++++++++++ src/core/qgsfields_p.h | 67 ++++ src/core/qgsgml.h | 2 +- src/core/qgsgmlschema.h | 2 +- src/core/qgsjsonutils.h | 2 +- src/core/qgsogrutils.cpp | 2 +- src/core/qgspallabeling.h | 2 +- src/core/qgsrelation.cpp | 8 +- src/core/qgsrelation.h | 2 +- src/core/qgsrelationmanager.cpp | 2 +- src/core/qgssqlexpressioncompiler.h | 2 +- src/core/qgsvectordataprovider.cpp | 4 +- src/core/qgsvectorfilewriter.cpp | 6 +- src/core/qgsvectorfilewriter.h | 2 +- src/core/qgsvectorlayer.cpp | 101 +++-- src/core/qgsvectorlayer.h | 15 +- src/core/qgsvectorlayereditbuffer.cpp | 2 +- src/core/qgsvectorlayereditbuffer.h | 2 +- src/core/qgsvectorlayerfeatureiterator.cpp | 18 +- src/core/qgsvectorlayerfeatureiterator.h | 2 +- src/core/qgsvectorlayerimport.cpp | 2 +- src/core/qgsvectorlayerjoinbuffer.cpp | 2 +- src/core/qgsvectorlayerlabelprovider.cpp | 4 +- src/core/qgsvectorlayerrenderer.h | 2 +- src/core/qgsvectorlayerundocommand.h | 2 +- src/core/qgsvirtuallayerdefinition.h | 6 +- src/core/qgsvirtuallayerdefinitionutils.cpp | 2 +- src/core/raster/qgsrasterdataprovider.h | 2 +- .../qgscategorizedsymbolrenderer.cpp | 4 +- .../qgsgraduatedsymbolrenderer.cpp | 6 +- src/core/symbology-ng/qgsheatmaprenderer.cpp | 2 +- src/core/symbology-ng/qgsrenderer.h | 2 +- src/core/symbology-ng/qgsrulebasedrenderer.h | 2 +- src/core/symbology-ng/qgssymbol.h | 2 +- src/core/symbology-ng/qgssymbollayer.cpp | 2 +- src/core/symbology-ng/qgssymbollayer.h | 2 +- .../qgsvectorfieldsymbollayer.cpp | 4 +- .../qgsattributetablefiltermodel.cpp | 2 +- .../attributetable/qgsattributetablemodel.cpp | 8 +- src/gui/attributetable/qgsdualview.cpp | 2 +- .../qgsorganizetablecolumnsdialog.cpp | 4 +- .../core/qgseditorwidgetautoconf.cpp | 4 +- .../core/qgseditorwidgetfactory.cpp | 2 +- .../core/qgseditorwidgetregistry.cpp | 2 +- .../core/qgseditorwidgetwrapper.cpp | 2 +- .../core/qgssearchwidgetwrapper.cpp | 2 +- .../qgscheckboxsearchwidgetwrapper.cpp | 2 +- .../qgsdatetimesearchwidgetwrapper.cpp | 2 +- .../qgsdefaultsearchwidgetwrapper.cpp | 2 +- .../qgskeyvaluewidgetfactory.cpp | 2 +- .../editorwidgets/qgslistwidgetfactory.cpp | 2 +- .../editorwidgets/qgsmultiedittoolbutton.h | 2 +- .../qgsrelationreferenceconfigdlg.cpp | 2 +- .../qgsrelationreferencefactory.cpp | 4 +- ...gsrelationreferencesearchwidgetwrapper.cpp | 2 +- .../qgsrelationreferencewidget.cpp | 16 +- .../qgstexteditsearchwidgetwrapper.cpp | 2 +- src/gui/editorwidgets/qgstexteditwrapper.cpp | 2 +- .../qgsvaluemapsearchwidgetwrapper.cpp | 2 +- .../qgsvaluerelationsearchwidgetwrapper.cpp | 2 +- .../qgsvaluerelationwidgetwrapper.cpp | 6 +- src/gui/qgsattributeform.cpp | 6 +- src/gui/qgsexpressionbuilderwidget.cpp | 2 +- src/gui/qgsfieldmodel.h | 2 +- src/gui/qgsfieldvalidator.cpp | 2 +- src/gui/qgsfieldvalidator.h | 2 +- src/gui/qgsmaptoolidentify.cpp | 2 +- src/gui/qgsmaptoolidentify.h | 2 +- src/gui/qgsrelationeditorwidget.cpp | 4 +- src/gui/qgssearchquerybuilder.cpp | 2 +- .../qgscategorizedsymbolrendererwidget.cpp | 2 +- .../qgspointdisplacementrendererwidget.cpp | 2 +- .../evisgenericeventbrowsergui.cpp | 2 +- .../ui/qgsgeometrycheckerresulttab.cpp | 4 +- src/plugins/grass/qgsgrassmoduleoptions.h | 2 +- src/plugins/grass/qgsgrassmoduleparam.h | 2 +- .../interpolation/qgsinterpolationdialog.cpp | 2 +- .../roadgraph/linevectorlayerwidget.cpp | 2 +- src/plugins/roadgraph/roadgraphplugin.cpp | 4 +- src/providers/arcgisrest/qgsafsprovider.h | 2 +- .../arcgisrest/qgsarcgisrestutils.cpp | 2 +- src/providers/db2/qgsdb2featureiterator.cpp | 10 +- src/providers/db2/qgsdb2featureiterator.h | 2 +- src/providers/db2/qgsdb2provider.cpp | 4 +- src/providers/db2/qgsdb2provider.h | 2 +- .../qgsdelimitedtextfeatureiterator.cpp | 11 +- .../qgsdelimitedtextprovider.cpp | 2 +- .../delimitedtext/qgsdelimitedtextprovider.h | 2 +- src/providers/gpx/qgsgpxprovider.cpp | 2 +- src/providers/gpx/qgsgpxprovider.h | 2 +- src/providers/grass/qgsgrass.cpp | 2 +- src/providers/grass/qgsgrass.h | 2 +- src/providers/grass/qgsgrassprovider.cpp | 2 +- src/providers/grass/qgsgrassvector.h | 2 +- src/providers/grass/qgsgrassvectormaplayer.h | 2 +- .../memory/qgsmemoryfeatureiterator.h | 2 +- src/providers/memory/qgsmemoryprovider.cpp | 2 +- src/providers/memory/qgsmemoryprovider.h | 2 +- .../mssql/qgsmssqlfeatureiterator.cpp | 10 +- src/providers/mssql/qgsmssqlfeatureiterator.h | 2 +- src/providers/mssql/qgsmssqlprovider.cpp | 6 +- src/providers/mssql/qgsmssqlprovider.h | 2 +- src/providers/ogr/qgsogrfeatureiterator.cpp | 11 +- src/providers/ogr/qgsogrfeatureiterator.h | 2 +- src/providers/ogr/qgsogrprovider.cpp | 4 +- src/providers/oracle/qgsoracleconn.cpp | 2 +- src/providers/oracle/qgsoracleprovider.cpp | 2 +- src/providers/oracle/qgsoracleprovider.h | 2 +- src/providers/postgres/qgspostgresconn.cpp | 2 +- .../postgres/qgspostgresfeatureiterator.cpp | 11 +- src/providers/postgres/qgspostgresprovider.h | 2 +- .../qgsspatialitefeatureiterator.cpp | 11 +- .../spatialite/qgsspatialitefeatureiterator.h | 2 +- .../spatialite/qgsspatialiteprovider.cpp | 6 +- .../spatialite/qgsspatialiteprovider.h | 2 +- .../qgsvirtuallayerfeatureiterator.cpp | 2 +- src/providers/wfs/qgswfsprovider.cpp | 6 +- src/providers/wfs/qgswfsshareddata.cpp | 2 +- src/server/qgsserverprojectparser.cpp | 2 +- src/server/qgswfsserver.cpp | 10 +- src/server/qgswmsserver.cpp | 2 +- tests/src/core/testqgsexpression.cpp | 2 +- tests/src/core/testqgsfields.cpp | 16 +- tests/src/core/testqgsrulebasedrenderer.cpp | 2 +- .../src/core/testqgsvectorlayerjoinbuffer.cpp | 2 +- 177 files changed, 1324 insertions(+), 1217 deletions(-) create mode 100644 python/core/qgsfields.sip create mode 100644 src/core/qgsfields.cpp create mode 100644 src/core/qgsfields.h create mode 100644 src/core/qgsfields_p.h diff --git a/doc/api_break.dox b/doc/api_break.dox index 1392a289391d..94dfb2d4166c 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -746,6 +746,7 @@ None will need to be modified, as the method will return an empty geometry if th
      • All const methods which return a field from QgsFields now return a QgsField value, not a reference.
      • +
      • fieldNameIndex has been renamed to lookupField. See the API documentation for details.
      \subsection qgis_api_break_3_0_QgsFieldExpressionWidget QgsFieldExpressionWidget @@ -1414,6 +1415,7 @@ displayExpression instead. For the map tip use mapTipTemplate() instead.
    • Deleted attributeEditorElementFromDomElement
    • editFormConfig() returns a copy instead of direct access (Use setEditFormConfig to update)
    • Removed valueRelation(), replaced with QgsEditFormConfig::editorWidgetConfig +
    • Removed fieldNameIndex(), use QgsFields::lookupField() or QgsFields::indexFromName() instead
    \subsection qgis_api_break_3_0_QgsVectorLayerEditBuffer QgsVectorLayerEditBuffer diff --git a/python/core/core.sip b/python/core/core.sip index f7f9a1215a06..6aea0feb7802 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -55,6 +55,7 @@ %Include qgsfeaturerequest.sip %Include qgsfeedback.sip %Include qgsfield.sip +%Include qgsfields.sip %Include qgsgeometrysimplifier.sip %Include qgsgeometryvalidator.sip %Include qgsgml.sip diff --git a/python/core/qgsexpression.sip b/python/core/qgsexpression.sip index 2b49ab81fe7a..5000d37aee29 100644 --- a/python/core/qgsexpression.sip +++ b/python/core/qgsexpression.sip @@ -53,6 +53,13 @@ class QgsExpression */ QStringList referencedColumns() const; + /** + * Return a list of field name indexes obtained from the provided fields. + * + * @note Added in QGIS 3.0 + */ + QSet referencedAttributeIndexes( const QgsFields& fields ) const; + //! Returns true if the expression uses feature geometry for some computation bool needsGeometry() const; diff --git a/python/core/qgsfield.sip b/python/core/qgsfield.sip index b6f83442dfc4..5ac7bd39085e 100644 --- a/python/core/qgsfield.sip +++ b/python/core/qgsfield.sip @@ -254,224 +254,3 @@ class QgsField */ const QgsEditorWidgetSetup& editorWidgetSetup() const; }; // class QgsField - - -/** \class QgsFields - * \ingroup core - * Container of fields for a vector layer. - * - * In addition to storing a list of QgsField instances, it also: - * - allows quick lookups of field names to index in the list - * - keeps track of where the field definition comes from (vector data provider, joined layer or newly added from an editing operation) - * \note QgsFields objects are implicitly shared. - */ - -class QgsFields -{ -%TypeHeaderCode -#include -%End - public: - - enum FieldOrigin - { - OriginUnknown, //!< it has not been specified where the field comes from - OriginProvider, //!< field comes from the underlying data provider of the vector layer (originIndex = index in provider's fields) - OriginJoin, //!< field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join) - OriginEdit, //!< field has been temporarily added in editing mode (originIndex = index in the list of added attributes) - OriginExpression //!< field is calculated from an expression - }; - - /** Constructor for an empty field container - */ - QgsFields(); - - /** Copy constructor - */ - QgsFields( const QgsFields& other ); - - virtual ~QgsFields(); - - //! Remove all fields - void clear(); - //! Append a field. The field must have unique name, otherwise it is rejected (returns false) - bool append( const QgsField& field, FieldOrigin origin = OriginProvider, int originIndex = -1 ); - //! Append an expression field. The field must have unique name, otherwise it is rejected (returns false) - bool appendExpressionField( const QgsField& field, int originIndex ); - //! Remove a field with the given index - void remove( int fieldIdx ); -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->count() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipCpp->remove( a0 ); - } -%End - - //! Extend with fields from another QgsFields container - void extend( const QgsFields& other ); - - //! Check whether the container is empty - bool isEmpty() const; - //! Return number of items - int count() const; - // __len__ annotation since sip 4.10.3 - //int count() const /__len__/; - int __len__() const; -%MethodCode - sipRes = sipCpp->count(); -%End - //! Return number of items - int size() const; - //! Return if a field index is valid - //! @param i Index of the field which needs to be checked - //! @return True if the field exists - bool exists( int i ) const; - - //! Get field at particular index (must be in range 0..N-1) - // const QgsField& operator[]( int i ) const; - QgsField& operator[](int i) /Factory/; -%MethodCode - SIP_SSIZE_T idx = sipConvertFromSequenceIndex(a0, sipCpp->count()); - if (idx < 0) - sipIsErr = 1; - else - sipRes = new QgsField(sipCpp->operator[](idx)); -%End - - //! Get field at particular index (must be in range 0..N-1) - QgsField at( int i ) const /Factory/; -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->count() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = new QgsField( sipCpp->at( a0 ) ); - } -%End - - //! Get field at particular index (must be in range 0..N-1) - QgsField field( int fieldIdx ) const /Factory/; -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->count() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = new QgsField( sipCpp->field( a0 ) ); - } -%End - - //! Get field at particular index (must be in range 0..N-1) - QgsField field( const QString& name ) const /Factory/; -%MethodCode - int fieldIdx = sipCpp->indexFromName(*a0); - if (fieldIdx == -1) - { - PyErr_SetString(PyExc_KeyError, a0->toAscii()); - sipIsErr = 1; - } - else - { - sipRes = new QgsField( sipCpp->field( *a0 ) ); - } -%End - - //! Get field's origin (value from an enumeration) - FieldOrigin fieldOrigin( int fieldIdx ) const; -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->count() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = sipCpp->fieldOrigin( a0 ); - } -%End - - //! Get field's origin index (its meaning is specific to each type of origin) - int fieldOriginIndex( int fieldIdx ) const; -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->count() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = sipCpp->fieldOriginIndex( a0 ); - } -%End - - //! Look up field's index from name. Returns -1 on error - int indexFromName( const QString& name ) const; - - //! Look up field's index from name - //! also looks up case-insensitive if there is no match otherwise - //! @note added in 2.4 - int fieldNameIndex( const QString& fieldName ) const; - - //! Utility function to get list of attribute indexes - //! @note added in 2.4 - QgsAttributeList allAttributesList() const; - - //! Utility function to return a list of QgsField instances - QList toList() const; - - //! @note added in 2.6 - bool operator==( const QgsFields& other ) const; - //! @note added in 2.6 - bool operator!=( const QgsFields& other ) const; - - /** Returns an icon corresponding to a field index, based on the field's type and source - * @note added in QGIS 2.14 - */ - QIcon iconForField( int fieldIdx ) const /Factory/; - %MethodCode - if ( a0 < 0 || a0 >= sipCpp->count() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = new QIcon( sipCpp->iconForField( a0 ) ); - } - %End - - //! Allows direct construction of QVariants from fields. - operator QVariant() const; - -/* SIP_PYOBJECT __getitem__(int key); -%MethodCode - if (a0 = sipConvertFromSequenceIndex(a0, sipCpp->count()) < 0) - sipIsErr = 1; - else - { - qDebug("__getitem__ %d", a0); - QgsField* fld = new QgsField(sipCpp->at(a0)); - sipRes = sipConvertFromType(fld, sipType_QgsField, Py_None); - } -%End*/ - -void __setitem__(int key, const QgsField& field); -%MethodCode - int idx = (int)sipConvertFromSequenceIndex(a0, sipCpp->count()); - if (idx < 0) - sipIsErr = 1; - else - (*sipCpp)[idx] = *a1; -%End - -}; diff --git a/python/core/qgsfields.sip b/python/core/qgsfields.sip new file mode 100644 index 000000000000..e5bfd8f89dde --- /dev/null +++ b/python/core/qgsfields.sip @@ -0,0 +1,239 @@ +/** \class QgsFields + * \ingroup core + * Container of fields for a vector layer. + * + * In addition to storing a list of QgsField instances, it also: + * - allows quick lookups of field names to index in the list + * - keeps track of where the field definition comes from (vector data provider, joined layer or newly added from an editing operation) + * \note QgsFields objects are implicitly shared. + */ + +class QgsFields +{ +%TypeHeaderCode +#include +%End + public: + + enum FieldOrigin + { + OriginUnknown, //!< it has not been specified where the field comes from + OriginProvider, //!< field comes from the underlying data provider of the vector layer (originIndex = index in provider's fields) + OriginJoin, //!< field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join) + OriginEdit, //!< field has been temporarily added in editing mode (originIndex = index in the list of added attributes) + OriginExpression //!< field is calculated from an expression + }; + + /** Constructor for an empty field container + */ + QgsFields(); + + /** Copy constructor + */ + QgsFields( const QgsFields& other ); + + virtual ~QgsFields(); + + //! Remove all fields + void clear(); + //! Append a field. The field must have unique name, otherwise it is rejected (returns false) + bool append( const QgsField& field, FieldOrigin origin = OriginProvider, int originIndex = -1 ); + //! Append an expression field. The field must have unique name, otherwise it is rejected (returns false) + bool appendExpressionField( const QgsField& field, int originIndex ); + //! Remove a field with the given index + void remove( int fieldIdx ); +%MethodCode + if ( a0 < 0 || a0 >= sipCpp->count() ) + { + PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); + sipIsErr = 1; + } + else + { + sipCpp->remove( a0 ); + } +%End + + //! Extend with fields from another QgsFields container + void extend( const QgsFields& other ); + + //! Check whether the container is empty + bool isEmpty() const; + //! Return number of items + int count() const; + // __len__ annotation since sip 4.10.3 + //int count() const /__len__/; + int __len__() const; +%MethodCode + sipRes = sipCpp->count(); +%End + //! Return number of items + int size() const; + //! Return if a field index is valid + //! @param i Index of the field which needs to be checked + //! @return True if the field exists + bool exists( int i ) const; + + //! Get field at particular index (must be in range 0..N-1) + // const QgsField& operator[]( int i ) const; + QgsField& operator[](int i) /Factory/; +%MethodCode + SIP_SSIZE_T idx = sipConvertFromSequenceIndex(a0, sipCpp->count()); + if (idx < 0) + sipIsErr = 1; + else + sipRes = new QgsField(sipCpp->operator[](idx)); +%End + + //! Get field at particular index (must be in range 0..N-1) + QgsField at( int i ) const /Factory/; +%MethodCode + if ( a0 < 0 || a0 >= sipCpp->count() ) + { + PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); + sipIsErr = 1; + } + else + { + sipRes = new QgsField( sipCpp->at( a0 ) ); + } +%End + + //! Get field at particular index (must be in range 0..N-1) + QgsField field( int fieldIdx ) const /Factory/; +%MethodCode + if ( a0 < 0 || a0 >= sipCpp->count() ) + { + PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); + sipIsErr = 1; + } + else + { + sipRes = new QgsField( sipCpp->field( a0 ) ); + } +%End + + //! Get field at particular index (must be in range 0..N-1) + QgsField field( const QString& name ) const /Factory/; +%MethodCode + int fieldIdx = sipCpp->indexFromName(*a0); + if (fieldIdx == -1) + { + PyErr_SetString(PyExc_KeyError, a0->toAscii()); + sipIsErr = 1; + } + else + { + sipRes = new QgsField( sipCpp->field( *a0 ) ); + } +%End + + //! Get field's origin (value from an enumeration) + FieldOrigin fieldOrigin( int fieldIdx ) const; +%MethodCode + if ( a0 < 0 || a0 >= sipCpp->count() ) + { + PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); + sipIsErr = 1; + } + else + { + sipRes = sipCpp->fieldOrigin( a0 ); + } +%End + + //! Get field's origin index (its meaning is specific to each type of origin) + int fieldOriginIndex( int fieldIdx ) const; +%MethodCode + if ( a0 < 0 || a0 >= sipCpp->count() ) + { + PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); + sipIsErr = 1; + } + else + { + sipRes = sipCpp->fieldOriginIndex( a0 ); + } +%End + + /** + * Look up field's index from the field name. + * This method takes is case sensitive and only matches the data source + * name of the field. + * + * @param fieldName The name of the field. + * + * @return The field index if found or -1 in case it cannot be found. + * @see lookupField For a more tolerant alternative. + */ + int indexFromName( const QString& fieldName ) const; + + /** + * Look up field's index from the field name. + * This method matches in the following order: + * + * 1. The exact field name taking case sensitivity into account + * 2. Looks for the field name by case insensitive comparison + * 3. The field alias (case insensitive) + * + * @param fieldName The name to look for. + * + * @return The field index if found or -1 in case it cannot be found. + * @see indexFromName For a more performant and precise but less tolerant alternative. + * @note added in 2.4 + */ + int lookupField( const QString& fieldName ) const; + + //! Utility function to get list of attribute indexes + //! @note added in 2.4 + QgsAttributeList allAttributesList() const; + + //! Utility function to return a list of QgsField instances + QList toList() const; + + //! @note added in 2.6 + bool operator==( const QgsFields& other ) const; + //! @note added in 2.6 + bool operator!=( const QgsFields& other ) const; + + /** Returns an icon corresponding to a field index, based on the field's type and source + * @note added in QGIS 2.14 + */ + QIcon iconForField( int fieldIdx ) const /Factory/; + %MethodCode + if ( a0 < 0 || a0 >= sipCpp->count() ) + { + PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); + sipIsErr = 1; + } + else + { + sipRes = new QIcon( sipCpp->iconForField( a0 ) ); + } + %End + + //! Allows direct construction of QVariants from fields. + operator QVariant() const; + +/* SIP_PYOBJECT __getitem__(int key); +%MethodCode + if (a0 = sipConvertFromSequenceIndex(a0, sipCpp->count()) < 0) + sipIsErr = 1; + else + { + qDebug("__getitem__ %d", a0); + QgsField* fld = new QgsField(sipCpp->at(a0)); + sipRes = sipConvertFromType(fld, sipType_QgsField, Py_None); + } +%End*/ + +void __setitem__(int key, const QgsField& field); +%MethodCode + int idx = (int)sipConvertFromSequenceIndex(a0, sipCpp->count()); + if (idx < 0) + sipIsErr = 1; + else + (*sipCpp)[idx] = *a1; +%End + +}; diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index f68bd6184ef9..dfd86db5d44f 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1190,9 +1190,6 @@ class QgsVectorLayer : QgsMapLayer /** Destroy active command and reverts all changes in it */ void destroyEditCommand(); - /** Returns the index of a field name or -1 if the field does not exist */ - int fieldNameIndex( const QString& fieldName ) const; - /** Editing vertex markers */ enum VertexMarkerType { diff --git a/src/analysis/vector/qgsgeometryanalyzer.cpp b/src/analysis/vector/qgsgeometryanalyzer.cpp index 31d73d814921..5f89c48747b1 100644 --- a/src/analysis/vector/qgsgeometryanalyzer.cpp +++ b/src/analysis/vector/qgsgeometryanalyzer.cpp @@ -18,7 +18,7 @@ #include "qgsgeometryanalyzer.h" #include "qgsapplication.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" #include "qgsfeatureiterator.h" #include "qgslogger.h" diff --git a/src/analysis/vector/qgsoverlayanalyzer.cpp b/src/analysis/vector/qgsoverlayanalyzer.cpp index f0bf0ffc528e..87408580965d 100644 --- a/src/analysis/vector/qgsoverlayanalyzer.cpp +++ b/src/analysis/vector/qgsoverlayanalyzer.cpp @@ -19,7 +19,7 @@ #include "qgsapplication.h" #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" #include "qgsgeometry.h" #include "qgslogger.h" diff --git a/src/app/ogr/qgsvectorlayersaveasdialog.h b/src/app/ogr/qgsvectorlayersaveasdialog.h index 9e4231c777ba..23bd037a7e4f 100644 --- a/src/app/ogr/qgsvectorlayersaveasdialog.h +++ b/src/app/ogr/qgsvectorlayersaveasdialog.h @@ -21,7 +21,7 @@ #include #include #include "qgscontexthelp.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorfilewriter.h" class QgsVectorLayer; diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 5a48125514db..273eb8c8bc25 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -7328,7 +7328,7 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) QgsAttributeList pkAttrList = pasteVectorLayer->pkAttributeList(); for ( int idx = 0; idx < fields.count(); ++idx ) { - int dst = pasteVectorLayer->fieldNameIndex( fields.at( idx ).name() ); + int dst = pasteVectorLayer->fields().lookupField( fields.at( idx ).name() ); if ( dst < 0 ) continue; diff --git a/src/app/qgisappinterface.cpp b/src/app/qgisappinterface.cpp index 2b18ca257ce4..c6bf04add48d 100644 --- a/src/app/qgisappinterface.cpp +++ b/src/app/qgisappinterface.cpp @@ -38,7 +38,7 @@ #include "qgslayertreeview.h" #include "qgsshortcutsmanager.h" #include "qgsattributedialog.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectordataprovider.h" #include "qgsfeatureaction.h" #include "qgsactionmanager.h" diff --git a/src/app/qgsaddattrdialog.h b/src/app/qgsaddattrdialog.h index 96802fb6d59d..5d26b8ca7180 100644 --- a/src/app/qgsaddattrdialog.h +++ b/src/app/qgsaddattrdialog.h @@ -20,7 +20,7 @@ #include "ui_qgsaddattrdialogbase.h" #include "qgisgui.h" -#include "qgsfield.h" +#include "qgsfields.h" class QgsVectorLayer; diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index a321a14d891a..4719b2652541 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -46,7 +46,7 @@ #include "qgsexpressionselectiondialog.h" #include "qgsfeaturelistmodel.h" #include "qgsrubberband.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgseditorwidgetregistry.h" #include "qgsfieldproxymodel.h" @@ -387,7 +387,7 @@ void QgsAttributeTableDialog::columnBoxInit() Q_FOREACH ( const QgsField& field, fields ) { - int idx = mLayer->fieldNameIndex( field.name() ); + int idx = mLayer->fields().lookupField( field.name() ); if ( idx < 0 ) continue; @@ -524,7 +524,7 @@ void QgsAttributeTableDialog::filterColumnChanged( QObject* filterAction ) } QString fieldName = mFilterButton->defaultAction()->data().toString(); // get the search widget - int fldIdx = mLayer->fieldNameIndex( fieldName ); + int fldIdx = mLayer->fields().lookupField( fieldName ); if ( fldIdx < 0 ) return; const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( mLayer, fieldName ); diff --git a/src/app/qgsclipboard.cpp b/src/app/qgsclipboard.cpp index 3e492801f433..d53fe18a9586 100644 --- a/src/app/qgsclipboard.cpp +++ b/src/app/qgsclipboard.cpp @@ -29,7 +29,7 @@ #include "qgsclipboard.h" #include "qgsfeature.h" #include "qgsfeaturestore.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgscoordinatereferencesystem.h" #include "qgslogger.h" diff --git a/src/app/qgsclipboard.h b/src/app/qgsclipboard.h index 1e9e03dcae82..acd8cbc49251 100644 --- a/src/app/qgsclipboard.h +++ b/src/app/qgsclipboard.h @@ -22,7 +22,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" #include "qgscoordinatereferencesystem.h" diff --git a/src/app/qgsdelattrdialog.cpp b/src/app/qgsdelattrdialog.cpp index 82b021539b3c..4256632bdbb3 100644 --- a/src/app/qgsdelattrdialog.cpp +++ b/src/app/qgsdelattrdialog.cpp @@ -17,7 +17,7 @@ #include "qgsapplication.h" #include "qgsdelattrdialog.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectordataprovider.h" #include "qgsvectorlayer.h" diff --git a/src/app/qgsdiagramproperties.cpp b/src/app/qgsdiagramproperties.cpp index cf9484a707be..350e594aad47 100644 --- a/src/app/qgsdiagramproperties.cpp +++ b/src/app/qgsdiagramproperties.cpp @@ -588,7 +588,7 @@ void QgsDiagramProperties::on_mFindMaximumValueButton_clicked() } else { - int attributeNumber = mLayer->fields().fieldNameIndex( sizeFieldNameOrExp ); + int attributeNumber = mLayer->fields().lookupField( sizeFieldNameOrExp ); maxValue = mLayer->maximumValue( attributeNumber ).toFloat(); } @@ -776,7 +776,7 @@ void QgsDiagramProperties::apply() } else { - int attributeNumber = mLayer->fields().fieldNameIndex( sizeFieldNameOrExp ); + int attributeNumber = mLayer->fields().lookupField( sizeFieldNameOrExp ); dr->setClassificationAttribute( attributeNumber ); } dr->setDiagramSettings( ds ); diff --git a/src/app/qgsdxfexportdialog.cpp b/src/app/qgsdxfexportdialog.cpp index 0154217986d0..f1a0f90f94c3 100644 --- a/src/app/qgsdxfexportdialog.cpp +++ b/src/app/qgsdxfexportdialog.cpp @@ -91,7 +91,7 @@ void FieldSelectorDelegate::setModelData( QWidget *editor, QAbstractItemModel *m if ( !fcb ) return; - model->setData( index, vl->fieldNameIndex( fcb->currentField() ) ); + model->setData( index, vl->fields().lookupField( fcb->currentField() ) ); } QgsVectorLayerAndAttributeModel::QgsVectorLayerAndAttributeModel( QgsLayerTreeGroup* rootNode, QObject *parent ) diff --git a/src/app/qgsfieldcalculator.h b/src/app/qgsfieldcalculator.h index 86ed24ef4fb0..b8b4f27923c6 100644 --- a/src/app/qgsfieldcalculator.h +++ b/src/app/qgsfieldcalculator.h @@ -18,7 +18,7 @@ #include "ui_qgsfieldcalculatorbase.h" #include "qgscontexthelp.h" -#include "qgsfield.h" +#include "qgsfields.h" class QgsVectorLayer; diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index f21981c3cc92..db3ae02d635f 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -855,7 +855,7 @@ QgsAttributeEditorElement* QgsFieldsProperties::createAttributeEditorWidget( QTr { case DesignerTreeItemData::Field: { - int idx = mLayer->fieldNameIndex( itemData.name() ); + int idx = mLayer->fields().lookupField( itemData.name() ); widgetDef = new QgsAttributeEditorField( itemData.name(), idx, parent ); break; } diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index 04ed3dece02f..5d1e846cb232 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -681,7 +681,7 @@ QString QgsIdentifyResultsDialog::representValue( QgsVectorLayer* vlayer, const QgsEditorWidgetFactory* factory = QgsEditorWidgetRegistry::instance()->factory( setup.type() ); - int idx = vlayer->fieldNameIndex( fieldName ); + int idx = vlayer->fields().lookupField( fieldName ); if ( !factory ) return value.toString(); diff --git a/src/app/qgsidentifyresultsdialog.h b/src/app/qgsidentifyresultsdialog.h index 5a6baff09a2d..52c5d718adf3 100644 --- a/src/app/qgsidentifyresultsdialog.h +++ b/src/app/qgsidentifyresultsdialog.h @@ -21,7 +21,7 @@ #include "ui_qgsidentifyresultsbase.h" #include "qgscontexthelp.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgscoordinatereferencesystem.h" #include "qgsmaptoolidentify.h" #include "qgswebview.h" diff --git a/src/app/qgslabelpropertydialog.cpp b/src/app/qgslabelpropertydialog.cpp index a57ca2be05b0..8b8c7ccd80df 100644 --- a/src/app/qgslabelpropertydialog.cpp +++ b/src/app/qgslabelpropertydialog.cpp @@ -98,7 +98,7 @@ void QgsLabelPropertyDialog::init( const QString& layerId, const QString& provid QString labelFieldName = vlayer->customProperty( "labeling/fieldName" ).toString(); if ( !labelFieldName.isEmpty() ) { - mCurLabelField = vlayer->fieldNameIndex( labelFieldName ); + mCurLabelField = vlayer->fields().lookupField( labelFieldName ); if ( mCurLabelField >= 0 ) { mLabelTextLineEdit->setText( attributeValues.at( mCurLabelField ).toString() ); @@ -373,7 +373,7 @@ void QgsLabelPropertyDialog::enableDataDefinedWidgets( QgsVectorLayer* vlayer ) continue; // can only modify attributes with an active data definition of a mapped field } - int ddIndx = vlayer->fieldNameIndex( ddField ); + int ddIndx = vlayer->fields().lookupField( ddField ); if ( ddIndx == -1 ) { continue; diff --git a/src/app/qgsmaptooladdfeature.cpp b/src/app/qgsmaptooladdfeature.cpp index 44cb915492b7..38bfa995a2cc 100644 --- a/src/app/qgsmaptooladdfeature.cpp +++ b/src/app/qgsmaptooladdfeature.cpp @@ -18,7 +18,7 @@ #include "qgsattributedialog.h" #include "qgscsexception.h" #include "qgscurvepolygon.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslinestring.h" #include "qgsmultipoint.h" diff --git a/src/app/qgsmaptoolfeatureaction.cpp b/src/app/qgsmaptoolfeatureaction.cpp index 49fcac42e264..11b766a2f9a1 100644 --- a/src/app/qgsmaptoolfeatureaction.cpp +++ b/src/app/qgsmaptoolfeatureaction.cpp @@ -17,7 +17,7 @@ #include "qgsfeature.h" #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsmapcanvas.h" diff --git a/src/app/qgsmaptoolidentifyaction.cpp b/src/app/qgsmaptoolidentifyaction.cpp index 8a4f46b06064..9e09c83d644a 100644 --- a/src/app/qgsmaptoolidentifyaction.cpp +++ b/src/app/qgsmaptoolidentifyaction.cpp @@ -20,7 +20,7 @@ #include "qgsdistancearea.h" #include "qgsfeature.h" #include "qgsfeaturestore.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsidentifyresultsdialog.h" diff --git a/src/app/qgsmaptoollabel.cpp b/src/app/qgsmaptoollabel.cpp index 2f3597c9451b..0e2db43b5a00 100644 --- a/src/app/qgsmaptoollabel.cpp +++ b/src/app/qgsmaptoollabel.cpp @@ -162,7 +162,7 @@ QString QgsMapToolLabel::currentLabelText( int trunc ) QString labelField = vlayer->customProperty( "labeling/fieldName" ).toString(); if ( !labelField.isEmpty() ) { - int labelFieldId = vlayer->fieldNameIndex( labelField ); + int labelFieldId = vlayer->fields().lookupField( labelField ); QgsFeature f; if ( vlayer->getFeatures( QgsFeatureRequest().setFilterFid( mCurrentLabel.pos.featureId ).setFlags( QgsFeatureRequest::NoGeometry ) ).nextFeature( f ) ) { @@ -434,7 +434,7 @@ int QgsMapToolLabel::dataDefinedColumnIndex( QgsPalLayerSettings::DataDefinedPro { QString fieldname = dataDefinedColumnName( p, labelSettings ); if ( !fieldname.isEmpty() ) - return vlayer->fieldNameIndex( fieldname ); + return vlayer->fields().lookupField( fieldname ); return -1; } @@ -497,7 +497,7 @@ bool QgsMapToolLabel::layerIsRotatable( QgsVectorLayer* vlayer, int& rotationCol bool QgsMapToolLabel::labelIsRotatable( QgsVectorLayer* layer, const QgsPalLayerSettings& settings, int& rotationCol ) const { QString rColName = dataDefinedColumnName( QgsPalLayerSettings::Rotation, settings ); - rotationCol = layer->fieldNameIndex( rColName ); + rotationCol = layer->fields().lookupField( rColName ); return rotationCol != -1; } @@ -606,8 +606,8 @@ bool QgsMapToolLabel::labelMoveable( QgsVectorLayer* vlayer, const QgsPalLayerSe QString xColName = dataDefinedColumnName( QgsPalLayerSettings::PositionX, settings ); QString yColName = dataDefinedColumnName( QgsPalLayerSettings::PositionY, settings ); //return !xColName.isEmpty() && !yColName.isEmpty(); - xCol = vlayer->fieldNameIndex( xColName ); - yCol = vlayer->fieldNameIndex( yColName ); + xCol = vlayer->fields().lookupField( xColName ); + yCol = vlayer->fields().lookupField( yColName ); return ( xCol != -1 && yCol != -1 ); } @@ -629,7 +629,7 @@ bool QgsMapToolLabel::labelCanShowHide( QgsVectorLayer* vlayer, int& showCol ) c { QString fieldname = dataDefinedColumnName( QgsPalLayerSettings::Show, vlayer->labeling()->settings( vlayer, providerId ) ); - showCol = vlayer->fieldNameIndex( fieldname ); + showCol = vlayer->fields().lookupField( fieldname ); if ( showCol != -1 ) return true; } diff --git a/src/app/qgsmergeattributesdialog.cpp b/src/app/qgsmergeattributesdialog.cpp index 4ca006375375..4731eac47a8e 100644 --- a/src/app/qgsmergeattributesdialog.cpp +++ b/src/app/qgsmergeattributesdialog.cpp @@ -21,7 +21,7 @@ #include "qgsapplication.h" #include "qgseditorwidgetwrapper.h" #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsmapcanvas.h" #include "qgsrubberband.h" #include "qgsvectorlayer.h" diff --git a/src/app/qgsmergeattributesdialog.h b/src/app/qgsmergeattributesdialog.h index 780416dd4c0a..20e7243328c9 100644 --- a/src/app/qgsmergeattributesdialog.h +++ b/src/app/qgsmergeattributesdialog.h @@ -22,7 +22,7 @@ #include "ui_qgsmergeattributesdialogbase.h" #include "qgsfeature.h" #include "qgsstatisticalsummary.h" -#include "qgsfield.h" +#include "qgsfields.h" class QgsMapCanvas; class QgsRubberBand; diff --git a/src/app/qgsstatisticalsummarydockwidget.cpp b/src/app/qgsstatisticalsummarydockwidget.cpp index 0dd154204259..0230b78b67cf 100644 --- a/src/app/qgsstatisticalsummarydockwidget.cpp +++ b/src/app/qgsstatisticalsummarydockwidget.cpp @@ -134,7 +134,7 @@ void QgsStatisticalSummaryDockWidget::refreshStatistics() if ( !mFieldExpressionWidget->isExpression() ) { QString field = mFieldExpressionWidget->currentField(); - fieldType = mLayer->fields().field( mLayer->fields().fieldNameIndex( field ) ).type(); + fieldType = mLayer->fields().field( mLayer->fields().lookupField( field ) ).type(); if ( fieldType == QVariant::String || fieldType == QVariant::Date || fieldType == QVariant::DateTime ) { isNumeric = false; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 71df5008a935..44d48f8ec792 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -122,6 +122,7 @@ SET(QGIS_CORE_SRCS qgsfeaturerequest.cpp qgsfeaturestore.cpp qgsfield.cpp + qgsfields.cpp qgsfontutils.cpp qgsgeometrycache.cpp qgsgeometrysimplifier.cpp @@ -637,6 +638,7 @@ SET(QGIS_CORE_HDRS qgsfeatureiterator.h qgsfeaturerequest.h qgsfeaturestore.h + qgsfields.h qgsfontutils.h qgsgeometrycache.h qgshistogram.h diff --git a/src/core/composer/qgsatlascomposition.cpp b/src/core/composer/qgsatlascomposition.cpp index aed44218ee00..1cea67e96db0 100644 --- a/src/core/composer/qgsatlascomposition.cpp +++ b/src/core/composer/qgsatlascomposition.cpp @@ -178,7 +178,7 @@ int QgsAtlasComposition::updateFeatures() QgsFeature feat; mFeatureIds.clear(); mFeatureKeys.clear(); - int sortIdx = mCoverageLayer->fieldNameIndex( mSortKeyAttributeName ); + int sortIdx = mCoverageLayer->fields().lookupField( mSortKeyAttributeName ); while ( fit.nextFeature( feat ) ) { diff --git a/src/core/composer/qgscomposerattributetablev2.cpp b/src/core/composer/qgscomposerattributetablev2.cpp index 99bd0ceb8da4..a8062962dc45 100644 --- a/src/core/composer/qgscomposerattributetablev2.cpp +++ b/src/core/composer/qgscomposerattributetablev2.cpp @@ -330,7 +330,7 @@ void QgsComposerAttributeTableV2::setDisplayedFields( const QStringList& fields, { Q_FOREACH ( const QString& field, fields ) { - int attrIdx = layerFields.fieldNameIndex( field ); + int attrIdx = layerFields.lookupField( field ); if ( attrIdx < 0 ) continue; @@ -373,7 +373,7 @@ void QgsComposerAttributeTableV2::restoreFieldAliasMap( const QMap QList::const_iterator columnIt = mColumns.constBegin(); for ( ; columnIt != mColumns.constEnd(); ++columnIt ) { - int attrIdx = source->fieldNameIndex(( *columnIt )->attribute() ); + int attrIdx = source->fields().lookupField(( *columnIt )->attribute() ); if ( map.contains( attrIdx ) ) { ( *columnIt )->setHeading( map.value( attrIdx ) ); @@ -499,7 +499,7 @@ bool QgsComposerAttributeTableV2::getTableContents( QgsComposerTableContents &co QList::const_iterator columnIt = mColumns.constBegin(); for ( ; columnIt != mColumns.constEnd(); ++columnIt ) { - int idx = layer->fieldNameIndex(( *columnIt )->attribute() ); + int idx = layer->fields().lookupField(( *columnIt )->attribute() ); if ( idx != -1 ) { currentRow << replaceWrapChar( f.attributes().at( idx ) ); diff --git a/src/core/qgsaggregatecalculator.cpp b/src/core/qgsaggregatecalculator.cpp index 79dee82337d3..46b16b377e26 100644 --- a/src/core/qgsaggregatecalculator.cpp +++ b/src/core/qgsaggregatecalculator.cpp @@ -56,7 +56,7 @@ QVariant QgsAggregateCalculator::calculate( QgsAggregateCalculator::Aggregate ag QScopedPointer expression; - int attrNum = mLayer->fieldNameIndex( fieldOrExpression ); + int attrNum = mLayer->fields().lookupField( fieldOrExpression ); if ( attrNum == -1 ) { diff --git a/src/core/qgsattributetableconfig.cpp b/src/core/qgsattributetableconfig.cpp index 5163aadf82ce..4ccd15d54718 100644 --- a/src/core/qgsattributetableconfig.cpp +++ b/src/core/qgsattributetableconfig.cpp @@ -14,7 +14,7 @@ * * ***************************************************************************/ #include "qgsattributetableconfig.h" -#include "qgsfield.h" +#include "qgsfields.h" #include QgsAttributeTableConfig::QgsAttributeTableConfig() @@ -65,7 +65,7 @@ void QgsAttributeTableConfig::update( const QgsFields& fields ) const ColumnConfig& column = mColumns.at( i ); if ( column.type == Field ) { - if ( fields.fieldNameIndex( column.name ) == -1 ) + if ( fields.lookupField( column.name ) == -1 ) { mColumns.remove( i ); } diff --git a/src/core/qgsdatadefined.cpp b/src/core/qgsdatadefined.cpp index 9612018035b6..c09d0c3fdd75 100644 --- a/src/core/qgsdatadefined.cpp +++ b/src/core/qgsdatadefined.cpp @@ -18,7 +18,7 @@ #include "qgslogger.h" #include "qgsexpression.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorlayer.h" QgsDataDefined::QgsDataDefined( bool active, diff --git a/src/core/qgsdiagramrenderer.h b/src/core/qgsdiagramrenderer.h index 4f963041fba3..185f3d0e0d79 100644 --- a/src/core/qgsdiagramrenderer.h +++ b/src/core/qgsdiagramrenderer.h @@ -23,7 +23,7 @@ #include #include "qgsexpressioncontext.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgscoordinatetransform.h" #include "qgssymbol.h" diff --git a/src/core/qgseditformconfig.cpp b/src/core/qgseditformconfig.cpp index 94d89d1d5d0f..42a4a8f09ab9 100644 --- a/src/core/qgseditformconfig.cpp +++ b/src/core/qgseditformconfig.cpp @@ -597,7 +597,7 @@ QgsAttributeEditorElement* QgsEditFormConfig::attributeEditorElementFromDomEleme else if ( elem.tagName() == "attributeEditorField" ) { QString name = elem.attribute( "name" ); - int idx = d->mFields.fieldNameIndex( name ); + int idx = d->mFields.lookupField( name ); newElement = new QgsAttributeEditorField( name, idx, parent ); } else if ( elem.tagName() == "attributeEditorRelation" ) diff --git a/src/core/qgseditformconfig_p.h b/src/core/qgseditformconfig_p.h index dd2426a84f72..6ba11a173fa6 100644 --- a/src/core/qgseditformconfig_p.h +++ b/src/core/qgseditformconfig_p.h @@ -18,7 +18,7 @@ #include -#include "qgsfield.h" +#include "qgsfields.h" #include "qgseditformconfig.h" /// @cond PRIVATE diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index fd10ebc37dce..6be741bf2aec 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3086,7 +3086,7 @@ static QVariant fcnGetFeature( const QVariantList& values, const QgsExpressionCo } QString attribute = getStringValue( values.at( 1 ), parent ); - int attributeId = vl->fieldNameIndex( attribute ); + int attributeId = vl->fields().lookupField( attribute ); if ( attributeId == -1 ) { return QVariant(); @@ -3824,6 +3824,24 @@ QStringList QgsExpression::referencedColumns() const return columns; } +QSet QgsExpression::referencedAttributeIndexes( const QgsFields& fields ) const +{ + QStringList referencedFields = d->mRootNode->referencedColumns(); + QSet referencedIndexes; + + Q_FOREACH ( const QString& fieldName, referencedFields ) + { + if ( fieldName == QgsFeatureRequest::AllAttributes ) + { + referencedIndexes = fields.allAttributesList().toSet(); + break; + } + referencedIndexes << fields.lookupField( fieldName ); + } + + return referencedIndexes; +} + bool QgsExpression::needsGeometry() const { if ( !d->mRootNode ) @@ -4807,7 +4825,7 @@ QVariant QgsExpression::NodeColumnRef::eval( QgsExpression *parent, const QgsExp if ( context && context->hasVariable( QgsExpressionContext::EXPR_FIELDS ) ) { QgsFields fields = qvariant_cast( context->variable( QgsExpressionContext::EXPR_FIELDS ) ); - index = fields.fieldNameIndex( mName ); + index = fields.lookupField( mName ); } } @@ -4829,7 +4847,7 @@ bool QgsExpression::NodeColumnRef::prepare( QgsExpression *parent, const QgsExpr QgsFields fields = qvariant_cast( context->variable( QgsExpressionContext::EXPR_FIELDS ) ); - mIndex = fields.fieldNameIndex( mName ); + mIndex = fields.lookupField( mName ); if ( mIndex >= 0 ) { return true; diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index 212b76eb0ea4..e295545d1270 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -179,10 +179,19 @@ class CORE_EXPORT QgsExpression * all attributes from the layer are required for evaluation of the expression. * QgsFeatureRequest::setSubsetOfAttributes automatically handles this case. * + * @see referencedAttributeIndexes() + * * TODO QGIS3: Return QSet */ QStringList referencedColumns() const; + /** + * Return a list of field name indexes obtained from the provided fields. + * + * @note Added in QGIS 3.0 + */ + QSet referencedAttributeIndexes( const QgsFields& fields ) const; + //! Returns true if the expression uses feature geometry for some computation bool needsGeometry() const; @@ -294,13 +303,13 @@ class CORE_EXPORT QgsExpression * in the string with the result of its evaluation with the specified context * * Additional substitutions can be passed through the substitutionMap parameter - * @param action - * @param context expression context - * @param distanceArea optional QgsDistanceArea. If specified, the QgsDistanceArea is used for distance + * @param action The source string in which placeholders should be replaced. + * @param context Expression context + * @param distanceArea Optional QgsDistanceArea. If specified, the QgsDistanceArea is used for distance * and area conversion * @note added in QGIS 2.12 */ - static QString replaceExpressionText( const QString &action, const QgsExpressionContext* context, + static QString replaceExpressionText( const QString& action, const QgsExpressionContext* context, const QgsDistanceArea* distanceArea = nullptr ); /** Attempts to evaluate a text string as an expression to a resultant double @@ -335,12 +344,12 @@ class CORE_EXPORT QgsExpression boAnd, // comparison - boEQ, // = - boNE, // <> - boLE, // <= - boGE, // >= - boLT, // < - boGT, // > + boEQ, //!< = + boNE, //!< <> + boLE, //!< <= + boGE, //!< >= + boLT, //!< < + boGT, //!< > boRegexp, boLike, boNotLike, diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index d9e886217a3a..0df4f1ca3d5f 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -17,7 +17,7 @@ #include "qgslogger.h" #include "qgsexpression.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorlayer.h" #include "qgsproject.h" #include "qgssymbollayerutils.h" diff --git a/src/core/qgsexpressionfieldbuffer.h b/src/core/qgsexpressionfieldbuffer.h index 3eaf5a1be8b0..6ac2d46a4195 100644 --- a/src/core/qgsexpressionfieldbuffer.h +++ b/src/core/qgsexpressionfieldbuffer.h @@ -22,7 +22,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsexpression.h" /** \ingroup core diff --git a/src/core/qgsfeature.cpp b/src/core/qgsfeature.cpp index 2416fe5e80b2..75d27482ba85 100644 --- a/src/core/qgsfeature.cpp +++ b/src/core/qgsfeature.cpp @@ -15,7 +15,7 @@ email : sherman at mrcc.com #include "qgsfeature.h" #include "qgsfeature_p.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgsrectangle.h" @@ -274,7 +274,7 @@ QVariant QgsFeature::attribute( const QString& name ) const int QgsFeature::fieldNameIndex( const QString& fieldName ) const { - return d->fields.fieldNameIndex( fieldName ); + return d->fields.lookupField( fieldName ); } /*************************************************************************** diff --git a/src/core/qgsfeature.h b/src/core/qgsfeature.h index 3b3d7e411225..3f1239caedd3 100644 --- a/src/core/qgsfeature.h +++ b/src/core/qgsfeature.h @@ -24,7 +24,7 @@ email : sherman at mrcc.com #include #include -#include "qgsfield.h" +#include "qgsfields.h" class QgsGeometry; class QgsRectangle; diff --git a/src/core/qgsfeature_p.h b/src/core/qgsfeature_p.h index 7e2e20c2f1df..2f6c2e02d4c7 100644 --- a/src/core/qgsfeature_p.h +++ b/src/core/qgsfeature_p.h @@ -33,7 +33,7 @@ email : nyall dot dawson at gmail dot com * See details in QEP #17 ****************************************************************************/ -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" diff --git a/src/core/qgsfeaturerequest.cpp b/src/core/qgsfeaturerequest.cpp index 80a6a5186886..a816b2ec229f 100644 --- a/src/core/qgsfeaturerequest.cpp +++ b/src/core/qgsfeaturerequest.cpp @@ -14,7 +14,7 @@ ***************************************************************************/ #include "qgsfeaturerequest.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include @@ -208,7 +208,7 @@ QgsFeatureRequest& QgsFeatureRequest::setSubsetOfAttributes( const QStringList& Q_FOREACH ( const QString& attrName, attrNames ) { - int attrNum = fields.fieldNameIndex( attrName ); + int attrNum = fields.lookupField( attrName ); if ( attrNum != -1 && !mAttrs.contains( attrNum ) ) mAttrs.append( attrNum ); } diff --git a/src/core/qgsfeaturestore.h b/src/core/qgsfeaturestore.h index 620658c80a1b..73729c3c2de0 100644 --- a/src/core/qgsfeaturestore.h +++ b/src/core/qgsfeaturestore.h @@ -17,7 +17,7 @@ #include "qgis.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgscoordinatereferencesystem.h" #include #include diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index 4363fb0f093b..95ccee0e8646 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -14,7 +14,7 @@ * * ***************************************************************************/ -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfield_p.h" #include "qgis.h" #include "qgsapplication.h" @@ -323,331 +323,3 @@ QDataStream& operator>>( QDataStream& in, QgsField& field ) field.setSubType( static_cast< QVariant::Type >( subType ) ); return in; } - -//////////////////////////////////////////////////////////////////////////// - - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -QgsFields::QgsFields() -{ - d = new QgsFieldsPrivate(); -} - -QgsFields::QgsFields( const QgsFields& other ) - : d( other.d ) -{ -} - -QgsFields& QgsFields::operator =( const QgsFields & other ) -{ - d = other.d; - return *this; -} - -QgsFields::~QgsFields() -{ - -} - -void QgsFields::clear() -{ - d->fields.clear(); - d->nameToIndex.clear(); -} - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -bool QgsFields::append( const QgsField& field, FieldOrigin origin, int originIndex ) -{ - if ( d->nameToIndex.contains( field.name() ) ) - return false; - - if ( originIndex == -1 && origin == OriginProvider ) - originIndex = d->fields.count(); - d->fields.append( Field( field, origin, originIndex ) ); - - d->nameToIndex.insert( field.name(), d->fields.count() - 1 ); - return true; -} - -bool QgsFields::appendExpressionField( const QgsField& field, int originIndex ) -{ - if ( d->nameToIndex.contains( field.name() ) ) - return false; - - d->fields.append( Field( field, OriginExpression, originIndex ) ); - - d->nameToIndex.insert( field.name(), d->fields.count() - 1 ); - return true; -} - -void QgsFields::remove( int fieldIdx ) -{ - if ( !exists( fieldIdx ) ) - return; - - d->fields.remove( fieldIdx ); - d->nameToIndex.clear(); - for ( int idx = 0; idx < count(); ++idx ) - { - d->nameToIndex.insert( d->fields.at( idx ).field.name(), idx ); - } -} - -void QgsFields::extend( const QgsFields& other ) -{ - for ( int i = 0; i < other.count(); ++i ) - { - append( other.at( i ), other.fieldOrigin( i ), other.fieldOriginIndex( i ) ); - } -} - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -bool QgsFields::isEmpty() const -{ - return d->fields.isEmpty(); -} - -int QgsFields::count() const -{ - return d->fields.count(); -} - -int QgsFields::size() const -{ - return d->fields.count(); -} - -bool QgsFields::exists( int i ) const -{ - return i >= 0 && i < d->fields.count(); -} - -QgsField &QgsFields::operator[]( int i ) -{ - return d->fields[i].field; -} - -QgsField QgsFields::at( int i ) const -{ - return d->fields[i].field; -} - -QgsField QgsFields::field( int fieldIdx ) const -{ - return d->fields[fieldIdx].field; -} - -QgsField QgsFields::field( const QString &name ) const -{ - return d->fields[ indexFromName( name )].field; -} - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -QgsField QgsFields::operator[]( int i ) const -{ - return d->fields[i].field; -} - -QgsFields::FieldOrigin QgsFields::fieldOrigin( int fieldIdx ) const -{ - if ( !exists( fieldIdx ) ) - return OriginUnknown; - - return d->fields[fieldIdx].origin; -} - -int QgsFields::fieldOriginIndex( int fieldIdx ) const -{ - return d->fields[fieldIdx].originIndex; -} - -int QgsFields::indexFromName( const QString &fieldName ) const -{ - return d->nameToIndex.value( fieldName, -1 ); -} - -QList QgsFields::toList() const -{ - QList lst; - for ( int i = 0; i < d->fields.count(); ++i ) - lst.append( d->fields[i].field ); - return lst; -} - -bool QgsFields::operator==( const QgsFields &other ) const -{ - return d->fields == other.d->fields; -} - -QgsFields::const_iterator QgsFields::constBegin() const noexcept -{ - if ( d->fields.isEmpty() ) - return const_iterator(); - - return const_iterator( &d->fields.first() ); -} - -QgsFields::const_iterator QgsFields::constEnd() const noexcept -{ - if ( d->fields.isEmpty() ) - return const_iterator(); - - return const_iterator( &d->fields.last() + 1 ); -} - -QgsFields::const_iterator QgsFields::begin() const noexcept -{ - if ( d->fields.isEmpty() ) - return const_iterator(); - - return const_iterator( &d->fields.first() ); -} - -QgsFields::const_iterator QgsFields::end() const noexcept -{ - if ( d->fields.isEmpty() ) - return const_iterator(); - - return const_iterator( &d->fields.last() + 1 ); -} - -QgsFields::iterator QgsFields::begin() -{ - if ( d->fields.isEmpty() ) - return iterator(); - - d.detach(); - return iterator( &d->fields.first() ); -} - -QgsFields::iterator QgsFields::end() -{ - if ( d->fields.isEmpty() ) - return iterator(); - - d.detach(); - return iterator( &d->fields.last() + 1 ); -} - -QIcon QgsFields::iconForField( int fieldIdx ) const -{ - switch ( d->fields.at( fieldIdx ).field.type() ) - { - case QVariant::Int: - case QVariant::UInt: - case QVariant::LongLong: - case QVariant::ULongLong: - { - return QgsApplication::getThemeIcon( "/mIconFieldInteger.svg" ); - } - case QVariant::Double: - { - return QgsApplication::getThemeIcon( "/mIconFieldFloat.svg" ); - } - case QVariant::String: - { - return QgsApplication::getThemeIcon( "/mIconFieldText.svg" ); - } - case QVariant::Date: - { - return QgsApplication::getThemeIcon( "/mIconFieldDate.svg" ); - } - case QVariant::DateTime: - { - return QgsApplication::getThemeIcon( "/mIconFieldDateTime.svg" ); - } - case QVariant::Time: - { - return QgsApplication::getThemeIcon( "/mIconFieldTime.svg" ); - } - default: - return QIcon(); - } -} - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -int QgsFields::fieldNameIndex( const QString& fieldName ) const -{ - for ( int idx = 0; idx < count(); ++idx ) - { - if ( d->fields[idx].field.name() == fieldName ) - return idx; - } - - for ( int idx = 0; idx < count(); ++idx ) - { - if ( QString::compare( d->fields[idx].field.name(), fieldName, Qt::CaseInsensitive ) == 0 ) - return idx; - } - - for ( int idx = 0; idx < count(); ++idx ) - { - if ( QString::compare( d->fields[idx].field.alias(), fieldName, Qt::CaseInsensitive ) == 0 ) - return idx; - } - - return -1; -} - -QgsAttributeList QgsFields::allAttributesList() const -{ - QgsAttributeList lst; - for ( int i = 0; i < d->fields.count(); ++i ) - lst.append( i ); - return lst; -} - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -QDataStream& operator<<( QDataStream& out, const QgsFields& fields ) -{ - out << static_cast< quint32 >( fields.size() ); - for ( int i = 0; i < fields.size(); i++ ) - { - out << fields.field( i ); - } - return out; -} - -QDataStream& operator>>( QDataStream& in, QgsFields& fields ) -{ - fields.clear(); - quint32 size; - in >> size; - for ( quint32 i = 0; i < size; i++ ) - { - QgsField field; - in >> field; - fields.append( field ); - } - return in; -} diff --git a/src/core/qgsfield.h b/src/core/qgsfield.h index 7dbe3d3505fe..fb002c5d5d77 100644 --- a/src/core/qgsfield.h +++ b/src/core/qgsfield.h @@ -269,291 +269,4 @@ CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsField& field ); CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsField& field ); - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -/** \class QgsFields - * \ingroup core - * Container of fields for a vector layer. - * - * In addition to storing a list of QgsField instances, it also: - * - allows quick lookups of field names to index in the list - * - keeps track of where the field definition comes from (vector data provider, joined layer or newly added from an editing operation) - * \note QgsFields objects are implicitly shared. - */ -class CORE_EXPORT QgsFields -{ - public: - - enum FieldOrigin - { - OriginUnknown, //!< it has not been specified where the field comes from - OriginProvider, //!< field comes from the underlying data provider of the vector layer (originIndex = index in provider's fields) - OriginJoin, //!< field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join) - OriginEdit, //!< field has been temporarily added in editing mode (originIndex = index in the list of added attributes) - OriginExpression //!< field is calculated from an expression - }; - - typedef struct Field - { - Field(): origin( OriginUnknown ), originIndex( -1 ) {} - Field( const QgsField& f, FieldOrigin o, int oi ): field( f ), origin( o ), originIndex( oi ) {} - - //! @note added in 2.6 - bool operator==( const Field& other ) const { return field == other.field && origin == other.origin && originIndex == other.originIndex; } - //! @note added in 2.6 - bool operator!=( const Field& other ) const { return !( *this == other ); } - - QgsField field; //!< field - FieldOrigin origin; //!< origin of the field - int originIndex; //!< index specific to the origin - } Field; - - /** Constructor for an empty field container - */ - QgsFields(); - - /** Copy constructor - */ - QgsFields( const QgsFields& other ); - - /** Assignment operator - */ - QgsFields& operator =( const QgsFields &other ); - - virtual ~QgsFields(); - - //! Remove all fields - void clear(); - //! Append a field. The field must have unique name, otherwise it is rejected (returns false) - bool append( const QgsField& field, FieldOrigin origin = OriginProvider, int originIndex = -1 ); - //! Append an expression field. The field must have unique name, otherwise it is rejected (returns false) - bool appendExpressionField( const QgsField& field, int originIndex ); - //! Remove a field with the given index - void remove( int fieldIdx ); - //! Extend with fields from another QgsFields container - void extend( const QgsFields& other ); - - //! Check whether the container is empty - bool isEmpty() const; - //! Return number of items - int count() const; - //! Return number of items - int size() const; - //! Return if a field index is valid - //! @param i Index of the field which needs to be checked - //! @return True if the field exists - bool exists( int i ) const; - - //! Get field at particular index (must be in range 0..N-1) - QgsField operator[]( int i ) const; - //! Get field at particular index (must be in range 0..N-1) - QgsField& operator[]( int i ); - //! Get field at particular index (must be in range 0..N-1) - QgsField at( int i ) const; - //! Get field at particular index (must be in range 0..N-1) - QgsField field( int fieldIdx ) const; - //! Get field with matching name - QgsField field( const QString& name ) const; - - //! Get field's origin (value from an enumeration) - FieldOrigin fieldOrigin( int fieldIdx ) const; - //! Get field's origin index (its meaning is specific to each type of origin) - int fieldOriginIndex( int fieldIdx ) const; - - /** - * Look up field's index from the field name. - * This method takes is case sensitive and only matches the data source - * name of the field. - * - * @param fieldName The name of the field. - * - * @return The field index if found or -1 in case it cannot be found. - * @see fieldNameIndex For a more tolerant alternative. - */ - int indexFromName( const QString& fieldName ) const; - - /** - * Look up field's index from the field name. - * This method matches in the following order: - * - * 1. The exact field name taking case sensitivity into account - * 2. Looks for the field name by case insensitive comparison - * 3. The field alias (case insensitive) - * - * @param fieldName The name to look for. - * - * @return The field index if found or -1 in case it cannot be found. - * @see indexFromName For a more performant and precise but less tolerant alternative. - * @note added in 2.4 - */ - int fieldNameIndex( const QString& fieldName ) const; - - //! Utility function to get list of attribute indexes - //! @note added in 2.4 - QgsAttributeList allAttributesList() const; - - //! Utility function to return a list of QgsField instances - QList toList() const; - - //! @note added in 2.6 - bool operator==( const QgsFields& other ) const; - //! @note added in 2.6 - bool operator!=( const QgsFields& other ) const { return !( *this == other ); } - /** Returns an icon corresponding to a field index, based on the field's type and source - * @note added in QGIS 2.14 - */ - QIcon iconForField( int fieldIdx ) const; - - //! Allows direct construction of QVariants from fields. - operator QVariant() const - { - return QVariant::fromValue( *this ); - } - - ///@cond PRIVATE - - class const_iterator; - - class iterator - { - public: - QgsFields::Field* d; - typedef std::random_access_iterator_tag iterator_category; - typedef qptrdiff difference_type; - - inline iterator() - : d( nullptr ) - {} - inline iterator( QgsFields::Field *n ) - : d( n ) - {} - - inline QgsField& operator*() const { return d->field; } - inline QgsField* operator->() const { return &d->field; } - inline QgsField& operator[]( difference_type j ) const { return d[j].field; } - inline bool operator==( const iterator &o ) const noexcept { return d == o.d; } - inline bool operator!=( const iterator &o ) const noexcept { return d != o.d; } - inline bool operator<( const iterator& other ) const noexcept { return d < other.d; } - inline bool operator<=( const iterator& other ) const noexcept { return d <= other.d; } - inline bool operator>( const iterator& other ) const noexcept { return d > other.d; } - inline bool operator>=( const iterator& other ) const noexcept { return d >= other.d; } - - inline iterator& operator++() { ++d; return *this; } - inline iterator operator++( int ) { QgsFields::Field* n = d; ++d; return n; } - inline iterator& operator--() { d--; return *this; } - inline iterator operator--( int ) { QgsFields::Field* n = d; d--; return n; } - inline iterator& operator+=( difference_type j ) { d += j; return *this; } - inline iterator& operator-=( difference_type j ) { d -= j; return *this; } - inline iterator operator+( difference_type j ) const { return iterator( d + j ); } - inline iterator operator-( difference_type j ) const { return iterator( d -j ); } - inline int operator-( iterator j ) const { return int( d - j.d ); } - }; - friend class iterator; - - class const_iterator - { - public: - const QgsFields::Field* d; - - typedef std::random_access_iterator_tag iterator_category; - typedef qptrdiff difference_type; - - inline const_iterator() - : d( nullptr ) {} - inline const_iterator( const QgsFields::Field* f ) - : d( f ) {} - inline const_iterator( const const_iterator &o ) - : d( o.d ) {} - inline explicit const_iterator( const iterator &o ) - : d( o.d ) {} - inline const QgsField& operator*() const { return d->field; } - inline const QgsField* operator->() const { return &d->field; } - inline const QgsField& operator[]( difference_type j ) const noexcept { return d[j].field; } - inline bool operator==( const const_iterator &o ) const noexcept { return d == o.d; } - inline bool operator!=( const const_iterator &o ) const noexcept { return d != o.d; } - inline bool operator<( const const_iterator& other ) const noexcept { return d < other.d; } - inline bool operator<=( const const_iterator& other ) const noexcept { return d <= other.d; } - inline bool operator>( const const_iterator& other ) const noexcept { return d > other.d; } - inline bool operator>=( const const_iterator& other ) const noexcept { return d >= other.d; } - inline const_iterator& operator++() { ++d; return *this; } - inline const_iterator operator++( int ) { const QgsFields::Field* n = d; ++d; return n; } - inline const_iterator& operator--() { d--; return *this; } - inline const_iterator operator--( int ) { const QgsFields::Field* n = d; --d; return n; } - inline const_iterator& operator+=( difference_type j ) { d += j; return *this; } - inline const_iterator& operator-=( difference_type j ) { d -= j; return *this; } - inline const_iterator operator+( difference_type j ) const { return const_iterator( d + j ); } - inline const_iterator operator-( difference_type j ) const { return const_iterator( d -j ); } - inline int operator-( const_iterator j ) const { return int( d - j.d ); } - }; - friend class const_iterator; - ///@endcond - - - /** - * Returns a const STL-style iterator pointing to the first item in the list. - * - * @note added in 2.16 - * @note not available in Python bindings - */ - const_iterator constBegin() const noexcept; - - /** - * Returns a const STL-style iterator pointing to the imaginary item after the last item in the list. - * - * @note added in 2.16 - * @note not available in Python bindings - */ - const_iterator constEnd() const noexcept; - - /** - * Returns a const STL-style iterator pointing to the first item in the list. - * - * @note added in 2.16 - * @note not available in Python bindings - */ - const_iterator begin() const noexcept; - - /** - * Returns a const STL-style iterator pointing to the imaginary item after the last item in the list. - * - * @note added in 2.16 - * @note not available in Python bindings - */ - const_iterator end() const noexcept; - - /** - * Returns an STL-style iterator pointing to the first item in the list. - * - * @note added in 2.16 - * @note not available in Python bindings - */ - iterator begin(); - - - /** - * Returns an STL-style iterator pointing to the imaginary item after the last item in the list. - * - * @note added in 2.16 - * @note not available in Python bindings - */ - iterator end(); - - private: - - QSharedDataPointer d; - -}; - -Q_DECLARE_METATYPE( QgsFields ) - -/** Writes the fields to stream out. QGIS version compatibility is not guaranteed. */ -CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsFields& fields ); -/** Reads fields from stream in into fields. QGIS version compatibility is not guaranteed. */ -CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsFields& fields ); - #endif diff --git a/src/core/qgsfield_p.h b/src/core/qgsfield_p.h index c1f193db426c..7c133a8c9f1a 100644 --- a/src/core/qgsfield_p.h +++ b/src/core/qgsfield_p.h @@ -30,7 +30,6 @@ #include #include #include -#include "qgsfield.h" /*************************************************************************** * This class is considered CRITICAL and any change MUST be accompanied with @@ -112,38 +111,6 @@ class QgsFieldPrivate : public QSharedData QgsEditorWidgetSetup editorWidgetSetup; }; - -/*************************************************************************** - * This class is considered CRITICAL and any change MUST be accompanied with - * full unit tests in testqgsfields.cpp. - * See details in QEP #17 - ****************************************************************************/ - -class CORE_EXPORT QgsFieldsPrivate : public QSharedData -{ - public: - - QgsFieldsPrivate() - { - } - - QgsFieldsPrivate( const QgsFieldsPrivate& other ) - : QSharedData( other ) - , fields( other.fields ) - , nameToIndex( other.nameToIndex ) - { - } - - ~QgsFieldsPrivate() {} - - //! internal storage of the container - QVector fields; - - //! map for quick resolution of name to index - QHash nameToIndex; - -}; - /// @endcond #endif diff --git a/src/core/qgsfields.cpp b/src/core/qgsfields.cpp new file mode 100644 index 000000000000..ccb68b3ee9b1 --- /dev/null +++ b/src/core/qgsfields.cpp @@ -0,0 +1,346 @@ +/*************************************************************************** + qgsfields.cpp - QgsFields + + --------------------- + begin : 22.9.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgsfields.h" +#include "qgsfields_p.h" +#include "qgsapplication.h" +#include + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +QgsFields::QgsFields() +{ + d = new QgsFieldsPrivate(); +} + +QgsFields::QgsFields( const QgsFields& other ) + : d( other.d ) +{ +} + +QgsFields& QgsFields::operator =( const QgsFields & other ) +{ + d = other.d; + return *this; +} + +QgsFields::~QgsFields() +{ + +} + +void QgsFields::clear() +{ + d->fields.clear(); + d->nameToIndex.clear(); +} + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +bool QgsFields::append( const QgsField& field, FieldOrigin origin, int originIndex ) +{ + if ( d->nameToIndex.contains( field.name() ) ) + return false; + + if ( originIndex == -1 && origin == OriginProvider ) + originIndex = d->fields.count(); + d->fields.append( Field( field, origin, originIndex ) ); + + d->nameToIndex.insert( field.name(), d->fields.count() - 1 ); + return true; +} + +bool QgsFields::appendExpressionField( const QgsField& field, int originIndex ) +{ + if ( d->nameToIndex.contains( field.name() ) ) + return false; + + d->fields.append( Field( field, OriginExpression, originIndex ) ); + + d->nameToIndex.insert( field.name(), d->fields.count() - 1 ); + return true; +} + +void QgsFields::remove( int fieldIdx ) +{ + if ( !exists( fieldIdx ) ) + return; + + d->fields.remove( fieldIdx ); + d->nameToIndex.clear(); + for ( int idx = 0; idx < count(); ++idx ) + { + d->nameToIndex.insert( d->fields.at( idx ).field.name(), idx ); + } +} + +void QgsFields::extend( const QgsFields& other ) +{ + for ( int i = 0; i < other.count(); ++i ) + { + append( other.at( i ), other.fieldOrigin( i ), other.fieldOriginIndex( i ) ); + } +} + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +bool QgsFields::isEmpty() const +{ + return d->fields.isEmpty(); +} + +int QgsFields::count() const +{ + return d->fields.count(); +} + +int QgsFields::size() const +{ + return d->fields.count(); +} + +bool QgsFields::exists( int i ) const +{ + return i >= 0 && i < d->fields.count(); +} + +QgsField &QgsFields::operator[]( int i ) +{ + return d->fields[i].field; +} + +QgsField QgsFields::at( int i ) const +{ + return d->fields[i].field; +} + +QgsField QgsFields::field( int fieldIdx ) const +{ + return d->fields[fieldIdx].field; +} + +QgsField QgsFields::field( const QString &name ) const +{ + return d->fields[ indexFromName( name )].field; +} + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +QgsField QgsFields::operator[]( int i ) const +{ + return d->fields[i].field; +} + +QgsFields::FieldOrigin QgsFields::fieldOrigin( int fieldIdx ) const +{ + if ( !exists( fieldIdx ) ) + return OriginUnknown; + + return d->fields[fieldIdx].origin; +} + +int QgsFields::fieldOriginIndex( int fieldIdx ) const +{ + return d->fields[fieldIdx].originIndex; +} + +int QgsFields::indexFromName( const QString &fieldName ) const +{ + return d->nameToIndex.value( fieldName, -1 ); +} + +QList QgsFields::toList() const +{ + QList lst; + for ( int i = 0; i < d->fields.count(); ++i ) + lst.append( d->fields[i].field ); + return lst; +} + +bool QgsFields::operator==( const QgsFields &other ) const +{ + return d->fields == other.d->fields; +} + +QgsFields::const_iterator QgsFields::constBegin() const noexcept +{ + if ( d->fields.isEmpty() ) + return const_iterator(); + + return const_iterator( &d->fields.first() ); +} + +QgsFields::const_iterator QgsFields::constEnd() const noexcept +{ + if ( d->fields.isEmpty() ) + return const_iterator(); + + return const_iterator( &d->fields.last() + 1 ); +} + +QgsFields::const_iterator QgsFields::begin() const noexcept +{ + if ( d->fields.isEmpty() ) + return const_iterator(); + + return const_iterator( &d->fields.first() ); +} + +QgsFields::const_iterator QgsFields::end() const noexcept +{ + if ( d->fields.isEmpty() ) + return const_iterator(); + + return const_iterator( &d->fields.last() + 1 ); +} + +QgsFields::iterator QgsFields::begin() +{ + if ( d->fields.isEmpty() ) + return iterator(); + + d.detach(); + return iterator( &d->fields.first() ); +} + +QgsFields::iterator QgsFields::end() +{ + if ( d->fields.isEmpty() ) + return iterator(); + + d.detach(); + return iterator( &d->fields.last() + 1 ); +} + +QIcon QgsFields::iconForField( int fieldIdx ) const +{ + switch ( d->fields.at( fieldIdx ).field.type() ) + { + case QVariant::Int: + case QVariant::UInt: + case QVariant::LongLong: + case QVariant::ULongLong: + { + return QgsApplication::getThemeIcon( "/mIconFieldInteger.svg" ); + } + case QVariant::Double: + { + return QgsApplication::getThemeIcon( "/mIconFieldFloat.svg" ); + } + case QVariant::String: + { + return QgsApplication::getThemeIcon( "/mIconFieldText.svg" ); + } + case QVariant::Date: + { + return QgsApplication::getThemeIcon( "/mIconFieldDate.svg" ); + } + case QVariant::DateTime: + { + return QgsApplication::getThemeIcon( "/mIconFieldDateTime.svg" ); + } + case QVariant::Time: + { + return QgsApplication::getThemeIcon( "/mIconFieldTime.svg" ); + } + default: + return QIcon(); + } +} + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +int QgsFields::lookupField( const QString& fieldName ) const +{ + for ( int idx = 0; idx < count(); ++idx ) + { + if ( d->fields[idx].field.name() == fieldName ) + return idx; + } + + for ( int idx = 0; idx < count(); ++idx ) + { + if ( QString::compare( d->fields[idx].field.name(), fieldName, Qt::CaseInsensitive ) == 0 ) + return idx; + } + + for ( int idx = 0; idx < count(); ++idx ) + { + QString alias = d->fields[idx].field.alias(); + if ( !alias.isNull() && QString::compare( alias, fieldName, Qt::CaseInsensitive ) == 0 ) + return idx; + } + + return -1; +} + +QgsAttributeList QgsFields::allAttributesList() const +{ + QgsAttributeList lst; + for ( int i = 0; i < d->fields.count(); ++i ) + lst.append( i ); + return lst; +} + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +QDataStream& operator<<( QDataStream& out, const QgsFields& fields ) +{ + out << static_cast< quint32 >( fields.size() ); + for ( int i = 0; i < fields.size(); i++ ) + { + out << fields.field( i ); + } + return out; +} + +QDataStream& operator>>( QDataStream& in, QgsFields& fields ) +{ + fields.clear(); + quint32 size; + in >> size; + for ( quint32 i = 0; i < size; i++ ) + { + QgsField field; + in >> field; + fields.append( field ); + } + return in; +} diff --git a/src/core/qgsfields.h b/src/core/qgsfields.h new file mode 100644 index 000000000000..0f2dca159379 --- /dev/null +++ b/src/core/qgsfields.h @@ -0,0 +1,314 @@ +/*************************************************************************** + qgsfields.h - QgsFields + + --------------------- + begin : 22.9.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSFIELDS_H +#define QGSFIELDS_H + +#include "qgsfield.h" + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +/** \class QgsFields + * \ingroup core + * Container of fields for a vector layer. + * + * In addition to storing a list of QgsField instances, it also: + * - allows quick lookups of field names to index in the list + * - keeps track of where the field definition comes from (vector data provider, joined layer or newly added from an editing operation) + * \note QgsFields objects are implicitly shared. + */ +class CORE_EXPORT QgsFields +{ + public: + + enum FieldOrigin + { + OriginUnknown, //!< it has not been specified where the field comes from + OriginProvider, //!< field comes from the underlying data provider of the vector layer (originIndex = index in provider's fields) + OriginJoin, //!< field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join) + OriginEdit, //!< field has been temporarily added in editing mode (originIndex = index in the list of added attributes) + OriginExpression //!< field is calculated from an expression + }; + + typedef struct Field + { + Field() + : origin( OriginUnknown ) + , originIndex( -1 ) + {} + Field( const QgsField& f, FieldOrigin o, int oi ) + : field( f ) + , origin( o ) + , originIndex( oi ) + {} + + //! @note added in 2.6 + bool operator==( const Field& other ) const { return field == other.field && origin == other.origin && originIndex == other.originIndex; } + //! @note added in 2.6 + bool operator!=( const Field& other ) const { return !( *this == other ); } + + QgsField field; //!< field + FieldOrigin origin; //!< origin of the field + int originIndex; //!< index specific to the origin + } Field; + + /** Constructor for an empty field container + */ + QgsFields(); + + /** Copy constructor + */ + QgsFields( const QgsFields& other ); + + /** Assignment operator + */ + QgsFields& operator =( const QgsFields& other ); + + virtual ~QgsFields(); + + //! Remove all fields + void clear(); + //! Append a field. The field must have unique name, otherwise it is rejected (returns false) + bool append( const QgsField& field, FieldOrigin origin = OriginProvider, int originIndex = -1 ); + //! Append an expression field. The field must have unique name, otherwise it is rejected (returns false) + bool appendExpressionField( const QgsField& field, int originIndex ); + //! Remove a field with the given index + void remove( int fieldIdx ); + //! Extend with fields from another QgsFields container + void extend( const QgsFields& other ); + + //! Check whether the container is empty + bool isEmpty() const; + //! Return number of items + int count() const; + //! Return number of items + int size() const; + //! Return if a field index is valid + //! @param i Index of the field which needs to be checked + //! @return True if the field exists + bool exists( int i ) const; + + //! Get field at particular index (must be in range 0..N-1) + QgsField operator[]( int i ) const; + //! Get field at particular index (must be in range 0..N-1) + QgsField& operator[]( int i ); + //! Get field at particular index (must be in range 0..N-1) + QgsField at( int i ) const; + //! Get field at particular index (must be in range 0..N-1) + QgsField field( int fieldIdx ) const; + //! Get field with matching name + QgsField field( const QString& name ) const; + + //! Get field's origin (value from an enumeration) + FieldOrigin fieldOrigin( int fieldIdx ) const; + //! Get field's origin index (its meaning is specific to each type of origin) + int fieldOriginIndex( int fieldIdx ) const; + + /** + * Look up field's index from the field name. + * This method takes is case sensitive and only matches the data source + * name of the field. + * + * @param fieldName The name of the field. + * + * @return The field index if found or -1 in case it cannot be found. + * @see lookupField For a more tolerant alternative. + */ + int indexFromName( const QString& fieldName ) const; + + /** + * Look up field's index from the field name. + * This method matches in the following order: + * + * 1. The exact field name taking case sensitivity into account + * 2. Looks for the field name by case insensitive comparison + * 3. The field alias (case insensitive) + * + * @param fieldName The name to look for. + * + * @return The field index if found or -1 in case it cannot be found. + * @see indexFromName For a more performant and precise but less tolerant alternative. + * @note added in 2.4 + */ + int lookupField( const QString& fieldName ) const; + + //! Utility function to get list of attribute indexes + //! @note added in 2.4 + QgsAttributeList allAttributesList() const; + + //! Utility function to return a list of QgsField instances + QList toList() const; + + //! @note added in 2.6 + bool operator==( const QgsFields& other ) const; + //! @note added in 2.6 + bool operator!=( const QgsFields& other ) const { return !( *this == other ); } + /** Returns an icon corresponding to a field index, based on the field's type and source + * @note added in QGIS 2.14 + */ + QIcon iconForField( int fieldIdx ) const; + + //! Allows direct construction of QVariants from fields. + operator QVariant() const + { + return QVariant::fromValue( *this ); + } + + ///@cond PRIVATE + + class const_iterator; + + class iterator + { + public: + QgsFields::Field* d; + typedef std::random_access_iterator_tag iterator_category; + typedef qptrdiff difference_type; + + inline iterator() + : d( nullptr ) + {} + inline iterator( QgsFields::Field *n ) + : d( n ) + {} + + inline QgsField& operator*() const { return d->field; } + inline QgsField* operator->() const { return &d->field; } + inline QgsField& operator[]( difference_type j ) const { return d[j].field; } + inline bool operator==( const iterator &o ) const noexcept { return d == o.d; } + inline bool operator!=( const iterator &o ) const noexcept { return d != o.d; } + inline bool operator<( const iterator& other ) const noexcept { return d < other.d; } + inline bool operator<=( const iterator& other ) const noexcept { return d <= other.d; } + inline bool operator>( const iterator& other ) const noexcept { return d > other.d; } + inline bool operator>=( const iterator& other ) const noexcept { return d >= other.d; } + + inline iterator& operator++() { ++d; return *this; } + inline iterator operator++( int ) { QgsFields::Field* n = d; ++d; return n; } + inline iterator& operator--() { d--; return *this; } + inline iterator operator--( int ) { QgsFields::Field* n = d; d--; return n; } + inline iterator& operator+=( difference_type j ) { d += j; return *this; } + inline iterator& operator-=( difference_type j ) { d -= j; return *this; } + inline iterator operator+( difference_type j ) const { return iterator( d + j ); } + inline iterator operator-( difference_type j ) const { return iterator( d -j ); } + inline int operator-( iterator j ) const { return int( d - j.d ); } + }; + friend class iterator; + + class const_iterator + { + public: + const QgsFields::Field* d; + + typedef std::random_access_iterator_tag iterator_category; + typedef qptrdiff difference_type; + + inline const_iterator() + : d( nullptr ) {} + inline const_iterator( const QgsFields::Field* f ) + : d( f ) {} + inline const_iterator( const const_iterator &o ) + : d( o.d ) {} + inline explicit const_iterator( const iterator &o ) + : d( o.d ) {} + inline const QgsField& operator*() const { return d->field; } + inline const QgsField* operator->() const { return &d->field; } + inline const QgsField& operator[]( difference_type j ) const noexcept { return d[j].field; } + inline bool operator==( const const_iterator &o ) const noexcept { return d == o.d; } + inline bool operator!=( const const_iterator &o ) const noexcept { return d != o.d; } + inline bool operator<( const const_iterator& other ) const noexcept { return d < other.d; } + inline bool operator<=( const const_iterator& other ) const noexcept { return d <= other.d; } + inline bool operator>( const const_iterator& other ) const noexcept { return d > other.d; } + inline bool operator>=( const const_iterator& other ) const noexcept { return d >= other.d; } + inline const_iterator& operator++() { ++d; return *this; } + inline const_iterator operator++( int ) { const QgsFields::Field* n = d; ++d; return n; } + inline const_iterator& operator--() { d--; return *this; } + inline const_iterator operator--( int ) { const QgsFields::Field* n = d; --d; return n; } + inline const_iterator& operator+=( difference_type j ) { d += j; return *this; } + inline const_iterator& operator-=( difference_type j ) { d -= j; return *this; } + inline const_iterator operator+( difference_type j ) const { return const_iterator( d + j ); } + inline const_iterator operator-( difference_type j ) const { return const_iterator( d -j ); } + inline int operator-( const_iterator j ) const { return int( d - j.d ); } + }; + friend class const_iterator; + ///@endcond + + + /** + * Returns a const STL-style iterator pointing to the first item in the list. + * + * @note added in 2.16 + * @note not available in Python bindings + */ + const_iterator constBegin() const noexcept; + + /** + * Returns a const STL-style iterator pointing to the imaginary item after the last item in the list. + * + * @note added in 2.16 + * @note not available in Python bindings + */ + const_iterator constEnd() const noexcept; + + /** + * Returns a const STL-style iterator pointing to the first item in the list. + * + * @note added in 2.16 + * @note not available in Python bindings + */ + const_iterator begin() const noexcept; + + /** + * Returns a const STL-style iterator pointing to the imaginary item after the last item in the list. + * + * @note added in 2.16 + * @note not available in Python bindings + */ + const_iterator end() const noexcept; + + /** + * Returns an STL-style iterator pointing to the first item in the list. + * + * @note added in 2.16 + * @note not available in Python bindings + */ + iterator begin(); + + + /** + * Returns an STL-style iterator pointing to the imaginary item after the last item in the list. + * + * @note added in 2.16 + * @note not available in Python bindings + */ + iterator end(); + + private: + + QSharedDataPointer d; + +}; + +Q_DECLARE_METATYPE( QgsFields ) + +/** Writes the fields to stream out. QGIS version compatibility is not guaranteed. */ +CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsFields& fields ); +/** Reads fields from stream in into fields. QGIS version compatibility is not guaranteed. */ +CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsFields& fields ); + +#endif // QGSFIELDS_H diff --git a/src/core/qgsfields_p.h b/src/core/qgsfields_p.h new file mode 100644 index 000000000000..a383cfe6a872 --- /dev/null +++ b/src/core/qgsfields_p.h @@ -0,0 +1,67 @@ +/*************************************************************************** + qgsfields_p - %{Cpp:License:ClassName} + + --------------------- + begin : 22.9.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSFIELDS_P_H +#define QGSFIELDS_P_H + + +/// @cond PRIVATE + +// +// W A R N I N G +// ------------- +// +// This file is not part of the QGIS API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// + +#include +#include "qgsfields.h" + +/*************************************************************************** + * This class is considered CRITICAL and any change MUST be accompanied with + * full unit tests in testqgsfields.cpp. + * See details in QEP #17 + ****************************************************************************/ + +class CORE_EXPORT QgsFieldsPrivate : public QSharedData +{ + public: + + QgsFieldsPrivate() + { + } + + QgsFieldsPrivate( const QgsFieldsPrivate& other ) + : QSharedData( other ) + , fields( other.fields ) + , nameToIndex( other.nameToIndex ) + { + } + + ~QgsFieldsPrivate() {} + + //! internal storage of the container + QVector fields; + + //! map for quick resolution of name to index + QHash nameToIndex; + +}; + +/// @endcond + +#endif // QGSFIELDS_P_H diff --git a/src/core/qgsgml.h b/src/core/qgsgml.h index c4dc3214e6c6..5abde772dc57 100644 --- a/src/core/qgsgml.h +++ b/src/core/qgsgml.h @@ -17,7 +17,7 @@ #include #include "qgis.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsrectangle.h" #include "qgswkbptr.h" #include "qgsfeature.h" diff --git a/src/core/qgsgmlschema.h b/src/core/qgsgmlschema.h index be3457b07000..345761f3af08 100644 --- a/src/core/qgsgmlschema.h +++ b/src/core/qgsgmlschema.h @@ -18,7 +18,7 @@ #include #include "qgis.h" #include "qgserror.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include #include diff --git a/src/core/qgsjsonutils.h b/src/core/qgsjsonutils.h index 576fef87bd21..6074bcd3de04 100644 --- a/src/core/qgsjsonutils.h +++ b/src/core/qgsjsonutils.h @@ -19,7 +19,7 @@ #include "qgsfeature.h" #include "qgscoordinatereferencesystem.h" #include "qgscoordinatetransform.h" -#include "qgsfield.h" +#include "qgsfields.h" class QTextCodec; class QgsVectorLayer; diff --git a/src/core/qgsogrutils.cpp b/src/core/qgsogrutils.cpp index c39cd01fe4c6..a1833aa17413 100644 --- a/src/core/qgsogrutils.cpp +++ b/src/core/qgsogrutils.cpp @@ -17,7 +17,7 @@ #include "qgsapplication.h" #include "qgslogger.h" #include "qgsgeometry.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include diff --git a/src/core/qgspallabeling.h b/src/core/qgspallabeling.h index fa25930c4d23..7e934e8c363c 100644 --- a/src/core/qgspallabeling.h +++ b/src/core/qgspallabeling.h @@ -31,7 +31,7 @@ #include #include "qgsfeature.h" #include "qgsgeometry.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgspoint.h" #include "qgsmapunitscale.h" #include "qgsstringutils.h" diff --git a/src/core/qgsrelation.cpp b/src/core/qgsrelation.cpp index 49150eaf69da..bdc3997d628b 100644 --- a/src/core/qgsrelation.cpp +++ b/src/core/qgsrelation.cpp @@ -279,7 +279,7 @@ QgsAttributeList QgsRelation::referencedFields() const Q_FOREACH ( const FieldPair& pair, mFieldPairs ) { - attrs << mReferencedLayer->fieldNameIndex( pair.second ); + attrs << mReferencedLayer->fields().lookupField( pair.second ); } return attrs; } @@ -290,7 +290,7 @@ QgsAttributeList QgsRelation::referencingFields() const Q_FOREACH ( const FieldPair& pair, mFieldPairs ) { - attrs << mReferencingLayer->fieldNameIndex( pair.first ); + attrs << mReferencingLayer->fields().lookupField( pair.first ); } return attrs; @@ -337,13 +337,13 @@ void QgsRelation::updateRelationStatus() Q_FOREACH ( const FieldPair& fieldPair, mFieldPairs ) { - if ( -1 == mReferencingLayer->fieldNameIndex( fieldPair.first ) ) + if ( -1 == mReferencingLayer->fields().lookupField( fieldPair.first ) ) { QgsDebugMsg( QString( "Invalid relation: field %1 does not exist in referencing layer %2" ).arg( fieldPair.first, mReferencingLayer->name() ) ); mValid = false; break; } - else if ( -1 == mReferencedLayer->fieldNameIndex( fieldPair.second ) ) + else if ( -1 == mReferencedLayer->fields().lookupField( fieldPair.second ) ) { QgsDebugMsg( QString( "Invalid relation: field %1 does not exist in referencedg layer %2" ).arg( fieldPair.second, mReferencedLayer->name() ) ); mValid = false; diff --git a/src/core/qgsrelation.h b/src/core/qgsrelation.h index 94223e0adb92..26fe3d560298 100644 --- a/src/core/qgsrelation.h +++ b/src/core/qgsrelation.h @@ -20,7 +20,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" class QgsVectorLayer; class QgsFeatureIterator; diff --git a/src/core/qgsrelationmanager.cpp b/src/core/qgsrelationmanager.cpp index bfd95abdd77c..e077178c3624 100644 --- a/src/core/qgsrelationmanager.cpp +++ b/src/core/qgsrelationmanager.cpp @@ -111,7 +111,7 @@ QList QgsRelationManager::referencingRelations( const QgsVectorLaye bool containsField = false; Q_FOREACH ( const QgsRelation::FieldPair& fp, rel.fieldPairs() ) { - if ( fieldIdx == layer->fieldNameIndex( fp.referencingField() ) ) + if ( fieldIdx == layer->fields().lookupField( fp.referencingField() ) ) { containsField = true; break; diff --git a/src/core/qgssqlexpressioncompiler.h b/src/core/qgssqlexpressioncompiler.h index 1974217960b7..5b9bf5f62d1e 100644 --- a/src/core/qgssqlexpressioncompiler.h +++ b/src/core/qgssqlexpressioncompiler.h @@ -17,7 +17,7 @@ #define QGSSQLEXPRESSIONCOMPILER_H #include "qgsexpression.h" -#include "qgsfield.h" +#include "qgsfields.h" /** \ingroup core * \class QgsSqlExpressionCompiler diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 38d1ddb31fd1..5a0f73229a93 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -26,7 +26,7 @@ #include "qgsfeature.h" #include "qgsfeatureiterator.h" #include "qgsfeaturerequest.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgsgeometrycollection.h" #include "qgsgeometryfactory.h" @@ -259,7 +259,7 @@ QString QgsVectorDataProvider::capabilitiesString() const int QgsVectorDataProvider::fieldNameIndex( const QString& fieldName ) const { - return fields().fieldNameIndex( fieldName ); + return fields().lookupField( fieldName ); } QMap QgsVectorDataProvider::fieldNameMap() const diff --git a/src/core/qgsvectorfilewriter.cpp b/src/core/qgsvectorfilewriter.cpp index c89b425f8f3c..482fcd65856d 100644 --- a/src/core/qgsvectorfilewriter.cpp +++ b/src/core/qgsvectorfilewriter.cpp @@ -17,7 +17,7 @@ ***************************************************************************/ #include "qgsapplication.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" #include "qgsfeatureiterator.h" #include "qgsgeometry.h" @@ -2866,10 +2866,10 @@ void QgsVectorFileWriter::addRendererAttributes( QgsVectorLayer* vl, QgsAttribut QList rendererAttributes = renderer->usedAttributes(); for ( int i = 0; i < rendererAttributes.size(); ++i ) { - int index = vl->fieldNameIndex( rendererAttributes.at( i ) ); + int index = vl->fields().lookupField( rendererAttributes.at( i ) ); if ( index != -1 ) { - attList.push_back( vl->fieldNameIndex( rendererAttributes.at( i ) ) ); + attList.push_back( vl->fields().lookupField( rendererAttributes.at( i ) ) ); } } } diff --git a/src/core/qgsvectorfilewriter.h b/src/core/qgsvectorfilewriter.h index 4541961e2e08..68664ef03cca 100644 --- a/src/core/qgsvectorfilewriter.h +++ b/src/core/qgsvectorfilewriter.h @@ -19,7 +19,7 @@ #ifndef QGSVECTORFILEWRITER_H #define QGSVECTORFILEWRITER_H -#include "qgsfield.h" +#include "qgsfields.h" #include "qgssymbol.h" #include diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index e811bb7def15..52f27c3aa5e2 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -47,7 +47,7 @@ #include "qgsexpressionfieldbuffer.h" #include "qgsfeature.h" #include "qgsfeaturerequest.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometrycache.h" #include "qgsgeometry.h" #include "qgslogger.h" @@ -726,7 +726,7 @@ bool QgsVectorLayer::countSymbolFeatures( bool showProgress ) QgsFeatureRequest request; if ( !mRenderer->filterNeedsGeometry() ) request.setFlags( QgsFeatureRequest::NoGeometry ); - request.setSubsetOfAttributes( mRenderer->usedAttributes(), mUpdatedFields ); + request.setSubsetOfAttributes( mRenderer->usedAttributes(), mFields ); QgsFeatureIterator fit = getFeatures( request ); QgsVectorLayerInterruptionCheckerDuringCountSymbolFeatures interruptionCheck( &progressDialog ); if ( showProgress ) @@ -1646,7 +1646,7 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, //default expressions QDomElement defaultsElem = document.createElement( "defaults" ); - Q_FOREACH ( const QgsField& field, mUpdatedFields ) + Q_FOREACH ( const QgsField& field, mFields ) { QDomElement defaultElem = document.createElement( "default" ); defaultElem.setAttribute( "field", field.name() ); @@ -1694,7 +1694,7 @@ bool QgsVectorLayer::readSymbology( const QDomNode& node, QString& errorMessage QString displayField = node.namedItem( "displayfield" ).toElement().text(); // Try to migrate pre QGIS 3.0 display field property - if ( mUpdatedFields.fieldNameIndex( displayField ) < 0 ) + if ( mFields.lookupField( displayField ) < 0 ) { // if it's not a field, it's a maptip if ( mMapTipTemplate.isEmpty() ) @@ -1904,11 +1904,11 @@ bool QgsVectorLayer::writeSymbology( QDomNode& node, QDomDocument& doc, QString& //attribute aliases QDomElement aliasElem = doc.createElement( "aliases" ); - Q_FOREACH ( const QgsField& field, mUpdatedFields ) + Q_FOREACH ( const QgsField& field, mFields ) { QDomElement aliasEntryElem = doc.createElement( "alias" ); aliasEntryElem.setAttribute( "field", field.name() ); - aliasEntryElem.setAttribute( "index", mUpdatedFields.indexFromName( field.name() ) ); + aliasEntryElem.setAttribute( "index", mFields.indexFromName( field.name() ) ); aliasEntryElem.setAttribute( "name", field.alias() ); aliasElem.appendChild( aliasEntryElem ); } @@ -2113,12 +2113,12 @@ void QgsVectorLayer::remAttributeAlias( int attIndex ) return; QString name = fields().at( attIndex ).name(); - mUpdatedFields.at( attIndex ).setAlias( QString() ); + mFields.at( attIndex ).setAlias( QString() ); if ( mAttributeAliasMap.contains( name ) ) { mAttributeAliasMap.remove( name ); updateFields(); - mEditFormConfig.setFields( mUpdatedFields ); + mEditFormConfig.setFields( mFields ); emit layerModified(); } } @@ -2139,8 +2139,8 @@ void QgsVectorLayer::addAttributeAlias( int attIndex, const QString& aliasString QString name = fields().at( attIndex ).name(); mAttributeAliasMap.insert( name, aliasString ); - mUpdatedFields[ attIndex ].setAlias( aliasString ); - mEditFormConfig.setFields( mUpdatedFields ); + mFields[ attIndex ].setAlias( aliasString ); + mEditFormConfig.setFields( mFields ); emit layerModified(); // TODO[MD]: should have a different signal? } @@ -2154,8 +2154,8 @@ QString QgsVectorLayer::attributeAlias( int attributeIndex ) const QString QgsVectorLayer::attributeDisplayName( int attributeIndex ) const { - if ( attributeIndex >= 0 && attributeIndex < mUpdatedFields.count() ) - return mUpdatedFields.at( attributeIndex ).displayName(); + if ( attributeIndex >= 0 && attributeIndex < mFields.count() ) + return mFields.at( attributeIndex ).displayName(); else return QString(); } @@ -2176,7 +2176,7 @@ bool QgsVectorLayer::deleteAttribute( int index ) if ( index < 0 || index >= fields().count() ) return false; - if ( mUpdatedFields.fieldOrigin( index ) == QgsFields::OriginExpression ) + if ( mFields.fieldOrigin( index ) == QgsFields::OriginExpression ) { removeExpressionField( index ); return true; @@ -2247,10 +2247,10 @@ QgsAttributeList QgsVectorLayer::pkAttributeList() const QgsAttributeList pkAttributesList; QgsAttributeList providerIndexes = mDataProvider->pkAttributeIndexes(); - for ( int i = 0; i < mUpdatedFields.count(); ++i ) + for ( int i = 0; i < mFields.count(); ++i ) { - if ( mUpdatedFields.fieldOrigin( i ) == QgsFields::OriginProvider && - providerIndexes.contains( mUpdatedFields.fieldOriginIndex( i ) ) ) + if ( mFields.fieldOrigin( i ) == QgsFields::OriginProvider && + providerIndexes.contains( mFields.fieldOriginIndex( i ) ) ) pkAttributesList << i; } @@ -2627,7 +2627,7 @@ void QgsVectorLayer::setDisplayExpression( const QString& displayExpression ) QString QgsVectorLayer::displayExpression() const { - if ( !mDisplayExpression.isEmpty() || mUpdatedFields.isEmpty() ) + if ( !mDisplayExpression.isEmpty() || mFields.isEmpty() ) { return mDisplayExpression; } @@ -2635,7 +2635,7 @@ QString QgsVectorLayer::displayExpression() const { QString idxName; - Q_FOREACH ( const QgsField& field, mUpdatedFields ) + Q_FOREACH ( const QgsField& field, mFields ) { QString fldName = field.name(); @@ -2666,7 +2666,7 @@ QString QgsVectorLayer::displayExpression() const } else { - return QgsExpression::quotedColumnRef( mUpdatedFields.at( 0 ).name() ); + return QgsExpression::quotedColumnRef( mFields.at( 0 ).name() ); } } } @@ -2774,11 +2774,6 @@ void QgsVectorLayer::destroyEditCommand() } } -int QgsVectorLayer::fieldNameIndex( const QString& fieldName ) const -{ - return fields().fieldNameIndex( fieldName ); -} - bool QgsVectorLayer::addJoin( const QgsVectorJoinInfo& joinInfo ) { return mJoinBuffer && mJoinBuffer->addJoin( joinInfo ); @@ -2812,7 +2807,7 @@ int QgsVectorLayer::addExpressionField( const QString& exp, const QgsField& fld emit beforeAddingExpressionField( fld.name() ); mExpressionFieldBuffer->addExpression( exp, fld ); updateFields(); - int idx = mUpdatedFields.indexFromName( fld.name() ); + int idx = mFields.indexFromName( fld.name() ); emit attributeAdded( idx ); return idx; } @@ -2820,7 +2815,7 @@ int QgsVectorLayer::addExpressionField( const QString& exp, const QgsField& fld void QgsVectorLayer::removeExpressionField( int index ) { emit beforeRemovingExpressionField( index ); - int oi = mUpdatedFields.fieldOriginIndex( index ); + int oi = mFields.fieldOriginIndex( index ); mExpressionFieldBuffer->removeExpression( oi ); updateFields(); emit attributeDeleted( index ); @@ -2828,7 +2823,7 @@ void QgsVectorLayer::removeExpressionField( int index ) QString QgsVectorLayer::expressionField( int index ) const { - int oi = mUpdatedFields.fieldOriginIndex( index ); + int oi = mFields.fieldOriginIndex( index ); if ( oi < 0 || oi >= mExpressionFieldBuffer->expressions().size() ) return QString(); @@ -2837,7 +2832,7 @@ QString QgsVectorLayer::expressionField( int index ) const void QgsVectorLayer::updateExpressionField( int index, const QString& exp ) { - int oi = mUpdatedFields.fieldOriginIndex( index ); + int oi = mFields.fieldOriginIndex( index ); mExpressionFieldBuffer->updateExpression( oi, exp ); } @@ -2846,44 +2841,44 @@ void QgsVectorLayer::updateFields() if ( !mDataProvider ) return; - QgsFields oldFields = mUpdatedFields; + QgsFields oldFields = mFields; - mUpdatedFields = mDataProvider->fields(); + mFields = mDataProvider->fields(); // added / removed fields if ( mEditBuffer ) - mEditBuffer->updateFields( mUpdatedFields ); + mEditBuffer->updateFields( mFields ); // joined fields if ( mJoinBuffer && mJoinBuffer->containsJoins() ) - mJoinBuffer->updateFields( mUpdatedFields ); + mJoinBuffer->updateFields( mFields ); if ( mExpressionFieldBuffer ) - mExpressionFieldBuffer->updateFields( mUpdatedFields ); + mExpressionFieldBuffer->updateFields( mFields ); // set aliases and default values QMap< QString, QString >::const_iterator aliasIt = mAttributeAliasMap.constBegin(); for ( ; aliasIt != mAttributeAliasMap.constEnd(); ++aliasIt ) { - int index = mUpdatedFields.fieldNameIndex( aliasIt.key() ); + int index = mFields.lookupField( aliasIt.key() ); if ( index < 0 ) continue; - mUpdatedFields[ index ].setAlias( aliasIt.value() ); + mFields[ index ].setAlias( aliasIt.value() ); } QMap< QString, QString >::const_iterator defaultIt = mDefaultExpressionMap.constBegin(); for ( ; defaultIt != mDefaultExpressionMap.constEnd(); ++defaultIt ) { - int index = mUpdatedFields.fieldNameIndex( defaultIt.key() ); + int index = mFields.lookupField( defaultIt.key() ); if ( index < 0 ) continue; - mUpdatedFields[ index ].setDefaultValueExpression( defaultIt.value() ); + mFields[ index ].setDefaultValueExpression( defaultIt.value() ); } - if ( oldFields != mUpdatedFields ) + if ( oldFields != mFields ) { emit updatedFields(); - mEditFormConfig.setFields( mUpdatedFields ); + mEditFormConfig.setFields( mFields ); } } @@ -2898,10 +2893,10 @@ void QgsVectorLayer::createJoinCaches() const QVariant QgsVectorLayer::defaultValue( int index, const QgsFeature& feature, QgsExpressionContext* context ) const { - if ( index < 0 || index >= mUpdatedFields.count() ) + if ( index < 0 || index >= mFields.count() ) return QVariant(); - QString expression = mUpdatedFields.at( index ).defaultValueExpression(); + QString expression = mFields.at( index ).defaultValueExpression(); if ( expression.isEmpty() ) return mDataProvider->defaultValue( index ); @@ -2947,26 +2942,26 @@ QVariant QgsVectorLayer::defaultValue( int index, const QgsFeature& feature, Qgs void QgsVectorLayer::setDefaultValueExpression( int index, const QString& expression ) { - if ( index < 0 || index >= mUpdatedFields.count() ) + if ( index < 0 || index >= mFields.count() ) return; if ( expression.isEmpty() ) { - mDefaultExpressionMap.remove( mUpdatedFields.at( index ).name() ); + mDefaultExpressionMap.remove( mFields.at( index ).name() ); } else { - mDefaultExpressionMap.insert( mUpdatedFields.at( index ).name(), expression ); + mDefaultExpressionMap.insert( mFields.at( index ).name(), expression ); } updateFields(); } QString QgsVectorLayer::defaultValueExpression( int index ) const { - if ( index < 0 || index >= mUpdatedFields.count() ) + if ( index < 0 || index >= mFields.count() ) return QString(); else - return mUpdatedFields.at( index ).defaultValueExpression(); + return mFields.at( index ).defaultValueExpression(); } void QgsVectorLayer::uniqueValues( int index, QList &uniqueValues, int limit ) const @@ -2977,7 +2972,7 @@ void QgsVectorLayer::uniqueValues( int index, QList &uniqueValues, int return; } - QgsFields::FieldOrigin origin = mUpdatedFields.fieldOrigin( index ); + QgsFields::FieldOrigin origin = mFields.fieldOrigin( index ); switch ( origin ) { case QgsFields::OriginUnknown: @@ -3082,7 +3077,7 @@ QVariant QgsVectorLayer::minimumValue( int index ) const return QVariant(); } - QgsFields::FieldOrigin origin = mUpdatedFields.fieldOrigin( index ); + QgsFields::FieldOrigin origin = mFields.fieldOrigin( index ); switch ( origin ) { @@ -3170,7 +3165,7 @@ QVariant QgsVectorLayer::maximumValue( int index ) const return QVariant(); } - QgsFields::FieldOrigin origin = mUpdatedFields.fieldOrigin( index ); + QgsFields::FieldOrigin origin = mFields.fieldOrigin( index ); switch ( origin ) { case QgsFields::OriginUnknown: @@ -3260,12 +3255,12 @@ QVariant QgsVectorLayer::aggregate( QgsAggregateCalculator::Aggregate aggregate, } // test if we are calculating based on a field - int attrIndex = mUpdatedFields.fieldNameIndex( fieldOrExpression ); + int attrIndex = mFields.lookupField( fieldOrExpression ); if ( attrIndex >= 0 ) { // aggregate is based on a field - if it's a provider field, we could possibly hand over the calculation // to the provider itself - QgsFields::FieldOrigin origin = mUpdatedFields.fieldOrigin( attrIndex ); + QgsFields::FieldOrigin origin = mFields.fieldOrigin( attrIndex ); if ( origin == QgsFields::OriginProvider ) { bool providerOk = false; @@ -3293,7 +3288,7 @@ QList QgsVectorLayer::getValues( const QString &fieldOrExpression, boo QScopedPointer expression; QgsExpressionContext context; - int attrNum = fieldNameIndex( fieldOrExpression ); + int attrNum = mFields.lookupField( fieldOrExpression ); if ( attrNum == -1 ) { @@ -3486,7 +3481,7 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) setCustomProperty( "labeling/fieldName", labelAttribute ); setCustomProperty( "labeling/isExpression", false ); - int fieldIndex = fieldNameIndex( labelAttribute ); + int fieldIndex = mFields.lookupField( labelAttribute ); if ( fieldIndex == -1 ) { // label attribute is not in columns, check if it is an expression diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 2fbe929247e1..b68fbf69c454 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -31,7 +31,7 @@ #include "qgsfeature.h" #include "qgsfeaturerequest.h" #include "qgseditorwidgetconfig.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgssnapper.h" #include "qgsvectorsimplifymethod.h" #include "qgseditformconfig.h" @@ -1128,7 +1128,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * * @return A list of fields */ - inline QgsFields fields() const { return mUpdatedFields; } + inline QgsFields fields() const { return mFields; } /** * Returns the list of fields of this layer. @@ -1137,19 +1137,19 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * * @return A list of fields */ - inline QgsFields pendingFields() const { return mUpdatedFields; } + inline QgsFields pendingFields() const { return mFields; } /** * Returns list of attribute indexes. i.e. a list from 0 ... fieldCount() * Alias for {@link attributeList()} */ - inline QgsAttributeList pendingAllAttributesList() const { return mUpdatedFields.allAttributesList(); } + inline QgsAttributeList pendingAllAttributesList() const { return mFields.allAttributesList(); } /** * Returns list of attribute indexes. i.e. a list from 0 ... fieldCount() * Alias for {@link attributeList()} */ - inline QgsAttributeList attributeList() const { return mUpdatedFields.allAttributesList(); } + inline QgsAttributeList attributeList() const { return mFields.allAttributesList(); } /** * Returns list of attributes making up the primary key @@ -1331,9 +1331,6 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte /** Destroy active command and reverts all changes in it */ void destroyEditCommand(); - /** Returns the index of a field name or -1 if the field does not exist */ - int fieldNameIndex( const QString& fieldName ) const; - /** Editing vertex markers */ enum VertexMarkerType { @@ -1917,7 +1914,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte QgsFeatureIds mSelectedFeatureIds; /** Field map to commit */ - QgsFields mUpdatedFields; + QgsFields mFields; /** Map that stores the aliases for attributes. Key is the attribute name and value the alias for that attribute*/ QgsStringMap mAttributeAliasMap; diff --git a/src/core/qgsvectorlayereditbuffer.cpp b/src/core/qgsvectorlayereditbuffer.cpp index f768ca66e1b4..387de922bccc 100644 --- a/src/core/qgsvectorlayereditbuffer.cpp +++ b/src/core/qgsvectorlayereditbuffer.cpp @@ -120,7 +120,7 @@ bool QgsVectorLayerEditBuffer::addFeature( QgsFeature& f ) { return false; } - if ( L->mUpdatedFields.count() != f.attributes().count() ) + if ( L->mFields.count() != f.attributes().count() ) return false; // TODO: check correct geometry type diff --git a/src/core/qgsvectorlayereditbuffer.h b/src/core/qgsvectorlayereditbuffer.h index a73920253833..4c91678278c1 100644 --- a/src/core/qgsvectorlayereditbuffer.h +++ b/src/core/qgsvectorlayereditbuffer.h @@ -19,7 +19,7 @@ #include #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" class QgsVectorLayer; diff --git a/src/core/qgsvectorlayerfeatureiterator.cpp b/src/core/qgsvectorlayerfeatureiterator.cpp index ba939d29ca4f..12cafd69d64c 100644 --- a/src/core/qgsvectorlayerfeatureiterator.cpp +++ b/src/core/qgsvectorlayerfeatureiterator.cpp @@ -105,12 +105,9 @@ QgsVectorLayerFeatureIterator::QgsVectorLayerFeatureIterator( QgsVectorLayerFeat if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) { //ensure that all fields required for filter expressions are prepared - Q_FOREACH ( const QString& field, mRequest.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !mRequest.subsetOfAttributes().contains( attrIdx ) ) - mRequest.setSubsetOfAttributes( mRequest.subsetOfAttributes() << attrIdx ); - } + QSet attributeIndexes = mRequest.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += mRequest.subsetOfAttributes().toSet(); + mRequest.setSubsetOfAttributes( attributeIndexes.toList() ); } } @@ -129,7 +126,8 @@ QgsVectorLayerFeatureIterator::QgsVectorLayerFeatureIterator( QgsVectorLayerFeat int nPendingFields = mSource->mFields.count(); Q_FOREACH ( int attrIndex, subset ) { - if ( attrIndex < 0 || attrIndex >= nPendingFields ) continue; + if ( attrIndex < 0 || attrIndex >= nPendingFields ) + continue; if ( mSource->mFields.fieldOrigin( attrIndex ) == QgsFields::OriginProvider ) providerSubset << mSource->mFields.fieldOriginIndex( attrIndex ); } @@ -143,7 +141,7 @@ QgsVectorLayerFeatureIterator::QgsVectorLayerFeatureIterator( QgsVectorLayerFeat { Q_FOREACH ( const QString& attr, mProviderRequest.orderBy().usedAttributes() ) { - providerSubset << mSource->mFields.fieldNameIndex( attr ); + providerSubset << mSource->mFields.lookupField( attr ); } } @@ -154,7 +152,7 @@ QgsVectorLayerFeatureIterator::QgsVectorLayerFeatureIterator( QgsVectorLayerFeat { Q_FOREACH ( const QString& field, mProviderRequest.filterExpression()->referencedColumns() ) { - int idx = source->mFields.fieldNameIndex( field ); + int idx = source->mFields.lookupField( field ); // If there are fields in the expression which are not of origin provider, the provider will not be able to filter based on them. // In this case we disable the expression filter. @@ -538,7 +536,7 @@ void QgsVectorLayerFeatureIterator::prepareExpression( int fieldIdx ) Q_FOREACH ( const QString& col, exp->referencedColumns() ) { - int dependantFieldIdx = mSource->mFields.fieldNameIndex( col ); + int dependantFieldIdx = mSource->mFields.lookupField( col ); if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) { mRequest.setSubsetOfAttributes( mRequest.subsetOfAttributes() << dependantFieldIdx ); diff --git a/src/core/qgsvectorlayerfeatureiterator.h b/src/core/qgsvectorlayerfeatureiterator.h index 26a32f474aa3..8f7666693ffd 100644 --- a/src/core/qgsvectorlayerfeatureiterator.h +++ b/src/core/qgsvectorlayerfeatureiterator.h @@ -16,7 +16,7 @@ #define QGSVECTORLAYERFEATUREITERATOR_H #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" #include diff --git a/src/core/qgsvectorlayerimport.cpp b/src/core/qgsvectorlayerimport.cpp index f66733b655bb..0f6f0376a5db 100644 --- a/src/core/qgsvectorlayerimport.cpp +++ b/src/core/qgsvectorlayerimport.cpp @@ -16,7 +16,7 @@ * * ***************************************************************************/ -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" #include "qgsfeatureiterator.h" #include "qgsgeometry.h" diff --git a/src/core/qgsvectorlayerjoinbuffer.cpp b/src/core/qgsvectorlayerjoinbuffer.cpp index 0d9c2f81b061..b3d4c099744a 100644 --- a/src/core/qgsvectorlayerjoinbuffer.cpp +++ b/src/core/qgsvectorlayerjoinbuffer.cpp @@ -192,7 +192,7 @@ QVector QgsVectorLayerJoinBuffer::joinSubsetIndices( QgsVectorLayer* joinLa for ( int i = 0; i < joinFieldsSubset.count(); ++i ) { QString joinedFieldName = joinFieldsSubset.at( i ); - int index = fields.fieldNameIndex( joinedFieldName ); + int index = fields.lookupField( joinedFieldName ); if ( index != -1 ) { subsetIndices.append( index ); diff --git a/src/core/qgsvectorlayerlabelprovider.cpp b/src/core/qgsvectorlayerlabelprovider.cpp index e74dc474f3b5..3dedaab2520d 100644 --- a/src/core/qgsvectorlayerlabelprovider.cpp +++ b/src/core/qgsvectorlayerlabelprovider.cpp @@ -154,7 +154,7 @@ bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QStr else { // If we aren't an expression, we check to see if we can find the column. - if ( mFields.fieldNameIndex( lyr.fieldName ) == -1 ) + if ( mFields.lookupField( lyr.fieldName ) == -1 ) { return false; } @@ -218,7 +218,7 @@ bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QStr lyr.rasterCompressFactor = context.rasterScaleFactor(); // save the pal layer to our layer context (with some additional info) - lyr.fieldIndex = mFields.fieldNameIndex( lyr.fieldName ); + lyr.fieldIndex = mFields.lookupField( lyr.fieldName ); lyr.xform = &mapSettings.mapToPixel(); lyr.ct = QgsCoordinateTransform(); diff --git a/src/core/qgsvectorlayerrenderer.h b/src/core/qgsvectorlayerrenderer.h index 412b2dce3577..70774e2090cc 100644 --- a/src/core/qgsvectorlayerrenderer.h +++ b/src/core/qgsvectorlayerrenderer.h @@ -34,7 +34,7 @@ class QgsSingleSymbolRenderer; typedef QList QgsAttributeList; #include "qgis.h" -#include "qgsfield.h" // QgsFields +#include "qgsfields.h" // QgsFields #include "qgsfeature.h" // QgsFeatureIds #include "qgsfeatureiterator.h" #include "qgsvectorsimplifymethod.h" diff --git a/src/core/qgsvectorlayerundocommand.h b/src/core/qgsvectorlayerundocommand.h index e3e0ecbd1eb6..c4daee3f17e0 100644 --- a/src/core/qgsvectorlayerundocommand.h +++ b/src/core/qgsvectorlayerundocommand.h @@ -22,7 +22,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" class QgsGeometry; diff --git a/src/core/qgsvirtuallayerdefinition.h b/src/core/qgsvirtuallayerdefinition.h index eec5191211ad..af04f5f05df0 100644 --- a/src/core/qgsvirtuallayerdefinition.h +++ b/src/core/qgsvirtuallayerdefinition.h @@ -17,8 +17,8 @@ email : hugo dot mercier at oslandia dot com #ifndef QGSVIRTUALLAYERDEFINITION_H #define QGSVIRTUALLAYERDEFINITION_H -#include -#include +#include "qgsfields.h" +#include "qgis.h" /** \ingroup core * Class to manipulate the definition of a virtual layer @@ -143,7 +143,7 @@ class CORE_EXPORT QgsVirtualLayerDefinition void setGeometrySrid( long srid ) { mGeometrySrid = srid; } //! Get field definitions - const QgsFields& fields() const { return mFields; } + QgsFields fields() const { return mFields; } //! Set field definitions void setFields( const QgsFields& fields ) { mFields = fields; } diff --git a/src/core/qgsvirtuallayerdefinitionutils.cpp b/src/core/qgsvirtuallayerdefinitionutils.cpp index 02c8f6bc760b..6a559fdfc7f0 100644 --- a/src/core/qgsvirtuallayerdefinitionutils.cpp +++ b/src/core/qgsvirtuallayerdefinitionutils.cpp @@ -39,7 +39,7 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinitionUtils::fromJoinedLayer( QgsVe { // find an uid name QString uid = "uid"; - while ( fields.fieldNameIndex( uid ) != -1 ) + while ( fields.lookupField( uid ) != -1 ) uid += "_"; // add "_" each time this name already exists // add a column diff --git a/src/core/raster/qgsrasterdataprovider.h b/src/core/raster/qgsrasterdataprovider.h index a6d8e420c486..135ecfdbb481 100644 --- a/src/core/raster/qgsrasterdataprovider.h +++ b/src/core/raster/qgsrasterdataprovider.h @@ -31,7 +31,7 @@ #include "qgscolorrampshader.h" #include "qgsdataprovider.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsraster.h" #include "qgsrasterinterface.h" #include "qgsrasterpyramid.h" diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp index 3a9e2ed8062f..b697010ae243 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp @@ -395,7 +395,7 @@ void QgsCategorizedSymbolRenderer::startRender( QgsRenderContext& context, const rebuildHash(); // find out classification attribute index from name - mAttrNum = fields.fieldNameIndex( mAttrName ); + mAttrNum = fields.lookupField( mAttrName ); if ( mAttrNum == -1 ) { mExpression.reset( new QgsExpression( mAttrName ) ); @@ -494,7 +494,7 @@ void QgsCategorizedSymbolRenderer::toSld( QDomDocument &doc, QDomElement &elemen QString QgsCategorizedSymbolRenderer::filter( const QgsFields& fields ) { - int attrNum = fields.fieldNameIndex( mAttrName ); + int attrNum = fields.lookupField( mAttrName ); bool isExpression = ( attrNum == -1 ); bool hasDefault = false; diff --git a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp index d03c26ffa4bf..884acdd4a0ac 100644 --- a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp @@ -383,7 +383,7 @@ void QgsGraduatedSymbolRenderer::startRender( QgsRenderContext& context, const Q mCounting = context.rendererScale() == 0.0; // find out classification attribute index from name - mAttrNum = fields.fieldNameIndex( mAttrName ); + mAttrNum = fields.lookupField( mAttrName ); if ( mAttrNum == -1 ) { @@ -804,7 +804,7 @@ QgsGraduatedSymbolRenderer* QgsGraduatedSymbolRenderer::createRenderer( return r; } -void QgsGraduatedSymbolRenderer::updateClasses( QgsVectorLayer *vlayer, Mode mode, int nclasses ) +void QgsGraduatedSymbolRenderer::updateClasses( QgsVectorLayer* vlayer, Mode mode, int nclasses ) { if ( mAttrName.isEmpty() ) return; @@ -822,7 +822,7 @@ void QgsGraduatedSymbolRenderer::updateClasses( QgsVectorLayer *vlayer, Mode mod double minimum; double maximum; - int attrNum = vlayer->fieldNameIndex( mAttrName ); + int attrNum = vlayer->fields().lookupField( mAttrName ); bool ok; if ( attrNum == -1 ) diff --git a/src/core/symbology-ng/qgsheatmaprenderer.cpp b/src/core/symbology-ng/qgsheatmaprenderer.cpp index b416bfab5c80..bc065011a257 100644 --- a/src/core/symbology-ng/qgsheatmaprenderer.cpp +++ b/src/core/symbology-ng/qgsheatmaprenderer.cpp @@ -73,7 +73,7 @@ void QgsHeatmapRenderer::startRender( QgsRenderContext& context, const QgsFields } // find out classification attribute index from name - mWeightAttrNum = fields.fieldNameIndex( mWeightExpressionString ); + mWeightAttrNum = fields.lookupField( mWeightExpressionString ); if ( mWeightAttrNum == -1 ) { mWeightExpression.reset( new QgsExpression( mWeightExpressionString ) ); diff --git a/src/core/symbology-ng/qgsrenderer.h b/src/core/symbology-ng/qgsrenderer.h index ff852f4277ed..55494d7598ea 100644 --- a/src/core/symbology-ng/qgsrenderer.h +++ b/src/core/symbology-ng/qgsrenderer.h @@ -20,7 +20,7 @@ #include "qgsrectangle.h" #include "qgsrendercontext.h" #include "qgssymbol.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeaturerequest.h" #include diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.h b/src/core/symbology-ng/qgsrulebasedrenderer.h index 3de9d577bd73..57be8f7463c2 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.h +++ b/src/core/symbology-ng/qgsrulebasedrenderer.h @@ -16,7 +16,7 @@ #ifndef QGSRULEBASEDRENDERERV2_H #define QGSRULEBASEDRENDERERV2_H -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" #include "qgis.h" diff --git a/src/core/symbology-ng/qgssymbol.h b/src/core/symbology-ng/qgssymbol.h index d4cc601bb488..eebca22f909d 100644 --- a/src/core/symbology-ng/qgssymbol.h +++ b/src/core/symbology-ng/qgssymbol.h @@ -22,7 +22,7 @@ #include "qgsmapunitscale.h" #include "qgspointv2.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" class QColor; class QImage; diff --git a/src/core/symbology-ng/qgssymbollayer.cpp b/src/core/symbology-ng/qgssymbollayer.cpp index 8ebe47891a11..ccd7cc86e142 100644 --- a/src/core/symbology-ng/qgssymbollayer.cpp +++ b/src/core/symbology-ng/qgssymbollayer.cpp @@ -179,7 +179,7 @@ QVariant QgsSymbolLayer::evaluateDataDefinedProperty( const QString& property, c } else if ( context.feature() && !dd->field().isEmpty() && !mFields.isEmpty() ) { - int attributeIndex = mFields.fieldNameIndex( dd->field() ); + int attributeIndex = mFields.lookupField( dd->field() ); if ( attributeIndex >= 0 ) { if ( ok ) diff --git a/src/core/symbology-ng/qgssymbollayer.h b/src/core/symbology-ng/qgssymbollayer.h index 776a1d67087a..eb50fb460c16 100644 --- a/src/core/symbology-ng/qgssymbollayer.h +++ b/src/core/symbology-ng/qgssymbollayer.h @@ -32,7 +32,7 @@ #include "qgssymbol.h" #include "qgssymbollayerutils.h" // QgsStringMap -#include "qgsfield.h" +#include "qgsfields.h" class QPainter; class QSize; diff --git a/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp b/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp index 3477a15fbfa6..2db2b6806987 100644 --- a/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp +++ b/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp @@ -213,8 +213,8 @@ void QgsVectorFieldSymbolLayer::startRender( QgsSymbolRenderContext& context ) QgsFields fields = context.fields(); if ( !fields.isEmpty() ) { - mXIndex = fields.fieldNameIndex( mXAttribute ); - mYIndex = fields.fieldNameIndex( mYAttribute ); + mXIndex = fields.lookupField( mXAttribute ); + mYIndex = fields.lookupField( mYAttribute ); } else { diff --git a/src/gui/attributetable/qgsattributetablefiltermodel.cpp b/src/gui/attributetable/qgsattributetablefiltermodel.cpp index 446d18196db1..83b24f797cf8 100644 --- a/src/gui/attributetable/qgsattributetablefiltermodel.cpp +++ b/src/gui/attributetable/qgsattributetablefiltermodel.cpp @@ -134,7 +134,7 @@ void QgsAttributeTableFilterModel::setAttributeTableConfig( const QgsAttributeTa continue; // The new value for the mapping (field index or -1 for action column) - int newValue = ( columnConfig.type == QgsAttributeTableConfig::Action ) ? -1 : layer()->fieldNameIndex( columnConfig.name ); + int newValue = ( columnConfig.type == QgsAttributeTableConfig::Action ) ? -1 : layer()->fields().lookupField( columnConfig.name ); newColumnMapping << newValue; } diff --git a/src/gui/attributetable/qgsattributetablemodel.cpp b/src/gui/attributetable/qgsattributetablemodel.cpp index 0e16d11b2646..b6f8755b284c 100644 --- a/src/gui/attributetable/qgsattributetablemodel.cpp +++ b/src/gui/attributetable/qgsattributetablemodel.cpp @@ -23,7 +23,7 @@ #include "qgsexpression.h" #include "qgsfeatureiterator.h" #include "qgsconditionalstyle.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgslogger.h" #include "qgsmapcanvas.h" #include "qgsmaplayeractionregistry.h" @@ -432,7 +432,7 @@ void QgsAttributeTableModel::fieldConditionalStyleChanged( const QString &fieldN return; } - int fieldIndex = mLayerCache->layer()->fieldNameIndex( fieldName ); + int fieldIndex = mLayerCache->layer()->fields().lookupField( fieldName ); if ( fieldIndex == -1 ) return; @@ -788,7 +788,7 @@ void QgsAttributeTableModel::prefetchSortData( const QString& expressionString ) if ( mSortCacheExpression.isField() ) { QString fieldName = static_cast( mSortCacheExpression.rootNode() )->name(); - mSortFieldIndex = mLayerCache->layer()->fieldNameIndex( fieldName ); + mSortFieldIndex = mLayerCache->layer()->fields().lookupField( fieldName ); } if ( mSortFieldIndex == -1 ) @@ -797,7 +797,7 @@ void QgsAttributeTableModel::prefetchSortData( const QString& expressionString ) Q_FOREACH ( const QString& col, mSortCacheExpression.referencedColumns() ) { - mSortCacheAttributes.append( mLayerCache->layer()->fieldNameIndex( col ) ); + mSortCacheAttributes.append( mLayerCache->layer()->fields().lookupField( col ) ); } } else diff --git a/src/gui/attributetable/qgsdualview.cpp b/src/gui/attributetable/qgsdualview.cpp index 81b8021cb65d..afd5fb61de24 100644 --- a/src/gui/attributetable/qgsdualview.cpp +++ b/src/gui/attributetable/qgsdualview.cpp @@ -138,7 +138,7 @@ void QgsDualView::columnBoxInit() Q_FOREACH ( const QgsField& field, fields ) { - int fieldIndex = mLayerCache->layer()->fieldNameIndex( field.name() ); + int fieldIndex = mLayerCache->layer()->fields().lookupField( field.name() ); if ( fieldIndex == -1 ) continue; diff --git a/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp b/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp index 5728b3e581ba..1f95fca6df07 100644 --- a/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp +++ b/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp @@ -36,7 +36,7 @@ #include "qgsexpressionselectiondialog.h" #include "qgsfeaturelistmodel.h" #include "qgsrubberband.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgseditorwidgetregistry.h" @@ -65,7 +65,7 @@ QgsOrganizeTableColumnsDialog::QgsOrganizeTableColumnsDialog( const QgsVectorLay } else { - int idx = vl->fieldNameIndex( columnConfig.name ); + int idx = vl->fields().lookupField( columnConfig.name ); item = new QListWidgetItem( vl->attributeDisplayName( idx ), mFieldsList ); switch ( vl->fields().fieldOrigin( idx ) ) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp index e0ef2e3027bb..63a496f5c0ff 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp @@ -31,7 +31,7 @@ class FromFactoriesPlugin: public QgsEditorWidgetAutoConfPlugin const QMap factories = QgsEditorWidgetRegistry::instance()->factories(); for ( QMap::const_iterator i = factories.begin(); i != factories.end(); ++i ) { - const int index = vl->fieldNameIndex( fieldName ); + const int index = vl->fields().lookupField( fieldName ); if ( index >= 0 ) { const int score = i.value()->fieldScore( vl, index ); @@ -109,4 +109,4 @@ void QgsEditorWidgetAutoConf::registerPlugin( QgsEditorWidgetAutoConfPlugin* plu { plugins.append( QSharedPointer( plugin ) ); } -///@endcond \ No newline at end of file +///@endcond diff --git a/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp b/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp index 0abafe644bbf..d9a8dfe82d27 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp @@ -16,7 +16,7 @@ #include "qgseditorwidgetfactory.h" #include "qgsdefaultsearchwidgetwrapper.h" #include "qgssearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectordataprovider.h" #include diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index 6bf98260082a..caf87a9dae92 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -244,7 +244,7 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle QString name = editTypeElement.attribute( "name" ); - int idx = vectorLayer->fieldNameIndex( name ); + int idx = vectorLayer->fields().lookupField( name ); if ( idx == -1 ) continue; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index ab2b2f4a090d..4eb28e16ced2 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -16,7 +16,7 @@ #include "qgseditorwidgetwrapper.h" #include "qgsvectorlayer.h" #include "qgsvectordataprovider.h" -#include "qgsfield.h" +#include "qgsfields.h" #include diff --git a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp index 58d57f7c0840..fec5a7bf71bb 100644 --- a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp @@ -16,7 +16,7 @@ #include "qgssearchwidgetwrapper.h" #include "qgsvectorlayer.h" #include "qgsvectordataprovider.h" -#include "qgsfield.h" +#include "qgsfields.h" #include diff --git a/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp index b8201df77e2d..2ffa882f5279 100644 --- a/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp @@ -15,7 +15,7 @@ #include "qgscheckboxsearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgscheckboxwidgetfactory.h" #include "qgsvectorlayer.h" diff --git a/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp index e313b61a1471..1ad54ed818f7 100644 --- a/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp @@ -15,7 +15,7 @@ #include "qgsdatetimesearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsdatetimeeditfactory.h" #include "qgsvectorlayer.h" #include "qgsdatetimeedit.h" diff --git a/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp index 860114c02be6..31970389d7b2 100644 --- a/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp @@ -15,7 +15,7 @@ #include "qgsdefaultsearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfieldvalidator.h" #include "qgsexpression.h" #include diff --git a/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp b/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp index c1d08f30e8e5..91dd023311af 100644 --- a/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp @@ -16,7 +16,7 @@ #include "qgskeyvaluewidgetfactory.h" #include "qgskeyvaluewidgetwrapper.h" #include "qgsdummyconfigdlg.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorlayer.h" #include diff --git a/src/gui/editorwidgets/qgslistwidgetfactory.cpp b/src/gui/editorwidgets/qgslistwidgetfactory.cpp index 708d4990fc61..d5a52883b636 100644 --- a/src/gui/editorwidgets/qgslistwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgslistwidgetfactory.cpp @@ -16,7 +16,7 @@ #include "qgslistwidgetfactory.h" #include "qgslistwidgetwrapper.h" #include "qgsdummyconfigdlg.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorlayer.h" #include "qgseditorwidgetregistry.h" diff --git a/src/gui/editorwidgets/qgsmultiedittoolbutton.h b/src/gui/editorwidgets/qgsmultiedittoolbutton.h index 9aeaa289d65c..b8e78042e34e 100644 --- a/src/gui/editorwidgets/qgsmultiedittoolbutton.h +++ b/src/gui/editorwidgets/qgsmultiedittoolbutton.h @@ -16,7 +16,7 @@ #ifndef QGSMULTIEDITTOOLBUTTON_H #define QGSMULTIEDITTOOLBUTTON_H -#include "qgsfield.h" +#include "qgsfields.h" #include /** \ingroup gui diff --git a/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp b/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp index 92dc346017b4..fea6ad17b5cc 100644 --- a/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp @@ -16,7 +16,7 @@ #include "qgsrelationreferenceconfigdlg.h" #include "qgseditorwidgetfactory.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsproject.h" #include "qgsrelationmanager.h" #include "qgsvectorlayer.h" diff --git a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp index ee7e91315136..e718d4430fc9 100644 --- a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp @@ -138,7 +138,7 @@ QString QgsRelationReferenceFactory::representValue( QgsVectorLayer* vl, int fie QgsDebugMsg( "representValue() with inconsistent vl parameter w.r.t relation referencingLayer" ); return value.toString(); } - int referencingFieldIdx = referencingLayer->fieldNameIndex( relation.fieldPairs().at( 0 ).first ); + int referencingFieldIdx = referencingLayer->fields().lookupField( relation.fieldPairs().at( 0 ).first ); if ( referencingFieldIdx != fieldIdx ) { QgsDebugMsg( "representValue() with inconsistent fieldIdx parameter w.r.t relation referencingFieldIdx" ); @@ -171,7 +171,7 @@ QString QgsRelationReferenceFactory::representValue( QgsVectorLayer* vl, int fie QString title = expr.evaluate( &context ).toString(); if ( expr.hasEvalError() ) { - int referencedFieldIdx = referencedLayer->fieldNameIndex( relation.fieldPairs().at( 0 ).second ); + int referencedFieldIdx = referencedLayer->fields().lookupField( relation.fieldPairs().at( 0 ).second ); title = feature.attribute( referencedFieldIdx ).toString(); } return title; diff --git a/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp index 079703c332ad..cd74a2ea60c3 100644 --- a/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp @@ -15,7 +15,7 @@ #include "qgsrelationreferencesearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsmaplayerregistry.h" #include "qgsvaluerelationwidgetfactory.h" #include "qgsvectorlayer.h" diff --git a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp index 6592e36f9955..c39132d5753d 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp @@ -28,7 +28,7 @@ #include "qgseditorwidgetfactory.h" #include "qgsexpression.h" #include "qgsfeaturelistmodel.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgshighlight.h" #include "qgsmapcanvas.h" @@ -193,8 +193,8 @@ void QgsRelationReferenceWidget::setRelation( const QgsRelation& relation, bool mReferencingLayer = relation.referencingLayer(); mRelationName = relation.name(); mReferencedLayer = relation.referencedLayer(); - mReferencedFieldIdx = mReferencedLayer->fieldNameIndex( relation.fieldPairs().at( 0 ).second ); - mReferencingFieldIdx = mReferencingLayer->fieldNameIndex( relation.fieldPairs().at( 0 ).first ); + mReferencedFieldIdx = mReferencedLayer->fields().lookupField( relation.fieldPairs().at( 0 ).second ); + mReferencingFieldIdx = mReferencingLayer->fields().lookupField( relation.fieldPairs().at( 0 ).first ); QgsAttributeEditorContext context( mEditorContext, relation, QgsAttributeEditorContext::Single, QgsAttributeEditorContext::Embed ); @@ -251,7 +251,7 @@ void QgsRelationReferenceWidget::setForeignKey( const QVariant& value ) // Attributes from the referencing layer QgsAttributes attrs = QgsAttributes( mReferencingLayer->fields().count() ); // Set the value on the foreign key field of the referencing record - attrs[ mReferencingLayer->fieldNameIndex( mRelation.fieldPairs().at( 0 ).first )] = value; + attrs[ mReferencingLayer->fields().lookupField( mRelation.fieldPairs().at( 0 ).first )] = value; QgsFeatureRequest request = mRelation.getReferencedFeatureRequest( attrs ); @@ -468,7 +468,7 @@ void QgsRelationReferenceWidget::init() Q_FOREACH ( const QString& fieldName, mFilterFields ) { QVariantList uniqueValues; - int idx = mReferencedLayer->fieldNameIndex( fieldName ); + int idx = mReferencedLayer->fields().lookupField( fieldName ); QComboBox* cb = new QComboBox(); cb->setProperty( "Field", fieldName ); cb->setProperty( "FieldAlias", mReferencedLayer->attributeDisplayName( idx ) ); @@ -523,7 +523,7 @@ void QgsRelationReferenceWidget::init() QgsAttributeList attributes; Q_FOREACH ( const QString& attr, requestedAttrs ) - attributes << mReferencedLayer->fieldNameIndex( attr ); + attributes << mReferencedLayer->fields().lookupField( attr ); layerCache->setCacheSubsetOfAttributes( attributes ); mMasterModel = new QgsAttributeTableModel( layerCache ); @@ -859,7 +859,7 @@ void QgsRelationReferenceWidget::filterChanged() filters << QString( "\"%1\" = %2" ).arg( fieldName, cb->currentText() ); } } - attrs << mReferencedLayer->fieldNameIndex( fieldName ); + attrs << mReferencedLayer->fields().lookupField( fieldName ); } } @@ -886,7 +886,7 @@ void QgsRelationReferenceWidget::addEntry() // if custom text is in the combobox and the displayExpression is simply a field, use the current text for the new feature if ( mComboBox->itemText( mComboBox->currentIndex() ) != mComboBox->currentText() ) { - int fieldIdx = mReferencedLayer->fieldNameIndex( mReferencedLayer->displayExpression() ); + int fieldIdx = mReferencedLayer->fields().lookupField( mReferencedLayer->displayExpression() ); if ( fieldIdx != -1 ) { diff --git a/src/gui/editorwidgets/qgstexteditsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgstexteditsearchwidgetwrapper.cpp index b627e4502c71..d60f5b9295bc 100644 --- a/src/gui/editorwidgets/qgstexteditsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgstexteditsearchwidgetwrapper.cpp @@ -15,7 +15,7 @@ #include "qgstexteditsearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorlayer.h" QgsTextEditSearchWidgetWrapper::QgsTextEditSearchWidgetWrapper( QgsVectorLayer* vl, int fieldIdx, QWidget* parent ) diff --git a/src/gui/editorwidgets/qgstexteditwrapper.cpp b/src/gui/editorwidgets/qgstexteditwrapper.cpp index 87e76ea7a958..033da9bcee1c 100644 --- a/src/gui/editorwidgets/qgstexteditwrapper.cpp +++ b/src/gui/editorwidgets/qgstexteditwrapper.cpp @@ -15,7 +15,7 @@ #include "qgstexteditwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfieldvalidator.h" #include "qgsfilterlineedit.h" diff --git a/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp index edf48680b16c..e94aed1c5a96 100644 --- a/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp @@ -17,7 +17,7 @@ #include "qgstexteditconfigdlg.h" #include "qgsvaluemapconfigdlg.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfieldvalidator.h" #include diff --git a/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp index add39fd11e91..41b440917e40 100644 --- a/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp @@ -15,7 +15,7 @@ #include "qgsvaluerelationsearchwidgetwrapper.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsmaplayerregistry.h" #include "qgsvaluerelationwidgetfactory.h" #include "qgsvectorlayer.h" diff --git a/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp index 7cee02c98f82..0fee631e1393 100644 --- a/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp @@ -16,7 +16,7 @@ #include "qgsvaluerelationwidgetwrapper.h" #include "qgis.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsmaplayerregistry.h" #include "qgsvaluerelationwidgetfactory.h" #include "qgsvectorlayer.h" @@ -197,8 +197,8 @@ QgsValueRelationWidgetWrapper::ValueRelationCache QgsValueRelationWidgetWrapper: if ( !layer ) return cache; - int ki = layer->fieldNameIndex( config.value( "Key" ).toString() ); - int vi = layer->fieldNameIndex( config.value( "Value" ).toString() ); + int ki = layer->fields().lookupField( config.value( "Key" ).toString() ); + int vi = layer->fields().lookupField( config.value( "Value" ).toString() ); QgsFeatureRequest request; diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 7c26c47a0b49..962e47278840 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -1219,7 +1219,7 @@ void QgsAttributeForm::init() int row = 0; Q_FOREACH ( const QgsField& field, mLayer->fields().toList() ) { - int idx = mLayer->fieldNameIndex( field.name() ); + int idx = mLayer->fields().lookupField( field.name() ); if ( idx < 0 ) continue; @@ -1512,7 +1512,7 @@ QgsAttributeForm::WidgetInfo QgsAttributeForm::createWidgetFromDef( const QgsAtt if ( !fieldDef ) break; - int fldIdx = vl->fieldNameIndex( fieldDef->name() ); + int fldIdx = vl->fields().lookupField( fieldDef->name() ); if ( fldIdx < vl->fields().count() && fldIdx >= 0 ) { const QgsEditorWidgetSetup widgetSetup = QgsEditorWidgetRegistry::instance()->findBest( mLayer, fieldDef->name() ); @@ -1717,7 +1717,7 @@ void QgsAttributeForm::createWrappers() { if ( field.name() == myWidget->objectName() ) { - int idx = mLayer->fieldNameIndex( field.name() ); + int idx = mLayer->fields().lookupField( field.name() ); QgsEditorWidgetWrapper* eww = QgsEditorWidgetRegistry::instance()->create( mLayer, idx, myWidget, this, mContext ); addWidgetWrapper( eww ); diff --git a/src/gui/qgsexpressionbuilderwidget.cpp b/src/gui/qgsexpressionbuilderwidget.cpp index dd620ce8fb75..8b3e35df97e8 100644 --- a/src/gui/qgsexpressionbuilderwidget.cpp +++ b/src/gui/qgsexpressionbuilderwidget.cpp @@ -330,7 +330,7 @@ void QgsExpressionBuilderWidget::fillFieldValues( const QString& fieldName, int // TODO We should thread this so that we don't hold the user up if the layer is massive. - int fieldIndex = mLayer->fieldNameIndex( fieldName ); + int fieldIndex = mLayer->fields().lookupField( fieldName ); if ( fieldIndex < 0 ) return; diff --git a/src/gui/qgsfieldmodel.h b/src/gui/qgsfieldmodel.h index 276437932937..b5b93e686605 100644 --- a/src/gui/qgsfieldmodel.h +++ b/src/gui/qgsfieldmodel.h @@ -19,7 +19,7 @@ #include #include #include -#include "qgsfield.h" +#include "qgsfields.h" class QgsVectorLayer; diff --git a/src/gui/qgsfieldvalidator.cpp b/src/gui/qgsfieldvalidator.cpp index 3e4fec64fbe7..9814d3137999 100644 --- a/src/gui/qgsfieldvalidator.cpp +++ b/src/gui/qgsfieldvalidator.cpp @@ -27,7 +27,7 @@ #include "qgslogger.h" #include "qgslonglongvalidator.h" -#include "qgsfield.h" +#include "qgsfields.h" QgsFieldValidator::QgsFieldValidator( QObject *parent, const QgsField &field, const QString& defaultValue, const QString& dateFormat ) : QValidator( parent ) diff --git a/src/gui/qgsfieldvalidator.h b/src/gui/qgsfieldvalidator.h index 3e106bf0be2f..82393a67cab9 100644 --- a/src/gui/qgsfieldvalidator.h +++ b/src/gui/qgsfieldvalidator.h @@ -23,7 +23,7 @@ #include #include #include -#include "qgsfield.h" +#include "qgsfields.h" /** \ingroup gui * \class QgsFieldValidator diff --git a/src/gui/qgsmaptoolidentify.cpp b/src/gui/qgsmaptoolidentify.cpp index 72dfb245bf02..7b5d07b30f57 100644 --- a/src/gui/qgsmaptoolidentify.cpp +++ b/src/gui/qgsmaptoolidentify.cpp @@ -19,7 +19,7 @@ #include "qgsfeature.h" #include "qgsfeatureiterator.h" #include "qgsfeaturestore.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgsidentifymenu.h" #include "qgslogger.h" diff --git a/src/gui/qgsmaptoolidentify.h b/src/gui/qgsmaptoolidentify.h index e8ff57ecc36f..1450a1c69ba3 100644 --- a/src/gui/qgsmaptoolidentify.h +++ b/src/gui/qgsmaptoolidentify.h @@ -17,7 +17,7 @@ #define QGSMAPTOOLIDENTIFY_H #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsmaptool.h" #include "qgspoint.h" #include "qgsunittypes.h" diff --git a/src/gui/qgsrelationeditorwidget.cpp b/src/gui/qgsrelationeditorwidget.cpp index 9decc9f87a0d..6b7372748367 100644 --- a/src/gui/qgsrelationeditorwidget.cpp +++ b/src/gui/qgsrelationeditorwidget.cpp @@ -380,7 +380,7 @@ void QgsRelationEditorWidget::linkFeature() QMap keys; Q_FOREACH ( const QgsRelation::FieldPair& fieldPair, mRelation.fieldPairs() ) { - int idx = mRelation.referencingLayer()->fieldNameIndex( fieldPair.referencingField() ); + int idx = mRelation.referencingLayer()->fields().lookupField( fieldPair.referencingField() ); QVariant val = mFeature.attribute( fieldPair.referencedField() ); keys.insert( idx, val ); } @@ -455,7 +455,7 @@ void QgsRelationEditorWidget::unlinkFeature() QMap keyFields; Q_FOREACH ( const QgsRelation::FieldPair& fieldPair, mRelation.fieldPairs() ) { - int idx = mRelation.referencingLayer()->fieldNameIndex( fieldPair.referencingField() ); + int idx = mRelation.referencingLayer()->fields().lookupField( fieldPair.referencingField() ); if ( idx < 0 ) { QgsDebugMsg( QString( "referencing field %1 not found" ).arg( fieldPair.referencingField() ) ); diff --git a/src/gui/qgssearchquerybuilder.cpp b/src/gui/qgssearchquerybuilder.cpp index 3186ee634714..7fca8aecb33a 100644 --- a/src/gui/qgssearchquerybuilder.cpp +++ b/src/gui/qgssearchquerybuilder.cpp @@ -25,7 +25,7 @@ #include #include "qgsfeature.h" #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgssearchquerybuilder.h" #include "qgsexpression.h" #include "qgsvectorlayer.h" diff --git a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp index a57dc4b268cc..f506486a50e6 100644 --- a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp @@ -645,7 +645,7 @@ QgsColorRamp* QgsCategorizedSymbolRendererWidget::getColorRamp() void QgsCategorizedSymbolRendererWidget::addCategories() { QString attrName = mExpressionWidget->currentField(); - int idx = mLayer->fieldNameIndex( attrName ); + int idx = mLayer->fields().lookupField( attrName ); QList unique_vals; if ( idx == -1 ) { diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index 42a1df451898..d73d619906d4 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -18,7 +18,7 @@ #include "qgspointdisplacementrendererwidget.h" #include "qgspointdisplacementrenderer.h" #include "qgsrendererregistry.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsstyle.h" #include "qgssymbolselectordialog.h" #include "qgssymbollayerutils.h" diff --git a/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp b/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp index e123bc273d01..5b0e9f19cc0b 100644 --- a/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp +++ b/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp @@ -33,7 +33,7 @@ #include "qgsgeometry.h" #include "qgslogger.h" #include "qgspoint.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsrectangle.h" #include diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp index c33a3bfc9035..8b6f22568db7 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp @@ -262,8 +262,8 @@ bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString& file ) return false; } - int fieldFeatureId = layer->fieldNameIndex( "FeatureID" ); - int fieldErrDesc = layer->fieldNameIndex( "ErrorDesc" ); + int fieldFeatureId = layer->fields().lookupField( "FeatureID" ); + int fieldErrDesc = layer->fields().lookupField( "ErrorDesc" ); for ( int row = 0, nRows = ui.tableWidgetErrors->rowCount(); row < nRows; ++row ) { QgsGeometryCheckError* error = ui.tableWidgetErrors->item( row, 0 )->data( Qt::UserRole ).value(); diff --git a/src/plugins/grass/qgsgrassmoduleoptions.h b/src/plugins/grass/qgsgrassmoduleoptions.h index 70fff72411a6..5f8e811d682f 100644 --- a/src/plugins/grass/qgsgrassmoduleoptions.h +++ b/src/plugins/grass/qgsgrassmoduleoptions.h @@ -24,7 +24,7 @@ //#include #include "qgis.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgscoordinatereferencesystem.h" #include "qgsgrassmoduleparam.h" diff --git a/src/plugins/grass/qgsgrassmoduleparam.h b/src/plugins/grass/qgsgrassmoduleparam.h index 0c222792e2b5..6c75bb3bb53b 100644 --- a/src/plugins/grass/qgsgrassmoduleparam.h +++ b/src/plugins/grass/qgsgrassmoduleparam.h @@ -26,7 +26,7 @@ #include "qgis.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgscoordinatereferencesystem.h" class QDomNode; diff --git a/src/plugins/interpolation/qgsinterpolationdialog.cpp b/src/plugins/interpolation/qgsinterpolationdialog.cpp index bb98eee8c0d5..339f79b16781 100644 --- a/src/plugins/interpolation/qgsinterpolationdialog.cpp +++ b/src/plugins/interpolation/qgsinterpolationdialog.cpp @@ -18,7 +18,7 @@ #include "qgsinterpolationdialog.h" #include "qgsinterpolatordialog.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgridfilewriter.h" #include "qgsidwinterpolatordialog.h" #include "qgstininterpolatordialog.h" diff --git a/src/plugins/roadgraph/linevectorlayerwidget.cpp b/src/plugins/roadgraph/linevectorlayerwidget.cpp index d4b7a40d5242..20f02710bbc8 100644 --- a/src/plugins/roadgraph/linevectorlayerwidget.cpp +++ b/src/plugins/roadgraph/linevectorlayerwidget.cpp @@ -25,7 +25,7 @@ #include // Qgis includes -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsvectorlayer.h" #include "qgsmaplayercombobox.h" diff --git a/src/plugins/roadgraph/roadgraphplugin.cpp b/src/plugins/roadgraph/roadgraphplugin.cpp index 264fc277dc8c..585d81309a2f 100644 --- a/src/plugins/roadgraph/roadgraphplugin.cpp +++ b/src/plugins/roadgraph/roadgraphplugin.cpp @@ -212,14 +212,14 @@ const QgsGraphDirector* RoadGraphPlugin::director() const QgsLineVectorLayerDirector * director = new QgsLineVectorLayerDirector( layer, - layer->fields().fieldNameIndex( mSettings->mDirection ), + layer->fields().lookupField( mSettings->mDirection ), mSettings->mFirstPointToLastPointDirectionVal, mSettings->mLastPointToFirstPointDirectionVal, mSettings->mBothDirectionVal, mSettings->mDefaultDirection ); director->addProperter( new QgsDistanceArcProperter() ); - director->addProperter( new RgSpeedProperter( layer->fields().fieldNameIndex( mSettings->mSpeed ), + director->addProperter( new RgSpeedProperter( layer->fields().lookupField( mSettings->mSpeed ), mSettings->mDefaultSpeed, speedUnit.multipler() ) ); return director; } diff --git a/src/providers/arcgisrest/qgsafsprovider.h b/src/providers/arcgisrest/qgsafsprovider.h index 84f5fd8d2142..d061dc8bd275 100644 --- a/src/providers/arcgisrest/qgsafsprovider.h +++ b/src/providers/arcgisrest/qgsafsprovider.h @@ -22,7 +22,7 @@ #include "qgsdatasourceuri.h" #include "qgscoordinatereferencesystem.h" #include "geometry/qgswkbtypes.h" -#include "qgsfield.h" +#include "qgsfields.h" /** * @brief A provider reading features from a ArcGIS Feature Service diff --git a/src/providers/arcgisrest/qgsarcgisrestutils.cpp b/src/providers/arcgisrest/qgsarcgisrestutils.cpp index c78bdf42ce87..90d890e65eb8 100644 --- a/src/providers/arcgisrest/qgsarcgisrestutils.cpp +++ b/src/providers/arcgisrest/qgsarcgisrestutils.cpp @@ -14,7 +14,7 @@ ***************************************************************************/ #include "qgsarcgisrestutils.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgslogger.h" #include "qgsnetworkaccessmanager.h" #include "qgsrectangle.h" diff --git a/src/providers/db2/qgsdb2featureiterator.cpp b/src/providers/db2/qgsdb2featureiterator.cpp index 29e31f1f0357..33805f7e920b 100644 --- a/src/providers/db2/qgsdb2featureiterator.cpp +++ b/src/providers/db2/qgsdb2featureiterator.cpp @@ -82,12 +82,10 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) // ensure that all attributes required for expression filter are being fetched if ( subsetOfAttributes && request.filterType() == QgsFeatureRequest::FilterExpression ) { - Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !attrs.contains( attrIdx ) ) - attrs << attrIdx; - } + //ensure that all fields required for filter expressions are prepared + QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += attrs.toSet(); + attrs = attributeIndexes.toList(); } Q_FOREACH ( int i, attrs ) diff --git a/src/providers/db2/qgsdb2featureiterator.h b/src/providers/db2/qgsdb2featureiterator.h index a2ee9d0c5874..42471b790a82 100644 --- a/src/providers/db2/qgsdb2featureiterator.h +++ b/src/providers/db2/qgsdb2featureiterator.h @@ -18,7 +18,7 @@ #ifndef QGSDB2FEATUREITERATOR_H #define QGSDB2FEATUREITERATOR_H -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeatureiterator.h" #include #include diff --git a/src/providers/db2/qgsdb2provider.cpp b/src/providers/db2/qgsdb2provider.cpp index ed5be828646d..57c715895758 100644 --- a/src/providers/db2/qgsdb2provider.cpp +++ b/src/providers/db2/qgsdb2provider.cpp @@ -1400,7 +1400,7 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin { QgsField fld = fields.field( i ); QgsDebugMsg( QString( "i: %1; fldIdx: %2; offset: %3" ) - .arg( i ).arg( fields.fieldNameIndex( fld.name() ) ).arg( offset ) ); + .arg( i ).arg( fields.lookupField( fld.name() ) ).arg( offset ) ); if ( oldToNewAttrIdxMap && fld.name() == primaryKey ) { @@ -1426,7 +1426,7 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin if ( oldToNewAttrIdxMap ) { - oldToNewAttrIdxMap->insert( fields.fieldNameIndex( fld.name() ), offset++ ); + oldToNewAttrIdxMap->insert( fields.lookupField( fld.name() ), offset++ ); } attr2Create += ',' + db2Field.toUpper(); } diff --git a/src/providers/db2/qgsdb2provider.h b/src/providers/db2/qgsdb2provider.h index 97ada43fef73..310ee349b12b 100644 --- a/src/providers/db2/qgsdb2provider.h +++ b/src/providers/db2/qgsdb2provider.h @@ -22,7 +22,7 @@ #include "qgsvectorlayerimport.h" #include #include "qgsgeometry.h" -#include "qgsfield.h" +#include "qgsfields.h" #include /** diff --git a/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp b/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp index 19ae2047de2d..0ebb0e23283c 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp +++ b/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp @@ -145,13 +145,10 @@ QgsDelimitedTextFeatureIterator::QgsDelimitedTextFeatureIterator( QgsDelimitedTe if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes && request.filterType() == QgsFeatureRequest::FilterExpression ) { QgsAttributeList attrs = request.subsetOfAttributes(); - Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !attrs.contains( attrIdx ) ) - attrs << attrIdx; - } - mRequest.setSubsetOfAttributes( attrs ); + //ensure that all fields required for filter expressions are prepared + QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += attrs.toSet(); + mRequest.setSubsetOfAttributes( attributeIndexes.toList() ); } QgsDebugMsg( QString( "Iterator is scanning file: " ) + ( mMode == FileScan ? "Yes" : "No" ) ); diff --git a/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp b/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp index 19f343619d74..275952c8ce9d 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp +++ b/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp @@ -32,7 +32,7 @@ #include "qgsdataprovider.h" #include "qgsexpression.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsmessagelog.h" diff --git a/src/providers/delimitedtext/qgsdelimitedtextprovider.h b/src/providers/delimitedtext/qgsdelimitedtextprovider.h index 2366f68fc93a..1645f255be01 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextprovider.h +++ b/src/providers/delimitedtext/qgsdelimitedtextprovider.h @@ -21,7 +21,7 @@ #include "qgsvectordataprovider.h" #include "qgscoordinatereferencesystem.h" #include "qgsdelimitedtextfile.h" -#include "qgsfield.h" +#include "qgsfields.h" #include diff --git a/src/providers/gpx/qgsgpxprovider.cpp b/src/providers/gpx/qgsgpxprovider.cpp index 7eb64850deeb..760c260d2b1d 100644 --- a/src/providers/gpx/qgsgpxprovider.cpp +++ b/src/providers/gpx/qgsgpxprovider.cpp @@ -36,7 +36,7 @@ #include "qgscoordinatereferencesystem.h" #include "qgsdataprovider.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsrectangle.h" diff --git a/src/providers/gpx/qgsgpxprovider.h b/src/providers/gpx/qgsgpxprovider.h index 0a1ccdcd72dc..7535331460a2 100644 --- a/src/providers/gpx/qgsgpxprovider.h +++ b/src/providers/gpx/qgsgpxprovider.h @@ -22,7 +22,7 @@ #include "qgsvectordataprovider.h" #include "gpsdata.h" -#include "qgsfield.h" +#include "qgsfields.h" class QgsFeature; class QgsField; diff --git a/src/providers/grass/qgsgrass.cpp b/src/providers/grass/qgsgrass.cpp index e2683f205cac..8204bb8d4fa7 100644 --- a/src/providers/grass/qgsgrass.cpp +++ b/src/providers/grass/qgsgrass.cpp @@ -35,7 +35,7 @@ #include "qgsapplication.h" #include "qgsconfig.h" #include "qgscoordinatereferencesystem.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgslocalec.h" #include "qgslogger.h" #include "qgsproject.h" diff --git a/src/providers/grass/qgsgrass.h b/src/providers/grass/qgsgrass.h index 39cae57629f1..bff3f38634ce 100644 --- a/src/providers/grass/qgsgrass.h +++ b/src/providers/grass/qgsgrass.h @@ -34,7 +34,7 @@ extern "C" #include "qgsapplication.h" #include "qgsexception.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include #include diff --git a/src/providers/grass/qgsgrassprovider.cpp b/src/providers/grass/qgsgrassprovider.cpp index 2b9ab2b56c5b..31e59309c1ec 100644 --- a/src/providers/grass/qgsgrassprovider.cpp +++ b/src/providers/grass/qgsgrassprovider.cpp @@ -24,7 +24,7 @@ #include "qgis.h" #include "qgsdataprovider.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgslinestring.h" #include "qgspointv2.h" #include "qgspolygon.h" diff --git a/src/providers/grass/qgsgrassvector.h b/src/providers/grass/qgsgrassvector.h index cff0facabb89..a714fe2ea25d 100644 --- a/src/providers/grass/qgsgrassvector.h +++ b/src/providers/grass/qgsgrassvector.h @@ -20,7 +20,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgrass.h" diff --git a/src/providers/grass/qgsgrassvectormaplayer.h b/src/providers/grass/qgsgrassvectormaplayer.h index 0972891b4098..98202dcfebb1 100644 --- a/src/providers/grass/qgsgrassvectormaplayer.h +++ b/src/providers/grass/qgsgrassvectormaplayer.h @@ -22,7 +22,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeature.h" extern "C" diff --git a/src/providers/memory/qgsmemoryfeatureiterator.h b/src/providers/memory/qgsmemoryfeatureiterator.h index 4aaa417cfe5b..5bbbe141e3dc 100644 --- a/src/providers/memory/qgsmemoryfeatureiterator.h +++ b/src/providers/memory/qgsmemoryfeatureiterator.h @@ -17,7 +17,7 @@ #include "qgsfeatureiterator.h" #include "qgsexpressioncontext.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" class QgsMemoryProvider; diff --git a/src/providers/memory/qgsmemoryprovider.cpp b/src/providers/memory/qgsmemoryprovider.cpp index b26238468b3b..1843af6a828d 100644 --- a/src/providers/memory/qgsmemoryprovider.cpp +++ b/src/providers/memory/qgsmemoryprovider.cpp @@ -17,7 +17,7 @@ #include "qgsmemoryfeatureiterator.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsspatialindex.h" diff --git a/src/providers/memory/qgsmemoryprovider.h b/src/providers/memory/qgsmemoryprovider.h index db300e53671f..7beb40298c04 100644 --- a/src/providers/memory/qgsmemoryprovider.h +++ b/src/providers/memory/qgsmemoryprovider.h @@ -15,7 +15,7 @@ #include "qgsvectordataprovider.h" #include "qgscoordinatereferencesystem.h" -#include "qgsfield.h" +#include "qgsfields.h" typedef QMap QgsFeatureMap; diff --git a/src/providers/mssql/qgsmssqlfeatureiterator.cpp b/src/providers/mssql/qgsmssqlfeatureiterator.cpp index 927226c571cb..616a2e1c7066 100644 --- a/src/providers/mssql/qgsmssqlfeatureiterator.cpp +++ b/src/providers/mssql/qgsmssqlfeatureiterator.cpp @@ -81,12 +81,10 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) // ensure that all attributes required for expression filter are being fetched if ( subsetOfAttributes && request.filterType() == QgsFeatureRequest::FilterExpression ) { - Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !attrs.contains( attrIdx ) ) - attrs << attrIdx; - } + //ensure that all fields required for filter expressions are prepared + QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += attrs.toSet(); + attrs = attributeIndexes.toList(); } Q_FOREACH ( int i, attrs ) diff --git a/src/providers/mssql/qgsmssqlfeatureiterator.h b/src/providers/mssql/qgsmssqlfeatureiterator.h index 3f3b4a5cdd43..676545abbce2 100644 --- a/src/providers/mssql/qgsmssqlfeatureiterator.h +++ b/src/providers/mssql/qgsmssqlfeatureiterator.h @@ -20,7 +20,7 @@ #include "qgsmssqlgeometryparser.h" #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include #include diff --git a/src/providers/mssql/qgsmssqlprovider.cpp b/src/providers/mssql/qgsmssqlprovider.cpp index 3b28d0ff8b20..0a2d5c68232c 100644 --- a/src/providers/mssql/qgsmssqlprovider.cpp +++ b/src/providers/mssql/qgsmssqlprovider.cpp @@ -37,7 +37,7 @@ #include "qgsapplication.h" #include "qgsdataprovider.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsmessageoutput.h" @@ -1833,7 +1833,7 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr QgsField fld = fields.at( i ); if ( oldToNewAttrIdxMap && fld.name() == primaryKey ) { - oldToNewAttrIdxMap->insert( fields.fieldNameIndex( fld.name() ), 0 ); + oldToNewAttrIdxMap->insert( fields.lookupField( fld.name() ), 0 ); continue; } @@ -1854,7 +1854,7 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr flist.append( fld ); if ( oldToNewAttrIdxMap ) - oldToNewAttrIdxMap->insert( fields.fieldNameIndex( fld.name() ), offset++ ); + oldToNewAttrIdxMap->insert( fields.lookupField( fld.name() ), offset++ ); } if ( !provider->addAttributes( flist ) ) diff --git a/src/providers/mssql/qgsmssqlprovider.h b/src/providers/mssql/qgsmssqlprovider.h index eb39eb4b51ee..982b2be960f2 100644 --- a/src/providers/mssql/qgsmssqlprovider.h +++ b/src/providers/mssql/qgsmssqlprovider.h @@ -21,7 +21,7 @@ #include "qgsvectordataprovider.h" #include "qgscoordinatereferencesystem.h" #include "qgsvectorlayerimport.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index 15b69fe0a18b..d2928af2cd48 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -81,13 +81,10 @@ QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool // ensure that all attributes required for expression filter are being fetched if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes && request.filterType() == QgsFeatureRequest::FilterExpression ) { - Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !attrs.contains( attrIdx ) ) - attrs << attrIdx; - } - mRequest.setSubsetOfAttributes( attrs ); + //ensure that all fields required for filter expressions are prepared + QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += attrs.toSet(); + mRequest.setSubsetOfAttributes( attributeIndexes.toList() ); } if ( request.filterType() == QgsFeatureRequest::FilterExpression && request.filterExpression()->needsGeometry() ) { diff --git a/src/providers/ogr/qgsogrfeatureiterator.h b/src/providers/ogr/qgsogrfeatureiterator.h index 60be9cbffe4f..220d6d3f45a5 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.h +++ b/src/providers/ogr/qgsogrfeatureiterator.h @@ -17,7 +17,7 @@ #include "qgsfeatureiterator.h" #include "qgsogrconnpool.h" -#include "qgsfield.h" +#include "qgsfields.h" #include diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 174d871fdb58..8c8645fbaa35 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -42,7 +42,7 @@ email : sherman at mrcc.com #include "qgsdataitem.h" #include "qgsdataprovider.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgscoordinatereferencesystem.h" #include "qgsvectorlayerimport.h" @@ -1350,7 +1350,7 @@ bool QgsOgrProvider::addAttributes( const QList &attributes ) // is still returned to the caller for ( QMap< QString, QVariant::Type >::const_iterator it = mapFieldTypesToPatch.begin(); it != mapFieldTypesToPatch.end(); ++it ) { - int idx = mAttributeFields.fieldNameIndex( it.key() ); + int idx = mAttributeFields.lookupField( it.key() ); if ( idx >= 0 ) mAttributeFields[ idx ].setType( *it ); } diff --git a/src/providers/oracle/qgsoracleconn.cpp b/src/providers/oracle/qgsoracleconn.cpp index 76c7fd659efb..d681c8785e03 100644 --- a/src/providers/oracle/qgsoracleconn.cpp +++ b/src/providers/oracle/qgsoracleconn.cpp @@ -20,7 +20,7 @@ #include "qgsdatasourceuri.h" #include "qgsmessagelog.h" #include "qgscredentials.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsoracletablemodel.h" #include diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index aa30de8ef5ed..7f1d6ffda420 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -16,7 +16,7 @@ ***************************************************************************/ #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgsmessageoutput.h" #include "qgsmessagelog.h" diff --git a/src/providers/oracle/qgsoracleprovider.h b/src/providers/oracle/qgsoracleprovider.h index 9ac719a88424..1c39a328b15c 100644 --- a/src/providers/oracle/qgsoracleprovider.h +++ b/src/providers/oracle/qgsoracleprovider.h @@ -23,7 +23,7 @@ #include "qgsvectorlayerimport.h" #include "qgsoracletablemodel.h" #include "qgsdatasourceuri.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include diff --git a/src/providers/postgres/qgspostgresconn.cpp b/src/providers/postgres/qgspostgresconn.cpp index 8417eda5a8c9..1ee8b93ff9f9 100644 --- a/src/providers/postgres/qgspostgresconn.cpp +++ b/src/providers/postgres/qgspostgresconn.cpp @@ -21,7 +21,7 @@ #include "qgsdatasourceuri.h" #include "qgsmessagelog.h" #include "qgscredentials.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgspgtablemodel.h" #include "qgsproviderregistry.h" #include "qgsvectordataprovider.h" diff --git a/src/providers/postgres/qgspostgresfeatureiterator.cpp b/src/providers/postgres/qgspostgresfeatureiterator.cpp index 1b72d4d97ab6..9ba1778b5c10 100644 --- a/src/providers/postgres/qgspostgresfeatureiterator.cpp +++ b/src/providers/postgres/qgspostgresfeatureiterator.cpp @@ -93,13 +93,10 @@ QgsPostgresFeatureIterator::QgsPostgresFeatureIterator( QgsPostgresFeatureSource if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) { QgsAttributeList attrs = mRequest.subsetOfAttributes(); - Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !attrs.contains( attrIdx ) ) - attrs << attrIdx; - } - mRequest.setSubsetOfAttributes( attrs ); + //ensure that all fields required for filter expressions are prepared + QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += attrs.toSet(); + mRequest.setSubsetOfAttributes( attributeIndexes.toList() ); } mFilterRequiresGeometry = request.filterExpression()->needsGeometry(); diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index 2322033b1458..f604241e2248 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -22,7 +22,7 @@ #include "qgsrectangle.h" #include "qgsvectorlayerimport.h" #include "qgspostgresconn.h" -#include "qgsfield.h" +#include "qgsfields.h" #include class QgsFeature; diff --git a/src/providers/spatialite/qgsspatialitefeatureiterator.cpp b/src/providers/spatialite/qgsspatialitefeatureiterator.cpp index b358d5c314f7..79c2fba0398f 100644 --- a/src/providers/spatialite/qgsspatialitefeatureiterator.cpp +++ b/src/providers/spatialite/qgsspatialitefeatureiterator.cpp @@ -89,13 +89,10 @@ QgsSpatiaLiteFeatureIterator::QgsSpatiaLiteFeatureIterator( QgsSpatiaLiteFeature if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes && request.filterType() == QgsFeatureRequest::FilterExpression ) { QgsAttributeList attrs = request.subsetOfAttributes(); - Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) - { - int attrIdx = mSource->mFields.fieldNameIndex( field ); - if ( !attrs.contains( attrIdx ) ) - attrs << attrIdx; - } - mRequest.setSubsetOfAttributes( attrs ); + //ensure that all fields required for filter expressions are prepared + QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); + attributeIndexes += attrs.toSet(); + mRequest.setSubsetOfAttributes( attributeIndexes.toList() ); } if ( request.filterExpression()->needsGeometry() ) { diff --git a/src/providers/spatialite/qgsspatialitefeatureiterator.h b/src/providers/spatialite/qgsspatialitefeatureiterator.h index 33d249c03ccd..f660064e9571 100644 --- a/src/providers/spatialite/qgsspatialitefeatureiterator.h +++ b/src/providers/spatialite/qgsspatialitefeatureiterator.h @@ -16,7 +16,7 @@ #define QGSSPATIALITEFEATUREITERATOR_H #include "qgsfeatureiterator.h" -#include "qgsfield.h" +#include "qgsfields.h" extern "C" { diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index 48352dde0777..2ceb1dcc8f88 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -17,7 +17,7 @@ email : a.furieri@lqt.it #include "qgis.h" #include "qgsapplication.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgsmessageoutput.h" #include "qgsrectangle.h" @@ -961,7 +961,7 @@ void QgsSpatiaLiteProvider::determineViewPrimaryKey() if ( rows > 0 ) { mPrimaryKey = results[1 * columns]; - int idx = mAttributeFields.fieldNameIndex( mPrimaryKey ); + int idx = mAttributeFields.lookupField( mPrimaryKey ); if ( idx != -1 ) mPrimaryKeyAttrs << idx; } @@ -989,7 +989,7 @@ bool QgsSpatiaLiteProvider::hasTriggers() bool QgsSpatiaLiteProvider::hasRowid() { - if ( mAttributeFields.fieldNameIndex( "ROWID" ) >= 0 ) + if ( mAttributeFields.lookupField( "ROWID" ) >= 0 ) return false; // table without rowid column diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 7d1134d446f0..b38c9abe6c97 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -28,7 +28,7 @@ extern "C" #include "qgsvectordataprovider.h" #include "qgsrectangle.h" #include "qgsvectorlayerimport.h" -#include "qgsfield.h" +#include "qgsfields.h" #include #include #include diff --git a/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp b/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp index c42b127a5e57..2dbfdc178155 100644 --- a/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp +++ b/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp @@ -91,7 +91,7 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF { Q_FOREACH ( const QString& field, request.filterExpression()->referencedColumns() ) { - int attrIdx = mFields.fieldNameIndex( field ); + int attrIdx = mFields.lookupField( field ); if ( !mAttributes.contains( attrIdx ) ) mAttributes << attrIdx; } diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index bc6c374a4727..72de7c08a4a0 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -18,7 +18,7 @@ #include "qgis.h" #include "qgsapplication.h" #include "qgsfeature.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsgeometry.h" #include "qgscoordinatereferencesystem.h" #include "qgslogger.h" @@ -257,7 +257,7 @@ void QgsWFSProviderSQLColumnRefValidator::visit( const QgsSQLStatement::NodeColu } QgsFields tableFields = mMapTypenameToFields[typeName]; - int idx = tableFields.fieldNameIndex( n.name() ); + int idx = tableFields.lookupField( n.name() ); if ( idx < 0 && mMapTypenameToGeometryAttribute[typeName] != n.name() ) { mError = true; @@ -595,7 +595,7 @@ bool QgsWFSProvider::processSQL( const QString& sqlString, QString& errorMsg, QS else { const QgsFields tableFields = mapTypenameToFields[columnTableTypename]; - int idx = tableFields.fieldNameIndex( columnRef->name() ); + int idx = tableFields.lookupField( columnRef->name() ); if ( idx < 0 ) { QgsDebugMsg( QString( "Should not happen. Cannot find field for %1" ).arg( columnRef->name() ) ); diff --git a/src/providers/wfs/qgswfsshareddata.cpp b/src/providers/wfs/qgswfsshareddata.cpp index e25cf10c60f4..12bcf765e0f3 100644 --- a/src/providers/wfs/qgswfsshareddata.cpp +++ b/src/providers/wfs/qgswfsshareddata.cpp @@ -247,7 +247,7 @@ bool QgsWFSSharedData::createCache() // Only GDAL >= 2.0 can use an alternate geometry or FID field name // but QgsVectorFileWriter will refuse anyway to create a ogc_fid, so we will // do it manually - bool useReservedNames = cacheFields.fieldNameIndex( "ogc_fid" ) >= 0; + bool useReservedNames = cacheFields.lookupField( "ogc_fid" ) >= 0; #if GDAL_VERSION_MAJOR < 2 if ( cacheFields.fieldNameIndex( "geometry" ) >= 0 ) useReservedNames = true; diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index b472577e6cbd..42c421fa0de1 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -782,7 +782,7 @@ void QgsServerProjectParser::addLayerProjectSettings( QDomElement& layerElem, QD if ( exp.isField() ) { displayField = static_cast( exp.rootNode() )->name(); - displayFieldIdx = vLayer->fieldNameIndex( displayField ); + displayFieldIdx = vLayer->fields().lookupField( displayField ); } //attributes diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index 8b307d9e15e4..c733aeeb4397 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -15,7 +15,7 @@ * * ***************************************************************************/ #include "qgswfsserver.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsexpression.h" #include "qgsfeatureiterator.h" #include "qgsgeometry.h" @@ -488,7 +488,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QgsStringMap::const_iterator aliasIt = aliasMap.constBegin(); for ( ; aliasIt != aliasMap.constEnd(); ++aliasIt ) { - int attrIndex = layer->fieldNameIndex( aliasIt.key() ); + int attrIndex = layer->fields().lookupField( aliasIt.key() ); if ( attrIndex != -1 ) { layerAliasInfo.insert( attrIndex, aliasIt.value() ); @@ -534,7 +534,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format { fieldName = fieldName.section( ":", 1, 1 ); } - int fieldNameIdx = fields.fieldNameIndex( fieldName ); + int fieldNameIdx = fields.lookupField( fieldName ); if ( fieldNameIdx > -1 ) { idxList.append( fieldNameIdx ); @@ -874,7 +874,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QgsStringMap::const_iterator aliasIt = aliasMap.constBegin(); for ( ; aliasIt != aliasMap.constEnd(); ++aliasIt ) { - int attrIndex = layer->fieldNameIndex( aliasIt.key() ); + int attrIndex = layer->fields().lookupField( aliasIt.key() ); if ( attrIndex != -1 ) { layerAliasInfo.insert( attrIndex, aliasIt.value() ); @@ -914,7 +914,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format for ( alstIt = attrList.begin(); alstIt != attrList.end(); ++alstIt ) { fieldName = *alstIt; - int fieldNameIdx = fields.fieldNameIndex( fieldName ); + int fieldNameIdx = fields.lookupField( fieldName ); if ( fieldNameIdx > -1 ) { idxList.append( fieldNameIdx ); diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index e4b7a1c900bf..a889bbc131f8 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -20,7 +20,7 @@ #include "qgscapabilitiescache.h" #include "qgscsexception.h" #include "qgsdxfexport.h" -#include "qgsfield.h" +#include "qgsfields.h" #include "qgsfeatureiterator.h" #include "qgsgeometry.h" #include "qgslayertree.h" diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 8de2d089872d..ae2f372e6590 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -2444,7 +2444,7 @@ class TestQgsExpression: public QObject // Let's remove the field referenced in the expression mPointsLayer->startEditing(); - mPointsLayer->deleteAttribute( mPointsLayer->fieldNameIndex( "Pilots" ) ); + mPointsLayer->deleteAttribute( mPointsLayer->fields().lookupField( "Pilots" ) ); // Now the prepared expression is broken // The cached field index points to the index which now is diff --git a/tests/src/core/testqgsfields.cpp b/tests/src/core/testqgsfields.cpp index 221008715e18..0b20caede330 100644 --- a/tests/src/core/testqgsfields.cpp +++ b/tests/src/core/testqgsfields.cpp @@ -19,7 +19,7 @@ #include #include -#include "qgsfield.h" +#include "qgsfields.h" class TestQgsFields: public QObject { @@ -338,25 +338,25 @@ void TestQgsFields::indexFromName() fields.append( field3 ); QCOMPARE( fields.indexFromName( QString( "bad" ) ), -1 ); - QCOMPARE( fields.fieldNameIndex( QString( "bad" ) ), -1 ); + QCOMPARE( fields.lookupField( QString( "bad" ) ), -1 ); QCOMPARE( fields.indexFromName( QString( "testfield" ) ), 0 ); - QCOMPARE( fields.fieldNameIndex( QString( "testfield" ) ), 0 ); + QCOMPARE( fields.lookupField( QString( "testfield" ) ), 0 ); QCOMPARE( fields.indexFromName( QString( "testfield3" ) ), 2 ); - QCOMPARE( fields.fieldNameIndex( QString( "testfield3" ) ), 2 ); + QCOMPARE( fields.lookupField( QString( "testfield3" ) ), 2 ); //indexFromName is case sensitive, fieldNameIndex isn't QCOMPARE( fields.indexFromName( QString( "teStFiEld2" ) ), -1 ); - QCOMPARE( fields.fieldNameIndex( QString( "teStFiEld2" ) ), 1 ); + QCOMPARE( fields.lookupField( QString( "teStFiEld2" ) ), 1 ); //test that fieldNameIndex prefers exact case matches over case insensitive matches QgsField sameNameDifferentCase( QString( "teStFielD" ) ); fields.append( sameNameDifferentCase ); - QCOMPARE( fields.fieldNameIndex( QString( "teStFielD" ) ), 3 ); + QCOMPARE( fields.lookupField( QString( "teStFielD" ) ), 3 ); //test that the alias is only matched with fieldNameIndex QCOMPARE( fields.indexFromName( "testfieldAlias" ), -1 ); - QCOMPARE( fields.fieldNameIndex( "testfieldAlias" ), 0 ); - QCOMPARE( fields.fieldNameIndex( "testfieldalias" ), 0 ); + QCOMPARE( fields.lookupField( "testfieldAlias" ), 0 ); + QCOMPARE( fields.lookupField( "testfieldalias" ), 0 ); } void TestQgsFields::toList() diff --git a/tests/src/core/testqgsrulebasedrenderer.cpp b/tests/src/core/testqgsrulebasedrenderer.cpp index c8b4267d5858..3ba0a43f3ae7 100644 --- a/tests/src/core/testqgsrulebasedrenderer.cpp +++ b/tests/src/core/testqgsrulebasedrenderer.cpp @@ -67,7 +67,7 @@ class TestQgsRuleBasedRenderer: public QObject { // prepare features QgsVectorLayer* layer = new QgsVectorLayer( "point?field=fld:int", "x", "memory" ); - int idx = layer->fieldNameIndex( "fld" ); + int idx = layer->fields().indexFromName( "fld" ); QVERIFY( idx != -1 ); QgsFeature f1; f1.initAttributes( 1 ); diff --git a/tests/src/core/testqgsvectorlayerjoinbuffer.cpp b/tests/src/core/testqgsvectorlayerjoinbuffer.cpp index 0a4b86aa7d96..a8821edcaa08 100644 --- a/tests/src/core/testqgsvectorlayerjoinbuffer.cpp +++ b/tests/src/core/testqgsvectorlayerjoinbuffer.cpp @@ -520,7 +520,7 @@ void TestVectorLayerJoinBuffer::testJoinLayerDefinitionFile() QCOMPARE( vLayer->vectorJoins().count(), 1 ); // Check for joined field - QVERIFY( vLayer->fieldNameIndex( joinInfo.prefix + "value" ) >= 0 ); + QVERIFY( vLayer->fields().lookupField( joinInfo.prefix + "value" ) >= 0 ); } void TestVectorLayerJoinBuffer::testCacheUpdate_data() From 4a7a8ff263dd748c153b5507e293bd0bcb92b31f Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 22 Sep 2016 12:09:13 +0200 Subject: [PATCH 049/897] Update python code --- python/core/qgsfields.sip | 16 +++++++++++++++- .../algs/qgis/BasicStatisticsStrings.py | 2 +- python/plugins/processing/algs/qgis/Buffer.py | 2 +- .../plugins/processing/algs/qgis/ConvexHull.py | 2 +- .../plugins/processing/algs/qgis/DeleteColumn.py | 2 +- python/plugins/processing/algs/qgis/Dissolve.py | 2 +- .../processing/algs/qgis/EquivalentNumField.py | 2 +- .../processing/algs/qgis/ExtractByAttribute.py | 2 +- .../processing/algs/qgis/JoinAttributes.py | 4 ++-- .../processing/algs/qgis/LinesIntersection.py | 4 ++-- .../plugins/processing/algs/qgis/MeanCoords.py | 4 ++-- .../processing/algs/qgis/PointDistance.py | 6 +++--- .../algs/qgis/PointsInPolygonUnique.py | 2 +- .../algs/qgis/PointsInPolygonWeighted.py | 2 +- .../processing/algs/qgis/PointsLayerFromTable.py | 4 ++-- .../algs/qgis/RandomExtractWithinSubsets.py | 2 +- .../algs/qgis/RandomSelectionWithinSubsets.py | 2 +- .../processing/algs/qgis/SelectByAttribute.py | 2 +- .../algs/qgis/SinglePartsToMultiparts.py | 2 +- .../algs/qgis/StatisticsByCategories.py | 4 ++-- .../plugins/processing/algs/qgis/TextToFloat.py | 2 +- .../plugins/processing/algs/qgis/UniqueValues.py | 2 +- .../plugins/processing/algs/qgis/VectorSplit.py | 2 +- .../Number_of_unique_values_in_classes.py | 4 ++-- python/plugins/processing/tools/vector.py | 4 ++-- src/core/qgsfields.cpp | 7 ++++++- src/core/qgsfields.h | 16 +++++++++++++++- tests/src/python/offlineditingtestbase.py | 6 +++--- tests/src/python/test_provider_mssql.py | 6 +++--- tests/src/python/test_provider_oracle.py | 4 ++-- tests/src/python/test_provider_postgres.py | 16 ++++++++-------- tests/src/python/test_provider_tabfile.py | 6 +++--- tests/src/python/test_qgsvectorfilewriter.py | 14 +++++++------- 33 files changed, 95 insertions(+), 62 deletions(-) diff --git a/python/core/qgsfields.sip b/python/core/qgsfields.sip index e5bfd8f89dde..fd027c05b38a 100644 --- a/python/core/qgsfields.sip +++ b/python/core/qgsfields.sip @@ -157,9 +157,10 @@ class QgsFields %End /** - * Look up field's index from the field name. + * Get the field index from the field name. * This method takes is case sensitive and only matches the data source * name of the field. + * Alias for indexOf * * @param fieldName The name of the field. * @@ -168,6 +169,19 @@ class QgsFields */ int indexFromName( const QString& fieldName ) const; + /** + * Get the field index from the field name. + * This method takes is case sensitive and only matches the data source + * name of the field. + * + * @param fieldName The name of the field. + * + * @return The field index if found or -1 in case it cannot be found. + * @see lookupField For a more tolerant alternative. + * @note Added in QGIS 3.0 + */ + int indexOf( const QString& fieldName ) const; + /** * Look up field's index from the field name. * This method matches in the following order: diff --git a/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py b/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py index 0f7d75758065..2d8ca9f9dc2a 100644 --- a/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py +++ b/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py @@ -86,7 +86,7 @@ def processAlgorithm(self, progress): outputFile = self.getOutputValue(self.OUTPUT_HTML_FILE) - index = layer.fieldNameIndex(fieldName) + index = layer.fields().lookupField(fieldName) sumValue = 0 minValue = 0 diff --git a/python/plugins/processing/algs/qgis/Buffer.py b/python/plugins/processing/algs/qgis/Buffer.py index a36e4034994d..fedc130555c4 100644 --- a/python/plugins/processing/algs/qgis/Buffer.py +++ b/python/plugins/processing/algs/qgis/Buffer.py @@ -35,7 +35,7 @@ def buffering(progress, writer, distance, field, useField, layer, dissolve, segments, endCapStyle=1, joinStyle=1, mitreLimit=2): if useField: - field = layer.fieldNameIndex(field) + field = layer.fields().lookupField(field) outFeat = QgsFeature() diff --git a/python/plugins/processing/algs/qgis/ConvexHull.py b/python/plugins/processing/algs/qgis/ConvexHull.py index 20673b538eb5..355cc3646aef 100644 --- a/python/plugins/processing/algs/qgis/ConvexHull.py +++ b/python/plugins/processing/algs/qgis/ConvexHull.py @@ -78,7 +78,7 @@ def processAlgorithm(self, progress): f = QgsField('value', QVariant.String, '', 255) if useField: - index = layer.fieldNameIndex(fieldName) + index = layer.fields().lookupField(fieldName) fType = layer.fields()[index].type() if fType in [QVariant.Int, QVariant.UInt, QVariant.LongLong, QVariant.ULongLong]: f.setType(fType) diff --git a/python/plugins/processing/algs/qgis/DeleteColumn.py b/python/plugins/processing/algs/qgis/DeleteColumn.py index c209baeea143..5405236ceda5 100644 --- a/python/plugins/processing/algs/qgis/DeleteColumn.py +++ b/python/plugins/processing/algs/qgis/DeleteColumn.py @@ -52,7 +52,7 @@ def defineCharacteristics(self): def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri( self.getParameterValue(self.INPUT)) - idx = layer.fieldNameIndex(self.getParameterValue(self.COLUMN)) + idx = layer.fields().lookupField(self.getParameterValue(self.COLUMN)) fields = layer.fields() fields.remove(idx) diff --git a/python/plugins/processing/algs/qgis/Dissolve.py b/python/plugins/processing/algs/qgis/Dissolve.py index 9363ec6423e4..25e71493f645 100644 --- a/python/plugins/processing/algs/qgis/Dissolve.py +++ b/python/plugins/processing/algs/qgis/Dissolve.py @@ -127,7 +127,7 @@ def processAlgorithm(self, progress): outFeat.setAttributes(attrs) writer.addFeature(outFeat) else: - field_indexes = [vlayerA.fieldNameIndex(f) for f in field_names.split(';')] + field_indexes = [vlayerA.fields().lookupField(f) for f in field_names.split(';')] attribute_dict = {} geometry_dict = defaultdict(lambda: []) diff --git a/python/plugins/processing/algs/qgis/EquivalentNumField.py b/python/plugins/processing/algs/qgis/EquivalentNumField.py index ef1b1fa05045..ee162d465701 100644 --- a/python/plugins/processing/algs/qgis/EquivalentNumField.py +++ b/python/plugins/processing/algs/qgis/EquivalentNumField.py @@ -54,7 +54,7 @@ def processAlgorithm(self, progress): output = self.getOutputFromName(self.OUTPUT) vlayer = dataobjects.getObjectFromUri( self.getParameterValue(self.INPUT)) - fieldindex = vlayer.fieldNameIndex(fieldname) + fieldindex = vlayer.fields().lookupField(fieldname) fields = vlayer.fields() fields.append(QgsField('NUM_FIELD', QVariant.Int)) writer = output.getVectorWriter(fields, vlayer.wkbType(), diff --git a/python/plugins/processing/algs/qgis/ExtractByAttribute.py b/python/plugins/processing/algs/qgis/ExtractByAttribute.py index 59900edc293f..660b1cfbcc66 100644 --- a/python/plugins/processing/algs/qgis/ExtractByAttribute.py +++ b/python/plugins/processing/algs/qgis/ExtractByAttribute.py @@ -87,7 +87,7 @@ def processAlgorithm(self, progress): writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, layer.wkbType(), layer.crs()) - idx = layer.fieldNameIndex(fieldName) + idx = layer.fields().lookupField(fieldName) fieldType = fields[idx].type() if fieldType != QVariant.String and operator in self.OPERATORS[-2:]: diff --git a/python/plugins/processing/algs/qgis/JoinAttributes.py b/python/plugins/processing/algs/qgis/JoinAttributes.py index f514fed19ad5..3a24c82c4e8a 100644 --- a/python/plugins/processing/algs/qgis/JoinAttributes.py +++ b/python/plugins/processing/algs/qgis/JoinAttributes.py @@ -70,10 +70,10 @@ def processAlgorithm(self, progress): field2 = self.getParameterValue(self.TABLE_FIELD_2) layer = dataobjects.getObjectFromUri(input) - joinField1Index = layer.fieldNameIndex(field) + joinField1Index = layer.fields().lookupField(field) layer2 = dataobjects.getObjectFromUri(input2) - joinField2Index = layer2.fieldNameIndex(field2) + joinField2Index = layer2.fields().lookupField(field2) outFields = vector.combineVectorFields(layer, layer2) writer = output.getVectorWriter(outFields, layer.wkbType(), diff --git a/python/plugins/processing/algs/qgis/LinesIntersection.py b/python/plugins/processing/algs/qgis/LinesIntersection.py index ba62f61a1a43..18a129ad38ba 100644 --- a/python/plugins/processing/algs/qgis/LinesIntersection.py +++ b/python/plugins/processing/algs/qgis/LinesIntersection.py @@ -79,8 +79,8 @@ def processAlgorithm(self, progress): fieldA = self.getParameterValue(self.FIELD_A) fieldB = self.getParameterValue(self.FIELD_B) - idxA = layerA.fieldNameIndex(fieldA) - idxB = layerB.fieldNameIndex(fieldB) + idxA = layerA.fields().lookupField(fieldA) + idxB = layerB.fields().lookupField(fieldB) fieldList = [layerA.fields()[idxA], layerB.fields()[idxB]] diff --git a/python/plugins/processing/algs/qgis/MeanCoords.py b/python/plugins/processing/algs/qgis/MeanCoords.py index 76d511512a34..9a18b596f69d 100644 --- a/python/plugins/processing/algs/qgis/MeanCoords.py +++ b/python/plugins/processing/algs/qgis/MeanCoords.py @@ -79,12 +79,12 @@ def processAlgorithm(self, progress): if weightField is None: weightIndex = -1 else: - weightIndex = layer.fieldNameIndex(weightField) + weightIndex = layer.fields().lookupField(weightField) if uniqueField is None: uniqueIndex = -1 else: - uniqueIndex = layer.fieldNameIndex(uniqueField) + uniqueIndex = layer.fields().lookupField(uniqueField) fieldList = [QgsField('MEAN_X', QVariant.Double, '', 24, 15), QgsField('MEAN_Y', QVariant.Double, '', 24, 15), diff --git a/python/plugins/processing/algs/qgis/PointDistance.py b/python/plugins/processing/algs/qgis/PointDistance.py index 3fc5d772e981..bd16c6fd2a05 100644 --- a/python/plugins/processing/algs/qgis/PointDistance.py +++ b/python/plugins/processing/algs/qgis/PointDistance.py @@ -122,8 +122,8 @@ def linearMatrix(self, inLayer, inField, targetLayer, targetField, index = vector.spatialindex(targetLayer) - inIdx = inLayer.fieldNameIndex(inField) - outIdx = targetLayer.fieldNameIndex(targetField) + inIdx = inLayer.fields().lookupField(inField) + outIdx = targetLayer.fields().lookupField(targetField) distArea = QgsDistanceArea() @@ -162,7 +162,7 @@ def regularMatrix(self, inLayer, inField, targetLayer, targetField, nPoints, progress): index = vector.spatialindex(targetLayer) - inIdx = inLayer.fieldNameIndex(inField) + inIdx = inLayer.fields().lookupField(inField) distArea = QgsDistanceArea() diff --git a/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py b/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py index 3d271555446b..dbb760403848 100644 --- a/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py +++ b/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py @@ -65,7 +65,7 @@ def processAlgorithm(self, progress): fields = polyLayer.fields() fields.append(QgsField(fieldName, QVariant.Int)) - classFieldIndex = pointLayer.fieldNameIndex(classFieldName) + classFieldIndex = pointLayer.fields().lookupField(classFieldName) (idxCount, fieldList) = vector.findOrCreateField(polyLayer, polyLayer.fields(), fieldName) diff --git a/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py b/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py index 28e631c68a77..89587a754ff6 100644 --- a/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py +++ b/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py @@ -68,7 +68,7 @@ def processAlgorithm(self, progress): polyLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.POLYGONS)) pointLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.POINTS)) fieldName = self.getParameterValue(self.FIELD) - fieldIdx = pointLayer.fieldNameIndex(self.getParameterValue(self.WEIGHT)) + fieldIdx = pointLayer.fields().lookupField(self.getParameterValue(self.WEIGHT)) fields = polyLayer.fields() fields.append(QgsField(fieldName, QVariant.Int)) diff --git a/python/plugins/processing/algs/qgis/PointsLayerFromTable.py b/python/plugins/processing/algs/qgis/PointsLayerFromTable.py index 4eb649ec85f2..9a28da31d9a4 100644 --- a/python/plugins/processing/algs/qgis/PointsLayerFromTable.py +++ b/python/plugins/processing/algs/qgis/PointsLayerFromTable.py @@ -65,8 +65,8 @@ def processAlgorithm(self, progress): output = self.getOutputFromName(self.OUTPUT) fields = vlayer.fields() writer = output.getVectorWriter(fields, QgsWkbTypes.Point, self.crs) - xfieldindex = vlayer.fieldNameIndex(self.getParameterValue(self.XFIELD)) - yfieldindex = vlayer.fieldNameIndex(self.getParameterValue(self.YFIELD)) + xfieldindex = vlayer.fields().lookupField(self.getParameterValue(self.XFIELD)) + yfieldindex = vlayer.fields().lookupField(self.getParameterValue(self.YFIELD)) crsId = self.getParameterValue(self.TARGET_CRS) targetCrs = QgsCoordinateReferenceSystem() diff --git a/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py b/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py index 1b52e4539363..a04bc2f34f4b 100644 --- a/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py +++ b/python/plugins/processing/algs/qgis/RandomExtractWithinSubsets.py @@ -71,7 +71,7 @@ def processAlgorithm(self, progress): field = self.getParameterValue(self.FIELD) method = self.getParameterValue(self.METHOD) - index = layer.fieldNameIndex(field) + index = layer.fields().lookupField(field) features = vector.features(layer) featureCount = len(features) diff --git a/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py b/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py index fc7ae77a3e82..7849b97fa29a 100644 --- a/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py +++ b/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py @@ -83,7 +83,7 @@ def processAlgorithm(self, progress): method = self.getParameterValue(self.METHOD) layer.removeSelection() - index = layer.fieldNameIndex(field) + index = layer.fields().lookupField(field) unique = vector.getUniqueValues(layer, index) featureCount = layer.featureCount() diff --git a/python/plugins/processing/algs/qgis/SelectByAttribute.py b/python/plugins/processing/algs/qgis/SelectByAttribute.py index b1c7650c8540..1358ad90c9b6 100644 --- a/python/plugins/processing/algs/qgis/SelectByAttribute.py +++ b/python/plugins/processing/algs/qgis/SelectByAttribute.py @@ -86,7 +86,7 @@ def processAlgorithm(self, progress): fields = layer.fields() - idx = layer.fieldNameIndex(fieldName) + idx = layer.fields().lookupField(fieldName) fieldType = fields[idx].type() if fieldType != QVariant.String and operator in self.OPERATORS[-2:]: diff --git a/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py b/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py index 3bf534dd8de8..0be51e4ccb32 100644 --- a/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py +++ b/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py @@ -75,7 +75,7 @@ def processAlgorithm(self, progress): inGeom = QgsGeometry() outGeom = QgsGeometry() - index = layer.fieldNameIndex(fieldName) + index = layer.fields().lookupField(fieldName) unique = vector.getUniqueValues(layer, index) current = 0 diff --git a/python/plugins/processing/algs/qgis/StatisticsByCategories.py b/python/plugins/processing/algs/qgis/StatisticsByCategories.py index 44f1f6f26a64..5316027702f4 100644 --- a/python/plugins/processing/algs/qgis/StatisticsByCategories.py +++ b/python/plugins/processing/algs/qgis/StatisticsByCategories.py @@ -62,8 +62,8 @@ def processAlgorithm(self, progress): categoriesFieldName = self.getParameterValue(self.CATEGORIES_FIELD_NAME) output = self.getOutputFromName(self.OUTPUT) - valuesField = layer.fieldNameIndex(valuesFieldName) - categoriesField = layer.fieldNameIndex(categoriesFieldName) + valuesField = layer.fields().lookupField(valuesFieldName) + categoriesField = layer.fields().lookupField(categoriesFieldName) features = vector.features(layer) total = 100.0 / len(features) diff --git a/python/plugins/processing/algs/qgis/TextToFloat.py b/python/plugins/processing/algs/qgis/TextToFloat.py index 23383df71507..f9cd9e40324a 100644 --- a/python/plugins/processing/algs/qgis/TextToFloat.py +++ b/python/plugins/processing/algs/qgis/TextToFloat.py @@ -53,7 +53,7 @@ def defineCharacteristics(self): def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) fieldName = self.getParameterValue(self.FIELD) - idx = layer.fieldNameIndex(fieldName) + idx = layer.fields().lookupField(fieldName) fields = layer.fields() fields[idx] = QgsField(fieldName, QVariant.Double, '', 24, 15) diff --git a/python/plugins/processing/algs/qgis/UniqueValues.py b/python/plugins/processing/algs/qgis/UniqueValues.py index b4ede40d0807..45311193294e 100644 --- a/python/plugins/processing/algs/qgis/UniqueValues.py +++ b/python/plugins/processing/algs/qgis/UniqueValues.py @@ -69,7 +69,7 @@ def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER)) fieldName = self.getParameterValue(self.FIELD_NAME) outputFile = self.getOutputValue(self.OUTPUT) - values = vector.getUniqueValues(layer, layer.fieldNameIndex(fieldName)) + values = vector.getUniqueValues(layer, layer.fields().lookupField(fieldName)) self.createHTML(outputFile, values) self.setOutputValue(self.TOTAL_VALUES, len(values)) self.setOutputValue(self.UNIQUE_VALUES, ';'.join([str(v) for v in diff --git a/python/plugins/processing/algs/qgis/VectorSplit.py b/python/plugins/processing/algs/qgis/VectorSplit.py index e7284d18d2d1..20c953cc8d03 100644 --- a/python/plugins/processing/algs/qgis/VectorSplit.py +++ b/python/plugins/processing/algs/qgis/VectorSplit.py @@ -67,7 +67,7 @@ def processAlgorithm(self, progress): mkdir(directory) - fieldIndex = layer.fieldNameIndex(fieldName) + fieldIndex = layer.fields().lookupField(fieldName) uniqueValues = vector.uniqueValues(layer, fieldIndex) baseName = os.path.join(directory, '{0}_{1}'.format(layer.name(), fieldName)) diff --git a/python/plugins/processing/algs/qgis/scripts/Number_of_unique_values_in_classes.py b/python/plugins/processing/algs/qgis/scripts/Number_of_unique_values_in_classes.py index 27ae12c8e53e..6a3b7fd41e96 100644 --- a/python/plugins/processing/algs/qgis/scripts/Number_of_unique_values_in_classes.py +++ b/python/plugins/processing/algs/qgis/scripts/Number_of_unique_values_in_classes.py @@ -14,8 +14,8 @@ writer = VectorWriter(N_unique_values, None, fields, layer.wkbType(), layer.crs()) -class_field_index = layer.fieldNameIndex(class_field) -value_field_index = layer.fieldNameIndex(value_field) +class_field_index = layer.fields().lookupField(class_field) +value_field_index = layer.fields().lookupField(value_field) outFeat = QgsFeature() classes = {} diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index d82ed899a8a9..169fe6d78ba2 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -156,7 +156,7 @@ def resolveFieldIndex(layer, attr): if isinstance(attr, int): return attr else: - index = layer.fieldNameIndex(str(attr)) + index = layer.fields().lookupField(attr) if index == -1: raise ValueError('Wrong field name') return index @@ -236,7 +236,7 @@ def found(name): def findOrCreateField(layer, fieldList, fieldName, fieldLen=24, fieldPrec=15): - idx = layer.fieldNameIndex(fieldName) + idx = layer.fields().lookupField(fieldName) if idx == -1: fn = createUniqueFieldName(fieldName, fieldList) field = QgsField(fn, QVariant.Double, '', fieldLen, fieldPrec) diff --git a/src/core/qgsfields.cpp b/src/core/qgsfields.cpp index ccb68b3ee9b1..ee2376cf3aa5 100644 --- a/src/core/qgsfields.cpp +++ b/src/core/qgsfields.cpp @@ -173,7 +173,12 @@ int QgsFields::fieldOriginIndex( int fieldIdx ) const return d->fields[fieldIdx].originIndex; } -int QgsFields::indexFromName( const QString &fieldName ) const +int QgsFields::indexFromName( const QString& fieldName ) const +{ + return d->nameToIndex.value( fieldName, -1 ); +} + +int QgsFields::indexOf( const QString& fieldName ) const { return d->nameToIndex.value( fieldName, -1 ); } diff --git a/src/core/qgsfields.h b/src/core/qgsfields.h index 0f2dca159379..7be72c736048 100644 --- a/src/core/qgsfields.h +++ b/src/core/qgsfields.h @@ -121,9 +121,10 @@ class CORE_EXPORT QgsFields int fieldOriginIndex( int fieldIdx ) const; /** - * Look up field's index from the field name. + * Get the field index from the field name. * This method takes is case sensitive and only matches the data source * name of the field. + * Alias for indexOf * * @param fieldName The name of the field. * @@ -132,6 +133,19 @@ class CORE_EXPORT QgsFields */ int indexFromName( const QString& fieldName ) const; + /** + * Get the field index from the field name. + * This method takes is case sensitive and only matches the data source + * name of the field. + * + * @param fieldName The name of the field. + * + * @return The field index if found or -1 in case it cannot be found. + * @see lookupField For a more tolerant alternative. + * @note Added in QGIS 3.0 + */ + int indexOf( const QString& fieldName ) const; + /** * Look up field's index from the field name. * This method matches in the following order: diff --git a/tests/src/python/offlineditingtestbase.py b/tests/src/python/offlineditingtestbase.py index a8f08fd9f2fb..d50f28c98322 100644 --- a/tests/src/python/offlineditingtestbase.py +++ b/tests/src/python/offlineditingtestbase.py @@ -152,7 +152,7 @@ def test_updateFeatures(self): # Edit feature 2 feat2 = self._getFeatureByAttribute(offline_layer, 'name', "'name 2'") self.assertTrue(offline_layer.startEditing()) - self.assertTrue(offline_layer.changeAttributeValue(feat2.id(), offline_layer.fieldNameIndex('name'), 'name 2 edited')) + self.assertTrue(offline_layer.changeAttributeValue(feat2.id(), offline_layer.fields().lookupField('name'), 'name 2 edited')) self.assertTrue(offline_layer.changeGeometry(feat2.id(), QgsGeometry.fromPoint(QgsPoint(33.0, 60.0)))) self.assertTrue(offline_layer.commitChanges()) feat2 = self._getFeatureByAttribute(offline_layer, 'name', "'name 2 edited'") @@ -182,11 +182,11 @@ def test_updateFeatures(self): # Edit feature 2 feat2 = self._getFeatureByAttribute(offline_layer, 'name', "'name 2 edited'") self.assertTrue(offline_layer.startEditing()) - self.assertTrue(offline_layer.changeAttributeValue(feat2.id(), offline_layer.fieldNameIndex('name'), 'name 2')) + self.assertTrue(offline_layer.changeAttributeValue(feat2.id(), offline_layer.fields().lookupField('name'), 'name 2')) self.assertTrue(offline_layer.changeGeometry(feat2.id(), QgsGeometry.fromPoint(TEST_FEATURES[1][2]))) # Edit feat 4 feat4 = self._getFeatureByAttribute(offline_layer, 'name', "'name 4'") - self.assertTrue(offline_layer.changeAttributeValue(feat4.id(), offline_layer.fieldNameIndex('name'), 'name 4 edited')) + self.assertTrue(offline_layer.changeAttributeValue(feat4.id(), offline_layer.fields().lookupField('name'), 'name 4 edited')) self.assertTrue(offline_layer.commitChanges()) # Sync ol.synchronize() diff --git a/tests/src/python/test_provider_mssql.py b/tests/src/python/test_provider_mssql.py index 509d87f1932c..747ce9c6f433 100644 --- a/tests/src/python/test_provider_mssql.py +++ b/tests/src/python/test_provider_mssql.py @@ -72,13 +72,13 @@ def testDateTimeTypes(self): f = next(vl.getFeatures(QgsFeatureRequest())) - date_idx = vl.fieldNameIndex('date_field') + date_idx = vl.fields().lookupField('date_field') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4)) - time_idx = vl.fieldNameIndex('time_field') + time_idx = vl.fields().lookupField('time_field') assert isinstance(f.attributes()[time_idx], QTime) self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 52)) - datetime_idx = vl.fieldNameIndex('datetime_field') + datetime_idx = vl.fields().lookupField('datetime_field') assert isinstance(f.attributes()[datetime_idx], QDateTime) self.assertEqual(f.attributes()[datetime_idx], QDateTime( QDate(2004, 3, 4), QTime(13, 41, 52))) diff --git a/tests/src/python/test_provider_oracle.py b/tests/src/python/test_provider_oracle.py index 9bc7ce81e93a..cf6bcc39a6e0 100644 --- a/tests/src/python/test_provider_oracle.py +++ b/tests/src/python/test_provider_oracle.py @@ -91,10 +91,10 @@ def testDateTimeTypes(self): f = next(vl.getFeatures(QgsFeatureRequest())) - date_idx = vl.fieldNameIndex('date_field') + date_idx = vl.fields().lookupField('date_field') self.assertTrue(isinstance(f.attributes()[date_idx], QDate)) self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4)) - datetime_idx = vl.fieldNameIndex('datetime_field') + datetime_idx = vl.fields().lookupField('datetime_field') self.assertTrue(isinstance(f.attributes()[datetime_idx], QDateTime)) self.assertEqual(f.attributes()[datetime_idx], QDateTime( QDate(2004, 3, 4), QTime(13, 41, 52))) diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 6247a6bcde2e..8c2782c79855 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -84,13 +84,13 @@ def testDateTimeTypes(self): f = next(vl.getFeatures(QgsFeatureRequest())) - date_idx = vl.fieldNameIndex('date_field') + date_idx = vl.fields().lookupField('date_field') self.assertTrue(isinstance(f.attributes()[date_idx], QDate)) self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4)) - time_idx = vl.fieldNameIndex('time_field') + time_idx = vl.fields().lookupField('time_field') self.assertTrue(isinstance(f.attributes()[time_idx], QTime)) self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 52)) - datetime_idx = vl.fieldNameIndex('datetime_field') + datetime_idx = vl.fields().lookupField('datetime_field') self.assertTrue(isinstance(f.attributes()[datetime_idx], QDateTime)) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2004, 3, 4), QTime(13, 41, 52))) @@ -165,7 +165,7 @@ def testSignedIdentifiers(self): def test_layer(ql, att, val, fidval): self.assertTrue(ql.isValid()) features = ql.getFeatures() - att_idx = ql.fieldNameIndex(att) + att_idx = ql.fields().lookupField(att) count = 0 for f in features: count += 1 @@ -344,7 +344,7 @@ def testHstore(self): f = next(vl.getFeatures(QgsFeatureRequest())) - value_idx = vl.fieldNameIndex('value') + value_idx = vl.fields().lookupField('value') self.assertTrue(isinstance(f.attributes()[value_idx], dict)) self.assertEqual(f.attributes()[value_idx], {'a': 'b', '1': '2'}) @@ -375,7 +375,7 @@ def testStringArray(self): f = next(vl.getFeatures(QgsFeatureRequest())) - value_idx = vl.fieldNameIndex('value') + value_idx = vl.fields().lookupField('value') self.assertTrue(isinstance(f.attributes()[value_idx], list)) self.assertEqual(f.attributes()[value_idx], ['a', 'b', 'c']) @@ -406,7 +406,7 @@ def testIntArray(self): f = next(vl.getFeatures(QgsFeatureRequest())) - value_idx = vl.fieldNameIndex('value') + value_idx = vl.fields().lookupField('value') self.assertTrue(isinstance(f.attributes()[value_idx], list)) self.assertEqual(f.attributes()[value_idx], [1, 2, -5]) @@ -420,7 +420,7 @@ def testDoubleArray(self): f = next(vl.getFeatures(QgsFeatureRequest())) - value_idx = vl.fieldNameIndex('value') + value_idx = vl.fields().lookupField('value') self.assertTrue(isinstance(f.attributes()[value_idx], list)) self.assertEqual(f.attributes()[value_idx], [1.1, 2, -5.12345]) diff --git a/tests/src/python/test_provider_tabfile.py b/tests/src/python/test_provider_tabfile.py index a98c3f25e4f0..edc51ba9c5c1 100644 --- a/tests/src/python/test_provider_tabfile.py +++ b/tests/src/python/test_provider_tabfile.py @@ -58,13 +58,13 @@ def testDateTimeFormats(self): f = next(vl.getFeatures(QgsFeatureRequest())) - date_idx = vl.fieldNameIndex('date') + date_idx = vl.fields().lookupField('date') assert isinstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2004, 5, 3)) - time_idx = vl.fieldNameIndex('time') + time_idx = vl.fields().lookupField('time') assert isinstance(f.attributes()[time_idx], QTime) self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 00)) - datetime_idx = vl.fieldNameIndex('date_time') + datetime_idx = vl.fields().lookupField('date_time') assert isinstance(f.attributes()[datetime_idx], QDateTime) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2004, 5, 3), QTime(13, 41, 00))) diff --git a/tests/src/python/test_qgsvectorfilewriter.py b/tests/src/python/test_qgsvectorfilewriter.py index 9e2cd10e51ad..943e61ad5420 100644 --- a/tests/src/python/test_qgsvectorfilewriter.py +++ b/tests/src/python/test_qgsvectorfilewriter.py @@ -132,15 +132,15 @@ def testDateTimeWriteShapefile(self): f = next(created_layer.getFeatures(QgsFeatureRequest())) - date_idx = created_layer.fieldNameIndex('date_f') + date_idx = created_layer.fields().lookupField('date_f') self.assertIsInstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5)) - time_idx = created_layer.fieldNameIndex('time_f') + time_idx = created_layer.fields().lookupField('time_f') #shapefiles do not support time types self.assertIsInstance(f.attributes()[time_idx], str) self.assertEqual(f.attributes()[time_idx], '13:45:22') #shapefiles do not support datetime types - datetime_idx = created_layer.fieldNameIndex('dt_f') + datetime_idx = created_layer.fields().lookupField('dt_f') self.assertIsInstance(f.attributes()[datetime_idx], str) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22)).toString("yyyy/MM/dd hh:mm:ss.zzz")) @@ -185,13 +185,13 @@ def testDateTimeWriteTabfile(self): f = next(created_layer.getFeatures(QgsFeatureRequest())) - date_idx = created_layer.fieldNameIndex('date_f') + date_idx = created_layer.fields().lookupField('date_f') self.assertIsInstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2014, 3, 5)) - time_idx = created_layer.fieldNameIndex('time_f') + time_idx = created_layer.fields().lookupField('time_f') self.assertIsInstance(f.attributes()[time_idx], QTime) self.assertEqual(f.attributes()[time_idx], QTime(13, 45, 22)) - datetime_idx = created_layer.fieldNameIndex('dt_f') + datetime_idx = created_layer.fields().lookupField('dt_f') self.assertIsInstance(f.attributes()[datetime_idx], QDateTime) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2014, 3, 5), QTime(13, 45, 22))) @@ -458,7 +458,7 @@ def testInteger64WriteTabfile(self): f = next(created_layer.getFeatures(QgsFeatureRequest())) - int8_idx = created_layer.fieldNameIndex('int8') + int8_idx = created_layer.fields().lookupField('int8') self.assertEqual(f.attributes()[int8_idx], 2123456789) def testDefaultDatasetOptions(self): From 9c1181401c47ebefdf8571159377867ba78f7a1e Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 22 Sep 2016 16:20:13 +0200 Subject: [PATCH 050/897] Add safety check to avoid crash --- src/core/qgsexpression.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 6be741bf2aec..a0fa137f6838 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3826,6 +3826,9 @@ QStringList QgsExpression::referencedColumns() const QSet QgsExpression::referencedAttributeIndexes( const QgsFields& fields ) const { + if ( !d->mRootNode ) + return QSet(); + QStringList referencedFields = d->mRootNode->referencedColumns(); QSet referencedIndexes; From 37e06ae587de1f7e0b244260fbdc19080a1e4f91 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 27 Sep 2016 13:28:46 +0200 Subject: [PATCH 051/897] Rename setAttributeAlias and removeAttributeAlias --- doc/api_break.dox | 4 +++- python/core/qgsvectorlayer.sip | 18 +++++++++++++----- src/app/qgsfieldsproperties.cpp | 4 ++-- src/core/qgsvectorlayer.cpp | 4 ++-- src/core/qgsvectorlayer.h | 18 +++++++++++++----- src/providers/ogr/qgsogrfeatureiterator.cpp | 3 ++- 6 files changed, 35 insertions(+), 16 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 94dfb2d4166c..fb718887c9c3 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1415,7 +1415,9 @@ displayExpression instead. For the map tip use mapTipTemplate() instead.
  • Deleted attributeEditorElementFromDomElement
  • editFormConfig() returns a copy instead of direct access (Use setEditFormConfig to update)
  • Removed valueRelation(), replaced with QgsEditFormConfig::editorWidgetConfig -
  • Removed fieldNameIndex(), use QgsFields::lookupField() or QgsFields::indexFromName() instead +
  • Removed fieldNameIndex(), use fields().lookupField() or fields().indexFromName() instead +
  • Renamed addAttributeAlias() to setAttributeAlias() +
  • Renamed remAttributeAlias() to removeAttributeAlias() \subsection qgis_api_break_3_0_QgsVectorLayerEditBuffer QgsVectorLayerEditBuffer diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index dfd86db5d44f..84f42737040c 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1073,17 +1073,25 @@ class QgsVectorLayer : QgsMapLayer */ bool addAttribute( const QgsField &field ); - /** Sets an alias (a display name) for attributes to display in dialogs */ - void addAttributeAlias( int attIndex, const QString& aliasString ); + /** + * Sets an alias (a display name) for attributes to display in dialogs + * + * @note Added in QGIS 3.0 + */ + void setAttributeAlias( int index, const QString& aliasString ); - /** Removes an alias (a display name) for attributes to display in dialogs */ - void remAttributeAlias( int attIndex ); + /** + * Removes an alias (a display name) for attributes to display in dialogs + * + * @note Added in QGIS 3.0 + */ + void removeAttributeAlias( int index ); /** Renames an attribute field (but does not commit it). * @param attIndex attribute index * @param newName new name of field * @note added in QGIS 2.16 - */ + */ bool renameAttribute( int attIndex, const QString& newName ); /** diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index db3ae02d635f..0ee3fc941934 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -765,11 +765,11 @@ void QgsFieldsProperties::attributesListCellChanged( int row, int column ) { if ( !aliasItem->text().trimmed().isEmpty() ) { - mLayer->addAttributeAlias( idx, aliasItem->text() ); + mLayer->setAttributeAlias( idx, aliasItem->text() ); } else { - mLayer->remAttributeAlias( idx ); + mLayer->removeAttributeAlias( idx ); } } } diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 52f27c3aa5e2..132dc0ecb00c 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -2107,7 +2107,7 @@ bool QgsVectorLayer::addAttribute( const QgsField &field ) return mEditBuffer->addAttribute( field ); } -void QgsVectorLayer::remAttributeAlias( int attIndex ) +void QgsVectorLayer::removeAttributeAlias( int attIndex ) { if ( attIndex < 0 || attIndex >= fields().count() ) return; @@ -2131,7 +2131,7 @@ bool QgsVectorLayer::renameAttribute( int attIndex, const QString& newName ) return mEditBuffer->renameAttribute( attIndex, newName ); } -void QgsVectorLayer::addAttributeAlias( int attIndex, const QString& aliasString ) +void QgsVectorLayer::setAttributeAlias( int attIndex, const QString& aliasString ) { if ( attIndex < 0 || attIndex >= fields().count() ) return; diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index b68fbf69c454..3bcf9e3e8a99 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1197,17 +1197,25 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool addAttribute( const QgsField &field ); - /** Sets an alias (a display name) for attributes to display in dialogs */ - void addAttributeAlias( int attIndex, const QString& aliasString ); + /** + * Sets an alias (a display name) for attributes to display in dialogs + * + * @note Added in QGIS 3.0 + */ + void setAttributeAlias( int index, const QString& aliasString ); - /** Removes an alias (a display name) for attributes to display in dialogs */ - void remAttributeAlias( int attIndex ); + /** + * Removes an alias (a display name) for attributes to display in dialogs + * + * @note Added in QGIS 3.0 + */ + void removeAttributeAlias( int index ); /** Renames an attribute field (but does not commit it). * @param attIndex attribute index * @param newName new name of field * @note added in QGIS 2.16 - */ + */ bool renameAttribute( int attIndex, const QString& newName ); /** diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index d2928af2cd48..a41304750b87 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -84,7 +84,8 @@ QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool //ensure that all fields required for filter expressions are prepared QSet attributeIndexes = request.filterExpression()->referencedAttributeIndexes( mSource->mFields ); attributeIndexes += attrs.toSet(); - mRequest.setSubsetOfAttributes( attributeIndexes.toList() ); + attrs = attributeIndexes.toList(); + mRequest.setSubsetOfAttributes( attrs ); } if ( request.filterType() == QgsFeatureRequest::FilterExpression && request.filterExpression()->needsGeometry() ) { From ff52a9f29bb3a87e912f161f17d9316be8369a99 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 27 Sep 2016 18:06:42 +0200 Subject: [PATCH 052/897] setAttributeAlias is now setFieldAlias --- doc/api_break.dox | 4 ++-- python/core/qgsvectorlayer.sip | 10 +++++----- src/app/qgsfieldsproperties.cpp | 4 ++-- src/core/qgsvectorlayer.cpp | 20 ++++++++++---------- src/core/qgsvectorlayer.h | 12 ++++++------ tests/src/python/test_qgsvectorlayer.py | 12 ++++++------ 6 files changed, 31 insertions(+), 31 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index fb718887c9c3..5b7e372b25e8 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1416,8 +1416,8 @@ displayExpression instead. For the map tip use mapTipTemplate() instead.
  • editFormConfig() returns a copy instead of direct access (Use setEditFormConfig to update)
  • Removed valueRelation(), replaced with QgsEditFormConfig::editorWidgetConfig
  • Removed fieldNameIndex(), use fields().lookupField() or fields().indexFromName() instead -
  • Renamed addAttributeAlias() to setAttributeAlias() -
  • Renamed remAttributeAlias() to removeAttributeAlias() +
  • Renamed addAttributeAlias() to setFieldAlias() +
  • Renamed remAttributeAlias() to removeFieldAlias() \subsection qgis_api_break_3_0_QgsVectorLayerEditBuffer QgsVectorLayerEditBuffer diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index 84f42737040c..2d815b789972 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1078,21 +1078,21 @@ class QgsVectorLayer : QgsMapLayer * * @note Added in QGIS 3.0 */ - void setAttributeAlias( int index, const QString& aliasString ); + void setFieldAlias( int index, const QString& aliasString ); /** * Removes an alias (a display name) for attributes to display in dialogs * * @note Added in QGIS 3.0 */ - void removeAttributeAlias( int index ); + void removeFieldAlias( int index ); /** Renames an attribute field (but does not commit it). * @param attIndex attribute index * @param newName new name of field * @note added in QGIS 2.16 */ - bool renameAttribute( int attIndex, const QString& newName ); + bool renameAttribute( int index, const QString& newName ); /** * Returns the alias of an attribute name or a null string if there is no alias. @@ -1100,10 +1100,10 @@ class QgsVectorLayer : QgsMapLayer * @see {attributeDisplayName( int attributeIndex )} which returns the field name * if no alias is defined. */ - QString attributeAlias( int attributeIndex ) const; + QString attributeAlias( int index ) const; /** Convenience function that returns the attribute alias if defined or the field name else */ - QString attributeDisplayName( int attributeIndex ) const; + QString attributeDisplayName( int index ) const; const QMap< QString, QString >& attributeAliases() const; diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index 0ee3fc941934..833153b04011 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -765,11 +765,11 @@ void QgsFieldsProperties::attributesListCellChanged( int row, int column ) { if ( !aliasItem->text().trimmed().isEmpty() ) { - mLayer->setAttributeAlias( idx, aliasItem->text() ); + mLayer->setFieldAlias( idx, aliasItem->text() ); } else { - mLayer->removeAttributeAlias( idx ); + mLayer->removeFieldAlias( idx ); } } } diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 132dc0ecb00c..c8837363bc80 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -2107,7 +2107,7 @@ bool QgsVectorLayer::addAttribute( const QgsField &field ) return mEditBuffer->addAttribute( field ); } -void QgsVectorLayer::removeAttributeAlias( int attIndex ) +void QgsVectorLayer::removeFieldAlias( int attIndex ) { if ( attIndex < 0 || attIndex >= fields().count() ) return; @@ -2123,15 +2123,15 @@ void QgsVectorLayer::removeAttributeAlias( int attIndex ) } } -bool QgsVectorLayer::renameAttribute( int attIndex, const QString& newName ) +bool QgsVectorLayer::renameAttribute( int index, const QString& newName ) { if ( !mEditBuffer || !mDataProvider ) return false; - return mEditBuffer->renameAttribute( attIndex, newName ); + return mEditBuffer->renameAttribute( index, newName ); } -void QgsVectorLayer::setAttributeAlias( int attIndex, const QString& aliasString ) +void QgsVectorLayer::setFieldAlias( int attIndex, const QString& aliasString ) { if ( attIndex < 0 || attIndex >= fields().count() ) return; @@ -2144,18 +2144,18 @@ void QgsVectorLayer::setAttributeAlias( int attIndex, const QString& aliasString emit layerModified(); // TODO[MD]: should have a different signal? } -QString QgsVectorLayer::attributeAlias( int attributeIndex ) const +QString QgsVectorLayer::attributeAlias( int index ) const { - if ( attributeIndex < 0 || attributeIndex >= fields().count() ) + if ( index < 0 || index >= fields().count() ) return QString(); - return fields().at( attributeIndex ).alias(); + return fields().at( index ).alias(); } -QString QgsVectorLayer::attributeDisplayName( int attributeIndex ) const +QString QgsVectorLayer::attributeDisplayName( int index ) const { - if ( attributeIndex >= 0 && attributeIndex < mFields.count() ) - return mFields.at( attributeIndex ).displayName(); + if ( index >= 0 && index < mFields.count() ) + return mFields.at( index ).displayName(); else return QString(); } diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 3bcf9e3e8a99..bd4c329e3d4c 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1202,21 +1202,21 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * * @note Added in QGIS 3.0 */ - void setAttributeAlias( int index, const QString& aliasString ); + void setFieldAlias( int index, const QString& aliasString ); /** * Removes an alias (a display name) for attributes to display in dialogs * * @note Added in QGIS 3.0 */ - void removeAttributeAlias( int index ); + void removeFieldAlias( int index ); /** Renames an attribute field (but does not commit it). - * @param attIndex attribute index + * @param index attribute index * @param newName new name of field * @note added in QGIS 2.16 */ - bool renameAttribute( int attIndex, const QString& newName ); + bool renameAttribute( int index, const QString& newName ); /** * Returns the alias of an attribute name or a null string if there is no alias. @@ -1224,10 +1224,10 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * @see {attributeDisplayName( int attributeIndex )} which returns the field name * if no alias is defined. */ - QString attributeAlias( int attributeIndex ) const; + QString attributeAlias( int index ) const; /** Convenience function that returns the attribute alias if defined or the field name else */ - QString attributeDisplayName( int attributeIndex ) const; + QString attributeDisplayName( int index ) const; //! Returns a map of field name to attribute alias QgsStringMap attributeAliases() const; diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 1e5f6372e422..8bee7f37e0d4 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1615,27 +1615,27 @@ def testGetSetAliases(self): self.assertFalse(layer.attributeAlias(1)) self.assertFalse(layer.attributeAlias(2)) - layer.addAttributeAlias(0, "test") + layer.setFieldAlias(0, "test") self.assertEqual(layer.attributeAlias(0), "test") self.assertFalse(layer.attributeAlias(1)) self.assertFalse(layer.attributeAlias(2)) self.assertEqual(layer.fields().at(0).alias(), "test") - layer.addAttributeAlias(1, "test2") + layer.setFieldAlias(1, "test2") self.assertEqual(layer.attributeAlias(0), "test") self.assertEqual(layer.attributeAlias(1), "test2") self.assertFalse(layer.attributeAlias(2)) self.assertEqual(layer.fields().at(0).alias(), "test") self.assertEqual(layer.fields().at(1).alias(), "test2") - layer.addAttributeAlias(1, None) + layer.setFieldAlias(1, None) self.assertEqual(layer.attributeAlias(0), "test") self.assertFalse(layer.attributeAlias(1)) self.assertFalse(layer.attributeAlias(2)) self.assertEqual(layer.fields().at(0).alias(), "test") self.assertFalse(layer.fields().at(1).alias()) - layer.remAttributeAlias(0) + layer.removeFieldAlias(0) self.assertFalse(layer.attributeAlias(0)) self.assertFalse(layer.attributeAlias(1)) self.assertFalse(layer.attributeAlias(2)) @@ -1657,8 +1657,8 @@ def testSaveRestoreAliases(self): self.assertFalse(layer2.attributeAlias(1)) # set some aliases - layer.addAttributeAlias(0, "test") - layer.addAttributeAlias(1, "test2") + layer.setFieldAlias(0, "test") + layer.setFieldAlias(1, "test2") doc = QDomDocument("testdoc") elem = doc.createElement("maplayer") From e45f01de138afea30c18f437ed56a22357c5ab45 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Sat, 1 Oct 2016 13:37:35 +0200 Subject: [PATCH 053/897] Fix compile errorr --- src/core/symbology-ng/qgspointdistancerenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index fd247444d76c..626e1f62a7ff 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -293,7 +293,7 @@ void QgsPointDistanceRenderer::startRender( QgsRenderContext& context, const Qgs } else { - mLabelIndex = fields.fieldNameIndex( mLabelAttributeName ); + mLabelIndex = fields.lookupField( mLabelAttributeName ); } if ( mMaxLabelScaleDenominator > 0 && context.rendererScale() > mMaxLabelScaleDenominator ) From ffaffadbfaa0ed9e6f76917dd48d2d78167b3fe1 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 1 Oct 2016 17:13:02 +0200 Subject: [PATCH 054/897] fix typos --- python/core/raster/qgsrasterdrawer.sip | 2 +- python/ext-libs/owslib/swe/common.py | 2 +- python/ext-libs/owslib/wmts.py | 2 +- python/ext-libs/owslib/wps.py | 4 ++-- python/gui/qgsunitselectionwidget.sip | 6 +++--- .../algs/otb/description/5.6.0/CompareImages.xml | 2 +- .../otb/description/5.6.0/OrthoRectification-epsg.xml | 2 +- .../5.6.0/OrthoRectification-fit-to-ortho.xml | 2 +- .../5.6.0/OrthoRectification-lambert-WGS84.xml | 2 +- .../otb/description/5.6.0/OrthoRectification-utm.xml | 2 +- .../description/5.6.0/RigidTransformResample-id.xml | 2 +- .../5.6.0/RigidTransformResample-rotation.xml | 2 +- .../5.6.0/RigidTransformResample-translation.xml | 2 +- .../algs/otb/description/5.6.0/Superimpose.xml | 2 +- .../5.6.0/doc/GridBasedImageResampling.html | 2 +- .../5.6.0/doc/HomologousPointsExtraction.html | 2 +- .../otb/description/5.6.0/doc/OpticalCalibration.html | 4 ++-- .../description/5.6.0/doc/OrthoRectification-epsg.html | 2 +- .../5.6.0/doc/OrthoRectification-fit-to-ortho.html | 2 +- .../5.6.0/doc/OrthoRectification-lambert-WGS84.html | 2 +- .../description/5.6.0/doc/OrthoRectification-utm.html | 2 +- .../otb/description/5.6.0/doc/OrthoRectification.html | 2 +- .../5.6.0/doc/RigidTransformResample-id.html | 2 +- .../5.6.0/doc/RigidTransformResample-rotation.html | 2 +- .../5.6.0/doc/RigidTransformResample-translation.html | 2 +- .../description/5.6.0/doc/RigidTransformResample.html | 2 +- .../otb/description/5.6.0/doc/Segmentation-cc.html | 4 ++-- .../description/5.6.0/doc/Segmentation-meanshift.html | 4 ++-- .../description/5.6.0/doc/Segmentation-mprofiles.html | 4 ++-- .../description/5.6.0/doc/Segmentation-watershed.html | 4 ++-- .../algs/otb/description/5.6.0/doc/Segmentation.html | 4 ++-- .../algs/otb/description/5.6.0/doc/Superimpose.html | 2 +- resources/function_help/json/array_intersect | 2 +- resources/function_help/json/array_prepend | 2 +- resources/function_help/json/map_concat | 2 +- scripts/chkspelling.sh | 2 +- src/core/qgsvectorlayerfeatureiterator.cpp | 10 +++++----- src/gui/qgsunitselectionwidget.h | 4 ++-- src/plugins/evis/README.TXT | 2 +- .../virtual/qgsvirtuallayersourceselectbase.ui | 2 +- tests/src/core/testqgsexpression.cpp | 2 +- tests/src/python/test_authmanager_endpoint.py | 2 +- tests/src/python/test_qgseditwidgets.py | 2 +- 43 files changed, 57 insertions(+), 57 deletions(-) diff --git a/python/core/raster/qgsrasterdrawer.sip b/python/core/raster/qgsrasterdrawer.sip index 557b6d1b4308..39929aff9a38 100644 --- a/python/core/raster/qgsrasterdrawer.sip +++ b/python/core/raster/qgsrasterdrawer.sip @@ -12,7 +12,7 @@ class QgsRasterDrawer /** Draws raster data. * @param p destination QPainter * @param viewPort viewport to render - * @param theQgsMapToPixel map to pixel convertor + * @param theQgsMapToPixel map to pixel converter * @param feedback optional raster feedback object for cancellation/preview. Added in QGIS 3.0. */ void draw( QPainter* p, QgsRasterViewPort* viewPort, const QgsMapToPixel* theQgsMapToPixel, QgsRasterBlockFeedback* feedback = nullptr ); diff --git a/python/ext-libs/owslib/swe/common.py b/python/ext-libs/owslib/swe/common.py index ea11064287e5..6904ed85f1fd 100644 --- a/python/ext-libs/owslib/swe/common.py +++ b/python/ext-libs/owslib/swe/common.py @@ -85,7 +85,7 @@ def __init__(self, element): self.id = testXMLAttribute(element,"id") # string, optional # Elements - self.extention = [] # anyType, min=0, max=X + self.extension = [] # anyType, min=0, max=X class AbstractSWEIdentifiable(AbstractSWE): def __init__(self, element): diff --git a/python/ext-libs/owslib/wmts.py b/python/ext-libs/owslib/wmts.py index 223513757ec2..57a61e270603 100644 --- a/python/ext-libs/owslib/wmts.py +++ b/python/ext-libs/owslib/wmts.py @@ -747,7 +747,7 @@ def __init__(self, elem, parent=None, index=0, @property def tilematrixsets(self): - # NB. This attribute has been superseeded by the + # NB. This attribute has been superceeded by the # `tilematrixsetlinks` attribute defined below, but is included # for now to provide continuity. warnings.warn("The 'tilematrixsets' attribute has been deprecated" diff --git a/python/ext-libs/owslib/wps.py b/python/ext-libs/owslib/wps.py index 3b9423493d24..b9138ec58295 100644 --- a/python/ext-libs/owslib/wps.py +++ b/python/ext-libs/owslib/wps.py @@ -1560,8 +1560,8 @@ def getXml(self): def monitorExecution(execution, sleepSecs=3, download=False, filepath=None): ''' - Convenience method to monitor the status of a WPS execution till it completes (succesfully or not), - and write the output to file after a succesfull job completion. + Convenience method to monitor the status of a WPS execution till it completes (successfully or not), + and write the output to file after a successful job completion. execution: WPSExecution instance sleepSecs: number of seconds to sleep in between check status invocations diff --git a/python/gui/qgsunitselectionwidget.sip b/python/gui/qgsunitselectionwidget.sip index eb5cbadba6f1..8f20f6f92cb9 100644 --- a/python/gui/qgsunitselectionwidget.sip +++ b/python/gui/qgsunitselectionwidget.sip @@ -1,7 +1,7 @@ /** \class QgsMapUnitScaleWidget * \ingroup gui * A widget which allows the user to choose the minimum and maximum scale of an object in map units - * and millimetres. This widget is designed to allow users to edit the properties of a + * and millimeters. This widget is designed to allow users to edit the properties of a * QgsMapUnitScale object. * \note added in QGIS 3.0 * \see QgsMapUnitScaleDialog @@ -53,7 +53,7 @@ class QgsMapUnitScaleWidget : QgsPanelWidget /** \class QgsMapUnitScaleDialog * \ingroup gui * A dialog which allows the user to choose the minimum and maximum scale of an object in map units - * and millimetres. This dialog is designed to allow users to edit the properties of a + * and millimeters. This dialog is designed to allow users to edit the properties of a * QgsMapUnitScale object. * \see QgsMapUnitScaleWidget * \see QgsUnitSelectionWidget @@ -130,7 +130,7 @@ class QgsUnitSelectionWidget : QWidget int getUnit() const; /** Returns the current predefined selected unit (if applicable). - * @returns selected output unit, or QgsSymbol::Mixed if the widget was populated with custom unit types + * @returns selected output unit, or QgsUnitTypes::RenderUnknownUnit if the widget was populated with custom unit types * @note added in QGIS 2.9 */ QgsUnitTypes::RenderUnit unit() const; diff --git a/python/plugins/processing/algs/otb/description/5.6.0/CompareImages.xml b/python/plugins/processing/algs/otb/description/5.6.0/CompareImages.xml index dc4f70d26b82..1f43f049bee5 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/CompareImages.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/CompareImages.xml @@ -1,7 +1,7 @@ CompareImages otbcli_CompareImages - Images comparaison + Image comparison Miscellaneous Estimator between 2 images. diff --git a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-epsg.xml b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-epsg.xml index 1ca3123425f6..feac1abc7c86 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-epsg.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-epsg.xml @@ -95,7 +95,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-fit-to-ortho.xml b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-fit-to-ortho.xml index 5d7ce55ef3c1..68d3fd51b22d 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-fit-to-ortho.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-fit-to-ortho.xml @@ -78,7 +78,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-lambert-WGS84.xml b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-lambert-WGS84.xml index 30f0bd09a7c1..4ba3128152a4 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-lambert-WGS84.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-lambert-WGS84.xml @@ -87,7 +87,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-utm.xml b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-utm.xml index 4f9a84fe044d..a5a76aa661db 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-utm.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/OrthoRectification-utm.xml @@ -103,7 +103,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-id.xml b/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-id.xml index 034f79e8052d..f0b20563d594 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-id.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-id.xml @@ -70,7 +70,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-rotation.xml b/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-rotation.xml index 69130b640956..ac2baad02aa2 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-rotation.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-rotation.xml @@ -80,7 +80,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-translation.xml b/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-translation.xml index f723ac8487a3..3d0700a4c494 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-translation.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/RigidTransformResample-translation.xml @@ -90,7 +90,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/Superimpose.xml b/python/plugins/processing/algs/otb/description/5.6.0/Superimpose.xml index 00453d389689..fcb4d9fa2a6b 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/Superimpose.xml +++ b/python/plugins/processing/algs/otb/description/5.6.0/Superimpose.xml @@ -78,7 +78,7 @@ ParameterNumber interpolator.bco.radius Radius for bicubic interpolation - This parameter allows controling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + This parameter allows controling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts. 2 diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/GridBasedImageResampling.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/GridBasedImageResampling.html index db4219381fd5..5d1cd7f9bb6c 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/GridBasedImageResampling.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/GridBasedImageResampling.html @@ -2,4 +2,4 @@ -

    GridBasedImageResampling

    Brief Description

    Resamples an image according to a resampling grid

    Tags

    Geometry

    Long Description

    This application allows performing image resampling from an input resampling grid.

    Parameters

    • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
    • [param] -grid <string> . Mandatory: True. Default Value: "0"
    • [param] -out <string> Parameters of the output image. Mandatory: True. Default Value: "0"
    • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
    • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
      • [group] -nn
        • [group] -linear
          • [group] -bco
            • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

        Limitations

        None

        Authors

        OTB-Team

        See Also

        otbStereorecificationGridGeneration

        Example of use

        • io.in: ROI_IKO_PAN_LesHalles_sub.tif

        • io.out: ROI_IKO_PAN_LesHalles_sub_resampled.tif uint8

        • grid.in: ROI_IKO_PAN_LesHalles_sub_deformation_field.tif

        • out.sizex: 256

        • out.sizey: 256

        • grid.type: def

        \ No newline at end of file +

        GridBasedImageResampling

        Brief Description

        Resamples an image according to a resampling grid

        Tags

        Geometry

        Long Description

        This application allows performing image resampling from an input resampling grid.

        Parameters

        • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
        • [param] -grid <string> . Mandatory: True. Default Value: "0"
        • [param] -out <string> Parameters of the output image. Mandatory: True. Default Value: "0"
        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
        • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
          • [group] -nn
            • [group] -linear
              • [group] -bco
                • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"

            Limitations

            None

            Authors

            OTB-Team

            See Also

            otbStereorecificationGridGeneration

            Example of use

            • io.in: ROI_IKO_PAN_LesHalles_sub.tif

            • io.out: ROI_IKO_PAN_LesHalles_sub_resampled.tif uint8

            • grid.in: ROI_IKO_PAN_LesHalles_sub_deformation_field.tif

            • out.sizex: 256

            • out.sizey: 256

            • grid.type: def

            diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/HomologousPointsExtraction.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/HomologousPointsExtraction.html index 39ef77e1dc46..3e6109cffcb5 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/HomologousPointsExtraction.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/HomologousPointsExtraction.html @@ -2,4 +2,4 @@ -

            HomologousPointsExtraction

            Brief Description

            Compute homologous points between images using keypoints

            Tags

            Feature Extraction

            Long Description

            This application allows computing homologous points between images using keypoints. SIFT or SURF keypoints can be used and the band on which keypoints are computed can be set independantly for both images. The application offers two modes : the first is the full mode where keypoints are extracted from the full extent of both images (please note that in this mode large image file are not supported). The second mode, called geobins, allows one to set-up spatial binning to get fewer points spread across the entire image. In this mode, the corresponding spatial bin in the second image is estimated using geographical transform or sensor modelling, and is padded according to the user defined precision. Last, in both modes the application can filter matches whose colocalisation in first image exceed this precision. The elevation parameters are to deal more precisely with sensor modelling in case of sensor geometry data. The outvector option allows creating a vector file with segments corresponding to the localisation error between the matches. It can be useful to assess the precision of a registration for instance. The vector file is always reprojected to EPSG:4326 to allow display in a GIS. This is done via reprojection or by applying the image sensor models.

            Parameters

            • [param] -in1 <string> First input image. Mandatory: True. Default Value: ""
            • [param] -band1 <int32> Index of the band from input image 1 to use for keypoints extraction. Mandatory: True. Default Value: "1"
            • [param] -in2 <string> Second input image. Mandatory: True. Default Value: ""
            • [param] -band2 <int32> Index of the band from input image 1 to use for keypoints extraction. Mandatory: True. Default Value: "1"
            • [param] -threshold <float> The distance threshold for matching.. Mandatory: True. Default Value: "0.6"
            • [param] -backmatching <boolean> If set to true, matches should be consistent in both ways.. Mandatory: False. Default Value: "True"
            • [param] -precision <float> Estimated precision of the colocalisation function in pixels. Mandatory: True. Default Value: "0"
            • [param] -mfilter <boolean> If enabled, this option allows one to filter matches according to colocalisation from sensor or geographical information, using the given tolerancy expressed in pixels. Mandatory: False. Default Value: "True"
            • [param] -2wgs84 <boolean> . Mandatory: False. Default Value: "True"
            • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
            • [param] -out <string> File containing the list of tie points. Mandatory: True. Default Value: ""
            • [param] -outvector <string> File containing segments representing matches . Mandatory: False. Default Value: ""
            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
            • [choice] -algorithm Choice of the detection algorithm to use surf,sift. Mandatory: True. Default Value: "surf"
              • [group] -surf
                • [group] -sift
                  [choice] -mode full,geobins. Mandatory: True. Default Value: "full"
                  • [group] -full
                    • [group] -geobins
                      • [param] -mode.geobins.binsize <int32> Radius of the spatial bin in pixels. Mandatory: True. Default Value: "256"
                      • [param] -mode.geobins.binsizey <int32> Radius of the spatial bin in pixels (y direction). If not set, the mode.geobins.binsize value is used.. Mandatory: False. Default Value: "0"
                      • [param] -mode.geobins.binstep <int32> Steps between bins in pixels. Mandatory: True. Default Value: "256"
                      • [param] -mode.geobins.binstepy <int32> Steps between bins in pixels (y direction). If not set, the mode.geobins.binstep value is used.. Mandatory: False. Default Value: "0"
                      • [param] -mode.geobins.margin <int32> Margin from image border to start/end bins (in pixels). Mandatory: True. Default Value: "10"

                  Limitations

                  Full mode does not handle large images.

                  Authors

                  OTB-Team

                  See Also

                  RefineSensorModel

                  Example of use

                  • in1: sensor_stereo_left.tif

                  • in2: sensor_stereo_right.tif

                  • mode: full

                  • out: homologous.txt

                  \ No newline at end of file +

                  HomologousPointsExtraction

                  Brief Description

                  Compute homologous points between images using keypoints

                  Tags

                  Feature Extraction

                  Long Description

                  This application allows computing homologous points between images using keypoints. SIFT or SURF keypoints can be used and the band on which keypoints are computed can be set independently for both images. The application offers two modes : the first is the full mode where keypoints are extracted from the full extent of both images (please note that in this mode large image file are not supported). The second mode, called geobins, allows one to set-up spatial binning to get fewer points spread across the entire image. In this mode, the corresponding spatial bin in the second image is estimated using geographical transform or sensor modelling, and is padded according to the user defined precision. Last, in both modes the application can filter matches whose colocalisation in first image exceed this precision. The elevation parameters are to deal more precisely with sensor modelling in case of sensor geometry data. The outvector option allows creating a vector file with segments corresponding to the localisation error between the matches. It can be useful to assess the precision of a registration for instance. The vector file is always reprojected to EPSG:4326 to allow display in a GIS. This is done via reprojection or by applying the image sensor models.

                  Parameters

                  • [param] -in1 <string> First input image. Mandatory: True. Default Value: ""
                  • [param] -band1 <int32> Index of the band from input image 1 to use for keypoints extraction. Mandatory: True. Default Value: "1"
                  • [param] -in2 <string> Second input image. Mandatory: True. Default Value: ""
                  • [param] -band2 <int32> Index of the band from input image 1 to use for keypoints extraction. Mandatory: True. Default Value: "1"
                  • [param] -threshold <float> The distance threshold for matching.. Mandatory: True. Default Value: "0.6"
                  • [param] -backmatching <boolean> If set to true, matches should be consistent in both ways.. Mandatory: False. Default Value: "True"
                  • [param] -precision <float> Estimated precision of the colocalisation function in pixels. Mandatory: True. Default Value: "0"
                  • [param] -mfilter <boolean> If enabled, this option allows one to filter matches according to colocalisation from sensor or geographical information, using the given tolerancy expressed in pixels. Mandatory: False. Default Value: "True"
                  • [param] -2wgs84 <boolean> . Mandatory: False. Default Value: "True"
                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                  • [param] -out <string> File containing the list of tie points. Mandatory: True. Default Value: ""
                  • [param] -outvector <string> File containing segments representing matches . Mandatory: False. Default Value: ""
                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                  • [choice] -algorithm Choice of the detection algorithm to use surf,sift. Mandatory: True. Default Value: "surf"
                    • [group] -surf
                      • [group] -sift
                        [choice] -mode full,geobins. Mandatory: True. Default Value: "full"
                        • [group] -full
                          • [group] -geobins
                            • [param] -mode.geobins.binsize <int32> Radius of the spatial bin in pixels. Mandatory: True. Default Value: "256"
                            • [param] -mode.geobins.binsizey <int32> Radius of the spatial bin in pixels (y direction). If not set, the mode.geobins.binsize value is used.. Mandatory: False. Default Value: "0"
                            • [param] -mode.geobins.binstep <int32> Steps between bins in pixels. Mandatory: True. Default Value: "256"
                            • [param] -mode.geobins.binstepy <int32> Steps between bins in pixels (y direction). If not set, the mode.geobins.binstep value is used.. Mandatory: False. Default Value: "0"
                            • [param] -mode.geobins.margin <int32> Margin from image border to start/end bins (in pixels). Mandatory: True. Default Value: "10"

                        Limitations

                        Full mode does not handle large images.

                        Authors

                        OTB-Team

                        See Also

                        RefineSensorModel

                        Example of use

                        • in1: sensor_stereo_left.tif

                        • in2: sensor_stereo_right.tif

                        • mode: full

                        • out: homologous.txt

                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/OpticalCalibration.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/OpticalCalibration.html index 7b88900b7074..e64a64b069b5 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/OpticalCalibration.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/OpticalCalibration.html @@ -56,5 +56,5 @@ # Each value must be separated with colons (:), with eventual spaces. Blank lines not allowed. 1540.494123 : 1826.087443 : 1982.671954 : 1094.747446 -Finally, the 'Logs' tab provides usefull messages that can help the user in knowing the process different status.

                        Parameters

                        • [param] -in <string> Input image filename (values in DN). Mandatory: True. Default Value: ""
                        • [param] -out <string> Output calibrated image filename. Mandatory: True. Default Value: ""
                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                        • [param] -milli <boolean> Flag to use milli-reflectance instead of reflectance. -This allows saving the image with integer pixel type (in the range [0, 1000] instead of floating point in the range [0, 1]. In order to do that, use this option and set the output pixel type (-out filename double for example). Mandatory: False. Default Value: "True"
                        • [param] -clamp <boolean> Clamping in the range [0, 100]. It can be useful to preserve area with specular reflectance.. Mandatory: False. Default Value: "True"
                        • [param] -acqui <string> This group allows setting the parameters related to the acquisition conditions.. Mandatory: True. Default Value: "0"
                        • [param] -atmo <string> This group allows setting the atmospheric parameters.. Mandatory: True. Default Value: "0"
                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                        • [choice] -level toa,toatoim,toc. Mandatory: True. Default Value: "toa"
                          • [group] -toa
                            • [group] -toatoim
                              • [group] -toc

                              Limitations

                              None

                              Authors

                              OTB-Team

                              See Also

                              The OTB CookBook

                              Example of use

                              • in: QB_1_ortho.tif

                              • level: toa

                              • out: OpticalCalibration.tif

                              \ No newline at end of file +Finally, the 'Logs' tab provides useful messages that can help the user in knowing the process different status.

                              Parameters

                              • [param] -in <string> Input image filename (values in DN). Mandatory: True. Default Value: ""
                              • [param] -out <string> Output calibrated image filename. Mandatory: True. Default Value: ""
                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                              • [param] -milli <boolean> Flag to use milli-reflectance instead of reflectance. +This allows saving the image with integer pixel type (in the range [0, 1000] instead of floating point in the range [0, 1]. In order to do that, use this option and set the output pixel type (-out filename double for example). Mandatory: False. Default Value: "True"
                              • [param] -clamp <boolean> Clamping in the range [0, 100]. It can be useful to preserve area with specular reflectance.. Mandatory: False. Default Value: "True"
                              • [param] -acqui <string> This group allows setting the parameters related to the acquisition conditions.. Mandatory: True. Default Value: "0"
                              • [param] -atmo <string> This group allows setting the atmospheric parameters.. Mandatory: True. Default Value: "0"
                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                              • [choice] -level toa,toatoim,toc. Mandatory: True. Default Value: "toa"
                                • [group] -toa
                                  • [group] -toatoim
                                    • [group] -toc

                                    Limitations

                                    None

                                    Authors

                                    OTB-Team

                                    See Also

                                    The OTB CookBook

                                    Example of use

                                    • in: QB_1_ortho.tif

                                    • level: toa

                                    • out: OpticalCalibration.tif

                                    diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-epsg.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-epsg.html index c90885e2c5c0..45127493c53e 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-epsg.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-epsg.html @@ -4,4 +4,4 @@

                                    OrthoRectification

                                    Brief Description

                                    This application allows ortho-rectification of optical images from supported sensors.

                                    Tags

                                    Geometry

                                    Long Description

                                    An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. -In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                    Parameters

                                    • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                    • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                    • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                    • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                    • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                      • [group] -utm
                                        • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                        • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                      • [group] -lambert2
                                        • [group] -lambert93
                                          • [group] -wgs
                                            • [group] -epsg
                                              • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                            [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                            • [group] -bco
                                              • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                            • [group] -nn
                                              • [group] -linear

                                              Limitations

                                              Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                              Authors

                                              OTB-Team

                                              See Also

                                              Ortho-rectification chapter from the OTB Software Guide

                                              Example of use

                                              • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                              • io.out: QB_Toulouse_ortho.tif

                                              \ No newline at end of file +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                              Parameters

                                              • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                              • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                              • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                              • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                • [group] -utm
                                                  • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                  • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                • [group] -lambert2
                                                  • [group] -lambert93
                                                    • [group] -wgs
                                                      • [group] -epsg
                                                        • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                      [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                      • [group] -bco
                                                        • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"
                                                      • [group] -nn
                                                        • [group] -linear

                                                        Limitations

                                                        Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                        Authors

                                                        OTB-Team

                                                        See Also

                                                        Ortho-rectification chapter from the OTB Software Guide

                                                        Example of use

                                                        • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                        • io.out: QB_Toulouse_ortho.tif

                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-fit-to-ortho.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-fit-to-ortho.html index c90885e2c5c0..45127493c53e 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-fit-to-ortho.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-fit-to-ortho.html @@ -4,4 +4,4 @@

                                                        OrthoRectification

                                                        Brief Description

                                                        This application allows ortho-rectification of optical images from supported sensors.

                                                        Tags

                                                        Geometry

                                                        Long Description

                                                        An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. -In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                        Parameters

                                                        • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                        • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                        • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                        • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                          • [group] -utm
                                                            • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                            • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                          • [group] -lambert2
                                                            • [group] -lambert93
                                                              • [group] -wgs
                                                                • [group] -epsg
                                                                  • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                • [group] -bco
                                                                  • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                • [group] -nn
                                                                  • [group] -linear

                                                                  Limitations

                                                                  Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                  Authors

                                                                  OTB-Team

                                                                  See Also

                                                                  Ortho-rectification chapter from the OTB Software Guide

                                                                  Example of use

                                                                  • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                  • io.out: QB_Toulouse_ortho.tif

                                                                  \ No newline at end of file +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                  Parameters

                                                                  • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                  • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                  • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                  • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                    • [group] -utm
                                                                      • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                      • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                    • [group] -lambert2
                                                                      • [group] -lambert93
                                                                        • [group] -wgs
                                                                          • [group] -epsg
                                                                            • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                          [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                          • [group] -bco
                                                                            • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"
                                                                          • [group] -nn
                                                                            • [group] -linear

                                                                            Limitations

                                                                            Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                            Authors

                                                                            OTB-Team

                                                                            See Also

                                                                            Ortho-rectification chapter from the OTB Software Guide

                                                                            Example of use

                                                                            • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                            • io.out: QB_Toulouse_ortho.tif

                                                                            diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-lambert-WGS84.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-lambert-WGS84.html index c90885e2c5c0..45127493c53e 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-lambert-WGS84.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-lambert-WGS84.html @@ -4,4 +4,4 @@

                                                                            OrthoRectification

                                                                            Brief Description

                                                                            This application allows ortho-rectification of optical images from supported sensors.

                                                                            Tags

                                                                            Geometry

                                                                            Long Description

                                                                            An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. -In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                            Parameters

                                                                            • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                            • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                            • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                            • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                            • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                              • [group] -utm
                                                                                • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                              • [group] -lambert2
                                                                                • [group] -lambert93
                                                                                  • [group] -wgs
                                                                                    • [group] -epsg
                                                                                      • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                    [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                    • [group] -bco
                                                                                      • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                    • [group] -nn
                                                                                      • [group] -linear

                                                                                      Limitations

                                                                                      Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                      Authors

                                                                                      OTB-Team

                                                                                      See Also

                                                                                      Ortho-rectification chapter from the OTB Software Guide

                                                                                      Example of use

                                                                                      • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                      • io.out: QB_Toulouse_ortho.tif

                                                                                      \ No newline at end of file +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                      Parameters

                                                                                      • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                      • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                      • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                      • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                      • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                        • [group] -utm
                                                                                          • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                          • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                        • [group] -lambert2
                                                                                          • [group] -lambert93
                                                                                            • [group] -wgs
                                                                                              • [group] -epsg
                                                                                                • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                              [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                              • [group] -bco
                                                                                                • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"
                                                                                              • [group] -nn
                                                                                                • [group] -linear

                                                                                                Limitations

                                                                                                Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                Authors

                                                                                                OTB-Team

                                                                                                See Also

                                                                                                Ortho-rectification chapter from the OTB Software Guide

                                                                                                Example of use

                                                                                                • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                • io.out: QB_Toulouse_ortho.tif

                                                                                                diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-utm.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-utm.html index c90885e2c5c0..45127493c53e 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-utm.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification-utm.html @@ -4,4 +4,4 @@

                                                                                                OrthoRectification

                                                                                                Brief Description

                                                                                                This application allows ortho-rectification of optical images from supported sensors.

                                                                                                Tags

                                                                                                Geometry

                                                                                                Long Description

                                                                                                An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. -In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                Parameters

                                                                                                • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                  • [group] -utm
                                                                                                    • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                    • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                  • [group] -lambert2
                                                                                                    • [group] -lambert93
                                                                                                      • [group] -wgs
                                                                                                        • [group] -epsg
                                                                                                          • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                        [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                        • [group] -bco
                                                                                                          • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                        • [group] -nn
                                                                                                          • [group] -linear

                                                                                                          Limitations

                                                                                                          Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                          Authors

                                                                                                          OTB-Team

                                                                                                          See Also

                                                                                                          Ortho-rectification chapter from the OTB Software Guide

                                                                                                          Example of use

                                                                                                          • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                          • io.out: QB_Toulouse_ortho.tif

                                                                                                          \ No newline at end of file +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                          Parameters

                                                                                                          • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                          • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                          • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                          • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                          • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                            • [group] -utm
                                                                                                              • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                              • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                            • [group] -lambert2
                                                                                                              • [group] -lambert93
                                                                                                                • [group] -wgs
                                                                                                                  • [group] -epsg
                                                                                                                    • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                  [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                  • [group] -bco
                                                                                                                    • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"
                                                                                                                  • [group] -nn
                                                                                                                    • [group] -linear

                                                                                                                    Limitations

                                                                                                                    Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                    Authors

                                                                                                                    OTB-Team

                                                                                                                    See Also

                                                                                                                    Ortho-rectification chapter from the OTB Software Guide

                                                                                                                    Example of use

                                                                                                                    • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                    • io.out: QB_Toulouse_ortho.tif

                                                                                                                    diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification.html index c90885e2c5c0..45127493c53e 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/OrthoRectification.html @@ -4,4 +4,4 @@

                                                                                                                    OrthoRectification

                                                                                                                    Brief Description

                                                                                                                    This application allows ortho-rectification of optical images from supported sensors.

                                                                                                                    Tags

                                                                                                                    Geometry

                                                                                                                    Long Description

                                                                                                                    An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. -In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                    Parameters

                                                                                                                    • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                    • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                    • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                    • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                    • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                      • [group] -utm
                                                                                                                        • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                        • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                      • [group] -lambert2
                                                                                                                        • [group] -lambert93
                                                                                                                          • [group] -wgs
                                                                                                                            • [group] -epsg
                                                                                                                              • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                            [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                            • [group] -bco
                                                                                                                              • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                            • [group] -nn
                                                                                                                              • [group] -linear

                                                                                                                              Limitations

                                                                                                                              Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                              Authors

                                                                                                                              OTB-Team

                                                                                                                              See Also

                                                                                                                              Ortho-rectification chapter from the OTB Software Guide

                                                                                                                              Example of use

                                                                                                                              • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                              • io.out: QB_Toulouse_ortho.tif

                                                                                                                              \ No newline at end of file +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                              Parameters

                                                                                                                              • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                              • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                              • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                              • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                • [group] -utm
                                                                                                                                  • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                  • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                • [group] -lambert2
                                                                                                                                  • [group] -lambert93
                                                                                                                                    • [group] -wgs
                                                                                                                                      • [group] -epsg
                                                                                                                                        • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                                      [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                      • [group] -bco
                                                                                                                                        • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"
                                                                                                                                      • [group] -nn
                                                                                                                                        • [group] -linear

                                                                                                                                        Limitations

                                                                                                                                        Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                                        Authors

                                                                                                                                        OTB-Team

                                                                                                                                        See Also

                                                                                                                                        Ortho-rectification chapter from the OTB Software Guide

                                                                                                                                        Example of use

                                                                                                                                        • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                        • io.out: QB_Toulouse_ortho.tif

                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-id.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-id.html index 2b3101772c0c..1ba465d54708 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-id.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-id.html @@ -2,4 +2,4 @@ -

                                                                                                                                        RigidTransformResample

                                                                                                                                        Brief Description

                                                                                                                                        Resample an image with a rigid transform

                                                                                                                                        Tags

                                                                                                                                        Conversion,Geometry

                                                                                                                                        Long Description

                                                                                                                                        This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                        Parameters

                                                                                                                                        • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                        • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                        • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                        • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                        • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                          • [group] -nn
                                                                                                                                            • [group] -linear
                                                                                                                                              • [group] -bco
                                                                                                                                                • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                            Limitations

                                                                                                                                            None

                                                                                                                                            Authors

                                                                                                                                            OTB-Team

                                                                                                                                            See Also

                                                                                                                                            Translation

                                                                                                                                            Example of use

                                                                                                                                            • in: qb_toulouse_sub.tif

                                                                                                                                            • out: rigitTransformImage.tif

                                                                                                                                            • transform.type: rotation

                                                                                                                                            • transform.type.rotation.angle: 20

                                                                                                                                            • transform.type.rotation.scalex: 2.

                                                                                                                                            • transform.type.rotation.scaley: 2.

                                                                                                                                            \ No newline at end of file +

                                                                                                                                            RigidTransformResample

                                                                                                                                            Brief Description

                                                                                                                                            Resample an image with a rigid transform

                                                                                                                                            Tags

                                                                                                                                            Conversion,Geometry

                                                                                                                                            Long Description

                                                                                                                                            This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                            Parameters

                                                                                                                                            • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                            • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                            • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                            • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                            • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                              • [group] -nn
                                                                                                                                                • [group] -linear
                                                                                                                                                  • [group] -bco
                                                                                                                                                    • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                Limitations

                                                                                                                                                None

                                                                                                                                                Authors

                                                                                                                                                OTB-Team

                                                                                                                                                See Also

                                                                                                                                                Translation

                                                                                                                                                Example of use

                                                                                                                                                • in: qb_toulouse_sub.tif

                                                                                                                                                • out: rigitTransformImage.tif

                                                                                                                                                • transform.type: rotation

                                                                                                                                                • transform.type.rotation.angle: 20

                                                                                                                                                • transform.type.rotation.scalex: 2.

                                                                                                                                                • transform.type.rotation.scaley: 2.

                                                                                                                                                diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-rotation.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-rotation.html index 2b3101772c0c..1ba465d54708 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-rotation.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-rotation.html @@ -2,4 +2,4 @@ -

                                                                                                                                                RigidTransformResample

                                                                                                                                                Brief Description

                                                                                                                                                Resample an image with a rigid transform

                                                                                                                                                Tags

                                                                                                                                                Conversion,Geometry

                                                                                                                                                Long Description

                                                                                                                                                This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                Parameters

                                                                                                                                                • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                  • [group] -nn
                                                                                                                                                    • [group] -linear
                                                                                                                                                      • [group] -bco
                                                                                                                                                        • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                    Limitations

                                                                                                                                                    None

                                                                                                                                                    Authors

                                                                                                                                                    OTB-Team

                                                                                                                                                    See Also

                                                                                                                                                    Translation

                                                                                                                                                    Example of use

                                                                                                                                                    • in: qb_toulouse_sub.tif

                                                                                                                                                    • out: rigitTransformImage.tif

                                                                                                                                                    • transform.type: rotation

                                                                                                                                                    • transform.type.rotation.angle: 20

                                                                                                                                                    • transform.type.rotation.scalex: 2.

                                                                                                                                                    • transform.type.rotation.scaley: 2.

                                                                                                                                                    \ No newline at end of file +

                                                                                                                                                    RigidTransformResample

                                                                                                                                                    Brief Description

                                                                                                                                                    Resample an image with a rigid transform

                                                                                                                                                    Tags

                                                                                                                                                    Conversion,Geometry

                                                                                                                                                    Long Description

                                                                                                                                                    This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                    Parameters

                                                                                                                                                    • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                    • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                    • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                    • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                    • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                      • [group] -nn
                                                                                                                                                        • [group] -linear
                                                                                                                                                          • [group] -bco
                                                                                                                                                            • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                        Limitations

                                                                                                                                                        None

                                                                                                                                                        Authors

                                                                                                                                                        OTB-Team

                                                                                                                                                        See Also

                                                                                                                                                        Translation

                                                                                                                                                        Example of use

                                                                                                                                                        • in: qb_toulouse_sub.tif

                                                                                                                                                        • out: rigitTransformImage.tif

                                                                                                                                                        • transform.type: rotation

                                                                                                                                                        • transform.type.rotation.angle: 20

                                                                                                                                                        • transform.type.rotation.scalex: 2.

                                                                                                                                                        • transform.type.rotation.scaley: 2.

                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-translation.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-translation.html index 2b3101772c0c..1ba465d54708 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-translation.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample-translation.html @@ -2,4 +2,4 @@ -

                                                                                                                                                        RigidTransformResample

                                                                                                                                                        Brief Description

                                                                                                                                                        Resample an image with a rigid transform

                                                                                                                                                        Tags

                                                                                                                                                        Conversion,Geometry

                                                                                                                                                        Long Description

                                                                                                                                                        This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                        Parameters

                                                                                                                                                        • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                        • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                        • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                        • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                        • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                          • [group] -nn
                                                                                                                                                            • [group] -linear
                                                                                                                                                              • [group] -bco
                                                                                                                                                                • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                            Limitations

                                                                                                                                                            None

                                                                                                                                                            Authors

                                                                                                                                                            OTB-Team

                                                                                                                                                            See Also

                                                                                                                                                            Translation

                                                                                                                                                            Example of use

                                                                                                                                                            • in: qb_toulouse_sub.tif

                                                                                                                                                            • out: rigitTransformImage.tif

                                                                                                                                                            • transform.type: rotation

                                                                                                                                                            • transform.type.rotation.angle: 20

                                                                                                                                                            • transform.type.rotation.scalex: 2.

                                                                                                                                                            • transform.type.rotation.scaley: 2.

                                                                                                                                                            \ No newline at end of file +

                                                                                                                                                            RigidTransformResample

                                                                                                                                                            Brief Description

                                                                                                                                                            Resample an image with a rigid transform

                                                                                                                                                            Tags

                                                                                                                                                            Conversion,Geometry

                                                                                                                                                            Long Description

                                                                                                                                                            This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                            Parameters

                                                                                                                                                            • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                            • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                            • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                            • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                            • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                              • [group] -nn
                                                                                                                                                                • [group] -linear
                                                                                                                                                                  • [group] -bco
                                                                                                                                                                    • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                Limitations

                                                                                                                                                                None

                                                                                                                                                                Authors

                                                                                                                                                                OTB-Team

                                                                                                                                                                See Also

                                                                                                                                                                Translation

                                                                                                                                                                Example of use

                                                                                                                                                                • in: qb_toulouse_sub.tif

                                                                                                                                                                • out: rigitTransformImage.tif

                                                                                                                                                                • transform.type: rotation

                                                                                                                                                                • transform.type.rotation.angle: 20

                                                                                                                                                                • transform.type.rotation.scalex: 2.

                                                                                                                                                                • transform.type.rotation.scaley: 2.

                                                                                                                                                                diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample.html index 2b3101772c0c..1ba465d54708 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/RigidTransformResample.html @@ -2,4 +2,4 @@ -

                                                                                                                                                                RigidTransformResample

                                                                                                                                                                Brief Description

                                                                                                                                                                Resample an image with a rigid transform

                                                                                                                                                                Tags

                                                                                                                                                                Conversion,Geometry

                                                                                                                                                                Long Description

                                                                                                                                                                This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                                Parameters

                                                                                                                                                                • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                                • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                                • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                  • [group] -nn
                                                                                                                                                                    • [group] -linear
                                                                                                                                                                      • [group] -bco
                                                                                                                                                                        • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                    Limitations

                                                                                                                                                                    None

                                                                                                                                                                    Authors

                                                                                                                                                                    OTB-Team

                                                                                                                                                                    See Also

                                                                                                                                                                    Translation

                                                                                                                                                                    Example of use

                                                                                                                                                                    • in: qb_toulouse_sub.tif

                                                                                                                                                                    • out: rigitTransformImage.tif

                                                                                                                                                                    • transform.type: rotation

                                                                                                                                                                    • transform.type.rotation.angle: 20

                                                                                                                                                                    • transform.type.rotation.scalex: 2.

                                                                                                                                                                    • transform.type.rotation.scaley: 2.

                                                                                                                                                                    \ No newline at end of file +

                                                                                                                                                                    RigidTransformResample

                                                                                                                                                                    Brief Description

                                                                                                                                                                    Resample an image with a rigid transform

                                                                                                                                                                    Tags

                                                                                                                                                                    Conversion,Geometry

                                                                                                                                                                    Long Description

                                                                                                                                                                    This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                                    Parameters

                                                                                                                                                                    • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                                    • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                    • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                                    • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                    • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                      • [group] -nn
                                                                                                                                                                        • [group] -linear
                                                                                                                                                                          • [group] -bco
                                                                                                                                                                            • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                        Limitations

                                                                                                                                                                        None

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        Translation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • in: qb_toulouse_sub.tif

                                                                                                                                                                        • out: rigitTransformImage.tif

                                                                                                                                                                        • transform.type: rotation

                                                                                                                                                                        • transform.type.rotation.angle: 20

                                                                                                                                                                        • transform.type.rotation.scalex: 2.

                                                                                                                                                                        • transform.type.rotation.scaley: 2.

                                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-cc.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-cc.html index b88a1efd82c1..d5faed62ee0b 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-cc.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-cc.html @@ -4,8 +4,8 @@

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Brief Description

                                                                                                                                                                        Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                        Tags

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Long Description

                                                                                                                                                                        This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. -In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colors. Please note that this mode loads the whole input image into memory, and as such can not handle large images. To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                        Parameters

                                                                                                                                                                        • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                          • [group] -meanshift
                                                                                                                                                                            • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                            • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                            • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                            • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                          • [group] -cc
                                                                                                                                                                            • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                          • [group] -watershed
                                                                                                                                                                            • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                            • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                          • [group] -mprofiles
                                                                                                                                                                            • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                          [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                          • [group] -vector
                                                                                                                                                                            • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                            • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                            • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                            • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                            • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                            • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                          • [group] -raster
                                                                                                                                                                            • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                        Limitations

                                                                                                                                                                        In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. MeanShift filter results depends on the number of threads used. -Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        \ No newline at end of file +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-meanshift.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-meanshift.html index b88a1efd82c1..d5faed62ee0b 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-meanshift.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-meanshift.html @@ -4,8 +4,8 @@

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Brief Description

                                                                                                                                                                        Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                        Tags

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Long Description

                                                                                                                                                                        This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. -In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colors. Please note that this mode loads the whole input image into memory, and as such can not handle large images. To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                        Parameters

                                                                                                                                                                        • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                          • [group] -meanshift
                                                                                                                                                                            • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                            • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                            • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                            • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                          • [group] -cc
                                                                                                                                                                            • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                          • [group] -watershed
                                                                                                                                                                            • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                            • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                          • [group] -mprofiles
                                                                                                                                                                            • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                          [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                          • [group] -vector
                                                                                                                                                                            • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                            • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                            • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                            • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                            • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                            • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                          • [group] -raster
                                                                                                                                                                            • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                        Limitations

                                                                                                                                                                        In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. MeanShift filter results depends on the number of threads used. -Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        \ No newline at end of file +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-mprofiles.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-mprofiles.html index b88a1efd82c1..d5faed62ee0b 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-mprofiles.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-mprofiles.html @@ -4,8 +4,8 @@

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Brief Description

                                                                                                                                                                        Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                        Tags

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Long Description

                                                                                                                                                                        This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. -In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colors. Please note that this mode loads the whole input image into memory, and as such can not handle large images. To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                        Parameters

                                                                                                                                                                        • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                          • [group] -meanshift
                                                                                                                                                                            • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                            • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                            • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                            • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                          • [group] -cc
                                                                                                                                                                            • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                          • [group] -watershed
                                                                                                                                                                            • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                            • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                          • [group] -mprofiles
                                                                                                                                                                            • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                          [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                          • [group] -vector
                                                                                                                                                                            • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                            • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                            • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                            • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                            • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                            • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                          • [group] -raster
                                                                                                                                                                            • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                        Limitations

                                                                                                                                                                        In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. MeanShift filter results depends on the number of threads used. -Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        \ No newline at end of file +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-watershed.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-watershed.html index b88a1efd82c1..d5faed62ee0b 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-watershed.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation-watershed.html @@ -4,8 +4,8 @@

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Brief Description

                                                                                                                                                                        Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                        Tags

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Long Description

                                                                                                                                                                        This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. -In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colors. Please note that this mode loads the whole input image into memory, and as such can not handle large images. To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                        Parameters

                                                                                                                                                                        • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                          • [group] -meanshift
                                                                                                                                                                            • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                            • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                            • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                            • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                          • [group] -cc
                                                                                                                                                                            • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                          • [group] -watershed
                                                                                                                                                                            • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                            • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                          • [group] -mprofiles
                                                                                                                                                                            • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                          [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                          • [group] -vector
                                                                                                                                                                            • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                            • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                            • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                            • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                            • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                            • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                          • [group] -raster
                                                                                                                                                                            • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                        Limitations

                                                                                                                                                                        In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. MeanShift filter results depends on the number of threads used. -Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        \ No newline at end of file +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation.html index b88a1efd82c1..d5faed62ee0b 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/Segmentation.html @@ -4,8 +4,8 @@

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Brief Description

                                                                                                                                                                        Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                        Tags

                                                                                                                                                                        Segmentation

                                                                                                                                                                        Long Description

                                                                                                                                                                        This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. -In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colors. Please note that this mode loads the whole input image into memory, and as such can not handle large images. To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                        Parameters

                                                                                                                                                                        • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                          • [group] -meanshift
                                                                                                                                                                            • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                            • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                            • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                            • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                          • [group] -cc
                                                                                                                                                                            • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                          • [group] -watershed
                                                                                                                                                                            • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                            • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                          • [group] -mprofiles
                                                                                                                                                                            • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                            • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                          [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                          • [group] -vector
                                                                                                                                                                            • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                            • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                            • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                            • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                            • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                            • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                            • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                            • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                            • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                          • [group] -raster
                                                                                                                                                                            • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                        Limitations

                                                                                                                                                                        In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. MeanShift filter results depends on the number of threads used. -Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        \ No newline at end of file +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                        Authors

                                                                                                                                                                        OTB-Team

                                                                                                                                                                        See Also

                                                                                                                                                                        MeanShiftSegmentation

                                                                                                                                                                        Example of use

                                                                                                                                                                        • Example of use with vector mode and watershed segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: vector

                                                                                                                                                                          • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                          • filter: watershed

                                                                                                                                                                        • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                          • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                          • mode: raster

                                                                                                                                                                          • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                          • filter: meanshift

                                                                                                                                                                        diff --git a/python/plugins/processing/algs/otb/description/5.6.0/doc/Superimpose.html b/python/plugins/processing/algs/otb/description/5.6.0/doc/Superimpose.html index 3dc2f37a031a..1dc724304b1f 100644 --- a/python/plugins/processing/algs/otb/description/5.6.0/doc/Superimpose.html +++ b/python/plugins/processing/algs/otb/description/5.6.0/doc/Superimpose.html @@ -2,4 +2,4 @@ -

                                                                                                                                                                        Superimpose

                                                                                                                                                                        Brief Description

                                                                                                                                                                        Using available image metadata, project one image onto another one

                                                                                                                                                                        Tags

                                                                                                                                                                        Geometry,Superimposition

                                                                                                                                                                        Long Description

                                                                                                                                                                        This application performs the projection of an image into the geometry of another one.

                                                                                                                                                                        Parameters

                                                                                                                                                                        • [param] -inr <string> The input reference image.. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -inm <string> The image to reproject into the geometry of the reference input.. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                        • [param] -lms <float> Generate a coarser deformation field with the given spacing. Mandatory: False. Default Value: "4"
                                                                                                                                                                        • [param] -out <string> Output reprojected image.. Mandatory: True. Default Value: ""
                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                        • [choice] -mode Superimposition mode default,phr. Mandatory: True. Default Value: "default"
                                                                                                                                                                          • [group] -default
                                                                                                                                                                            • [param] -elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                          • [group] -phr
                                                                                                                                                                            [choice] -interpolator This group of parameters allows defining how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                            • [group] -bco
                                                                                                                                                                              • [param] -interpolator.bco.radius <int32> This parameter allows controling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                            • [group] -nn
                                                                                                                                                                              • [group] -linear

                                                                                                                                                                              Limitations

                                                                                                                                                                              None

                                                                                                                                                                              Authors

                                                                                                                                                                              OTB-Team

                                                                                                                                                                              See Also

                                                                                                                                                                              Example of use

                                                                                                                                                                              • inr: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                              • inm: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                              • out: SuperimposedXS_to_PAN.tif

                                                                                                                                                                              \ No newline at end of file +

                                                                                                                                                                              Superimpose

                                                                                                                                                                              Brief Description

                                                                                                                                                                              Using available image metadata, project one image onto another one

                                                                                                                                                                              Tags

                                                                                                                                                                              Geometry,Superimposition

                                                                                                                                                                              Long Description

                                                                                                                                                                              This application performs the projection of an image into the geometry of another one.

                                                                                                                                                                              Parameters

                                                                                                                                                                              • [param] -inr <string> The input reference image.. Mandatory: True. Default Value: ""
                                                                                                                                                                              • [param] -inm <string> The image to reproject into the geometry of the reference input.. Mandatory: True. Default Value: ""
                                                                                                                                                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                              • [param] -lms <float> Generate a coarser deformation field with the given spacing. Mandatory: False. Default Value: "4"
                                                                                                                                                                              • [param] -out <string> Output reprojected image.. Mandatory: True. Default Value: ""
                                                                                                                                                                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                              • [choice] -mode Superimposition mode default,phr. Mandatory: True. Default Value: "default"
                                                                                                                                                                                • [group] -default
                                                                                                                                                                                  • [param] -elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                • [group] -phr
                                                                                                                                                                                  [choice] -interpolator This group of parameters allows defining how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                  • [group] -bco
                                                                                                                                                                                    • [param] -interpolator.bco.radius <int32> This parameter allows controling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                  • [group] -nn
                                                                                                                                                                                    • [group] -linear

                                                                                                                                                                                    Limitations

                                                                                                                                                                                    None

                                                                                                                                                                                    Authors

                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                    See Also

                                                                                                                                                                                    Example of use

                                                                                                                                                                                    • inr: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                    • inm: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                    • out: SuperimposedXS_to_PAN.tif

                                                                                                                                                                                    diff --git a/resources/function_help/json/array_intersect b/resources/function_help/json/array_intersect index 609782b6cf36..2ffc9c508c9d 100644 --- a/resources/function_help/json/array_intersect +++ b/resources/function_help/json/array_intersect @@ -3,6 +3,6 @@ "type": "function", "description": "Returns true if any element of array1 exists in array2.", "arguments": [ {"arg":"array1","description":"an array"}, - {"arg":"array2","description":"an other array"}], + {"arg":"array2","description":"another array"}], "examples": [ { "expression":"array_intersect(array(1,2,3,4),array(4,0,2,5))", "returns":"true"}] } diff --git a/resources/function_help/json/array_prepend b/resources/function_help/json/array_prepend index ead644e71bbe..a5d49c84cb65 100644 --- a/resources/function_help/json/array_prepend +++ b/resources/function_help/json/array_prepend @@ -1,7 +1,7 @@ { "name": "array_prepend", "type": "function", - "description": "Returns an array with the given value added at the begining.", + "description": "Returns an array with the given value added at the beginning.", "arguments": [ {"arg":"array","description":"an array"}, {"arg":"value","description":"the value to add"}], "examples": [ { "expression":"array_prepend(array(1,2,3),0)", "returns":"array: 0,1,2,3"}] diff --git a/resources/function_help/json/map_concat b/resources/function_help/json/map_concat index 3130934fde20..429367f2d526 100644 --- a/resources/function_help/json/map_concat +++ b/resources/function_help/json/map_concat @@ -7,6 +7,6 @@ {"arg":"map1", "syntaxOnly": true}, {"arg":"map2", "syntaxOnly": true}, {"arg":"map", "descOnly": true, "description":"a map"}], - "examples": [ { "expression":"map_concat(map('1','one', '2','overriden'),map('2','two', '3','three'))", "returns":"map: 1: 'one, 2: 'two', 3: 'three'"} + "examples": [ { "expression":"map_concat(map('1','one', '2','overridden'),map('2','two', '3','three'))", "returns":"map: 1: 'one, 2: 'two', 3: 'three'"} ] } diff --git a/scripts/chkspelling.sh b/scripts/chkspelling.sh index 40ff89ff4a8d..7494694929a5 100755 --- a/scripts/chkspelling.sh +++ b/scripts/chkspelling.sh @@ -17,6 +17,6 @@ RE=$(echo $(cut -d: -f1 scripts/spelling.dat | sed -e 's/^/\\|/;') | sed -e 's/| /|/g; s/|$//;') -EX="\.(svn-base|tmp|xpm|ts|o)|spelling\.dat|Exception_to_GPL_for_Qt.txt|sqlite3.c|qgisstyle|LexerR.py|debian/build*|ms-windows/osgeo4w|ChangeLog|src/plugins/grass/qtermwidget|src/app/gps/qwtpolar-|debian/tmp|src/plugins/dxf2shp_converter/dxflib|python/ext-libs|i18n/" +EX="\.(svn-base|tmp|xpm|ts|o)|spelling\.dat|Exception_to_GPL_for_Qt.txt|sqlite3.c|qgisstyle|LexerR.py|debian/build.*|debian/.*/usr/|ms-windows/osgeo4w|ChangeLog|src/plugins/grass/qtermwidget|src/app/gps/qwtpolar-|debian/tmp|src/plugins/dxf2shp_converter/dxflib|python/ext-libs|i18n/" egrep --exclude=*.{png,svg,db,bz2,pdf,qgs,qml,api,pyc} --exclude-dir=.git --exclude-dir=debian/build* --color=always "$RE" -ir . | egrep -iv "$EX" diff --git a/src/core/qgsvectorlayerfeatureiterator.cpp b/src/core/qgsvectorlayerfeatureiterator.cpp index 12cafd69d64c..32966eacf4ec 100644 --- a/src/core/qgsvectorlayerfeatureiterator.cpp +++ b/src/core/qgsvectorlayerfeatureiterator.cpp @@ -536,14 +536,14 @@ void QgsVectorLayerFeatureIterator::prepareExpression( int fieldIdx ) Q_FOREACH ( const QString& col, exp->referencedColumns() ) { - int dependantFieldIdx = mSource->mFields.lookupField( col ); + int dependentFieldIdx = mSource->mFields.lookupField( col ); if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) { - mRequest.setSubsetOfAttributes( mRequest.subsetOfAttributes() << dependantFieldIdx ); + mRequest.setSubsetOfAttributes( mRequest.subsetOfAttributes() << dependentFieldIdx ); } - // also need to fetch this dependant field - if ( !mPreparedFields.contains( dependantFieldIdx ) && !mFieldsToPrepare.contains( dependantFieldIdx ) ) - mFieldsToPrepare << dependantFieldIdx; + // also need to fetch this dependent field + if ( !mPreparedFields.contains( dependentFieldIdx ) && !mFieldsToPrepare.contains( dependentFieldIdx ) ) + mFieldsToPrepare << dependentFieldIdx; } if ( exp->needsGeometry() ) diff --git a/src/gui/qgsunitselectionwidget.h b/src/gui/qgsunitselectionwidget.h index 08b7a0bbf66c..3fd8ae789fd2 100644 --- a/src/gui/qgsunitselectionwidget.h +++ b/src/gui/qgsunitselectionwidget.h @@ -30,7 +30,7 @@ class QgsMapCanvas; /** \class QgsMapUnitScaleWidget * \ingroup gui * A widget which allows the user to choose the minimum and maximum scale of an object in map units - * and millimetres. This widget is designed to allow users to edit the properties of a + * and millimeters. This widget is designed to allow users to edit the properties of a * QgsMapUnitScale object. * \note added in QGIS 3.0 * \see QgsMapUnitScaleDialog @@ -90,7 +90,7 @@ class GUI_EXPORT QgsMapUnitScaleWidget : public QgsPanelWidget, private Ui::QgsM /** \class QgsMapUnitScaleDialog * \ingroup gui * A dialog which allows the user to choose the minimum and maximum scale of an object in map units - * and millimetres. This dialog is designed to allow users to edit the properties of a + * and millimeters. This dialog is designed to allow users to edit the properties of a * QgsMapUnitScale object. * \see QgsMapUnitScaleWidget * \see QgsUnitSelectionWidget diff --git a/src/plugins/evis/README.TXT b/src/plugins/evis/README.TXT index 1b394dec0eb5..a7852e156965 100644 --- a/src/plugins/evis/README.TXT +++ b/src/plugins/evis/README.TXT @@ -7,7 +7,7 @@ This plugin was originally written and distributed by the Center for Biodiversit http://biodiversityinformatics.amnh.org/open_source/evis/ eVis was contributed to the QGIS project on 2009-07-01. -eVis was started in 2007 with QGIS v0.7.0. It was our first experience with QGIS and QT. Since its early beginings, the QGIS API has under gone many changes and advances, and as a result there are still some old ideas in this code and much room for improvement. Were we to start this plugin now, we would have done it quite differently! There is still much room for imporovement. We hope the QGIS community will find eVis useful and extend its capabilities to make it even more robust. +eVis was started in 2007 with QGIS v0.7.0. It was our first experience with QGIS and QT. Since its early beginnings, the QGIS API has under gone many changes and advances, and as a result there are still some old ideas in this code and much room for improvement. Were we to start this plugin now, we would have done it quite differently! There is still much room for improvement. We hope the QGIS community will find eVis useful and extend its capabilities to make it even more robust. diff --git a/src/providers/virtual/qgsvirtuallayersourceselectbase.ui b/src/providers/virtual/qgsvirtuallayersourceselectbase.ui index f56c8defa10b..ed38209cf6d8 100644 --- a/src/providers/virtual/qgsvirtuallayersourceselectbase.ui +++ b/src/providers/virtual/qgsvirtuallayersourceselectbase.ui @@ -165,7 +165,7 @@ In particular, saving a virtual layer with embedded layers to a QLR file can be - <html><head/><body><p>This is the SQL query editor. You can edit here an SQL query refering to any existing vector layers or embedded layers.</p><p>Virtual layers rely on SQLite and Spatialite. Any functions from SQLite or Spatialite can then be used in the query. To add or access geometries of a table, you can use "tablename.geometry", regardless of original geometry column's name.</p><p><span style=" font-weight:600;">Special comments:</span></p><p>Because it is not always possible to autodetect the data type of each column in a query, special comments can be used in the query to force a specific type.</p><p>Special comments must be placed on the right of a column name and have the form <tt>/*:type*/</tt> where type can be any of <span style=" font-style:italic;">int</span>, <span style=" font-style:italic;">real</span> or <span style=" font-style:italic;">text</span>. They can also be used to specify the type and SRID of the geometry column with the following syntax: <tt>/*:gtype:srid*/</tt> where <span style=" font-style:italic;">gtype</span> can be <span style=" font-style:italic;">point</span>, <span style=" font-style:italic;">linestring</span> or <span style=" font-style:italic;">polygon</span> (with an optional <span style=" font-style:italic;">multi</span> prefix) and <span style=" font-style:italic;">srid</span> is an integer identifier.</p><p>Example:</p><p><tt>SELECT id + 1 as id /*:int*/, ST_Centroid(geometry) as geom /*:point:4326*/ FROM tab</tt></p></body></html> + <html><head/><body><p>This is the SQL query editor. You can edit here an SQL query referring to any existing vector layers or embedded layers.</p><p>Virtual layers rely on SQLite and Spatialite. Any functions from SQLite or Spatialite can then be used in the query. To add or access geometries of a table, you can use "tablename.geometry", regardless of original geometry column's name.</p><p><span style=" font-weight:600;">Special comments:</span></p><p>Because it is not always possible to autodetect the data type of each column in a query, special comments can be used in the query to force a specific type.</p><p>Special comments must be placed on the right of a column name and have the form <tt>/*:type*/</tt> where type can be any of <span style=" font-style:italic;">int</span>, <span style=" font-style:italic;">real</span> or <span style=" font-style:italic;">text</span>. They can also be used to specify the type and SRID of the geometry column with the following syntax: <tt>/*:gtype:srid*/</tt> where <span style=" font-style:italic;">gtype</span> can be <span style=" font-style:italic;">point</span>, <span style=" font-style:italic;">linestring</span> or <span style=" font-style:italic;">polygon</span> (with an optional <span style=" font-style:italic;">multi</span> prefix) and <span style=" font-style:italic;">srid</span> is an integer identifier.</p><p>Example:</p><p><tt>SELECT id + 1 as id /*:int*/, ST_Centroid(geometry) as geom /*:point:4326*/ FROM tab</tt></p></body></html> diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index ae2f372e6590..24701b60f982 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -2320,7 +2320,7 @@ class TestQgsExpression: public QObject concatExpected["1"] = "one"; concatExpected["2"] = "two"; concatExpected["3"] = "three"; - QCOMPARE( QgsExpression( "map_concat(map('1', 'one', '2', 'overriden by next map'), map('2', 'two', '3', 'three'))" ).evaluate( &context ), QVariant( concatExpected ) ); + QCOMPARE( QgsExpression( "map_concat(map('1', 'one', '2', 'overridden by next map'), map('2', 'two', '3', 'three'))" ).evaluate( &context ), QVariant( concatExpected ) ); QStringList keysExpected; keysExpected << "1" << "2"; diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_endpoint.py index 85bc68fddcef..3b0429442859 100644 --- a/tests/src/python/test_authmanager_endpoint.py +++ b/tests/src/python/test_authmanager_endpoint.py @@ -145,7 +145,7 @@ def _getWMSLayer(cls, layers, layer_name=None, authcfg=None): 'crs': 'EPSG:4326', 'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path), 'format': 'image/png', - # This is needed because of a really wierd implementation in QGIS Server, that + # This is needed because of a really weird implementation in QGIS Server, that # replaces _ in the the real layer name with spaces 'layers': urllib.parse.quote(layers).replace('_', ' '), 'styles': '', diff --git a/tests/src/python/test_qgseditwidgets.py b/tests/src/python/test_qgseditwidgets.py index 1651030fe938..939004556b78 100644 --- a/tests/src/python/test_qgseditwidgets.py +++ b/tests/src/python/test_qgseditwidgets.py @@ -107,7 +107,7 @@ def test_ValueMap_representValue(self): factory = reg.factory("ValueMap") self.assertIsNotNone(factory) - # Tests with different value types occuring in the value map + # Tests with different value types occurring in the value map config = {'two': '2', 'twoandhalf': '2.5', 'NULL text': 'NULL', 'nothing': self.VALUEMAP_NULL_TEXT} self.assertEqual(factory.representValue(layer, 0, config, None, 2), 'two') From 17db101cb5db1c72b434bcbaa00a2df8283b8478 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 2 Oct 2016 09:30:04 +1100 Subject: [PATCH 055/897] Fix Coverity uninitialized variable warnings --- src/core/qgsattributeeditorelement.h | 5 ++++- src/gui/qgsunitselectionwidget.cpp | 1 + src/plugins/grass/qgsgrassregion.cpp | 1 + src/providers/grass/qgsgrass.cpp | 6 +++--- src/providers/oracle/ocispatial/wkbptr.h | 9 +++++++++ src/providers/wms/qgswmsprovider.cpp | 2 ++ src/server/qgsserverlogger.cpp | 8 +++----- 7 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/core/qgsattributeeditorelement.h b/src/core/qgsattributeeditorelement.h index c02bbab62b8a..4c34336ba5bf 100644 --- a/src/core/qgsattributeeditorelement.h +++ b/src/core/qgsattributeeditorelement.h @@ -313,7 +313,10 @@ class CORE_EXPORT QgsAttributeEditorRelation : public QgsAttributeEditorElement QgsAttributeEditorRelation( const QString& name, const QgsRelation& relation, QgsAttributeEditorElement* parent ) : QgsAttributeEditorElement( AeTypeRelation, name, parent ) , mRelationId( relation.id() ) - , mRelation( relation ) {} + , mRelation( relation ) + , mShowLinkButton( true ) + , mShowUnlinkButton( true ) + {} //! Destructor virtual ~QgsAttributeEditorRelation() {} diff --git a/src/gui/qgsunitselectionwidget.cpp b/src/gui/qgsunitselectionwidget.cpp index 2885ee5fdd6b..e5426405db59 100644 --- a/src/gui/qgsunitselectionwidget.cpp +++ b/src/gui/qgsunitselectionwidget.cpp @@ -125,6 +125,7 @@ QgsMapUnitScale QgsMapUnitScaleWidget::mapUnitScale() const QgsUnitSelectionWidget::QgsUnitSelectionWidget( QWidget *parent ) : QWidget( parent ) + , mCanvas( nullptr ) { mMapUnitIdx = -1; diff --git a/src/plugins/grass/qgsgrassregion.cpp b/src/plugins/grass/qgsgrassregion.cpp index 5f9e12ad4417..6af9b218fde3 100644 --- a/src/plugins/grass/qgsgrassregion.cpp +++ b/src/plugins/grass/qgsgrassregion.cpp @@ -200,6 +200,7 @@ QgsGrassRegion::QgsGrassRegion( QgisInterface *iface, , mRegionEdit( 0 ) { QgsDebugMsg( "QgsGrassRegion()" ); + QgsGrass::initRegion( &mWindow ); setupUi( this ); setAttribute( Qt::WA_DeleteOnClose ); diff --git a/src/providers/grass/qgsgrass.cpp b/src/providers/grass/qgsgrass.cpp index 8204bb8d4fa7..f23ecce0f34d 100644 --- a/src/providers/grass/qgsgrass.cpp +++ b/src/providers/grass/qgsgrass.cpp @@ -1686,14 +1686,14 @@ bool QgsGrass::writeRegion( const QString& gisbase, const QString& location, const QString& mapset, const struct Cell_head *window ) { - QgsDebugMsg( QString( "n = %1 s = %2" ).arg( window->north ).arg( window->south ) ); - QgsDebugMsg( QString( "e = %1 w = %2" ).arg( window->east ).arg( window->west ) ); - if ( !window ) { return false; } + QgsDebugMsg( QString( "n = %1 s = %2" ).arg( window->north ).arg( window->south ) ); + QgsDebugMsg( QString( "e = %1 w = %2" ).arg( window->east ).arg( window->west ) ); + QgsGrass::setMapset( gisbase, location, mapset ); if ( G_put_window( window ) == -1 ) diff --git a/src/providers/oracle/ocispatial/wkbptr.h b/src/providers/oracle/ocispatial/wkbptr.h index ab5e929e946e..c5d87b5ae4e5 100644 --- a/src/providers/oracle/ocispatial/wkbptr.h +++ b/src/providers/oracle/ocispatial/wkbptr.h @@ -52,6 +52,15 @@ enum SDO_GTYPE_TT class QOCISpatialGeometry : public QSharedData { public: + QOCISpatialGeometry() + : isNull( true ) + , gtype( -1 ) + , srid( -1 ) + , x( 0.0 ) + , y( 0.0 ) + , z( 0.0 ) + {} + bool isNull; int gtype; int srid; diff --git a/src/providers/wms/qgswmsprovider.cpp b/src/providers/wms/qgswmsprovider.cpp index 188cc99d72a4..8e3e4dfe45ed 100644 --- a/src/providers/wms/qgswmsprovider.cpp +++ b/src/providers/wms/qgswmsprovider.cpp @@ -1218,6 +1218,7 @@ void QgsWmsProvider::setupXyzCapabilities( const QString &uri ) tm.tileWidth = tm.tileHeight = 256; tm.matrixWidth = tm.matrixHeight = 1 << zoom; tm.tres = xspan / ( tm.tileWidth * tm.matrixWidth ); + tm.scaleDenom = 0.0; mCaps.mTileMatrixSets[tms.identifier].tileMatrices[tm.tres] = tm; } @@ -3518,6 +3519,7 @@ QGISEXTERN bool isProvider() QgsWmsImageDownloadHandler::QgsWmsImageDownloadHandler( const QString& providerUri, const QUrl& url, const QgsWmsAuthorization& auth, QImage* image, QgsRasterBlockFeedback* feedback ) : mProviderUri( providerUri ) + , mCacheReply( nullptr ) , mCachedImage( image ) , mEventLoop( new QEventLoop ) , mFeedback( feedback ) diff --git a/src/server/qgsserverlogger.cpp b/src/server/qgsserverlogger.cpp index 6e7edeb6d0e7..8d4827a2d560 100644 --- a/src/server/qgsserverlogger.cpp +++ b/src/server/qgsserverlogger.cpp @@ -34,7 +34,9 @@ QgsServerLogger* QgsServerLogger::instance() return mInstance; } -QgsServerLogger::QgsServerLogger(): mLogFile( nullptr ) +QgsServerLogger::QgsServerLogger() + : mLogFile( nullptr ) + , mLogLevel( 3 ) { //logfile QString filePath = getenv( "QGIS_SERVER_LOG_FILE" ); @@ -53,10 +55,6 @@ QgsServerLogger::QgsServerLogger(): mLogFile( nullptr ) { mLogLevel = atoi( logLevelChar ); } - else - { - mLogLevel = 3; - } connect( QgsMessageLog::instance(), SIGNAL( messageReceived( QString, QString, QgsMessageLog::MessageLevel ) ), this, SLOT( logMessage( QString, QString, QgsMessageLog::MessageLevel ) ) ); From 4b7876c1f222e36a1505bac44b87fde8b686fd22 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 09:50:25 +1000 Subject: [PATCH 056/897] Fix some Coverity null derefence warnings --- .../qgscomposertablebackgroundcolorsdialog.cpp | 10 ++++++---- src/app/nodetool/qgsmaptoolnodetool.cpp | 7 ++++--- src/app/qgsvectorlayerproperties.cpp | 5 ++++- src/core/composer/qgscomposertablev2.cpp | 8 ++++++-- src/core/symbology-ng/qgscptcityarchive.cpp | 4 ++-- 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp b/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp index 39305c7c93e3..33cc88a31d16 100644 --- a/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp +++ b/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp @@ -73,13 +73,15 @@ void QgsComposerTableBackgroundColorsDialog::apply() composition->beginMultiFrameCommand( mComposerTable, tr( "Table background customisation" ), QgsComposerMultiFrameMergeCommand::TableCellStyle ); } - Q_FOREACH ( QgsComposerTableV2::CellStyleGroup styleGroup, mCheckBoxMap.keys() ) + QMap< QgsComposerTableV2::CellStyleGroup, QCheckBox* >::const_iterator checkBoxIt = mCheckBoxMap.constBegin(); + for ( ; checkBoxIt != mCheckBoxMap.constEnd(); ++checkBoxIt ) { QgsComposerTableStyle style; - style.enabled = mCheckBoxMap.value( styleGroup )->isChecked(); - style.cellBackgroundColor = mColorButtonMap.value( styleGroup )->color(); + style.enabled = checkBoxIt.value()->isChecked(); + if ( QgsColorButton* button = mColorButtonMap.value( checkBoxIt.key() ) ) + style.cellBackgroundColor = button->color(); - mComposerTable->setCellStyle( styleGroup, style ); + mComposerTable->setCellStyle( checkBoxIt.key(), style ); } mComposerTable->setBackgroundColor( mDefaultColorButton->color() ); diff --git a/src/app/nodetool/qgsmaptoolnodetool.cpp b/src/app/nodetool/qgsmaptoolnodetool.cpp index 99f6590735ce..b1f8b19bbde1 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.cpp +++ b/src/app/nodetool/qgsmaptoolnodetool.cpp @@ -166,13 +166,14 @@ void QgsMapToolNodeTool::canvasMoveEvent( QgsMapMouseEvent* e ) double deltaX = curPos.x() - pressPos.x(); double deltaY = curPos.y() - pressPos.y(); - Q_FOREACH ( QgsFeatureId fid, mMoveRubberBands.keys() ) + QMap::const_iterator moveBandsIt = mMoveRubberBands.constBegin(); + for ( ; moveBandsIt != mMoveRubberBands.constEnd(); ++moveBandsIt ) { typedef QPair MoveVertex; - Q_FOREACH ( const MoveVertex& pair, mMoveVertices[fid] ) + Q_FOREACH ( const MoveVertex& pair, mMoveVertices[ moveBandsIt.key()] ) { QgsPointV2 newPos( pair.second.x() + deltaX, pair.second.y() + deltaY ); - mMoveRubberBands.value( fid )->moveVertex( pair.first, newPos ); + moveBandsIt.value()->moveVertex( pair.first, newPos ); } } } diff --git a/src/app/qgsvectorlayerproperties.cpp b/src/app/qgsvectorlayerproperties.cpp index 61ca00117477..bf7c5ab57a84 100644 --- a/src/app/qgsvectorlayerproperties.cpp +++ b/src/app/qgsvectorlayerproperties.cpp @@ -295,7 +295,10 @@ QgsVectorLayerProperties::QgsVectorLayerProperties( mLayersDependenciesTreeGroup.reset( QgsProject::instance()->layerTreeRoot()->clone() ); QgsLayerTreeLayer* layer = mLayersDependenciesTreeGroup->findLayer( mLayer->id() ); - layer->parent()->takeChild( layer ); + if ( layer ) + { + layer->parent()->takeChild( layer ); + } mLayersDependenciesTreeModel.reset( new QgsLayerTreeModel( mLayersDependenciesTreeGroup.data() ) ); // use visibility as selection mLayersDependenciesTreeModel->setFlag( QgsLayerTreeModel::AllowNodeChangeVisibility ); diff --git a/src/core/composer/qgscomposertablev2.cpp b/src/core/composer/qgscomposertablev2.cpp index 8fb228f9442a..c9548fe58683 100644 --- a/src/core/composer/qgscomposertablev2.cpp +++ b/src/core/composer/qgscomposertablev2.cpp @@ -142,8 +142,12 @@ bool QgsComposerTableV2::writeXml( QDomElement& elem, QDomDocument & doc, bool i { QString styleName = it.value(); QDomElement styleElem = doc.createElement( styleName ); - mCellStyles.value( it.key() )->writeXml( styleElem, doc ); - stylesElem.appendChild( styleElem ); + QgsComposerTableStyle* style = mCellStyles.value( it.key() ); + if ( style ) + { + style->writeXml( styleElem, doc ); + stylesElem.appendChild( styleElem ); + } } elem.appendChild( stylesElem ); diff --git a/src/core/symbology-ng/qgscptcityarchive.cpp b/src/core/symbology-ng/qgscptcityarchive.cpp index 58693d5a1bb8..ecb187eccb34 100644 --- a/src/core/symbology-ng/qgscptcityarchive.cpp +++ b/src/core/symbology-ng/qgscptcityarchive.cpp @@ -115,8 +115,8 @@ QString QgsCptCityArchive::baseDir( QString archiveName ) // search for matching archive in the registry if ( archiveName.isNull() ) archiveName = DEFAULT_CPTCITY_ARCHIVE; - if ( mArchiveRegistry.contains( archiveName ) ) - return mArchiveRegistry.value( archiveName )->baseDir(); + if ( QgsCptCityArchive* archive = mArchiveRegistry.value( archiveName, nullptr ) ) + return archive->baseDir(); else return defaultBaseDir(); } From 230417c7a8d36ac67eda5332fa6fc7b2f84bcf9e Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 2 Oct 2016 22:10:01 +1100 Subject: [PATCH 057/897] Add method to create QgsMapToPixel from scale/dpi/mapunits --- python/core/qgsmaptopixel.sip | 9 +++++++++ src/core/qgsmaptopixel.cpp | 8 ++++++++ src/core/qgsmaptopixel.h | 11 ++++++++++- tests/src/core/testqgsmaptopixel.cpp | 14 ++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/python/core/qgsmaptopixel.sip b/python/core/qgsmaptopixel.sip index 78d9b4c898ce..cda77dfb60cb 100644 --- a/python/core/qgsmaptopixel.sip +++ b/python/core/qgsmaptopixel.sip @@ -30,6 +30,15 @@ class QgsMapToPixel */ QgsMapToPixel( double mapUnitsPerPixel ); + /** Returns a new QgsMapToPixel created using a specified scale and distance unit. + * @param scale map scale + * @param dpi screen DPI + * @param mapUnits map units + * @returns matching QgsMapToPixel + * @note added in QGIS 3.0 + */ + static QgsMapToPixel fromScale( double scale, QgsUnitTypes::DistanceUnit mapUnits, double dpi = 96 ); + /** * Constructor * diff --git a/src/core/qgsmaptopixel.cpp b/src/core/qgsmaptopixel.cpp index 209f0023c6f2..320aa617171c 100644 --- a/src/core/qgsmaptopixel.cpp +++ b/src/core/qgsmaptopixel.cpp @@ -24,6 +24,7 @@ #include "qgslogger.h" #include "qgspoint.h" + QgsMapToPixel::QgsMapToPixel( double mapUnitsPerPixel, double xc, double yc, @@ -56,6 +57,13 @@ QgsMapToPixel::QgsMapToPixel( double mapUnitsPerPixel ) updateMatrix(); } +QgsMapToPixel QgsMapToPixel::fromScale( double scale, QgsUnitTypes::DistanceUnit mapUnits, double dpi ) +{ + double metresPerPixel = 25.4 / dpi / 1000.0; + double mapUnitsPerPixel = metresPerPixel * QgsUnitTypes::fromUnitToUnitFactor( QgsUnitTypes::DistanceMeters, mapUnits ); + return QgsMapToPixel( mapUnitsPerPixel / scale ); +} + QgsMapToPixel::QgsMapToPixel() : mMapUnitsPerPixel( 1 ) , mWidth( 1 ) diff --git a/src/core/qgsmaptopixel.h b/src/core/qgsmaptopixel.h index 9f0bd0acb96c..f6d07891bdb2 100644 --- a/src/core/qgsmaptopixel.h +++ b/src/core/qgsmaptopixel.h @@ -19,7 +19,7 @@ #include #include - +#include "qgsunittypes.h" #include class QgsPoint; @@ -52,6 +52,15 @@ class CORE_EXPORT QgsMapToPixel */ QgsMapToPixel( double mapUnitsPerPixel ); + /** Returns a new QgsMapToPixel created using a specified scale and distance unit. + * @param scale map scale + * @param dpi screen DPI + * @param mapUnits map units + * @returns matching QgsMapToPixel + * @note added in QGIS 3.0 + */ + static QgsMapToPixel fromScale( double scale, QgsUnitTypes::DistanceUnit mapUnits, double dpi = 96 ); + /** * Constructor * diff --git a/tests/src/core/testqgsmaptopixel.cpp b/tests/src/core/testqgsmaptopixel.cpp index 3bf01f960322..d767f70cf7b3 100644 --- a/tests/src/core/testqgsmaptopixel.cpp +++ b/tests/src/core/testqgsmaptopixel.cpp @@ -20,6 +20,7 @@ #include #include #include "qgslogger.h" +#include "qgstestutils.h" class TestQgsMapToPixel: public QObject { @@ -27,6 +28,7 @@ class TestQgsMapToPixel: public QObject private slots: void rotation(); void getters(); + void fromScale(); }; void TestQgsMapToPixel::rotation() @@ -92,6 +94,18 @@ void TestQgsMapToPixel::getters() QCOMPARE( m2p.mapUnitsPerPixel(), 2.0 ); } +void TestQgsMapToPixel::fromScale() +{ + QgsMapToPixel m2p = QgsMapToPixel::fromScale( 0.001, QgsUnitTypes::DistanceMeters, 96.0 ); + QGSCOMPARENEAR( m2p.mapUnitsPerPixel(), 0.264583, 0.000001 ); + m2p = QgsMapToPixel::fromScale( 0.0001, QgsUnitTypes::DistanceMeters, 96.0 ); + QGSCOMPARENEAR( m2p.mapUnitsPerPixel(), 2.645833, 0.000001 ); + m2p = QgsMapToPixel::fromScale( 0.001, QgsUnitTypes::DistanceMeters, 72.0 ); + QGSCOMPARENEAR( m2p.mapUnitsPerPixel(), 0.352778, 0.000001 ); + m2p = QgsMapToPixel::fromScale( 0.001, QgsUnitTypes::DistanceKilometers, 96.0 ); + QGSCOMPARENEAR( m2p.mapUnitsPerPixel(), 0.000265, 0.000001 ); +} + QTEST_MAIN( TestQgsMapToPixel ) #include "testqgsmaptopixel.moc" From c4bf35cc9cb664965d3a938576f1fef1b62fef10 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 10:21:15 +1000 Subject: [PATCH 058/897] Default to WITH_QWTPOLAR OFF Since it's not compatible with Qt5 builds --- src/app/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 26a59169ae59..aaab88c269e3 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -345,7 +345,7 @@ SET (QGIS_APP_MOC_HDRS qgsvariantdelegate.h ) -SET (WITH_QWTPOLAR TRUE CACHE BOOL "Determines whether QwtPolar should be built") +SET (WITH_QWTPOLAR FALSE CACHE BOOL "Determines whether QwtPolar should be built") IF (WITH_QWTPOLAR) ADD_DEFINITIONS(-DWITH_QWTPOLAR) From ba210d015004ea85c32422a7f28d8b3815e660eb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 11:18:54 +1000 Subject: [PATCH 059/897] Fix build with GDAL < 2 --- src/providers/wfs/qgswfsshareddata.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/wfs/qgswfsshareddata.cpp b/src/providers/wfs/qgswfsshareddata.cpp index 12bcf765e0f3..adb20bb490b6 100644 --- a/src/providers/wfs/qgswfsshareddata.cpp +++ b/src/providers/wfs/qgswfsshareddata.cpp @@ -249,7 +249,7 @@ bool QgsWFSSharedData::createCache() // do it manually bool useReservedNames = cacheFields.lookupField( "ogc_fid" ) >= 0; #if GDAL_VERSION_MAJOR < 2 - if ( cacheFields.fieldNameIndex( "geometry" ) >= 0 ) + if ( cacheFields.lookupField( "geometry" ) >= 0 ) useReservedNames = true; #endif if ( !useReservedNames ) From dc481955a5848ee355238bf93f82068de71aca4f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 11:42:53 +1000 Subject: [PATCH 060/897] Fix many labeling unit settings are lost on closing dialog (and also don't trigger auto preview) --- src/app/qgslabelinggui.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index b5927059d1dd..cb252368f5db 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -352,6 +352,7 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mLineDistanceDDBtn << mLineDistanceSpnBx << mLineDistanceUnitDDBtn + << mLineDistanceUnitWidget << mMaxCharAngleDDBtn << mMaxCharAngleInDSpinBox << mMaxCharAngleOutDSpinBox @@ -365,6 +366,7 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mPointAngleSpinBox << mPointOffsetDDBtn << mPointOffsetUnitsDDBtn + << mPointOffsetUnitWidget << mPointOffsetXSpinBox << mPointOffsetYSpinBox << mPointPositionOrderDDBtn @@ -376,6 +378,7 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mRepeatDistanceDDBtn << mRepeatDistanceSpinBox << mRepeatDistanceUnitDDBtn + << mRepeatDistanceUnitWidget << mScaleBasedVisibilityChkBx << mScaleBasedVisibilityDDBtn << mScaleBasedVisibilityMaxDDBtn @@ -394,10 +397,12 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mShadowOffsetGlobalChkBx << mShadowOffsetSpnBx << mShadowOffsetUnitsDDBtn + << mShadowOffsetUnitWidget << mShadowRadiusAlphaChkBx << mShadowRadiusDDBtn << mShadowRadiusDblSpnBx << mShadowRadiusUnitsDDBtn + << mShadowRadiusUnitWidget << mShadowScaleDDBtn << mShadowScaleSpnBx << mShadowTranspDDBtn @@ -411,6 +416,7 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mShapeBorderUnitsDDBtn << mShapeBorderWidthDDBtn << mShapeBorderWidthSpnBx + << mShapeBorderWidthUnitWidget << mShapeDrawChkBx << mShapeDrawDDBtn << mShapeFillColorBtn @@ -419,6 +425,7 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mShapeOffsetUnitsDDBtn << mShapeOffsetXSpnBx << mShapeOffsetYSpnBx + << mShapeOffsetUnitWidget << mShapePenStyleCmbBx << mShapePenStyleDDBtn << mShapeRadiusDDBtn @@ -429,11 +436,13 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, << mShapeRotationDDBtn << mShapeRotationDblSpnBx << mShapeRotationTypeDDBtn + << mShapeRadiusUnitWidget << mShapeSVGPathDDBtn << mShapeSVGPathLineEdit << mShapeSizeCmbBx << mShapeSizeTypeDDBtn << mShapeSizeUnitsDDBtn + << mShapeSizeUnitWidget << mShapeSizeXDDBtn << mShapeSizeXSpnBx << mShapeSizeYDDBtn @@ -507,6 +516,10 @@ void QgsLabelingGui::connectValueChanged( QList widgets, const char * { connect( w, SIGNAL( fieldChanged( QString ) ), this, slot ); } + else if ( QgsUnitSelectionWidget* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( changed() ), this, slot ); + } else if ( QComboBox* w = qobject_cast( widget ) ) { connect( w, SIGNAL( currentIndexChanged( int ) ), this, slot ); From 82eeeac57f49fba59b275ee0e42b103622f6fad4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 12:15:15 +1000 Subject: [PATCH 061/897] Fix invalid debugging noise --- src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp index b697010ae243..3e0aeccd52a9 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp @@ -161,7 +161,7 @@ QgsCategorizedSymbolRenderer::QgsCategorizedSymbolRenderer( const QString& attrN //trigger a detachment and copy of mCategories BUT that same method CAN be used to modify a symbol in place Q_FOREACH ( const QgsRendererCategory& cat, categories ) { - if ( cat.symbol() ) + if ( !cat.symbol() ) { QgsDebugMsg( "invalid symbol in a category! ignoring..." ); } From 0a9491a20f6b681a3f4505f952f742caf756dee6 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 12:19:43 +1000 Subject: [PATCH 062/897] Fix oracle build --- src/providers/oracle/qgsoraclefeatureiterator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/oracle/qgsoraclefeatureiterator.cpp b/src/providers/oracle/qgsoraclefeatureiterator.cpp index a8db8272055f..2190c7ee5c49 100644 --- a/src/providers/oracle/qgsoraclefeatureiterator.cpp +++ b/src/providers/oracle/qgsoraclefeatureiterator.cpp @@ -51,7 +51,7 @@ QgsOracleFeatureIterator::QgsOracleFeatureIterator( QgsOracleFeatureSource* sour { Q_FOREACH ( const QString& field, mRequest.filterExpression()->referencedColumns() ) { - int attrIdx = mSource->mFields.fieldNameIndex( field ); + int attrIdx = mSource->mFields.lookupField( field ); if ( !mAttributeList.contains( attrIdx ) ) mAttributeList << attrIdx; } From 291f7bdaa3d6463e7e413e92a1a5b39d16efb039 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 13:00:37 +1000 Subject: [PATCH 063/897] Fix rule based renderer shows 0 count on first click of "show counts" --- src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp index 8d747ef28475..c3f67bd1761b 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp @@ -517,8 +517,6 @@ void QgsRuleBasedRendererWidget::countFeatures() countMap[rule].duplicateCount = 0; } - QgsFeatureRequest req = QgsFeatureRequest().setFilterExpression( mRenderer->filter( mLayer->fields() ) ); - QgsRenderContext renderContext; renderContext.setRendererScale( 0 ); // ignore scale @@ -543,10 +541,11 @@ void QgsRuleBasedRendererWidget::countFeatures() } renderContext.setExpressionContext( context ); - req.setExpressionContext( context ); mRenderer->startRender( renderContext, mLayer->fields() ); - + // QgsRuleBasedRenderer::filter must be called after startRender + QgsFeatureRequest req = QgsFeatureRequest().setFilterExpression( mRenderer->filter( mLayer->fields() ) ); + req.setExpressionContext( context ); req.setSubsetOfAttributes( mRenderer->usedAttributes(), mLayer->fields() ); QgsFeatureIterator fit = mLayer->getFeatures( req ); From 1f78393404b1a4dff545e84a5a462c55ce6470e6 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 3 Oct 2016 10:29:41 +0700 Subject: [PATCH 064/897] [gui] improve the layer dependencies icon --- images/themes/default/dependencies.svg | 644 +++++++++++++++++++++---- 1 file changed, 548 insertions(+), 96 deletions(-) diff --git a/images/themes/default/dependencies.svg b/images/themes/default/dependencies.svg index 9a89b39261c5..30c5b25c1b18 100644 --- a/images/themes/default/dependencies.svg +++ b/images/themes/default/dependencies.svg @@ -10,78 +10,512 @@ xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" - width="16" - height="16" - viewBox="0 0 16 16" - id="svg2" + width="64" + height="64" + viewBox="0 0 16.933333 16.933334" version="1.1" + id="svg8" inkscape:version="0.91 r13725" - sodipodi:docname="sync_views.svg"> + sodipodi:docname="dependencies.svg"> + id="defs2"> + id="linearGradient3481"> + id="stop3483" /> + id="stop3485" /> - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + xlink:href="#linearGradient3481" + id="linearGradient3487" + x1="3.5413208" + y1="289.65009" + x2="8.2772484" + y2="294.25168" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(1.0031007,0,0,1.0229573,-0.00205057,-7.2957563)" /> + inkscape:window-width="1865" + inkscape:window-height="1056" + inkscape:window-x="55" + inkscape:window-y="24" + inkscape:window-maximized="1" + inkscape:snap-grids="false" + showguides="false"> + id="grid4242" /> + id="metadata5"> image/svg+xml - + @@ -131,21 +558,46 @@ inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" - transform="translate(0,-1036.3622)"> - - - - + transform="translate(0,-280.06665)"> + + + + + + + From d36fb619b5a210406aaa50ed3aab59763f5f749a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 14:21:34 +1000 Subject: [PATCH 065/897] [labeling] Fix data defined placement with rotated maps For layers requiring reprojection and with rotated maps any labels with data defined x/y would not be rendered Fix #14236 --- src/core/qgspallabeling.cpp | 34 ++++++---------------------------- 1 file changed, 6 insertions(+), 28 deletions(-) diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index 25d92e8d1c32..af7c65606f46 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -2810,35 +2810,13 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont ydiff = yd; } - //project xPos and yPos from layer to map CRS - double z = 0; - if ( ct.isValid() && !ct.isShortCircuited() ) + //project xPos and yPos from layer to map CRS, handle rotation + QgsGeometry ddPoint( new QgsPointV2( xPos, yPos ) ); + if ( QgsPalLabeling::geometryRequiresPreparation( ddPoint, context, ct ) ) { - try - { - ct.transformInPlace( xPos, yPos, z ); - } - catch ( QgsCsException &e ) - { - Q_UNUSED( e ); - QgsDebugMsgLevel( QString( "Ignoring feature %1 due transformation exception on data-defined position" ).arg( f.id() ), 4 ); - return; - } - } - - //rotate position with map if data-defined - if ( dataDefinedPosition && m2p.mapRotation() ) - { - const QgsPoint& center = context.extent().center(); - QTransform t = QTransform::fromTranslate( center.x(), center.y() ); - t.rotate( -m2p.mapRotation() ); - t.translate( -center.x(), -center.y() ); - qreal xPosR, yPosR; - qreal xPos_qreal = xPos, yPos_qreal = yPos; - t.map( xPos_qreal, yPos_qreal, &xPosR, &yPosR ); - xPos = xPosR; - yPos = yPosR; - + ddPoint = QgsPalLabeling::prepareGeometry( ddPoint, context, ct ); + xPos = static_cast< QgsPointV2* >( ddPoint.geometry() )->x(); + yPos = static_cast< QgsPointV2* >( ddPoint.geometry() )->y(); } xPos += xdiff; From 7d27b43e79d58412d8c894f05cc984af47583bc0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 14:37:26 +1000 Subject: [PATCH 066/897] Fix data defined buttons sometimes incorrectly show error state --- src/gui/qgsdatadefinedbutton.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/qgsdatadefinedbutton.cpp b/src/gui/qgsdatadefinedbutton.cpp index 151cf216db1d..2cd99e244121 100644 --- a/src/gui/qgsdatadefinedbutton.cpp +++ b/src/gui/qgsdatadefinedbutton.cpp @@ -195,6 +195,7 @@ void QgsDataDefinedButton::init( const QgsVectorLayer* vl, mActionDataTypes->setText( tr( "Field type: " ) + mDataTypesString ); } + updateFieldLists(); updateGui(); } From 5b3f10a531765a8c3951fa35a33d7da5a0c27644 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 15:15:12 +1000 Subject: [PATCH 067/897] Fix identify menu highlight only works with simple geometry types Fix #15625 --- src/gui/qgshighlight.cpp | 79 +++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 41 deletions(-) diff --git a/src/gui/qgshighlight.cpp b/src/gui/qgshighlight.cpp index 467882b1cbc5..029fbc73e727 100644 --- a/src/gui/qgshighlight.cpp +++ b/src/gui/qgshighlight.cpp @@ -282,65 +282,62 @@ void QgsHighlight::paint( QPainter* p ) p->setPen( mPen ); p->setBrush( mBrush ); - switch ( mGeometry->wkbType() ) + switch ( mGeometry->type() ) { - case QgsWkbTypes::Point: - case QgsWkbTypes::Point25D: + case QgsWkbTypes::PointGeometry: { - paintPoint( p, mGeometry->asPoint() ); - } - break; - - case QgsWkbTypes::MultiPoint: - case QgsWkbTypes::MultiPoint25D: - { - QgsMultiPoint m = mGeometry->asMultiPoint(); - for ( int i = 0; i < m.size(); i++ ) + if ( !mGeometry->isMultipart() ) { - paintPoint( p, m[i] ); + paintPoint( p, mGeometry->asPoint() ); + } + else + { + QgsMultiPoint m = mGeometry->asMultiPoint(); + for ( int i = 0; i < m.size(); i++ ) + { + paintPoint( p, m[i] ); + } } } break; - case QgsWkbTypes::LineString: - case QgsWkbTypes::LineString25D: - { - paintLine( p, mGeometry->asPolyline() ); - } - break; - - case QgsWkbTypes::MultiLineString: - case QgsWkbTypes::MultiLineString25D: + case QgsWkbTypes::LineGeometry: { - QgsMultiPolyline m = mGeometry->asMultiPolyline(); - - for ( int i = 0; i < m.size(); i++ ) + if ( !mGeometry->isMultipart() ) { - paintLine( p, m[i] ); + paintLine( p, mGeometry->asPolyline() ); } - } - break; + else + { + QgsMultiPolyline m = mGeometry->asMultiPolyline(); - case QgsWkbTypes::Polygon: - case QgsWkbTypes::Polygon25D: - { - paintPolygon( p, mGeometry->asPolygon() ); + for ( int i = 0; i < m.size(); i++ ) + { + paintLine( p, m[i] ); + } + } + break; } - break; - case QgsWkbTypes::MultiPolygon: - case QgsWkbTypes::MultiPolygon25D: + case QgsWkbTypes::PolygonGeometry: { - QgsMultiPolygon m = mGeometry->asMultiPolygon(); - for ( int i = 0; i < m.size(); i++ ) + if ( !mGeometry->isMultipart() ) + { + paintPolygon( p, mGeometry->asPolygon() ); + } + else { - paintPolygon( p, m[i] ); + QgsMultiPolygon m = mGeometry->asMultiPolygon(); + for ( int i = 0; i < m.size(); i++ ) + { + paintPolygon( p, m[i] ); + } } + break; } - break; - case QgsWkbTypes::Unknown: - default: + case QgsWkbTypes::UnknownGeometry: + case QgsWkbTypes::NullGeometry: return; } } From 8e14cf06d31748bfad33f5195a3f15a893f2c23d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 16:15:23 +1000 Subject: [PATCH 068/897] Fix leak in edit form config (#3556) --- src/core/qgseditformconfig_p.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/qgseditformconfig_p.h b/src/core/qgseditformconfig_p.h index 6ba11a173fa6..91e050647046 100644 --- a/src/core/qgseditformconfig_p.h +++ b/src/core/qgseditformconfig_p.h @@ -54,6 +54,11 @@ class QgsEditFormConfigPrivate : public QSharedData , mFields( o.mFields ) {} + ~QgsEditFormConfigPrivate() + { + delete mInvisibleRootContainer; + } + /** The invisible root container for attribute editors in the drag and drop designer */ QgsAttributeEditorContainer* mInvisibleRootContainer; From ce37f9c6541550fe47c2513e15e1277c56eb6e9b Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 3 Oct 2016 10:45:55 +0200 Subject: [PATCH 069/897] Disable flaky PyQgsServerWFST test --- ci/travis/linux/script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 0ab8c4c1b41f..92e18e7fe131 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -21,5 +21,5 @@ export CCACHE_TEMPDIR=/tmp DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|PyQgsServerWFST$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure From 8e54acf7b74d159c6aa354857b3c2f4f07980e3d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 3 Oct 2016 11:38:34 +0200 Subject: [PATCH 070/897] [travis] fixme --- ci/travis/linux/script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 92e18e7fe131..fbdc0c86a792 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -21,5 +21,5 @@ export CCACHE_TEMPDIR=/tmp DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|PyQgsServerWFST$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|PyQgsServerWFST|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure From 28f547ea81de0b7795de94c7c941edd833343dc4 Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Mon, 3 Oct 2016 14:19:49 +0200 Subject: [PATCH 071/897] Wait for server ready (and times out) before starting the tests --- ci/travis/linux/script.sh | 2 +- tests/src/python/qgis_wrapped_server.py | 15 ++++++------ tests/src/python/test_authmanager_endpoint.py | 6 ++--- tests/src/python/test_offline_editing_wfs.py | 6 ++--- tests/src/python/test_qgsserver_wfst.py | 6 ++--- tests/src/python/utilities.py | 24 +++++++++++++++++++ 6 files changed, 41 insertions(+), 18 deletions(-) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index fbdc0c86a792..0ab8c4c1b41f 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -21,5 +21,5 @@ export CCACHE_TEMPDIR=/tmp DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|PyQgsServerWFST|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure diff --git a/tests/src/python/qgis_wrapped_server.py b/tests/src/python/qgis_wrapped_server.py index 4d033d0f1a64..1540790c0a2b 100644 --- a/tests/src/python/qgis_wrapped_server.py +++ b/tests/src/python/qgis_wrapped_server.py @@ -3,7 +3,8 @@ QGIS Server HTTP wrapper This script launches a QGIS Server listening on port 8081 or on the port -specified on the environment variable QGIS_SERVER_DEFAULT_PORT +specified on the environment variable QGIS_SERVER_PORT +QGIS_SERVER_HOST (defaults to 127.0.0.1) For testing purposes, HTTP Basic can be enabled by setting the following environment variables: @@ -36,10 +37,8 @@ from qgis.core import QgsApplication from qgis.server import QgsServer -try: - QGIS_SERVER_DEFAULT_PORT = int(os.environ['QGIS_SERVER_DEFAULT_PORT']) -except KeyError: - QGIS_SERVER_DEFAULT_PORT = 8081 +QGIS_SERVER_PORT = int(os.environ.get('QGIS_SERVER_PORT', '8081')) +QGIS_SERVER_HOST = os.environ.get('QGIS_SERVER_HOST', '127.0.0.1') qgs_app = QgsApplication([], False) qgs_server = QgsServer() @@ -101,9 +100,9 @@ def do_POST(self): if __name__ == '__main__': - server = HTTPServer(('localhost', QGIS_SERVER_DEFAULT_PORT), Handler) - print('Starting server on localhost:%s, use to stop' % - QGIS_SERVER_DEFAULT_PORT) + print('Starting server on %s:%s, use to stop' % + (QGIS_SERVER_HOST, QGIS_SERVER_PORT)) + server = HTTPServer((QGIS_SERVER_HOST, QGIS_SERVER_PORT), Handler) def signal_handler(signal, frame): global qgs_app diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_endpoint.py index 3b0429442859..8f8a745a6664 100644 --- a/tests/src/python/test_authmanager_endpoint.py +++ b/tests/src/python/test_authmanager_endpoint.py @@ -33,7 +33,7 @@ from urllib.parse import quote from shutil import rmtree -from utilities import unitTestDataPath +from utilities import unitTestDataPath, waitServer from qgis.core import ( QgsAuthManager, QgsAuthMethodConfig, @@ -92,12 +92,12 @@ def setUpClass(cls): os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1' os.environ['QGIS_SERVER_USERNAME'] = cls.username os.environ['QGIS_SERVER_PASSWORD'] = cls.password - os.environ['QGIS_SERVER_DEFAULT_PORT'] = str(cls.port) + os.environ['QGIS_SERVER_PORT'] = str(cls.port) server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen([sys.executable, server_path], env=os.environ) - sleep(2) + assert waitServer('http://127.0.0.1:%s' % cls.port), "Server is not responding!" @classmethod def tearDownClass(cls): diff --git a/tests/src/python/test_offline_editing_wfs.py b/tests/src/python/test_offline_editing_wfs.py index 3477581a77d7..3000e1c03659 100644 --- a/tests/src/python/test_offline_editing_wfs.py +++ b/tests/src/python/test_offline_editing_wfs.py @@ -35,7 +35,7 @@ from shutil import copytree, rmtree import tempfile from time import sleep -from utilities import unitTestDataPath +from utilities import unitTestDataPath, waitServer from qgis.core import QgsVectorLayer from qgis.testing import ( @@ -85,7 +85,7 @@ def setUpClass(cls): pass # Clear all test layers cls._clearLayer(cls._getLayer('test_point')) - os.environ['QGIS_SERVER_DEFAULT_PORT'] = str(cls.port) + os.environ['QGIS_SERVER_PORT'] = str(cls.port) cls.server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' @@ -99,7 +99,7 @@ def setUp(self): self.server = subprocess.Popen([sys.executable, self.server_path], env=os.environ) # Wait for the server process to start - sleep(2) + assert waitServer('http://127.0.0.1:%s' % self.port), "Server is not responding!" self._setUp() def tearDown(self): diff --git a/tests/src/python/test_qgsserver_wfst.py b/tests/src/python/test_qgsserver_wfst.py index 7462f828c49d..cb1d5e1113a6 100644 --- a/tests/src/python/test_qgsserver_wfst.py +++ b/tests/src/python/test_qgsserver_wfst.py @@ -41,7 +41,7 @@ from shutil import copytree, rmtree import tempfile from time import sleep -from utilities import unitTestDataPath +from utilities import unitTestDataPath, waitServer from qgis.core import ( QgsVectorLayer, QgsFeature, @@ -94,12 +94,12 @@ def setUpClass(cls): # Clear all test layers for ln in ['test_point', 'test_polygon', 'test_linestring']: cls._clearLayer(ln) - os.environ['QGIS_SERVER_DEFAULT_PORT'] = str(cls.port) + os.environ['QGIS_SERVER_PORT'] = str(cls.port) server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen([sys.executable, server_path], env=os.environ) - sleep(2) + assert waitServer('http://127.0.0.1:%s' % cls.port), "Server is not responding!" @classmethod def tearDownClass(cls): diff --git a/tests/src/python/utilities.py b/tests/src/python/utilities.py index 9a7d311f29af..5532f04474ad 100644 --- a/tests/src/python/utilities.py +++ b/tests/src/python/utilities.py @@ -18,6 +18,11 @@ import glob import platform import tempfile +try: + from urllib2 import urlopen, HTTPError +except ImportError: + from urllib.request import urlopen, HTTPError + from qgis.PyQt.QtCore import QDir @@ -828,3 +833,22 @@ def memberIsDocumented(self, member_elem): if doc is not None and list(doc): return True return False + + +def waitServer(url, timeout=10): + """ Wait for a server to be online and to respond + HTTP errors are ignored + @param timeout: in seconds + @return: True of False + """ + from time import time as now + end = now() + timeout + while True: + try: + urlopen(url, timeout=1) + return True + except HTTPError: + return True + except Exception as e: + if now() > end: + return False From 4fd5c014f2eeae2d663881a0053210846832fecf Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 3 Oct 2016 15:00:23 +0200 Subject: [PATCH 072/897] Synchronize edit button state with read only mode (#3562) --- src/app/qgisapp.cpp | 1 + src/app/qgsattributetabledialog.cpp | 3 ++- src/app/qgsattributetabledialog.h | 6 ------ 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 273eb8c8bc25..c7ce395726b5 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -10108,6 +10108,7 @@ void QgisApp::layersWereAdded( const QList& theLayers ) connect( vlayer, SIGNAL( layerModified() ), this, SLOT( updateLayerModifiedActions() ) ); connect( vlayer, SIGNAL( editingStarted() ), this, SLOT( layerEditStateChanged() ) ); connect( vlayer, SIGNAL( editingStopped() ), this, SLOT( layerEditStateChanged() ) ); + connect( vlayer, &QgsVectorLayer::readOnlyChanged, this, &QgisApp::layerEditStateChanged ); } connect( vlayer, SIGNAL( raiseError( QString ) ), this, SLOT( onLayerError( QString ) ) ); diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 4719b2652541..a84483bb498c 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -185,6 +185,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid connect( mLayer, SIGNAL( featuresDeleted( QgsFeatureIds ) ), this, SLOT( updateTitle() ) ); connect( mLayer, SIGNAL( attributeAdded( int ) ), this, SLOT( columnBoxInit() ) ); connect( mLayer, SIGNAL( attributeDeleted( int ) ), this, SLOT( columnBoxInit() ) ); + connect( mLayer, &QgsVectorLayer::readOnlyChanged, this, &QgsAttributeTableDialog::editingToggled ); // connect table info to window connect( mMainView, SIGNAL( filterChanged() ), this, SLOT( updateTitle() ) ); @@ -235,7 +236,6 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mActionToggleEditing->blockSignals( true ); mActionToggleEditing->setCheckable( true ); mActionToggleEditing->setChecked( mLayer->isEditable() ); - mActionToggleEditing->setEnabled(( canChangeAttributes || canDeleteFeatures || canAddAttributes || canDeleteAttributes || canAddFeatures ) && !mLayer->readOnly() ); mActionToggleEditing->blockSignals( false ); mActionSaveEdits->setEnabled( mActionToggleEditing->isEnabled() && mLayer->isEditable() ); @@ -761,6 +761,7 @@ void QgsAttributeTableDialog::editingToggled() mActionRemoveAttribute->setEnabled( canDeleteAttributes && mLayer->isEditable() ); mActionDeleteSelected->setEnabled( canDeleteFeatures && mLayer->isEditable() ); mActionAddFeature->setEnabled( canAddFeatures && mLayer->isEditable() ); + mActionToggleEditing->setEnabled(( canChangeAttributes || canDeleteFeatures || canAddAttributes || canDeleteAttributes || canAddFeatures ) && !mLayer->readOnly() ); mUpdateExpressionBox->setVisible( mLayer->isEditable() ); if ( mLayer->isEditable() && mFieldCombo->currentIndex() == -1 ) diff --git a/src/app/qgsattributetabledialog.h b/src/app/qgsattributetabledialog.h index 6ef8af03d9c9..abeea9dc05b4 100644 --- a/src/app/qgsattributetabledialog.h +++ b/src/app/qgsattributetabledialog.h @@ -168,12 +168,6 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib void replaceSearchWidget( QWidget* oldw, QWidget* neww ); signals: - /** - * Informs that editing mode has been toggled - * @param layer layer that has been toggled - */ - void editingToggled( QgsMapLayer *layer ); - /** * Informs that edits should be saved * @param layer layer whose edits are to be saved From d950e3b637339b452e03dbb8ab0b6762a9d9852b Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Mon, 3 Oct 2016 19:43:25 +0200 Subject: [PATCH 073/897] Yet another strategy to get a free port from the server --- tests/src/python/qgis_wrapped_server.py | 4 +-- tests/src/python/test_authmanager_endpoint.py | 9 +++++-- tests/src/python/test_offline_editing_wfs.py | 26 +++++++++---------- tests/src/python/test_qgsserver_wfst.py | 8 +++++- 4 files changed, 28 insertions(+), 19 deletions(-) diff --git a/tests/src/python/qgis_wrapped_server.py b/tests/src/python/qgis_wrapped_server.py index 1540790c0a2b..8740aa3d6c7b 100644 --- a/tests/src/python/qgis_wrapped_server.py +++ b/tests/src/python/qgis_wrapped_server.py @@ -100,9 +100,9 @@ def do_POST(self): if __name__ == '__main__': - print('Starting server on %s:%s, use to stop' % - (QGIS_SERVER_HOST, QGIS_SERVER_PORT)) server = HTTPServer((QGIS_SERVER_HOST, QGIS_SERVER_PORT), Handler) + print('Starting server on %s:%s, use to stop' % + (QGIS_SERVER_HOST, server.server_port), flush=True) def signal_handler(signal, frame): global qgs_app diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_endpoint.py index 8f8a745a6664..3f3b8ed3ba68 100644 --- a/tests/src/python/test_authmanager_endpoint.py +++ b/tests/src/python/test_authmanager_endpoint.py @@ -17,6 +17,7 @@ """ import os import sys +import re import subprocess import tempfile import random @@ -29,7 +30,6 @@ # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' -from time import sleep from urllib.parse import quote from shutil import rmtree @@ -96,13 +96,18 @@ def setUpClass(cls): server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen([sys.executable, server_path], - env=os.environ) + env=os.environ, stdout=subprocess.PIPE) + line = cls.server.stdout.readline() + cls.port = int(re.findall(b':(\d+)', line)[0]) + assert cls.port != 0 + # Wait for the server process to start assert waitServer('http://127.0.0.1:%s' % cls.port), "Server is not responding!" @classmethod def tearDownClass(cls): """Run after all tests""" cls.server.terminate() + cls.server.wait() rmtree(QGIS_AUTH_DB_DIR_PATH) del cls.server diff --git a/tests/src/python/test_offline_editing_wfs.py b/tests/src/python/test_offline_editing_wfs.py index 3000e1c03659..662ab9059179 100644 --- a/tests/src/python/test_offline_editing_wfs.py +++ b/tests/src/python/test_offline_editing_wfs.py @@ -31,6 +31,7 @@ import os import sys +import re import subprocess from shutil import copytree, rmtree import tempfile @@ -49,11 +50,7 @@ try: QGIS_SERVER_WFST_DEFAULT_PORT = os.environ['QGIS_SERVER_WFST_DEFAULT_PORT'] except: - import socket - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.bind(("", 0)) - QGIS_SERVER_WFST_DEFAULT_PORT = s.getsockname()[1] - s.close() + QGIS_SERVER_WFST_DEFAULT_PORT = '0' # Auto qgis_app = start_app() @@ -97,7 +94,10 @@ def tearDownClass(cls): def setUp(self): """Run before each test.""" self.server = subprocess.Popen([sys.executable, self.server_path], - env=os.environ) + env=os.environ, stdout=subprocess.PIPE) + line = self.server.stdout.readline() + self.port = int(re.findall(b':(\d+)', line)[0]) + assert self.port != 0 # Wait for the server process to start assert waitServer('http://127.0.0.1:%s' % self.port), "Server is not responding!" self._setUp() @@ -108,15 +108,13 @@ def tearDown(self): self._clearLayer(self._getOnlineLayer('test_point')) # Kill the server self.server.terminate() + self.server.wait() del self.server - # Wait for the server process to stop - sleep(2) # Delete the sqlite db os.unlink(os.path.join(self.temp_path, 'offlineDbFile.sqlite')) self._tearDown() - @classmethod - def _getOnlineLayer(cls, type_name, layer_name=None): + def _getOnlineLayer(self, type_name, layer_name=None): """ Return a new WFS layer, overriding the WFS cache """ @@ -125,14 +123,14 @@ def _getOnlineLayer(cls, type_name, layer_name=None): parms = { 'srsname': 'EPSG:4326', 'typename': type_name, - 'url': 'http://127.0.0.1:%s/%s/?map=%s' % (cls.port, - cls.counter, - cls.project_path), + 'url': 'http://127.0.0.1:%s/%s/?map=%s' % (self.port, + self.counter, + self.project_path), 'version': 'auto', 'table': '', #'sql': '', } - cls.counter += 1 + self.counter += 1 uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())]) wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS') assert wfs_layer.isValid() diff --git a/tests/src/python/test_qgsserver_wfst.py b/tests/src/python/test_qgsserver_wfst.py index cb1d5e1113a6..a93113dc5dfa 100644 --- a/tests/src/python/test_qgsserver_wfst.py +++ b/tests/src/python/test_qgsserver_wfst.py @@ -37,6 +37,7 @@ import os import sys +import re import subprocess from shutil import copytree, rmtree import tempfile @@ -98,13 +99,18 @@ def setUpClass(cls): server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen([sys.executable, server_path], - env=os.environ) + env=os.environ, stdout=subprocess.PIPE) + line = cls.server.stdout.readline() + cls.port = int(re.findall(b':(\d+)', line)[0]) + assert cls.port != 0 + # Wait for the server process to start assert waitServer('http://127.0.0.1:%s' % cls.port), "Server is not responding!" @classmethod def tearDownClass(cls): """Run after all tests""" cls.server.terminate() + cls.server.wait() del cls.server # Clear all test layers for ln in ['test_point', 'test_polygon', 'test_linestring']: From 9761a86e4fbd6699bfbe23867fb514d40e517af3 Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Mon, 3 Oct 2016 20:47:32 +0200 Subject: [PATCH 074/897] Renamed constants for consistency --- tests/src/python/test_authmanager_endpoint.py | 12 +++++------- tests/src/python/test_offline_editing_wfs.py | 6 +++--- tests/src/python/test_qgsserver_wfst.py | 10 +++------- 3 files changed, 11 insertions(+), 17 deletions(-) diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_endpoint.py index 3f3b8ed3ba68..5425e7e377db 100644 --- a/tests/src/python/test_authmanager_endpoint.py +++ b/tests/src/python/test_authmanager_endpoint.py @@ -45,14 +45,12 @@ unittest, ) + try: - QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT = os.environ['QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT'] + QGIS_SERVER_ENDPOINT_PORT = os.environ['QGIS_SERVER_ENDPOINT_PORT'] except: - import socket - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.bind(("", 0)) - QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT = s.getsockname()[1] - s.close() + QGIS_SERVER_ENDPOINT_PORT = '0' # Auto + QGIS_AUTH_DB_DIR_PATH = tempfile.mkdtemp() @@ -67,7 +65,7 @@ class TestAuthManager(unittest.TestCase): def setUpClass(cls): """Run before all tests: Creates an auth configuration""" - cls.port = QGIS_SERVER_AUTHMANAGER_DEFAULT_PORT + cls.port = QGIS_SERVER_ENDPOINT_PORT # Clean env just to be sure env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] for ev in env_vars: diff --git a/tests/src/python/test_offline_editing_wfs.py b/tests/src/python/test_offline_editing_wfs.py index 662ab9059179..8c58df9e78bc 100644 --- a/tests/src/python/test_offline_editing_wfs.py +++ b/tests/src/python/test_offline_editing_wfs.py @@ -48,9 +48,9 @@ try: - QGIS_SERVER_WFST_DEFAULT_PORT = os.environ['QGIS_SERVER_WFST_DEFAULT_PORT'] + QGIS_SERVER_OFFLINE_PORT = os.environ['QGIS_SERVER_OFFLINE_PORT'] except: - QGIS_SERVER_WFST_DEFAULT_PORT = '0' # Auto + QGIS_SERVER_OFFLINE_PORT = '0' # Auto qgis_app = start_app() @@ -63,7 +63,7 @@ class TestWFST(unittest.TestCase, OfflineTestBase): @classmethod def setUpClass(cls): """Run before all tests""" - cls.port = QGIS_SERVER_WFST_DEFAULT_PORT + cls.port = QGIS_SERVER_OFFLINE_PORT # Create tmp folder cls.temp_path = tempfile.mkdtemp() cls.testdata_path = cls.temp_path + '/' + 'wfs_transactional' + '/' diff --git a/tests/src/python/test_qgsserver_wfst.py b/tests/src/python/test_qgsserver_wfst.py index a93113dc5dfa..33f7fb1e8306 100644 --- a/tests/src/python/test_qgsserver_wfst.py +++ b/tests/src/python/test_qgsserver_wfst.py @@ -58,13 +58,9 @@ ) try: - QGIS_SERVER_WFST_DEFAULT_PORT = os.environ['QGIS_SERVER_WFST_DEFAULT_PORT'] + QGIS_SERVER_WFST_PORT = os.environ['QGIS_SERVER_WFST_PORT'] except: - import socket - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.bind(("", 0)) - QGIS_SERVER_WFST_DEFAULT_PORT = s.getsockname()[1] - s.close() + QGIS_SERVER_WFST_PORT = '0' # Auto qgis_app = start_app() @@ -75,7 +71,7 @@ class TestWFST(unittest.TestCase): @classmethod def setUpClass(cls): """Run before all tests""" - cls.port = QGIS_SERVER_WFST_DEFAULT_PORT + cls.port = QGIS_SERVER_WFST_PORT # Create tmp folder cls.temp_path = tempfile.mkdtemp() cls.testdata_path = cls.temp_path + '/' + 'wfs_transactional' + '/' From 19f6b62cd8e99fc73e5f89f3c0f82f586d5214ec Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 15:02:14 +1000 Subject: [PATCH 075/897] Fix layers with layer wide opacity "flashing" by rendering intermediate states without opacity --- src/core/qgsmaprenderercustompainterjob.cpp | 2 ++ src/core/qgsmaprendererjob.cpp | 7 +++++++ src/core/qgsmaprendererjob.h | 1 + src/core/qgsvectorlayerrenderer.cpp | 14 -------------- src/core/qgsvectorlayerrenderer.h | 1 - ...expected_vector_layertransparency_mask.png | Bin 11487 -> 11815 bytes 6 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/core/qgsmaprenderercustompainterjob.cpp b/src/core/qgsmaprenderercustompainterjob.cpp index c572e49a84db..67e07bac74d7 100644 --- a/src/core/qgsmaprenderercustompainterjob.cpp +++ b/src/core/qgsmaprenderercustompainterjob.cpp @@ -260,7 +260,9 @@ void QgsMapRendererCustomPainterJob::doRender() if ( job.img ) { // If we flattened this layer for alternate blend modes, composite it now + mPainter->setOpacity( job.opacity ); mPainter->drawImage( 0, 0, *job.img ); + mPainter->setOpacity( 1.0 ); } } diff --git a/src/core/qgsmaprendererjob.cpp b/src/core/qgsmaprendererjob.cpp index 01c012447dae..5ea92d336fab 100644 --- a/src/core/qgsmaprendererjob.cpp +++ b/src/core/qgsmaprendererjob.cpp @@ -245,6 +245,11 @@ LayerRenderJobs QgsMapRendererJob::prepareJobs( QPainter* painter, QgsLabelingEn job.cached = false; job.img = nullptr; job.blendMode = ml->blendMode(); + job.opacity = 1.0; + if ( QgsVectorLayer* vl = qobject_cast( ml ) ) + { + job.opacity = 1.0 - vl->layerTransparency() / 100.0; + } job.layerId = ml->id(); job.renderingTime = -1; @@ -360,8 +365,10 @@ QImage QgsMapRendererJob::composeImage( const QgsMapSettings& settings, const La const LayerRenderJob& job = *it; painter.setCompositionMode( job.blendMode ); + painter.setOpacity( job.opacity ); Q_ASSERT( job.img ); + painter.drawImage( 0, 0, *job.img ); } diff --git a/src/core/qgsmaprendererjob.h b/src/core/qgsmaprendererjob.h index b37815663dc8..ff57843cd961 100644 --- a/src/core/qgsmaprendererjob.h +++ b/src/core/qgsmaprendererjob.h @@ -46,6 +46,7 @@ struct LayerRenderJob QImage* img; // may be null if it is not necessary to draw to separate image (e.g. sequential rendering) QgsMapLayerRenderer* renderer; // must be deleted QPainter::CompositionMode blendMode; + double opacity; bool cached; // if true, img already contains cached image from previous rendering QString layerId; int renderingTime; //!< time it took to render the layer in ms (it is -1 if not rendered or still rendering) diff --git a/src/core/qgsvectorlayerrenderer.cpp b/src/core/qgsvectorlayerrenderer.cpp index d9630eaf0575..f07ed9fc773e 100644 --- a/src/core/qgsvectorlayerrenderer.cpp +++ b/src/core/qgsvectorlayerrenderer.cpp @@ -55,7 +55,6 @@ QgsVectorLayerRenderer::QgsVectorLayerRenderer( QgsVectorLayer* layer, QgsRender , mDiagrams( false ) , mLabelProvider( nullptr ) , mDiagramProvider( nullptr ) - , mLayerTransparency( 0 ) { mSource = new QgsVectorLayerFeatureSource( layer ); @@ -66,7 +65,6 @@ QgsVectorLayerRenderer::QgsVectorLayerRenderer( QgsVectorLayer* layer, QgsRender mGeometryType = layer->geometryType(); - mLayerTransparency = layer->layerTransparency(); mFeatureBlendMode = layer->featureBlendMode(); mSimplifyMethod = layer->simplifyMethod(); @@ -264,18 +262,6 @@ bool QgsVectorLayerRenderer::render() mRenderer->paintEffect()->end( mContext ); } - //apply layer transparency for vector layers - if ( mContext.useAdvancedEffects() && mLayerTransparency != 0 ) - { - // a layer transparency has been set, so update the alpha for the flattened layer - // by combining it with the layer transparency - QColor transparentFillColor = QColor( 0, 0, 0, 255 - ( 255 * mLayerTransparency / 100 ) ); - // use destination in composition mode to merge source's alpha with destination - mContext.painter()->setCompositionMode( QPainter::CompositionMode_DestinationIn ); - mContext.painter()->fillRect( 0, 0, mContext.painter()->device()->width(), - mContext.painter()->device()->height(), transparentFillColor ); - } - return true; } diff --git a/src/core/qgsvectorlayerrenderer.h b/src/core/qgsvectorlayerrenderer.h index 70774e2090cc..3a4ba17bf7c5 100644 --- a/src/core/qgsvectorlayerrenderer.h +++ b/src/core/qgsvectorlayerrenderer.h @@ -136,7 +136,6 @@ class QgsVectorLayerRenderer : public QgsMapLayerRenderer //! may be null. no need to delete: if exists it is owned by labeling engine QgsVectorLayerDiagramProvider* mDiagramProvider; - int mLayerTransparency; QPainter::CompositionMode mFeatureBlendMode; QgsVectorSimplifyMethod mSimplifyMethod; diff --git a/tests/testdata/control_images/expected_vector_layertransparency/default/expected_vector_layertransparency_mask.png b/tests/testdata/control_images/expected_vector_layertransparency/default/expected_vector_layertransparency_mask.png index 97a4ae9bce63cedc31ca8b61cadf7ac103a20ca5..16070fb00e1a053a5348cb3b752eff8f7e8f8ab4 100644 GIT binary patch literal 11815 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

                                                                                                                                                                                    3V4LBKWXSr^8mgN5s>>0LqizYue9|9pwfaSa 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 literal 11487 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 A^#A|> From 377de52b389999269abf5534df9f42861ce5e0dc Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 09:19:41 +1000 Subject: [PATCH 076/897] Port generate_test_mask_image.py to python3 --- scripts/generate_test_mask_image.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/scripts/generate_test_mask_image.py b/scripts/generate_test_mask_image.py index 18914ce1ed30..fcd629358763 100755 --- a/scripts/generate_test_mask_image.py +++ b/scripts/generate_test_mask_image.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -35,12 +35,12 @@ import argparse from PyQt5.QtGui import QImage, QColor, qRed, qBlue, qGreen, qAlpha, qRgb import struct -import urllib2 +import urllib.request, urllib.error, urllib.parse import glob def error(msg): - print msg + print(msg) sys.exit(1) @@ -53,9 +53,9 @@ def colorDiff(c1, c2): def imageFromPath(path): - if (path[:7] == 'http://' or path[:7] == 'file://'): + if (path[:7] == 'http://' or path[:7] == 'file://' or path[:8] == 'https://'): #fetch remote image - data = urllib2.urlopen(path).read() + data = urllib.request.urlopen(path).read() image = QImage() image.loadFromData(data) else: @@ -88,7 +88,7 @@ def getControlImagePath(path): error('No matching control images found for {}'.format(path)) found_image = filtered_images[0] - print 'Found matching control image: {}'.format(found_image) + print('Found matching control image: {}'.format(found_image)) return found_image @@ -101,10 +101,10 @@ def updateMask(control_image_path, rendered_image_path, mask_image_path): if not rendered_image: error('Could not read rendered image {}'.format(rendered_image_path)) if not rendered_image.width() == control_image.width() or not rendered_image.height() == control_image.height(): - print ('Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(control_image.width(), + print(('Size mismatch - control image is {}x{}, rendered image is {}x{}'.format(control_image.width(), control_image.height(), rendered_image.width(), - rendered_image.height())) + rendered_image.height()))) max_width = min(rendered_image.width(), control_image.width()) max_height = min(rendered_image.height(), control_image.height()) @@ -112,19 +112,19 @@ def updateMask(control_image_path, rendered_image_path, mask_image_path): #read current mask, if it exist mask_image = imageFromPath(mask_image_path) if mask_image.isNull(): - print 'Mask image does not exist, creating {}'.format(mask_image_path) + print('Mask image does not exist, creating {}'.format(mask_image_path)) mask_image = QImage(control_image.width(), control_image.height(), QImage.Format_ARGB32) mask_image.fill(QColor(0, 0, 0)) #loop through pixels in rendered image and compare mismatch_count = 0 linebytes = max_width * 4 - for y in xrange(max_height): + for y in range(max_height): control_scanline = control_image.constScanLine(y).asstring(linebytes) rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes) mask_scanline = mask_image.scanLine(y).asstring(linebytes) - for x in xrange(max_width): + for x in range(max_width): currentTolerance = qRed(struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0]) if currentTolerance == 255: @@ -143,9 +143,9 @@ def updateMask(control_image_path, rendered_image_path, mask_image_path): if mismatch_count: #update mask mask_image.save(mask_image_path, "png") - print 'Updated {} pixels in {}'.format(mismatch_count, mask_image_path) + print('Updated {} pixels in {}'.format(mismatch_count, mask_image_path)) else: - print 'No mismatches in {}'.format(mask_image_path) + print('No mismatches in {}'.format(mask_image_path)) parser = argparse.ArgumentParser() # OptionParser("usage: %prog control_image rendered_image mask_image") parser.add_argument('control_image') From c60c4f7f0ca09dc6bbc8e3f721339a238154ff57 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 12:26:34 +1000 Subject: [PATCH 077/897] Fix SVG preview blocks QGIS (fix #14255) Now SVG preview loading occurs in a background thread so that dialogs can open instantly --- src/core/qgsapplication.cpp | 2 +- src/gui/symbology-ng/qgssvgselectorwidget.cpp | 290 +++++++++++++++--- src/gui/symbology-ng/qgssvgselectorwidget.h | 159 +++++++++- src/gui/symbology-ng/qgssymbollayerwidget.cpp | 152 ++------- src/gui/symbology-ng/qgssymbollayerwidget.h | 33 -- 5 files changed, 420 insertions(+), 216 deletions(-) diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index fc3db6b53d46..30b5415986d4 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -715,7 +715,7 @@ QStringList QgsApplication::svgPaths() } myPathList << ABISYM( mDefaultSvgPaths ); - return myPathList; + return myPathList.toSet().toList(); } /*! diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.cpp b/src/gui/symbology-ng/qgssvgselectorwidget.cpp index 645130b169a8..012a7c01c6fa 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.cpp +++ b/src/gui/symbology-ng/qgssvgselectorwidget.cpp @@ -32,29 +32,221 @@ #include #include +// QgsSvgSelectorLoader -//--- QgsSvgSelectorListModel +///@cond PRIVATE +QgsSvgSelectorLoader::QgsSvgSelectorLoader( QObject* parent ) + : QThread( parent ) + , mCancelled( false ) + , mTimerThreshold( 0 ) +{ +} + +QgsSvgSelectorLoader::~QgsSvgSelectorLoader() +{ + stop(); +} + +void QgsSvgSelectorLoader::run() +{ + mCancelled = false; + mQueuedSvgs.clear(); + + // start with a small initial timeout (ms) + mTimerThreshold = 10; + mTimer.start(); + + loadPath( mPath ); + + if ( !mQueuedSvgs.isEmpty() ) + { + // make sure we notify model of any remaining queued svgs (ie svgs added since last foundSvgs() signal was emitted) + emit foundSvgs( mQueuedSvgs ); + } + mQueuedSvgs.clear(); +} + +void QgsSvgSelectorLoader::stop() +{ + mCancelled = true; + while ( isRunning() ) {} +} + +void QgsSvgSelectorLoader::loadPath( const QString& path ) +{ + if ( mCancelled ) + return; + + // QgsDebugMsg( QString( "loading path: %1" ).arg( path ) ); + + if ( path.isEmpty() ) + { + QStringList svgPaths = QgsApplication::svgPaths(); + Q_FOREACH ( const QString& svgPath, svgPaths ) + { + if ( mCancelled ) + return; + + loadPath( svgPath ); + } + } + else + { + loadImages( path ); + + QDir dir( path ); + Q_FOREACH ( const QString& item, dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) + { + if ( mCancelled ) + return; + + QString newPath = dir.path() + '/' + item; + loadPath( newPath ); + // QgsDebugMsg( QString( "added path: %1" ).arg( newPath ) ); + } + } +} + +void QgsSvgSelectorLoader::loadImages( const QString& path ) +{ + QDir dir( path ); + Q_FOREACH ( const QString& item, dir.entryList( QStringList( "*.svg" ), QDir::Files ) ) + { + if ( mCancelled ) + return; + + // TODO test if it is correct SVG + QString svgPath = dir.path() + '/' + item; + // QgsDebugMsg( QString( "adding svg: %1" ).arg( svgPath ) ); + + // add it to the list of queued SVGs + mQueuedSvgs << svgPath; + + // we need to avoid spamming the model with notifications about new svgs, so foundSvgs + // is only emitted for blocks of SVGs (otherwise the view goes all flickery) + if ( mTimer.elapsed() > mTimerThreshold ) + { + emit foundSvgs( mQueuedSvgs ); + mQueuedSvgs.clear(); + + // increase the timer threshold - this ensures that the first lots of svgs loaded are added + // to the view quickly, but as the list grows new svgs are added at a slower rate. + // ie, good for initial responsiveness but avoid being spammy as the list grows. + if ( mTimerThreshold < 1000 ) + mTimerThreshold *= 2; + mTimer.restart(); + } + } +} + + +// +// QgsSvgGroupLoader +// + +QgsSvgGroupLoader::QgsSvgGroupLoader( QObject* parent ) + : QThread( parent ) + , mCancelled( false ) +{ + +} + +QgsSvgGroupLoader::~QgsSvgGroupLoader() +{ + stop(); +} + +void QgsSvgGroupLoader::run() +{ + mCancelled = false; + + while ( !mCancelled && !mParentPaths.isEmpty() ) + { + QString parentPath = mParentPaths.takeFirst(); + loadGroup( parentPath ); + } +} + +void QgsSvgGroupLoader::stop() +{ + mCancelled = true; + while ( isRunning() ) {} +} + +void QgsSvgGroupLoader::loadGroup( const QString& parentPath ) +{ + QDir parentDir( parentPath ); + + Q_FOREACH ( const QString& item, parentDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) + { + if ( mCancelled ) + return; + + emit foundPath( parentPath, item ); + mParentPaths.append( parentDir.path() + '/' + item ); + } +} + +///@endcond + +//, +// QgsSvgSelectorListModel +// QgsSvgSelectorListModel::QgsSvgSelectorListModel( QObject* parent ) : QAbstractListModel( parent ) + , mSvgLoader( new QgsSvgSelectorLoader( this ) ) { - mSvgFiles = QgsSymbolLayerUtils::listSvgFiles(); + mSvgLoader->setPath( QString() ); + connect( mSvgLoader, SIGNAL( foundSvgs( QStringList ) ), this, SLOT( addSvgs( QStringList ) ) ); + mSvgLoader->start(); } -// Constructor to create model for icons in a specific path QgsSvgSelectorListModel::QgsSvgSelectorListModel( QObject* parent, const QString& path ) : QAbstractListModel( parent ) + , mSvgLoader( new QgsSvgSelectorLoader( this ) ) { - mSvgFiles = QgsSymbolLayerUtils::listSvgFilesAt( path ); + mSvgLoader->setPath( path ); + connect( mSvgLoader, SIGNAL( foundSvgs( QStringList ) ), this, SLOT( addSvgs( QStringList ) ) ); + mSvgLoader->start(); } -int QgsSvgSelectorListModel::rowCount( const QModelIndex & parent ) const +int QgsSvgSelectorListModel::rowCount( const QModelIndex& parent ) const { Q_UNUSED( parent ); return mSvgFiles.count(); } -QVariant QgsSvgSelectorListModel::data( const QModelIndex & index, int role ) const +QPixmap QgsSvgSelectorListModel::createPreview( const QString& entry ) const +{ + // render SVG file + QColor fill, outline; + double outlineWidth, fillOpacity, outlineOpacity; + bool fillParam, fillOpacityParam, outlineParam, outlineWidthParam, outlineOpacityParam; + bool hasDefaultFillColor = false, hasDefaultFillOpacity = false, hasDefaultOutlineColor = false, + hasDefaultOutlineWidth = false, hasDefaultOutlineOpacity = false; + QgsSvgCache::instance()->containsParams( entry, fillParam, hasDefaultFillColor, fill, + fillOpacityParam, hasDefaultFillOpacity, fillOpacity, + outlineParam, hasDefaultOutlineColor, outline, + outlineWidthParam, hasDefaultOutlineWidth, outlineWidth, + outlineOpacityParam, hasDefaultOutlineOpacity, outlineOpacity ); + + //if defaults not set in symbol, use these values + if ( !hasDefaultFillColor ) + fill = QColor( 200, 200, 200 ); + fill.setAlphaF( hasDefaultFillOpacity ? fillOpacity : 1.0 ); + if ( !hasDefaultOutlineColor ) + outline = Qt::black; + outline.setAlphaF( hasDefaultOutlineOpacity ? outlineOpacity : 1.0 ); + if ( !hasDefaultOutlineWidth ) + outlineWidth = 0.2; + + bool fitsInCache; // should always fit in cache at these sizes (i.e. under 559 px ^ 2, or half cache size) + const QImage& img = QgsSvgCache::instance()->svgAsImage( entry, 30.0, fill, outline, outlineWidth, 3.5 /*appr. 88 dpi*/, 1.0, fitsInCache ); + return QPixmap::fromImage( img ); +} + +QVariant QgsSvgSelectorListModel::data( const QModelIndex& index, int role ) const { QString entry = mSvgFiles.at( index.row() ); @@ -63,31 +255,7 @@ QVariant QgsSvgSelectorListModel::data( const QModelIndex & index, int role ) co QPixmap pixmap; if ( !QPixmapCache::find( entry, pixmap ) ) { - // render SVG file - QColor fill, outline; - double outlineWidth, fillOpacity, outlineOpacity; - bool fillParam, fillOpacityParam, outlineParam, outlineWidthParam, outlineOpacityParam; - bool hasDefaultFillColor = false, hasDefaultFillOpacity = false, hasDefaultOutlineColor = false, - hasDefaultOutlineWidth = false, hasDefaultOutlineOpacity = false; - QgsSvgCache::instance()->containsParams( entry, fillParam, hasDefaultFillColor, fill, - fillOpacityParam, hasDefaultFillOpacity, fillOpacity, - outlineParam, hasDefaultOutlineColor, outline, - outlineWidthParam, hasDefaultOutlineWidth, outlineWidth, - outlineOpacityParam, hasDefaultOutlineOpacity, outlineOpacity ); - - //if defaults not set in symbol, use these values - if ( !hasDefaultFillColor ) - fill = QColor( 200, 200, 200 ); - fill.setAlphaF( hasDefaultFillOpacity ? fillOpacity : 1.0 ); - if ( !hasDefaultOutlineColor ) - outline = Qt::black; - outline.setAlphaF( hasDefaultOutlineOpacity ? outlineOpacity : 1.0 ); - if ( !hasDefaultOutlineWidth ) - outlineWidth = 0.2; - - bool fitsInCache; // should always fit in cache at these sizes (i.e. under 559 px ^ 2, or half cache size) - const QImage& img = QgsSvgCache::instance()->svgAsImage( entry, 30.0, fill, outline, outlineWidth, 3.5 /*appr. 88 dpi*/, 1.0, fitsInCache ); - pixmap = QPixmap::fromImage( img ); + pixmap = createPreview( entry ); QPixmapCache::insert( entry, pixmap ); } @@ -101,18 +269,30 @@ QVariant QgsSvgSelectorListModel::data( const QModelIndex & index, int role ) co return QVariant(); } +void QgsSvgSelectorListModel::addSvgs( const QStringList& svgs ) +{ + beginInsertRows( QModelIndex(), mSvgFiles.count(), mSvgFiles.count() + svgs.size() - 1 ); + mSvgFiles.append( svgs ); + endInsertRows(); +} + + + + //--- QgsSvgSelectorGroupsModel QgsSvgSelectorGroupsModel::QgsSvgSelectorGroupsModel( QObject* parent ) : QStandardItemModel( parent ) + , mLoader( new QgsSvgGroupLoader( this ) ) { QStringList svgPaths = QgsApplication::svgPaths(); QStandardItem *parentItem = invisibleRootItem(); + QStringList parentPaths; for ( int i = 0; i < svgPaths.size(); i++ ) { - QDir dir( svgPaths[i] ); + QDir dir( svgPaths.at( i ) ); QStandardItem *baseGroup; if ( dir.path().contains( QgsApplication::pkgDataPath() ) ) @@ -127,31 +307,41 @@ QgsSvgSelectorGroupsModel::QgsSvgSelectorGroupsModel( QObject* parent ) { baseGroup = new QStandardItem( dir.dirName() ); } - baseGroup->setData( QVariant( svgPaths[i] ) ); + baseGroup->setData( QVariant( svgPaths.at( i ) ) ); baseGroup->setEditable( false ); baseGroup->setCheckable( false ); baseGroup->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); baseGroup->setToolTip( dir.path() ); parentItem->appendRow( baseGroup ); - createTree( baseGroup ); + parentPaths << svgPaths.at( i ); + mPathItemHash.insert( svgPaths.at( i ), baseGroup ); QgsDebugMsg( QString( "SVG base path %1: %2" ).arg( i ).arg( baseGroup->data().toString() ) ); } + mLoader->setParentPaths( parentPaths ); + connect( mLoader, SIGNAL( foundPath( QString, QString ) ), this, SLOT( addPath( QString, QString ) ) ); + mLoader->start(); } -void QgsSvgSelectorGroupsModel::createTree( QStandardItem* &parentGroup ) +QgsSvgSelectorGroupsModel::~QgsSvgSelectorGroupsModel() { - QDir parentDir( parentGroup->data().toString() ); - Q_FOREACH ( const QString& item, parentDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) - { - QStandardItem* group = new QStandardItem( item ); - group->setData( QVariant( parentDir.path() + '/' + item ) ); - group->setEditable( false ); - group->setCheckable( false ); - group->setToolTip( parentDir.path() + '/' + item ); - group->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); - parentGroup->appendRow( group ); - createTree( group ); - } + mLoader->stop(); +} + +void QgsSvgSelectorGroupsModel::addPath( const QString& parentPath, const QString& item ) +{ + QStandardItem* parentGroup = mPathItemHash.value( parentPath ); + if ( !parentGroup ) + return; + + QString fullPath = parentPath + '/' + item; + QStandardItem* group = new QStandardItem( item ); + group->setData( QVariant( fullPath ) ); + group->setEditable( false ); + group->setCheckable( false ); + group->setToolTip( fullPath ); + group->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); + parentGroup->appendRow( group ); + mPathItemHash.insert( fullPath, group ); } @@ -250,11 +440,14 @@ void QgsSvgSelectorWidget::populateIcons( const QModelIndex& idx ) { QString path = idx.data( Qt::UserRole + 1 ).toString(); + QAbstractItemModel* oldModel = mImagesListView->model(); QgsSvgSelectorListModel* m = new QgsSvgSelectorListModel( mImagesListView, path ); mImagesListView->setModel( m ); + delete oldModel; //explicitly delete old model to force any background threads to stop connect( mImagesListView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( svgSelectionChanged( const QModelIndex& ) ) ); + } void QgsSvgSelectorWidget::on_mFilePushButton_clicked() @@ -319,8 +512,10 @@ void QgsSvgSelectorWidget::populateList() } // Initally load the icons in the List view without any grouping + QAbstractItemModel* oldModel = mImagesListView->model(); QgsSvgSelectorListModel* m = new QgsSvgSelectorListModel( mImagesListView ); mImagesListView->setModel( m ); + delete oldModel; //explicitly delete old model to force any background threads to stop } //-- QgsSvgSelectorDialog @@ -357,3 +552,4 @@ QgsSvgSelectorDialog::~QgsSvgSelectorDialog() QSettings settings; settings.setValue( "/Windows/SvgSelectorDialog/geometry", saveGeometry() ); } + diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.h b/src/gui/symbology-ng/qgssvgselectorwidget.h index e7ccbdc2709c..f959d622e481 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.h +++ b/src/gui/symbology-ng/qgssvgselectorwidget.h @@ -20,13 +20,14 @@ #include "ui_widget_svgselector.h" #include "qgisgui.h" - #include #include #include #include #include #include +#include +#include class QCheckBox; class QLayout; @@ -35,29 +36,172 @@ class QListView; class QPushButton; class QTreeView; +///@cond PRIVATE + +/** \ingroup gui + * \class QgsSvgSelectorLoader + * Recursively loads SVG images from a path in a background thread. + * \note added in QGIS 2.18 + */ +class GUI_EXPORT QgsSvgSelectorLoader : public QThread +{ + Q_OBJECT + + public: + + /** Constructor for QgsSvgSelectorLoader + * @param parent parent object + */ + QgsSvgSelectorLoader( QObject* parent = nullptr ); + + ~QgsSvgSelectorLoader(); + + /** Starts the loader finding and generating previews for SVG images. foundSvgs() will be + * emitted as the loader encounters SVG images. + * @brief run + */ + virtual void run() override; + + /** Cancels the current loading operation. Waits until the thread has finished operation + * before returning. + */ + virtual void stop(); + + /** Sets the root path containing SVG images to load. If no path is set, the default SVG + * search paths will be used instead. + */ + void setPath( const QString& path ) + { + mPath = path; + } + + signals: + + /** Emitted when the loader has found a block of SVG images. This signal is emitted with blocks + * of SVG images to prevent spamming any connected model. + * @param svgs list of SVGs and preview images found. + */ + void foundSvgs( QStringList svgs ); + + private: + + QString mPath; + bool mCancelled; + QStringList mQueuedSvgs; + + QElapsedTimer mTimer; + int mTimerThreshold; + + void loadPath( const QString& path ); + void loadImages( const QString& path ); + +}; + +/** \ingroup gui + * \class QgsSvgGroupLoader + * Recursively loads SVG paths in a background thread. + * \note added in QGIS 2.18 + */ +class GUI_EXPORT QgsSvgGroupLoader : public QThread +{ + Q_OBJECT + + public: + + /** Constructor for QgsSvgGroupLoader + * @param parent parent object + */ + QgsSvgGroupLoader( QObject* parent = nullptr ); + + ~QgsSvgGroupLoader(); + + /** Starts the loader finding folders for SVG images. + * @brief run + */ + virtual void run() override; + + /** Cancels the current loading operation. Waits until the thread has finished operation + * before returning. + */ + virtual void stop(); + + /** Sets the root path containing child paths to find. If no path is set, the default SVG + * search paths will be used instead. + */ + void setParentPaths( const QStringList& parentPaths ) + { + mParentPaths = parentPaths; + } + + signals: + + /** Emitted when the loader has found a block of SVG images. This signal is emitted with blocks + * of SVG images to prevent spamming any connected model. + * @param svgs list of SVGs and preview images found. + */ + void foundPath( const QString& parentPath, const QString& path ); + + private: + + QStringList mParentPaths; + bool mCancelled; + + void loadGroup( const QString& parentPath ); + +}; + +///@endcond +/// + /** \ingroup gui * \class QgsSvgSelectorListModel + * A model for displaying SVG files with a preview icon. Population of the model is performed in + * a background thread to ensure that initial creation of the model is responsive and does + * not block the GUI. */ class GUI_EXPORT QgsSvgSelectorListModel : public QAbstractListModel { Q_OBJECT public: + + /** Constructor for QgsSvgSelectorListModel. All SVGs in folders from the application SVG + * search paths will be shown. + * @param parent parent object + */ QgsSvgSelectorListModel( QObject* parent ); - // Constructor to create model for icons in a specific path + /** Constructor for creating a model for SVG files in a specific path. + * @param parent parent object + * @param path initial path, which is recursively searched + */ QgsSvgSelectorListModel( QObject* parent, const QString& path ); int rowCount( const QModelIndex & parent = QModelIndex() ) const override; - QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const override; protected: QStringList mSvgFiles; + + private: + QPixmap createPreview( const QString& entry ) const; + QgsSvgSelectorLoader* mSvgLoader; + + private slots: + + /** Called to add SVG files to the model. + * @param svgs list of SVG files to add to model. + */ + void addSvgs( const QStringList& svgs ); + }; + /** \ingroup gui * \class QgsSvgSelectorGroupsModel + * A model for displaying SVG search paths. Population of the model is performed in + * a background thread to ensure that initial creation of the model is responsive and does + * not block the GUI. */ class GUI_EXPORT QgsSvgSelectorGroupsModel : public QStandardItemModel { @@ -65,9 +209,15 @@ class GUI_EXPORT QgsSvgSelectorGroupsModel : public QStandardItemModel public: QgsSvgSelectorGroupsModel( QObject* parent ); + ~QgsSvgSelectorGroupsModel(); private: - void createTree( QStandardItem* &parentGroup ); + QgsSvgGroupLoader* mLoader; + QHash< QString, QStandardItem* > mPathItemHash; + + private slots: + + void addPath( const QString& parentPath, const QString& path ); }; /** \ingroup gui @@ -114,6 +264,7 @@ class GUI_EXPORT QgsSvgSelectorWidget : public QWidget, private Ui::WidgetSvgSel private: QString mCurrentSvgPath; // always stored as absolute path + }; /** \ingroup gui diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.cpp b/src/gui/symbology-ng/qgssymbollayerwidget.cpp index d42460459b0c..9d614b0a6607 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgssymbollayerwidget.cpp @@ -34,6 +34,7 @@ #include "qgsmapcanvas.h" #include "qgsapplication.h" #include "qgsvectorlayer.h" +#include "qgssvgselectorwidget.h" #include "qgslogger.h" #include "qgssizescalewidget.h" @@ -1802,8 +1803,11 @@ QgsSvgMarkerSymbolLayerWidget::~QgsSvgMarkerSymbolLayerWidget() void QgsSvgMarkerSymbolLayerWidget::populateList() { - QgsSvgGroupsModel* g = new QgsSvgGroupsModel( viewGroups ); + QAbstractItemModel* oldModel = viewGroups->model(); + QgsSvgSelectorGroupsModel* g = new QgsSvgSelectorGroupsModel( viewGroups ); viewGroups->setModel( g ); + delete oldModel; + // Set the tree expanded at the first level int rows = g->rowCount( g->indexFromItem( g->invisibleRootItem() ) ); for ( int i = 0; i < rows; i++ ) @@ -1812,19 +1816,22 @@ void QgsSvgMarkerSymbolLayerWidget::populateList() } // Initally load the icons in the List view without any grouping - QgsSvgListModel* m = new QgsSvgListModel( viewImages ); + oldModel = viewImages->model(); + QgsSvgSelectorListModel* m = new QgsSvgSelectorListModel( viewImages ); viewImages->setModel( m ); + delete oldModel; } void QgsSvgMarkerSymbolLayerWidget::populateIcons( const QModelIndex& idx ) { QString path = idx.data( Qt::UserRole + 1 ).toString(); - QgsSvgListModel* m = new QgsSvgListModel( viewImages, path ); + QAbstractItemModel* oldModel = viewImages->model(); + QgsSvgSelectorListModel* m = new QgsSvgSelectorListModel( viewImages, path ); viewImages->setModel( m ); + delete oldModel; connect( viewImages->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setName( const QModelIndex& ) ) ); - emit changed(); } void QgsSvgMarkerSymbolLayerWidget::setGuiForSvg( const QgsSvgMarkerSymbolLayer* layer ) @@ -2285,8 +2292,11 @@ void QgsSVGFillSymbolLayerWidget::setFile( const QModelIndex& item ) void QgsSVGFillSymbolLayerWidget::insertIcons() { - QgsSvgGroupsModel* g = new QgsSvgGroupsModel( mSvgTreeView ); + QAbstractItemModel* oldModel = mSvgTreeView->model(); + QgsSvgSelectorGroupsModel* g = new QgsSvgSelectorGroupsModel( mSvgTreeView ); mSvgTreeView->setModel( g ); + delete oldModel; + // Set the tree expanded at the first level int rows = g->rowCount( g->indexFromItem( g->invisibleRootItem() ) ); for ( int i = 0; i < rows; i++ ) @@ -2294,19 +2304,22 @@ void QgsSVGFillSymbolLayerWidget::insertIcons() mSvgTreeView->setExpanded( g->indexFromItem( g->item( i ) ), true ); } - QgsSvgListModel* m = new QgsSvgListModel( mSvgListView ); + oldModel = mSvgListView->model(); + QgsSvgSelectorListModel* m = new QgsSvgSelectorListModel( mSvgListView ); mSvgListView->setModel( m ); + delete oldModel; } void QgsSVGFillSymbolLayerWidget::populateIcons( const QModelIndex& idx ) { QString path = idx.data( Qt::UserRole + 1 ).toString(); - QgsSvgListModel* m = new QgsSvgListModel( mSvgListView, path ); + QAbstractItemModel* oldModel = mSvgListView->model(); + QgsSvgSelectorListModel* m = new QgsSvgSelectorListModel( mSvgListView, path ); mSvgListView->setModel( m ); + delete oldModel; connect( mSvgListView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setFile( const QModelIndex& ) ) ); - emit changed(); } @@ -3203,129 +3216,6 @@ void QgsRasterFillSymbolLayerWidget::updatePreviewImage() } -/// @cond PRIVATE - -QgsSvgListModel::QgsSvgListModel( QObject* parent ) : QAbstractListModel( parent ) -{ - mSvgFiles = QgsSymbolLayerUtils::listSvgFiles(); -} - -QgsSvgListModel::QgsSvgListModel( QObject* parent, const QString& path ) : QAbstractListModel( parent ) -{ - mSvgFiles = QgsSymbolLayerUtils::listSvgFilesAt( path ); -} - -int QgsSvgListModel::rowCount( const QModelIndex& parent ) const -{ - Q_UNUSED( parent ); - return mSvgFiles.count(); -} - -QVariant QgsSvgListModel::data( const QModelIndex& index, int role ) const -{ - QString entry = mSvgFiles.at( index.row() ); - - if ( role == Qt::DecorationRole ) // icon - { - QPixmap pixmap; - if ( !QPixmapCache::find( entry, pixmap ) ) - { - // render SVG file - QColor fill, outline; - double outlineWidth, fillOpacity, outlineOpacity; - bool fillParam, fillOpacityParam, outlineParam, outlineWidthParam, outlineOpacityParam; - bool hasDefaultFillColor = false, hasDefaultFillOpacity = false, hasDefaultOutlineColor = false, - hasDefaultOutlineWidth = false, hasDefaultOutlineOpacity = false; - QgsSvgCache::instance()->containsParams( entry, fillParam, hasDefaultFillColor, fill, - fillOpacityParam, hasDefaultFillOpacity, fillOpacity, - outlineParam, hasDefaultOutlineColor, outline, - outlineWidthParam, hasDefaultOutlineWidth, outlineWidth, - outlineOpacityParam, hasDefaultOutlineOpacity, outlineOpacity ); - - //if defaults not set in symbol, use these values - if ( !hasDefaultFillColor ) - fill = QColor( 200, 200, 200 ); - fill.setAlphaF( hasDefaultFillOpacity ? fillOpacity : 1.0 ); - if ( !hasDefaultOutlineColor ) - outline = Qt::black; - outline.setAlphaF( hasDefaultOutlineOpacity ? outlineOpacity : 1.0 ); - if ( !hasDefaultOutlineWidth ) - outlineWidth = 0.6; - - bool fitsInCache; // should always fit in cache at these sizes (i.e. under 559 px ^ 2, or half cache size) - const QImage& img = QgsSvgCache::instance()->svgAsImage( entry, 30.0, fill, outline, outlineWidth, 3.5 /*appr. 88 dpi*/, 1.0, fitsInCache ); - pixmap = QPixmap::fromImage( img ); - QPixmapCache::insert( entry, pixmap ); - } - - return pixmap; - } - else if ( role == Qt::UserRole || role == Qt::ToolTipRole ) - { - return entry; - } - - return QVariant(); -} - - -QgsSvgGroupsModel::QgsSvgGroupsModel( QObject* parent ) : QStandardItemModel( parent ) -{ - QStringList svgPaths = QgsApplication::svgPaths(); - QStandardItem *parentItem = invisibleRootItem(); - - for ( int i = 0; i < svgPaths.size(); i++ ) - { - QDir dir( svgPaths[i] ); - QStandardItem *baseGroup; - - if ( dir.path().contains( QgsApplication::pkgDataPath() ) ) - { - baseGroup = new QStandardItem( QString( "App Symbols" ) ); - } - else if ( dir.path().contains( QgsApplication::qgisSettingsDirPath() ) ) - { - baseGroup = new QStandardItem( QString( "User Symbols" ) ); - } - else - { - baseGroup = new QStandardItem( dir.dirName() ); - } - baseGroup->setData( QVariant( svgPaths[i] ) ); - baseGroup->setEditable( false ); - baseGroup->setCheckable( false ); - baseGroup->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); - baseGroup->setToolTip( dir.path() ); - parentItem->appendRow( baseGroup ); - createTree( baseGroup ); - QgsDebugMsg( QString( "SVG base path %1: %2" ).arg( i ).arg( baseGroup->data().toString() ) ); - } -} - -void QgsSvgGroupsModel::createTree( QStandardItem*& parentGroup ) -{ - QDir parentDir( parentGroup->data().toString() ); - Q_FOREACH ( const QString& item, parentDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) - { - QStandardItem* group = new QStandardItem( item ); - group->setData( QVariant( parentDir.path() + '/' + item ) ); - group->setEditable( false ); - group->setCheckable( false ); - group->setToolTip( parentDir.path() + '/' + item ); - group->setIcon( QgsApplication::style()->standardIcon( QStyle::SP_DirIcon ) ); - parentGroup->appendRow( group ); - createTree( group ); - } -} - - -/// @endcond - - - - - - QgsGeometryGeneratorSymbolLayerWidget::QgsGeometryGeneratorSymbolLayerWidget( const QgsVectorLayer* vl, QWidget* parent ) : QgsSymbolLayerWidget( parent, vl ) , mLayer( nullptr ) diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.h b/src/gui/symbology-ng/qgssymbollayerwidget.h index 732f2926fcb4..02059124187f 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.h +++ b/src/gui/symbology-ng/qgssymbollayerwidget.h @@ -707,39 +707,6 @@ class GUI_EXPORT QgsCentroidFillSymbolLayerWidget : public QgsSymbolLayerWidget, }; -///@cond PRIVATE - -class QgsSvgListModel : public QAbstractListModel -{ - Q_OBJECT - - public: - explicit QgsSvgListModel( QObject* parent ); - - // Constructor to create model for icons in a specific path - QgsSvgListModel( QObject* parent, const QString& path ); - - int rowCount( const QModelIndex & parent = QModelIndex() ) const override; - - QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const override; - - protected: - QStringList mSvgFiles; -}; - -class QgsSvgGroupsModel : public QStandardItemModel -{ - Q_OBJECT - - public: - explicit QgsSvgGroupsModel( QObject* parent ); - - private: - void createTree( QStandardItem* &parentGroup ); -}; - -///@endcond - #include "ui_qgsgeometrygeneratorwidgetbase.h" class QgsGeometryGeneratorSymbolLayer; From a20c3cf68a6ddbe334495399df4f3758e0925700 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 15:26:56 +1000 Subject: [PATCH 078/897] Guard against circular symbolic links in SVG selector widget --- src/gui/symbology-ng/qgssvgselectorwidget.cpp | 19 ++++++++++++++++++- src/gui/symbology-ng/qgssvgselectorwidget.h | 2 ++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.cpp b/src/gui/symbology-ng/qgssvgselectorwidget.cpp index 012a7c01c6fa..70721b5c0b42 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.cpp +++ b/src/gui/symbology-ng/qgssvgselectorwidget.cpp @@ -51,6 +51,7 @@ void QgsSvgSelectorLoader::run() { mCancelled = false; mQueuedSvgs.clear(); + mTraversedPaths.clear(); // start with a small initial timeout (ms) mTimerThreshold = 10; @@ -92,9 +93,17 @@ void QgsSvgSelectorLoader::loadPath( const QString& path ) } else { + QDir dir( path ); + + //guard against circular symbolic links + QString canonicalPath = dir.canonicalPath(); + if ( mTraversedPaths.contains( canonicalPath ) ) + return; + + mTraversedPaths.insert( canonicalPath ); + loadImages( path ); - QDir dir( path ); Q_FOREACH ( const QString& item, dir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) { if ( mCancelled ) @@ -159,6 +168,7 @@ QgsSvgGroupLoader::~QgsSvgGroupLoader() void QgsSvgGroupLoader::run() { mCancelled = false; + mTraversedPaths.clear(); while ( !mCancelled && !mParentPaths.isEmpty() ) { @@ -177,6 +187,13 @@ void QgsSvgGroupLoader::loadGroup( const QString& parentPath ) { QDir parentDir( parentPath ); + //guard against circular symbolic links + QString canonicalPath = parentDir.canonicalPath(); + if ( mTraversedPaths.contains( canonicalPath ) ) + return; + + mTraversedPaths.insert( canonicalPath ); + Q_FOREACH ( const QString& item, parentDir.entryList( QDir::Dirs | QDir::NoDotAndDotDot ) ) { if ( mCancelled ) diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.h b/src/gui/symbology-ng/qgssvgselectorwidget.h index f959d622e481..3095aa8f1ff0 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.h +++ b/src/gui/symbology-ng/qgssvgselectorwidget.h @@ -91,6 +91,7 @@ class GUI_EXPORT QgsSvgSelectorLoader : public QThread QElapsedTimer mTimer; int mTimerThreshold; + QSet< QString > mTraversedPaths; void loadPath( const QString& path ); void loadImages( const QString& path ); @@ -145,6 +146,7 @@ class GUI_EXPORT QgsSvgGroupLoader : public QThread QStringList mParentPaths; bool mCancelled; + QSet< QString > mTraversedPaths; void loadGroup( const QString& parentPath ); From a2166bd04288a3e89097775ddc2464551142b9dc Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 15:34:13 +1000 Subject: [PATCH 079/897] Small optimisations to model/views --- src/gui/symbology-ng/qgssvgselectorwidget.cpp | 2 +- src/ui/symbollayer/widget_svgfill.ui | 29 ++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.cpp b/src/gui/symbology-ng/qgssvgselectorwidget.cpp index 70721b5c0b42..a7839c3e3491 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.cpp +++ b/src/gui/symbology-ng/qgssvgselectorwidget.cpp @@ -133,7 +133,7 @@ void QgsSvgSelectorLoader::loadImages( const QString& path ) // we need to avoid spamming the model with notifications about new svgs, so foundSvgs // is only emitted for blocks of SVGs (otherwise the view goes all flickery) - if ( mTimer.elapsed() > mTimerThreshold ) + if ( mTimer.elapsed() > mTimerThreshold && !mQueuedSvgs.isEmpty() ) { emit foundSvgs( mQueuedSvgs ); mQueuedSvgs.clear(); diff --git a/src/ui/symbollayer/widget_svgfill.ui b/src/ui/symbollayer/widget_svgfill.ui index da27629e813b..072f082711b6 100644 --- a/src/ui/symbollayer/widget_svgfill.ui +++ b/src/ui/symbollayer/widget_svgfill.ui @@ -6,7 +6,7 @@ 0 0 - 270 + 300 459 @@ -280,12 +280,27 @@ 0 + + + 32 + 32 + + QListView::LeftToRight + + QListView::Adjust + QListView::Batched + + + 36 + 36 + + QListView::IconMode @@ -306,12 +321,6 @@ - - QgsColorButton - QToolButton -
                                                                                                                                                                                    qgscolorbutton.h
                                                                                                                                                                                    - 1 -
                                                                                                                                                                                    QgsDataDefinedButton QToolButton @@ -328,6 +337,12 @@
                                                                                                                                                                                    qgsunitselectionwidget.h
                                                                                                                                                                                    1
                                                                                                                                                                                    + + QgsColorButton + QToolButton +
                                                                                                                                                                                    qgscolorbutton.h
                                                                                                                                                                                    + 1 +
                                                                                                                                                                                    mTextureWidthSpinBox From 3abded31869c40374315a2403f586aad7d07dae4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 15:45:17 +1000 Subject: [PATCH 080/897] Keep the user set order for svg paths --- src/core/qgsapplication.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 30b5415986d4..99c1465e2aa2 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -714,8 +714,20 @@ QStringList QgsApplication::svgPaths() myPathList = myPaths.split( '|' ); } - myPathList << ABISYM( mDefaultSvgPaths ); - return myPathList.toSet().toList(); + // maintain user set order while stripping duplicates + QStringList paths; + Q_FOREACH ( const QString& path, myPathList ) + { + if ( !paths.contains( path ) ) + paths.append( path ); + } + Q_FOREACH ( const QString& path, ABISYM( mDefaultSvgPaths ) ) + { + if ( !paths.contains( path ) ) + paths.append( path ); + } + + return paths; } /*! From 111106c64fcf4288617e65fc160a2b6112606cfc Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 16:34:02 +1000 Subject: [PATCH 081/897] Fix cannot modify diagram attribute expression (fix #15514) Also clean up some code --- src/app/qgsdiagramproperties.cpp | 123 +++++++++++++++++---------- src/app/qgsdiagramproperties.h | 30 +++++++ src/app/qgsvectorlayerproperties.cpp | 2 +- 3 files changed, 110 insertions(+), 45 deletions(-) diff --git a/src/app/qgsdiagramproperties.cpp b/src/app/qgsdiagramproperties.cpp index 350e594aad47..81d21d5024c1 100644 --- a/src/app/qgsdiagramproperties.cpp +++ b/src/app/qgsdiagramproperties.cpp @@ -19,7 +19,6 @@ #include "diagram/qgspiediagram.h" #include "diagram/qgstextdiagram.h" -#include "qgisapp.h" #include "qgsproject.h" #include "qgsapplication.h" #include "qgsdiagramproperties.h" @@ -36,18 +35,21 @@ #include "qgsmapcanvas.h" #include "qgsexpressionbuilderdialog.h" #include "qgslogger.h" +#include "qgisapp.h" #include #include #include + + QgsExpressionContext QgsDiagramProperties::createExpressionContext() const { QgsExpressionContext expContext; expContext << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ) - << QgsExpressionContextUtils::mapSettingsScope( QgisApp::instance()->mapCanvas()->mapSettings() ) + << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) << QgsExpressionContextUtils::layerScope( mLayer ); return expContext; @@ -79,7 +81,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM ); mDiagramTypeComboBox->blockSignals( false ); - mScaleRangeWidget->setMapCanvas( QgisApp::instance()->mapCanvas() ); + mScaleRangeWidget->setMapCanvas( mMapCanvas ); mSizeFieldExpressionWidget->registerExpressionContextGenerator( this ); mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) ); @@ -95,6 +97,9 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare mMaxValueSpinBox->setShowClearButton( false ); + mDiagramAttributesTreeWidget->setItemDelegateForColumn( ColumnAttributeExpression, new EditBlockerDelegate( this ) ); + mDiagramAttributesTreeWidget->setItemDelegateForColumn( ColumnColor, new EditBlockerDelegate( this ) ); + connect( mFixedSizeRadio, SIGNAL( toggled( bool ) ), this, SLOT( scalingTypeChanged() ) ); connect( mAttributeBasedScalingRadio, SIGNAL( toggled( bool ) ), this, SLOT( scalingTypeChanged() ) ); @@ -172,7 +177,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare mSizeFieldExpressionWidget->setLayer( mLayer ); QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); - myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); + myDa.setEllipsoidalMode( mMapCanvas->mapSettings().hasCrsTransformEnabled() ); myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); mSizeFieldExpressionWidget->setGeomCalculator( myDa ); @@ -183,7 +188,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget ); QString name = QString( "\"%1\"" ).arg( layerFields.at( idx ).name() ); newItem->setText( 0, name ); - newItem->setData( 0, Qt::UserRole, name ); + newItem->setData( 0, RoleAttributeExpression, name ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); mDataDefinedXComboBox->addItem( layerFields.at( idx ).name(), idx ); @@ -340,7 +345,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare { QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget ); newItem->setText( 0, *catIt ); - newItem->setData( 0, Qt::UserRole, *catIt ); + newItem->setData( 0, RoleAttributeExpression, *catIt ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); QColor col( *coIt ); col.setAlpha( 255 ); @@ -518,7 +523,7 @@ void QgsDiagramProperties::addAttribute( QTreeWidgetItem * item ) newItem->setText( 0, item->text( 0 ) ); newItem->setText( 2, guessLegendText( item->text( 0 ) ) ); - newItem->setData( 0, Qt::UserRole, item->data( 0, Qt::UserRole ) ); + newItem->setData( 0, RoleAttributeExpression, item->data( 0, RoleAttributeExpression ) ); newItem->setFlags(( newItem->flags() | Qt::ItemIsEditable ) & ~Qt::ItemIsDropEnabled ); //set initial color for diagram category @@ -567,7 +572,7 @@ void QgsDiagramProperties::on_mFindMaximumValueButton_clicked() QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() - << QgsExpressionContextUtils::mapSettingsScope( QgisApp::instance()->mapCanvas()->mapSettings() ) + << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) << QgsExpressionContextUtils::layerScope( mLayer ); exp.prepare( &context ); @@ -604,13 +609,33 @@ void QgsDiagramProperties::on_mDiagramFontButton_clicked() void QgsDiagramProperties::on_mDiagramAttributesTreeWidget_itemDoubleClicked( QTreeWidgetItem * item, int column ) { - if ( column == 1 ) //change color + switch ( column ) { - QColor newColor = QgsColorDialog::getColor( item->background( 1 ).color(), nullptr ); - if ( newColor.isValid() ) + case ColumnAttributeExpression: { - item->setBackground( 1, QBrush( newColor ) ); + QString currentExpression = item->data( 0, RoleAttributeExpression ).toString(); + + QString newExpression = showExpressionBuilder( currentExpression ); + if ( !newExpression.isEmpty() ) + { + item->setData( 0, Qt::DisplayRole, newExpression ); + item->setData( 0, RoleAttributeExpression, newExpression ); + } + break; } + + case ColumnColor: + { + QColor newColor = QgsColorDialog::getColor( item->background( 1 ).color(), nullptr ); + if ( newColor.isValid() ) + { + item->setBackground( 1, QBrush( newColor ) ); + } + break; + } + + case ColumnLegendText: + break; } } @@ -713,7 +738,7 @@ void QgsDiagramProperties::apply() QColor color = mDiagramAttributesTreeWidget->topLevelItem( i )->background( 1 ).color(); color.setAlpha( 255 - ds.transparency ); categoryColors.append( color ); - categoryAttributes.append( mDiagramAttributesTreeWidget->topLevelItem( i )->data( 0, Qt::UserRole ).toString() ); + categoryAttributes.append( mDiagramAttributesTreeWidget->topLevelItem( i )->data( 0, RoleAttributeExpression ).toString() ); categoryLabels.append( mDiagramAttributesTreeWidget->topLevelItem( i )->text( 2 ) ); } ds.categoryColors = categoryColors; @@ -827,56 +852,66 @@ void QgsDiagramProperties::apply() mLayer->setDiagramLayerSettings( dls ); // refresh - QgisApp::instance()->markDirty(); + QgsProject::instance()->setDirty( true ); mLayer->triggerRepaint(); } -void QgsDiagramProperties::showAddAttributeExpressionDialog() +QString QgsDiagramProperties::showExpressionBuilder( const QString& initialExpression ) { - QString expression; - QList selections = mAttributesTreeWidget->selectedItems(); - if ( !selections.empty() ) - { - expression = selections[0]->text( 0 ); - } - QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ) - << QgsExpressionContextUtils::mapSettingsScope( QgisApp::instance()->mapCanvas()->mapSettings() ) + << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) << QgsExpressionContextUtils::layerScope( mLayer ); - QgsExpressionBuilderDialog dlg( mLayer, expression, this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, initialExpression, this, "generic", context ); dlg.setWindowTitle( tr( "Expression based attribute" ) ); QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); - myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); + myDa.setEllipsoidalMode( mMapCanvas->mapSettings().hasCrsTransformEnabled() ); myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); dlg.setGeomCalculator( myDa ); if ( dlg.exec() == QDialog::Accepted ) { - QString expression = dlg.expressionText(); - //Only add the expression if the user has entered some text. - if ( !expression.isEmpty() ) - { - QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget ); - - newItem->setText( 0, expression ); - newItem->setText( 2, expression ); - newItem->setData( 0, Qt::UserRole, expression ); - newItem->setFlags(( newItem->flags() | Qt::ItemIsEditable ) & ~Qt::ItemIsDropEnabled ); - - //set initial color for diagram category - int red = 1 + ( int )( 255.0 * qrand() / ( RAND_MAX + 1.0 ) ); - int green = 1 + ( int )( 255.0 * qrand() / ( RAND_MAX + 1.0 ) ); - int blue = 1 + ( int )( 255.0 * qrand() / ( RAND_MAX + 1.0 ) ); - QColor randomColor( red, green, blue ); - newItem->setBackground( 1, QBrush( randomColor ) ); - mDiagramAttributesTreeWidget->addTopLevelItem( newItem ); - } + return dlg.expressionText(); + } + else + { + return QString(); + } +} + +void QgsDiagramProperties::showAddAttributeExpressionDialog() +{ + QString expression; + QList selections = mAttributesTreeWidget->selectedItems(); + if ( !selections.empty() ) + { + expression = selections[0]->text( 0 ); + } + + QString newExpression = showExpressionBuilder( expression ); + + //Only add the expression if the user has entered some text. + if ( !newExpression.isEmpty() ) + { + QTreeWidgetItem *newItem = new QTreeWidgetItem( mDiagramAttributesTreeWidget ); + + newItem->setText( 0, newExpression ); + newItem->setText( 2, newExpression ); + newItem->setData( 0, RoleAttributeExpression, newExpression ); + newItem->setFlags(( newItem->flags() | Qt::ItemIsEditable ) & ~Qt::ItemIsDropEnabled ); + + //set initial color for diagram category + int red = 1 + ( int )( 255.0 * qrand() / ( RAND_MAX + 1.0 ) ); + int green = 1 + ( int )( 255.0 * qrand() / ( RAND_MAX + 1.0 ) ); + int blue = 1 + ( int )( 255.0 * qrand() / ( RAND_MAX + 1.0 ) ); + QColor randomColor( red, green, blue ); + newItem->setBackground( 1, QBrush( randomColor ) ); + mDiagramAttributesTreeWidget->addTopLevelItem( newItem ); } activateWindow(); // set focus back parent } diff --git a/src/app/qgsdiagramproperties.h b/src/app/qgsdiagramproperties.h index 173950a7f430..f5c83ae5de9f 100644 --- a/src/app/qgsdiagramproperties.h +++ b/src/app/qgsdiagramproperties.h @@ -20,6 +20,7 @@ #include #include +#include class QgsVectorLayer; class QgsMapCanvas; @@ -58,6 +59,21 @@ class APP_EXPORT QgsDiagramProperties : public QWidget, private Ui::QgsDiagramPr QgsVectorLayer* mLayer; private: + + enum Columns + { + ColumnAttributeExpression = 0, + ColumnColor, + ColumnLegendText, + }; + + enum Roles + { + RoleAttributeExpression = Qt::UserRole, + }; + + QString showExpressionBuilder( const QString& initialExpression ); + // Keeps track of the diagram type to properly save / restore settings when the diagram type combo box is set to no diagram. QString mDiagramType; QScopedPointer< QgsMarkerSymbol > mSizeLegendSymbol; @@ -68,4 +84,18 @@ class APP_EXPORT QgsDiagramProperties : public QWidget, private Ui::QgsDiagramPr QgsExpressionContext createExpressionContext() const override; }; +class EditBlockerDelegate: public QStyledItemDelegate +{ + public: + EditBlockerDelegate( QObject* parent = nullptr ) + : QStyledItemDelegate( parent ) + {} + + virtual QWidget* createEditor( QWidget *, const QStyleOptionViewItem &, const QModelIndex & ) const override + { + return nullptr; + } +}; + + #endif // QGSDIAGRAMPROPERTIES_H diff --git a/src/app/qgsvectorlayerproperties.cpp b/src/app/qgsvectorlayerproperties.cpp index bf7c5ab57a84..815c0cb50a9f 100644 --- a/src/app/qgsvectorlayerproperties.cpp +++ b/src/app/qgsvectorlayerproperties.cpp @@ -236,7 +236,7 @@ QgsVectorLayerProperties::QgsVectorLayerProperties( QVBoxLayout* diagLayout = new QVBoxLayout( mDiagramFrame ); diagLayout->setMargin( 0 ); - diagramPropertiesDialog = new QgsDiagramProperties( mLayer, mDiagramFrame, nullptr ); + diagramPropertiesDialog = new QgsDiagramProperties( mLayer, mDiagramFrame, QgisApp::instance()->mapCanvas() ); diagramPropertiesDialog->layout()->setContentsMargins( -1, 0, -1, 0 ); diagLayout->addWidget( diagramPropertiesDialog ); mDiagramFrame->setLayout( diagLayout ); From 62c85100891b6b3f8fdf1ab828874341d7e47161 Mon Sep 17 00:00:00 2001 From: Mathieu Pellerin Date: Tue, 4 Oct 2016 15:45:10 +0700 Subject: [PATCH 082/897] [qt5] setConfirmOverwrite is gone, use setOption (#3567) --- .../plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py | 2 +- python/plugins/processing/gui/OutputSelectionPanel.py | 4 ++-- src/gui/qgisgui.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py index 8a18dd73ebed..91f2f0d8abcd 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py @@ -146,7 +146,7 @@ def selectFile(self): lastEncoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) - fileDialog.setConfirmOverwrite(True) + fileDialog.setOption(QFileDialog.DontConfirmOverwrite, False) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = str(fileDialog.encoding()) diff --git a/python/plugins/processing/gui/OutputSelectionPanel.py b/python/plugins/processing/gui/OutputSelectionPanel.py index 517fb8bccdce..58830956fba6 100644 --- a/python/plugins/processing/gui/OutputSelectionPanel.py +++ b/python/plugins/processing/gui/OutputSelectionPanel.py @@ -175,7 +175,7 @@ def saveToSpatialite(self): self, self.tr('Save Spatialite'), path, fileFilter, encoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) - fileDialog.setConfirmOverwrite(False) + fileDialog.setOption(QFileDialog.DontConfirmOverwrite, True) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() @@ -212,7 +212,7 @@ def selectFile(self): self, self.tr('Save file'), path, fileFilter, encoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) - fileDialog.setConfirmOverwrite(True) + fileDialog.setOption(QFileDialog.DontConfirmOverwrite, False) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() diff --git a/src/gui/qgisgui.cpp b/src/gui/qgisgui.cpp index 58b1d7cbfa52..a6f3ede74249 100644 --- a/src/gui/qgisgui.cpp +++ b/src/gui/qgisgui.cpp @@ -144,7 +144,7 @@ namespace QgisGui // allow for selection of more than one file fileDialog->setFileMode( QFileDialog::AnyFile ); fileDialog->setAcceptMode( QFileDialog::AcceptSave ); - fileDialog->setConfirmOverwrite( true ); + fileDialog->setOption( QFileDialog::DontConfirmOverwrite, false ); if ( !selectedFilter.isEmpty() ) // set the filter to the last one used { From 7332dda0d8f72db037110b30c7e7b82624390185 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 4 Oct 2016 10:46:56 +0200 Subject: [PATCH 083/897] Remove visitor pattern from QgsExpression (#3569) It is not in use anywhere and can easily be reintroduced if there is a use case where it is an appropriate fit. Fix https://github.com/qgis/qgis3.0_api/issues/64 --- doc/api_break.dox | 1 + python/core/qgsexpression.sip | 45 --------------------------------- src/core/qgsexpression.cpp | 6 ----- src/core/qgsexpression.h | 47 ----------------------------------- 4 files changed, 1 insertion(+), 98 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 5b7e372b25e8..dc5ecb545f6b 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -709,6 +709,7 @@ version instead.

                                                                                                                                                                                  • replaceExpressionText() no longer accepts a substitution map parameter. Use expression context variables instead.
                                                                                                                                                                                  • helptext() has been renamed to helpText()
                                                                                                                                                                                  • isValid() has been renamed to checkExpression()
                                                                                                                                                                                  • +
                                                                                                                                                                                  • acceptVisitor() has been removed
                                                                                                                                                                                  • \subsection qgis_api_break_3_0_QgsFeature QgsFeature diff --git a/python/core/qgsexpression.sip b/python/core/qgsexpression.sip index 5000d37aee29..caa560ef0c9a 100644 --- a/python/core/qgsexpression.sip +++ b/python/core/qgsexpression.sip @@ -528,23 +528,6 @@ class QgsExpression * @return true if a geometry is required to evaluate this expression */ virtual bool needsGeometry() const = 0; - - /** - * Support the visitor pattern. - * - * For any implementation this should look like - * - * C++: - * - * v.visit( *this ); - * - * Python: - * - * v.visit( self) - * - * @param v A visitor that visits this node. - */ - virtual void accept( QgsExpression::Visitor& v ) const = 0; }; //! Named node @@ -615,7 +598,6 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; virtual QgsExpression::Node* clone() const; }; @@ -636,7 +618,6 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; virtual QgsExpression::Node* clone() const; int precedence() const; @@ -671,7 +652,6 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; virtual QgsExpression::Node* clone() const; }; @@ -692,7 +672,6 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; virtual QgsExpression::Node* clone() const; //! Tests whether the provided argument list is valid for the matching function @@ -715,7 +694,6 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; }; class NodeColumnRef : QgsExpression::Node @@ -734,7 +712,6 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; virtual QgsExpression::Node* clone() const; }; @@ -766,30 +743,8 @@ class QgsExpression virtual QStringList referencedColumns() const; virtual bool needsGeometry() const; - virtual void accept( QgsExpression::Visitor& v ) const; virtual QgsExpression::Node* clone() const; }; - - ////// - - /** Support for visitor pattern - algorithms dealing with the expressions - may be implemented without modifying the Node classes */ - class Visitor - { - public: - virtual ~Visitor(); - virtual void visit( const QgsExpression::NodeUnaryOperator& n ) = 0; - virtual void visit( const QgsExpression::NodeBinaryOperator& n ) = 0; - virtual void visit( const QgsExpression::NodeInOperator& n ) = 0; - virtual void visit( const QgsExpression::NodeFunction& n ) = 0; - virtual void visit( const QgsExpression::NodeLiteral& n ) = 0; - virtual void visit( const QgsExpression::NodeColumnRef& n ) = 0; - virtual void visit( const QgsExpression::NodeCondition& n ) = 0; - }; - - /** Entry function for the visitor pattern */ - void acceptVisitor( QgsExpression::Visitor& v ) const; - /** Returns the help text for a specified function. * @param name function name * @see variableHelpText() diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index a0fa137f6838..c8ac0939ce24 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3976,12 +3976,6 @@ void QgsExpression::setAreaUnits( QgsUnitTypes::AreaUnit unit ) d->mAreaUnit = unit; } -void QgsExpression::acceptVisitor( QgsExpression::Visitor& v ) const -{ - if ( d->mRootNode ) - d->mRootNode->accept( v ); -} - QString QgsExpression::replaceExpressionText( const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea ) { QString expr_action; diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index e295545d1270..663f3e47e884 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -715,8 +715,6 @@ class CORE_EXPORT QgsExpression ////// - class Visitor; // visitor interface is defined below - enum NodeType { ntUnaryOperator, @@ -794,23 +792,6 @@ class CORE_EXPORT QgsExpression * @return true if a geometry is required to evaluate this expression */ virtual bool needsGeometry() const = 0; - - /** - * Support the visitor pattern. - * - * For any implementation this should look like - * - * C++: - * - * v.visit( *this ); - * - * Python: - * - * v.visit( self) - * - * @param v A visitor that visits this node. - */ - virtual void accept( Visitor& v ) const = 0; }; //! Named node @@ -900,7 +881,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override { return mOperand->referencedColumns(); } virtual bool needsGeometry() const override { return mOperand->needsGeometry(); } - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; protected: @@ -931,7 +911,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override { return mOpLeft->referencedColumns() + mOpRight->referencedColumns(); } virtual bool needsGeometry() const override { return mOpLeft->needsGeometry() || mOpRight->needsGeometry(); } - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; int precedence() const; @@ -976,7 +955,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override { QStringList lst( mNode->referencedColumns() ); Q_FOREACH ( const Node* n, mList->list() ) lst.append( n->referencedColumns() ); return lst; } virtual bool needsGeometry() const override { bool needs = false; Q_FOREACH ( Node* n, mList->list() ) needs |= n->needsGeometry(); return needs; } - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; protected: @@ -1041,7 +1019,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override; virtual bool needsGeometry() const override { bool needs = Functions()[mFnIndex]->usesGeometry(); if ( mArgs ) { Q_FOREACH ( Node* n, mArgs->list() ) needs |= n->needsGeometry(); } return needs; } - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; //! Tests whether the provided argument list is valid for the matching function @@ -1143,7 +1120,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override { return QStringList(); } virtual bool needsGeometry() const override { return false; } - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; protected: @@ -1171,7 +1147,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override { return QStringList( mName ); } virtual bool needsGeometry() const override { return false; } - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; protected: @@ -1222,7 +1197,6 @@ class CORE_EXPORT QgsExpression virtual QStringList referencedColumns() const override; virtual bool needsGeometry() const override; - virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; protected: @@ -1230,27 +1204,6 @@ class CORE_EXPORT QgsExpression Node* mElseExp; }; - ////// - - /** \ingroup core - * Support for visitor pattern - algorithms dealing with the expressions - may be implemented without modifying the Node classes */ - class CORE_EXPORT Visitor - { - public: - virtual ~Visitor() {} - virtual void visit( const NodeUnaryOperator& n ) = 0; - virtual void visit( const NodeBinaryOperator& n ) = 0; - virtual void visit( const NodeInOperator& n ) = 0; - virtual void visit( const NodeFunction& n ) = 0; - virtual void visit( const NodeLiteral& n ) = 0; - virtual void visit( const NodeColumnRef& n ) = 0; - virtual void visit( const NodeCondition& n ) = 0; - }; - - /** Entry function for the visitor pattern */ - void acceptVisitor( Visitor& v ) const; - /** Returns the help text for a specified function. * @param name function name * @see variableHelpText() From 6764447ddddfad7aa3914242b903c40fb507b9d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Tue, 4 Oct 2016 15:18:41 +0200 Subject: [PATCH 084/897] rename test --- .../plugins/processing/tests/testdata/qgis_algorithm_tests.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 36fdf516375b..dc2dba4ea9b4 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -230,7 +230,7 @@ tests: # case 3 split polygon layer with lines - algorithm: qgis:splitwithlines - name: Split lines with same lines + name: Split polygons with lines params: INPUT_A: name: polys.gml From b47f03db332619fae408cf273b77a82c3068a39b Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 3 Oct 2016 14:28:10 +0200 Subject: [PATCH 085/897] Fix testqgsogcutils --- tests/src/core/testqgsogcutils.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/src/core/testqgsogcutils.cpp b/tests/src/core/testqgsogcutils.cpp index 4b4e621e0879..1371eeae8239 100644 --- a/tests/src/core/testqgsogcutils.cpp +++ b/tests/src/core/testqgsogcutils.cpp @@ -107,14 +107,14 @@ void TestQgsOgcUtils::testGeometryToGML() QVERIFY( !elemPoint.isNull() ); doc.appendChild( elemPoint ); - QCOMPARE( doc.toString( -1 ), QString( "111,222" ) ); + QCOMPARE( doc.toString( -1 ), QString( "111,222" ) ); doc.removeChild( elemPoint ); QDomElement elemLine = QgsOgcUtils::geometryToGML( &geomLine, doc ); QVERIFY( !elemLine.isNull() ); doc.appendChild( elemLine ); - QCOMPARE( doc.toString( -1 ), QString( "111,222 222,222" ) ); + QCOMPARE( doc.toString( -1 ), QString( "111,222 222,222" ) ); doc.removeChild( elemLine ); // Test GML3 @@ -359,7 +359,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" "geometry" - "5,6 5,6" + "5,6 5,6" "" "" ); @@ -367,7 +367,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" "geometry" - "5,6" + "5,6" "" "" ); @@ -375,7 +375,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" "geometry" - "5,6" + "5,6" "" "" ); } @@ -726,7 +726,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" "geom" - "5,6" + "5,6" "" "" ); @@ -735,7 +735,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" "geom" - "5,6" + "5,6" "" "" ); From 1d6e5d28e6951df4e5fef9e0927e036e237c0b2b Mon Sep 17 00:00:00 2001 From: rldhont Date: Fri, 30 Sep 2016 16:40:15 +0200 Subject: [PATCH 086/897] [BUGFIX] Support OGC PropertyIsLike attributs The OGC PropertyIsLike element can have 4 attributs: * matchCase to specify LIKE or ILIKE * wildCard to specify a wildcard char symbol * signleChar to specify a single char symbol * escape to specify an escape char symbol --- src/core/qgsogcutils.cpp | 85 +++++++++++++++++++++++++++--- tests/src/core/testqgsogcutils.cpp | 48 ++++++++++++++++- 2 files changed, 123 insertions(+), 10 deletions(-) diff --git a/src/core/qgsogcutils.cpp b/src/core/qgsogcutils.cpp index bd4a25846523..693cae80ae08 100644 --- a/src/core/qgsogcutils.cpp +++ b/src/core/qgsogcutils.cpp @@ -1666,6 +1666,10 @@ static int binaryOperatorFromTagName( const QString& tagName ) static QString binaryOperatorToTagName( QgsExpression::BinaryOperator op ) { + if ( op == QgsExpression::boILike ) + { + return "PropertyIsLike"; + } return binaryOperatorsTagNamesMap().key( op, QString() ); } @@ -1752,6 +1756,11 @@ QgsExpression::NodeBinaryOperator* QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( return nullptr; } + if ( op == QgsExpression::boLike && element.hasAttribute( "matchCase" ) && element.attribute( "matchCase" ) == "false" ) + { + op = QgsExpression::boILike; + } + QDomElement operandElem = element.firstChildElement(); QgsExpression::Node *expr = nodeFromOgcFilter( operandElem, errorMessage ), *leftOp = expr; if ( !expr ) @@ -1772,6 +1781,64 @@ QgsExpression::NodeBinaryOperator* QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( return nullptr; } + if ( op == QgsExpression::boLike || op == QgsExpression::boILike ) + { + QString wildCard; + if ( element.hasAttribute( "wildCard" ) ) + { + wildCard = element.attribute( "wildCard" ); + } + QString singleChar; + if ( element.hasAttribute( "singleChar" ) ) + { + singleChar = element.attribute( "singleChar" ); + } + QString escape = "\\"; + if ( element.hasAttribute( "escape" ) ) + { + escape = element.attribute( "escape" ); + } + // replace + QString oprValue = static_cast( opRight )->value().toString(); + if ( !wildCard.isEmpty() && wildCard != "%" ) + { + oprValue.replace( '%', "\\%" ); + if ( oprValue.startsWith( wildCard ) ) + { + oprValue.replace( 0, 1, "%" ); + } + QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( wildCard ) + ")" ); + int pos = 0; + while (( pos = rx.indexIn( oprValue, pos ) ) != -1 ) + { + oprValue.replace( pos + 1, 1, "%" ); + pos += 1; + } + oprValue.replace( escape + wildCard, wildCard ); + } + if ( !singleChar.isEmpty() && singleChar != "_" ) + { + oprValue.replace( '_', "\\_" ); + if ( oprValue.startsWith( singleChar ) ) + { + oprValue.replace( 0, 1, "_" ); + } + QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( singleChar ) + ")" ); + int pos = 0; + while (( pos = rx.indexIn( oprValue, pos ) ) != -1 ) + { + oprValue.replace( pos + 1, 1, "_" ); + pos += 1; + } + oprValue.replace( escape + singleChar, singleChar ); + } + if ( !escape.isEmpty() && escape != "\\" ) + { + oprValue.replace( escape + escape, escape ); + } + opRight = new QgsExpression::NodeLiteral( oprValue ); + } + expr = new QgsExpression::NodeBinaryOperator( static_cast< QgsExpression::BinaryOperator >( op ), expr, opRight ); } @@ -2289,13 +2356,13 @@ QDomElement QgsOgcUtilsExprToFilter::expressionBinaryOperatorToOgcFilter( const if ( op == QgsExpression::boILike ) boElem.setAttribute( "matchCase", "false" ); - // setup wildcards to + // setup wildCards to boElem.setAttribute( "wildCard", "%" ); - boElem.setAttribute( "singleChar", "?" ); + boElem.setAttribute( "singleChar", "_" ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) - boElem.setAttribute( "escape", "!" ); + boElem.setAttribute( "escape", "\\" ); else - boElem.setAttribute( "escapeChar", "!" ); + boElem.setAttribute( "escapeChar", "\\" ); } boElem.appendChild( leftElem ); @@ -2712,6 +2779,8 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: opText = "PropertyIsGreaterThan"; else if ( op == QgsSQLStatement::boLike ) opText = "PropertyIsLike"; + else if ( op == QgsSQLStatement::boILike ) + opText = "PropertyIsLike"; if ( opText.isEmpty() ) { @@ -2727,13 +2796,13 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: if ( op == QgsSQLStatement::boILike ) boElem.setAttribute( "matchCase", "false" ); - // setup wildcards to + // setup wildCards to boElem.setAttribute( "wildCard", "%" ); - boElem.setAttribute( "singleChar", "?" ); + boElem.setAttribute( "singleChar", "_" ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) - boElem.setAttribute( "escape", "!" ); + boElem.setAttribute( "escape", "\\" ); else - boElem.setAttribute( "escapeChar", "!" ); + boElem.setAttribute( "escapeChar", "\\" ); } boElem.appendChild( leftElem ); diff --git a/tests/src/core/testqgsogcutils.cpp b/tests/src/core/testqgsogcutils.cpp index 1371eeae8239..dd0d510963f2 100644 --- a/tests/src/core/testqgsogcutils.cpp +++ b/tests/src/core/testqgsogcutils.cpp @@ -180,13 +180,41 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "" ) << QString( "POPULATION >= 100 AND POPULATION <= 200" ); - // TODO: needs to handle different wildcards, single chars, escape chars + // handle different wildcards, single chars, escape chars QTest::newRow( "like" ) << QString( "" - "" + "" "NAME*QGIS*" "" ) << QString( "NAME LIKE '*QGIS*'" ); + QTest::newRow( "ilike" ) << QString( + "" + "" + "NAME*QGIS*" + "" ) + << QString( "NAME ILIKE '*QGIS*'" ); + + // different wildCards + QTest::newRow( "like wildCard" ) << QString( + "" + "" + "NAME*%QGIS*\\*" + "" ) + << QString( "NAME LIKE '%\\\\%QGIS%*'" ); + // different single chars + QTest::newRow( "like single char" ) << QString( + "" + "" + "NAME._QGIS.\\." + "" ) + << QString( "NAME LIKE '_\\\\_QGIS_.'" ); + // different single chars + QTest::newRow( "like escape char" ) << QString( + "" + "" + "NAME_QGIS.!.!!%QGIS*!*" + "" ) + << QString( "NAME LIKE '\\\\_QGIS_.!\\\\%QGIS%*'" ); QTest::newRow( "is null" ) << QString( "" @@ -301,6 +329,22 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); + QTest::newRow( "like" ) << QString( "NAME LIKE '*QGIS*'" ) << QString( + "" + "" + "NAME" + "*QGIS*" + "" + "" ); + + QTest::newRow( "ilike" ) << QString( "NAME ILIKE '*QGIS*'" ) << QString( + "" + "" + "NAME" + "*QGIS*" + "" + "" ); + QTest::newRow( "is null" ) << QString( "A IS NULL" ) << QString( "" "" From 52a78def7f81eebc4b067048043dc27df3f1549c Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 4 Oct 2016 11:40:55 +0200 Subject: [PATCH 087/897] Reactivate ogcutils tests and update its --- ci/travis/linux/script.sh | 2 +- tests/src/core/testqgsogcutils.cpp | 172 +++++++++++++++++++++++------ 2 files changed, 141 insertions(+), 33 deletions(-) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 0ab8c4c1b41f..d7e680ea9c70 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -21,5 +21,5 @@ export CCACHE_TEMPDIR=/tmp DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|qgis_ogcutilstest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure diff --git a/tests/src/core/testqgsogcutils.cpp b/tests/src/core/testqgsogcutils.cpp index dd0d510963f2..9fd87c395caf 100644 --- a/tests/src/core/testqgsogcutils.cpp +++ b/tests/src/core/testqgsogcutils.cpp @@ -93,12 +93,126 @@ void TestQgsOgcUtils::testGeometryFromGML() QVERIFY( geomBox.wkbType() == QgsWkbTypes::Polygon ); } +static bool compareElements( QDomElement& element1, QDomElement& element2 ) +{ + QString tag1 = element1.tagName(); + tag1.replace( QRegExp( ".*:" ), "" ); + QString tag2 = element2.tagName(); + tag2.replace( QRegExp( ".*:" ), "" ); + if ( tag1 != tag2 ) + { + qDebug( "Different tag names: %s, %s", tag1.toAscii().data(), tag2.toAscii().data() ); + return false ; + } + + if ( element1.hasAttributes() != element2.hasAttributes() ) + { + qDebug( "Different hasAttributes: %s, %s", tag1.toAscii().data(), tag2.toAscii().data() ); + return false; + } + + if ( element1.hasAttributes() ) + { + QDomNamedNodeMap attrs1 = element1.attributes(); + QDomNamedNodeMap attrs2 = element2.attributes(); + + if ( attrs1.size() != attrs2.size() ) + { + qDebug( "Different attributes size: %s, %s", tag1.toAscii().data(), tag2.toAscii().data() ); + return false; + } + + for ( int i = 0 ; i < attrs1.size() ; ++i ) + { + QDomNode node1 = attrs1.item( i ); + QDomAttr attr1 = node1.toAttr(); + + if ( !element2.hasAttribute( attr1.name() ) ) + { + qDebug( "Element2 has not attribute: %s, %s, %s", tag1.toAscii().data(), tag2.toAscii().data(), attr1.name().toAscii().data() ); + return false; + } + + if ( element2.attribute( attr1.name() ) != attr1.value() ) + { + qDebug( "Element2 attribute has not the same value: %s, %s, %s", tag1.toAscii().data(), tag2.toAscii().data(), attr1.name().toAscii().data() ); + return false; + } + } + } + + if ( element1.hasChildNodes() != element2.hasChildNodes() ) + { + qDebug( "Different childNodes: %s, %s", tag1.toAscii().data(), tag2.toAscii().data() ); + return false; + } + + if ( element1.hasChildNodes() ) + { + QDomNodeList nodes1 = element1.childNodes(); + QDomNodeList nodes2 = element2.childNodes(); + + if ( nodes1.size() != nodes2.size() ) + { + qDebug( "Different childNodes size: %s, %s", tag1.toAscii().data(), tag2.toAscii().data() ); + return false; + } + + for ( int i = 0 ; i < nodes1.size() ; ++i ) + { + QDomNode node1 = nodes1.at( i ); + QDomNode node2 = nodes2.at( i ); + if ( node1.isElement() && node2.isElement() ) + { + QDomElement elt1 = node1.toElement(); + QDomElement elt2 = node2.toElement(); + + if ( !compareElements( elt1, elt2 ) ) + return false; + } + else if ( node1.isText() && node2.isText() ) + { + QDomText txt1 = node1.toText(); + QDomText txt2 = node2.toText(); + + if ( txt1.data() != txt2.data() ) + { + qDebug( "Different text data: %s %s", tag1.toAscii().data(), txt1.data().toAscii().data() ); + qDebug( "Different text data: %s %s", tag2.toAscii().data(), txt2.data().toAscii().data() ); + return false; + } + } + } + } + + if ( element1.text() != element2.text() ) + { + qDebug( "Different text: %s %s", tag1.toAscii().data(), element1.text().toAscii().data() ); + qDebug( "Different text: %s %s", tag2.toAscii().data(), element2.text().toAscii().data() ); + return false; + } + + return true; +} +static QDomElement comparableElement( const QString& xmlText ) +{ + QDomDocument doc; + if ( !doc.setContent( xmlText ) ) + return QDomElement(); + return doc.documentElement(); +} + + void TestQgsOgcUtils::testGeometryToGML() { QDomDocument doc; QgsGeometry geomPoint( QgsGeometry::fromPoint( QgsPoint( 111, 222 ) ) ); QgsGeometry geomLine( QgsGeometry::fromWkt( "LINESTRING(111 222, 222 222)" ) ); + // Elements to compare + QDomElement xmlElem; + QDomElement ogcElem; + // Test GML2 QDomElement elemInvalid = QgsOgcUtils::geometryToGML( 0, doc ); QVERIFY( elemInvalid.isNull() ); @@ -107,14 +221,18 @@ void TestQgsOgcUtils::testGeometryToGML() QVERIFY( !elemPoint.isNull() ); doc.appendChild( elemPoint ); - QCOMPARE( doc.toString( -1 ), QString( "111,222" ) ); + xmlElem = comparableElement( QString( "111,222" ) ); + ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemPoint ); QDomElement elemLine = QgsOgcUtils::geometryToGML( &geomLine, doc ); QVERIFY( !elemLine.isNull() ); doc.appendChild( elemLine ); - QCOMPARE( doc.toString( -1 ), QString( "111,222 222,222" ) ); + xmlElem = comparableElement( QString( "111,222 222,222" ) ); + ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemLine ); // Test GML3 @@ -125,14 +243,18 @@ void TestQgsOgcUtils::testGeometryToGML() QVERIFY( !elemPoint.isNull() ); doc.appendChild( elemPoint ); - QCOMPARE( doc.toString( -1 ), QString( "111 222" ) ); + xmlElem = comparableElement( QString( "111 222" ) ); + ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemPoint ); elemLine = QgsOgcUtils::geometryToGML( &geomLine, doc, "GML3" ); QVERIFY( !elemLine.isNull() ); doc.appendChild( elemLine ); - QCOMPARE( doc.toString( -1 ), QString( "111 222 222 222" ) ); + xmlElem = comparableElement( QString( "111 222 222 222" ) ); + ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemLine ); } @@ -287,7 +409,10 @@ void TestQgsOgcUtils::testExpressionToOgcFilter() qDebug( "EXPR: %s", exp.expression().toAscii().data() ); qDebug( "OGC : %s", doc.toString( -1 ).toAscii().data() ); - QCOMPARE( xmlText, doc.toString( -1 ) ); + + QDomElement xmlElem = comparableElement( xmlText ); + QDomElement ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); } void TestQgsOgcUtils::testExpressionToOgcFilter_data() @@ -449,7 +574,10 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS11() qDebug( "SRSNAME: %s", srsName.toAscii().data() ); qDebug( "OGC : %s", doc.toString( -1 ).toAscii().data() ); - QCOMPARE( xmlText, doc.toString( -1 ) ); + + QDomElement xmlElem = comparableElement( xmlText ); + QDomElement ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); } void TestQgsOgcUtils::testExpressionToOgcFilterWFS11_data() @@ -473,14 +601,6 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS11_data() "" ); } -static QString normalizeXML( const QString& xmlText ) -{ - QDomDocument doc; - if ( !doc.setContent( xmlText, true ) ) - return QString(); - return doc.toString( -1 ); -} - void TestQgsOgcUtils::testExpressionToOgcFilterWFS20() { QFETCH( QString, exprText ); @@ -506,15 +626,9 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS20() qDebug( "SRSNAME: %s", srsName.toAscii().data() ); qDebug( "OGC : %s", doc.toString( -1 ).toAscii().data() ); - QString normalizedExpected( normalizeXML( xmlText ) ); - QString normalizedGot( normalizeXML( doc.toString( -1 ) ) ); - - if ( normalizedExpected != normalizedGot ) - { - qDebug( "Normalized expected: %s", normalizedExpected.toAscii().data() ); - qDebug( "Normalized got: %s", normalizedGot.toAscii().data() ); - } - QCOMPARE( normalizedExpected, normalizedGot ); + QDomElement xmlElem = comparableElement( xmlText ); + QDomElement ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); } void TestQgsOgcUtils::testExpressionToOgcFilterWFS20_data() @@ -614,15 +728,9 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter() filterVersion == QgsOgcUtils::FILTER_FES_2_0 ? "FES 2.0" : "unknown" ); qDebug( "OGC : %s", doc.toString( -1 ).toAscii().data() ); - QString normalizedExpected( normalizeXML( xmlText ) ); - QString normalizedGot( normalizeXML( doc.toString( -1 ) ) ); - - if ( normalizedExpected != normalizedGot ) - { - qDebug( "Normalized expected: %s", normalizedExpected.toAscii().data() ); - qDebug( "Normalized got: %s", normalizedGot.toAscii().data() ); - } - QCOMPARE( normalizedExpected, normalizedGot ); + QDomElement xmlElem = comparableElement( xmlText ); + QDomElement ogcElem = comparableElement( doc.toString( -1 ) ); + QVERIFY( compareElements( xmlElem, ogcElem ) ); } void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() From d03d2069b96b2c25abe64588f54f24dab7ea7cc2 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 4 Oct 2016 17:06:06 +0300 Subject: [PATCH 088/897] [processing] correct GRASS 7 detection on Mac (fix #15645) follow up e1ff6e896a --- python/plugins/processing/algs/grass7/Grass7Utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/grass7/Grass7Utils.py b/python/plugins/processing/algs/grass7/Grass7Utils.py index 30c1553f622a..40f7676d0b96 100644 --- a/python/plugins/processing/algs/grass7/Grass7Utils.py +++ b/python/plugins/processing/algs/grass7/Grass7Utils.py @@ -244,8 +244,8 @@ def prepareGrass7Execution(commands): Grass7Utils.createGrass7BatchJobFileFromGrass7Commands(commands) os.chmod(Grass7Utils.grassBatchJobFilename(), stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE) - if isMac() and os.path.exists(os.path.join(Grass7Utils.grassPath(), '*grass.sh*')): - command = os.path.join(Grass7Utils.grassPath(), '*grass.sh*') + ' ' \ + if isMac() and os.path.exists(os.path.join(Grass7Utils.grassPath(), 'grass.sh')): + command = os.path.join(Grass7Utils.grassPath(), 'grass.sh') + ' ' \ + os.path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT') else: command = 'grass70 ' + os.path.join(Grass7Utils.grassMapsetFolder(), 'PERMANENT') From cc62c5226951c813a4c3a61744b51827aa5d3afa Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 4 Oct 2016 19:53:21 +0300 Subject: [PATCH 089/897] [processing] add icon caching for other providers --- python/plugins/processing/algs/gdal/GdalAlgorithm.py | 8 +++++++- python/plugins/processing/algs/otb/OTBAlgorithm.py | 5 ++++- python/plugins/processing/algs/r/RAlgorithm.py | 8 +++++++- python/plugins/processing/algs/saga/SagaAlgorithm212.py | 5 ++++- python/plugins/processing/algs/taudem/TauDEMAlgorithm.py | 5 ++++- 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/algs/gdal/GdalAlgorithm.py b/python/plugins/processing/algs/gdal/GdalAlgorithm.py index 8dc4310019f1..5cbcad690e07 100644 --- a/python/plugins/processing/algs/gdal/GdalAlgorithm.py +++ b/python/plugins/processing/algs/gdal/GdalAlgorithm.py @@ -41,8 +41,14 @@ class GdalAlgorithm(GeoAlgorithm): + def __init__(self): + GeoAlgorithm.__init__(self) + self._icon = None + def getIcon(self): - return QIcon(os.path.join(pluginPath, 'images', 'gdal.svg')) + if self._icon is None: + self._icon = QIcon(os.path.join(pluginPath, 'images', 'gdal.svg')) + return self._icon def getCustomParametersDialog(self): return GdalAlgorithmDialog(self) diff --git a/python/plugins/processing/algs/otb/OTBAlgorithm.py b/python/plugins/processing/algs/otb/OTBAlgorithm.py index dd9c484f1ccc..65d473e8ed82 100644 --- a/python/plugins/processing/algs/otb/OTBAlgorithm.py +++ b/python/plugins/processing/algs/otb/OTBAlgorithm.py @@ -67,6 +67,7 @@ def __init__(self, descriptionfile): self.defineCharacteristicsFromFile() self.numExportedLayers = 0 self.hasROI = None + self._icon = None def __str__(self): return("Algo : " + self.name + " from app : " + self.cliName + " in : " + self.group) @@ -77,7 +78,9 @@ def getCopy(self): return newone def getIcon(self): - return QIcon(os.path.join(pluginPath, 'images', 'otb.png')) + if self._icon is None: + self._icon = QIcon(os.path.join(pluginPath, 'images', 'otb.png')) + return self._icon def help(self): version = OTBUtils.getInstalledVersion() diff --git a/python/plugins/processing/algs/r/RAlgorithm.py b/python/plugins/processing/algs/r/RAlgorithm.py index a1b3fee7019e..d9a921e2c33b 100644 --- a/python/plugins/processing/algs/r/RAlgorithm.py +++ b/python/plugins/processing/algs/r/RAlgorithm.py @@ -61,6 +61,9 @@ from processing.script.WrongScriptException import WrongScriptException from .RUtils import RUtils +pluginPath = os.path.normpath(os.path.join( + os.path.split(os.path.dirname(__file__))[0], os.pardir)) + class RAlgorithm(GeoAlgorithm): @@ -80,9 +83,12 @@ def __init__(self, descriptionFile, script=None): self.defineCharacteristicsFromScript() if descriptionFile is not None: self.defineCharacteristicsFromFile() + self._icon = None def getIcon(self): - return QIcon(os.path.dirname(__file__) + '/../../images/r.svg') + if self._icon is None: + self._icon = QIcon(os.path.join(pluginPath, 'images', 'r.svg')) + return self._icon def defineCharacteristicsFromScript(self): lines = self.script.split('\n') diff --git a/python/plugins/processing/algs/saga/SagaAlgorithm212.py b/python/plugins/processing/algs/saga/SagaAlgorithm212.py index 683494d5bacb..dc5907b68329 100644 --- a/python/plugins/processing/algs/saga/SagaAlgorithm212.py +++ b/python/plugins/processing/algs/saga/SagaAlgorithm212.py @@ -72,6 +72,7 @@ def __init__(self, descriptionfile): self.allowUnmatchingGridExtents = False self.descriptionFile = descriptionfile self.defineCharacteristicsFromFile() + self._icon = None def getCopy(self): newone = SagaAlgorithm212(self.descriptionFile) @@ -79,7 +80,9 @@ def getCopy(self): return newone def getIcon(self): - return QIcon(os.path.join(pluginPath, 'images', 'saga.png')) + if self._icon is None: + self._icon = QIcon(os.path.join(pluginPath, 'images', 'saga.png')) + return self._icon def defineCharacteristicsFromFile(self): lines = open(self.descriptionFile) diff --git a/python/plugins/processing/algs/taudem/TauDEMAlgorithm.py b/python/plugins/processing/algs/taudem/TauDEMAlgorithm.py index ac048230d63f..5cd4622900ee 100644 --- a/python/plugins/processing/algs/taudem/TauDEMAlgorithm.py +++ b/python/plugins/processing/algs/taudem/TauDEMAlgorithm.py @@ -59,6 +59,7 @@ def __init__(self, descriptionfile): GeoAlgorithm.__init__(self) self.descriptionFile = descriptionfile self.defineCharacteristicsFromFile() + self._icon = None def getCopy(self): newone = TauDEMAlgorithm(self.descriptionFile) @@ -66,7 +67,9 @@ def getCopy(self): return newone def getIcon(self): - return QIcon(os.path.join(pluginPath, 'images', 'taudem.svg')) + if self._icon is None: + self._icon = QIcon(os.path.join(pluginPath, 'images', 'taudem.svg')) + return self._icon def defineCharacteristicsFromFile(self): with codecs.open(self.descriptionFile, encoding='utf-8') as f: From 03bff507d9814ec1a3d9fdfdbe5cfbc5b6274689 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 10:40:29 +1000 Subject: [PATCH 090/897] Fix measure dialog shows wrong results when changing units If the measurement was not finished (ie right click occurred) then the last length would be missing from the table Fix #15433 --- src/app/qgsmeasuredialog.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/app/qgsmeasuredialog.cpp b/src/app/qgsmeasuredialog.cpp index fa0144e5c1fa..8cd70d31c5be 100644 --- a/src/app/qgsmeasuredialog.cpp +++ b/src/app/qgsmeasuredialog.cpp @@ -112,6 +112,13 @@ void QgsMeasureDialog::unitsChanged( int index ) mTable->clear(); mTotal = 0.; updateUi(); + + if ( !mTool->done() ) + { + // re-add temporary mouse cursor position + addPoint( mLastMousePoint ); + mouseMove( mLastMousePoint ); + } } void QgsMeasureDialog::restart() From bad137283b7d22ab2f7bf889bc72b1088efaa742 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 10:52:14 +1000 Subject: [PATCH 091/897] Fix last segment length in measure dialog is incorrect after completing measurement with right mouse click --- src/app/qgsmeasuredialog.cpp | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/app/qgsmeasuredialog.cpp b/src/app/qgsmeasuredialog.cpp index 8cd70d31c5be..3668457d8b6f 100644 --- a/src/app/qgsmeasuredialog.cpp +++ b/src/app/qgsmeasuredialog.cpp @@ -213,16 +213,24 @@ void QgsMeasureDialog::removeLastPoint() //remove final row delete mTable->takeTopLevelItem( mTable->topLevelItemCount() - 1 ); - QgsPoint p1( mTool->points().last() ); - double d = mDa.measureLine( p1, mLastMousePoint ); - mTotal = mDa.measureLine( mTool->points() ); - editTotal->setText( formatDistance( mTotal + d ) ); - d = convertLength( d, mDistanceUnits ); + if ( !mTool->done() ) + { + // need to add the distance for the temporary mouse cursor point + QgsPoint p1( mTool->points().last() ); + double d = mDa.measureLine( p1, mLastMousePoint ); - QTreeWidgetItem *item = mTable->topLevelItem( mTable->topLevelItemCount() - 1 ); - item->setText( 0, QLocale::system().toString( d, 'f', mDecimalPlaces ) ); + d = convertLength( d, mDistanceUnits ); + + QTreeWidgetItem *item = mTable->topLevelItem( mTable->topLevelItemCount() - 1 ); + item->setText( 0, QLocale::system().toString( d, 'f', mDecimalPlaces ) ); + editTotal->setText( formatDistance( mTotal + d ) ); + } + else + { + editTotal->setText( formatDistance( mTotal ) ); + } } } From ddbd25d046ad514719b41c5f61f3c7fe34304a74 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 3 Oct 2016 12:31:20 +1000 Subject: [PATCH 092/897] Correctly emit panelAccepted when panel is not in dock mode Fixes #15373 - refine current rule not working when symbol widgets are not used in the style dock This fixes a behavioural difference when new panels are opened in a QgsPanelWidget when in docked/undocked mode. When in docked mode, the newly opened panel will emit panelAccepted when it is accepted. But for undocked mode, the parent panel was emitting the panelAccepted signal and so the connection to update the renderer was never triggered. Now both docked/undocked panels will always emit panelAccepted ONLY from the newly opened panel itself. This also fixes memory leaks as the clean up code was never run in undocked mode. I've updated the docs to clarify this behaviour. --- python/gui/qgspanelwidget.sip | 3 +++ src/gui/qgspanelwidget.cpp | 2 +- src/gui/qgspanelwidget.h | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/python/gui/qgspanelwidget.sip b/python/gui/qgspanelwidget.sip index ce45698b24fb..d019ab452754 100644 --- a/python/gui/qgspanelwidget.sip +++ b/python/gui/qgspanelwidget.sip @@ -89,6 +89,9 @@ class QgsPanelWidget : public QWidget * @param panel The panel widget that was accepted. * @note This argument is normally raised with emit panelAccepted(this) * so that callers can retrive the widget easier in calling code. + * @note this is emitted only when this panel is accepted, and is not emitted for + * child panels. Eg, if this panel opens a second stacked panel, then this panel + * will not emit panelAccepted when the second panel is accepted. */ void panelAccepted( QgsPanelWidget* panel ); diff --git a/src/gui/qgspanelwidget.cpp b/src/gui/qgspanelwidget.cpp index 53f593afc5d0..76fb67a16de1 100644 --- a/src/gui/qgspanelwidget.cpp +++ b/src/gui/qgspanelwidget.cpp @@ -84,7 +84,7 @@ void QgsPanelWidget::openPanel( QgsPanelWidget* panel ) dlg->layout()->addWidget( buttonBox ); dlg->exec(); settings.setValue( key, dlg->saveGeometry() ); - emit panelAccepted( panel ); + panel->acceptPanel(); } } diff --git a/src/gui/qgspanelwidget.h b/src/gui/qgspanelwidget.h index c45c4e0c658c..63bb2065af97 100644 --- a/src/gui/qgspanelwidget.h +++ b/src/gui/qgspanelwidget.h @@ -108,6 +108,9 @@ class GUI_EXPORT QgsPanelWidget : public QWidget * @param panel The panel widget that was accepted. * @note This argument is normally raised with emit panelAccepted(this) * so that callers can retrive the widget easier in calling code. + * @note this is emitted only when this panel is accepted, and is not emitted for + * child panels. Eg, if this panel opens a second stacked panel, then this panel + * will not emit panelAccepted when the second panel is accepted. */ void panelAccepted( QgsPanelWidget* panel ); From bc32b1fe5a9ac05f1763f45268eab833cc46e546 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 13:16:14 +1000 Subject: [PATCH 093/897] Fix crash when validating geometry (fix #15660) Also fix python bindings for QgsGeometryValidator --- python/core/qgsgeometryvalidator.sip | 2 +- src/core/qgsgeometryvalidator.cpp | 24 ++++++- tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgsgeometryvalidator.py | 71 +++++++++++++++++++ 4 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 tests/src/python/test_qgsgeometryvalidator.py diff --git a/python/core/qgsgeometryvalidator.sip b/python/core/qgsgeometryvalidator.sip index 4e8c04ab2470..9496a0eddb78 100644 --- a/python/core/qgsgeometryvalidator.sip +++ b/python/core/qgsgeometryvalidator.sip @@ -13,7 +13,7 @@ class QgsGeometryValidator : QThread void stop(); /** Validate geometry and produce a list of geometry errors */ - static void validateGeometry( const QgsGeometry *g, QList &errors ); + static void validateGeometry( const QgsGeometry *g, QList &errors /Out/ ); signals: void errorFound( const QgsGeometry::Error& ); diff --git a/src/core/qgsgeometryvalidator.cpp b/src/core/qgsgeometryvalidator.cpp index e68b87488ae6..a6b8e77abbbc 100644 --- a/src/core/qgsgeometryvalidator.cpp +++ b/src/core/qgsgeometryvalidator.cpp @@ -147,11 +147,31 @@ void QgsGeometryValidator::validatePolyline( int i, QgsPolyline line, bool ring if ( !intersectLines( line[j], v, line[k], w, s ) ) continue; - double d = -distLine2Point( line[j], v.perpVector(), s ); + double d = 0.0; + try + { + d = -distLine2Point( line[j], v.perpVector(), s ); + } + catch ( QgsException & e ) + { + Q_UNUSED( e ); + QgsDebugMsg( "Error validating: " + e.what() ); + continue; + } if ( d < 0 || d > vl ) continue; - d = -distLine2Point( line[k], w.perpVector(), s ); + try + { + d = -distLine2Point( line[k], w.perpVector(), s ); + } + catch ( QgsException & e ) + { + Q_UNUSED( e ); + QgsDebugMsg( "Error validating: " + e.what() ); + continue; + } + if ( d <= 0 || d >= w.length() ) continue; diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 1c7a12dd01f1..c02fd02e36c1 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -51,6 +51,7 @@ ADD_PYTHON_TEST(PyQgsFontUtils test_qgsfontutils.py) ADD_PYTHON_TEST(PyQgsGeometryAvoidIntersections test_qgsgeometry_avoid_intersections.py) ADD_PYTHON_TEST(PyQgsGeometryGeneratorSymbolLayer test_qgsgeometrygeneratorsymbollayer.py) ADD_PYTHON_TEST(PyQgsGeometryTest test_qgsgeometry.py) +ADD_PYTHON_TEST(PyQgsGeometryValidator test_qgsgeometryvalidator.py) ADD_PYTHON_TEST(PyQgsGraduatedSymbolRenderer test_qgsgraduatedsymbolrenderer.py) ADD_PYTHON_TEST(PyQgsInterval test_qgsinterval.py) ADD_PYTHON_TEST(PyQgsJSONUtils test_qgsjsonutils.py) diff --git a/tests/src/python/test_qgsgeometryvalidator.py b/tests/src/python/test_qgsgeometryvalidator.py new file mode 100644 index 000000000000..661817ff65fd --- /dev/null +++ b/tests/src/python/test_qgsgeometryvalidator.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsGeometryValidator. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '03/10/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import os +import csv +import math + +from qgis.core import ( + QgsGeometry, + QgsGeometryValidator +) + +from qgis.testing import ( + unittest +) + + +class TestQgsGeometryValidator(unittest.TestCase): + + def testIssue15660(self): + """ Test crash when validating geometry (#15660) """ + g = QgsGeometry.fromWkt( + "Polygon ((0.44256348235389709 -47.87645625696347906, -2.88231630340906797 -47.90003919913998232," + "-2.88589842578005751 -48.91215450743293047, -2.8858984257800584 -48.91215450743293047," + "-2.88589842578005751 -48.91215450743292337, -2.88589842632776516 -48.9121545074024624," + "-3.24858148608664266 -48.89198543875494352, -3.27689849271356159 -49.40119850743292318," + "-4.37689842578006072 -49.40119850743292318, -4.3768984257800625 -49.40119850743293739," + "-6.11689842578005738 -49.40119850743293739, -6.11689842578006093 -49.40119850743292318," + "-7.03689842578006086 -49.40119850743292318, -7.02239489567359776 -48.93302358132471852," + "-7.02177188091450688 -48.91291272055079276, -7.02177188393206286 -48.91291272045731375," + "-7.02141642578006309 -48.9014385074329212, -7.7002102410998674 -48.88041051649613422," + "-7.70077301577442341 -48.89187793078160382, -7.70077301577442341 -48.89187793078160382," + "-7.70233865095334291 -48.92378019651650334, -7.72576842578006051 -49.40119850743292318," + "-9.26576842578005966 -49.40119850743292318, -9.26576842578006321 -49.40119850743293739," + "-13.28076842578006023 -49.40119850743293739, -13.04700849136197149 -44.82717853953759857," + "-12.22739168108193297 -44.85224022031006541, -12.22501286465108805 -44.774446133668377," + "-12.22288921611744783 -44.774511069530881, -12.2155540445085915 -44.53462318893357264," + "-13.0310217329353506 -44.50968822589503304, -12.87640859053235687 -41.29089836691012749," + "-7.83390711693117936 -41.74840291007100745, -7.88211379129075596 -42.99075321817508666," + "-7.43245210877673657 -43.00820115628285123, -7.50410812906098013 -44.67868742523263847," + "-7.52086717830689011 -44.67817497540850979, -7.52820234991574644 -44.91806285600581816," + "-7.51439432253991058 -44.91848507095944854, -7.57421591980290287 -46.3130804785479242," + "-8.32385639731993621 -46.28985691678211367, -8.44985043007881842 -48.85718773355701217," + "-6.26478736265246283 -48.92487774800262912, -6.18500945357052245 -46.35611749220839073," + "-6.94163842159974198 -46.33267751510010157, -6.82382190915497944 -40.77447960826383166," + "-5.48772831582523146 -40.77837853452808758, -5.48973219643841759 -39.92687558952010107," + "-2.75658441771447116 -40.04490036239724304, -3.1241861109063862 -46.6551270968877958," + "-2.78977790434136885 -46.6737244011090695, -2.78977790434136796 -46.6737244011090695," + "-2.71083842578005996 -44.83541850743291945, -2.71083842578005729 -44.83541850743291945," + "-0.86779302740823816 -44.89143693883772812, -0.86745855610774569 -44.87743669555854353," + "0.29843811058281489 -44.90401226269042922, 0.20437651721061911 -46.69301920907949466," + "0.50389019278376956 -46.71008040893148916, 0.44256348235389709 -47.87645625696347906))") + + self.assertTrue(g) + # make sure validating this geometry doesn't crash QGIS + QgsGeometryValidator.validateGeometry(g) + + +if __name__ == '__main__': + unittest.main() From 1e0e9c2e9549fd77e93b3c93597d3716708ce5d1 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 4 Jul 2016 15:33:17 +0700 Subject: [PATCH 094/897] [pseudocolor renderer] fix invert check box in continous mode (fixes #15209) --- .../qgssinglebandpseudocolorrendererwidget.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp index 9ca7402848b7..dac7fb27bca5 100644 --- a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp +++ b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp @@ -369,14 +369,23 @@ void QgsSingleBandPseudoColorRendererWidget::on_mClassifyButton_clicked() { for ( int i = 0; i < numberOfEntries; ++i ) { - double value = colorRamp->value( i ); - entryValues.push_back( min + value * ( max - min ) ); + if ( mInvertCheckBox->isChecked() ) + { + double value = 1.0 - colorRamp->value( numberOfEntries - i - 1 ); + entryValues.push_back( min + value * ( max - min ) ); + } + else + { + 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 ) ) ); + int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i; + entryColors.push_back( colorRamp->color( colorRamp->value( idx ) ) ); } } } From 3e1536f1da20097eb68a57a34d65bdae45fb1568 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 14:16:10 +1000 Subject: [PATCH 095/897] Fix crash in raster transparency widget on close mPixelSelectorTool is owned by canvas, which may be deleted before the QgsRasterTransparencyWidget on QGIS exit --- src/gui/raster/qgsrastertransparencywidget.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/gui/raster/qgsrastertransparencywidget.cpp b/src/gui/raster/qgsrastertransparencywidget.cpp index d38e683321e0..45724faa7359 100644 --- a/src/gui/raster/qgsrastertransparencywidget.cpp +++ b/src/gui/raster/qgsrastertransparencywidget.cpp @@ -64,10 +64,6 @@ QgsRasterTransparencyWidget::QgsRasterTransparencyWidget( QgsRasterLayer *layer, QgsRasterTransparencyWidget::~QgsRasterTransparencyWidget() { - if ( mPixelSelectorTool ) - { - delete mPixelSelectorTool; - } } void QgsRasterTransparencyWidget::syncToLayer() From 79fd6fa0ac9f078c916d90fbfc2ff458206008cf Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 14:19:12 +1000 Subject: [PATCH 096/897] Fix raster style dock widgets not opened with dock mode flag Makes the color picker and ramp editors open inline for the raster properties pages --- src/app/qgslayerstylingwidget.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/app/qgslayerstylingwidget.cpp b/src/app/qgslayerstylingwidget.cpp index 70bbad9630fc..0d6f575b67e9 100644 --- a/src/app/qgslayerstylingwidget.cpp +++ b/src/app/qgslayerstylingwidget.cpp @@ -334,6 +334,7 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() if ( panel ) { connect( panel, SIGNAL( widgetChanged( QgsPanelWidget* ) ), this, SLOT( autoApply() ) ); + panel->setDockMode( true ); mWidgetStack->addMainPanel( panel ); } } @@ -385,12 +386,14 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() { case 0: // Style mRasterStyleWidget = new QgsRendererRasterPropertiesWidget( rlayer, mMapCanvas, mWidgetStack ); + mRasterStyleWidget->setDockMode( true ); connect( mRasterStyleWidget, SIGNAL( widgetChanged() ), this, SLOT( autoApply() ) ); mWidgetStack->addMainPanel( mRasterStyleWidget ); break; case 1: // Transparency { QgsRasterTransparencyWidget* transwidget = new QgsRasterTransparencyWidget( rlayer, mMapCanvas, mWidgetStack ); + transwidget->setDockMode( true ); connect( transwidget, SIGNAL( widgetChanged() ), this, SLOT( autoApply() ) ); mWidgetStack->addMainPanel( transwidget ); break; @@ -412,6 +415,7 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() connect( widget, SIGNAL( widgetChanged() ), this, SLOT( autoApply() ) ); QString name = mRasterStyleWidget->currentRenderWidget()->renderer()->type(); widget->setRendererWidget( name, mRasterStyleWidget->currentRenderWidget() ); + widget->setDockMode( true ); mWidgetStack->addMainPanel( widget ); } From b95a5e98c8cbd9bc388e42634eb11a2b161eecbb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 14:26:20 +1000 Subject: [PATCH 097/897] Fix missing live updates when raster colorize color changes --- src/gui/raster/qgsrendererrasterpropertieswidget.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/raster/qgsrendererrasterpropertieswidget.cpp b/src/gui/raster/qgsrendererrasterpropertieswidget.cpp index e32e5ddbd01a..0af84f433fcf 100644 --- a/src/gui/raster/qgsrendererrasterpropertieswidget.cpp +++ b/src/gui/raster/qgsrendererrasterpropertieswidget.cpp @@ -93,6 +93,7 @@ QgsRendererRasterPropertiesWidget::QgsRendererRasterPropertiesWidget( QgsMapLaye connect( mContrastSpinBox, SIGNAL( valueChanged( int ) ), this, SIGNAL( widgetChanged() ) ); connect( spinBoxSaturation, SIGNAL( valueChanged( int ) ), this, SIGNAL( widgetChanged() ) ); connect( spinColorizeStrength, SIGNAL( valueChanged( int ) ), this, SIGNAL( widgetChanged() ) ); + connect( btnColorizeColor, SIGNAL( colorChanged( QColor ) ), this, SIGNAL( widgetChanged() ) ); connect( mBlendModeComboBox, SIGNAL( currentIndexChanged( int ) ), this, SIGNAL( widgetChanged() ) ); connect( mZoomedInResamplingComboBox, SIGNAL( currentIndexChanged( int ) ), this, SIGNAL( widgetChanged() ) ); From 6976de6c9e58927d67b4fda720c728375496e0fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Wed, 5 Oct 2016 08:09:19 +0200 Subject: [PATCH 098/897] remove all splitWithLines tests --- .../tests/testdata/qgis_algorithm_tests.yaml | 55 ------------------- 1 file changed, 55 deletions(-) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index dc2dba4ea9b4..96cd233c984e 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -191,61 +191,6 @@ tests: name: expected/basic_statistics_string.html type: file - # Split with lines considers three cases - # case 1: two different line layers - - algorithm: qgis:splitwithlines - name: Split lines with lines - params: - INPUT_A: - name: lines.gml - type: vector - INPUT_B: - name: custom/lines2.gml - type: vector - results: - OUTPUT: - name: expected/lines_split_with_lines.gml - type: vector - compare: - geometry: - precision: 7 - - # case 2 split line layer with iself - - algorithm: qgis:splitwithlines - name: Split lines with same lines - params: - INPUT_A: - name: custom/lines2.gml - type: vector - INPUT_B: - name: custom/lines2.gml - type: vector - results: - OUTPUT: - name: expected/lines_split_with_same_lines.gml - type: vector - compare: - geometry: - precision: 7 - - # case 3 split polygon layer with lines - - algorithm: qgis:splitwithlines - name: Split polygons with lines - params: - INPUT_A: - name: polys.gml - type: vector - INPUT_B: - name: lines.gml - type: vector - results: - OUTPUT: - name: expected/polys_split_with_lines.gml - type: vector - compare: - geometry: - precision: 7 - - algorithm: qgis:addautoincrementalfield name: Add autoincremental field params: From b9ca91a55a981ddf6d99e0e5b9e4ecc9f6425e88 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 16 Sep 2016 10:48:52 +0300 Subject: [PATCH 099/897] [FEATURE] support for 2.5D geometries in memory provider --- src/providers/memory/qgsmemoryprovider.cpp | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/providers/memory/qgsmemoryprovider.cpp b/src/providers/memory/qgsmemoryprovider.cpp index 1843af6a828d..fe2ab2418f35 100644 --- a/src/providers/memory/qgsmemoryprovider.cpp +++ b/src/providers/memory/qgsmemoryprovider.cpp @@ -60,6 +60,18 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) mWkbType = QgsWkbTypes::MultiLineString; else if ( geometry == "multipolygon" ) mWkbType = QgsWkbTypes::MultiPolygon; + else if ( geometry == "point25d" ) + mWkbType = QgsWkbTypes::Point25D; + else if ( geometry == "linestring25d" ) + mWkbType = QgsWkbTypes::LineString25D; + else if ( geometry == "polygon25d" ) + mWkbType = QgsWkbTypes::Polygon25D; + else if ( geometry == "multipoint25d" ) + mWkbType = QgsWkbTypes::MultiPoint25D; + else if ( geometry == "multilinestring25d" ) + mWkbType = QgsWkbTypes::MultiLineString25D; + else if ( geometry == "multipolygon25d" ) + mWkbType = QgsWkbTypes::MultiPolygon25D; else if ( geometry == "none" ) mWkbType = QgsWkbTypes::NoGeometry; else @@ -229,6 +241,24 @@ QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const case QgsWkbTypes::MultiPolygon : geometry = "MultiPolygon"; break; + case QgsWkbTypes::Point25D : + geometry = "Point25D"; + break; + case QgsWkbTypes::LineString25D : + geometry = "LineString25D"; + break; + case QgsWkbTypes::Polygon25D : + geometry = "Polygon25D"; + break; + case QgsWkbTypes::MultiPoint25D : + geometry = "MultiPoint25D"; + break; + case QgsWkbTypes::MultiLineString25D : + geometry = "MultiLineString25D"; + break; + case QgsWkbTypes::MultiPolygon25D : + geometry = "MultiPolygon25D"; + break; case QgsWkbTypes::NoGeometry : geometry = "None"; break; From 2b115449ab5d769e033c0e5f1c8d9360d7bafd8c Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 16 Sep 2016 10:49:56 +0300 Subject: [PATCH 100/897] don't flatten geometries when pasting them as new memory layer --- src/app/qgisapp.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index c7ce395726b5..fe6e64f5c4ec 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -7505,7 +7505,7 @@ QgsVectorLayer *QgisApp::pasteToNewMemoryVector() if ( !feature.hasGeometry() ) continue; - QgsWkbTypes::Type type = QgsWkbTypes::flatType( feature.geometry().wkbType() ); + QgsWkbTypes::Type type = feature.geometry().wkbType(); if ( type == QgsWkbTypes::Unknown || type == QgsWkbTypes::NoGeometry ) continue; @@ -7535,7 +7535,7 @@ QgsVectorLayer *QgisApp::pasteToNewMemoryVector() QgsWkbTypes::Type wkbType = !typeCounts.isEmpty() ? typeCounts.keys().value( 0 ) : QgsWkbTypes::NoGeometry; - QString typeName = wkbType != QgsWkbTypes::NoGeometry ? QString( QgsWkbTypes::displayString( wkbType ) ).remove( "WKB" ) : "none"; + QString typeName = wkbType != QgsWkbTypes::NoGeometry ? QString( QgsWkbTypes::displayString( wkbType ) ) : "none"; if ( features.isEmpty() ) { @@ -7590,7 +7590,7 @@ QgsVectorLayer *QgisApp::pasteToNewMemoryVector() if ( !feature.hasGeometry() ) continue; - QgsWkbTypes::Type type = QgsWkbTypes::flatType( feature.geometry().wkbType() ); + QgsWkbTypes::Type type = feature.geometry().wkbType(); if ( type == QgsWkbTypes::Unknown || type == QgsWkbTypes::NoGeometry ) continue; From a4bdfb76c0c7a53d186eeb47cae8197fe052f634 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 16 Sep 2016 10:50:36 +0300 Subject: [PATCH 101/897] [processing] support more geometry types in memory layers (fix #15508) --- python/plugins/processing/tools/vector.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 169fe6d78ba2..47718c15d86e 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -60,6 +60,12 @@ QgsWkbTypes.MultiPoint: 'MultiPoint', QgsWkbTypes.MultiLineString: 'MultiLineString', QgsWkbTypes.MultiPolygon: 'MultiPolygon', + QgsWkbTypes.Point25D: 'Point25D', + QgsWkbTypes.LineString25D: 'LineString25D', + QgsWkbTypes.Polygon25D: 'Polygon25D', + QgsWkbTypes.MultiPoint25D: 'MultiPoint25D', + QgsWkbTypes.MultiLineString25D: 'MultiLineString25D', + QgsWkbTypes.MultiPolygon25D: 'MultiPolygon25D', } From 5b67d2a327513e6b210d20f0ff639a8c500ce6fa Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 4 Oct 2016 13:29:50 +0300 Subject: [PATCH 102/897] remove extra QString wrapper --- src/app/qgisapp.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index fe6e64f5c4ec..04493279e7ac 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -7535,7 +7535,7 @@ QgsVectorLayer *QgisApp::pasteToNewMemoryVector() QgsWkbTypes::Type wkbType = !typeCounts.isEmpty() ? typeCounts.keys().value( 0 ) : QgsWkbTypes::NoGeometry; - QString typeName = wkbType != QgsWkbTypes::NoGeometry ? QString( QgsWkbTypes::displayString( wkbType ) ) : "none"; + QString typeName = wkbType != QgsWkbTypes::NoGeometry ? QgsWkbTypes::displayString( wkbType ) : "none"; if ( features.isEmpty() ) { From 33644efeba3275843ee6507562fab405d091ad32 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 4 Oct 2016 13:31:48 +0300 Subject: [PATCH 103/897] use QgsWkbTypes methods to simplify code --- src/providers/memory/qgsmemoryprovider.cpp | 77 +--------------------- 1 file changed, 2 insertions(+), 75 deletions(-) diff --git a/src/providers/memory/qgsmemoryprovider.cpp b/src/providers/memory/qgsmemoryprovider.cpp index fe2ab2418f35..86a0afc8bc2a 100644 --- a/src/providers/memory/qgsmemoryprovider.cpp +++ b/src/providers/memory/qgsmemoryprovider.cpp @@ -47,35 +47,7 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) geometry = url.path(); } - geometry = geometry.toLower(); - if ( geometry == "point" ) - mWkbType = QgsWkbTypes::Point; - else if ( geometry == "linestring" ) - mWkbType = QgsWkbTypes::LineString; - else if ( geometry == "polygon" ) - mWkbType = QgsWkbTypes::Polygon; - else if ( geometry == "multipoint" ) - mWkbType = QgsWkbTypes::MultiPoint; - else if ( geometry == "multilinestring" ) - mWkbType = QgsWkbTypes::MultiLineString; - else if ( geometry == "multipolygon" ) - mWkbType = QgsWkbTypes::MultiPolygon; - else if ( geometry == "point25d" ) - mWkbType = QgsWkbTypes::Point25D; - else if ( geometry == "linestring25d" ) - mWkbType = QgsWkbTypes::LineString25D; - else if ( geometry == "polygon25d" ) - mWkbType = QgsWkbTypes::Polygon25D; - else if ( geometry == "multipoint25d" ) - mWkbType = QgsWkbTypes::MultiPoint25D; - else if ( geometry == "multilinestring25d" ) - mWkbType = QgsWkbTypes::MultiLineString25D; - else if ( geometry == "multipolygon25d" ) - mWkbType = QgsWkbTypes::MultiPolygon25D; - else if ( geometry == "none" ) - mWkbType = QgsWkbTypes::NoGeometry; - else - mWkbType = QgsWkbTypes::Unknown; + mWkbType = QgsWkbTypes::parseType( geometry ); if ( url.hasQueryItem( "crs" ) ) { @@ -220,52 +192,7 @@ QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const Q_UNUSED( expandAuthConfig ) QUrl uri( "memory" ); - QString geometry; - switch ( mWkbType ) - { - case QgsWkbTypes::Point : - geometry = "Point"; - break; - case QgsWkbTypes::LineString : - geometry = "LineString"; - break; - case QgsWkbTypes::Polygon : - geometry = "Polygon"; - break; - case QgsWkbTypes::MultiPoint : - geometry = "MultiPoint"; - break; - case QgsWkbTypes::MultiLineString : - geometry = "MultiLineString"; - break; - case QgsWkbTypes::MultiPolygon : - geometry = "MultiPolygon"; - break; - case QgsWkbTypes::Point25D : - geometry = "Point25D"; - break; - case QgsWkbTypes::LineString25D : - geometry = "LineString25D"; - break; - case QgsWkbTypes::Polygon25D : - geometry = "Polygon25D"; - break; - case QgsWkbTypes::MultiPoint25D : - geometry = "MultiPoint25D"; - break; - case QgsWkbTypes::MultiLineString25D : - geometry = "MultiLineString25D"; - break; - case QgsWkbTypes::MultiPolygon25D : - geometry = "MultiPolygon25D"; - break; - case QgsWkbTypes::NoGeometry : - geometry = "None"; - break; - default: - geometry = ""; - break; - } + QString geometry = QgsWkbTypes::displayString( mWkbType ); uri.addQueryItem( "geometry", geometry ); if ( mCrs.isValid() ) From 2f66e1d6e2828b248e3b7dd9ea1ac77b8fd61350 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 4 Oct 2016 13:47:36 +0300 Subject: [PATCH 104/897] add new geometry types to memory layer tests --- tests/src/python/test_provider_memory.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/src/python/test_provider_memory.py b/tests/src/python/test_provider_memory.py index c53335c6a2f6..b1f6032cbad4 100644 --- a/tests/src/python/test_provider_memory.py +++ b/tests/src/python/test_provider_memory.py @@ -127,6 +127,30 @@ def testLayerGeometry(self): ("MultiPoint", QgsWkbTypes.PointGeometry, QgsWkbTypes.MultiPoint), ("MultiLineString", QgsWkbTypes.LineGeometry, QgsWkbTypes.MultiLineString), ("MultiPolygon", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.MultiPolygon), + ("PointZ", QgsWkbTypes.PointGeometry, QgsWkbTypes.PointZ), + ("LineStringZ", QgsWkbTypes.LineGeometry, QgsWkbTypes.LineStringZ), + ("PolygonZ", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.PolygonZ), + ("MultiPointZ", QgsWkbTypes.PointGeometry, QgsWkbTypes.MultiPointZ), + ("MultiLineStringZ", QgsWkbTypes.LineGeometry, QgsWkbTypes.MultiLineStringZ), + ("MultiPolygonZ", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.MultiPolygonZ), + ("PointM", QgsWkbTypes.PointGeometry, QgsWkbTypes.PointM), + ("LineStringM", QgsWkbTypes.LineGeometry, QgsWkbTypes.LineStringM), + ("PolygonM", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.PolygonM), + ("MultiPointM", QgsWkbTypes.PointGeometry, QgsWkbTypes.MultiPointM), + ("MultiLineStringM", QgsWkbTypes.LineGeometry, QgsWkbTypes.MultiLineStringM), + ("MultiPolygonM", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.MultiPolygonM), + ("PointZM", QgsWkbTypes.PointGeometry, QgsWkbTypes.PointZM), + ("LineStringZM", QgsWkbTypes.LineGeometry, QgsWkbTypes.LineStringZM), + ("PolygonZM", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.PolygonZM), + ("MultiPointZM", QgsWkbTypes.PointGeometry, QgsWkbTypes.MultiPointZM), + ("MultiLineStringZM", QgsWkbTypes.LineGeometry, QgsWkbTypes.MultiLineStringZM), + ("MultiPolygonZM", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.MultiPolygonZM), + ("Point25D", QgsWkbTypes.PointGeometry, QgsWkbTypes.Point25D), + ("LineString25D", QgsWkbTypes.LineGeometry, QgsWkbTypes.LineString25D), + ("Polygon25D", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.Polygon25D), + ("MultiPoint25D", QgsWkbTypes.PointGeometry, QgsWkbTypes.MultiPoint25D), + ("MultiLineString25D", QgsWkbTypes.LineGeometry, QgsWkbTypes.MultiLineString25D), + ("MultiPolygon25D", QgsWkbTypes.PolygonGeometry, QgsWkbTypes.MultiPolygon25D), ("None", QgsWkbTypes.NullGeometry, QgsWkbTypes.NoGeometry)] for v in testVectors: layer = QgsVectorLayer(v[0], "test", "memory") From 7a49612a608a6a7c756a9bb29928a73a953d5154 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 4 Oct 2016 15:13:25 +0300 Subject: [PATCH 105/897] fix handling of layers without geometry --- src/providers/memory/qgsmemoryprovider.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/providers/memory/qgsmemoryprovider.cpp b/src/providers/memory/qgsmemoryprovider.cpp index 86a0afc8bc2a..3bb74fd2ee2f 100644 --- a/src/providers/memory/qgsmemoryprovider.cpp +++ b/src/providers/memory/qgsmemoryprovider.cpp @@ -47,7 +47,14 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) geometry = url.path(); } - mWkbType = QgsWkbTypes::parseType( geometry ); + if ( geometry.toLower() == "none" ) + { + mWkbType = QgsWkbTypes::NoGeometry; + } + else + { + mWkbType = QgsWkbTypes::parseType( geometry ); + } if ( url.hasQueryItem( "crs" ) ) { From eeb8269464f6e411f389400d8c39b261705bc1a8 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 5 Oct 2016 09:45:55 +0300 Subject: [PATCH 106/897] [processing] drop GEOM_TYPE_MAP in favour of QgsWkbTypes.displayString() --- python/plugins/processing/tools/vector.py | 23 +++-------------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 47718c15d86e..d8b135b8582f 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -52,23 +52,6 @@ from processing.tools import dataobjects, spatialite, postgis -GEOM_TYPE_MAP = { - QgsWkbTypes.NullGeometry: 'none', - QgsWkbTypes.Point: 'Point', - QgsWkbTypes.LineString: 'LineString', - QgsWkbTypes.Polygon: 'Polygon', - QgsWkbTypes.MultiPoint: 'MultiPoint', - QgsWkbTypes.MultiLineString: 'MultiLineString', - QgsWkbTypes.MultiPolygon: 'MultiPolygon', - QgsWkbTypes.Point25D: 'Point25D', - QgsWkbTypes.LineString25D: 'LineString25D', - QgsWkbTypes.Polygon25D: 'Polygon25D', - QgsWkbTypes.MultiPoint25D: 'MultiPoint25D', - QgsWkbTypes.MultiLineString25D: 'MultiLineString25D', - QgsWkbTypes.MultiPolygon25D: 'MultiPolygon25D', -} - - TYPE_MAP = { str: QVariant.String, float: QVariant.Double, @@ -567,7 +550,7 @@ def __init__(self, destination, encoding, fields, geometryType, if self.destination.startswith(self.MEMORY_LAYER_PREFIX): self.isNotFileBased = True - uri = GEOM_TYPE_MAP[geometryType] + "?uuid=" + str(uuid.uuid4()) + uri = QgsWkbTypes.displayString(geometryType) + "?uuid=" + str(uuid.uuid4()) if crs.isValid(): uri += '&crs=' + crs.authid() fieldsdesc = [] @@ -614,7 +597,7 @@ def _runSQL(sql): if geometryType != QgsWkbTypes.NullGeometry: _runSQL("SELECT AddGeometryColumn('{schema}', '{table}', 'the_geom', {srid}, '{typmod}', 2)".format( table=uri.table().lower(), schema=uri.schema(), srid=crs.authid().split(":")[-1], - typmod=GEOM_TYPE_MAP[geometryType].upper())) + typmod=QgsWkbTypes.displayString(geometryType).upper())) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "postgres") self.writer = self.layer.dataProvider() @@ -646,7 +629,7 @@ def _runSQL(sql): if geometryType != QgsWkbTypes.NullGeometry: _runSQL("SELECT AddGeometryColumn('{table}', 'the_geom', {srid}, '{typmod}', 2)".format( table=uri.table().lower(), srid=crs.authid().split(":")[-1], - typmod=GEOM_TYPE_MAP[geometryType].upper())) + typmod=QgsWkbTypes.displayString(geometryType).upper())) self.layer = QgsVectorLayer(uri.uri(), uri.table(), "spatialite") self.writer = self.layer.dataProvider() From 0348dd5ce78a530273ea37f580ac080f00214791 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Wed, 5 Oct 2016 12:17:33 +0200 Subject: [PATCH 107/897] Force use of estimated metadata upon loading topologies --- .../db_plugins/postgis/plugins/qgis_topoview/__init__.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py b/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py index e102d287efde..268d99cbd010 100644 --- a/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py +++ b/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py @@ -108,6 +108,9 @@ def run(item, action, mainwindow): provider = db.dbplugin().providerName() uri = db.uri() + # Force use of estimated metadata (topologies can be big) + uri.setUseEstimatedMetadata( True ) + # FACES group = legend.addGroup(u'Faces', False, supergroup) From 484fd18ef603c6a876c3391291ebe4fad2d8c483 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 25 Jul 2016 13:21:27 +0200 Subject: [PATCH 108/897] [processing] fixed add model from file fixes #15335 --- python/plugins/processing/modeler/ModelerAlgorithmProvider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/modeler/ModelerAlgorithmProvider.py b/python/plugins/processing/modeler/ModelerAlgorithmProvider.py index bb06a8a5eb1c..bf8af0bce483 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithmProvider.py +++ b/python/plugins/processing/modeler/ModelerAlgorithmProvider.py @@ -58,7 +58,7 @@ def initializeSettings(self): ModelerUtils.defaultModelsFolder(), valuetype=Setting.MULTIPLE_FOLDERS)) def modelsFolder(self): - return ModelerUtils.modelsFolder() + return ModelerUtils.modelsFolders()[0] def getDescription(self): return self.tr('Models', 'ModelerAlgorithmProvider') From 2ad27b172ea12add240bc256a1f183b0c71e2e70 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Tue, 23 Aug 2016 10:44:57 +0200 Subject: [PATCH 109/897] Add metadata property to parameters --- python/plugins/processing/core/parameters.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index ab84ef589ae5..f06205651638 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -58,7 +58,10 @@ class Parameter(object): take as input. """ - def __init__(self, name='', description='', default=None, optional=False): + default_metadata = {} + + def __init__(self, name='', description='', default=None, optional=False, + metadata={}): self.name = name self.description = description self.default = default @@ -73,6 +76,10 @@ def __init__(self, name='', description='', default=None, optional=False): self.optional = parseBool(optional) + # TODO: make deep copy and deep update + self.metadata = self.default_metadata.copy() + self.metadata.update(metadata) + def setValue(self, obj): """ Sets the value of the parameter. From ecb7b3a096f58ad60e212f901845ad1c435d29e8 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sat, 3 Sep 2016 22:46:19 +0200 Subject: [PATCH 110/897] Remove metadata from parameter.todict (do not save in model) --- python/plugins/processing/core/parameters.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index f06205651638..cb2b067cd7f6 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -120,7 +120,9 @@ def typeName(self): return self.__class__.__name__.replace('Parameter', '').lower() def todict(self): - return self.__dict__ + o = self.__dict__ + del o['metadata'] + return o def tr(self, string, context=''): if context == '': From 728be70c0b562490ed0fe10fa7e017cb373c9617 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Tue, 23 Aug 2016 10:46:22 +0200 Subject: [PATCH 111/897] Create the boolean widget wrapper --- python/plugins/processing/core/parameters.py | 8 +- python/plugins/processing/gui/wrappers.py | 117 +++++++++++++++++++ 2 files changed, 123 insertions(+), 2 deletions(-) create mode 100644 python/plugins/processing/gui/wrappers.py diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index cb2b067cd7f6..c444927948bb 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -132,8 +132,12 @@ def tr(self, string, context=''): class ParameterBoolean(Parameter): - def __init__(self, name='', description='', default=None, optional=False): - Parameter.__init__(self, name, description, parseBool(default), optional) + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.BooleanWidgetWrapper' + } + + def __init__(self, name='', description='', default=None, optional=False, metadata={}): + Parameter.__init__(self, name, description, parseBool(default), optional, metadata) def setValue(self, value): if value is None: diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py new file mode 100644 index 000000000000..633cf7fb4c66 --- /dev/null +++ b/python/plugins/processing/gui/wrappers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + BooleanWidget.py + --------------------- + Date : May 2016 + Copyright : (C) 2016 by Arnaud Morvan + Email : arnaud dot morvan at camptocamp dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Arnaud Morvan' +__date__ = 'May 2016' +__copyright__ = '(C) 2016, Arnaud Morvan' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + + +from inspect import isclass + +from qgis.PyQt.QtWidgets import ( + QCheckBox, + QComboBox, + ) + +DIALOG_STANDARD = 'standard' +DIALOG_BATCH = 'batch' +DIALOG_MODELER = 'modeler' + + +def wrapper_from_param(param, dialog=DIALOG_STANDARD, extra_values=[]): + wrapper = param.metadata.get('widget_wrapper', None) + # wrapper metadata should be a class path + if isinstance(wrapper, basestring): + tokens = wrapper.split('.') + mod = __import__('.'.join(tokens[:-1]), fromlist=[tokens[-1]]) + wrapper = getattr(mod, tokens[-1]) + # or directly a class object + if isclass(wrapper): + wrapper = wrapper(param=param, dialog=dialog, extra_values=extra_values) + # or a wrapper instance + return wrapper + + +class NotYetImplementedWidgetWrapper(): + + """Temporary substitute class for not yet implemented wrappers""" + + implemented = False + + def __init__(self, param, widget): + self.param = param + self.widget = widget + + +class WidgetWrapper(): + + implemented = True # TODO: Should be removed at the end + + def __init__(self, param, dialog=DIALOG_STANDARD, extra_values=[]): + self.param = param + self.dialog = dialog + self.widget = self.createWidget(extra_values) + self.setValue(param.default) + + def createWidget(self, extra_values=[]): + pass + + def setValue(self, value): + pass + + def value(self): + pass + + +class BooleanWidgetWrapper(WidgetWrapper): + + def createWidget(self, extra_values=[]): + if self.dialog == DIALOG_STANDARD: + return QCheckBox() + + if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): + widget = QComboBox() + widget.addItem(widget.tr('Yes'), True) + widget.addItem(widget.tr('No'), False) + for text, value in extra_values: + widget.addItem(text, value) + return widget + + def setValue(self, value): + if self.dialog == DIALOG_STANDARD: + self.widget.setChecked(value) + + if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): + values = [self.widget.itemData(i) for i in range(self.widget.count())] + try: + idx = values.index(value) + self.widget.setCurrentIndex(idx) + except ValueError: + pass + + def value(self): + if self.dialog == DIALOG_STANDARD: + return self.widget.isChecked() + + if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): + return self.widget.itemData(self.widget.currentIndex()) From f3c9aaaa2b653edeb2915966b9d1b25fa0349409 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Tue, 23 Aug 2016 10:49:32 +0200 Subject: [PATCH 112/897] Use boolean wrapper in standard algorithm dialog Conflicts: python/plugins/processing/gui/AlgorithmDialog.py --- .../plugins/processing/gui/AlgorithmDialog.py | 24 +++++++++----- .../plugins/processing/gui/ParametersPanel.py | 32 +++++++++++++------ 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index f708add40d0f..3a5531e6e4af 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -46,7 +46,6 @@ from processing.core.parameters import ParameterRaster from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterTable -from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterSelection from processing.core.parameters import ParameterFixedTable from processing.core.parameters import ParameterRange @@ -103,10 +102,17 @@ def setParamValues(self): for param in params: if param.hidden: continue - if not self.setParamValue( - param, self.mainWidget.valueItems[param.name]): - raise AlgorithmDialogBase.InvalidParameterValue( - param, self.mainWidget.valueItems[param.name]) + if isinstance(param, ParameterExtent): + continue + wrapper = self.mainWidget.widget_wrappers[param.name] + if not self.setParamValue(param, wrapper): + raise AlgorithmDialogBase.InvalidParameterValue(param, wrapper) + + for param in params: + if isinstance(param, ParameterExtent): + wrapper = self.mainWidget.widget_wrappers[param.name] + if not self.setParamValue(param, wrapper): + raise AlgorithmDialogBase.InvalidParameterValue(param, wrapper) for output in outputs: if output.hidden: @@ -129,7 +135,11 @@ def evaluateExpression(self, text): raise ValueError(exp.evalErrorString()) return result - def setParamValue(self, param, widget, alg=None): + def setParamValue(self, param, wrapper, alg=None): + if wrapper.implemented: + return param.setValue(wrapper.value()) + + widget = wrapper.widget if isinstance(param, ParameterRaster): return param.setValue(widget.getValue()) elif isinstance(param, (ParameterVector, ParameterTable)): @@ -137,8 +147,6 @@ def setParamValue(self, param, widget, alg=None): return param.setValue(widget.itemData(widget.currentIndex())) except: return param.setValue(widget.getValue()) - elif isinstance(param, ParameterBoolean): - return param.setValue(widget.isChecked()) elif isinstance(param, ParameterSelection): return param.setValue(widget.currentIndex()) elif isinstance(param, ParameterFixedTable): diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index f5ff19b62ab0..09273997193b 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -42,6 +42,11 @@ from processing.core.ProcessingConfig import ProcessingConfig +from processing.gui.wrappers import ( + wrapper_from_param, + NotYetImplementedWidgetWrapper, + ) + from processing.gui.OutputSelectionPanel import OutputSelectionPanel from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel from processing.gui.FixedTablePanel import FixedTablePanel @@ -59,7 +64,6 @@ from processing.core.parameters import ParameterRaster from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterTable -from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterTableField from processing.core.parameters import ParameterTableMultipleField from processing.core.parameters import ParameterSelection @@ -101,6 +105,7 @@ def __init__(self, parent, alg): self.parent = parent self.alg = alg self.valueItems = {} + self.widget_wrappers = {} self.labels = {} self.widgets = {} self.checkBoxes = {} @@ -195,8 +200,10 @@ def initWidgets(self): except: pass - widget = self.getWidgetFromParameter(param) - self.valueItems[param.name] = widget + wrapper = self.getWidgetWrapperFromParameter(param) + self.widget_wrappers[param.name] = wrapper + self.valueItems[param.name] = wrapper.widget + widget = wrapper.widget if isinstance(param, ParameterVector) and \ not self.alg.allowOnlyOpenedLayers: @@ -218,7 +225,7 @@ def initWidgets(self): tooltips = self.alg.getParameterDescriptions() widget.setToolTip(tooltips.get(param.name, param.description)) - if isinstance(param, ParameterBoolean): + if isinstance(widget, QCheckBox): widget.setText(desc) if param.isAdvanced: self.layoutAdvanced.addWidget(widget) @@ -255,6 +262,8 @@ def initWidgets(self): self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.valueItems[output.name] = widget + wrapper = NotYetImplementedWidgetWrapper(output, widget) + self.widget_wrappers[output.name] = wrapper if isinstance(output, OutputVector): if output.base_input in self.dependentItems: @@ -287,6 +296,15 @@ def getExtendedLayerName(self, layer): else: return layer.name() + def getWidgetWrapperFromParameter(self, param): + wrapper = wrapper_from_param(param) + if wrapper is not None: + return wrapper + + widget = self.getWidgetFromParameter(param) + wrapper = NotYetImplementedWidgetWrapper(param, widget) + return wrapper + def getWidgetFromParameter(self, param): # TODO Create Parameter widget class that holds the logic # for creating a widget that belongs to the parameter. @@ -343,12 +361,6 @@ def getWidgetFromParameter(self, param): if layer and layer.source() == param.value: items.insert(0, items.pop(i)) item = InputLayerSelectorPanel(items, param) - elif isinstance(param, ParameterBoolean): - item = QCheckBox() - if param.default: - item.setChecked(True) - else: - item.setChecked(False) elif isinstance(param, ParameterTableField) or isinstance(param, ParameterTableMultipleField): if isinstance(param, ParameterTableMultipleField): item = ListMultiSelectWidget() From fbab369c0d77cfd728d3d03155e49b9b7ee9e772 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Tue, 23 Aug 2016 14:40:06 +0200 Subject: [PATCH 113/897] Use boolean wrapper in batch algorithm dialog Conflicts: python/plugins/processing/gui/BatchPanel.py --- python/plugins/processing/gui/BatchPanel.py | 86 +++++++++++++++------ python/plugins/processing/gui/wrappers.py | 2 +- 2 files changed, 62 insertions(+), 26 deletions(-) diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index e4ed5faef2b3..927adef51367 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -36,6 +36,12 @@ from qgis.core import QgsApplication +from processing.gui.wrappers import ( + DIALOG_BATCH, + wrapper_from_param, + NotYetImplementedWidgetWrapper, +) + from processing.gui.FileSelectionPanel import FileSelectionPanel from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.ExtentSelectionPanel import ExtentSelectionPanel @@ -52,7 +58,6 @@ from processing.core.parameters import ParameterExtent from processing.core.parameters import ParameterCrs from processing.core.parameters import ParameterPoint -from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterSelection from processing.core.parameters import ParameterFixedTable from processing.core.parameters import ParameterMultipleInput @@ -72,6 +77,8 @@ def __init__(self, parent, alg): super(BatchPanel, self).__init__(None) self.setupUi(self) + self.widget_wrappers = [] + self.btnAdvanced.hide() # Set icons @@ -140,25 +147,26 @@ def initWidgets(self): self.tblParameters.verticalHeader().setResizeMode(QHeaderView.ResizeToContents) self.tblParameters.horizontalHeader().setStretchLastSection(True) + def getWidgetWrapperFromParameter(self, param, row, col): + wrapper = wrapper_from_param(param) # , DIALOG_BATCH) + if wrapper is not None: + return wrapper + + widget = self.getWidgetFromParameter(param, row, col) + wrapper = NotYetImplementedWidgetWrapper(param, widget) + return wrapper + def getWidgetFromParameter(self, param, row, col): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): item = BatchInputSelectionPanel(param, row, col, self) - elif isinstance(param, ParameterBoolean): - item = QComboBox() - item.addItem(self.tr('Yes')) - item.addItem(self.tr('No')) - if param.default: - item.setCurrentIndex(0) - else: - item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterExtent): - item = ExtentSelectionPanel(self.parent, param.default) + item = ExtentSelectionPanel(self.parent, self.alg, param.default) elif isinstance(param, ParameterPoint): item = PointSelectionPanel(self.parent, param.default) elif isinstance(param, ParameterCrs): @@ -181,9 +189,9 @@ def getWidgetFromParameter(self, param, row, col): return item def load(self): - filename, selected_filter = str(QFileDialog.getOpenFileName(self, - self.tr('Open batch'), None, - self.tr('JSON files (*.json)'))) + filename, selected_filter = QFileDialog.getOpenFileName(self, + self.tr('Open batch'), None, + self.tr('JSON files (*.json)')) if filename: with open(filename) as f: values = json.load(f) @@ -201,18 +209,18 @@ def load(self): for param in self.alg.parameters: if param.hidden: continue - widget = self.tblParameters.cellWidget(row, column) if param.name in params: value = params[param.name] - self.setValueInWidget(widget, value) + wrapper = self.widget_wrappers[row][column] + self.setValueInWidgetWrapper(wrapper, value) column += 1 for out in self.alg.outputs: if out.hidden: continue - widget = self.tblParameters.cellWidget(row, column) if out.name in outputs: value = outputs[out.name] + widget = self.tblParameters.cellWidget(row, column) self.setValueInWidget(widget, value) column += 1 except TypeError: @@ -221,6 +229,11 @@ def load(self): self.tr('Error'), self.tr('An error occurred while reading your file.')) + def setValueInWidgetWrapper(self, wrapper, value): + if wrapper.implemented: + return wrapper.setValue(value) + self.setValueInWidget(wrapper.widget, value) + def setValueInWidget(self, widget, value): if isinstance(widget, (BatchInputSelectionPanel, QLineEdit, FileSelectionPanel)): widget.setText(str(value)) @@ -249,13 +262,28 @@ def save(self): for param in alg.parameters: if param.hidden: continue - widget = self.tblParameters.cellWidget(row, col) - if not self.setParamValue(param, widget, alg): + if isinstance(param, ParameterExtent): + col += 1 + continue + wrapper = self.widget_wrappers[row][col] + if not self.setParamValue(param, wrapper, alg): self.parent.lblProgress.setText( self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) return algParams[param.name] = param.getValueAsCommandLineParameter() col += 1 + col = 0 + for param in alg.parameters: + if param.hidden: + continue + if isinstance(param, ParameterExtent): + wrapper = self.widget_wrappers[row][col] + if not self.setParamValue(param, wrapper, alg): + self.parent.lblProgress.setText( + self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) + return + algParams[param.name] = unicode(param.value()) + col += 1 for out in alg.outputs: if out.hidden: continue @@ -270,25 +298,27 @@ def save(self): return toSave.append({self.PARAMETERS: algParams, self.OUTPUTS: algOutputs}) - filename, filter = QFileDialog.getSaveFileName(self, + filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save batch'), None, - self.tr('JSON files (*.json)')) + self.tr('JSON files (*.json)'))) if filename: if not filename.endswith('.json'): filename += '.json' with open(filename, 'w') as f: json.dump(toSave, f) - def setParamValue(self, param, widget, alg=None): + def setParamValue(self, param, wrapper, alg=None): + if wrapper.implemented: + return param.setValue(wrapper.value()) + + widget = wrapper.widget if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): value = widget.getText() if str(value).strip() == '': value = None return param.setValue(value) - elif isinstance(param, ParameterBoolean): - return param.setValue(widget.currentIndex() == 0) elif isinstance(param, ParameterSelection): return param.setValue(widget.currentIndex()) elif isinstance(param, ParameterFixedTable): @@ -304,7 +334,12 @@ def setParamValue(self, param, widget, alg=None): else: return param.setValue(widget.text()) + def setCellWrapper(self, row, column, wrapper): + self.widget_wrappers[row][column] = wrapper + self.tblParameters.setCellWidget(row, column, wrapper.widget) + def addRow(self): + self.widget_wrappers.append([None] * self.tblParameters.columnCount()) self.tblParameters.setRowCount(self.tblParameters.rowCount() + 1) row = self.tblParameters.rowCount() - 1 @@ -313,8 +348,8 @@ def addRow(self): if param.hidden: continue - self.tblParameters.setCellWidget( - row, column, self.getWidgetFromParameter(param, row, column)) + wrapper = self.getWidgetWrapperFromParameter(param, row, column) + self.setCellWrapper(row, column, wrapper) column += 1 for out in self.alg.outputs: @@ -341,6 +376,7 @@ def removeRows(self): #~ self.tblParameters.model().removeRow(i.row()) #~ self.tblParameters.setUpdatesEnabled(True) if self.tblParameters.rowCount() > 2: + self.widget_wrappers.pop() self.tblParameters.setRowCount(self.tblParameters.rowCount() - 1) def fillParameterValues(self, column): diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 633cf7fb4c66..62d1d5c96a7f 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -31,7 +31,7 @@ from qgis.PyQt.QtWidgets import ( QCheckBox, QComboBox, - ) +) DIALOG_STANDARD = 'standard' DIALOG_BATCH = 'batch' From bb0938a5fe0fe9d628e4962c226cd73dc09a98c2 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Tue, 23 Aug 2016 14:48:11 +0200 Subject: [PATCH 114/897] Use boolean wrapper in modeler algorithm dialog --- .../modeler/ModelerParametersDialog.py | 66 +++++++++++-------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index d029d64b9d50..bf966095ca7d 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -40,6 +40,12 @@ from qgis.gui import QgsMessageBar +from processing.gui.wrappers import ( + DIALOG_MODELER, + wrapper_from_param, + NotYetImplementedWidgetWrapper, + ) + from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.MultipleInputPanel import MultipleInputPanel from processing.gui.FixedTablePanel import FixedTablePanel @@ -49,7 +55,6 @@ from processing.core.parameters import (ParameterExtent, ParameterRaster, ParameterVector, - ParameterBoolean, ParameterTable, ParameterFixedTable, ParameterMultipleInput, @@ -107,6 +112,7 @@ def setupUi(self): self.widgets = {} self.checkBoxes = {} self.showAdvanced = False + self.widget_wrappers = {} self.valueItems = {} self.dependentItems = {} self.resize(650, 450) @@ -160,7 +166,9 @@ def setupUi(self): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label - widget = self.getWidgetFromParameter(param) + wrapper = self.getWidgetWrapperFromParameter(param) + self.widget_wrappers[param.name] = wrapper + widget = wrapper.widget self.valueItems[param.name] = widget if param.name in list(tooltips.keys()): tooltip = tooltips[param.name] @@ -308,6 +316,20 @@ def resolveValueDescription(self, value): alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) + def getWidgetWrapperFromParameter(self, param): + extra_values = [] + values = self.getAvailableValuesOfType(param.__class__, None) + for value in values: + extra_values.append((self.resolveValueDescription(value), value)) + + wrapper = wrapper_from_param(param, DIALOG_MODELER, extra_values) + if wrapper is not None: + return wrapper + + widget = self.getWidgetFromParameter(param) + wrapper = NotYetImplementedWidgetWrapper(param, widget) + return wrapper + def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() @@ -333,17 +355,6 @@ def getWidgetFromParameter(self, param): item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) - elif isinstance(param, ParameterBoolean): - item = QComboBox() - item.addItem('Yes') - item.addItem('No') - bools = self.getAvailableValuesOfType(ParameterBoolean, None) - for b in bools: - item.addItem(self.resolveValueDescription(b), b) - if param.default: - item.setCurrentIndex(0) - else: - item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) @@ -487,11 +498,6 @@ def setComboBoxValue(self, combo, value, param): combo.setEditText(str(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) - elif isinstance(param, ParameterBoolean): - if value: - combo.setCurrentIndex(0) - else: - combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: @@ -500,11 +506,16 @@ def setPreviousValues(self): for param in alg.algorithm.parameters: if param.hidden: continue - widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = param.default + + wrapper = self.widget_wrappers[param.name] + if wrapper.implemented: + wrapper.setValue(value) + + widget = wrapper.widget if isinstance(param, ( ParameterRaster, ParameterVector, @@ -512,7 +523,6 @@ def setPreviousValues(self): ParameterTableField, ParameterSelection, ParameterNumber, - ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint, @@ -567,7 +577,7 @@ def createAlgorithm(self): for param in params: if param.hidden: continue - if not self.setParamValue(alg, param, self.valueItems[param.name]): + if not self.setParamValue(alg, param, self.widget_wrappers[param.name]): self.bar.pushMessage("Error", "Wrong or missing value for parameter '%s'" % param.description, level=QgsMessageBar.WARNING) return None @@ -723,17 +733,15 @@ def setParamCrsValue(self, alg, param, widget): alg.params[param.name] = value return True - def setParamValue(self, alg, param, widget): + def setParamValue(self, alg, param, wrapper): + if wrapper.implemented: + alg.params[param.name] = wrapper.value() + return True + + widget = wrapper.widget if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) - elif isinstance(param, ParameterBoolean): - if widget.currentIndex() < 2: - value = widget.currentIndex() == 0 - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): From 6158e9b3405090fa2e93e16a6248882ebf21778c Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Wed, 24 Aug 2016 15:23:25 +0200 Subject: [PATCH 115/897] Add CrsWidgetWrapper --- python/plugins/processing/core/parameters.py | 8 ++++++-- .../plugins/processing/gui/AlgorithmDialog.py | 3 +-- .../processing/gui/CrsSelectionPanel.py | 6 ++++-- .../plugins/processing/gui/ParametersPanel.py | 2 -- python/plugins/processing/gui/wrappers.py | 19 +++++++++++++++++++ 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index c444927948bb..a243a99118e3 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -162,12 +162,16 @@ def getAsScriptCode(self): class ParameterCrs(Parameter): - def __init__(self, name='', description='', default=None, optional=False): + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.CrsWidgetWrapper' + } + + def __init__(self, name='', description='', default=None, optional=False, metadata={}): '''The value is a string that uniquely identifies the coordinate reference system. Typically it is the auth id of the CRS (if the authority is EPSG) or proj4 string of the CRS (in case of other authorities or user defined projections).''' - Parameter.__init__(self, name, description, default, optional) + Parameter.__init__(self, name, description, default, optional, metadata) def setValue(self, value): if value is None or value.strip() == '': diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 3a5531e6e4af..1a0f0354f84f 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -55,7 +55,6 @@ from processing.core.parameters import ParameterString from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterFile -from processing.core.parameters import ParameterCrs from processing.core.parameters import ParameterPoint from processing.core.parameters import ParameterGeometryPredicate @@ -172,7 +171,7 @@ def setParamValue(self, param, wrapper, alg=None): else: options = dataobjects.getVectorLayers([param.datatype], sorting=False) return param.setValue([options[i] for i in widget.selectedoptions]) - elif isinstance(param, (ParameterNumber, ParameterFile, ParameterCrs, + elif isinstance(param, (ParameterNumber, ParameterFile, ParameterExtent, ParameterPoint)): return param.setValue(widget.getValue()) elif isinstance(param, ParameterString): diff --git a/python/plugins/processing/gui/CrsSelectionPanel.py b/python/plugins/processing/gui/CrsSelectionPanel.py index a9b1cbf4f821..854c30d08ee4 100644 --- a/python/plugins/processing/gui/CrsSelectionPanel.py +++ b/python/plugins/processing/gui/CrsSelectionPanel.py @@ -39,14 +39,16 @@ class CrsSelectionPanel(BASE, WIDGET): - def __init__(self, default): + def __init__(self, default='EPSG:4326'): super(CrsSelectionPanel, self).__init__(None) self.setupUi(self) self.leText.setEnabled(False) self.btnSelect.clicked.connect(self.browseCRS) - self.crs = QgsCoordinateReferenceSystem(default).authid() + + # TODO: Default should be removed + self.crs = default self.updateText() def setAuthId(self, authid): diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index 09273997193b..07e086b27b78 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -411,8 +411,6 @@ def getWidgetFromParameter(self, param): item = ExtentSelectionPanel(self.parent, self.alg, param.default) elif isinstance(param, ParameterPoint): item = PointSelectionPanel(self.parent, param.default) - elif isinstance(param, ParameterCrs): - item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterString): if param.multiline: verticalLayout = QVBoxLayout() diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 62d1d5c96a7f..999b32622330 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -28,11 +28,14 @@ from inspect import isclass +from qgis.core import QgsCoordinateReferenceSystem from qgis.PyQt.QtWidgets import ( QCheckBox, QComboBox, ) +from processing.gui.CrsSelectionPanel import CrsSelectionPanel + DIALOG_STANDARD = 'standard' DIALOG_BATCH = 'batch' DIALOG_MODELER = 'modeler' @@ -115,3 +118,19 @@ def value(self): if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): return self.widget.itemData(self.widget.currentIndex()) + + +class CrsWidgetWrapper(WidgetWrapper): + + def createWidget(self, extra_values=[]): + return CrsSelectionPanel() + + def setValue(self, value): + if isinstance(value, basestring): # authId + self.widget.crs = value + else: + self.widget.crs = QgsCoordinateReferenceSystem(value).authid() + self.widget.updateText() + + def value(self): + return self.widget.getValue() From a69b358aa7abfc3eaa43f0d1da2ae817ba7c1bc4 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sat, 3 Sep 2016 02:25:30 +0200 Subject: [PATCH 116/897] Create dedicated widget wrapper for modeler --- python/plugins/processing/gui/wrappers.py | 36 +++--- .../modeler/ModelerParametersDialog.py | 120 ++++++++++++++---- 2 files changed, 113 insertions(+), 43 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 999b32622330..d4228927a0c1 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -41,7 +41,7 @@ DIALOG_MODELER = 'modeler' -def wrapper_from_param(param, dialog=DIALOG_STANDARD, extra_values=[]): +def wrapper_from_param(param, dialog=DIALOG_STANDARD): wrapper = param.metadata.get('widget_wrapper', None) # wrapper metadata should be a class path if isinstance(wrapper, basestring): @@ -50,7 +50,7 @@ def wrapper_from_param(param, dialog=DIALOG_STANDARD, extra_values=[]): wrapper = getattr(mod, tokens[-1]) # or directly a class object if isclass(wrapper): - wrapper = wrapper(param=param, dialog=dialog, extra_values=extra_values) + wrapper = wrapper(param=param, dialog=dialog) # or a wrapper instance return wrapper @@ -70,25 +70,36 @@ class WidgetWrapper(): implemented = True # TODO: Should be removed at the end - def __init__(self, param, dialog=DIALOG_STANDARD, extra_values=[]): + def __init__(self, param, dialog=DIALOG_STANDARD): self.param = param self.dialog = dialog - self.widget = self.createWidget(extra_values) + self.widget = self.createWidget() self.setValue(param.default) - def createWidget(self, extra_values=[]): + def comboValue(self): + return self.widget.itemData(self.widget.currentIndex()) + + def createWidget(self): pass def setValue(self, value): pass + def setComboValue(self, value): + values = [self.widget.itemData(i) for i in range(self.widget.count())] + try: + idx = values.index(value) + self.widget.setCurrentIndex(idx) + except ValueError: + pass + def value(self): pass class BooleanWidgetWrapper(WidgetWrapper): - def createWidget(self, extra_values=[]): + def createWidget(self): if self.dialog == DIALOG_STANDARD: return QCheckBox() @@ -96,8 +107,6 @@ def createWidget(self, extra_values=[]): widget = QComboBox() widget.addItem(widget.tr('Yes'), True) widget.addItem(widget.tr('No'), False) - for text, value in extra_values: - widget.addItem(text, value) return widget def setValue(self, value): @@ -105,24 +114,19 @@ def setValue(self, value): self.widget.setChecked(value) if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): - values = [self.widget.itemData(i) for i in range(self.widget.count())] - try: - idx = values.index(value) - self.widget.setCurrentIndex(idx) - except ValueError: - pass + self.setComboValue(value) def value(self): if self.dialog == DIALOG_STANDARD: return self.widget.isChecked() if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): - return self.widget.itemData(self.widget.currentIndex()) + return self.comboValue() class CrsWidgetWrapper(WidgetWrapper): - def createWidget(self, extra_values=[]): + def createWidget(self): return CrsSelectionPanel() def setValue(self, value): diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index bf966095ca7d..0b156d7dec5d 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -86,6 +86,77 @@ from processing.modeler.MultilineTextPanel import MultilineTextPanel from processing.tools import dataobjects +from qgis.core import QgsApplication +from qgis.PyQt.QtGui import QToolButton, QMenu, QAction + + +class ModelerWidgetWrapper(QWidget): + + def __init__(self, wrapper, model_values): + super(ModelerWidgetWrapper, self).__init__() + + self.wrapper = wrapper + self.widget = wrapper.widget + self.implemented = wrapper.implemented + self.model_values = model_values + + menu = QMenu() + fixed_value_action = QAction(self.tr('Fixed value'), menu) + fixed_value_action.triggered.connect(self.on_fixedValue) + menu.addAction(fixed_value_action) + menu.addSeparator() + for text, value in model_values: + model_value_action = QAction(text, menu) + model_value_action.setData(value) + model_value_action.triggered.connect(self.on_modelValue) + menu.addAction(model_value_action) + + self.mIconDataDefine = QgsApplication.getThemeIcon("/mIconDataDefine.svg") + self.mIconDataDefineOn = QgsApplication.getThemeIcon("/mIconDataDefineOn.svg") + + button = QToolButton() + button.setIcon(self.mIconDataDefine) + button.setPopupMode(QToolButton.InstantPopup) + button.setMenu(menu) + self.button = button + + label = QLabel() + label.hide() + self.label = label + + layout = QHBoxLayout() + layout.addWidget(button, 0) + layout.addWidget(label, 1) + layout.addWidget(wrapper.widget, 1) + self.setLayout(layout) + + def on_fixedValue(self): + self.button.setIcon(self.mIconDataDefine) + self.label.hide() + self.wrapper.widget.show() + + def on_modelValue(self): + action = self.sender() + self.setValue(action.data()) + + def setValue(self, value): + for text, val in self.model_values: + if val == value: + self.model_value = value + self.button.setIcon(self.mIconDataDefineOn) + self.label.setText(text) + self.label.show() + self.wrapper.widget.hide() + return + self.wrapper.setValue(value) + self.on_fixedValue() + + def value(self): + if self.label.isVisible(): + return self.model_value + else: + return self.wrapper.value() + class ModelerParametersDialog(QDialog): @@ -166,8 +237,10 @@ def setupUi(self): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label + wrapper = self.getWidgetWrapperFromParameter(param) self.widget_wrappers[param.name] = wrapper + widget = wrapper.widget self.valueItems[param.name] = widget if param.name in list(tooltips.keys()): @@ -178,10 +251,11 @@ def setupUi(self): widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) - widget.setVisible(self.showAdvanced) + wrapper.setVisible(self.showAdvanced) self.widgets[param.name] = widget + self.verticalLayout.addWidget(label) - self.verticalLayout.addWidget(widget) + self.verticalLayout.addWidget(wrapper) for output in self._alg.outputs: if output.hidden: @@ -282,6 +356,12 @@ def showAdvancedParametersClicked(self): self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) + def getAvailableValuesForParam(self, param): + outputType = None + if isinstance(param, ParameterCrs): + outputType = OutputCrs + return self.getAvailableValuesOfType(param.__class__, outputType) + def getAvailableValuesOfType(self, paramType, outType=None, dataType=None): values = [] inputs = self.model.inputs @@ -317,18 +397,19 @@ def resolveValueDescription(self, value): return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) def getWidgetWrapperFromParameter(self, param): - extra_values = [] - values = self.getAvailableValuesOfType(param.__class__, None) + wrapper = wrapper_from_param(param, DIALOG_MODELER) + if wrapper is None: + widget = self.getWidgetFromParameter(param) + wrapper = NotYetImplementedWidgetWrapper(param, widget) + + model_values = [] + values = self.getAvailableValuesForParam(param) for value in values: - extra_values.append((self.resolveValueDescription(value), value)) + model_values.append((self.resolveValueDescription(value), value)) - wrapper = wrapper_from_param(param, DIALOG_MODELER, extra_values) - if wrapper is not None: - return wrapper + input_wrapper = ModelerWidgetWrapper(wrapper, model_values) + return input_wrapper - widget = self.getWidgetFromParameter(param) - wrapper = NotYetImplementedWidgetWrapper(param, widget) - return wrapper def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): @@ -411,11 +492,6 @@ def getWidgetFromParameter(self, param): for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(str(param.default)) - elif isinstance(param, ParameterCrs): - item = QComboBox() - values = self.getAvailableValuesOfType(ParameterCrs, OutputCrs) - for v in values: - item.addItem(self.resolveValueDescription(v), v) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) @@ -514,6 +590,7 @@ def setPreviousValues(self): wrapper = self.widget_wrappers[param.name] if wrapper.implemented: wrapper.setValue(value) + continue widget = wrapper.widget if isinstance(param, ( @@ -724,15 +801,6 @@ def setParamPointValue(self, alg, param, widget): alg.params[param.name] = value return True - def setParamCrsValue(self, alg, param, widget): - idx = widget.currentIndex() - if idx < 0: - return False - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True - def setParamValue(self, alg, param, wrapper): if wrapper.implemented: alg.params[param.name] = wrapper.value() @@ -758,8 +826,6 @@ def setParamValue(self, alg, param, wrapper): elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True - elif isinstance(param, ParameterCrs): - return self.setParamCrsValue(alg, param, widget) elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: From 8cc9a50a521bf3879700bb7b9a5ba32dc767bf74 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 5 Sep 2016 12:59:21 +0200 Subject: [PATCH 117/897] [processing] moved script syntax from script algorithm class to parameters classes --- python/plugins/processing/core/parameters.py | 211 +++++++++++++++++- .../processing/script/ScriptAlgorithm.py | 139 +----------- 2 files changed, 206 insertions(+), 144 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index a243a99118e3..b276411a5734 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -30,6 +30,7 @@ import sys import os +import inspect from qgis.PyQt.QtCore import QCoreApplication from qgis.core import QgsRasterLayer, QgsVectorLayer @@ -37,19 +38,23 @@ from processing.tools.system import isWindows from processing.tools import dataobjects - -def getParameterFromString(s): - tokens = s.split("|") - params = [t if str(t) != str(None) else None for t in tokens[1:]] - clazz = getattr(sys.modules[__name__], tokens[0]) - return clazz(*params) - - def parseBool(s): if s is None or s == str(None).lower(): return None return str(s).lower() == str(True).lower() +def _splitParameterOptions(line): + tokens = line.split('=', 1) + if tokens[1].lower().strip().startswith('optional'): + isOptional = True + definition = tokens[1].strip()[len('optional') + 1:] + else: + isOptional = False + definition = tokens[1] + return isOptional, tokens[0], definition + +def _createDescriptiveName(s): + return s.replace('_', ' ') class Parameter(object): @@ -128,8 +133,7 @@ def tr(self, string, context=''): if context == '': context = 'Parameter' return QCoreApplication.translate(context, string) - - + class ParameterBoolean(Parameter): default_metadata = { @@ -158,6 +162,20 @@ def getAsScriptCode(self): param_type += 'optional ' param_type += 'boolean ' return '##' + self.name + '=' + param_type + str(self.default) + + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.startswith("boolean"): + descName = _createDescriptiveName(name) + default = definition.strip()[len('boolean') + 1:] + if default: + param = ParameterBoolean(name, descName, default) + else: + param = ParameterBoolean(name, descName) + param.optional = isOptional + return param + class ParameterCrs(Parameter): @@ -194,6 +212,16 @@ def getAsScriptCode(self): param_type += 'crs ' return '##' + self.name + '=' + param_type + str(self.default) + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.startswith("crs"): + descName = _createDescriptiveName(name) + default = definition.strip()[len('crs') + 1:] + if default: + return ParameterCrs(name, descName, default, isOptional) + else: + return ParameterCrs(name, descName, None, isOptional) class ParameterDataObject(Parameter): @@ -243,6 +271,14 @@ def getAsScriptCode(self): param_type += 'optional ' param_type += 'extent' return '##' + self.name + '=' + param_type + + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.startswith("extent"): + descName = _createDescriptiveName(name) + default = definition.strip()[len('extent') + 1:] or None + return ParameterExtent(name, descName, default, isOptional) class ParameterPoint(Parameter): @@ -279,6 +315,14 @@ def getAsScriptCode(self): param_type += 'point' return '##' + self.name + '=' + param_type + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.startswith("point"): + descName = _createDescriptiveName(name) + default = definition.strip()[len('point') + 1:] or None + return ParameterPoint(name, descName, default, isOptional) + class ParameterFile(Parameter): @@ -318,6 +362,13 @@ def getAsScriptCode(self): param_type += 'file' return '##' + self.name + '=' + param_type + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.startswith("file") or definition.startswith("folder"): + descName = _createDescriptiveName(name) + return ParameterFile(name, descName, definition.startswith("folder"), isOptional) + class ParameterFixedTable(Parameter): @@ -356,6 +407,14 @@ def tableToString(table): tablestring = tablestring[:-1] return tablestring + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.startswith("point"): + descName = _createDescriptiveName(name) + default = definition.strip()[len('point') + 1:] or None + return ParameterPoint(name, descName, default, isOptional) + class ParameterMultipleInput(ParameterDataObject): @@ -542,6 +601,17 @@ def getAsScriptCode(self): param_type += 'multiple vector' return '##' + self.name + '=' + param_type + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip() == 'multiple raster': + return ParameterMultipleInput(name, descName, + dataobjects.TYPE_RASTER, isOptional) + elif definition.lower().strip() == 'multiple vector': + return ParameterMultipleInput(name, definition, + dataobjects.TYPE_VECTOR_ANY, isOptional) + class ParameterNumber(Parameter): @@ -599,6 +669,13 @@ def getAsScriptCode(self): param_type += 'number' return '##' + self.name + '=' + param_type + str(self.default) + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip().startswith('number'): + default = definition.strip()[len('number') + 1:] or None + return ParameterNumber(name, descName, default=default, optional=isOptional) class ParameterRange(Parameter): @@ -701,6 +778,13 @@ def getAsScriptCode(self): param_type += 'raster' return '##' + self.name + '=' + param_type + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + print isOptional, name, definition + if definition.lower().strip().startswith('raster'): + return ParameterRaster(name, descName, optional=isOptional) class ParameterSelection(Parameter): @@ -744,7 +828,18 @@ def setValue(self, n): except: return False - + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip().startswith('selectionfromfile'): + options = definition.strip()[len('selectionfromfile '):].split(';') + return ParameterSelection(name, descName, options, isSource=True, optional=isOptional) + elif definition.lower().strip().startswith('selection'): + options = definition.strip()[len('selection '):].split(';') + return ParameterSelection(name, descName, options, optional=isOptional) + + class ParameterString(Parameter): NEWLINE = '\n' @@ -781,6 +876,22 @@ def getAsScriptCode(self): param_type += 'string' return '##' + self.name + '=' + param_type + self.default + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip().startswith('string'): + default = definition.strip()[len('string') + 1:] + if default: + return ParameterString(name, descName, default, optional=isOptional) + else: + return ParameterString(name, descName, optional=isOptional) + elif definition.lower().strip().startswith('longstring'): + default = definition.strip()[len('longstring') + 1:] + if default: + return ParameterString(name, descName, default, multiline=True, optional=isOptional) + else: + return ParameterString(name, descName, multiline=True, optional=isOptional) class ParameterTable(ParameterDataObject): @@ -853,6 +964,13 @@ def getAsScriptCode(self): param_type += 'table' return '##' + self.name + '=' + param_type + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip().startswith('table'): + return ParameterTable(name, descName, isOptional) + class ParameterTableField(Parameter): @@ -908,6 +1026,24 @@ def getAsScriptCode(self): return '##' + self.name + '=' + param_type + self.parent + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip().startswith('field'): + if definition.lower().strip().startswith('field number'): + parent = definition.strip()[len('field number') + 1:] + datatype = ParameterTableField.DATA_TYPE_NUMBER + elif definition.lower().strip().startswith('field string'): + parent = definition.strip()[len('field string') + 1:] + datatype = ParameterTableField.DATA_TYPE_STRING + else: + parent = definition.strip()[len('field') + 1:] + datatype = ParameterTableField.DATA_TYPE_ANY + + return ParameterTableField(name, descName, parent, datatype, isOptional) + + class ParameterTableMultipleField(Parameter): """A parameter representing several table fields. @@ -974,6 +1110,23 @@ def getAsScriptCode(self): param_type += 'multiple field ' return '##' + self.name + '=' + param_type + self.parent + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + if definition.lower().strip().startswith('multiple field'): + descName = _createDescriptiveName(name) + if definition.lower().strip().startswith('multiple field number'): + field = definition.strip()[len('multiple field number') + 1:] + datatype = ParameterTableMultipleField.DATA_TYPE_NUMBER + elif definition.lower().strip().startswith('multiple field string'): + field = definition.strip()[len('multiple field string') + 1:] + datatype = ParameterTableMultipleField.DATA_TYPE_STRING + else: + field = definition.strip()[len('multiple field') + 1:] + datatype = ParameterTableMultipleField.DATA_TYPE_ANY + + return ParameterTableMultipleField(name, descName, field, datatype, isOptional) + class ParameterVector(ParameterDataObject): @@ -1050,6 +1203,22 @@ def getAsScriptCode(self): param_type += 'vector' return '##' + self.name + '=' + param_type + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + if definition.lower().strip() == 'vector': + return ParameterVector(name, descName, + [dataobjects.TYPE_VECTOR_ANY], isOptional) + elif definition.lower().strip() == 'vector point': + return ParameterVector(name, descName, + [dataobjects.TYPE_VECTOR_POINT], isOptional) + elif definition.lower().strip() == 'vector line': + return ParameterVector(name, descName, + [dataobjects.TYPE_VECTOR_LINE], isOptional) + elif definition.lower().strip() == 'vector polygon': + return ParameterVector(name, descName, + [dataobjects.TYPE_VECTOR_POLYGON], isOptional) class ParameterGeometryPredicate(Parameter): @@ -1089,3 +1258,23 @@ def setValue(self, value): else: self.value = value return True + + +paramClasses = [c for c in sys.modules[__name__].__dict__.values() if inspect.isclass(c) and issubclass(c, Parameter)] + +def getParameterFromString(s): + print s + #Try the parameter definitions used in description files + if '|' in s: + tokens = s.split("|") + params = [t if unicode(t) != unicode(None) else None for t in tokens[1:]] + clazz = getattr(sys.modules[__name__], tokens[0]) + return clazz(*params) + else: #try script syntax + for paramClass in paramClasses: + try: + param = paramClass.fromScriptCode(s) + if param is not None: + return param + except AttributeError: + pass diff --git a/python/plugins/processing/script/ScriptAlgorithm.py b/python/plugins/processing/script/ScriptAlgorithm.py index de552a1b4484..95ad656122cb 100644 --- a/python/plugins/processing/script/ScriptAlgorithm.py +++ b/python/plugins/processing/script/ScriptAlgorithm.py @@ -146,12 +146,6 @@ def processParameterLine(self, line): out = None line = line.replace('#', '') - # If the line is in the format of the text description files for - # normal algorithms, then process it using parameter and output - # factories - if '|' in line: - self.processDescriptionParameterLine(line) - return if line == "nomodeler": self.showInModeler = False return @@ -170,15 +164,8 @@ def processParameterLine(self, line): if tokens[1].lower().strip().startswith('output'): outToken = tokens[1].strip()[len('output') + 1:] out = self.processOutputParameterToken(outToken) - - elif tokens[1].lower().strip().startswith('optional'): - optToken = tokens[1].strip()[len('optional') + 1:] - param = self.processInputParameterToken(optToken, tokens[0]) - if param: - param.optional = True - else: - param = self.processInputParameterToken(tokens[1], tokens[0]) + param = getParameterFromString(line) if param is not None: self.addParameter(param) @@ -191,125 +178,11 @@ def processParameterLine(self, line): self.tr('Could not load script: %s.\n' 'Problem with line "%s"', 'ScriptAlgorithm') % (self.descriptionFile or '', line)) - def processInputParameterToken(self, token, name): - param = None - - descName = self.createDescriptiveName(name) - - if token.lower().strip() == 'raster': - param = ParameterRaster(name, descName, False) - elif token.lower().strip() == 'vector': - param = ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_ANY]) - elif token.lower().strip() == 'vector point': - param = ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_POINT]) - elif token.lower().strip() == 'vector line': - param = ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_LINE]) - elif token.lower().strip() == 'vector polygon': - param = ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_POLYGON]) - elif token.lower().strip() == 'table': - param = ParameterTable(name, descName, False) - elif token.lower().strip() == 'multiple raster': - param = ParameterMultipleInput(name, descName, - dataobjects.TYPE_RASTER) - param.optional = False - elif token.lower().strip() == 'multiple vector': - param = ParameterMultipleInput(name, descName, - dataobjects.TYPE_VECTOR_ANY) - param.optional = False - elif token.lower().strip().startswith('selectionfromfile'): - options = token.strip()[len('selectionfromfile '):].split(';') - param = ParameterSelection(name, descName, options, isSource=True) - elif token.lower().strip().startswith('selection'): - options = token.strip()[len('selection '):].split(';') - param = ParameterSelection(name, descName, options) - elif token.lower().strip().startswith('boolean'): - default = token.strip()[len('boolean') + 1:] - if default: - param = ParameterBoolean(name, descName, default) - else: - param = ParameterBoolean(name, descName) - elif token.lower().strip() == 'extent': - param = ParameterExtent(name, descName) - elif token.lower().strip() == 'point': - param = ParameterPoint(name, descName) - elif token.lower().strip() == 'file': - param = ParameterFile(name, descName, False) - elif token.lower().strip() == 'folder': - param = ParameterFile(name, descName, True) - elif token.lower().strip().startswith('number'): - default = token.strip()[len('number') + 1:] - if default: - param = ParameterNumber(name, descName, default=default) - else: - param = ParameterNumber(name, descName) - elif token.lower().strip().startswith('field'): - if token.lower().strip().startswith('field number'): - field = token.strip()[len('field number') + 1:] - datatype = ParameterTableField.DATA_TYPE_NUMBER - elif token.lower().strip().startswith('field string'): - field = token.strip()[len('field string') + 1:] - datatype = ParameterTableField.DATA_TYPE_STRING - else: - field = token.strip()[len('field') + 1:] - datatype = ParameterTableField.DATA_TYPE_ANY - found = False - for p in self.parameters: - if p.name == field: - found = True - break - if found: - param = ParameterTableField( - name=name, - description=descName, - parent=field, - datatype=datatype - ) - elif token.lower().strip().startswith('multiple field'): - if token.lower().strip().startswith('multiple field number'): - field = token.strip()[len('multiple field number') + 1:] - datatype = ParameterTableMultipleField.DATA_TYPE_NUMBER - elif token.lower().strip().startswith('multiple field string'): - field = token.strip()[len('multiple field string') + 1:] - datatype = ParameterTableMultipleField.DATA_TYPE_STRING - else: - field = token.strip()[len('multiple field') + 1:] - datatype = ParameterTableMultipleField.DATA_TYPE_ANY - found = False - for p in self.parameters: - if p.name == field: - found = True - break - if found: - param = ParameterTableMultipleField( - name=name, - description=descName, - parent=field, - datatype=datatype - ) - elif token.lower().strip().startswith('string'): - default = token.strip()[len('string') + 1:] - if default: - param = ParameterString(name, descName, default) - else: - param = ParameterString(name, descName) - elif token.lower().strip().startswith('longstring'): - default = token.strip()[len('longstring') + 1:] - if default: - param = ParameterString(name, descName, default, multiline=True) - else: - param = ParameterString(name, descName, multiline=True) - elif token.lower().strip().startswith('crs'): - default = token.strip()[len('crs') + 1:] - if default: - param = ParameterCrs(name, descName, default) - else: - param = ParameterCrs(name, descName) - - return param + def processInputParameterLine(self, line): + for paramClass in paramClasses: + param = paramClass.fromScriptCode(line) + if param is not None: + return param def processOutputParameterToken(self, token): out = None From b298c76ee451e7a7941de54cca44724cc1b7fef0 Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 7 Sep 2016 14:30:20 +0200 Subject: [PATCH 118/897] [processing] implemented parameter widget wrappers Conflicts: python/plugins/processing/core/GeoAlgorithm.py python/plugins/processing/gui/ExtentSelectionPanel.py python/plugins/processing/modeler/ModelerParametersDialog.py --- .../plugins/processing/core/GeoAlgorithm.py | 104 +-- python/plugins/processing/core/parameters.py | 112 ++- .../plugins/processing/gui/AlgorithmDialog.py | 76 +- .../gui/BatchInputSelectionPanel.py | 23 +- python/plugins/processing/gui/BatchPanel.py | 94 +-- .../processing/gui/ExtentSelectionPanel.py | 20 +- .../processing/gui/NumberInputPanel.py | 7 +- .../plugins/processing/gui/ParametersPanel.py | 342 +-------- python/plugins/processing/gui/wrappers.py | 716 +++++++++++++++++- .../modeler/ModelerParametersDialog.py | 401 +--------- 10 files changed, 916 insertions(+), 979 deletions(-) diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index a993dbdd23ca..3301b7ba3078 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -42,8 +42,7 @@ from processing.core.ProcessingConfig import ProcessingConfig from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.SilentProgress import SilentProgress -from processing.core.parameters import ParameterExtent -from processing.core.parameters import ParameterRaster, ParameterVector, ParameterMultipleInput, ParameterTable, Parameter +from processing.core.parameters import ParameterRaster, ParameterVector, ParameterMultipleInput, ParameterTable, Parameter, ParameterExtent from processing.core.outputs import OutputVector, OutputRaster, OutputTable, OutputHTML, Output from processing.algs.gdal.GdalUtils import GdalUtils from processing.tools import dataobjects, vector @@ -363,56 +362,6 @@ def checkOutputFileExtensions(self): if ext not in exts + ['dbf']: out.value = out.value + '.' + exts[0] - def resolveTemporaryOutputs(self): - """Sets temporary outputs (output.value = None) with a - temporary file instead. - """ - for out in self.outputs: - if not out.hidden and out.value is None: - setTempOutput(out, self) - - def setOutputCRS(self): - layers = dataobjects.getAllLayers() - for param in self.parameters: - if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): - if param.value: - if isinstance(param, ParameterMultipleInput): - inputlayers = param.value.split(';') - else: - inputlayers = [param.value] - for inputlayer in inputlayers: - for layer in layers: - if layer.source() == inputlayer: - self.crs = layer.crs() - return - p = dataobjects.getObjectFromUri(inputlayer) - if p is not None: - self.crs = p.crs() - p = None - return - try: - from qgis.utils import iface - if iface is not None: - self.crs = iface.mapCanvas().mapSettings().destinationCrs() - except: - pass - - def resolveDataObjects(self): - layers = dataobjects.getAllLayers() - for param in self.parameters: - if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, - ParameterMultipleInput)): - if param.value: - if isinstance(param, ParameterMultipleInput): - inputlayers = param.value.split(';') - else: - inputlayers = [param.value] - for i, inputlayer in enumerate(inputlayers): - for layer in layers: - if layer.name() == inputlayer: - inputlayers[i] = layer.source() - break - param.setValue(";".join(inputlayers)) def canUseAutoExtent(self): for param in self.parameters: @@ -468,6 +417,57 @@ def addToRegion(self, layer, first): self.xmax = max(self.xmax, layer.extent().xMaximum()) self.ymin = min(self.ymin, layer.extent().yMinimum()) self.ymax = max(self.ymax, layer.extent().yMaximum()) + + def resolveTemporaryOutputs(self): + """Sets temporary outputs (output.value = None) with a + temporary file instead. + """ + for out in self.outputs: + if not out.hidden and out.value is None: + setTempOutput(out, self) + + def setOutputCRS(self): + layers = dataobjects.getAllLayers() + for param in self.parameters: + if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): + if param.value: + if isinstance(param, ParameterMultipleInput): + inputlayers = param.value.split(';') + else: + inputlayers = [param.value] + for inputlayer in inputlayers: + for layer in layers: + if layer.source() == inputlayer: + self.crs = layer.crs() + return + p = dataobjects.getObjectFromUri(inputlayer) + if p is not None: + self.crs = p.crs() + p = None + return + try: + from qgis.utils import iface + if iface is not None: + self.crs = iface.mapCanvas().mapSettings().destinationCrs() + except: + pass + + def resolveDataObjects(self): + layers = dataobjects.getAllLayers() + for param in self.parameters: + if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, + ParameterMultipleInput)): + if param.value: + if isinstance(param, ParameterMultipleInput): + inputlayers = param.value.split(';') + else: + inputlayers = [param.value] + for i, inputlayer in enumerate(inputlayers): + for layer in layers: + if layer.name() == inputlayer: + inputlayers[i] = layer.source() + break + param.setValue(";".join(inputlayers)) def checkInputCRS(self): """It checks that all input layers use the same CRS. If so, diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index b276411a5734..45f02f9c5fdd 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -30,7 +30,9 @@ import sys import os -import inspect +from inspect import isclass +from copy import deepcopy + from qgis.PyQt.QtCore import QCoreApplication from qgis.core import QgsRasterLayer, QgsVectorLayer @@ -52,7 +54,7 @@ def _splitParameterOptions(line): isOptional = False definition = tokens[1] return isOptional, tokens[0], definition - + def _createDescriptiveName(s): return s.replace('_', ' ') @@ -82,8 +84,8 @@ def __init__(self, name='', description='', default=None, optional=False, self.optional = parseBool(optional) # TODO: make deep copy and deep update - self.metadata = self.default_metadata.copy() - self.metadata.update(metadata) + self.metadata = deepcopy(self.default_metadata) + self.metadata.update(deepcopy(metadata)) def setValue(self, obj): """ @@ -133,7 +135,20 @@ def tr(self, string, context=''): if context == '': context = 'Parameter' return QCoreApplication.translate(context, string) - + + def wrapper(self, dialog, row=0, col=0): + wrapper = self.metadata.get('widget_wrapper', None) + # wrapper metadata should be a class path + if isinstance(wrapper, basestring): + tokens = wrapper.split('.') + mod = __import__('.'.join(tokens[:-1]), fromlist=[tokens[-1]]) + wrapper = getattr(mod, tokens[-1]) + # or directly a class object + if isclass(wrapper): + wrapper = wrapper(self, dialog, row, col) + # or a wrapper instance + return wrapper + class ParameterBoolean(Parameter): default_metadata = { @@ -162,7 +177,7 @@ def getAsScriptCode(self): param_type += 'optional ' param_type += 'boolean ' return '##' + self.name + '=' + param_type + str(self.default) - + @classmethod def fromScriptCode(self, line): isOptional, name, definition = _splitParameterOptions(line) @@ -175,7 +190,7 @@ def fromScriptCode(self, line): param = ParameterBoolean(name, descName) param.optional = isOptional return param - + class ParameterCrs(Parameter): @@ -236,9 +251,13 @@ def getValueAsCommandLineParameter(self): class ParameterExtent(Parameter): + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.ExtentWidgetWrapper' + } + USE_MIN_COVERING_EXTENT = 'USE_MIN_COVERING_EXTENT' - def __init__(self, name='', description='', default=None, optional=False): + def __init__(self, name='', description='', default=None, optional=True): Parameter.__init__(self, name, description, default, optional) # The value is a string in the form "xmin, xmax, ymin, ymax" @@ -271,7 +290,7 @@ def getAsScriptCode(self): param_type += 'optional ' param_type += 'extent' return '##' + self.name + '=' + param_type - + @classmethod def fromScriptCode(self, line): isOptional, name, definition = _splitParameterOptions(line) @@ -283,6 +302,10 @@ def fromScriptCode(self, line): class ParameterPoint(Parameter): + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.PointWidgetWrapper' + } + def __init__(self, name='', description='', default=None, optional=False): Parameter.__init__(self, name, description, default, optional) # The value is a string in the form "x, y" @@ -326,6 +349,10 @@ def fromScriptCode(self, line): class ParameterFile(Parameter): + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.FileWidgetWrapper' + } + def __init__(self, name='', description='', isFolder=False, optional=True, ext=None): Parameter.__init__(self, name, description, None, parseBool(optional)) self.ext = ext @@ -371,6 +398,7 @@ def fromScriptCode(self, line): class ParameterFixedTable(Parameter): + def __init__(self, name='', description='', numRows=3, cols=['value'], fixedNumOfRows=False, optional=False): @@ -423,6 +451,11 @@ class ParameterMultipleInput(ParameterDataObject): Its value is a string with substrings separated by semicolons, each of which represents the data source location of each element. """ + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.MultipleInputWidgetWrapper' + } + exported = None @@ -607,13 +640,18 @@ def fromScriptCode(self, line): descName = _createDescriptiveName(name) if definition.lower().strip() == 'multiple raster': return ParameterMultipleInput(name, descName, - dataobjects.TYPE_RASTER, isOptional) + dataobjects.TYPE_RASTER, isOptional) elif definition.lower().strip() == 'multiple vector': return ParameterMultipleInput(name, definition, dataobjects.TYPE_VECTOR_ANY, isOptional) - + class ParameterNumber(Parameter): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.NumberWidgetWrapper' + } + def __init__(self, name='', description='', minValue=None, maxValue=None, default=None, optional=False): @@ -716,6 +754,11 @@ def getValueAsCommandLineParameter(self): class ParameterRaster(ParameterDataObject): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.RasterWidgetWrapper' + } + def __init__(self, name='', description='', optional=False, showSublayersDialog=True): ParameterDataObject.__init__(self, name, description, None, optional) @@ -787,6 +830,11 @@ def fromScriptCode(self, line): return ParameterRaster(name, descName, optional=isOptional) class ParameterSelection(Parameter): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.SelectionWidgetWrapper' + } + def __init__(self, name='', description='', options=[], default=None, isSource=False, optional=False): @@ -838,9 +886,14 @@ def fromScriptCode(self, line): elif definition.lower().strip().startswith('selection'): options = definition.strip()[len('selection '):].split(';') return ParameterSelection(name, descName, options, optional=isOptional) - - + + class ParameterString(Parameter): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.StringWidgetWrapper' + } + NEWLINE = '\n' ESCAPED_NEWLINE = '\\n' @@ -894,6 +947,11 @@ def fromScriptCode(self, line): return ParameterString(name, descName, multiline=True, optional=isOptional) class ParameterTable(ParameterDataObject): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.TableWidgetWrapper' + } + def __init__(self, name='', description='', optional=False): ParameterDataObject.__init__(self, name, description, None, optional) @@ -976,11 +1034,13 @@ class ParameterTableField(Parameter): """A parameter representing a table field. Its value is a string that represents the name of the field. - - In a script you can use it with - ##Field=[optional] field [number|string] Parentinput """ + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.TableFieldWidgetWrapper' + } + + DATA_TYPE_NUMBER = 0 DATA_TYPE_STRING = 1 DATA_TYPE_ANY = -1 @@ -1040,10 +1100,10 @@ def fromScriptCode(self, line): else: parent = definition.strip()[len('field') + 1:] datatype = ParameterTableField.DATA_TYPE_ANY - + return ParameterTableField(name, descName, parent, datatype, isOptional) - - + + class ParameterTableMultipleField(Parameter): """A parameter representing several table fields. @@ -1129,6 +1189,11 @@ def fromScriptCode(self, line): class ParameterVector(ParameterDataObject): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.VectorWidgetWrapper' + } + def __init__(self, name='', description='', datatype=[-1], optional=False): @@ -1139,6 +1204,7 @@ def __init__(self, name='', description='', datatype=[-1], datatype = [int(t) for t in datatype.split(',')] self.datatype = datatype self.exported = None + self.allowOnlyOpenedLayers = False def setValue(self, obj): self.exported = None @@ -1260,20 +1326,20 @@ def setValue(self, value): return True -paramClasses = [c for c in sys.modules[__name__].__dict__.values() if inspect.isclass(c) and issubclass(c, Parameter)] +paramClasses = [c for c in sys.modules[__name__].__dict__.values() if isclass(c) and issubclass(c, Parameter)] def getParameterFromString(s): print s - #Try the parameter definitions used in description files + # Try the parameter definitions used in description files if '|' in s: tokens = s.split("|") params = [t if unicode(t) != unicode(None) else None for t in tokens[1:]] clazz = getattr(sys.modules[__name__], tokens[0]) return clazz(*params) - else: #try script syntax + else: # try script syntax for paramClass in paramClasses: try: - param = paramClass.fromScriptCode(s) + param = paramClass.fromScriptCode(s) if param is not None: return param except AttributeError: diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 1a0f0354f84f..7ad7a0df4c28 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -85,8 +85,8 @@ def __init__(self, alg): self.cornerWidget.setLayout(layout) self.tabWidget.setCornerWidget(self.cornerWidget) - QgsMapLayerRegistry.instance().layerWasAdded.connect(self.mainWidget.layerAdded) - QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.mainWidget.layersWillBeRemoved) + QgsMapLayerRegistry.instance().layerWasAdded.connect(self.mainWidget.layerRegistryChanged) + QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.mainWidget.layerRegistryChanged) def runAsBatch(self): self.close() @@ -101,17 +101,9 @@ def setParamValues(self): for param in params: if param.hidden: continue - if isinstance(param, ParameterExtent): - continue - wrapper = self.mainWidget.widget_wrappers[param.name] + wrapper = self.mainWidget.wrappers[param.name] if not self.setParamValue(param, wrapper): - raise AlgorithmDialogBase.InvalidParameterValue(param, wrapper) - - for param in params: - if isinstance(param, ParameterExtent): - wrapper = self.mainWidget.widget_wrappers[param.name] - if not self.setParamValue(param, wrapper): - raise AlgorithmDialogBase.InvalidParameterValue(param, wrapper) + raise AlgorithmDialogBase.InvalidParameterValue(param, wrapper.widget) for output in outputs: if output.hidden: @@ -135,61 +127,7 @@ def evaluateExpression(self, text): return result def setParamValue(self, param, wrapper, alg=None): - if wrapper.implemented: - return param.setValue(wrapper.value()) - - widget = wrapper.widget - if isinstance(param, ParameterRaster): - return param.setValue(widget.getValue()) - elif isinstance(param, (ParameterVector, ParameterTable)): - try: - return param.setValue(widget.itemData(widget.currentIndex())) - except: - return param.setValue(widget.getValue()) - elif isinstance(param, ParameterSelection): - return param.setValue(widget.currentIndex()) - elif isinstance(param, ParameterFixedTable): - return param.setValue(widget.table) - elif isinstance(param, ParameterRange): - return param.setValue(widget.getValue()) - elif isinstance(param, ParameterTableField): - if param.optional and widget.currentIndex() == 0: - return param.setValue(None) - return param.setValue(widget.currentText()) - elif isinstance(param, ParameterTableMultipleField): - if param.optional and len(list(widget.get_selected_items())) == 0: - return param.setValue(None) - return param.setValue(list(widget.get_selected_items())) - elif isinstance(param, ParameterMultipleInput): - if param.datatype == dataobjects.TYPE_FILE: - return param.setValue(widget.selectedoptions) - else: - if param.datatype == dataobjects.TYPE_RASTER: - options = dataobjects.getRasterLayers(sorting=False) - elif param.datatype == dataobjects.TYPE_VECTOR_ANY: - options = dataobjects.getVectorLayers(sorting=False) - else: - options = dataobjects.getVectorLayers([param.datatype], sorting=False) - return param.setValue([options[i] for i in widget.selectedoptions]) - elif isinstance(param, (ParameterNumber, ParameterFile, - ParameterExtent, ParameterPoint)): - return param.setValue(widget.getValue()) - elif isinstance(param, ParameterString): - if param.multiline: - text = str(widget.toPlainText()) - else: - text = widget.text() - - if param.evaluateExpressions: - try: - text = self.evaluateExpression(text) - except: - pass - return param.setValue(text) - elif isinstance(param, ParameterGeometryPredicate): - return param.setValue(widget.value()) - else: - return param.setValue(str(widget.text())) + return param.setValue(wrapper.value()) def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) @@ -289,6 +227,6 @@ def finish(self): '\nOpen the results dialog to check it.')) def closeEvent(self, evt): - QgsMapLayerRegistry.instance().layerWasAdded.disconnect(self.mainWidget.layerAdded) - QgsMapLayerRegistry.instance().layersWillBeRemoved.disconnect(self.mainWidget.layersWillBeRemoved) + QgsMapLayerRegistry.instance().layerWasAdded.disconnect(self.mainWidget.layerRegistryChanged) + QgsMapLayerRegistry.instance().layersWillBeRemoved.disconnect(self.mainWidget.layerRegistryChanged) super(AlgorithmDialog, self).closeEvent(evt) diff --git a/python/plugins/processing/gui/BatchInputSelectionPanel.py b/python/plugins/processing/gui/BatchInputSelectionPanel.py index ef96de3ddf54..21d40bbadc0e 100644 --- a/python/plugins/processing/gui/BatchInputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchInputSelectionPanel.py @@ -45,11 +45,10 @@ class BatchInputSelectionPanel(QWidget): - def __init__(self, param, row, col, panel): + def __init__(self, param, row, col, dialog): super(BatchInputSelectionPanel, self).__init__(None) self.param = param - self.panel = panel - self.table = self.panel.tblParameters + self.dialog = dialog self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) @@ -67,6 +66,12 @@ def __init__(self, param, row, col, panel): self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout) + def _panel(self): + return self.dialog.mainDialog() + + def _table(self): + return self._panel().tblParameters + def showPopupMenu(self): popupmenu = QMenu() @@ -108,11 +113,11 @@ def showLayerSelectionDialog(self): if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(layers[idx].name() for idx in selected)) else: - rowdif = len(selected) - (self.table.rowCount() - self.row) + rowdif = len(selected) - (self._table().rowCount() - self.row) for i in range(rowdif): - self.panel.addRow() + self._panel().addRow() for i, layeridx in enumerate(selected): - self.table.cellWidget(i + self.row, + self._table().cellWidget(i + self.row, self.col).setText(layers[layeridx].name()) def showFileSelectionDialog(self): @@ -141,11 +146,11 @@ def showFileSelectionDialog(self): if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(str(f) for f in files)) else: - rowdif = len(files) - (self.table.rowCount() - self.row) + rowdif = len(files) - (self._table().rowCount() - self.row) for i in range(rowdif): - self.panel.addRow() + self._panel().addRow() for i, f in enumerate(files): - self.table.cellWidget(i + self.row, + self._table().cellWidget(i + self.row, self.col).setText(f) def setText(self, text): diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index 927adef51367..58d8441c7178 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -36,11 +36,7 @@ from qgis.core import QgsApplication -from processing.gui.wrappers import ( - DIALOG_BATCH, - wrapper_from_param, - NotYetImplementedWidgetWrapper, -) +from processing.gui.wrappers import NotYetImplementedWidgetWrapper from processing.gui.FileSelectionPanel import FileSelectionPanel from processing.gui.CrsSelectionPanel import CrsSelectionPanel @@ -77,7 +73,7 @@ def __init__(self, parent, alg): super(BatchPanel, self).__init__(None) self.setupUi(self) - self.widget_wrappers = [] + self.wrappers = [] self.btnAdvanced.hide() @@ -148,45 +144,15 @@ def initWidgets(self): self.tblParameters.horizontalHeader().setStretchLastSection(True) def getWidgetWrapperFromParameter(self, param, row, col): - wrapper = wrapper_from_param(param) # , DIALOG_BATCH) - if wrapper is not None: - return wrapper + return param.wrapper(self.parent, row, col) - widget = self.getWidgetFromParameter(param, row, col) - wrapper = NotYetImplementedWidgetWrapper(param, widget) - return wrapper def getWidgetFromParameter(self, param, row, col): - if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, - ParameterMultipleInput)): - item = BatchInputSelectionPanel(param, row, col, self) - elif isinstance(param, ParameterSelection): - item = QComboBox() - item.addItems(param.options) - elif isinstance(param, ParameterFixedTable): - item = FixedTablePanel(param) - elif isinstance(param, ParameterExtent): - item = ExtentSelectionPanel(self.parent, self.alg, param.default) - elif isinstance(param, ParameterPoint): - item = PointSelectionPanel(self.parent, param.default) - elif isinstance(param, ParameterCrs): - item = CrsSelectionPanel(param.default) - elif isinstance(param, ParameterFile): - item = FileSelectionPanel(param.isFolder) - elif isinstance(param, ParameterGeometryPredicate): + if isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates, rows=1) width = max(self.tblParameters.columnWidth(col), item.sizeHint().width()) self.tblParameters.setColumnWidth(col, width) - else: - item = QLineEdit() - if param.default is not None: - try: - item.setText(str(param.default)) - except: - pass - - return item def load(self): filename, selected_filter = QFileDialog.getOpenFileName(self, @@ -211,8 +177,8 @@ def load(self): continue if param.name in params: value = params[param.name] - wrapper = self.widget_wrappers[row][column] - self.setValueInWidgetWrapper(wrapper, value) + wrapper = self.wrappers[row][column] + wrapper.setValue(value) column += 1 for out in self.alg.outputs: @@ -221,7 +187,7 @@ def load(self): if out.name in outputs: value = outputs[out.name] widget = self.tblParameters.cellWidget(row, column) - self.setValueInWidget(widget, value) + widget.setValue(value) column += 1 except TypeError: QMessageBox.critical( @@ -235,22 +201,14 @@ def setValueInWidgetWrapper(self, wrapper, value): self.setValueInWidget(wrapper.widget, value) def setValueInWidget(self, widget, value): - if isinstance(widget, (BatchInputSelectionPanel, QLineEdit, FileSelectionPanel)): - widget.setText(str(value)) - elif isinstance(widget, (BatchOutputSelectionPanel, GeometryPredicateSelectionPanel)): - widget.setValue(str(value)) - - elif isinstance(widget, QComboBox): - idx = widget.findText(str(value)) - if idx != -1: - widget.setCurrentIndex(idx) + if isinstance(widget, (BatchOutputSelectionPanel, GeometryPredicateSelectionPanel)): + widget.setValue(unicode(value)) elif isinstance(widget, ExtentSelectionPanel): if value is not None: widget.setExtentFromString(value) else: widget.setExtentFromString('') - elif isinstance(widget, CrsSelectionPanel): - widget.setAuthId(value) + def save(self): toSave = [] @@ -265,7 +223,7 @@ def save(self): if isinstance(param, ParameterExtent): col += 1 continue - wrapper = self.widget_wrappers[row][col] + wrapper = self.wrappers[row][col] if not self.setParamValue(param, wrapper, alg): self.parent.lblProgress.setText( self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) @@ -277,7 +235,7 @@ def save(self): if param.hidden: continue if isinstance(param, ParameterExtent): - wrapper = self.widget_wrappers[row][col] + wrapper = self.wrappers[row][col] if not self.setParamValue(param, wrapper, alg): self.parent.lblProgress.setText( self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) @@ -313,29 +271,17 @@ def setParamValue(self, param, wrapper, alg=None): return param.setValue(wrapper.value()) widget = wrapper.widget - if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, - ParameterMultipleInput)): - value = widget.getText() - if str(value).strip() == '': - value = None - return param.setValue(value) - elif isinstance(param, ParameterSelection): - return param.setValue(widget.currentIndex()) - elif isinstance(param, ParameterFixedTable): - return param.setValue(widget.table) - elif isinstance(param, ParameterExtent): + if isinstance(param, ParameterExtent): if alg is not None: widget.useNewAlg(alg) return param.setValue(widget.getValue()) - elif isinstance(param, (ParameterCrs, ParameterFile)): - return param.setValue(widget.getValue()) elif isinstance(param, ParameterGeometryPredicate): return param.setValue(widget.value()) else: return param.setValue(widget.text()) def setCellWrapper(self, row, column, wrapper): - self.widget_wrappers[row][column] = wrapper + self.wrappers[row][column] = wrapper self.tblParameters.setCellWidget(row, column, wrapper.widget) def addRow(self): @@ -369,12 +315,12 @@ def addRow(self): self.tblParameters.setCellWidget(row, column, item) def removeRows(self): - #~ self.tblParameters.setUpdatesEnabled(False) - #~ indexes = self.tblParameters.selectionModel().selectedIndexes() - #~ indexes.sort() - #~ for i in reversed(indexes): - #~ self.tblParameters.model().removeRow(i.row()) - #~ self.tblParameters.setUpdatesEnabled(True) + # ~ self.tblParameters.setUpdatesEnabled(False) + # ~ indexes = self.tblParameters.selectionModel().selectedIndexes() + # ~ indexes.sort() + # ~ for i in reversed(indexes): + # ~ self.tblParameters.model().removeRow(i.row()) + # ~ self.tblParameters.setUpdatesEnabled(True) if self.tblParameters.rowCount() > 2: self.widget_wrappers.pop() self.tblParameters.setRowCount(self.tblParameters.rowCount() - 1) diff --git a/python/plugins/processing/gui/ExtentSelectionPanel.py b/python/plugins/processing/gui/ExtentSelectionPanel.py index 89437637ea37..dce7080c9cde 100644 --- a/python/plugins/processing/gui/ExtentSelectionPanel.py +++ b/python/plugins/processing/gui/ExtentSelectionPanel.py @@ -50,13 +50,13 @@ class ExtentSelectionPanel(BASE, WIDGET): - def __init__(self, dialog, alg, default=None): + def __init__(self, dialog, param): super(ExtentSelectionPanel, self).__init__(None) self.setupUi(self) self.dialog = dialog - self.alg = alg - if alg.canUseAutoExtent(): + self.param = param + if self.param.optional: if hasattr(self.leText, 'setPlaceholderText'): self.leText.setPlaceholderText( self.tr('[Leave blank to use min covering extent]')) @@ -68,18 +68,19 @@ def __init__(self, dialog, alg, default=None): self.tool = RectangleMapTool(canvas) self.tool.rectangleCreated.connect(self.updateExtent) - if default: - tokens = str(default).split(',') + if param.default: + tokens = param.default.split(',') if len(tokens) == 4: try: float(tokens[0]) float(tokens[1]) float(tokens[2]) float(tokens[3]) - self.leText.setText(str(default)) + self.leText.setText(param.default) except: pass + def selectExtent(self): popupmenu = QMenu() useLayerExtentAction = QAction( @@ -93,7 +94,7 @@ def selectExtent(self): selectOnCanvasAction.triggered.connect(self.selectOnCanvas) useLayerExtentAction.triggered.connect(self.useLayerExtent) - if self.canUseAutoExtent(): + if self.param.optional: useMincoveringExtentAction = QAction( self.tr('Use min covering extent from input layers'), self.btnSelect) @@ -153,9 +154,10 @@ def setValueFromRect(self, r): self.dialog.activateWindow() def getValue(self): - if str(self.leText.text()).strip() == '': + if str(self.leText.text()).strip() != '': + return str(self.leText.text()) + else: return None - return str(self.leText.text()) def setExtentFromString(self, s): self.leText.setText(s) diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index e9dcc759a977..3c3c55a3472c 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -62,7 +62,7 @@ def __init__(self, number, minimum, maximum, isInteger): if self.isInteger: self.spnValue.setDecimals(0) else: - #Guess reasonable step value + # Guess reasonable step value if (maximum == 0 or maximum) and (minimum == 0 or minimum): self.spnValue.setSingleStep(self.calculateStep(minimum, maximum)) @@ -75,7 +75,7 @@ def __init__(self, number, minimum, maximum, isInteger): else: self.spnValue.setMinimum(-99999999) - #Set default value + # Set default value if number == 0 or number: self.spnValue.setValue(float(number)) self.spnValue.setClearValue(float(number)) @@ -149,6 +149,9 @@ def expressionContext(self): def getValue(self): return self.spnValue.value() + def setValue(self, value): + self.spnValue.setValue(value) + def calculateStep(self, minimum, maximum): valueRange = maximum - minimum if valueRange <= 1.0: diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index 07e086b27b78..f72835091a5f 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -42,10 +42,7 @@ from processing.core.ProcessingConfig import ProcessingConfig -from processing.gui.wrappers import ( - wrapper_from_param, - NotYetImplementedWidgetWrapper, - ) +from processing.gui.wrappers import NotYetImplementedWidgetWrapper from processing.gui.OutputSelectionPanel import OutputSelectionPanel from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel @@ -82,8 +79,6 @@ from processing.core.outputs import OutputTable from processing.core.outputs import OutputVector -from processing.tools import dataobjects - pluginPath = os.path.split(os.path.dirname(__file__))[0] WIDGET, BASE = uic.loadUiType( os.path.join(pluginPath, 'ui', 'widgetParametersPanel.ui')) @@ -105,7 +100,7 @@ def __init__(self, parent, alg): self.parent = parent self.alg = alg self.valueItems = {} - self.widget_wrappers = {} + self.wrappers = {} self.labels = {} self.widgets = {} self.checkBoxes = {} @@ -114,69 +109,9 @@ def __init__(self, parent, alg): self.initWidgets() - def layerAdded(self, layer): - if layer.type() == QgsMapLayer.VectorLayer: - for param in self.alg.parameters: - if param.hidden: - continue - if isinstance(param, ParameterVector): - if dataobjects.canUseVectorLayer(layer, param.datatype): - widget = self.valueItems[param.name] - if isinstance(widget, InputLayerSelectorPanel): - widget = widget.cmbText - widget.addItem(self.getExtendedLayerName(layer), layer) - elif layer.type() == QgsMapLayer.RasterLayer and dataobjects.canUseRasterLayer(layer): - for param in self.alg.parameters: - if param.hidden: - continue - if isinstance(param, ParameterRaster): - widget = self.valueItems[param.name].cmbText - widget.addItem(self.getExtendedLayerName(layer), layer) - - self.updateMultipleInputs() - - def layersWillBeRemoved(self, layers): - for layer in layers: - self.layerRemoved(layer) - - def layerRemoved(self, layer): - layer = QgsMapLayerRegistry.instance().mapLayer(layer) - widget = None - if layer.type() == QgsMapLayer.VectorLayer: - for param in self.alg.parameters: - if param.hidden: - continue - if isinstance(param, ParameterVector): - widget = self.valueItems[param.name] - if isinstance(widget, InputLayerSelectorPanel): - widget = widget.cmbText - - elif layer.type() == QgsMapLayer.RasterLayer: - for param in self.alg.parameters: - if param.hidden: - continue - if isinstance(param, ParameterRaster): - widget = self.valueItems[param.name].cmbText - - if widget is not None: - idx = widget.findData(layer) - if idx != -1: - widget.removeItem(idx) - - self.updateMultipleInputs() - - def updateMultipleInputs(self): - for param in self.alg.parameters: - if isinstance(param, ParameterMultipleInput) and param.datatype != dataobjects.TYPE_FILE: - if param.datatype == dataobjects.TYPE_RASTER: - options = dataobjects.getRasterLayers(sorting=False) - elif param.datatype == dataobjects.TYPE_VECTOR_ANY: - options = dataobjects.getVectorLayers(sorting=False) - else: - options = dataobjects.getVectorLayers([param.datatype], sorting=False) - opts = [self.getExtendedLayerName(opt) for opt in options] - widget = self.valueItems[param.name] - widget.updateForOptions(opts) + def layerRegistryChanged(self, layers): + for wrapper in self.wrappers.values(): + wrapper.refresh() def initWidgets(self): # If there are advanced parameters — show corresponding groupbox @@ -201,12 +136,11 @@ def initWidgets(self): pass wrapper = self.getWidgetWrapperFromParameter(param) - self.widget_wrappers[param.name] = wrapper + self.wrappers[param.name] = wrapper self.valueItems[param.name] = wrapper.widget widget = wrapper.widget - if isinstance(param, ParameterVector) and \ - not self.alg.allowOnlyOpenedLayers: + if isinstance(param, ParameterVector): layout = QHBoxLayout() layout.setSpacing(2) layout.setMargin(0) @@ -222,28 +156,21 @@ def initWidgets(self): widget = QWidget() widget.setLayout(layout) + print wrapper tooltips = self.alg.getParameterDescriptions() widget.setToolTip(tooltips.get(param.name, param.description)) - if isinstance(widget, QCheckBox): - widget.setText(desc) - if param.isAdvanced: - self.layoutAdvanced.addWidget(widget) - else: - self.layoutMain.insertWidget( - self.layoutMain.count() - 2, widget) + label = QLabel(desc) + # label.setToolTip(tooltip) + self.labels[param.name] = label + if param.isAdvanced: + self.layoutAdvanced.addWidget(label) + self.layoutAdvanced.addWidget(widget) else: - label = QLabel(desc) - #label.setToolTip(tooltip) - self.labels[param.name] = label - if param.isAdvanced: - self.layoutAdvanced.addWidget(label) - self.layoutAdvanced.addWidget(widget) - else: - self.layoutMain.insertWidget( - self.layoutMain.count() - 2, label) - self.layoutMain.insertWidget( - self.layoutMain.count() - 2, widget) + self.layoutMain.insertWidget( + self.layoutMain.count() - 2, label) + self.layoutMain.insertWidget( + self.layoutMain.count() - 2, widget) self.widgets[param.name] = widget @@ -262,24 +189,9 @@ def initWidgets(self): self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.valueItems[output.name] = widget - wrapper = NotYetImplementedWidgetWrapper(output, widget) - self.widget_wrappers[output.name] = wrapper - - if isinstance(output, OutputVector): - if output.base_input in self.dependentItems: - items = self.dependentItems[output.base_input] - else: - items = [] - self.dependentItems[output.base_input] = items - items.append(output) - - base_input = self.alg.getParameterFromName(output.base_input) - if isinstance(base_input, ParameterVector): - layers = dataobjects.getVectorLayers(base_input.datatype) - else: - layers = dataobjects.getTables() - if len(layers) > 0: - output.base_layer = layers[0] + + for wrapper in self.wrappers.values(): + wrapper.postInitialize(self.wrappers.values()) def buttonToggled(self, value): if value: @@ -288,213 +200,11 @@ def buttonToggled(self, value): if button is not sender: button.setChecked(False) - def getExtendedLayerName(self, layer): - authid = layer.crs().authid() - if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \ - and authid is not None: - return u'{} [{}]'.format(layer.name(), authid) - else: - return layer.name() - def getWidgetWrapperFromParameter(self, param): - wrapper = wrapper_from_param(param) - if wrapper is not None: - return wrapper - - widget = self.getWidgetFromParameter(param) - wrapper = NotYetImplementedWidgetWrapper(param, widget) + wrapper = param.wrapper(self.parent) + wrapper.widgetValueHasChanged.connect(self.widgetValueHasChanged) return wrapper - def getWidgetFromParameter(self, param): - # TODO Create Parameter widget class that holds the logic - # for creating a widget that belongs to the parameter. - if isinstance(param, ParameterRaster): - layers = dataobjects.getRasterLayers() - items = [] - if param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((self.getExtendedLayerName(layer), layer)) - item = InputLayerSelectorPanel(items, param) - elif isinstance(param, ParameterVector): - if self.somethingDependsOnThisParameter(param) or self.alg.allowOnlyOpenedLayers: - item = QComboBox() - layers = dataobjects.getVectorLayers(param.datatype) - layers.sort(key=lambda lay: lay.name()) - if param.optional: - item.addItem(self.NOT_SELECTED, None) - for layer in layers: - item.addItem(self.getExtendedLayerName(layer), layer) - item.currentIndexChanged.connect(self.updateDependentFields) - item.name = param.name - else: - layers = dataobjects.getVectorLayers(param.datatype) - items = [] - if param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((self.getExtendedLayerName(layer), layer)) - # if already set, put first in list - for i, (name, layer) in enumerate(items): - if layer and layer.source() == param.value: - items.insert(0, items.pop(i)) - item = InputLayerSelectorPanel(items, param) - elif isinstance(param, ParameterTable): - if self.somethingDependsOnThisParameter(param): - item = QComboBox() - layers = dataobjects.getTables() - if param.optional: - item.addItem(self.NOT_SELECTED, None) - for layer in layers: - item.addItem(layer.name(), layer) - item.currentIndexChanged.connect(self.updateDependentFields) - item.name = param.name - else: - layers = dataobjects.getTables() - items = [] - if param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((layer.name(), layer)) - # if already set, put first in list - for i, (name, layer) in enumerate(items): - if layer and layer.source() == param.value: - items.insert(0, items.pop(i)) - item = InputLayerSelectorPanel(items, param) - elif isinstance(param, ParameterTableField) or isinstance(param, ParameterTableMultipleField): - if isinstance(param, ParameterTableMultipleField): - item = ListMultiSelectWidget() - else: - item = QComboBox() - if param.parent in self.dependentItems: - items = self.dependentItems[param.parent] - else: - items = [] - self.dependentItems[param.parent] = items - items.append(param) - parent = self.alg.getParameterFromName(param.parent) - if isinstance(parent, ParameterVector): - layers = dataobjects.getVectorLayers(parent.datatype) - else: - layers = dataobjects.getTables() - if len(layers) > 0: - if param.optional and isinstance(param, ParameterTableField): - item.addItem(self.tr('[not set]')) - item.addItems(self.getFields(layers[0], param.datatype)) - elif isinstance(param, ParameterSelection): - item = QComboBox() - item.addItems(param.options) - if param.default: - item.setCurrentIndex(param.default) - elif isinstance(param, ParameterFixedTable): - item = FixedTablePanel(param) - elif isinstance(param, ParameterRange): - item = RangePanel(param) - elif isinstance(param, ParameterFile): - item = FileSelectionPanel(param.isFolder, param.ext) - elif isinstance(param, ParameterMultipleInput): - if param.datatype == dataobjects.TYPE_FILE: - item = MultipleInputPanel(datatype=dataobjects.TYPE_FILE) - else: - if param.datatype == dataobjects.TYPE_RASTER: - options = dataobjects.getRasterLayers(sorting=False) - elif param.datatype == dataobjects.TYPE_VECTOR_ANY: - options = dataobjects.getVectorLayers(sorting=False) - else: - options = dataobjects.getVectorLayers([param.datatype], sorting=False) - opts = [self.getExtendedLayerName(opt) for opt in options] - item = MultipleInputPanel(opts) - elif isinstance(param, ParameterNumber): - item = NumberInputPanel(param.default, param.min, param.max, - param.isInteger) - elif isinstance(param, ParameterExtent): - item = ExtentSelectionPanel(self.parent, self.alg, param.default) - elif isinstance(param, ParameterPoint): - item = PointSelectionPanel(self.parent, param.default) - elif isinstance(param, ParameterString): - if param.multiline: - verticalLayout = QVBoxLayout() - verticalLayout.setSizeConstraint( - QLayout.SetDefaultConstraint) - textEdit = QPlainTextEdit() - if param.default: - textEdit.setPlainText(param.default) - verticalLayout.addWidget(textEdit) - item = textEdit - else: - item = QLineEdit() - if param.default: - item.setText(str(param.default)) - elif isinstance(param, ParameterGeometryPredicate): - item = GeometryPredicateSelectionPanel(param.enabledPredicates) - if param.left: - widget = self.valueItems[param.left] - if isinstance(widget, InputLayerSelectorPanel): - widget = widget.cmbText - widget.currentIndexChanged.connect(item.onLeftLayerChange) - item.leftLayer = widget.itemData(widget.currentIndex()) - if param.right: - widget = self.valueItems[param.right] - if isinstance(widget, InputLayerSelectorPanel): - widget = widget.cmbText - widget.currentIndexChanged.connect(item.onRightLayerChange) - item.rightLayer = widget.itemData(widget.currentIndex()) - item.updatePredicates() - if param.default: - item.setValue(param.default) - else: - item = QLineEdit() - if param.default: - item.setText(str(param.default)) - - return item - - def updateDependentFields(self): - sender = self.sender() - if not isinstance(sender, QComboBox): - return - if sender.name not in self.dependentItems: - return - layer = sender.itemData(sender.currentIndex()) - if not layer: - return - children = self.dependentItems[sender.name] - for child in children: - if (isinstance(child, ParameterTableField) or isinstance( - child, ParameterTableMultipleField)): - widget = self.valueItems[child.name] - widget.clear() - if (self.alg.getParameterFromName(child.name).optional and - not isinstance(child, ParameterTableMultipleField)): - widget.addItem(self.tr('[not set]')) - widget.addItems( - self.getFields(layer, self.alg.getParameterFromName( - child.name).datatype)) - if isinstance(child, OutputVector): - child.base_layer = layer - - def getFields(self, layer, datatype): - fieldTypes = [] - if datatype == ParameterTableField.DATA_TYPE_STRING: - fieldTypes = [QVariant.String] - elif datatype == ParameterTableField.DATA_TYPE_NUMBER: - fieldTypes = [QVariant.Int, QVariant.Double, QVariant.LongLong, - QVariant.UInt, QVariant.ULongLong] - - fieldNames = set() - for field in layer.fields(): - if not fieldTypes or field.type() in fieldTypes: - fieldNames.add(str(field.name())) - return sorted(list(fieldNames), cmp=locale.strcoll) - - def somethingDependsOnThisParameter(self, parent): - for param in self.alg.parameters: - if isinstance(param, (ParameterTableField, - ParameterTableMultipleField)): - if param.parent == parent.name: - return True - for output in self.alg.outputs: - if isinstance(output, OutputVector): - if output.base_layer == parent.name: - return True - return False + def widgetValueHasChanged(self, wrapper): + for wrapper in self.wrappers.values(): + wrapper.anotherParameterWidgetHasChanged(wrapper) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index d4228927a0c1..6de1b00233aa 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -5,8 +5,9 @@ BooleanWidget.py --------------------- Date : May 2016 - Copyright : (C) 2016 by Arnaud Morvan + Copyright : (C) 2016 by Arnaud Morvan, Victor Olaya Email : arnaud dot morvan at camptocamp dot com + volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * @@ -26,34 +27,37 @@ __revision__ = '$Format:%H$' -from inspect import isclass +import locale from qgis.core import QgsCoordinateReferenceSystem -from qgis.PyQt.QtWidgets import ( - QCheckBox, - QComboBox, -) +from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit +from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant +from processing.gui.NumberInputPanel import NumberInputPanel +from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel +from processing.modeler.MultilineTextPanel import MultilineTextPanel from processing.gui.CrsSelectionPanel import CrsSelectionPanel +from processing.gui.PointSelectionPanel import PointSelectionPanel +from processing.core.parameters import (ParameterBoolean, ParameterPoint, ParameterFile, + ParameterRaster, ParameterVector, ParameterNumber, ParameterString, ParameterTable, + ParameterTableField, ParameterExtent, ParameterFixedTable) +from processing.core.ProcessingConfig import ProcessingConfig +from processing.gui.FileSelectionPanel import FileSelectionPanel +from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, + OutputString, OutputTable, OutputExtent) +from processing.tools import dataobjects +from processing.gui.MultipleInputPanel import MultipleInputPanel +from processing.gui.BatchInputSelectionPanel import BatchInputSelectionPanel +from processing.gui.FixedTablePanel import FixedTablePanel +from processing.gui.ExtentSelectionPanel import ExtentSelectionPanel + DIALOG_STANDARD = 'standard' DIALOG_BATCH = 'batch' DIALOG_MODELER = 'modeler' - -def wrapper_from_param(param, dialog=DIALOG_STANDARD): - wrapper = param.metadata.get('widget_wrapper', None) - # wrapper metadata should be a class path - if isinstance(wrapper, basestring): - tokens = wrapper.split('.') - mod = __import__('.'.join(tokens[:-1]), fromlist=[tokens[-1]]) - wrapper = getattr(mod, tokens[-1]) - # or directly a class object - if isclass(wrapper): - wrapper = wrapper(param=param, dialog=dialog) - # or a wrapper instance - return wrapper - +class InvalidParameterValue(Exception): + pass class NotYetImplementedWidgetWrapper(): @@ -65,19 +69,43 @@ def __init__(self, param, widget): self.param = param self.widget = widget +dialogTypes = {"AlgorithmDialog":DIALOG_STANDARD, + "ModelerParametersDialog":DIALOG_MODELER, + "BatchAlgorithmDialog": DIALOG_BATCH} -class WidgetWrapper(): +def getExtendedLayerName(layer): + authid = layer.crs().authid() + if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) and authid is not None: + return u'{} [{}]'.format(layer.name(), authid) + else: + return layer.name() + +class WidgetWrapper(QObject): implemented = True # TODO: Should be removed at the end + + widgetValueHasChanged = pyqtSignal(object) - def __init__(self, param, dialog=DIALOG_STANDARD): + def __init__(self, param, dialog, row=0, col=0): + QObject.__init__(self) self.param = param self.dialog = dialog + self.row = row + self.col = col + self.dialogType = dialogTypes[dialog.__class__.__name__] self.widget = self.createWidget() - self.setValue(param.default) - - def comboValue(self): - return self.widget.itemData(self.widget.currentIndex()) + if param.default is not None: + self.setValue(param.default) + + def comboValue(self, validator=None): + idx = self.widget.findText(self.widget.currentText()) + if idx < 0: + v = self.widget.currentText().strip() + if validator is not None and not validator(v): + raise InvalidParameterValue() + return v + else: + return self.widget.itemData(self.widget.currentIndex()) def createWidget(self): pass @@ -86,41 +114,68 @@ def setValue(self, value): pass def setComboValue(self, value): + if isinstance(value, list): + value = value[0] values = [self.widget.itemData(i) for i in range(self.widget.count())] try: idx = values.index(value) self.widget.setCurrentIndex(idx) except ValueError: pass + if self.widget.isEditable(): + if value is not None: + self.widget.setEditText(unicode(value)) def value(self): pass + + def anotherParameterWidgetHasChanged(self, wrapper): + pass + + def postInitialize(self, wrappers): + pass + + def refresh(self): + pass class BooleanWidgetWrapper(WidgetWrapper): def createWidget(self): - if self.dialog == DIALOG_STANDARD: + if self.dialogType == DIALOG_STANDARD: return QCheckBox() - - if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): + elif self.dialogType == DIALOG_BATCH: + widget = QComboBox() + widget.addItem(self.tr('Yes')) + widget.addItem(self.tr('No')) + if self.param.default: + widget.setCurrentIndex(0) + else: + widget.setCurrentIndex(1) + return widget + else: widget = QComboBox() - widget.addItem(widget.tr('Yes'), True) - widget.addItem(widget.tr('No'), False) + widget.addItem('Yes', True) + widget.addItem('No', False) + bools = self.dialog.getAvailableValuesOfType(ParameterBoolean, None) + for b in bools: + widget.addItem(self.dialog.resolveValueDescription(b), b) + if self.param.default: + widget.setCurrentIndex(0) + else: + widget.setCurrentIndex(1) return widget def setValue(self, value): - if self.dialog == DIALOG_STANDARD: + if self.dialogType == DIALOG_STANDARD: self.widget.setChecked(value) - - if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): + else: self.setComboValue(value) def value(self): - if self.dialog == DIALOG_STANDARD: + if self.dialogType == DIALOG_STANDARD: return self.widget.isChecked() - - if self.dialog in (DIALOG_BATCH, DIALOG_MODELER): + else: return self.comboValue() @@ -138,3 +193,590 @@ def setValue(self, value): def value(self): return self.widget.getValue() + +class ExtentWidgetWrapper(WidgetWrapper): + + def createWidget(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return ExtentSelectionPanel(self.dialog, self.param) + else: + widget = QComboBox() + widget.setEditable(True) + extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) + if self.param.optional: + widget.addItem(self.USE_MIN_COVERING_EXTENT, None) + for ex in extents: + widget.addItem(self.dialog.resolveValueDescription(ex), ex) + if not self.param.default: + widget.setEditText(self.param.default) + return widget + + def setValue(self, value): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.widget.setExtentFromString(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return self.widget.getValue() + else: + idx = self.widget.findText(self.widget.currentText()) + if idx < 0: + s = unicode(self.widget.currentText()).strip() + if s: + try: + tokens = s.split(',') + if len(tokens) != 4: + raise InvalidParameterValue() + for token in tokens: + float(token) + except: + raise InvalidParameterValue() + elif self.param.optional: + s = None + else: + raise InvalidParameterValue() + return s + else: + return self.widget.itemData(self.widget.currentIndex()) + + +class PointWidgetWrapper(WidgetWrapper): + + def createWidget(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return PointSelectionPanel(self.dialog, self.param.default) + else: + item = QComboBox() + item.setEditable(True) + points = self.dialog.getAvailableValuesOfType(ParameterPoint) + for p in points: + item.addItem(self.dialog.resolveValueDescription(p), p) + item.setEditText(unicode(self.param.default)) + + def setValue(self, value): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.widget.setPointFromString(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return self.widget.getValue() + else: + idx = self.widget.findText(self.widget.currentText()) + if idx < 0: + s = unicode(self.widget.currentText()).strip() + if s: + try: + tokens = s.split(',') + if len(tokens) != 2: + raise InvalidParameterValue() + for token in tokens: + float(token) + except: + raise InvalidParameterValue() + elif self.param.optional: + s = None + else: + raise InvalidParameterValue() + return s + else: + return self.widget.itemData(self.widget.currentIndex()) + + +class FileWidgetWrapper(WidgetWrapper): + + def createWidget(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return FileSelectionPanel(self.param.isFolder, self.param.ext) + else: + widget = QComboBox() + widget.setEditable(True) + files = self.dialog.getAvailableValuesOfType(ParameterFile, OutputFile) + for f in files: + widget.addItem(self.dialog.resolveValueDescription(f), f) + return widget + + def setValue(self, value): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.widget.setText(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return self.widget.getValue() + else: + return self.comboValue() + +class FixedTableWidgetWrapper(WidgetWrapper): + + def createWidget(self): + return FixedTablePanel(self.param) + + def setValue(self, value): + pass + + def value(self): + if self.dialogType == DIALOG_MODELER: + table = self.widget.table + if not bool(table) and not self.param.optional: + raise InvalidParameterValue() + return ParameterFixedTable.tableToString(table) + else: + return self.widget.table + + +class MultipleInputWidgetWrapper(WidgetWrapper): + + def _getOptions(self): + if self.param.datatype == dataobjects.TYPE_VECTOR_ANY: + options = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) + elif self.param.datatype == dataobjects.TYPE_VECTOR_POINT: + options = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector, + [dataobjects.TYPE_VECTOR_POINT, dataobjects.TYPE_VECTOR_ANY]) + elif self.param.datatype == dataobjects.TYPE_VECTOR_LINE: + options = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector, + [dataobjects.TYPE_VECTOR_LINE, dataobjects.TYPE_VECTOR_ANY]) + elif self.param.datatype == dataobjects.TYPE_VECTOR_POLYGON: + options = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector, + [dataobjects.TYPE_VECTOR_POLYGON, dataobjects.TYPE_VECTOR_ANY]) + elif self.param.datatype == dataobjects.TYPE_RASTER: + options = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) + else: + options = self.dialog.getAvailableValuesOfType(ParameterFile, OutputFile) + return options + + def createWidget(self): + if self.dialogType == DIALOG_STANDARD: + if self.param.datatype == dataobjects.TYPE_FILE: + return MultipleInputPanel(datatype=dataobjects.TYPE_FILE) + else: + if self.param.datatype == dataobjects.TYPE_RASTER: + options = dataobjects.getRasterLayers(sorting=False) + elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY: + options = dataobjects.getVectorLayers(sorting=False) + else: + options = dataobjects.getVectorLayers([self.param.datatype], sorting=False) + opts = [getExtendedLayerName(opt) for opt in options] + return MultipleInputPanel(opts) + elif self.dialogType == DIALOG_BATCH: + return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + else: + options = [self.dialog.resolveValueDescription(opt) for opt in self._getOptions()] + return MultipleInputPanel(options) + + def refresh(self): + if self.param.datatype != dataobjects.TYPE_FILE: + if self.param.datatype == dataobjects.TYPE_RASTER: + options = dataobjects.getRasterLayers(sorting=False) + elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY: + options = dataobjects.getVectorLayers(sorting=False) + else: + options = dataobjects.getVectorLayers([self.param.datatype], sorting=False) + opts = [self.getExtendedLayerName(opt) for opt in options] + self.widget.updateForOptions(opts) + + def setValue(self, value): + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + return self.widget.setText(value) + else: + options = self._getOptions() + selected = [] + for i, opt in enumerate(options): + if opt in value: + selected.append(i) + self.widget.setSelectedItems(selected) + + def value(self): + if self.dialogType == DIALOG_STANDARD: + if self.param.datatype == dataobjects.TYPE_FILE: + return self.param.setValue(self.widget.selectedoptions) + else: + if self.param.datatype == dataobjects.TYPE_RASTER: + options = dataobjects.getRasterLayers(sorting=False) + elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY: + options = dataobjects.getVectorLayers(sorting=False) + else: + options = dataobjects.getVectorLayers([self.param.datatype], sorting=False) + return self.param.setValue([options[i] for i in self.widget.selectedoptions]) + elif self.dialogType == DIALOG_BATCH: + return self.widget.getText() + else: + options = self._getOptions() + values = [options[i] for i in self.widget.selectedoptions] + if len(values) == 0 and not self.param.optional: + raise InvalidParameterValue() + return values + + +class NumberWidgetWrapper(WidgetWrapper): + + def createWidget(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return NumberInputPanel(self.param.default, self.param.min, self.param.max, + self.param.isInteger) + else: + widget = QComboBox() + widget.setEditable(True) + files = self.dialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) + for f in files: + widget.addItem(self.dialog.resolveValueDescription(f), f) + return widget + + def setValue(self, value): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.widget.setValue(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return self.widget.getValue() + else: + def validator(v): + if str(v).strip(): + try: + if self.param.isInteger: + int(v) + else: + float(v) + return True + except: + return False + else: + return self.param.optional + return self.comboValue(validator) + + +class RasterWidgetWrapper(WidgetWrapper): + + NOT_SELECTED = '[Not selected]' + + def createWidget(self): + if self.dialogType == DIALOG_STANDARD: + layers = dataobjects.getRasterLayers() + items = [] + if self.param.optional: + items.append((self.NOT_SELECTED, None)) + for layer in layers: + items.append((getExtendedLayerName(layer), layer)) + return InputLayerSelectorPanel(items, self.param) + elif self.dialogType == DIALOG_BATCH: + return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + else: + widget = QComboBox() + widget.setEditable(True) + files = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) + for f in files: + widget.addItem(self.dialog.resolveValueDescription(f), f) + return widget + + def refresh(self): + self.widget.cmbText.clear() + layers = dataobjects.getRasterLayers(self) + layers.sort(key=lambda lay: lay.name()) + if self.param.optional: + self.widget.cmbText.addItem(self.NOT_SELECTED, None) + for layer in layers: + self.widget.cmbText.addItem(getExtendedLayerName(layer), layer) + + def setValue(self, value): + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + return self.widget.setText(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType == DIALOG_STANDARD: + return self.widget.getValue() + elif self.dialogType == DIALOG_BATCH: + return self.widget.getText() + else: + return self.comboValue() + + +class SelectionWidgetWrapper(WidgetWrapper): + + def createWidget(self): + widget = QComboBox() + widget.addItems(self.param.options) + if self.param.default: + widget.setCurrentIndex(self.param.default) + return widget + + def setValue(self, value): + self.widget.setCurrentIndex(int(value)) + + def value(self): + return self.widget.currentIndex() + + +class VectorWidgetWrapper(WidgetWrapper): + + NOT_SELECTED = '[Not selected]' + + def createWidget(self): + if self.dialogType == DIALOG_STANDARD: + widget = QComboBox() + self._populate(widget) + return widget + elif self.dialogType == DIALOG_BATCH: + return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + else: + widget = QComboBox() + layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) + if self.param.optional: + widget.addItem(self.NOT_SELECTED, None) + for layer in layers: + widget.addItem(self.dialog.resolveValueDescription(layer), layer) + return widget + + def _populate(self, widget): + widget.clear() + layers = dataobjects.getVectorLayers(self.param.datatype) + layers.sort(key=lambda lay: lay.name()) + if self.param.optional: + widget.addItem(self.NOT_SELECTED, None) + for layer in layers: + widget.addItem(getExtendedLayerName(layer), layer) + widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + widget.name = self.param.name + + def refresh(self): + self._populate(self.widget) + + def setValue(self, value): + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + return self.widget.setText(value) + else: + self.setComboValue(value) + + + def value(self): + if self.dialogType == DIALOG_STANDARD: + try: + return self.widget.itemData(self.widget.currentIndex()) + except: + return self.widget.getValue() + elif self.dialogType == DIALOG_BATCH: + return self.widget.getText() + else: + return self.comboValue() + +class StringWidgetWrapper(WidgetWrapper): + + def createWidget(self): + if self.dialogType == DIALOG_STANDARD: + if self.param.multiline: + widget = QPlainTextEdit() + if self.param.default: + widget.setPlainText(self.param.default) + else: + widget = QLineEdit() + if self.param.default: + widget.setText(self.param.default) + elif self.dialogType == DIALOG_BATCH: + widget = QLineEdit() + if self.param.default: + widget.setText(self.param.default) + else: + strings = self.dialog.getAvailableValuesOfType(ParameterString, OutputString) + options = [(self.dialog.resolveValueDescription(s), s) for s in strings] + if self.param.multiline: + widget = MultilineTextPanel(options) + widget.setText(self.param.default or "") + else: + widget = QComboBox() + widget.setEditable(True) + for desc, val in options: + widget.addItem(desc, val) + widget.setEditText(self.param.default or "") + return widget + + def setValue(self, value): + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + self.widget.setText(value) + else: + if self.param.multiline: + self.widget.setValue(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType in DIALOG_STANDARD: + if self.param.multiline: + text = self.widget.toPlainText() + else: + text = self.widget.text() + + if self.param.evaluateExpressions: + try: + text = self.evaluateExpression(text) + except: + pass + return text + if self.dialogType == DIALOG_BATCH: + text = self.widget.text() + if self.param.evaluateExpressions: + try: + text = self.evaluateExpression(text) + except: + pass + return text + else: + if self.param.multiline: + value = self.widget.getValue() + option = self.widget.getOption() + if option == MultilineTextPanel.USE_TEXT: + if value == '': + if self.param.optional: + return None + else: + raise InvalidParameterValue() + else: + return value + else: + return value + else: + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) + + +class TableWidgetWrapper(WidgetWrapper): + + NOT_SELECTED = '[Not selected]' + + def createWidget(self): + if self.dialogType == DIALOG_STANDARD: + widget = QComboBox() + layers = dataobjects.getTables() + layers.sort(key=lambda lay: lay.name()) + if self.param.optional: + widget.addItem(self.NOT_SELECTED, None) + for layer in layers: + widget.addItem(layer.name(), layer) + widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + widget.name = self.param.name + return widget + elif self.dialogType == DIALOG_BATCH: + return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + else: + widget = QComboBox() + tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) + layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) + if self.param.optional: + widget.addItem(self.NOT_SELECTED, None) + for table in tables: + widget.addItem(self.dialog.resolveValueDescription(table), table) + for layer in layers: + widget.addItem(self.dialog.resolveValueDescription(layer), layer) + return widget + + def setValue(self, value): + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + return self.widget.setText(value) + else: + self.setComboValue(value) + + + def value(self): + if self.dialogType == DIALOG_STANDARD: + try: + return self.widget.itemData(self.widget.currentIndex()) + except: + return self.widget.getValue() + elif self.dialogType == DIALOG_BATCH: + return self.widget.getText() + else: + return self.comboValue() + + +class TableFieldWidgetWrapper(WidgetWrapper): + + NOT_SET = '[Not set]' + + def createWidget(self): + if self.dialogType == DIALOG_STANDARD: + widget = QComboBox() + return widget + elif self.dialogType == DIALOG_BATCH: + item = QLineEdit() + if self.param.default is not None: + item.setText(self.param.default) + else: + widget = QComboBox() + widget.setEditable(True) + fields = self.getAvailableValuesOfType(ParameterTableField, None) + if self.param.optional: + widget.addItem(self.NOT_SELECTED, None) + for f in fields: + widget.addItem(self.resolveValueDescription(f), f) + return widget + + def postInitialize(self, wrappers): + for wrapper in wrappers: + if wrapper.param.name == self.param.parent: + layer = wrapper.widget.itemData(wrapper.widget.currentIndex()) + if layer is not None: + self.widget.clear() + if self.param.optional: + self.widget.addItem(self.tr(self.NOT_SET)) + self.widget.addItems(self.getFields(layer, wrapper.param.datatype)) + break + + def getFields(self, layer, datatype): + fieldTypes = [] + if datatype == ParameterTableField.DATA_TYPE_STRING: + fieldTypes = [QVariant.String] + elif datatype == ParameterTableField.DATA_TYPE_NUMBER: + fieldTypes = [QVariant.Int, QVariant.Double, QVariant.LongLong, + QVariant.UInt, QVariant.ULongLong] + + fieldNames = set() + for field in layer.fields(): + if not fieldTypes or field.type() in fieldTypes: + fieldNames.add(unicode(field.name())) + return sorted(list(fieldNames), cmp=locale.strcoll) + + def setValue(self, value): + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + return self.widget.setText(value) + else: + self.setComboValue(value) + + + def value(self): + if self.dialogType == DIALOG_STANDARD: + if self.param.optional and self.widget.currentIndex() == 0: + return None + return self.widget.currentText() + elif self.dialogType == DIALOG_BATCH: + return self.widget.text() + else: + return self.comboValue() + + def anotherParameterWidgetHasChanged(self,wrapper): + if wrapper.param.name == self.param.parent: + layer = wrapper.value() + if layer is not None: + self.widget.clear() + if self.param.optional: + self.widget.addItem(self.tr(self.NOT_SET)) + self.widget.addItems(self.getFields(layer, wrapper.param.datatype)) + diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 0b156d7dec5d..e2295896d020 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -40,12 +40,7 @@ from qgis.gui import QgsMessageBar -from processing.gui.wrappers import ( - DIALOG_MODELER, - wrapper_from_param, - NotYetImplementedWidgetWrapper, - ) - +from processing.gui.wrappers import NotYetImplementedWidgetWrapper, InvalidParameterValue from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.MultipleInputPanel import MultipleInputPanel from processing.gui.FixedTablePanel import FixedTablePanel @@ -183,7 +178,7 @@ def setupUi(self): self.widgets = {} self.checkBoxes = {} self.showAdvanced = False - self.widget_wrappers = {} + self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.resize(650, 450) @@ -238,8 +233,8 @@ def setupUi(self): label = QLabel(desc) self.labels[param.name] = label - wrapper = self.getWidgetWrapperFromParameter(param) - self.widget_wrappers[param.name] = wrapper + wrapper = param.wrapper(self) + self.wrappers[param.name] = wrapper widget = wrapper.widget self.valueItems[param.name] = widget @@ -255,7 +250,7 @@ def setupUi(self): self.widgets[param.name] = widget self.verticalLayout.addWidget(label) - self.verticalLayout.addWidget(wrapper) + self.verticalLayout.addWidget(wrapper.widget) for output in self._alg.outputs: if output.hidden: @@ -396,135 +391,6 @@ def resolveValueDescription(self, value): alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) - def getWidgetWrapperFromParameter(self, param): - wrapper = wrapper_from_param(param, DIALOG_MODELER) - if wrapper is None: - widget = self.getWidgetFromParameter(param) - wrapper = NotYetImplementedWidgetWrapper(param, widget) - - model_values = [] - values = self.getAvailableValuesForParam(param) - for value in values: - model_values.append((self.resolveValueDescription(value), value)) - - input_wrapper = ModelerWidgetWrapper(wrapper, model_values) - return input_wrapper - - - def getWidgetFromParameter(self, param): - if isinstance(param, ParameterRaster): - item = QComboBox() - layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) - if param.optional: - item.addItem(self.NOT_SELECTED, None) - for layer in layers: - item.addItem(self.resolveValueDescription(layer), layer) - elif isinstance(param, ParameterVector): - item = QComboBox() - layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) - if param.optional: - item.addItem(self.NOT_SELECTED, None) - for layer in layers: - item.addItem(self.resolveValueDescription(layer), layer) - elif isinstance(param, ParameterTable): - item = QComboBox() - tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) - layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) - if param.optional: - item.addItem(self.NOT_SELECTED, None) - for table in tables: - item.addItem(self.resolveValueDescription(table), table) - for layer in layers: - item.addItem(self.resolveValueDescription(layer), layer) - elif isinstance(param, ParameterSelection): - item = QComboBox() - item.addItems(param.options) - item.setCurrentIndex(param.default or 0) - elif isinstance(param, ParameterFixedTable): - item = FixedTablePanel(param) - elif isinstance(param, ParameterRange): - item = RangePanel(param) - elif isinstance(param, ParameterMultipleInput): - if param.datatype == dataobjects.TYPE_VECTOR_ANY: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector) - elif param.datatype == dataobjects.TYPE_VECTOR_POINT: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_POINT, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_VECTOR_LINE: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_LINE, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_VECTOR_POLYGON: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_POLYGON, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_RASTER: - options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) - else: - options = self.getAvailableValuesOfType(ParameterFile, OutputFile) - opts = [] - for opt in options: - opts.append(self.resolveValueDescription(opt)) - item = MultipleInputPanel(opts) - elif isinstance(param, ParameterString): - strings = self.getAvailableValuesOfType(ParameterString, OutputString) - options = [(self.resolveValueDescription(s), s) for s in strings] - if param.multiline: - item = MultilineTextPanel(options) - item.setText(str(param.default or "")) - else: - item = QComboBox() - item.setEditable(True) - for desc, val in options: - item.addItem(desc, val) - item.setEditText(str(param.default or "")) - elif isinstance(param, ParameterTableField): - item = QComboBox() - item.setEditable(True) - fields = self.getAvailableValuesOfType(ParameterTableField, None) - for f in fields: - item.addItem(self.resolveValueDescription(f), f) - elif isinstance(param, ParameterTableMultipleField): - item = QComboBox() - item.setEditable(True) - fields = self.getAvailableValuesOfType(ParameterTableMultipleField, None) - for f in fields: - item.addItem(self.resolveValueDescription(f), f) - elif isinstance(param, ParameterNumber): - item = QComboBox() - item.setEditable(True) - numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) - for n in numbers: - item.addItem(self.resolveValueDescription(n), n) - item.setEditText(str(param.default)) - elif isinstance(param, ParameterExtent): - item = QComboBox() - item.setEditable(True) - extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) - if self.canUseAutoExtent(): - item.addItem(self.USE_MIN_COVERING_EXTENT, None) - for ex in extents: - item.addItem(self.resolveValueDescription(ex), ex) - if not self.canUseAutoExtent(): - item.setEditText(str(param.default)) - elif isinstance(param, ParameterPoint): - item = QComboBox() - item.setEditable(True) - points = self.getAvailableValuesOfType(ParameterPoint) - for p in points: - item.addItem(self.resolveValueDescription(p), p) - item.setEditText(str(param.default)) - elif isinstance(param, ParameterFile): - item = QComboBox() - item.setEditable(True) - files = self.getAvailableValuesOfType(ParameterFile, OutputFile) - for f in files: - item.addItem(self.resolveValueDescription(f), f) - elif isinstance(param, ParameterGeometryPredicate): - item = GeometryPredicateSelectionPanel(param.enabledPredicates) - else: - item = QLineEdit() - try: - item.setText(str(param.default)) - except: - pass - return item - def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): @@ -559,22 +425,6 @@ def setTableContent(self): self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) - def setComboBoxValue(self, combo, value, param): - if isinstance(value, list): - value = value[0] - items = [combo.itemData(i) for i in range(combo.count())] - try: - idx = items.index(value) - combo.setCurrentIndex(idx) - return - except ValueError: - pass - if combo.isEditable(): - if value is not None: - combo.setEditText(str(value)) - elif isinstance(param, ParameterSelection): - combo.setCurrentIndex(int(value)) - def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] @@ -587,52 +437,8 @@ def setPreviousValues(self): else: value = param.default - wrapper = self.widget_wrappers[param.name] - if wrapper.implemented: - wrapper.setValue(value) - continue - - widget = wrapper.widget - if isinstance(param, ( - ParameterRaster, - ParameterVector, - ParameterTable, - ParameterTableField, - ParameterSelection, - ParameterNumber, - ParameterExtent, - ParameterFile, - ParameterPoint, - ParameterCrs - )): - self.setComboBoxValue(widget, value, param) - elif isinstance(param, ParameterString): - if param.multiline: - widget.setValue(value) - else: - self.setComboBoxValue(widget, value, param) - elif isinstance(param, ParameterFixedTable): - pass # TODO! - elif isinstance(param, ParameterMultipleInput): - if param.datatype == dataobjects.TYPE_VECTOR_ANY: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector) - elif param.datatype == dataobjects.TYPE_VECTOR_POINT: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_POINT, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_VECTOR_LINE: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_LINE, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_VECTOR_POLYGON: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_POLYGON, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_RASTER: - options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) - else: - options = self.getAvailableValuesOfType(ParameterFile, OutputFile) - selected = [] - for i, opt in enumerate(options): - if opt in value: - selected.append(i) - widget.setSelectedItems(selected) - elif isinstance(param, ParameterGeometryPredicate): - widget.setValue(value) + wrapper = self.wrappers[param.name] + wrapper.setValue(value) for name, out in alg.outputs.items(): widget = self.valueItems[name].setText(out.description) @@ -654,7 +460,7 @@ def createAlgorithm(self): for param in params: if param.hidden: continue - if not self.setParamValue(alg, param, self.widget_wrappers[param.name]): + if not self.setParamValue(alg, param, self.wrappers[param.name]): self.bar.pushMessage("Error", "Wrong or missing value for parameter '%s'" % param.description, level=QgsMessageBar.WARNING) return None @@ -671,194 +477,13 @@ def createAlgorithm(self): return alg - def setParamValueLayerOrTable(self, alg, param, widget): - idx = widget.currentIndex() - if idx < 0: - return False - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True - - def setParamTableFieldValue(self, alg, param, widget): - idx = widget.findText(widget.currentText()) - if idx < 0: - s = str(widget.currentText()).strip() - if s == '': - if param.optional: - alg.params[param.name] = None - return True - else: - return False - else: - alg.params[param.name] = s - return True - else: - alg.params[param.name] = widget.itemData(widget.currentIndex()) - return True - - def setParamStringValue(self, alg, param, widget): - if param.multiline: - value = widget.getValue() - option = widget.getOption() - if option == MultilineTextPanel.USE_TEXT: - if value == '': - if param.optional: - alg.params[param.name] = None - return True - else: - return False - else: - alg.params[param.name] = value - else: - alg.params[param.name] = value - else: - idx = widget.findText(widget.currentText()) - if idx < 0: - value = widget.currentText().strip() - if value == '': - if param.optional: - alg.params[param.name] = None - return True - else: - return False - else: - alg.params[param.name] = value - else: - alg.params[param.name] = widget.itemData(widget.currentIndex()) - return True - - def setParamFileValue(self, alg, param, widget): - idx = widget.findText(widget.currentText()) - if idx < 0: - value = widget.currentText() - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True - - def setParamNumberValue(self, alg, param, widget): - idx = widget.findText(widget.currentText()) - if idx < 0: - s = widget.currentText().strip() - if s: - try: - value = float(s) - except: - return False - elif param.optional: - value = None - else: - return False - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True - - def setParamExtentValue(self, alg, param, widget): - idx = widget.findText(widget.currentText()) - if idx < 0: - s = str(widget.currentText()).strip() - if s: - try: - tokens = s.split(',') - if len(tokens) != 4: - return False - for token in tokens: - float(token) - except: - return False - elif param.optional: - s = None - else: - return False - alg.params[param.name] = [s] - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True - - def setParamPointValue(self, alg, param, widget): - idx = widget.findText(widget.currentText()) - if idx < 0: - s = str(widget.currentText()).strip() - if s: - try: - tokens = s.split(',') - if len(tokens) != 2: - return False - for token in tokens: - float(token) - except: - return False - elif param.optional: - s = None - else: - return False - alg.params[param.name] = [s] - else: - value = widget.itemData(widget.currentIndex()) - alg.params[param.name] = value - return True - def setParamValue(self, alg, param, wrapper): - if wrapper.implemented: - alg.params[param.name] = wrapper.value() - return True - - widget = wrapper.widget - if isinstance(param, (ParameterRaster, ParameterVector, - ParameterTable)): - return self.setParamValueLayerOrTable(alg, param, widget) - elif isinstance(param, ParameterString): - return self.setParamStringValue(alg, param, widget) - elif isinstance(param, ParameterNumber): - return self.setParamNumberValue(alg, param, widget) - elif isinstance(param, ParameterExtent): - return self.setParamExtentValue(alg, param, widget) - elif isinstance(param, ParameterPoint): - return self.setParamPointValue(alg, param, widget) - elif isinstance(param, ParameterFile): - return self.setParamFileValue(alg, param, widget) - elif isinstance(param, ParameterSelection): - alg.params[param.name] = widget.currentIndex() - return True - elif isinstance(param, ParameterRange): - alg.params[param.name] = widget.getValue() - return True - elif isinstance(param, ParameterFixedTable): - table = widget.table - if not bool(table) and not param.optional: - return False - alg.params[param.name] = ParameterFixedTable.tableToString(table) - return True - elif isinstance(param, (ParameterTableField, - ParameterTableMultipleField)): - return self.setParamTableFieldValue(alg, param, widget) - elif isinstance(param, ParameterMultipleInput): - if param.datatype == dataobjects.TYPE_VECTOR_ANY: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector) - elif param.datatype == dataobjects.TYPE_VECTOR_POINT: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_POINT, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_VECTOR_LINE: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_LINE, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_VECTOR_POLYGON: - options = self.getAvailableValuesOfType(ParameterVector, OutputVector, [dataobjects.TYPE_VECTOR_POLYGON, dataobjects.TYPE_VECTOR_ANY]) - elif param.datatype == dataobjects.TYPE_RASTER: - options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) - else: - options = self.getAvailableValuesOfType(ParameterFile, OutputFile) - values = [options[i] for i in widget.selectedoptions] - if len(values) == 0 and not param.optional: - return False - alg.params[param.name] = values - return True - elif isinstance(param, ParameterGeometryPredicate): - alg.params[param.name] = widget.value() - return True - else: - alg.params[param.name] = str(widget.text()) + try: + value = wrapper.value() + alg.params[param.name] = value return True + except InvalidParameterValue: + return False def okPressed(self): self.alg = self.createAlgorithm() From efd73a491f7d1161067c33d9e3df0caa9c989f27 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 8 Sep 2016 09:57:18 +0200 Subject: [PATCH 119/897] [processing] fixes for new parameters architecture includes better managing of crd and extent parameters in models, not requiring now the use of modeler-only lags --- .../processing/algs/lidar/fusion/ClipData.py | 2 +- .../algs/lidar/lastools/lasquery.py | 2 +- .../plugins/processing/algs/qgis/GridLine.py | 2 +- .../processing/algs/qgis/GridPolygon.py | 2 +- .../algs/qgis/RandomPointsExtent.py | 2 +- .../processing/algs/qgis/RandomSelection.py | 1 - .../algs/qgis/RandomSelectionWithinSubsets.py | 1 - .../processing/algs/qgis/RegularPoints.py | 2 +- .../processing/algs/qgis/SetVectorStyle.py | 1 - .../algs/qgis/VectorGridPolygons.py | 2 +- .../processing/algs/saga/SagaAlgorithm212.py | 2 +- .../plugins/processing/core/GeoAlgorithm.py | 5 +- python/plugins/processing/core/parameters.py | 47 ++++++-- .../gui/BatchInputSelectionPanel.py | 2 +- python/plugins/processing/gui/BatchPanel.py | 114 ++---------------- .../plugins/processing/gui/ParametersPanel.py | 16 +-- .../processing/gui/ProcessingToolbox.py | 2 +- python/plugins/processing/gui/wrappers.py | 72 +++++++---- .../processing/modeler/ModelerDialog.py | 2 +- .../modeler/ModelerOnlyAlgorithmProvider.py | 10 +- .../modeler/ModelerParametersDialog.py | 79 +----------- .../modeler/RasterLayerBoundsAlgorithm.py | 66 ---------- .../modeler/RasterLayerCrsAlgorithm.py | 51 -------- .../modeler/VectorLayerBoundsAlgorithm.py | 66 ---------- .../modeler/VectorLayerCrsAlgorithm.py | 51 -------- .../processing/script/ScriptAlgorithm.py | 17 +-- 26 files changed, 112 insertions(+), 507 deletions(-) delete mode 100644 python/plugins/processing/modeler/RasterLayerBoundsAlgorithm.py delete mode 100644 python/plugins/processing/modeler/RasterLayerCrsAlgorithm.py delete mode 100644 python/plugins/processing/modeler/VectorLayerBoundsAlgorithm.py delete mode 100644 python/plugins/processing/modeler/VectorLayerCrsAlgorithm.py diff --git a/python/plugins/processing/algs/lidar/fusion/ClipData.py b/python/plugins/processing/algs/lidar/fusion/ClipData.py index d9295b889a07..2855744759c8 100644 --- a/python/plugins/processing/algs/lidar/fusion/ClipData.py +++ b/python/plugins/processing/algs/lidar/fusion/ClipData.py @@ -52,7 +52,7 @@ def defineCharacteristics(self): self.group, self.i18n_group = self.trAlgorithm('Points') self.addParameter(ParameterFile( self.INPUT, self.tr('Input LAS layer'))) - self.addParameter(ParameterExtent(self.EXTENT, self.tr('Extent'))) + self.addParameter(ParameterExtent(self.EXTENT, self.tr('Extent'), optional=False)) self.addParameter(ParameterSelection( self.SHAPE, self.tr('Shape'), ['Rectangle', 'Circle'])) self.addOutput(OutputFile( diff --git a/python/plugins/processing/algs/lidar/lastools/lasquery.py b/python/plugins/processing/algs/lidar/lastools/lasquery.py index af5b93b4f36f..b72fb1332a1c 100644 --- a/python/plugins/processing/algs/lidar/lastools/lasquery.py +++ b/python/plugins/processing/algs/lidar/lastools/lasquery.py @@ -45,7 +45,7 @@ def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('lasquery') self.group, self.i18n_group = self.trAlgorithm('LAStools') self.addParametersVerboseGUI() - self.addParameter(ParameterExtent(self.AOI, self.tr('area of interest'))) + self.addParameter(ParameterExtent(self.AOI, self.tr('area of interest'), optional=False)) self.addParametersAdditionalGUI() def processAlgorithm(self, progress): diff --git a/python/plugins/processing/algs/qgis/GridLine.py b/python/plugins/processing/algs/qgis/GridLine.py index fea6902fcff8..db725e22e63f 100644 --- a/python/plugins/processing/algs/qgis/GridLine.py +++ b/python/plugins/processing/algs/qgis/GridLine.py @@ -57,7 +57,7 @@ def defineCharacteristics(self): self.group, self.i18n_group = self.trAlgorithm('Vector creation tools') self.addParameter(ParameterExtent(self.EXTENT, - self.tr('Grid extent'))) + self.tr('Grid extent'), optional=False)) self.addParameter(ParameterNumber(self.HSPACING, self.tr('Horizontal spacing'), default=10.0)) self.addParameter(ParameterNumber(self.VSPACING, diff --git a/python/plugins/processing/algs/qgis/GridPolygon.py b/python/plugins/processing/algs/qgis/GridPolygon.py index cb9f39b736e1..880df0b7a6e8 100644 --- a/python/plugins/processing/algs/qgis/GridPolygon.py +++ b/python/plugins/processing/algs/qgis/GridPolygon.py @@ -65,7 +65,7 @@ def defineCharacteristics(self): self.addParameter(ParameterSelection(self.TYPE, self.tr('Grid type'), self.types)) self.addParameter(ParameterExtent(self.EXTENT, - self.tr('Grid extent'))) + self.tr('Grid extent'), optional=False)) self.addParameter(ParameterNumber(self.HSPACING, self.tr('Horizontal spacing'), default=10.0)) self.addParameter(ParameterNumber(self.VSPACING, diff --git a/python/plugins/processing/algs/qgis/RandomPointsExtent.py b/python/plugins/processing/algs/qgis/RandomPointsExtent.py index 2b734000624b..6d8cf1c36421 100644 --- a/python/plugins/processing/algs/qgis/RandomPointsExtent.py +++ b/python/plugins/processing/algs/qgis/RandomPointsExtent.py @@ -59,7 +59,7 @@ def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Random points in extent') self.group, self.i18n_group = self.trAlgorithm('Vector creation tools') self.addParameter(ParameterExtent(self.EXTENT, - self.tr('Input extent'))) + self.tr('Input extent'), optional=False)) self.addParameter(ParameterNumber(self.POINT_NUMBER, self.tr('Points number'), 1, None, 1)) self.addParameter(ParameterNumber(self.MIN_DISTANCE, diff --git a/python/plugins/processing/algs/qgis/RandomSelection.py b/python/plugins/processing/algs/qgis/RandomSelection.py index 4e86410e47b4..b0b64bf05cca 100644 --- a/python/plugins/processing/algs/qgis/RandomSelection.py +++ b/python/plugins/processing/algs/qgis/RandomSelection.py @@ -53,7 +53,6 @@ def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'random_selection.png')) def defineCharacteristics(self): - self.allowOnlyOpenedLayers = True self.name, self.i18n_name = self.trAlgorithm('Random selection') self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') diff --git a/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py b/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py index 7849b97fa29a..ff400d40a6db 100644 --- a/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py +++ b/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py @@ -57,7 +57,6 @@ def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'sub_selection.png')) def defineCharacteristics(self): - self.allowOnlyOpenedLayers = True self.name, self.i18n_name = self.trAlgorithm('Random selection within subsets') self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') diff --git a/python/plugins/processing/algs/qgis/RegularPoints.py b/python/plugins/processing/algs/qgis/RegularPoints.py index 372fb0a79f24..54479e285409 100644 --- a/python/plugins/processing/algs/qgis/RegularPoints.py +++ b/python/plugins/processing/algs/qgis/RegularPoints.py @@ -63,7 +63,7 @@ def defineCharacteristics(self): self.group, self.i18n_group = self.trAlgorithm('Vector creation tools') self.addParameter(ParameterExtent(self.EXTENT, - self.tr('Input extent'))) + self.tr('Input extent'), optional=False)) self.addParameter(ParameterNumber(self.SPACING, self.tr('Point spacing/count'), 0.0001, 999999999.999999999, 0.0001)) self.addParameter(ParameterNumber(self.INSET, diff --git a/python/plugins/processing/algs/qgis/SetVectorStyle.py b/python/plugins/processing/algs/qgis/SetVectorStyle.py index 532af23d1368..93b9aff53993 100644 --- a/python/plugins/processing/algs/qgis/SetVectorStyle.py +++ b/python/plugins/processing/algs/qgis/SetVectorStyle.py @@ -41,7 +41,6 @@ class SetVectorStyle(GeoAlgorithm): OUTPUT = 'OUTPUT' def defineCharacteristics(self): - # self.allowOnlyOpenedLayers = True self.name, self.i18n_name = self.trAlgorithm('Set style for vector layer') self.group, self.i18n_group = self.trAlgorithm('Vector general tools') self.addParameter(ParameterVector(self.INPUT, diff --git a/python/plugins/processing/algs/qgis/VectorGridPolygons.py b/python/plugins/processing/algs/qgis/VectorGridPolygons.py index ddb211305bf6..f69c24d9a59b 100644 --- a/python/plugins/processing/algs/qgis/VectorGridPolygons.py +++ b/python/plugins/processing/algs/qgis/VectorGridPolygons.py @@ -58,7 +58,7 @@ def defineCharacteristics(self): self.group, self.i18n_group = self.trAlgorithm('Vector creation tools') self.addParameter(ParameterExtent(self.EXTENT, - self.tr('Grid extent'))) + self.tr('Grid extent'), optional=False)) self.addParameter(ParameterNumber(self.STEP_X, self.tr('X spacing'), 0.0, 1000000000.0, 0.0001)) self.addParameter(ParameterNumber(self.STEP_Y, diff --git a/python/plugins/processing/algs/saga/SagaAlgorithm212.py b/python/plugins/processing/algs/saga/SagaAlgorithm212.py index dc5907b68329..03de55bf1f42 100644 --- a/python/plugins/processing/algs/saga/SagaAlgorithm212.py +++ b/python/plugins/processing/algs/saga/SagaAlgorithm212.py @@ -119,7 +119,7 @@ def defineCharacteristicsFromFile(self): # An extent parameter that wraps 4 SAGA numerical parameters self.extentParamNames = line[6:].strip().split(' ') self.addParameter(ParameterExtent(self.OUTPUT_EXTENT, - 'Output extent', '')) + 'Output extent')) else: self.addOutput(getOutputFromString(line)) line = lines.readline().strip('\n').strip() diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index 3301b7ba3078..d76f7dde53de 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -72,10 +72,7 @@ def __init__(self): # appear in the toolbox or modeler self.showInToolbox = True self.showInModeler = True - # if true, will show only loaded layers in parameters dialog. - # Also, if True, the algorithm does not run on the modeler - # or batch ptocessing interface - self.allowOnlyOpenedLayers = False + # False if it should not be run a a batch process self.canRunInBatchMode = True diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 45f02f9c5fdd..12902f1b5701 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -35,7 +35,7 @@ from qgis.PyQt.QtCore import QCoreApplication -from qgis.core import QgsRasterLayer, QgsVectorLayer +from qgis.core import QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsCoordinateReferenceSystem from processing.tools.vector import resolveFieldIndex, features from processing.tools.system import isWindows from processing.tools import dataobjects @@ -207,14 +207,29 @@ def __init__(self, name='', description='', default=None, optional=False, metada Parameter.__init__(self, name, description, default, optional, metadata) def setValue(self, value): - if value is None or value.strip() == '': + if not bool(value): if not self.optional: return False - self.value = None if value is None else value.strip() + self.value = None return True + if isinstance(value, QgsCoordinateReferenceSystem): + self.value = value.authid() + return True + if isinstance(value, QgsMapLayer): + self.value = value.crs().authid() + return True + try: + layer = dataobjects.getObjectFromUri(value) + if layer is not None: + self.value = layer.crs().authid() + return True + except: + pass + + # TODO: check it is a valid authid - self.value = str(value) + self.value = value return True def getValueAsCommandLineParameter(self): @@ -261,14 +276,30 @@ def __init__(self, name='', description='', default=None, optional=True): Parameter.__init__(self, name, description, default, optional) # The value is a string in the form "xmin, xmax, ymin, ymax" - def setValue(self, text): - if text is None: + def setValue(self, value): + if value is None: if not self.optional: return False self.value = None return True - tokens = str(text).split(',') + if isinstance(value, QgsMapLayer): + rect = value.extent() + self.value = '{},{},{},{}'.format( + rect.xMinimum(), rect.xMaximum(), rect.yMinimum(), rect.yMaximum()) + return True + + try: + layer = dataobjects.getObjectFromUri(value) + if layer is not None: + rect = layer.extent() + self.value = '{},{},{},{}'.format( + rect.xMinimum(), rect.xMaximum(), rect.yMinimum(), rect.yMaximum()) + return True + except: + pass + + tokens = str(value).split(',') if len(tokens) != 4: return False try: @@ -276,7 +307,7 @@ def setValue(self, text): float(tokens[1]) float(tokens[2]) float(tokens[3]) - self.value = text + self.value = value return True except: return False diff --git a/python/plugins/processing/gui/BatchInputSelectionPanel.py b/python/plugins/processing/gui/BatchInputSelectionPanel.py index 21d40bbadc0e..735f2b14efbf 100644 --- a/python/plugins/processing/gui/BatchInputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchInputSelectionPanel.py @@ -67,7 +67,7 @@ def __init__(self, param, row, col, dialog): self.setLayout(self.horizontalLayout) def _panel(self): - return self.dialog.mainDialog() + return self.dialog.mainWidget() def _table(self): return self._panel().tblParameters diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index 58d8441c7178..787008fb0745 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -36,14 +36,6 @@ from qgis.core import QgsApplication -from processing.gui.wrappers import NotYetImplementedWidgetWrapper - -from processing.gui.FileSelectionPanel import FileSelectionPanel -from processing.gui.CrsSelectionPanel import CrsSelectionPanel -from processing.gui.ExtentSelectionPanel import ExtentSelectionPanel -from processing.gui.FixedTablePanel import FixedTablePanel -from processing.gui.PointSelectionPanel import PointSelectionPanel -from processing.gui.BatchInputSelectionPanel import BatchInputSelectionPanel from processing.gui.BatchOutputSelectionPanel import BatchOutputSelectionPanel from processing.gui.GeometryPredicateSelectionPanel import GeometryPredicateSelectionPanel @@ -143,17 +135,6 @@ def initWidgets(self): self.tblParameters.verticalHeader().setResizeMode(QHeaderView.ResizeToContents) self.tblParameters.horizontalHeader().setStretchLastSection(True) - def getWidgetWrapperFromParameter(self, param, row, col): - return param.wrapper(self.parent, row, col) - - - def getWidgetFromParameter(self, param, row, col): - if isinstance(param, ParameterGeometryPredicate): - item = GeometryPredicateSelectionPanel(param.enabledPredicates, rows=1) - width = max(self.tblParameters.columnWidth(col), - item.sizeHint().width()) - self.tblParameters.setColumnWidth(col, width) - def load(self): filename, selected_filter = QFileDialog.getOpenFileName(self, self.tr('Open batch'), None, @@ -195,21 +176,6 @@ def load(self): self.tr('Error'), self.tr('An error occurred while reading your file.')) - def setValueInWidgetWrapper(self, wrapper, value): - if wrapper.implemented: - return wrapper.setValue(value) - self.setValueInWidget(wrapper.widget, value) - - def setValueInWidget(self, widget, value): - if isinstance(widget, (BatchOutputSelectionPanel, GeometryPredicateSelectionPanel)): - widget.setValue(unicode(value)) - elif isinstance(widget, ExtentSelectionPanel): - if value is not None: - widget.setExtentFromString(value) - else: - widget.setExtentFromString('') - - def save(self): toSave = [] for row in range(self.tblParameters.rowCount()): @@ -220,9 +186,6 @@ def save(self): for param in alg.parameters: if param.hidden: continue - if isinstance(param, ParameterExtent): - col += 1 - continue wrapper = self.wrappers[row][col] if not self.setParamValue(param, wrapper, alg): self.parent.lblProgress.setText( @@ -230,18 +193,6 @@ def save(self): return algParams[param.name] = param.getValueAsCommandLineParameter() col += 1 - col = 0 - for param in alg.parameters: - if param.hidden: - continue - if isinstance(param, ParameterExtent): - wrapper = self.wrappers[row][col] - if not self.setParamValue(param, wrapper, alg): - self.parent.lblProgress.setText( - self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) - return - algParams[param.name] = unicode(param.value()) - col += 1 for out in alg.outputs: if out.hidden: continue @@ -267,25 +218,14 @@ def save(self): json.dump(toSave, f) def setParamValue(self, param, wrapper, alg=None): - if wrapper.implemented: - return param.setValue(wrapper.value()) - - widget = wrapper.widget - if isinstance(param, ParameterExtent): - if alg is not None: - widget.useNewAlg(alg) - return param.setValue(widget.getValue()) - elif isinstance(param, ParameterGeometryPredicate): - return param.setValue(widget.value()) - else: - return param.setValue(widget.text()) + return param.setValue(wrapper.value()) def setCellWrapper(self, row, column, wrapper): self.wrappers[row][column] = wrapper self.tblParameters.setCellWidget(row, column, wrapper.widget) def addRow(self): - self.widget_wrappers.append([None] * self.tblParameters.columnCount()) + self.wrappers.append([None] * self.tblParameters.columnCount()) self.tblParameters.setRowCount(self.tblParameters.rowCount() + 1) row = self.tblParameters.rowCount() - 1 @@ -294,7 +234,7 @@ def addRow(self): if param.hidden: continue - wrapper = self.getWidgetWrapperFromParameter(param, row, column) + wrapper = param.wrapper(self.parent, row, column) self.setCellWrapper(row, column, wrapper) column += 1 @@ -315,53 +255,15 @@ def addRow(self): self.tblParameters.setCellWidget(row, column, item) def removeRows(self): - # ~ self.tblParameters.setUpdatesEnabled(False) - # ~ indexes = self.tblParameters.selectionModel().selectedIndexes() - # ~ indexes.sort() - # ~ for i in reversed(indexes): - # ~ self.tblParameters.model().removeRow(i.row()) - # ~ self.tblParameters.setUpdatesEnabled(True) if self.tblParameters.rowCount() > 2: - self.widget_wrappers.pop() + self.wrappers.pop() self.tblParameters.setRowCount(self.tblParameters.rowCount() - 1) def fillParameterValues(self, column): - widget = self.tblParameters.cellWidget(0, column) - - if isinstance(widget, QComboBox): - widgetValue = widget.currentIndex() - for row in range(1, self.tblParameters.rowCount()): - self.tblParameters.cellWidget(row, column).setCurrentIndex(widgetValue) - elif isinstance(widget, ExtentSelectionPanel): - widgetValue = widget.getValue() - for row in range(1, self.tblParameters.rowCount()): - if widgetValue is not None: - self.tblParameters.cellWidget(row, column).setExtentFromString(widgetValue) - else: - self.tblParameters.cellWidget(row, column).setExtentFromString('') - elif isinstance(widget, CrsSelectionPanel): - widgetValue = widget.getValue() - for row in range(1, self.tblParameters.rowCount()): - self.tblParameters.cellWidget(row, column).setAuthId(widgetValue) - elif isinstance(widget, FileSelectionPanel): - widgetValue = widget.getValue() - for row in range(1, self.tblParameters.rowCount()): - self.tblParameters.cellWidget(row, column).setText(widgetValue) - elif isinstance(widget, QLineEdit): - widgetValue = widget.text() - for row in range(1, self.tblParameters.rowCount()): - self.tblParameters.cellWidget(row, column).setText(widgetValue) - elif isinstance(widget, BatchInputSelectionPanel): - widgetValue = widget.getText() - for row in range(1, self.tblParameters.rowCount()): - self.tblParameters.cellWidget(row, column).setText(widgetValue) - elif isinstance(widget, GeometryPredicateSelectionPanel): - widgetValue = widget.value() - for row in range(1, self.tblParameters.rowCount()): - self.tblParameters.cellWidget(row, column).setValue(widgetValue) - else: - pass - + wrapper = self.wrappers[0][column] + for row in range(1, self.tblParameters.rowCount()): + self.wrappers[row][column].setValue(wrapper.value()) + def toggleAdvancedMode(self, checked): for column, param in enumerate(self.alg.parameters): if param.isAdvanced: diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index f72835091a5f..f8299221e7c1 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -37,27 +37,15 @@ from qgis.PyQt import uic from qgis.PyQt.QtCore import QCoreApplication, QVariant -from qgis.PyQt.QtWidgets import QWidget, QLayout, QVBoxLayout, QHBoxLayout, QToolButton, QLabel, QCheckBox, QComboBox, QLineEdit, QPlainTextEdit +from qgis.PyQt.QtWidgets import (QWidget, QLayout, QVBoxLayout, QHBoxLayout, QToolButton, + QLabel, QCheckBox, QComboBox, QLineEdit, QPlainTextEdit) from qgis.PyQt.QtGui import QIcon -from processing.core.ProcessingConfig import ProcessingConfig - -from processing.gui.wrappers import NotYetImplementedWidgetWrapper - from processing.gui.OutputSelectionPanel import OutputSelectionPanel -from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel -from processing.gui.FixedTablePanel import FixedTablePanel -from processing.gui.RangePanel import RangePanel -from processing.gui.MultipleInputPanel import MultipleInputPanel -from processing.gui.NumberInputPanel import NumberInputPanel -from processing.gui.ExtentSelectionPanel import ExtentSelectionPanel -from processing.gui.FileSelectionPanel import FileSelectionPanel -from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.PointSelectionPanel import PointSelectionPanel from processing.gui.GeometryPredicateSelectionPanel import \ GeometryPredicateSelectionPanel from processing.gui.ListMultiselectWidget import ListMultiSelectWidget - from processing.core.parameters import ParameterRaster from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterTable diff --git a/python/plugins/processing/gui/ProcessingToolbox.py b/python/plugins/processing/gui/ProcessingToolbox.py index 3f45215e3db5..f216db586fdb 100644 --- a/python/plugins/processing/gui/ProcessingToolbox.py +++ b/python/plugins/processing/gui/ProcessingToolbox.py @@ -187,7 +187,7 @@ def showPopupMenu(self, point): executeAction = QAction(self.tr('Execute'), self.algorithmTree) executeAction.triggered.connect(self.executeAlgorithm) popupmenu.addAction(executeAction) - if alg.canRunInBatchMode and not alg.allowOnlyOpenedLayers: + if alg.canRunInBatchMode: executeBatchAction = QAction( self.tr('Execute as batch process'), self.algorithmTree) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 6de1b00233aa..bd58e86c1d8d 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -40,7 +40,7 @@ from processing.gui.PointSelectionPanel import PointSelectionPanel from processing.core.parameters import (ParameterBoolean, ParameterPoint, ParameterFile, ParameterRaster, ParameterVector, ParameterNumber, ParameterString, ParameterTable, - ParameterTableField, ParameterExtent, ParameterFixedTable) + ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs) from processing.core.ProcessingConfig import ProcessingConfig from processing.gui.FileSelectionPanel import FileSelectionPanel from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, @@ -59,15 +59,6 @@ class InvalidParameterValue(Exception): pass -class NotYetImplementedWidgetWrapper(): - - """Temporary substitute class for not yet implemented wrappers""" - - implemented = False - - def __init__(self, param, widget): - self.param = param - self.widget = widget dialogTypes = {"AlgorithmDialog":DIALOG_STANDARD, "ModelerParametersDialog":DIALOG_MODELER, @@ -82,8 +73,6 @@ def getExtendedLayerName(layer): class WidgetWrapper(QObject): - implemented = True # TODO: Should be removed at the end - widgetValueHasChanged = pyqtSignal(object) def __init__(self, param, dialog, row=0, col=0): @@ -120,11 +109,14 @@ def setComboValue(self, value): try: idx = values.index(value) self.widget.setCurrentIndex(idx) + return except ValueError: pass if self.widget.isEditable(): if value is not None: self.widget.setEditText(unicode(value)) + else: + self.widget.setCurrentIndex(0) def value(self): pass @@ -175,6 +167,8 @@ def setValue(self, value): def value(self): if self.dialogType == DIALOG_STANDARD: return self.widget.isChecked() + elif self.dialogType == DIALOG_BATCH: + return self.widget.currentIndex == 0 else: return self.comboValue() @@ -182,31 +176,61 @@ def value(self): class CrsWidgetWrapper(WidgetWrapper): def createWidget(self): - return CrsSelectionPanel() + if self.dialogType == DIALOG_MODELER: + widget = QComboBox() + widget.setEditable(True) + crss = self.dialog.getAvailableValuesOfType(ParameterCrs) + for crs in crss: + widget.addItem(self.dialog.resolveValueDescription(crs), crs) + raster = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) + vector = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) + for r in raster: + widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(r), r) + for v in vector: + widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(v), v) + if not self.param.default: + widget.setEditText(self.param.default) + return widget + else: + return CrsSelectionPanel() def setValue(self, value): - if isinstance(value, basestring): # authId - self.widget.crs = value + if self.dialogType == DIALOG_MODELER: + self.setComboValue(value) else: - self.widget.crs = QgsCoordinateReferenceSystem(value).authid() - self.widget.updateText() + if isinstance(value, basestring): # authId + self.widget.crs = value + else: + self.widget.crs = QgsCoordinateReferenceSystem(value).authid() + self.widget.updateText() def value(self): - return self.widget.getValue() + if self.dialogType == DIALOG_MODELER: + return self.comboValue() + else: + return self.widget.getValue() class ExtentWidgetWrapper(WidgetWrapper): + USE_MIN_COVERING_EXTENT = "[Use min covering extent]" + def createWidget(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): return ExtentSelectionPanel(self.dialog, self.param) else: widget = QComboBox() widget.setEditable(True) - extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) + extents = self.dialog.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.param.optional: widget.addItem(self.USE_MIN_COVERING_EXTENT, None) + raster = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) + vector = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) for ex in extents: widget.addItem(self.dialog.resolveValueDescription(ex), ex) + for r in raster: + widget.addItem("Extent of " + self.dialog.resolveValueDescription(r), r) + for v in vector: + widget.addItem("Extent of " + self.dialog.resolveValueDescription(v), v) if not self.param.default: widget.setEditText(self.param.default) return widget @@ -674,8 +698,8 @@ def createWidget(self): return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: widget = QComboBox() - tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) - layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) + tables = self.dialog.getAvailableValuesOfType(ParameterTable, OutputTable) + layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) if self.param.optional: widget.addItem(self.NOT_SELECTED, None) for table in tables: @@ -720,11 +744,11 @@ def createWidget(self): else: widget = QComboBox() widget.setEditable(True) - fields = self.getAvailableValuesOfType(ParameterTableField, None) + fields = self.dialog.getAvailableValuesOfType(ParameterTableField, None) if self.param.optional: - widget.addItem(self.NOT_SELECTED, None) + widget.addItem(self.NOT_SET, None) for f in fields: - widget.addItem(self.resolveValueDescription(f), f) + widget.addItem(self.dialog.resolveValueDescription(f), f) return widget def postInitialize(self, wrappers): diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index d3c95faf1d89..cdbc42da12b8 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -480,7 +480,7 @@ def fillAlgorithmTreeUsingProviders(self): # Add algorithms for alg in algs: - if not alg.showInModeler or alg.allowOnlyOpenedLayers: + if not alg.showInModeler: continue if alg.commandLineName() == self.alg.commandLineName(): continue diff --git a/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py b/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py index 479099d10bd6..dce630ffbe92 100644 --- a/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py +++ b/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py @@ -29,10 +29,6 @@ from qgis.PyQt.QtGui import QIcon from processing.core.AlgorithmProvider import AlgorithmProvider from processing.modeler.CalculatorModelerAlgorithm import CalculatorModelerAlgorithm -from processing.modeler.RasterLayerBoundsAlgorithm import RasterLayerBoundsAlgorithm -from processing.modeler.VectorLayerBoundsAlgorithm import VectorLayerBoundsAlgorithm -from processing.modeler.RasterLayerCrsAlgorithm import RasterLayerCrsAlgorithm -from processing.modeler.VectorLayerCrsAlgorithm import VectorLayerCrsAlgorithm pluginPath = os.path.split(os.path.dirname(__file__))[0] @@ -52,10 +48,6 @@ def getIcon(self): return QIcon(os.path.join(pluginPath, 'images', 'model.png')) def _loadAlgorithms(self): - self.algs = [CalculatorModelerAlgorithm(), - RasterLayerBoundsAlgorithm(), - VectorLayerBoundsAlgorithm(), - RasterLayerCrsAlgorithm(), - VectorLayerCrsAlgorithm()] + self.algs = [CalculatorModelerAlgorithm()] for alg in self.algs: alg.provider = self diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index e2295896d020..d262f064e59a 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -40,11 +40,8 @@ from qgis.gui import QgsMessageBar -from processing.gui.wrappers import NotYetImplementedWidgetWrapper, InvalidParameterValue -from processing.gui.CrsSelectionPanel import CrsSelectionPanel +from processing.gui.wrappers import InvalidParameterValue from processing.gui.MultipleInputPanel import MultipleInputPanel -from processing.gui.FixedTablePanel import FixedTablePanel -from processing.gui.RangePanel import RangePanel from processing.gui.GeometryPredicateSelectionPanel import \ GeometryPredicateSelectionPanel from processing.core.parameters import (ParameterExtent, @@ -85,74 +82,6 @@ from qgis.PyQt.QtGui import QToolButton, QMenu, QAction -class ModelerWidgetWrapper(QWidget): - - def __init__(self, wrapper, model_values): - super(ModelerWidgetWrapper, self).__init__() - - self.wrapper = wrapper - self.widget = wrapper.widget - self.implemented = wrapper.implemented - self.model_values = model_values - - menu = QMenu() - fixed_value_action = QAction(self.tr('Fixed value'), menu) - fixed_value_action.triggered.connect(self.on_fixedValue) - menu.addAction(fixed_value_action) - menu.addSeparator() - for text, value in model_values: - model_value_action = QAction(text, menu) - model_value_action.setData(value) - model_value_action.triggered.connect(self.on_modelValue) - menu.addAction(model_value_action) - - self.mIconDataDefine = QgsApplication.getThemeIcon("/mIconDataDefine.svg") - self.mIconDataDefineOn = QgsApplication.getThemeIcon("/mIconDataDefineOn.svg") - - button = QToolButton() - button.setIcon(self.mIconDataDefine) - button.setPopupMode(QToolButton.InstantPopup) - button.setMenu(menu) - self.button = button - - label = QLabel() - label.hide() - self.label = label - - layout = QHBoxLayout() - layout.addWidget(button, 0) - layout.addWidget(label, 1) - layout.addWidget(wrapper.widget, 1) - self.setLayout(layout) - - def on_fixedValue(self): - self.button.setIcon(self.mIconDataDefine) - self.label.hide() - self.wrapper.widget.show() - - def on_modelValue(self): - action = self.sender() - self.setValue(action.data()) - - def setValue(self, value): - for text, val in self.model_values: - if val == value: - self.model_value = value - self.button.setIcon(self.mIconDataDefineOn) - self.label.setText(text) - self.label.show() - self.wrapper.widget.hide() - return - self.wrapper.setValue(value) - self.on_fixedValue() - - def value(self): - if self.label.isVisible(): - return self.model_value - else: - return self.wrapper.value() - - class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' @@ -391,12 +320,6 @@ def resolveValueDescription(self, value): alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) - def canUseAutoExtent(self): - for param in self._alg.parameters: - if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): - return True - return False - def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs diff --git a/python/plugins/processing/modeler/RasterLayerBoundsAlgorithm.py b/python/plugins/processing/modeler/RasterLayerBoundsAlgorithm.py deleted file mode 100644 index 98ecb3908dda..000000000000 --- a/python/plugins/processing/modeler/RasterLayerBoundsAlgorithm.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - RasterLayerBoundsAlgorithm.py - --------------------- - Date : January 2013 - Copyright : (C) 2013 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Victor Olaya' -__date__ = 'January 2013' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterRaster -from processing.core.outputs import OutputNumber -from processing.core.outputs import OutputExtent -from processing.tools import dataobjects - - -class RasterLayerBoundsAlgorithm(GeoAlgorithm): - - LAYER = 'LAYER' - XMIN = 'XMIN' - XMAX = 'XMAX' - YMIN = 'YMIN' - YMAX = 'YMAX' - EXTENT = 'EXTENT' - - def defineCharacteristics(self): - self.showInModeler = True - self.showInToolbox = False - self.name = self.tr('Raster layer bounds', 'RasterLayerBoundsAlgorithm') - self.group = self.tr('Modeler-only tools', 'RasterLayerBoundsAlgorithm') - self.addParameter(ParameterRaster(self.LAYER, self.tr('Layer', 'RasterLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.XMIN, self.tr('min X', 'RasterLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.XMAX, self.tr('max X', 'RasterLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.YMIN, self.tr('min Y', 'RasterLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.YMAX, self.tr('max Y', 'RasterLayerBoundsAlgorithm'))) - self.addOutput(OutputExtent(self.EXTENT, self.tr('Extent', 'RasterLayerBoundsAlgorithm'))) - - def processAlgorithm(self, progress): - uri = self.getParameterValue(self.LAYER) - layer = dataobjects.getObjectFromUri(uri) - self.setOutputValue(self.XMIN, layer.extent().xMinimum()) - self.setOutputValue(self.XMAX, layer.extent().xMaximum()) - self.setOutputValue(self.YMIN, layer.extent().yMinimum()) - self.setOutputValue(self.YMAX, layer.extent().yMaximum()) - self.setOutputValue(self.EXTENT, (layer.extent().xMinimum(), - layer.extent().xMaximum(), - layer.extent().yMinimum(), - layer.extent().yMaximum())) diff --git a/python/plugins/processing/modeler/RasterLayerCrsAlgorithm.py b/python/plugins/processing/modeler/RasterLayerCrsAlgorithm.py deleted file mode 100644 index c5e2136d6341..000000000000 --- a/python/plugins/processing/modeler/RasterLayerCrsAlgorithm.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - RasterLayerCrsAlgorithm.py - --------------------- - Date : August 2016 - Copyright : (C) 2016 by Alexander Bruy - Email : alexander dot bruy at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Alexander Bruy' -__date__ = 'August 2016' -__copyright__ = '(C) 2016, Alexander Bruy' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterRaster -from processing.core.outputs import OutputCrs -from processing.tools import dataobjects - - -class RasterLayerCrsAlgorithm(GeoAlgorithm): - - LAYER = 'LAYER' - CRS = 'CRS' - - def defineCharacteristics(self): - self.showInModeler = True - self.showInToolbox = False - - self.name = self.tr('Raster layer CRS', 'RasterLayerCrsAlgorithm') - self.group = self.tr('Modeler-only tools', 'RasterLayerCrsAlgorithm') - - self.addParameter(ParameterRaster(self.LAYER, self.tr('Layer', 'RasterLayerCrsAlgorithm'))) - self.addOutput(OutputCrs(self.CRS, self.tr('CRS', 'RasterLayerCrsAlgorithm'))) - - def processAlgorithm(self, progress): - layer = dataobjects.getObjectFromUri(self.getParameterValue(self.LAYER)) - self.setOutputValue(self.CRS, layer.crs().authid()) diff --git a/python/plugins/processing/modeler/VectorLayerBoundsAlgorithm.py b/python/plugins/processing/modeler/VectorLayerBoundsAlgorithm.py deleted file mode 100644 index dafc9047df1f..000000000000 --- a/python/plugins/processing/modeler/VectorLayerBoundsAlgorithm.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - VectorLayerBoundsAlgorithm.py - --------------------- - Date : January 2013 - Copyright : (C) 2013 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Victor Olaya' -__date__ = 'January 2013' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterVector -from processing.core.outputs import OutputNumber -from processing.core.outputs import OutputExtent -from processing.tools import dataobjects - - -class VectorLayerBoundsAlgorithm(GeoAlgorithm): - - LAYER = 'LAYER' - XMIN = 'XMIN' - XMAX = 'XMAX' - YMIN = 'YMIN' - YMAX = 'YMAX' - EXTENT = 'EXTENT' - - def defineCharacteristics(self): - self.showInModeler = True - self.showInToolbox = False - self.name = self.tr('Vector layer bounds', 'VectorLayerBoundsAlgorithm') - self.group = self.tr('Modeler-only tools', 'VectorLayerBoundsAlgorithm') - self.addParameter(ParameterVector(self.LAYER, self.tr('Layer', 'VectorLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.XMIN, self.tr('min X', 'VectorLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.XMAX, self.tr('max X', 'VectorLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.YMIN, self.tr('min Y', 'VectorLayerBoundsAlgorithm'))) - self.addOutput(OutputNumber(self.YMAX, self.tr('max Y', 'VectorLayerBoundsAlgorithm'))) - self.addOutput(OutputExtent(self.EXTENT, self.tr('Extent', 'VectorLayerBoundsAlgorithm'))) - - def processAlgorithm(self, progress): - uri = self.getParameterValue(self.LAYER) - layer = dataobjects.getObjectFromUri(uri) - self.setOutputValue(self.XMIN, layer.extent().xMinimum()) - self.setOutputValue(self.XMAX, layer.extent().xMaximum()) - self.setOutputValue(self.YMIN, layer.extent().yMinimum()) - self.setOutputValue(self.YMAX, layer.extent().yMaximum()) - self.setOutputValue(self.EXTENT, (layer.extent().xMinimum(), - layer.extent().xMaximum(), - layer.extent().yMinimum(), - layer.extent().yMaximum())) diff --git a/python/plugins/processing/modeler/VectorLayerCrsAlgorithm.py b/python/plugins/processing/modeler/VectorLayerCrsAlgorithm.py deleted file mode 100644 index 56922021a271..000000000000 --- a/python/plugins/processing/modeler/VectorLayerCrsAlgorithm.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - VectorLayerCrsAlgorithm.py - --------------------- - Date : August 2016 - Copyright : (C) 2016 by Alexander Bruy - Email : alexander dot bruy at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Alexander Bruy' -__date__ = 'August 2016' -__copyright__ = '(C) 2016, Alexander Bruy' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterVector -from processing.core.outputs import OutputCrs -from processing.tools import dataobjects - - -class VectorLayerCrsAlgorithm(GeoAlgorithm): - - LAYER = 'LAYER' - CRS = 'CRS' - - def defineCharacteristics(self): - self.showInModeler = True - self.showInToolbox = False - - self.name = self.tr('Vector layer CRS', 'VectorLayerCrsAlgorithm') - self.group = self.tr('Modeler-only tools', 'VectorLayerCrsAlgorithm') - - self.addParameter(ParameterVector(self.LAYER, self.tr('Layer', 'VectorLayerCrsAlgorithm'), )) - self.addOutput(OutputCrs(self.CRS, self.tr('CRS', 'VectorLayerCrsAlgorithm'))) - - def processAlgorithm(self, progress): - layer = dataobjects.getObjectFromUri(self.getParameterValue(self.LAYER)) - self.setOutputValue(self.CRS, layer.crs().authid()) diff --git a/python/plugins/processing/script/ScriptAlgorithm.py b/python/plugins/processing/script/ScriptAlgorithm.py index 95ad656122cb..e1a46f12728b 100644 --- a/python/plugins/processing/script/ScriptAlgorithm.py +++ b/python/plugins/processing/script/ScriptAlgorithm.py @@ -33,21 +33,7 @@ from qgis.PyQt.QtGui import QIcon from processing.core.GeoAlgorithm import GeoAlgorithm from processing.gui.Help2Html import getHtmlFromHelpFile -from processing.core.parameters import ParameterRaster -from processing.core.parameters import ParameterTable -from processing.core.parameters import ParameterVector -from processing.core.parameters import ParameterMultipleInput -from processing.core.parameters import ParameterString -from processing.core.parameters import ParameterCrs -from processing.core.parameters import ParameterNumber -from processing.core.parameters import ParameterBoolean -from processing.core.parameters import ParameterSelection -from processing.core.parameters import ParameterTableField -from processing.core.parameters import ParameterTableMultipleField -from processing.core.parameters import ParameterExtent -from processing.core.parameters import ParameterFile -from processing.core.parameters import ParameterPoint -from processing.core.parameters import getParameterFromString +from processing.core.parameters import getParameterFromString, paramClasses from processing.core.outputs import OutputTable from processing.core.outputs import OutputVector from processing.core.outputs import OutputRaster @@ -58,7 +44,6 @@ from processing.core.outputs import OutputDirectory from processing.core.outputs import getOutputFromString from processing.core.ProcessingLog import ProcessingLog -from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.script.WrongScriptException import WrongScriptException from processing.tools import dataobjects From 01f380863fd746e8d494450a47d7a4535888cde1 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 8 Sep 2016 10:30:30 +0200 Subject: [PATCH 120/897] [processing] improvements for scripts and R scripts --- .../plugins/processing/algs/r/RAlgorithm.py | 128 ++---------------- python/plugins/processing/core/outputs.py | 53 +++++++- python/plugins/processing/core/parameters.py | 8 +- .../processing/script/ScriptAlgorithm.py | 73 +--------- 4 files changed, 65 insertions(+), 197 deletions(-) diff --git a/python/plugins/processing/algs/r/RAlgorithm.py b/python/plugins/processing/algs/r/RAlgorithm.py index d9a921e2c33b..107207000f40 100644 --- a/python/plugins/processing/algs/r/RAlgorithm.py +++ b/python/plugins/processing/algs/r/RAlgorithm.py @@ -56,6 +56,8 @@ from processing.core.outputs import OutputRaster from processing.core.outputs import OutputHTML from processing.core.outputs import OutputFile +from processing.core.parameters import getParameterFromString +from processing.core.outputs import getOutputFromString from processing.tools import dataobjects from processing.tools.system import isWindows from processing.script.WrongScriptException import WrongScriptException @@ -148,7 +150,6 @@ def createDescriptiveName(self, s): def processParameterLine(self, line): param = None - out = None line = line.replace('#', '') if line.lower().strip().startswith('showplots'): self.showPlots = True @@ -169,133 +170,24 @@ def processParameterLine(self, line): self.name = self.i18n_name = tokens[0] return - if tokens[1].lower().strip().startswith('output'): - outToken = tokens[1].strip()[len('output') + 1:] - out = self.processOutputParameterToken(outToken) - - elif tokens[1].lower().strip().startswith('optional'): - optToken = tokens[1].strip()[len('optional') + 1:] - param = self.processInputParameterToken(optToken, tokens[0]) - if param: - param.optional = True - - else: - param = self.processInputParameterToken(tokens[1], tokens[0]) + out = getOutputFromString(line) + if out is None: + param = getParameterFromString(line) if param is not None: self.addParameter(param) elif out is not None: out.name = tokens[0] - out.description = tokens[0] + out.description = desc self.addOutput(out) else: raise WrongScriptException( - self.tr('Could not load R script: %s.\n Problem with line %s' % (self.descriptionFile, line))) - - def processInputParameterToken(self, token, name): - param = None - - desc = self.createDescriptiveName(name) - - if token.lower().strip().startswith('raster'): - param = ParameterRaster(name, desc, False) - elif token.lower().strip() == 'vector': - param = ParameterVector(name, desc, - [dataobjects.TYPE_VECTOR_ANY]) - elif token.lower().strip() == 'vector point': - param = ParameterVector(name, desc, - [dataobjects.TYPE_VECTOR_POINT]) - elif token.lower().strip() == 'vector line': - param = ParameterVector(name, desc, - [dataobjects.TYPE_VECTOR_LINE]) - elif token.lower().strip() == 'vector polygon': - param = ParameterVector(name, desc, - [dataobjects.TYPE_VECTOR_POLYGON]) - elif token.lower().strip() == 'table': - param = ParameterTable(name, desc, False) - elif token.lower().strip().startswith('multiple raster'): - param = ParameterMultipleInput(name, desc, - dataobjects.TYPE_RASTER) - param.optional = False - elif token.lower().strip() == 'multiple vector': - param = ParameterMultipleInput(name, desc, - dataobjects.TYPE_VECTOR_ANY) - param.optional = False - elif token.lower().strip().startswith('selection'): - options = token.strip()[len('selection'):].split(';') - param = ParameterSelection(name, desc, options) - elif token.lower().strip().startswith('boolean'): - default = token.strip()[len('boolean') + 1:] - if default: - param = ParameterBoolean(name, desc, default) - else: - param = ParameterBoolean(name, desc) - elif token.lower().strip().startswith('number'): - default = token.strip()[len('number') + 1:] - if default: - param = ParameterNumber(name, desc, default=default) - else: - param = ParameterNumber(name, desc) - elif token.lower().strip().startswith('field'): - field = token.strip()[len('field') + 1:] - found = False - for p in self.parameters: - if p.name == field: - found = True - break - if found: - param = ParameterTableField(name, desc, field) - elif token.lower().strip().startswith('multiple field'): - field = token.strip()[len('multiple field') + 1:] - found = False - for p in self.parameters: - if p.name == field: - found = True - break - if found: - param = ParameterTableMultipleField(token, desc, field) - elif token.lower().strip() == 'extent': - param = ParameterExtent(name, desc) - elif token.lower().strip() == 'point': - param = ParameterPoint(name, desc) - elif token.lower().strip() == 'file': - param = ParameterFile(name, desc, False) - elif token.lower().strip() == 'folder': - param = ParameterFile(name, desc, True) - elif token.lower().strip().startswith('string'): - default = token.strip()[len('string') + 1:] - if default: - param = ParameterString(name, desc, default) - else: - param = ParameterString(name, desc) - elif token.lower().strip().startswith('longstring'): - default = token.strip()[len('longstring') + 1:] - if default: - param = ParameterString(name, desc, default, multiline=True) - else: - param = ParameterString(name, desc, multiline=True) - elif token.lower().strip() == 'crs': - default = token.strip()[len('crs') + 1:] - if default: - param = ParameterCrs(name, desc, default) - else: - param = ParameterCrs(name, desc) + self.tr('Could not load script: %s.\n' + 'Problem with line "%s"', 'ScriptAlgorithm') % (self.descriptionFile or '', line)) - return param - - def processOutputParameterToken(self, token): - out = None - - if token.lower().strip().startswith('raster'): - out = OutputRaster() - elif token.lower().strip().startswith('vector'): - out = OutputVector() - elif token.lower().strip().startswith('table'): - out = OutputTable() - elif token.lower().strip().startswith('file'): - out = OutputFile() + raise WrongScriptException( + self.tr('Could not load R script: %s.\n Problem with line %s' % (self.descriptionFile, line))) - return out def processAlgorithm(self, progress): if isWindows(): diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index e7d1081334ee..0e1a69049ef4 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -39,13 +39,6 @@ from processing.tools import dataobjects -def getOutputFromString(s): - tokens = s.split("|") - params = [t if str(t) != "None" else None for t in tokens[1:]] - clazz = getattr(sys.modules[__name__], tokens[0]) - return clazz(*params) - - class Output(object): def __init__(self, name='', description='', hidden=False): @@ -351,3 +344,49 @@ def getVectorWriter(self, fields, geomType, crs, options=None): def dataType(self): return dataobjects.vectorDataType(self) + + + +def getOutputFromString(s): + try: + if "|" in s: + tokens = s.split("|") + params = [t if unicode(t) != "None" else None for t in tokens[1:]] + clazz = getattr(sys.modules[__name__], tokens[0]) + return clazz(*params) + else: + tokens = s.split("=") + token = tokens[1].strip()[len('output') + 1:] + out = None + + if token.lower().strip().startswith('raster'): + out = OutputRaster() + elif token.lower().strip() == 'vector': + out = OutputVector() + elif token.lower().strip() == 'vector point': + out = OutputVector(datatype=[dataobjects.TYPE_VECTOR_POINT]) + elif token.lower().strip() == 'vector line': + out = OutputVector(datatype=[OutputVector.TYPE_VECTOR_LINE]) + elif token.lower().strip() == 'vector polygon': + out = OutputVector(datatype=[OutputVector.TYPE_VECTOR_POLYGON]) + elif token.lower().strip().startswith('table'): + out = OutputTable() + elif token.lower().strip().startswith('html'): + out = OutputHTML() + elif token.lower().strip().startswith('file'): + out = OutputFile() + subtokens = token.split(' ') + if len(subtokens) > 2: + out.ext = subtokens[2] + elif token.lower().strip().startswith('directory'): + out = OutputDirectory() + elif token.lower().strip().startswith('number'): + out = OutputNumber() + elif token.lower().strip().startswith('string'): + out = OutputString() + elif token.lower().strip().startswith('extent'): + out = OutputExtent() + + return out + except: + return None \ No newline at end of file diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 12902f1b5701..c53aaa4f0fde 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1360,13 +1360,17 @@ def setValue(self, value): paramClasses = [c for c in sys.modules[__name__].__dict__.values() if isclass(c) and issubclass(c, Parameter)] def getParameterFromString(s): - print s # Try the parameter definitions used in description files if '|' in s: + isAdvanced = False + if s.startswith("*"): + s = s[1:] + isAdvanced = True tokens = s.split("|") params = [t if unicode(t) != unicode(None) else None for t in tokens[1:]] clazz = getattr(sys.modules[__name__], tokens[0]) - return clazz(*params) + param = clazz(*params) + param.isAdvanced = isAdvanced else: # try script syntax for paramClass in paramClasses: try: diff --git a/python/plugins/processing/script/ScriptAlgorithm.py b/python/plugins/processing/script/ScriptAlgorithm.py index e1a46f12728b..d1153a3d1b68 100644 --- a/python/plugins/processing/script/ScriptAlgorithm.py +++ b/python/plugins/processing/script/ScriptAlgorithm.py @@ -33,21 +33,11 @@ from qgis.PyQt.QtGui import QIcon from processing.core.GeoAlgorithm import GeoAlgorithm from processing.gui.Help2Html import getHtmlFromHelpFile -from processing.core.parameters import getParameterFromString, paramClasses -from processing.core.outputs import OutputTable -from processing.core.outputs import OutputVector -from processing.core.outputs import OutputRaster -from processing.core.outputs import OutputNumber -from processing.core.outputs import OutputString -from processing.core.outputs import OutputHTML -from processing.core.outputs import OutputFile -from processing.core.outputs import OutputDirectory +from processing.core.parameters import getParameterFromString from processing.core.outputs import getOutputFromString from processing.core.ProcessingLog import ProcessingLog from processing.script.WrongScriptException import WrongScriptException -from processing.tools import dataobjects - pluginPath = os.path.split(os.path.dirname(__file__))[0] @@ -128,7 +118,6 @@ def createDescriptiveName(self, s): def processParameterLine(self, line): param = None - out = None line = line.replace('#', '') if line == "nomodeler": @@ -146,10 +135,8 @@ def processParameterLine(self, line): self.name = self.i18n_name = tokens[0] return - if tokens[1].lower().strip().startswith('output'): - outToken = tokens[1].strip()[len('output') + 1:] - out = self.processOutputParameterToken(outToken) - else: + out = getOutputFromString(line) + if out is None: param = getParameterFromString(line) if param is not None: @@ -163,60 +150,6 @@ def processParameterLine(self, line): self.tr('Could not load script: %s.\n' 'Problem with line "%s"', 'ScriptAlgorithm') % (self.descriptionFile or '', line)) - def processInputParameterLine(self, line): - for paramClass in paramClasses: - param = paramClass.fromScriptCode(line) - if param is not None: - return param - - def processOutputParameterToken(self, token): - out = None - - if token.lower().strip().startswith('raster'): - out = OutputRaster() - elif token.lower().strip() == 'vector': - out = OutputVector() - elif token.lower().strip() == 'vector point': - out = OutputVector(datatype=[dataobjects.TYPE_VECTOR_POINT]) - elif token.lower().strip() == 'vector line': - out = OutputVector(datatype=[OutputVector.TYPE_VECTOR_LINE]) - elif token.lower().strip() == 'vector polygon': - out = OutputVector(datatype=[OutputVector.TYPE_VECTOR_POLYGON]) - elif token.lower().strip().startswith('table'): - out = OutputTable() - elif token.lower().strip().startswith('html'): - out = OutputHTML() - elif token.lower().strip().startswith('file'): - out = OutputFile() - subtokens = token.split(' ') - if len(subtokens) > 2: - out.ext = subtokens[2] - elif token.lower().strip().startswith('directory'): - out = OutputDirectory() - elif token.lower().strip().startswith('number'): - out = OutputNumber() - elif token.lower().strip().startswith('string'): - out = OutputString() - elif token.lower().strip().startswith('extent'): - out = OutputExtent() - - return out - - def processDescriptionParameterLine(self, line): - try: - if line.startswith('Parameter'): - self.addParameter(getParameterFromString(line)) - elif line.startswith('*Parameter'): - param = getParameterFromString(line[1:]) - param.isAdvanced = True - self.addParameter(param) - else: - self.addOutput(getOutputFromString(line)) - except Exception: - raise WrongScriptException( - self.tr('Could not load script: %s.\n' - 'Problem with line %d', 'ScriptAlgorithm') % (self.descriptionFile or '', line)) - def processAlgorithm(self, progress): ns = {} ns['progress'] = progress From e353d226a8cc0904bfbd6b5809f88bbd9de45798 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 9 Sep 2016 07:02:54 +0200 Subject: [PATCH 121/897] [processing] evaluate parameters before executing algorithm This allows a better use of expressions --- .../plugins/processing/core/GeoAlgorithm.py | 68 +------ python/plugins/processing/core/parameters.py | 180 ++++++++++++++++-- .../plugins/processing/gui/AlgorithmDialog.py | 16 +- .../processing/gui/NumberInputDialog.py | 153 --------------- .../processing/gui/NumberInputPanel.py | 115 ++--------- .../processing/gui/StringInputPanel.py | 74 +++++++ python/plugins/processing/gui/wrappers.py | 22 +-- .../processing/ui/widgetNumberSelector.ui | 58 ------ 8 files changed, 264 insertions(+), 422 deletions(-) delete mode 100644 python/plugins/processing/gui/NumberInputDialog.py create mode 100644 python/plugins/processing/gui/StringInputPanel.py delete mode 100644 python/plugins/processing/ui/widgetNumberSelector.ui diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index d76f7dde53de..bb10aa110c53 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -199,7 +199,7 @@ def execute(self, progress=SilentProgress(), model=None): self.setOutputCRS() self.resolveTemporaryOutputs() self.resolveDataObjects() - self.resolveMinCoveringExtent() + self.evaluateParameterValues() self.checkOutputFileExtensions() self.runPreExecutionScript(progress) self.processAlgorithm(progress) @@ -207,7 +207,7 @@ def execute(self, progress=SilentProgress(), model=None): self.convertUnsupportedFormats(progress) self.runPostExecutionScript(progress) except GeoAlgorithmExecutionException as gaee: - lines = [self.tr('Uncaught error while executing algorithm')] + lines = [self.tr('Error while executing algorithm')] lines.append(traceback.format_exc()) ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, gaee.msg) raise GeoAlgorithmExecutionException(gaee.msg, lines, gaee) @@ -340,11 +340,9 @@ def checkOutputFileExtensions(self): if not os.path.isabs(out.value): continue if isinstance(out, OutputRaster): - exts = \ - dataobjects.getSupportedOutputRasterLayerExtensions() + exts = dataobjects.getSupportedOutputRasterLayerExtensions() elif isinstance(out, OutputVector): - exts = \ - dataobjects.getSupportedOutputVectorLayerExtensions() + exts = dataobjects.getSupportedOutputVectorLayerExtensions() elif isinstance(out, OutputTable): exts = dataobjects.getSupportedOutputTableExtensions() elif isinstance(out, OutputHTML): @@ -360,60 +358,12 @@ def checkOutputFileExtensions(self): out.value = out.value + '.' + exts[0] - def canUseAutoExtent(self): - for param in self.parameters: - if isinstance(param, (ParameterRaster, ParameterVector)): - return True - if isinstance(param, ParameterMultipleInput): - return True - return False - - def resolveMinCoveringExtent(self): - for param in self.parameters: - if isinstance(param, ParameterExtent): - if param.value is None: - param.value = self.getMinCoveringExtent() - - def getMinCoveringExtent(self): - first = True - found = False + def evaluateParameterValues(self): for param in self.parameters: - if param.value: - if isinstance(param, (ParameterRaster, ParameterVector)): - if isinstance(param.value, (QgsRasterLayer, - QgsVectorLayer)): - layer = param.value - else: - layer = dataobjects.getObject(param.value) - if layer: - found = True - self.addToRegion(layer, first) - first = False - elif isinstance(param, ParameterMultipleInput): - layers = param.value.split(';') - for layername in layers: - layer = dataobjects.getObject(layername) - if layer: - found = True - self.addToRegion(layer, first) - first = False - if found: - return '{},{},{},{}'.format( - self.xmin, self.xmax, self.ymin, self.ymax) - else: - return None - - def addToRegion(self, layer, first): - if first: - self.xmin = layer.extent().xMinimum() - self.xmax = layer.extent().xMaximum() - self.ymin = layer.extent().yMinimum() - self.ymax = layer.extent().yMaximum() - else: - self.xmin = min(self.xmin, layer.extent().xMinimum()) - self.xmax = max(self.xmax, layer.extent().xMaximum()) - self.ymin = min(self.ymin, layer.extent().yMinimum()) - self.ymax = max(self.ymax, layer.extent().yMaximum()) + try: + param.evaluate(self) + except ValueError, e: + raise GeoAlgorithmExecutionException(str(e)) def resolveTemporaryOutputs(self): """Sets temporary outputs (output.value = None) with a diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index c53aaa4f0fde..d38bc933155f 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -33,11 +33,12 @@ from inspect import isclass from copy import deepcopy - +from qgis.utils import iface from qgis.PyQt.QtCore import QCoreApplication -from qgis.core import QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsCoordinateReferenceSystem +from qgis.core import (QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsCoordinateReferenceSystem, + QgsExpressionContext, QgsExpressionContextUtils, QgsExpression, QgsExpressionContextScope) + from processing.tools.vector import resolveFieldIndex, features -from processing.tools.system import isWindows from processing.tools import dataobjects def parseBool(s): @@ -58,7 +59,47 @@ def _splitParameterOptions(line): def _createDescriptiveName(s): return s.replace('_', ' ') -class Parameter(object): +def _expressionContext(): + context = QgsExpressionContext() + context.appendScope(QgsExpressionContextUtils.globalScope()) + context.appendScope(QgsExpressionContextUtils.projectScope()) + processingScope = QgsExpressionContextScope() + layers = dataobjects.getAllLayers() + for layer in layers: + name = layer.name() + processingScope.setVariable('%s_minx' % name, layer.extent().xMinimum()) + processingScope.setVariable('%s_miny' % name, layer.extent().yMinimum()) + processingScope.setVariable('%s_maxx' % name, layer.extent().xMaximum()) + processingScope.setVariable('%s_maxy' % name, layer.extent().yMaximum()) + if isinstance(layer, QgsRasterLayer): + cellsize = (layer.extent().xMaximum() + - layer.extent().xMinimum()) / layer.width() + processingScope.setVariable('%s_cellsize' % name, cellsize) + + layers = dataobjects.getRasterLayers() + for layer in layers: + for i in range(layer.bandCount()): + stats = layer.dataProvider().bandStatistics(i + 1) + processingScope.setVariable('%s_band%i_avg' % (name, i + 1), stats.mean) + processingScope.setVariable('%s_band%i_stddev' % (name, i + 1), stats.stdDev) + processingScope.setVariable('%s_band%i_min' % (name, i + 1), stats.minimumValue) + processingScope.setVariable('%s_band%i_max' % (name, i + 1), stats.maximumValue) + + extent = iface.mapCanvas().extent() + processingScope.setVariable('canvasextent_minx', extent.xMinimum()) + processingScope.setVariable('canvasextent_miny', extent.yMinimum()) + processingScope.setVariable('canvasextent_maxx', extent.xMaximum()) + processingScope.setVariable('canvasextent_maxy', extent.yMaximum()) + + extent = iface.mapCanvas().fullExtent() + processingScope.setVariable('fullextent_minx', extent.xMinimum()) + processingScope.setVariable('fullextent_miny', extent.yMinimum()) + processingScope.setVariable('fullextent_maxx', extent.xMaximum()) + processingScope.setVariable('fullextent_maxy', extent.yMaximum()) + context.appendScope(processingScope) + return context + +class Parameter: """ Base class for all parameters that a geoalgorithm might @@ -148,6 +189,9 @@ def wrapper(self, dialog, row=0, col=0): wrapper = wrapper(self, dialog, row, col) # or a wrapper instance return wrapper + + def evaluate(self, alg): + pass class ParameterBoolean(Parameter): @@ -330,6 +374,51 @@ def fromScriptCode(self, line): default = definition.strip()[len('extent') + 1:] or None return ParameterExtent(name, descName, default, isOptional) + def evaluate(self, alg): + if self.optional and not bool(self.value): + self.value = self.getMinCoveringExtent() + + def getMinCoveringExtent(self, alg): + first = True + found = False + for param in alg.parameters: + if param.value: + if isinstance(param, (ParameterRaster, ParameterVector)): + if isinstance(param.value, (QgsRasterLayer, + QgsVectorLayer)): + layer = param.value + else: + layer = dataobjects.getObject(param.value) + if layer: + found = True + self.addToRegion(layer, first) + first = False + elif isinstance(param, ParameterMultipleInput): + layers = param.value.split(';') + for layername in layers: + layer = dataobjects.getObject(layername) + if layer: + found = True + self.addToRegion(layer, first) + first = False + if found: + return '{},{},{},{}'.format( + self.xmin, self.xmax, self.ymin, self.ymax) + else: + return None + + def addToRegion(self, layer, first): + if first: + self.xmin = layer.extent().xMinimum() + self.xmax = layer.extent().xMaximum() + self.ymin = layer.extent().yMinimum() + self.ymax = layer.extent().yMaximum() + else: + self.xmin = min(self.xmin, layer.extent().xMinimum()) + self.xmax = max(self.xmax, layer.extent().xMaximum()) + self.ymin = min(self.ymin, layer.extent().yMinimum()) + self.ymax = max(self.ymax, layer.extent().yMaximum()) + class ParameterPoint(Parameter): @@ -715,21 +804,30 @@ def setValue(self, n): self.value = None return True - try: - if float(n) - int(float(n)) == 0: - value = int(float(n)) - else: - value = float(n) - if self.min is not None: - if value < self.min: - return False - if self.max is not None: - if value > self.max: - return False - self.value = value - return True - except: - return False + if isinstance(n, basestring): + try: + v = self._evaluate(n) + float(v) + self.value = n + return True + except: + return False + else: + try: + if float(n) - int(float(n)) == 0: + value = int(float(n)) + else: + value = float(n) + if self.min is not None: + if value < self.min: + return False + if self.max is not None: + if value > self.max: + return False + self.value = value + return True + except: + return False def getAsScriptCode(self): param_type = '' @@ -745,6 +843,31 @@ def fromScriptCode(self, line): if definition.lower().strip().startswith('number'): default = definition.strip()[len('number') + 1:] or None return ParameterNumber(name, descName, default=default, optional=isOptional) + + def _evaluate(self, v): + exp = QgsExpression(v) + if exp.hasParserError(): + raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) + result = exp.evaluate(_expressionContext()) + if exp.hasEvalError(): + raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) + return result + + def evaluate(self, alg): + if isinstance(self.value, basestring): + self.value = self._evaluate(self.value) + + def expressionContext(self): + return _expressionContext() + + def getValueAsCommandLineParameter(self): + if self.value is None: + return str(None) + if isinstance(self.value, basestring): + return '"%s"' % self.value + return str(self.value) + + class ParameterRange(Parameter): @@ -919,6 +1042,13 @@ def fromScriptCode(self, line): return ParameterSelection(name, descName, options, optional=isOptional) +class ParameterEvaluationException(Exception): + + def __init__(self, param, msg): + Exception.__init__(msg) + self.param = param + + class ParameterString(Parameter): default_metadata = { @@ -976,6 +1106,18 @@ def fromScriptCode(self, line): return ParameterString(name, descName, default, multiline=True, optional=isOptional) else: return ParameterString(name, descName, multiline=True, optional=isOptional) + + def evaluate(self, alg): + exp = QgsExpression(self.value) + if exp.hasParserError(): + raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) + result = exp.evaluate(_expressionContext()) + if exp.hasEvalError(): + raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) + self.value = result + + def expressionContext(self): + return _expressionContext() class ParameterTable(ParameterDataObject): diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 7ad7a0df4c28..c2d400d5a416 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -31,7 +31,7 @@ from qgis.PyQt.QtWidgets import QMessageBox, QApplication, QPushButton, QWidget, QVBoxLayout from qgis.PyQt.QtGui import QCursor, QColor, QPalette -from qgis.core import QgsMapLayerRegistry, QgsExpressionContext, QgsExpressionContextUtils, QgsExpression +from qgis.core import QgsMapLayerRegistry from processing.core.ProcessingLog import ProcessingLog from processing.core.ProcessingConfig import ProcessingConfig @@ -62,8 +62,6 @@ from processing.core.outputs import OutputVector from processing.core.outputs import OutputTable -from processing.tools import dataobjects - class AlgorithmDialog(AlgorithmDialogBase): @@ -114,18 +112,6 @@ def setParamValues(self): return True - def evaluateExpression(self, text): - context = QgsExpressionContext() - context.appendScope(QgsExpressionContextUtils.globalScope()) - context.appendScope(QgsExpressionContextUtils.projectScope()) - exp = QgsExpression(text) - if exp.hasParserError(): - raise Exception(exp.parserErrorString()) - result = exp.evaluate(context) - if exp.hasEvalError(): - raise ValueError(exp.evalErrorString()) - return result - def setParamValue(self, param, wrapper, alg=None): return param.setValue(wrapper.value()) diff --git a/python/plugins/processing/gui/NumberInputDialog.py b/python/plugins/processing/gui/NumberInputDialog.py deleted file mode 100644 index cc35eaacf814..000000000000 --- a/python/plugins/processing/gui/NumberInputDialog.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - NumberInputDialog.py - --------------------- - Date : August 2012 - Copyright : (C) 2012 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" -from builtins import str -from builtins import range - -__author__ = 'Victor Olaya' -__date__ = 'August 2012' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -import os - -from qgis.PyQt import uic -from qgis.PyQt.QtWidgets import QDialog, QTreeWidgetItem, QMessageBox -from qgis.core import QgsRasterLayer - -from qgis.utils import iface -from processing.tools import dataobjects - -pluginPath = os.path.split(os.path.dirname(__file__))[0] -WIDGET, BASE = uic.loadUiType( - os.path.join(pluginPath, 'ui', 'DlgNumberInput.ui')) - - -class NumberInputDialog(BASE, WIDGET): - - def __init__(self, isInteger): - super(NumberInputDialog, self).__init__(None) - self.setupUi(self) - - if hasattr(self.leFormula, 'setPlaceholderText'): - self.leFormula.setPlaceholderText( - self.tr('[Enter your formula here]')) - - self.treeValues.doubleClicked.connect(self.addValue) - - self.value = None - self.isInteger = isInteger - - if not self.isInteger: - self.lblWarning.hide() - - self.fillTree() - - def fillTree(self): - layersItem = QTreeWidgetItem() - layersItem.setText(0, self.tr('Values from data layers extents')) - self.treeValues.addTopLevelItem(layersItem) - layers = dataobjects.getAllLayers() - for layer in layers: - layerItem = QTreeWidgetItem() - layerItem.setText(0, str(layer.name())) - layerItem.addChild(TreeValueItem(self.tr('Min X'), - layer.extent().xMinimum())) - layerItem.addChild(TreeValueItem(self.tr('Max X'), - layer.extent().xMaximum())) - layerItem.addChild(TreeValueItem(self.tr('Min Y'), - layer.extent().yMinimum())) - layerItem.addChild(TreeValueItem(self.tr('Max Y'), - layer.extent().yMaximum())) - if isinstance(layer, QgsRasterLayer): - cellsize = (layer.extent().xMaximum() - - layer.extent().xMinimum()) / layer.width() - layerItem.addChild(TreeValueItem(self.tr('Cellsize'), - cellsize)) - layersItem.addChild(layerItem) - - layersItem = QTreeWidgetItem() - layersItem.setText(0, self.tr('Values from raster layers statistics')) - self.treeValues.addTopLevelItem(layersItem) - layers = dataobjects.getRasterLayers() - for layer in layers: - for i in range(layer.bandCount()): - stats = layer.dataProvider().bandStatistics(i + 1) - layerItem = QTreeWidgetItem() - layerItem.setText(0, str(layer.name())) - layerItem.addChild(TreeValueItem(self.tr('Mean'), stats.mean)) - layerItem.addChild(TreeValueItem(self.tr('Std. deviation'), - stats.stdDev)) - layerItem.addChild(TreeValueItem(self.tr('Max value'), - stats.maximumValue)) - layerItem.addChild(TreeValueItem(self.tr('Min value'), - stats.minimumValue)) - layersItem.addChild(layerItem) - - canvasItem = QTreeWidgetItem() - canvasItem.setText(0, self.tr('Values from QGIS map canvas')) - self.treeValues.addTopLevelItem(canvasItem) - extent = iface.mapCanvas().extent() - extentItem = QTreeWidgetItem() - extentItem.setText(0, self.tr('Current extent')) - extentItem.addChild(TreeValueItem(self.tr('Min X'), extent.xMinimum())) - extentItem.addChild(TreeValueItem(self.tr('Max X'), extent.xMaximum())) - extentItem.addChild(TreeValueItem(self.tr('Min Y'), extent.yMinimum())) - extentItem.addChild(TreeValueItem(self.tr('Max Y'), extent.yMaximum())) - canvasItem.addChild(extentItem) - - extent = iface.mapCanvas().fullExtent() - extentItem = QTreeWidgetItem() - extentItem.setText(0, - self.tr('Full extent of all layers in map canvas')) - extentItem.addChild(TreeValueItem(self.tr('Min X'), extent.xMinimum())) - extentItem.addChild(TreeValueItem(self.tr('Max X'), extent.xMaximum())) - extentItem.addChild(TreeValueItem(self.tr('Min Y'), extent.yMinimum())) - extentItem.addChild(TreeValueItem(self.tr('Max Y'), extent.yMaximum())) - canvasItem.addChild(extentItem) - - def addValue(self): - item = self.treeValues.currentItem() - if isinstance(item, TreeValueItem): - formula = self.leFormula.text() + ' ' + str(item.value) - self.leFormula.setText(formula.strip()) - - def accept(self): - try: - self.value = float(eval(str(self.leFormula.text()))) - if self.isInteger: - self.value = int(round(self.value)) - QDialog.accept(self) - except: - QMessageBox.critical(self, self.tr('Wrong expression'), - self.tr('The expression entered is not correct')) - - def reject(self): - self.value = None - QDialog.reject(self) - - -class TreeValueItem(QTreeWidgetItem): - - def __init__(self, name, value): - QTreeWidgetItem.__init__(self) - self.value = value - self.setText(0, name + ': ' + str(value)) diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index 3c3c55a3472c..d00a3f2bde6d 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -32,131 +32,44 @@ from qgis.PyQt.QtCore import pyqtSignal from qgis.PyQt.QtWidgets import QDialog -from math import log10, floor from qgis.core import (QgsDataSourceUri, QgsCredentials, - QgsExpressionContext, - QgsExpressionContextUtils, QgsExpression, - QgsRasterLayer, - QgsExpressionContextScope) + QgsRasterLayer) from qgis.gui import QgsEncodingFileDialog, QgsExpressionBuilderDialog from qgis.utils import iface -from processing.tools import dataobjects pluginPath = os.path.split(os.path.dirname(__file__))[0] WIDGET, BASE = uic.loadUiType( - os.path.join(pluginPath, 'ui', 'widgetNumberSelector.ui')) + os.path.join(pluginPath, 'ui', 'widgetBaseSelector.ui')) class NumberInputPanel(BASE, WIDGET): hasChanged = pyqtSignal() - def __init__(self, number, minimum, maximum, isInteger): + def __init__(self, param): super(NumberInputPanel, self).__init__(None) self.setupUi(self) - self.spnValue.setExpressionsEnabled(True) - self.isInteger = isInteger - if self.isInteger: - self.spnValue.setDecimals(0) - else: - # Guess reasonable step value - if (maximum == 0 or maximum) and (minimum == 0 or minimum): - self.spnValue.setSingleStep(self.calculateStep(minimum, maximum)) - - if maximum == 0 or maximum: - self.spnValue.setMaximum(maximum) - else: - self.spnValue.setMaximum(99999999) - if minimum == 0 or minimum: - self.spnValue.setMinimum(minimum) - else: - self.spnValue.setMinimum(-99999999) - - # Set default value - if number == 0 or number: - self.spnValue.setValue(float(number)) - self.spnValue.setClearValue(float(number)) - elif minimum == 0 or minimum: - self.spnValue.setValue(float(minimum)) - self.spnValue.setClearValue(float(minimum)) - else: - self.spnValue.setValue(0) - self.spnValue.setClearValue(0) - - self.btnCalc.setFixedHeight(self.spnValue.height()) - - self.btnCalc.clicked.connect(self.showExpressionsBuilder) - - self.spnValue.valueChanged.connect(lambda: self.hasChanged.emit()) + self.param = param + self.text = param.default + + self.btnSelect.clicked.connect(self.showExpressionsBuilder) + self.leText.textChanged.connect(lambda: self.hasChanged.emit()) def showExpressionsBuilder(self): - context = self.expressionContext() - dlg = QgsExpressionBuilderDialog(None, self.spnValue.text(), self, 'generic', context) + context = self.param.expressionContext() + dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: exp = QgsExpression(dlg.expressionText()) if not exp.hasParserError(): - result = exp.evaluate(context) - if not exp.hasEvalError(): - try: - self.spnValue.setValue(float(result)) - except: - pass - - def expressionContext(self): - context = QgsExpressionContext() - context.appendScope(QgsExpressionContextUtils.globalScope()) - context.appendScope(QgsExpressionContextUtils.projectScope()) - processingScope = QgsExpressionContextScope() - layers = dataobjects.getAllLayers() - for layer in layers: - name = layer.name() - processingScope.setVariable('%s_minx' % name, layer.extent().xMinimum()) - processingScope.setVariable('%s_miny' % name, layer.extent().yMinimum()) - processingScope.setVariable('%s_maxx' % name, layer.extent().xMaximum()) - processingScope.setVariable('%s_maxy' % name, layer.extent().yMaximum()) - if isinstance(layer, QgsRasterLayer): - cellsize = (layer.extent().xMaximum() - - layer.extent().xMinimum()) / layer.width() - processingScope.setVariable('%s_cellsize' % name, cellsize) - - layers = dataobjects.getRasterLayers() - for layer in layers: - for i in range(layer.bandCount()): - stats = layer.dataProvider().bandStatistics(i + 1) - processingScope.setVariable('%s_band%i_avg' % (name, i + 1), stats.mean) - processingScope.setVariable('%s_band%i_stddev' % (name, i + 1), stats.stdDev) - processingScope.setVariable('%s_band%i_min' % (name, i + 1), stats.minimumValue) - processingScope.setVariable('%s_band%i_max' % (name, i + 1), stats.maximumValue) - - extent = iface.mapCanvas().extent() - processingScope.setVariable('canvasextent_minx', extent.xMinimum()) - processingScope.setVariable('canvasextent_miny', extent.yMinimum()) - processingScope.setVariable('canvasextent_maxx', extent.xMaximum()) - processingScope.setVariable('canvasextent_maxy', extent.yMaximum()) - - extent = iface.mapCanvas().fullExtent() - processingScope.setVariable('fullextent_minx', extent.xMinimum()) - processingScope.setVariable('fullextent_miny', extent.yMinimum()) - processingScope.setVariable('fullextent_maxx', extent.xMaximum()) - processingScope.setVariable('fullextent_maxy', extent.yMaximum()) - context.appendScope(processingScope) - return context + self.setValue(dlg.expressionText()) + def getValue(self): - return self.spnValue.value() + return self.leText.text() def setValue(self, value): - self.spnValue.setValue(value) - - def calculateStep(self, minimum, maximum): - valueRange = maximum - minimum - if valueRange <= 1.0: - step = valueRange / 10.0 - # round to 1 significant figure - return round(step, -int(floor(log10(step)))) - else: - return 1.0 + self.leText.setText(unicode(value)) diff --git a/python/plugins/processing/gui/StringInputPanel.py b/python/plugins/processing/gui/StringInputPanel.py new file mode 100644 index 000000000000..b5ec19b7af54 --- /dev/null +++ b/python/plugins/processing/gui/StringInputPanel.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + NumberInputPanel.py + --------------------- + Date : August 2016 + Copyright : (C) 2016 by Victor Olaya + Email : volayaf at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Victor Olaya' +__date__ = 'August 2016' +__copyright__ = '(C) 2016, Victor Olaya' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +import os + +from qgis.PyQt import uic +from qgis.PyQt.QtCore import pyqtSignal +from qgis.PyQt.QtWidgets import QDialog + +from qgis.core import (QgsDataSourceUri, + QgsCredentials, + QgsExpression, + QgsRasterLayer) +from qgis.gui import QgsEncodingFileDialog, QgsExpressionBuilderDialog +from qgis.utils import iface + +pluginPath = os.path.split(os.path.dirname(__file__))[0] +WIDGET, BASE = uic.loadUiType( + os.path.join(pluginPath, 'ui', 'widgetBaseSelector.ui')) + + +class StringInputPanel(BASE, WIDGET): + + hasChanged = pyqtSignal() + + def __init__(self, param): + super(StringInputPanel, self).__init__(None) + self.setupUi(self) + + self.param = param + self.text = param.default + + self.btnSelect.clicked.connect(self.showExpressionsBuilder) + self.leText.textChanged.connect(lambda: self.hasChanged.emit()) + + def showExpressionsBuilder(self): + context = self.param.expressionContext() + dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) + dlg.setWindowTitle(self.tr('Expression based input')) + if dlg.exec_() == QDialog.Accepted: + exp = QgsExpression(dlg.expressionText()) + if not exp.hasParserError(): + self.setValue(dlg.expressionText()) + + + def getValue(self): + return self.leText.text() + + def setValue(self, value): + self.leText.setText(unicode(value)) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index bd58e86c1d8d..f9b804ccb3ec 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -50,6 +50,7 @@ from processing.gui.BatchInputSelectionPanel import BatchInputSelectionPanel from processing.gui.FixedTablePanel import FixedTablePanel from processing.gui.ExtentSelectionPanel import ExtentSelectionPanel +from processing.gui.StringInputPanel import StringInputPanel DIALOG_STANDARD = 'standard' @@ -442,8 +443,7 @@ class NumberWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - return NumberInputPanel(self.param.default, self.param.min, self.param.max, - self.param.isInteger) + return NumberInputPanel(self.param) else: widget = QComboBox() widget.setEditable(True) @@ -605,9 +605,9 @@ def createWidget(self): if self.param.default: widget.setPlainText(self.param.default) else: - widget = QLineEdit() + widget = StringInputPanel(self.param) if self.param.default: - widget.setText(self.param.default) + widget.setValue(self.param.default) elif self.dialogType == DIALOG_BATCH: widget = QLineEdit() if self.param.default: @@ -642,22 +642,10 @@ def value(self): if self.param.multiline: text = self.widget.toPlainText() else: - text = self.widget.text() - - if self.param.evaluateExpressions: - try: - text = self.evaluateExpression(text) - except: - pass + text = self.widget.getValue() return text if self.dialogType == DIALOG_BATCH: text = self.widget.text() - if self.param.evaluateExpressions: - try: - text = self.evaluateExpression(text) - except: - pass - return text else: if self.param.multiline: value = self.widget.getValue() diff --git a/python/plugins/processing/ui/widgetNumberSelector.ui b/python/plugins/processing/ui/widgetNumberSelector.ui deleted file mode 100644 index e5d88ff54b1a..000000000000 --- a/python/plugins/processing/ui/widgetNumberSelector.ui +++ /dev/null @@ -1,58 +0,0 @@ - - - Form - - - - 0 - 0 - 251 - 23 - - - - Form - - - - 2 - - - 0 - - - - - 6 - - - -99999999.999999001622200 - - - 99999999.999999001622200 - - - - - - - Open number input dialog - - - ... - - - - - - - - QgsDoubleSpinBox - QDoubleSpinBox -
                                                                                                                                                                                    qgis.gui
                                                                                                                                                                                    - 1 -
                                                                                                                                                                                    -
                                                                                                                                                                                    - - -
                                                                                                                                                                                    From bc06600871ea02d26eedc4b3512b93777ce20e95 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 9 Sep 2016 08:25:03 +0200 Subject: [PATCH 122/897] [processing] more work on parameter wrappers --- python/plugins/processing/core/parameters.py | 15 +++++++++++-- python/plugins/processing/gui/wrappers.py | 23 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index d38bc933155f..17d191a5a1e4 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -106,8 +106,10 @@ class Parameter: take as input. """ - default_metadata = {} - + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.BasicWidgetWrapper' + } + def __init__(self, name='', description='', default=None, optional=False, metadata={}): self.name = name @@ -870,6 +872,11 @@ def getValueAsCommandLineParameter(self): class ParameterRange(Parameter): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.BasicWidgetWrapper' + } + def __init__(self, name='', description='', default=None, optional=False): Parameter.__init__(self, name, description, default, optional) @@ -1461,6 +1468,10 @@ def fromScriptCode(self, line): class ParameterGeometryPredicate(Parameter): + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.BasicWidgetWrapper' + } + predicates = ('intersects', 'contains', 'disjoint', diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index f9b804ccb3ec..6e44b89377be 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -17,6 +17,7 @@ * * *************************************************************************** """ +from gui.GeometryPredicateSelectionPanel import GeometryPredicateSelectionPanel __author__ = 'Arnaud Morvan' __date__ = 'May 2016' @@ -131,6 +132,17 @@ def postInitialize(self, wrappers): def refresh(self): pass +class BasicWidgetWrapper(WidgetWrapper): + + def createWidget(self): + return QLineEdit() + + def setValue(self, value): + self.widget.setText(value) + + def value(self): + return self.widget.text() + class BooleanWidgetWrapper(WidgetWrapper): @@ -792,3 +804,14 @@ def anotherParameterWidgetHasChanged(self,wrapper): self.widget.addItem(self.tr(self.NOT_SET)) self.widget.addItems(self.getFields(layer, wrapper.param.datatype)) + +def GeometryPredicateWidgetWrapper(WidgetWrapper): + + def createWidget(self): + return GeometryPredicateSelectionPanel() + + def setValue(self, value): + self.widget.setValue(value) + + def value(self): + return self.widget.value() \ No newline at end of file From fe5d0166ccbb3c64589773df47dd11a07d089de3 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 9 Sep 2016 10:48:51 +0200 Subject: [PATCH 123/897] [processing] added multiple option to ParameterTableFIeld removed ParameterTableMultipleField and did some cleanup --- .../processing/algs/qgis/DeleteColumn.py | 24 ++-- .../plugins/processing/algs/qgis/Dissolve.py | 6 +- .../plugins/processing/algs/r/RAlgorithm.py | 4 +- python/plugins/processing/core/parameters.py | 128 +++--------------- .../plugins/processing/gui/AlgorithmDialog.py | 1 - .../plugins/processing/gui/ParametersPanel.py | 22 +-- python/plugins/processing/gui/wrappers.py | 118 ++++++++++------ .../ModelerParameterDefinitionDialog.py | 34 ++--- .../modeler/ModelerParametersDialog.py | 21 +-- .../processing/tests/ParametersTest.py | 59 +------- 10 files changed, 123 insertions(+), 294 deletions(-) diff --git a/python/plugins/processing/algs/qgis/DeleteColumn.py b/python/plugins/processing/algs/qgis/DeleteColumn.py index 5405236ceda5..8a4cc4be41a8 100644 --- a/python/plugins/processing/algs/qgis/DeleteColumn.py +++ b/python/plugins/processing/algs/qgis/DeleteColumn.py @@ -36,7 +36,7 @@ class DeleteColumn(GeoAlgorithm): INPUT = 'INPUT' - COLUMN = 'COLUMN' + COLUMNS = 'COLUMN' OUTPUT = 'OUTPUT' def defineCharacteristics(self): @@ -45,17 +45,20 @@ def defineCharacteristics(self): self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'))) - self.addParameter(ParameterTableField(self.COLUMN, - self.tr('Field to delete'), self.INPUT)) - self.addOutput(OutputVector(self.OUTPUT, self.tr('Deleted column'))) + self.addParameter(ParameterTableField(self.COLUMNS, + self.tr('Fields to delete'), self.INPUT, multiple=True)) + self.addOutput(OutputVector(self.OUTPUT, self.tr('Output layer'))) def processAlgorithm(self, progress): - layer = dataobjects.getObjectFromUri( - self.getParameterValue(self.INPUT)) - idx = layer.fields().lookupField(self.getParameterValue(self.COLUMN)) - + layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) + + toDelete = self.getParameterValue(self.COLUMNS) fields = layer.fields() - fields.remove(idx) + idxs = [] + for f in toDelete: + idx = layer.fieldNameIndex() + fields.remove(idx) + idxs.append[idx] writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, layer.wkbType(), layer.crs()) @@ -67,7 +70,8 @@ def processAlgorithm(self, progress): for current, f in enumerate(features): feat.setGeometry(f.geometry()) attributes = f.attributes() - del attributes[idx] + for idx in idxs: + del attributes[idx] feat.setAttributes(attributes) writer.addFeature(feat) diff --git a/python/plugins/processing/algs/qgis/Dissolve.py b/python/plugins/processing/algs/qgis/Dissolve.py index 25e71493f645..a70a20add6ed 100644 --- a/python/plugins/processing/algs/qgis/Dissolve.py +++ b/python/plugins/processing/algs/qgis/Dissolve.py @@ -37,7 +37,7 @@ from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterBoolean -from processing.core.parameters import ParameterTableMultipleField +from processing.core.parameters import ParameterTableField from processing.core.outputs import OutputVector from processing.tools import vector, dataobjects @@ -62,8 +62,8 @@ def defineCharacteristics(self): [dataobjects.TYPE_VECTOR_POLYGON, dataobjects.TYPE_VECTOR_LINE])) self.addParameter(ParameterBoolean(Dissolve.DISSOLVE_ALL, self.tr('Dissolve all (do not use fields)'), True)) - self.addParameter(ParameterTableMultipleField(Dissolve.FIELD, - self.tr('Unique ID fields'), Dissolve.INPUT, optional=True)) + self.addParameter(ParameterTableField(Dissolve.FIELD, + self.tr('Unique ID fields'), Dissolve.INPUT, optional=True, multiple=True)) self.addOutput(OutputVector(Dissolve.OUTPUT, self.tr('Dissolved'))) def processAlgorithm(self, progress): diff --git a/python/plugins/processing/algs/r/RAlgorithm.py b/python/plugins/processing/algs/r/RAlgorithm.py index 107207000f40..43636ac1f735 100644 --- a/python/plugins/processing/algs/r/RAlgorithm.py +++ b/python/plugins/processing/algs/r/RAlgorithm.py @@ -46,7 +46,6 @@ from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterSelection from processing.core.parameters import ParameterTableField -from processing.core.parameters import ParameterTableMultipleField from processing.core.parameters import ParameterExtent from processing.core.parameters import ParameterCrs from processing.core.parameters import ParameterFile @@ -328,8 +327,7 @@ def getImportCommands(self): commands.append(param.name + '= NULL') else: commands.append(param.name + ' = "' + param.value + '"') - elif isinstance(param, (ParameterTableField, ParameterTableMultipleField, ParameterString, - ParameterFile)): + elif isinstance(param, (ParameterTableField, ParameterString, ParameterFile)): if param.value is None: commands.append(param.name + '= NULL') else: diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 17d191a5a1e4..e84032e1ea71 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -106,10 +106,8 @@ class Parameter: take as input. """ - default_metadata = { - 'widget_wrapper': 'processing.gui.wrappers.BasicWidgetWrapper' - } - + default_metadata = {} + def __init__(self, name='', description='', default=None, optional=False, metadata={}): self.name = name @@ -809,8 +807,7 @@ def setValue(self, n): if isinstance(n, basestring): try: v = self._evaluate(n) - float(v) - self.value = n + self.value = float(v) return True except: return False @@ -846,8 +843,8 @@ def fromScriptCode(self, line): default = definition.strip()[len('number') + 1:] or None return ParameterNumber(name, descName, default=default, optional=isOptional) - def _evaluate(self, v): - exp = QgsExpression(v) + def _evaluate(self): + exp = QgsExpression(self.value) if exp.hasParserError(): raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) result = exp.evaluate(_expressionContext()) @@ -856,8 +853,7 @@ def _evaluate(self, v): return result def evaluate(self, alg): - if isinstance(self.value, basestring): - self.value = self._evaluate(self.value) + self.value = self._evaluate(self.value) def expressionContext(self): return _expressionContext() @@ -866,17 +862,12 @@ def getValueAsCommandLineParameter(self): if self.value is None: return str(None) if isinstance(self.value, basestring): - return '"%s"' % self.value + return '"%s"' + self.value return str(self.value) class ParameterRange(Parameter): - - default_metadata = { - 'widget_wrapper': 'processing.gui.wrappers.BasicWidgetWrapper' - } - def __init__(self, name='', description='', default=None, optional=False): Parameter.__init__(self, name, description, default, optional) @@ -1226,24 +1217,28 @@ class ParameterTableField(Parameter): DATA_TYPE_ANY = -1 def __init__(self, name='', description='', parent=None, datatype=-1, - optional=False): + optional=False, multiple = False): Parameter.__init__(self, name, description, None, optional) self.parent = parent + self.multiple = True self.datatype = int(datatype) def getValueAsCommandLineParameter(self): return '"' + str(self.value) + '"' if self.value is not None else str(None) def setValue(self, value): - if value is None: + if not bool(value): if not self.optional: return False self.value = None return True - - elif len(value) == 0 and not self.optional: - return False - self.value = str(value) + if isinstance(value, list): + if not self.multiple and len(value) > 1: + return False + self.value = ";".join(value) + return True + else: + self.value = str(value) return True def __str__(self): @@ -1284,97 +1279,12 @@ def fromScriptCode(self, line): return ParameterTableField(name, descName, parent, datatype, isOptional) -class ParameterTableMultipleField(Parameter): - - """A parameter representing several table fields. - Its value is a string with items separated by semicolons, each of - which represents the name of each field. - - In a script you can use it with - ##Fields=[optional] multiple field [number|string] Parentinput - - In the batch runner simply use a string with items separated by - semicolons, each of which represents the name of each field. - - see algs.qgis.DeleteColumn.py for an usage example - """ - - DATA_TYPE_NUMBER = 0 - DATA_TYPE_STRING = 1 - DATA_TYPE_ANY = -1 - - def __init__(self, name='', description='', parent=None, datatype=-1, - optional=False): - Parameter.__init__(self, name, description, None, optional) - self.parent = parent - self.datatype = int(datatype) - - def getValueAsCommandLineParameter(self): - return '"' + str(self.value) + '"' if self.value is not None else str(None) - - def setValue(self, obj): - if obj is None: - if self.optional: - self.value = None - return True - return False - - if isinstance(obj, list): - if len(obj) == 0: - if self.optional: - self.value = None - return True - return False - self.value = ";".join(obj) - return True - else: - self.value = str(obj) - return True - - def __str__(self): - return self.name + ' <' + self.__module__.split('.')[-1] + ' from ' \ - + self.parent + '>' - - def dataType(self): - if self.datatype == self.DATA_TYPE_NUMBER: - return 'numeric' - elif self.datatype == self.DATA_TYPE_STRING: - return 'string' - else: - return 'any' - - def getAsScriptCode(self): - param_type = '' - if self.optional: - param_type += 'optional ' - param_type += 'multiple field ' - return '##' + self.name + '=' + param_type + self.parent - - @classmethod - def fromScriptCode(self, line): - isOptional, name, definition = _splitParameterOptions(line) - if definition.lower().strip().startswith('multiple field'): - descName = _createDescriptiveName(name) - if definition.lower().strip().startswith('multiple field number'): - field = definition.strip()[len('multiple field number') + 1:] - datatype = ParameterTableMultipleField.DATA_TYPE_NUMBER - elif definition.lower().strip().startswith('multiple field string'): - field = definition.strip()[len('multiple field string') + 1:] - datatype = ParameterTableMultipleField.DATA_TYPE_STRING - else: - field = definition.strip()[len('multiple field') + 1:] - datatype = ParameterTableMultipleField.DATA_TYPE_ANY - - return ParameterTableMultipleField(name, descName, field, datatype, isOptional) - - class ParameterVector(ParameterDataObject): default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.VectorWidgetWrapper' } - def __init__(self, name='', description='', datatype=[-1], optional=False): ParameterDataObject.__init__(self, name, description, None, optional) @@ -1468,10 +1378,6 @@ def fromScriptCode(self, line): class ParameterGeometryPredicate(Parameter): - default_metadata = { - 'widget_wrapper': 'processing.gui.wrappers.BasicWidgetWrapper' - } - predicates = ('intersects', 'contains', 'disjoint', diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index c2d400d5a416..f6f294f45a82 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -50,7 +50,6 @@ from processing.core.parameters import ParameterFixedTable from processing.core.parameters import ParameterRange from processing.core.parameters import ParameterTableField -from processing.core.parameters import ParameterTableMultipleField from processing.core.parameters import ParameterMultipleInput from processing.core.parameters import ParameterString from processing.core.parameters import ParameterNumber diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index f8299221e7c1..8f87498336a6 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -42,27 +42,7 @@ from qgis.PyQt.QtGui import QIcon from processing.gui.OutputSelectionPanel import OutputSelectionPanel -from processing.gui.PointSelectionPanel import PointSelectionPanel -from processing.gui.GeometryPredicateSelectionPanel import \ - GeometryPredicateSelectionPanel -from processing.gui.ListMultiselectWidget import ListMultiSelectWidget -from processing.core.parameters import ParameterRaster -from processing.core.parameters import ParameterVector -from processing.core.parameters import ParameterTable -from processing.core.parameters import ParameterTableField -from processing.core.parameters import ParameterTableMultipleField -from processing.core.parameters import ParameterSelection -from processing.core.parameters import ParameterFixedTable -from processing.core.parameters import ParameterRange -from processing.core.parameters import ParameterMultipleInput -from processing.core.parameters import ParameterNumber -from processing.core.parameters import ParameterExtent -from processing.core.parameters import ParameterFile -from processing.core.parameters import ParameterCrs -from processing.core.parameters import ParameterString -from processing.core.parameters import ParameterPoint -from processing.core.parameters import ParameterGeometryPredicate - +from processing.core.parameters import ParameterVector, ParameterExtent, ParameterPoint from processing.core.outputs import OutputRaster from processing.core.outputs import OutputTable from processing.core.outputs import OutputVector diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 6e44b89377be..88b16d5ccee0 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -17,7 +17,6 @@ * * *************************************************************************** """ -from gui.GeometryPredicateSelectionPanel import GeometryPredicateSelectionPanel __author__ = 'Arnaud Morvan' __date__ = 'May 2016' @@ -52,6 +51,7 @@ from processing.gui.FixedTablePanel import FixedTablePanel from processing.gui.ExtentSelectionPanel import ExtentSelectionPanel from processing.gui.StringInputPanel import StringInputPanel +from processing.gui.GeometryPredicateSelectionPanel import GeometryPredicateSelectionPanel DIALOG_STANDARD = 'standard' @@ -440,7 +440,7 @@ def value(self): options = dataobjects.getVectorLayers(sorting=False) else: options = dataobjects.getVectorLayers([self.param.datatype], sorting=False) - return self.param.setValue([options[i] for i in self.widget.selectedoptions]) + return [options[i] for i in self.widget.selectedoptions] elif self.dialogType == DIALOG_BATCH: return self.widget.getText() else: @@ -734,32 +734,42 @@ class TableFieldWidgetWrapper(WidgetWrapper): NOT_SET = '[Not set]' def createWidget(self): - if self.dialogType == DIALOG_STANDARD: - widget = QComboBox() - return widget - elif self.dialogType == DIALOG_BATCH: - item = QLineEdit() - if self.param.default is not None: - item.setText(self.param.default) - else: - widget = QComboBox() - widget.setEditable(True) - fields = self.dialog.getAvailableValuesOfType(ParameterTableField, None) - if self.param.optional: - widget.addItem(self.NOT_SET, None) - for f in fields: - widget.addItem(self.dialog.resolveValueDescription(f), f) - return widget + if self.param.multiple: + if self.dialogType == DIALOG_STANDARD: + return MultipleInputPanel(options=[]) + else: + return QLineEdit() + else: + if self.dialogType == DIALOG_STANDARD: + widget = QComboBox() + return widget + elif self.dialogType == DIALOG_BATCH: + item = QLineEdit() + if self.param.default is not None: + item.setText(self.param.default) + else: + widget = QComboBox() + widget.setEditable(True) + fields = self.dialog.getAvailableValuesOfType(ParameterTableField, None) + if self.param.optional: + widget.addItem(self.NOT_SET, None) + for f in fields: + widget.addItem(self.dialog.resolveValueDescription(f), f) + return widget def postInitialize(self, wrappers): for wrapper in wrappers: if wrapper.param.name == self.param.parent: layer = wrapper.widget.itemData(wrapper.widget.currentIndex()) if layer is not None: - self.widget.clear() - if self.param.optional: - self.widget.addItem(self.tr(self.NOT_SET)) - self.widget.addItems(self.getFields(layer, wrapper.param.datatype)) + fields = self.getFields(layer, wrapper.param.datatype) + if self.param.multiple: + self.widget.updateForOptions(fields) + else: + self.widget.clear() + if self.param.optional: + self.widget.addItem(self.tr(self.NOT_SET)) + self.widget.addItems(fields) break def getFields(self, layer, datatype): @@ -777,33 +787,59 @@ def getFields(self, layer, datatype): return sorted(list(fieldNames), cmp=locale.strcoll) def setValue(self, value): - if self.dialogType == DIALOG_STANDARD: - pass # TODO - elif self.dialogType == DIALOG_BATCH: - return self.widget.setText(value) - else: - self.setComboValue(value) + if self.param.multiple: + if self.dialogType == DIALOG_STANDARD: + options = self.widget.options + selected = [] + for i, opt in enumerate(options): + if opt in value: + selected.append(i) + self.widget.setSelectedItems(selected) + else: + self.widget.setText(value) + else: + if self.dialogType == DIALOG_STANDARD: + pass # TODO + elif self.dialogType == DIALOG_BATCH: + return self.widget.setText(value) + else: + self.setComboValue(value) def value(self): - if self.dialogType == DIALOG_STANDARD: - if self.param.optional and self.widget.currentIndex() == 0: - return None - return self.widget.currentText() - elif self.dialogType == DIALOG_BATCH: - return self.widget.text() - else: - return self.comboValue() + if self.param.multiple: + if self.dialogType == DIALOG_STANDARD: + return [self.widget.options[i] for i in self.widget.selectedoptions] + elif self.dialogType == DIALOG_BATCH: + return self.widget.text() + else: + text = self.widget.text() + if not bool(text) and not self.param.optional: + raise InvalidParameterValue() + return text + else: + if self.dialogType == DIALOG_STANDARD: + if self.param.optional and self.widget.currentIndex() == 0: + return None + return self.widget.currentText() + elif self.dialogType == DIALOG_BATCH: + return self.widget.text() + else: + return self.comboValue() def anotherParameterWidgetHasChanged(self,wrapper): if wrapper.param.name == self.param.parent: layer = wrapper.value() if layer is not None: - self.widget.clear() - if self.param.optional: - self.widget.addItem(self.tr(self.NOT_SET)) - self.widget.addItems(self.getFields(layer, wrapper.param.datatype)) - + fields = self.getFields(layer, wrapper.param.datatype) + if self.param.multiple: + self.widget.updateForOptions(fields) + else: + self.widget.clear() + if self.param.optional: + self.widget.addItem(self.tr(self.NOT_SET)) + self.widget.addItems(fields) + def GeometryPredicateWidgetWrapper(WidgetWrapper): diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index cf467db77e4b..759b089588cd 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -51,8 +51,7 @@ ParameterExtent, ParameterFile, ParameterPoint, - ParameterCrs, - ParameterTableMultipleField) + ParameterCrs) from processing.gui.CrsSelectionPanel import CrsSelectionPanel @@ -65,7 +64,6 @@ class ModelerParameterDefinitionDialog(QDialog): PARAMETER_STRING = 'String' PARAMETER_BOOLEAN = 'Boolean' PARAMETER_TABLE_FIELD = 'Table field' - PARAMETER_TABLE_MULTIPLE_FIELD = 'Table multiple field' PARAMETER_EXTENT = 'Extent' PARAMETER_FILE = 'File' PARAMETER_POINT = 'Point' @@ -84,7 +82,6 @@ class ModelerParameterDefinitionDialog(QDialog): PARAMETER_STRING, PARAMETER_TABLE, PARAMETER_TABLE_FIELD, - PARAMETER_TABLE_MULTIPLE_FIELD, PARAMETER_VECTOR, PARAMETER_POINT, PARAMETER_CRS, @@ -132,7 +129,7 @@ def setupUi(self): self.nameTextBox.setText(self.param.description) if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \ - isinstance(self.param, ParameterBoolean): + isinstance(self.param, ParameterBoolean): self.state = QCheckBox() self.state.setText(self.tr('Checked')) self.state.setChecked(False) @@ -140,11 +137,8 @@ def setupUi(self): self.state.setChecked(True if self.param.value else False) self.horizontalLayoutParent.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayoutParent) - elif self.paramType in ( - ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD, - ModelerParameterDefinitionDialog.PARAMETER_TABLE_MULTIPLE_FIELD)\ - or isinstance(self.param, (ParameterTableField, - ParameterTableMultipleField)): + elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ + isinstance(self.param, ParameterTableField): self.horizontalLayoutParent.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 @@ -300,27 +294,15 @@ def okPressed(self): or isinstance(self.param, ParameterBoolean): self.param = ParameterBoolean(name, description, self.state.isChecked()) - elif self.paramType in ( - ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD, - ModelerParameterDefinitionDialog.PARAMETER_TABLE_MULTIPLE_FIELD)\ - or isinstance(self.param, (ParameterTableField, - ParameterTableMultipleField)): + elif self.paramType in ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD \ + or isinstance(self.param, ParameterTableField): if self.parentCombo.currentIndex() < 0: QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.itemData(self.parentCombo.currentIndex()) - datatype = self.datatypeCombo.itemData( - self.datatypeCombo.currentIndex()) - - if (self.paramType == - ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or - isinstance(self.param, ParameterTableField)): - self.param = ParameterTableField( - name, description, parent, datatype) - else: - self.param = ParameterTableMultipleField( - name, description, parent, datatype) + datatype = self.datatypeCombo.itemData(self.datatypeCombo.currentIndex()) + self.param = ParameterTableField(name, description, parent, datatype) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \ isinstance(self.param, ParameterRaster): self.param = ParameterRaster( diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index d262f064e59a..211a4f96f9e9 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -42,24 +42,6 @@ from processing.gui.wrappers import InvalidParameterValue from processing.gui.MultipleInputPanel import MultipleInputPanel -from processing.gui.GeometryPredicateSelectionPanel import \ - GeometryPredicateSelectionPanel -from processing.core.parameters import (ParameterExtent, - ParameterRaster, - ParameterVector, - ParameterTable, - ParameterFixedTable, - ParameterMultipleInput, - ParameterSelection, - ParameterRange, - ParameterNumber, - ParameterString, - ParameterCrs, - ParameterTableField, - ParameterTableMultipleField, - ParameterFile, - ParameterPoint, - ParameterGeometryPredicate) from processing.core.outputs import (OutputRaster, OutputVector, OutputTable, @@ -75,8 +57,7 @@ ValueFromOutput, Algorithm, ModelerOutput) -from processing.modeler.MultilineTextPanel import MultilineTextPanel -from processing.tools import dataobjects + from qgis.core import QgsApplication from qgis.PyQt.QtGui import QToolButton, QMenu, QAction diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index 666e2d3c1b72..65c21da62adb 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -39,8 +39,7 @@ ParameterPoint, ParameterString, ParameterVector, - ParameterTableField, - ParameterTableMultipleField) + ParameterTableField) from processing.tools import dataobjects from processing.tests.TestData import points2 @@ -435,61 +434,5 @@ def testOptional(self): 'myName', 'myDesc', parent_name, optional=True) -class ParameterTableMultipleFieldTest(unittest.TestCase): - - def setUp(self): - self.parent_name = 'test_parent_layer' - test_data = points2() - test_layer = QgsVectorLayer(test_data, self.parent_name, 'ogr') - self.parent = ParameterVector(self.parent_name, - self.parent_name) - self.parent.setValue(test_layer) - - def testGetAsScriptCode(self): - parameter = ParameterTableMultipleField( - 'myName', 'myDesc', self.parent_name, optional=False) - - self.assertEqual( - parameter.getAsScriptCode(), - '##myName=multiple field test_parent_layer') - - # test optional - parameter.optional = True - self.assertEqual( - parameter.getAsScriptCode(), - '##myName=optional multiple field test_parent_layer') - - def testOptional(self): - parameter = ParameterTableMultipleField( - 'myName', 'myDesc', self.parent_name, optional=True) - - parameter.setValue(['my', 'super', 'widget', '77']) - self.assertEqual(parameter.value, 'my;super;widget;77') - - parameter.setValue([]) - self.assertEqual(parameter.value, None) - - parameter.setValue(None) - self.assertEqual(parameter.value, None) - - parameter.setValue(['my', 'widget', '77']) - self.assertEqual(parameter.value, 'my;widget;77') - - def testSetValue(self): - parameter = ParameterTableMultipleField( - 'myName', 'myDesc', self.parent_name, optional=False) - - parameter.setValue(['my', 'super', 'widget', '77']) - self.assertEqual(parameter.value, 'my;super;widget;77') - - parameter.setValue([]) - self.assertEqual(parameter.value, 'my;super;widget;77') - - parameter.setValue(None) - self.assertEqual(parameter.value, 'my;super;widget;77') - - parameter.setValue(['my', 'widget', '77']) - self.assertEqual(parameter.value, 'my;widget;77') - if __name__ == '__main__': unittest.main() From e08fdaa444f2ffdc138b0eb847210f0449fd97e0 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 12 Sep 2016 06:17:23 +0200 Subject: [PATCH 124/897] [processing] support for expressions in numerical values in modeler includes cleanup of modeler, to adapt to latest changes in parameters architecture --- python/plugins/processing/core/Processing.py | 1 - python/plugins/processing/core/parameters.py | 41 ++++- .../processing/gui/NumberInputPanel.py | 39 ++++- python/plugins/processing/gui/wrappers.py | 34 +--- .../modeler/CalculatorModelerAlgorithm.py | 145 --------------- .../processing/modeler/ModelerAlgorithm.py | 165 +++++------------- .../modeler/ModelerOnlyAlgorithmProvider.py | 53 ------ .../ModelerParameterDefinitionDialog.py | 5 +- .../modeler/ModelerParametersDialog.py | 19 +- .../processing/modeler/ModelerScene.py | 5 +- 10 files changed, 127 insertions(+), 380 deletions(-) delete mode 100644 python/plugins/processing/modeler/CalculatorModelerAlgorithm.py delete mode 100644 python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py diff --git a/python/plugins/processing/core/Processing.py b/python/plugins/processing/core/Processing.py index 3ceab58e3abb..fded502cd7ae 100644 --- a/python/plugins/processing/core/Processing.py +++ b/python/plugins/processing/core/Processing.py @@ -54,7 +54,6 @@ from processing.core.alglist import algList from processing.modeler.ModelerAlgorithmProvider import ModelerAlgorithmProvider -from processing.modeler.ModelerOnlyAlgorithmProvider import ModelerOnlyAlgorithmProvider from processing.algs.qgis.QGISAlgorithmProvider import QGISAlgorithmProvider from processing.algs.grass.GrassAlgorithmProvider import GrassAlgorithmProvider from processing.algs.grass7.Grass7AlgorithmProvider import Grass7AlgorithmProvider diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index e84032e1ea71..a9afcd0ac611 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -32,6 +32,7 @@ import os from inspect import isclass from copy import deepcopy +import numbers from qgis.utils import iface from qgis.PyQt.QtCore import QCoreApplication @@ -40,6 +41,7 @@ from processing.tools.vector import resolveFieldIndex, features from processing.tools import dataobjects +from processing.core.outputs import OutputNumber def parseBool(s): if s is None or s == str(None).lower(): @@ -192,6 +194,9 @@ def wrapper(self, dialog, row=0, col=0): def evaluate(self, alg): pass + + def evaluateForModeler(self, value, model): + return value class ParameterBoolean(Parameter): @@ -810,6 +815,7 @@ def setValue(self, n): self.value = float(v) return True except: + raise return False else: try: @@ -826,6 +832,7 @@ def setValue(self, n): self.value = value return True except: + raise return False def getAsScriptCode(self): @@ -843,8 +850,8 @@ def fromScriptCode(self, line): default = definition.strip()[len('number') + 1:] or None return ParameterNumber(name, descName, default=default, optional=isOptional) - def _evaluate(self): - exp = QgsExpression(self.value) + def _evaluate(self, value): + exp = QgsExpression(value) if exp.hasParserError(): raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) result = exp.evaluate(_expressionContext()) @@ -853,7 +860,26 @@ def _evaluate(self): return result def evaluate(self, alg): - self.value = self._evaluate(self.value) + if isinstance(self.value, basestring): + self.value = self._evaluate(self.value) + + def evaluateForModeler(self, value, model): + if isinstance(value, numbers.Number): + return value + variables = {} + for param in model.parameters: + if isinstance(param, ParameterNumber): + variables["@" + param.name] = param.value + for alg in model.algs.values(): + for out in alg.algorithm.outputs: + if isinstance(out, OutputNumber): + variables["@%s_%s" % (alg.name, out.name)] = out.value + for k,v in variables.iteritems(): + print k,v + value = value.replace(k,unicode(v)) + + print value + return value def expressionContext(self): return _expressionContext() @@ -1427,9 +1453,12 @@ def getParameterFromString(s): isAdvanced = True tokens = s.split("|") params = [t if unicode(t) != unicode(None) else None for t in tokens[1:]] - clazz = getattr(sys.modules[__name__], tokens[0]) - param = clazz(*params) - param.isAdvanced = isAdvanced + try: + clazz = getattr(sys.modules[__name__], tokens[0]) + param = clazz(*params) + param.isAdvanced = isAdvanced + except: + return None else: # try script syntax for paramClass in paramClasses: try: diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index d00a3f2bde6d..65badfadf459 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -35,9 +35,13 @@ from qgis.core import (QgsDataSourceUri, QgsCredentials, QgsExpression, - QgsRasterLayer) + QgsRasterLayer, + QgsExpressionContextScope) from qgis.gui import QgsEncodingFileDialog, QgsExpressionBuilderDialog from qgis.utils import iface +from processing.core.parameters import ParameterNumber +from processing.core.outputs import OutputNumber +from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput, CompoundValue pluginPath = os.path.split(os.path.dirname(__file__))[0] WIDGET, BASE = uic.loadUiType( @@ -48,18 +52,27 @@ class NumberInputPanel(BASE, WIDGET): hasChanged = pyqtSignal() - def __init__(self, param): + def __init__(self, param, modelParametersDialog=None): super(NumberInputPanel, self).__init__(None) self.setupUi(self) self.param = param - self.text = param.default - + self.modelParametersDialog = modelParametersDialog + if param.default: + self.setValue(param.default) self.btnSelect.clicked.connect(self.showExpressionsBuilder) self.leText.textChanged.connect(lambda: self.hasChanged.emit()) def showExpressionsBuilder(self): context = self.param.expressionContext() + if self.modelParametersDialog is not None: + context.popScope() + values = self.modelParametersDialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) + modelerScope = QgsExpressionContextScope() + for value in values: + name = value.name if isinstance(value, ValueFromInput) else "%s_%s" % (value.alg, value.output) + modelerScope.setVariable(name, 1) + context.appendScope(modelerScope) dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: @@ -69,7 +82,23 @@ def showExpressionsBuilder(self): def getValue(self): - return self.leText.text() + if self.modelParametersDialog: + value = self.leText.text() + values = [] + for param in self.modelParametersDialog.model.parameters: + if isinstance(param, ParameterNumber): + if "@" + param.name in value: + values.append(ValueFromInput(param.name)) + for alg in self.modelParametersDialog.model.algs.values(): + for out in alg.algorithm.outputs: + if isinstance(out, OutputNumber) and "@%s_%s" % (alg.name, out.name) in value: + values.append(ValueFromOutput(alg.name, out.name)) + if values: + return CompoundValue(values, value) + else: + return value + else: + return self.leText.text() def setValue(self, value): self.leText.setText(unicode(value)) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 88b16d5ccee0..d4e3c21b2f75 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -455,39 +455,15 @@ class NumberWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - return NumberInputPanel(self.param) + return NumberInputPanel(self.param, None) else: - widget = QComboBox() - widget.setEditable(True) - files = self.dialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) - for f in files: - widget.addItem(self.dialog.resolveValueDescription(f), f) - return widget + return NumberInputPanel(self.param, self.dialog) def setValue(self, value): - if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - self.widget.setValue(value) - else: - self.setComboValue(value) - + self.widget.setValue(value) + def value(self): - if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - return self.widget.getValue() - else: - def validator(v): - if str(v).strip(): - try: - if self.param.isInteger: - int(v) - else: - float(v) - return True - except: - return False - else: - return self.param.optional - return self.comboValue(validator) - + return self.widget.getValue() class RasterWidgetWrapper(WidgetWrapper): diff --git a/python/plugins/processing/modeler/CalculatorModelerAlgorithm.py b/python/plugins/processing/modeler/CalculatorModelerAlgorithm.py deleted file mode 100644 index cf57f8a25ca7..000000000000 --- a/python/plugins/processing/modeler/CalculatorModelerAlgorithm.py +++ /dev/null @@ -1,145 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - CalculatorModelerAlgorithm.py - --------------------- - Date : August 2012 - Copyright : (C) 2012 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" -from builtins import chr -from builtins import str -from builtins import range - -__author__ = 'Victor Olaya' -__date__ = 'August 2012' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from qgis.PyQt.QtCore import Qt, QMetaObject -from qgis.PyQt.QtWidgets import QDialogButtonBox, QTextEdit, QLineEdit, QVBoxLayout - -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException -from processing.core.parameters import ParameterString -from processing.core.parameters import ParameterNumber -from processing.core.outputs import OutputNumber -from processing.modeler.ModelerParametersDialog import ModelerParametersDialog -from processing.modeler.ModelerAlgorithm import Algorithm - - -FORMULA = 'FORMULA' -NUMBER = 'NUMBER' -RESULT = 'RESULT' -AVAILABLE_VARIABLES = 10 - - -class CalculatorModelerAlgorithm(GeoAlgorithm): - - def defineCharacteristics(self): - self.showInModeler = True - self.showInToolbox = False - self.name = self.tr('Calculator', 'CalculatorModelerAlgorithm') - self.group = self.tr('Modeler-only tools', 'CalculatorModelerAlgorithm') - self.addParameter(ParameterString(FORMULA, - self.tr('Formula', 'CalculatorModelerAlgorithm'), '')) - for i in range(AVAILABLE_VARIABLES): - self.addParameter(ParameterNumber(NUMBER - + str(i), 'dummy', optional=True)) - self.addOutput(OutputNumber(RESULT, - self.tr('Result', 'CalculatorModelerAlgorithm'))) - - def processAlgorithm(self, progress): - formula = self.getParameterValue(FORMULA) - for i in range(AVAILABLE_VARIABLES): - name = NUMBER + str(i) - num = self.getParameterValue(name) - formula = formula.replace(chr(97 + i), str(num)) - try: - result = eval(formula) - self.setOutputValue(RESULT, result) - except: - raise GeoAlgorithmExecutionException( - self.tr('Wrong formula: %s', 'CalculatorModelerAlgorithm') % formula) - - def getCustomModelerParametersDialog(self, modelAlg, algName=None): - return CalculatorModelerParametersDialog(self, modelAlg, algName) - - -class CalculatorModelerParametersDialog(ModelerParametersDialog): - - def setupUi(self): - self.valueItems = {} - self.dependentItems = {} - self.resize(650, 450) - self.buttonBox = QDialogButtonBox() - self.buttonBox.setOrientation(Qt.Horizontal) - self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel - | QDialogButtonBox.Ok) - self.infoText = QTextEdit() - numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) - text = self.tr('You can refer to model values in your formula, using ' - 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') - ichar = 97 - if numbers: - for number in numbers: - text += chr(ichar) + '->' + self.resolveValueDescription(number) + '\n' - ichar += 1 - else: - text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') - self.infoText.setText(text) - self.infoText.setEnabled(False) - self.formulaText = QLineEdit() - if hasattr(self.formulaText, 'setPlaceholderText'): - self.formulaText.setPlaceholderText(self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) - if self._algName is not None: - alg = self.model.algs[self._algName] - self.formulaText.setText(alg.params[FORMULA]) - self.setWindowTitle(self.tr('Calculator', 'CalculatorModelerParametersDialog')) - self.verticalLayout = QVBoxLayout() - self.verticalLayout.setSpacing(2) - self.verticalLayout.setMargin(0) - self.verticalLayout.addWidget(self.infoText) - self.verticalLayout.addWidget(self.formulaText) - self.verticalLayout.addWidget(self.buttonBox) - self.setLayout(self.verticalLayout) - self.buttonBox.accepted.connect(self.okPressed) - self.buttonBox.rejected.connect(self.cancelPressed) - QMetaObject.connectSlotsByName(self) - - def createAlgorithm(self): - alg = Algorithm('modelertools:calculator') - alg.setName(self.model) - alg.description = self.tr('Calculator', 'CalculatorModelerParametersDialog') - - formula = self.formulaText.text() - alg.params[FORMULA] = formula - - for i in range(AVAILABLE_VARIABLES): - paramname = NUMBER + str(i) - alg.params[paramname] = None - - numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) - used = [] - for i in range(len(numbers)): - if str(chr(i + 97)) in formula: - used.append(numbers[i]) - - for i, variable in enumerate(used): - paramname = NUMBER + str(i) - alg.params[paramname] = variable - - # TODO check formula is correct - return alg diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index 22fb37b9cbd6..ce3e71a7f8ed 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -56,7 +56,7 @@ ParameterCrs, ParameterDataObject, ParameterMultipleInput) -from processing.tools import dataobjects + from processing.gui.Help2Html import getHtmlFromDescriptionsDict from processing.core.alglist import algList @@ -204,6 +204,27 @@ def __str__(self): def asPythonParameter(self): return "outputs_%s['%s']" % (self.alg, self.output) +class CompoundValue(): + + def __init__(self, values = [], definition=""): + self.values = values + self.definition = definition + + def todict(self): + return self.__dict__ + + def __eq__(self, other): + try: + return self.values == other.values and self.definition == other.definition + except: + return False + + def __str__(self): + return self.definition + + def asPythonParameter(self): + return "" #TODO + class ModelerAlgorithm(GeoAlgorithm): @@ -343,6 +364,12 @@ def getDependsOnAlgorithms(self, name): for value in list(alg.params.values()): if value is None: continue + if isinstance(value, CompoundValue): + print value + for v in value.values: + if isinstance(v, ValueFromOutput): + algs.add(v.alg) + algs.update(self.getDependsOnAlgorithms(v.alg)) if isinstance(value, list): for v in value: if isinstance(v, ValueFromOutput): @@ -387,7 +414,7 @@ def prepareAlgorithm(self, alg): for param in algInstance.parameters: if not param.hidden: if param.name in alg.params: - value = self.resolveValue(alg.params[param.name]) + value = self.resolveValue(alg.params[param.name], param) else: if iface is not None: iface.messageBar().pushMessage(self.tr("Warning"), @@ -430,17 +457,20 @@ def activateAlgorithm(self, algName): def getSafeNameForOutput(self, algName, outName): return outName + '_ALG' + algName - def resolveValue(self, value): + def resolveValue(self, value, param): if value is None: - return None + v = None if isinstance(value, list): - return ";".join([self.resolveValue(v) for v in value]) - if isinstance(value, ValueFromInput): - return self.getParameterFromName(value.name).value + v = ";".join([self.resolveValue(v, param) for v in value]) + elif isinstance(value, CompoundValue): + v = self.resolveValue(value.definition, param) + elif isinstance(value, ValueFromInput): + v = self.getParameterFromName(value.name).value elif isinstance(value, ValueFromOutput): - return self.algs[value.alg].algorithm.getOutputFromName(value.output).value + v = self.algs[value.alg].algorithm.getOutputFromName(value.output).value else: - return value + v = value + return param.evaluateForModeler(v, self) def processAlgorithm(self, progress): executed = [] @@ -571,128 +601,13 @@ def _import(name): return model @staticmethod - def fromJsonFile(filename): + def fromFile(filename): with open(filename) as f: s = f.read() alg = ModelerAlgorithm.fromJson(s) alg.descriptionFile = filename return alg - ############LEGACY METHOD TO SUPPORT OLD FORMAT########### - - LINE_BREAK_STRING = '%%%' - - @staticmethod - def fromFile(filename): - try: - alg = ModelerAlgorithm.fromJsonFile(filename) - return alg - except WrongModelException: - alg = ModelerAlgorithm.fromOldFormatFile(filename) - return alg - - @staticmethod - def fromOldFormatFile(filename): - def _tr(s): - return QCoreApplication.translate('ModelerAlgorithm', s) - hardcodedValues = {} - modelParameters = [] - modelAlgs = [] - model = ModelerAlgorithm() - model.descriptionFile = filename - lines = codecs.open(filename, 'r', encoding='utf-8') - line = lines.readline().strip('\n').strip('\r') - try: - while line != '': - if line.startswith('PARAMETER:'): - paramLine = line[len('PARAMETER:'):] - param = getParameterFromString(paramLine) - if param: - pass - else: - raise WrongModelException( - _tr('Error in parameter line: %s', 'ModelerAlgorithm') % line) - line = lines.readline().strip('\n') - tokens = line.split(',') - model.addParameter(ModelerParameter(param, - QPointF(float(tokens[0]), float(tokens[1])))) - modelParameters.append(param.name) - elif line.startswith('VALUE:'): - valueLine = line[len('VALUE:'):] - tokens = valueLine.split('===') - name = tokens[0] - value = tokens[1].replace(ModelerAlgorithm.LINE_BREAK_STRING, '\n') - hardcodedValues[name] = value - elif line.startswith('NAME:'): - model.name = line[len('NAME:'):] - elif line.startswith('GROUP:'): - model.group = line[len('GROUP:'):] - elif line.startswith('ALGORITHM:'): - algLine = line[len('ALGORITHM:'):] - alg = algList.getAlgorithm(algLine) - if alg is not None: - modelAlg = Algorithm(alg.commandLineName()) - modelAlg.description = alg.name - posline = lines.readline().strip('\n').strip('\r') - tokens = posline.split(',') - modelAlg.pos = QPointF(float(tokens[0]), float(tokens[1])) - # dependenceline = lines.readline().strip('\n').strip('\r') - for param in alg.parameters: - if not param.hidden: - line = lines.readline().strip('\n').strip('\r') - if line == str(None): - modelAlg.params[param.name] = None - else: - tokens = line.split('|') - try: - algIdx = int(tokens[0]) - except: - raise WrongModelException( - _tr('Number of parameters in the ' - '{} algorithm does not match ' - 'current Processing ' - 'implementation'.format(alg.name))) - if algIdx == -1: - if tokens[1] in modelParameters: - modelAlg.params[param.name] = ValueFromInput(tokens[1]) - else: - modelAlg.params[param.name] = hardcodedValues[tokens[1]] - else: - modelAlg.params[param.name] = ValueFromOutput(algIdx, tokens[1]) - - for out in alg.outputs: - if not out.hidden: - line = lines.readline().strip('\n').strip('\r') - if str(None) != line: - if '|' in line: - tokens = line.split('|') - name = tokens[0] - tokens = tokens[1].split(',') - pos = QPointF(float(tokens[0]), float(tokens[1])) - else: - name = line - pos = None - modelerOutput = ModelerOutput(name) - modelerOutput.pos = pos - modelAlg.outputs[out.name] = modelerOutput - - model.addAlgorithm(modelAlg) - modelAlgs.append(modelAlg.name) - else: - raise WrongModelException( - _tr('Error in algorithm name: %s',) % algLine) - line = lines.readline().strip('\n').strip('\r') - for modelAlg in list(model.algs.values()): - for name, value in modelAlg.params.items(): - if isinstance(value, ValueFromOutput): - value.alg = modelAlgs[value.alg] - return model - except Exception as e: - if isinstance(e, WrongModelException): - raise e - else: - raise WrongModelException(_tr('Error in model definition line: ') + '%s\n%s' % (line.strip(), traceback.format_exc())) - def toPython(self): s = ['##%s=name' % self.name] for param in list(self.inputs.values()): diff --git a/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py b/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py deleted file mode 100644 index dce630ffbe92..000000000000 --- a/python/plugins/processing/modeler/ModelerOnlyAlgorithmProvider.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - ModelerOnlyAlgorithmProvider.py - --------------------- - Date : August 2012 - Copyright : (C) 2012 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Victor Olaya' -__date__ = 'August 2012' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -import os.path -from qgis.PyQt.QtGui import QIcon -from processing.core.AlgorithmProvider import AlgorithmProvider -from processing.modeler.CalculatorModelerAlgorithm import CalculatorModelerAlgorithm - -pluginPath = os.path.split(os.path.dirname(__file__))[0] - - -class ModelerOnlyAlgorithmProvider(AlgorithmProvider): - - def __init__(self): - AlgorithmProvider.__init__(self) - - def getName(self): - return 'modelertools' - - def getDescription(self): - return self.tr('Modeler-only tools', 'ModelerOnlyAlgorithmProvider') - - def getIcon(self): - return QIcon(os.path.join(pluginPath, 'images', 'model.png')) - - def _loadAlgorithms(self): - self.algs = [CalculatorModelerAlgorithm()] - for alg in self.algs: - alg.provider = self diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 759b089588cd..7497550f971c 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -212,7 +212,8 @@ def setupUi(self): default = self.param.default if self.param.isInteger: default = int(math.floor(default)) - self.defaultTextBox.setText(str(default)) + if default: + self.defaultTextBox.setText(str(default)) self.horizontalLayoutDefault.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutDefault) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ @@ -294,7 +295,7 @@ def okPressed(self): or isinstance(self.param, ParameterBoolean): self.param = ParameterBoolean(name, description, self.state.isChecked()) - elif self.paramType in ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD \ + elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD \ or isinstance(self.param, ParameterTableField): if self.parentCombo.currentIndex() < 0: QMessageBox.warning(self, self.tr('Unable to define parameter'), diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 211a4f96f9e9..1188a3a18190 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -52,6 +52,7 @@ OutputString, OutputExtent, OutputCrs) +from processing.core.parameters import ParameterPoint, ParameterExtent from processing.modeler.ModelerAlgorithm import (ValueFromInput, ValueFromOutput, @@ -261,20 +262,15 @@ def showAdvancedParametersClicked(self): self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) - def getAvailableValuesForParam(self, param): - outputType = None - if isinstance(param, ParameterCrs): - outputType = OutputCrs - return self.getAvailableValuesOfType(param.__class__, outputType) - def getAvailableValuesOfType(self, paramType, outType=None, dataType=None): values = [] inputs = self.model.inputs for i in list(inputs.values()): param = i.param if isinstance(param, paramType): - if dataType is not None and param.datatype in dataType: - values.append(ValueFromInput(param.name)) + if dataType is not None: + if param.datatype in dataType: + values.append(ValueFromInput(param.name)) else: values.append(ValueFromInput(param.name)) if outType is None: @@ -340,12 +336,9 @@ def setPreviousValues(self): value = alg.params[param.name] else: value = param.default - - wrapper = self.wrappers[param.name] - wrapper.setValue(value) - + self.wrappers[param.name].setValue(value) for name, out in alg.outputs.items(): - widget = self.valueItems[name].setText(out.description) + self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() diff --git a/python/plugins/processing/modeler/ModelerScene.py b/python/plugins/processing/modeler/ModelerScene.py index 131abf10800a..9d1d37ffc863 100644 --- a/python/plugins/processing/modeler/ModelerScene.py +++ b/python/plugins/processing/modeler/ModelerScene.py @@ -30,7 +30,7 @@ from qgis.PyQt.QtWidgets import QGraphicsItem, QGraphicsScene from processing.modeler.ModelerGraphicItem import ModelerGraphicItem from processing.modeler.ModelerArrowItem import ModelerArrowItem -from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput +from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput, CompoundValue class ModelerScene(QGraphicsScene): @@ -65,6 +65,9 @@ def getItemsFromParamValue(self, value): if isinstance(value, list): for v in value: items.extend(self.getItemsFromParamValue(v)) + elif isinstance(value, CompoundValue): + for v in value.values: + items.extend(self.getItemsFromParamValue(v)) elif isinstance(value, ValueFromInput): items.append((self.paramItems[value.name], 0)) elif isinstance(value, ValueFromOutput): From a1642a376fe06a1b15b13e96e8006d90c9505bc3 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 12 Sep 2016 06:17:58 +0200 Subject: [PATCH 125/897] [processing] fixed loading of parameters for grass algorithms --- .../plugins/processing/algs/grass/GrassAlgorithm.py | 13 ++++++------- .../processing/algs/grass7/Grass7Algorithm.py | 8 ++------ 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/python/plugins/processing/algs/grass/GrassAlgorithm.py b/python/plugins/processing/algs/grass/GrassAlgorithm.py index e037e46e503c..a4911fc59244 100644 --- a/python/plugins/processing/algs/grass/GrassAlgorithm.py +++ b/python/plugins/processing/algs/grass/GrassAlgorithm.py @@ -34,6 +34,7 @@ import uuid import importlib import re +import traceback from qgis.PyQt.QtCore import QCoreApplication from qgis.PyQt.QtGui import QIcon @@ -145,18 +146,14 @@ def defineCharacteristicsFromFile(self): line = line.strip('\n').strip() if line.startswith('Hardcoded'): self.hardcodedStrings.append(line[len('Hardcoded|'):]) - elif line.startswith('Parameter'): - parameter = getParameterFromString(line) + parameter = getParameterFromString(line) + if parameter is not None: self.addParameter(parameter) if isinstance(parameter, ParameterVector): hasVectorInput = True if isinstance(parameter, ParameterMultipleInput) \ and parameter.datatype < 3: hasVectorInput = True - elif line.startswith('*Parameter'): - param = getParameterFromString(line[1:]) - param.isAdvanced = True - self.addParameter(param) else: output = getOutputFromString(line) self.addOutput(output) @@ -169,9 +166,11 @@ def defineCharacteristicsFromFile(self): " (raw output)", "txt")) line = lines.readline().strip('\n').strip() except Exception as e: + ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, - self.tr('Could not open GRASS algorithm: %s.\n%s' % (self.descriptionFile, line))) + traceback.format_exc()) + #self.tr('Could not open GRASS algorithm: %s.\n%s' % (self.descriptionFile, line))) raise e lines.close() diff --git a/python/plugins/processing/algs/grass7/Grass7Algorithm.py b/python/plugins/processing/algs/grass7/Grass7Algorithm.py index b7102a1c9b4a..31e76a9da292 100644 --- a/python/plugins/processing/algs/grass7/Grass7Algorithm.py +++ b/python/plugins/processing/algs/grass7/Grass7Algorithm.py @@ -177,18 +177,14 @@ def defineCharacteristicsFromFile(self): line = line.strip('\n').strip() if line.startswith('Hardcoded'): self.hardcodedStrings.append(line[len('Hardcoded|'):]) - elif line.startswith('Parameter'): - parameter = getParameterFromString(line) + parameter = getParameterFromString(line) + if parameter is not None: self.addParameter(parameter) if isinstance(parameter, ParameterVector): hasVectorInput = True if isinstance(parameter, ParameterMultipleInput) \ and parameter.datatype < 3: hasVectorInput = True - elif line.startswith('*Parameter'): - param = getParameterFromString(line[1:]) - param.isAdvanced = True - self.addParameter(param) else: output = getOutputFromString(line) self.addOutput(output) From 4751b706752dba2c19a3029058e7bdc8196c7a97 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 12 Sep 2016 07:54:15 +0200 Subject: [PATCH 126/897] [processing] fixed advanced parameters in modeler --- python/plugins/processing/modeler/ModelerParametersDialog.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 1188a3a18190..07dce172fbdc 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -157,11 +157,11 @@ def setupUi(self): widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) - wrapper.setVisible(self.showAdvanced) + widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) - self.verticalLayout.addWidget(wrapper.widget) + self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: From e1072e9718d2e2ea408d8773fe4c02286b26ca74 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 12 Sep 2016 07:54:55 +0200 Subject: [PATCH 127/897] [processing] added missing validators for param values in modeler --- python/plugins/processing/gui/wrappers.py | 25 +++++++++++++++-------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index d4e3c21b2f75..18a0dec223a3 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -501,7 +501,7 @@ def setValue(self, value): if self.dialogType == DIALOG_STANDARD: pass # TODO elif self.dialogType == DIALOG_BATCH: - return self.widget.setText(value) + self.widget.setText(value) else: self.setComboValue(value) @@ -511,7 +511,9 @@ def value(self): elif self.dialogType == DIALOG_BATCH: return self.widget.getText() else: - return self.comboValue() + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) class SelectionWidgetWrapper(WidgetWrapper): @@ -568,7 +570,7 @@ def setValue(self, value): if self.dialogType == DIALOG_STANDARD: pass # TODO elif self.dialogType == DIALOG_BATCH: - return self.widget.setText(value) + self.widget.setText(value) else: self.setComboValue(value) @@ -582,7 +584,9 @@ def value(self): elif self.dialogType == DIALOG_BATCH: return self.widget.getText() else: - return self.comboValue() + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) class StringWidgetWrapper(WidgetWrapper): @@ -702,9 +706,10 @@ def value(self): elif self.dialogType == DIALOG_BATCH: return self.widget.getText() else: - return self.comboValue() - - + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) + class TableFieldWidgetWrapper(WidgetWrapper): NOT_SET = '[Not set]' @@ -801,8 +806,10 @@ def value(self): elif self.dialogType == DIALOG_BATCH: return self.widget.text() else: - return self.comboValue() - + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) + def anotherParameterWidgetHasChanged(self,wrapper): if wrapper.param.name == self.param.parent: layer = wrapper.value() From 96406e52cddc1e7d2f66cb58785949e8312237cd Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 12 Sep 2016 08:00:16 +0200 Subject: [PATCH 128/897] [processing] removed message dialog when saving model. Using message bar instead --- python/plugins/processing/modeler/ModelerDialog.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index cdbc42da12b8..c7aca1f62272 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -33,8 +33,9 @@ from qgis.PyQt import uic from qgis.PyQt.QtCore import Qt, QRectF, QMimeData, QPoint, QPointF, QSettings, QByteArray from qgis.PyQt.QtWidgets import QGraphicsView, QTreeWidget, QMessageBox, QFileDialog, QTreeWidgetItem -from qgis.PyQt.QtGui import QIcon, QImage, QPainter +from qgis.PyQt.QtGui import QIcon, QImage, QPainter, QSizePolicy from qgis.core import QgsApplication +from qgis.gui import QgsMessageBar from processing.core.ProcessingConfig import ProcessingConfig from processing.core.ProcessingLog import ProcessingLog from processing.gui.HelpEditionDialog import HelpEditionDialog @@ -60,6 +61,10 @@ def __init__(self, alg=None): super(ModelerDialog, self).__init__(None) self.setupUi(self) + self.bar = QgsMessageBar() + self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) + self.layout().insertWidget(1, self.bar) + self.zoom = 1 self.setWindowFlags(Qt.WindowMinimizeButtonHint | @@ -335,9 +340,8 @@ def saveModel(self, saveAs): fout.write(text) fout.close() self.update = True - QMessageBox.information(self, self.tr('Model saved'), - self.tr('Model was correctly saved.')) - + self.bar.pushMessage("", "Model was correctly saved", level = QgsMessageBar.SUCCESS, duration = 5) + self.hasChanged = False def openModel(self): From bd06316c9daa3b5eda2686d1a94472d4c8d1bbcd Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 13 Sep 2016 06:45:02 +0200 Subject: [PATCH 129/897] [processing] richer expressions in number parameters --- python/plugins/processing/core/parameters.py | 27 +++++++++-- .../processing/gui/NumberInputPanel.py | 45 ++++++++++++++++--- 2 files changed, 63 insertions(+), 9 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index a9afcd0ac611..2028dc278545 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -41,7 +41,8 @@ from processing.tools.vector import resolveFieldIndex, features from processing.tools import dataobjects -from processing.core.outputs import OutputNumber +from processing.core.outputs import OutputNumber, OutputRaster, OutputVector +from processing.tools.dataobjects import getObject def parseBool(s): if s is None or s == str(None).lower(): @@ -863,6 +864,23 @@ def evaluate(self, alg): if isinstance(self.value, basestring): self.value = self._evaluate(self.value) + def _layerVariables(self, element, alg=None): + variables = {} + layer = getObject(element.value) + if layer is not None: + name = element.name if alg is None else "%s_%s" % (alg.name, element.name) + variables['@%s_minx' % name] = layer.extent().xMinimum() + variables['@%s_miny' % name] = layer.extent().yMinimum() + variables['@%s_maxx' % name] = layer.extent().yMaximum() + variables['@%s_maxy' % name]= layer.extent().yMaximum() + if isinstance(element, (ParameterRaster, OutputRaster)): + stats = layer.dataProvider().bandStatistics(1) + variables['@%s_avg' % name] = stats.mean + variables['@%s_stddev' % name] = stats.stdDev + variables['@%s_min' % name] = stats.minimumValue + variables['@%s_max' % name] = stats.maximumValue + return variables + def evaluateForModeler(self, value, model): if isinstance(value, numbers.Number): return value @@ -870,15 +888,18 @@ def evaluateForModeler(self, value, model): for param in model.parameters: if isinstance(param, ParameterNumber): variables["@" + param.name] = param.value + if isinstance(param, (ParameterRaster, ParameterVector)): + variables.update(self._layerVariables(param)) + for alg in model.algs.values(): for out in alg.algorithm.outputs: if isinstance(out, OutputNumber): variables["@%s_%s" % (alg.name, out.name)] = out.value + if isinstance(out, (OutputRaster, OutputVector)): + variables.update(self._layerVariables(out, alg)) for k,v in variables.iteritems(): - print k,v value = value.replace(k,unicode(v)) - print value return value def expressionContext(self): diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index 65badfadf459..362c7c1cd01d 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -39,8 +39,8 @@ QgsExpressionContextScope) from qgis.gui import QgsEncodingFileDialog, QgsExpressionBuilderDialog from qgis.utils import iface -from processing.core.parameters import ParameterNumber -from processing.core.outputs import OutputNumber +from processing.core.parameters import ParameterNumber, ParameterVector, ParameterRaster +from processing.core.outputs import OutputNumber, OutputVector, OutputRaster from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput, CompoundValue pluginPath = os.path.split(os.path.dirname(__file__))[0] @@ -68,12 +68,45 @@ def showExpressionsBuilder(self): if self.modelParametersDialog is not None: context.popScope() values = self.modelParametersDialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) - modelerScope = QgsExpressionContextScope() + variables = {} for value in values: - name = value.name if isinstance(value, ValueFromInput) else "%s_%s" % (value.alg, value.output) - modelerScope.setVariable(name, 1) - context.appendScope(modelerScope) + if isinstance(value, ValueFromInput): + name = value.name + element = self.modelParametersDialog.model.inputs[name].param + desc = element.description + else: + name = "%s_%s" % (value.alg, value.output) + alg = self.modelParametersDialog.model.algs[value.alg] + out = alg.algorithm.getOutputFromName(value.output) + desc = "Output '%s' from algorithm '%s" % (out.description, alg.description) + variables[name] = desc + values = self.modelParametersDialog.getAvailableValuesOfType(ParameterVector, OutputVector) + values.extend(self.modelParametersDialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)) + for value in values: + if isinstance(value, ValueFromInput): + name = value.name + element = self.modelParametersDialog.model.inputs[name].param + desc = element.description + else: + name = "%s_%s" % (value.alg, value.output) + alg = self.modelParametersDialog.model.algs[value.alg] + element = alg.algorithm.getOutputFromName(value.output) + desc = "Output '%s' from algorithm '%s" % (element.description, alg.description) + variables['%s_minx' % name] = "Minimum X of %s" % desc + variables['%s_miny' % name] = "Maximum X of %s" % desc + variables['%s_maxx' % name] = "Minimum Y of %s" % desc + variables['%s_maxy' % name] = "Maximum Y of %s" % desc + if isinstance(element, (ParameterRaster, OutputRaster)): + variables['%s_min' % name] = "Minimum value of %s" % desc + variables['%s_max' % name] = "Maximum value of %s" % desc + variables['%s_avg' % name] = "Mean value of %s" % desc + variables['%s_stddev' % name] = "Standard deviation of %s" % desc + + #context.appendScope(modelerScope) + #context.setHighlightedVariables(modelerScope.variableNames()) dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) + for variable, desc in variables.iteritems(): + dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: exp = QgsExpression(dlg.expressionText()) From a4a74b631a10a62b28068ea9c0f691f662333977 Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 13 Sep 2016 10:01:02 +0200 Subject: [PATCH 130/897] [processing] removed commented lines --- python/plugins/processing/gui/NumberInputPanel.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index 362c7c1cd01d..5e31788eb426 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -102,8 +102,6 @@ def showExpressionsBuilder(self): variables['%s_avg' % name] = "Mean value of %s" % desc variables['%s_stddev' % name] = "Standard deviation of %s" % desc - #context.appendScope(modelerScope) - #context.setHighlightedVariables(modelerScope.variableNames()) dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) for variable, desc in variables.iteritems(): dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) From 2bb6e4c19faee7f33b380f101385d22735ea1429 Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 14 Sep 2016 07:26:45 +0200 Subject: [PATCH 131/897] =?UTF-8?q?[processing]=20Asumme=20standard=20dial?= =?UTF-8?q?og=20when=20wrapper=E2=80=99s=20parent=20dialog=20is=20of=20unk?= =?UTF-8?q?nown=20class?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python/plugins/processing/gui/wrappers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 18a0dec223a3..3605e61bc8cd 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -83,7 +83,7 @@ def __init__(self, param, dialog, row=0, col=0): self.dialog = dialog self.row = row self.col = col - self.dialogType = dialogTypes[dialog.__class__.__name__] + self.dialogType = dialogTypes.get(dialog.__class__.__name__, DIALOG_STANDARD) self.widget = self.createWidget() if param.default is not None: self.setValue(param.default) From dfb4cdd34b93d0d05ce94a842a4cf871c5a900fd Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 14 Sep 2016 09:49:04 +0200 Subject: [PATCH 132/897] [processing] moved output value evaluation to output object itself --- .../processing/algs/qgis/FieldsCalculator.py | 5 - .../plugins/processing/core/GeoAlgorithm.py | 49 ++------ python/plugins/processing/core/outputs.py | 118 ++++++++++++------ python/plugins/processing/core/parameters.py | 37 ++++-- .../processing/gui/OutputSelectionPanel.py | 55 ++------ 5 files changed, 129 insertions(+), 135 deletions(-) diff --git a/python/plugins/processing/algs/qgis/FieldsCalculator.py b/python/plugins/processing/algs/qgis/FieldsCalculator.py index cbc6f9880098..d97df4332d94 100644 --- a/python/plugins/processing/algs/qgis/FieldsCalculator.py +++ b/python/plugins/processing/algs/qgis/FieldsCalculator.py @@ -89,11 +89,6 @@ def processAlgorithm(self, progress): output = self.getOutputFromName(self.OUTPUT_LAYER) - if output.value == '': - ext = output.getDefaultFileExtension(self) - output.value = system.getTempFilenameInTempFolder( - output.name + '.' + ext) - fields = layer.fields() if newField: fields.append(QgsField(fieldName, fieldType, '', width, precision)) diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index bb10aa110c53..9162331fd0f6 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -197,10 +197,8 @@ def execute(self, progress=SilentProgress(), model=None): self.model = model try: self.setOutputCRS() - self.resolveTemporaryOutputs() - self.resolveDataObjects() + self.resolveOutputs() self.evaluateParameterValues() - self.checkOutputFileExtensions() self.runPreExecutionScript(progress) self.processAlgorithm(progress) progress.setPercentage(100) @@ -328,51 +326,24 @@ def getFormatShortNameFromFilename(self, filename): return name return 'GTiff' - def checkOutputFileExtensions(self): - """Checks if the values of outputs are correct and have one of - the supported output extensions. - - If not, it adds the first one of the supported extensions, which - is assumed to be the default one. - """ - for out in self.outputs: - if not out.hidden and out.value is not None: - if not os.path.isabs(out.value): - continue - if isinstance(out, OutputRaster): - exts = dataobjects.getSupportedOutputRasterLayerExtensions() - elif isinstance(out, OutputVector): - exts = dataobjects.getSupportedOutputVectorLayerExtensions() - elif isinstance(out, OutputTable): - exts = dataobjects.getSupportedOutputTableExtensions() - elif isinstance(out, OutputHTML): - exts = ['html', 'htm'] - else: - continue - idx = out.value.rfind('.') - if idx == -1: - out.value = out.value + '.' + exts[0] - else: - ext = out.value[idx + 1:] - if ext not in exts + ['dbf']: - out.value = out.value + '.' + exts[0] - - def evaluateParameterValues(self): for param in self.parameters: try: param.evaluate(self) except ValueError, e: + traceback.print_exc() raise GeoAlgorithmExecutionException(str(e)) - def resolveTemporaryOutputs(self): + def resolveOutputs(self): """Sets temporary outputs (output.value = None) with a - temporary file instead. + temporary file instead. Resolves expressions as well. """ - for out in self.outputs: - if not out.hidden and out.value is None: - setTempOutput(out, self) - + try: + for out in self.outputs: + out.resolveValue(self) + except ValueError, e: + raise GeoAlgorithmExecutionException(str(e)) + def setOutputCRS(self): layers = dataobjects.getAllLayers() for param in self.parameters: diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index 0e1a69049ef4..b3e5d13371c6 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -20,7 +20,6 @@ from builtins import range from builtins import object - __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' @@ -29,15 +28,27 @@ __revision__ = '$Format:%H$' +import os import sys from qgis.PyQt.QtCore import QCoreApplication, QSettings from processing.core.ProcessingConfig import ProcessingConfig -from processing.tools.system import isWindows, getTempFilenameInTempFolder +from processing.tools.system import isWindows, getTempFilenameInTempFolder, getTempDirInTempFolder from processing.tools.vector import VectorWriter, TableWriter from processing.tools import dataobjects +from qgis.core import QgsExpressionContext, QgsExpressionContextUtils, QgsExpression, QgsExpressionContextScope + +def _expressionContext(alg): + context = QgsExpressionContext() + context.appendScope(QgsExpressionContextUtils.globalScope()) + context.appendScope(QgsExpressionContextUtils.projectScope()) + processingScope = QgsExpressionContextScope() + for param in alg.parameters: + processingScope.setVariable('%s_value' % param.name, '') + context.appendScope(processingScope) + return context class Output(object): @@ -82,6 +93,44 @@ def setValue(self, value): return True except: return False + + def _resolveTemporary(self, alg): + ext = self.getDefaultFileExtension() + return getTempFilenameInTempFolder(self.name + '.' + ext) + + def _supportedExtensions(self): + return [] + + def resolveValue(self, alg): + if not self.hidden and not bool(self.value): + self.value = self._resolveTemporary(alg) + else: + exp = QgsExpression(self.value) + if exp.hasParserError(): + raise ValueError(self.tr("Error in output expression: ") + exp.parserErrorString()) + self.value = exp.evaluate(_expressionContext(alg)) + if exp.hasEvalError(): + raise ValueError("Error evaluating output expression: " + exp.evalErrorString()) + + + + print self.value + if ":" not in self.value: + if not os.path.isabs(self.value): + self.value = os.path.join(ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER), + self.value) + supported = self._supportedExtensions() + if supported: + idx = self.value.rfind('.') + if idx == -1: + self.value = self.value + '.' + self.getDefaultFileExtension() + else: + ext = self.value[idx + 1:] + if ext not in supported: + self.value = self.value + '.' + self.getDefaultFileExtension() + + def expressionContext(self, alg): + return _expressionContext(alg) def typeName(self): return self.__class__.__name__.replace('Output', '').lower() @@ -93,7 +142,9 @@ def tr(self, string, context=''): class OutputDirectory(Output): - directory = True + + def resolveValue(self, alg): + self.value = getTempDirInTempFolder() class OutputExtent(Output): @@ -118,10 +169,7 @@ def setValue(self, value): class OutputCrs(Output): def __init__(self, name='', description=''): - self.name = name - self.description = description - self.value = None - self.hidden = True + Output.__init__(self, name, description, True) class OutputFile(Output): @@ -136,7 +184,7 @@ def getFileFilter(self, alg): else: return self.tr('%s files(*.%s)', 'OutputFile') % (self.ext, self.ext) - def getDefaultFileExtension(self, alg): + def getDefaultFileExtension(self): return self.ext or 'file' @@ -145,17 +193,14 @@ class OutputHTML(Output): def getFileFilter(self, alg): return self.tr('HTML files(*.html)', 'OutputHTML') - def getDefaultFileExtension(self, alg): + def getDefaultFileExtension(self): return 'html' class OutputNumber(Output): def __init__(self, name='', description=''): - self.name = name - self.description = description - self.value = None - self.hidden = True + Output.__init__(self, name, description, True) class OutputRaster(Output): @@ -168,11 +213,8 @@ def getFileFilter(self, alg): exts[i] = self.tr('%s files (*.%s)', 'OutputVector') % (exts[i].upper(), exts[i].lower()) return ';;'.join(exts) - def getDefaultFileExtension(self, alg): - supported = alg.provider.getSupportedOutputRasterLayerExtensions() - default = ProcessingConfig.getSetting(ProcessingConfig.DEFAULT_OUTPUT_RASTER_LAYER_EXT) - ext = default if default in supported else supported[0] - return ext + def getDefaultFileExtension(self): + return ProcessingConfig.getSetting(ProcessingConfig.DEFAULT_OUTPUT_RASTER_LAYER_EXT) def getCompatibleFileName(self, alg): """ @@ -189,18 +231,17 @@ def getCompatibleFileName(self, alg): return self.value else: if self.compatible is None: - self.compatible = getTempFilenameInTempFolder( - self.name + '.' + self.getDefaultFileExtension(alg)) + supported = alg.provider.getSupportedOutputRasterLayerExtensions() + default = ProcessingConfig.getSetting(ProcessingConfig.DEFAULT_OUTPUT_RASTER_LAYER_EXT) + ext = default if default in supported else supported[0] + self.compatible = getTempFilenameInTempFolder(self.name + '.' + ext) return self.compatible class OutputString(Output): def __init__(self, name='', description=''): - self.name = name - self.description = description - self.value = None - self.hidden = True + Output.__init__(self, name, description, True) class OutputTable(Output): @@ -209,13 +250,13 @@ class OutputTable(Output): compatible = None def getFileFilter(self, alg): - exts = ['csv'] + exts = ['dbf'] for i in range(len(exts)): exts[i] = exts[i].upper() + ' files(*.' + exts[i].lower() + ')' return ';;'.join(exts) - def getDefaultFileExtension(self, alg): - return alg.provider.getSupportedOutputTableExtensions()[0] + def getDefaultFileExtension(self): + return "dbf" def getCompatibleFileName(self, alg): """Returns a filename that is compatible with the algorithm @@ -233,7 +274,7 @@ def getCompatibleFileName(self, alg): else: if self.compatible is None: self.compatible = getTempFilenameInTempFolder( - self.name + '.' + self.getDefaultFileExtension(alg)) + self.name + '.' + alg.provider.getSupportedOutputTableExtensions()[0]) return self.compatible def getTableWriter(self, fields): @@ -286,14 +327,13 @@ def getFileFilter(self, alg): exts[i] = self.tr('%s files (*.%s)', 'OutputVector') % (exts[i].upper(), exts[i].lower()) return ';;'.join(exts) - def getDefaultFileExtension(self, alg): - supported = alg.provider.getSupportedOutputVectorLayerExtensions() + def getDefaultFileExtension(self): if self.hasGeometry(): default = ProcessingConfig.getSetting(ProcessingConfig.DEFAULT_OUTPUT_VECTOR_LAYER_EXT) else: default = 'dbf' - ext = default if default in supported else supported[0] - return ext + return default + def getCompatibleFileName(self, alg): """Returns a filename that is compatible with the algorithm @@ -309,8 +349,10 @@ def getCompatibleFileName(self, alg): return self.value else: if self.compatible is None: - self.compatible = getTempFilenameInTempFolder( - self.name + '.' + self.getDefaultFileExtension(alg)) + default = self.getDefaultFileExtension() + supported = alg.provider.getSupportedOutputVectorLayerExtensions() + ext = default if default in supported else supported[0] + self.compatible = getTempFilenameInTempFolder(self.name + '.' + ext) return self.compatible def getVectorWriter(self, fields, geomType, crs, options=None): @@ -345,7 +387,13 @@ def getVectorWriter(self, fields, geomType, crs, options=None): def dataType(self): return dataobjects.vectorDataType(self) - + def _resolveTemporary(self, alg): + if alg.provider.supportsNonFileBasedOutput(): + return "memory:" + else: + ext = self.getDefaultFileExtension() + return getTempFilenameInTempFolder(self.name + '.' + ext) + def getOutputFromString(s): try: diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 2028dc278545..bbb0ef45fc7f 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -102,6 +102,17 @@ def _expressionContext(): context.appendScope(processingScope) return context +def _resolveLayers(value): + layers = dataobjects.getAllLayers() + if value: + inputlayers = value.split(';') + for i, inputlayer in enumerate(inputlayers): + for layer in layers: + if layer.name() == inputlayer: + inputlayers[i] = layer.source() + break + return ";".join(inputlayers) + class Parameter: """ @@ -312,6 +323,9 @@ def getValueAsCommandLineParameter(self): s = dataobjects.normalizeLayerSource(str(self.value)) s = '"%s"' % s return s + + def evaluate(self, alg): + self.value = _resolveLayers(self.value) class ParameterExtent(Parameter): @@ -771,6 +785,9 @@ def fromScriptCode(self, line): return ParameterMultipleInput(name, definition, dataobjects.TYPE_VECTOR_ANY, isOptional) + def evaluate(self, alg): + self.value = _resolveLayers(self.value) + class ParameterNumber(Parameter): @@ -861,7 +878,7 @@ def _evaluate(self, value): return result def evaluate(self, alg): - if isinstance(self.value, basestring): + if isinstance(self.value, basestring) and bool(self.value): self.value = self._evaluate(self.value) def _layerVariables(self, element, alg=None): @@ -1024,7 +1041,6 @@ def getAsScriptCode(self): def fromScriptCode(self, line): isOptional, name, definition = _splitParameterOptions(line) descName = _createDescriptiveName(name) - print isOptional, name, definition if definition.lower().strip().startswith('raster'): return ParameterRaster(name, descName, optional=isOptional) @@ -1111,7 +1127,7 @@ def __init__(self, name='', description='', default=None, multiline=False, self.evaluateExpressions = parseBool(evaluateExpressions) def setValue(self, obj): - if obj is None: + if not bool(obj): if not self.optional: return False self.value = None @@ -1153,13 +1169,14 @@ def fromScriptCode(self, line): return ParameterString(name, descName, multiline=True, optional=isOptional) def evaluate(self, alg): - exp = QgsExpression(self.value) - if exp.hasParserError(): - raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) - result = exp.evaluate(_expressionContext()) - if exp.hasEvalError(): - raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) - self.value = result + if isinstance(self.value, basestring) and bool(self.value) and self.evaluateExpressions: + exp = QgsExpression(self.value) + if exp.hasParserError(): + raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) + result = exp.evaluate(_expressionContext()) + if exp.hasEvalError(): + raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) + self.value = result def expressionContext(self): return _expressionContext() diff --git a/python/plugins/processing/gui/OutputSelectionPanel.py b/python/plugins/processing/gui/OutputSelectionPanel.py index 58830956fba6..a18dcfe20a9f 100644 --- a/python/plugins/processing/gui/OutputSelectionPanel.py +++ b/python/plugins/processing/gui/OutputSelectionPanel.py @@ -83,14 +83,14 @@ def selectOutput(self): if isinstance(self.output, OutputVector) \ and self.alg.provider.supportsNonFileBasedOutput(): - # use memory layers for temporary files if supported - actionSaveToTempFile = QAction( + # use memory layers for temporary layers if supported + actionSaveToTemp = QAction( self.tr('Create temporary layer'), self.btnSelect) else: - actionSaveToTempFile = QAction( + actionSaveToTemp = QAction( self.tr('Save to a temporary file'), self.btnSelect) - actionSaveToTempFile.triggered.connect(self.saveToTemporaryFile) - popupMenu.addAction(actionSaveToTempFile) + actionSaveToTemp.triggered.connect(self.saveToTemporary) + popupMenu.addAction(actionSaveToTemp) actionSaveToFile = QAction( self.tr('Save to file...'), self.btnSelect) @@ -121,22 +121,13 @@ def selectOutput(self): popupMenu.exec_(QCursor.pos()) def showExpressionsBuilder(self): - dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', self.expressionContext()) + dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', + self.output.expressionContext(self.alg)) dlg.setWindowTitle(self.tr('Expression based output')) if dlg.exec_() == QDialog.Accepted: self.leText.setText(dlg.expressionText()) - def expressionContext(self): - context = QgsExpressionContext() - context.appendScope(QgsExpressionContextUtils.globalScope()) - context.appendScope(QgsExpressionContextUtils.projectScope()) - processingScope = QgsExpressionContextScope() - for param in self.alg.parameters: - processingScope.setVariable('%s_value' % param.name, '') - context.appendScope(processingScope) - return context - - def saveToTemporaryFile(self): + def saveToTemporary(self): self.leText.setText('') def saveToPostGIS(self): @@ -237,32 +228,4 @@ def selectDirectory(self): self.leText.setText(dirName) def getValue(self): - fileName = str(self.leText.text()) - context = self.expressionContext() - exp = QgsExpression(fileName) - if not exp.hasParserError(): - result = exp.evaluate(context) - if not exp.hasEvalError(): - fileName = result - if fileName.startswith("[") and fileName.endswith("]"): - fileName = fileName[1:-1] - if fileName.strip() in ['', self.SAVE_TO_TEMP_FILE, self.SAVE_TO_TEMP_LAYER]: - if isinstance(self.output, OutputVector) \ - and self.alg.provider.supportsNonFileBasedOutput(): - # use memory layers for temporary files if supported - value = 'memory:' - else: - value = None - elif fileName.startswith('memory:'): - value = fileName - elif fileName.startswith('postgis:'): - value = fileName - elif fileName.startswith('spatialite:'): - value = fileName - elif not os.path.isabs(fileName): - value = ProcessingConfig.getSetting( - ProcessingConfig.OUTPUT_FOLDER) + os.sep + fileName - else: - value = fileName - - return value + return self.leText.text() From c491c012664aa0d5a7836a0f6c4ada0f7d8d95eb Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 14 Sep 2016 09:51:17 +0200 Subject: [PATCH 133/897] [processing] changes to allow custom parameter dialog adapt to new parameter architecture --- .../processing/algs/gdal/GdalAlgorithmDialog.py | 9 ++------- .../processing/algs/qgis/ui/FieldsMapperDialogs.py | 3 +-- python/plugins/processing/gui/AlgorithmDialog.py | 5 +---- python/plugins/processing/gui/AlgorithmDialogBase.py | 11 +++++++++-- python/plugins/processing/gui/BatchAlgorithmDialog.py | 3 +-- python/plugins/processing/gui/BatchPanel.py | 4 ++++ 6 files changed, 18 insertions(+), 17 deletions(-) diff --git a/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py b/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py index d5f2137f485c..e0180754dfe8 100644 --- a/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py +++ b/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py @@ -40,9 +40,8 @@ def __init__(self, alg): AlgorithmDialogBase.__init__(self, alg) self.alg = alg - - self.mainWidget = GdalParametersPanel(self, alg) - self.setMainWidget() + + self.setMainWidget(GdalParametersPanel(self, alg)) cornerWidget = QWidget() layout = QVBoxLayout() @@ -56,10 +55,6 @@ def __init__(self, alg): self.mainWidget.parametersHaveChanged() - QgsMapLayerRegistry.instance().layerWasAdded.connect(self.mainWidget.layerAdded) - QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.mainWidget.layersWillBeRemoved) - - class GdalParametersPanel(ParametersPanel): def __init__(self, parent, alg): diff --git a/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py b/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py index 8d7f443afe7f..c90f46bec1ef 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py @@ -98,8 +98,7 @@ def __init__(self, alg): self.alg = alg - self.mainWidget = FieldsMapperParametersPanel(self, alg) - self.setMainWidget() + self.setMainWidget(FieldsMapperParametersPanel(self, alg)) def setParamValue(self, param, widget, alg=None): if isinstance(param, ParameterFieldsMapping): diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index f6f294f45a82..4a6f640cb25b 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -69,8 +69,7 @@ def __init__(self, alg): self.alg = alg - self.mainWidget = ParametersPanel(self, alg) - self.setMainWidget() + self.setMainWidget(ParametersPanel(self, alg)) self.cornerWidget = QWidget() layout = QVBoxLayout() @@ -82,8 +81,6 @@ def __init__(self, alg): self.cornerWidget.setLayout(layout) self.tabWidget.setCornerWidget(self.cornerWidget) - QgsMapLayerRegistry.instance().layerWasAdded.connect(self.mainWidget.layerRegistryChanged) - QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.mainWidget.layerRegistryChanged) def runAsBatch(self): self.close() diff --git a/python/plugins/processing/gui/AlgorithmDialogBase.py b/python/plugins/processing/gui/AlgorithmDialogBase.py index 651e5fea2910..53045dd820a3 100644 --- a/python/plugins/processing/gui/AlgorithmDialogBase.py +++ b/python/plugins/processing/gui/AlgorithmDialogBase.py @@ -35,7 +35,7 @@ from qgis.PyQt.QtNetwork import QNetworkRequest, QNetworkReply from qgis.utils import iface -from qgis.core import QgsNetworkAccessManager +from qgis.core import QgsNetworkAccessManager, QgsMapLayerRegistry from processing.core.ProcessingConfig import ProcessingConfig @@ -122,8 +122,15 @@ def closeEvent(self, evt): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) super(AlgorithmDialogBase, self).closeEvent(evt) - def setMainWidget(self): + def setMainWidget(self, widget): + if self.mainWidget is not None: + QgsMapLayerRegistry.instance().layerWasAdded.disconnect(self.mainWidget.layerRegistryChanged) + QgsMapLayerRegistry.instance().layersWillBeRemoved.disconnect(self.mainWidget.layerRegistryChanged) + self.mainWidget = widget self.tabWidget.widget(0).layout().addWidget(self.mainWidget) + QgsMapLayerRegistry.instance().layerWasAdded.connect(self.mainWidget.layerRegistryChanged) + QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.mainWidget.layerRegistryChanged) + def error(self, msg): QApplication.restoreOverrideCursor() diff --git a/python/plugins/processing/gui/BatchAlgorithmDialog.py b/python/plugins/processing/gui/BatchAlgorithmDialog.py index 59c8dfdc2ed9..dfda489b6c74 100644 --- a/python/plugins/processing/gui/BatchAlgorithmDialog.py +++ b/python/plugins/processing/gui/BatchAlgorithmDialog.py @@ -56,8 +56,7 @@ def __init__(self, alg): self.setWindowTitle(self.tr('Batch Processing - %s') % self.alg.name) - self.mainWidget = BatchPanel(self, self.alg) - self.setMainWidget() + self.setMainWidget(BatchPanel(self, self.alg)) self.textShortHelp.setVisible(False) diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index 787008fb0745..0968cfb85315 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -88,6 +88,10 @@ def __init__(self, parent, alg): self.fillParameterValues) self.initWidgets() + + + def layerRegistryChanged(self): + pass def initWidgets(self): # If there are advanced parameters — show corresponding button From cdcc01e97c0066767f8cd8192f65f31256ab424b Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 14 Sep 2016 09:51:41 +0200 Subject: [PATCH 134/897] [processing] removed debug lines --- python/plugins/processing/gui/BatchOutputSelectionPanel.py | 2 -- python/plugins/processing/gui/ParametersPanel.py | 1 - python/plugins/processing/modeler/ModelerAlgorithm.py | 1 - 3 files changed, 4 deletions(-) diff --git a/python/plugins/processing/gui/BatchOutputSelectionPanel.py b/python/plugins/processing/gui/BatchOutputSelectionPanel.py index 11ce95755191..964785382220 100644 --- a/python/plugins/processing/gui/BatchOutputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchOutputSelectionPanel.py @@ -83,8 +83,6 @@ def showSelectionDialog(self): path = '' filename, selectedFileFilter = QFileDialog.getSaveFileName(self, self.tr('Save file'), path, filefilter) - # fix_print_with_import - print(filename, selectedFileFilter) if filename: if not filename.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", filefilter))): diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index 8f87498336a6..06b02fe658a5 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -124,7 +124,6 @@ def initWidgets(self): widget = QWidget() widget.setLayout(layout) - print wrapper tooltips = self.alg.getParameterDescriptions() widget.setToolTip(tooltips.get(param.name, param.description)) diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index ce3e71a7f8ed..0bd81f995996 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -365,7 +365,6 @@ def getDependsOnAlgorithms(self, name): if value is None: continue if isinstance(value, CompoundValue): - print value for v in value.values: if isinstance(v, ValueFromOutput): algs.add(v.alg) From 0ea66299c85f18398a2add7c6df8d71a932278e2 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 15 Sep 2016 10:00:40 +0200 Subject: [PATCH 135/897] [processing] fixed error in constructor of ParameterTableField --- python/plugins/processing/core/parameters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index bbb0ef45fc7f..02b2def4d9a8 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1284,7 +1284,7 @@ def __init__(self, name='', description='', parent=None, datatype=-1, optional=False, multiple = False): Parameter.__init__(self, name, description, None, optional) self.parent = parent - self.multiple = True + self.multiple = multiple self.datatype = int(datatype) def getValueAsCommandLineParameter(self): From 257faf308376754307ebf3cd818a6658708ee6f6 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 15 Sep 2016 12:27:10 +0200 Subject: [PATCH 136/897] [processing] fixed evaluation of output values --- python/plugins/processing/core/outputs.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index b3e5d13371c6..3ca682e15621 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -106,15 +106,11 @@ def resolveValue(self, alg): self.value = self._resolveTemporary(alg) else: exp = QgsExpression(self.value) - if exp.hasParserError(): - raise ValueError(self.tr("Error in output expression: ") + exp.parserErrorString()) - self.value = exp.evaluate(_expressionContext(alg)) - if exp.hasEvalError(): - raise ValueError("Error evaluating output expression: " + exp.evalErrorString()) + if not exp.hasParserError(): + value = exp.evaluate(_expressionContext(alg)) + if not exp.hasEvalError(): + self.value = value - - - print self.value if ":" not in self.value: if not os.path.isabs(self.value): self.value = os.path.join(ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER), From d07aef9c5bb310f893fd36435f88af8b80b650d0 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 15 Sep 2016 12:28:03 +0200 Subject: [PATCH 137/897] [processing] added missing return statement in getParameterFromString --- python/plugins/processing/core/parameters.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 02b2def4d9a8..f91d817fda8a 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1495,6 +1495,7 @@ def getParameterFromString(s): clazz = getattr(sys.modules[__name__], tokens[0]) param = clazz(*params) param.isAdvanced = isAdvanced + return param except: return None else: # try script syntax From 53d0372cad9c2782989f4d00daf272694dd6cc90 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 15 Sep 2016 16:21:26 +0200 Subject: [PATCH 138/897] [processing] return copy of object dictionary in parameter todict method --- python/plugins/processing/core/parameters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index f91d817fda8a..d9c8337978d9 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -182,7 +182,7 @@ def typeName(self): return self.__class__.__name__.replace('Parameter', '').lower() def todict(self): - o = self.__dict__ + o = deepcopy(self.__dict__) del o['metadata'] return o From ccdf3722507bf9115af1e1bccf019d2439086923 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 16 Sep 2016 09:13:16 +0200 Subject: [PATCH 139/897] [processing] UI improvement for defining model parameters --- .../ModelerParameterDefinitionDialog.py | 210 ++++++++---------- 1 file changed, 97 insertions(+), 113 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 7497550f971c..7b1ebcb734f7 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -70,9 +70,6 @@ class ModelerParameterDefinitionDialog(QDialog): PARAMETER_CRS = 'CRS' PARAMETER_MULTIPLE = 'Multiple input' - # To add - PARAMETER_FIXED_TABLE = 'Fixed table' - paramTypes = [ PARAMETER_BOOLEAN, PARAMETER_EXTENT, @@ -98,32 +95,15 @@ def __init__(self, alg, paramType=None, param=None): def setupUi(self): self.setWindowTitle(self.tr('Parameter definition')) + self.setMinimumWidth(300) self.verticalLayout = QVBoxLayout(self) - self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) - self.horizontalLayoutName = QHBoxLayout(self) - self.horizontalLayoutName.setSpacing(2) - self.horizontalLayoutName.setMargin(0) self.label = QLabel(self.tr('Parameter name')) - self.horizontalLayoutName.addWidget(self.label) + self.verticalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() - self.horizontalLayoutName.addWidget(self.nameTextBox) - self.verticalLayout.addLayout(self.horizontalLayoutName) - - self.horizontalLayoutRequired = QHBoxLayout(self) - self.horizontalLayoutRequired.setSpacing(2) - self.horizontalLayoutRequired.setMargin(0) - self.horizontalLayoutParent = QHBoxLayout(self) - self.horizontalLayoutParent.setSpacing(2) - self.horizontalLayoutParent.setMargin(0) - self.horizontalLayoutDefault = QHBoxLayout(self) - self.horizontalLayoutDefault.setSpacing(2) - self.horizontalLayoutDefault.setMargin(0) - self.horizontalLayoutDatatype = QHBoxLayout(self) - self.horizontalLayoutDatatype.setSpacing(2) - self.horizontalLayoutDatatype.setMargin(0) + self.verticalLayout.addWidget(self.nameTextBox) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) @@ -134,12 +114,11 @@ def setupUi(self): self.state.setText(self.tr('Checked')) self.state.setChecked(False) if self.param is not None: - self.state.setChecked(True if self.param.value else False) - self.horizontalLayoutParent.addWidget(self.state) - self.verticalLayout.addLayout(self.horizontalLayoutParent) + self.state.setChecked(bool(self.param.value)) + self.verticalLayout.addWidget(self.state) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Parent layer'))) + self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in list(self.alg.inputs.values()): @@ -149,28 +128,25 @@ def setupUi(self): if self.param.parent == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 - self.horizontalLayoutParent.addWidget(self.parentCombo) - self.verticalLayout.addLayout(self.horizontalLayoutParent) + self.verticalLayout.addWidget(self.parentCombo) # add the datatype selector - self.horizontalLayoutDatatype.addWidget(QLabel(self.tr('Allowed ' - 'data type'))) + self.verticalLayout.addWidget(QLabel(self.tr('Allowed data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any'), -1) self.datatypeCombo.addItem(self.tr('Number'), 0) self.datatypeCombo.addItem(self.tr('String'), 1) - self.horizontalLayoutDatatype.addWidget(self.datatypeCombo) + self.verticalLayout.addWidget(self.datatypeCombo) if self.param is not None and self.param.datatype is not None: # QComboBoxes indexes start at 0, # self.param.datatype start with -1 that is why I need to do +1 - datatype_index = self.param.datatype + 1 - self.datatypeCombo.setCurrentIndex(datatype_index) - self.verticalLayout.addLayout(self.horizontalLayoutDatatype) + datatypeIndex = self.param.datatype + 1 + self.datatypeCombo.setCurrentIndex(datatypeIndex) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ - isinstance(self.param, ParameterVector): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Shape type'))) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or + isinstance(self.param, ParameterVector)): + self.verticalLayout.addWidget(QLabel(self.tr('Shape type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Any')) self.shapetypeCombo.addItem(self.tr('Point')) @@ -178,11 +154,10 @@ def setupUi(self): self.shapetypeCombo.addItem(self.tr('Polygon')) if self.param is not None: self.shapetypeCombo.setCurrentIndex(self.param.datatype[0] + 1) - self.horizontalLayoutParent.addWidget(self.shapetypeCombo) - self.verticalLayout.addLayout(self.horizontalLayoutParent) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ - isinstance(self.param, ParameterMultipleInput): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Data type'))) + self.verticalLayout.addWidget(self.shapetypeCombo) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or + isinstance(self.param, ParameterMultipleInput)): + self.verticalLayout.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Vector (any)')) self.datatypeCombo.addItem(self.tr('Vector (point)')) @@ -192,19 +167,18 @@ def setupUi(self): self.datatypeCombo.addItem(self.tr('File')) if self.param is not None: self.datatypeCombo.setCurrentIndex(self.param.datatype + 1) - self.horizontalLayoutParent.addWidget(self.datatypeCombo) - self.verticalLayout.addLayout(self.horizontalLayoutParent) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ - isinstance(self.param, ParameterNumber): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Min/Max values'))) + self.verticalLayout.addWidget(self.datatypeCombo) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or + isinstance(self.param, ParameterNumber)): + self.verticalLayout.addWidget(QLabel(self.tr('Min value'))) self.minTextBox = QLineEdit() + self.verticalLayout.addWidget(self.minTextBox) + self.verticalLayout.addWidget(QLabel(self.tr('Max value'))) self.maxTextBox = QLineEdit() + self.verticalLayout.addWidget(self.maxTextBox) if self.param is not None: self.minTextBox.setText(str(self.param.min)) self.maxTextBox.setText(str(self.param.max)) - self.horizontalLayoutParent.addWidget(self.minTextBox) - self.horizontalLayoutParent.addWidget(self.maxTextBox) - self.verticalLayout.addLayout(self.horizontalLayoutParent) self.horizontalLayoutDefault.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) @@ -213,54 +187,47 @@ def setupUi(self): if self.param.isInteger: default = int(math.floor(default)) if default: - self.defaultTextBox.setText(str(default)) - self.horizontalLayoutDefault.addWidget(self.defaultTextBox) - self.verticalLayout.addLayout(self.horizontalLayoutDefault) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ - isinstance(self.param, ParameterString): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) + self.defaultTextBox.setText(unicode(default)) + self.verticalLayout.addWidget(self.defaultTextBox) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or + isinstance(self.param, ParameterString)): + self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) - self.horizontalLayoutParent.addWidget(self.defaultTextBox) - self.verticalLayout.addLayout(self.horizontalLayoutParent) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ - isinstance(self.param, ParameterFile): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Type'))) + self.verticalLayout.addWidget(self.defaultTextBox) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or + isinstance(self.param, ParameterFile)): + self.verticalLayout.addWidget(QLabel(self.tr('Type'))) self.fileFolderCombo = QComboBox() self.fileFolderCombo.addItem(self.tr('File')) self.fileFolderCombo.addItem(self.tr('Folder')) if self.param is not None: self.fileFolderCombo.setCurrentIndex( 1 if self.param.isFolder else 0) - self.horizontalLayoutParent.addWidget(self.fileFolderCombo) - self.verticalLayout.addLayout(self.horizontalLayoutParent) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ - isinstance(self.param, ParameterPoint): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) + self.verticalLayout.addWidget(self.fileFolderCombo) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or + isinstance(self.param, ParameterPoint)): + self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) - self.horizontalLayoutParent.addWidget(self.defaultTextBox) - self.verticalLayout.addLayout(self.horizontalLayoutParent) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or \ - isinstance(self.param, ParameterCrs): - self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) + self.verticalLayout.addWidget(self.defaultTextBox) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or + isinstance(self.param, ParameterCrs)): + self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = CrsSelectionPanel('EPSG:4326') if self.param is not None: self.defaultTextBox.setAuthId(self.param.default) - self.horizontalLayoutParent.addWidget(self.defaultTextBox) - self.verticalLayout.addLayout(self.horizontalLayoutParent) + self.verticalLayout.addWidget(self.defaultTextBox) - self.horizontalLayoutRequired.addWidget(QLabel(self.tr('Required'))) - self.yesNoCombo = QComboBox() - self.yesNoCombo.addItem(self.tr('Yes')) - self.yesNoCombo.addItem(self.tr('No')) - self.horizontalLayoutRequired.addWidget(self.yesNoCombo) + self.verticalLayout.addSpacing(20) + self.requiredCheck = QCheckBox() + self.requiredCheck.setText(self.tr('Mandatory')) + self.requiredCheck.setChecked(True) if self.param is not None: - self.yesNoCombo.setCurrentIndex( - 1 if self.param.optional else 0) - self.verticalLayout.addLayout(self.horizontalLayoutRequired) + self.requiredCheck.setChecked(self.param.optional) + self.verticalLayout.addWidget(self.requiredCheck) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) @@ -270,6 +237,7 @@ def setupUi(self): self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) + self.verticalLayout.addStretch() self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) @@ -290,13 +258,11 @@ def okPressed(self): name = safeName.lower() + str(i) else: name = self.param.name - if self.paramType \ - == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \ - or isinstance(self.param, ParameterBoolean): - self.param = ParameterBoolean(name, description, - self.state.isChecked()) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD \ - or isinstance(self.param, ParameterTableField): + if (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN + or isinstance(self.param, ParameterBoolean)): + self.param = ParameterBoolean(name, description, self.state.isChecked()) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD + or isinstance(self.param, ParameterTableField)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) @@ -304,37 +270,41 @@ def okPressed(self): parent = self.parentCombo.itemData(self.parentCombo.currentIndex()) datatype = self.datatypeCombo.itemData(self.datatypeCombo.currentIndex()) self.param = ParameterTableField(name, description, parent, datatype) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \ - isinstance(self.param, ParameterRaster): + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or + isinstance(self.param, ParameterRaster)): self.param = ParameterRaster( - name, description, - self.yesNoCombo.currentIndex() == 1) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \ - isinstance(self.param, ParameterTable): + name, description) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or + isinstance(self.param, ParameterTable)): self.param = ParameterTable( - name, description, - self.yesNoCombo.currentIndex() == 1) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ - isinstance(self.param, ParameterVector): + name, description) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or + isinstance(self.param, ParameterVector)): self.param = ParameterVector( name, description, - [self.shapetypeCombo.currentIndex() - 1], - self.yesNoCombo.currentIndex() == 1) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ - isinstance(self.param, ParameterMultipleInput): + [self.shapetypeCombo.currentIndex() - 1]) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or + isinstance(self.param, ParameterMultipleInput)): self.param = ParameterMultipleInput( name, description, - self.datatypeCombo.currentIndex() - 1, - self.yesNoCombo.currentIndex() == 1) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ - isinstance(self.param, ParameterNumber): + self.datatypeCombo.currentIndex() - 1) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or + isinstance(self.param, ParameterNumber)): try: +<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe vmin = str(self.minTextBox.text()).strip() +======= + vmin = self.minTextBox.text().strip() +>>>>>>> [processing] UI improvement for defining model parameters if vmin == '': vmin = None else: vmin = float(vmin) +<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe vmax = str(self.maxTextBox.text()).strip() +======= + vmax = self.maxTextBox.text().strip() +>>>>>>> [processing] UI improvement for defining model parameters if vmax == '': vmax = None else: @@ -345,25 +315,39 @@ def okPressed(self): QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ - isinstance(self.param, ParameterString): + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or + isinstance(self.param, ParameterString)): self.param = ParameterString(name, description, +<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe str(self.defaultTextBox.text())) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \ isinstance(self.param, ParameterExtent): +======= + unicode(self.defaultTextBox.text())) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or + isinstance(self.param, ParameterExtent)): +>>>>>>> [processing] UI improvement for defining model parameters self.param = ParameterExtent(name, description) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ - isinstance(self.param, ParameterFile): + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or + isinstance(self.param, ParameterFile)): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = ParameterFile(name, description, isFolder=isFolder) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ - isinstance(self.param, ParameterPoint): + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or + isinstance(self.param, ParameterPoint)): self.param = ParameterPoint(name, description, +<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe str(self.defaultTextBox.text())) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or \ isinstance(self.param, ParameterCrs): self.param = ParameterCrs(name, description, self.defaultTextBox.getValue(), self.yesNoCombo.currentIndex() == 1) self.param.optional = self.yesNoCombo.currentIndex() == 1 +======= + unicode(self.defaultTextBox.text())) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or + isinstance(self.param, ParameterCrs)): + self.param = ParameterCrs(name, description, self.defaultTextbox.getValue()) + self.param.optional = self.requiredCheck.isChecked() +>>>>>>> [processing] UI improvement for defining model parameters self.close() def cancelPressed(self): From 56225c4d8cf46676fbf4ce1f1a88ee7538bfc945 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 16 Sep 2016 14:32:00 +0200 Subject: [PATCH 140/897] [processing] fixed batch processing interface Conflicts: python/plugins/processing/gui/BatchAlgorithmDialog.py --- .../processing/gui/BatchAlgorithmDialog.py | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/gui/BatchAlgorithmDialog.py b/python/plugins/processing/gui/BatchAlgorithmDialog.py index dfda489b6c74..e2de360a1214 100644 --- a/python/plugins/processing/gui/BatchAlgorithmDialog.py +++ b/python/plugins/processing/gui/BatchAlgorithmDialog.py @@ -27,9 +27,11 @@ __revision__ = '$Format:%H$' from qgis.PyQt.QtWidgets import QApplication, QMessageBox -from qgis.PyQt.QtGui import QCursor +from qgis.PyQt.QtGui import QCursor, QSizePolicy from qgis.PyQt.QtCore import Qt +from qgis.gui import QgsMessageBar + from processing.gui.BatchPanel import BatchPanel from processing.gui.AlgorithmDialogBase import AlgorithmDialogBase from processing.gui.AlgorithmExecutor import runalg @@ -60,6 +62,10 @@ def __init__(self, alg): self.textShortHelp.setVisible(False) + self.bar = QgsMessageBar() + self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) + self.layout().insertWidget(0, self.bar) + def accept(self): self.algs = [] self.load = [] @@ -71,10 +77,11 @@ def accept(self): for param in alg.parameters: if param.hidden: continue - widget = self.mainWidget.tblParameters.cellWidget(row, col) - if not self.mainWidget.setParamValue(param, widget, alg): - self.lblProgress.setText( - self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) + wrapper = self.mainWidget.wrappers[row][col] + if not self.mainWidget.setParamValue(param, wrapper, alg): + self.bar.pushMessage("", self.tr('Wrong or missing parameter value: %s (row %d)') + % (param.description, row + 1), + level=QgsMessageBar.WARNING, duration=5) self.algs = None return col += 1 @@ -88,8 +95,9 @@ def accept(self): out.value = text col += 1 else: - self.lblProgress.setText( - self.tr('Wrong or missing parameter value: %s (row %d)') % (out.description, row + 1)) + self.bar.pushMessage("", self.tr('Wrong or missing output value: %s (row %d)') + % (out.description, row + 1), + level=QgsMessageBar.WARNING, duration=5) self.algs = None return From 5464c4501b214ca2da0911967c92bd21e67226b8 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 16 Sep 2016 14:32:30 +0200 Subject: [PATCH 141/897] [processing] use QgsMessage bar in algorithm dialogs --- .../plugins/processing/gui/AlgorithmDialog.py | 17 ++++++++++------- python/plugins/processing/gui/BatchPanel.py | 17 ++++++++++------- .../PreconfiguredAlgorithmDialog.py | 7 +++++-- 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 4a6f640cb25b..8d6eb3e1ddf3 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -29,9 +29,10 @@ from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtWidgets import QMessageBox, QApplication, QPushButton, QWidget, QVBoxLayout -from qgis.PyQt.QtGui import QCursor, QColor, QPalette +from qgis.PyQt.QtGui import QCursor, QColor, QPalette, QSizePolicy from qgis.core import QgsMapLayerRegistry +from qgis.gui import QgsMessageBar from processing.core.ProcessingLog import ProcessingLog from processing.core.ProcessingConfig import ProcessingConfig @@ -71,6 +72,10 @@ def __init__(self, alg): self.setMainWidget(ParametersPanel(self, alg)) + self.bar = QgsMessageBar() + self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) + self.layout().insertWidget(0, self.bar) + self.cornerWidget = QWidget() layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 5) @@ -179,13 +184,11 @@ def accept(self): palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) - self.lblProgress.setText( - self.tr('Missing parameter value: %s') % e.parameter.description) - return except: - QMessageBox.critical(self, - self.tr('Unable to execute algorithm'), - self.tr('Wrong or missing parameter values')) + pass + self.bar.clearWidgets() + self.bar.pushMessage("", "Wrong or missing parameter value: %s" % e.parameter.description, + level=QgsMessageBar.WARNING, duration=5) def finish(self): keepOpen = ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN) diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index 0968cfb85315..d750f4968239 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -35,6 +35,7 @@ from qgis.PyQt.QtWidgets import QTableWidgetItem, QComboBox, QLineEdit, QHeaderView, QFileDialog, QMessageBox from qgis.core import QgsApplication +from qgis.gui import QgsMessageBar from processing.gui.BatchOutputSelectionPanel import BatchOutputSelectionPanel from processing.gui.GeometryPredicateSelectionPanel import GeometryPredicateSelectionPanel @@ -88,8 +89,8 @@ def __init__(self, parent, alg): self.fillParameterValues) self.initWidgets() - - + + def layerRegistryChanged(self): pass @@ -192,8 +193,9 @@ def save(self): continue wrapper = self.wrappers[row][col] if not self.setParamValue(param, wrapper, alg): - self.parent.lblProgress.setText( - self.tr('Missing parameter value: %s (row %d)') % (param.description, row + 1)) + self.parent.bar.pushMessage("", self.tr('Wrong or missing parameter value: %s (row %d)') + % (param.description, row + 1), + level=QgsMessageBar.WARNING, duration=5) return algParams[param.name] = param.getValueAsCommandLineParameter() col += 1 @@ -206,8 +208,9 @@ def save(self): algOutputs[out.name] = text.strip() col += 1 else: - self.parent.lblProgress.setText( - self.tr('Wrong or missing parameter value: %s (row %d)') % (out.description, row + 1)) + self.parent.bar.pushMessage("", self.tr('Wrong or missing output value: %s (row %d)') + % (out.description, row + 1), + level=QgsMessageBar.WARNING, duration=5) return toSave.append({self.PARAMETERS: algParams, self.OUTPUTS: algOutputs}) @@ -267,7 +270,7 @@ def fillParameterValues(self, column): wrapper = self.wrappers[0][column] for row in range(1, self.tblParameters.rowCount()): self.wrappers[row][column].setValue(wrapper.value()) - + def toggleAdvancedMode(self, checked): for column, param in enumerate(self.alg.parameters): if param.isAdvanced: diff --git a/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py b/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py index 7556bfd80521..f60b3f3782fa 100644 --- a/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py +++ b/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py @@ -38,6 +38,8 @@ from qgis.PyQt.QtWidgets import QMessageBox, QVBoxLayout, QLabel, QLineEdit, QWidget from qgis.PyQt.QtGui import QPalette, QColor +from qgis.gui import QgsMessageBar + class PreconfiguredAlgorithmDialog(AlgorithmDialog): @@ -77,8 +79,9 @@ def accept(self): palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) - self.lblProgress.setText( - self.tr('Missing parameter value: %s') % e.parameter.description) + self.parent.bar.pushMessage("", self.tr('Missing parameter value: %s') + % e.parameter.description, + level=QgsMessageBar.WARNING, duration=5) return except: QMessageBox.critical(self, From 8ce93b102c47d5fcd988e860ac25db6ee94efd14 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 16 Sep 2016 12:02:38 +0200 Subject: [PATCH 142/897] [processing] removed unused imports --- python/plugins/processing/gui/AlgorithmDialog.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 8d6eb3e1ddf3..fe2944719ceb 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -43,21 +43,6 @@ from processing.gui.AlgorithmExecutor import runalg, runalgIterating from processing.gui.Postprocessing import handleAlgorithmResults -from processing.core.parameters import ParameterExtent -from processing.core.parameters import ParameterRaster -from processing.core.parameters import ParameterVector -from processing.core.parameters import ParameterTable -from processing.core.parameters import ParameterSelection -from processing.core.parameters import ParameterFixedTable -from processing.core.parameters import ParameterRange -from processing.core.parameters import ParameterTableField -from processing.core.parameters import ParameterMultipleInput -from processing.core.parameters import ParameterString -from processing.core.parameters import ParameterNumber -from processing.core.parameters import ParameterFile -from processing.core.parameters import ParameterPoint -from processing.core.parameters import ParameterGeometryPredicate - from processing.core.outputs import OutputRaster from processing.core.outputs import OutputVector from processing.core.outputs import OutputTable From 36abbc427ce63f08e8193a9a490fcba203b18783 Mon Sep 17 00:00:00 2001 From: volaya Date: Fri, 16 Sep 2016 12:04:12 +0200 Subject: [PATCH 143/897] [processing] allow multiple values in ParameterSelection --- python/plugins/processing/core/parameters.py | 39 +++++++-- python/plugins/processing/gui/wrappers.py | 87 +++++++++++--------- 2 files changed, 79 insertions(+), 47 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index d9c8337978d9..3936b8eaa160 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1052,8 +1052,9 @@ class ParameterSelection(Parameter): def __init__(self, name='', description='', options=[], default=None, isSource=False, - optional=False): + multiple=False, optional=False): Parameter.__init__(self, name, description, default, optional) + self.multiple = multiple isSource = parseBool(isSource) self.options = options if isSource: @@ -1077,19 +1078,34 @@ def __init__(self, name='', description='', options=[], default=None, isSource=F self.default = 0 self.value = self.default - def setValue(self, n): - if n is None: + def setValue(self, value): + if value is None: if not self.optional: return False self.value = 0 return True - try: - n = int(n) - self.value = n + if isinstance(value, list): + if not self.multiple: + return False + values = [] + for v in value: + try: + n = int(v) + values.append(n) + except: + return False + if not self.optional and len(values) == 0: + return False + self.value = values return True - except: - return False + else: + try: + n = int(value) + self.value = n + return True + except: + return False @classmethod def fromScriptCode(self, line): @@ -1101,6 +1117,13 @@ def fromScriptCode(self, line): elif definition.lower().strip().startswith('selection'): options = definition.strip()[len('selection '):].split(';') return ParameterSelection(name, descName, options, optional=isOptional) + elif definition.lower().strip().startswith('multipleselectionfromfile'): + options = definition.strip()[len('multipleselectionfromfile '):].split(';') + return ParameterSelection(name, descName, options, isSource=True, + multiple=True, optional=isOptional) + elif definition.lower().strip().startswith('multipleselection'): + options = definition.strip()[len('multipleselection '):].split(';') + return ParameterSelection(name, descName, options, multiple=True, optional=isOptional) class ParameterEvaluationException(Exception): diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 3605e61bc8cd..0e05052ee616 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -2,7 +2,7 @@ """ *************************************************************************** - BooleanWidget.py + wrappers.py --------------------- Date : May 2016 Copyright : (C) 2016 by Arnaud Morvan, Victor Olaya @@ -43,7 +43,7 @@ ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs) from processing.core.ProcessingConfig import ProcessingConfig from processing.gui.FileSelectionPanel import FileSelectionPanel -from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, +from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, OutputString, OutputTable, OutputExtent) from processing.tools import dataobjects from processing.gui.MultipleInputPanel import MultipleInputPanel @@ -122,13 +122,13 @@ def setComboValue(self, value): def value(self): pass - + def anotherParameterWidgetHasChanged(self, wrapper): pass - + def postInitialize(self, wrappers): pass - + def refresh(self): pass @@ -136,7 +136,7 @@ class BasicWidgetWrapper(WidgetWrapper): def createWidget(self): return QLineEdit() - + def setValue(self, value): self.widget.setText(value) @@ -200,7 +200,7 @@ def createWidget(self): for r in raster: widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(r), r) for v in vector: - widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(v), v) + widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(v), v) if not self.param.default: widget.setEditText(self.param.default) return widget @@ -226,7 +226,7 @@ def value(self): class ExtentWidgetWrapper(WidgetWrapper): USE_MIN_COVERING_EXTENT = "[Use min covering extent]" - + def createWidget(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): return ExtentSelectionPanel(self.dialog, self.param) @@ -247,7 +247,7 @@ def createWidget(self): if not self.param.default: widget.setEditText(self.param.default) return widget - + def setValue(self, value): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): self.widget.setExtentFromString(value) @@ -364,7 +364,7 @@ def value(self): return ParameterFixedTable.tableToString(table) else: return self.widget.table - + class MultipleInputWidgetWrapper(WidgetWrapper): @@ -404,7 +404,7 @@ def createWidget(self): else: options = [self.dialog.resolveValueDescription(opt) for opt in self._getOptions()] return MultipleInputPanel(options) - + def refresh(self): if self.param.datatype != dataobjects.TYPE_FILE: if self.param.datatype == dataobjects.TYPE_RASTER: @@ -461,7 +461,7 @@ def createWidget(self): def setValue(self, value): self.widget.setValue(value) - + def value(self): return self.widget.getValue() @@ -496,7 +496,7 @@ def refresh(self): self.widget.cmbText.addItem(self.NOT_SELECTED, None) for layer in layers: self.widget.cmbText.addItem(getExtendedLayerName(layer), layer) - + def setValue(self, value): if self.dialogType == DIALOG_STANDARD: pass # TODO @@ -519,17 +519,26 @@ def validator(v): class SelectionWidgetWrapper(WidgetWrapper): def createWidget(self): - widget = QComboBox() - widget.addItems(self.param.options) - if self.param.default: - widget.setCurrentIndex(self.param.default) - return widget + if self.param.multiple: + return MultipleInputPanel(options=self.param.options) + else: + widget = QComboBox() + widget.addItems(self.param.options) + if self.param.default: + widget.setCurrentIndex(self.param.default) + return widget def setValue(self, value): - self.widget.setCurrentIndex(int(value)) + if self.param.multiple: + self.widget.setSelectedItems(value) + else: + self.widget.setCurrentIndex(int(value)) def value(self): - return self.widget.currentIndex() + if self.param.multiple: + return self.widget.selectedoptions + else: + return self.widget.currentIndex() class VectorWidgetWrapper(WidgetWrapper): @@ -551,7 +560,7 @@ def createWidget(self): for layer in layers: widget.addItem(self.dialog.resolveValueDescription(layer), layer) return widget - + def _populate(self, widget): widget.clear() layers = dataobjects.getVectorLayers(self.param.datatype) @@ -562,10 +571,10 @@ def _populate(self, widget): widget.addItem(getExtendedLayerName(layer), layer) widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) widget.name = self.param.name - + def refresh(self): self._populate(self.widget) - + def setValue(self, value): if self.dialogType == DIALOG_STANDARD: pass # TODO @@ -719,8 +728,8 @@ def createWidget(self): if self.dialogType == DIALOG_STANDARD: return MultipleInputPanel(options=[]) else: - return QLineEdit() - else: + return QLineEdit() + else: if self.dialogType == DIALOG_STANDARD: widget = QComboBox() return widget @@ -746,13 +755,13 @@ def postInitialize(self, wrappers): fields = self.getFields(layer, wrapper.param.datatype) if self.param.multiple: self.widget.updateForOptions(fields) - else: + else: self.widget.clear() if self.param.optional: self.widget.addItem(self.tr(self.NOT_SET)) self.widget.addItems(fields) break - + def getFields(self, layer, datatype): fieldTypes = [] if datatype == ParameterTableField.DATA_TYPE_STRING: @@ -766,7 +775,7 @@ def getFields(self, layer, datatype): if not fieldTypes or field.type() in fieldTypes: fieldNames.add(unicode(field.name())) return sorted(list(fieldNames), cmp=locale.strcoll) - + def setValue(self, value): if self.param.multiple: if self.dialogType == DIALOG_STANDARD: @@ -778,7 +787,7 @@ def setValue(self, value): self.widget.setSelectedItems(selected) else: self.widget.setText(value) - else: + else: if self.dialogType == DIALOG_STANDARD: pass # TODO elif self.dialogType == DIALOG_BATCH: @@ -794,11 +803,11 @@ def value(self): elif self.dialogType == DIALOG_BATCH: return self.widget.text() else: - text = self.widget.text() + text = self.widget.text() if not bool(text) and not self.param.optional: raise InvalidParameterValue() return text - else: + else: if self.dialogType == DIALOG_STANDARD: if self.param.optional and self.widget.currentIndex() == 0: return None @@ -808,9 +817,9 @@ def value(self): else: def validator(v): return bool(v) or self.param.optional - return self.comboValue(validator) - - def anotherParameterWidgetHasChanged(self,wrapper): + return self.comboValue(validator) + + def anotherParameterWidgetHasChanged(self, wrapper): if wrapper.param.name == self.param.parent: layer = wrapper.value() if layer is not None: @@ -822,15 +831,15 @@ def anotherParameterWidgetHasChanged(self,wrapper): if self.param.optional: self.widget.addItem(self.tr(self.NOT_SET)) self.widget.addItems(fields) - + def GeometryPredicateWidgetWrapper(WidgetWrapper): - + def createWidget(self): return GeometryPredicateSelectionPanel() - + def setValue(self, value): self.widget.setValue(value) - + def value(self): - return self.widget.value() \ No newline at end of file + return self.widget.value() From c8f35fb4cebfdbb1426278e5f4e33a0063551f2f Mon Sep 17 00:00:00 2001 From: volaya Date: Sun, 18 Sep 2016 23:24:36 +0200 Subject: [PATCH 144/897] [processing] fixed typo in modeler/ModelerParameterDefinitionDialog.py --- .../processing/modeler/ModelerParameterDefinitionDialog.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 7b1ebcb734f7..52fe11c608fb 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -345,7 +345,7 @@ def okPressed(self): unicode(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or isinstance(self.param, ParameterCrs)): - self.param = ParameterCrs(name, description, self.defaultTextbox.getValue()) + self.param = ParameterCrs(name, description, self.defaultTextBox.getValue()) self.param.optional = self.requiredCheck.isChecked() >>>>>>> [processing] UI improvement for defining model parameters self.close() From c65cc920098e39cfb4838ab1fa8d336e1de8448d Mon Sep 17 00:00:00 2001 From: volaya Date: Sun, 18 Sep 2016 23:25:25 +0200 Subject: [PATCH 145/897] [processing] improved widgets for raster and vector layers in modeler --- python/plugins/processing/gui/wrappers.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 0e05052ee616..0b0a00ce5a6f 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -18,6 +18,7 @@ *************************************************************************** """ + __author__ = 'Arnaud Morvan' __date__ = 'May 2016' __copyright__ = '(C) 2016, Arnaud Morvan' @@ -28,6 +29,7 @@ import locale +import os from qgis.core import QgsCoordinateReferenceSystem from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit @@ -486,6 +488,8 @@ def createWidget(self): files = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) for f in files: widget.addItem(self.dialog.resolveValueDescription(f), f) + if self.param.optional: + widget.setEditText("") return widget def refresh(self): @@ -512,7 +516,10 @@ def value(self): return self.widget.getText() else: def validator(v): - return bool(v) or self.param.optional + if not bool(v): + return self.param.optional + else: + return os.path.exists(v) return self.comboValue(validator) @@ -555,10 +562,11 @@ def createWidget(self): else: widget = QComboBox() layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) - if self.param.optional: - widget.addItem(self.NOT_SELECTED, None) + widget.setEditable(True) for layer in layers: widget.addItem(self.dialog.resolveValueDescription(layer), layer) + if self.param.optional: + widget.setEditText("") return widget def _populate(self, widget): @@ -594,7 +602,10 @@ def value(self): return self.widget.getText() else: def validator(v): - return bool(v) or self.param.optional + if not bool(v): + return self.param.optional + else: + return os.path.exists(v) return self.comboValue(validator) class StringWidgetWrapper(WidgetWrapper): From a968fa3dea1222231f44e8ec5149c95318dc5fe0 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 09:11:43 +0200 Subject: [PATCH 146/897] [processing] use original filename when possible when exporting vector layer Conflicts: python/plugins/processing/tools/dataobjects.py --- python/plugins/processing/tools/dataobjects.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 82e5dafeb7db..2f66677302de 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -47,6 +47,7 @@ from processing.algs.gdal.GdalUtils import GdalUtils from processing.tools.system import (getTempFilenameInTempFolder, getTempFilename, + removeInvalidChars isWindows) ALL_TYPES = [-1] @@ -311,6 +312,13 @@ def exportVectorLayer(layer, supported=None): systemEncoding = settings.value('/UI/encoding', 'System') output = getTempFilename('shp') + basename = removeInvalidChars(os.path.basename(layer.source())) + if basename: + if not basename.endswith("shp"): + basename = basename + ".shp" + output = getTempFilenameInTempFolder(basename) + else: + output = getTempFilename("shp") provider = layer.dataProvider() useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) if useSelection and layer.selectedFeatureCount() != 0: From e6f9499716e5cb3f8766ca2d2c5256d8faaf46c9 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 09:12:32 +0200 Subject: [PATCH 147/897] [processing] improvements for modeler UI Do not show help tab if there is no help add "optional" tag for optional parameters --- .../plugins/processing/modeler/ModelerParametersDialog.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 07dce172fbdc..6c7297535d81 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -141,6 +141,8 @@ def setupUi(self): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') + if param.optional: + desc += self.tr(' [optional]') label = QLabel(desc) self.labels[param.name] = label @@ -213,12 +215,14 @@ def setupUi(self): else: html = self.tr('

                                                                                                                                                                                    Downloading algorithm help... Please wait.

                                                                                                                                                                                    ') self.txtHelp.setHtml(html) + self.tabWidget.addTab(self.txtHelp, 'Help') self.reply = QgsNetworkAccessManager.instance().get(QNetworkRequest(algHelp)) self.reply.finished.connect(self.requestFinished) except: - self.txtHelp.setHtml(self.tr('

                                                                                                                                                                                    No help available for this algorithm

                                                                                                                                                                                    ')) + pass + + - self.tabWidget.addTab(self.txtHelp, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) From ae0e9c8442e864742dcf2e39e1b10de69afe7e49 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 09:14:08 +0200 Subject: [PATCH 148/897] [processing]minor code cleaning Conflicts: python/plugins/processing/core/parameters.py --- python/plugins/processing/gui/ParametersPanel.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index 06b02fe658a5..fc042574aedd 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -37,7 +37,7 @@ from qgis.PyQt import uic from qgis.PyQt.QtCore import QCoreApplication, QVariant -from qgis.PyQt.QtWidgets import (QWidget, QLayout, QVBoxLayout, QHBoxLayout, QToolButton, +from qgis.PyQt.QtWidgets import (QWidget, QLayout, QVBoxLayout, QHBoxLayout, QToolButton, QLabel, QCheckBox, QComboBox, QLineEdit, QPlainTextEdit) from qgis.PyQt.QtGui import QIcon @@ -97,11 +97,8 @@ def initWidgets(self): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr(' (x, y)') - try: - if param.optional: - desc += self.tr(' [optional]') - except: - pass + if param.optional: + desc += self.tr(' [optional]') wrapper = self.getWidgetWrapperFromParameter(param) self.wrappers[param.name] = wrapper From affc8f7ca5639545cde28b20e15bea6cf37b4240 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 09:15:07 +0200 Subject: [PATCH 149/897] [processing] correctly return widget in TableFieldWidgetWrapper --- python/plugins/processing/gui/wrappers.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 0b0a00ce5a6f..6ce666438aad 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -745,9 +745,10 @@ def createWidget(self): widget = QComboBox() return widget elif self.dialogType == DIALOG_BATCH: - item = QLineEdit() - if self.param.default is not None: - item.setText(self.param.default) + widget = QLineEdit() + if self.param.default: + widget.setText(self.param.default) + return widget else: widget = QComboBox() widget.setEditable(True) From a38c13d523c8aa7fc70fb0970a73af18fe8fa216 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sat, 17 Sep 2016 23:33:42 +0200 Subject: [PATCH 150/897] Create FieldMappingWrapper --- .../processing/algs/qgis/FieldsMapper.py | 8 - .../processing/algs/qgis/fieldsmapping.py | 4 + .../algs/qgis/ui/FieldsMapperDialogs.py | 143 ------------------ .../algs/qgis/ui/FieldsMappingPanel.py | 39 ++++- 4 files changed, 40 insertions(+), 154 deletions(-) delete mode 100644 python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py diff --git a/python/plugins/processing/algs/qgis/FieldsMapper.py b/python/plugins/processing/algs/qgis/FieldsMapper.py index 609e292a181a..3f74bcac4188 100644 --- a/python/plugins/processing/algs/qgis/FieldsMapper.py +++ b/python/plugins/processing/algs/qgis/FieldsMapper.py @@ -37,8 +37,6 @@ from processing.tools import dataobjects, vector from .fieldsmapping import ParameterFieldsMapping -from .ui.FieldsMapperDialogs import (FieldsMapperParametersDialog, - FieldsMapperModelerParametersDialog) class FieldsMapper(GeoAlgorithm): @@ -151,9 +149,3 @@ def processAlgorithm(self, progress): raise GeoAlgorithmExecutionException( self.tr('An error occurred while evaluating the calculation' ' string:\n') + error) - - def getCustomParametersDialog(self): - return FieldsMapperParametersDialog(self) - - def getCustomModelerParametersDialog(self, modelAlg, algName=None): - return FieldsMapperModelerParametersDialog(self, modelAlg, algName) diff --git a/python/plugins/processing/algs/qgis/fieldsmapping.py b/python/plugins/processing/algs/qgis/fieldsmapping.py index e85ec663c596..12f4750a4402 100644 --- a/python/plugins/processing/algs/qgis/fieldsmapping.py +++ b/python/plugins/processing/algs/qgis/fieldsmapping.py @@ -33,6 +33,10 @@ class ParameterFieldsMapping(Parameter): + default_metadata = { + 'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper' + } + def __init__(self, name='', description='', parent=None): Parameter.__init__(self, name, description) self.parent = parent diff --git a/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py b/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py deleted file mode 100644 index c90f46bec1ef..000000000000 --- a/python/plugins/processing/algs/qgis/ui/FieldsMapperDialogs.py +++ /dev/null @@ -1,143 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - FieldsMapper.py - --------------------- - Date : October 2014 - Copyright : (C) 2014 by Arnaud Morvan - Email : arnaud dot morvan at camptocamp dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" -from builtins import str - -__author__ = 'Arnaud Morvan' -__date__ = 'October 2014' -__copyright__ = '(C) 2014, Arnaud Morvan' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - - -from qgis.PyQt.QtWidgets import QComboBox, QSpacerItem - -from processing.core.parameters import ParameterVector -from processing.tools import dataobjects -from processing.gui.ParametersPanel import ParametersPanel -from processing.gui.AlgorithmDialog import AlgorithmDialog, AlgorithmDialogBase -from processing.modeler.ModelerParametersDialog import ModelerParametersDialog - -from processing.algs.qgis.fieldsmapping import ParameterFieldsMapping -from .FieldsMappingPanel import FieldsMappingPanel - - -class FieldsMapperParametersPanel(ParametersPanel): - - def __init__(self, parent, alg): - ParametersPanel.__init__(self, parent, alg) - - item = self.layoutMain.itemAt(self.layoutMain.count() - 1) - if isinstance(item, QSpacerItem): - self.layoutMain.removeItem(item) - item = None - - def getWidgetFromParameter(self, param): - if isinstance(param, ParameterFieldsMapping): - item = FieldsMappingPanel() - if param.parent in self.dependentItems: - items = self.dependentItems[param.parent] - else: - items = [] - self.dependentItems[param.parent] = items - items.append(param) - - parent = self.alg.getParameterFromName(param.parent) - if isinstance(parent, ParameterVector): - layers = dataobjects.getVectorLayers(parent.shapetype) - else: - layers = dataobjects.getTables() - if len(layers) > 0: - item.setLayer(layers[0]) - return item - return ParametersPanel.getWidgetFromParameter(self, param) - - def updateDependentFields(self): - sender = self.sender() - if not isinstance(sender, QComboBox): - return - if sender.name not in self.dependentItems: - return - layer = sender.itemData(sender.currentIndex()) - children = self.dependentItems[sender.name] - for child in children: - widget = self.valueItems[child.name] - if isinstance(widget, FieldsMappingPanel): - widget.setLayer(layer) - ParametersPanel.updateDependentFields(self) - - def somethingDependsOnThisParameter(self, parent): - for param in self.alg.parameters: - if isinstance(param, ParameterFieldsMapping): - if param.parent == parent.name: - return True - return ParametersPanel.somethingDependsOnThisParameter(self, parent) - - -class FieldsMapperParametersDialog(AlgorithmDialog): - - def __init__(self, alg): - AlgorithmDialogBase.__init__(self, alg) - - self.alg = alg - - self.setMainWidget(FieldsMapperParametersPanel(self, alg)) - - def setParamValue(self, param, widget, alg=None): - if isinstance(param, ParameterFieldsMapping): - return param.setValue(widget.value()) - return AlgorithmDialog.setParamValue(self, param, widget, alg) - - -class FieldsMapperModelerParametersDialog(ModelerParametersDialog): - - def __init__(self, alg, model, algName=None): - ModelerParametersDialog.__init__(self, alg, model, algName) - - paramsLayout = self.paramPanel.layout() - item = paramsLayout.itemAt(paramsLayout.count() - 1) - if isinstance(item, QSpacerItem): - paramsLayout.removeItem(item) - item = None - - def getWidgetFromParameter(self, param): - if isinstance(param, ParameterFieldsMapping): - return FieldsMappingPanel() - return ModelerParametersDialog.getWidgetFromParameter(self, param) - - def setPreviousValues(self): - ModelerParametersDialog.setPreviousValues(self) - if self._algName is not None: - alg = self.model.algs[self._algName] - for param in alg.algorithm.parameters: - if isinstance(param, ParameterFieldsMapping): - widget = self.valueItems[param.name] - value = alg.params[param.name] - if isinstance(value, str): - # convert to list because of ModelerAlgorithme.resolveValue behavior with lists - value = eval(value) - widget.setValue(value) - - def setParamValue(self, alg, param, widget): - if isinstance(param, ParameterFieldsMapping): - # convert to unicode because of ModelerAlgorithme.resolveValue behavior with lists - alg.params[param.name] = str(widget.value()) - return True - return ModelerParametersDialog.setParamValue(self, alg, param, widget) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py index 6e24d1f1cb8c..02cb595c1adf 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py @@ -31,13 +31,14 @@ from collections import OrderedDict from qgis.PyQt import uic -from qgis.PyQt.QtGui import QBrush, QIcon +from qgis.PyQt.QtGui import QBrush, QIcon, QSpacerItem from qgis.PyQt.QtWidgets import QComboBox, QHeaderView, QLineEdit, QMessageBox, QSpinBox, QStyledItemDelegate from qgis.PyQt.QtCore import QItemSelectionModel, QAbstractTableModel, QModelIndex, QVariant, Qt, pyqtSlot -from qgis.core import QgsExpression, QgsExpressionContextUtils, QgsApplication +from qgis.core import QgsExpression, QgsExpressionContextUtils, QgsApplication, QgsFeature from qgis.gui import QgsFieldExpressionWidget +from processing.gui.wrappers import WidgetWrapper, DIALOG_STANDARD, DIALOG_MODELER from processing.tools import dataobjects pluginPath = os.path.dirname(__file__) @@ -93,7 +94,7 @@ def testExpression(self, row): if self._layer is None: return context = QgsExpressionContextUtils.createFeatureBasedContext(QgsFeature(), self._layer.fields()) - for feature in dp.getFeatures(): + for feature in self._layer.getFeatures(): context.setFeature(feature) expression.evaluate(context) if expression.hasEvalError(): @@ -473,3 +474,35 @@ def on_loadLayerFieldsButton_clicked(self, checked=False): if layer is None: return self.model.loadLayerFields(layer) + + +class FieldsMappingWidgetWrapper(WidgetWrapper): + + def createWidget(self): + return FieldsMappingPanel() + + def postInitialize(self, wrappers): + for wrapper in wrappers: + if wrapper.param.name == self.param.parent: + wrapper.widgetValueHasChanged.connect(self.parentLayerChanged) + break + layers = dataobjects.getTables() + if len(layers) > 0: + # as first item in combobox is already selected + self.widget.setLayer(layers[0]) + + # remove exiting spacers to get FieldsMappingPanel fully expanded + if self.dialogType in (DIALOG_STANDARD, DIALOG_MODELER): + layout = self.widget.parent().layout() + spacer = layout.itemAt(layout.count() - 1) + if isinstance(spacer, QSpacerItem): + layout.removeItem(spacer) + + def parentLayerChanged(self): + self.widget.setLayer(self.sender().value()) + + def setValue(self, value): + self.widget.setValue(value) + + def value(self): + return self.widget.value() From 8d16161742a9cd2d90940884237fe78d12e16701 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 18 Sep 2016 12:56:24 +0200 Subject: [PATCH 151/897] Call postInitialise in modeler Dialog --- python/plugins/processing/modeler/ModelerParametersDialog.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 6c7297535d81..746d056e930e 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -185,9 +185,7 @@ def setupUi(self): self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) - self.verticalLayout.addStretch(1000) - self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) @@ -231,6 +229,9 @@ def setupUi(self): self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) + for wrapper in self.wrappers.values(): + wrapper.postInitialize(self.wrappers.values()) + def requestFinished(self): """Change the webview HTML content""" reply = self.sender() From c1bc364a76cbc88b754a36b9d3a03020a0f5c57b Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 18 Sep 2016 13:24:38 +0200 Subject: [PATCH 152/897] Fix PointWidgetWrapper with modeler --- python/plugins/processing/gui/wrappers.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 6ce666438aad..83343aee4267 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -293,6 +293,7 @@ def createWidget(self): for p in points: item.addItem(self.dialog.resolveValueDescription(p), p) item.setEditText(unicode(self.param.default)) + return item def setValue(self, value): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): From 9e36582febdce3e95ba5e8cad15208dd4549f0c2 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 18 Sep 2016 16:07:32 +0200 Subject: [PATCH 153/897] Simplify TableFieldWidgetWrapper Conflicts: python/plugins/processing/gui/ParametersPanel.py python/plugins/processing/gui/wrappers.py --- .../plugins/processing/gui/ParametersPanel.py | 8 +- python/plugins/processing/gui/wrappers.py | 102 ++++++++---------- 2 files changed, 48 insertions(+), 62 deletions(-) diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index fc042574aedd..f958ce28d6cf 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -165,10 +165,4 @@ def buttonToggled(self, value): button.setChecked(False) def getWidgetWrapperFromParameter(self, param): - wrapper = param.wrapper(self.parent) - wrapper.widgetValueHasChanged.connect(self.widgetValueHasChanged) - return wrapper - - def widgetValueHasChanged(self, wrapper): - for wrapper in self.wrappers.values(): - wrapper.anotherParameterWidgetHasChanged(wrapper) + return param.wrapper(self.parent) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 83343aee4267..6fb9f6058f6e 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -31,7 +31,7 @@ import locale import os -from qgis.core import QgsCoordinateReferenceSystem +from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant @@ -42,7 +42,7 @@ from processing.gui.PointSelectionPanel import PointSelectionPanel from processing.core.parameters import (ParameterBoolean, ParameterPoint, ParameterFile, ParameterRaster, ParameterVector, ParameterNumber, ParameterString, ParameterTable, - ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs) + ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs, _resolveLayers) from processing.core.ProcessingConfig import ProcessingConfig from processing.gui.FileSelectionPanel import FileSelectionPanel from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, @@ -97,8 +97,7 @@ def comboValue(self, validator=None): if validator is not None and not validator(v): raise InvalidParameterValue() return v - else: - return self.widget.itemData(self.widget.currentIndex()) + return self.widget.itemData(self.widget.currentIndex()) def createWidget(self): pass @@ -125,9 +124,6 @@ def setComboValue(self, value): def value(self): pass - def anotherParameterWidgetHasChanged(self, wrapper): - pass - def postInitialize(self, wrappers): pass @@ -403,7 +399,9 @@ def createWidget(self): opts = [getExtendedLayerName(opt) for opt in options] return MultipleInputPanel(opts) elif self.dialogType == DIALOG_BATCH: - return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + widget.textChanged + return widget else: options = [self.dialog.resolveValueDescription(opt) for opt in self._getOptions()] return MultipleInputPanel(options) @@ -557,9 +555,12 @@ def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QComboBox() self._populate(widget) + widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: - return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + return widget else: widget = QComboBox() layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) @@ -578,7 +579,6 @@ def _populate(self, widget): widget.addItem(self.NOT_SELECTED, None) for layer in layers: widget.addItem(getExtendedLayerName(layer), layer) - widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) widget.name = self.param.name def refresh(self): @@ -588,11 +588,10 @@ def setValue(self, value): if self.dialogType == DIALOG_STANDARD: pass # TODO elif self.dialogType == DIALOG_BATCH: - self.widget.setText(value) + self.widget.setValue(value) else: self.setComboValue(value) - def value(self): if self.dialogType == DIALOG_STANDARD: try: @@ -600,7 +599,7 @@ def value(self): except: return self.widget.getValue() elif self.dialogType == DIALOG_BATCH: - return self.widget.getText() + return self.widget.value() else: def validator(v): if not bool(v): @@ -736,19 +735,18 @@ class TableFieldWidgetWrapper(WidgetWrapper): NOT_SET = '[Not set]' def createWidget(self): + self._layer = None + if self.param.multiple: if self.dialogType == DIALOG_STANDARD: - return MultipleInputPanel(options=[]) + return MultipleInputPanel(options=[]) else: return QLineEdit() else: - if self.dialogType == DIALOG_STANDARD: + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): widget = QComboBox() - return widget - elif self.dialogType == DIALOG_BATCH: - widget = QLineEdit() - if self.param.default: - widget.setText(self.param.default) + if self.dialogType == DIALOG_BATCH: + widget.setEditable(True) # Should be removed at the end return widget else: widget = QComboBox() @@ -763,28 +761,42 @@ def createWidget(self): def postInitialize(self, wrappers): for wrapper in wrappers: if wrapper.param.name == self.param.parent: - layer = wrapper.widget.itemData(wrapper.widget.currentIndex()) - if layer is not None: - fields = self.getFields(layer, wrapper.param.datatype) - if self.param.multiple: - self.widget.updateForOptions(fields) - else: - self.widget.clear() - if self.param.optional: - self.widget.addItem(self.tr(self.NOT_SET)) - self.widget.addItems(fields) + # self.refreshItems() + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.setLayer(wrapper.value()) + wrapper.widgetValueHasChanged.connect(self.parentValueChanged) break - def getFields(self, layer, datatype): + def parentValueChanged(self, wrapper): + self.setLayer(wrapper.value()) + + def setLayer(self, layer): + if isinstance(layer, basestring): + layer = dataobjects.getObjectFromUri(_resolveLayers(layer)) + self._layer = layer + self.refreshItems() + + def refreshItems(self): + if self.param.multiple: + self.widget.updateForOptions(self.getFields()) + else: + self.widget.clear() + if self.param.optional: + self.widget.addItem(self.tr(self.NOT_SET)) + self.widget.addItems(self.getFields()) + + def getFields(self): + if self._layer is None: + return [] fieldTypes = [] - if datatype == ParameterTableField.DATA_TYPE_STRING: + if self.param.datatype == ParameterTableField.DATA_TYPE_STRING: fieldTypes = [QVariant.String] - elif datatype == ParameterTableField.DATA_TYPE_NUMBER: + elif self.param.datatype == ParameterTableField.DATA_TYPE_NUMBER: fieldTypes = [QVariant.Int, QVariant.Double, QVariant.LongLong, QVariant.UInt, QVariant.ULongLong] fieldNames = set() - for field in layer.fields(): + for field in self._layer.fields(): if not fieldTypes or field.type() in fieldTypes: fieldNames.add(unicode(field.name())) return sorted(list(fieldNames), cmp=locale.strcoll) @@ -802,13 +814,8 @@ def setValue(self, value): self.widget.setText(value) else: if self.dialogType == DIALOG_STANDARD: - pass # TODO - elif self.dialogType == DIALOG_BATCH: - return self.widget.setText(value) - else: self.setComboValue(value) - def value(self): if self.param.multiple: if self.dialogType == DIALOG_STANDARD: @@ -821,30 +828,15 @@ def value(self): raise InvalidParameterValue() return text else: - if self.dialogType == DIALOG_STANDARD: + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): if self.param.optional and self.widget.currentIndex() == 0: return None return self.widget.currentText() - elif self.dialogType == DIALOG_BATCH: - return self.widget.text() else: def validator(v): return bool(v) or self.param.optional return self.comboValue(validator) - def anotherParameterWidgetHasChanged(self, wrapper): - if wrapper.param.name == self.param.parent: - layer = wrapper.value() - if layer is not None: - fields = self.getFields(layer, wrapper.param.datatype) - if self.param.multiple: - self.widget.updateForOptions(fields) - else: - self.widget.clear() - if self.param.optional: - self.widget.addItem(self.tr(self.NOT_SET)) - self.widget.addItems(fields) - def GeometryPredicateWidgetWrapper(WidgetWrapper): From be5f951cd111d1b3c2d1496bbfb43bb7c3dc076a Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 18 Sep 2016 16:09:30 +0200 Subject: [PATCH 154/897] Support layer objects in BatchInputSelectionPanel --- .../gui/BatchInputSelectionPanel.py | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/python/plugins/processing/gui/BatchInputSelectionPanel.py b/python/plugins/processing/gui/BatchInputSelectionPanel.py index 735f2b14efbf..319a46f0393b 100644 --- a/python/plugins/processing/gui/BatchInputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchInputSelectionPanel.py @@ -29,10 +29,12 @@ import os -from qgis.PyQt.QtCore import QSettings +from qgis.PyQt.QtCore import QSettings, pyqtSignal from qgis.PyQt.QtWidgets import QWidget, QHBoxLayout, QMenu, QPushButton, QLineEdit, QSizePolicy, QAction, QFileDialog from qgis.PyQt.QtGui import QCursor +from qgis.core import QgsMapLayer + from processing.gui.MultipleInputDialog import MultipleInputDialog from processing.core.parameters import ParameterMultipleInput @@ -45,6 +47,8 @@ class BatchInputSelectionPanel(QWidget): + valueChanged = pyqtSignal() + def __init__(self, param, row, col, dialog): super(BatchInputSelectionPanel, self).__init__(None) self.param = param @@ -55,8 +59,10 @@ def __init__(self, param, row, col, dialog): self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() + self.text.setObjectName('text') self.text.setMinimumWidth(300) - self.text.setText('') + self.setValue('') + self.text.editingFinished.connect(self.on_text_EditingFinished) self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) @@ -67,7 +73,7 @@ def __init__(self, param, row, col, dialog): self.setLayout(self.horizontalLayout) def _panel(self): - return self.dialog.mainWidget() + return self.dialog.mainWidget def _table(self): return self._panel().tblParameters @@ -118,7 +124,7 @@ def showLayerSelectionDialog(self): self._panel().addRow() for i, layeridx in enumerate(selected): self._table().cellWidget(i + self.row, - self.col).setText(layers[layeridx].name()) + self.col).setValue(layers[layeridx]) def showFileSelectionDialog(self): settings = QSettings() @@ -151,10 +157,19 @@ def showFileSelectionDialog(self): self._panel().addRow() for i, f in enumerate(files): self._table().cellWidget(i + self.row, - self.col).setText(f) - - def setText(self, text): - return self.text.setText(text) - - def getText(self): - return self.text.text() + self.col).setValue(f) + + def on_text_EditingFinished(self): + self._value = self.text.text() + self.valueChanged.emit() + + def value(self): + return self._value + + def setValue(self, value): + self._value = value + if isinstance(value, QgsMapLayer): + self.text.setText(value.name()) + else: # should be basestring + self.text.setText(value) + self.valueChanged.emit() From c010a035c31360b6699217cd426dd98fdb8ea9ec Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 18 Sep 2016 16:11:34 +0200 Subject: [PATCH 155/897] Call postInitialise in BatchAlgorithmDialog --- python/plugins/processing/gui/BatchPanel.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index d750f4968239..d09b765c4116 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -235,6 +235,7 @@ def addRow(self): self.wrappers.append([None] * self.tblParameters.columnCount()) self.tblParameters.setRowCount(self.tblParameters.rowCount() + 1) + wrappers = {} row = self.tblParameters.rowCount() - 1 column = 0 for param in self.alg.parameters: @@ -242,6 +243,7 @@ def addRow(self): continue wrapper = param.wrapper(self.parent, row, column) + wrappers[param.name] = wrapper self.setCellWrapper(row, column, wrapper) column += 1 @@ -261,6 +263,9 @@ def addRow(self): item.setCurrentIndex(0) self.tblParameters.setCellWidget(row, column, item) + for wrapper in wrappers.values(): + wrapper.postInitialize(wrappers.values()) + def removeRows(self): if self.tblParameters.rowCount() > 2: self.wrappers.pop() From d33e33874a6490241e5aeb33a3bbf6e2a2511b47 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 18 Sep 2016 17:14:50 +0200 Subject: [PATCH 156/897] Fix StringWidgetWrapper.value method --- python/plugins/processing/gui/wrappers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 6fb9f6058f6e..3989211b86a3 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -657,7 +657,7 @@ def value(self): text = self.widget.getValue() return text if self.dialogType == DIALOG_BATCH: - text = self.widget.text() + return self.widget.text() else: if self.param.multiline: value = self.widget.getValue() From c605c67b8c452fd09cc45d1c87bcb542e55521c6 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 13:33:06 +0200 Subject: [PATCH 157/897] [processing] some minor changes for batch processing interface --- python/plugins/processing/gui/BatchInputSelectionPanel.py | 6 +++--- python/plugins/processing/gui/wrappers.py | 4 +--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/python/plugins/processing/gui/BatchInputSelectionPanel.py b/python/plugins/processing/gui/BatchInputSelectionPanel.py index 319a46f0393b..dedb974eca8b 100644 --- a/python/plugins/processing/gui/BatchInputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchInputSelectionPanel.py @@ -62,7 +62,7 @@ def __init__(self, param, row, col, dialog): self.text.setObjectName('text') self.text.setMinimumWidth(300) self.setValue('') - self.text.editingFinished.connect(self.on_text_EditingFinished) + self.text.editingFinished.connect(self.textEditingFinished) self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) @@ -159,7 +159,7 @@ def showFileSelectionDialog(self): self._table().cellWidget(i + self.row, self.col).setValue(f) - def on_text_EditingFinished(self): + def textEditingFinished(self): self._value = self.text.text() self.valueChanged.emit() @@ -170,6 +170,6 @@ def setValue(self, value): self._value = value if isinstance(value, QgsMapLayer): self.text.setText(value.name()) - else: # should be basestring + else: #  should be basestring self.text.setText(value) self.valueChanged.emit() diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 3989211b86a3..6d50eb49a7d7 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -399,9 +399,7 @@ def createWidget(self): opts = [getExtendedLayerName(opt) for opt in options] return MultipleInputPanel(opts) elif self.dialogType == DIALOG_BATCH: - widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) - widget.textChanged - return widget + return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: options = [self.dialog.resolveValueDescription(opt) for opt in self._getOptions()] return MultipleInputPanel(options) From a20c86c0c3fc82c063584bc1063832ddca704685 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 14:12:11 +0200 Subject: [PATCH 158/897] [processing] use InputLayerSelectorPanel for vector layers --- .../processing/gui/InputLayerSelectorPanel.py | 11 ++++++- python/plugins/processing/gui/wrappers.py | 32 ++++++++++++------- 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/python/plugins/processing/gui/InputLayerSelectorPanel.py b/python/plugins/processing/gui/InputLayerSelectorPanel.py index 95b25ed317f7..254bad199a48 100644 --- a/python/plugins/processing/gui/InputLayerSelectorPanel.py +++ b/python/plugins/processing/gui/InputLayerSelectorPanel.py @@ -29,7 +29,7 @@ import os from qgis.PyQt import uic -from qgis.PyQt.QtCore import QSettings +from qgis.PyQt.QtCore import QSettings, pyqtSignal from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtWidgets import QFileDialog from processing.tools import dataobjects @@ -41,6 +41,8 @@ class InputLayerSelectorPanel(BASE, WIDGET): + valueHasChanged = pyqtSignal() + def __init__(self, options, param): super(InputLayerSelectorPanel, self).__init__(None) self.setupUi(self) @@ -55,6 +57,7 @@ def __init__(self, options, param): self.cmbText.addItem(name, value) self.btnSelect.clicked.connect(self.showSelectionDialog) + self.cmbText.currentIndexChanged.connect(self.valueHasChanged.emit) def showSelectionDialog(self): settings = QSettings() @@ -77,5 +80,11 @@ def showSelectionDialog(self): self.cmbText.addItem(filename, filename) self.cmbText.setCurrentIndex(self.cmbText.count() - 1) + def update(self, options): + self.cmbText.clear() + for (name, value) in options: + self.cmbText.addItem(name, value) + self.valueHasChanged.emit() + def getValue(self): return self.cmbText.itemData(self.cmbText.currentIndex()) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 6d50eb49a7d7..f4e77755f8bf 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -490,13 +490,13 @@ def createWidget(self): return widget def refresh(self): - self.widget.cmbText.clear() - layers = dataobjects.getRasterLayers(self) - layers.sort(key=lambda lay: lay.name()) + items = [] + layers = dataobjects.getRasterLayers() if self.param.optional: - self.widget.cmbText.addItem(self.NOT_SELECTED, None) + items.append((self.NOT_SELECTED, None)) for layer in layers: - self.widget.cmbText.addItem(getExtendedLayerName(layer), layer) + items.append((getExtendedLayerName(layer), layer)) + self.widget.update(items) def setValue(self, value): if self.dialogType == DIALOG_STANDARD: @@ -551,9 +551,15 @@ class VectorWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType == DIALOG_STANDARD: - widget = QComboBox() - self._populate(widget) - widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + layers = dataobjects.getVectorLayers(self.param.datatype) + items = [] + if self.param.optional: + items.append((self.NOT_SELECTED, None)) + for layer in layers: + items.append((getExtendedLayerName(layer), layer)) + widget = InputLayerSelectorPanel(items, self.param) + widget.name = self.param.name + widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) @@ -570,14 +576,16 @@ def createWidget(self): return widget def _populate(self, widget): - widget.clear() + items = [] layers = dataobjects.getVectorLayers(self.param.datatype) layers.sort(key=lambda lay: lay.name()) if self.param.optional: - widget.addItem(self.NOT_SELECTED, None) + items.append((self.NOT_SELECTED, None)) for layer in layers: - widget.addItem(getExtendedLayerName(layer), layer) - widget.name = self.param.name + items.append((getExtendedLayerName(layer), layer)) + self.widget.update(items) + + def refresh(self): self._populate(self.widget) From 3407ced90e9c212a7a7b5dfe0bf60c99854df836 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 19 Sep 2016 11:52:31 +0300 Subject: [PATCH 159/897] fix indentation Conflicts: python/plugins/processing/gui/BatchInputSelectionPanel.py python/plugins/processing/gui/wrappers.py --- .../algs/gdal/GdalAlgorithmDialog.py | 3 +- .../processing/algs/grass/GrassAlgorithm.py | 4 +- .../processing/algs/qgis/DeleteColumn.py | 2 +- .../plugins/processing/algs/qgis/Dissolve.py | 2 +- .../plugins/processing/algs/r/RAlgorithm.py | 1 - .../plugins/processing/core/GeoAlgorithm.py | 5 +- python/plugins/processing/core/outputs.py | 23 ++-- python/plugins/processing/core/parameters.py | 109 +++++++++--------- .../plugins/processing/gui/AlgorithmDialog.py | 1 - .../processing/gui/AlgorithmDialogBase.py | 1 - .../processing/gui/BatchAlgorithmDialog.py | 4 +- .../gui/BatchInputSelectionPanel.py | 6 +- python/plugins/processing/gui/BatchPanel.py | 5 +- .../processing/gui/ExtentSelectionPanel.py | 1 - .../processing/gui/NumberInputPanel.py | 9 +- .../processing/gui/OutputSelectionPanel.py | 2 +- .../processing/gui/StringInputPanel.py | 1 - python/plugins/processing/gui/wrappers.py | 30 +++-- .../processing/modeler/ModelerAlgorithm.py | 7 +- .../processing/modeler/ModelerDialog.py | 4 +- .../modeler/ModelerParametersDialog.py | 3 - .../PreconfiguredAlgorithmDialog.py | 4 +- 22 files changed, 114 insertions(+), 113 deletions(-) diff --git a/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py b/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py index e0180754dfe8..a3093d76c77c 100644 --- a/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py +++ b/python/plugins/processing/algs/gdal/GdalAlgorithmDialog.py @@ -40,7 +40,7 @@ def __init__(self, alg): AlgorithmDialogBase.__init__(self, alg) self.alg = alg - + self.setMainWidget(GdalParametersPanel(self, alg)) cornerWidget = QWidget() @@ -55,6 +55,7 @@ def __init__(self, alg): self.mainWidget.parametersHaveChanged() + class GdalParametersPanel(ParametersPanel): def __init__(self, parent, alg): diff --git a/python/plugins/processing/algs/grass/GrassAlgorithm.py b/python/plugins/processing/algs/grass/GrassAlgorithm.py index a4911fc59244..54a672838574 100644 --- a/python/plugins/processing/algs/grass/GrassAlgorithm.py +++ b/python/plugins/processing/algs/grass/GrassAlgorithm.py @@ -166,11 +166,11 @@ def defineCharacteristicsFromFile(self): " (raw output)", "txt")) line = lines.readline().strip('\n').strip() except Exception as e: - + ProcessingLog.addToLog( ProcessingLog.LOG_ERROR, traceback.format_exc()) - #self.tr('Could not open GRASS algorithm: %s.\n%s' % (self.descriptionFile, line))) + #self.tr('Could not open GRASS algorithm: %s.\n%s' % (self.descriptionFile, line))) raise e lines.close() diff --git a/python/plugins/processing/algs/qgis/DeleteColumn.py b/python/plugins/processing/algs/qgis/DeleteColumn.py index 8a4cc4be41a8..484f0d032d94 100644 --- a/python/plugins/processing/algs/qgis/DeleteColumn.py +++ b/python/plugins/processing/algs/qgis/DeleteColumn.py @@ -51,7 +51,7 @@ def defineCharacteristics(self): def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) - + toDelete = self.getParameterValue(self.COLUMNS) fields = layer.fields() idxs = [] diff --git a/python/plugins/processing/algs/qgis/Dissolve.py b/python/plugins/processing/algs/qgis/Dissolve.py index a70a20add6ed..161ceabb1b91 100644 --- a/python/plugins/processing/algs/qgis/Dissolve.py +++ b/python/plugins/processing/algs/qgis/Dissolve.py @@ -63,7 +63,7 @@ def defineCharacteristics(self): self.addParameter(ParameterBoolean(Dissolve.DISSOLVE_ALL, self.tr('Dissolve all (do not use fields)'), True)) self.addParameter(ParameterTableField(Dissolve.FIELD, - self.tr('Unique ID fields'), Dissolve.INPUT, optional=True, multiple=True)) + self.tr('Unique ID fields'), Dissolve.INPUT, optional=True, multiple=True)) self.addOutput(OutputVector(Dissolve.OUTPUT, self.tr('Dissolved'))) def processAlgorithm(self, progress): diff --git a/python/plugins/processing/algs/r/RAlgorithm.py b/python/plugins/processing/algs/r/RAlgorithm.py index 43636ac1f735..114608005f1f 100644 --- a/python/plugins/processing/algs/r/RAlgorithm.py +++ b/python/plugins/processing/algs/r/RAlgorithm.py @@ -187,7 +187,6 @@ def processParameterLine(self, line): raise WrongScriptException( self.tr('Could not load R script: %s.\n Problem with line %s' % (self.descriptionFile, line))) - def processAlgorithm(self, progress): if isWindows(): path = RUtils.RFolder() diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index 9162331fd0f6..a1b39766c92b 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -73,7 +73,6 @@ def __init__(self): self.showInToolbox = True self.showInModeler = True - # False if it should not be run a a batch process self.canRunInBatchMode = True @@ -333,7 +332,7 @@ def evaluateParameterValues(self): except ValueError, e: traceback.print_exc() raise GeoAlgorithmExecutionException(str(e)) - + def resolveOutputs(self): """Sets temporary outputs (output.value = None) with a temporary file instead. Resolves expressions as well. @@ -343,7 +342,7 @@ def resolveOutputs(self): out.resolveValue(self) except ValueError, e: raise GeoAlgorithmExecutionException(str(e)) - + def setOutputCRS(self): layers = dataobjects.getAllLayers() for param in self.parameters: diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index 3ca682e15621..796e82763e6c 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -40,6 +40,7 @@ from qgis.core import QgsExpressionContext, QgsExpressionContextUtils, QgsExpression, QgsExpressionContextScope + def _expressionContext(alg): context = QgsExpressionContext() context.appendScope(QgsExpressionContextUtils.globalScope()) @@ -50,6 +51,7 @@ def _expressionContext(alg): context.appendScope(processingScope) return context + class Output(object): def __init__(self, name='', description='', hidden=False): @@ -93,17 +95,17 @@ def setValue(self, value): return True except: return False - + def _resolveTemporary(self, alg): ext = self.getDefaultFileExtension() return getTempFilenameInTempFolder(self.name + '.' + ext) - + def _supportedExtensions(self): return [] - + def resolveValue(self, alg): if not self.hidden and not bool(self.value): - self.value = self._resolveTemporary(alg) + self.value = self._resolveTemporary(alg) else: exp = QgsExpression(self.value) if not exp.hasParserError(): @@ -113,7 +115,7 @@ def resolveValue(self, alg): if ":" not in self.value: if not os.path.isabs(self.value): - self.value = os.path.join(ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER), + self.value = os.path.join(ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER), self.value) supported = self._supportedExtensions() if supported: @@ -138,7 +140,7 @@ def tr(self, string, context=''): class OutputDirectory(Output): - + def resolveValue(self, alg): self.value = getTempDirInTempFolder() @@ -330,7 +332,6 @@ def getDefaultFileExtension(self): default = 'dbf' return default - def getCompatibleFileName(self, alg): """Returns a filename that is compatible with the algorithm that is going to generate this output. @@ -389,7 +390,7 @@ def _resolveTemporary(self, alg): else: ext = self.getDefaultFileExtension() return getTempFilenameInTempFolder(self.name + '.' + ext) - + def getOutputFromString(s): try: @@ -402,7 +403,7 @@ def getOutputFromString(s): tokens = s.split("=") token = tokens[1].strip()[len('output') + 1:] out = None - + if token.lower().strip().startswith('raster'): out = OutputRaster() elif token.lower().strip() == 'vector': @@ -430,7 +431,7 @@ def getOutputFromString(s): out = OutputString() elif token.lower().strip().startswith('extent'): out = OutputExtent() - + return out except: - return None \ No newline at end of file + return None diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 3936b8eaa160..1ede0f943258 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -36,7 +36,7 @@ from qgis.utils import iface from qgis.PyQt.QtCore import QCoreApplication -from qgis.core import (QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsCoordinateReferenceSystem, +from qgis.core import (QgsRasterLayer, QgsVectorLayer, QgsMapLayer, QgsCoordinateReferenceSystem, QgsExpressionContext, QgsExpressionContextUtils, QgsExpression, QgsExpressionContextScope) from processing.tools.vector import resolveFieldIndex, features @@ -44,11 +44,13 @@ from processing.core.outputs import OutputNumber, OutputRaster, OutputVector from processing.tools.dataobjects import getObject + def parseBool(s): if s is None or s == str(None).lower(): return None return str(s).lower() == str(True).lower() + def _splitParameterOptions(line): tokens = line.split('=', 1) if tokens[1].lower().strip().startswith('optional'): @@ -59,9 +61,11 @@ def _splitParameterOptions(line): definition = tokens[1] return isOptional, tokens[0], definition + def _createDescriptiveName(s): return s.replace('_', ' ') + def _expressionContext(): context = QgsExpressionContext() context.appendScope(QgsExpressionContextUtils.globalScope()) @@ -78,7 +82,7 @@ def _expressionContext(): cellsize = (layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width() processingScope.setVariable('%s_cellsize' % name, cellsize) - + layers = dataobjects.getRasterLayers() for layer in layers: for i in range(layer.bandCount()): @@ -87,13 +91,13 @@ def _expressionContext(): processingScope.setVariable('%s_band%i_stddev' % (name, i + 1), stats.stdDev) processingScope.setVariable('%s_band%i_min' % (name, i + 1), stats.minimumValue) processingScope.setVariable('%s_band%i_max' % (name, i + 1), stats.maximumValue) - + extent = iface.mapCanvas().extent() processingScope.setVariable('canvasextent_minx', extent.xMinimum()) processingScope.setVariable('canvasextent_miny', extent.yMinimum()) processingScope.setVariable('canvasextent_maxx', extent.xMaximum()) processingScope.setVariable('canvasextent_maxy', extent.yMaximum()) - + extent = iface.mapCanvas().fullExtent() processingScope.setVariable('fullextent_minx', extent.xMinimum()) processingScope.setVariable('fullextent_miny', extent.yMinimum()) @@ -102,6 +106,7 @@ def _expressionContext(): context.appendScope(processingScope) return context + def _resolveLayers(value): layers = dataobjects.getAllLayers() if value: @@ -113,6 +118,7 @@ def _resolveLayers(value): break return ";".join(inputlayers) + class Parameter: """ @@ -203,13 +209,14 @@ def wrapper(self, dialog, row=0, col=0): wrapper = wrapper(self, dialog, row, col) # or a wrapper instance return wrapper - + def evaluate(self, alg): pass - + def evaluateForModeler(self, value, model): return value + class ParameterBoolean(Parameter): default_metadata = { @@ -253,7 +260,6 @@ def fromScriptCode(self, line): return param - class ParameterCrs(Parameter): default_metadata = { @@ -287,8 +293,7 @@ def setValue(self, value): return True except: pass - - + # TODO: check it is a valid authid self.value = value return True @@ -314,6 +319,7 @@ def fromScriptCode(self, line): else: return ParameterCrs(name, descName, None, isOptional) + class ParameterDataObject(Parameter): def getValueAsCommandLineParameter(self): @@ -323,7 +329,7 @@ def getValueAsCommandLineParameter(self): s = dataobjects.normalizeLayerSource(str(self.value)) s = '"%s"' % s return s - + def evaluate(self, alg): self.value = _resolveLayers(self.value) @@ -333,7 +339,7 @@ class ParameterExtent(Parameter): default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.ExtentWidgetWrapper' } - + USE_MIN_COVERING_EXTENT = 'USE_MIN_COVERING_EXTENT' def __init__(self, name='', description='', default=None, optional=True): @@ -438,7 +444,7 @@ def addToRegion(self, layer, first): self.xmax = max(self.xmax, layer.extent().xMaximum()) self.ymin = min(self.ymin, layer.extent().yMinimum()) self.ymax = max(self.ymax, layer.extent().yMaximum()) - + class ParameterPoint(Parameter): @@ -538,7 +544,6 @@ def fromScriptCode(self, line): class ParameterFixedTable(Parameter): - def __init__(self, name='', description='', numRows=3, cols=['value'], fixedNumOfRows=False, optional=False): @@ -591,12 +596,11 @@ class ParameterMultipleInput(ParameterDataObject): Its value is a string with substrings separated by semicolons, each of which represents the data source location of each element. """ - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.MultipleInputWidgetWrapper' } - exported = None def __init__(self, name='', description='', datatype=-1, optional=False): @@ -780,22 +784,21 @@ def fromScriptCode(self, line): descName = _createDescriptiveName(name) if definition.lower().strip() == 'multiple raster': return ParameterMultipleInput(name, descName, - dataobjects.TYPE_RASTER, isOptional) + dataobjects.TYPE_RASTER, isOptional) elif definition.lower().strip() == 'multiple vector': return ParameterMultipleInput(name, definition, - dataobjects.TYPE_VECTOR_ANY, isOptional) + dataobjects.TYPE_VECTOR_ANY, isOptional) def evaluate(self, alg): self.value = _resolveLayers(self.value) class ParameterNumber(Parameter): - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.NumberWidgetWrapper' } - def __init__(self, name='', description='', minValue=None, maxValue=None, default=None, optional=False): Parameter.__init__(self, name, description, default, optional) @@ -835,7 +838,7 @@ def setValue(self, n): except: raise return False - else: + else: try: if float(n) - int(float(n)) == 0: value = int(float(n)) @@ -867,7 +870,7 @@ def fromScriptCode(self, line): if definition.lower().strip().startswith('number'): default = definition.strip()[len('number') + 1:] or None return ParameterNumber(name, descName, default=default, optional=isOptional) - + def _evaluate(self, value): exp = QgsExpression(value) if exp.hasParserError(): @@ -876,20 +879,20 @@ def _evaluate(self, value): if exp.hasEvalError(): raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) return result - + def evaluate(self, alg): if isinstance(self.value, basestring) and bool(self.value): self.value = self._evaluate(self.value) - + def _layerVariables(self, element, alg=None): variables = {} layer = getObject(element.value) if layer is not None: name = element.name if alg is None else "%s_%s" % (alg.name, element.name) - variables['@%s_minx' % name] = layer.extent().xMinimum() + variables['@%s_minx' % name] = layer.extent().xMinimum() variables['@%s_miny' % name] = layer.extent().yMinimum() - variables['@%s_maxx' % name] = layer.extent().yMaximum() - variables['@%s_maxy' % name]= layer.extent().yMaximum() + variables['@%s_maxx' % name] = layer.extent().yMaximum() + variables['@%s_maxy' % name] = layer.extent().yMaximum() if isinstance(element, (ParameterRaster, OutputRaster)): stats = layer.dataProvider().bandStatistics(1) variables['@%s_avg' % name] = stats.mean @@ -897,7 +900,7 @@ def _layerVariables(self, element, alg=None): variables['@%s_min' % name] = stats.minimumValue variables['@%s_max' % name] = stats.maximumValue return variables - + def evaluateForModeler(self, value, model): if isinstance(value, numbers.Number): return value @@ -907,21 +910,21 @@ def evaluateForModeler(self, value, model): variables["@" + param.name] = param.value if isinstance(param, (ParameterRaster, ParameterVector)): variables.update(self._layerVariables(param)) - + for alg in model.algs.values(): for out in alg.algorithm.outputs: if isinstance(out, OutputNumber): variables["@%s_%s" % (alg.name, out.name)] = out.value if isinstance(out, (OutputRaster, OutputVector)): variables.update(self._layerVariables(out, alg)) - for k,v in variables.iteritems(): - value = value.replace(k,unicode(v)) - + for k, v in variables.iteritems(): + value = value.replace(k, unicode(v)) + return value - + def expressionContext(self): return _expressionContext() - + def getValueAsCommandLineParameter(self): if self.value is None: return str(None) @@ -930,7 +933,6 @@ def getValueAsCommandLineParameter(self): return str(self.value) - class ParameterRange(Parameter): def __init__(self, name='', description='', default=None, optional=False): @@ -970,12 +972,11 @@ def getValueAsCommandLineParameter(self): class ParameterRaster(ParameterDataObject): - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.RasterWidgetWrapper' } - def __init__(self, name='', description='', optional=False, showSublayersDialog=True): ParameterDataObject.__init__(self, name, description, None, optional) self.showSublayersDialog = parseBool(showSublayersDialog) @@ -1044,15 +1045,15 @@ def fromScriptCode(self, line): if definition.lower().strip().startswith('raster'): return ParameterRaster(name, descName, optional=isOptional) + class ParameterSelection(Parameter): - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.SelectionWidgetWrapper' } - def __init__(self, name='', description='', options=[], default=None, isSource=False, - multiple=False, optional=False): + multiple=False, optional=False): Parameter.__init__(self, name, description, default, optional) self.multiple = multiple isSource = parseBool(isSource) @@ -1127,19 +1128,18 @@ def fromScriptCode(self, line): class ParameterEvaluationException(Exception): - + def __init__(self, param, msg): Exception.__init__(msg) self.param = param class ParameterString(Parameter): - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.StringWidgetWrapper' } - NEWLINE = '\n' ESCAPED_NEWLINE = '\\n' @@ -1190,7 +1190,7 @@ def fromScriptCode(self, line): return ParameterString(name, descName, default, multiline=True, optional=isOptional) else: return ParameterString(name, descName, multiline=True, optional=isOptional) - + def evaluate(self, alg): if isinstance(self.value, basestring) and bool(self.value) and self.evaluateExpressions: exp = QgsExpression(self.value) @@ -1200,17 +1200,17 @@ def evaluate(self, alg): if exp.hasEvalError(): raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) self.value = result - + def expressionContext(self): return _expressionContext() + class ParameterTable(ParameterDataObject): - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.TableWidgetWrapper' } - def __init__(self, name='', description='', optional=False): ParameterDataObject.__init__(self, name, description, None, optional) self.exported = None @@ -1298,13 +1298,12 @@ class ParameterTableField(Parameter): 'widget_wrapper': 'processing.gui.wrappers.TableFieldWidgetWrapper' } - DATA_TYPE_NUMBER = 0 DATA_TYPE_STRING = 1 DATA_TYPE_ANY = -1 def __init__(self, name='', description='', parent=None, datatype=-1, - optional=False, multiple = False): + optional=False, multiple=False): Parameter.__init__(self, name, description, None, optional) self.parent = parent self.multiple = multiple @@ -1319,6 +1318,7 @@ def setValue(self, value): return False self.value = None return True + if isinstance(value, list): if not self.multiple and len(value) > 1: return False @@ -1347,7 +1347,6 @@ def getAsScriptCode(self): param_type += 'field' return '##' + self.name + '=' + param_type + self.parent - @classmethod def fromScriptCode(self, line): isOptional, name, definition = _splitParameterOptions(line) @@ -1367,7 +1366,7 @@ def fromScriptCode(self, line): class ParameterVector(ParameterDataObject): - + default_metadata = { 'widget_wrapper': 'processing.gui.wrappers.VectorWidgetWrapper' } @@ -1452,16 +1451,17 @@ def fromScriptCode(self, line): descName = _createDescriptiveName(name) if definition.lower().strip() == 'vector': return ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_ANY], isOptional) + [dataobjects.TYPE_VECTOR_ANY], isOptional) elif definition.lower().strip() == 'vector point': return ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_POINT], isOptional) + [dataobjects.TYPE_VECTOR_POINT], isOptional) elif definition.lower().strip() == 'vector line': return ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_LINE], isOptional) + [dataobjects.TYPE_VECTOR_LINE], isOptional) elif definition.lower().strip() == 'vector polygon': return ParameterVector(name, descName, - [dataobjects.TYPE_VECTOR_POLYGON], isOptional) + [dataobjects.TYPE_VECTOR_POLYGON], isOptional) + class ParameterGeometryPredicate(Parameter): @@ -1505,6 +1505,7 @@ def setValue(self, value): paramClasses = [c for c in sys.modules[__name__].__dict__.values() if isclass(c) and issubclass(c, Parameter)] + def getParameterFromString(s): # Try the parameter definitions used in description files if '|' in s: diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index fe2944719ceb..786f44d8789a 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -71,7 +71,6 @@ def __init__(self, alg): self.cornerWidget.setLayout(layout) self.tabWidget.setCornerWidget(self.cornerWidget) - def runAsBatch(self): self.close() dlg = BatchAlgorithmDialog(self.alg) diff --git a/python/plugins/processing/gui/AlgorithmDialogBase.py b/python/plugins/processing/gui/AlgorithmDialogBase.py index 53045dd820a3..bbd3a8eac1cb 100644 --- a/python/plugins/processing/gui/AlgorithmDialogBase.py +++ b/python/plugins/processing/gui/AlgorithmDialogBase.py @@ -131,7 +131,6 @@ def setMainWidget(self, widget): QgsMapLayerRegistry.instance().layerWasAdded.connect(self.mainWidget.layerRegistryChanged) QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self.mainWidget.layerRegistryChanged) - def error(self, msg): QApplication.restoreOverrideCursor() self.setInfo(msg, True) diff --git a/python/plugins/processing/gui/BatchAlgorithmDialog.py b/python/plugins/processing/gui/BatchAlgorithmDialog.py index e2de360a1214..855462dea33b 100644 --- a/python/plugins/processing/gui/BatchAlgorithmDialog.py +++ b/python/plugins/processing/gui/BatchAlgorithmDialog.py @@ -80,8 +80,8 @@ def accept(self): wrapper = self.mainWidget.wrappers[row][col] if not self.mainWidget.setParamValue(param, wrapper, alg): self.bar.pushMessage("", self.tr('Wrong or missing parameter value: %s (row %d)') - % (param.description, row + 1), - level=QgsMessageBar.WARNING, duration=5) + % (param.description, row + 1), + level=QgsMessageBar.WARNING, duration=5) self.algs = None return col += 1 diff --git a/python/plugins/processing/gui/BatchInputSelectionPanel.py b/python/plugins/processing/gui/BatchInputSelectionPanel.py index dedb974eca8b..38671343d106 100644 --- a/python/plugins/processing/gui/BatchInputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchInputSelectionPanel.py @@ -124,7 +124,7 @@ def showLayerSelectionDialog(self): self._panel().addRow() for i, layeridx in enumerate(selected): self._table().cellWidget(i + self.row, - self.col).setValue(layers[layeridx]) + self.col).setValue(layers[layeridx]) def showFileSelectionDialog(self): settings = QSettings() @@ -157,7 +157,7 @@ def showFileSelectionDialog(self): self._panel().addRow() for i, f in enumerate(files): self._table().cellWidget(i + self.row, - self.col).setValue(f) + self.col).setValue(f) def textEditingFinished(self): self._value = self.text.text() @@ -170,6 +170,6 @@ def setValue(self, value): self._value = value if isinstance(value, QgsMapLayer): self.text.setText(value.name()) - else: #  should be basestring + else: # should be basestring self.text.setText(value) self.valueChanged.emit() diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index d09b765c4116..52eb6747584a 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -90,7 +90,6 @@ def __init__(self, parent, alg): self.initWidgets() - def layerRegistryChanged(self): pass @@ -194,8 +193,8 @@ def save(self): wrapper = self.wrappers[row][col] if not self.setParamValue(param, wrapper, alg): self.parent.bar.pushMessage("", self.tr('Wrong or missing parameter value: %s (row %d)') - % (param.description, row + 1), - level=QgsMessageBar.WARNING, duration=5) + % (param.description, row + 1), + level=QgsMessageBar.WARNING, duration=5) return algParams[param.name] = param.getValueAsCommandLineParameter() col += 1 diff --git a/python/plugins/processing/gui/ExtentSelectionPanel.py b/python/plugins/processing/gui/ExtentSelectionPanel.py index dce7080c9cde..4ff826716c44 100644 --- a/python/plugins/processing/gui/ExtentSelectionPanel.py +++ b/python/plugins/processing/gui/ExtentSelectionPanel.py @@ -80,7 +80,6 @@ def __init__(self, dialog, param): except: pass - def selectExtent(self): popupmenu = QMenu() useLayerExtentAction = QAction( diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index 5e31788eb426..d3e64e5bcade 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -71,7 +71,7 @@ def showExpressionsBuilder(self): variables = {} for value in values: if isinstance(value, ValueFromInput): - name = value.name + name = value.name element = self.modelParametersDialog.model.inputs[name].param desc = element.description else: @@ -79,12 +79,12 @@ def showExpressionsBuilder(self): alg = self.modelParametersDialog.model.algs[value.alg] out = alg.algorithm.getOutputFromName(value.output) desc = "Output '%s' from algorithm '%s" % (out.description, alg.description) - variables[name] = desc + variables[name] = desc values = self.modelParametersDialog.getAvailableValuesOfType(ParameterVector, OutputVector) values.extend(self.modelParametersDialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)) for value in values: - if isinstance(value, ValueFromInput): - name = value.name + if isinstance(value, ValueFromInput): + name = value.name element = self.modelParametersDialog.model.inputs[name].param desc = element.description else: @@ -111,7 +111,6 @@ def showExpressionsBuilder(self): if not exp.hasParserError(): self.setValue(dlg.expressionText()) - def getValue(self): if self.modelParametersDialog: value = self.leText.text() diff --git a/python/plugins/processing/gui/OutputSelectionPanel.py b/python/plugins/processing/gui/OutputSelectionPanel.py index a18dcfe20a9f..eb3c91a8d3ad 100644 --- a/python/plugins/processing/gui/OutputSelectionPanel.py +++ b/python/plugins/processing/gui/OutputSelectionPanel.py @@ -121,7 +121,7 @@ def selectOutput(self): popupMenu.exec_(QCursor.pos()) def showExpressionsBuilder(self): - dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', + dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', self.output.expressionContext(self.alg)) dlg.setWindowTitle(self.tr('Expression based output')) if dlg.exec_() == QDialog.Accepted: diff --git a/python/plugins/processing/gui/StringInputPanel.py b/python/plugins/processing/gui/StringInputPanel.py index b5ec19b7af54..8a5c1d50db33 100644 --- a/python/plugins/processing/gui/StringInputPanel.py +++ b/python/plugins/processing/gui/StringInputPanel.py @@ -66,7 +66,6 @@ def showExpressionsBuilder(self): if not exp.hasParserError(): self.setValue(dlg.expressionText()) - def getValue(self): return self.leText.text() diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index f4e77755f8bf..309dbfcec678 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -41,12 +41,12 @@ from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.PointSelectionPanel import PointSelectionPanel from processing.core.parameters import (ParameterBoolean, ParameterPoint, ParameterFile, - ParameterRaster, ParameterVector, ParameterNumber, ParameterString, ParameterTable, - ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs, _resolveLayers) + ParameterRaster, ParameterVector, ParameterNumber, ParameterString, ParameterTable, + ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs, _resolveLayers) from processing.core.ProcessingConfig import ProcessingConfig from processing.gui.FileSelectionPanel import FileSelectionPanel from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, - OutputString, OutputTable, OutputExtent) + OutputString, OutputTable, OutputExtent) from processing.tools import dataobjects from processing.gui.MultipleInputPanel import MultipleInputPanel from processing.gui.BatchInputSelectionPanel import BatchInputSelectionPanel @@ -60,14 +60,16 @@ DIALOG_BATCH = 'batch' DIALOG_MODELER = 'modeler' + class InvalidParameterValue(Exception): pass -dialogTypes = {"AlgorithmDialog":DIALOG_STANDARD, - "ModelerParametersDialog":DIALOG_MODELER, +dialogTypes = {"AlgorithmDialog": DIALOG_STANDARD, + "ModelerParametersDialog": DIALOG_MODELER, "BatchAlgorithmDialog": DIALOG_BATCH} + def getExtendedLayerName(layer): authid = layer.crs().authid() if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) and authid is not None: @@ -75,6 +77,7 @@ def getExtendedLayerName(layer): else: return layer.name() + class WidgetWrapper(QObject): widgetValueHasChanged = pyqtSignal(object) @@ -130,6 +133,7 @@ def postInitialize(self, wrappers): def refresh(self): pass + class BasicWidgetWrapper(WidgetWrapper): def createWidget(self): @@ -221,6 +225,7 @@ def value(self): else: return self.widget.getValue() + class ExtentWidgetWrapper(WidgetWrapper): USE_MIN_COVERING_EXTENT = "[Use min covering extent]" @@ -347,6 +352,7 @@ def value(self): else: return self.comboValue() + class FixedTableWidgetWrapper(WidgetWrapper): def createWidget(self): @@ -464,6 +470,7 @@ def setValue(self, value): def value(self): return self.widget.getValue() + class RasterWidgetWrapper(WidgetWrapper): NOT_SELECTED = '[Not selected]' @@ -540,7 +547,7 @@ def setValue(self, value): def value(self): if self.param.multiple: - return self.widget.selectedoptions + return self.widget.selectedoptions else: return self.widget.currentIndex() @@ -614,6 +621,7 @@ def validator(v): return os.path.exists(v) return self.comboValue(validator) + class StringWidgetWrapper(WidgetWrapper): def createWidget(self): @@ -627,9 +635,9 @@ def createWidget(self): if self.param.default: widget.setValue(self.param.default) elif self.dialogType == DIALOG_BATCH: - widget = QLineEdit() - if self.param.default: - widget.setText(self.param.default) + widget = QLineEdit() + if self.param.default: + widget.setText(self.param.default) else: strings = self.dialog.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.dialog.resolveValueDescription(s), s) for s in strings] @@ -722,7 +730,6 @@ def setValue(self, value): else: self.setComboValue(value) - def value(self): if self.dialogType == DIALOG_STANDARD: try: @@ -736,6 +743,7 @@ def validator(v): return bool(v) or self.param.optional return self.comboValue(validator) + class TableFieldWidgetWrapper(WidgetWrapper): NOT_SET = '[Not set]' @@ -825,7 +833,7 @@ def setValue(self, value): def value(self): if self.param.multiple: if self.dialogType == DIALOG_STANDARD: - return [self.widget.options[i] for i in self.widget.selectedoptions] + return [self.widget.options[i] for i in self.widget.selectedoptions] elif self.dialogType == DIALOG_BATCH: return self.widget.text() else: diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index 0bd81f995996..6b908fb0abf2 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -204,9 +204,10 @@ def __str__(self): def asPythonParameter(self): return "outputs_%s['%s']" % (self.alg, self.output) + class CompoundValue(): - def __init__(self, values = [], definition=""): + def __init__(self, values=[], definition=""): self.values = values self.definition = definition @@ -223,7 +224,7 @@ def __str__(self): return self.definition def asPythonParameter(self): - return "" #TODO + return "" # TODO class ModelerAlgorithm(GeoAlgorithm): @@ -368,7 +369,7 @@ def getDependsOnAlgorithms(self, name): for v in value.values: if isinstance(v, ValueFromOutput): algs.add(v.alg) - algs.update(self.getDependsOnAlgorithms(v.alg)) + algs.update(self.getDependsOnAlgorithms(v.alg)) if isinstance(value, list): for v in value: if isinstance(v, ValueFromOutput): diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index c7aca1f62272..91ab29b51670 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -340,8 +340,8 @@ def saveModel(self, saveAs): fout.write(text) fout.close() self.update = True - self.bar.pushMessage("", "Model was correctly saved", level = QgsMessageBar.SUCCESS, duration = 5) - + self.bar.pushMessage("", "Model was correctly saved", level=QgsMessageBar.SUCCESS, duration=5) + self.hasChanged = False def openModel(self): diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 746d056e930e..e8652ab870db 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -219,9 +219,6 @@ def setupUi(self): except: pass - - - self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) diff --git a/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py b/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py index f60b3f3782fa..4a89d2d356ee 100644 --- a/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py +++ b/python/plugins/processing/preconfigured/PreconfiguredAlgorithmDialog.py @@ -80,8 +80,8 @@ def accept(self): palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) self.parent.bar.pushMessage("", self.tr('Missing parameter value: %s') - % e.parameter.description, - level=QgsMessageBar.WARNING, duration=5) + % e.parameter.description, + level=QgsMessageBar.WARNING, duration=5) return except: QMessageBox.critical(self, From e04780a27901e913c166969a5d7dfe0ac217d7bf Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 19 Sep 2016 11:53:21 +0300 Subject: [PATCH 160/897] add missed comma --- python/plugins/processing/tools/dataobjects.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 2f66677302de..89eb5d7951b2 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -47,7 +47,7 @@ from processing.algs.gdal.GdalUtils import GdalUtils from processing.tools.system import (getTempFilenameInTempFolder, getTempFilename, - removeInvalidChars + removeInvalidChars, isWindows) ALL_TYPES = [-1] From b2fd1a456045d88ca270ede6ec2547ec8e66f4fa Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 14:35:33 +0200 Subject: [PATCH 161/897] [processing] use cmp_to_key to ensure Python3 compatibility Conflicts: python/plugins/processing/gui/wrappers.py --- python/plugins/processing/gui/wrappers.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 309dbfcec678..7ff15790a347 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -30,6 +30,7 @@ import locale import os +from functools import cmp_to_key from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit @@ -813,7 +814,7 @@ def getFields(self): for field in self._layer.fields(): if not fieldTypes or field.type() in fieldTypes: fieldNames.add(unicode(field.name())) - return sorted(list(fieldNames), cmp=locale.strcoll) + return sorted(list(fieldNames), key=cmp_to_key(locale.strcoll)) def setValue(self, value): if self.param.multiple: From 1a95110dcc7934a16310261f36951b3180f78d6d Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 15:13:45 +0200 Subject: [PATCH 162/897] [processing] renamed wrongly named signal in InputLayerSelectionPanel --- python/plugins/processing/gui/InputLayerSelectorPanel.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/InputLayerSelectorPanel.py b/python/plugins/processing/gui/InputLayerSelectorPanel.py index 254bad199a48..56313549d3d2 100644 --- a/python/plugins/processing/gui/InputLayerSelectorPanel.py +++ b/python/plugins/processing/gui/InputLayerSelectorPanel.py @@ -41,7 +41,7 @@ class InputLayerSelectorPanel(BASE, WIDGET): - valueHasChanged = pyqtSignal() + valueChanged = pyqtSignal() def __init__(self, options, param): super(InputLayerSelectorPanel, self).__init__(None) @@ -57,7 +57,7 @@ def __init__(self, options, param): self.cmbText.addItem(name, value) self.btnSelect.clicked.connect(self.showSelectionDialog) - self.cmbText.currentIndexChanged.connect(self.valueHasChanged.emit) + self.cmbText.currentIndexChanged.connect(self.valueChanged.emit) def showSelectionDialog(self): settings = QSettings() @@ -84,7 +84,7 @@ def update(self, options): self.cmbText.clear() for (name, value) in options: self.cmbText.addItem(name, value) - self.valueHasChanged.emit() + self.valueChanged.emit() def getValue(self): return self.cmbText.itemData(self.cmbText.currentIndex()) From db7b1e7890df3cb342e982d12d52c0ea19794985 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 15:40:14 +0200 Subject: [PATCH 163/897] [processing] correctly resolve values for hidden outputs --- python/plugins/processing/core/outputs.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index 796e82763e6c..34f66c360eb2 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -104,7 +104,9 @@ def _supportedExtensions(self): return [] def resolveValue(self, alg): - if not self.hidden and not bool(self.value): + if self.hidden: + return + if not bool(self.value): self.value = self._resolveTemporary(alg) else: exp = QgsExpression(self.value) From 6f498a313872ad6eb19e22e0382f4fef943daadc Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 19:30:00 +0200 Subject: [PATCH 164/897] [processing] removed debug line --- python/plugins/processing/core/parameters.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 1ede0f943258..2e483c22c363 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -836,7 +836,6 @@ def setValue(self, n): self.value = float(v) return True except: - raise return False else: try: From 23aec61501ccad1360f7e3eec9e3b05eaf471f75 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 19 Sep 2016 21:52:59 +0200 Subject: [PATCH 165/897] [processing] connect signal in multipleinput widget --- python/plugins/processing/gui/wrappers.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 7ff15790a347..e8a202243414 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -406,7 +406,9 @@ def createWidget(self): opts = [getExtendedLayerName(opt) for opt in options] return MultipleInputPanel(opts) elif self.dialogType == DIALOG_BATCH: - return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) + widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + return widget else: options = [self.dialog.resolveValueDescription(opt) for opt in self._getOptions()] return MultipleInputPanel(options) From 404c57bc59bedf9c1d09c3d15b9b8dc5ef0fe86f Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 20 Sep 2016 13:43:10 +0200 Subject: [PATCH 166/897] [processing] fixed table fields in batch processing interface Conflicts: python/plugins/processing/gui/BatchInputSelectionPanel.py --- python/plugins/processing/gui/BatchInputSelectionPanel.py | 5 +++-- python/plugins/processing/gui/wrappers.py | 3 --- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/gui/BatchInputSelectionPanel.py b/python/plugins/processing/gui/BatchInputSelectionPanel.py index 38671343d106..5b7c3a573990 100644 --- a/python/plugins/processing/gui/BatchInputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchInputSelectionPanel.py @@ -114,7 +114,7 @@ def showLayerSelectionDialog(self): if dlg.selectedoptions is not None: selected = dlg.selectedoptions if len(selected) == 1: - self.text.setText(layers[selected[0]].name()) + self.setValue(layers[selected[0]]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(layers[idx].name() for idx in selected)) @@ -148,6 +148,7 @@ def showFileSelectionDialog(self): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) + self.textEditingFinished() else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(str(f) for f in files)) @@ -170,6 +171,6 @@ def setValue(self, value): self._value = value if isinstance(value, QgsMapLayer): self.text.setText(value.name()) - else: # should be basestring + else: # should be basestring self.text.setText(value) self.valueChanged.emit() diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index e8a202243414..edcfe40b66d6 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -762,8 +762,6 @@ def createWidget(self): else: if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): widget = QComboBox() - if self.dialogType == DIALOG_BATCH: - widget.setEditable(True) # Should be removed at the end return widget else: widget = QComboBox() @@ -778,7 +776,6 @@ def createWidget(self): def postInitialize(self, wrappers): for wrapper in wrappers: if wrapper.param.name == self.param.parent: - # self.refreshItems() if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): self.setLayer(wrapper.value()) wrapper.widgetValueHasChanged.connect(self.parentValueChanged) From effcb5ed14f144db9ab831ca8e4a5ec04330f963 Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 21 Sep 2016 11:27:08 +0200 Subject: [PATCH 167/897] [processing] [modeler] show options of MultipleInputParameter sorted in alphabetical order fixes # 4836 --- python/plugins/processing/gui/wrappers.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index edcfe40b66d6..2b9575a55fb3 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -390,6 +390,7 @@ def _getOptions(self): options = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) else: options = self.dialog.getAvailableValuesOfType(ParameterFile, OutputFile) + options = sorted(options, key=lambda opt: self.dialog.resolveValueDescription(opt)) return options def createWidget(self): From 4184934b9a8889d015f6a45021b27e88a60a754b Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Tue, 27 Sep 2016 19:51:06 +0200 Subject: [PATCH 168/897] [processing] Apply 2to3 on changes --- .../plugins/processing/algs/gdal/GdalUtils.py | 2 +- .../processing/algs/gdal/gdal2tiles.py | 2 +- .../plugins/processing/algs/grass7/ext/i.py | 2 +- .../processing/algs/grass7/ext/v_net.py | 2 +- .../plugins/processing/algs/help/__init__.py | 2 +- .../algs/lidar/lastools/lasquery.py | 2 +- .../processing/algs/otb/OTBAlgorithm.py | 3 ++- .../algs/otb/maintenance/parsing.py | 1 + .../processing/algs/qgis/ConcaveHull.py | 2 +- .../plugins/processing/algs/qgis/Delaunay.py | 1 + .../algs/qgis/DeleteDuplicateGeometries.py | 2 +- .../processing/algs/qgis/Difference.py | 1 + .../processing/algs/qgis/ExtractByLocation.py | 1 + .../processing/algs/qgis/HubDistanceLines.py | 1 + .../processing/algs/qgis/HubDistancePoints.py | 1 + .../processing/algs/qgis/HypsometricCurves.py | 2 +- .../processing/algs/qgis/Intersection.py | 1 + .../processing/algs/qgis/LinesIntersection.py | 1 + .../processing/algs/qgis/MeanCoords.py | 2 +- .../algs/qgis/NearestNeighbourAnalysis.py | 1 + .../processing/algs/qgis/PointDistance.py | 1 + .../algs/qgis/PointsDisplacement.py | 3 ++- .../processing/algs/qgis/PointsToPaths.py | 2 +- .../processing/algs/qgis/RandomExtract.py | 2 +- .../algs/qgis/RandomPointsAlongLines.py | 1 + .../processing/algs/qgis/RandomPointsLayer.py | 1 + .../processing/algs/qgis/RandomSelection.py | 2 +- .../algs/qgis/SelectByAttributeSum.py | 1 + .../processing/algs/qgis/SelectByLocation.py | 1 + .../algs/qgis/SplitLinesWithLines.py | 1 + .../plugins/processing/algs/qgis/SumLines.py | 1 + python/plugins/processing/algs/qgis/Union.py | 1 + .../processing/algs/qgis/VoronoiPolygons.py | 3 ++- .../algs/qgis/ui/FieldsMappingPanel.py | 2 +- .../plugins/processing/algs/qgis/voronoi.py | 1 + .../plugins/processing/core/GeoAlgorithm.py | 4 ++-- .../plugins/processing/core/ProcessingLog.py | 2 +- python/plugins/processing/core/outputs.py | 2 +- python/plugins/processing/core/parameters.py | 22 ++++++++--------- .../plugins/processing/gui/AlgorithmDialog.py | 4 ++-- .../processing/gui/BatchAlgorithmDialog.py | 4 ++-- python/plugins/processing/gui/BatchPanel.py | 6 ++--- python/plugins/processing/gui/LexerR.py | 2 +- .../processing/gui/NumberInputPanel.py | 7 +++--- .../plugins/processing/gui/ParametersPanel.py | 6 ++--- .../processing/gui/ProcessingToolbox.py | 2 +- .../processing/gui/ScriptEditorDialog.py | 2 +- .../processing/gui/StringInputPanel.py | 3 ++- python/plugins/processing/gui/wrappers.py | 16 +++++++------ .../processing/modeler/ModelerAlgorithm.py | 18 +++++++------- .../processing/modeler/ModelerDialog.py | 4 ++-- .../ModelerParameterDefinitionDialog.py | 24 +------------------ .../modeler/ModelerParametersDialog.py | 14 ++++------- .../processing/modeler/ModelerScene.py | 8 +++---- .../preconfigured/PreconfiguredAlgorithm.py | 4 ++-- .../processing/script/ScriptSelector.py | 2 +- .../plugins/processing/tools/translation.py | 2 +- 57 files changed, 106 insertions(+), 107 deletions(-) diff --git a/python/plugins/processing/algs/gdal/GdalUtils.py b/python/plugins/processing/algs/gdal/GdalUtils.py index 427068ea9db1..f366d8fd075c 100644 --- a/python/plugins/processing/algs/gdal/GdalUtils.py +++ b/python/plugins/processing/algs/gdal/GdalUtils.py @@ -155,7 +155,7 @@ def getVectorDriverFromFileName(filename): return 'ESRI Shapefile' formats = QgsVectorFileWriter.supportedFiltersAndFormats() - for k, v in formats.items(): + for k, v in list(formats.items()): if ext in k: return v return 'ESRI Shapefile' diff --git a/python/plugins/processing/algs/gdal/gdal2tiles.py b/python/plugins/processing/algs/gdal/gdal2tiles.py index 04b6cd02c3b7..f63c794628d2 100644 --- a/python/plugins/processing/algs/gdal/gdal2tiles.py +++ b/python/plugins/processing/algs/gdal/gdal2tiles.py @@ -168,7 +168,7 @@ def getConsoleCommands(self): parameters = {self.TITLE: '-t', self.COPYRIGHT: '-c', self.GOOGLEKEY: '-g', self.BINGKEY: '-b'} - for arg, parameter in parameters.items(): + for arg, parameter in list(parameters.items()): if self.getParameterValue(arg): arguments.append(parameter) arguments.append(self.getParameterValue(arg)) diff --git a/python/plugins/processing/algs/grass7/ext/i.py b/python/plugins/processing/algs/grass7/ext/i.py index 577b33360f22..3caf1d597917 100644 --- a/python/plugins/processing/algs/grass7/ext/i.py +++ b/python/plugins/processing/algs/grass7/ext/i.py @@ -174,7 +174,7 @@ def exportInputRasters(alg, rasterDic): { 'inputName1': 'outputName1', 'inputName2': 'outputName2'} """ # Get inputs and outputs - for inputName, outputName in rasterDic.items(): + for inputName, outputName in list(rasterDic.items()): inputRaster = alg.getParameterValue(inputName) outputRaster = alg.getOutputFromName(outputName) command = 'r.out.gdal -c -t -f --overwrite createopt="TFW=YES,COMPRESS=LZW" input={} output=\"{}\"'.format( diff --git a/python/plugins/processing/algs/grass7/ext/v_net.py b/python/plugins/processing/algs/grass7/ext/v_net.py index cf5548446e80..48c4b3410164 100644 --- a/python/plugins/processing/algs/grass7/ext/v_net.py +++ b/python/plugins/processing/algs/grass7/ext/v_net.py @@ -87,7 +87,7 @@ def variableOutput(alg, params, nocats=True): """ # Build the v.out.ogr commands - for outputName, typeList in params.items(): + for outputName, typeList in list(params.items()): if not isinstance(typeList, list): continue diff --git a/python/plugins/processing/algs/help/__init__.py b/python/plugins/processing/algs/help/__init__.py index ea56b00c64bf..ec4843cd93a6 100644 --- a/python/plugins/processing/algs/help/__init__.py +++ b/python/plugins/processing/algs/help/__init__.py @@ -50,7 +50,7 @@ def replace(s): return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None - h = {k: replace(v) for k, v in h.items()} + h = {k: replace(v) for k, v in list(h.items())} return h diff --git a/python/plugins/processing/algs/lidar/lastools/lasquery.py b/python/plugins/processing/algs/lidar/lastools/lasquery.py index b72fb1332a1c..be1c9f5246a3 100644 --- a/python/plugins/processing/algs/lidar/lastools/lasquery.py +++ b/python/plugins/processing/algs/lidar/lastools/lasquery.py @@ -61,7 +61,7 @@ def processAlgorithm(self, progress): layers = QgsMapLayerRegistry.instance().mapLayers() # loop over layers - for name, layer in layers.items(): + for name, layer in list(layers.items()): layerType = layer.type() if layerType == QgsMapLayer.VectorLayer: shp_file_name = layer.source() diff --git a/python/plugins/processing/algs/otb/OTBAlgorithm.py b/python/plugins/processing/algs/otb/OTBAlgorithm.py index 65d473e8ed82..fd39294f481f 100644 --- a/python/plugins/processing/algs/otb/OTBAlgorithm.py +++ b/python/plugins/processing/algs/otb/OTBAlgorithm.py @@ -22,6 +22,7 @@ * * *************************************************************************** """ +from builtins import next from future import standard_library standard_library.install_aliases() from builtins import map @@ -307,7 +308,7 @@ def processAlgorithm(self, progress): OTBUtils.executeOtb(helperCommands, progress) if self.roiRasters: - supportRaster = next(iter(self.roiRasters.values())) + supportRaster = next(iter(list(self.roiRasters.values()))) for roiInput, roiFile in list(self.roiVectors.items()): helperCommands = [ "otbcli_VectorDataExtractROIApplication", diff --git a/python/plugins/processing/algs/otb/maintenance/parsing.py b/python/plugins/processing/algs/otb/maintenance/parsing.py index 99b533ec0a2b..66f930543db6 100644 --- a/python/plugins/processing/algs/otb/maintenance/parsing.py +++ b/python/plugins/processing/algs/otb/maintenance/parsing.py @@ -17,6 +17,7 @@ * * *************************************************************************** """ +from builtins import next from builtins import str from builtins import range __author__ = 'Julien Malik, Oscar Picas' diff --git a/python/plugins/processing/algs/qgis/ConcaveHull.py b/python/plugins/processing/algs/qgis/ConcaveHull.py index 82f86d711976..4dd63de67720 100644 --- a/python/plugins/processing/algs/qgis/ConcaveHull.py +++ b/python/plugins/processing/algs/qgis/ConcaveHull.py @@ -89,7 +89,7 @@ def processAlgorithm(self, progress): counter = 50. / len(edges) i = 0 ids = [] - for id, max_len in edges.items(): + for id, max_len in list(edges.items()): if max_len > alpha * max_length: ids.append(id) progress.setPercentage(50 + i * counter) diff --git a/python/plugins/processing/algs/qgis/Delaunay.py b/python/plugins/processing/algs/qgis/Delaunay.py index 5e6ab6c1d408..728b941f9ba9 100644 --- a/python/plugins/processing/algs/qgis/Delaunay.py +++ b/python/plugins/processing/algs/qgis/Delaunay.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/DeleteDuplicateGeometries.py b/python/plugins/processing/algs/qgis/DeleteDuplicateGeometries.py index 504ce307cafd..35bb4a18987b 100644 --- a/python/plugins/processing/algs/qgis/DeleteDuplicateGeometries.py +++ b/python/plugins/processing/algs/qgis/DeleteDuplicateGeometries.py @@ -64,7 +64,7 @@ def processAlgorithm(self, progress): cleaned = dict(geoms) - for i, g in geoms.items(): + for i, g in list(geoms.items()): for j in list(cleaned.keys()): if i == j or i not in cleaned: continue diff --git a/python/plugins/processing/algs/qgis/Difference.py b/python/plugins/processing/algs/qgis/Difference.py index a1511c2d6520..1eecde8bc736 100644 --- a/python/plugins/processing/algs/qgis/Difference.py +++ b/python/plugins/processing/algs/qgis/Difference.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/ExtractByLocation.py b/python/plugins/processing/algs/qgis/ExtractByLocation.py index 6ddfac02cb77..2620fd51661b 100644 --- a/python/plugins/processing/algs/qgis/ExtractByLocation.py +++ b/python/plugins/processing/algs/qgis/ExtractByLocation.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/HubDistanceLines.py b/python/plugins/processing/algs/qgis/HubDistanceLines.py index 79615265d374..646a17a4dba9 100644 --- a/python/plugins/processing/algs/qgis/HubDistanceLines.py +++ b/python/plugins/processing/algs/qgis/HubDistanceLines.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Michael Minn' __date__ = 'May 2010' diff --git a/python/plugins/processing/algs/qgis/HubDistancePoints.py b/python/plugins/processing/algs/qgis/HubDistancePoints.py index b3e759d1457f..7e4cc7521384 100644 --- a/python/plugins/processing/algs/qgis/HubDistancePoints.py +++ b/python/plugins/processing/algs/qgis/HubDistancePoints.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Michael Minn' __date__ = 'May 2010' diff --git a/python/plugins/processing/algs/qgis/HypsometricCurves.py b/python/plugins/processing/algs/qgis/HypsometricCurves.py index 39e87439c988..369de94395a2 100644 --- a/python/plugins/processing/algs/qgis/HypsometricCurves.py +++ b/python/plugins/processing/algs/qgis/HypsometricCurves.py @@ -197,7 +197,7 @@ def calculateHypsometry(self, fid, fName, progress, data, pX, pY, else: multiplier = pX * pY - for k, v in out.items(): + for k, v in list(out.items()): out[k] = v * multiplier prev = None diff --git a/python/plugins/processing/algs/qgis/Intersection.py b/python/plugins/processing/algs/qgis/Intersection.py index 408767148a2b..6525d1315f4f 100644 --- a/python/plugins/processing/algs/qgis/Intersection.py +++ b/python/plugins/processing/algs/qgis/Intersection.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/LinesIntersection.py b/python/plugins/processing/algs/qgis/LinesIntersection.py index 18a129ad38ba..bc63111cef64 100644 --- a/python/plugins/processing/algs/qgis/LinesIntersection.py +++ b/python/plugins/processing/algs/qgis/LinesIntersection.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/MeanCoords.py b/python/plugins/processing/algs/qgis/MeanCoords.py index 9a18b596f69d..c1e8451019c2 100644 --- a/python/plugins/processing/algs/qgis/MeanCoords.py +++ b/python/plugins/processing/algs/qgis/MeanCoords.py @@ -124,7 +124,7 @@ def processAlgorithm(self, progress): current = 0 total = 100.0 / len(means) - for (clazz, values) in means.items(): + for (clazz, values) in list(means.items()): outFeat = QgsFeature() cx = values[0] / values[2] cy = values[1] / values[2] diff --git a/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py b/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py index 5b2ec3a51a06..162790b434fb 100644 --- a/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py +++ b/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next from builtins import str __author__ = 'Victor Olaya' diff --git a/python/plugins/processing/algs/qgis/PointDistance.py b/python/plugins/processing/algs/qgis/PointDistance.py index bd16c6fd2a05..f6e0cbe16860 100644 --- a/python/plugins/processing/algs/qgis/PointDistance.py +++ b/python/plugins/processing/algs/qgis/PointDistance.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next from builtins import str from builtins import range diff --git a/python/plugins/processing/algs/qgis/PointsDisplacement.py b/python/plugins/processing/algs/qgis/PointsDisplacement.py index 00469d959314..a2cab293c456 100644 --- a/python/plugins/processing/algs/qgis/PointsDisplacement.py +++ b/python/plugins/processing/algs/qgis/PointsDisplacement.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Alexander Bruy' __date__ = 'July 2013' @@ -86,7 +87,7 @@ def processAlgorithm(self, progress): fullPerimeter = 2 * math.pi request = QgsFeatureRequest() - for (geom, fids) in duplicates.items(): + for (geom, fids) in list(duplicates.items()): count = len(fids) if count == 1: f = next(layer.getFeatures(request.setFilterFid(fids[0]))) diff --git a/python/plugins/processing/algs/qgis/PointsToPaths.py b/python/plugins/processing/algs/qgis/PointsToPaths.py index 74f65cab263c..04b03c22a1fa 100644 --- a/python/plugins/processing/algs/qgis/PointsToPaths.py +++ b/python/plugins/processing/algs/qgis/PointsToPaths.py @@ -106,7 +106,7 @@ def processAlgorithm(self, progress): current = 0 total = 100.0 / len(points) - for group, vertices in points.items(): + for group, vertices in list(points.items()): vertices.sort() f = QgsFeature() f.initAttributes(len(fields)) diff --git a/python/plugins/processing/algs/qgis/RandomExtract.py b/python/plugins/processing/algs/qgis/RandomExtract.py index f07e1ac3ec4e..1422e5e6082f 100644 --- a/python/plugins/processing/algs/qgis/RandomExtract.py +++ b/python/plugins/processing/algs/qgis/RandomExtract.py @@ -81,7 +81,7 @@ def processAlgorithm(self, progress): "different value and try again.")) value = int(round(value / 100.0000, 4) * featureCount) - selran = random.sample(range(featureCount), value) + selran = random.sample(list(range(featureCount)), value) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields().toList(), layer.wkbType(), layer.crs()) diff --git a/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py b/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py index 9d2f87d4495d..c5422acfed05 100644 --- a/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py +++ b/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Alexander Bruy' __date__ = 'April 2014' diff --git a/python/plugins/processing/algs/qgis/RandomPointsLayer.py b/python/plugins/processing/algs/qgis/RandomPointsLayer.py index 906756094622..730fcd377748 100644 --- a/python/plugins/processing/algs/qgis/RandomPointsLayer.py +++ b/python/plugins/processing/algs/qgis/RandomPointsLayer.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Alexander Bruy' __date__ = 'April 2014' diff --git a/python/plugins/processing/algs/qgis/RandomSelection.py b/python/plugins/processing/algs/qgis/RandomSelection.py index b0b64bf05cca..cfb6cb7a2a03 100644 --- a/python/plugins/processing/algs/qgis/RandomSelection.py +++ b/python/plugins/processing/algs/qgis/RandomSelection.py @@ -89,7 +89,7 @@ def processAlgorithm(self, progress): "different value and try again.")) value = int(round(value / 100.0, 4) * featureCount) - selran = random.sample(range(featureCount), value) + selran = random.sample(list(range(featureCount)), value) layer.selectByIds(selran) self.setOutputValue(self.OUTPUT, filename) diff --git a/python/plugins/processing/algs/qgis/SelectByAttributeSum.py b/python/plugins/processing/algs/qgis/SelectByAttributeSum.py index 0fd6b1ae93fc..8060419bad98 100644 --- a/python/plugins/processing/algs/qgis/SelectByAttributeSum.py +++ b/python/plugins/processing/algs/qgis/SelectByAttributeSum.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Alexander Bruy' __date__ = 'April 2015' diff --git a/python/plugins/processing/algs/qgis/SelectByLocation.py b/python/plugins/processing/algs/qgis/SelectByLocation.py index df69cb431e89..0adbed34d99c 100644 --- a/python/plugins/processing/algs/qgis/SelectByLocation.py +++ b/python/plugins/processing/algs/qgis/SelectByLocation.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py index b2f266461499..0bbc864e6421 100644 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -17,6 +17,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Bernhard Ströbl' __date__ = 'November 2014' diff --git a/python/plugins/processing/algs/qgis/SumLines.py b/python/plugins/processing/algs/qgis/SumLines.py index cbc143f6ee7a..f980c8c9427d 100644 --- a/python/plugins/processing/algs/qgis/SumLines.py +++ b/python/plugins/processing/algs/qgis/SumLines.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/Union.py b/python/plugins/processing/algs/qgis/Union.py index 9440bdfa3a97..3d378e12662f 100644 --- a/python/plugins/processing/algs/qgis/Union.py +++ b/python/plugins/processing/algs/qgis/Union.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' diff --git a/python/plugins/processing/algs/qgis/VoronoiPolygons.py b/python/plugins/processing/algs/qgis/VoronoiPolygons.py index a4e1a94b91bd..7c98de1cb575 100644 --- a/python/plugins/processing/algs/qgis/VoronoiPolygons.py +++ b/python/plugins/processing/algs/qgis/VoronoiPolygons.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import next __author__ = 'Victor Olaya' __date__ = 'August 2012' @@ -109,7 +110,7 @@ def processAlgorithm(self, progress): current = 0 total = 100.0 / len(c.polygons) - for (site, edges) in c.polygons.items(): + for (site, edges) in list(c.polygons.items()): request = QgsFeatureRequest().setFilterFid(ptDict[ids[site]]) inFeat = next(layer.getFeatures(request)) lines = self.clip_voronoi(edges, c, width, height, extent, extraX, extraY) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py index 02cb595c1adf..106926ba66f3 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py @@ -248,7 +248,7 @@ def createEditor(self, parent, option, index): fieldType = FieldsMappingModel.columns[column]['type'] if fieldType == QVariant.Type: editor = QComboBox(parent) - for key, text in FieldsMappingModel.fieldTypes.items(): + for key, text in list(FieldsMappingModel.fieldTypes.items()): editor.addItem(text, key) elif fieldType == QgsExpression: diff --git a/python/plugins/processing/algs/qgis/voronoi.py b/python/plugins/processing/algs/qgis/voronoi.py index 9f9963a09251..e05d2095c067 100644 --- a/python/plugins/processing/algs/qgis/voronoi.py +++ b/python/plugins/processing/algs/qgis/voronoi.py @@ -17,6 +17,7 @@ *************************************************************************** """ from __future__ import print_function +from builtins import next from past.builtins import cmp from builtins import str from builtins import range diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index a1b39766c92b..e7fbd43471d3 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -329,7 +329,7 @@ def evaluateParameterValues(self): for param in self.parameters: try: param.evaluate(self) - except ValueError, e: + except ValueError as e: traceback.print_exc() raise GeoAlgorithmExecutionException(str(e)) @@ -340,7 +340,7 @@ def resolveOutputs(self): try: for out in self.outputs: out.resolveValue(self) - except ValueError, e: + except ValueError as e: raise GeoAlgorithmExecutionException(str(e)) def setOutputCRS(self): diff --git a/python/plugins/processing/core/ProcessingLog.py b/python/plugins/processing/core/ProcessingLog.py index 8131f164b834..265e3f8a1957 100644 --- a/python/plugins/processing/core/ProcessingLog.py +++ b/python/plugins/processing/core/ProcessingLog.py @@ -135,7 +135,7 @@ def clearLog(): def saveLog(fileName): entries = ProcessingLog.getLogEntries() with codecs.open(fileName, 'w', encoding='utf-8') as f: - for k, v in entries.items(): + for k, v in list(entries.items()): for entry in v: f.write('%s|%s|%s\n' % (k, entry.date, entry.text)) diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index 34f66c360eb2..60fbee6f6d2e 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -398,7 +398,7 @@ def getOutputFromString(s): try: if "|" in s: tokens = s.split("|") - params = [t if unicode(t) != "None" else None for t in tokens[1:]] + params = [t if str(t) != "None" else None for t in tokens[1:]] clazz = getattr(sys.modules[__name__], tokens[0]) return clazz(*params) else: diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 2e483c22c363..a90e7c6a8124 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -119,7 +119,7 @@ def _resolveLayers(value): return ";".join(inputlayers) -class Parameter: +class Parameter(object): """ Base class for all parameters that a geoalgorithm might @@ -200,7 +200,7 @@ def tr(self, string, context=''): def wrapper(self, dialog, row=0, col=0): wrapper = self.metadata.get('widget_wrapper', None) # wrapper metadata should be a class path - if isinstance(wrapper, basestring): + if isinstance(wrapper, str): tokens = wrapper.split('.') mod = __import__('.'.join(tokens[:-1]), fromlist=[tokens[-1]]) wrapper = getattr(mod, tokens[-1]) @@ -830,7 +830,7 @@ def setValue(self, n): self.value = None return True - if isinstance(n, basestring): + if isinstance(n, str): try: v = self._evaluate(n) self.value = float(v) @@ -880,7 +880,7 @@ def _evaluate(self, value): return result def evaluate(self, alg): - if isinstance(self.value, basestring) and bool(self.value): + if isinstance(self.value, str) and bool(self.value): self.value = self._evaluate(self.value) def _layerVariables(self, element, alg=None): @@ -910,14 +910,14 @@ def evaluateForModeler(self, value, model): if isinstance(param, (ParameterRaster, ParameterVector)): variables.update(self._layerVariables(param)) - for alg in model.algs.values(): + for alg in list(model.algs.values()): for out in alg.algorithm.outputs: if isinstance(out, OutputNumber): variables["@%s_%s" % (alg.name, out.name)] = out.value if isinstance(out, (OutputRaster, OutputVector)): variables.update(self._layerVariables(out, alg)) - for k, v in variables.iteritems(): - value = value.replace(k, unicode(v)) + for k, v in list(variables.items()): + value = value.replace(k, str(v)) return value @@ -927,7 +927,7 @@ def expressionContext(self): def getValueAsCommandLineParameter(self): if self.value is None: return str(None) - if isinstance(self.value, basestring): + if isinstance(self.value, str): return '"%s"' + self.value return str(self.value) @@ -1191,7 +1191,7 @@ def fromScriptCode(self, line): return ParameterString(name, descName, multiline=True, optional=isOptional) def evaluate(self, alg): - if isinstance(self.value, basestring) and bool(self.value) and self.evaluateExpressions: + if isinstance(self.value, str) and bool(self.value) and self.evaluateExpressions: exp = QgsExpression(self.value) if exp.hasParserError(): raise ValueError(self.tr("Error in parameter expression: ") + exp.parserErrorString()) @@ -1502,7 +1502,7 @@ def setValue(self, value): return True -paramClasses = [c for c in sys.modules[__name__].__dict__.values() if isclass(c) and issubclass(c, Parameter)] +paramClasses = [c for c in list(sys.modules[__name__].__dict__.values()) if isclass(c) and issubclass(c, Parameter)] def getParameterFromString(s): @@ -1513,7 +1513,7 @@ def getParameterFromString(s): s = s[1:] isAdvanced = True tokens = s.split("|") - params = [t if unicode(t) != unicode(None) else None for t in tokens[1:]] + params = [t if str(t) != str(None) else None for t in tokens[1:]] try: clazz = getattr(sys.modules[__name__], tokens[0]) param = clazz(*params) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 786f44d8789a..aa13eca88781 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -28,8 +28,8 @@ __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import Qt -from qgis.PyQt.QtWidgets import QMessageBox, QApplication, QPushButton, QWidget, QVBoxLayout -from qgis.PyQt.QtGui import QCursor, QColor, QPalette, QSizePolicy +from qgis.PyQt.QtWidgets import QMessageBox, QApplication, QPushButton, QWidget, QVBoxLayout, QSizePolicy +from qgis.PyQt.QtGui import QCursor, QColor, QPalette from qgis.core import QgsMapLayerRegistry from qgis.gui import QgsMessageBar diff --git a/python/plugins/processing/gui/BatchAlgorithmDialog.py b/python/plugins/processing/gui/BatchAlgorithmDialog.py index 855462dea33b..3dcc62f89313 100644 --- a/python/plugins/processing/gui/BatchAlgorithmDialog.py +++ b/python/plugins/processing/gui/BatchAlgorithmDialog.py @@ -26,8 +26,8 @@ __revision__ = '$Format:%H$' -from qgis.PyQt.QtWidgets import QApplication, QMessageBox -from qgis.PyQt.QtGui import QCursor, QSizePolicy +from qgis.PyQt.QtWidgets import QApplication, QMessageBox, QSizePolicy +from qgis.PyQt.QtGui import QCursor from qgis.PyQt.QtCore import Qt from qgis.gui import QgsMessageBar diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index 52eb6747584a..b999d73ab81a 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -213,7 +213,7 @@ def save(self): return toSave.append({self.PARAMETERS: algParams, self.OUTPUTS: algOutputs}) - filename = unicode(QFileDialog.getSaveFileName(self, + filename, __ = str(QFileDialog.getSaveFileName(self, self.tr('Save batch'), None, self.tr('JSON files (*.json)'))) @@ -262,8 +262,8 @@ def addRow(self): item.setCurrentIndex(0) self.tblParameters.setCellWidget(row, column, item) - for wrapper in wrappers.values(): - wrapper.postInitialize(wrappers.values()) + for wrapper in list(wrappers.values()): + wrapper.postInitialize(list(wrappers.values())) def removeRows(self): if self.tblParameters.rowCount() > 2: diff --git a/python/plugins/processing/gui/LexerR.py b/python/plugins/processing/gui/LexerR.py index bc02348cc6df..1f509287ed64 100644 --- a/python/plugins/processing/gui/LexerR.py +++ b/python/plugins/processing/gui/LexerR.py @@ -52,7 +52,7 @@ def __init__(self, parent=None): 4: 'String', } - for (k, v) in self._styles.items(): + for (k, v) in list(self._styles.items()): setattr(self, v, k) def description(self, style): diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index d3e64e5bcade..d17aedc4a308 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import str from builtins import range __author__ = 'Victor Olaya' @@ -103,7 +104,7 @@ def showExpressionsBuilder(self): variables['%s_stddev' % name] = "Standard deviation of %s" % desc dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) - for variable, desc in variables.iteritems(): + for variable, desc in list(variables.items()): dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: @@ -119,7 +120,7 @@ def getValue(self): if isinstance(param, ParameterNumber): if "@" + param.name in value: values.append(ValueFromInput(param.name)) - for alg in self.modelParametersDialog.model.algs.values(): + for alg in list(self.modelParametersDialog.model.algs.values()): for out in alg.algorithm.outputs: if isinstance(out, OutputNumber) and "@%s_%s" % (alg.name, out.name) in value: values.append(ValueFromOutput(alg.name, out.name)) @@ -131,4 +132,4 @@ def getValue(self): return self.leText.text() def setValue(self, value): - self.leText.setText(unicode(value)) + self.leText.setText(str(value)) diff --git a/python/plugins/processing/gui/ParametersPanel.py b/python/plugins/processing/gui/ParametersPanel.py index f958ce28d6cf..20ed8b3e4934 100644 --- a/python/plugins/processing/gui/ParametersPanel.py +++ b/python/plugins/processing/gui/ParametersPanel.py @@ -78,7 +78,7 @@ def __init__(self, parent, alg): self.initWidgets() def layerRegistryChanged(self, layers): - for wrapper in self.wrappers.values(): + for wrapper in list(self.wrappers.values()): wrapper.refresh() def initWidgets(self): @@ -154,8 +154,8 @@ def initWidgets(self): self.checkBoxes[output.name] = check self.valueItems[output.name] = widget - for wrapper in self.wrappers.values(): - wrapper.postInitialize(self.wrappers.values()) + for wrapper in list(self.wrappers.values()): + wrapper.postInitialize(list(self.wrappers.values())) def buttonToggled(self, value): if value: diff --git a/python/plugins/processing/gui/ProcessingToolbox.py b/python/plugins/processing/gui/ProcessingToolbox.py index f216db586fdb..a691323fb6af 100644 --- a/python/plugins/processing/gui/ProcessingToolbox.py +++ b/python/plugins/processing/gui/ProcessingToolbox.py @@ -112,7 +112,7 @@ def textChanged(self): if text: self.algorithmTree.expandAll() self.disabledWithMatchingAlgs = [] - for providerName, provider in algList.algs.items(): + for providerName, provider in list(algList.algs.items()): name = 'ACTIVATE_' + providerName.upper().replace(' ', '_') if not ProcessingConfig.getSetting(name): for alg in list(provider.values()): diff --git a/python/plugins/processing/gui/ScriptEditorDialog.py b/python/plugins/processing/gui/ScriptEditorDialog.py index 291ab657845e..74751fcef67a 100644 --- a/python/plugins/processing/gui/ScriptEditorDialog.py +++ b/python/plugins/processing/gui/ScriptEditorDialog.py @@ -151,7 +151,7 @@ def decreaseFontSize(self): def showSnippets(self, evt): popupmenu = QMenu() - for name, snippet in self.snippets.items(): + for name, snippet in list(self.snippets.items()): action = QAction(self.tr(name), self.btnSnippets) action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet)) popupmenu.addAction(action) diff --git a/python/plugins/processing/gui/StringInputPanel.py b/python/plugins/processing/gui/StringInputPanel.py index 8a5c1d50db33..fdcce13cfaec 100644 --- a/python/plugins/processing/gui/StringInputPanel.py +++ b/python/plugins/processing/gui/StringInputPanel.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from builtins import str __author__ = 'Victor Olaya' __date__ = 'August 2016' @@ -70,4 +71,4 @@ def getValue(self): return self.leText.text() def setValue(self, value): - self.leText.setText(unicode(value)) + self.leText.setText(str(value)) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 2b9575a55fb3..025fc724cd7c 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -17,6 +17,8 @@ * * *************************************************************************** """ +from builtins import str +from builtins import range __author__ = 'Arnaud Morvan' @@ -121,7 +123,7 @@ def setComboValue(self, value): pass if self.widget.isEditable(): if value is not None: - self.widget.setEditText(unicode(value)) + self.widget.setEditText(str(value)) else: self.widget.setCurrentIndex(0) @@ -214,7 +216,7 @@ def setValue(self, value): if self.dialogType == DIALOG_MODELER: self.setComboValue(value) else: - if isinstance(value, basestring): # authId + if isinstance(value, str): # authId self.widget.crs = value else: self.widget.crs = QgsCoordinateReferenceSystem(value).authid() @@ -264,7 +266,7 @@ def value(self): else: idx = self.widget.findText(self.widget.currentText()) if idx < 0: - s = unicode(self.widget.currentText()).strip() + s = str(self.widget.currentText()).strip() if s: try: tokens = s.split(',') @@ -294,7 +296,7 @@ def createWidget(self): points = self.dialog.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.dialog.resolveValueDescription(p), p) - item.setEditText(unicode(self.param.default)) + item.setEditText(str(self.param.default)) return item def setValue(self, value): @@ -309,7 +311,7 @@ def value(self): else: idx = self.widget.findText(self.widget.currentText()) if idx < 0: - s = unicode(self.widget.currentText()).strip() + s = str(self.widget.currentText()).strip() if s: try: tokens = s.split(',') @@ -786,7 +788,7 @@ def parentValueChanged(self, wrapper): self.setLayer(wrapper.value()) def setLayer(self, layer): - if isinstance(layer, basestring): + if isinstance(layer, str): layer = dataobjects.getObjectFromUri(_resolveLayers(layer)) self._layer = layer self.refreshItems() @@ -813,7 +815,7 @@ def getFields(self): fieldNames = set() for field in self._layer.fields(): if not fieldTypes or field.type() in fieldTypes: - fieldNames.add(unicode(field.name())) + fieldNames.add(str(field.name())) return sorted(list(fieldNames), key=cmp_to_key(locale.strcoll)) def setValue(self, value): diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index 6b908fb0abf2..cbf5c38c59b6 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -116,7 +116,7 @@ def __init__(self, consoleName=""): self.active = True def todict(self): - return {k: v for k, v in self.__dict__.items() if not k.startswith("_")} + return {k: v for k, v in list(self.__dict__.items()) if not k.startswith("_")} @property def algorithm(self): @@ -205,7 +205,7 @@ def asPythonParameter(self): return "outputs_%s['%s']" % (self.alg, self.output) -class CompoundValue(): +class CompoundValue(object): def __init__(self, values=[], definition=""): self.values = values @@ -401,12 +401,12 @@ def getDependentAlgorithms(self, name): return algs def setPositions(self, paramPos, algPos, outputsPos): - for param, pos in paramPos.items(): + for param, pos in list(paramPos.items()): self.inputs[param].pos = pos - for alg, pos in algPos.items(): + for alg, pos in list(algPos.items()): self.algs[alg].pos = pos - for alg, positions in outputsPos.items(): - for output, pos in positions.items(): + for alg, positions in list(outputsPos.items()): + for output, pos in list(positions.items()): self.algs[alg].outputs[output].pos = pos def prepareAlgorithm(self, alg): @@ -553,7 +553,7 @@ def getParameterDescriptions(self): def todict(self): keys = ["inputs", "group", "name", "algs", "helpContent"] - return {k: v for k, v in self.__dict__.items() if k in keys} + return {k: v for k, v in list(self.__dict__.items()) if k in keys} def toJson(self): def todict(o): @@ -587,7 +587,7 @@ def _import(name): module = _import(moduleName) clazz = getattr(module, className) instance = clazz() - for k, v in values.items(): + for k, v in list(values.items()): instance.__dict__[k] = v return instance except KeyError: @@ -613,7 +613,7 @@ def toPython(self): for param in list(self.inputs.values()): s.append(param.param.getAsScriptCode()) for alg in list(self.algs.values()): - for name, out in alg.outputs.items(): + for name, out in list(alg.outputs.items()): s.append('##%s=%s' % (safeName(out.description).lower(), alg.getOutputType(name))) executed = [] diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index 91ab29b51670..bfe942a55e9d 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -32,8 +32,8 @@ from qgis.PyQt import uic from qgis.PyQt.QtCore import Qt, QRectF, QMimeData, QPoint, QPointF, QSettings, QByteArray -from qgis.PyQt.QtWidgets import QGraphicsView, QTreeWidget, QMessageBox, QFileDialog, QTreeWidgetItem -from qgis.PyQt.QtGui import QIcon, QImage, QPainter, QSizePolicy +from qgis.PyQt.QtWidgets import QGraphicsView, QTreeWidget, QMessageBox, QFileDialog, QTreeWidgetItem, QSizePolicy +from qgis.PyQt.QtGui import QIcon, QImage, QPainter from qgis.core import QgsApplication from qgis.gui import QgsMessageBar from processing.core.ProcessingConfig import ProcessingConfig diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 52fe11c608fb..7d2a911be10b 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -187,7 +187,7 @@ def setupUi(self): if self.param.isInteger: default = int(math.floor(default)) if default: - self.defaultTextBox.setText(unicode(default)) + self.defaultTextBox.setText(str(default)) self.verticalLayout.addWidget(self.defaultTextBox) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or isinstance(self.param, ParameterString)): @@ -291,20 +291,12 @@ def okPressed(self): elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or isinstance(self.param, ParameterNumber)): try: -<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe - vmin = str(self.minTextBox.text()).strip() -======= vmin = self.minTextBox.text().strip() ->>>>>>> [processing] UI improvement for defining model parameters if vmin == '': vmin = None else: vmin = float(vmin) -<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe - vmax = str(self.maxTextBox.text()).strip() -======= vmax = self.maxTextBox.text().strip() ->>>>>>> [processing] UI improvement for defining model parameters if vmax == '': vmax = None else: @@ -318,15 +310,9 @@ def okPressed(self): elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or isinstance(self.param, ParameterString)): self.param = ParameterString(name, description, -<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe str(self.defaultTextBox.text())) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \ - isinstance(self.param, ParameterExtent): -======= - unicode(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or isinstance(self.param, ParameterExtent)): ->>>>>>> [processing] UI improvement for defining model parameters self.param = ParameterExtent(name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or isinstance(self.param, ParameterFile)): @@ -335,19 +321,11 @@ def okPressed(self): elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or isinstance(self.param, ParameterPoint)): self.param = ParameterPoint(name, description, -<<<<<<< 8d5f46e6e491417b3449d4beca6ad490e6d2c5fe str(self.defaultTextBox.text())) - elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or \ - isinstance(self.param, ParameterCrs): - self.param = ParameterCrs(name, description, self.defaultTextBox.getValue(), self.yesNoCombo.currentIndex() == 1) - self.param.optional = self.yesNoCombo.currentIndex() == 1 -======= - unicode(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or isinstance(self.param, ParameterCrs)): self.param = ParameterCrs(name, description, self.defaultTextBox.getValue()) self.param.optional = self.requiredCheck.isChecked() ->>>>>>> [processing] UI improvement for defining model parameters self.close() def cancelPressed(self): diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index e8652ab870db..183201446fc2 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -33,10 +33,10 @@ QFrame, QPushButton, QSizePolicy, QVBoxLayout, QHBoxLayout, QTabWidget, QWidget, QScrollArea, QComboBox, QTableWidgetItem, QMessageBox, - QTextBrowser) + QTextBrowser, QToolButton, QMenu, QAction) from qgis.PyQt.QtNetwork import QNetworkRequest, QNetworkReply -from qgis.core import QgsNetworkAccessManager +from qgis.core import QgsApplication, QgsNetworkAccessManager from qgis.gui import QgsMessageBar @@ -60,10 +60,6 @@ ModelerOutput) -from qgis.core import QgsApplication -from qgis.PyQt.QtGui import QToolButton, QMenu, QAction - - class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' @@ -226,8 +222,8 @@ def setupUi(self): self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) - for wrapper in self.wrappers.values(): - wrapper.postInitialize(self.wrappers.values()) + for wrapper in list(self.wrappers.values()): + wrapper.postInitialize(list(self.wrappers.values())) def requestFinished(self): """Change the webview HTML content""" @@ -339,7 +335,7 @@ def setPreviousValues(self): else: value = param.default self.wrappers[param.name].setValue(value) - for name, out in alg.outputs.items(): + for name, out in list(alg.outputs.items()): self.valueItems[name].setText(out.description) selected = [] diff --git a/python/plugins/processing/modeler/ModelerScene.py b/python/plugins/processing/modeler/ModelerScene.py index 9d1d37ffc863..280c3a757b9d 100644 --- a/python/plugins/processing/modeler/ModelerScene.py +++ b/python/plugins/processing/modeler/ModelerScene.py @@ -43,16 +43,16 @@ def __init__(self, parent=None): self.setItemIndexMethod(QGraphicsScene.NoIndex) def getParameterPositions(self): - return {key: item.pos() for key, item in self.paramItems.items()} + return {key: item.pos() for key, item in list(self.paramItems.items())} def getAlgorithmPositions(self): - return {key: item.pos() for key, item in self.algItems.items()} + return {key: item.pos() for key, item in list(self.algItems.items())} def getOutputPositions(self): pos = {} - for algName, outputs in self.outputItems.items(): + for algName, outputs in list(self.outputItems.items()): outputPos = {} - for (key, value) in outputs.items(): + for (key, value) in list(outputs.items()): if value is not None: outputPos[key] = value.pos() else: diff --git a/python/plugins/processing/preconfigured/PreconfiguredAlgorithm.py b/python/plugins/processing/preconfigured/PreconfiguredAlgorithm.py index e2739a6b90e6..619bb53e0c63 100644 --- a/python/plugins/processing/preconfigured/PreconfiguredAlgorithm.py +++ b/python/plugins/processing/preconfigured/PreconfiguredAlgorithm.py @@ -59,9 +59,9 @@ def defineCharacteristics(self): def execute(self, progress): self.alg = algList.getAlgorithm(self.description["algname"]).getCopy() - for name, value in self.description["parameters"].items(): + for name, value in list(self.description["parameters"].items()): self.alg.setParameterValue(name, value) - for name, value in self.description["outputs"].items(): + for name, value in list(self.description["outputs"].items()): self.alg.setOutputValue(name, value) self.alg.execute(progress) self.outputs = self.alg.outputs diff --git a/python/plugins/processing/script/ScriptSelector.py b/python/plugins/processing/script/ScriptSelector.py index 204e351ab1d7..851b53f2f830 100644 --- a/python/plugins/processing/script/ScriptSelector.py +++ b/python/plugins/processing/script/ScriptSelector.py @@ -51,7 +51,7 @@ def __init__(self): for script in alglist: allScripts[script.group].append(script) - for group, groupScripts in allScripts.items(): + for group, groupScripts in list(allScripts.items()): groupItem = QTreeWidgetItem() groupItem.setText(0, group) groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate) diff --git a/python/plugins/processing/tools/translation.py b/python/plugins/processing/tools/translation.py index 44347270c621..afcae1b70660 100644 --- a/python/plugins/processing/tools/translation.py +++ b/python/plugins/processing/tools/translation.py @@ -76,7 +76,7 @@ def translationShadow(): f.write(''' """Groups and subgroups""" ''') - for group, context in groups.items(): + for group, context in list(groups.items()): f.write(" QCoreApplication.translate(\"{}\", \"{}\")\n" .format(context, group.replace('"', '\\"'))) From bc0cdc7b0df24b817e7447a30e56c445c10fee6f Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 4 Oct 2016 08:56:57 +0200 Subject: [PATCH 169/897] [processing] fixed handling of integer values --- python/plugins/processing/core/parameters.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index a90e7c6a8124..02a8636e203a 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -30,6 +30,7 @@ import sys import os +import math from inspect import isclass from copy import deepcopy import numbers @@ -834,6 +835,8 @@ def setValue(self, n): try: v = self._evaluate(n) self.value = float(v) + if self.isInteger: + self.value = int(math.floor(self.value)) return True except: return False @@ -877,7 +880,10 @@ def _evaluate(self, value): result = exp.evaluate(_expressionContext()) if exp.hasEvalError(): raise ValueError("Error evaluating parameter expression: " + exp.evalErrorString()) - return result + if self.isInteger: + return math.floor(result) + else: + return result def evaluate(self, alg): if isinstance(self.value, str) and bool(self.value): From 2207669001928a06d01ddeb747bb6f0e285b8e89 Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 4 Oct 2016 08:57:18 +0200 Subject: [PATCH 170/897] [processing] fixed expressions dialog when not in modeler --- python/plugins/processing/gui/NumberInputPanel.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index d17aedc4a308..92bc1f09f86a 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -66,6 +66,7 @@ def __init__(self, param, modelParametersDialog=None): def showExpressionsBuilder(self): context = self.param.expressionContext() + dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) if self.modelParametersDialog is not None: context.popScope() values = self.modelParametersDialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) @@ -102,10 +103,8 @@ def showExpressionsBuilder(self): variables['%s_max' % name] = "Maximum value of %s" % desc variables['%s_avg' % name] = "Mean value of %s" % desc variables['%s_stddev' % name] = "Standard deviation of %s" % desc - - dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) - for variable, desc in list(variables.items()): - dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) + for variable, desc in variables.iteritems(): + dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: exp = QgsExpression(dlg.expressionText()) From b642c3ff5ede2cae88d30f881f7ae7c99e1bfccc Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 5 Oct 2016 13:41:03 +0200 Subject: [PATCH 171/897] Show fields in "default value" expression editor --- src/app/qgsattributetypedialog.cpp | 2 ++ src/gui/qgsexpressionlineedit.cpp | 3 +++ src/gui/qgsexpressionlineedit.h | 32 ++++++++++++++++++++---------- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 4f242c61d2b2..5d3748d648e4 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -69,6 +69,8 @@ QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl, int fieldIdx isFieldEditableCheckBox->setEnabled( false ); } + mExpressionWidget->setLayer( vl ); + connect( mExpressionWidget, SIGNAL( expressionChanged( QString ) ), this, SLOT( defaultExpressionChanged() ) ); QSettings settings; diff --git a/src/gui/qgsexpressionlineedit.cpp b/src/gui/qgsexpressionlineedit.cpp index cf5ae564751e..e54279027fb4 100644 --- a/src/gui/qgsexpressionlineedit.cpp +++ b/src/gui/qgsexpressionlineedit.cpp @@ -20,6 +20,7 @@ #include "qgsexpressionbuilderdialog.h" #include "qgsexpressioncontextgenerator.h" #include "qgscodeeditorsql.h" +#include "qgsvectorlayer.h" #include #include #include @@ -113,6 +114,8 @@ void QgsExpressionLineEdit::setGeomCalculator( const QgsDistanceArea &da ) void QgsExpressionLineEdit::setLayer( QgsVectorLayer* layer ) { + if ( !mExpressionContextGenerator || mExpressionContextGenerator == mLayer ) + mExpressionContextGenerator = layer; mLayer = layer; } diff --git a/src/gui/qgsexpressionlineedit.h b/src/gui/qgsexpressionlineedit.h index 7979f6cc3ea2..eb6faff90aca 100644 --- a/src/gui/qgsexpressionlineedit.h +++ b/src/gui/qgsexpressionlineedit.h @@ -54,35 +54,44 @@ class GUI_EXPORT QgsExpressionLineEdit : public QWidget */ explicit QgsExpressionLineEdit( QWidget *parent = nullptr ); - /** Sets the title used in the expression builder dialog + /** + * Sets the title used in the expression builder dialog * @param title dialog title * @see expressionDialogTitle() */ void setExpressionDialogTitle( const QString& title ); - /** Returns the title used for the expression dialog. + /** + * Returns the title used for the expression dialog. * @see setExpressionDialogTitle() */ QString expressionDialogTitle() const { return mExpressionDialogTitle; } - /** Sets whether the widget should show a multiline text editor. + /** + * Sets whether the widget should show a multiline text editor. * @param multiLine set to true to show multiline editor, or false * to show single line editor (the default). */ void setMultiLine( bool multiLine ); - /** Set the geometry calculator used in the expression dialog. + /** + * Set the geometry calculator used in the expression dialog. * @param distanceArea calculator */ void setGeomCalculator( const QgsDistanceArea &distanceArea ); - /** Sets a layer associated with the widget. Required in order to get the fields and values - * from the layer. - * @param layer vector layer - */ + /** + * Sets a layer associated with the widget. Required in order to get the fields and values + * from the layer. + * This will also automatically register the layer as expression context generator if + * no generator has been set before or the previous layer has been used as generator. + * + * @see registerExpressionContextGenerator + */ void setLayer( QgsVectorLayer* layer ); - /** Returns the current expression shown in the widget. + /** + * Returns the current expression shown in the widget. * @see setExpression() */ QString expression() const; @@ -110,16 +119,19 @@ class GUI_EXPORT QgsExpressionLineEdit : public QWidget public slots: - /** Sets the current expression to show in the widget. + /** + * Sets the current expression to show in the widget. * @param expression expression string * @see expression() */ void setExpression( const QString& expression ); protected: + void changeEvent( QEvent* event ) override; private slots: + //! When the expression is edited by the user in the line edit, it will be checked for validity void expressionEdited( const QString& expression ); void expressionEdited(); From 3767cd4819271b7247041c7945fe89cddf8095c8 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 3 Oct 2016 09:01:34 +0200 Subject: [PATCH 172/897] Debloat QgsExpression header it's used throughout the project and keeping it slick should keep compile time a little lower. These methods are also normally used while building the request or preparing, so inlining them shouldn't make much difference. --- src/core/qgsexpression.cpp | 170 +++++++++++++++++++++++++++++++++++++ src/core/qgsexpression.h | 134 +++-------------------------- 2 files changed, 181 insertions(+), 123 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index c8ac0939ce24..725a2fef904e 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3824,6 +3824,14 @@ QStringList QgsExpression::referencedColumns() const return columns; } +bool QgsExpression::NodeInOperator::needsGeometry() const +{ + bool needs = false; + Q_FOREACH ( Node* n, mList->list() ) + needs |= n->needsGeometry(); + return needs; +} + QSet QgsExpression::referencedAttributeIndexes( const QgsFields& fields ) const { if ( !d->mRootNode ) @@ -4056,6 +4064,13 @@ double QgsExpression::evaluateToDouble( const QString &text, const double fallba /////////////////////////////////////////////// // nodes +void QgsExpression::NodeList::append( QgsExpression::NamedNode* node ) +{ + mList.append( node->node ); + mNameList.append( node->name.toLower() ); + mHasNamedNodes = true; +} + QgsExpression::NodeList* QgsExpression::NodeList::clone() const { NodeList* nl = new NodeList; @@ -4603,6 +4618,21 @@ QString QgsExpression::NodeBinaryOperator::dump() const return fmt.arg( mOpLeft->dump(), BinaryOperatorText[mOp], rdump ); } +QStringList QgsExpression::NodeBinaryOperator::referencedColumns() const +{ + return mOpLeft->referencedColumns() + mOpRight->referencedColumns(); +} + +bool QgsExpression::NodeBinaryOperator::needsGeometry() const +{ + return mOpLeft->needsGeometry() || mOpRight->needsGeometry(); +} + +void QgsExpression::NodeBinaryOperator::accept( QgsExpression::Visitor& v ) const +{ + v.visit( *this ); +} + QgsExpression::Node* QgsExpression::NodeBinaryOperator::clone() const { return new NodeBinaryOperator( mOp, mOpLeft->clone(), mOpRight->clone() ); @@ -4718,6 +4748,46 @@ QVariant QgsExpression::NodeFunction::eval( QgsExpression *parent, const QgsExpr return res; } +QgsExpression::NodeFunction::NodeFunction( int fnIndex, QgsExpression::NodeList* args ) + : mFnIndex( fnIndex ) +{ + const ParameterList& functionParams = Functions()[mFnIndex]->parameters(); + if ( !args || functionParams.isEmpty() ) + { + // no parameters, or function does not support them + mArgs = args; + } + else + { + mArgs = new NodeList(); + + int idx = 0; + //first loop through unnamed arguments + while ( idx < args->names().size() && args->names().at( idx ).isEmpty() ) + { + mArgs->append( args->list().at( idx )->clone() ); + idx++; + } + + //next copy named parameters in order expected by function + for ( ; idx < functionParams.count(); ++idx ) + { + int nodeIdx = args->names().indexOf( functionParams.at( idx ).name().toLower() ); + if ( nodeIdx < 0 ) + { + //parameter not found - insert default value for parameter + mArgs->append( new NodeLiteral( functionParams.at( idx ).defaultValue() ) ); + } + else + { + mArgs->append( args->list().at( nodeIdx )->clone() ); + } + } + + delete args; + } +} + bool QgsExpression::NodeFunction::prepare( QgsExpression *parent, const QgsExpressionContext *context ) { Function* fd = Functions()[mFnIndex]; @@ -4762,11 +4832,95 @@ QStringList QgsExpression::NodeFunction::referencedColumns() const return functionColumns.toSet().toList(); } +bool QgsExpression::NodeFunction::needsGeometry() const +{ + bool needs = Functions()[mFnIndex]->usesGeometry(); + if ( mArgs ) + { + Q_FOREACH ( Node* n, mArgs->list() ) + needs |= n->needsGeometry(); + } + return needs; +} + QgsExpression::Node* QgsExpression::NodeFunction::clone() const { return new NodeFunction( mFnIndex, mArgs ? mArgs->clone() : nullptr ); } +bool QgsExpression::NodeFunction::validateParams( int fnIndex, QgsExpression::NodeList* args, QString& error ) +{ + if ( !args || !args->hasNamedNodes() ) + return true; + + const ParameterList& functionParams = Functions()[fnIndex]->parameters(); + if ( functionParams.isEmpty() ) + { + error = QString( "%1 does not supported named parameters" ).arg( Functions()[fnIndex]->name() ); + return false; + } + else + { + QSet< int > providedArgs; + QSet< int > handledArgs; + int idx = 0; + //first loop through unnamed arguments + while ( args->names().at( idx ).isEmpty() ) + { + providedArgs << idx; + handledArgs << idx; + idx++; + } + + //next check named parameters + for ( ; idx < functionParams.count(); ++idx ) + { + int nodeIdx = args->names().indexOf( functionParams.at( idx ).name().toLower() ); + if ( nodeIdx < 0 ) + { + if ( !functionParams.at( idx ).optional() ) + { + error = QString( "No value specified for parameter '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); + return false; + } + } + else + { + if ( providedArgs.contains( idx ) ) + { + error = QString( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); + return false; + } + } + providedArgs << idx; + handledArgs << nodeIdx; + } + + //last check for bad names + idx = 0; + Q_FOREACH ( const QString& name, args->names() ) + { + if ( !name.isEmpty() && !functionParams.contains( name ) ) + { + error = QString( "Invalid parameter name '%1' for %2" ).arg( name, Functions()[fnIndex]->name() ); + return false; + } + if ( !name.isEmpty() && !handledArgs.contains( idx ) ) + { + int functionIdx = functionParams.indexOf( name ); + if ( providedArgs.contains( functionIdx ) ) + { + error = QString( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( functionIdx ).name(), Functions()[fnIndex]->name() ); + return false; + } + } + idx++; + } + + } + return true; +} + // QVariant QgsExpression::NodeLiteral::eval( QgsExpression *parent, const QgsExpressionContext *context ) @@ -5294,3 +5448,19 @@ const QgsExpression::Node* QgsExpression::rootNode() const { return d->mRootNode; } + +QStringList QgsExpression::NodeInOperator::referencedColumns() const +{ + QStringList lst( mNode->referencedColumns() ); + Q_FOREACH ( const Node* n, mList->list() ) + lst.append( n->referencedColumns() ); + return lst; +} + +bool QgsExpression::Function::operator==( const QgsExpression::Function& other ) const +{ + if ( QString::compare( mName, other.mName, Qt::CaseInsensitive ) == 0 ) + return true; + + return false; +} diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index 663f3e47e884..ffe63200e662 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -555,13 +555,7 @@ class CORE_EXPORT QgsExpression */ virtual QVariant func( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ) = 0; - bool operator==( const Function& other ) const - { - if ( QString::compare( mName, other.mName, Qt::CaseInsensitive ) == 0 ) - return true; - - return false; - } + bool operator==( const Function& other ) const; virtual bool handlesNull() const { return mHandlesNull; } @@ -830,7 +824,7 @@ class CORE_EXPORT QgsExpression /** Adds a named node. Takes ownership of the provided node. * @note added in QGIS 2.16 */ - void append( NamedNode* node ) { mList.append( node->node ); mNameList.append( node->name.toLower() ); mHasNamedNodes = true; } + void append( NamedNode* node ); /** Returns the number of nodes in the list. */ @@ -909,8 +903,8 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override { return mOpLeft->referencedColumns() + mOpRight->referencedColumns(); } - virtual bool needsGeometry() const override { return mOpLeft->needsGeometry() || mOpRight->needsGeometry(); } + virtual QStringList referencedColumns() const override; + virtual bool needsGeometry() const override; virtual Node* clone() const override; int precedence() const; @@ -953,8 +947,8 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override { QStringList lst( mNode->referencedColumns() ); Q_FOREACH ( const Node* n, mList->list() ) lst.append( n->referencedColumns() ); return lst; } - virtual bool needsGeometry() const override { bool needs = false; Q_FOREACH ( Node* n, mList->list() ) needs |= n->needsGeometry(); return needs; } + virtual QStringList referencedColumns() const override; + virtual bool needsGeometry() const override; virtual Node* clone() const override; protected: @@ -968,44 +962,7 @@ class CORE_EXPORT QgsExpression class CORE_EXPORT NodeFunction : public Node { public: - NodeFunction( int fnIndex, NodeList* args ) : mFnIndex( fnIndex ) - { - const ParameterList& functionParams = Functions()[mFnIndex]->parameters(); - if ( !args || functionParams.isEmpty() ) - { - // no parameters, or function does not support them - mArgs = args; - } - else - { - mArgs = new NodeList(); - - int idx = 0; - //first loop through unnamed arguments - while ( idx < args->names().size() && args->names().at( idx ).isEmpty() ) - { - mArgs->append( args->list().at( idx )->clone() ); - idx++; - } - - //next copy named parameters in order expected by function - for ( ; idx < functionParams.count(); ++idx ) - { - int nodeIdx = args->names().indexOf( functionParams.at( idx ).name().toLower() ); - if ( nodeIdx < 0 ) - { - //parameter not found - insert default value for parameter - mArgs->append( new NodeLiteral( functionParams.at( idx ).defaultValue() ) ); - } - else - { - mArgs->append( args->list().at( nodeIdx )->clone() ); - } - } - - delete args; - } - } + NodeFunction( int fnIndex, NodeList* args ); virtual ~NodeFunction() { delete mArgs; } @@ -1018,82 +975,11 @@ class CORE_EXPORT QgsExpression virtual QString dump() const override; virtual QStringList referencedColumns() const override; - virtual bool needsGeometry() const override { bool needs = Functions()[mFnIndex]->usesGeometry(); if ( mArgs ) { Q_FOREACH ( Node* n, mArgs->list() ) needs |= n->needsGeometry(); } return needs; } + virtual bool needsGeometry() const override; virtual Node* clone() const override; //! Tests whether the provided argument list is valid for the matching function - static bool validateParams( int fnIndex, NodeList* args, QString& error ) - { - if ( !args || !args->hasNamedNodes() ) - return true; - - const ParameterList& functionParams = Functions()[fnIndex]->parameters(); - if ( functionParams.isEmpty() ) - { - error = QString( "%1 does not supported named parameters" ).arg( Functions()[fnIndex]->name() ); - return false; - } - else - { - QSet< int > providedArgs; - QSet< int > handledArgs; - int idx = 0; - //first loop through unnamed arguments - while ( args->names().at( idx ).isEmpty() ) - { - providedArgs << idx; - handledArgs << idx; - idx++; - } - - //next check named parameters - for ( ; idx < functionParams.count(); ++idx ) - { - int nodeIdx = args->names().indexOf( functionParams.at( idx ).name().toLower() ); - if ( nodeIdx < 0 ) - { - if ( !functionParams.at( idx ).optional() ) - { - error = QString( "No value specified for parameter '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); - return false; - } - } - else - { - if ( providedArgs.contains( idx ) ) - { - error = QString( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); - return false; - } - } - providedArgs << idx; - handledArgs << nodeIdx; - } - - //last check for bad names - idx = 0; - Q_FOREACH ( const QString& name, args->names() ) - { - if ( !name.isEmpty() && !functionParams.contains( name ) ) - { - error = QString( "Invalid parameter name '%1' for %2" ).arg( name, Functions()[fnIndex]->name() ); - return false; - } - if ( !name.isEmpty() && !handledArgs.contains( idx ) ) - { - int functionIdx = functionParams.indexOf( name ); - if ( providedArgs.contains( functionIdx ) ) - { - error = QString( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( functionIdx ).name(), Functions()[fnIndex]->name() ); - return false; - } - } - idx++; - } - - } - return true; - } + static bool validateParams( int fnIndex, NodeList* args, QString& error ); protected: int mFnIndex; @@ -1333,6 +1219,8 @@ class CORE_EXPORT QgsExpression friend class QgsOgcUtils; }; + + Q_DECLARE_METATYPE( QgsExpression::Node* ) #endif // QGSEXPRESSION_H From 722fdefe436641ff9b85eb647dbbe51a4d4f155c Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 3 Oct 2016 10:39:41 +0200 Subject: [PATCH 173/897] referencedColumns returns QSet instead of QStringList The order of the elements is irrelevant and duplicate elements are unwanted. It is therefore a perfect candidate for a set instead of a list. This prevents filtering for duplicates manually be replacing some filer codes with (more performant) builtin methods of QSet. --- doc/api_break.dox | 5 + python/core/qgsdatadefined.sip | 2 +- python/core/qgsexpression.sip | 24 +-- python/core/qgsexpressioncontext.sip | 2 +- python/core/qgspallabeling.sip | 12 +- python/core/symbology-ng/qgs25drenderer.sip | 2 +- .../qgscategorizedsymbolrenderer.sip | 2 +- .../qgsgraduatedsymbolrenderer.sip | 2 +- .../core/symbology-ng/qgsheatmaprenderer.sip | 2 +- .../qgsinvertedpolygonrenderer.sip | 2 +- .../symbology-ng/qgsnullsymbolrenderer.sip | 2 +- .../symbology-ng/qgspointclusterrenderer.sip | 2 +- .../qgspointdisplacementrenderer.sip | 2 +- .../symbology-ng/qgspointdistancerenderer.sip | 2 +- python/core/symbology-ng/qgsrenderer.sip | 4 +- .../symbology-ng/qgsrulebasedrenderer.sip | 2 +- .../symbology-ng/qgssinglesymbolrenderer.sip | 2 +- src/core/dxf/qgsdxfexport.cpp | 7 +- src/core/qgsaggregatecalculator.cpp | 4 +- src/core/qgsdatadefined.cpp | 2 +- src/core/qgsdatadefined.h | 2 +- src/core/qgsdatadefined_p.h | 2 +- src/core/qgsexpression.cpp | 152 ++++++++---------- src/core/qgsexpression.h | 30 ++-- src/core/qgsexpressioncontext.h | 7 +- src/core/qgsfeaturerequest.cpp | 23 ++- src/core/qgsfeaturerequest.h | 3 + src/core/qgspallabeling.cpp | 4 +- src/core/qgspallabeling.h | 8 +- src/core/qgsrulebasedlabeling.cpp | 6 +- src/core/qgsrulebasedlabeling.h | 4 +- src/core/qgsvectorfilewriter.cpp | 8 +- src/core/qgsvectorlayer.cpp | 4 +- src/core/qgsvectorlayerdiagramprovider.cpp | 10 +- src/core/qgsvectorlayerdiagramprovider.h | 2 +- src/core/qgsvectorlayerlabelprovider.cpp | 12 +- src/core/qgsvectorlayerlabelprovider.h | 2 +- src/core/qgsvectorlayerrenderer.cpp | 4 +- src/core/qgsvectorlayerrenderer.h | 6 +- src/core/symbology-ng/qgs25drenderer.cpp | 4 +- src/core/symbology-ng/qgs25drenderer.h | 2 +- .../qgscategorizedsymbolrenderer.cpp | 6 +- .../qgscategorizedsymbolrenderer.h | 2 +- .../qgsgeometrygeneratorsymbollayer.cpp | 2 +- .../qgsgraduatedsymbolrenderer.cpp | 6 +- .../symbology-ng/qgsgraduatedsymbolrenderer.h | 2 +- src/core/symbology-ng/qgsheatmaprenderer.cpp | 6 +- src/core/symbology-ng/qgsheatmaprenderer.h | 2 +- .../qgsinvertedpolygonrenderer.cpp | 4 +- .../symbology-ng/qgsinvertedpolygonrenderer.h | 2 +- .../symbology-ng/qgsnullsymbolrenderer.cpp | 4 +- src/core/symbology-ng/qgsnullsymbolrenderer.h | 2 +- .../symbology-ng/qgspointclusterrenderer.cpp | 6 +- .../symbology-ng/qgspointclusterrenderer.h | 2 +- .../qgspointdisplacementrenderer.cpp | 6 +- .../qgspointdisplacementrenderer.h | 2 +- .../symbology-ng/qgspointdistancerenderer.cpp | 6 +- .../symbology-ng/qgspointdistancerenderer.h | 2 +- src/core/symbology-ng/qgsrenderer.h | 3 +- .../symbology-ng/qgsrulebasedrenderer.cpp | 7 +- src/core/symbology-ng/qgsrulebasedrenderer.h | 2 +- .../symbology-ng/qgssinglesymbolrenderer.cpp | 7 +- .../symbology-ng/qgssinglesymbolrenderer.h | 2 +- src/core/symbology-ng/qgssymbollayer.cpp | 6 +- .../qgsrelationreferencewidget.cpp | 4 +- src/gui/symbology-ng/qgssizescalewidget.cpp | 2 +- tests/src/core/testqgsdatadefined.cpp | 10 +- tests/src/core/testqgsexpression.cpp | 4 +- tests/src/core/testqgslabelingengine.cpp | 4 +- tests/src/python/test_qgsexpression.py | 3 +- 70 files changed, 250 insertions(+), 245 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index dc5ecb545f6b..8c97fd9f696d 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -710,6 +710,9 @@ version instead.
                                                                                                                                                                                  • helptext() has been renamed to helpText()
                                                                                                                                                                                  • isValid() has been renamed to checkExpression()
                                                                                                                                                                                  • acceptVisitor() has been removed
                                                                                                                                                                                  • +
                                                                                                                                                                                  • QgsExpression::referencedColumns() returns QSet instead of QStringList
                                                                                                                                                                                  • +
                                                                                                                                                                                  • QgsExpression::Node::referencedColumns() returns QSet instead of QStringList
                                                                                                                                                                                  • +
                                                                                                                                                                                  • QgsExpression::Function::referencedColumns() returns QSet instead of QStringList
                                                                                                                                                                                  • \subsection qgis_api_break_3_0_QgsFeature QgsFeature @@ -1482,6 +1485,8 @@ optional property map passing down layer level properties to the SLD encoders. I scaleMinDenom and scaleMaxDenom properties.
                                                                                                                                                                                  • The RotationField capabitity was removed. This is now handled using data defined rotation at a symbol layer level
                                                                                                                                                                                  • setScaleMethodToSymbol was removed. This is now handled using data defined scaling at a symbol layer level
                                                                                                                                                                                  • +
                                                                                                                                                                                  • setScaleMethodToSymbol was removed. This is now handled using data defined scaling at a symbol layer level
                                                                                                                                                                                  • +
                                                                                                                                                                                  • usedAttributes is now a const method and returns QSet instead of QStringList
                                                                                                                                                                                  • diff --git a/python/core/qgsdatadefined.sip b/python/core/qgsdatadefined.sip index f753eda2af8d..f769081fdea7 100644 --- a/python/core/qgsdatadefined.sip +++ b/python/core/qgsdatadefined.sip @@ -128,7 +128,7 @@ class QgsDataDefined * @param context expression context, used for preparing the expression if required * @note added in QGIS 2.12 */ - QStringList referencedColumns( const QgsExpressionContext& context = QgsExpressionContext() ); + QSet referencedColumns( const QgsExpressionContext& context = QgsExpressionContext() ); /** * Get the field which this QgsDataDefined represents. Be aware that this may return diff --git a/python/core/qgsexpression.sip b/python/core/qgsexpression.sip index caa560ef0c9a..f4dc271ecd86 100644 --- a/python/core/qgsexpression.sip +++ b/python/core/qgsexpression.sip @@ -51,7 +51,7 @@ class QgsExpression * * TODO QGIS3: Return QSet */ - QStringList referencedColumns() const; + QSet referencedColumns() const; /** * Return a list of field name indexes obtained from the provided fields. @@ -301,7 +301,7 @@ class QgsExpression const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ); @@ -314,7 +314,7 @@ class QgsExpression const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ); @@ -350,7 +350,7 @@ class QgsExpression */ bool lazyEval() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; /** Returns whether the function is only available if provided by a QgsExpressionContext object. * @note added in QGIS 2.12 @@ -517,7 +517,7 @@ class QgsExpression * * @return A list of columns required to evaluate this expression */ - virtual QStringList referencedColumns() const = 0; + virtual QSet referencedColumns() const = 0; /** * Abstract virtual method which returns if the geometry is required to evaluate @@ -596,7 +596,7 @@ class QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ); virtual QString dump() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; }; @@ -616,7 +616,7 @@ class QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ); virtual QString dump() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; @@ -650,7 +650,7 @@ class QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ); virtual QString dump() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; }; @@ -670,7 +670,7 @@ class QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ); virtual QString dump() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; @@ -692,7 +692,7 @@ class QgsExpression virtual QString dump() const; virtual QgsExpression::Node* clone() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; }; @@ -709,7 +709,7 @@ class QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ); virtual QString dump() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; @@ -741,7 +741,7 @@ class QgsExpression virtual bool prepare( QgsExpression* parent, const QgsExpressionContext* context ); virtual QString dump() const; - virtual QStringList referencedColumns() const; + virtual QSet referencedColumns() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; }; diff --git a/python/core/qgsexpressioncontext.sip b/python/core/qgsexpressioncontext.sip index f2712123675d..8aece97fac6f 100644 --- a/python/core/qgsexpressioncontext.sip +++ b/python/core/qgsexpressioncontext.sip @@ -17,7 +17,7 @@ class QgsScopedExpressionFunction : QgsExpression::Function const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = true ); diff --git a/python/core/qgspallabeling.sip b/python/core/qgspallabeling.sip index 71c11d37f556..4c7ab13e101e 100644 --- a/python/core/qgspallabeling.sip +++ b/python/core/qgspallabeling.sip @@ -122,14 +122,14 @@ class QgsLabelingEngineInterface //! clears data defined objects from PAL layer settings for a registered layer virtual void clearActiveLayer( const QString& layerID ) = 0; //! called when starting rendering of a layer - virtual int prepareLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx ) = 0; + virtual int prepareLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ) = 0; //! adds a diagram layer to the labeling engine //! @note added in QGIS 2.12 - virtual int prepareDiagramLayer( QgsVectorLayer *layer, QStringList &attrNames, QgsRenderContext &ctx ); + virtual int prepareDiagramLayer( QgsVectorLayer *layer, QSet& attrNames, QgsRenderContext& ctx ); //! called for every feature - virtual void registerFeature( const QString &layerID, QgsFeature &feat, QgsRenderContext &context ) = 0; + virtual void registerFeature( const QString &layerID, QgsFeature& feat, QgsRenderContext& context ) = 0; //! called for every diagram feature - virtual void registerDiagramFeature( const QString &layerID, QgsFeature &feat, QgsRenderContext &context ); + virtual void registerDiagramFeature( const QString& layerID, QgsFeature& feat, QgsRenderContext& context ); //! called when the map is drawn and labels should be placed virtual void drawLabeling( QgsRenderContext& context ) = 0; //! called when we're done with rendering @@ -915,10 +915,10 @@ class QgsPalLabeling : QgsLabelingEngineInterface //! clears data defined objects from PAL layer settings for a registered layer virtual void clearActiveLayer( const QString& layerID ); //! hook called when drawing layer before issuing select() - virtual int prepareLayer( QgsVectorLayer* layer, QStringList &attrNames, QgsRenderContext& ctx ); + virtual int prepareLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ); //! adds a diagram layer to the labeling engine //! @note added in QGIS 2.12 - virtual int prepareDiagramLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx ); + virtual int prepareDiagramLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ); /** Register a feature for labelling. * @param layerID string identifying layer associated with label diff --git a/python/core/symbology-ng/qgs25drenderer.sip b/python/core/symbology-ng/qgs25drenderer.sip index 56c58f600916..dce3ace659df 100644 --- a/python/core/symbology-ng/qgs25drenderer.sip +++ b/python/core/symbology-ng/qgs25drenderer.sip @@ -33,7 +33,7 @@ class Qgs25DRenderer : QgsFeatureRenderer void startRender( QgsRenderContext& context, const QgsFields& fields ); void stopRender( QgsRenderContext& context ); - QList usedAttributes(); + QSet usedAttributes() const; QgsFeatureRenderer* clone() const; virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ); diff --git a/python/core/symbology-ng/qgscategorizedsymbolrenderer.sip b/python/core/symbology-ng/qgscategorizedsymbolrenderer.sip index 7c27c6053f74..f7b143b602d4 100644 --- a/python/core/symbology-ng/qgscategorizedsymbolrenderer.sip +++ b/python/core/symbology-ng/qgscategorizedsymbolrenderer.sip @@ -59,7 +59,7 @@ class QgsCategorizedSymbolRenderer : QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; virtual QString dump() const; diff --git a/python/core/symbology-ng/qgsgraduatedsymbolrenderer.sip b/python/core/symbology-ng/qgsgraduatedsymbolrenderer.sip index 7a32a49a8a50..c9f7d6de4395 100644 --- a/python/core/symbology-ng/qgsgraduatedsymbolrenderer.sip +++ b/python/core/symbology-ng/qgsgraduatedsymbolrenderer.sip @@ -102,7 +102,7 @@ class QgsGraduatedSymbolRenderer : QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; virtual QString dump() const; diff --git a/python/core/symbology-ng/qgsheatmaprenderer.sip b/python/core/symbology-ng/qgsheatmaprenderer.sip index c6664ee99da0..3e9da2d15695 100644 --- a/python/core/symbology-ng/qgsheatmaprenderer.sip +++ b/python/core/symbology-ng/qgsheatmaprenderer.sip @@ -18,7 +18,7 @@ class QgsHeatmapRenderer : QgsFeatureRenderer //! @note symbol2 in python bindings virtual QgsSymbolList symbols( QgsRenderContext& context ); virtual QString dump() const; - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; static QgsFeatureRenderer* create( QDomElement& element ) /Factory/; virtual QDomElement save( QDomDocument& doc ); static QgsHeatmapRenderer* convertFromRenderer( const QgsFeatureRenderer* renderer ) /Factory/; diff --git a/python/core/symbology-ng/qgsinvertedpolygonrenderer.sip b/python/core/symbology-ng/qgsinvertedpolygonrenderer.sip index 65f97d54cff1..ca39659faf39 100644 --- a/python/core/symbology-ng/qgsinvertedpolygonrenderer.sip +++ b/python/core/symbology-ng/qgsinvertedpolygonrenderer.sip @@ -39,7 +39,7 @@ class QgsInvertedPolygonRenderer : QgsFeatureRenderer virtual QString dump() const; /** Proxy that will call this method on the embedded renderer. */ - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; /** Proxy that will call this method on the embedded renderer. */ virtual QgsFeatureRenderer::Capabilities capabilities(); /** Proxy that will call this method on the embedded renderer. diff --git a/python/core/symbology-ng/qgsnullsymbolrenderer.sip b/python/core/symbology-ng/qgsnullsymbolrenderer.sip index 3f140595503f..7fa52b478b03 100644 --- a/python/core/symbology-ng/qgsnullsymbolrenderer.sip +++ b/python/core/symbology-ng/qgsnullsymbolrenderer.sip @@ -24,7 +24,7 @@ class QgsNullSymbolRenderer : QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ); virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; virtual QString dump() const; virtual QgsFeatureRenderer* clone() const /Factory/; virtual QgsSymbolList symbols( QgsRenderContext& context ); diff --git a/python/core/symbology-ng/qgspointclusterrenderer.sip b/python/core/symbology-ng/qgspointclusterrenderer.sip index 57e6a5308852..298e88cfb4fa 100644 --- a/python/core/symbology-ng/qgspointclusterrenderer.sip +++ b/python/core/symbology-ng/qgspointclusterrenderer.sip @@ -16,7 +16,7 @@ class QgsPointClusterRenderer : QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); void stopRender( QgsRenderContext& context ); QDomElement save( QDomDocument& doc ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; //! Create a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; diff --git a/python/core/symbology-ng/qgspointdisplacementrenderer.sip b/python/core/symbology-ng/qgspointdisplacementrenderer.sip index 966c3f6d17f4..36713b2ca237 100644 --- a/python/core/symbology-ng/qgspointdisplacementrenderer.sip +++ b/python/core/symbology-ng/qgspointdisplacementrenderer.sip @@ -26,7 +26,7 @@ class QgsPointDisplacementRenderer : QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ); void stopRender( QgsRenderContext& context ); QDomElement save( QDomDocument& doc ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; //! Create a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ) /Factory/; diff --git a/python/core/symbology-ng/qgspointdistancerenderer.sip b/python/core/symbology-ng/qgspointdistancerenderer.sip index c2bead6b27be..761c0df5dfde 100644 --- a/python/core/symbology-ng/qgspointdistancerenderer.sip +++ b/python/core/symbology-ng/qgspointdistancerenderer.sip @@ -50,7 +50,7 @@ class QgsPointDistanceRenderer : QgsFeatureRenderer virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const; bool renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer = -1, bool selected = false, bool drawVertexMarker = false ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; virtual Capabilities capabilities(); virtual QgsSymbolList symbols( QgsRenderContext& context ); virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ); diff --git a/python/core/symbology-ng/qgsrenderer.sip b/python/core/symbology-ng/qgsrenderer.sip index bf0cdd6b25e4..b09f7e954272 100644 --- a/python/core/symbology-ng/qgsrenderer.sip +++ b/python/core/symbology-ng/qgsrenderer.sip @@ -119,10 +119,8 @@ class QgsFeatureRenderer /** * Returns a set of attributes required for this renderer. - * - * TODO QGIS3: Change QList to QSet */ - virtual QList usedAttributes() = 0; + virtual QSet usedAttributes() const = 0; /** * Returns true if this renderer requires the geometry to apply the filter. diff --git a/python/core/symbology-ng/qgsrulebasedrenderer.sip b/python/core/symbology-ng/qgsrulebasedrenderer.sip index 8eff5f1a8b0e..e65197fb3645 100644 --- a/python/core/symbology-ng/qgsrulebasedrenderer.sip +++ b/python/core/symbology-ng/qgsrulebasedrenderer.sip @@ -340,7 +340,7 @@ class QgsRuleBasedRenderer : QgsFeatureRenderer virtual QString filter( const QgsFields& fields = QgsFields() ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; virtual bool filterNeedsGeometry() const; diff --git a/python/core/symbology-ng/qgssinglesymbolrenderer.sip b/python/core/symbology-ng/qgssinglesymbolrenderer.sip index fa162e1069df..11bcb202a920 100644 --- a/python/core/symbology-ng/qgssinglesymbolrenderer.sip +++ b/python/core/symbology-ng/qgssinglesymbolrenderer.sip @@ -19,7 +19,7 @@ class QgsSingleSymbolRenderer : QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ); - virtual QList usedAttributes(); + virtual QSet usedAttributes() const; QgsSymbol* symbol() const; void setSymbol( QgsSymbol* s /Transfer/ ); diff --git a/src/core/dxf/qgsdxfexport.cpp b/src/core/dxf/qgsdxfexport.cpp index 76263384de3a..4c1d20920c36 100644 --- a/src/core/dxf/qgsdxfexport.cpp +++ b/src/core/dxf/qgsdxfexport.cpp @@ -965,12 +965,11 @@ void QgsDxfExport::writeEntities() } renderer->startRender( ctx, vl->fields() ); - QStringList attributes = renderer->usedAttributes(); + QSet attributes = renderer->usedAttributes(); if ( vl->fields().exists( layerIt->second ) ) { QString layerAttr = vl->fields().at( layerIt->second ).name(); - if ( !attributes.contains( layerAttr ) ) - attributes << layerAttr; + attributes << layerAttr; } const QgsAbstractVectorLayerLabeling *labeling = vl->labeling(); @@ -1106,7 +1105,7 @@ void QgsDxfExport::writeEntitiesSymbolLevels( QgsVectorLayer* layer ) { req.setFlags( QgsFeatureRequest::NoGeometry ); } - req.setSubsetOfAttributes( QStringList( renderer->usedAttributes() ), layer->fields() ); + req.setSubsetOfAttributes( renderer->usedAttributes(), layer->fields() ); req.setFilterRect( mMapSettings.mapToLayerCoordinates( layer, mExtent ) ); QgsFeatureIterator fit = layer->getFeatures( req ); diff --git a/src/core/qgsaggregatecalculator.cpp b/src/core/qgsaggregatecalculator.cpp index 46b16b377e26..59d32584ec07 100644 --- a/src/core/qgsaggregatecalculator.cpp +++ b/src/core/qgsaggregatecalculator.cpp @@ -71,9 +71,9 @@ QVariant QgsAggregateCalculator::calculate( QgsAggregateCalculator::Aggregate ag } } - QStringList lst; + QSet lst; if ( expression.isNull() ) - lst.append( fieldOrExpression ); + lst.insert( fieldOrExpression ); else lst = expression->referencedColumns(); diff --git a/src/core/qgsdatadefined.cpp b/src/core/qgsdatadefined.cpp index c09d0c3fdd75..8600a4bca7fc 100644 --- a/src/core/qgsdatadefined.cpp +++ b/src/core/qgsdatadefined.cpp @@ -187,7 +187,7 @@ QgsExpression *QgsDataDefined::expression() return d->expression; } -QStringList QgsDataDefined::referencedColumns( const QgsExpressionContext& context ) +QSet QgsDataDefined::referencedColumns( const QgsExpressionContext& context ) { if ( !d->exprRefColumns.isEmpty() ) { diff --git a/src/core/qgsdatadefined.h b/src/core/qgsdatadefined.h index 27ba85ba921c..285fe6e2a08e 100644 --- a/src/core/qgsdatadefined.h +++ b/src/core/qgsdatadefined.h @@ -154,7 +154,7 @@ class CORE_EXPORT QgsDataDefined * @param context expression context, used for preparing the expression if required * @note added in QGIS 2.12 */ - QStringList referencedColumns( const QgsExpressionContext& context = QgsExpressionContext() ); + QSet referencedColumns( const QgsExpressionContext& context = QgsExpressionContext() ); /** * Get the field which this QgsDataDefined represents. Be aware that this may return diff --git a/src/core/qgsdatadefined_p.h b/src/core/qgsdatadefined_p.h index 23d83db91391..8b7d4c1ede33 100644 --- a/src/core/qgsdatadefined_p.h +++ b/src/core/qgsdatadefined_p.h @@ -80,7 +80,7 @@ class QgsDataDefinedPrivate : public QSharedData QString field; bool expressionPrepared; - QStringList exprRefColumns; + QSet exprRefColumns; }; /// @endcond diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 725a2fef904e..36f6133753a9 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3427,43 +3427,43 @@ const QList& QgsExpression::Functions() << new StaticFunction( "scale_exp", 6, fcnExpScale, "Math" ) << new StaticFunction( "floor", 1, fcnFloor, "Math" ) << new StaticFunction( "ceil", 1, fcnCeil, "Math" ) - << new StaticFunction( "pi", 0, fcnPi, "Math", QString(), false, QStringList(), false, QStringList() << "$pi" ) - << new StaticFunction( "to_int", 1, fcnToInt, "Conversions", QString(), false, QStringList(), false, QStringList() << "toint" ) - << new StaticFunction( "to_real", 1, fcnToReal, "Conversions", QString(), false, QStringList(), false, QStringList() << "toreal" ) - << new StaticFunction( "to_string", 1, fcnToString, "Conversions", QString(), false, QStringList(), false, QStringList() << "tostring" ) - << new StaticFunction( "to_datetime", 1, fcnToDateTime, "Conversions", QString(), false, QStringList(), false, QStringList() << "todatetime" ) - << new StaticFunction( "to_date", 1, fcnToDate, "Conversions", QString(), false, QStringList(), false, QStringList() << "todate" ) - << new StaticFunction( "to_time", 1, fcnToTime, "Conversions", QString(), false, QStringList(), false, QStringList() << "totime" ) - << new StaticFunction( "to_interval", 1, fcnToInterval, "Conversions", QString(), false, QStringList(), false, QStringList() << "tointerval" ) - << new StaticFunction( "coalesce", -1, fcnCoalesce, "Conditionals", QString(), false, QStringList(), false, QStringList(), true ) - << new StaticFunction( "if", 3, fcnIf, "Conditionals", QString(), False, QStringList(), true ) + << new StaticFunction( "pi", 0, fcnPi, "Math", QString(), false, QSet(), false, QStringList() << "$pi" ) + << new StaticFunction( "to_int", 1, fcnToInt, "Conversions", QString(), false, QSet(), false, QStringList() << "toint" ) + << new StaticFunction( "to_real", 1, fcnToReal, "Conversions", QString(), false, QSet(), false, QStringList() << "toreal" ) + << new StaticFunction( "to_string", 1, fcnToString, "Conversions", QString(), false, QSet(), false, QStringList() << "tostring" ) + << new StaticFunction( "to_datetime", 1, fcnToDateTime, "Conversions", QString(), false, QSet(), false, QStringList() << "todatetime" ) + << new StaticFunction( "to_date", 1, fcnToDate, "Conversions", QString(), false, QSet(), false, QStringList() << "todate" ) + << new StaticFunction( "to_time", 1, fcnToTime, "Conversions", QString(), false, QSet(), false, QStringList() << "totime" ) + << new StaticFunction( "to_interval", 1, fcnToInterval, "Conversions", QString(), false, QSet(), false, QStringList() << "tointerval" ) + << new StaticFunction( "coalesce", -1, fcnCoalesce, "Conditionals", QString(), false, QSet(), false, QStringList(), true ) + << new StaticFunction( "if", 3, fcnIf, "Conditionals", QString(), False, QSet(), true ) << new StaticFunction( "aggregate", ParameterList() << Parameter( "layer" ) << Parameter( "aggregate" ) << Parameter( "expression" ) - << Parameter( "filter", true ) << Parameter( "concatenator", true ), fcnAggregate, "Aggregates", QString(), false, QStringList(), true ) + << Parameter( "filter", true ) << Parameter( "concatenator", true ), fcnAggregate, "Aggregates", QString(), false, QSet(), true ) << new StaticFunction( "relation_aggregate", ParameterList() << Parameter( "relation" ) << Parameter( "aggregate" ) << Parameter( "expression" ) << Parameter( "concatenator", true ), - fcnAggregateRelation, "Aggregates", QString(), False, QStringList( QgsFeatureRequest::AllAttributes ), true ) - - << new StaticFunction( "count", aggParams, fcnAggregateCount, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "count_distinct", aggParams, fcnAggregateCountDistinct, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "count_missing", aggParams, fcnAggregateCountMissing, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "minimum", aggParams, fcnAggregateMin, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "maximum", aggParams, fcnAggregateMax, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "sum", aggParams, fcnAggregateSum, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "mean", aggParams, fcnAggregateMean, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "median", aggParams, fcnAggregateMedian, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "stdev", aggParams, fcnAggregateStdev, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "range", aggParams, fcnAggregateRange, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "minority", aggParams, fcnAggregateMinority, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "majority", aggParams, fcnAggregateMajority, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "q1", aggParams, fcnAggregateQ1, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "q3", aggParams, fcnAggregateQ3, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "iqr", aggParams, fcnAggregateIQR, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "min_length", aggParams, fcnAggregateMinLength, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "max_length", aggParams, fcnAggregateMaxLength, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "collect", aggParams, fcnAggregateCollectGeometry, "Aggregates", QString(), False, QStringList(), true ) - << new StaticFunction( "concatenate", aggParams << Parameter( "concatenator", true ), fcnAggregateStringConcat, "Aggregates", QString(), False, QStringList(), true ) + fcnAggregateRelation, "Aggregates", QString(), False, QSet() << QgsFeatureRequest::AllAttributes, true ) + + << new StaticFunction( "count", aggParams, fcnAggregateCount, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "count_distinct", aggParams, fcnAggregateCountDistinct, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "count_missing", aggParams, fcnAggregateCountMissing, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "minimum", aggParams, fcnAggregateMin, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "maximum", aggParams, fcnAggregateMax, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "sum", aggParams, fcnAggregateSum, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "mean", aggParams, fcnAggregateMean, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "median", aggParams, fcnAggregateMedian, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "stdev", aggParams, fcnAggregateStdev, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "range", aggParams, fcnAggregateRange, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "minority", aggParams, fcnAggregateMinority, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "majority", aggParams, fcnAggregateMajority, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "q1", aggParams, fcnAggregateQ1, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "q3", aggParams, fcnAggregateQ3, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "iqr", aggParams, fcnAggregateIQR, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "min_length", aggParams, fcnAggregateMinLength, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "max_length", aggParams, fcnAggregateMaxLength, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "collect", aggParams, fcnAggregateCollectGeometry, "Aggregates", QString(), False, QSet(), true ) + << new StaticFunction( "concatenate", aggParams << Parameter( "concatenator", true ), fcnAggregateStringConcat, "Aggregates", QString(), False, QSet(), true ) << new StaticFunction( "regexp_match", 2, fcnRegexpMatch, "Conditionals" ) - << new StaticFunction( "now", 0, fcnNow, "Date and Time", QString(), false, QStringList(), false, QStringList() << "$now" ) + << new StaticFunction( "now", 0, fcnNow, "Date and Time", QString(), false, QSet(), false, QStringList() << "$now" ) << new StaticFunction( "age", 2, fcnAge, "Date and Time" ) << new StaticFunction( "year", 1, fcnYear, "Date and Time" ) << new StaticFunction( "month", 1, fcnMonth, "Date and Time" ) @@ -3488,7 +3488,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( "regexp_replace", 3, fcnRegexpReplace, "String" ) << new StaticFunction( "regexp_substr", 2, fcnRegexpSubstr, "String" ) << new StaticFunction( "substr", 3, fcnSubstr, "String" ) - << new StaticFunction( "concat", -1, fcnConcat, "String", QString(), false, QStringList(), false, QStringList(), true ) + << new StaticFunction( "concat", -1, fcnConcat, "String", QString(), false, QSet(), false, QStringList(), true ) << new StaticFunction( "strpos", 2, fcnStrpos, "String" ) << new StaticFunction( "left", 2, fcnLeft, "String" ) << new StaticFunction( "right", 2, fcnRight, "String" ) @@ -3531,16 +3531,16 @@ const QList& QgsExpression::Functions() << new StaticFunction( "make_point_m", 3, fcnMakePointM, "GeometryGroup" ) << new StaticFunction( "make_line", -1, fcnMakeLine, "GeometryGroup" ) << new StaticFunction( "make_polygon", -1, fcnMakePolygon, "GeometryGroup" ) - << new StaticFunction( "$x_at", 1, fcnXat, "GeometryGroup", QString(), true, QStringList(), false, QStringList() << "xat" << "x_at" ) - << new StaticFunction( "$y_at", 1, fcnYat, "GeometryGroup", QString(), true, QStringList(), false, QStringList() << "yat" << "y_at" ) - << new StaticFunction( "x_min", 1, fcnXMin, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "xmin" ) - << new StaticFunction( "x_max", 1, fcnXMax, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "xmax" ) - << new StaticFunction( "y_min", 1, fcnYMin, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "ymin" ) - << new StaticFunction( "y_max", 1, fcnYMax, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "ymax" ) - << new StaticFunction( "geom_from_wkt", 1, fcnGeomFromWKT, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "geomFromWKT" ) - << new StaticFunction( "geom_from_gml", 1, fcnGeomFromGML, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "geomFromGML" ) + << new StaticFunction( "$x_at", 1, fcnXat, "GeometryGroup", QString(), true, QSet(), false, QStringList() << "xat" << "x_at" ) + << new StaticFunction( "$y_at", 1, fcnYat, "GeometryGroup", QString(), true, QSet(), false, QStringList() << "yat" << "y_at" ) + << new StaticFunction( "x_min", 1, fcnXMin, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "xmin" ) + << new StaticFunction( "x_max", 1, fcnXMax, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "xmax" ) + << new StaticFunction( "y_min", 1, fcnYMin, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "ymin" ) + << new StaticFunction( "y_max", 1, fcnYMax, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "ymax" ) + << new StaticFunction( "geom_from_wkt", 1, fcnGeomFromWKT, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "geomFromWKT" ) + << new StaticFunction( "geom_from_gml", 1, fcnGeomFromGML, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "geomFromGML" ) << new StaticFunction( "relate", -1, fcnRelate, "GeometryGroup" ) - << new StaticFunction( "intersects_bbox", 2, fcnBbox, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "bbox" ) + << new StaticFunction( "intersects_bbox", 2, fcnBbox, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "bbox" ) << new StaticFunction( "disjoint", 2, fcnDisjoint, "GeometryGroup" ) << new StaticFunction( "intersects", 2, fcnIntersects, "GeometryGroup" ) << new StaticFunction( "touches", 2, fcnTouches, "GeometryGroup" ) @@ -3584,14 +3584,14 @@ const QList& QgsExpression::Functions() << new StaticFunction( "bounds_width", 1, fcnBoundsWidth, "GeometryGroup" ) << new StaticFunction( "bounds_height", 1, fcnBoundsHeight, "GeometryGroup" ) << new StaticFunction( "is_closed", 1, fcnIsClosed, "GeometryGroup" ) - << new StaticFunction( "convex_hull", 1, fcnConvexHull, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "convexHull" ) + << new StaticFunction( "convex_hull", 1, fcnConvexHull, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "convexHull" ) << new StaticFunction( "difference", 2, fcnDifference, "GeometryGroup" ) << new StaticFunction( "distance", 2, fcnDistance, "GeometryGroup" ) << new StaticFunction( "intersection", 2, fcnIntersection, "GeometryGroup" ) - << new StaticFunction( "sym_difference", 2, fcnSymDifference, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "symDifference" ) + << new StaticFunction( "sym_difference", 2, fcnSymDifference, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "symDifference" ) << new StaticFunction( "combine", 2, fcnCombine, "GeometryGroup" ) << new StaticFunction( "union", 2, fcnCombine, "GeometryGroup" ) - << new StaticFunction( "geom_to_wkt", -1, fcnGeomToWKT, "GeometryGroup", QString(), false, QStringList(), false, QStringList() << "geomToWKT" ) + << new StaticFunction( "geom_to_wkt", -1, fcnGeomToWKT, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "geomToWKT" ) << new StaticFunction( "geometry", 1, fcnGetGeometry, "GeometryGroup", QString(), true ) << new StaticFunction( "transform", 3, fcnTransformGeometry, "GeometryGroup" ) << new StaticFunction( "extrude", 3, fcnExtrude, "GeometryGroup", QString() ) @@ -3610,16 +3610,16 @@ const QList& QgsExpression::Functions() << Parameter( "vertex" ), fcnDistanceToVertex, "GeometryGroup" ) << new StaticFunction( "$id", 0, fcnFeatureId, "Record" ) << new StaticFunction( "$currentfeature", 0, fcnFeature, "Record" ) - << new StaticFunction( "uuid", 0, fcnUuid, "Record", QString(), false, QStringList(), false, QStringList() << "$uuid" ) - << new StaticFunction( "get_feature", 3, fcnGetFeature, "Record", QString(), false, QStringList(), false, QStringList() << "getFeature" ) + << new StaticFunction( "uuid", 0, fcnUuid, "Record", QString(), false, QSet(), false, QStringList() << "$uuid" ) + << new StaticFunction( "get_feature", 3, fcnGetFeature, "Record", QString(), false, QSet(), false, QStringList() << "getFeature" ) << new StaticFunction( "layer_property", 2, fcnGetLayerProperty, "General" ) << new StaticFunction( "var", 1, fcnGetVariable, "General" ) //return all attributes string for referencedColumns - this is caught by // QgsFeatureRequest::setSubsetOfAttributes and causes all attributes to be fetched by the // feature request - << new StaticFunction( "eval", 1, fcnEval, "General", QString(), true, QStringList( QgsFeatureRequest::AllAttributes ) ) - << new StaticFunction( "attribute", 2, fcnAttribute, "Record", QString(), false, QStringList( QgsFeatureRequest::AllAttributes ) ) + << new StaticFunction( "eval", 1, fcnEval, "General", QString(), true, QSet() << QgsFeatureRequest::AllAttributes ) + << new StaticFunction( "attribute", 2, fcnAttribute, "Record", QString(), false, QSet() << QgsFeatureRequest::AllAttributes ) // functions for arrays << new StaticFunction( "array", -1, fcnArray, "Arrays" ) @@ -3800,28 +3800,12 @@ bool QgsExpression::hasParserError() const { return !d->mParserErrorString.isNul QString QgsExpression::parserErrorString() const { return d->mParserErrorString; } -QStringList QgsExpression::referencedColumns() const +QSet QgsExpression::referencedColumns() const { if ( !d->mRootNode ) - return QStringList(); + return QSet(); - QStringList columns = d->mRootNode->referencedColumns(); - - // filter out duplicates - for ( int i = 0; i < columns.count(); i++ ) - { - QString col = columns.at( i ); - for ( int j = i + 1; j < columns.count(); j++ ) - { - if ( QString::compare( col, columns[j], Qt::CaseInsensitive ) == 0 ) - { - // this column is repeated: remove it! - columns.removeAt( j-- ); - } - } - } - - return columns; + return d->mRootNode->referencedColumns(); } bool QgsExpression::NodeInOperator::needsGeometry() const @@ -3837,10 +3821,10 @@ QSet QgsExpression::referencedAttributeIndexes( const QgsFields& fields ) c if ( !d->mRootNode ) return QSet(); - QStringList referencedFields = d->mRootNode->referencedColumns(); + const QSet referencedFields = d->mRootNode->referencedColumns(); QSet referencedIndexes; - Q_FOREACH ( const QString& fieldName, referencedFields ) +for ( const QString& fieldName : referencedFields ) { if ( fieldName == QgsFeatureRequest::AllAttributes ) { @@ -4618,7 +4602,7 @@ QString QgsExpression::NodeBinaryOperator::dump() const return fmt.arg( mOpLeft->dump(), BinaryOperatorText[mOp], rdump ); } -QStringList QgsExpression::NodeBinaryOperator::referencedColumns() const +QSet QgsExpression::NodeBinaryOperator::referencedColumns() const { return mOpLeft->referencedColumns() + mOpRight->referencedColumns(); } @@ -4628,11 +4612,6 @@ bool QgsExpression::NodeBinaryOperator::needsGeometry() const return mOpLeft->needsGeometry() || mOpRight->needsGeometry(); } -void QgsExpression::NodeBinaryOperator::accept( QgsExpression::Visitor& v ) const -{ - v.visit( *this ); -} - QgsExpression::Node* QgsExpression::NodeBinaryOperator::clone() const { return new NodeBinaryOperator( mOp, mOpLeft->clone(), mOpRight->clone() ); @@ -4812,10 +4791,10 @@ QString QgsExpression::NodeFunction::dump() const return QString( "%1(%2)" ).arg( fd->name(), mArgs ? mArgs->dump() : QString() ); // function } -QStringList QgsExpression::NodeFunction::referencedColumns() const +QSet QgsExpression::NodeFunction::referencedColumns() const { Function* fd = Functions()[mFnIndex]; - QStringList functionColumns = fd->referencedColumns(); + QSet functionColumns = fd->referencedColumns(); if ( !mArgs ) { @@ -4825,11 +4804,10 @@ QStringList QgsExpression::NodeFunction::referencedColumns() const Q_FOREACH ( Node* n, mArgs->list() ) { - functionColumns.append( n->referencedColumns() ); + functionColumns.unite( n->referencedColumns() ); } - //remove duplicates and return - return functionColumns.toSet().toList(); + return functionColumns; } bool QgsExpression::NodeFunction::needsGeometry() const @@ -5078,9 +5056,9 @@ QString QgsExpression::NodeCondition::dump() const return msg; } -QStringList QgsExpression::NodeCondition::referencedColumns() const +QSet QgsExpression::NodeCondition::referencedColumns() const { - QStringList lst; + QSet lst; Q_FOREACH ( WhenThen* cond, mConditions ) { lst += cond->mWhenExp->referencedColumns() + cond->mThenExp->referencedColumns(); @@ -5449,11 +5427,11 @@ const QgsExpression::Node* QgsExpression::rootNode() const return d->mRootNode; } -QStringList QgsExpression::NodeInOperator::referencedColumns() const +QSet QgsExpression::NodeInOperator::referencedColumns() const { - QStringList lst( mNode->referencedColumns() ); + QSet lst( mNode->referencedColumns() ); Q_FOREACH ( const Node* n, mList->list() ) - lst.append( n->referencedColumns() ); + lst.unite( n->referencedColumns() ); return lst; } diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index ffe63200e662..2216afd0b6d0 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -183,7 +183,7 @@ class CORE_EXPORT QgsExpression * * TODO QGIS3: Return QSet */ - QStringList referencedColumns() const; + QSet referencedColumns() const; /** * Return a list of field name indexes obtained from the provided fields. @@ -451,7 +451,7 @@ class CORE_EXPORT QgsExpression const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ) @@ -475,7 +475,7 @@ class CORE_EXPORT QgsExpression const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ) @@ -534,7 +534,7 @@ class CORE_EXPORT QgsExpression * Functions are non lazy default and will be given the node return value when called **/ bool lazyEval() const { return mLazyEval; } - virtual QStringList referencedColumns() const { return mReferencedColumns; } + virtual QSet referencedColumns() const { return mReferencedColumns; } /** Returns whether the function is only available if provided by a QgsExpressionContext object. * @note added in QGIS 2.12 @@ -566,7 +566,7 @@ class CORE_EXPORT QgsExpression bool mUsesGeometry; QString mGroup; QString mHelpText; - QStringList mReferencedColumns; + QSet mReferencedColumns; bool mLazyEval; bool mHandlesNull; bool mIsContextual; //if true function is only available through an expression context @@ -588,7 +588,7 @@ class CORE_EXPORT QgsExpression const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, const QStringList& aliases = QStringList(), bool handlesNull = false ) @@ -605,7 +605,7 @@ class CORE_EXPORT QgsExpression const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, const QStringList& aliases = QStringList(), bool handlesNull = false ) @@ -775,7 +775,7 @@ class CORE_EXPORT QgsExpression * * @return A list of columns required to evaluate this expression */ - virtual QStringList referencedColumns() const = 0; + virtual QSet referencedColumns() const = 0; /** * Abstract virtual method which returns if the geometry is required to evaluate @@ -873,7 +873,7 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override { return mOperand->referencedColumns(); } + virtual QSet referencedColumns() const override { return mOperand->referencedColumns(); } virtual bool needsGeometry() const override { return mOperand->needsGeometry(); } virtual Node* clone() const override; @@ -903,7 +903,7 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override; + virtual QSet referencedColumns() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; @@ -947,7 +947,7 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override; + virtual QSet referencedColumns() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; @@ -974,7 +974,7 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override; + virtual QSet referencedColumns() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; @@ -1004,7 +1004,7 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override { return QStringList(); } + virtual QSet referencedColumns() const override { return QSet(); } virtual bool needsGeometry() const override { return false; } virtual Node* clone() const override; @@ -1030,7 +1030,7 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override { return QStringList( mName ); } + virtual QSet referencedColumns() const override { return QSet() << mName; } virtual bool needsGeometry() const override { return false; } virtual Node* clone() const override; @@ -1081,7 +1081,7 @@ class CORE_EXPORT QgsExpression virtual bool prepare( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QStringList referencedColumns() const override; + virtual QSet referencedColumns() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index c7d33787e10d..620f74b1b441 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -41,12 +41,17 @@ class QgsSymbol; class CORE_EXPORT QgsScopedExpressionFunction : public QgsExpression::Function { public: + /** + * Create a new QgsScopedExpressionFunction + * + * @note Added in QGIS 2.12 + */ QgsScopedExpressionFunction( const QString& fnname, int params, const QString& group, const QString& helpText = QString(), bool usesGeometry = false, - const QStringList& referencedColumns = QStringList(), + const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = true ) diff --git a/src/core/qgsfeaturerequest.cpp b/src/core/qgsfeaturerequest.cpp index a816b2ec229f..8c010d7358c7 100644 --- a/src/core/qgsfeaturerequest.cpp +++ b/src/core/qgsfeaturerequest.cpp @@ -216,6 +216,27 @@ QgsFeatureRequest& QgsFeatureRequest::setSubsetOfAttributes( const QStringList& return *this; } +QgsFeatureRequest& QgsFeatureRequest::setSubsetOfAttributes( const QSet& attrNames, const QgsFields& fields ) +{ + if ( attrNames.contains( QgsFeatureRequest::AllAttributes ) ) + { + //attribute string list contains the all attributes flag, so we must fetch all attributes + return *this; + } + + mFlags |= SubsetOfAttributes; + mAttrs.clear(); + + Q_FOREACH ( const QString& attrName, attrNames ) + { + int attrNum = fields.lookupField( attrName ); + if ( attrNum != -1 && !mAttrs.contains( attrNum ) ) + mAttrs.append( attrNum ); + } + + return *this; +} + QgsFeatureRequest& QgsFeatureRequest::setSimplifyMethod( const QgsSimplifyMethod& simplifyMethod ) { mSimplifyMethod = simplifyMethod; @@ -387,7 +408,7 @@ QSet QgsFeatureRequest::OrderBy::usedAttributes() const { const OrderByClause& clause = *it; - usedAttributes.unite( clause.expression().referencedColumns().toSet() ); + usedAttributes.unite( clause.expression().referencedColumns() ); } return usedAttributes; diff --git a/src/core/qgsfeaturerequest.h b/src/core/qgsfeaturerequest.h index 006deae7b913..7c8d0a128ad1 100644 --- a/src/core/qgsfeaturerequest.h +++ b/src/core/qgsfeaturerequest.h @@ -377,6 +377,9 @@ class CORE_EXPORT QgsFeatureRequest //! Set a subset of attributes by names that will be fetched QgsFeatureRequest& setSubsetOfAttributes( const QStringList& attrNames, const QgsFields& fields ); + //! Set a subset of attributes by names that will be fetched + QgsFeatureRequest& setSubsetOfAttributes( const QSet& attrNames, const QgsFields& fields ); + //! Set a simplification method for geometries that will be fetched //! @note added in 2.2 QgsFeatureRequest& setSimplifyMethod( const QgsSimplifyMethod& simplifyMethod ); diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index af7c65606f46..e3f33f5754a7 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -3946,7 +3946,7 @@ void QgsPalLabeling::clearActiveLayer( const QString &layerID ) } -int QgsPalLabeling::prepareLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx ) +int QgsPalLabeling::prepareLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ) { if ( !willUseLayer( layer ) ) { @@ -3974,7 +3974,7 @@ int QgsPalLabeling::prepareLayer( QgsVectorLayer* layer, QStringList& attrNames, return 1; // init successful } -int QgsPalLabeling::prepareDiagramLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx ) +int QgsPalLabeling::prepareDiagramLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ) { QgsVectorLayerDiagramProvider* dp = new QgsVectorLayerDiagramProvider( layer, false ); // need to be added before calling prepare() - uses map settings from engine diff --git a/src/core/qgspallabeling.h b/src/core/qgspallabeling.h index 7e934e8c363c..ef3635b10d59 100644 --- a/src/core/qgspallabeling.h +++ b/src/core/qgspallabeling.h @@ -135,11 +135,11 @@ class CORE_EXPORT QgsLabelingEngineInterface //! clears data defined objects from PAL layer settings for a registered layer virtual void clearActiveLayer( const QString& layerID ) = 0; //! called when starting rendering of a layer - virtual int prepareLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx ) = 0; + virtual int prepareLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ) = 0; //! adds a diagram layer to the labeling engine //! @note added in QGIS 2.12 - virtual int prepareDiagramLayer( QgsVectorLayer *layer, QStringList &attrNames, QgsRenderContext &ctx ) + virtual int prepareDiagramLayer( QgsVectorLayer *layer, QSet& attrNames, QgsRenderContext &ctx ) { Q_UNUSED( layer ); Q_UNUSED( attrNames ); Q_UNUSED( ctx ); return 0; } //! called for every feature @@ -1037,10 +1037,10 @@ class CORE_EXPORT QgsPalLabeling : public QgsLabelingEngineInterface //! clears data defined objects from PAL layer settings for a registered layer virtual void clearActiveLayer( const QString& layerID ) override; //! hook called when drawing layer before issuing select() - virtual int prepareLayer( QgsVectorLayer* layer, QStringList &attrNames, QgsRenderContext& ctx ) override; + virtual int prepareLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ) override; //! adds a diagram layer to the labeling engine //! @note added in QGIS 2.12 - virtual int prepareDiagramLayer( QgsVectorLayer* layer, QStringList& attrNames, QgsRenderContext& ctx ) override; + virtual int prepareDiagramLayer( QgsVectorLayer* layer, QSet& attrNames, QgsRenderContext& ctx ) override; /** Register a feature for labelling. * @param layerID string identifying layer associated with label diff --git a/src/core/qgsrulebasedlabeling.cpp b/src/core/qgsrulebasedlabeling.cpp index 840843a8af9a..1846db12d88d 100644 --- a/src/core/qgsrulebasedlabeling.cpp +++ b/src/core/qgsrulebasedlabeling.cpp @@ -32,7 +32,7 @@ QgsVectorLayerLabelProvider *QgsRuleBasedLabelProvider::createProvider( QgsVecto return new QgsVectorLayerLabelProvider( layer, providerId, withFeatureLoop, settings ); } -bool QgsRuleBasedLabelProvider::prepare( const QgsRenderContext& context, QStringList& attributeNames ) +bool QgsRuleBasedLabelProvider::prepare( const QgsRenderContext& context, QSet& attributeNames ) { Q_FOREACH ( QgsVectorLayerLabelProvider* provider, mSubProviders ) provider->setEngine( mEngine ); @@ -264,7 +264,7 @@ void QgsRuleBasedLabeling::Rule::createSubProviders( QgsVectorLayer* layer, QgsR } } -void QgsRuleBasedLabeling::Rule::prepare( const QgsRenderContext& context, QStringList& attributeNames, QgsRuleBasedLabeling::RuleToProviderMap& subProviders ) +void QgsRuleBasedLabeling::Rule::prepare( const QgsRenderContext& context, QSet& attributeNames, QgsRuleBasedLabeling::RuleToProviderMap& subProviders ) { if ( mSettings ) { @@ -278,7 +278,7 @@ void QgsRuleBasedLabeling::Rule::prepare( const QgsRenderContext& context, QStri if ( mFilter ) { - attributeNames << mFilter->referencedColumns(); + attributeNames.unite( mFilter->referencedColumns() ); mFilter->prepare( &context.expressionContext() ); } diff --git a/src/core/qgsrulebasedlabeling.h b/src/core/qgsrulebasedlabeling.h index 3d778f4656a3..addc64495005 100644 --- a/src/core/qgsrulebasedlabeling.h +++ b/src/core/qgsrulebasedlabeling.h @@ -238,7 +238,7 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling void subProviderIds( QStringList& list ) const; //! call prepare() on sub-providers and populate attributeNames - void prepare( const QgsRenderContext& context, QStringList& attributeNames, RuleToProviderMap& subProviders ); + void prepare( const QgsRenderContext& context, QSet& attributeNames, RuleToProviderMap& subProviders ); //! register individual features RegisterResult registerFeature( QgsFeature& feature, QgsRenderContext& context, RuleToProviderMap& subProviders, QgsGeometry* obstacleGeometry = nullptr ); @@ -330,7 +330,7 @@ class CORE_EXPORT QgsRuleBasedLabelProvider : public QgsVectorLayerLabelProvider // reimplemented - virtual bool prepare( const QgsRenderContext& context, QStringList& attributeNames ) override; + virtual bool prepare( const QgsRenderContext& context, QSet& attributeNames ) override; virtual void registerFeature( QgsFeature& feature, QgsRenderContext& context, QgsGeometry* obstacleGeometry = nullptr ) override; diff --git a/src/core/qgsvectorfilewriter.cpp b/src/core/qgsvectorfilewriter.cpp index 482fcd65856d..b74dce3c74c2 100644 --- a/src/core/qgsvectorfilewriter.cpp +++ b/src/core/qgsvectorfilewriter.cpp @@ -2863,13 +2863,13 @@ void QgsVectorFileWriter::addRendererAttributes( QgsVectorLayer* vl, QgsAttribut QgsFeatureRenderer* renderer = symbologyRenderer( vl ); if ( renderer ) { - QList rendererAttributes = renderer->usedAttributes(); - for ( int i = 0; i < rendererAttributes.size(); ++i ) + const QSet rendererAttributes = renderer->usedAttributes(); + for ( const QString& attr : rendererAttributes ) { - int index = vl->fields().lookupField( rendererAttributes.at( i ) ); + int index = vl->fields().lookupField( attr ); if ( index != -1 ) { - attList.push_back( vl->fields().lookupField( rendererAttributes.at( i ) ) ); + attList.append( index ); } } } diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 56623d5d51bc..799b3809e6a5 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -3306,9 +3306,9 @@ QList QgsVectorLayer::getValues( const QString &fieldOrExpression, boo } QgsFeature f; - QStringList lst; + QSet lst; if ( expression.isNull() ) - lst.append( fieldOrExpression ); + lst.insert( fieldOrExpression ); else lst = expression->referencedColumns(); diff --git a/src/core/qgsvectorlayerdiagramprovider.cpp b/src/core/qgsvectorlayerdiagramprovider.cpp index ddaf4f97e126..6e9ada148c89 100644 --- a/src/core/qgsvectorlayerdiagramprovider.cpp +++ b/src/core/qgsvectorlayerdiagramprovider.cpp @@ -87,7 +87,7 @@ QList QgsVectorLayerDiagramProvider::labelFeatures( QgsRenderC return mFeatures; } - QStringList attributeNames; + QSet attributeNames; if ( !prepare( context, attributeNames ) ) return QList(); @@ -155,7 +155,7 @@ void QgsVectorLayerDiagramProvider::drawLabel( QgsRenderContext& context, pal::L } -bool QgsVectorLayerDiagramProvider::prepare( const QgsRenderContext& context, QStringList& attributeNames ) +bool QgsVectorLayerDiagramProvider::prepare( const QgsRenderContext& context, QSet& attributeNames ) { QgsDiagramLayerSettings& s2 = mSettings; const QgsMapSettings& mapSettings = mEngine->mapSettings(); @@ -177,11 +177,7 @@ bool QgsVectorLayerDiagramProvider::prepare( const QgsRenderContext& context, QS s2.setRenderer( mDiagRenderer ); //add attributes needed by the diagram renderer - Q_FOREACH ( const QString& field, s2.referencedFields( context.expressionContext(), mFields ) ) - { - if ( !attributeNames.contains( field ) ) - attributeNames << field; - } + attributeNames.unite( s2.referencedFields( context.expressionContext(), mFields ) ); return true; } diff --git a/src/core/qgsvectorlayerdiagramprovider.h b/src/core/qgsvectorlayerdiagramprovider.h index 7d93dcfd41df..8db71242163b 100644 --- a/src/core/qgsvectorlayerdiagramprovider.h +++ b/src/core/qgsvectorlayerdiagramprovider.h @@ -85,7 +85,7 @@ class CORE_EXPORT QgsVectorLayerDiagramProvider : public QgsAbstractLabelProvide * @param attributeNames list of attribute names to which additional required attributes shall be added * @return Whether the preparation was successful - if not, the provider shall not be used */ - virtual bool prepare( const QgsRenderContext& context, QStringList& attributeNames ); + virtual bool prepare( const QgsRenderContext& context, QSet& attributeNames ); /** * Register a feature for labeling as one or more QgsLabelFeature objects stored into mFeatures diff --git a/src/core/qgsvectorlayerlabelprovider.cpp b/src/core/qgsvectorlayerlabelprovider.cpp index 3dedaab2520d..0ce998f1ae97 100644 --- a/src/core/qgsvectorlayerlabelprovider.cpp +++ b/src/core/qgsvectorlayerlabelprovider.cpp @@ -128,7 +128,7 @@ QgsVectorLayerLabelProvider::~QgsVectorLayerLabelProvider() } -bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QStringList& attributeNames ) +bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QSet& attributeNames ) { QgsPalLayerSettings& lyr = mSettings; const QgsMapSettings& mapSettings = mEngine->mapSettings(); @@ -178,12 +178,12 @@ bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QStr Q_FOREACH ( const QString& name, exp->referencedColumns() ) { QgsDebugMsgLevel( "REFERENCED COLUMN = " + name, 4 ); - attributeNames.append( name ); + attributeNames.insert( name ); } } else { - attributeNames.append( lyr.fieldName ); + attributeNames.insert( lyr.fieldName ); } // add field indices of data defined expression or field @@ -198,12 +198,12 @@ bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QStr // this will return columns for expressions or field name, depending upon what is set to be used // this also prepares any expressions, too - QStringList cols = dd->referencedColumns( context.expressionContext() ); + QSet cols = dd->referencedColumns( context.expressionContext() ); //QgsDebugMsgLevel( QString( "Data defined referenced columns:" ) + cols.join( "," ), 4 ); Q_FOREACH ( const QString& name, cols ) { - attributeNames.append( name ); + attributeNames.insert( name ); } } } @@ -258,7 +258,7 @@ QList QgsVectorLayerLabelProvider::labelFeatures( QgsRenderCon return mLabels; } - QStringList attrNames; + QSet attrNames; if ( !prepare( ctx, attrNames ) ) return QList(); diff --git a/src/core/qgsvectorlayerlabelprovider.h b/src/core/qgsvectorlayerlabelprovider.h index c24adc422258..c3b88ca2f7f7 100644 --- a/src/core/qgsvectorlayerlabelprovider.h +++ b/src/core/qgsvectorlayerlabelprovider.h @@ -66,7 +66,7 @@ class CORE_EXPORT QgsVectorLayerLabelProvider : public QgsAbstractLabelProvider * @param attributeNames list of attribute names to which additional required attributes shall be added * @return Whether the preparation was successful - if not, the provider shall not be used */ - virtual bool prepare( const QgsRenderContext& context, QStringList& attributeNames ); + virtual bool prepare( const QgsRenderContext& context, QSet& attributeNames ); /** * Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels diff --git a/src/core/qgsvectorlayerrenderer.cpp b/src/core/qgsvectorlayerrenderer.cpp index f07ed9fc773e..9aec1cf58cba 100644 --- a/src/core/qgsvectorlayerrenderer.cpp +++ b/src/core/qgsvectorlayerrenderer.cpp @@ -534,7 +534,7 @@ void QgsVectorLayerRenderer::stopRenderer( QgsSingleSymbolRenderer* selRenderer -void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer* layer, QStringList& attributeNames ) +void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer* layer, QSet& attributeNames ) { if ( !mContext.labelingEngine() ) { @@ -591,7 +591,7 @@ void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer* layer, QStringList } } -void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer* layer, QStringList& attributeNames ) +void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer* layer, QSet& attributeNames ) { if ( !mContext.labelingEngine() ) { diff --git a/src/core/qgsvectorlayerrenderer.h b/src/core/qgsvectorlayerrenderer.h index 3a4ba17bf7c5..a74ef62dfef5 100644 --- a/src/core/qgsvectorlayerrenderer.h +++ b/src/core/qgsvectorlayerrenderer.h @@ -82,8 +82,8 @@ class QgsVectorLayerRenderer : public QgsMapLayerRenderer @param layer diagram layer @param attributeNames attributes needed for labeling and diagrams will be added to the list */ - void prepareLabeling( QgsVectorLayer* layer, QStringList& attributeNames ); - void prepareDiagrams( QgsVectorLayer* layer, QStringList& attributeNames ); + void prepareLabeling( QgsVectorLayer* layer, QSet& attributeNames ); + void prepareDiagrams( QgsVectorLayer* layer, QSet& attributeNames ); /** Draw layer with renderer V2. QgsFeatureRenderer::startRender() needs to be called before using this method */ @@ -122,7 +122,7 @@ class QgsVectorLayerRenderer : public QgsMapLayerRenderer QgsWkbTypes::GeometryType mGeometryType; - QStringList mAttrNames; + QSet mAttrNames; //! used with old labeling engine (QgsPalLabeling): whether labeling is enabled bool mLabeling; diff --git a/src/core/symbology-ng/qgs25drenderer.cpp b/src/core/symbology-ng/qgs25drenderer.cpp index 7f9bbcda1d37..5fc3ea2b11bc 100644 --- a/src/core/symbology-ng/qgs25drenderer.cpp +++ b/src/core/symbology-ng/qgs25drenderer.cpp @@ -146,9 +146,9 @@ void Qgs25DRenderer::stopRender( QgsRenderContext& context ) mSymbol->stopRender( context ); } -QList Qgs25DRenderer::usedAttributes() +QSet Qgs25DRenderer::usedAttributes() const { - return mSymbol->usedAttributes().toList(); + return mSymbol->usedAttributes(); } QgsFeatureRenderer* Qgs25DRenderer::clone() const diff --git a/src/core/symbology-ng/qgs25drenderer.h b/src/core/symbology-ng/qgs25drenderer.h index 6d0a9a438d61..3708cd1da943 100644 --- a/src/core/symbology-ng/qgs25drenderer.h +++ b/src/core/symbology-ng/qgs25drenderer.h @@ -39,7 +39,7 @@ class CORE_EXPORT Qgs25DRenderer : public QgsFeatureRenderer void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; - QList usedAttributes() override; + QSet usedAttributes() const override; QgsFeatureRenderer* clone() const override; virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp index 3e0aeccd52a9..19617dc7c09e 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp @@ -430,7 +430,7 @@ void QgsCategorizedSymbolRenderer::stopRender( QgsRenderContext& context ) mExpression.reset(); } -QList QgsCategorizedSymbolRenderer::usedAttributes() +QSet QgsCategorizedSymbolRenderer::usedAttributes() const { QSet attributes; @@ -442,7 +442,7 @@ QList QgsCategorizedSymbolRenderer::usedAttributes() QgsExpression testExpr( mAttrName ); if ( !testExpr.hasParserError() ) - attributes.unite( testExpr.referencedColumns().toSet() ); + attributes.unite( testExpr.referencedColumns() ); QgsCategoryList::const_iterator catIt = mCategories.constBegin(); for ( ; catIt != mCategories.constEnd(); ++catIt ) @@ -453,7 +453,7 @@ QList QgsCategorizedSymbolRenderer::usedAttributes() attributes.unite( catSymbol->usedAttributes() ); } } - return attributes.toList(); + return attributes; } QString QgsCategorizedSymbolRenderer::dump() const diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.h b/src/core/symbology-ng/qgscategorizedsymbolrenderer.h index 2d0f02a57f45..37302a87342c 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.h +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.h @@ -86,7 +86,7 @@ class CORE_EXPORT QgsCategorizedSymbolRenderer : public QgsFeatureRenderer virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; virtual void stopRender( QgsRenderContext& context ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; virtual QString dump() const override; virtual QgsCategorizedSymbolRenderer* clone() const override; virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const override; diff --git a/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp b/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp index 307f515a6b80..898685dae0ee 100644 --- a/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp +++ b/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp @@ -178,7 +178,7 @@ bool QgsGeometryGeneratorSymbolLayer::setSubSymbol( QgsSymbol* symbol ) QSet QgsGeometryGeneratorSymbolLayer::usedAttributes() const { - return mSymbol->usedAttributes() + mExpression->referencedColumns().toSet(); + return mSymbol->usedAttributes() + mExpression->referencedColumns(); } bool QgsGeometryGeneratorSymbolLayer::isCompatibleWithSymbol( QgsSymbol* symbol ) const diff --git a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp index 884acdd4a0ac..fb312469269b 100644 --- a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp @@ -412,7 +412,7 @@ void QgsGraduatedSymbolRenderer::stopRender( QgsRenderContext& context ) } } -QList QgsGraduatedSymbolRenderer::usedAttributes() +QSet QgsGraduatedSymbolRenderer::usedAttributes() const { QSet attributes; @@ -424,7 +424,7 @@ QList QgsGraduatedSymbolRenderer::usedAttributes() QgsExpression testExpr( mAttrName ); if ( !testExpr.hasParserError() ) - attributes.unite( testExpr.referencedColumns().toSet() ); + attributes.unite( testExpr.referencedColumns() ); QgsRangeList::const_iterator range_it = mRanges.constBegin(); for ( ; range_it != mRanges.constEnd(); ++range_it ) @@ -435,7 +435,7 @@ QList QgsGraduatedSymbolRenderer::usedAttributes() attributes.unite( symbol->usedAttributes() ); } } - return attributes.toList(); + return attributes; } bool QgsGraduatedSymbolRenderer::updateRangeSymbol( int rangeIndex, QgsSymbol* symbol ) diff --git a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.h b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.h index a0be327423d0..8876567dd3b2 100644 --- a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.h +++ b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.h @@ -140,7 +140,7 @@ class CORE_EXPORT QgsGraduatedSymbolRenderer : public QgsFeatureRenderer virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feature, QgsRenderContext &context ) override; virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; virtual void stopRender( QgsRenderContext& context ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; virtual QString dump() const override; virtual QgsGraduatedSymbolRenderer* clone() const override; virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const override; diff --git a/src/core/symbology-ng/qgsheatmaprenderer.cpp b/src/core/symbology-ng/qgsheatmaprenderer.cpp index bc065011a257..34ba0532ef4a 100644 --- a/src/core/symbology-ng/qgsheatmaprenderer.cpp +++ b/src/core/symbology-ng/qgsheatmaprenderer.cpp @@ -384,7 +384,7 @@ QgsSymbolList QgsHeatmapRenderer::symbols( QgsRenderContext& ) return QgsSymbolList(); } -QList QgsHeatmapRenderer::usedAttributes() +QSet QgsHeatmapRenderer::usedAttributes() const { QSet attributes; @@ -396,9 +396,9 @@ QList QgsHeatmapRenderer::usedAttributes() QgsExpression testExpr( mWeightExpressionString ); if ( !testExpr.hasParserError() ) - attributes.unite( testExpr.referencedColumns().toSet() ); + attributes.unite( testExpr.referencedColumns() ); - return attributes.toList(); + return attributes; } QgsHeatmapRenderer* QgsHeatmapRenderer::convertFromRenderer( const QgsFeatureRenderer *renderer ) diff --git a/src/core/symbology-ng/qgsheatmaprenderer.h b/src/core/symbology-ng/qgsheatmaprenderer.h index 125ad362175b..70cea65df7dd 100644 --- a/src/core/symbology-ng/qgsheatmaprenderer.h +++ b/src/core/symbology-ng/qgsheatmaprenderer.h @@ -46,7 +46,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer //! @note symbol2 in python bindings virtual QgsSymbolList symbols( QgsRenderContext &context ) override; virtual QString dump() const override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; static QgsFeatureRenderer* create( QDomElement& element ); virtual QDomElement save( QDomDocument& doc ) override; static QgsHeatmapRenderer* convertFromRenderer( const QgsFeatureRenderer* renderer ); diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp b/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp index b246bb52d233..1c27ea8d9e30 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp @@ -464,11 +464,11 @@ QgsFeatureRenderer::Capabilities QgsInvertedPolygonRenderer::capabilities() return mSubRenderer->capabilities(); } -QList QgsInvertedPolygonRenderer::usedAttributes() +QSet QgsInvertedPolygonRenderer::usedAttributes() const { if ( !mSubRenderer ) { - return QList(); + return QSet(); } return mSubRenderer->usedAttributes(); } diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h index a33b0ab479f2..a7e510acff2e 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h @@ -71,7 +71,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer virtual QString dump() const override; /** Proxy that will call this method on the embedded renderer. */ - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; /** Proxy that will call this method on the embedded renderer. */ virtual Capabilities capabilities() override; /** Proxy that will call this method on the embedded renderer. diff --git a/src/core/symbology-ng/qgsnullsymbolrenderer.cpp b/src/core/symbology-ng/qgsnullsymbolrenderer.cpp index a013c2c5e75c..5dabae674490 100644 --- a/src/core/symbology-ng/qgsnullsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgsnullsymbolrenderer.cpp @@ -84,9 +84,9 @@ bool QgsNullSymbolRenderer::willRenderFeature( QgsFeature&, QgsRenderContext& ) return true; } -QList QgsNullSymbolRenderer::usedAttributes() +QSet QgsNullSymbolRenderer::usedAttributes() const { - return QList(); + return QSet(); } QString QgsNullSymbolRenderer::dump() const diff --git a/src/core/symbology-ng/qgsnullsymbolrenderer.h b/src/core/symbology-ng/qgsnullsymbolrenderer.h index eae2f8d0b293..9defdf3b1b92 100644 --- a/src/core/symbology-ng/qgsnullsymbolrenderer.h +++ b/src/core/symbology-ng/qgsnullsymbolrenderer.h @@ -42,7 +42,7 @@ class CORE_EXPORT QgsNullSymbolRenderer : public QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ) override; virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; virtual QString dump() const override; virtual QgsFeatureRenderer* clone() const override; virtual QgsSymbolList symbols( QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index 5bd0f11a85d6..d0a7f01b03ba 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -157,11 +157,11 @@ QDomElement QgsPointClusterRenderer::save( QDomDocument& doc ) return rendererElement; } -QList QgsPointClusterRenderer::usedAttributes() +QSet QgsPointClusterRenderer::usedAttributes() const { - QList attr = QgsPointDistanceRenderer::usedAttributes(); + QSet attr = QgsPointDistanceRenderer::usedAttributes(); if ( mClusterSymbol ) - attr.append( mClusterSymbol->usedAttributes().toList() ); + attr.unite( mClusterSymbol->usedAttributes() ); return attr; } diff --git a/src/core/symbology-ng/qgspointclusterrenderer.h b/src/core/symbology-ng/qgspointclusterrenderer.h index 575f03b1ad05..600de1d8a79a 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.h +++ b/src/core/symbology-ng/qgspointclusterrenderer.h @@ -35,7 +35,7 @@ class CORE_EXPORT QgsPointClusterRenderer: public QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; QDomElement save( QDomDocument& doc ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; //! Creates a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ); diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index 74b7676341b0..b189cf5db829 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -215,11 +215,11 @@ QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) return rendererElement; } -QList QgsPointDisplacementRenderer::usedAttributes() +QSet QgsPointDisplacementRenderer::usedAttributes() const { - QList attr = QgsPointDistanceRenderer::usedAttributes(); + QSet attr = QgsPointDistanceRenderer::usedAttributes(); if ( mCenterSymbol ) - attr.append( mCenterSymbol->usedAttributes().toList() ); + attr.unite( mCenterSymbol->usedAttributes() ); return attr; } diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.h b/src/core/symbology-ng/qgspointdisplacementrenderer.h index f5a4f66d46fe..8a1e5cfade76 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.h +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.h @@ -45,7 +45,7 @@ class CORE_EXPORT QgsPointDisplacementRenderer: public QgsPointDistanceRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; QDomElement save( QDomDocument& doc ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; //! Create a renderer from XML element static QgsFeatureRenderer* create( QDomElement& symbologyElem ); diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index 626e1f62a7ff..e67ef1dcb1b5 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -204,12 +204,12 @@ QString QgsPointDistanceRenderer::filter( const QgsFields& fields ) return mRenderer->filter( fields ); } -QList QgsPointDistanceRenderer::usedAttributes() +QSet QgsPointDistanceRenderer::usedAttributes() const { - QList attributeList; + QSet attributeList; if ( !mLabelAttributeName.isEmpty() ) { - attributeList.push_back( mLabelAttributeName ); + attributeList.insert( mLabelAttributeName ); } if ( mRenderer ) { diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index 0dc136274688..758a9ebf7c9f 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -76,7 +76,7 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer virtual void toSld( QDomDocument& doc, QDomElement &element, QgsStringMap props = QgsStringMap() ) const override; bool renderFeature( QgsFeature& feature, QgsRenderContext& context, int layer = -1, bool selected = false, bool drawVertexMarker = false ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; virtual Capabilities capabilities() override; virtual QgsSymbolList symbols( QgsRenderContext& context ) override; virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgsrenderer.h b/src/core/symbology-ng/qgsrenderer.h index 55494d7598ea..b333413a82df 100644 --- a/src/core/symbology-ng/qgsrenderer.h +++ b/src/core/symbology-ng/qgsrenderer.h @@ -148,8 +148,7 @@ class CORE_EXPORT QgsFeatureRenderer * * @return A set of attributes */ - // TODO QGIS3: Change QList to QSet - virtual QList usedAttributes() = 0; + virtual QSet usedAttributes() const = 0; /** * Returns true if this renderer requires the geometry to apply the filter. diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.cpp b/src/core/symbology-ng/qgsrulebasedrenderer.cpp index ec50e51184ff..db7b25c6c137 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.cpp +++ b/src/core/symbology-ng/qgsrulebasedrenderer.cpp @@ -185,7 +185,7 @@ QSet QgsRuleBasedRenderer::Rule::usedAttributes() const // attributes needed by this rule QSet attrs; if ( mFilter ) - attrs.unite( mFilter->referencedColumns().toSet() ); + attrs.unite( mFilter->referencedColumns() ); if ( mSymbol ) attrs.unite( mSymbol->usedAttributes() ); @@ -910,10 +910,9 @@ QString QgsRuleBasedRenderer::filter( const QgsFields& ) return mFilter; } -QList QgsRuleBasedRenderer::usedAttributes() +QSet QgsRuleBasedRenderer::usedAttributes() const { - QSet attrs = mRootRule->usedAttributes(); - return attrs.toList(); + return mRootRule->usedAttributes(); } bool QgsRuleBasedRenderer::filterNeedsGeometry() const diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.h b/src/core/symbology-ng/qgsrulebasedrenderer.h index 57be8f7463c2..6739c1c3e985 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.h +++ b/src/core/symbology-ng/qgsrulebasedrenderer.h @@ -421,7 +421,7 @@ class CORE_EXPORT QgsRuleBasedRenderer : public QgsFeatureRenderer virtual QString filter( const QgsFields& fields = QgsFields() ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; virtual bool filterNeedsGeometry() const override; diff --git a/src/core/symbology-ng/qgssinglesymbolrenderer.cpp b/src/core/symbology-ng/qgssinglesymbolrenderer.cpp index fce4b14e356f..dcd9e6c7b21a 100644 --- a/src/core/symbology-ng/qgssinglesymbolrenderer.cpp +++ b/src/core/symbology-ng/qgssinglesymbolrenderer.cpp @@ -72,11 +72,12 @@ void QgsSingleSymbolRenderer::stopRender( QgsRenderContext& context ) mSymbol->stopRender( context ); } -QList QgsSingleSymbolRenderer::usedAttributes() +QSet QgsSingleSymbolRenderer::usedAttributes() const { QSet attributes; - if ( mSymbol.data() ) attributes.unite( mSymbol->usedAttributes() ); - return attributes.toList(); + if ( mSymbol.data() ) + attributes.unite( mSymbol->usedAttributes() ); + return attributes; } QgsSymbol* QgsSingleSymbolRenderer::symbol() const diff --git a/src/core/symbology-ng/qgssinglesymbolrenderer.h b/src/core/symbology-ng/qgssinglesymbolrenderer.h index e92f31e65a0a..dc56f556be5c 100644 --- a/src/core/symbology-ng/qgssinglesymbolrenderer.h +++ b/src/core/symbology-ng/qgssinglesymbolrenderer.h @@ -36,7 +36,7 @@ class CORE_EXPORT QgsSingleSymbolRenderer : public QgsFeatureRenderer virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; virtual void stopRender( QgsRenderContext& context ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() const override; QgsSymbol* symbol() const; void setSymbol( QgsSymbol* s ); diff --git a/src/core/symbology-ng/qgssymbollayer.cpp b/src/core/symbology-ng/qgssymbollayer.cpp index ccd7cc86e142..51ba4764e87b 100644 --- a/src/core/symbology-ng/qgssymbollayer.cpp +++ b/src/core/symbology-ng/qgssymbollayer.cpp @@ -303,18 +303,18 @@ bool QgsSymbolLayer::isCompatibleWithSymbol( QgsSymbol* symbol ) const QSet QgsSymbolLayer::usedAttributes() const { - QStringList columns; + QSet columns; QMap< QString, QgsDataDefined* >::const_iterator ddIt = mDataDefinedProperties.constBegin(); for ( ; ddIt != mDataDefinedProperties.constEnd(); ++ddIt ) { if ( ddIt.value() && ddIt.value()->isActive() ) { - columns.append( ddIt.value()->referencedColumns() ); + columns.unite( ddIt.value()->referencedColumns() ); } } - return columns.toSet(); + return columns; } void QgsSymbolLayer::saveDataDefinedProperties( QgsStringMap& stringMap ) const diff --git a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp index c39132d5753d..73874d6a17bc 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp @@ -518,7 +518,7 @@ void QgsRelationReferenceWidget::init() QgsExpression exp( mReferencedLayer->displayExpression() ); - requestedAttrs += exp.referencedColumns().toSet(); + requestedAttrs += exp.referencedColumns(); requestedAttrs << mRelation.fieldPairs().at( 0 ).second; QgsAttributeList attributes; @@ -527,7 +527,7 @@ void QgsRelationReferenceWidget::init() layerCache->setCacheSubsetOfAttributes( attributes ); mMasterModel = new QgsAttributeTableModel( layerCache ); - mMasterModel->setRequest( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( requestedAttrs.toList(), mReferencedLayer->fields() ) ); + mMasterModel->setRequest( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( requestedAttrs, mReferencedLayer->fields() ) ); mFilterModel = new QgsAttributeTableFilterModel( mCanvas, mMasterModel, mMasterModel ); mFeatureListModel = new QgsFeatureListModel( mFilterModel, this ); mFeatureListModel->setDisplayExpression( mReferencedLayer->displayExpression() ); diff --git a/src/gui/symbology-ng/qgssizescalewidget.cpp b/src/gui/symbology-ng/qgssizescalewidget.cpp index 4187bfc671b6..9344aa233926 100644 --- a/src/gui/symbology-ng/qgssizescalewidget.cpp +++ b/src/gui/symbology-ng/qgssizescalewidget.cpp @@ -277,7 +277,7 @@ void QgsSizeScaleWidget::computeFromLayerTriggered() if ( ! expression.prepare( &context ) ) return; - QStringList lst( expression.referencedColumns() ); + QSet lst( expression.referencedColumns() ); QgsFeatureIterator fit = mLayer->getFeatures( QgsFeatureRequest().setFlags( expression.needsGeometry() diff --git a/tests/src/core/testqgsdatadefined.cpp b/tests/src/core/testqgsdatadefined.cpp index 0e6d203dc6f5..73970942a8b2 100644 --- a/tests/src/core/testqgsdatadefined.cpp +++ b/tests/src/core/testqgsdatadefined.cpp @@ -273,20 +273,20 @@ void TestQgsDataDefined::referencedColumns() dd.setActive( true ); dd.setUseExpression( true ); - QStringList cols = dd.referencedColumns(); + QSet cols = dd.referencedColumns(); QVERIFY( cols.isEmpty() ); //set as expression dd.setExpressionString( "1+col1+col2" ); cols = dd.referencedColumns(); - QCOMPARE( cols.length(), 2 ); + QCOMPARE( cols.size(), 2 ); QVERIFY( cols.contains( QString( "col1" ) ) ); QVERIFY( cols.contains( QString( "col2" ) ) ); //alter expression and check that referenced columns is updated dd.setExpressionString( "1+col1+col2+col3" ); cols = dd.referencedColumns(); - QCOMPARE( cols.length(), 3 ); + QCOMPARE( cols.size(), 3 ); QVERIFY( cols.contains( QString( "col1" ) ) ); QVERIFY( cols.contains( QString( "col2" ) ) ); QVERIFY( cols.contains( QString( "col3" ) ) ); @@ -298,13 +298,13 @@ void TestQgsDataDefined::referencedColumns() dd.setField( "field" ); cols = dd.referencedColumns(); - QCOMPARE( cols.length(), 1 ); + QCOMPARE( cols.size(), 1 ); QVERIFY( cols.contains( QString( "field" ) ) ); //switch back to expression dd.setUseExpression( true ); cols = dd.referencedColumns(); - QCOMPARE( cols.length(), 3 ); + QCOMPARE( cols.size(), 3 ); QVERIFY( cols.contains( QString( "col1" ) ) ); QVERIFY( cols.contains( QString( "col2" ) ) ); QVERIFY( cols.contains( QString( "col3" ) ) ); diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 24701b60f982..0b4656a918c0 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1494,7 +1494,7 @@ class TestQgsExpression: public QObject expectedCols << "foo" << "bar" << "ppp" << "qqq" << "rrr"; QgsExpression exp( "length(Bar || FOO) = 4 or foo + sqrt(bar) > 0 or case when ppp then qqq else rrr end" ); QCOMPARE( exp.hasParserError(), false ); - QStringList refCols = exp.referencedColumns(); + QSet refCols = exp.referencedColumns(); // make sure we have lower case QSet refColsSet; Q_FOREACH ( const QString& col, refCols ) @@ -1507,7 +1507,7 @@ class TestQgsExpression: public QObject { QgsExpression exp( "attribute($currentfeature,'test')" ); QCOMPARE( exp.hasParserError(), false ); - QStringList refCols = exp.referencedColumns(); + QSet refCols = exp.referencedColumns(); // make sure we get the all attributes flag bool allAttributesFlag = refCols.contains( QgsFeatureRequest::AllAttributes ); QCOMPARE( allAttributesFlag, true ); diff --git a/tests/src/core/testqgslabelingengine.cpp b/tests/src/core/testqgslabelingengine.cpp index b38633737e39..648333b9a6bf 100644 --- a/tests/src/core/testqgslabelingengine.cpp +++ b/tests/src/core/testqgslabelingengine.cpp @@ -437,7 +437,7 @@ void TestQgsLabelingEngine::testSubstitutions() mapSettings.setLayers( QStringList() << vl->id() ); mapSettings.setOutputDpi( 96 ); QgsRenderContext context = QgsRenderContext::fromMapSettings( mapSettings ); - QStringList attributes; + QSet attributes; QgsLabelingEngine engine; engine.setMapSettings( mapSettings ); engine.addProvider( provider ); @@ -469,7 +469,7 @@ void TestQgsLabelingEngine::testCapitalization() mapSettings.setLayers( QStringList() << vl->id() ); mapSettings.setOutputDpi( 96 ); QgsRenderContext context = QgsRenderContext::fromMapSettings( mapSettings ); - QStringList attributes; + QSet attributes; QgsLabelingEngine engine; engine.setMapSettings( mapSettings ); diff --git a/tests/src/python/test_qgsexpression.py b/tests/src/python/test_qgsexpression.py index 8115cab530af..7eece9e2d46e 100644 --- a/tests/src/python/test_qgsexpression.py +++ b/tests/src/python/test_qgsexpression.py @@ -129,7 +129,8 @@ def testCanRegisterGeometryFunction(self): def testReferencedColumnsNoSet(self): success = QgsExpression.registerFunction(self.no_referenced_columns_set) exp = QgsExpression('no_referenced_columns_set()') - self.assertEqual(exp.referencedColumns(), [QgsFeatureRequest.AllAttributes]) + self.assertEqual(exp.referencedColumns(), + {QgsFeatureRequest.AllAttributes}) def testReferencedColumnsSet(self): success = QgsExpression.registerFunction(self.referenced_columns_set) From 5179a3a55dbf3cda4ef566cd3e4ac037923f79d2 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 5 Oct 2016 15:51:43 +0200 Subject: [PATCH 174/897] [processing] Fix extent selection widget --- python/plugins/processing/gui/ExtentSelectionPanel.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/ExtentSelectionPanel.py b/python/plugins/processing/gui/ExtentSelectionPanel.py index 89437637ea37..791071075254 100644 --- a/python/plugins/processing/gui/ExtentSelectionPanel.py +++ b/python/plugins/processing/gui/ExtentSelectionPanel.py @@ -93,7 +93,7 @@ def selectExtent(self): selectOnCanvasAction.triggered.connect(self.selectOnCanvas) useLayerExtentAction.triggered.connect(self.useLayerExtent) - if self.canUseAutoExtent(): + if self.alg.canUseAutoExtent(): useMincoveringExtentAction = QAction( self.tr('Use min covering extent from input layers'), self.btnSelect) From d0ec36704479a96298dfd5e7191d168bd74a7ae8 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 5 Oct 2016 16:18:29 +0200 Subject: [PATCH 175/897] Fix crash in QgsEncodingFileDialog --- src/gui/qgsencodingfiledialog.cpp | 8 +++++--- src/gui/qgsencodingfiledialog.h | 6 +++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/gui/qgsencodingfiledialog.cpp b/src/gui/qgsencodingfiledialog.cpp index 6a771122ecdb..b59978b0e347 100644 --- a/src/gui/qgsencodingfiledialog.cpp +++ b/src/gui/qgsencodingfiledialog.cpp @@ -25,15 +25,17 @@ #include #include -QgsEncodingFileDialog::QgsEncodingFileDialog( QWidget * parent, - const QString & caption, const QString & directory, - const QString & filter, const QString & encoding ) +QgsEncodingFileDialog::QgsEncodingFileDialog( QWidget* parent, + const QString& caption, const QString& directory, + const QString& filter, const QString& encoding ) : QFileDialog( parent, caption, directory, filter ) { mCancelAll = false; mCancelAllButton = nullptr; mEncodingComboBox = new QComboBox( this ); QLabel* l = new QLabel( tr( "Encoding:" ), this ); + + setOption( QFileDialog::DontUseNativeDialog ); layout()->addWidget( l ); layout()->addWidget( mEncodingComboBox ); diff --git a/src/gui/qgsencodingfiledialog.h b/src/gui/qgsencodingfiledialog.h index 4b4342606c39..87fe19c4f5cb 100644 --- a/src/gui/qgsencodingfiledialog.h +++ b/src/gui/qgsencodingfiledialog.h @@ -27,9 +27,9 @@ class GUI_EXPORT QgsEncodingFileDialog: public QFileDialog { Q_OBJECT public: - QgsEncodingFileDialog( QWidget * parent = nullptr, - const QString & caption = QString(), const QString & directory = QString(), - const QString & filter = QString(), const QString & encoding = QString() ); + QgsEncodingFileDialog( QWidget* parent = nullptr, + const QString& caption = QString(), const QString& directory = QString(), + const QString& filter = QString(), const QString& encoding = QString() ); ~QgsEncodingFileDialog(); /** Returns a string describing the chosen encoding*/ QString encoding() const; From 9242d225e507b0e480fe990ee560853c9d598ffe Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 5 Oct 2016 20:02:51 +0200 Subject: [PATCH 176/897] Remove fields from default value configuration widget --- src/app/qgsattributetypedialog.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 5d3748d648e4..4f242c61d2b2 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -69,8 +69,6 @@ QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl, int fieldIdx isFieldEditableCheckBox->setEnabled( false ); } - mExpressionWidget->setLayer( vl ); - connect( mExpressionWidget, SIGNAL( expressionChanged( QString ) ), this, SLOT( defaultExpressionChanged() ) ); QSettings settings; From 7c59e4117712dc9f730380e06e0b903474fbb954 Mon Sep 17 00:00:00 2001 From: Marco Bernasocchi Date: Wed, 5 Oct 2016 20:35:28 +0200 Subject: [PATCH 177/897] fix save to postgis table in processing --- python/plugins/processing/tools/postgis.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/postgis.py b/python/plugins/processing/tools/postgis.py index 1ac4441f0b55..4140ac63437c 100644 --- a/python/plugins/processing/tools/postgis.py +++ b/python/plugins/processing/tools/postgis.py @@ -186,6 +186,7 @@ def __init__(self, host=None, port=None, dbname=None, user=None, passwd=None, service=None, uri=None): # Regular expression for identifiers without need to quote them self.re_ident_ok = re.compile(r"^\w+$") + port = str(port) if uri: self.uri = uri @@ -199,7 +200,7 @@ def __init__(self, host=None, port=None, dbname=None, user=None, conninfo = self.uri.connectionInfo(False) err = None for i in range(4): - expandedConnInfo = uri.connectionInfo(True) + expandedConnInfo = self.uri.connectionInfo(True) try: self.con = psycopg2.connect(expandedConnInfo.encode('utf-8')) if err is not None: From 3b0486cc6e62c46114b4320cb46d3bcd3223cdb5 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 5 Oct 2016 22:14:58 +0200 Subject: [PATCH 178/897] Followup 722fdef: fix grass plugin build --- src/plugins/grass/qgsgrasseditrenderer.cpp | 2 +- src/plugins/grass/qgsgrasseditrenderer.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/grass/qgsgrasseditrenderer.cpp b/src/plugins/grass/qgsgrasseditrenderer.cpp index 132fdcf1b6ab..6c224bf0bade 100644 --- a/src/plugins/grass/qgsgrasseditrenderer.cpp +++ b/src/plugins/grass/qgsgrasseditrenderer.cpp @@ -173,7 +173,7 @@ void QgsGrassEditRenderer::stopRender( QgsRenderContext& context ) mMarkerRenderer->stopRender( context ); } -QList QgsGrassEditRenderer::usedAttributes() +QSet QgsGrassEditRenderer::usedAttributes() { return mLineRenderer->usedAttributes(); } diff --git a/src/plugins/grass/qgsgrasseditrenderer.h b/src/plugins/grass/qgsgrasseditrenderer.h index f60b0e330d0a..f4c796fe28ea 100644 --- a/src/plugins/grass/qgsgrasseditrenderer.h +++ b/src/plugins/grass/qgsgrasseditrenderer.h @@ -38,7 +38,7 @@ class QgsGrassEditRenderer : public QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ) override; - virtual QList usedAttributes() override; + virtual QSet usedAttributes() override; virtual QgsFeatureRenderer* clone() const override; From fbdc4149570d7dd2804eb0f42de1c1963b7a6b38 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 6 Oct 2016 07:15:45 +1000 Subject: [PATCH 179/897] Rename methods in QgsPanelWidgetStack for consistency --- doc/api_break.dox | 8 ++++++++ python/gui/qgspanelwidgetstack.sip | 19 +++++++++++++------ src/app/qgslayerstylingwidget.cpp | 19 +++++++++---------- src/gui/qgspanelwidgetstack.cpp | 6 +++--- src/gui/qgspanelwidgetstack.h | 19 +++++++++++++------ 5 files changed, 46 insertions(+), 25 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 8c97fd9f696d..3e0a804fca6b 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1090,6 +1090,14 @@ be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                  • prepareGeometry() and geometryRequiresPreparation() now take a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                  • +\subsection qgis_api_break_3_0_QgsPanelWidgetStack QgsPanelWidgetStack + +
                                                                                                                                                                                      +
                                                                                                                                                                                    • addMainPanel() has been renamed to setMainPanel()
                                                                                                                                                                                    • +
                                                                                                                                                                                    • mainWidget() has been renamed to mainPanel()
                                                                                                                                                                                    • +
                                                                                                                                                                                    • takeMainWidget() has been renamed to takeMainPanel()
                                                                                                                                                                                    • +
                                                                                                                                                                                    + \subsection qgis_api_break_3_0_QgsPluginLayer QgsPluginLayer
                                                                                                                                                                                      diff --git a/python/gui/qgspanelwidgetstack.sip b/python/gui/qgspanelwidgetstack.sip index e13357945f6b..941b5c397b3b 100644 --- a/python/gui/qgspanelwidgetstack.sip +++ b/python/gui/qgspanelwidgetstack.sip @@ -19,26 +19,33 @@ class QgsPanelWidgetStack: public QWidget QgsPanelWidgetStack( QWidget* parent = nullptr ); /** - * Adds the main widget to the stack and selects it for the user + * Adds the main panel widget to the stack and selects it for the user * The main widget can not be closed and only the showPanel signal is attached * to handle children widget opening panels. * @param panel The panel to set as the first widget in the stack. + * @note a stack can have only one main panel. Any existing main panel + * should be removed by first calling takeMainPanel(). + * @see mainPanel() + * @see takeMainPanel() */ - void addMainPanel( QgsPanelWidget* panel ); + void setMainPanel( QgsPanelWidget* panel ); /** - * The main widget that is set in the stack. The main widget can not be closed + * The main panel widget that is set in the stack. The main widget can not be closed * and doesn't display a back button. * @return The main QgsPanelWidget that is active in the stack. + * @see setMainPanel() */ - QgsPanelWidget* mainWidget(); + QgsPanelWidget* mainPanel(); /** - * Removes the main widget from the stack and transfers ownsership to the + * Removes the main panel widget from the stack and transfers ownsership to the * caller. * @return The main widget that is set in the stack. + * @see mainPanel() + * @see setMainPanel() */ - QgsPanelWidget* takeMainWidget(); + QgsPanelWidget* takeMainPanel(); /** * Clear the stack of all widgets. Unless the panels autoDelete is set to false diff --git a/src/app/qgslayerstylingwidget.cpp b/src/app/qgslayerstylingwidget.cpp index 0d6f575b67e9..fa83c4743832 100644 --- a/src/app/qgslayerstylingwidget.cpp +++ b/src/app/qgslayerstylingwidget.cpp @@ -226,7 +226,7 @@ void QgsLayerStylingWidget::apply() QString undoName = "Style Change"; - QWidget* current = mWidgetStack->mainWidget(); + QWidget* current = mWidgetStack->mainPanel(); bool styleWasChanged = false; if ( QgsLabelingWidget* widget = qobject_cast( current ) ) @@ -307,7 +307,7 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() mStackedWidget->setCurrentIndex( mLayerPage ); - QgsPanelWidget* current = mWidgetStack->takeMainWidget(); + QgsPanelWidget* current = mWidgetStack->takeMainPanel(); if ( current ) { if ( QgsLabelingWidget* widget = qobject_cast( current ) ) @@ -334,15 +334,14 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() if ( panel ) { connect( panel, SIGNAL( widgetChanged( QgsPanelWidget* ) ), this, SLOT( autoApply() ) ); - panel->setDockMode( true ); - mWidgetStack->addMainPanel( panel ); + mWidgetStack->setMainPanel( panel ); } } // The last widget is always the undo stack. if ( row == mOptionsListWidget->count() - 1 ) { - mWidgetStack->addMainPanel( mUndoWidget ); + mWidgetStack->setMainPanel( mUndoWidget ); } else if ( mCurrentLayer->type() == QgsMapLayer::VectorLayer ) { @@ -359,7 +358,7 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() QgsPanelWidgetWrapper* wrapper = new QgsPanelWidgetWrapper( styleWidget, mStackedWidget ); wrapper->setDockMode( true ); connect( styleWidget, SIGNAL( showPanel( QgsPanelWidget* ) ), wrapper, SLOT( openPanel( QgsPanelWidget* ) ) ); - mWidgetStack->addMainPanel( wrapper ); + mWidgetStack->setMainPanel( wrapper ); break; } case 1: // Labels @@ -371,7 +370,7 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() connect( mLabelingWidget, SIGNAL( widgetChanged() ), this, SLOT( autoApply() ) ); } mLabelingWidget->setLayer( vlayer ); - mWidgetStack->addMainPanel( mLabelingWidget ); + mWidgetStack->setMainPanel( mLabelingWidget ); break; } default: @@ -388,14 +387,14 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() mRasterStyleWidget = new QgsRendererRasterPropertiesWidget( rlayer, mMapCanvas, mWidgetStack ); mRasterStyleWidget->setDockMode( true ); connect( mRasterStyleWidget, SIGNAL( widgetChanged() ), this, SLOT( autoApply() ) ); - mWidgetStack->addMainPanel( mRasterStyleWidget ); + mWidgetStack->setMainPanel( mRasterStyleWidget ); break; case 1: // Transparency { QgsRasterTransparencyWidget* transwidget = new QgsRasterTransparencyWidget( rlayer, mMapCanvas, mWidgetStack ); transwidget->setDockMode( true ); connect( transwidget, SIGNAL( widgetChanged() ), this, SLOT( autoApply() ) ); - mWidgetStack->addMainPanel( transwidget ); + mWidgetStack->setMainPanel( transwidget ); break; } case 2: // Histogram @@ -417,7 +416,7 @@ void QgsLayerStylingWidget::updateCurrentWidgetLayer() widget->setRendererWidget( name, mRasterStyleWidget->currentRenderWidget() ); widget->setDockMode( true ); - mWidgetStack->addMainPanel( widget ); + mWidgetStack->setMainPanel( widget ); } break; } diff --git a/src/gui/qgspanelwidgetstack.cpp b/src/gui/qgspanelwidgetstack.cpp index 3b153dad5c25..0fbbb06ebc60 100644 --- a/src/gui/qgspanelwidgetstack.cpp +++ b/src/gui/qgspanelwidgetstack.cpp @@ -32,7 +32,7 @@ QgsPanelWidgetStack::QgsPanelWidgetStack( QWidget *parent ) connect( mBackButton, SIGNAL( pressed() ), this, SLOT( acceptCurrentPanel() ) ); } -void QgsPanelWidgetStack::addMainPanel( QgsPanelWidget *panel ) +void QgsPanelWidgetStack::setMainPanel( QgsPanelWidget *panel ) { // TODO Don't allow adding another main widget or else that would be strange for the user. connect( panel, SIGNAL( showPanel( QgsPanelWidget* ) ), this, SLOT( showPanel( QgsPanelWidget* ) ), @@ -43,12 +43,12 @@ void QgsPanelWidgetStack::addMainPanel( QgsPanelWidget *panel ) mStackedWidget->setCurrentIndex( 0 ); } -QgsPanelWidget *QgsPanelWidgetStack::mainWidget() +QgsPanelWidget *QgsPanelWidgetStack::mainPanel() { return qobject_cast( mStackedWidget->widget( 0 ) ); } -QgsPanelWidget *QgsPanelWidgetStack::takeMainWidget() +QgsPanelWidget *QgsPanelWidgetStack::takeMainPanel() { QWidget* widget = mStackedWidget->widget( 0 ); mStackedWidget->removeWidget( widget ); diff --git a/src/gui/qgspanelwidgetstack.h b/src/gui/qgspanelwidgetstack.h index 9c6e30a694c7..5ded4fa6e57e 100644 --- a/src/gui/qgspanelwidgetstack.h +++ b/src/gui/qgspanelwidgetstack.h @@ -43,26 +43,33 @@ class GUI_EXPORT QgsPanelWidgetStack : public QWidget, private Ui::QgsRendererWi QgsPanelWidgetStack( QWidget* parent = nullptr ); /** - * Adds the main widget to the stack and selects it for the user + * Adds the main panel widget to the stack and selects it for the user * The main widget can not be closed and only the showPanel signal is attached * to handle children widget opening panels. * @param panel The panel to set as the first widget in the stack. + * @note a stack can have only one main panel. Any existing main panel + * should be removed by first calling takeMainPanel(). + * @see mainPanel() + * @see takeMainPanel() */ - void addMainPanel( QgsPanelWidget* panel ); + void setMainPanel( QgsPanelWidget* panel ); /** - * The main widget that is set in the stack. The main widget can not be closed + * The main panel widget that is set in the stack. The main widget can not be closed * and doesn't display a back button. * @return The main QgsPanelWidget that is active in the stack. + * @see setMainPanel() */ - QgsPanelWidget* mainWidget(); + QgsPanelWidget* mainPanel(); /** - * Removes the main widget from the stack and transfers ownsership to the + * Removes the main panel widget from the stack and transfers ownsership to the * caller. * @return The main widget that is set in the stack. + * @see mainPanel() + * @see setMainPanel() */ - QgsPanelWidget* takeMainWidget(); + QgsPanelWidget* takeMainPanel(); /** * Clear the stack of all widgets. Unless the panels autoDelete is set to false From 37e3dd76c44b0a8f9247541ad87ad6d8987dde42 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 6 Oct 2016 08:09:54 +1000 Subject: [PATCH 180/897] When taking main widget from QgsPanelWidgetStack, auto accept all open child panel widgets Avoids the stack state becoming inconsistent because child panel widgets from a different main panel are still present And add unit tests for QgsPanelWidgetStack --- python/gui/qgspanelwidgetstack.sip | 14 ++ src/gui/qgspanelwidgetstack.cpp | 31 +++- src/gui/qgspanelwidgetstack.h | 17 ++ tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgspanelwidgetstack.py | 165 +++++++++++++++++++ 5 files changed, 225 insertions(+), 3 deletions(-) create mode 100644 tests/src/python/test_qgspanelwidgetstack.py diff --git a/python/gui/qgspanelwidgetstack.sip b/python/gui/qgspanelwidgetstack.sip index 941b5c397b3b..17566eb04109 100644 --- a/python/gui/qgspanelwidgetstack.sip +++ b/python/gui/qgspanelwidgetstack.sip @@ -53,15 +53,29 @@ class QgsPanelWidgetStack: public QWidget */ void clear(); + /** + * Returns the panel currently shown in the stack. + * @note added in QGIS 3.0 + */ + QgsPanelWidget* currentPanel(); public slots: /** * Accept the current active widget in the stack. * * Calls the panelAccepeted signal on the active widget. + * @see acceptAllPanels() */ void acceptCurrentPanel(); + /** + * Accepts all panel widgets open in the stack in turn until until only the mainPanel() + * remains. + * @see acceptCurrentPanel(); + * @note added in QGIS 3.0 + */ + void acceptAllPanels(); + /** * Show a panel in the stack widget. Will connect to the panels showPanel event to handle * nested panels. Auto switches the the given panel for the user. diff --git a/src/gui/qgspanelwidgetstack.cpp b/src/gui/qgspanelwidgetstack.cpp index 0fbbb06ebc60..5a8e0195cf70 100644 --- a/src/gui/qgspanelwidgetstack.cpp +++ b/src/gui/qgspanelwidgetstack.cpp @@ -50,6 +50,9 @@ QgsPanelWidget *QgsPanelWidgetStack::mainPanel() QgsPanelWidget *QgsPanelWidgetStack::takeMainPanel() { + // clear out the current stack + acceptAllPanels(); + QWidget* widget = mStackedWidget->widget( 0 ); mStackedWidget->removeWidget( widget ); return qobject_cast( widget ); @@ -57,7 +60,7 @@ QgsPanelWidget *QgsPanelWidgetStack::takeMainPanel() void QgsPanelWidgetStack::clear() { - for ( int i = mStackedWidget->count(); i >= 0; i-- ) + for ( int i = mStackedWidget->count() - 1; i >= 0; i-- ) { if ( QgsPanelWidget* panelWidget = qobject_cast( mStackedWidget->widget( i ) ) ) { @@ -79,16 +82,38 @@ void QgsPanelWidgetStack::clear() this->updateBreadcrumb(); } +QgsPanelWidget* QgsPanelWidgetStack::currentPanel() +{ + return qobject_cast( mStackedWidget->currentWidget() ); +} + void QgsPanelWidgetStack::acceptCurrentPanel() { // You can't accept the main panel. - if ( mStackedWidget->currentIndex() == 0 ) + if ( mStackedWidget->currentIndex() <= 0 ) return; - QgsPanelWidget* widget = qobject_cast( mStackedWidget->currentWidget() ); + QgsPanelWidget* widget = currentPanel(); widget->acceptPanel(); } +void QgsPanelWidgetStack::acceptAllPanels() +{ + //avoid messy multiple redraws + setUpdatesEnabled( false ); + mStackedWidget->setUpdatesEnabled( false ); + + for ( int i = mStackedWidget->count() - 1; i > 0; --i ) + { + if ( QgsPanelWidget* panelWidget = qobject_cast( mStackedWidget->widget( i ) ) ) + { + panelWidget->acceptPanel(); + } + } + setUpdatesEnabled( true ); + mStackedWidget->setUpdatesEnabled( true ); +} + void QgsPanelWidgetStack::showPanel( QgsPanelWidget *panel ) { mTitles.push( panel->panelTitle() ); diff --git a/src/gui/qgspanelwidgetstack.h b/src/gui/qgspanelwidgetstack.h index 5ded4fa6e57e..bafcefb22759 100644 --- a/src/gui/qgspanelwidgetstack.h +++ b/src/gui/qgspanelwidgetstack.h @@ -66,6 +66,8 @@ class GUI_EXPORT QgsPanelWidgetStack : public QWidget, private Ui::QgsRendererWi * Removes the main panel widget from the stack and transfers ownsership to the * caller. * @return The main widget that is set in the stack. + * @note Calling this will clear out any current stacked panels by accepting + * each panel in turn. * @see mainPanel() * @see setMainPanel() */ @@ -77,14 +79,29 @@ class GUI_EXPORT QgsPanelWidgetStack : public QWidget, private Ui::QgsRendererWi */ void clear(); + /** + * Returns the panel currently shown in the stack. + * @note added in QGIS 3.0 + */ + QgsPanelWidget* currentPanel(); + public slots: /** * Accept the current active widget in the stack. * * Calls the panelAccepeted signal on the active widget. + * @see acceptAllPanels() */ void acceptCurrentPanel(); + /** + * Accepts all panel widgets open in the stack in turn until until only the mainPanel() + * remains. + * @see acceptCurrentPanel(); + * @note added in QGIS 3.0 + */ + void acceptAllPanels(); + /** * Show a panel in the stack widget. Will connect to the panels showPanel event to handle * nested panels. Auto switches the the given panel for the user. diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index c02fd02e36c1..e86c51356057 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -69,6 +69,7 @@ ADD_PYTHON_TEST(PyQgsPalLabelingCanvas test_qgspallabeling_canvas.py) ADD_PYTHON_TEST(PyQgsPalLabelingComposer test_qgspallabeling_composer.py) ADD_PYTHON_TEST(PyQgsPalLabelingPlacement test_qgspallabeling_placement.py) ADD_PYTHON_TEST(PyQgsPanelWidget test_qgspanelwidget.py) +ADD_PYTHON_TEST(PyQgsPanelWidgetStack test_qgspanelwidgetstack.py) ADD_PYTHON_TEST(PyQgsPoint test_qgspoint.py) ADD_PYTHON_TEST(PyQgsPointClusterRenderer test_qgspointclusterrenderer.py) ADD_PYTHON_TEST(PyQgsPointDisplacementRenderer test_qgspointdisplacementrenderer.py) diff --git a/tests/src/python/test_qgspanelwidgetstack.py b/tests/src/python/test_qgspanelwidgetstack.py new file mode 100644 index 000000000000..4933acba253f --- /dev/null +++ b/tests/src/python/test_qgspanelwidgetstack.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsPanelWidgetStack. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '05/10/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +from qgis.PyQt.QtWidgets import QWidget +from qgis.gui import QgsPanelWidget, QgsPanelWidgetStack +from qgis.testing import start_app, unittest +from qgis.PyQt.QtTest import QSignalSpy + +start_app() + + +class TestQgsPanelWidgetStack(unittest.TestCase): + + def testMainPanel(self): + """ test mainPanel methods """ + + s = QgsPanelWidgetStack() + + # no main panel + self.assertFalse(s.mainPanel()) + self.assertFalse(s.takeMainPanel()) + + # set main panel + p1 = QgsPanelWidget() + s.setMainPanel(p1) + self.assertEqual(s.mainPanel(), p1) + + # takeMainPanel() + self.assertEqual(s.takeMainPanel(), p1) + self.assertFalse(s.mainPanel()) + self.assertFalse(s.takeMainPanel()) + + def testAddingPanels(self): + """ test adding panels to stack """ + + s = QgsPanelWidgetStack() + mp = QgsPanelWidget() + s.setMainPanel(mp) + + p1 = QgsPanelWidget() + s.showPanel(p1) + self.assertEqual(s.currentPanel(), p1) + + p2 = QgsPanelWidget() + s.showPanel(p2) + self.assertEqual(s.currentPanel(), p2) + + def testAcceptCurrentPanel(self): + """ test accepting current panel """ + + s = QgsPanelWidgetStack() + # call on empty stack + s.acceptCurrentPanel() + + mp = QgsPanelWidget() + s.setMainPanel(mp) + # call on main panel - should be no effect + s.acceptCurrentPanel() + self.assertEqual(s.mainPanel(), mp) + self.assertEqual(s.currentPanel(), mp) + + # add panels + p1 = QgsPanelWidget() + s.showPanel(p1) + p2 = QgsPanelWidget() + s.showPanel(p2) + + # accept them + self.assertEqual(s.currentPanel(), p2) + p2_accept_spy = QSignalSpy(p2.panelAccepted) + s.acceptCurrentPanel() + self.assertEqual(s.currentPanel(), p1) + self.assertEqual(len(p2_accept_spy), 1) + p1_accept_spy = QSignalSpy(p1.panelAccepted) + s.acceptCurrentPanel() + self.assertEqual(s.currentPanel(), mp) + self.assertEqual(len(p1_accept_spy), 1) + + def testAcceptAllPanel(self): + """ test accepting all panels """ + s = QgsPanelWidgetStack() + # call on empty stack + s.acceptAllPanels() + + mp = QgsPanelWidget() + s.setMainPanel(mp) + # call on main panel - should be no effect + s.acceptAllPanels() + self.assertEqual(s.mainPanel(), mp) + self.assertEqual(s.currentPanel(), mp) + + # add panels + p1 = QgsPanelWidget() + s.showPanel(p1) + p1_accept_spy = QSignalSpy(p1.panelAccepted) + p2 = QgsPanelWidget() + s.showPanel(p2) + p2_accept_spy = QSignalSpy(p2.panelAccepted) + p3 = QgsPanelWidget() + s.showPanel(p3) + p3_accept_spy = QSignalSpy(p3.panelAccepted) + + # accept all + s.acceptAllPanels() + self.assertEqual(s.currentPanel(), mp) + self.assertEqual(len(p1_accept_spy), 1) + self.assertEqual(len(p2_accept_spy), 1) + self.assertEqual(len(p3_accept_spy), 1) + + def testClear(self): + """ test clearing stack """ + s = QgsPanelWidgetStack() + # call on empty stack + s.clear() + + # add panels + mp = QgsPanelWidget() + s.setMainPanel(mp) + p1 = QgsPanelWidget() + s.showPanel(p1) + p2 = QgsPanelWidget() + s.showPanel(p2) + p3 = QgsPanelWidget() + s.showPanel(p3) + + # clear + s.clear() + self.assertFalse(s.currentPanel()) + self.assertFalse(s.mainPanel()) + + def testTakeMainAcceptsAll(self): + """ test that taking the main panel accepts all open child panels""" + s = QgsPanelWidgetStack() + mp = QgsPanelWidget() + s.setMainPanel(mp) + p1 = QgsPanelWidget() + s.showPanel(p1) + p1_accept_spy = QSignalSpy(p1.panelAccepted) + p2 = QgsPanelWidget() + s.showPanel(p2) + p2_accept_spy = QSignalSpy(p2.panelAccepted) + p3 = QgsPanelWidget() + s.showPanel(p3) + p3_accept_spy = QSignalSpy(p3.panelAccepted) + + # take main + s.takeMainPanel() + self.assertEqual(len(p1_accept_spy), 1) + self.assertEqual(len(p2_accept_spy), 1) + self.assertEqual(len(p3_accept_spy), 1) +if __name__ == '__main__': + unittest.main() From c6436f897129829647e79654bdc8530367c5de62 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 6 Oct 2016 18:50:45 +1000 Subject: [PATCH 181/897] Make modifications through the style dock much faster Before any change in the style dock would invalidate the cache for ALL map layers, resulting in every layer being redrawn. Now only the affected layer is redrawn and all others just use the cached render. --- src/app/qgslayerstylingwidget.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app/qgslayerstylingwidget.cpp b/src/app/qgslayerstylingwidget.cpp index fa83c4743832..27c170dadff6 100644 --- a/src/app/qgslayerstylingwidget.cpp +++ b/src/app/qgslayerstylingwidget.cpp @@ -268,8 +268,7 @@ void QgsLayerStylingWidget::apply() { emit styleChanged( mCurrentLayer ); QgsProject::instance()->setDirty( true ); - mMapCanvas->clearCache(); - mMapCanvas->refresh(); + mCurrentLayer->triggerRepaint(); } connect( mCurrentLayer, SIGNAL( styleChanged() ), this, SLOT( updateCurrentWidgetLayer() ) ); } From 028db7e54182a82c4e64e955dfe4971210b21f5b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 6 Oct 2016 08:13:05 +1000 Subject: [PATCH 182/897] [FEATURE] Port composer config widgets to QgsPanelWidgets Brings the inline (ie, no modal dialogs!) color modification and symbol editing from the layer styling panel to composer item configuration. --- src/app/composer/qgscomposer.cpp | 26 +++--- src/app/composer/qgscomposer.h | 5 +- src/app/composer/qgscomposerarrowwidget.cpp | 1 + .../qgscomposerattributetablewidget.cpp | 1 + src/app/composer/qgscomposerhtmlwidget.cpp | 1 + src/app/composer/qgscomposeritemwidget.cpp | 87 +++++++++++-------- src/app/composer/qgscomposeritemwidget.h | 77 +++++++++++++--- src/app/composer/qgscomposerlabelwidget.cpp | 1 + src/app/composer/qgscomposerlegendwidget.cpp | 1 + src/app/composer/qgscomposermapwidget.cpp | 1 + src/app/composer/qgscomposerpicturewidget.cpp | 1 + src/app/composer/qgscomposerpolygonwidget.cpp | 1 + .../composer/qgscomposerpolylinewidget.cpp | 1 + .../composer/qgscomposerscalebarwidget.cpp | 2 + src/app/composer/qgscomposershapewidget.cpp | 37 +++++--- src/app/composer/qgscomposershapewidget.h | 2 + 16 files changed, 174 insertions(+), 71 deletions(-) diff --git a/src/app/composer/qgscomposer.cpp b/src/app/composer/qgscomposer.cpp index 064449321889..cd55b1f2740a 100644 --- a/src/app/composer/qgscomposer.cpp +++ b/src/app/composer/qgscomposer.cpp @@ -67,6 +67,7 @@ #include "qgsvectorlayer.h" #include "qgscomposerimageexportoptionsdialog.h" #include "ui_qgssvgexportoptions.h" +#include "qgspanelwidgetstack.h" #include #include @@ -578,6 +579,8 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) mItemDock = new QgsDockWidget( tr( "Item properties" ), this ); mItemDock->setObjectName( "ItemDock" ); mItemDock->setMinimumWidth( minDockWidth ); + mItemPropertiesStack = new QgsPanelWidgetStack(); + mItemDock->setWidget( mItemPropertiesStack ); mPanelMenu->addAction( mItemDock->toggleViewAction() ); mUndoDock = new QgsDockWidget( tr( "Command history" ), this ); mUndoDock->setObjectName( "CommandDock" ); @@ -996,28 +999,27 @@ void QgsComposer::updateStatusAtlasMsg( const QString& message ) void QgsComposer::showItemOptions( QgsComposerItem* item ) { - QWidget* currentWidget = mItemDock->widget(); - if ( !item ) { - mItemDock->setWidget( nullptr ); + mItemPropertiesStack->takeMainPanel(); return; } - QMap::const_iterator it = mItemWidgetMap.constFind( item ); + QMap::const_iterator it = mItemWidgetMap.constFind( item ); if ( it == mItemWidgetMap.constEnd() ) { return; } - QWidget* newWidget = it.value(); - - if ( !newWidget || newWidget == currentWidget ) //bail out if new widget does not exist or is already there + QgsPanelWidget* newWidget = it.value(); + if ( !newWidget || newWidget == mItemPropertiesStack->mainPanel() ) //bail out if new widget does not exist or is already there { return; } - mItemDock->setWidget( newWidget ); + ( void ) mItemPropertiesStack->takeMainPanel(); + newWidget->setDockMode( true ); + mItemPropertiesStack->setMainPanel( newWidget ); } void QgsComposer::on_mActionOptions_triggered() @@ -3774,7 +3776,7 @@ void QgsComposer::addComposerHtmlFrame( QgsComposerHtml* html, QgsComposerFrame* void QgsComposer::deleteItem( QgsComposerItem* item ) { - QMap::const_iterator it = mItemWidgetMap.constFind( item ); + QMap::const_iterator it = mItemWidgetMap.constFind( item ); if ( it == mItemWidgetMap.constEnd() ) { @@ -3800,7 +3802,7 @@ void QgsComposer::setSelectionTool() bool QgsComposer::containsWmsLayer() const { - QMap::const_iterator item_it = mItemWidgetMap.constBegin(); + QMap::const_iterator item_it = mItemWidgetMap.constBegin(); QgsComposerItem* currentItem = nullptr; QgsComposerMap* currentMap = nullptr; @@ -3822,7 +3824,7 @@ bool QgsComposer::containsWmsLayer() const bool QgsComposer::containsAdvancedEffects() const { // Check if composer contains any blend modes or flattened layers for transparency - QMap::const_iterator item_it = mItemWidgetMap.constBegin(); + QMap::const_iterator item_it = mItemWidgetMap.constBegin(); QgsComposerItem* currentItem = nullptr; QgsComposerMap* currentMap = nullptr; @@ -3893,7 +3895,7 @@ void QgsComposer::showAdvancedEffectsWarning() void QgsComposer::cleanupAfterTemplateRead() { - QMap::const_iterator itemIt = mItemWidgetMap.constBegin(); + QMap::const_iterator itemIt = mItemWidgetMap.constBegin(); for ( ; itemIt != mItemWidgetMap.constEnd(); ++itemIt ) { //update all legends completely diff --git a/src/app/composer/qgscomposer.h b/src/app/composer/qgscomposer.h index 05043a3a4f69..664d693ff936 100644 --- a/src/app/composer/qgscomposer.h +++ b/src/app/composer/qgscomposer.h @@ -18,6 +18,7 @@ #define QGSCOMPOSER_H #include "ui_qgscomposerbase.h" +#include "qgspanelwidget.h" class QgisApp; class QgsComposerArrow; class QgsComposerPolygon; @@ -44,6 +45,7 @@ class QgsDockWidget; class QgsMapLayer; class QgsFeature; class QgsVectorLayer; +class QgsPanelWidgetStack; class QGridLayout; class QDomNode; @@ -568,7 +570,7 @@ class QgsComposer: public QMainWindow, private Ui::QgsComposerBase QSizeGrip *mSizeGrip; //! To know which item to show if selection changes - QMap mItemWidgetMap; + QMap mItemWidgetMap; //! Window menu action to select this window QAction *mWindowAction; @@ -597,6 +599,7 @@ class QgsComposer: public QMainWindow, private Ui::QgsComposerBase QMap< QgsComposerMap*, int > mMapsToRestore; QgsDockWidget* mItemDock; + QgsPanelWidgetStack* mItemPropertiesStack; QgsDockWidget* mUndoDock; QgsDockWidget* mGeneralDock; QgsDockWidget* mAtlasDock; diff --git a/src/app/composer/qgscomposerarrowwidget.cpp b/src/app/composer/qgscomposerarrowwidget.cpp index 47effd16247d..bffe84645379 100644 --- a/src/app/composer/qgscomposerarrowwidget.cpp +++ b/src/app/composer/qgscomposerarrowwidget.cpp @@ -28,6 +28,7 @@ QgsComposerArrowWidget::QgsComposerArrowWidget( QgsComposerArrow* arrow ): QgsComposerItemBaseWidget( nullptr, arrow ), mArrow( arrow ) { setupUi( this ); + setPanelTitle( tr( "Arrow properties" ) ); mRadioButtonGroup = new QButtonGroup( this ); mRadioButtonGroup->addButton( mDefaultMarkerRadioButton ); mRadioButtonGroup->addButton( mNoMarkerRadioButton ); diff --git a/src/app/composer/qgscomposerattributetablewidget.cpp b/src/app/composer/qgscomposerattributetablewidget.cpp index 963a128d5874..138f8e8772d6 100644 --- a/src/app/composer/qgscomposerattributetablewidget.cpp +++ b/src/app/composer/qgscomposerattributetablewidget.cpp @@ -39,6 +39,7 @@ QgsComposerAttributeTableWidget::QgsComposerAttributeTableWidget( QgsComposerAtt , mFrame( frame ) { setupUi( this ); + setPanelTitle( tr( "Table properties" ) ); blockAllSignals( true ); diff --git a/src/app/composer/qgscomposerhtmlwidget.cpp b/src/app/composer/qgscomposerhtmlwidget.cpp index 5c0a904c8567..ca4c48eba1a7 100644 --- a/src/app/composer/qgscomposerhtmlwidget.cpp +++ b/src/app/composer/qgscomposerhtmlwidget.cpp @@ -31,6 +31,7 @@ QgsComposerHtmlWidget::QgsComposerHtmlWidget( QgsComposerHtml* html, QgsComposer , mFrame( frame ) { setupUi( this ); + setPanelTitle( tr( "HTML properties" ) ); //setup html editor mHtmlEditor = new QgsCodeEditorHTML( this ); diff --git a/src/app/composer/qgscomposeritemwidget.cpp b/src/app/composer/qgscomposeritemwidget.cpp index f699d9723723..e6295ac5c2be 100644 --- a/src/app/composer/qgscomposeritemwidget.cpp +++ b/src/app/composer/qgscomposeritemwidget.cpp @@ -30,18 +30,20 @@ //QgsComposerItemBaseWidget -QgsComposerItemBaseWidget::QgsComposerItemBaseWidget( QWidget* parent, QgsComposerObject *composerObject ): QWidget( parent ), mComposerObject( composerObject ) +QgsComposerConfigObject::QgsComposerConfigObject( QWidget* parent, QgsComposerObject *composerObject ) + : QObject( parent ) + , mComposerObject( composerObject ) { connect( atlasComposition(), SIGNAL( coverageLayerChanged( QgsVectorLayer* ) ), this, SLOT( updateDataDefinedButtons() ) ); connect( atlasComposition(), SIGNAL( toggled( bool ) ), this, SLOT( updateDataDefinedButtons() ) ); } -QgsComposerItemBaseWidget::~QgsComposerItemBaseWidget() +QgsComposerConfigObject::~QgsComposerConfigObject() { } -void QgsComposerItemBaseWidget::updateDataDefinedProperty() +void QgsComposerConfigObject::updateDataDefinedProperty() { //match data defined button to item's data defined property QgsDataDefinedButton* ddButton = dynamic_cast( sender() ); @@ -64,7 +66,7 @@ void QgsComposerItemBaseWidget::updateDataDefinedProperty() mComposerObject->refreshDataDefinedProperty( property ); } -void QgsComposerItemBaseWidget::updateDataDefinedButtons() +void QgsComposerConfigObject::updateDataDefinedButtons() { Q_FOREACH ( QgsDataDefinedButton* button, findChildren< QgsDataDefinedButton* >() ) { @@ -72,7 +74,7 @@ void QgsComposerItemBaseWidget::updateDataDefinedButtons() } } -void QgsComposerItemBaseWidget::setDataDefinedProperty( const QgsDataDefinedButton *ddBtn, QgsComposerObject::DataDefinedProperty p ) +void QgsComposerConfigObject::setDataDefinedProperty( const QgsDataDefinedButton *ddBtn, QgsComposerObject::DataDefinedProperty p ) { if ( !mComposerObject ) { @@ -83,7 +85,7 @@ void QgsComposerItemBaseWidget::setDataDefinedProperty( const QgsDataDefinedButt mComposerObject->setDataDefinedProperty( p, map.value( "active" ).toInt(), map.value( "useexpr" ).toInt(), map.value( "expression" ), map.value( "field" ) ); } -void QgsComposerItemBaseWidget::registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, +void QgsComposerConfigObject::registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, QgsDataDefinedButton::DataType type, const QString& description ) { button->blockSignals( true ); @@ -98,7 +100,7 @@ void QgsComposerItemBaseWidget::registerDataDefinedButton( QgsDataDefinedButton* button->blockSignals( false ); } -QgsAtlasComposition* QgsComposerItemBaseWidget::atlasComposition() const +QgsAtlasComposition* QgsComposerConfigObject::atlasComposition() const { if ( !mComposerObject ) { @@ -115,7 +117,7 @@ QgsAtlasComposition* QgsComposerItemBaseWidget::atlasComposition() const return &composition->atlasComposition(); } -QgsVectorLayer* QgsComposerItemBaseWidget::atlasCoverageLayer() const +QgsVectorLayer* QgsComposerConfigObject::atlasCoverageLayer() const { QgsAtlasComposition* atlasMap = atlasComposition(); @@ -140,8 +142,9 @@ void QgsComposerItemWidget::updateVariables() } QgsComposerItemWidget::QgsComposerItemWidget( QWidget* parent, QgsComposerItem* item ) - : QgsComposerItemBaseWidget( parent, item ) + : QWidget( parent ) , mItem( item ) + , mConfigObject( new QgsComposerConfigObject( this, item ) ) , mFreezeXPosSpin( false ) , mFreezeYPosSpin( false ) , mFreezeWidthSpin( false ) @@ -184,18 +187,6 @@ QgsComposerItemWidget::QgsComposerItemWidget( QWidget* parent, QgsComposerItem* connect( mItem->composition(), SIGNAL( variablesChanged() ), this, SLOT( updateVariables() ) ); } -QgsComposerItemWidget::QgsComposerItemWidget() - : QgsComposerItemBaseWidget( nullptr, nullptr ) - , mItem( nullptr ) - , mFreezeXPosSpin( false ) - , mFreezeYPosSpin( false ) - , mFreezeWidthSpin( false ) - , mFreezeHeightSpin( false ) - , mFreezePageSpin( false ) -{ - -} - QgsComposerItemWidget::~QgsComposerItemWidget() { @@ -552,22 +543,22 @@ void QgsComposerItemWidget::setValuesForGuiNonPositionElements() void QgsComposerItemWidget::populateDataDefinedButtons() { - registerDataDefinedButton( mXPositionDDBtn, QgsComposerObject::PositionX, - QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mYPositionDDBtn, QgsComposerObject::PositionY, - QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mWidthDDBtn, QgsComposerObject::ItemWidth, - QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mHeightDDBtn, QgsComposerObject::ItemHeight, - QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mItemRotationDDBtn, QgsComposerObject::ItemRotation, - QgsDataDefinedButton::AnyType, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mTransparencyDDBtn, QgsComposerObject::Transparency, - QgsDataDefinedButton::AnyType, QgsDataDefinedButton::intTranspDesc() ); - registerDataDefinedButton( mBlendModeDDBtn, QgsComposerObject::BlendMode, - QgsDataDefinedButton::String, QgsDataDefinedButton::blendModesDesc() ); - registerDataDefinedButton( mExcludePrintsDDBtn, QgsComposerObject::ExcludeFromExports, - QgsDataDefinedButton::String, QgsDataDefinedButton::boolDesc() ); + mConfigObject->registerDataDefinedButton( mXPositionDDBtn, QgsComposerObject::PositionX, + QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); + mConfigObject->registerDataDefinedButton( mYPositionDDBtn, QgsComposerObject::PositionY, + QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); + mConfigObject->registerDataDefinedButton( mWidthDDBtn, QgsComposerObject::ItemWidth, + QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); + mConfigObject->registerDataDefinedButton( mHeightDDBtn, QgsComposerObject::ItemHeight, + QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); + mConfigObject->registerDataDefinedButton( mItemRotationDDBtn, QgsComposerObject::ItemRotation, + QgsDataDefinedButton::AnyType, QgsDataDefinedButton::double180RotDesc() ); + mConfigObject->registerDataDefinedButton( mTransparencyDDBtn, QgsComposerObject::Transparency, + QgsDataDefinedButton::AnyType, QgsDataDefinedButton::intTranspDesc() ); + mConfigObject->registerDataDefinedButton( mBlendModeDDBtn, QgsComposerObject::BlendMode, + QgsDataDefinedButton::String, QgsDataDefinedButton::blendModesDesc() ); + mConfigObject->registerDataDefinedButton( mExcludePrintsDDBtn, QgsComposerObject::ExcludeFromExports, + QgsDataDefinedButton::String, QgsDataDefinedButton::boolDesc() ); } void QgsComposerItemWidget::setValuesForGuiElements() @@ -786,3 +777,25 @@ void QgsComposerItemWidget::on_mExcludeFromPrintsCheckBox_toggled( bool checked mItem->endCommand(); } } + +QgsComposerItemBaseWidget::QgsComposerItemBaseWidget( QWidget* parent, QgsComposerObject* composerObject ) + : QgsPanelWidget( parent ) + , mConfigObject( new QgsComposerConfigObject( this, composerObject ) ) +{ + +} + +void QgsComposerItemBaseWidget::registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, QgsDataDefinedButton::DataType type, const QString& description ) +{ + mConfigObject->registerDataDefinedButton( button, property, type, description ); +} + +QgsVectorLayer* QgsComposerItemBaseWidget::atlasCoverageLayer() const +{ + return mConfigObject->atlasCoverageLayer(); +} + +QgsAtlasComposition* QgsComposerItemBaseWidget::atlasComposition() const +{ + return mConfigObject->atlasComposition(); +} diff --git a/src/app/composer/qgscomposeritemwidget.h b/src/app/composer/qgscomposeritemwidget.h index b4004be32053..defdec92514b 100644 --- a/src/app/composer/qgscomposeritemwidget.h +++ b/src/app/composer/qgscomposeritemwidget.h @@ -20,31 +20,84 @@ #include "ui_qgscomposeritemwidgetbase.h" #include "qgscomposeritem.h" +#include "qgspanelwidget.h" class QgsComposerItem; class QgsAtlasComposition; class QgsDataDefinedButton; -/** A base class for property widgets for composer items. All composer item widgets should inherit from - * this base class. + +// NOTE - the inheritance here is tricky, as we need to avoid the multiple inheritance +// diamond problem and the ideal base object (QgsComposerConfigObject) MUST be a QObject +// because of its slots. + +// So here we go: +// QgsComposerItemWidget is just a QWidget which is embedded inside specific item property +// widgets and contains common settings like position and rotation of the items. While the +// actual individual item type widgets MUST be QgsPanelWidgets unfortunately QgsComposerItemWidget +// CANNOT be a QgsPanelWidget and must instead be a generic QWidget (otherwise a QgsPanelWidget +// contains a child QgsPanelWidget, which breaks lots of assumptions made in QgsPanelWidget +// and related classes). +// So QgsComposerItemWidget HAS a QgsComposerConfigObject to handle these common tasks. +// Specific item property widgets (eg QgsComposerMapWidget) should inherit from QgsComposerItemBaseWidget +// (which is a QgsPanelWidget) and also HAS a QgsComposerConfigObject, with protected methods +// which are just proxied through to the QgsComposerConfigObject. +// phew! +// long story short - don't change this without good reason. If you add a new item type, inherit +// from QgsComposerItemWidget and trust that everything else has been done for you. + +/** An object for property widgets for composer items. All composer config type widgets should contain + * this object. */ -class QgsComposerItemBaseWidget: public QWidget +class QgsComposerConfigObject: public QObject { Q_OBJECT public: - QgsComposerItemBaseWidget( QWidget* parent, QgsComposerObject* composerObject ); - ~QgsComposerItemBaseWidget(); + QgsComposerConfigObject( QWidget* parent, QgsComposerObject* composerObject ); + ~QgsComposerConfigObject(); - protected slots: + /** Sets a data defined property for the item from its current data defined button settings*/ + void setDataDefinedProperty( const QgsDataDefinedButton *ddBtn, QgsComposerObject::DataDefinedProperty p ); + + /** Registers a data defined button, setting up its initial value, connections and description. + * @param button button to register + * @param property correponding data defined property + * @param type valid data types for button + * @param description user visible description for data defined property + */ + void registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, + QgsDataDefinedButton::DataType type, const QString& description ); + + /** Returns the current atlas coverage layer (if set)*/ + QgsVectorLayer* atlasCoverageLayer() const; + + /** Returns the atlas for the composition*/ + QgsAtlasComposition *atlasComposition() const; + + private slots: /** Must be called when a data defined button changes*/ void updateDataDefinedProperty(); //! Updates data defined buttons to reflect current state of atlas (eg coverage layer) void updateDataDefinedButtons(); + private: + + QgsComposerObject* mComposerObject; +}; + +/** + * A base class for property widgets for composer items. All composer item widgets should inherit from + * this base class. + */ +class QgsComposerItemBaseWidget: public QgsPanelWidget +{ + Q_OBJECT + + public: + QgsComposerItemBaseWidget( QWidget* parent, QgsComposerObject* composerObject ); + protected: - /** Sets a data defined property for the item from its current data defined button settings*/ - void setDataDefinedProperty( const QgsDataDefinedButton *ddBtn, QgsComposerObject::DataDefinedProperty p ); /** Registers a data defined button, setting up its initial value, connections and description. * @param button button to register @@ -61,12 +114,14 @@ class QgsComposerItemBaseWidget: public QWidget /** Returns the atlas for the composition*/ QgsAtlasComposition *atlasComposition() const; - QgsComposerObject* mComposerObject; + private: + + QgsComposerConfigObject* mConfigObject; }; /** A class to enter generic properties for composer items (e.g. background, outline, frame). This widget can be embedded into other item widgets*/ -class QgsComposerItemWidget: public QgsComposerItemBaseWidget, private Ui::QgsComposerItemWidgetBase +class QgsComposerItemWidget: public QWidget, private Ui::QgsComposerItemWidgetBase { Q_OBJECT public: @@ -132,9 +187,9 @@ class QgsComposerItemWidget: public QgsComposerItemBaseWidget, private Ui::QgsCo void populateDataDefinedButtons(); private: - QgsComposerItemWidget(); QgsComposerItem* mItem; + QgsComposerConfigObject* mConfigObject; bool mFreezeXPosSpin; bool mFreezeYPosSpin; diff --git a/src/app/composer/qgscomposerlabelwidget.cpp b/src/app/composer/qgscomposerlabelwidget.cpp index 1fd9fdc1807a..855557d5a751 100644 --- a/src/app/composer/qgscomposerlabelwidget.cpp +++ b/src/app/composer/qgscomposerlabelwidget.cpp @@ -29,6 +29,7 @@ QgsComposerLabelWidget::QgsComposerLabelWidget( QgsComposerLabel* label ): QgsComposerItemBaseWidget( nullptr, label ), mComposerLabel( label ) { setupUi( this ); + setPanelTitle( tr( "Label properties" ) ); //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, label ); diff --git a/src/app/composer/qgscomposerlegendwidget.cpp b/src/app/composer/qgscomposerlegendwidget.cpp index 2cd9e12452fc..f00ba5db41dc 100644 --- a/src/app/composer/qgscomposerlegendwidget.cpp +++ b/src/app/composer/qgscomposerlegendwidget.cpp @@ -47,6 +47,7 @@ QgsComposerLegendWidget::QgsComposerLegendWidget( QgsComposerLegend* legend ) , mLegend( legend ) { setupUi( this ); + setPanelTitle( tr( "Legend properties" ) ); // setup icons mAddToolButton->setIcon( QIcon( QgsApplication::iconPath( "symbologyAdd.svg" ) ) ); diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index 753c5f913abb..7a4880836745 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -48,6 +48,7 @@ QgsComposerMapWidget::QgsComposerMapWidget( QgsComposerMap* composerMap ) , mComposerMap( composerMap ) { setupUi( this ); + setPanelTitle( tr( "Map properties" ) ); //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, composerMap ); diff --git a/src/app/composer/qgscomposerpicturewidget.cpp b/src/app/composer/qgscomposerpicturewidget.cpp index b10871961088..9ecffd1e996a 100644 --- a/src/app/composer/qgscomposerpicturewidget.cpp +++ b/src/app/composer/qgscomposerpicturewidget.cpp @@ -36,6 +36,7 @@ QgsComposerPictureWidget::QgsComposerPictureWidget( QgsComposerPicture* picture ): QgsComposerItemBaseWidget( nullptr, picture ), mPicture( picture ), mPreviewsLoaded( false ) { setupUi( this ); + setPanelTitle( tr( "Picture properties" ) ); mFillColorButton->setAllowAlpha( true ); mFillColorButton->setColorDialogTitle( tr( "Select fill color" ) ); diff --git a/src/app/composer/qgscomposerpolygonwidget.cpp b/src/app/composer/qgscomposerpolygonwidget.cpp index 8a0832814a84..cf20635f5a58 100644 --- a/src/app/composer/qgscomposerpolygonwidget.cpp +++ b/src/app/composer/qgscomposerpolygonwidget.cpp @@ -26,6 +26,7 @@ QgsComposerPolygonWidget::QgsComposerPolygonWidget( QgsComposerPolygon* composer , mComposerPolygon( composerPolygon ) { setupUi( this ); + setPanelTitle( tr( "Polygon properties" ) ); //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, composerPolygon ); diff --git a/src/app/composer/qgscomposerpolylinewidget.cpp b/src/app/composer/qgscomposerpolylinewidget.cpp index f16bef6c8233..5e0777713ca1 100644 --- a/src/app/composer/qgscomposerpolylinewidget.cpp +++ b/src/app/composer/qgscomposerpolylinewidget.cpp @@ -26,6 +26,7 @@ QgsComposerPolylineWidget::QgsComposerPolylineWidget( QgsComposerPolyline* compo , mComposerPolyline( composerPolyline ) { setupUi( this ); + setPanelTitle( tr( "Polyline properties" ) ); //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, composerPolyline ); diff --git a/src/app/composer/qgscomposerscalebarwidget.cpp b/src/app/composer/qgscomposerscalebarwidget.cpp index 4992ddcbd702..1f3c7e966bdc 100644 --- a/src/app/composer/qgscomposerscalebarwidget.cpp +++ b/src/app/composer/qgscomposerscalebarwidget.cpp @@ -27,6 +27,8 @@ QgsComposerScaleBarWidget::QgsComposerScaleBarWidget( QgsComposerScaleBar* scaleBar ): QgsComposerItemBaseWidget( nullptr, scaleBar ), mComposerScaleBar( scaleBar ) { setupUi( this ); + setPanelTitle( tr( "Scalebar properties" ) ); + connectUpdateSignal(); //add widget for general composer item properties diff --git a/src/app/composer/qgscomposershapewidget.cpp b/src/app/composer/qgscomposershapewidget.cpp index fc9770413e46..8e736c2ba465 100644 --- a/src/app/composer/qgscomposershapewidget.cpp +++ b/src/app/composer/qgscomposershapewidget.cpp @@ -27,6 +27,7 @@ QgsComposerShapeWidget::QgsComposerShapeWidget( QgsComposerShape* composerShape ): QgsComposerItemBaseWidget( nullptr, composerShape ), mComposerShape( composerShape ) { setupUi( this ); + setPanelTitle( tr( "Shape properties" ) ); //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, composerShape ); @@ -109,19 +110,18 @@ void QgsComposerShapeWidget::on_mShapeStyleButton_clicked() QgsFillSymbol* newSymbol = mComposerShape->shapeStyleSymbol()->clone(); QgsExpressionContext context = mComposerShape->createExpressionContext(); - QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), coverageLayer, this ); + + + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); QgsSymbolWidgetContext symbolContext; symbolContext.setExpressionContext( &context ); - d.setContext( symbolContext ); + d->setContext( symbolContext ); - if ( d.exec() == QDialog::Accepted ) - { - mComposerShape->beginCommand( tr( "Shape style changed" ) ); - mComposerShape->setShapeStyleSymbol( newSymbol ); - updateShapeStyle(); - mComposerShape->endCommand(); - } - delete newSymbol; + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateSymbolFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpSymbolSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerShape->beginCommand( tr( "Shape style changed" ) ); } void QgsComposerShapeWidget::updateShapeStyle() @@ -182,5 +182,22 @@ void QgsComposerShapeWidget::toggleRadiusSpin( const QString& shapeText ) } } +void QgsComposerShapeWidget::updateSymbolFromWidget() +{ + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mComposerShape->setShapeStyleSymbol( dynamic_cast< QgsFillSymbol* >( w->symbol() ) ); +} + +void QgsComposerShapeWidget::cleanUpSymbolSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + updateShapeStyle(); + mComposerShape->endCommand(); +} + diff --git a/src/app/composer/qgscomposershapewidget.h b/src/app/composer/qgscomposershapewidget.h index 053af65970cf..21b86ea55bac 100644 --- a/src/app/composer/qgscomposershapewidget.h +++ b/src/app/composer/qgscomposershapewidget.h @@ -49,6 +49,8 @@ class QgsComposerShapeWidget: public QgsComposerItemBaseWidget, private Ui::QgsC /** Enables or disables the rounded radius spin box based on shape type*/ void toggleRadiusSpin( const QString& shapeText ); + void updateSymbolFromWidget(); + void cleanUpSymbolSelector( QgsPanelWidget* container ); }; #endif // QGSCOMPOSERSHAPEWIDGET_H From 521cc3becd95ff0951fea3624c9b7259c26094ce Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 6 Oct 2016 19:03:00 +1000 Subject: [PATCH 183/897] [composer] Merge color change undo commands Avoids color modifications spamming the undo stack --- python/core/composer/qgscomposeritemcommand.sip | 17 +++++++++++++++++ .../composer/qgscomposermultiframecommand.sip | 6 +++++- src/app/composer/qgscomposerarrowwidget.cpp | 4 ++-- .../qgscomposerattributetablewidget.cpp | 8 ++++---- src/app/composer/qgscomposeritemwidget.cpp | 4 ++-- src/app/composer/qgscomposerlabelwidget.cpp | 2 +- src/app/composer/qgscomposerlegendwidget.cpp | 4 ++-- src/app/composer/qgscomposermapwidget.cpp | 8 ++++---- src/app/composer/qgscomposerpicturewidget.cpp | 4 ++-- src/app/composer/qgscomposerscalebarwidget.cpp | 8 ++++---- src/core/composer/qgscomposeritemcommand.h | 17 +++++++++++++++++ .../composer/qgscomposermultiframecommand.h | 6 +++++- 12 files changed, 65 insertions(+), 23 deletions(-) diff --git a/python/core/composer/qgscomposeritemcommand.sip b/python/core/composer/qgscomposeritemcommand.sip index 0f517ffdd468..564d6c5a7703 100644 --- a/python/core/composer/qgscomposeritemcommand.sip +++ b/python/core/composer/qgscomposeritemcommand.sip @@ -49,9 +49,14 @@ class QgsComposerMergeCommand : QgsComposerItemCommand //composer label ComposerLabelSetText, ComposerLabelSetId, + ComposerLabelFontColor, //composer map ComposerMapRotation, ComposerMapAnnotationDistance, + ComposerMapGridFramePenColor, + ComposerMapGridFrameFill1Color, + ComposerMapGridFrameFill2Color, + ComposerMapGridAnnotationFontColor, //composer legend ComposerLegendText, LegendColumnCount, @@ -69,8 +74,12 @@ class QgsComposerMergeCommand : QgsComposerItemCommand LegendBoxSpace, LegendColumnSpace, LegendRasterBorderWidth, + LegendFontColor, + LegendRasterBorderColor, //composer picture ComposerPictureRotation, + ComposerPictureFillColor, + ComposerPictureOutlineColor, // composer scalebar ScaleBarLineWidth, ScaleBarHeight, @@ -81,6 +90,10 @@ class QgsComposerMergeCommand : QgsComposerItemCommand ScaleBarMapUnitsSegment, ScaleBarLabelBarSize, ScaleBarBoxContentSpace, + ScaleBarFontColor, + ScaleBarFillColor, + ScaleBarFill2Color, + ScaleBarStrokeColor, // composer table TableMaximumFeatures, TableMargin, @@ -90,9 +103,13 @@ class QgsComposerMergeCommand : QgsComposerItemCommand ShapeOutlineWidth, //composer arrow ArrowOutlineWidth, + ArrowHeadFillColor, + ArrowHeadOutlineColor, ArrowHeadWidth, //item ItemOutlineWidth, + ItemOutlineColor, + ItemBackgroundColor, ItemMove, ItemRotation, ItemTransparency, diff --git a/python/core/composer/qgscomposermultiframecommand.sip b/python/core/composer/qgscomposermultiframecommand.sip index e405fa291ac5..23738b81f819 100644 --- a/python/core/composer/qgscomposermultiframecommand.sip +++ b/python/core/composer/qgscomposermultiframecommand.sip @@ -49,7 +49,11 @@ class QgsComposerMultiFrameMergeCommand: QgsComposerMultiFrameCommand TableMaximumFeatures, TableMargin, TableGridStrokeWidth, - TableCellStyle + TableCellStyle, + TableHeaderFontColor, + TableContentFontColor, + TableGridColor, + TableBackgroundColor, }; QgsComposerMultiFrameMergeCommand( Context c, QgsComposerMultiFrame* multiFrame, const QString& text ); diff --git a/src/app/composer/qgscomposerarrowwidget.cpp b/src/app/composer/qgscomposerarrowwidget.cpp index bffe84645379..abaaa6d6f51e 100644 --- a/src/app/composer/qgscomposerarrowwidget.cpp +++ b/src/app/composer/qgscomposerarrowwidget.cpp @@ -99,7 +99,7 @@ void QgsComposerArrowWidget::on_mArrowHeadFillColorButton_colorChanged( const QC return; } - mArrow->beginCommand( tr( "Arrow head fill color" ) ); + mArrow->beginCommand( tr( "Arrow head fill color" ), QgsComposerMergeCommand::ArrowHeadFillColor ); mArrow->setArrowHeadFillColor( newColor ); mArrow->update(); mArrow->endCommand(); @@ -112,7 +112,7 @@ void QgsComposerArrowWidget::on_mArrowHeadOutlineColorButton_colorChanged( const return; } - mArrow->beginCommand( tr( "Arrow head outline color" ) ); + mArrow->beginCommand( tr( "Arrow head outline color" ), QgsComposerMergeCommand::ArrowHeadOutlineColor ); mArrow->setArrowHeadOutlineColor( newColor ); mArrow->update(); mArrow->endCommand(); diff --git a/src/app/composer/qgscomposerattributetablewidget.cpp b/src/app/composer/qgscomposerattributetablewidget.cpp index 138f8e8772d6..a2a264e0b96e 100644 --- a/src/app/composer/qgscomposerattributetablewidget.cpp +++ b/src/app/composer/qgscomposerattributetablewidget.cpp @@ -269,7 +269,7 @@ void QgsComposerAttributeTableWidget::on_mHeaderFontColorButton_colorChanged( co QgsComposition* composition = mComposerTable->composition(); if ( composition ) { - composition->beginMultiFrameCommand( mComposerTable, tr( "Table header font color" ) ); + composition->beginMultiFrameCommand( mComposerTable, tr( "Table header font color" ), QgsComposerMultiFrameMergeCommand::TableHeaderFontColor ); } mComposerTable->setHeaderFontColor( newColor ); if ( composition ) @@ -310,7 +310,7 @@ void QgsComposerAttributeTableWidget::on_mContentFontColorButton_colorChanged( c QgsComposition* composition = mComposerTable->composition(); if ( composition ) { - composition->beginMultiFrameCommand( mComposerTable, tr( "Table content font color" ) ); + composition->beginMultiFrameCommand( mComposerTable, tr( "Table content font color" ), QgsComposerMultiFrameMergeCommand::TableContentFontColor ); } mComposerTable->setContentFontColor( newColor ); if ( composition ) @@ -348,7 +348,7 @@ void QgsComposerAttributeTableWidget::on_mGridColorButton_colorChanged( const QC QgsComposition* composition = mComposerTable->composition(); if ( composition ) { - composition->beginMultiFrameCommand( mComposerTable, tr( "Table grid color" ) ); + composition->beginMultiFrameCommand( mComposerTable, tr( "Table grid color" ), QgsComposerMultiFrameMergeCommand::TableGridColor ); } mComposerTable->setGridColor( newColor ); if ( composition ) @@ -386,7 +386,7 @@ void QgsComposerAttributeTableWidget::on_mBackgroundColorButton_colorChanged( co QgsComposition* composition = mComposerTable->composition(); if ( composition ) { - composition->beginMultiFrameCommand( mComposerTable, tr( "Table background color" ) ); + composition->beginMultiFrameCommand( mComposerTable, tr( "Table background color" ), QgsComposerMultiFrameMergeCommand::TableBackgroundColor ); } mComposerTable->setBackgroundColor( newColor ); if ( composition ) diff --git a/src/app/composer/qgscomposeritemwidget.cpp b/src/app/composer/qgscomposeritemwidget.cpp index e6295ac5c2be..30393dfdaf9d 100644 --- a/src/app/composer/qgscomposeritemwidget.cpp +++ b/src/app/composer/qgscomposeritemwidget.cpp @@ -210,7 +210,7 @@ void QgsComposerItemWidget::on_mFrameColorButton_colorChanged( const QColor& new { return; } - mItem->beginCommand( tr( "Frame color changed" ) ); + mItem->beginCommand( tr( "Frame color changed" ), QgsComposerMergeCommand::ItemOutlineColor ); mItem->setFrameOutlineColor( newFrameColor ); mItem->update(); mItem->endCommand(); @@ -230,7 +230,7 @@ void QgsComposerItemWidget::on_mBackgroundColorButton_colorChanged( const QColor { return; } - mItem->beginCommand( tr( "Background color changed" ) ); + mItem->beginCommand( tr( "Background color changed" ), QgsComposerMergeCommand::ItemBackgroundColor ); mItem->setBackgroundColor( newBackgroundColor ); //if the item is a composer map, we need to regenerate the map image diff --git a/src/app/composer/qgscomposerlabelwidget.cpp b/src/app/composer/qgscomposerlabelwidget.cpp index 855557d5a751..31d8b80fc969 100644 --- a/src/app/composer/qgscomposerlabelwidget.cpp +++ b/src/app/composer/qgscomposerlabelwidget.cpp @@ -125,7 +125,7 @@ void QgsComposerLabelWidget::on_mFontColorButton_colorChanged( const QColor &new return; } - mComposerLabel->beginCommand( tr( "Label color changed" ) ); + mComposerLabel->beginCommand( tr( "Label color changed" ), QgsComposerMergeCommand::ComposerLabelFontColor ); mComposerLabel->setFontColor( newLabelColor ); mComposerLabel->update(); mComposerLabel->endCommand(); diff --git a/src/app/composer/qgscomposerlegendwidget.cpp b/src/app/composer/qgscomposerlegendwidget.cpp index f00ba5db41dc..6bd430175369 100644 --- a/src/app/composer/qgscomposerlegendwidget.cpp +++ b/src/app/composer/qgscomposerlegendwidget.cpp @@ -406,7 +406,7 @@ void QgsComposerLegendWidget::on_mFontColorButton_colorChanged( const QColor& ne return; } - mLegend->beginCommand( tr( "Legend font color changed" ) ); + mLegend->beginCommand( tr( "Legend font color changed" ), QgsComposerMergeCommand::LegendFontColor ); mLegend->setFontColor( newFontColor ); mLegend->update(); mLegend->endCommand(); @@ -624,7 +624,7 @@ void QgsComposerLegendWidget::on_mRasterBorderColorButton_colorChanged( const QC return; } - mLegend->beginCommand( tr( "Legend raster border color" ) ); + mLegend->beginCommand( tr( "Legend raster border color" ), QgsComposerMergeCommand::LegendRasterBorderColor ); mLegend->setRasterBorderColor( newColor ); mLegend->update(); mLegend->endCommand(); diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index 7a4880836745..5e9ec828e1d3 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -1730,7 +1730,7 @@ void QgsComposerMapWidget::on_mGridFramePenColorButton_colorChanged( const QColo return; } - mComposerMap->beginCommand( tr( "Grid frame color changed" ) ); + mComposerMap->beginCommand( tr( "Grid frame color changed" ), QgsComposerMergeCommand::ComposerMapGridFramePenColor ); grid->setFramePenColor( newColor ); mComposerMap->update(); mComposerMap->endCommand(); @@ -1744,7 +1744,7 @@ void QgsComposerMapWidget::on_mGridFrameFill1ColorButton_colorChanged( const QCo return; } - mComposerMap->beginCommand( tr( "Grid frame first fill color changed" ) ); + mComposerMap->beginCommand( tr( "Grid frame first fill color changed" ), QgsComposerMergeCommand::ComposerMapGridFrameFill1Color ); grid->setFrameFillColor1( newColor ); mComposerMap->update(); mComposerMap->endCommand(); @@ -1758,7 +1758,7 @@ void QgsComposerMapWidget::on_mGridFrameFill2ColorButton_colorChanged( const QCo return; } - mComposerMap->beginCommand( tr( "Grid frame second fill color changed" ) ); + mComposerMap->beginCommand( tr( "Grid frame second fill color changed" ), QgsComposerMergeCommand::ComposerMapGridFrameFill2Color ); grid->setFrameFillColor2( newColor ); mComposerMap->update(); mComposerMap->endCommand(); @@ -2077,7 +2077,7 @@ void QgsComposerMapWidget::on_mAnnotationFontColorButton_colorChanged( const QCo return; } - mComposerMap->beginCommand( tr( "Annotation color changed" ) ); + mComposerMap->beginCommand( tr( "Annotation color changed" ), QgsComposerMergeCommand::ComposerMapGridAnnotationFontColor ); grid->setAnnotationFontColor( color ); mComposerMap->update(); mComposerMap->endCommand(); diff --git a/src/app/composer/qgscomposerpicturewidget.cpp b/src/app/composer/qgscomposerpicturewidget.cpp index 9ecffd1e996a..cc055d8de150 100644 --- a/src/app/composer/qgscomposerpicturewidget.cpp +++ b/src/app/composer/qgscomposerpicturewidget.cpp @@ -633,7 +633,7 @@ void QgsComposerPictureWidget::loadPicturePreviews( bool collapsed ) void QgsComposerPictureWidget::on_mFillColorButton_colorChanged( const QColor& color ) { - mPicture->beginCommand( tr( "Picture fill color changed" ) ); + mPicture->beginCommand( tr( "Picture fill color changed" ), QgsComposerMergeCommand::ComposerPictureFillColor ); mPicture->setSvgFillColor( color ); mPicture->endCommand(); mPicture->update(); @@ -641,7 +641,7 @@ void QgsComposerPictureWidget::on_mFillColorButton_colorChanged( const QColor& c void QgsComposerPictureWidget::on_mOutlineColorButton_colorChanged( const QColor& color ) { - mPicture->beginCommand( tr( "Picture border color changed" ) ); + mPicture->beginCommand( tr( "Picture border color changed" ), QgsComposerMergeCommand::ComposerPictureOutlineColor ); mPicture->setSvgBorderColor( color ); mPicture->endCommand(); mPicture->update(); diff --git a/src/app/composer/qgscomposerscalebarwidget.cpp b/src/app/composer/qgscomposerscalebarwidget.cpp index 1f3c7e966bdc..102b6dc1dffb 100644 --- a/src/app/composer/qgscomposerscalebarwidget.cpp +++ b/src/app/composer/qgscomposerscalebarwidget.cpp @@ -263,7 +263,7 @@ void QgsComposerScaleBarWidget::on_mFontColorButton_colorChanged( const QColor& return; } - mComposerScaleBar->beginCommand( tr( "Scalebar font color changed" ) ); + mComposerScaleBar->beginCommand( tr( "Scalebar font color changed" ), QgsComposerMergeCommand::ScaleBarFontColor ); disconnectUpdateSignal(); mComposerScaleBar->setFontColor( newColor ); mComposerScaleBar->update(); @@ -278,7 +278,7 @@ void QgsComposerScaleBarWidget::on_mFillColorButton_colorChanged( const QColor& return; } - mComposerScaleBar->beginCommand( tr( "Scalebar color changed" ) ); + mComposerScaleBar->beginCommand( tr( "Scalebar color changed" ), QgsComposerMergeCommand::ScaleBarFillColor ); disconnectUpdateSignal(); QBrush newBrush = mComposerScaleBar->brush(); newBrush.setColor( newColor ); @@ -295,7 +295,7 @@ void QgsComposerScaleBarWidget::on_mFillColor2Button_colorChanged( const QColor return; } - mComposerScaleBar->beginCommand( tr( "Scalebar secondary color changed" ) ); + mComposerScaleBar->beginCommand( tr( "Scalebar secondary color changed" ), QgsComposerMergeCommand::ScaleBarFill2Color ); disconnectUpdateSignal(); QBrush newBrush = mComposerScaleBar->brush2(); newBrush.setColor( newColor ); @@ -312,7 +312,7 @@ void QgsComposerScaleBarWidget::on_mStrokeColorButton_colorChanged( const QColor return; } - mComposerScaleBar->beginCommand( tr( "Scalebar line color changed" ) ); + mComposerScaleBar->beginCommand( tr( "Scalebar line color changed" ), QgsComposerMergeCommand::ScaleBarStrokeColor ); disconnectUpdateSignal(); QPen newPen = mComposerScaleBar->pen(); newPen.setColor( newColor ); diff --git a/src/core/composer/qgscomposeritemcommand.h b/src/core/composer/qgscomposeritemcommand.h index 0a5a094b4f8c..4b931186176e 100644 --- a/src/core/composer/qgscomposeritemcommand.h +++ b/src/core/composer/qgscomposeritemcommand.h @@ -87,9 +87,14 @@ class CORE_EXPORT QgsComposerMergeCommand: public QgsComposerItemCommand //composer label ComposerLabelSetText, ComposerLabelSetId, + ComposerLabelFontColor, //composer map ComposerMapRotation, ComposerMapAnnotationDistance, + ComposerMapGridFramePenColor, + ComposerMapGridFrameFill1Color, + ComposerMapGridFrameFill2Color, + ComposerMapGridAnnotationFontColor, //composer legend ComposerLegendText, LegendColumnCount, @@ -107,8 +112,12 @@ class CORE_EXPORT QgsComposerMergeCommand: public QgsComposerItemCommand LegendBoxSpace, LegendColumnSpace, LegendRasterBorderWidth, + LegendFontColor, + LegendRasterBorderColor, //composer picture ComposerPictureRotation, + ComposerPictureFillColor, + ComposerPictureOutlineColor, // composer scalebar ScaleBarLineWidth, ScaleBarHeight, @@ -119,6 +128,10 @@ class CORE_EXPORT QgsComposerMergeCommand: public QgsComposerItemCommand ScaleBarMapUnitsSegment, ScaleBarLabelBarSize, ScaleBarBoxContentSpace, + ScaleBarFontColor, + ScaleBarFillColor, + ScaleBarFill2Color, + ScaleBarStrokeColor, // composer table TableMaximumFeatures, TableMargin, @@ -128,9 +141,13 @@ class CORE_EXPORT QgsComposerMergeCommand: public QgsComposerItemCommand ShapeOutlineWidth, //composer arrow ArrowOutlineWidth, + ArrowHeadFillColor, + ArrowHeadOutlineColor, ArrowHeadWidth, //item ItemOutlineWidth, + ItemOutlineColor, + ItemBackgroundColor, ItemMove, ItemRotation, ItemTransparency, diff --git a/src/core/composer/qgscomposermultiframecommand.h b/src/core/composer/qgscomposermultiframecommand.h index cc72fe3e844b..255c5065fbf7 100644 --- a/src/core/composer/qgscomposermultiframecommand.h +++ b/src/core/composer/qgscomposermultiframecommand.h @@ -78,7 +78,11 @@ class CORE_EXPORT QgsComposerMultiFrameMergeCommand: public QgsComposerMultiFram TableMaximumFeatures, TableMargin, TableGridStrokeWidth, - TableCellStyle + TableCellStyle, + TableHeaderFontColor, + TableContentFontColor, + TableGridColor, + TableBackgroundColor, }; QgsComposerMultiFrameMergeCommand( Context c, QgsComposerMultiFrame* multiFrame, const QString& text ); From d9349e5bbb8cbdc5f6785fb3f2872c6629f2e90a Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 4 Oct 2016 15:44:50 +0200 Subject: [PATCH 184/897] update configuration settings to qgis3 --- debian/{compat.in => compat} | 0 mac/app.info.plist.in | 2 +- mac/browser.info.plist.in | 2 +- ms-windows/plugins.nsh | 34 +++++++++---------- ms-windows/python_plugins.nsh | 6 ++-- python/core/auth/qgsauthmanager.sip | 2 +- python/core/qgsapplication.sip | 2 +- python/plugins/MetaSearch/pavement.py | 4 +-- .../processing/algs/otb/maintenance/README | 2 +- resources/context_help/PythonConsole | 2 +- scripts/mkuidefaults.py | 2 +- src/analysis/CMakeLists.txt | 2 +- src/analysis/network/CMakeLists.txt | 2 +- src/browser/main.cpp | 2 +- src/core/CMakeLists.txt | 2 +- src/core/auth/qgsauthmanager.h | 2 +- src/core/qgsapplication.cpp | 7 ++-- src/core/qgsapplication.h | 2 +- src/gui/CMakeLists.txt | 2 +- src/helpviewer/main.cpp | 2 +- src/providers/grass/CMakeLists.txt | 2 +- src/providers/oracle/qgsoracletablecache.h | 2 +- src/python/qgspythonutilsimpl.cpp | 4 +-- src/server/qgsserver.cpp | 2 +- tests/bench/main.cpp | 2 +- tests/src/python/test_qgsappstartup.py | 2 +- .../QGIS/{QGIS2.ini => QGIS.ini} | 0 .../qgis.org/{QGIS2.ini => QGIS.ini} | 0 28 files changed, 46 insertions(+), 49 deletions(-) rename debian/{compat.in => compat} (100%) rename tests/testdata/test_plugin_path/QGIS/{QGIS2.ini => QGIS.ini} (100%) rename tests/testdata/test_plugin_path/qgis.org/{QGIS2.ini => QGIS.ini} (100%) diff --git a/debian/compat.in b/debian/compat similarity index 100% rename from debian/compat.in rename to debian/compat diff --git a/mac/app.info.plist.in b/mac/app.info.plist.in index 5c103012b613..4513d99ab0e8 100644 --- a/mac/app.info.plist.in +++ b/mac/app.info.plist.in @@ -7,7 +7,7 @@ CFBundleName QGIS CFBundleIdentifier - org.qgis.qgis2 + org.qgis.qgis3 CFBundleExecutable ${QGIS_APP_NAME} CFBundlePackageType diff --git a/mac/browser.info.plist.in b/mac/browser.info.plist.in index 38617f88565d..c2eac3199185 100644 --- a/mac/browser.info.plist.in +++ b/mac/browser.info.plist.in @@ -7,7 +7,7 @@ CFBundleName QGIS Browser CFBundleIdentifier - org.qgis.qgis2_browser + org.qgis.qgis3_browser CFBundleExecutable QGIS Browser CFBundlePackageType diff --git a/ms-windows/plugins.nsh b/ms-windows/plugins.nsh index a4384c54780d..f751da0d410e 100644 --- a/ms-windows/plugins.nsh +++ b/ms-windows/plugins.nsh @@ -7,22 +7,22 @@ # Please don't remove this header. # ################################################################################ -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "coordinatecaptureplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "diagramoverlay" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "dxf2shpconverterplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "evis" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "georefplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "globeplugin" "false" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "gpsimporterplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "grassplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "heatmapplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "interpolationplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "offlineeditingplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "oracleplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "rasterterrainplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "roadgraphplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "spatialqueryplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "topolplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\Plugins" "zonalstatisticsplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "coordinatecaptureplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "diagramoverlay" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "dxf2shpconverterplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "evis" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "georefplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "globeplugin" "false" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "gpsimporterplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "grassplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "heatmapplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "interpolationplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "offlineeditingplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "oracleplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "rasterterrainplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "roadgraphplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "spatialqueryplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "topolplugin" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "zonalstatisticsplugin" "true" ############################### reg2nsis end ################################# diff --git a/ms-windows/python_plugins.nsh b/ms-windows/python_plugins.nsh index dec5c76dadce..7a86b37ec826 100644 --- a/ms-windows/python_plugins.nsh +++ b/ms-windows/python_plugins.nsh @@ -7,8 +7,8 @@ # Please don't remove this header. # ################################################################################ -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\PythonPlugins" "GdalTools" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\PythonPlugins" "db_manager" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS2\PythonPlugins" "processing" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\PythonPlugins" "GdalTools" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\PythonPlugins" "db_manager" "true" +WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\PythonPlugins" "processing" "true" ############################### reg2nsis end ################################# diff --git a/python/core/auth/qgsauthmanager.sip b/python/core/auth/qgsauthmanager.sip index f2f6200c1c0b..4be77a4dbc6e 100644 --- a/python/core/auth/qgsauthmanager.sip +++ b/python/core/auth/qgsauthmanager.sip @@ -44,7 +44,7 @@ class QgsAuthManager : QObject /** Standard message for when QCA's qca-ossl plugin is missing and system is disabled */ const QString disabledMessage() const; - /** The standard authentication database file in ~/.qgis2/ or defined location + /** The standard authentication database file in ~/.qgis3/ or defined location * @see QgsApplication::qgisAuthDbFilePath */ const QString authenticationDbPath() const; diff --git a/python/core/qgsapplication.sip b/python/core/qgsapplication.sip index 05bcc95a51f4..8a8dd5a24ce1 100644 --- a/python/core/qgsapplication.sip +++ b/python/core/qgsapplication.sip @@ -124,7 +124,7 @@ static void qtgui_UpdatePyArgv(PyObject *argvlist, int argc, char **argv) static void setUITheme( const QString &themeName ); /** - * @brief All themes found in ~/.qgis2/themes folder. + * @brief All themes found in ~/.qgis3/themes folder. * The path is to the root folder for the theme * @note Valid theme folders must contain a style.qss file. * @return A hash of theme name and theme path. Valid theme folders contain style.qss diff --git a/python/plugins/MetaSearch/pavement.py b/python/plugins/MetaSearch/pavement.py index 8a4f42936979..10abad958976 100644 --- a/python/plugins/MetaSearch/pavement.py +++ b/python/plugins/MetaSearch/pavement.py @@ -49,7 +49,7 @@ home=BASEDIR, plugin=path(BASEDIR), ui=path(BASEDIR) / 'plugin' / PLUGIN_NAME / 'ui', - install=path('%s/.qgis2/python/plugins/MetaSearch' % USERDIR), + install=path('%s/.qgis3/python/plugins/MetaSearch' % USERDIR), ext_libs=path('plugin/MetaSearch/ext-libs'), tmp=path(path('%s/MetaSearch-dist' % USERDIR)), version=VERSION @@ -86,7 +86,7 @@ def clean(): def install(): """install plugin into user QGIS environment""" - plugins_dir = path(USERDIR) / '.qgis2/python/plugins' + plugins_dir = path(USERDIR) / '.qgis3/python/plugins' if os.path.exists(options.base.install): if os.path.islink(options.base.install): diff --git a/python/plugins/processing/algs/otb/maintenance/README b/python/plugins/processing/algs/otb/maintenance/README index ba7c61229254..487759026cdb 100644 --- a/python/plugins/processing/algs/otb/maintenance/README +++ b/python/plugins/processing/algs/otb/maintenance/README @@ -19,7 +19,7 @@ export LD_LIBRARY_PATH=/path/to/OTB/install/lib/:$LD_LIBRARY_PATH Set QGIS environment --------------------- export QGIS_PREFIX_PATH=/path/to/QGIS/install -export PYTHONPATH=:/usr/share/qgis/python/plugins:~/.qgis2/python/plugins:$PYTHONPATH +export PYTHONPATH=:/usr/share/qgis/python/plugins:~/.qgis3/python/plugins:$PYTHONPATH # Set LD_LIBRARY_PATH export LD_LIBRARY_PATH=$QGIS_PREFIX_PATH/lib/:$LD_LIBRARY_PATH # Add maintenance folder to python path diff --git a/resources/context_help/PythonConsole b/resources/context_help/PythonConsole index 041f2ad03949..1554b9d227c1 100644 --- a/resources/context_help/PythonConsole +++ b/resources/context_help/PythonConsole @@ -52,7 +52,7 @@ uncomment code, check syntax, share the code via codepad.org and much more).
                                                                                                                                                                                    • Open PyQGIS Cookbook by typing .

                                                                                                                                                                                    • Save and clear the command history accessing from context menu of input pane. -The history will be saved into the file ~/.qgis2/console_history.txt
                                                                                                                                                                                    • +The history will be saved into the file ~/.qgis3/console_history.txt
                                                                                                                                                                                    diff --git a/scripts/mkuidefaults.py b/scripts/mkuidefaults.py index 1a3ad6c7de0d..223bf79d4e25 100644 --- a/scripts/mkuidefaults.py +++ b/scripts/mkuidefaults.py @@ -32,7 +32,7 @@ def chunks(l, n): QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") -QCoreApplication.setApplicationName("QGIS2") +QCoreApplication.setApplicationName("QGIS3") s = QSettings() diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index e35804717080..5da66b09cbee 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -167,7 +167,7 @@ ELSE(NOT APPLE) FRAMEWORK_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}" MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_SOURCE_DIR}/mac/framework.info.plist.in" MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${COMPLETE_VERSION} - MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis2_analysis + MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis3_analysis BUILD_WITH_INSTALL_RPATH TRUE PUBLIC_HEADER "${QGIS_ANALYSIS_HDRS}" LINK_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" diff --git a/src/analysis/network/CMakeLists.txt b/src/analysis/network/CMakeLists.txt index 2a83a23c817d..e59d7c21d415 100644 --- a/src/analysis/network/CMakeLists.txt +++ b/src/analysis/network/CMakeLists.txt @@ -61,7 +61,7 @@ ELSE(NOT APPLE) FRAMEWORK_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}" MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_SOURCE_DIR}/mac/framework.info.plist.in" MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${COMPLETE_VERSION} - MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis2_networkanalysis + MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis3_networkanalysis BUILD_WITH_INSTALL_RPATH TRUE PUBLIC_HEADER "${QGIS_NETWORK_ANALYSIS_HDRS};${QGIS_NETWORK_ANALYSIS_MOC_HDRS}" LINK_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" diff --git a/src/browser/main.cpp b/src/browser/main.cpp index 7fb6d6d9a787..5fb4d3182ca5 100644 --- a/src/browser/main.cpp +++ b/src/browser/main.cpp @@ -51,7 +51,7 @@ int main( int argc, char ** argv ) // Set up the QSettings environment must be done after qapp is created QCoreApplication::setOrganizationName( "QGIS" ); QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS2" ); + QCoreApplication::setApplicationName( "QGIS3" ); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 44d48f8ec792..dd64fdb41d9c 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -917,7 +917,7 @@ ELSE(NOT APPLE) FRAMEWORK_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}" MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_SOURCE_DIR}/mac/framework.info.plist.in" MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${COMPLETE_VERSION} - MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis2_core + MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis3_core BUILD_WITH_INSTALL_RPATH TRUE PUBLIC_HEADER "${QGIS_CORE_HDRS};${QGIS_CORE_MOC_HDRS}" LINK_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" diff --git a/src/core/auth/qgsauthmanager.h b/src/core/auth/qgsauthmanager.h index a6be82feeddb..fee03683487d 100644 --- a/src/core/auth/qgsauthmanager.h +++ b/src/core/auth/qgsauthmanager.h @@ -90,7 +90,7 @@ class CORE_EXPORT QgsAuthManager : public QObject /** Standard message for when QCA's qca-ossl plugin is missing and system is disabled */ const QString disabledMessage() const; - /** The standard authentication database file in ~/.qgis2/ or defined location + /** The standard authentication database file in ~/.qgis3/ or defined location * @see QgsApplication::qgisAuthDbFilePath */ const QString authenticationDbPath() const { return mAuthDbPath; } diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 99c1465e2aa2..898f9371e4ec 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -83,7 +83,7 @@ QString QgsApplication::sPlatformName = "desktop"; const char* QgsApplication::QGIS_ORGANIZATION_NAME = "QGIS"; const char* QgsApplication::QGIS_ORGANIZATION_DOMAIN = "qgis.org"; -const char* QgsApplication::QGIS_APPLICATION_NAME = "QGIS2"; +const char* QgsApplication::QGIS_APPLICATION_NAME = "QGIS3"; /*! \class QgsApplication @@ -116,10 +116,7 @@ void QgsApplication::init( QString customConfigPath ) } else { - // TODO Switch to this for release. - //customConfigPath = QString( "%1/.qgis%2/" ).arg( QDir::homePath() ).arg( Qgis::QGIS_VERSION_INT / 10000 ); - // Use qgis-dev for dev versions of QGIS to avoid mixing 2 and 3 API plugins. - customConfigPath = QString( "%1/.qgis%2/" ).arg( QDir::homePath() ).arg( "-dev" ); + customConfigPath = QString( "%1/.qgis3/" ).arg( QDir::homePath() ); } } diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index 9bb559f72969..cb468852a3fd 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -87,7 +87,7 @@ class CORE_EXPORT QgsApplication : public QApplication static void setUITheme( const QString &themeName ); /** - * @brief All themes found in ~/.qgis2/themes folder. + * @brief All themes found in ~/.qgis3/themes folder. * The path is to the root folder for the theme * @note Valid theme folders must contain a style.qss file. * @return A hash of theme name and theme path. Valid theme folders contain style.qss diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index 1fa7da8522c2..fb9cc6bc2d60 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -832,7 +832,7 @@ ELSE(NOT APPLE) FRAMEWORK_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}" MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_SOURCE_DIR}/mac/framework.info.plist.in" MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${COMPLETE_VERSION} - MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis2_gui + MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis3_gui BUILD_WITH_INSTALL_RPATH TRUE PUBLIC_HEADER "${QGIS_GUI_HDRS};${QGIS_GUI_MOC_HDRS}" LINK_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" diff --git a/src/helpviewer/main.cpp b/src/helpviewer/main.cpp index 5d0d9413baa6..6988c92bff0c 100644 --- a/src/helpviewer/main.cpp +++ b/src/helpviewer/main.cpp @@ -33,7 +33,7 @@ int main( int argc, char ** argv ) // Set up the QSettings environment must be done after qapp is created QCoreApplication::setOrganizationName( "QGIS" ); QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS2" ); + QCoreApplication::setApplicationName( "QGIS3" ); QString myTranslationCode = ""; diff --git a/src/providers/grass/CMakeLists.txt b/src/providers/grass/CMakeLists.txt index ad0a53fe66f5..5e24956f731e 100644 --- a/src/providers/grass/CMakeLists.txt +++ b/src/providers/grass/CMakeLists.txt @@ -93,7 +93,7 @@ MACRO(ADD_GRASSLIB GRASS_BUILD_VERSION) FRAMEWORK_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}" MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_SOURCE_DIR}/mac/framework.info.plist.in" MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${COMPLETE_VERSION} - MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis2_grass + MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis3_grass COMPILE_FLAGS "-DGRASS_BASE=\\\"${GRASS_PREFIX}\\\" \"-DGRASS_LIB_EXPORT=${DLLEXPORT}\" \"-DGRASS_EXPORT=${DLLIMPORT}\" ${GRASS_OFF_T_SIZE_DEF}" ) diff --git a/src/providers/oracle/qgsoracletablecache.h b/src/providers/oracle/qgsoracletablecache.h index 709b63972ab6..3687ff0fb1fd 100644 --- a/src/providers/oracle/qgsoracletablecache.h +++ b/src/providers/oracle/qgsoracletablecache.h @@ -28,7 +28,7 @@ email : wonder.sk at gmail dot com * This class contains routines for local caching of listing of layers, so the add Oracle * layer dialog does not need to discover the tables every time the user wants to add a layer. * - * The cached entries are stored in SQLite database in QGIS user directory (usually ~/.qgis2). + * The cached entries are stored in SQLite database in QGIS user directory (usually ~/.qgis3). * The database can be used for other data sources, too. Each saved connection's list is stored * in one table "oracle_xyz" (where xyz is the name of the connection). There is one meta table * "meta_oracle" which has a list of cached connections and the combination of flags used for diff --git a/src/python/qgspythonutilsimpl.cpp b/src/python/qgspythonutilsimpl.cpp index 3bb2e74db286..1ddecb8580ad 100644 --- a/src/python/qgspythonutilsimpl.cpp +++ b/src/python/qgspythonutilsimpl.cpp @@ -595,9 +595,9 @@ QString QgsPythonUtilsImpl::pluginsPath() QString QgsPythonUtilsImpl::homePythonPath() { QString settingsDir = QgsApplication::qgisSettingsDirPath(); - if ( QDir::cleanPath( settingsDir ) == QDir::homePath() + QString( "/.qgis%1" ).arg( Qgis::QGIS_VERSION_INT / 10000 ) ) + if ( QDir::cleanPath( settingsDir ) == QDir::homePath() + QString( "/.qgis3" ) ) { - return QString( "b\"%1/.qgis%2/python\".decode('utf-8')" ).arg( QDir::homePath() ).arg( Qgis::QGIS_VERSION_INT / 10000 ); + return QString( "b\"%1/.qgis3/python\".decode('utf-8')" ).arg( QDir::homePath() ); } else { diff --git a/src/server/qgsserver.cpp b/src/server/qgsserver.cpp index 31dc5e175dc8..4aff5dbe2eac 100644 --- a/src/server/qgsserver.cpp +++ b/src/server/qgsserver.cpp @@ -364,7 +364,7 @@ bool QgsServer::init( ) QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs) // Instantiate authentication system - // creates or uses qgis-auth.db in ~/.qgis2/ or directory defined by QGIS_AUTH_DB_DIR_PATH env variable + // creates or uses qgis-auth.db in ~/.qgis3/ or directory defined by QGIS_AUTH_DB_DIR_PATH env variable // set the master password as first line of file defined by QGIS_AUTH_PASSWORD_FILE env variable // (QGIS_AUTH_PASSWORD_FILE variable removed from environment after accessing) QgsAuthManager::instance()->init( QgsApplication::pluginPath() ); diff --git a/tests/bench/main.cpp b/tests/bench/main.cpp index 669e8ebedbda..83440169a7ac 100644 --- a/tests/bench/main.cpp +++ b/tests/bench/main.cpp @@ -394,7 +394,7 @@ int main( int argc, char *argv[] ) // Set up the QSettings environment must be done after qapp is created QgsApplication::setOrganizationName( "QGIS" ); QgsApplication::setOrganizationDomain( "qgis.org" ); - QgsApplication::setApplicationName( "QGIS2" ); + QgsApplication::setApplicationName( "QGIS3" ); QgsProviderRegistry::instance( QgsApplication::pluginPath() ); diff --git a/tests/src/python/test_qgsappstartup.py b/tests/src/python/test_qgsappstartup.py index 6acdef57e19c..f2fb287fe3c9 100644 --- a/tests/src/python/test_qgsappstartup.py +++ b/tests/src/python/test_qgsappstartup.py @@ -101,7 +101,7 @@ def testOptionsPath(self): subdir = 'QGIS' # Linux if sys.platform[:3] == 'dar': # Mac subdir = 'qgis.org' - ini = os.path.join(subdir, 'QGIS2.ini') + ini = os.path.join(subdir, 'QGIS.ini') for p in ['test_opts', 'test opts', 'test_optsé€']: self.doTestStartup(option="--optionspath", testDir=os.path.join(self.TMP_DIR, p), diff --git a/tests/testdata/test_plugin_path/QGIS/QGIS2.ini b/tests/testdata/test_plugin_path/QGIS/QGIS.ini similarity index 100% rename from tests/testdata/test_plugin_path/QGIS/QGIS2.ini rename to tests/testdata/test_plugin_path/QGIS/QGIS.ini diff --git a/tests/testdata/test_plugin_path/qgis.org/QGIS2.ini b/tests/testdata/test_plugin_path/qgis.org/QGIS.ini similarity index 100% rename from tests/testdata/test_plugin_path/qgis.org/QGIS2.ini rename to tests/testdata/test_plugin_path/qgis.org/QGIS.ini From 98c0da9cf540c9c2a199e2c94434e746798bded0 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Thu, 6 Oct 2016 12:09:15 +0200 Subject: [PATCH 185/897] grass plugin fix (followup 3b0486c) --- src/plugins/grass/qgsgrasseditrenderer.cpp | 2 +- src/plugins/grass/qgsgrasseditrenderer.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/grass/qgsgrasseditrenderer.cpp b/src/plugins/grass/qgsgrasseditrenderer.cpp index 6c224bf0bade..dc7cc139402d 100644 --- a/src/plugins/grass/qgsgrasseditrenderer.cpp +++ b/src/plugins/grass/qgsgrasseditrenderer.cpp @@ -173,7 +173,7 @@ void QgsGrassEditRenderer::stopRender( QgsRenderContext& context ) mMarkerRenderer->stopRender( context ); } -QSet QgsGrassEditRenderer::usedAttributes() +QSet QgsGrassEditRenderer::usedAttributes() const { return mLineRenderer->usedAttributes(); } diff --git a/src/plugins/grass/qgsgrasseditrenderer.h b/src/plugins/grass/qgsgrasseditrenderer.h index f4c796fe28ea..1162b23f6477 100644 --- a/src/plugins/grass/qgsgrasseditrenderer.h +++ b/src/plugins/grass/qgsgrasseditrenderer.h @@ -38,7 +38,7 @@ class QgsGrassEditRenderer : public QgsFeatureRenderer virtual void stopRender( QgsRenderContext& context ) override; - virtual QSet usedAttributes() override; + virtual QSet usedAttributes() const override; virtual QgsFeatureRenderer* clone() const override; From b4f3126be07b8aa9764768d9445be2a00de54f84 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 4 Oct 2016 15:45:55 +0200 Subject: [PATCH 186/897] debian packages * remove outdated conditionals * switch to ninja --- debian/changelog | 4 +- debian/compat | 3 +- debian/control | 94 +++++++++++++++++++++++++--------------------- debian/control.in | 16 ++++---- debian/rules | 18 ++++++--- doc/CMakeLists.txt | 9 ++++- 6 files changed, 81 insertions(+), 63 deletions(-) diff --git a/debian/changelog b/debian/changelog index 1eb61d82c0f1..722b5c3fdeb6 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,9 +1,9 @@ qgis (2.99.0) UNRELEASED; urgency=medium * New development version 2.999 after branch of 2.16 - * move to qt5/python3 + * move to qt5/python3/ninja - -- Jürgen E. Fischer Fri, 08 Jul 2016 14:12:36 +0200 + -- Jürgen E. Fischer Thu, 06 Oct 2016 13:30:42 +0200 qgis (2.16.0) unstable; urgency=medium diff --git a/debian/compat b/debian/compat index 1d51f689fbd9..ec635144f600 100644 --- a/debian/compat +++ b/debian/compat @@ -1,2 +1 @@ -#stretch sid jessie trusty xenial#9 -#jessie#8 +9 diff --git a/debian/control b/debian/control index c797fc73b8be..34d66b5086eb 100644 --- a/debian/control +++ b/debian/control @@ -6,35 +6,41 @@ Priority: optional Build-Depends: bison, cmake (>= 2.8), - debhelper (>= 7), + debhelper (>= 9), + dh-python, flex, grass-dev, libexpat1-dev, libfcgi-dev, - libgdal1-dev | libgdal-dev, + libgdal-dev (>= 1.11), + libgsl-dev, libgeos-dev (>= 3.0.0), - libgsl0-dev, libpq-dev, libproj-dev, - qtbase5-dev, - libqca-qt5-2-dev, - libqwt-qt5-dev, libspatialite-dev, libsqlite3-dev, libspatialindex-dev, + qtbase5-dev, qttools5-dev-tools, qttools5-dev, qtscript5-dev, qtpositioning5-dev, + libqt5svg5-dev, libqt5xmlpatterns5-dev, libqt5webkit5-dev, libqt5opengl5-dev, libqt5sql5-sqlite, libqt5scintilla2-dev, + libqwt-qt5-dev, libqca-qt5-2-dev, libqca-qt5-2-plugins, + python3-dev, python3-all-dev, python3-sip, python3-sip-dev, + pyqt5-dev-tools, pyqt5-dev, pyqt5.qsci-dev, + python3-pyqt5, python3-pyqt5.qsci, python3-pyqt5.qtsql, python3-pyqt5.qtsvg, + python3-gdal, + python3-nose2, python3-yaml, python3-mock, python3-psycopg2, python3-future, python3-termcolor, pkg-config, - pyqt5-dev, - python3-dev, - python3-all-dev, - python3-sip, - python3-sip-dev, - python3-pyqt5, git, txt2tags, - doxygen + doxygen, + gdal-bin, + spawn-fcgi, lighttpd, poppler-utils, + graphviz, + xvfb, xauth, + xfonts-base, xfonts-100dpi, xfonts-75dpi, xfonts-scalable, + libosgearth-dev, + locales, ca-certificates, ninja-build Build-Conflicts: libqgis-dev, qgis-dev -Standards-Version: 3.8.4 -XS-Python-Version: current +Standards-Version: 3.9.7 Vcs-Browser: https://github.com/qgis/QGIS/ Vcs-Git: https://github.com/qgis/QGIS.git Homepage: http://qgis.org/ @@ -64,7 +70,9 @@ Description: Geographic Information System (GIS) Package: qgis-common Architecture: all Depends: - ${misc:Depends} + libjs-jquery, + libjs-leaflet, + ${misc:Depends} Description: QGIS - architecture-independent data QGIS is a Geographic Information System (GIS) which manages, analyzes and display databases of geographic information. @@ -72,20 +80,20 @@ Description: QGIS - architecture-independent data This package contains architecture-independent supporting data files for use with QGIS. -Package: libqgis-app3.0.0 +Package: libqgis-app2.99.0 Architecture: any Section: libs Depends: ${shlibs:Depends}, ${misc:Depends} -Replaces: libqgis{QGIS_ABI} +Replaces: libqgis2.99.0 Description: QGIS - shared app library QGIS is a Geographic Information System (GIS) which manages, analyzes and display databases of geographic information. . This package contains the shared app library. -Package: libqgis-core3.0.0 +Package: libqgis-core2.99.0 Architecture: any Section: libs Depends: @@ -97,7 +105,7 @@ Description: QGIS - shared core library . This package contains the shared core library. -Package: libqgis-gui3.0.0 +Package: libqgis-gui2.99.0 Architecture: any Section: libs Depends: @@ -109,7 +117,7 @@ Description: QGIS - shared gui library . This package contains the shared gui library. -Package: libqgis-analysis3.0.0 +Package: libqgis-analysis2.99.0 Architecture: any Section: libs Depends: @@ -121,7 +129,7 @@ Description: QGIS - shared analysis library . This package contains the shared analysis library. -Package: libqgis-networkanalysis3.0.0 +Package: libqgis-networkanalysis2.99.0 Architecture: any Section: libs Depends: @@ -133,7 +141,7 @@ Description: QGIS - shared network analysis library . This package contains the shared network analysis library. -Package: libqgisgrass3.0.0 +Package: libqgisgrass7-2.99.0 Architecture: any Section: libs Depends: @@ -145,13 +153,13 @@ Description: QGIS - shared grass library . This package contains the shared grass library. -Package: libqgispython3.0.0 +Package: libqgispython2.99.0 Architecture: any Section: libs Depends: ${shlibs:Depends}, ${misc:Depends} -Replaces: libqgis3.0.0 +Replaces: libqgis2.99.0 Description: QGIS - shared Python library QGIS is a Geographic Information System (GIS) which manages, analyzes and display databases of geographic information. @@ -170,7 +178,7 @@ Description: QGIS custom widgets for Qt Designer . This package contains a library to use specific QGIS widgets in Qt Designer. -Package: libqgis-server{QGIS_ABI} +Package: libqgis-server2.99.0 Architecture: any Depends: ${shlibs:Depends}, @@ -187,18 +195,18 @@ Section: libdevel Depends: grass-dev, libexpat1-dev, - libgdal1-dev, + libgdal-dev (>= 1.11), libgeos-dev (>= 3.0.0), - libgsl0-dev, + libgsl-dev, libpq-dev, libproj-dev, - libqgis-app3.0.0 (= ${binary:Version}), - libqgis-core3.0.0 (= ${binary:Version}), - libqgis-gui3.0.0 (= ${binary:Version}), - libqgis-analysis3.0.0 (= ${binary:Version}), - libqgis-networkanalysis3.0.0 (= ${binary:Version}), - libqgisgrass7.0.4-3.0.0 (= ${binary:Version}), - libqgispython3.0.0 (= ${binary:Version}), + libqgis-app2.99.0 (= ${binary:Version}), + libqgis-core2.99.0 (= ${binary:Version}), + libqgis-gui2.99.0 (= ${binary:Version}), + libqgis-analysis2.99.0 (= ${binary:Version}), + libqgis-networkanalysis2.99.0 (= ${binary:Version}), + libqgisgrass7-2.99.0 (= ${binary:Version}), + libqgispython2.99.0 (= ${binary:Version}), libsqlite3-dev, qtbase5-dev, python3-pyqt5, qttools5-dev, libqt5svg5-dev, pyqt5.qsci-dev, @@ -229,13 +237,13 @@ Architecture: any Section: debug Priority: extra Depends: - libqgis-app{QGIS_ABI} (= ${binary:Version}), - libqgis-core{QGIS_ABI} (= ${binary:Version}), - libqgis-gui{QGIS_ABI} (= ${binary:Version}), - libqgis-analysis{QGIS_ABI} (= ${binary:Version}), - libqgis-networkanalysis{QGIS_ABI} (= ${binary:Version}), - libqgisgrass{GRASSVER}-{QGIS_ABI} (= ${binary:Version}), - libqgispython{QGIS_ABI} (= ${binary:Version}), + libqgis-app2.99.0 (= ${binary:Version}), + libqgis-core2.99.0 (= ${binary:Version}), + libqgis-gui2.99.0 (= ${binary:Version}), + libqgis-analysis2.99.0 (= ${binary:Version}), + libqgis-networkanalysis2.99.0 (= ${binary:Version}), + libqgisgrass7-2.99.0 (= ${binary:Version}), + libqgispython2.99.0 (= ${binary:Version}), ${misc:Depends} Suggests: gdb Description: QGIS - debugging symbols @@ -304,7 +312,7 @@ Depends: python3-six, python3-yaml, python3-future, - libqgispython3.0.0, + libqgispython2.99.0, ${shlibs:Depends}, ${python:Depends}, ${misc:Depends}, diff --git a/debian/control.in b/debian/control.in index 322a4f5ba7bb..85ac9a81b3a6 100644 --- a/debian/control.in +++ b/debian/control.in @@ -6,14 +6,14 @@ Priority: optional Build-Depends: bison, cmake (>= 2.8), -#sid stretch jessie trusty xenial# debhelper (>= 9), -#sid stretch jessie trusty xenial# dh-python, + debhelper (>= 9), + dh-python, flex, grass-dev, libexpat1-dev, libfcgi-dev, -#sid stretch jessie trusty xenial# libgdal-dev (>= 1.10.1-0~), -#jessie trusty# libgsl0-dev, + libgdal-dev (>= 1.11), +#trusty# libgsl0-dev, #sid stretch xenial# libgsl-dev, libgeos-dev (>= 3.0.0), libpq-dev, @@ -40,12 +40,10 @@ Build-Depends: xfonts-base, xfonts-100dpi, xfonts-75dpi, xfonts-scalable, #sid# libosgearth-dev, #oracle# oracle-instantclient12.1-devel, - locales, ca-certificates + locales, ca-certificates, ninja-build Build-Conflicts: libqgis-dev, qgis-dev #sid stretch xenial#Standards-Version: 3.9.7 -#jessie#Standards-Version: 3.9.6 #trusty#Standards-Version: 3.8.4 -#sid stretch jessie#X-Python-Version: >= 2.7, << 2.8 #trusty xenial#XS-Python-Version: current Vcs-Browser: https://github.com/qgis/QGIS/ Vcs-Git: https://github.com/qgis/QGIS.git @@ -202,9 +200,9 @@ Section: libdevel Depends: grass-dev, libexpat1-dev, -#sid stretch jessie trusty xenial# libgdal-dev (>= 1.10.1-0~), + libgdal-dev (>= 1.11), libgeos-dev (>= 3.0.0), -#jessie trusty# libgsl0-dev, +#trusty# libgsl0-dev, #sid stretch xenial# libgsl-dev, libpq-dev, libproj-dev, diff --git a/debian/rules b/debian/rules index 84b4b5f8324c..cd4d482298c8 100755 --- a/debian/rules +++ b/debian/rules @@ -36,7 +36,7 @@ endif QT_PLUGINS_DIR = usr/lib/$(DEB_BUILD_MULTIARCH)/qt5/plugins -ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"stretch xenial")) +ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"trusty stretch xenial")) DISTRIBUTION := sid endif @@ -56,6 +56,7 @@ GRASS=grass$(subst .,,$(shell pkg-config --modversion grass|cut -d. -f1,2)) GRASSVER=$(subst .,,$(shell pkg-config --modversion grass|cut -d. -f1)) CMAKE_OPTS := \ + -G Ninja \ -DBUILDNAME=$(DEB_BUILD_NAME) \ -DCMAKE_VERBOSE_MAKEFILE=1 \ -DCMAKE_INSTALL_PREFIX=/usr \ @@ -84,7 +85,8 @@ CMAKE_OPTS := \ -DWITH_QSPATIALITE=TRUE \ -DWITH_PYSPATIALITE=TRUE \ -DQT_PLUGINS_DIR=$(QT_PLUGINS_DIR) \ - -DPYTHON_LIBRARY=$(shell python3-config --ldflags | sed -e 's\#-L\(.*\) -L/usr/lib -l\([^ ]*\) .*$$\#\1/lib\2.so\#') + -DPYTHON_LIBRARY=$(shell python3-config --ldflags | sed -e 's\#-L\(.*\) -L/usr/lib -l\([^ ]*\) .*$$\#\1/lib\2.so\#') \ + -DDOXYGEN_ON_DEMAND=TRUE ifneq ($(SHA),) CMAKE_OPTS += -DSHA=$(SHA) @@ -136,7 +138,7 @@ endif -DORACLE_INCLUDEDIR=$(ORACLE_INCLUDEDIR) endif -ifneq (,$(findstring $(DISTRIBUTION),"sid stretch jessie")) +ifneq (,$(findstring $(DISTRIBUTION),"sid stretch")) CMAKE_OPTS += -DSPATIALINDEX_LIBRARY=/usr/lib/$(DEB_BUILD_MULTIARCH)/libspatialindex.so endif @@ -154,12 +156,10 @@ else CMAKE_OPTS += -DENABLE_TESTS=TRUE endif -ifneq (,$(findstring $(DISTRIBUTION),"jessie stretch trusty sid")) CPPFLAGS := $(shell dpkg-buildflags --get CPPFLAGS) CFLAGS := $(shell dpkg-buildflags --get CFLAGS) $(CPPFLAGS) CXXFLAGS := $(shell dpkg-buildflags --get CXXFLAGS) $(CPPFLAGS) LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) -endif ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS))) INSTALL_PROGRAM += -s @@ -236,6 +236,12 @@ override_dh_clean: cleantemplates override_dh_auto_configure: dh_auto_configure -- $(CMAKE_OPTS) +override_dh_auto_build-arch: + ninja -C $(QGIS_BUILDDIR) + +override_dh_auto_build-indep: + ninja -C $(QGIS_BUILDDIR) apidoc + override_dh_auto_test: test-stamp test-stamp: @@ -254,7 +260,7 @@ endif touch test-stamp override_dh_auto_install: - dh_auto_install + DESTDIR=$(CURDIR)/debian/tmp ninja -C $(QGIS_BUILDDIR) install # remove unwanted files $(RM) $(CURDIR)/debian/tmp/usr/share/qgis/doc/api/installdox diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 5c8edeffe46c..c1802517118b 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -103,7 +103,14 @@ IF(WITH_APIDOC) STRING(REPLACE ";" " " DOXYGEN_INPUT "${DOXYGEN_INPUT}") CONFIGURE_FILE(${CMAKE_SOURCE_DIR}/cmake_templates/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) - ADD_CUSTOM_TARGET(apidoc ALL DEPENDS ${QHP_FILES}) + + SET (DOXYGEN_ON_DEMAND FALSE CACHE BOOL "Determines whether the QGIS API doxygen documentation should be build on demand only") + + IF(DOXYGEN_ON_DEMAND) + ADD_CUSTOM_TARGET(apidoc DEPENDS ${QHP_FILES}) + ELSE(DOXYGEN_ON_DEMAND) + ADD_CUSTOM_TARGET(apidoc ALL DEPENDS ${QHP_FILES}) + ENDIF(DOXYGEN_ON_DEMAND) ADD_CUSTOM_COMMAND( OUTPUT ${QHP_FILES} DEPENDS ${DOXYGEN_FILES} From d2c20495d93af6d9481735ab3f6565b246cad6f7 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Wed, 5 Oct 2016 14:22:17 +0200 Subject: [PATCH 187/897] osgeo4w: switch to ninja --- ms-windows/osgeo4w/package-nightly.cmd | 29 +++++++++++++++----------- ms-windows/osgeo4w/package.cmd | 22 +++++++++---------- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/ms-windows/osgeo4w/package-nightly.cmd b/ms-windows/osgeo4w/package-nightly.cmd index df96c18e6735..92417b6aad2d 100644 --- a/ms-windows/osgeo4w/package-nightly.cmd +++ b/ms-windows/osgeo4w/package-nightly.cmd @@ -52,35 +52,36 @@ if not "%PROGRAMFILES(X86)%"=="" set PF86=%PROGRAMFILES(X86)% if "%PF86%"=="" set PF86=%PROGRAMFILES% if "%PF86%"=="" (echo PROGRAMFILES not set & goto error) -if "%ARCH%"=="x86" goto devenv_x86 -goto devenv_x86_64 +if "%ARCH%"=="x86" goto cmake_x86 +goto cmake_x86_64 -:devenv_x86 +:cmake_x86 set GRASS6_VERSION=6.4.4 call "%PF86%\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86 if exist "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" call "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" /x86 /Release path %path%;%PF86%\Microsoft Visual Studio 10.0\VC\bin +set CMAKE_COMPILER_PATH=%PF86%\Microsoft Visual Studio 10.0\VC\bin set CMAKE_OPT=^ - -G "Visual Studio 10" ^ -D SIP_BINARY_PATH=%O4W_ROOT%/apps/Python27/sip.exe ^ -D QWT_LIBRARY=%O4W_ROOT%/lib/qwt.lib ^ -D CMAKE_CXX_FLAGS_RELWITHDEBINFO="/MD /ZI /MP /Od /D NDEBUG /D QGISDEBUG" ^ - -D CMAKE_PDB_OUTPUT_DIRECTORY_RELWITHDEBINFO=%BUILDDIR%\apps\%PACKAGENAME%\pdb -goto devenv + -D CMAKE_PDB_OUTPUT_DIRECTORY_RELWITHDEBINFO=%BUILDDIR%\apps\%PACKAGENAME%\pdb ^ + -D SPATIALINDEX_LIBRARY=%O4W_ROOT%/lib/spatialindex_i.lib +goto cmake -:devenv_x86_64 +:cmake_x86_64 set GRASS6_VERSION=6.4.3 call "%PF86%\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" amd64 if exist "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" call "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" /x64 /Release path %path%;%PF86%\Microsoft Visual Studio 10.0\VC\bin +set CMAKE_COMPILER_PATH=%PF86%\Microsoft Visual Studio 10.0\VC\bin\amd64 set SETUPAPI_LIBRARY=%PF86%\Microsoft SDKs\Windows\v7.0A\Lib\x64\SetupAPI.Lib if not exist "%SETUPAPI_LIBRARY%" set SETUPAPI_LIBRARY=%PROGRAMFILES%\Microsoft SDKs\Windows\v7.1\Lib\x64\SetupAPI.lib if not exist "%SETUPAPI_LIBRARY%" (echo SETUPAPI_LIBRARY not found & goto error) set CMAKE_OPT=^ - -G "Visual Studio 10 Win64" ^ -D SPATIALINDEX_LIBRARY=%O4W_ROOT%/lib/spatialindex-64.lib ^ -D SIP_BINARY_PATH=%O4W_ROOT%/bin/sip.exe ^ -D QWT_LIBRARY=%O4W_ROOT%/lib/qwt5.lib ^ @@ -89,7 +90,7 @@ set CMAKE_OPT=^ -D SETUPAPI_LIBRARY="%SETUPAPI_LIBRARY%" ^ -D CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS=TRUE -:devenv +:cmake for /f "usebackq tokens=1" %%a in (`%OSGEO4W_ROOT%\bin\grass70 --config path`) do set GRASS70_PATH=%%a for %%i in ("%GRASS70_PATH%") do set GRASS70_VERSION=%%~nxi set GRASS70_VERSION=%GRASS70_VERSION:grass-=% @@ -153,7 +154,10 @@ if errorlevel 1 goto error set LIB=%LIB%;%OSGEO4W_ROOT%\lib set INCLUDE=%INCLUDE%;%OSGEO4W_ROOT%\include -cmake %CMAKE_OPT% ^ +cmake -G Ninja ^ + -D CMAKE_CXX_COMPILER="%CMAKE_COMPILER_PATH:\=/%/cl.exe" ^ + -D CMAKE_C_COMPILER="%CMAKE_COMPILER_PATH:\=/%/cl.exe" ^ + -D CMAKE_LINKER="%CMAKE_COMPILER_PATH:\=/%/link.exe" ^ -D BUILDNAME="%PACKAGENAME%-%VERSION%%SHA%-Nightly-VC10-%ARCH%" ^ -D SITE="%SITE%" ^ -D PEDANTIC=TRUE ^ @@ -195,7 +199,8 @@ cmake %CMAKE_OPT% ^ -D WITH_INTERNAL_MOCK=FALSE ^ -D WITH_INTERNAL_HTTPLIB2=FALSE ^ -D WITH_INTERNAL_FUTURE=FALSE ^ - %SRCDIR% + %CMAKE_OPT% ^ + %SRCDIR:\=/% if errorlevel 1 (echo cmake failed & goto error) :skipcmake @@ -244,7 +249,7 @@ if exist "%PKGDIR%" ( ) echo INSTALL: %DATE% %TIME% -cmake --build %BUILDDIR% --target INSTALL --config %BUILDCONF% +cmake --build %BUILDDIR% --target install --config %BUILDCONF% if errorlevel 1 (echo INSTALL failed & goto error) :package diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index 67bac59be679..091158482842 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -52,22 +52,22 @@ if not "%PROGRAMFILES(X86)%"=="" set PF86=%PROGRAMFILES(X86)% if "%PF86%"=="" set PF86=%PROGRAMFILES% if "%PF86%"=="" (echo PROGRAMFILES not set & goto error) -if "%ARCH%"=="x86" goto devenv_x86 -goto devenv_x86_64 +if "%ARCH%"=="x86" goto cmake_x86 +goto cmake_x86_64 -:devenv_x86 +:cmake_x86 set GRASS6_VERSION=6.4.4 call "%PF86%\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86 if exist "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" call "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" /x86 /Release path %path%;%PF86%\Microsoft Visual Studio 10.0\VC\bin +set CMAKE_COMPILER_PATH=%PF86%\Microsoft Visual Studio 10.0\VC\bin set CMAKE_OPT=^ - -G "Visual Studio 10" ^ -D SIP_BINARY_PATH=%O4W_ROOT%/apps/Python27/sip.exe ^ -D QWT_LIBRARY=%O4W_ROOT%/lib/qwt.lib -goto devenv +goto cmake -:devenv_x86_64 +:cmake_x86_64 set GRASS6_VERSION=6.4.3 call "%PF86%\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" amd64 if exist "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" call "c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.Cmd" /x64 /Release @@ -78,14 +78,13 @@ if not exist "%SETUPAPI_LIBRARY%" set SETUPAPI_LIBRARY=%PROGRAMFILES%\Microsoft if not exist "%SETUPAPI_LIBRARY%" (echo SETUPAPI_LIBRARY not found & goto error) set CMAKE_OPT=^ - -G "Visual Studio 10 Win64" ^ -D SPATIALINDEX_LIBRARY=%O4W_ROOT%/lib/spatialindex-64.lib ^ -D SIP_BINARY_PATH=%O4W_ROOT%/bin/sip.exe ^ -D QWT_LIBRARY=%O4W_ROOT%/lib/qwt5.lib ^ -D SETUPAPI_LIBRARY="%SETUPAPI_LIBRARY%" ^ -D CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS=TRUE -:devenv +:cmake for /f "usebackq tokens=1" %%a in (`%OSGEO4W_ROOT%\bin\grass70 --config path`) do set GRASS70_PATH=%%a for %%i in ("%GRASS70_PATH%") do set GRASS70_VERSION=%%~nxi set GRASS70_VERSION=%GRASS70_VERSION:grass-=% @@ -149,7 +148,7 @@ if errorlevel 1 goto error set LIB=%LIB%;%OSGEO4W_ROOT%\lib set INCLUDE=%INCLUDE%;%OSGEO4W_ROOT%\include -cmake %CMAKE_OPT% ^ +cmake -G Ninja ^ -D BUILDNAME="%PACKAGENAME%-%VERSION%%SHA%-Release-VC10-%ARCH%" ^ -D SITE="%SITE%" ^ -D PEDANTIC=TRUE ^ @@ -189,7 +188,8 @@ cmake %CMAKE_OPT% ^ -D WITH_INTERNAL_PYTZ=FALSE ^ -D WITH_INTERNAL_SIX=FALSE ^ -D WITH_INTERNAL_FUTURE=FALSE ^ - %SRCDIR% + %CMAKE_OPT% ^ + %SRCDIR:\=/% if errorlevel 1 (echo cmake failed & goto error) :skipcmake @@ -229,7 +229,7 @@ if exist "%PKGDIR%" ( ) echo INSTALL: %DATE% %TIME% -cmake --build %BUILDDIR% --target INSTALL --config %BUILDCONF% +cmake --build %BUILDDIR% --target install --config %BUILDCONF% if errorlevel 1 (echo INSTALL failed & goto error) echo PACKAGE: %DATE% %TIME% From 17010acf5519d121e8e4ef816e4c57d6ffb33efa Mon Sep 17 00:00:00 2001 From: Mathieu Pellerin Date: Thu, 6 Oct 2016 18:40:24 +0700 Subject: [PATCH 188/897] [travis] fix grass7 plugin build by adding GRASS_PREFIX7 (#3578) * [travis] fix grass7 plugin build by adding GRASS_PREFIX7 * Followup 3n0486c: fix grass plugin build, take 2 --- ci/travis/linux/install.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ci/travis/linux/install.sh b/ci/travis/linux/install.sh index 2e0ebee66b6e..344607830e76 100755 --- a/ci/travis/linux/install.sh +++ b/ci/travis/linux/install.sh @@ -42,6 +42,8 @@ cmake \ -DCMAKE_PREFIX_PATH=/home/travis/osgeo4travis \ -DWITH_STAGED_PLUGINS=ON \ -DWITH_GRASS=ON \ + -DWITH_GRASS7=ON \ + -DGRASS_PREFIX7=/home/travis/osgeo4travis/grass-7.0.4 \ -DSUPPRESS_QT_WARNINGS=ON \ -DENABLE_MODELTEST=ON \ -DENABLE_PGTEST=ON \ From 45a84419ffea466fbc432f2016090d869c36a453 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 15:57:13 +0300 Subject: [PATCH 189/897] [processing] show error message instead of Python error if output raster is temp output and test can not be created --- python/plugins/processing/gui/TestTools.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/TestTools.py b/python/plugins/processing/gui/TestTools.py index a8d320915921..e5f0ebe5e2d3 100644 --- a/python/plugins/processing/gui/TestTools.py +++ b/python/plugins/processing/gui/TestTools.py @@ -37,7 +37,7 @@ from numpy import nan_to_num from qgis.PyQt.QtCore import QCoreApplication, QMetaObject -from qgis.PyQt.QtWidgets import QDialog, QVBoxLayout, QTextEdit +from qgis.PyQt.QtWidgets import QDialog, QVBoxLayout, QTextEdit, QMessageBox from processing.core.Processing import Processing from processing.core.outputs import ( @@ -232,6 +232,15 @@ def createTest(text): if isinstance(out, (OutputNumber, OutputString)): results[out.name] = str(out) elif isinstance(out, OutputRaster): + if token is None: + QMessageBox.warning(None, + tr('Error'), + tr('Seems some outputs are temporary ' + 'files. To create test you need to ' + 'redirect all algorithm outputs to ' + 'files')) + return + dataset = gdal.Open(token, GA_ReadOnly) dataArray = nan_to_num(dataset.ReadAsArray(0)) strhash = hashlib.sha224(dataArray.data).hexdigest() From daf8f7a2444cbe00eb539480b8a2f47c1c9e35f9 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Thu, 6 Oct 2016 15:54:27 +0200 Subject: [PATCH 190/897] fix PyQgsAppStartup (followup d9349e5) --- tests/src/python/test_qgsappstartup.py | 2 +- tests/testdata/test_plugin_path/QGIS/{QGIS.ini => QGIS3.ini} | 0 .../testdata/test_plugin_path/qgis.org/{QGIS.ini => QGIS3.ini} | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename tests/testdata/test_plugin_path/QGIS/{QGIS.ini => QGIS3.ini} (100%) rename tests/testdata/test_plugin_path/qgis.org/{QGIS.ini => QGIS3.ini} (100%) diff --git a/tests/src/python/test_qgsappstartup.py b/tests/src/python/test_qgsappstartup.py index f2fb287fe3c9..4bf21c0a6f50 100644 --- a/tests/src/python/test_qgsappstartup.py +++ b/tests/src/python/test_qgsappstartup.py @@ -101,7 +101,7 @@ def testOptionsPath(self): subdir = 'QGIS' # Linux if sys.platform[:3] == 'dar': # Mac subdir = 'qgis.org' - ini = os.path.join(subdir, 'QGIS.ini') + ini = os.path.join(subdir, 'QGIS3.ini') for p in ['test_opts', 'test opts', 'test_optsé€']: self.doTestStartup(option="--optionspath", testDir=os.path.join(self.TMP_DIR, p), diff --git a/tests/testdata/test_plugin_path/QGIS/QGIS.ini b/tests/testdata/test_plugin_path/QGIS/QGIS3.ini similarity index 100% rename from tests/testdata/test_plugin_path/QGIS/QGIS.ini rename to tests/testdata/test_plugin_path/QGIS/QGIS3.ini diff --git a/tests/testdata/test_plugin_path/qgis.org/QGIS.ini b/tests/testdata/test_plugin_path/qgis.org/QGIS3.ini similarity index 100% rename from tests/testdata/test_plugin_path/qgis.org/QGIS.ini rename to tests/testdata/test_plugin_path/qgis.org/QGIS3.ini From 5b6e4b80b102bea6df38b3482cfc07f0314b6c1a Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 16:14:45 +0200 Subject: [PATCH 191/897] [OGR provider] Check if REPACK has emitted errors Refs #15393 and #15570 Real fix for the REPACK issues has been committed per GDAL ticket https://trac.osgeo.org/gdal/ticket/6672 (GDAL 2.1.2 or above) Add test to simulate the situations that caused problems. --- src/providers/ogr/qgsogrprovider.cpp | 5 ++ tests/src/python/test_provider_shapefile.py | 57 +++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 8c8645fbaa35..14c554247d1f 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -154,7 +154,12 @@ void QgsOgrProvider::repack() // run REPACK on shape files QByteArray sql = QByteArray( "REPACK " ) + layerName; // don't quote the layer name as it works with spaces in the name and won't work if the name is quoted QgsDebugMsg( QString( "SQL: %1" ).arg( FROM8( sql ) ) ); + CPLErrorReset(); OGR_DS_ExecuteSQL( ogrDataSource, sql.constData(), nullptr, nullptr ); + if ( CPLGetLastErrorType() != CE_None ) + { + pushError( tr( "OGR[%1] error %2: %3" ).arg( CPLGetLastErrorType() ).arg( CPLGetLastErrorNo() ).arg( CPLGetLastErrorMsg() ) ); + } if ( mFilePath.endsWith( ".shp", Qt::CaseInsensitive ) || mFilePath.endsWith( ".dbf", Qt::CaseInsensitive ) ) { diff --git a/tests/src/python/test_provider_shapefile.py b/tests/src/python/test_provider_shapefile.py index fd268b476dbd..1830f08388e9 100644 --- a/tests/src/python/test_provider_shapefile.py +++ b/tests/src/python/test_provider_shapefile.py @@ -30,6 +30,19 @@ TEST_DATA_DIR = unitTestDataPath() +def GDAL_COMPUTE_VERSION(maj, min, rev): + return ((maj) * 1000000 + (min) * 10000 + (rev) * 100) + + +class ErrorReceiver(): + + def __init__(self): + self.msg = None + + def receiveError(self, msg): + self.msg = msg + + class TestPyQgsShapefileProvider(unittest.TestCase, ProviderTestCase): @classmethod @@ -380,5 +393,49 @@ def testDeleteShapes(self): vl = None + def testRepackUnderFileLocks(self): + ''' Test fix for #15570 and #15393 ''' + + # This requires a GDAL fix done per https://trac.osgeo.org/gdal/ticket/6672 + # but on non-Windows version the test would succeed + if int(osgeo.gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 1, 2): + return + + tmpdir = tempfile.mkdtemp() + self.dirs_to_cleanup.append(tmpdir) + srcpath = os.path.join(TEST_DATA_DIR, 'provider') + for file in glob.glob(os.path.join(srcpath, 'shapefile.*')): + shutil.copy(os.path.join(srcpath, file), tmpdir) + datasource = os.path.join(tmpdir, 'shapefile.shp') + + vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') + feature_count = vl.featureCount() + + # Keep a file descriptor opened on the .dbf, .shp and .shx + f_shp = open(os.path.join(tmpdir, 'shapefile.shp'), 'rb') + f_shx = open(os.path.join(tmpdir, 'shapefile.shx'), 'rb') + f_dbf = open(os.path.join(tmpdir, 'shapefile.dbf'), 'rb') + + # Delete a feature + self.assertTrue(vl.startEditing()) + self.assertTrue(vl.deleteFeature(1)) + + # Commit changes and check no error is emitted + cbk = ErrorReceiver() + vl.dataProvider().raiseError.connect(cbk.receiveError) + self.assertTrue(vl.commitChanges()) + self.assertIsNone(cbk.msg) + + vl = None + + del f_shp + del f_shx + del f_dbf + + # Test repacking has been done + ds = osgeo.ogr.Open(datasource) + self.assertTrue(ds.GetLayer(0).GetFeatureCount(), feature_count - 1) + ds = None + if __name__ == '__main__': unittest.main() From fffbf784b099307cc22d74cfd522209693aa1339 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 18:01:03 +0200 Subject: [PATCH 192/897] Fix exception in GDALTools.doRasterize.loadFields due to Python 3 conversion --- python/plugins/GdalTools/tools/doRasterize.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/python/plugins/GdalTools/tools/doRasterize.py b/python/plugins/GdalTools/tools/doRasterize.py index b682da930f94..9b88dabf2b5e 100644 --- a/python/plugins/GdalTools/tools/doRasterize.py +++ b/python/plugins/GdalTools/tools/doRasterize.py @@ -153,6 +153,10 @@ def loadFields(self, vectorFile): self.inSelector.setLayer(None) return - ncodec = QTextCodec.codecForName(self.lastEncoding) + # GDAL Python3 bindings return fields as str and not bytes + # so no recoding is needed. But this assumes that the underlying + # OGR driver always return a Unicode string. hum... + #ncodec = QTextCodec.codecForName(self.lastEncoding) for name in names: - self.attributeComboBox.addItem(ncodec.toUnicode(name)) + self.attributeComboBox.addItem(name) + #self.attributeComboBox.addItem(ncodec.toUnicode(name)) From b8ff71af4671165b61fa4f9a7f652e38e4f8bb18 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 18:44:35 +0200 Subject: [PATCH 193/897] [WFS provider] Force refresh of GetCapabilities when pressing Connect The cached response to GetCapabilities was always used, even when pressing Connect. Now a new request is sent over the network. Fixes #15647 --- src/providers/wfs/qgswfscapabilities.cpp | 4 ++-- src/providers/wfs/qgswfscapabilities.h | 2 +- src/providers/wfs/qgswfsdataitems.cpp | 4 +++- src/providers/wfs/qgswfsprovider.cpp | 4 +++- src/providers/wfs/qgswfssourceselect.cpp | 4 +++- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/providers/wfs/qgswfscapabilities.cpp b/src/providers/wfs/qgswfscapabilities.cpp index 605d220747e9..50da4f219ad4 100644 --- a/src/providers/wfs/qgswfscapabilities.cpp +++ b/src/providers/wfs/qgswfscapabilities.cpp @@ -35,7 +35,7 @@ QgsWfsCapabilities::~QgsWfsCapabilities() { } -bool QgsWfsCapabilities::requestCapabilities( bool synchronous ) +bool QgsWfsCapabilities::requestCapabilities( bool synchronous, bool forceRefresh ) { QUrl url( baseURL() ); url.addQueryItem( "REQUEST", "GetCapabilities" ); @@ -47,7 +47,7 @@ bool QgsWfsCapabilities::requestCapabilities( bool synchronous ) else url.addQueryItem( "VERSION", version ); - if ( !sendGET( url, synchronous, false ) ) + if ( !sendGET( url, synchronous, forceRefresh ) ) { emit gotCapabilities(); return false; diff --git a/src/providers/wfs/qgswfscapabilities.h b/src/providers/wfs/qgswfscapabilities.h index acb7fe77ff47..cb056e1fcc1a 100644 --- a/src/providers/wfs/qgswfscapabilities.h +++ b/src/providers/wfs/qgswfscapabilities.h @@ -30,7 +30,7 @@ class QgsWfsCapabilities : public QgsWfsRequest virtual ~QgsWfsCapabilities(); //! start network connection to get capabilities - bool requestCapabilities( bool synchronous ); + bool requestCapabilities( bool synchronous, bool forceRefresh ); //! description of a vector layer struct FeatureType diff --git a/src/providers/wfs/qgswfsdataitems.cpp b/src/providers/wfs/qgswfsdataitems.cpp index 67cb0d76447b..7a9772467968 100644 --- a/src/providers/wfs/qgswfsdataitems.cpp +++ b/src/providers/wfs/qgswfsdataitems.cpp @@ -62,7 +62,9 @@ QVector QgsWfsConnectionItem::createChildren() QgsWfsCapabilities capabilities( mUri ); - capabilities.requestCapabilities( true ); + const bool synchronous = true; + const bool forceRefresh = false; + capabilities.requestCapabilities( synchronous, forceRefresh ); QVector layers; if ( capabilities.errorCode() == QgsWfsCapabilities::NoError ) diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index 72de7c08a4a0..d1ed7ea82605 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -1437,7 +1437,9 @@ bool QgsWFSProvider::getCapabilities() if ( mShared->mCaps.version.isEmpty() ) { QgsWfsCapabilities getCapabilities( mShared->mURI.uri( false ) ); - if ( !getCapabilities.requestCapabilities( true ) ) + const bool synchronous = true; + const bool forceRefresh = false; + if ( !getCapabilities.requestCapabilities( synchronous, forceRefresh ) ) { QgsMessageLog::logMessage( tr( "GetCapabilities failed for url %1: %2" ). arg( dataSourceUri() ).arg( getCapabilities.errorMessage() ), tr( "WFS" ) ); diff --git a/src/providers/wfs/qgswfssourceselect.cpp b/src/providers/wfs/qgswfssourceselect.cpp index e0d5585d2e2a..3ed15d37da46 100644 --- a/src/providers/wfs/qgswfssourceselect.cpp +++ b/src/providers/wfs/qgswfssourceselect.cpp @@ -353,7 +353,9 @@ void QgsWFSSourceSelect::connectToServer() } if ( mCapabilities ) { - mCapabilities->requestCapabilities( false ); + const bool synchronous = false; + const bool forceRefresh = true; + mCapabilities->requestCapabilities( synchronous, forceRefresh ); } } From 1ebd5a454d9e580bbf04d42d619bdfd95ee07260 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 19:09:24 +0200 Subject: [PATCH 194/897] [WFS provider] Do not append crs at end of BBOX in WFS 1.0 Fixes #15464 --- src/providers/wfs/qgswfsfeatureiterator.cpp | 7 +++++- tests/src/python/test_provider_wfs.py | 25 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/providers/wfs/qgswfsfeatureiterator.cpp b/src/providers/wfs/qgswfsfeatureiterator.cpp index c1fedbe48b17..437037f69c93 100644 --- a/src/providers/wfs/qgswfsfeatureiterator.cpp +++ b/src/providers/wfs/qgswfsfeatureiterator.cpp @@ -310,7 +310,12 @@ QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool fo qgsDoubleToString( mShared->mRect.yMaximum() ) ) ); // Some servers like Geomedia need the srsname to be explictly appended // otherwise they are confused and do not interpret it properly - bbox += "," + mShared->srsName(); + if ( !mShared->mWFSVersion.startsWith( "1.0" ) ) + { + // but it is illegal in WFS 1.0 and some servers definitely not like + // it. See #15464 + bbox += "," + mShared->srsName(); + } getFeatureUrl.addQueryItem( "BBOX", bbox ); } else if ( !mShared->mWFSFilter.isEmpty() ) diff --git a/tests/src/python/test_provider_wfs.py b/tests/src/python/test_provider_wfs.py index 575b0475ff6b..f1f6da02ede8 100644 --- a/tests/src/python/test_provider_wfs.py +++ b/tests/src/python/test_provider_wfs.py @@ -462,6 +462,31 @@ def testWFS10(self): assert not vl.dataProvider().deleteFeatures([0]) + # Test with restrictToRequestBBOX=1 + with open(sanitize(endpoint, '?SERVICE=WFS&REQUEST=GetFeature&VERSION=1.0.0&TYPENAME=my:typename&SRSNAME=EPSG:32631&BBOX=400000,5400000,450000,5500000'), 'wb') as f: + f.write(""" + + unknown + + + + 426858,5427937 + + 100 + + +""".encode('UTF-8')) + + vl = QgsVectorLayer("url='http://" + endpoint + "' typename='my:typename' version='1.0.0' restrictToRequestBBOX=1", 'test', 'WFS') + + extent = QgsRectangle(400000.0, 5400000.0, 450000.0, 5500000.0) + request = QgsFeatureRequest().setFilterRect(extent) + values = [f['INTFIELD'] for f in vl.getFeatures(request)] + self.assertEqual(values, [100]) + def testWFS10_latlongboundingbox_in_WGS84(self): """Test WFS 1.0 with non conformatn LatLongBoundingBox""" From 7182b1b871c594417b3598d5d0927529494ba253 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 19:43:00 +0200 Subject: [PATCH 195/897] Properly deal with empty cache/directory in WFS provider, server and globe plugin Fixes #15111 --- src/plugins/globe/globe_plugin.cpp | 4 +++- src/providers/wfs/qgswfsutils.cpp | 4 +++- src/server/qgsserver.cpp | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/plugins/globe/globe_plugin.cpp b/src/plugins/globe/globe_plugin.cpp index 2ddfe65541dd..4b58ddc7527b 100644 --- a/src/plugins/globe/globe_plugin.cpp +++ b/src/plugins/globe/globe_plugin.cpp @@ -342,7 +342,9 @@ void GlobePlugin::run() } else { - QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString(); + QString cacheDirectory = settings.value( "cache/directory" ).toString(); + if ( cacheDirectory.isEmpty() ) + cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache"; osgEarth::Drivers::FileSystemCacheOptions cacheOptions; cacheOptions.rootPath() = cacheDirectory.toStdString(); diff --git a/src/providers/wfs/qgswfsutils.cpp b/src/providers/wfs/qgswfsutils.cpp index 23adf9e15d82..dbb2b8978496 100644 --- a/src/providers/wfs/qgswfsutils.cpp +++ b/src/providers/wfs/qgswfsutils.cpp @@ -37,7 +37,9 @@ int QgsWFSUtils::gmCounter = 0; QString QgsWFSUtils::getBaseCacheDirectory( bool createIfNotExisting ) { QSettings settings; - QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString(); + QString cacheDirectory = settings.value( "cache/directory" ).toString(); + if ( cacheDirectory.isEmpty() ) + cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache"; if ( createIfNotExisting ) { QMutexLocker locker( &gmMutex ); diff --git a/src/server/qgsserver.cpp b/src/server/qgsserver.cpp index 4aff5dbe2eac..36ad91d9d38d 100644 --- a/src/server/qgsserver.cpp +++ b/src/server/qgsserver.cpp @@ -112,7 +112,9 @@ void QgsServer::setupNetworkAccessManager() QSettings settings; QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance(); QNetworkDiskCache *cache = new QNetworkDiskCache( nullptr ); - QString cacheDirectory = settings.value( "cache/directory", QgsApplication::qgisSettingsDirPath() + "cache" ).toString(); + QString cacheDirectory = settings.value( "cache/directory" ).toString(); + if ( cacheDirectory.isEmpty() ) + cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache"; qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong(); QgsMessageLog::logMessage( QString( "setCacheDirectory: %1" ).arg( cacheDirectory ), "Server", QgsMessageLog::INFO ); QgsMessageLog::logMessage( QString( "setMaximumCacheSize: %1" ).arg( cacheSize ), "Server", QgsMessageLog::INFO ); From 893263952d190d9abc2f239fa513cb327df77bee Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 20:45:46 +0200 Subject: [PATCH 196/897] QgsSymbol::renderFeature(): render larger parts of multipolygon first When drawing an invalid multipolygon, that has a part inside another one, there is a chance we draw first the smaller part and then the larger part, making it invisible. Change the drawing order to start with larger parts. Fixes #15419 --- src/core/symbology-ng/qgssymbol.cpp | 54 ++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index 25648668d171..04e590645f31 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -47,6 +47,7 @@ #include #include +#include inline QgsDataDefined* rotateWholeSymbol( double additionalRotation, const QgsDataDefined& dd ) @@ -842,30 +843,49 @@ void QgsSymbol::renderFeature( const QgsFeature& feature, QgsRenderContext& cont const QgsGeometryCollection& geomCollection = dynamic_cast( *segmentizedGeometry.geometry() ); const unsigned int num = geomCollection.numGeometries(); + // Sort components by approximate area (probably a bit faster than using + // area() ) + std::map > mapAreaToPartNum; for ( unsigned int i = 0; i < num; ++i ) { - mSymbolRenderContext->setGeometryPartNum( i + 1 ); - mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1 ); - - context.setGeometry( geomCollection.geometryN( i ) ); const QgsPolygonV2& polygon = dynamic_cast( *geomCollection.geometryN( i ) ); - _getPolygon( pts, holes, context, polygon, !tileMapRendering && clipFeaturesToExtent() ); - static_cast( this )->renderPolygon( pts, ( !holes.isEmpty() ? &holes : nullptr ), &feature, context, layer, selected ); + const QgsRectangle r( polygon.boundingBox() ); + mapAreaToPartNum[ r.width() * r.height()] << i; + } - if ( drawVertexMarker && !usingSegmentizedGeometry ) + // Draw starting with larger parts down to smaller parts, so that in + // case of a part being incorrectly inside another part, it is drawn + // on top of it (#15419) + std::map >::const_reverse_iterator iter = mapAreaToPartNum.rbegin(); + for ( ; iter != mapAreaToPartNum.rend(); ++iter ) + { + const QList& listPartIndex = iter->second; + for ( int idx = 0; idx < listPartIndex.size(); ++idx ) { - if ( i == 0 ) - { - markers = pts; - } - else - { - markers << pts; - } + const unsigned i = listPartIndex[idx]; + mSymbolRenderContext->setGeometryPartNum( i + 1 ); + mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1 ); + + context.setGeometry( geomCollection.geometryN( i ) ); + const QgsPolygonV2& polygon = dynamic_cast( *geomCollection.geometryN( i ) ); + _getPolygon( pts, holes, context, polygon, !tileMapRendering && clipFeaturesToExtent() ); + static_cast( this )->renderPolygon( pts, ( !holes.isEmpty() ? &holes : nullptr ), &feature, context, layer, selected ); - Q_FOREACH ( const QPolygonF& hole, holes ) + if ( drawVertexMarker && !usingSegmentizedGeometry ) { - markers << hole; + if ( i == 0 ) + { + markers = pts; + } + else + { + markers << pts; + } + + Q_FOREACH ( const QPolygonF& hole, holes ) + { + markers << hole; + } } } } From e5f7cdcba44166b2f8aeb1a7a22f3175065e27bf Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Oct 2016 23:18:22 +0200 Subject: [PATCH 197/897] [WFS provider] Be robust to field names ending with spaces in DescribeFeatureType Fixes #3426 --- src/providers/wfs/qgswfsprovider.cpp | 7 +++++++ tests/src/python/test_provider_wfs.py | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index d1ed7ea82605..4c9cbbd4b111 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -1249,8 +1249,15 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, for ( int i = 0; i < attributeNodeList.size(); ++i ) { QDomElement attributeElement = attributeNodeList.at( i ).toElement(); + //attribute name QString name = attributeElement.attribute( "name" ); + // Some servers like http://ogi.state.ok.us/geoserver/wfs on layer ogi:doq_centroids + // return attribute names padded with spaces. See http://hub.qgis.org/issues/3426 + // I'm not completely sure how legal this + // is but this validates with Xerces 3.1, and its schema analyzer does also the trimming. + name = name.trimmed(); + //attribute type QString type = attributeElement.attribute( "type" ); if ( type.isEmpty() ) diff --git a/tests/src/python/test_provider_wfs.py b/tests/src/python/test_provider_wfs.py index f1f6da02ede8..66eef5b62735 100644 --- a/tests/src/python/test_provider_wfs.py +++ b/tests/src/python/test_provider_wfs.py @@ -111,7 +111,8 @@ def setUpClass(cls): - + + From dab18e767535e77285de7f0526a1beea475046e5 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 7 Oct 2016 11:53:30 +0700 Subject: [PATCH 198/897] [db manager] fix non-spatial import --- python/plugins/db_manager/dlg_export_vector.py | 2 +- python/plugins/db_manager/dlg_import_vector.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/db_manager/dlg_export_vector.py b/python/plugins/db_manager/dlg_export_vector.py index e3e8ab778438..89a8c9e779d0 100644 --- a/python/plugins/db_manager/dlg_export_vector.py +++ b/python/plugins/db_manager/dlg_export_vector.py @@ -163,7 +163,7 @@ def accept(self): if self.chkDropTable.isChecked(): options['overwrite'] = True - outCrs = None + outCrs = QgsCoordinateReferenceSystem if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) diff --git a/python/plugins/db_manager/dlg_import_vector.py b/python/plugins/db_manager/dlg_import_vector.py index 4cb8e6d0402e..f8b46ad9dee1 100644 --- a/python/plugins/db_manager/dlg_import_vector.py +++ b/python/plugins/db_manager/dlg_import_vector.py @@ -315,7 +315,7 @@ def accept(self): if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(): options['forceSinglePartGeometryType'] = True - outCrs = None + outCrs = QgsCoordinateReferenceSystem() if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) From 20d006e101ec4a515e2cc85901f5bf4c886599bf Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 7 Oct 2016 11:54:16 +0700 Subject: [PATCH 199/897] [db manager] fix spatialite error reporting --- python/plugins/db_manager/db_plugins/spatialite/connector.py | 1 + python/plugins/db_manager/dlg_export_vector.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/python/plugins/db_manager/db_plugins/spatialite/connector.py b/python/plugins/db_manager/db_plugins/spatialite/connector.py index 378d076f81c1..cefebda77e1d 100644 --- a/python/plugins/db_manager/db_plugins/spatialite/connector.py +++ b/python/plugins/db_manager/db_plugins/spatialite/connector.py @@ -31,6 +31,7 @@ from ..plugin import ConnectionError, DbError, Table from qgis.utils import spatialite_connect +import sqlite3 as sqlite def classFactory(): diff --git a/python/plugins/db_manager/dlg_export_vector.py b/python/plugins/db_manager/dlg_export_vector.py index 89a8c9e779d0..4add06735878 100644 --- a/python/plugins/db_manager/dlg_export_vector.py +++ b/python/plugins/db_manager/dlg_export_vector.py @@ -163,7 +163,7 @@ def accept(self): if self.chkDropTable.isChecked(): options['overwrite'] = True - outCrs = QgsCoordinateReferenceSystem + outCrs = QgsCoordinateReferenceSystem() if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) From 12a8891b15be7fddbd5d9c56bf0cb6e1cc001339 Mon Sep 17 00:00:00 2001 From: Frits van Veen Date: Mon, 5 Sep 2016 08:53:11 +0200 Subject: [PATCH 200/897] Fix curved labels --- src/core/pal/feature.cpp | 23 ++++++++++++++++++----- src/core/pal/feature.h | 2 +- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/core/pal/feature.cpp b/src/core/pal/feature.cpp index 861efc6e9b03..64511d265a45 100644 --- a/src/core/pal/feature.cpp +++ b/src/core/pal/feature.cpp @@ -1170,6 +1170,19 @@ int FeaturePart::createCurvedCandidatesAlongLine( QList< LabelPosition* >& lPos, return 0; } + //calculate overall angle of line + double lineAngle; + double bx = mapShape->x[0]; + double by = mapShape->y[0]; + double ex = mapShape->x[ mapShape->nbPoints - 1 ]; + double ey = mapShape->y[ mapShape->nbPoints - 1 ]; + if ( qgsDoubleNear( ey, by ) && qgsDoubleNear( ex, bx ) ) + { + lineAngle = 0.0; + } + else + lineAngle = atan2( ey - by, ex - bx ); + QLinkedList positions; double delta = qMax( li->label_height, total_distance / mLF->layer()->pal->line_p ); @@ -1178,7 +1191,7 @@ int FeaturePart::createCurvedCandidatesAlongLine( QList< LabelPosition* >& lPos, flags = FLAG_ON_LINE; // default flag // generate curved labels - for ( int i = 0; i * delta < total_distance; i++ ) + for ( double i = 0; i < total_distance; i += delta ) { bool flip = false; // placements may need to be reversed if using map orientation and the line has right-to-left direction @@ -1193,7 +1206,7 @@ int FeaturePart::createCurvedCandidatesAlongLine( QList< LabelPosition* >& lPos, orientation = 1; } - LabelPosition* slp = curvedPlacementAtOffset( mapShape, path_distances, orientation, 1, i * delta, reversed, flip ); + LabelPosition* slp = curvedPlacementAtOffset( mapShape, path_distances, orientation, 1, i, reversed, flip ); if ( slp == nullptr ) continue; @@ -1205,7 +1218,7 @@ int FeaturePart::createCurvedCandidatesAlongLine( QList< LabelPosition* >& lPos, { delete slp; orientation = -orientation; - slp = curvedPlacementAtOffset( mapShape, path_distances, orientation, 1, i * delta, reversed, flip ); + slp = curvedPlacementAtOffset( mapShape, path_distances, orientation, 1, i, reversed, flip ); } } if ( slp == nullptr ) @@ -1236,7 +1249,7 @@ int FeaturePart::createCurvedCandidatesAlongLine( QList< LabelPosition* >& lPos, if ( cost < 0.0001 ) cost = 0.0001; // penalize positions which are further from the line's midpoint - double labelCenter = ( i * delta ) + getLabelWidth() / 2; + double labelCenter = i + getLabelWidth() / 2; double costCenter = qAbs( total_distance / 2 - labelCenter ) / total_distance; // <0, 0.5> cost += costCenter / 1000; // < 0, 0.0005 > slp->setCost( cost ); @@ -1753,7 +1766,7 @@ bool FeaturePart::showUprightLabels() const return uprightLabel; } -bool FeaturePart::nextCharPosition( int charWidth, double segment_length, PointSet* path_positions, int& index, double& distance, +bool FeaturePart::nextCharPosition( double charWidth, double segment_length, PointSet* path_positions, int& index, double& distance, double& start_x, double& start_y, double& end_x, double& end_y ) const { // Coordinates this character will start at diff --git a/src/core/pal/feature.h b/src/core/pal/feature.h index a58abee1554a..5df362e73a44 100644 --- a/src/core/pal/feature.h +++ b/src/core/pal/feature.h @@ -271,7 +271,7 @@ namespace pal bool showUprightLabels() const; //! Returns true if the next char position is found. The referenced parameters are updated. - bool nextCharPosition( int charWidth, double segment_length, PointSet* path_positions, int& index, double& distance, + bool nextCharPosition( double charWidth, double segment_length, PointSet* path_positions, int& index, double& distance, double& start_x, double& start_y, double& end_x, double& end_y ) const; protected: From 2c92152c7d10b76226abff0776397972c1016206 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Fri, 7 Oct 2016 09:48:35 +0200 Subject: [PATCH 201/897] debian packaging: run tests with ninja too (followup b4f3126) --- debian/rules | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/debian/rules b/debian/rules index cd4d482298c8..3af8146ba98f 100755 --- a/debian/rules +++ b/debian/rules @@ -43,9 +43,9 @@ endif DEB_BUILD_NAME ?= $(DISTRIBUTION)-$(DEB_BUILD_ARCH) ifeq (,$(DISPLAY)) -TESTMAKE=xvfb-run -a -n 1 -s "-screen 0 1280x1024x24 -dpi 96" $(MAKE) +TESTMAKE=xvfb-run -a -n 1 -s "-screen 0 1280x1024x24 -dpi 96" ninja else -TESTMAKE=$(MAKE) +TESTMAKE=ninja endif QGIS_MAJOR=$(shell sed -ne 's/SET(CPACK_PACKAGE_VERSION_MAJOR "\([0-9]*\)")/\1/p' CMakeLists.txt) From 6db9a371724a403700632f02f2efd786e5d5da6d Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Fri, 7 Oct 2016 11:23:55 +0200 Subject: [PATCH 202/897] osgeo4w: use package name in build directory (cherry picked from commit 706431e31d6f0a288856ceeff39d7ce432c20633) --- ms-windows/osgeo4w/package-nightly.cmd | 2 +- ms-windows/osgeo4w/package.cmd | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ms-windows/osgeo4w/package-nightly.cmd b/ms-windows/osgeo4w/package-nightly.cmd index 92417b6aad2d..119d13a9e62e 100644 --- a/ms-windows/osgeo4w/package-nightly.cmd +++ b/ms-windows/osgeo4w/package-nightly.cmd @@ -29,7 +29,7 @@ if "%ARCH%"=="" goto usage if not "%SHA%"=="" set SHA=-%SHA% if "%SITE%"=="" set SITE=qgis.org -set BUILDDIR=%CD%\build-nightly-%ARCH% +set BUILDDIR=%CD%\build-%PACKAGE%-%ARCH% if "%OSGEO4W_ROOT%"=="" ( if "%ARCH%"=="x86" ( diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index 091158482842..b42d7ad83daf 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -29,7 +29,7 @@ if "%ARCH%"=="" goto usage if not "%SHA%"=="" set SHA=-%SHA% if "%SITE%"=="" set SITE=qgis.org -set BUILDDIR=%CD%\build-%ARCH% +set BUILDDIR=%CD%\build-%PACKAGE%-%ARCH% if "%OSGEO4W_ROOT%"=="" ( if "%ARCH%"=="x86" ( From 3a906a188cf2f238003a15f56b0b5177dcf87a2c Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Fri, 7 Oct 2016 12:14:52 +0200 Subject: [PATCH 203/897] [OGR provider] Force REPACK at the first edit action. In the case where we deal with a shapefile, it is possible that it has pre-existing holes in the DBF (see #15407), so if using a GDAL version recent enough (>=2.1.2) to have reliable packing, do a packing at the first edit action. Fixes #15407 --- src/providers/ogr/qgsogrprovider.cpp | 12 ++++++ tests/src/python/test_provider_shapefile.py | 44 +++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 14c554247d1f..2d10ec9c99e6 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -3365,6 +3365,18 @@ void QgsOgrProvider::open( OpenMode mode ) ogrLayer = ogrOrigLayer = nullptr; mValid = false; +#if defined(GDAL_COMPUTE_VERSION) + // In the case where we deal with a shapefile, it is possible that it has + // pre-existing holes in the DBF (see #15407), so if using a GDAL version + // recent enough to have reliable packing, do a packing at the first edit + // action. + if ( ogrDriverName == "ESRI Shapefile" && + atoi( GDALVersionInfo( "VERSION_NUM" ) ) >= GDAL_COMPUTE_VERSION( 2, 1, 2 ) ) + { + mShapefileMayBeCorrupted = true; + } +#endif + ogrDataSource = QgsOgrProviderUtils::OGROpenWrapper( TO8F( mFilePath ), false, &ogrDriver ); mWriteAccess = false; diff --git a/tests/src/python/test_provider_shapefile.py b/tests/src/python/test_provider_shapefile.py index 1830f08388e9..040ed5427107 100644 --- a/tests/src/python/test_provider_shapefile.py +++ b/tests/src/python/test_provider_shapefile.py @@ -437,5 +437,49 @@ def testRepackUnderFileLocks(self): self.assertTrue(ds.GetLayer(0).GetFeatureCount(), feature_count - 1) ds = None + def testRepackAtFirstSave(self): + ''' Test fix for #15407 ''' + + # This requires a GDAL fix done per https://trac.osgeo.org/gdal/ticket/6672 + # but on non-Windows version the test would succeed + if int(osgeo.gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 1, 2): + return + + tmpdir = tempfile.mkdtemp() + self.dirs_to_cleanup.append(tmpdir) + srcpath = os.path.join(TEST_DATA_DIR, 'provider') + for file in glob.glob(os.path.join(srcpath, 'shapefile.*')): + shutil.copy(os.path.join(srcpath, file), tmpdir) + datasource = os.path.join(tmpdir, 'shapefile.shp') + + ds = osgeo.ogr.Open(datasource) + lyr = ds.GetLayer(0) + original_feature_count = lyr.GetFeatureCount() + lyr.DeleteFeature(2) + ds = None + + vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') + + self.assertTrue(vl.featureCount(), original_feature_count) + + # Edit a feature (attribute change only) + self.assertTrue(vl.startEditing()) + self.assertTrue(vl.dataProvider().changeAttributeValues({0: {0: 100}})) + + # Commit changes and check no error is emitted + cbk = ErrorReceiver() + vl.dataProvider().raiseError.connect(cbk.receiveError) + self.assertTrue(vl.commitChanges()) + self.assertIsNone(cbk.msg) + + self.assertTrue(vl.featureCount(), original_feature_count - 1) + + vl = None + + # Test repacking has been done + ds = osgeo.ogr.Open(datasource) + self.assertTrue(ds.GetLayer(0).GetFeatureCount(), original_feature_count - 1) + ds = None + if __name__ == '__main__': unittest.main() From a5a18c2eb1677b6d27b45adff0cb296c5677dd7b Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Fri, 7 Oct 2016 13:42:05 +0200 Subject: [PATCH 204/897] [OGR provider] Make feature iterator work on GeometryCollection sublayers When trying to reproduce http://hub.qgis.org/issues/10485, I noticed a regression. Now attribute table no longer shows features with OGR GeometryCollection. Fixes also issues where sublayer geometry type is too strict regarding 2D vs 2.5D geometry types. Fixes #15675 --- src/providers/ogr/qgsogrfeatureiterator.cpp | 12 +++++++++--- src/providers/ogr/qgsogrprovider.cpp | 5 ++++- tests/src/python/test_provider_ogr.py | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index a41304750b87..a5f7ac5cd328 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -311,8 +311,13 @@ bool QgsOgrFeatureIterator::readFeature( OGRFeatureH fet, QgsFeature& feature ) else feature.clearGeometry(); - if (( useIntersect && ( !feature.hasGeometry() || !feature.geometry().intersects( mRequest.filterRect() ) ) ) - || ( geometryTypeFilter && ( !feature.hasGeometry() || QgsOgrProvider::ogrWkbSingleFlatten(( OGRwkbGeometryType )feature.geometry().wkbType() ) != mSource->mOgrGeometryTypeFilter ) ) ) + if ( mSource->mOgrGeometryTypeFilter == wkbGeometryCollection && + geom && wkbFlatten( OGR_G_GetGeometryType( geom ) ) == wkbGeometryCollection ) + { + // OK + } + else if (( useIntersect && ( !feature.hasGeometry() || !feature.geometry().intersects( mRequest.filterRect() ) ) ) + || ( geometryTypeFilter && ( !feature.hasGeometry() || QgsOgrProvider::ogrWkbSingleFlatten(( OGRwkbGeometryType )feature.geometry().wkbType() ) != mSource->mOgrGeometryTypeFilter ) ) ) { OGR_F_Destroy( fet ); return false; @@ -359,7 +364,8 @@ QgsOgrFeatureSource::QgsOgrFeatureSource( const QgsOgrProvider* p ) mFieldsWithoutFid.append( mFields.at( i ) ); mDriverName = p->ogrDriverName; mFirstFieldIsFid = p->mFirstFieldIsFid; - mOgrGeometryTypeFilter = wkbFlatten( p->mOgrGeometryTypeFilter ); + mOgrGeometryTypeFilter = QgsOgrProvider::ogrWkbSingleFlatten( p->mOgrGeometryTypeFilter ); + QgsDebugMsg( QString( "mOgrGeometryTypeFilter: %1" ).arg( mOgrGeometryTypeFilter ) ); QgsOgrConnPool::instance()->ref( mDataSource ); } diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 2d10ec9c99e6..f7a3d5c03a3d 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -3155,13 +3155,16 @@ void QgsOgrProvider::recalculateFeatureCount() setRelevantFields( ogrLayer, true, QgsAttributeList() ); OGR_L_ResetReading( ogrLayer ); OGRFeatureH fet; + const OGRwkbGeometryType flattenGeomTypeFilter = + QgsOgrProvider::ogrWkbSingleFlatten( mOgrGeometryTypeFilter ); while (( fet = OGR_L_GetNextFeature( ogrLayer ) ) ) { OGRGeometryH geom = OGR_F_GetGeometryRef( fet ); if ( geom ) { OGRwkbGeometryType gType = OGR_G_GetGeometryType( geom ); - if ( gType == mOgrGeometryTypeFilter ) mFeaturesCounted++; + gType = QgsOgrProvider::ogrWkbSingleFlatten( gType ); + if ( gType == flattenGeomTypeFilter ) mFeaturesCounted++; } OGR_F_Destroy( fet ); } diff --git a/tests/src/python/test_provider_ogr.py b/tests/src/python/test_provider_ogr.py index e9d4e3b341b6..aebfcbcd994a 100644 --- a/tests/src/python/test_provider_ogr.py +++ b/tests/src/python/test_provider_ogr.py @@ -221,5 +221,24 @@ def testNoDanglingFileDescriptorAfterCloseVariant2(self): os.unlink(datasource) self.assertFalse(os.path.exists(datasource)) + def testGeometryCollection(self): + ''' Test that we can at least retrieves attribute of features with geometry collection ''' + + datasource = os.path.join(self.basetestpath, 'testGeometryCollection.csv') + with open(datasource, 'wt') as f: + f.write('id,WKT\n') + f.write('1,POINT Z(2 49 0)\n') + f.write('2,GEOMETRYCOLLECTION Z (POINT Z (2 49 0))\n') + + vl = QgsVectorLayer('{}|layerid=0|geometrytype=GeometryCollection'.format(datasource), 'test', 'ogr') + self.assertTrue(vl.isValid()) + self.assertTrue(vl.featureCount(), 1) + values = [f['id'] for f in vl.getFeatures()] + self.assertEqual(values, ['2']) + del vl + + os.unlink(datasource) + self.assertFalse(os.path.exists(datasource)) + if __name__ == '__main__': unittest.main() From ccb8b0f9249f3d2aeba0fa4290e00cdf6576ae9b Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Fri, 7 Oct 2016 14:01:45 +0200 Subject: [PATCH 205/897] Remove useless debug trace --- src/providers/ogr/qgsogrfeatureiterator.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index a5f7ac5cd328..5e31dab1f625 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -365,7 +365,6 @@ QgsOgrFeatureSource::QgsOgrFeatureSource( const QgsOgrProvider* p ) mDriverName = p->ogrDriverName; mFirstFieldIsFid = p->mFirstFieldIsFid; mOgrGeometryTypeFilter = QgsOgrProvider::ogrWkbSingleFlatten( p->mOgrGeometryTypeFilter ); - QgsDebugMsg( QString( "mOgrGeometryTypeFilter: %1" ).arg( mOgrGeometryTypeFilter ) ); QgsOgrConnPool::instance()->ref( mDataSource ); } From f971b0dbd16edd857cd76cc09fe7a08ac0b03cbe Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Fri, 7 Oct 2016 15:22:41 +0200 Subject: [PATCH 206/897] osgeo4w: really use package name (fixes 6db9a371) --- ms-windows/osgeo4w/package-nightly.cmd | 2 +- ms-windows/osgeo4w/package.cmd | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ms-windows/osgeo4w/package-nightly.cmd b/ms-windows/osgeo4w/package-nightly.cmd index 119d13a9e62e..042b7703ef5a 100644 --- a/ms-windows/osgeo4w/package-nightly.cmd +++ b/ms-windows/osgeo4w/package-nightly.cmd @@ -29,7 +29,7 @@ if "%ARCH%"=="" goto usage if not "%SHA%"=="" set SHA=-%SHA% if "%SITE%"=="" set SITE=qgis.org -set BUILDDIR=%CD%\build-%PACKAGE%-%ARCH% +set BUILDDIR=%CD%\build-%PACKAGENAME%-%ARCH% if "%OSGEO4W_ROOT%"=="" ( if "%ARCH%"=="x86" ( diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index b42d7ad83daf..7d02cbb05189 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -29,7 +29,7 @@ if "%ARCH%"=="" goto usage if not "%SHA%"=="" set SHA=-%SHA% if "%SITE%"=="" set SITE=qgis.org -set BUILDDIR=%CD%\build-%PACKAGE%-%ARCH% +set BUILDDIR=%CD%\build-%PACKAGENAME%-%ARCH% if "%OSGEO4W_ROOT%"=="" ( if "%ARCH%"=="x86" ( From 1df9d7e1a60b3e6c913fae1414a6b397a1dc6aae Mon Sep 17 00:00:00 2001 From: rldhont Date: Fri, 7 Oct 2016 15:17:46 +0200 Subject: [PATCH 207/897] [BUGFIX][QGIS Server] Joins was not reloaded if the layer is in cache With the commit f6aad8bad6db72d0b1e573998ac7dcb2405dce55, the QgsMapLayerRegistry signal `layersWillBeRemoved` is always emit. This imply that the vector layer join buffer is empty and not reloaded if the layer is in cache. To fix it, the layer XML element has to be read each time the layer is used. This commit fixed #15522 Qgis Server doesnt' respect the styling from Desktop --- src/server/qgsserverprojectparser.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 42c421fa0de1..50e5c0f6ddc0 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -28,6 +28,9 @@ #include "qgslayertreegroup.h" #include "qgslogger.h" +#include "qgslogger.h" +#include "qgsmessagelog.h" + #include #include #include @@ -234,8 +237,11 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& if ( !QgsMapLayerRegistry::instance()->mapLayer( id ) ) QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); if ( layer->type() == QgsMapLayer::VectorLayer ) + { addValueRelationLayersForLayer( dynamic_cast( layer ) ); - + // Reload joins and expression fields + layer->readLayerXML( const_cast( elem ) ); + } return layer; } @@ -1541,7 +1547,7 @@ void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerEl { QString id = joinNodeList.at( i ).toElement().attribute( "joinLayerId" ); QgsMapLayer* layer = mapLayerFromLayerId( id ); - if ( layer ) + if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id )) { QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); } From db1b52a249e7f5187e5ec2462bdf88ca91c5c988 Mon Sep 17 00:00:00 2001 From: rldhont Date: Fri, 7 Oct 2016 15:48:10 +0200 Subject: [PATCH 208/897] fix typo 1df9d7e1a60b3e6c913fae1414a6b397a1dc6aae --- src/server/qgsserverprojectparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 50e5c0f6ddc0..43a3055415e8 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -1547,7 +1547,7 @@ void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerEl { QString id = joinNodeList.at( i ).toElement().attribute( "joinLayerId" ); QgsMapLayer* layer = mapLayerFromLayerId( id ); - if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id )) + if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id ) ) { QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); } From 9b757460037b1f69005153c4262dd23ac82ca124 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 12:09:18 +0300 Subject: [PATCH 209/897] [processing] remove obsolete import --- python/plugins/processing/tests/AlgorithmsTestBase.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/tests/AlgorithmsTestBase.py b/python/plugins/processing/tests/AlgorithmsTestBase.py index e31fb496c5b9..8152167b56ed 100644 --- a/python/plugins/processing/tests/AlgorithmsTestBase.py +++ b/python/plugins/processing/tests/AlgorithmsTestBase.py @@ -16,10 +16,6 @@ * * *************************************************************************** """ -from __future__ import print_function -from builtins import zip -from builtins import str -from builtins import object __author__ = 'Matthias Kuhn' __date__ = 'January 2016' @@ -29,7 +25,13 @@ __revision__ = ':%H$' +from __future__ import print_function +from builtins import zip +from builtins import str +from builtins import object + import qgis # NOQA switch sip api + import os import yaml import nose2 @@ -42,7 +44,6 @@ import processing from processing.modeler.ModelerAlgorithmProvider import ModelerAlgorithmProvider -from processing.modeler.ModelerOnlyAlgorithmProvider import ModelerOnlyAlgorithmProvider from processing.algs.qgis.QGISAlgorithmProvider import QGISAlgorithmProvider from processing.algs.grass.GrassAlgorithmProvider import GrassAlgorithmProvider from processing.algs.grass7.Grass7AlgorithmProvider import Grass7AlgorithmProvider From 8648bd12f39e17e3e656101e5b12a13b170e59c5 Mon Sep 17 00:00:00 2001 From: rldhont Date: Fri, 7 Oct 2016 19:28:51 +0200 Subject: [PATCH 210/897] Fix QGIS server for PyQgsServerAccessControl --- src/server/qgsserverprojectparser.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 43a3055415e8..fc10b19394c5 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -240,7 +240,10 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& { addValueRelationLayersForLayer( dynamic_cast( layer ) ); // Reload joins and expression fields + QgsVectorLayer* vlayer = dynamic_cast( layer ); + QString subsetString = vlayer->subsetString(); layer->readLayerXML( const_cast( elem ) ); + vlayer->setSubsetString( subsetString ); } return layer; } From a8d08891ce9a9b7add36955261cf402202a54e80 Mon Sep 17 00:00:00 2001 From: Piotr Pociask Date: Sat, 8 Oct 2016 19:43:37 +0200 Subject: [PATCH 211/897] Fix VSIUnlink in QgsOgrUtils::stringToFeatureList --- src/core/qgsogrutils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsogrutils.cpp b/src/core/qgsogrutils.cpp index a1833aa17413..3f1da65e0bef 100644 --- a/src/core/qgsogrutils.cpp +++ b/src/core/qgsogrutils.cpp @@ -274,7 +274,7 @@ QgsFeatureList QgsOgrUtils::stringToFeatureList( const QString& string, const Qg } OGR_DS_Destroy( hDS ); - VSIUnlink( "/vsimem/clipboard.dat" ); + VSIUnlink( TO8( randomFileName ) ); return features; } From 3b9316dae919a3debd31440eab18b51116cf478d Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 8 Oct 2016 22:51:31 +0200 Subject: [PATCH 212/897] fix 1df9d7e --- src/server/qgsserverprojectparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index fc10b19394c5..1197cf1085ad 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -242,7 +242,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& // Reload joins and expression fields QgsVectorLayer* vlayer = dynamic_cast( layer ); QString subsetString = vlayer->subsetString(); - layer->readLayerXML( const_cast( elem ) ); + layer->readLayerXml( const_cast( elem ) ); vlayer->setSubsetString( subsetString ); } return layer; From 3a76708bcb4785f5fe930be0b18396e5fa87031f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 9 Oct 2016 08:56:50 +1000 Subject: [PATCH 213/897] Fix renaming a virtual field leads to crash (fix #15669) --- python/core/qgsexpressionfieldbuffer.sip | 10 +++++++ src/core/qgsexpressionfieldbuffer.cpp | 5 ++++ src/core/qgsexpressionfieldbuffer.h | 10 +++++++ src/core/qgsvectorlayer.cpp | 35 ++++++++++++++++++++++-- tests/src/python/test_qgsvectorlayer.py | 10 +++++++ 5 files changed, 68 insertions(+), 2 deletions(-) diff --git a/python/core/qgsexpressionfieldbuffer.sip b/python/core/qgsexpressionfieldbuffer.sip index dfa3aee5e8fb..8bceb4a67db4 100644 --- a/python/core/qgsexpressionfieldbuffer.sip +++ b/python/core/qgsexpressionfieldbuffer.sip @@ -27,6 +27,16 @@ class QgsExpressionFieldBuffer */ void removeExpression( int index ); + /** + * Renames an expression field at a given index + * + * @param index The index of the expression to change + * @param name New name for field + * + * @note added in 3.0 + */ + void renameExpression( int index, const QString& name ); + /** * Changes the expression at a given index * diff --git a/src/core/qgsexpressionfieldbuffer.cpp b/src/core/qgsexpressionfieldbuffer.cpp index 84766c79ad9b..9b73009998e0 100644 --- a/src/core/qgsexpressionfieldbuffer.cpp +++ b/src/core/qgsexpressionfieldbuffer.cpp @@ -33,6 +33,11 @@ void QgsExpressionFieldBuffer::removeExpression( int index ) mExpressions.removeAt( index ); } +void QgsExpressionFieldBuffer::renameExpression( int index, const QString& name ) +{ + mExpressions[index].field.setName( name ); +} + void QgsExpressionFieldBuffer::updateExpression( int index, const QString& exp ) { mExpressions[index].cachedExpression = QgsExpression( exp ); diff --git a/src/core/qgsexpressionfieldbuffer.h b/src/core/qgsexpressionfieldbuffer.h index 6ac2d46a4195..b73c4bd5f377 100644 --- a/src/core/qgsexpressionfieldbuffer.h +++ b/src/core/qgsexpressionfieldbuffer.h @@ -61,6 +61,16 @@ class CORE_EXPORT QgsExpressionFieldBuffer */ void removeExpression( int index ); + /** + * Renames an expression field at a given index + * + * @param index The index of the expression to change + * @param name New name for field + * + * @note added in 3.0 + */ + void renameExpression( int index, const QString& name ); + /** * Changes the expression at a given index * diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 799b3809e6a5..23c0cabfb07b 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -2125,10 +2125,41 @@ void QgsVectorLayer::removeFieldAlias( int attIndex ) bool QgsVectorLayer::renameAttribute( int index, const QString& newName ) { - if ( !mEditBuffer || !mDataProvider ) + if ( index < 0 || index >= fields().count() ) return false; - return mEditBuffer->renameAttribute( index, newName ); + switch ( mFields.fieldOrigin( index ) ) + { + case QgsFields::OriginExpression: + { + if ( mExpressionFieldBuffer ) + { + int oi = mFields.fieldOriginIndex( index ); + mExpressionFieldBuffer->renameExpression( oi, newName ); + updateFields(); + return true; + } + else + { + return false; + } + } + + case QgsFields::OriginProvider: + case QgsFields::OriginEdit: + + if ( !mEditBuffer || !mDataProvider ) + return false; + + return mEditBuffer->renameAttribute( index, newName ); + + case QgsFields::OriginJoin: + case QgsFields::OriginUnknown: + return false; + + } + + return false; // avoid warning } void QgsVectorLayer::setFieldAlias( int attIndex, const QString& aliasString ) diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 8bee7f37e0d4..f289b7617438 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1058,6 +1058,16 @@ def checkFieldNames(names): #layer.undoStack().redo() #checkFieldNames(['fldint']) + def test_RenameExpressionField(self): + layer = createLayerWithOnePoint() + exp_field_idx = layer.addExpressionField('1+1', QgsField('math_is_hard', QVariant.Int)) + + #rename and check + self.assertTrue(layer.renameAttribute(exp_field_idx, 'renamed')) + self.assertEqual(layer.fields()[exp_field_idx].name(), 'renamed') + f = next(layer.getFeatures()) + self.assertEqual(f.fields()[exp_field_idx].name(), 'renamed') + def test_fields(self): layer = createLayerWithOnePoint() From 22af5bf5d42aa43d135e00be60cd7b43501d7599 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sun, 9 Oct 2016 01:46:22 +0200 Subject: [PATCH 214/897] fix typos --- resources/context_help/HeatmapGui | 2 +- src/app/gps/qwtpolar-0.1/qwt_polar_plot.cpp | 2 +- src/app/gps/qwtpolar-1.0/qwt_polar_plot.cpp | 2 +- src/app/gps/qwtpolar-1.1.1/qwt_polar_plot.cpp | 2 +- src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h | 2 +- src/providers/gdal/qgsgdalprovider.cpp | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/resources/context_help/HeatmapGui b/resources/context_help/HeatmapGui index e722f10e928b..612d8d28347f 100644 --- a/resources/context_help/HeatmapGui +++ b/resources/context_help/HeatmapGui @@ -26,7 +26,7 @@ clustering of points.

                                                                                                                                                                                    Rows and Columns

                                                                                                                                                                                    Used to change the dimensions of the output raster file. These values are also linked to the Cell size X and Cell size Y values. -Increasing the number of rows or colums will decrease the cell size and increase the file size of the output file. The values in Rows and Columns +Increasing the number of rows or columns will decrease the cell size and increase the file size of the output file. The values in Rows and Columns are also linked, so doubling the number of rows will automatically double the number of columns and the cell sizes will also be halved. The geographical area of the output raster will remain the same!

                                                                                                                                                                                    Cell size X and Y

                                                                                                                                                                                    diff --git a/src/app/gps/qwtpolar-0.1/qwt_polar_plot.cpp b/src/app/gps/qwtpolar-0.1/qwt_polar_plot.cpp index 623d6ac74801..b2af0cc441e7 100644 --- a/src/app/gps/qwtpolar-0.1/qwt_polar_plot.cpp +++ b/src/app/gps/qwtpolar-0.1/qwt_polar_plot.cpp @@ -186,7 +186,7 @@ const QwtTextLabel *QwtPolarPlot::titleLabel() const \param legend Legend \param pos The legend's position. For top/left position the number - of colums will be limited to 1, otherwise it will be set to + of columns will be limited to 1, otherwise it will be set to unlimited. \param ratio Ratio between legend and the bounding rect diff --git a/src/app/gps/qwtpolar-1.0/qwt_polar_plot.cpp b/src/app/gps/qwtpolar-1.0/qwt_polar_plot.cpp index aa6c40412900..add40f7f02f6 100644 --- a/src/app/gps/qwtpolar-1.0/qwt_polar_plot.cpp +++ b/src/app/gps/qwtpolar-1.0/qwt_polar_plot.cpp @@ -167,7 +167,7 @@ const QwtTextLabel *QwtPolarPlot::titleLabel() const \param legend Legend \param pos The legend's position. For top/left position the number - of colums will be limited to 1, otherwise it will be set to + of columns will be limited to 1, otherwise it will be set to unlimited. \param ratio Ratio between legend and the bounding rect diff --git a/src/app/gps/qwtpolar-1.1.1/qwt_polar_plot.cpp b/src/app/gps/qwtpolar-1.1.1/qwt_polar_plot.cpp index 09cc5403505b..b1b8b53dab55 100644 --- a/src/app/gps/qwtpolar-1.1.1/qwt_polar_plot.cpp +++ b/src/app/gps/qwtpolar-1.1.1/qwt_polar_plot.cpp @@ -171,7 +171,7 @@ const QwtTextLabel *QwtPolarPlot::titleLabel() const \param legend Legend \param pos The legend's position. For top/left position the number - of colums will be limited to 1, otherwise it will be set to + of columns will be limited to 1, otherwise it will be set to unlimited. \param ratio Ratio between legend and the bounding rect diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h index dd2432d713fe..654195b46a2c 100644 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h +++ b/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h @@ -697,7 +697,7 @@ struct DXFLIB_EXPORT DL_InsertData { double sz; /*! Rotation angle in degrees. */ double angle; - /*! Number of colums if we insert an array of the block or 1. */ + /*! Number of columns if we insert an array of the block or 1. */ int cols; /*! Number of rows if we insert an array of the block or 1. */ int rows; diff --git a/src/providers/gdal/qgsgdalprovider.cpp b/src/providers/gdal/qgsgdalprovider.cpp index 53a3f31bc09b..f22dba4ab841 100644 --- a/src/providers/gdal/qgsgdalprovider.cpp +++ b/src/providers/gdal/qgsgdalprovider.cpp @@ -600,7 +600,7 @@ void QgsGdalProvider::readBlock( int theBandNo, QgsRectangle const & theExtent, char *tmpBlock = ( char * )qgsMalloc( dataSize * tmpWidth * tmpHeight ); if ( ! tmpBlock ) { - QgsDebugMsg( QString( "Coudn't allocate temporary buffer of %1 bytes" ).arg( dataSize * tmpWidth * tmpHeight ) ); + QgsDebugMsg( QString( "Couldn't allocate temporary buffer of %1 bytes" ).arg( dataSize * tmpWidth * tmpHeight ) ); return; } GDALRasterBandH gdalBand = GDALGetRasterBand( mGdalDataset, theBandNo ); From 8d690fa4f652d6c4f8ad408e77b24328fa6549e5 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 9 Oct 2016 18:10:25 +1000 Subject: [PATCH 215/897] [composer] Use inline panels for grid and overview symbol style selectors --- src/app/composer/qgscomposermapwidget.cpp | 171 +++++++++++++++----- src/app/composer/qgscomposermapwidget.h | 7 + src/app/composer/qgscomposershapewidget.cpp | 4 +- 3 files changed, 140 insertions(+), 42 deletions(-) diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index 5e9ec828e1d3..82d1569c16c1 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -292,6 +292,99 @@ void QgsComposerMapWidget::onPresetsChanged() } } +void QgsComposerMapWidget::updateGridLineStyleFromWidget() +{ + QgsComposerMapGrid* grid = currentGrid(); + if ( !grid ) + { + return; + } + + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + grid->setLineSymbol( dynamic_cast< QgsLineSymbol* >( w->symbol()->clone() ) ); + mComposerMap->update(); +} + +void QgsComposerMapWidget::cleanUpGridLineStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + + QgsComposerMapGrid* grid = currentGrid(); + if ( !grid ) + { + return; + } + + updateGridLineSymbolMarker( grid ); + mComposerMap->endCommand(); +} + +void QgsComposerMapWidget::updateGridMarkerStyleFromWidget() +{ + QgsComposerMapGrid* grid = currentGrid(); + if ( !grid ) + { + return; + } + + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + grid->setMarkerSymbol( dynamic_cast< QgsMarkerSymbol* >( w->symbol()->clone() ) ); + mComposerMap->update(); +} + +void QgsComposerMapWidget::cleanUpGridMarkerStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + + QgsComposerMapGrid* grid = currentGrid(); + if ( !grid ) + { + return; + } + + updateGridMarkerSymbolMarker( grid ); + mComposerMap->endCommand(); +} + +void QgsComposerMapWidget::updateOverviewFrameStyleFromWidget() +{ + QgsComposerMapOverview* overview = currentOverview(); + if ( !overview ) + { + return; + } + + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + overview->setFrameSymbol( dynamic_cast< QgsFillSymbol* >( w->symbol()->clone() ) ); + mComposerMap->update(); +} + +void QgsComposerMapWidget::cleanUpOverviewFrameStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + + QgsComposerMapOverview* overview = currentOverview(); + if ( !overview ) + { + return; + } + + updateOverviewFrameSymbolMarker( overview ); + mComposerMap->endCommand(); +} + void QgsComposerMapWidget::on_mAtlasCheckBox_toggled( bool checked ) { if ( !mComposerMap ) @@ -1496,21 +1589,21 @@ void QgsComposerMapWidget::on_mGridLineStyleButton_clicked() return; } + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + QgsLineSymbol* newSymbol = static_cast( grid->lineSymbol()->clone() ); - QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), nullptr, this ); + QgsExpressionContext context = mComposerMap->createExpressionContext(); - if ( d.exec() == QDialog::Accepted ) - { - mComposerMap->beginCommand( tr( "Grid line style changed" ) ); - grid->setLineSymbol( newSymbol ); - updateGridLineSymbolMarker( grid ); - mComposerMap->endCommand(); - mComposerMap->update(); - } - else - { - delete newSymbol; - } + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d->setContext( symbolContext ); + + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateGridLineStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpGridLineStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerMap->beginCommand( tr( "Grid line style changed" ) ); } void QgsComposerMapWidget::on_mGridMarkerStyleButton_clicked() @@ -1521,21 +1614,21 @@ void QgsComposerMapWidget::on_mGridMarkerStyleButton_clicked() return; } + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + QgsMarkerSymbol* newSymbol = static_cast( grid->markerSymbol()->clone() ); - QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), nullptr, this ); + QgsExpressionContext context = mComposerMap->createExpressionContext(); - if ( d.exec() == QDialog::Accepted ) - { - mComposerMap->beginCommand( tr( "Grid markers style changed" ) ); - grid->setMarkerSymbol( newSymbol ); - updateGridMarkerSymbolMarker( grid ); - mComposerMap->endCommand(); - mComposerMap->update(); - } - else - { - delete newSymbol; - } + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d->setContext( symbolContext ); + + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateGridMarkerStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpGridMarkerStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerMap->beginCommand( tr( "Grid markers style changed" ) ); } void QgsComposerMapWidget::on_mIntervalXSpinBox_editingFinished() @@ -2463,21 +2556,21 @@ void QgsComposerMapWidget::on_mOverviewFrameStyleButton_clicked() return; } + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + QgsFillSymbol* newSymbol = static_cast( overview->frameSymbol()->clone() ); - QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), nullptr, this ); + QgsExpressionContext context = mComposerMap->createExpressionContext(); - if ( d.exec() == QDialog::Accepted ) - { - mComposerMap->beginCommand( tr( "Overview frame style changed" ) ); - overview->setFrameSymbol( newSymbol ); - updateOverviewFrameSymbolMarker( overview ); - mComposerMap->endCommand(); - mComposerMap->update(); - } - else - { - delete newSymbol; - } + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d->setContext( symbolContext ); + + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateOverviewFrameStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpOverviewFrameStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerMap->beginCommand( tr( "Overview frame style changed" ) ); } void QgsComposerMapWidget::on_mOverviewBlendModeComboBox_currentIndexChanged( int index ) diff --git a/src/app/composer/qgscomposermapwidget.h b/src/app/composer/qgscomposermapwidget.h index a02a16c32324..727bc4cb347e 100644 --- a/src/app/composer/qgscomposermapwidget.h +++ b/src/app/composer/qgscomposermapwidget.h @@ -174,6 +174,13 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void onPresetsChanged(); + void updateGridLineStyleFromWidget(); + void cleanUpGridLineStyleSelector( QgsPanelWidget* container ); + void updateGridMarkerStyleFromWidget(); + void cleanUpGridMarkerStyleSelector( QgsPanelWidget* container ); + void updateOverviewFrameStyleFromWidget(); + void cleanUpOverviewFrameStyleSelector( QgsPanelWidget* container ); + private: QgsComposerMap* mComposerMap; diff --git a/src/app/composer/qgscomposershapewidget.cpp b/src/app/composer/qgscomposershapewidget.cpp index 8e736c2ba465..b076b14cff42 100644 --- a/src/app/composer/qgscomposershapewidget.cpp +++ b/src/app/composer/qgscomposershapewidget.cpp @@ -32,7 +32,7 @@ QgsComposerShapeWidget::QgsComposerShapeWidget( QgsComposerShape* composerShape //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, composerShape ); - //shapes don't use background or frame, since the symbol style is set through a QgsSymbolSelectorDialog + //shapes don't use background or frame, since the symbol style is set through a QgsSymbolSelectorWidget itemPropertiesWidget->showBackgroundGroup( false ); itemPropertiesWidget->showFrameGroup( false ); @@ -111,8 +111,6 @@ void QgsComposerShapeWidget::on_mShapeStyleButton_clicked() QgsFillSymbol* newSymbol = mComposerShape->shapeStyleSymbol()->clone(); QgsExpressionContext context = mComposerShape->createExpressionContext(); - - QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); QgsSymbolWidgetContext symbolContext; symbolContext.setExpressionContext( &context ); From b51e3c7ca668cd9d58f9f676baff1af0bdc966ee Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Mon, 10 Oct 2016 00:44:02 +0200 Subject: [PATCH 216/897] fix warning (cherry picked from commit cd3adc077eda76f1503ed7d4e29b1b2e41218d47) --- src/core/qgsprojectproperty.cpp | 12 ++++++++++++ src/core/qgsprojectproperty.h | 12 ++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/core/qgsprojectproperty.cpp b/src/core/qgsprojectproperty.cpp index df756ceb406c..221edea3d9fd 100644 --- a/src/core/qgsprojectproperty.cpp +++ b/src/core/qgsprojectproperty.cpp @@ -21,6 +21,18 @@ #include #include +QgsProperty::QgsProperty() +{ +} + +QgsProperty::~QgsProperty() +{ +} + +QgsPropertyValue::~QgsPropertyValue() +{ +} + void QgsPropertyValue::dump( int tabs ) const { QString tabString; diff --git a/src/core/qgsprojectproperty.h b/src/core/qgsprojectproperty.h index 0a4b6e8b4d44..8eae560b0fe0 100644 --- a/src/core/qgsprojectproperty.h +++ b/src/core/qgsprojectproperty.h @@ -47,12 +47,8 @@ class QDomDocument; class CORE_EXPORT QgsProperty { public: - - QgsProperty() - {} - - virtual ~QgsProperty() - {} + QgsProperty(); + virtual ~QgsProperty(); /** Dumps out the keys and values * @@ -125,7 +121,7 @@ class CORE_EXPORT QgsPropertyValue : public QgsProperty : value_( value ) {} - virtual ~QgsPropertyValue() {} + virtual ~QgsPropertyValue(); /** Returns true if is a QgsPropertyKey */ virtual bool isKey() const override { return false; } @@ -208,7 +204,7 @@ class CORE_EXPORT QgsPropertyKey : public QgsProperty /// add the given property key - QgsPropertyKey * addKey( const QString & keyName ) + QgsPropertyKey *addKey( const QString & keyName ) { delete mProperties.take( keyName ); mProperties.insert( keyName, new QgsPropertyKey( keyName ) ); From 3b1dfa7071f7ddd9b2164b0d795141612a93d302 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 10 Oct 2016 08:00:42 +0200 Subject: [PATCH 217/897] [processing] made -te parameter optional in gdal warp --- python/plugins/processing/algs/gdal/warp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/gdal/warp.py b/python/plugins/processing/algs/gdal/warp.py index e729d19af85c..7040e11da99e 100644 --- a/python/plugins/processing/algs/gdal/warp.py +++ b/python/plugins/processing/algs/gdal/warp.py @@ -88,7 +88,7 @@ def defineCharacteristics(self): 0.0, None, 0.0)) self.addParameter(ParameterSelection(self.METHOD, self.tr('Resampling method'), self.METHOD_OPTIONS)) - self.addParameter(ParameterExtent(self.RAST_EXT, self.tr('Raster extent'))) + self.addParameter(ParameterExtent(self.RAST_EXT, self.tr('Raster extent'), optional=True)) if GdalUtils.version() >= 2000000: self.addParameter(ParameterCrs(self.EXT_CRS, From 0c4bf943c141ff88519ee7e2474d828230c84272 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 10 Oct 2016 12:27:11 +1000 Subject: [PATCH 218/897] Allow expression functions to appear in multiple groups (fix #15682) Now functions which make sense for multiple contexts (eg length, to_date) can appear in more than one group. --- python/core/qgsexpression.sip | 43 +++++++++++- src/core/qgsexpression.cpp | 22 +++---- src/core/qgsexpression.h | 90 ++++++++++++++++++++++++-- src/gui/qgsexpressionbuilderwidget.cpp | 14 +++- src/gui/qgsexpressionbuilderwidget.h | 14 ++++ 5 files changed, 163 insertions(+), 20 deletions(-) diff --git a/python/core/qgsexpression.sip b/python/core/qgsexpression.sip index f4dc271ecd86..0df7bff7ec7d 100644 --- a/python/core/qgsexpression.sip +++ b/python/core/qgsexpression.sip @@ -306,6 +306,19 @@ class QgsExpression bool handlesNull = false, bool isContextual = false ); + /** Constructor for function which uses unnamed parameters and group list + * @note added in QGIS 3.0 + */ + Function( const QString& fnname, + int params, + const QStringList& groups, + const QString& helpText = QString(), + bool usesGeometry = false, + const QSet& referencedColumns = QSet(), + bool lazyEval = false, + bool handlesNull = false, + bool isContextual = false ); + /** Constructor for function which uses named parameter list. * @note added in QGIS 2.16 */ @@ -319,6 +332,19 @@ class QgsExpression bool handlesNull = false, bool isContextual = false ); + /** Constructor for function which uses named parameter list and group list. + * @note added in QGIS 3.0 + */ + Function( const QString& fnname, + const QgsExpression::ParameterList& params, + const QStringList& groups, + const QString& helpText = QString(), + bool usesGeometry = false, + const QSet& referencedColumns = QSet(), + bool lazyEval = false, + bool handlesNull = false, + bool isContextual = false ); + virtual ~Function(); /** The name of the function. */ @@ -357,8 +383,23 @@ class QgsExpression */ bool isContextual() const; - /** The group the function belongs to. */ + /** Returns true if the function is deprecated and should not be presented as a valid option + * to users in expression builders. + * @note added in QGIS 3.0 + */ + virtual bool isDeprecated() const; + + /** Returns the first group which the function belongs to. + * @note consider using groups() instead, as some functions naturally belong in multiple groups + */ QString group() const; + + /** Returns a list of the groups the function belongs to. + * @note added in QGIS 3.0 + * @see group() + */ + QStringList groups() const; + /** The help text for the function. */ const QString helpText() const; diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 36f6133753a9..d6516a202d38 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3403,7 +3403,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( "sqrt", ParameterList() << Parameter( "value" ), fcnSqrt, "Math" ) << new StaticFunction( "radians", ParameterList() << Parameter( "degrees" ), fcnRadians, "Math" ) << new StaticFunction( "degrees", ParameterList() << Parameter( "radians" ), fcnDegrees, "Math" ) - << new StaticFunction( "azimuth", ParameterList() << Parameter( "point_a" ) << Parameter( "point_b" ), fcnAzimuth, "Math" ) + << new StaticFunction( "azimuth", ParameterList() << Parameter( "point_a" ) << Parameter( "point_b" ), fcnAzimuth, QStringList() << "Math" << "GeometryGroup" ) << new StaticFunction( "project", ParameterList() << Parameter( "point" ) << Parameter( "distance" ) << Parameter( "bearing" ), fcnProject, "GeometryGroup" ) << new StaticFunction( "abs", ParameterList() << Parameter( "value" ), fcnAbs, "Math" ) << new StaticFunction( "cos", ParameterList() << Parameter( "angle" ), fcnCos, "Math" ) @@ -3428,13 +3428,13 @@ const QList& QgsExpression::Functions() << new StaticFunction( "floor", 1, fcnFloor, "Math" ) << new StaticFunction( "ceil", 1, fcnCeil, "Math" ) << new StaticFunction( "pi", 0, fcnPi, "Math", QString(), false, QSet(), false, QStringList() << "$pi" ) - << new StaticFunction( "to_int", 1, fcnToInt, "Conversions", QString(), false, QSet(), false, QStringList() << "toint" ) - << new StaticFunction( "to_real", 1, fcnToReal, "Conversions", QString(), false, QSet(), false, QStringList() << "toreal" ) - << new StaticFunction( "to_string", 1, fcnToString, "Conversions", QString(), false, QSet(), false, QStringList() << "tostring" ) - << new StaticFunction( "to_datetime", 1, fcnToDateTime, "Conversions", QString(), false, QSet(), false, QStringList() << "todatetime" ) - << new StaticFunction( "to_date", 1, fcnToDate, "Conversions", QString(), false, QSet(), false, QStringList() << "todate" ) - << new StaticFunction( "to_time", 1, fcnToTime, "Conversions", QString(), false, QSet(), false, QStringList() << "totime" ) - << new StaticFunction( "to_interval", 1, fcnToInterval, "Conversions", QString(), false, QSet(), false, QStringList() << "tointerval" ) + << new StaticFunction( "to_int", ParameterList() << Parameter( "value" ), fcnToInt, "Conversions", QString(), false, QSet(), false, QStringList() << "toint" ) + << new StaticFunction( "to_real", ParameterList() << Parameter( "value" ), fcnToReal, "Conversions", QString(), false, QSet(), false, QStringList() << "toreal" ) + << new StaticFunction( "to_string", ParameterList() << Parameter( "value" ), fcnToString, QStringList() << "Conversions" << "String", QString(), false, QSet(), false, QStringList() << "tostring" ) + << new StaticFunction( "to_datetime", ParameterList() << Parameter( "value" ), fcnToDateTime, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "todatetime" ) + << new StaticFunction( "to_date", ParameterList() << Parameter( "value" ), fcnToDate, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "todate" ) + << new StaticFunction( "to_time", ParameterList() << Parameter( "value" ), fcnToTime, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "totime" ) + << new StaticFunction( "to_interval", ParameterList() << Parameter( "value" ), fcnToInterval, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "tointerval" ) << new StaticFunction( "coalesce", -1, fcnCoalesce, "Conditionals", QString(), false, QSet(), false, QStringList(), true ) << new StaticFunction( "if", 3, fcnIf, "Conditionals", QString(), False, QSet(), true ) << new StaticFunction( "aggregate", ParameterList() << Parameter( "layer" ) << Parameter( "aggregate" ) << Parameter( "expression" ) @@ -3462,7 +3462,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( "collect", aggParams, fcnAggregateCollectGeometry, "Aggregates", QString(), False, QSet(), true ) << new StaticFunction( "concatenate", aggParams << Parameter( "concatenator", true ), fcnAggregateStringConcat, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "regexp_match", 2, fcnRegexpMatch, "Conditionals" ) + << new StaticFunction( "regexp_match", ParameterList() << Parameter( "string" ) << Parameter( "regex" ), fcnRegexpMatch, QStringList() << "Conditionals" << "String" ) << new StaticFunction( "now", 0, fcnNow, "Date and Time", QString(), false, QSet(), false, QStringList() << "$now" ) << new StaticFunction( "age", 2, fcnAge, "Date and Time" ) << new StaticFunction( "year", 1, fcnYear, "Date and Time" ) @@ -3483,7 +3483,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( "soundex", 1, fcnSoundex, "Fuzzy Matching" ) << new StaticFunction( "char", 1, fcnChar, "String" ) << new StaticFunction( "wordwrap", ParameterList() << Parameter( "text" ) << Parameter( "length" ) << Parameter( "delimiter", true, "" ), fcnWordwrap, "String" ) - << new StaticFunction( "length", 1, fcnLength, "String" ) + << new StaticFunction( "length", ParameterList() << Parameter( "text", true, "" ), fcnLength, QStringList() << "String" << "GeometryGroup" ) << new StaticFunction( "replace", 3, fcnReplace, "String" ) << new StaticFunction( "regexp_replace", 3, fcnRegexpReplace, "String" ) << new StaticFunction( "regexp_substr", 2, fcnRegexpSubstr, "String" ) @@ -3496,7 +3496,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( "lpad", 3, fcnLPad, "String" ) << new StaticFunction( "format", -1, fcnFormatString, "String" ) << new StaticFunction( "format_number", 2, fcnFormatNumber, "String" ) - << new StaticFunction( "format_date", 2, fcnFormatDate, "String" ) + << new StaticFunction( "format_date", ParameterList() << Parameter( "date" ) << Parameter( "format" ), fcnFormatDate, QStringList() << "String" << "Date and Time" ) << new StaticFunction( "color_rgb", 3, fcnColorRgb, "Color" ) << new StaticFunction( "color_rgba", 4, fncColorRgba, "Color" ) << new StaticFunction( "ramp_color", 2, fcnRampColor, "Color" ) diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index 2216afd0b6d0..0e3f07426197 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -458,7 +458,31 @@ class CORE_EXPORT QgsExpression : mName( fnname ) , mParams( params ) , mUsesGeometry( usesGeometry ) - , mGroup( group ) + , mGroups( group.isEmpty() ? QStringList() : QStringList() << group ) + , mHelpText( helpText ) + , mReferencedColumns( referencedColumns ) + , mLazyEval( lazyEval ) + , mHandlesNull( handlesNull ) + , mIsContextual( isContextual ) + { + } + + /** Constructor for function which uses unnamed parameters and group list + * @note added in QGIS 3.0 + */ + Function( const QString& fnname, + int params, + const QStringList& groups, + const QString& helpText = QString(), + bool usesGeometry = false, + const QSet& referencedColumns = QSet(), + bool lazyEval = false, + bool handlesNull = false, + bool isContextual = false ) + : mName( fnname ) + , mParams( params ) + , mUsesGeometry( usesGeometry ) + , mGroups( groups ) , mHelpText( helpText ) , mReferencedColumns( referencedColumns ) , mLazyEval( lazyEval ) @@ -483,7 +507,31 @@ class CORE_EXPORT QgsExpression , mParams( 0 ) , mParameterList( params ) , mUsesGeometry( usesGeometry ) - , mGroup( group ) + , mGroups( group.isEmpty() ? QStringList() : QStringList() << group ) + , mHelpText( helpText ) + , mReferencedColumns( referencedColumns ) + , mLazyEval( lazyEval ) + , mHandlesNull( handlesNull ) + , mIsContextual( isContextual ) + {} + + /** Constructor for function which uses named parameter list and group list. + * @note added in QGIS 3.0 + */ + Function( const QString& fnname, + const ParameterList& params, + const QStringList& groups, + const QString& helpText = QString(), + bool usesGeometry = false, + const QSet& referencedColumns = QSet(), + bool lazyEval = false, + bool handlesNull = false, + bool isContextual = false ) + : mName( fnname ) + , mParams( 0 ) + , mParameterList( params ) + , mUsesGeometry( usesGeometry ) + , mGroups( groups ) , mHelpText( helpText ) , mReferencedColumns( referencedColumns ) , mLazyEval( lazyEval ) @@ -541,8 +589,22 @@ class CORE_EXPORT QgsExpression */ bool isContextual() const { return mIsContextual; } - /** The group the function belongs to. */ - QString group() const { return mGroup; } + /** Returns true if the function is deprecated and should not be presented as a valid option + * to users in expression builders. + * @note added in QGIS 3.0 + */ + virtual bool isDeprecated() const { return mGroups.isEmpty() ? false : mGroups.contains( "deprecated" ); } + + /** Returns the first group which the function belongs to. + * @note consider using groups() instead, as some functions naturally belong in multiple groups + */ + QString group() const { return mGroups.isEmpty() ? QString() : mGroups.at( 0 ); } + + /** Returns a list of the groups the function belongs to. + * @note added in QGIS 3.0 + * @see group() + */ + QStringList groups() const { return mGroups; } /** The help text for the function. */ const QString helpText() const { return mHelpText.isEmpty() ? QgsExpression::helpText( mName ) : mHelpText; } @@ -564,7 +626,7 @@ class CORE_EXPORT QgsExpression int mParams; ParameterList mParameterList; bool mUsesGeometry; - QString mGroup; + QStringList mGroups; QString mHelpText; QSet mReferencedColumns; bool mLazyEval; @@ -614,6 +676,24 @@ class CORE_EXPORT QgsExpression , mAliases( aliases ) {} + /** Static function for evaluation against a QgsExpressionContext, using a named list of parameter values and list + * of groups. + */ + StaticFunction( const QString& fnname, + const ParameterList& params, + FcnEval fcn, + const QStringList& groups, + const QString& helpText = QString(), + bool usesGeometry = false, + const QSet& referencedColumns = QSet(), + bool lazyEval = false, + const QStringList& aliases = QStringList(), + bool handlesNull = false ) + : Function( fnname, params, groups, helpText, usesGeometry, referencedColumns, lazyEval, handlesNull ) + , mFnc( fcn ) + , mAliases( aliases ) + {} + virtual ~StaticFunction() {} /** Returns result of evaluating the function. diff --git a/src/gui/qgsexpressionbuilderwidget.cpp b/src/gui/qgsexpressionbuilderwidget.cpp index 8b3e35df97e8..cfbc54f62766 100644 --- a/src/gui/qgsexpressionbuilderwidget.cpp +++ b/src/gui/qgsexpressionbuilderwidget.cpp @@ -479,7 +479,7 @@ void QgsExpressionBuilderWidget::updateFunctionTree() QString name = func->name(); if ( name.startsWith( '_' ) ) // do not display private functions continue; - if ( func->group() == "deprecated" ) // don't show deprecated functions + if ( func->isDeprecated() ) // don't show deprecated functions continue; if ( func->isContextual() ) { @@ -491,7 +491,7 @@ void QgsExpressionBuilderWidget::updateFunctionTree() name += '('; else if ( !name.startsWith( '$' ) ) name += "()"; - registerItem( func->group(), func->name(), ' ' + name + ' ', func->helpText() ); + registerItemForAllGroups( func->groups(), func->name(), ' ' + name + ' ', func->helpText() ); } loadExpressionContext(); @@ -614,7 +614,15 @@ void QgsExpressionBuilderWidget::loadExpressionContext() continue; if ( func->params() != 0 ) name += '('; - registerItem( func->group(), func->name(), ' ' + name + ' ', func->helpText() ); + registerItemForAllGroups( func->groups(), func->name(), ' ' + name + ' ', func->helpText() ); + } +} + +void QgsExpressionBuilderWidget::registerItemForAllGroups( const QStringList& groups, const QString& label, const QString& expressionText, const QString& helpText, QgsExpressionItem::ItemType type, bool highlightedItem, int sortOrder ) +{ + Q_FOREACH ( const QString& group, groups ) + { + registerItem( group, label, expressionText, helpText, type, highlightedItem, sortOrder ); } } diff --git a/src/gui/qgsexpressionbuilderwidget.h b/src/gui/qgsexpressionbuilderwidget.h index 40be6f978077..453abb7d7917 100644 --- a/src/gui/qgsexpressionbuilderwidget.h +++ b/src/gui/qgsexpressionbuilderwidget.h @@ -281,6 +281,20 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp void loadExpressionContext(); + /** Registers a node item for the expression builder, adding multiple items when the function exists in multiple groups + * @param groups The groups the item will be show in the tree view. If a group doesn't exist it will be created. + * @param label The label that is show to the user for the item in the tree. + * @param expressionText The text that is inserted into the expression area when the user double clicks on the item. + * @param helpText The help text that the user will see when item is selected. + * @param type The type of the expression item. + * @param highlightedItem set to true to make the item highlighted, which inserts a bold copy of the item at the top level + * @param sortOrder sort ranking for item + */ + void registerItemForAllGroups( const QStringList& groups, const QString& label, const QString& expressionText, + const QString& helpText = "", + QgsExpressionItem::ItemType type = QgsExpressionItem::ExpressionNode, + bool highlightedItem = false, int sortOrder = 1 ); + bool mAutoSave; QString mFunctionsPath; QgsVectorLayer *mLayer; From e69dd9c9b2fa13efe3a4cd2a512885accfec60b4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 10 Oct 2016 12:41:29 +1000 Subject: [PATCH 219/897] Fix escaping in regexp function help --- resources/function_help/json/regexp_match | 4 ++-- resources/function_help/json/regexp_replace | 6 +++--- resources/function_help/json/regexp_substr | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/resources/function_help/json/regexp_match b/resources/function_help/json/regexp_match index 46422a39febb..90a193f84e2e 100644 --- a/resources/function_help/json/regexp_match +++ b/resources/function_help/json/regexp_match @@ -3,7 +3,7 @@ "type": "function", "description": "Returns true if any part of a string matches the supplied regular expression.", "arguments": [ {"arg":"input_string","description":"the string to test against the regular expression"}, - {"arg":"regex","description":"The regular expression to test against. Backslash characters must be double escaped (eg \"\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."} + {"arg":"regex","description":"The regular expression to test against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."} ], - "examples": [ { "expression":"regexp_match('QGIS ROCKS','\\\\sROCKS')", "returns":"true"}] + "examples": [ { "expression":"regexp_match('QGIS ROCKS','\\\\\\\\sROCKS')", "returns":"true"}] } diff --git a/resources/function_help/json/regexp_replace b/resources/function_help/json/regexp_replace index 10a0147bf1ad..aacce8023ca5 100644 --- a/resources/function_help/json/regexp_replace +++ b/resources/function_help/json/regexp_replace @@ -3,8 +3,8 @@ "type": "function", "description": "Returns a string with the supplied regular expression replaced.", "arguments": [ {"arg":"input_string","description":"the string to replace matches in"}, - {"arg":"regex","description":"The regular expression to replace. Backslash characters must be double escaped (eg \"\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."}, - {"arg":"replacement","description":"The string that will replace any matching occurrences of the supplied regular expression. Captured groups can be inserted into the replacement string using \\\\1, \\\\2, etc."} + {"arg":"regex","description":"The regular expression to replace. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."}, + {"arg":"replacement","description":"The string that will replace any matching occurrences of the supplied regular expression. Captured groups can be inserted into the replacement string using \\\\\\\\1, \\\\\\\\2, etc."} ], - "examples": [ { "expression":"regexp_replace('QGIS SHOULD ROCK','\\\\sSHOULD\\\\s',' DOES ')", "returns":"'QGIS DOES ROCK'"}] + "examples": [ { "expression":"regexp_replace('QGIS SHOULD ROCK','\\\\\\\\sSHOULD\\\\\\\\s',' DOES ')", "returns":"'QGIS DOES ROCK'"}] } diff --git a/resources/function_help/json/regexp_substr b/resources/function_help/json/regexp_substr index 28a6cd460cc9..58fabdb9136d 100644 --- a/resources/function_help/json/regexp_substr +++ b/resources/function_help/json/regexp_substr @@ -3,7 +3,7 @@ "type": "function", "description": "Returns the portion of a string which matches a supplied regular expression.", "arguments": [ {"arg":"input_string","description":"the string to find matches in"}, - {"arg":"regex","description":"The regular expression to match against. Backslash characters must be double escaped (eg \"\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."} + {"arg":"regex","description":"The regular expression to match against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."} ], - "examples": [ { "expression":"regexp_substr('abc123','(\\\\d+)')", "returns":"'123'"}] + "examples": [ { "expression":"regexp_substr('abc123','(\\\\\\\\d+)')", "returns":"'123'"}] } From c1cf896c1a76fdac16b3e800b7e1f106f983e299 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 10 Oct 2016 13:03:27 +1000 Subject: [PATCH 220/897] Fix invalid values for @map_extent_width/height (fix #15672) --- src/core/qgsexpressioncontext.cpp | 4 ++-- tests/src/core/testqgs25drenderer.cpp | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index 0df4f1ca3d5f..f808727ee7eb 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -779,8 +779,8 @@ QgsExpressionContextScope* QgsExpressionContextUtils::mapSettingsScope( const Qg scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_id", "canvas", true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_rotation", mapSettings.rotation(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_scale", mapSettings.scale(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_width", mapSettings.extent().width(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_height", mapSettings.extent().height(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_width", mapSettings.visibleExtent().width(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_height", mapSettings.visibleExtent().height(), true ) ); QgsGeometry centerPoint = QgsGeometry::fromPoint( mapSettings.visibleExtent().center() ); scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_center", QVariant::fromValue( centerPoint ), true ) ); diff --git a/tests/src/core/testqgs25drenderer.cpp b/tests/src/core/testqgs25drenderer.cpp index 03203f087ffd..762b8b52178e 100644 --- a/tests/src/core/testqgs25drenderer.cpp +++ b/tests/src/core/testqgs25drenderer.cpp @@ -146,6 +146,7 @@ bool TestQgs25DRenderer::imageCheck( const QString& theTestType ) //use the QgsRenderChecker test utility class to //ensure the rendered output matches our control image mMapSettings.setExtent( mpPolysLayer->extent() ); + mMapSettings.setOutputSize( QSize( 400, 400 ) ); mMapSettings.setOutputDpi( 96 ); QgsExpressionContext context; context << QgsExpressionContextUtils::mapSettingsScope( mMapSettings ); From 748d8acddb5ab6e72b09d2ae6485d46fc17c4d16 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 10 Oct 2016 14:15:56 +1000 Subject: [PATCH 221/897] Fix first marker is drawn twice for marker line interval mode --- src/core/symbology-ng/qgslinesymbollayer.cpp | 7 ------- ...pected_composerpaper_markerborder_mask.png | Bin 18524 -> 18639 bytes 2 files changed, 7 deletions(-) diff --git a/src/core/symbology-ng/qgslinesymbollayer.cpp b/src/core/symbology-ng/qgslinesymbollayer.cpp index 13877135ef41..cac0e139bec0 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.cpp +++ b/src/core/symbology-ng/qgslinesymbollayer.cpp @@ -929,7 +929,6 @@ void QgsMarkerLineSymbolLayer::renderPolylineInterval( const QPolygonF& points, QPointF lastPt = points[0]; double lengthLeft = 0; // how much is left until next marker - bool first = mOffsetAlongLine ? false : true; //only draw marker at first vertex when no offset along line is set QgsRenderContext& rc = context.renderContext(); double interval = mInterval; @@ -976,12 +975,6 @@ void QgsMarkerLineSymbolLayer::renderPolylineInterval( const QPolygonF& points, mMarker->setLineAngle( l.angle() * 180 / M_PI ); } - // draw first marker - if ( first ) - { - mMarker->renderPoint( lastPt, context.feature(), rc, -1, context.selected() ); - first = false; - } // while we're not at the end of line segment, draw! while ( lengthLeft > painterUnitInterval ) diff --git a/tests/testdata/control_images/composer_paper/expected_composerpaper_markerborder/expected_composerpaper_markerborder_mask.png b/tests/testdata/control_images/composer_paper/expected_composerpaper_markerborder/expected_composerpaper_markerborder_mask.png index 9f7c30ab0dff7ff86d5dde5f09e17abb2bf91e3d..c56c2cf0f1cde797d1845023b03b1bde052a8027 100644 GIT binary patch literal 18639 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 literal 18524 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 Q8mb*|aI-J}?5jWiKMkPpyZ`_I From ddfe91f76342578934398f9cc56aa68e4e525020 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 10 Oct 2016 15:08:17 +1000 Subject: [PATCH 222/897] Fix @geometry_point_num and @geometry_point_count for marker lines Fixes #15673 --- src/core/symbology-ng/qgslinesymbollayer.cpp | 24 +++++++ tests/src/core/testqgsmarkerlinesymbol.cpp | 65 ++++++++++++++++++ .../expected_point_num_interval.png | Bin 0 -> 2765 bytes .../expected_point_num_vertex.png | Bin 0 -> 1650 bytes 4 files changed, 89 insertions(+) create mode 100644 tests/testdata/control_images/symbol_markerline/expected_point_num_interval/expected_point_num_interval.png create mode 100644 tests/testdata/control_images/symbol_markerline/expected_point_num_vertex/expected_point_num_vertex.png diff --git a/src/core/symbology-ng/qgslinesymbollayer.cpp b/src/core/symbology-ng/qgslinesymbollayer.cpp index cac0e139bec0..6ebcc2492daf 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.cpp +++ b/src/core/symbology-ng/qgslinesymbollayer.cpp @@ -933,6 +933,9 @@ void QgsMarkerLineSymbolLayer::renderPolylineInterval( const QPolygonF& points, QgsRenderContext& rc = context.renderContext(); double interval = mInterval; + QgsExpressionContextScope* scope = new QgsExpressionContextScope(); + context.renderContext().expressionContext().appendScope( scope ); + if ( hasDataDefinedProperty( QgsSymbolLayer::EXPR_INTERVAL ) ) { context.setOriginalValueVariable( mInterval ); @@ -952,6 +955,7 @@ void QgsMarkerLineSymbolLayer::renderPolylineInterval( const QPolygonF& points, double painterUnitInterval = QgsSymbolLayerUtils::convertToPainterUnits( rc, interval, mIntervalUnit, mIntervalMapUnitScale ); lengthLeft = painterUnitInterval - QgsSymbolLayerUtils::convertToPainterUnits( rc, offsetAlongLine, mIntervalUnit, mIntervalMapUnitScale ); + int pointNum = 0; for ( int i = 1; i < points.count(); ++i ) { const QPointF& pt = points[i]; @@ -982,12 +986,15 @@ void QgsMarkerLineSymbolLayer::renderPolylineInterval( const QPolygonF& points, // "c" is 1 for regular point or in interval (0,1] for begin of line segment lastPt += c * diff; lengthLeft -= painterUnitInterval; + scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum ); mMarker->renderPoint( lastPt, context.feature(), rc, -1, context.selected() ); c = 1; // reset c (if wasn't 1 already) } lastPt = pt; } + + delete context.renderContext().expressionContext().popScope(); } static double _averageAngle( QPointF prevPt, QPointF pt, QPointF nextPt ) @@ -1011,6 +1018,10 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg int i, maxCount; bool isRing = false; + QgsExpressionContextScope* scope = new QgsExpressionContextScope(); + context.renderContext().expressionContext().appendScope( scope ); + scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, points.size() ); + double offsetAlongLine = mOffsetAlongLine; if ( hasDataDefinedProperty( QgsSymbolLayer::EXPR_OFFSET_ALONG_LINE ) ) { @@ -1033,8 +1044,11 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg QgsPointV2 vPoint; double x, y, z; QPointF mapPoint; + int pointNum = 0; while ( context.renderContext().geometry()->nextVertex( vId, vPoint ) ) { + scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum ); + if (( placement == Vertex && vId.type == QgsVertexId::SegmentVertex ) || ( placement == CurvePoint && vId.type == QgsVertexId::CurveVertex ) ) { @@ -1056,6 +1070,8 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg mMarker->renderPoint( mapPoint, context.feature(), rc, -1, context.selected() ); } } + + delete context.renderContext().expressionContext().popScope(); return; } @@ -1078,6 +1094,7 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg } else { + delete context.renderContext().expressionContext().popScope(); return; } @@ -1088,11 +1105,16 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg renderOffsetVertexAlongLine( points, i, distance, context ); // restore original rotation mMarker->setAngle( origAngle ); + + delete context.renderContext().expressionContext().popScope(); return; } + int pointNum = 0; for ( ; i < maxCount; ++i ) { + scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum ); + if ( isRing && placement == Vertex && i == points.count() - 1 ) { continue; // don't draw the last marker - it has been drawn already @@ -1109,6 +1131,8 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg // restore original rotation mMarker->setAngle( origAngle ); + + delete context.renderContext().expressionContext().popScope(); } double QgsMarkerLineSymbolLayer::markerAngle( const QPolygonF& points, bool isRing, int vertex ) diff --git a/tests/src/core/testqgsmarkerlinesymbol.cpp b/tests/src/core/testqgsmarkerlinesymbol.cpp index 5c252fbd233f..9eae4042c1f4 100644 --- a/tests/src/core/testqgsmarkerlinesymbol.cpp +++ b/tests/src/core/testqgsmarkerlinesymbol.cpp @@ -28,6 +28,10 @@ #include "qgsapplication.h" #include "qgspallabeling.h" #include "qgsfontutils.h" +#include "qgslinesymbollayer.h" +#include "qgssinglesymbolrenderer.h" +#include "qgsmarkersymbollayer.h" +#include "qgsdatadefined.h" //qgis unit test includes #include @@ -55,6 +59,8 @@ class TestQgsMarkerLineSymbol : public QObject void cleanup() {} // will be called after every testfunction. void lineOffset(); + void pointNumInterval(); + void pointNumVertex(); private: bool render( const QString& theFileName ); @@ -136,6 +142,65 @@ void TestQgsMarkerLineSymbol::lineOffset() // http://hub.qgis.org/issues/13811#note-1 } +void TestQgsMarkerLineSymbol::pointNumInterval() +{ + mMapSettings->setLayers( QStringList() << mLinesLayer->id() ); + + QgsMarkerLineSymbolLayer* ml = new QgsMarkerLineSymbolLayer(); + ml->setPlacement( QgsMarkerLineSymbolLayer::Interval ); + ml->setInterval( 4 ); + QgsLineSymbol* lineSymbol = new QgsLineSymbol(); + lineSymbol->changeSymbolLayer( 0, ml ); + QgsSingleSymbolRenderer* r = new QgsSingleSymbolRenderer( lineSymbol ); + + // make sub-symbol + QgsStringMap props; + props["color"] = "255,0,0"; + props["size"] = "2"; + props["outline_style"] = "no"; + QgsSimpleMarkerSymbolLayer* marker = static_cast< QgsSimpleMarkerSymbolLayer* >( QgsSimpleMarkerSymbolLayer::create( props ) ); + + marker->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "@geometry_point_num * 2" ) ); + + QgsMarkerSymbol* subSymbol = new QgsMarkerSymbol(); + subSymbol->changeSymbolLayer( 0, marker ); + ml->setSubSymbol( subSymbol ); + + mLinesLayer->setRenderer( r ); + + mMapSettings->setExtent( QgsRectangle( -140, -140, 140, 140 ) ); + QVERIFY( render( "point_num_interval" ) ); +} + +void TestQgsMarkerLineSymbol::pointNumVertex() +{ + mMapSettings->setLayers( QStringList() << mLinesLayer->id() ); + + QgsMarkerLineSymbolLayer* ml = new QgsMarkerLineSymbolLayer(); + ml->setPlacement( QgsMarkerLineSymbolLayer::Vertex ); + QgsLineSymbol* lineSymbol = new QgsLineSymbol(); + lineSymbol->changeSymbolLayer( 0, ml ); + QgsSingleSymbolRenderer* r = new QgsSingleSymbolRenderer( lineSymbol ); + + // make sub-symbol + QgsStringMap props; + props["color"] = "255,0,0"; + props["size"] = "2"; + props["outline_style"] = "no"; + QgsSimpleMarkerSymbolLayer* marker = static_cast< QgsSimpleMarkerSymbolLayer* >( QgsSimpleMarkerSymbolLayer::create( props ) ); + + marker->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "@geometry_point_num * 2" ) ); + + QgsMarkerSymbol* subSymbol = new QgsMarkerSymbol(); + subSymbol->changeSymbolLayer( 0, marker ); + ml->setSubSymbol( subSymbol ); + + mLinesLayer->setRenderer( r ); + + mMapSettings->setExtent( QgsRectangle( -140, -140, 140, 140 ) ); + QVERIFY( render( "point_num_vertex" ) ); +} + bool TestQgsMarkerLineSymbol::render( const QString& theTestType ) { mReport += "

                                                                                                                                                                                    " + theTestType + "

                                                                                                                                                                                    \n"; diff --git a/tests/testdata/control_images/symbol_markerline/expected_point_num_interval/expected_point_num_interval.png b/tests/testdata/control_images/symbol_markerline/expected_point_num_interval/expected_point_num_interval.png new file mode 100644 index 0000000000000000000000000000000000000000..777dc1caf317929e6da377a33471189bbace1c24 GIT binary patch literal 2765 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 T+bx!T00000NkvXXu0mjf7hE`Q literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/symbol_markerline/expected_point_num_vertex/expected_point_num_vertex.png b/tests/testdata/control_images/symbol_markerline/expected_point_num_vertex/expected_point_num_vertex.png new file mode 100644 index 0000000000000000000000000000000000000000..5ded20a30ae797d6c5962715b2bf3c0f60888e1d GIT binary patch literal 1650 zcmZ9Ndpy&77{@2EOP0B1j8j`XiBKd-QVrQ$!cGcPn~a#&Hj!26He-n+QVO|`k5Y%!ayJpoPc*G z0-m}AL>-u!Lz(*kr+(Po)fuE*8u|B2GXMq3#QPryfmS|VLM3ymP-_kdiNypx+OvUHcax3 zwC6cIjAZA=*mLW!<14Psn`rZSC@Pi4_rJrkJFvxoYj3MO`+YUf{Fo|C50ygqg5)&n z;~QMM`;B9AO z)=*#K?D{-#LvS%GYur9{;)Yvs16z6AoKi0mR%vMNuTZJ(D66K^P>I+ba7y?XEerLf z=;lcFwLgXDsM2TaqW_V+~PHg-s zdG)g$3u;iGWpq0T={ve3y6%A^!~%suM`n!Oz4UmbVxD0k^{3hf0?Ouw?|*Nik?=_q zjTPQZWW5xh)LRp7pmeu@@^-y95`OG{d3U8YW^3Q(NUfUCw!|YNDxwjxg-la+FV+xg_B^-HlX)O_S%i&Cd=hFYd;}=8 zh?@)R^pytF2|>5Er$7(%;=`4yAcQ0qMPHE{X5p9cH}$?@cF7?$!%UHkhNAJ1U)hbr zL;lN5_ZqX;d^q?rkf5M)t^lqk;)mo%q#6VJ_N|{KXt9556?$$uIJaxAOec=3>mcxO z6~Iux^%*~@V?zN-zbwGlO;wjOwE{z1q?(1drR%xvbPXB2>A#8kdMMdNBm#bGQRm7~<2_DhL`nolXTT?Gu zV;wc0mN=#3yacwg^YAxOU7I`;>wm1ma)))uZ)(wYW-pvOFDXAA@nGeqSz?8Jq5{DdJ@t3StX9nuhk@ zb8gJ}Qh&Pkrv<_B8KxM3KS* zuF+{t)VyAYZ3){Xr$3RgyQo*AJS@)-o48e{yl&J=;Jj&v_|elXyBc2IVkgFuV~iIO zb*c{H0inG8BAHA>sqQDeMbO@o-hGWODctzX&=Y8T2|H1NY|U>Tv%-Cb4(Qkb2Dx76 z-KRkQb?U;hB(jp6$F;U`5!ZT>XpG|Ax>EiO_#s5B}hdxI$&Gkp+k6->C+6tF?}Pw5-qtw zg_SW}FS9&wEx(!c4mgBB6^ghaQGM}1U{yEku3d=z+`4e?Y{{;P(+#}TkCzbz(+;a9 z`YhK|wpAEvV>E{Q_~_#U0zCb03Ty5LA*na3>NNI!Xkf$|bfk{O`diec#~=?Kf~+qB z7J<97dQW90=b5K4j`cX!&1NAZIxNN*O{Yc$Nx~#;bWMb1E%=o4c=4V}~x!d)v_f?)dLzvj*1M|30@^PTC9E YV7q$U(VfLNfZqW`aM|lzg`=GR2c?$&4gdfE literal 0 HcmV?d00001 From 6fd5815523d148728aac0ca8ad1667380f1d544f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 10 Oct 2016 19:15:02 +1000 Subject: [PATCH 223/897] @cluster_color should default to null, not empty string --- src/core/symbology-ng/qgspointdistancerenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index e67ef1dcb1b5..c046417b9448 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -454,7 +454,7 @@ QgsExpressionContextScope* QgsPointDistanceRenderer::createGroupScope( const Clu else { //mixed colors - clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); + clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, QVariant() ); } clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, group.size() ); From 2c9fdae414eba22061179e6a0b228aa078512318 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 10 Oct 2016 15:56:00 +0300 Subject: [PATCH 224/897] move imports to the top --- python/plugins/processing/tests/AlgorithmsTestBase.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/tests/AlgorithmsTestBase.py b/python/plugins/processing/tests/AlgorithmsTestBase.py index 8152167b56ed..194049415a17 100644 --- a/python/plugins/processing/tests/AlgorithmsTestBase.py +++ b/python/plugins/processing/tests/AlgorithmsTestBase.py @@ -16,6 +16,10 @@ * * *************************************************************************** """ +from __future__ import print_function +from builtins import zip +from builtins import str +from builtins import object __author__ = 'Matthias Kuhn' __date__ = 'January 2016' @@ -25,10 +29,6 @@ __revision__ = ':%H$' -from __future__ import print_function -from builtins import zip -from builtins import str -from builtins import object import qgis # NOQA switch sip api From 3b65a91b959a34d94bb8b4db26360a931fe53920 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 14:09:00 +0200 Subject: [PATCH 225/897] Revert "fix 1df9d7e" This reverts commit 3b9316dae919a3debd31440eab18b51116cf478d. --- src/server/qgsserverprojectparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 1197cf1085ad..fc10b19394c5 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -242,7 +242,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& // Reload joins and expression fields QgsVectorLayer* vlayer = dynamic_cast( layer ); QString subsetString = vlayer->subsetString(); - layer->readLayerXml( const_cast( elem ) ); + layer->readLayerXML( const_cast( elem ) ); vlayer->setSubsetString( subsetString ); } return layer; From be58cd781b51b7054b0108b2b66361d4655109f3 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 14:09:19 +0200 Subject: [PATCH 226/897] Revert "Fix QGIS server for PyQgsServerAccessControl" This reverts commit 8648bd12f39e17e3e656101e5b12a13b170e59c5. --- src/server/qgsserverprojectparser.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index fc10b19394c5..43a3055415e8 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -240,10 +240,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& { addValueRelationLayersForLayer( dynamic_cast( layer ) ); // Reload joins and expression fields - QgsVectorLayer* vlayer = dynamic_cast( layer ); - QString subsetString = vlayer->subsetString(); layer->readLayerXML( const_cast( elem ) ); - vlayer->setSubsetString( subsetString ); } return layer; } From f4cae3334a0b4a5d8390f3507e5f293da7993dfd Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 14:09:39 +0200 Subject: [PATCH 227/897] Revert "fix typo 1df9d7e1a60b3e6c913fae1414a6b397a1dc6aae" This reverts commit db1b52a249e7f5187e5ec2462bdf88ca91c5c988. --- src/server/qgsserverprojectparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 43a3055415e8..50e5c0f6ddc0 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -1547,7 +1547,7 @@ void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerEl { QString id = joinNodeList.at( i ).toElement().attribute( "joinLayerId" ); QgsMapLayer* layer = mapLayerFromLayerId( id ); - if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id ) ) + if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id )) { QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); } From 801d4cd9cd61438aea74bfa6cabc891afdca9159 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 14:10:01 +0200 Subject: [PATCH 228/897] Revert "[BUGFIX][QGIS Server] Joins was not reloaded if the layer is in cache" This reverts commit 1df9d7e1a60b3e6c913fae1414a6b397a1dc6aae. --- src/server/qgsserverprojectparser.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 50e5c0f6ddc0..42c421fa0de1 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -28,9 +28,6 @@ #include "qgslayertreegroup.h" #include "qgslogger.h" -#include "qgslogger.h" -#include "qgsmessagelog.h" - #include #include #include @@ -237,11 +234,8 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& if ( !QgsMapLayerRegistry::instance()->mapLayer( id ) ) QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); if ( layer->type() == QgsMapLayer::VectorLayer ) - { addValueRelationLayersForLayer( dynamic_cast( layer ) ); - // Reload joins and expression fields - layer->readLayerXML( const_cast( elem ) ); - } + return layer; } @@ -1547,7 +1541,7 @@ void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerEl { QString id = joinNodeList.at( i ).toElement().attribute( "joinLayerId" ); QgsMapLayer* layer = mapLayerFromLayerId( id ); - if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id )) + if ( layer ) { QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); } From e34116d7b9451c167f978fd3fbcd1d93e2c49660 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 15:26:53 +0200 Subject: [PATCH 229/897] Redo [BUGFIX][QGIS Server] Joins was not reloaded if the layer is in cache With the commit f6aad8b, the QgsMapLayerRegistry signal `layersWillBeRemoved` is always emit. This imply that the vector layer join buffer is empty and not reloaded if the layer is in cache. To fix it, the QgsServerProjectParser has to have the same method as QgsVectorLayerJoinBuffer::readXml. This commit fixed #15522 Qgis Server doesnt' respect the styling from Desktop --- src/server/qgsserverprojectparser.cpp | 52 +++++++++++++++++++++++++-- src/server/qgsserverprojectparser.h | 3 ++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 42c421fa0de1..c98da2c82309 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -234,7 +234,11 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& if ( !QgsMapLayerRegistry::instance()->mapLayer( id ) ) QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); if ( layer->type() == QgsMapLayer::VectorLayer ) - addValueRelationLayersForLayer( dynamic_cast( layer ) ); + { + QgsVectorLayer* vlayer = qobject_cast( layer ); + addValueRelationLayersForLayer( vlayer ); + addJoinsToLayer( const_cast( elem ), vlayer ); + } return layer; } @@ -1541,13 +1545,57 @@ void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerEl { QString id = joinNodeList.at( i ).toElement().attribute( "joinLayerId" ); QgsMapLayer* layer = mapLayerFromLayerId( id ); - if ( layer ) + if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id ) ) { QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); } } } +// Based on QgsVectorLayerJoinBuffer::readXml +void QgsServerProjectParser::addJoinsToLayer( const QDomElement& layerElem, QgsVectorLayer *vl ) const +{ + if ( !vl ) + return; + + QDomElement vectorJoinsElem = layerElem.firstChildElement( "vectorjoins" ); + if ( vectorJoinsElem.isNull() ) + { + return; + } + + QDomNodeList joinList = vectorJoinsElem.elementsByTagName( "join" ); + for ( int i = 0; i < joinList.size(); ++i ) + { + QDomElement infoElem = joinList.at( i ).toElement(); + QgsVectorJoinInfo info; + info.joinFieldName = infoElem.attribute( "joinFieldName" ); + info.joinLayerId = infoElem.attribute( "joinLayerId" ); + info.targetFieldName = infoElem.attribute( "targetFieldName" ); + info.memoryCache = infoElem.attribute( "memoryCache" ).toInt(); + + info.joinFieldIndex = infoElem.attribute( "joinField" ).toInt(); //for compatibility with 1.x + info.targetFieldIndex = infoElem.attribute( "targetField" ).toInt(); //for compatibility with 1.x + + QDomElement subsetElem = infoElem.firstChildElement( "joinFieldsSubset" ); + if ( !subsetElem.isNull() ) + { + QStringList* fieldNames = new QStringList; + QDomNodeList fieldNodes = infoElem.elementsByTagName( "field" ); + for ( int i = 0; i < fieldNodes.count(); ++i ) + *fieldNames << fieldNodes.at( i ).toElement().attribute( "name" ); + info.setJoinFieldNamesSubset( fieldNames ); + } + + if ( infoElem.attribute( "hasCustomPrefix" ).toInt() ) + info.prefix = infoElem.attribute( "customPrefix" ); + else + info.prefix = QString::null; + + vl->addJoin( info ); + } +} + void QgsServerProjectParser::addValueRelationLayersForLayer( const QgsVectorLayer *vl ) const { if ( !vl ) diff --git a/src/server/qgsserverprojectparser.h b/src/server/qgsserverprojectparser.h index eaba967259a3..8a067c160329 100644 --- a/src/server/qgsserverprojectparser.h +++ b/src/server/qgsserverprojectparser.h @@ -112,7 +112,10 @@ class SERVER_EXPORT QgsServerProjectParser QStringList wfsLayers() const; QStringList wcsLayers() const; + /** Add layers for vector joins */ void addJoinLayersForElement( const QDomElement& layerElem ) const; + /** Update vector joins to layer, based on QgsVectorLayerJoinBuffer::readXml */ + void addJoinsToLayer( const QDomElement& layerElem, QgsVectorLayer *vl ) const; void addValueRelationLayersForLayer( const QgsVectorLayer *vl ) const; /** Add layers which are necessary for the evaluation of the expression function 'getFeature( layer, attributField, value)'*/ From c96d8b200ed65a8ddd9c468cd947d48a7a7320cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n?= Date: Mon, 10 Oct 2016 09:32:49 -0500 Subject: [PATCH 230/897] Adding contribution details. Grabbed from former OSGeo trac: https://trac.osgeo.org/qgis/ --- doc/contributors.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/contributors.json b/doc/contributors.json index 55c38d4d5455..ebc8404b3533 100644 --- a/doc/contributors.json +++ b/doc/contributors.json @@ -425,6 +425,8 @@ "properties": { "Name": "Germán Carrillo", "Committer": "No", + "First Commit Message": "Applied patch to fix legend cursor. Provided by gcarrillo", + "First Commit Date": "10-06-2009", "GIT Nickname": "gacarrillor" }, "geometry": { From 49459c8d703b0334a67a3cf878b91b75325e6606 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 17:18:59 +0200 Subject: [PATCH 231/897] [QGIS Server] Use qobject_cast when it's usefull --- src/server/qgshostedrdsbuilder.cpp | 2 +- src/server/qgsowsserver.cpp | 4 ++-- src/server/qgsremoteowsbuilder.cpp | 4 ++-- src/server/qgswcsprojectparser.cpp | 4 ++-- src/server/qgswcsserver.cpp | 2 +- src/server/qgswfsprojectparser.cpp | 4 ++-- src/server/qgswfsserver.cpp | 4 ++-- src/server/qgswmsprojectparser.cpp | 16 ++++++++-------- src/server/qgswmsserver.cpp | 6 +++--- 9 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/server/qgshostedrdsbuilder.cpp b/src/server/qgshostedrdsbuilder.cpp index 3e1d766473fc..8de34c7a3909 100644 --- a/src/server/qgshostedrdsbuilder.cpp +++ b/src/server/qgshostedrdsbuilder.cpp @@ -59,7 +59,7 @@ QgsMapLayer* QgsHostedRDSBuilder::createMapLayer( const QDomElement& elem, QgsRasterLayer* rl = nullptr; if ( allowCaching ) { - rl = dynamic_cast( QgsMSLayerCache::instance()->searchLayer( uri, layerName ) ); + rl = qobject_cast( QgsMSLayerCache::instance()->searchLayer( uri, layerName ) ); } if ( !rl ) { diff --git a/src/server/qgsowsserver.cpp b/src/server/qgsowsserver.cpp index 35326981b5c7..5768aa08df90 100644 --- a/src/server/qgsowsserver.cpp +++ b/src/server/qgsowsserver.cpp @@ -25,7 +25,7 @@ /** Apply filter from AccessControl */ void QgsOWSServer::applyAccessControlLayerFilters( QgsMapLayer* mapLayer, QHash& originalLayerFilters ) const { - if ( QgsVectorLayer* layer = dynamic_cast( mapLayer ) ) + if ( QgsVectorLayer* layer = qobject_cast( mapLayer ) ) { QString sql = mAccessControl->extraSubsetString( layer ); if ( !sql.isEmpty() ) @@ -54,7 +54,7 @@ void QgsOWSServer::restoreLayerFilters( const QHash& filt QHash::const_iterator filterIt = filterMap.constBegin(); for ( ; filterIt != filterMap.constEnd(); ++filterIt ) { - QgsVectorLayer* filteredLayer = dynamic_cast( filterIt.key() ); + QgsVectorLayer* filteredLayer = qobject_cast( filterIt.key() ); if ( filteredLayer ) { QgsVectorDataProvider* dp = filteredLayer->dataProvider(); diff --git a/src/server/qgsremoteowsbuilder.cpp b/src/server/qgsremoteowsbuilder.cpp index 1630bd94f7d1..d597a70ae44e 100644 --- a/src/server/qgsremoteowsbuilder.cpp +++ b/src/server/qgsremoteowsbuilder.cpp @@ -162,7 +162,7 @@ QgsRasterLayer* QgsRemoteOWSBuilder::wmsLayerFromUrl( const QString& url, const if ( allowCaching ) { - result = dynamic_cast( QgsMSLayerCache::instance()->searchLayer( url, layerName ) ); + result = qobject_cast( QgsMSLayerCache::instance()->searchLayer( url, layerName ) ); } if ( result ) @@ -414,7 +414,7 @@ QgsVectorLayer* QgsRemoteOWSBuilder::sosLayer( const QDomElement& remoteOWSElem, QgsVectorLayer* sosLayer = nullptr; if ( allowCaching ) { - sosLayer = dynamic_cast( QgsMSLayerCache::instance()->searchLayer( providerUrl, layerName ) ); + sosLayer = qobject_cast( QgsMSLayerCache::instance()->searchLayer( providerUrl, layerName ) ); if ( sosLayer ) { return sosLayer; diff --git a/src/server/qgswcsprojectparser.cpp b/src/server/qgswcsprojectparser.cpp index 6c49064826ed..5b0b0a70ecb4 100644 --- a/src/server/qgswcsprojectparser.cpp +++ b/src/server/qgswcsprojectparser.cpp @@ -224,7 +224,7 @@ void QgsWCSProjectParser::describeCoverage( const QString& aCoveName, QDomElemen QString type = elem.attribute( "type" ); if ( type == "raster" ) { - QgsRasterLayer *rLayer = dynamic_cast( mProjectParser->createLayerFromElement( elem ) ); + QgsRasterLayer *rLayer = qobject_cast( mProjectParser->createLayerFromElement( elem ) ); if ( !rLayer ) continue; @@ -439,7 +439,7 @@ QList QgsWCSProjectParser::mapLayerFromCoverage( const QString& cN if ( type == "raster" ) { QgsMapLayer *mLayer = mProjectParser->createLayerFromElement( elem, useCache ); - QgsRasterLayer* layer = dynamic_cast( mLayer ); + QgsRasterLayer* layer = qobject_cast( mLayer ); if ( !layer || !wcsLayersId.contains( layer->id() ) ) return layerList; diff --git a/src/server/qgswcsserver.cpp b/src/server/qgswcsserver.cpp index 2c2456cdad71..2b02215da147 100644 --- a/src/server/qgswcsserver.cpp +++ b/src/server/qgswcsserver.cpp @@ -377,7 +377,7 @@ QByteArray* QgsWCSServer::getCoverage() QgsRectangle rect( minx, miny, maxx, maxy ); QgsMapLayer* layer = layerList.at( 0 ); - QgsRasterLayer* rLayer = dynamic_cast( layer ); + QgsRasterLayer* rLayer = qobject_cast( layer ); if ( rLayer && wcsLayersId.contains( rLayer->id() ) ) { #ifdef HAVE_SERVER_PYTHON_PLUGINS diff --git a/src/server/qgswfsprojectparser.cpp b/src/server/qgswfsprojectparser.cpp index b52e340cad62..4821cf142d37 100644 --- a/src/server/qgswfsprojectparser.cpp +++ b/src/server/qgswfsprojectparser.cpp @@ -347,7 +347,7 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle if ( type == "vector" ) { QgsMapLayer *mLayer = mProjectParser->createLayerFromElement( elem ); - QgsVectorLayer* layer = dynamic_cast( mLayer ); + QgsVectorLayer* layer = qobject_cast( mLayer ); if ( !layer ) continue; @@ -566,7 +566,7 @@ QList QgsWfsProjectParser::mapLayerFromTypeName( const QString& aT if ( type == "vector" ) { QgsMapLayer *mLayer = mProjectParser->createLayerFromElement( elem ); - QgsVectorLayer* layer = dynamic_cast( mLayer ); + QgsVectorLayer* layer = qobject_cast( mLayer ); if ( !layer ) continue; diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index c733aeeb4397..600298eb749e 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -469,7 +469,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format } currentLayer = layerList.at( 0 ); - QgsVectorLayer* layer = dynamic_cast( currentLayer ); + QgsVectorLayer* layer = qobject_cast( currentLayer ); if ( layer && wfsLayersId.contains( layer->id() ) ) { #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -863,7 +863,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format currentLayer = layerList.at( 0 ); - QgsVectorLayer* layer = dynamic_cast( currentLayer ); + QgsVectorLayer* layer = qobject_cast( currentLayer ); if ( layer && wfsLayersId.contains( layer->id() ) ) { expressionContext << QgsExpressionContextUtils::layerScope( layer ); diff --git a/src/server/qgswmsprojectparser.cpp b/src/server/qgswmsprojectparser.cpp index abcd8a1bfcf9..4c2fa12e4fae 100644 --- a/src/server/qgswmsprojectparser.cpp +++ b/src/server/qgswmsprojectparser.cpp @@ -502,19 +502,19 @@ QgsComposition* QgsWmsProjectParser::initComposition( const QString& composerTem QList::iterator itemIt = itemList.begin(); for ( ; itemIt != itemList.end(); ++itemIt ) { - QgsComposerLabel* label = dynamic_cast< QgsComposerLabel *>( *itemIt ); + QgsComposerLabel* label = qobject_cast< QgsComposerLabel *>( *itemIt ); if ( label ) { labelList.push_back( label ); continue; } - QgsComposerMap* map = dynamic_cast< QgsComposerMap *>( *itemIt ); + QgsComposerMap* map = qobject_cast< QgsComposerMap *>( *itemIt ); if ( map ) { mapList.push_back( map ); continue; } - QgsComposerLegend* legend = dynamic_cast< QgsComposerLegend *>( *itemIt ); + QgsComposerLegend* legend = qobject_cast< QgsComposerLegend *>( *itemIt ); if ( legend ) { QgsLegendModelV2* model = legend->model(); @@ -566,7 +566,7 @@ QgsComposition* QgsWmsProjectParser::initComposition( const QString& composerTem legendList.push_back( legend ); continue; } - QgsComposerPicture* pic = dynamic_cast< QgsComposerPicture *>( *itemIt ); + QgsComposerPicture* pic = qobject_cast< QgsComposerPicture *>( *itemIt ); if ( pic ) { pic->setPicturePath( mProjectParser->convertToAbsolutePath(( pic )->picturePath() ) ); @@ -575,11 +575,11 @@ QgsComposition* QgsWmsProjectParser::initComposition( const QString& composerTem // an html item will be a composer frame and if it is we can try to get // its multiframe parent and then try to cast that to a composer html - const QgsComposerFrame* frame = dynamic_cast( *itemIt ); + const QgsComposerFrame* frame = qobject_cast( *itemIt ); if ( frame ) { const QgsComposerMultiFrame * multiFrame = frame->multiFrame(); - const QgsComposerHtml* composerHtml = dynamic_cast( multiFrame ); + const QgsComposerHtml* composerHtml = qobject_cast( multiFrame ); if ( composerHtml ) { htmlList.push_back( composerHtml ); @@ -1331,7 +1331,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, bool geometryLayer = true; if ( currentLayer->type() == QgsMapLayer::VectorLayer ) { - QgsVectorLayer* vLayer = dynamic_cast( currentLayer ); + QgsVectorLayer* vLayer = qobject_cast( currentLayer ); if ( vLayer ) { if ( vLayer->wkbType() == QgsWkbTypes::NoGeometry ) @@ -1840,7 +1840,7 @@ QDomDocument QgsWmsProjectParser::getStyles( QStringList& layerList ) const for ( int j = 0; j < currentLayerList.size(); j++ ) { QgsMapLayer* currentLayer = currentLayerList.at( j ); - QgsVectorLayer* layer = dynamic_cast( currentLayer ); + QgsVectorLayer* layer = qobject_cast( currentLayer ); if ( !layer ) { throw QgsMapServiceException( "Error", QString( "Could not get style because:\n%1" ).arg( "Non-vector layers not supported yet" ) ); diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index a889bbc131f8..d0529f36950e 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -1742,7 +1742,7 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) } //switch depending on vector or raster - QgsVectorLayer* vectorLayer = dynamic_cast( currentLayer ); + QgsVectorLayer* vectorLayer = qobject_cast( currentLayer ); QDomElement layerElement; if ( infoFormat.startsWith( "application/vnd.ogc.gml" ) ) @@ -1788,7 +1788,7 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) getFeatureInfoElement.appendChild( layerElement ); } - QgsRasterLayer* rasterLayer = dynamic_cast( currentLayer ); + QgsRasterLayer* rasterLayer = qobject_cast( currentLayer ); if ( rasterLayer ) { if ( !infoPoint.data() ) @@ -2579,7 +2579,7 @@ void QgsWmsServer::applyRequestedLayerFilters( const QStringList& layerList , QH Q_FOREACH ( QgsMapLayer *filter, layersToFilter ) { - QgsVectorLayer* filteredLayer = dynamic_cast( filter ); + QgsVectorLayer* filteredLayer = qobject_cast( filter ); if ( filteredLayer ) { originalFilters.insert( filteredLayer, filteredLayer->subsetString() ); From 90aebd117d7a936e606d4993b0bc6ccc7f64080d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 08:46:38 +1000 Subject: [PATCH 232/897] [processing] Add geometry info should add z/m values (fix #14659) --- .../algs/qgis/ExportGeometryInfo.py | 17 ++++ .../testdata/expected/add_geometry_pointz.gfs | 30 +++++++ .../testdata/expected/add_geometry_pointz.gml | 86 +++++++++++++++++++ .../processing/tests/testdata/pointsz.gfs | 15 ++++ .../processing/tests/testdata/pointsz.gml | 59 +++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 12 +++ python/plugins/processing/tools/vector.py | 17 ++-- 7 files changed, 228 insertions(+), 8 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml create mode 100644 python/plugins/processing/tests/testdata/pointsz.gfs create mode 100644 python/plugins/processing/tests/testdata/pointsz.gml diff --git a/python/plugins/processing/algs/qgis/ExportGeometryInfo.py b/python/plugins/processing/algs/qgis/ExportGeometryInfo.py index 2be354d17698..5c5921a81768 100644 --- a/python/plugins/processing/algs/qgis/ExportGeometryInfo.py +++ b/python/plugins/processing/algs/qgis/ExportGeometryInfo.py @@ -74,6 +74,8 @@ def processAlgorithm(self, progress): geometryType = layer.geometryType() fields = layer.fields() + export_z = False + export_m = False if geometryType == QgsWkbTypes.PolygonGeometry: areaName = vector.createUniqueFieldName('area', fields) fields.append(QgsField(areaName, QVariant.Double)) @@ -87,6 +89,14 @@ def processAlgorithm(self, progress): fields.append(QgsField(xName, QVariant.Double)) yName = vector.createUniqueFieldName('ycoord', fields) fields.append(QgsField(yName, QVariant.Double)) + if QgsWkbTypes.hasZ(layer.wkbType()): + export_z = True + zName = vector.createUniqueFieldName('zcoord', fields) + fields.append(QgsField(zName, QVariant.Double)) + if QgsWkbTypes.hasM(layer.wkbType()): + export_m = True + zName = vector.createUniqueFieldName('mvalue', fields) + fields.append(QgsField(zName, QVariant.Double)) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( fields.toList(), layer.wkbType(), layer.crs()) @@ -130,6 +140,13 @@ def processAlgorithm(self, progress): attrs.append(attr1) if attr2 is not None: attrs.append(attr2) + + # add point z/m + if export_z: + attrs.append(inGeom.geometry().z()) + if export_m: + attrs.append(inGeom.geometry().m()) + outFeat.setAttributes(attrs) writer.addFeature(outFeat) diff --git a/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs new file mode 100644 index 000000000000..ffe1b014dc4b --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs @@ -0,0 +1,30 @@ + + + add_geometry_pointz + add_geometry_pointz + -2147483647 + EPSG:4326 + + 9 + 0.00000 + 8.00000 + -5.00000 + 3.00000 + + + xcoord + xcoord + Integer + + + ycoord + ycoord + Integer + + + zcoord + zcoord + Integer + + + diff --git a/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml new file mode 100644 index 000000000000..d02f6d18f20b --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml @@ -0,0 +1,86 @@ + + + + + 0-50 + 837 + + + + + + 1,1,3 + 1 + 1 + 3 + + + + + 3,3,0 + 3 + 3 + 0 + + + + + 2,2,2 + 2 + 2 + 2 + + + + + 5,2,0 + 5 + 2 + 0 + + + + + 4,1,0 + 4 + 1 + 0 + + + + + 0,-5,5 + 0 + -5 + 5 + + + + + 8,-1,7 + 8 + -1 + 7 + + + + + 7,-1,6 + 7 + -1 + 6 + + + + + 0,-1,4 + 0 + -1 + 4 + + + diff --git a/python/plugins/processing/tests/testdata/pointsz.gfs b/python/plugins/processing/tests/testdata/pointsz.gfs new file mode 100644 index 000000000000..770d77f10f1c --- /dev/null +++ b/python/plugins/processing/tests/testdata/pointsz.gfs @@ -0,0 +1,15 @@ + + + pointsz + pointsz + -2147483647 + EPSG:4326 + + 9 + 0.00000 + 8.00000 + -5.00000 + 3.00000 + + + diff --git a/python/plugins/processing/tests/testdata/pointsz.gml b/python/plugins/processing/tests/testdata/pointsz.gml new file mode 100644 index 000000000000..83d588b347dd --- /dev/null +++ b/python/plugins/processing/tests/testdata/pointsz.gml @@ -0,0 +1,59 @@ + + + + + 0-50 + 837 + + + + + + 1,1,3 + + + + + 3,3,0 + + + + + 2,2,2 + + + + + 5,2,0 + + + + + 4,1,0 + + + + + 0,-5,5 + + + + + 8,-1,7 + + + + + 7,-1,6 + + + + + 0,-1,4 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 4af0ce4ce768..a532c0247196 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -993,3 +993,15 @@ tests: OUTPUT_LAYER: name: expected/smoothed_lines_max_angle.gml type: vector + + - algorithm: qgis:exportaddgeometrycolumns + name: Add Geometry PointZ + params: + CALC_METHOD: '0' + INPUT: + name: pointsz.gml + type: vector + results: + OUTPUT: + name: expected/add_geometry_pointz.gml + type: vector diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index d8b135b8582f..8d0014dbe8d3 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -269,14 +269,15 @@ def simpleMeasure(geom, method=0, ellips=None, crs=None): # 1 - project CRS # 2 - ellipsoidal - if geom.wkbType() in [QgsWkbTypes.Point, QgsWkbTypes.Point25D]: - pt = geom.asPoint() - attr1 = pt.x() - attr2 = pt.y() - elif geom.wkbType() in [QgsWkbTypes.MultiPoint, QgsWkbTypes.MultiPoint25D]: - pt = geom.asMultiPoint() - attr1 = pt[0].x() - attr2 = pt[0].y() + if geom.type() == QgsWkbTypes.PointGeometry: + if not geom.isMultipart(): + pt = geom.geometry() + attr1 = pt.x() + attr2 = pt.y() + else: + pt = geom.asMultiPoint() + attr1 = pt[0].x() + attr2 = pt[0].y() else: measure = QgsDistanceArea() From d4323addf04e0a1bdccec2127c7b2b8a59661799 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 09:02:03 +1000 Subject: [PATCH 233/897] [processing] Fix missing points in polygons menu item (fix #15670) Also add a unit test --- python/plugins/processing/gui/menus.py | 2 +- .../testdata/expected/points_in_polys.gfs | 36 ++++++++ .../testdata/expected/points_in_polys.gml | 64 ++++++++++++++ .../tests/testdata/points_in_polys.gfs | 15 ++++ .../tests/testdata/points_in_polys.gml | 87 +++++++++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 16 ++++ 6 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/tests/testdata/expected/points_in_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/points_in_polys.gml create mode 100644 python/plugins/processing/tests/testdata/points_in_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/points_in_polys.gml diff --git a/python/plugins/processing/gui/menus.py b/python/plugins/processing/gui/menus.py index e12b5dfc1f3d..2557ebc37917 100644 --- a/python/plugins/processing/gui/menus.py +++ b/python/plugins/processing/gui/menus.py @@ -21,7 +21,7 @@ analysisToolsMenu = vectorMenu + "/" + Processing.tr('&Analysis Tools') defaultMenuEntries.update({'qgis:distancematrix': analysisToolsMenu, 'qgis:sumlinelengths': analysisToolsMenu, - 'qgis:pointsinpolygon': analysisToolsMenu, + 'qgis:countpointsinpolygon': analysisToolsMenu, 'qgis:listuniquevalues': analysisToolsMenu, 'qgis:basicstatisticsfornumericfields': analysisToolsMenu, 'qgis:basicstatisticsfortextfields': analysisToolsMenu, diff --git a/python/plugins/processing/tests/testdata/expected/points_in_polys.gfs b/python/plugins/processing/tests/testdata/expected/points_in_polys.gfs new file mode 100644 index 000000000000..7b721f55ffae --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/points_in_polys.gfs @@ -0,0 +1,36 @@ + + + points_in_polys + points_in_polys + 3 + EPSG:4326 + + 6 + -1.00000 + 10.00000 + -3.00000 + 6.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + NUMPOINTS + NUMPOINTS + Integer + + + diff --git a/python/plugins/processing/tests/testdata/expected/points_in_polys.gml b/python/plugins/processing/tests/testdata/expected/points_in_polys.gml new file mode 100644 index 000000000000..b22867c01ea2 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/points_in_polys.gml @@ -0,0 +1,64 @@ + + + + + -1-3 + 106 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.123456 + 4 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + 1 + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.123 + 0 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + ASDF + 0 + 2 + + + + + 120 + -100291.43213 + 0 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 2 + 3.33 + 3 + + + diff --git a/python/plugins/processing/tests/testdata/points_in_polys.gfs b/python/plugins/processing/tests/testdata/points_in_polys.gfs new file mode 100644 index 000000000000..05cdcde88a51 --- /dev/null +++ b/python/plugins/processing/tests/testdata/points_in_polys.gfs @@ -0,0 +1,15 @@ + + + points_in_polys + points_in_polys + 1 + EPSG:4326 + + 15 + -0.13645 + 7.79548 + -2.63675 + 5.68735 + + + diff --git a/python/plugins/processing/tests/testdata/points_in_polys.gml b/python/plugins/processing/tests/testdata/points_in_polys.gml new file mode 100644 index 000000000000..dfb7e6a98db1 --- /dev/null +++ b/python/plugins/processing/tests/testdata/points_in_polys.gml @@ -0,0 +1,87 @@ + + + + + -0.1364457831325305-2.636746987951807 + 7.7954819277108445.687349397590362 + + + + + + 1.078012048192771,2.499397590361446 + + + + + 0.154518072289156,2.499397590361446 + + + + + -0.136445783132531,0.551204819277109 + + + + + 0.926204819277108,0.563855421686747 + + + + + 2.279819277108433,3.941566265060241 + + + + + 4.40512048192771,2.347590361445783 + + + + + 4.430421686746987,5.687349397590362 + + + + + + + + + 5.379216867469879,0.18433734939759 + + + + + 4.253313253012048,-0.777108433734941 + + + + + 4.569578313253012,-1.257831325301205 + + + + + 7.744879518072288,-2.636746987951807 + + + + + 7.795481927710844,0.525903614457832 + + + + + 5.126204819277108,4.283132530120482 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index a532c0247196..0f2aa24c19b4 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1005,3 +1005,19 @@ tests: OUTPUT: name: expected/add_geometry_pointz.gml type: vector + + + - algorithm: qgis:countpointsinpolygon + name: Count points in polygon + params: + FIELD: NUMPOINTS + POINTS: + name: points_in_polys.gml + type: vector + POLYGONS: + name: polys.gml + type: vector + results: + OUTPUT: + name: expected/points_in_polys.gml + type: vector From 01a402ca113b448f9a8891fda4c062d8bc310f77 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 10:44:26 +1000 Subject: [PATCH 234/897] [labeling] Fix line orientation option gets checked randomly --- src/app/qgslabelinggui.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index cb252368f5db..284075a75eb1 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -659,8 +659,7 @@ void QgsLabelingGui::init() chkLineAbove->setChecked( lyr.placementFlags & QgsPalLayerSettings::AboveLine ); chkLineBelow->setChecked( lyr.placementFlags & QgsPalLayerSettings::BelowLine ); chkLineOn->setChecked( lyr.placementFlags & QgsPalLayerSettings::OnLine ); - if ( !( lyr.placementFlags & QgsPalLayerSettings::MapOrientation ) ) - chkLineOrientationDependent->setChecked( true ); + chkLineOrientationDependent->setChecked( !( lyr.placementFlags & QgsPalLayerSettings::MapOrientation ) ); switch ( lyr.placement ) { From c36c242e8ef242ef7f2da524fca0b7b16ee13ce7 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 11:33:50 +1000 Subject: [PATCH 235/897] [labeling] When in line orientation placement mode, rename above/ below options to left of line/right of line Makes their meaning clearer --- src/app/qgslabelinggui.cpp | 14 ++++++++++++++ src/app/qgslabelinggui.h | 1 + src/ui/qgslabelingguibase.ui | 14 +++++++------- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index 284075a75eb1..2b582fbcc7b9 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -2124,6 +2124,20 @@ void QgsLabelingGui::on_mChkNoObstacle_toggled( bool active ) mObstaclePriorityFrame->setEnabled( active ); } +void QgsLabelingGui::on_chkLineOrientationDependent_toggled( bool active ) +{ + if ( active ) + { + chkLineAbove->setText( tr( "Left of line" ) ); + chkLineBelow->setText( tr( "Right of line" ) ); + } + else + { + chkLineAbove->setText( tr( "Above line" ) ); + chkLineBelow->setText( tr( "Below line" ) ); + } +} + void QgsLabelingGui::on_mToolButtonConfigureSubstitutes_clicked() { QgsPanelWidget* panel = QgsPanelWidget::findParentPanel( this ); diff --git a/src/app/qgslabelinggui.h b/src/app/qgslabelinggui.h index 2ec4bb691f2a..058c71fe1138 100644 --- a/src/app/qgslabelinggui.h +++ b/src/app/qgslabelinggui.h @@ -94,6 +94,7 @@ class APP_EXPORT QgsLabelingGui : public QWidget, private Ui::QgsLabelingGuiBase void on_mDirectSymbLeftToolBtn_clicked(); void on_mDirectSymbRightToolBtn_clicked(); void on_mChkNoObstacle_toggled( bool active ); + void on_chkLineOrientationDependent_toggled( bool active ); void on_mToolButtonConfigureSubstitutes_clicked(); diff --git a/src/ui/qgslabelingguibase.ui b/src/ui/qgslabelingguibase.ui index ea7a45dcc08b..33971f380e7f 100644 --- a/src/ui/qgslabelingguibase.ui +++ b/src/ui/qgslabelingguibase.ui @@ -618,7 +618,7 @@ - 0 + 5 @@ -1439,8 +1439,8 @@ font-style: italic; 0 0 - 466 - 356 + 342 + 338
                                                                                                                                                                                    @@ -2074,8 +2074,8 @@ font-style: italic; 0 0 - 466 - 376 + 285 + 245 @@ -2456,7 +2456,7 @@ font-style: italic; 0 0 - 452 + 431 628 @@ -3276,7 +3276,7 @@ font-style: italic; 0 0 - 452 + 305 398 From 44546e8ebb3658fd9d0c4599ac5f2c4549d33708 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 11:58:08 +1000 Subject: [PATCH 236/897] [composer] Port remaining symbol pickers to inline panels --- src/app/composer/qgscomposer.cpp | 11 +++-- src/app/composer/qgscomposer.h | 1 + src/app/composer/qgscomposerarrowwidget.cpp | 42 ++++++++++++------- src/app/composer/qgscomposerarrowwidget.h | 3 ++ src/app/composer/qgscomposerpolygonwidget.cpp | 41 +++++++++++------- src/app/composer/qgscomposerpolygonwidget.h | 3 ++ .../composer/qgscomposerpolylinewidget.cpp | 40 ++++++++++++------ src/app/composer/qgscomposerpolylinewidget.h | 3 ++ src/app/composer/qgscompositionwidget.cpp | 41 +++++++++++++----- src/app/composer/qgscompositionwidget.h | 7 +++- 10 files changed, 137 insertions(+), 55 deletions(-) diff --git a/src/app/composer/qgscomposer.cpp b/src/app/composer/qgscomposer.cpp index cd55b1f2740a..4ed6dd4fa401 100644 --- a/src/app/composer/qgscomposer.cpp +++ b/src/app/composer/qgscomposer.cpp @@ -575,6 +575,8 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) mGeneralDock = new QgsDockWidget( tr( "Composition" ), this ); mGeneralDock->setObjectName( "CompositionDock" ); mGeneralDock->setMinimumWidth( minDockWidth ); + mGeneralPropertiesStack = new QgsPanelWidgetStack(); + mGeneralDock->setWidget( mGeneralPropertiesStack ); mPanelMenu->addAction( mGeneralDock->toggleViewAction() ); mItemDock = new QgsDockWidget( tr( "Item properties" ), this ); mItemDock->setObjectName( "ItemDock" ); @@ -925,7 +927,7 @@ bool QgsComposer::loadFromTemplate( const QDomDocument& templateDoc, bool clearE if ( result ) { // update composition widget - QgsCompositionWidget* oldCompositionWidget = qobject_cast( mGeneralDock->widget() ); + QgsCompositionWidget* oldCompositionWidget = qobject_cast( mGeneralPropertiesStack->takeMainPanel() ); delete oldCompositionWidget; createCompositionWidget(); } @@ -1548,7 +1550,7 @@ void QgsComposer::setComposition( QgsComposition* composition ) } //delete composition widget - QgsCompositionWidget* oldCompositionWidget = qobject_cast( mGeneralDock->widget() ); + QgsCompositionWidget* oldCompositionWidget = qobject_cast( mGeneralPropertiesStack->takeMainPanel() ); delete oldCompositionWidget; deleteItemWidgets(); @@ -3514,10 +3516,11 @@ void QgsComposer::createCompositionWidget() } QgsCompositionWidget* compositionWidget = new QgsCompositionWidget( mGeneralDock, mComposition ); + compositionWidget->setDockMode( true ); connect( mComposition, SIGNAL( paperSizeChanged() ), compositionWidget, SLOT( displayCompositionWidthHeight() ) ); connect( this, SIGNAL( printAsRasterChanged( bool ) ), compositionWidget, SLOT( setPrintAsRasterCheckBox( bool ) ) ); connect( compositionWidget, SIGNAL( pageOrientationChanged( QString ) ), this, SLOT( pageOrientationChanged( QString ) ) ); - mGeneralDock->setWidget( compositionWidget ); + mGeneralPropertiesStack->setMainPanel( compositionWidget ); } void QgsComposer::readXml( const QDomElement& composerElem, const QDomDocument& doc, bool fromTemplate ) @@ -3532,7 +3535,7 @@ void QgsComposer::readXml( const QDomElement& composerElem, const QDomDocument& } //delete composition widget - QgsCompositionWidget* oldCompositionWidget = qobject_cast( mGeneralDock->widget() ); + QgsCompositionWidget* oldCompositionWidget = qobject_cast( mGeneralPropertiesStack->takeMainPanel() ); delete oldCompositionWidget; deleteItemWidgets(); diff --git a/src/app/composer/qgscomposer.h b/src/app/composer/qgscomposer.h index 664d693ff936..3f12a1d67203 100644 --- a/src/app/composer/qgscomposer.h +++ b/src/app/composer/qgscomposer.h @@ -602,6 +602,7 @@ class QgsComposer: public QMainWindow, private Ui::QgsComposerBase QgsPanelWidgetStack* mItemPropertiesStack; QgsDockWidget* mUndoDock; QgsDockWidget* mGeneralDock; + QgsPanelWidgetStack* mGeneralPropertiesStack; QgsDockWidget* mAtlasDock; QgsDockWidget* mItemsDock; diff --git a/src/app/composer/qgscomposerarrowwidget.cpp b/src/app/composer/qgscomposerarrowwidget.cpp index abaaa6d6f51e..1c144604d5f2 100644 --- a/src/app/composer/qgscomposerarrowwidget.cpp +++ b/src/app/composer/qgscomposerarrowwidget.cpp @@ -169,6 +169,24 @@ void QgsComposerArrowWidget::setGuiElementValues() blockAllSignals( false ); } +void QgsComposerArrowWidget::updateLineStyleFromWidget() +{ + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mArrow->setLineSymbol( dynamic_cast< QgsLineSymbol* >( w->symbol()->clone() ) ); + mArrow->update(); +} + +void QgsComposerArrowWidget::cleanUpLineStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + updateLineSymbolMarker(); + mArrow->endCommand(); +} + void QgsComposerArrowWidget::enableSvgInputElements( bool enable ) { mStartMarkerLineEdit->setEnabled( enable ); @@ -310,25 +328,21 @@ void QgsComposerArrowWidget::on_mLineStyleButton_clicked() return; } + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + QgsLineSymbol* newSymbol = mArrow->lineSymbol()->clone(); - QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), nullptr, this ); QgsExpressionContext context = mArrow->createExpressionContext(); + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); QgsSymbolWidgetContext symbolContext; symbolContext.setExpressionContext( &context ); - d.setContext( symbolContext ); + d->setContext( symbolContext ); - if ( d.exec() == QDialog::Accepted ) - { - mArrow->beginCommand( tr( "Arrow line style changed" ) ); - mArrow->setLineSymbol( newSymbol ); - updateLineSymbolMarker(); - mArrow->endCommand(); - mArrow->update(); - } - else - { - delete newSymbol; - } + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateLineStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpLineStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mArrow->beginCommand( tr( "Arrow line style changed" ) ); } void QgsComposerArrowWidget::updateLineSymbolMarker() diff --git a/src/app/composer/qgscomposerarrowwidget.h b/src/app/composer/qgscomposerarrowwidget.h index 89acf23faffa..0497de69861f 100644 --- a/src/app/composer/qgscomposerarrowwidget.h +++ b/src/app/composer/qgscomposerarrowwidget.h @@ -57,6 +57,9 @@ class QgsComposerArrowWidget: public QgsComposerItemBaseWidget, private Ui::QgsC void on_mLineStyleButton_clicked(); void setGuiElementValues(); + + void updateLineStyleFromWidget(); + void cleanUpLineStyleSelector( QgsPanelWidget* container ); }; #endif // QGSCOMPOSERARROWWIDGET_H diff --git a/src/app/composer/qgscomposerpolygonwidget.cpp b/src/app/composer/qgscomposerpolygonwidget.cpp index cf20635f5a58..74a814e7ad73 100644 --- a/src/app/composer/qgscomposerpolygonwidget.cpp +++ b/src/app/composer/qgscomposerpolygonwidget.cpp @@ -31,7 +31,7 @@ QgsComposerPolygonWidget::QgsComposerPolygonWidget( QgsComposerPolygon* composer //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, composerPolygon ); - //shapes don't use background or frame, since the symbol style is set through a QgsSymbolSelectorDialog + //shapes don't use background or frame, since the symbol style is set through a QgsSymbolSelectorWidget itemPropertiesWidget->showBackgroundGroup( false ); itemPropertiesWidget->showFrameGroup( false ); mainLayout->addWidget( itemPropertiesWidget ); @@ -59,23 +59,18 @@ void QgsComposerPolygonWidget::on_mPolygonStyleButton_clicked() // use the atlas coverage layer, if any QgsVectorLayer* coverageLayer = atlasCoverageLayer(); - QScopedPointer newSymbol; - newSymbol.reset( mComposerPolygon->polygonStyleSymbol()->clone() ); - + QgsFillSymbol* newSymbol = mComposerPolygon->polygonStyleSymbol()->clone(); QgsExpressionContext context = mComposerPolygon->createExpressionContext(); - QgsSymbolSelectorDialog d( newSymbol.data(), QgsStyle::defaultStyle(), - coverageLayer, this ); + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); QgsSymbolWidgetContext symbolContext; symbolContext.setExpressionContext( &context ); - d.setContext( symbolContext ); + d->setContext( symbolContext ); - if ( d.exec() == QDialog::Accepted ) - { - mComposerPolygon->beginCommand( tr( "Polygon style changed" ) ); - mComposerPolygon->setPolygonStyleSymbol( newSymbol.data() ); - updatePolygonStyle(); - mComposerPolygon->endCommand(); - } + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerPolygon->beginCommand( tr( "Polygon style changed" ) ); } void QgsComposerPolygonWidget::setGuiElementValues() @@ -88,6 +83,24 @@ void QgsComposerPolygonWidget::setGuiElementValues() updatePolygonStyle(); } +void QgsComposerPolygonWidget::updateStyleFromWidget() +{ + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mComposerPolygon->setPolygonStyleSymbol( dynamic_cast< QgsFillSymbol* >( w->symbol() ) ); + mComposerPolygon->update(); +} + +void QgsComposerPolygonWidget::cleanUpStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + updatePolygonStyle(); + mComposerPolygon->endCommand(); +} + void QgsComposerPolygonWidget::updatePolygonStyle() { if ( mComposerPolygon ) diff --git a/src/app/composer/qgscomposerpolygonwidget.h b/src/app/composer/qgscomposerpolygonwidget.h index 8b9837b8288c..96e3a362021e 100644 --- a/src/app/composer/qgscomposerpolygonwidget.h +++ b/src/app/composer/qgscomposerpolygonwidget.h @@ -43,6 +43,9 @@ class QgsComposerPolygonWidget: public QgsComposerItemBaseWidget, private Ui::Qg /** Sets the GUI elements to the currentValues of mComposerShape*/ void setGuiElementValues(); + + void updateStyleFromWidget(); + void cleanUpStyleSelector( QgsPanelWidget* container ); }; #endif // QGSCOMPOSERPOLYGONWIDGET_H diff --git a/src/app/composer/qgscomposerpolylinewidget.cpp b/src/app/composer/qgscomposerpolylinewidget.cpp index 5e0777713ca1..a2054c60157d 100644 --- a/src/app/composer/qgscomposerpolylinewidget.cpp +++ b/src/app/composer/qgscomposerpolylinewidget.cpp @@ -51,23 +51,21 @@ void QgsComposerPolylineWidget::on_mLineStyleButton_clicked() if ( !mComposerPolyline ) return; - QScopedPointer newSymbol; - newSymbol.reset( mComposerPolyline->polylineStyleSymbol()->clone() ); + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + QgsLineSymbol* newSymbol = mComposerPolyline->polylineStyleSymbol()->clone(); QgsExpressionContext context = mComposerPolyline->createExpressionContext(); - QgsSymbolSelectorDialog d( newSymbol.data(), QgsStyle::defaultStyle(), - nullptr, this ); + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); QgsSymbolWidgetContext symbolContext; symbolContext.setExpressionContext( &context ); - d.setContext( symbolContext ); + d->setContext( symbolContext ); - if ( d.exec() == QDialog::Accepted ) - { - mComposerPolyline->beginCommand( tr( "Polyline style changed" ) ); - mComposerPolyline->setPolylineStyleSymbol( newSymbol.data() ); - updatePolylineStyle(); - mComposerPolyline->endCommand(); - } + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerPolyline->beginCommand( tr( "Polyline style changed" ) ); } void QgsComposerPolylineWidget::setGuiElementValues() @@ -78,6 +76,24 @@ void QgsComposerPolylineWidget::setGuiElementValues() updatePolylineStyle(); } +void QgsComposerPolylineWidget::updateStyleFromWidget() +{ + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mComposerPolyline->setPolylineStyleSymbol( dynamic_cast< QgsLineSymbol* >( w->symbol() ) ); + mComposerPolyline->update(); +} + +void QgsComposerPolylineWidget::cleanUpStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + updatePolylineStyle(); + mComposerPolyline->endCommand(); +} + void QgsComposerPolylineWidget::updatePolylineStyle() { if ( mComposerPolyline ) diff --git a/src/app/composer/qgscomposerpolylinewidget.h b/src/app/composer/qgscomposerpolylinewidget.h index 173dd20d9d0d..b74a8b699f09 100644 --- a/src/app/composer/qgscomposerpolylinewidget.h +++ b/src/app/composer/qgscomposerpolylinewidget.h @@ -43,6 +43,9 @@ class QgsComposerPolylineWidget: public QgsComposerItemBaseWidget, private Ui::Q /** Sets the GUI elements to the currentValues of mComposerShape*/ void setGuiElementValues(); + + void updateStyleFromWidget(); + void cleanUpStyleSelector( QgsPanelWidget* container ); }; #endif // QGSCOMPOSERPOLYLINEWIDGET_H diff --git a/src/app/composer/qgscompositionwidget.cpp b/src/app/composer/qgscompositionwidget.cpp index 536e6978fb02..873fe92b7440 100644 --- a/src/app/composer/qgscompositionwidget.cpp +++ b/src/app/composer/qgscompositionwidget.cpp @@ -28,9 +28,13 @@ #include #include //for screen resolution -QgsCompositionWidget::QgsCompositionWidget( QWidget* parent, QgsComposition* c ): QWidget( parent ), mComposition( c ) +QgsCompositionWidget::QgsCompositionWidget( QWidget* parent, QgsComposition* c )\ +: +QgsPanelWidget( parent ) +, mComposition( c ) { setupUi( this ); + setPanelTitle( tr( "Composition properties" ) ); blockSignals( true ); createPaperEntries(); @@ -133,7 +137,9 @@ QgsCompositionWidget::QgsCompositionWidget( QWidget* parent, QgsComposition* c ) blockSignals( false ); } -QgsCompositionWidget::QgsCompositionWidget(): QWidget( nullptr ), mComposition( nullptr ) +QgsCompositionWidget::QgsCompositionWidget() + : QgsPanelWidget( nullptr ) + , mComposition( nullptr ) { setupUi( this ); } @@ -247,6 +253,23 @@ QgsComposerObject::DataDefinedProperty QgsCompositionWidget::ddPropertyForWidget return QgsComposerObject::NoProperty; } +void QgsCompositionWidget::updateStyleFromWidget() +{ + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mComposition->setPageStyleSymbol( dynamic_cast< QgsFillSymbol* >( w->symbol() ) ); + mComposition->update(); +} + +void QgsCompositionWidget::cleanUpStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + updatePageStyle(); +} + void QgsCompositionWidget::updateDataDefinedProperty() { QgsDataDefinedButton* ddButton = dynamic_cast( sender() ); @@ -572,17 +595,15 @@ void QgsCompositionWidget::on_mPageStyleButton_clicked() newSymbol = new QgsFillSymbol(); } QgsExpressionContext context = mComposition->createExpressionContext(); - QgsSymbolSelectorDialog d( newSymbol, QgsStyle::defaultStyle(), coverageLayer, this ); + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); QgsSymbolWidgetContext symbolContext; symbolContext.setExpressionContext( &context ); - d.setContext( symbolContext ); + d->setContext( symbolContext ); - if ( d.exec() == QDialog::Accepted ) - { - mComposition->setPageStyleSymbol( newSymbol ); - updatePageStyle(); - } - delete newSymbol; + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); } void QgsCompositionWidget::on_mResizePageButton_clicked() diff --git a/src/app/composer/qgscompositionwidget.h b/src/app/composer/qgscompositionwidget.h index 62f01ed8ee83..4d75ce65701d 100644 --- a/src/app/composer/qgscompositionwidget.h +++ b/src/app/composer/qgscompositionwidget.h @@ -15,6 +15,7 @@ ***************************************************************************/ #include "ui_qgscompositionwidgetbase.h" +#include "qgspanelwidget.h" class QgsComposition; class QgsComposerMap; @@ -34,7 +35,7 @@ struct QgsCompositionPaper /** \ingroup app * Input widget for QgsComposition */ -class QgsCompositionWidget: public QWidget, private Ui::QgsCompositionWidgetBase +class QgsCompositionWidget: public QgsPanelWidget, private Ui::QgsCompositionWidgetBase { Q_OBJECT public: @@ -85,6 +86,9 @@ class QgsCompositionWidget: public QWidget, private Ui::QgsCompositionWidgetBase void updateVariables(); + void updateStyleFromWidget(); + void cleanUpStyleSelector( QgsPanelWidget* container ); + private: QgsComposition* mComposition; QMap mPaperMap; @@ -115,4 +119,5 @@ class QgsCompositionWidget: public QWidget, private Ui::QgsCompositionWidgetBase /** Returns the data defined property corresponding to a data defined button widget*/ virtual QgsComposerObject::DataDefinedProperty ddPropertyForWidget( QgsDataDefinedButton* widget ); + }; From 0dc5e836929770e61e3948335ed40ca46aad384b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 13:41:49 +1000 Subject: [PATCH 237/897] Fix unused variable warning --- src/core/pal/feature.cpp | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/core/pal/feature.cpp b/src/core/pal/feature.cpp index 64511d265a45..266adf1cff3c 100644 --- a/src/core/pal/feature.cpp +++ b/src/core/pal/feature.cpp @@ -1170,19 +1170,6 @@ int FeaturePart::createCurvedCandidatesAlongLine( QList< LabelPosition* >& lPos, return 0; } - //calculate overall angle of line - double lineAngle; - double bx = mapShape->x[0]; - double by = mapShape->y[0]; - double ex = mapShape->x[ mapShape->nbPoints - 1 ]; - double ey = mapShape->y[ mapShape->nbPoints - 1 ]; - if ( qgsDoubleNear( ey, by ) && qgsDoubleNear( ex, bx ) ) - { - lineAngle = 0.0; - } - else - lineAngle = atan2( ey - by, ex - bx ); - QLinkedList positions; double delta = qMax( li->label_height, total_distance / mLF->layer()->pal->line_p ); From 9263abe4a14815f9a6e09a82912fce4687c0038b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 15:57:08 +1000 Subject: [PATCH 238/897] [composer] Move all grid settings into seperate panel Now grid settings are accessed by clicking "Modify grid" from the composer map properties panel. This opens a new stacked panel with all the grid settings. This helps make the composer map widget less confusing. Before it was absolutely jammed with controls, including lots of nested groups. --- src/app/CMakeLists.txt | 2 + src/app/composer/qgscomposermapgridwidget.cpp | 1223 +++++++++++++++++ src/app/composer/qgscomposermapgridwidget.h | 146 ++ src/app/composer/qgscomposermapwidget.cpp | 1098 +-------------- src/app/composer/qgscomposermapwidget.h | 70 +- .../composer/qgscomposermapgridwidgetbase.ui | 816 +++++++++++ src/ui/composer/qgscomposermapwidgetbase.ui | 767 +---------- 7 files changed, 2267 insertions(+), 1855 deletions(-) create mode 100644 src/app/composer/qgscomposermapgridwidget.cpp create mode 100644 src/app/composer/qgscomposermapgridwidget.h create mode 100644 src/ui/composer/qgscomposermapgridwidgetbase.ui diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 8907d907a275..f452f162870b 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -139,6 +139,7 @@ SET(QGIS_APP_SRCS composer/qgscomposerlabelwidget.cpp composer/qgscomposerpicturewidget.cpp composer/qgscomposermanager.cpp + composer/qgscomposermapgridwidget.cpp composer/qgscomposermapwidget.cpp composer/qgscomposerscalebarwidget.cpp composer/qgscomposershapewidget.cpp @@ -314,6 +315,7 @@ SET (QGIS_APP_MOC_HDRS composer/qgscomposerlegenditemdialog.h composer/qgscomposerlegendlayersdialog.h composer/qgscomposermanager.h + composer/qgscomposermapgridwidget.h composer/qgscomposermapwidget.h composer/qgscomposerpicturewidget.h composer/qgscomposerscalebarwidget.h diff --git a/src/app/composer/qgscomposermapgridwidget.cpp b/src/app/composer/qgscomposermapgridwidget.cpp new file mode 100644 index 000000000000..49eddeb410df --- /dev/null +++ b/src/app/composer/qgscomposermapgridwidget.cpp @@ -0,0 +1,1223 @@ +/*************************************************************************** + qgscomposermapgridwidget.cpp + ---------------------------- + begin : October 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgscomposermapgridwidget.h" +#include "qgssymbolselectordialog.h" +#include "qgssymbol.h" +#include "qgscomposermap.h" +#include "qgsproject.h" +#include "qgssymbollayerutils.h" +#include "qgsstyle.h" +#include "qgsgenericprojectionselector.h" +#include "qgscomposition.h" +#include "qgsmapsettings.h" +#include "qgsexpressionbuilderdialog.h" + +QgsComposerMapGridWidget::QgsComposerMapGridWidget( QgsComposerMapGrid* mapGrid, QgsComposerMap* composerMap ) + : QgsComposerItemBaseWidget( nullptr, mapGrid ) + , mComposerMap( composerMap ) + , mComposerMapGrid( mapGrid ) +{ + setupUi( this ); + setPanelTitle( tr( "Map grid properties" ) ); + + blockAllSignals( true ); + + mGridTypeComboBox->insertItem( 0, tr( "Solid" ) ); + mGridTypeComboBox->insertItem( 1, tr( "Cross" ) ); + mGridTypeComboBox->insertItem( 2, tr( "Markers" ) ); + mGridTypeComboBox->insertItem( 3, tr( "Frame and annotations only" ) ); + + insertFrameDisplayEntries( mFrameDivisionsLeftComboBox ); + insertFrameDisplayEntries( mFrameDivisionsRightComboBox ); + insertFrameDisplayEntries( mFrameDivisionsTopComboBox ); + insertFrameDisplayEntries( mFrameDivisionsBottomComboBox ); + + mAnnotationFormatComboBox->addItem( tr( "Decimal" ), QgsComposerMapGrid::Decimal ); + mAnnotationFormatComboBox->addItem( tr( "Decimal with suffix" ), QgsComposerMapGrid::DecimalWithSuffix ); + mAnnotationFormatComboBox->addItem( tr( "Degree, minute" ), QgsComposerMapGrid::DegreeMinuteNoSuffix ); + mAnnotationFormatComboBox->addItem( tr( "Degree, minute with suffix" ), QgsComposerMapGrid::DegreeMinute ); + mAnnotationFormatComboBox->addItem( tr( "Degree, minute aligned" ), QgsComposerMapGrid::DegreeMinutePadded ); + mAnnotationFormatComboBox->addItem( tr( "Degree, minute, second" ), QgsComposerMapGrid::DegreeMinuteSecondNoSuffix ); + mAnnotationFormatComboBox->addItem( tr( "Degree, minute, second with suffix" ), QgsComposerMapGrid::DegreeMinuteSecond ); + mAnnotationFormatComboBox->addItem( tr( "Degree, minute, second aligned" ), QgsComposerMapGrid::DegreeMinuteSecondPadded ); + mAnnotationFormatComboBox->addItem( tr( "Custom" ), QgsComposerMapGrid::CustomFormat ); + + mAnnotationFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); + mAnnotationFontColorButton->setAllowAlpha( true ); + mAnnotationFontColorButton->setContext( "composer" ); + + insertAnnotationDisplayEntries( mAnnotationDisplayLeftComboBox ); + insertAnnotationDisplayEntries( mAnnotationDisplayRightComboBox ); + insertAnnotationDisplayEntries( mAnnotationDisplayTopComboBox ); + insertAnnotationDisplayEntries( mAnnotationDisplayBottomComboBox ); + + insertAnnotationPositionEntries( mAnnotationPositionLeftComboBox ); + insertAnnotationPositionEntries( mAnnotationPositionRightComboBox ); + insertAnnotationPositionEntries( mAnnotationPositionTopComboBox ); + insertAnnotationPositionEntries( mAnnotationPositionBottomComboBox ); + + insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxLeft ); + insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxRight ); + insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxTop ); + insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxBottom ); + + mGridFramePenColorButton->setColorDialogTitle( tr( "Select grid frame color" ) ); + mGridFramePenColorButton->setAllowAlpha( true ); + mGridFramePenColorButton->setContext( "composer" ); + mGridFramePenColorButton->setNoColorString( tr( "Transparent frame" ) ); + mGridFramePenColorButton->setShowNoColor( true ); + + mGridFrameFill1ColorButton->setColorDialogTitle( tr( "Select grid frame fill color" ) ); + mGridFrameFill1ColorButton->setAllowAlpha( true ); + mGridFrameFill1ColorButton->setContext( "composer" ); + mGridFrameFill1ColorButton->setNoColorString( tr( "Transparent fill" ) ); + mGridFrameFill1ColorButton->setShowNoColor( true ); + + mGridFrameFill2ColorButton->setColorDialogTitle( tr( "Select grid frame fill color" ) ); + mGridFrameFill2ColorButton->setAllowAlpha( true ); + mGridFrameFill2ColorButton->setContext( "composer" ); + mGridFrameFill2ColorButton->setNoColorString( tr( "Transparent fill" ) ); + mGridFrameFill2ColorButton->setShowNoColor( true ); + + //set initial state of frame style controls + toggleFrameControls( false, false, false ); + + updateGuiElements(); + + blockAllSignals( false ); +} + +QgsComposerMapGridWidget::~QgsComposerMapGridWidget() +{ +} + +void QgsComposerMapGridWidget::populateDataDefinedButtons() +{ + // none for now +} + + +void QgsComposerMapGridWidget::updateGridLineStyleFromWidget() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mComposerMapGrid->setLineSymbol( dynamic_cast< QgsLineSymbol* >( w->symbol()->clone() ) ); + mComposerMap->update(); +} + +void QgsComposerMapGridWidget::cleanUpGridLineStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + updateGridLineSymbolMarker(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::updateGridMarkerStyleFromWidget() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + QgsSymbolSelectorWidget* w = qobject_cast( sender() ); + mComposerMapGrid->setMarkerSymbol( dynamic_cast< QgsMarkerSymbol* >( w->symbol()->clone() ) ); + mComposerMap->update(); +} + +void QgsComposerMapGridWidget::cleanUpGridMarkerStyleSelector( QgsPanelWidget* container ) +{ + QgsSymbolSelectorWidget* w = qobject_cast( container ); + if ( !w ) + return; + + delete w->symbol(); + + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + updateGridMarkerSymbolMarker(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::setGuiElementValues() +{ + updateGuiElements(); +} + +void QgsComposerMapGridWidget::updateGuiElements() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + blockAllSignals( true ); + populateDataDefinedButtons(); + setGridItems(); + blockAllSignals( false ); +} + +void QgsComposerMapGridWidget::blockAllSignals( bool block ) +{ + //grid + mGridTypeComboBox->blockSignals( block ); + mIntervalXSpinBox->blockSignals( block ); + mIntervalYSpinBox->blockSignals( block ); + mOffsetXSpinBox->blockSignals( block ); + mOffsetYSpinBox->blockSignals( block ); + mCrossWidthSpinBox->blockSignals( block ); + mFrameStyleComboBox->blockSignals( block ); + mFrameWidthSpinBox->blockSignals( block ); + mGridLineStyleButton->blockSignals( block ); + mMapGridUnitComboBox->blockSignals( block ); + mGridFramePenSizeSpinBox->blockSignals( block ); + mGridFramePenColorButton->blockSignals( block ); + mGridFrameFill1ColorButton->blockSignals( block ); + mGridFrameFill2ColorButton->blockSignals( block ); + mGridBlendComboBox->blockSignals( block ); + mCheckGridLeftSide->blockSignals( block ); + mCheckGridRightSide->blockSignals( block ); + mCheckGridTopSide->blockSignals( block ); + mCheckGridBottomSide->blockSignals( block ); + mFrameDivisionsLeftComboBox->blockSignals( block ); + mFrameDivisionsRightComboBox->blockSignals( block ); + mFrameDivisionsTopComboBox->blockSignals( block ); + mFrameDivisionsBottomComboBox->blockSignals( block ); + + //grid annotation + mDrawAnnotationGroupBox->blockSignals( block ); + mAnnotationFormatComboBox->blockSignals( block ); + mAnnotationDisplayLeftComboBox->blockSignals( block ); + mAnnotationPositionLeftComboBox->blockSignals( block ); + mAnnotationDirectionComboBoxLeft->blockSignals( block ); + mAnnotationDisplayRightComboBox->blockSignals( block ); + mAnnotationPositionRightComboBox->blockSignals( block ); + mAnnotationDirectionComboBoxRight->blockSignals( block ); + mAnnotationDisplayTopComboBox->blockSignals( block ); + mAnnotationPositionTopComboBox->blockSignals( block ); + mAnnotationDirectionComboBoxTop->blockSignals( block ); + mAnnotationDisplayBottomComboBox->blockSignals( block ); + mAnnotationPositionBottomComboBox->blockSignals( block ); + mAnnotationDirectionComboBoxBottom->blockSignals( block ); + mDistanceToMapFrameSpinBox->blockSignals( block ); + mCoordinatePrecisionSpinBox->blockSignals( block ); + mAnnotationFontColorButton->blockSignals( block ); + mAnnotationFontButton->blockSignals( block ); +} + +void QgsComposerMapGridWidget::handleChangedFrameDisplay( QgsComposerMapGrid::BorderSide border, const QgsComposerMapGrid::DisplayMode mode ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Frame divisions changed" ) ); + mComposerMapGrid->setFrameDivisions( mode, border ); + mComposerMap->endCommand(); + mComposerMap->updateBoundingRect(); +} + +void QgsComposerMapGridWidget::handleChangedAnnotationDisplay( QgsComposerMapGrid::BorderSide border, const QString &text ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Annotation display changed" ) ); + if ( text == tr( "Show all" ) ) + { + mComposerMapGrid->setAnnotationDisplay( QgsComposerMapGrid::ShowAll, border ); + } + else if ( text == tr( "Show latitude only" ) ) + { + mComposerMapGrid->setAnnotationDisplay( QgsComposerMapGrid::LatitudeOnly, border ); + } + else if ( text == tr( "Show longitude only" ) ) + { + mComposerMapGrid->setAnnotationDisplay( QgsComposerMapGrid::LongitudeOnly, border ); + } + else //disabled + { + mComposerMapGrid->setAnnotationDisplay( QgsComposerMapGrid::HideAll, border ); + } + + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::toggleFrameControls( bool frameEnabled, bool frameFillEnabled, bool frameSizeEnabled ) +{ + //set status of frame controls + mFrameWidthSpinBox->setEnabled( frameSizeEnabled ); + mGridFramePenSizeSpinBox->setEnabled( frameEnabled ); + mGridFramePenColorButton->setEnabled( frameEnabled ); + mGridFrameFill1ColorButton->setEnabled( frameFillEnabled ); + mGridFrameFill2ColorButton->setEnabled( frameFillEnabled ); + mFrameWidthLabel->setEnabled( frameSizeEnabled ); + mFramePenLabel->setEnabled( frameEnabled ); + mFrameFillLabel->setEnabled( frameFillEnabled ); + mCheckGridLeftSide->setEnabled( frameEnabled ); + mCheckGridRightSide->setEnabled( frameEnabled ); + mCheckGridTopSide->setEnabled( frameEnabled ); + mCheckGridBottomSide->setEnabled( frameEnabled ); + mFrameDivisionsLeftComboBox->setEnabled( frameEnabled ); + mFrameDivisionsRightComboBox->setEnabled( frameEnabled ); + mFrameDivisionsTopComboBox->setEnabled( frameEnabled ); + mFrameDivisionsBottomComboBox->setEnabled( frameEnabled ); + mLeftDivisionsLabel->setEnabled( frameEnabled ); + mRightDivisionsLabel->setEnabled( frameEnabled ); + mTopDivisionsLabel->setEnabled( frameEnabled ); + mBottomDivisionsLabel->setEnabled( frameEnabled ); +} + +void QgsComposerMapGridWidget::insertAnnotationPositionEntries( QComboBox* c ) +{ + c->insertItem( 0, tr( "Inside frame" ) ); + c->insertItem( 1, tr( "Outside frame" ) ); +} + +void QgsComposerMapGridWidget::insertAnnotationDirectionEntries( QComboBox* c ) +{ + c->addItem( tr( "Horizontal" ), QgsComposerMapGrid::Horizontal ); + c->addItem( tr( "Vertical ascending" ), QgsComposerMapGrid::Vertical ); + c->addItem( tr( "Vertical descending" ), QgsComposerMapGrid::VerticalDescending ); +} + +void QgsComposerMapGridWidget::initFrameDisplayBox( QComboBox *c, QgsComposerMapGrid::DisplayMode display ) +{ + if ( !c ) + { + return; + } + c->setCurrentIndex( c->findData( display ) ); +} + +void QgsComposerMapGridWidget::initAnnotationDisplayBox( QComboBox *c, QgsComposerMapGrid::DisplayMode display ) +{ + if ( !c ) + { + return; + } + + if ( display == QgsComposerMapGrid::ShowAll ) + { + c->setCurrentIndex( c->findText( tr( "Show all" ) ) ); + } + else if ( display == QgsComposerMapGrid::LatitudeOnly ) + { + c->setCurrentIndex( c->findText( tr( "Show latitude only" ) ) ); + } + else if ( display == QgsComposerMapGrid::LongitudeOnly ) + { + c->setCurrentIndex( c->findText( tr( "Show longitude only" ) ) ); + } + else + { + c->setCurrentIndex( c->findText( tr( "Disabled" ) ) ); + } +} + +void QgsComposerMapGridWidget::handleChangedAnnotationPosition( QgsComposerMapGrid::BorderSide border, const QString& text ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Annotation position changed" ) ); + if ( text == tr( "Inside frame" ) ) + { + mComposerMapGrid->setAnnotationPosition( QgsComposerMapGrid::InsideMapFrame, border ); + } + else //Outside frame + { + mComposerMapGrid->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, border ); + } + + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::handleChangedAnnotationDirection( QgsComposerMapGrid::BorderSide border, QgsComposerMapGrid::AnnotationDirection direction ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Changed annotation direction" ) ); + mComposerMapGrid->setAnnotationDirection( direction, border ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::insertFrameDisplayEntries( QComboBox *c ) +{ + c->addItem( tr( "All" ), QgsComposerMapGrid::ShowAll ); + c->addItem( tr( "Latitude/Y only" ), QgsComposerMapGrid::LatitudeOnly ); + c->addItem( tr( "Longitude/X only" ), QgsComposerMapGrid::LongitudeOnly ); +} + +void QgsComposerMapGridWidget::insertAnnotationDisplayEntries( QComboBox *c ) +{ + c->insertItem( 0, tr( "Show all" ) ); + c->insertItem( 1, tr( "Show latitude only" ) ); + c->insertItem( 2, tr( "Show longitude only" ) ); + c->insertItem( 3, tr( "Disabled" ) ); +} + +void QgsComposerMapGridWidget::initAnnotationPositionBox( QComboBox* c, QgsComposerMapGrid::AnnotationPosition pos ) +{ + if ( !c ) + { + return; + } + + if ( pos == QgsComposerMapGrid::InsideMapFrame ) + { + c->setCurrentIndex( c->findText( tr( "Inside frame" ) ) ); + } + else + { + c->setCurrentIndex( c->findText( tr( "Outside frame" ) ) ); + } +} + +void QgsComposerMapGridWidget::initAnnotationDirectionBox( QComboBox* c, QgsComposerMapGrid::AnnotationDirection dir ) +{ + if ( !c ) + { + return; + } + c->setCurrentIndex( c->findData( dir ) ); +} + +bool QgsComposerMapGridWidget::hasPredefinedScales() const +{ + // first look at project's scales + QStringList scales( QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ) ); + bool hasProjectScales( QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ) ); + if ( !hasProjectScales || scales.isEmpty() ) + { + // default to global map tool scales + QSettings settings; + QString scalesStr( settings.value( "Map/scales", PROJECT_SCALES ).toString() ); + QStringList myScalesList = scalesStr.split( ',' ); + return !myScalesList.isEmpty() && myScalesList[0] != ""; + } + return true; +} + +void QgsComposerMapGridWidget::setGridItems() +{ + if ( !mComposerMapGrid ) + { + return; + } + + mIntervalXSpinBox->setValue( mComposerMapGrid->intervalX() ); + mIntervalYSpinBox->setValue( mComposerMapGrid->intervalY() ); + mOffsetXSpinBox->setValue( mComposerMapGrid->offsetX() ); + mOffsetYSpinBox->setValue( mComposerMapGrid->offsetY() ); + mCrossWidthSpinBox->setValue( mComposerMapGrid->crossLength() ); + mFrameWidthSpinBox->setValue( mComposerMapGrid->frameWidth() ); + mGridFramePenSizeSpinBox->setValue( mComposerMapGrid->framePenSize() ); + mGridFramePenColorButton->setColor( mComposerMapGrid->framePenColor() ); + mGridFrameFill1ColorButton->setColor( mComposerMapGrid->frameFillColor1() ); + mGridFrameFill2ColorButton->setColor( mComposerMapGrid->frameFillColor2() ); + + QgsComposerMapGrid::GridStyle gridStyle = mComposerMapGrid->style(); + switch ( gridStyle ) + { + case QgsComposerMapGrid::Cross: + mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Cross" ) ) ); + mCrossWidthSpinBox->setVisible( true ); + mCrossWidthLabel->setVisible( true ); + mGridLineStyleButton->setVisible( true ); + mLineStyleLabel->setVisible( true ); + mGridMarkerStyleButton->setVisible( false ); + mMarkerStyleLabel->setVisible( false ); + mGridBlendComboBox->setVisible( true ); + mGridBlendLabel->setVisible( true ); + break; + case QgsComposerMapGrid::Markers: + mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Markers" ) ) ); + mCrossWidthSpinBox->setVisible( false ); + mCrossWidthLabel->setVisible( false ); + mGridLineStyleButton->setVisible( false ); + mLineStyleLabel->setVisible( false ); + mGridMarkerStyleButton->setVisible( true ); + mMarkerStyleLabel->setVisible( true ); + mGridBlendComboBox->setVisible( true ); + mGridBlendLabel->setVisible( true ); + break; + case QgsComposerMapGrid::Solid: + mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Solid" ) ) ); + mCrossWidthSpinBox->setVisible( false ); + mCrossWidthLabel->setVisible( false ); + mGridLineStyleButton->setVisible( true ); + mLineStyleLabel->setVisible( true ); + mGridMarkerStyleButton->setVisible( false ); + mMarkerStyleLabel->setVisible( false ); + mGridBlendComboBox->setVisible( true ); + mGridBlendLabel->setVisible( true ); + break; + case QgsComposerMapGrid::FrameAnnotationsOnly: + mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Frame and annotations only" ) ) ); + mCrossWidthSpinBox->setVisible( false ); + mCrossWidthLabel->setVisible( false ); + mGridLineStyleButton->setVisible( false ); + mLineStyleLabel->setVisible( false ); + mGridMarkerStyleButton->setVisible( false ); + mMarkerStyleLabel->setVisible( false ); + mGridBlendComboBox->setVisible( false ); + mGridBlendLabel->setVisible( false ); + break; + } + + //grid frame + mFrameWidthSpinBox->setValue( mComposerMapGrid->frameWidth() ); + QgsComposerMapGrid::FrameStyle gridFrameStyle = mComposerMapGrid->frameStyle(); + switch ( gridFrameStyle ) + { + case QgsComposerMapGrid::Zebra: + mFrameStyleComboBox->setCurrentIndex( 1 ); + toggleFrameControls( true, true, true ); + break; + case QgsComposerMapGrid::InteriorTicks: + mFrameStyleComboBox->setCurrentIndex( 2 ); + toggleFrameControls( true, false, true ); + break; + case QgsComposerMapGrid::ExteriorTicks: + mFrameStyleComboBox->setCurrentIndex( 3 ); + toggleFrameControls( true, false, true ); + break; + case QgsComposerMapGrid::InteriorExteriorTicks: + mFrameStyleComboBox->setCurrentIndex( 4 ); + toggleFrameControls( true, false, true ); + break; + case QgsComposerMapGrid::LineBorder: + mFrameStyleComboBox->setCurrentIndex( 5 ); + toggleFrameControls( true, false, false ); + break; + default: + mFrameStyleComboBox->setCurrentIndex( 0 ); + toggleFrameControls( false, false, false ); + break; + } + + mCheckGridLeftSide->setChecked( mComposerMapGrid->testFrameSideFlag( QgsComposerMapGrid::FrameLeft ) ); + mCheckGridRightSide->setChecked( mComposerMapGrid->testFrameSideFlag( QgsComposerMapGrid::FrameRight ) ); + mCheckGridTopSide->setChecked( mComposerMapGrid->testFrameSideFlag( QgsComposerMapGrid::FrameTop ) ); + mCheckGridBottomSide->setChecked( mComposerMapGrid->testFrameSideFlag( QgsComposerMapGrid::FrameBottom ) ); + + initFrameDisplayBox( mFrameDivisionsLeftComboBox, mComposerMapGrid->frameDivisions( QgsComposerMapGrid::Left ) ); + initFrameDisplayBox( mFrameDivisionsRightComboBox, mComposerMapGrid->frameDivisions( QgsComposerMapGrid::Right ) ); + initFrameDisplayBox( mFrameDivisionsTopComboBox, mComposerMapGrid->frameDivisions( QgsComposerMapGrid::Top ) ); + initFrameDisplayBox( mFrameDivisionsBottomComboBox, mComposerMapGrid->frameDivisions( QgsComposerMapGrid::Bottom ) ); + + //line style + updateGridLineSymbolMarker(); + //marker style + updateGridMarkerSymbolMarker(); + + mGridBlendComboBox->setBlendMode( mComposerMapGrid->blendMode() ); + + mDrawAnnotationGroupBox->setChecked( mComposerMapGrid->annotationEnabled() ); + initAnnotationDisplayBox( mAnnotationDisplayLeftComboBox, mComposerMapGrid->annotationDisplay( QgsComposerMapGrid::Left ) ); + initAnnotationDisplayBox( mAnnotationDisplayRightComboBox, mComposerMapGrid->annotationDisplay( QgsComposerMapGrid::Right ) ); + initAnnotationDisplayBox( mAnnotationDisplayTopComboBox, mComposerMapGrid->annotationDisplay( QgsComposerMapGrid::Top ) ); + initAnnotationDisplayBox( mAnnotationDisplayBottomComboBox, mComposerMapGrid->annotationDisplay( QgsComposerMapGrid::Bottom ) ); + + initAnnotationPositionBox( mAnnotationPositionLeftComboBox, mComposerMapGrid->annotationPosition( QgsComposerMapGrid::Left ) ); + initAnnotationPositionBox( mAnnotationPositionRightComboBox, mComposerMapGrid->annotationPosition( QgsComposerMapGrid::Right ) ); + initAnnotationPositionBox( mAnnotationPositionTopComboBox, mComposerMapGrid->annotationPosition( QgsComposerMapGrid::Top ) ); + initAnnotationPositionBox( mAnnotationPositionBottomComboBox, mComposerMapGrid->annotationPosition( QgsComposerMapGrid::Bottom ) ); + + initAnnotationDirectionBox( mAnnotationDirectionComboBoxLeft, mComposerMapGrid->annotationDirection( QgsComposerMapGrid::Left ) ); + initAnnotationDirectionBox( mAnnotationDirectionComboBoxRight, mComposerMapGrid->annotationDirection( QgsComposerMapGrid::Right ) ); + initAnnotationDirectionBox( mAnnotationDirectionComboBoxTop, mComposerMapGrid->annotationDirection( QgsComposerMapGrid::Top ) ); + initAnnotationDirectionBox( mAnnotationDirectionComboBoxBottom, mComposerMapGrid->annotationDirection( QgsComposerMapGrid::Bottom ) ); + + mAnnotationFontColorButton->setColor( mComposerMapGrid->annotationFontColor() ); + + mAnnotationFormatComboBox->setCurrentIndex( mAnnotationFormatComboBox->findData( mComposerMapGrid->annotationFormat() ) ); + mAnnotationFormatButton->setEnabled( mComposerMapGrid->annotationFormat() == QgsComposerMapGrid::CustomFormat ); + mDistanceToMapFrameSpinBox->setValue( mComposerMapGrid->annotationFrameDistance() ); + mCoordinatePrecisionSpinBox->setValue( mComposerMapGrid->annotationPrecision() ); + + //Unit + QgsComposerMapGrid::GridUnit gridUnit = mComposerMapGrid->units(); + if ( gridUnit == QgsComposerMapGrid::MapUnit ) + { + mMapGridUnitComboBox->setCurrentIndex( mMapGridUnitComboBox->findText( tr( "Map unit" ) ) ); + } + else if ( gridUnit == QgsComposerMapGrid::MM ) + { + mMapGridUnitComboBox->setCurrentIndex( mMapGridUnitComboBox->findText( tr( "Millimeter" ) ) ); + } + else if ( gridUnit == QgsComposerMapGrid::CM ) + { + mMapGridUnitComboBox->setCurrentIndex( mMapGridUnitComboBox->findText( tr( "Centimeter" ) ) ); + } + + //CRS button + QgsCoordinateReferenceSystem gridCrs = mComposerMapGrid->crs(); + QString crsButtonText = gridCrs.isValid() ? gridCrs.authid() : tr( "change..." ); + mMapGridCRSButton->setText( crsButtonText ); +} + +void QgsComposerMapGridWidget::updateGridLineSymbolMarker() +{ + if ( mComposerMapGrid ) + { + QgsLineSymbol* nonConstSymbol = const_cast( mComposerMapGrid->lineSymbol() ); //bad + QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( nonConstSymbol, mGridLineStyleButton->iconSize() ); + mGridLineStyleButton->setIcon( icon ); + } +} + +void QgsComposerMapGridWidget::updateGridMarkerSymbolMarker() +{ + if ( mComposerMapGrid ) + { + QgsMarkerSymbol* nonConstSymbol = const_cast( mComposerMapGrid->markerSymbol() ); //bad + QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( nonConstSymbol, mGridMarkerStyleButton->iconSize() ); + mGridMarkerStyleButton->setIcon( icon ); + } +} + +void QgsComposerMapGridWidget::on_mGridLineStyleButton_clicked() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + + QgsLineSymbol* newSymbol = static_cast( mComposerMapGrid->lineSymbol()->clone() ); + QgsExpressionContext context = mComposerMap->createExpressionContext(); + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d->setContext( symbolContext ); + + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateGridLineStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpGridLineStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerMap->beginCommand( tr( "Grid line style changed" ) ); +} + +void QgsComposerMapGridWidget::on_mGridMarkerStyleButton_clicked() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + // use the atlas coverage layer, if any + QgsVectorLayer* coverageLayer = atlasCoverageLayer(); + + QgsMarkerSymbol* newSymbol = static_cast( mComposerMapGrid->markerSymbol()->clone() ); + QgsExpressionContext context = mComposerMap->createExpressionContext(); + + QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); + QgsSymbolWidgetContext symbolContext; + symbolContext.setExpressionContext( &context ); + d->setContext( symbolContext ); + + connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateGridMarkerStyleFromWidget() ) ); + connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpGridMarkerStyleSelector( QgsPanelWidget* ) ) ); + openPanel( d ); + mComposerMap->beginCommand( tr( "Grid markers style changed" ) ); +} + +void QgsComposerMapGridWidget::on_mIntervalXSpinBox_editingFinished() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid interval changed" ) ); + mComposerMapGrid->setIntervalX( mIntervalXSpinBox->value() ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mIntervalYSpinBox_editingFinished() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid interval changed" ) ); + mComposerMapGrid->setIntervalY( mIntervalYSpinBox->value() ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mOffsetXSpinBox_valueChanged( double value ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid offset changed" ) ); + mComposerMapGrid->setOffsetX( value ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mOffsetYSpinBox_valueChanged( double value ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid offset changed" ) ); + mComposerMapGrid->setOffsetY( value ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mCrossWidthSpinBox_valueChanged( double val ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Cross width changed" ) ); + mComposerMapGrid->setCrossLength( val ); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mFrameWidthSpinBox_valueChanged( double val ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Frame width changed" ) ); + mComposerMapGrid->setFrameWidth( val ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mCheckGridLeftSide_toggled( bool checked ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Frame left side changed" ) ); + mComposerMapGrid->setFrameSideFlag( QgsComposerMapGrid::FrameLeft, checked ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mCheckGridRightSide_toggled( bool checked ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Frame right side changed" ) ); + mComposerMapGrid->setFrameSideFlag( QgsComposerMapGrid::FrameRight, checked ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mCheckGridTopSide_toggled( bool checked ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Frame top side changed" ) ); + mComposerMapGrid->setFrameSideFlag( QgsComposerMapGrid::FrameTop, checked ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mCheckGridBottomSide_toggled( bool checked ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Frame bottom side changed" ) ); + mComposerMapGrid->setFrameSideFlag( QgsComposerMapGrid::FrameBottom, checked ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mFrameDivisionsLeftComboBox_currentIndexChanged( int index ) +{ + handleChangedFrameDisplay( QgsComposerMapGrid::Left, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsLeftComboBox->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mFrameDivisionsRightComboBox_currentIndexChanged( int index ) +{ + handleChangedFrameDisplay( QgsComposerMapGrid::Right, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsRightComboBox->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mFrameDivisionsTopComboBox_currentIndexChanged( int index ) +{ + handleChangedFrameDisplay( QgsComposerMapGrid::Top, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsTopComboBox->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mFrameDivisionsBottomComboBox_currentIndexChanged( int index ) +{ + handleChangedFrameDisplay( QgsComposerMapGrid::Bottom, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsBottomComboBox->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mGridFramePenSizeSpinBox_valueChanged( double d ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Changed grid frame line thickness" ) ); + mComposerMapGrid->setFramePenSize( d ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mGridFramePenColorButton_colorChanged( const QColor& newColor ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid frame color changed" ), QgsComposerMergeCommand::ComposerMapGridFramePenColor ); + mComposerMapGrid->setFramePenColor( newColor ); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mGridFrameFill1ColorButton_colorChanged( const QColor& newColor ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid frame first fill color changed" ), QgsComposerMergeCommand::ComposerMapGridFrameFill1Color ); + mComposerMapGrid->setFrameFillColor1( newColor ); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mGridFrameFill2ColorButton_colorChanged( const QColor& newColor ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid frame second fill color changed" ), QgsComposerMergeCommand::ComposerMapGridFrameFill2Color ); + mComposerMapGrid->setFrameFillColor2( newColor ); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mFrameStyleComboBox_currentIndexChanged( const QString& text ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Changed grid frame style" ) ); + if ( text == tr( "Zebra" ) ) + { + mComposerMapGrid->setFrameStyle( QgsComposerMapGrid::Zebra ); + toggleFrameControls( true, true, true ); + } + else if ( text == tr( "Interior ticks" ) ) + { + mComposerMapGrid->setFrameStyle( QgsComposerMapGrid::InteriorTicks ); + toggleFrameControls( true, false, true ); + } + else if ( text == tr( "Exterior ticks" ) ) + { + mComposerMapGrid->setFrameStyle( QgsComposerMapGrid::ExteriorTicks ); + toggleFrameControls( true, false, true ); + } + else if ( text == tr( "Interior and exterior ticks" ) ) + { + mComposerMapGrid->setFrameStyle( QgsComposerMapGrid::InteriorExteriorTicks ); + toggleFrameControls( true, false, true ); + } + else if ( text == tr( "Line border" ) ) + { + mComposerMapGrid->setFrameStyle( QgsComposerMapGrid::LineBorder ); + toggleFrameControls( true, false, false ); + } + else //no frame + { + mComposerMapGrid->setFrameStyle( QgsComposerMapGrid::NoFrame ); + toggleFrameControls( false, false, false ); + } + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mMapGridUnitComboBox_currentIndexChanged( const QString& text ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Changed grid unit" ) ); + if ( text == tr( "Map unit" ) ) + { + mComposerMapGrid->setUnits( QgsComposerMapGrid::MapUnit ); + } + else if ( text == tr( "Millimeter" ) ) + { + mComposerMapGrid->setUnits( QgsComposerMapGrid::MM ); + } + else if ( text == tr( "Centimeter" ) ) + { + mComposerMapGrid->setUnits( QgsComposerMapGrid::CM ); + } + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mGridBlendComboBox_currentIndexChanged( int index ) +{ + Q_UNUSED( index ); + if ( mComposerMapGrid ) + { + mComposerMap->beginCommand( tr( "Grid blend mode changed" ) ); + mComposerMapGrid->setBlendMode( mGridBlendComboBox->blendMode() ); + mComposerMap->update(); + mComposerMap->endCommand(); + } + +} + +void QgsComposerMapGridWidget::on_mGridTypeComboBox_currentIndexChanged( const QString& text ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Grid type changed" ) ); + if ( text == tr( "Cross" ) ) + { + mComposerMapGrid->setStyle( QgsComposerMapGrid::Cross ); + mCrossWidthSpinBox->setVisible( true ); + mCrossWidthLabel->setVisible( true ); + mGridLineStyleButton->setVisible( true ); + mLineStyleLabel->setVisible( true ); + mGridMarkerStyleButton->setVisible( false ); + mMarkerStyleLabel->setVisible( false ); + mGridBlendComboBox->setVisible( true ); + mGridBlendLabel->setVisible( true ); + } + else if ( text == tr( "Markers" ) ) + { + mComposerMapGrid->setStyle( QgsComposerMapGrid::Markers ); + mCrossWidthSpinBox->setVisible( false ); + mCrossWidthLabel->setVisible( false ); + mGridLineStyleButton->setVisible( false ); + mLineStyleLabel->setVisible( false ); + mGridMarkerStyleButton->setVisible( true ); + mMarkerStyleLabel->setVisible( true ); + mGridBlendComboBox->setVisible( true ); + mGridBlendLabel->setVisible( true ); + } + else if ( text == tr( "Solid" ) ) + { + mComposerMapGrid->setStyle( QgsComposerMapGrid::Solid ); + mCrossWidthSpinBox->setVisible( false ); + mCrossWidthLabel->setVisible( false ); + mGridLineStyleButton->setVisible( true ); + mLineStyleLabel->setVisible( true ); + mGridMarkerStyleButton->setVisible( false ); + mMarkerStyleLabel->setVisible( false ); + mGridBlendComboBox->setVisible( true ); + mGridBlendLabel->setVisible( true ); + } + else + { + mComposerMapGrid->setStyle( QgsComposerMapGrid::FrameAnnotationsOnly ); + mCrossWidthSpinBox->setVisible( false ); + mCrossWidthLabel->setVisible( false ); + mGridLineStyleButton->setVisible( false ); + mLineStyleLabel->setVisible( false ); + mGridMarkerStyleButton->setVisible( false ); + mMarkerStyleLabel->setVisible( false ); + mGridBlendComboBox->setVisible( false ); + mGridBlendLabel->setVisible( false ); + } + + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mMapGridCRSButton_clicked() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + QgsGenericProjectionSelector crsDialog( this ); + QgsCoordinateReferenceSystem crs = mComposerMapGrid->crs(); + QString currentAuthId = crs.isValid() ? crs.authid() : mComposerMap->composition()->mapSettings().destinationCrs().authid(); + crsDialog.setSelectedAuthId( currentAuthId ); + + if ( crsDialog.exec() == QDialog::Accepted ) + { + mComposerMap->beginCommand( tr( "Grid CRS changed" ) ); + QString selectedAuthId = crsDialog.selectedAuthId(); + mComposerMapGrid->setCrs( QgsCoordinateReferenceSystem( selectedAuthId ) ); + mComposerMap->updateBoundingRect(); + mMapGridCRSButton->setText( selectedAuthId ); + mComposerMap->endCommand(); + } +} + +void QgsComposerMapGridWidget::on_mDrawAnnotationGroupBox_toggled( bool state ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Annotation toggled" ) ); + mComposerMapGrid->setAnnotationEnabled( state ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mAnnotationFormatButton_clicked() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + QgsExpressionContext expressionContext = mComposerMapGrid->createExpressionContext(); + + QgsExpressionBuilderDialog exprDlg( nullptr, mComposerMapGrid->annotationExpression(), this, "generic", expressionContext ); + exprDlg.setWindowTitle( tr( "Expression based annotation" ) ); + + if ( exprDlg.exec() == QDialog::Accepted ) + { + QString expression = exprDlg.expressionText(); + mComposerMap->beginCommand( tr( "Annotation format changed" ) ); + mComposerMapGrid->setAnnotationExpression( expression ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); + } +} + +void QgsComposerMapGridWidget::on_mAnnotationDisplayLeftComboBox_currentIndexChanged( const QString &text ) +{ + handleChangedAnnotationDisplay( QgsComposerMapGrid::Left, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDisplayRightComboBox_currentIndexChanged( const QString &text ) +{ + handleChangedAnnotationDisplay( QgsComposerMapGrid::Right, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDisplayTopComboBox_currentIndexChanged( const QString &text ) +{ + handleChangedAnnotationDisplay( QgsComposerMapGrid::Top, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDisplayBottomComboBox_currentIndexChanged( const QString &text ) +{ + handleChangedAnnotationDisplay( QgsComposerMapGrid::Bottom, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationPositionLeftComboBox_currentIndexChanged( const QString& text ) +{ + handleChangedAnnotationPosition( QgsComposerMapGrid::Left, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationPositionRightComboBox_currentIndexChanged( const QString& text ) +{ + handleChangedAnnotationPosition( QgsComposerMapGrid::Right, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationPositionTopComboBox_currentIndexChanged( const QString& text ) +{ + handleChangedAnnotationPosition( QgsComposerMapGrid::Top, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationPositionBottomComboBox_currentIndexChanged( const QString& text ) +{ + handleChangedAnnotationPosition( QgsComposerMapGrid::Bottom, text ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDirectionComboBoxLeft_currentIndexChanged( int index ) +{ + handleChangedAnnotationDirection( QgsComposerMapGrid::Left, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxLeft->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDirectionComboBoxRight_currentIndexChanged( int index ) +{ + handleChangedAnnotationDirection( QgsComposerMapGrid::Right, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxRight->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDirectionComboBoxTop_currentIndexChanged( int index ) +{ + handleChangedAnnotationDirection( QgsComposerMapGrid::Top, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxTop->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mAnnotationDirectionComboBoxBottom_currentIndexChanged( int index ) +{ + handleChangedAnnotationDirection( QgsComposerMapGrid::Bottom, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxBottom->itemData( index ).toInt() ); +} + +void QgsComposerMapGridWidget::on_mDistanceToMapFrameSpinBox_valueChanged( double d ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Annotation distance changed" ), QgsComposerMergeCommand::ComposerMapAnnotationDistance ); + mComposerMapGrid->setAnnotationFrameDistance( d ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mAnnotationFontButton_clicked() +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + bool ok; + QFont newFont = QgisGui::getFont( ok, mComposerMapGrid->annotationFont() ); + if ( ok ) + { + mComposerMap->beginCommand( tr( "Annotation font changed" ) ); + mComposerMapGrid->setAnnotationFont( newFont ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); + } +} + +void QgsComposerMapGridWidget::on_mAnnotationFontColorButton_colorChanged( const QColor& color ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Annotation color changed" ), QgsComposerMergeCommand::ComposerMapGridAnnotationFontColor ); + mComposerMapGrid->setAnnotationFontColor( color ); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mAnnotationFormatComboBox_currentIndexChanged( int index ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + + mComposerMap->beginCommand( tr( "Annotation format changed" ) ); + + mComposerMapGrid->setAnnotationFormat(( QgsComposerMapGrid::AnnotationFormat )mAnnotationFormatComboBox->itemData( index ).toInt() ); + mAnnotationFormatButton->setEnabled( mComposerMapGrid->annotationFormat() == QgsComposerMapGrid::CustomFormat ); + + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} + +void QgsComposerMapGridWidget::on_mCoordinatePrecisionSpinBox_valueChanged( int value ) +{ + if ( !mComposerMapGrid || !mComposerMap ) + { + return; + } + mComposerMap->beginCommand( tr( "Changed annotation precision" ) ); + mComposerMapGrid->setAnnotationPrecision( value ); + mComposerMap->updateBoundingRect(); + mComposerMap->update(); + mComposerMap->endCommand(); +} diff --git a/src/app/composer/qgscomposermapgridwidget.h b/src/app/composer/qgscomposermapgridwidget.h new file mode 100644 index 000000000000..b4c55073160e --- /dev/null +++ b/src/app/composer/qgscomposermapgridwidget.h @@ -0,0 +1,146 @@ +/*************************************************************************** + qgscomposermapgridwidget.h + ---------------------- + begin : October 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSCOMPOSERMAPGRIDWIDGET_H +#define QGSCOMPOSERMAPGRIDWIDGET_H + +#include "ui_qgscomposermapgridwidgetbase.h" +#include "qgscomposeritemwidget.h" +#include "qgscomposermapgrid.h" + +/** \ingroup app + * Input widget for the configuration of QgsComposerMapGrids + * */ +class QgsComposerMapGridWidget: public QgsComposerItemBaseWidget, private Ui::QgsComposerMapGridWidgetBase +{ + Q_OBJECT + + public: + explicit QgsComposerMapGridWidget( QgsComposerMapGrid* mapGrid, QgsComposerMap* composerMap ); + virtual ~QgsComposerMapGridWidget(); + + public slots: + + void setGridItems(); + void on_mGridLineStyleButton_clicked(); + void on_mGridMarkerStyleButton_clicked(); + void on_mIntervalXSpinBox_editingFinished(); + void on_mIntervalYSpinBox_editingFinished(); + void on_mOffsetXSpinBox_valueChanged( double value ); + void on_mOffsetYSpinBox_valueChanged( double value ); + void on_mCrossWidthSpinBox_valueChanged( double val ); + void on_mFrameWidthSpinBox_valueChanged( double val ); + void on_mFrameStyleComboBox_currentIndexChanged( const QString& text ); + void on_mGridFramePenSizeSpinBox_valueChanged( double d ); + void on_mGridFramePenColorButton_colorChanged( const QColor& newColor ); + void on_mGridFrameFill1ColorButton_colorChanged( const QColor& newColor ); + void on_mGridFrameFill2ColorButton_colorChanged( const QColor& newColor ); + void on_mGridTypeComboBox_currentIndexChanged( const QString& text ); + void on_mMapGridCRSButton_clicked(); + void on_mMapGridUnitComboBox_currentIndexChanged( const QString& text ); + void on_mGridBlendComboBox_currentIndexChanged( int index ); + void on_mCheckGridLeftSide_toggled( bool checked ); + void on_mCheckGridRightSide_toggled( bool checked ); + void on_mCheckGridTopSide_toggled( bool checked ); + void on_mCheckGridBottomSide_toggled( bool checked ); + + //frame divisions display + void on_mFrameDivisionsLeftComboBox_currentIndexChanged( int index ); + void on_mFrameDivisionsRightComboBox_currentIndexChanged( int index ); + void on_mFrameDivisionsTopComboBox_currentIndexChanged( int index ); + void on_mFrameDivisionsBottomComboBox_currentIndexChanged( int index ); + + void on_mDrawAnnotationGroupBox_toggled( bool state ); + void on_mAnnotationFormatButton_clicked(); + + //annotation display + void on_mAnnotationDisplayLeftComboBox_currentIndexChanged( const QString& text ); + void on_mAnnotationDisplayRightComboBox_currentIndexChanged( const QString& text ); + void on_mAnnotationDisplayTopComboBox_currentIndexChanged( const QString& text ); + void on_mAnnotationDisplayBottomComboBox_currentIndexChanged( const QString& text ); + + //annotation position + void on_mAnnotationPositionLeftComboBox_currentIndexChanged( const QString& text ); + void on_mAnnotationPositionRightComboBox_currentIndexChanged( const QString& text ); + void on_mAnnotationPositionTopComboBox_currentIndexChanged( const QString& text ); + void on_mAnnotationPositionBottomComboBox_currentIndexChanged( const QString& text ); + + //annotation direction + void on_mAnnotationDirectionComboBoxLeft_currentIndexChanged( int index ); + void on_mAnnotationDirectionComboBoxRight_currentIndexChanged( int index ); + void on_mAnnotationDirectionComboBoxTop_currentIndexChanged( int index ); + void on_mAnnotationDirectionComboBoxBottom_currentIndexChanged( int index ); + + void on_mAnnotationFormatComboBox_currentIndexChanged( int index ); + void on_mCoordinatePrecisionSpinBox_valueChanged( int value ); + void on_mDistanceToMapFrameSpinBox_valueChanged( double d ); + void on_mAnnotationFontButton_clicked(); + void on_mAnnotationFontColorButton_colorChanged( const QColor &color ); + + protected: + + /** Sets the current composer map values to the GUI elements*/ + virtual void updateGuiElements(); + + protected slots: + /** Initializes data defined buttons to current atlas coverage layer*/ + void populateDataDefinedButtons(); + + private slots: + + /** Sets the GUI elements to the values of mPicture*/ + void setGuiElementValues(); + + void updateGridLineStyleFromWidget(); + void cleanUpGridLineStyleSelector( QgsPanelWidget* container ); + void updateGridMarkerStyleFromWidget(); + void cleanUpGridMarkerStyleSelector( QgsPanelWidget* container ); + + private: + QgsComposerMap* mComposerMap; + QgsComposerMapGrid* mComposerMapGrid; + + /** Blocks / unblocks the signals of all GUI elements*/ + void blockAllSignals( bool b ); + + void handleChangedFrameDisplay( QgsComposerMapGrid::BorderSide border, const QgsComposerMapGrid::DisplayMode mode ); + void handleChangedAnnotationDisplay( QgsComposerMapGrid::BorderSide border, const QString& text ); + void handleChangedAnnotationPosition( QgsComposerMapGrid::BorderSide border, const QString& text ); + void handleChangedAnnotationDirection( QgsComposerMapGrid::BorderSide border, QgsComposerMapGrid::AnnotationDirection direction ); + + void insertFrameDisplayEntries( QComboBox* c ); + void insertAnnotationDisplayEntries( QComboBox* c ); + void insertAnnotationPositionEntries( QComboBox* c ); + void insertAnnotationDirectionEntries( QComboBox* c ); + + void initFrameDisplayBox( QComboBox* c, QgsComposerMapGrid::DisplayMode display ); + void initAnnotationDisplayBox( QComboBox* c, QgsComposerMapGrid::DisplayMode display ); + void initAnnotationPositionBox( QComboBox* c, QgsComposerMapGrid::AnnotationPosition pos ); + void initAnnotationDirectionBox( QComboBox* c, QgsComposerMapGrid::AnnotationDirection dir ); + + void updateGridLineSymbolMarker(); + void updateGridMarkerSymbolMarker(); + + /** Enables/disables grid frame related controls*/ + void toggleFrameControls( bool frameEnabled, bool frameFillEnabled, bool frameSizeEnabled ); + + /** Is there some predefined scales, globally or as project's options ?*/ + bool hasPredefinedScales() const; + +}; + +#endif //QGSCOMPOSERMAPGRIDWIDGET_H diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index 82d1569c16c1..9883e813baee 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -23,19 +23,17 @@ #include "qgscomposermapoverview.h" #include "qgscomposermapwidget.h" #include "qgscomposeritemwidget.h" +#include "qgscomposermapgridwidget.h" #include "qgscomposition.h" #include "qgsmaplayerstylemanager.h" #include "qgsstyle.h" #include "qgssymbol.h" #include "qgssymbolselectordialog.h" -#include "qgssymbollayerutils.h" #include "qgsvectorlayer.h" #include "qgsvectordataprovider.h" #include "qgsmaplayerregistry.h" #include "qgscomposershape.h" #include "qgspaperitem.h" -#include "qgsexpressionbuilderdialog.h" -#include "qgsgenericprojectionselector.h" #include "qgsproject.h" #include "qgsmapthemecollection.h" #include "qgsmapthemes.h" @@ -66,66 +64,6 @@ QgsComposerMapWidget::QgsComposerMapWidget( QgsComposerMap* composerMap ) mPreviewModeComboBox->insertItem( 1, tr( "Render" ) ); mPreviewModeComboBox->insertItem( 2, tr( "Rectangle" ) ); - mGridTypeComboBox->insertItem( 0, tr( "Solid" ) ); - mGridTypeComboBox->insertItem( 1, tr( "Cross" ) ); - mGridTypeComboBox->insertItem( 2, tr( "Markers" ) ); - mGridTypeComboBox->insertItem( 3, tr( "Frame and annotations only" ) ); - - insertFrameDisplayEntries( mFrameDivisionsLeftComboBox ); - insertFrameDisplayEntries( mFrameDivisionsRightComboBox ); - insertFrameDisplayEntries( mFrameDivisionsTopComboBox ); - insertFrameDisplayEntries( mFrameDivisionsBottomComboBox ); - - mAnnotationFormatComboBox->addItem( tr( "Decimal" ), QgsComposerMapGrid::Decimal ); - mAnnotationFormatComboBox->addItem( tr( "Decimal with suffix" ), QgsComposerMapGrid::DecimalWithSuffix ); - mAnnotationFormatComboBox->addItem( tr( "Degree, minute" ), QgsComposerMapGrid::DegreeMinuteNoSuffix ); - mAnnotationFormatComboBox->addItem( tr( "Degree, minute with suffix" ), QgsComposerMapGrid::DegreeMinute ); - mAnnotationFormatComboBox->addItem( tr( "Degree, minute aligned" ), QgsComposerMapGrid::DegreeMinutePadded ); - mAnnotationFormatComboBox->addItem( tr( "Degree, minute, second" ), QgsComposerMapGrid::DegreeMinuteSecondNoSuffix ); - mAnnotationFormatComboBox->addItem( tr( "Degree, minute, second with suffix" ), QgsComposerMapGrid::DegreeMinuteSecond ); - mAnnotationFormatComboBox->addItem( tr( "Degree, minute, second aligned" ), QgsComposerMapGrid::DegreeMinuteSecondPadded ); - mAnnotationFormatComboBox->addItem( tr( "Custom" ), QgsComposerMapGrid::CustomFormat ); - - mAnnotationFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); - mAnnotationFontColorButton->setAllowAlpha( true ); - mAnnotationFontColorButton->setContext( "composer" ); - - insertAnnotationDisplayEntries( mAnnotationDisplayLeftComboBox ); - insertAnnotationDisplayEntries( mAnnotationDisplayRightComboBox ); - insertAnnotationDisplayEntries( mAnnotationDisplayTopComboBox ); - insertAnnotationDisplayEntries( mAnnotationDisplayBottomComboBox ); - - insertAnnotationPositionEntries( mAnnotationPositionLeftComboBox ); - insertAnnotationPositionEntries( mAnnotationPositionRightComboBox ); - insertAnnotationPositionEntries( mAnnotationPositionTopComboBox ); - insertAnnotationPositionEntries( mAnnotationPositionBottomComboBox ); - - insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxLeft ); - insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxRight ); - insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxTop ); - insertAnnotationDirectionEntries( mAnnotationDirectionComboBoxBottom ); - - mGridFramePenColorButton->setColorDialogTitle( tr( "Select grid frame color" ) ); - mGridFramePenColorButton->setAllowAlpha( true ); - mGridFramePenColorButton->setContext( "composer" ); - mGridFramePenColorButton->setNoColorString( tr( "Transparent frame" ) ); - mGridFramePenColorButton->setShowNoColor( true ); - - mGridFrameFill1ColorButton->setColorDialogTitle( tr( "Select grid frame fill color" ) ); - mGridFrameFill1ColorButton->setAllowAlpha( true ); - mGridFrameFill1ColorButton->setContext( "composer" ); - mGridFrameFill1ColorButton->setNoColorString( tr( "Transparent fill" ) ); - mGridFrameFill1ColorButton->setShowNoColor( true ); - - mGridFrameFill2ColorButton->setColorDialogTitle( tr( "Select grid frame fill color" ) ); - mGridFrameFill2ColorButton->setAllowAlpha( true ); - mGridFrameFill2ColorButton->setContext( "composer" ); - mGridFrameFill2ColorButton->setNoColorString( tr( "Transparent fill" ) ); - mGridFrameFill2ColorButton->setShowNoColor( true ); - - //set initial state of frame style controls - toggleFrameControls( false, false, false ); - // follow preset combo mFollowVisibilityPresetCombo->setModel( new QStringListModel( mFollowVisibilityPresetCombo ) ); connect( mFollowVisibilityPresetCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( followVisibilityPresetSelected( int ) ) ); @@ -292,68 +230,6 @@ void QgsComposerMapWidget::onPresetsChanged() } } -void QgsComposerMapWidget::updateGridLineStyleFromWidget() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - QgsSymbolSelectorWidget* w = qobject_cast( sender() ); - grid->setLineSymbol( dynamic_cast< QgsLineSymbol* >( w->symbol()->clone() ) ); - mComposerMap->update(); -} - -void QgsComposerMapWidget::cleanUpGridLineStyleSelector( QgsPanelWidget* container ) -{ - QgsSymbolSelectorWidget* w = qobject_cast( container ); - if ( !w ) - return; - - delete w->symbol(); - - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - updateGridLineSymbolMarker( grid ); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::updateGridMarkerStyleFromWidget() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - QgsSymbolSelectorWidget* w = qobject_cast( sender() ); - grid->setMarkerSymbol( dynamic_cast< QgsMarkerSymbol* >( w->symbol()->clone() ) ); - mComposerMap->update(); -} - -void QgsComposerMapWidget::cleanUpGridMarkerStyleSelector( QgsPanelWidget* container ) -{ - QgsSymbolSelectorWidget* w = qobject_cast( container ); - if ( !w ) - return; - - delete w->symbol(); - - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - updateGridMarkerSymbolMarker( grid ); - mComposerMap->endCommand(); -} - void QgsComposerMapWidget::updateOverviewFrameStyleFromWidget() { QgsComposerMapOverview* overview = currentOverview(); @@ -851,7 +727,6 @@ void QgsComposerMapWidget::blockAllSignals( bool b ) mSetToMapCanvasExtentButton->blockSignals( b ); mUpdatePreviewButton->blockSignals( b ); - blockGridItemsSignals( b ); blockOverviewItemsSignals( b ); } @@ -900,31 +775,6 @@ void QgsComposerMapWidget::handleChangedAnnotationDisplay( QgsComposerMapGrid::B mComposerMap->endCommand(); } -void QgsComposerMapWidget::toggleFrameControls( bool frameEnabled, bool frameFillEnabled, bool frameSizeEnabled ) -{ - //set status of frame controls - mFrameWidthSpinBox->setEnabled( frameSizeEnabled ); - mGridFramePenSizeSpinBox->setEnabled( frameEnabled ); - mGridFramePenColorButton->setEnabled( frameEnabled ); - mGridFrameFill1ColorButton->setEnabled( frameFillEnabled ); - mGridFrameFill2ColorButton->setEnabled( frameFillEnabled ); - mFrameWidthLabel->setEnabled( frameSizeEnabled ); - mFramePenLabel->setEnabled( frameEnabled ); - mFrameFillLabel->setEnabled( frameFillEnabled ); - mCheckGridLeftSide->setEnabled( frameEnabled ); - mCheckGridRightSide->setEnabled( frameEnabled ); - mCheckGridTopSide->setEnabled( frameEnabled ); - mCheckGridBottomSide->setEnabled( frameEnabled ); - mFrameDivisionsLeftComboBox->setEnabled( frameEnabled ); - mFrameDivisionsRightComboBox->setEnabled( frameEnabled ); - mFrameDivisionsTopComboBox->setEnabled( frameEnabled ); - mFrameDivisionsBottomComboBox->setEnabled( frameEnabled ); - mLeftDivisionsLabel->setEnabled( frameEnabled ); - mRightDivisionsLabel->setEnabled( frameEnabled ); - mTopDivisionsLabel->setEnabled( frameEnabled ); - mBottomDivisionsLabel->setEnabled( frameEnabled ); -} - void QgsComposerMapWidget::on_mUpdatePreviewButton_clicked() { if ( !mComposerMap ) @@ -1297,12 +1147,17 @@ void QgsComposerMapWidget::on_mGridListWidget_currentItemChanged( QListWidgetIte Q_UNUSED( previous ); if ( !current ) { - mGridCheckBox->setEnabled( false ); + mDrawGridCheckBox->setEnabled( false ); + mDrawGridCheckBox->setChecked( false ); + mGridPropertiesButton->setEnabled( false ); return; } - mGridCheckBox->setEnabled( true ); - setGridItems( mComposerMap->grids()->constGrid( current->data( Qt::UserRole ).toString() ) ); + mDrawGridCheckBox->setEnabled( true ); + mDrawGridCheckBox->setChecked( currentGrid()->enabled() ); + mGridPropertiesButton->setEnabled( currentGrid()->enabled() ); + + mDrawGridCheckBox->setText( QString( tr( "Draw \"%1\" grid" ) ).arg( currentGrid()->name() ) ); } void QgsComposerMapWidget::on_mGridListWidget_itemChanged( QListWidgetItem* item ) @@ -1322,435 +1177,77 @@ void QgsComposerMapWidget::on_mGridListWidget_itemChanged( QListWidgetItem* item if ( item->isSelected() ) { //update check box title if item is current item - mGridCheckBox->setTitle( QString( tr( "Draw \"%1\" grid" ) ).arg( grid->name() ) ); - } -} - -void QgsComposerMapWidget::setGridItemsEnabled( bool enabled ) -{ - mGridTypeComboBox->setEnabled( enabled ); - mIntervalXSpinBox->setEnabled( enabled ); - mIntervalYSpinBox->setEnabled( enabled ); - mOffsetXSpinBox->setEnabled( enabled ); - mOffsetYSpinBox->setEnabled( enabled ); - mCrossWidthSpinBox->setEnabled( enabled ); - mFrameStyleComboBox->setEnabled( enabled ); - mFrameWidthSpinBox->setEnabled( enabled ); - mGridLineStyleButton->setEnabled( enabled ); - mGridFramePenSizeSpinBox->setEnabled( enabled ); - mGridFramePenColorButton->setEnabled( enabled ); - mGridFrameFill1ColorButton->setEnabled( enabled ); - mGridFrameFill2ColorButton->setEnabled( enabled ); - mFrameDivisionsLeftComboBox->setEnabled( enabled ); - mFrameDivisionsRightComboBox->setEnabled( enabled ); - mFrameDivisionsTopComboBox->setEnabled( enabled ); - mFrameDivisionsBottomComboBox->setEnabled( enabled ); -} - -void QgsComposerMapWidget::blockGridItemsSignals( bool block ) -{ - //grid - mGridCheckBox->blockSignals( block ); - mGridTypeComboBox->blockSignals( block ); - mIntervalXSpinBox->blockSignals( block ); - mIntervalYSpinBox->blockSignals( block ); - mOffsetXSpinBox->blockSignals( block ); - mOffsetYSpinBox->blockSignals( block ); - mCrossWidthSpinBox->blockSignals( block ); - mFrameStyleComboBox->blockSignals( block ); - mFrameWidthSpinBox->blockSignals( block ); - mGridLineStyleButton->blockSignals( block ); - mMapGridUnitComboBox->blockSignals( block ); - mGridFramePenSizeSpinBox->blockSignals( block ); - mGridFramePenColorButton->blockSignals( block ); - mGridFrameFill1ColorButton->blockSignals( block ); - mGridFrameFill2ColorButton->blockSignals( block ); - mGridBlendComboBox->blockSignals( block ); - mCheckGridLeftSide->blockSignals( block ); - mCheckGridRightSide->blockSignals( block ); - mCheckGridTopSide->blockSignals( block ); - mCheckGridBottomSide->blockSignals( block ); - mFrameDivisionsLeftComboBox->blockSignals( block ); - mFrameDivisionsRightComboBox->blockSignals( block ); - mFrameDivisionsTopComboBox->blockSignals( block ); - mFrameDivisionsBottomComboBox->blockSignals( block ); - - //grid annotation - mDrawAnnotationGroupBox->blockSignals( block ); - mAnnotationFormatComboBox->blockSignals( block ); - mAnnotationDisplayLeftComboBox->blockSignals( block ); - mAnnotationPositionLeftComboBox->blockSignals( block ); - mAnnotationDirectionComboBoxLeft->blockSignals( block ); - mAnnotationDisplayRightComboBox->blockSignals( block ); - mAnnotationPositionRightComboBox->blockSignals( block ); - mAnnotationDirectionComboBoxRight->blockSignals( block ); - mAnnotationDisplayTopComboBox->blockSignals( block ); - mAnnotationPositionTopComboBox->blockSignals( block ); - mAnnotationDirectionComboBoxTop->blockSignals( block ); - mAnnotationDisplayBottomComboBox->blockSignals( block ); - mAnnotationPositionBottomComboBox->blockSignals( block ); - mAnnotationDirectionComboBoxBottom->blockSignals( block ); - mDistanceToMapFrameSpinBox->blockSignals( block ); - mCoordinatePrecisionSpinBox->blockSignals( block ); - mAnnotationFontColorButton->blockSignals( block ); - mAnnotationFontButton->blockSignals( block ); -} - -void QgsComposerMapWidget::setGridItems( const QgsComposerMapGrid* grid ) -{ - if ( !grid ) - { - return; - } - - blockGridItemsSignals( true ); - - mGridCheckBox->setTitle( QString( tr( "Draw \"%1\" grid" ) ).arg( grid->name() ) ); - mGridCheckBox->setChecked( grid->enabled() ); - mIntervalXSpinBox->setValue( grid->intervalX() ); - mIntervalYSpinBox->setValue( grid->intervalY() ); - mOffsetXSpinBox->setValue( grid->offsetX() ); - mOffsetYSpinBox->setValue( grid->offsetY() ); - mCrossWidthSpinBox->setValue( grid->crossLength() ); - mFrameWidthSpinBox->setValue( grid->frameWidth() ); - mGridFramePenSizeSpinBox->setValue( grid->framePenSize() ); - mGridFramePenColorButton->setColor( grid->framePenColor() ); - mGridFrameFill1ColorButton->setColor( grid->frameFillColor1() ); - mGridFrameFill2ColorButton->setColor( grid->frameFillColor2() ); - - QgsComposerMapGrid::GridStyle gridStyle = grid->style(); - switch ( gridStyle ) - { - case QgsComposerMapGrid::Cross: - mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Cross" ) ) ); - mCrossWidthSpinBox->setVisible( true ); - mCrossWidthLabel->setVisible( true ); - mGridLineStyleButton->setVisible( true ); - mLineStyleLabel->setVisible( true ); - mGridMarkerStyleButton->setVisible( false ); - mMarkerStyleLabel->setVisible( false ); - mGridBlendComboBox->setVisible( true ); - mGridBlendLabel->setVisible( true ); - break; - case QgsComposerMapGrid::Markers: - mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Markers" ) ) ); - mCrossWidthSpinBox->setVisible( false ); - mCrossWidthLabel->setVisible( false ); - mGridLineStyleButton->setVisible( false ); - mLineStyleLabel->setVisible( false ); - mGridMarkerStyleButton->setVisible( true ); - mMarkerStyleLabel->setVisible( true ); - mGridBlendComboBox->setVisible( true ); - mGridBlendLabel->setVisible( true ); - break; - case QgsComposerMapGrid::Solid: - mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Solid" ) ) ); - mCrossWidthSpinBox->setVisible( false ); - mCrossWidthLabel->setVisible( false ); - mGridLineStyleButton->setVisible( true ); - mLineStyleLabel->setVisible( true ); - mGridMarkerStyleButton->setVisible( false ); - mMarkerStyleLabel->setVisible( false ); - mGridBlendComboBox->setVisible( true ); - mGridBlendLabel->setVisible( true ); - break; - case QgsComposerMapGrid::FrameAnnotationsOnly: - mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Frame and annotations only" ) ) ); - mCrossWidthSpinBox->setVisible( false ); - mCrossWidthLabel->setVisible( false ); - mGridLineStyleButton->setVisible( false ); - mLineStyleLabel->setVisible( false ); - mGridMarkerStyleButton->setVisible( false ); - mMarkerStyleLabel->setVisible( false ); - mGridBlendComboBox->setVisible( false ); - mGridBlendLabel->setVisible( false ); - break; - } - - //grid frame - mFrameWidthSpinBox->setValue( grid->frameWidth() ); - QgsComposerMapGrid::FrameStyle gridFrameStyle = grid->frameStyle(); - switch ( gridFrameStyle ) - { - case QgsComposerMapGrid::Zebra: - mFrameStyleComboBox->setCurrentIndex( 1 ); - toggleFrameControls( true, true, true ); - break; - case QgsComposerMapGrid::InteriorTicks: - mFrameStyleComboBox->setCurrentIndex( 2 ); - toggleFrameControls( true, false, true ); - break; - case QgsComposerMapGrid::ExteriorTicks: - mFrameStyleComboBox->setCurrentIndex( 3 ); - toggleFrameControls( true, false, true ); - break; - case QgsComposerMapGrid::InteriorExteriorTicks: - mFrameStyleComboBox->setCurrentIndex( 4 ); - toggleFrameControls( true, false, true ); - break; - case QgsComposerMapGrid::LineBorder: - mFrameStyleComboBox->setCurrentIndex( 5 ); - toggleFrameControls( true, false, false ); - break; - default: - mFrameStyleComboBox->setCurrentIndex( 0 ); - toggleFrameControls( false, false, false ); - break; - } - - mCheckGridLeftSide->setChecked( grid->testFrameSideFlag( QgsComposerMapGrid::FrameLeft ) ); - mCheckGridRightSide->setChecked( grid->testFrameSideFlag( QgsComposerMapGrid::FrameRight ) ); - mCheckGridTopSide->setChecked( grid->testFrameSideFlag( QgsComposerMapGrid::FrameTop ) ); - mCheckGridBottomSide->setChecked( grid->testFrameSideFlag( QgsComposerMapGrid::FrameBottom ) ); - - initFrameDisplayBox( mFrameDivisionsLeftComboBox, grid->frameDivisions( QgsComposerMapGrid::Left ) ); - initFrameDisplayBox( mFrameDivisionsRightComboBox, grid->frameDivisions( QgsComposerMapGrid::Right ) ); - initFrameDisplayBox( mFrameDivisionsTopComboBox, grid->frameDivisions( QgsComposerMapGrid::Top ) ); - initFrameDisplayBox( mFrameDivisionsBottomComboBox, grid->frameDivisions( QgsComposerMapGrid::Bottom ) ); - - //line style - updateGridLineSymbolMarker( grid ); - //marker style - updateGridMarkerSymbolMarker( grid ); - - mGridBlendComboBox->setBlendMode( grid->blendMode() ); - - mDrawAnnotationGroupBox->setChecked( grid->annotationEnabled() ); - initAnnotationDisplayBox( mAnnotationDisplayLeftComboBox, grid->annotationDisplay( QgsComposerMapGrid::Left ) ); - initAnnotationDisplayBox( mAnnotationDisplayRightComboBox, grid->annotationDisplay( QgsComposerMapGrid::Right ) ); - initAnnotationDisplayBox( mAnnotationDisplayTopComboBox, grid->annotationDisplay( QgsComposerMapGrid::Top ) ); - initAnnotationDisplayBox( mAnnotationDisplayBottomComboBox, grid->annotationDisplay( QgsComposerMapGrid::Bottom ) ); - - initAnnotationPositionBox( mAnnotationPositionLeftComboBox, grid->annotationPosition( QgsComposerMapGrid::Left ) ); - initAnnotationPositionBox( mAnnotationPositionRightComboBox, grid->annotationPosition( QgsComposerMapGrid::Right ) ); - initAnnotationPositionBox( mAnnotationPositionTopComboBox, grid->annotationPosition( QgsComposerMapGrid::Top ) ); - initAnnotationPositionBox( mAnnotationPositionBottomComboBox, grid->annotationPosition( QgsComposerMapGrid::Bottom ) ); - - initAnnotationDirectionBox( mAnnotationDirectionComboBoxLeft, grid->annotationDirection( QgsComposerMapGrid::Left ) ); - initAnnotationDirectionBox( mAnnotationDirectionComboBoxRight, grid->annotationDirection( QgsComposerMapGrid::Right ) ); - initAnnotationDirectionBox( mAnnotationDirectionComboBoxTop, grid->annotationDirection( QgsComposerMapGrid::Top ) ); - initAnnotationDirectionBox( mAnnotationDirectionComboBoxBottom, grid->annotationDirection( QgsComposerMapGrid::Bottom ) ); - - mAnnotationFontColorButton->setColor( grid->annotationFontColor() ); - - mAnnotationFormatComboBox->setCurrentIndex( mAnnotationFormatComboBox->findData( grid->annotationFormat() ) ); - mAnnotationFormatButton->setEnabled( grid->annotationFormat() == QgsComposerMapGrid::CustomFormat ); - mDistanceToMapFrameSpinBox->setValue( grid->annotationFrameDistance() ); - mCoordinatePrecisionSpinBox->setValue( grid->annotationPrecision() ); - - //Unit - QgsComposerMapGrid::GridUnit gridUnit = grid->units(); - if ( gridUnit == QgsComposerMapGrid::MapUnit ) - { - mMapGridUnitComboBox->setCurrentIndex( mMapGridUnitComboBox->findText( tr( "Map unit" ) ) ); - } - else if ( gridUnit == QgsComposerMapGrid::MM ) - { - mMapGridUnitComboBox->setCurrentIndex( mMapGridUnitComboBox->findText( tr( "Millimeter" ) ) ); - } - else if ( gridUnit == QgsComposerMapGrid::CM ) - { - mMapGridUnitComboBox->setCurrentIndex( mMapGridUnitComboBox->findText( tr( "Centimeter" ) ) ); - } - - //CRS button - QgsCoordinateReferenceSystem gridCrs = grid->crs(); - QString crsButtonText = gridCrs.isValid() ? gridCrs.authid() : tr( "change..." ); - mMapGridCRSButton->setText( crsButtonText ); - - blockGridItemsSignals( false ); -} - -void QgsComposerMapWidget::updateGridLineSymbolMarker( const QgsComposerMapGrid* grid ) -{ - if ( grid ) - { - QgsLineSymbol* nonConstSymbol = const_cast( grid->lineSymbol() ); //bad - QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( nonConstSymbol, mGridLineStyleButton->iconSize() ); - mGridLineStyleButton->setIcon( icon ); - } -} - -void QgsComposerMapWidget::updateGridMarkerSymbolMarker( const QgsComposerMapGrid *grid ) -{ - if ( grid ) - { - QgsMarkerSymbol* nonConstSymbol = const_cast( grid->markerSymbol() ); //bad - QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( nonConstSymbol, mGridMarkerStyleButton->iconSize() ); - mGridMarkerStyleButton->setIcon( icon ); - } -} - -void QgsComposerMapWidget::on_mGridLineStyleButton_clicked() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - // use the atlas coverage layer, if any - QgsVectorLayer* coverageLayer = atlasCoverageLayer(); - - QgsLineSymbol* newSymbol = static_cast( grid->lineSymbol()->clone() ); - QgsExpressionContext context = mComposerMap->createExpressionContext(); - - QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); - QgsSymbolWidgetContext symbolContext; - symbolContext.setExpressionContext( &context ); - d->setContext( symbolContext ); - - connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateGridLineStyleFromWidget() ) ); - connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpGridLineStyleSelector( QgsPanelWidget* ) ) ); - openPanel( d ); - mComposerMap->beginCommand( tr( "Grid line style changed" ) ); -} - -void QgsComposerMapWidget::on_mGridMarkerStyleButton_clicked() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; + mDrawGridCheckBox->setText( QString( tr( "Draw \"%1\" grid" ) ).arg( grid->name() ) ); } - - // use the atlas coverage layer, if any - QgsVectorLayer* coverageLayer = atlasCoverageLayer(); - - QgsMarkerSymbol* newSymbol = static_cast( grid->markerSymbol()->clone() ); - QgsExpressionContext context = mComposerMap->createExpressionContext(); - - QgsSymbolSelectorWidget* d = new QgsSymbolSelectorWidget( newSymbol, QgsStyle::defaultStyle(), coverageLayer, nullptr ); - QgsSymbolWidgetContext symbolContext; - symbolContext.setExpressionContext( &context ); - d->setContext( symbolContext ); - - connect( d, SIGNAL( widgetChanged() ), this, SLOT( updateGridMarkerStyleFromWidget() ) ); - connect( d, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( cleanUpGridMarkerStyleSelector( QgsPanelWidget* ) ) ); - openPanel( d ); - mComposerMap->beginCommand( tr( "Grid markers style changed" ) ); } -void QgsComposerMapWidget::on_mIntervalXSpinBox_editingFinished() +void QgsComposerMapWidget::on_mGridPropertiesButton_clicked() { - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) + if ( !mComposerMap ) { return; } - mComposerMap->beginCommand( tr( "Grid interval changed" ) ); - grid->setIntervalX( mIntervalXSpinBox->value() ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mIntervalYSpinBox_editingFinished() -{ QgsComposerMapGrid* grid = currentGrid(); if ( !grid ) { return; } - mComposerMap->beginCommand( tr( "Grid interval changed" ) ); - grid->setIntervalY( mIntervalYSpinBox->value() ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); + QgsComposerMapGridWidget* w = new QgsComposerMapGridWidget( grid, mComposerMap ); + openPanel( w ); } -void QgsComposerMapWidget::on_mOffsetXSpinBox_valueChanged( double value ) +QListWidgetItem* QgsComposerMapWidget::addGridListItem( const QString& id, const QString& name ) { - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Grid offset changed" ) ); - grid->setOffsetX( value ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); + QListWidgetItem* item = new QListWidgetItem( name, nullptr ); + item->setData( Qt::UserRole, id ); + item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable ); + mGridListWidget->insertItem( 0, item ); + return item; } -void QgsComposerMapWidget::on_mOffsetYSpinBox_valueChanged( double value ) +void QgsComposerMapWidget::loadGridEntries() { - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) + //save selection + QSet selectedIds; + QList itemSelection = mGridListWidget->selectedItems(); + QList::const_iterator sIt = itemSelection.constBegin(); + for ( ; sIt != itemSelection.constEnd(); ++sIt ) { - return; + selectedIds.insert(( *sIt )->data( Qt::UserRole ).toString() ); } - mComposerMap->beginCommand( tr( "Grid offset changed" ) ); - grid->setOffsetY( value ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mCrossWidthSpinBox_valueChanged( double val ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) + mGridListWidget->clear(); + if ( !mComposerMap ) { return; } - mComposerMap->beginCommand( tr( "Cross width changed" ) ); - grid->setCrossLength( val ); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mFrameWidthSpinBox_valueChanged( double val ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) + //load all composer grids into list widget + QList< QgsComposerMapGrid* > grids = mComposerMap->grids()->asList(); + QList< QgsComposerMapGrid* >::const_iterator gridIt = grids.constBegin(); + for ( ; gridIt != grids.constEnd(); ++gridIt ) { - return; + QListWidgetItem* item = addGridListItem(( *gridIt )->id(), ( *gridIt )->name() ); + if ( selectedIds.contains(( *gridIt )->id() ) ) + { + item->setSelected( true ); + mGridListWidget->setCurrentItem( item ); + } } - mComposerMap->beginCommand( tr( "Frame width changed" ) ); - grid->setFrameWidth( val ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mCheckGridLeftSide_toggled( bool checked ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) + if ( mGridListWidget->currentItem() ) { - return; + on_mGridListWidget_currentItemChanged( mGridListWidget->currentItem(), nullptr ); } - - mComposerMap->beginCommand( tr( "Frame left side changed" ) ); - grid->setFrameSideFlag( QgsComposerMapGrid::FrameLeft, checked ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mCheckGridRightSide_toggled( bool checked ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) + else { - return; + on_mGridListWidget_currentItemChanged( nullptr, nullptr ); } - - mComposerMap->beginCommand( tr( "Frame right side changed" ) ); - grid->setFrameSideFlag( QgsComposerMapGrid::FrameRight, checked ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); } -void QgsComposerMapWidget::on_mCheckGridTopSide_toggled( bool checked ) +void QgsComposerMapWidget::on_mDrawGridCheckBox_toggled( bool state ) { QgsComposerMapGrid* grid = currentGrid(); if ( !grid ) @@ -1758,512 +1255,7 @@ void QgsComposerMapWidget::on_mCheckGridTopSide_toggled( bool checked ) return; } - mComposerMap->beginCommand( tr( "Frame top side changed" ) ); - grid->setFrameSideFlag( QgsComposerMapGrid::FrameTop, checked ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mCheckGridBottomSide_toggled( bool checked ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Frame bottom side changed" ) ); - grid->setFrameSideFlag( QgsComposerMapGrid::FrameBottom, checked ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mFrameDivisionsLeftComboBox_currentIndexChanged( int index ) -{ - handleChangedFrameDisplay( QgsComposerMapGrid::Left, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsLeftComboBox->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mFrameDivisionsRightComboBox_currentIndexChanged( int index ) -{ - handleChangedFrameDisplay( QgsComposerMapGrid::Right, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsRightComboBox->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mFrameDivisionsTopComboBox_currentIndexChanged( int index ) -{ - handleChangedFrameDisplay( QgsComposerMapGrid::Top, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsTopComboBox->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mFrameDivisionsBottomComboBox_currentIndexChanged( int index ) -{ - handleChangedFrameDisplay( QgsComposerMapGrid::Bottom, ( QgsComposerMapGrid::DisplayMode ) mFrameDivisionsBottomComboBox->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mGridFramePenSizeSpinBox_valueChanged( double d ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid || !mComposerMap ) - { - return; - } - - mComposerMap->beginCommand( tr( "Changed grid frame line thickness" ) ); - grid->setFramePenSize( d ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mGridFramePenColorButton_colorChanged( const QColor& newColor ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid || !mComposerMap ) - { - return; - } - - mComposerMap->beginCommand( tr( "Grid frame color changed" ), QgsComposerMergeCommand::ComposerMapGridFramePenColor ); - grid->setFramePenColor( newColor ); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mGridFrameFill1ColorButton_colorChanged( const QColor& newColor ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid || !mComposerMap ) - { - return; - } - - mComposerMap->beginCommand( tr( "Grid frame first fill color changed" ), QgsComposerMergeCommand::ComposerMapGridFrameFill1Color ); - grid->setFrameFillColor1( newColor ); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mGridFrameFill2ColorButton_colorChanged( const QColor& newColor ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid || !mComposerMap ) - { - return; - } - - mComposerMap->beginCommand( tr( "Grid frame second fill color changed" ), QgsComposerMergeCommand::ComposerMapGridFrameFill2Color ); - grid->setFrameFillColor2( newColor ); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mFrameStyleComboBox_currentIndexChanged( const QString& text ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Changed grid frame style" ) ); - if ( text == tr( "Zebra" ) ) - { - grid->setFrameStyle( QgsComposerMapGrid::Zebra ); - toggleFrameControls( true, true, true ); - } - else if ( text == tr( "Interior ticks" ) ) - { - grid->setFrameStyle( QgsComposerMapGrid::InteriorTicks ); - toggleFrameControls( true, false, true ); - } - else if ( text == tr( "Exterior ticks" ) ) - { - grid->setFrameStyle( QgsComposerMapGrid::ExteriorTicks ); - toggleFrameControls( true, false, true ); - } - else if ( text == tr( "Interior and exterior ticks" ) ) - { - grid->setFrameStyle( QgsComposerMapGrid::InteriorExteriorTicks ); - toggleFrameControls( true, false, true ); - } - else if ( text == tr( "Line border" ) ) - { - grid->setFrameStyle( QgsComposerMapGrid::LineBorder ); - toggleFrameControls( true, false, false ); - } - else //no frame - { - grid->setFrameStyle( QgsComposerMapGrid::NoFrame ); - toggleFrameControls( false, false, false ); - } - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mMapGridUnitComboBox_currentIndexChanged( const QString& text ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Changed grid unit" ) ); - if ( text == tr( "Map unit" ) ) - { - grid->setUnits( QgsComposerMapGrid::MapUnit ); - } - else if ( text == tr( "Millimeter" ) ) - { - grid->setUnits( QgsComposerMapGrid::MM ); - } - else if ( text == tr( "Centimeter" ) ) - { - grid->setUnits( QgsComposerMapGrid::CM ); - } - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mGridBlendComboBox_currentIndexChanged( int index ) -{ - Q_UNUSED( index ); - QgsComposerMapGrid* grid = currentGrid(); - if ( grid ) - { - mComposerMap->beginCommand( tr( "Grid blend mode changed" ) ); - grid->setBlendMode( mGridBlendComboBox->blendMode() ); - mComposerMap->update(); - mComposerMap->endCommand(); - } - -} - -void QgsComposerMapWidget::on_mGridTypeComboBox_currentIndexChanged( const QString& text ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Grid type changed" ) ); - if ( text == tr( "Cross" ) ) - { - grid->setStyle( QgsComposerMapGrid::Cross ); - mCrossWidthSpinBox->setVisible( true ); - mCrossWidthLabel->setVisible( true ); - mGridLineStyleButton->setVisible( true ); - mLineStyleLabel->setVisible( true ); - mGridMarkerStyleButton->setVisible( false ); - mMarkerStyleLabel->setVisible( false ); - mGridBlendComboBox->setVisible( true ); - mGridBlendLabel->setVisible( true ); - } - else if ( text == tr( "Markers" ) ) - { - grid->setStyle( QgsComposerMapGrid::Markers ); - mCrossWidthSpinBox->setVisible( false ); - mCrossWidthLabel->setVisible( false ); - mGridLineStyleButton->setVisible( false ); - mLineStyleLabel->setVisible( false ); - mGridMarkerStyleButton->setVisible( true ); - mMarkerStyleLabel->setVisible( true ); - mGridBlendComboBox->setVisible( true ); - mGridBlendLabel->setVisible( true ); - } - else if ( text == tr( "Solid" ) ) - { - grid->setStyle( QgsComposerMapGrid::Solid ); - mCrossWidthSpinBox->setVisible( false ); - mCrossWidthLabel->setVisible( false ); - mGridLineStyleButton->setVisible( true ); - mLineStyleLabel->setVisible( true ); - mGridMarkerStyleButton->setVisible( false ); - mMarkerStyleLabel->setVisible( false ); - mGridBlendComboBox->setVisible( true ); - mGridBlendLabel->setVisible( true ); - } - else - { - grid->setStyle( QgsComposerMapGrid::FrameAnnotationsOnly ); - mCrossWidthSpinBox->setVisible( false ); - mCrossWidthLabel->setVisible( false ); - mGridLineStyleButton->setVisible( false ); - mLineStyleLabel->setVisible( false ); - mGridMarkerStyleButton->setVisible( false ); - mMarkerStyleLabel->setVisible( false ); - mGridBlendComboBox->setVisible( false ); - mGridBlendLabel->setVisible( false ); - } - - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mMapGridCRSButton_clicked() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid || !mComposerMap ) - { - return; - } - - QgsGenericProjectionSelector crsDialog( this ); - QgsCoordinateReferenceSystem crs = grid->crs(); - QString currentAuthId = crs.isValid() ? crs.authid() : mComposerMap->composition()->mapSettings().destinationCrs().authid(); - crsDialog.setSelectedAuthId( currentAuthId ); - - if ( crsDialog.exec() == QDialog::Accepted ) - { - mComposerMap->beginCommand( tr( "Grid CRS changed" ) ); - QString selectedAuthId = crsDialog.selectedAuthId(); - grid->setCrs( QgsCoordinateReferenceSystem( selectedAuthId ) ); - mComposerMap->updateBoundingRect(); - mMapGridCRSButton->setText( selectedAuthId ); - mComposerMap->endCommand(); - } -} - -void QgsComposerMapWidget::on_mDrawAnnotationGroupBox_toggled( bool state ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Annotation toggled" ) ); - grid->setAnnotationEnabled( state ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mAnnotationFormatButton_clicked() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - QgsExpressionContext expressionContext = grid->createExpressionContext(); - - QgsExpressionBuilderDialog exprDlg( nullptr, grid->annotationExpression(), this, "generic", expressionContext ); - exprDlg.setWindowTitle( tr( "Expression based annotation" ) ); - - if ( exprDlg.exec() == QDialog::Accepted ) - { - QString expression = exprDlg.expressionText(); - mComposerMap->beginCommand( tr( "Annotation format changed" ) ); - grid->setAnnotationExpression( expression ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); - } -} - -void QgsComposerMapWidget::on_mAnnotationDisplayLeftComboBox_currentIndexChanged( const QString &text ) -{ - handleChangedAnnotationDisplay( QgsComposerMapGrid::Left, text ); -} - -void QgsComposerMapWidget::on_mAnnotationDisplayRightComboBox_currentIndexChanged( const QString &text ) -{ - handleChangedAnnotationDisplay( QgsComposerMapGrid::Right, text ); -} - -void QgsComposerMapWidget::on_mAnnotationDisplayTopComboBox_currentIndexChanged( const QString &text ) -{ - handleChangedAnnotationDisplay( QgsComposerMapGrid::Top, text ); -} - -void QgsComposerMapWidget::on_mAnnotationDisplayBottomComboBox_currentIndexChanged( const QString &text ) -{ - handleChangedAnnotationDisplay( QgsComposerMapGrid::Bottom, text ); -} - -void QgsComposerMapWidget::on_mAnnotationPositionLeftComboBox_currentIndexChanged( const QString& text ) -{ - handleChangedAnnotationPosition( QgsComposerMapGrid::Left, text ); -} - -void QgsComposerMapWidget::on_mAnnotationPositionRightComboBox_currentIndexChanged( const QString& text ) -{ - handleChangedAnnotationPosition( QgsComposerMapGrid::Right, text ); -} - -void QgsComposerMapWidget::on_mAnnotationPositionTopComboBox_currentIndexChanged( const QString& text ) -{ - handleChangedAnnotationPosition( QgsComposerMapGrid::Top, text ); -} - -void QgsComposerMapWidget::on_mAnnotationPositionBottomComboBox_currentIndexChanged( const QString& text ) -{ - handleChangedAnnotationPosition( QgsComposerMapGrid::Bottom, text ); -} - -void QgsComposerMapWidget::on_mAnnotationDirectionComboBoxLeft_currentIndexChanged( int index ) -{ - handleChangedAnnotationDirection( QgsComposerMapGrid::Left, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxLeft->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mAnnotationDirectionComboBoxRight_currentIndexChanged( int index ) -{ - handleChangedAnnotationDirection( QgsComposerMapGrid::Right, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxRight->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mAnnotationDirectionComboBoxTop_currentIndexChanged( int index ) -{ - handleChangedAnnotationDirection( QgsComposerMapGrid::Top, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxTop->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mAnnotationDirectionComboBoxBottom_currentIndexChanged( int index ) -{ - handleChangedAnnotationDirection( QgsComposerMapGrid::Bottom, ( QgsComposerMapGrid::AnnotationDirection ) mAnnotationDirectionComboBoxBottom->itemData( index ).toInt() ); -} - -void QgsComposerMapWidget::on_mDistanceToMapFrameSpinBox_valueChanged( double d ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Annotation distance changed" ), QgsComposerMergeCommand::ComposerMapAnnotationDistance ); - grid->setAnnotationFrameDistance( d ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mAnnotationFontButton_clicked() -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - bool ok; - QFont newFont = QgisGui::getFont( ok, grid->annotationFont() ); - if ( ok ) - { - mComposerMap->beginCommand( tr( "Annotation font changed" ) ); - grid->setAnnotationFont( newFont ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); - } -} - -void QgsComposerMapWidget::on_mAnnotationFontColorButton_colorChanged( const QColor& color ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Annotation color changed" ), QgsComposerMergeCommand::ComposerMapGridAnnotationFontColor ); - grid->setAnnotationFontColor( color ); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mAnnotationFormatComboBox_currentIndexChanged( int index ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - - mComposerMap->beginCommand( tr( "Annotation format changed" ) ); - - grid->setAnnotationFormat(( QgsComposerMapGrid::AnnotationFormat )mAnnotationFormatComboBox->itemData( index ).toInt() ); - mAnnotationFormatButton->setEnabled( grid->annotationFormat() == QgsComposerMapGrid::CustomFormat ); - - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -void QgsComposerMapWidget::on_mCoordinatePrecisionSpinBox_valueChanged( int value ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } - mComposerMap->beginCommand( tr( "Changed annotation precision" ) ); - grid->setAnnotationPrecision( value ); - mComposerMap->updateBoundingRect(); - mComposerMap->update(); - mComposerMap->endCommand(); -} - -QListWidgetItem* QgsComposerMapWidget::addGridListItem( const QString& id, const QString& name ) -{ - QListWidgetItem* item = new QListWidgetItem( name, nullptr ); - item->setData( Qt::UserRole, id ); - item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable ); - mGridListWidget->insertItem( 0, item ); - return item; -} - -void QgsComposerMapWidget::loadGridEntries() -{ - //save selection - QSet selectedIds; - QList itemSelection = mGridListWidget->selectedItems(); - QList::const_iterator sIt = itemSelection.constBegin(); - for ( ; sIt != itemSelection.constEnd(); ++sIt ) - { - selectedIds.insert(( *sIt )->data( Qt::UserRole ).toString() ); - } - - mGridListWidget->clear(); - if ( !mComposerMap ) - { - return; - } - - //load all composer grids into list widget - QList< QgsComposerMapGrid* > grids = mComposerMap->grids()->asList(); - QList< QgsComposerMapGrid* >::const_iterator gridIt = grids.constBegin(); - for ( ; gridIt != grids.constEnd(); ++gridIt ) - { - QListWidgetItem* item = addGridListItem(( *gridIt )->id(), ( *gridIt )->name() ); - if ( selectedIds.contains(( *gridIt )->id() ) ) - { - item->setSelected( true ); - mGridListWidget->setCurrentItem( item ); - } - } - - if ( mGridListWidget->currentItem() ) - { - on_mGridListWidget_currentItemChanged( mGridListWidget->currentItem(), nullptr ); - } - else - { - on_mGridListWidget_currentItemChanged( nullptr, nullptr ); - } -} - -void QgsComposerMapWidget::on_mGridCheckBox_toggled( bool state ) -{ - QgsComposerMapGrid* grid = currentGrid(); - if ( !grid ) - { - return; - } + mGridPropertiesButton->setEnabled( state ); mComposerMap->beginCommand( tr( "Grid checkbox toggled" ) ); if ( state ) diff --git a/src/app/composer/qgscomposermapwidget.h b/src/app/composer/qgscomposermapwidget.h index 727bc4cb347e..e89bbcc73899 100644 --- a/src/app/composer/qgscomposermapwidget.h +++ b/src/app/composer/qgscomposermapwidget.h @@ -71,66 +71,10 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void on_mGridDownButton_clicked(); QgsComposerMapGrid* currentGrid(); - void on_mGridCheckBox_toggled( bool state ); + void on_mDrawGridCheckBox_toggled( bool state ); void on_mGridListWidget_currentItemChanged( QListWidgetItem* current, QListWidgetItem* previous ); void on_mGridListWidget_itemChanged( QListWidgetItem* item ); - void setGridItemsEnabled( bool enabled ); - void setGridItems( const QgsComposerMapGrid* grid ); - void blockGridItemsSignals( bool block ); - void on_mGridLineStyleButton_clicked(); - void on_mGridMarkerStyleButton_clicked(); - void on_mIntervalXSpinBox_editingFinished(); - void on_mIntervalYSpinBox_editingFinished(); - void on_mOffsetXSpinBox_valueChanged( double value ); - void on_mOffsetYSpinBox_valueChanged( double value ); - void on_mCrossWidthSpinBox_valueChanged( double val ); - void on_mFrameWidthSpinBox_valueChanged( double val ); - void on_mFrameStyleComboBox_currentIndexChanged( const QString& text ); - void on_mGridFramePenSizeSpinBox_valueChanged( double d ); - void on_mGridFramePenColorButton_colorChanged( const QColor& newColor ); - void on_mGridFrameFill1ColorButton_colorChanged( const QColor& newColor ); - void on_mGridFrameFill2ColorButton_colorChanged( const QColor& newColor ); - void on_mGridTypeComboBox_currentIndexChanged( const QString& text ); - void on_mMapGridCRSButton_clicked(); - void on_mMapGridUnitComboBox_currentIndexChanged( const QString& text ); - void on_mGridBlendComboBox_currentIndexChanged( int index ); - void on_mCheckGridLeftSide_toggled( bool checked ); - void on_mCheckGridRightSide_toggled( bool checked ); - void on_mCheckGridTopSide_toggled( bool checked ); - void on_mCheckGridBottomSide_toggled( bool checked ); - - //frame divisions display - void on_mFrameDivisionsLeftComboBox_currentIndexChanged( int index ); - void on_mFrameDivisionsRightComboBox_currentIndexChanged( int index ); - void on_mFrameDivisionsTopComboBox_currentIndexChanged( int index ); - void on_mFrameDivisionsBottomComboBox_currentIndexChanged( int index ); - - void on_mDrawAnnotationGroupBox_toggled( bool state ); - void on_mAnnotationFormatButton_clicked(); - - //annotation display - void on_mAnnotationDisplayLeftComboBox_currentIndexChanged( const QString& text ); - void on_mAnnotationDisplayRightComboBox_currentIndexChanged( const QString& text ); - void on_mAnnotationDisplayTopComboBox_currentIndexChanged( const QString& text ); - void on_mAnnotationDisplayBottomComboBox_currentIndexChanged( const QString& text ); - - //annotation position - void on_mAnnotationPositionLeftComboBox_currentIndexChanged( const QString& text ); - void on_mAnnotationPositionRightComboBox_currentIndexChanged( const QString& text ); - void on_mAnnotationPositionTopComboBox_currentIndexChanged( const QString& text ); - void on_mAnnotationPositionBottomComboBox_currentIndexChanged( const QString& text ); - - //annotation direction - void on_mAnnotationDirectionComboBoxLeft_currentIndexChanged( int index ); - void on_mAnnotationDirectionComboBoxRight_currentIndexChanged( int index ); - void on_mAnnotationDirectionComboBoxTop_currentIndexChanged( int index ); - void on_mAnnotationDirectionComboBoxBottom_currentIndexChanged( int index ); - - void on_mAnnotationFormatComboBox_currentIndexChanged( int index ); - void on_mCoordinatePrecisionSpinBox_valueChanged( int value ); - void on_mDistanceToMapFrameSpinBox_valueChanged( double d ); - void on_mAnnotationFontButton_clicked(); - void on_mAnnotationFontColorButton_colorChanged( const QColor &color ); + void on_mGridPropertiesButton_clicked(); //overviews void on_mAddOverviewPushButton_clicked(); @@ -174,10 +118,6 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void onPresetsChanged(); - void updateGridLineStyleFromWidget(); - void cleanUpGridLineStyleSelector( QgsPanelWidget* container ); - void updateGridMarkerStyleFromWidget(); - void cleanUpGridMarkerStyleSelector( QgsPanelWidget* container ); void updateOverviewFrameStyleFromWidget(); void cleanUpOverviewFrameStyleSelector( QgsPanelWidget* container ); @@ -205,12 +145,6 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void initAnnotationPositionBox( QComboBox* c, QgsComposerMapGrid::AnnotationPosition pos ); void initAnnotationDirectionBox( QComboBox* c, QgsComposerMapGrid::AnnotationDirection dir ); - void updateGridLineSymbolMarker( const QgsComposerMapGrid* grid ); - void updateGridMarkerSymbolMarker( const QgsComposerMapGrid* grid ); - - /** Enables/disables grid frame related controls*/ - void toggleFrameControls( bool frameEnabled, bool frameFillEnabled, bool frameSizeEnabled ); - /** Enables or disables the atlas margin and predefined scales radio depending on the atlas coverage layer type*/ void toggleAtlasScalingOptionsByLayerType(); diff --git a/src/ui/composer/qgscomposermapgridwidgetbase.ui b/src/ui/composer/qgscomposermapgridwidgetbase.ui new file mode 100644 index 000000000000..da69e57b5d6c --- /dev/null +++ b/src/ui/composer/qgscomposermapgridwidgetbase.ui @@ -0,0 +1,816 @@ + + + QgsComposerMapGridWidgetBase + + + + 0 + 0 + 403 + 734 + + + + + 0 + 0 + + + + Map Options + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + QFrame::NoFrame + + + true + + + + + 0 + -108 + 387 + 1348 + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Appearance + + + + + + + + + Grid type + + + false + + + + + + + + + + CRS + + + + + + + change... + + + + + + + Interval units + + + + + + + + Map unit + + + + + Millimeter + + + + + Centimeter + + + + + + + + Interval + + + false + + + + + + + + + X + + + 12 + + + 9999999.000000000000000 + + + + + + + Y + + + 12 + + + 9999999.000000000000000 + + + + + + + + + Offset + + + false + + + + + + + + + X + + + 12 + + + 9999999.000000000000000 + + + + + + + Y + + + 12 + + + 9999999.000000000000000 + + + + + + + + + Cross width + + + false + + + + + + + mm + + + 2 + + + false + + + + + + + Line style + + + false + + + + + + + change... + + + + + + + Marker style + + + false + + + + + + + change... + + + + + + + Blend mode + + + + + + + + + + + + + Qt::StrongFocus + + + Frame + + + composermapgrid + + + + + + Frame style + + + false + + + + + + + Frame size + + + false + + + + + + + Frame line thickness + + + + + + + mm + + + false + + + + + + + + 100 + 0 + + + + + 100 + 16777215 + + + + + + + + + + + Frame fill colors + + + + + + + + 100 + 0 + + + + + 100 + 16777215 + + + + + + + + + + + + 100 + 0 + + + + + 100 + 16777215 + + + + + + + + + + + + + Left side + + + + + + + Right side + + + + + + + Top side + + + + + + + Bottom side + + + + + + + + + + No frame + + + + + Zebra + + + + + Interior ticks + + + + + Exterior ticks + + + + + Interior and exterior ticks + + + + + Line border + + + + + + + + mm + + + false + + + + + + + Right divisions + + + + + + + Left divisions + + + + + + + Top divisions + + + + + + + Bottom divisions + + + + + + + + + + + + + + + + + + + + + + true + + + Draw coordinates + + + true + + + false + + + composermapgrid + + + false + + + + + + Format + + + + + + + + + + + + ... + + + + :/images/themes/default/mIconExpression.svg:/images/themes/default/mIconExpression.svg + + + + + + + + + Left + + + true + + + + + + + + + + + + + + + + Right + + + true + + + + + + + + + + + + + + + + Top + + + true + + + + + + + + + + + + + + + + Bottom + + + true + + + + + + + + + + + + + + + + Font + + + + + + + Font... + + + + + + + Font color + + + + + + + Distance to map frame + + + true + + + + + + + mm + + + + + + + Coordinate precision + + + true + + + + + + + false + + + + + + + + + + 120 + 0 + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + QgsCollapsibleGroupBoxBasic + QGroupBox +
                                                                                                                                                                                    qgscollapsiblegroupbox.h
                                                                                                                                                                                    + 1 +
                                                                                                                                                                                    + + QgsDoubleSpinBox + QDoubleSpinBox +
                                                                                                                                                                                    qgsdoublespinbox.h
                                                                                                                                                                                    +
                                                                                                                                                                                    + + QgsSpinBox + QSpinBox +
                                                                                                                                                                                    qgsspinbox.h
                                                                                                                                                                                    +
                                                                                                                                                                                    + + QgsBlendModeComboBox + QComboBox +
                                                                                                                                                                                    qgsblendmodecombobox.h
                                                                                                                                                                                    +
                                                                                                                                                                                    + + QgsColorButton + QToolButton +
                                                                                                                                                                                    qgscolorbutton.h
                                                                                                                                                                                    + 1 +
                                                                                                                                                                                    +
                                                                                                                                                                                    + + scrollArea + mGridTypeComboBox + mMapGridCRSButton + mMapGridUnitComboBox + mIntervalXSpinBox + mIntervalYSpinBox + mOffsetXSpinBox + mOffsetYSpinBox + mCrossWidthSpinBox + mGridLineStyleButton + mGridMarkerStyleButton + mGridBlendComboBox + mFrameStyleComboBox + mFrameWidthSpinBox + mGridFramePenSizeSpinBox + mGridFramePenColorButton + mGridFrameFill1ColorButton + mGridFrameFill2ColorButton + mFrameDivisionsLeftComboBox + mFrameDivisionsRightComboBox + mFrameDivisionsTopComboBox + mFrameDivisionsBottomComboBox + mCheckGridLeftSide + mCheckGridRightSide + mCheckGridTopSide + mCheckGridBottomSide + mAnnotationFormatComboBox + mAnnotationFormatButton + mAnnotationDisplayLeftComboBox + mAnnotationPositionLeftComboBox + mAnnotationDirectionComboBoxLeft + mAnnotationDisplayRightComboBox + mAnnotationPositionRightComboBox + mAnnotationDirectionComboBoxRight + mAnnotationDisplayTopComboBox + mAnnotationPositionTopComboBox + mAnnotationDirectionComboBoxTop + mAnnotationDisplayBottomComboBox + mAnnotationPositionBottomComboBox + mAnnotationDirectionComboBoxBottom + mAnnotationFontButton + mDistanceToMapFrameSpinBox + mCoordinatePrecisionSpinBox + + + + + +
                                                                                                                                                                                    diff --git a/src/ui/composer/qgscomposermapwidgetbase.ui b/src/ui/composer/qgscomposermapwidgetbase.ui index 1f0cf6c43e8a..3213c1fb3b46 100644 --- a/src/ui/composer/qgscomposermapwidgetbase.ui +++ b/src/ui/composer/qgscomposermapwidgetbase.ui @@ -6,8 +6,8 @@ 0 0 - 472 - 2688 + 384 + 749 @@ -23,7 +23,16 @@ 0 - + + 0 + + + 0 + + + 0 + + 0 @@ -55,8 +64,8 @@ 0 0 - 466 - 2627 + 364 + 1248 @@ -571,683 +580,25 @@
                                                                                                                                                                                    - - - Draw grid - - - true - - - true - - - composermapgrid - - - false - - - - - - - - - Grid type - - - false - - - - - - - - - - CRS - - - - - - - change... - - - - - - - Interval units - - - - - - - - Map unit - - - - - Millimeter - - - - - Centimeter - - - - - - - - Interval - - - false - - - - - - - - - X - - - 12 - - - 9999999.000000000000000 - - - - - - - Y - - - 12 - - - 9999999.000000000000000 - - - - - - - - - Offset - - - false - - - - - - - - - X - - - 12 - - - 9999999.000000000000000 - - - - - - - Y - - - 12 - - - 9999999.000000000000000 - - - - - - - - - Cross width - - - false - - - - - - - mm - - - 2 - - - false - - - - - - - Line style - - - false - - - - - - - change... - - - - - - - Marker style - - - false - - - - - - - change... - - - - - - - Blend mode - - - - - - - - - - Qt::StrongFocus - - - Grid frame - - - composermapgrid - - - - - - Frame style - - - false - - - - - - - Frame size - - - false - - - - - - - Frame line thickness - - - - - - - mm - - - false - - - - - - - - 100 - 0 - - - - - 100 - 16777215 - - - - - - - - - - - Frame fill colors - - - - - - - - 100 - 0 - - - - - 100 - 16777215 - - - - - - - - - - - - 100 - 0 - - - - - 100 - 16777215 - - - - - - - - - - - - - Left side - - - - - - - Right side - - - - - - - Top side - - - - - - - Bottom side - - - - - - - - - - No frame - - - - - Zebra - - - - - Interior ticks - - - - - Exterior ticks - - - - - Interior and exterior ticks - - - - - Line border - - - - - - - - mm - - - false - - - - - - - Right divisions - - - - - - - Left divisions - - - - - - - Top divisions - - - - - - - Bottom divisions - - - - - - - - - - - - - - - - - - - - - - true - - - Draw coordinates - - - true - - - false - - - composermapgrid - - - false - - - - 6 - - - 6 - - - - - Right - - - true - - - mAnnotationPositionRightComboBox - - - - - - - - - - Left - - - true - - - mAnnotationPositionLeftComboBox - - - - - - - Format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Font - - - - - - - Font... - - - - - - - Font color - - - - - - - - 120 - 0 - - - - - 120 - 16777215 - - - - - - - - - - - Distance to map frame - - - true - - - mDistanceToMapFrameSpinBox - - - - - - - mm - - - - - - - Coordinate precision - - - true - - - mCoordinatePrecisionSpinBox - - - - - - - false - - - - - - - - - - Top - - - true - - - mAnnotationPositionTopComboBox - - - - - - - - - - - - - Bottom - - - true - - - mAnnotationPositionRightComboBox - - - - - - - - - - - - ... - - - - :/images/themes/default/mIconExpression.svg:/images/themes/default/mIconExpression.svg - - - - - - - - - - + + + + + Draw grid + + + true + + + + + + + Modify grid... + + + + @@ -1429,12 +780,6 @@
                                                                                                                                                                                    qgscollapsiblegroupbox.h
                                                                                                                                                                                    1 - - QgsColorButton - QToolButton -
                                                                                                                                                                                    qgscolorbutton.h
                                                                                                                                                                                    - 1 -
                                                                                                                                                                                    QgsDoubleSpinBox QDoubleSpinBox @@ -1501,52 +846,6 @@ mGridUpButton mGridDownButton mGridListWidget - mGridCheckBox - mGridTypeComboBox - mMapGridCRSButton - mMapGridUnitComboBox - mIntervalXSpinBox - mIntervalYSpinBox - mOffsetXSpinBox - mOffsetYSpinBox - mCrossWidthSpinBox - mGridLineStyleButton - mGridMarkerStyleButton - mGridBlendComboBox - mGridFrameGroupBox - mFrameStyleComboBox - mFrameWidthSpinBox - mGridFramePenSizeSpinBox - mGridFramePenColorButton - mGridFrameFill1ColorButton - mGridFrameFill2ColorButton - mFrameDivisionsLeftComboBox - mFrameDivisionsRightComboBox - mFrameDivisionsTopComboBox - mFrameDivisionsBottomComboBox - mCheckGridLeftSide - mCheckGridRightSide - mCheckGridTopSide - mCheckGridBottomSide - mDrawAnnotationGroupBox - mAnnotationFormatComboBox - mAnnotationFormatButton - mAnnotationDisplayLeftComboBox - mAnnotationPositionLeftComboBox - mAnnotationDirectionComboBoxLeft - mAnnotationDisplayRightComboBox - mAnnotationPositionRightComboBox - mAnnotationDirectionComboBoxRight - mAnnotationDisplayTopComboBox - mAnnotationPositionTopComboBox - mAnnotationDirectionComboBoxTop - mAnnotationDisplayBottomComboBox - mAnnotationPositionBottomComboBox - mAnnotationDirectionComboBoxBottom - mAnnotationFontButton - mAnnotationFontColorButton - mDistanceToMapFrameSpinBox - mCoordinatePrecisionSpinBox mOverviewsGroupBox mAddOverviewPushButton mRemoveOverviewPushButton From 60cc853747e53303fd9b2846b65c915dec28abfa Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 11 Oct 2016 16:46:43 +1000 Subject: [PATCH 239/897] Add perceptually uniform colormaps to default styles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the Viridis, Magma, Plasma and Inferno uniform color ramps created by Stéfan van der Walt and Nathaniel Smith See https://bids.github.io/colormap/ for more details Note that I've thinned out the stops here, and only kept every 5th stop from the original ramps --- resources/symbology-ng-style.db | Bin 84992 -> 98304 bytes resources/symbology-ng-style.xml | 24 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/resources/symbology-ng-style.db b/resources/symbology-ng-style.db index 130aa0b6782a23152d4630c27fa38bfc63bab21c..4807ad6169908372f0a2707e49f2475cd686fbed 100644 GIT binary patch delta 6361 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 N^s5o%kj4s5_#czSu*v`c delta 974 zcmZWmZ%kWN6u;-4*T*AaeeG5=`iIiZFjfj~EQJ*nLNYPi z(zr!u;NQK+Z7F4pMKit@@u<65H4~pi)s5pK$y%vQuGVs>V;0Zi89aq2ah%&7 zA*ACaPW$dUQPUg{SJ*GEU^Tx~a#$``ab83$insB1EaEL(#G7~>=SAaHq;ECIXR+SGdx7CrXxdfbYCWpq{(WrLfI!L}}o1 zjyiK1-_-g7n4(NCYw7zBM`&)@!mVw;03B+&O1T4HnM{oC-@lpXAL*3z2^ZL@5ZWN3 z80bGf4X)Sa{B~7>ZU!Ggx9}v$BlC7pUmdJgn0q2fdlv@n0;1`3c$>oRIg?a}hR4R~ z^GrEkyjCG`d3_yCju7qabMbsJ0pwjAp_MN*@;%(ck6f9CyArtlt!3aNZxT?!s23YK zn5|Wm4u)Ci;9YVA`1{u*k~O_+yV%8Kj~XA2J(;9fotsYo@PIku9&z^4OuL8j#h`J` z3toXVYNLZo?^5GK9`3vGFB6T1Jv8^Am2Twh`k@|h>MMirCuz5R#zYJf5)}ge|8f5o zk+gJQjl!H$RcbsrHkOE+Gg416Vv@IrvyV?LoB-VyfOZ=AHK(TnAX8yUfoJth6dZK8 zrj!QON~wA6dGarRttX!V>)p}yj13$-|5K-Ah}?NV0X7S=N4P%Aq^&S3T(2=2J#Z2> zq}v;X%Ttn}59aOWER + + + + + + + + + + + + + + + + + + + + + + + + From e76a4678babf533a811c566e5ad42839f265e2a9 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:34:17 +0300 Subject: [PATCH 240/897] [processing] expose Aspect from Raster terrain analysis plugin in toolbox --- python/plugins/processing/algs/qgis/Aspect.py | 64 +++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 7 +- python/plugins/processing/tools/raster.py | 50 +++++++++++++-- 3 files changed, 111 insertions(+), 10 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/Aspect.py diff --git a/python/plugins/processing/algs/qgis/Aspect.py b/python/plugins/processing/algs/qgis/Aspect.py new file mode 100644 index 000000000000..8dbbbf5bc237 --- /dev/null +++ b/python/plugins/processing/algs/qgis/Aspect.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + Aspect.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" +from builtins import str + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsAspectFilter + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterNumber +from processing.core.outputs import OutputRaster +from processing.tools import raster + + +class Aspect(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + Z_FACTOR = 'Z_FACTOR' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Aspect') + self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') + + self.addParameter(ParameterRaster(self.INPUT_LAYER, + self.tr('Elevation layer'))) + self.addParameter(ParameterNumber(self.Z_FACTOR, + self.tr('Z factor'), 1.0, 999999.99, 1.0)) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Aspect'))) + + def processAlgorithm(self, progress): + inputFile = self.getParameterValue(self.INPUT_LAYER) + zFactor = self.getParameterValue(self.Z_FACTOR) + outputFile = self.getOutputValue(self.OUTPUT_LAYER) + + outputFormat = raster.formatShortNameFromFileName(outputFile) + + aspect = QgsAspectFilter(inputFile, outputFile, outputFormat) + aspect.setZFactor(zFactor) + aspect.processRaster(None) diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index a4e1d3994037..b300a9c8d65b 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -158,6 +158,7 @@ from .Translate import Translate from .SingleSidedBuffer import SingleSidedBuffer from .PointsAlongGeometry import PointsAlongGeometry +from .Aspect import Aspect pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -212,9 +213,9 @@ def __init__(self): RectanglesOvalsDiamondsVariable(), RectanglesOvalsDiamondsFixed(), MergeLines(), BoundingBox(), Boundary(), PointOnSurface(), - OffsetLine(), PolygonCentroids(), - Translate(), SingleSidedBuffer(), - PointsAlongGeometry() + OffsetLine(), PolygonCentroids(), Translate(), + SingleSidedBuffer(), PointsAlongGeometry(), + Aspect(), ] if hasMatplotlib: diff --git a/python/plugins/processing/tools/raster.py b/python/plugins/processing/tools/raster.py index 96b63593bf5d..6ef5e5ca39ce 100644 --- a/python/plugins/processing/tools/raster.py +++ b/python/plugins/processing/tools/raster.py @@ -16,9 +16,6 @@ * * *************************************************************************** """ -from builtins import str -from builtins import range -from builtins import object __author__ = 'Victor Olaya and Alexander Bruy' __date__ = 'February 2013' @@ -28,16 +25,55 @@ __revision__ = '$Format:%H$' +from builtins import str +from builtins import range +from builtins import object + +import os import struct + import numpy from osgeo import gdal -from osgeo.gdalconst import GA_ReadOnly + from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +RASTER_EXTENSION_MAP = None + + +def initGdalData(): + global RASTER_EXTENSION_MAP + + if RASTER_EXTENSION_MAP is not None: + return + + if gdal.GetDriverCount() == 0: + gdal.AllRegister() + + RASTER_EXTENSION_MAP = dict() + for i in range(gdal.GetDriverCount()): + driver = gdal.GetDriver(i) + if driver is None: + continue + md = driver.GetMetadata() + if gdal.DCAP_CREATE in md and md[gdal.DCAP_CREATE].lower() == 'yes': + ext = md[gdal.DMD_EXTENSION] if gdal.DMD_EXTENSION in md else None + if ext is not None and ext != '': + RASTER_EXTENSION_MAP[driver.ShortName] = ext + + +def formatShortNameFromFileName(fileName): + initGdalData() + ext = os.path.splitext(fileName)[1][1:] + for k, v in RASTER_EXTENSION_MAP.items(): + if ext == v: + return k + return 'GTiff' + + def scanraster(layer, progress): filename = str(layer.source()) - dataset = gdal.Open(filename, GA_ReadOnly) + dataset = gdal.Open(filename, gdal.GA_ReadOnly) band = dataset.GetRasterBand(1) nodata = band.GetNoDataValue() bandtype = gdal.GetDataTypeName(band.DataType) @@ -114,8 +150,8 @@ def getValue(self, x, y, band=0): return self.NODATA def close(self): - format = 'GTiff' - driver = gdal.GetDriverByName(format) + fmt = 'GTiff' + driver = gdal.GetDriverByName(fmt) dst_ds = driver.Create(self.fileName, self.nx, self.ny, 1, gdal.GDT_Float32) dst_ds.SetProjection(str(self.crs.toWkt())) From 48c7c49c73c3e21e7d80807bb5314626bb44ec8a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:35:08 +0300 Subject: [PATCH 241/897] [processing] expose Slope from Raster terrain analysis plugin in toolbox --- .../algs/qgis/QGISAlgorithmProvider.py | 3 +- python/plugins/processing/algs/qgis/Slope.py | 64 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/Slope.py diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index b300a9c8d65b..6afad5e541d3 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -159,6 +159,7 @@ from .SingleSidedBuffer import SingleSidedBuffer from .PointsAlongGeometry import PointsAlongGeometry from .Aspect import Aspect +from .Slope import Slope pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -215,7 +216,7 @@ def __init__(self): BoundingBox(), Boundary(), PointOnSurface(), OffsetLine(), PolygonCentroids(), Translate(), SingleSidedBuffer(), PointsAlongGeometry(), - Aspect(), + Aspect(), Slope(), ] if hasMatplotlib: diff --git a/python/plugins/processing/algs/qgis/Slope.py b/python/plugins/processing/algs/qgis/Slope.py new file mode 100644 index 000000000000..99c2f04ce456 --- /dev/null +++ b/python/plugins/processing/algs/qgis/Slope.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + Slope.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" +from builtins import str + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsSlopeFilter + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterNumber +from processing.core.outputs import OutputRaster +from processing.tools import raster + + +class Slope(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + Z_FACTOR = 'Z_FACTOR' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Slope') + self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') + + self.addParameter(ParameterRaster(self.INPUT_LAYER, + self.tr('Elevation layer'))) + self.addParameter(ParameterNumber(self.Z_FACTOR, + self.tr('Z factor'), 1.0, 999999.99, 1.0)) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Slope'))) + + def processAlgorithm(self, progress): + inputFile = self.getParameterValue(self.INPUT_LAYER) + zFactor = self.getParameterValue(self.Z_FACTOR) + outputFile = self.getOutputValue(self.OUTPUT_LAYER) + + outputFormat = raster.formatShortNameFromFileName(outputFile) + + slope = QgsSlopeFilter(inputFile, outputFile, outputFormat) + slope.setZFactor(zFactor) + slope.processRaster(None) From 2c2ff64f7df19a3f6d7a473ecd7bf8cd1254a5c8 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:36:13 +0300 Subject: [PATCH 242/897] [processing] expose Ruggedness from Raster terrain analysis plugin in toolbox --- .../algs/qgis/QGISAlgorithmProvider.py | 3 +- .../processing/algs/qgis/Ruggedness.py | 64 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/Ruggedness.py diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 6afad5e541d3..1929146611cc 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -160,6 +160,7 @@ from .PointsAlongGeometry import PointsAlongGeometry from .Aspect import Aspect from .Slope import Slope +from .Ruggedness import Ruggedness pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -216,7 +217,7 @@ def __init__(self): BoundingBox(), Boundary(), PointOnSurface(), OffsetLine(), PolygonCentroids(), Translate(), SingleSidedBuffer(), PointsAlongGeometry(), - Aspect(), Slope(), + Aspect(), Slope(), Ruggedness(), ] if hasMatplotlib: diff --git a/python/plugins/processing/algs/qgis/Ruggedness.py b/python/plugins/processing/algs/qgis/Ruggedness.py new file mode 100644 index 000000000000..8487638af171 --- /dev/null +++ b/python/plugins/processing/algs/qgis/Ruggedness.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + Ruggedness.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" +from builtins import str + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsRuggednessFilter + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterNumber +from processing.core.outputs import OutputRaster +from processing.tools import raster + + +class Ruggedness(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + Z_FACTOR = 'Z_FACTOR' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Ruggedness index') + self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') + + self.addParameter(ParameterRaster(self.INPUT_LAYER, + self.tr('Elevation layer'))) + self.addParameter(ParameterNumber(self.Z_FACTOR, + self.tr('Z factor'), 1.0, 999999.99, 1.0)) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Ruggedness index'))) + + def processAlgorithm(self, progress): + inputFile = self.getParameterValue(self.INPUT_LAYER) + zFactor = self.getParameterValue(self.Z_FACTOR) + outputFile = self.getOutputValue(self.OUTPUT_LAYER) + + outputFormat = raster.formatShortNameFromFileName(outputFile) + + ruggedness = QgsRuggednessFilter(inputFile, outputFile, outputFormat) + ruggedness.setZFactor(zFactor) + ruggedness.processRaster(None) From 15902aa2fa229dabbbf68c649eb62d751fcac1cb Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:37:11 +0300 Subject: [PATCH 243/897] [processing] expose Hillshade from Raster terrain analysis plugin in toolbox --- .../plugins/processing/algs/qgis/Hillshade.py | 72 +++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 3 +- 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/Hillshade.py diff --git a/python/plugins/processing/algs/qgis/Hillshade.py b/python/plugins/processing/algs/qgis/Hillshade.py new file mode 100644 index 000000000000..b9367e781b37 --- /dev/null +++ b/python/plugins/processing/algs/qgis/Hillshade.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + Hillshade.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" +from builtins import str + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsHillshadeFilter + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterNumber +from processing.core.outputs import OutputRaster +from processing.tools import raster + + +class Hillshade(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + Z_FACTOR = 'Z_FACTOR' + AZIMUTH = 'AZIMUTH' + V_ANGLE = 'V_ANGLE' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Hillshade') + self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') + + self.addParameter(ParameterRaster(self.INPUT_LAYER, + self.tr('Elevation layer'))) + self.addParameter(ParameterNumber(self.Z_FACTOR, + self.tr('Z factor'), 1.0, 999999.99, 1.0)) + self.addParameter(ParameterNumber(self.AZIMUTH, + self.tr('Azimuth (horizontal angle)'), 0.00, 360.00, 300.00)) + self.addParameter(ParameterNumber(self.V_ANGLE, + self.tr('Vertical angle'), 1.00, 90.00, 40.00)) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Hillshade'))) + + def processAlgorithm(self, progress): + inputFile = self.getParameterValue(self.INPUT_LAYER) + zFactor = self.getParameterValue(self.Z_FACTOR) + azimuth = self.getParameterValue(self.AZIMUTH) + vAngle = self.getParameterValue(self.V_ANGLE) + outputFile = self.getOutputValue(self.OUTPUT_LAYER) + + outputFormat = raster.formatShortNameFromFileName(outputFile) + + hillshade = QgsHillshadeFilter(inputFile, outputFile, outputFormat, azimuth, vAngle) + hillshade.setZFactor(zFactor) + hillshade.processRaster(None) diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 1929146611cc..fc1bb67b4b23 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -161,6 +161,7 @@ from .Aspect import Aspect from .Slope import Slope from .Ruggedness import Ruggedness +from .Hillshade import Hillshade pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -217,7 +218,7 @@ def __init__(self): BoundingBox(), Boundary(), PointOnSurface(), OffsetLine(), PolygonCentroids(), Translate(), SingleSidedBuffer(), PointsAlongGeometry(), - Aspect(), Slope(), Ruggedness(), + Aspect(), Slope(), Ruggedness(), Hillshade(), ] if hasMatplotlib: From 7b747743221ddb82fefad9732eabdccfc75eed22 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:38:09 +0300 Subject: [PATCH 244/897] [processing] expose Relief from Raster terrain analysis plugin in toolbox --- .../algs/qgis/QGISAlgorithmProvider.py | 2 + .../processing/algs/qgis/ReliefAuto.py | 72 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 python/plugins/processing/algs/qgis/ReliefAuto.py diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index fc1bb67b4b23..f053e2c71c6a 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -162,6 +162,7 @@ from .Slope import Slope from .Ruggedness import Ruggedness from .Hillshade import Hillshade +from .ReliefAuto import ReliefAuto pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -219,6 +220,7 @@ def __init__(self): OffsetLine(), PolygonCentroids(), Translate(), SingleSidedBuffer(), PointsAlongGeometry(), Aspect(), Slope(), Ruggedness(), Hillshade(), + ReliefAuto(), ] if hasMatplotlib: diff --git a/python/plugins/processing/algs/qgis/ReliefAuto.py b/python/plugins/processing/algs/qgis/ReliefAuto.py new file mode 100644 index 000000000000..17533df69cbe --- /dev/null +++ b/python/plugins/processing/algs/qgis/ReliefAuto.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ReliefAuto.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" +from builtins import str + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsRelief + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterNumber +from processing.core.outputs import OutputRaster +from processing.core.outputs import OutputTable +from processing.tools import raster + + +class ReliefAuto(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + Z_FACTOR = 'Z_FACTOR' + OUTPUT_LAYER = 'OUTPUT_LAYER' + FREQUENCY_DISTRIBUTION = 'FREQUENCY_DISTRIBUTION' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Relief (automatic colors)') + self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') + + self.addParameter(ParameterRaster(self.INPUT_LAYER, + self.tr('Elevation layer'))) + self.addParameter(ParameterNumber(self.Z_FACTOR, + self.tr('Z factor'), 1.0, 999999.99, 1.0)) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Refilef'))) + self.addOutput(OutputTable(self.FREQUENCY_DISTRIBUTION, + self.tr('Frequesncy distribution'))) + + def processAlgorithm(self, progress): + inputFile = self.getParameterValue(self.INPUT_LAYER) + zFactor = self.getParameterValue(self.Z_FACTOR) + outputFile = self.getOutputValue(self.OUTPUT_LAYER) + frequencyDistribution = self.getOutputValue(self.FREQUENCY_DISTRIBUTION) + + outputFormat = raster.formatShortNameFromFileName(outputFile) + + relief = QgsRelief(inputFile, outputFile, outputFormat) + colors = relief.calculateOptimizedReliefClasses() + relief.setReliefColors(colors) + relief.setZFactor(zFactor) + relief.exportFrequencyDistributionToCsv(frequencyDistribution) + relief.processRaster(None) From e2f36e40d15f9a154261ea69206c3c7386e833ca Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:38:49 +0300 Subject: [PATCH 245/897] [processing] remove unused imports --- python/plugins/processing/algs/qgis/Aspect.py | 1 - python/plugins/processing/algs/qgis/Hillshade.py | 1 - python/plugins/processing/algs/qgis/ReliefAuto.py | 1 - python/plugins/processing/algs/qgis/Ruggedness.py | 1 - python/plugins/processing/algs/qgis/Slope.py | 1 - 5 files changed, 5 deletions(-) diff --git a/python/plugins/processing/algs/qgis/Aspect.py b/python/plugins/processing/algs/qgis/Aspect.py index 8dbbbf5bc237..82a4fdb773ed 100644 --- a/python/plugins/processing/algs/qgis/Aspect.py +++ b/python/plugins/processing/algs/qgis/Aspect.py @@ -16,7 +16,6 @@ * * *************************************************************************** """ -from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2016' diff --git a/python/plugins/processing/algs/qgis/Hillshade.py b/python/plugins/processing/algs/qgis/Hillshade.py index b9367e781b37..ec925cc83445 100644 --- a/python/plugins/processing/algs/qgis/Hillshade.py +++ b/python/plugins/processing/algs/qgis/Hillshade.py @@ -16,7 +16,6 @@ * * *************************************************************************** """ -from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2016' diff --git a/python/plugins/processing/algs/qgis/ReliefAuto.py b/python/plugins/processing/algs/qgis/ReliefAuto.py index 17533df69cbe..6ad8afe6751e 100644 --- a/python/plugins/processing/algs/qgis/ReliefAuto.py +++ b/python/plugins/processing/algs/qgis/ReliefAuto.py @@ -16,7 +16,6 @@ * * *************************************************************************** """ -from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2016' diff --git a/python/plugins/processing/algs/qgis/Ruggedness.py b/python/plugins/processing/algs/qgis/Ruggedness.py index 8487638af171..6a16532ca849 100644 --- a/python/plugins/processing/algs/qgis/Ruggedness.py +++ b/python/plugins/processing/algs/qgis/Ruggedness.py @@ -16,7 +16,6 @@ * * *************************************************************************** """ -from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2016' diff --git a/python/plugins/processing/algs/qgis/Slope.py b/python/plugins/processing/algs/qgis/Slope.py index 99c2f04ce456..5dbf8869ba66 100644 --- a/python/plugins/processing/algs/qgis/Slope.py +++ b/python/plugins/processing/algs/qgis/Slope.py @@ -16,7 +16,6 @@ * * *************************************************************************** """ -from builtins import str __author__ = 'Alexander Bruy' __date__ = 'October 2016' From fabc0970c5f2fa8874a065a4c1a395797d914ca2 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:42:28 +0300 Subject: [PATCH 246/897] [processing] add icons for raster terrain analysis algorithms --- python/plugins/processing/algs/qgis/Aspect.py | 9 +++++++++ python/plugins/processing/algs/qgis/Hillshade.py | 9 +++++++++ .../plugins/processing/algs/qgis/ReliefAuto.py | 9 +++++++++ .../plugins/processing/algs/qgis/Ruggedness.py | 9 +++++++++ python/plugins/processing/algs/qgis/Slope.py | 9 +++++++++ python/plugins/processing/images/dem.png | Bin 0 -> 1555 bytes 6 files changed, 45 insertions(+) create mode 100644 python/plugins/processing/images/dem.png diff --git a/python/plugins/processing/algs/qgis/Aspect.py b/python/plugins/processing/algs/qgis/Aspect.py index 82a4fdb773ed..5034ca1acb90 100644 --- a/python/plugins/processing/algs/qgis/Aspect.py +++ b/python/plugins/processing/algs/qgis/Aspect.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.analysis import QgsAspectFilter from processing.core.GeoAlgorithm import GeoAlgorithm @@ -33,6 +37,8 @@ from processing.core.outputs import OutputRaster from processing.tools import raster +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class Aspect(GeoAlgorithm): @@ -40,6 +46,9 @@ class Aspect(GeoAlgorithm): Z_FACTOR = 'Z_FACTOR' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'dem.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Aspect') self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') diff --git a/python/plugins/processing/algs/qgis/Hillshade.py b/python/plugins/processing/algs/qgis/Hillshade.py index ec925cc83445..9521b4bd8b1a 100644 --- a/python/plugins/processing/algs/qgis/Hillshade.py +++ b/python/plugins/processing/algs/qgis/Hillshade.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.analysis import QgsHillshadeFilter from processing.core.GeoAlgorithm import GeoAlgorithm @@ -33,6 +37,8 @@ from processing.core.outputs import OutputRaster from processing.tools import raster +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class Hillshade(GeoAlgorithm): @@ -42,6 +48,9 @@ class Hillshade(GeoAlgorithm): V_ANGLE = 'V_ANGLE' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'dem.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Hillshade') self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') diff --git a/python/plugins/processing/algs/qgis/ReliefAuto.py b/python/plugins/processing/algs/qgis/ReliefAuto.py index 6ad8afe6751e..06782d9242d9 100644 --- a/python/plugins/processing/algs/qgis/ReliefAuto.py +++ b/python/plugins/processing/algs/qgis/ReliefAuto.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.analysis import QgsRelief from processing.core.GeoAlgorithm import GeoAlgorithm @@ -34,6 +38,8 @@ from processing.core.outputs import OutputTable from processing.tools import raster +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class ReliefAuto(GeoAlgorithm): @@ -42,6 +48,9 @@ class ReliefAuto(GeoAlgorithm): OUTPUT_LAYER = 'OUTPUT_LAYER' FREQUENCY_DISTRIBUTION = 'FREQUENCY_DISTRIBUTION' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'dem.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Relief (automatic colors)') self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') diff --git a/python/plugins/processing/algs/qgis/Ruggedness.py b/python/plugins/processing/algs/qgis/Ruggedness.py index 6a16532ca849..5d3d19f54cf8 100644 --- a/python/plugins/processing/algs/qgis/Ruggedness.py +++ b/python/plugins/processing/algs/qgis/Ruggedness.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.analysis import QgsRuggednessFilter from processing.core.GeoAlgorithm import GeoAlgorithm @@ -33,6 +37,8 @@ from processing.core.outputs import OutputRaster from processing.tools import raster +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class Ruggedness(GeoAlgorithm): @@ -40,6 +46,9 @@ class Ruggedness(GeoAlgorithm): Z_FACTOR = 'Z_FACTOR' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'dem.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Ruggedness index') self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') diff --git a/python/plugins/processing/algs/qgis/Slope.py b/python/plugins/processing/algs/qgis/Slope.py index 5dbf8869ba66..a8edbdc31b70 100644 --- a/python/plugins/processing/algs/qgis/Slope.py +++ b/python/plugins/processing/algs/qgis/Slope.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.analysis import QgsSlopeFilter from processing.core.GeoAlgorithm import GeoAlgorithm @@ -33,6 +37,8 @@ from processing.core.outputs import OutputRaster from processing.tools import raster +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class Slope(GeoAlgorithm): @@ -40,6 +46,9 @@ class Slope(GeoAlgorithm): Z_FACTOR = 'Z_FACTOR' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'dem.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Slope') self.group, self.i18n_group = self.trAlgorithm('Raster terrain analysis') diff --git a/python/plugins/processing/images/dem.png b/python/plugins/processing/images/dem.png new file mode 100644 index 0000000000000000000000000000000000000000..851710baedd49f3bac8cc87b194ad3ec921fd834 GIT binary patch literal 1555 zcmV+u2JHEXP)V>IRB3Hx05UK!GA%GPEiyHow$x() z002^SMObu0Z*X~XX=iA307F9{L3DI-X<~JBX>V>VQ)ppwWkGCdYh@s4baZe!FE3+q zWnpw_c4cF4ZEbIEb1rXkXD@7NV`Xl0WpgiLc`b8cFEcJMFJ6OMyZ`_M)k#D_R7i=H zl}l_JRTPH58IQ+rdtxV!(k`gM^R}AR$q)K`hvz?pUxx>=3FD zuwjWPs{*Qk@{lM+r9fNJ2T5t0I&oshv17+$d){+dOi73geVpC=_niOJJ!kH{()Tl6 z!CizabadxWOs~p?+IO_=D>#0Oba)C)-HoR1LR0qu5&+Vj0=n)jHS=p$tkVb_0A^d~ zXc`NBxw*(b?$3TiG*m#jopIAXL)AD=*Zr$+EfLOOI!nYt3PM2BHUVf@r#QdzDtm{H z{Xf9RqSX1AhIMkIsS;)^o?Y&TX+9Iaw z0#J}&0tf&C!8QE|w%I_~N!Ez@LC*O3&T!6!S! ziWXPeO-@uw0BGtSRJXVeShdfhI~M`ipC6?Vi{o`^I}AYkd;;H+5VnoI5d2N`UXNwF z!@wh5Qd0)D@cF!aoip`nU?#=csl81klt+!m0?o&vWt|0Jduo7?B;n~Y#(Wrrz?_>y z_&&?M9_@i9g~vK5Nso%riOSr-ZAg*j?Tk7?jcMwFPagv#A01&KSMLt1+Z^?M= zHcq`x(=_RBT}HcU{!6{WR|~TMgk_D*i9;0PPXi$UWLai#WPE)FvCzocN7d*B+f@v# z@)CyYQuEss_5}KTPv`hzU_Kguj$+~vAvv*DFG&)^W7|+8v2}nd50VP+M0YMz?&+9z zjp)zY!$8-3;gxsh?=sZ5_P8;-yy*x z1nvV>atCw(F1G4iYBflPcaV=B>@&&cH<8NZ`g8z!rRxDIqwyC2_@h~4wd>#u0TOgQ zhcC<50oa;+4c0E_Ahg^tnQZ<)&DUB4P)xiGfaQ67Q!eC*X z!NNFq8htNXF>wfxSco1)I3d#hev0uIQPc?Wo6qIl#NV9DClxU$YB~S_002ovPDHLk FV1h{_xLg1L literal 0 HcmV?d00001 From a356bac1a5ead4d299a11371aedf0dd36c1ef80a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 6 Oct 2016 19:43:31 +0300 Subject: [PATCH 247/897] [procesing] add tests for raster terrain analysis algorithms --- .../plugins/processing/tests/testdata/dem.tif | Bin 0 -> 524063 bytes .../tests/testdata/qgis_algorithm_tests.yaml | 62 ++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 python/plugins/processing/tests/testdata/dem.tif diff --git a/python/plugins/processing/tests/testdata/dem.tif b/python/plugins/processing/tests/testdata/dem.tif new file mode 100644 index 0000000000000000000000000000000000000000..efa17dd827e1beaaa58c70fcf6fa0e49ba794815 GIT binary patch literal 524063 zcmeF3^;Z>b`}Vh_fr5yLfg)m|bSNNooPgckjosbd?QM6rdvA8m&|qPAcXunceh;7f zdDr^>@UHhScwOsqW=~!-?EN{9InMK%`t^M^qklMRTr`>jwweMOjb;@8EAZd>E}Xad z@4Oe++5UI_?{*IVYrc2^J53UoJ>iOy|7*GXf9LJFuGD|GIm7vK|7)9;|DCtx@?tZb zG=HbRZ8VzcGo3UJoOkB}-5gtu7w3~Wub<(r6wODxh(wT0rBQP(ah9djZYx z$ptj4))&yEDg`umE*H?)d@P`;;$ov|;Af*5+`vY&ypN5>GSfzLW2=qkcczWT`<9I+ z>6?wFKmTBhLu@sMX11CugKRb5=i6$^@3Gb3h^;31fvsl#A6t#KoSo)EgqzID1WGXM0VT@%EbOtL-(rO!k@+=j}Cb z-q>qgog6gb)g3e)k{mRXdpc;gO?A*5-RPisk?No+cFjQ({MkX%#??_XKEP44sga{5 zx1Xct$!teW;T?_|{~Sk6i#v{*hwPb>3_aN|BwGFr_GtVd|z{Hk-x9|OOf1vF1w3KUG4!?hZR|9oCtsZc@voWJXf z{Aa4s%pEjxmFJG(e~%Zpt5v)Bwsl*2)efDgnX9O{&9+BXaW7TH*mM{ zMbHryyN{`;aze#{Qz~N5s(5f-#imOt#$Dz1H&m>@t>W%Iu6v}y@Ki+l$ z`K%)1n+nTM6;(BBB`ibG!=i?%xtZlQgMgNdvg7s0;xE`eXixJ zsQpgG*Jmoc@AEjEL!&Ka7e};LhaOFAAI;+q+u(1z$pA@`%sler-g5oz6Tt25D?il-*p0KM`HzpV-?&ARPeE)f-|lP=G!Xp`D8`!M^=2hXvOAS zD?;>E9N1um?Oe_ew<4^g6&kT(L3Jyx7PI2X2Mdl}wqS|Xf{tq}XgSsbeOn9i!YwG_ zZh?2c8NIHWp{Qn5++fC^iDsBOm{B0qj3JI@xL+`#ip9$aCruR2t8>e=COjzB+gz}wC zxYfc0-$WDI2biGIn6R?62?xuV5LVKJlTId_voYc67bE(=GGgOBBX(XgBLA2Xxn?6A zR~b>Lml3Ocj2L#$0BkZ~em4W$sv2uf?T-T5O)K#qxDp%rj}R;G7m0-)Q0MqQk;) z9WM6PVb*pXK7G<*S|>fiuIb^~GXR5j!3B{Lq(v>-p+ z3ZEBN#BJpFstLcJzxdtUlM1y_8sc80;pCKbd~(Ww+wu%-aLL4g1(|Sj%);4uS#TZ=DME{!_IaJeDtljKo&>%;t(zuXp{#{rm%yg1J4~xqFO3w1W zzKb;JR9sGVah0;IN=Q_Un~bhdQVRVjDW5L6i+xHd*|p3=hKwmK$GVr1OHIqltGIH~ zJk(R{s+X5yI;4g)DqmA{xizJEM?ZP>)K60S`OA=p{u16kK>nNwke^9`V#*Gbyoex~ zs|ylauVAS)KUmUU2g}$7Au@MMh=jfik;0LoQg}+Je8~=#!!}{^q+Xb~t__n%U&F*W zAYAUf3zv&CYRNUv+M+78Wq-2>sr)!X_Kb~`HO^5Ir;U;$ZR$v+g3)p}Gg@?`W8_+m zSXq2CRyNIulaCeSWuz%yydog=v=G%*B&WAX@!cYuu855KB(g`7AaUgRYPP;A*+r(; zOIJ~gOz%#no5=L?Wao-wDqP6)rDS?(^3*`4_af74k?DbCdNVS81)2W&A&>J^#p4$$ zdXwo7->c|Grr-Ihq7(Ui`HzYyGJQ0e-IMITOs20P%f}TQ3UPYT7Dr{Gi^>fMEaVpl4sp)OFkEm$q zuR`yxqU{d__pX!U2Ni^bDEOdP;C@fR6B`wmJXQFFFa{;4uxX(py0ePm$tvsztB50~ zTk)7(CaD-qe$OMv50dAX*?w@|lZ>xDnfG8k*N;-Mg-rj(^DiaSXS7%GmQ4TnU#7>A z>Dgp@g13rW9=rxJeKeUqkxbu4reFUr(`%6FMHqjUk?EVrbWfuKhdl~9Z(!e-Dp*gZ z?;+Fskm)zcblWD30c3hokb;KZ3JRA{aEwgfM5YHnw!-1E6~_-*F)+o7w;Qc!KF^9J zBdplk$%=^yR=Cx$BH6`?k)JH6ca=O)ELgLaOdn@K`*s%mB-1lXTF~XQ8Tu<`a+=Q}3MJ7vNW zvk5lqO=vmIgg=AHZ1Q_SUox6(Z#B?_xtu=d=gqxL*xtp2!EH>?H!xvS1ml9Q31)8- zCX_d!Xekp?i<%H;Yl7`pBkGdrjmh*eWO}RPM%>9Z;@nOnvWFOk(K)k9N;>*qW!q^*uVgny15& z0Xj4%( zC%F9504;Tb7N6I0ol%RoXSwXP7C(yWaDc~N-iha3sl&5Jj3Z6-sC-5bkIpIR|0xB# zmm07=(1@bE)<@$_s9xC&>jg9XXIOAQ%!-@Ot$0MHui$sE2lZ6;{#4X#o`#lh)8IQR z9pzm!(0o+}Ub|*u?fguJl{$@K3PYs-kN+R~?Og!FqJA*p0~vm#N_ zW_Of4Yg$K=ZKLH%dbC_3(^~vc z2}Q1(;Q7XcAKy%<{L6$2U#Yuan$UrqFP3G(s?8=e9%DjwXA??Mi*KejA2Nh&8fHTH zP!oDl@5gglFuC4|T;E8pA8BYpj~KE)$b?yyO|Vj{?{YT5$IgTRGX45XBii0IBIu$K zU-FEYb;S4|U0-Lk5gn@=F^xKX`f@V8g#k^f7*I=Nz{6uHSTsEaJHt}Y@wpyVcIz>6 zq#m6c>+!-@5AQ;HJbJ1_hhsYI*sa6yxjJO^C&wG>kQu1M5;q+#ebr*=Z7uHPYVl`} z79E#rF?F04WqXs|Ewwn8sD(nF&kNLI6`LLP`n*^*t@)xDP2MIPF`|SQ&FaWsVMv2c#Dwfch31ph4jkui%fT&S5->%swPTE zby@qZy7X3k<=z zy>NMTGhBv|>9_oA%i9aJzeaA|q~^Rs{*k$p9#f}2 zQ_=I43iYiDhmYiMzKV0-$n{?;g6XLgCDU({+k?pO;bi%&;;D#qO+_51OUd=I)arA& z%}{EK>EEe$d5lXh$zvTUtV8$UZ{xnr_h#W>Q?#H;`ID%f!SQSGj z@!5bp7c#udY?PA%UZ8eA&S^HaxkW*Z{R*1$_jzHt zf|s)t92(1bG(f@k&I(#L<2)1uhVr^9bH1cPjwwj_YQ>P3R@A#?#gvm)G*PYixYLT2 z%d7~WXhn8!YV;;nl%S^DUd9ULw*^h^TQD%!01IX**ZtMvFW>;aH+Wo z*XnS-rU^Hw)!!Fq46rw$8JS*|Oy7Llh??h&*m{WGOR5oZTaEZM*oZ7&BgQ^4;PM&+ z&uKv67z1urG{EIa3NEf>i%dcC6+Pa~(PKnMJ(3gkSW;Dwa*leGexk$FBRXX7)Zy!F z9X$K#P^^&-n*(&%RYC_lGX20Uwj3>L?bbrSNDIp-ErPmf;n_rs!f{$u45N;(uI0J4 zm>r?Tp%z+9qK@w}S&R0ow5XDzMKqaSiA+CJkTIj8j?Z2?G_1*UchQNvu z1*;yXz<;Iz>na(sjBzWR_b7(<`0XM79mZJj(2w34^p5oZvO&v0cC@$E)~Q?k2u=y9>_-k1%o0b3_Ea!H9JqU>o)YeH;Ho)>VzfjkJ}H zH|(XCO+o4Tw2+*eT|`>Gagy+WVlu6jvrOsjBH;szOXVT1(yM<7a?4FB1(cL6pG(SV zv%5^6QA&37_mJqWr6sXR87UuDR-C=diC=k7*;S#uv@cab`q+6%n@?U+;$212QKxTt zTuGLm^^v~T%F={Pf4rosJRV$4?nG9X)nqy>zG56xLtJasl*Z3%%8B_Kt+pgDi;zjKkzzkNQW`vt zluyY~^47hMBtEVq!z|Hqb3%+*YsJd8*RkTUIZhtbkC!^n<7LuV$hl7tbQbwVjlSul z$TjZ-NsLR7CXEv0qKT|B^KVWzJ|x%QlIv~gX?)Hkn{wzW9Hu5eO1_inb;;3Yr|Bb~ zrADPzzE7>b;EIY_*HxS%YwO>mH&3nJ{V91)U455Y{pCAq+fUqwTHW>sz3M;YJvI1e z$5bpK({H<^QX{6q-JO0*$y5v>+k4QD8O-&k$bSvFzMlJ6jpZliSgw50CIfsJl>D_^rRM$@0?DX%eX+U zH=RZ=W&-cWC>3sl>09+y@lPk-gBB`|lj&2)^lG6ho>r%CQ-M5pXI~go`r4}4`JLYR z2eSKxf}v#kT{6AJMe6dC^oDX3_^I^9wF>h2`z*Xt!I3%iUB)XYG)Tejt_s3iP|qhQ zI3BK0+bLLGT0yrW3VQ#hfBv4@{2~383*>ngz4HTB^jTxYfEiW{9mEH?HddrWTd}kf z8SiLC=nLxe6V&Be__SLZgz{c#np^J1%L#ya}D3j)k28%F)eR># z6Wr%eyK~x!o=lsGCX^uCXOi{))a^Y-n6PfG3C*eNXC|2Ng<8E0J(xmn)a?%R+R60F zFX*Y?q;5TB#ELYsZnqI1<{7cJn-NR>*gjFGn+=GbXF!d~2KXf#;84zhe0>V8)Js7D zGMyP!lxU@gUxFSXWO^wFJ%rvzsY5!HrnlX5CVlQ?9sC>U5ah4JI#(S+zi4s&CbfCC z7KuCQna|f^_fRct+iNkH8a=m`7C!^DIOeNG$lob-dIoj+zCQG6=+U&GS2JJB{mFFi zw_3Q+duijNLlHlEE-j~)g-lX zb$Rl>y0~rkl_?`?h)wgFQoX33Wa<2*YaM@?Y4Vrq?g3JU-it;PAiJUirTgPRIWv?x z{Z){}cL|m+$AYC@jS%TMFGSWq2$65$p^`HzRGOU*mCc32q+xA(=#9c8CnQYF6~koP zvM^b{FkBk$tR-D$)|O*+BBbY~2(dJXl#**BWx@VPDWQpyH^-x-`t3ThC@WfQ=fudl z*jUkij+JHFI0;XV7hhLM;66xv4H45yk@GJ^Y-=XS!VU@2YfOUFn2{hG4D>3D^d3y~ zO33x@3Uy~1buXFjLZ-hyME`?Kx8|u>dxHEw#T+TQzMV|flIs;Ok$q%r=Nr_jcc`cD zlYfs@WIUsueMvv(4Vg=>pZrLj{)M`iT;D=Ym*=yfJDJ{`3@__Jc9%iF$s`ql6B$UiaOkm+N2OgF}i+qcL^J|ifMF`3!a?(F-8-8}9(YV1WSu1=vxO}*Tn zT;0`<{tS5?O&$Irf;rAmYG-o1RxK45qv?SsF)mP_-{p3F$#XyQyefI#Wi-!2M(fD) zo8)=lxqKcW$CvQt5Wp^*9w>`JB+LuZp={==rx|?zleh zFPYws=UrEg$1l(8aAW)^OuwiAy(>OD^m?bj@=U?3`wEVd>0K^SkDsPyKdN9CJ@rur zu47&|ceR42^AupBf*XSsZ0t@Csg;5Tb?Mtg(!Z%myY8vp)Pw^*d@f*~)W*?-)?|9vb0g|sH=;a!mop|K%o~k(G1Z7gosF0r z%6w@->h;?Ol+H5XsA^zt#fUix1`Irvg8SW4aQ1^9zc=XVpXu?P-pez3FEM0#1U2%_ zEFFe#*5U3{=0F_;Che`1|j2=q9 zzt`dFEHeDq?o8T*+7dE&vp`5h~c?V?7Y#&8Se zZ|Y+z5)Y)|V~2EH{FRPA%#Y44nTg}mGm(8U6Hk6;qVtzboY|a-IuA2(qe`WyjuKX|5T{PktecZ;pIlTLZz?8@_c=?46)s#}T>7qdl`FaulC<4Twu~t$ zt*g0_Gxyz_l9@1=KX<0F?j2x;}mdnb@R3A@i*0H?UwXPukZeCpGB{zOml$kXu z$+Rjy{9O4z?MiAD(VVU-V@%Z~eJpi)abGU?l|`#-$c`B`Wn6-voMnDAXr#Ynyz-Y7 z%>!h?#sK-}XMluH4V0fAK~iaBkc@Q;mZ{T&W!CdxY1%METI>yx!FHjtr&FkW(}zlx zKWq{vTSqZRIwwrpwF~2ULjTkHsNwSQYb|;Cq_!N|5h2^^M9SWSY%e2a@r6ik6Cq(2 zqU7`UI^ujkT54~Ok;+N2((*&B^itzw^@4bbXbeez3-K5wGW(v$=gJ~Ba`Y)z1Z z842<$FF_1Caz#%~nZg_-*`7$Q4^*jB)2Xe=%avq$V=}!*9(C+-dd%edZ?e?)G`W3- zd_PB?U8IgD*Q?xQO$T-KWOCQ~g#3J_V)hHxr@SK5-_XDKK+T#@z5kP(r>~w!kL3rM zeupe?RXG*Ls?3X4OvOOz^+@{dL;sMgi~~ivU)F2J6dvnuUClBc|1-J1iRZ1#eobKv z>a8VDx6&h8!8kIPv1TG!O*Yp^=D9mDZnY-+$?gl}`!Tj)&W~xy=LoXgrYm_({;wUt zxIi8^8AHx;|DMz6latl|kl7y>@>Bs>&kYJpLcV45_vzB+culbI76-e zipMI$7_pA$Jw&G8WBjNQ%>Ak`MwDeNDbD!d$b0jf%w|o_UV8lthVCxbSvgitLIRw+r?P%!kfC?o<93y`swsvnryOQ z3!mddn^<1kqr5@Lc%-Myu|8HI;3KgxE0uo;nq%vjFWnV;K?GUM|E z`ZF`lIJm@&mW#}oI+|>6PVNMn(Ym-9hdzsez+9@emkAH)t4~NW;dmH*m&zs>-07*4>3zubf1VkUch!jb^dmx3jQFifKADU8jThL>*ptr5BP&uKVh6pEWA!WV(jlOC##^reyl>nObb6m;OCL ziw+gEFcj5dtcMmaL$!#kuSIX__nlmC!@8Hw9QG4Lwmf`bl^>FIQ8rNh}# zI^=KC;p2U_`g%+{rAPC2DX@8z0=J)L^dpENg-2g*}b7prix;##b1# z`JEX|@9;$9RMhfF!-^Ye_(U(gb!-O0ZfC%@UnXkarjH(&1yhSGL{-UxZgM6$oQ6A% zv$0Z}i^~fRBQN+U9A@TW@1~Q8pLG@k4Akglu3=%zTNpj=9+v1I!C3A&uFQRnDNEmD zZ|W!54*!ZmM}FbEjg8DYYA5GC9c4n3LbBhxh@4sJBu?2y#pgjW8T!syA|JZQwwuMp z@WfR<=a-QE&)sBCPDx3a=q~SzmXh|zO3B-!9-@C)TAtl2!vc@8vTSxaIl9tQR;HB~ zld*ziO!1O-oh!=IUf%L~Y9(nk#z&qfRu)IkDzdqFRq=4ICLZ6bNrl|%^17d|WO&t( zYxy+ElBoX4HECV!O}z*ESu=N zcn=Mc+NVQgfo~{1l~A##=Ta{wOuUzd$(xH|Qu240fHg1uKZnWnq2ZD@vX*F9)Rwm6 zB4kKdq$Hn-l!C%~mjzK$W@(iC$%~Sv9qP#Mq-fbyF-G>^jghpdSh<}WD@PB+N&8dr z@?r<%O%su2mqnJwCdj~LY-bXr(6H&{>BGqMj%25h>2ugNvb|@!PQEWcMgRRQIdy?tCD${_+IRPvcYMrR6LS4Kr&T$< zLl%3!iqoG}RR2XUoLW7Un*2(IRLl!Y#i8g_JP)LwUMdy;aNToiboY<+H5d;n zykgv7+e5Yov)MCVSTIrO2(>NAT~JYU9I6*Anin!X92 z2ZZPGV*6(;efm|r2V{G*g^WGa^rI%w?_oUY(~Hj*ZMkg&75-%Uq(H_UAKn8Gp0_Bs zwPlR>PXFY+g4560=(}XzqKCp7OCi&*TwosbvVv;Nm!{K$xpR;V-=JX8BG$f4Q7~e- z!df@xQ`;+;(pbT&c(Ol?^^m@-aV*cgD|4mO3-b6stoVn%dhB&8>Qbx6nd!r9v!d!! zD`wJHAKk|azh%Wesaw7SKDVH#2iI+0J^H{oPEM*3yIz2_{~v z3CpX{gJy0=-rpHd>vOY#MY-Ge;)`^sLGveb%1J0Z< zz_84K)=37qz9S>oq+o-jU^(jM;KAvj`@piCM;@6uZz!Azv-b}IBrE}erLen!~Vgka863YA-8mly`GM<)aX}Z zGSTNoCTjw+P~d15ntac~^BY+>=bnX_?pY|?IR_Uy9!8xlN8#D&uYaD0?ki4ndJZcK zU%~OUH}L%C9sF{Ch$o|-!u{n-97}qK3!OfpPyMe581NHMXKKXbn~hBAU@!IOIm*f@ zWO_sq*<*H+_yWbGo1e1`N^p^9jf%^=rmj+;WeEvs?k43>Qm%QqOMy4;^2bz4TFmp1 zeWOdu_n~E^a__Rzp;uPzrW_{x#TzT&R0Ar+?8l$?5gQY+t2iqH3#EyV)Fetv)q`V}C} z2L#H*tAR2zAxK`P1W6&!V3{x@SVA8KOOIIAx~vY7%=aO(w0WpJv4l!wg)lixZGQiC znA~n0E)TcTKYtZ2)e>t-t24DEVR3D_k{ltY$n$5^=Du^HB;KKpRPI|x^3*!A#wA*= z4TzR?rK2SwD@OVckClSEW2xU`|PGpR8T(Q`hg!ifz3M6N&K{B|<_&=Kl% zw#S_B%5}k~sddTqx7V0ceL!ZB<1ZhP$JFif$=(5X7%#|raJh+WPW!}XfZseW>ltfN zr+=uG%I|$DssyK^5VgCB>qdT{=4KqodP={8EuHhl$@sq>dn)z5D?cBK52|a zj7$5s@my=@p-?-&m`xr}Vc*E<`Q&vY>gP;OuhJhGM&3J4V*ZuWrEG6G-+XU8Z|q;^upx0u+<^o zH5xt}(1STiPrd3!?z33I+^Gt#j-amZqo7PD1v$;A&l44_rT?-mfZCs0eI9-FD@9o& z$$V+G4_4H8V8ycYRvgK;;)c$OlbcxIxX6l<6Ik<-%xCq+%#+fCIa<_;q~{j&KV-oe z*1r@QX+d&*`s!sZ==;Kq=yWssZ#1L9N;A^wt7ovNAu5BlweShN0(xlwvA2g&q%Wcq$G-FLka z$7UMQjyY0~_C|8eh_~c=n2Qm$ZyE4@wE_Bu2JHQvg3l=_n8e!eXT?)6I!BN3WAx}1 zu1E3TI;5V_p*ZUpC$i>c`5+ynwGQzyI^(gMFuTga>3`-`5P7t(h3xpY`ZPvr&0XHbQ=99?RB+^=+M)CURu%O2!WPiMdfaKd~+V(!jN<2ni#}}}_^ago}AMtt2 z7fhP>11{VC!0A;1X;I8h&Q@}ec4Z367v@Kw&t)CsZzs9axR}hD>MWx-xyWX1aT#xM zmHA2uS!Z;U^E*n))A{bwvTrF_As(!ODJ_eg%gDI`WyO^~dhZwIB=4T5{JCCUnq8#4tNOb!t9qX4PUg*nl4fl@F!Nc!yv5`Dp7snK!YEj>pQhfpKy@Jx)4>$IGC?kO|Hr zCoYPtADAGPhY3fZSo)Su*bb22mRBy0G{?ovnTOXqSKeHmNo_%Upz9P)|V&E+*XZOa@a=JCVns3s`eQMvs`O z;t1R7x!i`!+mq48e;A*rtxfY7!`N)d@yp!4E_HcLZZmKNdClX*Qjf3QNFRkv@4A!Q z@g7Am{!M1{+|OqLo^vqoUsayh#O;6bn0qJF?;phHhK`Jh4R}8y={Nb3@#R>{@67vR z%lk|pefk>(a~><$N}k`oLa&4zuY6j;&J(O(VGB5;U?p>&~xDsC3bUbowy9yIB*t(gYp-7bBUzt3Q1gdg&jVk@sZ! z4Kh84Oz%{hv7oRCReu<9iaFBg>l}x3)Cd^Z=%>5QWuBB;_DK&T#}RQ^M{-|`m{@@0 zleQahf_076iWt!1TngsQPeEW%3W8V%{&bukI|KA+^Ooa(=)3G&se==>^LTpcJ6M~( zJyM6;Rp@&&hw1m5xzJ}?Jf^uM{y)rnf1ZLP%>dMx!PY2nX&=tuf9 zXAIny{`;WQT7*7gJYcO$k1+B)nf2(a>A#$$R_8OqI?yM0)2PqWj^fOg<0uz<3a?Vm;Gpe!Ue5)1 zyt|5T18$+X)uI5@9ia3+EkP_vDE05D#c6jfc4oqWadrmr;IUqhPDtSOI2`cVf5Nc4Gs85)^$eDw8Nss6EkxcXhe+>~5D|_u`s%D=~HAfuNCC;*rIsfLFU382!Tz`w_PT>9A$rzy< z!E5hKU%fuBKb+4PRha8_C*KQkEYwd0=64EW=%K%%-*TQ_%LlT&a~{VS(LayOVZM{U z$0HdEB2?Bi>J<#wq2L5_q~--=J(*s06m@xj#)WPidqhutSz~%I2?~ZpaXeM9f=bmC zBzP*QTbw%GPCT~@neS-t5-62%JHR#z?zuSR>oWl z$0Jx!e!m69=)qj*%`v8ltbwU+!8=zA*4tXJ=(`!VWPIIEW^`hE`q_;0U+JU&q{m*s zf{Ko;t1E1Qh0Vb2t8tsWTV{l2n=zO^OsDB)c=a?RlU%>&WybB_^jq%GKhI?y%zn}-T?rvaVF^dUuA*LZ{DGg;#}Eh+`?$@I@7Soh+s z$I**A1gzDe(O4Z^S;N?{9mfMPKN?p{2P2ujs-zBPTOA6$*CPJ5mg9f5h&iZ5xrJI- zM^mRW2Rd<<7E@MeQG@=zBXoGtoq5s4IxNegSO1Z% zrXI%z=rKEmbvVEExZNxT$9AWn9sAk3tpRWL7*OiH0UiBWr#Z=p;U!EM>B2m9a|@<3 zUa!2N;1M-agHmZIbEW~&wIJb z>>(wj(0DiLH=(2~80s$TI+v1-jXWePvb6N9Rz?PRl$AY2%ZY12Pl>QEF9mHYhzoO~ zAHI5t_p^%f_Jp@M?W`o{C;3SC4y;L!tRfj@t4gacRmF6on!H+7T{d;~m5^#RWaP&h zQtAln(s%mF^}ha6|F^$*j}4G*c7bwjL!f9wgQSxhB%>+>i!v-&US|hONAmnbpAeaC z36TpwLL@mfR7wm9m8Kc=)BVFFJ||3y4i1;@KDEU4b}f0ov9>&D6Cp=zBUzUpDFgaN zNoW5$;_|MJ4Br_o(kMpSJdcq*lVio+B~BJ@jT8G?@f>3nFNX#}e%XoCUL#VUb&8L7 zB*?sqiSm4Hq8znJlHqNWBy4q(+{;Z8%dI4N|13#7Unj{Awh!dkN^;DH97`d`lF6f0 zDCNUZy7Jx^iUnSe5+b_8S>L zVz^H$_Tlku<}kl9Ps@79U0;}^B)TFUVR4o^Q%uwzB{A$n0ihax1cV#v0~U z$?szP+<@z99-xkA-#y9qLX2nCdEE-PtHWuR4a|pfnIG?i#}1y0+kGU<(|Ju3GpMt9 zAI36%6=d7Ne%f+bUG}vG*E^@OR+9J4jmIiGmdEKtuO*Q>KZxg$!`Ow~G1?LP3KI`~y0P6GDoeCaqAlv`p7^Hc8F97{? z8!|m{fC9T7)c5q%t2C#NL#@7>zWU|}?jNY&QWfg@vWx}A6qGKY;2J%cdCZrZnLl$N z*XOdnaS)%;{i)mk*0gt|7xTHj6{&$%Bsg&$ec9L(7PKYT&rq*N4Yy!LdkbzPuofoN zg3HzDvonACiN4Ij()8ikTsgnFyalT&F~3Uw=lfaEI=})CU$UL+-jMC>sNZYSmx-Zo zQ)HGI9eSA2kK<8&i_yz@!kU*OCcN6mDRp|inI>ErMg7k4M@eM*6nZap5;=CXHhmdi z6U5VmGtMUD7GQq$gAr5jv9^V^jE$@uKf1+;_hfpRkw$oTrx(-8h!D2E5&zaTu35=? zz(fPul9AUr_UI?a9)(w9zLefe(PY-97uVwfHF`)0$LM#{;S_o9MX&p2oDO3`b=XGl z+Mf!(JfVrD4iDR0~UVccq+!bnm!ghV7%VX@7uQ~9OpMG4R7btcUhPL&74eR&d7qY zFdJ#Ra`5_WF3J}?jB6c_pyQLHupG)m&Yu&wu;?@jG(U%mH7~;Id zWuELITI4@PQl(d@yy6`qy+6Z#?l*+4{e_5Bjbtyhk+<=7a^sG@R2b+eJ6;u(n_UV^ zheJhVf=5yD?odox&vurkTU=x@eHTxwtL)1xA=gg0QJ1=l&oOstn_5cTOdc|OUuoI9 zwu~&8TbARF%1QDJPsy26UcS$*AXw-nzZO@N9n-w!WZO#8*3(DS$38MCt+G7YSVfl3 ztSURYR}-h2)y4irbs4&gUV3s3De7C3<2!3gqTWv)_w<)O_5pH%buMG00%hfkK-o&3 zx9_PW92=^6D_M5FH=v% zOPj%vsL~=M4vUoTnIMN=CdiK-iPHXjqG%(NWcK8#qB-41Rtg!qhwILBdX1k?lWYI1Cii)~9;>MN$CmpNt{D(is~V zKYYpaGHgHC&sS{I$?fypuN9B=g2x!nKFuJ*mvdP#&vBk?pTc=x_V+HA&t`kYmPcK_ zi_2EB1#%mkzdTRlZ-eK)$GB4C9DSJcd>;&_t$6-7?Ei!uUSB5tr9=P5r#8IKv!hu% z(~i$1v5Y0Y^sh?s9y##&C7XrL*{Ar>UTYOm0&iaWV z~1Ew~~U9Ec&qSFkrrm{Ub!f)_v5<*DloT7eR|!I^^o+`Yd3|OH>2Ggosl$2Jq_=_&Q|P;_4rc8O>t1Sm>Clp6N%__=)F7ul@;P?&r54-iua_gg z&$1rIbf52ad7(vXuB%|D!{HK)36(h}mD+rEb9(0V=zlMwH*X}+V{VOg?iF^R8aOu1D8VUUM7qjqah&&4;ME_bCSLdC6;jhw(!{arzz6mS5Ou)yU^r zHd3LXoxHhZFFt{elCY|v1iUOHUxSKBqcKi0GPS70y(%VWZCqrbeQ`-G;41C^xXQCX zB_zn9q^JemWw(7PIcw)3RZEwajh^(;?aNBm1M2kK4x1<7{wl32Tn;t}dC zCn8wq@}ZIpnc^dtLMzJ(yDD<^Wfd{Jt19bnRFm(^tIM65tVh4)%ew9w@{={`1DyQC zlIdO8Ob;Z1| zt`vJySDJa(lYqo}a;;@ODcYc(>?>bS(tp;KaqsHN#;MexYOAeA&dh-Z0*>paQj;mG^lc?$CF+#@ZaR z{SvwUn@n%Y_|lzmWf%MUb|CL-6V~g8v5yrP1D)94@2p>W!FSJ)=LP7M_oByA+d^%9 zfVGG8R!p17-*pP_JI5Q5;RV_1tWc1>oc_uZGMTPH+9}H!CL4TMuRZauUZPnA5hqW-H_%4{XWPB8Ly0;big{_GEY{98}7L+}0fmyX+|1Jx5tgvA4Obb?ywxH_( z=2Cl-?HqUdr6ZsFIbFf=N&~sP-&hOkGY*VjNspIWKf53Om=FsN{i45qk>it?OZ_{3 zsX-?*UNXm5khP67So^Y$buV*gnGiLWV3)AtjQ+R z|FHI@gDc-H!}<@`_w>){sTa&P;_P-K(qA9%X=me)bcIMA0Y-^BQEsSDrd zGFpe3tf$E}=+N&f$24)w(>g!qW|uIm!CdQG7q$2aeTimWF87FM22$Xq1@=Wm^_1%%$g| z%fXX6hY(ue2&x}EiW_y-N$zTEdR;Bp^f;(*hss4Tk?=BujnXcCKQyVmkP=1{K8T;zlc02 zUsPuIXKr+jvpikwB8$2gm)-ST(V?{S*egz zmL79Cnc(gz$#u$enU`cX@e<#96=mI8Z+@;Uo5V+Un|)+jx5_fLW);~`l6ldp)ws@A za*kD(!YzE|`%hm_$FJ8q1q;E=qjO-97H{62c{@WlqvN4$N z#0rsiwL-+aEJPaEhsvOpp>ozfOx|*g=;~%+QfOG1Je|Y5=>0JI>fzFHQ7!p8xVCsS zjF5FzBjuoDlnj3zB`!DXNSlk%QsPF8T>MIX{vu9pt|ZIdAYV9!s5a{p2mcUhZA_4` z35im#M-uy8Pu8rdE7R`Q71ywOvTSBO>3gi66#O5S&H^f`{`>lbf(j-oVuK1Ih$u)Y zqUWHJ(ssvVcX#~k?(S}8h8V=a?(XjH?sz}^d6(<1>6v@4y1)DGv(G+%!Zcr{a199# z*X#AdwZ3P#j(QXJfA7!S8KyholE>Nd4@SFYiyQ)<1xrhU!4<$&+tKiMF#ia*3&CVZ zp4-c7=3&%A*$!soE?Zu<3w*xAK)$Ch&w*$8I^!d6hliv!ztIwI&F%IMXdJv2&1cK9 zhWr`FdH`lSu@6?gsayVsHs1;k-WZ)cj%$Wkd@qUY2cKQl9lYhe$HB`jVD$Kv^sBPQ ze4K^nkgfkbaCZft1?RK%qWxyDeIvC_-n*3NukrrFYq+ie(__Kyp5TABPIH|t+tb-- zJKP(MC<9&Th=Fy&#J=s~IKk`T*Vy+b;Ql)_m(N_UuubRw6Q0Wg*AJdx-O6NtSqHkZ zPa8NN9vpMUx?H=s@!dt}1NfIA+u!j2485iBnG7jN-Lnxod0DW0-xB=kb8;~I9z6UA zxIKsM^@I$mF*!q;OwEutY-_pyeH=B@VHr}iFZkRUZr%p2j`p$|OrMv4UxsZX+tT<9 z84tdfQhJzt`7Bv5=ZfHwvBF#P3G9AC-x1pSXSn(TFuf0${&*odU!%=3tczKS$D3t3 zJ*MS6%yN?KfUkCB{rv&2U#H9P8|l&yZ$&E;+GER{y{Xh%H$G376(7>Y(VQ;R;O;&1kr@W2FWyPb66x4Xt~UVJSHRV?vjwi9tCy~nD)Gh8VE%&PkI~YPk@>O_ zuloN|WNWJwspFSIe`bm-LZ`U3(or-=w&jZaH|M*>adJx#|#`cr@;b8nip8r!7y!K3%FT8Ibx085o z2Jbn}dfcQ zT79gI+J3dwsLnY(M(6g}Y56(!x_E7V^?OkO{3)!CZwu+1^@X+Vh$6bBgM-E;6xB*$ z#q?p_;@Y>4qs|H~p}AWkM6@rdvm;CCugax$e}yt?jejvJrksw6D6e_zJ8Q3gE?RnE z1qmK@*=Bov6`|6n}KeeIXf9Cd@ zTKRrWJyFe1A8+*2y;1%;+aW+#JP*+G2LrX!x*)xU_q@r-+FE^Ru$~%QM}1a=Xr()K zIesz~=ZnVKsa9T3{WB_5ZT{hB$*ix}$2HLFZ5wL6@?qM2dzii`6s{}!h3nTn;hO7X zxXvmWp(_F-G;d^tUXO^-G~Wn)`Y&7`UJKX4C&Kjr__~nIhixU8d7o>wJZx3Ef_q)y znBekOaQ1g6dUn{d*ur>h%kyTo{Jdu$wW??Nzj5xx_ip9a2fg3tScy^FT9 zPJrK2lHuiS4Z!gvBm2afP?Gh)VlNnd6rOV#Z~W7ob>coc{#bgYa^b<8$Ni6Bd*27t zf=_Xs!slM|8zor-53qLiX~^fQaxBGo-V$y79l5x7Go%Z6UIVRV2|9Vqax`!Bl>Yw% zcfsjH{n1)_la<>GpLrkf8GR*-=YzrVV&HjUwDe5gJ8LN1yC-{JvRXGJbvd?d$2%yCwLZ8~^*kH1V5EUs5cYf<@^=y_PDM=r^j~ zCso>j-@n`8cVSz`=7U$Sd|9zbmh!HX3V?^FNbi z$m(QS0;j%6p34Gipe}gP7dVs22yWlUqtd2!vP9P-Ukg2aH+9on;b`oU$#JS! zxMssc5I+nZ{ly-73HC|XMOktwbHB`+b3oc2$m#d5Q1^)JA9-Bs!EJ&*2xoL5^`vQtx8d+q(nUXwoO*WslL>UNJpdeFA8)<0ZW zZ!RvP{f9ZIXUC!%kx)$MG$^i)VEX=`651`$Nn?G`UMiN--9_;)+LzI5`OE6}g5@-* zKzU8c4^Ovqp|{6HD;%q!<;Pd#3Zjx`6mZom&s?>{F*iNGsaM%cUcx_D(XB^4 zbi*P~?HN~9E$JPd^`Do{d+LQJv6_Cg_tt*N-r69sx`uzMt|cdvt6R)Ri>~$2_Wr)w z>4C2n?pjmpX4X_keCWOF`04g-e%i^;Ur*ff*MsyF^=TPM_EwPgcc`U-R`mJ*A-^Se z9c^ARLYJ_m)?e{VQIKt z1-p%BBXmc>NbOW1Qp;+jc5WT1e|kjf((aMEqdH_o*V7qneD)G z@OT>>Ii)%EPOx?+xLgnnZ5a)QgU?B9#nBQ{d2S%D8NuRr@aY?D)wq8YUOj>L^aaOv z)`myd;C*gz>C)h5QT!%_!DaBRXc@i-oPOnr7F~^7FR}%|@cl0E?Gjuo*n#W6;hk^E zr+Pt6@ICcIIPL*HAHjP%c!S%uSZf5`1l-)hZytyTlUu;C|3fF~&-aW3tH*(*$`5n(+G}d*E8#0ZNkcIUB!^IzPjU3sPIwySFw<*t~i=TjJJ2V0RTZ8T0;Ok&`5_tX_{be86 zzHA8R1CD+KJU@iqGBb*rYb4p}@bYNzUBL6-!^sWc`yKmbXK2IOYog^i^PL4VWcWYo zqwmQAz_Y&nl3A>dnB@_AdZ&$OuyFMflg+Yl7+k%#SrYNCw`peusd8>2nF77ZQjbU#XBT>t@W8yHRw`t^Y?+83CLBC3nj$d|OfmwFerG5- zFJh9~xlMBWfKk#1;}N7b+WneA9*~{x>1&Wd_mid51Ux83bMjU)FOj*0zvX3VFd9rx zfOjW1AZrWWolfm^ZJT82)(IT%mMm9$p|kg=ema<}uaRK>xMazg0;bO)A7%;seJyp- z9e8Kx${=r6nbR?y{jD(WxWO8W0o zCHn7Ob;%Gn^@^&j@5{Jr(0g|+cA|>zGoq*O@zmKft7=p(FD)7BrLjA_;Nj$@lfzh} zy|>P?t*-BPRM&NJH8ki0o|hRuy3oy68}9birSyv0@2IIei}-1uv3@$w#$Ok2@z>YX zMMvfd)E`-aI(1f%YQI|A?!Vglwp*}v8&yXet_;ytN9*e4m-TemH}cQ#@s@3&+OJ!E z{pi|2pFV7$E~^@9#};8)vUs?5I2*1frbMVqt4Mf#w7#elrNtUWX^;LR1ckn*T(Vw>2Bo7mIN2`!R3F@Hv={|dq58OQ+VS? zvPr<`>9+7@@Vf@vRU35lzxb(n?ZHEO+u^bqJL!>M4gcgen#U6!fp1?jq>44`O961y z5uK$h>q#Z_7f-YlKlY1#*bSb#G(!(!y?WT4eI9^UaTLcgl{H}@c)J!ZzMXXp{H_Nd zAH()N4P7ObepI$VFg*!Oe{zUpIM44q;F!MRH79TEUNtglA~WSd0y*$?Gi6iBOlb|? zN1fvJ4b)Uega4e%Ha;Ae1LyHOzVavJDbhPMm1AhJKSN^C&g-I)m!{77A6UKz96uX@ z9ukrv$^Lj=;Ic__3B`1Mt|xAefj$Y<(qLUTuJe-BRQZprxp%NHy9OC4~U?G*1n z#dH3w4>QK*^eZ(6+e`5sgZb`86{xKiA#>fD+AKA+ZcnL!qQ4ABe_4tCVh2|*yOv%R zaNTJ-nT_M&?xW1|aU`Bca=$i^DUj`tSuhk&MHpI*8`?Ymm@6OC|#`_v*b z1Xl3A^=K?x(cO(`>TvS4`^arU)A@58-}|LxY4@BpAh&_+V0?@8|JUwkkPz}0*PK9q z`DTz?u0|Q#EITjVC^OF*WoZe#i>ygU{?H4%oy>U7g&jRyZKzqqk>|7bCx5>!GNsmq z-EyGmUg`E`pX{2pUkZ31l&~v@#B za7$)+-4n;fkMLbSBggC&eH3q``^fjQ`SnLh>H0-X_TMGz;!jzY@kffaw9qM!EVXV= zYu)-am&T5>(d1Hjw9(kSntO3R{XEc4JGZ1Z8k!$Xq<~%r)B9T#(k}N3>HdtudSgxz zEr^eC9{r<_{fp`Ga>aFW9!G8R$x#y@;Cs2?q=yfbRBvM`Exx9-2G1*_ukgJjjUk$L$RF?hclp zYycjC0Et@#__#P6^k(4d>2;V=sn-mf=0m0?7pk0u#ahP+#hvVCym$ zbR78Ul-ywZha5Z`n}R;P2JQ%+RXd3v;}%&|VBOT08PbjI2lqSOp`Y@6hV0k}j&HzY zJt`-wWFVNd3T$tkK^^b}9&GS&Fu33C6+M-o&@lKn{K1NAiTv!V6Fi*#o5H@d61X?V z<(H8GYp-$C62J zP!>Fy+jpzTX36H=tDRVer@4^I_g}DS}3^Qh4tb!*8p4L^OO0Vdo|GA;psQP z^gOxAj`?PmS})D=;x?Z2b7rx{|6*%KKi^LO5x8D*89k@?V5(9#Ejk~4c8OWWZ8pnY zxcoHqnHg=(a<&edjWc?Utyu!zp_PN{5#ah0>Zp%)rpqn#n11kex5ap0$axF_&!5yx zmwO-SA>DwFIx$V6ZRj!Gk8VDR85eC*1I*L-N`EQqgZl+M>VwD*s7bGq1$i)JsCQb5*M&Z#GEVg5JcE~~qMwg3 zNwX*ux#1?6O%8eWWTV73A?xsiLHy7=sy8&qf#1neEQ8wR5bB&l_6oS(4Bh1*HPH1H z(ZBuS=}~ZO@O%qeO41}a_(C{1{QJUoJThtYB*DSU9Z44N)6`Sp;-ha+6TOEn{{#$w zLB;^v8D5)iX^_LE4Du*|o+2`4Y^NGzN4h~?!_j-#8>O|sQCvG3#hzZHtN1PNT9BI_ zXX5)zG7D`fZZ|b!yrDhIu>N);@9hA-WAEMM^6im|XfC_IXUVV31M+skAsILGh>YEO zOzwR+K~LOiDP8WI4E}jRW_`Xa^~+ypy}m84-`{1<*+cnc^GwNLP!r^izt^(~-vix0Q-w5mRbjnE7UPm=2R-doRAY)3(;MIDIl5Y0hnO8T zV|58_GRH|Lk=u2xM=3QWmDY@UWi-sEtgdq_r|X=^*UjxrR<5&7IpU({msHTrohqtp zl}Z}&s*--$>8ibkyJ?rC$~rsHUGJBzqBE^M)b!6oCmrzA5}s9cddI5z??hFt9Ob2t zA9?B8>DAPmKh<+r*V<(3_Fh&)M>oZn{>Mkh&cg5FR8v>2p)Ok0Pe<+d(_iiUwOEM& zEr-`7aa^FL_yy@a>sosMc`eO+Tw8bi4c0uqA!;02SEI7(=_f1IMM0suw{d-~(5QiK zt=v!}J~h-1X<=HfPq_M5iqOof5xQhzq&D!2Qq#RCtu{DXt-eR=zrKy|IB*#NIy9f39i*WOVFt_>G|Tp6ATKH9>c9X{j1 z06%ws1V7-&-NE)%&Uibj;41;!dK^y&-1Yfs{2SbF4d!{7@aKWwJtpI)28)bn!SmX|-{G_=e1{e5Lc<;K zRWp5-yub5N_$=R%33h(vw>rGekT&QxtHAe=a$qt0c1rQ$G+~_q*IQ2jyH~P??Sj{z zq!s{X{|6uU;PLQe)+%)N3Tzv8P+Lu>9>8mxFM;nb=sl&^sbCQNXLct47k7*E=u8QL zr%$=h_03`4%UbcOBemYL=twWP4gt#>ZN#Stzb=MmQhs?3Z!R+$Y)!!D0&hO+LPl31 z);F|}GiV{VAEQ;Had!o0P52G%-v4`)H{Ms~JeKAfi1$7Q)8F8K8TH1DkB8X_m(4Qt zINW=$Sz_RN8Q^-=P2l)C@SH7mJ-w&k`QR;Pd9{Z80DSDOeVK_z9rZ>{_L~}NcS~xm zFVZFJ5`LKdaP#DJDT)U38-Gj|{uqxQcx4*m$0&;CPQU4ov1wAxot(zAsnTvFwLMK0 zUuvE2E2N4Ox05}{_j1qCVX8MkBkw>T($G}#pGL;la`-yDyzw#ojc>?T|ClO=52i|^ ze(3Sp>%f;3nSz&b;lOOJo+4p*UBWJagDXw4o17G@nkFf1ZIZ?Rzt89wK0*7Fcn5n^ z8>L2B_7?r2tI%Bfql3pMOBmk8rf%ryaP)!HNssgRWDr@#Wl`g^j-CW_{ z{nAm)g#5Ex-s45j^vRNK-}Xzsn+Ik74VCyIvr1=AG&(0 z6P5La*5YO}SfhD3U4clwVCp~2)^=&c)vSJ#z8 zYG_oFj~4&wqlrV9VPsuX*D=4y&dpD45Bce>uKpTWDnPF==OTQ1pmq%l(qDz?{r_G| zw_D`+(f5oDQMVg)wY87vhq=rrvZ}Af`VDkdXhXFw9HtxYh3V*Z;aastgf7h&saw+` z$tOT(v5wXsYopaZsFB`1*+^@*kI`o3Vp%WaHDG3}wv$-3tPqP<6RSRjWA#A6SZxS5 zzYU&e*Yj@H!&4YYy%Bx8WO;mx_S7ifgO}ju26%SQBjD;Ad~)FR!V>5l70^uF(e2># zMs9Oggtw!&j7Ar^^p|=d>p*p|HZ>hQnh6FEAwv*6Tf2nb$jxw11NZsfEO7iPIDLOT z9C8tSbRsz44-W`jG${#A+5|r~xW1tm+;tdzHSpDq)A54L1Me53S%8)6!1{+<;qUO^ z(PvqM9?@fu=Cg@?@u-BaF&M1~P2}HTaCZrQ!@W5*PxtHS;NbdqF#Xp0oZh2#yxt7l z@3jei9PU0F-ZKkaH@rrJB8%owT&A?_OwTL$e*P&wMc%Urj-Ktc$xR($9oHT0IHt{0 z;Nv|w2hHKi@#xvjc%C&XBZPIWEHlOOu;#&)J)Yqi1XC*>Fv~sqM5e=o$AP0(VCcIP zYLrL8TyS?VbxkLG)`o(t1-2RT_YX4V&}_+9X>|4m7iaCrJuaQzfqwcjGLVyK&b#Q%~;?n}jODdeN4h`noy zTzzMfANbKdnGMu1(Il6sjkaJGhE1xGIeA98Nss2(nFevLWss9!lVwvf8H{jr2fT)1 zZRitC#DC~Z9kUp`y%e|}08aCK*9qinZ3g?n@)_Xx=GSDx{K(ed4N?v44o1Vta5hK{ zck+9yQUAmr*|xR;?$2D&Fy>pt801|d-t)K|FMOZrJU))s1t z>O4FoeLfwL-Gh$Hj9I7Td!BRR2%djfdPRcvU6-Y2ZpqZ^cP0AM1Fnyr$n)gq@?qL* zDbV*lb?VPDX4*IDoa?7t3;!+6ru~&2t`=JJxrLT{YpMQ@)*2m}OJBCjt#Lza^zI^C zZL}{B87Aa)9nYs;tL)UJyS?@Z&aauJ3+Ppgf@-*0P|b4-=@==j(Z9&=I#xvIY;@4+ zOLBUSs(TbyulvPy`WZ*P_@{)vDo|1z-YBWAqe^LHv(j3sNg1{1P*y8;D5q1x%4^^9 z&U(?pMbA8S(SGR_v}LP`+Tcw^z52gOcp_c(tF4=MDw5-CoM>{_Oz$e{ypP#+p&q*I zh=;CfL0`mM|4yu|zJ$Va|fXjn~MUer$w zX@1(Etv?z~fF8IIpxw!ISri?lAAbbtsq3}W(kfW%bgrWp$#0ony`GL*D*CKosCuri z4=#u4>M~)P^*u~I@vO979-$tQk-F=Bq>h~*rB7-`Yt75idazd`?V3AATP=;zk-o9| z_HnF!XdI_^yT$1MjnhZ|ar%s{Tdg>q8yu&JVESb+y(X9*0j3`cK)Fov^0v2Nw@QV>t$&-vmF8;x<2zYk>7X^MP?c=|$(Wi_X)ZZU$dh zfhlm+lhg2P%w~N6yHl5e?JHO(xJ_ROCeJ|k9gAMjhwFhh=m{~rAD)>Pg=XpYOAhd2alsefDoZN3XWTE5q@$2G`qk;CSbA zeF3H~1*%E<6tXWHL41d1On1)!limJ-EGmKiWOm?(zt&9c~_c zi0gm_Xi#0b-w55t4Gji<9=RHwg?$QO-v_(Fnc>k}ZCRr@hsDA0(J#zW@RnIxUogua zbnH3%$W4S3Ps;Y2^hfgmCttTQlP3j6_Cn(ZJEtz9CJDZ}gZmA^-q&a)sb{HKo}z|% zf~-Zh0X*+_$t(rn`Iny4SM(X*IsCsOzwNRMP8YjPaC7`GHAm5BIwV~}+n}erf$!wLWc$(Q)FTJx68PH{e*HX!+M!7X zqYtlr$DFyMWU6O-Sn8z8)@(edHhN|Ry+&v*_twDa;pko&Xy{=1#588ttxc6fqtR_* z!FlG{^}k2<3-gWMlku_;zsnNx3#X=-B-d~>^|~fmNo{ohaict$06zK}r7k#{jgeFE zFE+VGK389|y6~R=@JN;eEpjxHktL{sqNxx4LQZatWO47xOu6NFV@{&CP~*HvCU5rV zKcS1KQR_SdcDthE`~bJNH8IExbd>^~46>&?HPHSBxj7uYd;)XwW^g;pAh}kf{T!or z^%pZxE0X8VJfq-tMrkz2D5vQ)if0znvkapQ`D&DA)B;kt?x~W{H=dEG^%rE-e^(^*>vgdTxh)H7 z-;;tx9?JDMk7fGXXJS+KmAo79R_fmVAU`X8kwaC#OEHUIGN~T`sDNI)YEy@Z(ly$HO)>_8`^7){P{JI`J*TQ6wp@> z3hLisg>>NSLK;82utqd5q9bZK=xFDnYI(1y&K_1wkD{yZ%Im1FVoHF2rL+S6m)l26 zYMo7`bbe-O9dBJ$+c=lg?eEH|d473qG{{-^uX54j(<^9~ycN|Czq*&XqQ*4B+nCo? ztNwJ=I*;A7<+{px!{1#;pK{mIaaGjuVioP!&O^`S^VF1+o|*}+x5Tra*0Gu<5A@ck z4P>XAYUuV+KI&DEugZ0XeI{MkEu6`d=Pm|w@7VQ}dMmNyq!y4+(j4=KE814LRgtp%qsXYUubo`Yl zP3Rx30}C|LM;jaI$YAjNVvOeP6szk#$7+{Bar*XJoCXw(*WFd(sSC%eCd6yej`8}j zd%On6pg%;TH-PIJ3h$=I+0`4ocE;0U4?e#~w><_Xq{6G=>wfR3$>l}2C`E6kEA>_I zf4mpEdA9ZrPruBgXMFBWcow1`$N{cg z)-0QH9{zGONvIktxVC_g}zrpk1-DX+B zF=T-GX^+^Cr+8y{Zxi&GM-#Y?=!MU{IWu+8*1MKqM&7G*$;g5?!qFcOM^pa~Erx!i zGpEzZI0S$2x;#Ti|7}4=<0dc|%$~!{xhyibYVS*tS?DHj;OPc*@dP}I!_Zu6qPdis znJN!fGpEh~7taLevr^>_b=8tQz6D3O8$jR<|0NSIBfQ+`Vvv+TgQUZ~EgDnfY;TY`Jq>bsFj~$SgY2A)jsk8Q z7J%)`4bp7`GdB$A=KH|+GvpB5HAvVOxH}#fK?fS#g3KAbIHzae#aTwSE?WdWQE79i zk>)YUHF`&V$YQL4?(&fO#H!VB0{$PmJm%VQ=N{SFWuMf1m?eeI@0VLs4oa;lN5sPQ zgoO1vEzR7{OYXLp<-_djQfAd{DO>8k#65T@zk{C0r{m!Hn3uAw#TywC_g7e7~wEr6J-*@IY z@^wQi=*yNBw8;JnIx?uD{ybGtdrzsPg9f^4L>D*RP^+@a{mSas++8CMxodPp6}@He zq4VE+Xp2*xdT2#eojTu3mu6MdGJm{vW!V~P@8F|f?)hkydA_>Sk6A_+m`z8%OW#ud zntab+znTNoc4?q?85*P~LdjmNQ(LEx57x;RA=;asQQt%LbdI}f#qFW$T)Tk|OKqqF zN`>p{xe@Ghv`(87rFER5brwC4DhhsEh7H&)tfT z4{q)UhQA$!&N2iq%OL7{1F4S=fPeRcm&0x6x2DfBlKd$!+8M3D4E7Ytg;xgsw|ibV zJa{x2u9=7?JfaAX*?w@pOMdFD+;0c|?@;iZb>S%AU1=8D48I+Hg1nShtT7JgOp4au zf!?ZaWV*D5mvj6tSkLxzEN=Y2sLz`Ah-;Q@-SIk($9q1E^UxgpkHptl7hMTo&+;;G ze~z*9Rn`mEtFG+-&7hohmZkj8*8!{#|1--oYMWcOcr`90zpui}=gmksI(IYb@6piQBlQV0|$T&sl5k zvLE+q;B^GkE$K1Jpa;ngZeFA=UKjdca#@iXU?hvTHaUzB@sxw-)}vCTX+vtC@bYnB z`G0I>?eHwRG5<(YWl~G#QiIhU(a=YN=O0bz=jbh$PQumCq)L;c^pU25^Yonh^u;Gr zkJsU@%g6?}z92=~P#?WsitoH{k|AU;&gy6qa|LFQJ~YazRYoy1H_E+2c)t&Uw}a5Q zz0gOfUGBt}p3U2z;A^QEg*FZ^?@adM7x3Kj$4)tgmvKE>`uhj;_SZMaYVf;EANoFr z!OtfdWbu4@QQ_Uyw;5!5Dth@IJdy_uavvVv9t=Nw)gaBDvX1;@juOAWi=LteVwBSK zJ%xhZgO(e`gf7(hD1AofjnW?v2z0nJ@>|5OFqf37Yzk;bG3qc zeo{eAD^W;~+%Kdl-wLb6n4&tv%Rvt}a!{uO4!UkYQFU%pOs%^XR~hK2gGQIorVE_3 z>#>r|t1GSdqs!>*Qf2j2a#^j^vz)%@QC<%;aMn>*owa9m7oE1#Mawu=&=fE}?*;O` z-c{75OuDZtg?O>U0GemR@Mo(E91D-MFfeHVur?>-%E# zN@%Qpxe}|Vdd6uFt9TtdDPF_A#OwIz1l_wNK_j0e=*fUY9XBIUZ=OrkCT|io9j-aN zC0x51x^NH@IN z0c`)|4itHJ)L56s2931>bC{%!+r7vR%C8?oyHzwU^h+ZHcIJLW!c{})?4_xB~? z{i{n3N_j9CZh7)HI>L3X=i!H^(G%vpkIIS$JrXgEAAWKu)#TN+JLc6=rGl& zBZkteiB2N6AKw9X zXKUmgIL?wBlYMUdF<)3m9-#Yk?ecRy{rap;Cs{)l@w=v@@L9O`=Pu|Xjo_{U@MCBA zu032AUv|h-`f#qHFP{RVkEKg@G7rOf&iWadSkx3hf`QxH(ql=zE35%MIg#{WHfP>Y z|8%jU&iG&tJ@{|PSt$)CW<3ZEA(O=iPG6bzqmo&kc)-;H!Q*K7GnikT_2kMDd?{da z2)azQ$7b1#20x_?=b#F8X6maxKe-loU>3)7Xe#?zA6ScglhIkg>;7!ndAvz{{t8_E z=5aLpyJlI=`e1tsp1uxVJ{iBuF#cY~=B!QE*q?=W!I+il(jSjYVj#Vy1z4XRq>0;R zvKO1C$$?inb)RaYF>+3oZUOif<0z9on8!W8rn@c9fHO3mBw@DzH7@UvWMPUdYL{N>b0 zuTmpj;7R{~y==_Kvq;_3#|N$t@BVKMy3KZjWM-24g_d*jib4GGu9SL3Kk6s=`45A9 z{%w$kXe$|3M!8c0-W_0+Z|uY0K1QiOlj{chSsR=(N~vc?>YQjT`S9w{WAq&Te+?Ng z|GJSi=E2&B7S%g~taRbuO*Q74ur7CltN1L~El&n9=i>7cg?4p&gavjo$S=x(Oz3!u-8t5^J~@L`E}BO0%}HIPf07NUDg!R$Bhf? znC*r2;F-eO-@S+qHPT}`!9fGp7u8PBi)pFSj_TU5gjOHoq*>cbYLVlmw6CGGuIa|S zqg-WmUi-4z;#*lQ`mmg~`&eH8+vKbvC0x|HLUw*Yd9C!Kf=-%SN&D_`)rnKxbm4b5 zZF0r!|G0hMaCc22hu8PGhqiXg_BvM4U*TR_+rwMUbE@lpa}7<}?xS}G`RZM~FQ1ra zbo&@N0S(Y!>iTQn!2!BuaiDfQAEdLH72Tp%PJPtjYzX~R_0(d9Xt@`v^IFwcpZg88 zYhsx8$qLuCr6cudyC|JIGg?gt8mZ5Y81?m!)sd58)!#Bscg>Ge>ssLW!+0&#Cqd6$ zOweZ~618W`L`^az>dcRRF}7GONsJ`Yan0G71` zyMy51&EVuceDOM>&FlrkZQ%8;P4PGK{!`8Hk;Icz4!(Z^*Q>gsMHD6<0E`?8{sn@6 zQ@5jW&q1F+n^@GGI%XL4OEmJ4XeEUc@oco9ml6&AP!n=y>!1x3L&v|D%?aU~yU>P@ z;i&*eMxI3L1v^9FjcfLSJ!rq@!J?wzjmIUk6ak+)Q1^4OAd?n8YEhA%O|+Tf{HE&& zFnuK&4|>eKOVnBKp$FY(O}PPvpJa|_1{(bad^Jn)jjzHZvIjnTg?)sJH#)*T^7_Bc ztUL3#R$!fQjm1k+4$b}vTy-UycSA7I#>}i5@~)nsJ6uVZYhd;9E$K3kp31Q!(&ZpH zcd==@oNq*yRWyBVLf-du(KK)x{v9MNby`L`b@Ohv7@N!SI`WSTZ{&4mAX6XVh?}o1r<=k8< zNp8Rr^mH(NBX!l6aP(l#=R;GDw{_zWx@D{u3Yi zU;0YFrAkBa{V90w3+E5V2U(~fy-4^NJ!g;+5DK>EW!}*plZ+&nwo@CE93v~eIsErD zJv@H#M)_G1Kgm6VJY7kaZ3~0sEd%!AH$09XaUx#x`Tr%0XEb_w-DEk0uW?d5`CDk| zy*H4%>xh0%e~>#kz8V~_bK4+q-WsI!Kl+FA8|6K^&H}XYQB~pJzD8MwFVV;vU}0gD zujGZ*8)1}waPnQd>HWWD6i;y6s;o&$)n>L{0{(OM_Zl_b^~Lf9DHX`{|X0{_lxYcE@=MxX zAailUKaq_V+7(PsC`*sgMJpXP$y!?l<S_=P5v8H)7 z;9*`BW=jV%w=UzXowjdpua+0>^{;<^^-asKixLWG^B)D&Z)`!d;)2?$Xd%7aqL2n0 z&zVzt{&5jqK~IutPcaR8P+Y6!EulX3owUf%l3E#$<1zQrdI@abb+a^B%;W!+)dH`} zY1)PIx~`qGw%X{d(-K|u^2!Qo;ZsT5baK@l(QZ2PnVTM_cA7M+vfkX}uA>UlWBSWO z|Md3M#vWDCz`Zm+fcY4!tE>CD8d~&}kH#*ePFj~O zMeEtdF?>h7o_iguTixSy>zX+IRXbkmeUI0n_Y<_$v_v(-#}8de)HAk8y103gF1eDV zu8SL^-#1l@#3tIF>$PhG@oEo1Pw30FTTkkq|KWK-SMJ_~tSYcOfjVk*HpVxCmxK3D z;P&BY&$IiZrw^g0hued!3q{Z;I)qazM8o(92VQT3C*~y_{4_p`onSXQNcLRh?GZT| zMQ6BlH+1nf=+C3U$GT`QuX+7=6kZMRIO(QYK7b<&!IM^K0nXskJb2@|^>Fp2=+txY zXn-rf=b0rC{7K@qdhp3;@ZaJBK8+i2O7Ql~5Ae1`&RS7`>w#k9(Y=?U>u_N1L^`Yr9xiT3j_USSaUv|4&%;7vv&dHuMX~dTOnJ&yR zIMg;xW;9HbM6`*7V0djf^PF3!NfTyAw1?w9WyVBLu-}t>mF)fccL7~vcDigC!tV`E z7yF6y->*u?v(1`;{&BP<96ACmWgxZI#rS5x;>FjwzWIx`&iSo}p5B#p)9*02&N+_f z99p8;H0GSHo5AzkHssts<+FFd_&9j^XttTlnWe$&8Q}So)?|Ry=N!1B3t96V+R;+h zuU84_($|so>vozHS%(iDk4t$^`bA%(jiY~W0e=g&#+yjrXA-`aiDYpNuaGKv!K(v) zaP1DS)Jv60 zwmH`UVZ&17b``SI-8zexi$K>GKEwJqDnu>}7t&8-v^i$6r;V zKM4L^6c1t|xP1>jQJK;=XWnm;&<0FCy%w|e@~5M-7<5@!z7FFo$nrO zlA_B^@-vgV?irKpIh4KcCh6HFMZBt@Q?aI9KEk<7A$y1Gsy+v(d2OSgBxbkl`Mp;% znjVl_;|@!SXf)GJS(+2UX;8MSEXHzoAUeS9Wg~d5W5qPrP+<=eD`~474cTe z?sz9(Cw!2g0iVP^{EJK}^i7sM`!1EP{1k_Szr|>iKI@uSLyF|n!;j(ZgX}ab znJo2_b~--TUR`h6Ypy~0HSrbRm`Vk7Rd4|v{9ge*jrP8KUO_!txv*}wb0Cn7+Q8RiO6u14 zSI`kIm2_-`t2!sS=`p{`+TmMe?VshYDaI;#JPo*j&9f*@ zua=G1KZoMA_4EX-GcS?jZld|dCh51%Nt%CVl0LhUr1ira>wwpdwP^b$x@%?=jhO&; zvvp)kL_2mLiw-j!{|XqN)dO!f`2L|ix(nN#j_`Oi=pDQ^U>sh*g<$w9dM>#w#OHeT zCIO$XSCHxrK_iJUyVR(A> zoVGm;;Phx2-_dNlW#R2hM(2eqX7k2u&UttO_xqXURvY+vQ?q!(5%Ypu)2G1U!Jm?F z%M;*!7Ih=j3h-tNnhe;Rje}8D@!Z6r|A5bb;M&8{P7JIgA>j5XzYK8!=ZYEdTJsye zd{>w2tPMPuP?qGsDz{0Wk`s$&d)Av4MdAd|V)gmoH}x804QbBlM^Zy!}_2w6-QA%ZUv0THt$UW>=tnd_@CEaYnOh z#=1D#EX|g|+u7%Cm%-?V==q%ALEyRNRxqCP8lQd4BhX=nkPX1rWjOU(j_=a46= z1?HkD&1RkkdP{X)zuOkwOSzVEVYbFE=3}5Gjo~^XxILN@*A-u$fjg{4r@N=g{AwKg z7wVZ==q0o9n&V4MN<>>hGcSP7QlT2h3Z7e7q)LxE_!8TI&ES6G@>KDl9@_C*s-%Bn zjt}^Ks50wf9oEFiH1Ud0T+!mr44-RKED_bf+qe>>42SMMA3bo-B6c`nT; zwpm7ba}sWTCujaf^&tDEE_T)fdpvU9hPwRp`W5jH8(vj%kl>H%xW3AQjWJDZwu z3;wN?Wlmtte(7?Azt=*2@gE%II=a(taTvZ=931w``uvAPB94mr@Ck{Yd`1k5F39j> zSES038}dE+4s*Zn%aeJJWa*`+a;^JIc|7=yR9*W{awmR})5|`|pUq$7u;(|~(eb-X z`u#%|pZg^TQvXO;zkf2mhlTe4Vxhe{SZdNSOZD-zQpY7$+6fJ&)=X=??3hb$rRCB- zBXfg4w)(+rqeon9b=Y=WZ7q2;>3$w{nV+Mx-~W?WSK8*&TnqByySCG9K_!Z7iMDj|GN*JXxPHT;r1o82Qjc~i zrH6)>){95W=$u03^k=#9y7_2%zJqL-V=g+tyP{t6uB4qqTy^(oH@(HIjIQ`!2B(o3 zu+Br*&|i9YY*qcy%u81ms>bK4Y5R)R^=SVZ+H{tW&Y$3`7hBfUb|w7u>TW;X-GbS4 zB?B}nf1v(z57JMqYUz?ywe`faVEyPBq6L^gw|a9ub$ddVF0(E6w5_iz*EP_IWa8Ei z3)cZ_A~gI%q~5C$t>K*;spo_k{XR5S%hit4;Ja~pb2$3BTY_4=NYMEg6V-7wOug5z!J(aF}EFK~N?$3lLez4U?OE z#=CIaG;kD5|KET3XTbD#?)d7Q=$U~p&dm>3FG|0RCw-T`XxeB3{oayAat@pUg9>n+ zKLIWiXI)XX&_j1z85|1LLPW6YKh!0 zdIYWDAMdY>rXuk67;2ncA8f6UN5>1Vr7haf3Hsz&E3&z>cQ}{@Ki!MwlOGJM@{HQ% z9dw;z^j@-NHW3IUwYZLO?N-!5TcXp$zuWUTm2(|Fh;zr9FnB!Y@qg4o(a%qI zVQr13Z?Otmz9qHUi_D_t8lfrLQhK$V>y_rrC0*ASo?e65)Zp=j4Dbltt%(+VC6@Xq zcs?dDRi^o%n|PC(Tb23J;MSK&=3#UvXK@-iFC6n0*0mIlyN50PrttE94brF&gX`o9 zlpc~MUGPMn1k+cu2K+9Ko^yaq#%?K+fsWpdysq7&=p7Aaei1WAt;u$|Gnw4l7DkDx zZIpl2s5@#7zBVHNaM}oZ^F64SK4nH7zVo7R@(O6@N2{Q#`|un*J!&#|e~=j%R@6OX zm|MC7?_x2deClA77qjT|gnwU6#jA1{&*3GqWbPZK{2O|Pe&AWbLpii4Su>SQ5)fh{ zSKdUXsfpfVbpEqsi&-(hqc&^N5c1#C(2u^P$i86w`zyfna%r-axqo?CGtK$&pk9aD zP~Y*O2d>N7J6QI<+S=Lf|K79eqn%c| znx8qN1+{m*!Yb(N;big}Gm2^K@8Y`UpQDa5l+byvOQ>acC+38f)VcXe>!(F!bbZNk z`YEowwheIB(f-Vx9$G=iov)~7b0xkTO&yM2Zi~AXF;&s?8$5I~cpf;ds*WG$r6+q= z(?x;adaz)1btzaw%X#?dNe^E=Q5^l8?5?O(Keg}c&%OlcpfNN z!Fq0e9gTe$q7fzP>2qd7w;ZUNcU`D%J6B)#ex^QJJxotd57%~|BXoPcD1A5tOkdVW z(>BED__?u~);3PF9OLx?9KBiZ1pQn#QT>l4>buw^y|*JthrLNs-^z{kO1H-P!Pr49H_ zznjn1;=NP%)5nv69>0;k9@c~Byx(aw{g|EcJ5p<%Rf7J~7x3>)bdBlw7Tcl2pl_E( zhyI1HuIV>$_&I#>u2~{(;|&2bd+=}dJi7U^U0@I#axT~U*)#6*f+tVl=NrJBV?lTV zEwXd|(&Yk}a=SKI1s>H0yDGuiKZ5Ul63`7Ca_~6?T>rcV&HVvB?|kHCRm4A!#$sCo ztsIS|4Qos7S72QVbAI^#eAUo!>Z99$V{%jtNUxT4dvWUa}*J}J-fEODbp6nxLMlQro+e4DlD$tbX)DRqia zyyl!EC(dgq=W9xHfCl9*q)d3erBy;G$0Ws?}knPjW4Nvb_Jiq9Hmcy_@nSj#9YsZVaUq!*LAWfL2tH2F?VbGJbp zIvB{DLmQ_?`gK{dgf^w$-yYqC8FPMC` zsZ;+D9`d97ogWv|=hG4&bwO;4T$RPCw|MTUw5aw-3Os!*$wAMg)4mrnt*V*V~ zdmFITN*i{u#rv06!+PdZtzf5t{p_??Ejw*D+>RbfYO1{o=*zbS)!G?f3>m$d?;P~} z^kQ1#TyZUV%uyHpS3++MEx~KW^?m7*+?LWAX=QX+r*dj_vb_GYb{wh3-WVU>{)krgL(f5BiRtqeM)0y${_}&xr z&6Whc9hRsKZzk%@#!0#+GfC&$HP(&s;Q4~a+U81Q{bkogAJk}~zqN_3gJav7a^{Ox zJ(k0}S8y%2f#(~nM_*roeh!C^2gf71y}b-RzLvTuYrvKi`t8B|(E(M8JO>4?G;vJy?<3LO6@{=&knEBHV5v%SIBw*&ru1e}`#haEcuuFrQgWGl`( z@^ud1y%4>eb;U3S{h~7-MdAMxzq<)dJ9BIfFRhOTQto7$yqQbid$Tl|R6b3-pQ00Q zftP~iU(kyan3d@b<~)hQiw2G_U6S3qZjyFQm{&sv$;yV*!jeqVtG`M7$b)rGgV*6j zwzj4R9Buf&#yPoEg%_qsVlp$5sRjN3$GpMCitW)T!1!;E=(Pt+8!V?LSutI%qqFbZ z%>1G4^yEKHm;B&yw#GGWI@cin|Bs}z42!D$y10ccBBF>QBDNwH(gu4gDk33acX!9% z?tHMjyBP)s5bW+&?7&8)M8Veg$IFLv0mGR(1M6P*+H0>3A1}jNSd4X%Jj$-~iaa=C0{|aJW^#gR84qWSpT$i3?71B5Av>;mE zJLYQ9ho*w%)F=<*Hz}WFr02rOJYBLE@u^(hX_R)$==m9pPuz{3PWty96UowDiPr@T zAIvP@F|+jTMnYS0_Bm_DLxa(U6qr-J7l%jQ1kFjqd$*3mK$9{z7& zv>3)mOW)biGHMw;Pg|m8aU^r*sCf=1FLz@WbFNv>kM&|!YLrPT6^W6&>}5V(LW^^z zu5u84sXqJ0^W@O8zRpDZ%gN|GWX#bj@khlR53$^zabuj z?})wK1Nph;sr+a6QbsdF^mMa#;C8Fp3jYsUfw^z02hj}y#vS-P3NsZvl|C4=$K=C-qL#*| z)Yjyeb#zpmqvl;xSM8{Www_2P!2J4J>TCmWm-*3i&|A!%)%gksndzHGxsYYxs*_5% zX`Vzk>Z0!2b*hKD4)oNy1HE+d+$NfRt|>WR&Gph)=87&7y)&KBql;ST?5!=;l;ER2 zcUq}+@irRsKVP+e-BvxU+UX2Ce=S@iKx6C!)yynNZ{H2lSIgS#?PkH6{W4e=jt|j@ zUm<#XM5qqD%TX&#Z;uPphDXEH`bU^nckG}G13G9@_YP{G0A3#@&-^rfme=r^-vW;> zlW~58d_yBXb+FqOj4lSg7v?C#_a(S30L)(uuXhI1jXXv{&L7X??1#5+xRSdz%vyv_ z@6BWW#qUQQXXgSuis&6VywRPb&3iBbtz+YE`0+?M@invyaM=;=cx@qlFpJTF7oZV< zt6iqREx}kB1jcm1I}L}d4yUZtn7SNz?hBvv1Me4tJ2k-F?L0;v_+(XX^Mbp-;PKu^ zp%btNNY7$DC_=r~l6@<9z7O7>_Je-SSLnj%5$oaNDPZ_Gu>JZXvr1q>S(}SBAJKQW-vMjZMajxpa7jE7%g|x-;6-*j&yf-(&ers`H^qn7HCpZu$-UqH zHQ)le!lXas3o`5B^azvGp$D@t{4U*vK9mJ;_hdL8+I`Ody(hKGZ}@7uqRB+^niKF# ztjI)@JxhJ|2!43*BJmNvIBKi;zLCZCH%=}W##>{{zJ&ENs3-ajcs^$(K1$ZuQ(W6t z>|?IvVQzI48M?jjSe9X~5uTm6`LXg@m^=Lk?rdUDF@`xsaL#CR@Hy2aY4q(s_`#Z1 zfOUx5y4#?$*FaN8S1;KPUpjd9b{6{i4ltV9sQr7gxr)Tfg*vg4hUWBfC?5BPvC@gX zP~+XqtnPyjgCE8gjl!R6;L2M0eNVJBfg5L^jgnVET-S7?^Z>uxhtrQg(J0FXp_zAQ zj!`IcK7GlvZEBP*)s6JO8)XMMEjixw%d?nM;Tb8jGYwMmwn2Q~8N|FAn2zUV@M*Ld z`u$Va8O66qlxsa!XXSoH-FK<*%T%Bu2}xSIpwb zjF#KzEDuVXWRtx~ZnQSZ3-)7;%(w>ZXPU6@x=#IM$~E+*Q1XjY;^fx~cttBR>+TAO%}b#^`ftR{y>g|Kb7EXNph#E}Ud*n35DW7Z=~g36>?>zT|39C_A>oTG_s^0K@!8CY{w58be$WT;Q*N4m$uP@5 z_#pmD@{hvgc<8g#{w_BRiYx+|T#s3wb{dqLv zeqJs7CZFzklwSkl3h07SX4*M_K{d=PsP&u+>A8A^^-*vU-QByW=5;NmD}EHy_BV>F z|HTrz_<^~O&10eF^-JlRZk9TGS!um^(@HCqD61b+o`q z>kh7`o?Yte*&Yq_;GBl~bY>$B@FH9Hmb2z#meH{w7tL^V)t~=dHUAkmZ8pVSH@EcA zdbXZgeJ<+I{$O1 z9&Z(<2iAmX#TQ|EzfuPc3+c zhy}ml;QP^IW=1e;BIf|li^I_;#gUT^o^L1Duny-}<$f1#aV|K%%kZujC_Z-@Sp zAAjT-bdLG>3jN7#q23q>S5AG3K7NdS{W@@TAYR3G^tZQ16BrDJfEnY!=hGY?Cculw zqFaOe&-h(!xJpm3zey)*df@w3e)aZ9QQox!i>%z~&! zk7h~M3p9tT)C9wu<3+^JvJyUJ0lwt1ij`xh$ORlpek?u(D>U+|tC@N1WRmdXU~>>2 zH8PmoRz=C=miQrxk?HY@S;AMycf~&uf5Iq%_@%celb>xJCEEhgfTu@Ef%Q>RgFeD` z;73Dzc(cg-$X6Aw!~p7RVA$Vx;D{r7&IA)Zzj!|2!SV3p=@;;i{ECrF)neu7U^2_$ zw=ciM%AK-gB-Wufs1@^x#^Hy=b9n&YitS_Oh~5YL!T3XXB_CA4i_W#~!RPdh&#O3l znJt^yKlLUfpaA;JN@~H*^oS`;9R(sGp)$T?W%nvo^IYPR+oHbpo8b2c~Dt zBKvDG`yq~;HLE3@c8oQ;6z}~y8R@Ut>wIFZbimhg3y)zAMq8INN?Ku~j50II3b4B! zx2>cH^xEf0S@$Uy$CsZa-(^2DK^HUUxfh<724pdsQyZn<=px$7(xSQfT?Oe$%3G5j zqa8-EK*w?9^Vs)2O3npD%kufr;&YI`{ad__R51J>7>}RwT`6+K&{x`^tu<_nwuaC0 z2>P01=iHpJ*U!kh=^7(J_sGEEea=C{>j_`TWc@wJ9`jyjv`a^_^T-^UU*f3jb3G{wQhf6dW&{6};ah)6mASv= zaLqsRrQ08wVgE;_ntn^ie!rR7^jo@a{4GIt_}AlpOYHog65s2GbhG~@PqzG(w&42c z$9Z+)pL|-%rhwk6Vx~_^7u473cph&T((_je>rt{{e%>vLE|a697uSE&OX$rt=4usD zQm02TZ9I$o{Rd~g}v7+zNE>;uzd%V~6ijZP+u*Yv!C4z;bQ|0de$nh%xq zW$((G^vprWcdDwtAK`TwR70aG&{t$zhv%rLp=d3?$l0C0-AT&~t*7;T>T7Ms2Kw5z zp*}Egq>Vo}((4J%I&BQuy38`_^TS2=Cgx`9w(sMvt;=|5=f})4I^?O<7ka7Fz+6B2 z_Q+=HR)u-d!$dbsQ(Z+Cz?4xf)oP}X_S?`(ubgbH2eaGgm{x7|=zKq&xVs&*Q2n*~ zqX4b&Dp0$bf^=5*_9|Av>ToVt&-DsXv-cs|3*Dv5;ZW^w5vFJQhUtRXFpbRDL8th3 z(0L0w=$cscm&+aW$60!e!1G<;abGY!FC6_V8qCV`_!iGFd+r1oSMcwp=quT9gG8{r zHea`c^@-dT4(|UvPL3nz?qfZ;_W;hGLDpgaBT{rf=Yr|w^TP2@(mOgEKR1|u*&Yo2 zfo6Um-$*QY32rL5y_Wra5qNMyFYubZ{(12G_)xg>Ftly->#-aiI08AmN1&y^n+JgT zRpy`;=EyA16olEZ*u%;QKA~mZx}TlJUfRqb`W2rVSkZkafIVEKB_s zExo=OzWHqQVle;RJ^Jp?v7W@>p9I(c&cjQ|>#5L^*W`c)BtP}obiCJ%I0r0r0vnHC zjg`O!vC`fnR<@x71W@C1C`?`J7&`e{X3_Z3tIl3~f-Sn~9{dmJug$+2#eQQh-Y9js zA?UahEa+VXZ^B=bv;C2IX!X%-*BB-Gwoz)N7-a-F|GzW2_p$v>jz};*=hab?avQFX zhhidJei?Y;^*ve^P-`nUE?28@`-m2g_VEEt!}=N;HT#HZZKz#RXDoRF&TC06AUuxQ zIdQTMJ?SSNo&u}UQ{eOi(Q96^mTkF7zbN%L^~ z59KOeo(I%{9p}f$ZuTgp!1Mj-=-batVtyMuyJnJYH_4uQ#LNon!41IrF7WkkXfQ{- z=nd_NUwr~|*zo^sM0;8BHb#2#m?s>0j&|thXv;R)*q*c@&QSk@aFt z6XtQESxx(m=X?~`h3hpsjLgF`%oQ35c2o0=T@fkAwnXB8jg(RwBIP(5%ju<&BIxAK z^!v}l=aS_UDXtBf1#KTGo@FD&*NPl;zNUid{rel_3|_|8b;(yW7|BV-3(0z$jfUoq z*5a@|T7q7X(QapwIld+t(TVvSp{%id-GshUd8kQR{Ldsc7n)?yMqcwF6Pmb5{L!Au z#k03^B~oq{*~Vvkvjn!a~w@=uvvWGa7DrgS|fMeZM$8_c4!i#jb{cIU+J z-Ua!4_Ojf0c1@01-jZ(J?#jm__vLf3$9z^#<%QiVne_af+@1bWe%?rt`z_Ms$!~aO(;w1f#y6fXLkgGT`!&Didy9W^=t&-}Uo)Rp3(v2gels_t zMM2%xv5?jdEUXjouZImOs+A@b(+~ZM>n8FWWBtu_UC)yGXpDt!Tv1As;w|;;lhXR` zi9SPTG4^JssJ!zD_IMKm*bmkPF#RBlb5^$7#-L->NbB zUoKkyl8X*r;;Kb^x#{&f?%Mply9R9X(Ca-tb!-DKtz5i`u1;y98L3Uxu6%QS+}&H< zSBj=bsRo^Cp|`1x{-V#Q^0!vH#j1@S@buMA1Ka8h@&Hn!$UwjAukFoq^A;VF!B8sc=}Fw`gFK{ zd+xjYF7?tR9`6Po_7(UNo04ry9jAXB{h?FIhxH}L1r7UH7JU2;{VCC4IhekFGJT8a zDouKT&v5Vi95>+N2Yb?A1P>n#kFO23cLm3NCb9>ePM^<$!{W+)AA!3`MrwNS>zg<5 z7Cxbd1U45=g;#%pqk}<~dE+G!EYHEAad_1yRK^=moixmWek5Bm3BdU6{QmNHJdq#Z z>yPoh!|Th!Nee8)YQe|xax%GALiDPHM=(@gveL=lb&bjLyqCyM{SNcqme)o<@xdCy&&^@d^B90Y?nXWUJ=edE~h476(gy2Vx$FJedGZ47XP8i#KcGp zx=J-O=1*4#>srK0R)2J)U1$<}m`B}`Jpp{)x?=8rz#Lt}0?p+m7`wb=lvvUm8uFK{ zaxxTiuIK(g1_`JaDYKd}XO7;`EiPo?a;^K2)isPh(U-Q|RsuYSlNZU$e2c>5E|SG~ zrV3dAaQ51b;q_#CrNz^4#Ajm5p6ZSVGoK^Lcw|;Z$+6L5f1cW?g-NEP>*siyvUi&# zWiwtx>fwd=ndB^*xjFB>%?%SXtjV@PKd4Y(POWC=GYPWmiHL*5s%9(=ab@A5idG(qE~D@FLbw&&3IMTcex?|_THAq1ro)! z??ahvcp~BcFUTo=Exyfj{peHkq{&eGbk?>Ex$B-O87IDo@0YK#HZF_WOt$n}mMuT> ze3PT#bHftf$pZT>*Ngp-1r|RfdeL_o9P>?_GO{IPUbc*#oh|VfvdMJ#CN2JDOLxtd z`EdOe3%^Up3BRNdy#D)~e^RzVUcFEtzn*=Rn-7zgP)L8DEKFus5nWTVnD%Uje=)R# z?r3AK2kMv90#z*ZSM5?7zzpgZGfQjleO9{iU>Uu;p{#msx7L)Ha(d;KjoM|E*FW?e z*-fpeWp3N)EHc%*z|lKhbI>_0tLon~)wGUx4YGi1>UU<6j!dkhFP!UYQb#8p<6lpQ z*R8L{{0(%%J!X*ZB7<>4BfKhPb(L!^*u>@gf)IkthxQ^D~MSIGkalfU0f zkOue3B)myB5V-CQAGZO+uY>28;OP+@efYjQntC)`zAs!oo%^|P|D=7)u^WsJvIh5g zOU~9lvbjdXg}pi8#vU1X$HC0;;KY9`!0t)(pTmWBcSdVz52gp8-3G$7L+A_Tw&A_G zEk_$4kJn-*-j*fkC+I4RBk(4kMEAV~2EU@W@he$a)R0=Eshr0v>4U#!Hoo$bD}tZhdCS`+>cAcr}rY4i>_u5FpAf7yd1unB>4GW zbmPHsu#7A*j+_uFmq zNYHaHp^%w1DS#gr9%<86yv)V#FK$yfb`zIhx9cBxc7QXOFPcB>ycp$>arSE%Qwh zOONMjIBFa4E&P^Aex-0*UcBX{(Tb>-Ht{D<7yo9zZSeNn=qh<)rI-VpydmC5aD4pi zoY%@8?=yAP%INlsnD_Goy@P$qd&0ptlM|W7+GSwBQsjq8Cg!L9 zTZ%eM%@`RMNbO)583~`LIdqSe3h!biaVkB-mHGSQe`GIQDA@xKT7@HWu*p%0H64@G zu_xr*fK%iloRN?f=frsTg4FMKS$6cfCZA0=Wk~hAQeoqLsZjK>6rcKxoTQhs?9LmB zeUmI58l=d$c4_k8=5$$E^|NGM%@o(@uTnZAOI9_=mJ0W?M>XjuooU-L>zi)EG1>MH| zm%Q5bo6qW}RJxt3w^zKIi|J>671A1uretw~`flNm=dURaVEAx7N!Qm{saxqaQn#*Rbgo^lFT)T3Xq0j=j1?<4ONq zS&x(9mE&0~-|1} zmyNTId*iI(`y1`s@|?G)Dlm+ak`Hhm$cGFD_g72x;C1+%~z`(Y^z;k{WSh$ zJC&=a{>U9u=e;mbTXoQ-amBF}Kes6F>URv!VL@Td1yX7N+6L!qhA|OtV{c zQ1inbw4cDw3wF}<@J`H`#+%5|g~PKl<-{=qYVV zCOog}5O{wC+|TjD?90z+=NQNeHpmZr7R#;qy?>?(@W1z5=IacJl!Nd~mkMYH@XKj_^u@p* za~{9y4d!Q(;~GKMh+Pq85`*u?%v`Oe2Dokz0Sq$ThC{rKV`^T<>eQ@pdSz3tUHuKyzgnRMj7@R^qI5%e=3pLRVWsl4ECMRXo!qd|0{8=gT;ynAFi&C%973tjY zx}5uVOUkXkC)H{{l!N=8h_&?#c{=5lxIB0(X9|80x7(j2+&oQMKc&xT!e{2Fe37xm zv-k{tk{6sUKdWR(wUb}PY~5Em%2E8pS4l0CB|o0#p5yl6i*)t02&c z`d-bDlpWF<loCORFC-pobEes$3`jV z=%X>Itu)|nYrS=~jn=yCtJBZ7)wd`8^m0Nw9b)p=NBaYG!@58nHZ4eZ_N0H*H&_?6 z4^b^ozv$FZU9vq?2fYT@8{lD_i|+Ca?+bqPGlx3p9Wec8y-r+@t~whWAI;&*Vb4*U z;~7VVYYB3jdgngyd>a_wni^;uIQmhv^qJuIWA=eQhsboYXE-r8QallcA%Z3 zxl|uSZ(CjJq#0mo3|?@!h8J4;(&}I>c=_-pTKX9{`EF{OVDzVv_{KXi8xss~l-)Fg8`c6sse@$j*&_6V35IXM+dgo_@ z;gj&UkTDa(@rC2fc=E)?&x!UieQ(;#-+3}Ok^|BrK) zSE9eg15V$9eitwDq`>k=cMSN1BE*98tl{_*ZWv@dTCd$?X6zI~haoq1>oR8OY$Y=a z{o&7lM)`M|+tDMMx1hHXkIjMSQ8K(8{)+_sGi6OO4a{BpUoO7(#}nvb86#d{_z1Vr z`w70^se(QON47+VPjaS*(*~ap+|p+^JyhUt-;(seKH)LYRnk_NB;R=S2Q=iF&8Umk zWk2A+-oTFMsf^}84%JsrxOE5~6)<@z{?3XAO=5L|eyc|&@%d$vQdP)%0r%q3V0ypK z(N^Nb_y~-jf`6s~K9_qYNoJ|-m!oRZ$h&q!M1^J3ZOqC6~pnd@^&OucT%?&f#I#_Yb_y7owhdp(nl zdy?e#tJkvWK7FGzKS+l>DU#7RO|IHx$aLdpIa}(B^q=}weClLL!zW*5&X+Gzr}r1x zknamK88c;2WTt#NohgU-d7@vYoM@0Cj{;NKKjq9pdMCxYf0F6XQe|7!4B0b0Q;uBv zDy^G+lirViNX+ctXj}i}&DT6?8jw#d$@^+I)=cN771TB%h4tRSBD&A4m^zLwuJa3# z1<;APcFipG_8SYWd$^Qd-DRn^%*xmvWu?Q8meI?{%Id~r)_U+lIW73cMzZ8sTHF=|*etcI+JzXnniIoo8xjYcw*VUFDdgr8vhK=*o z^!i?^nO<7zL=*K}-&BjwYNpdiHrL8Mz4cG1=%a3`SLd|QGf!Lc{H^s>rPliLFLN-c zk3LED)z~L(HTjI6HapNxcdhc*PSXQ)c0Y0fS_EkWG6Bw#zgYHcu&x`8rv5EN=XDF! zYYCxxwoI5-7!jtM&*6Eo>7W(=*Fnd8?VyJbb<|Z(o%A92y`CedHfoRlVu`kHj>g`V z8fhoExe1;8HvBxNzi3A^en&hn8^H3-`l9rPx`gB{UT&cnywHHL57Q;#bRhqpwJ zvBgVQA75h|Jm=`@9y7r9jnpX7xd+{)b_74K3jVgNP3Ahdylx=5zN>O{b7t2?kw;&iN>#25XAdgwXu%>5J|Mf!z~4ULwY)GYts3pddyYh3ZK z+$B4Ny4$Fy1}V56Oxa=(FZT6yFBzmlH2N;wFaivz*f5tL_U>WeF*xs}K`y*B$Pse8 z*O-$TMV+o}F)%9CAhWn%1@LLrnB4mu;qmH$^{1%=wmQ#q6*0ewy@d_7a)rg%7NHK+dP1lBe($&^C)J@D3bX@*ID7e}X_fmiTBl+>puw8VMlF%KcPr4%{nC(yh{N6JMsmlo(OD-Eo96WGW2 z8t~m4B(#!&%xJD%DT9nHYLNCN4bsBiATRk0S~X{$H0NCd`>Q3O(XdylJUmjqo?>n^ zkG;M(xh{vvaKw{zXl`z=Q8m`_pLe2VlQVw@XfA%wO>&ExZ){IA^5rqqOk!j%ewOX5 zja$CPi0?Q0f>WruP|wKOqnQ1TkpjJ9rOX-nWWn^a71@tc=Q&V`|EWLpgUn+_V#gz# zOFh2VaoJh$v^X?4C!5|}kl8+$<*DCQ>3i$CNafp{b4Qj2JS6-730VZs<(%0oZhI#; zPP`W%>yL7%SBiwMNR!tKsbiMNl$Jm6y!8Dd7dVpgeUTZxGsW-dXFkKv_|h_@XP*q2 zSs{bR$RPJAP0~uINZ*UelDFkMDctUzg!f36M|nTV(g&&H^)*B6AAgapFS6yk^-tM8 z`HwUnnMc3TYdXDOetmMFfckwlQwJ%esjCWW%lAbzzgIDpHO2MEhY}iXS5o^{v(Uxn zc+v5?*u1sWyDv)X-Xvy~zAmFR-ht_#teFc}P8Tx!sA*liF2T0?dsam?9=B8P{Px;2 zxUya}I_Q4;s=9VRv!*-L(6r>5Iz?;i(aCjm^)*LrRl`XKEUu?Ri#5=SZ5rzJYK`>v ztw#D2pUdsHjdjsW7o9QFRkx(OYWXE@`l6A$-o5Is)q67U!pu{vp77L#lf3j)gC<%Q z-DUJmF#UWp9TV4Fi!ArnZ~a7vGpZtSU<(b1YN36HYmF?`MiVRfs;5m`HIfN% z?uegSEpDe@2a&JqAE4?Ks5kNl>C+oQ+HZM#EeKby{Uumq7lde+;^cMB4pncwj9ch8 zvfPP3{S7%Ul{=`_zz&)i-9cMD@1Qv|Ie&uZZ^84No}(M!cmg|H?le_I@Cd4kX7q`+wx(>hkGQ6^L@VtzJ-}iyf`@;8YF)QgWp7cxfN6g8s zO&+KcFQtp2ai>z}yhA2S0^000Jm+(%Yr?_vwgRiG!q?#_h0>@)!i)d>rZ=&|Vfoqg zupH`5?Q#xv(OvWmoyFVo3h!b*{4~@%6`ejOt9SKmbd-bS>z*eI_X>RdEcnfFg4dCB zotaA4$Rs!oM>o)0xdEO&9~}nn-W+b;GmLBkF#U!jvzU0DMcGR%#z)g{7+Ho6IsNo; zk~$iWZqAJ4O?dUFE#}NotArnKNE?$l;9r8%bk0jfM;La`AYajS_E2Mey^i_ym*MMZzK(h6buW&W1}y4pVU)vo z_ck2J)oCnkj56kqQJS{~*YQ;jJ4W9OoHK1pl$1OJ&Qoiw5fd%*OOsasR=-$`cV{me z%^~JYY{oA+iT)uUbS5k6f9cUu=m~zCYtb^|Oth>xhL@iE?jyfs!)AJG@Y63_iAQ@i z-kgohkK0Q&RXo0X`r$hzGgB_V36Cq>9PU02ZhxQ0{=U^D1umntqsQE!=KMB=n)3m4 z7Q7_&pOVYfGg?w_l9T0-yN15wJr2T)m^2YDq9^l*3PwuNM1%b1`WzpH$K1;xUw%c< zmlGj@9KAn8$T*Hp4C6bky1#=L*LA7 zqThIvdf`jI9wm>w=qEZ5O_o2eoju1^>H|mFV|Wgak;q8u1MksZ%EXE*89y=bfUjWp zwE^fXJ?IH*PMIk}q(1tE-nB0L-Om_I9SALR;lGqNrDn0Vwkj3wAiQS-k{QjwAn;uKQrq85X`6O|!@>&de-^tsV z$&$GLqhy{;k$`t;(xLBXsR)LzYW77=%*~YKU!SS1e3m*pGsF*FCeR^WF3m`j#EewA z+%;8J%t(P_eUc5?$uf1<+y8%_DQn-zknDGS|4w{@QbgCMORuA7FfFplgZ?S4g6LHm zn^!%<^6RaI1@vmLnO^QwP(Q3HqzQ?I)vsbvZ9kxxHjON<$tfjtEc2(A*09iF)k^8{ z@|J3DQCgD=TWLo#{EG$3s288)~Z;*H=`hTXuTa!d{nm zt*m8Z9W>dtsyeQzrVY#2(E1x{s#mev8i+65?;-ioJMY-!_M-Qzu-$Q3r@l>-s^ow5cQlI`!^x(H9 zdf-7*jWKVoeCrM`ukEV4KZ({eS7+9G@h3(rTw(# zN&6G^ovQ8i{jK(Tcv7$qARC}1{+H`M9^3;ex2{`D-d@&a6W5jo}|%sxh| zo(2Z5c@8e4rB^>fjxL_Ky!coCf$1Lw?_gOxiuj}B@s%uyq&Macwa7epTwKx6`_MOv zPBSk8&HZMsh8{xCkf4P-z_U+~#}&1nxf_S$K zOnRTd_rcNpej}O-xc(eH#;GS6y1vYqYe0^dC3?*#a%6ao{*&;i*P@pRjdOXwIB8di ztlRKdIhcwL;GN5}X3$fznw}E_T5g+_Mro0s{=_NFK&y%$4sY`~@VM*?gA}+5SA>7N z!v6xni&<#9sT&PsN*Tlt9eq7V>Qc0q9R}GGYmh(aD)+%_-{)}kSDXWHw|QcaA$Q>N z=mH%$5+4|(aW?ue8qMFfWJ`^WB)R> zeCu_&+u@ePwYe)z&fk}yj7Rcj+*4V({<#cyc`431ok#VWO>0*QVmi%g|wu@Tnw0v!}Pp{lwqkPxeYFbS{9i8N-eQvkYClCEK z{bGQoP7lbfOV%d`&D`J2gknHHu`Dx$$; zglg;Op}PEGsHR@0ho7S+xSj=14*=6Ipta0_pXcAhd^$Mzbm}u57ooSn$uE)vlLnp# zg7E{^(pS0!@8S%OVVvKdzEgKH8Ec@ymjOG!p;h0Cm!Uh*L%_^!8ZWg=+|nY<@Ti7vw4T>kn%N$2$$jL1 z=JX+ECau9EgZ_RdhZhBt6X_l=@2Qja=kfo0z?!pxy#xD%MfABI4vFJ$H@7yJj?P@{ z5}XVi3N1{}58A3fcwXBIJl}){LR~JWZn+lxo^#hAXTj$E=-va+Tqd7IZ^3V|0L*x5 zM3VvA2f-(sgXIBx&;!s4mhroUGhj9Az%MYo%|q}WJl_qzj{@7LzQvo7!rJg1E{~Re znR@FZ_-SY;c_c%ap~;#uAAV_r_xjJWNO>C`N!B-Wk!SGp%19{)*7qo5l*rELGU)A9 z_Z#Ire(Q($;p2B1W%Fm|xb=>b^jNs?mni98FrvXefm9_T#bKXdg8-}3ZGu@~6k8!Zc| zFWO9xmMR;f5A5tY+#+mT(klXS)rxuD&yaw01 z!M|K?T?`GSp@Tu@d9X&haqVj2UqM@`ml`46jz&oHZ4t5)OdobJLVUsWc9$Zg*-gIx z62VMa*2-1}2@cJDtRt+$hr370r<-89JM-qYf$N2$WD@VS_0uRB)s}t6an|z&^iORw z$<2byOYMg@{|r5?G?vtoV?lnKDNzhX9*WQD$I{CAnQWc^LY#iRl$xjCNaYgAa(4Si`Cp+FX%0{SW5uk|{24O2 z?q|tU;Ik}EOBa9Zbg~1|WPHg~Nm}(uiur$(MN>aWz8}fd9g<~iz8e6 zHeQ^x^2DI+V=alkbabKv{EL?1G-|W1;=pl+p%jsXg6G>%n?fTD4{w zeOaZfMpm)b-ZjhV>4r8MsO7bB=L#A+!B)3ysHhvy+3Bn7N*dOvvf55^(2tj@=;X@P zz}4z%QK+WQT2@PkP$R8%DreqBJzWq|PhIIVIv@=+#iOCVpho)M-dW$6H`ad1_|o^f z=(T~aTCszhF0AaX$G5qwSGK!;neCzTeLeNdFHcRJ?xkyfduhIFP1G~Hsc!h*O!seT zu7j<-wccHC^*$$>_m%2s=a!oG#E0kg)w^rks6()?7Ju)n1A4aAAaH%QM>}0*@K?9H z0h-V~Pzx^()QCTU>a{LNt;l`JTPs*c7QzE_DTIAUsP4@ZMn*$NeUKiimO-Iv|1U&G zkf}cBe2A{64tnSobJ=c?yNC{R5FLF4JiR`(&|^9J3RvE#5xov*D{)|W&dlYl@O1;2 z?$6J2!r|%D(QJk=C#hYI=LK&&m_Do`k6}iB037-4(RjJF3>~C5eitYDHuIyge?TJ# zFK?r%57>(SGL_8kFnaN8!o%r<4!b~B(P?y-H*xYDUA>nt^~wp%>Dh8vrmz-tdynrC zeWWv-`dmk9pJ4K)z4XIeiI=MHsKx$3Ln(j`S(IEz3$!2`ygPO9X*#j*u*N_C8J*@X zHB_?2PVQtrUN}5{9RBpKtPcvd*CyAi40(;k<0TVc&2ZKnKlTj%__hs)_&?1bE6*MA z*rA`6C)>lZ0={!^>Sp}!ZwFtpn?}mU`v&U9VD|y^l*{NQ;QGHr@SCG6-%rD@_!Eq8 z1!nh$k5@l!kSE6sa_9)>95u+I;|6^H=rjCoFXuex{OCspsr<$u?r1Uj!LSgp{9CC= zv1R=zZI9Mahh8OD{OuYkzx*PlelYVJ!uVasNU7eL*VdB^lM#{Pun7Moy3kg9Awvq1 z7f#QUTMMHs2sFxZYP$PIQdgzE`rl3j5B=qRy1A0_7C;)Jhw zb4rjoTZ61E_#?f8%kI~yS$nGsUsA6WexjU^*OR=~s8QdgeK@BRbFlh9w1UPVaD z^a%Nrk3Ccsd@$(fP9v$IvTt%_J9)r^NFt!l?6E$+`{`B3-5&2j0xH#Z(>F0G?{JWi%c}LI7e2+_Fzx|4APrW8* zo8FW&2XBjWqkFRR=6#ts@R6*#|3sb^elFi_lO#UymHbP7BfHw>`qE$C_#{E^KFJSL ziu^i|D(Az}q~93w0qoLb|DsgscN|<^@JT$6ec&~`lLAifrRsrqvit2@$^ZL}G%NE) zW=(l5GUK&GxW5s*4R2-b95DUa2U#{RMFx#Xmptn;rO&@CnLOc#M4k8}!^!&U;h0~q zgcs0-r^xb3E~xv;7uIqiMfAzCqB{C|F@0}VLfbi;>(8K)+PJHQ-pZMG)W%Y8d6d>b zCoA=?Rz`nSDy!%0taXe-IlW!SMy)){>!pAS>M_VxSIw)a&U=}Iaify%&r?}XG4-P;EG=1N07wylv4 z9q6pJt2WmCj~nX&yyYs>;B8+Fb0y7e&0j4boSJ18J_AE!3>N= zO|Cx7TqOg7x?D5UpMoUt`r!Jytzb z>t7Ago6aHH^I@=_*b%H5{{`#k`(Rxn{l<66Nyon!53WbR)g6!EQ=}F;5^jDA-2R5f zatJIB-%TbjhX=LM{%9{3;PI)msiTgjm$WnYX@w5sg|5yzU;(bzK~s-=g!Y2YQDXtv z+l|a}7iLhD#$$q)yvsd$g-rAs;Q`M^w|1Zws{Bn`l%g-xoPG=HrS+PTlSqAZ!a{oW z;q@EQUEWX|?F;5wd*MYN5HBNEGei0eew7c*Dk_ZUz5;uP%B)rPWJKE0CtHckcfP+< zp0x{{FAsnBeu_s7uAUceZ;_+fur93X7cV1y<7FOe#a(-90X5Lpuc5=NBUgqRsh2hX zdtLA@;#DY*wp;E{v{XfZZaE?c*WiNwa9>|II=w16{f5nBsmGl&h&>oS9e!N_Jf8H< zAW84RboBKSpU`eO68Jeb$sm2uQL2OUnc(;`FeUYrK~93}MW}%e0M{F_P7LSV`+4xD zgEvK;;N^AESI~Ux+eC^5^*kTG-sE><(PGMi^HzM_ZwD`@Z{{l=kgnjoCHhRq#hine zV_5>;_QXh;`U(C0SEMX1Ol=ph`(qcp*WKu+Uu2XIu|}!+0Dt61qm)X6tG=dx5^wfR z`26+3M(NqkD2eDeH9WP&0L8hPT*&k)xs$_B7@s8Z%w-P=d&D``_&YXTF*OtB{ z?)IhpI`L9kcYn=Hv$yiQ#e11a#$(&LDU!AzUFIfaO3TIq<{#R0cCRpg89;I{F^kPJ&|2m+cJZ+ z$*8K}WHo)+riL!es;Mnz)z-Y(b+l#Mx;kT;lSZtqr{%WR*GelJ=*+bu)r%aRXJZJUQ4fwyN_c(AUHf8DpUD41(UJHT_s5InEBaH->3c%Yf9Z=?#|K<*$m^=fYjvPTV4EOSO5?d? z|1bhfx99xWo4l4|ysq7F{Kc$0!|=kiV|}QPep8Mf(^B|gzU2BPUCzZ(qs*OUaTXo@ zJ+(T^x_HpbM~PB=z`RJves9 z0+F($Sfo^gXCEm^jtD=O`vQjt+b^LB$AaSz&}WXo**n7DC*@%Kb^Lg*&|?bGhtwJ@ zqyB0I503!T9gEQa{)hel-XQ|_MS!=&sq>U4Ik$w`ekF-2V64BrTgTpyksx)$tab-8>My8D0ykm z9A&iWl|fN5eIR|GaQZPz&}h(bQufj_h3=D+TX~WmDr?UD2T$HT6;F6gqjbGR4hw5j zPS1W1*3Rvr2I-yGAWOmW1aLi?qjP+OR6fnu%MmgjonDW} zgWPLnkQKuXvSYJBELea4n&Ta1?VG(bM?d2=vvleOdC%i3ni^6PD~ z6r1!xmL`9Y>a{=0MRb-EWConK{3O$ce-w}E$&%{)R%(rZEz^g-lEYhHN&wmGXJ)*B zt2~hfb(5rmypksE&~>)G6LYls63tVX+nz2?v6<4NP_`6t`@#O}51Gk%wAjpi>hv$a zb{=M?Kd%+k-(Y&4QAIQ~uBgt+DyCE2O6awf<{EaYq%PTEp%d|@&#!H%M@p2|!@o*v z9WnuOdXCzrl-2N5Yc!T}I;&85EncC5W;ofZl~klx$xcsqti*ZtYJIG-mML9DJNs4D z?pvy9R>c~6Ca$KgY*bsjt*)bcpE+uRg_F*ACg;V!zLpJYpnEDe)HGv5%`DeQqo^Gfm__j=5p7e(e65Sl!r#6yH9Ka zwl{5}x3sA~a&M+{$O@?aySeuM>8>&q!E$t&u7^1vY#)XP z#tvK`0uzJE0NucMfuGZFn9uVem=Wba1f@47}7z&mEK<)sd4i%+F7 zbxk}geNXY2;Pog^wDMq{kJsC(Biai;53Y;vvI<^#IJ&(BuRT9&6`0-~jmC;S#DOd5 zEph1T>)_;LsI7wO)8Xf}^TE&2hi2lw1T-@Hy8UU^gih%7%{LgtncC|RzScQukSTa)M)SIS^22j^9q-X=-nHfRb)aVn zjb<&6xw$d#ry+RGZJk%4&r?&KdJgRduVhiawgL0cnnW!4ndh#)lW?U~d<50cr^i+u*yaTj|Ue|(Dj>ag~GjF9C=BIM)N z2ys~#A!{~ANcRH~@_^fZqq`))&ntuH*#)_N<*8TWYwXq>PTt)h>lU+LqR#O)5AWHV zdhNs>D`bL=a#*{6;uMo;!Mv_Ssf!kZnD&&!X<+UG}@;doTKT{tRd_vQLp z+~%K@A@xtohGS>Ms@XYtY<@w$+Mu}f#q<7+XNd@IZUy%o1}@8m^~_tNItd+Ay% zS+2Pxi}QcU61*ZubIFi54)0{$f>*NmagrR8B#GSlLN@1lA+z0{OLeE`vfKHEB$a$A z|CMPM@JI;^Ihj&EE^-*>RrW9uvH)HDYz-L$HfT~|#D z7ObI_=hoCiWHJVO*HQbijyi68UA=P2Njrb3r~R5V(4H0PBkkKzf46T)-)BRedB36l z4QiwhzckY6mz-6y8}oeb8lB~$?_*tb*bx`?`{V+)lhydlRZW}RGNMic$JqN%2tH`7FFsFqo|d5slHs>YsHEgRB8|GaCVryjRdi*l{>=!({A-@{jX z9B8YD>iVf~OKPZ>{nWU;ot7HyuNyrAH0x=AmR}pFZSDnXt=@rJ=)VA+U_qwiHGl0F z<*#;`3DWX2+&Ufac?#KF$@p3Ldus!}JHX%PgYnKUb9+PkJxY*=SIJL5gO-s%whO#H zV?TPv4*E(rvo>ttK774=F!%iY;Cwoq{jfLBQ4Nm_n#UFDmaFg;n!{D@bkFrTMrWa| zqrrSQg08ZkSreP#>TB?XuY$upDzi1$D-fY-eZua zTjBOA4f1WeflSuinqOUSgLtAb?C#8dU^1A`dG**6m}eMdwiy_15h;CHdy;?AS9vw} zJ|iC*@!*_htUqAiG*9vg>YzJwzwfMNwtSz-{^7xPW_R9>loRm$ zllUlC+Z&}3nd4eDSAW0b3U}wa-5X+*d2`_X8~=}_vyO{u?V_+ECI*5Ch>C!qD1xn+ zu(#cM?e6Yt>$SVRcI&lc07U@@5d=X+=~TcLySu+fi?Erac z2w=uXfUF1W+n(h$J9s|pmTBEg;QMXOd$t|vFAcrOVfo@Gw~f>m_#9&!@jaotgkLep z75cjBEI?P8VUSMq4f1G{L7JR4&@XL}V!0;Y3-#yfnDNdH>Pm}`9lI6cLX?&h+`MY$c zwAh@mA_lPmWxKPH31jV*c-4 zan}2?t-vF>zw(J(`SV(cRn0*L_}0JN~lJYafbhuc{?A(WjKox3|=VH!St_{?htoxs@)RZOv@vGJ0aF zjb=_StAG7tt9O`L_wOEiy?CaaF23rZ?sv*-tFINbu$`k$)k@lf`J>L!&KhZ5Sx=31 z)$Va_da-%l9E?xd)iflZht{l8L(}oU{QBEV&Ejf;*L8K$sam?DLoLm2S4+JX*3#zp zYUzqGwY4Rh%oj(z>)Ca6m{&bbD^X9w-__Og&+F=64eDuhR6Sj>tiJB2N68W0J@C7? zu97@&%(G?mnqF?APX;yBNv)fa@z`A7ziO@{=lSTx(!SdA20ocM(a#m}Jzi<4?cSSa zW^~k~!tK=RLtAYzp`9M6M$Y<+_S$_%2i@KQ{@$k(&*`Rz2X@l+<4ihyN1Ybhfq6|G zH1;>WK^#qgl8gHdzv5@K5^%m07~d0&AM^r_{tAB!_m@3{$D_Zu2Rpk*;a5bP$qb~A z)WCay?TwFJkSE-3qrQ6UEL?aGy89fs`(X4PaJG3P@_ehn>B06Qx6wV|#UKA7gO~oE zKX-$vBZA{s@V=n0Gzvn8L1&LUj|R!(V^_&nWbb+fj&90yoK_-)KKu|V1W&&?7=O!o zX5g8TZGeW}#F;);ck~tye3~2utKpw#O(|ZUbqh?l`-9f<79ZndvR=URP28I5z`fCi za?mr6ONeadnmpj>r#6G<&G0lPqKUQ)5|_QqpUcE+h9`Xi9Ia-hvocuE$h4L4(Kqz$ zPe%`MgwMi(r{eiPp7&hN}efq!7&0(XB&1N&lI<4xIQ;=lpo^$+uODu99L zG;vq`MBwE|4)A(#IesPD0@$1hAN@Upe{w9--M>K7JObzp1?eC_#Y0Q*O{Zv z96yPj=qEYgcL6YOcsab*;GQLXb#k~t?tCn7*9vo`GJ9p=;0T=P_m_GMvKBwa>w4p=( z5(uZC8|P1ctiKe1@87&mZzj4QGswYl23g<9fI-+G3%eVn#59Ar z?lH*AXoFOuSGO~I%i9L5fxTE8C*bj)ly}`T_|8u`uwD(|ns%|a-Ddq|9ojO1wdHbv zbfOO4cNR5a{5&Q-C_Cn?j2MK!@^hdJ`S+a6CX2=^<-D}P!(vCxbNUc^>F~pjz+3fe z4S$zyjpFpyDCd@k%I(q@#edsHnd=ZH2abnHW}8cLwQ#uT>u@>wJ3@TxMoP~WQTUCn zNdGx8vfJgFl>Ts?n#&FLmT^)oF+qN(CCOp;R4H^mO^%gGmo*>Lm?fGn@3S(bX31N! zw#se!+%rpB`DaVPLi8RryDQ84+!N2?_vQD*2eP9#x=O}FIT86#-f-WAnRX4PJ&*^J z?n|w|?~2ow9Fe8jGN(eeWFO2TH!MpYe9w~eZ?fffzB_Wk@6P{m|DeS~@tvG2cXFSJ zXFlq!Q{GF?kk4|g$akqV|CdxA$?S|@`Stjk0&3^TJdB-%bT3&i6DQ@(C2f1gLMzQF zu4|{1&_xqV>cIY`G|b0RySbOvW#z4OpRKj#v%~vR-bPpBeHrL!i$B{=cXzg@@3Ne> zp6{SFc9qwb#tJ&)UPXOVvXaKPa?)`toOM%zi~gwSs%2-m>7?{3I>F6dJM;z9XIIyC zdp)%5#TuFlS8tHyMGtFDb#7Nv>%a2S+ZkTE8vZ`GVNGp*sHVEsuB9F+wN!`J))vX+ ze1ZRcPS(~^QybyY{NW_qGybFFdNMLacy;M-*!5$4n0c;+v~=W?KLXCokp#1r`@Nw)5+u8X{i!M>08_=p~Z~Su82|U z7Bosoexpclk;d%qKK;_=VLoGI#GXw~m@>1h~HJ3cW{R)J)N0Lcs8j=rQ&j z>-?#kg6)IA^y;hWMVf^sG9EAFC^FV3qk{~&AoJnQS$N0S{u?3#&=^hr#wU-NSMd-Z zIC{B9O0b-aCx?;4Eg7zSi~In77Xe2%%_KTtN!~zZJcmuuCDG?AZ=vQHiBAQM+~O0p zP4N8>_`LueZ;zfnzdGv+cwd8`)%}jYg<5JS&c8Yh&m)J!)eu>AkoOyhAF>g-jfLRs z=sXYb&hM_r+#mXlHg};13SZhfeCdx$o|ETpfpArNaz^0c!y{7QEjZ8#P30l=&oDG} zaBfC691{NfwMU*#(hV;DPhEeRZI9++MfP7M_%E+%Gzg!JH~ajLcwykjeZkmRcw;L5 zi}B!dy(!@GP<-lL@IE%o!=SMh;OX|{P}%Z)XZmU2opsxyx%b4o*AHD8EPv6J*TBtP z+|g}{f@N6-X|clO$389Fj~eLf#aG!Ie-7APbO*fmKR+4B@qQaQ2Fu{^Gsz7H^R|PX zV|efF7I1q!B=+ErCGIRg1v)zgP!&zo?3S;>+u5Ji!;}NzJuCI6jkgY%!dd zBXbVl5#PgWbgCe3KP>Z?;zz;ztNya}zQ1&4ZM^&n-wv2M^*ptSd1yTF^2gWnK6iLW zuB9bwW*xE<>{#Q_QcmJy`Ha?bcBDbJ)-lMbVg?!a`?SolH%R5q26`$DQU(rR6b9`-}4Qmi5funn*3bNS_eNwxGroe?eaEFv`%rp<-om zQO2BxmrEG>W|({#a!K-kza*Xh3zzdlBjmZyW#;=uN=CmZ@!E1l9zKqi=UuK!_4I4< z{qI;bk(;tUJx*3FPLOvFNpgRBvW)RfkwxAqV$&d5Di%)`^WG`4wqu$&B&W;NxtX$2 zZ%ck=*DcJ=mdK|$^3T&dveuqnq#O68;=d1M_^111$Ka6(K(8@JFRy!tIkP#^**068 zJhS-Qy)E@?-IB1EnNq3fZP`{dTSo29ksDEWq{Etf(!lqj#QNm*9clU3(kkh_%)9tm zYV`On`%nFnsbG46$NANFU;%CQBrm_qYG+}so>N4JS`^deKZ@zzXbUYIP+Tht#mni;Dh`_4l6(N_ zq}4Z(ogVI}eLq&x=3dTfGucIRgDPwF0&cpna}{;mR8^yxadbbcnlAoUU2oQ}p*7t- z_2o8Ct+U=!k4*MdvzDIvmY-d&<*DiY$!lP zJ}-?fR8vp;!SiR-(jj2J!>T&!ytl62m_qKlb$$JfcV-8A&D$R6@vj@G)xm~(q$?Wy zeQ(awi1oo+cRXyY3;X2duXow&qiKyr_q9~bN>F}pI@)NL{jD^?*h}DSbwxAyaJ4W_6O|( z4nG}@W-!{!n>%PI;Ck;ka5);kVmRE~NL@6D`O|Rp9pL(glXx8uqF--An}MU;Uq-&; zDrTGVvpRK*GIA1i*-Gd&=-HE(;UTBix!pEImZGVQgNLV5J3R;|4+qCjJ_?r5r_8N; zLxwrI0uRx-O|z-@;!81kXfAXk7YrTTgzFvw_-xQ&>aY)3|C-+yVJ-1u29qy+RW-WYo|85N)%jV>^Q|D?<52?wU z(4U^b`Zei`SMss(-Tj`4C;Mms9&G%A?AuLy`$7NGw|^ME90-R_1v|hC8#s9l^opmY zsf~Vydq2jX2OiRKFPoFa>MiMgLTK|`pF~Kk&xkd`~KqE>chng@c4)U4ga*fJ!Oyw zCGcl*j#;b;jX7p<&h7X}OkToojaUoLf%89EE2@w|-o#%@`J#QZZUwVPDa77o<_9uX z*vo|Q9M_uu;xpJ^UM|67zl~l{jsx892F8}Fj6Rj&Cxf}3!NsZhW*Vd#hYdbNKRhhH zVFpP;Z@DoMeWeNC16V%l*lFp%^0agbKP`tm46+U_W->heEuY~puJh0g)+_cJ=8yRN zpOYT(^cDpNi52yi4*$Rjx?GUom5kC7o#jkqsQkP7qPzjiTRaaF`=ys;O4)F! zd^{XIKSFBdM##PWm*pA#M7;+_N&4_BvVBRk9HcJlXLgOf=yh3^7%NlT-;^EEaq`O} zL3WNzltt~5r2CO18P*Waz9E6Xy=zjdRiZpwn#}!VSzR2hy-22XUU-XHkhi7q0@Ga5 zY;xIhWJdkF+|OlB(_J}JB}e}C&X%bWS@LaI7P+an<=Vj8GB)&G@P|NVZX zX3D+kSyEw14twys@-XneSoL@$gB+g7+)z{g%UjvD_Jhp(i@cY(@3QCfFR>V(Pv2e1 zuU%~msM`#4ErXwN4SvR_p9||%v!d$%y{Hb%Ev6?@(baDj*D~=Xbh&B1(bH1e_P3?F z+gNG6YS!w~w2aQ}Y@>#uWwp*sdXLuGX^SKFIx?c1j=$@`dsWcW)hen@FGt{#KZRM- z9X#|ya}Ryi)kD88_Ryh89{Q>g^QVn9z*jGw9_FFOr}U&ccaL@&;+2eVsQ;C3 zq<*U!Yd6oPdL_P@+LZ9oW)FOH-xKCkXNn#jteVqX)nk@w!dcbs9EV=1F5T2ZCzJj7 z;%G~C^lPanYZ%3rBc!@f*1H>Jx0_KOI@60>(J0OAjncx}DE;B_W60v4{R0dK*9(E` zGr;xr;QBUjJv4?|=w)<|i}dw`;Eh3#>E(yN1TE&ve!MR`=|=+F&vP4l3jaEI9|X?N zA9g|3g0rRI)(!E)bm$5u*C1cZhD_XoAu{a;KF80&aumbyfU{pTfv` zVGW2q0AF8=?lJ|>3-7bK8aZI>1zhkVShT7^D?A)zv!>V_%Li zhy(tPwOhP58#fPSKnf_XI z|Bv{0q7UQW`9{7%Kk^=9(b?#ab-YGT>|cT6lM^T({vtD%eucF~$OEDmy2T*=21j0y zlYNci?-MHPoiEC8b7nwig-O3Xm!w6DaCDt;**`KumcEUUHVZC`(LPdc((fOM-m-Ye z6`9v9n)%i-h#BV&F}&^pBH*&*EkF%LM7NB~i+SCQ6OQi83}d zUZ!ch9BG^&6)cm;=ueiJ{ZnPOdpdRL3|YJ~Q&xK4lKCOGWHGu-y+5}lyk?fHnR;8^ zKhKnij+uCdGbK1Vll3xF!Y*bqgD;aD^-LLAJ3}%%WyrGhOc~rQOGd5EktsLs%BvO+ zB)s%v>DTqCJn(ucNh98han47nc^Z*r7 zkK%>ZzHkv8^u36#dRA1oXBE>@85Y|9UU41rt%M${R7(GJvec$?N~_f#D=iXatyytp zbYHHGw*OOBH2m>Twau5~$09pRw&SCrSqh6;Kly`ox~Rnnt1oU~zIXDzkfMSbHc z>tj1Nt-i2|E<93IOHOfD_cGPA<?Eo#|3d_m!)r z##+_%$>?g@Dx#Y9)#@6xxv<*Gbj%%|F$3hl_`9N$}8>8}qO~ zA=Oh0HuciGo4j=0b1$8;8GVPo)%AyKYl%H|bo$V`c;D-3;V1RTw5g9Dv7sJ#@2v@e zjdikPQ$5hEnci_}&PSVul;=z<}%B{^NQ3;Ox{-H}58^cMEvFoF1hmd9~Daws3f?95=Y{i)W@6&zWc+A}_1rSHU0o z3eMhXEcMd)=qT{^%7HwGHKY4)wD&K(CKI0x+a>&Yva8zSX~vlg_* zOXG&m5}rOOliKX5V6mS|&rwS_FFG8B^9JEFG*G|X&R%~e_}mGstw>F?5L$*cSyJdH$H3Ra zz2K95z<%(jD|lJB0o>may%*hhFCOd6?Rc#lp`E-rEd#!tmJNRy9hYSPz`3Ru=I3SL$Nc_rWBfUs<4Y^Fb#6nu`N@#MtUchn z0Ze!1=QVkcQ=j3%XYw%h>v@CRgp;p!%EM(FuJ;r?de=^}v6k>Tce8#)vJQdiuRh_= zXJ0b;A^VRDoM$6-T)vNs0=A>?S704-;k@Tf-;L>cHs~(4coYkO>ses`VRUn@=M~rf z6TPSo`pUSW)Ib**q%LdBCu*Td{S9)yu|e!?3^M28Y1zE}G`+#6rQfB~vb&Z+wyfq_ zGq`@f!=Mq=Mg8zSvOidXr^kffwhvfyzW7TM>bVb}p@)6rF__*4&;3K{quF104!-mS zIcM;ToRtS;0obe{f09`okNI0L^$1zaBY*e(fDkmo%!#OGDIWQCX<829F4>2_(L;f zMf(idH8ew-jmwb3+cW4T&6JKSZb|?CS#n@*j`WYaE6;~Nkp6uh%de=XGVJ0@$sYbr z`k(wHg{yy)pVNQJrJ;W$=NL1NI_B3qHOw@wN&$_iVy*$s1$BiD{ui^tTH{4w?T}hT z=SCLQXBUgksKG2$Fa3JFrrK_*rG@L&)|r8|)plZ?|8x4cVEbQp8tR>ijr8=v#(I8X6J1xd zsWx?Ms%E>I@EmU~)1#@*9o0++v}~>wM*HZ&?Y{cN0llUPtsvcu)bEUPyNgjgIy2|6 zgHcYlF-k8r%J3#eNkk`!gukzWw{NvVn*rCGqO%)bqZ2;FA9EWHoP_=oi{~4Cy#qQ- z20Ba-I?O_FJq=u6a2!q#u4jPflQyHnuLR%!p?*0B|Kk9-e+78_4f=)FFn6e5i1ded zSA&1gFUR9D%rB*0xzd7+uEHVG6@0%5fB%dBJFlrf{lzf{9-jyXn`RgdsuDua9l2Z` zsCD*c9hiW(h4 zz4S;)Z4@O3cSK3GFHzz$=!z7*eMN>(ik4WX7ew;;iFq9_-*3f>@4pEW6qhJNoRj5Kj}$oo zUw`PFCfnDf$$<%JQetkZ-29cqwOxZ#B*|$w{jNqSQsh^P%>R@s1vjTjXNz=MHX~j9 zo~FyM`5CfdK&Fh?bBjK|Ea_S^M>bGLZBgQZ%q{*{4laHwj;miv?#Oq%=Xbea{Y{#- zG|j>=)2==8X+2{;9Wy7tRvT=l0UZlyzB=amvs6J{`MjXEi7BLa4;9uO%gIxpSyb~c zE2cRYE%bJk5^A4ZQj2%9RI|CIwd6!A&9}~4m&4W9{mxU<^tYQ1c;l+B<6YI@?5fj?@cgo_dZ&e}Zd~iC`Tus+zaLlDcWo={ zlzNqQ_`J&6=uTy|t>vm4#<*&e?XG$&h38gv)9=1+`sI+D9ve_a-#s;D{<>=6!PWHH z5)bY1zJ@k_>ZwtaywrTS7r*l&^sAOyd)L*^{pzbbv#d8Z^ww9_jkM{GMp`I_jNg@w zv~d)9zt_kSYu{8mFKMO+_cd3ql|JfQ(O38N^3?((!1Li?HAnqnMsXZsl$`^pk@hyq z0{%8Pv@*(}Mn-9mK2yulDBs}gl?%Y(KjU3_PJQ$)zD6{d*=R5UaP_8WFlJ#FB4y*+il?OBhcGFqO}L(lQG8=vk_0s_j}C9cn{8l?KzeqQUNdGXvaL9 zH|5N%9||95A5dWdYr-OUI>!UBJpUYU9L;6n2t4WCdEA^#0WjUG824Y}c}XQxERs4Y zKFThBc<5a?Po*I7czaH^Tr~BApOr9wd=OE1Ha6hzK93eLn|{RO_%jUP5jYpM9dG#- z>V{yJ%W^pDcr@?UcuCMGCZVIO+?R)Ip~vxPfZ1DJ@v}Dt$9PU0xF5s)L16JOd-M!2 z_tYJO{LLCLYBX9%Yl931-;xdFQGvC==qu6S_+2o(6PRhjXz_-7^Im7c(SBX%W9kM+ zhgV}}k=euXsH4{}1i$|q<|kE$QfuY`#iY zPx)?;|LU_o?BV?AEKk7mQ!mNViYBvVHGGL4HP)Jn^wUlzXYDNh z%X{edaPxfBMMJVpYqP&RqUWF;eX*zLp*3;&8jH_}U48n7=^Y(8@~jkTO8zjj3Xdh7 zmq;UXx%s=P$^Lca>QG5@43oc(T#{SA!^OG9WigD7l;}=T^gBd}cl|3;e;JsQ3h zJQ^K4nzc1=cfrW)+t`rc8`76cfbVY%^xYYCZEn&kYDGGH`8W~3TXKI0{Y8nuIE-3RP)}2G_`7B{r0D@*8g2ZH#94z z_BSoG)0q-rU1^=N+fx5tU0Q#gv(kzddHqMyi}@I>ZS`9ZJN-O2&#OLW4_y5~d7YF| zf!9^i7=xoG_o$@b)k$+|IIHbTXT34sMZ1-&tn0EWGgr=y=T%eJ25wpsypLR$*LON? zw2St*Q8!z=6S#jg5!lbfEbT~#BiR#VR{)%Ea34}DXnhVFZA()Fup zsnO{1PPNskNnP!7x1KgC(?EkCH_%2S8)~vYx=em=eP>|SQg$Ov=+Z>TU1+MEo;K5( zDa|#0ypNtc?W6zVl|9Fi&T*QAFJSr{FuhACen$9u8IHy0=}ARHZw*iXmpbX08SwQX zaQoJHWZdX=`UNkhUKxoF;xsA`hu72zk=gaApVp%PzdG58E_fBuSe)=Mx}vE&!l6xB zy{0+O4Z+&%8~A4M#-!cH+x`UaA-&e~si|h8!JGJdRdo8rEqQGZYN3PRNFPo5yXq^AG(BhdxUgKvYMfQR6lO%9lO6C5$3r-OY+*#fUy?x< zqX}=?g=P{-7D++4F!)`*CHitFKXR1d!EovKb-+S+@=!}&hhDM$p+V-O58IGkvK4K7 z0(e!>7HqDKr;yiP>WtpPv7#$$3g@dknso#W&Nm(Y3`UPf<9`okPh90E{_EiF8_-KO z!sl6ce0NeOJxF%dQF08A`N<-1SkRMNZ71hoGoNJ}=U}ZW5(MVPq3`7SN%AjrB6zQr z6Mjq&ye;+p#i1G5Gt@@wQa2uep1vELZUmN|<2@5u3l2`D=Vu779l9Y{gW3yCF-!Xqp6X8!e>fNbYGPKF++3l zqDR(zBU$Vp$V;d1sqiFx>GYRXCu3|z3ue+W>!L3GMTc15_mk~rs+~u-qW`W+s2q8O z*W7SP2CR#a2QwpOJ2~frhDS?*XVGF&G)Bt0#>k%@F;f4Z80o(zM*dzEBS)6S$j)6c z^5tm^nebPc&vlKu&ULBwhndkAVr6CH8}h^Z2IsjZ`QziHtaqZkj7<{zTZ-UPWmG*KRwOp+zV;Oq7&5_U61n%_&2>)li2>$GI4b0tX@ z?n#oXH0k6X&96)_l{-A^)s1L@69dgJugc< z$K*(lsJk+B&jUI4{jn?|AK=oSSM)=@6R&9>Wp%wTa%tf=InwV3e;+@k_PO6OxqsgL zx?d&CGzxt^|KtLCq_(-vMq}@Krl2k#SqN+^tW{?f(URqgalg3w-z%XX+mzB}V=Z;- z>C$9bS*vgRGFoYbjs6@~R)b=umKW`ud25;lF)#bJ0lnR>WP*Im0t*CaL z9CiO!N3HR1C2eQtr2e~|)VsMe{rN6h?y8HX;Ezd}=B%wEoix$ONkjgrq`NX4bqB8t zv2dif)KML~JL>qkd3~ybi#lq-GZppgp^EzQaz$($YK@U`sdDXQ?TMw;P)>He>uc_-6 z*47c_@V>XGrz^kL({}yq>$#)#b@|u&8bvSb=+)jjgxPt9vQ5=%STnsgxVbJY7{FSLCQO# z(foj$r;=-alG}OkW;75-w3D-K$>M@zpJ)unu8qzPZ;wQ0uLM^Q1hY;2y!ILNmq564 z6tkaW@TkD4e}ypviDMpK_Y{1P5An<-q1jA>yASeYt!Nq|o!jA~1m9<|FUW+$KLY2w z!qZ2gz5I4(jvZXT)fd)>yZGkuG=}s3?N*Ta`;EL^59a@p`7&sAo{l=_#98S{Hr2R! z0W$1V-b}h>)cEQ*!h>B2&pMpdAKcp)g@z6u*69sz{skUIkVO)VUVuKn5+BRBLg1`B zIM)XM3pl(G&RlsgKSNV@YQkE;?>@Rve{@BQu0%f*+;xaEoYxC3E%0o(bBU4Y?_lLs zaNFczDY%&PtwcixvlBS?Be?MP|HuV9PJNbr#Iv*f3~Y|O0CrzQ&yPTRi3Yb>hdL+o z^E5Jl)8Y2qDu-=`pES%tXMalW*f+fKaPh|YTEg)2oasg`0zQ>>L%BZ&-y+`h5*#}R zQX8$E$9+eF>ub?qZgM_nuHnl8*07V{Jm-vk%enEynEF+}l)%HzIyid@>r+E?c5Cz; zzO$20@U^6a)z=KNAdGxP^!@IK4C1~8-#Pq!G5Bt`oGjf9^!|hS27dn{7Tulw(9=@9 zPo2Cq!i@dEuFmwk;-UORU9@I7`kj2pEgMdL4cy!-8NYlLGAWmk6_#~I>U%I}6#wGQ zPt;Fd2g*P%vd()ln|2ia&HSDIGaNtfJ?1}ey(kTQE=f_(2syJTQs$SAmXC2)#lP!y zSyG%?L=~>d=EB#+w*NKhJMx-XH@PPD-tqgLS7mgAtIYYjDm7oBxqQ1O`s%vOPly%Q zT{mQJ)0=Yc-<$H!+BorFnjoP+lH^@PikMwV6=Q)k37D2Dr!tc9eJ0B6HgNdU2~uM~ zqNHz1kd#RYax6Mg-aSZ`makHzM+5Zp&nZ%NTncl-k|k_vvfOh>mTsq$cAR@6U5CDq zm>aKUXZkz2+V`U*Py8%RT6~oOMZSyW?H{runLdj#)BOty z=<6Eh8X04*PAv+mf7?P}X%Tg*TTJI$7uTL=OXxG_Qfj%#QjO`Q^@M}9j%iy)bB5cf zi;^S2>M8?V!J#mDjlu<@LBv1MP z*~Z^N_jh&BmUA8Sa)yHreB_{3UmWyKgYw#?S9u-#th|mdS5Y^eaMZo`D`_7yXSFQm zq7eluYn$?}I%=w$`k}!uHFMXlN$&b`0W+AER@VmZ^tO6>>0_r_`Z$C>);o1{|LnS2 zrb}IQ$1~$w)YQvbSHHvA&EGZBWByIlr+hQDXxLoC-Z$5~K5%t>vjIDe@_4sVn(W8V zcnCZ{ino!YEsxu6zzZ|WD0K$G)6rpCco}6LHPah~jq(Bg#qSAyM_~F2v=>{jyCQhr z3eBY%+`I<*%dqIYI_P&Eo9_hY7vUuw$NcKQ@WwR4_;PeT8nq?6kE3GS`~f46$(2 z9qi{Pkmb^XY_0Ol9(_YiG=yA{NoeZ%!Am@UkHMx8bMVRy?};zm9xOl0@2h~vxr^|6 zaNBb-KL@W(Jo9Diyk40VgV4gqpxJ}najU2`qV4>*6Ws%h9DfwN1t&*?*%tzM-gz({ zeEb7mFM*#niAQ?@pL?KJ@3@DK@`&d?VJ&!0&f{xzel+mtALN8lqik5rU$VegcX+lJ z{zGd!d?AitHrU&$A^lbD{bj}oJR>XdtL$SA#eRP|PhFuOUc_18rD^Z-dWFBV=?Q%XHdJ*F!a9{80#ox)|vpn(t=iE^> zNqU}T4S0|$f10Gp;zDVXGe1?fJx&pK{OmhJlVu4t)g|VMGWB-6q_7s$PEV2-X({r? zBTc%MPZ#&g=~C4xLk^bD5clW|X*}GD2K8d1?%JCAWzwRh11XgsGT zy6KzTlY>U6D`ldc!M|AaV=r3cxp@rjXtO};@q(*ui&1Ee5d4BYBPdtmA@iT76 z17q?xdZ4|0+C(4eJZhz*xZf2o44D23k9tr+yzBhmC>IBopGEW7jjwzaGm+-fe>ag? z7sHqt4Yr%X-EGlEQqfWNm&?;=CW5+fqEx+{SSMG zxy8xs0%O16Gr3?(&Z9lvY}TFChz9LOH^1zU4h9}3kz;ldULNc(oi6dS3uKLf_2Z_K3De!5ye`g%J~Iq{zvmCW z_^<3SxE}LT%;?~J-W~m!VeKz(xb7aisbvo0x@+^f?D#yE=p|O{QEXVl%1}oxj#r&^ zt~#2`_{Ro`$OhMM8>HSngG7S)`M`fW3)aVy>`^`$B)S-0__6FeIA4Rm>G!(Dnp-_U z%8Ux2Eh8;gc_L(WFsluj{mGB7z_qJAbwx4B8O zd|QfKT4loTY$@!2TM7-x61Te9Qub_?9J0JEn?30>vdxghv8IWkRleNC136H{dudd#Y*WT`SZZw(kZ@}}%zFW~K!D$%pkq@+)} zT%$)dIxt=0dhSIDJ>ltRG7JSmtB=&dZERjC(Eh%-+i64ew-N z#}Cq~#wRIQ;ft&>|0Y`!zss;WKgG7tZ;6@*Z=aS=D^aPO*0CTg+ZZPs`KY-?y~ag=g*1R_wH`O&&g51dt8Jy3qJ~S@oP> zR`&&zRoBY4+PS%{-gC9pbN9=t1v9SmqxU@OSXSeYm(@94$cYTL)t8xN!Q9e}Ft*j? zOZGb6+d++2%InLK74;#t+D1j3w8beWwO!@Je2t2_y`77?&vMl(wpDaVMe4I1Onw?y zJ%5Yb$l*1#Il6io_gXsOzuH>+6uAVy>S)m6x|(KNUtJ0})GfWewNYXt9r=GBOfx;K zKI%-3w0}!q{mTz8V}Mcmox|f2inaodkIgd5j9>h%77Ue%4~_Enm{E$%BX5Yh>7B+# z@pduFrxHe~@Pj;oXXxbU=~vKQp25YFj^TsBx0sC1a(*wF{s+jl-H(rb8$CbxUAD|5 zCvgPX>fPv1Z3?%q0@p8vuMwZ&v%7d(uA_yVqo?Q)HPg*_Qp(yMU}+BT&+5Wak~tosLGrv? zo`zcZJ#!{4&Phox<{^wYD=nG*)|5SaLF#H>`{9?cAtMCrsQe%Ol;iMN)W%=&8Ei)9 z*n}41x*o0#W*-N?mxfVmM4x^FZ~X~I&w@j@%)~2llOqx>_!9Vpev=yyo`ZRH!RIRA z@(}c$Ab9f=){Lgk>$|F?5*q=;PDq2}PS((uSI3J#uYWJJz$FJmVTGv!*m?n#b$y z;OoEnF1pO)`w;v>VED)Ud|t5Gw;CQIALhxm)jU9w})S{iQ%Ad`YR=riV0Kgg?vT5g7;_h24f zzCf9LlsVWP$wU8oPBMeeOV*(v>5_;Z=XF8c;XyO%UKI2AFxfsWT#OYjOWmMIi8a3> zVeMk1=HBb#+9ggJyibspi;|>OWRj#dNs=$85+!oB2|JU;dttnEJ9twj+=-RIjO%j! z!FAaKKc58O+?BB}v*l0AESZ&gODb-|t8ynpYMEzB`>0IuoO(-|uDT^h6Eme@@eH{XlO}Vv zrOEj_X|mQlO}-UMk(|Xz@-mAI-{=&H8l5H+sF7YxOqZS?(&b7#c-|&m!X~6ky+axF zg4~im^fB!T&yl2Y_atZdL)p5UIe9+M#G=RxY3BP<L(uybxSR- z=R1{D$8)9halz8s%hyU5kFeILab>iZkBxrHu+duG%c|q{vbtbrS)DzltgaYTRwMhB z)uW@z>Yg?He0*88dPW|5WgERZwv6`cX{{FbthA?E>kcv?tuB&906rJ2TSl+uv(XQA zZFJzLGV0j3jK)l`))sB7wR`8dOT z-C4P!E`IH(hDJ`B{nkmR-*eJdWJVSbch=)CDr-*BDte`TRgHuZbZ+S{sz zhCcCB&y1S-cSLPnJFKpTUaY5mi#E`cQyc2%Sa0<|p4Wf+YJF3+x|26w$=yYCZVk~W zc=%rM-2DO`#mh#y7H^c%xkjm2CKPQTR2qMSv!5}_aPF?IbBVT=z4P0IV?=I(FJ6}{7p_6+GF4D^qb=2-NXNl zn-0vcE{uNj0ly2lZVg`#55-e>n%e0;`u6_?U%_@Gy#2#uG?I~U`hFo&t1}wB4|C_h z;H^bNzlZ?rX7?xNG2cpEIg9pUO- z@xzZ{EkRrNMr+S-!Yf~xS*rB1ZcM^sbC!DRCT4Ik4y}Bouu#tSh2V~5C8yz6m-2-If8@O!{8v6qBp}@^)VC($+^h=^S z%zc9%@QE7eZ#cAtzbvW%XLe<-MMZk%!MoFD=pS&)(C^?DoZK25U&V8J)WM?x7B?L1 zFJ|DS`7He0W8uZ{;lx(tsM2 zeLpLWg90UrdD^y3&P(Z1L9(7&N?;LqL6;rTKi|d6;UbCBw^5QzSb~!Vwm`CDR_n|bbc3(bjyeqkN?nul0Ibz9-jL(a+s~~bGB4@dF%i0 z6*DMPN)%(>-Q-N^-8DmUhlAM-(xqESy7U{KA)RA0WLsi}4BwhTuSA9fyJpCrK^YSJ zJ44#UXUe3wTXL{9Mv&v{?RP zdi{`vo^dOor`ML$+%Ki{Ve`^@YKWCi-)gOm=atbR31zf?R-P~Bb|AV;r!v~joO)`! zwYnX()_(CDXlI?O6w@*TUXuB?7UId z>bl!n%^ETn)!a&VowC$8dR>3svQozyHfnLStiE4qt6MGY^ftL-ZLRE8>znohWwpmH z2hG=|q6$5&Lkl}=_6KJT?dPHgYPs`h zBbOjs1CG9{o{m}5KpVIA)!|^`$qcEw$4@`_b9AGAn5FBlz|n{=Xdsg9G=ID=;5!Jv~^u(=YUPNw9cR-`swdtYzQ;*4xpv89%S-fSGVJD{D)qomvHqD{C{T# z{AxTfAG!oe_`l3nd(9l5;ml~x&%DZ@0C8LpAXg*+-x~RYH~gjLUb0PQqep;iF>uy7 z&A?l*w;;G%kjIDnPq$mGvLPX?Db%G)JQT^#_)WwbOg9PV+rQ~uY3CEz2?XTI5)WMe28=Xhd#u6 zbTPn{gIG5%Q}g7Sw`HKCJOlGTgT3GUr3Luy_k+)nKR`woM!T>GkV+hH3Zh;7q$d0h zUFWgCjLl^Iie+DL5uL`5gZKZjjlBfxNX7(z8O-PXV#jAg(|>n{x&c^iJsyuu5A=U; zdic>>YG2LsdftJrk39jNzuK{3 zNughH@}xw9RI*QGE_;%c_f3}A)D$_lC{4oRGh}_$EIHEhu9R8yP{J1FN`XVZM zeB*QFK%>Xv_TZuH`|p9AU3gy(H8yehY?-_Eo=jeHUz*IiFBb#uNzC^}`Qi^!0jM>1sp%M9{wGR3t< zrp#HMA^RR?$Y}g9>8uw&rs0JdeP4Eddmu$?Jd*s(&MQ_gSL&8}COuEQl;8<(q|A|b zk~Q&zoV)c=3g>>3GqXO6hu;^j^Sd-^@=Ff6=hLkb`SruN0$RkQpc+0G(tDSR=wGXg z>E$xTbyS}cdURLG|MTgfSC)F(!wRgm(Vexd)jHQoFGpGFrP)?`v#^zhknd>X-3>lj z>hg`2`ssBkEp1UsucOZ&{83!n{8wBZ8V&a&TCtbC_OvOd4^NlVIuFa~0=)93+N#+y zbeEe>`fiMi=HFadJ9Tu`Ycn~Rz0`VX75&l6T{j-Brj1WlSNk;{%u%YLgXWofP^;7~T$M`;*(1Go6|#Sbh(DU(NmSNf#sq%r8EW3|{mXn^x#G4baxB zlOy9uW}?*vIrN9R<*N|colTE^JXtW2^bUo9xBm3)AIGbXE_3c+2=!1h1km3*oxo#= zU&bF??}fkRS1MkYKzcsG_BL?x-|Lxmw~`sA;C$VQaP_HZ?{N0#*U0RJt3RTjNge1> zs>r^;ju}imo=RVn)6-!23Z{pLk)cjKY$m-&OHVQ{6~Ck@$I;}GyvGd5IX#&Jzv!Ht zh-A)v;k-JU#GAa0WcbYcZ@p8;pD6PGtTZvA$+EBH2fKDav9Uj}l! z2~0k`2A;eKJjOqL5=`zl6s|rD?HX)q%zEIm9*%y>UpA+Mk#OWk;OnlZ@ZkjT5k2J8 z0koK{)G0Tjfo}lEH~Gs|u(a%ces>c6#7Lbpks}AJ%R(RFbtl2zLL66bvMwZ(OLL3& zeZV^NiWzrc_)FF#V=4ON$xsY0A0Ydkz(qG^R8$R+&v*d4xsaoXf8;68>02N`8hj?> zg>_(THW|K2;QBRg;rhQ>C*r{P0f)H`)|uax;QeSy;hpko3{BBb?!mc3t5P?xr^Y}{ zv{ezb6ttLX=t`!w%e2NFd5@NUJ+F5)do7yz@VwXGuZb6P4SSkWd_U8u8}OMrb6pq7 za4$=auPFobEq!8dKb?{19r2p84o60xm9ekRN*wj>gY=T!YjaM1k+T?BJxE;9@Rn0! zS>1-Z(ITT9yB8`W(9hS@3zs|9F3ZK%QIfNgna}uFeAmP>Ln2OE>`RnaMN*mnk|8JN z-Ihb;vn3FoY{FK%=C@?Y$P9_xlqT(tr-)TRk}Qr*kbGA0k~En4MUUcSziWa_Z<|O4 zMUupK%*$>$Iv<{&k|FP>-Ind=$-5;x*RruGJL|3Nzx!Mo?|d#R`ZC{Q(KE4b{Zul@ zU>OFMww(-T4u33d*5%4&t0$6v!1S72@*L^^Ec{qDTR)P>`wy6dO&I2y_6x@#!T@}$>iTYQ+D+?>Fe~a_REloQ*Sd{ zFq@2wJMwABT?yK8Pnz1B>ZjTAI*VN2FVE!0!{Cd)_fUewMP^0G**6?O|S&sLEEa)FCuI6babX8hOHINMx zMeVf5RZA_$oTS*+mO7+}rJgjD(p^5K)cjUS9Wai)+;ic;OvOYM3pV1SKr>;ZIAw98p^PvtH~hYo+7cm)1)cEw#n=(t7N!wJz;c zR+GK$bgRF;x+ay=m6S|E{2?236E2cp)DqIH^;riI=--=|ne8zfwi5r&QGq zKJI#~b2UwvR$a$U_s~UcYG`LGPqNWH^;CZ^^_Wys1Ic@I@vN^?dU$JQNwRtuHPaUH zKDu|h=)zvApCeU0JGIc<>=wHBua;^&&{C&HwA7@-@NVj)ws7&GC#aFKr%VCoFP);7 z^gpB2+h~-@_}0tzH_CKh^1j^B5b-h|%}4(8Tjta~y1?HVvyU#2zliSAdCCRx?MJUD z$9lN>7I=9Iddq*)&|0{?#^cgp{S3Hzivjc{{YB;reBFeR)6il%bGr!6e$Sj9RJ540 zaQ1w+!R|z6nqFg8QWW|~M2Og328XYc-EyB<&?A|_0p7cy$wYhR;kv_Ja+L5g77RcW z2iwEZURuG^kIxI1PRsGafX`R>{q)DdGVEutR7SgLh=#tP7+jxqVL!Fk1G&tJOhI># z2$o8`Pu1hWMEM2FN^m}ae6PqZ!E&29Hc7kB<9R$MX7$fWwH<--9vxQky;a1|+;lCo zm0O%4j~rY_i)r#dmd-jZs=e#tbc)^G-HM%iV}Om_UDvo?ySux)yP2T`?CvfU6$R<; z5`4crynmd}qd%(KziW(&QESPPy< z;TinJ`F{h~Swo^Y#}&5Bp5uIL8K}cHbdx~*lv*(tpD#0eiX340`Ej)KGLB>!bOPh& zqMyU%bMd?#YnpQ}GQi5BLH!{k9?stMHNMYFygmufGsY^938ox5~OukUltn&P|+@A>t2hY>#qhFsw zHp;gja-r7`vF!C7-)4YZ{qjW;&@*Nl@s#X)FP-JL`To!4cj?!X`0pFM-fyMc zqj$17;yt?GM;Wp3v;2p#C&?JeA*e! zJeer@85$|)Vk4#ekEs7)rtR)%u}_PVG&bYoXgTH=O}2lO4Br%sb_%tI)fE^rSy^OhtS+`~BhZ zUu9n8SDC*nKn_g$E>)HVO3R(U#QEfJsnH=^4#q{wY0DTncP>_{gvE*7qj*_U8}B3d zes6fPB#uav0-7nqow6mqt%)Y#iJ6$5>xHq_f&;Df`+F z`8#W&t$xn2(@WTge0n>XH)}m(%>kp5@8h@N#Rycp#3B`0z zKnZR6x|F&ODx*6$;B(wuP75C@ubX~VQ2Vi!bbbCR`t(^<-Tz;8ZEu&CDX?u8`7%;R zk5r(K)TW-k39F~Jhw5wF#QGY&rGa+3MBZbK#_GL3FDD@6Knooh(pqPIZl~8bchn0N zocR2%nz^X6E?(DJ@7(IFVa!VEUAK#t=+Q-I4eg@w`_azvGCH$0Wb44=@q57TZDhZ! z_LG~l$l@IdcPB5Pcw;|VSk@1H4^E%z3+DOC>rdeN1G1sr=rID*t1lS5^IKj|HUyC;6}k@5jPasoWRkmw_`;PfjWlEuExM_N%sy-){z#)`aMF!|nd zeClxar)Vt)&`oYEB)1n#&!T49>@l1)cYI=J@~IC|}rYcc?yz5vcY zun2pi0?9Y`Q+d( zSLib>Kb$#K4oc!I!<^we7*? zNHF=UFBk>K^@ij3VlC*InVZ!P?_`$HNU+wOUiO1v*a-0X)^BhW42?zmaArFShHno9 zyF<}=!0l%lU@TnvG@l*9JfbtqtQcR&Aj>$0Pf>jKB{@eteq%Ym<8=*EwHfnAI~XLO z8|OUGAp6G}4HAEOBxHvIiSJHFdp^pe(i>hY_LjJYD_;QKr@l-+1B3A6Eep2yb?e!Fy}muV1M zQ)jL>n!Cy5denMrpzl;>eJH^inL(CK5!Q*N)CbCtX@As!x7{e?=>ZLjHp=J$?(+Mt zyIi2Az3rffJjepmse#U2?U zZw1Q1Q9mSZ!#AP(U5dT@ESF|}l(8e|@u7~|c=sEr@s3=@UvI@e>z&+o{2=$vew5o2 zKTE~6U&JdWK!#rWfiM4;1U&gI%Q}Qf(60#TZ5<!A$4RX# zapL7pw${W1xjHIA4yDFRT&o0Gb0U#*%ajNCxStUtFFvydSVhX265--oF--D(43$ZP zLdoO*Ez>#$iPyY98FKNvlqZKbawM6($G%CrqSNn3bMg4h-;?t_?Jw_KzKY%J+_mSO ztRM7Ew!RINNu$UR_<`Qv9}oMw2r1hyN=~q*jERkr2A^W(gj<}vdm1m@$0myRykvPE zohm0iGGy(OKQgCqUZ2wMRpvU(-$LKVTj~RHVji2==!7U6?S2bBq z`DI(f@T7IQKhug_cB_3ayiZ3 zUS6y8s-X2pRn$6VE9*{j1I9P0uC8Rp#Eqz>g~$erEm~LeSFfiV3f0%YS@kvaO9O3x zxS<}c*+`u`HR604s8iJ@nh?`egI6`vRm@G=yN3*bfOfhfq@#8VaMHj<2Hy}-|P9Y5j)Us=45jP-TC@^B&jbYS-bbe8RC zF*CsSL~b90<#o|u0(spZJ!a5cU&#dP%ksYa+?L=y%i;I0JCY$#k7JgD?-yjvu!Qqx z(-VZ&UJUO39gO#6>j9pZO<;~FTs|1io{AJ(7x0pd z1-ePa`grOafysCglbWLagWsE58sutQgA7vUO}n6_^yPNALHfaY{lW3$YYp;wKOFu% zxP1xkeuUeV1}Qs%?*^_L9noMoAAbk*8P2so>&%cy^c%2!Bj2qapTC*!8qYfQ0!*KX zS3PzGy{ptaZCatjIFV62gbZJF@v%Gcwp^!ADUvM3Vyt=a`Z?{X0e9p34Mw;5hnnzW z=BjcX)8CVMOK4F$`ZG7_l|iQCGavU9f2p`jiVw4@>w8GmGaiz^jHje*VRmSSr<@$( z1xF`8`MZ|{`FqK`=H8Ol@R~R*p^t%oyQ|~rwFvN&#&d7br*TUrZNJUm=9V z9?4_+h%V26CfUzlN`G*9j@<`df5-ok0C9TrQ~FH|mY?N*OUr+PC2>=b`0n~8)1L;) zOG~^WPru0IlApyf`Gf49`(Cd5zLVEC-$|Xm^m=ywAf~JEk>|&Mp5!k(8U;wb``@L* zfuFK(PcX9`L*>fJa6T(k&P|Gy8{-otXD)p{i<0Hx=p=ErNRpn-lcYslk^}`MOZ6Qo z^7DL(lv$J_eGa8am))r{>T)Xmv?)@QxzHC9;$_#`I61d8R&G~_<+$$(4z}d*GP=^Xd0*wU)mK^Y^s5Yh7a(r)0;I~v0O|ki zyHtAcQ(jvJON3bnbIL-c0dwv~qQOk9&-DUXj^pfN|@vGc7d{pW|8!wb@GF>0B#q*VbAq{;<~Z{cW`RMH{Vr z!bb1*v(ZUpgRQ)2t-rji_3CSDJ^0mHci*?xLH}CgFSpXB>#X$2B5UnZ##XIgR_T*Vmf<4RmH)Lv=`Do|1oKy|ufE zzOT_#17|nYB9$C<2J&DZ^6vgc~v>SAnKfL!k{M>Cn`>ekvb0=Ms zqmJac$I=hJ$6F@jo7_U?$JfPP(voa-pG}@(jD`b_@Q@n6+@<&|a{LOpOW1Xz?3_Wi zUjw7uO=B+e6L{n?G?T^X)NtHvw2TBWwLTp88XPkM-fRGali;=Mz~twD&|b_8vJfmB zhPKfKOuk;#XSqj_9lU3kX6iE#I2=*NXh&>PA7N^(1w$Ip5G39nngk>i_#$sOS6 zU77LOi}eJ|&HxAV4>U*^+kb;O{xE}hk21(taQZepeBpfFyP6Ezod)@RhWFkv$f0n9 ztV=aW?XS#~KE;eTzRLixKT?=U$2xPh2%dE?JseA==;nS}UfEVT$d6(Jv_DkW5grhqSMITy4uP$0u zhk(2_aC|@35!RR_xcS5lxit-U$y~=AXj>17*ythq^5J9I296hEZs<-giO=sXH&&C8 zo8T?;2Hi%PcUcn(uj{zZqp}eU(R0!mi#LJF8n54S_I1G)m&{5~x}BO_m$AlI4(Zl2o0PD5Z+U%hb0qQY17=l3PZ~ zGjeqs)DM-`KEV=smbufznNPaoyX^k+U5@nsA@k0orBi=>v_DWjJ^d*s2L#FW-}ITf zFe7hQsLZ|>CT%{2OU0+G75gKlZs#a*MjNU>HCmG6qb15YMkeo#mGWFm4^AD=oLu=yz6ndpy`a#72iNv(;YYhDEit*A6@EwaJxy>KTz= z?|Bx|S^h=z>ilAQ5-bn1E}?E8N@zuTk&0a{s}Fit(D|eAoByt?-IA-Q=c%fic&D1W zxYy7TXe_zB`>`XQMCS(DaZy91&zubEb#)m+UTTWC~y z`u*Ft(h=)g>(`2H^*=IpuiojXR;!)#VUsRe|GBd+itVNonN|1UeowuZz*@wZb$eNcwHFfjgm z3AlYR{O@3Wb2OSWXf!>-$%lFEBiD>R;fmy|BWUg1 z|4If}mru-!q~`e!Twf2CyMh1xVz0?AboMlKmpC~3gbCDCkJ1B#GfSNB|h zJI~)^jxe*zv?Q}_-g)tVm6~aYr!?&7DO)`~ZfK#DfP)9m)+1Ywla5f79J9C^uDt}Mzw<9g3&j??f3Ba+r{zCz-=#;MYE`a)&XAr z0LK@@rLg5ltJgaiFKFO1Ub z53{a)IEPK>KXCaIe8wC;*S`e3Kf_J>pabQ9%=HI)e(v>$=M`$P>(GIQ;q9!2MwCoV z^C3B4Cz$sPj(g%|+<_1ApUe0XZ^PBm%V(mI-=%k|8h*!_wej3fpmuu^PY(Kj9KTo9 z&0I%B7??4R#`4%G>(pK9F<-7y4-fhH$wOL>;qOBB+Rx=)vakqV7UqSnZ_YK@L$2Za z_{h*8=8doQmEyga+0vfe^G-LUTicuPT(WY@+?FK!yYh3!eHp#)q5P#kbbPaC5^?s0 zY`gJFjO*UY_NgD`;mEZ7?3FAyTZ-ur%3Z5sj{nAns^jS7ne8bvhIF{{98Rs#t+NpcQ@0k zqjSWs243(Bf8_bJKk~8eAF+LuB?CHSNh41(x0+_kyAK&s>s*F3ev=^+tun+SF;y1! zOqTtJ66NWecqz>_f$z*H>SE#Y;BxNz^i4Vr`6U)HzoauWlY-KJN%Lkww1ot5of9l0 zn*WxcCLyx#dWaOC7AmHdr~!NlldBuT#j|3BOy7lVvD0ZG!hcB%}xk|qnD)30=q?3gQmW$jlJ9pgcd(nK>&$}-bh3(R%NWpfP%>;12q zf~lEe-pN$oEHKkk&CNC7m$_!SS*Yy^w3{Z z2l=`&b@g6+eeJZrq0VgHSbG?nXy1KJIj5#Nc}sJh8^NrjDJ}JDc1vCRyp@*v+*(uO z+GwMcwkme*)sj4}b55ccwmRv6!d>*`d}rOhqMPn-)I$qC>8Zuu_vTmw)xJ$14fN`z zb)tIe{FOcR*wCKZjoN25^p)216HSAc@9R#FDEwqp3+knH{Fvd1FUHV;wl|A?s!Sq_I$lP6mrjEX{4P0+M1CIzg%eyV~BfUUN zxr~-_o;v9nU-^2RS#}3F&UP}@*TB!gbysjb1C4!iA744t8Lho7xZccHsx+c@iYC(x zj6Yb1oL{#7wecd|K44|K;5c>|ptjBjw9UetNl zq@9vE@Yh>TU-6bqvOnfndrQ^{FR4}5OD^GAKb3?2vf4wM74?u?7u{uHC+3~SpzEGB z%5D76TU!|AwT)5U|3LfjgBydFt-#L~Q|M72MEwyCT^Y>Y39tSSeE$tTCxh3aJU6&K z_zFJ9@t%v_@V}#XL~uLO1q|i6*KmGoZm+XGIDoHau3$XJTndgq26Ma5=DJ`Rbx&|` z$bNYLG4vF+Bb@Oj*T0eX6-560ceY1lH@+mh*A}in9ghEodNOOrumfCc zSQsUfnNypS@U+Zvm-%=SFEd;2Lvc^3cHUFG+j_|pw3W9DyyZg$dKS1&JN2KB#Fivu z^fowvXLcU{Ns9FSBukt>$x=Lz@5g=_ z7!!RPWuh)8O_}j#rW?tEY&+0O*G5`v*bL?@eY4a3CGzPpGTU=C__NLhbwylZEjO*0 z7JXJik0h1ST_4M+Zxym0_mtQ2k1A@P8&$N~iM&ilC;Qs!f4sK#cB-RSYSh)PW9sP; zdWK?lHq_aJ8|$gXxmey(Ym8~GPZM%=m3I2`b{jn&&_;KG;}iVb>c)-j_0XRVdhLEk zZP-F|NFUV`2~KKRvWupFan>D;x@*wI9$IT>Po4a&ms;=dqp_=8wOVag-DKNGJCE&6 zMtpA#4C!%s?;V#bjznY-zD6T`?@{0z=M0hht@ zhhTYGBQ;Psde=+vaxi^7yxVyLendETrKR}I7n1?N=7zo!02iNk6#d=6eIGIee3^~G z7Qu0zfboIsKaMq_@Ot(`Z(o9D(`Ph1e1Na??ZNTD_R<}}do-ELVEjjJr|`ILC$b1! z&^zJvLvp!2k2^LXS0*2Nd@%k-KeU(KiPTT28l!EYZh+7#?wj8;;#uR;C+H%kvT$j>3vBZq?3 zY#Z1Xvy~nOwhw0?Fude=v=I1sP5AiZg$8-F+Q4-TxP1h!f5jlH?xUl;hF?EJi@$*{ z(Szf2?eO3-xhHG_j$biyt>BIR0zbEWM7{KlLHd8EJ{!tw!K@XpsGoAI+`OBpf8ooV z)4-lwYcyu2K=C)W##?M2cuOqn@jOR*9nyWI{Y_som+^G9x-PD9*QJxk4T-pNQ~spi zlAPstq*JYX(lPSB7+;Zx`}wh?T0E0$%%wOTO)t=`x03wxgG7zjBOt$>%mnF>>!sGEAIyX#~ z+A9;}pl7U@8KY&;$|$m2a_85DN@2SQY11`AX5dLbf~UqeJWOhshKZppxPBo-;)6q^ z-rP_r>K{su9p1{8p1ip9&FnhEmqd7{j! zog$|%rOCS%eAks^wI9urxC4JA@V{(XvMXCE9{eK}H)M*-`wS`IlqK^X;h%Yt!+B*& zg^Q-@{M}qnW}wxSwb7Z`w(99;uR{hp=!En6b$IiFdaG|?JnTjF=86)UR<*R=xLj6; z)*y4SVr30HPEJez>N@C44Xu2twl+KW8>Ivo2p-P220idhNAJs}9<=kMLYq^||e&W5bv|es$wDS2b-Q(=4vvc}r+VMVWHM)YkyW}rT_V#D8{thrRXS7i&H8P5ql~JmI z>%sS^ZJvi4??7i+iatFJy<`knJ`(%{pZ9Zr=Qx9`MB}bEiPz!W{lM!`wxRI*47Nh- zlQ13K<3DtB)`mWd&|+2^By$7T0lPR3SRQeK9!ei{aBzJ5?>rAmWpV3}kGOrEX zwgu~Z-$fH*JI8r-ddRiH6MU1re(o)r(Fd+6-ZS6nDYICw!P_~mHJ=m5c@<&3iD2!? z^;r%`ruTo3n^dfxtGmF%Q^+B!i{1jB-v--5sFBWX>?WJbgX@`jnEirYA+u`qPPO29 z-Z#Dt{(JU62CnDgek6FG38vq!f&R}rRKkUIlC^Ts3hL5zJ;V#GdNw~rTn)}K2ve#wZpX+FLHza%AO)*&AlAB4ld%Y9i!5^i<4S$*B{Y|dc`z3+o%|34tB@eu*^VLt3 zN}-AJfL{3JRZ{+kC)dnV#N%LsOg)X)!z@xt%nX&a!9nDE28zSOZ&KyWSMgo-h0Jz; zdeuJ5`~93s$CjcL#pJBH;B>dhTDDshf>CeUs+;caXW>+-k17qRrLw zum#v*t^2N9=+QD3ntIk;=ae>A>k($!W{auX-#5{c8SwkQIkNNgANdfJDXSl)OICR9 z_luVz?-Qih#CW0_W2M2*7&+@2BYtzDW%jTrDVP)?g^GsDs97Ph%=EXMpZi-9`MqY& z2mh@@WyO@=GP+Z+gqH}G0s(nm%9|FU67wlStmZ{ap<%Hy@LQae>7F1?uM@?}F_~HF zDYCs|sywNhCM6xxCGJzY*f?g$=-27exI^0i&goi0xiZF6ZOeTsMGDL8I0Yor-_8tKCMjkUn(CTdp5QMZzj8|>6V4~4eWu2);@ zzi->>+mY?{R?5qWfbxr^`bX!~>9k<0*69Qaye6XwTyYH&=kGkrJO-xB{gm9 zMZAsRxtAUNN9Zlx!+mAad$1Ee^B8Z-crdr$CUo`Hcv{x_O4Wn8y*Fs_U}@AcU#T#k z9;10^Ckw!T9#7{z4bfHR9ERUtq*m(ZE0)j6?)sj$Uz-RpKLF1CjCBIuUX;&p;h6I_ z`^paX_r^a{X)>QVin=Q}{cIp>z+g0&k?`_KX!^66t3kcBIcrMpd9;6>tKE}N!!<+D zAg&S6Yt9zqoT#N<4`hDnHS&AckP!oCUk0wbkOdY}iR?%2zp6oBYE>V(S&keSxcq&v z{TbNpiWlY_JbpggdT{=fnU7@h-rTy`t<*g39%DvtDqi&gf4rD2;3Z|sdC9--p5y>{ z$^+`9j%WZ|%iy0Q>#K1;cTp>MIdjh_{nr^~5Bl%T>PD$ek5c>=S z@X2KcnF_!DHXmJM0rTtG!r21Z&atgvJI&UL_e=%9$1g$GUQUh)e0(PRzt{$6Mo+On zj&2W@zwrcn!RZLN^<+M;WD5K6*(0;iq@(%#An-cCAm-qEBA8wG9mfH~7qSJjRp7BR zw|~L*d0>A%U-&+{jMY}^0JC%Fb{eEH+K)pkY5-->WX;oXUe=zsnX@2RLQ}UXYP?Et9GQxm+vXk_kE%i z+#APS>1f&hC0v@036b>$gXB`(Kw0#ietj}rPT%~(HL$<5e)L&_v0u!WXYO)k`Pm?yaGNt;KKhm*oo@Ua#o~arao2qZ7sovUT zrunLvYlG|NI={1p_Cr_x7-gYuMJ%<8i>3NqwA2PYm?h_Br5PuzG^vV}zB**7N75|R zUoCY0c60sk+e}wDndx?TeJ3YVJzj!&bZ9xhopWUU(kywjJwq}*)1>m~6j?qeNq&*H zTWLT%b=p{ogU84GjgWPZHo{A?f0MFiVb2&ym{KO?1T?u0gh0XtFn%kD)etr-HqP&UMi0Wee({xrH@h zSW&H5v$!7FT2iOaWcDYJ8vTL2R!3 zMm8bWrLoRQYOGJ&Hqqh%P1N%Znu}dCb)VK;8-$S4GNF|&Ol_?dmbcYzU)$+}6mnV| zI_j~hqAP1S>7GiR^|(b>{ZqqPN1b%m0X1B-eV=Z+gW6}gK0VcYXD{7wthf5@>7$1h zy6UoKeRY#(UyX|Ds|n$K_4xC?diz>mU0n?vtV%urKE)Pj=c|gLz0mhx$CT`@czXW9 z+g0%B?dQ>2z-F^W^ossN1|t|dc{p0gL|^ehC+P`S&OZ+P=5aF~-vn#d!nKXy?c7~x z?Z@dIHBjTcL+=r5#Oz4c3v;q#&~|2JfYCo#1Hknf;Cd3c?tREt8o>L}QOA<|+m|(|H^*!X z-lNHsd`Py-vj6uwIx%ay8=5LxiLO3k-O)#iHusUh+T@9W?Hvp9x+VU|Twb1q1`DTO z$$iJ-%sedsw&R-#TyRY;S(D|y(OVvrMuRbW$@XquQkyK^0c$+Py>_nWnVRVU4;dEh zE^ctifO_t-CWP74XzNe$!c-EYRA#P5sdVrYJiP|4A2FbToWvgpwol(l9}jxTI`G+o z?dTS?nN4^J!R&bIm-E;x*YiA&d!c_+;=Se3!n+=VD{~C1OS}gx|8R@@aP#bsXz5`0 z-#9pV7M?}wwQI>TIM4m{$s8k={Uca6;P6v_8D!57^qFs*#~0R{PjGoKedkkfo8w)- zVvuc|<6+jG2(BR>xftY6Beb332C<``DLNvY^_Fbt zM_$XKJF;@)T`4#Eo=iG*U)HaFCheyu-~S-luAgN%zCAN$ z{p8|Pt8>3)%A`oieiA3c!jfeU8pys288YxOHOBmzvMMb@epqM7$+Bq@z6?*{p#;f? zzW&eFD47%=CO++cOJvz!(q!!qNuB;pUfumFTQ+}@235bvh{x&}*>^uyW*(21NiP%SpE}8s z+$lvmyQhjbb>fg!oX_qY`NQ>!N5j0{r3-_swQqY{ow3kf&G4eDe{SD@aUDCNnD(n( zLW}s6Qa8JDI=DbZ{XDp`c66z#8;sR;k5w(r&Z(`<1M2Ef`h>1eZKUGbM89qVzn?YL z$DU2qjeh<&Kbz`h4@YX5%`~BW3*9`wrG9$ZO7E0uqZP+e2R+da+;6WZs&~|+(NbL#C6xV&OLR|(Ozl@?5$<(;o@b%@`C-CXWfr% znEv{>CRT!@YWrkm}d*Yp&*yd03?0ORg0v@5EQ0?0-|qzGH^C1{UO;c~prbX|Zt5fUaCQ^)m^EPeIqIhkcV3es zE@(7(;X0wIn>NK0_sNTlRWJEank*PUe2s%Wi;c>LYN0JTBmi9MD0kjTxZ+I`9ef~Lc5-z;tEF7KNj^Omi!)P*KX(6yX z0!?MaZut3Lc>MuxkD{5JW__!Ie@>wsXMCUhBWiYeeT7Q!HHeclUhX5&m2ESh4UvlonZz(n> zLe3Y6lQwb5Xz&>l7@Q?L$dO&oY@Y#JvSmZJY-w;eOA;GpNaR}h`-3DoR3^7SC|+t8 zij>c`p)&DOkbL+YC_7eum&N-7B>dhN`O)Bu=Y_AEW}k^#dkbX!RzRdbW&}9`2mm zZ)2y~y=`=7LmT~omwW$V8%<5OQR@k|Iv^{r|Gvm^+y7;(q?NYO`+M<#*S6LIpR9Bh zJbuSPD>bqfEP86CV~XSThVRd?wNSq^W_lpYM8hurzkYp+_3UVxG%1oI-MOZ)c@o3- z4i($ik>VK^B`pg?OU=dPdu@x90rw*0%%lkEJ|jYcFGWak`$$RO7b)@GqU3O)XlZso zS}rz*P3SNxy>Hq;(N3Kctv8pHM>W%9mCP&)oTU z)pW$i%35J?Rb70ty0!_gsb|Q;ZN9Irc359ulh-uVPyaO5U&Hh2pw(77YFm8fh37hI zw~o!!Z9;Qhb+d&!IJD9N4O;8crfu|j`?i`mrk#Fgj_BOX4(hmE^gwGT-7lSW>Zq=I z{DrgnO?A=4?=G5fubVo@ch~$~dg?qwFCAO4kKSG5sv}?Y)eUL=^ltY7+8||swz)V! zW4`oPhi(0JFrM>j1^lEV-29g{^DfMoTbGTmFf$JWAHGDlMhEW<=WdODU9U0z^b&Z@ zZPC7S@P38l_U8MDc_w|EHPAc2^$^~7Vj}uCJUV9$^;0mt>KQTuyukg(VD?wE^H@A% z==JrAF#i;;-XV#4XE0v(kLVfT`fxw+{}T0AaQW31YNq^uG?|j;i988M_u_n3g4Zn% zqS2p2&++8C;HIxc-{pN^dyEhJg6pqX8-8Dgr?XC^^Z3pxU-{7L z3*DgDWTQBBFv{t2MmdfS@-iH)1ulIU+)M$F(|yoOz|S4G$rnI3na_O}uzn4=-2_c# zF&G}s*7$@$>VWyii|8>%bavk73g^F#PLjboaTnfwHy*tG10T0GN?Jjqn3d$V3>gMx znbpL#LK!k8H}ZTR@coIoQ5>?-XHxMq!rg;H(aL|IwV=r?<=k$gqnAHLeV1#55+VI{zTe4K9k!MUPzPIuf%K?^Ot*nkZ-*{OH4ofgnhru8rPrlc4)Bl-OCJ!4v}bW zc>5M5Nvn<-d}lMQGy5<7X=H-u$7eDjuLp9=W@?qkv&1$aUD`O%>(e?(4u6c31M8z? zO}8*v7#b|4KmQcVravTb;5X@f_$&XfKFB`$@drKnF5S}tUPae{oB}UzRC95q6j^e)9kcKysg@AvDIT8Z1tAC zt#(bY(RGP7+B(BVM}4=^hz&MsL%s1VIC(V!F5kdHPb@Lhn`WkZcI#i6@0u-V?q-VH zy)@}uD4E|VURTj*%Kj4=+j>iVy}7Qg18Ey?vN)26WMx}y3dwzv+tP)hrz zl~p$~TdpQn(m{qQnprB(=hCr%ZJm)*M~C>=(>Xp3wCA=)+G7SmC1M)^^j9_qyw>T0Qmg)n59kdmlYkvaj|(&`;Og>94_xDd?OiX6yR%Qd>*FPzK4DdCYJ|C-CI$MG~s#r z@*}A`4g(XXbNk>U_!p0MQ5u|YPQ9}y?;VW>GYicH3|+I^R|bITtG(gQ;Pu`waO+5X zjOo5|^eZ?2#1g^V&#q;t!&lj^29i}`wj1TzTYBBr3&wnn2zi(ij*~{$- za>2mt++$b0g&&^teSRMgJGVc<_CPScDWCc6J^Q|(r}aGg&P>ipsjZf0ZmK!^$I}1( z9Z&m9vIp?Vgq~z3HP`9hlgWHUlR4hZhrTN^BCGjG^$h&!)I}XPFsl?i-_RUCqdh(u ze`eYp$D2OZTkcfwmYtuyWX2vZF|;6y*V|KiR`itk!}!%}cu4SVW+F{+m*i4-8^0L& zJox!+BYpQq@u_8$;_&4yaOjso_zORPm1red51EVk2z+~;iQE!fIFP2to5-{>KNo7VxGD}asL3mDOfjFM8tD2r?37pYG# z6q|Eh>b5mFmr7(A@OmUZ#U)_-QgoTXG<+~I9Fz09^9k%mds**?mcwVqu1CiijgHd< zecb}hh#nv}vSw!P!M8XUui{Ync^9;Ewu0lxFWUikzeDChC_S>4TnkjhAJdv#$zk|c z)>5nWMswnPXK)UkT#V9ifl+px1JggS{$$}7B1iF`&|IHOZXXpH=k$3!xI{jKo45RT znk=7<{7v~c7+({8?MxZB21tVyKV;X%U$W)RZ<%EtE*D4R^DvK-8ySfb z=b9!@TKtg(rY1Vn1V2e{bnK(d?s;LV!81&?)qE56ub(5`XJv`go^-LEnIga6B{2Ig zkGBpa-|EbnyxL&Bl0U@u<2QQdzR80E-z9&-4;j7Xr<5%dB%gi;%UKuZPMnI6TCZc6 znUdGvFFP`&AsOUeLrk>UW>a-pXr^cWG1oVJEY!NOrN$Su(#lCzn)=;Zdpxw!qT6h> zQe8XEJOGYI+o>tN^c(isYnya?ecw5so*bV~KXKc@G@rinvezy1>Bs3|uW62WM4H%Z zrH=O6w70$1?QX9f>)Y$hf_c68e;U~8v)R^KF2GW2jkC~Z=rUIWOx5~0Uh-WzGR!?o zrq|ApPo2}`Kv0SVox?kGi43ogiSj)&L9W>(ko6fa9;{axYh$G5<0$Ez9w~=cMad@j zXz7;}Et3aC%bF{Zk~S|w?kDQelHPH$G zB6I9=dqWp7t8_$cRc$3TbX%8N%(AGX7yj1Oj$iBRhdm87vUFo@)wPM57HFz=N1Li| z8%I4~shQfKrQaIRl4G>fNh@3HEkkQvGQ5p$?bBAHm$cJizuN1{6&-bdJ=O5%PFiAo zXZ3yCMdM<-YQ^8q>Tc6bM~vvMTZ4P()J?rK#HEi8Z`+sS4ODl({<`|i0PWUhpt`0H zP~XM_bY@I{T??kR2g|EwQHMD9M3k@7z-UNKx z?#n!&w`}11yfC=!AG~43;qufZM|TB3dH=?V~4Mg=tL&(0eYC|M=G?7>v>o5cI#e~D@F0RCwt3* z*WQxvlDD*7=`C%#dCMkqW)I)V>p?pD%2P_$#Q$={LjtOLFk_xMXrt(DEbcB=Uyafe zOcc7Da!igRYeZceO;CVan+=XL|MLX%7&Kh7vzZ1u|1N7>#eXVCL+vz6dl z!KyWDMpH1q4p?5F8gS;2FL=T^pJ!Y%H0B(-?=eWV@#rqq!TezA znCL0S1@wx-$+HKrDfQ11@v=k^+9(kFU|_^s9ra+g?fNSUzh({-4OF|vd&N4Bs2MzJcOSckKPs2f%m0o>4)+v^O1y_K9$*3o=X_H zh_^p6Pw2!uDed-AR($oBo&~;1-2s7e!!tZ=^TWin)D_zpvQoWcpTF}ZIt;SUU zp{}~ASB_L2k|qCE%aG@GT)XT_lS2o|+Z{+R>!&37ZkH%wVfb8{=B;_@3!3A)MJx*H{T_w&!&Q8Y%r^=+UrKLRDyyG2 zm)FjT71iCfimp3SP4~U7p=qhLw06O|+BB=4UOCu6EB|fC42{O>T(^miq)*gtb5r#j z=cvc`Hq)O%ee_IAo%&BJO=sSm)4bN2e?%Ltu%fM=4r!;8cXR-wRf~R5{WG-__q%FH zfv&o#kh6B`<)X*$bki9VduV3wUYc5^kM4Nys!=(8wJ%!w)Gqz?-sS#kcDKK7Io@9@ zuj#LeaODGOU>-c#3XS_l82J7JtbGIKp=A`|y7kpE`hmc|E?{43G?^=pm_u=gIYjU9 zko>?a!gKrnGLHycEM6bJjow~xFl)tBc=J*;7ckiJ6xuiVJPJ&22&Vgoz}3NUQ?UFb zn^hvX&FA;xxx3*!{tjmclZ(Q$SFqnCbQn9crDK3m$`~Y!|T;5W~w4x?x z^M!aFTv&o0io#_J%2HHOI3HgFI&Bt ziQp|yZ+gkgE?#o=nx}Y{!~=u&5)KxK008p#7V@gy{pEnssv82bD<+5{ZE{ylVxT#oF?eQ?~&%^*{_?aAXUJa2vNe0V2%b9#gA1C8=_uu(>^RU2TG*j{KbU5s+5E!pDe z8~New!JN|odoY$7>H^jpD|mlDt{IMUE>~D@QqXt?EySx+mg|EDWb9J^{8b5G3)xy} z;Q2_Q@2F^=U*##iLbt-`Ep5QD#?lM54z1__o|^5fNf($O$7f9X7q2J%sS)Me<;@f} zG89J@_K?&6dB{V5583bJDKl<+iqk08&1TH2Xh2UeTw@h~zhHWw$5g*A)r#DZqwzQ7 zz4uM=9dt|fdf$>_J8z41)4Q^^$9-v5>Y+^d_(+aFej=v}GgoLC^PA7UmTq;J#q9b~ zLQKBMxnFRy>-(wk(-_biRyB2yM-W>fbu(apb^(NoD> z2Mx)qA7)*!(9X}zH9Ol(or;?2t5_4wHvKDe?qx~ovFT!eCz;FybagVgz8;B?5Wi5F zzT&scPYRMYe}BnpvSCi{BOm6|FR?cZlHptPa%;DZ43TIO7(P11v6d#w()4ucKQ)^< zP9}P_znKOcFxLauEY#p(shiHy3xCL3i*K{ho{MaC$1wDihHz{+dG?8Xno-+9zaMwd zTV?a>s$=)-r3y>O`Y|pnf^n5 zORh)g1$Et_#j~YrV3w?Fmno&XrAtn13hOBuH0V=LPR2^7A#w6>Fn-Aq=;iz4Br}Z6 zGBPD^pN|&rb}{m}BG)YaqNTyiXt|jmKl{3P+1Dgd0xBfSo6D(W+-FG2$}FzyGUdO* zrn(m&Pv;~{4HFxUCFASY)O`ACTb`eBf0ZKoYfUkom{mg8EiA47rIuBT5f!wL0SzXt ziY9lct_P0P)b>s5sCWN*>UF<9S-TB%cE3hCaRazsr-}ZzyouIq)l_%3chojBn(4cv z%{As)3thXnrJnBDO1~9tt;HL((bc=#>if3s@sf7XtE)w?mv++6dpl{Fubs81Sy$aV z#92T8cG10OyK7aqp8Q^}I`euTb=>2sUB>s-m-hX1-^za4;%Pr!9okQO#q`rB;OQ9f zG*{mq2KN2?3mp7}P7OAif|dQ?$JM~)4@1CG{=e+B2eZNOO!)aUe;=s^rZS9-v8@knpe+TR&Di? zBUWUJEcK+m?;+N6JpR|)_+fLNN5djHudlw;VKnqv^p%3Iv%t_Oc<~YRkp_wQ5z)VQ zgUctu^cUc{4IDNX&pmITYoomkfg{fb&%dI#+yc{^z|q_C+H=6DAmC#$tnb6@sT5&|6yP;rFKeZc@G{b2g}nzQU*26z-m@ zm)vVZ{dOfiN~}LCf~bY2aGepHr@>Dhj!qtBlsC+et7~+Z0X818dmO*tD`rVK^ILxL zl<=iq5(JjF`h)NM*)=I~mKm};;R0L8H{W($`tQCWM|R(oN$YRPm$A3eFz(=&zQbqV zl0AR!$;^HarFYrKGHu`!iLLoej-<{Cmm+y_A_S6-_sdV$>fhTJeVWT&X{QLEK`kZZ?2!HM+PltmZqhZPJCmjDOD`> z*CsIDnrxC{=BnFFwI4m2h06W;-*Fy&PA2y%UM%XzNEP!)sW~l7!trr;%+D-|dchLl z7bK~Bg2Z%V5Nk`2lrRgHB5ml^(54Nz7tQ6Nj;XWbh~xjX7YZ_eWT0g^iY4 zZHSd#A7HJ)cv*^%wABXv>~s`*`G?~9G?on7NO<_1Ci!*Tqx{UfFQCpzxifzXY0*;! z)#z1F8@w;5-prDiSfP;4>BsZ?3+d9RLRyRb*(0|L>#%Y~)M_ZT#f3#QYHtzdQZVD~ zdLeyhT~JG$%C8?6I_ROSSEBQsY#t zM170?-)~a%QH<0X5-$gD=GCFkMKTBVTe`IWKbEdKE~@r>(%l_`ASH-|fP#T~##RKo z>$N*y?9SKj?rvmBB}~8;u{#MxBt$_F{LOy%_s9J#EW7vKMVV)wIdkS{SIh2$H6klj zHI7!#wP0MMgJ|XhynA4PX*ot1u4{@_gU#_U-4b`5Y!H!dhb2QC(f+Ozj7sXFgKs@t zpXZLRrJm5f>doJkKN@suh%i4tJbmiV@7eqRFc7KQ%;!4S2;;T{A#-;yh9-pIeNkin zJPg-}?c2tL;qlz2NGWcH$o(zQqE|~isBDGlD+L$+0{Evbwlha}hHnS#xzQ0Vj&#P% zgAr&R9*GJ4qj0}jH`uy#hfjWY99Y%^ead^VUyAtNttY&RaZ0}2jaZsU?wmp_)qg~8 zOATWKG5F3tdJmV<$2gKW3F4nCu~(CN`IltY+>)h$T6)b#di_`<{g*hX^uoBcrhla; z>z#bh*_q_)tEs8*JQIk?i+J8g#B?Rbj^nkv@<`wT9_x7@{dphJ#9_nt^w*HjYZIUS zZxQp!tyhzaA4=x=6REqz6RUZg;jxIA-iVlfiWohFYrt;a|88F63D>9FTsyM4X3eOg zXNNk|2iAZ$u{NvAn(%Pe5c>1y`?-F_DAxw+H%fg*d2h~stkd3N4V9i4zwl%+W`ELE z=EF>6@94*_%!08^VjVqEl5bH*r{?mS9_X0)iIO)jQ6kvi@;Wa;hOkE3@ov2M)1y9~ z{iFk;;-vTud)8+tn5U(Xe?L*TPNJ7_J?GQ2M*6-(tlXxa{nCmVU)0RKN~o0+@18#+ zPCuaMgq*nTHF{x)*}aM9V~OXpiRCWTU0$7`md>wV@VOPlNoQj1h8*hDeE&4+B`b7^ zldOYIqTbS!{Cv+~YAp+6Wx&>0Im_b@y*G9%W4Rs?>*sRMFez464X4&Z4&RU7l98dY z66_u;Z;j}q|3STndxxjgT`u!_8{?>}@1^f?AlDk!MvqfhNuj?*!;{`b_6o($p)c_$ zXMWtJZ&8PJ-|p0C4$>!+%k_ZTP9XOumNTdW@w(MVxOZSKPVRr42U@NWt!{Br$hm+f z`tdS-QM{bAOOR2_)v4j{yqx_*wY!t$!65q0S?Awf#9aS^6mh9Yl_zHDGO6KZ*?}wa zy!}s7h(OvszNLYbB@Vubio?4!uYX6fq0-W}+4hh~xA2 z>7aj!4zjX!5HUvwqw4D5?Hg_WP3yveI`;t1+M_j3|clx(nI!-T<-fzB1 zY5o^kyFQ=Uytz^}{yG`LWQng+@ZefgpZiW~fru5h7;@xr` z?BW`z)swYcQ%xkNsbg8B8iKmiNV5Y~QtkMg^CjsI-Buw394a^?>6hHd_{o0uaxpmZ zLq0{9$(WiF`B%MI<~I1wJey)U7E&tF)YM;SmrLKqzvSqfN(t&$Esr#6<=7lGZ1L5= z7A-BDd#w$#<+?aX&(DMe1GM~Zgod+B@#C#IP6t~3@3SfMT>{D+(V^N2;SF41`ENZO z{pgNf3%y{o$s6t;eK6rg11uZS5G%>qv-bI;*fId;9t5B^CJ=*<5Z_M*;creb9KM7g z@JeGCwQqv29YV3RGz_MHnxW_I7BHID5=MVp!D5a;zYuWk*B1Nlldt#d0F#C)kK@l} z5eSd(ibXFYG4E>>VqbT|?&IBI+`0$qAMb%X**)M*9DVeSJ)Xq20P@!}ugQ&b$c;0} zdx@28j`8aa^fgkW_(SeJy)ki@e7x5W&I!H4x?&1v$lXttk_vi9Z1{d+;YjlIqVB9s z{=-`2G-C2{_L=Tt@6UO1|La^Io^egcr9YC_9l-0KAU}W0Bb8s*=W`7T=u`Q~>+xQ8 zJ*6I#O)S67nkUx-ePa8abkcc02Px z^!=D6!2Z#2<^eR1PLegv*>^-gx)r_8gUHWMu1S>oW2vXNPn3~$5~cEGg80o%kc+wr zvTPHzbbDq2QcJI>$Bcjkh3HZjzF|nN{*XEgF)Vu?wHNZ@_S8BixUqkRTJni1_Ww}h z=uMAFCiV0h)=8B;{6)m`Le>w*#nK;6EWdt|b;RT3>^$uFbv~baP5q_g6~342z=IF; z08)3c<~g-^?jgkH#ICWD$u;ELMrDmrA?r`@aYw9--NMIB+&io$zAlcXFOGH739%AQ z{2xeOKZdzu|4@UuOkMskxp@uu1w*#5220JQx*s(dZ~9)ob53;v`##xY)RW$pJsVjo zrB5-J&tKus`%j`zGllo9PYtLiIX~BszSPST`TGcNO>gHi_G59b>w-3MVoWSQ@i$He zaZOybFP<|6*%Nv{L0Ts#%C{?=CCJ)`np%pCNV+6-`lrb8#;J0@X_~wrm@dt?US@Ca z74ffgjh?pavUJT2vAmff8=7Uw!oN4=R>^JYlYLj#_q;C)HfGCB&YhTA_)I$e_eyS= zzmrk1AEnnYB@g~8y-pN~ckfb}9Q>0RgY=zi)X28mfBFAZ4ZGPt|NImEd!?GlGt@?# z5FHrL*Twn>`UA(%AEKiNlT2MSP1HrwQe7mh)xl%(({uS6FpE&fkler0Ve20`1op=C z{vj_zi{-KB?G9Rp-}8e*n}5w2Jo?a|)fyeMt+8pi4en^!A|QsE za}PVL%eTX#Xl1^YBV3=@;nqQ0IL)zv+IVa9=X)3OJXI|%k)dgcypWy}AC`m}(>Th$h-J(V%9mhK+;%%HJi*T0xZz*;g(7&8y`W zegA6g7quT#A)}uClx6zm(p;@f9+Z`c?!;2*_n}NW`j<=ca^?tlRfsKh`^nR)<(wM5 zo+H!{`$ip4hH2u>8!gmn&VRFkDs8B_jv>BmXHLK`Q}hLA;Bmfbr$M#|O|-{=Oh>qt zI3c*93j*e=^1JFy^TgMeUeI(@a&{lQNos(R?|rfBVMA<9^uvN9{>a-90L92aEFRGa z7Ub<_$-#IrG=#4Y#v_Dc)`F(U>e-y%hhx|5mUvRu3YO!Avps-&oL`iGr5%6P0fjc5 zFzZ5R9JGqSmw&q=_(~)e7erxZem4XqbjQ9nJ3br-Z`K)7ZBkw;;?4*wJlHB_xb&^x%g3F5jY*BOud)Mj{J4XMdz6Wbf4QQs#|SI*KnPka|*`Zr>FJ7T&a-*<`czrpok z2haWVH~s6{+?TUQwt^W5tEMWw@hP&M8GH?Y67zYk%B@^;CQuIw;W>yG7mm>fGdNl7 zskeZD5Xyl#C=tQgnBV6ir(}{ z=8Y)(jpByKiA$kE^p_}PlaE5&^QeI+VyXF1a~T~g5#+-C=sUSVePa)`^b4h|gHnrl zN{;@Sx_CG8?ljgt-xJT*5lhqQZ`pH!qk|TThM=IpUIfe9L-h2=<6hqE1tHmTktaRy8I!#r;n|^`e;z1hdtzh_qrG$l(^oRJl=#g!(Zn$aBs1ySEu`Y@_y%E zJa>ucl@^K3hp)29xqv-PxnkSvv-H~ZNop=LEO`^SbTWbWW~LlflIH-(jf8NAZXaBY@3 z<^>STKUm=0YD-KYj=xE#%(umY{dO2Q!X9119B|0n5gzXy zv9E0%gxJ<$ZmlB2@BiyW=2OK2dnR2|*xt7GJUYWR;m{{LpyvRA7{UahH? zB{9FH)xio`*F=?3&?@hT5kOr&GWT{B&(RuBQXrmAZ(UsgF)shG?j5g8rS&kiLLE zL0GRJjQxE=P!`aHnPKcl`r8!M3!1aO-U4ZZTcY91R+v3T@ZmYI&8aO$jcbQJ)%3%} zb;Qi^ozd5td0t1lB3nNS58HObsNUVNx_%GDuJ3`D{JXeA9Q7wxtt5`tBM#nq!MY)F zw-+@De`4_A6#5y7$6wY_2Oml7ZADCWq?SS4Go=U6rHC~|OY&ep_HBY5MsoDWeTlWi z_04?TKjorSY$4X4L@8$m1)B>A`%>J-)s%*Nxww*we~$ z{quvEPwizT{rK;EsJrx`Cx7TANhMFu;%7EI&U!2N6mP;=N7bRTb5EsZ=1xP#UvU1h`H$pnC~))d9AGz<(GA$w98Fky)%LRA*_qOid8~83WPUlh zb_%iibUO7H>Md=E=O@#3m~J_g`pz_7kC;7nL#$M8<4o*5>|-UyKO)8tI7a`=(O9W}fIU$B zS^X8neBP^LyI6^}=FhoSbmX;^+W3z!?iF0P29?H0+~pYAc7$2!=a`M2!}-+w`Jq5+ z>{FTF%UXa^Tk6F9Ku|f?u1JMs9#_bVYK45F#xmk8XSou~)1o;G^do?yVL7ZTq7jWlffK?>&N3O0R_7bucJ zCrYH!s9f4juaJb?Dlv?%74>@RaLUtwg{KxQKC>@#xi)Bq>g$eHPW}NQtpf| zmxT5u^2z6$xKQ(HrJW}+S3k+_86Rc$*N<}H%xAgWF;7aI3gm7FW)WQdCOaaE|F;(G zb*+$Y4gbi!aca2C^A@u{yYK=z=uKk!Ap=-*c3a1Ph@FpBwZLjqbJV|Wj*^Yctm*tx} zjGYUeVeP^h5j&k=$-3g;4s~#7we6SgjreG0qOa4$s0SK&@LL_fjMZ_2 zJpgg6Pd|v~n%JCm&7^K6{-w6NDk8*|3#;FXykoXb@`S6c2SI6S}%uQymg5zpTZ*QM*+lg!q3#2|mw z=T1HBf@^+}$T((5Y&QKAoClW?T!LWVTn?WtAT$sTFX!XB+mRw#Ca+?Gc+y z?|OP?6z+_`&(@Ksn-+yJ*4^Phu?Jk6^+XtPbQp0|h^yC#eL2L@9q-t`LrmOCTu&lK zPQS0xzxN)a<}sK3o&D$`Y(}2!PQApQ`nn7GcOZ3;cEshr^rnm?ryfg;9jJUC`TPuK zY3-(t6L(Sml1s;tbB}yOeV*4kK};_uKR;J?QOb$CaXen~o)+vByIsBaU zYWY59!Ea{oY+vGg1=o)dt_Oow&<7vI+OQq>2XB)lmLByn?4>Gcpz1m5NA0#|Y?4g& zNfJd-qU?xEl$O-a)jA}~2HQkg@hw5L?lKR6by2t_NYQR)0XWCYw$pL4w0WEuWh>+$ z{fh_4&%dtY+-Y+23&hov)IqA7#LD%$tUt1!a|E^Tb*zj2N4@$dIqiPp`Dfz!D&q4P z;`un@`Le^ra^iLfG1X}UJ>mb6r!T)C-b#Y|qE13?{G}T) zyf15>)a`dhkejm>xoL8&lr3UimbjkJT5aEx#Crubpo_7xG%Z$U^3dnkYJ5(}9q3_)2nz%DdanAP)@z%a65zehgr2l)v-{Ueeh>go)-0F9kk;Nv@Y*-@h?3kXWMXIPNhDsY%{=?N&_4< zHbfJ8zyG;tfQ&^3coSxTT4uYBH`l|OVLGUJsfFIdHPPV_y^lI-m|k1W`5(-M@%SNg zLX_T`JUOGEFY}lkpsd#(fAdk&$kSJP=1Kj8d?`BgMM{4Z%9B;!W$*V=dDQHeSeRDJ zse^w-U0nmCJ+$zW87?*x^ziu~1GrE}Kgan!r9(^+ecKEk1?HG~i?frDTcTpF71ofK zpS8Au?@Jr}$JuNWVTau%b^vviG4>9yswDr`se?}DPMB8L8SXxH5fI{nV}&m0>F#|DYCJEmPXn%6%XD8Ee#V?=15vTWKKv zg$Aa^Xd)qxUVi?&TxLGP>|6Q(^VB2tOwiWX470r~u-(-PW({o++|mx!%^a|b{y>!VFqAGrKzfZ~x2G2($Af?5SY=SCnh zrUaqRWTgfZhOs?E;n^|_HjA2~B)@#Jr_Qbz8#Pu2E>+^`6nUClj zBz~TZAtxqRcb-b@?oS^|CuYBpmpf5w8P}aS{tq*?rV+OnQ3F{?-^dbrX_nGEvxPoF z^8BiF>gdGWoz&CE5og!tb1fmJULl5iQ~wxW!N*GC|1a`;V*5(sdK$Hp2y*SNydRUd zx2Ug$Xm&$`@Eq?k=)wy7Cq(HFUUV>^!5?YXA{rkiRUTA^VP(2 z4|4MZYuT4WEPp{wBXB0`spP^n^mzB=@ejX#HjiANubay?;VFHHO6{B~tDNxRx7u2dBLB(qhFp!pVzAQ_uWhn4EGg{EMg^$ z>(2Y5oS`&}nd+U`FJ!3HfK+~$=P8^U+J^r4P3(Oo_AB|k#WB%ALstA+XZ&6%6LZUbjwjpfX(z9~{S zfWDTSsj_%+n#`P?F7szymNkW!#qR4B8S~7*8x%LP7`TDcCuKyw>)!)VK?ho-vuaNP-s^ptltrRR*!xUm9 z7HVQVGp(w}=wSDHT|8q?z2dDNqGsr$%FqB~IETJ&J^DNTqen2)5Id=L7&6B-ZMh+~ zwKc@T|M!EpXa8bMPhC{s=AOT=7Dkt7;3NBzGW!3O0@rHJ`}rl~`;|(IvTrhB8E1_$ zZ~VYg;<|hm4c}Z*d|*cT_dE&TULbd#ew7EQ)L%xGO1tw)?V(DRpRJXqBh|5Mr6%@1 z*M?OSJ#?TSJr_n;U||BUTc&UxV2cJ zhv`8F>EVb4Ggmx@fW11y9bp!fAOuR9U*A_cAx!eC&orR_-_!=8lan z?nq5=!+1M4bY;Je$tzb(?d^&tk6m~!7d(o0#w$xFgiLnCrPuaoJ=_kbsL}6FwMHOw z5$mwVy3gAJ6<^J8qq8ZlMj0b^g&}6R8X%hes}6T{F<=L4(A@7-vX=3C82bT;)9S2q z_$SoJ-*K!xkLOxk`$xu4`Xh_S{*i<|HS&>tt+q4NQ1wF%Z6eiidVxCb4(2|IzWJu~ z^yjd~9ezg}slmE9(1mqn>M$eez3&*Ss_&*QwuJgzYgC2WBJQ*uY>l|i@pm)nu@lz3 ztBW3|T(PN{8!|S!GY8CrKl8x-P4zKtu@9y z{Y-tGJbYs@ufsLPmiKVAn%Ax6&uXZ{SCMD)UXF5&8Ozr`<9j}kb8C~Q`|ti&83)r#p~Y_ zL|c&{7IPA$pi6?Z)l85dYvaX_-bKA3^ih9O$dh#niHJ~eb~W*mTJBlZ|)=Lp^w*RZbN`}e880oS$IHiT z&JW>??w%)EhX_iP{!fYLYnWwE-78Fk`@9sc#hkI2(lJF|d8SIRR+^M&q{-;;bk=jy zqXk8JZ(!;Qo0xWgLgS!NT?JIVPt)jHf$>!Bs*66d_p zN5A<7P%|Q4Z!|=E9V4_KWrRw4v$x+g!mjH^7`u<$n0+{x^o{T)-jJFoy(g*qxL98g zPSiz&m~_@zi}Qk+Yx_bS-vtVJC>F>z#XrakOF+o9&LEgt>DIx9UjeN8OkqHT`g zP*dohG=^z=BfR}%fP)Hstm>zSvR69jY^BZDQj-bQz{OuG-}`x2HAGW?uUNo5#tCZ3 zVeYWjRW&TFRKtCHb?l^$)=^y@8~;_kz8UvR`<81Wj=7b}bJZWF3)dWd+=w%T=U`)` zx|rf2eLRs*El_u&6&|LkY6Ah5_L$h)5v}GqvCpV3jybrZY%k|bzjH(IFb`~<;Dy{V z-dJ_j2Z`4jz@gd~+GG5o#L&M{^u9 z-a(C@IVV}t_tEPzE?H8U2hfX| zT?O5(K?*fYABI{HZZ7MFFVE})$#`_q}{Ix|6z1SZJYym+~_j{3O^HQ@uy z0WhFGOl~}!c&TuoNyNC$#CBr3y(|0l^@)$)i02tfpEo)933?XE%Z+2% zt4V*NCNcBuQTkk115MgNeBVetoqam@$`UwSF&t=WEuv+Pos@0COipEZDW+!uVL zUq(HVUQKE(Rg*ajB%itQFZX|C!X8`%+3Q=u_PGPTXgHl(H9`sW#(_9OrzA zn#N@^jDERKTmHzLGs?enEnHOB!WJL;Sr+Rc^Q$gwS@U$`4Ep`~26(mE5HUVRI1_7x zWKUysSZ<7pEMwFuG=>5DEAt*2$^ZaR9EF19iA zaH=h5B`;FxIj6PN@n@sTw_Y~&huHTimW}Pc$rPin5@SxMotc?+xkj`!n1xGU$8qMbEE=JQrkf1Vh-;1A8G2n#nqmGm3w}Nu zY|F96lDjr&`@t5gzT2S=XZnnz#_~h64tCi(A-bhAU+02*K`zLsup&F6H|r8fee{(LUeQ z@rZLVibhfIBBrOjR>PgiYDhh*hSC^nG4`5x_)HU?FSO7on%QIn^sx7+KGtd&;@K7c zTPK-dz#ucI-#14u_9l(ZqGt5i2CeMv@gvj`QH`B2%AzjT-*Z8_GEczI9b22La$-)` z^Tyz}-Uu!5!4vUCxw;?X&-x>`JOCFz1Om1}2s#mr8s@~TF$zWJrC~UHy(x~yH^Urf zr7wow_S9Bb^tuhEMt9)%5hxCdKrLt1jXuX5-uY2z`YZ}(iR0J*Qa9JQB+rSZ*O{jk z#;*ra3kffzeoai?MQ;844mA?u=d@VW%(*6esmTxM8Ge?$^ZWC0s8K5x4J_kW+K5NFYvU@$n76&mtFJ$34Pmt|iKKU@WtKqnY{Jo1Vk= zd|xDA+mvg;I^y|XV!0;QmLl^0nV0C5N#uIL{Xi*?@MLmvUV8vv_vcI%~qOnZI}`Su}RgvpAWLpq_3?Z#w56?K_(! zZ)PNkLsMn|{7IB%ml9>`j70HikSNh_6Qmw9qpoo#+QTpL;zi$LO+dVu-i+gn$T->Z zTp{&1UwUYeLRQhMcbr;=-U<57=PMe1{sJk3wjd3^g7^$T!UrSA$y1DsmdPyd74$%?Nib9^pRXI(v&g$5KaD zNY^lhTwb6MuRRKB|1Y_^yMpsk=x0CAy~SMC1GwL4=N&8ESu-uSq94YS-?N4~Hk#T_ z60_m;6w++CLMCP@#Ex@W6BTi?FeF~g*jKCLPpxWug6Po4|J*)N&UZ|dhDQ>mUTBgy zdov%iFMA!>KUBq>7L#?UyoWTIoWL2+%u%e&xgxLcU6rYs*CaIiy7*MwkSYF|@@hqv z-156c@8ccLin}L4W3naD_mNCfdny~UpNrFuSMq1zTe;WZgSgs%mQ2Z)Zx_GHo`v7# z(C#wXU{WDdE>ugRzZw)P>7!e&h1;B+&?-_FujBRbwgEXg{VZFF&3)LPGMM$oLB#Gm z6HO5R)C9NcnWCnnDUNh8MJD?%FI1VJf*6`7CitFej5Kp&EDkcl3_C+C%VPbH^Nsb( zbnqmWe)b1im>I2!!2{J{nNcGjy8o7CHNQt4>_U3Pvf6bqNHGM^Z3@r5(ursj$5 z#(bH<{HmTh-z4@$v6OD+%uxN`vYb6Tx;Ex5pKSvmJt^?C)PS8H!jKUXn@uAiQuXXC-ww@az1Kbfl z%>!R9dm>1uKK=x$FuG`X19*4vMTSK~xY+tZllnsO6+ayB!`VM3e&`k35TW#Mt4~(W zk?==(od&3%S|6#mJaHk=1CL9n-B81^&Q$UL>H#h&qh=p%R|f{_4k#$KMOQ}~gwPu~ z(ApArZkglCTGlVA%Z$x8{@=gL?~TfTA6>j+M%i=vkD{3qe7hlY%cg3hLyQ(il@RAc zG|`!JLA0o~jBlupv5(cT;43wo8S2>9T?4uF3#riux}Tn*m7S^WjMPPjm(n++3-wF` zXr3~{HTK(f=f7{j5;N=`VS(kWpU%s*!7mMa{L8&Yvau7En%2dHFD?k#$DH0F?r{6Y zy-ckqPR4rS(HQ>Tc6y`UO4Zu;=BXcEKk>)n27#FJvJu=A!T1{87`shE;l4Nwz7LyX z)#qk7_q_$e%vxjk#WuX34j8e%6QWmk!K%^-__{`7Y)K@nJ4Rt0@w|js`ib7{cxK-! zdv3~fiRr(Ydq`cxJD+vRx2!o*>!?fadxqTCOTiw0;^prX)GSW2E_s$U)db=xF?Bv) z*Rp_k&+~>8n@zkgNiJtp4`80ICox`#-|0Wd@2O`e@aRt6WjLRkKuljvj$X>_UuFJo zDm{mriRn>aIU|D@T}3<(oKnLpmq10{2%g-8eO(;l~;YrEzcO7~8bY>n5qt``}CB%tY+nixk zemzMlH*q%Iz$6*so+S746Q$@_qP!Z!JQr%d+f&%f$eBj}>Lf^y6Y(;Z{pu^oQLyrEn!v*OVe1WsUsIjQC zFX=rq5R>T*U(TGBwlQ+tEQWc?#P=!e)Bh7AMTVRR(LN ztmBp%lcNhgDZ3Ty<&6`koz%gbDP#z_dQ>*^XvpcmO^ub*4y>~_Wj&xL>#5Y_HSaKI z%S0ii^x%7(Q;4l`9A|aJNdwkE8_c67Wx%<9J2(f5bL56IZ~nxyM6qYh`S6}Zsiimc z!4B1ok-hsaiEV9)v|~=o;g4xj=yqA$H(ZfZH?K;Ml53)AdqYlBGao-cQ*LHvNxttb z*_v@%%1_*-kM+L1ih3wE<&UI)!c)mv{X!Z{crC|zyc3hwALV^`u4D`=5beu_;yj4##eS|sNwW@g%>f<;wB9b%aKk4GfKz*EjW`J2!jIfY7C=W&wtFM|Mt+^={ z-7v+oc4k;|+6@1^Q~C1dUo-n(|4vd2F z7D&LXFLJ*ta|@priB3(4v^rKU?ax=rU85RV$85$n3p5d0hdD17^kAfGh@TC3ZC6ti z+nXam%Mw=}TOog)4L+O%pa<@l zWZ;P>y}j@_ralH+_~6Hq2Iw5p5D(Y;;ZawA969BWO)Uao{xAT$y9Yv3tr5I9WBEL5 zf<HW1 z9usQT^iS@2ZHpNzSf}h`jTzxqh;CqsW9AlU_mcfm{5}7yGKO}E5q8uXQtL3lBG#m< zg6SjGV6NCBZF&>6P{|ygv=$n8TA_w@6V8m8JHy)>tg~bN&_cX#i=6)&Hcl7`>wAf<7TwW{myTSd=OFI<)bU?bZ$`>>8 zqzi5v)x(!jZctn8j^5O%T4^bHy9YE1>m%T=4^pT3V&lMuaN`>2ni+tx4ngRy$qcXy zjd8boC@d_RBDzj<1f+-aeZcn(oNd>rJ#x=?#EW~KabQ&hg5PvSHT~*OU8A^9VI7qC zo37;Me-Z8{?17iAWa_xTP$&aa(JR|p>b)R@n-Fi_f@iU2D6XN(bJ|5)v&Kcyy z)J2ApQ+Fa}2Qi2JV?*}#?PA6$=bP4JK6^AVy8&@}12Mc8vHSxuU77dtnqRx{dZC=d z;YTk@AHFt}-jwP}?jb(24=9_xOVn9(c)hgK%mO=1ePs{%_cr#861UAa(bvw$_PeMZ zag903Bc0FHrM7acJN5r?^7)3me<$KQv3%XnWHEa|J|4$B1NMn3XN)GbV9r5svfQN? z{Tt_Aw0z8d^HZEDJts-3+H)?oMUq@*k5RK-iIUqjQNpU(Cwd@3x-{qfi%0aJk5T#1 zJFaGLkw=_NeM~Ieq>$P^3i(CdrRmRD>3KU=rV$Gt64M{DHW}8EnI`Vcb}=BHmeJ?; znmB!%b1SG}+@S7qkDALd^68$3E=a&W=GPL_8*gDR5qbI!^7JFK`22YGbQ06=v?oWW z=5mP~-L@h|em`K3&t7KS_KcAcob&d;=e$_{KF6&2^OBhrBVVY0+y3S`TClf>db;5n zdMUYw7($+Y_#<^8EqcZM71DUBLgsE(aGsJvrZs1lq_skffAMuW)NQE0J9T9yFSYe& zvtp$QpLgu3kR!~qnf6m5=Q`8Vaz0L~-Qwlnv+?qxZGs&Ak{~D7CrT&!SOP92Nj+xM zdwM0yF8Yd;KK?o7$zq;+Nfs?km8|z^aw0vQ&!>yR?y9stc8%FR*Cn}LhTNW>DH}N- zG`qzud2{%-bgO$;{GZ=r4#)#()FwxUWIrb6J)_T(`Qx^4lc8um2Oz}1l|9b{TpV!?ZT#Emk<)dC}InWypqR`z7y z{2?>wS(xM7UUTf~Xo0TO1s-NuzMbe_cY}dCRv)jG@As=DWvj}s9-UGmBbpS;nUzK2`lwJ` zsl(hF_eI`J{3`uVf0J*2zKizCQkgTMT&xNztF`hd@4$Ht0 z#5E2^|0I=etT8hXlbL;W=2Ju5AMFcuzXli)!$q~m&?J@tS9eP{Xp;riX_n|7?eewk>6m77??|LeY=IJ)-Om~dnN1UDyNV zQmcbi`{`Ak##td;BQ{4HKyM&3dJnUIE7}D2_L$+<3=3oovw}a@n>n}bFs_*Oh-~h6 zMsQBjW$tw>Tv6Vp9&FmVVXlTdG;7>Z_^&4lBI_et-3R}0c9ODZX+sNtY<(Pvy0?N5 z)hPt7zZzpvoiO}+u^9%e3df-#tx} zie8jz@@-;mG4XvckDYwZ>?doV)JDw7)s>n^1hKl_Bli1H(`ZLrZ$yl(zCzy4`eev0 zYUsrCj<1!O0eqhL>_<#aB1iw)_>yE0+wIA_3#jc(O8V$ zP)8b1y}l2%SYo+yR>w^Xdd@Y8>pzm&%fUI*tb_WUr}um{dtV16i*E>@tD7vz7Rl1P zI*I+ONiy(alJp@*?>#a}-iGjdEzYic%xo@Zqzkq5y~UhyxsEkaXFeXIZ-cXpvd+ax zIJ0!!)2X4ew`Q?z|Y4F~9r~=i(91HxDDXUcesHZOnu` z#r;Dn{pgQW9+!ILEOPcrgFo(wYhD$l)@S$`#R*R)*D znpDce;6Ji7SPf0OYT!DvS`M$#LH+f5*wEhqhCk_9nP&{YQsO!LEmNkN;|F=6@mLFd zXRR!Ch$S94sCvj>FSo)qH!G}uV2N4dEHUPn1#V5ZfaOzSsEs)qMw#L7Rh56jp~eWS zZ!ml1t{z%_(Lv5%Efo3DCpn)v12KQ4+WC(ls!|+nf69bAWzx-?bKoWw%d-PTQjfW_ z%9`%{gN1VVa}oPWiaBSmR2D4%AqMm_UYb=UdH4Rxn}yU8Jhbucn=aZPHNdI%#&BP0 zif#N1+ng;?Q)q=hSvE*GVTUaX9niT;9ki#vd_J}90dHN=+Sd)OL)Tg3>p72N8b%A)Q9fY}egRsga7_ZI*qmcbHyL=j>utO8*eQ5%d zbY@tYHNlhvjS>4c1l@N8kFtmocDv?iH7)g(H9Bq#T>uH=YJUIOwE44 z2shjfaK+y_b+I(m89|XwXt=))^7ZPVf>|uH4mhAF+a3X(RK2W;yKFFMkQFMs(AN`Y zhH~cF4D&O>7k2~Lo9f~2eN{bmT9O7Vsk2}Ds{z|`P3WxE!sXvuxX-$Eufy~t6=`Ex zC^H?{OIG_r2faJ!qVacKtbD150xbiK7;lJACdLSTXoBqNsy*8B;Z}Hi!UjW++OaO` zfZM<6&!52B>3wIkc67l8amA|0dN>#9hEAT`_w4jQ#vLyhyZK;kgfDbX_+hYNAhbU> zLa&a>IUB*)+A$O#teYY9P76F((+cf+0{yMp;qJu_2oLFum9rzzWN0KDE<_=xMK@Rx zJBRSN!y}c)EaGZf8S#)fd#jLtXVgCaB~NermR$NVdH6lzJ~6zKI*c-h7TuAo=$&^7JKKGc<_lb$AUY{w*Ki8jzFEycr(- zc%0?6OnIKO?|7{ztfO-M*c;0l?I9HxpSFTt_PONw)97OyM{Yixy+wnV^+F8a(~Z2p zBXyQ$tb2NLebFaxFJ%rF^Jp^2%fB(pz@EB!_|ask_>cU2JZqvIljV*NdAm91C;U#5 zZSTp=sks!;3tc-eNlI8770$fa@-tC_ZW5DN!!vA^D5Hq!ov5W>GD#54+3~XRJGF%| z7!b+epsKm6jLQF8Qf>MqF#sC!d;IZ0g4-9v99`TDv|#B}2N`?;KFH-TCVxq8<& z?9udLK8z9H$9Zq27pc3<Qyi$RLm@81xc?x3zd>Eet(`)4bW=#Qg8CBs z`Sa;#DXw50v~j%L`8Qr(-;9^=HmoC;CCH8k%sk6V68o%VX?dCd_Q#poKO;qS-BZPw zGoB02q>0zNbeYZCry}L5>^8YB9Xj6-rxh7edoxp7R%XeJ=QnxpH|6vR=Hl+ZC*~a< z$mfh~`EI7l-WuWkR5}{G;A>t>i}7#8`OkZadizPnc;?H^6JObb^qtvXoMqXqTr%@2 z#DO_lVMMa4;v2{z&+XsW7v0MaMl#d*gL%{C$Gd3d!j5++K)Y&%;#Rj`r5WY zQ=FM?44uJ-SUo}?&F1K0|55r=K51ffV-47Cr2cZdM)FovN#VWy8f1wgSFE8wK~?bPp7*(GYN9_ zVg5j=7nq~8k2zeK-{SM!3X#`sP$$U_85bO|CbkaF+;GM)bEW3t0mBjQsGxSPe$5l9 z?)4F|%NzOu4bVK(7yUZ<`0g-7uWYZvw3`jnUz8Fd7dJLb+EXyz>f#byNVht?@@uLq9aS z)c`kQ>!a+c2Q2rvA=;oGE?B!_={6UfjB-J#rOFo>dC3`1Gn_Em%n6fg9Ff_<0lyvW z@VdqtA8uKqBl~1i3{3H4lMyx%*IS;ao>r`liU4g)ZKjRVp7eXJ(MJC?ZO$;F_dQP= zqlo7-%C%9frUNrG&Sy2(!OFMVm}swqemc4^pQ(pOZ}pKf(GYi>jWH+71R6WIX79AX zrBhbWSYU%%Pdm&!r&?#u@2UeAHD}c8QWs5@xZv`3`anA>YX__wFkir{#v4gjeK9fD z4>tP(VAZ1$o<9h}%8em#$!-F*iA^zxvo!1uw}jjH=Tahc89I^q(l) za_o-EwC-q5F5Xhf$9aq(9v2X2mlMnXEuj9KOReGqeTHx734EsN&;LwJ|9poSPAre1 z7L!3d&wWXZ|46Na?^{PLWg{_tGW+m-nUj@BzCN0dF~oBr?|#fZ!DOx-uf9|3CVofp z{DnOKe69(4FR0-Y$1StzvEiDb%+GCkj=IlY>ho*K%@@!cIfYpQBj_pb&pK=rb(!|u zSG1(}ya_e^hSYUj+4E}7=c|)Bzg(4hzWHLZOo>mHUnh8Mr-r^HS@zM}(l{zvrc!UI zu;cf&^tOCXlKu3#OlMuR{yH8LnAt_$#nO>ldM-KodG;AiV4smoqQpH{dC^aOkC*f9 z;$_r@IH{~3C%eyZhBUS0B-Taekkguwqu(wk|9#AUo_J~&TVus4nzcmg>CK7hJAF6@ zlr=_sb=FM3vG?;SdxprCgBgO7FTW&BOvzKV}``CI`xyE=84um#l5 zSu0&ZTu&md>-w?=YD(`5Gge+@#>n1XoCmioMzm66q)kuGII6?z9pydI!xEmzi~`m? zbIvgnl1JJ}J|2u^KdP#3x|IHw!>pmcVg1yb+`MS4LZ+YR?7ckdNtSW4DLhVWIg>9l zCr%c#{yBRMXRy-Gvi@tl*l8q4VZ#K;+?^mhM<&X*8_chJ1F&l#20LqIv126lmR+@D_I@u=QOz#Z25{_Xl!S z`=KPA&k?K8#}awuiNue6ChOB*NEP#Omj=C)Ew4XF(FB!GQR5l)iY?z|zik=k-Tai~ z^_9fGDv5;}H1=vBJxvP_uj{}!OAiwt8DQlLBj{5ze=^4m3T+E??{A5XqpYCiY>k1N znR}9Jjo?N$NM2@x70+y-ZEuUl^ej(oY0GRvTO8?agS0)?*v_0QrN88AKTAw5Vvo;Z zGjwBaZQWz4y58Y3eJnSl#?xL0`8&1Hsa6B-6WObp@K;i!|A@=p-?Eunzr*^U%&Pw( zP0Y)rPfUqy`C2TEe;0H8<($v_QZe>npOSaEgzEf~35LJr`{Ww=%^A?+&T8UAE9woJ z`k4LO5XX<0pxHw+G>oyp#p703ciIMzi0PLfIv`5h3CUq~VL#6mGse1Ms=5b`&1U|f zZhg$2>y1T)KA3gTm!HQU)4uydo%+dU>mal|7L51W)CjzqV3K(#OkakgJ2Pd6Mm9x( zS~DCy*bM!Bo8$fY=7{%bfosI3mUo)rq)t-=^$EqR=Z#UjH3TKQg3-k|7>`G&^cmv- zKm58yUw66}WP}GgsJkPRy1vC(H}oaPwdv!IEuY=+C%Ya>_PS!>Bp0;wt&4bt6FOBo z;#avnP8_hsd<}Z<8?ctCVT!*^j4)A6RZBgstp}ZltbuOU<;*%=46Ub2eMSeJcIn`K zC(hW`)WHbmI3%Cb#*w+&=vS=L$HsCtYnykR(P}}T{C0iJ98T??{`r8WrWkEyj^huQ zX)|86cUwH!7JJ#Z6*SEO-wGV@wW||O#W>@Xz6)wYT(QE!4GEPVsE$|Gn*E`h;s@jA z0l1kTh=qrPU^PDkhO3*P<&7|Ga!_T$Tzu0SU98(;seK3N{^^7*%DCyMXygKI%O zaQ6#qi99;+7(*QYNSxhIo_vT{TS=@hkM&tf5Xml{jCgg4~>%i&9fr!|N#X0fs%L_MXFxcCHV# z)OC(!5aZKWH;toqf1KG~+sV^c(B~4(*>D%)t-iOU)Dx{BS{t#(*s{6N@LdavYRE!_-_gF{ZN9~hbPGD_;_ly z%;_2#C%s-Pr1eS#J$MRf!g}I%7lnlBQj;!ZUp=|55wSCOJu_@sTRhR59uw;6HtdzZ zW6%6U)=Be!Fmvk-d;G7lU+5hDEyV6}@^WkP@?c{6jNJGdoR{IomJY(2DA|vvpGRB2GOIqF+prrCdxRMWXb3Mt*Mha-0Sk=|AB#A)|OaqN*RgX{~WFr2w9&p3nlbeZUM`6b3T zncL!9!@1UKc#^?cbLnz{jvlgso;GLDH?qdjT1&KD z&Yn#>b8Owq400X%WV#yR!5jljJgkS2^l0?#rj1(q=+=(bz_d~|9Jr#I>1mhpo7o)| z;%)d#O#79~v5GSOZI#g{R4U&~O2t2~Oje*=zUNY>d08P{beV6(^~#?4zr${6z?+{h zky>(}p9ZK$fA<7KGhATi;>3aUz09|P>k;zw#}3%*s;cXGjdsN;xM8HT2j*LP5i5L< zJLl*&hzQSpPH)Lin>_Wc=3{t8_vU+%ycPeogVavMJ0JoV_`!Ihs4Q zpzpo~1|MNhIpIT_zL>n8PY2#LuF1qj4M_u+NeR*e$W_wKGU}BDb zeJ$X4+7ffTtl2AT1Fc@n6u4)PqfH(8?^*{_7dqqFe=Z2FsE0XEJn-Gz8(j+;V6wg+ z7G3birKy2f-7*L>okFnHun7+T3Ppl{Gj!7q$M=D);X&`q`nTsMy65X)_Ojs1MzD&qJlp6?d* zm19?_-4M&8ljub}$34O!-q$8-{EJlclJ*W}KWJC>rIM2m3Zzcs&YX2SJ{nQyQDd$y zYioh@vGjhKEIHK6hm)HJl9w+eFW*Wm-##~4E>B?Q81?gJ9g-!N{QM#@CdVLI3h8m_ z`GUBeo+N9jxg1_fJg1Is)-g%!sHKk@MgD#xQ9?)4o6elBJ{O5u0}|x_Si0)Cs1~*< zf^>IxcL<0A;xjZTieh(ncjvX^+TGnOv1_+pySo*!6$3<6{AS<%{y4u~VGGnbbLN?6 zCXQXBn+6uj>&FG`ve01Y-;?}+h6)oGtc6F6mkDkd-lbBRLHMk+>fp1ek`#( z-iE)2HOz>ok7diuV)>8fzPZ};@xLpUv_8esIf~y~#q1V(78{-5?4rvd>6meZ?{!qx zkeA1eW4H77Q!>BP8F71lR(cJjuJZM~WcI!&PFF8UEz>Kqt;bc__~n{(op(bDYu%DD z6K;#X>0Q~g?w$pCN!U=j?ZoOwu=x2%2`X<{- zDx~?IDp_t*Et}|H>+GQoo%zJkGkP#RX@E6@HN8J;$8fjhss*|~vEu&~Tg>yaL$iN0 z-jHQ`9S}Rk0qsUQpkOrrk4|+!$zlg|+UJ1KQq6U?l{g@wl|70k+ChJlEyB0iV8AGA z_;^^MKXYt-1I)2+9zBkaI489Bq8Icyke%TxqY?VJ6Qvf z18VYTsEJuVdN|R*5dJ@m(Z9bLvW{Dzc};5s*0)8;XwDi{j;OEY0>=n9?1}Th3qLO` z^YOvsL_ajB8vs4sAiO*hj1FtK135PwS^q?033I_8ZHDwBouMl-$4i9&3W&WMd@ea_6@b zyD@sQZ?&U7%$WJ`?kV*ded;g7@b-;rA+~ibG|Z`m?_sqt^H;f@%)!5N*qyMgXqI41ev zOMpLy{}%|QUI=Q|B&I(JN3kjreK~hX9~Fb0%;i;|>rPEeK*3-3Quj%Q>+>|M%FjgI zbJ-aFyCEJGH$wRRMwmyfLkB8GP*mXH2LK2P3$>?89UspACjaZC94EWTzN z&OOzBnLotvB}K&iLe5t6IosUDIp=!nISa_c$5ZF;&DU!|4`hm_gXpmr@!Ohy7+reh zf3k~%oczaAm4w_>i59Qxn{uz;Yo|)Kt)i!e9>s$bm<7!J6|-(CG0fxMe-bIucMFw)StIib4QatlE}04iEN{HksP?F zeZEYl?&4CLT^Ql{Qb^n^bjp|dCd?A2uHJ;Yx{?~qF5+ocllD zJ5v*H%yZ3;eA#n?nOf_po6qM?D}D3tsI`2FAineQ-Kh0HY|1{nExdK$&eT@!^d}X_ zcg{Xrv(MR@`S86gilr0h3?bC1swfYs`DQ&gb5c^N)z- zEAGhaFLz~o*ZWf6;-LhbdPG0W6Y*{RlwIM^d_@{U=whmMy@&zr?lKUui!@?RTij+*I~-j?%}s{p9A$j4?Hv|Hq@u@q(V?uyxj$vf37} za_zDHAhV}lIl^tB69(<%Ze=fekmH@O$k_>>bevH7%@K{>IpQh34tt9o$*mlbli+~n z?d&n6A2pdyw&)gagFO$d5ZB!j-|4$+SfBszmzY3x#|YM+G+8E*6}kv}R|`E3>Y(8i zZF-+Ic&xYfugKNk%!;j&%l#`QXhr0ZICc@@<0>0l*#JbV- z(ffXVSdK};sN@Ft5i01P2#gt@j5lQ|cs3~&j>l4PDli%8Ck1!28sPF0_HrIfz@3}* zU~@hWuZL4_|5ckF$w;{N3db;N5`7Cp(78nj`+!1_uM>(5g`sdS4n_9m5FBkEj2(4? z@DqXf*dYLJz36?<_r*d-Zw&n74(s18xMA#s(cSFP^rsE{_o{z(3)D3=M=xq@N7daO zF~*qu))0H98sPFTJ;Vj8@wz73`__Wv8RB?(Ef{>Oh3&lGf;#*H@^|e~x~Map+3V~Y ziLm3`yC-u5GEI>>SM8B9hS6F2S~psvw6-s+T{)N z*?!p0>y8fecQ)j#A~Yr({cIy)_k+3XoGE|47z?+6x)|b-fOm6~Fx4>`w^pU`wHo4^ zTNchw%|iC4EJQnJV-zuV9gizKF7jx|!;IX#^r|LLWfZyjJ>t1K&o-PGoKGxnc9uE~ zzkZ9@eunrwfVxZvYAA~z^ZTzkGvy4_fqKgt;<~!$Lfsd)j^~NdeC!RL7Zwo1Ym{rSCYCSg!P#hAdMv1&mo-pHHSt{ST?{uOho^>q zlbVa%R?6l>O37NMl-3iK^13}W^m_Cza&Pqe8)6pw=>F+fEPtGf*}qaG9zBcXrcROU zU`|&6{Vq;L1u{+wWCi;!x-U@3!q)7ii>8;)o?Muie)1)C>T|?z^7IqaIcuc;q3($u z5W}7d?j2o60^V1)AC`z4C4{a`&%pbOYGnMa;;{*Bx|#` zg0JDibHLAX_SSKKXxdw5#Jpm6MhPEF9G}eRbkkw~kQX!0n^4bRz}Y9YmZrq={$H5U zb&zHs6wY)_0_6`CW<6yf3Q_ z9!lhZNBrGAl2I3*ibd<^(!Smc&fQ;dzp_MHpL`{UufCSyI`25IWyj|Q=3xE)B54*C zGU-&6yjlI1dr>v9u7$>{xW&x?-L@Fv*%K4gKc(@byq;}^S(|NOwAl`A$2s7uzY~JT zIb%dFvq@ID;LkMvKjg0bpDJg}JnW3|)7UMa>x=+*XY_jJ1at1wk0HMAIb#{N?m4{Y>s9|df!U!)K*A~-Q|*-P7k|lg|vJALyjH!DUo-7$(s0T zsUBGaCEvB+x=+^ByOs)6CZgn2Jdhe&?8+|k6?{n`_hv93zRnf1qgL=(s zV)!ER?YY!@W>d@I?a3uPZxG|Nc2OfIrtcX-ttF58d0n1AJgL*0a8H%ITtO@^xuX*A zb1F$ACpRM}4j%zbd@epx*GgFYB%yzHOnJD#^_FgI(V9C96 zZRVqwlSh)HFSy9O#eAjIS*(-?LzEIij{e4Jm*B(f2|h$U*x4Ldk8rQhPb`n*MEiVOs7dX8+4Q z(tg~(Cx#kk(9_7nE}1$9b(j;x)NaJ~;U4+&gBtr8Yv!pCV@Fx>){b2nF7%NTpS8&A z-N~Wj>4W^i$BuPoM-jjOm5;Tw;O-A^!|j>T#m6>}W>$J5YWCE}yDa8@Qvvm#lhk_- z(0{XvIq8GgLCW`c?i66>~TrU>~T@{Q|LAQ7D}! z6^Z>L_V#h_He@}sfEFKQ-uWS>Qyi8q)rTcy`Vm=r^N2*-9TmG{^q2b_7yY12*PBWnYqmo>#>4%T+mY^t$BDyD0}d-j{n^jjxPz$9H>o^qA#_a(nK67rA0;TUX35aK$a|vTJuH&i{3W-gIY_es)3~>ZT?1 zvK<@aK&`_bw)N~#|FI36bFHy;p(R$lFvmFNBYvwiLDR{`Sl~v!UP2$maeee!s)y^j zx+tZuu6mv}-kR4$2K(0Ry{e^7{x9iR@>5o>sT7|xKjhb#AM&95hj@DZlvUU0lVMIx zTD`v#Sycm$^fF%d(ZRryTCh5=2NUkDwp18lAa`1~nwjIj)s}o;=IR!!xuX-Zf|!qM z>59Je+_^IYz;1vy!i#;;%ar@+RiB2;!uw}63&)Hp4QJ1)0 zz*2a{&wNbex3Ts|P zVsk_!?(T}fmPrx+`;37NL(yiU#`k?J*cT&xy-=0vj@kWPIFqFQ;cbtpA8oMfD|_l3 zIWx{NM<4DWgiPmoud`;3`d=0E8(#5ucV7>4E->@AKo7;+m;-Z44;MVByHoOsjchN=jiH)vXjpEP|F?N z`g-BzSYMcE1>mq1XBKyYah|!nqxrkO+dUHV!fRuGb_}|da<7#8q@~rG-J=zr$*}93 zf^EjBxG*slzt5y1^d%4SW;^1t4RQGZvAUYrTtE)Kkhhim^AuwETw=8gx%)0^F(t(R z6n=dNIeWcg@-GGPct155>L%6X-}{d8J~bI9YB+;}zmP&3WQZtWZH*_79?24uy6GbgOTqTQwRPx0`B@L{J{W>c7 z{Dr+mkCpQ88KpehN!?|RQeyikWpRp9W^gV#^h2=>Ru)UoF~!n9miof`BJtr4WH0U+ z={zbF3+8;QHHBbex_7eznOCWh_T0Nv>(Y(5uTz)(bk5YQpM4@Pznw2f4-&)IGpqa` zV*FsvCA+aRj+}i-3(g-K=gU>%yB?SykdQBf>ahQac)WiiPg|Y?3ht5DZzngO!(5ng8a!9=9AfgB+`UjCYh5+-g3&vuxlC7kehMXt=g2H~ za`JJ9WLx@&$HB zUt;gY6^SsqCVqdfOV3v~nOAjND!1Mht@-z5#_WeuU-?+J>|-uV-gCKg|AkcVDUr^1 z=*wR5mhWH2+|Bp0qxzj#1gi6KO9gCQF8T3EUYUN8rQ5$s!!;UhB6`IyvCh(h!4Ms& zy6d5DBDGIL6EwePh8-s?@u!{*eC_RUW`#ZcTR9>y$r>+Elc1~~>;N>BNKwz|k>?#P)` zZERYsg%iWc)tN;z@=KK%ldq5M|5L92sFXQAKjoZrm3Zy>C6C#+IsFSgGcC2S`5n8a z*KnrSRTp!j^|ACXGsjkHW(KkI&CuA)60hf5W4DhTJV!a;(hMh94|l=iiEik!%>&Ed zd%?AlFMeO7pRj!pTGR+d&w_9~Nr=L)Im{AN#+9E+*m7cWNy;KtTUw zTpF2z9kWxhWN#V@UZtaU?M(b$mIa?y+1L=7jd`=P(6@0GiU((6*tm2YJDtMcGjLD4 z0dEr#cs?G(Uov~vBo4i2$KqBeb)RQ#oZ1_M{g+~qT(=Iozl=qRUMzky*Kq9YXuS7{ z#+>uDv1fD?COJmHVM-_rS_EV1nE>ow?~B6bUYOm@9Yc4y;H0|~l26;?=^|TThBY=a zN8Xr!Cj&=lbdxQI3}N`(0G+7C_(d7OhFvFrxRbkKu0H0h)`$OR`jsXcpa(OQS20se zx7Y}`+Z!W*GxoLnxmPyb6ffqP!Qh-ZW=C7H|HumCkJ%vLvK@LlJ7UEx?ob_P#?5X| zv|8`OpDhsWlLE2gLlCsD@cdaAhQG5S5ZoZ@e?RxyU$OA}SQq{Gv*)h5J~r@Ls8xZW z=|CX!18_Aa8TXndqXV({8gUuK=SPRgg~`d=60?8v)|&Xdh({GUwt5DtBu2*)+x3a_ z_66kR>&OUyGTFV7^F=PpvobovoL zlau$Mhh=MXmFUrDKDI8ka(|7svduvy{hc@qb);tQ!j5Qf?iKNSTY3B4P9?g!D*2a~ z-u9tVEKhM~bh}atXDX$356(uDl=782`j!{PQnssDW(_EoQNi@2KQEHk+%wwDx!;3Z zg>rB(H3-W>u_qJpd)wf+faWe#w+rOw>-{K``Ad|;|+c)93HqT_IbtJW&j?8I)!x^iJeMY+#@^CKCS@jF0mUEGeXP?soYEv)i zCz{dYpmc7@T&)|Nd0x`&d;aNgLdvR6a#nd-Iz*h2HM7o2vg?16z3aRjjK3(Zr!UEB zk1I0t$W<9}{JM<#dsE`|?nv)HcV+mO`||SDLrJ~+Sk69wDorC_{12;JyniKE`@9yn zu5TqM|GjKT{Uj|)K8u4-nLM5RS=v^7k|V8{byZm=3v$27h=g+KrsO=d=?@w7?I(M| z|8nnN8xFs9k?UrNSZ@<-u{OtWeJe~3RPP`V;;h z-ss8P)Sz|LWj(zywxJge?BuSzrze_i_ds=o2kI#_KIsQr+_1^U4Jkuh@#eG(+>KrE zCeax#*-khX>WG6Exvxn*m4PLAx!Vfs-7WDd-yG9&%;2MEikT(GXh6TAT8C}b&j8BP zdiap73!Nh7kKCz=OWSJjdsUp_|CUqbzofS5FUfuIQ%21DDH)5aWXAyRkCMypbL9@{ zbYglPZRFRgg>E;Qd$LL&*QxoAeQku2wI)!^(r8VU9@e-t#TNhWrOsUBh@SMQ4>{zD zloFn|>UbebMNdX&f6NXD!u)dPe{Z9AIwlI6w??CFtvZmFby06^Jmy?UWbQCKk`D_O zG*8CQJt=tpBo$Ni(-9b-fwki^vGZ0IJQEvYlYS#~f8P+3VjH62#B9u-l7+2Cne1s! z$N1P(Tyaju)gKM8^;UhHIFo?KL#gf1+y2Tgjvnwh3Qm8{5HXode!5S4Ztn zx8CD{A+8c2I+9-X?bN!czno@HKv}|R37O)P)Q z>;1y^)X1r;{KuK+4f61je)P!^zYiI6&z!nSe=U_f;bFu%T`2W)Yihnu5h^JrUk`QX z^9-o1)9><>n7)OWUVDd9l4jGx*pu11#Pl)D0%-HJm>q1)eWicnOb~sHFN&lEJ1>?p zgYnBv=1`HRPi5Dr4`-yudKbuDhXQ(5m?yhXA(mYfQjd?|B+ecq z_uWg3Udzn#g`7vu$d@_9=L^(0T97xp6XWB_;qQ@K2NJ)#6PHi&d();cGjSeuabmN9 zf|&w`sksyqqc=(nZ2w|vG5OT(H}c#; zOyAL#T8{_clRlg4?YZlezfVFZvQN~WndjvBJKHiBU{rw&TV5!)j}(bp75#`je}3e3 zm;2yD5?kkpRB9g+{Vm6(LD>men|DecRujt)oRtB8HFHmQt&39r;F82oxFV;tu1WWH z*X8RF&3=&Ev)l5j?mdZW@_^X=NFFzTB13bYNk;7#(#g9-cBYj|2fUGOzuwC19q;A+ zrH|5YNSXZD@>OP^`z9SfeUoom-(^}deSG@mQm=c3gu7Ns@{6CcbL=k}cS@6Qc!_)9 z-}0DwzRLhnZ;dg^fqVVT)Kkx@;zFo-?{UJWp)UC6jw?=$bcb;lPgI^$`zAQED)q&) z{=PVB?TZDAeK5Mx8#(R0(fGC(j(% z`Qm~{%s1TsUXww-V~;%yYG~$UIY+IyvuTMSg*o#F%#fR8iajYNSmR@iboOYhrcV2t z*ZFEK{J0zWc7+y3cBp}jifZw7u9l5@e`NO1U;N!wNd0@i2*(;~yq``JGt=sz@=#qEIVT{ZTYZ?UXn_5vL9b>C zOsJJ-hNmODX9lM2$i$TIS@6zj2&Ws3`19oA*@7G#KGz8CEgIov9q!DyWyAewChmo) zwU~4)XvlMdE1>wCgf;`zS_5@^`rDiDV2%|BuEYH5)8A4bUN!0?(linJKgsE@)r0Nn zx^V9shf8x}u_hxLQEpN2@`}L0OVrvwan8$Y4nJ*Q^qK922y+iSq~Foxs1tTJa=>z4 zuc-e`#7wkAW}-Q6uiz|sm&^@yYFRZE{Bvs~L^CV@ zCwrvE*E7bQX2w{ukF)48CiLd>H9j%dt*HgtKeEK2CDzz8ogE+t?f;kK*oNnRn|OEZ zU+sxT%nO(s?+0tncu$WC!iiZSSiL9=$?T~fY0Mpff*9zpj6({&{bt|dv7=W4w12WY zgZ`qBmx);5TOV&4)W^P=^nX*+-mrlA<(zTl64%w7{1vf$Ds}BG^QoEe7)tyOB`0rB zzWtPst00!o8&7N>#B)Md4PGB>#H^Qe>Mkkd;>7N{snlI~G?oK0DTZ@VU(R7|sHNy} zhDsm#&~lahDWm`Jvr1a<*iU_B;yac6enxJ6gMO9cTuk`3hDw|*;S+IJ;8tCgbs#4HgWe_km$-&Jy7QzZ@ai0M2J><^&t zg`SsVeC$qYFT2hvC59R4AqzP#rRT+$dq(x`*j4wO8I0T69nC!>(@^dj)hL#h{}#y= z^7NRy>>3?YD6SsFcKWmjj3|&tfd%4Ks*tBUxg*bf6vrHe1XGK)He@d2SI#D%5l62u z58x>K;mFrV5pQP^ch4^2F6jbxWz40IkY2*&JW7bow}{QtiOu2U^?sYl<@ucO6TJUO z?MGB_*Or-%|B-JWCdL=>8h}{8g~uG;pFy2Ry$8CE*9JWM8NA|*JZX1Mt};u@?b8M6HTse$9IuGZ_p9PpdR?-X-;~A{ zx8+OII}+XYu9WV%CvN{dkl5poq}H=1QuyNj%C;hoHW{9dZI zev~?kKFikYU&MxavTCln>Fy8NSp7o`dsNC;i=UEjUnR=%za-o9kL)Y1mc@-~U}zsL zn6=SHw6`vLOjmnL_I!4C#eemJR zpm3i%9-F&k+iW+!uRDf!bAf3-`+ce%P_KnOx*fK~K1c4Kj<>>QLrY9QV2)8U&9HBv zDIA!~GPJ@7?mZ1rc1@o-fO?pl%zgEK+ORFx!qrbTus*d0N@xC+?8enH_SqlVHMd$E z_WYIoi_{rpRqPGd!iM+Si1<(oE0ucaFx&ujY8yepe5-9cO|hlBIhqA>H-?y=U0{Rr zZS2tPmp$jQj##_f8JEtu;=m(!yzSuy#dco|?5p0@4?`H|lUX5AsQoY+3#Zq?c8_{E zzb*lrw30B0Gtr@Ylli!GEUcZ5^sX5Q+ntHMKeNy=vmxBpH^Nb!#<+67F-AUXjQ!0T zqrNp*}s4KO^BbBOFs+h2Th75biAY$IK*+ z*WJg;1E+#r;XKg^4{JGKIJ>b&o@Vb;Hw$Rf@3`Ut&wmc4aGzj;>*NC=0mhK`8m&Ek zsv$CGaV{E8ulpQh++A&qF>UCb*=mH8+2r>07#%ccPf{l{G-AH7hp{F6Hd(=fd&YYw z*}>$P15Pq`GGde~;_ka6pVviC7y97MBR{M$4@6>QFn%`)#mrgZIPoVE+a5>5^o9C5 zBoR@K>fvvCJxt*~SF%w&`|;v&b$dK!or=fm{`8V^Il!HLYAcn6^pNjmXEi-6r^(Cr5X%FG za;DiyGw+mo^dORxS6b0?PCg#-gC25X_qbA}ynmvU>Gzb<^^Q_(A1Gz?GkRBEGE?yv z=bzMN)IEAx^rw%c_hmCNJ%TgRX-}D>%Nc2Du~PQa_tJyDmos@vaq?8k)VIZwz}?Y0 z1B=BaoE-HvJLwh`$;CQFvhFeW-X|AIQ9z*_x>+FmCKpH(_OMl!Gmr2vvtDK?q%Hm2 zYX6H`U*Gj7Uuu7(?m|5NK#UC~HlHJJE+S{Yy**zlh}j>>pO^C}*+iaAjU;v#IXijv zdukvPPIBLrm>l?oofY57$^YgvH-~uxuX!$bOiq4}U88sSn7jP?19}gM_h(+QJLx@n zcp3HkFU%kK%yU91x%zF5wx7xK#oP9r$=Wa@fLR1*E%!?ZGkTrRQG?+*BW^{3ytgZo zC&kPb9?nkZW(Va{4t4V$N9Em8W|!YQDY~X-Aye;>$?h4HA%e&F+iCgzje78N4F}EL!ZqKK3t^0GiweF>OJbuNliZ{~n6|-Yo zy{G5>gLF0eB&BOUOIF?&X_oL!vis1#SF=*i#rQ9rV*!zqCVqV|IRCV3#v@ zOwF_{G2^^B!t%`!ddZZ273TQzy5H%t0S0qU7sg%Cx$AWB-dP*P1~t)p1bgr6Xdzlx z3rFaSSskf`f1Ib2xOe zL@ein`}(uDhq*5^`I$~PcYu3KCk)x*nMDOlP)4dFH!_&y?&`?%E0BO0P$S|dEWmxEHhCfIYm3GSKX zqQ$Ew__n4Ay7g*;%6?67{z+r}>X(CieHx;}x-8sykbz8_bUdDt3L9$kBVAL_qZyA4 zDfst93Z5KELBt!i2A_@>4}pON+{HOoADua`?RljhdaB}3G%glScF}NI&fW>ja7>&L zf=A3k3|jAxA%VV#8R&&~liV?9g$vB~IpX9oJ1n`T-T}2h$LHp7u`);eC^IxLFvD+h z?vtjb(AK60RofUbZ;VjMZoQVBOgM{SM*dI}lr!tiS*g~~^q?efe|gFTQ7=sK=BXLx zX6F#@lbaZ8Dy- zOkzl2UzMyQFW1T;KTK3f_h7z;gGvmD<r<6V9@F6iOdC-KsKaDz$C$n|+Rg(NoDY?Y`OuokYQ-;3oeXQYWE)gJ3&dHuFX269ibLj&gPzAltX_8Cp!{?4mM1u}Yefvj&(Act!d z$g2Moa%mZJcKa%1bFxBwy}5^E%-pLg;`BRW`onzsOSpqi&fJ7r%usUb14{Oi65}0+ z-{1M?e*Ai;Gn{>1;&X_>KZxbOsNdA7;PdFE*~|UZ^}6)d@c#8*`C{>tIy^Bxm-kl@ z@6&22WF<4(cUdT;hb`~ZSNWH>dFJ$6YAfXDCwdsKQ^O}8zc4gkQflYRK^^*FT*>PT z_+Cd9GKqPLw&$5=vy~YM`*=O}=#XRu9Ay{baf!A+B{BQXNPNnFvh3&uIs5&REXGw? zdE&b4i@hZdQFmlx$~~#O>w#={e=H@no-!BqnPi4N7v;O>a&Peq$-MJY++M$uwG-aR z_t)wyt`ROZ~qth(D9p~{JXR`!d;s~m6G?cO8Wiy&1K+e zaI&<;_RaJ|q+8*!mL(27G3U;_CJ!otyl_mBAx6F6JdV@zl;gE9FJ1k!u^X8^%hvxf zTkvd6_F2@#Bqwe7_0YzE)6Ak09hi95LV1QRhBwv2riuD!>0yYa4!lk&VczZ{Gw6D8 zhn?9Zhkse2Z?X+k9c^(rNTWT(agROtqBDd!DoNq&t61-iAuIgRj6Du>7KGuFG7{Ez zqv7lnho%wnaD1JJ!3`Q9av^Z!d0p;s- zYS!r}{+y1Ozv(z#o{lG_>1Yy@j*MNY=<`o9KJ^iLM3N92m53Gb@zB$*i-SF5v1@m2 z^z0molQqL}yJH9%?F_`w_Wqp9`XET9)|lL(A4hEEzm4NswsrJ+YSPoo0>rI9v3YWsi@S9I>9gfUiT{Fwn#k-7371M-8S&Pypsf zv!gmU1mCBIA?{@aTpuz6#v~fO|BYsEMhu!QV788JEVfML!CaUlWwDSTY9u_)P~UDJ zK;NPd=byyrU)IEO19}L_Z4G{@l6{RGQzi+8l%0wIb)IIoGuKaA&YOegH2b~(t0P^&a*OhYjtWsv3)?|0@ zAXhg?r2j>Wk2zB;L#MH)j=5cJDwqYZh5PS0%!@5A6wsgkIX$bvB$4{dIA+f_AXk6lMBYvu9z;y;^d?_S$*tSpqMkzT-QxoHfvBO3JWpQ> zF?<c2bvmeiD7CsKIRO3Cub9W)zJ0nL(Ig7KA~}n$6}u zh$L_GNt-uf2Q+;vgk`Mj~@?octT9fy|!ZDt(IqHrHrf$gW?Sh%NoG`Va zBmUg5$Cyrb(5|pSGJAabMp-dGiq{gvkb-nGSd&v<>}&*w!`xj@(Z}F-y1=GdSaMtk zjXLSzP%cS)0Ma5&l)>3?mpttqo#n1Q9;%^8QD(gS1djPo+ z!Z{4~^w&A>)9f3mb%5@ZsNueDfUXhAux!o@*kS2dz9^GFdqaqGBaG^sgBtmb;cSqL zy_+=Ho#dW}y_L<7tdoblfIQ5anuiNnc_^;a41IU!B7AidK0g=jKdJTihKSmqjd5+W z@vT8Nj^uK#+C7`RH5(m{aqfCL6OD2*@Vr+VhDWAA#mmB`bCTdYS*^pI#En91zT+=~_%^_pH+dJ&V0 zEzyUb{^i{HZ;->ktHzp4U)Mlpgxw|XH!+9B1~aVxXo|358|msA6f1L>$ZM4-!TB=dj-+E69Td0%yeTo z;*Lk)Nw-Ki>1zBi3s%?0P5)?=OpQk7u4uf|q4vV#p%y)h)VRk~u&<4?$*qscjmfiH zo=}O)A>uBN0P5Qp&y(ZcBj2U|E#>qTQv058klcC&J3L1+zqXmichZI!{jsG=vO7?3 zA=my+3|~l`J{nJ+PCa`hF}93c*;h{`(+oAw33cKe(_6*PNtN8??OEclBOm9($JMD+ zQkPYV`)v*G-tR`uyM4@nm5Q&L($Jtt{@qn5$Fd8>fSHU_=M{)YA~OkVGH>@TyQJwCF`lZB79ABbvVlUT z`!Umy9+)%KVO~&M_am-1p}y`-&OV5`i6ak-2kdhuj!!S4F8+bJFvR~$YTbr>+k+f? zl-e7~*I66PehPXeM@Fzmh}hhTI>}R>H)<2V2N1t=(iPH~9(j{C3fa+>`VW0L&cn#l zM=Qi_fTIh3Wy6mOgSW_ws ztkqt_GSM#jAe;Jpkcs&pB*d4!$oM2XL(0T$%U9`GSJRJN^_N{k@s(nCr&6N!|CH4y zsw9;fi(lVAl41N;90%5bX?HDL%VSqfEV-$r4my_W;K!$0cx|GG&Rv+L`ojQonZHqX zk$HLKyzfU^Vx_+g8n`egkG+wJyIisMDQB8Tyir1p{A73lM(hrR$=)D%Gs`=l``M4T zgdigz6o$P+k(wKdyT3z-Qz0k|4ne?~V3alu=Bz9TcN+!a9QBzQ9|AD@mp@|k{qZ^4 z5B=x+!iKZBE!=k*QRIb_xKX&N@Ag^YnG;;bWg(0{4@a>SC86ca@gw z;aP${bgJ|baoPa)r|=p@o4yTd0k&(^+LJNn?lMCMzJ3i8OB6E;I7+PXbvd(8oS8HB zku!#+^laaBr038X5B6v^`()f}Fx z=E(2V9L@IRp~KN;D1O=$ryl2``^F~tGPW_^KFopT${dWGnu9@WbI{+uG1gF<|698qDhu)IAi0 zM5RC0-1SCVb~%->7d5<_BSKy5FrdH+0cR~>ecA&5^7^g=z2(K_*4XvX2A!DuqxMRT z_25i|9>{&mtT5*VeW8AqKo1L)?>EPCdvh3WGD8IO+B~0{qGFOM+CMi%J7RkO1r|uq zwL;SZYvd_yF=vN8)(&z+G5xQOHJRJE&I7tjyfC^R^Wy_FxiBpSDi!ur`!`29#FJ0EiIk~n?kx=LdIQ^{arbgOMDnNMzg zhd3R}*<{r);_ztd-{jvBi^-?gtK`TAdcBu0zjnMz?sw!aX97LqoLT0ZX*800{wjGE z!r5gov6?ttgIwE+_CnNTB%KBC#<>{mj(rnhhuweOn5-M7Tu1H7-KKJx0d zQoh|K&Qe?1vQ;S?S}Xsjg;aRcuhNc~K3XaFW|OBcRmx}Lc^G+nIW?HYe2)tc_-A7G zV7`t4&kK)#kb84BI{l+k()gYysNd`*pSPj+C8ba)BY0j|G={rJjrm&cO3`Nr&!PhA zE`y7ieOD}2_lxAuL~?a6X1<&#l*R1|Wzf$8*|13M-!72dy3A&L!t6qNy3foZj`t#7 zW-8<+G1$~mA+zaMFDK{zLT+qF9p*PR?^eWcH{Nz8&IeKxX-6zSNG!iW4*i8Z+>$t6 zLF}Fo&&&bx?Dyo`mx*f;ETPfsCCteTqB|eX&)DBb&NZ z%g>R2Wkq%k^k&Cq^jj^wEUSsEuiE&-oIJDlweW!XSEt_U;glh{d0#{PaHp5d#uQZ% z=4d|55+h2ik>Ax0&vG2G;j9a`(}VaA`FYGnwI&{bHbKEidKv=v)u9OFu6bMjUpde? z4BO^~p~to`bY2{Wx*ft0>J$dK7Yfz2qQT!-JZt2yDWV;ZPvrif!qsSsR!Mkdg#I3bT3l_j3J+| zGr^F0tPw)lkvGNM1fRIi*z2+>yqFvIi5@+hYZf^9))FtsGu2$tH^T;Zx7#A*JGGZf zR?I4QK%GNQ_%px-Q#aCczsMacj(cI!5kFLS3c{F+p-A}>!ROY-EAGHdppUWobA9|d zFW4HLf{$&|@MUxc7HrGHzj_*v%f-4)km{0)wW&?9ZE`cD?#P4Lp62WkX@UQ`v_$!Y zmN1HGiTtt_oFBG8Q4ulzQXaFdnj!jqQ#6g_^RDD#Xnrmdx8>sD#$1dr)$sjqJXcIN zRA&*ZyRE}MH-Au)U#UPMph#G>(su-IGmpnja647kddsyA8S_FHpgdYF?-Fh3~Y6h;lru!sA*b-dZ3!t=mC-1lm7 zl-C5zE6BHUMC~U|SWeH;-+gX4-PQvk$C$I;%Nu4LeQ~C>KQ_Ln$37(pPg(|Jic1J$ zxC7==8H!^T;b`(a97noGP>1KfZJ|o8DyUU+F8N_Adwy22H-cEM#&GLA4XE%y?`e{gm>m-EY)->98a4$Go+7uj@S+7q?^q_O% zt#?sQ7G06W4{wM^>Rox+?x7gAdMal}zLc-ON@e{9_T1ljFNT{wNnXZR{ykU8NBau7 zP*N_7!Yicf`wDpzR4H}LnWy#NFM0X(xBS{g{GL!PlY;-s+hc#FX?P9nURVQhwX}dq zTF9%^%>De?*%|bY4j!&x?sb7K0xs!c@k91Ca|Za5eUT%bjNxu%ii@q-MZ`Xe0CtMC zjb(Py1x>zI<96;aoU7JExHsN|S%bO3xNt)K|GPHoIYnT9NjPSehhwl=1iV}$FxMdh zR)5LsZib`Nrf{5_7!FT*DB3g#N8p4oOdA@C#pLv%>Q;cSKH(BYfWEInYR@dJ>u^EUsLqj z#XVDnF#13XX|;6^J$jCV9bt@lP)aKRX^M@`WFxGCnJ zH^XXb0(C!FV2Pm>x>{M&&&l71rw!`Nu)&r-wm3hY`$ik=vBSs#o>v^OBE<>WVJ>KR zz!e6W?r`Hy{XEVHoMZiwzBUNCRiQ|VjYR7;(U_1Fha`Fko3u+p0e3+69!i1rtu&uI;+Z>lC<>64fJRBv?H-4LkmEH0%>1;E+uWE|PQ*&|habvuz zpMz+6C2f{vV#cyGbQ+V4*^?T;pbLGEQV#=}>HB6}G#tp&yQYL=qfaP)ZwNxO9{w=d z?~Tcvd6=Jf!A*99yx?_HF86(%w5(wN)Cwx*I$W}~N4uJi=s&>;9@O1$u!DO)JD2*O zaX?@fdxQttF*ny1$INYT*3BBd;@GK2ZALQKb5*K2KYzJvhNAWs*mc+v!z|fh+QSC( zPT1m_hdr!jv!hze2?M5Z52>2F4XxeKaiC`JA@hJ2?p&wtKiLm=O8qfOI}n}9`0wmR z5b}Qqql;@OO3lKsXKxr{zJ?){_}!Va%DLp<)5fXf(ID#0om7&SO-&_KC2qFl>&I1;4(Mytn5qdQh%W?;sX;xJSOr<2~_jklwAZo7zc z&rwS0){e8!Y^9jxFkh=9x&AQnbYi;EQsVz6rF7=w^ZESA7pb2R)B8SS|6D0`8O}>* z@VG-fzwkmS#yoe#@bk9h;}#Ip)A-q1uj6BRo~hrDK1aU((-7)7I{dk>6w9d@#Zpq6 z-S)Scb<)2`+-op%cRusey$j{{sRFSbR3PO+1!D4z9`%#dM>r=PJXj%Lse|;2QOILA zg*0SW=WZ=_WpJi>gnWE+Idyd&hk5@l@qC?*LSC6OGsc}6<J+L%J~|m$@x3E;4(}y-+;ajeUxJP5aNXvxz#B>KM<#T@J|3IfrCa=uv6OEZjb$ zsJDDOC#EYe%8A}rrCax#%t^c}v1cC2>Ss@7*5#KHKbD=%7v6F1`cZ0UmPtkRSMheM zko=LA(tGAlX?*IZ8274@6@7n+Q|WK{V5I5(jK5d|Z(h{E6fZ4!(zg+HPzyuMYGTx& zni%t}CZ@H}#?uShs9;V@XFGQP+UO!CQ4hwG^dUzL;Qqpp+|vlzCp7wkweY(4q9q7Rl4y|y)l?@KCy=sS@+O`NK z-^&fK#M%kwSm14jX1b<0NUz0c`WruQ(D>*q9So6t&XD_^#Cm2=El)JTGfz`AvS;5$ zq&b%Lv_N0Z;v8>VAQe9&;aKMKo&ken2TJBmm=NsmF;%Q*T-5^z72zVuGX%pFg~ z(1dhcGvU7I*DM^p-4L~w=3uQ`6YQOs3zO?jG0iy-Z@M(c%l$2|(4!R!BUb9Ufh2jmgVf!D&rP1iom2)`MDLZjTn&V5B(*oc3*jUqkaS(XbhMjLpS{ z!;R5~Gu6u*vw`SL81_xWr8db}AJ72y#>^Dcss~->y2r&wBWN0T?LUXXp=$_S3j#4$ z<%bKCy^+c+bK6oEY?$PT)Nytw)3-t9|7W0|VjfNy_lup^YkX2?h_~Av-O&7l3+j70 zQ?yvM` zrbGZHKMcg=p24_3DFizaiWpvNe(p+4?#w+*YTiG{%m2-!?p;qMx2c=_p z$m1l>Jq!7@Up(LF+~9r@G2QnxF`nm-4DOTu=6kK2Ko1Q+Td!71XHKiP(Ai--Yt;ei3QR$ra+8-D&*K1YUnEzQcO&L-IzE_p04G> zj!$ai@2crlr$@z?huY^@gZMs(Vs$YuEy-3^_*!EtNSWA z58bSg6H64_AEYkBqmWoWYAw$Ldx+!5dCs^^Kg>sV5piDI%Z=Dgk7d2w0@3YTATon{ zQM(Fc6umkleYpp_gnO{`+rQ9dN2o1-<~}O<`^~Ox&7C zJl}m%2&1#2_GqGh)i-fJ;j@4ZO;{84z# z{vv*V`X(eEKg6CEzl3%6Z}B$skLZ;Cmwl;?LS;@fYOE@-Pp5a|xGFY3RE3p6b1d)D z91qtw$Ad4;p+yXTb4m>Xk@Q$sFatbNgPd3c2L@|0bE^fO^x-@<>dp6Bw#G?nEqyF> zu3QthmHwJ%oCP=EmKu-*KYeZBk=5iCTs@K= z`5ZGuj5omt89Cv*ws49zfc+6Y3?E8ga}OO%oX+gP1FeyDivH*h+Bh>x8_u7a)-W~J z--;LMpv$Z#zf2@?q_d2j7wHQDoZ@CC}qAbZ;W2^-9JL^-g#_kA9cNE=b5tLw^}D{d+eo^vHl+ zNOw#&$b`p}OmzQ}g^Etun6^9%DxR6>;MpCng&BC%ECaQ7)1mF0f!CkY@%DN*w9@K| zwY^i(c{lr)PNZPM00cv|1&uW#8`%GtKA=<4l8e&CK1)y$iZV6BpMOH*npUA^erc3@4^gjp%ny_+`> z1Brz{h~rhK$z#cV)ybVBDyVbtNIOD4D<@X&Atn=lrxH^Y#6!(R)L#}--{x_YIQ@4n z`SVO-_#{48A-OWKa#By~*g5pb<#H_`Hh&sWE+!Pvn@DZ^5AWB02Jv_{HTF4t4xVl! z=EqJXZyw1t<6ris6U(D`I)@nFeJc4lUu!zof>^$n*9XY)PjLp_)pC(UJ>9gH`RDu` zM~UagJVw!{wZ{`#(dt55+PAwJH{-t7i19g&<%uZiPOs4jN1oo7AP)ji^ z5h=|}gcfy|2I}c`)LxXBu0ftYk33yY54$rleLg)bxo-5HwBz$oSFu~px+XbyNF%j$ z@^04();6~j``2>a;1NZP4WewMaSpNA; zsi>)E4wrG6xYC1}HMM1;AH6&~4=Y4pC$8r&ng5`EL>NvuCRDo|7hz*gii+AZB56pq zxE{;Q#KG6a-7~lNzVC~3TOJF)sAr;z^XpgIz7@LtKZwvRpGD-dJFOhgM<&S>&+*zKb?Z!&xP)W}UUbx=LC3D1gZ43N)$|5>w4aE$qg zrrn$7Jgl2&3x^a3*r(EyH^mjU0UoH5dST;YZ_H`#i`W5vaC_F|xZVb*_dx4(Pqy9&7XM(B9XU9uNuq{#xT_krnb9EYR;4^UI~C(Bxd4SLe7V zk8F!exAalXIn@W(>7p0sSX?X9!O4GgP?n+tUwWor$aV0Nocs%Y&n->$(U+c#lO5Zl zJLfC;YZ)VItO*u=W47dEbL@ArL|5|fttmFRa?=JYU)i8*lmrV`NnrDo`3CK5k#K^! zU7>bZ{I4C}xhb*S2AW0=m^s!78J3)j;qQ)$C0-~}VQ$v+KooxuK~0|sc)yK?=A9VK zdl`#a|Fp+_y^e4>6VH8AB5s5w4uz~T%n`J0aEKf2+;!mj93pNc_x zU2ssN6SU4GVP@9^TsYAIwl884%6`_MsZsdRD;(y1LXa{g5O)=R$ZO_<;xtd(-|dDz z-=!E9qpU$XV03>8tj1cwkv*kZ%)>v$zS>Y`ZC%=IiX%A|@Y1w~7JG$rj@Y4ctUVUe ztNPH(7DGa8ux^zVp1E6MZJjyN_A_5$t|?>_O%OMgUe)9@8L;N_u*SaK z7WVb@%7!_jc#;!3s!LH&*yP`tq3VuvC)|<8y5$67_ycnCIn={;$tfLobkl)DWj>4 z@X#Qxz8FEiKAgUCo|^Ky7R3Ku#C!?g&na^HP`=OZN6Fub(ShV=vXU;bHX}lEFi1-zxdm9yWb~; zFro)0`GQ=CSh=vODig6uW#Ydl%zI%U{Z5BcvGR3^Xix2BCb@J{fBFbfBL3Kx2z%nS zHnDpwedd03%q-_oz}n~*)<(xtQ!nCeO7D1t0reM0K8`%SRWEXTt_@k_-OAi7f3;FE zi@J*H9_|4)m52_+^F7qf)%kjw#QkmG=vkqrZy8c5Tyjgf|0xx-ck}d8srdVrr!C8b zJ@uBQ+*|lFucqWB`=-vw#dk~Ao1f9M*!r-jSa4Jf8B{6GZLJbprDw$T=jX+w!(g70GB`d`eo{Ua7WU=O=vGq^o$ z#(C~4@C#GL?-#0AwX!*Sq^KdfjXG+ttMh+K6Dv+|4(L}6oC(&%>sgv;!3@*pp)D|V zD`$f`w?xnLoK;Yug$>`daOF}f=)1SZ!G~=yIZqc0F6rTeH~G)awupLYgin5^=)c4q z<;3I^obuTeS;vK9EzFyBG7tWGzNOc zpnqB{vliOpbRF{+7scbB=tMZHCBwch1u7>yb5?gM0=}i8Ju5^{N2kMZR|b|*X9;?p z2~V|btZ~hOMR5)yy5wMGZZ?iA&cei}nONC56N9gIha#>!W)s&REKNrrbVJnUG#o$J z1!7?*9F-J6trPZTV4L&5{* zAX+)0(a|1OeiFoOvBLW*>e+qFv23;(3M$MnR#mB1p$1{1WcG4~=f+80^CE#Dl^x|+ehz!YWFy54RyMiq5)CIA1&*$B0%^o=ew zf*R6Ga^6eSJd6n}g|53F1r&p62j!4If{@=lem7A547zw>R&@HR8Q?j0zu6mMudvS^AnqMOB_|t!)&pdTv_T?w^ys(ET zojpgN*-xtM+4rp}7GLRMETIp^pBhYmdShD9?=qF#-aUym&vC4a9%r8sYpn>8?;p=*|DHVa-E36`(kDgm94jw8MmE`5_ZOg>?VCIf>DHD6L z%Eaa5GNBV!CQN6sXR1H@irR3kWR63x+lR$R#W69o;kd9_cS>wpdQQYvT@)#8uZb0# zYeZenJ+a>Au^4{wshBtZrFibZI;h_#QMlzR=aGLGi*G42R#Y+VWiy0lvZwQh3QlfQ z#aC+L-CC>RSCty-Myo^DLj(J3HPEn16OX)G;O3eZc=w_O4zULKb!khOyln}WXf1fn z(t@!jXVBDemgY@utWY}+64r(msAhd`%4ZWi zEHuVbU3yV&u})WOfJq|^aDKi427ESvc}81UR=35;M9$cJWQdO=jL^Bh2`?txHbGWI zlRiH27wZR0INyRZ-0ELRaBYPhv#K0magg~n9?tkfFaF{vDJ&YCvAfb4r>dOcq1}Yt z5n)oCwU;7mv=mdjx?t)uS7h|2_wRxyes1@{Km6Rg>w}={8ivo7k?`Cajrazjs6{L` zzKFxX9UYLL9M82T0maLc=q*oyi9r`^RZD~V(5`qrqZ@mv(vkNn1FNkvaWgRs7@Up9 zZaH{-DF>%Zb0GI1u20RzkB3=^>5v7dBbn&ooQcN5?pQG=12ysK7`dk_9A&9E-M2Gt z-c3ee%S2Ru?0_UY`q(f*Guuj(24sT z``-STwvlIIL zm0(C!Q$6!$x)lyNSR%mM0)cT&_3uf{yj0LHQ}~`es;i9ggTL>(-o}XQYK)u^W5hQz zhTlx${lq4{$KKrtLw6hVZ^9G--_3AQ-x8yftg!Z!HT^fNacsB8;PZ|!TILK#3)TdN zx#H1bH$-lAhpmPOa*5yDZm_0#h1xc8Ts9ifYa(r9XWWab2m$RP$(|Lrt7~J&L}?)2OX5b0B{PFY|oc zx$IRXuAikx@$Plbvi@EoZrL{JEuZ*ao*gU|8J|i;v1=LMJNFYy%EZ0WGSOU7CWi|OCqilMVUiMw{+M10#HLX(>LaP4M@SWmyh(`E-@U=nj)d1G*i2pUErsy%m42_-4F`=JwE#v?HRV&PN<_zQc z5`=ZKLs5tWUTHd^&un@u!(1>uzKPSt4|B)u6>hMg7P~;l4X^Fp;KB21W^P#Z*A=5Z z-LT^f>jSsl@r+*1mGRyfKF1g4jsgGs?8@(D^~^}jcoGf8Zy@4kJG9ynhp4_Cm{$@H z-NgyKUm{Z0rywG{$$MzNt1II7cEgqj>3DC|otk(i_V3HWiuc)2Y0N>v(p+fG%7t!= zTuAbBpmHJ`oxQT5y)z58wpmD7mWewLx>G00z!CFwy!n#`hecfw_A~`oUL+!Oen(V2 ziv?qE_}URT$sCj|Rl(3`69|KU{oww|8-2!6dwH(>4qPy)uM?)yFPLX7;bqROqR(`H zA?Jc{J=~gV4Uf;vcCfa?MPCQ}Yv2T*B4_xPy28PfIY8--*vkD*_lb767jKJ$wi4KV zw+3!l!Q(3PecoGObW00p8Ji=Dxt!+A(%;fRO=boAx;mIZoBB@mK4X~0@}N(>#VuyJ z?=r;2MeGxZWX9JGQ$#Q4UTb2LemKBVf;1yLWN}|LvyT%3;-oODb%8edgRM1nF}XWd zeRRiH;&*#FHH%{6CUJZXb@7QSsVUE8k32C`hZ^^`-sH^b^rFO5Qz4JOPkgSmDHm6@ zS?i=0@%FqzM6rjyYn4Kn)-j*<8#7YWxCXRleNvxVw^6xBG^SR<GAy+^F((XN)-%X{*BdgoWPWj4V(eug4yGkm<& zP`)=lcOuu0avt(L;ye%K<;#5CZ=JXfxbyp9PNU<$3St>E0>;UOkA_?vUS1}ic$JBA z)<{n*DisE-LoTE4F`JzF?bH%+GMIjJ73$*bDVlSbn7*S}gs!Fkd^z*ZdHlDU`U~@2 zlG(#K={$Q!nFnLfUL+%)29nd?qvozf-rm86{Y2#Zmekl6(?_#4mwiM9CG6#-CuTo& zn48pk*zYu$b5ZRE&{w&=RP1?PDm;njtqQ33A1)Iajhx@%$9d0jtnKQ_#j^mV53|XO zuGDqHyB!kg^P7C=Q|6uIZD&Qv6V4v`a!ojR-4;%-9`L&7VzFMmXq@^+d@29P%Rfbz z4L`)g(BHx|tx=p!Qo+1Ws#xy9UZ78Em@`Tp;kL|reWHPVa!uwOwLtm6mbhu4#h!C| z^VsXTles3h2WxY7S8F_*(Ha;2@|1Ny|3htXjaeC&`q9@rNf(*l^^nlf0Q&RV;s(9k zqlx9p{pk>DkI#sQ%Ku5D5!?eu*kb4bd(3XbJi#O>T26C?_C9wkIPHnOZ@h6q%MWX* zlP7i!#I?aec$CQu4L8n4z7c|cv7u0#7>bfbq4>Nh6hEGX;+ZTId6z?&u@wyMl|j(2 z4@AU_Kuo$HfP^xCtWWX7gM44Uz8_ZX^}@Y<9(XHvgWEUioSQlKjoC59lbw(=!V&d- z9I!No{7!{_67Hju!)+j`u|nz~OU@By7R)@(!1FPM#zAB3O)w&U7~t*@Biy4GBci_v zD$|%F8D)knCv(VJTcGQ23-UPSzMMTXmNuMaFF|CWEsik9WC!!bl$y%_bdw|(gr0WA zglX=`QYd{oe9!c4ws_4tz)(-*QjdtR@`SpkC!XH-z>_VU3pbm+R#!ckHSUQ^^mEQx zOfQg?A3T{=?i&$|@2kV0nBUZI^tu+40l@IM04+0*22{;%w3s?D6b^ zM%6T&Dd>s;8@l1z%XE}Sc89^*OysF#WAd0B9CXRUFT;E+y`P7mx?J|#^5U{{C^;-=53h?no?{ z9)`4o!GLifjt#%3eBfl!eX8UF70BE(lh>Ug2w?u*Ax{^x52$Fb~@9e;IQ7UD(^^?1Gf1%$js|=d2^{ql`Jv&&~s# z$U}FoARk>qy@6acVLG+vvE=DP%7q?rE}J~ri@2&A%=3_6p6{B z$kT`MbNu9bG;D9VSim)^%`tjePL+$3PRh$m8FU z#Uf=AwU`CP;xV&VlpKAzf|)Nn>4o8;%*OR*-d8g98aL)~E#~?lp)Rx6w?zEp9-wg~ z^UXKY??Rrww*_mUqEuK-VeixFQcOfIMO?r0UCi?TEna{5D<(2as$h*O{!lAdYUC59X>dl5CQ8p}V)Tj@_%*gA z?u}7;@wDN}W5RT8MA^2+!i%lZY+4)E=X5Zumbs(@bdm8$7aN5h_RnkTqjuZ5fCmwL$3jJ{ZrLy}d9f6q=ty;kP6Vvp$8P{U6S|zZiz3|HANrvyTJHIIsOx z2C>{1&ju~&QQ2Hzi>g993>j>XF*6*{ro@r6cARi;nG}v= z*bf!&j_+6413K0VH64BMg5I60V|?+K{>^jr_gzc!frf_2wnHbiIE=c`9t)Or#Ke&a zh~L`OcVvICGv|$@qTy{CdiU>!*7wp8-LX3w4`t$>e>QGh%RyF69-q4pe(uXh*^E5& zyp)SlLC$_52QSIllhkui#yV=dk4?2y_0z<4dSR3~G37m!`+&|o5^-0jJx_tRc~O|9 z8_x5=&`%1)=%;?<)XX1?ZQ4uCW)JY5t?cFDUhY$dJ?_@qVtWf)XckD|d|E;;iyd08 zB0pzuaGNJmdf*%qa zd~Z!{P0b4PS=ZRkSt~zhm?Qm>8H^&$aBLlOhsfJ!CYoT|eq*S0G{&7gW1OdVGLPO! z_kCv2YG;9bZTfLEm@~#)IQ>cF1D73MJ$G(5=KZ^&oO|XKEZK#5pZ`KZwN^)RY5i6~daHZTB*TXfaMDcn9)&?7xxybi*=Z!)X zs__2aT(bmkqYhNZ&zM8cc1=HpunAO%Wesxii@M7;W~e_uR3>~nmWf{E!;8t$-IGhj zB`0Dk>zOw5sgtnBsG2z{ugS-?h~Kj^na7w+PkIN=!)VX`|Bmb%<>k&@iQW0dVmtHF zpN?n77jZtbA3ZQVIFqgq{f&HV^>pUFtS=Txn#P2<&rB{E^-gcYE9yJGGvOj~8DE|Jb*pzWpcWnST?> zr+ZqsZnSofiAOP2<`*SvtA1vEb%V}hP(hM({)sf%Yy5s!{Vri}mp5;h!tg|yb;e=2x zN8}khp#3*HG@Q4^*agZxzYSvOYw&hrcB7spy69S9Rx5LC?PrFSBh4_kP17Fa0=+A7 ztE~{t{k?OT1OaKb_?Pv9^UNSyFwy~cmoevkzZ3eOaHbDOih+)$`g3s(}~u zsQJ5e@nzPeAKt9;N7^HQs2}vl*h&64!Mg8@G=Ee@_#;{09|!ySq1_kd8t93^^ykak z_@Qd3KeqET|J4q{Laz{L9ty+LpAqP*8I9ks1^QIPVAH}_+|6x|&2Al`t(^c9NfK7O zryyIaGa8R{LByyuSlD;NjYH{J9o-%KDl;LC&c@-ZIe51^4{F=4rzqt~l)L0;fi2{667?q}fg0LdW&?sQ+Y#g*tXn zf5Ciqa{nLX?3N>~@O!Bxre3r_oq+|$b~ESPS2Orjnqv1$dKii0TVRZdzU)giG{IGR zXBz9x5S40ydA}^tnI5Sb-E47Q&jAnk8?SsX#j+Q!sEcmumkXHeiMeY$usGENmE__- z^Xb{nrq)c(+A5hGw;ee-dHEjl^2_AQrPM`Ch7(CA>|eokiH{k?<>gYDybwPR7)8?9`)Z%aOeRmnA5bXjK;@{Q^=K9LTtVeROd6``37|KQ9%reoSTPCj3S8|`8 z!5-An6^Bd2m_gLQ4VjO{JS@9H&ZKC^*+Wv!sIwq;n-HIQOfhHftu-}vJ9=H5n4#rL z&Bc=#&coN2UPn{T!O$rd%X!3@ah`?;v)AK`McEMg+NswZp-$6*oPA(8`&B2Dh^i{) zdNFrvY7mI(Z6f@z<~cdM)*C&5P_;j*j{0T^RtXml3{|FL{sEWGh@D;Io1rY z#0vv!TzG2(#r-Bv%cp*h$aQeW4HXx-tGQu#m5AvxftoMpUZc+rMj0lH(Sr~G6h9bHs1bbw` zC@7}>QXGg|y91!U+8>?A`e9*5Up!UuVeQQe8yr2cdM`a?9o(?Cl`Dp@r&~h*%LHby zzdzy#{rwJzSZ5Cj=Q1RWu!Z^%2_7;-YA~~HGmcv!>#HUDb+JTNOG|hJTEgY1CF0qq zAISapXXXn`As2iwpS*GhaXgc=iBp^qH_RFLE0`JinI4F*?0ceKd_&&@y+?cEGJB&; zRG0;F!Vg_S1Mu(0K+Inogke{MAeqeE);>X;!4O2RTo59+1z~Gp5Wff36;zbExgYM+ zyE#whkIB@ks#XQT`BgBoIeTcKb2vIai-3Gh6fDyOu3N<*Oe+>?&*HFmeFp?`E?qkg zk1m!Zp=&aT4W zx6gC(`x$l^ZDETOoEg>svNiTSwnC1n6$a;Vw&79>Y+$dM<{C4M-e8J5Lrt)cn7(>d zTgcd#y0F0%)vo4T6D_cK68i|4>**NU^tZ0m(oQXOLDo1o7}IC9j`;wm?sy>E)dR1o zr~4$(!$Jf+2iDI>nUI;s%n#{#bO|~4L2}$<3UT+iLOiE_k-_73r9$|S%ZKs$ zG9DqkE$6gC>?J2&beEbuIrCoXGIMm9y<$uK#gm+!?@N#R`fFnQAnMyw$uB47m4EJA6-KLP<_JP#QiTg@?Hs`vPNZxPtk$GHI#BOr$pnv%}lDUQi zD#TS6W`t9Z$PQBoPjd3J#Pats3NiMpTpXu9;lm!I)2o&FCrvt&Is4};naQYswp5(V zXKyC^dz8BN=5EwmelrVw9kb74nZeb(SS)=g6Nj$JM30*?5%WMMN}kDt)?1la^@+2E zzRJY8Z!$6ai%bl9Cleu0IY;h>Ozf$YiNi9Pn6pG#>`W3#HBL|q}PCaNWy^1^NKi@u3E>dlnSJRyJ27P9#(cem&Be1&X!ZF5hgZGbBH__KjVzr zH)7P6&*JgAAEHIpACZ5jQEVNe0+}}FFYH%?s$jm@QImreI#|hiELxh{oN3D0sU@Vu@=6 zYFxwN;1Gr@Mw~CB9)gIkLAXav{nfny+&<%v;2nNAT@N+f^P*SY6P4~B=u+zj z1^Y_d&v3!Gf2FwA+ZnrZouHBBh{iMr_-5HdPQAox8-3vqByi#E)6h{i@O@y7ZAsR+ zDz&Db#G}9l;f2iqpf`Ex&!!%r|NURH_M7i4g}#vsCd3fOi<@eng8PKudp$Akuorr0 zvBzeuFZvMAlsG-?KoEjlLU=v`N5*rmf^#Sm+(J=GjQ-&mh7`_4)Bh2Q?MFf|bU-j_ z=<94Y$rp37gD_xaFy7A(!M~G2VNIRdhO;mtFSAe6Itq{1M8h^7un2C)=WdT>N86(~ zz9W3}60lJ<2|o-{*e~B1nnP20dpFedPUn20?wGqN6Agyh_(*MK-0)ni3eH2^?mX68 z^WZ`)Mx4sSEmMfIReikc;0HId~+YzHXC=TPM=7j`;yTnq9E-c`{s1Bw*k1 zroN*Y4+VDHMI!V{D3(_R;a~P29Fq8AbYCxw-R_QUCtUFFcGf%(IAP#ECv4l{1ncX zv<2sFggD`_Gk@d9_N*b>p{$E7O1YPO(Z&XbJ*_e40c+T8tdRVzNo(72#*BSWOz4DQ>A>5)zMxszy(hyEiS+|en;9p^*c zVIN382zBG{#Ldx8)TgcJWi({YN-Js;)LEuekBA|+{-WSK&OQo}w2uDlEzA@rZckiA zEqoDm_5Y|#%v6Y(JPytwz7ykfRx5<_W`+2+lNvO6`xo-xK3oTiiWFkQUfxd3x96Jh znLK|w&!_YHH?aoL{~XtoNnDpYD#S|*YX7Wt{;83RwiR+w zUL+S&cgaQ4Ub%>t$wmGSxv-lp7wOEgy6G<$CrvpALsu@|Xv&5Dr83cm*{GdjjWW z;tfwfRLI2AVqU*iCU#GhiHn>&q~1;@9tU$Bh#{8ukcr>(WFo6dCW=*xMK1N5ORJdU z$QtT@i6vtD-V*VFnBHs<{qfbzh;*iBep;D`eqAO$7sy3lu2t{3$9W)Q?s3>5G3NDQ zv9;o;=zgj~WNMrcv!!+Sm*OCaB_&H#56GsUvYM@!Yf}EIBJ#WmhZwys8b8SFN$hhLpO{SO9^&2Eb!V+}EWsu3=&HpcuC6Z&CHnHgnf!dVte?ao3%eWJq^Hu z?LpX^9fGIL!jL{K9M5VZ@bB|TxE4iWFW5hRG8&H(1n$=h$W?%0sRCXSdanOO;^9-y z1-lrIH~Yizenu$ksUgS>2}Z7zYlL+mR_X>|;Adj`8NS|pA6)L>jig3TEMXSdvysG& z_HI}tC9X5W*N}BJb@I6b^h9@%Htp5#%(lm;Iy*>WiPg;UK1D7Teo2Cn*-e^E!FLJz zwY0-N8+wvEIbiO3M?6e)hSzO+tC{)Hu+C0Pi(;fe1vi7#wDRk?-Jx4i?0( z&VKlM(jT`c1tQ-%7{e!p;QF&rn6?f_>5_0vS{)AE6X8&`;o7C$RPU@l!#QX}!cjdf z48^ybd_P(TLNUrR3~%RzVZBB;rZN-YqB_0lOC#vFiG=$WX1;g{+*OOg_DAhdG&2sW zsvU56Uq{sMOF;OmBq(A!VUD5;e(83_7w2^BY{~W93@7xk4$7bz=-jywTZBW2Hmltb5iR&!kJ)J$hsphDjWQKPI zW|(1U4vQ*tbo$2vmCr43oF1Ba{jAZP^;cK!?dG3wz!7?>%u-ySSKx{-HOyFdbVFj2 z8%|}o;kG^bxsnUB_9@ybagtn}+}!sEH5B6NCu%KuXB1)}aX5t-zMOjOPiid(h}+la zQjeIS5F?3`4dbZC@X((~{yR+}w21Aqc%OZIOcwQ+;ly`)9uwD-CzB&j=52S$?REGZ zk9oSD&)b9RMcf|ZKKBFLsmE;n%5{S8Pw8WCK~29$BiDo13eJ__y21C^phbP?H#L)| zyv*y&$m`X-h~30}rx%<}#QlUHU(=t5@^dXp;C#_Pa&fLoE+ot4V$M*xSk_4{u5xaX zwxe7qOsF}xk&A21nbGyBOxWCE*6cy@T;`;or1x(rGp@qu>0ZX#V~dmYx3C_nPCQSh zKRlkg_GD_@LpCxS-J2YG59h)CDq`Mjk?6U%NF=wBiGl59q9d_=-b|UOT|sQ$C=*|Z z@vqj&gx(^V=r>j-4iNu8ddb8zK6c#MBJqQvp^nFRye<;DoGEuFUnX34k+c7ii6>db z!r>I>X!w+fUmHtAoeuqr<4Q&1vr>`Ju1rkk98pW=jJZY1#bphJIMIuH8fq@(Hiw0| z#ZmFvqe3|MKQ6l7t`ga!PYZ!_VxIj4k*IQ6blZ59-`O>>F#V3Wy!0Vw(btKtkJ(>@ z58@y92H|$`x0u(t8Dx7^px}Hs>u_}pPSHe)drLIirG>J`t?`bg zIad!GX6qw#k^$5QwZ+7)hWH*!A7VRWj7g<`cNqD}1~WK3;oRTWmRLeRhYhnwKa<}a z45pvpKU*wQr{+Mv`G4b`*rzDPq4Tb|y|_tJ+~&$U-)|r2$N9nQia)N53q)pQFcQ^5 zaaIPs}*osNP#Jd;_F`vu|J*g)hI24HTkKL&>Q!JGX{L6?{TGuI1)<2~`xzysR! z!|U*WZnV;4Q7y&k+s^3p$q5o8C$1ficv9+s=bjE&c*vgFQT8~iZO@DrJFM8jKE>NS zi1{B@J79J>b9?KZVCN%6@GKW_fCc@IZis#A4%asx*l6X2+<8rTiS0N0!XcjXEB*a3 zJuLuEn*w2|84Sgs5X?Tsb%}jAML`jW$cuzmn<&JEMd3!rD6IPwh5y2$>BEmg^n*yW z=^u&S!y+-4r!UPS;k`2g75_!x=%NT%u8Y8zdu}C0gI@>W4k#Ve>{1=QD`vc&A-4~J{%pf=SKu0@Qtn`-R!8z`CHn693 zgA4W)x#ImnH|WzB2v<*Zp?~xGea>Gk2tdwNYVu%+8vku$ zPuLDiB+wThxz+;3yDYHt6XyqZv!v!^2}|DI=ZH0SYe?W5ZHt%G{IfJ2an{QjTQ*A3 zf2s?1X}Q9@n=9&x@&A&O_ov1(l=`v*d9gFO`Lr(zkwEPH`A{LgUnZZWK60Fx{*##7 zo4T{}e1(Xgr4W-Q6Sv0@Cx^2JI+XZ5SV3Q4Qzps>UjK0l^>kwUH{y4n6~t%iGSv&H zad5^&Ti!mI+K0^`g_y!)#W01?z@1#_$(ji)DZK$$q0UM9>@CJJ2GmqWe$&DT;2XuIIHj* z*~2r8^Q4(;_~cWGDBQ{3edd&J*J4i){pKQ#+BvnA3F*Y=IYrzz>=PxiMI!ogk(g>q zT_sK?WW8h}eWXm-OqPk2Q)FTUvHW3wnHZZa6NyeTq4T~-T-jJ8mbe!Q?a%u~xKWWP z7*RxhrAQcl=lY=J?c2!tsmsq_#_TU@_am4eFo6A|KbZL&-KtFdV!oosNv=cGUWU?d znIK`WD1X~qrJM)e@`zXzeoWMlsuZ*Co)G23P6?HWvqJ7#&77Z0Vv+4tk@DlZQ0;w7 zj4it-#+5!6K_{Py0miSz`U4+CX|HeM>&9PVj7~FnwozqIzZ&dJHSnshvTt9TJ_&6M z>)0Bj=tcacr;GDmdMIYLbi9!Pe6*Q=p>BxUMngROWrWp#jKRis)JxbK-_aa*XIh}e ztESqgO1KS{dP{JkF*8OtMvB`7E=b(t3eN}ZYyabpfi1Wn(DXu;wl{R8 zKFlTXMdDmPB=z^lReH#i^a5dG6GUHmFfPxcX2RLT{}Io>A_CW@M56iEC|pd4!43<- z41s7wO9W;|a*txi&;BkNMX#grJX1hAia7l;8n+vx(0@!6`beXY|0ohSI9GahqH^v; zFb?}iV%RQaJt6`J^Y3in#l8sXwH0=PDj#E?v{=S|L(Z{E)!FF zXQSJO9E{(Pi^=`+@a0b)`t;7n4%SQ0SLdU#HXoyZ=R-fH2WD60vtKF?_vdA!wLvB( zu^-i?JPl@7J7dVzWb8hcfO*S1pdcX@)~Ce(-p{bzVOVU%wK%n@?`Z!PZ&>{2fpV^k z?p4&p21t?qj|(%W9DuMX>GMK*7D2!~R|4AAQ$L)d8 zF$uu$QS`-rWzB}`X{5vpE9QG3`lK6L4Qtv1+~;rC-`g32nvRa66W$DP#P(4R*pXt7 zI2$`0d{0mNMH}M2H8j3kLDJ6(3vB33HM2rMj1}xxSmCO%HI|*X<{sDvZxfpKZx^}N zw>ssBscFu**hh+q#x58*-UX6vtjV($sjJBzN^)~oa$a}hxd-w5!()X|Bc^7Oqc5c< z@`(D#wzUeenp#VH;`t8palMi3rzDPR6F-CV$&+))?RnVs;7sO!s7({66ULK^6Q`dk zH5wl4i09V4zLxj9m_n_kgF><9%>W+zR+7v+oTrcF)TmMsM18sXTqY{3io~xzMZ)U(ey&gZ zMEc(SLSj}V^1Bp?eUpnsU-EbLP?<=$AQNG|nKST{wO0DngKSEfn_MdDqv&BgUMA+U zCu(klT%f$khu)Wdru_Mbgoo)-(LT3ARIEELPP92GX5Tn1^6s4zI)5&RK)WmAVbXPR zXLXHe@V_hUq8^Ha+n$Kz$QNSH%h#Nf{XyKe_$H2|{u1f>&ETJ^iZEv1zB;Ob=>{zk z=H3dn@3gUfCTArN=WKx1)L9G+Fzt{5mMv#C_#8vdbT>kmrN+?TXoCAPQ+zyY1}Qyy zYUa$v%VxjEQEQxP!FkV~w%A5ZqHr4fIvzWqJk1GKb<9th!#!sTJ&JxF7#QS*D6qHD z!4DrQ{So992-$`pdUiwL#9HWzmCSHj*Q6=@nj&zt5ZFoVR%*VT*!O63yd7rmq6cqP zJB;|3vo3Yop*kl9-v$F}-37XPMB~7_NVHfR0k^PlXi=Lzy&wcDX9c5iV-PAgGeclm z0OFbBx~sb%Og(&Y?yEO0?{4zT^-lMIB;6hRI78#V4EAFZm&tOazr z%lW3|PMBHbgpu@6gngy&F~u3T9yvp{gI?&ZE)eI~E7<6ULN8|BcJxG_j$RlV>tn(6q%yF~!|V(GEG9Ege|LHJk^j6pT@-cuv*WfzVxV(`_%NJQ<7!mU5i z+(!sZjs-Tx0IB@U&zA#*dx1MgfhXUAm3x}LD^IT&j8z5hB@5iT6ph#2s8?Nz!ryO^ zh_>Mme35wP#t4ug{7P$Al5_R0=0zZQ?io=Gr0or1w5yTCNLD=zIx$IyM< zq1Pje>v1-EYv#hUc^+P#%R_xmK0;3CqfV^{Dr|Z{Zry`(HhN%;EFXoh^00bVF21kN zMoDTWu2N55@->Y*PZuownT&z;>|L$yfZgk2v4{D;5B#HGJ|-Nuzp-bmLlE3K^KH** z`Z9MYxwQ*gQom}}j9mIXb8D%azyINhJG;Fh8N|AJmjD0!O%2b3v5&sZ!WZEfvm+ek z9m23tlli^Nf|2?xkeW>ZZVvN9?>Zl9F5Z~B(v!NCJ2riH#r=-1m_h&1Mwtt;B~5zH zeW^1ttJzmv=zw$=d*)%}=x&T~!p>#RxS1hE{UxqV)PA(6XY?h1TS%>?>a#+0dP6OxjvD$M z>MIu&qOp>iIXScQcKZFOqimT+{e%4bJ@Gt@{CENJ`=503=493usZ-x+Pah05j&$Pl z?p)rN_qi~EYXmvEGuMQA>M~hb^fX2g)1_PstmsWQ=i{u2_0Gg{ANmEusju)kl=lng zdT}|2+6u9}@;kE-%jKfybm}L)W&*Q!3=t(dW3y#U`$6ITF?m`28NGHuYYE`COk5i>U*TiOda^;>gSsV#EEDBH_gu z(SAU+czNQIINIi#IM(B)u)A?v%o}-Mgmrx^CiQ(PRxYg<`wze28uLM%_WCA_d;bzC z-pw$Ee)OMT)G#Vq6RBfb!g+Bk44%~*x|4PAnSK_fkLAJQw&)=-#EZX%IQ!R#T8atG zoY=z;GwAg+$BP*jkQQ6w)Ke?WvbVwcffAIJ+2Wt?%tZm`z-@KJS1V^cCB9V$y2A9P z8$#F*qtew220lL6rtOCo*Zg74T$Y*Y!El%pg3c!FTQ3jCF5;I;muR$kEU>W=F!>mR zgO0K2+bj+(!s3`m5{C(QV$pq5EdIu`r~E=Y)N_`xUAq`if`OxnKuA>-0#YNfxIP@g z>@|-W5lWAB2!8()j75Eea5{^#AUgyg$ip97TKeI@9Ut^#PpNiKFIdpQ_>ybSZwGh0 zWG2VX5Le6|;eu`tq_{jnibD3`JGw}*G(d_LSyC)nrSz^yQ8|=zz}}NKM8+_rXY7mXL8z9_$741`SBU-p~}Q3YU!p0>=#{^3;jiTi0Pb<7f9|Z1NvUE zL)uPTc+GF(;q}Dt;a{!sX}>jg4YbCjF4oL?v4+}m8(eH-3+HM(Od9LJeU2ltT00|~ zn%;?2&dHr2g{*-dlyB6qKao?vr3d9XIrsyGP+X_3a+VtU5o+N@3Nc|bIrK7WB;?%v z$-PySx=AnUBwZEa#{aQ&)p1d`-_pibumeF5q>=7A11z<42?j`)-TK*y}1!$?cyd+;vQkV`E~G4*7jcew{}2q1-MJEoNr^ zQ1iY_&&lxOVky{AELkhqEl3Y`w>iaPKAHS`DEA_>Z_to=eciUjvhGch*ze;WpXo)! zPio)JMZ~xwDJI`;|G7|_Jt&mKQ|w70c9%@&o*;Ti<_UYw=`H`l?%U4n)+!@zuV!X{ zF<<`8`_;tIE9`2yPAu=s9MSj;`dgd}WEXcdFFQ*uWfrxS2#x6Ka-R8HE%HSz)oN(C zTT>%}*5u;E?;d=AlLYE8)X&!v-)lf4jg83Tf2d{uLA6XCs+PnqYT5Z)B{yEFB$v1I z_f)cRbrpAyNh9y)9Q9C#0`?XZNS{Hx4p|n-<*!9Dmowatob_5vp;nc^?wo*KqR8JZ z2S)CdJ$v`dq&kOWs=*Pt``{?&-bdwp>}l!R^1RHMdPz#3Uy*4c*CqM%Em@m!Pjov! zl0Sc*%IG^UWocoB48QR~E{*ys3ubXAQ5^enpVq*Sl-fMAYGGjY`qFfKIpq z$M*T7aYKJRC!#M-@C9X5bm9!PR|9Xv4);VpJYW*)4r`?w1_Zfcx*xMQ?#|4Va|YSY z5t-E-Fr0gU({|Wm{0JN37dv1&TEqFTB@{0$(B*?U26r~c+&VvxGNiaBY2<^W^L^BEuH%ui8PIdB~Ry_;uE^r-q)MtS^qR z-R#6p7H51kcVW+s3v@5L;sUc$aqHcoSnYuW8$7W`?S)6B-ndcf14H7u_XJ?J_(J34cz#DHG-eJL4TKPRE=Wly}l z*#o+~9^4K{fak+l{{5q%92pMZK1$3P8-$$g3XFWovxS@B$!0Hn?!xTR1y}fva7LUn zab4FQjl0>RgxLiz>g(@_@xQ2{cyFW+e~2T#r*H;7gxvlJb5;IT=e)P{YpUl6_AaW_ zbnw4h#TQRZPjctWm6-=(yV?nU5soo;l zBew1^#ABrqW~q&F=~QP}ldB(YZi@2(rtAczANvD$_z=$@zMzlr5%HHCy*>2~yW_m= zW*&Y!UtdK|K99V5(oQiNMjoF-e+qf@4QeLCU8s>5(c3}{j;T)#r3raDdG|D1eyrb4 zdcw)i^LX8$P7^>rKdm+AsMJX&?E_SO>18>PZ`vB_Oi(VGVNoIXIaUSULi2LHGn=HCa|H+Xe<}r(8>=f>SAcilp zplL}Z~9gcQm%e`YdW*|%j>C@EUp6ZeogeP%fCPo@{KYk|C^ zC)}Ez^241AL_v@FU1o;*Wib<)S0GoJ1=<$JE=BJG382UPNj2^)x}}kg1;lI4K!1{d zM|x;PsE_~cppk>*;7zQE_3j!O9;6XfEN7_12>VB21|EQ9Jd1@)AcC(>HfgC6(kdg7sAL(+3QJrG>LVr$I zURRe=YtdWD9ajH#%eobN<;D2@61wJ~)VXq4Zhk!~-=7^9kKj`>I_<11`*J~=$6l73 z+sehJ@l9zq{f>M#d?5WUK9)YCp35rz*YdaUt;FYjl(}2J%KT}+#5RvlY{!~#dQlr) zdod@vvOYc^Y=}9B8so-+rf9c|U9l6JV;K4Qa&PWtV;*u(NgI^^X$zfz_GmO)7e<#l z;7@&h++^=-$v^}A-fD=MnjHOA_hongtm+{ndd7@AV$(;L6V8h`X{P;{I-Ea(e2 zv2}#$LnrK*^Bg94a04@B6| zK<=Ll#1{IQ8&nU(=79m!oE12#tw7^=f9UM?!{id;dP~6ON0nCmuazfSyAapC+|kU# z4UL^$5oF_nKPJvt)q#3P6GzNtPq%Fu^^oPZsMp;F>)5Y;{FW8sHdvzPbPL#QHOGUF z#O`Y5aB=3@e3LmQvY+=wkp;4yEivnuC2po$VXc`pJDR#+vp>)C`)#4pP+uW#45{G+ z*B~eKz3PNP3G5xa>5S_sF8outVnm@Uy+Lk_!n>m*y)FGd(4+F$6WR~GQ1rwbC!Y9V za=D6d3qn-&sHS3?puPD$vy{0M)Mr;PlY|JPr&%iv|H`c}IcJZ3_Gyp+NWU z3fLwo_8BM{~;uKsfPl4uW3fhiLf$DcJ zR3~?Tmza!wU6U|pR8M}cWE^;x0Il#i?g)*7eL*;qRx7zzj(Mj5cK#OlVTUPTvfCRv zsh*s}xT9$!SIlqbj3&fg)5p9vzO=)mxptUR!yc2I9q{J0Bi^5J#?-aUBGBtJrLGqi zE%!m2LSTLaKP=qg$Nm66EEw#EWxBo?uElX4pKEU}c)&8*9R}Q!XZgSdyXo~$7|XxW zJbs>+3VXO%^vL_8~yqI~9cnAL1Vo#fO!;x#?wmzESr>7)V~POg2> zja<7nGd^eNLz&H)W!K6s6piep<~?U4^=taZ_s~=Rik|aX^$J9Xk8S;3BafdDuP@Ng zLLJ?XUc?3C=rbqY7E@ChrO-$zb(kXF7W&cKLM{CX@jQ_Jl|p{roPiqg8LE+t{?yZX z9cV=zesq2E`)g|1MO+`p+2}w~%f&A$nRQJi*$vb(e1=*&x73K$I(`guOT%Ut$Xfc; zO&)Xa(I<8kP=|WGnI0pHU7~$-w>%oSSMDkIi%H}`Q4c#TX(dO+;Ky-!8FflVy*eX# zSI*16PnX2T;HqqmzAnet-jbOe?n&$Y59M3xQ)&43g{&L!Mn-LX$K6sNW$%YCvbE7K z>6%jw6T@rre~WuD>()cR=mzi_&c2obRUUM$$Yu!QZs*sB*cocw8qxFGz?^uV+^0R3 z-POfSFFhPwppS#MJK|e&LzJKs-t;kI*N8Df>G2rGJq)+^nBiTt1tzq&Lf&m_>>>Bn z(ze5zGJEu!?}#1V&NzG11#A1eVM|R9{F&;Bb2YqiDcgs8j|2)WU)X#2p+ky4)FTx* zG%EmSmIlI*T&_{GU<|Md#_i`pc+x8f*GmH7_$B~t+Xdi8Hw8M~uAK1&AlAnh8`=mQ z^Srqa#|s6%o_Or%fweyF=)rvHeg{{K<@r0#mh(t^@?~pByw-NW&&zfg_@6CK>DfU0 zpf$o0t?c=TO!ToUd#PNZjtd~M5hoAMTF$p9u(E5Qp;UXtZk_@xSlgxK}XJ ze+D3OfY57{Qd@t({^UmN$Uhm!ec5vyko?OL^GsYY zg`R!4f0f+Z6Mr&&FrG8>{MuE|h2H^z*mfuohmY}kSL~0mXMEA{59cm9oK3X!M*SrDOG=(^e0+&GfO()c{xjFxN2Kh<_VnOs{4F&r2p~ zPVHsWG*cuI({+jIt%>Q;#Po;6^oPXs|A^`LiRpTrkJ@kJ%yT8PM02bBCf%u@%t&L` zOBDII*G`EvW>-LM&Ok3$;dJQP649ggJF*FRIr)0e&gB2RwQA37X-#T6oM(R6SR!4B z=ktiy)BLEb5WDB;l*oAM;0M1I%W8V?zSEDgggQzlxw%f8B3=Vja&9Q~5auVlJF>fq zJ+y7R70Ss}c35Rn`%Y)(C!tVA`7(!Nz&$}9xfhOJl(yv5^&3;8pf9`;AuMQZ2Oh}qSW_%-Q!8Ih-v z{lj@Jn68m6)ZZ2BHO#$gWHvE=t~W8hA@fN0>2WC~SD&cn-Z?d|Ydd6lU$q?3;rG9Q zAH%c3GIk8~h~jmK*QoLs_5*Of+rqm<)bx4gzt|;?=l0001N)@^g#$9;_aV{v9F>!c zj?2`fImDZ+2Pa zbZmp=-0`)+p*>t)>T<8A9(Gsji2v9*t9{rIrN2AjfUYsR*t7dC#smhlOi}Bx846-8 z@a2^yGk4bTim}1RW_GxJ+a6D-9anPJCqAyYcf}2RQamvAl_y?gac+0p2ehA{dMam~ z!~Nhf*&n^;DR6vM0QT(+#G|J{=o}G(R?Ikdw^qVtRtUzu4Mus3VCJ%eaHT~cmN^7q z1U=SI`LV-l`C$%gpmy!?!JU!b@XYkWh9plMj`hIwV0SqCx?!!aD{R>7Xuvc3+oU=CDZi`Pdm={_~|9hDO>^d?Bo677DzZvVtRk@+R?7Q7<>yF_w-C=Waj+Y_tL}@MZwo zya_~&1wl~H4#HUS?pL1!@!>V+oWBDx#4rdSQhEJ56a*88VD6_1W{xU^e+TLvx}oT2 z6^7XE;q0M}K)6v97VeCOb9yXv%;FLDqASMFO~kFv-C?<|2Qpsw#Fc+Z==miXQ>m?7 zD@wtqL8-`Yn}+a3X)wH>hNExOaPU|f;*!%~b}$t?uck0_*$cX+$>^BV6WW2@5m1kYpbp73RUIC-QS;v2Z)-*ad7 zQ8GW~S>=c6-OL3yr?}zO77vVA?u9#QAAG6J83Ma|&mRfE@!mn~-K_k1Bayf&7!4u= zd6uMx$Ly^77@uqBxrc*(DOW%8i9KFuPS0oG(;jFt&I5)vmAx~b_(o0tNdqU;EVjpX z4_nkaX^ll|EFsLx&A4QWUxw_ESZj=C)K$iJ?1a%R3{l1`>c7a2SkaJr%%YAse!~F4 z?Dbjm*9fYf+)+B(1Z`qWQF@0NsTTCizTYXwi0e<^uv?MZ%Z-OSB>52?MJIZjPw z5B2dKoQ=|hVmqI+%Zc;|lBdU~lW%hlTHl+Top>#E+1quGnfWs%Qu{jnDBnut0Ckv& z)Xn?1q5qJ&xOPK&3;Fhi%=vuZS|VY?OPFCLrnf7RBX5eu^gyx9qNi{-Jt=!EivQ=c z9x|1@^Bd=t>=!StALGxrm(jmCg?#*9A7cApjclSub8IcYhoig}yyN`zE4B6$8d<~lnR{uZ zkFG{SwfMCv)KY7|S~k!RlcukcNyQq8u_%yMQwpRmf94+}i0w<&vR7RortBy9SC6w~ z_MJs;-Yw@2?UkvI_w(_GqFg%&lNI^=DJG?qH5=?pZXrYKi*E)|f=UUh*YdY^Ro-JJk^rM>*5?=8Cm8^qpV! zK!-#x%q;W9aeu)M{%_sZ^+T8T{`kV)RUB8KPC)?PZwci7$snx$9E_6XmEO8Y#A!m2 z92knmr<9nvEd*;!g7N-SAcm2fT0K+1=M=LmBRMN<=ZnI#f`D~CxV*?4*VsoGGQtyI zdwHNZnw>ClZkUnfipA`1Y<9XTTmP_!BNiUx`99SSruS{|iN3>ck1XNNp2$kC#i9uA zfX}vMe%=~x6_q|2d$c}di@$a3uym3gB5dtZUef_Dzd7JDIpx*P&TynJ(Um*n)cf6V zp~RhgHaxIsDE0Es#3B0VTUU6Zn7@nB^p~#~#eAom4<>3e3-nhovw<(#L|5fJm-6Qt z{ly=n*rOQoQo#fY?%S`&oznjl==7lfC0g0M;_7zI6pk#aJaI&KI% zGD8r5PKj}QLy=b)hI8cQ-PcCo$GJ!(SVUvimKgMQjALdd9?HiFn010$OGXdm|Lutx znaQXX-V3iks9nR$msA$C<8NM-?I4Ba9^r&CAQ=-R#AhZh)K)@$IG(HC$Wj^?% z!W-wdc%p7y5BxXN4ZnHDnemC5)m9gHy1Am1`Kp&@p3sS;hbLQbVlwsk{ro-gTvB=6 zx;-rfo@bQ^@(V?7iW06%gHg*g2wFV5=sr~7d*>=m>hu<0nEn=co$$egKi+75x>C0T zqK^-`O@X|lAN#^3YSHA#s_hzSNUY91sF7i}sYQS0e6cRO zR2ouOA%Bgf9x{O(dcZ&puP1!$)JjcSC6)@ce4_Vz-VNq>IFHn=#T@=m-ru38WP@4) zLe$cBchwxyJWwSoma9bbLnU#kYT2$)%k)=jnaR&L$5A6Mf~coNYGiw075}$M&`8)| zW$yTobf9tmBvPv%@cAUo3!%SEGO+=+BTPPm+wPiM}`3BL=n>D481x^PAQUA-o~ z58Ra1L+^-N;(d9%=8=queI~2yU&%ndx6=CN2l;FLMXI0sE~}mXNJp>gu&P}P&7Ri5 z*^Tv3!=xcz_iBuaVNLNfO9#FEnqvlc$c;5-$6TAXh`rPf72S1FS5FW2?5gh5x+>$Y zaWTdob`n+k%8rqzIMb*2WVksT=379k%o2@lt&u~HyDycyo}KOC-PsX$4V+u#K~;CcZc}uL`$5u2WzW`L-kf=k68 zpP`uM7=|9)IbVtI|4O)*=T|VkYzso%lt3)(6M#ac0(*FE81&2+0rdA>C=i^yOnkWG zjnHE9_5So!Bzj;?syiBwb3*`ikaz6se!GF!9P+;!?8sW4SE+;BWApPa__d7wWqk{{ z7@4ECnFSh-v%(T~O5N^2{|>Q#LkoKx#E4U}_nR?R|n#V{b4*TZX`JQV1-X zvJZWq5{DOtqQ{OfI2c7>Zh9ol-J+24Gz#q-#Nhk7SnT$Q$7EGkG~phLns(j!^Cz=E zFbRK?IQy)Yj+C5K)LfkkWxF)y@zY?{FC7ov-{;F^9KC=bfz!$&T4n;9qNYLligrE&>dDIxhwlO|CVpP(O3tlZ_gQnp8{tC z193Vg7-xQkU~scgEM?E+<=de=|Aj)ckvp{4hhX&jV9Y-rgs{3i<9!dnoB!B1{K^l< z3w+V%H0#v8!Cq&<=T*#g`FY}J19zS`T#)wO5nn9qk)z?+j2Yl`T}%AtjAgQsDUPlr zuICyfag-5kPISUkBl_9nEB|No(LI{8)M`dJvb8f7@Ui{l%}`6p+`@fxOknr@w;$x< zyhVQ_E)&~(5!b^XQ!lwmPb2l0bw@ZqEuk-w`t12-%p=X9-u@qbE4|6fd(z($O0S|j z=cnZAm0c)ziQmVY5yQ#P7x6ZNSihZGd*%C1P>ZR&&nEWozEmPs^p7vK<(!nB!$Cvn zzoSnj_E3=w%%B&Xx_I?%+yUoFZRL1@II_cVC9!)IvF($KM#eu;%j(UQIIWSZ)#(HD zXa15}#~sh1bz9917 z@oIS&t(Ha9tN$!jiD#5bTzje{qLQm~Ch6@=4Q7~Hnis0&-$S)5uS*@hlSbY;kbm?0 zNd$43m_D0&N-t_K6E;wHDJFg&*2w%b8aaHH+R8qSR9~hMFY@|Hybjc?)M9x38CF5e zHz^Q3Ax={tSCOk%{#>o8$LN$Zr}U4X!H zZyXk4!D`IefpX-2ZuskYLTbduO-O-y>wH2mZ`75@$o-pV|+F4ovVpo zr)tB6`-v)ZMjcl)f;snN{@tUEwF{f!vvCV_{N56;oZCRNr5#@G)Wwb*z5hKYdvn*N zi;)q%FUACULbelkm1X+EXBRbv<_a`04}i;~05t2#StxmT{?Z^!jR;0W`w)cj z|FiK;C7#X=#Vz7`vLXxT#@SIf?Ay2?iazYFJ_Fduw(S*ua^+kv~%CxiE3SryUOXYUPOJbIi0%bi(@>XRNU29JVd{ z1(}Iey>`Qjv-IAqShv0)z3w@aP7wDG>)-R=op2OdbhaYCw z@`n*IJ;halD2)O~OahR&BLFj80&)ICAd*6ZkVg;Vbp8$!w*=#9ix9NoPB?8XC5A6h zqM-}VG}Xee{d*W%xJBT^&&qz=I5;{p%XuUQtzN~V-RgM0tsD1rCsMoVhSyhnpuw&r zOr|F>qGc*(<`KimyKCB}LvL0((%NRA=u8GOmt^AYge-j9kd6B8IY|7GjU@)z_%SLA z{++Y`UKgsyABHVHUR!J&^3)(c?_L!v^j@^ss@+9xI%3t@Hwz;nfrq#HMye z+A3qL>|l&#hm5e8Gtppb=-U<y@{|Ytr@#D$i2NAO~h|dYkoGUqx^JXr{ ziG1INGgC`qIW_j#9q31FMNcC!-ir8sonGlI&PpeNc~j~z$JTQH8|S30xvwF~r&z9^ zV_!)UJ=XMxk6KtLUAu6v^2q|pOyF)e;@)6t6^l&ReZ|a8Jo$7b@2A6#3$Df~E74KY_Ox2Vau-sP=Xfef~z zCz9AbTbmjRvA$y~?m-IY>oeKQODz9p&tBd2%sa8q*JM|b><=#%6KYmnrn7UAztb#s zunpa`OCAp2Bil#s6Z_Q%#AL@IIoa%})Vpw8^p~EJ;`(RhP||tP+j~(awz@27hp)=E zqt~Uz$6GSC&OQ0|`+=M~^;it-p7D44Om1o_WZI^Wa=6JiF>m`zT+{za3;h~ASJuM! zTrEt|tB>*9nH&Ap7%nZek=MQ%62CRa!ND#0d~1ouXWQZs{Vgu{_3({z{DfPESaRM7 z9^*T6zorTMRA@|iVTOV1N(x(Tfs7n4K?>ZvCg$sF@ z8&>*z;8TPbo+J~y?17%-plvzFGK*HwR~LXQZ`GuljG%F55s49?WVO|@iDxe(b&;MyZ*beYT z{Bpozz2M^jAFML-rncdQVa&&08(XEB{>^s7^B0`MO?Sp8S0{XZ=76N(_83lITWT0R zEDx+PEYlhr*cUQ;o(&>7BbdS6)w&NH;6)wY;j$wP>1&z)*a;7purD#m1vA-gYf#M% zuIJrwU}!GC($9|e^f`fUY!(&%xi2*Ab>fw0gDLei`tOr*}Dzc?7{^h01=7=ph+N_2U_ z+w@S_c!nWFI~>28N1#VSB$oV(!mi91+)0eZl6G-e9Ttz#@4I5%H1hNJ-EiNp2WCC% ziTEwa*g84|?Z>3y&f9d{8I^&T6Eo2AN(OY}GtsDC76Kk-p~j1Bh<`5s-hGj@EtmU5 za$vJP8}~kC;m_$z6n;&|@Uf|I`;?5R);%#fq8kP-?ur{tr8EA_5r`BDfouv)CUI$YCd0-1i9dsUHC~HJ`qlLNQ>v601`} z@WMS9eaYL;l?9+a&x?zb=(#HQ#lOpf3$fm~Kbo_cS+00|$O(^wsygX|>vq8oTT7h0 zYK9uE*`?dk1Q%Cv57XezxH7ae+V1C`y*v{fRI$rli`@_{EimJ&1wVsS2;?*VhQ>8Mt0>cp*BvBddrc- z_dew7Y20(vgWX--_&RS_sK-d0S(UutV>a;?ep)3i^bn>~f4N1>*N#_lk_#$-mpqr3O@}VW%)Xi{CVIhh4e<*rn)Bysp$mN+!`CLvH`sjCwiG z5u>Q9e7c~K)zp>VQvaWxT_BUl$I~Yl$PxN<{Liq5m)WNJ)L53jER>{N@^UTqw(lyI zmm`>=jo`V-qf}H8yCiJQZt-#3E2G)va@GEz{OosFlCB;V_w*C;quFVhu;Q%bmYtV| z`!9<7<}$hd@``vCUK4}6H>JJ)UAZ0fK&Hk%mg?TmB>2q>e!p)dBLBS@O!*=M+y4~B z?7z}&dUZHg)Wn*cIxzfE7vbZX8~xshy&6rCFiHo%*%i8PSxY3PwZ?~0ZE>cFF1}vX z!%!H&a$zU*W6w$34)j}frN&a-90}*mF?N{+J%5(4(WWl3+X`=a4sA{UUu0(+v|MG2 zxv}iB4WOr(`JRFmu6SC?E-7}L*W2lhn)E6bB>H08KRWa_#HuEtI5ks=<4;3iYZ!uK!NExC z5d`qs(45}K^-c;bwep9yjUUo%IcL-dzJ2q73ukYAi@Y#_GfBl?4{UG2J@pUWP(GZQ zq%JP7`RK%*8jjqN=YU1#JZD$4gNLy#e%-RcG49-X*~t#syHq*z-L;C|h_m#z zxH;o*xihMB9;#w**zitn(7!{^#uRtNQbXVP#smL0)3cfGg%cfkxFecoqyj>c_1_$)1r=G(8rIm3_jnTsIusUx#D<>j)h05QS{^EG}S&*2|}{SWrJ6 zmze>&bRYrkyt=__e|MPp^u&{!N${D~3(4uJm_}Y+$+w@a$VAIonb>(h6GOAIpskn9 zzhO4|Y31URM;<(%z=`nPshRMy|7Y}_;NQ?yOO~B zI2>6W!~00?1&qK)r*Ne74@J?|5G>UVMt7b;nvDs-9%}{Kz4gPf$MpWh_@YCGFPgpf zg~4P$&Y}Hrq#-r8SHbjIh9c=;IB+%sJ3B`reNH60y^BPFXB6Izi(>XD3WnVAQTcTb zg-2oLr3e^q4Tl!}o83Ny;x@Y|2OJ8)IUHRPqrc)|i*?(1?-73p#vpf9{eTl^Nro?sg+r;;C zRlQo($<+s~q$hDU_4RS=sO7A50X3K>IppH~smoAnPp3BH+m|^dA9n8=a*j&9<-gj@ z8Bt5OA-+#0Pj8k)U7a8ErVXzj{YoTuIp@KjL!k>oI3`^8`D_=~wwo{dnp| zcG3E3n3tpvWVBk|8mrl3qLMj#RC1KJj<;3vzBc_Joz>#v$_%|H{eGNlE+Ph>siqeD z>ndqS{15G=l4O6C?BKoiYU(PdRFcTgbAj2+gYQ(b?Irm+vH$Q@m3+RyYsN*Dc$KT9 z{Dw*{o>$2OK6X zS%3S5M7Me)y64`BmdqV961@*vqBMp3 zS!!CNem=8Aox0%Bye?RCqzj7X(gPS{hxvQCr{SFw3R=0M1AW&`sYxDp^G5ALvZFXaotIY?=zH`c3X*ht@*!a zABqc|L($*^_v0*9qLz^oYxC)w_!5i>M!|^Y3@o>4Afmn~F!+r>EI#-l>yK4vUA_W7$9ln3OnTO_38dcxMco;EcC_ow0_R>zY(oERA-~%*s_WqvU z?SakRJrUi49V?gVZ5hU#|0ibPl|Hz;(g$^_3GV(UFr?3AdNp78+E&dMHjVO!(_H3d zU-}~~jXBz{3T#*$z`bnLoxcQP{J0?8`yGVtV}r54AOufugrIpbb3^AsadB4|ETh6< za5|j&bp*TYBk^@h6rR71#zMzf3?CT>-9zz6)lR^`;fXl+tsA1o^ngy&B-GfPjCa8) z_^);v%08qczh@@8HOxYucNQ)eW+5;*8@p@g;OL7S%&(V+;AeSgnw<*Cg}($?QSthEX57!eewCevF8L`BCmCl}MZ?#$M15 zWA96qE|Q=h4D-vx>_Y*V|6PG~a}*dr9&qx50y*O4Vv317npHbT})m)XRtb;l7QP zrf65+3`wiZ@P~e>{e>3P+PL?k)EX<_(dYik2HT%h?k=%M>=!$9W{&x#9(P5s&(^v< zcYd~F?+f<}m65x9QjfXH`Dwy)?!LHA3_nSpO|E{4v(oYf#QaIrV20BJLo6RyiQ&We zHgfn%4!)i*w{qvlQg6xqRU(eBsh>Y7ktHun#Dz1`*3{QCeJefhrQ+SEL=w5jz8(2z z{tn`~3HSGqpZ6nQJwpv5VYf!kPuRQn^n?!2)nS%Rs8;Th^>W6ZVpz-SaSU12UYUw5_OiF z%;A%}C-c^wH)CRZtH;FuXDTUv#B0EbDxK$98|p9PnBkT(}xVB z|78U|G}OcM$k9*J?_P2`R^x$g^^n)q6bj=mMELm%b0=Ql~c|4SZwSHqwwH4t>F7N0*_Slz!K zBJVbUX+&ebt_|}h&G0p*1?uFt!ng+P$=%x?A6MxiVx0lKT}B9^=W30IDIyk{Lnc@v zV7(ReJ25w3VhwG2u~+Qxf(6Xmf2Tg0B&lWxer?|}mL zN7Xs%gVmFX=ftZg)Vs?#&m7=Heoii4`TyknMu}VtB@*6;VBfnCgf~_q#Z!s_=*&IokfR56_d-O7HxmDP<25z(;Q>DAJC44b2juI?f@kFEJIT`xnG;npKefu3 zIjUG{0K5I+>aIZcbp@u-@A4`(5SPL@8zr8nb2hq@Gr#dZoQM7m!Ms;W{4}eYA$zi~ zC987;u04-Ht*4RjYZQ(1(J`1^$}CZ{cBjwcT`~Js9QL=4WrjBzJ3mL_ z`Pc|_vZfaEAQTVgDDfjU1i$HDAHF{bg}Fh<$PU8b^FeqpJs8jHDlsdf>St}fECyCC z%ttBWfRC}*d@dHN_QzuSkyvEij)ilbIM{aJzNSa9Ftd)uJ=+*)xklsTkSN^Kio&3^ zk=Q~X&?k1#Z1oC7=${bi6W80t1){Z|Kc-I*SS)3Se;7OYhd5)xS_l3PDzVubz4R^7 zHq;#Zh~v53jXur79HG?AKmWGi*^zrMo>^n(NE>9*ALX2DkJt3pAA=*ilpL{Wp(AQ= z59derk#{%a{!U}=3ex8}zBTze`^IO~DwXkH>0N(Hj|(-JJ@mk6wo-2)cCRBR-%U(+ zAfCU>-YJjs*bg(B7|;1>|E}zLp?2Pb{+FY-N~GjyiOel35qtU-?CT=Ts6zKL3?i9>r^e(+6_+pDH;~oqm{_%yRM?;Z#R0h17U1Y*5QH_O~1+ z9{;4@P>Yy;j@rxi!R$iMCq^IBNYY1*1e;NFQP5LKZ1-+iAi7N}J%9>*kA>0s4%qs!BNj9<;`7uD z5Asa$@sk<-fEL)EZv~;Y(%YE(o{!n!w1F*JFq?Cx!WMezb~tpx4mIA}!Rn|zHt{)H zsY$%=<^~<&Wz1qPyq(D`WDlU|pD)(`=Z}7G>BUPA#H;W0wUmb-g6G~a18U_=T6o0!_PrLo6drPzrCUT+zZFWx0j?W+5@THC$ z9&~a=4*iGCMml36`@UN2a>PrXJH9I%@MxL?8YvyQm&pnJ$C}~ z;?In3=w{FZzs~l=zCp=Yu9bo#15%Mguldm$88~E`iN4lZSky8b70!yMFklZC~rGof+Hz}~HCDEyRygeL6ws-1+u zkJNcSB{D;lfYCkTaqUDbS_Z|S>w_qij*i4E!wAHehapYPbJ=+%Zg?x9O$^s>QN`i+ zFAc>jk8n)t8;S4JD>a;MnBA`{Y`S+vs&QBL?8ZZTW;`{=c+|^^$B1$4ZQmb{(0TD_ za6S&%n`2S8IEK01Xben=#`{*x&8Ek|j+#vOdtn%+6AImSAy~dA5DTvR<3vtnw}2|4+I8xi=egGFQ7g({^zoWYgv^iJPqaJ&j9pw+XOUQ-0I4_%W?C&^{$@jfNY zZ_*e3hB#W_tCp$c(24~rSwh}DcsS>m!-%!KA23=adnfaL4)u{mD$!Y@l3~RAA;fcC zKGrNrC0Bx|k3%IN!d22am%ekp?;|ysm%J9lkcZE?rjl{w<%_>kYaxCg=3I4!ky?)0 zs^tlFd5=_TJM_p@a_gVJiS63F))>;yLVf%S{q5!SxgTCgFXI93F?!0mX$|%a5Xbd6 zADu=G=@nnD)XmQ_&)8f_}sL&^R>2&-BJnY;Fqs-#R#$)dEL;w8ECc zw)nkB7ftr+^Eqoou5Ju@Vge85K?nG9r(8oTeE({VCT(odYZ3Pg7*zHNR(bvYF^5r~ zo!^UgaZg%?BQvQ^*wWI4c^2la6&~o5;DvXwKCtWtoG|jkMd}EK`xMysIRJS!L1^AL z80xtpkRD3<43%)-LtaJ(?#el1Ge7oPv*R&KpcUu?J11}S z;J&-94xV@t;DN?D?pVgmqQf0m^ERo|Vmr=kwb+A#A@BRDsO+ zpK`_qZx^)M?}FnMJTi9H#}h1!4v9WcAwAVK8i+OcuZY(Y!7cZ z%wQI3f;SBIu>-w>4|=chq5ngW_DrCh3ry+ai}?qAamkN!-ZJ_+^8E2yPXT9o)0dnL zz+Rq3j&Bb_ROeu<8XAm`wL=g{{mOfg5=TQq5!5*hbAE*3^VM*Cyb^(NwW1J_7>)f$ zV~}AVhYpM5(c&HPFO&|jtKHzvi*BQ^B<5~=;rqoD{A-wo?RC=;Zjyn^!I}7zo<%=> zHfjycL0Dies^81Sir_qiuFb>kD|zT}JP%I>RT8#j^nI1kGIufI8E(+L2v}l-=k*!G#XCR;xPGUS72x&CR|R0{FjIzbpmR-&

                                                                                                                                                                                    -Last Updated: Saturday October 01, 2016 -Last Change : Saturday October 01, 2016 +Last Updated: Monday October 17, 2016 +Last Change : Monday October 17, 2016

                                                                                                                                                                                    @@ -312,16 +312,24 @@

                                                                                                                                                                                    3.3. Install build dependencies

                                                                                                                                                                                    install command for packages +trusty +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui + + stretch -apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui xenial -apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui + + +yakkety +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui sid -apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui +apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui @@ -2996,5 +3004,5 @@

                                                                                                                                                                                    9. Authors and Acknowledgments

                                                                                                                                                                                    - + diff --git a/doc/linux.t2t b/doc/linux.t2t index cc6751dbb1bf..0ff0db24d0ff 100644 --- a/doc/linux.t2t +++ b/doc/linux.t2t @@ -44,9 +44,11 @@ sudo apt-get update == Install build dependencies == || Distribution | install command for packages | -| stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | -| sid | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| trusty | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| yakkety | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | +| sid | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | (extracted from the control.in file in ``debian/``) diff --git a/doc/news.html b/doc/news.html index d43506a090b3..524432af9cae 100644 --- a/doc/news.html +++ b/doc/news.html @@ -5,7 +5,7 @@ QGIS News - + "; // tabInfoHTML += ""; tabInfoHTML += it.value(); From 9a90a24504df738318ac35541e1e463b42a25041 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 18 Oct 2016 06:03:55 +1000 Subject: [PATCH 290/897] Add processing test .aux.xml to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e87e0c1a103f..2a91bfa058aa 100644 --- a/.gitignore +++ b/.gitignore @@ -65,4 +65,5 @@ tests/testdata/raster/band3_float32_noct_epsg4326.tif.aux.xml tests/testdata/raster/band3_int16_noct_epsg4326.tif.aux.xml python/plugins/processing/tests/testdata/custom/grass7/float_raster.tif.aux.xml python/plugins/processing/tests/testdata/custom/grass7/raster_1class.tif.aux.xml +python/plugins/processing/tests/testdata/dem.tif.aux.xml Thumb.db From ecee43814a3ee13470683e376191cb3719ec0e44 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 18 Oct 2016 09:55:56 +1000 Subject: [PATCH 291/897] Fix changing project CRS from legend doesn't correctly set CRS Also avoid fragile duplicated code for setting/retrieving common project properties Fixes #15717 --- python/core/qgsproject.sip | 49 ++++++++++++++++++ src/app/qgisapp.cpp | 7 ++- src/app/qgisappinterface.cpp | 2 +- .../qgsattributeactionpropertiesdialog.cpp | 4 +- src/app/qgsattributetabledialog.cpp | 6 +-- src/app/qgsdiagramproperties.cpp | 4 +- src/app/qgsfeatureaction.cpp | 2 +- src/app/qgsfieldcalculator.cpp | 4 +- src/app/qgslabelinggui.cpp | 2 +- src/app/qgsmaptoolmeasureangle.cpp | 2 +- src/app/qgsmeasuredialog.cpp | 2 +- src/app/qgsprojectproperties.cpp | 18 +++---- src/core/composer/qgscomposerhtml.cpp | 2 +- src/core/composer/qgscomposerlabel.cpp | 2 +- src/core/composer/qgscomposerscalebar.cpp | 2 +- src/core/qgsproject.cpp | 40 +++++++++++++++ src/core/qgsproject.h | 51 +++++++++++++++++++ src/core/qgsvectorlayerfeatureiterator.cpp | 2 +- .../layertree/qgslayertreemapcanvasbridge.cpp | 3 ++ src/gui/qgsmaptoolidentify.cpp | 2 +- src/gui/qgsowssourceselect.cpp | 15 ++---- src/gui/qgsprojectionselectionwidget.cpp | 3 +- src/gui/qgssourceselectdialog.cpp | 3 +- src/providers/wfs/qgswfssourceselect.cpp | 3 +- src/providers/wms/qgswmssourceselect.cpp | 15 ++---- tests/src/app/testqgsattributetable.cpp | 20 +++----- tests/src/app/testqgsfieldcalculator.cpp | 20 +++----- .../src/app/testqgsmaptoolidentifyaction.cpp | 32 +++++------- tests/src/app/testqgsmeasuretool.cpp | 20 +++----- tests/src/core/testqgsproject.cpp | 4 +- tests/src/python/test_qgsproject.py | 31 ++++++++++- 31 files changed, 255 insertions(+), 117 deletions(-) diff --git a/python/core/qgsproject.sip b/python/core/qgsproject.sip index 3d59dda19521..6371c8914871 100644 --- a/python/core/qgsproject.sip +++ b/python/core/qgsproject.sip @@ -64,6 +64,38 @@ class QgsProject : QObject */ QFileInfo fileInfo() const; + /** + * Returns the project's native coordinate reference system. + * @note added in QGIS 2.18 + * @see setCrs() + * @see ellipsoid() + */ + QgsCoordinateReferenceSystem crs() const; + + /** + * Sets the project's native coordinate reference system. + * @note added in QGIS 2.18 + * @see crs() + * @see setEllipsoid() + */ + void setCrs( const QgsCoordinateReferenceSystem& crs ); + + /** + * Returns a proj string representing the project's ellipsoid setting, eg "WGS84". + * @see setEllipsoid() + * @see crs() + * @note added in QGIS 2.18 + */ + QString ellipsoid() const; + + /** + * Sets the project's ellipsoid from a proj string representation, eg "WGS84". + * @see ellipsoid() + * @see setCrs() + * @note added in QGIS 2.18 + */ + void setEllipsoid( const QString& ellipsoid ); + /** Clear the project - removes all settings and resets it back to an empty, default state. * @note added in 2.4 */ @@ -258,16 +290,33 @@ class QgsProject : QObject /** Convenience function to query default distance measurement units for project. * @note added in QGIS 2.14 + * @see setDistanceUnits() * @see areaUnits() */ QgsUnitTypes::DistanceUnit distanceUnits() const; + /** + * Sets the default distance measurement units for the project. + * @note added in QGIS 2.18 + * @see distanceUnits() + * @see setAreaUnits() + */ + void setDistanceUnits( QgsUnitTypes::DistanceUnit unit ); + /** Convenience function to query default area measurement units for project. * @note added in QGIS 2.14 * @see distanceUnits() */ QgsUnitTypes::AreaUnit areaUnits() const; + /** + * Sets the default area measurement units for the project. + * @note added in QGIS 2.18 + * @see areaUnits() + * @see setDistanceUnits() + */ + void setAreaUnits( QgsUnitTypes::AreaUnit unit ); + /** Return project's home path @return home path of project (or QString::null if not set) */ QString homePath() const; diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 59cf1c5b53e2..c5245645da16 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -4435,9 +4435,7 @@ void QgisApp::fileNew( bool thePromptToSaveFlag, bool forceBlank ) QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( defCrs ); mMapCanvas->setDestinationCrs( srs ); // write the projections _proj string_ to project settings - prj->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - prj->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - prj->writeEntry( "SpatialRefSys", "/ProjectCRSID", static_cast< int >( srs.srsid() ) ); + prj->setCrs( srs ); prj->setDirty( false ); if ( srs.mapUnits() != QgsUnitTypes::DistanceUnknownUnit ) { @@ -7306,7 +7304,7 @@ void QgisApp::selectByForm() myDa.setSourceCrs( vlayer->crs().srsid() ); myDa.setEllipsoidalMode( mMapCanvas->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); QgsAttributeEditorContext context; context.setDistanceArea( myDa ); @@ -8582,6 +8580,7 @@ void QgisApp::setProjectCrsFromLayer() QgsCoordinateReferenceSystem crs = mLayerTreeView->currentLayer()->crs(); mMapCanvas->freeze(); mMapCanvas->setDestinationCrs( crs ); + QgsProject::instance()->setCrs( crs ); if ( crs.mapUnits() != QgsUnitTypes::DistanceUnknownUnit ) { mMapCanvas->setMapUnits( crs.mapUnits() ); diff --git a/src/app/qgisappinterface.cpp b/src/app/qgisappinterface.cpp index c6bf04add48d..636a6bef9a81 100644 --- a/src/app/qgisappinterface.cpp +++ b/src/app/qgisappinterface.cpp @@ -681,7 +681,7 @@ QgsAttributeDialog* QgisAppInterface::getFeatureForm( QgsVectorLayer *l, QgsFeat myDa.setSourceCrs( l->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); QgsAttributeEditorContext context; context.setDistanceArea( myDa ); diff --git a/src/app/qgsattributeactionpropertiesdialog.cpp b/src/app/qgsattributeactionpropertiesdialog.cpp index 41c7e9124cea..f859dc0ca918 100644 --- a/src/app/qgsattributeactionpropertiesdialog.cpp +++ b/src/app/qgsattributeactionpropertiesdialog.cpp @@ -52,7 +52,7 @@ QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsActio QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); mFieldExpression->setLayer( mLayer ); mFieldExpression->setGeomCalculator( myDa ); @@ -81,7 +81,7 @@ QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsVecto QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); mFieldExpression->setLayer( mLayer ); mFieldExpression->setGeomCalculator( myDa ); diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index a84483bb498c..e10005d4728d 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -126,7 +126,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid myDa->setSourceCrs( mLayer->crs() ); myDa->setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa->setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa->setEllipsoid( QgsProject::instance()->ellipsoid() ); mEditorContext.setDistanceArea( *myDa ); mEditorContext.setVectorLayerTools( QgisApp::instance()->vectorLayerTools() ); @@ -559,7 +559,7 @@ void QgsAttributeTableDialog::filterExpressionBuilder() QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); dlg.setGeomCalculator( myDa ); if ( dlg.exec() == QDialog::Accepted ) @@ -920,7 +920,7 @@ void QgsAttributeTableDialog::setFilterExpression( const QString& filterString, myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); // parse search string and build parsed tree QgsExpression filterExpression( filter ); diff --git a/src/app/qgsdiagramproperties.cpp b/src/app/qgsdiagramproperties.cpp index 81d21d5024c1..6be3c268ba83 100644 --- a/src/app/qgsdiagramproperties.cpp +++ b/src/app/qgsdiagramproperties.cpp @@ -178,7 +178,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( mMapCanvas->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); mSizeFieldExpressionWidget->setGeomCalculator( myDa ); //insert all attributes into the combo boxes @@ -871,7 +871,7 @@ QString QgsDiagramProperties::showExpressionBuilder( const QString& initialExpre QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( mMapCanvas->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); dlg.setGeomCalculator( myDa ); if ( dlg.exec() == QDialog::Accepted ) diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index a02a5c78f82f..6905984e68fc 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -57,7 +57,7 @@ QgsAttributeDialog *QgsFeatureAction::newDialog( bool cloneFeature ) myDa.setSourceCrs( mLayer->crs() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); context.setDistanceArea( myDa ); context.setVectorLayerTools( QgisApp::instance()->vectorLayerTools() ); diff --git a/src/app/qgsfieldcalculator.cpp b/src/app/qgsfieldcalculator.cpp index 5dd7bc383493..75e15357ba98 100644 --- a/src/app/qgsfieldcalculator.cpp +++ b/src/app/qgsfieldcalculator.cpp @@ -60,7 +60,7 @@ QgsFieldCalculator::QgsFieldCalculator( QgsVectorLayer* vl, QWidget* parent ) QgsDistanceArea myDa; myDa.setSourceCrs( vl->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); builder->setGeomCalculator( myDa ); //default values for field width and precision @@ -160,7 +160,7 @@ void QgsFieldCalculator::accept() myDa.setSourceCrs( mVectorLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); QString calcString = builder->expressionText(); QgsExpression exp( calcString ); diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index 2b582fbcc7b9..9b16629bb295 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -590,7 +590,7 @@ void QgsLabelingGui::init() QgsDistanceArea myDa; myDa.setSourceCrs( mLayer->crs().srsid() ); myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); mFieldExpressionWidget->setGeomCalculator( myDa ); // set placement methods page based on geometry type diff --git a/src/app/qgsmaptoolmeasureangle.cpp b/src/app/qgsmaptoolmeasureangle.cpp index ecae82aaa536..37e71af1ef69 100644 --- a/src/app/qgsmaptoolmeasureangle.cpp +++ b/src/app/qgsmaptoolmeasureangle.cpp @@ -181,7 +181,7 @@ void QgsMapToolMeasureAngle::updateSettings() void QgsMapToolMeasureAngle::configureDistanceArea() { - QString ellipsoidId = QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ); + QString ellipsoidId = QgsProject::instance()->ellipsoid(); mDa.setSourceCrs( mCanvas->mapSettings().destinationCrs().srsid() ); mDa.setEllipsoid( ellipsoidId ); // Only use ellipsoidal calculation when project wide transformation is enabled. diff --git a/src/app/qgsmeasuredialog.cpp b/src/app/qgsmeasuredialog.cpp index 3668457d8b6f..25d6e799a4ed 100644 --- a/src/app/qgsmeasuredialog.cpp +++ b/src/app/qgsmeasuredialog.cpp @@ -79,7 +79,7 @@ void QgsMeasureDialog::updateSettings() mDistanceUnits = QgsProject::instance()->distanceUnits(); mAreaUnits = QgsProject::instance()->areaUnits(); mDa.setSourceCrs( mTool->canvas()->mapSettings().destinationCrs().srsid() ); - mDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + mDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); // Only use ellipsoidal calculation when project wide transformation is enabled. if ( mTool->canvas()->mapSettings().hasCrsTransformEnabled() ) { diff --git a/src/app/qgsprojectproperties.cpp b/src/app/qgsprojectproperties.cpp index 3321544567b6..81ca3f6d8244 100644 --- a/src/app/qgsprojectproperties.cpp +++ b/src/app/qgsprojectproperties.cpp @@ -783,9 +783,7 @@ void QgsProjectProperties::apply() QgsDebugMsg( QString( "Selected CRS " ) + srs.description() ); // write the currently selected projections _proj string_ to project settings QgsDebugMsg( QString( "SpatialRefSys/ProjectCRSProj4String: %1" ).arg( projectionSelector->selectedProj4String() ) ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", projectionSelector->selectedProj4String() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) projectionSelector->selectedCrsId() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", projectionSelector->selectedAuthId() ); + QgsProject::instance()->setCrs( srs ); // Set the map units to the projected coordinates if we are projecting if ( isProjected() ) @@ -837,10 +835,10 @@ void QgsProjectProperties::apply() emit displayPrecisionChanged(); QgsUnitTypes::DistanceUnit distanceUnits = static_cast< QgsUnitTypes::DistanceUnit >( mDistanceUnitsCombo->currentData().toInt() ); - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( distanceUnits ) ); + QgsProject::instance()->setDistanceUnits( distanceUnits ); QgsUnitTypes::AreaUnit areaUnits = static_cast< QgsUnitTypes::AreaUnit >( mAreaUnitsCombo->currentData().toInt() ); - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( areaUnits ) ); + QgsProject::instance()->setAreaUnits( areaUnits ); QgsProject::instance()->writeEntry( "Paths", "/Absolute", cbxAbsolutePath->currentIndex() == 0 ); @@ -855,13 +853,13 @@ void QgsProjectProperties::apply() major = QLocale::system().toDouble( leSemiMajor->text() ); minor = QLocale::system().toDouble( leSemiMinor->text() ); } - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "PARAMETER:%1:%2" ) - .arg( major, 0, 'g', 17 ) - .arg( minor, 0, 'g', 17 ) ); + QgsProject::instance()->setEllipsoid( QString( "PARAMETER:%1:%2" ) + .arg( major, 0, 'g', 17 ) + .arg( minor, 0, 'g', 17 ) ); } else { - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", mEllipsoidList[ mEllipsoidIndex ].acronym ); + QgsProject::instance()->setEllipsoid( mEllipsoidList[ mEllipsoidIndex ].acronym ); } //set the color for selections @@ -2001,7 +1999,7 @@ void QgsProjectProperties::projectionSelectorInitialized() QgsDebugMsg( "Setting up ellipsoid" ); // Reading ellipsoid from setttings - QStringList mySplitEllipsoid = QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ).split( ':' ); + QStringList mySplitEllipsoid = QgsProject::instance()->ellipsoid().split( ':' ); int myIndex = 0; for ( int i = 0; i < mEllipsoidList.length(); i++ ) diff --git a/src/core/composer/qgscomposerhtml.cpp b/src/core/composer/qgscomposerhtml.cpp index 0a9f0082604b..5a6d113c8e25 100644 --- a/src/core/composer/qgscomposerhtml.cpp +++ b/src/core/composer/qgscomposerhtml.cpp @@ -548,7 +548,7 @@ void QgsComposerHtml::setExpressionContext( const QgsFeature &feature, QgsVector { mDistanceArea->setEllipsoidalMode( mComposition->mapSettings().hasCrsTransformEnabled() ); } - mDistanceArea->setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + mDistanceArea->setEllipsoid( QgsProject::instance()->ellipsoid() ); // create JSON representation of feature QgsJSONExporter exporter( layer ); diff --git a/src/core/composer/qgscomposerlabel.cpp b/src/core/composer/qgscomposerlabel.cpp index 01cb62334d91..41e101eef243 100644 --- a/src/core/composer/qgscomposerlabel.cpp +++ b/src/core/composer/qgscomposerlabel.cpp @@ -265,7 +265,7 @@ void QgsComposerLabel::refreshExpressionContext() mDistanceArea->setSourceCrs( mComposition->mapSettings().destinationCrs().srsid() ); } mDistanceArea->setEllipsoidalMode( mComposition->mapSettings().hasCrsTransformEnabled() ); - mDistanceArea->setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + mDistanceArea->setEllipsoid( QgsProject::instance()->ellipsoid() ); contentChanged(); update(); diff --git a/src/core/composer/qgscomposerscalebar.cpp b/src/core/composer/qgscomposerscalebar.cpp index 96a5ddc08e2d..a84fa4398031 100644 --- a/src/core/composer/qgscomposerscalebar.cpp +++ b/src/core/composer/qgscomposerscalebar.cpp @@ -304,7 +304,7 @@ double QgsComposerScaleBar::mapWidth() const QgsDistanceArea da; da.setEllipsoidalMode( mComposition->mapSettings().hasCrsTransformEnabled() ); da.setSourceCrs( mComposition->mapSettings().destinationCrs().srsid() ); - da.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", "WGS84" ) ); + da.setEllipsoid( QgsProject::instance()->ellipsoid() ); QgsUnitTypes::DistanceUnit units = QgsUnitTypes::DistanceMeters; double measure = da.measureLine( QgsPoint( composerMapRect.xMinimum(), composerMapRect.yMinimum() ), diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index c7989001f89a..3b5932ecc381 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -444,6 +444,36 @@ QFileInfo QgsProject::fileInfo() const return QFileInfo( imp_->file ); } +QgsCoordinateReferenceSystem QgsProject::crs() const +{ + QgsCoordinateReferenceSystem projectCrs; + long currentCRS = readNumEntry( "SpatialRefSys", "/ProjectCRSID", -1 ); + if ( currentCRS != -1 ) + { + projectCrs = QgsCoordinateReferenceSystem::fromSrsId( currentCRS ); + } + return projectCrs; +} + +void QgsProject::setCrs( const QgsCoordinateReferenceSystem &crs ) +{ + writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", crs.toProj4() ); + writeEntry( "SpatialRefSys", "/ProjectCRSID", static_cast< int >( crs.srsid() ) ); + writeEntry( "SpatialRefSys", "/ProjectCrs", crs.authid() ); + setDirty( true ); +} + +QString QgsProject::ellipsoid() const +{ + return readEntry( "Measure", "/Ellipsoid", GEO_NONE ); +} + +void QgsProject::setEllipsoid( const QString& ellipsoid ) +{ + writeEntry( "Measure", "/Ellipsoid", ellipsoid ); + setDirty( true ); +} + void QgsProject::clear() { imp_->clear(); @@ -2108,6 +2138,11 @@ QgsUnitTypes::DistanceUnit QgsProject::distanceUnits() const return ok ? type : QgsUnitTypes::DistanceMeters; } +void QgsProject::setDistanceUnits( QgsUnitTypes::DistanceUnit unit ) +{ + writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( unit ) ); +} + QgsUnitTypes::AreaUnit QgsProject::areaUnits() const { QString areaUnitString = QgsProject::instance()->readEntry( "Measurement", "/AreaUnits", QString() ); @@ -2121,6 +2156,11 @@ QgsUnitTypes::AreaUnit QgsProject::areaUnits() const return ok ? type : QgsUnitTypes::AreaSquareMeters; } +void QgsProject::setAreaUnits( QgsUnitTypes::AreaUnit unit ) +{ + writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( unit ) ); +} + void QgsProjectBadLayerDefaultHandler::handleBadLayers( const QList& /*layers*/, const QDomDocument& /*projectDom*/ ) { // just ignore any bad layers diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index e838ab6cb82a..017f5e1b3bc6 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -34,6 +34,7 @@ #include "qgsunittypes.h" #include "qgsprojectversion.h" #include "qgsexpressioncontextgenerator.h" +#include "qgscoordinatereferencesystem.h" class QFileInfo; class QDomDocument; @@ -74,6 +75,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera Q_PROPERTY( QStringList nonIdentifiableLayers READ nonIdentifiableLayers WRITE setNonIdentifiableLayers NOTIFY nonIdentifiableLayersChanged ) Q_PROPERTY( QString fileName READ fileName WRITE setFileName NOTIFY fileNameChanged ) Q_PROPERTY( QString homePath READ homePath NOTIFY homePathChanged ) + Q_PROPERTY( QgsCoordinateReferenceSystem crs READ crs WRITE setCrs ) public: @@ -120,6 +122,38 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ QFileInfo fileInfo() const; + /** + * Returns the project's native coordinate reference system. + * @note added in QGIS 2.18 + * @see setCrs() + * @see ellipsoid() + */ + QgsCoordinateReferenceSystem crs() const; + + /** + * Sets the project's native coordinate reference system. + * @note added in QGIS 2.18 + * @see crs() + * @see setEllipsoid() + */ + void setCrs( const QgsCoordinateReferenceSystem& crs ); + + /** + * Returns a proj string representing the project's ellipsoid setting, eg "WGS84". + * @see setEllipsoid() + * @see crs() + * @note added in QGIS 2.18 + */ + QString ellipsoid() const; + + /** + * Sets the project's ellipsoid from a proj string representation, eg "WGS84". + * @see ellipsoid() + * @see setCrs() + * @note added in QGIS 2.18 + */ + void setEllipsoid( const QString& ellipsoid ); + /** Clear the project - removes all settings and resets it back to an empty, default state. * @note added in 2.4 */ @@ -314,16 +348,33 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera /** Convenience function to query default distance measurement units for project. * @note added in QGIS 2.14 + * @see setDistanceUnits() * @see areaUnits() */ QgsUnitTypes::DistanceUnit distanceUnits() const; + /** + * Sets the default distance measurement units for the project. + * @note added in QGIS 2.18 + * @see distanceUnits() + * @see setAreaUnits() + */ + void setDistanceUnits( QgsUnitTypes::DistanceUnit unit ); + /** Convenience function to query default area measurement units for project. * @note added in QGIS 2.14 * @see distanceUnits() */ QgsUnitTypes::AreaUnit areaUnits() const; + /** + * Sets the default area measurement units for the project. + * @note added in QGIS 2.18 + * @see areaUnits() + * @see setDistanceUnits() + */ + void setAreaUnits( QgsUnitTypes::AreaUnit unit ); + /** Return project's home path @return home path of project (or QString::null if not set) */ QString homePath() const; diff --git a/src/core/qgsvectorlayerfeatureiterator.cpp b/src/core/qgsvectorlayerfeatureiterator.cpp index 7aeb2a24a206..5014532951f5 100644 --- a/src/core/qgsvectorlayerfeatureiterator.cpp +++ b/src/core/qgsvectorlayerfeatureiterator.cpp @@ -548,7 +548,7 @@ void QgsVectorLayerFeatureIterator::prepareExpression( int fieldIdx ) QgsDistanceArea da; da.setSourceCrs( mSource->mCrsId ); da.setEllipsoidalMode( true ); - da.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) ); + da.setEllipsoid( QgsProject::instance()->ellipsoid() ); exp->setGeomCalculator( &da ); exp->setDistanceUnits( QgsProject::instance()->distanceUnits() ); exp->setAreaUnits( QgsProject::instance()->areaUnits() ); diff --git a/src/gui/layertree/qgslayertreemapcanvasbridge.cpp b/src/gui/layertree/qgslayertreemapcanvasbridge.cpp index 179bea4ab307..81c2edbd229d 100644 --- a/src/gui/layertree/qgslayertreemapcanvasbridge.cpp +++ b/src/gui/layertree/qgslayertreemapcanvasbridge.cpp @@ -20,6 +20,7 @@ #include "qgsmaplayer.h" #include "qgsvectorlayer.h" #include "qgsmapcanvas.h" +#include "qgsproject.h" QgsLayerTreeMapCanvasBridge::QgsLayerTreeMapCanvasBridge( QgsLayerTreeGroup *root, QgsMapCanvas *canvas, QObject* parent ) : QObject( parent ) @@ -146,6 +147,7 @@ void QgsLayerTreeMapCanvasBridge::setCanvasLayers() if ( layerNode->layer()->isSpatial() ) { mCanvas->setDestinationCrs( layerNode->layer()->crs() ); + QgsProject::instance()->setCrs( layerNode->layer()->crs() ); mCanvas->setMapUnits( layerNode->layer()->crs().mapUnits() ); break; } @@ -182,6 +184,7 @@ void QgsLayerTreeMapCanvasBridge::setCanvasLayers() if ( layerNode->layer() && layerNode->layer()->crs().isValid() && layerNode->layer()->crs() != mFirstCRS ) { mCanvas->setDestinationCrs( mFirstCRS ); + QgsProject::instance()->setCrs( mFirstCRS ); mCanvas->setCrsTransformEnabled( true ); break; } diff --git a/src/gui/qgsmaptoolidentify.cpp b/src/gui/qgsmaptoolidentify.cpp index 7b5d07b30f57..5b5325017633 100644 --- a/src/gui/qgsmaptoolidentify.cpp +++ b/src/gui/qgsmaptoolidentify.cpp @@ -352,7 +352,7 @@ QMap< QString, QString > QgsMapToolIdentify::featureDerivedAttributes( QgsFeatur QMap< QString, QString > derivedAttributes; // init distance/area calculator - QString ellipsoid = QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ); + QString ellipsoid = QgsProject::instance()->ellipsoid(); QgsDistanceArea calc; calc.setEllipsoidalMode( mCanvas->hasCrsTransformEnabled() ); calc.setEllipsoid( ellipsoid ); diff --git a/src/gui/qgsowssourceselect.cpp b/src/gui/qgsowssourceselect.cpp index cc386b8113fd..952553e1a914 100644 --- a/src/gui/qgsowssourceselect.cpp +++ b/src/gui/qgsowssourceselect.cpp @@ -93,15 +93,11 @@ QgsOWSSourceSelect::QgsOWSSourceSelect( const QString& service, QWidget * parent { connect( mAddButton, SIGNAL( clicked() ), this, SLOT( addClicked() ) ); //set the current project CRS if available - long currentCRS = QgsProject::instance()->readNumEntry( "SpatialRefSys", "/ProjectCRSID", -1 ); - if ( currentCRS != -1 ) + QgsCoordinateReferenceSystem currentRefSys = QgsProject::instance()->crs(); + //convert CRS id to epsg + if ( currentRefSys.isValid() ) { - //convert CRS id to epsg - QgsCoordinateReferenceSystem currentRefSys = QgsCoordinateReferenceSystem::fromSrsId( currentCRS ); - if ( currentRefSys.isValid() ) - { - mSelectedCRS = currentRefSys.authid(); - } + mSelectedCRS = currentRefSys.authid(); } } else @@ -383,8 +379,7 @@ void QgsOWSSourceSelect::on_mChangeCRSButton_clicked() mySelector->setMessage(); mySelector->setOgcWmsCrsFilter( mSelectedLayersCRSs ); - QString myDefaultCrs = QgsProject::instance()->readEntry( "SpatialRefSys", "/ProjectCrs", GEO_EPSG_CRS_AUTHID ); - QgsCoordinateReferenceSystem defaultCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( myDefaultCrs ); + QgsCoordinateReferenceSystem defaultCRS = QgsProject::instance()->crs(); if ( defaultCRS.isValid() ) { mySelector->setSelectedCrsId( defaultCRS.srsid() ); diff --git a/src/gui/qgsprojectionselectionwidget.cpp b/src/gui/qgsprojectionselectionwidget.cpp index eb1a7ba8640e..e507b7872f01 100644 --- a/src/gui/qgsprojectionselectionwidget.cpp +++ b/src/gui/qgsprojectionselectionwidget.cpp @@ -40,8 +40,7 @@ QgsProjectionSelectionWidget::QgsProjectionSelectionWidget( QWidget *parent ) { //only show project CRS if OTF reprojection is enabled - otherwise the //CRS stored in the project can be misleading - QString projectCrsString = QgsProject::instance()->readEntry( "SpatialRefSys", "/ProjectCrs" ); - mProjectCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( projectCrsString ); + mProjectCrs = QgsProject::instance()->crs(); addProjectCrsOption(); } diff --git a/src/gui/qgssourceselectdialog.cpp b/src/gui/qgssourceselectdialog.cpp index e5c2b4211dfc..ef495638ce83 100644 --- a/src/gui/qgssourceselectdialog.cpp +++ b/src/gui/qgssourceselectdialog.cpp @@ -194,9 +194,8 @@ QString QgsSourceSelectDialog::getPreferredCrs( const QSet& crsSet ) co } //first: project CRS - long ProjectCRSID = QgsProject::instance()->readNumEntry( "SpatialRefSys", "/ProjectCRSID", -1 ); + QgsCoordinateReferenceSystem projectRefSys = QgsProject::instance()->crs(); //convert to EPSG - QgsCoordinateReferenceSystem projectRefSys = QgsCoordinateReferenceSystem::fromSrsId( ProjectCRSID ); QString ProjectCRS; if ( projectRefSys.isValid() ) { diff --git a/src/providers/wfs/qgswfssourceselect.cpp b/src/providers/wfs/qgswfssourceselect.cpp index 3ed15d37da46..0fa4d9417070 100644 --- a/src/providers/wfs/qgswfssourceselect.cpp +++ b/src/providers/wfs/qgswfssourceselect.cpp @@ -179,9 +179,8 @@ QString QgsWFSSourceSelect::getPreferredCrs( const QSet& crsSet ) const } //first: project CRS - long ProjectCRSID = QgsProject::instance()->readNumEntry( "SpatialRefSys", "/ProjectCRSID", -1 ); + QgsCoordinateReferenceSystem projectRefSys = QgsProject::instance()->crs(); //convert to EPSG - QgsCoordinateReferenceSystem projectRefSys = QgsCoordinateReferenceSystem::fromSrsId( ProjectCRSID ); QString ProjectCRS; if ( projectRefSys.isValid() ) { diff --git a/src/providers/wms/qgswmssourceselect.cpp b/src/providers/wms/qgswmssourceselect.cpp index 1dbdcd53b19d..fb43dc1c2f41 100644 --- a/src/providers/wms/qgswmssourceselect.cpp +++ b/src/providers/wms/qgswmssourceselect.cpp @@ -112,15 +112,11 @@ QgsWMSSourceSelect::QgsWMSSourceSelect( QWidget * parent, Qt::WindowFlags fl, bo setTabOrder( lstLayers, mImageFormatGroup->button( 0 ) ); //set the current project CRS if available - long currentCRS = QgsProject::instance()->readNumEntry( "SpatialRefSys", "/ProjectCRSID", -1 ); - if ( currentCRS != -1 ) + QgsCoordinateReferenceSystem currentRefSys = QgsProject::instance()->crs(); + //convert CRS id to epsg + if ( currentRefSys.isValid() ) { - //convert CRS id to epsg - QgsCoordinateReferenceSystem currentRefSys = QgsCoordinateReferenceSystem::fromSrsId( currentCRS ); - if ( currentRefSys.isValid() ) - { - mDefaultCRS = mCRS = currentRefSys.authid(); - } + mDefaultCRS = mCRS = currentRefSys.authid(); } // set up the default WMS Coordinate Reference System @@ -616,8 +612,7 @@ void QgsWMSSourceSelect::on_btnChangeSpatialRefSys_clicked() mySelector->setMessage(); mySelector->setOgcWmsCrsFilter( mCRSs ); - QString myDefaultCrs = QgsProject::instance()->readEntry( "SpatialRefSys", "/ProjectCrs", GEO_EPSG_CRS_AUTHID ); - QgsCoordinateReferenceSystem defaultCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( myDefaultCrs ); + QgsCoordinateReferenceSystem defaultCRS = QgsProject::instance()->crs(); if ( defaultCRS.isValid() ) { mySelector->setSelectedCrsId( defaultCRS.srsid() ); diff --git a/tests/src/app/testqgsattributetable.cpp b/tests/src/app/testqgsattributetable.cpp index 2aac54cbdde0..b4600508fa13 100644 --- a/tests/src/app/testqgsattributetable.cpp +++ b/tests/src/app/testqgsattributetable.cpp @@ -87,11 +87,9 @@ void TestQgsAttributeTable::testFieldCalculation() // set project CRS and ellipsoid QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); // run length calculation QScopedPointer< QgsAttributeTableDialog > dlg( new QgsAttributeTableDialog( tempLayer.data() ) ); @@ -106,7 +104,7 @@ void TestQgsAttributeTable::testFieldCalculation() QVERIFY( qgsDoubleNear( f.attribute( "col1" ).toDouble(), expected, 0.001 ) ); // change project length unit, check calculation respects unit - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceFeet ); QScopedPointer< QgsAttributeTableDialog > dlg2( new QgsAttributeTableDialog( tempLayer.data() ) ); tempLayer->startEditing(); dlg2->runFieldCalculation( tempLayer.data(), "col1", "$length" ); @@ -140,11 +138,9 @@ void TestQgsAttributeTable::testFieldCalculationArea() // set project CRS and ellipsoid QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); // run area calculation QScopedPointer< QgsAttributeTableDialog > dlg( new QgsAttributeTableDialog( tempLayer.data() ) ); @@ -159,7 +155,7 @@ void TestQgsAttributeTable::testFieldCalculationArea() QVERIFY( qgsDoubleNear( f.attribute( "col1" ).toDouble(), expected, 1.0 ) ); // change project area unit, check calculation respects unit - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMiles ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMiles ); QScopedPointer< QgsAttributeTableDialog > dlg2( new QgsAttributeTableDialog( tempLayer.data() ) ); tempLayer->startEditing(); dlg2->runFieldCalculation( tempLayer.data(), "col1", "$area" ); diff --git a/tests/src/app/testqgsfieldcalculator.cpp b/tests/src/app/testqgsfieldcalculator.cpp index b81afd0ed88a..ec656a2b070f 100644 --- a/tests/src/app/testqgsfieldcalculator.cpp +++ b/tests/src/app/testqgsfieldcalculator.cpp @@ -87,11 +87,9 @@ void TestQgsFieldCalculator::testLengthCalculations() // set project CRS and ellipsoid QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); // run length calculation tempLayer->startEditing(); @@ -113,7 +111,7 @@ void TestQgsFieldCalculator::testLengthCalculations() QVERIFY( qgsDoubleNear( f.attribute( "col1" ).toDouble(), expected, 0.001 ) ); // change project length unit, check calculation respects unit - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceFeet ); tempLayer->startEditing(); QScopedPointer< QgsFieldCalculator > calc2( new QgsFieldCalculator( tempLayer.data() ) ); calc2->mUpdateExistingGroupBox->setChecked( true ); @@ -151,11 +149,9 @@ void TestQgsFieldCalculator::testAreaCalculations() // set project CRS and ellipsoid QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); // run area calculation tempLayer->startEditing(); @@ -177,7 +173,7 @@ void TestQgsFieldCalculator::testAreaCalculations() QVERIFY( qgsDoubleNear( f.attribute( "col1" ).toDouble(), expected, 1.0 ) ); // change project area unit, check calculation respects unit - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMiles ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMiles ); tempLayer->startEditing(); QScopedPointer< QgsFieldCalculator > calc2( new QgsFieldCalculator( tempLayer.data() ) ); calc2->mUpdateExistingGroupBox->setChecked( true ); diff --git a/tests/src/app/testqgsmaptoolidentifyaction.cpp b/tests/src/app/testqgsmaptoolidentifyaction.cpp index 2a4f71ae139e..399e1f51c4e3 100644 --- a/tests/src/app/testqgsmaptoolidentifyaction.cpp +++ b/tests/src/app/testqgsmaptoolidentifyaction.cpp @@ -130,11 +130,9 @@ void TestQgsMapToolIdentifyAction::lengthCalculation() canvas->setCrsTransformEnabled( true ); canvas->setDestinationCrs( srs ); canvas->setExtent( f1.geometry().boundingBox() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( 2484588, 2425722 ); @@ -146,7 +144,7 @@ void TestQgsMapToolIdentifyAction::lengthCalculation() QVERIFY( qgsDoubleNear( length, 26932.2, 0.1 ) ); //check that project units are respected - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceFeet ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); derivedLength = result.at( 0 ).mDerivedAttributes[tr( "Length" )]; @@ -186,11 +184,9 @@ void TestQgsMapToolIdentifyAction::perimeterCalculation() canvas->setCrsTransformEnabled( true ); canvas->setDestinationCrs( srs ); canvas->setExtent( f1.geometry().boundingBox() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( 2484588, 2425722 ); @@ -202,7 +198,7 @@ void TestQgsMapToolIdentifyAction::perimeterCalculation() QCOMPARE( perimeter, 128289.074 ); //check that project units are respected - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceFeet ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); derivedPerimeter = result.at( 0 ).mDerivedAttributes[tr( "Perimeter" )]; @@ -243,11 +239,9 @@ void TestQgsMapToolIdentifyAction::areaCalculation() canvas->setCrsTransformEnabled( true ); canvas->setDestinationCrs( srs ); canvas->setExtent( f1.geometry().boundingBox() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( 2484588, 2425722 ); @@ -259,7 +253,7 @@ void TestQgsMapToolIdentifyAction::areaCalculation() QVERIFY( qgsDoubleNear( area, 1009089817.0, 1.0 ) ); //check that project units are respected - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMiles ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMiles ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); derivedArea = result.at( 0 ).mDerivedAttributes[tr( "Area" )]; @@ -268,7 +262,7 @@ void TestQgsMapToolIdentifyAction::areaCalculation() //test unchecked "keep base units" setting s.setValue( "/qgis/measure/keepbaseunit", false ); - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareFeet ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareFeet ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); derivedArea = result.at( 0 ).mDerivedAttributes[tr( "Area" )]; diff --git a/tests/src/app/testqgsmeasuretool.cpp b/tests/src/app/testqgsmeasuretool.cpp index 00b038d1f276..84a1de0cb95f 100644 --- a/tests/src/app/testqgsmeasuretool.cpp +++ b/tests/src/app/testqgsmeasuretool.cpp @@ -94,11 +94,9 @@ void TestQgsMeasureTool::testLengthCalculation() QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); mCanvas->setCrsTransformEnabled( true ); mCanvas->setDestinationCrs( srs ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); // run length calculation QScopedPointer< QgsMeasureTool > tool( new QgsMeasureTool( mCanvas, false ) ); @@ -117,7 +115,7 @@ void TestQgsMeasureTool::testLengthCalculation() QGSCOMPARENEAR( measured, expected, 0.001 ); // change project length unit, check calculation respects unit - QgsProject::instance()->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); + QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceFeet ); QScopedPointer< QgsMeasureTool > tool2( new QgsMeasureTool( mCanvas, false ) ); QScopedPointer< QgsMeasureDialog > dlg2( new QgsMeasureDialog( tool2.data() ) ); @@ -163,11 +161,9 @@ void TestQgsMeasureTool::testAreaCalculation() QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); mCanvas->setCrsTransformEnabled( true ); mCanvas->setDestinationCrs( srs ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", srs.toProj4() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCRSID", ( int ) srs.srsid() ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectCrs", srs.authid() ); - QgsProject::instance()->writeEntry( "Measure", "/Ellipsoid", QString( "WGS84" ) ); - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMeters ) ); + QgsProject::instance()->setCrs( srs ); + QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); // run length calculation QScopedPointer< QgsMeasureTool > tool( new QgsMeasureTool( mCanvas, true ) ); @@ -188,7 +184,7 @@ void TestQgsMeasureTool::testAreaCalculation() QGSCOMPARENEAR( measured, expected, 1.0 ); // change project area unit, check calculation respects unit - QgsProject::instance()->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareMiles ) ); + QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMiles ); QScopedPointer< QgsMeasureTool > tool2( new QgsMeasureTool( mCanvas, true ) ); QScopedPointer< QgsMeasureDialog > dlg2( new QgsMeasureDialog( tool2.data() ) ); diff --git a/tests/src/core/testqgsproject.cpp b/tests/src/core/testqgsproject.cpp index a8ae721fba54..1421360e6e79 100644 --- a/tests/src/core/testqgsproject.cpp +++ b/tests/src/core/testqgsproject.cpp @@ -104,7 +104,7 @@ void TestQgsProject::testProjectUnits() QCOMPARE( prj->distanceUnits(), QgsUnitTypes::DistanceFeet ); //test setting new units for project - prj->writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceNauticalMiles ) ); + prj->setDistanceUnits( QgsUnitTypes::DistanceNauticalMiles ); QCOMPARE( prj->distanceUnits(), QgsUnitTypes::DistanceNauticalMiles ); // AREA @@ -121,7 +121,7 @@ void TestQgsProject::testProjectUnits() QCOMPARE( prj->areaUnits(), QgsUnitTypes::AreaSquareYards ); //test setting new units for project - prj->writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaAcres ) ); + prj->setAreaUnits( QgsUnitTypes::AreaAcres ); QCOMPARE( prj->areaUnits(), QgsUnitTypes::AreaAcres ); } diff --git a/tests/src/python/test_qgsproject.py b/tests/src/python/test_qgsproject.py index 9ef08523a997..9e79d01fa663 100644 --- a/tests/src/python/test_qgsproject.py +++ b/tests/src/python/test_qgsproject.py @@ -16,7 +16,7 @@ import qgis # NOQA -from qgis.core import QgsProject, QgsMessageLog +from qgis.core import QgsProject, QgsMessageLog, QgsUnitTypes, QgsCoordinateReferenceSystem from qgis.testing import start_app, unittest @@ -111,5 +111,34 @@ def test_makeKeyTokens_(self): def catchMessage(self): self.messageCaught = True + def testCrs(self): + prj = QgsProject.instance() + prj.clear() + + self.assertFalse(prj.crs().isValid()) + prj.setCrs(QgsCoordinateReferenceSystem.fromOgcWmsCrs('EPSG:3111')) + self.assertEqual(prj.crs().authid(), 'EPSG:3111') + + def testEllipsoid(self): + prj = QgsProject.instance() + prj.clear() + + prj.setEllipsoid('WGS84') + self.assertEqual(prj.ellipsoid(), 'WGS84') + + def testDistanceUnits(self): + prj = QgsProject.instance() + prj.clear() + + prj.setDistanceUnits(QgsUnitTypes.DistanceFeet) + self.assertEqual(prj.distanceUnits(), QgsUnitTypes.DistanceFeet) + + def testAreaUnits(self): + prj = QgsProject.instance() + prj.clear() + + prj.setAreaUnits(QgsUnitTypes.AreaSquareFeet) + self.assertEqual(prj.areaUnits(), QgsUnitTypes.AreaSquareFeet) + if __name__ == '__main__': unittest.main() From 4589a807d0d24ddb43a8ed2b94b8ab2ace9b3295 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 18 Oct 2016 12:38:31 +1000 Subject: [PATCH 292/897] Followup ecee438 --- tests/src/core/testqgscomposerscalebar.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/src/core/testqgscomposerscalebar.cpp b/tests/src/core/testqgscomposerscalebar.cpp index 9929ad6e967e..6b7159a90554 100644 --- a/tests/src/core/testqgscomposerscalebar.cpp +++ b/tests/src/core/testqgscomposerscalebar.cpp @@ -25,6 +25,7 @@ #include "qgsrasterlayer.h" #include "qgsrasterdataprovider.h" #include "qgsfontutils.h" +#include "qgsproject.h" #include #include @@ -75,6 +76,8 @@ void TestQgsComposerScaleBar::initTestCase() // so we enforce C locale to make sure we get expected result QLocale::setDefault( QLocale::c() ); + QgsProject::instance()->setEllipsoid( "WGS84" ); + mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry From bd81edc36f867bd2774acc6bf956802ae8cd2cd7 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 14 Oct 2016 13:29:38 +1000 Subject: [PATCH 293/897] Defer processing of dropped files On Windows (and maybe other platforms) Qt locks the dragging application for the duration of dropEvent. This means that dropping large files or projects onto QGIS results in Explorer windows being locked and unresponsive until the entire file/project is loaded. There does not seem to be any Qt method for releasing this lock early, so instead we return from dropEvent as quickly as possible and defer the actual file loading to a slot which is fired up immediately after dropEvent concludes. --- src/app/qgisapp.cpp | 40 +++++++++++++++++++++++++++++++++---- src/app/qgisapp.h | 3 +++ src/core/qgsmimedatautils.h | 2 ++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index c5245645da16..4bbeb093dd98 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -1287,10 +1287,17 @@ void QgisApp::dragEnterEvent( QDragEnterEvent *event ) void QgisApp::dropEvent( QDropEvent *event ) { - mMapCanvas->freeze(); + // dragging app is locked for the duration of dropEvent. This causes explorer windows to hang + // while large projects/layers are loaded. So instead we return from dropEvent as quickly as possible + // and do the actual handling of the drop after a very short timeout + QTimer* timer = new QTimer( this ); + timer->setSingleShot( true ); + timer->setInterval( 50 ); + // get the file list QList::iterator i; QListurls = event->mimeData()->urls(); + QStringList files; for ( i = urls.begin(); i != urls.end(); ++i ) { QString fileName = i->toLocalFile(); @@ -1343,18 +1350,43 @@ void QgisApp::dropEvent( QDropEvent *event ) // so we test for length to make sure we have something if ( !fileName.isEmpty() ) { - openFile( fileName ); + files << fileName; } } + timer->setProperty( "files", files ); + QgsMimeDataUtils::UriList lst; if ( QgsMimeDataUtils::isUriList( event->mimeData() ) ) { - QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( event->mimeData() ); + lst = QgsMimeDataUtils::decodeUriList( event->mimeData() ); + } + timer->setProperty( "uris", QVariant::fromValue( lst ) ); + + connect( timer, SIGNAL( timeout() ), this, SLOT( dropEventTimeout() ) ); + + event->acceptProposedAction(); + timer->start(); +} + +void QgisApp::dropEventTimeout() +{ + mMapCanvas->freeze(); + QStringList files = sender()->property( "files" ).toStringList(); + sender()->deleteLater(); + + Q_FOREACH ( const QString& file, files ) + { + openFile( file ); + } + + QgsMimeDataUtils::UriList lst = sender()->property( "uris" ).value(); + if ( !lst.isEmpty() ) + { handleDropUriList( lst ); } + mMapCanvas->freeze( false ); mMapCanvas->refresh(); - event->acceptProposedAction(); } diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index c122295658ee..14bfd91b9ae9 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -1335,6 +1335,9 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow /** Set the layer for the map style dock. Doesn't show the style dock */ void setMapStyleDockLayer( QgsMapLayer *layer ); + //! Handles processing of dropped mimedata + void dropEventTimeout(); + signals: /** Emitted when a key is pressed and we want non widget sublasses to be able to pick up on this (e.g. maplayer) */ diff --git a/src/core/qgsmimedatautils.h b/src/core/qgsmimedatautils.h index 9d92d0e77932..dfbab68edfcd 100644 --- a/src/core/qgsmimedatautils.h +++ b/src/core/qgsmimedatautils.h @@ -76,5 +76,7 @@ class CORE_EXPORT QgsMimeDataUtils }; +Q_DECLARE_METATYPE( QgsMimeDataUtils::UriList ); + #endif // QGSMIMEDATAUTILS_H From 2a873b83ade6ac2a49ad18598e25e27fd6e9d3d2 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 18:32:19 +1000 Subject: [PATCH 294/897] Fix effects lost on geometry generator symbol layer --- src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp b/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp index 898685dae0ee..fb3c96cfc540 100644 --- a/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp +++ b/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp @@ -117,6 +117,8 @@ QgsSymbolLayer* QgsGeometryGeneratorSymbolLayer::clone() const clone->setSymbolType( mSymbolType ); + copyPaintEffect( clone ); + return clone; } From b8c2e68fc53bc0aba8bdcfcdc1906f70ea28c041 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 13 Oct 2016 07:39:49 +1000 Subject: [PATCH 295/897] [FEATURE] Allow symbol layers to be temporarily disabled Adds a new checkbox at the bottom of each symbol layer's properties which allows you to control whether the layer is enabled or not. Disabled layers are not drawn, but are saved and can be enabled at a later stage. This makes it easier to tweak symbol appearance without having to totally delete a symbol layer. --- python/core/symbology-ng/qgssymbollayer.sip | 16 ++ src/core/symbology-ng/qgssymbol.cpp | 29 ++- src/core/symbology-ng/qgssymbollayer.cpp | 1 + src/core/symbology-ng/qgssymbollayer.h | 20 ++ src/core/symbology-ng/qgssymbollayerutils.cpp | 3 + .../symbology-ng/qgslayerpropertieswidget.cpp | 7 + .../symbology-ng/qgslayerpropertieswidget.h | 1 + src/ui/symbollayer/widget_layerproperties.ui | 34 ++- tests/src/python/test_qgssymbollayer.py | 197 +++++++++++++++++- .../expected_symbollayer_disabled.png | Bin 0 -> 610 bytes 10 files changed, 301 insertions(+), 7 deletions(-) create mode 100644 tests/testdata/control_images/symbol_layer/expected_symbollayer_disabled/expected_symbollayer_disabled.png diff --git a/python/core/symbology-ng/qgssymbollayer.sip b/python/core/symbology-ng/qgssymbollayer.sip index 407e2e3e2c0b..bee1c7798426 100644 --- a/python/core/symbology-ng/qgssymbollayer.sip +++ b/python/core/symbology-ng/qgssymbollayer.sip @@ -67,6 +67,22 @@ class QgsSymbolLayer virtual ~QgsSymbolLayer(); + /** + * Returns true if symbol layer is enabled and will be drawn. + * @note added in QGIS 3.0 + * @see setEnabled() + */ + bool enabled() const; + + /** + * Sets whether symbol layer is enabled and should be drawn. Disabled + * layers are not drawn, but remain part of the symbol and can be re-enabled + * when desired. + * @note added in QGIS 3.0 + * @see enabled() + */ + void setEnabled( bool enabled ); + /** * The fill color. */ diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index 04e590645f31..42bc5efac0c9 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -396,7 +396,12 @@ void QgsSymbol::startRender( QgsRenderContext& context, const QgsFields& fields mSymbolRenderContext->setExpressionContextScope( scope ); Q_FOREACH ( QgsSymbolLayer* layer, mLayers ) + { + if ( !layer->enabled() ) + continue; + layer->startRender( symbolContext ); + } } void QgsSymbol::stopRender( QgsRenderContext& context ) @@ -405,7 +410,12 @@ void QgsSymbol::stopRender( QgsRenderContext& context ) if ( mSymbolRenderContext ) { Q_FOREACH ( QgsSymbolLayer* layer, mLayers ) + { + if ( !layer->enabled() ) + continue; + layer->stopRender( *mSymbolRenderContext ); + } } delete mSymbolRenderContext; @@ -442,6 +452,9 @@ void QgsSymbol::drawPreviewIcon( QPainter* painter, QSize size, QgsRenderContext Q_FOREACH ( QgsSymbolLayer* layer, mLayers ) { + if ( !layer->enabled() ) + continue; + if ( mType == Fill && layer->type() == Line ) { // line symbol layer would normally draw just a line @@ -587,6 +600,7 @@ QgsSymbolLayerList QgsSymbol::cloneLayers() const QgsSymbolLayer* layer = ( *it )->clone(); layer->setLocked(( *it )->isLocked() ); layer->setRenderingPass(( *it )->renderingPass() ); + layer->setEnabled(( *it )->enabled() ); lst.append( layer ); } return lst; @@ -1417,7 +1431,7 @@ void QgsMarkerSymbol::renderPoint( QPointF point, const QgsFeature* f, QgsRender if ( layerIdx != -1 ) { QgsSymbolLayer* symbolLayer = mLayers.value( layerIdx ); - if ( symbolLayer ) + if ( symbolLayer && symbolLayer->enabled() ) { if ( symbolLayer->type() == QgsSymbol::Marker ) { @@ -1432,6 +1446,9 @@ void QgsMarkerSymbol::renderPoint( QPointF point, const QgsFeature* f, QgsRender Q_FOREACH ( QgsSymbolLayer* symbolLayer, mLayers ) { + if ( !symbolLayer->enabled() ) + continue; + if ( symbolLayer->type() == QgsSymbol::Marker ) { QgsMarkerSymbolLayer* markerLayer = static_cast( symbolLayer ); @@ -1625,7 +1642,7 @@ void QgsLineSymbol::renderPolyline( const QPolygonF& points, const QgsFeature* f if ( layerIdx != -1 ) { QgsSymbolLayer* symbolLayer = mLayers.value( layerIdx ); - if ( symbolLayer ) + if ( symbolLayer && symbolLayer->enabled() ) { if ( symbolLayer->type() == QgsSymbol::Line ) { @@ -1640,6 +1657,9 @@ void QgsLineSymbol::renderPolyline( const QPolygonF& points, const QgsFeature* f Q_FOREACH ( QgsSymbolLayer* symbolLayer, mLayers ) { + if ( !symbolLayer->enabled() ) + continue; + if ( symbolLayer->type() == QgsSymbol::Line ) { QgsLineSymbolLayer* lineLayer = static_cast( symbolLayer ); @@ -1704,7 +1724,7 @@ void QgsFillSymbol::renderPolygon( const QPolygonF& points, QList* ri if ( layerIdx != -1 ) { QgsSymbolLayer* symbolLayer = mLayers.value( layerIdx ); - if ( symbolLayer ) + if ( symbolLayer && symbolLayer->enabled() ) { if ( symbolLayer->type() == Fill || symbolLayer->type() == Line ) renderPolygonUsingLayer( symbolLayer, points, rings, symbolContext ); @@ -1716,6 +1736,9 @@ void QgsFillSymbol::renderPolygon( const QPolygonF& points, QList* ri Q_FOREACH ( QgsSymbolLayer* symbolLayer, mLayers ) { + if ( !symbolLayer->enabled() ) + continue; + if ( symbolLayer->type() == Fill || symbolLayer->type() == Line ) renderPolygonUsingLayer( symbolLayer, points, rings, symbolContext ); else diff --git a/src/core/symbology-ng/qgssymbollayer.cpp b/src/core/symbology-ng/qgssymbollayer.cpp index 51ba4764e87b..fe95e6d259e6 100644 --- a/src/core/symbology-ng/qgssymbollayer.cpp +++ b/src/core/symbology-ng/qgssymbollayer.cpp @@ -261,6 +261,7 @@ void QgsSymbolLayer::setPaintEffect( QgsPaintEffect *effect ) QgsSymbolLayer::QgsSymbolLayer( QgsSymbol::SymbolType type, bool locked ) : mType( type ) + , mEnabled( true ) , mLocked( locked ) , mRenderingPass( 0 ) , mPaintEffect( nullptr ) diff --git a/src/core/symbology-ng/qgssymbollayer.h b/src/core/symbology-ng/qgssymbollayer.h index eb50fb460c16..bd4265ce2e48 100644 --- a/src/core/symbology-ng/qgssymbollayer.h +++ b/src/core/symbology-ng/qgssymbollayer.h @@ -53,6 +53,22 @@ class CORE_EXPORT QgsSymbolLayer virtual ~QgsSymbolLayer(); + /** + * Returns true if symbol layer is enabled and will be drawn. + * @note added in QGIS 3.0 + * @see setEnabled() + */ + bool enabled() const { return mEnabled; } + + /** + * Sets whether symbol layer is enabled and should be drawn. Disabled + * layers are not drawn, but remain part of the symbol and can be re-enabled + * when desired. + * @note added in QGIS 3.0 + * @see enabled() + */ + void setEnabled( bool enabled ) { mEnabled = enabled; } + /** * The fill color. */ @@ -266,6 +282,10 @@ class CORE_EXPORT QgsSymbolLayer QgsSymbolLayer( QgsSymbol::SymbolType type, bool locked = false ); QgsSymbol::SymbolType mType; + + //! True if layer is enabled and should be drawn + bool mEnabled; + bool mLocked; QColor mColor; int mRenderingPass; diff --git a/src/core/symbology-ng/qgssymbollayerutils.cpp b/src/core/symbology-ng/qgssymbollayerutils.cpp index 5a71ce73ec61..0b991a813998 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.cpp +++ b/src/core/symbology-ng/qgssymbollayerutils.cpp @@ -852,6 +852,7 @@ QgsSymbolLayer* QgsSymbolLayerUtils::loadSymbolLayer( QDomElement& element ) { QString layerClass = element.attribute( "class" ); bool locked = element.attribute( "locked" ).toInt(); + bool enabled = element.attribute( "enabled", "1" ).toInt(); int pass = element.attribute( "pass" ).toInt(); // parse properties @@ -863,6 +864,7 @@ QgsSymbolLayer* QgsSymbolLayerUtils::loadSymbolLayer( QDomElement& element ) { layer->setLocked( locked ); layer->setRenderingPass( pass ); + layer->setEnabled( enabled ); //restore layer effect QDomElement effectElem = element.firstChildElement( "effect" ); @@ -910,6 +912,7 @@ QDomElement QgsSymbolLayerUtils::saveSymbol( const QString& name, QgsSymbol* sym QDomElement layerEl = doc.createElement( "layer" ); layerEl.setAttribute( "class", layer->layerType() ); + layerEl.setAttribute( "enabled", layer->enabled() ); layerEl.setAttribute( "locked", layer->isLocked() ); layerEl.setAttribute( "pass", layer->renderingPass() ); saveProperties( layer->properties(), doc, layerEl ); diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp index 9d4d1cef8a97..6f3e149ccaff 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp @@ -112,6 +112,7 @@ QgsLayerPropertiesWidget::QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const // update layer type combo box int idx = cboLayerType->findData( mLayer->layerType() ); cboLayerType->setCurrentIndex( idx ); + mEnabledCheckBox->setChecked( mLayer->enabled() ); // set the corresponding widget updateSymbolLayerWidget( layer ); connect( cboLayerType, SIGNAL( currentIndexChanged( int ) ), this, SLOT( layerTypeChanged() ) ); @@ -236,3 +237,9 @@ void QgsLayerPropertiesWidget::reloadLayer() { emit changeLayer( mLayer ); } + +void QgsLayerPropertiesWidget::on_mEnabledCheckBox_toggled( bool enabled ) +{ + mLayer->setEnabled( enabled ); + emitSignalChanged(); +} diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.h b/src/gui/symbology-ng/qgslayerpropertieswidget.h index 545b7c586f80..eb4573e35ed8 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.h +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.h @@ -82,6 +82,7 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L private slots: void reloadLayer(); + void on_mEnabledCheckBox_toggled( bool enabled ); private: diff --git a/src/ui/symbollayer/widget_layerproperties.ui b/src/ui/symbollayer/widget_layerproperties.ui index f2d56be27386..7ff618f4f70c 100644 --- a/src/ui/symbollayer/widget_layerproperties.ui +++ b/src/ui/symbollayer/widget_layerproperties.ui @@ -30,7 +30,7 @@ 3 - + @@ -50,6 +50,9 @@ + + + @@ -69,7 +72,34 @@ - + + + 0 + + + 0 + + + + + Enable layer + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + diff --git a/tests/src/python/test_qgssymbollayer.py b/tests/src/python/test_qgssymbollayer.py index 9e298e257bc0..2d2b04aac46e 100644 --- a/tests/src/python/test_qgssymbollayer.py +++ b/tests/src/python/test_qgssymbollayer.py @@ -29,7 +29,7 @@ from qgis.PyQt.QtCore import pyqtWrapperType, Qt, QDir, QFile, QIODevice, QPointF from qgis.PyQt.QtXml import QDomDocument -from qgis.PyQt.QtGui import QColor +from qgis.PyQt.QtGui import QColor, QImage, QPainter from qgis.core import (QgsCentroidFillSymbolLayer, QgsEllipseSymbolLayer, @@ -55,7 +55,17 @@ QgsShapeburstFillSymbolLayer, QgsArrowSymbolLayer, QgsSymbol, - QgsUnitTypes + QgsUnitTypes, + QgsFillSymbol, + QgsLineSymbol, + QgsMarkerSymbol, + QgsSymbolLayerUtils, + QgsMapSettings, + QgsGeometry, + QgsFeature, + QgsRenderContext, + QgsRenderChecker, + QgsRectangle ) from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -79,6 +89,14 @@ class TestQgsSymbolLayer(unittest.TestCase): returns NULL """ + def setUp(self): + self.report = "

                                                                                                                                                                                    Python QgsSymbolLayer Tests

                                                                                                                                                                                    \n" + + def tearDown(self): + report_file_path = "%s/qgistest.html" % QDir.tempPath() + with open(report_file_path, 'a') as report_file: + report_file.write(self.report) + def testBinding(self): """Test python bindings existence.""" mType = type(QgsSymbolLayer) @@ -270,6 +288,181 @@ def testBinding(self): mMessage = 'Expected "%s" got "%s"' % (mExpectedType, mType) assert mExpectedType == mType, mMessage + def testGettersSetters(self): + """ test base class getters/setters """ + layer = QgsSimpleFillSymbolLayer() + + layer.setEnabled(False) + self.assertFalse(layer.enabled()) + layer.setEnabled(True) + self.assertTrue(layer.enabled()) + + layer.setLocked(False) + self.assertFalse(layer.isLocked()) + layer.setLocked(True) + self.assertTrue(layer.isLocked()) + + layer.setRenderingPass(5) + self.assertEqual(layer.renderingPass(), 5) + + def testSaveRestore(self): + """ Test saving and restoring base symbol layer properties to xml""" + + layer = QgsSimpleFillSymbolLayer() + layer.setEnabled(False) + layer.setLocked(True) + layer.setRenderingPass(5) + + symbol = QgsFillSymbol() + symbol.changeSymbolLayer(0, layer) + + doc = QDomDocument("testdoc") + elem = QgsSymbolLayerUtils.saveSymbol('test', symbol, doc) + + restored_symbol = QgsSymbolLayerUtils.loadSymbol(elem) + restored_layer = restored_symbol.symbolLayer(0) + self.assertFalse(restored_layer.enabled()) + self.assertTrue(restored_layer.isLocked()) + self.assertEqual(restored_layer.renderingPass(), 5) + + def testClone(self): + """ test that base symbol layer properties are cloned with layer """ + + layer = QgsSimpleFillSymbolLayer() + layer.setEnabled(False) + layer.setLocked(True) + layer.setRenderingPass(5) + + symbol = QgsFillSymbol() + symbol.changeSymbolLayer(0, layer) + + cloned_symbol = symbol.clone() + cloned_layer = cloned_symbol.symbolLayer(0) + self.assertFalse(cloned_layer.enabled()) + self.assertTrue(cloned_layer.isLocked()) + self.assertEqual(cloned_layer.renderingPass(), 5) + + def imageCheck(self, name, reference_image, image): + self.report += "

                                                                                                                                                                                    Render {}

                                                                                                                                                                                    \n".format(name) + temp_dir = QDir.tempPath() + '/' + file_name = temp_dir + 'symbollayer_' + name + ".png" + image.save(file_name, "PNG") + checker = QgsRenderChecker() + checker.setControlPathPrefix("symbol_layer") + checker.setControlName("expected_" + reference_image) + checker.setRenderedImage(file_name) + checker.setColorTolerance(2) + result = checker.compareImages(name, 20) + self.report += checker.report() + print((self.report)) + return result + + def testRenderFillLayerDisabled(self): + """ test that rendering a fill symbol with disabled layer works""" + layer = QgsSimpleFillSymbolLayer() + layer.setEnabled(False) + + symbol = QgsFillSymbol() + symbol.changeSymbolLayer(0, layer) + + image = QImage(200, 200, QImage.Format_RGB32) + painter = QPainter() + ms = QgsMapSettings() + + geom = QgsGeometry.fromWkt('Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))') + f = QgsFeature() + f.setGeometry(geom) + + extent = geom.geometry().boundingBox() + # buffer extent by 10% + extent = extent.buffer((extent.height() + extent.width()) / 20.0) + + ms.setExtent(extent) + ms.setOutputSize(image.size()) + context = QgsRenderContext.fromMapSettings(ms) + context.setPainter(painter) + context.setScaleFactor(96 / 25.4) # 96 DPI + + painter.begin(image) + image.fill(QColor(255, 255, 255)) + + symbol.startRender(context) + symbol.renderFeature(f, context) + symbol.stopRender(context) + painter.end() + + self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image)) + + def testRenderLineLayerDisabled(self): + """ test that rendering a line symbol with disabled layer works""" + layer = QgsSimpleLineSymbolLayer() + layer.setEnabled(False) + + symbol = QgsLineSymbol() + symbol.changeSymbolLayer(0, layer) + + image = QImage(200, 200, QImage.Format_RGB32) + painter = QPainter() + ms = QgsMapSettings() + + geom = QgsGeometry.fromWkt('LineString (0 0,3 4,4 3)') + f = QgsFeature() + f.setGeometry(geom) + + extent = geom.geometry().boundingBox() + # buffer extent by 10% + extent = extent.buffer((extent.height() + extent.width()) / 20.0) + + ms.setExtent(extent) + ms.setOutputSize(image.size()) + context = QgsRenderContext.fromMapSettings(ms) + context.setPainter(painter) + context.setScaleFactor(96 / 25.4) # 96 DPI + + painter.begin(image) + image.fill(QColor(255, 255, 255)) + + symbol.startRender(context) + symbol.renderFeature(f, context) + symbol.stopRender(context) + painter.end() + + self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image)) + + def testRenderMarkerLayerDisabled(self): + """ test that rendering a marker symbol with disabled layer works""" + layer = QgsSimpleMarkerSymbolLayer() + layer.setEnabled(False) + + symbol = QgsMarkerSymbol() + symbol.changeSymbolLayer(0, layer) + + image = QImage(200, 200, QImage.Format_RGB32) + painter = QPainter() + ms = QgsMapSettings() + + geom = QgsGeometry.fromWkt('Point (1 2)') + f = QgsFeature() + f.setGeometry(geom) + + extent = QgsRectangle(0, 0, 4, 4) + + ms.setExtent(extent) + ms.setOutputSize(image.size()) + context = QgsRenderContext.fromMapSettings(ms) + context.setPainter(painter) + context.setScaleFactor(96 / 25.4) # 96 DPI + + painter.begin(image) + image.fill(QColor(255, 255, 255)) + + symbol.startRender(context) + symbol.renderFeature(f, context) + symbol.stopRender(context) + painter.end() + + self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image)) + def testQgsSimpleFillSymbolLayer(self): """Create a new style from a .sld file and match test. """ diff --git a/tests/testdata/control_images/symbol_layer/expected_symbollayer_disabled/expected_symbollayer_disabled.png b/tests/testdata/control_images/symbol_layer/expected_symbollayer_disabled/expected_symbollayer_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..243ba19d679e759c4c359b86f0cecb372f0d8733 GIT binary patch literal 610 zcmeAS@N?(olHy`uVBq!ia0vp^CqS5k2}mkgS)K$^oCO|{#S9F5M?jcysy3fA0|S$Y zr;B4q#hka74)PvQ5IC^m(%*8sX$nqG-&iVB&Yodk{&zcb#pI1165TDM#0Uw4BW#LX WEWI~Z^-c#S8U{~SKbLh*2~7Y)?DWF` literal 0 HcmV?d00001 From a6148deb3093af0d076a1ab8ad4b470fdd40159b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 15:44:19 +1000 Subject: [PATCH 296/897] [FEATURE] Data defined symbol layer visibility Adds a data defined override to control a symbol layer's visibility. Allows users to disable drawing certain symbol layers for matching features. --- python/core/symbology-ng/qgssymbollayer.sip | 9 +- .../symbology-ng/qgslayerpropertieswidget.sip | 2 +- .../symbology-ng/qgsellipsesymbollayer.cpp | 1 - src/core/symbology-ng/qgsfillsymbollayer.cpp | 16 +-- .../qgsgeometrygeneratorsymbollayer.cpp | 7 +- src/core/symbology-ng/qgslinesymbollayer.cpp | 6 -- .../symbology-ng/qgsmarkersymbollayer.cpp | 4 - src/core/symbology-ng/qgssymbol.cpp | 33 ++++++ src/core/symbology-ng/qgssymbollayer.cpp | 1 + src/core/symbology-ng/qgssymbollayer.h | 17 +-- .../symbology-ng/qgslayerpropertieswidget.cpp | 77 ++++++++++++++ .../symbology-ng/qgslayerpropertieswidget.h | 6 +- src/ui/symbollayer/widget_layerproperties.ui | 25 ++++- tests/src/python/test_qgssymbollayer.py | 99 +++++++++++++++++- .../expected_filllayer_ddenabled.png | Bin 0 -> 6783 bytes .../expected_linelayer_ddenabled.png | Bin 0 -> 6758 bytes .../expected_markerlayer_ddenabled.png | Bin 0 -> 2405 bytes 17 files changed, 262 insertions(+), 41 deletions(-) create mode 100644 tests/testdata/control_images/symbol_layer/expected_filllayer_ddenabled/expected_filllayer_ddenabled.png create mode 100644 tests/testdata/control_images/symbol_layer/expected_linelayer_ddenabled/expected_linelayer_ddenabled.png create mode 100644 tests/testdata/control_images/symbol_layer/expected_markerlayer_ddenabled/expected_markerlayer_ddenabled.png diff --git a/python/core/symbology-ng/qgssymbollayer.sip b/python/core/symbology-ng/qgssymbollayer.sip index bee1c7798426..3df37061fe96 100644 --- a/python/core/symbology-ng/qgssymbollayer.sip +++ b/python/core/symbology-ng/qgssymbollayer.sip @@ -277,9 +277,6 @@ class QgsSymbolLayer */ void setPaintEffect( QgsPaintEffect* effect /Transfer/); - protected: - QgsSymbolLayer( QgsSymbol::SymbolType type, bool locked = false ); - /** Prepares all data defined property expressions for evaluation. This should * be called prior to evaluating data defined properties. * @param context symbol render context @@ -287,6 +284,12 @@ class QgsSymbolLayer */ virtual void prepareExpressions( const QgsSymbolRenderContext& context ); + //! Data defined layer enabled string + static const QString EXPR_LAYER_ENABLED; + + protected: + QgsSymbolLayer( QgsSymbol::SymbolType type, bool locked = false ); + /** Saves all data defined properties to a string map. * @param stringMap destination string map * @see restoreDataDefinedProperties diff --git a/python/gui/symbology-ng/qgslayerpropertieswidget.sip b/python/gui/symbology-ng/qgslayerpropertieswidget.sip index 9b0b9609aa83..83c4bcd69c86 100644 --- a/python/gui/symbology-ng/qgslayerpropertieswidget.sip +++ b/python/gui/symbology-ng/qgslayerpropertieswidget.sip @@ -1,4 +1,4 @@ -class QgsLayerPropertiesWidget : QgsPanelWidget +class QgsLayerPropertiesWidget : QgsPanelWidget, QgsExpressionContextGenerator { %TypeHeaderCode #include diff --git a/src/core/symbology-ng/qgsellipsesymbollayer.cpp b/src/core/symbology-ng/qgsellipsesymbollayer.cpp index 57364613e6e6..66fb783ddb0c 100644 --- a/src/core/symbology-ng/qgsellipsesymbollayer.cpp +++ b/src/core/symbology-ng/qgsellipsesymbollayer.cpp @@ -353,7 +353,6 @@ void QgsEllipseSymbolLayer::startRender( QgsSymbolRenderContext& context ) mPen.setJoinStyle( mPenJoinStyle ); mPen.setWidthF( QgsSymbolLayerUtils::convertToPainterUnits( context.renderContext(), mOutlineWidth, mOutlineWidthUnit, mOutlineWidthMapUnitScale ) ); mBrush.setColor( mColor ); - prepareExpressions( context ); } void QgsEllipseSymbolLayer::stopRender( QgsSymbolRenderContext & ) diff --git a/src/core/symbology-ng/qgsfillsymbollayer.cpp b/src/core/symbology-ng/qgsfillsymbollayer.cpp index e78c9abf1015..cc63c7e4251c 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.cpp +++ b/src/core/symbology-ng/qgsfillsymbollayer.cpp @@ -258,7 +258,6 @@ void QgsSimpleFillSymbolLayer::startRender( QgsSymbolRenderContext& context ) mPen.setStyle( mBorderStyle ); mPen.setWidthF( QgsSymbolLayerUtils::convertToPainterUnits( context.renderContext(), mBorderWidth, mBorderWidthUnit, mBorderWidthMapUnitScale ) ); mPen.setJoinStyle( mPenJoinStyle ); - prepareExpressions( context ); } void QgsSimpleFillSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -838,9 +837,6 @@ void QgsGradientFillSymbolLayer::startRender( QgsSymbolRenderContext& context ) QColor selColor = context.renderContext().selectionColor(); if ( ! selectionIsOpaque ) selColor.setAlphaF( context.alpha() ); mSelBrush = QBrush( selColor ); - - //update mBrush to use a gradient fill with specified properties - prepareExpressions( context ); } void QgsGradientFillSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -1132,8 +1128,6 @@ void QgsShapeburstFillSymbolLayer::startRender( QgsSymbolRenderContext& context QColor selColor = context.renderContext().selectionColor(); if ( ! selectionIsOpaque ) selColor.setAlphaF( context.alpha() ); mSelBrush = QBrush( selColor ); - - prepareExpressions( context ); } void QgsShapeburstFillSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -1996,8 +1990,6 @@ void QgsSVGFillSymbolLayer::startRender( QgsSymbolRenderContext& context ) { mOutline->startRender( context.renderContext(), context.fields() ); } - - prepareExpressions( context ); } void QgsSVGFillSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -2831,8 +2823,6 @@ void QgsLinePatternFillSymbolLayer::startRender( QgsSymbolRenderContext& context { mFillLineSymbol->startRender( context.renderContext(), context.fields() ); } - - prepareExpressions( context ); } void QgsLinePatternFillSymbolLayer::stopRender( QgsSymbolRenderContext & ) @@ -3257,7 +3247,6 @@ void QgsPointPatternFillSymbolLayer::startRender( QgsSymbolRenderContext& contex { mOutline->startRender( context.renderContext(), context.fields() ); } - prepareExpressions( context ); } void QgsPointPatternFillSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -3451,6 +3440,8 @@ QgsSymbolLayer* QgsCentroidFillSymbolLayer::create( const QgsStringMap& properti if ( properties.contains( "point_on_all_parts" ) ) sl->setPointOnAllParts( properties["point_on_all_parts"].toInt() != 0 ); + sl->restoreDataDefinedProperties( properties ); + return sl; } @@ -3533,6 +3524,7 @@ QgsStringMap QgsCentroidFillSymbolLayer::properties() const QgsStringMap map; map["point_on_surface"] = QString::number( mPointOnSurface ); map["point_on_all_parts"] = QString::number( mPointOnAllParts ); + saveDataDefinedProperties( map ); return map; } @@ -3544,6 +3536,7 @@ QgsCentroidFillSymbolLayer* QgsCentroidFillSymbolLayer::clone() const x->setSubSymbol( mMarker->clone() ); x->setPointOnSurface( mPointOnSurface ); x->setPointOnAllParts( mPointOnAllParts ); + copyDataDefinedProperties( x ); copyPaintEffect( x ); return x; } @@ -3760,7 +3753,6 @@ void QgsRasterFillSymbolLayer::renderPolygon( const QPolygonF &points, QListsetSubSymbol( QgsFillSymbol::createSimple( properties ) ); } + symbolLayer->restoreDataDefinedProperties( properties ); return symbolLayer; } @@ -117,6 +118,7 @@ QgsSymbolLayer* QgsGeometryGeneratorSymbolLayer::clone() const clone->setSymbolType( mSymbolType ); + copyDataDefinedProperties( clone ); copyPaintEffect( clone ); return clone; @@ -138,6 +140,7 @@ QgsStringMap QgsGeometryGeneratorSymbolLayer::properties() const props.insert( "SymbolType", "Fill" ); break; } + saveDataDefinedProperties( props ); return props; } @@ -180,7 +183,9 @@ bool QgsGeometryGeneratorSymbolLayer::setSubSymbol( QgsSymbol* symbol ) QSet QgsGeometryGeneratorSymbolLayer::usedAttributes() const { - return mSymbol->usedAttributes() + mExpression->referencedColumns(); + return QgsSymbolLayer::usedAttributes() + + mSymbol->usedAttributes() + + mExpression->referencedColumns(); } bool QgsGeometryGeneratorSymbolLayer::isCompatibleWithSymbol( QgsSymbol* symbol ) const diff --git a/src/core/symbology-ng/qgslinesymbollayer.cpp b/src/core/symbology-ng/qgslinesymbollayer.cpp index 237d4508d7a3..2633544e31cd 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.cpp +++ b/src/core/symbology-ng/qgslinesymbollayer.cpp @@ -228,9 +228,6 @@ void QgsSimpleLineSymbolLayer::startRender( QgsSymbolRenderContext& context ) if ( ! selectionIsOpaque ) selColor.setAlphaF( context.alpha() ); mSelPen.setColor( selColor ); - - //prepare expressions for data defined properties - prepareExpressions( context ); } void QgsSimpleLineSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -815,9 +812,6 @@ void QgsMarkerLineSymbolLayer::startRender( QgsSymbolRenderContext& context ) mMarker->setRenderHints( hints ); mMarker->startRender( context.renderContext(), context.fields() ); - - //prepare expressions for data defined properties - prepareExpressions( context ); } void QgsMarkerLineSymbolLayer::stopRender( QgsSymbolRenderContext& context ) diff --git a/src/core/symbology-ng/qgsmarkersymbollayer.cpp b/src/core/symbology-ng/qgsmarkersymbollayer.cpp index b8676280e2b5..87605334826f 100644 --- a/src/core/symbology-ng/qgsmarkersymbollayer.cpp +++ b/src/core/symbology-ng/qgsmarkersymbollayer.cpp @@ -160,8 +160,6 @@ void QgsSimpleMarkerSymbolLayerBase::startRender( QgsSymbolRenderContext &contex else mPath = transform.map( mPath ); - prepareExpressions( context ); - QgsMarkerSymbolLayer::startRender( context ); } @@ -1909,7 +1907,6 @@ void QgsSvgMarkerSymbolLayer::startRender( QgsSymbolRenderContext& context ) { QgsMarkerSymbolLayer::startRender( context ); // get anchor point expressions Q_UNUSED( context ); - prepareExpressions( context ); } void QgsSvgMarkerSymbolLayer::stopRender( QgsSymbolRenderContext& context ) @@ -2574,7 +2571,6 @@ void QgsFontMarkerSymbolLayer::startRender( QgsSymbolRenderContext& context ) mChrWidth = mFontMetrics->width( mChr ); mChrOffset = QPointF( mChrWidth / 2.0, -mFontMetrics->ascent() / 2.0 ); mOrigSize = mSize; // save in case the size would be data defined - prepareExpressions( context ); } void QgsFontMarkerSymbolLayer::stopRender( QgsSymbolRenderContext& context ) diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index 42bc5efac0c9..bfde6421f6ce 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -400,6 +400,7 @@ void QgsSymbol::startRender( QgsRenderContext& context, const QgsFields& fields if ( !layer->enabled() ) continue; + layer->prepareExpressions( symbolContext ); layer->startRender( symbolContext ); } } @@ -610,6 +611,14 @@ void QgsSymbol::renderUsingLayer( QgsSymbolLayer* layer, QgsSymbolRenderContext& { Q_ASSERT( layer->type() == Hybrid ); + if ( layer->hasDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED ) ) + { + bool ok = false; + bool enabled = layer->evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED, context, QVariant(), &ok ).toBool(); + if ( ok && !enabled ) + return; + } + QgsGeometryGeneratorSymbolLayer* generatorLayer = static_cast( layer ); QgsPaintEffect* effect = generatorLayer->paintEffect(); @@ -1403,6 +1412,14 @@ void QgsMarkerSymbol::renderPointUsingLayer( QgsMarkerSymbolLayer* layer, QPoint { static QPointF nullPoint( 0, 0 ); + if ( layer->hasDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED ) ) + { + bool ok = false; + bool enabled = layer->evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED, context, QVariant(), &ok ).toBool(); + if ( ok && !enabled ) + return; + } + QgsPaintEffect* effect = layer->paintEffect(); if ( effect && effect->enabled() ) { @@ -1676,6 +1693,14 @@ void QgsLineSymbol::renderPolyline( const QPolygonF& points, const QgsFeature* f void QgsLineSymbol::renderPolylineUsingLayer( QgsLineSymbolLayer *layer, const QPolygonF &points, QgsSymbolRenderContext &context ) { + if ( layer->hasDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED ) ) + { + bool ok = false; + bool enabled = layer->evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED, context, QVariant(), &ok ).toBool(); + if ( ok && !enabled ) + return; + } + QgsPaintEffect* effect = layer->paintEffect(); if ( effect && effect->enabled() ) { @@ -1748,6 +1773,14 @@ void QgsFillSymbol::renderPolygon( const QPolygonF& points, QList* ri void QgsFillSymbol::renderPolygonUsingLayer( QgsSymbolLayer* layer, const QPolygonF& points, QList* rings, QgsSymbolRenderContext& context ) { + if ( layer->hasDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED ) ) + { + bool ok = false; + bool enabled = layer->evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED, context, QVariant(), &ok ).toBool(); + if ( ok && !enabled ) + return; + } + QgsSymbol::SymbolType layertype = layer->type(); QgsPaintEffect* effect = layer->paintEffect(); diff --git a/src/core/symbology-ng/qgssymbollayer.cpp b/src/core/symbology-ng/qgssymbollayer.cpp index fe95e6d259e6..9e9ed17efc79 100644 --- a/src/core/symbology-ng/qgssymbollayer.cpp +++ b/src/core/symbology-ng/qgssymbollayer.cpp @@ -89,6 +89,7 @@ const QString QgsSymbolLayer::EXPR_INTERVAL( "interval" ); const QString QgsSymbolLayer::EXPR_OFFSET_ALONG_LINE( "offset_along_line" ); const QString QgsSymbolLayer::EXPR_HORIZONTAL_ANCHOR_POINT( "horizontal_anchor_point" ); const QString QgsSymbolLayer::EXPR_VERTICAL_ANCHOR_POINT( "vertical_anchor_point" ); +const QString QgsSymbolLayer::EXPR_LAYER_ENABLED( "enabled" ); QgsDataDefined *QgsSymbolLayer::getDataDefinedProperty( const QString &property ) const { diff --git a/src/core/symbology-ng/qgssymbollayer.h b/src/core/symbology-ng/qgssymbollayer.h index bd4265ce2e48..3b9610847868 100644 --- a/src/core/symbology-ng/qgssymbollayer.h +++ b/src/core/symbology-ng/qgssymbollayer.h @@ -278,6 +278,16 @@ class CORE_EXPORT QgsSymbolLayer */ void setPaintEffect( QgsPaintEffect* effect ); + /** Prepares all data defined property expressions for evaluation. This should + * be called prior to evaluating data defined properties. + * @param context symbol render context + * @note added in QGIS 2.12 + */ + virtual void prepareExpressions( const QgsSymbolRenderContext& context ); + + //! Data defined layer enabled string + static const QString EXPR_LAYER_ENABLED; + protected: QgsSymbolLayer( QgsSymbol::SymbolType type, bool locked = false ); @@ -299,13 +309,6 @@ class CORE_EXPORT QgsSymbolLayer static const bool selectFillBorder = false; // Fill symbol layer also selects border symbology static const bool selectFillStyle = false; // Fill symbol uses symbol layer style.. - /** Prepares all data defined property expressions for evaluation. This should - * be called prior to evaluating data defined properties. - * @param context symbol render context - * @note added in QGIS 2.12 - */ - virtual void prepareExpressions( const QgsSymbolRenderContext& context ); - /** Saves all data defined properties to a string map. * @param stringMap destination string map * @see restoreDataDefinedProperties diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp index 6f3e149ccaff..2b45bdcbf317 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp @@ -33,6 +33,9 @@ #include "qgsvectorfieldsymbollayerwidget.h" #include "qgssymbol.h" //for the unit #include "qgspanelwidget.h" +#include "qgsdatadefined.h" +#include "qgsmapcanvas.h" +#include "qgsvectorlayer.h" static bool _initWidgetFunction( const QString& name, QgsSymbolLayerWidgetFunc f ) { @@ -112,7 +115,10 @@ QgsLayerPropertiesWidget::QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const // update layer type combo box int idx = cboLayerType->findData( mLayer->layerType() ); cboLayerType->setCurrentIndex( idx ); + + connect( mEnabledCheckBox, SIGNAL( toggled( bool ) ), mEnabledDDBtn, SLOT( setEnabled( bool ) ) ); mEnabledCheckBox->setChecked( mLayer->enabled() ); + // set the corresponding widget updateSymbolLayerWidget( layer ); connect( cboLayerType, SIGNAL( currentIndexChanged( int ) ), this, SLOT( layerTypeChanged() ) ); @@ -122,6 +128,25 @@ QgsLayerPropertiesWidget::QgsLayerPropertiesWidget( QgsSymbolLayer* layer, const this->connectChildPanel( mEffectWidget ); mEffectWidget->setPaintEffect( mLayer->paintEffect() ); + + const QgsDataDefined* dd = mLayer->getDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED ); + mEnabledDDBtn->init( mVectorLayer, dd, QgsDataDefinedButton::AnyType, QgsDataDefinedButton::boolDesc() ); + connect( mEnabledDDBtn, SIGNAL( dataDefinedChanged( const QString& ) ), this, SLOT( updateDataDefinedEnable() ) ); + connect( mEnabledDDBtn, SIGNAL( dataDefinedActivated( bool ) ), this, SLOT( updateDataDefinedEnable() ) ); + mEnabledDDBtn->registerExpressionContextGenerator( this ); +} + +void QgsLayerPropertiesWidget::updateDataDefinedEnable() +{ + QgsDataDefined* dd = mLayer->getDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED ); + if ( !dd ) + { + dd = new QgsDataDefined(); + mLayer->setDataDefinedProperty( QgsSymbolLayer::EXPR_LAYER_ENABLED, dd ); + } + mEnabledDDBtn->updateDataDefined( dd ); + + emit changed(); } void QgsLayerPropertiesWidget::setContext( const QgsSymbolWidgetContext& context ) @@ -199,6 +224,58 @@ void QgsLayerPropertiesWidget::updateSymbolLayerWidget( QgsSymbolLayer* layer ) stackedWidget->setCurrentWidget( pageDummy ); } +QgsExpressionContext QgsLayerPropertiesWidget::createExpressionContext() const +{ + if ( mContext.expressionContext() ) + return *mContext.expressionContext(); + + QgsExpressionContext expContext; + expContext << QgsExpressionContextUtils::globalScope() + << QgsExpressionContextUtils::projectScope() + << QgsExpressionContextUtils::atlasScope( nullptr ); + + if ( mContext.mapCanvas() ) + { + expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() ) + << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() ); + } + else + { + expContext << QgsExpressionContextUtils::mapSettingsScope( QgsMapSettings() ); + } + + expContext << QgsExpressionContextUtils::layerScope( mVectorLayer ); + + QgsExpressionContextScope* symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() ); + if ( mLayer ) + { + //cheat a bit - set the symbol color variable to match the symbol layer's color (when we should really be using the *symbols* + //color, but that's not accessible here). 99% of the time these will be the same anyway + symbolScope->setVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, mLayer->color() ); + } + expContext << symbolScope; + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT, 1, true ) ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, 1, true ) ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, 1, true ) ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, 1, true ) ); + + // additional scopes + Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() ) + { + expContext.appendScope( new QgsExpressionContextScope( scope ) ); + } + + //TODO - show actual value + expContext.setOriginalValueVariable( QVariant() ); + + expContext.setHighlightedVariables( QStringList() << QgsExpressionContext::EXPR_ORIGINAL_VALUE << QgsExpressionContext::EXPR_SYMBOL_COLOR + << QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT << QgsExpressionContext::EXPR_GEOMETRY_PART_NUM + << QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT << QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM + << QgsExpressionContext::EXPR_CLUSTER_COLOR << QgsExpressionContext::EXPR_CLUSTER_SIZE ); + + return expContext; +} + void QgsLayerPropertiesWidget::layerTypeChanged() { QgsSymbolLayer* layer = mLayer; diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.h b/src/gui/symbology-ng/qgslayerpropertieswidget.h index eb4573e35ed8..c1aed7d18c5c 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.h +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.h @@ -35,7 +35,7 @@ class SymbolLayerItem; /** \ingroup gui * \class QgsLayerPropertiesWidget */ -class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::LayerPropertiesWidget +class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, protected QgsExpressionContextGenerator, private Ui::LayerPropertiesWidget { Q_OBJECT @@ -74,6 +74,8 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L void populateLayerTypes(); void updateSymbolLayerWidget( QgsSymbolLayer* layer ); + QgsExpressionContext createExpressionContext() const override; + protected: // data QgsSymbolLayer* mLayer; @@ -84,6 +86,8 @@ class GUI_EXPORT QgsLayerPropertiesWidget : public QgsPanelWidget, private Ui::L void reloadLayer(); void on_mEnabledCheckBox_toggled( bool enabled ); + void updateDataDefinedEnable(); + private: QgsSymbolWidgetContext mContext; diff --git a/src/ui/symbollayer/widget_layerproperties.ui b/src/ui/symbollayer/widget_layerproperties.ui index 7ff618f4f70c..0b15f442902e 100644 --- a/src/ui/symbollayer/widget_layerproperties.ui +++ b/src/ui/symbollayer/widget_layerproperties.ui @@ -50,9 +50,6 @@ - - - @@ -86,6 +83,23 @@ + + + + ... + + + + + + + 30 + + + + + + @@ -110,6 +124,11 @@
                                                                                                                                                                                    qgseffectstackpropertieswidget.h
                                                                                                                                                                                    1 + + QgsDataDefinedButton + QToolButton +
                                                                                                                                                                                    qgsdatadefinedbutton.h
                                                                                                                                                                                    +
                                                                                                                                                                                    diff --git a/tests/src/python/test_qgssymbollayer.py b/tests/src/python/test_qgssymbollayer.py index 2d2b04aac46e..5fa7ee132c3f 100644 --- a/tests/src/python/test_qgssymbollayer.py +++ b/tests/src/python/test_qgssymbollayer.py @@ -27,7 +27,7 @@ import os -from qgis.PyQt.QtCore import pyqtWrapperType, Qt, QDir, QFile, QIODevice, QPointF +from qgis.PyQt.QtCore import pyqtWrapperType, Qt, QDir, QFile, QIODevice, QPointF, QSize from qgis.PyQt.QtXml import QDomDocument from qgis.PyQt.QtGui import QColor, QImage, QPainter @@ -65,7 +65,12 @@ QgsFeature, QgsRenderContext, QgsRenderChecker, - QgsRectangle + QgsRectangle, + QgsVectorLayer, + QgsMapLayerRegistry, + QgsMultiRenderChecker, + QgsSingleSymbolRenderer, + QgsDataDefined ) from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -74,6 +79,8 @@ # not used in this test start_app() +TEST_DATA_DIR = unitTestDataPath() + class TestQgsSymbolLayer(unittest.TestCase): @@ -393,6 +400,35 @@ def testRenderFillLayerDisabled(self): self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image)) + def testRenderFillLayerDataDefined(self): + """ test that rendering a fill symbol with data defined enabled layer works""" + + polys_shp = os.path.join(TEST_DATA_DIR, 'polys.shp') + polys_layer = QgsVectorLayer(polys_shp, 'Polygons', 'ogr') + QgsMapLayerRegistry.instance().addMapLayer(polys_layer) + + layer = QgsSimpleFillSymbolLayer() + layer.setDataDefinedProperty("enabled", QgsDataDefined("Name='Lake'")) + layer.setBorderStyle(Qt.NoPen) + layer.setColor(QColor(100, 150, 150)) + + symbol = QgsFillSymbol() + symbol.changeSymbolLayer(0, layer) + polys_layer.setRenderer(QgsSingleSymbolRenderer(symbol)) + + ms = QgsMapSettings() + ms.setOutputSize(QSize(400, 400)) + ms.setOutputDpi(96) + ms.setExtent(QgsRectangle(-133, 22, -70, 52)) + ms.setLayers([polys_layer.id()]) + + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(ms) + renderchecker.setControlPathPrefix('symbol_layer') + renderchecker.setControlName('expected_filllayer_ddenabled') + self.assertTrue(renderchecker.runTest('filllayer_ddenabled')) + QgsMapLayerRegistry.instance().removeMapLayer(polys_layer) + def testRenderLineLayerDisabled(self): """ test that rendering a line symbol with disabled layer works""" layer = QgsSimpleLineSymbolLayer() @@ -429,6 +465,35 @@ def testRenderLineLayerDisabled(self): self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image)) + def testRenderLineLayerDataDefined(self): + """ test that rendering a line symbol with data defined enabled layer works""" + + lines_shp = os.path.join(TEST_DATA_DIR, 'lines.shp') + lines_layer = QgsVectorLayer(lines_shp, 'Lines', 'ogr') + QgsMapLayerRegistry.instance().addMapLayer(lines_layer) + + layer = QgsSimpleLineSymbolLayer() + layer.setDataDefinedProperty("enabled", QgsDataDefined("Name='Highway'")) + layer.setColor(QColor(100, 150, 150)) + layer.setWidth(5) + + symbol = QgsLineSymbol() + symbol.changeSymbolLayer(0, layer) + lines_layer.setRenderer(QgsSingleSymbolRenderer(symbol)) + + ms = QgsMapSettings() + ms.setOutputSize(QSize(400, 400)) + ms.setOutputDpi(96) + ms.setExtent(QgsRectangle(-133, 22, -70, 52)) + ms.setLayers([lines_layer.id()]) + + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(ms) + renderchecker.setControlPathPrefix('symbol_layer') + renderchecker.setControlName('expected_linelayer_ddenabled') + self.assertTrue(renderchecker.runTest('linelayer_ddenabled')) + QgsMapLayerRegistry.instance().removeMapLayer(lines_layer) + def testRenderMarkerLayerDisabled(self): """ test that rendering a marker symbol with disabled layer works""" layer = QgsSimpleMarkerSymbolLayer() @@ -463,6 +528,36 @@ def testRenderMarkerLayerDisabled(self): self.assertTrue(self.imageCheck('symbol_layer', 'symbollayer_disabled', image)) + def testRenderMarkerLayerDataDefined(self): + """ test that rendering a marker symbol with data defined enabled layer works""" + + points_shp = os.path.join(TEST_DATA_DIR, 'points.shp') + points_layer = QgsVectorLayer(points_shp, 'Points', 'ogr') + QgsMapLayerRegistry.instance().addMapLayer(points_layer) + + layer = QgsSimpleMarkerSymbolLayer() + layer.setDataDefinedProperty("enabled", QgsDataDefined("Class='Biplane'")) + layer.setColor(QColor(100, 150, 150)) + layer.setSize(5) + layer.setOutlineStyle(Qt.NoPen) + + symbol = QgsMarkerSymbol() + symbol.changeSymbolLayer(0, layer) + points_layer.setRenderer(QgsSingleSymbolRenderer(symbol)) + + ms = QgsMapSettings() + ms.setOutputSize(QSize(400, 400)) + ms.setOutputDpi(96) + ms.setExtent(QgsRectangle(-133, 22, -70, 52)) + ms.setLayers([points_layer.id()]) + + renderchecker = QgsMultiRenderChecker() + renderchecker.setMapSettings(ms) + renderchecker.setControlPathPrefix('symbol_layer') + renderchecker.setControlName('expected_markerlayer_ddenabled') + self.assertTrue(renderchecker.runTest('markerlayer_ddenabled')) + QgsMapLayerRegistry.instance().removeMapLayer(points_layer) + def testQgsSimpleFillSymbolLayer(self): """Create a new style from a .sld file and match test. """ diff --git a/tests/testdata/control_images/symbol_layer/expected_filllayer_ddenabled/expected_filllayer_ddenabled.png b/tests/testdata/control_images/symbol_layer/expected_filllayer_ddenabled/expected_filllayer_ddenabled.png new file mode 100644 index 0000000000000000000000000000000000000000..cfba7437337f3201b97c9e62de3819af3166bd89 GIT binary patch literal 6783 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 P1bhr{nCez)-+BBm?&R~= literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/symbol_layer/expected_linelayer_ddenabled/expected_linelayer_ddenabled.png b/tests/testdata/control_images/symbol_layer/expected_linelayer_ddenabled/expected_linelayer_ddenabled.png new file mode 100644 index 0000000000000000000000000000000000000000..cd4e1e25048b9abb48253e5276c2b596fb957999 GIT binary patch literal 6758 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 literal 0 HcmV?d00001 From 2835cad6ebc959a546b65ce2dc8588b2077eaa69 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 20:21:23 +1000 Subject: [PATCH 297/897] Grey out disabled symbol layers in tree --- src/gui/symbology-ng/qgssymbolselectordialog.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.cpp b/src/gui/symbology-ng/qgssymbolselectordialog.cpp index 5d2a3d2b1d98..a727846b15ab 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.cpp +++ b/src/gui/symbology-ng/qgssymbolselectordialog.cpp @@ -191,6 +191,16 @@ class SymbolLayerItem : public QStandardItem } } } + else if ( role == Qt::ForegroundRole && mIsLayer ) + { + QBrush brush( Qt::black, Qt::SolidPattern ); + if ( !mLayer->enabled() ) + { + brush.setColor( Qt::lightGray ); + } + return brush; + } + // if ( role == Qt::SizeHintRole ) // return QVariant( QSize( 32, 32 ) ); if ( role == Qt::CheckStateRole ) From fb860fb618f785a929ba7ffc15797fdd7589cdc0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 18 Oct 2016 11:37:48 +1000 Subject: [PATCH 298/897] New class QgsBearingUtils with method to calculate true north --- python/core/core.sip | 1 + python/core/qgsbearingutils.sip | 21 +++++++++ src/core/CMakeLists.txt | 2 + src/core/qgsbearingutils.cpp | 49 ++++++++++++++++++++ src/core/qgsbearingutils.h | 45 ++++++++++++++++++ tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgsbearingutils.py | 59 ++++++++++++++++++++++++ 7 files changed, 178 insertions(+) create mode 100644 python/core/qgsbearingutils.sip create mode 100644 src/core/qgsbearingutils.cpp create mode 100644 src/core/qgsbearingutils.h create mode 100644 tests/src/python/test_qgsbearingutils.py diff --git a/python/core/core.sip b/python/core/core.sip index 6aea0feb7802..6dd36227ae6e 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -21,6 +21,7 @@ %Include qgsaggregatecalculator.sip %Include qgsattributetableconfig.sip %Include qgsattributeeditorelement.sip +%Include qgsbearingutils.sip %Include qgsbrowsermodel.sip %Include qgsclipper.sip %Include qgscolorramp.sip diff --git a/python/core/qgsbearingutils.sip b/python/core/qgsbearingutils.sip new file mode 100644 index 000000000000..078907cd5d82 --- /dev/null +++ b/python/core/qgsbearingutils.sip @@ -0,0 +1,21 @@ +/** + * \class QgsBearingUtils + * \ingroup core + * Utilities for calculating bearings and directions. + * \note Added in version 2.18 +*/ +class QgsBearingUtils +{ +%TypeHeaderCode +#include +%End + public: + + /** + * Returns the direction to true north from a specified point and for a specified + * coordinate reference system. The returned value is in degrees clockwise from + * vertical. An exception will be thrown if the bearing could not be calculated. + */ + static double bearingTrueNorth( const QgsCoordinateReferenceSystem& crs, + const QgsPoint& point ); +}; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index dd64fdb41d9c..e09cccab8218 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -85,6 +85,7 @@ SET(QGIS_CORE_SRCS qgsaggregatecalculator.cpp qgsattributetableconfig.cpp qgsattributeeditorelement.cpp + qgsbearingutils.cpp qgsbrowsermodel.cpp qgscachedfeatureiterator.cpp qgscacheindex.cpp @@ -600,6 +601,7 @@ SET(QGIS_CORE_HDRS qgsannotation.h qgsattributetableconfig.h qgsattributeeditorelement.h + qgsbearingutils.h qgscachedfeatureiterator.h qgscacheindex.h qgscacheindexfeatureid.h diff --git a/src/core/qgsbearingutils.cpp b/src/core/qgsbearingutils.cpp new file mode 100644 index 000000000000..0ba94138af3c --- /dev/null +++ b/src/core/qgsbearingutils.cpp @@ -0,0 +1,49 @@ +/*************************************************************************** + qgsbearingutils.cpp + ------------------- + begin : October 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgsbearingutils.h" +#include "qgscoordinatereferencesystem.h" +#include "qgspoint.h" +#include "qgscoordinatetransform.h" +#include "qgsexception.h" + +double QgsBearingUtils::bearingTrueNorth( const QgsCoordinateReferenceSystem &crs, const QgsPoint &point ) +{ + // step 1 - transform point into WGS84 geographic crs + QgsCoordinateTransform transform( crs, QgsCoordinateReferenceSystem::fromEpsgId( 4326 ) ); + + if ( !transform.isValid() ) + { + //raise + throw QgsException( QObject::tr( "Could not create transform to calculate true north" ) ); + } + + if ( transform.isShortCircuited() ) + return 0.0; + + QgsPoint p1 = transform.transform( point ); + + // shift point a tiny bit north + QgsPoint p2 = p1; + p2.setY( p2.y() + 0.000001 ); + + //transform back + QgsPoint p3 = transform.transform( p2, QgsCoordinateTransform::ReverseTransform ); + + // find bearing from point to p3 + return point.azimuth( p3 ); +} diff --git a/src/core/qgsbearingutils.h b/src/core/qgsbearingutils.h new file mode 100644 index 000000000000..400d107ba24e --- /dev/null +++ b/src/core/qgsbearingutils.h @@ -0,0 +1,45 @@ +/*************************************************************************** + qgsbearingutils.h + ----------------- + begin : October 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSBEARINGUTILS_H +#define QGSBEARINGUTILS_H + +class QgsCoordinateReferenceSystem; +class QgsPoint; + + +/** + * \class QgsBearingUtils + * \ingroup core + * Utilities for calculating bearings and directions. + * \note Added in version 2.18 +*/ +class CORE_EXPORT QgsBearingUtils +{ + public: + + /** + * Returns the direction to true north from a specified point and for a specified + * coordinate reference system. The returned value is in degrees clockwise from + * vertical. An exception will be thrown if the bearing could not be calculated. + */ + static double bearingTrueNorth( const QgsCoordinateReferenceSystem& crs, + const QgsPoint& point ); + +}; + +#endif //QGSBEARINGUTILS_H diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index e86c51356057..db31d0a6b2ca 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -17,6 +17,7 @@ ADD_PYTHON_TEST(PyQgsAttributeFormEditorWidget test_qgsattributeformeditorwidget ADD_PYTHON_TEST(PyQgsAttributeTableConfig test_qgsattributetableconfig.py) ADD_PYTHON_TEST(PyQgsAttributeTableModel test_qgsattributetablemodel.py) #ADD_PYTHON_TEST(PyQgsAuthenticationSystem test_qgsauthsystem.py) +ADD_PYTHON_TEST(PyQgsBearingUtils test_qgsbearingutils.py) ADD_PYTHON_TEST(PyQgsBlendModes test_qgsblendmodes.py) ADD_PYTHON_TEST(PyQgsCategorizedSymbolRenderer test_qgscategorizedsymbolrenderer.py) ADD_PYTHON_TEST(PyQgsColorButton test_qgscolorbutton.py) diff --git a/tests/src/python/test_qgsbearingutils.py b/tests/src/python/test_qgsbearingutils.py new file mode 100644 index 000000000000..f091b55f0169 --- /dev/null +++ b/tests/src/python/test_qgsbearingutils.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsBearingUtils. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '18/10/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # switch sip api + +from qgis.core import (QgsBearingUtils, + QgsCoordinateReferenceSystem, + QgsPoint + ) + +from qgis.testing import (start_app, + unittest + ) + + +start_app() + + +class TestQgsBearingUtils(unittest.TestCase): + + def testTrueNorth(self): + """ test calculating bearing to true north""" + + # short circuit - already a geographic crs + crs = QgsCoordinateReferenceSystem.fromEpsgId(4326) + self.assertEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(0, 0)), 0) + self.assertEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(44, 0)), 0) + self.assertEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(44, -43)), 0) + self.assertEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(44, 43)), 0) + + self.assertEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(44, 200)), 0) + self.assertEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(44, -200)), 0) + + # no short circuit + crs = QgsCoordinateReferenceSystem.fromEpsgId(3111) + self.assertAlmostEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(2508807, 2423425)), 0.06, 2) + + # try a south-up crs + crs = QgsCoordinateReferenceSystem.fromEpsgId(2053) + self.assertAlmostEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(29, -27.55)), -180.0, 1) + + # try a north pole crs + crs = QgsCoordinateReferenceSystem.fromEpsgId(3575) + self.assertAlmostEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(-780770, 652329)), 129.9, 1) + self.assertAlmostEqual(QgsBearingUtils.bearingTrueNorth(crs, QgsPoint(513480, 873173)), -149.5, 1) + +if __name__ == '__main__': + unittest.main() From e8be0ed988f091bac1c8c6653777869f9f3f222c Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 18 Oct 2016 13:40:34 +1000 Subject: [PATCH 299/897] [composer] Allow syncing pictures to true north Previously pictures could only be synced to grid north, which can be totally wrong for many CRSes (especially in polar areas) Users now are given a choice of grid or true north, and can also enter an optional offset to apply if eg magnetic north is instead desired. When synced to true north the bearing is calculated using the centre point of the linked map item. Fix #192, #4711 This fix was sponsored by the Norwegian Polar Institute's Quantarctica project (http://quantarctica.npolar.no) and coordinated by Faunalia. --- ci/travis/linux/blacklist.txt | 1 - python/core/composer/qgscomposerpicture.sip | 39 ++++++++++ src/app/composer/qgscomposerpicturewidget.cpp | 37 +++++++++ src/app/composer/qgscomposerpicturewidget.h | 2 + src/core/composer/qgscomposeritemcommand.h | 1 + src/core/composer/qgscomposerpicture.cpp | 75 +++++++++++++++++-- src/core/composer/qgscomposerpicture.h | 47 ++++++++++++ .../composer/qgscomposerpicturewidgetbase.ui | 39 +++++++++- tests/src/python/test_qgscomposerpicture.py | 62 ++++++++++++++- 9 files changed, 293 insertions(+), 10 deletions(-) diff --git a/ci/travis/linux/blacklist.txt b/ci/travis/linux/blacklist.txt index ec620316bd9a..5cf3ccbf362e 100755 --- a/ci/travis/linux/blacklist.txt +++ b/ci/travis/linux/blacklist.txt @@ -1,4 +1,3 @@ -PyQgsComposerPicture PyQgsJSONUtils PyQgsLocalServer PyQgsPalLabelingServer diff --git a/python/core/composer/qgscomposerpicture.sip b/python/core/composer/qgscomposerpicture.sip index 73ffdfcabafc..fe9dbb818232 100644 --- a/python/core/composer/qgscomposerpicture.sip +++ b/python/core/composer/qgscomposerpicture.sip @@ -30,6 +30,13 @@ class QgsComposerPicture: QgsComposerItem Unknown }; + //! Method for syncing rotation to a map's North direction + enum NorthMode + { + GridNorth, /*!< Align to grid north */ + TrueNorth, /*!< Align to true north */ + }; + QgsComposerPicture( QgsComposition *composition /TransferThis/); ~QgsComposerPicture(); @@ -109,6 +116,38 @@ class QgsComposerPicture: QgsComposerItem */ bool useRotationMap() const; + /** + * Returns the mode used to align the picture to a map's North. + * @see setNorthMode() + * @see northOffset() + * @note added in QGIS 2.18 + */ + NorthMode northMode() const; + + /** + * Sets the mode used to align the picture to a map's North. + * @see northMode() + * @see setNorthOffset() + * @note added in QGIS 2.18 + */ + void setNorthMode( NorthMode mode ); + + /** + * Returns the offset added to the picture's rotation from a map's North. + * @see setNorthOffset() + * @see northMode() + * @note added in QGIS 2.18 + */ + double northOffset() const; + + /** + * Sets the offset added to the picture's rotation from a map's North. + * @see northOffset() + * @see setNorthMode() + * @note added in QGIS 2.18 + */ + void setNorthOffset( double offset ); + /** Returns the resize mode used for drawing the picture within the composer * item's frame. * @returns resize mode of picture diff --git a/src/app/composer/qgscomposerpicturewidget.cpp b/src/app/composer/qgscomposerpicturewidget.cpp index cc055d8de150..458d0898407a 100644 --- a/src/app/composer/qgscomposerpicturewidget.cpp +++ b/src/app/composer/qgscomposerpicturewidget.cpp @@ -45,6 +45,13 @@ QgsComposerPictureWidget::QgsComposerPictureWidget( QgsComposerPicture* picture mOutlineColorButton->setColorDialogTitle( tr( "Select outline color" ) ); mOutlineColorButton->setContext( "composer" ); + mNorthTypeComboBox->blockSignals( true ); + mNorthTypeComboBox->addItem( tr( "Grid north" ), QgsComposerPicture::GridNorth ); + mNorthTypeComboBox->addItem( tr( "True north" ), QgsComposerPicture::TrueNorth ); + mNorthTypeComboBox->blockSignals( false ); + mPictureRotationOffsetSpinBox->setClearValue( 0.0 ); + mPictureRotationSpinBox->setClearValue( 0.0 ); + //add widget for general composer item properties QgsComposerItemWidget* itemPropertiesWidget = new QgsComposerItemWidget( this, picture ); mainLayout->addWidget( itemPropertiesWidget ); @@ -270,6 +277,8 @@ void QgsComposerPictureWidget::on_mRotationFromComposerMapCheckBox_stateChanged( mPicture->setRotationMap( -1 ); mPictureRotationSpinBox->setEnabled( true ); mComposerMapComboBox->setEnabled( false ); + mNorthTypeComboBox->setEnabled( false ); + mPictureRotationOffsetSpinBox->setEnabled( false ); mPicture->setPictureRotation( mPictureRotationSpinBox->value() ); } else @@ -278,6 +287,8 @@ void QgsComposerPictureWidget::on_mRotationFromComposerMapCheckBox_stateChanged( int mapId = map ? map->id() : -1; mPicture->setRotationMap( mapId ); mPictureRotationSpinBox->setEnabled( false ); + mNorthTypeComboBox->setEnabled( true ); + mPictureRotationOffsetSpinBox->setEnabled( true ); mComposerMapComboBox->setEnabled( true ); } mPicture->endCommand(); @@ -325,6 +336,8 @@ void QgsComposerPictureWidget::setGuiElementValues() mPictureLineEdit->blockSignals( true ); mComposerMapComboBox->blockSignals( true ); mRotationFromComposerMapCheckBox->blockSignals( true ); + mNorthTypeComboBox->blockSignals( true ); + mPictureRotationOffsetSpinBox->blockSignals( true ); mResizeModeComboBox->blockSignals( true ); mAnchorPointComboBox->blockSignals( true ); mFillColorButton->blockSignals( true ); @@ -345,13 +358,19 @@ void QgsComposerPictureWidget::setGuiElementValues() mRotationFromComposerMapCheckBox->setCheckState( Qt::Checked ); mPictureRotationSpinBox->setEnabled( false ); mComposerMapComboBox->setEnabled( true ); + mNorthTypeComboBox->setEnabled( true ); + mPictureRotationOffsetSpinBox->setEnabled( true ); } else { mRotationFromComposerMapCheckBox->setCheckState( Qt::Unchecked ); mPictureRotationSpinBox->setEnabled( true ); mComposerMapComboBox->setEnabled( false ); + mNorthTypeComboBox->setEnabled( false ); + mPictureRotationOffsetSpinBox->setEnabled( false ); } + mNorthTypeComboBox->setCurrentIndex( mNorthTypeComboBox->findData( mPicture->northMode() ) ); + mPictureRotationOffsetSpinBox->setValue( mPicture->northOffset() ); mResizeModeComboBox->setCurrentIndex(( int )mPicture->resizeMode() ); //disable picture rotation for non-zoom modes @@ -379,6 +398,8 @@ void QgsComposerPictureWidget::setGuiElementValues() mPictureRotationSpinBox->blockSignals( false ); mPictureLineEdit->blockSignals( false ); mComposerMapComboBox->blockSignals( false ); + mNorthTypeComboBox->blockSignals( false ); + mPictureRotationOffsetSpinBox->blockSignals( false ); mResizeModeComboBox->blockSignals( false ); mAnchorPointComboBox->blockSignals( false ); mFillColorButton->blockSignals( false ); @@ -655,6 +676,22 @@ void QgsComposerPictureWidget::on_mOutlineWidthSpinBox_valueChanged( double d ) mPicture->update(); } +void QgsComposerPictureWidget::on_mPictureRotationOffsetSpinBox_valueChanged( double d ) +{ + mPicture->beginCommand( tr( "Picture North offset changed" ), QgsComposerMergeCommand::ComposerPictureNorthOffset ); + mPicture->setNorthOffset( d ); + mPicture->endCommand(); + mPicture->update(); +} + +void QgsComposerPictureWidget::on_mNorthTypeComboBox_currentIndexChanged( int index ) +{ + mPicture->beginCommand( tr( "Picture North mode changed" ) ); + mPicture->setNorthMode( static_cast< QgsComposerPicture::NorthMode >( mNorthTypeComboBox->itemData( index ).toInt() ) ); + mPicture->endCommand(); + mPicture->update(); +} + void QgsComposerPictureWidget::resizeEvent( QResizeEvent * event ) { Q_UNUSED( event ); diff --git a/src/app/composer/qgscomposerpicturewidget.h b/src/app/composer/qgscomposerpicturewidget.h index b87c05fbf373..4f6eaf4466ff 100644 --- a/src/app/composer/qgscomposerpicturewidget.h +++ b/src/app/composer/qgscomposerpicturewidget.h @@ -70,6 +70,8 @@ class QgsComposerPictureWidget: public QgsComposerItemBaseWidget, private Ui::Qg void on_mFillColorButton_colorChanged( const QColor& color ); void on_mOutlineColorButton_colorChanged( const QColor& color ); void on_mOutlineWidthSpinBox_valueChanged( double d ); + void on_mPictureRotationOffsetSpinBox_valueChanged( double d ); + void on_mNorthTypeComboBox_currentIndexChanged( int index ); private: QgsComposerPicture* mPicture; diff --git a/src/core/composer/qgscomposeritemcommand.h b/src/core/composer/qgscomposeritemcommand.h index 4b931186176e..711e33b8c569 100644 --- a/src/core/composer/qgscomposeritemcommand.h +++ b/src/core/composer/qgscomposeritemcommand.h @@ -118,6 +118,7 @@ class CORE_EXPORT QgsComposerMergeCommand: public QgsComposerItemCommand ComposerPictureRotation, ComposerPictureFillColor, ComposerPictureOutlineColor, + ComposerPictureNorthOffset, // composer scalebar ScaleBarLineWidth, ScaleBarHeight, diff --git a/src/core/composer/qgscomposerpicture.cpp b/src/core/composer/qgscomposerpicture.cpp index 564bd33ed92a..c7bc7cd87050 100644 --- a/src/core/composer/qgscomposerpicture.cpp +++ b/src/core/composer/qgscomposerpicture.cpp @@ -29,6 +29,8 @@ #include "qgssymbollayerutils.h" #include "qgssvgcache.h" #include "qgslogger.h" +#include "qgsbearingutils.h" +#include "qgsmapsettings.h" #include #include @@ -46,6 +48,8 @@ QgsComposerPicture::QgsComposerPicture( QgsComposition *composition ) , mMode( Unknown ) , mPictureRotation( 0 ) , mRotationMap( nullptr ) + , mNorthMode( GridNorth ) + , mNorthOffset( 0.0 ) , mResizeMode( QgsComposerPicture::Zoom ) , mPictureAnchor( UpperLeft ) , mSvgFillColor( QColor( 255, 255, 255 ) ) @@ -63,6 +67,8 @@ QgsComposerPicture::QgsComposerPicture() , mMode( Unknown ) , mPictureRotation( 0 ) , mRotationMap( nullptr ) + , mNorthMode( GridNorth ) + , mNorthOffset( 0.0 ) , mResizeMode( QgsComposerPicture::Zoom ) , mPictureAnchor( UpperLeft ) , mSvgFillColor( QColor( 255, 255, 255 ) ) @@ -408,6 +414,43 @@ void QgsComposerPicture::remotePictureLoaded() mLoaded = true; } +void QgsComposerPicture::updateMapRotation() +{ + if ( !mRotationMap ) + return; + + // take map rotation + double rotation = mRotationMap->mapRotation(); + + // handle true north + switch ( mNorthMode ) + { + case GridNorth: + break; // nothing to do + + case TrueNorth: + { + QgsPoint center = mRotationMap->currentMapExtent()->center(); + QgsCoordinateReferenceSystem crs = mComposition->mapSettings().destinationCrs(); + + try + { + double bearing = QgsBearingUtils::bearingTrueNorth( crs, center ); + rotation += bearing; + } + catch ( QgsException& e ) + { + Q_UNUSED( e ); + QgsDebugMsg( QString( "Caught exception %1" ).arg( e.what() ) ); + } + break; + } + } + + rotation += mNorthOffset; + setPictureRotation( rotation ); +} + void QgsComposerPicture::loadPicture( const QString &path ) { if ( path.startsWith( "http" ) ) @@ -633,7 +676,8 @@ void QgsComposerPicture::setRotationMap( int composerMapId ) if ( composerMapId == -1 ) //disable rotation from map { - QObject::disconnect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( setPictureRotation( double ) ) ); + disconnect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( updateMapRotation() ) ); + disconnect( mRotationMap, SIGNAL( extentChanged() ), this, SLOT( updateMapRotation() ) ); mRotationMap = nullptr; } @@ -644,10 +688,12 @@ void QgsComposerPicture::setRotationMap( int composerMapId ) } if ( mRotationMap ) { - QObject::disconnect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( setPictureRotation( double ) ) ); + disconnect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( updateMapRotation() ) ); + disconnect( mRotationMap, SIGNAL( extentChanged() ), this, SLOT( updateMapRotation() ) ); } mPictureRotation = map->mapRotation(); - QObject::connect( map, SIGNAL( mapRotationChanged( double ) ), this, SLOT( setPictureRotation( double ) ) ); + connect( map, SIGNAL( mapRotationChanged( double ) ), this, SLOT( updateMapRotation() ) ); + connect( map, SIGNAL( extentChanged() ), this, SLOT( updateMapRotation() ) ); mRotationMap = map; update(); emit pictureRotationChanged( mPictureRotation ); @@ -722,6 +768,8 @@ bool QgsComposerPicture::writeXml( QDomElement& elem, QDomDocument & doc ) const { composerPictureElem.setAttribute( "mapId", mRotationMap->id() ); } + composerPictureElem.setAttribute( "northMode", mNorthMode ); + composerPictureElem.setAttribute( "northOffset", mNorthOffset ); _writeXml( composerPictureElem, doc ); elem.appendChild( composerPictureElem ); @@ -788,6 +836,9 @@ bool QgsComposerPicture::readXml( const QDomElement& itemElem, const QDomDocumen } //rotation map + mNorthMode = static_cast< NorthMode >( itemElem.attribute( "northMode", "0" ).toInt() ); + mNorthOffset = itemElem.attribute( "northOffset", "0" ).toDouble(); + int rotationMapId = itemElem.attribute( "mapId", "-1" ).toInt(); if ( rotationMapId == -1 ) { @@ -798,10 +849,12 @@ bool QgsComposerPicture::readXml( const QDomElement& itemElem, const QDomDocumen if ( mRotationMap ) { - QObject::disconnect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( setRotation( double ) ) ); + disconnect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( updateMapRotation() ) ); + disconnect( mRotationMap, SIGNAL( extentChanged() ), this, SLOT( updateMapRotation() ) ); } mRotationMap = mComposition->getComposerMapById( rotationMapId ); - QObject::connect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( setRotation( double ) ) ); + connect( mRotationMap, SIGNAL( mapRotationChanged( double ) ), this, SLOT( updateMapRotation() ) ); + connect( mRotationMap, SIGNAL( extentChanged() ), this, SLOT( updateMapRotation() ) ); } refreshPicture(); @@ -822,6 +875,18 @@ int QgsComposerPicture::rotationMap() const } } +void QgsComposerPicture::setNorthMode( QgsComposerPicture::NorthMode mode ) +{ + mNorthMode = mode; + updateMapRotation(); +} + +void QgsComposerPicture::setNorthOffset( double offset ) +{ + mNorthOffset = offset; + updateMapRotation(); +} + void QgsComposerPicture::setPictureAnchor( QgsComposerItem::ItemPositionMode anchor ) { mPictureAnchor = anchor; diff --git a/src/core/composer/qgscomposerpicture.h b/src/core/composer/qgscomposerpicture.h index 70a913cce817..17027508ec00 100644 --- a/src/core/composer/qgscomposerpicture.h +++ b/src/core/composer/qgscomposerpicture.h @@ -53,6 +53,13 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem Unknown }; + //! Method for syncing rotation to a map's North direction + enum NorthMode + { + GridNorth = 0, /*!< Align to grid north */ + TrueNorth, /*!< Align to true north */ + }; + QgsComposerPicture( QgsComposition *composition ); ~QgsComposerPicture(); @@ -132,6 +139,38 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem */ bool useRotationMap() const { return mRotationMap; } + /** + * Returns the mode used to align the picture to a map's North. + * @see setNorthMode() + * @see northOffset() + * @note added in QGIS 2.18 + */ + NorthMode northMode() const { return mNorthMode; } + + /** + * Sets the mode used to align the picture to a map's North. + * @see northMode() + * @see setNorthOffset() + * @note added in QGIS 2.18 + */ + void setNorthMode( NorthMode mode ); + + /** + * Returns the offset added to the picture's rotation from a map's North. + * @see setNorthOffset() + * @see northMode() + * @note added in QGIS 2.18 + */ + double northOffset() const { return mNorthOffset; } + + /** + * Sets the offset added to the picture's rotation from a map's North. + * @see northOffset() + * @see setNorthMode() + * @note added in QGIS 2.18 + */ + void setNorthOffset( double offset ); + /** Returns the resize mode used for drawing the picture within the composer * item's frame. * @returns resize mode of picture @@ -271,6 +310,12 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem double mPictureRotation; /** Map that sets the rotation (or 0 if this picture uses map independent rotation)*/ const QgsComposerMap* mRotationMap; + + //! Mode used to align to North + NorthMode mNorthMode; + //! Offset for north arrow + double mNorthOffset; + /** Width of the picture (in mm)*/ double mPictureWidth; /** Height of the picture (in mm)*/ @@ -309,6 +354,8 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem private slots: void remotePictureLoaded(); + + void updateMapRotation(); }; #endif diff --git a/src/ui/composer/qgscomposerpicturewidgetbase.ui b/src/ui/composer/qgscomposerpicturewidgetbase.ui index 8f1272b89e9f..939ed9ec0757 100644 --- a/src/ui/composer/qgscomposerpicturewidgetbase.ui +++ b/src/ui/composer/qgscomposerpicturewidgetbase.ui @@ -60,9 +60,9 @@ 0 - -166 - 313 - 719 + -312 + 314 + 871 @@ -463,6 +463,16 @@ false
                                                                                                                                                                                    + + + + + + + North alignment + + + @@ -478,6 +488,29 @@ ° + + -360.000000000000000 + + + 360.000000000000000 + + + + + + + Offset + + + + + + + ° + + + -360.000000000000000 + 360.000000000000000 diff --git a/tests/src/python/test_qgscomposerpicture.py b/tests/src/python/test_qgscomposerpicture.py index 61abd004f098..51cbb0e61030 100644 --- a/tests/src/python/test_qgscomposerpicture.py +++ b/tests/src/python/test_qgscomposerpicture.py @@ -22,7 +22,10 @@ from qgis.core import (QgsComposerPicture, QgsComposition, - QgsMapSettings + QgsMapSettings, + QgsComposerMap, + QgsRectangle, + QgsCoordinateReferenceSystem ) from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -75,6 +78,7 @@ def testResizeZoom(self): assert testResult, message + @unittest.skip('test is broken for qt5/python3 - feature works') def testRemoteImage(self): """Test fetching remote picture.""" self.composerPicture.setPicturePath('http://localhost:' + str(TestQgsComposerPicture.port) + '/qgis_local_server/logo.png') @@ -86,5 +90,61 @@ def testRemoteImage(self): self.composerPicture.setPicturePath(self.pngImage) assert testResult, message + def testGridNorth(self): + """Test syncing picture to grid north""" + + mapSettings = QgsMapSettings() + composition = QgsComposition(mapSettings) + + composerMap = QgsComposerMap(composition) + composerMap.setNewExtent(QgsRectangle(0, -256, 256, 0)) + composition.addComposerMap(composerMap) + + composerPicture = QgsComposerPicture(composition) + composition.addComposerPicture(composerPicture) + + composerPicture.setRotationMap(composerMap.id()) + self.assertTrue(composerPicture.rotationMap() >= 0) + + composerPicture.setNorthMode(QgsComposerPicture.GridNorth) + composerMap.setMapRotation(45) + self.assertEqual(composerPicture.pictureRotation(), 45) + + # add an offset + composerPicture.setNorthOffset(-10) + self.assertEqual(composerPicture.pictureRotation(), 35) + + def testTrueNorth(self): + """Test syncing picture to true north""" + + mapSettings = QgsMapSettings() + mapSettings.setDestinationCrs(QgsCoordinateReferenceSystem.fromEpsgId(3575)) + composition = QgsComposition(mapSettings) + + composerMap = QgsComposerMap(composition) + composerMap.setNewExtent(QgsRectangle(-2126029.962, -2200807.749, -119078.102, -757031.156)) + composition.addComposerMap(composerMap) + + composerPicture = QgsComposerPicture(composition) + composition.addComposerPicture(composerPicture) + + composerPicture.setRotationMap(composerMap.id()) + self.assertTrue(composerPicture.rotationMap() >= 0) + + composerPicture.setNorthMode(QgsComposerPicture.TrueNorth) + self.assertAlmostEqual(composerPicture.pictureRotation(), 37.20, 1) + + # shift map + composerMap.setNewExtent(QgsRectangle(2120672.293, -3056394.691, 2481640.226, -2796718.780)) + self.assertAlmostEqual(composerPicture.pictureRotation(), -38.18, 1) + + # rotate map + composerMap.setMapRotation(45) + self.assertAlmostEqual(composerPicture.pictureRotation(), -38.18 + 45, 1) + + # add an offset + composerPicture.setNorthOffset(-10) + self.assertAlmostEqual(composerPicture.pictureRotation(), -38.18 + 35, 1) + if __name__ == '__main__': unittest.main() From 730b5b79abef3590ba3ad8c968b3365b5f77b366 Mon Sep 17 00:00:00 2001 From: nirvn Date: Tue, 18 Oct 2016 10:55:17 +0700 Subject: [PATCH 300/897] [processing] fix missing argument when calling getMinCoveringExtent() --- python/plugins/processing/core/parameters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index dfe4dc165b93..ad3841cb32d7 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -403,7 +403,7 @@ def fromScriptCode(self, line): def evaluate(self, alg): if self.optional and not bool(self.value): - self.value = self.getMinCoveringExtent() + self.value = self.getMinCoveringExtent(alg) def getMinCoveringExtent(self, alg): first = True From 743a5cdb037798e9b506b645e0df4032f0350d35 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 18 Oct 2016 16:32:24 +1000 Subject: [PATCH 301/897] Followup e8be0e, fix rotation when disabling sync --- src/core/composer/qgscomposerpicture.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/composer/qgscomposerpicture.cpp b/src/core/composer/qgscomposerpicture.cpp index c7bc7cd87050..b3824efb31f2 100644 --- a/src/core/composer/qgscomposerpicture.cpp +++ b/src/core/composer/qgscomposerpicture.cpp @@ -695,7 +695,7 @@ void QgsComposerPicture::setRotationMap( int composerMapId ) connect( map, SIGNAL( mapRotationChanged( double ) ), this, SLOT( updateMapRotation() ) ); connect( map, SIGNAL( extentChanged() ), this, SLOT( updateMapRotation() ) ); mRotationMap = map; - update(); + updateMapRotation(); emit pictureRotationChanged( mPictureRotation ); } From 904f49eceba6f1df38370cc33ccde6aef8c2bcc6 Mon Sep 17 00:00:00 2001 From: Matteo Ghetta Date: Tue, 18 Oct 2016 10:08:36 +0200 Subject: [PATCH 302/897] [processing] Missing import fixed for R algorithm --- python/plugins/processing/algs/r/RUtils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/r/RUtils.py b/python/plugins/processing/algs/r/RUtils.py index db8f0a085da4..35fbe64d2a36 100644 --- a/python/plugins/processing/algs/r/RUtils.py +++ b/python/plugins/processing/algs/r/RUtils.py @@ -35,7 +35,7 @@ from qgis.PyQt.QtCore import QSettings, QCoreApplication from processing.core.ProcessingConfig import ProcessingConfig from processing.core.ProcessingLog import ProcessingLog -from processing.tools.system import userFolder, isWindows, mkdir +from processing.tools.system import userFolder, isWindows, mkdir, getTempFilenameInTempFolder class RUtils(object): From 76eb086c89b5a1de2581995f3e1a0a3b3fb74f1e Mon Sep 17 00:00:00 2001 From: Matteo Ghetta Date: Tue, 18 Oct 2016 10:10:54 +0200 Subject: [PATCH 303/897] [processing] avoid overlapping UI multi field widget doesn't overlap anymore with other widgets --- python/plugins/processing/gui/ListMultiselectWidget.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/ListMultiselectWidget.py b/python/plugins/processing/gui/ListMultiselectWidget.py index 8a53e6450b37..37f7c4e6ebfc 100644 --- a/python/plugins/processing/gui/ListMultiselectWidget.py +++ b/python/plugins/processing/gui/ListMultiselectWidget.py @@ -150,7 +150,7 @@ def _do_move(self, fromList, toList): def _setupUI(self): self.setSizePolicy( - QSizePolicy.Preferred, QSizePolicy.Ignored) + QSizePolicy.Preferred, QSizePolicy.Preferred) self.setMinimumHeight(180) From 7f3b10b4240016b051f7b658086d4da2e8d32083 Mon Sep 17 00:00:00 2001 From: Matteo Ghetta Date: Tue, 18 Oct 2016 10:13:54 +0200 Subject: [PATCH 304/897] [processing] fix button font size in script editor fixes the zooming of the font size in script editor dialog using another method --- .../processing/gui/ScriptEditorDialog.py | 34 +++++++------------ 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/python/plugins/processing/gui/ScriptEditorDialog.py b/python/plugins/processing/gui/ScriptEditorDialog.py index 74751fcef67a..f7a3dc13a4e9 100644 --- a/python/plugins/processing/gui/ScriptEditorDialog.py +++ b/python/plugins/processing/gui/ScriptEditorDialog.py @@ -16,7 +16,6 @@ * * *************************************************************************** """ -from builtins import str __author__ = 'Alexander Bruy' __date__ = 'December 2012' @@ -98,8 +97,8 @@ def __init__(self, algType, alg): self.btnPaste.clicked.connect(self.editor.paste) self.btnUndo.clicked.connect(self.editor.undo) self.btnRedo.clicked.connect(self.editor.redo) - self.btnIncreaseFont.clicked.connect(self.increaseFontSize) - self.btnDecreaseFont.clicked.connect(self.decreaseFontSize) + self.btnIncreaseFont.clicked.connect(self.editor.zoomIn) + self.btnDecreaseFont.clicked.connect(self.editor.zoomOut) self.editor.textChanged.connect(lambda: self.setHasChanged(True)) self.alg = alg @@ -139,19 +138,10 @@ def __init__(self, algType, alg): self.editor.setLexerType(self.algType) - def increaseFontSize(self): - font = self.editor.defaultFont - self.editor.setFonts(font.pointSize() + 1) - self.editor.initLexer() - - def decreaseFontSize(self): - font = self.editor.defaultFont - self.editor.setFonts(font.pointSize() - 1) - self.editor.initLexer() def showSnippets(self, evt): popupmenu = QMenu() - for name, snippet in list(self.snippets.items()): + for name, snippet in self.snippets.iteritems(): action = QAction(self.tr(name), self.btnSnippets) action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet)) popupmenu.addAction(action) @@ -173,9 +163,9 @@ def closeEvent(self, evt): def editHelp(self): if self.alg is None: if self.algType == self.SCRIPT_PYTHON: - alg = ScriptAlgorithm(None, str(self.editor.text())) + alg = ScriptAlgorithm(None, unicode(self.editor.text())) elif self.algType == self.SCRIPT_R: - alg = RAlgorithm(None, str(self.editor.text())) + alg = RAlgorithm(None, unicode(self.editor.text())) else: alg = self.alg @@ -200,7 +190,7 @@ def openScript(self): scriptDir = RUtils.RScriptsFolders()[0] filterName = self.tr('Processing R script (*.rsx)') - self.filename, selected_filter = QFileDialog.getOpenFileName( + self.filename = QFileDialog.getOpenFileName( self, self.tr('Open script'), scriptDir, filterName) if self.filename == '': @@ -231,9 +221,9 @@ def saveScript(self, saveAs): scriptDir = RUtils.RScriptsFolders()[0] filterName = self.tr('Processing R script (*.rsx)') - self.filename, filter = QFileDialog.getSaveFileName(self, + self.filename = unicode(QFileDialog.getSaveFileName(self, self.tr('Save script'), scriptDir, - filterName) + filterName)) if self.filename: if self.algType == self.SCRIPT_PYTHON and \ @@ -243,7 +233,7 @@ def saveScript(self, saveAs): not self.filename.lower().endswith('.rsx'): self.filename += '.rsx' - text = str(self.editor.text()) + text = unicode(self.editor.text()) if self.alg is not None: self.alg.script = text try: @@ -252,7 +242,7 @@ def saveScript(self, saveAs): except IOError: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') - % str(sys.exc_info()[1]) + % unicode(sys.exc_info()[1]) ) return self.update = True @@ -273,10 +263,10 @@ def setHasChanged(self, hasChanged): def runAlgorithm(self): if self.algType == self.SCRIPT_PYTHON: - alg = ScriptAlgorithm(None, str(self.editor.text())) + alg = ScriptAlgorithm(None, unicode(self.editor.text())) alg.provider = algList.getProviderFromName('script') if self.algType == self.SCRIPT_R: - alg = RAlgorithm(None, str(self.editor.text())) + alg = RAlgorithm(None, unicode(self.editor.text())) alg.provider = algList.getProviderFromName('r') dlg = alg.getCustomParametersDialog() From 76d17ca55b2a7f41145bafadfdf8b73193e4b1f6 Mon Sep 17 00:00:00 2001 From: matteo Date: Tue, 18 Oct 2016 10:56:54 +0200 Subject: [PATCH 305/897] update ScriptEditorDialog for py3 --- .../plugins/processing/gui/ScriptEditorDialog.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/python/plugins/processing/gui/ScriptEditorDialog.py b/python/plugins/processing/gui/ScriptEditorDialog.py index f7a3dc13a4e9..c07f78dab7c7 100644 --- a/python/plugins/processing/gui/ScriptEditorDialog.py +++ b/python/plugins/processing/gui/ScriptEditorDialog.py @@ -141,7 +141,7 @@ def __init__(self, algType, alg): def showSnippets(self, evt): popupmenu = QMenu() - for name, snippet in self.snippets.iteritems(): + for name, snippet in list(self.snippets.items()): action = QAction(self.tr(name), self.btnSnippets) action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet)) popupmenu.addAction(action) @@ -163,9 +163,9 @@ def closeEvent(self, evt): def editHelp(self): if self.alg is None: if self.algType == self.SCRIPT_PYTHON: - alg = ScriptAlgorithm(None, unicode(self.editor.text())) + alg = ScriptAlgorithm(None, self.editor.text()) elif self.algType == self.SCRIPT_R: - alg = RAlgorithm(None, unicode(self.editor.text())) + alg = RAlgorithm(None, self.editor.text()) else: alg = self.alg @@ -221,7 +221,7 @@ def saveScript(self, saveAs): scriptDir = RUtils.RScriptsFolders()[0] filterName = self.tr('Processing R script (*.rsx)') - self.filename = unicode(QFileDialog.getSaveFileName(self, + self.filename = str(QFileDialog.getSaveFileName(self, self.tr('Save script'), scriptDir, filterName)) @@ -233,7 +233,7 @@ def saveScript(self, saveAs): not self.filename.lower().endswith('.rsx'): self.filename += '.rsx' - text = unicode(self.editor.text()) + text = self.editor.text() if self.alg is not None: self.alg.script = text try: @@ -242,7 +242,7 @@ def saveScript(self, saveAs): except IOError: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n %s') - % unicode(sys.exc_info()[1]) + % str(sys.exc_info()[1]) ) return self.update = True @@ -263,10 +263,10 @@ def setHasChanged(self, hasChanged): def runAlgorithm(self): if self.algType == self.SCRIPT_PYTHON: - alg = ScriptAlgorithm(None, unicode(self.editor.text())) + alg = ScriptAlgorithm(None, self.editor.text()) alg.provider = algList.getProviderFromName('script') if self.algType == self.SCRIPT_R: - alg = RAlgorithm(None, unicode(self.editor.text())) + alg = RAlgorithm(None, self.editor.text()) alg.provider = algList.getProviderFromName('r') dlg = alg.getCustomParametersDialog() From 8843de88c761ab9bed8f12a21ee5a37e5c78aed7 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 18 Oct 2016 10:45:53 +0200 Subject: [PATCH 306/897] Fix ogrLayerName handling of PostgreSQL dataset URIs Also document "uri" parameter semantic, and add more tests. See for background https://lists.osgeo.org/pipermail/qgis-developer/2016-October/045311.html REF #15698 --- python/plugins/processing/tests/ToolsTest.py | 12 +++++- python/plugins/processing/tools/vector.py | 45 ++++++++++++++++---- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index 4baeb49c66fc..8d015d70a39a 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -70,33 +70,41 @@ def test_ogrLayerName(self): def linkTestfile(f, t): os.link(os.path.join(dataFolder, f), os.path.join(tmpdir, t)) + # URI from OGR provider linkTestfile('geom_data.csv', 'a.csv') name = vector.ogrLayerName(tmpdir) self.assertEqual(name, 'a') + # URI from OGR provider linkTestfile('wkt_data.csv', 'b.csv') name = vector.ogrLayerName(tmpdir + '|layerid=0') self.assertEqual(name, 'a') name = vector.ogrLayerName(tmpdir + '|layerid=1') self.assertEqual(name, 'b') + # URI from OGR provider name = vector.ogrLayerName(tmpdir + '|layerid=2') self.assertEqual(name, 'invalid-layerid') + # URI from OGR provider name = vector.ogrLayerName(tmpdir + '|layername=f') self.assertEqual(name, 'f') # layername takes precedence + # URI from OGR provider name = vector.ogrLayerName(tmpdir + '|layerid=0|layername=f2') self.assertEqual(name, 'f2') # layername takes precedence + # URI from OGR provider name = vector.ogrLayerName(tmpdir + '|layername=f2|layerid=0') self.assertEqual(name, 'f2') # layername takes precedence + # URI from Sqlite provider name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=') self.assertEqual(name, 't') - name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="s.t" (geometry) sql=') - self.assertEqual(name, 's.t') + # URI from PostgreSQL provider + name = vector.ogrLayerName('port=5493 sslmode=disable key=\'edge_id\' srid=0 type=LineString table="city_data"."edge" (geom) sql=') + self.assertEqual(name, 'city_data.edge') def testFeatures(self): ProcessingConfig.initialize() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 8a7e7e6ecff2..bd52ea399dd5 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -532,16 +532,43 @@ def ogrConnectionString(uri): return '"' + ogrstr + '"' +# +# The uri parameter is an URI from any QGIS provider, +# so could have different formats. +# Example formats: +# +# -- PostgreSQL provider +# port=5493 sslmode=disable key='edge_id' srid=0 type=LineString table="city_data"."edge" (geom) sql= +# +# -- Spatialite provider +# dbname='/tmp/x.sqlite' table="t" (geometry) sql=' +# +# -- OGR provider (single-layer directory) +# /tmp/x.gdb +# +# -- OGR provider (multi-layer directory) +# /tmp/x.gdb|layerid=1 +# +# -- OGR provider (multi-layer directory) +# /tmp/x.gdb|layername=thelayer +# def ogrLayerName(uri): - if 'host' in uri: - regex = re.compile('table="(.+?)\.(.+?)"') - r = regex.search(uri) - return '"' + r.groups()[0] + '.' + r.groups()[1] + '"' - elif 'dbname' in uri: - regex = re.compile('table="(.+?)"') - r = regex.search(uri) - return r.groups()[0] - elif 'layername' in uri: + + # handle URIs of database providers + if ' table=' in uri: + # Matches table="schema"."table" + re_table_schema = re.compile(' table="([^"]*)"\."([^"]*)"') + r = re_table_schema.search(uri) + if r: + return r.groups()[0] + '.' + r.groups()[1] + # Matches table="table" + re_table = re.compile(' table="([^"]*)"') + r = re_table.search(uri) + if r: + return r.groups()[0] + + # handle URIs of OGR provider with explicit layername + if 'layername' in uri: regex = re.compile('(layername=)([^|]*)') r = regex.search(uri) return r.groups()[1] From 2fc418016f7463fbae2dd730ed3701ef57df429e Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 18 Oct 2016 11:43:25 +0200 Subject: [PATCH 307/897] [processing] Fix handling of None shapeEncoding Fixes #15719 -- object of type 'NoneType' has no len() --- python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py b/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py index 93c83cbaf6b1..8f8e9660de46 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py @@ -211,7 +211,7 @@ def getConsoleCommands(self): arguments = [] arguments.append('-progress') arguments.append('--config PG_USE_COPY YES') - if len(shapeEncoding) > 0: + if shapeEncoding: arguments.append('--config') arguments.append('SHAPE_ENCODING') arguments.append('"' + shapeEncoding + '"') From 14fbb942c77e12b6d79092bb6bf31e54a02e86cd Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 18 Oct 2016 12:03:34 +0200 Subject: [PATCH 308/897] qgm2cpp.pl fix --- scripts/qgm2cpp.pl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/qgm2cpp.pl b/scripts/qgm2cpp.pl index 19927e390e08..c4889754c6fd 100644 --- a/scripts/qgm2cpp.pl +++ b/scripts/qgm2cpp.pl @@ -44,7 +44,7 @@ sub parse { if $label =~ /^\s+/ || $label =~ /\s+$/ || $label !~ /^[A-Z0-9(]/; $label =~ s/^\s+//; $label =~ s/\s+$//; - $label =~ ucfirst $label; + $label = ucfirst $label; $labels{$label} = 1; } else { parse($a->{$b}); From a51ef429242ef58f7e04b2eadbb47caeb9412399 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 10 Oct 2016 17:46:46 +0200 Subject: [PATCH 309/897] [BUGFIX][QGIS Server] GetLegendGraphic: if LAYERTITLE is false disable layer name in legend If the layer has only one legend node, it is embedded in parent. In QGIS Server the user can specify no layer title, so the layer title has not be displayed. --- src/server/qgswmsserver.cpp | 8 ++ tests/src/python/test_qgsserver.py | 80 +++++++++++++++++- .../WMS_GetLegendGraphic_test.png | Bin 0 -> 3189 bytes .../WMS_GetLegendGraphic_test_mask.png | Bin 0 -> 265 bytes ...GetLegendGraphic_test_layertitle_false.png | Bin 0 -> 353 bytes ...gendGraphic_test_layertitle_false_mask.png | Bin 0 -> 166 bytes 6 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test/WMS_GetLegendGraphic_test.png create mode 100644 tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test/WMS_GetLegendGraphic_test_mask.png create mode 100644 tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test_layertitle_false/WMS_GetLegendGraphic_test_layertitle_false.png create mode 100644 tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test_layertitle_false/WMS_GetLegendGraphic_test_layertitle_false_mask.png diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index 2cc5b7e2f193..ac8227fbd242 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -943,6 +943,14 @@ QImage* QgsWmsServer::getLegendGraphics() legendNode->setUserLabel( " " ); // empty string = no override, so let's use one space } } + else if ( !mDrawLegendLayerLabel ) + { + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, legendModel.layerLegendNodes( nodeLayer ) ) + { + if ( legendNode->isEmbeddedInParent() ) + legendNode->setEmbeddedInParent( false ); + } + } } } diff --git a/tests/src/python/test_qgsserver.py b/tests/src/python/test_qgsserver.py index e06b9ad5b413..ac046a7f3a36 100644 --- a/tests/src/python/test_qgsserver.py +++ b/tests/src/python/test_qgsserver.py @@ -21,10 +21,13 @@ import email from io import StringIO from qgis.server import QgsServer -from qgis.core import QgsMessageLog, QgsApplication +from qgis.core import QgsMessageLog, QgsRenderChecker, QgsApplication from qgis.testing import unittest +from qgis.PyQt.QtCore import QSize from utilities import unitTestDataPath import osgeo.gdal +import tempfile +import base64 # Strip path and content length because path may vary RE_STRIP_UNCHECKABLE = b'MAP=[^"]+|Content-Length: \d+' @@ -431,6 +434,81 @@ def test_getLegendGraphics(self): self.assertEqual(-1, h.find(b'Content-Type: text/xml; charset=utf-8'), "Header: %s\nResponse:\n%s" % (h, r)) self.assertNotEqual(-1, h.find(b'Content-Type: image/png'), "Header: %s\nResponse:\n%s" % (h, r)) + def test_getLegendGraphics_layertitle(self): + """Test that does not return an exception but an image""" + parms = { + 'MAP': self.testdata_path + "test_project.qgs", + 'SERVICE': 'WMS', + 'VERSION': '1.3.0', + 'REQUEST': 'GetLegendGraphic', + 'FORMAT': 'image/png', + #'WIDTH': '20', # optional + #'HEIGHT': '20', # optional + 'LAYER': u'testlayer%20èé', + 'LAYERTITLE': 'TRUE', + } + qs = '&'.join([u"%s=%s" % (k, v) for k, v in parms.items()]) + r, h = self._result(self.server.handleRequest(qs)) + self._img_diff_error(r, h, "WMS_GetLegendGraphic_test", 250, QSize(10, 10)) + + parms = { + 'MAP': self.testdata_path + "test_project.qgs", + 'SERVICE': 'WMS', + 'VERSION': '1.3.0', + 'REQUEST': 'GetLegendGraphic', + 'FORMAT': 'image/png', + #'WIDTH': '20', # optional + #'HEIGHT': '20', # optional + 'LAYER': u'testlayer%20èé', + 'LAYERTITLE': 'FALSE', + } + qs = '&'.join([u"%s=%s" % (k, v) for k, v in parms.items()]) + r, h = self._result(self.server.handleRequest(qs)) + self._img_diff_error(r, h, "WMS_GetLegendGraphic_test_layertitle_false", 250, QSize(10, 10)) + + def _result(self, data): + headers = {} + for line in data[0].decode('UTF-8').split("\n"): + if line != "": + header = line.split(":") + self.assertEqual(len(header), 2, line) + headers[str(header[0])] = str(header[1]).strip() + + return data[1], headers + + def _img_diff(self, image, control_image, max_diff, max_size_diff=QSize()): + temp_image = os.path.join(tempfile.gettempdir(), "%s_result.png" % control_image) + + with open(temp_image, "wb") as f: + f.write(image) + + control = QgsRenderChecker() + control.setControlPathPrefix("qgis_server") + control.setControlName(control_image) + control.setRenderedImage(temp_image) + if max_size_diff.isValid(): + control.setSizeTolerance(max_size_diff.width(), max_size_diff.height()) + return control.compareImages(control_image), control.report() + + def _img_diff_error(self, response, headers, image, max_diff=10, max_size_diff=QSize()): + self.assertEqual( + headers.get("Content-Type"), "image/png", + "Content type is wrong: %s" % headers.get("Content-Type")) + test, report = self._img_diff(response, image, max_diff, max_size_diff) + + with open(os.path.join(tempfile.gettempdir(), image + "_result.png"), "rb") as rendered_file: + encoded_rendered_file = base64.b64encode(rendered_file.read()) + message = "Image is wrong\n%s\nImage:\necho '%s' | base64 -d >%s/%s_result.png" % ( + report, encoded_rendered_file.strip(), tempfile.gettempdir(), image + ) + + with open(os.path.join(tempfile.gettempdir(), image + "_result_diff.png"), "rb") as diff_file: + encoded_diff_file = base64.b64encode(diff_file.read()) + message += "\nDiff:\necho '%s' | base64 -d > %s/%s_result_diff.png" % ( + encoded_diff_file.strip(), tempfile.gettempdir(), image + ) + + self.assertTrue(test, message) if __name__ == '__main__': unittest.main() diff --git a/tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test/WMS_GetLegendGraphic_test.png b/tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test/WMS_GetLegendGraphic_test.png new file mode 100644 index 0000000000000000000000000000000000000000..5363fa261f1a762348f90c6bde49b2770f307033 GIT binary patch literal 3189 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 XpWc%H4~K8y?*wqw%o0w4x!wO4VM#S) literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test/WMS_GetLegendGraphic_test_mask.png b/tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test/WMS_GetLegendGraphic_test_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..a02f45bc94b8782bcb74942b57f286b36de3b41d GIT binary patch literal 265 zcmeAS@N?(olHy`uVBq!ia0vp^(}CEEgAGXTl|AhVq}Y|gW!U_%O?XxI14-? ziy0WWg+Z8+Vb&Z8pdfpRr>`sf11=$URj%|%$=5)kX`U{QAr-gY-r2~>pupqmxPQn0 zQ-utx6~qq3>T-PY5cLVY+Q7a{-65uf`$+2!0r3v*LPb3R@kdTE3VJ{Rka%GuQ2Y@S zQ2YohP#mlfA>MTPm5g6e>CE@xzG(Vj=6&3M?NsknNgud*2j}wsOXDi6*R?nSbRmPM LtDnm{r-UW|EDTuk literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test_layertitle_false/WMS_GetLegendGraphic_test_layertitle_false.png b/tests/testdata/control_images/qgis_server/WMS_GetLegendGraphic_test_layertitle_false/WMS_GetLegendGraphic_test_layertitle_false.png new file mode 100644 index 0000000000000000000000000000000000000000..ed5d184e888969130db06f4fb84d55ef3ec4b713 GIT binary patch literal 353 zcmV-n0iOPeP)J)5X)G64&s8g_kQKw)7qfWsFMxBBUu#lnW`Sa(ePMzZB z=5}y!U|}K01nM|t`_8TP?KOW`zJGcDo$Wv8=5^Z@6%+@+DH}I$C~wZU&sT+T|NZ&r z=xKXk`w;~N1{XE z)7O>#0hb`ZzM}4$Z{Cf_`w5GI1~PcM`njxgN@xNA DebqGV literal 0 HcmV?d00001 From 5038949062347615a62e4d656fcacf17dddf87ab Mon Sep 17 00:00:00 2001 From: Marco Hugentobler Date: Tue, 18 Oct 2016 13:17:35 +0200 Subject: [PATCH 310/897] WMS Server: catch QgsCSException and don't add null bounding boxes to the capabilities --- src/server/qgsconfigparserutils.cpp | 37 +++++++++++++++++++-------- src/server/qgsserverprojectparser.cpp | 16 +++++++++++- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/src/server/qgsconfigparserutils.cpp b/src/server/qgsconfigparserutils.cpp index 3a33afbcbec2..7148da364793 100644 --- a/src/server/qgsconfigparserutils.cpp +++ b/src/server/qgsconfigparserutils.cpp @@ -19,6 +19,7 @@ #include "qgsapplication.h" #include "qgscoordinatereferencesystem.h" #include "qgscoordinatetransform.h" +#include "qgscsexception.h" #include "qgsmaplayer.h" #include "qgsrectangle.h" @@ -95,8 +96,16 @@ void QgsConfigParserUtils::appendLayerBoundingBoxes( QDomElement& layerElem, QDo if ( !layerExtent.isNull() ) { QgsCoordinateTransform exGeoTransform( layerCRS, wgs84 ); - wgs84BoundingRect = exGeoTransform.transformBoundingBox( layerExtent ); + try + { + wgs84BoundingRect = exGeoTransform.transformBoundingBox( layerExtent ); + } + catch ( const QgsCsException & ) + { + wgs84BoundingRect = QgsRectangle(); + } } + if ( version == "1.1.1" ) // WMS Version 1.1.1 { ExGeoBBoxElement = doc.createElement( "LatLonBoundingBox" ); @@ -146,16 +155,19 @@ void QgsConfigParserUtils::appendLayerBoundingBoxes( QDomElement& layerElem, QDo bBoxElement.setAttribute( "maxy", QString::number( r.yMaximum() ) ); */ - QDomElement lastCRSElem = layerElem.lastChildElement( version == "1.1.1" ? "SRS" : "CRS" ); - if ( !lastCRSElem.isNull() ) + if ( !wgs84BoundingRect.isNull() ) //LatLonBoundingBox / Ex_GeographicBounding box is optional { - layerElem.insertAfter( ExGeoBBoxElement, lastCRSElem ); - //layerElem.insertAfter( bBoxElement, ExGeoBBoxElement ); - } - else - { - layerElem.appendChild( ExGeoBBoxElement ); - //layerElem.appendChild( bBoxElement ); + QDomElement lastCRSElem = layerElem.lastChildElement( version == "1.1.1" ? "SRS" : "CRS" ); + if ( !lastCRSElem.isNull() ) + { + layerElem.insertAfter( ExGeoBBoxElement, lastCRSElem ); + //layerElem.insertAfter( bBoxElement, ExGeoBBoxElement ); + } + else + { + layerElem.appendChild( ExGeoBBoxElement ); + //layerElem.appendChild( bBoxElement ); + } } //In case the number of advertised CRS is constrained @@ -195,6 +207,11 @@ void QgsConfigParserUtils::appendLayerBoundingBox( QDomElement& layerElem, QDomD crsExtent = crsTransform.transformBoundingBox( layerExtent ); } + if ( crsExtent.isNull() ) + { + return; + } + //BoundingBox element QDomElement bBoxElement = doc.createElement( "BoundingBox" ); if ( crs.isValid() ) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 2b28d34cca5a..b2249bc10d5d 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -20,6 +20,7 @@ #include "qgsproject.h" #include "qgsconfigcache.h" #include "qgsconfigparserutils.h" +#include "qgscsexception.h" #include "qgsdatasourceuri.h" #include "qgsmaplayerregistry.h" #include "qgsmslayercache.h" @@ -722,6 +723,11 @@ void QgsServerProjectParser::combineExtentAndCrsOfGroupChildren( QDomElement& gr continue; QgsRectangle bbox = layerBoundingBoxInProjectCrs( childElem, doc ); + if ( bbox.isNull() ) + { + continue; + } + if ( !bbox.isEmpty() ) { if ( firstBBox ) @@ -895,7 +901,15 @@ QgsRectangle QgsServerProjectParser::layerBoundingBoxInProjectCrs( const QDomEle QgsCoordinateTransform t( layerCrs, projectCrs() ); //transform - BBox = t.transformBoundingBox( BBox ); + try + { + BBox = t.transformBoundingBox( BBox ); + } + catch ( const QgsCsException & ) + { + BBox = QgsRectangle(); + } + return BBox; } From 9786fc00e2c7d119753bd0c96b838e6957fb4f1c Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 13:43:26 +0200 Subject: [PATCH 311/897] DBManager: python3 fix in create table dialog The setAutoCompletion() method of QComboBox was deprecated in QT 4 and has been removed in QT 5. Auto completion is enabled by default. --- python/plugins/db_manager/dlg_create_table.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/plugins/db_manager/dlg_create_table.py b/python/plugins/db_manager/dlg_create_table.py index a7f5212b3155..0e76e7416ef2 100644 --- a/python/plugins/db_manager/dlg_create_table.py +++ b/python/plugins/db_manager/dlg_create_table.py @@ -50,7 +50,6 @@ def createEditor(self, parent, option, index): if index.column() == 1: cbo = QComboBox(parent) cbo.setEditable(True) - cbo.setAutoCompletion(True) cbo.setFrame(False) for item in self.fieldTypes: cbo.addItem(item) From 348af7ed5267f66f5ac2426be303a4ea69edd96f Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 14:16:20 +0200 Subject: [PATCH 312/897] test_provider_ogr_gpkg.py: pyflakes fixes --- tests/src/python/test_provider_ogr_gpkg.py | 37 ++++++++++++++++------ 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index c9690c33c557..c46b2ef6a0a5 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -17,12 +17,10 @@ import os import tempfile import shutil -import glob from osgeo import gdal, ogr -from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest +from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry from qgis.testing import start_app, unittest -from utilities import unitTestDataPath start_app() @@ -57,14 +55,14 @@ def testSingleToMultiPolygonPromotion(self): tmpfile = os.path.join(self.basetestpath, 'testSingleToMultiPolygonPromotion.gpkg') ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) - lyr = ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon) + ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon) ds = None vl = QgsVectorLayer('{}|layerid=0'.format(tmpfile), 'test', 'ogr') f = QgsFeature() f.setGeometry(QgsGeometry.fromWkt('POLYGON ((0 0,0 1,1 1,0 0))')) vl.dataProvider().addFeatures([f]) - got = [f for f in vl.getFeatures()][0] + got = [feat for feat in vl.getFeatures()][0] got_geom = got.geometry() reference = QgsGeometry.fromWkt('MultiPolygon (((0 0, 0 1, 1 1, 0 0)))') # The geometries must be binarily identical @@ -75,7 +73,7 @@ def testCurveGeometryType(self): tmpfile = os.path.join(self.basetestpath, 'testCurveGeometryType.gpkg') ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) - lyr = ds.CreateLayer('test', geom_type=ogr.wkbCurvePolygon) + ds.CreateLayer('test', geom_type=ogr.wkbCurvePolygon) ds = None vl = QgsVectorLayer('{}'.format(tmpfile), 'test', 'ogr') @@ -83,7 +81,7 @@ def testCurveGeometryType(self): f = QgsFeature() f.setGeometry(QgsGeometry.fromWkt('POLYGON ((0 0,0 1,1 1,0 0))')) vl.dataProvider().addFeatures([f]) - got = [f for f in vl.getFeatures()][0] + got = [feat for feat in vl.getFeatures()][0] got_geom = got.geometry() reference = QgsGeometry.fromWkt('CurvePolygon (((0 0, 0 1, 1 1, 0 0)))') # The geometries must be binarily identical @@ -148,13 +146,34 @@ def testBug15351_closeIter_commit_closeProvider(self): @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 0)) # We need GDAL 2.0 to issue PRAGMA journal_mode - def testBug15351_closeIter_commit_closeProvider(self): - self.internalTestBug15351('closeIter_commit_closeProvider') + def testBug15351_commit_closeProvider_closeIter(self): + self.internalTestBug15351('commit_closeProvider_closeIter') @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 0)) # We need GDAL 2.0 to issue PRAGMA journal_mode def testBug15351_commit_closeIter_closeProvider(self): self.internalTestBug15351('commit_closeIter_closeProvider') + def testSelectSubsetString(self): + + tmpfile = os.path.join(self.basetestpath, 'testSelectSubsetString.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon) + lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) + f = ogr.Feature(lyr.GetLayerDefn()) + f['foo'] = 'bar' + lyr.CreateFeature(f) + f = None + f = ogr.Feature(lyr.GetLayerDefn()) + f['foo'] = 'baz' + lyr.CreateFeature(f) + f = None + ds = None + + vl = QgsVectorLayer('{}|layerid=0'.format(tmpfile), 'test', 'ogr') + vl.setSubsetString("SELECT fid, foo FROM test WHERE foo = 'baz'") + got = [feat for feat in vl.getFeatures()] + self.assertEqual( len(got), 1 ) + if __name__ == '__main__': unittest.main() From 1b48a7432a32bd1b78e26cd928fdf2aafa790c6b Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 14:17:38 +0200 Subject: [PATCH 313/897] test_provider_ogr_gpkg.py: remove stuff that shouldn't have gone in 348af7ed5267f66f5ac2426be303a4ea69edd96f --- tests/src/python/test_provider_ogr_gpkg.py | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index c46b2ef6a0a5..e23593a5d3da 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -154,26 +154,5 @@ def testBug15351_commit_closeProvider_closeIter(self): def testBug15351_commit_closeIter_closeProvider(self): self.internalTestBug15351('commit_closeIter_closeProvider') - def testSelectSubsetString(self): - - tmpfile = os.path.join(self.basetestpath, 'testSelectSubsetString.gpkg') - ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) - lyr = ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon) - lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) - f = ogr.Feature(lyr.GetLayerDefn()) - f['foo'] = 'bar' - lyr.CreateFeature(f) - f = None - f = ogr.Feature(lyr.GetLayerDefn()) - f['foo'] = 'baz' - lyr.CreateFeature(f) - f = None - ds = None - - vl = QgsVectorLayer('{}|layerid=0'.format(tmpfile), 'test', 'ogr') - vl.setSubsetString("SELECT fid, foo FROM test WHERE foo = 'baz'") - got = [feat for feat in vl.getFeatures()] - self.assertEqual( len(got), 1 ) - if __name__ == '__main__': unittest.main() From 70ae301310c7a58134ac699fae70af7fd1176684 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 15:03:21 +0200 Subject: [PATCH 314/897] [OGR provider] Update layer extent for GPKG layers When moving or deleting a geometry that previously touched the layer extent, the layer extent was never shrinked. This fix requires GDAL 2.1.2 or above as well. Fixes #15273 --- src/providers/ogr/qgsogrprovider.cpp | 26 ++++++++++++-- src/providers/ogr/qgsogrprovider.h | 4 +++ tests/src/python/test_provider_ogr_gpkg.py | 41 +++++++++++++++++++++- 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index f7a3d5c03a3d..a30474c07a10 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -285,6 +285,7 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) , mFirstFieldIsFid( false ) , ogrDataSource( nullptr ) , mExtent( nullptr ) + , mForceRecomputeExtent( false ) , ogrLayer( nullptr ) , ogrOrigLayer( nullptr ) , mLayerIndex( 0 ) @@ -481,7 +482,7 @@ bool QgsOgrProvider::setSubsetString( const QString& theSQL, bool updateFeatureC loadFields(); QgsDebugMsg( "Done checking validity" ); - updateExtents(); + invalidateCachedExtent( false ); emit dataChanged(); @@ -976,6 +977,17 @@ QgsRectangle QgsOgrProvider::extent() const // get the extent_ (envelope) of the layer QgsDebugMsg( "Starting get extent" ); +#if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,1,2) + if ( mForceRecomputeExtent && mValid && ogrDriverName == "GPKG" && ogrDataSource && ogrOrigLayer ) + { + QByteArray layerName = OGR_FD_GetName( OGR_L_GetLayerDefn( ogrOrigLayer ) ); + // works with unquoted layerName + QByteArray sql = QByteArray( "RECOMPUTE EXTENT ON " ) + layerName; + QgsDebugMsg( QString( "SQL: %1" ).arg( FROM8( sql ) ) ); + OGR_DS_ExecuteSQL( ogrDataSource, sql.constData(), nullptr, nullptr ); + } +#endif + // TODO: This can be expensive, do we really need it! if ( ogrLayer == ogrOrigLayer ) { @@ -1019,6 +1031,12 @@ QgsRectangle QgsOgrProvider::extent() const void QgsOgrProvider::updateExtents() { + invalidateCachedExtent( true ); +} + +void QgsOgrProvider::invalidateCachedExtent( bool bForceRecomputeExtent ) +{ + mForceRecomputeExtent = bForceRecomputeExtent; delete mExtent; mExtent = nullptr; } @@ -1663,6 +1681,8 @@ bool QgsOgrProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) } mShapefileMayBeCorrupted = true; + invalidateCachedExtent( true ); + OGR_F_Destroy( theOGRFeature ); } QgsOgrConnPool::instance()->invalidateConnections( dataSourceUri() ); @@ -1732,7 +1752,7 @@ bool QgsOgrProvider::deleteFeatures( const QgsFeatureIds & id ) clearMinMaxCache(); - updateExtents(); + invalidateCachedExtent( true ); return returnvalue; } @@ -3440,7 +3460,7 @@ void QgsOgrProvider::close() mValid = false; setProperty( "_debug_open_mode", "invalid" ); - updateExtents(); + invalidateCachedExtent( false ); } void QgsOgrProvider::reloadData() diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index 8c013ee8cbd1..9d8c2f6aa877 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -280,6 +280,9 @@ class QgsOgrProvider : public QgsVectorDataProvider /** Clean shapefile from features which are marked as deleted */ void repack(); + /** Invalidate extent and optionnaly force its low level recomputation */ + void invalidateCachedExtent( bool bForceRecomputeExtent ); + enum OpenMode { OpenModeInitial, @@ -299,6 +302,7 @@ class QgsOgrProvider : public QgsVectorDataProvider bool mFirstFieldIsFid; OGRDataSourceH ogrDataSource; mutable OGREnvelope* mExtent; + bool mForceRecomputeExtent; /** This member variable receives the same value as extent_ in the method QgsOgrProvider::extent(). The purpose is to prevent a memory leak*/ diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index e23593a5d3da..63c4bc664207 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -19,7 +19,7 @@ import shutil from osgeo import gdal, ogr -from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry +from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsRectangle from qgis.testing import start_app, unittest start_app() @@ -154,5 +154,44 @@ def testBug15351_commit_closeProvider_closeIter(self): def testBug15351_commit_closeIter_closeProvider(self): self.internalTestBug15351('commit_closeIter_closeProvider') + @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 1, 2)) + def testGeopackageExtentUpdate(self): + ''' test http://hub.qgis.org/issues/15273 ''' + tmpfile = os.path.join(self.basetestpath, 'testGeopackageExtentUpdate.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) + f = ogr.Feature(lyr.GetLayerDefn()) + f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 0)')) + lyr.CreateFeature(f) + f = ogr.Feature(lyr.GetLayerDefn()) + f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 1)')) + lyr.CreateFeature(f) + f = None + f = ogr.Feature(lyr.GetLayerDefn()) + f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 0.5)')) + lyr.CreateFeature(f) + f = None + ds = None + + vl = QgsVectorLayer(u'{}'.format(tmpfile), u'test', u'ogr') + + # Test moving a geometry that touches the bbox + self.assertTrue(vl.startEditing()) + self.assertTrue(vl.changeGeometry(1, QgsGeometry.fromWkt('Point (0.5 0)'))) + self.assertTrue(vl.commitChanges()) + reference = QgsGeometry.fromRect(QgsRectangle(0.5, 0.0, 1.0, 1.0)) + provider_extent = QgsGeometry.fromRect(vl.extent()) + self.assertTrue(QgsGeometry.compare(provider_extent.asPolygon()[0], reference.asPolygon()[0], 0.00001), + provider_extent.asPolygon()[0]) + + # Test deleting a geometry that touches the bbox + self.assertTrue(vl.startEditing()) + self.assertTrue(vl.deleteFeature(2)) + self.assertTrue(vl.commitChanges()) + reference = QgsGeometry.fromRect(QgsRectangle(0.5, 0.0, 1.0, 0.5)) + provider_extent = QgsGeometry.fromRect(vl.extent()) + self.assertTrue(QgsGeometry.compare(provider_extent.asPolygon()[0], reference.asPolygon()[0], 0.00001), + provider_extent.asPolygon()[0]) + if __name__ == '__main__': unittest.main() From e0fc641402b7dc9d46eb740f1ad8530a23a8fe18 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 18 Oct 2016 15:43:28 +0200 Subject: [PATCH 315/897] Show commit errors in transaction mode --- python/core/qgsproject.sip | 9 ++++++++- src/app/qgisapp.cpp | 10 ++++++++++ src/app/qgisapp.h | 2 ++ src/core/qgsproject.cpp | 12 ++++++++++-- src/core/qgsproject.h | 17 +++++++++++++---- 5 files changed, 43 insertions(+), 7 deletions(-) diff --git a/python/core/qgsproject.sip b/python/core/qgsproject.sip index 6371c8914871..c4790386a12c 100644 --- a/python/core/qgsproject.sip +++ b/python/core/qgsproject.sip @@ -467,8 +467,15 @@ class QgsProject : QObject */ void variablesChanged(); - public slots: + /** + * Emitted whenever a new transaction group has been created or a + * transaction group has been removed. + * + * @note Added in QGIS 3.0 + */ + void transactionGroupsChanged(); + public slots: /** * Flag the project as dirty (modified). If this flag is set, the user will * be asked to save changes to the project before closing the current project. diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 4bbeb093dd98..d5601a6829d5 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -2773,6 +2773,8 @@ void QgisApp::setupConnections() connect( this, SIGNAL( projectRead() ), this, SLOT( fileOpenedOKAfterLaunch() ) ); + connect( QgsProject::instance(), &QgsProject::transactionGroupsChanged, this, &QgisApp::onTransactionGroupsChanged ); + // connect preview modes actions connect( mActionPreviewModeOff, SIGNAL( triggered() ), this, SLOT( disablePreviewMode() ) ); connect( mActionPreviewModeGrayscale, SIGNAL( triggered() ), this, SLOT( activateGrayscalePreview() ) ); @@ -11201,6 +11203,14 @@ void QgisApp::keyPressEvent( QKeyEvent * e ) } } +void QgisApp::onTransactionGroupsChanged() +{ + Q_FOREACH ( QgsTransactionGroup* tg, QgsProject::instance()->transactionGroups().values() ) + { + connect( tg, SIGNAL( commitError( QString ) ), this, SLOT( displayMessage( QString, QString, QgsMessageBar::MessageLevel ) ), Qt::UniqueConnection ); + } +} + void QgisApp::startProfile( const QString& name ) { mProfiler->start( name ); diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index 14bfd91b9ae9..61b79b7ddad7 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -726,6 +726,8 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow #endif private slots: + void onTransactionGroupsChanged(); + //! validate a SRS void validateCrs( QgsCoordinateReferenceSystem &crs ); diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 3b5932ecc381..04d3f84c722a 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -995,6 +995,8 @@ void QgsProject::onMapLayersAdded( const QList& layers ) { QMap existingMaps = QgsMapLayerRegistry::instance()->mapLayers(); + bool tgChanged = false; + Q_FOREACH ( QgsMapLayer* layer, layers ) { QgsVectorLayer* vlayer = qobject_cast( layer ); @@ -1013,8 +1015,7 @@ void QgsProject::onMapLayersAdded( const QList& layers ) { tg = new QgsTransactionGroup(); mTransactionGroups.insert( qMakePair( key, connString ), tg ); - - connect( tg, SIGNAL( commitError( QString ) ), this, SLOT( displayMapToolMessage( QString ) ) ); + tgChanged = true; } tg->addLayer( vlayer ); } @@ -1022,6 +1023,9 @@ void QgsProject::onMapLayersAdded( const QList& layers ) vlayer->dataProvider()->setProviderProperty( QgsVectorDataProvider::EvaluateDefaultValues, evaluateDefaultValues() ); } + if ( tgChanged ) + emit transactionGroupsChanged(); + connect( layer, SIGNAL( configChanged() ), this, SLOT( setDirty() ) ); // check if we have to update connections for layers with dependencies @@ -1039,18 +1043,22 @@ void QgsProject::onMapLayersAdded( const QList& layers ) void QgsProject::cleanTransactionGroups( bool force ) { + bool changed = false; for ( QMap< QPair< QString, QString>, QgsTransactionGroup*>::Iterator tg = mTransactionGroups.begin(); tg != mTransactionGroups.end(); ) { if ( tg.value()->isEmpty() || force ) { delete tg.value(); tg = mTransactionGroups.erase( tg ); + changed = true; } else { ++tg; } } + if ( changed ) + emit transactionGroupsChanged(); } bool QgsProject::read( QDomNode &layerNode ) diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index 017f5e1b3bc6..b912b7532902 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -513,9 +513,11 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera //! emitted when an old project file is read. void oldProjectVersionWarning( const QString& ); - //! emitted when a layer from a projects was read - // @param i current layer - // @param n number of layers + /** + * Emitted when a layer from a projects was read. + * @param i current layer + * @param n number of layers + */ void layerLoaded( int i, int n ); void loadingLayer( const QString& ); @@ -536,8 +538,15 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ void variablesChanged(); - public slots: + /** + * Emitted whenever a new transaction group has been created or a + * transaction group has been removed. + * + * @note Added in QGIS 3.0 + */ + void transactionGroupsChanged(); + public slots: /** * Flag the project as dirty (modified). If this flag is set, the user will * be asked to save changes to the project before closing the current project. From 135576ec4d89c925d7d32b5afada0e99ba1a8de8 Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 27 Sep 2016 00:56:37 +0200 Subject: [PATCH 316/897] [processing] fixed wrong import in i_aster_toar Conflicts: python/plugins/processing/algs/grass7/ext/i_aster_toar.py --- python/plugins/processing/algs/grass7/ext/i_aster_toar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/grass7/ext/i_aster_toar.py b/python/plugins/processing/algs/grass7/ext/i_aster_toar.py index 86938870309a..0972f978a9e3 100644 --- a/python/plugins/processing/algs/grass7/ext/i_aster_toar.py +++ b/python/plugins/processing/algs/grass7/ext/i_aster_toar.py @@ -27,7 +27,7 @@ __revision__ = '$Format:%H$' from .i import multipleOutputDir -from processoing.core.parameters import getParameterFromString +from processing.core.parameters import getParameterFromString def processCommand(alg): From c0e3b8fbf9975b1b1875c70a493dc1e7a2ffaa26 Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 27 Sep 2016 13:26:01 +0200 Subject: [PATCH 317/897] [processing] added short help for saga raster calculator --- python/plugins/processing/algs/help/saga.yaml | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 python/plugins/processing/algs/help/saga.yaml diff --git a/python/plugins/processing/algs/help/saga.yaml b/python/plugins/processing/algs/help/saga.yaml new file mode 100644 index 000000000000..8068ccbb1495 --- /dev/null +++ b/python/plugins/processing/algs/help/saga.yaml @@ -0,0 +1,48 @@ +saga:rastercalculator: > + This algorithm allows to perform algebraic operations on raster layers + + It requires a base layer, and a set of additional layers. The base layer is identified as "a" in the formula, while the additional layers are identified as "b, c, d...", using the order in which they appear in the multiple selection dialog. + + The resulting layer has the extent and cellsize of the main layer. + + The following operators and functions are available. + + - Addition (+) + + - Subtraction ( - ) + + - Multiplication (*) + + - Division (/) + + - Power (^) + + - ln(x): returns natural logarithm of x. + + - sin(x): returns the sine of x. x must be in radians + + - cos(x): returns the cosine of x. x must be in radians + + - cos(x): returns the tangente of x. x must be in radians + + - asin(x): returns the arcsine of x, in radians + + - acos(x): returns the arccosine of x, in radians + + - atan(x): returns the arctangent of x, in radians + + - atan2(x,y): returns the arctangent y/x, in radians + + - abs(x): return the absolute value of x. abs(- 5)=5 + + - int(x): returns the integer part of x. int(5.4)=5 + + - mod(x,y): returns the modulus of x/y. mod(7,4)=3 + + - gt(x,y): true if x is greater than y + + - lt(x,y): true if x is lower than y + + - eq(x,y): true if x equals y. When using this function SAGA evaluates it in a per–cell basis. Therefore, eq(a,b) will not return 1 if grid a equals grid b. It will return 1 for those cells that have the same value in both grids, and zero otherwise. + + - ifelse(condition, x, y) returns x if condition evaluates to true (condition=1) or y if it evaluates to false \ No newline at end of file From 128da3002a72b9d88e355ada3087cee25e8dbbdf Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 29 Sep 2016 13:36:29 +0200 Subject: [PATCH 318/897] [processing] better update of expression widget when layer is changed in fields calculator --- .../algs/qgis/ui/FieldsCalculatorDialog.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py index 91f2f0d8abcd..84e36e612b29 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py @@ -90,22 +90,21 @@ def manageGui(self): self.builder.loadRecent('fieldcalc') - self.updateLayer() + self.initContext() - def updateLayer(self): - self.layer = dataobjects.getObject(self.cmbInputLayer.currentText()) - - self.builder.setLayer(self.layer) - self.builder.loadFieldNames() - - exp_context = QgsExpressionContext() + def initContext(self): + exp_context = self.builder.expressionContext() exp_context.appendScope(QgsExpressionContextUtils.globalScope()) exp_context.appendScope(QgsExpressionContextUtils.projectScope()) exp_context.appendScope(QgsExpressionContextUtils.layerScope(self.layer)) exp_context.lastScope().setVariable("row_number", 1) exp_context.setHighlightedVariables(["row_number"]) self.builder.setExpressionContext(exp_context) - + + def updateLayer(self): + self.layer = dataobjects.getObject(self.cmbInputLayer.currentText()) + self.builder.setLayer(self.layer) + self.builder.loadFieldNames() self.populateFields() def setupSpinboxes(self, index): From 90db24648894d24cecf170e1550726db1b35d99f Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 20 Sep 2016 14:33:09 +0200 Subject: [PATCH 319/897] [processing] use only selected features for spatial index fixes #15584 --- python/plugins/processing/tools/vector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index bd52ea399dd5..8472cb725d08 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -221,7 +221,7 @@ def testForUniqueness(fieldList1, fieldList2): def spatialindex(layer): """Creates a spatial index for the passed vector layer. """ - idx = QgsSpatialIndex(layer.getFeatures()) + idx = QgsSpatialIndex(features(layer)) return idx From eb5fc90f44521411ca85aa1ed45be1bd981a7f6f Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 21 Sep 2016 10:49:36 +0200 Subject: [PATCH 320/897] [processing] dont use hidden outputs when exporting to python or displaying alg help fixes #14998 Conflicts: python/plugins/processing/core/GeoAlgorithm.py --- python/plugins/processing/core/GeoAlgorithm.py | 3 ++- python/plugins/processing/modeler/ModelerAlgorithm.py | 9 +++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index e7fbd43471d3..7f39d5d8e18c 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -462,7 +462,8 @@ def __str__(self): for param in self.parameters: s += '\t' + str(param) + '\n' for out in self.outputs: - s += '\t' + str(out) + '\n' + if not out.hidden: + s += '\t' + str(out) + '\n' s += '\n' return s diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index cbf5c38c59b6..dc00787f7bd9 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -154,10 +154,11 @@ def _toString(v): return str(value) params.append(_toString(value)) for out in self.algorithm.outputs: - if out.name in self.outputs: - params.append(safeName(self.outputs[out.name].description).lower()) - else: - params.append(str(None)) + if not out.hidden: + if out.name in self.outputs: + params.append(safeName(self.outputs[out.name].description).lower()) + else: + params.append(str(None)) s.append("outputs_%s=processing.runalg('%s', %s)" % (self.name, self.consoleName, ",".join(params))) return s From 22a6c473d95479c13522b9c93e7401de86035af0 Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 21 Sep 2016 08:12:21 +0200 Subject: [PATCH 321/897] [processing] alternative way of copying algorithms in a model. should fix #15060 and #15480 --- python/plugins/processing/modeler/ModelerAlgorithm.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index dc00787f7bd9..294b5027cb6d 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -235,7 +235,11 @@ class ModelerAlgorithm(GeoAlgorithm): def getCopy(self): newone = ModelerAlgorithm() newone.provider = self.provider - newone.algs = copy.deepcopy(self.algs) + + newone.algs = {} + for algname, alg in self.algs.iteritems(): + newone.algs[algname] = Algorithm() + newone.algs[algname].__dict__.update(copy.deepcopy(alg.todict())) newone.inputs = copy.deepcopy(self.inputs) newone.defineCharacteristics() newone.name = self.name From 7a87fb55b0536204a434719b87f50f496d52120b Mon Sep 17 00:00:00 2001 From: volaya Date: Wed, 21 Sep 2016 09:41:22 +0200 Subject: [PATCH 322/897] [processing] don't use full path for naming layers when loaded in dataobjects.load --- python/plugins/processing/tools/dataobjects.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 40c9bf32b422..810d3a359881 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -273,14 +273,15 @@ def getObjectFromUri(uri, forceLoad=True): settings.setValue('/Projections/defaultBehaviour', '') # If is not opened, we open it + name = os.path.basename(uri) for provider in ['ogr', 'postgres', 'spatialite', 'virtual']: - layer = QgsVectorLayer(uri, uri, provider) + layer = QgsVectorLayer(uri, name, provider) if layer.isValid(): if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) _loadedLayers[normalizeLayerSource(layer.source())] = layer return layer - layer = QgsRasterLayer(uri, uri) + layer = QgsRasterLayer(uri, name) if layer.isValid(): if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) From b4562d143e6ef140e14b0cb9625ef923412db793 Mon Sep 17 00:00:00 2001 From: volaya Date: Tue, 4 Oct 2016 09:50:51 +0200 Subject: [PATCH 323/897] [processing] fixed iterative execution fixes #15650 --- python/plugins/processing/gui/AlgorithmExecutor.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmExecutor.py b/python/plugins/processing/gui/AlgorithmExecutor.py index db94b25cde25..13d9c9151110 100644 --- a/python/plugins/processing/gui/AlgorithmExecutor.py +++ b/python/plugins/processing/gui/AlgorithmExecutor.py @@ -52,7 +52,8 @@ def runalg(alg, progress=None): return True except GeoAlgorithmExecutionException as e: ProcessingLog.addToLog(sys.exc_info()[0], ProcessingLog.LOG_ERROR) - progress.error(e.msg) + if progress is not None: + progress.error(e.msg) return False @@ -89,7 +90,7 @@ def runalgIterating(alg, paramToIter, progress): out.value = filename progress.setText(tr('Executing iteration %s/%s...' % (str(i), str(len(filelist))))) progress.setPercentage(i * 100 / len(filelist)) - if runalg(alg): + if runalg(alg, progress): handleAlgorithmResults(alg, None, False) else: return False From b83fbb16c921943823a29d8cfb296abf1e1901c6 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 13 Oct 2016 13:40:47 +0200 Subject: [PATCH 324/897] [processing] warn if extent might not be in the expected CRS --- .../processing/core/ProcessingConfig.py | 5 +++ .../plugins/processing/gui/AlgorithmDialog.py | 45 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/python/plugins/processing/core/ProcessingConfig.py b/python/plugins/processing/core/ProcessingConfig.py index a4fdba897cab..72254a879594 100644 --- a/python/plugins/processing/core/ProcessingConfig.py +++ b/python/plugins/processing/core/ProcessingConfig.py @@ -60,6 +60,7 @@ class ProcessingConfig(object): POST_EXECUTION_SCRIPT = 'POST_EXECUTION_SCRIPT' SHOW_CRS_DEF = 'SHOW_CRS_DEF' WARN_UNMATCHING_CRS = 'WARN_UNMATCHING_CRS' + WARN_UNMATCHING_EXTENT_CRS = 'WARN_UNMATCHING_EXTENT_CRS' DEFAULT_OUTPUT_RASTER_LAYER_EXT = 'DEFAULT_OUTPUT_RASTER_LAYER_EXT' DEFAULT_OUTPUT_VECTOR_LAYER_EXT = 'DEFAULT_OUTPUT_VECTOR_LAYER_EXT' SHOW_PROVIDERS_TOOLTIP = "SHOW_PROVIDERS_TOOLTIP" @@ -108,6 +109,10 @@ def initialize(): ProcessingConfig.tr('General'), ProcessingConfig.WARN_UNMATCHING_CRS, ProcessingConfig.tr("Warn before executing if layer CRS's do not match"), True)) + ProcessingConfig.addSetting(Setting( + ProcessingConfig.tr('General'), + ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS, + ProcessingConfig.tr("Warn before executing if extent CRS might not match layers CRS"), True)) ProcessingConfig.addSetting(Setting( ProcessingConfig.tr('General'), ProcessingConfig.RASTER_STYLE, diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index aa13eca88781..cc7e47b8b774 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -48,6 +48,9 @@ from processing.core.outputs import OutputTable +from qgis.utils import iface + + class AlgorithmDialog(AlgorithmDialogBase): def __init__(self, alg): @@ -100,6 +103,37 @@ def setParamValues(self): def setParamValue(self, param, wrapper, alg=None): return param.setValue(wrapper.value()) + def checkExtentCRS(self): + unmatchingCRS = False + hasExtent = False + projectCRS = iface.mapCanvas().mapSettings().destinationCrs() + layers = dataobjects.getAllLayers() + for param in self.alg.parameters: + if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): + if param.value: + if isinstance(param, ParameterMultipleInput): + inputlayers = param.value.split(';') + else: + inputlayers = [param.value] + for inputlayer in inputlayers: + for layer in layers: + if layer.source() == inputlayer: + if layer.crs() != projectCRS: + unmatchingCRS = True + + p = dataobjects.getObjectFromUri(inputlayer) + if p is not None: + if p.crs() != projectCRS: + unmatchingCRS = True + if isinstance(param, ParameterExtent): + value = self.mainWidget.valueItems[param.name].leText.text().strip() + print value + if value: + hasExtent = True + + return hasExtent and unmatchingCRS + + def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) @@ -115,6 +149,17 @@ def accept(self): QMessageBox.No) if reply == QMessageBox.No: return + checkExtentCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) + if checkExtentCRS and self.checkExtentCRS(): + reply = QMessageBox.question(self, self.tr("Extent CRS"), + self.tr('Extent parameters must use the same CRS as the input layers.\n' + 'Your input layers do not have the same extent as the project, ' + 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' + 'Do you want to continue?'), + QMessageBox.Yes | QMessageBox.No, + QMessageBox.No) + if reply == QMessageBox.No: + return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning( From d63222e68e34591ed55d0960c58aeca5c6eb9d47 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Sat, 15 Oct 2016 10:44:05 +0200 Subject: [PATCH 325/897] [processing] Allow using libpq defaults for host,port,user,pass and dbname Fixes #15706 --- .../processing/algs/gdal/ogr2ogrtopostgis.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py index 2820f89bab75..d8fbbe7b2eda 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py @@ -203,17 +203,20 @@ def getConsoleCommands(self): arguments.append('"' + shapeEncoding + '"') arguments.append('-f') arguments.append('PostgreSQL') - arguments.append('PG:"host=' + host) - arguments.append('port=' + port) - if len(dbname) > 0: + arguments.append('PG:"') + if host: + arguments.append(' host=' + host) + if port: + arguments.append('port=' + port) + if dbname: arguments.append('dbname=' + dbname) - if len(password) > 0: + if password: arguments.append('password=' + password) - if len(schema) > 0: + if schema: arguments.append('active_schema=' + schema) - else: - arguments.append('active_schema=public') - arguments.append('user=' + user + '"') + if user: + arguments.append('user=' + user) + arguments.append('"') arguments.append(dimstring) arguments.append(ogrLayer) arguments.append(ogrLayerName(inLayer)) From 6731eaa9e52da8047bcc42a972eec3c3c944c877 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Sat, 15 Oct 2016 11:14:29 +0200 Subject: [PATCH 326/897] Add test for setting up connection string Conflicts: python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py --- .../processing/algs/gdal/ogr2ogrtopostgis.py | 41 +++++++++------- .../processing/tests/GdalAlgorithmsTest.py | 48 +++++++++++++++++++ 2 files changed, 71 insertions(+), 18 deletions(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py index d8fbbe7b2eda..273eb33f0a2d 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py @@ -154,6 +154,28 @@ def defineCharacteristics(self): self.addParameter(ParameterString(self.OPTIONS, self.tr('Additional creation options'), '', optional=True)) + def getConnectionString(self): + host = str(self.getParameterValue(self.HOST)) + port = str(self.getParameterValue(self.PORT)) + user = str(self.getParameterValue(self.USER)) + dbname = str(self.getParameterValue(self.DBNAME)) + password = str(self.getParameterValue(self.PASSWORD)) + schema = str(self.getParameterValue(self.SCHEMA)) + arguments = [] + if host: + arguments.append('host=' + host) + if port: + arguments.append('port=' + port) + if dbname: + arguments.append('dbname=' + dbname) + if password: + arguments.append('password=' + password) + if schema: + arguments.append('active_schema=' + schema) + if user: + arguments.append('user=' + user) + return GdalUtils.escapeAndJoin(arguments) + def getConsoleCommands(self): inLayer = self.getParameterValue(self.INPUT_LAYER) ogrLayer = ogrConnectionString(inLayer)[1:-1] @@ -161,12 +183,6 @@ def getConsoleCommands(self): ssrs = str(self.getParameterValue(self.S_SRS)) tsrs = str(self.getParameterValue(self.T_SRS)) asrs = str(self.getParameterValue(self.A_SRS)) - host = str(self.getParameterValue(self.HOST)) - port = str(self.getParameterValue(self.PORT)) - user = str(self.getParameterValue(self.USER)) - dbname = str(self.getParameterValue(self.DBNAME)) - password = str(self.getParameterValue(self.PASSWORD)) - schema = str(self.getParameterValue(self.SCHEMA)) table = str(self.getParameterValue(self.TABLE)) pk = str(self.getParameterValue(self.PK)) pkstring = "-lco FID=" + pk @@ -204,18 +220,7 @@ def getConsoleCommands(self): arguments.append('-f') arguments.append('PostgreSQL') arguments.append('PG:"') - if host: - arguments.append(' host=' + host) - if port: - arguments.append('port=' + port) - if dbname: - arguments.append('dbname=' + dbname) - if password: - arguments.append('password=' + password) - if schema: - arguments.append('active_schema=' + schema) - if user: - arguments.append('user=' + user) + arguments.append(self.getConnectionString()) arguments.append('"') arguments.append(dimstring) arguments.append(ogrLayer) diff --git a/python/plugins/processing/tests/GdalAlgorithmsTest.py b/python/plugins/processing/tests/GdalAlgorithmsTest.py index 3766cdd3d36d..57f6f13c276c 100644 --- a/python/plugins/processing/tests/GdalAlgorithmsTest.py +++ b/python/plugins/processing/tests/GdalAlgorithmsTest.py @@ -26,6 +26,7 @@ __revision__ = ':%H$' import AlgorithmsTestBase +from processing.algs.gdal.ogr2ogrtopostgis import Ogr2OgrToPostGis import nose2 import shutil @@ -54,5 +55,52 @@ def test_definition_file(self): return 'gdal_algorithm_tests.yaml' +class TestGdalOgr2OgrToPostgis(unittest.TestCase): + + @classmethod + def setUpClass(cls): + #start_app() + pass + + @classmethod + def tearDownClass(cls): + pass + + # See http://hub.qgis.org/issues/15706 + def test_getConnectionString(self): + + obj = Ogr2OgrToPostGis() + + cs = obj.getConnectionString() + # NOTE: defaults are debatable, see + # https://github.com/qgis/QGIS/pull/3607#issuecomment-253971020 + self.assertEquals(obj.getConnectionString(), + "host=localhost port=5432 active_schema=public") + + obj.setParameterValue('HOST', 'remote') + self.assertEquals(obj.getConnectionString(), + "host=remote port=5432 active_schema=public") + + obj.setParameterValue('HOST', '') + self.assertEquals(obj.getConnectionString(), + "port=5432 active_schema=public") + + obj.setParameterValue('PORT', '5555') + self.assertEquals(obj.getConnectionString(), + "port=5555 active_schema=public") + + obj.setParameterValue('PORT', '') + self.assertEquals(obj.getConnectionString(), + "active_schema=public") + + obj.setParameterValue('USER', 'usr') + self.assertEquals(obj.getConnectionString(), + "active_schema=public user=usr") + + obj.setParameterValue('PASSWORD', 'pwd') + self.assertEquals(obj.getConnectionString(), + "password=pwd active_schema=public user=usr") + + if __name__ == '__main__': nose2.main() From e55d1923fc08900864f7ef02866cca0a2e11cc15 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 17 Oct 2016 09:18:33 +0200 Subject: [PATCH 327/897] [processing] fixes for 'import into PostGIS' alg fixes #15097 --- python/plugins/processing/algs/qgis/ImportIntoPostGIS.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py b/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py index da47c25c71a2..ae6240bd8b0c 100644 --- a/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py +++ b/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py @@ -94,7 +94,7 @@ def processAlgorithm(self, progress): convertLowerCase = self.getParameterValue(self.LOWERCASE_NAMES) dropStringLength = self.getParameterValue(self.DROP_STRING_LENGTH) forceSinglePart = self.getParameterValue(self.FORCE_SINGLEPART) - primaryKeyField = self.getParameterValue(self.PRIMARY_KEY) + primaryKeyField = self.getParameterValue(self.PRIMARY_KEY) or 'id' encoding = self.getParameterValue(self.ENCODING) layerUri = self.getParameterValue(self.INPUT) @@ -103,6 +103,7 @@ def processAlgorithm(self, progress): table = self.getParameterValue(self.TABLENAME).strip() if table == '': table = layer.name() + table = "_".join(table.split(".")[:-1]) table = table.replace(' ', '').lower()[0:62] providerName = 'postgres' @@ -126,10 +127,7 @@ def processAlgorithm(self, progress): geomColumn = None uri = db.uri - if primaryKeyField: - uri.setDataSource(schema, table, geomColumn, '', primaryKeyField) - else: - uri.setDataSource(schema, table, geomColumn, '') + uri.setDataSource(schema, table, geomColumn, '', primaryKeyField) if encoding: layer.setProviderEncoding(encoding) From aeaef6f549832bce107cd67095c64e1e776c781a Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 17 Oct 2016 09:39:15 +0200 Subject: [PATCH 328/897] [processing] made connection params optional in ogr2ogrtopostgis.py --- .../plugins/processing/algs/gdal/ogr2ogrtopostgis.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py index 273eb33f0a2d..3475fd52449f 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py @@ -94,15 +94,15 @@ def defineCharacteristics(self): self.addParameter(ParameterCrs(self.S_SRS, self.tr('Override source CRS'), '', optional=True)) self.addParameter(ParameterString(self.HOST, - self.tr('Host'), 'localhost', optional=False)) + self.tr('Host'), 'localhost', optional=True)) self.addParameter(ParameterString(self.PORT, - self.tr('Port'), '5432', optional=False)) + self.tr('Port'), '5432', optional=True)) self.addParameter(ParameterString(self.USER, - self.tr('Username'), '', optional=False)) + self.tr('Username'), '', optional=True)) self.addParameter(ParameterString(self.DBNAME, - self.tr('Database name'), '', optional=False)) + self.tr('Database name'), '', optional=True)) self.addParameter(ParameterString(self.PASSWORD, - self.tr('Password'), '', optional=False)) + self.tr('Password'), '', optional=True)) self.addParameter(ParameterString(self.SCHEMA, self.tr('Schema name'), 'public', optional=True)) self.addParameter(ParameterString(self.TABLE, From 63955e657448ad328ce205694028debd61f0c6ed Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 17 Oct 2016 10:16:26 +0200 Subject: [PATCH 329/897] [processing] fixed handling of None param values in ogr2ogrtopostgis.py Conflicts: python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py --- .../processing/algs/gdal/ogr2ogrtopostgis.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py index 3475fd52449f..272707f96cb2 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrtopostgis.py @@ -155,17 +155,17 @@ def defineCharacteristics(self): self.tr('Additional creation options'), '', optional=True)) def getConnectionString(self): - host = str(self.getParameterValue(self.HOST)) - port = str(self.getParameterValue(self.PORT)) - user = str(self.getParameterValue(self.USER)) - dbname = str(self.getParameterValue(self.DBNAME)) - password = str(self.getParameterValue(self.PASSWORD)) - schema = str(self.getParameterValue(self.SCHEMA)) + host = self.getParameterValue(self.HOST) + port = self.getParameterValue(self.PORT) + user = self.getParameterValue(self.USER) + dbname = self.getParameterValue(self.DBNAME) + password = self.getParameterValue(self.PASSWORD) + schema = self.getParameterValue(self.SCHEMA) arguments = [] if host: arguments.append('host=' + host) if port: - arguments.append('port=' + port) + arguments.append('port=' + str(port)) if dbname: arguments.append('dbname=' + dbname) if password: From 700441eec9836b225fc0b577dda9c895c86d22cc Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 18 Oct 2016 16:54:16 +0300 Subject: [PATCH 330/897] [processing] remove debug line and fix spatial index creation --- python/plugins/processing/gui/AlgorithmDialog.py | 2 -- python/plugins/processing/tools/vector.py | 8 +++++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index cc7e47b8b774..dd07e94c3c36 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -127,13 +127,11 @@ def checkExtentCRS(self): unmatchingCRS = True if isinstance(param, ParameterExtent): value = self.mainWidget.valueItems[param.name].leText.text().strip() - print value if value: hasExtent = True return hasExtent and unmatchingCRS - def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 8472cb725d08..16564e6932eb 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -221,7 +221,13 @@ def testForUniqueness(fieldList1, fieldList2): def spatialindex(layer): """Creates a spatial index for the passed vector layer. """ - idx = QgsSpatialIndex(features(layer)) + request = QgsFeatureRequest() + request.setSubsetOfAttributes([]) + if ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) \ + and layer.selectedFeatureCount() > 0: + idx = layer.selectedFeaturesIterator(request) + else: + idx = QgsSpatialIndex(layer.getFeatures(request)) return idx From 8c37370310e137cf716f23a0c1edb2f65d1a9cb2 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 15:59:40 +0200 Subject: [PATCH 331/897] Fix 70ae301310c7a58134ac699fae70af7fd1176684 70ae301310c7a58134ac699fae70af7fd1176684 requires a recent enough GDAL trunk or GDAL 2.1.2 --- tests/src/python/test_provider_ogr_gpkg.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index 63c4bc664207..97c102531583 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -171,7 +171,13 @@ def testGeopackageExtentUpdate(self): f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(1 0.5)')) lyr.CreateFeature(f) f = None + gdal.ErrorReset() + ds.ExecuteSQL('RECOMPUTE EXTENT ON test') + has_error = gdal.GetLastErrorMsg() != '' ds = None + if has_error: + print('Too old GDAL trunk version. Please update') + return vl = QgsVectorLayer(u'{}'.format(tmpfile), u'test', u'ogr') From 9d6acbdb999f96003111ca4a36e6f4e5efb89bb5 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 18 Oct 2016 20:57:34 +0300 Subject: [PATCH 332/897] [processing] add missed imports --- python/plugins/processing/gui/AlgorithmDialog.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index dd07e94c3c36..89f2d34900bc 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -33,6 +33,7 @@ from qgis.core import QgsMapLayerRegistry from qgis.gui import QgsMessageBar +from qgis.utils import iface from processing.core.ProcessingLog import ProcessingLog from processing.core.ProcessingConfig import ProcessingConfig @@ -43,12 +44,16 @@ from processing.gui.AlgorithmExecutor import runalg, runalgIterating from processing.gui.Postprocessing import handleAlgorithmResults +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterExtent +from processing.core.parameters import ParameterMultipleInput + from processing.core.outputs import OutputRaster from processing.core.outputs import OutputVector from processing.core.outputs import OutputTable - -from qgis.utils import iface +from processing.tools import dataobjects class AlgorithmDialog(AlgorithmDialogBase): From 68cb04a549d86bfba85a52fbe8eea6d8f184a33d Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 14:25:36 +0200 Subject: [PATCH 333/897] [OGR provider] Support full SELECT subset string This will be useful for DBManager SQL request layer. --- src/providers/ogr/qgsogrprovider.cpp | 10 ++++++++-- tests/src/python/test_provider_ogr_gpkg.py | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index a30474c07a10..b43b307aa51d 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -3249,8 +3249,14 @@ OGRLayerH QgsOgrProviderUtils::setSubsetString( OGRLayerH layer, OGRDataSourceH layerName = encoding->fromUnicode( modifiedLayerName ); } } - QByteArray sql = "SELECT * FROM " + quotedIdentifier( layerName, ogrDriverName ); - sql += " WHERE " + encoding->fromUnicode( subsetString ); + QByteArray sql; + if ( subsetString.startsWith( "SELECT ", Qt::CaseInsensitive ) ) + sql = encoding->fromUnicode( subsetString ); + else + { + sql = "SELECT * FROM " + quotedIdentifier( layerName, ogrDriverName ); + sql += " WHERE " + encoding->fromUnicode( subsetString ); + } QgsDebugMsg( QString( "SQL: %1" ).arg( encoding->toUnicode( sql ) ) ); return OGR_DS_ExecuteSQL( ds, sql.constData(), nullptr, nullptr ); diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index 97c102531583..32c89f1f4eb0 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -199,5 +199,27 @@ def testGeopackageExtentUpdate(self): self.assertTrue(QgsGeometry.compare(provider_extent.asPolygon()[0], reference.asPolygon()[0], 0.00001), provider_extent.asPolygon()[0]) + def testSelectSubsetString(self): + + tmpfile = os.path.join(self.basetestpath, 'testSelectSubsetString.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon) + lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) + f = ogr.Feature(lyr.GetLayerDefn()) + f['foo'] = 'bar' + lyr.CreateFeature(f) + f = None + f = ogr.Feature(lyr.GetLayerDefn()) + f['foo'] = 'baz' + lyr.CreateFeature(f) + f = None + ds = None + + vl = QgsVectorLayer('{}|layerid=0'.format(tmpfile), 'test', 'ogr') + vl.setSubsetString("SELECT fid, foo FROM test WHERE foo = 'baz'") + got = [feat for feat in vl.getFeatures()] + self.assertEqual(len(got), 1) + + if __name__ == '__main__': unittest.main() From 3f2866c47a0fc2960bd7c3760f242be8dce2c680 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 14:26:46 +0200 Subject: [PATCH 334/897] [FEATURE] [DBManager] Add a GeoPackage dedicated plugin --- python/plugins/db_manager/db_model.py | 3 +- .../db_manager/db_plugins/CMakeLists.txt | 1 + .../plugins/db_manager/db_plugins/__init__.py | 3 +- .../db_manager/db_plugins/gpkg/CMakeLists.txt | 9 + .../db_manager/db_plugins/gpkg/__init__.py | 0 .../db_manager/db_plugins/gpkg/connector.py | 796 ++++++++++++++++++ .../db_manager/db_plugins/gpkg/data_model.py | 51 ++ .../db_plugins/gpkg/icons/gpkg_icon.png | Bin 0 -> 23317 bytes .../db_manager/db_plugins/gpkg/info_model.py | 47 ++ .../db_manager/db_plugins/gpkg/plugin.py | 314 +++++++ .../db_manager/db_plugins/gpkg/resources.qrc | 5 + .../db_plugins/gpkg/sql_dictionary.py | 28 + python/plugins/db_manager/db_tree.py | 2 +- .../db_manager/dlg_sql_layer_window.py | 2 + 14 files changed, 1258 insertions(+), 3 deletions(-) create mode 100644 python/plugins/db_manager/db_plugins/gpkg/CMakeLists.txt create mode 100644 python/plugins/db_manager/db_plugins/gpkg/__init__.py create mode 100644 python/plugins/db_manager/db_plugins/gpkg/connector.py create mode 100644 python/plugins/db_manager/db_plugins/gpkg/data_model.py create mode 100644 python/plugins/db_manager/db_plugins/gpkg/icons/gpkg_icon.png create mode 100644 python/plugins/db_manager/db_plugins/gpkg/info_model.py create mode 100644 python/plugins/db_manager/db_plugins/gpkg/plugin.py create mode 100644 python/plugins/db_manager/db_plugins/gpkg/resources.qrc create mode 100644 python/plugins/db_manager/db_plugins/gpkg/sql_dictionary.py diff --git a/python/plugins/db_manager/db_model.py b/python/plugins/db_manager/db_model.py index 662f07c1a66b..2485fd3bf905 100644 --- a/python/plugins/db_manager/db_model.py +++ b/python/plugins/db_manager/db_model.py @@ -300,6 +300,7 @@ def __init__(self, parent=None): self.importVector.connect(self.vectorImport) self.hasSpatialiteSupport = "spatialite" in supportedDbTypes() + self.hasGPKGSupport = "gpkg" in supportedDbTypes() self.rootItem = TreeItem(None, None) for dbtype in supportedDbTypes(): @@ -401,7 +402,7 @@ def flags(self, index): flags |= Qt.ItemIsDropEnabled # SL/Geopackage db files can be dropped everywhere in the tree - if self.hasSpatialiteSupport: + if self.hasSpatialiteSupport or self.hasGPKGSupport: flags |= Qt.ItemIsDropEnabled return flags diff --git a/python/plugins/db_manager/db_plugins/CMakeLists.txt b/python/plugins/db_manager/db_plugins/CMakeLists.txt index c3e16d10f90e..c94a1d303bfd 100644 --- a/python/plugins/db_manager/db_plugins/CMakeLists.txt +++ b/python/plugins/db_manager/db_plugins/CMakeLists.txt @@ -1,5 +1,6 @@ ADD_SUBDIRECTORY(postgis) ADD_SUBDIRECTORY(spatialite) +ADD_SUBDIRECTORY(gpkg) IF(WITH_ORACLE) ADD_SUBDIRECTORY(oracle) ENDIF(WITH_ORACLE) diff --git a/python/plugins/db_manager/db_plugins/__init__.py b/python/plugins/db_manager/db_plugins/__init__.py index 327344d302bb..f91700dd5abc 100644 --- a/python/plugins/db_manager/db_plugins/__init__.py +++ b/python/plugins/db_manager/db_plugins/__init__.py @@ -25,7 +25,8 @@ class NotSupportedDbType(Exception): def __init__(self, dbtype): - self.msg = self.tr("%s is not supported yet") % dbtype + from qgis.PyQt.QtWidgets import QApplication + self.msg = QApplication.translate("DBManagerPlugin", "%s is not supported yet" % dbtype) Exception(self, self.msg) def __str__(self): diff --git a/python/plugins/db_manager/db_plugins/gpkg/CMakeLists.txt b/python/plugins/db_manager/db_plugins/gpkg/CMakeLists.txt new file mode 100644 index 000000000000..afc6b2de1514 --- /dev/null +++ b/python/plugins/db_manager/db_plugins/gpkg/CMakeLists.txt @@ -0,0 +1,9 @@ + +FILE(GLOB PY_FILES *.py) +FILE(GLOB ICON_FILES icons/*.png) + +PYQT_ADD_RESOURCES(PYRC_FILES resources.qrc) + +PLUGIN_INSTALL(db_manager db_plugins/gpkg ${PY_FILES} ${PYRC_FILES}) +PLUGIN_INSTALL(db_manager db_plugins/gpkg/icons ${ICON_FILES}) + diff --git a/python/plugins/db_manager/db_plugins/gpkg/__init__.py b/python/plugins/db_manager/db_plugins/gpkg/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/plugins/db_manager/db_plugins/gpkg/connector.py b/python/plugins/db_manager/db_plugins/gpkg/connector.py new file mode 100644 index 000000000000..07517248f59f --- /dev/null +++ b/python/plugins/db_manager/db_plugins/gpkg/connector.py @@ -0,0 +1,796 @@ +# -*- coding: utf-8 -*- + +""" +/*************************************************************************** +Name : DB Manager +Description : Database manager plugin for QGIS +Date : Oct 14 2016 +copyright : (C) 2016 by Even Rouault + (C) 2011 by Giuseppe Sucameli +email : even.rouault at spatialys.com + + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +""" +from builtins import str + +from functools import cmp_to_key + +from qgis.PyQt.QtWidgets import QApplication + +from ..connector import DBConnector +from ..plugin import ConnectionError, DbError, Table + +from qgis.utils import spatialite_connect +import sqlite3 + +from osgeo import gdal, ogr, osr + + +def classFactory(): + return GPKGDBConnector + + +class GPKGDBConnector(DBConnector): + + def __init__(self, uri): + DBConnector.__init__(self, uri) + + self.dbname = uri.database() + self.has_raster = False + self.mapSridToName = {} + + if hasattr(gdal, 'OpenEx'): + # GDAL >= 2 + self.gdal_ds = gdal.OpenEx(self.dbname, gdal.OF_UPDATE) + if self.gdal_ds is None: + self.gdal_ds = gdal.OpenEx(self.dbname) + if self.gdal_ds is None or self.gdal_ds.GetDriver().ShortName != 'GPKG': + raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{0}" not found').format(self.dbname)) + self.has_raster = self.gdal_ds.RasterCount != 0 or self.gdal_ds.GetMetadata('SUBDATASETS') is not None + self.connection = None + self.gdal2 = True + else: + # GDAL 1.X compat. To be removed at some point + self.gdal_ds = ogr.Open(self.dbname, update=1) + if self.gdal_ds is None: + self.gdal_ds = ogr.Open(self.dbname) + if self.gdal_ds is None or self.gdal_ds.GetDriver().GetName() != 'GPKG': + raise ConnectionError(QApplication.translate("DBManagerPlugin", '"{0}" not found').format(self.dbname)) + # For GDAL 1.X, we cannot issue direct SQL SELECT to the OGR datasource + # so we need a direct sqlite connection + try: + self.connection = spatialite_connect(str(self.dbname)) + except self.connection_error_types() as e: + raise ConnectionError(e) + self.gdal2 = False + + def unquoteId(self, quotedId): + if len(quotedId) <= 2 or quotedId[0] != '"' or quotedId[len(quotedId) - 1] != '"': + return quotedId + unquoted = '' + i = 1 + while i < len(quotedId) - 1: + if quotedId[i] == '"' and quotedId[i + 1] == '"': + unquoted += '"' + i += 2 + else: + unquoted += quotedId[i] + i += 1 + return unquoted + + def _fetchOne(self, sql): + if not self.gdal2: + # GDAL 1.X compat. To be removed at some point + c = self._get_cursor() + self._execute(c, sql) + res = c.fetchone() + if res is not None: + return res + else: + return None + else: + sql_lyr = self.gdal_ds.ExecuteSQL(sql) + if sql_lyr is None: + return None + f = sql_lyr.GetNextFeature() + if f is None: + ret = None + else: + ret = [f.GetField(i) for i in range(f.GetFieldCount())] + self.gdal_ds.ReleaseResultSet(sql_lyr) + return ret + + def _fetchAll(self, sql, include_fid_and_geometry=False): + if not self.gdal2: + # GDAL 1.X compat. To be removed at some point + c = self._get_cursor() + self._execute(c, sql) + return c.fetchall() + else: + sql_lyr = self.gdal_ds.ExecuteSQL(sql) + if sql_lyr is None: + return None + ret = [] + while True: + f = sql_lyr.GetNextFeature() + if f is None: + break + else: + if include_fid_and_geometry: + field_vals = [f.GetFID()] + if sql_lyr.GetLayerDefn().GetGeomType() != ogr.wkbNone: + geom = f.GetGeometryRef() + if geom is not None: + geom = geom.ExportToWkt() + field_vals += [geom] + field_vals += [f.GetField(i) for i in range(f.GetFieldCount())] + ret.append(field_vals) + else: + ret.append([f.GetField(i) for i in range(f.GetFieldCount())]) + self.gdal_ds.ReleaseResultSet(sql_lyr) + return ret + + def _fetchAllFromLayer(self, table): + + lyr = self.gdal_ds.GetLayerByName(table.name) + if lyr is None: + return [] + + lyr.ResetReading() + ret = [] + while True: + f = lyr.GetNextFeature() + if f is None: + break + else: + field_vals = [f.GetFID()] + if lyr.GetLayerDefn().GetGeomType() != ogr.wkbNone: + geom = f.GetGeometryRef() + if geom is not None: + geom = geom.ExportToWkt() + field_vals += [geom] + field_vals += [f.GetField(i) for i in range(f.GetFieldCount())] + ret.append(field_vals) + return ret + + def _execute_and_commit(self, sql): + if not self.gdal2: + DBConnector._execute_and_commit(self, sql) + else: + sql_lyr = self.gdal_ds.ExecuteSQL(sql) + self.gdal_ds.ReleaseResultSet(sql_lyr) + + def _execute(self, cursor, sql): + + if self.gdal2 and self.connection is None: + # Needed when evaluating a SQL query + try: + self.connection = spatialite_connect(str(self.dbname)) + except self.connection_error_types() as e: + raise ConnectionError(e) + + return DBConnector._execute(self, cursor, sql) + + def _commit(self): + if not self.gdal2: + return + + try: + self.connection.commit() + + except self.connection_error_types() as e: + raise ConnectionError(e) + + except self.execution_error_types() as e: + # do the rollback to avoid a "current transaction aborted, commands ignored" errors + self._rollback() + raise DbError(e) + + @classmethod + def isValidDatabase(self, path): + if hasattr(gdal, 'OpenEx'): + ds = gdal.OpenEx(self.dbname) + if ds is None or ds.GetDriver().ShortName != 'GPKG': + return False + else: + ds = ogr.Open(path) + if ds is None or ds.GetDriver().GetName() != 'GPKG': + return False + return True + + def getInfo(self): + return None + + def getSpatialInfo(self): + return None + + def hasSpatialSupport(self): + return True + + def hasRasterSupport(self): + return self.has_raster + + def hasCustomQuerySupport(self): + return True + + def hasTableColumnEditingSupport(self): + return True + + def hasCreateSpatialViewSupport(self): + return False + + def fieldTypes(self): + # From "Table 1. GeoPackage Data Types" (http://www.geopackage.org/spec/) + return [ + "TEXT", + "MEDIUMINT", + "INTEGER", + "TINYINT", + "SMALLINT", + "DOUBLE", + "FLOAT" + "DATE", + "DATETIME", + "BOOLEAN", + ] + + def getSchemas(self): + return None + + def getTables(self, schema=None, add_sys_tables=False): + """ get list of tables """ + items = [] + + try: + vectors = self.getVectorTables(schema) + for tbl in vectors: + items.append(tbl) + except DbError: + pass + + try: + rasters = self.getRasterTables(schema) + for tbl in rasters: + items.append(tbl) + except DbError: + pass + + for i, tbl in enumerate(items): + tbl.insert(3, False) # not system table + + return sorted(items, key=cmp_to_key(lambda x, y: (x[1] > y[1]) - (x[1] < y[1]))) + + def getVectorTables(self, schema=None): + + items = [] + for i in range(self.gdal_ds.GetLayerCount()): + lyr = self.gdal_ds.GetLayer(i) + geomtype = lyr.GetGeomType() + if hasattr(ogr, 'GT_Flatten'): + geomtype_flatten = ogr.GT_Flatten(geomtype) + else: + geomtype_flatten = geomtype + geomname = ogr.GeometryTypeToName(geomtype_flatten).upper() + geomdim = 'XY' + if hasattr(ogr, 'GT_HasZ') and ogr.GT_HasZ(lyr.GetGeomType()): + geomdim += 'Z' + if hasattr(ogr, 'GT_HasM') and ogr.GT_HasM(lyr.GetGeomType()): + geomdim += 'M' + srs = lyr.GetSpatialRef() + srid = None + if srs is not None: + if srs.IsProjected(): + name = srs.GetAttrValue('PROJCS', 0) + elif srs.IsGeographic(): + name = srs.GetAttrValue('GEOGCS', 0) + else: + name = None + srid = srs.GetAuthorityCode(None) + if srid is not None: + srid = int(srid) + else: + srid = self._fetchOne('SELECT srid FROM gpkg_spatial_ref_sys WHERE table_name = %s' % self.quoteString(lyr.GetName())) + if srid is not None: + srid = int(srid) + self.mapSridToName[srid] = name + + if geomtype == ogr.wkbNone: + item = list([Table.TableType, + lyr.GetName(), + False, # is_view + ]) + else: + item = list([Table.VectorType, + lyr.GetName(), + False, # is_view + lyr.GetName(), + lyr.GetGeometryColumn(), + geomname, + geomdim, + srid]) + items.append(item) + return items + + def getRasterTables(self, schema=None): + """ get list of table with a geometry column + it returns: + name (table name) + type = 'view' (is a view?) + geometry_column: + r.table_name (the prefix table name, use this to load the layer) + r.geometry_column + srid + """ + + sql = u"""SELECT table_name, 0 AS is_view, table_name AS r_table_name, '' AS r_geometry_column, srs_id FROM gpkg_contents WHERE data_type = 'tiles'""" + ret = self._fetchAll(sql) + if ret is None: + return [] + items = [] + for i, tbl in enumerate(ret): + item = list(tbl) + item.insert(0, Table.RasterType) + items.append(item) + return items + + def getTableRowCount(self, table): + lyr = self.gdal_ds.GetLayerByName(self.getSchemaTableName(table)[1]) + return lyr.GetFeatureCount() if lyr is not None else None + + def getTableFields(self, table): + """ return list of columns in table """ + sql = u"PRAGMA table_info(%s)" % (self.quoteId(table)) + ret = self._fetchAll(sql) + if ret is None: + ret = [] + return ret + + def getTableIndexes(self, table): + """ get info about table's indexes """ + sql = u"PRAGMA index_list(%s)" % (self.quoteId(table)) + indexes = self._fetchAll(sql) + if indexes is None: + return [] + + for i, idx in enumerate(indexes): + # sqlite has changed the number of columns returned by index_list since 3.8.9 + # I am not using self.getInfo() here because this behaviour + # can be changed back without notice as done for index_info, see: + # http://repo.or.cz/sqlite.git/commit/53555d6da78e52a430b1884b5971fef33e9ccca4 + if len(idx) == 3: + num, name, unique = idx + if len(idx) == 5: + num, name, unique, createdby, partial = idx + sql = u"PRAGMA index_info(%s)" % (self.quoteId(name)) + + idx = [num, name, unique] + cols = [] + for seq, cid, cname in self._fetchAll(sql): + cols.append(cid) + idx.append(cols) + indexes[i] = idx + + return indexes + + def getTableConstraints(self, table): + return None + + def getTableTriggers(self, table): + + _, tablename = self.getSchemaTableName(table) + # Do not list rtree related triggers as we don't want them to be dropped + sql = u"SELECT name, sql FROM sqlite_master WHERE tbl_name = %s AND type = 'trigger'" % (self.quoteString(tablename)) + if self.isVectorTable(table): + sql += u" AND name NOT LIKE 'rtree_%%'" + elif self.isRasterTable(table): + sql += u" AND name NOT LIKE '%%_zoom_insert'" + sql += u" AND name NOT LIKE '%%_zoom_update'" + sql += u" AND name NOT LIKE '%%_tile_column_insert'" + sql += u" AND name NOT LIKE '%%_tile_column_update'" + sql += u" AND name NOT LIKE '%%_tile_row_insert'" + sql += u" AND name NOT LIKE '%%_tile_row_update'" + return self._fetchAll(sql) + + def deleteTableTrigger(self, trigger, table=None): + """ delete trigger """ + sql = u"DROP TRIGGER %s" % self.quoteId(trigger) + self._execute_and_commit(sql) + + def getTableExtent(self, table, geom, force=False): + """ find out table extent """ + _, tablename = self.getSchemaTableName(table) + + if self.isRasterTable(table): + + md = self.gdal_ds.GetMetadata('SUBDATASETS') + if md is None or len(md) == 0: + ds = self.gdal_ds + else: + subdataset_name = 'GPKG:%s:%s' % (self.gdal_ds.GetDescription(), tablename) + ds = gdal.Open(subdataset_name) + if ds is None: + return None + gt = ds.GetGeoTransform() + minx = gt[0] + maxx = gt[0] + gt[1] * ds.RasterYSize + maxy = gt[3] + miny = gt[3] + gt[5] * ds.RasterYSize + + return (minx, miny, maxx, maxy) + + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return None + ret = lyr.GetExtent(force=force, can_return_null=True) + if ret is None: + return None + minx, maxx, miny, maxy = ret + return (minx, miny, maxx, maxy) + + def getViewDefinition(self, view): + """ returns definition of the view """ + return None + + def getSpatialRefInfo(self, srid): + if srid in self.mapSridToName: + return self.mapSridToName[srid] + + sql = u"SELECT srs_name FROM gpkg_spatial_ref_sys WHERE srs_id = %s" % self.quoteString(srid) + res = self._fetchOne(sql) + if res is not None: + res = res[0] + self.mapSridToName[srid] = res + return res + + def isVectorTable(self, table): + + _, tablename = self.getSchemaTableName(table) + return self.gdal_ds.GetLayerByName(tablename) is not None + + def isRasterTable(self, table): + if self.has_raster and not self.isVectorTable(table): + _, tablename = self.getSchemaTableName(table) + md = self.gdal_ds.GetMetadata('SUBDATASETS') + if md is None or len(md) == 0: + sql = u"SELECT COUNT(*) FROM gpkg_contents WHERE data_type = 'tiles' AND table_name = %s" % self.quoteString(tablename) + ret = self._fetchOne(sql) + return ret is not None and ret[0] == 1 + else: + subdataset_name = 'GPKG:%s:%s' % (self.gdal_ds.GetDescription(), tablename) + for key in md: + if md[key] == subdataset_name: + return True + + return False + + def getOGRFieldTypeFromSQL(self, sql_type): + ogr_type = ogr.OFTString + ogr_subtype = ogr.OFSTNone + width = 0 + if not sql_type.startswith('TEXT ('): + pos = sql_type.find(' (') + if pos >= 0: + sql_type = sql_type[0:pos] + if sql_type == 'BOOLEAN': + ogr_type = ogr.OFTInteger + ogr_subtype = ogr.OFSTBoolean + elif sql_type in ('TINYINT', 'SMALLINT', 'MEDIUMINT'): + ogr_type = ogr.OFTInteger + elif sql_type == 'INTEGER': + ogr_type = ogr.OFTInteger64 + elif sql_type == 'FLOAT': + ogr_type = ogr.OFTReal + ogr_subtype = ogr.OFSTFloat32 + elif sql_type == 'DOUBLE': + ogr_type = ogr.OFTReal + elif sql_type == 'DATE': + ogr_type = ogr.OFTDate + elif sql_type == 'DATETIME': + ogr_type = ogr.OFTDateTime + elif sql_type.startswith('TEXT (') and sql_type.endswith(')'): + width = int(sql_type[len('TEXT ('):-1]) + return (ogr_type, ogr_subtype, width) + + def createOGRFieldDefnFromSQL(self, sql_fielddef): + f_split = sql_fielddef.split(' ') + quoted_name = f_split[0] + name = self.unquoteId(quoted_name) + sql_type = f_split[1].upper() + ogr_type, ogr_subtype, width = self.getOGRFieldTypeFromSQL(sql_type) + fld_defn = ogr.FieldDefn(name, ogr_type) + fld_defn.SetSubType(ogr_subtype) + fld_defn.SetWidth(width) + if len(f_split) >= 4 and f_split[2] == 'NOT' and f_split[3] == 'NULL': + fld_defn.SetNullable(False) + return fld_defn + + def createTable(self, table, field_defs, pkey): + """ create ordinary table + 'fields' is array containing field definitions + 'pkey' is the primary key name + """ + if len(field_defs) == 0: + return False + + options = [] + if pkey is not None and pkey != "": + options += ['FID=' + pkey] + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.CreateLayer(tablename, geom_type=ogr.wkbNone, options=options) + if lyr is None: + return False + for field_def in field_defs: + fld_defn = self.createOGRFieldDefnFromSQL(field_def) + if fld_defn.GetName() == pkey: + continue + if lyr.CreateField(fld_defn) != 0: + return False + + return True + + def deleteTable(self, table): + """ delete table from the database """ + if self.isRasterTable(table): + return False + + _, tablename = self.getSchemaTableName(table) + for i in range(self.gdal_ds.GetLayerCount()): + if self.gdal_ds.GetLayer(i).GetName() == tablename: + return self.gdal_ds.DeleteLayer(i) == 0 + return False + + def emptyTable(self, table): + """ delete all rows from table """ + if self.isRasterTable(table): + return False + + sql = u"DELETE FROM %s" % self.quoteId(table) + self._execute_and_commit(sql) + + def renameTable(self, table, new_table): + """ rename a table """ + + if self.isRasterTable(table): + return False + + _, tablename = self.getSchemaTableName(table) + if new_table == tablename: + return True + + if tablename.find('"') >= 0: + tablename = self.quotedId(tablename) + if new_table.find('"') >= 0: + new_table = self.quotedId(new_table) + + gdal.ErrorReset() + self.gdal_ds.ExecuteSQL('ALTER TABLE %s RENAME TO %s' % (tablename, new_table)) + return gdal.GetLastErrorMsg() == '' + + def moveTable(self, table, new_table, new_schema=None): + return self.renameTable(table, new_table) + + def runVacuum(self): + """ run vacuum on the db """ + self._execute_and_commit("VACUUM") + + def addTableColumn(self, table, field_def): + """ add a column to table """ + + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return False + fld_defn = self.createOGRFieldDefnFromSQL(field_def) + return lyr.CreateField(fld_defn) == 0 + + def deleteTableColumn(self, table, column): + """ delete column from a table """ + if self.isGeometryColumn(table, column): + return False + + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return False + idx = lyr.GetLayerDefn().GetFieldIndex(column) + if idx >= 0: + return lyr.DeleteField(idx) == 0 + return False + + def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not_null=None, new_default=None): + if self.isGeometryColumn(table, column): + return False + + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return False + if lyr.TestCapability(ogr.OLCAlterFieldDefn) == 0: + return False + idx = lyr.GetLayerDefn().GetFieldIndex(column) + if idx >= 0: + old_fielddefn = lyr.GetLayerDefn().GetFieldDefn(idx) + flag = 0 + if new_name is not None: + flag |= ogr.ALTER_NAME_FLAG + else: + new_name = column + if new_data_type is None: + ogr_type = old_fielddefn.GetType() + ogr_subtype = old_fielddefn.GetSubType() + width = old_fielddefn.GetWidth() + else: + flag |= ogr.ALTER_TYPE_FLAG + flag |= ogr.ALTER_WIDTH_PRECISION_FLAG + ogr_type, ogr_subtype, width = self.getOGRFieldTypeFromSQL(new_data_type) + new_fielddefn = ogr.FieldDefn(new_name, ogr_type) + new_fielddefn.SetSubType(ogr_subtype) + new_fielddefn.SetWidth(width) + if new_default is not None: + flag |= ogr.ALTER_DEFAULT_FLAG + if new_default == '': + new_fielddefn.SetDefault(None) + elif new_default == 'NULL' or ogr_type in (ogr.OFTInteger, ogr.OFTReal): + new_fielddefn.SetDefault(str(new_default)) + else: + new_fielddefn.SetDefault(self.quoteString(new_default)) + else: + new_fielddefn.SetDefault(old_fielddefn.GetDefault()) + if new_not_null is not None: + flag |= ogr.ALTER_NULLABLE_FLAG + new_fielddefn.SetNullable(not new_not_null) + else: + new_fielddefn.SetNullable(old_fielddefn.IsNullable()) + return lyr.AlterFieldDefn(idx, new_fielddefn, flag) == 0 + + return False + + def isGeometryColumn(self, table, column): + + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return False + return column == lyr.GetGeometryColumn() + + def addGeometryColumn(self, table, geom_column='geometry', geom_type='POINT', srid=-1, dim=2): + + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return False + ogr_type = ogr.wkbUnknown + if geom_type == 'POINT': + ogr_type = ogr.wkbPoint + elif geom_type == 'LINESTRING': + ogr_type = ogr.wkbLineString + elif geom_type == 'POLYGON': + ogr_type = ogr.wkbPolygon + elif geom_type == 'MULTIPOINT': + ogr_type = ogr.wkbMultiPoint + elif geom_type == 'MULTILINESTRING': + ogr_type = ogr.wkbMultiLineString + elif geom_type == 'MULTIPOLYGON': + ogr_type = ogr.wkbMultiPolygon + elif geom_type == 'GEOMETRYCOLLECTION': + ogr_type = ogr.wkbGeometryCollection + + if dim == 3: + ogr_type = ogr_type | ogr.wkb25DBit + elif dim == 4: + if hasattr(ogr, 'GT_HasZ'): + ogr_type = ogr.GT_SetZ(ogr_type) + else: + ogr_type = ogr_type | ogr.wkb25DBit + if hasattr(ogr, 'GT_HasM'): + ogr_type = ogr.GT_SetM(ogr_type) + + geom_field_defn = ogr.GeomFieldDefn(self.unquoteId(geom_column), ogr_type) + if srid > 0: + sr = osr.SpatialReference() + if sr.ImportFromEPSG(srid) == 0: + geom_field_defn.SetSpatialRef(sr) + + return lyr.CreateGeomField(geom_field_defn) == 0 + + def deleteGeometryColumn(self, table, geom_column): + return False # not supported + + def addTableUniqueConstraint(self, table, column): + """ add a unique constraint to a table """ + return False # constraints not supported + + def deleteTableConstraint(self, table, constraint): + """ delete constraint in a table """ + return False # constraints not supported + + def addTablePrimaryKey(self, table, column): + """ add a primery key (with one column) to a table """ + sql = u"ALTER TABLE %s ADD PRIMARY KEY (%s)" % (self.quoteId(table), self.quoteId(column)) + self._execute_and_commit(sql) + + def createTableIndex(self, table, name, column, unique=False): + """ create index on one column using default options """ + unique_str = u"UNIQUE" if unique else "" + sql = u"CREATE %s INDEX %s ON %s (%s)" % ( + unique_str, self.quoteId(name), self.quoteId(table), self.quoteId(column)) + self._execute_and_commit(sql) + + def deleteTableIndex(self, table, name): + schema, tablename = self.getSchemaTableName(table) + sql = u"DROP INDEX %s" % self.quoteId((schema, name)) + self._execute_and_commit(sql) + + def createSpatialIndex(self, table, geom_column): + if self.isRasterTable(table): + return False + _, tablename = self.getSchemaTableName(table) + sql = u"SELECT CreateSpatialIndex(%s, %s)" % ( + self.quoteId(tablename), self.quoteId(geom_column)) + res = self._fetchOne(sql) + return res is not None and res[0] == 1 + + def deleteSpatialIndex(self, table, geom_column): + if self.isRasterTable(table): + return False + _, tablename = self.getSchemaTableName(table) + sql = u"SELECT DisableSpatialIndex(%s, %s)" % ( + self.quoteId(tablename), self.quoteId(geom_column)) + res = self._fetchOne(sql) + return res is not None and res[0] == 1 + + def hasSpatialIndex(self, table, geom_column): + if self.isRasterTable(table) or geom_column is None: + return False + _, tablename = self.getSchemaTableName(table) + if self.gdal2: + # Only try this for GDAL >= 2 (but only available in >= 2.1.2) + sql = u"SELECT HasSpatialIndex(%s, %s)" % (self.quoteString(tablename), self.quoteString(geom_column)) + gdal.PushErrorHandler() + ret = self._fetchOne(sql) + gdal.PopErrorHandler() + else: + ret = None + if ret is None: + # might be the case for GDAL < 2.1.2 + sql = u"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name LIKE %s" % self.quoteString("%%rtree_" + tablename + "_%%") + ret = self._fetchOne(sql) + if ret is None: + return False + else: + return ret[0] >= 1 + + def execution_error_types(self): + return sqlite3.Error, sqlite3.ProgrammingError, sqlite3.Warning + + def connection_error_types(self): + return sqlite3.InterfaceError, sqlite3.OperationalError + + def getSqlDictionary(self): + from .sql_dictionary import getSqlDictionary + + sql_dict = getSqlDictionary() + + items = [] + for tbl in self.getTables(): + items.append(tbl[1]) # table name + + for fld in self.getTableFields(tbl[0]): + items.append(fld[1]) # field name + + sql_dict["identifier"] = items + return sql_dict + + def getQueryBuilderDictionary(self): + from .sql_dictionary import getQueryBuilderDictionary + + return getQueryBuilderDictionary() diff --git a/python/plugins/db_manager/db_plugins/gpkg/data_model.py b/python/plugins/db_manager/db_plugins/gpkg/data_model.py new file mode 100644 index 000000000000..f5f5af06e31a --- /dev/null +++ b/python/plugins/db_manager/db_plugins/gpkg/data_model.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- + +""" +/*************************************************************************** +Name : DB Manager +Description : Database manager plugin for QGIS +Date : May 23, 2011 +copyright : (C) 2011 by Giuseppe Sucameli +email : brush.tyler@gmail.com + + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +""" + +from ..data_model import TableDataModel, SqlResultModel + + +class GPKGTableDataModel(TableDataModel): + + def __init__(self, table, parent=None): + TableDataModel.__init__(self, table, parent) + + #fields_txt = u", ".join(self.fields) + #table_txt = self.db.quoteId((self.table.schemaName(), self.table.name)) + + # run query and get results + #sql = u"SELECT %s FROM %s" % (fields_txt, table_txt) + #self.resdata = self.db._fetchAll(sql, include_fid_and_geometry = True) + + self.resdata = self.db._fetchAllFromLayer(table) + + self.fetchedFrom = 0 + self.fetchedCount = len(self.resdata) + + def _sanitizeTableField(self, field): + return self.db.quoteId(field.name) + + def rowCount(self, index=None): + return self.fetchedCount + + +class GPKGSqlResultModel(SqlResultModel): + pass diff --git a/python/plugins/db_manager/db_plugins/gpkg/icons/gpkg_icon.png b/python/plugins/db_manager/db_plugins/gpkg/icons/gpkg_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..17bf308b4c27de7f02776f45b3f717bc1fa68afa GIT binary patch literal 23317 zcmX_o18^lx8*Z|(ZQHhOZEV}Nwb91O#OsV-cvO-bEdj`x_kQ7^FBQh zzvU(1ps}HWfPmnnBt?~gfPev)z(A1TfRm0>sTtq|>MSg!0txu}K$?UD{zExPYB~b} zB^La50MFIm4g+ptxrk}FDBGL4xEnf|0=c`p(_7kEI~yB1n9|!jnP*({Vgm|c{#QuF z(#6IUNJ2`P(9+o6j?l%z)Yg=ck)HWlIXCzJl@W4vv9NanQnEKPb#ft8_A>S|buhFu zwboawg9MbJ{I4BRQ)go*O9vNAdpjTt7Z(R^1_r19m8W<9|K;f&Y#3PY&IbW?l>VzD zV(;MTWNB{U0wf|rDCFYeWNGC3UjuZ?7JzOG*;rbe68_(|jGaskT`b*9jqPo1?d_cZ z8wG=nrLn1IM617GzxQ5_ROwd+EfKg2j*lfj0By@NejotulN*d4WBkG3LeOFpH%>fHvKs%vSakt(Wx-OkC!#?8x5A?5cD2ESj?{Ax}^ z=qM6h2hdao-~q>@^~b211!pyL79G}&>+IZFL?ZUA>8#jQ;YSTx~AHLnDemyrEv1Yn;#Q$dOh`1Xu1I&h3EuFP3o7!nyy#_1_*5;>7tF8@^VC0Zft$<)-`85}|?UBm%$g3^3?zBU03u3N^0n(AHG z#F@u#fo96j{OT81x&;$Z^k}N3Gm0zs7aqBD|KQ-^qK}l-T5^-Bs@hs*vOZuC-u&6V zLw|;^XX53ffGt3W=red#D8g~c@Qz&o1mixJHAzD;N6#BH(p9>m0tGju(#t4hJ#cc^^MJ z4jJ?>DKvFK&A%h}>DdX}e<`5!QxOAZiyI&biENy~Ej#b_heZ5EL>fX$GR9nAna5;| zvRob+SsqzWvF(4j4}nvKB7sQ2W5dl+)tP z%~PvlCq1$(x7JBvd`hCcGCXOLs>WJoj+dXJnuCL&?XdtPqE+(oa7B^Uv-FFY*kyJjFS`OePAa`I{+ zIt&o1llp{=c*&LLs(j>HYkHdv)zMDRWoLj3bMOswh*j5kNUvzgN7n4hDo4WxHXfC^ zg%&gV&E=7KFa$mG=%Lqmihw2a8ZL{5-0>>lGluE2m{`Tb;`EspuJ1v5thu)RVW)DyikmQ?B$JUx{RrHap6LN~E zAv42JT|69G3Dfa|IThb|lhwIPV%;{>40P){ntJOMrc$#;K<6ftiz#FP^`L;I*)}5K zh0xNKu&t{VpPY?5RgL$=xrP7lvk6$$nrNP6ae4gyzCNL!pI|1tk#2m;S`9Ex*zko-?JSwW&`0AozTlATt&DT0~8g7rz? z$dlKu$l>KVO2Fr`p2K*yiCiHHm@@>Rm2%?ZvtFv^OqN$(v}#7=^wI*@XOaG`VF`3mY$w=bSQ=DhVfY4*(Ye@9$z8XGuHp0x&@nfA}=S+=RRPXS8x z8q!#Az7dSL8hr+OK2TTj(`pA7vo3p)k18)mz25#F=0VW)Q2g7zLTb4d4nEy|l?>zj zu+goxbBHf?XN+j~2Z6s>Z|1>k)8}WSPm_d#A6#39x zqJtj9e=0m}%@eF<$^Et?%Z>Y3i*s+4{>iU+pvH8&fWv7oP2_ZuJcT2tHH|taehZEN z`5zBe&V>Y|+|(&R z#w9Zs3GrD!GQJQ!w_04LvrMV5*!L)?$6a^8864GQ3~#$gYQbv5xm8C{q$dVBH~D$?qTpb&4(*E7CS(u!VBmjIo;Mb zgZ^H2nu;fKT?U_&mmAD^ob8nG0O2*jPWu1Qd~0=tl1*?hUrE#PwYvzbewFHR=tZaT z9kC@k)T4kk=)VJnEledG;he7X=V;e(LxklQtZIEAY+a?C&ea9veCwdp=OiGO%AIBg zB09)s$5V%8bTtQ@B-*K@K95c$B|%_Z-MxQau4{)#RrHmv#K)zEOp(k=LVN9rD5~H_ z{z0~W5~^B|gtf>S{KMxKSq@Jw?Rv3_J#kIEd{YX^6RnY80vJ>__enFD>VFn`;7N+9-wj6I{HsqLIJ&&6hums##fmHd^*uko( zD({)T&SBo1->9>FznppXz{+Ag@&~R8Y%#S0#v;tBdtP0}b>KKo&AMcp#SBNTktfYa zxU4kLj9Ysit_6t;j5T6dK!Y7-!vMQho*SkAH zt~zAOyPn6xc5VSjTuQQZ*fLipXDx;PXImEA&!x$f0MFa;%F&@|u@Un*l5lQ3nLNG^ zEsDZ<>wuCi9lNATv^A^tHOtFH6Vz-V!dZIuZki^hh`SddV@W|K^v^0gClAT_9 z^v$=8ITS5YMioF?^lO_~8AZ&o`E%VGEgXKx$({s(A%9DA&&P&+d zEm%)eJ&qZ{AJ6}amyBE|QdSvLAw6Rh#gDRov|V?fIJU#XKR+gc%HwRuDu+Fq#-iC& zr&qU(l*Ab%)j?8#Cx+6I;nRY{9ffX;Nh=UBup}RXl9=m0FuH|R2z}W=rddjvm=?#+ zwL?Tg`oq)GP;K6>Z<)Kt7_RJ3EA9c)zT1AC(71Dd{J{Z37c7B|z(DU*x2<|#BkC)M znZX^V8UX)&&PL>oiu+9cyU#>rRC3mEe(dvO=;rqAt2L9pGg<9>+mxbbN{A0Bn7Z-D-s*Yc^wInkx;N;{=sbG(9p?s&mI#p$5PJRvPnLNOVkN}O0gs<^N*$s{;%KLOf|_XQr%P87^EZVa`- zQ8qI3LPD8~m*;I-3%2X6$nFO{;MuKJar`52A|(h6&T- zCjxWq0w}?HBXB91p*VO$VW3r7WD}dur%{<~^#Z{kPX-c2gL(eZY7x|lcK+qV&e|u1 z52KG0ZzY2=tUo?rW!!pR4=8?b*1Ad^wBrWG8HIy=Uc&cgM>Q+x{Deb@Q* z*jHpy#B)Z4`Qy`?B;d0}zWfa*et+{>vp~rj$l|w0;KVB67|3aVuhqFOko~8xteLL0 zbU5?jdIdIK=slh9iv5b<`|&@2Dz*EjtA0Yh{sI=MRJaw_*T>kD>`{{@M_ox_B%P^r zQz34H&~V{u>s?+->vR7cEdRB}@^!shN4H%19~%1)4t{?Fvy}^0UWWxS6O+P*j`7$T zg03Fjdd-P{(H9<8ef|iY_aDaH>=G>7b6WdtC$DXLzyI80C8J5@27vl`rKfzs#w{Ds9nzj7@z>R zs(Q+Xk2SSCHJndj!3xs8#}U0go5h7ZRrI3fbgmCQfkRU~S`J3r`85j^=2gAxsPo;F z5JIVoqqG$Pp4)XtKA!u#hL(jo!joQWh3?Qy{yutQ#mXBxguC+Y78xtMm96Ul&){}n zTOT*|N`bSPWkrYiUp}=08$$23%fly5&U{5vL|C>jM9s}85^fnKjoCtbvSEvYth5wM zI_=F+t&HPdI4h908@k-2z3MHvA^A{iCj4@BxV&at^IKZyqd!O7QaPTswC@sl4?v~- zE0qA+phm^-JW}FDHBr_(D^+bQ7(Cu<-1`E?+-!lNCwoVc_iK+}O&kQ6T=-7*@5VeE znkQmZgba6dHS3=V{R^&_KWPvlGBKzLwB)1;WM2IUzl+U}V(>V8zk4y=XpULEF^bXu z?tC^m%ZCmSET5{QhA#Qj^_|$hPFk^^dhF_B)Kv)&oz!^tY>M`sMEM&{js{-VLpLYA zVKVtp9$l~NDu^jcNy`<>Z1|98GF55;F==5sI!<*lI9t$4R?HEW{mSTiE{dM;JybpH zwjKXpI8d}TFw$c;qBpX0_}fI2oQlnsXx1i*9p4eZ*MIx%>~N_A*RaIXR_B9bx%~9d zZPRngBNA7s>f)jL4a%qI(0=>t)7;MQ)s%VimujeV7(zwEbzoOR|I8MLUifVKZzG3# zdwVI<=ti9?@!^_MQgSk;lfDbjm$Ea7%%nDXZQtt&Sp~x@JB$u$G;mk>;TwdRRdTWt z)0m!vCko@a5f6t!tN_&w8hxe3Tfa*3J+qmZDn(Db9{j7Z@#!*GMr$@?J8v`?el1wg z=RDORnRHE&FqeqSr1nr6R54TI_%LE?o8=8Yo|fbK1_>2!+kt<&sZZE$s;^Q~a(y*| z`E7ee?di}hI!u4wSnT(PemVj_>^cL0M_dF8=5moCXU#~l9RJxNeE6MdwsHK;VsEj% z^upzdp#*W*#;ciO)=FR*u)J_v=koTzcz3hLNH#Aar`WA99_XuFsr48uxBA%OaYL(j zeGuS%8O8{~@`-`Md0xd@{n4;%ef%r*0y91#o$B<$;(G1E$`Nz17JseF zQ&%@SV3+Ziohr|D@*2(rbR1F`JAn51*j9e}J1$sXk%XSsk<-6&UDQ;Q z2`hpdUO#{m`m}KguJ>C-TS^i%9yA=sR6coP8f&adJ!{~angBf*yvyjMYR1pvvRVu+ zS`Fnfq+n^UNTTFdC%-^!&nFQ`M`4)nP2=B6%_%yL-Ec;rgW{QswDfFG8&2CUd=84o zGnd_;ukX{UD)ULdWU(C|h2lAp3KhC~(%I3VPSUg*|L=}v>+hEZ{X*;|@QYnG)Qkm* z40hYPGH@TiWYFNjg&M!{_o*kIrjhNpzU4^%G?cEvc}~klH4&X!0n%8ji^r zVUB}gBtszCe}iucsCxbS;`x8aFgd+xKs_!z>G?46Yhq)2zN4+LJ>jcv0g?ZqChE1H z4}Znan&JhUTUgXqC>d%YoBWnwmAH{;EbKi>A0bU@BlDFKn4UKo4Lh!OyswuVHrtx0jaMKFJyVJ9`e1D62z6wAr9>Qx`{~}<=1;|0jnneRf;ZDX zuRZ!Wq@eRjo)3vPoW`R5CQ{^FbFyjL!BeVRFe<3YgN2~5UU&(l@#&cXQVlrnm;*x= z^``*TmUj0T(>J7a{t_-=Ea6p}v!Q3_ra=EC$g0MYR49~%U5XC90DkSrR3^L+A$M*R zQWIv7qlRDg=AfKMuebTeP)4NDfBZ$`j_uURYMXMB@+ zp$0c<^@I-gav|;KtCPEOT!hLJYvpg+`~6~Qtp1uy4BxU)gWj*d8T>U8R$gWr#01zw zVp`HhO)I?op^uBB7gG=idnemRFGm-UuIoyWeZd_1gL>9J=9`(MY5FNue2lNL;<)r2 z6KZyZeJajxrmh~AJIz1`-3iyfP8X@^DnG6tex-}i=4ui^WPAL4$SklpzlU0#Ja}^D zNqh%3{p1yny4iVA`neKvw@e)r3UygzF9FK8Ng>@fy^tu$^K(rhoXlJW59Djvk+@nbe#_de#1sn!#cadM#NW@LccS ztOpKlcOHDdWsp))K=m8#S*R-v$JBqYz+vpz1%GSQC%< z2|^fxNgVQu`-;;F6vy*S5ISc98-`vB<{cENoPDuGRv_YDEaC8+K!Sj|u z+tk|Y0!5wF=q8$OE0c)%dg#sUQ<}@gp&{cx&U2}TozHv3I`kN-)vv>0k$6E=CplUd z-djA)$K5#7_K$xDJqngaPoE4iBDe*^7`p-rlN$X1ju3A4r31-qAz)sFNkUp7HGn@c zIQMSZhX+;e*WKVe8N?J%H@fWHIcS8Ar$VD}W;bq;gc-euk20Otf2-MVPQS7!7DF3jQ z10xEP!Vp~pHUF9cvK7`{XxkaBz0OKee9^OQ7n}IdA2g?{T(LY`s{%1~BPe1gxOi?a zC_f^I6wT^CgCr;9bMFF>e zsT>olPk|HonaMgFgFoFoF8J0YdAimnrx7;B{ID(+apsBeizfu}Ar#S<*vkOc0u?Y* zqv*oC;5H!N2#_*^BrOMZq(y)1&YxP(w(DH8ZZcT;yFYAIQ@f%wlSpCQb$sdB6?Uzg zC0<3WA@O4~q%(qFx<5m;&FOP%8xueq;-78r*A&l<+(R*975d21xV{FzX}_Go;A_UQ zNMb772om#R_Cu#Yi9orqs35+36k6O=IG4c3DsbSqKkc+NX0F+shy(CjVKvA@UKJr7 zs}c7wDkH!g*?@$@pM}FQASYj2e&s2bKgV1A=_|>?Q`3$aXjD zKC``Y*wPrx>^iT3pXFDZuio-pWxdGpHzX)CX*N3GxeFZcd){D|&manMpPfk5YO2CW zLFYf=Z$aF*HQ-|m4IqP!dNjdgfwgM~LUwKsbCp|h<8tjbpP%@AlyG_c33goLB5^1M zAMYtryW5FM@%_10`inOB0_Q;ds zUM_ZF)F#(me!oOM+(&GfcVmSk>Zh;n?^=Z^RLRIo;^WeFH?*q)Bm%PlQxuBmI^1I< zBnuaSXjF>053|c)@T=)ads)a1{I393H4nnO3wTdvAQe#~chrO-8Bc?qaXB%3=4~X} z7?jx`*i)&tuDgn3+-g$ZLVtwIZG#;B-+Q-rE6dQ+Tu-3g-*5K&sWqr5^qj_&X!uwi z>clmw*26jMAx9U@aYm8T5GBj#_M>ni<32wrcPSjuxSumpN;_ssH$1 zaX%rA?*O{JX{JQ`!v_#@C1xVJy@iSwl@_Igy8*()7KQyeE`m5itJisQ z1|GZ`ipE-5wTqaiE?4bcM+1QE(IgU0fo#V}0w;h#7sd>f0+r`O3$f6H(+tYSGyGlC zt0jQh!Q&g#hstYq`sBg+*1C@HeK}INQtN#Ip6zp#`0m1H19+Q|6qydZMa#v?d=xxu z0cuKh?P%0^dRk=Gw;!9AbkqkUMHOqct{m>0C*hPD|Bnmcz|=t#3?V+{1qbDYm>{UC z(%72j^0DCfjtXbKY@2d0SG@Z~b69ffak;kAx|hIGsze7z-~7HbLo=5qtgyJzlR9YM zQ*EvwB^s+3SQGFAq+hDYIYCgzKpP?nUJYXR>pXckccHgVcP}J6@YIj;(&-~Em_YC@ z6n>a^$)8ZL(d!EYjY{i^5!{_Q!hpTni5?sj9UsT;CP_*#=*1tlW#*1Hk)HNy zz6m9(FxWybm5@&blHYo-e6>zDEo(_N$MciBy!nVp**>CReKf4^95Vi`5Qy2AcM`Nb>^)K8%`07T&A6 zWpI)8?o88eWe%^Y#INjL5#jK+UY7Fm<(g)`r*L3MB5p{cV<7E-vqj@uigd%pyW1KV zLyw(zI6okNVU2SAMr$-ZMzb0@hn1#-ip>84(q0r{A4s5em#9~)we7&GON$(B&cW#?M}d@`^e>BfviQW zWWkd0f=l^byBdgZM{mI&L4q2rDoO!s$lm_dP=^&F>?jHi@bip$9- zqtJ}i^U$dG5y^VF*ktF>A|NU6d|k#kBpout;Upn@yg}_PgY!#ovZc@Thu-wy$K638 zUiH0#=2b9wF^ECj|7^!zekBh<1PNpa^t$0|o(S&ivfdevLak`_)+j1Nk$c)%Z{X?5 zWO4$!(EFw|*?3G66^Fg-gV3ilJhn|CF@f9py2sG}yru9n*{3_hgP(>ZozeF?p?OA4 zVR!(PEM5f#B>B|=^o&x8{I7=?JWb@8}zI70r_l(mOfV><4+4%;n#$`vp4utUJe6q z>(C2W6!U=)P$ndyS$IUCF19F`uWd}6m#2%aM7SWS>8ROHTe11jpMC;ho_Poux?aza z;;`pYajbv&ED4M3(&n8QDB!P00BAydhWNAs+dLiizfZjvSiHXqJ-Xv1JM>j|?F&bJ zXZODqO-l$VNGyg7#6l|=Foys&4yfCa;o(aXy(&!x$l17ndulK>Q8ovD!{wzkhUG5^ z{@Bgd;MlBVF@pZsAY4K%2ixqT5e*XV;;X8@2)nlUVF!--X$0&4`*r>0dIF~8X3X>o z+}VCR?rv@#B1y^#8>UXiHYRGOb$c<5!xr8*f;aIGnIR)8)20SBNee{alsYAMhY1hq z=}UPKGfP~!q}}5n@y6K6Un;?4FR&tw-O?t@)(zvI(UY|&!04Qkz9prt1>KR`%W0rk?U4~7Oe%*&&O8ZtdC-%npEXps}P zt2+GhSUMg2A{}a)tGup1zX8GSgYr1^ZR+adPWtW}=m^ z|I_f*DVYF!No>_oT+&*kgk2k?2rd4#8f@k;Ass?-9{iK~OK{(}!i|c)SbRGN*!HARjJ!MeaT2cYZy_+`EuS z5)%{hC8OuTkROP)%ydB=Cq7sYC$#Tx_SI*zf$UXIbCzr#@D=qsmd?4<5c)Kd@pbK= zyzW12HfwcZ_0Txw<@Kj0J!`GD3X>llIigWWU41}I$R=`)n5B>f>*;bEAi>`5gENY% zufA+P9jpeR#6^8DdH2*FcOo7SGU0A%TqT>_v|j=R{LDOR*T@>OUZ_&~7tKpdSsO~K zBV%n}Hgr!)I!i7=I`k#MS>7_n-))ZQG z?3&e~Vawhc&sL+|blaU@qA^%bS4(po%MvH1@ufm}+=zM4sP-&3TU~95{f4)dJl>37 z_f!7B`9TfRI)d)bJ zLCLmu2v^?HqT^xcqH1ZA76PAc+}Kr^7_5qY`t z$YcS+&UV+*ZZ;ArWNzEf@jqf94dO?DwEpmwC(Vj|pUrGsy3R-C$@6Qg?eZ^vtwzuQ zbN!!8+6IC*L?Lvv+V>_|E&-pl@XX0ulUDenVnEJ(*cD|>5ox0+UHsqOhsa3?rPEi8 zlKm$9OczW~B_v;8wyT=Na%I|Np;VXfHb*5{0HVV(!s{$$Zakzy~hEJ$5}zI zVVLCI#9o{7JLI!4yu>`#=md9acviZ}aE)3{GIQc1DP~5s;w&Tq0Q4Wa@)Y>01CNs5 z#aOSMFQ=(=15iM)qw?MpswR&QT8%s6vl9@N5`4}J>n6K>nH6?exGbdY)wGZw@Y@0b zx#<#RA^0wD7gOyr3bVN%5yk%B(B!fp2Clu{`U5!n!eZfdNhvA45CoY6{h=pw<*FXW zC3;Li4M@ehuml45lAlmR)kYrobgzeDg6ForcTu;Sq{gVk6Z~Q-GUU`1jRkz910$u0 zjw+}L#V@m<4}L%n94g_J)gTure^-K{g5{p%}&PT7xlnhfN z_3oOxp=hoCNEP%8{?AtUNCTOSszmpt}_Im@Y)Y|Cf5WZmC`u^V`#kjOY8AvZQR~52wW} zeeZ2|?QKM_We+#>Eq?C-oX0PPF1b}JO6kqmBqPz(}86^ zQu0NHBhG9K;i@U4-WmT&qNV(S^JFe(QHQnW2xIv|#=)3~{79_}u5H&V4;w#Swu3!2 z*2nAlVsY&(wO~@P?kLd)U;;UF8Wl`0 zhg@KA+u)0qAXZ$^4*ExwZ0J7IaQQ@J;uuD0=6 zhr<(!=>aL$G_E%`m46es&?|Z_UeRR1BNqkv`N#$G;>oV4YC|u%YMf8eLw@3nd7m3%yClrDUS!#r=~R27O7Rtt7Ry8lMtd5sg-e z9F_vom`E!QYkJ3fnG1iMd~$*>N_W(34*Se^iU61g|JM5cBZn?lr9nPHU4Fk+Nq*-q zO=JyPv&Z)IhAL9f6c;{8Og@}=t{6_RHx|Wq#ePc5RI!{mp{tx&x^uBl9 z=GLgj5Eg<6UqF-+g3ukh!jB*u(>FTK{P4VC{I(zUV7WlfE!?O0!}f9oeZvp#t`9Xv z#Ou-XYlk6Nvj)7G%j%iF(IpN$bRRyfzG!jc5N5{Y9L*Sutq>t`nlJTyy+#6J{x5Zv z5-Vn7wANgi+UE6piKs+y+YJLTkI?YZii6M1xe%pPLaO6a8>fnh21s51p7CjKaJJ~h zri+gdvRV~=C=$hEzCz1+*s%0?MQLeixae7BU&ukYRKg$Ai`_JLLsLj11|oy|L;gx_ zj!-C+cCnJgj}N4!j;o%s0H_kse_$s$&`RMYoH~KFF&F~8HXDqv@v#;dZ@*Pn)s9I@ zL8s{nmK3UqKXsryI>DQ&?kAj6E!0I{vN7V=#p66cX1?rk6CD~gCjIxP z*|yYFer>zT=YA7#h*;qDUT?9y-i^qlvY4}ujXf>S!vv?kH%OtkS|fM%Rfn4!jNH-y@W&(@fmRL3p4%!Up7ETx%L~+-VD$~}#ftKR#!hhi38wD&MMWjKG(%u@J@i_}uwivvh zIx7@xwr@Q}-I$o26VtI0XU~hhiM0kU4@a$Fp#c#DxPzJ=awd!4rzmyt$SGj9CBHn5 z{8C*}OhP%K%F1t7ygVM!R@?bq!1THPHvED!)lQ3DkmrhT$;p)O_@t#J2l*!d2eiK)bT`f-{yj>Vs92wO=u}J{C3#@mP}%DpkhfGTXnoy5NcP>GZwc~ z!hX-QtgLjgI;S=xlhM@hmBwG}NNSx@>eD7iJS1!@Yy`Td8t0i`=tfKRQc zkSuY0C=`h6A(eoMcrYN)RM%5{vcA)O*!00*a+NS6qUZc}#HZO}2aTbRyRzSV#{u*) zHWTzC8^+}>OlhdsGcz&IfN^{7i&4KfV{g@Y1Di~bCbsD(B%M$+jIja$nO*?7xGh6- zdqXOjpU(_=O>SrUg@gOb^;ZD33ANB-wCQz>v6YcZ^_4H4O7(K) zI?0r(bM;RgkdR_>7|aZI45?Hm`=v%@_bY^Th4jnqo-#+BMV|<#ZL-jY+jZvf{t!wU z#|`ZKJTcGGIwCe-h3RjGR}1#eZ?4W;{?(w;qIK%XSEuW)%Fl0-KXR>UkDbpzt^1VR znrA^Vw)e9#5YaJ0G|CzpgA+G&`)PJp8qMzndS4z)3_UH70VOwSf2DFTn}|_e^Gd1f zmjwY%NoY}@zek;cx*?Xi{)=SOik{c2IB}Y}&uHVge1V7%Jx^8M0Z^p=&>8$_r)C%S zw16)ofanu;<+x~d>)GY=`2Ntz^CR%u)ki^=C2uzT_n_?{M(Fe@x}{)|v|fwVX*X%l z{3oz(K!if+^8Lhq+w0J&+xx>&=b2i^kr(v9;R8TJCS@5DUFPQypb^?XQ~!bK4g2{> zdqJQ{Winp=H4nGlnn~*NdZ^U|hYb=<8>TW^1yiBTc+ouJfU>=;-nJF&zcbUeczm#E z2vYVqWRKPC_NHXlcBr!L<>)rrC*WdX{g0t1;p2v2y)>90JsfydK?|AJg|71s@zH{y zv#Ol3@^z0yuj}Sl_s`{4DFrB)u|iRff22<17-Xfrt~`%-B#77T4!vgRL2YWt*4eQ> zLKkGreCc8Vf_U20K-~A1@%vwgv!ynmSmd>ns#@<=E%>43+rJ$%HMKSqLN(?xWnt11 zm&yUQ%hK8YF5vFE&h$Jj;4`OEa%}ha6D1E@?ih1LG6SJP1wx6;Kp$soNZVeR_?_gr zg1E2%lCqe+z)<6ay!q5l&qztIVA|G5eU<8Hf*^GA87LsnKAGAT;9`9Fa?W?knWu2Y ztgRI-n`38tfK1DK^GKAmPR!7+xT6b7Hkq_z;b|m5uQeKdk~5kgYX3(CIGwW&!g>W< zlsjDsTB=|K=v){Q)15fe2bcFnk5HL0b-MpwbVb`mx-*v3JtlqEp1cxEz45k04a2T0 zCahNoB9T9+UQSMnz*n~OH0D@L{VEuJRFz+`4rhALvK>Dnpmu9mmi>u-K@McGNMb~17 zKlCJrU}%hj15WC3z%l{9H%~*>;i4!|aPQ8QfSso|HVWP8D`d~7b{DIYXxV6vRHxwk z?ZyB8OkH5MA{i-)iTzn!Q8n@sd1l+2tpxsh>JlsE;qhyQ$>a9UhDv=+d(Y6kEzG#R z+4ymmpHwTKz!#sz2}m{jwbEX@20DS6jX*;70aR9M$%vZ*nhhs!qI4?-3F zzi$t`l+2=Hf$8hKq?oM7q|14bq-&BbGpJL!PQC(4)D#4K2FgukJ04l}yswdXuXpcP zMhJ37>P-_pUibDejZF><#2T1@KCrle_&u3_V^bv|&Ti{&c$mDS@p?RvU9NXik$*`w zSZF>z)O+clJbS!-wakd%=tQ~pDP9CNdP)r8&` zrLp(;x~6PKB2=(=7Ez>aV%GgibkTB|4V#W_j%2A6GY|=h!{D;UoG#>yfT`@utN(jOksD=zF)N+-kO~vL(18Rf!#yUK(|N zG(bnH&9%_&-|tr^n+|;uK5u;$MDA(RJT)}dEAo5i6|uHTLfyYvWk70kGF?1A%~Jgt zTwoO)mTn&EZlk$$IQ%eoeD8!*&X1)Ma`WqCBq!L1RML139*X8BCax&ZUWIH13Q~d`6 zo$z|u0M+?%&FSQnUag~}%W4hi#rM`;a9SWSc?6Nt42^Wu+YAVY^T(m1jaEm#(9D$N zY^}pw4U+y&jfA(39HC@&d@g4au3Ty+(|#*<-5-x#b(MLg1dV1d77yJev%UU&qigT? zDv+O@0%hQAt!{U*yN5At2FC+1lDC7CbgGju;)$R#?Dl@^rh=p$eRtlGB+geJK)oVb+Vton zt{Fi|en16m9)LUj7RytJH+UM)^xOyHe=~zRgMu)o!LIsqFOp;ybFr01ZSIO-u&|CM z+w%#l_cjyUn%OtQ@OYCmK;W;_cezHwl#yYV74E=k1l#MUguJ^wcKci~OA#X4US96= zwbRmO_xYRO*W6A6O&5OX;z_JCDK2C;yJY)toF~U{{z~DX`JVwhYYb8xo0G(h9{YCTaa zlY->z-J&u@gUOib<27Epm82A^X)6KuKJ$@n{yc6RYM`zck2lKCsnF!0Szq$Qq4dYQzzYLXhW|neTVWjV zW0nnw$>wAo9oK+$!Nn|2R|@z5Iy~jsle05$#s6oI#*Wh;G^d+|!6eT9a#bD>VTa<_ zU+z$zPt@gG+AE0%vit#cfjIU7s_{cd#4d}%(`I+tfx}>Qc(tJKxU*w+4w7LyYfRUY zF_s9L+S|`BQy>hQ*ZV(u=p8Ww0M6y4OrN5$&`vMKbS=Ns>s4yt9N8; z(dGJ+lGDmzLN9re$KGxnSe zD>pxl&Tt$C%)Wk(q(kf3B`E6MB%@b(;T=_))XhxQc+LQAZ%XG9_t$U*iwZO;Q zg1zT!6t(etY|?Lgd@~j6adRK;a$vLZe%?C#qXY2WUti|-fkE?(X;R%8K5x`hzpyW< z$~vm{AL`AgVv}sO#q47DNKM#e!G?{Pa|wa(w6!7X(@7pUefSB4L+Jlv$^HBJCUG{~ z2IS#4gq!)^4x4#@J}K8*Vikt6j)ni*3aK0$w&%Nd6l=IG3|TCE-JH^J)DkN>X(b^a zYj`>p|Fye*Y`(90aFKgvk{qoaoMZ?Sv~(<*n5tqslJEO3f=+DOtBfpE#MG1OA;&9# z;2T40hLL1ou;<4Y8HHlFWnbPo&lC!g+zU^KgFjcC)k*O5Sv53ct@c&*x$+H(Oq6MK z{d7GKt(r5Z0)UuJ6=xyoUbuM2A*=}}kqUiWf+FWrMl}80F2kMVU^?Bx0ITcFMY&!S zH^P1sHhKU(kus3v%Di4kd${m};xLr&m%Qc_sa)#FxU~=!9)=OvPRq&+wkwnqmt4ydqWd>5MKLrSV~_hDoP2tWd6w}I+5 z*TVpSBlF522}Z(#7b^9a8$cZZ#dsivhyT?%qP+YH1UTGiKIQ{oW>dmm< zjDQWoaDxB#_80aZN`A4y3X{#PO}I7Og>kI5eOmiu6N(`Q7J{3lytU8eJW7#ZhY?9{!bfM84zXAt(Rqqr6mYI{XaA3%$$1WnP7gb|7>gi zB?GCFx&AShZ{Ba5>o(c>EiM~(@BPB#F$sX3E=oeODqV&gggNw+L9bbaxnA|ybaL(O zN$J)IC|PI~+5aTs_H<(TJhWffuxVs>USV9)vmTR!v-gi?0`=TdZmRQM*M%8E*~00K zDUut=9v%ik?N55|bwHomy%8tQ4v27)_2sktSuey^XBD%0FyuRZA^sS!+v}ni7ji~j zH($vno=5yWZ{>YgWr*qBHSW@`E$F?7r=5zX{ye18gupxgqL>UDk#^`0>L3rY?@aXX zjD}iiv^L?PFII3J#csN*@o#$QPEEIea6Jw|Dl{M2hmSzbeSJ$KUH#U9RCx@AlW#= zcMiki{GF=_rL$Tb8I%ox&NV&{r#AL76JmSO2;EwI{9QGQfP#%jG4-7bP|9+R^M2~= zEViFJVKtfqprw(D6#FK9KI7x97H2Pl368fEiwe#`Gs@gwqlWIyex|DA=f=JGX1thj z!+h;A&c#ZA)_&xI%?icYBGu=o!X4 z{~SydxShFxaz=GjzX^4Gdb9ZfX`}3@?UQAI6tRPi%1VTMtrQns#i}4g_^n550xtJa zfd06^LurQbw*U#Xx0%2%L2_r2MkR11IZEx#V!|o#9@}D3RtqmmTwcA4)qY7MSX<_d ziV`@{`HrsC5Ba}4(L~K0{=EADBsT--&Ec|nZMXa$kPuk!E&tX-fPW(t{&jvO0{}kW znHc85nHzseZrE@z>-%VJD&xyM--}CIoaZ_DC=~T88p`mgdz|yFAq3YR0yk|~eD1;E z%rfwgdicuWD90Ya_704Yz5Y`gia%}+qK^+S`qkRETnUe(ex{sT`z`Sn;~H>e4TNbO zR{CT506O_>dpmw{W)HkM@gMWG z6`}-KZ%Y78M>8$>{U_i^_5 zEDp>dop1o^e42#wG1n1!auJ`8IfJo6z81n~Ok|TQa^t91Kf!Ns z+gN$%k+;i<(Y(x>eWQau-H~x*q)&FhId#C*vAWOkpuN(JK?D-`exQ595JbEao+kR# z%66~uW@*u1QOBsrm*EDVVQ4DN!@8nnvBk%Fp~cOk?4go14iRBQt~%uH3KB^e%woj# zfRlxVFjyV@o>vvp@k)UjB40+~BbrD-2xBe0-icDZt1@!U5to@+D{Hq8_7=0w=|Fm!N^U4edj*?)ABCNIrxnUy#PrEt{u1Reo{tD6&RM&@I1IdL=Mv+^ zfmDCpL5`@J?JH@-_YWmk>5R8*{>ISDV(NMtR3(};R-9T=gg$Gvu&3SeTui;TwzjUZ z9AP(hI2T)T(6#ViSm|Ngm?+|LapBv?2$C-zon;39rj(;N>k90gHRiu2J^Sr{G8-N3 zPK&s&Qu0vipU>1vh7Y{kyLfrYpdprJ9}fLR*XAowgw+UzuM*1?QgmP8VSel6O<8PFs@Wdjc0O zhVWU9^ktr#+X_?`74xrM;T+j&q!bXG=$dTpd=2dJ-IX3`T58PKEM3CdF(7`qL0S6e zwHfqf9Ht4fy)j=2;q$Rhn~Sw%RN<$;28#-%(4*Vv^UcmKlk3xf>&td#y}A`Q3E|S- zi589i6V9OP?;7M3bThG)MqQs5wE109f`Y&AUNhpO52_xp`;uM64v&nO|KkwUMV||% zw|>t`KhDr7Pra&N%JN+7aOjDmx`U&d6Ob6r)SMH$ZEQK2a?HYF5PjTtswB6R;?v5;RZ&Qxr z9Ix+(T_)wa5Jrha^WDXFJ6+7|hG0URo(H*4g(DboM*(C`oC!N&~*NDDWLB?R876bbulVTB4`w7^s*(~w1eNPmF7}{yyx9cbAcExfy`hmW5q(a zETjcO5%z&Dd|fR)*@~3;lu@VQ&&}S|sl(<>70RxOCLdUQ3-lE!i46hz-16UIL3~X+!?M^kkWV1U;FPx8nW1k#WjI4^ym1?w?IMc+S-TR8dDH5XA@c-I z(p_VJQ@8%L2be-p%`%~^u5kZ%!C&_EZd||-_^uVqk2)};c~8k_+tADSTVjZgf4{;X zX?_-olJRe27Zm)dqx*zk1S={^i7d1p3?Rc08eEGyS$ z`ePv)8@|m7=9@kf9P0+FfR#J{T;u#|m+uhQt!_!ESE6Cov%JYk!cgf6n*b#9jqx6*-{l)3UrC0D= zH#2Es5_O6J(&PTC2?mV4Y0cvuB`Kj@;@#0O_gf*)+|J#f2-}V1z4$0xSYkc*j0!1% z`l6(KNVDoqCO4r6KSt6bNBu+p+DBYdXKy*|YVC@R4C~ddvc$)ammB+keO_U&Mh=+AVPn)!;Bferl_-r;ag zT*}PIj1dT40+S}Khwz?%7#a+Y%t@VVHy*WI1A2XZ2YXeF(UiG#{;Xreu&x(apP2Hz zy;s!;A0-AaKxlOPJAqxB<;&{wGgwPs&#Dy{3emn zM#{-$tnQF2>^z`js7>ov528N}yXtc~SzzGsV`ndX_4UM1!qZqmAIMvWQm@q1ec`2| zhsI5QjJgxlz@mjdcD!*(fXL{ZqJn>mq3iwr-Fd)P5E*l92sgo%SFYU|^X7{40igoo zG>N^S%`1<11&5@_g#5dtn8ac&3X9(C|FHX9YII>SlC4@3Y6WUV(xVUye=cZko>IUQ z`0IkE8k?I7tb&|ZI2=Wm#avt>6Ca5toi5!>Z;{R9^ zmm1VkES}@GpPsR2lt75l%Ld#pQc*L*B1VnAa<#Leq?&LK3dWR!jbuG9`KzaCo3Pbs zr1F8bWK`k^F|k0IB%fp2v9>E$b&U!FD_-y@-1hOnxxKR>QNzRBLW}m_axdDk%aei_ zffejU$M{(%Lp%^l!gjH@4&M_+?iCt9Di2RL(Y4?@%Flh$ixb~2Veq#yWUQK_+s}%Z zUL3(W(BEIIQ^oh`wS`Ct;-8-cem~?KR|`h-$F*gt46Gsn*2I&*l^GQ*e$yUtZ!Djg zL2|olTpaOB!g(1?!`;nqKl`vMw5_1M0EG|dK7zTTlkw0p_wVA$<7_$9NRp@KvrVS7 z%ps}fi(k&c2T%!fUxa6BGh{`GIa%KpFo)q$zcvBE!;yW+%2Z`oi?T|%*<|iohI8kk zHC8ML#Mw#Is@D^oFNg2}$J=-Vae4Oco;I#L*R8Z1gW?*({&^ zHYMSinSU~+!x8b}gVnX)X!>~u|I)eO6@R%2=fQ{^iVT#5WI~SSTg^aC}_z;PomLwG^Hv7!;QX+ce5$ukN9}*k<~)M7mz#T8C3& zW7w9dc(@+*cHA7QQ>klUT?BGq7e=kt)n}ve48i>_tsmav<&rNSa`+z8lVn01mcldu z?>rmtjoDA+6iAz^JM{{6#8p;K{~K<$rqccp)GToSE=gkNC58WwqgK89y4Ah17H*w7 z+R1l?Y^0MOsbM!>=Opd7C$2HYwsc^3!1o}qD@{L}Oq#CX;>^PCS+QB2_0S-uMFj0t*lT_Cr&##W^k4LD& zv~NUgg6!e?HjJA){dh}yw~DVrbE{^$hY<2K0px1P=ch~SMLcBBB2IJe57`cv>%>Eo zjzXUf3~bihHYE1O(7EjATi>+muuomN;Eu@AxS2XAseNEO*!QZY=L?S2vp(eG zF0M^)hTbxHTRssG$j0+T6AUVykCAtA^FK`kxhnl2OT=01HO#|IB~fn(k{Nr`jo@MM zqpA99>w3oW?w9Ji(1(+GUl-g9`M2lmNB~LCMSwu43D`02AnsR(nytoX3zgMJb~n+( zP{jVe&L?Akkt%dsax{ruT3P0`Zy?ety8nRV+v`uNxWlp=QiB$X9Zw=&y>xS(2A>E34Y$dYy5C2w*y-tC!XEM7$J=C2?q@Cs-Zqk86?i`&|%0!ANEGXnd_cUY#8ru2VM^F;OSM9 zMV}r}ojSWCf3`k51+THkaDS?uS9r`$1ws}I!CU!tVoraW>o|$j1p^CBd zFI!v%{{F;zyV`?`Zx#`Y*C$tI`<8zlJcQAjbks6+3#`(&a;EnjqKr zGU0H?h3UBLow>lOw!##cp0680L7W<}YL)OmWSYJ1I{R;X6upWcmDg&+oP+0T--Jg* zXLb)JWw&mj+YJ}4z5~XgG>Zp}bB?bOcjRwh7c{i@!*|R=$na=xa||jnQ~741bW%Cn z$Ce2@qKC!^@(Xj>DiLiWXv~s8Aoe0 zl6NQ*m|NLLN4@{FjOZ&Q?)k(_suhgcw9;Yy&n0X_YCe;(*>Zbr8B$hbfi8HNR{D2w zTaW(%{$wDZy?VgxLl6kA0|TN>*W91Q@Lc%&7QP9sjh$i%f0m?YQb|tsixR}6mUqK- zH^x-(3ieQ~bn>lRArddyCdq3s_#?2VeV)H!T-F1EsG7AarIamK*^_ytS82X5X(anr zGKbMP8-kk=>K_VqkbjWJ3>zp9D~IJrqi$@m=%Nzq@rs}Hwo~a{X@b){S$N-|n(?dN zJEEE`kUc?ETRR5-;p_?}Dz}S5!;M9J^<8+#WSc*h%S0wDo=w!3CQ>?V6D>N%4ESW4 z3aBN{U14HKPPP3_fynqEuaDwr%0i>zVUY~NKt0y0@AsL)T{gg+EV=^%J~cz)UZ9e3$#FCsTuP`^ zKL!USyi77LS$<<_d3e5MR|*8y{{D19`dqsyrh{oKugZCiQcgzc3;U)*E}8Qnt)vr; z&<0sXh46>WO9^+*$PY9n0`41%RoA| z_tzb7sZr9<49~Y@&$&q!-(-9A_5R~Z0TCe!iBZ`Ee{f|)^I@qpc0P9<8?<@cYiqkR zoB|Y*xCO-n=D*l+ysSw%xCIKCIj+!LkP#olKKZhR!Tdnom@Vj=Bx=G}_>R-=p0H8q8n z{4AthajK~`Dy)+L7pye|bF!mo&8=_`9bEdBj?y!DtICr5r2D9Wmi1XVGq5*Khw6W4&ijKKr&p_inm~lZ-+n!DYTe8VH)nPwHY=F+%5;@Si9BRZ?p>o7HjDIjAHeoP>Zedl zkKftCco}$=5}EVAczSQHT1xVMF;7^Sw3#O%v$3@I!IP=7;e4kh4@)b3mEA1dY}9u+ zszJ0VA&?j6EUi!+fU4#O^YLCb(*%m6LD3YF{a;KwWb*U#^_oU}Ch1LK>+(xaZnbKG zyn?W2#cPt=;G9X-BxjK(&~~`Bvg}0M^y=uUt3R=sw7M5V@Bd64bvz`+xPkv2<=!h> zK&-}#L(K{o6sQX-YHSYS$a~9tX6m>%g5T&U{TzTiX;O1_b<;AKyzKbAi9o(MKuR}z zR`QY17^Oy*h>o5fzZt7g0ON^|NIjH+l7zV}l8DA!%()#q@gf#3#|5wak)P8Hpaj2)}P(pg&S(w*~yMwNZIs4sT$o}_@l5rtmx zhM;NWC~Z-i-a{NA?*;bva`l!2Pj4sR`orzZ0WkL*kEril3;_AU0@naQZc<~jf8TP; zB7Z=hw>%*P*b}&KRA+wiz$T>HTs;|uEP|L)fYdYdpDvtm4wy8~xA$B&X`eAXcO_?} zXc?q7(feywGnEkKlV?0=I9i@U!FKUoB%t+r=J!iJZ&$Iq&gajC4iS$;4%Yj9)S;M@5wW1rt1!F%8T zMj=IlJLD7Cy;rk)SW7>QOYGoTpxCz_>@Wqv4bPH4>5UA{Jx!b z%T`^GfE;!4OsksYNyaUXUUL$OOZ7?uOfi|)b-O1>xq}KyMx}qb_U-5ZZrrnOQtaIw zquHBF97(+iz@$#LM*#NS-KVER#7$2)5}F9)RTWAJi;f+=bF>X z%__tP2%yV(5|(IrpaY{DE&52ct(y$vvgnT|%3Z?Qa!>AVJT*Zg!MW+5owa{eV74Gv epoji7^D{Or$BRxOG2n-25L^KvU-`^5_ + + icons/gpkg_icon.png + + diff --git a/python/plugins/db_manager/db_plugins/gpkg/sql_dictionary.py b/python/plugins/db_manager/db_plugins/gpkg/sql_dictionary.py new file mode 100644 index 000000000000..a08980e73d31 --- /dev/null +++ b/python/plugins/db_manager/db_plugins/gpkg/sql_dictionary.py @@ -0,0 +1,28 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + sql_dictionary.py + --------------------- + Date : April 2012 + Copyright : (C) 2012 by Giuseppe Sucameli + Email : brush dot tyler at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + + +def getSqlDictionary(spatial=True): + from ..spatialite.sql_dictionary import getSqlDictionary + return getSqlDictionary(spatial) + + +def getQueryBuilderDictionary(): + from ..spatialite.sql_dictionary import getQueryBuilderDictionary + return getQueryBuilderDictionary() diff --git a/python/plugins/db_manager/db_tree.py b/python/plugins/db_manager/db_tree.py index 04b1dd802895..111e09db5ebe 100644 --- a/python/plugins/db_manager/db_tree.py +++ b/python/plugins/db_manager/db_tree.py @@ -137,7 +137,7 @@ def contextMenuEvent(self, ev): menu.addAction(self.tr("Re-connect"), self.reconnect) menu.addAction(self.tr("Remove"), self.delete) - elif not index.parent().isValid() and item.typeName() == "spatialite": + elif not index.parent().isValid() and item.typeName() in ("spatialite", "gpkg"): menu.addAction(self.tr("New Connection..."), self.newConnection) if not menu.isEmpty(): diff --git a/python/plugins/db_manager/dlg_sql_layer_window.py b/python/plugins/db_manager/dlg_sql_layer_window.py index 56dd81ce69be..5ac41b5c4e93 100644 --- a/python/plugins/db_manager/dlg_sql_layer_window.py +++ b/python/plugins/db_manager/dlg_sql_layer_window.py @@ -71,6 +71,8 @@ def __init__(self, iface, layer, parent=None): dbplugin = createDbPlugin('oracle', 'oracle') elif layer.dataProvider().name() == 'virtual': dbplugin = createDbPlugin('vlayers', 'virtual') + elif layer.dataProvider().name() == 'ogr': + dbplugin = createDbPlugin('gpkg', 'gpkg') if dbplugin: dbplugin.connectToUri(uri) db = dbplugin.db From d10e564b574c96529e1493841c2fd749b3b97cf1 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 14:28:11 +0200 Subject: [PATCH 335/897] [DBManager] Add tests for GPKG plugin --- tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_db_manager_gpkg.py | 393 +++++++++++++++++++++++ 2 files changed, 394 insertions(+) create mode 100644 tests/src/python/test_db_manager_gpkg.py diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index db31d0a6b2ca..b20cbb774d26 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -118,6 +118,7 @@ ADD_PYTHON_TEST(PyQgsWFSProviderGUI test_provider_wfs_gui.py) ADD_PYTHON_TEST(PyQgsConsole test_console.py) ADD_PYTHON_TEST(PyQgsLayerDependencies test_layer_dependencies.py) ADD_PYTHON_TEST(PyQgsVersionCompare test_versioncompare.py) +ADD_PYTHON_TEST(PyQgsDBManagerGpkg test_db_manager_gpkg.py) IF (NOT WIN32) ADD_PYTHON_TEST(PyQgsLogger test_qgslogger.py) diff --git a/tests/src/python/test_db_manager_gpkg.py b/tests/src/python/test_db_manager_gpkg.py new file mode 100644 index 000000000000..da86e4fc86d4 --- /dev/null +++ b/tests/src/python/test_db_manager_gpkg.py @@ -0,0 +1,393 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for the DBManager GPKG plugin + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Even Rouault' +__date__ = '2016-10-17' +__copyright__ = 'Copyright 2016, Even Rouault' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +import os +import tempfile +import shutil +from osgeo import gdal, ogr, osr + +from qgis.core import QgsDataSourceUri +from qgis.PyQt.QtCore import QCoreApplication, QSettings +from qgis.testing import start_app, unittest + +from plugins.db_manager.db_plugins import supportedDbTypes, createDbPlugin +from plugins.db_manager.db_plugins.plugin import TableField + + +def GDAL_COMPUTE_VERSION(maj, min, rev): + return ((maj) * 1000000 + (min) * 10000 + (rev) * 100) + + +class TestPyQgsDBManagerGpkg(unittest.TestCase): + + @classmethod + def setUpClass(cls): + """Run before all tests""" + + QCoreApplication.setOrganizationName("QGIS_Test") + QCoreApplication.setOrganizationDomain("TestPyQgsDBManagerGpkg.com") + QCoreApplication.setApplicationName("TestPyQgsDBManagerGpkg") + QSettings().clear() + start_app() + + cls.basetestpath = tempfile.mkdtemp() + + cls.test_gpkg = os.path.join(cls.basetestpath, 'TestPyQgsDBManagerGpkg.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(cls.test_gpkg) + lyr = ds.CreateLayer('testLayer', geom_type=ogr.wkbLineString, options=['SPATIAL_INDEX=NO']) + cls.supportsAlterFieldDefn = lyr.TestCapability(ogr.OLCAlterFieldDefn) == 1 + lyr.CreateField(ogr.FieldDefn('text_field', ogr.OFTString)) + f = ogr.Feature(lyr.GetLayerDefn()) + f['text_field'] = 'foo' + f.SetGeometry(ogr.CreateGeometryFromWkt('LINESTRING(1 2,3 4)')) + lyr.CreateFeature(f) + f = None + ds = None + + @classmethod + def tearDownClass(cls): + """Run after all tests""" + + QSettings().clear() + shutil.rmtree(cls.basetestpath, True) + + def testSupportedDbTypes(self): + self.assertIn('gpkg', supportedDbTypes()) + + def testCreateDbPlugin(self): + plugin = createDbPlugin('gpkg') + self.assertIsNotNone(plugin) + + def testConnect(self): + connection_name = 'testConnect' + plugin = createDbPlugin('gpkg') + + uri = QgsDataSourceUri() + uri.setDatabase(self.test_gpkg) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connections = plugin.connections() + self.assertEqual(len(connections), 1) + + connection = createDbPlugin('gpkg', connection_name + '_does_not_exist') + connection_succeeded = False + try: + connection.connect() + connection_succeeded = True + except: + pass + self.assertFalse(connection_succeeded, 'exception should have been raised') + + connection = connections[0] + connection.connect() + + connection.reconnect() + + connection.remove() + + self.assertEqual(len(plugin.connections()), 0) + + connection = createDbPlugin('gpkg', connection_name) + connection_succeeded = False + try: + connection.connect() + connection_succeeded = True + except: + pass + self.assertFalse(connection_succeeded, 'exception should have been raised') + + def testListLayer(self): + connection_name = 'testListLayer' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + uri.setDatabase(self.test_gpkg) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 1) + table = tables[0] + self.assertEqual(table.name, 'testLayer') + info = table.info() + expected_html = """

                                                                                                                                                                                    General info

                                                                                                                                                                                    Relation type: Table 
                                                                                                                                                                                    Rows: 

                                                                                                                                                                                    Fields

                                                                                                                                                                                    Name Type Null Default 
                                                                                                                                                                                    fid INTEGER  
                                                                                                                                                                                    geom LINESTRING  
                                                                                                                                                                                    text_field TEXT  
                                                                                                                                                                                    """ + self.assertEqual(info.toHtml(), expected_html, info.toHtml()) + + connection.remove() + + def testCreateRenameDeleteTable(self): + connection_name = 'testCreateRenameDeleteTable' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + + test_gpkg_new = os.path.join(self.basetestpath, 'testCreateRenameDeleteTable.gpkg') + shutil.copy(self.test_gpkg, test_gpkg_new) + + uri.setDatabase(test_gpkg_new) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 1) + table = tables[0] + self.assertTrue(table.rename('newName')) + self.assertEqual(table.name, 'newName') + + connection.reconnect() + + db = connection.database() + tables = db.tables() + self.assertEqual(len(tables), 1) + table = tables[0] + self.assertEqual(table.name, 'newName') + + fields = [] + geom = ['geometry', 'POINT', 4326, 3] + field1 = TableField(table) + field1.name = 'fid' + field1.dataType = 'INTEGER' + field1.notNull = True + field1.primaryKey = True + + field2 = TableField(table) + field2.name = 'str_field' + field2.dataType = 'TEXT' + field2.modifier = 20 + + fields = [field1, field2] + self.assertTrue(db.createVectorTable('newName2', fields, geom)) + + tables = db.tables() + self.assertEqual(len(tables), 2) + new_table = tables[1] + self.assertEqual(new_table.name, 'newName2') + fields = new_table.fields() + self.assertEqual(len(fields), 3) + self.assertFalse(new_table.hasSpatialIndex()) + + self.assertTrue(new_table.createSpatialIndex()) + self.assertTrue(new_table.hasSpatialIndex()) + + self.assertTrue(new_table.delete()) + + tables = db.tables() + self.assertEqual(len(tables), 1) + + connection.remove() + + def testCreateRenameDeleteFields(self): + + if not self.supportsAlterFieldDefn: + return + + connection_name = 'testCreateRenameDeleteFields' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + + test_gpkg_new = os.path.join(self.basetestpath, 'testCreateRenameDeleteFields.gpkg') + shutil.copy(self.test_gpkg, test_gpkg_new) + + uri.setDatabase(test_gpkg_new) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 1) + table = tables[0] + + field_before_count = len(table.fields()) + + field = TableField(table) + field.name = 'real_field' + field.dataType = 'DOUBLE' + self.assertTrue(table.addField(field)) + + self.assertEqual(len(table.fields()), field_before_count + 1) + + self.assertTrue(field.update('real_field2', new_type_str='TEXT (30)', new_not_null=True, new_default_str='foo')) + + field = table.fields()[field_before_count] + self.assertEqual(field.name, 'real_field2') + self.assertEqual(field.dataType, 'TEXT(30)') + self.assertEqual(field.notNull, 1) + self.assertEqual(field.default, "'foo'") + + self.assertTrue(table.deleteField(field)) + + self.assertEqual(len(table.fields()), field_before_count) + + connection.remove() + + def testTableDataModel(self): + connection_name = 'testTableDataModel' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + uri.setDatabase(self.test_gpkg) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 1) + table = tables[0] + self.assertEqual(table.name, 'testLayer') + model = table.tableDataModel(None) + self.assertEqual(model.rowCount(), 1) + self.assertEqual(model.getData(0, 0), 1) # fid + self.assertEqual(model.getData(0, 1), 'LINESTRING (1 2,3 4)') + self.assertEqual(model.getData(0, 2), 'foo') + + connection.remove() + + def testRaster(self): + + if int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 2): + return + + connection_name = 'testRaster' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + + test_gpkg_new = os.path.join(self.basetestpath, 'testRaster.gpkg') + shutil.copy(self.test_gpkg, test_gpkg_new) + mem_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) + mem_ds.SetGeoTransform([2, 0.01, 0, 49, 0, -0.01]) + sr = osr.SpatialReference() + sr.ImportFromEPSG(4326) + mem_ds.SetProjection(sr.ExportToWkt()) + mem_ds.GetRasterBand(1).Fill(255) + gdal.GetDriverByName('GPKG').CreateCopy(test_gpkg_new, mem_ds, options=['APPEND_SUBDATASET=YES', 'RASTER_TABLE=raster_table']) + mem_ds = None + + uri.setDatabase(test_gpkg_new) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 2) + table = None + for i in range(2): + if tables[i].name == 'raster_table': + table = tables[i] + break + self.assertIsNotNone(table) + info = table.info() + expected_html = """

                                                                                                                                                                                    General info

                                                                                                                                                                                    Relation type: Table 
                                                                                                                                                                                    Rows: Unknown (find out

                                                                                                                                                                                    GeoPackage

                                                                                                                                                                                    Column:  
                                                                                                                                                                                    Geometry: RASTER 
                                                                                                                                                                                    Spatial ref: WGS 84 geodetic (4326) 
                                                                                                                                                                                    Extent: 2.00000, 48.80000 - 2.20000, 49.00000 

                                                                                                                                                                                    Fields

                                                                                                                                                                                    Name Type Null Default 
                                                                                                                                                                                    id INTEGER  
                                                                                                                                                                                    zoom_level INTEGER  
                                                                                                                                                                                    tile_column INTEGER  
                                                                                                                                                                                    tile_row INTEGER  
                                                                                                                                                                                    tile_data BLOB  

                                                                                                                                                                                    Indexes

                                                                                                                                                                                    Name Column(s) 
                                                                                                                                                                                    sqlite_autoindex_raster_table_1 zoom_level
                                                                                                                                                                                    tile_column
                                                                                                                                                                                    tile_row 
                                                                                                                                                                                    """ + self.assertEqual(info.toHtml(), expected_html, info.toHtml()) + + connection.remove() + + def testTwoRaster(self): + + if int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 2): + return + + connection_name = 'testTwoRaster' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + + test_gpkg_new = os.path.join(self.basetestpath, 'testTwoRaster.gpkg') + shutil.copy(self.test_gpkg, test_gpkg_new) + mem_ds = gdal.GetDriverByName('MEM').Create('', 20, 20) + mem_ds.SetGeoTransform([2, 0.01, 0, 49, 0, -0.01]) + sr = osr.SpatialReference() + sr.ImportFromEPSG(4326) + mem_ds.SetProjection(sr.ExportToWkt()) + mem_ds.GetRasterBand(1).Fill(255) + for i in range(2): + gdal.GetDriverByName('GPKG').CreateCopy(test_gpkg_new, mem_ds, options=['APPEND_SUBDATASET=YES', 'RASTER_TABLE=raster_table%d' % (i + 1)]) + mem_ds = None + + uri.setDatabase(test_gpkg_new) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 3) + table = None + for i in range(2): + if tables[i].name.startswith('raster_table'): + table = tables[i] + info = table.info() + info.toHtml() + + connection.remove() + + def testNonSpatial(self): + + connection_name = 'testNonSpatial' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + + test_gpkg = os.path.join(self.basetestpath, 'testNonSpatial.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(test_gpkg) + lyr = ds.CreateLayer('testNonSpatial', geom_type=ogr.wkbNone) + lyr.CreateField(ogr.FieldDefn('text_field', ogr.OFTString)) + f = ogr.Feature(lyr.GetLayerDefn()) + f['text_field'] = 'foo' + lyr.CreateFeature(f) + f = None + ds = None + + uri.setDatabase(test_gpkg) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + self.assertEqual(len(tables), 1) + table = tables[0] + self.assertEqual(table.name, 'testNonSpatial') + info = table.info() + expected_html = """

                                                                                                                                                                                    General info

                                                                                                                                                                                    Relation type: Table 
                                                                                                                                                                                    Rows: 

                                                                                                                                                                                    Fields

                                                                                                                                                                                    Name Type Null Default 
                                                                                                                                                                                    fid INTEGER  
                                                                                                                                                                                    text_field TEXT  
                                                                                                                                                                                    """ + self.assertEqual(info.toHtml(), expected_html, info.toHtml()) + + connection.remove() + +if __name__ == '__main__': + unittest.main() From 2c1356cd1d60b22944c1b10f3e36739abb78b347 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 14:28:30 +0200 Subject: [PATCH 336/897] [DBManager] Remove geopackage support from spatialite plugin --- .../db_plugins/spatialite/connector.py | 74 +------------------ .../db_plugins/spatialite/info_model.py | 5 +- .../db_plugins/spatialite/plugin.py | 24 ++---- 3 files changed, 9 insertions(+), 94 deletions(-) diff --git a/python/plugins/db_manager/db_plugins/spatialite/connector.py b/python/plugins/db_manager/db_plugins/spatialite/connector.py index cefebda77e1d..7ab9820963e5 100644 --- a/python/plugins/db_manager/db_plugins/spatialite/connector.py +++ b/python/plugins/db_manager/db_plugins/spatialite/connector.py @@ -55,7 +55,6 @@ def __init__(self, uri): self._checkSpatial() self._checkRaster() - self._checkGeopackage() def _connectionInfo(self): return str(self.dbname) @@ -92,11 +91,6 @@ def _checkRaster(self): self.has_raster = self._checkRasterTables() return self.has_raster - def _checkGeopackage(self): - """ check if it's a geopackage db """ - self.is_gpkg = self._checkGeopackageTables() - return self.is_gpkg - def _checkGeometryColumnsTable(self): try: c = self._get_cursor() @@ -118,36 +112,6 @@ def _checkRasterTables(self): ret = c.fetchone() return ret and ret[0] - def _checkGeopackageTables(self): - try: - sql = u"SELECT HasGeoPackage()" - result = self._execute(None, sql).fetchone()[0] == 1 - except ConnectionError: - result = False - except Exception: - # SpatiaLite < 4.2 does not have HasGeoPackage() function - result = False - - if result: - try: - sql = u"SELECT CheckGeoPackageMetaData()" - result = self._execute(None, sql).fetchone()[0] == 1 - except ConnectionError: - result = False - else: - # Spatialite < 4.2 has no GeoPackage support, check for filename and GPKG layout - ver = list(map(int, self.getInfo()[0].split('.')[0:2])) - if ver[0] < 4 or (ver[0] == 4 and ver[1] < 2): - hasGpkgFileExt = self.dbname[-5:] == ".gpkg" or self.dbname[-11:] == ".geopackage" - - sql = u"SELECT count(*) = 3 FROM sqlite_master WHERE name IN ('gpkg_geometry_columns', 'gpkg_spatial_ref_sys', 'gpkg_contents')" - ret = self._execute(None, sql).fetchone() - hasGpkgLayout = ret and ret[0] - - result = hasGpkgFileExt and hasGpkgLayout - - return result - def getInfo(self): c = self._get_cursor() self._execute(c, u"SELECT sqlite_version()") @@ -159,7 +123,7 @@ def getSpatialInfo(self): - geos version - proj version """ - if not self.has_spatial and not self.is_gpkg: + if not self.has_spatial: return c = self._get_cursor() @@ -187,9 +151,6 @@ def hasTableColumnEditingSupport(self): def hasCreateSpatialViewSupport(self): return True - def isGpkg(self): - return self.is_gpkg - def fieldTypes(self): return [ "integer", "bigint", "smallint", # integers @@ -307,14 +268,6 @@ def getVectorTables(self, schema=None): WHERE m.type in ('table', 'view') ORDER BY m.name, g.f_geometry_column""" % cols - elif self.is_gpkg: - # get info from gpkg_geometry_columns table - dim = " 'XY' || CASE z WHEN 1 THEN 'Z' END || CASE m WHEN 1 THEN 'M' END AS coord_dimension " - sql = u"""SELECT m.name, m.type = 'view', g.table_name, g.column_name, g.geometry_type_name AS gtype, %s, g.srs_id - FROM sqlite_master AS m JOIN gpkg_geometry_columns AS g ON upper(m.name) = upper(g.table_name) - WHERE m.type in ('table', 'view') - ORDER BY m.name, g.column_name""" % dim - else: return [] @@ -340,8 +293,6 @@ def getRasterTables(self, schema=None): srid """ - if self.is_gpkg: - return [] # Not implemented if not self.has_geometry_columns: return [] if not self.has_raster: @@ -447,10 +398,7 @@ def getViewDefinition(self, view): return ret[0] if ret is not None else None def getSpatialRefInfo(self, srid): - if self.is_gpkg: - sql = u"SELECT srs_name FROM gpkg_spatial_ref_sys WHERE srs_id = %s" % self.quoteString(srid) - else: - sql = u"SELECT ref_sys_name FROM spatial_ref_sys WHERE srid = %s" % self.quoteString(srid) + sql = u"SELECT ref_sys_name FROM spatial_ref_sys WHERE srid = %s" % self.quoteString(srid) c = self._execute(None, sql) ret = c.fetchone() return ret[0] if ret is not None else None @@ -503,8 +451,6 @@ def deleteTable(self, table): """ delete table from the database """ if self.isRasterTable(table): return False - if self.is_gpkg: - return False # Not implemented c = self._get_cursor() sql = u"DROP TABLE %s" % self.quoteId(table) @@ -518,8 +464,6 @@ def emptyTable(self, table): """ delete all rows from table """ if self.isRasterTable(table): return False - if self.is_gpkg: - return False # Not implemented sql = u"DELETE FROM %s" % self.quoteId(table) self._execute_and_commit(sql) @@ -532,8 +476,6 @@ def renameTable(self, table, new_table): if self.isRasterTable(table): return False - if self.is_gpkg: - return False # Not implemented c = self._get_cursor() @@ -573,8 +515,6 @@ def renameView(self, view, new_name): return self.renameTable(view, new_name) def createSpatialView(self, view, query): - if self.is_gpkg: - return False # Not implemented self.createView(view, query) # get type info about the view @@ -654,8 +594,6 @@ def setColumnNull(self, table, column, is_null): return False # column editing not supported def isGeometryColumn(self, table, column): - if self.is_gpkg: - return False # Not implemented c = self._get_cursor() schema, tablename = self.getSchemaTableName(table) @@ -665,8 +603,6 @@ def isGeometryColumn(self, table, column): return c.fetchone()[0] == 't' def addGeometryColumn(self, table, geom_column='geometry', geom_type='POINT', srid=-1, dim=2): - if self.is_gpkg: - return False # Not implemented schema, tablename = self.getSchemaTableName(table) sql = u"SELECT AddGeometryColumn(%s, %s, %d, %s, %s)" % ( @@ -704,8 +640,6 @@ def deleteTableIndex(self, table, name): def createSpatialIndex(self, table, geom_column='geometry'): if self.isRasterTable(table): return False - if self.is_gpkg: - return False # Not implemented schema, tablename = self.getSchemaTableName(table) sql = u"SELECT CreateSpatialIndex(%s, %s)" % (self.quoteString(tablename), self.quoteString(geom_column)) @@ -714,8 +648,6 @@ def createSpatialIndex(self, table, geom_column='geometry'): def deleteSpatialIndex(self, table, geom_column='geometry'): if self.isRasterTable(table): return False - if self.is_gpkg: - return False # Not implemented schema, tablename = self.getSchemaTableName(table) try: @@ -729,8 +661,6 @@ def deleteSpatialIndex(self, table, geom_column='geometry'): self.deleteTable(idx_table_name) def hasSpatialIndex(self, table, geom_column='geometry'): - if self.is_gpkg: - return False # Not implemented if not self.has_geometry_columns or self.isRasterTable(table): return False c = self._get_cursor() diff --git a/python/plugins/db_manager/db_plugins/spatialite/info_model.py b/python/plugins/db_manager/db_plugins/spatialite/info_model.py index 7e0d10d511b0..81a0457a499b 100644 --- a/python/plugins/db_manager/db_plugins/spatialite/info_model.py +++ b/python/plugins/db_manager/db_plugins/spatialite/info_model.py @@ -58,10 +58,7 @@ def spatialInfo(self): ] ret.append(HtmlTable(tbl)) - if self.db.connector.is_gpkg: - pass - - elif not self.db.connector.has_geometry_columns: + if not self.db.connector.has_geometry_columns: ret.append(HtmlParagraph( QApplication.translate("DBManagerPlugin", " geometry_columns table doesn't exist!\n" "This table is essential for many GIS applications for enumeration of tables."))) diff --git a/python/plugins/db_manager/db_plugins/spatialite/plugin.py b/python/plugins/db_manager/db_plugins/spatialite/plugin.py index 40d7a73636dd..af80e93d58ce 100644 --- a/python/plugins/db_manager/db_plugins/spatialite/plugin.py +++ b/python/plugins/db_manager/db_plugins/spatialite/plugin.py @@ -52,7 +52,7 @@ def typeName(self): @classmethod def typeNameString(self): - return 'SpatiaLite/Geopackage' + return 'SpatiaLite' @classmethod def providerName(self): @@ -90,7 +90,7 @@ def addConnection(self, conn_name, uri): def addConnectionActionSlot(self, item, action, parent, index): QApplication.restoreOverrideCursor() try: - filename, selected_filter = QFileDialog.getOpenFileName(parent, "Choose Sqlite/Spatialite/Geopackage file") + filename, selected_filter = QFileDialog.getOpenFileName(parent, "Choose Sqlite/Spatialite file") if not filename: return finally: @@ -184,21 +184,13 @@ def ogrUri(self): return ogrUri def mimeUri(self): - if self.database().connector.isGpkg(): - # QGIS has no provider to load Geopackage vectors, let's use OGR - return u"vector:ogr:%s:%s" % (self.name, self.ogrUri()) return Table.mimeUri(self) def toMapLayer(self): from qgis.core import QgsVectorLayer - if self.database().connector.isGpkg(): - # QGIS has no provider to load Geopackage vectors, let's use OGR - provider = "ogr" - uri = self.ogrUri() - else: - provider = self.database().dbplugin().providerName() - uri = self.uri().uri() + provider = self.database().dbplugin().providerName() + uri = self.uri().uri() return QgsVectorLayer(uri, self.name, provider) @@ -283,12 +275,8 @@ def mimeUri(self): def toMapLayer(self): from qgis.core import QgsRasterLayer, QgsContrastEnhancement - if self.database().connector.isGpkg(): - # QGIS has no provider to load Geopackage rasters, let's use GDAL - uri = self.ogrUri() - else: - # QGIS has no provider to load Rasterlite rasters, let's use GDAL - uri = self.rasterliteGdalUri() + # QGIS has no provider to load Rasterlite rasters, let's use GDAL + uri = self.rasterliteGdalUri() rl = QgsRasterLayer(uri, self.name) if rl.isValid(): From d32a949bf825919c9a39b38b2b1fc32bce3b3973 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 19:02:59 +0200 Subject: [PATCH 337/897] Blacklist PyQgsDBManagerGpkg test The test consistently segfaults on Travis, but run fine locally, normally or under Valgrind. Trying to run it under Valgrind on Travis runners does not succeed: https://travis-ci.org/rouault/Quantum-GIS/builds/168674938 So blacklist for now --- ci/travis/linux/blacklist.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/ci/travis/linux/blacklist.txt b/ci/travis/linux/blacklist.txt index 5cf3ccbf362e..12851f4ec41b 100755 --- a/ci/travis/linux/blacklist.txt +++ b/ci/travis/linux/blacklist.txt @@ -5,3 +5,4 @@ qgis_composermapgridtest qgis_composerutils ProcessingGrass7AlgorithmsImageryTest ProcessingGrass7AlgorithmsRasterTest +PyQgsDBManagerGpkg From cea47427d0e645170d0f1688b88548ba57761bae Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 08:38:11 +1000 Subject: [PATCH 338/897] Optimise creation of spatial indexes Use constructor which takes an iterator instead of manually adding features, and don't request attributes for spatial index features --- .../algs/qgis/SelectByAttributeSum.py | 2 +- src/analysis/vector/qgsoverlayanalyzer.cpp | 47 ++++++------------- .../geometry_checker/utils/qgsfeaturepool.cpp | 6 +-- .../geometry_snapper/qgsgeometrysnapper.cpp | 6 +-- 4 files changed, 18 insertions(+), 43 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SelectByAttributeSum.py b/python/plugins/processing/algs/qgis/SelectByAttributeSum.py index 4a78e94b86f5..99262a1d47d4 100644 --- a/python/plugins/processing/algs/qgis/SelectByAttributeSum.py +++ b/python/plugins/processing/algs/qgis/SelectByAttributeSum.py @@ -73,7 +73,7 @@ def processAlgorithm(self, progress): geom = ft.geometry() attrSum = ft[fieldName] - idx = QgsSpatialIndex(layer.getFeatures()) + idx = QgsSpatialIndex(layer.getFeatures(QgsFeatureRequest.setSubsetOfAttributes([]))) req = QgsFeatureRequest() completed = False while not completed: diff --git a/src/analysis/vector/qgsoverlayanalyzer.cpp b/src/analysis/vector/qgsoverlayanalyzer.cpp index 87408580965d..5b42b135f672 100644 --- a/src/analysis/vector/qgsoverlayanalyzer.cpp +++ b/src/analysis/vector/qgsoverlayanalyzer.cpp @@ -54,31 +54,25 @@ bool QgsOverlayAnalyzer::intersection( QgsVectorLayer* layerA, QgsVectorLayer* l QgsVectorFileWriter vWriter( shapefileName, dpA->encoding(), fieldsA, outputType, crs ); QgsFeature currentFeature; - QgsSpatialIndex index; //take only selection if ( onlySelectedFeatures ) { - const QgsFeatureIds selectionB = layerB->selectedFeaturesIds(); - QgsFeatureIds::const_iterator it = selectionB.constBegin(); - for ( ; it != selectionB.constEnd(); ++it ) - { - if ( !layerB->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) ) - { - continue; - } - index.insertFeature( currentFeature ); - } + QgsFeatureIds selectionB = layerB->selectedFeaturesIds(); + QgsFeatureRequest req = QgsFeatureRequest().setFilterFids( selectionB ).setSubsetOfAttributes( QgsAttributeList() ); + QgsSpatialIndex index = QgsSpatialIndex( layerB->getFeatures( req ) ); + //use QgsVectorLayer::featureAtId const QgsFeatureIds selectionA = layerA->selectedFeaturesIds(); if ( p ) { p->setMaximum( selectionA.size() ); } + req = QgsFeatureRequest().setFilterFids( selectionA ); + QgsFeatureIterator selectionAIt = layerA->getFeatures( req ); QgsFeature currentFeature; int processedFeatures = 0; - it = selectionA.constBegin(); - for ( ; it != selectionA.constEnd(); ++it ) + while ( selectionAIt.nextFeature( currentFeature ) ) { if ( p ) { @@ -89,10 +83,7 @@ bool QgsOverlayAnalyzer::intersection( QgsVectorLayer* layerA, QgsVectorLayer* l { break; } - if ( !layerA->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) ) - { - continue; - } + intersectFeature( currentFeature, &vWriter, layerB, &index ); ++processedFeatures; } @@ -105,11 +96,8 @@ bool QgsOverlayAnalyzer::intersection( QgsVectorLayer* layerA, QgsVectorLayer* l //take all features else { - QgsFeatureIterator fit = layerB->getFeatures(); - while ( fit.nextFeature( currentFeature ) ) - { - index.insertFeature( currentFeature ); - } + QgsFeatureRequest req = QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() ); + QgsSpatialIndex index = QgsSpatialIndex( layerB->getFeatures( req ) ); int featureCount = layerA->featureCount(); if ( p ) @@ -118,7 +106,7 @@ bool QgsOverlayAnalyzer::intersection( QgsVectorLayer* layerA, QgsVectorLayer* l } int processedFeatures = 0; - fit = layerA->getFeatures(); + QgsFeatureIterator fit = layerA->getFeatures(); QgsFeature currentFeature; while ( fit.nextFeature( currentFeature ) ) @@ -154,17 +142,12 @@ void QgsOverlayAnalyzer::intersectFeature( QgsFeature& f, QgsVectorFileWriter* v QgsGeometry intersectGeometry; QgsFeature overlayFeature; - QList intersects; - intersects = index->intersects( featureGeometry.boundingBox() ); - QList::const_iterator it = intersects.constBegin(); + QList intersects = index->intersects( featureGeometry.boundingBox() ); + QgsFeatureRequest req = QgsFeatureRequest().setFilterFids( intersects.toSet() ); + QgsFeatureIterator intersectIt = vl->getFeatures( req ); QgsFeature outFeature; - for ( ; it != intersects.constEnd(); ++it ) + while ( intersectIt.nextFeature( overlayFeature ) ) { - if ( !vl->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( overlayFeature ) ) - { - continue; - } - if ( featureGeometry.intersects( overlayFeature.geometry() ) ) { intersectGeometry = featureGeometry.intersection( overlayFeature.geometry() ); diff --git a/src/plugins/geometry_checker/utils/qgsfeaturepool.cpp b/src/plugins/geometry_checker/utils/qgsfeaturepool.cpp index 6501d2ed4544..80cb7adfacb6 100644 --- a/src/plugins/geometry_checker/utils/qgsfeaturepool.cpp +++ b/src/plugins/geometry_checker/utils/qgsfeaturepool.cpp @@ -44,11 +44,7 @@ QgsFeaturePool::QgsFeaturePool( QgsVectorLayer *layer, bool selectedOnly ) QgsFeature feature; QgsFeatureRequest req; req.setSubsetOfAttributes( QgsAttributeList() ); - QgsFeatureIterator it = layer->getFeatures( req ); - while ( it.nextFeature( feature ) ) - { - mIndex.insertFeature( feature ); - } + mIndex = QgsSpatialIndex( layer->getFeatures( req ) ); } bool QgsFeaturePool::get( QgsFeatureId id , QgsFeature& feature ) diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp b/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp index 1231504c2395..35253c293144 100644 --- a/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp +++ b/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp @@ -45,11 +45,7 @@ QgsGeometrySnapper::QgsGeometrySnapper( QgsVectorLayer *adjustLayer, QgsVectorLa QgsFeature feature; QgsFeatureRequest req; req.setSubsetOfAttributes( QgsAttributeList() ); - QgsFeatureIterator it = mReferenceLayer->getFeatures( req ); - while ( it.nextFeature( feature ) ) - { - mIndex.insertFeature( feature ); - } + mIndex = QgsSpatialIndex( mReferenceLayer->getFeatures( req ) ); } QFuture QgsGeometrySnapper::processFeatures() From 4b398d3c80ce76503b285bdd82859a16dfc4cb7d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 09:18:36 +1000 Subject: [PATCH 339/897] Fix badly worded string --- src/app/qgssubstitutionlistwidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/qgssubstitutionlistwidget.cpp b/src/app/qgssubstitutionlistwidget.cpp index 34b27d6c21bb..888b9025e0bf 100644 --- a/src/app/qgssubstitutionlistwidget.cpp +++ b/src/app/qgssubstitutionlistwidget.cpp @@ -160,7 +160,7 @@ void QgsSubstitutionListWidget::on_mButtonImport_clicked() if ( root.tagName() != "substitutions" ) { QMessageBox::warning( nullptr, tr( "Import substitutions" ), - tr( "The selected file in not an substitutions list." ), + tr( "The selected file is not a substitution list." ), QMessageBox::Ok, QMessageBox::Ok ); return; From 4bcd97066f0c52f6f4f95adc665193bca0ab4a93 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 10:31:45 +1000 Subject: [PATCH 340/897] Fix more occurances of drawPolygon issues on Windows --- src/core/composer/qgscomposeritem.cpp | 8 +++++++- src/gui/qgsmapoverviewcanvas.cpp | 13 ++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/core/composer/qgscomposeritem.cpp b/src/core/composer/qgscomposeritem.cpp index 6e7d487ae3b4..2d7f38961852 100644 --- a/src/core/composer/qgscomposeritem.cpp +++ b/src/core/composer/qgscomposeritem.cpp @@ -525,7 +525,13 @@ void QgsComposerItem::drawSelectionBoxes( QPainter* p ) selectedItemPen.setWidth( 0 ); p->setPen( selectedItemPen ); p->setBrush( Qt::NoBrush ); - p->drawPolygon( rect() ); + + // drawPolygon causes issues on windows - corners of path may be missing resulting in triangles being drawn + // instead of rectangles! (Same cause as #13343) + QPainterPath path; + path.addPolygon( rect() ); + p->drawPath( path ); + p->restore(); } diff --git a/src/gui/qgsmapoverviewcanvas.cpp b/src/gui/qgsmapoverviewcanvas.cpp index 4d32e255d0d4..42f3b19e5220 100644 --- a/src/gui/qgsmapoverviewcanvas.cpp +++ b/src/gui/qgsmapoverviewcanvas.cpp @@ -291,6 +291,11 @@ void QgsPanningWidget::setPolygon( const QPolygon& p ) { if ( p == mPoly ) return; mPoly = p; + + //ensure polygon is closed + if ( mPoly.at( 0 ) != mPoly.at( mPoly.length() - 1 ) ) + mPoly.append( mPoly.at( 0 ) ); + setGeometry( p.boundingRect() ); update(); } @@ -303,7 +308,13 @@ void QgsPanningWidget::paintEvent( QPaintEvent* pe ) p.begin( this ); p.setPen( Qt::red ); QPolygonF t = mPoly.translated( -mPoly.boundingRect().left(), -mPoly.boundingRect().top() ); - p.drawConvexPolygon( t ); + + // drawPolygon causes issues on windows - corners of path may be missing resulting in triangles being drawn + // instead of rectangles! (Same cause as #13343) + QPainterPath path; + path.addPolygon( t ); + p.drawPath( path ); + p.end(); } From 455874258cfe7deeb4de888483adbedd97c4da7b Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 14 Oct 2016 17:32:17 +0700 Subject: [PATCH 341/897] [legend] insure multi-line labels are vertically centered with tall symbols --- .../layertree/qgslayertreemodellegendnode.cpp | 6 ++--- tests/src/core/testqgslegendrenderer.cpp | 23 ++++++++++++++++++ .../expected_legend_tall_symbol.png | Bin 0 -> 20452 bytes .../expected_legend_tall_symbol_mask.png | Bin 0 -> 21170 bytes 4 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 tests/testdata/control_images/legend/expected_legend_tall_symbol/expected_legend_tall_symbol.png create mode 100644 tests/testdata/control_images/legend/expected_legend_tall_symbol/expected_legend_tall_symbol_mask.png diff --git a/src/core/layertree/qgslayertreemodellegendnode.cpp b/src/core/layertree/qgslayertreemodellegendnode.cpp index ec6e351f284c..721b7f49655a 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.cpp +++ b/src/core/layertree/qgslayertreemodellegendnode.cpp @@ -108,9 +108,9 @@ QSizeF QgsLayerTreeModelLegendNode::drawSymbolText( const QgsLegendSettings& set // Vertical alignment of label with symbol if ( labelSize.height() < symbolSize.height() ) - labelY += symbolSize.height() / 2 + textHeight / 2; // label centered with symbol - else - labelY += textHeight; // label starts at top and runs under symbol + labelY += symbolSize.height() / 2 - labelSize.height() / 2; // label centered with symbol + + labelY += textHeight; } for ( QStringList::Iterator itemPart = lines.begin(); itemPart != lines.end(); ++itemPart ) diff --git a/tests/src/core/testqgslegendrenderer.cpp b/tests/src/core/testqgslegendrenderer.cpp index 78457e67a156..1cf9ba354f22 100644 --- a/tests/src/core/testqgslegendrenderer.cpp +++ b/tests/src/core/testqgslegendrenderer.cpp @@ -114,6 +114,7 @@ class TestQgsLegendRenderer : public QObject void testBasic(); void testBigMarker(); void testMapUnits(); + void testTallSymbol(); void testLongSymbolText(); void testThreeColumns(); void testFilterByMap(); @@ -338,6 +339,28 @@ void TestQgsLegendRenderer::testMapUnits() QVERIFY( _verifyImage( testName, mReport ) ); } +void TestQgsLegendRenderer::testTallSymbol() +{ + QString testName = "legend_tall_symbol"; + + QgsCategorizedSymbolRenderer* catRenderer = dynamic_cast( mVL3->renderer() ); + QVERIFY( catRenderer ); + catRenderer->updateCategoryLabel( 1, "This is\nthree lines\nlong label" ); + + mVL2->setName( "This is a two lines\nlong label" ); + + QgsLayerTreeModel legendModel( mRoot ); + + QgsLegendSettings settings; + settings.setWrapChar( "\n" ); + settings.setSymbolSize( QSizeF( 10.0, 10.0 ) ); + _setStandardTestFont( settings ); + _renderLegend( testName, &legendModel, settings ); + QVERIFY( _verifyImage( testName, mReport ) ); + + mVL2->setName( "Polygon Layer" ); +} + void TestQgsLegendRenderer::testLongSymbolText() { QString testName = "legend_long_symbol_text"; diff --git a/tests/testdata/control_images/legend/expected_legend_tall_symbol/expected_legend_tall_symbol.png b/tests/testdata/control_images/legend/expected_legend_tall_symbol/expected_legend_tall_symbol.png new file mode 100644 index 0000000000000000000000000000000000000000..39b5a3bbadbf525862adde4ca5c678dfc6a8388e GIT binary patch literal 20452 zcmcJ%cRZJU|2KXZg=9Bm&r*~j*J4&|z4|v5p`J20dNPL-_R_ zK~U7uuEl@ZTq!QZFLchjM=uftV-0zQeU9&jQv8pn8WYD!V zeM2(+@bwrWy<6tHSR6L!(MjG7l$5NswyU3%toE<=+*c7am2jf6UrHoOU!6tWwQ1wy zqJ4AOUfwfjy}1Tklph-(csBUmg@@<#SnlUzsl}a3qa~lO>a(cRiiA3BNG+jJHR9%G zU=6iV^Yedb_K`1HWRr}pNa&h>_FK`WhNh;0fBty1w6x^R8H&&`i|VqnvNE%?2mc!U zpnrAm>b|-=JN@q5*(4w+*m+Il7IpAOp{AxLvn-o6jNFPs!&8PPK^h11|KsKPv-sY9 z_)s&~?H!S2TVwMvNsV3BVME&ss|fk?-((6u1ki8p8692E6G5|Q&z^G~uhwkbxN&}Y zt~={ohm_FPt#XBlK|wTujNGB+el!)Wts74_-e);_`DfcRv%GU#_UY?SP4;TIU%7Ik zHj*5BXFwwH$~FE6h>$DZw5$+geLyz75YXjH!RUiG5% zDJUoiHct3j;No}Y%o%1v^YG!@>$gbxUwQHD*#RD950RV?Oe%j=3FhtFw@bNCTHDy# zYV`N_2S0u+9ItdujzV>pMFHQ-g9i>U#P7Mhi$Ya_i*dL!Uwn&%HPL(FH8n9cHN`Sg z^Y!a}f{%ugi|^H|SDJcyA#rhW%twzNrSzGZ=uRy5TrxdVYUQ;MfV!ZKs1X#@zCr$A z<=eN{>+j0y_s^#_Cb#g&fSU7L+8EL2pd<@Zod9Bt3?BlxtnwI4ls z64){Lqv4+BzI~x-85uEgaqLh2{Qmj5^8NczX9cdPRl3j5E%k}WC_$a*{{E9s_R7lM zrVCtMnJcASlDQ=+A`;nEbeT;#@gOaKf5Sa_@~;tm=J`$=+Xr#s{p$u;Pn|l&x^ZLG zta8Z{R@r_G46t0ea^+!ivf71<7XxOmP50CFIxAFu{c4d^%&&V#+-g_OK}}6+3e~Oq zOc)+M98g@mS7iHkHGO^klSOOSuGQ7mWfr+MJG#YZakWe%aQ%rz_tMhOFRc8S zuj41v($Z*i7x>-W+z8cEr-Y47&CSC`N6*#P)umjX_$E+u`plW&M~{S}I@7#MO&Ox! zzu(8KUN&%{snmN_`{&VP$83f^CKH5mqLm8saCHz)o}h`Tkr4&)v8~N1N1Tm~jqpL) zf0Wx5+j+*jza&>OJtKpH2n`Lr*>=R#)XA0e_r&LPwTF)$QLkCE#>B+Ldg5EjP*V!c zPvv#%*5TV|>FLq!+qW<2$&;-n+oYw9(=vP0q#asBM!QQ_zteQnYH4YSh=?S;e94US zX=rH3oE~%gws6+U)7j4>-Fn(LIo1&KgNfdEOFq1d*%pxZ_{kFiW#urT{OXHiO zjVtx$&$NC^Yb#x@BtDIqnHit3@S1L~CC8NS_VeS@k|=o^0;fC1P<3Vgd&Eqj&9={( z&Ck-(MB2Z6ktqFN0ZsoXp_bNI&Iq%%L)8njA+t^r*Qg@l^)3PYJ zx)Dc@AnM~JspvQFs!Y}hk~s5`Z~ue6TW}2vuKwQf=+UE|p&_yb`c<&p7`CkmFK=vQ z#0jZN*mGIp;*b3^qaAFIA3t{gGcVbguqWt^=Tcu^RoKq?ravDZYK1YgvR=oTyuqWy zp?^or_u)f<#{0YdN>>)?{b-n;=)^SczyGt6VNS38cvedMpARrwkHRyu&jy#cJQbe|Y4@aR~{DGt>Lpf@t|AWMnk)`rnGLG!LEX3rx|m zx8I(VlarL1N^{^qL)#+zjhPu&Tq{+y#Z8+wH7ts?l*Uy0X!QSN^X|StjcZu* zF) zwxAlVh8_gv<;h(dZKu%Dsky}Q*WYj6nY8kxH$^7`l}Vsov$M08efh$1;lhP6C7E>k zpN4AcM%*k3Z}g4C&O{n+pyv?UP<4GRomN&7{@~yEtuP$T(9m`LgM(ofl)(-bYHGf< zzeAsft7R?-Z8NxE)|`5foLjE=W=&V`$)B&5@AmNX_otq8FE-^qqw~_SQ_fd5@8qdd z$tfvR*REX~8XnFqu(Y?gSJ<;B%;J88gSX9rZY7sKYIO|_Nldz}evh&{^Bg&GM*ZLK z=3@M_yqtBa?#?Cljl%ZNt``3O{n;wz;X_KlwG0jocIG!DBA5&k6n`5z&I~pA9W8m2 zle1y4F+n4OM``kVgi7E1)c0pHhtdV@TLbvszkhFNV&adPC@ork#KeRTT@4c;=+!GJ zp1tlqr$0PUGd5c< zuCA4{W1W(h$1UzFxKKJdIn~eN)xH+G(Jw4447Fx#K6mb%+2GI5EiFBmXNE>bEDKkD zj*LX!zP$!7>zi`b(Q)U)l$5E(-)CpWIybkqwYkrYb7z~zM@L5+?zuevRZUxat;ylT zk{9}QxBk|oQm2)Yl8SpHB`xhTH*Sg9Skc&MAn^09n{HpG^MKM{QMCWG-NR#tUWf%--<&3@X!=hdM>SyNp{&_TO)~MkgJ$Ued82OdD zKT(C>m}=sq}Ak#TXfo}QkW=J^I^Rx!rNK8d+9j~9$eOpI8Xo2YpIe%;y6&#PXP zuI$M9@cQDQ^GM5f@*|+w=YPH^gaP1A3l^g^?t+9&!6-yw{PFB>VFrLg|h1( z7?3U8Dq-mDH9k1F&7^Vg7YhrEFHVW?w9EJE@~SGW%nwsP8aRIxl@(o{h`V7<&Z0jH zzsQS9!^C6#)}IayctiW=Z{K*97k_JLYHG%K;!P@=npn_(RIRP~3f+FLO2Gq{gGDIgPcAt#IfbQ)n z_fsG6XWr{E&y2IeB60*EVUO;H4I3m*H*yibQ?(Tp72_mMP{s_U@^7~<^;*^(KM&Be zS^RiXak0fv-OQ4Qr>D#8=us}Es~fC5rq(z(I81i0u51RD^1Xd~qwxgbEWtOU^Em4j zN^WRmBy@k)XXX|X!l?-~PCS=Bo6X0P%YMnWI-EO9SpSYpVM!KsA_E{hb+n&c4!63y8SfGs+r~oiUA5tZ5m@p%+5+>H78SNf@uLcUvO&%JTD5e6POA);@cp z+9qk`^q-kwZF^=OBzokz_4wD<>QD1H4cPL}bzJ}Q<=B(GN=n>1 z;an^Z&8V8z)>c|NIu;S{TrR_oa%R5PdCHZ~|mgI`c_aB!#(fMS^CoH5E+ zf2Jm!oBRTH^>Gy5-rhGjyNc$)6!4{QFmTERw;G^#_2L!+M^X6H8XKbA#E!nAR#Q`ZnVns+Ez#pTAkv@N z&hrxT@-^s3)CRGC{`{HjJYRaE;jV1YuZ5TS`8uYin=lap^+WIzmlm2u`THy=&lXUB zZLjL($NDj&$livE^3;Z-a!|NLGOv_>9MBt zL02naMb1ORfIzD@4b#)&Q!2ED(;@#rZ3zI!+TzlP_ZL4pn;qFZJRngy9 z@#Z06WPC;1j})C~Mv<*s*PFNwE?i?79>WLHl7+=FC>({&8_a5iG znf49X=jG*z;~O?_&bKc$sdF1XWq=9%?VCo@${NM7C{3f)}hu4b2a;%a=LB${&`C5pCI{(Z{&sAsusjU7HG_0wqp(*_{9rp2!o}QlbrAyit7F@=g*x0BxZ{CcO^Q-w@{^0{tKtMqK zEC?bnqo9BQB|vh;WN*cZGiTa`r};xuh6VL#eeULM(ajdq&fua-NlA&PjwdGPr)>QL z1IcC)r|hX%ePfFs+TGiC@91!={Xm=vzMVT6fVn^@17Exl->`9`%lzbt8|;#l;1UvY zaw};r+$vsN82*z}QzUxhN`lcb8OGS0@=3QFeU|J(xz2pia1i+AF&T4zTJTkga-$iC;e&{Nm%c$esTt zCdFWW(Ic*)1@sA6fR>il`g$cUEO2y%mG|-*adC0tcf4~1*Y4{JzXmmqALo&km7N45 z3JarO`Sa`Glai;#sWxRk6bhF{*^5g`;-^PO9KM!%^J4b%%C0m%8RqL~(@q&u#W3$3 z9Tl7WR$sp!;E5QySP9m|^X=O=ksUkK0iBFLx3%RpSwuA4j*k!d`S}Hj57M4L*Y@&K zegJv}703Ct1xZ!P%PDYt_D9~|dxaIldH}T1_o28}?mHN=ov9hCo4}i5M9f`IcOpvjG87UxG?DmQq7@V2|bB zpCzQFH86F_s}4PaS>5pH(RW-W%Bz1a?!PC;a4=E1s?3*)Wy1#lrW76N;Y}Qr70u1Y zCslauzS-z6cO7;c79Zc)6nSh>Wp#mxmS6qFT!h%psC)Oq05z>~Z3`|>@T@HU6#uib zG*Lg?y%aC?WPdy*6%`c(hhALh0?Ry+_L;sCI%1) zdJM~^OktM2iuLH^_C&pJ*{yPjJX1>zLH{rovL z_a+J1roPuuo&w01kd*YjabrC`aMrasrlZ0fXG z`T5%*N7O4@dH&uw+*OosXbui>a=QN=Le$YWlB_}60?f5>r?o8yLI?F;=Iz~oD1-Fq67zHu2JO-&P zPfKH5?I3%ip=sh`10(P|pAT}doY9>YKWt%fV`%6M1UXQH^pc?Fr%j{`J)`{Zv+(~h z6Yk!3b(?*=#$QJ}uhp#5M#)2A@97Ut6DJHUbz^?%ZD?sRTo}t&r8(Am@Y3?t4R5>} z#6D^pMYo-d6tO?kV`;kSqwk8wd;2p00fEE<-188t{8mP{0m!l=&O7n6jc3 zsl9}Tg&7?=GG{dAx|a7xMrL|CpuXOo@HCeMr`%hh4^i|-y=!rp0cyyrdEL(sW1(;B z&$A8=0(^XgmzUR09`pVC*N={lGV}6AfUx8gBt%S259p&2KtIa1Ts+?cxC%OK7toOC zy|M+}l3VJ)@l^WgPoEC?4rtWX)v;{eOau9E234~Ce66g&b4lCkBphE}SvlOS8(XBc z`CJUmFJ8Q;ftqkZXl${syGpa!#}M}0AgK7T$k^rsz^ zh3~QrroQR3V*w{B0+YR0S6*gim6MR=?%nENgTh<4zU}DPf`Z!Lfp*s0+e-nhAA;o# zu)E)`l9)OfM_yE?8Kq!C`hx|Xz`@Jxb~DX1^Tj0vD=WiaZ)|LAFS;y_w#j(<^l7Nw zQf}fF1qA*Z=qr4?{=tJm+1b*pY;5tbAh#5}eq9c(_^zfsdZyER`FE^p;pE⪚&c? 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 literal 0 HcmV?d00001 From ee9e1c3328379b83ed457e2281f0a94518b7a6f4 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 19 Oct 2016 09:19:00 +0300 Subject: [PATCH 342/897] [processing] add missed spatial index constructor (follow up 700441eec9) --- python/plugins/processing/tools/vector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 16564e6932eb..2d2ac2067290 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -225,7 +225,7 @@ def spatialindex(layer): request.setSubsetOfAttributes([]) if ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) \ and layer.selectedFeatureCount() > 0: - idx = layer.selectedFeaturesIterator(request) + idx = QgsSpatialIndex(layer.selectedFeaturesIterator(request)) else: idx = QgsSpatialIndex(layer.getFeatures(request)) return idx From 41fafd69823cd72d9f4599ef80f94996640ddaaa Mon Sep 17 00:00:00 2001 From: Piotr Pociask Date: Sun, 16 Oct 2016 15:07:03 +0200 Subject: [PATCH 343/897] [processing] support MultiPoint geometries in Delaunay triangulation --- .../plugins/processing/algs/qgis/Delaunay.py | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/python/plugins/processing/algs/qgis/Delaunay.py b/python/plugins/processing/algs/qgis/Delaunay.py index 728b941f9ba9..a73b05342c68 100644 --- a/python/plugins/processing/algs/qgis/Delaunay.py +++ b/python/plugins/processing/algs/qgis/Delaunay.py @@ -82,12 +82,16 @@ def processAlgorithm(self, progress): total = 100.0 / len(features) for current, inFeat in enumerate(features): geom = inFeat.geometry() - point = geom.asPoint() - x = point.x() - y = point.y() - pts.append((x, y)) - ptNdx += 1 - ptDict[ptNdx] = inFeat.id() + if geom.isMultipart(): + points = geom.asMultiPoint() + else: + points = [ geom.asPoint() ] + for n, point in enumerate(points): + x = point.x() + y = point.y() + pts.append((x, y)) + ptNdx += 1 + ptDict[ptNdx] = (inFeat.id(), n) progress.setPercentage(int(current * total)) if len(pts) < 3: @@ -111,10 +115,14 @@ def processAlgorithm(self, progress): attrs = [] step = 0 for index in indicies: - request = QgsFeatureRequest().setFilterFid(ptDict[ids[index]]) + fid, n = ptDict[ids[index]] + request = QgsFeatureRequest().setFilterFid(fid) inFeat = next(layer.getFeatures(request)) geom = inFeat.geometry() - point = QgsPoint(geom.asPoint()) + if geom.isMultipart(): + point = QgsPoint(geom.asMultiPoint()[n]) + else: + point = QgsPoint(geom.asPoint()) polygon.append(point) if step <= 3: attrs.append(ids[index]) From 3af23036fdfb7ae7ac6cee2269080471b63e6dc5 Mon Sep 17 00:00:00 2001 From: Piotr Pociask Date: Mon, 17 Oct 2016 10:47:20 +0200 Subject: [PATCH 344/897] Test for multipoint Delaunay triangulation --- .../plugins/processing/algs/qgis/Delaunay.py | 4 +- .../testdata/expected/multipoint_delaunay.gml | 94 +++++++++++++++++++ .../testdata/expected/multipoint_delaunay.xsd | 47 ++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 13 ++- 4 files changed, 155 insertions(+), 3 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml create mode 100644 python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd diff --git a/python/plugins/processing/algs/qgis/Delaunay.py b/python/plugins/processing/algs/qgis/Delaunay.py index a73b05342c68..2a266c06a7fd 100644 --- a/python/plugins/processing/algs/qgis/Delaunay.py +++ b/python/plugins/processing/algs/qgis/Delaunay.py @@ -81,7 +81,7 @@ def processAlgorithm(self, progress): features = vector.features(layer) total = 100.0 / len(features) for current, inFeat in enumerate(features): - geom = inFeat.geometry() + geom = QgsGeometry(inFeat.geometry()) if geom.isMultipart(): points = geom.asMultiPoint() else: @@ -118,7 +118,7 @@ def processAlgorithm(self, progress): fid, n = ptDict[ids[index]] request = QgsFeatureRequest().setFilterFid(fid) inFeat = next(layer.getFeatures(request)) - geom = inFeat.geometry() + geom = QgsGeometry(inFeat.geometry()) if geom.isMultipart(): point = QgsPoint(geom.asMultiPoint()[n]) else: diff --git a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml new file mode 100644 index 000000000000..eeaaf78f5447 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml @@ -0,0 +1,94 @@ + + + + + 0-5 + 83 + + + + + + 7,-1 8,-1 0,-5 7,-1 + 8.000000000000000 + 7.000000000000000 + 6.000000000000000 + + + + + 0,-5 4,1 7,-1 0,-5 + 6.000000000000000 + 5.000000000000000 + 8.000000000000000 + + + + + 0,-1 4,1 0,-5 0,-1 + 9.000000000000000 + 5.000000000000000 + 6.000000000000000 + + + + + 1,1 0,-1 0,0 1,1 + 1.000000000000000 + 9.000000000000000 + 0.000000000000000 + + + + + 1,1 4,1 0,-1 1,1 + 1.000000000000000 + 5.000000000000000 + 9.000000000000000 + + + + + 2,2 4,1 1,1 2,2 + 2.000000000000000 + 5.000000000000000 + 1.000000000000000 + + + + + 5,2 7,-1 4,1 5,2 + 4.000000000000000 + 8.000000000000000 + 5.000000000000000 + + + + + 3,3 4,1 2,2 3,3 + 3.000000000000000 + 5.000000000000000 + 2.000000000000000 + + + + + 3,3 5,2 4,1 3,3 + 3.000000000000000 + 4.000000000000000 + 5.000000000000000 + + + + + 5,2 8,-1 7,-1 5,2 + 4.000000000000000 + 7.000000000000000 + 8.000000000000000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd new file mode 100644 index 000000000000..498417068abd --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index aae4f9f61fdf..6cc5909acec4 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1112,4 +1112,15 @@ tests: results: OUTPUT: name: expected/sum_line_length.gml - type: vector \ No newline at end of file + type: vector + + - algorithm: qgis:delaunaytriangulation + name: Delaunay triangulation (multipoint data) + params: + INPUT: + name: multipoints.gml + type: vector + results: + OUTPUT: + name: expected/multipoint_delaunay.gml + type: vector From cd0fefb42b1e58fb06f76c02d9bcce12a27e25c1 Mon Sep 17 00:00:00 2001 From: Piotr Pociask Date: Mon, 17 Oct 2016 13:45:51 +0200 Subject: [PATCH 345/897] [processing] Update voronoi classes for Python3; update expected data for multipoint Delaunay traingulation test --- .../plugins/processing/algs/qgis/Delaunay.py | 2 + .../plugins/processing/algs/qgis/voronoi.py | 38 +++++----- .../testdata/expected/multipoint_delaunay.gfs | 31 ++++++++ .../testdata/expected/multipoint_delaunay.gml | 70 ++++++++----------- 4 files changed, 84 insertions(+), 57 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gfs diff --git a/python/plugins/processing/algs/qgis/Delaunay.py b/python/plugins/processing/algs/qgis/Delaunay.py index 2a266c06a7fd..ad2cc63794af 100644 --- a/python/plugins/processing/algs/qgis/Delaunay.py +++ b/python/plugins/processing/algs/qgis/Delaunay.py @@ -82,6 +82,8 @@ def processAlgorithm(self, progress): total = 100.0 / len(features) for current, inFeat in enumerate(features): geom = QgsGeometry(inFeat.geometry()) + if geom.isEmpty(): + continue if geom.isMultipart(): points = geom.asMultiPoint() else: diff --git a/python/plugins/processing/algs/qgis/voronoi.py b/python/plugins/processing/algs/qgis/voronoi.py index e05d2095c067..3336cc83b221 100644 --- a/python/plugins/processing/algs/qgis/voronoi.py +++ b/python/plugins/processing/algs/qgis/voronoi.py @@ -391,17 +391,18 @@ def dump(self): # fix_print_with_import print("Site #%d (%g, %g)" % (self.sitenum, self.x, self.y)) - def __cmp__(self, other): + def __eq__(self, other): + return (self.x==other.x) and (self.y==other.y) + + def __lt__(self, other): if self.y < other.y: - return -1 + return True elif self.y > other.y: - return 1 + return False elif self.x < other.x: - return -1 + return True elif self.x > other.x: - return 1 - else: - return 0 + return False def distance(self, other): dx = self.x - other.x @@ -505,17 +506,18 @@ def dump(self): # fix_print_with_import print("ystar: ", self.ystar) - def __cmp__(self, other): - if self.ystar > other.ystar: - return 1 - elif self.ystar < other.ystar: - return -1 - elif self.vertex.x > other.vertex.x: - return 1 + def __eq__(self, other): + return (self.vertex.x==other.vertex.x) and (self.ystar==other.ystar) + + def __lt__(self, other): + if self.ystar < other.ystar: + return True + elif self.ystar > other.ystar: + return False elif self.vertex.x < other.vertex.x: - return -1 - else: - return 0 + return True + elif self.vertex.x > other.vertex.x: + return False def leftreg(self, default): if not self.edge: @@ -791,7 +793,7 @@ def __init__(this, lst): def __iter__(this): return this - def next(this): + def __next__(this): try: return next(this.generator) except StopIteration: diff --git a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gfs b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gfs new file mode 100644 index 000000000000..768fa5b251af --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gfs @@ -0,0 +1,31 @@ + + + mp + mp + + 3 + EPSG:4326 + + 9 + 0.00000 + 8.00000 + -5.00000 + 3.00000 + + + POINTA + POINTA + Real + + + POINTB + POINTB + Real + + + POINTC + POINTC + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml index eeaaf78f5447..639be1c39f50 100644 --- a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml +++ b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.gml @@ -14,81 +14,73 @@ 7,-1 8,-1 0,-5 7,-1 - 8.000000000000000 - 7.000000000000000 - 6.000000000000000 + 7.000000000000000 + 6.000000000000000 + 5.000000000000000 0,-5 4,1 7,-1 0,-5 - 6.000000000000000 - 5.000000000000000 - 8.000000000000000 + 5.000000000000000 + 4.000000000000000 + 7.000000000000000 0,-1 4,1 0,-5 0,-1 - 9.000000000000000 - 5.000000000000000 - 6.000000000000000 + 8.000000000000000 + 4.000000000000000 + 5.000000000000000 - 1,1 0,-1 0,0 1,1 - 1.000000000000000 - 9.000000000000000 - 0.000000000000000 + 1,1 4,1 0,-1 1,1 + 0.000000000000000 + 4.000000000000000 + 8.000000000000000 - 1,1 4,1 0,-1 1,1 + 2,2 4,1 1,1 2,2 1.000000000000000 - 5.000000000000000 - 9.000000000000000 + 4.000000000000000 + 0.000000000000000 - 2,2 4,1 1,1 2,2 - 2.000000000000000 - 5.000000000000000 - 1.000000000000000 - - - - 5,2 7,-1 4,1 5,2 - 4.000000000000000 - 8.000000000000000 - 5.000000000000000 + 3.000000000000000 + 7.000000000000000 + 4.000000000000000 - + 3,3 4,1 2,2 3,3 - 3.000000000000000 - 5.000000000000000 - 2.000000000000000 + 2.000000000000000 + 4.000000000000000 + 1.000000000000000 - + 3,3 5,2 4,1 3,3 - 3.000000000000000 - 4.000000000000000 - 5.000000000000000 + 2.000000000000000 + 3.000000000000000 + 4.000000000000000 - + 5,2 8,-1 7,-1 5,2 - 4.000000000000000 - 7.000000000000000 - 8.000000000000000 + 3.000000000000000 + 6.000000000000000 + 7.000000000000000 From c130372730e2fed2f8ea0ac7f6015b618d69c171 Mon Sep 17 00:00:00 2001 From: Jaka Kranjc Date: Wed, 19 Oct 2016 12:09:01 +0200 Subject: [PATCH 346/897] doc: fixed processing's description for v.extract (#3637) --- python/plugins/processing/algs/grass/description/v.extract.txt | 2 +- python/plugins/processing/algs/grass7/description/v.extract.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/grass/description/v.extract.txt b/python/plugins/processing/algs/grass/description/v.extract.txt index d10213e7c88a..76c72d362ed9 100644 --- a/python/plugins/processing/algs/grass/description/v.extract.txt +++ b/python/plugins/processing/algs/grass/description/v.extract.txt @@ -1,5 +1,5 @@ v.extract -Selects vector objects from a vector layer a new layer containing only the selected objects. +Selects vector objects from a vector layer and creates a new layer containing only the selected objects. Vector (v.*) ParameterVector|input|Vector layer|-1|False ParameterString|where|WHERE conditions of SQL statement without 'where' keyword| diff --git a/python/plugins/processing/algs/grass7/description/v.extract.txt b/python/plugins/processing/algs/grass7/description/v.extract.txt index d10213e7c88a..76c72d362ed9 100644 --- a/python/plugins/processing/algs/grass7/description/v.extract.txt +++ b/python/plugins/processing/algs/grass7/description/v.extract.txt @@ -1,5 +1,5 @@ v.extract -Selects vector objects from a vector layer a new layer containing only the selected objects. +Selects vector objects from a vector layer and creates a new layer containing only the selected objects. Vector (v.*) ParameterVector|input|Vector layer|-1|False ParameterString|where|WHERE conditions of SQL statement without 'where' keyword| From a9795ad8ea12d294604fdb137b843c34ea5be2d8 Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 18 Oct 2016 10:49:26 +0200 Subject: [PATCH 347/897] [DB Manager] Allow lowercase field names for homogenize PostGIS Import PostGIS provider has an option to lowercase field names. This options is available for user in QGIS algorithm ImportIntoPostGIS and not in DB Mananger. This commit fix it. --- python/plugins/db_manager/db_plugins/plugin.py | 3 +++ .../plugins/db_manager/db_plugins/postgis/plugin.py | 3 +++ python/plugins/db_manager/dlg_import_vector.py | 13 +++++++++++-- python/plugins/db_manager/ui/DlgImportVector.ui | 9 ++++++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/python/plugins/db_manager/db_plugins/plugin.py b/python/plugins/db_manager/db_plugins/plugin.py index a45b8125752b..f56a8d2fcc29 100644 --- a/python/plugins/db_manager/db_plugins/plugin.py +++ b/python/plugins/db_manager/db_plugins/plugin.py @@ -552,6 +552,9 @@ def explicitSpatialIndex(self): def spatialIndexClause(self, src_table, src_column, dest_table, dest_table_column): return None + def hasLowercaseFieldNamesOption(self): + return False + class Schema(DbItemObject): diff --git a/python/plugins/db_manager/db_plugins/postgis/plugin.py b/python/plugins/db_manager/db_plugins/postgis/plugin.py index 1e3060c125b9..4885e3686532 100644 --- a/python/plugins/db_manager/db_plugins/postgis/plugin.py +++ b/python/plugins/db_manager/db_plugins/postgis/plugin.py @@ -168,6 +168,9 @@ def runRefreshMaterializedViewSlot(self, item, action, parent): item.runRefreshMaterializedView() + def hasLowercaseFieldNamesOption(self): + return True + class PGSchema(Schema): diff --git a/python/plugins/db_manager/dlg_import_vector.py b/python/plugins/db_manager/dlg_import_vector.py index f8b46ad9dee1..0eea6761f702 100644 --- a/python/plugins/db_manager/dlg_import_vector.py +++ b/python/plugins/db_manager/dlg_import_vector.py @@ -108,6 +108,10 @@ def checkSupports(self): if not self.chkSpatialIndex.isEnabled(): self.chkSpatialIndex.setChecked(False) + self.chkLowercaseFieldNames.setEnabled(self.db.hasLowercaseFieldNamesOption()) + if not self.chkLowercaseFieldNames.isEnabled(): + self.chkLowercaseFieldNames.setChecked(False) + def populateLayers(self): self.cboInputLayer.clear() for index, layer in enumerate(iface.legendInterface().layers()): @@ -302,13 +306,18 @@ def accept(self): else: geom = None + options = {} + if self.chkLowercaseFieldNames.isEnabled() and self.chkLowercaseFieldNames.isChecked(): + pk = pk.lower() + if geom: + geom = geom.lower() + options['lowercaseFieldNames'] = True + # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) uri = self.outUri.uri(False) providerName = self.db.dbplugin().providerName() - - options = {} if self.chkDropTable.isChecked(): options['overwrite'] = True diff --git a/python/plugins/db_manager/ui/DlgImportVector.ui b/python/plugins/db_manager/ui/DlgImportVector.ui index 34f60608f9db..c2ec343f53ac 100644 --- a/python/plugins/db_manager/ui/DlgImportVector.ui +++ b/python/plugins/db_manager/ui/DlgImportVector.ui @@ -253,7 +253,7 @@ - + Create spatial index @@ -267,6 +267,13 @@ + + + + Convert field names to lowercase + + + From f7575e08f5b2bdff65fce468f37938ea557ab0f5 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 10 Oct 2016 20:07:42 +0300 Subject: [PATCH 348/897] [processing] expose IDW interpolation from Interpolation plugin in toolbox --- .../algs/qgis/IdwInterpolationAttribute.py | 138 ++++++++++++++++++ .../algs/qgis/IdwInterpolationZValue.py | 135 +++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 6 +- 3 files changed, 278 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py create mode 100644 python/plugins/processing/algs/qgis/IdwInterpolationZValue.py diff --git a/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py b/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py new file mode 100644 index 000000000000..9e9598699fed --- /dev/null +++ b/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + IdwInterpolationAttribute.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import QgsRectangle +from qgis.analysis import (QgsInterpolator, + QgsIDWInterpolator, + QgsGridFileWriter + ) + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterTableField +from processing.core.parameters import ParameterSelection +from processing.core.parameters import ParameterNumber +from processing.core.parameters import ParameterExtent +from processing.core.outputs import OutputRaster +from processing.tools import dataobjects + + +class IdwInterpolationAttribute(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + ATTRIBUTE = 'ATTRIBUTE' + LAYER_TYPE = 'LAYER_TYPE' + DISTANCE_COEFFICIENT = 'DISTANCE_COEFFICIENT' + COLUMNS = 'COLUMNS' + ROWS = 'ROWS' + CELLSIZE_X = 'CELLSIZE_X' + CELLSIZE_Y = 'CELLSIZE_Y' + EXTENT = 'EXTENT' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('IDW interpolation (using attribute)') + self.group, self.i18n_group = self.trAlgorithm('Interpolation') + + self.TYPES = [self.tr('Points'), + self.tr('Structure lines'), + self.tr('Break lines') + ] + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Vector layer'))) + self.addParameter(ParameterTableField(self.ATTRIBUTE, + self.tr('Interpolation attribute'), + self.INPUT_LAYER, + ParameterTableField.DATA_TYPE_NUMBER)) + self.addParameter(ParameterSelection(self.LAYER_TYPE, + self.tr('Type'), + self.TYPES, + 0)) + self.addParameter(ParameterNumber(self.DISTANCE_COEFFICIENT, + self.tr('Distance coefficient P'), + 0.0, 99.99, 2.0)) + self.addParameter(ParameterNumber(self.COLUMNS, + self.tr('Number of columns'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.ROWS, + self.tr('Number of rows'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.CELLSIZE_X, + self.tr('Cellsize X'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterNumber(self.CELLSIZE_Y, + self.tr('Cellsize Y'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterExtent(self.EXTENT, + self.tr('Extent'))) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Interpolated'))) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + fieldName = self.getParameterValue(self.ATTRIBUTE) + layerType = self.getParameterValue(self.LAYER_TYPE) + coefficient = self.getParameterValue(self.DISTANCE_COEFFICIENT) + columns = self.getParameterValue(self.COLUMNS) + rows = self.getParameterValue(self.ROWS) + cellsizeX = self.getParameterValue(self.CELLSIZE_X) + cellsizeY = self.getParameterValue(self.CELLSIZE_Y) + extent = self.getParameterValue(self.EXTENT).split(',') + output = self.getOutputValue(self.OUTPUT_LAYER) + + xMin = float(extent[0]) + xMax = float(extent[1]) + yMin = float(extent[2]) + yMax = float(extent[3]) + bbox = QgsRectangle(xMin, yMin, xMax, yMax) + + layerData = QgsInterpolator.LayerData() + layerData.vectorLayer = layer + layerData.zCoordInterpolation = False + layerData.interpolationAttribute = layer.dataProvider().fieldNameIndex(fieldName) + + if layerType == 0: + layerData.mInputType = QgsInterpolator.POINTS + elif layerType == 1: + layerData.mInputType = QgsInterpolator.STRUCTURE_LINES + else: + layerData.mInputType = QgsInterpolator.BREAK_LINES + + interpolator = QgsIDWInterpolator([layerData]) + interpolator.setDistanceCoefficient(coefficient) + + writer = QgsGridFileWriter(interpolator, + output, + bbox, + columns, + rows, + cellsizeX, + cellsizeY) + + writer.writeFile() diff --git a/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py b/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py new file mode 100644 index 000000000000..686f10e36279 --- /dev/null +++ b/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + IdwInterpolationZValue.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import QgsRectangle, QgsWkbTypes +from qgis.analysis import (QgsInterpolator, + QgsIDWInterpolator, + QgsGridFileWriter + ) + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterSelection +from processing.core.parameters import ParameterNumber +from processing.core.parameters import ParameterExtent +from processing.core.outputs import OutputRaster +from processing.tools import dataobjects + + +class IdwInterpolationZValue(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + LAYER_TYPE = 'LAYER_TYPE' + DISTANCE_COEFFICIENT = 'DISTANCE_COEFFICIENT' + COLUMNS = 'COLUMNS' + ROWS = 'ROWS' + CELLSIZE_X = 'CELLSIZE_X' + CELLSIZE_Y = 'CELLSIZE_Y' + EXTENT = 'EXTENT' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('IDW interpolation (using Z-values)') + self.group, self.i18n_group = self.trAlgorithm('Interpolation') + + self.TYPES = [self.tr('Points'), + self.tr('Structure lines'), + self.tr('Break lines') + ] + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Vector layer'))) + self.addParameter(ParameterSelection(self.LAYER_TYPE, + self.tr('Type'), + self.TYPES, + 0)) + self.addParameter(ParameterNumber(self.DISTANCE_COEFFICIENT, + self.tr('Distance coefficient P'), + 0.0, 99.99, 2.0)) + self.addParameter(ParameterNumber(self.COLUMNS, + self.tr('Number of columns'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.ROWS, + self.tr('Number of rows'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.CELLSIZE_X, + self.tr('Cellsize X'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterNumber(self.CELLSIZE_Y, + self.tr('Cellsize Y'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterExtent(self.EXTENT, + self.tr('Extent'))) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Interpolated'))) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + layerType = self.getParameterValue(self.LAYER_TYPE) + coefficient = self.getParameterValue(self.DISTANCE_COEFFICIENT) + columns = self.getParameterValue(self.COLUMNS) + rows = self.getParameterValue(self.ROWS) + cellsizeX = self.getParameterValue(self.CELLSIZE_X) + cellsizeY = self.getParameterValue(self.CELLSIZE_Y) + extent = self.getParameterValue(self.EXTENT).split(',') + output = self.getOutputValue(self.OUTPUT_LAYER) + + if not QgsWkbTypes.hasZ(layer.wkbType()): + raise GeoAlgorithmExecutionException( + self.tr('Geometries in input layer does not have Z coordinates.')) + + xMin = float(extent[0]) + xMax = float(extent[1]) + yMin = float(extent[2]) + yMax = float(extent[3]) + bbox = QgsRectangle(xMin, yMin, xMax, yMax) + + layerData = QgsInterpolator.LayerData() + layerData.vectorLayer = layer + layerData.zCoordInterpolation = True + layerData.interpolationAttribute = -1 + + if layerType == 0: + layerData.mInputType = QgsInterpolator.POINTS + elif layerType == 1: + layerData.mInputType = QgsInterpolator.STRUCTURE_LINES + else: + layerData.mInputType = QgsInterpolator.BREAK_LINES + + interpolator = QgsIDWInterpolator([layerData]) + interpolator.setDistanceCoefficient(coefficient) + + writer = QgsGridFileWriter(interpolator, + output, + bbox, + columns, + rows, + cellsizeX, + cellsizeY) + + writer.writeFile() diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index f053e2c71c6a..5bcab1d686ad 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -163,6 +163,9 @@ from .Ruggedness import Ruggedness from .Hillshade import Hillshade from .ReliefAuto import ReliefAuto +from .IdwInterpolationZValue import IdwInterpolationZValue +from .IdwInterpolationAttribute import IdwInterpolationAttribute + pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -220,7 +223,8 @@ def __init__(self): OffsetLine(), PolygonCentroids(), Translate(), SingleSidedBuffer(), PointsAlongGeometry(), Aspect(), Slope(), Ruggedness(), Hillshade(), - ReliefAuto(), + ReliefAuto(), IdwInterpolationZValue(), + IdwInterpolationAttribute() ] if hasMatplotlib: From 774965c2d4ee1678219c725e279760027c73534f Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 11 Oct 2016 11:42:18 +0300 Subject: [PATCH 349/897] [processing] expose TIN interpolation from interpolation plugin in toolbox --- .../algs/qgis/QGISAlgorithmProvider.py | 5 +- .../algs/qgis/TinInterpolationAttribute.py | 154 ++++++++++++++++++ .../algs/qgis/TinInterpolationZValue.py | 151 +++++++++++++++++ 3 files changed, 309 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/TinInterpolationAttribute.py create mode 100644 python/plugins/processing/algs/qgis/TinInterpolationZValue.py diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 5bcab1d686ad..8c459b565ba8 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -165,6 +165,8 @@ from .ReliefAuto import ReliefAuto from .IdwInterpolationZValue import IdwInterpolationZValue from .IdwInterpolationAttribute import IdwInterpolationAttribute +from .TinInterpolationZValue import TinInterpolationZValue +from .TinInterpolationAttribute import TinInterpolationAttribute pluginPath = os.path.normpath(os.path.join( @@ -224,7 +226,8 @@ def __init__(self): SingleSidedBuffer(), PointsAlongGeometry(), Aspect(), Slope(), Ruggedness(), Hillshade(), ReliefAuto(), IdwInterpolationZValue(), - IdwInterpolationAttribute() + IdwInterpolationAttribute(), TinInterpolationZValue(), + TinInterpolationAttribute() ] if hasMatplotlib: diff --git a/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py b/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py new file mode 100644 index 000000000000..a44fe25ccfc4 --- /dev/null +++ b/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + TinInterpolationAttribute.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import QgsRectangle +from qgis.analysis import (QgsInterpolator, + QgsTINInterpolator, + QgsGridFileWriter + ) + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterTableField +from processing.core.parameters import ParameterSelection +from processing.core.parameters import ParameterNumber +from processing.core.parameters import ParameterExtent +from processing.core.outputs import OutputRaster +from processing.core.outputs import OutputVector +from processing.tools import dataobjects + + +class TinInterpolationAttribute(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + ATTRIBUTE = 'ATTRIBUTE' + LAYER_TYPE = 'LAYER_TYPE' + METHOD = 'METHOD' + COLUMNS = 'COLUMNS' + ROWS = 'ROWS' + CELLSIZE_X = 'CELLSIZE_X' + CELLSIZE_Y = 'CELLSIZE_Y' + EXTENT = 'EXTENT' + OUTPUT_LAYER = 'OUTPUT_LAYER' + TRIANULATION_FILE = 'TRIANULATION_FILE' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('TIN interpolation (using attribute)') + self.group, self.i18n_group = self.trAlgorithm('Interpolation') + + self.TYPES = [self.tr('Points'), + self.tr('Structure lines'), + self.tr('Break lines') + ] + self.METHODS = [self.tr('Linear'), + self.tr('Clough-Toucher (cubic)') + ] + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Vector layer'))) + self.addParameter(ParameterTableField(self.ATTRIBUTE, + self.tr('Interpolation attribute'), + self.INPUT_LAYER, + ParameterTableField.DATA_TYPE_NUMBER)) + self.addParameter(ParameterSelection(self.LAYER_TYPE, + self.tr('Type'), + self.TYPES, + 0)) + self.addParameter(ParameterSelection(self.METHOD, + self.tr('Interpolation method'), + self.METHODS, + 0)) + self.addParameter(ParameterNumber(self.COLUMNS, + self.tr('Number of columns'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.ROWS, + self.tr('Number of rows'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.CELLSIZE_X, + self.tr('Cellsize X'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterNumber(self.CELLSIZE_Y, + self.tr('Cellsize Y'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterExtent(self.EXTENT, + self.tr('Extent'))) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Interpolated'))) + self.addOutput(OutputVector(self.TRIANULATION_FILE, + self.tr('Triangulation'), + )) # datatype=dataobjects.TYPE_VECTOR_LINE)) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + fieldName = self.getParameterValue(self.ATTRIBUTE) + layerType = self.getParameterValue(self.LAYER_TYPE) + method = self.getParameterValue(self.METHOD) + columns = self.getParameterValue(self.COLUMNS) + rows = self.getParameterValue(self.ROWS) + cellsizeX = self.getParameterValue(self.CELLSIZE_X) + cellsizeY = self.getParameterValue(self.CELLSIZE_Y) + extent = self.getParameterValue(self.EXTENT).split(',') + output = self.getOutputValue(self.OUTPUT_LAYER) + triangulation = self.getOutputValue(self.TRIANULATION_FILE) + + xMin = float(extent[0]) + xMax = float(extent[1]) + yMin = float(extent[2]) + yMax = float(extent[3]) + bbox = QgsRectangle(xMin, yMin, xMax, yMax) + + layerData = QgsInterpolator.LayerData() + layerData.vectorLayer = layer + layerData.zCoordInterpolation = False + layerData.interpolationAttribute = layer.dataProvider().fieldNameIndex(fieldName) + + if layerType == 0: + layerData.mInputType = QgsInterpolator.POINTS + elif layerType == 1: + layerData.mInputType = QgsInterpolator.STRUCTURE_LINES + else: + layerData.mInputType = QgsInterpolator.BREAK_LINES + + if method == 0: + interpolationMethod = QgsTINInterpolator.Linear + else: + interpolationMethod = QgsTINInterpolator.CloughTocher + + interpolator = QgsTINInterpolator([layerData], interpolationMethod) + interpolator.setExportTriangulationToFile(True) + interpolator.setTriangulationFilePath(triangulation) + + writer = QgsGridFileWriter(interpolator, + output, + bbox, + columns, + rows, + cellsizeX, + cellsizeY) + + writer.writeFile() diff --git a/python/plugins/processing/algs/qgis/TinInterpolationZValue.py b/python/plugins/processing/algs/qgis/TinInterpolationZValue.py new file mode 100644 index 000000000000..1c26d097da97 --- /dev/null +++ b/python/plugins/processing/algs/qgis/TinInterpolationZValue.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + TinInterpolationZValue.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Alexander Bruy' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import QgsRectangle, QgsWkbTypes +from qgis.analysis import (QgsInterpolator, + QgsTINInterpolator, + QgsGridFileWriter + ) + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterSelection +from processing.core.parameters import ParameterNumber +from processing.core.parameters import ParameterExtent +from processing.core.outputs import OutputRaster +from processing.core.outputs import OutputVector +from processing.tools import dataobjects + + +class TinInterpolationZValue(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + LAYER_TYPE = 'LAYER_TYPE' + METHOD = 'METHOD' + COLUMNS = 'COLUMNS' + ROWS = 'ROWS' + CELLSIZE_X = 'CELLSIZE_X' + CELLSIZE_Y = 'CELLSIZE_Y' + EXTENT = 'EXTENT' + OUTPUT_LAYER = 'OUTPUT_LAYER' + TRIANULATION_FILE = 'TRIANULATION_FILE' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('TIN interpolation (using Z-values)') + self.group, self.i18n_group = self.trAlgorithm('Interpolation') + + self.TYPES = [self.tr('Points'), + self.tr('Structure lines'), + self.tr('Break lines') + ] + self.METHODS = [self.tr('Linear'), + self.tr('Clough-Toucher (cubic)') + ] + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Vector layer'))) + self.addParameter(ParameterSelection(self.LAYER_TYPE, + self.tr('Type'), + self.TYPES, + 0)) + self.addParameter(ParameterSelection(self.METHOD, + self.tr('Interpolation method'), + self.METHODS, + 0)) + self.addParameter(ParameterNumber(self.COLUMNS, + self.tr('Number of columns'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.ROWS, + self.tr('Number of rows'), + 0, 10000000, 300)) + self.addParameter(ParameterNumber(self.CELLSIZE_X, + self.tr('Cellsize X'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterNumber(self.CELLSIZE_Y, + self.tr('Cellsize Y'), + 0.0, 999999.000000, 0.0)) + self.addParameter(ParameterExtent(self.EXTENT, + self.tr('Extent'))) + self.addOutput(OutputRaster(self.OUTPUT_LAYER, + self.tr('Interpolated'))) + self.addOutput(OutputVector(self.TRIANULATION_FILE, + self.tr('Triangulation'), + )) # datatype=dataobjects.TYPE_VECTOR_LINE)) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + layerType = self.getParameterValue(self.LAYER_TYPE) + method = self.getParameterValue(self.METHOD) + columns = self.getParameterValue(self.COLUMNS) + rows = self.getParameterValue(self.ROWS) + cellsizeX = self.getParameterValue(self.CELLSIZE_X) + cellsizeY = self.getParameterValue(self.CELLSIZE_Y) + extent = self.getParameterValue(self.EXTENT).split(',') + output = self.getOutputValue(self.OUTPUT_LAYER) + triangulation = self.getOutputValue(self.TRIANULATION_FILE) + + if not QgsWkbTypes.hasZ(layer.wkbType()): + raise GeoAlgorithmExecutionException( + self.tr('Geometries in input layer does not have Z coordinates.')) + + xMin = float(extent[0]) + xMax = float(extent[1]) + yMin = float(extent[2]) + yMax = float(extent[3]) + bbox = QgsRectangle(xMin, yMin, xMax, yMax) + + layerData = QgsInterpolator.LayerData() + layerData.vectorLayer = layer + layerData.zCoordInterpolation = True + layerData.interpolationAttribute = -1 + + if layerType == 0: + layerData.mInputType = QgsInterpolator.POINTS + elif layerType == 1: + layerData.mInputType = QgsInterpolator.STRUCTURE_LINES + else: + layerData.mInputType = QgsInterpolator.BREAK_LINES + + if method == 0: + interpolationMethod = QgsTINInterpolator.Linear + else: + interpolationMethod = QgsTINInterpolator.CloughTocher + + interpolator = QgsTINInterpolator([layerData], interpolationMethod) + interpolator.setExportTriangulationToFile(True) + interpolator.setTriangulationFilePath(triangulation) + + writer = QgsGridFileWriter(interpolator, + output, + bbox, + columns, + rows, + cellsizeX, + cellsizeY) + + writer.writeFile() From ca66951ab1bfbef387aaf9c96c6672d2c9203a31 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 11 Oct 2016 11:50:09 +0300 Subject: [PATCH 350/897] [processing] add icons for interpolation tools --- .../algs/qgis/IdwInterpolationAttribute.py | 9 +++++++++ .../algs/qgis/IdwInterpolationZValue.py | 9 +++++++++ .../algs/qgis/TinInterpolationAttribute.py | 9 +++++++++ .../algs/qgis/TinInterpolationZValue.py | 9 +++++++++ .../plugins/processing/images/interpolation.png | Bin 0 -> 617 bytes 5 files changed, 36 insertions(+) create mode 100644 python/plugins/processing/images/interpolation.png diff --git a/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py b/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py index 9e9598699fed..64a9fc72e72f 100644 --- a/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py +++ b/python/plugins/processing/algs/qgis/IdwInterpolationAttribute.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.core import QgsRectangle from qgis.analysis import (QgsInterpolator, QgsIDWInterpolator, @@ -40,6 +44,8 @@ from processing.core.outputs import OutputRaster from processing.tools import dataobjects +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class IdwInterpolationAttribute(GeoAlgorithm): @@ -54,6 +60,9 @@ class IdwInterpolationAttribute(GeoAlgorithm): EXTENT = 'EXTENT' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'interpolation.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('IDW interpolation (using attribute)') self.group, self.i18n_group = self.trAlgorithm('Interpolation') diff --git a/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py b/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py index 686f10e36279..4c81006265be 100644 --- a/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py +++ b/python/plugins/processing/algs/qgis/IdwInterpolationZValue.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.core import QgsRectangle, QgsWkbTypes from qgis.analysis import (QgsInterpolator, QgsIDWInterpolator, @@ -39,6 +43,8 @@ from processing.core.outputs import OutputRaster from processing.tools import dataobjects +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class IdwInterpolationZValue(GeoAlgorithm): @@ -52,6 +58,9 @@ class IdwInterpolationZValue(GeoAlgorithm): EXTENT = 'EXTENT' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'interpolation.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('IDW interpolation (using Z-values)') self.group, self.i18n_group = self.trAlgorithm('Interpolation') diff --git a/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py b/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py index a44fe25ccfc4..fdf4b30bda89 100644 --- a/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py +++ b/python/plugins/processing/algs/qgis/TinInterpolationAttribute.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.core import QgsRectangle from qgis.analysis import (QgsInterpolator, QgsTINInterpolator, @@ -41,6 +45,8 @@ from processing.core.outputs import OutputVector from processing.tools import dataobjects +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class TinInterpolationAttribute(GeoAlgorithm): @@ -56,6 +62,9 @@ class TinInterpolationAttribute(GeoAlgorithm): OUTPUT_LAYER = 'OUTPUT_LAYER' TRIANULATION_FILE = 'TRIANULATION_FILE' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'interpolation.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('TIN interpolation (using attribute)') self.group, self.i18n_group = self.trAlgorithm('Interpolation') diff --git a/python/plugins/processing/algs/qgis/TinInterpolationZValue.py b/python/plugins/processing/algs/qgis/TinInterpolationZValue.py index 1c26d097da97..332f6303f619 100644 --- a/python/plugins/processing/algs/qgis/TinInterpolationZValue.py +++ b/python/plugins/processing/algs/qgis/TinInterpolationZValue.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.core import QgsRectangle, QgsWkbTypes from qgis.analysis import (QgsInterpolator, QgsTINInterpolator, @@ -40,6 +44,8 @@ from processing.core.outputs import OutputVector from processing.tools import dataobjects +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class TinInterpolationZValue(GeoAlgorithm): @@ -54,6 +60,9 @@ class TinInterpolationZValue(GeoAlgorithm): OUTPUT_LAYER = 'OUTPUT_LAYER' TRIANULATION_FILE = 'TRIANULATION_FILE' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'interpolation.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('TIN interpolation (using Z-values)') self.group, self.i18n_group = self.trAlgorithm('Interpolation') diff --git a/python/plugins/processing/images/interpolation.png b/python/plugins/processing/images/interpolation.png new file mode 100644 index 0000000000000000000000000000000000000000..a12fa2dce6c08249644a560cdfb8af55f1ba1eb9 GIT binary patch literal 617 zcmeAS@N?(olHy`uVBq!ia0vp^5+KaM1|%Pp+x`GjEX7WqAsj$Z!;#Vf2?p zUk71ECym(^Ktah8*NBqf{Irtt#G+J&^73-M%)IR4K#ic8tEFC=o*>M-F77zs3r(x zj&puNWl?5&MhSznvw~wuNl|7}DM*iQa0bxHjyajxsR|h-B?VUc`pID9fKJKJ&CSm% z2KhigCo?%UuQ;_>KdDl;I8onN&px`r? zLjMvPHwXvvB|pkFIi`Aw>Cf7m$sS)s^6p%n+V&u1W#*LaS<7laU%LL1N4mG&_{2fc zBeO#`%;GQE^> z-QR!EdW-emU3oLafEH}9lPi1fFSAnmMO$X7*A1;hn$ukaCDy1*c6Sxr$gp|Rv{%?u zAmsZ0RUKIYT7e6trUWrQl`LKn#Ot-vVbZeYD_h>r>F(-t+i7=;*(mwzYUvX_SBs)l cjKkh<`BQV3d-?Szz>sI~boFyt=akR{0K4JsNdN!< literal 0 HcmV?d00001 From 010fc7c6404b42c7731e720b9120c7ac45b3fcfb Mon Sep 17 00:00:00 2001 From: rldhont Date: Wed, 19 Oct 2016 14:35:17 +0200 Subject: [PATCH 351/897] Fix [DB Manager] Allow lowercase field names for homogenize PostGIS Import --- python/plugins/db_manager/dlg_import_vector.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python/plugins/db_manager/dlg_import_vector.py b/python/plugins/db_manager/dlg_import_vector.py index 0eea6761f702..c8f87bcba8d4 100644 --- a/python/plugins/db_manager/dlg_import_vector.py +++ b/python/plugins/db_manager/dlg_import_vector.py @@ -78,6 +78,10 @@ def setupWorkingMode(self, mode): self.editPrimaryKey.setText(self.default_pk) self.editGeomColumn.setText(self.default_geom) + + self.chkLowercaseFieldNames.setEnabled(self.db.hasLowercaseFieldNamesOption()) + if not self.chkLowercaseFieldNames.isEnabled(): + self.chkLowercaseFieldNames.setChecked(False) else: # set default values self.checkSupports() From cf6004959e2a4f6bdd2e18bf2504008222c2c82d Mon Sep 17 00:00:00 2001 From: Mathieu Pellerin Date: Wed, 19 Oct 2016 19:58:23 +0700 Subject: [PATCH 352/897] [processing] ensure that outputs of vector overlay operations are multiparts (#3622) --- python/plugins/processing/algs/qgis/Clip.py | 2 +- python/plugins/processing/algs/qgis/Difference.py | 2 +- python/plugins/processing/algs/qgis/Intersection.py | 2 +- python/plugins/processing/algs/qgis/SymmetricalDifference.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/algs/qgis/Clip.py b/python/plugins/processing/algs/qgis/Clip.py index 5deeceeecfa5..0c9d17ad80bc 100644 --- a/python/plugins/processing/algs/qgis/Clip.py +++ b/python/plugins/processing/algs/qgis/Clip.py @@ -67,7 +67,7 @@ def processAlgorithm(self, progress): writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( source_layer.fields(), - source_layer.wkbType(), + QgsWkbTypes.multiType(source_layer.wkbType()), source_layer.crs()) # first build up a list of clip geometries diff --git a/python/plugins/processing/algs/qgis/Difference.py b/python/plugins/processing/algs/qgis/Difference.py index 71783562ab5d..9045757b41e7 100644 --- a/python/plugins/processing/algs/qgis/Difference.py +++ b/python/plugins/processing/algs/qgis/Difference.py @@ -69,7 +69,7 @@ def processAlgorithm(self, progress): self.getParameterValue(Difference.OVERLAY)) ignoreInvalid = self.getParameterValue(Difference.IGNORE_INVALID) - geomType = layerA.wkbType() + geomType = QgsWkbTypes.multiType(layerA.wkbType()) writer = self.getOutputFromName( Difference.OUTPUT).getVectorWriter(layerA.fields(), geomType, diff --git a/python/plugins/processing/algs/qgis/Intersection.py b/python/plugins/processing/algs/qgis/Intersection.py index b00bd2b7177d..2f42f5763df2 100644 --- a/python/plugins/processing/algs/qgis/Intersection.py +++ b/python/plugins/processing/algs/qgis/Intersection.py @@ -75,7 +75,7 @@ def processAlgorithm(self, progress): vlayerB = dataobjects.getObjectFromUri( self.getParameterValue(self.INPUT2)) - geomType = vlayerA.wkbType() + geomType = QgsWkbTypes.multiType(vlayerA.wkbType()) fields = vector.combineVectorFields(vlayerA, vlayerB) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, geomType, vlayerA.crs()) diff --git a/python/plugins/processing/algs/qgis/SymmetricalDifference.py b/python/plugins/processing/algs/qgis/SymmetricalDifference.py index 53138d7fef1f..098f7da0cca3 100644 --- a/python/plugins/processing/algs/qgis/SymmetricalDifference.py +++ b/python/plugins/processing/algs/qgis/SymmetricalDifference.py @@ -65,7 +65,7 @@ def processAlgorithm(self, progress): layerB = dataobjects.getObjectFromUri( self.getParameterValue(self.OVERLAY)) - geomType = layerA.wkbType() + geomType = QgsWkbTypes.multiType(layerA.wkbType()) fields = vector.combineVectorFields(layerA, layerB) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( fields, geomType, layerA.crs()) From 58f31f1a82d8fe1f9649495fb28f7b59266f2b9a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 12 Oct 2016 08:35:05 +0300 Subject: [PATCH 353/897] [processing] add tests for interpolation tools --- .../testdata/expected/add_geometry_pointz.gfs | 5 ++ .../testdata/expected/add_geometry_pointz.gml | 11 ++- .../tests/testdata/expected/triangulation.gfs | 14 +++ .../tests/testdata/expected/triangulation.gml | 89 +++++++++++++++++++ .../processing/tests/testdata/pointsz.gfs | 5 ++ .../processing/tests/testdata/pointsz.gml | 9 ++ .../tests/testdata/qgis_algorithm_tests.yaml | 82 ++++++++++++++++- 7 files changed, 212 insertions(+), 3 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/triangulation.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/triangulation.gml diff --git a/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs index ffe1b014dc4b..493600d875b1 100644 --- a/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs +++ b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gfs @@ -11,6 +11,11 @@ -5.00000 3.00000 + + elev + elev + Integer + xcoord xcoord diff --git a/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml index d02f6d18f20b..d1918bb6d581 100644 --- a/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml +++ b/python/plugins/processing/tests/testdata/expected/add_geometry_pointz.gml @@ -10,10 +10,11 @@ 837 - + 1,1,3 + 3 1 1 3 @@ -22,6 +23,7 @@ 3,3,0 + 0 3 3 0 @@ -30,6 +32,7 @@ 2,2,2 + 2 2 2 2 @@ -38,6 +41,7 @@ 5,2,0 + 0 5 2 0 @@ -46,6 +50,7 @@ 4,1,0 + 0 4 1 0 @@ -54,6 +59,7 @@ 0,-5,5 + 5 0 -5 5 @@ -62,6 +68,7 @@ 8,-1,7 + 7 8 -1 7 @@ -70,6 +77,7 @@ 7,-1,6 + 6 7 -1 6 @@ -78,6 +86,7 @@ 0,-1,4 + 4 0 -1 4 diff --git a/python/plugins/processing/tests/testdata/expected/triangulation.gfs b/python/plugins/processing/tests/testdata/expected/triangulation.gfs new file mode 100644 index 000000000000..ce4a0be568ea --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/triangulation.gfs @@ -0,0 +1,14 @@ + + + triangulation + triangulation + 2 + + 15 + 0.00000 + 8.00000 + -5.00000 + 3.00000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/triangulation.gml b/python/plugins/processing/tests/testdata/expected/triangulation.gml new file mode 100644 index 000000000000..09c0b3da500b --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/triangulation.gml @@ -0,0 +1,89 @@ + + + + + 0-5 + 83 + + + + + + 4,1 1,1 + + + + + 3,3 1,1 + + + + + 3,3 4,1 + + + + + 5,2 4,1 + + + + + 3,3 5,2 + + + + + 4,1 0,-1 + + + + + 4,1 0,-5 + + + + + 7,-1 5,2 + + + + + 0,-1 1,1 + + + + + 0,-5 0,-1 + + + + + 8,-1 0,-5 + + + + + 5,2 8,-1 + + + + + 0,-5 7,-1 + + + + + 8,-1 7,-1 + + + + + 4,1 7,-1 + + + diff --git a/python/plugins/processing/tests/testdata/pointsz.gfs b/python/plugins/processing/tests/testdata/pointsz.gfs index 770d77f10f1c..2ccfac7377b3 100644 --- a/python/plugins/processing/tests/testdata/pointsz.gfs +++ b/python/plugins/processing/tests/testdata/pointsz.gfs @@ -11,5 +11,10 @@ -5.00000 3.00000 + + elev + elev + Integer + diff --git a/python/plugins/processing/tests/testdata/pointsz.gml b/python/plugins/processing/tests/testdata/pointsz.gml index 83d588b347dd..ede57d47f0dc 100644 --- a/python/plugins/processing/tests/testdata/pointsz.gml +++ b/python/plugins/processing/tests/testdata/pointsz.gml @@ -14,46 +14,55 @@ 1,1,3 + 3 3,3,0 + 0 2,2,2 + 2 5,2,0 + 0 4,1,0 + 0 0,-5,5 + 5 8,-1,7 + 7 7,-1,6 + 6 0,-1,4 + 4 diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 6cc5909acec4..f3a13971f3ea 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -871,7 +871,6 @@ tests: name: expected/single_sided_buffer_multiline_bevel.gml type: vector - - algorithm: qgis:extractnodes name: Test (qgis:extractnodes) params: @@ -1006,7 +1005,6 @@ tests: name: expected/add_geometry_pointz.gml type: vector - - algorithm: qgis:countpointsinpolygon name: Count points in polygon params: @@ -1124,3 +1122,83 @@ tests: OUTPUT: name: expected/multipoint_delaunay.gml type: vector + + - algorithm: qgis:idwinterpolationusingattribute + name: IDW interpolation using attribute + params: + ATTRIBUTE: elev + CELLSIZE_X: 0.02667 + CELLSIZE_Y: 0.02667 + COLUMNS: 300 + DISTANCE_COEFFICIENT: 2.0 + EXTENT: 0, 8, -5, 3 + INPUT_LAYER: + name: pointsz.gml + type: vector + LAYER_TYPE: '0' + ROWS: 300 + results: + OUTPUT_LAYER: + hash: 56d2671d50444f8571affba3f9e585830b82af5e380394178f521065 + type: rasterhash + + - algorithm: qgis:idwinterpolationusingzvalues + name: IDW interpolation using Z value + params: + CELLSIZE_X: 0.02667 + CELLSIZE_Y: 0.02667 + COLUMNS: 300 + DISTANCE_COEFFICIENT: 2.0 + EXTENT: 0, 8, -5, 3 + INPUT_LAYER: + name: pointsz.gml + type: vector + LAYER_TYPE: '0' + ROWS: 300 + results: + OUTPUT_LAYER: + hash: 56d2671d50444f8571affba3f9e585830b82af5e380394178f521065 + type: rasterhash + + - algorithm: qgis:tininterpolationusingattribute + name: TIN interpolation using attribute + params: + ATTRIBUTE: elev + CELLSIZE_X: 0.02667 + CELLSIZE_Y: 0.02667 + COLUMNS: 300 + EXTENT: 0, 8, -5, 3 + INPUT_LAYER: + name: pointsz.gml + type: vector + LAYER_TYPE: '0' + METHOD: '0' + ROWS: 300 + results: + OUTPUT_LAYER: + hash: 87f40be6ec08f3fcbb5707762de71f6be35bb265c61f594335562a26 + type: rasterhash + #TRIANULATION_FILE: + # name: expected/triangulation.gml + # type: vector + + - algorithm: qgis:tininterpolationusingzvalues + name: TIN interpolation using Z value + params: + CELLSIZE_X: 0.02667 + CELLSIZE_Y: 0.02667 + COLUMNS: 300 + EXTENT: 0, 8, -5, 3 + INPUT_LAYER: + name: pointsz.gml + type: vector + LAYER_TYPE: '0' + METHOD: '1' + ROWS: 300 + results: + OUTPUT_LAYER: + hash: 5e14dd0b879884b8b8da56c082947dad681feb4e9f1137f5cda126f8 + type: rasterhash + #TRIANULATION_FILE: + # name: expected/triangulation.gml + # type: vector From c9251c5793ed0948185f88eadf8b1737d65e06fe Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 20 Oct 2016 07:39:07 +1000 Subject: [PATCH 354/897] Avoid creating multiple render contexts when calculating legend node size Partial fix for qgis slowdown when using layer with large number of legend nodes --- python/core/layertree/qgslayertreemodel.sip | 2 +- .../layertree/qgslayertreemodellegendnode.sip | 17 ++++++++++++-- src/core/layertree/qgslayertreemodel.cpp | 22 +++++++++++++++++-- src/core/layertree/qgslayertreemodel.h | 8 ++++++- .../layertree/qgslayertreemodellegendnode.cpp | 12 ++++++---- .../layertree/qgslayertreemodellegendnode.h | 17 ++++++++++++-- 6 files changed, 66 insertions(+), 12 deletions(-) diff --git a/python/core/layertree/qgslayertreemodel.sip b/python/core/layertree/qgslayertreemodel.sip index 89dc3dfa9224..f5ea1064db0f 100644 --- a/python/core/layertree/qgslayertreemodel.sip +++ b/python/core/layertree/qgslayertreemodel.sip @@ -166,7 +166,7 @@ class QgsLayerTreeModel : QAbstractItemModel //! Get hints about map view - to be used in legend nodes. Arguments that are not null will receive values. //! If there are no valid map view data (from previous call to setLegendMapViewData()), returned values are zeros. //! @note added in 2.6 - void legendMapViewData( double *mapUnitsPerPixel /Out/, int *dpi /Out/, double *scale /Out/ ); + void legendMapViewData( double *mapUnitsPerPixel /Out/, int *dpi /Out/, double *scale /Out/ ) const; //! Get map of map layer style overrides (key: layer ID, value: style name) where a different style should be used instead of the current one //! @note added in 2.10 diff --git a/python/core/layertree/qgslayertreemodellegendnode.sip b/python/core/layertree/qgslayertreemodellegendnode.sip index 9332867f8bf7..99ba2971aa16 100644 --- a/python/core/layertree/qgslayertreemodellegendnode.sip +++ b/python/core/layertree/qgslayertreemodellegendnode.sip @@ -141,10 +141,23 @@ class QgsSymbolLegendNode : QgsLayerTreeModelLegendNode //! @note added in 2.10 QSize iconSize() const; - //! Get the minimum icon size to prevent cropping - //! @note added in 2.10 + /** + * Calculates the minimum icon size to prevent cropping. When evaluating + * the size for multiple icons it is more efficient to create a single + * render context in advance and use the variant which accepts a QgsRenderContext + * argument. + * @note added in 2.10 + */ QSize minimumIconSize() const; + /** + * Calculates the minimum icon size to prevent cropping. When evaluating + * the size for multiple icons it is more efficient to create a single + * render context in advance and call this method instead of minimumIconSize(). + * @note added in QGIS 2.18 + */ + QSize minimumIconSize( QgsRenderContext &context ) const; + /** Returns the symbol used by the legend node. * @see setSymbol() * @note added in QGIS 2.14 diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index 57bb9e82f931..e170d1f9ffbf 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -663,7 +663,7 @@ void QgsLayerTreeModel::setLegendMapViewData( double mapUnitsPerPixel, int dpi, refreshScaleBasedLayers(); } -void QgsLayerTreeModel::legendMapViewData( double* mapUnitsPerPixel, int* dpi, double* scale ) +void QgsLayerTreeModel::legendMapViewData( double* mapUnitsPerPixel, int* dpi, double* scale ) const { if ( mapUnitsPerPixel ) *mapUnitsPerPixel = mLegendMapViewMupp; if ( dpi ) *dpi = mLegendMapViewDpi; @@ -1269,6 +1269,22 @@ void QgsLayerTreeModel::tryBuildLegendTree( LayerLegendData& data ) } } +QgsRenderContext* QgsLayerTreeModel::createTemporaryRenderContext() const +{ + double scale = 0.0; + double mupp = 0.0; + int dpi = 0; + legendMapViewData( &mupp, &dpi, &scale ); + bool validData = !qgsDoubleNear( mupp, 0.0 ) && dpi != 0 && !qgsDoubleNear( scale, 0.0 ); + + // setup temporary render context + QScopedPointer context( new QgsRenderContext ); + context->setScaleFactor( dpi / 25.4 ); + context->setRendererScale( scale ); + context->setMapToPixel( QgsMapToPixel( mupp ) ); + return validData ? context.take() : nullptr; +} + QgsLayerTreeModelLegendNode* QgsLayerTreeModel::index2legendNode( const QModelIndex& index ) { @@ -1470,6 +1486,8 @@ void QgsLayerTreeModel::invalidateLegendMapBasedData() // we do that here because for symbols with size defined in map units // the symbol sizes changes depends on the zoom level + QScopedPointer context( createTemporaryRenderContext() ); + Q_FOREACH ( const LayerLegendData& data, mLegend ) { QList symbolNodes; @@ -1479,7 +1497,7 @@ void QgsLayerTreeModel::invalidateLegendMapBasedData() QgsSymbolLegendNode* n = dynamic_cast( legendNode ); if ( n ) { - const QSize sz( n->minimumIconSize() ); + const QSize sz( n->minimumIconSize( *context ) ); const QString parentKey( n->data( QgsLayerTreeModelLegendNode::ParentRuleKeyRole ).toString() ); widthMax[parentKey] = qMax( sz.width(), widthMax.contains( parentKey ) ? widthMax[parentKey] : 0 ); n->setIconSize( sz ); diff --git a/src/core/layertree/qgslayertreemodel.h b/src/core/layertree/qgslayertreemodel.h index 1cf6498076a7..7095803cd257 100644 --- a/src/core/layertree/qgslayertreemodel.h +++ b/src/core/layertree/qgslayertreemodel.h @@ -31,6 +31,7 @@ class QgsMapHitTest; class QgsMapLayer; class QgsMapSettings; class QgsExpression; +class QgsRenderContext; /** \ingroup core * The QgsLayerTreeModel class is model implementation for Qt item views framework. @@ -191,7 +192,7 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel //! Get hints about map view - to be used in legend nodes. Arguments that are not null will receive values. //! If there are no valid map view data (from previous call to setLegendMapViewData()), returned values are zeros. //! @note added in 2.6 - void legendMapViewData( double *mapUnitsPerPixel, int *dpi, double *scale ); + void legendMapViewData( double *mapUnitsPerPixel, int *dpi, double *scale ) const; //! Get map of map layer style overrides (key: layer ID, value: style name) where a different style should be used instead of the current one //! @note added in 2.10 @@ -328,6 +329,11 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel int mLegendMapViewDpi; double mLegendMapViewScale; QTimer mDeferLegendInvalidationTimer; + + private: + + //! Returns a temporary render context + QgsRenderContext* createTemporaryRenderContext() const; }; Q_DECLARE_OPERATORS_FOR_FLAGS( QgsLayerTreeModel::Flags ) diff --git a/src/core/layertree/qgslayertreemodellegendnode.cpp b/src/core/layertree/qgslayertreemodellegendnode.cpp index 721b7f49655a..ab751f23bccb 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.cpp +++ b/src/core/layertree/qgslayertreemodellegendnode.cpp @@ -157,23 +157,27 @@ Qt::ItemFlags QgsSymbolLegendNode::flags() const QSize QgsSymbolLegendNode::minimumIconSize() const +{ + QScopedPointer context( createTemporaryRenderContext() ); + return minimumIconSize( *context ); +} + +QSize QgsSymbolLegendNode::minimumIconSize( QgsRenderContext& context ) const { QSize minSz( 16, 16 ); if ( mItem.symbol() && mItem.symbol()->type() == QgsSymbol::Marker ) { - QScopedPointer context( createTemporaryRenderContext() ); minSz = QgsImageOperation::nonTransparentImageRect( QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( 512, 512 ), - context.data() ).toImage(), + &context ).toImage(), minSz, true ).size(); } else if ( mItem.symbol() && mItem.symbol()->type() == QgsSymbol::Line ) { - QScopedPointer context( createTemporaryRenderContext() ); minSz = QgsImageOperation::nonTransparentImageRect( QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( minSz.width(), 512 ), - context.data() ).toImage(), + &context ).toImage(), minSz, true ).size(); } diff --git a/src/core/layertree/qgslayertreemodellegendnode.h b/src/core/layertree/qgslayertreemodellegendnode.h index 906892aff4cd..66fdc94b59ac 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.h +++ b/src/core/layertree/qgslayertreemodellegendnode.h @@ -171,10 +171,23 @@ class CORE_EXPORT QgsSymbolLegendNode : public QgsLayerTreeModelLegendNode //! @note added in 2.10 QSize iconSize() const { return mIconSize; } - //! Get the minimum icon size to prevent cropping - //! @note added in 2.10 + /** + * Calculates the minimum icon size to prevent cropping. When evaluating + * the size for multiple icons it is more efficient to create a single + * render context in advance and use the variant which accepts a QgsRenderContext + * argument. + * @note added in 2.10 + */ QSize minimumIconSize() const; + /** + * Calculates the minimum icon size to prevent cropping. When evaluating + * the size for multiple icons it is more efficient to create a single + * render context in advance and call this method instead of minimumIconSize(). + * @note added in QGIS 2.18 + */ + QSize minimumIconSize( QgsRenderContext &context ) const; + /** Returns the symbol used by the legend node. * @see setSymbol() * @note added in QGIS 2.14 From 8c7d772f22339495f9650554cd23a99a39a8702d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 20 Oct 2016 08:21:33 +1000 Subject: [PATCH 355/897] Further optimisations to nonTransparentImageRect calculation --- src/core/effects/qgsimageoperation.cpp | 57 ++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/src/core/effects/qgsimageoperation.cpp b/src/core/effects/qgsimageoperation.cpp index ed05c760e57e..3f74133d26f7 100644 --- a/src/core/effects/qgsimageoperation.cpp +++ b/src/core/effects/qgsimageoperation.cpp @@ -806,19 +806,62 @@ QRect QgsImageOperation::nonTransparentImageRect( const QImage &image, QSize min int ymin = height; int ymax = 0; - for ( int x = 0; x < width; ++x ) + // scan down till we hit something + for ( int y = 0; y < height; ++y ) { - for ( int y = 0; y < height; ++y ) + const QRgb* imgScanline = reinterpret_cast< const QRgb* >( image.constScanLine( y ) ); + for ( int x = 0; x < width; ++x ) + { + if ( qAlpha( imgScanline[x] ) ) + { + ymin = y; + xmin = x; + xmax = x; + } + } + } + + //scan up till we hit something + for ( int y = height - 1; y > ymin; --y ) + { + const QRgb* imgScanline = reinterpret_cast< const QRgb* >( image.constScanLine( y ) ); + for ( int x = 0; x < width; ++x ) + { + if ( qAlpha( imgScanline[x] ) ) + { + ymax = y; + xmin = qMin( xmin, x ); + xmax = qMax( xmax, x ); + } + } + } + + //scan left to right till we hit something, using a refined y region + for ( int y = ymin; y <= ymax; ++y ) + { + const QRgb* imgScanline = reinterpret_cast< const QRgb* >( image.constScanLine( y ) ); + for ( int x = 0; x < xmin; ++x ) { - if ( qAlpha( image.pixel( x, y ) ) ) + if ( qAlpha( imgScanline[x] ) ) { - xmin = qMin( x, xmin ); - xmax = qMax( x, xmax ); - ymin = qMin( y, ymin ); - ymax = qMax( y, ymax ); + xmin = x; } } } + + //scan right to left till we hit something, using the refined y region + for ( int y = ymin; y <= ymax; ++y ) + { + const QRgb* imgScanline = reinterpret_cast< const QRgb* >( image.constScanLine( y ) ); + for ( int x = width - 1; x > xmax; --x ) + { + if ( qAlpha( imgScanline[x] ) ) + { + xmax = x; + } + } + } + if ( minSize.isValid() ) { if ( xmax - xmin < minSize.width() ) // centers image on x From 1e7018f0ccde01fce8fb5142970ee155dbfcb372 Mon Sep 17 00:00:00 2001 From: Manuel Grizonnet Date: Mon, 22 Aug 2016 16:04:41 +0200 Subject: [PATCH 356/897] TEST: add test of OTB BandMath application in processing --- .../plugins/processing/tests/CMakeLists.txt | 2 + .../processing/tests/OTBAlgorithmsTest.py | 58 ++++++++++++++++++ .../processing/tests/data/raster.tif.aux.xml | 20 ++++++ .../testdata/expected/otb/raster_bandmath.tif | Bin 0 -> 1315 bytes .../expected/otb/raster_bandmath.tif.aux.xml | 10 +++ .../tests/testdata/otb_algorithm_tests.yaml | 18 ++++++ 6 files changed, 108 insertions(+) create mode 100644 python/plugins/processing/tests/OTBAlgorithmsTest.py create mode 100644 python/plugins/processing/tests/data/raster.tif.aux.xml create mode 100644 python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif create mode 100644 python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml create mode 100644 python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml diff --git a/python/plugins/processing/tests/CMakeLists.txt b/python/plugins/processing/tests/CMakeLists.txt index 3cf8fa4c2316..f27ea0289ade 100644 --- a/python/plugins/processing/tests/CMakeLists.txt +++ b/python/plugins/processing/tests/CMakeLists.txt @@ -12,4 +12,6 @@ IF(ENABLE_TESTS) ADD_PYTHON_TEST(ProcessingGdalAlgorithmsTest GdalAlgorithmsTest.py) ADD_PYTHON_TEST(ProcessingGrass7AlgorithmsImageryTest Grass7AlgorithmsImageryTest.py) ADD_PYTHON_TEST(ProcessingGrass7AlgorithmsRasterTest Grass7AlgorithmsRasterTest.py) + #TODO uncomment when OTB is installed on Travis CI instance + #ADD_PYTHON_TEST(ProcessingOTBAlgorithmsTest OTBAlgorithmsTest.py) ENDIF(ENABLE_TESTS) diff --git a/python/plugins/processing/tests/OTBAlgorithmsTest.py b/python/plugins/processing/tests/OTBAlgorithmsTest.py new file mode 100644 index 000000000000..0d2d3585d1bb --- /dev/null +++ b/python/plugins/processing/tests/OTBAlgorithmsTest.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + OTBAlgorithmTests.py + --------------------- + Date : August 2016 + Copyright : (C) 2016 by Manuel Grizonnet + Email : manuel.grizonnet@cnes.fr +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Manuel Grizonnet' +__date__ = 'August 2016' +__copyright__ = '(C) 2016, Manuel Grizonnet' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = ':%H$' + +import AlgorithmsTestBase + +import nose2 +import shutil + +from qgis.testing import ( + start_app, + unittest +) + + +class TestOTBAlgorithms(unittest.TestCase, AlgorithmsTestBase.AlgorithmsTest): + + @classmethod + def setUpClass(cls): + start_app() + from processing.core.Processing import Processing + Processing.initialize() + cls.cleanup_paths = [] + + @classmethod + def tearDownClass(cls): + for path in cls.cleanup_paths: + shutil.rmtree(path) + + def test_definition_file(self): + return 'otb_algorithm_tests.yaml' + + +if __name__ == '__main__': + nose2.main() diff --git a/python/plugins/processing/tests/data/raster.tif.aux.xml b/python/plugins/processing/tests/data/raster.tif.aux.xml new file mode 100644 index 000000000000..abf1b4b7c636 --- /dev/null +++ b/python/plugins/processing/tests/data/raster.tif.aux.xml @@ -0,0 +1,20 @@ + + + + + 825.8245192307693 + 899.1754807692307 + 208 + 0 + 0 + 4|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|6|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|6|0|0|0|0|0|4|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|9|0|0|0|0|0|6|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|10|0|0|0|0|4|0|0|0|0|0|0|0|0|6|0|0|0|0|9|0|0|0|0|0|6|0|0|0|0|0|0|0|0|0|0|4|0|0|9|0|0|0|0|0|0|0|0|0|0|0|0|0|6|0|0|0|0|0|6|0|0|6|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|13|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|6 + + + + 899 + 865.86666666667 + 826 + 17.808206597584 + + + diff --git a/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif b/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif new file mode 100644 index 0000000000000000000000000000000000000000..ceed156090f5705db71a5c3446eb8e85bba8d31e GIT binary patch literal 1315 zcmebD)MDUZU|C#kkkkZ2*+5|izGfZ<5Pb`Xn_74n*nspWAYR|j%%B3Km4N1NXoslD z0ouT2mQp-ht2qV7eg!LOaAAaCI>?P|#Nh4e?c|%FjzxFgEb30g2Tx=o%ZDn^}O> aGceRULok#}GDWF=k}Vw7Fd72GA_M^5Juo%^ literal 0 HcmV?d00001 diff --git a/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml b/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml new file mode 100644 index 000000000000..3ae89ceffcc6 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml @@ -0,0 +1,10 @@ + + + + 255 + 4.5535714285714 + 0 + 33.770189539453 + + + diff --git a/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml new file mode 100644 index 000000000000..07689c5d129e --- /dev/null +++ b/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml @@ -0,0 +1,18 @@ +# See ../README.md for a description of the file format + +tests: + - algorithm: otb:bandmath + name: Test (otb:bandmath) + params: + !!python/unicode '-exp': im1b1==826?255:0 + !!python/unicode '-il': + params: + - name: raster.tif + type: raster + type: multi + !!python/unicode '-ram': 128 + results: + !!python/unicode '-out': + hash: a8acb8da3cf40a156fe26f815588a7cbf8f3c8f6b3c226968b1eab1e + type: rasterhash + From afea25bda2b30f97b354d17fc5b18c9db0b03be2 Mon Sep 17 00:00:00 2001 From: Manuel Grizonnet Date: Tue, 23 Aug 2016 10:14:51 +0200 Subject: [PATCH 357/897] BUG: add version 5.4 to supported version --- python/plugins/processing/algs/otb/OTBUtils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/otb/OTBUtils.py b/python/plugins/processing/algs/otb/OTBUtils.py index 0a34407d4b10..dca0ed151a7b 100644 --- a/python/plugins/processing/algs/otb/OTBUtils.py +++ b/python/plugins/processing/algs/otb/OTBUtils.py @@ -143,7 +143,7 @@ def getInstalledVersion(runOtb=False): def compatibleDescriptionPath(version): - supportedVersions = {"5.0.0": "5.0.0", "5.6.0": "5.6.0"} + supportedVersions = {"5.0.0": "5.0.0", "5.4.0": "5.4.0", "5.6.0": "5.6.0"} if version is None: return None if version not in supportedVersions: From a7d4b19fc9acf317b31594c5ea6f9cf286832cd3 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 20 Oct 2016 09:22:36 +0300 Subject: [PATCH 358/897] update readme for otb maintenance script --- python/plugins/processing/algs/otb/maintenance/README | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/algs/otb/maintenance/README b/python/plugins/processing/algs/otb/maintenance/README index 487759026cdb..9ee567ae0c51 100644 --- a/python/plugins/processing/algs/otb/maintenance/README +++ b/python/plugins/processing/algs/otb/maintenance/README @@ -9,9 +9,9 @@ Set OTB environment -------------------- export PYTHONPATH=/path/to/OTB/install/lib/otb/python/:$PYTHONPATH -# Environment variable for old OTB versions +# Environment variable for old OTB versions (< 5.2) export ITK_AUTOLOAD_PATH=/path/to/OTB/install/lib/otb/applications/ -# Environment variable for new OTB versions +# Environment variable for new OTB versions (>= 5.2) export OTB_APPLICATION_PATH=/path/to/OTB/install/lib/otb/applications/ # Set LD_LIBRARY_PATH export LD_LIBRARY_PATH=/path/to/OTB/install/lib/:$LD_LIBRARY_PATH @@ -19,7 +19,7 @@ export LD_LIBRARY_PATH=/path/to/OTB/install/lib/:$LD_LIBRARY_PATH Set QGIS environment --------------------- export QGIS_PREFIX_PATH=/path/to/QGIS/install -export PYTHONPATH=:/usr/share/qgis/python/plugins:~/.qgis3/python/plugins:$PYTHONPATH +export PYTHONPATH=$QGIS_PREFIX_PATH/share/qgis/python:$QGIS_PREFIX_PATH/share/qgis/python/plugins:$PYTHONPATH # Set LD_LIBRARY_PATH export LD_LIBRARY_PATH=$QGIS_PREFIX_PATH/lib/:$LD_LIBRARY_PATH # Add maintenance folder to python path From d4f410a30764362248318577af6a9a710d2c6360 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 20 Oct 2016 09:23:09 +0300 Subject: [PATCH 359/897] Install OTB in QGIS Travis CI script to be able to run OTB test --- python/plugins/processing/tests/CMakeLists.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python/plugins/processing/tests/CMakeLists.txt b/python/plugins/processing/tests/CMakeLists.txt index f27ea0289ade..a1ac75d3617f 100644 --- a/python/plugins/processing/tests/CMakeLists.txt +++ b/python/plugins/processing/tests/CMakeLists.txt @@ -12,6 +12,5 @@ IF(ENABLE_TESTS) ADD_PYTHON_TEST(ProcessingGdalAlgorithmsTest GdalAlgorithmsTest.py) ADD_PYTHON_TEST(ProcessingGrass7AlgorithmsImageryTest Grass7AlgorithmsImageryTest.py) ADD_PYTHON_TEST(ProcessingGrass7AlgorithmsRasterTest Grass7AlgorithmsRasterTest.py) - #TODO uncomment when OTB is installed on Travis CI instance - #ADD_PYTHON_TEST(ProcessingOTBAlgorithmsTest OTBAlgorithmsTest.py) + ADD_PYTHON_TEST(ProcessingOTBAlgorithmsTest OTBAlgorithmsTest.py) ENDIF(ENABLE_TESTS) From 3212d393c10e2e0da9ab7870dc9d919e9b8051cf Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 20 Oct 2016 13:23:21 +0700 Subject: [PATCH 360/897] [symbology] prevent creation of a zero width/height line pattern image (fixes #15728) --- src/core/symbology-ng/qgsfillsymbollayer.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/symbology-ng/qgsfillsymbollayer.cpp b/src/core/symbology-ng/qgsfillsymbollayer.cpp index cc63c7e4251c..0baa7acb0c8c 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.cpp +++ b/src/core/symbology-ng/qgsfillsymbollayer.cpp @@ -2654,7 +2654,8 @@ void QgsLinePatternFillSymbolLayer::applyPattern( const QgsSymbolRenderContext& width += 2 * xBuffer; height += 2 * yBuffer; - if ( width > 10000 || height > 10000 ) //protect symbol layer from eating too much memory + //protect from zero width/height image and symbol layer from eating too much memory + if ( width > 10000 || height > 10000 || width == 0 || height == 0 ) { return; } From 7b22f5d8da7ae3e994b318215d3aa9ea119db301 Mon Sep 17 00:00:00 2001 From: Manuel Grizonnet Date: Tue, 23 Aug 2016 18:43:43 +0200 Subject: [PATCH 361/897] TEST: add a test for otb conversion application (simpler than bandmath) --- .../testdata/expected/otb/raster_convert.tif | Bin 0 -> 1315 bytes .../tests/testdata/otb_algorithm_tests.yaml | 24 ++++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/otb/raster_convert.tif diff --git a/python/plugins/processing/tests/testdata/expected/otb/raster_convert.tif b/python/plugins/processing/tests/testdata/expected/otb/raster_convert.tif new file mode 100644 index 0000000000000000000000000000000000000000..a985aa5636f13df574b76254243006867fc58328 GIT binary patch literal 1315 zcmebD)MDUZU|C#kkkkZ2*+5|izGfZ<5Pb`Xn_74n*nspWAYR|j%%B3Km4N1NXoslD z0ouT2mQp-ht2qV7eg!LOaAAaCI>?P|#Nh4e?c|%FjzxFgEb30g2Tx=o%ZDn^^$W zH!wV^sILcM-#!F>IJdqYgiF^VFvs5ddJqQbLB^Eo|1-0`9)u^XL|~Pj_4Ocp^cVsw z-K(z$VPv~O?19z~bL)dc_4P1Za;d%^gxMb1kwNhLomAi1Faw3JtK(^09aCW;s5{u literal 0 HcmV?d00001 diff --git a/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml index 07689c5d129e..785166eaa630 100644 --- a/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/otb_algorithm_tests.yaml @@ -1,18 +1,20 @@ # See ../README.md for a description of the file format tests: - - algorithm: otb:bandmath - name: Test (otb:bandmath) + + - algorithm: otb:imageconversion + name: Test (otb:imageconversion) params: - !!python/unicode '-exp': im1b1==826?255:0 - !!python/unicode '-il': - params: - - name: raster.tif - type: raster - type: multi - !!python/unicode '-ram': 128 + -hcp.high: 2 + -hcp.low: 2 + -in: + name: raster.tif + type: raster + -ram: 128 + -type: '1' + -type.linear.gamma: 1 results: - !!python/unicode '-out': - hash: a8acb8da3cf40a156fe26f815588a7cbf8f3c8f6b3c226968b1eab1e + -out: + hash: b3657f4d848b64f688db41638ea6d86d9de1d0a169bc1bafef8af82a type: rasterhash From bc30cdf41d2698e7404a24c39d793f2a7b735981 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 20 Oct 2016 17:32:06 +1000 Subject: [PATCH 362/897] Followup c9251c, fix crash --- python/core/layertree/qgslayertreemodellegendnode.sip | 2 +- src/core/layertree/qgslayertreemodel.cpp | 2 +- src/core/layertree/qgslayertreemodellegendnode.cpp | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/python/core/layertree/qgslayertreemodellegendnode.sip b/python/core/layertree/qgslayertreemodellegendnode.sip index 99ba2971aa16..689bbd37dfb4 100644 --- a/python/core/layertree/qgslayertreemodellegendnode.sip +++ b/python/core/layertree/qgslayertreemodellegendnode.sip @@ -156,7 +156,7 @@ class QgsSymbolLegendNode : QgsLayerTreeModelLegendNode * render context in advance and call this method instead of minimumIconSize(). * @note added in QGIS 2.18 */ - QSize minimumIconSize( QgsRenderContext &context ) const; + QSize minimumIconSize( QgsRenderContext* context ) const; /** Returns the symbol used by the legend node. * @see setSymbol() diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index e170d1f9ffbf..3d325dfc0963 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -1497,7 +1497,7 @@ void QgsLayerTreeModel::invalidateLegendMapBasedData() QgsSymbolLegendNode* n = dynamic_cast( legendNode ); if ( n ) { - const QSize sz( n->minimumIconSize( *context ) ); + const QSize sz( n->minimumIconSize( context.data() ) ); const QString parentKey( n->data( QgsLayerTreeModelLegendNode::ParentRuleKeyRole ).toString() ); widthMax[parentKey] = qMax( sz.width(), widthMax.contains( parentKey ) ? widthMax[parentKey] : 0 ); n->setIconSize( sz ); diff --git a/src/core/layertree/qgslayertreemodellegendnode.cpp b/src/core/layertree/qgslayertreemodellegendnode.cpp index ab751f23bccb..fc232c010c8d 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.cpp +++ b/src/core/layertree/qgslayertreemodellegendnode.cpp @@ -159,17 +159,17 @@ Qt::ItemFlags QgsSymbolLegendNode::flags() const QSize QgsSymbolLegendNode::minimumIconSize() const { QScopedPointer context( createTemporaryRenderContext() ); - return minimumIconSize( *context ); + return minimumIconSize( context.data() ); } -QSize QgsSymbolLegendNode::minimumIconSize( QgsRenderContext& context ) const +QSize QgsSymbolLegendNode::minimumIconSize( QgsRenderContext* context ) const { QSize minSz( 16, 16 ); if ( mItem.symbol() && mItem.symbol()->type() == QgsSymbol::Marker ) { minSz = QgsImageOperation::nonTransparentImageRect( QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( 512, 512 ), - &context ).toImage(), + context ).toImage(), minSz, true ).size(); } @@ -177,7 +177,7 @@ QSize QgsSymbolLegendNode::minimumIconSize( QgsRenderContext& context ) const { minSz = QgsImageOperation::nonTransparentImageRect( QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( minSz.width(), 512 ), - &context ).toImage(), + context ).toImage(), minSz, true ).size(); } From 02fc2b08585a0715622bed728a8248f80b6c229d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 20 Oct 2016 17:38:19 +1000 Subject: [PATCH 363/897] Fix missing commit --- src/core/layertree/qgslayertreemodellegendnode.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/layertree/qgslayertreemodellegendnode.h b/src/core/layertree/qgslayertreemodellegendnode.h index 66fdc94b59ac..138574f8ec30 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.h +++ b/src/core/layertree/qgslayertreemodellegendnode.h @@ -186,7 +186,7 @@ class CORE_EXPORT QgsSymbolLegendNode : public QgsLayerTreeModelLegendNode * render context in advance and call this method instead of minimumIconSize(). * @note added in QGIS 2.18 */ - QSize minimumIconSize( QgsRenderContext &context ) const; + QSize minimumIconSize( QgsRenderContext* context ) const; /** Returns the symbol used by the legend node. * @see setSymbol() From 69e8da0fb1b5d7ca0d37bdc0055c2a599b1f2e3a Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 20 Oct 2016 15:02:59 +0700 Subject: [PATCH 364/897] [composer] fix attribute table widget connect warning --- src/app/composer/qgscomposerattributetablewidget.cpp | 4 ++-- src/app/composer/qgscomposerattributetablewidget.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/composer/qgscomposerattributetablewidget.cpp b/src/app/composer/qgscomposerattributetablewidget.cpp index f21e5240b541..12ed6eaff16f 100644 --- a/src/app/composer/qgscomposerattributetablewidget.cpp +++ b/src/app/composer/qgscomposerattributetablewidget.cpp @@ -66,7 +66,7 @@ QgsComposerAttributeTableWidget::QgsComposerAttributeTableWidget( QgsComposerAtt mComposerMapComboBox->setComposition( mComposerTable->composition() ); mComposerMapComboBox->setItemType( QgsComposerItem::ComposerMap ); - connect( mComposerMapComboBox, SIGNAL( itemChanged( QgsComposerItem* ) ), this, SLOT( composerMapChanged( const QgsComposerItem* ) ) ); + connect( mComposerMapComboBox, SIGNAL( itemChanged( QgsComposerItem* ) ), this, SLOT( composerMapChanged( QgsComposerItem* ) ) ); mHeaderFontColorButton->setColorDialogTitle( tr( "Select header font color" ) ); mHeaderFontColorButton->setAllowAlpha( true ); @@ -176,7 +176,7 @@ void QgsComposerAttributeTableWidget::on_mAttributesPushButton_clicked() } } -void QgsComposerAttributeTableWidget::composerMapChanged( const QgsComposerItem* item ) +void QgsComposerAttributeTableWidget::composerMapChanged( QgsComposerItem* item ) { if ( !mComposerTable ) { diff --git a/src/app/composer/qgscomposerattributetablewidget.h b/src/app/composer/qgscomposerattributetablewidget.h index 76749c776c30..e5d1431df08b 100644 --- a/src/app/composer/qgscomposerattributetablewidget.h +++ b/src/app/composer/qgscomposerattributetablewidget.h @@ -45,7 +45,7 @@ class QgsComposerAttributeTableWidget: public QgsComposerItemBaseWidget, private private slots: void on_mRefreshPushButton_clicked(); void on_mAttributesPushButton_clicked(); - void composerMapChanged( const QgsComposerItem* item ); + void composerMapChanged( QgsComposerItem* item ); void on_mMaximumRowsSpinBox_valueChanged( int i ); void on_mMarginSpinBox_valueChanged( double d ); void on_mGridStrokeWidthSpinBox_valueChanged( double d ); From 47222749f6c0fddd66fe50948ebacba775af017d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 20 Oct 2016 18:16:34 +1000 Subject: [PATCH 365/897] Fix calculation of transparent region --- src/core/effects/qgsimageoperation.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/core/effects/qgsimageoperation.cpp b/src/core/effects/qgsimageoperation.cpp index 3f74133d26f7..c17bf0f723e9 100644 --- a/src/core/effects/qgsimageoperation.cpp +++ b/src/core/effects/qgsimageoperation.cpp @@ -809,21 +809,28 @@ QRect QgsImageOperation::nonTransparentImageRect( const QImage &image, QSize min // scan down till we hit something for ( int y = 0; y < height; ++y ) { + bool found = false; const QRgb* imgScanline = reinterpret_cast< const QRgb* >( image.constScanLine( y ) ); for ( int x = 0; x < width; ++x ) { if ( qAlpha( imgScanline[x] ) ) { ymin = y; + ymax = y; xmin = x; xmax = x; + found = true; + break; } } + if ( found ) + break; } //scan up till we hit something - for ( int y = height - 1; y > ymin; --y ) + for ( int y = height - 1; y >= ymin; --y ) { + bool found = false; const QRgb* imgScanline = reinterpret_cast< const QRgb* >( image.constScanLine( y ) ); for ( int x = 0; x < width; ++x ) { @@ -832,8 +839,12 @@ QRect QgsImageOperation::nonTransparentImageRect( const QImage &image, QSize min ymax = y; xmin = qMin( xmin, x ); xmax = qMax( xmax, x ); + found = true; + break; } } + if ( found ) + break; } //scan left to right till we hit something, using a refined y region From b9d5b2c4526874f3b76eaada63ceb5707441045a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 19 Oct 2016 17:11:04 +0300 Subject: [PATCH 366/897] fix conflicts --- ci/travis/linux/before_install.sh | 4 ++++ ci/travis/linux/script.sh | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/ci/travis/linux/before_install.sh b/ci/travis/linux/before_install.sh index a09a2b7bb64a..e6afb59e8406 100755 --- a/ci/travis/linux/before_install.sh +++ b/ci/travis/linux/before_install.sh @@ -26,6 +26,10 @@ pushd ${HOME} curl -L https://github.com/opengisch/osgeo4travis/archive/qt5bin.tar.gz | tar -xzC /home/travis --strip-components=1 curl -L https://cmake.org/files/v3.5/cmake-3.5.0-Linux-x86_64.tar.gz | tar --strip-components=1 -zxC /home/travis/osgeo4travis + +# Download OTB package for Processing tests +wget https://www.orfeo-toolbox.org/packages/archives/OTB/OTB-5.6.0-Linux64.run -O /home/travis/OTB-5.6.0-Linux64.run && sh /home/travis/OTB-5.6.0-Linux64.run + popd pip install psycopg2 numpy nose2 pyyaml mock future termcolor diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index d7e680ea9c70..09d1ace4c24d 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -14,12 +14,15 @@ ########################################################################### export PYTHONPATH=${HOME}/osgeo4travis/lib/python3.3/site-packages/ -export PATH=${HOME}/osgeo4travis/bin:${HOME}/osgeo4travis/sbin:${PATH} +export PATH=${HOME}/osgeo4travis/bin:${HOME}/osgeo4travis/sbin:${HOME}/OTB-5.6.0-Linux64/bin:${PATH} export LD_LIBRARY_PATH=${HOME}/osgeo4travis/lib export CTEST_PARALLEL_LEVEL=1 export CCACHE_TEMPDIR=/tmp DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +# Set OTB application path (installed in before_install.sh script) +export OTB_APPLICATION_PATH=${HOME}/OTB-5.6.0-Linux64/lib/otb/applications + xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure From fd8379c140434231dc1ec5f49440f5f6ee41abc9 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 19 Oct 2016 17:11:51 +0300 Subject: [PATCH 367/897] [processing] remove unused file --- .../processing/tests/data/raster.tif.aux.xml | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 python/plugins/processing/tests/data/raster.tif.aux.xml diff --git a/python/plugins/processing/tests/data/raster.tif.aux.xml b/python/plugins/processing/tests/data/raster.tif.aux.xml deleted file mode 100644 index abf1b4b7c636..000000000000 --- a/python/plugins/processing/tests/data/raster.tif.aux.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - 825.8245192307693 - 899.1754807692307 - 208 - 0 - 0 - 4|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|6|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|6|0|0|0|0|0|4|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|9|0|0|0|0|0|6|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|10|0|0|0|0|4|0|0|0|0|0|0|0|0|6|0|0|0|0|9|0|0|0|0|0|6|0|0|0|0|0|0|0|0|0|0|4|0|0|9|0|0|0|0|0|0|0|0|0|0|0|0|0|6|0|0|0|0|0|6|0|0|6|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|13|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|6 - - - - 899 - 865.86666666667 - 826 - 17.808206597584 - - - From 2778a8fe8c4a9df349dc7c7523780e5428966c32 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 19 Oct 2016 17:23:24 +0300 Subject: [PATCH 368/897] [processing] minor formatting fixes to the OTB README --- .../processing/algs/otb/maintenance/README | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/python/plugins/processing/algs/otb/maintenance/README b/python/plugins/processing/algs/otb/maintenance/README index 9ee567ae0c51..9465b0542734 100644 --- a/python/plugins/processing/algs/otb/maintenance/README +++ b/python/plugins/processing/algs/otb/maintenance/README @@ -1,13 +1,9 @@ Requirements ============ -QGIS ----- -Python plugins --------------- Set OTB environment -------------------- - +``` export PYTHONPATH=/path/to/OTB/install/lib/otb/python/:$PYTHONPATH # Environment variable for old OTB versions (< 5.2) export ITK_AUTOLOAD_PATH=/path/to/OTB/install/lib/otb/applications/ @@ -15,22 +11,26 @@ export ITK_AUTOLOAD_PATH=/path/to/OTB/install/lib/otb/applications/ export OTB_APPLICATION_PATH=/path/to/OTB/install/lib/otb/applications/ # Set LD_LIBRARY_PATH export LD_LIBRARY_PATH=/path/to/OTB/install/lib/:$LD_LIBRARY_PATH +``` Set QGIS environment --------------------- + +``` export QGIS_PREFIX_PATH=/path/to/QGIS/install export PYTHONPATH=$QGIS_PREFIX_PATH/share/qgis/python:$QGIS_PREFIX_PATH/share/qgis/python/plugins:$PYTHONPATH # Set LD_LIBRARY_PATH export LD_LIBRARY_PATH=$QGIS_PREFIX_PATH/lib/:$LD_LIBRARY_PATH # Add maintenance folder to python path export PYTHONPATH=/path/to/QGIS/src/python/plugins/processing/algs/otb/maintenance:$PYTHONPATH +``` Check the white and black list for the current OTB version ---------------------------------------------------------- -In the maintenance directory, the OTB applications are split in two files black_list.xml and white_list.xml. -These files are organized as follows : -For each OTB version, a new node version with id as attribute is added to the node data. -Each application is then added in the node app_name. +In the maintenance directory, the OTB applications are split in two files `black_list.xml` and `white_list.xml`. +These files are organized as follows. For each OTB version, a new node version with id as attribute is added +to the node data. Each application is then added in the node app_name. + ```xml @@ -52,14 +52,18 @@ Each application is then added in the node app_name. ``` + The list of available applications for each version is not fixed. OTBSpecific_XMLcreation.py -------------------------- -Warning : Some of the applications needs to be split to be user-friendly. Here comes the file OTBSpecific_XMLcreation.py. -Each function follows the pattern getNameOfTheOTBApplication(). +Warning: Some of the applications needs to be split to be user-friendly. Here comes the file `OTBSpecific_XMLcreation.py`. +Each function follows the pattern `getNameOfTheOTBApplication()`. Creating xml files ------------------ + +``` cd /path/to/QGIS/src/python/plugins/processing/algs/otb/maintenance -python ./OTBHelper.py +python ./OTBHelper.py +``` From df90e6b964f3b267857728d22a2a955db5ff0f3f Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 20 Oct 2016 10:56:19 +0300 Subject: [PATCH 369/897] [processing] remove unused test data --- .../testdata/expected/otb/raster_bandmath.tif | Bin 1315 -> 0 bytes .../expected/otb/raster_bandmath.tif.aux.xml | 10 ---------- .../testdata/expected/otb/raster_convert.tif | Bin 1315 -> 0 bytes 3 files changed, 10 deletions(-) delete mode 100644 python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif delete mode 100644 python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml delete mode 100644 python/plugins/processing/tests/testdata/expected/otb/raster_convert.tif diff --git a/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif b/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif deleted file mode 100644 index ceed156090f5705db71a5c3446eb8e85bba8d31e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1315 zcmebD)MDUZU|C#kkkkZ2*+5|izGfZ<5Pb`Xn_74n*nspWAYR|j%%B3Km4N1NXoslD z0ouT2mQp-ht2qV7eg!LOaAAaCI>?P|#Nh4e?c|%FjzxFgEb30g2Tx=o%ZDn^}O> aGceRULok#}GDWF=k}Vw7Fd72GA_M^5Juo%^ diff --git a/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml b/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml deleted file mode 100644 index 3ae89ceffcc6..000000000000 --- a/python/plugins/processing/tests/testdata/expected/otb/raster_bandmath.tif.aux.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - 255 - 4.5535714285714 - 0 - 33.770189539453 - - - diff --git a/python/plugins/processing/tests/testdata/expected/otb/raster_convert.tif b/python/plugins/processing/tests/testdata/expected/otb/raster_convert.tif deleted file mode 100644 index a985aa5636f13df574b76254243006867fc58328..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1315 zcmebD)MDUZU|C#kkkkZ2*+5|izGfZ<5Pb`Xn_74n*nspWAYR|j%%B3Km4N1NXoslD z0ouT2mQp-ht2qV7eg!LOaAAaCI>?P|#Nh4e?c|%FjzxFgEb30g2Tx=o%ZDn^^$W zH!wV^sILcM-#!F>IJdqYgiF^VFvs5ddJqQbLB^Eo|1-0`9)u^XL|~Pj_4Ocp^cVsw z-K(z$VPv~O?19z~bL)dc_4P1Za;d%^gxMb1kwNhLomAi1Faw3JtK(^09aCW;s5{u From 06976a2e87737c755f5783243e09185e7c872e06 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Wed, 19 Oct 2016 12:09:27 +0200 Subject: [PATCH 370/897] Make Extent and Extent CRS GDAL parameters optional Specify what the default is when extent CRS is not specified. Allow using "auto" to have extent automatically set to min covering extent. Fixes #15685 --- python/plugins/processing/algs/gdal/warp.py | 9 ++++----- python/plugins/processing/core/parameters.py | 2 +- python/plugins/processing/gui/ExtentSelectionPanel.py | 6 +++--- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/python/plugins/processing/algs/gdal/warp.py b/python/plugins/processing/algs/gdal/warp.py index 7040e11da99e..e2c236b5e843 100644 --- a/python/plugins/processing/algs/gdal/warp.py +++ b/python/plugins/processing/algs/gdal/warp.py @@ -92,7 +92,8 @@ def defineCharacteristics(self): if GdalUtils.version() >= 2000000: self.addParameter(ParameterCrs(self.EXT_CRS, - self.tr('CRS of the raster extent'), '')) + self.tr('CRS of the raster extent, leave blank for using Destination SRS'), + optional=True)) params = [] params.append(ParameterSelection(self.RTYPE, @@ -136,7 +137,7 @@ def getConsoleCommands(self): compress = self.COMPRESSTYPE[self.getParameterValue(self.COMPRESS)] bigtiff = self.BIGTIFFTYPE[self.getParameterValue(self.BIGTIFF)] tfw = str(self.getParameterValue(self.TFW)) - rastext = str(self.getParameterValue(self.RAST_EXT)) + rastext = self.getParameterValue(self.RAST_EXT) rastext_crs = self.getParameterValue(self.EXT_CRS) arguments = [] @@ -174,11 +175,9 @@ def getConsoleCommands(self): rastext.append(regionCoords[3]) except IndexError: rastext = [] - if rastext: - arguments.extend(rastext) if GdalUtils.version() >= 2000000: - if rastext and rastext_crs is not None: + if rastext and rastext_crs: arguments.append('-te_srs') arguments.append(rastext_crs) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index ad3841cb32d7..c31223394477 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -348,7 +348,7 @@ def __init__(self, name='', description='', default=None, optional=True): # The value is a string in the form "xmin, xmax, ymin, ymax" def setValue(self, value): - if value is None: + if not value: if not self.optional: return False self.value = None diff --git a/python/plugins/processing/gui/ExtentSelectionPanel.py b/python/plugins/processing/gui/ExtentSelectionPanel.py index 4ff826716c44..408d88c7eed3 100644 --- a/python/plugins/processing/gui/ExtentSelectionPanel.py +++ b/python/plugins/processing/gui/ExtentSelectionPanel.py @@ -59,7 +59,7 @@ def __init__(self, dialog, param): if self.param.optional: if hasattr(self.leText, 'setPlaceholderText'): self.leText.setPlaceholderText( - self.tr('[Leave blank to use min covering extent]')) + self.tr('[Use "auto" to use min covering extent]')) self.btnSelect.clicked.connect(self.selectExtent) @@ -104,7 +104,7 @@ def selectExtent(self): popupmenu.exec_(QCursor.pos()) def useMinCoveringExtent(self): - self.leText.setText('') + self.leText.setText('auto') def useLayerExtent(self): CANVAS_KEY = 'Use canvas extent' @@ -153,7 +153,7 @@ def setValueFromRect(self, r): self.dialog.activateWindow() def getValue(self): - if str(self.leText.text()).strip() != '': + if str(self.leText.text()).strip() == '': return str(self.leText.text()) else: return None From 797181534360ebf68145d5bf787cc5d3a65c9e93 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 20 Oct 2016 10:51:07 +0200 Subject: [PATCH 371/897] Do not pass None to len() --- python/plugins/processing/algs/gdal/warp.py | 34 ++++++++++----------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/python/plugins/processing/algs/gdal/warp.py b/python/plugins/processing/algs/gdal/warp.py index e2c236b5e843..5d8146525fd0 100644 --- a/python/plugins/processing/algs/gdal/warp.py +++ b/python/plugins/processing/algs/gdal/warp.py @@ -143,13 +143,13 @@ def getConsoleCommands(self): arguments = [] arguments.append('-ot') arguments.append(self.TYPE[self.getParameterValue(self.RTYPE)]) - if len(srccrs) > 0: + if srccrs: arguments.append('-s_srs') arguments.append(srccrs) - if len(dstcrs) > 0: + if dstcrs: arguments.append('-t_srs') arguments.append(dstcrs) - if noData and len(noData) > 0: + if noData: arguments.append('-dstnodata') arguments.append(noData) arguments.append('-r') @@ -165,21 +165,19 @@ def getConsoleCommands(self): extra = self.getParameterValue(self.EXTRA) if extra is not None: extra = str(extra) - regionCoords = rastext.split(',') - try: - rastext = [] - rastext.append('-te') - rastext.append(regionCoords[0]) - rastext.append(regionCoords[2]) - rastext.append(regionCoords[1]) - rastext.append(regionCoords[3]) - except IndexError: - rastext = [] - - if GdalUtils.version() >= 2000000: - if rastext and rastext_crs: - arguments.append('-te_srs') - arguments.append(rastext_crs) + if rastext: + regionCoords = rastext.split(',') + if len(regionCoords) >= 4: + arguments.append('-te') + arguments.append(regionCoords[0]) + arguments.append(regionCoords[2]) + arguments.append(regionCoords[1]) + arguments.append(regionCoords[3]) + + if GdalUtils.version() >= 2000000: + if rastext_crs: + arguments.append('-te_srs') + arguments.append(rastext_crs) if extra and len(extra) > 0: arguments.append(extra) From 7bd431597093e20a650b8629528fafac649d6cbb Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 12 Oct 2016 12:02:29 +0300 Subject: [PATCH 372/897] [processing] expose zonal statistics from Zonal statistics plugin in toolbox --- .../algs/qgis/QGISAlgorithmProvider.py | 7 +- .../algs/qgis/ZonalStatisticsQgis.py | 102 ++++++++++++++++++ 2 files changed, 106 insertions(+), 3 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 8c459b565ba8..d9e4a87b024b 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -167,6 +167,7 @@ from .IdwInterpolationAttribute import IdwInterpolationAttribute from .TinInterpolationZValue import TinInterpolationZValue from .TinInterpolationAttribute import TinInterpolationAttribute +from .ZonalStatisticsQgis import ZonalStatisticsQgis pluginPath = os.path.normpath(os.path.join( @@ -225,9 +226,9 @@ def __init__(self): OffsetLine(), PolygonCentroids(), Translate(), SingleSidedBuffer(), PointsAlongGeometry(), Aspect(), Slope(), Ruggedness(), Hillshade(), - ReliefAuto(), IdwInterpolationZValue(), - IdwInterpolationAttribute(), TinInterpolationZValue(), - TinInterpolationAttribute() + ReliefAuto(), ZonalStatisticsQgis(), + IdwInterpolationZValue(), IdwInterpolationAttribute(), + TinInterpolationZValue(), TinInterpolationAttribute() ] if hasMatplotlib: diff --git a/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py b/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py new file mode 100644 index 000000000000..7578e99de682 --- /dev/null +++ b/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ZonalStatisticsQgis.py + --------------------- + Date : September 2016 + Copyright : (C) 2016 by Alexander Bruy + Email : alexander dot bruy at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Alexander Bruy' +__date__ = 'September 2016' +__copyright__ = '(C) 2016, Alexander Bruy' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsZonalStatistics + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterRaster +from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterNumber +from processing.core.parameters import ParameterSelection +from processing.core.outputs import OutputVector +from processing.tools import dataobjects + + +class ZonalStatisticsQgis(GeoAlgorithm): + + INPUT_RASTER = 'INPUT_RASTER' + RASTER_BAND = 'RASTER_BAND' + INPUT_VECTOR = 'INPUT_VECTOR' + COLUMN_PREFIX = 'COLUMN_PREFIX' + STATISTICS = 'STATS' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def defineCharacteristics(self): + self.STATS = {self.tr('Count'): QgsZonalStatistics.Count, + self.tr('Sum'): QgsZonalStatistics.Count, + self.tr('Mean'): QgsZonalStatistics.Count, + self.tr('Median'): QgsZonalStatistics.Count, + self.tr('Std. dev.'): QgsZonalStatistics.Count, + self.tr('Min'): QgsZonalStatistics.Count, + self.tr('Max'): QgsZonalStatistics.Count, + self.tr('Range'): QgsZonalStatistics.Count, + self.tr('Minority'): QgsZonalStatistics.Count, + self.tr('Majority'): QgsZonalStatistics.Count, + self.tr('Variety'): QgsZonalStatistics.Count, + self.tr('All'): QgsZonalStatistics.All + } + + self.name, self.i18n_name = self.trAlgorithm('Zonal Statistics (QGIS)') + self.group, self.i18n_group = self.trAlgorithm('Raster tools') + + self.addParameter(ParameterRaster(self.INPUT_RASTER, + self.tr('Raster layer'))) + self.addParameter(ParameterNumber(self.RASTER_BAND, + self.tr('Raster band'), 1, 999, 1)) + self.addParameter(ParameterVector(self.INPUT_VECTOR, + self.tr('Vector layer containing zones'), + [dataobjects.TYPE_VECTOR_POLYGON])) + self.addParameter(ParameterString(self.COLUMN_PREFIX, + self.tr('Output column prefix'), '_')) + self.addParameter(ParameterSelection(self.STATISTICS, + self.tr('Statistics to calculate'), + list(self.STATS.keys()), + multiple=True)) + self.addOutput(OutputVector(self.OUTPUT_LAYER, + self.tr('Zonal statistics'), + True, + datatype=[dataobjects.TYPE_VECTOR_POLYGON])) + + def processAlgorithm(self, progress): + rasterPath = self.getParameterValue(self.INPUT_RASTER) + vectorPath = self.getParameterValue(self.INPUT_VECTOR) + bandNumber = self.getParameterValue(self.RASTER_BAND) + columnPrefix = self.getParameterValue(self.COLUMN_PREFIX) + st = self.getParameterValue(self.STATISTICS) + + vectorLayer = dataobjects.getObjectFromUri(vectorPath) + + keys = list(self.STATS.keys()) + selectedStats = 0 + for i in st: + selectedStats |= self.STATS[keys[i]] + + zs = QgsZonalStatistics(vectorLayer, rasterPath, columnPrefix, bandNumber, selectedStats) + zs.calculateStatistics(None) + + self.setOutputValue(self.OUTPUT_LAYER, vectorPath) From 8f7183b2a4480ab0013057982be18081e5c36c76 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 12 Oct 2016 12:05:41 +0300 Subject: [PATCH 373/897] [processing] add icon for zonal statistics tool --- .../algs/qgis/ZonalStatisticsQgis.py | 18 ++++++++++++++++-- .../plugins/processing/images/zonalstats.png | Bin 0 -> 733 bytes 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 python/plugins/processing/images/zonalstats.png diff --git a/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py b/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py index 7578e99de682..71366a18cb22 100644 --- a/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py +++ b/python/plugins/processing/algs/qgis/ZonalStatisticsQgis.py @@ -25,6 +25,10 @@ __revision__ = '$Format:%H$' +import os + +from qgis.PyQt.QtGui import QIcon + from qgis.analysis import QgsZonalStatistics from processing.core.GeoAlgorithm import GeoAlgorithm @@ -36,6 +40,8 @@ from processing.core.outputs import OutputVector from processing.tools import dataobjects +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + class ZonalStatisticsQgis(GeoAlgorithm): @@ -46,6 +52,9 @@ class ZonalStatisticsQgis(GeoAlgorithm): STATISTICS = 'STATS' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'zonalstats.png')) + def defineCharacteristics(self): self.STATS = {self.tr('Count'): QgsZonalStatistics.Count, self.tr('Sum'): QgsZonalStatistics.Count, @@ -67,7 +76,8 @@ def defineCharacteristics(self): self.addParameter(ParameterRaster(self.INPUT_RASTER, self.tr('Raster layer'))) self.addParameter(ParameterNumber(self.RASTER_BAND, - self.tr('Raster band'), 1, 999, 1)) + self.tr('Raster band'), + 1, 999, 1)) self.addParameter(ParameterVector(self.INPUT_VECTOR, self.tr('Vector layer containing zones'), [dataobjects.TYPE_VECTOR_POLYGON])) @@ -96,7 +106,11 @@ def processAlgorithm(self, progress): for i in st: selectedStats |= self.STATS[keys[i]] - zs = QgsZonalStatistics(vectorLayer, rasterPath, columnPrefix, bandNumber, selectedStats) + zs = QgsZonalStatistics(vectorLayer, + rasterPath, + columnPrefix, + bandNumber, + selectedStats) zs.calculateStatistics(None) self.setOutputValue(self.OUTPUT_LAYER, vectorPath) diff --git a/python/plugins/processing/images/zonalstats.png b/python/plugins/processing/images/zonalstats.png new file mode 100644 index 0000000000000000000000000000000000000000..1f812a74b8d98fb9a8bdcc1630e92a72b1f28cad GIT binary patch literal 733 zcmeAS@N?(olHy`uVBq!ia0vp^5+KaM1|%Pp+x`GjEX7WqAsj$Z!;#Vf2?p zUk71ECym(^Ktah8*NBqf{Irtt#G+J&^73-M%)IR4 zKdDl;I8onN&p$n$RP|?JoPwFdVr>uFSneHy`C!J-v;A4$UN={p4+b26)|M%th zuYdpixY8x`r>~?wzwN}2HbEL9r?`(j{3n3 zJNNpf4`1B=I}1f~6gawe&2lsl^;NK1c43~W-1iBscPtOCo*8U&?or|2AmN57pEqyz z%?_R_7#P;{^5)8o>A{VH>YZ~ z`h`mM^CBve8`=(}vi{C}9Tz`!^HQbNckXSKG1u8&I9H1EM1#ijb&UJYoaGa6Gu3%t yrLaJu@A7M@1r^&G-<~%Ty_X|Ym*H!FSyGkCiCxvX Date: Wed, 19 Oct 2016 14:55:49 +0300 Subject: [PATCH 374/897] [processing] add test for ParameterSelection --- .../processing/tests/ParametersTest.py | 52 ++++++++++++++++++- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index 65c21da62adb..e98d424fb9fd 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -39,7 +39,8 @@ ParameterPoint, ParameterString, ParameterVector, - ParameterTableField) + ParameterTableField, + ParameterSelection) from processing.tools import dataobjects from processing.tests.TestData import points2 @@ -178,7 +179,7 @@ def testOptional(self): optionalParameter.setValue('1,2') self.assertEqual(optionalParameter.value, '1,2') self.assertTrue(optionalParameter.setValue(None)) - # Extent is unique in that it will let you set `None`, whereas other + # Point like Extent is unique in that it will let you set `None`, whereas other # optional parameters become "default" when assigning None. self.assertEqual(optionalParameter.value, None) @@ -190,6 +191,53 @@ def testOptional(self): self.assertEqual(requiredParameter.value, '1,2') +class ParameterSelectionTest(unittest.TestCase): + + def testSetValue(self): + parameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3']) + self.assertIsNone(parameter.value) + self.assertEqual(parameter.setValue(1), True) + self.assertEqual(parameter.value, 1) + self.assertEqual(parameter.setValue('1'), True) + self.assertEqual(parameter.value, 1) + self.assertEqual(parameter.setValue(1.0), True) + self.assertEqual(parameter.value, 1) + self.assertEqual(parameter.setValue('1a'), False) + self.assertEqual(parameter.setValue([1]), False) + + def testMultiple(self): + parameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3'], multiple=True) + self.assertEqual(parameter.setValue(1), True) + self.assertEqual(parameter.value, 1) + self.assertEqual(parameter.setValue([0, 1]), True) + self.assertEqual(parameter.value, [0, 1]) + self.assertEqual(parameter.setValue(['0', '1']), True) + self.assertEqual(parameter.value, [0, 1]) + + def testDefault(self): + parameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3'], default=0) + self.assertEqual(parameter.value, 0) + parameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3'], default=0.0) + self.assertEqual(parameter.value, 0) + parameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3'], default='a') + self.assertEqual(parameter.value, 0) + + def testOptional(self): + optionalParameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3'], default=0, optional=True) + self.assertEqual(optionalParameter.value, 0) + optionalParameter.setValue(1) + self.assertEqual(optionalParameter.value, 1) + self.assertTrue(optionalParameter.setValue(None)) + self.assertEqual(optionalParameter.value, 0) + + requiredParameter = ParameterSelection('myName', 'myDesc', ['option1', 'option2', 'option3'], default=0, optional=False) + self.assertEqual(requiredParameter.value, 0) + requiredParameter.setValue(1) + self.assertEqual(requiredParameter.value, 1) + self.assertFalse(requiredParameter.setValue(None)) + self.assertEqual(requiredParameter.value, 1) + + class ParameterFileTest(unittest.TestCase): def testSetValue(self): From e0d8db721c132e496edec800405e06a448a685aa Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 20 Oct 2016 12:49:56 +0200 Subject: [PATCH 375/897] Rename README to README.md --- .../processing/algs/otb/maintenance/{README => README.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename python/plugins/processing/algs/otb/maintenance/{README => README.md} (97%) diff --git a/python/plugins/processing/algs/otb/maintenance/README b/python/plugins/processing/algs/otb/maintenance/README.md similarity index 97% rename from python/plugins/processing/algs/otb/maintenance/README rename to python/plugins/processing/algs/otb/maintenance/README.md index 9465b0542734..dc4bb0a6754a 100644 --- a/python/plugins/processing/algs/otb/maintenance/README +++ b/python/plugins/processing/algs/otb/maintenance/README.md @@ -5,7 +5,7 @@ Set OTB environment -------------------- ``` export PYTHONPATH=/path/to/OTB/install/lib/otb/python/:$PYTHONPATH -# Environment variable for old OTB versions (< 5.2) +# Environment variable for old OTB versions (< 5.2) export ITK_AUTOLOAD_PATH=/path/to/OTB/install/lib/otb/applications/ # Environment variable for new OTB versions (>= 5.2) export OTB_APPLICATION_PATH=/path/to/OTB/install/lib/otb/applications/ From bb225f562b0478b13597fefab66c8f4cff8e2280 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 20 Oct 2016 12:54:54 +0200 Subject: [PATCH 376/897] Improve db_manager README --- python/plugins/db_manager/README | 16 ---------------- python/plugins/db_manager/README.md | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 16 deletions(-) delete mode 100644 python/plugins/db_manager/README create mode 100644 python/plugins/db_manager/README.md diff --git a/python/plugins/db_manager/README b/python/plugins/db_manager/README deleted file mode 100644 index 137c16f04c59..000000000000 --- a/python/plugins/db_manager/README +++ /dev/null @@ -1,16 +0,0 @@ -DB Manager * Copyright (c) 2011 Giuseppe Sucameli - -DB Manager is a database manager plugin for QGIS. -It allows showing the DBs contents and run query on them. - -In this moment DB Manager supports the following DBMS backends: -- PostgreSQL/PostGIS through the psycopg2 pymodule -- SQLite/SpatiaLite using the pyspatialite pymodule -- Oracle Spatial using PyQt QtSql module - -For more info about the project, see at the wiki page: - http://qgis.org/wiki/DB_Manager_plugin_GSoC_2011 - -or visit my GitHub repository: - https://github.com/brushtyler/db_manager - diff --git a/python/plugins/db_manager/README.md b/python/plugins/db_manager/README.md new file mode 100644 index 000000000000..84cde582ad24 --- /dev/null +++ b/python/plugins/db_manager/README.md @@ -0,0 +1,18 @@ +DB Manager +========== + +Copyright (c) 2011 Giuseppe Sucameli + +DB Manager is a database manager core plugin for QGIS. +It allows showing the database contents and running queries on them. + +At the moment DB Manager supports the following DBMS backends: + +- PostgreSQL/PostGIS through the psycopg2 pymodule +- SQLite/SpatiaLite using the pyspatialite pymodule +- GeoPackage +- Oracle Spatial using PyQt QtSql module + +For more info about the project see the [QGIS +Documentation](http://docs.qgis.org/testing/en/docs/user_manual/plugins/plugins_db_manager.html) +or the [GSoC 2011 wiki page](http://qgis.org/wiki/DB_Manager_plugin_GSoC_2011). From f3482d2ce2c4e6f324e684e66089dc1a88c3ab9d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 20 Oct 2016 12:55:48 +0200 Subject: [PATCH 377/897] Rename visibility presets to map themes part 2 (#3641) --- doc/api_break.dox | 2 + python/core/qgsmapthemecollection.sip | 149 ++++++++++--------- src/app/composer/qgscomposermapwidget.cpp | 6 +- src/app/main.cpp | 2 +- src/app/qgsdxfexportdialog.cpp | 4 +- src/app/qgsmapthemes.cpp | 53 ++++--- src/app/qgsmapthemes.h | 8 +- src/core/composer/qgscomposermap.cpp | 8 +- src/core/qgsmapthemecollection.cpp | 130 ++++++++++------- src/core/qgsmapthemecollection.h | 167 +++++++++++++++------- src/core/qgsproject.cpp | 10 +- src/core/qgsproject.h | 3 +- tests/src/core/testqgscomposermap.cpp | 5 +- 13 files changed, 330 insertions(+), 217 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 3e0a804fca6b..494461c0fa15 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1467,6 +1467,8 @@ in code which previously passed a null pointer to QgsVectorLayerImport.
                                                                                                                                                                                    • Has been renamed to QgsMapThemeCollection
                                                                                                                                                                                    • +
                                                                                                                                                                                    • The nested class PresetRecord has been renamed to MapThemeRecord
                                                                                                                                                                                    • +
                                                                                                                                                                                    • Various member functions have been renamed from *preset* to *mapTheme*
                                                                                                                                                                                    \subsection qgis_api_break_3_0_QgsVectorFileWriter QgsVectorFileWriter diff --git a/python/core/qgsmapthemecollection.sip b/python/core/qgsmapthemecollection.sip index e0377bb3197c..490731d444a9 100644 --- a/python/core/qgsmapthemecollection.sip +++ b/python/core/qgsmapthemecollection.sip @@ -1,9 +1,9 @@ /** \class QgsMapThemeCollection \ingroup core - \brief Container class that allows storage of visibility presets consisting of visible + \brief Container class that allows storage of map themes consisting of visible map layers and layer styles. - \note added in QGIS 2.12 + \note Added in QGIS 2.12, renamed for QGIS 3.0 */ class QgsMapThemeCollection : QObject @@ -13,119 +13,134 @@ class QgsMapThemeCollection : QObject %End public: - /** Individual preset record of visible layers and styles. + /** \ingroup core + * Individual map theme record of visible layers and styles. */ - class PresetRecord + class MapThemeRecord { public: - bool operator==( const QgsMapThemeCollection::PresetRecord& other ) const; - bool operator!=( const QgsMapThemeCollection::PresetRecord& other ) const; + bool operator==( const QgsMapThemeCollection::MapThemeRecord& other ) const; + bool operator!=( const QgsMapThemeCollection::MapThemeRecord& other ) const; - //! Ordered list of layers that are visible - QStringList mVisibleLayerIDs; - /** For layers that have checkable legend symbols and not all symbols are checked - list which ones are + /** + * Ordered list of visible layers + */ + QStringList visibleLayerIds() const; + + /** + * Ordered list of visible layers + */ + void setVisibleLayerIds( const QStringList& visibleLayerIds ); + + /** + * Lists which legend symbols are checked for layers which support this and where + * not all symbols are checked. + * @note not available in Python bindings + */ +// QMap > perLayerCheckedLegendSymbols() const; + + /** + * Lists which legend symbols are checked for layers which support this and where + * not all symbols are checked. * @note not available in Python bindings */ - //QMap > mPerLayerCheckedLegendSymbols; - //! For layers that use multiple styles - which one is currently selected - QMap mPerLayerCurrentStyle; +// void setPerLayerCheckedLegendSymbols(const QMap >& perLayerCheckedLegendSymbols); + + /** + * The currently used style name for layers with multiple styles. + * The map has layer ids as keys and style names as values. + */ + QMap perLayerCurrentStyle() const; + + /** + * The currently used style name for layers with multiple styles. + * The map has layer ids as keys and style names as values. + */ + void setPerLayerCurrentStyle(const QMap& perLayerCurrentStyle); + }; QgsMapThemeCollection(); - /** Returns whether a preset with a matching name exists. - * @param name name of preset to check - * @returns true if preset exists + /** + * Returns whether a map theme with a matching name exists. */ - bool hasPreset( const QString& name ) const; + bool hasMapTheme( const QString& name ) const; - /** Inserts a new preset to the collection. - * @param name name of preset - * @param state preset record + /** + * Inserts a new map theme to the collection. * @see update() */ - void insert( const QString& name, const PresetRecord& state ); + void insert( const QString& name, const MapThemeRecord& state ); - /** Updates a preset within the collection. - * @param name name of preset to update - * @param state preset record to replace existing preset + /** + * Updates a map theme within the collection. + * @param name name of map theme to update + * @param state map theme record to replace existing map theme * @see insert() */ - void update( const QString& name, const PresetRecord& state ); + void update( const QString& name, const MapThemeRecord& state ); - /** Remove existing preset from collection. - * @param name preset name + /** + * Remove an existing map theme from collection. */ - void removePreset( const QString& name ); + void removeMapTheme( const QString& name ); - //! Remove all presets from the collection. + //! Remove all map themes from the collection. void clear(); - //! Returns a list of existing preset names. - QStringList presets() const; + //! Returns a list of existing map theme names. + QStringList mapThemes() const; - /** Returns the recorded state of a preset. - * @param name name of preset + /** + * Returns the recorded state of a map theme. */ - PresetRecord presetState( const QString& name ) const; + MapThemeRecord mapThemeState( const QString& name ) const; - /** Returns the list of layer IDs that should be visible for the specified preset. + /** + * Returns the list of layer IDs that are visible for the specified map theme. + * * @note The order of the returned list is not guaranteed to reflect the order of layers * in the canvas. - * @param name preset name */ - QStringList presetVisibleLayers( const QString& name ) const; + QStringList mapThemeVisibleLayers( const QString& name ) const; - /** Apply check states of legend nodes of a given layer as defined in the preset. - * @param name preset name - * @param layerID layer ID + /** + * Apply check states of legend nodes of a given layer as defined in the map theme. */ - void applyPresetCheckedLegendNodesToLayer( const QString& name, const QString& layerID ); + void applyMapThemeCheckedLegendNodesToLayer( const QString& name, const QString& layerID ); - /** Get layer style overrides (for QgsMapSettings) of the visible layers for given preset. - * @param name preset name + /** + * Get layer style overrides (for QgsMapSettings) of the visible layers for given map theme. */ - QMap presetStyleOverrides( const QString& name ); + QMap mapThemeStyleOverride( const QString& name ); - /** Reads the preset collection state from XML + /** + * Reads the map theme collection state from XML * @param doc DOM document - * @see writeXML + * @see writeXml */ void readXml( const QDomDocument& doc ); - /** Writes the preset collection state to XML. + /** Writes the map theme collection state to XML. * @param doc DOM document - * @see readXML + * @see readXml */ void writeXml( QDomDocument& doc ); - /** Static method for adding visible layers from a layer tree group to a preset + /** + * Static method for adding visible layers from a layer tree group to a map theme * record. * @param parent layer tree group parent - * @param rec preset record to amend + * @param rec map theme record to amend */ - static void addVisibleLayersToPreset( QgsLayerTreeGroup* parent, PresetRecord& rec ); + static void addVisibleLayersToMapTheme( QgsLayerTreeGroup* parent, MapThemeRecord& rec ); signals: - /** Emitted when presets within the collection are changed. - */ - void presetsChanged(); - - protected slots: - - /** Handles updates of the preset collection when layers are removed from the registry - */ - void registryLayersRemoved( const QStringList& layerIDs ); - - //! Update style name if a stored style gets renamed - void layerStyleRenamed( const QString& oldName, const QString& newName ); - - protected: - - /** Reconnects all preset layers to handle style renames + /** Emitted when map themes within the collection are changed. */ - void reconnectToLayersStyleManager(); + void mapThemesChanged(); }; diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index 9883e813baee..e43ac8978ac5 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -158,7 +158,7 @@ void QgsComposerMapWidget::aboutToShowKeepLayersVisibilityPresetsMenu() return; menu->clear(); - Q_FOREACH ( const QString& presetName, QgsProject::instance()->mapThemeCollection()->presets() ) + Q_FOREACH ( const QString& presetName, QgsProject::instance()->mapThemeCollection()->mapThemes() ) { menu->addAction( presetName, this, SLOT( keepLayersVisibilityPresetSelected() ) ); } @@ -206,7 +206,7 @@ void QgsComposerMapWidget::keepLayersVisibilityPresetSelected() mKeepLayerStylesCheckBox->setChecked( true ); - mComposerMap->setLayerStyleOverrides( QgsProject::instance()->mapThemeCollection()->presetStyleOverrides( presetName ) ); + mComposerMap->setLayerStyleOverrides( QgsProject::instance()->mapThemeCollection()->mapThemeStyleOverride( presetName ) ); mComposerMap->cache(); mComposerMap->update(); @@ -219,7 +219,7 @@ void QgsComposerMapWidget::onPresetsChanged() { QStringList lst; lst.append( tr( "(none)" ) ); - lst += QgsProject::instance()->mapThemeCollection()->presets(); + lst += QgsProject::instance()->mapThemeCollection()->mapThemes(); model->setStringList( lst ); // select the previously selected item again diff --git a/src/app/main.cpp b/src/app/main.cpp index c67fdeda7e0b..6b671995f928 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -1200,7 +1200,7 @@ int main( int argc, char *argv[] ) QList< QPair > layers; if ( !dxfPreset.isEmpty() ) { - Q_FOREACH ( const QString& layer, QgsProject::instance()->mapThemeCollection()->presetVisibleLayers( dxfPreset ) ) + Q_FOREACH ( const QString& layer, QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( dxfPreset ) ) { QgsVectorLayer *vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layer ) ); if ( !vl ) diff --git a/src/app/qgsdxfexportdialog.cpp b/src/app/qgsdxfexportdialog.cpp index f1a0f90f94c3..580b9d60708a 100644 --- a/src/app/qgsdxfexportdialog.cpp +++ b/src/app/qgsdxfexportdialog.cpp @@ -346,7 +346,7 @@ void QgsVectorLayerAndAttributeModel::applyVisibilityPreset( const QString &name } else { - visibleLayers = QgsProject::instance()->mapThemeCollection()->presetVisibleLayers( name ).toSet(); + visibleLayers = QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( name ).toSet(); } if ( visibleLayers.isEmpty() ) @@ -452,7 +452,7 @@ QgsDxfExportDialog::QgsDxfExportDialog( QWidget *parent, Qt::WindowFlags f ) mLayerTitleAsName->setChecked( QgsProject::instance()->readEntry( "dxf", "/lastDxfLayerTitleAsName", s.value( "qgis/lastDxfLayerTitleAsName", "false" ).toString() ) != "false" ); mMapExtentCheckBox->setChecked( QgsProject::instance()->readEntry( "dxf", "/lastDxfMapRectangle", s.value( "qgis/lastDxfMapRectangle", "false" ).toString() ) != "false" ); - QStringList ids = QgsProject::instance()->mapThemeCollection()->presets(); + QStringList ids = QgsProject::instance()->mapThemeCollection()->mapThemes(); ids.prepend( "" ); mVisibilityPresets->addItems( ids ); mVisibilityPresets->setCurrentIndex( mVisibilityPresets->findText( QgsProject::instance()->readEntry( "dxf", "/lastVisibliltyPreset", "" ) ) ); diff --git a/src/app/qgsmapthemes.cpp b/src/app/qgsmapthemes.cpp index 404804828bac..5408ce012f33 100644 --- a/src/app/qgsmapthemes.cpp +++ b/src/app/qgsmapthemes.cpp @@ -55,11 +55,11 @@ QgsMapThemes::QgsMapThemes() connect( mMenu, SIGNAL( aboutToShow() ), this, SLOT( menuAboutToShow() ) ); } -void QgsMapThemes::addPerLayerCheckedLegendSymbols( QgsMapThemeCollection::PresetRecord& rec ) +void QgsMapThemes::addPerLayerCheckedLegendSymbols( QgsMapThemeCollection::MapThemeRecord& rec ) { QgsLayerTreeModel* model = QgisApp::instance()->layerTreeView()->layerTreeModel(); - Q_FOREACH ( const QString& layerID, rec.mVisibleLayerIDs ) + Q_FOREACH ( const QString& layerID, rec.visibleLayerIds() ) { QgsLayerTreeLayer* nodeLayer = model->rootGroup()->findLayer( layerID ); if ( !nodeLayer ) @@ -81,30 +81,37 @@ void QgsMapThemes::addPerLayerCheckedLegendSymbols( QgsMapThemeCollection::Prese } } + QMap > checkedSymbols = rec.perLayerCheckedLegendSymbols(); + if ( hasCheckableItems && someItemsUnchecked ) - rec.mPerLayerCheckedLegendSymbols.insert( nodeLayer->layerId(), checkedItems ); + checkedSymbols.insert( nodeLayer->layerId(), checkedItems ); + + rec.setPerLayerCheckedLegendSymbols( checkedSymbols ); } } -void QgsMapThemes::addPerLayerCurrentStyle( QgsMapThemeCollection::PresetRecord& rec ) +void QgsMapThemes::addPerLayerCurrentStyle( QgsMapThemeCollection::MapThemeRecord& rec ) { QgsLayerTreeModel* model = QgisApp::instance()->layerTreeView()->layerTreeModel(); - Q_FOREACH ( const QString& layerID, rec.mVisibleLayerIDs ) + QMap styles = rec.perLayerCurrentStyle(); + + Q_FOREACH ( const QString& layerID, rec.visibleLayerIds() ) { QgsLayerTreeLayer* nodeLayer = model->rootGroup()->findLayer( layerID ); if ( !nodeLayer ) continue; - rec.mPerLayerCurrentStyle[layerID] = nodeLayer->layer()->styleManager()->currentStyle(); + styles[layerID] = nodeLayer->layer()->styleManager()->currentStyle(); } + rec.setPerLayerCurrentStyle( styles ); } -QgsMapThemeCollection::PresetRecord QgsMapThemes::currentState() +QgsMapThemeCollection::MapThemeRecord QgsMapThemes::currentState() { - QgsMapThemeCollection::PresetRecord rec; + QgsMapThemeCollection::MapThemeRecord rec; QgsLayerTreeGroup* root = QgsProject::instance()->layerTreeRoot(); - QgsMapThemeCollection::addVisibleLayersToPreset( root, rec ); + QgsMapThemeCollection::addVisibleLayersToMapTheme( root, rec ); addPerLayerCheckedLegendSymbols( rec ); addPerLayerCurrentStyle( rec ); return rec; @@ -130,7 +137,7 @@ void QgsMapThemes::updatePreset( const QString& name ) QStringList QgsMapThemes::orderedPresetVisibleLayers( const QString& name ) const { - QStringList visibleIds = QgsProject::instance()->mapThemeCollection()->presetVisibleLayers( name ); + QStringList visibleIds = QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( name ); // also make sure to order the layers according to map canvas order QgsLayerTreeMapCanvasBridge* bridge = QgisApp::instance()->layerTreeCanvasBridge(); @@ -153,7 +160,7 @@ QMenu* QgsMapThemes::menu() void QgsMapThemes::addPreset() { - QStringList existingNames = QgsProject::instance()->mapThemeCollection()->presets(); + QStringList existingNames = QgsProject::instance()->mapThemeCollection()->mapThemes(); QgsNewNameDialog dlg( tr( "theme" ) , tr( "Theme" ), QStringList(), existingNames, QRegExp(), Qt::CaseInsensitive, mMenu ); dlg.setWindowTitle( tr( "Map Themes" ) ); dlg.setHintString( tr( "Name of the new theme" ) ); @@ -185,7 +192,7 @@ void QgsMapThemes::replaceTriggered() addPreset( actionPreset->text() ); } -void QgsMapThemes::applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const QgsMapThemeCollection::PresetRecord& rec ) +void QgsMapThemes::applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const QgsMapThemeCollection::MapThemeRecord& rec ) { Q_FOREACH ( QgsLayerTreeNode* node, parent->children() ) { @@ -194,21 +201,21 @@ void QgsMapThemes::applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const else if ( QgsLayerTree::isLayer( node ) ) { QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node ); - bool isVisible = rec.mVisibleLayerIDs.contains( nodeLayer->layerId() ); + bool isVisible = rec.visibleLayerIds().contains( nodeLayer->layerId() ); nodeLayer->setVisible( isVisible ? Qt::Checked : Qt::Unchecked ); if ( isVisible ) { - if ( rec.mPerLayerCurrentStyle.contains( nodeLayer->layerId() ) ) + if ( rec.perLayerCurrentStyle().contains( nodeLayer->layerId() ) ) { // apply desired style first - nodeLayer->layer()->styleManager()->setCurrentStyle( rec.mPerLayerCurrentStyle[nodeLayer->layerId()] ); + nodeLayer->layer()->styleManager()->setCurrentStyle( rec.perLayerCurrentStyle().value( nodeLayer->layerId() ) ); } QgsLayerTreeModel* model = QgisApp::instance()->layerTreeView()->layerTreeModel(); - if ( rec.mPerLayerCheckedLegendSymbols.contains( nodeLayer->layerId() ) ) + if ( rec.perLayerCheckedLegendSymbols().contains( nodeLayer->layerId() ) ) { - const QSet& checkedNodes = rec.mPerLayerCheckedLegendSymbols[nodeLayer->layerId()]; + const QSet& checkedNodes = rec.perLayerCheckedLegendSymbols().value( nodeLayer->layerId() ); // some nodes are not checked Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer ) ) { @@ -236,10 +243,10 @@ void QgsMapThemes::applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const void QgsMapThemes::applyState( const QString& presetName ) { - if ( !QgsProject::instance()->mapThemeCollection()->hasPreset( presetName ) ) + if ( !QgsProject::instance()->mapThemeCollection()->hasMapTheme( presetName ) ) return; - applyStateToLayerTreeGroup( QgsProject::instance()->layerTreeRoot(), QgsProject::instance()->mapThemeCollection()->presetState( presetName ) ); + applyStateToLayerTreeGroup( QgsProject::instance()->layerTreeRoot(), QgsProject::instance()->mapThemeCollection()->mapThemeState( presetName ) ); // also make sure that the preset is up-to-date (not containing any non-existent legend items) QgsProject::instance()->mapThemeCollection()->update( presetName, currentState() ); @@ -251,7 +258,7 @@ void QgsMapThemes::removeCurrentPreset() { if ( a->isChecked() ) { - QgsProject::instance()->mapThemeCollection()->removePreset( a->text() ); + QgsProject::instance()->mapThemeCollection()->removeMapTheme( a->text() ); break; } } @@ -265,14 +272,14 @@ void QgsMapThemes::menuAboutToShow() qDeleteAll( mMenuReplaceActions ); mMenuReplaceActions.clear(); - QgsMapThemeCollection::PresetRecord rec = currentState(); + QgsMapThemeCollection::MapThemeRecord rec = currentState(); bool hasCurrent = false; - Q_FOREACH ( const QString& grpName, QgsProject::instance()->mapThemeCollection()->presets() ) + Q_FOREACH ( const QString& grpName, QgsProject::instance()->mapThemeCollection()->mapThemes() ) { QAction* a = new QAction( grpName, mMenu ); a->setCheckable( true ); - if ( !hasCurrent && rec == QgsProject::instance()->mapThemeCollection()->presetState( grpName ) ) + if ( !hasCurrent && rec == QgsProject::instance()->mapThemeCollection()->mapThemeState( grpName ) ) { a->setChecked( true ); hasCurrent = true; diff --git a/src/app/qgsmapthemes.h b/src/app/qgsmapthemes.h index 8af5b7b3eff8..3b2fa802c422 100644 --- a/src/app/qgsmapthemes.h +++ b/src/app/qgsmapthemes.h @@ -74,14 +74,14 @@ class APP_EXPORT QgsMapThemes : public QObject QgsMapThemes(); // singleton //! Applies current layer state to a preset record - void applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const QgsMapThemeCollection::PresetRecord& rec ); + void applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const QgsMapThemeCollection::MapThemeRecord& rec ); //! Applies layer checked legend symbols to a preset record - void addPerLayerCheckedLegendSymbols( QgsMapThemeCollection::PresetRecord& rec ); + void addPerLayerCheckedLegendSymbols( QgsMapThemeCollection::MapThemeRecord& rec ); //! Applies current layer styles to a preset record - void addPerLayerCurrentStyle( QgsMapThemeCollection::PresetRecord& rec ); + void addPerLayerCurrentStyle( QgsMapThemeCollection::MapThemeRecord& rec ); //! Returns the current state of the map canvas as a preset record - QgsMapThemeCollection::PresetRecord currentState(); + QgsMapThemeCollection::MapThemeRecord currentState(); //! Applies a preset for the project's collection to the canvas void applyState( const QString& presetName ); diff --git a/src/core/composer/qgscomposermap.cpp b/src/core/composer/qgscomposermap.cpp index cb7942c11435..7b1ddb35ffa5 100644 --- a/src/core/composer/qgscomposermap.cpp +++ b/src/core/composer/qgscomposermap.cpp @@ -537,8 +537,8 @@ QStringList QgsComposerMap::layersToRender( const QgsExpressionContext* context presetName = exprVal.toString(); } - if ( QgsProject::instance()->mapThemeCollection()->hasPreset( presetName ) ) - renderLayerSet = QgsProject::instance()->mapThemeCollection()->presetVisibleLayers( presetName ); + if ( QgsProject::instance()->mapThemeCollection()->hasMapTheme( presetName ) ) + renderLayerSet = QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( presetName ); else // fallback to using map canvas layers renderLayerSet = mComposition->mapSettings().layers(); } @@ -598,8 +598,8 @@ QMap QgsComposerMap::layerStyleOverridesToRender( const QgsExp presetName = exprVal.toString(); } - if ( QgsProject::instance()->mapThemeCollection()->hasPreset( presetName ) ) - return QgsProject::instance()->mapThemeCollection()->presetStyleOverrides( presetName ); + if ( QgsProject::instance()->mapThemeCollection()->hasMapTheme( presetName ) ) + return QgsProject::instance()->mapThemeCollection()->mapThemeStyleOverride( presetName ); else return QMap(); } diff --git a/src/core/qgsmapthemecollection.cpp b/src/core/qgsmapthemecollection.cpp index 60b07404d252..41e742ef2e55 100644 --- a/src/core/qgsmapthemecollection.cpp +++ b/src/core/qgsmapthemecollection.cpp @@ -32,85 +32,85 @@ QgsMapThemeCollection::QgsMapThemeCollection() this, SLOT( registryLayersRemoved( QStringList ) ) ); } -void QgsMapThemeCollection::addVisibleLayersToPreset( QgsLayerTreeGroup* parent, QgsMapThemeCollection::PresetRecord& rec ) +void QgsMapThemeCollection::addVisibleLayersToMapTheme( QgsLayerTreeGroup* parent, QgsMapThemeCollection::MapThemeRecord& rec ) { Q_FOREACH ( QgsLayerTreeNode* node, parent->children() ) { if ( QgsLayerTree::isGroup( node ) ) - addVisibleLayersToPreset( QgsLayerTree::toGroup( node ), rec ); + addVisibleLayersToMapTheme( QgsLayerTree::toGroup( node ), rec ); else if ( QgsLayerTree::isLayer( node ) ) { QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node ); if ( nodeLayer->isVisible() ) - rec.mVisibleLayerIDs << nodeLayer->layerId(); + rec.mVisibleLayerIds << nodeLayer->layerId(); } } } -bool QgsMapThemeCollection::hasPreset( const QString& name ) const +bool QgsMapThemeCollection::hasMapTheme( const QString& name ) const { - return mPresets.contains( name ); + return mMapThemes.contains( name ); } -void QgsMapThemeCollection::insert( const QString& name, const QgsMapThemeCollection::PresetRecord& state ) +void QgsMapThemeCollection::insert( const QString& name, const QgsMapThemeCollection::MapThemeRecord& state ) { - mPresets.insert( name, state ); + mMapThemes.insert( name, state ); reconnectToLayersStyleManager(); - emit presetsChanged(); + emit mapThemesChanged(); } -void QgsMapThemeCollection::update( const QString& name, const PresetRecord& state ) +void QgsMapThemeCollection::update( const QString& name, const MapThemeRecord& state ) { - if ( !mPresets.contains( name ) ) + if ( !mMapThemes.contains( name ) ) return; - mPresets[name] = state; + mMapThemes[name] = state; reconnectToLayersStyleManager(); - emit presetsChanged(); + emit mapThemesChanged(); } -void QgsMapThemeCollection::removePreset( const QString& name ) +void QgsMapThemeCollection::removeMapTheme( const QString& name ) { - if ( !mPresets.contains( name ) ) + if ( !mMapThemes.contains( name ) ) return; - mPresets.remove( name ); + mMapThemes.remove( name ); reconnectToLayersStyleManager(); - emit presetsChanged(); + emit mapThemesChanged(); } void QgsMapThemeCollection::clear() { - mPresets.clear(); + mMapThemes.clear(); reconnectToLayersStyleManager(); - emit presetsChanged(); + emit mapThemesChanged(); } -QStringList QgsMapThemeCollection::presets() const +QStringList QgsMapThemeCollection::mapThemes() const { - return mPresets.keys(); + return mMapThemes.keys(); } -QStringList QgsMapThemeCollection::presetVisibleLayers( const QString& name ) const +QStringList QgsMapThemeCollection::mapThemeVisibleLayers( const QString& name ) const { - return mPresets.value( name ).mVisibleLayerIDs; + return mMapThemes.value( name ).mVisibleLayerIds; } -void QgsMapThemeCollection::applyPresetCheckedLegendNodesToLayer( const QString& name, const QString& layerID ) +void QgsMapThemeCollection::applyMapThemeCheckedLegendNodesToLayer( const QString& name, const QString& layerID ) { - if ( !mPresets.contains( name ) ) + if ( !mMapThemes.contains( name ) ) return; QgsMapLayer* layer = QgsMapLayerRegistry::instance()->mapLayer( layerID ); if ( !layer ) return; - const PresetRecord& rec = mPresets[name]; + const MapThemeRecord& rec = mMapThemes[name]; QgsVectorLayer* vlayer = qobject_cast( layer ); if ( !vlayer || !vlayer->renderer() ) @@ -131,14 +131,14 @@ void QgsMapThemeCollection::applyPresetCheckedLegendNodesToLayer( const QString& } -QMap QgsMapThemeCollection::presetStyleOverrides( const QString& presetName ) +QMap QgsMapThemeCollection::mapThemeStyleOverride( const QString& presetName ) { QMap styleOverrides; - if ( !mPresets.contains( presetName ) ) + if ( !mMapThemes.contains( presetName ) ) return styleOverrides; - QStringList lst = presetVisibleLayers( presetName ); - const QgsMapThemeCollection::PresetRecord& rec = mPresets[presetName]; + QStringList lst = mapThemeVisibleLayers( presetName ); + const QgsMapThemeCollection::MapThemeRecord& rec = mMapThemes[presetName]; Q_FOREACH ( const QString& layerID, lst ) { QgsMapLayer* layer = QgsMapLayerRegistry::instance()->mapLayer( layerID ); @@ -152,7 +152,7 @@ QMap QgsMapThemeCollection::presetStyleOverrides( const QStrin layer->styleManager()->setOverrideStyle( overrideStyleName ); // set the checked legend nodes - applyPresetCheckedLegendNodesToLayer( presetName, layerID ); + applyMapThemeCheckedLegendNodesToLayer( presetName, layerID ); // save to overrides QgsMapLayerStyle layerStyle; @@ -169,10 +169,10 @@ void QgsMapThemeCollection::reconnectToLayersStyleManager() // disconnect( 0, 0, this, SLOT( layerStyleRenamed( QString, QString ) ) ); QSet layerIDs; - PresetRecordMap::const_iterator it = mPresets.constBegin(); - for ( ; it != mPresets.constEnd(); ++it ) + MapThemeRecordMap::const_iterator it = mMapThemes.constBegin(); + for ( ; it != mMapThemes.constEnd(); ++it ) { - const PresetRecord& rec = it.value(); + const MapThemeRecord& rec = it.value(); QMap::const_iterator layerIt = rec.mPerLayerCurrentStyle.constBegin(); for ( ; layerIt != rec.mPerLayerCurrentStyle.constEnd(); ++layerIt ) layerIDs << layerIt.key(); @@ -197,14 +197,14 @@ void QgsMapThemeCollection::readXml( const QDomDocument& doc ) while ( !visPresetElem.isNull() ) { QString presetName = visPresetElem.attribute( "name" ); - PresetRecord rec; + MapThemeRecord rec; QDomElement visPresetLayerElem = visPresetElem.firstChildElement( "layer" ); while ( !visPresetLayerElem.isNull() ) { QString layerID = visPresetLayerElem.attribute( "id" ); if ( QgsMapLayerRegistry::instance()->mapLayer( layerID ) ) { - rec.mVisibleLayerIDs << layerID; // only use valid layer IDs + rec.mVisibleLayerIds << layerID; // only use valid layer IDs if ( visPresetLayerElem.hasAttribute( "style" ) ) rec.mPerLayerCurrentStyle[layerID] = visPresetLayerElem.attribute( "style" ); } @@ -229,26 +229,26 @@ void QgsMapThemeCollection::readXml( const QDomDocument& doc ) checkedLegendNodesElem = checkedLegendNodesElem.nextSiblingElement( "checked-legend-nodes" ); } - mPresets.insert( presetName, rec ); + mMapThemes.insert( presetName, rec ); visPresetElem = visPresetElem.nextSiblingElement( "visibility-preset" ); } reconnectToLayersStyleManager(); - emit presetsChanged(); + emit mapThemesChanged(); } void QgsMapThemeCollection::writeXml( QDomDocument& doc ) { QDomElement visPresetsElem = doc.createElement( "visibility-presets" ); - PresetRecordMap::const_iterator it = mPresets.constBegin(); - for ( ; it != mPresets.constEnd(); ++ it ) + MapThemeRecordMap::const_iterator it = mMapThemes.constBegin(); + for ( ; it != mMapThemes.constEnd(); ++ it ) { QString grpName = it.key(); - const PresetRecord& rec = it.value(); + const MapThemeRecord& rec = it.value(); QDomElement visPresetElem = doc.createElement( "visibility-preset" ); visPresetElem.setAttribute( "name", grpName ); - Q_FOREACH ( const QString& layerID, rec.mVisibleLayerIDs ) + Q_FOREACH ( const QString& layerID, rec.mVisibleLayerIds ) { QDomElement layerElem = doc.createElement( "layer" ); layerElem.setAttribute( "id", layerID ); @@ -282,16 +282,16 @@ void QgsMapThemeCollection::registryLayersRemoved( const QStringList& layerIDs ) { Q_FOREACH ( const QString& layerID, layerIDs ) { - PresetRecordMap::iterator it = mPresets.begin(); - for ( ; it != mPresets.end(); ++it ) + MapThemeRecordMap::iterator it = mMapThemes.begin(); + for ( ; it != mMapThemes.end(); ++it ) { - PresetRecord& rec = it.value(); - rec.mVisibleLayerIDs.removeAll( layerID ); + MapThemeRecord& rec = it.value(); + rec.mVisibleLayerIds.removeAll( layerID ); rec.mPerLayerCheckedLegendSymbols.remove( layerID ); rec.mPerLayerCurrentStyle.remove( layerID ); } } - emit presetsChanged(); + emit mapThemesChanged(); } void QgsMapThemeCollection::layerStyleRenamed( const QString& oldName, const QString& newName ) @@ -302,10 +302,10 @@ void QgsMapThemeCollection::layerStyleRenamed( const QString& oldName, const QSt QString layerID = styleMgr->layer()->id(); - PresetRecordMap::iterator it = mPresets.begin(); - for ( ; it != mPresets.end(); ++it ) + MapThemeRecordMap::iterator it = mMapThemes.begin(); + for ( ; it != mMapThemes.end(); ++it ) { - PresetRecord& rec = it.value(); + MapThemeRecord& rec = it.value(); if ( rec.mPerLayerCurrentStyle.contains( layerID ) ) { @@ -314,5 +314,35 @@ void QgsMapThemeCollection::layerStyleRenamed( const QString& oldName, const QSt rec.mPerLayerCurrentStyle[layerID] = newName; } } - emit presetsChanged(); + emit mapThemesChanged(); +} + +QStringList QgsMapThemeCollection::MapThemeRecord::visibleLayerIds() const +{ + return mVisibleLayerIds; +} + +void QgsMapThemeCollection::MapThemeRecord::setVisibleLayerIds( const QStringList& visibleLayerIds ) +{ + mVisibleLayerIds = visibleLayerIds; +} + +QMap > QgsMapThemeCollection::MapThemeRecord::perLayerCheckedLegendSymbols() const +{ + return mPerLayerCheckedLegendSymbols; +} + +void QgsMapThemeCollection::MapThemeRecord::setPerLayerCheckedLegendSymbols( const QMap >& perLayerCheckedLegendSymbols ) +{ + mPerLayerCheckedLegendSymbols = perLayerCheckedLegendSymbols; +} + +QMap QgsMapThemeCollection::MapThemeRecord::perLayerCurrentStyle() const +{ + return mPerLayerCurrentStyle; +} + +void QgsMapThemeCollection::MapThemeRecord::setPerLayerCurrentStyle( const QMap& perLayerCurrentStyle ) +{ + mPerLayerCurrentStyle = perLayerCurrentStyle; } diff --git a/src/core/qgsmapthemecollection.h b/src/core/qgsmapthemecollection.h index ddb02ae9bf30..b203f38f42cd 100644 --- a/src/core/qgsmapthemecollection.h +++ b/src/core/qgsmapthemecollection.h @@ -37,134 +37,193 @@ class CORE_EXPORT QgsMapThemeCollection : public QObject { Q_OBJECT + Q_PROPERTY( QStringList mapThemes READ mapThemes NOTIFY mapThemesChanged ) + public: - /** \ingroup core - * Individual preset record of visible layers and styles. + /** + * \ingroup core + * Individual map theme record of visible layers and styles. + * + * @note Added in QGIS 3.0, Previously called PresetRecord */ - class PresetRecord + class MapThemeRecord { public: - bool operator==( const PresetRecord& other ) const + bool operator==( const MapThemeRecord& other ) const { - return mVisibleLayerIDs.toSet() == other.mVisibleLayerIDs.toSet() + return mVisibleLayerIds.toSet() == other.mVisibleLayerIds.toSet() && mPerLayerCheckedLegendSymbols == other.mPerLayerCheckedLegendSymbols && mPerLayerCurrentStyle == other.mPerLayerCurrentStyle; } - bool operator!=( const PresetRecord& other ) const + bool operator!=( const MapThemeRecord& other ) const { return !( *this == other ); } - //! Ordered list of layers that are visible - QStringList mVisibleLayerIDs; - /** For layers that have checkable legend symbols and not all symbols are checked - list which ones are + /** + * Ordered list of visible layers + * @note Added in QGIS 3.0 + */ + QStringList visibleLayerIds() const; + + /** + * Ordered list of visible layers + * @note Added in QGIS 3.0 + */ + void setVisibleLayerIds( const QStringList& visibleLayerIds ); + + /** + * Lists which legend symbols are checked for layers which support this and where + * not all symbols are checked. + * @note not available in Python bindings + * @note Added in QGIS 3.0 + */ + QMap > perLayerCheckedLegendSymbols() const; + + /** + * Lists which legend symbols are checked for layers which support this and where + * not all symbols are checked. * @note not available in Python bindings + * @note Added in QGIS 3.0 */ + void setPerLayerCheckedLegendSymbols( const QMap >& perLayerCheckedLegendSymbols ); + + /** + * The currently used style name for layers with multiple styles. + * The map has layer ids as keys and style names as values. + * @note Added in QGIS 3.0 + */ + QMap perLayerCurrentStyle() const; + + /** + * The currently used style name for layers with multiple styles. + * The map has layer ids as keys and style names as values. + * @note Added in QGIS 3.0 + */ + void setPerLayerCurrentStyle( const QMap& perLayerCurrentStyle ); + + private: + QStringList mVisibleLayerIds; QMap > mPerLayerCheckedLegendSymbols; - //! For layers that use multiple styles - which one is currently selected QMap mPerLayerCurrentStyle; + + friend class QgsMapThemeCollection; }; QgsMapThemeCollection(); - /** Returns whether a preset with a matching name exists. - * @param name name of preset to check - * @returns true if preset exists + /** + * Returns whether a map theme with a matching name exists. + * @note Added in QGIS 3.0 */ - bool hasPreset( const QString& name ) const; + bool hasMapTheme( const QString& name ) const; - /** Inserts a new preset to the collection. - * @param name name of preset - * @param state preset record + /** + * Inserts a new map theme to the collection. * @see update() */ - void insert( const QString& name, const PresetRecord& state ); + void insert( const QString& name, const MapThemeRecord& state ); - /** Updates a preset within the collection. - * @param name name of preset to update - * @param state preset record to replace existing preset + /** + * Updates a map theme within the collection. + * @param name name of map theme to update + * @param state map theme record to replace existing map theme * @see insert() */ - void update( const QString& name, const PresetRecord& state ); + void update( const QString& name, const MapThemeRecord& state ); - /** Remove existing preset from collection. - * @param name preset name + /** + * Remove an existing map theme from collection. + * @note Added in QGIS 3.0 */ - void removePreset( const QString& name ); + void removeMapTheme( const QString& name ); - //! Remove all presets from the collection. + //! Remove all map themes from the collection. void clear(); - //! Returns a list of existing preset names. - QStringList presets() const; + /** + * Returns a list of existing map theme names. + * @note Added in QGIS 3.0 + */ + QStringList mapThemes() const; - /** Returns the recorded state of a preset. - * @param name name of preset + /** + * Returns the recorded state of a map theme. + * @note Added in QGIS 3.0 */ - PresetRecord presetState( const QString& name ) const { return mPresets[name]; } + MapThemeRecord mapThemeState( const QString& name ) const { return mMapThemes[name]; } - /** Returns the list of layer IDs that should be visible for the specified preset. + /** + * Returns the list of layer IDs that are visible for the specified map theme. + * * @note The order of the returned list is not guaranteed to reflect the order of layers * in the canvas. - * @param name preset name + * @note Added in QGIS 3.0 */ - QStringList presetVisibleLayers( const QString& name ) const; + QStringList mapThemeVisibleLayers( const QString& name ) const; - /** Apply check states of legend nodes of a given layer as defined in the preset. - * @param name preset name - * @param layerID layer ID + /** + * Apply check states of legend nodes of a given layer as defined in the map theme. + * @note Added in QGIS 3.0 */ - void applyPresetCheckedLegendNodesToLayer( const QString& name, const QString& layerID ); + void applyMapThemeCheckedLegendNodesToLayer( const QString& name, const QString& layerID ); - /** Get layer style overrides (for QgsMapSettings) of the visible layers for given preset. - * @param name preset name + /** + * Get layer style overrides (for QgsMapSettings) of the visible layers for given map theme. + * @note Added in QGIS 3.0 */ - QMap presetStyleOverrides( const QString& name ); + QMap mapThemeStyleOverride( const QString& name ); - /** Reads the preset collection state from XML + /** + * Reads the map theme collection state from XML * @param doc DOM document * @see writeXml */ void readXml( const QDomDocument& doc ); - /** Writes the preset collection state to XML. + /** Writes the map theme collection state to XML. * @param doc DOM document * @see readXml */ void writeXml( QDomDocument& doc ); - /** Static method for adding visible layers from a layer tree group to a preset + /** + * Static method for adding visible layers from a layer tree group to a map theme * record. * @param parent layer tree group parent - * @param rec preset record to amend + * @param rec map theme record to amend */ - static void addVisibleLayersToPreset( QgsLayerTreeGroup* parent, PresetRecord& rec ); + static void addVisibleLayersToMapTheme( QgsLayerTreeGroup* parent, MapThemeRecord& rec ); signals: - /** Emitted when presets within the collection are changed. + /** + * Emitted when map themes within the collection are changed. + * @note Added in QGIS 3.0 */ - void presetsChanged(); + void mapThemesChanged(); - protected slots: + private slots: - /** Handles updates of the preset collection when layers are removed from the registry + /** + * Handles updates of the map theme collection when layers are removed from the registry */ void registryLayersRemoved( const QStringList& layerIDs ); //! Update style name if a stored style gets renamed void layerStyleRenamed( const QString& oldName, const QString& newName ); - protected: + private: - /** Reconnects all preset layers to handle style renames + /** + * Reconnects all map theme layers to handle style renames */ void reconnectToLayersStyleManager(); - typedef QMap PresetRecordMap; - PresetRecordMap mPresets; + typedef QMap MapThemeRecordMap; + MapThemeRecordMap mMapThemes; }; diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 04d3f84c722a..48cbfb9f660d 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -480,7 +480,7 @@ void QgsProject::clear() mEmbeddedLayers.clear(); mRelationManager->clear(); - mVisibilityPresetCollection.reset( new QgsMapThemeCollection() ); + mMapThemeCollection.reset( new QgsMapThemeCollection() ); mRootGroup->removeAllChildren(); @@ -916,8 +916,8 @@ bool QgsProject::read() mRootGroup->removeCustomProperty( "loading" ); - mVisibilityPresetCollection.reset( new QgsMapThemeCollection() ); - mVisibilityPresetCollection->readXml( *doc ); + mMapThemeCollection.reset( new QgsMapThemeCollection() ); + mMapThemeCollection->readXml( *doc ); // reassign change dependencies now that all layers are loaded QMap existingMaps = QgsMapLayerRegistry::instance()->mapLayers(); @@ -1203,7 +1203,7 @@ bool QgsProject::write() imp_->properties_.writeXml( "properties", qgisNode, *doc ); } - mVisibilityPresetCollection->writeXml( *doc ); + mMapThemeCollection->writeXml( *doc ); // now wrap it up and ship it to the project file doc->normalize(); // XXX I'm not entirely sure what this does @@ -2195,7 +2195,7 @@ QgsLayerTreeGroup *QgsProject::layerTreeRoot() const QgsMapThemeCollection* QgsProject::mapThemeCollection() { - return mVisibilityPresetCollection.data(); + return mMapThemeCollection.data(); } void QgsProject::setNonIdentifiableLayers( QList layers ) diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index b912b7532902..5905fba58687 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -76,6 +76,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera Q_PROPERTY( QString fileName READ fileName WRITE setFileName NOTIFY fileNameChanged ) Q_PROPERTY( QString homePath READ homePath NOTIFY homePathChanged ) Q_PROPERTY( QgsCoordinateReferenceSystem crs READ crs WRITE setCrs ) + Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) public: @@ -615,7 +616,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera //! map of transaction group: QPair( providerKey, connString ) -> transactionGroup QMap< QPair< QString, QString>, QgsTransactionGroup*> mTransactionGroups; - QScopedPointer mVisibilityPresetCollection; + QScopedPointer mMapThemeCollection; }; diff --git a/tests/src/core/testqgscomposermap.cpp b/tests/src/core/testqgscomposermap.cpp index 4a6df1b01ec5..8bbfe727d05d 100644 --- a/tests/src/core/testqgscomposermap.cpp +++ b/tests/src/core/testqgscomposermap.cpp @@ -349,9 +349,8 @@ void TestQgsComposerMap::dataDefinedStyles() mComposerMap->setFrameEnabled( true ); mComposition->addComposerMap( mComposerMap ); - QgsMapThemeCollection::PresetRecord rec; - rec.mVisibleLayerIDs << mPointsLayer->id(); - rec.mVisibleLayerIDs << mLinesLayer->id(); + QgsMapThemeCollection::MapThemeRecord rec; + rec.setVisibleLayerIds( QStringList() << mPointsLayer->id() << mLinesLayer->id() ); QgsProject::instance()->mapThemeCollection()->insert( "test preset", rec ); From 64d3c788f19acc19ca428274a355ae696e344f77 Mon Sep 17 00:00:00 2001 From: Denis Rouzaud Date: Fri, 26 Aug 2016 15:36:07 +0200 Subject: [PATCH 378/897] Use toolbar or status bar for snapping config --- images/images.qrc | 9 + images/themes/default/mIconSnapping.svg | 105 ++ .../default/mIconSnappingActiveLayer.svg | 1133 ++++++++++++++ .../themes/default/mIconSnappingAdvanced.svg | 1363 +++++++++++++++++ .../themes/default/mIconSnappingAllLayers.svg | 1167 ++++++++++++++ .../default/mIconSnappingIntersection.svg | 1124 ++++++++++++++ .../themes/default/mIconSnappingSegment.svg | 1105 +++++++++++++ images/themes/default/mIconSnappingVertex.svg | 1120 ++++++++++++++ .../default/mIconSnappingVertexAndSegment.svg | 1126 ++++++++++++++ .../default/mIconTopologicalEditing.svg | 1118 ++++++++++++++ python/core/core.sip | 1 + python/core/qgsmaplayermodel.sip | 2 - python/core/qgsproject.sip | 38 +- python/core/qgssnappingconfig.sip | 238 +++ python/core/qgssnappingutils.sip | 36 +- src/app/CMakeLists.txt | 4 + src/app/qgisapp.cpp | 63 +- src/app/qgisapp.h | 34 +- src/app/qgsmaptooloffsetcurve.cpp | 21 +- src/app/qgsoptions.cpp | 14 +- src/app/qgssnappingdialog.cpp | 16 +- src/app/qgssnappinglayertreemodel.cpp | 636 ++++++++ src/app/qgssnappinglayertreemodel.h | 94 ++ src/app/qgssnappingwidget.cpp | 476 ++++++ src/app/qgssnappingwidget.h | 130 ++ src/core/CMakeLists.txt | 3 + src/core/qgsproject.cpp | 162 +- src/core/qgsproject.h | 79 +- src/core/qgssnappingconfig.cpp | 509 ++++++ src/core/qgssnappingconfig.h | 245 +++ src/core/qgssnappingutils.cpp | 234 +-- src/core/qgssnappingutils.h | 52 +- src/gui/qgsmapcanvastracer.cpp | 11 +- src/gui/qgsmapmouseevent.cpp | 38 +- src/ui/qgisapp.ui | 13 +- src/ui/qgsoptionsbase.ui | 132 +- tests/src/core/testqgssnappingutils.cpp | 40 +- tests/src/python/test_layer_dependencies.py | 32 +- 38 files changed, 12138 insertions(+), 585 deletions(-) create mode 100644 images/themes/default/mIconSnapping.svg create mode 100644 images/themes/default/mIconSnappingActiveLayer.svg create mode 100644 images/themes/default/mIconSnappingAdvanced.svg create mode 100644 images/themes/default/mIconSnappingAllLayers.svg create mode 100644 images/themes/default/mIconSnappingIntersection.svg create mode 100644 images/themes/default/mIconSnappingSegment.svg create mode 100644 images/themes/default/mIconSnappingVertex.svg create mode 100644 images/themes/default/mIconSnappingVertexAndSegment.svg create mode 100644 images/themes/default/mIconTopologicalEditing.svg create mode 100644 python/core/qgssnappingconfig.sip create mode 100644 src/app/qgssnappinglayertreemodel.cpp create mode 100644 src/app/qgssnappinglayertreemodel.h create mode 100644 src/app/qgssnappingwidget.cpp create mode 100644 src/app/qgssnappingwidget.h create mode 100644 src/core/qgssnappingconfig.cpp create mode 100644 src/core/qgssnappingconfig.h diff --git a/images/images.qrc b/images/images.qrc index f3c4e148bbac..c1f9ec460971 100644 --- a/images/images.qrc +++ b/images/images.qrc @@ -574,6 +574,15 @@ themes/default/mIconClearText.svg themes/default/mIconClearTextHover.svg themes/default/rendererPointClusterSymbol.svg + themes/default/mIconSnapping.svg + themes/default/mIconSnappingActiveLayer.svg + themes/default/mIconSnappingAdvanced.svg + themes/default/mIconSnappingAllLayers.svg + themes/default/mIconSnappingVertexAndSegment.svg + themes/default/mIconSnappingVertex.svg + themes/default/mIconSnappingSegment.svg + themes/default/mIconTopologicalEditing.svg + themes/default/mIconSnappingIntersection.svg qgis_tips/symbol_levels.png diff --git a/images/themes/default/mIconSnapping.svg b/images/themes/default/mIconSnapping.svg new file mode 100644 index 000000000000..6151ab07d8a4 --- /dev/null +++ b/images/themes/default/mIconSnapping.svg @@ -0,0 +1,105 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingActiveLayer.svg b/images/themes/default/mIconSnappingActiveLayer.svg new file mode 100644 index 000000000000..03bda8119bc3 --- /dev/null +++ b/images/themes/default/mIconSnappingActiveLayer.svg @@ -0,0 +1,1133 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingAdvanced.svg b/images/themes/default/mIconSnappingAdvanced.svg new file mode 100644 index 000000000000..07db9ec22c44 --- /dev/null +++ b/images/themes/default/mIconSnappingAdvanced.svg @@ -0,0 +1,1363 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingAllLayers.svg b/images/themes/default/mIconSnappingAllLayers.svg new file mode 100644 index 000000000000..2f49090185dd --- /dev/null +++ b/images/themes/default/mIconSnappingAllLayers.svg @@ -0,0 +1,1167 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingIntersection.svg b/images/themes/default/mIconSnappingIntersection.svg new file mode 100644 index 000000000000..9fd14fa2bd63 --- /dev/null +++ b/images/themes/default/mIconSnappingIntersection.svg @@ -0,0 +1,1124 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingSegment.svg b/images/themes/default/mIconSnappingSegment.svg new file mode 100644 index 000000000000..d7ddc89cf340 --- /dev/null +++ b/images/themes/default/mIconSnappingSegment.svg @@ -0,0 +1,1105 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingVertex.svg b/images/themes/default/mIconSnappingVertex.svg new file mode 100644 index 000000000000..4102cfa7522a --- /dev/null +++ b/images/themes/default/mIconSnappingVertex.svg @@ -0,0 +1,1120 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconSnappingVertexAndSegment.svg b/images/themes/default/mIconSnappingVertexAndSegment.svg new file mode 100644 index 000000000000..86614fe7ae06 --- /dev/null +++ b/images/themes/default/mIconSnappingVertexAndSegment.svg @@ -0,0 +1,1126 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mIconTopologicalEditing.svg b/images/themes/default/mIconTopologicalEditing.svg new file mode 100644 index 000000000000..dd01ee70b4b3 --- /dev/null +++ b/images/themes/default/mIconTopologicalEditing.svg @@ -0,0 +1,1118 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + diff --git a/python/core/core.sip b/python/core/core.sip index 6dd36227ae6e..267998d9a73d 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -111,6 +111,7 @@ %Include qgspointlocator.sip %Include qgsproject.sip %Include qgsprojectproperty.sip +%Include qgssnappingconfig.sip %Include qgsprojectversion.sip %Include qgsprovidermetadata.sip %Include qgsproviderregistry.sip diff --git a/python/core/qgsmaplayermodel.sip b/python/core/qgsmaplayermodel.sip index 3ea7faa7587d..80565e911cb0 100644 --- a/python/core/qgsmaplayermodel.sip +++ b/python/core/qgsmaplayermodel.sip @@ -65,8 +65,6 @@ class QgsMapLayerModel : QAbstractItemModel /** * Returns strings for all roles supported by this model. - * - * @note Available only with Qt5 (python and c++) */ QHash roleNames() const; diff --git a/python/core/qgsproject.sip b/python/core/qgsproject.sip index c4790386a12c..334e7b6dc3df 100644 --- a/python/core/qgsproject.sip +++ b/python/core/qgsproject.sip @@ -274,14 +274,6 @@ class QgsProject : QObject */ QgsLayerTreeGroup* createEmbeddedGroup( const QString& groupName, const QString& projectFilePath, const QStringList &invisibleLayers ); - /** Convenience function to set snap settings per layer */ - void setSnapSettingsForLayer( const QString& layerId, bool enabled, QgsSnapper::SnappingType type, QgsTolerance::UnitType unit, double tolerance, - bool avoidIntersection ); - - /** Convenience function to query snap settings of a layer */ - bool snapSettingsForLayer( const QString& layerId, bool& enabled /Out/, QgsSnapper::SnappingType& type /Out/, QgsTolerance::UnitType& units /Out/, double& tolerance /Out/, - bool& avoidIntersection /Out/ ) const; - /** Convenience function to set topological editing */ void setTopologicalEditing( bool enabled ); @@ -389,27 +381,14 @@ class QgsProject : QObject QgsExpressionContext createExpressionContext() const; - protected: - - /** Set error message from read/write operation - * @note not available in Python bindings + /** + * The snapping configuration for this project. */ - //void setError( const QString& errorMessage ); - - /** Clear error message - * @note not available in Python bindings + QgsSnappingConfig snappingConfig() const; + /** + * The snapping configuration for this project. */ - //void clearError(); - - //! Creates layer and adds it to maplayer registry - //! @note not available in python bindings - // bool addLayer( const QDomElement& layerElem, QList& brokenNodes, QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList ); - - //! @note not available in python bindings - // void initializeEmbeddedSubtree( const QString& projectFilePath, QgsLayerTreeGroup* group ); - - //! @note not available in python bindings - // void loadEmbeddedNodes( QgsLayerTreeGroup* group ); + void setSnappingConfig( const QgsSnappingConfig& snappingConfig ); signals: //! emitted when project is being read @@ -451,8 +430,6 @@ class QgsProject : QObject void loadingLayer( const QString& ); - void snapSettingsChanged(); - //! Emitted when the list of layer which are excluded from map identification changes void nonIdentifiableLayersChanged( QStringList nonIdentifiableLayers ); @@ -462,6 +439,9 @@ class QgsProject : QObject //! Emitted when the home path of the project changes void homePathChanged(); + //! emitted whenever the configuration for snapping has changed + void snappingConfigChanged(); + /** Emitted whenever the expression variables stored in the project have been changed. * @note added in QGIS 3.0 */ diff --git a/python/core/qgssnappingconfig.sip b/python/core/qgssnappingconfig.sip new file mode 100644 index 000000000000..268dbdf47c7a --- /dev/null +++ b/python/core/qgssnappingconfig.sip @@ -0,0 +1,238 @@ +/** \ingroup core + * This is a container for configuration of the snapping of the project + * @note added in 3.0 + */ +class QgsSnappingConfig +{ +%TypeHeaderCode +#include +%End + public: + /** + * SnappingMode defines on which layer the snapping is performed + */ + enum SnappingMode + { + ActiveLayer, /*!< on the active layer */ + AllLayers, /*!< on all vector layers */ + AdvancedConfiguration, /*!< on a per layer configuration basis */ + }; + + /** + * SnappingType defines on what object the snapping is performed + */ + enum SnappingType + { + Vertex, /*!< on vertices only */ + VertexAndSegment, /*!< both on vertices and segments */ + Segment, /*!< on segments only */ + }; + + /** \ingroup core + * This is a container of advanced configuration (per layer) of the snapping of the project + * @note added in 3.0 + */ + class IndividualLayerSettings + { + public: + /** + * @brief IndividualLayerSettings + * @param enabled + * @param type + * @param tolerance + * @param units + * @param avoidIntersection + */ + IndividualLayerSettings( bool enabled, QgsSnappingConfig::SnappingType type, double tolerance, QgsTolerance::UnitType units, bool avoidIntersection = false ); + + /** + * Constructs an invalid setting + */ + IndividualLayerSettings(); + + //! return if settings are valid + bool valid() const; + + //! return if snaping is enbaled + bool enabled() const; + + //! enables the snapping + void setEnabled( bool enabled ); + + //! return the type (vertices and/or segments) + QgsSnappingConfig::SnappingType type() const; + + //! define the type of snapping + void setType( QgsSnappingConfig::SnappingType type ); + + //! return the tolerance + double tolerance() const; + + //! set the tolerance + void setTolerance( double tolerance ); + + //! return the type of units + QgsTolerance::UnitType units() const; + + //! set the type of units + void setUnits( QgsTolerance::UnitType units ); + + //! return if it shall avoid intersection (polygon layers only) + bool avoidIntersection() const; + + //! set if it shall avoid intersection (polygon layers only) + void setAvoidIntersection( bool avoidIntersection ); + + /** + * Compare this configuration to other. + */ + //bool operator!= ( const QgsSnappingConfig::IndividualLayerSettings& other ) const; + + //bool operator== ( const QgsSnappingConfig::IndividualLayerSettings& other ) const; + }; + + /** + * Constructor with default parameters defined in global settings + */ + explicit QgsSnappingConfig(); + + ~QgsSnappingConfig(); + + //! reset to default values + void reset(); + + //! return if snaping is enbaled + bool enabled() const; + + //! enables the snapping + void setEnabled( bool enabled ); + + //! return the mode (all layers, active layer, per layer settings) + QgsSnappingConfig::SnappingMode mode() const; + + //! define the mode of snapping + void setMode( QgsSnappingConfig::SnappingMode mode ); + + //! return the type (vertices and/or segments) + QgsSnappingConfig::SnappingType type() const; + + //! define the type of snapping + void setType( QgsSnappingConfig::SnappingType type ); + + //! return the tolerance + double tolerance() const; + + //! set the tolerance + void setTolerance( double tolerance ); + + //! return the type of units + QgsTolerance::UnitType units() const; + + //! set the type of units + void setUnits( QgsTolerance::UnitType units ); + + //! return if the topological editing is enabled + bool topologicalEditing() const; + + //! set if the topological editing is enabled + void setTopologicalEditing( bool enabled ); + + //! return if the snapping on intersection is enabled + bool intersectionSnapping() const; + + //! set if the snapping on intersection is enabled + void setIntersectionSnapping( bool enabled ); + + //! return individual snapping settings for all layers + SIP_PYDICT individualLayerSettings() const; +%MethodCode + // Create the dictionary. + PyObject* d = PyDict_New(); + if (!d) + return nullptr; + // Set the dictionary elements. + QHash container = sipCpp->individualLayerSettings(); + QHash::const_iterator i = container.constBegin(); + while ( i != container.constEnd() ) + { + QgsVectorLayer* vl = i.key(); + QgsSnappingConfig::IndividualLayerSettings* ils = new QgsSnappingConfig::IndividualLayerSettings( i.value() ); + + PyObject* vlobj = sipConvertFromType( vl, sipType_QgsVectorLayer, nullptr ); + PyObject* ilsobj = sipConvertFromType( ils, sipType_QgsSnappingConfig_IndividualLayerSettings, Py_None ); + + if ( !vlobj || !ilsobj || PyDict_SetItem( d, vlobj, ilsobj) < 0) + { + Py_DECREF( d ); + if ( vlobj ) + { + Py_DECREF( vlobj ); + } + if ( ilsobj ) + { + Py_DECREF( ilsobj ); + } + else + { + delete ils; + } + PyErr_SetString(PyExc_StopIteration,""); + } + Py_DECREF( vlobj ); + Py_DECREF( ilsobj ); + ++i; + } + sipRes = d; +%End + + //! return individual layer snappings settings (applied if mode is AdvancedConfiguration) + QgsSnappingConfig::IndividualLayerSettings individualLayerSettings( QgsVectorLayer* vl ) const; + + //! set individual layer snappings settings (applied if mode is AdvancedConfiguration) + void setIndividualLayerSettings( QgsVectorLayer* vl, QgsSnappingConfig::IndividualLayerSettings individualLayerSettings ); + + /** + * Compare this configuration to other. + */ + bool operator!= ( const QgsSnappingConfig& other ) const; + + public: + /** + * Reads the configuration from the specified QGIS project document. + * + * @note Added in QGIS 3.0 + */ + void readProject( const QDomDocument& doc ); + + /** + * Writes the configuration to the specified QGIS project document. + * + * @note Added in QGIS 3.0 + */ + void writeProject( QDomDocument& doc ); + + /** + * Adds the specified layers as individual layers to the configuration + * with standard configuration. + * When implementing a long-living QgsSnappingConfig (like the one in QgsProject) + * it is best to directly feed this with information from the layer registry. + * + * @return True if changes have been done. + * + * @note Added in QGIS 3.0 + */ + bool addLayers( const QList& layers ); + + + /** + * Removes the specified layers from the individual layer configuration. + * When implementing a long-living QgsSnappingConfig (like the one in QgsProject) + * it is best to directly feed this with information from the layer registry. + * + * @return True if changes have been done. + * + * @note Added in QGIS 3.0 + */ + bool removeLayers( const QList& layers ); + +}; diff --git a/python/core/qgssnappingutils.sip b/python/core/qgssnappingutils.sip index 56e064f961fa..4dcaff53494d 100644 --- a/python/core/qgssnappingutils.sip +++ b/python/core/qgssnappingutils.sip @@ -25,10 +25,11 @@ class QgsSnappingUtils : QObject /** Assign current map settings to the utils - used for conversion between screen coords to map coords */ void setMapSettings( const QgsMapSettings& settings ); - const QgsMapSettings& mapSettings() const; + QgsMapSettings mapSettings() const; /** Set current layer so that if mode is SnapCurrentLayer we know which layer to use */ void setCurrentLayer( QgsVectorLayer* layer ); + /** The current layer used if mode is SnapCurrentLayer */ QgsVectorLayer* currentLayer() const; @@ -42,11 +43,6 @@ class QgsSnappingUtils : QObject SnapAdvanced, //!< snap according to the configuration set in setLayers() }; - /** Set how the snapping to map is done */ - void setSnapToMapMode( SnapToMapMode mode ); - /** Find out how the snapping to map is done */ - SnapToMapMode snapToMapMode() const; - enum IndexingStrategy { IndexAlwaysFull, //!< For all layers build index of full extent. Uses more memory, but queries are faster. @@ -59,11 +55,6 @@ class QgsSnappingUtils : QObject /** Find out which strategy is used for indexing - by default hybrid indexing is used */ IndexingStrategy indexingStrategy() const; - /** Configure options used when the mode is snap to current layer or to all layers */ - void setDefaultSettings( int type, double tolerance, QgsTolerance::UnitType unit ); - /** Query options used when the mode is snap to current layer or to all layers */ - void defaultSettings( int& type /Out/, double& tolerance /Out/, QgsTolerance::UnitType& unit /Out/ ); - /** * Configures how a certain layer should be handled in a snapping operation */ @@ -84,28 +75,27 @@ class QgsSnappingUtils : QObject QgsTolerance::UnitType unit; }; - /** Set layers which will be used for snapping */ - void setLayers( const QList& layers ); /** Query layers used for snapping */ QList layers() const; - /** Set whether to consider intersections of nearby segments for snapping */ - void setSnapOnIntersections( bool enabled ); - /** Query whether to consider intersections of nearby segments for snapping */ - bool snapOnIntersections() const; - /** Get extra information about the instance * @note added in QGIS 2.14 */ QString dump(); - public slots: - /** Read snapping configuration from the project */ - void readConfigFromProject(); + /** + * The snapping configuration controls the behavior of this object + */ + QgsSnappingConfig config() const; + + /** + * The snapping configuration controls the behavior of this object + */ + void setConfig( const QgsSnappingConfig& snappingConfig ); signals: - /** Emitted when snapping configuration has been changed - * @note added in QGIS 2.14 + /** + * Emitted when the snapping settings object changes. */ void configChanged(); diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index f452f162870b..c0a95ef9f0cf 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -49,6 +49,8 @@ SET(QGIS_APP_SRCS qgsmaplayerstyleguiutils.cpp qgsrulebasedlabelingwidget.cpp qgssavestyletodbdialog.cpp + qgssnappinglayertreemodel.cpp + qgssnappingwidget.cpp qgsstatusbarcoordinateswidget.cpp qgsstatusbarmagnifierwidget.cpp qgsstatusbarscalewidget.cpp @@ -228,6 +230,8 @@ SET (QGIS_APP_MOC_HDRS qgsmaplayerstyleguiutils.h qgsrulebasedlabelingwidget.h qgssavestyletodbdialog.h + qgssnappinglayertreemodel.h + qgssnappingwidget.h qgsstatusbarcoordinateswidget.h qgsstatusbarmagnifierwidget.h qgsstatusbarscalewidget.h diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index d5601a6829d5..f4d3092d6b5d 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -215,6 +216,7 @@ #include "qgsshortcutsmanager.h" #include "qgssinglebandgrayrenderer.h" #include "qgssnappingdialog.h" +#include "qgssnappingwidget.h" #include "qgssourceselectdialog.h" #include "qgssponsors.h" #include "qgsstatisticalsummarydockwidget.h" @@ -589,6 +591,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh , mInternalClipboard( nullptr ) , mShowProjectionTab( false ) , mPythonUtils( nullptr ) + , mSnappingWidget( nullptr ) , mMapStylingDock( nullptr ) , mComposerManager( nullptr ) , mpTileScaleWidget( nullptr ) @@ -758,8 +761,8 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh startProfile( "Snapping utils" ); mSnappingUtils = new QgsMapCanvasSnappingUtils( mMapCanvas, this ); mMapCanvas->setSnappingUtils( mSnappingUtils ); - connect( QgsProject::instance(), SIGNAL( snapSettingsChanged() ), mSnappingUtils, SLOT( readConfigFromProject() ) ); - connect( this, SIGNAL( projectRead() ), mSnappingUtils, SLOT( readConfigFromProject() ) ); + connect( QgsProject::instance(), &QgsProject::snappingConfigChanged, this, &QgisApp::onSnappingConfigChanged ); + endProfile(); functionProfile( &QgisApp::createActions, this, "Create actions" ); @@ -807,8 +810,27 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh endProfile(); startProfile( "Snapping dialog" ); - mSnappingDialog = new QgsSnappingDialog( this, mMapCanvas ); - mSnappingDialog->setObjectName( "SnappingOption" ); + mSnappingDialogWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, this ); + QString mainSnappingWidgetMode = QSettings().value( "/qgis/mainSnappingWidgetMode", "dialog" ).toString(); + if ( mainSnappingWidgetMode == "dock" ) + { + QgsSnappingDock* dock = new QgsSnappingDock( tr( "Snapping and Digitizing Options" ), QgisApp::instance() ); + dock->setAllowedAreas( Qt::AllDockWidgetAreas ); + dock->setWidget( mSnappingDialogWidget ); + addDockWidget( Qt::LeftDockWidgetArea, dock ); + mSnappingDialogContainer = dock; + dock->hide(); + } + else + { + QDialog* dialog = new QDialog( this ); + dialog->setWindowTitle( tr( "Project snapping settings" ) ); + QVBoxLayout* layout = new QVBoxLayout( dialog ); + QDialogButtonBox* button = new QDialogButtonBox( QDialogButtonBox::Close ); + layout->addWidget( mSnappingDialogWidget ); + layout->addWidget( button ); + mSnappingDialogContainer = dialog; + } endProfile(); mBrowserWidget = new QgsBrowserDockWidget( tr( "Browser Panel" ), this ); @@ -1160,7 +1182,8 @@ QgisApp::QgisApp() , mAdvancedDigitizingDockWidget( nullptr ) , mStatisticalSummaryDockWidget( nullptr ) , mBookMarksDockWidget( nullptr ) - , mSnappingDialog( nullptr ) + , mSnappingWidget( nullptr ) + , mSnappingDialogContainer( nullptr ) , mPluginManager( nullptr ) , mMapStylingDock( nullptr ) , mMapStyleWidget( nullptr ) @@ -2048,6 +2071,18 @@ void QgisApp::createToolBars() << mWebToolBar << mLabelToolBar; + + // snapping widget as tool bar + QString simpleSnappingWidgetMode = QSettings().value( "/qgis/simpleSnappingWidgetMode", "toolbar" ).toString(); + if ( simpleSnappingWidgetMode != "statusbar" ) + { + mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, mSnappingToolBar ); + mSnappingWidget->setObjectName( "mSnappingWidget" ); + //mSnappingWidget->setFont( myFont ); + connect( mSnappingWidget, SIGNAL( snapSettingsChanged() ), QgsProject::instance(), SIGNAL( snapSettingsChanged() ) ); + mSnappingToolBar->addWidget( mSnappingWidget ); + } + QList toolbarMenuActions; // Set action names so that they can be used in customization Q_FOREACH ( QToolBar *toolBar, toolbarMenuToolBars ) @@ -2395,6 +2430,17 @@ void QgisApp::createStatusBar() mRotationLabel->setToolTip( tr( "Current clockwise map rotation in degrees" ) ); statusBar()->addPermanentWidget( mRotationLabel, 0 ); + // snapping widget + QString simpleSnappingWidgetMode = QSettings().value( "/qgis/simpleSnappingWidgetMode", "toolbar" ).toString(); + if ( simpleSnappingWidgetMode == "statusbar" ) + { + mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, statusBar() ); + mSnappingWidget->setObjectName( "mSnappingWidget" ); + mSnappingWidget->setFont( myFont ); + connect( mSnappingWidget, SIGNAL( snapSettingsChanged() ), QgsProject::instance(), SIGNAL( snapSettingsChanged() ) ); + statusBar()->addPermanentWidget( mSnappingWidget, 0 ); + } + mRotationEdit = new QgsDoubleSpinBox( statusBar() ); mRotationEdit->setObjectName( "mRotationEdit" ); mRotationEdit->setClearValue( 0.0 ); @@ -7179,7 +7225,7 @@ void QgisApp::offsetPointSymbol() void QgisApp::snappingOptions() { - mSnappingDialog->show(); + mSnappingDialogContainer->show(); } void QgisApp::splitFeatures() @@ -11211,6 +11257,11 @@ void QgisApp::onTransactionGroupsChanged() } } +void QgisApp::onSnappingConfigChanged() +{ + mSnappingUtils->setConfig( QgsProject::instance()->snappingConfig() ); +} + void QgisApp::startProfile( const QString& name ) { mProfiler->start( name ); diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index 61b79b7ddad7..e1dd8e889fdf 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -40,49 +40,50 @@ class QValidator; class QgisAppInterface; class QgisAppStyleSheet; class QgsAnnotationItem; +class QgsAuthManager; +class QgsBookmarks; class QgsClipboard; class QgsComposer; class QgsComposerManager; class QgsComposerView; -class QgsCustomDropHandler; -class QgsStatusBarCoordinatesWidget; -class QgsStatusBarMagnifierWidget; -class QgsStatusBarScaleWidget; class QgsContrastEnhancement; +class QgsCoordinateReferenceSystem; +class QgsCustomDropHandler; class QgsCustomLayerOrderWidget; class QgsDockWidget; class QgsDoubleSpinBox; class QgsFeature; +class QgsFeatureStore; class QgsGeometry; class QgsLayerTreeMapCanvasBridge; class QgsLayerTreeView; class QgsMapCanvas; class QgsMapLayer; class QgsMapLayerConfigWidgetFactory; +class QgsMapOverviewCanvas; class QgsMapTip; class QgsMapTool; class QgsMapToolAdvancedDigitizing; -class QgsMapOverviewCanvas; class QgsPluginLayer; +class QgsPluginLayer; +class QgsPluginManager; class QgsPoint; class QgsProviderRegistry; class QgsPythonUtils; +class QgsRasterLayer; class QgsRectangle; +class QgsRuntimeProfiler; class QgsSnappingUtils; +class QgsSnappingWidget; +class QgsStatusBarCoordinatesWidget; +class QgsStatusBarMagnifierWidget; +class QgsStatusBarScaleWidget; class QgsTransactionGroup; class QgsUndoWidget; class QgsUserInputDockWidget; class QgsVectorLayer; class QgsVectorLayerTools; class QgsWelcomePage; -class QgsRasterLayer; -class QgsPluginLayer; -class QgsCoordinateReferenceSystem; -class QgsFeatureStore; -class QgsAuthManager; -class QgsPluginManager; -class QgsRuntimeProfiler; -class QgsBookmarks; class QDomDocument; class QNetworkReply; @@ -728,6 +729,8 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow private slots: void onTransactionGroupsChanged(); + void onSnappingConfigChanged(); + //! validate a SRS void validateCrs( QgsCoordinateReferenceSystem &crs ); @@ -1741,7 +1744,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QgsStatisticalSummaryDockWidget* mStatisticalSummaryDockWidget; QgsBookmarks* mBookMarksDockWidget; - QgsSnappingDialog *mSnappingDialog; + //! snapping widget + QgsSnappingWidget *mSnappingWidget; + QWidget *mSnappingDialogContainer; + QgsSnappingWidget *mSnappingDialogWidget; QgsPluginManager *mPluginManager; QgsDockWidget *mMapStylingDock; diff --git a/src/app/qgsmaptooloffsetcurve.cpp b/src/app/qgsmaptooloffsetcurve.cpp index e0e8a5d9481d..8722764e1b90 100644 --- a/src/app/qgsmaptooloffsetcurve.cpp +++ b/src/app/qgsmaptooloffsetcurve.cpp @@ -22,6 +22,7 @@ #include "qgssnappingutils.h" #include "qgsvectorlayer.h" #include "qgsvertexmarker.h" +#include "qgssnappingconfig.h" #include #include @@ -84,24 +85,20 @@ void QgsMapToolOffsetCurve::canvasReleaseEvent( QgsMapMouseEvent* e ) QgsSnappingUtils* snapping = mCanvas->snappingUtils(); // store previous settings - int oldType; - double oldSearchRadius; - QgsTolerance::UnitType oldSearchRadiusUnit; - QgsSnappingUtils::SnapToMapMode oldMode = snapping->snapToMapMode(); - snapping->defaultSettings( oldType, oldSearchRadius, oldSearchRadiusUnit ); - + QgsSnappingConfig oldConfig = snapping->config(); + QgsSnappingConfig config = snapping->config(); // setup new settings (temporary) QSettings settings; - snapping->setSnapToMapMode( QgsSnappingUtils::SnapAllLayers ); - snapping->setDefaultSettings( QgsPointLocator::Edge, - settings.value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble(), - ( QgsTolerance::UnitType ) settings.value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt() ); + config.setMode( QgsSnappingConfig::AllLayers ); + config.setType( QgsSnappingConfig::Segment ); + config.setTolerance( settings.value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble() ); + config.setUnits( static_cast( settings.value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt() ) ); + snapping->setConfig( config ); QgsPointLocator::Match match = snapping->snapToMap( e->pos() ); // restore old settings - snapping->setSnapToMapMode( oldMode ); - snapping->setDefaultSettings( oldType, oldSearchRadius, oldSearchRadiusUnit ); + snapping->setConfig( oldConfig ); if ( match.hasEdge() && match.layer() ) { diff --git a/src/app/qgsoptions.cpp b/src/app/qgsoptions.cpp index cb7576b04cc4..f954d7efe234 100644 --- a/src/app/qgsoptions.cpp +++ b/src/app/qgsoptions.cpp @@ -625,7 +625,6 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) cbxShowTips->setChecked( mSettings->value( QString( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), true ).toBool() ); cbxCheckVersion->setChecked( mSettings->value( "/qgis/checkVersion", true ).toBool() ); cbxAttributeTableDocked->setChecked( mSettings->value( "/qgis/dockAttributeTable", false ).toBool() ); - cbxSnappingOptionsDocked->setChecked( mSettings->value( "/qgis/dockSnapping", false ).toBool() ); cbxAddPostgisDC->setChecked( mSettings->value( "/qgis/addPostgisDC", false ).toBool() ); cbxAddOracleDC->setChecked( mSettings->value( "/qgis/addOracleDC", false ).toBool() ); cbxCompileExpressions->setChecked( mSettings->value( "/qgis/compileExpressions", true ).toBool() ); @@ -912,6 +911,15 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) chkDisableAttributeValuesDlg->setChecked( mSettings->value( "/qgis/digitizing/disable_enter_attribute_values_dialog", false ).toBool() ); mValidateGeometries->setCurrentIndex( mSettings->value( "/qgis/digitizing/validate_geometries", 1 ).toInt() ); + mSnappingMainDialogComboBox->clear(); + mSnappingMainDialogComboBox->addItem( tr( "dialog" ), "dialog" ); + mSnappingMainDialogComboBox->addItem( tr( "dock" ), "dock" ); + mSnappingMainDialogComboBox->setCurrentIndex( mSnappingMainDialogComboBox->findData( mSettings->value( "/qgis/mainSnappingWidgetMode", "dialog" ).toString() ) ); + mSnappingSimplePanelComboBox->clear(); + mSnappingSimplePanelComboBox->addItem( tr( "tool bar" ), "toolbar" ); + mSnappingSimplePanelComboBox->addItem( tr( "status bar" ), "statusbar" ); + mSnappingSimplePanelComboBox->setCurrentIndex( mSnappingSimplePanelComboBox->findData( mSettings->value( "/qgis/simpleSnappingWidgetMode", "toolbar" ).toString() ) ); + mOffsetJoinStyleComboBox->addItem( tr( "Round" ), 0 ); mOffsetJoinStyleComboBox->addItem( tr( "Mitre" ), 1 ); mOffsetJoinStyleComboBox->addItem( tr( "Bevel" ), 2 ); @@ -1182,7 +1190,9 @@ void QgsOptions::saveOptions() mSettings->setValue( "/qgis/scanZipInBrowser2", cmbScanZipInBrowser->currentData().toString() ); mSettings->setValue( "/qgis/ignoreShapeEncoding", cbxIgnoreShapeEncoding->isChecked() ); - mSettings->setValue( "/qgis/dockSnapping", cbxSnappingOptionsDocked->isChecked() ); + mSettings->setValue( "/qgis/mainSnappingWidgetMode", mSnappingMainDialogComboBox->currentData() ); + mSettings->setValue( "/qgis/simpleSnappingWidgetMode", mSnappingSimplePanelComboBox->currentData() ); + mSettings->setValue( "/qgis/addPostgisDC", cbxAddPostgisDC->isChecked() ); mSettings->setValue( "/qgis/addOracleDC", cbxAddOracleDC->isChecked() ); mSettings->setValue( "/qgis/compileExpressions", cbxCompileExpressions->isChecked() ); diff --git a/src/app/qgssnappingdialog.cpp b/src/app/qgssnappingdialog.cpp index d61aeab89dd3..145a295698a9 100644 --- a/src/app/qgssnappingdialog.cpp +++ b/src/app/qgssnappingdialog.cpp @@ -15,22 +15,24 @@ * * ***************************************************************************/ -#include "qgssnappingdialog.h" +#include "qgisapp.h" +#include "qgsdockwidget.h" +#include "qgslogger.h" #include "qgsmapcanvas.h" #include "qgsmaplayer.h" -#include "qgsvectorlayer.h" #include "qgsmaplayerregistry.h" -#include "qgisapp.h" #include "qgsproject.h" -#include "qgslogger.h" -#include "qgsdockwidget.h" +#include "qgssnappingdialog.h" +#include "qgsvectorlayer.h" + #include -#include #include +#include +#include #include #include -#include + QgsSnappingDialog::QgsSnappingDialog( QWidget* parent, QgsMapCanvas* canvas ) : QDialog( parent ) diff --git a/src/app/qgssnappinglayertreemodel.cpp b/src/app/qgssnappinglayertreemodel.cpp new file mode 100644 index 000000000000..8007309e5cf3 --- /dev/null +++ b/src/app/qgssnappinglayertreemodel.cpp @@ -0,0 +1,636 @@ +/*************************************************************************** + qgssnappinglayertreemodel.cpp - QgsSnappingLayerTreeView + + --------------------- + begin : 31.8.2016 + copyright : (C) 2016 by Denis Rouzaud + email : denis.rouzaud@gmail.com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include +#include + +#include "qgssnappinglayertreemodel.h" + +#include "qgslayertree.h" +#include "qgsmapcanvas.h" +#include "qgsproject.h" +#include "qgssnappingconfig.h" +#include "qgsvectorlayer.h" + + +QgsSnappingLayerDelegate::QgsSnappingLayerDelegate( QgsMapCanvas* canvas, QObject* parent ) + : QItemDelegate( parent ) + , mCanvas( canvas ) +{ +} + +QWidget* QgsSnappingLayerDelegate::createEditor( QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index ) const +{ + Q_UNUSED( option ); + Q_UNUSED( index ); + + if ( index.column() == QgsSnappingLayerTreeModel::TypeColumn ) + { + QComboBox* w = new QComboBox( parent ); + w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertex.svg" ) ), "Vertex", QgsSnappingConfig::Vertex ); + w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertexAndSegment.svg" ) ), "Vertex and segment", QgsSnappingConfig::VertexAndSegment ); + w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingSegment.svg" ) ), "Segment", QgsSnappingConfig::Segment ); + return w; + } + + if ( index.column() == QgsSnappingLayerTreeModel::ToleranceColumn ) + { + QDoubleSpinBox* w = new QDoubleSpinBox( parent ); + QVariant val = index.model()->data( index.model()->sibling( index.row(), QgsSnappingLayerTreeModel::UnitsColumn, index ), Qt::UserRole ); + if ( val.isValid() ) + { + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )val.toInt(); + if ( units == QgsTolerance::Pixels ) + { + w->setDecimals( 0 ); + } + else + { + QgsUnitTypes::DistanceUnitType type = QgsUnitTypes::unitType( mCanvas->mapUnits() ); + w->setDecimals( type == QgsUnitTypes::Standard ? 2 : 5 ); + } + } + else + { + w->setDecimals( 5 ); + } + return w; + } + + if ( index.column() == QgsSnappingLayerTreeModel::UnitsColumn ) + { + QComboBox* w = new QComboBox( parent ); + w->addItem( tr( "px" ), QgsTolerance::Pixels ); + w->addItem( QgsUnitTypes::toString( QgsProject::instance()->distanceUnits() ), QgsTolerance::ProjectUnits ); + return w; + } + + return nullptr; +} + +void QgsSnappingLayerDelegate::setEditorData( QWidget* editor, const QModelIndex& index ) const +{ + QVariant val = index.model()->data( index, Qt::UserRole ); + if ( !val.isValid() ) + return; + + if ( index.column() == QgsSnappingLayerTreeModel::TypeColumn ) + { + QgsSnappingConfig::SnappingType type = ( QgsSnappingConfig::SnappingType )val.toInt(); + QComboBox *cb = qobject_cast( editor ); + if ( cb ) + { + cb->setCurrentIndex( cb->findData( type ) ); + } + } + else if ( index.column() == QgsSnappingLayerTreeModel::ToleranceColumn ) + { + QDoubleSpinBox *w = qobject_cast( editor ); + if ( w ) + { + w->setValue( val.toDouble() ); + } + } + else if ( index.column() == QgsSnappingLayerTreeModel::UnitsColumn ) + { + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )val.toInt(); + QComboBox *w = qobject_cast( editor ); + if ( w ) + { + w->setCurrentIndex( w->findData( units ) ); + } + } +} + +void QgsSnappingLayerDelegate::setModelData( QWidget* editor, QAbstractItemModel* model, const QModelIndex& index ) const +{ + if ( index.column() == QgsSnappingLayerTreeModel::TypeColumn || + index.column() == QgsSnappingLayerTreeModel::UnitsColumn ) + { + QComboBox *w = qobject_cast( editor ); + if ( w ) + { + model->setData( index, w->currentData(), Qt::EditRole ); + } + } + else if ( index.column() == QgsSnappingLayerTreeModel::ToleranceColumn ) + { + QDoubleSpinBox *w = qobject_cast( editor ); + if ( w ) + { + model->setData( index, w->value(), Qt::EditRole ); + } + } +} + + +QgsSnappingLayerTreeModel::QgsSnappingLayerTreeModel( QgsProject* project, QObject *parent ) + : QSortFilterProxyModel( parent ) + , mProject( project ) + , mIndividualLayerSettings( project->snappingConfig().individualLayerSettings() ) +{ + connect( project, &QgsProject::snappingConfigChanged, this, &QgsSnappingLayerTreeModel::onSnappingSettingsChanged ); +} + +QgsSnappingLayerTreeModel::~QgsSnappingLayerTreeModel() +{ +} + +int QgsSnappingLayerTreeModel::columnCount( const QModelIndex& parent ) const +{ + Q_UNUSED( parent ); + return 5; +} + +Qt::ItemFlags QgsSnappingLayerTreeModel::flags( const QModelIndex& idx ) const +{ + if ( idx.column() == LayerColumn ) + { + return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; + } + + QgsVectorLayer* vl = vectorLayer( idx ); + if ( !vl ) + { + return Qt::NoItemFlags; + } + else + { + const QModelIndex layerIndex = sibling( idx.row(), LayerColumn, idx ); + if ( data( layerIndex, Qt::CheckStateRole ) == Qt::Checked ) + { + if ( idx.column() == AvoidIntersectionColumn ) + { + if ( vl->geometryType() == QgsWkbTypes::PolygonGeometry ) + { + return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsUserCheckable; + } + else + { + return Qt::NoItemFlags; + } + } + else + { + return Qt::ItemIsEnabled | Qt::ItemIsEditable; + } + } + } + return Qt::NoItemFlags; +} + +QModelIndex QgsSnappingLayerTreeModel::index( int row, int column, const QModelIndex& parent ) const +{ + QModelIndex newIndex = QSortFilterProxyModel::index( row, 0, parent ); + if ( column == LayerColumn ) + return newIndex; + + return createIndex( row, column, newIndex.internalId() ); +} + +QModelIndex QgsSnappingLayerTreeModel::parent( const QModelIndex& child ) const +{ + return QSortFilterProxyModel::parent( createIndex( child.row(), 0, child.internalId() ) ); +} + +QModelIndex QgsSnappingLayerTreeModel::sibling( int row, int column, const QModelIndex& idx ) const +{ + QModelIndex parent = idx.parent(); + return index( row, column, parent ); +} + +QgsVectorLayer* QgsSnappingLayerTreeModel::vectorLayer( const QModelIndex& idx ) const +{ + QgsLayerTreeNode* node; + if ( idx.column() == LayerColumn ) + { + node = mLayerTreeModel->index2node( mapToSource( idx ) ); + } + else + { + node = mLayerTreeModel->index2node( mapToSource( index( idx.row(), 0, idx.parent() ) ) ); + } + + if ( !node || !QgsLayerTree::isLayer( node ) ) + return nullptr; + + return qobject_cast( QgsLayerTree::toLayer( node )->layer() ); +} + +void QgsSnappingLayerTreeModel::onSnappingSettingsChanged() +{ + const QHash oldSettings = mIndividualLayerSettings; + + Q_FOREACH ( QgsVectorLayer* vl, oldSettings.keys() ) + { + if ( !mProject->snappingConfig().individualLayerSettings().contains( vl ) ) + { + beginResetModel(); + mIndividualLayerSettings = mProject->snappingConfig().individualLayerSettings(); + endResetModel(); + return; + } + } + Q_FOREACH ( QgsVectorLayer* vl, mProject->snappingConfig().individualLayerSettings().keys() ) + { + if ( !oldSettings.contains( vl ) ) + { + beginResetModel(); + mIndividualLayerSettings = mProject->snappingConfig().individualLayerSettings(); + endResetModel(); + return; + } + } + + hasRowchanged( mLayerTreeModel->rootGroup(), oldSettings ); +} + +void QgsSnappingLayerTreeModel::hasRowchanged( QgsLayerTreeNode* node, const QHash &oldSettings ) +{ + if ( node->nodeType() == QgsLayerTreeNode::NodeGroup ) + { + Q_FOREACH ( QgsLayerTreeNode *child, node->children() ) + { + hasRowchanged( child, oldSettings ); + } + } + else + { + QModelIndex idx = mapFromSource( mLayerTreeModel->node2index( node ) ); + QgsVectorLayer* vl = vectorLayer( idx ); + if ( !vl ) + { + emit dataChanged( QModelIndex(), idx ); + } + if ( oldSettings.value( vl ) != mProject->snappingConfig().individualLayerSettings().value( vl ) ) + { + mIndividualLayerSettings.insert( vl, mProject->snappingConfig().individualLayerSettings().value( vl ) ); + emit dataChanged( idx, index( idx.row(), columnCount( idx ) - 1 ) ); + } + } +} + +QgsLayerTreeModel* QgsSnappingLayerTreeModel::layerTreeModel() const +{ + return mLayerTreeModel; +} + +void QgsSnappingLayerTreeModel::setLayerTreeModel( QgsLayerTreeModel* layerTreeModel ) +{ + mLayerTreeModel = layerTreeModel; + QSortFilterProxyModel::setSourceModel( layerTreeModel ); +} + +bool QgsSnappingLayerTreeModel::filterAcceptsRow( int sourceRow, const QModelIndex& sourceParent ) const +{ + QgsLayerTreeNode* node = mLayerTreeModel->index2node( mLayerTreeModel->index( sourceRow, 0, sourceParent ) ); + return nodeShown( node ); +} + +bool QgsSnappingLayerTreeModel::nodeShown( QgsLayerTreeNode* node ) const +{ + if ( !node ) + return false; + if ( node->nodeType() == QgsLayerTreeNode::NodeGroup ) + { + Q_FOREACH ( QgsLayerTreeNode *child, node->children() ) + { + if ( nodeShown( child ) ) + { + return true; + } + } + return false; + } + else + { + QgsMapLayer* layer = QgsLayerTree::toLayer( node )->layer(); + if ( layer && layer->type() == QgsMapLayer::VectorLayer ) + return true; + } + return false; +} + +QVariant QgsSnappingLayerTreeModel::headerData( int section, Qt::Orientation orientation, int role ) const +{ + if ( orientation == Qt::Horizontal ) + { + if ( role == Qt::DisplayRole ) + { + switch ( section ) + { + case 0: + return tr( "Layer" ); + case 1: + return tr( "Type" ); + case 2: + return tr( "Tolerance" ); + case 3: + return tr( "Units" ); + case 4: + return tr( "Avoid intersection" ); + default: + return QVariant(); + } + } + } + return mLayerTreeModel->headerData( section, orientation, role ); +} + +QVariant QgsSnappingLayerTreeModel::data( const QModelIndex& idx, int role ) const +{ + if ( idx.column() == LayerColumn ) + { + if ( role == Qt::CheckStateRole ) + { + QgsVectorLayer *vl = vectorLayer( idx ); + if ( vl && mIndividualLayerSettings.contains( vl ) ) + { + const QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + if ( !ls.valid() ) + { + return QVariant(); + } + if ( ls.enabled() ) + { + return Qt::Checked; + } + else + { + return Qt::Unchecked; + } + } + else + { + // i.e. this is a group, analyse its children + bool hasChecked = false, hasUnchecked = false; + int n; + for ( n = 0; !hasChecked || !hasUnchecked; n++ ) + { + QVariant v = data( idx.child( n, 0 ), role ); + if ( !v.isValid() ) + break; + + switch ( v.toInt() ) + { + case Qt::PartiallyChecked: + // parent of partially checked child shared state + return Qt::PartiallyChecked; + + case Qt::Checked: + hasChecked = true; + break; + + case Qt::Unchecked: + hasUnchecked = true; + break; + } + } + + // unchecked leaf + if ( n == 0 ) + return Qt::Unchecked; + + // both + if ( hasChecked && hasUnchecked ) + return Qt::PartiallyChecked; + + if ( hasChecked ) + return Qt::Checked; + + Q_ASSERT( hasUnchecked ); + return Qt::Unchecked; + } + } + else + { + return mLayerTreeModel->data( mapToSource( idx ), role ); + } + } + else + { + QgsVectorLayer *vl = vectorLayer( idx ); + + if ( !vl || !mIndividualLayerSettings.contains( vl ) ) + { + return QVariant(); + } + + const QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + + // type + if ( idx.column() == TypeColumn ) + { + if ( role == Qt::DisplayRole ) + { + switch ( ls.type() ) + { + case QgsSnappingConfig::Vertex: + return tr( "vertex" ); + case QgsSnappingConfig::VertexAndSegment: + return tr( "vertex and segment" ); + case QgsSnappingConfig::Segment: + return tr( "segment" ); + default: + return tr( "N/A" ); + } + } + + if ( role == Qt::UserRole ) + return ls.type(); + } + + // tolerance + if ( idx.column() == ToleranceColumn ) + { + if ( role == Qt::DisplayRole ) + { + return QString::number( ls.tolerance() ); + } + + if ( role == Qt::UserRole ) + { + return ls.tolerance(); + } + } + + // units + if ( idx.column() == UnitsColumn ) + { + if ( role == Qt::DisplayRole ) + { + switch ( ls.units() ) + { + case QgsTolerance::Pixels: + return tr( "pixels" ); + case QgsTolerance::ProjectUnits: + return QgsUnitTypes::toString( QgsProject::instance()->distanceUnits() ); + default: + return QVariant(); + } + } + + if ( role == Qt::UserRole ) + { + return ls.units(); + } + } + + // avoid intersection + if ( idx.column() == AvoidIntersectionColumn ) + { + if ( role == Qt::CheckStateRole && vl->geometryType() == QgsWkbTypes::PolygonGeometry ) + { + if ( ls.avoidIntersection() ) + { + return Qt::Checked; + } + else + { + return Qt::Unchecked; + } + } + } + } + + return QVariant(); +} + +bool QgsSnappingLayerTreeModel::setData( const QModelIndex& index, const QVariant& value, int role ) +{ + if ( index.column() == LayerColumn ) + { + if ( role == Qt::CheckStateRole ) + { + int i = 0; + for ( i = 0; ; i++ ) + { + QModelIndex child = index.child( i, 0 ); + if ( !child.isValid() ) + break; + + setData( child, value, role ); + } + + if ( i == 0 ) + { + QgsVectorLayer* vl = vectorLayer( index ); + if ( !vl || !mIndividualLayerSettings.contains( vl ) ) + { + return false; + } + QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + if ( !ls.valid() ) + return false; + if ( value.toInt() == Qt::Checked ) + ls.setEnabled( true ); + else if ( value.toInt() == Qt::Unchecked ) + ls.setEnabled( false ); + else + Q_ASSERT( "expected checked or unchecked" ); + + QgsSnappingConfig config = mProject->snappingConfig(); + config.setIndividualLayerSettings( vl, ls ); + mProject->setSnappingConfig( config ); + } + return true; + } + + return mLayerTreeModel->setData( mapToSource( index ), value, role ); + } + + if ( index.column() == TypeColumn && role == Qt::EditRole ) + { + QgsVectorLayer *vl = vectorLayer( index ); + if ( vl ) + { + if ( !mIndividualLayerSettings.contains( vl ) ) + return false; + + QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + if ( !ls.valid() ) + return false; + + ls.setType(( QgsSnappingConfig::SnappingType )value.toInt() ); + QgsSnappingConfig config = mProject->snappingConfig(); + config.setIndividualLayerSettings( vl, ls ); + mProject->setSnappingConfig( config ); + return true; + } + } + + if ( index.column() == ToleranceColumn && role == Qt::EditRole ) + { + QgsVectorLayer *vl = vectorLayer( index ); + if ( vl ) + { + if ( !mIndividualLayerSettings.contains( vl ) ) + return false; + + QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + if ( !ls.valid() ) + return false; + + ls.setTolerance( value.toDouble() ); + QgsSnappingConfig config = mProject->snappingConfig(); + config.setIndividualLayerSettings( vl, ls ); + mProject->setSnappingConfig( config ); + return true; + } + } + + if ( index.column() == UnitsColumn && role == Qt::EditRole ) + { + QgsVectorLayer *vl = vectorLayer( index ); + if ( vl ) + { + if ( !mIndividualLayerSettings.contains( vl ) ) + return false; + + QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + if ( !ls.valid() ) + return false; + + ls.setUnits(( QgsTolerance::UnitType )value.toInt() ); + QgsSnappingConfig config = mProject->snappingConfig(); + config.setIndividualLayerSettings( vl, ls ); + mProject->setSnappingConfig( config ); + return true; + } + } + + if ( index.column() == AvoidIntersectionColumn && role == Qt::CheckStateRole ) + { + QgsVectorLayer *vl = vectorLayer( index ); + if ( vl ) + { + if ( !mIndividualLayerSettings.contains( vl ) ) + return false; + + QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); + if ( !ls.valid() ) + return false; + + ls.setAvoidIntersection( value.toInt() == Qt::Checked ); + QgsSnappingConfig config = mProject->snappingConfig(); + config.setIndividualLayerSettings( vl, ls ); + mProject->setSnappingConfig( config ); + return true; + } + } + + return false; +} diff --git a/src/app/qgssnappinglayertreemodel.h b/src/app/qgssnappinglayertreemodel.h new file mode 100644 index 000000000000..e54890b0516d --- /dev/null +++ b/src/app/qgssnappinglayertreemodel.h @@ -0,0 +1,94 @@ +/*************************************************************************** + qgssnappinglayertreemodel.h - QgsSnappingLayerTreeModel + + --------------------- + begin : 31.8.2016 + copyright : (C) 2016 by Denis Rouzaud + email : denis.rouzaud@gmail.com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSSNAPPINGLAYERTREEVIEW_H +#define QGSSNAPPINGLAYERTREEVIEW_H + + + +#include +#include + +#include "qgslayertreemodel.h" +#include "qgssnappingconfig.h" + +class QgsMapCanvas; +class QgsProject; + + +class APP_EXPORT QgsSnappingLayerDelegate : public QItemDelegate +{ + Q_OBJECT + + public: + explicit QgsSnappingLayerDelegate( QgsMapCanvas* canvas, QObject *parent = nullptr ); + + QWidget *createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const override; + void setEditorData( QWidget *editor, const QModelIndex &index ) const override; + void setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const override; + + private: + QgsMapCanvas* mCanvas; +}; + + +class APP_EXPORT QgsSnappingLayerTreeModel : public QSortFilterProxyModel +{ + Q_OBJECT + + public: + enum Columns + { + LayerColumn = 0, + TypeColumn, + ToleranceColumn, + UnitsColumn, + AvoidIntersectionColumn + }; + + QgsSnappingLayerTreeModel( QgsProject* project, QObject* parent = nullptr ); + ~QgsSnappingLayerTreeModel(); + + int columnCount( const QModelIndex& parent ) const override; + QVariant headerData( int section, Qt::Orientation orientation, int role ) const override; + Qt::ItemFlags flags( const QModelIndex& idx ) const override; + QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const override; + QModelIndex parent( const QModelIndex& child ) const override; + QModelIndex sibling( int row, int column, const QModelIndex &idx ) const override; + QVariant data( const QModelIndex& index, int role ) const override; + bool setData( const QModelIndex& index, const QVariant& value, int role ) override; + + QgsLayerTreeModel* layerTreeModel() const; + void setLayerTreeModel( QgsLayerTreeModel* layerTreeModel ); + + QgsVectorLayer* vectorLayer( const QModelIndex& idx ) const; + + protected: + bool filterAcceptsRow( int sourceRow, const QModelIndex& sourceParent ) const override; + + private slots: + void onSnappingSettingsChanged(); + + private: + bool nodeShown( QgsLayerTreeNode* node ) const; + + QgsProject* mProject; + QHash mIndividualLayerSettings; + QgsLayerTreeModel* mLayerTreeModel; + + void hasRowchanged( QgsLayerTreeNode* node, const QHash& oldSettings ); +}; + +#endif // QGSSNAPPINGLAYERTREEVIEW_H diff --git a/src/app/qgssnappingwidget.cpp b/src/app/qgssnappingwidget.cpp new file mode 100644 index 000000000000..3fbd47181cfc --- /dev/null +++ b/src/app/qgssnappingwidget.cpp @@ -0,0 +1,476 @@ +/*************************************************************************** + qgssnappingwidget.cpp + begin : August 2016 + copyright : (C) 2016 Denis Rouzaud + email : denis.rouzaud@gmail.com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "qgsapplication.h" +#include "qgslayertreegroup.h" +#include "qgslayertree.h" +#include "qgslayertreeview.h" +#include "qgsmapcanvas.h" +#include "qgsmaplayer.h" +#include "qgsproject.h" +#include "qgssnappingconfig.h" +#include "qgssnappinglayertreemodel.h" +#include "qgssnappingwidget.h" +#include "qgsunittypes.h" + + + +QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas *canvas, QWidget* parent ) + : QWidget( parent ) + , mProject( project ) + , mCanvas( canvas ) + , mModeAction( nullptr ) + , mTypeAction( nullptr ) + , mToleranceAction( nullptr ) + , mUnitAction( nullptr ) + , mLayerTreeView( nullptr ) +{ + // detect the type of display + QToolBar* tb = qobject_cast( parent ); + if ( tb ) + { + mDisplayMode = ToolBar; + setObjectName( "SnappingOptionToolBar" ); + } + else + { + QStatusBar *sb = qobject_cast( parent ); + if ( sb ) + { + mDisplayMode = StatusBar; + setObjectName( "SnappingOptionStatusBar" ); + } + else + { + mDisplayMode = Widget; + setObjectName( "SnappingOptionDialog" ); + } + } + + // enable button + mEnabledAction = new QAction( this ); + mEnabledAction->setCheckable( true ); + mEnabledAction->setIcon( QIcon( QgsApplication::getThemeIcon( "/mIconSnapping.svg" ) ) ); + mEnabledAction->setToolTip( tr( "Enable snapping" ) ); + mEnabledAction->setObjectName( "EnableSnappingAction" ); + connect( mEnabledAction, SIGNAL( toggled( bool ) ) , this, SLOT( enableSnapping( bool ) ) ); + + // mode button + mModeButton = new QToolButton(); + mModeButton->setToolTip( tr( "Snapping mode" ) ); + mModeButton->setPopupMode( QToolButton::InstantPopup ); + QMenu *modeMenu = new QMenu( tr( "Set snapping mode" ), this ); + mAllLayersAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingAllLayers.svg" ) ), "All layers", modeMenu ); + mActiveLayerAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingActiveLayer.svg" ) ), "Active layer", modeMenu ); + mAdvancedModeAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingAdvanced.svg" ) ), "Advanced configuration", modeMenu ); + modeMenu->addAction( mAllLayersAction ); + modeMenu->addAction( mActiveLayerAction ); + modeMenu->addAction( mAdvancedModeAction ); + mModeButton->setMenu( modeMenu ); + mModeButton->setObjectName( "SnappingModeButton" ); + if ( mDisplayMode == Widget ) + { + mModeButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); + } + connect( mModeButton, SIGNAL( triggered( QAction* ) ), this, SLOT( modeButtonTriggered( QAction* ) ) ); + + // type button + mTypeButton = new QToolButton(); + mTypeButton->setToolTip( tr( "Snapping type" ) ); + mTypeButton->setPopupMode( QToolButton::InstantPopup ); + QMenu *typeMenu = new QMenu( tr( "Set snapping mode" ), this ); + mVertexAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertex.svg" ) ), "Vertex", typeMenu ); + mVertexAndSegmentAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertexAndSegment.svg" ) ), "Vertex and segment", typeMenu ); + mSegmentAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingSegment.svg" ) ), "Segment", typeMenu ); + typeMenu->addAction( mVertexAction ); + typeMenu->addAction( mVertexAndSegmentAction ); + typeMenu->addAction( mSegmentAction ); + mTypeButton->setMenu( typeMenu ); + mTypeButton->setObjectName( "SnappingTypeButton" ); + if ( mDisplayMode == Widget ) + { + mTypeButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); + } + connect( mTypeButton, SIGNAL( triggered( QAction* ) ), this, SLOT( typeButtonTriggered( QAction* ) ) ); + + // tolerance + mToleranceSpinBox = new QDoubleSpinBox(); + mToleranceSpinBox->setToolTip( tr( "Snapping tolerance in defined units" ) ); + mToleranceSpinBox->setObjectName( "SnappingToleranceSpinBox" ); + connect( mToleranceSpinBox, SIGNAL( valueChanged( double ) ), this, SLOT( changeTolerance( double ) ) ); + + // units + mUnitsComboBox = new QComboBox(); + mUnitsComboBox->addItem( tr( "px" ), QgsTolerance::Pixels ); + mUnitsComboBox->addItem( QgsUnitTypes::toString( QgsProject::instance()->distanceUnits() ), QgsTolerance::ProjectUnits ); + mUnitsComboBox->setToolTip( tr( "Snapping unit type: pixels (px) or map units (mu)" ) ); + mUnitsComboBox->setObjectName( "SnappingUnitComboBox" ); + connect( mUnitsComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( changeUnit( int ) ) ); + + // topological editing button + mTopologicalEditingAction = new QAction( tr( "topological editing" ), this ); + mTopologicalEditingAction->setCheckable( true ); + mTopologicalEditingAction->setIcon( QIcon( QgsApplication::getThemeIcon( "/mIconTopologicalEditing.svg" ) ) ); + mTopologicalEditingAction->setToolTip( tr( "Enable topological editing" ) ); + mTopologicalEditingAction->setObjectName( "TopologicalEditingAction" ); + connect( mTopologicalEditingAction, SIGNAL( toggled( bool ) ) , this, SLOT( enableTopologicalEditing( bool ) ) ); + + // snapping on intersection button + mIntersectionSnappingAction = new QAction( tr( "snapping on intersection" ), this ); + mIntersectionSnappingAction->setCheckable( true ); + mIntersectionSnappingAction->setIcon( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingIntersection.svg" ) ) ); + mIntersectionSnappingAction->setToolTip( tr( "Enable snapping on intersection" ) ); + mIntersectionSnappingAction->setObjectName( "IntersectionSnappingAction" ); + connect( mIntersectionSnappingAction, SIGNAL( toggled( bool ) ) , this, SLOT( enableIntersectionSnapping( bool ) ) ); + + // layout + if ( mDisplayMode == ToolBar ) + { + // hiding widget in a toolbar is not possible, actions are required + tb->addAction( mEnabledAction ); + mModeAction = tb->addWidget( mModeButton ); + mTypeAction = tb->addWidget( mTypeButton ); + mToleranceAction = tb->addWidget( mToleranceSpinBox ); + mUnitAction = tb->addWidget( mUnitsComboBox ); + tb->addAction( mTopologicalEditingAction ); + tb->addAction( mIntersectionSnappingAction ); + } + else + { + // mode = widget or status bar + QHBoxLayout* layout = new QHBoxLayout(); + + QToolButton* enabledButton = new QToolButton(); + enabledButton->addAction( mEnabledAction ); + enabledButton->setDefaultAction( mEnabledAction ); + layout->addWidget( enabledButton ); + + layout->addWidget( mModeButton ); + layout->addWidget( mTypeButton ); + layout->addWidget( mToleranceSpinBox ) ; + layout->addWidget( mUnitsComboBox ) ; + + QToolButton* topoButton = new QToolButton(); + topoButton->addAction( mTopologicalEditingAction ); + topoButton->setDefaultAction( mTopologicalEditingAction ); + if ( mDisplayMode == Widget ) + { + topoButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); + } + layout->addWidget( topoButton ); + QToolButton* interButton = new QToolButton(); + interButton->addAction( mIntersectionSnappingAction ); + interButton->setDefaultAction( mIntersectionSnappingAction ); + if ( mDisplayMode == Widget ) + { + interButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); + } + layout->addWidget( interButton ); + + layout->setContentsMargins( 0, 0, 0, 0 ); + layout->setAlignment( Qt::AlignRight ); + layout->setSpacing( mDisplayMode == Widget ? 3 : 0 ); + + if ( mDisplayMode == Widget ) + { + mLayerTreeView = new QTreeView(); + QgsSnappingLayerTreeModel* model = new QgsSnappingLayerTreeModel( mProject, this ); + model->setLayerTreeModel( new QgsLayerTreeModel( QgsProject::instance()->layerTreeRoot(), model ) ); + // model->setFlags( 0 ); + mLayerTreeView->setModel( model ); + mLayerTreeView->resizeColumnToContents( 0 ); + mLayerTreeView->header()->show(); + mLayerTreeView->header()->setSectionResizeMode( QHeaderView::ResizeToContents ); + mLayerTreeView->header()->setSectionResizeMode( QHeaderView::Interactive ); + mLayerTreeView->setSelectionMode( QAbstractItemView::NoSelection ); + + // item delegates + mLayerTreeView->setEditTriggers( QAbstractItemView::AllEditTriggers ); + mLayerTreeView->setItemDelegate( new QgsSnappingLayerDelegate( mCanvas, this ) ); + + QGridLayout* topLayout = new QGridLayout(); + topLayout->addLayout( layout, 0, 0, Qt::AlignLeft | Qt::AlignTop ); + topLayout->addWidget( mLayerTreeView, 1, 0 ); + setLayout( topLayout ); + } + else + { + // mode = status bar + setLayout( layout ); + } + } + + // connect settings changed and map units changed to properly update the widget + connect( project, &QgsProject::snappingConfigChanged, this, &QgsSnappingWidget::projectSnapSettingsChanged ); + connect( mCanvas, SIGNAL( mapUnitsChanged() ), this, SLOT( updateToleranceDecimals() ) ); + + // modeChanged determines if widget are visible or not based on mode + modeChanged(); + updateToleranceDecimals(); +} + +QgsSnappingWidget::~QgsSnappingWidget() +{ + if ( mDisplayMode == Widget ) + { + QSettings().setValue( "/Windows/SnappingWidget/geometry", saveGeometry() ); + } +} + +void QgsSnappingWidget::projectSnapSettingsChanged() +{ + QgsSnappingConfig config = mProject->snappingConfig(); + if ( mConfig == config ) + return; + mConfig = config; + + mEnabledAction->setChecked( config.enabled() ); + + if ( config.mode() == QgsSnappingConfig::AllLayers && mModeButton->defaultAction() != mActiveLayerAction ) + { + mModeButton->setDefaultAction( mAllLayersAction ); + modeChanged(); + updateToleranceDecimals(); + } + if ( config.mode() == QgsSnappingConfig::ActiveLayer && mModeButton->defaultAction() != mActiveLayerAction ) + { + mModeButton->setDefaultAction( mActiveLayerAction ); + modeChanged(); + updateToleranceDecimals(); + } + if ( config.mode() == QgsSnappingConfig::AdvancedConfiguration && mModeButton->defaultAction() != mAdvancedModeAction ) + { + mModeButton->setDefaultAction( mAdvancedModeAction ); + modeChanged(); + updateToleranceDecimals(); + } + + if ( config.type() == QgsSnappingConfig::Vertex && mTypeButton->defaultAction() != mVertexAction ) + { + mTypeButton->setDefaultAction( mVertexAction ); + } + if ( config.type() == QgsSnappingConfig::VertexAndSegment && mTypeButton->defaultAction() != mVertexAndSegmentAction ) + { + mTypeButton->setDefaultAction( mVertexAndSegmentAction ); + } + if ( config.type() == QgsSnappingConfig::Segment && mTypeButton->defaultAction() != mSegmentAction ) + { + mTypeButton->setDefaultAction( mSegmentAction ); + } + + if ( mToleranceSpinBox->value() != config.tolerance() ) + { + mToleranceSpinBox->setValue( config.tolerance() ); + } + + if (( QgsTolerance::UnitType )mUnitsComboBox->currentData().toInt() != config.units() ) + { + mUnitsComboBox->setCurrentIndex( mUnitsComboBox->findData( config.units() ) ); + } + + if ( config.topologicalEditing() != mTopologicalEditingAction->isChecked() ) + { + mTopologicalEditingAction->setChecked( config.topologicalEditing() ); + } + + if ( config.intersectionSnapping() != mIntersectionSnappingAction->isChecked() ) + { + mIntersectionSnappingAction->setChecked( config.intersectionSnapping() ); + } +} + +void QgsSnappingWidget::enableSnapping( bool checked ) +{ + mModeButton->setEnabled( checked ); + mTypeButton->setEnabled( checked ); + mToleranceSpinBox->setEnabled( checked ); + mUnitsComboBox->setEnabled( checked ); + if ( mLayerTreeView ) + { + mLayerTreeView->setEnabled( checked ); + } + mTopologicalEditingAction->setEnabled( checked ); + mIntersectionSnappingAction->setEnabled( checked ); + + mConfig.setEnabled( checked ); + mProject->setSnappingConfig( mConfig ); +} + +void QgsSnappingWidget::changeTolerance( double tolerance ) +{ + mConfig.setTolerance( tolerance ); + mProject->setSnappingConfig( mConfig ); +} + +void QgsSnappingWidget::changeUnit( int idx ) +{ + QgsTolerance::UnitType unit = ( QgsTolerance::UnitType )mUnitsComboBox->itemData( idx ).toInt(); + mConfig.setUnits( unit ); + mProject->setSnappingConfig( mConfig ); + + updateToleranceDecimals(); +} + +void QgsSnappingWidget::enableTopologicalEditing( bool enabled ) +{ + mConfig.setTopologicalEditing( enabled ); + mProject->setSnappingConfig( mConfig ); +} + +void QgsSnappingWidget::enableIntersectionSnapping( bool enabled ) +{ + mConfig.setIntersectionSnapping( enabled ); + mProject->setSnappingConfig( mConfig ); +} + +void QgsSnappingWidget::modeButtonTriggered( QAction* action ) +{ + if ( action != mModeButton->defaultAction() ) + { + mModeButton->setDefaultAction( action ); + if ( action == mAllLayersAction ) + { + mConfig.setMode( QgsSnappingConfig::AllLayers ); + } + else if ( action == mActiveLayerAction ) + { + mConfig.setMode( QgsSnappingConfig::ActiveLayer ); + } + else if ( action == mAdvancedModeAction ) + { + mConfig.setMode( QgsSnappingConfig::AdvancedConfiguration ); + } + mProject->setSnappingConfig( mConfig ); + updateToleranceDecimals(); + modeChanged(); + } +} + +void QgsSnappingWidget::typeButtonTriggered( QAction* action ) +{ + if ( action != mTypeButton->defaultAction() ) + { + mTypeButton->setDefaultAction( action ); + if ( action == mVertexAction ) + { + mConfig.setType( QgsSnappingConfig::Vertex ); + } + else if ( action == mVertexAndSegmentAction ) + { + mConfig.setType( QgsSnappingConfig::VertexAndSegment ); + } + else if ( action == mSegmentAction ) + { + mConfig.setType( QgsSnappingConfig::Segment ); + } + mProject->setSnappingConfig( mConfig ); + } +} + +void QgsSnappingWidget::updateToleranceDecimals() +{ + if ( mConfig.units() == QgsTolerance::Pixels ) + { + mToleranceSpinBox->setDecimals( 0 ); + } + else + { + QgsUnitTypes::DistanceUnit mapUnit = mCanvas->mapUnits(); + QgsUnitTypes::DistanceUnitType type = QgsUnitTypes::unitType( mapUnit ); + if ( type == QgsUnitTypes::Standard ) + { + mToleranceSpinBox->setDecimals( 2 ); + } + else + { + mToleranceSpinBox->setDecimals( 5 ); + } + } +} + +void QgsSnappingWidget::modeChanged() +{ + bool advanced = mConfig.mode() == QgsSnappingConfig::AdvancedConfiguration; + + if ( mDisplayMode == ToolBar ) + { + mTypeAction->setVisible( !advanced ); + mToleranceAction->setVisible( !advanced ); + mUnitAction->setVisible( !advanced ); + } + else + { + mTypeButton->setVisible( !advanced ); + mToleranceSpinBox->setVisible( !advanced ); + mUnitsComboBox->setVisible( !advanced ); + if ( mDisplayMode == Widget && mLayerTreeView ) + { + mLayerTreeView->setVisible( advanced ); + } + } +} + +QgsSnappingConfig QgsSnappingWidget::config() const +{ + return mConfig; +} + +void QgsSnappingWidget::setConfig( const QgsSnappingConfig& config ) +{ + if ( mConfig == config ) + return; + + mConfig = config; +} + + + +void QgsSnappingWidget::cleanGroup( QgsLayerTreeNode *node ) +{ + QgsLayerTreeGroup *group = QgsLayerTree::isGroup( node ) ? QgsLayerTree::toGroup( node ) : nullptr; + if ( !group ) + return; + + QList toRemove; + Q_FOREACH ( QgsLayerTreeNode *child, node->children() ) + { + if ( QgsLayerTree::isLayer( child ) && QgsLayerTree::toLayer( child )->layer()->type() != QgsMapLayer::VectorLayer ) + { + toRemove << child; + continue; + } + + cleanGroup( child ); + + if ( QgsLayerTree::isGroup( child ) && child->children().isEmpty() ) + toRemove << child; + } + + Q_FOREACH ( QgsLayerTreeNode *child, toRemove ) + group->removeChildNode( child ); +} diff --git a/src/app/qgssnappingwidget.h b/src/app/qgssnappingwidget.h new file mode 100644 index 000000000000..0a3223cfb3f5 --- /dev/null +++ b/src/app/qgssnappingwidget.h @@ -0,0 +1,130 @@ +/*************************************************************************** + qgssnappingwidget.h + begin : August 2016 + copyright : (C) 2016 Denis Rouzaud + email : denis.rouzaud@gmail.com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSSNAPPINGWIDGET_H +#define QGSSNAPPINGWIDGET_H + +class QAction; +class QComboBox; +class QDoubleSpinBox; +class QFont; +class QToolButton; +class QTreeView; + +class QgsLayerTreeGroup; +class QgsLayerTreeNode; +class QgsLayerTreeView; +class QgsMapCanvas; +class QgsProject; + +#include "qgssnappingconfig.h" + +#include + +/** + * A widget which lets the user defines settings for snapping on a project + * The widget can be displayed as a toolbar, in the status bar or as dialog/widget. + * The display mode is automatically chose based on the parent widget type. + */ +class APP_EXPORT QgsSnappingWidget : public QWidget +{ + Q_OBJECT + + public: + + /** + * Constructor + * @param project The project with which this widget configuration will be synchronized + * @param canvas the map canvas (used for map units) + * @param parent is the parent widget. Based on the type of parent, it will + * be displayed a tool bar, in the status bar or as a widget/dialog. + */ + QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, QWidget* parent = nullptr ); + + /** Destructor */ + virtual ~QgsSnappingWidget(); + + /** + * The snapping configuration is what is managed by this widget. + */ + QgsSnappingConfig config() const; + + /** + * The snapping configuration is what is managed by this widget. + */ + void setConfig( const QgsSnappingConfig& config ); + + signals: + void snappingConfigChanged( ); + + private slots: + void projectSnapSettingsChanged(); + + void enableSnapping( bool checked ); + + void changeTolerance( double tolerance ); + + void changeUnit( int idx ); + + void enableTopologicalEditing( bool enabled ); + + void enableIntersectionSnapping( bool enabled ); + + void modeButtonTriggered( QAction* action ); + void typeButtonTriggered( QAction* action ); + + //! number of decimals of the tolerance spin box depends on map units + void updateToleranceDecimals(); + + private: + enum DisplayMode + { + ToolBar, + StatusBar, + Widget + }; + DisplayMode mDisplayMode; + + //! modeChanged determines if widget are visible or not based on mode + void modeChanged(); + + QgsProject* mProject; + QgsSnappingConfig mConfig; + QgsMapCanvas* mCanvas; + + QAction* mEnabledAction; + QToolButton* mModeButton; + QAction* mModeAction; // hide widget does not work on toolbar, action needed + QAction* mAllLayersAction; + QAction* mActiveLayerAction; + QAction* mAdvancedModeAction; + QToolButton* mTypeButton; + QAction* mTypeAction; // hide widget does not work on toolbar, action needed + QAction* mVertexAction; + QAction* mSegmentAction; + QAction* mVertexAndSegmentAction; + QDoubleSpinBox* mToleranceSpinBox; + QAction* mToleranceAction; // hide widget does not work on toolbar, action needed + QComboBox* mUnitsComboBox; + QAction* mUnitAction; // hide widget does not work on toolbar, action needed + QAction* mTopologicalEditingAction; + QAction* mIntersectionSnappingAction; + QTreeView* mLayerTreeView; + + void cleanGroup( QgsLayerTreeNode* node ); +}; + +#endif diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index e09cccab8218..b518d1c80d3b 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -179,6 +179,7 @@ SET(QGIS_CORE_SRCS qgspointlocator.cpp qgsproject.cpp qgsprojectfiletransform.cpp + qgssnappingconfig.cpp qgsprojectproperty.cpp qgsprojectversion.cpp qgsprovidermetadata.cpp @@ -678,6 +679,7 @@ SET(QGIS_CORE_HDRS qgsproject.h qgsprojectfiletransform.h qgsprojectproperty.h + qgssnappingconfig.h qgsprojectversion.h qgsprovidermetadata.h qgsproviderregistry.h @@ -692,6 +694,7 @@ SET(QGIS_CORE_HDRS qgsscaleutils.h qgssimplifymethod.h qgssnapper.h + qgssnappingconfig.h qgssnappingutils.h qgsspatialindex.h qgssqlexpressioncompiler.h diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 48cbfb9f660d..533de5cbe8bc 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -28,6 +28,7 @@ #include "qgspluginlayer.h" #include "qgspluginlayerregistry.h" #include "qgsprojectfiletransform.h" +#include "qgssnappingconfig.h" #include "qgsprojectproperty.h" #include "qgsprojectversion.h" #include "qgsrasterlayer.h" @@ -368,6 +369,7 @@ QgsProject::QgsProject() mLayerTreeRegistryBridge = new QgsLayerTreeRegistryBridge( mRootGroup, this ); connect( QgsMapLayerRegistry::instance(), SIGNAL( layersAdded( QList ) ), this, SLOT( onMapLayersAdded( QList ) ) ); connect( QgsMapLayerRegistry::instance(), SIGNAL( layersRemoved( QStringList ) ), this, SLOT( cleanTransactionGroups() ) ); + connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QList ) ), this, SLOT( onMapLayersRemoved( QList ) ) ); } @@ -479,6 +481,7 @@ void QgsProject::clear() imp_->clear(); mEmbeddedLayers.clear(); mRelationManager->clear(); + mSnappingConfig.reset(); mMapThemeCollection.reset( new QgsMapThemeCollection() ); @@ -632,6 +635,21 @@ void QgsProject::processLayerJoins( QgsVectorLayer* layer ) layer->updateFields(); } +QgsSnappingConfig QgsProject::snappingConfig() const +{ + return mSnappingConfig; +} + +void QgsProject::setSnappingConfig( const QgsSnappingConfig& snappingConfig ) +{ + if ( mSnappingConfig == snappingConfig ) + return; + + mSnappingConfig = snappingConfig; + setDirty(); + emit snappingConfigChanged(); +} + bool QgsProject::_getMapLayers( const QDomDocument& doc, QList& brokenNodes ) { // Layer order is set by the restoring the legend settings from project file. @@ -926,6 +944,9 @@ bool QgsProject::read() it.value()->setDependencies( it.value()->dependencies() ); } + mSnappingConfig.readProject( *doc ); + emit snappingConfigChanged(); + // read the project: used by map canvas and legend emit readProject( *doc ); @@ -1039,6 +1060,15 @@ void QgsProject::onMapLayersAdded( const QList& layers ) } } } + + if ( mSnappingConfig.addLayers( layers ) ) + emit snappingConfigChanged(); +} + +void QgsProject::onMapLayersRemoved( const QList& layers ) +{ + if ( mSnappingConfig.removeLayers( layers ) ) + emit snappingConfigChanged(); } void QgsProject::cleanTransactionGroups( bool force ) @@ -1143,6 +1173,8 @@ bool QgsProject::write() clonedRoot->writeXml( qgisNode ); delete clonedRoot; + mSnappingConfig.writeProject( *doc ); + // let map canvas and legend write their information emit writeProject( *doc ); @@ -1975,134 +2007,6 @@ void QgsProject::initializeEmbeddedSubtree( const QString &projectFilePath, QgsL } } -void QgsProject::setSnapSettingsForLayer( const QString &layerId, bool enabled, QgsSnapper::SnappingType type, QgsTolerance::UnitType unit, double tolerance, bool avoidIntersection ) -{ - QStringList layerIdList, enabledList, snapTypeList, toleranceUnitList, toleranceList, avoidIntersectionList; - snapSettings( layerIdList, enabledList, snapTypeList, toleranceUnitList, toleranceList, avoidIntersectionList ); - int idx = layerIdList.indexOf( layerId ); - if ( idx != -1 ) - { - layerIdList.removeAt( idx ); - enabledList.removeAt( idx ); - snapTypeList.removeAt( idx ); - toleranceUnitList.removeAt( idx ); - toleranceList.removeAt( idx ); - avoidIntersectionList.removeOne( layerId ); - } - - layerIdList.append( layerId ); - - // enabled - enabledList.append( enabled ? "enabled" : "disabled" ); - - // snap type - QString typeString; - if ( type == QgsSnapper::SnapToSegment ) - { - typeString = "to_segment"; - } - else if ( type == QgsSnapper::SnapToVertexAndSegment ) - { - typeString = "to_vertex_and_segment"; - } - else - { - typeString = "to_vertex"; - } - snapTypeList.append( typeString ); - - // units - toleranceUnitList.append( QString::number( unit ) ); - - // tolerance - toleranceList.append( QString::number( tolerance ) ); - - // avoid intersection - if ( avoidIntersection ) - { - avoidIntersectionList.append( layerId ); - } - - writeEntry( "Digitizing", "/LayerSnappingList", layerIdList ); - writeEntry( "Digitizing", "/LayerSnappingEnabledList", enabledList ); - writeEntry( "Digitizing", "/LayerSnappingToleranceList", toleranceList ); - writeEntry( "Digitizing", "/LayerSnappingToleranceUnitList", toleranceUnitList ); - writeEntry( "Digitizing", "/LayerSnapToList", snapTypeList ); - writeEntry( "Digitizing", "/AvoidIntersectionsList", avoidIntersectionList ); - emit snapSettingsChanged(); -} - -bool QgsProject::snapSettingsForLayer( const QString &layerId, bool &enabled, QgsSnapper::SnappingType &type, QgsTolerance::UnitType &units, double &tolerance, - bool &avoidIntersection ) const -{ - QStringList layerIdList, enabledList, snapTypeList, toleranceUnitList, toleranceList, avoidIntersectionList; - snapSettings( layerIdList, enabledList, snapTypeList, toleranceUnitList, toleranceList, avoidIntersectionList ); - int idx = layerIdList.indexOf( layerId ); - if ( idx == -1 ) - { - return false; - } - - // make sure all lists are long enough - int minListEntries = idx + 1; - if ( layerIdList.size() < minListEntries || enabledList.size() < minListEntries || snapTypeList.size() < minListEntries || - toleranceUnitList.size() < minListEntries || toleranceList.size() < minListEntries ) - { - return false; - } - - // enabled - enabled = enabledList.at( idx ) == "enabled"; - - // snap type - QString snapType = snapTypeList.at( idx ); - if ( snapType == "to_segment" ) - { - type = QgsSnapper::SnapToSegment; - } - else if ( snapType == "to_vertex_and_segment" ) - { - type = QgsSnapper::SnapToVertexAndSegment; - } - else // to vertex - { - type = QgsSnapper::SnapToVertex; - } - - // units - if ( toleranceUnitList.at( idx ) == "1" ) - { - units = QgsTolerance::Pixels; - } - else if ( toleranceUnitList.at( idx ) == "2" ) - { - units = QgsTolerance::ProjectUnits; - } - else - { - units = QgsTolerance::LayerUnits; - } - - // tolerance - tolerance = toleranceList.at( idx ).toDouble(); - - // avoid intersection - avoidIntersection = ( avoidIntersectionList.indexOf( layerId ) != -1 ); - - return true; -} - -void QgsProject::snapSettings( QStringList &layerIdList, QStringList &enabledList, QStringList &snapTypeList, QStringList &toleranceUnitList, QStringList &toleranceList, - QStringList &avoidIntersectionList ) const -{ - layerIdList = readListEntry( "Digitizing", "/LayerSnappingList" ); - enabledList = readListEntry( "Digitizing", "/LayerSnappingEnabledList" ); - toleranceList = readListEntry( "Digitizing", "/LayerSnappingToleranceList" ); - toleranceUnitList = readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList" ); - snapTypeList = readListEntry( "Digitizing", "/LayerSnapToList" ); - avoidIntersectionList = readListEntry( "Digitizing", "/AvoidIntersectionsList" ); -} - bool QgsProject::evaluateDefaultValues() const { return imp_->evaluateDefaultValues; @@ -2125,7 +2029,7 @@ void QgsProject::setEvaluateDefaultValues( bool evaluateDefaultValues ) void QgsProject::setTopologicalEditing( bool enabled ) { QgsProject::instance()->writeEntry( "Digitizing", "/TopologicalEditing", ( enabled ? 1 : 0 ) ); - emit snapSettingsChanged(); + // todo emit snapSettingsChanged(); } bool QgsProject::topologicalEditing() const diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index 5905fba58687..3e0590779c87 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -32,6 +32,7 @@ //#include #include "qgssnapper.h" #include "qgsunittypes.h" +#include "qgssnappingconfig.h" #include "qgsprojectversion.h" #include "qgsexpressioncontextgenerator.h" #include "qgscoordinatereferencesystem.h" @@ -44,12 +45,13 @@ class QDomNode; class QgsLayerTreeGroup; class QgsLayerTreeRegistryBridge; class QgsMapLayer; +class QgsMapThemeCollection; class QgsProjectBadLayerHandler; class QgsRelationManager; -class QgsVectorLayer; -class QgsMapThemeCollection; -class QgsTransactionGroup; class QgsTolerance; +class QgsTransactionGroup; +class QgsVectorLayer; + /** \ingroup core * Reads and writes project states. @@ -77,6 +79,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera Q_PROPERTY( QString homePath READ homePath NOTIFY homePathChanged ) Q_PROPERTY( QgsCoordinateReferenceSystem crs READ crs WRITE setCrs ) Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) + Q_PROPERTY( QgsSnappingConfig snappingConfig READ snappingConfig WRITE setSnappingConfig NOTIFY snappingConfigChanged ) public: @@ -333,14 +336,6 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ QgsLayerTreeGroup* createEmbeddedGroup( const QString& groupName, const QString& projectFilePath, const QStringList &invisibleLayers ); - /** Convenience function to set snap settings per layer */ - void setSnapSettingsForLayer( const QString& layerId, bool enabled, QgsSnapper::SnappingType type, QgsTolerance::UnitType unit, double tolerance, - bool avoidIntersection ); - - /** Convenience function to query snap settings of a layer */ - bool snapSettingsForLayer( const QString& layerId, bool& enabled, QgsSnapper::SnappingType& type, QgsTolerance::UnitType& units, double& tolerance, - bool& avoidIntersection ) const; - /** Convenience function to set topological editing */ void setTopologicalEditing( bool enabled ); @@ -460,33 +455,26 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera QgsExpressionContext createExpressionContext() const override; - protected: - /** Set error message from read/write operation - * @note not available in Python bindings + /** + * The snapping configuration for this project. + * + * @note Added in QGIS 3.0 */ - void setError( const QString& errorMessage ); + QgsSnappingConfig snappingConfig() const; - /** Clear error message - * @note not available in Python bindings + /** + * The snapping configuration for this project. + * + * @note Added in QGIS 3.0 */ - void clearError(); - - //! Creates layer and adds it to maplayer registry - //! @note not available in python bindings - bool addLayer( const QDomElement& layerElem, QList& brokenNodes, QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList ); - - //! @note not available in python bindings - void initializeEmbeddedSubtree( const QString& projectFilePath, QgsLayerTreeGroup* group ); - - //! @note not available in python bindings - void loadEmbeddedNodes( QgsLayerTreeGroup* group ); + void setSnappingConfig( const QgsSnappingConfig& snappingConfig ); signals: //! emitted when project is being read - void readProject( const QDomDocument & ); + void readProject( const QDomDocument& ); //! emitted when project is being written - void writeProject( QDomDocument & ); + void writeProject( QDomDocument& ); /** * Emitted, after the basic initialization of a layer from the project @@ -496,7 +484,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera * @param mapLayer The map layer which is being initialized * @param layerNode The layer node from the project file */ - void readMapLayer( QgsMapLayer *mapLayer, const QDomElement &layerNode ); + void readMapLayer( QgsMapLayer* mapLayer, const QDomElement& layerNode ); /** * Emitted, when a layer is being saved. You can use this method to save @@ -523,8 +511,6 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera void loadingLayer( const QString& ); - void snapSettingsChanged(); - //! Emitted when the list of layer which are excluded from map identification changes void nonIdentifiableLayersChanged( QStringList nonIdentifiableLayers ); @@ -534,6 +520,9 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera //! Emitted when the home path of the project changes void homePathChanged(); + //! emitted whenever the configuration for snapping has changed + void snappingConfigChanged(); + /** Emitted whenever the expression variables stored in the project have been changed. * @note added in QGIS 3.0 */ @@ -566,6 +555,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera private slots: void onMapLayersAdded( const QList& layers ); + void onMapLayersRemoved( const QList& layers ); void cleanTransactionGroups( bool force = false ); private: @@ -594,6 +584,26 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ void processLayerJoins( QgsVectorLayer* layer ); + /** Set error message from read/write operation + * @note not available in Python bindings + */ + void setError( const QString& errorMessage ); + + /** Clear error message + * @note not available in Python bindings + */ + void clearError(); + + //! Creates layer and adds it to maplayer registry + //! @note not available in python bindings + bool addLayer( const QDomElement& layerElem, QList& brokenNodes, QList< QPair< QgsVectorLayer*, QDomElement > >& vectorLayerList ); + + //! @note not available in python bindings + void initializeEmbeddedSubtree( const QString& projectFilePath, QgsLayerTreeGroup* group ); + + //! @note not available in python bindings + void loadEmbeddedNodes( QgsLayerTreeGroup* group ); + QString mErrorMessage; QgsProjectBadLayerHandler* mBadLayerHandler; @@ -604,8 +614,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ QHash< QString, QPair< QString, bool> > mEmbeddedLayers; - void snapSettings( QStringList& layerIdList, QStringList& enabledList, QStringList& snapTypeList, QStringList& snapUnitList, QStringList& toleranceUnitList, - QStringList& avoidIntersectionList ) const; + QgsSnappingConfig mSnappingConfig; QgsRelationManager* mRelationManager; diff --git a/src/core/qgssnappingconfig.cpp b/src/core/qgssnappingconfig.cpp new file mode 100644 index 000000000000..04bd356c83d2 --- /dev/null +++ b/src/core/qgssnappingconfig.cpp @@ -0,0 +1,509 @@ +/*************************************************************************** + qgsprojectsnappingsettings.cpp - QgsProjectSnappingSettings + + --------------------- + begin : 29.8.2016 + copyright : (C) 2016 by Denis Rouzaud + email : denis.rouzaud@gmail.com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgssnappingconfig.h" + +#include +#include +#include + +#include "qgslogger.h" +#include "qgsmaplayerregistry.h" +#include "qgsvectorlayer.h" +#include "qgsproject.h" + +QgsSnappingConfig::IndividualLayerSettings::IndividualLayerSettings() + : mValid( false ) + , mEnabled( false ) + , mType( Vertex ) + , mTolerance( 0 ) + , mUnits( QgsTolerance::Pixels ) + , mAvoidIntersection( false ) +{} + + +QgsSnappingConfig::IndividualLayerSettings::IndividualLayerSettings( bool enabled, SnappingType type, double tolerance, QgsTolerance::UnitType units, bool avoidIntersection ) + : mValid( true ) + , mEnabled( enabled ) + , mType( type ) + , mTolerance( tolerance ) + , mUnits( units ) + , mAvoidIntersection( avoidIntersection ) +{} + +bool QgsSnappingConfig::IndividualLayerSettings::valid() const +{ + return mValid; +} + +bool QgsSnappingConfig::IndividualLayerSettings::enabled() const +{ + return mEnabled; +} + +void QgsSnappingConfig::IndividualLayerSettings::setEnabled( bool enabled ) +{ + mEnabled = enabled; +} + +QgsSnappingConfig::SnappingType QgsSnappingConfig::IndividualLayerSettings::type() const +{ + return mType; +} + +void QgsSnappingConfig::IndividualLayerSettings::setType( SnappingType type ) +{ + mType = type; +} + +double QgsSnappingConfig::IndividualLayerSettings::tolerance() const +{ + return mTolerance; +} + +void QgsSnappingConfig::IndividualLayerSettings::setTolerance( double tolerance ) +{ + mTolerance = tolerance; +} + +QgsTolerance::UnitType QgsSnappingConfig::IndividualLayerSettings::units() const +{ + return mUnits; +} + +void QgsSnappingConfig::IndividualLayerSettings::setUnits( QgsTolerance::UnitType units ) +{ + mUnits = units; +} + +bool QgsSnappingConfig::IndividualLayerSettings::avoidIntersection() const +{ + return mAvoidIntersection; +} + +void QgsSnappingConfig::IndividualLayerSettings::setAvoidIntersection( bool avoidIntersection ) +{ + mAvoidIntersection = avoidIntersection; +} + +bool QgsSnappingConfig::IndividualLayerSettings::operator !=( const QgsSnappingConfig::IndividualLayerSettings& other ) const +{ + return mValid != other.mValid + || mEnabled != other.mEnabled + || mType != other.mType + || mTolerance != other.mTolerance + || mUnits != other.mUnits + || mAvoidIntersection != other.mAvoidIntersection; +} + +bool QgsSnappingConfig::IndividualLayerSettings::operator ==( const QgsSnappingConfig::IndividualLayerSettings& other ) const +{ + return mValid == other.mValid + && mEnabled == other.mEnabled + && mType == other.mType + && mTolerance == other.mTolerance + && mUnits == other.mUnits + && mAvoidIntersection == other.mAvoidIntersection; +} + + +QgsSnappingConfig::QgsSnappingConfig() +{ + reset(); +} + +QgsSnappingConfig::~QgsSnappingConfig() +{ +} + +bool QgsSnappingConfig::operator==( const QgsSnappingConfig& other ) const +{ + return mEnabled == other.mEnabled + && mMode == other.mMode + && mType == other.mType + && mTolerance == other.mTolerance + && mUnits == other.mUnits + && mTopologicalEditing == other.mTopologicalEditing + && mIntersectionSnapping == other.mIntersectionSnapping + && mIndividualLayerSettings == other.mIndividualLayerSettings; +} + +void QgsSnappingConfig::reset() +{ + // get defaults values. They are both used for standard and advanced configuration (per layer) + bool enabled = QSettings().value( "/qgis/digitizing/default_advanced_snap_enabled", true ).toBool(); + SnappingMode mode = ( SnappingMode )QSettings().value( "/qgis/digitizing/default_snap_mode", ( int )AllLayers ).toInt(); + if ( mMode == 0 ) + { + // backward compatibility with QGIS 2.x + // could be removed in 3.4+ + mMode = AllLayers; + } + SnappingType type = ( SnappingType )QSettings().value( "/qgis/digitizing/default_snap_type", ( int )Vertex ).toInt(); + double tolerance = QSettings().value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( "/qgis/digitizing/default_snapping_tolerance_unit", ( int )QgsTolerance::ProjectUnits ).toInt(); + + // assign main (standard) config + mEnabled = enabled; + mMode = mode; + mType = type; + mTolerance = tolerance; + // do not allow unit to be "layer" if not in advanced configuration + if ( mMode != AdvancedConfiguration ) + { + mUnits = QgsTolerance::ProjectUnits; + } + else + { + mUnits = units; + } + mTopologicalEditing = false; + mIntersectionSnapping = false; + + // set advanced config + mIndividualLayerSettings = QHash(); + Q_FOREACH ( QgsMapLayer *ml, QgsMapLayerRegistry::instance()->mapLayers() ) + { + QgsVectorLayer* vl = dynamic_cast( ml ); + if ( vl ) + { + mIndividualLayerSettings.insert( vl, IndividualLayerSettings( enabled, type, tolerance, units ) ); + } + } +} + +bool QgsSnappingConfig::enabled() const +{ + return mEnabled; +} + +void QgsSnappingConfig::setEnabled( bool enabled ) +{ + if ( mEnabled == enabled ) + { + return; + } + mEnabled = enabled; +} + +QgsSnappingConfig::SnappingMode QgsSnappingConfig::mode() const +{ + return mMode; +} + +void QgsSnappingConfig::setMode( QgsSnappingConfig::SnappingMode mode ) +{ + if ( mMode == mode ) + { + return; + } + mMode = mode; +} + +QgsSnappingConfig::SnappingType QgsSnappingConfig::type() const +{ + return mType; +} + +void QgsSnappingConfig::setType( QgsSnappingConfig::SnappingType type ) +{ + if ( mType == type ) + { + return; + } + mType = type; +} + +double QgsSnappingConfig::tolerance() const +{ + return mTolerance; +} + +void QgsSnappingConfig::setTolerance( double tolerance ) +{ + if ( mTolerance == tolerance ) + { + return; + } + mTolerance = tolerance; +} + +QgsTolerance::UnitType QgsSnappingConfig::units() const +{ + return mUnits; +} + +void QgsSnappingConfig::setUnits( QgsTolerance::UnitType units ) +{ + if ( mUnits == units ) + { + return; + } + mUnits = units; +} + +bool QgsSnappingConfig::topologicalEditing() const +{ + return mTopologicalEditing; +} + +void QgsSnappingConfig::setTopologicalEditing( bool enabled ) +{ + mTopologicalEditing = enabled; +} + +bool QgsSnappingConfig::intersectionSnapping() const +{ + return mIntersectionSnapping; +} + +void QgsSnappingConfig::setIntersectionSnapping( bool enabled ) +{ + mIntersectionSnapping = enabled; +} + +QHash QgsSnappingConfig::individualLayerSettings() const +{ + return mIndividualLayerSettings; +} + +QgsSnappingConfig::IndividualLayerSettings QgsSnappingConfig::individualLayerSettings( QgsVectorLayer* vl ) const +{ + if ( vl && mIndividualLayerSettings.contains( vl ) ) + { + return mIndividualLayerSettings.value( vl ); + } + else + { + // return invalid settings + return IndividualLayerSettings(); + } +} + +void QgsSnappingConfig::setIndividualLayerSettings( QgsVectorLayer* vl, IndividualLayerSettings individualLayerSettings ) +{ + if ( !vl || mIndividualLayerSettings.value( vl ) == individualLayerSettings ) + { + return; + } + mIndividualLayerSettings.insert( vl, individualLayerSettings ); +} + +bool QgsSnappingConfig::operator!=( const QgsSnappingConfig& other ) const +{ + return mEnabled != other.mEnabled + || mMode != other.mMode + || mType != other.mType + || mTolerance != other.mTolerance + || mUnits != other.mUnits + || mIndividualLayerSettings != other.mIndividualLayerSettings; +} + +void QgsSnappingConfig::readProject( const QDomDocument& doc ) +{ + QDomElement snapSettingsElem = doc.firstChildElement( "qgis" ).firstChildElement( "snapping-settings" ); + if ( snapSettingsElem.isNull() ) + { + readLegacySettings(); + return; + } + + if ( snapSettingsElem.hasAttribute( "enabled" ) ) + mEnabled = snapSettingsElem.attribute( "enabled" ) == "1"; + + if ( snapSettingsElem.hasAttribute( "mode" ) ) + mMode = ( SnappingMode )snapSettingsElem.attribute( "mode" ).toInt(); + + if ( snapSettingsElem.hasAttribute( "type" ) ) + mType = ( SnappingType )snapSettingsElem.attribute( "type" ).toInt(); + + if ( snapSettingsElem.hasAttribute( "tolerance" ) ) + mTolerance = snapSettingsElem.attribute( "tolerance" ).toDouble(); + + if ( snapSettingsElem.hasAttribute( "unit" ) ) + mUnits = ( QgsTolerance::UnitType )snapSettingsElem.attribute( "unit" ).toInt(); + + if ( snapSettingsElem.hasAttribute( "topological-editing" ) ) + mTopologicalEditing = snapSettingsElem.attribute( "topological-editing" ) == "1"; + + if ( snapSettingsElem.hasAttribute( "intersection-snapping" ) ) + mIntersectionSnapping = snapSettingsElem.attribute( "intersection-snapping" ) == "1"; + + // do not clear the settings as they must be automatically synchronized with current layers + QDomNodeList nodes = snapSettingsElem.elementsByTagName( "individual-layer-settings" ); + if ( nodes.count() ) + { + QDomNode node = nodes.item( 0 ); + QDomNodeList settingNodes = node.childNodes(); + int layerCount = settingNodes.count(); + for ( int i = 0; i < layerCount; ++i ) + { + QDomElement settingElement = settingNodes.at( i ).toElement(); + if ( settingElement.tagName() != "layer-setting" ) + { + QgsLogger::warning( QApplication::translate( "QgsProjectSnappingSettings", "Cannot read individual settings. Unexpected tag '%1'" ).arg( settingElement.tagName() ) ); + continue; + } + + QString layerId = settingElement.attribute( "id" ); + bool enabled = settingElement.attribute( "enabled" ) == "1"; + SnappingType type = ( SnappingType )settingElement.attribute( "type" ).toInt(); + double tolerance = settingElement.attribute( "tolerance" ).toDouble(); + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )settingElement.attribute( "units" ).toInt(); + bool avoidIntersection = settingElement.attribute( "avoid-intersection" ) == "1"; + + QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( layerId ); + if ( !ml || ml->type() != QgsMapLayer::VectorLayer ) + continue; + + QgsVectorLayer* vl = qobject_cast( ml ); + + IndividualLayerSettings setting = IndividualLayerSettings( enabled, type, tolerance, units, avoidIntersection ); + mIndividualLayerSettings.insert( vl, setting ); + } + } +} + +void QgsSnappingConfig::writeProject( QDomDocument& doc ) +{ + QDomElement snapSettingsElem = doc.createElement( "snapping-settings" ); + snapSettingsElem.setAttribute( "enabled", QString::number( mEnabled ) ); + snapSettingsElem.setAttribute( "mode", ( int )mMode ); + snapSettingsElem.setAttribute( "type", ( int )mType ); + snapSettingsElem.setAttribute( "tolerance", mTolerance ); + snapSettingsElem.setAttribute( "unit", ( int )mUnits ); + snapSettingsElem.setAttribute( "topological-editing", QString::number( mTopologicalEditing ) ); + snapSettingsElem.setAttribute( "intersection-snapping", QString::number( mIntersectionSnapping ) ); + + QDomElement ilsElement = doc.createElement( "individual-layer-settings" ); + Q_FOREACH ( QgsVectorLayer* vl, mIndividualLayerSettings.keys() ) + { + IndividualLayerSettings setting = mIndividualLayerSettings.value( vl ); + + QDomElement layerElement = doc.createElement( "layer-setting" ); + layerElement.setAttribute( "id", vl->id() ); + layerElement.setAttribute( "enabled", QString::number( setting.enabled() ) ); + layerElement.setAttribute( "type", ( int )setting.type() ); + layerElement.setAttribute( "tolerance", setting.tolerance() ); + layerElement.setAttribute( "units", ( int )setting.units() ); + layerElement.setAttribute( "avoid-intersection", QString::number( setting.avoidIntersection() ) ); + ilsElement.appendChild( layerElement ); + } + snapSettingsElem.appendChild( ilsElement ); + + doc.firstChildElement( "qgis" ).appendChild( snapSettingsElem ); +} + +bool QgsSnappingConfig::addLayers( const QList& layers ) +{ + bool changed = false; + bool enabled = QSettings().value( "/qgis/digitizing/default_advanced_snap_enabled", true ).toBool(); + SnappingType type = ( SnappingType )QSettings().value( "/qgis/digitizing/default_snap_type", Vertex ).toInt(); + double tolerance = QSettings().value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( "/qgis/digitizing/default_snapping_tolerance_unit", QgsTolerance::ProjectUnits ).toInt(); + + Q_FOREACH ( QgsMapLayer* ml, layers ) + { + QgsVectorLayer* vl = qobject_cast( ml ); + if ( vl ) + { + mIndividualLayerSettings.insert( vl, IndividualLayerSettings( enabled, type, tolerance, units ) ); + changed = true; + } + } + return changed; +} + +bool QgsSnappingConfig::removeLayers( const QList& layers ) +{ + bool changed = false; + Q_FOREACH ( QgsMapLayer* ml, layers ) + { + QgsVectorLayer* vl = qobject_cast( ml ); + if ( vl ) + { + mIndividualLayerSettings.remove( vl ); + changed = true; + } + } + return changed; +} + +void QgsSnappingConfig::readLegacySettings() +{ + mMode = ActiveLayer; + mIndividualLayerSettings.clear(); + + QString snapMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode" ); + + QString snapType = QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType", QString( "off" ) ); + if ( snapType == "to segment" ) + mType = Segment; + else if ( snapType == "to vertex and segment" ) + mType = VertexAndSegment; + else if ( snapType == "to vertex" ) + mType = Vertex; + mTolerance = QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance", 0 ); + mUnits = static_cast< QgsTolerance::UnitType >( QgsProject::instance()->readNumEntry( "Digitizing", "/DefaultSnapToleranceUnit", QgsTolerance::ProjectUnits ) ); + + mIntersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); + + //read snapping settings from project + bool snappingDefinedInProject, ok; + QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &snappingDefinedInProject ); + QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); + QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); + QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); + QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); + + // lists must have the same size, otherwise something is wrong + if ( layerIdList.size() != enabledList.size() || + layerIdList.size() != toleranceList.size() || + layerIdList.size() != toleranceUnitList.size() || + layerIdList.size() != snapToList.size() ) + return; + + if ( !snappingDefinedInProject ) + return; // nothing defined in project - use current layer + + // Use snapping information from the project + if ( snapMode == "current_layer" ) + mMode = ActiveLayer; + else if ( snapMode == "all_layers" ) + mMode = AllLayers; + else // either "advanced" or empty (for background compatibility) + mMode = AdvancedConfiguration; + + // load layers, tolerances, snap type + QStringList::const_iterator layerIt( layerIdList.constBegin() ); + QStringList::const_iterator tolIt( toleranceList.constBegin() ); + QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() ); + QStringList::const_iterator snapIt( snapToList.constBegin() ); + QStringList::const_iterator enabledIt( enabledList.constBegin() ); + for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt ) + { + QgsVectorLayer* vlayer = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) ); + if ( !vlayer || !vlayer->hasGeometryType() ) + continue; + + SnappingType t( *snapIt == "to_vertex" ? Vertex : + ( *snapIt == "to_segment" ? Segment : + VertexAndSegment + ) + ); + + mIndividualLayerSettings.insert( vlayer, IndividualLayerSettings( *enabledIt == "enabled", t, tolIt->toDouble(), static_cast( tolUnitIt->toInt() ) ) ); + } +} diff --git a/src/core/qgssnappingconfig.h b/src/core/qgssnappingconfig.h new file mode 100644 index 000000000000..2a3c6e9d491a --- /dev/null +++ b/src/core/qgssnappingconfig.h @@ -0,0 +1,245 @@ +/*************************************************************************** + qgssnappingconfig.h - QgsSnappingConfig + + --------------------- + begin : 29.8.2016 + copyright : (C) 2016 by Denis Rouzaud + email : denis.rouzaud@gmail.com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSPROJECTSNAPPINGSETTINGS_H +#define QGSPROJECTSNAPPINGSETTINGS_H + +#include "qgstolerance.h" + +class QDomDocument; +class QgsVectorLayer; + + +/** \ingroup core + * This is a container for configuration of the snapping of the project + * @note added in 3.0 + */ +class CORE_EXPORT QgsSnappingConfig +{ + public: + /** + * SnappingMode defines on which layer the snapping is performed + */ + enum SnappingMode + { + ActiveLayer = 1, /*!< on the active layer */ + AllLayers = 2, /*!< on all vector layers */ + AdvancedConfiguration = 3, /*!< on a per layer configuration basis */ + }; + + /** + * SnappingType defines on what object the snapping is performed + */ + enum SnappingType + { + Vertex = 1, /*!< on vertices only */ + VertexAndSegment = 2, /*!< both on vertices and segments */ + Segment = 3, /*!< on segments only */ + }; + + /** \ingroup core + * This is a container of advanced configuration (per layer) of the snapping of the project + * @note added in 3.0 + */ + class CORE_EXPORT IndividualLayerSettings + { + public: + /** + * @brief IndividualLayerSettings + * @param enabled + * @param type + * @param tolerance + * @param units + * @param avoidIntersection + */ + IndividualLayerSettings( bool enabled, QgsSnappingConfig::SnappingType type, double tolerance, QgsTolerance::UnitType units, bool avoidIntersection = false ); + + /** + * Constructs an invalid setting + */ + IndividualLayerSettings(); + + //! return if settings are valid + bool valid() const; + + //! return if snaping is enbaled + bool enabled() const; + + //! enables the snapping + void setEnabled( bool enabled ); + + //! return the type (vertices and/or segments) + QgsSnappingConfig::SnappingType type() const; + + //! define the type of snapping + void setType( QgsSnappingConfig::SnappingType type ); + + //! return the tolerance + double tolerance() const; + + //! set the tolerance + void setTolerance( double tolerance ); + + //! return the type of units + QgsTolerance::UnitType units() const; + + //! set the type of units + void setUnits( QgsTolerance::UnitType units ); + + //! return if it shall avoid intersection (polygon layers only) + bool avoidIntersection() const; + + //! set if it shall avoid intersection (polygon layers only) + void setAvoidIntersection( bool avoidIntersection ); + + /** + * Compare this configuration to other. + */ + bool operator!= ( const IndividualLayerSettings& other ) const; + + bool operator== ( const IndividualLayerSettings& other ) const; + + private: + bool mValid; + bool mEnabled; + SnappingType mType; + double mTolerance; + QgsTolerance::UnitType mUnits; + bool mAvoidIntersection; + }; + + /** + * Constructor with default parameters defined in global settings + */ + explicit QgsSnappingConfig(); + + ~QgsSnappingConfig(); + + bool operator==( const QgsSnappingConfig& other ) const; + + //! reset to default values + void reset(); + + //! return if snapping is enbaled + bool enabled() const; + + //! enables the snapping + void setEnabled( bool enabled ); + + //! return the mode (all layers, active layer, per layer settings) + SnappingMode mode() const; + + //! define the mode of snapping + void setMode( SnappingMode mode ); + + //! return the type (vertices and/or segments) + SnappingType type() const; + + //! define the type of snapping + void setType( SnappingType type ); + + //! return the tolerance + double tolerance() const; + + //! set the tolerance + void setTolerance( double tolerance ); + + //! return the type of units + QgsTolerance::UnitType units() const; + + //! set the type of units + void setUnits( QgsTolerance::UnitType units ); + + //! return if the topological editing is enabled + bool topologicalEditing() const; + + //! set if the topological editing is enabled + void setTopologicalEditing( bool enabled ); + + //! return if the snapping on intersection is enabled + bool intersectionSnapping() const; + + //! set if the snapping on intersection is enabled + void setIntersectionSnapping( bool enabled ); + + //! return individual snapping settings for all layers + QHash individualLayerSettings() const; + + //! return individual layer snappings settings (applied if mode is AdvancedConfiguration) + QgsSnappingConfig::IndividualLayerSettings individualLayerSettings( QgsVectorLayer* vl ) const; + + //! set individual layer snappings settings (applied if mode is AdvancedConfiguration) + void setIndividualLayerSettings( QgsVectorLayer* vl, QgsSnappingConfig::IndividualLayerSettings individualLayerSettings ); + + /** + * Compare this configuration to other. + */ + bool operator!= ( const QgsSnappingConfig& other ) const; + + public: + /** + * Reads the configuration from the specified QGIS project document. + * + * @note Added in QGIS 3.0 + */ + void readProject( const QDomDocument& doc ); + + /** + * Writes the configuration to the specified QGIS project document. + * + * @note Added in QGIS 3.0 + */ + void writeProject( QDomDocument& doc ); + + /** + * Adds the specified layers as individual layers to the configuration + * with standard configuration. + * When implementing a long-living QgsSnappingConfig (like the one in QgsProject) + * it is best to directly feed this with information from the layer registry. + * + * @return True if changes have been done. + * + * @note Added in QGIS 3.0 + */ + bool addLayers( const QList& layers ); + + + /** + * Removes the specified layers from the individual layer configuration. + * When implementing a long-living QgsSnappingConfig (like the one in QgsProject) + * it is best to directly feed this with information from the layer registry. + * + * @return True if changes have been done. + * + * @note Added in QGIS 3.0 + */ + bool removeLayers( const QList& layers ); + + private: + void readLegacySettings(); + + bool mEnabled; + SnappingMode mMode; + SnappingType mType; + double mTolerance; + QgsTolerance::UnitType mUnits; + bool mTopologicalEditing; + bool mIntersectionSnapping; + + QHash mIndividualLayerSettings; + +}; + +#endif // QGSPROJECTSNAPPINGSETTINGS_H diff --git a/src/core/qgssnappingutils.cpp b/src/core/qgssnappingutils.cpp index 1f205ecca377..f478404fe34b 100644 --- a/src/core/qgssnappingutils.cpp +++ b/src/core/qgssnappingutils.cpp @@ -24,16 +24,10 @@ QgsSnappingUtils::QgsSnappingUtils( QObject* parent ) : QObject( parent ) , mCurrentLayer( nullptr ) - , mSnapToMapMode( SnapCurrentLayer ) , mStrategy( IndexHybrid ) - , mDefaultType( QgsPointLocator::Vertex ) - , mDefaultTolerance( 10 ) - , mDefaultUnit( QgsTolerance::Pixels ) - , mSnapOnIntersection( false ) , mHybridPerLayerFeatureLimit( 50000 ) , mIsIndexing( false ) { - connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( onLayersWillBeRemoved( QStringList ) ) ); } QgsSnappingUtils::~QgsSnappingUtils() @@ -57,12 +51,10 @@ QgsPointLocator* QgsSnappingUtils::locatorForLayer( QgsVectorLayer* vl ) void QgsSnappingUtils::clearAllLocators() { - Q_FOREACH ( QgsPointLocator* vlpl, mLocators ) - delete vlpl; + qDeleteAll( mLocators ); mLocators.clear(); - Q_FOREACH ( QgsPointLocator* vlpl, mTemporaryLocators ) - delete vlpl; + qDeleteAll( mTemporaryLocators ); mTemporaryLocators.clear(); } @@ -214,17 +206,17 @@ inline QgsRectangle _areaOfInterest( const QgsPoint& point, double tolerance ) QgsPointLocator::Match QgsSnappingUtils::snapToMap( const QgsPoint& pointMap, QgsPointLocator::MatchFilter* filter ) { - if ( !mMapSettings.hasValidSettings() ) + if ( !mMapSettings.hasValidSettings() || !mSnappingConfig.enabled() ) return QgsPointLocator::Match(); - if ( mSnapToMapMode == SnapCurrentLayer ) + if ( mSnappingConfig.mode() == QgsSnappingConfig::ActiveLayer ) { - if ( !mCurrentLayer || mDefaultType == 0 ) + if ( !mCurrentLayer || mSnappingConfig.type() == 0 ) return QgsPointLocator::Match(); // data from project - double tolerance = QgsTolerance::toleranceInProjectUnits( mDefaultTolerance, mCurrentLayer, mMapSettings, mDefaultUnit ); - int type = mDefaultType; + double tolerance = QgsTolerance::toleranceInProjectUnits( mSnappingConfig.tolerance(), mCurrentLayer, mMapSettings, mSnappingConfig.units() ); + int type = mSnappingConfig.type(); prepareIndex( QList() << qMakePair( mCurrentLayer, _areaOfInterest( pointMap, tolerance ) ) ); @@ -236,7 +228,7 @@ QgsPointLocator::Match QgsSnappingUtils::snapToMap( const QgsPoint& pointMap, Qg QgsPointLocator::Match bestMatch; _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter ); - if ( mSnapOnIntersection ) + if ( mSnappingConfig.intersectionSnapping() ) { QgsPointLocator* locEdges = locatorForLayerUsingStrategy( mCurrentLayer, pointMap, tolerance ); QgsPointLocator::MatchList edges = locEdges->edgesInRect( pointMap, tolerance ); @@ -245,7 +237,7 @@ QgsPointLocator::Match QgsSnappingUtils::snapToMap( const QgsPoint& pointMap, Qg return bestMatch; } - else if ( mSnapToMapMode == SnapAdvanced ) + else if ( mSnappingConfig.mode() == QgsSnappingConfig::AdvancedConfiguration ) { QList layers; Q_FOREACH ( const LayerConfig& layerConfig, mLayers ) @@ -266,7 +258,7 @@ QgsPointLocator::Match QgsSnappingUtils::snapToMap( const QgsPoint& pointMap, Qg { _updateBestMatch( bestMatch, pointMap, loc, layerConfig.type, tolerance, filter ); - if ( mSnapOnIntersection ) + if ( mSnappingConfig.intersectionSnapping() ) { edges << loc->edgesInRect( pointMap, tolerance ); maxSnapIntTolerance = qMax( maxSnapIntTolerance, tolerance ); @@ -274,16 +266,16 @@ QgsPointLocator::Match QgsSnappingUtils::snapToMap( const QgsPoint& pointMap, Qg } } - if ( mSnapOnIntersection ) + if ( mSnappingConfig.intersectionSnapping() ) _replaceIfBetter( bestMatch, _findClosestSegmentIntersection( pointMap, edges ), maxSnapIntTolerance ); return bestMatch; } - else if ( mSnapToMapMode == SnapAllLayers ) + else if ( mSnappingConfig.mode() == QgsSnappingConfig::AllLayers ) { // data from project - double tolerance = QgsTolerance::toleranceInProjectUnits( mDefaultTolerance, nullptr, mMapSettings, mDefaultUnit ); - int type = mDefaultType; + double tolerance = QgsTolerance::toleranceInProjectUnits( mSnappingConfig.tolerance(), nullptr, mMapSettings, mSnappingConfig.units() ); + int type = mSnappingConfig.type(); QgsRectangle aoi = _areaOfInterest( pointMap, tolerance ); QList layers; @@ -302,12 +294,12 @@ QgsPointLocator::Match QgsSnappingUtils::snapToMap( const QgsPoint& pointMap, Qg { _updateBestMatch( bestMatch, pointMap, loc, type, tolerance, filter ); - if ( mSnapOnIntersection ) + if ( mSnappingConfig.intersectionSnapping() ) edges << loc->edgesInRect( pointMap, tolerance ); } } - if ( mSnapOnIntersection ) + if ( mSnappingConfig.intersectionSnapping() ) _replaceIfBetter( bestMatch, _findClosestSegmentIntersection( pointMap, edges ), tolerance ); return bestMatch; @@ -404,6 +396,22 @@ void QgsSnappingUtils::prepareIndex( const QList& layers mIsIndexing = false; } +QgsSnappingConfig QgsSnappingUtils::config() const +{ + return mSnappingConfig; +} + +void QgsSnappingUtils::setConfig( const QgsSnappingConfig& config ) +{ + if ( mSnappingConfig == config ) + return; + + if ( mSnappingConfig.individualLayerSettings() != config.individualLayerSettings() ) + onIndividualLayerSettingsChanged( config.individualLayerSettings() ); + + mSnappingConfig = config; + emit configChanged(); +} QgsPointLocator::Match QgsSnappingUtils::snapToCurrentLayer( QPoint point, int type, QgsPointLocator::MatchFilter* filter ) { @@ -437,58 +445,6 @@ void QgsSnappingUtils::setCurrentLayer( QgsVectorLayer* layer ) mCurrentLayer = layer; } -void QgsSnappingUtils::setSnapToMapMode( QgsSnappingUtils::SnapToMapMode mode ) -{ - if ( mSnapToMapMode == mode ) - return; - - mSnapToMapMode = mode; - emit configChanged(); -} - -void QgsSnappingUtils::setDefaultSettings( int type, double tolerance, QgsTolerance::UnitType unit ) -{ - // force map units - can't use layer units for just any layer - if ( unit == QgsTolerance::LayerUnits ) - unit = QgsTolerance::ProjectUnits; - - if ( mDefaultType == type && mDefaultTolerance == tolerance && mDefaultUnit == unit ) - return; - - mDefaultType = type; - mDefaultTolerance = tolerance; - mDefaultUnit = unit; - - if ( mSnapToMapMode != SnapAdvanced ) // does not affect advanced mode - emit configChanged(); -} - -void QgsSnappingUtils::defaultSettings( int& type, double& tolerance, QgsTolerance::UnitType& unit ) -{ - type = mDefaultType; - tolerance = mDefaultTolerance; - unit = mDefaultUnit; -} - -void QgsSnappingUtils::setLayers( const QList& layers ) -{ - if ( mLayers == layers ) - return; - - mLayers = layers; - if ( mSnapToMapMode == SnapAdvanced ) // only affects advanced mode - emit configChanged(); -} - -void QgsSnappingUtils::setSnapOnIntersections( bool enabled ) -{ - if ( mSnapOnIntersection == enabled ) - return; - - mSnapOnIntersection = enabled; - emit configChanged(); -} - QString QgsSnappingUtils::dump() { QString msg = "--- SNAPPING UTILS DUMP ---\n"; @@ -501,25 +457,25 @@ QString QgsSnappingUtils::dump() QList layers; - if ( mSnapToMapMode == SnapCurrentLayer ) + if ( mSnappingConfig.mode() == QgsSnappingConfig::ActiveLayer ) { - if ( mSnapToMapMode == SnapCurrentLayer && !mCurrentLayer ) + if ( mSnappingConfig.mode() == QgsSnappingConfig::ActiveLayer && !mCurrentLayer ) { msg += "no current layer!"; return msg; } - layers << LayerConfig( mCurrentLayer, QgsPointLocator::Types( mDefaultType ), mDefaultTolerance, mDefaultUnit ); + layers << LayerConfig( mCurrentLayer, QgsPointLocator::Types( mSnappingConfig.type() ), mSnappingConfig.tolerance(), mSnappingConfig.units() ); } - else if ( mSnapToMapMode == SnapAllLayers ) + else if ( mSnappingConfig.mode() == QgsSnappingConfig::AllLayers ) { Q_FOREACH ( const QString& layerID, mMapSettings.layers() ) { if ( QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerID ) ) ) - layers << LayerConfig( vl, QgsPointLocator::Types( mDefaultType ), mDefaultTolerance, mDefaultUnit ); + layers << LayerConfig( vl, QgsPointLocator::Types( mSnappingConfig.type() ), mSnappingConfig.tolerance(), mSnappingConfig.units() ); } } - else if ( mSnapToMapMode == SnapAdvanced ) + else if ( mSnappingConfig.mode() == QgsSnappingConfig::AdvancedConfiguration ) { layers = mLayers; } @@ -575,117 +531,23 @@ QgsCoordinateReferenceSystem QgsSnappingUtils::destinationCrs() const return mMapSettings.hasCrsTransformEnabled() ? mMapSettings.destinationCrs() : QgsCoordinateReferenceSystem(); } - -void QgsSnappingUtils::readConfigFromProject() +void QgsSnappingUtils::onIndividualLayerSettingsChanged( const QHash layerSettings ) { - mSnapToMapMode = SnapCurrentLayer; mLayers.clear(); - QString snapMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode" ); - - int type = 0; - QString snapType = QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType", QString( "off" ) ); - if ( snapType == "to segment" ) - type = QgsPointLocator::Edge; - else if ( snapType == "to vertex and segment" ) - type = QgsPointLocator::Vertex | QgsPointLocator::Edge; - else if ( snapType == "to vertex" ) - type = QgsPointLocator::Vertex; - double tolerance = QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance", 0 ); - QgsTolerance::UnitType unit = static_cast< QgsTolerance::UnitType >( QgsProject::instance()->readNumEntry( "Digitizing", "/DefaultSnapToleranceUnit", QgsTolerance::ProjectUnits ) ); - setDefaultSettings( type, tolerance, unit ); - - //snapping on intersection on? - setSnapOnIntersections( QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ) ); - - //read snapping settings from project - bool snappingDefinedInProject, ok; - QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &snappingDefinedInProject ); - QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); - QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); - QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); - QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); - - // lists must have the same size, otherwise something is wrong - if ( layerIdList.size() != enabledList.size() || - layerIdList.size() != toleranceList.size() || - layerIdList.size() != toleranceUnitList.size() || - layerIdList.size() != snapToList.size() ) - return; - - if ( !snappingDefinedInProject ) - return; // nothing defined in project - use current layer - - // Use snapping information from the project - if ( snapMode == "current_layer" ) - mSnapToMapMode = SnapCurrentLayer; - else if ( snapMode == "all_layers" ) - mSnapToMapMode = SnapAllLayers; - else // either "advanced" or empty (for background compatibility) - mSnapToMapMode = SnapAdvanced; - - - - // load layers, tolerances, snap type - QStringList::const_iterator layerIt( layerIdList.constBegin() ); - QStringList::const_iterator tolIt( toleranceList.constBegin() ); - QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() ); - QStringList::const_iterator snapIt( snapToList.constBegin() ); - QStringList::const_iterator enabledIt( enabledList.constBegin() ); - for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt ) - { - // skip layer if snapping is not enabled - if ( *enabledIt != "enabled" ) - continue; - - QgsVectorLayer *vlayer = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) ); - if ( !vlayer || !vlayer->hasGeometryType() ) - continue; - - QgsPointLocator::Types t( *snapIt == "to_vertex" ? QgsPointLocator::Vertex : - ( *snapIt == "to_segment" ? QgsPointLocator::Edge : - QgsPointLocator::Vertex | QgsPointLocator::Edge - ) - ); - mLayers.append( LayerConfig( vlayer, t, tolIt->toDouble(), static_cast< QgsTolerance::UnitType >( tolUnitIt->toInt() ) ) ); - } - - emit configChanged(); -} + QHash::const_iterator i; -void QgsSnappingUtils::onLayersWillBeRemoved( const QStringList& layerIds ) -{ - // remove locators for layers that are going to be deleted - Q_FOREACH ( const QString& layerId, layerIds ) + for ( i = layerSettings.constBegin(); i != layerSettings.constEnd(); ++i ) { - if ( mHybridMaxAreaPerLayer.contains( layerId ) ) - mHybridMaxAreaPerLayer.remove( layerId ); - - for ( LocatorsMap::iterator it = mLocators.begin(); it != mLocators.end(); ) + if ( i->enabled() ) { - if ( it.key()->id() == layerId ) - { - delete it.value(); - it = mLocators.erase( it ); - } - else - { - ++it; - } - } + QgsPointLocator::Types t( i->type() == QgsSnappingConfig::Vertex ? QgsPointLocator::Vertex : + ( i->type() == QgsSnappingConfig::Segment ? QgsPointLocator::Edge : + QgsPointLocator::Vertex | QgsPointLocator::Edge + ) + ); - for ( LocatorsMap::iterator it = mTemporaryLocators.begin(); it != mTemporaryLocators.end(); ) - { - if ( it.key()->id() == layerId ) - { - delete it.value(); - it = mTemporaryLocators.erase( it ); - } - else - { - ++it; - } + mLayers.append( LayerConfig( i.key(), t, i->tolerance(), i->units() ) ); } } } - diff --git a/src/core/qgssnappingutils.h b/src/core/qgssnappingutils.h index 82f74523c284..c968d7e965e7 100644 --- a/src/core/qgssnappingutils.h +++ b/src/core/qgssnappingutils.h @@ -20,6 +20,9 @@ #include "qgsmapsettings.h" #include "qgstolerance.h" #include "qgspointlocator.h" +#include "qgssnappingconfig.h" + +class QgsSnappingConfig; /** \ingroup core * This class has all the configuration of snapping and can return answers to snapping queries. @@ -41,6 +44,9 @@ class CORE_EXPORT QgsSnappingUtils : public QObject { Q_OBJECT + + Q_PROPERTY( QgsSnappingConfig config READ config WRITE setConfig NOTIFY configChanged ) + public: QgsSnappingUtils( QObject* parent = nullptr ); ~QgsSnappingUtils(); @@ -61,7 +67,7 @@ class CORE_EXPORT QgsSnappingUtils : public QObject /** Assign current map settings to the utils - used for conversion between screen coords to map coords */ void setMapSettings( const QgsMapSettings& settings ); - const QgsMapSettings& mapSettings() const { return mMapSettings; } + QgsMapSettings mapSettings() const { return mMapSettings; } /** Set current layer so that if mode is SnapCurrentLayer we know which layer to use */ void setCurrentLayer( QgsVectorLayer* layer ); @@ -79,11 +85,6 @@ class CORE_EXPORT QgsSnappingUtils : public QObject SnapAdvanced, //!< snap according to the configuration set in setLayers() }; - /** Set how the snapping to map is done */ - void setSnapToMapMode( SnapToMapMode mode ); - /** Find out how the snapping to map is done */ - SnapToMapMode snapToMapMode() const { return mSnapToMapMode; } - enum IndexingStrategy { IndexAlwaysFull, //!< For all layers build index of full extent. Uses more memory, but queries are faster. @@ -96,11 +97,6 @@ class CORE_EXPORT QgsSnappingUtils : public QObject /** Find out which strategy is used for indexing - by default hybrid indexing is used */ IndexingStrategy indexingStrategy() const { return mStrategy; } - /** Configure options used when the mode is snap to current layer or to all layers */ - void setDefaultSettings( int type, double tolerance, QgsTolerance::UnitType unit ); - /** Query options used when the mode is snap to current layer or to all layers */ - void defaultSettings( int& type, double& tolerance, QgsTolerance::UnitType& unit ); - /** * Configures how a certain layer should be handled in a snapping operation */ @@ -150,28 +146,27 @@ class CORE_EXPORT QgsSnappingUtils : public QObject QgsTolerance::UnitType unit; }; - /** Set layers which will be used for snapping */ - void setLayers( const QList& layers ); /** Query layers used for snapping */ QList layers() const { return mLayers; } - /** Set whether to consider intersections of nearby segments for snapping */ - void setSnapOnIntersections( bool enabled ); - /** Query whether to consider intersections of nearby segments for snapping */ - bool snapOnIntersections() const { return mSnapOnIntersection; } - /** Get extra information about the instance * @note added in QGIS 2.14 */ QString dump(); - public slots: - /** Read snapping configuration from the project */ - void readConfigFromProject(); + /** + * The snapping configuration controls the behavior of this object + */ + QgsSnappingConfig config() const; + + /** + * The snapping configuration controls the behavior of this object + */ + void setConfig( const QgsSnappingConfig& snappingConfig ); signals: - /** Emitted when snapping configuration has been changed - * @note added in QGIS 2.14 + /** + * Emitted when the snapping settings object changes. */ void configChanged(); @@ -181,10 +176,8 @@ class CORE_EXPORT QgsSnappingUtils : public QObject //! Called when finished indexing a layer. When index == count the indexing is complete virtual void prepareIndexProgress( int index ) { Q_UNUSED( index ); } - private slots: - void onLayersWillBeRemoved( const QStringList& layerIds ); - private: + void onIndividualLayerSettingsChanged( const QHash layerSettings ); //! Get destination CRS from map settings, or an invalid CRS if projections are disabled QgsCoordinateReferenceSystem destinationCrs() const; @@ -208,14 +201,11 @@ class CORE_EXPORT QgsSnappingUtils : public QObject QgsMapSettings mMapSettings; QgsVectorLayer* mCurrentLayer; + QgsSnappingConfig mSnappingConfig; + // configuration - SnapToMapMode mSnapToMapMode; IndexingStrategy mStrategy; - int mDefaultType; - double mDefaultTolerance; - QgsTolerance::UnitType mDefaultUnit; QList mLayers; - bool mSnapOnIntersection; // internal data typedef QMap LocatorsMap; diff --git a/src/gui/qgsmapcanvastracer.cpp b/src/gui/qgsmapcanvastracer.cpp index c4d5b3b259c4..e0473457c93c 100644 --- a/src/gui/qgsmapcanvastracer.cpp +++ b/src/gui/qgsmapcanvastracer.cpp @@ -21,6 +21,7 @@ #include "qgsmessagebaritem.h" #include "qgssnappingutils.h" #include "qgsvectorlayer.h" +#include "qgssnappingconfig.h" #include @@ -101,17 +102,17 @@ void QgsMapCanvasTracer::configure() QList layers; QStringList visibleLayerIds = mCanvas->mapSettings().layers(); - switch ( mCanvas->snappingUtils()->snapToMapMode() ) + switch ( mCanvas->snappingUtils()->config().mode() ) { default: - case QgsSnappingUtils::SnapCurrentLayer: + case QgsSnappingConfig::ActiveLayer: { QgsVectorLayer* vl = qobject_cast( mCanvas->currentLayer() ); if ( vl && visibleLayerIds.contains( vl->id() ) ) layers << vl; } break; - case QgsSnappingUtils::SnapAllLayers: + case QgsSnappingConfig::AllLayers: Q_FOREACH ( const QString& layerId, visibleLayerIds ) { QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerId ) ); @@ -119,7 +120,7 @@ void QgsMapCanvasTracer::configure() layers << vl; } break; - case QgsSnappingUtils::SnapAdvanced: + case QgsSnappingConfig::AdvancedConfiguration: Q_FOREACH ( const QgsSnappingUtils::LayerConfig& cfg, mCanvas->snappingUtils()->layers() ) { if ( visibleLayerIds.contains( cfg.layer->id() ) ) @@ -134,6 +135,6 @@ void QgsMapCanvasTracer::configure() void QgsMapCanvasTracer::onCurrentLayerChanged() { // no need to bother if we are not snapping - if ( mCanvas->snappingUtils()->snapToMapMode() == QgsSnappingUtils::SnapCurrentLayer ) + if ( mCanvas->snappingUtils()->config().mode() == QgsSnappingConfig::ActiveLayer ) invalidateGraph(); } diff --git a/src/gui/qgsmapmouseevent.cpp b/src/gui/qgsmapmouseevent.cpp index b1cb728c5ad6..8c46c66f7407 100644 --- a/src/gui/qgsmapmouseevent.cpp +++ b/src/gui/qgsmapmouseevent.cpp @@ -18,6 +18,7 @@ #include "qgsmapcanvas.h" #include "qgssnappingutils.h" +#include "qgssnappingconfig.h" /// @cond PRIVATE struct EdgesOnlyFilter : public QgsPointLocator::MatchFilter @@ -62,18 +63,18 @@ QgsPoint QgsMapMouseEvent::snapPoint( SnappingMode snappingMode ) } QgsSnappingUtils* snappingUtils = mMapCanvas->snappingUtils(); - QgsSnappingUtils::SnapToMapMode canvasMode = snappingUtils->snapToMapMode(); if ( snappingMode == SnapAllLayers ) { - int type; - double tolerance; - QgsTolerance::UnitType unit; - snappingUtils->defaultSettings( type, tolerance, unit ); - snappingUtils->setSnapToMapMode( QgsSnappingUtils::SnapAllLayers ); - snappingUtils->setDefaultSettings( QgsPointLocator::Vertex | QgsPointLocator::Edge, tolerance, unit ); + QgsSnappingConfig canvasConfig = snappingUtils->config(); + QgsSnappingConfig localConfig = snappingUtils->config(); + + localConfig.setMode( QgsSnappingConfig::AllLayers ); + localConfig.setType( QgsSnappingConfig::VertexAndSegment ); + snappingUtils->setConfig( localConfig ); + mSnapMatch = snappingUtils->snapToMap( mMapPoint ); - snappingUtils->setSnapToMapMode( canvasMode ); - snappingUtils->setDefaultSettings( type, tolerance, unit ); + + snappingUtils->setConfig( canvasConfig ); } else { @@ -119,16 +120,17 @@ QList QgsMapMouseEvent::snapSegment( SnappingMode snappingMode, bool* { // run snapToMap with only edges on all layers QgsSnappingUtils* snappingUtils = mMapCanvas->snappingUtils(); - QgsSnappingUtils::SnapToMapMode canvasMode = snappingUtils->snapToMapMode(); - int type; - double tolerance; - QgsTolerance::UnitType unit; - snappingUtils->defaultSettings( type, tolerance, unit ); - snappingUtils->setSnapToMapMode( QgsSnappingUtils::SnapAllLayers ); - snappingUtils->setDefaultSettings( QgsPointLocator::Edge, tolerance, unit ); + + QgsSnappingConfig canvasConfig = snappingUtils->config(); + QgsSnappingConfig localConfig = snappingUtils->config(); + + localConfig.setMode( QgsSnappingConfig::AllLayers ); + localConfig.setType( QgsSnappingConfig::Segment ); + snappingUtils->setConfig( localConfig ); + match = snappingUtils->snapToMap( mOriginalMapPoint ); - snappingUtils->setSnapToMapMode( canvasMode ); - snappingUtils->setDefaultSettings( type, tolerance, unit ); + + snappingUtils->setConfig( canvasConfig ); } if ( match.isValid() && match.hasEdge() ) { diff --git a/src/ui/qgisapp.ui b/src/ui/qgisapp.ui index 255a649af091..3e24abf62057 100644 --- a/src/ui/qgisapp.ui +++ b/src/ui/qgisapp.ui @@ -17,7 +17,7 @@ 0 0 1018 - 25 + 19 @@ -570,6 +570,17 @@ false + + + Snapping toolbar + + + TopToolBarArea + + + false + + diff --git a/src/ui/qgsoptionsbase.ui b/src/ui/qgsoptionsbase.ui index 36007432399e..2ac1c1a094c1 100644 --- a/src/ui/qgsoptionsbase.ui +++ b/src/ui/qgsoptionsbase.ui @@ -6,7 +6,7 @@ 0 0 - 791 + 857 658 @@ -308,7 +308,7 @@ - 0 + 13 @@ -337,8 +337,8 @@ 0 0 - 723 - 640 + 685 + 612 @@ -1023,8 +1023,8 @@ 0 0 - 607 - 850 + 671 + 869 @@ -1456,8 +1456,8 @@ 0 0 - 601 - 694 + 671 + 659 @@ -1814,8 +1814,8 @@ 0 0 - 747 - 972 + 684 + 924 @@ -2612,8 +2612,8 @@ 0 0 - 617 - 607 + 685 + 612 @@ -2759,8 +2759,8 @@ 0 0 - 617 - 607 + 685 + 612 @@ -3102,7 +3102,7 @@ 0 0 - 650 + 685 612 @@ -3533,8 +3533,8 @@ 0 0 - 617 - 607 + 685 + 612 @@ -3802,8 +3802,8 @@ 0 0 - 601 - 668 + 671 + 669 @@ -4003,14 +4003,7 @@ Snapping - - - - Default snap mode - - - - + @@ -4020,14 +4013,7 @@ - - - - Default snapping tolerance - - - - + 5 @@ -4037,14 +4023,7 @@ - - - - Search radius for vertex edits - - - - + 5 @@ -4054,7 +4033,7 @@ - + @@ -4074,7 +4053,7 @@ - + @@ -4088,7 +4067,7 @@ - + Qt::Horizontal @@ -4101,7 +4080,7 @@ - + Qt::Horizontal @@ -4114,7 +4093,7 @@ - + Qt::Horizontal @@ -4127,13 +4106,47 @@ - - + + - Open snapping options in a dock window (QGIS restart required) + Search radius for vertex edits + + + + Display main dialog as (restart required) + + + + + + + Default snap mode + + + + + + + Display simplified panel in (restart required) + + + + + + + Default snapping tolerance + + + + + + + + + @@ -4347,8 +4360,8 @@ 0 0 - 617 - 607 + 685 + 612 @@ -4486,8 +4499,8 @@ 0 0 - 601 - 644 + 671 + 638 @@ -4732,8 +4745,8 @@ 0 0 - 617 - 607 + 685 + 612 @@ -4841,8 +4854,8 @@ 0 0 - 601 - 737 + 671 + 689 @@ -5540,7 +5553,6 @@ mLineColorToolButton mFillColorToolButton mLineGhostCheckBox - cbxSnappingOptionsDocked mDefaultSnapModeComboBox mDefaultSnappingToleranceSpinBox mDefaultSnappingToleranceComboBox diff --git a/tests/src/core/testqgssnappingutils.cpp b/tests/src/core/testqgssnappingutils.cpp index 61057d6e029a..fd8ed395dae6 100644 --- a/tests/src/core/testqgssnappingutils.cpp +++ b/tests/src/core/testqgssnappingutils.cpp @@ -23,6 +23,7 @@ #include "qgsgeometry.h" #include "qgsmaplayerregistry.h" #include "qgssnappingutils.h" +#include "qgssnappingconfig.h" struct FilterExcludePoint : public QgsPointLocator::MatchFilter @@ -93,14 +94,21 @@ class TestQgsSnappingUtils : public QObject u.setCurrentLayer( mVL ); // first try with no snapping enabled - u.setDefaultSettings( 0, 10, QgsTolerance::Pixels ); + QgsSnappingConfig snappingConfig = u.config(); + snappingConfig.setEnabled( false ); + snappingConfig.setTolerance( 10 ); + snappingConfig.setUnits( QgsTolerance::Pixels ); + snappingConfig.setMode( QgsSnappingConfig::ActiveLayer ); + u.setConfig( snappingConfig ); QgsPointLocator::Match m0 = u.snapToMap( QPoint( 100, 100 ) ); QVERIFY( !m0.isValid() ); QVERIFY( !m0.hasVertex() ); // now enable snapping - u.setDefaultSettings( QgsPointLocator::Vertex | QgsPointLocator::Edge, 10, QgsTolerance::Pixels ); + snappingConfig.setEnabled( true ); + snappingConfig.setType( QgsSnappingConfig::Vertex ); + u.setConfig( snappingConfig ); QgsPointLocator::Match m = u.snapToMap( QPoint( 100, 100 ) ); QVERIFY( m.isValid() ); @@ -113,7 +121,9 @@ class TestQgsSnappingUtils : public QObject // do not consider edges in the following test - on 32-bit platforms // result was an edge match very close to (1,0) instead of being exactly (1,0) - u.setDefaultSettings( QgsPointLocator::Vertex, 10, QgsTolerance::Pixels ); + + snappingConfig.setType( QgsSnappingConfig::Vertex ); + u.setConfig( snappingConfig ); // test with filtering FilterExcludePoint myFilter( QgsPoint( 1, 0 ) ); @@ -129,8 +139,10 @@ class TestQgsSnappingUtils : public QObject QVERIFY( mapSettings.hasValidSettings() ); QgsSnappingUtils u; + QgsSnappingConfig snappingConfig = u.config(); u.setMapSettings( mapSettings ); - u.setSnapToMapMode( QgsSnappingUtils::SnapAllLayers ); + snappingConfig.setMode( QgsSnappingConfig::AllLayers ); + u.setConfig( snappingConfig ); // right now there are no layers in map settings - snapping will fail @@ -154,11 +166,11 @@ class TestQgsSnappingUtils : public QObject QVERIFY( mapSettings.hasValidSettings() ); QgsSnappingUtils u; + QgsSnappingConfig snappingConfig = u.config(); u.setMapSettings( mapSettings ); - u.setSnapToMapMode( QgsSnappingUtils::SnapAdvanced ); - QList layers; - layers << QgsSnappingUtils::LayerConfig( mVL, QgsPointLocator::Vertex, 10, QgsTolerance::Pixels ); - u.setLayers( layers ); + snappingConfig.setMode( QgsSnappingConfig::AdvancedConfiguration ); + snappingConfig.setIndividualLayerSettings( mVL, QgsSnappingConfig::IndividualLayerSettings( true, QgsSnappingConfig::Vertex, 10, QgsTolerance::Pixels ) ); + u.setConfig( snappingConfig ); QgsPointLocator::Match m = u.snapToMap( QPoint( 100, 100 ) ); QVERIFY( m.isValid() ); @@ -201,16 +213,18 @@ class TestQgsSnappingUtils : public QObject QgsSnappingUtils u; u.setMapSettings( mapSettings ); - u.setSnapToMapMode( QgsSnappingUtils::SnapAdvanced ); - QList layers; - layers << QgsSnappingUtils::LayerConfig( vl, QgsPointLocator::Vertex, 0.1, QgsTolerance::ProjectUnits ); - u.setLayers( layers ); + QgsSnappingConfig snappingConfig = u.config(); + snappingConfig.setMode( QgsSnappingConfig::AdvancedConfiguration ); + QgsSnappingConfig::IndividualLayerSettings layerSettings( true, QgsSnappingConfig::Vertex, 0.1, QgsTolerance::ProjectUnits ); + snappingConfig.setIndividualLayerSettings( vl, layerSettings ); + u.setConfig( snappingConfig ); // no snapping on intersections by default - should find nothing QgsPointLocator::Match m = u.snapToMap( QgsPoint( 0.45, 0.5 ) ); QVERIFY( !m.isValid() ); - u.setSnapOnIntersections( true ); + snappingConfig.setIntersectionSnapping( true ); + u.setConfig( snappingConfig ); QgsPointLocator::Match m2 = u.snapToMap( QgsPoint( 0.45, 0.5 ) ); QVERIFY( m2.isValid() ); diff --git a/tests/src/python/test_layer_dependencies.py b/tests/src/python/test_layer_dependencies.py index da70df132ae2..39f99b5a73f0 100644 --- a/tests/src/python/test_layer_dependencies.py +++ b/tests/src/python/test_layer_dependencies.py @@ -19,6 +19,7 @@ QgsVectorLayer, QgsMapSettings, QgsSnappingUtils, + QgsSnappingConfig, QgsPointLocator, QgsTolerance, QgsRectangle, @@ -111,9 +112,12 @@ def test_resetSnappingIndex(self): u = QgsSnappingUtils() u.setMapSettings(ms) - u.setSnapToMapMode(QgsSnappingUtils.SnapAdvanced) - layers = [QgsSnappingUtils.LayerConfig(self.pointsLayer, QgsPointLocator.Vertex, 20, QgsTolerance.Pixels)] - u.setLayers(layers) + cfg = u.config() + cfg.setMode(QgsSnappingConfig.AdvancedConfiguration) + cfg.setIndividualLayerSettings(self.pointsLayer, + QgsSnappingConfig.IndividualLayerSettings(True, + QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) + u.setConfig(cfg) m = u.snapToMap(QPoint(95, 100)) self.assertTrue(m.isValid()) @@ -153,10 +157,10 @@ def test_resetSnappingIndex(self): self.pointsLayer.setDependencies([]) # test chained layer dependencies A -> B -> C - layers = [QgsSnappingUtils.LayerConfig(self.pointsLayer, QgsPointLocator.Vertex, 20, QgsTolerance.Pixels), - QgsSnappingUtils.LayerConfig(self.pointsLayer2, QgsPointLocator.Vertex, 20, QgsTolerance.Pixels) - ] - u.setLayers(layers) + cfg.setIndividualLayerSettings(self.pointsLayer2, + QgsSnappingConfig.IndividualLayerSettings(True, + QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) + u.setConfig(cfg) self.pointsLayer.setDependencies([QgsMapLayerDependency(self.linesLayer.id())]) self.pointsLayer2.setDependencies([QgsMapLayerDependency(self.pointsLayer.id())]) # add another line @@ -230,11 +234,15 @@ def test_signalConnection(self): u = QgsSnappingUtils() u.setMapSettings(ms) - u.setSnapToMapMode(QgsSnappingUtils.SnapAdvanced) - layers = [QgsSnappingUtils.LayerConfig(self.pointsLayer, QgsPointLocator.Vertex, 20, QgsTolerance.Pixels), - QgsSnappingUtils.LayerConfig(self.pointsLayer2, QgsPointLocator.Vertex, 20, QgsTolerance.Pixels) - ] - u.setLayers(layers) + cfg = u.config() + cfg.setMode(QgsSnappingConfig.AdvancedConfiguration) + cfg.setIndividualLayerSettings(self.pointsLayer, + QgsSnappingConfig.IndividualLayerSettings(True, + QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) + cfg.setIndividualLayerSettings(self.pointsLayer2, + QgsSnappingConfig.IndividualLayerSettings(True, + QgsSnappingConfig.Vertex, 20, QgsTolerance.Pixels)) + u.setConfig(cfg) # add another line f = QgsFeature(self.linesLayer.fields()) f.setFeatureId(4) From 80641488e1cd372216a13162ae165606c4b6209a Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Sat, 8 Oct 2016 21:30:06 +0200 Subject: [PATCH 379/897] Make QgsPoint a Q_GADGET --- src/core/CMakeLists.txt | 2 +- src/core/qgspoint.h | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index b518d1c80d3b..293756e20060 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -479,6 +479,7 @@ SET(QGIS_CORE_MOC_HDRS qgsofflineediting.h qgsowsconnection.h qgspluginlayer.h + qgspoint.h qgspointlocator.h qgsproject.h qgsrelationmanager.h @@ -674,7 +675,6 @@ SET(QGIS_CORE_HDRS qgspainting.h qgspallabeling.h qgspluginlayerregistry.h - qgspoint.h qgspointlocator.h qgsproject.h qgsprojectfiletransform.h diff --git a/src/core/qgspoint.h b/src/core/qgspoint.h index 1d89da1c06fd..56fed3917edf 100644 --- a/src/core/qgspoint.h +++ b/src/core/qgspoint.h @@ -110,6 +110,11 @@ class CORE_EXPORT QgsVector */ class CORE_EXPORT QgsPoint { + Q_GADGET + + Q_PROPERTY( double x READ x WRITE setX ) + Q_PROPERTY( double y READ y WRITE setY ) + public: /// Default constructor QgsPoint() From a6a4f2edba41ebbe2d9fd7507d7204eac5018393 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Sat, 8 Oct 2016 21:34:20 +0200 Subject: [PATCH 380/897] Enable C++11 by default --- CMakeLists.txt | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d1968d7cd8cf..a3e9379e1a2a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -346,23 +346,8 @@ FIND_PROGRAM(QT_LRELEASE_EXECUTABLE # or definitely Apple LLVM 5.0 (based on LLVM 3.3svn, in Xcode 5+): # https://gist.github.com/yamaya/2924292 -IF (CMAKE_CXX_COMPILER_ID MATCHES "GNU") - EXECUTE_PROCESS(COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION) - IF (GCC_VERSION VERSION_GREATER 4.7 OR GCC_VERSION VERSION_EQUAL 4.7) - SET(USE_CXX_11 TRUE) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") - ENDIF() -ELSEIF (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - IF ((NOT APPLE AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "3.2") - OR (APPLE AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "4.1")) - SET(USE_CXX_11 TRUE) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wno-error=c++11-narrowing") - ENDIF() -ELSEIF (MSVC AND MSVC_VERSION GREATER 1600) - SET(USE_CXX_11 TRUE) -ELSE() - SET(USE_CXX_11 FALSE) -ENDIF() +SET(CMAKE_CXX_STANDARD 11) +SET(USE_CXX_11 TRUE) #allow override keyword if available IF(NOT USE_CXX_11) From 5c919fbcca490091d637c1f25291223d23e429d7 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 18 Oct 2016 16:17:07 +0200 Subject: [PATCH 381/897] Move topological editing setting management fully to QgsProject --- python/core/qgsproject.sip | 7 +++++++ python/core/qgssnappingconfig.sip | 6 ------ src/app/nodetool/qgsmaptoolnodetool.cpp | 9 ++++----- src/app/nodetool/qgsselectedfeature.cpp | 12 ++---------- src/app/qgsmaptooladdfeature.cpp | 2 +- src/app/qgsmaptooladdpart.cpp | 2 +- src/app/qgsmaptoolsplitfeatures.cpp | 2 +- src/app/qgsmaptoolsplitparts.cpp | 2 +- src/app/qgssnappingwidget.cpp | 17 ++++++++++------- src/app/qgssnappingwidget.h | 2 ++ src/core/qgsproject.cpp | 4 ++-- src/core/qgsproject.h | 7 +++++++ src/core/qgssnappingconfig.cpp | 16 ---------------- src/core/qgssnappingconfig.h | 7 ------- src/gui/qgsmapcanvassnapper.cpp | 4 ++-- 15 files changed, 40 insertions(+), 59 deletions(-) diff --git a/python/core/qgsproject.sip b/python/core/qgsproject.sip index 334e7b6dc3df..61fab5ed00f3 100644 --- a/python/core/qgsproject.sip +++ b/python/core/qgsproject.sip @@ -455,6 +455,13 @@ class QgsProject : QObject */ void transactionGroupsChanged(); + /** + * Emitted when the topological editing flag has changed. + * + * @note Added in QGIS 3.0 + */ + void topologicalEditingChanged(); + public slots: /** * Flag the project as dirty (modified). If this flag is set, the user will diff --git a/python/core/qgssnappingconfig.sip b/python/core/qgssnappingconfig.sip index 268dbdf47c7a..9beec6e7622a 100644 --- a/python/core/qgssnappingconfig.sip +++ b/python/core/qgssnappingconfig.sip @@ -131,12 +131,6 @@ class QgsSnappingConfig //! set the type of units void setUnits( QgsTolerance::UnitType units ); - //! return if the topological editing is enabled - bool topologicalEditing() const; - - //! set if the topological editing is enabled - void setTopologicalEditing( bool enabled ); - //! return if the snapping on intersection is enabled bool intersectionSnapping() const; diff --git a/src/app/nodetool/qgsmaptoolnodetool.cpp b/src/app/nodetool/qgsmaptoolnodetool.cpp index b1f8b19bbde1..7f98df300dee 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.cpp +++ b/src/app/nodetool/qgsmaptoolnodetool.cpp @@ -150,7 +150,7 @@ void QgsMapToolNodeTool::canvasMoveEvent( QgsMapMouseEvent* e ) if ( vertexEntry->isSelected() ) mMoveVertices[mSelectedFeature->featureId()].append( qMakePair( vertexEntry->vertexId(), toMapCoordinates( vlayer, vertexEntry->point() ) ) ); } - if ( QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ) ) + if ( QgsProject::instance()->topologicalEditing() ) { createTopologyRubberBands(); } @@ -492,10 +492,9 @@ void QgsMapToolNodeTool::canvasReleaseEvent( QgsMapMouseEvent* e ) { pressLayerCoords = toLayerCoordinates( vlayer, mClosestMapVertex ); - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); - if ( topologicalEditing ) + if ( QgsProject::instance()->topologicalEditing() ) { - //insert vertices for snap, but don't add them to features which already has a vertex being moved + //insert vertices for snap, but don't add them to features which already have a vertex being moved insertSegmentVerticesForSnap( snapResults, vlayer, movedFids ); } } @@ -608,7 +607,7 @@ void QgsMapToolNodeTool::canvasDoubleClickEvent( QgsMapMouseEvent* e ) QgsVectorLayer *vlayer = mSelectedFeature->vlayer(); Q_ASSERT( vlayer ); - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); QMultiMap currentResultList; QList snapResults; diff --git a/src/app/nodetool/qgsselectedfeature.cpp b/src/app/nodetool/qgsselectedfeature.cpp index 5118cf1a4503..c9d0ac680e7d 100644 --- a/src/app/nodetool/qgsselectedfeature.cpp +++ b/src/app/nodetool/qgsselectedfeature.cpp @@ -35,14 +35,11 @@ QgsSelectedFeature::QgsSelectedFeature( QgsFeatureId featureId, , mChangingGeometry( false ) , mValidator( nullptr ) { - QgsDebugCall; setSelectedFeature( featureId, vlayer, canvas ); } QgsSelectedFeature::~QgsSelectedFeature() { - QgsDebugCall; - deleteVertexMap(); while ( !mGeomErrorMarkers.isEmpty() ) @@ -63,15 +60,12 @@ QgsSelectedFeature::~QgsSelectedFeature() void QgsSelectedFeature::currentLayerChanged( QgsMapLayer *layer ) { - QgsDebugCall; if ( layer == mVlayer ) deleteLater(); } void QgsSelectedFeature::updateGeometry( const QgsGeometry *geom ) { - QgsDebugCall; - delete mGeometry; if ( !geom ) @@ -119,7 +113,6 @@ void QgsSelectedFeature::setSelectedFeature( QgsFeatureId featureId, QgsVectorLa void QgsSelectedFeature::beforeRollBack() { - QgsDebugCall; disconnect( mVlayer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry & ) ), this, SLOT( geometryChanged( QgsFeatureId, const QgsGeometry & ) ) ); deleteVertexMap(); } @@ -165,7 +158,6 @@ void QgsSelectedFeature::geometryChanged( QgsFeatureId fid, const QgsGeometry &g void QgsSelectedFeature::validateGeometry( QgsGeometry *g ) { - QgsDebugCall; QSettings settings; if ( settings.value( "/qgis/digitizing/validate_geometries", 1 ).toInt() == 0 ) return; @@ -242,7 +234,7 @@ void QgsSelectedFeature::deleteSelectedVertexes() if ( nSelected == 0 ) return; - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); QMultiMap currentResultList; mVlayer->beginEditCommand( QObject::tr( "Deleted vertices" ) ); @@ -328,7 +320,7 @@ void QgsSelectedFeature::moveSelectedVertexes( QgsVector v ) return; mVlayer->beginEditCommand( QObject::tr( "Moved vertices" ) ); - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); beginGeometryChange(); diff --git a/src/app/qgsmaptooladdfeature.cpp b/src/app/qgsmaptooladdfeature.cpp index 38bfa995a2cc..33933537e573 100644 --- a/src/app/qgsmaptooladdfeature.cpp +++ b/src/app/qgsmaptooladdfeature.cpp @@ -292,7 +292,7 @@ void QgsMapToolAddFeature::cadCanvasReleaseEvent( QgsMapMouseEvent* e ) if ( addFeature( vlayer, f.data(), false ) ) { //add points to other features to keep topology up-to-date - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); //use always topological editing for avoidIntersection. //Otherwise, no way to guarantee the geometries don't have a small gap in between. diff --git a/src/app/qgsmaptooladdpart.cpp b/src/app/qgsmaptooladdpart.cpp index 7fdcd7f36ec4..7b65e40bdb5b 100644 --- a/src/app/qgsmaptooladdpart.cpp +++ b/src/app/qgsmaptooladdpart.cpp @@ -185,7 +185,7 @@ void QgsMapToolAddPart::cadCanvasReleaseEvent( QgsMapMouseEvent * e ) emit messageDiscarded(); //add points to other features to keep topology up-to-date - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); if ( topologicalEditing ) { addTopologicalPoints( points() ); diff --git a/src/app/qgsmaptoolsplitfeatures.cpp b/src/app/qgsmaptoolsplitfeatures.cpp index ea04df80f5f9..8a00b5c468de 100644 --- a/src/app/qgsmaptoolsplitfeatures.cpp +++ b/src/app/qgsmaptoolsplitfeatures.cpp @@ -96,7 +96,7 @@ void QgsMapToolSplitFeatures::cadCanvasReleaseEvent( QgsMapMouseEvent * e ) deleteTempRubberBand(); //bring up dialog if a split was not possible (polygon) or only done once (line) - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + int topologicalEditing = QgsProject::instance()->topologicalEditing(); vlayer->beginEditCommand( tr( "Features split" ) ); int returnCode = vlayer->splitFeatures( points(), topologicalEditing ); vlayer->endEditCommand(); diff --git a/src/app/qgsmaptoolsplitparts.cpp b/src/app/qgsmaptoolsplitparts.cpp index 4f2d1983845d..78f2a4bfa4f1 100644 --- a/src/app/qgsmaptoolsplitparts.cpp +++ b/src/app/qgsmaptoolsplitparts.cpp @@ -94,7 +94,7 @@ void QgsMapToolSplitParts::cadCanvasReleaseEvent( QgsMapMouseEvent * e ) deleteTempRubberBand(); //bring up dialog if a split was not possible (polygon) or only done once (line) - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); vlayer->beginEditCommand( tr( "Parts split" ) ); int returnCode = vlayer->splitParts( points(), topologicalEditing ); vlayer->endEditCommand(); diff --git a/src/app/qgssnappingwidget.cpp b/src/app/qgssnappingwidget.cpp index 3fbd47181cfc..9d77e3d6f6fd 100644 --- a/src/app/qgssnappingwidget.cpp +++ b/src/app/qgssnappingwidget.cpp @@ -40,7 +40,7 @@ -QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas *canvas, QWidget* parent ) +QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, QWidget* parent ) : QWidget( parent ) , mProject( project ) , mCanvas( canvas ) @@ -227,6 +227,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas *canvas, // connect settings changed and map units changed to properly update the widget connect( project, &QgsProject::snappingConfigChanged, this, &QgsSnappingWidget::projectSnapSettingsChanged ); + connect( project, &QgsProject::topologicalEditingChanged, this, &QgsSnappingWidget::projectTopologicalEditingChanged ); connect( mCanvas, SIGNAL( mapUnitsChanged() ), this, SLOT( updateToleranceDecimals() ) ); // modeChanged determines if widget are visible or not based on mode @@ -293,14 +294,17 @@ void QgsSnappingWidget::projectSnapSettingsChanged() mUnitsComboBox->setCurrentIndex( mUnitsComboBox->findData( config.units() ) ); } - if ( config.topologicalEditing() != mTopologicalEditingAction->isChecked() ) + if ( config.intersectionSnapping() != mIntersectionSnappingAction->isChecked() ) { - mTopologicalEditingAction->setChecked( config.topologicalEditing() ); + mIntersectionSnappingAction->setChecked( config.intersectionSnapping() ); } +} - if ( config.intersectionSnapping() != mIntersectionSnappingAction->isChecked() ) +void QgsSnappingWidget::projectTopologicalEditingChanged() +{ + if ( QgsProject::instance()->topologicalEditing() != mTopologicalEditingAction->isChecked() ) { - mIntersectionSnappingAction->setChecked( config.intersectionSnapping() ); + mTopologicalEditingAction->setChecked( QgsProject::instance()->topologicalEditing() ); } } @@ -338,8 +342,7 @@ void QgsSnappingWidget::changeUnit( int idx ) void QgsSnappingWidget::enableTopologicalEditing( bool enabled ) { - mConfig.setTopologicalEditing( enabled ); - mProject->setSnappingConfig( mConfig ); + QgsProject::instance()->setTopologicalEditing( enabled ); } void QgsSnappingWidget::enableIntersectionSnapping( bool enabled ) diff --git a/src/app/qgssnappingwidget.h b/src/app/qgssnappingwidget.h index 0a3223cfb3f5..e1089a188832 100644 --- a/src/app/qgssnappingwidget.h +++ b/src/app/qgssnappingwidget.h @@ -73,6 +73,8 @@ class APP_EXPORT QgsSnappingWidget : public QWidget private slots: void projectSnapSettingsChanged(); + void projectTopologicalEditingChanged(); + void enableSnapping( bool checked ); void changeTolerance( double tolerance ); diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 533de5cbe8bc..66626849f42b 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -2029,12 +2029,12 @@ void QgsProject::setEvaluateDefaultValues( bool evaluateDefaultValues ) void QgsProject::setTopologicalEditing( bool enabled ) { QgsProject::instance()->writeEntry( "Digitizing", "/TopologicalEditing", ( enabled ? 1 : 0 ) ); - // todo emit snapSettingsChanged(); + emit topologicalEditingChanged(); } bool QgsProject::topologicalEditing() const { - return ( QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ) > 0 ); + return QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); } QgsUnitTypes::DistanceUnit QgsProject::distanceUnits() const diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index 3e0590779c87..ad86946ec789 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -536,6 +536,13 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ void transactionGroupsChanged(); + /** + * Emitted when the topological editing flag has changed. + * + * @note Added in QGIS 3.0 + */ + void topologicalEditingChanged(); + public slots: /** * Flag the project as dirty (modified). If this flag is set, the user will diff --git a/src/core/qgssnappingconfig.cpp b/src/core/qgssnappingconfig.cpp index 04bd356c83d2..c82f10caf65c 100644 --- a/src/core/qgssnappingconfig.cpp +++ b/src/core/qgssnappingconfig.cpp @@ -135,7 +135,6 @@ bool QgsSnappingConfig::operator==( const QgsSnappingConfig& other ) const && mType == other.mType && mTolerance == other.mTolerance && mUnits == other.mUnits - && mTopologicalEditing == other.mTopologicalEditing && mIntersectionSnapping == other.mIntersectionSnapping && mIndividualLayerSettings == other.mIndividualLayerSettings; } @@ -169,7 +168,6 @@ void QgsSnappingConfig::reset() { mUnits = units; } - mTopologicalEditing = false; mIntersectionSnapping = false; // set advanced config @@ -254,16 +252,6 @@ void QgsSnappingConfig::setUnits( QgsTolerance::UnitType units ) mUnits = units; } -bool QgsSnappingConfig::topologicalEditing() const -{ - return mTopologicalEditing; -} - -void QgsSnappingConfig::setTopologicalEditing( bool enabled ) -{ - mTopologicalEditing = enabled; -} - bool QgsSnappingConfig::intersectionSnapping() const { return mIntersectionSnapping; @@ -335,9 +323,6 @@ void QgsSnappingConfig::readProject( const QDomDocument& doc ) if ( snapSettingsElem.hasAttribute( "unit" ) ) mUnits = ( QgsTolerance::UnitType )snapSettingsElem.attribute( "unit" ).toInt(); - if ( snapSettingsElem.hasAttribute( "topological-editing" ) ) - mTopologicalEditing = snapSettingsElem.attribute( "topological-editing" ) == "1"; - if ( snapSettingsElem.hasAttribute( "intersection-snapping" ) ) mIntersectionSnapping = snapSettingsElem.attribute( "intersection-snapping" ) == "1"; @@ -384,7 +369,6 @@ void QgsSnappingConfig::writeProject( QDomDocument& doc ) snapSettingsElem.setAttribute( "type", ( int )mType ); snapSettingsElem.setAttribute( "tolerance", mTolerance ); snapSettingsElem.setAttribute( "unit", ( int )mUnits ); - snapSettingsElem.setAttribute( "topological-editing", QString::number( mTopologicalEditing ) ); snapSettingsElem.setAttribute( "intersection-snapping", QString::number( mIntersectionSnapping ) ); QDomElement ilsElement = doc.createElement( "individual-layer-settings" ); diff --git a/src/core/qgssnappingconfig.h b/src/core/qgssnappingconfig.h index 2a3c6e9d491a..01ee2048a3ef 100644 --- a/src/core/qgssnappingconfig.h +++ b/src/core/qgssnappingconfig.h @@ -162,12 +162,6 @@ class CORE_EXPORT QgsSnappingConfig //! set the type of units void setUnits( QgsTolerance::UnitType units ); - //! return if the topological editing is enabled - bool topologicalEditing() const; - - //! set if the topological editing is enabled - void setTopologicalEditing( bool enabled ); - //! return if the snapping on intersection is enabled bool intersectionSnapping() const; @@ -235,7 +229,6 @@ class CORE_EXPORT QgsSnappingConfig SnappingType mType; double mTolerance; QgsTolerance::UnitType mUnits; - bool mTopologicalEditing; bool mIntersectionSnapping; QHash mIndividualLayerSettings; diff --git a/src/gui/qgsmapcanvassnapper.cpp b/src/gui/qgsmapcanvassnapper.cpp index 8040ff880878..787614ee040f 100644 --- a/src/gui/qgsmapcanvassnapper.cpp +++ b/src/gui/qgsmapcanvassnapper.cpp @@ -71,7 +71,7 @@ int QgsMapCanvasSnapper::snapToCurrentLayer( QPoint p, QList& return 1; //topological editing on? - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); if ( allResutInTolerance ) { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); @@ -134,7 +134,7 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QListreadNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + bool topologicalEditing = QgsProject::instance()->topologicalEditing(); //snapping on intersection on? int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); From 85c105d6b000d922d76ab3f55151e7ce3992431d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 18 Oct 2016 16:27:30 +0200 Subject: [PATCH 382/897] Move management of avoidIntersectionLayers to QgsProject --- python/core/qgsproject.sip | 21 +++++++++++++++++++ python/core/qgssnappingconfig.sip | 9 +------- src/app/qgsmaptooladdfeature.cpp | 2 +- src/app/qgssnappinglayertreemodel.cpp | 18 ++++++++-------- src/core/geometry/qgsgeometryeditutils.cpp | 6 ++---- src/core/qgsproject.cpp | 11 ++++++++++ src/core/qgsproject.h | 22 ++++++++++++++++++++ src/core/qgssnappingconfig.cpp | 24 ++++------------------ src/core/qgssnappingconfig.h | 10 +-------- 9 files changed, 72 insertions(+), 51 deletions(-) diff --git a/python/core/qgsproject.sip b/python/core/qgsproject.sip index 61fab5ed00f3..4805c2216864 100644 --- a/python/core/qgsproject.sip +++ b/python/core/qgsproject.sip @@ -390,6 +390,20 @@ class QgsProject : QObject */ void setSnappingConfig( const QgsSnappingConfig& snappingConfig ); + /** + * A list of layers with which intersections should be avoided. + * + * @note Added in QGIS 3.0 + */ + QStringList avoidIntersectionsList() const; + + /** + * A list of layers with which intersections should be avoided. + * + * @note Added in QGIS 3.0 + */ + void setAvoidIntersectionsList(const QStringList& avoidIntersectionsList); + signals: //! emitted when project is being read void readProject( const QDomDocument & ); @@ -462,6 +476,13 @@ class QgsProject : QObject */ void topologicalEditingChanged(); + /** + * Emitted whenever avoidIntersectionsList has changed. + * + * @note Added in QGIS 3.0 + */ + void avoidIntersectionsListChanged(); + public slots: /** * Flag the project as dirty (modified). If this flag is set, the user will diff --git a/python/core/qgssnappingconfig.sip b/python/core/qgssnappingconfig.sip index 9beec6e7622a..f6987f7b37c6 100644 --- a/python/core/qgssnappingconfig.sip +++ b/python/core/qgssnappingconfig.sip @@ -41,9 +41,8 @@ class QgsSnappingConfig * @param type * @param tolerance * @param units - * @param avoidIntersection */ - IndividualLayerSettings( bool enabled, QgsSnappingConfig::SnappingType type, double tolerance, QgsTolerance::UnitType units, bool avoidIntersection = false ); + IndividualLayerSettings( bool enabled, QgsSnappingConfig::SnappingType type, double tolerance, QgsTolerance::UnitType units ); /** * Constructs an invalid setting @@ -77,12 +76,6 @@ class QgsSnappingConfig //! set the type of units void setUnits( QgsTolerance::UnitType units ); - //! return if it shall avoid intersection (polygon layers only) - bool avoidIntersection() const; - - //! set if it shall avoid intersection (polygon layers only) - void setAvoidIntersection( bool avoidIntersection ); - /** * Compare this configuration to other. */ diff --git a/src/app/qgsmaptooladdfeature.cpp b/src/app/qgsmaptooladdfeature.cpp index 33933537e573..fd4c7368de7d 100644 --- a/src/app/qgsmaptooladdfeature.cpp +++ b/src/app/qgsmaptooladdfeature.cpp @@ -296,7 +296,7 @@ void QgsMapToolAddFeature::cadCanvasReleaseEvent( QgsMapMouseEvent* e ) //use always topological editing for avoidIntersection. //Otherwise, no way to guarantee the geometries don't have a small gap in between. - QStringList intersectionLayers = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList" ); + QStringList intersectionLayers = QgsProject::instance()->avoidIntersectionsList(); bool avoidIntersection = !intersectionLayers.isEmpty(); if ( avoidIntersection ) //try to add topological points also to background layers { diff --git a/src/app/qgssnappinglayertreemodel.cpp b/src/app/qgssnappinglayertreemodel.cpp index 8007309e5cf3..337bc89f404c 100644 --- a/src/app/qgssnappinglayertreemodel.cpp +++ b/src/app/qgssnappinglayertreemodel.cpp @@ -494,7 +494,7 @@ QVariant QgsSnappingLayerTreeModel::data( const QModelIndex& idx, int role ) con { if ( role == Qt::CheckStateRole && vl->geometryType() == QgsWkbTypes::PolygonGeometry ) { - if ( ls.avoidIntersection() ) + if ( mProject->avoidIntersectionsList().contains( vl->id() ) ) { return Qt::Checked; } @@ -614,20 +614,20 @@ bool QgsSnappingLayerTreeModel::setData( const QModelIndex& index, const QVarian if ( index.column() == AvoidIntersectionColumn && role == Qt::CheckStateRole ) { - QgsVectorLayer *vl = vectorLayer( index ); + QgsVectorLayer* vl = vectorLayer( index ); if ( vl ) { if ( !mIndividualLayerSettings.contains( vl ) ) return false; - QgsSnappingConfig::IndividualLayerSettings ls = mIndividualLayerSettings.value( vl ); - if ( !ls.valid() ) - return false; + QStringList avoidIntersectionsList = mProject->avoidIntersectionsList(); - ls.setAvoidIntersection( value.toInt() == Qt::Checked ); - QgsSnappingConfig config = mProject->snappingConfig(); - config.setIndividualLayerSettings( vl, ls ); - mProject->setSnappingConfig( config ); + if ( value.toInt() == Qt::Checked && !avoidIntersectionsList.contains( vl->id() ) ) + avoidIntersectionsList.append( vl->id() ); + else + avoidIntersectionsList.removeAll( vl->id() ); + + mProject->setAvoidIntersectionsList( avoidIntersectionsList ); return true; } } diff --git a/src/core/geometry/qgsgeometryeditutils.cpp b/src/core/geometry/qgsgeometryeditutils.cpp index fb657f1c359f..cef714e48b80 100644 --- a/src/core/geometry/qgsgeometryeditutils.cpp +++ b/src/core/geometry/qgsgeometryeditutils.cpp @@ -241,10 +241,8 @@ QgsAbstractGeometry* QgsGeometryEditUtils::avoidIntersections( const QgsAbstract return nullptr; } - //read avoid intersections list from project properties - bool listReadOk; - QStringList avoidIntersectionsList = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList", QStringList(), &listReadOk ); - if ( !listReadOk ) + QStringList avoidIntersectionsList = QgsProject::instance()->avoidIntersectionsList(); + if ( avoidIntersectionsList.isEmpty() ) return nullptr; //no intersections stored in project does not mean error QList< QgsAbstractGeometry* > nearGeometries; diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 66626849f42b..a4ab11770c46 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -1002,6 +1002,17 @@ void QgsProject::loadEmbeddedNodes( QgsLayerTreeGroup *group ) } } +QStringList QgsProject::avoidIntersectionsList() const +{ + return readListEntry( "Digitizing", "/AvoidIntersectionsList", QStringList() ); +} + +void QgsProject::setAvoidIntersectionsList( const QStringList& avoidIntersectionsList ) +{ + writeEntry( "Digitizing", "/AvoidIntersectionsList", avoidIntersectionsList ); + emit avoidIntersectionsListChanged(); +} + QgsExpressionContext QgsProject::createExpressionContext() const { QgsExpressionContext context; diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index ad86946ec789..c96afaab8e2c 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -80,6 +80,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera Q_PROPERTY( QgsCoordinateReferenceSystem crs READ crs WRITE setCrs ) Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) Q_PROPERTY( QgsSnappingConfig snappingConfig READ snappingConfig WRITE setSnappingConfig NOTIFY snappingConfigChanged ) + Q_PROPERTY( QStringList avoidIntersectionsList READ avoidIntersectionsList WRITE setAvoidIntersectionsList NOTIFY avoidIntersectionsListChanged ) public: @@ -469,6 +470,20 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ void setSnappingConfig( const QgsSnappingConfig& snappingConfig ); + /** + * A list of layers with which intersections should be avoided. + * + * @note Added in QGIS 3.0 + */ + QStringList avoidIntersectionsList() const; + + /** + * A list of layers with which intersections should be avoided. + * + * @note Added in QGIS 3.0 + */ + void setAvoidIntersectionsList( const QStringList& avoidIntersectionsList ); + signals: //! emitted when project is being read void readProject( const QDomDocument& ); @@ -543,6 +558,13 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ void topologicalEditingChanged(); + /** + * Emitted whenever avoidIntersectionsList has changed. + * + * @note Added in QGIS 3.0 + */ + void avoidIntersectionsListChanged(); + public slots: /** * Flag the project as dirty (modified). If this flag is set, the user will diff --git a/src/core/qgssnappingconfig.cpp b/src/core/qgssnappingconfig.cpp index c82f10caf65c..3ffbaa6903c5 100644 --- a/src/core/qgssnappingconfig.cpp +++ b/src/core/qgssnappingconfig.cpp @@ -30,17 +30,15 @@ QgsSnappingConfig::IndividualLayerSettings::IndividualLayerSettings() , mType( Vertex ) , mTolerance( 0 ) , mUnits( QgsTolerance::Pixels ) - , mAvoidIntersection( false ) {} -QgsSnappingConfig::IndividualLayerSettings::IndividualLayerSettings( bool enabled, SnappingType type, double tolerance, QgsTolerance::UnitType units, bool avoidIntersection ) +QgsSnappingConfig::IndividualLayerSettings::IndividualLayerSettings( bool enabled, SnappingType type, double tolerance, QgsTolerance::UnitType units ) : mValid( true ) , mEnabled( enabled ) , mType( type ) , mTolerance( tolerance ) , mUnits( units ) - , mAvoidIntersection( avoidIntersection ) {} bool QgsSnappingConfig::IndividualLayerSettings::valid() const @@ -88,24 +86,13 @@ void QgsSnappingConfig::IndividualLayerSettings::setUnits( QgsTolerance::UnitTyp mUnits = units; } -bool QgsSnappingConfig::IndividualLayerSettings::avoidIntersection() const -{ - return mAvoidIntersection; -} - -void QgsSnappingConfig::IndividualLayerSettings::setAvoidIntersection( bool avoidIntersection ) -{ - mAvoidIntersection = avoidIntersection; -} - bool QgsSnappingConfig::IndividualLayerSettings::operator !=( const QgsSnappingConfig::IndividualLayerSettings& other ) const { return mValid != other.mValid || mEnabled != other.mEnabled || mType != other.mType || mTolerance != other.mTolerance - || mUnits != other.mUnits - || mAvoidIntersection != other.mAvoidIntersection; + || mUnits != other.mUnits; } bool QgsSnappingConfig::IndividualLayerSettings::operator ==( const QgsSnappingConfig::IndividualLayerSettings& other ) const @@ -114,8 +101,7 @@ bool QgsSnappingConfig::IndividualLayerSettings::operator ==( const QgsSnappingC && mEnabled == other.mEnabled && mType == other.mType && mTolerance == other.mTolerance - && mUnits == other.mUnits - && mAvoidIntersection == other.mAvoidIntersection; + && mUnits == other.mUnits; } @@ -347,7 +333,6 @@ void QgsSnappingConfig::readProject( const QDomDocument& doc ) SnappingType type = ( SnappingType )settingElement.attribute( "type" ).toInt(); double tolerance = settingElement.attribute( "tolerance" ).toDouble(); QgsTolerance::UnitType units = ( QgsTolerance::UnitType )settingElement.attribute( "units" ).toInt(); - bool avoidIntersection = settingElement.attribute( "avoid-intersection" ) == "1"; QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( layerId ); if ( !ml || ml->type() != QgsMapLayer::VectorLayer ) @@ -355,7 +340,7 @@ void QgsSnappingConfig::readProject( const QDomDocument& doc ) QgsVectorLayer* vl = qobject_cast( ml ); - IndividualLayerSettings setting = IndividualLayerSettings( enabled, type, tolerance, units, avoidIntersection ); + IndividualLayerSettings setting = IndividualLayerSettings( enabled, type, tolerance, units ); mIndividualLayerSettings.insert( vl, setting ); } } @@ -382,7 +367,6 @@ void QgsSnappingConfig::writeProject( QDomDocument& doc ) layerElement.setAttribute( "type", ( int )setting.type() ); layerElement.setAttribute( "tolerance", setting.tolerance() ); layerElement.setAttribute( "units", ( int )setting.units() ); - layerElement.setAttribute( "avoid-intersection", QString::number( setting.avoidIntersection() ) ); ilsElement.appendChild( layerElement ); } snapSettingsElem.appendChild( ilsElement ); diff --git a/src/core/qgssnappingconfig.h b/src/core/qgssnappingconfig.h index 01ee2048a3ef..f9639ea884a2 100644 --- a/src/core/qgssnappingconfig.h +++ b/src/core/qgssnappingconfig.h @@ -62,9 +62,8 @@ class CORE_EXPORT QgsSnappingConfig * @param type * @param tolerance * @param units - * @param avoidIntersection */ - IndividualLayerSettings( bool enabled, QgsSnappingConfig::SnappingType type, double tolerance, QgsTolerance::UnitType units, bool avoidIntersection = false ); + IndividualLayerSettings( bool enabled, QgsSnappingConfig::SnappingType type, double tolerance, QgsTolerance::UnitType units ); /** * Constructs an invalid setting @@ -98,12 +97,6 @@ class CORE_EXPORT QgsSnappingConfig //! set the type of units void setUnits( QgsTolerance::UnitType units ); - //! return if it shall avoid intersection (polygon layers only) - bool avoidIntersection() const; - - //! set if it shall avoid intersection (polygon layers only) - void setAvoidIntersection( bool avoidIntersection ); - /** * Compare this configuration to other. */ @@ -117,7 +110,6 @@ class CORE_EXPORT QgsSnappingConfig SnappingType mType; double mTolerance; QgsTolerance::UnitType mUnits; - bool mAvoidIntersection; }; /** From f60466819338e0494d8d0bb5a61474698951db81 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 18 Oct 2016 16:29:04 +0200 Subject: [PATCH 383/897] Remove QgsSnappingDialog --- src/app/CMakeLists.txt | 2 - src/app/qgisapp.cpp | 4 +- src/app/qgisapp.h | 1 - src/app/qgsprojectproperties.cpp | 1 - src/app/qgssnappingdialog.cpp | 517 ------------------------------- src/app/qgssnappingdialog.h | 116 ------- src/ui/qgssnappingdialogbase.ui | 312 ------------------- 7 files changed, 2 insertions(+), 951 deletions(-) delete mode 100644 src/app/qgssnappingdialog.cpp delete mode 100644 src/app/qgssnappingdialog.h delete mode 100644 src/ui/qgssnappingdialogbase.ui diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index c0a95ef9f0cf..cb6483891a5c 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -119,7 +119,6 @@ SET(QGIS_APP_SRCS qgsstatisticalsummarydockwidget.cpp qgssubstitutionlistwidget.cpp qgstextannotationdialog.cpp - qgssnappingdialog.cpp qgssvgannotationdialog.cpp qgsundowidget.cpp qgstipgui.cpp @@ -294,7 +293,6 @@ SET (QGIS_APP_MOC_HDRS qgsrelationmanagerdialog.h qgsrelationadddlg.h qgsselectbyformdialog.h - qgssnappingdialog.h qgssponsors.h qgsstatisticalsummarydockwidget.h qgssubstitutionlistwidget.h diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index f4d3092d6b5d..c075e4841247 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -215,7 +215,6 @@ #include "qgsselectbyformdialog.h" #include "qgsshortcutsmanager.h" #include "qgssinglebandgrayrenderer.h" -#include "qgssnappingdialog.h" #include "qgssnappingwidget.h" #include "qgssourceselectdialog.h" #include "qgssponsors.h" @@ -814,9 +813,10 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QString mainSnappingWidgetMode = QSettings().value( "/qgis/mainSnappingWidgetMode", "dialog" ).toString(); if ( mainSnappingWidgetMode == "dock" ) { - QgsSnappingDock* dock = new QgsSnappingDock( tr( "Snapping and Digitizing Options" ), QgisApp::instance() ); + QgsDockWidget* dock = new QgsDockWidget( tr( "Snapping and Digitizing Options" ), QgisApp::instance() ); dock->setAllowedAreas( Qt::AllDockWidgetAreas ); dock->setWidget( mSnappingDialogWidget ); + dock->setObjectName( "Snapping and Digitizing Options" ); addDockWidget( Qt::LeftDockWidgetArea, dock ); mSnappingDialogContainer = dock; dock->hide(); diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index e1dd8e889fdf..232dc43c65ae 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -92,7 +92,6 @@ class QAuthenticator; class QgsBrowserDockWidget; class QgsAdvancedDigitizingDockWidget; -class QgsSnappingDialog; class QgsGPSInformationWidget; class QgsStatisticalSummaryDockWidget; class QgsMapCanvasTracer; diff --git a/src/app/qgsprojectproperties.cpp b/src/app/qgsprojectproperties.cpp index 81ca3f6d8244..ec284d07854d 100644 --- a/src/app/qgsprojectproperties.cpp +++ b/src/app/qgsprojectproperties.cpp @@ -31,7 +31,6 @@ #include "qgsmaplayerregistry.h" #include "qgsproject.h" #include "qgsprojectlayergroupdialog.h" -#include "qgssnappingdialog.h" #include "qgsrasterlayer.h" #include "qgsvectorlayer.h" #include "qgsvectordataprovider.h" diff --git a/src/app/qgssnappingdialog.cpp b/src/app/qgssnappingdialog.cpp deleted file mode 100644 index 145a295698a9..000000000000 --- a/src/app/qgssnappingdialog.cpp +++ /dev/null @@ -1,517 +0,0 @@ -/*************************************************************************** - qgssnappingdialog.cpp - --------------------- - begin : June 11, 2007 - copyright : (C) 2007 by Marco Hugentobler - email : marco dot hugentobler at karto dot baug dot ethz dot ch - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgisapp.h" -#include "qgsdockwidget.h" -#include "qgslogger.h" -#include "qgsmapcanvas.h" -#include "qgsmaplayer.h" -#include "qgsmaplayerregistry.h" -#include "qgsproject.h" -#include "qgssnappingdialog.h" -#include "qgsvectorlayer.h" - - -#include -#include -#include -#include -#include -#include - - -QgsSnappingDialog::QgsSnappingDialog( QWidget* parent, QgsMapCanvas* canvas ) - : QDialog( parent ) - , mMapCanvas( canvas ) - , mDock( nullptr ) -{ - setupUi( this ); - - mDefaultSnapToComboBox->insertItem( 0, tr( "To vertex" ), "to vertex" ); - mDefaultSnapToComboBox->insertItem( 1, tr( "To segment" ), "to segment" ); - mDefaultSnapToComboBox->insertItem( 2, tr( "To vertex and segment" ), "to vertex and segment" ); - mDefaultSnapToComboBox->insertItem( 3, tr( "Off" ), "off" ); - - QSettings myQsettings; - bool myDockFlag = myQsettings.value( "/qgis/dockSnapping", false ).toBool(); - if ( myDockFlag ) - { - mDock = new QgsSnappingDock( tr( "Snapping and Digitizing Options" ), QgisApp::instance() ); - mDock->setAllowedAreas( Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea ); - mDock->setWidget( this ); - connect( this, SIGNAL( destroyed() ), mDock, SLOT( close() ) ); - QgisApp::instance()->addDockWidget( Qt::BottomDockWidgetArea, mDock ); - mButtonBox->setVisible( false ); - - connect( mSnapModeComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - connect( mDefaultSnapToComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - connect( mDefaultSnappingToleranceSpinBox, SIGNAL( valueChanged( double ) ), this, SLOT( apply() ) ); - connect( mDefaultSnappingToleranceComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - } - else - { - connect( mButtonBox, SIGNAL( accepted() ), this, SLOT( apply() ) ); - connect( mButtonBox->button( QDialogButtonBox::Apply ), SIGNAL( clicked() ), this, SLOT( apply() ) ); - } - connect( QgsMapLayerRegistry::instance(), SIGNAL( layersAdded( QList ) ), this, SLOT( addLayers( QList ) ) ); - connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( layersWillBeRemoved( QStringList ) ) ); - connect( mSnapModeComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( onSnappingModeIndexChanged( int ) ) ); - connect( cbxEnableTopologicalEditingCheckBox, SIGNAL( stateChanged( int ) ), this, SLOT( on_cbxEnableTopologicalEditingCheckBox_stateChanged( int ) ) ); - connect( cbxEnableIntersectionSnappingCheckBox, SIGNAL( stateChanged( int ) ), this, SLOT( on_cbxEnableIntersectionSnappingCheckBox_stateChanged( int ) ) ); - - reload(); - - QMap< QString, QgsMapLayer *> mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); - QMap< QString, QgsMapLayer *>::iterator it; - for ( it = mapLayers.begin(); it != mapLayers.end() ; ++it ) - { - addLayer( it.value() ); - } - - mLayerTreeWidget->setHeaderLabels( QStringList() << "" ); - mLayerTreeWidget->setSortingEnabled( true ); - - connect( QgsProject::instance(), SIGNAL( snapSettingsChanged() ), this, SLOT( reload() ) ); - connect( QgisApp::instance(), SIGNAL( newProject() ), this, SLOT( initNewProject() ) ); - connect( QgisApp::instance(), SIGNAL( projectRead() ), this, SLOT( reload() ) ); -} - -QgsSnappingDialog::QgsSnappingDialog() - : mMapCanvas( nullptr ) - , mDock( nullptr ) -{ -} - -QgsSnappingDialog::~QgsSnappingDialog() -{ -} - - -void QgsSnappingDialog::reload() -{ - setSnappingMode(); - - int idx; - QSettings settings; - QString snapType = settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); - snapType = QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType", snapType ); - if ( snapType == "to segment" ) - idx = 1; - else if ( snapType == "to vertex and segment" ) - idx = 2; - else if ( snapType == "to vertex" ) - idx = 0; - else // off - idx = 3; - mDefaultSnapToComboBox->blockSignals( true ); - mDefaultSnapToComboBox->setCurrentIndex( idx ); - mDefaultSnapToComboBox->blockSignals( false ); - - double tolerance = settings.value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); - tolerance = QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance", tolerance ); - mDefaultSnappingToleranceSpinBox->blockSignals( true ); - mDefaultSnappingToleranceSpinBox->setValue( tolerance ); - mDefaultSnappingToleranceSpinBox->blockSignals( false ); - - int unit = settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", QgsTolerance::ProjectUnits ).toInt(); - unit = QgsProject::instance()->readNumEntry( "Digitizing", "/DefaultSnapToleranceUnit", unit ); - mDefaultSnappingToleranceComboBox->blockSignals( true ); - mDefaultSnappingToleranceComboBox->setCurrentIndex( unit == QgsTolerance::Pixels ? 1 : 0 ); - mDefaultSnappingToleranceComboBox->blockSignals( false ); - - mLayerTreeWidget->clear(); - - QMap< QString, QgsMapLayer *> mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); - QMap< QString, QgsMapLayer *>::iterator it; - for ( it = mapLayers.begin(); it != mapLayers.end() ; ++it ) - { - addLayer( it.value() ); - } - - setTopologicalEditingState(); - setIntersectionSnappingState(); -} - -void QgsSnappingDialog::on_cbxEnableTopologicalEditingCheckBox_stateChanged( int state ) -{ - QgsProject::instance()->writeEntry( "Digitizing", "/TopologicalEditing", state == Qt::Checked ); - setTopologicalEditingState(); -} - -void QgsSnappingDialog::on_cbxEnableIntersectionSnappingCheckBox_stateChanged( int state ) -{ - QgsProject::instance()->writeEntry( "Digitizing", "/IntersectionSnapping", state == Qt::Checked ); -} - -void QgsSnappingDialog::onSnappingModeIndexChanged( int index ) -{ - if ( index == 0 || index == 1 ) - mStackedWidget->setCurrentIndex( 0 ); - else - mStackedWidget->setCurrentIndex( 1 ); -} - -void QgsSnappingDialog::initNewProject() -{ - QgsProject::instance()->writeEntry( "Digitizing", "/SnappingMode", QString( "current_layer" ) ); - - QSettings settings; - QString snapType = settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); - QgsProject::instance()->writeEntry( "Digitizing", "/DefaultSnapType", snapType ); - double tolerance = settings.value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); - QgsProject::instance()->writeEntry( "Digitizing", "/DefaultSnapTolerance", tolerance ); - int unit = settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", QgsTolerance::ProjectUnits ).toInt(); - QgsProject::instance()->writeEntry( "Digitizing", "/DefaultSnapToleranceUnit", unit ); - - reload(); - emitProjectSnapSettingsChanged(); -} - -void QgsSnappingDialog::closeEvent( QCloseEvent* event ) -{ - QDialog::closeEvent( event ); - - if ( !mDock ) - { - QSettings settings; - settings.setValue( "/Windows/BetterSnapping/geometry", saveGeometry() ); - } -} - -void QgsSnappingDialog::apply() -{ - QString snapMode; - switch ( mSnapModeComboBox->currentIndex() ) - { - case 0: - snapMode = "current_layer"; - break; - case 1: - snapMode = "all_layers"; - break; - default: - snapMode = "advanced"; - break; - } - QgsProject::instance()->writeEntry( "Digitizing", "/SnappingMode", snapMode ); - - QString snapType = mDefaultSnapToComboBox->currentData().toString(); - QgsProject::instance()->writeEntry( "Digitizing", "/DefaultSnapType", snapType ); - QgsProject::instance()->writeEntry( "Digitizing", "/DefaultSnapTolerance", mDefaultSnappingToleranceSpinBox->value() ); - QgsProject::instance()->writeEntry( "Digitizing", "/DefaultSnapToleranceUnit", mDefaultSnappingToleranceComboBox->currentIndex() == 1 ? QgsTolerance::Pixels : QgsTolerance::ProjectUnits ); - - - QStringList layerIdList; - QStringList snapToList; - QStringList toleranceList; - QStringList enabledList; - QStringList toleranceUnitList; - QStringList avoidIntersectionList; - - for ( int i = 0; i < mLayerTreeWidget->topLevelItemCount(); ++i ) - { - QTreeWidgetItem *currentItem = mLayerTreeWidget->topLevelItem( i ); - if ( !currentItem ) - { - continue; - } - - layerIdList << currentItem->data( 0, Qt::UserRole ).toString(); - enabledList << ( qobject_cast( mLayerTreeWidget->itemWidget( currentItem, 0 ) )->isChecked() ? "enabled" : "disabled" ); - - QString snapToItemText = qobject_cast( mLayerTreeWidget->itemWidget( currentItem, 2 ) )->currentText(); - if ( snapToItemText == tr( "to vertex" ) ) - { - snapToList << "to_vertex"; - } - else if ( snapToItemText == tr( "to segment" ) ) - { - snapToList << "to_segment"; - } - else //to vertex and segment - { - snapToList << "to_vertex_and_segment"; - } - - toleranceList << QString::number( qobject_cast( mLayerTreeWidget->itemWidget( currentItem, 3 ) )->value(), 'f' ); - toleranceUnitList << QString::number( qobject_cast( mLayerTreeWidget->itemWidget( currentItem, 4 ) )->currentIndex() ); - - QCheckBox *cbxAvoidIntersection = qobject_cast( mLayerTreeWidget->itemWidget( currentItem, 5 ) ); - if ( cbxAvoidIntersection && cbxAvoidIntersection->isChecked() ) - { - avoidIntersectionList << currentItem->data( 0, Qt::UserRole ).toString(); - } - } - - QgsProject::instance()->writeEntry( "Digitizing", "/LayerSnappingList", layerIdList ); - QgsProject::instance()->writeEntry( "Digitizing", "/LayerSnapToList", snapToList ); - QgsProject::instance()->writeEntry( "Digitizing", "/LayerSnappingToleranceList", toleranceList ); - QgsProject::instance()->writeEntry( "Digitizing", "/LayerSnappingToleranceUnitList", toleranceUnitList ); - QgsProject::instance()->writeEntry( "Digitizing", "/LayerSnappingEnabledList", enabledList ); - QgsProject::instance()->writeEntry( "Digitizing", "/AvoidIntersectionsList", avoidIntersectionList ); - - emitProjectSnapSettingsChanged(); -} - -void QgsSnappingDialog::emitProjectSnapSettingsChanged() -{ - disconnect( QgsProject::instance(), SIGNAL( snapSettingsChanged() ), this, SLOT( reload() ) ); - connect( this, SIGNAL( snapSettingsChanged() ), QgsProject::instance(), SIGNAL( snapSettingsChanged() ) ); - - emit snapSettingsChanged(); - - disconnect( this, SIGNAL( snapSettingsChanged() ), QgsProject::instance(), SIGNAL( snapSettingsChanged() ) ); - connect( QgsProject::instance(), SIGNAL( snapSettingsChanged() ), this, SLOT( reload() ) ); -} - -void QgsSnappingDialog::show() -{ - setTopologicalEditingState(); - setIntersectionSnappingState(); - if ( mDock ) - mDock->setVisible( true ); - else - QDialog::show(); - - mLayerTreeWidget->resizeColumnToContents( 0 ); - mLayerTreeWidget->resizeColumnToContents( 1 ); - mLayerTreeWidget->resizeColumnToContents( 2 ); - mLayerTreeWidget->resizeColumnToContents( 3 ); - mLayerTreeWidget->resizeColumnToContents( 4 ); -} - -void QgsSnappingDialog::addLayers( const QList& layers ) -{ - Q_FOREACH ( QgsMapLayer* layer, layers ) - { - addLayer( layer ); - } -} - -void QgsSnappingDialog::addLayer( QgsMapLayer *theMapLayer ) -{ - QgsVectorLayer *currentVectorLayer = qobject_cast( theMapLayer ); - if ( !currentVectorLayer || currentVectorLayer->geometryType() == QgsWkbTypes::NullGeometry ) - return; - - QSettings myQsettings; - bool myDockFlag = myQsettings.value( "/qgis/dockSnapping", false ).toBool(); - double defaultSnappingTolerance = myQsettings.value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); - int defaultSnappingUnit = myQsettings.value( "/qgis/digitizing/default_snapping_tolerance_unit", QgsTolerance::ProjectUnits ).toInt(); - QString defaultSnappingString = myQsettings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); - - int defaultSnappingStringIdx = 0; - if ( defaultSnappingString == "to vertex" ) - { - defaultSnappingStringIdx = 0; - } - else if ( defaultSnappingString == "to segment" ) - { - defaultSnappingStringIdx = 1; - } - else - { - // to vertex and segment - defaultSnappingStringIdx = 2; - } - - bool layerIdListOk, enabledListOk, toleranceListOk, toleranceUnitListOk, snapToListOk, avoidIntersectionListOk; - QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &layerIdListOk ); - QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &enabledListOk ); - QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), & toleranceListOk ); - QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &toleranceUnitListOk ); - QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &snapToListOk ); - QStringList avoidIntersectionsList = QgsProject::instance()->readListEntry( "Digitizing", "/AvoidIntersectionsList", QStringList(), &avoidIntersectionListOk ); - - //snap to layer yes/no - QTreeWidgetItem *item = new QTreeWidgetItem( mLayerTreeWidget ); - - QCheckBox *cbxEnable = new QCheckBox( mLayerTreeWidget ); - mLayerTreeWidget->setItemWidget( item, 0, cbxEnable ); - item->setData( 0, Qt::UserRole, currentVectorLayer->id() ); - item->setText( 1, currentVectorLayer->name() ); - - //snap to vertex/ snap to segment - QComboBox *cbxSnapTo = new QComboBox( mLayerTreeWidget ); - cbxSnapTo->insertItem( 0, tr( "to vertex" ) ); - cbxSnapTo->insertItem( 1, tr( "to segment" ) ); - cbxSnapTo->insertItem( 2, tr( "to vertex and segment" ) ); - cbxSnapTo->setCurrentIndex( defaultSnappingStringIdx ); - mLayerTreeWidget->setItemWidget( item, 2, cbxSnapTo ); - - //snapping tolerance - QDoubleSpinBox* sbTolerance = new QDoubleSpinBox( mLayerTreeWidget ); - sbTolerance->setRange( 0., 100000000. ); - sbTolerance->setDecimals( 5 ); - sbTolerance->setValue( defaultSnappingTolerance ); - - mLayerTreeWidget->setItemWidget( item, 3, sbTolerance ); - - //snap to vertex/ snap to segment - QComboBox *cbxUnits = new QComboBox( mLayerTreeWidget ); - cbxUnits->insertItem( 0, tr( "layer units" ) ); - cbxUnits->insertItem( 1, tr( "pixels" ) ); - cbxUnits->insertItem( 2, tr( "map units" ) ); - cbxUnits->setCurrentIndex( defaultSnappingUnit ); - mLayerTreeWidget->setItemWidget( item, 4, cbxUnits ); - - QCheckBox *cbxAvoidIntersection = nullptr; - if ( currentVectorLayer->geometryType() == QgsWkbTypes::PolygonGeometry ) - { - cbxAvoidIntersection = new QCheckBox( mLayerTreeWidget ); - mLayerTreeWidget->setItemWidget( item, 5, cbxAvoidIntersection ); - } - - //resize treewidget columns - for ( int i = 0 ; i < 4 ; ++i ) - { - mLayerTreeWidget->resizeColumnToContents( i ); - } - - int idx = layerIdList.indexOf( currentVectorLayer->id() ); - if ( idx < 0 ) - { - if ( myDockFlag ) - { - connect( cbxEnable, SIGNAL( stateChanged( int ) ), this, SLOT( apply() ) ); - connect( cbxSnapTo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - connect( sbTolerance, SIGNAL( valueChanged( double ) ), this, SLOT( apply() ) ); - connect( cbxUnits, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - - if ( cbxAvoidIntersection ) - { - connect( cbxAvoidIntersection, SIGNAL( stateChanged( int ) ), this, SLOT( apply() ) ); - } - setTopologicalEditingState(); - setIntersectionSnappingState(); - } - - cbxEnable->setChecked( defaultSnappingString != "off" ); - - // no settings for this layer yet - return; - } - - cbxEnable->setChecked( enabledList[ idx ] == "enabled" ); - - int snappingStringIdx = 0; - if ( snapToList[idx] == "to_vertex" ) - { - snappingStringIdx = 0; - } - else if ( snapToList[idx] == "to_segment" ) - { - snappingStringIdx = 1; - } - else //to vertex and segment - { - snappingStringIdx = 2; - } - - cbxSnapTo->setCurrentIndex( snappingStringIdx ); - sbTolerance->setValue( toleranceList[idx].toDouble() ); - cbxUnits->setCurrentIndex( toleranceUnitList[idx].toInt() ); - if ( cbxAvoidIntersection ) - { - cbxAvoidIntersection->setChecked( avoidIntersectionsList.contains( currentVectorLayer->id() ) ); - } - - if ( myDockFlag ) - { - connect( cbxEnable, SIGNAL( stateChanged( int ) ), this, SLOT( apply() ) ); - connect( cbxSnapTo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - connect( sbTolerance, SIGNAL( valueChanged( double ) ), this, SLOT( apply() ) ); - connect( cbxUnits, SIGNAL( currentIndexChanged( int ) ), this, SLOT( apply() ) ); - - if ( cbxAvoidIntersection ) - { - connect( cbxAvoidIntersection, SIGNAL( stateChanged( int ) ), this, SLOT( apply() ) ); - } - - setTopologicalEditingState(); - setIntersectionSnappingState(); - } -} - -void QgsSnappingDialog::layersWillBeRemoved( const QStringList& thelayers ) -{ - Q_FOREACH ( const QString& theLayerId, thelayers ) - { - QTreeWidgetItem *item = nullptr; - - for ( int i = 0; i < mLayerTreeWidget->topLevelItemCount(); ++i ) - { - item = mLayerTreeWidget->topLevelItem( i ); - if ( item && item->data( 0, Qt::UserRole ).toString() == theLayerId ) - break; - item = nullptr; - } - - if ( item ) - delete item; - } - apply(); -} - -void QgsSnappingDialog::setTopologicalEditingState() -{ - // read the digitizing settings - int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); - cbxEnableTopologicalEditingCheckBox->blockSignals( true ); - cbxEnableTopologicalEditingCheckBox->setChecked( topologicalEditing ); - cbxEnableTopologicalEditingCheckBox->blockSignals( false ); -} - -void QgsSnappingDialog::setIntersectionSnappingState() -{ - // read the digitizing settings - int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); - cbxEnableIntersectionSnappingCheckBox->blockSignals( true ); - cbxEnableIntersectionSnappingCheckBox->setChecked( intersectionSnapping ); - cbxEnableIntersectionSnappingCheckBox->blockSignals( false ); -} - -void QgsSnappingDialog::setSnappingMode() -{ - mSnapModeComboBox->blockSignals( true ); - QString snapMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode" ); - if ( snapMode == "current_layer" ) - mSnapModeComboBox->setCurrentIndex( 0 ); - else if ( snapMode == "all_layers" ) - mSnapModeComboBox->setCurrentIndex( 1 ); - else // "advanced" or empty (backward compatibility) - mSnapModeComboBox->setCurrentIndex( 2 ); - onSnappingModeIndexChanged( mSnapModeComboBox->currentIndex() ); - mSnapModeComboBox->blockSignals( false ); -} - - -// -// QgsSnappingDock -// - -QgsSnappingDock::QgsSnappingDock( const QString& title, QWidget* parent, Qt::WindowFlags flags ) - : QgsDockWidget( title, parent, flags ) -{ - setObjectName( "Snapping and Digitizing Options" ); // set object name so the position can be saved -} - -void QgsSnappingDock::closeEvent( QCloseEvent* e ) -{ - Q_UNUSED( e ); - // deleteLater(); -} diff --git a/src/app/qgssnappingdialog.h b/src/app/qgssnappingdialog.h deleted file mode 100644 index 17e8c6463231..000000000000 --- a/src/app/qgssnappingdialog.h +++ /dev/null @@ -1,116 +0,0 @@ -/*************************************************************************** - qgssnappingdialog.h - -------------------------- - begin : June 11, 2007 - copyright : (C) 2007 by Marco Hugentobler - email : marco dot hugentobler at karto dot baug dot ethz dot ch - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGSSNAPPINGDIALOG_H -#define QGSSNAPPINGDIALOG_H - -#include "qgsdockwidget.h" -#include "ui_qgssnappingdialogbase.h" - -class QgsMapCanvas; -class QgsMapLayer; - -/** A dialog to enter advanced editing properties, e.g. topological editing, snapping settings -for the individual layers*/ -class APP_EXPORT QgsSnappingDialog: public QDialog, private Ui::QgsSnappingDialogBase -{ - Q_OBJECT - - public: - - //! Returns the instance pointer, creating the object on the first call - //static QgsSnappingDialog * instance( QgsMapCanvas* canvas ); - QgsSnappingDialog( QWidget* parent, QgsMapCanvas* canvas ); - ~QgsSnappingDialog(); - - public slots: - //! apply the changes - void apply(); - - //! show dialog or dock - void show(); - - //! add layer to tree - void addLayer( QgsMapLayer* theMapLayer ); - - void addLayers( const QList& layers ); - - //! layers removed - void layersWillBeRemoved( const QStringList& ); - - void on_cbxEnableTopologicalEditingCheckBox_stateChanged( int ); - - void on_cbxEnableIntersectionSnappingCheckBox_stateChanged( int ); - - void onSnappingModeIndexChanged( int ); - - void initNewProject(); - - void emitProjectSnapSettingsChanged(); - - protected: - /** Constructor - * @param canvas pointer to the map canvas (for detecting which vector layers are loaded - */ - //QgsSnappingDialog( QgsMapCanvas* canvas ); - - /** - * Handle closing of the window - * @param event unused - */ - void closeEvent( QCloseEvent* event ) override; - - signals: - void snapSettingsChanged(); - - private slots: - void reload(); - - private: - /** Default constructor forbidden*/ - QgsSnappingDialog(); - - /** Stores ids of layers where intersections of new polygons is considered. Is passed to / read from QgsAvoidIntersectionsDialog*/ - QSet mAvoidIntersectionsSettings; - - /** Used to query the loaded layers*/ - QgsMapCanvas* mMapCanvas; - - QgsDockWidget *mDock; - - /** Set checkbox value based on project setting*/ - void setTopologicalEditingState(); - - /** Set checkbox value based on project setting*/ - void setIntersectionSnappingState(); - - void setSnappingMode(); -}; - - -class QgsSnappingDock : public QgsDockWidget -{ - Q_OBJECT - - public: - QgsSnappingDock( const QString & title, QWidget * parent = nullptr, Qt::WindowFlags flags = 0 ); - - virtual void closeEvent( QCloseEvent *e ) override; - -}; - -#endif diff --git a/src/ui/qgssnappingdialogbase.ui b/src/ui/qgssnappingdialogbase.ui deleted file mode 100644 index a982081805e1..000000000000 --- a/src/ui/qgssnappingdialogbase.ui +++ /dev/null @@ -1,312 +0,0 @@ - - - QgsSnappingDialogBase - - - - 0 - 0 - 798 - 290 - - - - Snapping options - - - - - - - - Layer selection - - - - - - - - 0 - 0 - - - - - Current layer - - - - - All visible layers - - - - - Advanced - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - 0 - - - - - 0 - - - - - - - Snap to - - - - - - - - - - Tolerance - - - - - - - 5 - - - 99999999.989999994635582 - - - - - - - - 0 - 0 - - - - - map units - - - - - pixels - - - - - - - - - - Qt::Horizontal - - - - 390 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 137 - - - - - - - - - - 0 - - - - - QAbstractItemView::NoSelection - - - 0 - - - false - - - - - - - AlignHCenter|AlignVCenter|AlignCenter - - - - - Layer - - - - - Mode - - - - - Tolerance - - - - - Units - - - - - Avoid intersections - - - Avoid intersections of new polygons - - - AlignLeft|AlignVCenter - - - - - - - - - - - - 3 - - - 0 - - - 3 - - - - - Enable topological editing - - - false - - - false - - - - - - - Enable snapping on intersection - - - false - - - false - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Apply|QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - mSnapModeComboBox - mDefaultSnapToComboBox - mDefaultSnappingToleranceSpinBox - mDefaultSnappingToleranceComboBox - mLayerTreeWidget - cbxEnableTopologicalEditingCheckBox - cbxEnableIntersectionSnappingCheckBox - mButtonBox - - - - - mButtonBox - accepted() - QgsSnappingDialogBase - accept() - - - 248 - 254 - - - 157 - 274 - - - - - mButtonBox - rejected() - QgsSnappingDialogBase - reject() - - - 316 - 260 - - - 286 - 274 - - - - - From bb23d6ebd0c5692ade36649f061c4db600c4c954 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 18 Oct 2016 16:56:33 +0200 Subject: [PATCH 384/897] Move snapping options to project menu --- src/app/qgisapp.cpp | 3 --- src/ui/qgisapp.ui | 6 +++--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index c075e4841247..fd2f7e85af90 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -17,9 +17,6 @@ * * ***************************************************************************/ -// -// QT4 includes make sure to use the new style! -// #include #include #include diff --git a/src/ui/qgisapp.ui b/src/ui/qgisapp.ui index 3e24abf62057..45fc44713f26 100644 --- a/src/ui/qgisapp.ui +++ b/src/ui/qgisapp.ui @@ -17,7 +17,7 @@ 0 0 1018 - 19 + 28 @@ -52,6 +52,7 @@ + @@ -229,7 +230,6 @@ - @@ -2169,7 +2169,7 @@ Acts on currently active editable layer true - + :/images/themes/default/mActionRotateFeature.png:/images/themes/default/mActionRotateFeature.png From 067e5905667b4fad16b8fd0333819a2038d9362f Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 19 Oct 2016 16:33:41 +0200 Subject: [PATCH 385/897] Update snapping settings widget when avoid intersection list changes --- src/app/qgssnappinglayertreemodel.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/app/qgssnappinglayertreemodel.cpp b/src/app/qgssnappinglayertreemodel.cpp index 337bc89f404c..0469ef3d0eaa 100644 --- a/src/app/qgssnappinglayertreemodel.cpp +++ b/src/app/qgssnappinglayertreemodel.cpp @@ -143,6 +143,7 @@ QgsSnappingLayerTreeModel::QgsSnappingLayerTreeModel( QgsProject* project, QObje , mIndividualLayerSettings( project->snappingConfig().individualLayerSettings() ) { connect( project, &QgsProject::snappingConfigChanged, this, &QgsSnappingLayerTreeModel::onSnappingSettingsChanged ); + connect( project, &QgsProject::avoidIntersectionsListChanged, this, &QgsSnappingLayerTreeModel::onSnappingSettingsChanged ); } QgsSnappingLayerTreeModel::~QgsSnappingLayerTreeModel() From 0f93fb0bc0d2466ab29d55953a52a42ef093b60b Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 19 Oct 2016 10:12:04 +0200 Subject: [PATCH 386/897] Q_PROPERTYze QgsCoordinateReferenceSystem::unitType --- src/core/qgscoordinatereferencesystem.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/qgscoordinatereferencesystem.h b/src/core/qgscoordinatereferencesystem.h index 3695fe2c80b0..954c052f3bde 100644 --- a/src/core/qgscoordinatereferencesystem.h +++ b/src/core/qgscoordinatereferencesystem.h @@ -186,6 +186,8 @@ class CORE_EXPORT QgsCoordinateReferenceSystem { Q_GADGET + Q_PROPERTY( QgsUnitTypes::DistanceUnit mapUnits READ mapUnits ) + public: //! Enumeration of types of IDs accepted in createFromId() method From 58be4fc8996538588183504e84e3592088349fc1 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 19 Oct 2016 15:36:43 +0200 Subject: [PATCH 387/897] Rename visibility presets to map themes part 2 --- src/core/qgsproject.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index c96afaab8e2c..743cd805836b 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -81,6 +81,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) Q_PROPERTY( QgsSnappingConfig snappingConfig READ snappingConfig WRITE setSnappingConfig NOTIFY snappingConfigChanged ) Q_PROPERTY( QStringList avoidIntersectionsList READ avoidIntersectionsList WRITE setAvoidIntersectionsList NOTIFY avoidIntersectionsListChanged ) + Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) public: From 3e83fafc42212d35f9fa26a2469e7cdb9688adfc Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 20 Oct 2016 12:49:02 +0200 Subject: [PATCH 388/897] Expose QgsUnitTypes to QML --- src/core/CMakeLists.txt | 2 +- src/core/qgsunittypes.h | 42 +++++++++++++++++++++-------------------- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 293756e20060..a7c74d7af9ec 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -488,6 +488,7 @@ SET(QGIS_CORE_MOC_HDRS qgstracer.h qgstransaction.h qgstransactiongroup.h + qgsunittypes.h qgsvectordataprovider.h qgsvectorlayercache.h qgsvectorlayereditbuffer.h @@ -705,7 +706,6 @@ SET(QGIS_CORE_HDRS qgstextlabelfeature.h qgstolerance.h qgstracer.h - qgsunittypes.h qgsvectordataprovider.h qgsvectorlayercache.h diff --git a/src/core/qgsunittypes.h b/src/core/qgsunittypes.h index fbb6aebabb18..05bccab2dff2 100644 --- a/src/core/qgsunittypes.h +++ b/src/core/qgsunittypes.h @@ -34,6 +34,8 @@ class CORE_EXPORT QgsUnitTypes { + Q_GADGET + public: //! Units of distance @@ -102,14 +104,14 @@ class CORE_EXPORT QgsUnitTypes /** Returns the type for a distance unit. */ - static DistanceUnitType unitType( DistanceUnit unit ); + Q_INVOKABLE static DistanceUnitType unitType( DistanceUnit unit ); /** Encodes a distance unit to a string. * @param unit unit to encode * @returns encoded string * @see decodeDistanceUnit() */ - static QString encodeUnit( QgsUnitTypes::DistanceUnit unit ); + Q_INVOKABLE static QString encodeUnit( QgsUnitTypes::DistanceUnit unit ); /** Decodes a distance unit from a string. * @param string string to decode @@ -117,40 +119,40 @@ class CORE_EXPORT QgsUnitTypes * @returns decoded units * @see encodeUnit() */ - static QgsUnitTypes::DistanceUnit decodeDistanceUnit( const QString& string, bool *ok = 0 ); + Q_INVOKABLE static QgsUnitTypes::DistanceUnit decodeDistanceUnit( const QString& string, bool *ok = 0 ); /** Returns a translated string representing a distance unit. * @param unit unit to convert to string * @see stringToDistanceUnit() */ - static QString toString( QgsUnitTypes::DistanceUnit unit ); + Q_INVOKABLE static QString toString( QgsUnitTypes::DistanceUnit unit ); /** Converts a translated string to a distance unit. * @param string string representing a distance unit * @param ok optional boolean, will be set to true if string was converted successfully * @see toString() */ - static QgsUnitTypes::DistanceUnit stringToDistanceUnit( const QString& string, bool *ok = 0 ); + Q_INVOKABLE static QgsUnitTypes::DistanceUnit stringToDistanceUnit( const QString& string, bool *ok = 0 ); /** Returns the conversion factor between the specified distance units. * @param fromUnit distance unit to convert from * @param toUnit distance unit to convert to * @returns multiplication factor to convert between units */ - static double fromUnitToUnitFactor( QgsUnitTypes::DistanceUnit fromUnit, QgsUnitTypes::DistanceUnit toUnit ); + Q_INVOKABLE static double fromUnitToUnitFactor( QgsUnitTypes::DistanceUnit fromUnit, QgsUnitTypes::DistanceUnit toUnit ); // AREAL UNITS /** Returns the type for an areal unit. */ - static DistanceUnitType unitType( AreaUnit unit ); + Q_INVOKABLE static DistanceUnitType unitType( AreaUnit unit ); /** Encodes an areal unit to a string. * @param unit unit to encode * @returns encoded string * @see decodeAreaUnit() */ - static QString encodeUnit( AreaUnit unit ); + Q_INVOKABLE static QString encodeUnit( AreaUnit unit ); /** Decodes an areal unit from a string. * @param string string to decode @@ -158,33 +160,33 @@ class CORE_EXPORT QgsUnitTypes * @returns decoded units * @see encodeUnit() */ - static AreaUnit decodeAreaUnit( const QString& string, bool *ok = 0 ); + Q_INVOKABLE static AreaUnit decodeAreaUnit( const QString& string, bool *ok = 0 ); /** Returns a translated string representing an areal unit. * @param unit unit to convert to string * @see stringToAreaUnit() */ - static QString toString( AreaUnit unit ); + Q_INVOKABLE static QString toString( AreaUnit unit ); /** Converts a translated string to an areal unit. * @param string string representing an areal unit * @param ok optional boolean, will be set to true if string was converted successfully * @see toString() */ - static AreaUnit stringToAreaUnit( const QString& string, bool *ok = 0 ); + Q_INVOKABLE static AreaUnit stringToAreaUnit( const QString& string, bool *ok = 0 ); /** Returns the conversion factor between the specified areal units. * @param fromUnit area unit to convert from * @param toUnit area unit to convert to * @returns multiplication factor to convert between units */ - static double fromUnitToUnitFactor( AreaUnit fromUnit, AreaUnit toUnit ); + Q_INVOKABLE static double fromUnitToUnitFactor( AreaUnit fromUnit, AreaUnit toUnit ); /** Converts a distance unit to its corresponding area unit, eg meters to square meters * @param distanceUnit distance unit to convert * @return matching areal unit */ - static AreaUnit distanceToAreaUnit( QgsUnitTypes::DistanceUnit distanceUnit ); + Q_INVOKABLE static AreaUnit distanceToAreaUnit( QgsUnitTypes::DistanceUnit distanceUnit ); // ANGULAR UNITS @@ -193,7 +195,7 @@ class CORE_EXPORT QgsUnitTypes * @returns encoded string * @see decodeAngleUnit() */ - static QString encodeUnit( AngleUnit unit ); + Q_INVOKABLE static QString encodeUnit( AngleUnit unit ); /** Decodes an angular unit from a string. * @param string string to decode @@ -201,19 +203,19 @@ class CORE_EXPORT QgsUnitTypes * @returns decoded units * @see encodeUnit() */ - static AngleUnit decodeAngleUnit( const QString& string, bool *ok = 0 ); + Q_INVOKABLE static AngleUnit decodeAngleUnit( const QString& string, bool *ok = 0 ); /** Returns a translated string representing an angular unit. * @param unit unit to convert to string */ - static QString toString( AngleUnit unit ); + Q_INVOKABLE static QString toString( AngleUnit unit ); /** Returns the conversion factor between the specified angular units. * @param fromUnit angle unit to convert from * @param toUnit angle unit to convert to * @returns multiplication factor to convert between units */ - static double fromUnitToUnitFactor( AngleUnit fromUnit, AngleUnit toUnit ); + Q_INVOKABLE static double fromUnitToUnitFactor( AngleUnit fromUnit, AngleUnit toUnit ); /** Returns an angle formatted as a friendly string. * @param angle angle to format @@ -221,7 +223,7 @@ class CORE_EXPORT QgsUnitTypes * @param unit unit of angle * @returns formatted angle string */ - static QString formatAngle( double angle, int decimals, AngleUnit unit ); + Q_INVOKABLE static QString formatAngle( double angle, int decimals, AngleUnit unit ); // RENDER UNITS @@ -230,7 +232,7 @@ class CORE_EXPORT QgsUnitTypes * @returns encoded string * @see decodeRenderUnit() */ - static QString encodeUnit( RenderUnit unit ); + Q_INVOKABLE static QString encodeUnit( RenderUnit unit ); /** Decodes a render unit from a string. * @param string string to decode @@ -238,7 +240,7 @@ class CORE_EXPORT QgsUnitTypes * @returns decoded units * @see encodeUnit() */ - static RenderUnit decodeRenderUnit( const QString& string, bool *ok = 0 ); + Q_INVOKABLE static RenderUnit decodeRenderUnit( const QString& string, bool *ok = 0 ); }; From 9bab3fa305757e4628149e87f77f958bc5d91db8 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 20 Oct 2016 14:05:30 +0200 Subject: [PATCH 389/897] Fix build warning --- src/core/qgsproject.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index 743cd805836b..c96afaab8e2c 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -81,7 +81,6 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) Q_PROPERTY( QgsSnappingConfig snappingConfig READ snappingConfig WRITE setSnappingConfig NOTIFY snappingConfigChanged ) Q_PROPERTY( QStringList avoidIntersectionsList READ avoidIntersectionsList WRITE setAvoidIntersectionsList NOTIFY avoidIntersectionsListChanged ) - Q_PROPERTY( QgsMapThemeCollection* mapThemeCollection READ mapThemeCollection ) public: From fba53db7857b014498a2c6ae1f7040ed9e7af03b Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 20 Oct 2016 14:55:18 +0200 Subject: [PATCH 390/897] Followup a6a4f2ed: clean pre-cxx-11 garbage --- CMakeLists.txt | 10 ---------- src/core/qgsexpressioncontext.cpp | 2 -- src/core/qgsexpressioncontext.h | 2 -- 3 files changed, 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a3e9379e1a2a..76ef19d1c0a2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -347,16 +347,6 @@ FIND_PROGRAM(QT_LRELEASE_EXECUTABLE # https://gist.github.com/yamaya/2924292 SET(CMAKE_CXX_STANDARD 11) -SET(USE_CXX_11 TRUE) - -#allow override keyword if available -IF(NOT USE_CXX_11) - ADD_DEFINITIONS("-Doverride=") - ADD_DEFINITIONS("-Dnoexcept=") - ADD_DEFINITIONS("-Dnullptr=0") -ELSE() - ADD_DEFINITIONS("-DHAS_MOVE_SEMANTICS") -ENDIF() ############################################################# # enable warnings diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index f808727ee7eb..20b9f7a88fea 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -219,7 +219,6 @@ QgsExpressionContext::QgsExpressionContext( const QgsExpressionContext& other ) mCachedValues = other.mCachedValues; } -#ifdef HAS_MOVE_SEMANTICS QgsExpressionContext& QgsExpressionContext::operator=( QgsExpressionContext && other ) { if ( this != &other ) @@ -234,7 +233,6 @@ QgsExpressionContext& QgsExpressionContext::operator=( QgsExpressionContext && o } return *this; } -#endif QgsExpressionContext& QgsExpressionContext::operator=( const QgsExpressionContext & other ) { diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index 620f74b1b441..463bd15dce6c 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -264,9 +264,7 @@ class CORE_EXPORT QgsExpressionContext QgsExpressionContext& operator=( const QgsExpressionContext& other ); -#ifdef HAS_MOVE_SEMANTICS QgsExpressionContext& operator=( QgsExpressionContext && other ); -#endif ~QgsExpressionContext(); From 2013984297e2983f4475310d2b7a45bce21b2a1c Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Thu, 20 Oct 2016 18:16:37 +0200 Subject: [PATCH 391/897] fix translation strings --- python/plugins/processing/algs/qgis/ReliefAuto.py | 4 ++-- resources/function_help/json/array_insert | 2 +- resources/function_help/json/array_remove_at | 2 +- resources/function_help/json/map_concat | 2 +- src/plugins/grass/modules/r.unpack.qgm | 2 +- src/plugins/grass/modules/v.class.mlpy.qgis.qgm | 2 +- src/plugins/grass/modules/v.unpack.qgm | 2 +- src/plugins/grass/scripts/v.class.mlpy.qgis.py | 2 +- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/python/plugins/processing/algs/qgis/ReliefAuto.py b/python/plugins/processing/algs/qgis/ReliefAuto.py index 06782d9242d9..76575a9d6d44 100644 --- a/python/plugins/processing/algs/qgis/ReliefAuto.py +++ b/python/plugins/processing/algs/qgis/ReliefAuto.py @@ -60,9 +60,9 @@ def defineCharacteristics(self): self.addParameter(ParameterNumber(self.Z_FACTOR, self.tr('Z factor'), 1.0, 999999.99, 1.0)) self.addOutput(OutputRaster(self.OUTPUT_LAYER, - self.tr('Refilef'))) + self.tr('Relief'))) self.addOutput(OutputTable(self.FREQUENCY_DISTRIBUTION, - self.tr('Frequesncy distribution'))) + self.tr('Frequency distribution'))) def processAlgorithm(self, progress): inputFile = self.getParameterValue(self.INPUT_LAYER) diff --git a/resources/function_help/json/array_insert b/resources/function_help/json/array_insert index 4b3904a6c59f..dab0f495ccae 100644 --- a/resources/function_help/json/array_insert +++ b/resources/function_help/json/array_insert @@ -3,7 +3,7 @@ "type": "function", "description": "Returns an array with the given value added at the given position.", "arguments": [ {"arg":"array","description":"an array"}, - {"arg":"pos","description":"the position where to add (0 based"}, + {"arg":"pos","description":"the position where to add (0 based)"}, {"arg":"value","description":"the value to add"}], "examples": [ { "expression":"array_insert(array(1,2,3),1,100)", "returns":"array: 1,100,2,3"}] } diff --git a/resources/function_help/json/array_remove_at b/resources/function_help/json/array_remove_at index 3bd54e1e320f..191af42c47e7 100644 --- a/resources/function_help/json/array_remove_at +++ b/resources/function_help/json/array_remove_at @@ -3,6 +3,6 @@ "type": "function", "description": "Returns an array with the given index removed.", "arguments": [ {"arg":"array","description":"an array"}, - {"arg":"pos","description":"the position to remove (0 based"}], + {"arg":"pos","description":"the position to remove (0 based)"}], "examples": [ { "expression":"array_remove_at(array(1,2,3),1)", "returns":"array: 1,3"}] } diff --git a/resources/function_help/json/map_concat b/resources/function_help/json/map_concat index 429367f2d526..514e51d643d5 100644 --- a/resources/function_help/json/map_concat +++ b/resources/function_help/json/map_concat @@ -1,7 +1,7 @@ { "name": "map_concat", "type": "function", - "description": "Returns a map containing all the entries of the given map. If two maps contain the same key, the value of the second map is taken.", + "description": "Returns a map containing all the entries of the given maps. If two maps contain the same key, the value of the second map is taken.", "variableLenArguments": true, "arguments": [ {"arg":"map1", "syntaxOnly": true}, diff --git a/src/plugins/grass/modules/r.unpack.qgm b/src/plugins/grass/modules/r.unpack.qgm index 0f90dfebb30b..d510a0200aad 100644 --- a/src/plugins/grass/modules/r.unpack.qgm +++ b/src/plugins/grass/modules/r.unpack.qgm @@ -1,7 +1,7 @@ - + + + + + Show partials labels + + + @@ -334,7 +327,6 @@ chkShowPartialsLabels chkShowAllLabels chkShowCandidates - mShadowDebugRectChkBox buttonBox From 5495f205894ed6e9d6ec06458bf6bd7a970571b8 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 27 Sep 2016 15:01:46 +1000 Subject: [PATCH 444/897] Minor refactor of label drawing Remove use of scale factors from PAL layer settings and use render context factors directly --- python/core/qgspallabeling.sip | 10 ++----- src/app/qgslabelpreview.cpp | 4 +-- src/core/qgspallabeling.cpp | 38 +++++++++--------------- src/core/qgspallabeling.h | 10 ++----- src/core/qgsvectorlayerlabelprovider.cpp | 12 +++----- 5 files changed, 25 insertions(+), 49 deletions(-) diff --git a/python/core/qgspallabeling.sip b/python/core/qgspallabeling.sip index f71e10556315..f9e1de595900 100644 --- a/python/core/qgspallabeling.sip +++ b/python/core/qgspallabeling.sip @@ -515,10 +515,6 @@ class QgsPalLayerSettings //! Z-Index of label, where labels with a higher z-index are rendered on top of labels with a lower z-index double zIndex; - //-- scale factors - double vectorScaleFactor; //scale factor painter units->pixels - double rasterCompressFactor; //pixel resolution scale factor - // called from register feature hook void calculateLabelSize( const QFontMetricsF* fm, QString text, double& labelX, double& labelY, QgsFeature* f = 0, QgsRenderContext* context = 0 ); @@ -836,15 +832,15 @@ class QgsPalLabeling : QgsLabelingEngineInterface static void drawLabelBuffer( QgsRenderContext& context, const QgsLabelComponent &component, - const QgsPalLayerSettings& tmpLyr ); + const QgsTextFormat& format ); static void drawLabelBackground( QgsRenderContext& context, QgsLabelComponent component, - const QgsPalLayerSettings& tmpLyr ); + const QgsTextFormat& format ); static void drawLabelShadow( QgsRenderContext &context, const QgsLabelComponent &component, - const QgsPalLayerSettings& tmpLyr ); + const QgsTextFormat& format ); //! load/save engine settings to project file void loadEngineSettings(); diff --git a/src/app/qgslabelpreview.cpp b/src/app/qgslabelpreview.cpp index a3e64ab52d1f..0ab89700e9b5 100644 --- a/src/app/qgslabelpreview.cpp +++ b/src/app/qgslabelpreview.cpp @@ -75,9 +75,7 @@ void QgsLabelPreview::paintEvent( QPaintEvent *e ) mContext.setPainter( &p ); QgsLabelComponent component; component.setText( text() ); - QgsPalLayerSettings tmpLyr; - tmpLyr.setFormat( mFormat ); - QgsPalLabeling::drawLabelBuffer( mContext, component, tmpLyr ); + QgsPalLabeling::drawLabelBuffer( mContext, component, mFormat ); } QPainterPath path; diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index ec40661688d2..004595facbe3 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -175,10 +175,6 @@ QgsPalLayerSettings::QgsPalLayerSettings() obstacleType = PolygonInterior; zIndex = 0.0; - // scale factors - vectorScaleFactor = 1.0; - rasterCompressFactor = 1.0; - // data defined string and old-style index values // NOTE: in QPair use -1 for second value (other values are for old-style layer properties migration) @@ -390,9 +386,6 @@ QgsPalLayerSettings& QgsPalLayerSettings::operator=( const QgsPalLayerSettings & } mDataDefinedNames = s.mDataDefinedNames; - // scale factors - vectorScaleFactor = s.vectorScaleFactor; - rasterCompressFactor = s.rasterCompressFactor; return *this; } @@ -1431,7 +1424,7 @@ void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString t double labelHeight = fm->ascent() + fm->descent(); // ignore +1 for baseline h += fm->height() + static_cast< double >(( lines - 1 ) * labelHeight * multilineH ); - h /= rasterCompressFactor; + h /= context->rasterScaleFactor(); for ( int i = 0; i < lines; ++i ) { @@ -1441,7 +1434,7 @@ void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString t w = width; } } - w /= rasterCompressFactor; + w /= context->rasterScaleFactor(); #if 0 // XXX strk QgsPoint ptSize = xform->toMapCoordinatesF( w, h ); @@ -2252,7 +2245,7 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont double topMargin = qMax( 0.25 * labelFontMetrics->ascent(), 0.0 ); double bottomMargin = 1.0 + labelFontMetrics->descent(); QgsLabelFeature::VisualMargin vm( topMargin, 0.0, bottomMargin, 0.0 ); - vm *= xform->mapUnitsPerPixel() / rasterCompressFactor; + vm *= xform->mapUnitsPerPixel() / context.rasterScaleFactor(); ( *labelFeature )->setVisualMargin( vm ); // store the label's calculated font for later use during painting @@ -2262,7 +2255,7 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont // TODO: only for placement which needs character info // account for any data defined font metrics adjustments lf->calculateInfo( placement == QgsPalLayerSettings::Curved || placement == QgsPalLayerSettings::PerimeterCurved, - labelFontMetrics.data(), xform, rasterCompressFactor, maxcharanglein, maxcharangleout ); + labelFontMetrics.data(), xform, context.rasterScaleFactor(), maxcharanglein, maxcharangleout ); // for labelFeature the LabelInfo is passed to feat when it is registered // TODO: allow layer-wide feature dist in PAL...? @@ -2297,7 +2290,7 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont } else //mm { - distance *= vectorScaleFactor; + distance *= context.scaleFactor(); } // when using certain placement modes, we force a tiny minimum distance. This ensures that @@ -4082,11 +4075,10 @@ void QgsPalLabeling::drawLabelCandidateRect( pal::LabelPosition* lp, QPainter* p void QgsPalLabeling::drawLabelBuffer( QgsRenderContext& context, const QgsLabelComponent& component, - const QgsPalLayerSettings& tmpLyr ) + const QgsTextFormat& format ) { QPainter* p = context.painter(); - QgsTextFormat format = tmpLyr.format(); QgsTextBufferSettings buffer = format.buffer(); double penSize = QgsTextRenderer::scaleToPixelContext( buffer.size(), context, @@ -4120,7 +4112,7 @@ void QgsPalLabeling::drawLabelBuffer( QgsRenderContext& context, bufferComponent.setOrigin( QgsPoint( 0.0, 0.0 ) ); bufferComponent.setPicture( &buffPict ); bufferComponent.setPictureBuffer( penSize / 2.0 ); - drawLabelShadow( context, bufferComponent, tmpLyr ); + drawLabelShadow( context, bufferComponent, format ); } p->save(); @@ -4141,9 +4133,8 @@ void QgsPalLabeling::drawLabelBuffer( QgsRenderContext& context, void QgsPalLabeling::drawLabelBackground( QgsRenderContext& context, QgsLabelComponent component, - const QgsPalLayerSettings& tmpLyr ) + const QgsTextFormat& format ) { - QgsTextFormat format = tmpLyr.format(); QgsTextBackgroundSettings background = format.background(); QPainter* p = context.painter(); @@ -4274,7 +4265,7 @@ void QgsPalLabeling::drawLabelBackground( QgsRenderContext& context, p->rotate( component.rotationOffset() ); p->translate( -svgSize / 2, svgSize / 2 ); - drawLabelShadow( context, component, tmpLyr ); + drawLabelShadow( context, component, format ); p->restore(); delete svgShdwM; @@ -4415,7 +4406,7 @@ void QgsPalLabeling::drawLabelBackground( QgsRenderContext& context, component.setSize( QgsPoint( rect.width(), rect.height() ) ); component.setOffset( QgsPoint( rect.width() / 2, -rect.height() / 2 ) ); - drawLabelShadow( context, component, tmpLyr ); + drawLabelShadow( context, component, format ); } p->setOpacity( background.opacity() ); @@ -4434,15 +4425,14 @@ void QgsPalLabeling::drawLabelBackground( QgsRenderContext& context, void QgsPalLabeling::drawLabelShadow( QgsRenderContext& context, const QgsLabelComponent& component, - const QgsPalLayerSettings& tmpLyr ) + const QgsTextFormat& format ) { + QgsTextShadowSettings shadow = format.shadow(); + // incoming component sizes should be multiplied by rasterCompressFactor, as // this allows shadows to be created at paint device dpi (e.g. high resolution), // then scale device painter by 1.0 / rasterCompressFactor for output - QgsTextFormat format = tmpLyr.format(); - QgsTextShadowSettings shadow = format.shadow(); - QPainter* p = context.painter(); double componentWidth = component.size().x(), componentHeight = component.size().y(); double xOffset = component.offset().x(), yOffset = component.offset().y(); @@ -4451,7 +4441,7 @@ void QgsPalLabeling::drawLabelShadow( QgsRenderContext& context, // generate pixmap representation of label component drawing bool mapUnits = shadow.blurRadiusUnit() == QgsUnitTypes::RenderMapUnits; double radius = QgsTextRenderer::scaleToPixelContext( shadow.blurRadius(), context, shadow.blurRadiusUnit(), !mapUnits, shadow.blurRadiusMapUnitScale() ); - radius /= ( mapUnits ? tmpLyr.vectorScaleFactor / component.dpiRatio() : 1 ); + radius /= ( mapUnits ? context.scaleFactor() / component.dpiRatio() : 1 ); radius = static_cast< int >( radius + 0.5 ); // TODO: add labeling gui option to adjust blurBufferClippingScale to minimize pixels, or diff --git a/src/core/qgspallabeling.h b/src/core/qgspallabeling.h index aadbaf399cdd..5d08fc74ccd3 100644 --- a/src/core/qgspallabeling.h +++ b/src/core/qgspallabeling.h @@ -535,10 +535,6 @@ class CORE_EXPORT QgsPalLayerSettings //! Z-Index of label, where labels with a higher z-index are rendered on top of labels with a lower z-index double zIndex; - //-- scale factors - double vectorScaleFactor; //scale factor painter units->pixels - double rasterCompressFactor; //pixel resolution scale factor - // called from register feature hook void calculateLabelSize( const QFontMetricsF* fm, QString text, double& labelX, double& labelY, QgsFeature* f = nullptr, QgsRenderContext* context = nullptr ); @@ -961,15 +957,15 @@ class CORE_EXPORT QgsPalLabeling : public QgsLabelingEngineInterface static void drawLabelBuffer( QgsRenderContext& context, const QgsLabelComponent &component, - const QgsPalLayerSettings& tmpLyr ); + const QgsTextFormat& format ); static void drawLabelBackground( QgsRenderContext& context, QgsLabelComponent component, - const QgsPalLayerSettings& tmpLyr ); + const QgsTextFormat& format ); static void drawLabelShadow( QgsRenderContext &context, const QgsLabelComponent &component, - const QgsPalLayerSettings& tmpLyr ); + const QgsTextFormat& format ); //! load/save engine settings to project file void loadEngineSettings(); diff --git a/src/core/qgsvectorlayerlabelprovider.cpp b/src/core/qgsvectorlayerlabelprovider.cpp index fcaf07e4d453..b78d0686a397 100644 --- a/src/core/qgsvectorlayerlabelprovider.cpp +++ b/src/core/qgsvectorlayerlabelprovider.cpp @@ -213,10 +213,6 @@ bool QgsVectorLayerLabelProvider::prepare( const QgsRenderContext& context, QSet // TODO: ideally these (non-configuration) members should get out of QgsPalLayerSettings to here // (together with registerFeature() & related methods) and QgsPalLayerSettings just stores config - //raster and vector scale factors - lyr.vectorScaleFactor = context.scaleFactor(); - lyr.rasterCompressFactor = context.rasterScaleFactor(); - // save the pal layer to our layer context (with some additional info) lyr.fieldIndex = mFields.lookupField( lyr.fieldName ); @@ -575,7 +571,7 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q component.setCenter( centerPt ); component.setSize( QgsPoint( label->getWidth(), label->getHeight() ) ); - QgsPalLabeling::drawLabelBackground( context, component, tmpLyr ); + QgsPalLabeling::drawLabelBackground( context, component, tmpLyr.format() ); } else if ( drawType == QgsPalLabeling::LabelBuffer @@ -689,7 +685,7 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q // scale down painter: the font size has been multiplied by raster scale factor // to workaround a Qt font scaling bug with small font sizes - painter->scale( 1.0 / tmpLyr.rasterCompressFactor, 1.0 / tmpLyr.rasterCompressFactor ); + painter->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); // figure x offset for horizontal alignment of multiple lines double xMultiLineOffset = 0.0; @@ -717,7 +713,7 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q if ( drawType == QgsPalLabeling::LabelBuffer ) { // draw label's buffer - QgsPalLabeling::drawLabelBuffer( context, component, tmpLyr ); + QgsPalLabeling::drawLabelBuffer( context, component, tmpLyr.format() ); } else { @@ -746,7 +742,7 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q component.setPictureBuffer( 0.0 ); // no pen width to deal with component.setOrigin( QgsPoint( 0.0, 0.0 ) ); - QgsPalLabeling::drawLabelShadow( context, component, tmpLyr ); + QgsPalLabeling::drawLabelShadow( context, component, tmpLyr.format() ); } // paint the text From 074ae4219d07635226cc8622176e3ee4ca8bf6ae Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 27 Sep 2016 15:49:52 +1000 Subject: [PATCH 445/897] Restore separate handling of label component opacity ...in a way that avoids unnecessary detachments of the settings objects --- src/core/qgspallabeling.cpp | 8 +-- src/core/qgstextrenderer.cpp | 65 ++++++++++++------------ src/core/qgstextrenderer_p.h | 12 +++++ src/core/qgsvectorlayerlabelprovider.cpp | 8 ++- 4 files changed, 56 insertions(+), 37 deletions(-) diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index 004595facbe3..6f3bdd944a6b 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -4087,10 +4087,12 @@ void QgsPalLabeling::drawLabelBuffer( QgsRenderContext& context, QPainterPath path; path.setFillRule( Qt::WindingFill ); path.addText( 0, 0, format.scaledFont( context ), component.text() ); - QPen pen( buffer.color() ); + QColor bufferColor = buffer.color(); + bufferColor.setAlphaF( buffer.opacity() ); + QPen pen( bufferColor ); pen.setWidthF( penSize ); pen.setJoinStyle( buffer.joinStyle() ); - QColor tmpColor( buffer.color() ); + QColor tmpColor( bufferColor ); // honor pref for whether to fill buffer interior if ( !buffer.fillBufferInterior() ) { @@ -4240,7 +4242,7 @@ void QgsPalLabeling::drawLabelBackground( QgsRenderContext& context, QgsSymbolLayer* symShdwL = QgsSvgMarkerSymbolLayer::create( shdwmap ); QgsSvgMarkerSymbolLayer* svgShdwM = static_cast( symShdwL ); - QgsSymbolRenderContext svgShdwContext( shdwContext, QgsUnitTypes::RenderUnknownUnit, shadow.opacity() ); + QgsSymbolRenderContext svgShdwContext( shdwContext, QgsUnitTypes::RenderUnknownUnit, background.opacity() ); double svgSize = QgsTextRenderer::scaleToPixelContext( sizeOut, context, background.sizeUnit(), true, background.sizeMapUnitScale() ); diff --git a/src/core/qgstextrenderer.cpp b/src/core/qgstextrenderer.cpp index e8557bd62ae9..2440b50d418c 100644 --- a/src/core/qgstextrenderer.cpp +++ b/src/core/qgstextrenderer.cpp @@ -123,12 +123,12 @@ void QgsTextBufferSettings::setFillBufferInterior( bool fill ) double QgsTextBufferSettings::opacity() const { - return d->color.alphaF(); + return d->opacity; } void QgsTextBufferSettings::setOpacity( double opacity ) { - d->color.setAlphaF( opacity ); + d->opacity = opacity; } Qt::PenJoinStyle QgsTextBufferSettings::joinStyle() const @@ -197,11 +197,11 @@ void QgsTextBufferSettings::readFromLayer( QgsVectorLayer* layer ) d->color = _readColor( layer, "labeling/bufferColor", Qt::white, false ); if ( layer->customProperty( "labeling/bufferOpacity" ).toString().isEmpty() ) { - d->color.setAlphaF( 1 - layer->customProperty( "labeling/bufferTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( "labeling/bufferTransp" ).toInt() / 100.0 ); //0 -100 } else { - d->color.setAlphaF( layer->customProperty( "labeling/bufferOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( "labeling/bufferOpacity" ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/bufferBlendMode", QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); @@ -218,7 +218,7 @@ void QgsTextBufferSettings::writeToLayer( QgsVectorLayer* layer ) const layer->setCustomProperty( "labeling/bufferSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); _writeColor( layer, "labeling/bufferColor", d->color ); layer->setCustomProperty( "labeling/bufferNoFill", !d->fillBufferInterior ); - layer->setCustomProperty( "labeling/bufferOpacity", d->color.alphaF() ); + layer->setCustomProperty( "labeling/bufferOpacity", d->opacity ); layer->setCustomProperty( "labeling/bufferJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); layer->setCustomProperty( "labeling/bufferBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); } @@ -270,11 +270,11 @@ void QgsTextBufferSettings::readXml( const QDomElement& elem ) if ( !textBufferElem.hasAttribute( "bufferOpacity" ) ) { - d->color.setAlphaF( 1 - textBufferElem.attribute( "bufferTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - textBufferElem.attribute( "bufferTransp" ).toInt() / 100.0 ); //0 -100 } else { - d->color.setAlphaF( textBufferElem.attribute( "bufferOpacity" ).toDouble() ); + d->opacity = ( textBufferElem.attribute( "bufferOpacity" ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( @@ -293,7 +293,7 @@ QDomElement QgsTextBufferSettings::writeXml( QDomDocument& doc ) const textBufferElem.setAttribute( "bufferSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); textBufferElem.setAttribute( "bufferColor", QgsSymbolLayerUtils::encodeColor( d->color ) ); textBufferElem.setAttribute( "bufferNoFill", !d->fillBufferInterior ); - textBufferElem.setAttribute( "bufferOpacity", d->color.alphaF() ); + textBufferElem.setAttribute( "bufferOpacity", d->opacity ); textBufferElem.setAttribute( "bufferJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); textBufferElem.setAttribute( "bufferBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); return textBufferElem; @@ -478,12 +478,12 @@ void QgsTextBackgroundSettings::setRadiiMapUnitScale( const QgsMapUnitScale &sca double QgsTextBackgroundSettings::opacity() const { - return d->fillColor.alphaF(); + return d->opacity; } void QgsTextBackgroundSettings::setOpacity( double opacity ) { - d->fillColor.setAlphaF( opacity ); + d->opacity = opacity; } QPainter::CompositionMode QgsTextBackgroundSettings::blendMode() const @@ -660,11 +660,11 @@ void QgsTextBackgroundSettings::readFromLayer( QgsVectorLayer* layer ) if ( layer->customProperty( "labeling/shapeOpacity" ).toString().isEmpty() ) { - d->fillColor.setAlphaF( 1 - layer->customProperty( "labeling/shapeTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( "labeling/shapeTransparency" ).toInt() / 100.0 ); //0 -100 } else { - d->fillColor.setAlphaF( layer->customProperty( "labeling/shapeOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( "labeling/shapeOpacity" ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/shapeBlendMode", QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); @@ -696,7 +696,7 @@ void QgsTextBackgroundSettings::writeToLayer( QgsVectorLayer* layer ) const layer->setCustomProperty( "labeling/shapeBorderWidthUnit", QgsUnitTypes::encodeUnit( d->borderWidthUnits ) ); layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->borderWidthMapUnitScale ) ); layer->setCustomProperty( "labeling/shapeJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); - layer->setCustomProperty( "labeling/shapeOpacity", d->fillColor.alphaF() ); + layer->setCustomProperty( "labeling/shapeOpacity", d->opacity ); layer->setCustomProperty( "labeling/shapeBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); } @@ -804,11 +804,11 @@ void QgsTextBackgroundSettings::readXml( const QDomElement& elem ) if ( !backgroundElem.hasAttribute( "shapeOpacity" ) ) { - d->fillColor.setAlphaF( 1 - backgroundElem.attribute( "shapeTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - backgroundElem.attribute( "shapeTransparency" ).toInt() / 100.0 ); //0 -100 } else { - d->fillColor.setAlphaF( backgroundElem.attribute( "shapeOpacity" ).toDouble() ); + d->opacity = ( backgroundElem.attribute( "shapeOpacity" ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( @@ -843,7 +843,7 @@ QDomElement QgsTextBackgroundSettings::writeXml( QDomDocument& doc ) const backgroundElem.setAttribute( "shapeBorderWidthUnit", QgsUnitTypes::encodeUnit( d->borderWidthUnits ) ); backgroundElem.setAttribute( "shapeBorderWidthMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->borderWidthMapUnitScale ) ); backgroundElem.setAttribute( "shapeJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); - backgroundElem.setAttribute( "shapeOpacity", d->fillColor.alphaF() ); + backgroundElem.setAttribute( "shapeOpacity", d->opacity ); backgroundElem.setAttribute( "shapeBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); return backgroundElem; } @@ -987,12 +987,12 @@ void QgsTextShadowSettings::setBlurAlphaOnly( bool alphaOnly ) double QgsTextShadowSettings::opacity() const { - return d->color.alphaF(); + return d->opacity; } void QgsTextShadowSettings::setOpacity( double opacity ) { - d->color.setAlphaF( opacity ); + d->opacity = opacity; } int QgsTextShadowSettings::scale() const @@ -1077,11 +1077,11 @@ void QgsTextShadowSettings::readFromLayer( QgsVectorLayer* layer ) if ( layer->customProperty( "labeling/shadowOpacity" ).toString().isEmpty() ) { - d->color.setAlphaF( 1 - layer->customProperty( "labeling/shadowTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( "labeling/shadowTransparency" ).toInt() / 100.0 ); //0 -100 } else { - d->color.setAlphaF( layer->customProperty( "labeling/shadowOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( "labeling/shadowOpacity" ).toDouble() ); } d->scale = layer->customProperty( "labeling/shadowScale", QVariant( 100 ) ).toInt(); d->color = _readColor( layer, "labeling/shadowColor", Qt::black, false ); @@ -1102,7 +1102,7 @@ void QgsTextShadowSettings::writeToLayer( QgsVectorLayer* layer ) const layer->setCustomProperty( "labeling/shadowRadiusUnit", QgsUnitTypes::encodeUnit( d->radiusUnits ) ); layer->setCustomProperty( "labeling/shadowRadiusMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->radiusMapUnitScale ) ); layer->setCustomProperty( "labeling/shadowRadiusAlphaOnly", d->radiusAlphaOnly ); - layer->setCustomProperty( "labeling/shadowOpacity", d->color.alphaF() ); + layer->setCustomProperty( "labeling/shadowOpacity", d->opacity ); layer->setCustomProperty( "labeling/shadowScale", d->scale ); _writeColor( layer, "labeling/shadowColor", d->color, false ); layer->setCustomProperty( "labeling/shadowBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); @@ -1162,11 +1162,11 @@ void QgsTextShadowSettings::readXml( const QDomElement& elem ) if ( !shadowElem.hasAttribute( "shadowOpacity" ) ) { - d->color.setAlphaF( 1 - shadowElem.attribute( "shadowTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - shadowElem.attribute( "shadowTransparency" ).toInt() / 100.0 ); //0 -100 } else { - d->color.setAlphaF( shadowElem.attribute( "shadowOpacity" ).toDouble() ); + d->opacity = ( shadowElem.attribute( "shadowOpacity" ).toDouble() ); } d->scale = shadowElem.attribute( "shadowScale", "100" ).toInt(); d->color = QgsSymbolLayerUtils::decodeColor( shadowElem.attribute( "shadowColor", QgsSymbolLayerUtils::encodeColor( Qt::black ) ) ); @@ -1188,7 +1188,7 @@ QDomElement QgsTextShadowSettings::writeXml( QDomDocument& doc ) const shadowElem.setAttribute( "shadowRadiusUnit", QgsUnitTypes::encodeUnit( d->radiusUnits ) ); shadowElem.setAttribute( "shadowRadiusMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->radiusMapUnitScale ) ); shadowElem.setAttribute( "shadowRadiusAlphaOnly", d->radiusAlphaOnly ); - shadowElem.setAttribute( "shadowOpacity", d->color.alphaF() ); + shadowElem.setAttribute( "shadowOpacity", d->opacity ); shadowElem.setAttribute( "shadowScale", d->scale ); shadowElem.setAttribute( "shadowColor", QgsSymbolLayerUtils::encodeColor( d->color ) ); shadowElem.setAttribute( "shadowBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); @@ -1308,12 +1308,12 @@ void QgsTextFormat::setColor( const QColor &color ) double QgsTextFormat::opacity() const { - return d->textColor.alphaF(); + return d->opacity; } void QgsTextFormat::setOpacity( double opacity ) { - d->textColor.setAlphaF( opacity ); + d->opacity = opacity; } QPainter::CompositionMode QgsTextFormat::blendMode() const @@ -1401,11 +1401,11 @@ void QgsTextFormat::readFromLayer( QgsVectorLayer* layer ) d->textColor = _readColor( layer, "labeling/textColor", Qt::black, false ); if ( layer->customProperty( "labeling/textOpacity" ).toString().isEmpty() ) { - d->textColor.setAlphaF( 1 - layer->customProperty( "labeling/textTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( "labeling/textTransp" ).toInt() / 100.0 ); //0 -100 } else { - d->textColor.setAlphaF( layer->customProperty( "labeling/textOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( "labeling/textOpacity" ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/blendMode", QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); @@ -1428,10 +1428,11 @@ void QgsTextFormat::writeToLayer( QgsVectorLayer* layer ) const layer->setCustomProperty( "labeling/fontStrikeout", d->textFont.strikeOut() ); layer->setCustomProperty( "labeling/fontUnderline", d->textFont.underline() ); _writeColor( layer, "labeling/textColor", d->textColor ); + layer->setCustomProperty( "labeling/textOpacity", d->opacity ); layer->setCustomProperty( "labeling/fontCapitals", static_cast< unsigned int >( d->textFont.capitalization() ) ); layer->setCustomProperty( "labeling/fontLetterSpacing", d->textFont.letterSpacing() ); layer->setCustomProperty( "labeling/fontWordSpacing", d->textFont.wordSpacing() ); - layer->setCustomProperty( "labeling/textOpacity", d->textColor.alphaF() ); + layer->setCustomProperty( "labeling/textOpacity", d->opacity ); layer->setCustomProperty( "labeling/blendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); layer->setCustomProperty( "labeling/multilineHeight", d->multilineHeight ); @@ -1505,11 +1506,11 @@ void QgsTextFormat::readXml( const QDomElement& elem ) d->textColor = QgsSymbolLayerUtils::decodeColor( textStyleElem.attribute( "textColor", QgsSymbolLayerUtils::encodeColor( Qt::black ) ) ); if ( !textStyleElem.hasAttribute( "textOpacity" ) ) { - d->textColor.setAlphaF( 1 - textStyleElem.attribute( "textTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - textStyleElem.attribute( "textTransp" ).toInt() / 100.0 ); //0 -100 } else { - d->textColor.setAlphaF( textStyleElem.attribute( "textOpacity" ).toDouble() ); + d->opacity = ( textStyleElem.attribute( "textOpacity" ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( textStyleElem.attribute( "blendMode", QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); @@ -1567,7 +1568,7 @@ QDomElement QgsTextFormat::writeXml( QDomDocument& doc ) const textStyleElem.setAttribute( "fontCapitals", static_cast< unsigned int >( d->textFont.capitalization() ) ); textStyleElem.setAttribute( "fontLetterSpacing", d->textFont.letterSpacing() ); textStyleElem.setAttribute( "fontWordSpacing", d->textFont.wordSpacing() ); - textStyleElem.setAttribute( "textOpacity", d->textColor.alphaF() ); + textStyleElem.setAttribute( "textOpacity", d->opacity ); textStyleElem.setAttribute( "blendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); textStyleElem.setAttribute( "multilineHeight", d->multilineHeight ); diff --git a/src/core/qgstextrenderer_p.h b/src/core/qgstextrenderer_p.h index 32369e09d7d8..83f35c8c4241 100644 --- a/src/core/qgstextrenderer_p.h +++ b/src/core/qgstextrenderer_p.h @@ -45,6 +45,7 @@ class CORE_EXPORT QgsTextBufferSettingsPrivate : public QSharedData , size( 1 ) , sizeUnit( QgsUnitTypes::RenderMillimeters ) , color( Qt::white ) + , opacity( 1.0 ) , fillBufferInterior( false ) , joinStyle( Qt::RoundJoin ) , blendMode( QPainter::CompositionMode_SourceOver ) @@ -58,6 +59,7 @@ class CORE_EXPORT QgsTextBufferSettingsPrivate : public QSharedData , sizeUnit( other.sizeUnit ) , sizeMapUnitScale( other.sizeMapUnitScale ) , color( other.color ) + , opacity( other.opacity ) , fillBufferInterior( other.fillBufferInterior ) , joinStyle( other.joinStyle ) , blendMode( other.blendMode ) @@ -71,6 +73,7 @@ class CORE_EXPORT QgsTextBufferSettingsPrivate : public QSharedData QgsUnitTypes::RenderUnit sizeUnit; QgsMapUnitScale sizeMapUnitScale; QColor color; + double opacity; bool fillBufferInterior; Qt::PenJoinStyle joinStyle; QPainter::CompositionMode blendMode; @@ -96,6 +99,7 @@ class CORE_EXPORT QgsTextBackgroundSettingsPrivate : public QSharedData , blendMode( QPainter::CompositionMode_SourceOver ) , fillColor( Qt::white ) , borderColor( Qt::darkGray ) + , opacity( 1.0 ) , borderWidth( 0.0 ) , borderWidthUnits( QgsUnitTypes::RenderMillimeters ) , joinStyle( Qt::BevelJoin ) @@ -122,6 +126,7 @@ class CORE_EXPORT QgsTextBackgroundSettingsPrivate : public QSharedData , blendMode( other.blendMode ) , fillColor( other.fillColor ) , borderColor( other.borderColor ) + , opacity( other.opacity ) , borderWidth( other.borderWidth ) , borderWidthUnits( other.borderWidthUnits ) , borderWidthMapUnitScale( other.borderWidthMapUnitScale ) @@ -149,6 +154,7 @@ class CORE_EXPORT QgsTextBackgroundSettingsPrivate : public QSharedData QPainter::CompositionMode blendMode; QColor fillColor; QColor borderColor; + double opacity; double borderWidth; QgsUnitTypes::RenderUnit borderWidthUnits; QgsMapUnitScale borderWidthMapUnitScale; @@ -173,6 +179,7 @@ class CORE_EXPORT QgsTextShadowSettingsPrivate : public QSharedData , radiusAlphaOnly( false ) , scale( 100 ) , color( QColor( 0, 0, 0, 76 ) ) + , opacity( 0.7 ) , blendMode( QPainter::CompositionMode_Multiply ) { @@ -193,6 +200,7 @@ class CORE_EXPORT QgsTextShadowSettingsPrivate : public QSharedData , radiusAlphaOnly( other.radiusAlphaOnly ) , scale( other.scale ) , color( other.color ) + , opacity( other.opacity ) , blendMode( other.blendMode ) { } @@ -212,6 +220,7 @@ class CORE_EXPORT QgsTextShadowSettingsPrivate : public QSharedData bool radiusAlphaOnly; int scale; QColor color; + double opacity; QPainter::CompositionMode blendMode; }; @@ -225,6 +234,7 @@ class CORE_EXPORT QgsTextSettingsPrivate : public QSharedData , fontSizeUnits( QgsUnitTypes::RenderPoints ) , fontSize( 10 ) , textColor( Qt::black ) + , opacity( 1.0 ) , blendMode( QPainter::CompositionMode_SourceOver ) , multilineHeight( 1.0 ) { @@ -238,6 +248,7 @@ class CORE_EXPORT QgsTextSettingsPrivate : public QSharedData , fontSizeMapUnitScale( other.fontSizeMapUnitScale ) , fontSize( other.fontSize ) , textColor( other.textColor ) + , opacity( other.opacity ) , blendMode( other.blendMode ) , multilineHeight( other.multilineHeight ) { @@ -251,6 +262,7 @@ class CORE_EXPORT QgsTextSettingsPrivate : public QSharedData QgsMapUnitScale fontSizeMapUnitScale; double fontSize; //may differ from size in textFont due to units (eg size in map units) QColor textColor; + double opacity; QPainter::CompositionMode blendMode; double multilineHeight; //0.0 to 10.0, leading between lines as multiplyer of line height diff --git a/src/core/qgsvectorlayerlabelprovider.cpp b/src/core/qgsvectorlayerlabelprovider.cpp index b78d0686a397..93de335dff2d 100644 --- a/src/core/qgsvectorlayerlabelprovider.cpp +++ b/src/core/qgsvectorlayerlabelprovider.cpp @@ -727,7 +727,9 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q QPainter textp; textp.begin( &textPict ); textp.setPen( Qt::NoPen ); - textp.setBrush( tmpLyr.format().color() ); + QColor textColor = tmpLyr.format().color(); + textColor.setAlphaF( tmpLyr.format().opacity() ); + textp.setBrush( textColor ); textp.drawPath( path ); // TODO: why are some font settings lost on drawPicture() when using drawText() inside QPicture? // e.g. some capitalization options, but not others @@ -764,7 +766,9 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q { // draw text as text (for SVG and PDF exports) painter->setFont( tmpLyr.format().scaledFont( context ) ); - painter->setPen( tmpLyr.format().color() ); + QColor textColor = tmpLyr.format().color(); + textColor.setAlphaF( tmpLyr.format().opacity() ); + painter->setPen( textColor ); painter->setRenderHint( QPainter::TextAntialiasing ); painter->drawText( 0, 0, component.text() ); } From 08143475edb5a920523fb0f56ca7ffbb1870d45e Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 27 Sep 2016 18:52:48 +1000 Subject: [PATCH 446/897] [FEATURE] QgsTextRenderer class for rich text rendering Moves all the drawing code out of labeling into a new class which just handles rendering text. This allows other parts of the code to utilise all the advanced formatting options that labeling supports, eg rendering text with shadows, buffers and backgrounds. --- python/core/qgspallabeling.sip | 75 - python/core/qgstextrenderer.sip | 83 ++ src/app/qgslabelinggui.cpp | 2 +- src/app/qgslabelpreview.cpp | 6 +- src/core/qgspallabeling.cpp | 516 ------- src/core/qgspallabeling.h | 115 -- src/core/qgstextrenderer.cpp | 947 +++++++++++++ src/core/qgstextrenderer.h | 177 ++- src/core/qgstextrenderer_p.h | 2 +- src/core/qgsvectorlayerlabelprovider.cpp | 217 +-- src/core/qgsvectorlayerlabelprovider.h | 2 +- tests/src/python/test_qgstextrenderer.py | 1243 ++++++++++++++++- .../background_disabled.png | Bin 0 -> 1413 bytes .../background_ellipse_pixels.png | Bin 0 -> 2849 bytes .../background_fillcolor.png | Bin 0 -> 1508 bytes .../background_offset_mapunits.png | Bin 0 -> 1498 bytes .../background_offset_mm.png | Bin 0 -> 1487 bytes .../background_opacity/background_opacity.png | Bin 0 -> 1487 bytes .../background_outline/background_outline.png | Bin 0 -> 1750 bytes .../background_point_buffer_pixels.png | Bin 0 -> 1448 bytes .../background_point_center_buffer_pixels.png | Bin 0 -> 1454 bytes .../background_point_center_mapunits.png | Bin 0 -> 1457 bytes .../background_point_mapunits.png | Bin 0 -> 1478 bytes ...ground_point_multiline_buffer_mapunits.png | Bin 0 -> 1450 bytes .../background_point_multiline_mapunits.png | Bin 0 -> 1479 bytes .../background_point_right_buffer_pixels.png | Bin 0 -> 1442 bytes .../background_point_right_mapunits.png | Bin 0 -> 1491 bytes .../background_radii_mapunits.png | Bin 0 -> 2286 bytes .../background_radii_mm.png | Bin 0 -> 2250 bytes .../background_rect_buffer_mapunits.png | Bin 0 -> 1448 bytes .../background_rect_buffer_mm.png | Bin 0 -> 1485 bytes .../background_rect_buffer_pixels.png | Bin 0 -> 1448 bytes .../background_rect_center_buffer_pixels.png | Bin 0 -> 1454 bytes .../background_rect_center_mapunits.png | Bin 0 -> 1458 bytes .../background_rect_mapunits.png | Bin 0 -> 1488 bytes .../background_rect_mm/background_rect_mm.png | Bin 0 -> 1494 bytes ...kground_rect_multiline_buffer_mapunits.png | Bin 0 -> 1450 bytes .../background_rect_multiline_mapunits.png | Bin 0 -> 1479 bytes .../background_rect_pixels.png | Bin 0 -> 1488 bytes .../background_rect_right_buffer_pixels.png | Bin 0 -> 1446 bytes .../background_rect_right_mapunits.png | Bin 0 -> 1489 bytes .../background_rotation_fixed.png | Bin 0 -> 2374 bytes .../background_rotation_offset.png | Bin 0 -> 3484 bytes .../background_rotation_sync.png | Bin 0 -> 3994 bytes .../background_svg_buffer_mapunits.png | Bin 0 -> 1485 bytes .../background_svg_buffer_mm.png | Bin 0 -> 1488 bytes .../background_svg_buffer_pixels.png | Bin 0 -> 1489 bytes .../background_svg_fixed_mapunits.png | Bin 0 -> 1475 bytes .../background_svg_fixed_mm.png | Bin 0 -> 1474 bytes .../background_svg_fixed_pixels.png | Bin 0 -> 1488 bytes .../shadow_color/shadow_color.png | Bin 0 -> 6340 bytes .../shadow_enabled/shadow_enabled.png | Bin 0 -> 7353 bytes .../shadow_offset_angle.png | Bin 0 -> 7172 bytes .../shadow_offset_mapunits.png | Bin 0 -> 8015 bytes .../shadow_offset_pixels.png | Bin 0 -> 6793 bytes .../shadow_opacity/shadow_opacity.png | Bin 0 -> 7256 bytes .../shadow_placement_background.png | Bin 0 -> 1537 bytes .../shadow_placement_buffer.png | Bin 0 -> 5944 bytes .../shadow_radius_mapunits.png | Bin 0 -> 15244 bytes .../shadow_radius_mm/shadow_radius_mm.png | Bin 0 -> 14849 bytes .../shadow_radius_pixels.png | Bin 0 -> 13411 bytes .../shadow_scale_150/shadow_scale_150.png | Bin 0 -> 12624 bytes .../shadow_scale_50/shadow_scale_50.png | Bin 0 -> 6019 bytes .../text_renderer/text_angled/text_angled.png | Bin 0 -> 3727 bytes .../text_blend_mode/text_blend_mode.png | Bin 0 -> 4637 bytes .../text_renderer/text_bold/text_bold.png | Bin 0 -> 5220 bytes .../text_buffer_color/text_buffer_color.png | Bin 0 -> 8987 bytes .../text_buffer_interior.png | Bin 0 -> 4726 bytes .../text_buffer_mapunits.png | Bin 0 -> 3921 bytes .../text_buffer_mm/text_buffer_mm.png | Bin 0 -> 7470 bytes .../text_buffer_opacity.png | Bin 0 -> 6720 bytes .../text_buffer_pixels/text_buffer_pixels.png | Bin 0 -> 6177 bytes .../text_renderer/text_color/text_color.png | Bin 0 -> 5082 bytes .../text_disabled_buffer.png | Bin 0 -> 1413 bytes .../text_line_height/text_line_height.png | Bin 0 -> 6221 bytes .../text_mapunits/text_mapunits.png | Bin 0 -> 3578 bytes .../text_multiline/text_multiline.png | Bin 0 -> 6212 bytes .../text_named_style/text_named_style.png | Bin 0 -> 6104 bytes .../text_opacity/text_opacity.png | Bin 0 -> 5159 bytes .../text_renderer/text_pixels/text_pixels.png | Bin 0 -> 4084 bytes .../text_point_bold/text_point_bold.png | Bin 0 -> 5214 bytes .../text_point_center_aligned.png | Bin 0 -> 3571 bytes .../text_point_center_multiline_aligned.png | Bin 0 -> 9584 bytes .../text_point_multiline.png | Bin 0 -> 6097 bytes .../text_point_right_aligned.png | Bin 0 -> 3631 bytes .../text_point_right_multiline_aligned.png | Bin 0 -> 8744 bytes .../text_rect_center_aligned.png | Bin 0 -> 3601 bytes .../text_rect_multiline_center_aligned.png | Bin 0 -> 7632 bytes .../text_rect_multiline_right_aligned.png | Bin 0 -> 8912 bytes .../text_rect_right_aligned.png | Bin 0 -> 3604 bytes .../text_with_background.png | Bin 0 -> 5216 bytes .../text_with_buffer/text_with_buffer.png | Bin 0 -> 7493 bytes .../text_with_buffer_and_background.png | Bin 0 -> 7880 bytes .../text_with_shadow_and_background.png | Bin 0 -> 5291 bytes .../text_with_shadow_and_buffer.png | Bin 0 -> 9198 bytes ...ith_shadow_below_buffer_and_background.png | Bin 0 -> 9148 bytes ..._with_shadow_below_text_and_background.png | Bin 0 -> 7324 bytes ...text_with_shadow_below_text_and_buffer.png | Bin 0 -> 9875 bytes ...hadow_below_text_buffer_and_background.png | Bin 0 -> 9839 bytes ...text_with_shadow_buffer_and_background.png | Bin 0 -> 7941 bytes 100 files changed, 2488 insertions(+), 897 deletions(-) create mode 100644 tests/testdata/control_images/text_renderer/background_disabled/background_disabled.png create mode 100644 tests/testdata/control_images/text_renderer/background_ellipse_pixels/background_ellipse_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_fillcolor/background_fillcolor.png create mode 100644 tests/testdata/control_images/text_renderer/background_offset_mapunits/background_offset_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_offset_mm/background_offset_mm.png create mode 100644 tests/testdata/control_images/text_renderer/background_opacity/background_opacity.png create mode 100644 tests/testdata/control_images/text_renderer/background_outline/background_outline.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_buffer_pixels/background_point_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_center_buffer_pixels/background_point_center_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_center_mapunits/background_point_center_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_mapunits/background_point_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_multiline_buffer_mapunits/background_point_multiline_buffer_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_multiline_mapunits/background_point_multiline_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_right_buffer_pixels/background_point_right_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_right_mapunits/background_point_right_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_radii_mapunits/background_radii_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_radii_mm/background_radii_mm.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_buffer_mapunits/background_rect_buffer_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_buffer_mm/background_rect_buffer_mm.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_buffer_pixels/background_rect_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_center_buffer_pixels/background_rect_center_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_center_mapunits/background_rect_center_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_mapunits/background_rect_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_mm/background_rect_mm.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_multiline_buffer_mapunits/background_rect_multiline_buffer_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_multiline_mapunits/background_rect_multiline_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_pixels/background_rect_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_right_buffer_pixels/background_rect_right_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_right_mapunits/background_rect_right_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_rotation_fixed/background_rotation_fixed.png create mode 100644 tests/testdata/control_images/text_renderer/background_rotation_offset/background_rotation_offset.png create mode 100644 tests/testdata/control_images/text_renderer/background_rotation_sync/background_rotation_sync.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_buffer_mapunits/background_svg_buffer_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_buffer_mm/background_svg_buffer_mm.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_buffer_pixels/background_svg_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_fixed_mapunits/background_svg_fixed_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_fixed_mm/background_svg_fixed_mm.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_fixed_pixels/background_svg_fixed_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_color/shadow_color.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_enabled/shadow_enabled.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_offset_angle/shadow_offset_angle.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_offset_mapunits/shadow_offset_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_offset_pixels/shadow_offset_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_opacity/shadow_opacity.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_placement_background/shadow_placement_background.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_placement_buffer/shadow_placement_buffer.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_radius_mapunits/shadow_radius_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_radius_mm/shadow_radius_mm.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_radius_pixels/shadow_radius_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_scale_150/shadow_scale_150.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_scale_50/shadow_scale_50.png create mode 100644 tests/testdata/control_images/text_renderer/text_angled/text_angled.png create mode 100644 tests/testdata/control_images/text_renderer/text_blend_mode/text_blend_mode.png create mode 100644 tests/testdata/control_images/text_renderer/text_bold/text_bold.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_color/text_buffer_color.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_interior/text_buffer_interior.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_mapunits/text_buffer_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_mm/text_buffer_mm.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_opacity/text_buffer_opacity.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_pixels/text_buffer_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/text_color/text_color.png create mode 100644 tests/testdata/control_images/text_renderer/text_disabled_buffer/text_disabled_buffer.png create mode 100644 tests/testdata/control_images/text_renderer/text_line_height/text_line_height.png create mode 100644 tests/testdata/control_images/text_renderer/text_mapunits/text_mapunits.png create mode 100644 tests/testdata/control_images/text_renderer/text_multiline/text_multiline.png create mode 100644 tests/testdata/control_images/text_renderer/text_named_style/text_named_style.png create mode 100644 tests/testdata/control_images/text_renderer/text_opacity/text_opacity.png create mode 100644 tests/testdata/control_images/text_renderer/text_pixels/text_pixels.png create mode 100644 tests/testdata/control_images/text_renderer/text_point_bold/text_point_bold.png create mode 100644 tests/testdata/control_images/text_renderer/text_point_center_aligned/text_point_center_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_point_center_multiline_aligned/text_point_center_multiline_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_point_multiline/text_point_multiline.png create mode 100644 tests/testdata/control_images/text_renderer/text_point_right_aligned/text_point_right_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_point_right_multiline_aligned/text_point_right_multiline_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_center_aligned/text_rect_center_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_multiline_center_aligned/text_rect_multiline_center_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_multiline_right_aligned/text_rect_multiline_right_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_right_aligned/text_rect_right_aligned.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_background/text_with_background.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_buffer/text_with_buffer.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_buffer_and_background/text_with_buffer_and_background.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_and_background/text_with_shadow_and_background.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_and_buffer/text_with_shadow_and_buffer.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_buffer_and_background/text_with_shadow_below_buffer_and_background.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_background/text_with_shadow_below_text_and_background.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_buffer/text_with_shadow_below_text_and_buffer.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_text_buffer_and_background/text_with_shadow_below_text_buffer_and_background.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_buffer_and_background/text_with_shadow_buffer_and_background.png diff --git a/python/core/qgspallabeling.sip b/python/core/qgspallabeling.sip index f9e1de595900..8aeedf5d90fe 100644 --- a/python/core/qgspallabeling.sip +++ b/python/core/qgspallabeling.sip @@ -649,61 +649,6 @@ class QgsLabelCandidate double cost; }; -/** \ingroup core - * Maintains current state of more grainular and temporal values when creating/painting - * component parts of an individual label (e.g. buffer, background, shadow, etc.). - */ -class QgsLabelComponent -{ -%TypeHeaderCode -#include -%End - - public: - QgsLabelComponent(); - - // methods - - QString text() const; - void setText( const QString& text ); - - const QgsPoint& origin() const; - void setOrigin( const QgsPoint& point ); - - bool useOrigin() const; - void setUseOrigin( const bool use ); - - double rotation() const; - void setRotation( const double rotation ); - - double rotationOffset() const; - void setRotationOffset( const double rotation ); - - bool useRotation() const; - void setUseRotation( const bool use ); - - const QgsPoint& center() const; - void setCenter( const QgsPoint& point ); - - bool useCenter() const; - void setUseCenter( const bool use ); - - const QgsPoint& size() const; - void setSize( const QgsPoint& point ); - - const QgsPoint& offset() const; - void setOffset( const QgsPoint& point ); - - const QPicture* picture() const; - void setPicture( QPicture* picture ); - - double pictureBuffer() const; - void setPictureBuffer( const double buffer ); - - double dpiRatio() const; - void setDpiRatio( const double ratio ); -}; - /** * Class that stores computed placement from labeling engine. @@ -736,14 +681,6 @@ class QgsPalLabeling : QgsLabelingEngineInterface %End public: - enum DrawLabelType - { - LabelText, - LabelBuffer, - LabelShape, - LabelSVG, - LabelShadow - }; QgsPalLabeling(); ~QgsPalLabeling(); @@ -830,18 +767,6 @@ class QgsPalLabeling : QgsLabelingEngineInterface //! @note not available in python bindings // void drawLabelCandidateRect( pal::LabelPosition* lp, QPainter* painter, const QgsMapToPixel* xform ); - static void drawLabelBuffer( QgsRenderContext& context, - const QgsLabelComponent &component, - const QgsTextFormat& format ); - - static void drawLabelBackground( QgsRenderContext& context, - QgsLabelComponent component, - const QgsTextFormat& format ); - - static void drawLabelShadow( QgsRenderContext &context, - const QgsLabelComponent &component, - const QgsTextFormat& format ); - //! load/save engine settings to project file void loadEngineSettings(); void saveEngineSettings(); diff --git a/python/core/qgstextrenderer.sip b/python/core/qgstextrenderer.sip index 9d1b52aec4ea..8e102fa1f054 100644 --- a/python/core/qgstextrenderer.sip +++ b/python/core/qgstextrenderer.sip @@ -856,6 +856,15 @@ class QgsTextFormat */ QFont font() const; + /** Returns a font with the size scaled to match the format's size settings (including + * units and map unit scale) for a specified render context. + * @param context destination render context + * @returns font with scaled size + * @see font() + * @see size() + */ + QFont scaledFont( const QgsRenderContext& context ) const; + /** Sets the font used for rendering text. Note that the size of the font * is not used, and setSize() should be called instead to explicitly set the size * of rendered text. @@ -1021,6 +1030,21 @@ class QgsTextRenderer public: + enum TextPart + { + Text, + Buffer, + Background, + Shadow + }; + + enum HAlignment + { + AlignLeft, + AlignCenter, + AlignRight, + }; + /** Calculates pixel size (considering output size should be in pixel or map units, scale factors and optionally oversampling) * @param size size to convert * @param c rendercontext @@ -1041,4 +1065,63 @@ class QgsTextRenderer */ static double scaleToPixelContext( double size, const QgsRenderContext& c, QgsUnitTypes::RenderUnit unit, bool rasterfactor = false, const QgsMapUnitScale& mapUnitScale = QgsMapUnitScale() ); + /** Draws text within a rectangle using the specified settings. + * @param rect destination rectangle for text + * @param rotation text rotation + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawText( const QRectF& rect, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + bool drawAsOutlines = true ); + + /** Draws text at a point origin using the specified settings. + * @param point origin of text + * @param rotation text rotation + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawText( const QPointF& point, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + bool drawAsOutlines = true ); + + /** Draws a single component of rendered text using the specified settings. + * @param rect destination rectangle for text + * @param rotation text rotation + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param part component of text to draw + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawPart( const QRectF& rect, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + TextPart part, bool drawAsOutlines = true ); + + /** Draws a single component of rendered text using the specified settings. + * @param origin origin for start of text. Y coordinate will be used as baseline. + * @param rotation text rotation + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param part component of text to draw. Note that Shadow parts cannot be drawn + * individually and instead are drawn with their associated part (eg drawn together + * with the text or background parts) + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawPart( const QPointF& origin, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + TextPart part, bool drawAsOutlines = true ); }; diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index d35e5963bed9..d783a1ec2ee1 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -771,7 +771,7 @@ void QgsLabelingGui::init() mZIndexSpinBox->setValue( lyr.zIndex ); mRefFont = format.font(); - mFontSizeSpinBox->setValue( format.font().pointSizeF() ); + mFontSizeSpinBox->setValue( format.size() ); btnTextColor->setColor( format.color() ); mFontTranspSpinBox->setValue( 100 - 100 * format.opacity() ); comboBlendMode->setBlendMode( format.blendMode() ); diff --git a/src/app/qgslabelpreview.cpp b/src/app/qgslabelpreview.cpp index 0ab89700e9b5..70f6508dcbd0 100644 --- a/src/app/qgslabelpreview.cpp +++ b/src/app/qgslabelpreview.cpp @@ -73,9 +73,9 @@ void QgsLabelPreview::paintEvent( QPaintEvent *e ) if ( mFormat.buffer().size() != 0 ) { mContext.setPainter( &p ); - QgsLabelComponent component; - component.setText( text() ); - QgsPalLabeling::drawLabelBuffer( mContext, component, mFormat ); + QgsTextRenderer::Component component; + component.text = text(); + QgsTextRenderer::drawBuffer( mContext, component, mFormat ); } QPainterPath path; diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index 6f3bdd944a6b..dbaa89e7a968 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -62,20 +62,6 @@ #include -Q_GUI_EXPORT extern int qt_defaultDpiX(); -Q_GUI_EXPORT extern int qt_defaultDpiY(); - -static void _fixQPictureDPI( QPainter* p ) -{ - // QPicture makes an assumption that we drawing to it with system DPI. - // Then when being drawn, it scales the painter. The following call - // negates the effect. There is no way of setting QPicture's DPI. - // See QTBUG-20361 - p->scale( static_cast< double >( qt_defaultDpiX() ) / p->device()->logicalDpiX(), - static_cast< double >( qt_defaultDpiY() ) / p->device()->logicalDpiY() ); -} - - using namespace pal; // ------------- @@ -4072,508 +4058,6 @@ void QgsPalLabeling::drawLabelCandidateRect( pal::LabelPosition* lp, QPainter* p drawLabelCandidateRect( lp->getNextPart(), painter, xform, candidates ); } - -void QgsPalLabeling::drawLabelBuffer( QgsRenderContext& context, - const QgsLabelComponent& component, - const QgsTextFormat& format ) -{ - QPainter* p = context.painter(); - - QgsTextBufferSettings buffer = format.buffer(); - - double penSize = QgsTextRenderer::scaleToPixelContext( buffer.size(), context, - buffer.sizeUnit(), true, buffer.sizeMapUnitScale() ); - - QPainterPath path; - path.setFillRule( Qt::WindingFill ); - path.addText( 0, 0, format.scaledFont( context ), component.text() ); - QColor bufferColor = buffer.color(); - bufferColor.setAlphaF( buffer.opacity() ); - QPen pen( bufferColor ); - pen.setWidthF( penSize ); - pen.setJoinStyle( buffer.joinStyle() ); - QColor tmpColor( bufferColor ); - // honor pref for whether to fill buffer interior - if ( !buffer.fillBufferInterior() ) - { - tmpColor.setAlpha( 0 ); - } - - // store buffer's drawing in QPicture for drop shadow call - QPicture buffPict; - QPainter buffp; - buffp.begin( &buffPict ); - buffp.setPen( pen ); - buffp.setBrush( tmpColor ); - buffp.drawPath( path ); - buffp.end(); - - if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowBuffer ) - { - QgsLabelComponent bufferComponent = component; - bufferComponent.setOrigin( QgsPoint( 0.0, 0.0 ) ); - bufferComponent.setPicture( &buffPict ); - bufferComponent.setPictureBuffer( penSize / 2.0 ); - drawLabelShadow( context, bufferComponent, format ); - } - - p->save(); - if ( context.useAdvancedEffects() ) - { - p->setCompositionMode( buffer.blendMode() ); - } -// p->setPen( pen ); -// p->setBrush( tmpColor ); -// p->drawPath( path ); - - // scale for any print output or image saving @ specific dpi - p->scale( component.dpiRatio(), component.dpiRatio() ); - _fixQPictureDPI( p ); - p->drawPicture( 0, 0, buffPict ); - p->restore(); -} - -void QgsPalLabeling::drawLabelBackground( QgsRenderContext& context, - QgsLabelComponent component, - const QgsTextFormat& format ) -{ - QgsTextBackgroundSettings background = format.background(); - - QPainter* p = context.painter(); - double labelWidth = component.size().x(), labelHeight = component.size().y(); - //QgsDebugMsgLevel( QString( "Background label rotation: %1" ).arg( component.rotation() ), 4 ); - - // shared calculations between shapes and SVG - - // configure angles, set component rotation and rotationOffset - if ( background.rotationType() != QgsTextBackgroundSettings::RotationFixed ) - { - component.setRotation( -( component.rotation() * 180 / M_PI ) ); // RotationSync - component.setRotationOffset( - background.rotationType() == QgsTextBackgroundSettings::RotationOffset ? background.rotation() : 0.0 ); - } - else // RotationFixed - { - component.setRotation( 0.0 ); // don't use label's rotation - component.setRotationOffset( background.rotation() ); - } - - // TODO: the following label-buffered generated shapes and SVG symbols should be moved into marker symbology classes - - if ( background.type() == QgsTextBackgroundSettings::ShapeSVG ) - { - // all calculations done in shapeSizeUnits, which are then passed to symbology class for painting - - if ( background.svgFile().isEmpty() ) - return; - - double sizeOut = 0.0; - // only one size used for SVG sizing/scaling (no use of shapeSize.y() or Y field in gui) - if ( background.sizeType() == QgsTextBackgroundSettings::SizeFixed ) - { - sizeOut = background.size().width(); - } - else if ( background.sizeType() == QgsTextBackgroundSettings::SizeBuffer ) - { - // add buffer to greatest dimension of label - if ( labelWidth >= labelHeight ) - sizeOut = labelWidth; - else - sizeOut = labelHeight; - - // label size in map units, convert to shapeSizeUnits, if different - if ( background.sizeUnit() != QgsUnitTypes::RenderMapUnits ) - { - sizeOut = QgsSymbolLayerUtils::convertToMapUnits( context, sizeOut, - background.sizeUnit(), background.sizeMapUnitScale() ); - } - - // add buffer - sizeOut += background.size().width() * 2; - } - - // don't bother rendering symbols smaller than 1x1 pixels in size - // TODO: add option to not show any svgs under/over a certain size - if ( QgsTextRenderer::scaleToPixelContext( sizeOut, context, background.sizeUnit(), - false, background.sizeMapUnitScale() ) < 1.0 ) - return; - - QgsStringMap map; // for SVG symbology marker - map["name"] = QgsSymbolLayerUtils::symbolNameToPath( background.svgFile().trimmed() ); - map["size"] = QString::number( sizeOut ); - map["size_unit"] = QgsUnitTypes::encodeUnit( background.sizeUnit() ); - map["angle"] = QString::number( 0.0 ); // angle is handled by this local painter - - // offset is handled by this local painter - // TODO: see why the marker renderer doesn't seem to translate offset *after* applying rotation - //map["offset"] = QgsSymbolLayerUtils::encodePoint( tmpLyr.shapeOffset ); - //map["offset_unit"] = QgsUnitTypes::encodeUnit( - // tmpLyr.shapeOffsetUnits == QgsPalLayerSettings::MapUnits ? QgsUnitTypes::MapUnit : QgsUnitTypes::MM ); - - map["fill"] = background.fillColor().name(); - map["outline"] = background.borderColor().name(); - map["outline-width"] = QString::number( background.borderWidth() ); - map["outline_width_unit"] = QgsUnitTypes::encodeUnit( background.borderWidthUnit() ); - - if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowShape ) - { - QgsTextShadowSettings shadow = format.shadow(); - // configure SVG shadow specs - QgsStringMap shdwmap( map ); - shdwmap["fill"] = shadow.color().name(); - shdwmap["outline"] = shadow.color().name(); - shdwmap["size"] = QString::number( sizeOut * context.rasterScaleFactor() ); - - // store SVG's drawing in QPicture for drop shadow call - QPicture svgPict; - QPainter svgp; - svgp.begin( &svgPict ); - - // draw shadow symbol - - // clone current render context map unit/mm conversion factors, but not - // other map canvas parameters, then substitute this painter for use in symbology painting - // NOTE: this is because the shadow needs to be scaled correctly for output to map canvas, - // but will be created relative to the SVG's computed size, not the current map canvas - QgsRenderContext shdwContext; - shdwContext.setMapToPixel( context.mapToPixel() ); - shdwContext.setScaleFactor( context.scaleFactor() ); - shdwContext.setPainter( &svgp ); - - QgsSymbolLayer* symShdwL = QgsSvgMarkerSymbolLayer::create( shdwmap ); - QgsSvgMarkerSymbolLayer* svgShdwM = static_cast( symShdwL ); - QgsSymbolRenderContext svgShdwContext( shdwContext, QgsUnitTypes::RenderUnknownUnit, background.opacity() ); - - double svgSize = QgsTextRenderer::scaleToPixelContext( sizeOut, context, background.sizeUnit(), - true, background.sizeMapUnitScale() ); - svgShdwM->renderPoint( QPointF( svgSize / 2, -svgSize / 2 ), svgShdwContext ); - svgp.end(); - - component.setPicture( &svgPict ); - // TODO: when SVG symbol's border width/units is fixed in QgsSvgCache, adjust for it here - component.setPictureBuffer( 0.0 ); - - component.setSize( QgsPoint( svgSize, svgSize ) ); - component.setOffset( QgsPoint( 0.0, 0.0 ) ); - - // rotate about origin center of SVG - p->save(); - p->translate( component.center().x(), component.center().y() ); - p->rotate( component.rotation() ); - p->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); - double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), true, background.offsetMapUnitScale() ); - double yoff = QgsTextRenderer::scaleToPixelContext( background.offset().y(), context, background.offsetUnit(), true, background.offsetMapUnitScale() ); - p->translate( QPointF( xoff, yoff ) ); - p->rotate( component.rotationOffset() ); - p->translate( -svgSize / 2, svgSize / 2 ); - - drawLabelShadow( context, component, format ); - p->restore(); - - delete svgShdwM; - svgShdwM = nullptr; - } - - // draw the actual symbol - QgsSymbolLayer* symL = QgsSvgMarkerSymbolLayer::create( map ); - QgsSvgMarkerSymbolLayer* svgM = static_cast( symL ); - QgsSymbolRenderContext svgContext( context, QgsUnitTypes::RenderUnknownUnit, background.opacity() ); - - p->save(); - if ( context.useAdvancedEffects() ) - { - p->setCompositionMode( background.blendMode() ); - } - p->translate( component.center().x(), component.center().y() ); - p->rotate( component.rotation() ); - double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); - double yoff = QgsTextRenderer::scaleToPixelContext( background.offset().y(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); - p->translate( QPointF( xoff, yoff ) ); - p->rotate( component.rotationOffset() ); - svgM->renderPoint( QPointF( 0, 0 ), svgContext ); - p->setCompositionMode( QPainter::CompositionMode_SourceOver ); // just to be sure - p->restore(); - - delete svgM; - svgM = nullptr; - - } - else // Generated Shapes - { - // all calculations done in background size units - double w = QgsSymbolLayerUtils::convertFromMapUnits( context, labelWidth, background.sizeUnit() ); - double h = QgsSymbolLayerUtils::convertFromMapUnits( context, labelHeight, background.sizeUnit() ); - - double xsize = background.size().width(); - double ysize = background.size().height(); - - if ( background.sizeType() == QgsTextBackgroundSettings::SizeFixed ) - { - w = xsize; - h = ysize; - } - else if ( background.sizeType() == QgsTextBackgroundSettings::SizeBuffer ) - { - if ( background.type() == QgsTextBackgroundSettings::ShapeSquare ) - { - if ( w > h ) - h = w; - else if ( h > w ) - w = h; - } - else if ( background.type() == QgsTextBackgroundSettings::ShapeCircle ) - { - // start with label bound by circle - h = sqrt( pow( w, 2 ) + pow( h, 2 ) ); - w = h; - } - else if ( background.type() == QgsTextBackgroundSettings::ShapeEllipse ) - { - // start with label bound by ellipse - h = h / sqrt( 2.0 ) * 2; - w = w / sqrt( 2.0 ) * 2; - } - - w += xsize * 2; - h += ysize * 2; - } - - // convert everything over to map pixels from here on - w = QgsTextRenderer::scaleToPixelContext( w, context, background.sizeUnit(), true, background.sizeMapUnitScale() ); - h = QgsTextRenderer::scaleToPixelContext( h, context, background.sizeUnit(), true, background.sizeMapUnitScale() ); - - // offsets match those of symbology: -x = left, -y = up - QRectF rect( -w / 2.0, - h / 2.0, w, h ); - - if ( rect.isNull() ) - return; - - p->save(); - p->translate( QPointF( component.center().x(), component.center().y() ) ); - p->rotate( component.rotation() ); - double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); - double yoff = QgsTextRenderer::scaleToPixelContext( background.offset().y(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); - p->translate( QPointF( xoff, yoff ) ); - p->rotate( component.rotationOffset() ); - - double penSize = QgsTextRenderer::scaleToPixelContext( background.borderWidth(), context, background.borderWidthUnit(), true, background.borderWidthMapUnitScale() ); - - QPen pen; - if ( background.borderWidth() > 0 ) - { - pen.setColor( background.borderColor() ); - pen.setWidthF( penSize ); - if ( background.type() == QgsTextBackgroundSettings::ShapeRectangle ) - pen.setJoinStyle( background.joinStyle() ); - } - else - { - pen = Qt::NoPen; - } - - // store painting in QPicture for shadow drawing - QPicture shapePict; - QPainter shapep; - shapep.begin( &shapePict ); - shapep.setPen( pen ); - shapep.setBrush( background.fillColor() ); - - if ( background.type() == QgsTextBackgroundSettings::ShapeRectangle - || background.type() == QgsTextBackgroundSettings::ShapeSquare ) - { - if ( background.radiiUnit() == QgsUnitTypes::RenderPercentage ) - { - shapep.drawRoundedRect( rect, background.radii().width(), background.radii().height(), Qt::RelativeSize ); - } - else - { - double xRadius = QgsTextRenderer::scaleToPixelContext( background.radii().width(), context, background.radiiUnit(), true, background.radiiMapUnitScale() ); - double yRadius = QgsTextRenderer::scaleToPixelContext( background.radii().height(), context, background.radiiUnit(), true, background.radiiMapUnitScale() ); - shapep.drawRoundedRect( rect, xRadius, yRadius ); - } - } - else if ( background.type() == QgsTextBackgroundSettings::ShapeEllipse - || background.type() == QgsTextBackgroundSettings::ShapeCircle ) - { - shapep.drawEllipse( rect ); - } - shapep.end(); - - p->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); - - if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowShape ) - { - component.setPicture( &shapePict ); - component.setPictureBuffer( penSize / 2.0 ); - - component.setSize( QgsPoint( rect.width(), rect.height() ) ); - component.setOffset( QgsPoint( rect.width() / 2, -rect.height() / 2 ) ); - drawLabelShadow( context, component, format ); - } - - p->setOpacity( background.opacity() ); - if ( context.useAdvancedEffects() ) - { - p->setCompositionMode( background.blendMode() ); - } - - // scale for any print output or image saving @ specific dpi - p->scale( component.dpiRatio(), component.dpiRatio() ); - _fixQPictureDPI( p ); - p->drawPicture( 0, 0, shapePict ); - p->restore(); - } -} - -void QgsPalLabeling::drawLabelShadow( QgsRenderContext& context, - const QgsLabelComponent& component, - const QgsTextFormat& format ) -{ - QgsTextShadowSettings shadow = format.shadow(); - - // incoming component sizes should be multiplied by rasterCompressFactor, as - // this allows shadows to be created at paint device dpi (e.g. high resolution), - // then scale device painter by 1.0 / rasterCompressFactor for output - - QPainter* p = context.painter(); - double componentWidth = component.size().x(), componentHeight = component.size().y(); - double xOffset = component.offset().x(), yOffset = component.offset().y(); - double pictbuffer = component.pictureBuffer(); - - // generate pixmap representation of label component drawing - bool mapUnits = shadow.blurRadiusUnit() == QgsUnitTypes::RenderMapUnits; - double radius = QgsTextRenderer::scaleToPixelContext( shadow.blurRadius(), context, shadow.blurRadiusUnit(), !mapUnits, shadow.blurRadiusMapUnitScale() ); - radius /= ( mapUnits ? context.scaleFactor() / component.dpiRatio() : 1 ); - radius = static_cast< int >( radius + 0.5 ); - - // TODO: add labeling gui option to adjust blurBufferClippingScale to minimize pixels, or - // to ensure shadow isn't clipped too tight. (Or, find a better method of buffering) - double blurBufferClippingScale = 3.75; - int blurbuffer = ( radius > 17 ? 16 : radius ) * blurBufferClippingScale; - - QImage blurImg( componentWidth + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ), - componentHeight + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ), - QImage::Format_ARGB32_Premultiplied ); - - // TODO: add labeling gui option to not show any shadows under/over a certian size - // keep very small QImages from causing paint device issues, i.e. must be at least > 1 - int minBlurImgSize = 1; - // max limitation on QgsSvgCache is 10,000 for screen, which will probably be reasonable for future caching here, too - // 4 x QgsSvgCache limit for output to print/image at higher dpi - // TODO: should it be higher, scale with dpi, or have no limit? Needs testing with very large labels rendered at high dpi output - int maxBlurImgSize = 40000; - if ( blurImg.isNull() - || ( blurImg.width() < minBlurImgSize || blurImg.height() < minBlurImgSize ) - || ( blurImg.width() > maxBlurImgSize || blurImg.height() > maxBlurImgSize ) ) - return; - - blurImg.fill( QColor( Qt::transparent ).rgba() ); - QPainter pictp; - if ( !pictp.begin( &blurImg ) ) - return; - pictp.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); - QPointF imgOffset( blurbuffer + pictbuffer + xOffset, - blurbuffer + pictbuffer + componentHeight + yOffset ); - - pictp.drawPicture( imgOffset, - *component.picture() ); - - // overlay shadow color - pictp.setCompositionMode( QPainter::CompositionMode_SourceIn ); - pictp.fillRect( blurImg.rect(), shadow.color() ); - pictp.end(); - - // blur the QImage in-place - if ( shadow.blurRadius() > 0.0 && radius > 0 ) - { - QgsSymbolLayerUtils::blurImageInPlace( blurImg, blurImg.rect(), radius, shadow.blurAlphaOnly() ); - } - -#if 0 - // debug rect for QImage shadow registration and clipping visualization - QPainter picti; - picti.begin( &blurImg ); - picti.setBrush( Qt::Dense7Pattern ); - QPen imgPen( QColor( 0, 0, 255, 255 ) ); - imgPen.setWidth( 1 ); - picti.setPen( imgPen ); - picti.setOpacity( 0.1 ); - picti.drawRect( 0, 0, blurImg.width(), blurImg.height() ); - picti.end(); -#endif - - double offsetDist = QgsTextRenderer::scaleToPixelContext( shadow.offsetDistance(), context, - shadow.offsetUnit(), true, shadow.offsetMapUnitScale() ); - double angleRad = shadow.offsetAngle() * M_PI / 180; // to radians - if ( shadow.offsetGlobal() ) - { - // TODO: check for differences in rotation origin and cw/ccw direction, - // when this shadow function is used for something other than labels - - // it's 0-->cw-->360 for labels - //QgsDebugMsgLevel( QString( "Shadow aggregated label rotation (degrees): %1" ).arg( component.rotation() + component.rotationOffset() ), 4 ); - angleRad -= ( component.rotation() * M_PI / 180 + component.rotationOffset() * M_PI / 180 ); - } - - QPointF transPt( -offsetDist * cos( angleRad + M_PI / 2 ), - -offsetDist * sin( angleRad + M_PI / 2 ) ); - - p->save(); - p->setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); - if ( context.useAdvancedEffects() ) - { - p->setCompositionMode( shadow.blendMode() ); - } - p->setOpacity( shadow.opacity() ); - - double scale = shadow.scale() / 100.0; - // TODO: scale from center/center, left/center or left/top, instead of default left/bottom? - p->scale( scale, scale ); - if ( component.useOrigin() ) - { - p->translate( component.origin().x(), component.origin().y() ); - } - p->translate( transPt ); - p->translate( -imgOffset.x(), - -imgOffset.y() ); - p->drawImage( 0, 0, blurImg ); - p->restore(); - - // debug rects -#if 0 - // draw debug rect for QImage painting registration - p->save(); - p->setBrush( Qt::NoBrush ); - QPen imgPen( QColor( 255, 0, 0, 10 ) ); - imgPen.setWidth( 2 ); - imgPen.setStyle( Qt::DashLine ); - p->setPen( imgPen ); - p->scale( scale, scale ); - if ( component.useOrigin() ) - { - p->translate( component.origin().x(), component.origin().y() ); - } - p->translate( transPt ); - p->translate( -imgOffset.x(), - -imgOffset.y() ); - p->drawRect( 0, 0, blurImg.width(), blurImg.height() ); - p->restore(); - - // draw debug rect for passed in component dimensions - p->save(); - p->setBrush( Qt::NoBrush ); - QPen componentRectPen( QColor( 0, 255, 0, 70 ) ); - componentRectPen.setWidth( 1 ); - if ( component.useOrigin() ) - { - p->translate( component.origin().x(), component.origin().y() ); - } - p->setPen( componentRectPen ); - p->drawRect( QRect( -xOffset, -componentHeight - yOffset, componentWidth, componentHeight ) ); - p->restore(); -#endif -} - void QgsPalLabeling::loadEngineSettings() { mEngine->readSettingsFromProject(); diff --git a/src/core/qgspallabeling.h b/src/core/qgspallabeling.h index 5d08fc74ccd3..f67685413d42 100644 --- a/src/core/qgspallabeling.h +++ b/src/core/qgspallabeling.h @@ -731,102 +731,7 @@ class CORE_EXPORT QgsLabelCandidate double cost; }; -/** \ingroup core - * Maintains current state of more grainular and temporal values when creating/painting - * component parts of an individual label (e.g. buffer, background, shadow, etc.). - */ -class CORE_EXPORT QgsLabelComponent -{ - public: - QgsLabelComponent() - : mText( QString() ) - , mOrigin( QgsPoint() ) - , mUseOrigin( false ) - , mRotation( 0.0 ) - , mRotationOffset( 0.0 ) - , mUseRotation( false ) - , mCenter( QgsPoint() ) - , mUseCenter( false ) - , mSize( QgsPoint() ) - , mOffset( QgsPoint() ) - , mPicture( nullptr ) - , mPictureBuffer( 0.0 ) - , mDpiRatio( 1.0 ) - {} - - // methods - - QString text() const { return mText; } - void setText( const QString& text ) { mText = text; } - - const QgsPoint& origin() const { return mOrigin; } - void setOrigin( const QgsPoint& point ) { mOrigin = point; } - - bool useOrigin() const { return mUseOrigin; } - void setUseOrigin( const bool use ) { mUseOrigin = use; } - - double rotation() const { return mRotation; } - void setRotation( const double rotation ) { mRotation = rotation; } - - double rotationOffset() const { return mRotationOffset; } - void setRotationOffset( const double rotation ) { mRotationOffset = rotation; } - - bool useRotation() const { return mUseRotation; } - void setUseRotation( const bool use ) { mUseRotation = use; } - - const QgsPoint& center() const { return mCenter; } - void setCenter( const QgsPoint& point ) { mCenter = point; } - - bool useCenter() const { return mUseCenter; } - void setUseCenter( const bool use ) { mUseCenter = use; } - const QgsPoint& size() const { return mSize; } - void setSize( const QgsPoint& point ) { mSize = point; } - - const QgsPoint& offset() const { return mOffset; } - void setOffset( const QgsPoint& point ) { mOffset = point; } - - const QPicture* picture() const { return mPicture; } - void setPicture( QPicture* picture ) { mPicture = picture; } - - double pictureBuffer() const { return mPictureBuffer; } - void setPictureBuffer( const double buffer ) { mPictureBuffer = buffer; } - - double dpiRatio() const { return mDpiRatio; } - void setDpiRatio( const double ratio ) { mDpiRatio = ratio; } - - private: - // current label component text, - // e.g. single line in a multi-line label or charcater in curved labeling - QString mText; - // current origin point for painting (generally current painter rotation point) - QgsPoint mOrigin; - // whether to translate the painter to supplied origin - bool mUseOrigin; - // any rotation to be applied to painter (in radians) - double mRotation; - // any rotation to be applied to painter (in radians) after initial rotation - double mRotationOffset; - // whether to use the rotation to rotate the painter - bool mUseRotation; - // current center point of label compnent, after rotation - QgsPoint mCenter; - // whether to translate the painter to supplied origin based upon center - bool mUseCenter; - // width and height of label component, transformed and ready for painting - QgsPoint mSize; - // any translation offsets to be applied before painting, transformed and ready for painting - QgsPoint mOffset; - - // a stored QPicture of painting for the component - QPicture* mPicture; - // buffer for component to accommodate graphic items ignored by QPicture, - // e.g. half-width of an applied QPen, which would extend beyond boundingRect() of QPicture - double mPictureBuffer; - - // a ratio of native painter dpi and that of rendering context's painter - double mDpiRatio; -}; /** \ingroup core @@ -861,14 +766,6 @@ class CORE_EXPORT QgsLabelingResults class CORE_EXPORT QgsPalLabeling : public QgsLabelingEngineInterface { public: - enum DrawLabelType - { - LabelText = 0, - LabelBuffer, - LabelShape, - LabelSVG, - LabelShadow - }; QgsPalLabeling(); ~QgsPalLabeling(); @@ -955,18 +852,6 @@ class CORE_EXPORT QgsPalLabeling : public QgsLabelingEngineInterface //! @note not available in python bindings static void drawLabelCandidateRect( pal::LabelPosition* lp, QPainter* painter, const QgsMapToPixel* xform, QList* candidates = nullptr ); - static void drawLabelBuffer( QgsRenderContext& context, - const QgsLabelComponent &component, - const QgsTextFormat& format ); - - static void drawLabelBackground( QgsRenderContext& context, - QgsLabelComponent component, - const QgsTextFormat& format ); - - static void drawLabelShadow( QgsRenderContext &context, - const QgsLabelComponent &component, - const QgsTextFormat& format ); - //! load/save engine settings to project file void loadEngineSettings(); void saveEngineSettings(); diff --git a/src/core/qgstextrenderer.cpp b/src/core/qgstextrenderer.cpp index 2440b50d418c..54a47a7f237e 100644 --- a/src/core/qgstextrenderer.cpp +++ b/src/core/qgstextrenderer.cpp @@ -20,8 +20,22 @@ #include "qgsvectorlayer.h" #include "qgssymbollayerutils.h" #include "qgspainting.h" +#include "qgsmarkersymbollayer.h" #include +Q_GUI_EXPORT extern int qt_defaultDpiX(); +Q_GUI_EXPORT extern int qt_defaultDpiY(); + +static void _fixQPictureDPI( QPainter* p ) +{ + // QPicture makes an assumption that we drawing to it with system DPI. + // Then when being drawn, it scales the painter. The following call + // negates the effect. There is no way of setting QPicture's DPI. + // See QTBUG-20361 + p->scale( static_cast< double >( qt_defaultDpiX() ) / p->device()->logicalDpiX(), + static_cast< double >( qt_defaultDpiY() ) / p->device()->logicalDpiY() ); +} + static QColor _readColor( QgsVectorLayer* layer, const QString& property, const QColor& defaultColor = Qt::black, bool withAlpha = true ) { int r = layer->customProperty( property + 'R', QVariant( defaultColor.red() ) ).toInt(); @@ -1634,3 +1648,936 @@ double QgsTextRenderer::scaleToPixelContext( double size, const QgsRenderContext } return size; } + +void QgsTextRenderer::drawText( const QRectF& rect, double rotation, QgsTextRenderer::HAlignment alignment, const QStringList& textLines, QgsRenderContext& context, const QgsTextFormat& format, bool drawAsOutlines ) +{ + QgsTextFormat tmpFormat = updateShadowPosition( format ); + + if ( tmpFormat.background().enabled() ) + { + drawPart( rect, rotation, alignment, textLines, context, tmpFormat, Background, drawAsOutlines ); + } + + if ( tmpFormat.buffer().enabled() ) + { + drawPart( rect, rotation, alignment, textLines, context, tmpFormat, Buffer, drawAsOutlines ); + } + + drawPart( rect, rotation, alignment, textLines, context, tmpFormat, Text, drawAsOutlines ); +} + +void QgsTextRenderer::drawText( const QPointF& point, double rotation, QgsTextRenderer::HAlignment alignment, const QStringList& textLines, QgsRenderContext& context, const QgsTextFormat& format, bool drawAsOutlines ) +{ + QgsTextFormat tmpFormat = updateShadowPosition( format ); + + if ( tmpFormat.background().enabled() ) + { + drawPart( point, rotation, alignment, textLines, context, tmpFormat, Background, drawAsOutlines ); + } + + if ( tmpFormat.buffer().enabled() ) + { + drawPart( point, rotation, alignment, textLines, context, tmpFormat, Buffer, drawAsOutlines ); + } + + drawPart( point, rotation, alignment, textLines, context, tmpFormat, Text, drawAsOutlines ); +} + +QgsTextFormat QgsTextRenderer::updateShadowPosition( const QgsTextFormat& format ) +{ + if ( !format.shadow().enabled() || format.shadow().shadowPlacement() != QgsTextShadowSettings::ShadowLowest ) + return format; + + QgsTextFormat tmpFormat = format; + if ( tmpFormat.background().enabled() ) + { + tmpFormat.shadow().setShadowPlacement( QgsTextShadowSettings::ShadowShape ); + } + else if ( tmpFormat.buffer().enabled() ) + { + tmpFormat.shadow().setShadowPlacement( QgsTextShadowSettings::ShadowBuffer ); + } + else + { + tmpFormat.shadow().setShadowPlacement( QgsTextShadowSettings::ShadowText ); + } + return tmpFormat; +} + +void QgsTextRenderer::drawPart( const QRectF& rect, double rotation, HAlignment alignment, + const QStringList& textLines, QgsRenderContext& context, const QgsTextFormat& format, QgsTextRenderer::TextPart part, bool drawAsOutlines ) +{ + if ( !context.painter() ) + { + return; + } + + Component component; + component.dpiRatio = 1.0; + component.origin = rect.topLeft(); + component.rotation = rotation; + component.size = rect.size(); + component.hAlign = alignment; + + switch ( part ) + { + case Background: + { + if ( !format.background().enabled() ) + return; + + if ( !qgsDoubleNear( rotation, 0.0 ) ) + { + // get rotated label's center point + + double xc = rect.width() / 2.0; + double yc = rect.height() / 2.0; + + double angle = -rotation; + double xd = xc * cos( angle ) - yc * sin( angle ); + double yd = xc * sin( angle ) + yc * cos( angle ); + + component.center = QPointF( component.origin.x() + xd, component.origin.y() + yd ); + } + else + { + component.center = rect.center(); + } + + QgsTextRenderer::drawBackground( context, component, format, textLines, Rect ); + + break; + } + + case Buffer: + { + if ( !format.buffer().enabled() ) + break; + } + FALLTHROUGH; + case Text: + case Shadow: + { + QFontMetricsF fm( format.scaledFont( context ) ); + drawTextInternal( part, context, format, component, + textLines, + &fm, + alignment, + drawAsOutlines ); + break; + } + } +} + +void QgsTextRenderer::drawPart( const QPointF& origin, double rotation, QgsTextRenderer::HAlignment alignment, const QStringList& textLines, QgsRenderContext& context, const QgsTextFormat& format, QgsTextRenderer::TextPart part, bool drawAsOutlines ) +{ + if ( !context.painter() ) + { + return; + } + + Component component; + component.dpiRatio = 1.0; + component.origin = origin; + component.rotation = rotation; + component.hAlign = alignment; + + switch ( part ) + { + case Background: + { + if ( !format.background().enabled() ) + return; + + QgsTextRenderer::drawBackground( context, component, format, textLines, Point ); + break; + } + + case Buffer: + { + if ( !format.buffer().enabled() ) + break; + } + FALLTHROUGH; + case Text: + case Shadow: + { + QFontMetricsF fm( format.scaledFont( context ) ); + drawTextInternal( part, context, format, component, + textLines, + &fm, + alignment, + drawAsOutlines, + Point ); + break; + } + } +} + +void QgsTextRenderer::drawBuffer( QgsRenderContext& context, const QgsTextRenderer::Component& component, const QgsTextFormat& format ) +{ + QPainter* p = context.painter(); + + QgsTextBufferSettings buffer = format.buffer(); + + double penSize = QgsTextRenderer::scaleToPixelContext( buffer.size(), context, + buffer.sizeUnit(), true, buffer.sizeMapUnitScale() ); + + QPainterPath path; + path.setFillRule( Qt::WindingFill ); + path.addText( 0, 0, format.scaledFont( context ), component.text ); + QColor bufferColor = buffer.color(); + bufferColor.setAlphaF( buffer.opacity() ); + QPen pen( bufferColor ); + pen.setWidthF( penSize ); + pen.setJoinStyle( buffer.joinStyle() ); + QColor tmpColor( bufferColor ); + // honor pref for whether to fill buffer interior + if ( !buffer.fillBufferInterior() ) + { + tmpColor.setAlpha( 0 ); + } + + // store buffer's drawing in QPicture for drop shadow call + QPicture buffPict; + QPainter buffp; + buffp.begin( &buffPict ); + buffp.setPen( pen ); + buffp.setBrush( tmpColor ); + buffp.drawPath( path ); + buffp.end(); + + if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowBuffer ) + { + QgsTextRenderer::Component bufferComponent = component; + bufferComponent.origin = QPointF( 0.0, 0.0 ); + bufferComponent.picture = buffPict; + bufferComponent.pictureBuffer = penSize / 2.0; + drawShadow( context, bufferComponent, format ); + } + + p->save(); + if ( context.useAdvancedEffects() ) + { + p->setCompositionMode( buffer.blendMode() ); + } + + // scale for any print output or image saving @ specific dpi + p->scale( component.dpiRatio, component.dpiRatio ); + _fixQPictureDPI( p ); + p->drawPicture( 0, 0, buffPict ); + p->restore(); +} + +double QgsTextRenderer::textWidth( const QgsRenderContext& context, const QgsTextFormat& format, const QStringList &textLines, QFontMetricsF* fm ) +{ + //calculate max width of text lines + QScopedPointer< QFontMetricsF > newFm; + if ( !fm ) + { + newFm.reset( new QFontMetricsF( format.scaledFont( context ) ) ); + fm = newFm.data(); + } + + double maxWidth = 0; + Q_FOREACH ( const QString& line, textLines ) + { + maxWidth = qMax( maxWidth, fm->width( line ) ); + } + return maxWidth; +} + +double QgsTextRenderer::textHeight( const QgsRenderContext& context, const QgsTextFormat& format, const QStringList& textLines, DrawMode mode, QFontMetricsF* fm ) +{ + //calculate max width of text lines + QScopedPointer< QFontMetricsF > newFm; + if ( !fm ) + { + newFm.reset( new QFontMetricsF( format.scaledFont( context ) ) ); + fm = newFm.data(); + } + + double labelHeight = fm->ascent() + fm->descent(); // ignore +1 for baseline + + switch ( mode ) + { + case Label: + // rendering labels needs special handling - in this case text should be + // drawn with the bottom left corner coinciding with origin, vs top left + // for standard text rendering. Line height is also slightly different. + return labelHeight + ( textLines.size() - 1 ) * labelHeight * format.lineHeight(); + + case Rect: + case Point: + // standard rendering - designed to exactly replicate QPainter's drawText method + return labelHeight + ( textLines.size() - 1 ) * fm->lineSpacing() * format.lineHeight(); + } + + return 0; +} + +void QgsTextRenderer::drawBackground( QgsRenderContext& context, QgsTextRenderer::Component component, const QgsTextFormat& format, + const QStringList& textLines, DrawMode mode ) +{ + QgsTextBackgroundSettings background = format.background(); + + QPainter* p = context.painter(); + //QgsDebugMsgLevel( QString( "Background label rotation: %1" ).arg( component.rotation() ), 4 ); + + // shared calculations between shapes and SVG + + // configure angles, set component rotation and rotationOffset + if ( background.rotationType() != QgsTextBackgroundSettings::RotationFixed ) + { + component.rotation = -( component.rotation * 180 / M_PI ); // RotationSync + component.rotationOffset = + background.rotationType() == QgsTextBackgroundSettings::RotationOffset ? background.rotation() : 0.0; + } + else // RotationFixed + { + component.rotation = 0.0; // don't use label's rotation + component.rotationOffset = background.rotation(); + } + + if ( mode != Label ) + { + // need to calculate size of text + QFontMetricsF fm( format.scaledFont( context ) ); + double width = textWidth( context, format, textLines, &fm ); + double height = textHeight( context, format, textLines, mode, &fm ); + + switch ( mode ) + { + case Rect: + switch ( component.hAlign ) + { + case AlignLeft: + component.center = QPointF( component.origin.x() + width / 2.0, + component.origin.y() + height / 2.0 ); + break; + + case AlignCenter: + component.center = QPointF( component.origin.x() + component.size.width() / 2.0, + component.origin.y() + height / 2.0 ); + break; + + case AlignRight: + component.center = QPointF( component.origin.x() + component.size.width() - width / 2.0, + component.origin.y() + height / 2.0 ); + break; + } + break; + + case Point: + { + double originAdjust = fm.ascent() / 2.0 - fm.leading() / 2.0; + switch ( component.hAlign ) + { + case AlignLeft: + component.center = QPointF( component.origin.x() + width / 2.0, + component.origin.y() - height / 2.0 + originAdjust ); + break; + + case AlignCenter: + component.center = QPointF( component.origin.x(), + component.origin.y() - height / 2.0 + originAdjust ); + break; + + case AlignRight: + component.center = QPointF( component.origin.x() - width / 2.0, + component.origin.y() - height / 2.0 + originAdjust ); + break; + } + } + + case Label: + break; + } + + if ( format.background().sizeType() != QgsTextBackgroundSettings::SizeFixed ) + component.size = QSizeF( width, height ); + } + + // TODO: the following label-buffered generated shapes and SVG symbols should be moved into marker symbology classes + + if ( background.type() == QgsTextBackgroundSettings::ShapeSVG ) + { + // all calculations done in shapeSizeUnits, which are then passed to symbology class for painting + + if ( background.svgFile().isEmpty() ) + return; + + double sizeOut = 0.0; + // only one size used for SVG sizing/scaling (no use of shapeSize.y() or Y field in gui) + if ( background.sizeType() == QgsTextBackgroundSettings::SizeFixed ) + { + sizeOut = scaleToPixelContext( background.size().width(), context, background.sizeUnit(), + false, background.sizeMapUnitScale() ); + } + else if ( background.sizeType() == QgsTextBackgroundSettings::SizeBuffer ) + { + sizeOut = qMax( component.size.width(), component.size.height() ); + double bufferSize = scaleToPixelContext( background.size().width(), context, background.sizeUnit(), + false, background.sizeMapUnitScale() ); + + // add buffer + sizeOut += bufferSize * 2; + } + + // don't bother rendering symbols smaller than 1x1 pixels in size + // TODO: add option to not show any svgs under/over a certain size + if ( sizeOut < 1.0 ) + return; + + QgsStringMap map; // for SVG symbology marker + map["name"] = QgsSymbolLayerUtils::symbolNameToPath( background.svgFile().trimmed() ); + map["size"] = QString::number( sizeOut ); + map["size_unit"] = QgsUnitTypes::encodeUnit( QgsUnitTypes::RenderPixels ); + map["angle"] = QString::number( 0.0 ); // angle is handled by this local painter + + // offset is handled by this local painter + // TODO: see why the marker renderer doesn't seem to translate offset *after* applying rotation + //map["offset"] = QgsSymbolLayerUtils::encodePoint( tmpLyr.shapeOffset ); + //map["offset_unit"] = QgsUnitTypes::encodeUnit( + // tmpLyr.shapeOffsetUnits == QgsPalLayerSettings::MapUnits ? QgsUnitTypes::MapUnit : QgsUnitTypes::MM ); + + map["fill"] = background.fillColor().name(); + map["outline"] = background.borderColor().name(); + map["outline-width"] = QString::number( background.borderWidth() ); + map["outline_width_unit"] = QgsUnitTypes::encodeUnit( background.borderWidthUnit() ); + + if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowShape ) + { + QgsTextShadowSettings shadow = format.shadow(); + // configure SVG shadow specs + QgsStringMap shdwmap( map ); + shdwmap["fill"] = shadow.color().name(); + shdwmap["outline"] = shadow.color().name(); + shdwmap["size"] = QString::number( sizeOut * context.rasterScaleFactor() ); + + // store SVG's drawing in QPicture for drop shadow call + QPicture svgPict; + QPainter svgp; + svgp.begin( &svgPict ); + + // draw shadow symbol + + // clone current render context map unit/mm conversion factors, but not + // other map canvas parameters, then substitute this painter for use in symbology painting + // NOTE: this is because the shadow needs to be scaled correctly for output to map canvas, + // but will be created relative to the SVG's computed size, not the current map canvas + QgsRenderContext shdwContext; + shdwContext.setMapToPixel( context.mapToPixel() ); + shdwContext.setScaleFactor( context.scaleFactor() ); + shdwContext.setPainter( &svgp ); + + QgsSymbolLayer* symShdwL = QgsSvgMarkerSymbolLayer::create( shdwmap ); + QgsSvgMarkerSymbolLayer* svgShdwM = static_cast( symShdwL ); + QgsSymbolRenderContext svgShdwContext( shdwContext, QgsUnitTypes::RenderUnknownUnit, background.opacity() ); + + svgShdwM->renderPoint( QPointF( sizeOut / 2, -sizeOut / 2 ), svgShdwContext ); + svgp.end(); + + component.picture = svgPict; + // TODO: when SVG symbol's border width/units is fixed in QgsSvgCache, adjust for it here + component.pictureBuffer = 0.0; + + component.size = QSizeF( sizeOut, sizeOut ); + component.offset = QPointF( 0.0, 0.0 ); + + // rotate about origin center of SVG + p->save(); + p->translate( component.center.x(), component.center.y() ); + p->rotate( component.rotation ); + p->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); + double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), true, background.offsetMapUnitScale() ); + double yoff = QgsTextRenderer::scaleToPixelContext( background.offset().y(), context, background.offsetUnit(), true, background.offsetMapUnitScale() ); + p->translate( QPointF( xoff, yoff ) ); + p->rotate( component.rotationOffset ); + p->translate( -sizeOut / 2, sizeOut / 2 ); + + drawShadow( context, component, format ); + p->restore(); + + delete svgShdwM; + svgShdwM = nullptr; + } + + // draw the actual symbol + QgsSymbolLayer* symL = QgsSvgMarkerSymbolLayer::create( map ); + QgsSvgMarkerSymbolLayer* svgM = static_cast( symL ); + QgsSymbolRenderContext svgContext( context, QgsUnitTypes::RenderUnknownUnit, background.opacity() ); + + p->save(); + if ( context.useAdvancedEffects() ) + { + p->setCompositionMode( background.blendMode() ); + } + p->translate( component.center.x(), component.center.y() ); + p->rotate( component.rotation ); + double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); + double yoff = QgsTextRenderer::scaleToPixelContext( background.offset().y(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); + p->translate( QPointF( xoff, yoff ) ); + p->rotate( component.rotationOffset ); + svgM->renderPoint( QPointF( 0, 0 ), svgContext ); + p->setCompositionMode( QPainter::CompositionMode_SourceOver ); // just to be sure + p->restore(); + + delete svgM; + svgM = nullptr; + + } + else // Generated Shapes + { + double w = component.size.width(); + double h = component.size.height(); + + if ( background.sizeType() == QgsTextBackgroundSettings::SizeFixed ) + { + w = scaleToPixelContext( background.size().width(), context, background.sizeUnit(), + false, background.sizeMapUnitScale() ); + h = scaleToPixelContext( background.size().height(), context, background.sizeUnit(), + false, background.sizeMapUnitScale() ); + } + else if ( background.sizeType() == QgsTextBackgroundSettings::SizeBuffer ) + { + if ( background.type() == QgsTextBackgroundSettings::ShapeSquare ) + { + if ( w > h ) + h = w; + else if ( h > w ) + w = h; + } + else if ( background.type() == QgsTextBackgroundSettings::ShapeCircle ) + { + // start with label bound by circle + h = sqrt( pow( w, 2 ) + pow( h, 2 ) ); + w = h; + } + else if ( background.type() == QgsTextBackgroundSettings::ShapeEllipse ) + { + // start with label bound by ellipse + h = h / sqrt( 2.0 ) * 2; + w = w / sqrt( 2.0 ) * 2; + } + + double bufferWidth = scaleToPixelContext( background.size().width(), context, background.sizeUnit(), + false, background.sizeMapUnitScale() ); + double bufferHeight = scaleToPixelContext( background.size().height(), context, background.sizeUnit(), + false, background.sizeMapUnitScale() ); + + w += bufferWidth * 2; + h += bufferHeight * 2; + } + + // offsets match those of symbology: -x = left, -y = up + QRectF rect( -w / 2.0, - h / 2.0, w, h ); + + if ( rect.isNull() ) + return; + + p->save(); + p->translate( QPointF( component.center.x(), component.center.y() ) ); + p->rotate( component.rotation ); + double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); + double yoff = QgsTextRenderer::scaleToPixelContext( background.offset().y(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); + p->translate( QPointF( xoff, yoff ) ); + p->rotate( component.rotationOffset ); + + double penSize = QgsTextRenderer::scaleToPixelContext( background.borderWidth(), context, background.borderWidthUnit(), true, background.borderWidthMapUnitScale() ); + + QPen pen; + if ( background.borderWidth() > 0 ) + { + pen.setColor( background.borderColor() ); + pen.setWidthF( penSize ); + if ( background.type() == QgsTextBackgroundSettings::ShapeRectangle ) + pen.setJoinStyle( background.joinStyle() ); + } + else + { + pen = Qt::NoPen; + } + + // store painting in QPicture for shadow drawing + QPicture shapePict; + QPainter shapep; + shapep.begin( &shapePict ); + shapep.setPen( pen ); + shapep.setBrush( background.fillColor() ); + + if ( background.type() == QgsTextBackgroundSettings::ShapeRectangle + || background.type() == QgsTextBackgroundSettings::ShapeSquare ) + { + if ( background.radiiUnit() == QgsUnitTypes::RenderPercentage ) + { + shapep.drawRoundedRect( rect, background.radii().width(), background.radii().height(), Qt::RelativeSize ); + } + else + { + double xRadius = QgsTextRenderer::scaleToPixelContext( background.radii().width(), context, background.radiiUnit(), true, background.radiiMapUnitScale() ); + double yRadius = QgsTextRenderer::scaleToPixelContext( background.radii().height(), context, background.radiiUnit(), true, background.radiiMapUnitScale() ); + shapep.drawRoundedRect( rect, xRadius, yRadius ); + } + } + else if ( background.type() == QgsTextBackgroundSettings::ShapeEllipse + || background.type() == QgsTextBackgroundSettings::ShapeCircle ) + { + shapep.drawEllipse( rect ); + } + shapep.end(); + + p->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); + + if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowShape ) + { + component.picture = shapePict; + component.pictureBuffer = penSize / 2.0; + + component.size = rect.size(); + component.offset = QPointF( rect.width() / 2, -rect.height() / 2 ); + drawShadow( context, component, format ); + } + + p->setOpacity( background.opacity() ); + if ( context.useAdvancedEffects() ) + { + p->setCompositionMode( background.blendMode() ); + } + + // scale for any print output or image saving @ specific dpi + p->scale( component.dpiRatio, component.dpiRatio ); + _fixQPictureDPI( p ); + p->drawPicture( 0, 0, shapePict ); + p->restore(); + } +} + +void QgsTextRenderer::drawShadow( QgsRenderContext& context, const QgsTextRenderer::Component& component, const QgsTextFormat& format ) +{ + QgsTextShadowSettings shadow = format.shadow(); + + // incoming component sizes should be multiplied by rasterCompressFactor, as + // this allows shadows to be created at paint device dpi (e.g. high resolution), + // then scale device painter by 1.0 / rasterCompressFactor for output + + QPainter* p = context.painter(); + double componentWidth = component.size.width(), componentHeight = component.size.height(); + double xOffset = component.offset.x(), yOffset = component.offset.y(); + double pictbuffer = component.pictureBuffer; + + // generate pixmap representation of label component drawing + bool mapUnits = shadow.blurRadiusUnit() == QgsUnitTypes::RenderMapUnits; + double radius = QgsTextRenderer::scaleToPixelContext( shadow.blurRadius(), context, shadow.blurRadiusUnit(), !mapUnits, shadow.blurRadiusMapUnitScale() ); + radius /= ( mapUnits ? context.scaleFactor() / component.dpiRatio : 1 ); + radius = static_cast< int >( radius + 0.5 ); + + // TODO: add labeling gui option to adjust blurBufferClippingScale to minimize pixels, or + // to ensure shadow isn't clipped too tight. (Or, find a better method of buffering) + double blurBufferClippingScale = 3.75; + int blurbuffer = ( radius > 17 ? 16 : radius ) * blurBufferClippingScale; + + QImage blurImg( componentWidth + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ), + componentHeight + ( pictbuffer * 2.0 ) + ( blurbuffer * 2.0 ), + QImage::Format_ARGB32_Premultiplied ); + + // TODO: add labeling gui option to not show any shadows under/over a certian size + // keep very small QImages from causing paint device issues, i.e. must be at least > 1 + int minBlurImgSize = 1; + // max limitation on QgsSvgCache is 10,000 for screen, which will probably be reasonable for future caching here, too + // 4 x QgsSvgCache limit for output to print/image at higher dpi + // TODO: should it be higher, scale with dpi, or have no limit? Needs testing with very large labels rendered at high dpi output + int maxBlurImgSize = 40000; + if ( blurImg.isNull() + || ( blurImg.width() < minBlurImgSize || blurImg.height() < minBlurImgSize ) + || ( blurImg.width() > maxBlurImgSize || blurImg.height() > maxBlurImgSize ) ) + return; + + blurImg.fill( QColor( Qt::transparent ).rgba() ); + QPainter pictp; + if ( !pictp.begin( &blurImg ) ) + return; + pictp.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); + QPointF imgOffset( blurbuffer + pictbuffer + xOffset, + blurbuffer + pictbuffer + componentHeight + yOffset ); + + pictp.drawPicture( imgOffset, + component.picture ); + + // overlay shadow color + pictp.setCompositionMode( QPainter::CompositionMode_SourceIn ); + pictp.fillRect( blurImg.rect(), shadow.color() ); + pictp.end(); + + // blur the QImage in-place + if ( shadow.blurRadius() > 0.0 && radius > 0 ) + { + QgsSymbolLayerUtils::blurImageInPlace( blurImg, blurImg.rect(), radius, shadow.blurAlphaOnly() ); + } + +#if 0 + // debug rect for QImage shadow registration and clipping visualization + QPainter picti; + picti.begin( &blurImg ); + picti.setBrush( Qt::Dense7Pattern ); + QPen imgPen( QColor( 0, 0, 255, 255 ) ); + imgPen.setWidth( 1 ); + picti.setPen( imgPen ); + picti.setOpacity( 0.1 ); + picti.drawRect( 0, 0, blurImg.width(), blurImg.height() ); + picti.end(); +#endif + + double offsetDist = QgsTextRenderer::scaleToPixelContext( shadow.offsetDistance(), context, + shadow.offsetUnit(), true, shadow.offsetMapUnitScale() ); + double angleRad = shadow.offsetAngle() * M_PI / 180; // to radians + if ( shadow.offsetGlobal() ) + { + // TODO: check for differences in rotation origin and cw/ccw direction, + // when this shadow function is used for something other than labels + + // it's 0-->cw-->360 for labels + //QgsDebugMsgLevel( QString( "Shadow aggregated label rotation (degrees): %1" ).arg( component.rotation() + component.rotationOffset() ), 4 ); + angleRad -= ( component.rotation * M_PI / 180 + component.rotationOffset * M_PI / 180 ); + } + + QPointF transPt( -offsetDist * cos( angleRad + M_PI / 2 ), + -offsetDist * sin( angleRad + M_PI / 2 ) ); + + p->save(); + p->setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); + if ( context.useAdvancedEffects() ) + { + p->setCompositionMode( shadow.blendMode() ); + } + p->setOpacity( shadow.opacity() ); + + double scale = shadow.scale() / 100.0; + // TODO: scale from center/center, left/center or left/top, instead of default left/bottom? + p->scale( scale, scale ); + if ( component.useOrigin ) + { + p->translate( component.origin.x(), component.origin.y() ); + } + p->translate( transPt ); + p->translate( -imgOffset.x(), + -imgOffset.y() ); + p->drawImage( 0, 0, blurImg ); + p->restore(); + + // debug rects +#if 0 + // draw debug rect for QImage painting registration + p->save(); + p->setBrush( Qt::NoBrush ); + QPen imgPen( QColor( 255, 0, 0, 10 ) ); + imgPen.setWidth( 2 ); + imgPen.setStyle( Qt::DashLine ); + p->setPen( imgPen ); + p->scale( scale, scale ); + if ( component.useOrigin() ) + { + p->translate( component.origin().x(), component.origin().y() ); + } + p->translate( transPt ); + p->translate( -imgOffset.x(), + -imgOffset.y() ); + p->drawRect( 0, 0, blurImg.width(), blurImg.height() ); + p->restore(); + + // draw debug rect for passed in component dimensions + p->save(); + p->setBrush( Qt::NoBrush ); + QPen componentRectPen( QColor( 0, 255, 0, 70 ) ); + componentRectPen.setWidth( 1 ); + if ( component.useOrigin() ) + { + p->translate( component.origin().x(), component.origin().y() ); + } + p->setPen( componentRectPen ); + p->drawRect( QRect( -xOffset, -componentHeight - yOffset, componentWidth, componentHeight ) ); + p->restore(); +#endif +} + +void QgsTextRenderer::drawTextInternal( TextPart drawType, + QgsRenderContext& context, + const QgsTextFormat& format, + const Component& component, + const QStringList& textLines, + const QFontMetricsF *fontMetrics, + HAlignment alignment, + bool drawAsOutlines + , DrawMode mode ) +{ + if ( !context.painter() ) + { + return; + } + + double labelWidest = 0.0; + switch ( mode ) + { + case Label: + case Point: + Q_FOREACH ( const QString& line, textLines ) + { + double labelWidth = fontMetrics->width( line ); + if ( labelWidth > labelWidest ) + { + labelWidest = labelWidth; + } + } + break; + + case Rect: + labelWidest = component.size.width(); + break; + } + + double labelHeight = fontMetrics->ascent() + fontMetrics->descent(); // ignore +1 for baseline + // double labelHighest = labelfm->height() + ( double )(( lines - 1 ) * labelHeight * tmpLyr.multilineHeight ); + + // needed to move bottom of text's descender to within bottom edge of label + double ascentOffset = 0.25 * fontMetrics->ascent(); // labelfm->descent() is not enough + + int i = 0; + + bool adjustForAlignment = alignment != AlignLeft && ( mode != Label || textLines.size() > 1 ); + + Q_FOREACH ( const QString& line, textLines ) + { + context.painter()->save(); + context.painter()->translate( component.origin ); + if ( !qgsDoubleNear( component.rotation, 0.0 ) ) + context.painter()->rotate( -component.rotation * 180 / M_PI ); + + // scale down painter: the font size has been multiplied by raster scale factor + // to workaround a Qt font scaling bug with small font sizes + context.painter()->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); + + // figure x offset for horizontal alignment of multiple lines + double xMultiLineOffset = 0.0; + double labelWidth = fontMetrics->width( line ); + if ( adjustForAlignment ) + { + double labelWidthDiff = labelWidest - labelWidth; + if ( alignment == AlignCenter ) + { + labelWidthDiff /= 2; + } + switch ( mode ) + { + case Label: + case Rect: + xMultiLineOffset = labelWidthDiff; + break; + + case Point: + if ( alignment == AlignRight ) + xMultiLineOffset = labelWidthDiff - labelWidest; + else if ( alignment == AlignCenter ) + xMultiLineOffset = labelWidthDiff - labelWidest / 2.0; + + break; + } + //QgsDebugMsgLevel( QString( "xMultiLineOffset: %1" ).arg( xMultiLineOffset ), 4 ); + } + + double yMultiLineOffset = 0.0; + switch ( mode ) + { + case Label: + // rendering labels needs special handling - in this case text should be + // drawn with the bottom left corner coinciding with origin, vs top left + // for standard text rendering. Line height is also slightly different. + yMultiLineOffset = - ascentOffset - ( textLines.size() - 1 - i ) * labelHeight * format.lineHeight(); + break; + + case Rect: + // standard rendering - designed to exactly replicate QPainter's drawText method + yMultiLineOffset = - ascentOffset + labelHeight - 1 /*baseline*/ + format.lineHeight() * fontMetrics->lineSpacing() * i; + break; + + case Point: + // standard rendering - designed to exactly replicate QPainter's drawText rect method + yMultiLineOffset = 0 - ( textLines.size() - 1 - i ) * fontMetrics->lineSpacing() * format.lineHeight(); + break; + + } + + context.painter()->translate( QPointF( xMultiLineOffset, yMultiLineOffset ) ); + + Component subComponent; + subComponent.text = line; + subComponent.size = QSizeF( labelWidth, labelHeight ); + subComponent.offset = QPointF( 0.0, -ascentOffset ); + subComponent.rotation = -component.rotation * 180 / M_PI; + subComponent.rotationOffset = 0.0; + + if ( drawType == QgsTextRenderer::Buffer ) + { + QgsTextRenderer::drawBuffer( context, subComponent, format ); + } + else + { + // draw text, QPainterPath method + QPainterPath path; + path.setFillRule( Qt::WindingFill ); + path.addText( 0, 0, format.scaledFont( context ), subComponent.text ); + + // store text's drawing in QPicture for drop shadow call + QPicture textPict; + QPainter textp; + textp.begin( &textPict ); + textp.setPen( Qt::NoPen ); + QColor textColor = format.color(); + textColor.setAlphaF( format.opacity() ); + textp.setBrush( textColor ); + textp.drawPath( path ); + // TODO: why are some font settings lost on drawPicture() when using drawText() inside QPicture? + // e.g. some capitalization options, but not others + //textp.setFont( tmpLyr.textFont ); + //textp.setPen( tmpLyr.textColor ); + //textp.drawText( 0, 0, component.text() ); + textp.end(); + + if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowText ) + { + subComponent.picture = textPict; + subComponent.pictureBuffer = 0.0; // no pen width to deal with + subComponent.origin = QPointF( 0.0, 0.0 ); + + QgsTextRenderer::drawShadow( context, subComponent, format ); + } + + // paint the text + if ( context.useAdvancedEffects() ) + { + context.painter()->setCompositionMode( format.blendMode() ); + } + + // scale for any print output or image saving @ specific dpi + context.painter()->scale( subComponent.dpiRatio, subComponent.dpiRatio ); + + if ( drawAsOutlines ) + { + // draw outlined text + _fixQPictureDPI( context.painter() ); + context.painter()->drawPicture( 0, 0, textPict ); + } + else + { + // draw text as text (for SVG and PDF exports) + context.painter()->setFont( format.scaledFont( context ) ); + QColor textColor = format.color(); + textColor.setAlphaF( format.opacity() ); + context.painter()->setPen( textColor ); + context.painter()->setRenderHint( QPainter::TextAntialiasing ); + context.painter()->drawText( 0, 0, subComponent.text ); + } + } + context.painter()->restore(); + i++; + } +} diff --git a/src/core/qgstextrenderer.h b/src/core/qgstextrenderer.h index 72b0a0f05413..d36b266f18af 100644 --- a/src/core/qgstextrenderer.h +++ b/src/core/qgstextrenderer.h @@ -21,6 +21,7 @@ #include "qgsunittypes.h" #include #include +#include class QgsTextBufferSettingsPrivate; class QgsTextBackgroundSettingsPrivate; @@ -210,7 +211,7 @@ class CORE_EXPORT QgsTextBackgroundSettings enum ShapeType { ShapeRectangle = 0, /*!< rectangle */ - ShapeSquare, /*!< square */ + ShapeSquare, /*!< square - buffered sizes only*/ ShapeEllipse, /*!< ellipse */ ShapeCircle, /*!< circle */ ShapeSVG /*!< SVG file */ @@ -1096,11 +1097,34 @@ class CORE_EXPORT QgsTextFormat }; +/** \class QgsTextRenderer + * \ingroup core + * Handles rendering text using rich formatting options, including drop shadows, buffers + * and background shapes. + * \note added in QGIS 3.0 + */ class CORE_EXPORT QgsTextRenderer { public: + //! Components of text + enum TextPart + { + Text = 0, //!< Text component + Buffer, //!< Buffer component + Background, //!< Background shape + Shadow, //!< Drop shadow + }; + + //! Horizontal alignment + enum HAlignment + { + AlignLeft = 0, //!< Left align + AlignCenter, //!< Center align + AlignRight, //!< Right align + }; + /** Calculates pixel size (considering output size should be in pixel or map units, scale factors and optionally oversampling) * @param size size to convert * @param c rendercontext @@ -1121,6 +1145,157 @@ class CORE_EXPORT QgsTextRenderer */ static double scaleToPixelContext( double size, const QgsRenderContext& c, QgsUnitTypes::RenderUnit unit, bool rasterfactor = false, const QgsMapUnitScale& mapUnitScale = QgsMapUnitScale() ); + /** Draws text within a rectangle using the specified settings. + * @param rect destination rectangle for text + * @param rotation text rotation + * @param alignment horizontal alignment + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawText( const QRectF& rect, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + bool drawAsOutlines = true ); + + /** Draws text at a point origin using the specified settings. + * @param point origin of text + * @param rotation text rotation + * @param alignment horizontal alignment + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawText( const QPointF& point, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + bool drawAsOutlines = true ); + + /** Draws a single component of rendered text using the specified settings. + * @param rect destination rectangle for text + * @param rotation text rotation + * @param alignment horizontal alignment + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param part component of text to draw. Note that Shadow parts cannot be drawn + * individually and instead are drawn with their associated part (eg drawn together + * with the text or background parts) + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawPart( const QRectF& rect, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + TextPart part, bool drawAsOutlines = true ); + + /** Draws a single component of rendered text using the specified settings. + * @param origin origin for start of text. Y coordinate will be used as baseline. + * @param rotation text rotation + * @param alignment horizontal alignment + * @param textLines list of lines of text to draw + * @param context render context + * @param format text format + * @param part component of text to draw. Note that Shadow parts cannot be drawn + * individually and instead are drawn with their associated part (eg drawn together + * with the text or background parts) + * @param drawAsOutlines set to false to render text as text. This allows outputs to + * formats like SVG to maintain text as text objects, but at the cost of degraded + * rendering and may result in side effects like misaligned text buffers. + */ + static void drawPart( const QPointF& origin, double rotation, HAlignment alignment, const QStringList& textLines, + QgsRenderContext& context, const QgsTextFormat& format, + TextPart part, bool drawAsOutlines = true ); + + private: + + enum DrawMode + { + Rect = 0, + Point, + Label, + }; + + struct Component + { + Component() + : useOrigin( false ) + , rotation( 0.0 ) + , rotationOffset( 0.0 ) + , pictureBuffer( 0.0 ) + , dpiRatio( 1.0 ) + , hAlign( AlignLeft ) + {} + + //! Component text + QString text; + //! Current origin point for painting (generally current painter rotation point) + QPointF origin; + //! Whether to translate the painter to supplied origin + bool useOrigin; + //! Any rotation to be applied to painter (in radians) + double rotation; + //! Any rotation to be applied to painter (in radians) after initial rotation + double rotationOffset; + //! Current center point of label component, after rotation + QPointF center; + //! Width and height of label component, transformed and ready for painting + QSizeF size; + //! Any translation offsets to be applied before painting, transformed and ready for painting + QPointF offset; + //! A stored QPicture of painting for the component + QPicture picture; + //! Buffer for component to accommodate graphic items ignored by QPicture, + //! e.g. half-width of an applied QPen, which would extend beyond boundingRect() of QPicture + double pictureBuffer; + //! A ratio of native painter dpi and that of rendering context's painter + double dpiRatio; + //! Horizontal alignment + HAlignment hAlign; + }; + + static void drawBuffer( QgsRenderContext& context, + const Component &component, + const QgsTextFormat& format ); + + static void drawBackground( QgsRenderContext& context, + Component component, + const QgsTextFormat& format, + const QStringList& textLines, + DrawMode mode = Rect ); + + static void drawShadow( QgsRenderContext &context, + const Component &component, + const QgsTextFormat& format ); + + static void drawText( QgsRenderContext &context, + const Component &component, + const QgsTextFormat& format ); + + static void drawTextInternal( TextPart drawType, + QgsRenderContext& context, + const QgsTextFormat& format, + const Component& component, + const QStringList& textLines, + const QFontMetricsF *fontMetrics, + HAlignment alignment, + bool drawAsOutlines, + DrawMode mode = Rect ); + + friend class QgsVectorLayerLabelProvider; + friend class QgsLabelPreview; + + static QgsTextFormat updateShadowPosition( const QgsTextFormat& format ); + + static double textWidth( const QgsRenderContext& context, const QgsTextFormat& format, const QStringList& textLines, + QFontMetricsF* fm = 0 ); + static double textHeight( const QgsRenderContext& context, const QgsTextFormat& format, const QStringList& textLines, DrawMode mode, + QFontMetricsF* fm = 0 ); + }; diff --git a/src/core/qgstextrenderer_p.h b/src/core/qgstextrenderer_p.h index 83f35c8c4241..741fd3797ee9 100644 --- a/src/core/qgstextrenderer_p.h +++ b/src/core/qgstextrenderer_p.h @@ -178,7 +178,7 @@ class CORE_EXPORT QgsTextShadowSettingsPrivate : public QSharedData , radiusUnits( QgsUnitTypes::RenderMillimeters ) , radiusAlphaOnly( false ) , scale( 100 ) - , color( QColor( 0, 0, 0, 76 ) ) + , color( QColor( 0, 0, 0 ) ) , opacity( 0.7 ) , blendMode( QPainter::CompositionMode_Multiply ) { diff --git a/src/core/qgsvectorlayerlabelprovider.cpp b/src/core/qgsvectorlayerlabelprovider.cpp index 93de335dff2d..0bf77029d78c 100644 --- a/src/core/qgsvectorlayerlabelprovider.cpp +++ b/src/core/qgsvectorlayerlabelprovider.cpp @@ -35,21 +35,6 @@ using namespace pal; -Q_GUI_EXPORT extern int qt_defaultDpiX(); -Q_GUI_EXPORT extern int qt_defaultDpiY(); - -static void _fixQPictureDPI( QPainter* p ) -{ - // QPicture makes an assumption that we drawing to it with system DPI. - // Then when being drawn, it scales the painter. The following call - // negates the effect. There is no way of setting QPicture's DPI. - // See QTBUG-20361 - p->scale( static_cast< double >( qt_defaultDpiX() ) / p->device()->logicalDpiX(), - static_cast< double >( qt_defaultDpiY() ) / p->device()->logicalDpiY() ); -} - - - QgsVectorLayerLabelProvider::QgsVectorLayerLabelProvider( QgsVectorLayer* layer, const QString& providerId, bool withFeatureLoop, const QgsPalLayerSettings* settings, const QString& layerName ) : QgsAbstractLabelProvider( layer->id(), providerId ) , mSettings( settings ? *settings : QgsPalLayerSettings::fromLayer( layer ) ) @@ -477,15 +462,15 @@ void QgsVectorLayerLabelProvider::drawLabel( QgsRenderContext& context, pal::Lab if ( tmpLyr.format().background().enabled() ) { - drawLabelPrivate( label, context, tmpLyr, QgsPalLabeling::LabelShape ); + drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Background ); } if ( tmpLyr.format().buffer().enabled() ) { - drawLabelPrivate( label, context, tmpLyr, QgsPalLabeling::LabelBuffer ); + drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Buffer ); } - drawLabelPrivate( label, context, tmpLyr, QgsPalLabeling::LabelText ); + drawLabelPrivate( label, context, tmpLyr, QgsTextRenderer::Text ); // add to the results QString labeltext = label->getFeaturePart()->feature()->labelText(); @@ -493,35 +478,24 @@ void QgsVectorLayerLabelProvider::drawLabel( QgsRenderContext& context, pal::Lab } -void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, QgsRenderContext& context, QgsPalLayerSettings& tmpLyr, QgsPalLabeling::DrawLabelType drawType, double dpiRatio ) const +void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, QgsRenderContext& context, QgsPalLayerSettings& tmpLyr, QgsTextRenderer::TextPart drawType, double dpiRatio ) const { // NOTE: this is repeatedly called for multi-part labels QPainter* painter = context.painter(); -#if 1 // XXX strk + // features are pre-rotated but not scaled/translated, // so we only disable rotation here. Ideally, they'd be // also pre-scaled/translated, as suggested here: // http://hub.qgis.org/issues/11856 QgsMapToPixel xform = context.mapToPixel(); xform.setMapRotation( 0, 0, 0 ); -#else - const QgsMapToPixel& xform = context.mapToPixel(); -#endif - QgsLabelComponent component; - component.setDpiRatio( dpiRatio ); - - QgsPoint outPt = xform.transform( label->getX(), label->getY() ); -// QgsPoint outPt2 = xform->transform( label->getX() + label->getWidth(), label->getY() + label->getHeight() ); -// QRectF labelRect( 0, 0, outPt2.x() - outPt.x(), outPt2.y() - outPt.y() ); - - component.setOrigin( outPt ); - component.setRotation( label->getAlpha() ); + QPointF outPt = xform.transform( label->getX(), label->getY() ).toQPointF(); if ( mEngine->testFlag( QgsLabelingEngine::DrawLabelRectOnly ) ) // TODO: this should get directly to labeling engine { //debugging rect - if ( drawType != QgsPalLabeling::LabelText ) + if ( drawType != QgsTextRenderer::Text ) return; QgsPoint outPt2 = xform.transform( label->getX() + label->getWidth(), label->getY() + label->getHeight() ); @@ -551,31 +525,43 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q return; } - if ( drawType == QgsPalLabeling::LabelShape ) + QgsTextRenderer::Component component; + component.dpiRatio = dpiRatio; + component.origin = outPt; + component.rotation = label->getAlpha(); + + + + if ( drawType == QgsTextRenderer::Background ) { // get rotated label's center point - QgsPoint centerPt( outPt ); + QPointF centerPt( outPt ); QgsPoint outPt2 = xform.transform( label->getX() + label->getWidth() / 2, label->getY() + label->getHeight() / 2 ); double xc = outPt2.x() - outPt.x(); double yc = outPt2.y() - outPt.y(); - double angle = -label->getAlpha(); + double angle = -component.rotation; double xd = xc * cos( angle ) - yc * sin( angle ); double yd = xc * sin( angle ) + yc * cos( angle ); centerPt.setX( centerPt.x() + xd ); centerPt.setY( centerPt.y() + yd ); - component.setCenter( centerPt ); - component.setSize( QgsPoint( label->getWidth(), label->getHeight() ) ); + component.center = centerPt; + + // convert label size to render units + double labelWidthPx = QgsTextRenderer::scaleToPixelContext( label->getWidth(), context, QgsUnitTypes::RenderMapUnits, true ); + double labelHeightPx = QgsTextRenderer::scaleToPixelContext( label->getHeight(), context, QgsUnitTypes::RenderMapUnits, true ); - QgsPalLabeling::drawLabelBackground( context, component, tmpLyr.format() ); + component.size = QSizeF( labelWidthPx, labelHeightPx ); + + QgsTextRenderer::drawBackground( context, component, tmpLyr.format(), QStringList(), QgsTextRenderer::Label ); } - else if ( drawType == QgsPalLabeling::LabelBuffer - || drawType == QgsPalLabeling::LabelText ) + else if ( drawType == QgsTextRenderer::Buffer + || drawType == QgsTextRenderer::Text ) { // TODO: optimize access :) @@ -633,148 +619,19 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q //QgsDebugMsgLevel( "drawLabel " + txt, 4 ); QStringList multiLineList = QgsPalLabeling::splitToLines( txt, tmpLyr.wrapChar ); - int lines = multiLineList.size(); - - double labelWidest = 0.0; - for ( int i = 0; i < lines; ++i ) - { - double labelWidth = labelfm->width( multiLineList.at( i ) ); - if ( labelWidth > labelWidest ) - { - labelWidest = labelWidth; - } - } - - double labelHeight = labelfm->ascent() + labelfm->descent(); // ignore +1 for baseline - // double labelHighest = labelfm->height() + ( double )(( lines - 1 ) * labelHeight * tmpLyr.multilineHeight ); - - // needed to move bottom of text's descender to within bottom edge of label - double ascentOffset = 0.25 * labelfm->ascent(); // labelfm->descent() is not enough - - for ( int i = 0; i < lines; ++i ) - { - painter->save(); -#if 0 // TODO: generalize some of this - LabelPosition* lp = label; - double w = lp->getWidth(); - double h = lp->getHeight(); - double cx = lp->getX() + w / 2.0; - double cy = lp->getY() + h / 2.0; - double scale = 1.0 / xform->mapUnitsPerPixel(); - double rotation = xform->mapRotation(); - double sw = w * scale; - double sh = h * scale; - QRectF rect( -sw / 2, -sh / 2, sw, sh ); - painter->translate( xform->transform( QPointF( cx, cy ) ).toQPointF() ); - if ( rotation ) - { - // Only if not horizontal - if ( lp->getFeaturePart()->getLayer()->getArrangement() != P_POINT && - lp->getFeaturePart()->getLayer()->getArrangement() != P_POINT_OVER && - lp->getFeaturePart()->getLayer()->getArrangement() != P_HORIZ ) - { - painter->rotate( rotation ); - } - } - painter->translate( rect.bottomLeft() ); - painter->rotate( -lp->getAlpha() * 180 / M_PI ); -#else - painter->translate( QPointF( outPt.x(), outPt.y() ) ); - painter->rotate( -label->getAlpha() * 180 / M_PI ); -#endif - - // scale down painter: the font size has been multiplied by raster scale factor - // to workaround a Qt font scaling bug with small font sizes - painter->scale( 1.0 / context.rasterScaleFactor(), 1.0 / context.rasterScaleFactor() ); - - // figure x offset for horizontal alignment of multiple lines - double xMultiLineOffset = 0.0; - double labelWidth = labelfm->width( multiLineList.at( i ) ); - if ( lines > 1 && tmpLyr.multilineAlign != QgsPalLayerSettings::MultiLeft ) - { - double labelWidthDiff = labelWidest - labelWidth; - if ( tmpLyr.multilineAlign == QgsPalLayerSettings::MultiCenter ) - { - labelWidthDiff /= 2; - } - xMultiLineOffset = labelWidthDiff; - //QgsDebugMsgLevel( QString( "xMultiLineOffset: %1" ).arg( xMultiLineOffset ), 4 ); - } - double yMultiLineOffset = ( lines - 1 - i ) * labelHeight * tmpLyr.format().lineHeight(); - painter->translate( QPointF( xMultiLineOffset, - ascentOffset - yMultiLineOffset ) ); + QgsTextRenderer::HAlignment hAlign = QgsTextRenderer::AlignLeft; + if ( tmpLyr.multilineAlign == QgsPalLayerSettings::MultiCenter ) + hAlign = QgsTextRenderer::AlignCenter; + else if ( tmpLyr.multilineAlign == QgsPalLayerSettings::MultiRight ) + hAlign = QgsTextRenderer::AlignRight; - component.setText( multiLineList.at( i ) ); - component.setSize( QgsPoint( labelWidth, labelHeight ) ); - component.setOffset( QgsPoint( 0.0, -ascentOffset ) ); - component.setRotation( -component.rotation() * 180 / M_PI ); - component.setRotationOffset( 0.0 ); + QgsTextRenderer::Component component; + component.origin = outPt; + component.rotation = label->getAlpha(); + QgsTextRenderer::drawTextInternal( drawType, context, tmpLyr.format(), component, multiLineList, labelfm, + hAlign, mEngine->testFlag( QgsLabelingEngine::RenderOutlineLabels ), QgsTextRenderer::Label ); - if ( drawType == QgsPalLabeling::LabelBuffer ) - { - // draw label's buffer - QgsPalLabeling::drawLabelBuffer( context, component, tmpLyr.format() ); - } - else - { - // draw label's text, QPainterPath method - QPainterPath path; - path.setFillRule( Qt::WindingFill ); - path.addText( 0, 0, tmpLyr.format().scaledFont( context ), component.text() ); - - // store text's drawing in QPicture for drop shadow call - QPicture textPict; - QPainter textp; - textp.begin( &textPict ); - textp.setPen( Qt::NoPen ); - QColor textColor = tmpLyr.format().color(); - textColor.setAlphaF( tmpLyr.format().opacity() ); - textp.setBrush( textColor ); - textp.drawPath( path ); - // TODO: why are some font settings lost on drawPicture() when using drawText() inside QPicture? - // e.g. some capitalization options, but not others - //textp.setFont( tmpLyr.textFont ); - //textp.setPen( tmpLyr.textColor ); - //textp.drawText( 0, 0, component.text() ); - textp.end(); - - if ( tmpLyr.format().shadow().enabled() && tmpLyr.format().shadow().shadowPlacement() == QgsTextShadowSettings::ShadowText ) - { - component.setPicture( &textPict ); - component.setPictureBuffer( 0.0 ); // no pen width to deal with - component.setOrigin( QgsPoint( 0.0, 0.0 ) ); - - QgsPalLabeling::drawLabelShadow( context, component, tmpLyr.format() ); - } - - // paint the text - if ( context.useAdvancedEffects() ) - { - painter->setCompositionMode( tmpLyr.format().blendMode() ); - } - - // scale for any print output or image saving @ specific dpi - painter->scale( component.dpiRatio(), component.dpiRatio() ); - - if ( mEngine->testFlag( QgsLabelingEngine::RenderOutlineLabels ) ) - { - // draw outlined text - _fixQPictureDPI( painter ); - painter->drawPicture( 0, 0, textPict ); - } - else - { - // draw text as text (for SVG and PDF exports) - painter->setFont( tmpLyr.format().scaledFont( context ) ); - QColor textColor = tmpLyr.format().color(); - textColor.setAlphaF( tmpLyr.format().opacity() ); - painter->setPen( textColor ); - painter->setRenderHint( QPainter::TextAntialiasing ); - painter->drawText( 0, 0, component.text() ); - } - } - painter->restore(); - } } // NOTE: this used to be within above multi-line loop block, at end. (a mistake since 2010? [LS]) diff --git a/src/core/qgsvectorlayerlabelprovider.h b/src/core/qgsvectorlayerlabelprovider.h index c3b88ca2f7f7..d1e4ab8c87bf 100644 --- a/src/core/qgsvectorlayerlabelprovider.h +++ b/src/core/qgsvectorlayerlabelprovider.h @@ -95,7 +95,7 @@ class CORE_EXPORT QgsVectorLayerLabelProvider : public QgsAbstractLabelProvider //! initialization method - called from constructors void init(); //! Internal label drawing method - void drawLabelPrivate( pal::LabelPosition* label, QgsRenderContext& context, QgsPalLayerSettings& tmpLyr, QgsPalLabeling::DrawLabelType drawType, double dpiRatio = 1.0 ) const; + void drawLabelPrivate( pal::LabelPosition* label, QgsRenderContext& context, QgsPalLayerSettings& tmpLyr, QgsTextRenderer::TextPart drawType, double dpiRatio = 1.0 ) const; protected: //! Layer's labeling configuration diff --git a/tests/src/python/test_qgstextrenderer.py b/tests/src/python/test_qgstextrenderer.py index f67f14ec2f60..6b59ce78f07f 100644 --- a/tests/src/python/test_qgstextrenderer.py +++ b/tests/src/python/test_qgstextrenderer.py @@ -13,6 +13,7 @@ __revision__ = '$Format:%H$' import qgis # NOQA +import os from qgis.core import (QgsTextBufferSettings, QgsTextBackgroundSettings, @@ -20,12 +21,17 @@ QgsTextFormat, QgsUnitTypes, QgsMapUnitScale, - QgsVectorLayer) -from qgis.PyQt.QtGui import (QColor, QPainter, QFont) -from qgis.PyQt.QtCore import (Qt, QSizeF, QPointF) + QgsVectorLayer, + QgsTextRenderer, + QgsMapSettings, + QgsRenderContext, + QgsRectangle, + QgsRenderChecker) +from qgis.PyQt.QtGui import (QColor, QPainter, QFont, QImage, QBrush, QPen) +from qgis.PyQt.QtCore import (Qt, QSizeF, QPointF, QRectF, QDir) from qgis.PyQt.QtXml import (QDomDocument, QDomElement) from qgis.testing import unittest, start_app -from utilities import getTestFont +from utilities import getTestFont, svgSymbolsPath start_app() @@ -38,6 +44,14 @@ def createEmptyLayer(): class PyQgsTextRenderer(unittest.TestCase): + def setUp(self): + self.report = "

                                                                                                                                                                                    Python QgsTextRenderer Tests

                                                                                                                                                                                    \n" + + def tearDown(self): + report_file_path = "%s/qgistest.html" % QDir.tempPath() + with open(report_file_path, 'a') as report_file: + report_file.write(self.report) + def createBufferSettings(self): s = QgsTextBufferSettings() s.setEnabled(True) @@ -402,6 +416,1227 @@ def testFontFoundFromXml(self): f.readXml(parent) self.assertTrue(f.fontFound()) + def imageCheck(self, name, reference_image, image): + self.report += "

                                                                                                                                                                                    Render {}

                                                                                                                                                                                    \n".format(name) + temp_dir = QDir.tempPath() + '/' + file_name = temp_dir + name + ".png" + image.save(file_name, "PNG") + checker = QgsRenderChecker() + checker.setControlPathPrefix("text_renderer") + checker.setControlName(reference_image) + checker.setRenderedImage(file_name) + checker.setColorTolerance(2) + result = checker.compareImages(name, 20) + self.report += checker.report() + print(checker.report()) + return result + + def checkRender(self, format, name, part=None, angle=0, alignment=QgsTextRenderer.AlignLeft, + text=['test'], + rect=QRectF(100, 100, 50, 250)): + + image = QImage(400, 400, QImage.Format_RGB32) + + painter = QPainter() + ms = QgsMapSettings() + ms.setExtent(QgsRectangle(0, 0, 50, 50)) + ms.setOutputSize(image.size()) + context = QgsRenderContext.fromMapSettings(ms) + context.setPainter(painter) + context.setScaleFactor(96 / 25.4) # 96 DPI + + painter.begin(image) + painter.setRenderHint(QPainter.Antialiasing) + image.fill(QColor(152, 219, 249)) + + painter.setBrush(QBrush(QColor(182, 239, 255))) + painter.setPen(Qt.NoPen) + # to highlight rect on image + #painter.drawRect(rect) + + if part is not None: + QgsTextRenderer.drawPart(rect, + angle, + alignment, + text, + context, + format, + part) + else: + QgsTextRenderer.drawText(rect, + angle, + alignment, + text, + context, + format) + + painter.setFont(format.scaledFont(context)) + painter.setPen(QPen(QColor(255, 0, 255, 200))) + # For comparison with QPainter's methods: + if alignment == QgsTextRenderer.AlignCenter: + align = Qt.AlignHCenter + elif alignment == QgsTextRenderer.AlignRight: + align = Qt.AlignRight + else: + align = Qt.AlignLeft + #painter.drawText(rect, align, '\n'.join(text)) + + painter.end() + return self.imageCheck(name, name, image) + + def checkRenderPoint(self, format, name, part=None, angle=0, alignment=QgsTextRenderer.AlignLeft, + text=['test'], + point=QPointF(100, 200)): + image = QImage(400, 400, QImage.Format_RGB32) + + painter = QPainter() + ms = QgsMapSettings() + ms.setExtent(QgsRectangle(0, 0, 50, 50)) + ms.setOutputSize(image.size()) + context = QgsRenderContext.fromMapSettings(ms) + context.setPainter(painter) + context.setScaleFactor(96 / 25.4) # 96 DPI + + painter.begin(image) + painter.setRenderHint(QPainter.Antialiasing) + image.fill(QColor(152, 219, 249)) + + painter.setBrush(QBrush(QColor(182, 239, 255))) + painter.setPen(Qt.NoPen) + # to highlight point on image + #painter.drawRect(QRectF(point.x() - 5, point.y() - 5, 10, 10)) + + if part is not None: + QgsTextRenderer.drawPart(point, + angle, + alignment, + text, + context, + format, + part) + else: + QgsTextRenderer.drawText(point, + angle, + alignment, + text, + context, + format) + + painter.setFont(format.scaledFont(context)) + painter.setPen(QPen(QColor(255, 0, 255, 200))) + # For comparison with QPainter's methods: + #painter.drawText(point, '\n'.join(text)) + + painter.end() + return self.imageCheck(name, name, image) + + def testDrawBackgroundDisabled(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(False) + assert self.checkRender(format, 'background_disabled', QgsTextRenderer.Background) + + def testDrawBackgroundRectangleFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_rect_mapunits', QgsTextRenderer.Background) + + def testDrawBackgroundRectangleMultilineFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_rect_multiline_mapunits', QgsTextRenderer.Background, + text=['test', 'multi', 'line']) + + def testDrawBackgroundPointMultilineFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRenderPoint(format, 'background_point_multiline_mapunits', QgsTextRenderer.Background, + text=['test', 'multi', 'line']) + + def testDrawBackgroundRectangleMultilineBufferMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(4, 2)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_rect_multiline_buffer_mapunits', QgsTextRenderer.Background, + text=['test', 'multi', 'line']) + + def testDrawBackgroundPointMultilineBufferMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(4, 2)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRenderPoint(format, 'background_point_multiline_buffer_mapunits', QgsTextRenderer.Background, + text=['test', 'multi', 'line']) + + def testDrawBackgroundPointFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRenderPoint(format, 'background_point_mapunits', QgsTextRenderer.Background, + text=['Testy']) + + def testDrawBackgroundRectangleCenterAlignFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_rect_center_mapunits', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignCenter) + + def testDrawBackgroundPointCenterAlignFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRenderPoint(format, 'background_point_center_mapunits', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignCenter) + + def testDrawBackgroundRectangleRightAlignFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_rect_right_mapunits', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignRight) + + def testDrawBackgroundPointRightAlignFixedSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRenderPoint(format, 'background_point_right_mapunits', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignRight) + + def testDrawBackgroundRectangleFixedSizeMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_rect_mm', QgsTextRenderer.Background) + + def testDrawBackgroundRectangleFixedSizePixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(60, 80)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_rect_pixels', QgsTextRenderer.Background) + + def testDrawBackgroundRectBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 50)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_rect_buffer_pixels', QgsTextRenderer.Background, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundRectRightAlignBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 50)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_rect_right_buffer_pixels', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignRight, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundRectCenterAlignBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 50)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_rect_center_buffer_pixels', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignCenter, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundPointBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 50)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRenderPoint(format, 'background_point_buffer_pixels', QgsTextRenderer.Background, + point=QPointF(100, 100)) + + def testDrawBackgroundPointRightAlignBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 50)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRenderPoint(format, 'background_point_right_buffer_pixels', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignRight, + point=QPointF(100, 100)) + + def testDrawBackgroundPointCenterAlignBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 50)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRenderPoint(format, 'background_point_center_buffer_pixels', QgsTextRenderer.Background, + alignment=QgsTextRenderer.AlignCenter, + point=QPointF(100, 100)) + + def testDrawBackgroundRectBufferMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(4, 6)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_rect_buffer_mapunits', QgsTextRenderer.Background, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundRectBufferMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(10, 16)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_rect_buffer_mm', QgsTextRenderer.Background, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundEllipse(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeEllipse) + format.background().setSize(QSizeF(60, 80)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_ellipse_pixels', QgsTextRenderer.Background) + + def testDrawBackgroundSvgFixedPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeSVG) + format.background().setSize(QSizeF(60, 80)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_svg_fixed_pixels', QgsTextRenderer.Background) + + def testDrawBackgroundSvgFixedMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeSVG) + format.background().setSize(QSizeF(20, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_svg_fixed_mapunits', QgsTextRenderer.Background) + + def testDrawBackgroundSvgFixedMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeSVG) + format.background().setSize(QSizeF(30, 30)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_svg_fixed_mm', QgsTextRenderer.Background) + + def testDrawBackgroundRotationSynced(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setRotation(45) # should be ignored + format.background().setRotationType(QgsTextBackgroundSettings.RotationSync) + assert self.checkRender(format, 'background_rotation_sync', QgsTextRenderer.Background, angle=20) + + def testDrawBackgroundSvgBufferPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeSVG) + format.background().setSize(QSizeF(30, 30)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'background_svg_buffer_pixels', QgsTextRenderer.Background, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundSvgBufferMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeSVG) + format.background().setSize(QSizeF(4, 4)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_svg_buffer_mapunits', QgsTextRenderer.Background, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundSvgBufferMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + svg = os.path.join( + svgSymbolsPath(), 'backgrounds', 'background_square.svg') + format.background().setSvgFile(svg) + format.background().setType(QgsTextBackgroundSettings.ShapeSVG) + format.background().setSize(QSizeF(10, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeBuffer) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_svg_buffer_mm', QgsTextRenderer.Background, + rect=QRectF(100, 100, 100, 100)) + + def testDrawBackgroundRotationFixed(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setRotation(45) + format.background().setRotationType(QgsTextBackgroundSettings.RotationFixed) + assert self.checkRender(format, 'background_rotation_fixed', QgsTextRenderer.Background, angle=20) + + def testDrawRotationOffset(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setRotation(45) + format.background().setRotationType(QgsTextBackgroundSettings.RotationOffset) + assert self.checkRender(format, 'background_rotation_offset', QgsTextRenderer.Background, angle=20) + + def testDrawBackgroundOffsetMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setOffset(QPointF(30, 20)) + format.background().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_offset_mm', QgsTextRenderer.Background) + + def testDrawBackgroundOffsetMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setOffset(QPointF(10, 5)) + format.background().setOffsetUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_offset_mapunits', QgsTextRenderer.Background) + + def testDrawBackgroundRadiiMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setRadii(QSizeF(6, 4)) + format.background().setRadiiUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_radii_mm', QgsTextRenderer.Background) + + def testDrawBackgroundRadiiMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.background().setRadii(QSizeF(3, 2)) + format.background().setRadiiUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'background_radii_mapunits', QgsTextRenderer.Background) + + def testDrawBackgroundOpacity(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setOpacity(0.6) + assert self.checkRender(format, 'background_opacity', QgsTextRenderer.Background) + + def testDrawBackgroundFillColor(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setFillColor(QColor(50, 100, 50)) + assert self.checkRender(format, 'background_fillcolor', QgsTextRenderer.Background) + + def testDrawBackgroundOutline(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(30, 20)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setBorderColor(QColor(50, 100, 50)) + format.background().setBorderWidth(3) + format.background().setBorderWidthUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'background_outline', QgsTextRenderer.Background) + + def testDrawText(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_bold', QgsTextRenderer.Text, text=['test']) + + def testDrawTextPoint(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRenderPoint(format, 'text_point_bold', QgsTextRenderer.Text, text=['test']) + + def testDrawTextNamedStyle(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + # need to call getTestFont to make sure font style is installed and ready to go + temp_font = getTestFont('Bold Oblique') + format.setFont(getTestFont()) + format.setNamedStyle('Bold Oblique') + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_named_style', QgsTextRenderer.Text, text=['test']) + + def testDrawTextColor(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(0, 255, 0)) + assert self.checkRender(format, 'text_color', QgsTextRenderer.Text, text=['test']) + + def testDrawTextOpacity(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setOpacity(0.7) + assert self.checkRender(format, 'text_opacity', QgsTextRenderer.Text, text=['test']) + + def testDrawTextBlendMode(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(100, 100, 100)) + format.setBlendMode(QPainter.CompositionMode_Difference) + assert self.checkRender(format, 'text_blend_mode', QgsTextRenderer.Text, text=['test']) + + def testDrawTextAngle(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_angled', QgsTextRenderer.Text, angle=90 / 180 * 3.141, text=['test']) + + def testDrawTextMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(5) + format.setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'text_mapunits', QgsTextRenderer.Text, text=['test']) + + def testDrawTextPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(50) + format.setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'text_pixels', QgsTextRenderer.Text, text=['test']) + + def testDrawMultiLineText(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_multiline', QgsTextRenderer.Text, text=['test', 'multi', 'line']) + + def testDrawMultiLineTextPoint(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRenderPoint(format, 'text_point_multiline', QgsTextRenderer.Text, text=['test', 'multi', 'line']) + + def testDrawLineHeightText(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setLineHeight(1.5) + assert self.checkRender(format, 'text_line_height', QgsTextRenderer.Text, text=['test', 'multi', 'line']) + + def testDrawBufferSizeMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(2) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_buffer_mm', QgsTextRenderer.Buffer, text=['test']) + + def testDrawBufferDisabled(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(False) + assert self.checkRender(format, 'text_disabled_buffer', QgsTextRenderer.Buffer, text=['test']) + + def testDrawBufferSizeMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(2) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'text_buffer_mapunits', QgsTextRenderer.Buffer, text=['test']) + + def testDrawBufferSizePixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(10) + format.buffer().setSizeUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'text_buffer_pixels', QgsTextRenderer.Buffer, text=['test']) + + def testDrawBufferColor(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(2) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.buffer().setColor(QColor(0, 255, 0)) + assert self.checkRender(format, 'text_buffer_color', QgsTextRenderer.Buffer, text=['test']) + + def testDrawBufferOpacity(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(2) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.buffer().setOpacity(0.5) + assert self.checkRender(format, 'text_buffer_opacity', QgsTextRenderer.Buffer, text=['test']) + + def testDrawBufferFillInterior(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(2) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + format.buffer().setFillBufferInterior(True) + assert self.checkRender(format, 'text_buffer_interior', QgsTextRenderer.Buffer, text=['test']) + + def testDrawShadow(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_enabled', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowOffsetAngle(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetAngle(0) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_offset_angle', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowOffsetMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(10) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'shadow_offset_mapunits', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowOffsetPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(10) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'shadow_offset_pixels', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowBlurRadiusMM(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setBlurRadius(1) + format.shadow().setBlurRadiusUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_radius_mm', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowBlurRadiusMapUnits(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setBlurRadius(3) + format.shadow().setBlurRadiusUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'shadow_radius_mapunits', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowBlurRadiusPixels(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(1.0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setBlurRadius(3) + format.shadow().setBlurRadiusUnit(QgsUnitTypes.RenderPixels) + assert self.checkRender(format, 'shadow_radius_pixels', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowOpacity(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setOpacity(0.5) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_opacity', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowColor(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setColor(QColor(255, 255, 0)) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_color', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowScale(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setScale(50) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_scale_50', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowScaleUp(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.shadow().setScale(150) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_scale_150', QgsTextRenderer.Text, text=['test']) + + def testDrawShadowBackgroundPlacement(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowShape) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'shadow_placement_background', QgsTextRenderer.Background, text=['test']) + + def testDrawShadowBufferPlacement(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.setColor(QColor(255, 255, 255)) + format.shadow().setEnabled(True) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowBuffer) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'shadow_placement_buffer', QgsTextRenderer.Buffer, text=['test']) + + def testDrawTextWithBuffer(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_buffer', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithBackground(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'text_with_background', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithBufferAndBackground(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setColor(QColor(100, 255, 100)) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_buffer_and_background', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithShadowAndBuffer(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setColor(QColor(100, 255, 100)) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_shadow_and_buffer', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithShadowBelowTextAndBuffer(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setColor(QColor(100, 255, 100)) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_shadow_below_text_and_buffer', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithBackgroundAndShadow(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'text_with_shadow_and_background', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithShadowBelowTextAndBackground(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + assert self.checkRender(format, 'text_with_shadow_below_text_and_background', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithBackgroundBufferAndShadow(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setColor(QColor(100, 255, 100)) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_shadow_buffer_and_background', text=['test'], rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithBackgroundBufferAndShadowBelowText(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowText) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setColor(QColor(100, 255, 100)) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_shadow_below_text_buffer_and_background', text=['test'], + rect=QRectF(100, 100, 200, 100)) + + def testDrawTextWithBackgroundBufferAndShadowBelowBuffer(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(60) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + format.shadow().setEnabled(True) + format.shadow().setOpacity(1.0) + format.shadow().setBlurRadius(0) + format.shadow().setOffsetDistance(5) + format.shadow().setOffsetUnit(QgsUnitTypes.RenderMillimeters) + format.shadow().setColor(QColor(255, 100, 100)) + format.shadow().setShadowPlacement(QgsTextShadowSettings.ShadowBuffer) + format.background().setEnabled(True) + format.background().setType(QgsTextBackgroundSettings.ShapeRectangle) + format.background().setSize(QSizeF(20, 10)) + format.background().setSizeType(QgsTextBackgroundSettings.SizeFixed) + format.background().setSizeUnit(QgsUnitTypes.RenderMapUnits) + format.buffer().setEnabled(True) + format.buffer().setSize(4) + format.buffer().setColor(QColor(100, 255, 100)) + format.buffer().setSizeUnit(QgsUnitTypes.RenderMillimeters) + assert self.checkRender(format, 'text_with_shadow_below_buffer_and_background', text=['test'], + rect=QRectF(100, 100, 200, 100)) + + def testDrawTextRectMultilineRightAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_rect_multiline_right_aligned', text=['test', 'right', 'aligned'], + alignment=QgsTextRenderer.AlignRight, rect=QRectF(100, 100, 200, 100)) + + def testDrawTextRectRightAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_rect_right_aligned', text=['test'], + alignment=QgsTextRenderer.AlignRight, rect=QRectF(100, 100, 200, 100)) + + def testDrawTextRectMultilineCenterAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_rect_multiline_center_aligned', text=['test', 'c', 'aligned'], + alignment=QgsTextRenderer.AlignCenter, rect=QRectF(100, 100, 200, 100)) + + def testDrawTextRectCenterAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRender(format, 'text_rect_center_aligned', text=['test'], + alignment=QgsTextRenderer.AlignCenter, rect=QRectF(100, 100, 200, 100)) + + def testDrawTextPointMultilineRightAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRenderPoint(format, 'text_point_right_multiline_aligned', text=['test', 'right', 'aligned'], + alignment=QgsTextRenderer.AlignRight, point=QPointF(300, 200)) + + def testDrawTextPointMultilineCenterAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRenderPoint(format, 'text_point_center_multiline_aligned', text=['test', 'center', 'aligned'], + alignment=QgsTextRenderer.AlignCenter, point=QPointF(200, 200)) + + def testDrawTextPointRightAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRenderPoint(format, 'text_point_right_aligned', text=['test'], + alignment=QgsTextRenderer.AlignRight, point=QPointF(300, 200)) + + def testDrawTextPointCenterAlign(self): + format = QgsTextFormat() + format.setFont(getTestFont('bold')) + format.setFont(getTestFont('bold')) + format.setSize(30) + format.setSizeUnit(QgsUnitTypes.RenderPoints) + assert self.checkRenderPoint(format, 'text_point_center_aligned', text=['test'], + alignment=QgsTextRenderer.AlignCenter, point=QPointF(200, 200)) + if __name__ == '__main__': unittest.main() diff --git a/tests/testdata/control_images/text_renderer/background_disabled/background_disabled.png b/tests/testdata/control_images/text_renderer/background_disabled/background_disabled.png new file mode 100644 index 0000000000000000000000000000000000000000..16764240269f69e8b9c4a9663c9b0dea5da422c3 GIT binary patch literal 1413 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& z)!fs?F{EP7+bf2=42lc~4m|(MeL&jl#)boKv+iiVxMFzy9|PCF>x>NBdALs)=qMcC t(7;aam44$rjF6*2UngC3U(+2a=jhHlwgt)iHM8u`2OGIR2_v|_QFU*|%;W_W~e&6%F=X{>`ywCGw z`FdZ{JaX~~007Xua@iFQ04V)%V270z3V5olNU^BLUk=0q0H8Mqrj!o>=>h;phOf9f zT~8`ro{Eb@@s#@3u(c%>Uhts`bNTgBx{C85HGi8bb#?WqnDN)kQ_F5ksxgnFhD@xj z8X9#iPuu3Rs_BDOQFnf{&01~;hUYmCo6v91gvcb{G8Tk{jP^!NT z0N_2D4|K??Z?vF>nP?>|6^+NIk>4F7gpZ0dcI@o|B`Ui`&XW+P}~Q)4utW%#4bT`h%T|saZEq^ z{)11x+BMRIgsN{k$Ly^Tqp*lYssMwlN0k)Qq+a&jwts6L>aGvxs1i(&1bkRk3hvd$ z=Sf+N99O-*RJJQ{*)$bXwy9D`y(-}}k}ybT7goL-_#PG_T^{dm-7OUCE_uk8Ji2Rd zFk$3I)TJt#-OGh@R~?dSy5NZUU*WM~?1C`05{U@hNp1i%+jr{MLB8 z1kMK1WZE6aAJ+e~tq9@nPb&(B@smSYrpmDM4)}z-UHcynN8^U0``Ua2T(aJC-NXZ~ zxjL&L3qtf0p_dxm*mZ@)9l zK&MU&V>dT)v*oeLqIh9HWzImY;qPYmiZK4c7x~mmjyM;O-w3n03SzZ!wokyYbb-T- z=heaSc4kBhdg}ZH-P-_zFnkBaMU2~=(J^JU&40c%6)TWh`4tqP_`W*jRIkA``$04A z#i6&>9n8VPbu%Y3H)hvXXNGsQZ7t@)&E|#*%M`M|hZ)X4IA+a-Xkot7q~)PqQ}l$( zPn4)<)xoU&9nzScJ(Q=~HE@sQ72k=OM?z5RSryi<+y|FK_{(myR=ZN>^MPpjhLms{KlZhFS6MPJxz_wJKQ(cLE5 zD1-UZ!~xj{`pVcay1_ExnSM?AwMW_pg;!3RADwywgq&3hEYBz_`iwSrGoHOXlA@J~ z`I*9_dlbF=MZ%C^@~wk(nzBIrJtQgWqvMFbz0P`x$2F}js zR47B^jB}1>VumO<`?JV@bMK(t=z&z#@B3{{!65olG}Ak9>A9(q%V5YbtC5^0hqwaGAA$)b_v=GZ$Q0Gq- zqeQv)Ekq@rGB9fIvQc&kda6f|zki1xxEi!bnq@#*Xe%v1t=UNr`M~n;IhWd}Wc^Zp z>E70@)e8u6yal-tA{6?7ZamjeXiBZ*qdPV&^^<7#A5p~k z85MDQj3&EpRLzc*5XnI46}|$Egje}_@xlqdwo*<`T5AU{CTUPD(}|fG(K%Y9acs%d r?uqiBtP%cM8~p#d{s6ODwp!14yj>a2X!5@R(~7IJ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_fillcolor/background_fillcolor.png b/tests/testdata/control_images/text_renderer/background_fillcolor/background_fillcolor.png new file mode 100644 index 0000000000000000000000000000000000000000..5bd592852e054e860dfe58556dc4618f184c4b3f GIT binary patch literal 1508 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zb(*J(V@SoEx7Rm%Iwvx;1}Y13y9NpfHnj>{v@yS6I`=?=ZvyKZnFF>umpR4En!@&- z6OCInUw@AA!L@cfy1%B~V%E4JZ_ALNcaX`5h5Lknj)L=s2A<)>Nw%yyAhvA({q^U+ zU(_x;d-c_~2Ol!NaLrgMvS$AK{_WS7gG3KMK7I4(*%zV)-QFB29AXm`BOKZi7$uun zhdpPbjBNt<^5@sfzn@gTe~DWM4fNh+x& literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_offset_mapunits/background_offset_mapunits.png b/tests/testdata/control_images/text_renderer/background_offset_mapunits/background_offset_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..1010a0a3ebef669e732bd943c70eb047354f6496 GIT binary patch literal 1498 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwa3%NF{EP7+v^8CogF3IE~>B`o$LMfgwWfAY;TTE&D$g_-t|N>ZjFLM|A8l`EJbS! z3hLAT{@4`HD3asG&+tS0Ad?Xb_Xz^y_dU;) zvu#?+^1A45+*Cqy0Z^WZeA| zED!FA`Ca+-muY_-qxg~O0;6eiG+z#_vgrqF7NhK5*Oo^~z`~lr)78&qol`;+02t!D ATmS$7 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_offset_mm/background_offset_mm.png b/tests/testdata/control_images/text_renderer/background_offset_mm/background_offset_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..c0ee8482859f68056d8764c5c83580a909fe17d6 GIT binary patch literal 1487 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwb9eXF{EP7+v|HhSs4Y~0>h`VH+42P9=)-=^+tDNXD6$M#*gji#dumCzO!E5q%Wa& zrs(^RLbiYcJ6nba>sh!@2)F|yNMithgOsdUb~4bgE?Tpy21be literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_opacity/background_opacity.png b/tests/testdata/control_images/text_renderer/background_opacity/background_opacity.png new file mode 100644 index 0000000000000000000000000000000000000000..89b251a7edac9d9deec1e1f600d778e67ff320ee GIT binary patch literal 1487 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwb9eXF{EP7+v^*B4=0GYU6k-~WNzMI;2jvWkvUK*;J~!VgDdM|i_fvde_r=x+4cU{ zoC_Z0ePL+W%ffv^Ku5uOLj%u2CZplR>8bqEAbsZY%a@5#dmm-!?Z3UNSB~-bl%}s1 z{`%*?FAkSEd%N;)lt?$5zTyPM2#2-=M#(1D6b`Xr&pBpOb%1x@^tXRE^~DvMTrZWj zW&Ebantju6zWqAxfBGXWI7UvykNT8$+598>!OwD{zxgLu083~FPgg&ebxsLQ0L2KO Am;e9( literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_outline/background_outline.png b/tests/testdata/control_images/text_renderer/background_outline/background_outline.png new file mode 100644 index 0000000000000000000000000000000000000000..ae868a1a3958836a93aeea736331839697f59aff GIT binary patch literal 1750 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zt;5sBF{EP7+gls6=9bDFf2fusy6e_Lg@sNFyZc--j&#YWRIu*t@msrX#ccBnWgn%! zERZ~MOR?mNYB0a+Eyc($Ok59-Tz#6*@#W8b|4%mIA7txl{_XjYXA`w&CriKv%PNKg znVe!16eAqk5*Q_$SW`HLFz48{7mUld#>m;vwXfKEL*Dkuo}2sXeqVcY@7S{C-3@LV zrk#EqU;pFPdGYNzf7?G{Ze{s)bgVT@BP!i-y6rM?Q0d`zW%?2?ZZQsHGhA< z;M{O&Ni*w*e0V^*J@)?|x@~>V{hx2ny%1IHudk{3^8Mlq(E_)(32*P+xx06#b(QPM zhw<(H&-~riHyD5N$VW|L5G(i`rh#&OcwQe&FWT=C7YVJU#qg zzAuh(O{c$;g7bz3o`XzAEZiq%lx(=S_t(J}oZ{!Eu9okc#{ddk>-qIR@BNnVk1K49 z*=_jy#pT_L!w+~(=DYUn*){d}nzfOy3*R2gNiVBUF21CGkk$O_>nm%%251X0v9F5E zpB)vr@ngovv@dPJk$U~}&<JdebjgbT21Pnv;& zHOkY)F{EP7+iM3onH(8d4hHin8=41SYM-e2?4e>3mtEMkwpAR@uAX^UQ?19q`uip` z!#>prhqeSp$tKnm4zUS}bmy$u%-&OOC70&^gM0n=qS~Cz;RihA2Eri&;`_m3=`pM7 z0~OPMn^iM?5FQQv0m=%4B{2+SaWH7ZKz`k0p8vPnv;& zHNn%xF{EP7+iM#+4+Su|2AW1X#2h&nde?KpmvJ)b{+wq+EF zapPyO@Y>M8bCAi1h5Lknj)F7YIWye(EuPfPmD`^ArEC9(sPEr*^~W(LS423pB```h zv8Hf{O;8-=&>;*yzhG?FxxFvv_Y2Vj338*MKAQ4Ib01m>WdHr9AP3u@i(7yNFoUP7 KpUXO@geCxdNsBB1 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_center_mapunits/background_point_center_mapunits.png b/tests/testdata/control_images/text_renderer/background_point_center_mapunits/background_point_center_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..6f73583f7a226c68f18fb84bf47723a626b69659 GIT binary patch literal 1457 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHQCd}F{EP7+v|Hd4>5?i1=briu70tBPgK32{fk)B)~QZSC#M$wVvjF<_;&sG<9rJq zZ1~2|kk2VLK{3LiErC(8i8X~|lrw_DfTy@mfBEAe>l+IStJc{v-aEr}Epo%ZSqU3W z1}0xusHId6f5@+MSaE5JTh7|u%_%`2oMou U$}o>91(v}Kp00i_>zopr00EtjUjP6A literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_mapunits/background_point_mapunits.png b/tests/testdata/control_images/text_renderer/background_point_mapunits/background_point_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..76b6462d23431c0542c20687182932f7dc65a146 GIT binary patch literal 1478 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwZhZIF{EP7+v^8CnHfb~1J#9F)*P|Qxp8ch&>KYoi5QZJJeF3wa zb2}W&{Ke4lUr0y6c|!xwK_(*>?h^u|oDmcT7X54L_RQ6LZDe#-I3~Y8_y62|P0X{n zuKoI_7192+wm#?g7eSec(*;IQkf3LP$2Oa)_P(87Dmn8R=eF8kOng~d5&aWm70!Bd sq;QB$P>gVBOJJ02Vjbm-&@ia~-X>wX$+y)5STHkqy85}Sb4q9e0DGXPD*ylh literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_multiline_buffer_mapunits/background_point_multiline_buffer_mapunits.png b/tests/testdata/control_images/text_renderer/background_point_multiline_buffer_mapunits/background_point_multiline_buffer_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..9bb94b6ea29e6ff9553c513532ce7e6f23703980 GIT binary patch literal 1450 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHOAA$F{EP7+iRyenF1MD9H*u#8=41S+8w!;ee#C~>?W+OQ{A0IS&FmLs$bsef`b2zfQ2uEr>mdKI;Vst0PSy}SpWb4 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_multiline_mapunits/background_point_multiline_mapunits.png b/tests/testdata/control_images/text_renderer/background_point_multiline_mapunits/background_point_multiline_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..bdf680c457bbe340046962eeef0a47a099ccf343 GIT binary patch literal 1479 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwbIkYF{EP7+v^8?4+n_29(=FD>!5idr;90&!FGbFP~T-HogddWrb+F{FI}=d#(qD$ z!@dS6VxV!zMTEv0-m7I;E id0;f_la=)!Gfw;|^|NBblFPu7nZeW5&t;ucLK6T9X}Vbe literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_right_buffer_pixels/background_point_right_buffer_pixels.png b/tests/testdata/control_images/text_renderer/background_point_right_buffer_pixels/background_point_right_buffer_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..9fbba9238fe1c4c90e00fffe24c45f95cf5bb817 GIT binary patch literal 1442 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHN?}!F{EP7+iM$nog8^s9h?0`oU%<=8K*YBXqLaobTf15OtyK8r}}@tUe3UEZZ|)} zkLd}Fl1;2B9AXm`BOKc3&e>>|cYob<)fvXdpDW~d`!_HgWH4gkJ|Uo^;Jl%M=OEK4 zhvs1rA-#S6{N%@06CNKP4erq-H=6BGi=M~q_ma6;FR$8t6jPnv;& zwbj$bF{EP7+v|pYPL2|8fsR~Tw`?j9&%5S3^G2}niYJigR; zb46_ZeFhO7cYcN++6S48Sh!CJ=qNaEXy6&;jG!>+xq9<&$@Yr6fQ|Lp)^p8%KYk%< zaM^XkyXpG<+ntvcu)d$)ezxul$Bfg-Tq8JrB$t-G-`AHf?>w!5_x4MZDyB2#f@@xG tna$_CjN#9@=>j7-Xhus6c&S;(aCoZh3ESTre*sHr22WQ%mvv4FO#qLAyIKGM literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_radii_mapunits/background_radii_mapunits.png b/tests/testdata/control_images/text_renderer/background_radii_mapunits/background_radii_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..a37c8f41692b5a6fe05797addf8bece2b8df19da GIT binary patch literal 2286 zcmeHJ`A^da6#p{h5crlEA`CfnLB}>nlx+wdRCHoQ2Xw=O0%d#)OX`=S1r_OfjA%2^ zbWkxW6ASeK87t62=}G`WEYK_*-GCM<6yzvcT1pGFv{>3z{|aN4yd&@Z^4=$TpZDJN z?-NddZoAw7002+M#v}rO!;LrU`hh*;sd#YD?zZQ}CSL>qMDH7QxV<0Y2LP`3PsSWQ zLt-sYr7>9rzE5ZI)$+>~1fTP;`?VuCKJ-ezb|y5`ANF9E6EossEPsIa2&S1+fiwqNE$CPr18gwa>I7naI@Tedd&x2CN8tQzA&Fd!cnL= zN@pbKLrhq~rfaooZ#5KfRe(frS=BaOv$;H_UMtq;o2;4hg}Va|Oku3b&DEyy>%B_4 zVPx3!TwXd9)P0tArBt409kWoF!$p(=+g9qs;~3L@CVv)>U+g9&HfjfCRMJ*`X%bq} z_~6pn@P_$$-R5aO3G1If54^Of%wG5S;nCAGLU_lmC>kR zD>1w-T1FIKmDxnsuLtpih1j@L89ijPe&Xp&-hpVs-w$gpS;cZ)t1t~QCd8r>Pcg@r zOXcmh#b@KW*@tuF&96Rn%I18X(|@OkR`+NOn8~$%ek;(y|L4G_cVs$ip?Hp{8VZOn zK><_Ui992#k^6LdWDW4Gg_gBkV?dLmKnkPL?cn!|I)SSAZ!KqV=Nf*bsS7#pSvgtUOxt z*^8rl>0urs1#FTkX}d4bl8Hs_7K3t&R$m9t^IS-Iqgkdcfl|=7B>2kj-kPX-(Qjq= zf}w*mut9`(;$|V*;@psmuIS*hDs3D0<6wwxX$LRe%K<%B)b30T&b^F*OlxvO^df z-e5-8HxyIY3P*D1QSg1-e(&2h{~yo0b)hXT{pDZS7M#D_VSiwNlgATcn!bgu{s&?r Bht2>1 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_radii_mm/background_radii_mm.png b/tests/testdata/control_images/text_renderer/background_radii_mm/background_radii_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..eb442c9f62129171c7a6c4bb49f0faa950d741c6 GIT binary patch literal 2250 zcmeHJ{WIGK7>||}U1hf!ipA{BY$R=ic#W>~%0`$Hskdaw+RUiXRw6H|7wtBU(o#u} zh#NCoE5vQ2B%xV}_9R@J5-*9AtfIo#d5MscO#h1Q+F_*wlRPQ%g6MA3Eavg34PGXy{)lo&<@CmJDSm1{DEw3DzGJorAHC)G zew5(Kn|nzRI+tuLu59IaI*QKf5W0zmvL`pf2hZ{bXU-wV%S(;H<8lLaYQHp!e5|xn z=-Hr6&p-xdPSimgYEiI+xF$>WPSe)Nfi*?x)|_Oko?iD*(RF~SBR4WTYh_BJD>g(} zv?|B1!~`r5hFgCnqLpyspc?^RDcnG)fZS=ZsDoO7=ibECr&Z`-{_Q+0P~?k{xe<=u zAPz%$A);V)xmKHHT^KVz`0FGViMf}}Sejk+;IKtW#^pt*>>`Jq3iB)30?ZVls>}cB zq}03!tnc`s^%RJtvc%df87P|Rc#%2+yL?GEFNu26_?ei^Sb?)RJoVT24p0gxw3mJ8^_wB2Ib?4OF; zyet89F-}Woyyz-+XJv~wH-|%7V&Y*KSoj>6Ir#k91%}~bS27--YJCcy3-whn|&&qV?oYV73mv5&V|X z1@EG0OO2gRlrJW4?BVld2Vc8`Mg0ygH@z{(f56!sX4-vg|L=-s9AAGvA^+`=loMY{ z&H0ig2UH{YT~t+0u)W=j^cdEpk$e%xRo_-}^UMN&iRBM#>R`lb)^At1Z z#5CQ!xfeY8(Y5whUXkPC)r}pKBV?PVghEi9}0m;dcl_Bt07H3 z-K(e6xH-T#8icCeF;rR@hEU!_6_ayzel)2@uxVKled=5M$}n}giqwu3bs`0+PY@Eu z5^f6aSvMNMLy9(6y9ahBiIqL2%pE-kApxW|&4jp+Lbx~E|A>UKE`A3gF$7dysbcy< z#zcBXNMPo4T^o0I*}TeVnuuBwM2=WiAi#4J;5;M!MzucL&fw)VrZZdS%$8G;(3TG2 zoeegDbd=0dmi?{@uPjwC?jJUd>2PpTZW8yB4;*8~M^x?@#nvYXVMfkxs}=5hG1&H6 hQ2*c0f9v>edQ?$A(B83T8+V@*Q0z%mblV9W^B+*pj6(nb literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_buffer_mapunits/background_rect_buffer_mapunits.png b/tests/testdata/control_images/text_renderer/background_rect_buffer_mapunits/background_rect_buffer_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..b4132085552aff9c4d5e6ca77308036a055e7784 GIT binary patch literal 1448 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHOkY)F{EP7+iM3onH(8d4hHin8=41SYM-e2?4e>3mtEMkwpAR@uAX^UQ?19q`uip` z!#>prhqeSp$tKnm4zUS}gOc<54WshhzV@5K|IWSM8zX=Fji^Ce`yh7jU=B-?+_v$Y zoWZ51`_9f|_%mTNzz26GAt_=9XFeayUXcIp&-1_Gc-($q(aYfJ>gTe~DWM4f3UPwp literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_buffer_mm/background_rect_buffer_mm.png b/tests/testdata/control_images/text_renderer/background_rect_buffer_mm/background_rect_buffer_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..62b3341c34f83fb437633fd72c20979f0e2a25ca GIT binary patch literal 1485 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwcgXkF{EP7+v|pYOo0rpf$fThCQ%#NxXj-i)8P4bjf>OJF@f8v)!y7Popt@Lle6Ra z@AEUTuD;03Q0Kj&f#)ET5exST0UZTr`f+-`zF<84c3#-*N~yhzo|o+0E5Ckm_yM7Z z343kM-*!LvYjgkRgutglOp;BkDI8)G6eAqk5*SB0gFg(`xbsKk{r|an=JJc$ResZN xzu?>uU=fiYfBm9xL;Yxkj;7;bmzN9KCvKEdU^`hY2P~f%JYD@<);T3K0RZo|l~Vu! literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_buffer_pixels/background_rect_buffer_pixels.png b/tests/testdata/control_images/text_renderer/background_rect_buffer_pixels/background_rect_buffer_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..3f17b966ac87006e5e39656c0efb9ba89b95c7f4 GIT binary patch literal 1448 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHOkY)F{EP7+iM3onH(8d4hHin8=41SYM-e2?4e>3mtEMkwpAR@uAX^UQ?19q`uip` z!#>prhqeSp$tKnm4zUS}gNw8AoSebEmlZQ?AL{S9clztbvvG{dm4nNPgDk{o;+)rS z7$3*JyZwgqfPckk=nu9`LX#*Tl*Pe7`cz)@5zl|NtFAo2qL;zb)z4*}Q$iB}yOx3a literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_center_buffer_pixels/background_rect_center_buffer_pixels.png b/tests/testdata/control_images/text_renderer/background_rect_center_buffer_pixels/background_rect_center_buffer_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..12367d56790f553fba4e4f52429c44b8c9a8b744 GIT binary patch literal 1454 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHNn%xF{EP7+iM$n4>>TfI3CDjxX2;7_L8trksrT>+6EWyl=FvtSjE@o)z|JRV_a8otAJ`|o1uy-oL@Ck|5Q4zkdr zqI1qHW^d7by=~3y7os2BZFCfzH#G1ZWHMsmJ|Qs584ZJxkq&yyZ8QWqp1g=L1s1>z Mp00i_>zopr0DYH}ZU6uP literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_center_mapunits/background_rect_center_mapunits.png b/tests/testdata/control_images/text_renderer/background_rect_center_mapunits/background_rect_center_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..9a4068af1186832a2e310b46b1f2dffa39bb0629 GIT binary patch literal 1458 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHO14#F{EP7+v~e|4+Su=INGgi2wM=*Wh8om*^*JHvzWu-eD>Lpf{R|;_urdu-OzOS z1tY_KAsq$h4Gla8nT%MtPY4VPPO_A3LZPLsyZ?j!XUDU@uxv}vJ!r*!Z5gMS{X-!p z$tKnm4zUS}5e{t$j3bNVvzT2cumAcB&I7mBszz*1V4T0BW#omz2#x$vZ&M-P?_vD5 WNs!6E-3U}VGkCiCxvXPnv;& zwaL@PF{EP7+v^(x4+n_2I-a&LlvKRHdi9d@#z41@wgW=C0<~uack|v6pF7ihZ~dP+ z3|!}`+7e5 zRn=7zn~zq!zMdKPt~&nU$4bsdo`XzAEZipqbQGL7G>j~cUUHh<{_VND`)?-gsf_$? z*I1tzup#esRrE0*#`dSGEF(2sMrd*v^)@9X!DI1@&T@J;U#VUJ7SRlzu6{1-oD!M< D=x?=w literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_mm/background_rect_mm.png b/tests/testdata/control_images/text_renderer/background_rect_mm/background_rect_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..5baaef4b75865a6411170df29b8fca365c93137b GIT binary patch literal 1494 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwZqfJF{EP7+v^)WSrSFuF5XNHJj1h9*?SAS^agQdUo&B5*Rq(joJ6sf`P$DzKDbW* zUe>R_oO3~feHFujuqM_N4zUS}5e{t$jFQ8Nb1d;o19!~(<-4U@|0W-QpBm@Z-;nEd zaM#{jws)qpsoU)RyXXAt7orWW>Tf>^YAOst&N)J^T8zLT>M) z{XcEiFIGPgwlrbxw3lDACHFE(9P{QFrb%MBCGk=J45DJ|57V)4vU@*x-<}67s2Mz6 L{an^LB{Ts5C7`2b literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_multiline_buffer_mapunits/background_rect_multiline_buffer_mapunits.png b/tests/testdata/control_images/text_renderer/background_rect_multiline_buffer_mapunits/background_rect_multiline_buffer_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..ff35e1cf19f964165b01f7746ceb8c24b84e6dee GIT binary patch literal 1450 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHOAA$F{EP7+iRyenF1MD9H*u#8=41S+8w!;ee#C~>?W+OQ{A0IS&FmLs$Pnv;& zwbIkYF{EP7+v^8?4+n_29(=FD>!5idr;90&!FGbFP~T-HogddWrb+F{FI}=d#(qD$ z!@Pnv;& zwaL@PF{EP7+v|pYOpGF~feun{bgstki29z^TQbd0XGS4+z~4Is=eXiZCvX4%=htmU z5t(J|40pUXH1Hf`GGgIAA)uq+JS;dpkH0i{zF&U$b*BB^M|RIs_v+mK!ZqXLg@aYq z_v-i9_^#h^{@3Q+I@e!{8XQ(-8CG5=Eh;Vi_-B0iyF2%GY1PqMz0+29mO#&MA_OK`i=p2nd*m>s4>BXGu{QxYY89ZJ6T-G@yGywo63%qgw literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_right_buffer_pixels/background_rect_right_buffer_pixels.png b/tests/testdata/control_images/text_renderer/background_rect_right_buffer_pixels/background_rect_right_buffer_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..473e80ead5a59c2269336080f115b253e68924ee GIT binary patch literal 1446 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zHNw-yF{EP7+iM$n4><_99%PObamqGHWzu54$ljN6@a8K|W6?iP?%hkR|1ainu(XQd zKx7kZ3WwMP#R!MC1V+h0#<~54!LRa8{_Mw_u0_56X}L_@;FvOl5exST0UZVB4Gla8 znMOG@4}%-a*b7d*uJ-Y7sH_{5sbr8P+EM2Wx^jf#D5;Mu=4L%ymnI7=co{rh{an^L HB{Ts5uW^aX literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_right_mapunits/background_rect_right_mapunits.png b/tests/testdata/control_images/text_renderer/background_rect_right_mapunits/background_rect_right_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..190ff482931728a4662fe0c0d6061ab54256d53f GIT binary patch literal 1489 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwb|3fF{EP7+v|pYOo<|HfsR~Dw=60U&%5S3^G2}niY?6>8w$BEPq3dpXLHl~U6uJ? zcmA(t(unAnW7seyfl;!FHHAZLf?|Y2+wkDbzQ`C9vJmDUCXsU%$$d0PrTynJPRzN89ZJ6T-G@yGywo$iJi#+ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rotation_fixed/background_rotation_fixed.png b/tests/testdata/control_images/text_renderer/background_rotation_fixed/background_rotation_fixed.png new file mode 100644 index 0000000000000000000000000000000000000000..9a280c9e57deab10b7e0fd2c922c8157e08566c4 GIT binary patch literal 2374 zcmeHJ`BxKH7!4R|LdqgkHUUwr*d}5TaG_#FK@wRj8j?{kVi_Ss@K_O$vKZb9J{RD!}6?lNQYPgC(Ak8s6Jr2Yd zjrF-_+eBJk7_2{W%#x0J@&#Wjt~iNu!tGEU8gVy$uV*~bDx!}VzN6$!ljhIrsi3%| z?!1FDH5DWIA6FL+EWXj`1Wvx}Sx&ItCrN!D)7?y@v>DUv_Wa8WwPk2u=GIO1Nkm^? ziQ)81bYb{vee$d_AbI}vaL=uuDu`-3A93>ADf1)u?!B3>4HoJJuVDpf0&9Q!T=oJX zs>!olc?a#bK6bV}O^!sE9WLP{;r2^Nz;Pdaglu%7I5H%*Cpls>p`N)tYu3G%Nm1}0 z8;e$NFNcT%kabAyc@%3TXo}?FRZH!@d9YN ztuY}j7KaA@QBOG`*C5SQ=)^Lwg|q`z6#RUYoF$xgR`6qo_3?vT`P}PiMT{#2FWA5e z76B5clFg5uh6=b~Eo)UZoQo(_O|nnaK(QfSM9YW-gZ*qt;al z#-5}V_D^-1z@XNSpS&8;SAycnYwa~g-z{Y@mLC1g5rJFF{kAtb@JA@xdVb`s)TRqg zUs`z3nhkd{SG3R;$ArAJo=*qD;Wt&PACS}vh5Ld+G~>{Bj&*7>w~ITNGCAoHGZm!d z{sH(F_U0lo>{^I9eusd92fC08qxsfJQ{?lzWCFIG4mUOjbrOq%cZqE)*zJ+e)&$mi zN0^!RL{qwcX9$~lTZGHxZdXvJyp3ia;u0^Jpmn(X8q>Rjwq7cByrJxLxopX!8pMS5 zFT9jLvSG+ncTec4OK-&uER4;JrHt1l(eqGgOs_s}F(gLC-?K+m!+cklC|5;T{Y?u| z8M`*ptm%hNj)4O4lc`F_-iwOBxf6xc`(&zgzvXaogT zPSZicJ48yC%QkI9$P{{oe59p34a2O2av|EOq-Ys8zK~o%#Z~MN4yG-cuXV82YHS?S zT9Y0vnF+m`ZTYS(@rjAE-U`G+MprQ;EfxcjxSOzfX3RmWz9l+XD=!UC{6}BWb5v`< zd$tog$Sc_~p`jYXxwhz~<^7bD*@?LBow_?4Mxf!~rkH`ZuX=mq`mGN&Oo5791|s#- z7=g6M_fxk-Wx$dEk%r6Q&UCsmvI;ikSzaF20@(AHkQJLF zL5M7;t_)#9nrl@|KJtxotfb|kVm~zlHNxjoWPdpY$+|K&U{=R6C!#0r6;!dgURODH zw=zK01)Iml3oDsjWISi|Hk;dQNWznvc=?Fbh(DcL?CK*{8DM8s(ZWjRXgWB@h7e?O z+}A&+$-`2>Vedq%S2nF<1w4jSD&|JN0YtLNc$o0Ba?9?7mw{w)OK4L*Wr?{mV zBxv`Q_z&v>x%CdL>!)!bN5a#KtJz$=J(8aXe+3N|31=5cKw&irZ!D^Sz*OXn{6drS z6N&0O+0pq3cAcmm&5i&dji@#$QG(W!6(Y)ZIF(~8dYsSzfvM>7SvVeGBJxRut&7GY z>g{eoUPi`azk=g~p&^>ogrvB{*^Br4lNZPR#V>a8WBnHA>zSDI+&bbrdXc}AUyuJy f|08!hb5UoYJk_rKR2voiF(NR${5|V-bNGJ)L_F7@ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rotation_offset/background_rotation_offset.png b/tests/testdata/control_images/text_renderer/background_rotation_offset/background_rotation_offset.png new file mode 100644 index 0000000000000000000000000000000000000000..5249ba533c9666d9c7245449bd9f758c6769bdbf GIT binary patch literal 3484 zcmeHK{Xf%dA77`06i&{~Ey+oBB#ZJ8hoUJ5IZPhE8(iT=8i{s(g zmSI!IT8oGyrM1oD)L|YrEQb-=c7OG{|AhO8ez~VHF?*V~qyR$Wvz5y+2;}1*0k8-S&Upxe&+O;*d6&b1OfX;5t=V4yS zWeekTxA*fhx<9ZvEpcJ=Be}I#{B@jh^C$OCol`#~;*Fhu)UWkjSL|-ZZF~PczW)NX z{&=C&MPWtxd_(&88bH%?bZtAoWTp*LrK~Fj{#vgTN+Z{vKn~XzOSeOU3K82*?oj#d zAaHg!>zm6;n(F5$zx+E(p-Ub5{mrjzDewfaAmv<=V(85q-I1tarozCRzGe)hF{Z}% zQIxMur*K>aF8?sB?ZZqt5xm%#)p7{H8I#u%Z%Rej$b}rjOG`x#idoKkh0oM1JIT7x zJZNI6C>^AvA{Tm4(o?>v;%J|wHIah+1hAX6%U#m9S<1QQp7F%n`*oU=#Xcp?@*@Cw zb=n_gULT{{@Ty2Fqa^bxab%WoNUeERpA}inX-KCA=HHZ7Mt7`SVmA23?B0+sm0uo& zWpRuNCM!Q-WsakqK4g>?$T7>oK-tGAio60s4N|O&^1V=G3CQ;8kE_jh9(_x?DqQQ! zxx~2!FqrFOIddlA;Y0H2(w@2v$LIejbFT*ki1Kf8@?n^2%nulu1SSz}3Yw5mx&uWs zl5vcu$hkJeq-M67nIpa1nghoxh9}O}DRK2zE~F&2?Ay~o9QDRrWM|rJXH_A0h@$rR zq*cQ#_W6vObl`;4j&?uL(Bc@QGN;P2)-YmRN4M{j4g&vpjP3VgZgOQi>E|eJ!=pNk z!S{~cc*13Kl5AnL%>`-=ntQS{#oZ4^w0-Q>FT!4vK8KT2 z`dZH==+>Y+Wmc7y>hQ%j{XA%sfk%#V>@c2ghjZQ3NrdGq(3J2Y%#5H1PpFzO0uLo- z`agv@(v>_A>T-3k z?HFm%N>m;@a|ZZAkwbowzXfy@=(1t5_C2y4ccOg)K|UdfBLQ=|R{FVDW{d%NH$Lem z=QY8)xFeb20p2bKGdpO*8n{UDww>8%50Ue61)g^ru&fK(;Jl!fh-nKxkaEeXc5w%ie2iDMm0Q{|UMsQJtLe9Q*@(cW zZ$`CO8>45wP<*2WwO3FiZV&BsiCec9=X3aLwr;Qo9SC$3G{x|zPGPX#(8Sq_KM;Wd z;)UG}I#^k14v6^o^n;Cs?Rs_J!_QKJ9yODwdCY7EFfwG<&oXV62a8x28iwzKk?q+1Sn zZVhYQK&8bjY8;c1+{!&Zywr~^QfPa^T|R(?l2y3a$!S?rE=eH{=TLm=5wD4bb7(s` zTdHp0q=QALp<+BIFO$3lLLVI-3PhbJgUEd#H7TUBF3GZYl(k{pJ$?`7zpbHRFFxIc7=V{CLBqq~WRNRwj5KK~EaZ(@8576i|9u)~d6Ap#gfm3%XKuFS|AypXJ?e zZ}LWt1|CMLEW<4I_lS3%TQZzl&Ycq7T%0L2X%z>hlh3JKPb}GNj>N`hOb;-emXd`_hVF`l8@n4({e{e(FbR< z``mUj&2zv)=)x(2I&#v_0I~T!8=5Iu`~i;c=~r7KzaV zudLN^xycnqQC1IFR_eVIN88Rg7dKr|dON%&e0I2kNG4A|J`9-tF?*e|IL|Xc`)!6a z-=4XebV~2FP_Y|-(3OC-K=my~$-+@9E{3j#l^|ejpelHIr^yo&q;B>Gm&9KiQF|`Q zq@{JtPe4A}kDzT0o|%2s4cyn?V*a1uSJ?OePcG#X%D(hQNV;8_1pM8CI6JtVe`Jry F`VUk7MBxAc literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rotation_sync/background_rotation_sync.png b/tests/testdata/control_images/text_renderer/background_rotation_sync/background_rotation_sync.png new file mode 100644 index 0000000000000000000000000000000000000000..48f06ee625316edf3cba9cff90798644398b9646 GIT binary patch literal 3994 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_buffer_mapunits/background_svg_buffer_mapunits.png b/tests/testdata/control_images/text_renderer/background_svg_buffer_mapunits/background_svg_buffer_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..1d2f4979333b0f50dd5479f354c2b2306ec5d0c5 GIT binary patch literal 1485 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwcgXkF{EP7+v^*1n-fIb0y{jOs&1Mtewt~XR&Tq3Yl_MyC#fH$7cGTr&hEZ6dw+eM zdP7tHMP`P7-WwWt4l)_BaGwy+QE(m>oSxJ#4a{dRmqb6isO`5k@3&nQv&{2T2Y2ay z{`n*PCdb?QtK;t@@HMO(i_$2g> zcypw1h)qz8aA-?llx$)h<&1{GXga`=7e2B_{g-~o6|=k=SUxj&y85}Sb4q9e034d8 AtpET3 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_buffer_mm/background_svg_buffer_mm.png b/tests/testdata/control_images/text_renderer/background_svg_buffer_mm/background_svg_buffer_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..0e6da8970e81182e46dce16a7e6ad69dc6ffe4bf GIT binary patch literal 1488 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwaL@PF{EP7+v^)Mk2r|92A?t|e#V&`l#lGi8sudWe)sJ@Fc9@@FSLejWxaq8U70{an^L HB{Ts5gwM9f literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_buffer_pixels/background_svg_buffer_pixels.png b/tests/testdata/control_images/text_renderer/background_svg_buffer_pixels/background_svg_buffer_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..3b1354d4f92d504b8bdd0c10b3648686b63db127 GIT binary patch literal 1489 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwb|3fF{EP7+v^*Bk2r|92KIpgY!dbQnJJ!$t`}nt2_0fXY zmGf;G+pOz0Y&*R#wkFMjNnLRSg~iB;^--VFE|33VY^jmIS)uvsBCw2R@O1TaS?83{ F1OPT?pws{W literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_fixed_mapunits/background_svg_fixed_mapunits.png b/tests/testdata/control_images/text_renderer/background_svg_fixed_mapunits/background_svg_fixed_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..4a639339364c8a814bda317bcabdf8ce30947dce GIT binary patch literal 1475 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwbawaF{EP7+v^82odQK%FMdDlZdA75ZbbU4jlCrg4(wFQV4Zd5-u(?>tn7L@J5HZ} zpUWUpb5@SwLwpl!3WwMP#R!MC1V%}EabCY+OztVPTJ!s^Q8jCR?ECYdpBh%P<|s$} zzFYK1Oy>cAoRfm{h6bL4Ohzo+Cj@jxIYTK7lIPkc^cb%D{`?JR%_E1LBWg{h`)tzu t8JPC8&^49OD>aYWL%)(^5QX(I?!&$!<#_tAM34gQu&X%Q~loCIEC2oe}^5 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_fixed_mm/background_svg_fixed_mm.png b/tests/testdata/control_images/text_renderer/background_svg_fixed_mm/background_svg_fixed_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..d82947c8299b94212838505238f33bce063fafdc GIT binary patch literal 1474 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwZzlKF{EP7+v^)UnG!|ZF3wFANN(OL{d$Ys?G4P#pJiEc9RvRCJ!~mjv**E~*?rId z%QrOLzsSrmPc_1!ErC(8i8X~oY=Ytt;vBQ7Iv_3c@7dinslAVG$4>wKvPgO_Q{1Mu zgtumw>$D>_)Wta|IB#g+Iml$h!hJ$OXOu%^7|d|zuV{W( literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_fixed_pixels/background_svg_fixed_pixels.png b/tests/testdata/control_images/text_renderer/background_svg_fixed_pixels/background_svg_fixed_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..0cd5f805dcd64028ae0755b7266b49f3e8f26976 GIT binary patch literal 1488 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& zwaL@PF{EP7+v^)M4+k)~UR-}9%hu`GshpVywU>ToVk_TfaEhg^Bwqa7%m<<3_db38 zEy2JlznPuk&-4UF$tKnm4zUS}5e{u5kW)Cz_JM%i^uoC5H?{BW%Kx1`->i-Ojwt;d@H&f4eFCK!7E?$1v{q4qI2o zzH_Q9Ml9SX1auUfH#G1ZWE$m+hQVk$phjNkv3Jgrz1$M_buO@oX7F_Nb6Mw<&;$Uy C=C7Fm literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_color/shadow_color.png b/tests/testdata/control_images/text_renderer/shadow_color/shadow_color.png new file mode 100644 index 0000000000000000000000000000000000000000..de625b98b57ea55c29077863053863f37d597de3 GIT binary patch literal 6340 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

                                                                                                                                                                                    ^@ zt^V0(&398a#*Q72NJP{jMt(ocyR{Et=P|wj!skmBr?yRJP=M?StZ+$C%jhppaUJV( zZKZgKLR7ceOF-l25x&;;fb13pp($%ils~#fng~NC6Yk}N=gejzY=MCbgX&(F^JLU? zWp!o26Dq6eWUv@Eluzob5ROPPA|(tI+*wP9ok_J~i)LfHP)NggE3G4pK7x~xlsTLg z63-lmNU8%UN))AC*vuQpB-)#YcN*s%Sx2NkPl>G_1(-l|1egym|8`)@l9Y z7_#J^ork=dgXxhcJDe}>uxxb6|5X}z+luqqRMesEFDD^$?HQM#pq8K75-xVgL}tHF zx!_3G=OJKIP1^D%Rv%SaLKU^CxS<+chS52qp{Lt=&Xxlw<#eVK%C1Dy)NqcW4%91z zdq`io-m0PpWx{Qx8c=pBq*DIDr*ft%tzTsM**hm%m9jpI{*=@y>i36ripz*|78A-h zb66^To-~Q$x6$)<8Mp2xn%094Ran-X&jhA4?Zn8;v_b|$_X}h8MlneiN9TU*wzbfRUo>ap!sF#$x>t}T2UjK*2mU0cm`S%#FpMG z>K+Y=SDngnJCAxN?khv|GuN`yEIDJJV5Bg3J<|=I!1&8cR^q5eD_~=+B(4rgQ!Wwj z`BahwxJm7#msn>r88fxmmewpMOPuO&ZFZ_|aF4J7dAMEAAW`U7w6G{`t)Vl4ltqfA zbwj38PLqyz8Iuh9qQz4dx$tWIZz73!T zU!*yiALq+-gWCdw7b>*n%)uHk!yd?k5`!KLZCJE~9Fm8^ekUo>UTIzt8r;pwRA2P7 zYDFXuN7lq*1BZTy3(H2r>W5?A-Jq5eh83(9x1L4l{kZ@CXi5EFEvtX`|8q<4Uwr=i c@!8i;dSbdgU&(EC^ew>!zGY!tY3LIFKOd1Sn*aa+ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_enabled/shadow_enabled.png b/tests/testdata/control_images/text_renderer/shadow_enabled/shadow_enabled.png new file mode 100644 index 0000000000000000000000000000000000000000..23ed666c707e3d956d1ef6f0f003f6f58c8dcec5 GIT binary patch literal 7353 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_offset_mapunits/shadow_offset_mapunits.png b/tests/testdata/control_images/text_renderer/shadow_offset_mapunits/shadow_offset_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..13249081f8d5095c5fd10cb77259b5fd99e7f687 GIT binary patch literal 8015 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_offset_pixels/shadow_offset_pixels.png b/tests/testdata/control_images/text_renderer/shadow_offset_pixels/shadow_offset_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..7cf72b2e5afa9e4c899f1526c244fdc6183f87d6 GIT binary patch literal 6793 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_opacity/shadow_opacity.png b/tests/testdata/control_images/text_renderer/shadow_opacity/shadow_opacity.png new file mode 100644 index 0000000000000000000000000000000000000000..d6735c34d3905c0e9d317380fce1855001116ea3 GIT binary patch literal 7256 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 y^%MWr2-@nON_;u#`d|Dv2mj^3|AhlPnv;& zb+f07V@SoEx3>+woE;flFCOVgP+fO;Zsblj^M%vQ7WGcuy}@s(MxFyFhob8u?+@af z^QF(PTwZZCb=i!UUr%Q-1r!*3V`x~&!hJ$ON5OeR1J6MwqfrhO!hr9%+y?b?etdoD zmp6uQ(EfZhZRbD9YSyN$s_E*RFDoCs6`g;7_S332f)zqcicPF39AXm`BOKZi7$tFV z&Y%CV{rBna>)-no)z9b4mD@hEFFs5KhYqsX28Y|T?ynznte!mieEIOY;~Prn$9Hd3 zH<-zBZQB{~*^TP!^WK;3V)-^hU6DYLK?2ifeSBDQK7+&&-qA!pnzskMeCvr{u|hR- U#v;E)V42R~>FVdQ&MBb@05pTsqW}N^ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_placement_buffer/shadow_placement_buffer.png b/tests/testdata/control_images/text_renderer/shadow_placement_buffer/shadow_placement_buffer.png new file mode 100644 index 0000000000000000000000000000000000000000..d7834eb6b76e9cdcc337601eb21e73fbb5ebd33c GIT binary patch literal 5944 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 TO`(?8UeZ?Ae_5sWCj9>ab35^I literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_radius_mm/shadow_radius_mm.png b/tests/testdata/control_images/text_renderer/shadow_radius_mm/shadow_radius_mm.png new file mode 100644 index 0000000000000000000000000000000000000000..ee591d50015d6b2d4ce3734ddf67e04e476b73a5 GIT binary patch literal 14849 zcmeIZ`8S*07e3sl)uJdmp{k~uYL1$zqBRetVhAzREH#UviboACVkn|D*GwYON@7TA zD3z)hYKlsPqNL`csQJzFzVA=p|KPjUCu`j+Yn^-L&bjwKd!K#n>pCfqEDSj=-ne+? z%oz@2qX*V!&is@0-^Fs4F~UhJD`b4J1{pboo;h>r^MBVraOq3@XU+(nF@B(H6IrxI zi~8m@0T%p=p@lYkM>jiTN!c=PYz{2c@5zm= zy|N#%dst_&)+L^GN^!XGB)aS01Xl6z-!H@_iFr7CTT{Qfy@=>MLW$>z+TJuhir`2a zq8{&3HGUq}$<-aMHJ8%chho`c#|`Ef2B!+GY6s{@P7nco-AvYq)D z-+A^-pwRm>o&5hB`ky8K&owdUCD`f0G!yl7^3A5Z_ZWxvkFCUp|zCEb!jKg+{+&10T0v%vh&VO zVNAe9CUP0T;L28?;E&wPdc5wr3XI!NP>RHs8Sr9*R25@T%B{D)`(>wwjV%O%f|gG6 zfH`xm^`xqZAR;SZ#Y@qI&lCMTL(+Yn@w`iXXICE8;Tso2c=SiPJ#wvy>cUL

                                                                                                                                                                                    c@{ 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_radius_pixels/shadow_radius_pixels.png b/tests/testdata/control_images/text_renderer/shadow_radius_pixels/shadow_radius_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..60c096ffeef901e0748f0c0c0d52deef56700d3c GIT binary patch literal 13411 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_scale_150/shadow_scale_150.png b/tests/testdata/control_images/text_renderer/shadow_scale_150/shadow_scale_150.png new file mode 100644 index 0000000000000000000000000000000000000000..daff33a4a33151894f6e71b28e1cc5736dca03c1 GIT binary patch literal 12624 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_angled/text_angled.png b/tests/testdata/control_images/text_renderer/text_angled/text_angled.png new file mode 100644 index 0000000000000000000000000000000000000000..e3d249cb828617dfbd25ebc67ec785c112e95a94 GIT binary patch literal 3727 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 TVp26HHsrczWMPQXcZ>TUs^3n9 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_buffer_color/text_buffer_color.png b/tests/testdata/control_images/text_renderer/text_buffer_color/text_buffer_color.png new file mode 100644 index 0000000000000000000000000000000000000000..5afdfb03376822a531d7979edc9e44d18f630aa3 GIT binary patch literal 8987 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 E4@dwrw*UYD literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_buffer_interior/text_buffer_interior.png b/tests/testdata/control_images/text_renderer/text_buffer_interior/text_buffer_interior.png new file mode 100644 index 0000000000000000000000000000000000000000..0c32ab69e7c3f5bcd642572d133638a016297eb0 GIT binary patch literal 4726 zcmeHL`#TeC_+KZKklr^dOOjL0Y9cx8E$0-y<*?>7V(Z{gXc(p(D?dG7o9+@I@n-%qdESxFp_Jpcdz zBy6nBuLA(PUi>k!-9nGlL=H~4?7we)GY9~XZ2M!ouo{ve0O0Ux8}o|}p>G!_Y=Vx@ zMRxq&Sq;7=!xGMz4U zn=94k(tq7kwz#ge>(JH(+YpH1Ke4rsKEcr+keIghpl=tIbo1_Tfc7B}es%a_;>TT& zb~6_Y0D!VnP=NO#O~6?(8Nji<;*SnS@B2rjW%tP#_^uZhD*&A*|J(lmmX;^se35F2 z4z~HQghhFKR5Lc-h3=`i-!0O)*5zEFYKgy+|3lDlm2SP96V5jeV_q@7-upUg6UqoI zZNlyg4^e2WeuJ93I(1?$fv@x7$78b-)_aLk8DG~k#w;Tf%v$yFg|*Jf@*kZLvv@u$ zG`I@AL1K4(~hOM0xOyk zPZIb3>W@8j@zzWv@@LcU>*ao&v6J+|r3#zz>GSXR9I&cD-@+$e`!pq8IypAG+kxqV zGlM&>M4~*?hgii4BP`Lm7rv|naRxJn-zUZrOKWp&($^Gav3Mt2|o+vs;;!`({){G zxYKnxW0xl-Hnt!MdQe4i+*3alPjF?QUa4Mdpkk@MS)zO=+rW2|+tS$XHfeb~Mp!p! z0yE~(-D!7I8N3_^o2ybNO3X)Zz||V7GD!kQRdqI_BFgs*`3y2palf;E6+yqM4yL-^ zI2E@~21t>Q9GECN;0!-B^QpSUw-?KBpkaCfgTkf^4~ z&@tv`YSyvDtn4Qj&U1{MPy}k5&Xw52#9yNc$C!&3+)+AmiFS_lp*E^0RPnsM<09?M zj*h|0TRx*DuuPi0O5Tp!)xY9zPFPh)rmsR(3NCxUR3=xC?*DMZaR)g#U>)Lh!96f4 z?5qF{4i7gil0$Ho`Ty=D{(4)GBI&7%YJQyzoNp|(m}WV&d(d;CZo+d$KJ%3Dj_7X^ zp-3G&3yACz?-)rnew#ykOrA}1p=-&>3vL^uH=zUK|Gq7(g^m9RH%bsiZ}F@w20ZtW<2oE#S4d%TgLdqMUS0i66S5nPzR3~yrY<*8- zcNK>tSXssrpOcYy-yPj+OR+EbE~;w4=}uA2TX74BFX(xvyIr{d_31i!4iCQUkL}FD zZTP=fYdb{I`1^edYLD?1&l}~i5Kp~v6YM$KQ_#`JPKQck*0zggOd4$2p53X7S9;XL zO1Le-@x$7Lq@Z_L_njBVrS~qtJ>;sP(a+F#6W7c%HA&5QWJ~&raq&=ZuWY84L2HDT z<`4x29-_n6zI7ueNy;m)3HwgOI6QBvT^^c4+?$$+8EbJUPxSH zHMR#YP;bE-h>*KkNhkc|>UT$L>9>;lp3gl#5)UWc&6jqPW%4(& z3VDASrsFdSafykd^4o9aSiObiw&M9zhwXxUHxI99TW-G_qg7T3OT|7Z6imO;+P8TB z!5N#F$bd13{?8CdMjb44j!Vv-MuWG1mzxm>c4Z*D+tFXY>R(C~bMojJY}?H${ksMq zt6kPbx_267pIj>hjUussbkM+G1>0#U%D8Ug%JgzuQ;dbLk-7x+rlI8DX{%Hjkek#< zc^Vnnk&EnL%_F$f#o(BjO2zn+*hs(X5L+<0HB+LU4Rh%^J;&L2u~Xk6f;m4adPDu% z$>`xxuB&Vg;dvXI=M)fcSV@MMj1ZOg4E(jXBx=#vv$`MK=%+M=YD6X=Ajea(dLqvq zQs-e3&bRU~!9EC?a4>Oa{?~AI#)n*RyLQVncTey-p?2eGaRM1E($IvRV6bQS0G+E3 z&MsJ=gz`1SFK2w3bh93uY-AP%ma92mYtd(Wz@%nf3lqqQaKoOHb9l=a|5Wgt4_~?S z#D}|v;BIYZO*k4jqD-R3fFF~DaVIr-?D^JoXEwXsr@3yxbzy*R3bw8|@nCNWVJ$+f ze2x$D(;2{~bgBMKL-go(=l;>?q#1M$yRH(;N3rSRF$E=p z4At-Tqp=&e4f)>6Ti(iz)oFIljLeHssO4|ivcTfWtsifLVpSieatlvF{fdz-rTj($ zYq3b0+3DL~1W3}<95FlWTQl+)KP&vQu6c#>^U0r4n6~T-KU)fybn@wUbcuo9>wgIO z^^+`6O4E3!c7V4*4Y3Z!Yq<_vK~>GGUiPn=RSbc`mb}n-KoQD-#3;`aY&ILduslbVF^=9$v;7b7zK(s;pW}k4h_8<+oz-lUZr+VcBhtvf;8&%?Z9P>FgE2eGP!{`7$e}k z%d|k$WX9%Oj@gxE##tha0zMnvL&(gSdN+ixz{+|k*?8=Sg(5eY55772P^td#flcX1 ze`6khQ7Nhd#VVbmr3UyQm~s+wD=uu!CyXNU1F|L~Xv0az`{ybnRuvjIb@o0k{Xkgx zP;k4}2*p*E>Mgf#-Q?aviyCl3_jvu;AXeg~igCTs#UDxatew+)S+I}fYl%tMdVeXa z-1u8a7)9wY&(%7DKcfAh%#d4C$l{>p*zRn4UL2f6Pz;jf0@>S}RKKiHE9+By0ayCX!3#-`G!A6`(VrbvoTt5d%pwYN_(FJ z*IoN=RQ-Y{NuX?28Gg4-DEB&yDwQZ`Frzq*w#b@AogYed_#@ES4#W7uji+e~4(7o5 zscuV@5AjwIvw`@l3Rkr8>lv=7n)t|Eh7~izQ5>PDA8Jv*G+lbUu8Lemek{ZNHgUv? zej`apJ_c?NI=V5%(;~2=3+KQte(}Qys9)?1;`M|i2!CFA4lk7K4qaEV6XsnK9sZ|L z`6HjRTMeNEJ!Y2i2-#BYA|wG&?nsw-%G9kT)yv z*wr^TZ;Q|`mv)v2lmpBvODwffGU4>i)hzNW8bX%mIWNMK5Z^H2-7Oma`USEeqj&b6 zUTf9Z4X*)U?Pan5n#uo~=>KL5|5r1W-#aC!qq&Iglb?ixB!G>Doq72sc=Z1O+C4{U literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_buffer_mapunits/text_buffer_mapunits.png b/tests/testdata/control_images/text_renderer/text_buffer_mapunits/text_buffer_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..d2f42e26613e59d0d201c9bc4e432e53aab88f25 GIT binary patch literal 3921 zcmeH~`#%%xGnx#Uz1r(BcEVc54+ZZ#z~*I5e9Wr(?q(Zj8BspDkHWiDSa z_mRs)wkWDGVm2B}WHd7?Y#7_VJKsOz`^)$I@P54CkI(Ig&*SxYzF+T$*FcU+2Q&`I z$jB%;J6&{_k&*rL?~vakT~TIMmPph7C@1e28JUA`{|;Gtph)2DX`%lilowzh_ z7N@ALcH-@!k^!izVAX|zY1g1!iC^l^TGMEHJ_ZU~B<$RbV{4aDU|JI(BB{od}X{!`&x(m7r2*cqg9WMmvdX{|eJJ z;m>!hbu``8H5s^%MpbSNZpTIUdodS7N?1da5mnA}TJ$J;i-6pE@abw`QU#x#SOR-{ zywr%8c+>n(U1Z+F_lGsmKnypi{Y^eCp&V;quW2>hblt;evdGUu2)G`DmSkXY};Ed^Yv=S<)^=P?3uJ3xI@`+{{fD8DA# z*7JGYNo2O)f_d$DMe{!7GK3BGRvtE8dMr3maP(eoVNB zAyJAUErN!PMG&7#x!aTa*8ciJEW9(}wsC4;v)3PNP!EJ2xjGTK;t|Fio7voX9V=e& z`|)9We#V*Cv-<#wY34$BaU4EE1SKqs#brfq6t!}@X`3I|^!TcP>Y*N*o7E7d3}FFk zIT%xeC81l!_dSuqF<$Ph{cu&{=vaRP#rD~biO;gU(z1G|1|wenip_T`v2WGswc0A5 zF6sFAVbq9l-1kms)-{p~J_3VBVBP_-9t#^2ft*jQvDqVs`VBN$ZkFZ^=SOZb$E0G? z$4PaFZ|fFInhV=6S(@)pi%)R<7_X9(?v5{c;8cKf)Rt#umxBKi() zWs4!%EL-&d8vu+Tgl4-5Uo znVGJ9+s7eBE=L9RdTROLjL($T{fxW>BsF)*d22@|8FK(i8mpjebvR#j%mR6j9q% zV64)SMu3n4;(z53leH$}NMbP{{fS-3gIi`)ktuN2kbvSB>U80C8ed262KS)m7_Z?O zHT&s@jd|cmX1#q%O~Td{@v!?11z9{79mS~ff8J`_ia8a*U+$ew@~B4PuW0V@H31ld zbeu!WBQT8}-$UcYQE#|jHEQ18ga~<(pu{s0{u^wtSY?$A^gA|V28f&~eN$|xttq!U zEI#XPqx$4NK&A1+{DQsKg%-V>C%RGceZ_`o1x!D7Km9hlBu+j)*yqi~1jKgwF=$(v zi%ngbKZ1+?_Mo?(+VmoY;2SAW%yyHKDI=t?r1&p#t!+o__qq3ck+7P>@+IWvxurW? z=rS;%ZUdA%N$r8*$r@79VOoLl-(SWwnW*boxwT}$n70r9n7KQIuDGhwcp?^C^X1yl z-v2H0TK<@D2ssd+Zb`-gO{gZ3&(`fL zp|j2O9;7#JvQsgGcV61W@Zkl3%id3xf=MZJ%lr1FOBpcvu2r?x;(^9*UixGBaZgA%Mnnbi z?mcF4eQ7`_yPRRBDOJ>PY-9n9iJ9esXVDF$&dIIEp`JJhfm|?N0g@ylzxNV$Zl!t+ zv6#yPVXP_Td(EqpsheO48Cx#f`nid;1D33Gc8 zoWwaU<>;$vhO>6MgM?fJe-MNW!V8^F+;veN{l(2twJ66(z$vpB>|quUYNzO8~Tz z9$FGpXiWV`h9hkPN{x&u3ps5A6aL{tjxd!h`AO)^1)#Y51t^e~Pu>A<} zIvpN=4Ugn-=S-|Agms6Iwe6xnq)mAVdBAjg`6>G{i8zMG^CrWRX#CG(`8IF;048oM z4EvQC7E-fzL7#9x9PW*yKzqj;tOS4iE)K=-1m(0*?AjFr%2A#0x?6~<-WO0F-S?|~ zQ9{7s#w2e8+yJO7aw!v39L9>vXIK+*Jm_@+G|?G;gVa=f<^gD72?eH1mvye~XC1_B9$NG~Cw2_Xc?%U$npct5pu+2@?upU?j6J#o*>47ktVIM2bs z!EI!y_kx4t#J~U9*^}%$Jf!?A_T`+vq4jGHj*H#@*@<+Si-H^+Lcfjl9$37|rjnLl zznTd7yhYCr(-e2*bXJIbr0DfYBK|?K9>k>B0<>Xl)9Q_3;Etak)2fK&_C`V0ozuK- z)((S1h1Z4@gx;Tvjndcu5jH~L(T+ON0zO6ZEJTJ!6umG~I;%}u;iBh;(bSi~x>e^n zJe^XQCphkxoaN^L{LlXX-GlG*5gaYM(e7d%=Ob4)=S^z!?lP15MAr(w2cf^2E}6n7 zS3wp55!LHfls0{-%bi3F7Z+8j)`sEtHp6C*Ps|8QU6k+F;Vuf*&NX z)QV0e3w3IUQ0(5FY%!=wHpsZ}Oln4>{;8QrF+ivgvJQ{X_CDy!%jLcx{Pg7a%lmnb z_^jiFn6%l|zfg#irztmm_38-Qpb(|hlTUZzYOga2C;Iqguc}F${>+Iv!00~|&%Y|q zs~-1sXg?8Q) zALM$2C@P18?i{<|0*~FK>XuycwDX$6hBLnEAD9>Gx)nnpMwPKXddCUebi(^Al+Z$} z|4lbJ{`DRm&0K1!Xe7eU2@;u2R4-janA)KGfE*>&f;g}xKA6{RZw%)uR1uO8kkd~eNj=J zu3eoEgb(8S$`V7IwZg+EF_wv#^`(8k!PUf&0}Fr2;8-N|p|}TR&(uuh##c;coSEB@ zqQeq%*l<&{BB0wDKPwIlqiot0=ZK7;>LS?_dhv?`myr#NkX_Nu{&cYj%Olk#uSyc- z|6;6az{B&`Uk&E8Fe3Gxj5TQO4pwl>6{47eYH`^qZOZPsF>FlS z0o6rbd1!w2wt&dymusTcEh(whE2PQ;-I+v8nDmO%)Ukf;|a3VG_|!)6~kY)#o%XRtyB)_BHc(;)slLwM9Lb_(+Ji z_0)Bp*R`A%lu%74yYA9ohiDEw(fSeNM8z3nF_!BtvY};5Nbj)lLt~PzZsU~9_WG(n zy&+vyoHY~A^t@XQt}xb7Fb`46ZD2fuM8>s~6JHfAp?q6hut+hu8_Cf+7Yz^rhfnGv_j(4W=_PY%?smUoXL1rzXNtTp|z`&G`!yk^|I$f?TF2ZwSBzy@!Hqgi)Mm-A+mp{Wzy0H@v^I7a z6DZY_nJ0&)NCejtN$(#`fu;OAaDxr)ZTf0Hr$KoKU7EPhATz%Y(=rJGtxe{)l*!sx zO&5LLF#_s!k!-f7CNx}UAeX;T?XQ_;u#`oTseyrzn{K&+7es}(T-@XwLmB6jN=P&1-sCmm-0(-=5D#D40 zDI%Tew&E|KHVm9uk{^azRY=;8mm3WXuxShIVIKF$A`-#UNN<7vW0M0tP5HKPYRB`J zMU=t&w;}?Yf@WFZM)m7<6-=Z%WzkovXx@5fna_U1_v#HsXLs`BbshU)RMT~i0nY7} z#(7lh`TiKIC&5>=Rq>Ra(bf;?-M4DEIN#3B1XX_fc@xOB`pfBiR{oB7P7v`4x?F=% zLJ-D{)<+(C-fO@F@Pi7=pc}G3@+7dbd4KrjA$8>vj5?w-$ zHzXR*StJ%qQD=_3j*Lv&etdr2p6#P@+wAj?NH$%XWDCO9m!vzqa@XWMlDWr$@#EV3 zA48#ie!AdQoU1*_u7A*y%??*;GuF=?@F%GXMB9>BUd^=tToeP^r9Flv5%Uq|*I!G! z(kM-0b=Mggb?~ZdJq|Ql{qjx_B_sp24{r^j{H&fhGMF;Ma=s`|3u~ORPHAb)IAQRQ zQ;sJ!Q;o!1xfNx5SDw86sMdi_L4b2Q$ABs&LJT|ro$1$XTe>eO5!^Um&?Xr@Iz0uZ zQJVl#$ccH!5k10v&KK@wYbYep>In4i0iDnH_UeHX)`*gXFS$rdp0@i}!Tm$C2>uxn zn6~Mp_euQt}M6=fu zM@LwsCYyImYt=YOM3i}FMHL*6eifVzb-C?%W7V;OnP*?Y@|HZPTo#toyZv>WWd5V^ z)y?EHu0Sa(*O;G{af8T_52UHVt)|cpxuE(rM^J{sPg+*IVef$c0@#wTF|PN;NZ3%|WeU4b0-C$a2;AfH~>sk%$ugs4ym#>pw-+1WT{(8^o4lv|r!l zM~wD45&tS0diLMRvlsdXPR12Hs9gisaCJ{`uw8stslN-Nl0T_d%*0K>2){@TS=Hm! z!bz^*C=#mXLDaq78%9|hDbXX@sjGEacbFMNFcML`CbdiPFX8oTC_kDS{EwKD8+#!h zJ9`Y3!7(izp-Yu0t+#=Y#}46?%ucb4Li3&&&J@;37Td9-z?bD9`;QRgcHU#*EnP(5y5=BwfoTq;=xM!Zl3+(He*zx-*q}OOW&YAw{ zQn3%RC94YdwIA)(&i?k9(Lh)wY>{Elne?9KokgCh5WmV0XVGQ1TV5`c&t42{z5IR+ zuOs2mX)*+#Q}d4j&qc>0JKyQ*rYRvOg2R(~_H5sYq^_niNrzPgYjbsGRGe@^PDi~E z1~WI~7^e%2`%$;#Gm|^G(O&oR%kc;Gye3Cl+X*&Nme}Ac`l*KjX5sq0q7UZY#hNvR z^;{MMGA#nnotlfY{nv8tUCIy;jUwaiwsYSDmJ?ozhGc-!^2^$MiF331gmL@rq5X<1 z+R?b2Tpss3$Wx53YMJ+7mPwPJ`|#;s7BZJZ!qwhD|K9iMf_2Om5BhcRVj8ZLRGBWV zQQo;)CAG7obbk3o0!ta3lBT- z?QPc6)OA_GzSTtGk<8wJQ8^x;L3Y(-75Dg+G_tKa7XShOC&x78>)nE@*k~u&5qzsI zdL~_Yh!f3>{P0&X8-m%xpStf{h`Nij!0~Rbkc%hC0*pY>J<8 zNG3b1g>avTCOT2g0jt=5o4+x92)bHhyAwP~hlJJ7SC}KJc9emPd<2+#N>`3nx)f6p z;KF8!T%E9|dG?hDMVaKpa8eu~wKnyfDSm*B{~+Ci`UX}{uDAid&tk@G@$v0T2yCDH zc)0q@mriMKsS01F`r{!c? zRq>nCBlCukWuMYPc>?efy5gy|AG+{gBaIAbgh3p!NYeQes$JnzyU~&X?m`z&vFFU_-r+`+6`~Wsvb)eg49W5=y8>j?3LBgm z2RdXXb-0LkPN>-9P%%FKpuiP7!Uz~`8|%FAQ*<0?w#7H$HWNVVn9momF=mF%{#7NJL~N?6T`&ZGd(wv@!Jfmn?6^h!EPO3TZ0w(4_u3?$d8Z8|=2%socyo z{Pa*dU+%lnfwY2i1x<^SES%4u!PS-d2H~hEHT7#yGUh3M8fK(fqpQg4GX|s7BnY4# zAQL8LdUcV1q9uJdO!Y$dp#Q!ZdBXMxZ~LePdZ5Q{6s+!)vDvojXLV8^Mp-ZiJ7sce z@8PZ4�WqL6`BT$Z2-|vD*>rmvYS6ZLafy{B|_u2+?7 zz1~Rkc6{HmVD;|l&9p$e=dXZy_Fe3&%0ES>#F>ni-73UqWIJh8 zlU+q7MX%Tx_$T#Un4d+z4FjwDH3>i^{7nCD-)WjKS?cU0ae`UR*OENUsrG50>Q(^T534(o!w4eJtu2k~2ESrHdo~Bu}uNB&mGd#g2}+nwIq zANwF-YdCL`Kt+<5K?m)&x00`oMst8FWP1v|BIRLTH80PtzaR+P6NCkI%<0-CElYPO z4p=51E$(U>geMWw9SZqX$!#ur?{V(;JR~7O_oj9iq9oaxG%yf%*W&2KxB#f*GD-JF5*MYS)kz5lVZAv=(qH z?{!rxQO&pGY3xWTI-yI9fZ&`4*hEI+`a}H)I-XG4#b~7&XIHnoX@Pp{^J6Vs*vcfj zT;8B#sc@}uiA_OQ&s7!Plk}Bvb-U?yBcY6^P@~sW*y@#`SR<*iyH6y8XOO%ip zjx|~jUy#_A6gBjeP?l6q<)+EfbbfW#(I|l|;)|&`aVu5()~L$&$D@B@mR#~l5)O&Iho0Z0Zz@-fEtz7?9KGXd%1vlE^V%FAq-@6 zGf5E<`vw8eO<^5muez0mWnU7S+w*Rqv1W zMjp~vGD4ngl6ia_yrURq5q{=UbvY#$DFu|Jls*+hxv6baO_aD1%aPVYhUBEE}1s=3(fLtw3k9wkK0oOUida<*7s z+;urjpzIb*r-0E*WSe-_#Q4FUx~Cw51*ew838%8PuE0b=^~bw*l?RS?D0p4aw-7?? zp`0LU)+qyX^fh!kWmbm0)gnS)={%>o>PUF-@|O|K*x&5dtBO#zJXD8Nt~m%`G2S!R z_l7F<#Jyg7DX67UpmZFp)d7OKnx$H@Vth*($+@n|MU71KKH730!j2fccM^^tHFTZ9 zy}>7Xq#+ZCBz!0^2hM(yEx;3Cje!&UFd&Lah|iO0&8XX0GnE$j)Ss=Mro?BhnXSTg z^=D5x%cToei?&s6bxBHe8+wCJcEj#>EcvU+gYW*>s1d=l<$}R21$MsbHSRSoj|$$z z#}_cuE({Uct`BCKU)Ri3X&s65EY(X(CZ#^LbKT%LqyG#4>XgycLLfG?W^SeSCeRUTg_cwX+MA6!qt)_XTp6CVhF&3Hjh zAAhx@iXmxF?n^Kj8}52xI^YP>1vwzcBu5avvJhxs%A@x)G*_5 zBR%LM$ktc&zP>t7o6R7-sA7j6f#L1gJu0m3HTz%@oPDD}B>s7M37W9m#Z>Zc%kFYd zt^EhXUV5{!gh_qzYwMP^*wl zS=678(=hj57fIAM=BTg2=3OPM`!rhWYPCGe;$cd50A5D`!l9%=4#!Q+pii`hRL z$Gs(nWl%#>kQ6Qv0kzM|#Vh7$WGP+GCZUeMCq_y(VF0^mkTs#@}UgDicK3>8@) zbA`j#&AR$)qJ`q);cu&ciy^%OcDvcP)HV_MDqC{*R^ChBZCiil51U;m;OGM0*PnSLR%Ehg%wA@$Iy@JL%OhaI;V}?&P z+*eu1iGK`8sGk{jEpzXs3l5N3J7fzgR16uoqPfEdMVeC$cR$^k+wVivRI60{1Cnn3 z_~G*3K4;pRrs8w*P$sT=+RD?)0EL7#y$iyO^Iz7QT>rq6g5bleUPI6 z&Vc$7?!C4KH_e`oZGuKcLW8wZ$_{<^5B=DaQ1MEneBrMHg?|ml) z&8Yh|c+E?7*qGF~N!o0XWi60a9F^5Wv_dfIw4l**&?Q9$7lw@_gy||hfndRa|DTgXJo+B>4d&gHDf4DAS-{0FHv=QaG zFm&s$786Z5f@320Eo(V8&jK61xcps0gxnF*MXj8gvTDL7rMGuX8zSy|0L+Tc zK7IFlTMf2Gzj*I$-Ru|NeNKtAs;P<>wIZbL<26ZMGN0d5rnfBzkp^wm@1ll^SW2Y<1w= zf>~Mgf}pM7Yf{m=vJ`t%-Bo5$hP*0S6+**J883lsxlp*-zr{CFAs#9+>*J0Dvc4&d zeVqNHXV;lhFW&k6ZjQF)X6+!%nSMsF&s4CE2VvKmQoL*N=t5j%Ff_M()V?Ts5`0Z8 z)A#l^J?rQ%sqH|4XuwGBhX?mhoe-*}W?H!)D<1(CQ?>d=JqI*>pXb+P(6C-(Qe3jp zQ(y)VKMFReQj_BHueaNZn)QiOm8KEjPl4sWLT>KA@LT>?k+C|iWxU}d2xTKWko8A% z_88(@M(K?9z5Ukh!)m3h@cf^UVCueOWI}Ij>5IT(Jbf2Q_!}AVbK_HL9|&gIDAUD4a1tq|R|We6#Db=-FUuCzaB*BdLN#j)j#}2`^)gcKiq*KVwTHhMw{n62pd; zXSm3W$m`?q=t!15%=A;&S3W{nxi0si=H*0YXlVvqV?aQvW9TamzD@f)eaVeW1e`k# zzdnn|JzHiTdZJBUj41;Oqy6C%RYb!NPPoTKvnKT4O;yDNzNQFHx7oFqabF5odCRM1 zg_X5aQS?*oiaS?+(>_%5iPfxSgTY*ddf}!7e_DiMaD9dTNktzG5Ul{dE zKOQBuKx?0dW1_bx8{WdL?auIS;8(|6sF3Z--2TzkBCBt=mC`z9qBK$*0^89SJQgV5 z-x@QSnQ$M@HkZuCK(Ia-|#D?@5-dc6SynkL>V+l{p zpv}%6&spq~gKGoYRMMhTe+UUl!AiRAi-Oj;23QQp9r8138A|`1{`Z_;tfWM#1^0r7 z_TcrN?=|A#S&Z=+k4P<&J6po6=9#`(GuT|aG60Rt6yfUg=5DhYnF0RH0m?VLa>aoh zlT6xY`%29ecod!UQE)XMC%jctK%RUMSMe`%R;1IQ>{r_RPj1C;TXUz(&Acw4P4jaW z3)_cfSnau&3$kWBf6itl2*kEWh3=c0796XEM!&Uj%yX+-Gx_1qzf^th?3#X=2x7y* z`UGF!C>g5!p6%w=ez5!GGuasUgZj0Px>zlRb(#96uHcH1i~i)idJ&t<=G=*WR%R(M z_N|ddukVkGk`40W4g&tIiLVf*XyYlMK{&1T{%Cf_0G{iqT2u|7;PxCOdmN{-S@ zS@S*3C_T=@MNe_oV-CYS<40C?FSj)f0$^=`bV2M8H{zTP(+XDcI8WkP$>--L(B+CV zJ2Gr_$BQ(vTCud#DdW02nd^v)F+l~e*?qavm~CXh+K%P<62^(!J-i*@AWCaJr}g|t zJtjjbYA&@>U770^gl%y;Bk%unAb!20sgdZKZn30cq+7otSr+aT>em&gjR$yC5DM82 z#FFWXv%7)dl5p5~<<@cF6v6ngDN|oC6JsPdXv((xU=_n48mYpSQ3p)zEmA$bb#bg8 zrj9FNz*lK9Hi6k+o3zCr|R-R}=XW{t)t9u_h5?Wxe+ z$)pG06v>^V5BH^vZD;2>*DyoaRW$20gHi_)%=$=>l3j2gHkTSy7yx0* zcaM>5snwupV%aw8m8Gbk<@$7a%Lw5AURd5PG-m|7TQ*y_Kd$LzJ&_uFu6B`d5u2*G36tq-ej{+cAUpME-`s9-fKn}J_$h-^K#;3>qWvUapbJ* z9+cxTwtne0Mn|3j366q)^R(P%J}u6g0Gy{8|JU&FKmq zeOPO^b&Jqhug5NV?cUK$ca@S*30L(T-Z4i64#w--(obJf z;cvr$bUeoBt_QQVY5gZ2_+G0PCQV>}I;=jYIco}o7hO`5S)csrOsPOh(4o@_#P@wg zppPVM|An&cW*-JpZ^`AwlHIr7`e%<3>Z&%oxvy)v`JY`6?YlUZDBId8r+XQlv{HAq zF#@&XzU?gFkW%h%mto5tsiLWl5CqSfl=~+vvP=qkh9QJGNqciNqLc~^u3ZJ6mphqy zJrLG}f^DP-E;@rVWmLN9O7)Jny5dBaRkVr+Cx;>v)MA1BJ{M>s-uls7Hi|Z#!nnl3 z!;|mwes4<$%tYoBUpPxp^tYIA+XiW4-(zL5{&0t=3$!*x-jZ7uN80aE*Yv z=`*41%$7sdy9Y)B{Ao~Cm|+ZCVs~{jL&F~Z)0x%-g z8!bK@@D4aXGx2;{%}Ms*53;Cd)Y@clAz@0&=5fpb7RYT0I0H>Ho6aLPjBv`2fvPN_ zP}VCmXpK^I2czV~iEgxSbJ*wixJqyF6Hf8#%Ch!lt|K2Ov~6<#x3NuuwB)zQ@(5L+ z?G@%XML5ezUub|^j`G_A^Db@8GSmHBj_uNNLzM@i0bTtjynNH2rNw1^IhfN58f;Y& zlxKqL*+2>E&QPK8I9Q7FxikYRQ(GvPXTgAZakGre_xVz7azO2$3Z{*jjUh(v60PM; z8(>KS>9%V6!z#-_ctA|G?QZ{(H*t*0Y9d*F9$YI zA(g9Mr+IjkxdYVBi;^C9B@K$>19EPp4zlVhYU@SD45}>0DL&AtPM9)mu@5oPxBlKS zO~T0UWPzkk8pGMj9(!FUdzjb1vzP3~B0Dg&Mnz5AxA(bfFdpio_F?8dlNrisLxpe5 zGr>l}0!VmoNr*0*l+_(ov?iaebF_IX`~Ed**V*;7KW0EJLg$EA0W3ABA9q6#nK=zF z)x<|ljkRPKp98yUT^$g~Ft4xqhaI+2lSzZe>BQnosC;6r1yqZcj~aOizBp!MpF&S! z+_u05!h5UODI%2UzOzrIOtpCSQQWsFASNAQzMnQ2>=5{L!k1rUQBB09ub?@5f+jpi zGv7jEhbI}ET3LIZ%P$oel}A0(Gwi_tT1B3KwLPVN7_WSxtf1DO9VT^}1VGg#2EU)Tfq{UH()-LL}=DsIU|t zb-ch1P?lDT+Kv7_;1n(`1;QKii5|WFA(O}a+6j+KhfIjVh3F>%^KLHJfO75Yr$SN- zLq!nwGq^2->mk3vB%Viqx~exMUjC_{J**(2$|~KYA-O4@T_1Uht=8wKE)RKouV0_H z;UkdrP+}LhDC8c`orhLRWX^;BfrrMo+`<%uF{JevHGFPM?$m^FqJ*wkmvMTHavC;e z!C~*JX{yd|Gq>U64Idm*#vKklIAhyCYt2lg6qaRu-M=@eGhz;xFwbU_uh$Mw=`A=0 zzM0uSx_E`a9imOzINH)gyc(xJQcm99FF1(!<*4SV2#&hZtc%y^Rj-m;y|gWJ`ctuq zJPtub&wVj3L1&UlY_RSfHnJnj=PX2nI9lWj<=eIA2h)R=`wJrIZExq({i+8?#P7h~ z*1GVNI}(+}d-d!%ZttGs=oqafA6+>a;^#8laQFgkoz9+cqIg*V9oc?8p6q#33w8ga zBW!F#x2aMKbb}P6NUn&K(Z_wWtZVw?6J3wjrU~Uq{gMRM_(rEyAy-c&03Zgi17uMP zK5jl4e>V!Ki+^sH^hpJ?543gmjGLbw-mSWJDw!-^k7>fvdM&gm*?Pi@YBB_e33J|u zuIyPHqj0J(-8z56sAI@=aAu_UqHJw}WDArm*FXPUn?RSeo>s#A`L3kUW=mlDaj{%V zg%n#Xp3J?9~IsrMVZWV8U@5%MAuvOkV^N9DHbE zio`|-EsN!r0Aq?kG2OJ8vRXwvu&2N$l=kYbm?YsfyUDqP`XP1qql%U~-X1O5AP~%X srU6vN@!$F{2LI*2|1k%)PS3c;!FZA{>SVHi32_)cHr14qXwLI=@+ z0TVz#Y6PT)5F!$al!QYC3^2Ny0C7I2rW1Ty0fK!13ak7<>8_tYEd z_nt@}^yhr9uxoYXVxQyKgWh>fxCg#3T#zG-`ZG&e*?+HY05x3Fkn*2{bw?e=H*-AW za%pwt;81<#cFZ#VKm5PcKx&o7V|jgx)DQ#F@jZ+hCxM!UP)p72PE9uWsk}sS9jUM- zG&OaA8+)dKJk(X^jq%Ix8f(bLZ--zV2axGRgAsU0a*g~jwRo?dp6MfJD}uceh^ zg|fQrDib_Nx@S=(H}!49_T7IgIGt?)tiT)ZAslLRl6WhJ$H%LeM}|h9XUkYvw1VXY zGxdl%S`xg-$fPmpCrq~JbHLv(^0(*0Uq zrwGM57eY}tA#D~7Qjh&sxR3$nl?kj+d?Rh=r&`#9hf~Wtevd_laCG@3EQEbtxf+^u zq17<*RM%hcxc(PHMp^Vmb6L6u1Ep^cO zDEd_DDV;z-X--WjK6B#*A)>T6Gu7LwxLn5=_D1=e=&AY_-xJJhz|h;%Q+ZI78{|Z- zDC$C1c+Mremx|fSNcfyF11bp$e``US^XWylkeWb><60`kN{eC;Sp}sBYj1{tr#!F}&rgV)tj{I*^w!%rRg8%%pUIEQ z7BqgU{gqmXOQx~zXZo&Py?pC6QKxDiJ-(?ru1YYJToe>t5vZNCs+Y^4Dviy@?iwca!^NonV4g- zA3ek^U7``TV$hROcs+Zg9Zn1C($iZ8sm>L7stVcf+(cLrJ6v=J@d?s`bzJ1{FhY&Z zy}_(TGcF>!jioj6TaWTVsblFX=13V3MuV{*Nq@X;Zdux$V!x%Ro&Ks=|E*Dk^~)u3 zt>T^Zl`l8%-3>#O!3;6VVo@t5NYgvdWAB^ca(-irTI_x%R_6Uswa5`*GGAukYfVry!rbFiR zO>L{NWppgC$j7(dM@K3n<6xxlC!g~`PPlDY|GMx$q=zpgCZ3w*wP5C`53v8zpWZuXSSmNB- z-JMsd&ir&>mREW10=Re3^wmO8#Pou!K~UfgGoLlF*_8Gdr|jg~K_VMRa41pH8UJC# z`GYq%LnWed>GGeRGz~Z&FS$sCFt)N~_#j|# z-Iunr47yQHe<%VBP%cy#$k-R)gB@Yg3`rZ$Sa%6T9(1xw-J^0Hl;WDjBW#8jJtiKc zCLFTN9D}a9I3%^)rtgLX%rNpOgD|NlJBz5TkP z=@VMv-VyU>6j>u?42N70m?x&hsEVsQjRK36=)B>8AZaKSYlTAxpdC`@5JrEyX{SNLtdRyMa6TaLvgZ|CvQG)yyv zP!QR;V~Yhb>@($9`MFF!+{NjnZ~UJXE{54{?qGngk9^z>znOJl zU@T+*LLP)!rn`Uq8}x#;S6di6o%}@F-~&_NPl@(1^Ff;>ut zslnG9$uo|Q{AQ97jbpm$o~hpD>Z?qIf_SX_)};bCCtlJIPc?&4&N87|ZJz`Qz}0(? zzBshAHCz|A)p=)tjHWkkey*)omw0K=^w#RbHtn#lqlFbHU2wmEg?33hh%M0-?9r)s zuLs@CFCnbJXRqbr;%ongY%IT8P_N+M#=7v>!@=3O!h`z!chzn8ZrTD`22bzc5D zn(o%mHIx!`I!kL}?dU3w7}j1`-yck8Qa{}HKD+^bQF6yS(t}@D` zjLV&S%rp~^JmIXha6TJ=s}b+Mfjo4ZiOW7%PX4L?Js1Eg<{{#rntsG+3!61RK7ep` zt=*?))zFTwVb$Opi#o2(xX|xlt*?7?{|xE`1Hyf@HE}D9Af+g>$=>FkEY5aaJR(v% zhmzoZ{~cB|gmS-nX22A7+Ug|X)y{$~;(59BltAThnTI5C8h9wh@{x}*$sEqvh#GS) z~3?8P~QytVUVruCpmt zn5};Lz~b`oAyVez{C;C^f4%LaQWDdu31Edcjg(dBmQyKIf2r%y=G_VNz=n8z7imji z%eH^y0@E9^cP;iK8#`@Uo?I$Qt4jFTR0s(|ISW<#Xb9yFk+%lIot9s zuE@qZ{q85h&`wyu=dPAom57^*n-V{}H(%VMUleB573tpDmJxb8NoY>Vk^G)Ga3h_X zrlUz>?Nqy6@tcw-Pv)$m#&T$0*Fp5Hug~JSl1?fhz7HQkrG!9`;)s*GEdki+R|geaqI|x!{Q4<(moOp?25s zLdK1;{%?fr8{1-a3VhagyvTzv53!F{P(ZU~kPYl7*ohHGy%+Cze)N?a@~d{T*rIwn z>(MZSxl_i(l(eVhR5Uxw^_^G`|6YsbI+MBd2AJu)^%hUsL#{>{6{m-?-m$i=WHp4e zVzz);JNGV!P-TktAh18G%$G*!=*Hk$aPE+Q>C-#k_JK)m$oKBf9DP$ zdLtu`%D+_euLjgm7A4#o&Jz$uzgXdp=cHO4pesh&fx=+WQK>tDOi6GK!koKZtsmGy z*mFJCd-qU)nI*vAE0M&O5_87+=Gl7whrG4IRM=~-(4z#AS#|lxmpsYngU@+5iT25~ z&Gpp$WOIdI;x+h0-IUEcHx!$RbF-0qt{POj#xHi}P7}H{{QKe?gC++-P=8Uwkx4OR zC3j225b{)cNq-(P()KI7w_jqZ+Wn=~2T4$_bd1`Q49e>F zndg%!RvYj98Q%M|=HeDn+i_a4!F*UrjrTo>bE>MgAre4jm1}TTvg_j~MN#h2`xp26 zWSO_bv7-0j`8=^#*b)I^x*QlUD89g!`VnbO&{~Pau73HsO@ezVClnGi?qcijb#?1+ zokRrfbN%Fuhjqu&LJ+QZWYg!Hgc)M>B%8oKk09*26HI7q0=(^X?&ab(nF&{13#4AM z+8%hWQR*aEJ|z>Mf*ysrD_3=_?)SRyPerb0iHZ9c{1Q8uQ)2m!$0==peHwZ|^O<^y zr==n9>Zf}SgNjbOOJ^tb8{suD;s6=b50q|^Z(*Ac4%v~keX?q@-e&AFQ-yWlN{HdR z##cW4h}JpBU0f)!o0f^Kv98z5^aYX|Pl#)Yog97`R)5&*9%9rn9RN%${e*&y(o@+L zO-{X;r|$T2U{3Fwp+m2#A^|9qU8sLLQ>nYNuf%$_cuSh*EbAB%L0wEPv?un|CD2mm zfIksBxYHF+dy|KS39hGG)~-nA@5heGFi>t0*3sPgkXTDH&DZjYtS6I^ZmkjP6Q+>^?Z2Fsd6{(MD18u=-{D*JZikZj*l|2e=*8LzFZ9bR5^3yk5~54C%o}+c_9q zT`}nT_=L)_tY&LyW4*!6n+8aU!lM2?i7@Yuya_2m_&J9N4~4@6_ZbpYG&5`HM7vPi zK%Gbj?hX%|+P(AikmEZ|Z?d;Z^T#M%mt!?cQQ4(gD~;BRBbN^U+SzIfgN|CPeHb}% zxQ-e+0gJ$sfxV#hA0%0B1WPO^&T#ds|E7q z0ti1u@)zw@ir77)*)Qr_`L+&!{Ll$_|4z?0mF4gfjRLg?_Q5l9=UST%_Bi=81(lEkY(}K71;*68_dWb_lwvUfb*vx?=#e z^-;It9@tmTrF~QOy6(q*X?pU*6wYhg*M3H(z~yH%TAYvk{dvpH^j@cWD`OtL1sZPr zo)i_QZ51s=jnQhj#5@y`+li`{wyqcxw=K1ON`b{;j-+xiiA#clq3bFYLNoBmf}P{#y@asR~I00HiKKILp9DHI(0^r`rqHs$;-KyS#ul`{N7ng zceKd#n&syU;e1EMMZ1n&RGDpi&nsY5JwRT+azH>h=FBx~?-2WhafN37(~-nIgTAqb z1>BAa|w0Ok;l1KUf6nK2>>hadY=brc+dTsvi z@_)Nq*l$oR?`GMR*;oWbi=HQgS7SUJEa6COcF3Yf9#Z{d$>PzfX(n<4Lai!)I#()t zsp=0^Uxkla6$b2tYD+R*8{wWS-9CeHH+cWwu&a`VVUkAQ=0g|ht2d3hUn0K%m498c z2q{$|-Oeki1wwbxRJV{uIJ9T+<|H{l85NPB*2`c2=1*~PMJX-EM4eQ9mVqu(A_Oc#;o9YV7(udwkp#a%{6c!j#SlK6`j?y%N_e+F zJ!UJm$`>T{^V4DPdiiJzr-=DGsS|eHZr}#2cM7cHK8rYumG|y#ZyH_igEWIBEb(>~=l@oWJZct*a{O#~I$`EvUk68lF=v!(^3?bR+=61>xKa=Vfa(hUii=fxl z+Lp#6DOxcRzV-23xzXW;0DIMLwz_#`i&OhK0gS3Qg3MW_tW*|#?+M#=@g_5H)=N?#r%u%BLm9+9I)-))5N z!6>H4DC`Rz)w4ui#ODRoHLrV-mX-QKL44)xY}O{lzL6=PF_H*ej1mjIX;5%d?M8_$ zis{_1pSBlOSSbH;fX9Be% zz>96?2acuaPAi_KOit`|dFMr7`-MOC>-4W-AKcu3iS7GKv`)(xZ3r{s0%^;A@x!_m zO5eDHP`H2^_BKi@RMZMcAt@m!Su&l1iJ{qcgh3H@*Uy zX(qA#OHEUiiJTql0noCnbN-d3??ly^7nkF|to6vwcxP50V3sh;9*C{#!FS}Dq4`ir znsJhP+z64!VTs*$2o$RZ4=BgzxI)0CozzQvIGhn}+T&YCs5OTcLOqrVWu9_U&R*!0 zrFHDIRY+WZ^2bdg9crHWX2cEAAgu3#6>kw&wiXQCP#f1M;!L_3!61Yvf+D5Tvws_C zyEHt^lEbKe`H{}&FLl|xz8t*qE%gcv7VGp!$Erf z-Q%)}y|lHg8UCdA2l?^H{nB)Gsq{qU$pske58|&!-KxHLy(Y0Rz+**9|68_Xk`gtY<24gDYq)%9!=A6?hDnJQwgb1xW>3h}h?fqiId_l2WXeFW^ zNC|_lAI4p3N_2{2;wpBVXP<6`XP!bk+$adY`}6xh9-3ble~MUq(OKDEr~_Nv+1Ab- zHZ}>g<(#P2XF>pnV(ie%kps_zaV`#c?uT?oGBn zQRnYT37DlD-C8*ma%ZF%J=HWf7qAieLjPF-(oKV*eW2FZC78H>FnP9r7c7ly zT8%9vF$Yh6$`D%=y@cLNT?!Rnq)H%p5y{Uz^oE?i<_Aw`H(qXz?=8^}@rnstaGsku zQkN)+9Z__^izgM&qC5WSs5&l~HNlsx5ZsFzW0BvNOBKG(3o#wXtaMWQI;pn?=op@v zBqMATmxFC+NaUmKWAWZUUW`+?jBjZse1UtrN>97Nw7e$dy4&;$aX@SxhBdDS?h#Um zg~70is?q}F#HlzqbQanC$PRjVeO;gw!dJdZ3mw?0S+@dR-1pRU=eiLCcDOF%ze`6e z)+C%hz6>x`znzV8%tlpl#3}Y9o*&K?9kO0-*uk*M5zOpl{V>sRmvD6F%ZZka#3RDo zXZZJ-TL&cg*etvG4!zMF1b%2u?)kKl0cu!glT7b%&h9u9yN2Ivy?vn|-CqSBwb|aCF_zfekFVvl za(9kPgk1ibQW#8u7bqS#Lgw)-chC#P93w>R}tTm;uF5a4)3o#Ga&El)ZGWe|U7J9dxRvdQMAMa{l#Zk(|8zU&@Z zsh_=$n>J?|+t+J2W}Q)9UpvD#xd*O|p!+L@*G0vyS_URF*&X;#*y!*MhejU^SUeRC6hvKGfyi zyKv|^&$ws;MclXifcq1oI|op*W*mi$O}dvZ_EOEyjmZjWA-#ANSIeci%@Xyp-R>%S zp=?%x7otqHe8@&4c{nEOLYxuwlQPpqD(^y{DWY$_p7Ezh$VHw&a=Z(8mvwuLNo3FS` zmJ|)wsxYXZ$1@RN-6B67CI3-0`jvx>MCb{two%CP_eJlBugPe3suYjCY@|`rFGgkx38M`P4w(E*n%0h&H%>HWm zENh{6y?^KGSdSpf+53L<9z$aK^m3su)Bcyg9>Q9P@^t#%?IR&l+LrUyfU=89OJ0pgpWE9f7CP7$ zmekt zGt@dRxo}z=o@kg+rlc_`Qu;U*n>ALawzkZ4?U;>Yr!m+EW9}$mr;Ahb2?j%nLd(xF zW+s>Q25Q?eWhH2Bpy2qPeM@_ZU|tvbk%vn>E~uFpUt9)S z-<6x1G-0H1&2uAZj3hkgjcG}}#}%6?dfHABXBlYA4bu}NOSkehRiFbba9|bOp!p0b zo&4zkvgI(|o1~31#dvo~kNPV$fg+HPp_4<250~1_J-2FyY_eUZnoV|Na9y%}>(BDu zYMV9b>znG5Y0uD*x!<|FHKJKMKHQS(aLiNV4oXJ9ahV=Ts!+e1T^+;PersKk#il@i;b%7 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_disabled_buffer/text_disabled_buffer.png b/tests/testdata/control_images/text_renderer/text_disabled_buffer/text_disabled_buffer.png new file mode 100644 index 0000000000000000000000000000000000000000..16764240269f69e8b9c4a9663c9b0dea5da422c3 GIT binary patch literal 1413 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL985qF{<{lj11Zh|kH}&M2EHR8%s5q>Pnv;& z)!fs?F{EP7+bf2=42lc~4m|(MeL&jl#)boKv+iiVxMFzy9|PCF>x>NBdALs)=qMcC t(7;aam44$rjF6*2UngC3U(+2Nga8akV4sdpT8W-h=O8uV<}i-TPV3-uJ$*YhU|Lxo=_2eOlx+007`N zxqI6h0AP9fk8zw}zTqW&%ws-I1>bcF1ps)y{bMX|WqB?D07AzmxAko!^2vm!5du4m zj*ZD_Xs;2{P(4oXrNLFH=GeH?QjP-m`2+-v8XNsL^a6CGQth?R$QFyroMg!?J^{S{ z{4(2JjwEHhdj>qcEgEW*4{0>^z(RH9t9f;;eUfb;_%$MfG60Q^ni;zH$iC}Gmgz~r z)nGr$NkD83halkQ|LotNgXvrti?!I{@E!833O^vfPF?s| z{LRtL#dbL1aNri%-Q7`3jkiE{Tj;%M+VIsiOG^tW`5%gEf+AcBG5VJR@lcXV#KYur zG+R9Ody`Ymc)qgaugvR(Kv-pUd55hVX>N`*b-lOQ{5j};@ZBDSYcc!Y$wYse+atMZ zLIR}Wq|*w%n>`^Z^qTl!9OkTQCzOiW?XLH^Ku45)T}xXQ`XtimT;s#TXk;+F`(Vuh z;Oj`K^60XVPzj01p0$J3`!<0YQ|o^anb}LFMK$niSTRj#inx04Vb<@IQH6}PgFUjj zA~0ync)zv>I7OJx{g@st6uhtA>CblV+V>_)op;FS0LJL)hT*_HdJ!c0aJ=nYp5|`q zc!5ojoXbsWW*P61Z+{GDz0&D=rD{R5z&d~vGHKy)qQ?8$duRmK8TZ2+NGFZ)N$y71 z(n68EH?+UH7%{*lp?digd`UvYl@LJ z&CXGHuYG$e2MDiMmVw+R*9IJEE-lHgk}QyrO+tekW8IpwS2tSQgKi&cv>%v>`5gV$ zIP~XcNWy|P5bRo3gJTxxeVnP4fTaYcVptAFKT4_GkWh@CqWI*>d&Ycd)xNfW&_;C{mq4hN5IM7LH8rePN_4&n^MPFw0h$h?1i zTEB{#B{{;baTg)0rx~|!)jsXo&blIg;~NI%ecncH#puoC=%=c%`;J>O<<0u2nO<0Ksj?Zk*UJw?Atv23lkl-YbHCe$}oq3Ml ztX?fi+=mb|$})-74i2qI{5Gh7=|Kx{XbT>d*af?SbKU}mjO+40ANBwFT6Oc7a-(K= z{X*e1(wM$HT=LHRT!7%9xp``Hzb8O)KI^ARRJ>tW4~$17h|WKhTD*6%qIqWa>CC~5MchqS_nH1e6DWNh2*tEr z)>a~IHWRN!y5}rE6M`#f7KI+ntvN)ed_J86zU~mmhxnDs2aZbG3&38aQ3tzA12nU z!auc^Ib^=Ogb%@S^QRU^?C%GZm0XilMXGlAxkzfGkS!Aze_;djQdP>F%XX<&0wvWq zh!K~xfXebfM!Sxnmhr_>CavhBC7t=yCrUbP(Q)|ju#l1c0TYs8+Se!0


                                                                                                                                                                                    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 U2n`Q5=KTP`#K__{!oWT5KPcD75dZ)H literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_mapunits/text_mapunits.png b/tests/testdata/control_images/text_renderer/text_mapunits/text_mapunits.png new file mode 100644 index 0000000000000000000000000000000000000000..fc5297290f8a97e9bf63d4bd215886fbfaefb65a GIT binary patch literal 3578 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_pixels/text_pixels.png b/tests/testdata/control_images/text_renderer/text_pixels/text_pixels.png new file mode 100644 index 0000000000000000000000000000000000000000..6ae2fe6844eccb0e12938156efdde04bc8805254 GIT binary patch literal 4084 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 a>{=BO4!5CM50u|{74S7@`|6+klm7z|A9(}- literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_point_bold/text_point_bold.png b/tests/testdata/control_images/text_renderer/text_point_bold/text_point_bold.png new file mode 100644 index 0000000000000000000000000000000000000000..60452c964e4fc5235cb33197bbcb1bf1d1041596 GIT binary patch literal 5214 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 ARR910 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_point_center_aligned/text_point_center_aligned.png b/tests/testdata/control_images/text_renderer/text_point_center_aligned/text_point_center_aligned.png new file mode 100644 index 0000000000000000000000000000000000000000..25dc95374df6ac8a6912c0521019e1ce5471d1c5 GIT binary patch literal 3571 zcmeHKSyU6&7R5SXwGi7Xv{0ayT2urUG6cbdX91BSgFqrOD~(Yw1Wl8GA*2=sDFXFT z;K`H%3y>j(IfjHpM8SegLI?zsD5DTEKuAIck{AE_^}gSScdfJTUH6=?z4ku)ob2F0 zU!#3y`wR>WjQq}dhZq>__~S$D{Y3u*;8vFEuTPWDT|yZc7{B-sI|^-$&Gp4Ke%@!o zQp$u}+#iLDm;2YFO~S*A1OowK?I}CF9nXe3u7Bb1xSDmq_e-*$O|4%C=cH?kqnS%~ zJ)((Ia-qR7w8}5Q==yi)qX~9ZbNBqet30mA0sf(GJwaJ;+u^ut|NX<^|N5-wlPh~o4tO>H`qgi{ zUmQ5`ZRW?+M>PHiH{8X-PbH2Cj~lsNF#oYQ7#a;zSmIz{+>^`FT9QoWlTiq|9R`Jn z3zZVXAHprB=M}T^*DtIN8O3Z0J%V%_9UqF52JqPP__xDVJtNyP#fX*zlnJf7QdWdCHh^s4^V z*_SEmR)s0*SH>u@tJqVb7Wa zohMi(#0z9F_qP1F**EBo>Ed(+PhRK!jkwvpSDERCt0lp*Bo@(csc>S+eY6$N|dyoK}U?&{~Pjs<_Oq1-{-YNtc3{oQdbFbGyNhCZ@ z3A$Jz)i_utNT*r0MYDM2C0f&=wSUKrW%{&L5F}mx{th-XE%CVVktD{FV!ZZGuuR~A zOqgv|R+n0+?ThaooT1<3-fd)#wj&b9Qhb)}iH!F_0I;fnwXGsYY5E?-21ZeTP8S&M zyZ78{o~#iSNN>xmrcO>hg-K`O6-V8}AY^bnnDDZvI$u0SZ*C`6~2#X?O=S0J$;(?@M9!9Jwu0=%9#)ZNa zPr_TxI;B&Sj$ZMowdZyLPNjvFl6h2r_Cw;S_yzdz(}hXGaa-H=2bA+qaevp{fx%#q zZgnT>>@VMoF1Hl;w88)6A>ES~9J4G4AuE0QT;A#HH^$!T74fp|YP%-9D>yN-x5$^V zy(}b1*!5Laq4#tF$CmiJJT6H#+G;Yo)qpZ7k(q!}*OCxT^O0^+>O-6IX-&$ro-EAD zBtEh?kblc5{>_W83x1HVdL~OMt@l`_ZRwfrwD~y57<^;F-W1i6|K$lx>t&dE4j^Lk ztWb0&f)w{YWLo$oJVr9G;Oh@;jP7p0$QqOmfr;7{6nkK2rWJbP`f^3eyJD5G*+$RO z5TobFVUJ_c!`j0K?Kt$eDzSWxO(@2>AP`Zm*vSQ45>2`Jd8kN7)2n4LdWyZ*#N*i7 zRLipAF;&QD$zdy80pksQueDUBgr$UtZs4yfIFuGp})FZ$k6giuzqzagnEMI%^#LBCJe#_L2 zsn*t36~}0Bc_>vNqb5R6q+-Veg9K07X7%5s$kkZFyGQfG-PZuI#d+S%?yVbv2zmyO z*G?*r&b08T{Y4@()h3Q)up;y%w+=jwc#&P_qMHhj1+L^F3!m)8W8WqESX<3Kcz-VH z3(U_5ExN1&X@`UtTL-$;g!=f5z5P8EwZxq0yOkBvSY)4~<)?=@KaIzQs&Nn~gox!1 z)y&IEe>W{pzwcCK{drSfQ&(;7$Wn}o)!SBgz9Cx5%M;G{6NON&Am8C>)3xT{qna%T z2OPXdN9XTHAUUr3rU8h;{Y`>fY_Epqn}XEc(mb3-6v?Jj+so_iOJr&0QgLLO7ilQ+ zhLeq_yVNuN0_`@W6z=Uiw_oGl`mznKk>n7$<#yt7N{c^?veci*k4YbVRQ(e{Nu|>@ zTT({y>#6+-nV$(kaml?)0cgP_U8b6?Au~2OsGyD$Ft^nS)RR;Rn}nrnx3)`>M1YxV z+Cp6rUw8jPMwSs-M2UsvR|Mo5ne%a2-e!G}Zow+Yq`0WC5Wmgn&pRd6Oj_G64Jmt` zy4pwhb6s!{J=nCiBWGrNS6>-h;?u-CGJp()$dJ=`_0{MglBtVjC=09Bf2{mK(wV4F zx=Nw;>G6wmKn!Z$5}!~a9;INO-5=Ap&?opAm$%@7BbR-lW7I(^;pTkS)VkgdVpDo8 za0&s-fx1{x1jO69L&D0i+yK4TX$aqjTg>{!YF1BO)D2~w8+mjw*GeZTz#Cdg?#NeX zYXpCJWf4Z%$3d?SdHyGPHr14(T>EtX$yNcg>m|Qo3P{cB2)d?abRS{jQdw_yN4m0# zw0*Y(xNwqQ6J@d&@#B_{n$vh|7?U2wjPBWmx-zHLKil%YLM6Z;=&?33NHH-t?Nl^e zPQ4*&dP6Qik}m4*^jElunmpBg_Fh!IxtQ7nL^-QpLj0G36Nuy619pmL_wReIQ1otP zk4G=z22EMW+2B|jqpAv}N1laO3$dfkJG`=FGrGUHse_?M5Aq^AuW>zWUCFVLlyn4F z<&rByN7En>`D32=nb#g8b8yO(#Pwpt87KY3xyAqN6o!xZnN@XaQ4B literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_point_center_multiline_aligned/text_point_center_multiline_aligned.png b/tests/testdata/control_images/text_renderer/text_point_center_multiline_aligned/text_point_center_multiline_aligned.png new file mode 100644 index 0000000000000000000000000000000000000000..13ed06da89fb62a952b45f7d85f84e60906c1608 GIT binary patch literal 9584 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 VJx%p#paV2I>mPEu{^ZrW{{iz;e+d8p literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_point_right_multiline_aligned/text_point_right_multiline_aligned.png b/tests/testdata/control_images/text_renderer/text_point_right_multiline_aligned/text_point_right_multiline_aligned.png new file mode 100644 index 0000000000000000000000000000000000000000..faa18a48c8cf9adfafa63bc25cc4ee2d8a66593b GIT binary patch literal 8744 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_rect_multiline_right_aligned/text_rect_multiline_right_aligned.png b/tests/testdata/control_images/text_renderer/text_rect_multiline_right_aligned/text_rect_multiline_right_aligned.png new file mode 100644 index 0000000000000000000000000000000000000000..7c8c4af77ad53fc301a1d2f977539459783fbe39 GIT binary patch literal 8912 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

                                                                                                                                                                                    faz_T{@mst%ZXbVn(!weA%ju8&2LqM zTs{RSY_c`xZbVY0IUYuZ3oCWDa!npE9(@?K9E;%Oo6|_S2KVX2((+*W5Q$+OZR}%w zp0?I7Dc69ZU}EN?(7@3e!Xj7*i@bzQlUvK*U@D$@q1l6UK^MU(cEWUOcUY7CT8YL6umn&#dYtM!(yr2R?>>_j1G2CAkB>EN?Lzv zBJRvMF#(bYXalQVfV|CT)tzA=-sE(^NStaXeaT!1m7cbQ}T)n41pPmPVuqjM+}% ztYv}vt76-!-sOJ-gbIWKwSKg>Y_anGxm5G&o+Ms3-PYC#LGeSM1Kgk6?mQZLjjS$e zr1pO&?D+Ymve~SR1*UydK(w%45Z!xUWNm09hGeIta~RFdPh3$BFK0k>Ys+hG06zYv zwYK7N&@pG!_fhmkzEEhuiIV%DOVlH!hf?fgHRMyp*mjso0CI=H=wLlxP&ti3hdvK5 zw?QgoT&+mgHGR!j+7?Y}+JvUL&;a~*X%VyWnMZ)}R3ONvesybAGp0mZW^XG`VH8o^ zVgCroR#~L0{7NAP zNIK-;$Ks-HQzxpTO5hB(I5ZNF6#&k78zdPNs@4c+pxt-uS9;u3z|=g^GH%ts?{E)Z z?SryM4BEy@UCAT^tGu(px`BKeeCECRwb(Qfsc?uDu~veLn62ClXIFljzr8f4U*T{> zfmgfj!M5j`_JBTtL`%V2z}dChrD&b)wWeT@@A}gKhdirZ_A1+>VnB^(IZpkgU|t(@ z!+(56hcuL%7X?N0|IOR31p zNv;KA9bYB`eZ~&vcTECrVJjf7>BO$5bQh`$LTyOcPB$vK3YE z>%EAXqNZ=CwC6QZk*M_{qocU+&%=lx+O*ZI3!tE^ERHpkmmy+>y4S{ z(gZ<=Qb?cIOcL?jh1NAqd!DJ^!LIwu)$~&RX)i-VwX4g^D#(tw(xsmR^O@O32Y4q7 zgN1iKfDs01nqz8$?PX?+cJYv=_SwYuH`d_c-p1L3PrMKL0&<%iJ_$?;31lAeBzw04 zpe@cbM-c-_Oz6J@3``f2gUwhOFApkT{Z*<$Rrm)9yh`Ug_5*N(ahfD(B?4>&`H^C2 zZ3$hPpT}kpowt||ph zf&Eq7h2BuRhqpYPYdKwlgA50uc|?P~ohBy*dbTIUx{+tILX(ry4e_^FR&w$?Oujv7 zh9dA$d%2B9)pw6a_UIK1zXB%A-AD1aAGDDn`|&!gKqMxCq`GFG)4u)NM|({c-WCaH z&?F5KTjYTef`?(fv4uo`y|cirrzpUNsB`4vsH}GVD&xn!>87tFVkK2mX3sp5>)N$` z7L)FNz-T{zeG%LyBRCS?C}`s0^WHI7QtEk1MvAq=n)%i`9uNsrJYByq_2nudCl~%2 zxEl4e|Gl01f6!Ovx!L`ThUUD--@O3;>B|3SQ^NntJsA{*ZHHYwAG6gcV2cWks?w_$ JrHbaC{s%Y707n1- literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_rect_right_aligned/text_rect_right_aligned.png b/tests/testdata/control_images/text_renderer/text_rect_right_aligned/text_rect_right_aligned.png new file mode 100644 index 0000000000000000000000000000000000000000..187c4e07efb3ad225a03e106ea9146eca18d77b3 GIT binary patch literal 3604 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_background/text_with_background.png b/tests/testdata/control_images/text_renderer/text_with_background/text_with_background.png new file mode 100644 index 0000000000000000000000000000000000000000..fd6a95d437fb55e33f545ea5f0331c43abf2f52f GIT binary patch literal 5216 zcmeHL=U3B9*9Aq1AfUpPD&VznmENTUL=;q-N=c{*0tTfhQlulIM1@d9Kza#HdhZ=V zkxLCBlmH4y?<5J^A!VSCfT_hl!4kj^)Aq zyHDuo=);Z&f=W!&r0;O~aU z4fCq5dymvFf8k(YXx+S%Ok)uL>E8L(QCA^&PdLw6#EK6kQ`DxA5hD3)AuD1!OcDOn zQeNElrbXBV97F%Q2LJimuwqhFP*~wU749su2{vH3jF(_Yw`nTV`AFZn^H%d-Cm3s|AOqS;w^SUSqzj$E) z*VdAVgqDlJ(y|H-CVtQ9@4in~=Nw$0))ZPJI5u#*{p{-)qOyE0Z` zsNpzV*woU}GPW0(nV`90GZH1mE7C`DSh6@;?BZ^7Zw-DXr{# z=1Yt=vjVHT~&p{;jUf3zQ4B@b702K#LP_0H7>Dg4{2_0 zHsb%$-|y6ytQH;~u8wBK1P9xD;wGVLYHFuWoyt>={`_f8NcRx=m^U6m+29|VZnTx* zS9Gy$et*W&(lSo|rK4J&43Cb7#~u;kcZrMZ7C3rWw0MQDQF?m%nKNhn{r!bu`Sw1? zlK`GQd-mkX6Em~;=x8FykEx$_$DP8~8rP+v-HmB17W-ypl(3KGJ{veQGt=1EsHaLT zmG#mB9~c-J3rxzg>+3tUZZLn($tf8K@3%ZJG9o1{o#aQ`gL;wSJBj{ zJKJP^JAjc*LsN6I+O?~=QPJ*E{bu$cWM@Qlw7l!$U|?XNoYM5_cnzoMll?;# zSy{qpL{miY2W&H`&Wln;w8+WLHSqhKlr*`$fCq6ndGaJwS^0&Xoz}yLA$$rTnZOf2CDBEAAvK->p{zX%DVwhAj7EH30`mfx8A_WaZ;hcx~;B=g~4 zlArI`63Fthfm%N0TxHiY?N2GZ`aoCLC^s@MZv}`Czp*ez17GoS^6OU)+!+yz+Tm7M z0iq%QbyzgQ*LcGPGdwba5m5CVD|a9kAP^0{K5G+orfz&4_X=A+l!J>iQF3zM+! zIEQPJl$2x_(ly}rnD0wDJUpDO&#sJ3u?c!CF!Sq|q}@>NamqGtokJr(g(oEy?5;-E z)lm=kwz?H}mq$we(2R9Yve*dh9IJQqb>b6juY495>ZbWYr$)wceAUbg+NZXEriC+zCua z`!2+w5+5tPYeIgLwTl8J8O$v`lxys~{<8__VAet)mEmC%P~j60SX)`CLpGf#-f8_4 zF7>V6Mx9q08uPm=nzBgfdYC!1-~u#_jfKUqf$2gh`@3uEXcGpcA{=xAFUqQ+*;Jp@ zhYug7+b|$aNjtj!A)k<)ecP`|ZrdH#AV2|ybmKo_Fl7^bfQQplQ`#am?N(sQ&*f#( zguX;*LBU!g)T`WnWRv9FYrMb#A}}j9k9J|u3KTQ1E~Rk%ok4h!sS_6!5fKp?DQnes zR$N>>C}|3?vGd1|;$6#r%OX~-)3|#xJQ$4}f*2rdwtO-hGqb)xF5$(MKaUZtF+Ea( z0!0uV6XUT;ssfr|I>U;b^gVE}wzgghJ$ZhZt?R@nQdI=oKR-2L{|-@kwV?5g5Ct8Hw|z4SBbTrJv$K0$Fr*)vQ7`+R)y z{l||GT(~NATR*6Gpk7&7xhR4jP_ha1FeoSp`Y{?i=8gCY+3aQC6P!yk-R&BM-&t>j5CuwKMte5 zErdkL!fzM!`9H%HWMxVC{90}O#2&{y^zIb1oc(aJ`*h6c=xA$et9ZlV>;3HoCnqOh zICOP&bCa_i{ZBH2v%U`uB(F`XUcH)D zHD+i4gRPB}%pI&X=;`PrcrbLxZs5O@5z z6pfnCy%t*f#VCh*xYe6i=Trj$B@RR2Uk-V}=f6RsY|aXthuZx3DyNiy!E_JhnQ8`e z^*=)`zXcvpg|=(8v(ePlB%`JH&W770&kbnVA}pdb5!e74^#IV%mVn__6j4=eC@qz7 zrpTIAy-qha)k(%)hF_fi^~>pJqyOxxpAAcSdAU}U$leYSkyk_*REKV>x0Q49^Cw0| z{+^pdt+HRbbO{hpGnC%}W1PZrPDE=FpVHplv>iOveb`7+sp;ZH8wx) za?guSKvVrJVhv%imt*Ckva&lsc|_sT2?+^M_jROmlA*bI0`OEX2-zj5-q-_D1|J_E zphPMbo2eah;o`-N-DW&eVrF*s8Bj-SYd#h4;dji}YwPNOBbw`uLwy$`5(q29MOI5g zc|hH5n^eq>sDu#Om3C9>>yI=GMX-+xSEYF{z_!;^pdxfL@e3|DIdi|k7ijl2u#!ST zbMyUJP^|!q4WB{OfTdxDK)4iL=0Bdl5_pz7wOA0(5YY7K(W6&@{P;}0x!Ku76`xU( zm8m)*vAFGMu?& z8yTJgv#KviNq%$m;Ae2f5j%S2>gq!tK^>4+mX?<6P$(2(Z+>SVT#9nQRjJOi4BWv$ ztKJs?mQGAetf!|3yaHC!Xf$v?P*G7C3i@h1>{J>c2#@NQ3^=8A8Gh+5dUukOE=v$j z*ZQ9ZGRV5CgUB6k4J)I8HtG{iiQF)L~e zf=E(PvzTL!e6Rcc3*Rr_T6eFUWUZ|8u6?riv-f_UlaH@8pEEP^FrGVij``(_XWHk^ zo&R#S=>Gz~xs3ak4ty}Uy)g1TcaEj=Y@JU8vGATd$G89T*%Mvg3=%HDO?MvGy0w_m zJP!-G^~H_h%8NQxmDYFkcSB3nMDvQ}CM@ow9kJ!rm*zg}{*bd8FTa!*u7%&0yLR1K zh4)P{eGb=`7fd|Dvo|rV>hvKrKNlK$*Rys`+d!5Tjk4)$5tQD2iIZ==y;BlXIM+eh z&bujNm95QX;C`(rRA;7S!om%3X@MnmeKCOyY62#u9~&ubuheXg~% z20?}PQrs%q1)BB#L)w+)md~2y!jn^MF$_%x?O)=*8dJ-9Z$_5TszQ>PQ^iDON8LxH zq;AEUchTTQESBaz_Z3Mi$Q3n9t1Kt?dR`Oanz#~CcO#N#A0JR^VR%%vQCy2(Iq7Pb z#4d7j@3C>a*R zFu(pxh9)3J+GX17Xx9PcWLWK}M^j4|+a)+VZZKz&0!HpUFcFi!f-EW>>}V96(5v3& z>!M*{C~dh*dYdO#btyS%Z8(nfrb1cPd!Pgqng1%UDPlXdu**)`SECm5m|&abDibh! z^IBuc(W7cbO;H@8-fO@?N7EG8j{s@h%SHqO`|~lcMPcJaiS!`bO0d+?tJ+!_X>pqF zh93IRaVb+BWj68?2LETYU>|9*VRKz&gnqW)gcZNj!x^(8*JSHR>04R?314mMy$mn~ z-7SiPT%UPinowc2Gt z7Ctijmxl(T?V~>=M^Qv>NXslPOZw-?Y*fB>F|6`mPhwT^RruEG_ohETVhZf0o}$oe z(8jL#^?dHV{%Kvu;ASdeks^5dv(dTm##B;v&VF=f!G^cXLNasrtSYLOF7k<(DFER} z;bqw^e@QW=hDk^kImJ$)8^IybmT$XT8OiVU(Czm>QFm}d8M0_pFx9Pg(Ji;Uasm@i z;6j>T1|`h)9=T9Twz=#y5akXvpC3_hXtTEkwm=qmM_oGN$v3hWe4a
                                                                                                                                                                                    8ljk71z0 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 OCIhKzt5m+W3j05TGeQ#p literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_and_background/text_with_shadow_and_background.png b/tests/testdata/control_images/text_renderer/text_with_shadow_and_background/text_with_shadow_and_background.png new file mode 100644 index 0000000000000000000000000000000000000000..45973a5ae81db722b8382a4a2c8087551c6a51e9 GIT binary patch literal 5291 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 KsFo;O2mK!r!^&#_ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_and_buffer/text_with_shadow_and_buffer.png b/tests/testdata/control_images/text_renderer/text_with_shadow_and_buffer/text_with_shadow_and_buffer.png new file mode 100644 index 0000000000000000000000000000000000000000..3ee800a11436da8d1352c5c90634658faebdda42 GIT binary patch literal 9198 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_below_buffer_and_background/text_with_shadow_below_buffer_and_background.png b/tests/testdata/control_images/text_renderer/text_with_shadow_below_buffer_and_background/text_with_shadow_below_buffer_and_background.png new file mode 100644 index 0000000000000000000000000000000000000000..90246476770c8bcc7b00486a8c79e4115b799062 GIT binary patch literal 9148 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 z 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 ZdXMV$)-RsC4=gh*B?UG4a#_=${|EYFgJb{z literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_below_text_buffer_and_background/text_with_shadow_below_text_buffer_and_background.png b/tests/testdata/control_images/text_renderer/text_with_shadow_below_text_buffer_and_background/text_with_shadow_below_text_buffer_and_background.png new file mode 100644 index 0000000000000000000000000000000000000000..b479d6e7b7ffc4677b1a810b4b58a35da5af545a GIT binary patch literal 9839 zcmeHt^-~+p^EX9HixdjQp~XvaFBYV@7xz$HgS)f@mqKyZLV@7!7Tl!}ENF2E!5zN5 z|BUCE&kr{@vvW7Iv%9yquiaOKnu;v$EAm$;C@8q{a$mlppuC9tZ@ol)mf*wlGM+bV zCpkS=6coJP|JIA7Pk0n4DDP3^zes3$Wgfvjy$rYVc1~6^_vn;0$h06M{PDv4^F{MT ztzCTfsPb}NnXU902Z_o{a7BLacsSD#d`#Kp3X^{b7vB_{MDqJ2Wfu_znj_H6AbyK> zB)QC3)`Hi6JM%#bXl^4TL^meqvwr1$|F64XYBa*!-+kD3Md$3!RpJdngn0S^?t9v= zQQfq(rkuK8=y5Qk!h^ek1iv^*S!oF|!O~xPfK}mgq&V*gu)+U3^#800qy%6TNNjb7 zlu`XLLl8!x!b99)EQ@P9aW9ZTzTW77ms2-Kmqf-q(5*rs$V*P{3##dVZWp1?{8jw# z^*+3YalUNo!fankk}f)Ju&#^y^^!~h>dW(jRs7E39SY!}xQx)WMvE4&D9)T4vl`}% zs+;hokFxSBA`~mlzzWRtuZb(s8I`?BpzyllXrrQrj%&8rV+nmdsmW0}vR3UI@wxbTGpCU+SoYxs!I9kPz}0fQ z?3Vi(MNYf(1{kz4#x~ELfLov_^XAUC?g?@ScGL=6frwvdFsLPR zxfFg*%!#}zboSy{Ckh?IB{5P(zwl2G*&%?_v8cAJRxao4V#>wwo6cAv$&Bt-*^RyM zH`XL5?WGLzD*@^RkrjRQ2h}U#dpS)f-JV3UvFr0Tnc4mA0~*7!0c69&>c%nqrZ|8| zStgoE*nodul2Kg6DBrq4xAqxn%Jfyw0mA2cW3J$BX7x! zit^B?sCMULA4+_qg3tBvePh_7mO2WOK6|RY;?i}#iFQz~7}#mhPT|cz!4|1T6J{6P z2=yiLpz7_`JnTe4LZ8TueMycTp$*FOyhD$0hF6Jbf=F6p%3dG~zfJZTg%JBcG5x9P zgj&o(JTS42!JKO(BR9<8q#8}Iihx2{T1Xh4XG=np2# zv*bOGx+fffFB+&<*a87QCb{nW)23Z;YcHQV7rL=dt!+;|)7-ogOnPZ*f@_P(88>Mq zeNO<&5SV-$eodzys7Ys2XIZ{ds>-1t&^pS3Z$cX`67#2Z>H)*gbQvX_vj=~p`(0h} zD!sI}A5}*c6D2jaY}>DJfqdr3@v@opdZF6!RGYegdi3paoywxyH`g3HZ^7M>Y`>%Y z-xb*frVyr8rR3cz`0t3-UrjEOEVA8jsjQZkBoS&YyCW(*TU%E4_QmFp4v>AmMdM{7 z9W266MfX7zuWRPaC~tu3T=T-3|fY4=dA z7qGY9fSGKlsBfBH|98L4L#ULBOp&{6Ywly?8}Z}2c7oMwl32`HmBe}fs-@Jt{Znfn z`Ih=#p~o2d999g5G`dZVASn5_gF&xmy3M4B*r%bBKa*K@IQkI$ z9PuaF?{;5jUN1ywJY6MHs*JmjTEAcP&uzUE_oUiKvG=l<+VW45_uit{@Jiy;B4u62 z@IkvnEWsLtv87~QFsm1?PlfgmQ0P3E&qmUeg?onDk$AB6De|uHV=x~+w(iwBFJ9K+WiA$ zdq-A%ej>2yi`EnH!FSac#P}AgbiKm8)8`D5*Nv{SPIJHAjpVeG{@4w~F1gs6gRaUC z{UvydD}dK|5z?rcTx}PqbLKksafSBw{99G;W`*nV!?Lk-c6&&;fr*3YEuGe<2R>1F z;(kn?Do?f>Ni^lJtCe;Ek@zmIl=5Zm<^pbzS+?0P=o;^!!~$&Zz^4&%64C!t)RyG1 z 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 V?K_(4GlL98URvc#g(NWO{{V%%bfEwM literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_buffer_and_background/text_with_shadow_buffer_and_background.png b/tests/testdata/control_images/text_renderer/text_with_shadow_buffer_and_background/text_with_shadow_buffer_and_background.png new file mode 100644 index 0000000000000000000000000000000000000000..75dd6cf337f12f85074d8f6ea54d874c30e23500 GIT binary patch literal 7941 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 literal 0 HcmV?d00001 From e820da3c20231390632ec577c054ed59587fc1cb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 2 Oct 2016 22:11:59 +1100 Subject: [PATCH 447/897] Fix unit handling for labeling dialog --- src/app/qgslabelinggui.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index d783a1ec2ee1..2514e6e84508 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -84,11 +84,11 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, { unitWidget->setMapCanvas( mMapCanvas ); } - mFontSizeUnitWidget->setUnits( QStringList() << tr( "Points" ) << tr( "Map unit" ), 1 ); + mFontSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderMapUnits ); mBufferUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); mShapeSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); mShapeOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mShapeRadiusUnitWidget->setUnits( QStringList() << tr( "Millimeter" ) << tr( "Map unit" ) << tr( "% of length" ), 1 ); + mShapeRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPercentage ); mShapeBorderWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); mShadowOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); mShadowRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); From a5356011fc43eddc50d60ef4c11239294d93ceff Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 30 Sep 2016 13:49:16 +1000 Subject: [PATCH 448/897] Test masks --- .../background_ellipse_pixels_mask.png | Bin 0 -> 3566 bytes .../background_fillcolor_mask.png | Bin 0 -> 1548 bytes .../background_offset_mapunits_mask.png | Bin 0 -> 1615 bytes .../background_offset_mm_mask.png | Bin 0 -> 1612 bytes .../background_opacity_mask.png | Bin 0 -> 1548 bytes .../background_outline_mask.png | Bin 0 -> 1671 bytes .../background_point_buffer_pixels_mask.png | Bin 0 -> 1581 bytes ...ckground_point_center_buffer_pixels_mask.png | Bin 0 -> 1593 bytes .../background_point_center_mapunits_mask.png | Bin 0 -> 1546 bytes .../background_point_mapunits_mask.png | Bin 0 -> 1572 bytes ...und_point_multiline_buffer_mapunits_mask.png | Bin 0 -> 1548 bytes ...background_point_multiline_mapunits_mask.png | Bin 0 -> 1595 bytes ...ackground_point_right_buffer_pixels_mask.png | Bin 0 -> 1549 bytes .../background_point_right_mapunits_mask.png | Bin 0 -> 1574 bytes .../background_radii_mapunits_mask.png | Bin 0 -> 2775 bytes .../background_radii_mm_mask.png | Bin 0 -> 2761 bytes .../background_rect_buffer_mapunits_mask.png | Bin 0 -> 1529 bytes .../background_rect_buffer_mm_mask.png | Bin 0 -> 1531 bytes .../background_rect_buffer_pixels_mask.png | Bin 0 -> 1538 bytes ...ackground_rect_center_buffer_pixels_mask.png | Bin 0 -> 1531 bytes .../background_rect_center_mapunits_mask.png | Bin 0 -> 1567 bytes .../background_rect_mapunits_mask.png | Bin 0 -> 1588 bytes .../background_rect_mm_mask.png | Bin 0 -> 1615 bytes ...ound_rect_multiline_buffer_mapunits_mask.png | Bin 0 -> 1538 bytes .../background_rect_multiline_mapunits_mask.png | Bin 0 -> 1600 bytes .../background_rect_pixels_mask.png | Bin 0 -> 1588 bytes ...background_rect_right_buffer_pixels_mask.png | Bin 0 -> 1539 bytes .../background_rect_right_mapunits_mask.png | Bin 0 -> 1601 bytes .../background_rotation_fixed_mask.png | Bin 0 -> 2627 bytes .../background_rotation_offset_mask.png | Bin 0 -> 4409 bytes .../background_rotation_sync_mask.png | Bin 0 -> 2358 bytes .../background_svg_buffer_mapunits_mask.png | Bin 0 -> 1604 bytes .../background_svg_buffer_mm_mask.png | Bin 0 -> 1606 bytes .../background_svg_buffer_pixels_mask.png | Bin 0 -> 1607 bytes .../background_svg_fixed_mapunits_mask.png | Bin 0 -> 1605 bytes .../background_svg_fixed_mm_mask.png | Bin 0 -> 1604 bytes .../background_svg_fixed_pixels_mask.png | Bin 0 -> 1551 bytes .../shadow_color/shadow_color_mask.png | Bin 0 -> 5473 bytes .../shadow_enabled/shadow_enabled_mask.png | Bin 0 -> 5605 bytes .../shadow_offset_angle_mask.png | Bin 0 -> 5287 bytes .../shadow_offset_mapunits_mask.png | Bin 0 -> 6536 bytes .../shadow_offset_pixels_mask.png | Bin 0 -> 5284 bytes .../shadow_opacity/shadow_opacity_mask.png | Bin 0 -> 5438 bytes .../shadow_placement_background_mask.png | Bin 0 -> 1581 bytes .../shadow_placement_buffer_mask.png | Bin 0 -> 4981 bytes .../shadow_radius_mapunits_mask.png | Bin 0 -> 13824 bytes .../shadow_radius_mm/shadow_radius_mm_mask.png | Bin 0 -> 13766 bytes .../shadow_radius_pixels_mask.png | Bin 0 -> 13535 bytes .../shadow_scale_150/shadow_scale_150_mask.png | Bin 0 -> 7320 bytes .../shadow_scale_50/shadow_scale_50_mask.png | Bin 0 -> 4944 bytes .../text_angled/text_angled_mask.png | Bin 0 -> 3199 bytes .../text_blend_mode/text_blend_mode_mask.png | Bin 0 -> 5082 bytes .../text_renderer/text_bold/text_bold_mask.png | Bin 0 -> 4201 bytes .../text_buffer_color_mask.png | Bin 0 -> 6261 bytes .../text_buffer_interior_mask.png | Bin 0 -> 4249 bytes .../text_buffer_mapunits_mask.png | Bin 0 -> 4783 bytes .../text_buffer_mm/text_buffer_mm_mask.png | Bin 0 -> 8334 bytes .../text_buffer_opacity_mask.png | Bin 0 -> 7307 bytes .../text_buffer_pixels_mask.png | Bin 0 -> 5183 bytes .../text_color/text_color_mask.png | Bin 0 -> 4292 bytes .../text_line_height/text_line_height_mask.png | Bin 0 -> 4368 bytes .../text_mapunits/text_mapunits_mask.png | Bin 0 -> 3306 bytes .../text_multiline/text_multiline_mask.png | Bin 0 -> 5593 bytes .../text_named_style/text_named_style_mask.png | Bin 0 -> 4687 bytes .../text_opacity/text_opacity_mask.png | Bin 0 -> 4132 bytes .../text_pixels/text_pixels_mask.png | Bin 0 -> 3320 bytes .../text_rect_center_aligned_mask.png | Bin 0 -> 3316 bytes .../text_rect_multiline_center_aligned_mask.png | Bin 0 -> 6592 bytes .../text_rect_multiline_right_aligned_mask.png | Bin 0 -> 7593 bytes .../text_rect_right_aligned_mask.png | Bin 0 -> 3314 bytes .../text_with_background_mask.png | Bin 0 -> 4238 bytes .../text_with_buffer/text_with_buffer_mask.png | Bin 0 -> 6193 bytes .../text_with_buffer_and_background_mask.png | Bin 0 -> 8410 bytes .../text_with_shadow_and_background_mask.png | Bin 0 -> 4252 bytes .../text_with_shadow_and_buffer_mask.png | Bin 0 -> 7217 bytes ..._shadow_below_buffer_and_background_mask.png | Bin 0 -> 7231 bytes ...th_shadow_below_text_and_background_mask.png | Bin 0 -> 5602 bytes ...t_with_shadow_below_text_and_buffer_mask.png | Bin 0 -> 7276 bytes ...ow_below_text_buffer_and_background_mask.png | Bin 0 -> 7190 bytes ...t_with_shadow_buffer_and_background_mask.png | Bin 0 -> 6245 bytes 80 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/testdata/control_images/text_renderer/background_ellipse_pixels/background_ellipse_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_fillcolor/background_fillcolor_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_offset_mapunits/background_offset_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_offset_mm/background_offset_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_opacity/background_opacity_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_outline/background_outline_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_buffer_pixels/background_point_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_center_buffer_pixels/background_point_center_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_center_mapunits/background_point_center_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_mapunits/background_point_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_multiline_buffer_mapunits/background_point_multiline_buffer_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_multiline_mapunits/background_point_multiline_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_right_buffer_pixels/background_point_right_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_point_right_mapunits/background_point_right_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_radii_mapunits/background_radii_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_radii_mm/background_radii_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_buffer_mapunits/background_rect_buffer_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_buffer_mm/background_rect_buffer_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_buffer_pixels/background_rect_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_center_buffer_pixels/background_rect_center_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_center_mapunits/background_rect_center_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_mapunits/background_rect_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_mm/background_rect_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_multiline_buffer_mapunits/background_rect_multiline_buffer_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_multiline_mapunits/background_rect_multiline_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_pixels/background_rect_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_right_buffer_pixels/background_rect_right_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rect_right_mapunits/background_rect_right_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rotation_fixed/background_rotation_fixed_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rotation_offset/background_rotation_offset_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_rotation_sync/background_rotation_sync_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_buffer_mapunits/background_svg_buffer_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_buffer_mm/background_svg_buffer_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_buffer_pixels/background_svg_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_fixed_mapunits/background_svg_fixed_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_fixed_mm/background_svg_fixed_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/background_svg_fixed_pixels/background_svg_fixed_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_color/shadow_color_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_enabled/shadow_enabled_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_offset_angle/shadow_offset_angle_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_offset_mapunits/shadow_offset_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_offset_pixels/shadow_offset_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_opacity/shadow_opacity_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_placement_background/shadow_placement_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_placement_buffer/shadow_placement_buffer_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_radius_mapunits/shadow_radius_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_radius_mm/shadow_radius_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_radius_pixels/shadow_radius_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_scale_150/shadow_scale_150_mask.png create mode 100644 tests/testdata/control_images/text_renderer/shadow_scale_50/shadow_scale_50_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_angled/text_angled_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_blend_mode/text_blend_mode_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_bold/text_bold_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_color/text_buffer_color_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_interior/text_buffer_interior_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_mapunits/text_buffer_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_mm/text_buffer_mm_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_opacity/text_buffer_opacity_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_buffer_pixels/text_buffer_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_color/text_color_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_line_height/text_line_height_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_mapunits/text_mapunits_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_multiline/text_multiline_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_named_style/text_named_style_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_opacity/text_opacity_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_pixels/text_pixels_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_center_aligned/text_rect_center_aligned_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_multiline_center_aligned/text_rect_multiline_center_aligned_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_multiline_right_aligned/text_rect_multiline_right_aligned_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_rect_right_aligned/text_rect_right_aligned_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_background/text_with_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_buffer/text_with_buffer_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_buffer_and_background/text_with_buffer_and_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_and_background/text_with_shadow_and_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_and_buffer/text_with_shadow_and_buffer_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_buffer_and_background/text_with_shadow_below_buffer_and_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_background/text_with_shadow_below_text_and_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_buffer/text_with_shadow_below_text_and_buffer_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_below_text_buffer_and_background/text_with_shadow_below_text_buffer_and_background_mask.png create mode 100644 tests/testdata/control_images/text_renderer/text_with_shadow_buffer_and_background/text_with_shadow_buffer_and_background_mask.png diff --git a/tests/testdata/control_images/text_renderer/background_ellipse_pixels/background_ellipse_pixels_mask.png b/tests/testdata/control_images/text_renderer/background_ellipse_pixels/background_ellipse_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..c65cd62208764937b44d6b305a9f31c4e49e24ec GIT binary patch literal 3566 zcmeHK{XdiIAK#>jXcc)5M;(%OJ1u zPwpNv;;z4tXjk|Ysp>_bw9>g)k3GFd6$$Uh#mzG0nC{{CAtYR7%9&Y$}IP4M*=Unbdif+^ti9}`x5AKxNrnwK&tD;WCcN zvl?E9G0w@!35<#|^YZd4E-TYdPDy#t+KTR(j{eoPbcDmn469T3_4Tc8YEow~7-m*h z>UZwkF*7sUQF^wVn*#s1M`~z>hECLqiHTX{fA~XHTbnY~Md{*lL*(V zJ2g@rWM*!zh(e(h(1}tFTPmNbql6q2E$wH!q0~S~yFhz4%J^Ga6OA$ircE z&#sFgzZR&DYasUU_GaU(=LOIYDl0cuX7h?VB~T5Oo`?{ajI-G);o;#?v#$z3@Q5B? zA7lO$1aV=V#Xh0ayFl&l*%F#S_8L)$A*uZQ{KXaC7)p(j z3NTq3Lwdu7u6CFSaEhpvkAD_pg@)Ky_tIpLT1u!*A%J7SfP-cS4h*amHmw;>M<0do z_#ixY=0p^_?S*Nt#4=u zif7N7zzUy-J)WMPR#j8`>f7qi^lpX(`z61HlM17uU zU!A7YkR{F8Rr#zs>^L&K>bCbw7T)WGoYPyB!9jC{hLYZLdI!$O(2w-ubSyL;c` zLSB4Np7Q5eKSx{@)WR`~e_~91S|HhgP}at;;+rzre(O;thl$^`(=0NVyxnx$Tp5NxKzKUYhGCH59aJ5r^0u+bSe9eQOo-;B&p1!fMA%RY^HE5As zqG!cVg;uw==>Z4~*qg0*5c0FLl>OZrB=?fkkaWRPPqW9XS|VB>JO^Z^UufA69rI|p zx~RKN)ABT5{=OYpmF@cD8#bFv8}tO+Gqbex`8F?cheLxvf5@}}r8-O>u4t3gkWmU! zJ5%4Cri6N6kVB;g#m3fh)$H1(OOCItt$}{t1?J}j5TDNn0V6Jxw&CpzVyz1fhdX)lWXCNTB#E{}8E;KQKYaLbyh(c1l(q{Kl8|6? zftk>VjTA8J>y>ew=CnP|nM$b5Ar4YQfwTREl>8&OdQsWausY0m(-lM8HSPn6tUPYu z!V4aP4)pT&o|>n(nm|3`S_VUdU3s1i?CKbfo~YYa7=t)VynXw2ZfZ$l)I7WcQ! z*Ua5$HfjzI4wB4sfiy-(9|Z0+&Ln{DPrN+E%1~8TCskKhOTxI>$sIzWb^~vUc;y&5 z{%i**yIY~{dA?Era(mXzzTRHPM!!r`=4x@()_K59Td{EYk>~!Xnch5m3mD$r+wr3^ z>Sk(EQqnUCDr+Cgfcs$L#;KY?Y%uH5WTbus|kHtDB(IsVN<;k+b>!b(H6xKie_l4G(is8V} zPy=NZm7t%0{;`R{2nr5<-!S%s`cL;?6nFyYM^i}Q>XXV{q>loS|Lm`175AQ(*r^vDSR-+J=MzfWZU4=mmp NJYD@<);T3K0RXMY+;so| literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_offset_mapunits/background_offset_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_offset_mapunits/background_offset_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..8af0d3530ae70bc66f65dc1f30fa2cbc16b6094c GIT binary patch literal 1615 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z#^~wd7*a9k?ahsyPJs+A7oRK1vluITZ(#p@oG<6#1)rWfLMiY0?`b^`F}TT_W_+xI zm*L0a`8Syve)upkIVdSGsEkr{4T4Q`Z5#f-|5?*_`>k0uo3?EK@r^pC-$>R7GCo{; z{ITJ>>#yHPt|_sQN%MbjI_H?g`kTrOKWyv-7=#!Z6$D2pHRe*pOs@g@cd&V!vqcvhR%jjYBUIj dZ7Mja-ZZrveBY(@Y~*41 zapC?OMus($8yF^Va4>X^QX?n`a?<%5%J1fF|5#y@cK!kP@yCTRded(j{}5zMH1%74 zxnghJ=JXG(haVbLGudyEOxD@#&alC*PJuy%iOE4}BvPB^+A`exT4Q&7lMX0k?&g_) z`~CNgqXTq2>%fOM{C8g9pnfH5vpoP6bco Y#a2se@^z}q1FHuHPgg&ebxsLQ05s5OI{*Lx literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_opacity/background_opacity_mask.png b/tests/testdata/control_images/text_renderer/background_opacity/background_opacity_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..38bb2e27ec43b96a9b55ded145466f11df4e6885 GIT binary patch literal 1548 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zy3fFyYM^i}Q>XXV{q>loS|Lm`175AQ(*r^vDSR-+J=MzfWZU4=mmp NJYD@<);T3K0RXMY+;so| literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_outline/background_outline_mask.png b/tests/testdata/control_images/text_renderer/background_outline/background_outline_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..fd48aab036e160a0be42fb963f2b417f2eb121e4 GIT binary patch literal 1671 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zX6fnT7*a9k?H$J~WkUgnz|0eW*WZa`-7}N(r_W-)pL>NlxL)rr*#150briz~=XyVR zhKBo|4h$YFEDbKhj(YO=3*)=8*y}HqKg@r-*I%A7;;^~E#~CMM9!h?T%6_u^Tc1npY}}FZtZMFZUzT%H;y^Y2E)OJ+u|DapIFq)o;NFRb9WnQsEe}T~*SoMk zh*LHfV0fplz@Wm!G`uMJ<@^PgN@JJz zABcYg3eF#GyethV>$leMvOhSEVAdPlGDOpYf#k@|=j$oBr~Q z_&I6u3D?Ch#26XxJ$IG69jr!GX>upK&G8rFoJW)OJ~n)I%TtI4DwwHlbNB_&ir+o= v92j==H!w`#0EX`;8yF^V zaEwxeAqa9-v)8P;{(5WGp|!cU&H5fk*fLi%H~dMw{~a8CJFA#JEITgoILel(;r(Ow q!H~KJHf@jEKEQ>`Fo}Rq+&7o<9R7Ut`9Wa$&*16m=d#Wzp$P!<6%f4u literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_center_buffer_pixels/background_point_center_buffer_pixels_mask.png b/tests/testdata/control_images/text_renderer/background_point_center_buffer_pixels/background_point_center_buffer_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..7f954d1662e3cb922c8e0e135be4249d3c04b37c GIT binary patch literal 1593 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX z`r6aQF{EP7+nWbhG6f2-Ui_9Uz?Zgg#{XM$9d{UT_dXOqarogJj(6)8{5CLt&)87^ zE83Q!;l7Fjg9;OqgVKOfMKQJyX2-3+ZZrS<*rU=;Fd{ywzrCfVgGSX z?gkeJ1`igNQED&*LEmcjn#+$r&iMUzU)8a7ck{OIjL`$d*BdK^<(D(pU4Q*ba`(2} z+pjneD7DY5TrbCX;QdEtMg>6u1|h~#YBUH&QvpR8;U`0csIaf%uWfUIbpeB?tDnm{ Hr-UW|0Dar- literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_center_mapunits/background_point_center_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_point_center_mapunits/background_point_center_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..561d444ff393123e61ff9b420b5e0e1754311e78 GIT binary patch literal 1546 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zy2sPSF{EP7+Zz`-nFBc(9C=^ve>z>P==4EBqu_=gPn)cb(-|Htx_+6P;lpeemIfCG z29Hr{Gzf5{f_vrsHqYDZM-eB-8D1g>#qbEYUIVm z7&;pmCU9_!Qjj3H6UJZh+~$0x-Tc+*9~SpLo>6;0{Cq?I*0X1}RzW^EryZVxPg&)z4*}Q$iB}5q2vE literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_multiline_buffer_mapunits/background_point_multiline_buffer_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_point_multiline_buffer_mapunits/background_point_multiline_buffer_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..828a5aa0c05730a6ab5c23e14ea07c788ada7685 GIT binary patch literal 1548 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zy3f_U2&fcEZ!MB MUHx3vIVCg!0682n%>V!Z literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_multiline_mapunits/background_point_multiline_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_point_multiline_mapunits/background_point_multiline_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..ba35df3680c6ab6de21ef90fd901653267dcd696 GIT binary patch literal 1595 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX z`qtCMF{EP7+Z!7Tj~EEBI655lnJF&3)KT?Aeuj+0(RUozX78Gv+>_35K>qIIwaONT*NI(*`GI3OjxAt(PKur^@uboFyt=akR{ E0Jm=34gdfE literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_right_buffer_pixels/background_point_right_buffer_pixels_mask.png b/tests/testdata/control_images/text_renderer/background_point_right_buffer_pixels/background_point_right_buffer_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..05e2d0cf686f08dbf105c999344e38cfaebcabb7 GIT binary patch literal 1549 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zy5G~qF{EP7+ZzWbGAjzO9GuDh^S#mYrfqgdw2X9Lh_k*qGl#LE{a+qG!-KgjEDbIW z3?2hZ*==X9c|51M`q25?cW(?KENf&Fp7YGjO;Qz@{Q9{T7l&|gQu&X J%Q~loCIB2442%E( literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_point_right_mapunits/background_point_right_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_point_right_mapunits/background_point_right_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..f3df45d569daa4be7e51636ecac595c51fb15c9f GIT binary patch literal 1574 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# zdc)JjF{EP7+ZzX09%2x1y?FAtoXezt+T9cM{_t`MpUXO@geCy~{U6r= literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_radii_mapunits/background_radii_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_radii_mapunits/background_radii_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..1c4ede6765cdb0298d48f6e184a0def28d57f312 GIT binary patch literal 2775 zcmeHJi&N5B6#hXEEH&+6nxZn*=(LvZwt+oN+15vn0hIxnskK`oxRsAU#YdKv*=E>o zJ2|FUS!ftin=C01md`dHm4XR@q^=GENeZbcwAb04*?(cD-8*yV&bjB_bMHCle&4wT zyYXT6i(MB(5M&>|Gk7lq!HVX(%|bAfE5)>fVNue~s8k4YI6T*3RY8?h2wGea9{kO| z^iqSWi?AZ!v*o?R4Qz$S+VxiKv7+=U>N;24t^l-EX@152!5+h0t#lL$oc8Z1d9{*} z_k8lj)e8@JfoA2EPTeoz=jUF?g&dbU zLaX6$Y%mtOU}FO<{VbJj1snu2tm0+W`NqTc3-cPk-{gwkUY$HRIEY50=|e7VZi&p5 z##0+fL)MGD}qKRu~#~YpaXhs7c$6 z_V*{3;VXxShiMGPZ+LbrUmQPk47h*6NT73L)TeuOd#}NWB3Q#=suct=4amJj}!?FR%_1ooY_YtGFjJIwoP#V z{tMGujeRW!1w!T#kiJ_a6458$sY*&pXw1DjgTWwkj?3CZ>09$%j5B6l=5u3X@!PR>x+uZHWOnWCEWz>zcH<_wkQ+_ET(P(ePXzSQwi~3atW6* zC9xnQ7hAtdHjm1f?*~FG#zqGm0Tx?9glR$6#Nsz5JM~k8Qka;XEzz!ONUR-RDSt@m zqA{8E@f6B+_S0ylbvC1r#pvhm%#QaRD2uxm>MQd;S`9Dxuk_t*Pm3Ix_VsY^rujKusS4K@GhERah3O?KAP z5{ZQ44e=8~uz^#WJOB?|m&Wt8T3rJoz@b2X)DUb-YwLocVx>YsW5SIWm*X6!gzfF^ zJ#smzqq7sU{hZJ=J3Zm*d7?SfeKYC61UWJIaxiQ4_O&Fs`5i~jCS9k9etz+t)E zt!4P^i4K2o$c8M7xtDI8ou1RZm*{53q$ik*PaHaSjOXR$Ma#)~tX&6k z{RN6h6rSj>k;!Dt5BjL?$SGS%EFZiyl{n)eSW)f*D3KF3s|1XolAe+dkBlTzsdu$o z#NQn~dgr4hM8JHAc?btuTAJ{kS`r-@2>?iws8p(tu%jOv>m6)mCDQ2v;Af<* ztu2lKS7UYa_7c&6QC?Pr$#iBKxCsDqVoJ)d+Ne(%c~5RUwtP@B$A`i<`1;Dn$5YAz zGJvMRZCTMZyWG!yckz{xl+IErbKt@IiLM~Bw4eVs2TCL{&VI20 zmmWr+Ps&=<*6*?;Umy_B)8YEb8S`^LX%A>u8i~J;NtppIc1u`qllB8cz+S40rmrtb zcvlm&0}DqW5MlVMc~2UGwsE-y1qEyNl$Dm6);i7RF9MZkGUhX`K>w9W`@f%`(YMNq Y(5ThEoP|Ag;HL_Ohv0*2b{snMCtKRi?*IS* literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_radii_mm/background_radii_mm_mask.png b/tests/testdata/control_images/text_renderer/background_radii_mm/background_radii_mm_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..6ecca1f51cab3013d185e5e0131d3515614cc544 GIT binary patch literal 2761 zcmeHJ`!kzq6#kNGy*~)8f%BP?ja4k)}?i==uH!J+i^*SN`v*er0wpiL9wQ; z4c(n_i4cM$rA<(smbTb7LdlTWQX~y=NnC>L$Nsec!A^I7ICI`P&&+w}yzhCQb8gs?#3}$)U67W`2 zBi|zfhxHEw$Kh~K@6QrU?vTQA1{W6zI*0D=(Bdjhb#oGiktdLppn}4}3v9t;_kDA> zcZzRB*^k1)xjVZ(Q70Od>q}#!qvz%6oQa8v#=5wy^;y@`r*V{^dMOq0BFVK03K@+P z*bxp64o)Z(mdE3f#3NKw3yVbXYnh%#e^^RNN_=J}hr6Q?Kq)3v@03!lq~zo_X>QJt zefM^og-A#ri_GSfmX^lfy!lq+pso#UGrU{a^5DUPE^wVNI5^0!aEK8XxJ)%LP8R0k zIyf9oSLzaOvXfY!wK1K8Bz_FQK22kEO%en=^4y6P*!cK3waO)N6iSPo8?I@Yot;Id ze7Y!T_wnI5l9USRWh}OtI5))aB+fnb6BQXRkUi35kLWng<-EK+()6=~>$4G##@g}M zuh()_yUMQQ*)tT6AKRqPyPz)BuUOE5D25b7MU2|!mTe?y?Bm+nOh6>q^-4u%QzeX)RiH8>@3a9%$N*D z=u)>TOAxl9Rg#F39iIJvtE6ow)bAF;KMp2g{=MDAwY6u87;)yrHmWW5N|>c_$K zwfRs%7&*q6s&t{zX!7YCi}dBCB4aZ%T2^;tWTrfPAFVLxA4aRL5Q)UBI8uK=K)?vC zg)26MBmU@Do0;N(%*T)4E41PD!8LRylgWw!f=w#OX)Pj|_!g4%=kwhCNN$W}p#@rz zvU+U&m2C@#=Sc8+20L}cx`@GGRF;>=f`?Q+%O76iQ&ZVelO6+~={$sah!qJ=ZLF-RX`xc7TQeoW@i8&=Qa6w9c#iVrmlk7dYqti6 zhFB=X#sNyB>44G=kH?cfyeR0(*h~%#3}m8mA`=o5$C&sr@w?iyPH41HVJ-^Jzv0=q zt0eUDX&3O((ZAW@p3bB0egP@W*2-&pJdxN=ztVZmI=K1*TI+T=@Kmy3grXWeLR=?UXI$Si@@#IOw-QFlweC3P0 z+~E0JNM$soyu5+HmN;8(pVfe-kIEGOdC#2x%543=&d+3#+D5dW>5u(+wyhA_O#%P! LgS_eAM&0=faPYKf literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_buffer_mapunits/background_rect_buffer_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_rect_buffer_mapunits/background_rect_buffer_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..1997cd96a4b14747bb5e7599cf07a4900d51245f GIT binary patch literal 1529 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zy4uslF{EP7+v^(znH+go96Oc%PwAJao723=y6LOit(lh04E%fZ_!%CUb8;|rHZV-! z7^OyofXGyE^7prf{Ni&vZ6CgW^X@ID!vkhUg_|=AibXkyV0yS(o3I{ Z>~HRK$lIhmYy_6(44$rjF6*2Ung9ytdjJ3c literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_buffer_pixels/background_rect_buffer_pixels_mask.png b/tests/testdata/control_images/text_renderer/background_rect_buffer_pixels/background_rect_buffer_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..ec65a7a045666fc010918cb0a3d3d8091ae32893 GIT binary patch literal 1538 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# zy2aDQF{EP7+v^8;4><_195mhKBRh4mso@11zQwCJo?V}noc4~ffq!oqKf{BWEG!K! z4h$Zn)MyZpmgzopr0FPmEcmMzZ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_center_mapunits/background_rect_center_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_rect_center_mapunits/background_rect_center_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..3da9cb411869569c3f593dd292c603ff864df6a2 GIT binary patch literal 1567 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# zdePIxF{EP7+nXCF9ySnQaeUw{Iq|2v!?Bir$HxvjW$qiU^%fTQY-D4od71y6fnlDf z1A_+(OM}aBrtEgJi(D^#JMTdE+~+&1nf|o6v!$E^G7h{xYk2IIEmOnukIak;f&vUe zjH47V2!6hi3%K)rZ#9#CnauHboF9bcBqwaW_KuTbz4>v8b%qS_pGSjhG^vc{7J3vI blj;+H@+;q7)ldg4@fkc_{an^LB{Ts5`>L(# literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_mapunits/background_rect_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_rect_mapunits/background_rect_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..73ed4b6a5230c3a752e95bbc66036c4d53fdcd09 GIT binary patch literal 1588 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z`pnbCF{EP7+nXCFG8qcEI=<{u5&Oi?YsNFTmH)h;$X&sj?0JU8Jsa5=_Posh&cLv5 zas$Hz4i1LS;Y`Jp@mK7+|NgPf`MbtH0=M7Jl{vn#nyqGPKj(=##b+$b&oex51%^pk zKf{CHKN^RBcn}}oppdJwk%NZZ_1C3{kc-M*v$YHoau2hZKbYAIFbFX+DhQ5Jqd_p5 f3TT=UezNbVlu#DPn`;5A1{geD{an^LB{Ts5?d|j( literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_mm/background_rect_mm_mask.png b/tests/testdata/control_images/text_renderer/background_rect_mm/background_rect_mm_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..e4c3852a251267453ae751406c7f9f7beb971760 GIT binary patch literal 1615 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z#^~wd7*a9k?ahsyPJs+A7oRK1vluITZ(#p@oG<6#1)rWfM-G&%f8hLW4wu^QgKLgS z^fNNle=)9RV7Tw;z~I5c(%>=zsB4?qYYzRblb?P%^&8K`+J=d1G z;+Ht%%^b7G1r}%K9h^Nab>?W8jqrqmFA(=rp7You>^y^? zmxZOl#eu#tYX&EK7VVC7shh2nD?uidh3mN$KV z$ClAAzt1oxli}Z4{?UL$B%&v~st>47Kb?9fZ~I;2AA#9xKUUb3oo@)X&ULsJm3(ez zHJkmbzjg2DF)TL+CdTg^4Ey@!IT$({7$$IxQlmjInhJ=`2q)zqI7=(6P_;AxRtXHA Lu6{1-oD!M*SwTzMJ>aaQp3Cnd2L)*)}vb?715)wd4`JJmd7G? zyEA;K{o}yk!NStuGD?AhKyNqupIOHr8=m`o$M$jZy6dkk`jWr%Brr2pZrpk;BKz$; z#t&u1Jr8d&elW2YU=U(tR1h4cMuT8970@&z{ABN%DxsVh>!tv#1{geD{an^LB{Ts5 D-x`JIRD`Q;D&+zBP)@lZZ^C}7q zDojicN~6?h5RjM(-rr@enD^P{`L1<$jsM+>%Kpys;}kQaf@RvXd$vps&p$dac(AZE lxQtSxK`@#M@MnZ4%mHoO@-`3BC4r?ngQu&X%Q~loCIF;;2h{)o literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rect_right_mapunits/background_rect_right_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_rect_right_mapunits/background_rect_right_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..d910e0c6a47a1d92edbab07aa9076969e7db72fe GIT binary patch literal 1601 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z`q|UPF{EP7+nWbFl^q3K53WhA5peo+--z>8cbxQ>1)6Chi3jaPzVhu%dnUv1@~ literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rotation_fixed/background_rotation_fixed_mask.png b/tests/testdata/control_images/text_renderer/background_rotation_fixed/background_rotation_fixed_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..a2e2603246959f9a4c866e82b828649bdc29b881 GIT binary patch literal 2627 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 F`7eB*K4Sm? literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_rotation_sync/background_rotation_sync_mask.png b/tests/testdata/control_images/text_renderer/background_rotation_sync/background_rotation_sync_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..e649fb27dbfc25e8fea61c5fcdeec9d48f65983a GIT binary patch literal 2358 zcmeHJ{ZA8T9KX93dM7VZh{&+C2exQvfuU1iLOB&E2%>I_79q8$%q0XU;4CPGLl`e9 z(t;7t0W~36wung62{;f>hTLHhvJt@qoH!t`@Y*^86d60;+noG>T5q&#$R2W2NQ&y0D~YvuavA-WZYd43qMv@We@3;2Wq zp+dQ_ypT2SP!}`PIyIrTmn4f?TJWkS%+v3pDtl>FW{AMqBJFKDT+w5m3k{2=0iE)d z7syS_6H#7ZIE_3ld+W9~nVVP+gs`>#Hx|bp%)`h63}zXWk2G;}!7uO4WwmJx((t2xmyA z%moIoxvBfB<0WCya+xz_BjsuICq`X9qV5Bx{1SyNWcHZ5&r|yH2@Z3-C;R=ZQphJ( z5z1!SJlr4X*ek*6C=1XRjn(zKeF$h2^oC(|T^1MeaX}yg7s*vbHgg=|ESFtU5$()^ zzYxFPNX*(G?$(RtDVuxglw37)rRVua=4Dh9kKchQ`CK)b=ADoN9VlM(D@#I16pik& z;426P*k_Y^@n`_e1N(9E@tMo2Qkqu}!$1jcyTxOIDSPe{K@h_mEWLAYuFiZ7z9zamax3(ugD*B(y}tgp@m$? zj4FFqV|faD$Q(7uB61Omu|-V#=qu%owN@&)P^WPV!C-ZaNqGvN&CH%{DO!Ok|DbfR z^%RyfT9y?u&FG87=9Hsust#H$@_q2lsad^6Sf*aJS7-Tghtl$9)Zlnc&EaEwI zJ6@EMzk~Wsqn)&!L!$(E>Cl=WVG18f(R<&ZkQ4OMnF~%U3OU_FAV?MfV{_$LA`nc~(~p zBZQPU-0Z#NeO<`mz8ab2AgvSqZ6U;w_*`~QPM}QkVz+?kuZ%}qq=J@M9uXW>llQSO z!x1N?s8Y&bZ;khf`sZn$j$Wq*S0~LQd>*D4XKhLr!E6b3bJwwpDj+1Sm>ZyAHDQIV zyUXhTcpAqeQbjBI1@&(&&%35Cta@1YQBYPzeckP1?m}E2y|n`o#WiP2&6%j_deBCs zBGjH!QHE7fJ2v)XDxNYx literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_buffer_mm/background_svg_buffer_mm_mask.png b/tests/testdata/control_images/text_renderer/background_svg_buffer_mm/background_svg_buffer_mm_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..8847d180bc4f4e20fd9aa3a3b5cd34d3cce54d5f GIT binary patch literal 1606 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z`oq)3F{EP7+nWn}nF1MHFP>*J<*ZWSy-=@e(jep8lxmyzzUzF-xs?xgYTwK3`6$Qm z!QFl{JHrNlCME|Z1qPL2L_NRByzlJipE9?%ot;<6@p@O^>8D23YyzAo+ONMhmFqwL zMzUQ&ZbSZZ!(-LoI2gViXCHPUK>Nr9hw--D$94P91H*Xx?c6o5tsr5X8hPw%)m+=h z0@G4w+A{uVzbx_Cwwi_E_hV*81wjD@A;wW^Gzdmh0hKbsr1)Gzi44QJtUADofx*+& K&t;ucLK6Txytq;T literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_buffer_pixels/background_svg_buffer_pixels_mask.png b/tests/testdata/control_images/text_renderer/background_svg_buffer_pixels/background_svg_buffer_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..9f89164ee66b8c3a1db1b001ef2a2b18c15ef2a4 GIT binary patch literal 1607 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z`qR_JF{EP7+nXCZog5ilFBTeJIPoEw^V|I%UJfZK$t>Qu35nB+wJL7%-plLxD97+& z>HeF{3=xwX7$$IVFm#Rp>Pw|2#0v zo)%b~naA+w1Tb06vt?@d`on?2gN3ERWt18Xg3(k!^Ne7}<{**OeM#^gux4QJboFyt I=akR{0G1Md5dZ)H literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_fixed_mapunits/background_svg_fixed_mapunits_mask.png b/tests/testdata/control_images/text_renderer/background_svg_fixed_mapunits/background_svg_fixed_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..68920720d27a875dce3ff695fb098314b6f57eca GIT binary patch literal 1605 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1Aih2Gp?{-p2@(# z`rXsTF{EP7+nWb-nH(8d4jz3ZbfbY|owrWQ*RJPZw5D_}*pq%GH!Y5t;s49~ z?-&_s)EF5R1O*s`hC220rtJg$3LCl2*KXN9em(cO<@evU-+3PRZl78CR&L|%sO)vG zK@zgZ4WC!Oo5#4v(}BUGMu9b8X0m~>g8U&-Mfc%V5$M{)8ZuZqr SwUWSUfx*+&&t;ucLK6Tycq-}u literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/background_svg_fixed_pixels/background_svg_fixed_pixels_mask.png b/tests/testdata/control_images/text_renderer/background_svg_fixed_pixels/background_svg_fixed_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..3a7ca25c7d6c71b7a39004c6d6a9c6f141bfd9cf GIT binary patch literal 1551 zcmeAS@N?(olHy`uVBq!ia0y~yV4MKL9Be?5hW%z|fD~teM`SSr1K$x4W}K?cC(XdX zdeGCwF{EP7+v^uISsZy-9Z$ym)9gzB@*k!1L>c>Zl>h9C1;SQ=a$ z7(7NPq#$@wTzz2n+~Pd{iX-pt&10xxl;>bLdG3t$`4k4Zr_78Bf&vUej6;K(bp9=4 ze%ZO5whsk&S64HAV69PLP_Z_CZ!?*(VhaCg+>fSvq;x-85Dbp8@QJu=4v+j+4Ws|S P5}v`+)z4*}Q$iB}Z@Mj6 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_color/shadow_color_mask.png b/tests/testdata/control_images/text_renderer/shadow_color/shadow_color_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..546d7af5a7e66cfb5bf33b4c1e9fa28a89b7fe6d GIT binary patch literal 5473 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 E0ZZhe5&!@I literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_enabled/shadow_enabled_mask.png b/tests/testdata/control_images/text_renderer/shadow_enabled/shadow_enabled_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..da3f61d37edb3d7eec22929b516ccf9644404f00 GIT binary patch literal 5605 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 Ximkq+$N>Acd?tn#2Bm-A{p-H~aPIVj literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_offset_angle/shadow_offset_angle_mask.png b/tests/testdata/control_images/text_renderer/shadow_offset_angle/shadow_offset_angle_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..217fba1d1b5f09f995082368156fb7300fb5666b GIT binary patch literal 5287 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_offset_pixels/shadow_offset_pixels_mask.png b/tests/testdata/control_images/text_renderer/shadow_offset_pixels/shadow_offset_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..059c2cc7bfb0ed40334ff4ff6f2dd7bb253d8232 GIT binary patch literal 5284 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 N*f?3&TR!^re*m}ZZL|OY literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_opacity/shadow_opacity_mask.png b/tests/testdata/control_images/text_renderer/shadow_opacity/shadow_opacity_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..d8bff7d74f8ef017cb0db947460b7bc12351293b GIT binary patch literal 5438 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_placement_buffer/shadow_placement_buffer_mask.png b/tests/testdata/control_images/text_renderer/shadow_placement_buffer/shadow_placement_buffer_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..d16d657c027a8d15e4ed923c32f5b055edac3868 GIT binary patch literal 4981 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_radius_mapunits/shadow_radius_mapunits_mask.png b/tests/testdata/control_images/text_renderer/shadow_radius_mapunits/shadow_radius_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..afa64385d9ddcc3fe8b3022550b0686bb084c8ce GIT binary patch literal 13824 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_radius_mm/shadow_radius_mm_mask.png b/tests/testdata/control_images/text_renderer/shadow_radius_mm/shadow_radius_mm_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..3f7f09fd396da5a3ff55de18195e427845220eb2 GIT binary patch literal 13766 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/shadow_scale_50/shadow_scale_50_mask.png b/tests/testdata/control_images/text_renderer/shadow_scale_50/shadow_scale_50_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..390e0ca2ff0af7995b711dbc2101214ace59e697 GIT binary patch literal 4944 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_angled/text_angled_mask.png b/tests/testdata/control_images/text_renderer/text_angled/text_angled_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..2b64d9cbdc9a8f742fd2daf5d6e5311c0f6c19b0 GIT binary patch literal 3199 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 LKabjz=dS$=wEf2N literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_blend_mode/text_blend_mode_mask.png b/tests/testdata/control_images/text_renderer/text_blend_mode/text_blend_mode_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..1a6e6223663b9021a35b88dfddacc2dc312a0f99 GIT binary patch literal 5082 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 W*yrewC2&|LbIQfTx%R~6fB!ef?5+6# literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_bold/text_bold_mask.png b/tests/testdata/control_images/text_renderer/text_bold/text_bold_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..1d406edec74ce1c57f3d10c589111135500456fc GIT binary patch literal 4201 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

                                                                                                                                                                                    9yR!!FC_JB)d1gb-(~fr?#)i$|~c+Y)%dY3G2&; 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_buffer_interior/text_buffer_interior_mask.png b/tests/testdata/control_images/text_renderer/text_buffer_interior/text_buffer_interior_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..dc7c7df5a5b8dc06f1b6f7e6b96c541cdfab92bc GIT binary patch literal 4249 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_buffer_mapunits/text_buffer_mapunits_mask.png b/tests/testdata/control_images/text_renderer/text_buffer_mapunits/text_buffer_mapunits_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..f8bd155c7870c97a9861d9d1e416e0f1c97d25e0 GIT binary patch literal 4783 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 SFF;37>691Dv+kE)|NUS616JGs literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_color/text_color_mask.png b/tests/testdata/control_images/text_renderer/text_color/text_color_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..0fabe2b76c5b4df323fb862b299d970646f86b37 GIT binary patch literal 4292 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%0Dy(cXKpVsXi4IVOenk*;j+-K>+y#Jtf00m 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 X{ves>^}hsuUO?f8BB7L@FWmYcmp2Wf literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_multiline/text_multiline_mask.png b/tests/testdata/control_images/text_renderer/text_multiline/text_multiline_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..36f93d83b2f18b3f91b5f9e4735d8839277095de GIT binary patch literal 5593 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_opacity/text_opacity_mask.png b/tests/testdata/control_images/text_renderer/text_opacity/text_opacity_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..d23c023c58f39e961142df7c73b2b77dda88008c GIT binary patch literal 4132 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_pixels/text_pixels_mask.png b/tests/testdata/control_images/text_renderer/text_pixels/text_pixels_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..757e796f32c75c64796070aa07cfbac8ad67391e GIT binary patch literal 3320 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_rect_multiline_center_aligned/text_rect_multiline_center_aligned_mask.png b/tests/testdata/control_images/text_renderer/text_rect_multiline_center_aligned/text_rect_multiline_center_aligned_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..c44eb20deddc0bb4465329d58ddf6202782dea36 GIT binary patch literal 6592 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 I{)4Cg0;M-M{Qv*} literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_rect_multiline_right_aligned/text_rect_multiline_right_aligned_mask.png b/tests/testdata/control_images/text_renderer/text_rect_multiline_right_aligned/text_rect_multiline_right_aligned_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..f963afd81a4b78a16dd6c616b84e73a5f100a42a GIT binary patch literal 7593 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 HkDvbs{vB*c literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_rect_right_aligned/text_rect_right_aligned_mask.png b/tests/testdata/control_images/text_renderer/text_rect_right_aligned/text_rect_right_aligned_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..0c76b5a750809ac6e6fd2938a25fc860f2c5bdcd GIT binary patch literal 3314 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_buffer_and_background/text_with_buffer_and_background_mask.png b/tests/testdata/control_images/text_renderer/text_with_buffer_and_background/text_with_buffer_and_background_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..8fa619df3f910ce8046eebf24f1f052757eb10e5 GIT binary patch literal 8410 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_and_background/text_with_shadow_and_background_mask.png b/tests/testdata/control_images/text_renderer/text_with_shadow_and_background/text_with_shadow_and_background_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..8aeb45625c7ed740fe0e60fa7cce79cd89488d3b GIT binary patch literal 4252 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 Zx%9JM6m8ia_}u{VI^yF|<9_z~zW{zON}&J% literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_and_buffer/text_with_shadow_and_buffer_mask.png b/tests/testdata/control_images/text_renderer/text_with_shadow_and_buffer/text_with_shadow_and_buffer_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..a68683d03aea9a1f58e4d949dc9e256855928ed2 GIT binary patch literal 7217 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 E0Rp4j>i_@% literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_background/text_with_shadow_below_text_and_background_mask.png b/tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_background/text_with_shadow_below_text_and_background_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..1f131a3a04f3e925ce6efe1cb877c7c78d9208c3 GIT binary patch literal 5602 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_buffer/text_with_shadow_below_text_and_buffer_mask.png b/tests/testdata/control_images/text_renderer/text_with_shadow_below_text_and_buffer/text_with_shadow_below_text_and_buffer_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..1776c42f412940313bd66a84ee5d196d4c8d318b GIT binary patch literal 7276 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/text_renderer/text_with_shadow_buffer_and_background/text_with_shadow_buffer_and_background_mask.png b/tests/testdata/control_images/text_renderer/text_with_shadow_buffer_and_background/text_with_shadow_buffer_and_background_mask.png new file mode 100644 index 0000000000000000000000000000000000000000..a24051c0b5e744a534cbb97fa6ef2578aa859d01 GIT binary patch literal 6245 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 Qfq>TyYe%cvE4Lo}4-2 Date: Tue, 4 Oct 2016 10:29:55 +1000 Subject: [PATCH 449/897] Fix text renderer not respecting min/max mm scale for map units (fix #14698) --- src/core/qgstextrenderer.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/core/qgstextrenderer.cpp b/src/core/qgstextrenderer.cpp index 54a47a7f237e..dd1bd44d670a 100644 --- a/src/core/qgstextrenderer.cpp +++ b/src/core/qgstextrenderer.cpp @@ -1627,6 +1627,14 @@ double QgsTextRenderer::scaleToPixelContext( double size, const QgsRenderContext { size = size / mapUnitsPerPixel * ( rasterfactor ? c.rasterScaleFactor() : 1 ); } + if ( unit == QgsUnitTypes::RenderMapUnits ) + { + //check max/min size + if ( mapUnitScale.minSizeMMEnabled ) + size = qMax( size, mapUnitScale.minSizeMM * c.scaleFactor() ); + if ( mapUnitScale.maxSizeMMEnabled ) + size = qMin( size, mapUnitScale.maxSizeMM * c.scaleFactor() ); + } break; case QgsUnitTypes::RenderPixels: From 0b88de2487ac6a5b141cdebca0ec5ff86ca6e48f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 1 Oct 2016 14:29:05 +1000 Subject: [PATCH 450/897] New widget QgsTextPreview for previewing all formatting for QgsTextRenderer Switch the labeling gui to use this widget, which has the benefits: - previews all label settings, including shadow and background - previews at a specified scale, so that any sizes using map units will be correct --- python/gui/gui.sip | 1 + python/gui/qgstextpreview.sip | 66 ++++ src/app/qgslabelinggui.cpp | 110 ++----- src/app/qgslabelinggui.h | 3 +- src/gui/CMakeLists.txt | 2 + src/gui/qgstextpreview.cpp | 97 ++++++ src/gui/qgstextpreview.h | 98 ++++++ src/ui/qgslabelingguibase.ui | 581 ++++++++++++++++------------------ 8 files changed, 576 insertions(+), 382 deletions(-) create mode 100644 python/gui/qgstextpreview.sip create mode 100644 src/gui/qgstextpreview.cpp create mode 100644 src/gui/qgstextpreview.h diff --git a/python/gui/gui.sip b/python/gui/gui.sip index ca8e6a4575f3..ef63cb219e28 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -161,6 +161,7 @@ %Include qgstabwidget.sip %Include qgstablewidgetitem.sip %Include qgstextannotationitem.sip +%Include qgstextpreview.sip %Include qgstrackedvectorlayertools.sip %Include qgstreewidgetitem.sip %Include qgsunitselectionwidget.sip diff --git a/python/gui/qgstextpreview.sip b/python/gui/qgstextpreview.sip new file mode 100644 index 000000000000..a87d984b7f00 --- /dev/null +++ b/python/gui/qgstextpreview.sip @@ -0,0 +1,66 @@ +/** \class QgsTextPreview + * \ingroup gui + * A widget for previewing text formatting settings. + * + * QgsTextPreview provides a widget for previewing the appearance of text rendered + * using QgsTextRenderer. The preview includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * In order to preview the exact appearance of text which uses sizes in map units, + * the scale and map units must be set by calling setScale() and setMapUnits(). + * + * @note Added in QGIS 3.0 + */ + +class QgsTextPreview : public QLabel +{ +%TypeHeaderCode + #include +%End + public: + + /** Constructor for QgsTextPreview + * @param parent parent widget + */ + QgsTextPreview( QWidget* parent = nullptr ); + + void paintEvent( QPaintEvent* e ); + + /** Sets the text format for previewing in the widget. + * @param format text format + * @see format() + */ + void setFormat( const QgsTextFormat& format ); + + /** Returns the text format used for previewing text in the widget. + * @see setFormat() + */ + QgsTextFormat format() const; + + /** Sets the scale to use for previewing format sizes in map units. + * @param scale preview map scale + * @see scale() + * @see setMapUnits() + */ + void setScale( double scale ); + + /** Returns the scale used for previewing format sizes in map units. + * @see setScale() + * @see mapUnits() + */ + double scale() const; + + /** Sets the map unit type for previewing format sizes in map units. + * @param unit map units + * @see mapUnits() + * @see setScale() + */ + void setMapUnits( QgsUnitTypes::DistanceUnit unit ); + + /** Returns the map unit type used for previewing format sizes in map units. + * @see setMapUnits() + * @see scale() + */ + QgsUnitTypes::DistanceUnit mapUnits() const; + +}; diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index 2514e6e84508..63212e74bbff 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -78,6 +78,10 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, { setupUi( this ); + mPreviewScaleComboBox->setMapCanvas( mMapCanvas ); + mPreviewScaleComboBox->setShowCurrentScaleButton( true ); + connect( mPreviewScaleComboBox, SIGNAL( scaleChanged( double ) ), this, SLOT( previewScaleChanged( double ) ) ); + mFieldExpressionWidget->registerExpressionContextGenerator( this ); Q_FOREACH ( QgsUnitSelectionWidget* unitWidget, findChildren() ) @@ -485,6 +489,12 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, // set correct initial tab to match displayed setting page whileBlocking( mOptionsTab )->setCurrentIndex( mLabelStackedWidget->currentIndex() ); + + if ( mMapCanvas ) + { + lblFontPreview->setMapUnits( mMapCanvas->mapSettings().mapUnits() ); + mPreviewScaleComboBox->setScale( 1.0 / mMapCanvas->mapSettings().scale() ); + } } void QgsLabelingGui::setDockMode( bool enabled ) @@ -958,7 +968,10 @@ QgsPalLayerSettings QgsLabelingGui::layerSettings() lyr.distInMapUnits = ( mLineDistanceUnitWidget->unit() == QgsUnitTypes::RenderMapUnits ); lyr.distMapUnitScale = mLineDistanceUnitWidget->getMapUnitScale(); lyr.offsetType = static_cast< QgsPalLayerSettings::OffsetType >( mOffsetTypeComboBox->currentData().toInt() ); - lyr.quadOffset = ( QgsPalLayerSettings::QuadrantPosition )mQuadrantBtnGrp->checkedId(); + if ( mQuadrantBtnGrp ) + { + lyr.quadOffset = ( QgsPalLayerSettings::QuadrantPosition )mQuadrantBtnGrp->checkedId(); + } lyr.xOffset = mPointOffsetXSpinBox->value(); lyr.yOffset = mPointOffsetYSpinBox->value(); lyr.labelOffsetInMapUnits = ( mPointOffsetUnitWidget->unit() == QgsUnitTypes::RenderMapUnits ); @@ -1036,6 +1049,7 @@ QgsPalLayerSettings QgsLabelingGui::layerSettings() QgsTextFormat format; format.setColor( btnTextColor->color() ); format.setFont( mRefFont ); + format.setSize( mFontSizeSpinBox->value() ); format.setNamedStyle( mFontStyleComboBox->currentText() ); format.setOpacity( 1.0 - mFontTranspSpinBox->value() / 100.0 ); format.setBlendMode( comboBlendMode->blendMode() ); @@ -1115,9 +1129,14 @@ QgsPalLayerSettings QgsLabelingGui::layerSettings() lyr.leftDirectionSymbol = mDirectSymbLeftLineEdit->text(); lyr.rightDirectionSymbol = mDirectSymbRightLineEdit->text(); lyr.reverseDirectionSymbol = mDirectSymbRevChkBx->isChecked(); - lyr.placeDirectionSymbol = ( QgsPalLayerSettings::DirectionSymbols )mDirectSymbBtnGrp->checkedId(); - - lyr.upsidedownLabels = ( QgsPalLayerSettings::UpsideDownLabels )mUpsidedownBtnGrp->checkedId(); + if ( mDirectSymbBtnGrp ) + { + lyr.placeDirectionSymbol = ( QgsPalLayerSettings::DirectionSymbols )mDirectSymbBtnGrp->checkedId(); + } + if ( mUpsidedownBtnGrp ) + { + lyr.upsidedownLabels = ( QgsPalLayerSettings::UpsideDownLabels )mUpsidedownBtnGrp->checkedId(); + } lyr.maxCurvedCharAngleIn = mMaxCharAngleInDSpinBox->value(); // lyr.maxCurvedCharAngleOut must be negative, but it is shown as positive spinbox in GUI @@ -1590,78 +1609,12 @@ void QgsLabelingGui::updatePreview() return; } + QgsTextFormat format = layerSettings().format(); + scrollPreview(); - lblFontPreview->setFont( mRefFont ); - QFont previewFont = lblFontPreview->font(); - double fontSize = mFontSizeSpinBox->value(); - double previewRatio = mPreviewSize / fontSize; - double bufferSize = 0.0; + lblFontPreview->setFormat( format ); QString grpboxtitle; - QString sampleTxt = tr( "Text/Buffer sample" ); - - if ( mFontSizeUnitWidget->getUnit() == 1 ) // map units - { - // TODO: maybe match current map zoom level instead? - previewFont.setPointSize( mPreviewSize ); - mPreviewSizeSlider->setEnabled( true ); - grpboxtitle = sampleTxt + tr( " @ %1 pts (using map units)" ).arg( mPreviewSize ); - - previewFont.setWordSpacing( previewRatio * mFontWordSpacingSpinBox->value() ); - previewFont.setLetterSpacing( QFont::AbsoluteSpacing, previewRatio * mFontLetterSpacingSpinBox->value() ); - - if ( mBufferDrawChkBx->isChecked() ) - { - if ( mBufferUnitWidget->unit() == QgsUnitTypes::RenderMapUnits ) - { - bufferSize = previewRatio * spinBufferSize->value() / 3.527; - } - else // millimeters - { - grpboxtitle = sampleTxt + tr( " @ %1 pts (using map units, BUFFER IN MILLIMETERS)" ).arg( mPreviewSize ); - bufferSize = spinBufferSize->value(); - } - } - } - else // in points - { - if ( fontSize > 0 ) - previewFont.setPointSize( fontSize ); - mPreviewSizeSlider->setEnabled( false ); - grpboxtitle = sampleTxt; - - if ( mBufferDrawChkBx->isChecked() ) - { - if ( mBufferUnitWidget->unit() == QgsUnitTypes::RenderMillimeters ) - { - bufferSize = spinBufferSize->value(); - } - else // map units - { - grpboxtitle = sampleTxt + tr( " (BUFFER NOT SHOWN, in map units)" ); - } - } - } - - lblFontPreview->setFont( previewFont ); groupBox_mPreview->setTitle( grpboxtitle ); - - QColor prevColor = btnTextColor->color(); - prevColor.setAlphaF(( 100.0 - ( double )( mFontTranspSpinBox->value() ) ) / 100.0 ); - lblFontPreview->setTextColor( prevColor ); - - bool bufferNoFill = false; - if ( mBufferDrawChkBx->isChecked() && bufferSize != 0.0 ) - { - QColor buffColor = btnBufferColor->color(); - buffColor.setAlphaF(( 100.0 - ( double )( mBufferTranspSpinBox->value() ) ) / 100.0 ); - - bufferNoFill = !mBufferTranspFillChbx->isChecked(); - lblFontPreview->setBuffer( bufferSize, buffColor, mBufferJoinStyleComboBox->penJoinStyle(), bufferNoFill ); - } - else - { - lblFontPreview->setBuffer( 0, Qt::white, Qt::BevelJoin, bufferNoFill ); - } } void QgsLabelingGui::scrollPreview() @@ -1813,12 +1766,6 @@ void QgsLabelingGui::populateFontStyleComboBox() mFontStyleComboBox->setCurrentIndex( curIndx ); } -void QgsLabelingGui::on_mPreviewSizeSlider_valueChanged( int i ) -{ - mPreviewSize = i; - updatePreview(); -} - void QgsLabelingGui::on_mFontSizeSpinBox_valueChanged( double d ) { mRefFont.setPointSizeF( d ); @@ -2013,6 +1960,11 @@ void QgsLabelingGui::onSubstitutionsChanged( const QgsStringReplacementCollectio emit widgetChanged(); } +void QgsLabelingGui::previewScaleChanged( double scale ) +{ + lblFontPreview->setScale( scale ); +} + void QgsLabelingGui::updateSvgWidgets( const QString& svgPath ) { if ( mShapeSVGPathLineEdit->text() != svgPath ) diff --git a/src/app/qgslabelinggui.h b/src/app/qgslabelinggui.h index e0a7cba5ae75..ce7e2856ac95 100644 --- a/src/app/qgslabelinggui.h +++ b/src/app/qgslabelinggui.h @@ -22,6 +22,7 @@ #include #include #include "qgsstringutils.h" +#include "qgspallabeling.h" class QgsVectorLayer; class QgsMapCanvas; @@ -67,7 +68,6 @@ class APP_EXPORT QgsLabelingGui : public QWidget, private Ui::QgsLabelingGuiBase void updatePlacementWidgets(); void updateSvgWidgets( const QString& svgPath ); - void on_mPreviewSizeSlider_valueChanged( int i ); void on_mFontSizeSpinBox_valueChanged( double d ); void on_mFontCapitalsComboBox_currentIndexChanged( int index ); void on_mFontFamilyCmbBx_currentFontChanged( const QFont& f ); @@ -150,6 +150,7 @@ class APP_EXPORT QgsLabelingGui : public QWidget, private Ui::QgsLabelingGuiBase void on_mShapeSVGPathLineEdit_textChanged( const QString& text ); void updateLinePlacementOptions(); void onSubstitutionsChanged( const QgsStringReplacementCollection& substitutions ); + void previewScaleChanged( double scale ); }; #endif diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index fb9cc6bc2d60..2f42b62ba2db 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -308,6 +308,7 @@ SET(QGIS_GUI_SRCS qgstabwidget.cpp qgstablewidgetitem.cpp qgstextannotationitem.cpp + qgstextpreview.cpp qgstrackedvectorlayertools.cpp qgstreewidgetitem.cpp qgsunitselectionwidget.cpp @@ -461,6 +462,7 @@ SET(QGIS_GUI_MOC_HDRS qgssublayersdialog.h qgstablewidgetbase.h qgstabwidget.h + qgstextpreview.h qgstreewidgetitem.h qgsunitselectionwidget.h qgsuserinputdockwidget.h diff --git a/src/gui/qgstextpreview.cpp b/src/gui/qgstextpreview.cpp new file mode 100644 index 000000000000..00f8a92864f8 --- /dev/null +++ b/src/gui/qgstextpreview.cpp @@ -0,0 +1,97 @@ +/*************************************************************************** + qgstextpreview.cpp + ------------------ + begin : October 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgstextpreview.h" +#include +#include + +QgsTextPreview::QgsTextPreview( QWidget* parent ) + : QLabel( parent ) + , mScale( -1 ) + , mMapUnits( QgsUnitTypes::DistanceMeters ) +{ + // initially use a basic transform with no scale + QgsMapToPixel newCoordXForm; + newCoordXForm.setParameters( 1, 0, 0, 0, 0, 0 ); + mContext.setMapToPixel( newCoordXForm ); + + mContext.setScaleFactor( QgsApplication::desktop()->logicalDpiX() / 25.4 ); + mContext.setUseAdvancedEffects( true ); +} + + +void QgsTextPreview::paintEvent( QPaintEvent *e ) +{ + Q_UNUSED( e ); + QPainter p( this ); + + p.setRenderHint( QPainter::Antialiasing ); + + // slightly inset text + double xtrans = 0; + if ( mFormat.buffer().enabled() ) + xtrans = QgsTextRenderer::scaleToPixelContext( mFormat.buffer().size(), mContext, mFormat.buffer().sizeUnit(), false, mFormat.buffer().sizeMapUnitScale() ); + if ( mFormat.background().enabled() && mFormat.background().sizeType() != QgsTextBackgroundSettings::SizeFixed ) + xtrans = qMax( xtrans, QgsTextRenderer::scaleToPixelContext( mFormat.background().size().width(), mContext, mFormat.background().sizeUnit(), false, mFormat.background().sizeMapUnitScale() ) ); + xtrans += 4; + + double ytrans = 0.0; + if ( mFormat.buffer().enabled() ) + ytrans = qMax( ytrans, QgsTextRenderer::scaleToPixelContext( mFormat.buffer().size(), mContext, mFormat.buffer().sizeUnit(), false, mFormat.buffer().sizeMapUnitScale() ) ); + if ( mFormat.background().enabled() ) + ytrans = qMax( ytrans, QgsTextRenderer::scaleToPixelContext( mFormat.background().size().height(), mContext, mFormat.background().sizeUnit(), false, mFormat.background().sizeMapUnitScale() ) ); + ytrans += 4; + + QRectF textRect = rect(); + textRect.setLeft( xtrans ); + textRect.setWidth( textRect.width() - xtrans ); + textRect.setTop( ytrans ); + if ( textRect.height() > 300 ) + textRect.setHeight( 300 ); + if ( textRect.width() > 2000 ) + textRect.setWidth( 2000 ); + + mContext.setPainter( &p ); + QgsTextRenderer::drawText( textRect, 0 , QgsTextRenderer::AlignLeft, QStringList() << text(), + mContext, mFormat ); +} + +void QgsTextPreview::setFormat( const QgsTextFormat& format ) +{ + mFormat = format; + update(); +} + +void QgsTextPreview::updateContext() +{ + if ( mScale >= 0 ) + { + QgsMapToPixel newCoordXForm = QgsMapToPixel::fromScale( mScale, mMapUnits, QgsApplication::desktop()->logicalDpiX() ); + mContext.setMapToPixel( newCoordXForm ); + } + update(); +} + +void QgsTextPreview::setScale( double scale ) +{ + mScale = scale; + updateContext(); +} + +void QgsTextPreview::setMapUnits( QgsUnitTypes::DistanceUnit unit ) +{ + mMapUnits = unit; + updateContext(); +} diff --git a/src/gui/qgstextpreview.h b/src/gui/qgstextpreview.h new file mode 100644 index 000000000000..7f1304c4e11f --- /dev/null +++ b/src/gui/qgstextpreview.h @@ -0,0 +1,98 @@ +/*************************************************************************** + qgstextpreview.h + ---------------- + begin : October 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSTEXTPREVIEW_H +#define QGSTEXTPREVIEW_H + +#include "qgstextrenderer.h" + +#include + +/** \class QgsTextPreview + * \ingroup gui + * A widget for previewing text formatting settings. + * + * QgsTextPreview provides a widget for previewing the appearance of text rendered + * using QgsTextRenderer. The preview includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * In order to preview the exact appearance of text which uses sizes in map units, + * the scale and map units must be set by calling setScale() and setMapUnits(). + * + * @note Added in QGIS 3.0 + */ + +class GUI_EXPORT QgsTextPreview : public QLabel +{ + Q_OBJECT + + Q_PROPERTY( QgsTextFormat format READ format WRITE setFormat ) + Q_PROPERTY( double scale READ scale WRITE setScale ) + Q_PROPERTY( QgsUnitTypes::DistanceUnit mapUnits READ mapUnits WRITE setMapUnits ) + + public: + + /** Constructor for QgsTextPreview + * @param parent parent widget + */ + QgsTextPreview( QWidget* parent = nullptr ); + + void paintEvent( QPaintEvent* e ) override; + + /** Sets the text format for previewing in the widget. + * @param format text format + * @see format() + */ + void setFormat( const QgsTextFormat& format ); + + /** Returns the text format used for previewing text in the widget. + * @see setFormat() + */ + QgsTextFormat format() const { return mFormat; } + + /** Sets the scale to use for previewing format sizes in map units. + * @param scale preview map scale + * @see scale() + * @see setMapUnits() + */ + void setScale( double scale ); + + /** Returns the scale used for previewing format sizes in map units. + * @see setScale() + * @see mapUnits() + */ + double scale() const { return mScale; } + + /** Sets the map unit type for previewing format sizes in map units. + * @param unit map units + * @see mapUnits() + * @see setScale() + */ + void setMapUnits( QgsUnitTypes::DistanceUnit unit ); + + /** Returns the map unit type used for previewing format sizes in map units. + * @see setMapUnits() + * @see scale() + */ + QgsUnitTypes::DistanceUnit mapUnits() const { return mMapUnits; } + + private: + QgsTextFormat mFormat; + QgsRenderContext mContext; + double mScale; + QgsUnitTypes::DistanceUnit mMapUnits; + void updateContext(); +}; + +#endif // QGSTEXTPREVIEW_H diff --git a/src/ui/qgslabelingguibase.ui b/src/ui/qgslabelingguibase.ui index 33971f380e7f..32d69cce2203 100644 --- a/src/ui/qgslabelingguibase.ui +++ b/src/ui/qgslabelingguibase.ui @@ -78,7 +78,7 @@ - Text/Buffer Sample + Text Sample true @@ -112,7 +112,7 @@ 0 0 - 486 + 482 300 @@ -139,7 +139,7 @@ 0 - + true @@ -243,39 +243,12 @@ - - - - 0 - 0 - - - - - 200 - 0 - + + + Qt::StrongFocus - Size for sample text in map units - - - 8 - - - 320 - - - 4 - - - 24 - - - Qt::Horizontal - - - 4 + Preview text at specific map scale @@ -618,7 +591,7 @@ - 5 + 0 @@ -647,8 +620,8 @@ 0 0 - 452 - 387 + 448 + 442 @@ -691,28 +664,85 @@ 0 - - - - ... - - - - - + + - + 0 0 - - Style + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Available typeface styles + + + QComboBox::AdjustToContentsOnFirstShow - - + + + + + + + 0 + 0 + + + + letter + + + + + + + + 0 + 0 + + + + Space in pixels or map units, relative to size unit choice + + + 4 + + + -1000.000000000000000 + + + 999999999.000000000000000 + + + 0.100000000000000 + + + true + + + + + + + ... + + + + @@ -730,42 +760,19 @@ - - - - true - - - Transparency - - - - - + + - + 0 0 - - - 120 - 0 - - - - - 120 - 16777215 - - - - - - - Blend mode + Color + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter @@ -776,10 +783,10 @@ - - + + - + 0 @@ -787,12 +794,12 @@ - letter + word - + 0 @@ -820,7 +827,7 @@ - + ... @@ -828,16 +835,75 @@ - - + + + + + 0 + 0 + + + + Size + + - - + + ... + + + + ... + + + + + + + ... + + + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + 4 + + + 999999999.000000000000000 + + + false + + + + + + + Spacing + + + @@ -854,64 +920,74 @@ - - + + + + ... + + + + + - + 0 0 - 0 + 120 0 - 16777215 + 120 16777215 - - Available typeface styles - - - QComboBox::AdjustToContentsOnFirstShow - - - - - - 0 - 0 - + + + + + + + If enabled, the label text will automatically be modified using a preset list of substitutes - Type case + Apply label text substitutes - - - - ... + + + + false - - + + + + true + - + 0 0 - - Size + + + 16777215 + 16777215 + + + + Capitalization style of text @@ -983,85 +1059,18 @@ - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 0 - 0 - - - - color: #990000; -font-style: italic; - - - Font is missing. - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - 4 - - - 999999999.000000000000000 - - - false - - - - - - - Spacing + + + + true - - - - - ... + Transparency - - + + ... @@ -1249,96 +1258,80 @@ font-style: italic; - - + + ... - - - - - - - 0 - 0 - - - - word - - - - - - - - 0 - 0 - - - - Space in pixels or map units, relative to size unit choice - - - 4 - - - -1000.000000000000000 - - - 999999999.000000000000000 - - - 0.100000000000000 - - - true - - - - - - - ... - - - - - - - - - false + + + + Blend mode - - - - true + + + + ... + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + color: #990000; +font-style: italic; + + + Font is missing. + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + + - + 0 0 - - - 16777215 - 16777215 - - - - Capitalization style of text + + Type case - - + + 0 @@ -1346,27 +1339,7 @@ font-style: italic; - Color - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - - - - - - ... - - - - - - - If enabled, the label text will automatically be modified using a preset list of substitutes - - - Apply label text substitutes + Style @@ -1439,8 +1412,8 @@ font-style: italic; 0 0 - 342 - 338 + 383 + 389 @@ -2074,8 +2047,8 @@ font-style: italic; 0 0 - 285 - 245 + 301 + 280 @@ -2456,8 +2429,8 @@ font-style: italic; 0 0 - 431 - 628 + 454 + 720 @@ -3276,8 +3249,8 @@ font-style: italic; 0 0 - 305 - 398 + 330 + 447 @@ -3773,8 +3746,8 @@ font-style: italic; 0 0 - 452 - 839 + 430 + 917 @@ -5399,8 +5372,8 @@ font-style: italic; 0 0 - 452 - 731 + 429 + 799 @@ -6430,16 +6403,20 @@ font-style: italic;

                                                                                                                                                                                    qgspenstylecombobox.h
                                                                                                                                                                                    - QgsLabelPreview + QgsTextPreview QLabel -
                                                                                                                                                                                    qgslabelpreview.h
                                                                                                                                                                                    +
                                                                                                                                                                                    qgstextpreview.h
                                                                                                                                                                                    +
                                                                                                                                                                                    + + QgsScaleWidget + QWidget +
                                                                                                                                                                                    qgsscalewidget.h
                                                                                                                                                                                    scrollArea_mPreview mPreviewTextEdit mPreviewTextBtn - mPreviewSizeSlider mPreviewBackgroundBtn mLabelingOptionsListWidget scrollArea From 25b3c633701294e9e1600584dea262585201aecd Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 12:04:34 +1000 Subject: [PATCH 451/897] Remove unused QgsLabelPreview class --- src/app/CMakeLists.txt | 2 - src/app/qgslabelpreview.cpp | 89 ------------------------------------- src/app/qgslabelpreview.h | 49 -------------------- 3 files changed, 140 deletions(-) delete mode 100644 src/app/qgslabelpreview.cpp delete mode 100644 src/app/qgslabelpreview.h diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index cb6483891a5c..14cb52ed6bdd 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -44,7 +44,6 @@ SET(QGIS_APP_SRCS qgslabelengineconfigdialog.cpp qgslabelinggui.cpp qgslabelingwidget.cpp - qgslabelpreview.cpp qgsloadstylefromdbdialog.cpp qgsmaplayerstyleguiutils.cpp qgsrulebasedlabelingwidget.cpp @@ -222,7 +221,6 @@ SET (QGIS_APP_MOC_HDRS qgsidentifyresultsdialog.h qgslabelengineconfigdialog.h qgslabelinggui.h - qgslabelpreview.h qgslabelingwidget.h qgslabelpropertydialog.h qgsloadstylefromdbdialog.h diff --git a/src/app/qgslabelpreview.cpp b/src/app/qgslabelpreview.cpp deleted file mode 100644 index 70f6508dcbd0..000000000000 --- a/src/app/qgslabelpreview.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/*************************************************************************** - qgslabelpreview.cpp - --------------------- - begin : May 2010 - copyright : (C) 2010 by Marco Hugentobler - email : marco dot hugentobler at sourcepole dot ch - *************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ -#include "qgslabelpreview.h" - -#include -#include - -#include "qgspallabeling.h" - -QgsLabelPreview::QgsLabelPreview( QWidget* parent ) - : QLabel( parent ) -{ - // construct a device-based render context - QgsMapToPixel newCoordXForm( 1 ); - mContext.setMapToPixel( newCoordXForm ); -} - -void QgsLabelPreview::setTextColor( const QColor& color ) -{ - mTextColor = color; - update(); -} - -void QgsLabelPreview::setBuffer( double size, const QColor& color, Qt::PenJoinStyle joinStyle, bool noFill ) -{ - QgsTextBufferSettings buffer = mFormat.buffer(); - buffer.setSize( size * 88 / 25.4 ); //assume standard dpi for preview; - buffer.setSizeUnit( QgsUnitTypes::RenderMillimeters ); - buffer.setColor( color ); - buffer.setJoinStyle( joinStyle ); - buffer.setFillBufferInterior( !noFill ); - mFormat.setBuffer( buffer ); - - mFormat.setFont( font() ); - update(); -} - -void QgsLabelPreview::paintEvent( QPaintEvent *e ) -{ - Q_UNUSED( e ); - QPainter p( this ); - - // TODO: draw all label components when this preview is an actual map canvas - // for now, only preview label's text and buffer - mFormat.shadow().setEnabled( false ); - - p.setRenderHint( QPainter::Antialiasing ); - p.setFont( font() ); - QFontMetrics fm( font() ); - - // otherwise thin buffers don't look like those on canvas - if ( mFormat.buffer().size() != 0 && mFormat.buffer().size() < 1 ) - mFormat.buffer().setSize( 1 ); - - double xtrans = 0; - if ( mFormat.buffer().size() != 0 ) - xtrans = mFormat.buffer().size() / 4; - - p.translate( xtrans, fm.ascent() + 4 ); - - if ( mFormat.buffer().size() != 0 ) - { - mContext.setPainter( &p ); - QgsTextRenderer::Component component; - component.text = text(); - QgsTextRenderer::drawBuffer( mContext, component, mFormat ); - } - - QPainterPath path; - path.addText( 0, 0, font(), text() ); - p.setPen( Qt::NoPen ); - p.setBrush( mTextColor ); - p.drawPath( path ); - -// p.setPen( mTextColor ); -// p.drawText( 0, 0, text() ); -} diff --git a/src/app/qgslabelpreview.h b/src/app/qgslabelpreview.h deleted file mode 100644 index 1e50e1739545..000000000000 --- a/src/app/qgslabelpreview.h +++ /dev/null @@ -1,49 +0,0 @@ -/*************************************************************************** - qgslabelpreview.h - --------------------- - begin : May 2010 - copyright : (C) 2010 by Marco Hugentobler - email : marco dot hugentobler at sourcepole dot ch - *************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ -#ifndef QGSLABELPREVIEW_H -#define QGSLABELPREVIEW_H - -#include "qgspallabeling.h" - -#include - -class QgsRenderContext; - -class APP_EXPORT QgsLabelPreview : public QLabel -{ - Q_OBJECT - - public: - QgsLabelPreview( QWidget* parent = nullptr ); - - void setTextColor( const QColor& color ); - - void setBuffer( double size, const QColor& color, Qt::PenJoinStyle joinStyle, bool noFill = false ); - - void setFont( const QFont& f ) { mFont = f; } - QFont font() { return mFont; } - - void paintEvent( QPaintEvent* e ) override; - - private: - QgsTextFormat mFormat; - QColor mTextColor; - QFont mFont; - - // device-based render context - QgsRenderContext mContext; -}; - -#endif // LABELPREVIEW_H From 169b367c5b5ed5997052e8fa536f1bf8adef4386 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 12:29:14 +1000 Subject: [PATCH 452/897] [FEATURE] Allow label font size in mm/pixels And all other label sizes (eg buffer size) now accept sizes in pixels too --- src/app/qgslabelinggui.cpp | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index 63212e74bbff..b50d0fe3b09f 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -88,17 +88,19 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, { unitWidget->setMapCanvas( mMapCanvas ); } - mFontSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderMapUnits ); - mBufferUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mShapeSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mShapeOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mShapeRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPercentage ); - mShapeBorderWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mShadowOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mShadowRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mPointOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mLineDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); - mRepeatDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits ); + mFontSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderMapUnits + << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderPixels ); + mBufferUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShapeSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShapeOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShapeRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits + << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderPercentage ); + mShapeBorderWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShadowOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShadowRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mPointOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mLineDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mRepeatDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); mFontLineHeightSpinBox->setClearValue( 1.0 ); mShapeRotationDblSpnBx->setClearValue( 0.0 ); From 76c12ba94c20a2e93b4db2cad3ecd06a4d4690d1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 4 Oct 2016 21:31:17 +1000 Subject: [PATCH 453/897] Split QgsLabelingGui off into QgsTextFormatWidget New widget allows for setting just the formatting properties of text --- python/gui/gui.sip | 2 + python/gui/qgssubstitutionlistwidget.sip | 73 + python/gui/qgstextformatwidget.sip | 88 ++ src/app/CMakeLists.txt | 2 - src/app/qgslabelinggui.cpp | 1344 +--------------- src/app/qgslabelinggui.h | 101 +- src/gui/CMakeLists.txt | 4 + .../qgssubstitutionlistwidget.cpp | 0 src/{app => gui}/qgssubstitutionlistwidget.h | 9 +- src/gui/qgstextformatwidget.cpp | 1378 +++++++++++++++++ src/gui/qgstextformatwidget.h | 198 +++ ...gguibase.ui => qgstextformatwidgetbase.ui} | 978 ++++++------ tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgstextformatwidget.py | 189 +++ 14 files changed, 2471 insertions(+), 1896 deletions(-) create mode 100644 python/gui/qgssubstitutionlistwidget.sip create mode 100644 python/gui/qgstextformatwidget.sip rename src/{app => gui}/qgssubstitutionlistwidget.cpp (100%) rename src/{app => gui}/qgssubstitutionlistwidget.h (95%) create mode 100644 src/gui/qgstextformatwidget.cpp create mode 100644 src/gui/qgstextformatwidget.h rename src/ui/{qgslabelingguibase.ui => qgstextformatwidgetbase.ui} (98%) create mode 100644 tests/src/python/test_qgstextformatwidget.py diff --git a/python/gui/gui.sip b/python/gui/gui.sip index ef63cb219e28..db7c97cff9e7 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -156,11 +156,13 @@ %Include qgsslider.sip %Include qgssourceselectdialog.sip %Include qgssublayersdialog.sip +%Include qgssubstitutionlistwidget.sip %Include qgssvgannotationitem.sip %Include qgstablewidgetbase.sip %Include qgstabwidget.sip %Include qgstablewidgetitem.sip %Include qgstextannotationitem.sip +%Include qgstextformatwidget.sip %Include qgstextpreview.sip %Include qgstrackedvectorlayertools.sip %Include qgstreewidgetitem.sip diff --git a/python/gui/qgssubstitutionlistwidget.sip b/python/gui/qgssubstitutionlistwidget.sip new file mode 100644 index 000000000000..083ecf886ae1 --- /dev/null +++ b/python/gui/qgssubstitutionlistwidget.sip @@ -0,0 +1,73 @@ +/** \class QgsSubstitutionListWidget + * \ingroup gui + * A widget which allows users to specify a list of substitutions to apply to a string, with + * options for exporting and importing substitution lists. + * \note added in QGIS 3.0 + * \see QgsSubstitutionListDialog + */ + +class QgsSubstitutionListWidget : public QgsPanelWidget +{ +%TypeHeaderCode + #include +%End + + public: + + /** Constructor for QgsSubstitutionListWidget. + * @param parent parent widget + */ + QgsSubstitutionListWidget( QWidget* parent /TransferThis/ = nullptr ); + + /** Sets the list of substitutions to show in the widget. + * @param substitutions substitution list + * @see substitutions() + */ + void setSubstitutions( const QgsStringReplacementCollection& substitutions ); + + /** Returns the list of substitutions currently defined by the widget. + * @see setSubstitutions() + */ + QgsStringReplacementCollection substitutions() const; + + signals: + + //! Emitted when the substitution definitions change. + void substitutionsChanged( const QgsStringReplacementCollection& substitutions ); + +}; + + + +/** \class QgsSubstitutionListDialog + * \ingroup gui + * A dialog which allows users to specify a list of substitutions to apply to a string, with + * options for exporting and importing substitution lists. + * \see QgsSubstitutionListWidget +*/ + +class QgsSubstitutionListDialog : public QDialog +{ +%TypeHeaderCode + #include +%End + + public: + + /** Constructor for QgsSubstitutionListDialog. + * @param parent parent widget + */ + QgsSubstitutionListDialog( QWidget* parent /TransferThis/ = nullptr ); + + /** Sets the list of substitutions to show in the dialog. + * @param substitutions substitution list + * @see substitutions() + */ + void setSubstitutions( const QgsStringReplacementCollection& substitutions ); + + /** Returns the list of substitutions currently defined by the dialog. + * @see setSubstitutions() + */ + QgsStringReplacementCollection substitutions() const; + +}; diff --git a/python/gui/qgstextformatwidget.sip b/python/gui/qgstextformatwidget.sip new file mode 100644 index 000000000000..371e0f542554 --- /dev/null +++ b/python/gui/qgstextformatwidget.sip @@ -0,0 +1,88 @@ +/** \class QgsTextFormatWidget + * \ingroup gui + * A widget for customising text formatting settings. + * + * QgsTextFormatWidget provides a widget for controlling the appearance of text rendered + * using QgsTextRenderer. The preview includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * Additionally, the widget can handle labeling settings due to the large overlap between + * the text renderer settings and the labeling settings. This mode is possible by + * subclassing QgsTextFormatWidget and calling the protected constructor with a mode + * of Labeling. + * + * @note Added in QGIS 3.0 + */ + +class QgsTextFormatWidget : public QgsPanelWidget +{ +%TypeHeaderCode + #include +%End + + public: + + /** Constructor for QgsTextFormatWidget. + * @param format initial formatting settings to show in widget + * @param mapCanvas associated map canvas + * @param parent parent widget + */ + QgsTextFormatWidget( const QgsTextFormat& format = QgsTextFormat(), QgsMapCanvas* mapCanvas = nullptr, QWidget* parent /TransferThis/ = nullptr ); + + ~QgsTextFormatWidget(); + + /** Returns the current formatting settings defined by the widget. + */ + QgsTextFormat format() const; + + public slots: + + /** Sets whether the widget should be shown in a compact dock mode. + * @param enabled set to true to show in dock mode. + */ + void setDockMode( bool enabled ); + + signals: + + //! Emitted when the text format defined by the widget changes + void widgetChanged(); + + protected: + + //! Widget mode + enum Mode + { + Text, //!< Default mode, show text formatting settings only + Labeling, //!< Show labeling settings in addition to text formatting settings + }; + + /** Constructor for QgsTextFormatWidget. + * @param mapCanvas associated map canvas + * @param parent parent widget + * @param mode widget mode + */ + QgsTextFormatWidget( QgsMapCanvas* mapCanvas, QWidget* parent /TransferThis/, Mode mode ); + + /** Updates the widget's state to reflect the settings in a QgsTextFormat. + * @param format source format + */ + void updateWidgetForFormat( const QgsTextFormat& format ); + + /** Sets the background color for the text preview widget. + * @param color background color + */ + void setPreviewBackground( const QColor& color ); + + /** Controls whether data defined alignment buttons are enabled. + * @param enable set to true to enable alignment controls + */ + void enableDataDefinedAlignment( bool enable ); + + protected slots: + + //! Updates line placement options to reflect current state of widget + void updateLinePlacementOptions(); + + //! Updates label placement options to reflect current state of widget + void updatePlacementWidgets(); +}; diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 14cb52ed6bdd..0c185ca42974 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -116,7 +116,6 @@ SET(QGIS_APP_SRCS qgsrelationadddlg.cpp qgsselectbyformdialog.cpp qgsstatisticalsummarydockwidget.cpp - qgssubstitutionlistwidget.cpp qgstextannotationdialog.cpp qgssvgannotationdialog.cpp qgsundowidget.cpp @@ -293,7 +292,6 @@ SET (QGIS_APP_MOC_HDRS qgsselectbyformdialog.h qgssponsors.h qgsstatisticalsummarydockwidget.h - qgssubstitutionlistwidget.h qgssvgannotationdialog.h qgstextannotationdialog.h qgstipgui.h diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index b50d0fe3b09f..02943242428d 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -16,28 +16,11 @@ ***************************************************************************/ #include "qgslabelinggui.h" - -#include -#include -#include -#include - -#include "qgsdatadefinedbutton.h" -#include "qgsexpressionbuilderdialog.h" -#include "qgsexpression.h" -#include "qgsfontutils.h" #include "qgisapp.h" -#include "qgsproject.h" -#include "qgssvgcache.h" -#include "qgssymbollayerutils.h" -#include "qgscharacterselectdialog.h" -#include "qgssvgselectorwidget.h" +#include "qgsvectorlayer.h" +#include "qgsmapcanvas.h" #include "qgsvectorlayerlabeling.h" -#include "qgslogger.h" -#include "qgssubstitutionlistwidget.h" - -#include -#include +#include "qgsproject.h" QgsExpressionContext QgsLabelingGui::createExpressionContext() const { @@ -60,69 +43,11 @@ QgsExpressionContext QgsLabelingGui::createExpressionContext() const } QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, const QgsPalLayerSettings* layerSettings, QWidget* parent ) - : QWidget( parent ) + : QgsTextFormatWidget( mapCanvas, parent, QgsTextFormatWidget::Labeling ) , mLayer( layer ) - , mMapCanvas( mapCanvas ) , mSettings( layerSettings ) , mMode( NoLabels ) - , mCharDlg( nullptr ) - , mQuadrantBtnGrp( nullptr ) - , mDirectSymbBtnGrp( nullptr ) - , mUpsidedownBtnGrp( nullptr ) - , mPlacePointBtnGrp( nullptr ) - , mPlaceLineBtnGrp( nullptr ) - , mPlacePolygonBtnGrp( nullptr ) - , mPreviewSize( 24 ) - , mMinPixelLimit( 0 ) - , mLoadSvgParams( false ) { - setupUi( this ); - - mPreviewScaleComboBox->setMapCanvas( mMapCanvas ); - mPreviewScaleComboBox->setShowCurrentScaleButton( true ); - connect( mPreviewScaleComboBox, SIGNAL( scaleChanged( double ) ), this, SLOT( previewScaleChanged( double ) ) ); - - mFieldExpressionWidget->registerExpressionContextGenerator( this ); - - Q_FOREACH ( QgsUnitSelectionWidget* unitWidget, findChildren() ) - { - unitWidget->setMapCanvas( mMapCanvas ); - } - mFontSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderMapUnits - << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderPixels ); - mBufferUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mShapeSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mShapeOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mShapeRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits - << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderPercentage ); - mShapeBorderWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mShadowOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mShadowRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mPointOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mLineDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - mRepeatDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); - - mFontLineHeightSpinBox->setClearValue( 1.0 ); - mShapeRotationDblSpnBx->setClearValue( 0.0 ); - mShapeOffsetXSpnBx->setClearValue( 0.0 ); - mShapeOffsetYSpnBx->setClearValue( 0.0 ); - mPointOffsetXSpinBox->setClearValue( 0.0 ); - mPointOffsetYSpinBox->setClearValue( 0.0 ); - mPointAngleSpinBox->setClearValue( 0.0 ); - mFontLetterSpacingSpinBox->setClearValue( 0.0 ); - mFontWordSpacingSpinBox->setClearValue( 0.0 ); - mZIndexSpinBox->setClearValue( 0.0 ); - - mObstacleTypeComboBox->addItem( tr( "Over the feature's interior" ), QgsPalLayerSettings::PolygonInterior ); - mObstacleTypeComboBox->addItem( tr( "Over the feature's boundary" ), QgsPalLayerSettings::PolygonBoundary ); - - mOffsetTypeComboBox->addItem( tr( "From point" ), QgsPalLayerSettings::FromPoint ); - mOffsetTypeComboBox->addItem( tr( "From symbol bounds" ), QgsPalLayerSettings::FromSymbolBounds ); - - mCharDlg = new QgsCharacterSelectorDialog( this ); - - mRefFont = lblFontPreview->font(); - // connections for groupboxes with separate activation checkboxes (that need to honor data defined setting) connect( mBufferDrawChkBx, SIGNAL( toggled( bool ) ), this, SLOT( updateUi() ) ); connect( mShapeDrawChkBx, SIGNAL( toggled( bool ) ), this, SLOT( updateUi() ) ); @@ -132,443 +57,9 @@ QgsLabelingGui::QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, connect( mScaleBasedVisibilityChkBx, SIGNAL( toggled( bool ) ), this, SLOT( updateUi() ) ); connect( mFontLimitPixelChkBox, SIGNAL( toggled( bool ) ), this, SLOT( updateUi() ) ); - // internal connections - connect( mFontTranspSlider, SIGNAL( valueChanged( int ) ), mFontTranspSpinBox, SLOT( setValue( int ) ) ); - connect( mFontTranspSpinBox, SIGNAL( valueChanged( int ) ), mFontTranspSlider, SLOT( setValue( int ) ) ); - connect( mBufferTranspSlider, SIGNAL( valueChanged( int ) ), mBufferTranspSpinBox, SLOT( setValue( int ) ) ); - connect( mBufferTranspSpinBox, SIGNAL( valueChanged( int ) ), mBufferTranspSlider, SLOT( setValue( int ) ) ); - connect( mShapeTranspSlider, SIGNAL( valueChanged( int ) ), mShapeTranspSpinBox, SLOT( setValue( int ) ) ); - connect( mShapeTranspSpinBox, SIGNAL( valueChanged( int ) ), mShapeTranspSlider, SLOT( setValue( int ) ) ); - connect( mShadowOffsetAngleDial, SIGNAL( valueChanged( int ) ), mShadowOffsetAngleSpnBx, SLOT( setValue( int ) ) ); - connect( mShadowOffsetAngleSpnBx, SIGNAL( valueChanged( int ) ), mShadowOffsetAngleDial, SLOT( setValue( int ) ) ); - connect( mShadowTranspSlider, SIGNAL( valueChanged( int ) ), mShadowTranspSpnBx, SLOT( setValue( int ) ) ); - connect( mShadowTranspSpnBx, SIGNAL( valueChanged( int ) ), mShadowTranspSlider, SLOT( setValue( int ) ) ); - connect( mLimitLabelChkBox, SIGNAL( toggled( bool ) ), mLimitLabelSpinBox, SLOT( setEnabled( bool ) ) ); - connect( mCheckBoxSubstituteText, SIGNAL( toggled( bool ) ), mToolButtonConfigureSubstitutes, SLOT( setEnabled( bool ) ) ); - - //connections to prevent users removing all line placement positions - connect( chkLineAbove, SIGNAL( toggled( bool ) ), this, SLOT( updateLinePlacementOptions() ) ); - connect( chkLineBelow, SIGNAL( toggled( bool ) ), this, SLOT( updateLinePlacementOptions() ) ); - connect( chkLineOn, SIGNAL( toggled( bool ) ), this, SLOT( updateLinePlacementOptions() ) ); - - populateFontCapitalsComboBox(); - - // color buttons - mPreviewBackgroundBtn->setColorDialogTitle( tr( "Select fill color" ) ); - mPreviewBackgroundBtn->setContext( "labelling" ); - btnTextColor->setColorDialogTitle( tr( "Select text color" ) ); - btnTextColor->setContext( "labelling" ); - btnTextColor->setDefaultColor( Qt::black ); - btnBufferColor->setColorDialogTitle( tr( "Select buffer color" ) ); - btnBufferColor->setContext( "labelling" ); - btnBufferColor->setDefaultColor( Qt::white ); - mShapeBorderColorBtn->setColorDialogTitle( tr( "Select border color" ) ); - mShapeBorderColorBtn->setContext( "labelling" ); - mShapeFillColorBtn->setColorDialogTitle( tr( "Select fill color" ) ); - mShapeFillColorBtn->setContext( "labelling" ); - mShadowColorBtn->setColorDialogTitle( tr( "Select shadow color" ) ); - mShadowColorBtn->setContext( "labelling" ); - mShadowColorBtn->setDefaultColor( Qt::black ); - - // set up quadrant offset button group - mQuadrantBtnGrp = new QButtonGroup( this ); - mQuadrantBtnGrp->addButton( mPointOffsetAboveLeft, ( int )QgsPalLayerSettings::QuadrantAboveLeft ); - mQuadrantBtnGrp->addButton( mPointOffsetAbove, ( int )QgsPalLayerSettings::QuadrantAbove ); - mQuadrantBtnGrp->addButton( mPointOffsetAboveRight, ( int )QgsPalLayerSettings::QuadrantAboveRight ); - mQuadrantBtnGrp->addButton( mPointOffsetLeft, ( int )QgsPalLayerSettings::QuadrantLeft ); - mQuadrantBtnGrp->addButton( mPointOffsetOver, ( int )QgsPalLayerSettings::QuadrantOver ); - mQuadrantBtnGrp->addButton( mPointOffsetRight, ( int )QgsPalLayerSettings::QuadrantRight ); - mQuadrantBtnGrp->addButton( mPointOffsetBelowLeft, ( int )QgsPalLayerSettings::QuadrantBelowLeft ); - mQuadrantBtnGrp->addButton( mPointOffsetBelow, ( int )QgsPalLayerSettings::QuadrantBelow ); - mQuadrantBtnGrp->addButton( mPointOffsetBelowRight, ( int )QgsPalLayerSettings::QuadrantBelowRight ); - mQuadrantBtnGrp->setExclusive( true ); - - // setup direction symbol(s) button group - mDirectSymbBtnGrp = new QButtonGroup( this ); - mDirectSymbBtnGrp->addButton( mDirectSymbRadioBtnLR, ( int )QgsPalLayerSettings::SymbolLeftRight ); - mDirectSymbBtnGrp->addButton( mDirectSymbRadioBtnAbove, ( int )QgsPalLayerSettings::SymbolAbove ); - mDirectSymbBtnGrp->addButton( mDirectSymbRadioBtnBelow, ( int )QgsPalLayerSettings::SymbolBelow ); - mDirectSymbBtnGrp->setExclusive( true ); - - // upside-down labels button group - mUpsidedownBtnGrp = new QButtonGroup( this ); - mUpsidedownBtnGrp->addButton( mUpsidedownRadioOff, ( int )QgsPalLayerSettings::Upright ); - mUpsidedownBtnGrp->addButton( mUpsidedownRadioDefined, ( int )QgsPalLayerSettings::ShowDefined ); - mUpsidedownBtnGrp->addButton( mUpsidedownRadioAll, ( int )QgsPalLayerSettings::ShowAll ); - mUpsidedownBtnGrp->setExclusive( true ); - - //mShapeCollisionsChkBx->setVisible( false ); // until implemented - - // post updatePlacementWidgets() connections - connect( chkLineAbove, SIGNAL( toggled( bool ) ), this, SLOT( updatePlacementWidgets() ) ); - connect( chkLineBelow, SIGNAL( toggled( bool ) ), this, SLOT( updatePlacementWidgets() ) ); - - // setup point placement button group - mPlacePointBtnGrp = new QButtonGroup( this ); - mPlacePointBtnGrp->addButton( radPredefinedOrder, ( int )QgsPalLayerSettings::OrderedPositionsAroundPoint ); - mPlacePointBtnGrp->addButton( radAroundPoint, ( int )QgsPalLayerSettings::AroundPoint ); - mPlacePointBtnGrp->addButton( radOverPoint, ( int )QgsPalLayerSettings::OverPoint ); - mPlacePointBtnGrp->setExclusive( true ); - connect( mPlacePointBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePlacementWidgets() ) ); - - // setup line placement button group (assigned enum id currently unused) - mPlaceLineBtnGrp = new QButtonGroup( this ); - mPlaceLineBtnGrp->addButton( radLineParallel, ( int )QgsPalLayerSettings::Line ); - mPlaceLineBtnGrp->addButton( radLineCurved, ( int )QgsPalLayerSettings::Curved ); - mPlaceLineBtnGrp->addButton( radLineHorizontal, ( int )QgsPalLayerSettings::Horizontal ); - mPlaceLineBtnGrp->setExclusive( true ); - connect( mPlaceLineBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePlacementWidgets() ) ); - - // setup polygon placement button group (assigned enum id currently unused) - mPlacePolygonBtnGrp = new QButtonGroup( this ); - mPlacePolygonBtnGrp->addButton( radOverCentroid, ( int )QgsPalLayerSettings::OverPoint ); - mPlacePolygonBtnGrp->addButton( radAroundCentroid, ( int )QgsPalLayerSettings::AroundPoint ); - mPlacePolygonBtnGrp->addButton( radPolygonHorizontal, ( int )QgsPalLayerSettings::Horizontal ); - mPlacePolygonBtnGrp->addButton( radPolygonFree, ( int )QgsPalLayerSettings::Free ); - mPlacePolygonBtnGrp->addButton( radPolygonPerimeter, ( int )QgsPalLayerSettings::Line ); - mPlacePolygonBtnGrp->addButton( radPolygonPerimeterCurved, ( int )QgsPalLayerSettings::PerimeterCurved ); - mPlacePolygonBtnGrp->setExclusive( true ); - connect( mPlacePolygonBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePlacementWidgets() ) ); - - // TODO: is this necessary? maybe just use the data defined-only rotation? - mPointAngleDDBtn->setVisible( false ); - - // Global settings group for groupboxes' saved/retored collapsed state - // maintains state across different dialogs - Q_FOREACH ( QgsCollapsibleGroupBox *grpbox, findChildren() ) - { - grpbox->setSettingGroup( QString( "mAdvLabelingDlg" ) ); - } - - connect( groupBox_mPreview, - SIGNAL( collapsedStateChanged( bool ) ), - this, - SLOT( collapseSample( bool ) ) ); - - // get rid of annoying outer focus rect on Mac - mLabelingOptionsListWidget->setAttribute( Qt::WA_MacShowFocusRect, false ); - - QSettings settings; - - // reset horiz strech of left side of options splitter (set to 1 for previewing in Qt Designer) - QSizePolicy policy( mLabelingOptionsListFrame->sizePolicy() ); - policy.setHorizontalStretch( 0 ); - mLabelingOptionsListFrame->setSizePolicy( policy ); - if ( !settings.contains( QString( "/Windows/Labeling/OptionsSplitState" ) ) ) - { - // set left list widget width on intial showing - QList splitsizes; - splitsizes << 115; - mLabelingOptionsSplitter->setSizes( splitsizes ); - } - - // set up reverse connection from stack to list - connect( mLabelStackedWidget, SIGNAL( currentChanged( int ) ), this, SLOT( optionsStackedWidget_CurrentChanged( int ) ) ); - - // restore dialog, splitters and current tab - mFontPreviewSplitter->restoreState( settings.value( QString( "/Windows/Labeling/FontPreviewSplitState" ) ).toByteArray() ); - mLabelingOptionsSplitter->restoreState( settings.value( QString( "/Windows/Labeling/OptionsSplitState" ) ).toByteArray() ); - - mLabelingOptionsListWidget->setCurrentRow( settings.value( QString( "/Windows/Labeling/Tab" ), 0 ).toInt() ); - - setDockMode( false ); - - - QList widgets; - widgets << btnBufferColor - << btnTextColor - << chkLabelPerFeaturePart - << chkLineAbove - << chkLineBelow - << chkLineOn - << chkLineOrientationDependent - << chkMergeLines - << chkPreserveRotation - << comboBlendMode - << comboBufferBlendMode - << mAlwaysShowDDBtn - << mBufferBlendModeDDBtn - << mBufferColorDDBtn - << mBufferDrawChkBx - << mBufferDrawDDBtn - << mBufferJoinStyleComboBox - << mBufferJoinStyleDDBtn - << mBufferSizeDDBtn - << mBufferTranspDDBtn - << mBufferTranspFillChbx - << mBufferTranspSpinBox - << mBufferUnitsDDBtn - << mCentroidDDBtn - << mCentroidInsideCheckBox - << mChkNoObstacle - << mCoordAlignmentHDDBtn - << mCoordAlignmentVDDBtn - << mCoordRotationDDBtn - << mCoordXDDBtn - << mCoordYDDBtn - << mDirectSymbChkBx - << mDirectSymbDDBtn - << mDirectSymbLeftDDBtn - << mDirectSymbLeftLineEdit - << mDirectSymbPlacementDDBtn - << mDirectSymbRevChkBx - << mDirectSymbRevDDBtn - << mDirectSymbRightDDBtn - << mDirectSymbRightLineEdit - << mFitInsidePolygonCheckBox - << mFontBlendModeDDBtn - << mFontBoldDDBtn - << mFontCapitalsComboBox - << mFontCaseDDBtn - << mFontColorDDBtn - << mFontDDBtn - << mFontItalicDDBtn - << mFontLetterSpacingDDBtn - << mFontLetterSpacingSpinBox - << mFontLimitPixelChkBox - << mFontLimitPixelDDBtn - << mFontLineHeightDDBtn - << mFontLineHeightSpinBox - << mFontMaxPixelDDBtn - << mFontMaxPixelSpinBox - << mFontMinPixelDDBtn - << mFontMinPixelSpinBox - << mFontMultiLineAlignComboBox - << mFontMultiLineAlignDDBtn - << mFontSizeDDBtn - << mFontSizeSpinBox - << mFontStrikeoutDDBtn - << mFontStyleComboBox - << mFontStyleDDBtn - << mFontTranspDDBtn - << mFontTranspSpinBox - << mFontUnderlineDDBtn - << mFontUnitsDDBtn - << mFontWordSpacingDDBtn - << mFontWordSpacingSpinBox - << mFormatNumChkBx - << mFormatNumDDBtn - << mFormatNumDecimalsDDBtn - << mFormatNumDecimalsSpnBx - << mFormatNumPlusSignChkBx - << mFormatNumPlusSignDDBtn - << mIsObstacleDDBtn - << mLimitLabelChkBox - << mLimitLabelSpinBox - << mLineDistanceDDBtn - << mLineDistanceSpnBx - << mLineDistanceUnitDDBtn - << mLineDistanceUnitWidget - << mMaxCharAngleDDBtn - << mMaxCharAngleInDSpinBox - << mMaxCharAngleOutDSpinBox - << mMinSizeSpinBox - << mObstacleFactorDDBtn - << mObstacleFactorSlider - << mObstacleTypeComboBox - << mOffsetTypeComboBox - << mPalShowAllLabelsForLayerChkBx - << mPointAngleDDBtn - << mPointAngleSpinBox - << mPointOffsetDDBtn - << mPointOffsetUnitsDDBtn - << mPointOffsetUnitWidget - << mPointOffsetXSpinBox - << mPointOffsetYSpinBox - << mPointPositionOrderDDBtn - << mPointQuadOffsetDDBtn - << mPreviewBackgroundBtn - << mPreviewTextEdit - << mPriorityDDBtn - << mPrioritySlider - << mRepeatDistanceDDBtn - << mRepeatDistanceSpinBox - << mRepeatDistanceUnitDDBtn - << mRepeatDistanceUnitWidget - << mScaleBasedVisibilityChkBx - << mScaleBasedVisibilityDDBtn - << mScaleBasedVisibilityMaxDDBtn - << mScaleBasedVisibilityMaxSpnBx - << mScaleBasedVisibilityMinDDBtn - << mScaleBasedVisibilityMinSpnBx - << mShadowBlendCmbBx - << mShadowBlendDDBtn - << mShadowColorBtn - << mShadowColorDDBtn - << mShadowDrawChkBx - << mShadowDrawDDBtn - << mShadowOffsetAngleDDBtn - << mShadowOffsetAngleSpnBx - << mShadowOffsetDDBtn - << mShadowOffsetGlobalChkBx - << mShadowOffsetSpnBx - << mShadowOffsetUnitsDDBtn - << mShadowOffsetUnitWidget - << mShadowRadiusAlphaChkBx - << mShadowRadiusDDBtn - << mShadowRadiusDblSpnBx - << mShadowRadiusUnitsDDBtn - << mShadowRadiusUnitWidget - << mShadowScaleDDBtn - << mShadowScaleSpnBx - << mShadowTranspDDBtn - << mShadowTranspSpnBx - << mShadowUnderCmbBx - << mShadowUnderDDBtn - << mShapeBlendCmbBx - << mShapeBlendModeDDBtn - << mShapeBorderColorBtn - << mShapeBorderColorDDBtn - << mShapeBorderUnitsDDBtn - << mShapeBorderWidthDDBtn - << mShapeBorderWidthSpnBx - << mShapeBorderWidthUnitWidget - << mShapeDrawChkBx - << mShapeDrawDDBtn - << mShapeFillColorBtn - << mShapeFillColorDDBtn - << mShapeOffsetDDBtn - << mShapeOffsetUnitsDDBtn - << mShapeOffsetXSpnBx - << mShapeOffsetYSpnBx - << mShapeOffsetUnitWidget - << mShapePenStyleCmbBx - << mShapePenStyleDDBtn - << mShapeRadiusDDBtn - << mShapeRadiusUnitsDDBtn - << mShapeRadiusXDbSpnBx - << mShapeRadiusYDbSpnBx - << mShapeRotationCmbBx - << mShapeRotationDDBtn - << mShapeRotationDblSpnBx - << mShapeRotationTypeDDBtn - << mShapeRadiusUnitWidget - << mShapeSVGPathDDBtn - << mShapeSVGPathLineEdit - << mShapeSizeCmbBx - << mShapeSizeTypeDDBtn - << mShapeSizeUnitsDDBtn - << mShapeSizeUnitWidget - << mShapeSizeXDDBtn - << mShapeSizeXSpnBx - << mShapeSizeYDDBtn - << mShapeSizeYSpnBx - << mShapeTranspDDBtn - << mShapeTranspSpinBox - << mShapeTypeCmbBx - << mShapeTypeDDBtn - << mShowLabelDDBtn - << mWrapCharDDBtn - << mZIndexDDBtn - << mZIndexSpinBox - << spinBufferSize - << wrapCharacterEdit - << mCentroidRadioVisible - << mCentroidRadioWhole - << mDirectSymbRadioBtnAbove - << mDirectSymbRadioBtnBelow - << mDirectSymbRadioBtnLR - << mUpsidedownRadioAll - << mUpsidedownRadioDefined - << mUpsidedownRadioOff - << radAroundCentroid - << radAroundPoint - << radLineCurved - << radLineHorizontal - << radLineParallel - << radOverCentroid - << radOverPoint - << radPolygonFree - << radPolygonHorizontal - << radPolygonPerimeter - << radPolygonPerimeterCurved - << radPredefinedOrder - << mFieldExpressionWidget - << mCheckBoxSubstituteText; - connectValueChanged( widgets, SLOT( updatePreview() ) ); - - connect( mQuadrantBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePreview() ) ); - - // set correct initial tab to match displayed setting page - whileBlocking( mOptionsTab )->setCurrentIndex( mLabelStackedWidget->currentIndex() ); - - if ( mMapCanvas ) - { - lblFontPreview->setMapUnits( mMapCanvas->mapSettings().mapUnits() ); - mPreviewScaleComboBox->setScale( 1.0 / mMapCanvas->mapSettings().scale() ); - } -} - -void QgsLabelingGui::setDockMode( bool enabled ) -{ - mOptionsTab->setVisible( enabled ); - mOptionsTab->setTabToolTip( 0, tr( "Text" ) ); - mOptionsTab->setTabToolTip( 1, tr( "Formatting" ) ); - mOptionsTab->setTabToolTip( 2, tr( "Buffer" ) ); - mOptionsTab->setTabToolTip( 3, tr( "Background" ) ); - mOptionsTab->setTabToolTip( 4, tr( "Shadow" ) ); - mOptionsTab->setTabToolTip( 5, tr( "Placement" ) ); - mOptionsTab->setTabToolTip( 6, tr( "Rendering" ) ); - - mLabelingOptionsListFrame->setVisible( !enabled ); - groupBox_mPreview->setVisible( !enabled ); - mDockMode = enabled; -} + mFieldExpressionWidget->registerExpressionContextGenerator( this ); -void QgsLabelingGui::connectValueChanged( const QList& widgets, const char *slot ) -{ - Q_FOREACH ( QWidget* widget, widgets ) - { - if ( QgsDataDefinedButton* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( dataDefinedActivated( bool ) ), this, slot ); - connect( w, SIGNAL( dataDefinedChanged( QString ) ), this, slot ); - } - else if ( QgsFieldExpressionWidget* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( fieldChanged( QString ) ), this, slot ); - } - else if ( QgsUnitSelectionWidget* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( changed() ), this, slot ); - } - else if ( QComboBox* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( currentIndexChanged( int ) ), this, slot ); - } - else if ( QSpinBox* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( valueChanged( int ) ), this, slot ); - } - else if ( QDoubleSpinBox* w = qobject_cast( widget ) ) - { - connect( w , SIGNAL( valueChanged( double ) ), this, slot ); - } - else if ( QgsColorButton* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( colorChanged( QColor ) ), this, slot ); - } - else if ( QCheckBox* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( toggled( bool ) ), this, slot ); - } - else if ( QRadioButton* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( toggled( bool ) ), this, slot ); - } - else if ( QLineEdit* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( textEdited( QString ) ), this, slot ); - } - else if ( QSlider* w = qobject_cast( widget ) ) - { - connect( w, SIGNAL( valueChanged( int ) ), this, slot ); - } - else - { - QgsLogger::warning( QString( "Could not create connection for widget %1" ).arg( widget->objectName() ) ); - } - } + setLayer( layer ); } void QgsLabelingGui::setLayer( QgsMapLayer* mapLayer ) @@ -584,12 +75,15 @@ void QgsLabelingGui::setLayer( QgsMapLayer* mapLayer ) } QgsVectorLayer *layer = qobject_cast( mapLayer ); - mLayer = layer ; - init(); -} + mLayer = layer; + + // load labeling settings from layer + QgsPalLayerSettings lyr; + if ( mSettings ) + lyr = *mSettings; + else + lyr.readFromLayer( mLayer ); -void QgsLabelingGui::init() -{ // show/hide options based upon geometry type chkMergeLines->setVisible( mLayer->geometryType() == QgsWkbTypes::LineGeometry ); mDirectSymbolsFrame->setVisible( mLayer->geometryType() == QgsWkbTypes::LineGeometry ); @@ -597,13 +91,12 @@ void QgsLabelingGui::init() mPolygonObstacleTypeFrame->setVisible( mLayer->geometryType() == QgsWkbTypes::PolygonGeometry ); mPolygonFeatureOptionsFrame->setVisible( mLayer->geometryType() == QgsWkbTypes::PolygonGeometry ); - // field combo and expression button mFieldExpressionWidget->setLayer( mLayer ); - QgsDistanceArea myDa; - myDa.setSourceCrs( mLayer->crs().srsid() ); - myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); - mFieldExpressionWidget->setGeomCalculator( myDa ); + QgsDistanceArea da; + da.setSourceCrs( mLayer->crs().srsid() ); + da.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); + da.setEllipsoid( QgsProject::instance()->ellipsoid() ); + mFieldExpressionWidget->setGeomCalculator( da ); // set placement methods page based on geometry type switch ( mLayer->geometryType() ) @@ -636,24 +129,13 @@ void QgsLabelingGui::init() mFontMultiLineAlignComboBox->removeItem( idx ); } - // load labeling settings from layer - QgsPalLayerSettings lyr; - if ( mSettings ) - lyr = *mSettings; - else - lyr.readFromLayer( mLayer ); + mFieldExpressionWidget->setEnabled( mMode == Labels ); + mLabelingFrame->setEnabled( mMode == Labels ); - QgsTextFormat format = lyr.format(); - QgsTextBufferSettings buffer = format.buffer(); - QgsTextBackgroundSettings background = format.background(); - QgsTextShadowSettings shadow = format.shadow(); + updateWidgetForFormat( lyr.format() ); blockInitSignals( true ); - mFieldExpressionWidget->setEnabled( mMode == Labels ); - mLabelingFrame->setEnabled( mMode == Labels ); - - // set the current field or add the current expression to the bottom of the list mFieldExpressionWidget->setRow( -1 ); mFieldExpressionWidget->setField( lyr.fieldName ); mCheckBoxSubstituteText->setChecked( lyr.useSubstitutions ); @@ -744,7 +226,6 @@ void QgsLabelingGui::init() mMaxCharAngleOutDSpinBox->setValue( qAbs( lyr.maxCurvedCharAngleOut ) ); wrapCharacterEdit->setText( lyr.wrapChar ); - mFontLineHeightSpinBox->setValue( format.lineHeight() ); mFontMultiLineAlignComboBox->setCurrentIndex(( unsigned int ) lyr.multilineAlign ); chkPreserveRotation->setChecked( lyr.preserveRotation ); @@ -756,17 +237,6 @@ void QgsLabelingGui::init() mScaleBasedVisibilityMinSpnBx->setValue( lyr.scaleMin ); mScaleBasedVisibilityMaxSpnBx->setValue( lyr.scaleMax ); - // buffer - mBufferDrawChkBx->setChecked( buffer.enabled() ); - spinBufferSize->setValue( buffer.size() ); - mBufferUnitWidget->setUnit( buffer.sizeUnit() ); - mBufferUnitWidget->setMapUnitScale( buffer.sizeMapUnitScale() ); - btnBufferColor->setColor( buffer.color() ); - mBufferTranspSpinBox->setValue( 100 - 100 * buffer.opacity() ); - mBufferJoinStyleComboBox->setPenJoinStyle( buffer.joinStyle() ); - mBufferTranspFillChbx->setChecked( buffer.fillBufferInterior() ); - comboBufferBlendMode->setBlendMode( buffer.blendMode() ); - mFormatNumChkBx->setChecked( lyr.formatNumbers ); mFormatNumDecimalsSpnBx->setValue( lyr.decimals ); mFormatNumPlusSignChkBx->setChecked( lyr.plusSign ); @@ -777,96 +247,9 @@ void QgsLabelingGui::init() mMinPixelLimit = lyr.fontMinPixelSize; // ignored after first settings save mFontMinPixelSpinBox->setValue( lyr.fontMinPixelSize == 0 ? 3 : lyr.fontMinPixelSize ); mFontMaxPixelSpinBox->setValue( lyr.fontMaxPixelSize ); - mFontSizeUnitWidget->setUnit( format.sizeUnit() ); - mFontSizeUnitWidget->setMapUnitScale( format.sizeMapUnitScale() ); mZIndexSpinBox->setValue( lyr.zIndex ); - mRefFont = format.font(); - mFontSizeSpinBox->setValue( format.size() ); - btnTextColor->setColor( format.color() ); - mFontTranspSpinBox->setValue( 100 - 100 * format.opacity() ); - comboBlendMode->setBlendMode( format.blendMode() ); - - mFontWordSpacingSpinBox->setValue( format.font().wordSpacing() ); - mFontLetterSpacingSpinBox->setValue( format.font().letterSpacing() ); - - QgsFontUtils::updateFontViaStyle( mRefFont, format.namedStyle() ); - updateFont( mRefFont ); - - // show 'font not found' if substitution has occurred (should come after updateFont()) - mFontMissingLabel->setVisible( !format.fontFound() ); - if ( !format.fontFound() ) - { - QString missingTxt = tr( "%1 not found. Default substituted." ); - QString txtPrepend = tr( "Chosen font" ); - if ( !format.resolvedFontFamily().isEmpty() ) - { - txtPrepend = QString( "'%1'" ).arg( format.resolvedFontFamily() ); - } - mFontMissingLabel->setText( missingTxt.arg( txtPrepend ) ); - - // ensure user is sent to 'Text style' section to see notice - mLabelingOptionsListWidget->setCurrentRow( 0 ); - } - - // shape background - mShapeDrawChkBx->setChecked( background.enabled() ); - mShapeTypeCmbBx->blockSignals( true ); - mShapeTypeCmbBx->setCurrentIndex( background.type() ); - mShapeTypeCmbBx->blockSignals( false ); - mShapeSVGPathLineEdit->setText( background.svgFile() ); - - mShapeSizeCmbBx->setCurrentIndex( background.sizeType() ); - mShapeSizeXSpnBx->setValue( background.size().width() ); - mShapeSizeYSpnBx->setValue( background.size().height() ); - mShapeSizeUnitWidget->setUnit( background.sizeUnit() ); - mShapeSizeUnitWidget->setMapUnitScale( background.sizeMapUnitScale() ); - mShapeRotationCmbBx->setCurrentIndex( background.rotationType() ); - mShapeRotationDblSpnBx->setEnabled( background.rotationType() != QgsTextBackgroundSettings::RotationSync ); - mShapeRotationDDBtn->setEnabled( background.rotationType() != QgsTextBackgroundSettings::RotationSync ); - mShapeRotationDblSpnBx->setValue( background.rotation() ); - mShapeOffsetXSpnBx->setValue( background.offset().x() ); - mShapeOffsetYSpnBx->setValue( background.offset().y() ); - mShapeOffsetUnitWidget->setUnit( background.offsetUnit() ); - mShapeOffsetUnitWidget->setMapUnitScale( background.offsetMapUnitScale() ); - mShapeRadiusXDbSpnBx->setValue( background.radii().width() ); - mShapeRadiusYDbSpnBx->setValue( background.radii().height() ); - mShapeRadiusUnitWidget->setUnit( background.radiiUnit() ); - mShapeRadiusUnitWidget->setMapUnitScale( background.radiiMapUnitScale() ); - - mShapeFillColorBtn->setColor( background.fillColor() ); - mShapeBorderColorBtn->setColor( background.borderColor() ); - mShapeBorderWidthSpnBx->setValue( background.borderWidth() ); - mShapeBorderWidthUnitWidget->setUnit( background.borderWidthUnit() ); - mShapeBorderWidthUnitWidget->setMapUnitScale( background.borderWidthMapUnitScale() ); - mShapePenStyleCmbBx->setPenJoinStyle( background.joinStyle() ); - - mShapeTranspSpinBox->setValue( 100 - background.opacity() * 100.0 ); - mShapeBlendCmbBx->setBlendMode( background.blendMode() ); - - mLoadSvgParams = false; - on_mShapeTypeCmbBx_currentIndexChanged( background.type() ); // force update of shape background gui - - // drop shadow - mShadowDrawChkBx->setChecked( shadow.enabled() ); - mShadowUnderCmbBx->setCurrentIndex( shadow.shadowPlacement() ); - mShadowOffsetAngleSpnBx->setValue( shadow.offsetAngle() ); - mShadowOffsetSpnBx->setValue( shadow.offsetDistance() ); - mShadowOffsetUnitWidget->setUnit( shadow.offsetUnit() ); - mShadowOffsetUnitWidget->setMapUnitScale( shadow.offsetMapUnitScale() ); - mShadowOffsetGlobalChkBx->setChecked( shadow.offsetGlobal() ); - - mShadowRadiusDblSpnBx->setValue( shadow.blurRadius() ); - mShadowRadiusUnitWidget->setUnit( shadow.blurRadiusUnit() ); - mShadowRadiusUnitWidget->setMapUnitScale( shadow.blurRadiusMapUnitScale() ); - mShadowRadiusAlphaChkBx->setChecked( shadow.blurAlphaOnly() ); - mShadowTranspSpnBx->setValue( 100 - shadow.opacity() * 100.0 ); - mShadowScaleSpnBx->setValue( shadow.scale() ); - - mShadowColorBtn->setColor( shadow.color() ); - mShadowBlendCmbBx->setBlendMode( shadow.blendMode() ); - updatePlacementWidgets(); updateLinePlacementOptions(); @@ -878,18 +261,9 @@ void QgsLabelingGui::init() populateDataDefinedButtons( lyr ); enableDataDefinedAlignment( mCoordXDDBtn->isActive() && mCoordYDDBtn->isActive() ); - updateUi(); // should come after data defined button setup } -QgsLabelingGui::~QgsLabelingGui() -{ - QSettings settings; - settings.setValue( QString( "/Windows/Labeling/FontPreviewSplitState" ), mFontPreviewSplitter->saveState() ); - settings.setValue( QString( "/Windows/Labeling/OptionsSplitState" ), mLabelingOptionsSplitter->saveState() ); - settings.setValue( QString( "/Windows/Labeling/Tab" ), mLabelingOptionsListWidget->currentRow() ); -} - void QgsLabelingGui::blockInitSignals( bool block ) { chkLineAbove->blockSignals( block ); @@ -899,29 +273,6 @@ void QgsLabelingGui::blockInitSignals( bool block ) mPlacePolygonBtnGrp->blockSignals( block ); } - -void QgsLabelingGui::optionsStackedWidget_CurrentChanged( int indx ) -{ - mLabelingOptionsListWidget->blockSignals( true ); - mLabelingOptionsListWidget->setCurrentRow( indx ); - mLabelingOptionsListWidget->blockSignals( false ); -} - -void QgsLabelingGui::collapseSample( bool collapse ) -{ - if ( collapse ) - { - QList splitSizes = mFontPreviewSplitter->sizes(); - if ( splitSizes[0] > groupBox_mPreview->height() ) - { - int delta = splitSizes[0] - groupBox_mPreview->height(); - splitSizes[0] -= delta; - splitSizes[1] += delta; - mFontPreviewSplitter->setSizes( splitSizes ); - } - } -} - void QgsLabelingGui::apply() { writeSettingsToLayer(); @@ -943,7 +294,6 @@ void QgsLabelingGui::writeSettingsToLayer() void QgsLabelingGui::setLabelMode( LabelMode mode ) { mMode = mode; - mFieldExpressionWidget->setEnabled( mMode == Labels ); mLabelingFrame->setEnabled( mMode == Labels ); } @@ -1048,78 +398,7 @@ QgsPalLayerSettings QgsLabelingGui::layerSettings() lyr.useSubstitutions = mCheckBoxSubstituteText->isChecked(); lyr.substitutions = mSubstitutions; - QgsTextFormat format; - format.setColor( btnTextColor->color() ); - format.setFont( mRefFont ); - format.setSize( mFontSizeSpinBox->value() ); - format.setNamedStyle( mFontStyleComboBox->currentText() ); - format.setOpacity( 1.0 - mFontTranspSpinBox->value() / 100.0 ); - format.setBlendMode( comboBlendMode->blendMode() ); - format.setSizeUnit( mFontSizeUnitWidget->unit() ); - format.setSizeMapUnitScale( mFontSizeUnitWidget->getMapUnitScale() ); - format.setLineHeight( mFontLineHeightSpinBox->value() ); - - // buffer - QgsTextBufferSettings buffer; - buffer.setEnabled( mBufferDrawChkBx->isChecked() ); - buffer.setSize( spinBufferSize->value() ); - buffer.setColor( btnBufferColor->color() ); - buffer.setOpacity( 1.0 - mBufferTranspSpinBox->value() / 100.0 ); - buffer.setSizeUnit( mBufferUnitWidget->unit() ); - buffer.setSizeMapUnitScale( mBufferUnitWidget->getMapUnitScale() ); - buffer.setJoinStyle( mBufferJoinStyleComboBox->penJoinStyle() ); - buffer.setFillBufferInterior( mBufferTranspFillChbx->isChecked() ); - buffer.setBlendMode( comboBufferBlendMode->blendMode() ); - format.setBuffer( buffer ); - - // shape background - QgsTextBackgroundSettings background; - background.setEnabled( mShapeDrawChkBx->isChecked() ); - background.setType(( QgsTextBackgroundSettings::ShapeType )mShapeTypeCmbBx->currentIndex() ); - background.setSvgFile( mShapeSVGPathLineEdit->text() ); - background.setSizeType(( QgsTextBackgroundSettings::SizeType )mShapeSizeCmbBx->currentIndex() ); - background.setSize( QSizeF( mShapeSizeXSpnBx->value(), mShapeSizeYSpnBx->value() ) ); - background.setSizeUnit( mShapeSizeUnitWidget->unit() ); - background.setSizeMapUnitScale( mShapeSizeUnitWidget->getMapUnitScale() ); - background.setRotationType(( QgsTextBackgroundSettings::RotationType )( mShapeRotationCmbBx->currentIndex() ) ); - background.setRotation( mShapeRotationDblSpnBx->value() ); - background.setOffset( QPointF( mShapeOffsetXSpnBx->value(), mShapeOffsetYSpnBx->value() ) ); - background.setOffsetUnit( mShapeOffsetUnitWidget->unit() ); - background.setOffsetMapUnitScale( mShapeOffsetUnitWidget->getMapUnitScale() ); - background.setRadii( QSizeF( mShapeRadiusXDbSpnBx->value(), mShapeRadiusYDbSpnBx->value() ) ); - background.setRadiiUnit( mShapeRadiusUnitWidget->unit() ); - background.setRadiiMapUnitScale( mShapeRadiusUnitWidget->getMapUnitScale() ); - - background.setFillColor( mShapeFillColorBtn->color() ); - background.setBorderColor( mShapeBorderColorBtn->color() ); - background.setBorderWidth( mShapeBorderWidthSpnBx->value() ); - background.setBorderWidthUnit( mShapeBorderWidthUnitWidget->unit() ); - background.setBorderWidthMapUnitScale( mShapeBorderWidthUnitWidget->getMapUnitScale() ); - background.setJoinStyle( mShapePenStyleCmbBx->penJoinStyle() ); - background.setOpacity( 1.0 - mShapeTranspSpinBox->value() / 100.0 ); - background.setBlendMode( mShapeBlendCmbBx->blendMode() ); - format.setBackground( background ); - - // drop shadow - QgsTextShadowSettings shadow; - shadow.setEnabled( mShadowDrawChkBx->isChecked() ); - shadow.setShadowPlacement(( QgsTextShadowSettings::ShadowPlacement )mShadowUnderCmbBx->currentIndex() ); - shadow.setOffsetAngle( mShadowOffsetAngleSpnBx->value() ); - shadow.setOffsetDistance( mShadowOffsetSpnBx->value() ); - shadow.setOffsetUnit( mShadowOffsetUnitWidget->unit() ); - shadow.setOffsetMapUnitScale( mShadowOffsetUnitWidget->getMapUnitScale() ); - shadow.setOffsetGlobal( mShadowOffsetGlobalChkBx->isChecked() ); - shadow.setBlurRadius( mShadowRadiusDblSpnBx->value() ); - shadow.setBlurRadiusUnit( mShadowRadiusUnitWidget->unit() ); - shadow.setBlurRadiusMapUnitScale( mShadowRadiusUnitWidget->getMapUnitScale() ); - shadow.setBlurAlphaOnly( mShadowRadiusAlphaChkBx->isChecked() ); - shadow.setOpacity( 1.0 - mShadowTranspSpnBx->value() / 100.0 ); - shadow.setScale( mShadowScaleSpnBx->value() ); - shadow.setColor( mShadowColorBtn->color() ); - shadow.setBlendMode( mShadowBlendCmbBx->blendMode() ); - format.setShadow( shadow ); - - lyr.setFormat( format ); + lyr.setFormat( format() ); // format numbers lyr.formatNumbers = mFormatNumChkBx->isChecked(); @@ -1553,84 +832,6 @@ void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); } -void QgsLabelingGui::changeTextColor( const QColor &color ) -{ - Q_UNUSED( color ) - updatePreview(); -} - -void QgsLabelingGui::updateFont( const QFont& font ) -{ - // update background reference font - if ( font != mRefFont ) - { - mRefFont = font; - } - - // test if font is actually available - // NOTE: QgsFontUtils::fontMatchOnSystem may fail here, just crosscheck family - mFontMissingLabel->setVisible( !QgsFontUtils::fontFamilyMatchOnSystem( mRefFont.family() ) ); - - mDirectSymbLeftLineEdit->setFont( mRefFont ); - mDirectSymbRightLineEdit->setFont( mRefFont ); - - blockFontChangeSignals( true ); - mFontFamilyCmbBx->setCurrentFont( mRefFont ); - populateFontStyleComboBox(); - int idx = mFontCapitalsComboBox->findData( QVariant(( unsigned int ) mRefFont.capitalization() ) ); - mFontCapitalsComboBox->setCurrentIndex( idx == -1 ? 0 : idx ); - mFontUnderlineBtn->setChecked( mRefFont.underline() ); - mFontStrikethroughBtn->setChecked( mRefFont.strikeOut() ); - blockFontChangeSignals( false ); - - // update font name with font face -// font.setPixelSize( 24 ); - - updatePreview(); -} - -void QgsLabelingGui::blockFontChangeSignals( bool blk ) -{ - mFontFamilyCmbBx->blockSignals( blk ); - mFontStyleComboBox->blockSignals( blk ); - mFontCapitalsComboBox->blockSignals( blk ); - mFontUnderlineBtn->blockSignals( blk ); - mFontStrikethroughBtn->blockSignals( blk ); - mFontWordSpacingSpinBox->blockSignals( blk ); - mFontLetterSpacingSpinBox->blockSignals( blk ); -} - -void QgsLabelingGui::updatePreview() -{ - // In dock mode we don't have a preview we - // just let stuff know we have changed because - // there might be live updates connected. - if ( mLayer && mDockMode ) - { - emit widgetChanged(); - return; - } - - QgsTextFormat format = layerSettings().format(); - - scrollPreview(); - lblFontPreview->setFormat( format ); - QString grpboxtitle; - groupBox_mPreview->setTitle( grpboxtitle ); -} - -void QgsLabelingGui::scrollPreview() -{ - scrollArea_mPreview->ensureVisible( 0, 0, 0, 0 ); -} - -void QgsLabelingGui::setPreviewBackground( const QColor& color ) -{ - scrollArea_mPreview->widget()->setStyleSheet( QString( "background: rgb(%1, %2, %3);" ).arg( QString::number( color.red() ), - QString::number( color.green() ), - QString::number( color.blue() ) ) ); -} - void QgsLabelingGui::syncDefinedCheckboxFrame( QgsDataDefinedButton* ddBtn, QCheckBox* chkBx, QFrame* f ) { if ( ddBtn->isActive() && !chkBx->isChecked() ) @@ -1654,505 +855,6 @@ void QgsLabelingGui::updateUi() syncDefinedCheckboxFrame( mFontLimitPixelDDBtn, mFontLimitPixelChkBox, mFontLimitPixelFrame ); } -void QgsLabelingGui::changeBufferColor( const QColor &color ) -{ - Q_UNUSED( color ) - updatePreview(); -} - -void QgsLabelingGui::updatePlacementWidgets() -{ - QWidget* curWdgt = stackedPlacement->currentWidget(); - - bool showLineFrame = false; - bool showCentroidFrame = false; - bool showQuadrantFrame = false; - bool showFixedQuadrantFrame = false; - bool showPlacementPriorityFrame = false; - bool showOffsetTypeFrame = false; - bool showOffsetFrame = false; - bool showDistanceFrame = false; - bool showRotationFrame = false; - bool showMaxCharAngleFrame = false; - - bool enableMultiLinesFrame = true; - - if (( curWdgt == pagePoint && radAroundPoint->isChecked() ) - || ( curWdgt == pagePolygon && radAroundCentroid->isChecked() ) ) - { - showCentroidFrame = ( curWdgt == pagePolygon && radAroundCentroid->isChecked() ); - showDistanceFrame = true; - //showRotationFrame = true; // TODO: uncomment when supported - if ( curWdgt == pagePoint ) - { - showQuadrantFrame = true; - } - } - else if (( curWdgt == pagePoint && radOverPoint->isChecked() ) - || ( curWdgt == pagePolygon && radOverCentroid->isChecked() ) ) - { - showCentroidFrame = ( curWdgt == pagePolygon && radOverCentroid->isChecked() ); - showQuadrantFrame = true; - showFixedQuadrantFrame = true; - showOffsetFrame = true; - showRotationFrame = true; - } - else if ( curWdgt == pagePoint && radPredefinedOrder->isChecked() ) - { - showDistanceFrame = true; - showPlacementPriorityFrame = true; - showOffsetTypeFrame = true; - } - else if (( curWdgt == pageLine && radLineParallel->isChecked() ) - || ( curWdgt == pagePolygon && radPolygonPerimeter->isChecked() ) - || ( curWdgt == pageLine && radLineCurved->isChecked() ) - || ( curWdgt == pagePolygon && radPolygonPerimeterCurved->isChecked() ) ) - { - showLineFrame = true; - showDistanceFrame = true; - //showRotationFrame = true; // TODO: uncomment when supported - - bool offline = chkLineAbove->isChecked() || chkLineBelow->isChecked(); - chkLineOrientationDependent->setEnabled( offline ); - mPlacementDistanceFrame->setEnabled( offline ); - - bool isCurved = ( curWdgt == pageLine && radLineCurved->isChecked() ) - || ( curWdgt == pagePolygon && radPolygonPerimeterCurved->isChecked() ); - showMaxCharAngleFrame = isCurved; - // TODO: enable mMultiLinesFrame when supported for curved labels - enableMultiLinesFrame = !isCurved; - } - - mPlacementLineFrame->setVisible( showLineFrame ); - mPlacementCentroidFrame->setVisible( showCentroidFrame ); - mPlacementQuadrantFrame->setVisible( showQuadrantFrame ); - mPlacementFixedQuadrantFrame->setVisible( showFixedQuadrantFrame ); - mPlacementCartographicFrame->setVisible( showPlacementPriorityFrame ); - mPlacementOffsetFrame->setVisible( showOffsetFrame ); - mPlacementDistanceFrame->setVisible( showDistanceFrame ); - mPlacementOffsetTypeFrame->setVisible( showOffsetTypeFrame ); - mPlacementRotationFrame->setVisible( showRotationFrame ); - mPlacementRepeatDistanceFrame->setVisible( curWdgt == pageLine || ( curWdgt == pagePolygon && - ( radPolygonPerimeter->isChecked() || radPolygonPerimeterCurved->isChecked() ) ) ); - mPlacementMaxCharAngleFrame->setVisible( showMaxCharAngleFrame ); - - mMultiLinesFrame->setEnabled( enableMultiLinesFrame ); -} - -void QgsLabelingGui::populateFontCapitalsComboBox() -{ - mFontCapitalsComboBox->addItem( tr( "No change" ), QVariant( 0 ) ); - mFontCapitalsComboBox->addItem( tr( "All uppercase" ), QVariant( 1 ) ); - mFontCapitalsComboBox->addItem( tr( "All lowercase" ), QVariant( 2 ) ); - // Small caps doesn't work right with QPainterPath::addText() - // https://bugreports.qt-project.org/browse/QTBUG-13965 -// mFontCapitalsComboBox->addItem( tr( "Small caps" ), QVariant( 3 ) ); - mFontCapitalsComboBox->addItem( tr( "Capitalize first letter" ), QVariant( 4 ) ); -} - -void QgsLabelingGui::populateFontStyleComboBox() -{ - mFontStyleComboBox->clear(); - Q_FOREACH ( const QString &style, mFontDB.styles( mRefFont.family() ) ) - { - mFontStyleComboBox->addItem( style ); - } - - int curIndx = 0; - int stylIndx = mFontStyleComboBox->findText( mFontDB.styleString( mRefFont ) ); - if ( stylIndx > -1 ) - { - curIndx = stylIndx; - } - - mFontStyleComboBox->setCurrentIndex( curIndx ); -} - -void QgsLabelingGui::on_mFontSizeSpinBox_valueChanged( double d ) -{ - mRefFont.setPointSizeF( d ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontCapitalsComboBox_currentIndexChanged( int index ) -{ - int capitalsindex = mFontCapitalsComboBox->itemData( index ).toUInt(); - mRefFont.setCapitalization(( QFont::Capitalization ) capitalsindex ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontFamilyCmbBx_currentFontChanged( const QFont& f ) -{ - mRefFont.setFamily( f.family() ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontStyleComboBox_currentIndexChanged( const QString & text ) -{ - QgsFontUtils::updateFontViaStyle( mRefFont, text ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontUnderlineBtn_toggled( bool ckd ) -{ - mRefFont.setUnderline( ckd ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontStrikethroughBtn_toggled( bool ckd ) -{ - mRefFont.setStrikeOut( ckd ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontWordSpacingSpinBox_valueChanged( double spacing ) -{ - mRefFont.setWordSpacing( spacing ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontLetterSpacingSpinBox_valueChanged( double spacing ) -{ - mRefFont.setLetterSpacing( QFont::AbsoluteSpacing, spacing ); - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontSizeUnitWidget_changed() -{ - int index = mFontSizeUnitWidget->getUnit(); - // disable pixel size limiting for labels defined in points - if ( index == 0 ) - { - mFontLimitPixelChkBox->setChecked( false ); - } - else if ( index == 1 && mMinPixelLimit == 0 ) - { - // initial minimum trigger value set, turn on pixel size limiting by default - // for labels defined in map units (ignored after first settings save) - mFontLimitPixelChkBox->setChecked( true ); - } - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mFontMinPixelSpinBox_valueChanged( int px ) -{ - // ensure max font pixel size for map unit labels can't be lower than min - mFontMaxPixelSpinBox->setMinimum( px ); - mFontMaxPixelSpinBox->update(); -} - -void QgsLabelingGui::on_mFontMaxPixelSpinBox_valueChanged( int px ) -{ - // ensure max font pixel size for map unit labels can't be lower than min - if ( px < mFontMinPixelSpinBox->value() ) - { - mFontMaxPixelSpinBox->blockSignals( true ); - mFontMaxPixelSpinBox->setValue( mFontMinPixelSpinBox->value() ); - mFontMaxPixelSpinBox->blockSignals( false ); - } - mFontMaxPixelSpinBox->setMinimum( mFontMinPixelSpinBox->value() ); -} - -void QgsLabelingGui::on_mBufferUnitWidget_changed() -{ - updateFont( mRefFont ); -} - -void QgsLabelingGui::on_mCoordXDDBtn_dataDefinedActivated( bool active ) -{ - if ( !active ) //no data defined alignment without data defined position - { - enableDataDefinedAlignment( false ); - } - else if ( mCoordYDDBtn->isActive() ) - { - enableDataDefinedAlignment( true ); - } -} - -void QgsLabelingGui::on_mCoordYDDBtn_dataDefinedActivated( bool active ) -{ - if ( !active ) //no data defined alignment without data defined position - { - enableDataDefinedAlignment( false ); - } - else if ( mCoordXDDBtn->isActive() ) - { - enableDataDefinedAlignment( true ); - } -} - -void QgsLabelingGui::on_mShapeTypeCmbBx_currentIndexChanged( int index ) -{ - // shape background - bool isRect = (( QgsTextBackgroundSettings::ShapeType )index == QgsTextBackgroundSettings::ShapeRectangle - || ( QgsTextBackgroundSettings::ShapeType )index == QgsTextBackgroundSettings::ShapeSquare ); - bool isSVG = (( QgsTextBackgroundSettings::ShapeType )index == QgsTextBackgroundSettings::ShapeSVG ); - - showBackgroundPenStyle( isRect ); - showBackgroundRadius( isRect ); - - mShapeSVGPathFrame->setVisible( isSVG ); - // symbology SVG renderer only supports size^2 scaling, so we only use the x size spinbox - mShapeSizeYLabel->setVisible( !isSVG ); - mShapeSizeYSpnBx->setVisible( !isSVG ); - mShapeSizeYDDBtn->setVisible( !isSVG ); - mShapeSizeXLabel->setText( tr( "Size%1" ).arg( !isSVG ? tr( " X" ) : "" ) ); - - // SVG parameter setting doesn't support color's alpha component yet - mShapeFillColorBtn->setAllowAlpha( !isSVG ); - mShapeFillColorBtn->setButtonBackground(); - mShapeBorderColorBtn->setAllowAlpha( !isSVG ); - mShapeBorderColorBtn->setButtonBackground(); - - // configure SVG parameter widgets - mShapeSVGParamsBtn->setVisible( isSVG ); - if ( isSVG ) - { - updateSvgWidgets( mShapeSVGPathLineEdit->text() ); - } - else - { - mShapeFillColorLabel->setEnabled( true ); - mShapeFillColorBtn->setEnabled( true ); - mShapeFillColorDDBtn->setEnabled( true ); - mShapeBorderColorLabel->setEnabled( true ); - mShapeBorderColorBtn->setEnabled( true ); - mShapeBorderColorDDBtn->setEnabled( true ); - mShapeBorderWidthLabel->setEnabled( true ); - mShapeBorderWidthSpnBx->setEnabled( true ); - mShapeBorderWidthDDBtn->setEnabled( true ); - } - // TODO: fix overriding SVG symbol's border width units in QgsSvgCache - // currently broken, fall back to symbol units only - mShapeBorderWidthUnitWidget->setVisible( !isSVG ); - mShapeSVGUnitsLabel->setVisible( isSVG ); - mShapeBorderUnitsDDBtn->setEnabled( !isSVG ); -} - -void QgsLabelingGui::on_mShapeSVGPathLineEdit_textChanged( const QString& text ) -{ - updateSvgWidgets( text ); -} -void QgsLabelingGui::updateLinePlacementOptions() -{ - int numOptionsChecked = ( chkLineAbove->isChecked() ? 1 : 0 ) + - ( chkLineBelow->isChecked() ? 1 : 0 ) + - ( chkLineOn->isChecked() ? 1 : 0 ); - - if ( numOptionsChecked == 1 ) - { - //prevent unchecking last option - chkLineAbove->setEnabled( !chkLineAbove->isChecked() ); - chkLineBelow->setEnabled( !chkLineBelow->isChecked() ); - chkLineOn->setEnabled( !chkLineOn->isChecked() ); - } - else - { - chkLineAbove->setEnabled( true ); - chkLineBelow->setEnabled( true ); - chkLineOn->setEnabled( true ); - } -} - -void QgsLabelingGui::onSubstitutionsChanged( const QgsStringReplacementCollection& substitutions ) -{ - mSubstitutions = substitutions; - emit widgetChanged(); -} - -void QgsLabelingGui::previewScaleChanged( double scale ) -{ - lblFontPreview->setScale( scale ); -} - -void QgsLabelingGui::updateSvgWidgets( const QString& svgPath ) -{ - if ( mShapeSVGPathLineEdit->text() != svgPath ) - { - mShapeSVGPathLineEdit->setText( svgPath ); - } - - QString resolvedPath = QgsSymbolLayerUtils::symbolNameToPath( svgPath ); - bool validSVG = !resolvedPath.isNull(); - - // draw red text for path field if invalid (path can't be resolved) - mShapeSVGPathLineEdit->setStyleSheet( QString( !validSVG ? "QLineEdit{ color: rgb(225, 0, 0); }" : "" ) ); - mShapeSVGPathLineEdit->setToolTip( !validSVG ? tr( "File not found" ) : resolvedPath ); - - QColor fill, outline; - double outlineWidth = 0.0; - bool fillParam = false, outlineParam = false, outlineWidthParam = false; - if ( validSVG ) - { - QgsSvgCache::instance()->containsParams( resolvedPath, fillParam, fill, outlineParam, outline, outlineWidthParam, outlineWidth ); - } - - mShapeSVGParamsBtn->setEnabled( validSVG && ( fillParam || outlineParam || outlineWidthParam ) ); - - mShapeFillColorLabel->setEnabled( validSVG && fillParam ); - mShapeFillColorBtn->setEnabled( validSVG && fillParam ); - mShapeFillColorDDBtn->setEnabled( validSVG && fillParam ); - if ( mLoadSvgParams && validSVG && fillParam ) - mShapeFillColorBtn->setColor( fill ); - - mShapeBorderColorLabel->setEnabled( validSVG && outlineParam ); - mShapeBorderColorBtn->setEnabled( validSVG && outlineParam ); - mShapeBorderColorDDBtn->setEnabled( validSVG && outlineParam ); - if ( mLoadSvgParams && validSVG && outlineParam ) - mShapeBorderColorBtn->setColor( outline ); - - mShapeBorderWidthLabel->setEnabled( validSVG && outlineWidthParam ); - mShapeBorderWidthSpnBx->setEnabled( validSVG && outlineWidthParam ); - mShapeBorderWidthDDBtn->setEnabled( validSVG && outlineWidthParam ); - if ( mLoadSvgParams && validSVG && outlineWidthParam ) - mShapeBorderWidthSpnBx->setValue( outlineWidth ); - - // TODO: fix overriding SVG symbol's border width units in QgsSvgCache - // currently broken, fall back to symbol's - //mShapeBorderWidthUnitWidget->setEnabled( validSVG && outlineWidthParam ); - //mShapeBorderUnitsDDBtn->setEnabled( validSVG && outlineWidthParam ); - mShapeSVGUnitsLabel->setEnabled( validSVG && outlineWidthParam ); -} - -void QgsLabelingGui::on_mShapeSVGSelectorBtn_clicked() -{ - QgsSvgSelectorDialog svgDlg( this ); - svgDlg.setWindowTitle( tr( "Select SVG file" ) ); - svgDlg.svgSelector()->setSvgPath( mShapeSVGPathLineEdit->text().trimmed() ); - - if ( svgDlg.exec() == QDialog::Accepted ) - { - QString svgPath = svgDlg.svgSelector()->currentSvgPath(); - if ( !svgPath.isEmpty() ) - { - mShapeSVGPathLineEdit->setText( svgPath ); - } - } -} - -void QgsLabelingGui::on_mShapeSVGParamsBtn_clicked() -{ - QString svgPath = mShapeSVGPathLineEdit->text(); - mLoadSvgParams = true; - updateSvgWidgets( svgPath ); - mLoadSvgParams = false; -} - -void QgsLabelingGui::on_mShapeRotationCmbBx_currentIndexChanged( int index ) -{ - mShapeRotationDblSpnBx->setEnabled(( QgsTextBackgroundSettings::RotationType )index != QgsTextBackgroundSettings::RotationSync ); - mShapeRotationDDBtn->setEnabled(( QgsTextBackgroundSettings::RotationType )index != QgsTextBackgroundSettings::RotationSync ); -} - -void QgsLabelingGui::on_mPreviewTextEdit_textChanged( const QString & text ) -{ - lblFontPreview->setText( text ); - updatePreview(); -} - -void QgsLabelingGui::on_mPreviewTextBtn_clicked() -{ - mPreviewTextEdit->setText( QString( "Lorem Ipsum" ) ); - updatePreview(); -} - -void QgsLabelingGui::on_mPreviewBackgroundBtn_colorChanged( const QColor &color ) -{ - setPreviewBackground( color ); -} - -void QgsLabelingGui::on_mDirectSymbLeftToolBtn_clicked() -{ - bool gotChar = false; - QChar dirSymb = mCharDlg->selectCharacter( &gotChar, mRefFont, mFontDB.styleString( mRefFont ) ); - - if ( !gotChar ) - return; - - if ( !dirSymb.isNull() ) - mDirectSymbLeftLineEdit->setText( QString( dirSymb ) ); -} - -void QgsLabelingGui::on_mDirectSymbRightToolBtn_clicked() -{ - bool gotChar = false; - QChar dirSymb = mCharDlg->selectCharacter( &gotChar, mRefFont, mFontDB.styleString( mRefFont ) ); - - if ( !gotChar ) - return; - - if ( !dirSymb.isNull() ) - mDirectSymbRightLineEdit->setText( QString( dirSymb ) ); -} - -void QgsLabelingGui::on_mChkNoObstacle_toggled( bool active ) -{ - mPolygonObstacleTypeFrame->setEnabled( active ); - mObstaclePriorityFrame->setEnabled( active ); -} - -void QgsLabelingGui::on_chkLineOrientationDependent_toggled( bool active ) -{ - if ( active ) - { - chkLineAbove->setText( tr( "Left of line" ) ); - chkLineBelow->setText( tr( "Right of line" ) ); - } - else - { - chkLineAbove->setText( tr( "Above line" ) ); - chkLineBelow->setText( tr( "Below line" ) ); - } -} - -void QgsLabelingGui::on_mToolButtonConfigureSubstitutes_clicked() -{ - QgsPanelWidget* panel = QgsPanelWidget::findParentPanel( this ); - if ( panel && panel->dockMode() ) - { - QgsSubstitutionListWidget* widget = new QgsSubstitutionListWidget( panel ); - widget->setPanelTitle( tr( "Substitutions" ) ); - widget->setSubstitutions( mSubstitutions ); - connect( widget, SIGNAL( substitutionsChanged( QgsStringReplacementCollection ) ), this, SLOT( onSubstitutionsChanged( QgsStringReplacementCollection ) ) ); - panel->openPanel( widget ); - return; - } - - QgsSubstitutionListDialog dlg( this ); - dlg.setSubstitutions( mSubstitutions ); - if ( dlg.exec() == QDialog::Accepted ) - { - mSubstitutions = dlg.substitutions(); - emit widgetChanged(); - } -} - -void QgsLabelingGui::showBackgroundRadius( bool show ) -{ - mShapeRadiusLabel->setVisible( show ); - mShapeRadiusXDbSpnBx->setVisible( show ); - - mShapeRadiusYDbSpnBx->setVisible( show ); - - mShapeRadiusUnitWidget->setVisible( show ); - - mShapeRadiusDDBtn->setVisible( show ); - mShapeRadiusUnitsDDBtn->setVisible( show ); -} - -void QgsLabelingGui::showBackgroundPenStyle( bool show ) -{ - mShapePenStyleLabel->setVisible( show ); - mShapePenStyleCmbBx->setVisible( show ); - - mShapePenStyleDDBtn->setVisible( show ); -} - -void QgsLabelingGui::enableDataDefinedAlignment( bool enable ) -{ - mCoordAlignmentFrame->setEnabled( enable ); -} diff --git a/src/app/qgslabelinggui.h b/src/app/qgslabelinggui.h index ce7e2856ac95..789c15062900 100644 --- a/src/app/qgslabelinggui.h +++ b/src/app/qgslabelinggui.h @@ -15,26 +15,18 @@ * * ***************************************************************************/ -#ifndef QgsLabelingGUI_H -#define QgsLabelingGUI_H +#ifndef QGSLABELINGGUI_H +#define QGSLABELINGGUI_H -#include -#include -#include -#include "qgsstringutils.h" #include "qgspallabeling.h" +#include "qgstextformatwidget.h" -class QgsVectorLayer; -class QgsMapCanvas; -class QgsCharacterSelectorDialog; - -class APP_EXPORT QgsLabelingGui : public QWidget, private Ui::QgsLabelingGuiBase, private QgsExpressionContextGenerator +class APP_EXPORT QgsLabelingGui : public QgsTextFormatWidget, private QgsExpressionContextGenerator { Q_OBJECT public: QgsLabelingGui( QgsVectorLayer* layer, QgsMapCanvas* mapCanvas, const QgsPalLayerSettings* settings, QWidget* parent ); - ~QgsLabelingGui(); QgsPalLayerSettings layerSettings(); void writeSettingsToLayer(); @@ -48,111 +40,30 @@ class APP_EXPORT QgsLabelingGui : public QWidget, private Ui::QgsLabelingGuiBase void setLabelMode( LabelMode mode ); - signals: - void widgetChanged(); + void setLayer( QgsMapLayer* layer ); public slots: - void setLayer( QgsMapLayer* layer ); - void setDockMode( bool enabled ); - void connectValueChanged( const QList &widgets, const char* slot ); - void init(); - void collapseSample( bool collapse ); void apply(); - void changeTextColor( const QColor &color ); - void changeBufferColor( const QColor &color ); void updateUi(); - void updatePreview(); - void scrollPreview(); - void updatePlacementWidgets(); - void updateSvgWidgets( const QString& svgPath ); - - void on_mFontSizeSpinBox_valueChanged( double d ); - void on_mFontCapitalsComboBox_currentIndexChanged( int index ); - void on_mFontFamilyCmbBx_currentFontChanged( const QFont& f ); - void on_mFontStyleComboBox_currentIndexChanged( const QString & text ); - void on_mFontUnderlineBtn_toggled( bool ckd ); - void on_mFontStrikethroughBtn_toggled( bool ckd ); - void on_mFontWordSpacingSpinBox_valueChanged( double spacing ); - void on_mFontLetterSpacingSpinBox_valueChanged( double spacing ); - void on_mFontSizeUnitWidget_changed(); - void on_mFontMinPixelSpinBox_valueChanged( int px ); - void on_mFontMaxPixelSpinBox_valueChanged( int px ); - void on_mBufferUnitWidget_changed(); - void on_mCoordXDDBtn_dataDefinedActivated( bool active ); - void on_mCoordYDDBtn_dataDefinedActivated( bool active ); - - void on_mShapeTypeCmbBx_currentIndexChanged( int index ); - void on_mShapeRotationCmbBx_currentIndexChanged( int index ); - void on_mShapeSVGParamsBtn_clicked(); - void on_mShapeSVGSelectorBtn_clicked(); - - void on_mPreviewTextEdit_textChanged( const QString & text ); - void on_mPreviewTextBtn_clicked(); - void on_mPreviewBackgroundBtn_colorChanged( const QColor &color ); - void on_mDirectSymbLeftToolBtn_clicked(); - void on_mDirectSymbRightToolBtn_clicked(); - void on_mChkNoObstacle_toggled( bool active ); - void on_chkLineOrientationDependent_toggled( bool active ); - - void on_mToolButtonConfigureSubstitutes_clicked(); protected: void blockInitSignals( bool block ); - void blockFontChangeSignals( bool blk ); - void setPreviewBackground( const QColor& color ); void syncDefinedCheckboxFrame( QgsDataDefinedButton* ddBtn, QCheckBox* chkBx, QFrame* f ); - void populateFontCapitalsComboBox(); - void populateFontStyleComboBox(); - void populatePlacementMethods(); - void populateFieldNames(); void populateDataDefinedButtons( QgsPalLayerSettings& s ); /** Sets data defined property attribute to map */ void setDataDefinedProperty( const QgsDataDefinedButton* ddBtn, QgsPalLayerSettings::DataDefinedProperties p, QgsPalLayerSettings& lyr ); - void updateFont( const QFont& font ); private: QgsVectorLayer* mLayer; - QgsMapCanvas* mMapCanvas; const QgsPalLayerSettings* mSettings; LabelMode mMode; - QFontDatabase mFontDB; - QgsCharacterSelectorDialog* mCharDlg; - - QButtonGroup* mQuadrantBtnGrp; - QButtonGroup* mDirectSymbBtnGrp; - QButtonGroup* mUpsidedownBtnGrp; - - QButtonGroup* mPlacePointBtnGrp; - QButtonGroup* mPlaceLineBtnGrp; - QButtonGroup* mPlacePolygonBtnGrp; - - // background reference font - QFont mRefFont; - bool mDockMode; - int mPreviewSize; - - int mMinPixelLimit; - - bool mLoadSvgParams; - - QgsStringReplacementCollection mSubstitutions; - - void enableDataDefinedAlignment( bool enable ); QgsExpressionContext createExpressionContext() const override; - private slots: - void optionsStackedWidget_CurrentChanged( int indx ); - void showBackgroundRadius( bool show ); - void showBackgroundPenStyle( bool show ); - void on_mShapeSVGPathLineEdit_textChanged( const QString& text ); - void updateLinePlacementOptions(); - void onSubstitutionsChanged( const QgsStringReplacementCollection& substitutions ); - void previewScaleChanged( double scale ); }; -#endif +#endif // QGSLABELINGGUI_H diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index 2f42b62ba2db..f2c0dc0c176a 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -302,12 +302,14 @@ SET(QGIS_GUI_SRCS qgsshortcutsmanager.cpp qgsslider.cpp qgssublayersdialog.cpp + qgssubstitutionlistwidget.cpp qgssqlcomposerdialog.cpp qgssvgannotationitem.cpp qgstablewidgetbase.cpp qgstabwidget.cpp qgstablewidgetitem.cpp qgstextannotationitem.cpp + qgstextformatwidget.cpp qgstextpreview.cpp qgstrackedvectorlayertools.cpp qgstreewidgetitem.cpp @@ -460,8 +462,10 @@ SET(QGIS_GUI_MOC_HDRS qgsslider.h qgssqlcomposerdialog.h qgssublayersdialog.h + qgssubstitutionlistwidget.h qgstablewidgetbase.h qgstabwidget.h + qgstextformatwidget.h qgstextpreview.h qgstreewidgetitem.h qgsunitselectionwidget.h diff --git a/src/app/qgssubstitutionlistwidget.cpp b/src/gui/qgssubstitutionlistwidget.cpp similarity index 100% rename from src/app/qgssubstitutionlistwidget.cpp rename to src/gui/qgssubstitutionlistwidget.cpp diff --git a/src/app/qgssubstitutionlistwidget.h b/src/gui/qgssubstitutionlistwidget.h similarity index 95% rename from src/app/qgssubstitutionlistwidget.h rename to src/gui/qgssubstitutionlistwidget.h index acd8529a0dc2..155fe7c59242 100644 --- a/src/app/qgssubstitutionlistwidget.h +++ b/src/gui/qgssubstitutionlistwidget.h @@ -24,13 +24,13 @@ #include "qgsstringutils.h" /** \class QgsSubstitutionListWidget - * \ingroup app + * \ingroup gui * A widget which allows users to specify a list of substitutions to apply to a string, with * options for exporting and importing substitution lists. * \note added in QGIS 3.0 * \see QgsSubstitutionListDialog */ -class APP_EXPORT QgsSubstitutionListWidget : public QgsPanelWidget, private Ui::QgsSubstitutionListWidgetBase +class GUI_EXPORT QgsSubstitutionListWidget : public QgsPanelWidget, private Ui::QgsSubstitutionListWidgetBase { Q_OBJECT Q_PROPERTY( QgsStringReplacementCollection substitutions READ substitutions WRITE setSubstitutions NOTIFY substitutionsChanged ) @@ -73,12 +73,13 @@ class APP_EXPORT QgsSubstitutionListWidget : public QgsPanelWidget, private Ui:: }; /** \class QgsSubstitutionListDialog - * \ingroup app + * \ingroup gui * A dialog which allows users to specify a list of substitutions to apply to a string, with * options for exporting and importing substitution lists. + * \note added in QGIS 3.0 * \see QgsSubstitutionListWidget */ -class APP_EXPORT QgsSubstitutionListDialog : public QDialog +class GUI_EXPORT QgsSubstitutionListDialog : public QDialog { Q_OBJECT Q_PROPERTY( QgsStringReplacementCollection substitutions READ substitutions WRITE setSubstitutions ) diff --git a/src/gui/qgstextformatwidget.cpp b/src/gui/qgstextformatwidget.cpp new file mode 100644 index 000000000000..934c7e2a9af8 --- /dev/null +++ b/src/gui/qgstextformatwidget.cpp @@ -0,0 +1,1378 @@ +/*************************************************************************** + qgstextformatwidget.h + --------------------- + begin : June 2009 + copyright : (C) Martin Dobias + email : wonder dot sk at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgstextformatwidget.h" +#include "qgsmapcanvas.h" +#include "qgscharacterselectdialog.h" +#include "qgslogger.h" +#include "qgsfontutils.h" +#include "qgssymbollayerutils.h" +#include "qgssvgcache.h" +#include "qgssvgselectorwidget.h" +#include "qgssubstitutionlistwidget.h" +#include "qgspallabeling.h" // for enum values +#include + +QgsTextFormatWidget::QgsTextFormatWidget( const QgsTextFormat& format, QgsMapCanvas* mapCanvas, QWidget* parent ) + : QWidget( parent ) + , mQuadrantBtnGrp( nullptr ) + , mDirectSymbBtnGrp( nullptr ) + , mUpsidedownBtnGrp( nullptr ) + , mPlacePointBtnGrp( nullptr ) + , mPlaceLineBtnGrp( nullptr ) + , mPlacePolygonBtnGrp( nullptr ) + , mMinPixelLimit( 0 ) + , mWidgetMode( Text ) + , mMapCanvas( mapCanvas ) + , mCharDlg( nullptr ) + , mLoadSvgParams( false ) +{ + initWidget(); + setWidgetMode( Text ); + updateWidgetForFormat( format ); +} + +QgsTextFormatWidget::QgsTextFormatWidget( QgsMapCanvas* mapCanvas, QWidget* parent, Mode mode ) + : QWidget( parent ) + , mQuadrantBtnGrp( nullptr ) + , mDirectSymbBtnGrp( nullptr ) + , mUpsidedownBtnGrp( nullptr ) + , mPlacePointBtnGrp( nullptr ) + , mPlaceLineBtnGrp( nullptr ) + , mPlacePolygonBtnGrp( nullptr ) + , mMinPixelLimit( 0 ) + , mWidgetMode( mode ) + , mMapCanvas( mapCanvas ) + , mCharDlg( nullptr ) + , mLoadSvgParams( false ) +{ + initWidget(); + setWidgetMode( mode ); +} + +void QgsTextFormatWidget::initWidget() +{ + setupUi( this ); + + mPreviewScaleComboBox->setMapCanvas( mMapCanvas ); + mPreviewScaleComboBox->setShowCurrentScaleButton( true ); + connect( mPreviewScaleComboBox, SIGNAL( scaleChanged( double ) ), this, SLOT( previewScaleChanged( double ) ) ); + + Q_FOREACH ( QgsUnitSelectionWidget* unitWidget, findChildren() ) + { + unitWidget->setMapCanvas( mMapCanvas ); + } + mFontSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderMapUnits + << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderPixels ); + mBufferUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShapeSizeUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShapeOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShapeRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits + << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderPercentage ); + mShapeBorderWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShadowOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mShadowRadiusUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mPointOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mLineDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + mRepeatDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels ); + + mFontLineHeightSpinBox->setClearValue( 1.0 ); + mShapeRotationDblSpnBx->setClearValue( 0.0 ); + mShapeOffsetXSpnBx->setClearValue( 0.0 ); + mShapeOffsetYSpnBx->setClearValue( 0.0 ); + mPointOffsetXSpinBox->setClearValue( 0.0 ); + mPointOffsetYSpinBox->setClearValue( 0.0 ); + mPointAngleSpinBox->setClearValue( 0.0 ); + mFontLetterSpacingSpinBox->setClearValue( 0.0 ); + mFontWordSpacingSpinBox->setClearValue( 0.0 ); + mZIndexSpinBox->setClearValue( 0.0 ); + + mObstacleTypeComboBox->addItem( tr( "Over the feature's interior" ), QgsPalLayerSettings::PolygonInterior ); + mObstacleTypeComboBox->addItem( tr( "Over the feature's boundary" ), QgsPalLayerSettings::PolygonBoundary ); + + mOffsetTypeComboBox->addItem( tr( "From point" ), QgsPalLayerSettings::FromPoint ); + mOffsetTypeComboBox->addItem( tr( "From symbol bounds" ), QgsPalLayerSettings::FromSymbolBounds ); + + mCharDlg = new QgsCharacterSelectorDialog( this ); + + mRefFont = lblFontPreview->font(); + + // internal connections + connect( mFontTranspSlider, SIGNAL( valueChanged( int ) ), mFontTranspSpinBox, SLOT( setValue( int ) ) ); + connect( mFontTranspSpinBox, SIGNAL( valueChanged( int ) ), mFontTranspSlider, SLOT( setValue( int ) ) ); + connect( mBufferTranspSlider, SIGNAL( valueChanged( int ) ), mBufferTranspSpinBox, SLOT( setValue( int ) ) ); + connect( mBufferTranspSpinBox, SIGNAL( valueChanged( int ) ), mBufferTranspSlider, SLOT( setValue( int ) ) ); + connect( mShapeTranspSlider, SIGNAL( valueChanged( int ) ), mShapeTranspSpinBox, SLOT( setValue( int ) ) ); + connect( mShapeTranspSpinBox, SIGNAL( valueChanged( int ) ), mShapeTranspSlider, SLOT( setValue( int ) ) ); + connect( mShadowOffsetAngleDial, SIGNAL( valueChanged( int ) ), mShadowOffsetAngleSpnBx, SLOT( setValue( int ) ) ); + connect( mShadowOffsetAngleSpnBx, SIGNAL( valueChanged( int ) ), mShadowOffsetAngleDial, SLOT( setValue( int ) ) ); + connect( mShadowTranspSlider, SIGNAL( valueChanged( int ) ), mShadowTranspSpnBx, SLOT( setValue( int ) ) ); + connect( mShadowTranspSpnBx, SIGNAL( valueChanged( int ) ), mShadowTranspSlider, SLOT( setValue( int ) ) ); + connect( mLimitLabelChkBox, SIGNAL( toggled( bool ) ), mLimitLabelSpinBox, SLOT( setEnabled( bool ) ) ); + connect( mCheckBoxSubstituteText, SIGNAL( toggled( bool ) ), mToolButtonConfigureSubstitutes, SLOT( setEnabled( bool ) ) ); + + //connections to prevent users removing all line placement positions + connect( chkLineAbove, SIGNAL( toggled( bool ) ), this, SLOT( updateLinePlacementOptions() ) ); + connect( chkLineBelow, SIGNAL( toggled( bool ) ), this, SLOT( updateLinePlacementOptions() ) ); + connect( chkLineOn, SIGNAL( toggled( bool ) ), this, SLOT( updateLinePlacementOptions() ) ); + + populateFontCapitalsComboBox(); + + // color buttons + mPreviewBackgroundBtn->setColorDialogTitle( tr( "Select fill color" ) ); + mPreviewBackgroundBtn->setContext( "labelling" ); + mPreviewBackgroundBtn->setColor( QColor( 255, 255, 255 ) ); + btnTextColor->setColorDialogTitle( tr( "Select text color" ) ); + btnTextColor->setContext( "labelling" ); + btnTextColor->setDefaultColor( Qt::black ); + btnBufferColor->setColorDialogTitle( tr( "Select buffer color" ) ); + btnBufferColor->setContext( "labelling" ); + btnBufferColor->setDefaultColor( Qt::white ); + mShapeBorderColorBtn->setColorDialogTitle( tr( "Select border color" ) ); + mShapeBorderColorBtn->setContext( "labelling" ); + mShapeFillColorBtn->setColorDialogTitle( tr( "Select fill color" ) ); + mShapeFillColorBtn->setContext( "labelling" ); + mShadowColorBtn->setColorDialogTitle( tr( "Select shadow color" ) ); + mShadowColorBtn->setContext( "labelling" ); + mShadowColorBtn->setDefaultColor( Qt::black ); + + // set up quadrant offset button group + mQuadrantBtnGrp = new QButtonGroup( this ); + mQuadrantBtnGrp->addButton( mPointOffsetAboveLeft, ( int )QgsPalLayerSettings::QuadrantAboveLeft ); + mQuadrantBtnGrp->addButton( mPointOffsetAbove, ( int )QgsPalLayerSettings::QuadrantAbove ); + mQuadrantBtnGrp->addButton( mPointOffsetAboveRight, ( int )QgsPalLayerSettings::QuadrantAboveRight ); + mQuadrantBtnGrp->addButton( mPointOffsetLeft, ( int )QgsPalLayerSettings::QuadrantLeft ); + mQuadrantBtnGrp->addButton( mPointOffsetOver, ( int )QgsPalLayerSettings::QuadrantOver ); + mQuadrantBtnGrp->addButton( mPointOffsetRight, ( int )QgsPalLayerSettings::QuadrantRight ); + mQuadrantBtnGrp->addButton( mPointOffsetBelowLeft, ( int )QgsPalLayerSettings::QuadrantBelowLeft ); + mQuadrantBtnGrp->addButton( mPointOffsetBelow, ( int )QgsPalLayerSettings::QuadrantBelow ); + mQuadrantBtnGrp->addButton( mPointOffsetBelowRight, ( int )QgsPalLayerSettings::QuadrantBelowRight ); + mQuadrantBtnGrp->setExclusive( true ); + + // setup direction symbol(s) button group + mDirectSymbBtnGrp = new QButtonGroup( this ); + mDirectSymbBtnGrp->addButton( mDirectSymbRadioBtnLR, ( int )QgsPalLayerSettings::SymbolLeftRight ); + mDirectSymbBtnGrp->addButton( mDirectSymbRadioBtnAbove, ( int )QgsPalLayerSettings::SymbolAbove ); + mDirectSymbBtnGrp->addButton( mDirectSymbRadioBtnBelow, ( int )QgsPalLayerSettings::SymbolBelow ); + mDirectSymbBtnGrp->setExclusive( true ); + + // upside-down labels button group + mUpsidedownBtnGrp = new QButtonGroup( this ); + mUpsidedownBtnGrp->addButton( mUpsidedownRadioOff, ( int )QgsPalLayerSettings::Upright ); + mUpsidedownBtnGrp->addButton( mUpsidedownRadioDefined, ( int )QgsPalLayerSettings::ShowDefined ); + mUpsidedownBtnGrp->addButton( mUpsidedownRadioAll, ( int )QgsPalLayerSettings::ShowAll ); + mUpsidedownBtnGrp->setExclusive( true ); + + //mShapeCollisionsChkBx->setVisible( false ); // until implemented + + // post updatePlacementWidgets() connections + connect( chkLineAbove, SIGNAL( toggled( bool ) ), this, SLOT( updatePlacementWidgets() ) ); + connect( chkLineBelow, SIGNAL( toggled( bool ) ), this, SLOT( updatePlacementWidgets() ) ); + + // setup point placement button group + mPlacePointBtnGrp = new QButtonGroup( this ); + mPlacePointBtnGrp->addButton( radPredefinedOrder, ( int )QgsPalLayerSettings::OrderedPositionsAroundPoint ); + mPlacePointBtnGrp->addButton( radAroundPoint, ( int )QgsPalLayerSettings::AroundPoint ); + mPlacePointBtnGrp->addButton( radOverPoint, ( int )QgsPalLayerSettings::OverPoint ); + mPlacePointBtnGrp->setExclusive( true ); + connect( mPlacePointBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePlacementWidgets() ) ); + + // setup line placement button group (assigned enum id currently unused) + mPlaceLineBtnGrp = new QButtonGroup( this ); + mPlaceLineBtnGrp->addButton( radLineParallel, ( int )QgsPalLayerSettings::Line ); + mPlaceLineBtnGrp->addButton( radLineCurved, ( int )QgsPalLayerSettings::Curved ); + mPlaceLineBtnGrp->addButton( radLineHorizontal, ( int )QgsPalLayerSettings::Horizontal ); + mPlaceLineBtnGrp->setExclusive( true ); + connect( mPlaceLineBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePlacementWidgets() ) ); + + // setup polygon placement button group (assigned enum id currently unused) + mPlacePolygonBtnGrp = new QButtonGroup( this ); + mPlacePolygonBtnGrp->addButton( radOverCentroid, ( int )QgsPalLayerSettings::OverPoint ); + mPlacePolygonBtnGrp->addButton( radAroundCentroid, ( int )QgsPalLayerSettings::AroundPoint ); + mPlacePolygonBtnGrp->addButton( radPolygonHorizontal, ( int )QgsPalLayerSettings::Horizontal ); + mPlacePolygonBtnGrp->addButton( radPolygonFree, ( int )QgsPalLayerSettings::Free ); + mPlacePolygonBtnGrp->addButton( radPolygonPerimeter, ( int )QgsPalLayerSettings::Line ); + mPlacePolygonBtnGrp->addButton( radPolygonPerimeterCurved, ( int )QgsPalLayerSettings::PerimeterCurved ); + mPlacePolygonBtnGrp->setExclusive( true ); + connect( mPlacePolygonBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePlacementWidgets() ) ); + + // TODO: is this necessary? maybe just use the data defined-only rotation? + mPointAngleDDBtn->setVisible( false ); + + // Global settings group for groupboxes' saved/retored collapsed state + // maintains state across different dialogs + Q_FOREACH ( QgsCollapsibleGroupBox *grpbox, findChildren() ) + { + grpbox->setSettingGroup( QString( "mAdvLabelingDlg" ) ); + } + + connect( groupBox_mPreview, + SIGNAL( collapsedStateChanged( bool ) ), + this, + SLOT( collapseSample( bool ) ) ); + + // get rid of annoying outer focus rect on Mac + mLabelingOptionsListWidget->setAttribute( Qt::WA_MacShowFocusRect, false ); + + QSettings settings; + + // reset horiz strech of left side of options splitter (set to 1 for previewing in Qt Designer) + QSizePolicy policy( mLabelingOptionsListFrame->sizePolicy() ); + policy.setHorizontalStretch( 0 ); + mLabelingOptionsListFrame->setSizePolicy( policy ); + if ( !settings.contains( QString( "/Windows/Labeling/OptionsSplitState" ) ) ) + { + // set left list widget width on intial showing + QList splitsizes; + splitsizes << 115; + mLabelingOptionsSplitter->setSizes( splitsizes ); + } + + // set up reverse connection from stack to list + connect( mLabelStackedWidget, SIGNAL( currentChanged( int ) ), this, SLOT( optionsStackedWidget_CurrentChanged( int ) ) ); + + // restore dialog, splitters and current tab + mFontPreviewSplitter->restoreState( settings.value( QString( "/Windows/Labeling/FontPreviewSplitState" ) ).toByteArray() ); + mLabelingOptionsSplitter->restoreState( settings.value( QString( "/Windows/Labeling/OptionsSplitState" ) ).toByteArray() ); + + mLabelingOptionsListWidget->setCurrentRow( settings.value( QString( "/Windows/Labeling/Tab" ), 0 ).toInt() ); + + setDockMode( false ); + + + QList widgets; + widgets << btnBufferColor + << btnTextColor + << chkLabelPerFeaturePart + << chkLineAbove + << chkLineBelow + << chkLineOn + << chkLineOrientationDependent + << chkMergeLines + << chkPreserveRotation + << comboBlendMode + << comboBufferBlendMode + << mAlwaysShowDDBtn + << mBufferBlendModeDDBtn + << mBufferColorDDBtn + << mBufferDrawChkBx + << mBufferDrawDDBtn + << mBufferJoinStyleComboBox + << mBufferJoinStyleDDBtn + << mBufferSizeDDBtn + << mBufferTranspDDBtn + << mBufferTranspFillChbx + << mBufferTranspSpinBox + << mBufferUnitsDDBtn + << mCentroidDDBtn + << mCentroidInsideCheckBox + << mChkNoObstacle + << mCoordAlignmentHDDBtn + << mCoordAlignmentVDDBtn + << mCoordRotationDDBtn + << mCoordXDDBtn + << mCoordYDDBtn + << mDirectSymbChkBx + << mDirectSymbDDBtn + << mDirectSymbLeftDDBtn + << mDirectSymbLeftLineEdit + << mDirectSymbPlacementDDBtn + << mDirectSymbRevChkBx + << mDirectSymbRevDDBtn + << mDirectSymbRightDDBtn + << mDirectSymbRightLineEdit + << mFitInsidePolygonCheckBox + << mFontBlendModeDDBtn + << mFontBoldDDBtn + << mFontCapitalsComboBox + << mFontCaseDDBtn + << mFontColorDDBtn + << mFontDDBtn + << mFontItalicDDBtn + << mFontLetterSpacingDDBtn + << mFontLetterSpacingSpinBox + << mFontLimitPixelChkBox + << mFontLimitPixelDDBtn + << mFontLineHeightDDBtn + << mFontLineHeightSpinBox + << mFontMaxPixelDDBtn + << mFontMaxPixelSpinBox + << mFontMinPixelDDBtn + << mFontMinPixelSpinBox + << mFontMultiLineAlignComboBox + << mFontMultiLineAlignDDBtn + << mFontSizeDDBtn + << mFontSizeSpinBox + << mFontStrikeoutDDBtn + << mFontStyleComboBox + << mFontStyleDDBtn + << mFontTranspDDBtn + << mFontTranspSpinBox + << mFontUnderlineDDBtn + << mFontUnitsDDBtn + << mFontWordSpacingDDBtn + << mFontWordSpacingSpinBox + << mFormatNumChkBx + << mFormatNumDDBtn + << mFormatNumDecimalsDDBtn + << mFormatNumDecimalsSpnBx + << mFormatNumPlusSignChkBx + << mFormatNumPlusSignDDBtn + << mIsObstacleDDBtn + << mLimitLabelChkBox + << mLimitLabelSpinBox + << mLineDistanceDDBtn + << mLineDistanceSpnBx + << mLineDistanceUnitDDBtn + << mLineDistanceUnitWidget + << mMaxCharAngleDDBtn + << mMaxCharAngleInDSpinBox + << mMaxCharAngleOutDSpinBox + << mMinSizeSpinBox + << mObstacleFactorDDBtn + << mObstacleFactorSlider + << mObstacleTypeComboBox + << mOffsetTypeComboBox + << mPalShowAllLabelsForLayerChkBx + << mPointAngleDDBtn + << mPointAngleSpinBox + << mPointOffsetDDBtn + << mPointOffsetUnitsDDBtn + << mPointOffsetUnitWidget + << mPointOffsetXSpinBox + << mPointOffsetYSpinBox + << mPointPositionOrderDDBtn + << mPointQuadOffsetDDBtn + << mPreviewBackgroundBtn + << mPreviewTextEdit + << mPriorityDDBtn + << mPrioritySlider + << mRepeatDistanceDDBtn + << mRepeatDistanceSpinBox + << mRepeatDistanceUnitDDBtn + << mRepeatDistanceUnitWidget + << mScaleBasedVisibilityChkBx + << mScaleBasedVisibilityDDBtn + << mScaleBasedVisibilityMaxDDBtn + << mScaleBasedVisibilityMaxSpnBx + << mScaleBasedVisibilityMinDDBtn + << mScaleBasedVisibilityMinSpnBx + << mShadowBlendCmbBx + << mShadowBlendDDBtn + << mShadowColorBtn + << mShadowColorDDBtn + << mShadowDrawChkBx + << mShadowDrawDDBtn + << mShadowOffsetAngleDDBtn + << mShadowOffsetAngleSpnBx + << mShadowOffsetDDBtn + << mShadowOffsetGlobalChkBx + << mShadowOffsetSpnBx + << mShadowOffsetUnitsDDBtn + << mShadowOffsetUnitWidget + << mShadowRadiusAlphaChkBx + << mShadowRadiusDDBtn + << mShadowRadiusDblSpnBx + << mShadowRadiusUnitsDDBtn + << mShadowRadiusUnitWidget + << mShadowScaleDDBtn + << mShadowScaleSpnBx + << mShadowTranspDDBtn + << mShadowTranspSpnBx + << mShadowUnderCmbBx + << mShadowUnderDDBtn + << mShapeBlendCmbBx + << mShapeBlendModeDDBtn + << mShapeBorderColorBtn + << mShapeBorderColorDDBtn + << mShapeBorderUnitsDDBtn + << mShapeBorderWidthDDBtn + << mShapeBorderWidthSpnBx + << mShapeBorderWidthUnitWidget + << mShapeDrawChkBx + << mShapeDrawDDBtn + << mShapeFillColorBtn + << mShapeFillColorDDBtn + << mShapeOffsetDDBtn + << mShapeOffsetUnitsDDBtn + << mShapeOffsetXSpnBx + << mShapeOffsetYSpnBx + << mShapeOffsetUnitWidget + << mShapePenStyleCmbBx + << mShapePenStyleDDBtn + << mShapeRadiusDDBtn + << mShapeRadiusUnitsDDBtn + << mShapeRadiusXDbSpnBx + << mShapeRadiusYDbSpnBx + << mShapeRotationCmbBx + << mShapeRotationDDBtn + << mShapeRotationDblSpnBx + << mShapeRotationTypeDDBtn + << mShapeRadiusUnitWidget + << mShapeSVGPathDDBtn + << mShapeSVGPathLineEdit + << mShapeSizeCmbBx + << mShapeSizeTypeDDBtn + << mShapeSizeUnitsDDBtn + << mShapeSizeUnitWidget + << mShapeSizeXDDBtn + << mShapeSizeXSpnBx + << mShapeSizeYDDBtn + << mShapeSizeYSpnBx + << mShapeTranspDDBtn + << mShapeTranspSpinBox + << mShapeTypeCmbBx + << mShapeTypeDDBtn + << mShowLabelDDBtn + << mWrapCharDDBtn + << mZIndexDDBtn + << mZIndexSpinBox + << spinBufferSize + << wrapCharacterEdit + << mCentroidRadioVisible + << mCentroidRadioWhole + << mDirectSymbRadioBtnAbove + << mDirectSymbRadioBtnBelow + << mDirectSymbRadioBtnLR + << mUpsidedownRadioAll + << mUpsidedownRadioDefined + << mUpsidedownRadioOff + << radAroundCentroid + << radAroundPoint + << radLineCurved + << radLineHorizontal + << radLineParallel + << radOverCentroid + << radOverPoint + << radPolygonFree + << radPolygonHorizontal + << radPolygonPerimeter + << radPolygonPerimeterCurved + << radPredefinedOrder + << mFieldExpressionWidget + << mCheckBoxSubstituteText; + connectValueChanged( widgets, SLOT( updatePreview() ) ); + + connect( mQuadrantBtnGrp, SIGNAL( buttonClicked( int ) ), this, SLOT( updatePreview() ) ); + + // set correct initial tab to match displayed setting page + whileBlocking( mOptionsTab )->setCurrentIndex( mLabelStackedWidget->currentIndex() ); + + if ( mMapCanvas ) + { + lblFontPreview->setMapUnits( mMapCanvas->mapSettings().mapUnits() ); + mPreviewScaleComboBox->setScale( 1.0 / mMapCanvas->mapSettings().scale() ); + } +} + +void QgsTextFormatWidget::setWidgetMode( QgsTextFormatWidget::Mode mode ) +{ + mWidgetMode = mode; + switch ( mode ) + { + case Labeling: + toggleDDButtons( true ); + break; + + case Text: + toggleDDButtons( false ); + delete mLabelingOptionsListWidget->takeItem( 6 ); + delete mLabelingOptionsListWidget->takeItem( 5 ); + mOptionsTab->removeTab( 6 ); + mOptionsTab->removeTab( 5 ); + + frameLabelWith->hide(); + mDirectSymbolsFrame->hide(); + mFormatNumFrame->hide(); + mFormatNumChkBx->hide(); + mFormatNumDDBtn->hide(); + mSubstitutionsFrame->hide(); + mFontBoldBtn->hide(); + mFontItalicBtn->hide(); + + break; + } +} + +void QgsTextFormatWidget::toggleDDButtons( bool visible ) +{ + Q_FOREACH ( QgsDataDefinedButton* button, findChildren< QgsDataDefinedButton* >() ) + { + button->setVisible( visible ); + } +} + +void QgsTextFormatWidget::setDockMode( bool enabled ) +{ + mOptionsTab->setVisible( enabled ); + mOptionsTab->setTabToolTip( 0, tr( "Text" ) ); + mOptionsTab->setTabToolTip( 1, tr( "Formatting" ) ); + mOptionsTab->setTabToolTip( 2, tr( "Buffer" ) ); + mOptionsTab->setTabToolTip( 3, tr( "Background" ) ); + mOptionsTab->setTabToolTip( 4, tr( "Shadow" ) ); + mOptionsTab->setTabToolTip( 5, tr( "Placement" ) ); + mOptionsTab->setTabToolTip( 6, tr( "Rendering" ) ); + + mLabelingOptionsListFrame->setVisible( !enabled ); + groupBox_mPreview->setVisible( !enabled ); + mDockMode = enabled; +} + +void QgsTextFormatWidget::connectValueChanged( const QList& widgets, const char *slot ) +{ + Q_FOREACH ( QWidget* widget, widgets ) + { + if ( QgsDataDefinedButton* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( dataDefinedActivated( bool ) ), this, slot ); + connect( w, SIGNAL( dataDefinedChanged( QString ) ), this, slot ); + } + else if ( QgsFieldExpressionWidget* w = qobject_cast< QgsFieldExpressionWidget*>( widget ) ) + { + connect( w, SIGNAL( fieldChanged( QString ) ), this, slot ); + } + else if ( QgsUnitSelectionWidget* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( changed() ), this, slot ); + } + else if ( QComboBox* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( currentIndexChanged( int ) ), this, slot ); + } + else if ( QSpinBox* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( valueChanged( int ) ), this, slot ); + } + else if ( QDoubleSpinBox* w = qobject_cast( widget ) ) + { + connect( w , SIGNAL( valueChanged( double ) ), this, slot ); + } + else if ( QgsColorButton* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( colorChanged( QColor ) ), this, slot ); + } + else if ( QCheckBox* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( toggled( bool ) ), this, slot ); + } + else if ( QRadioButton* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( toggled( bool ) ), this, slot ); + } + else if ( QLineEdit* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( textEdited( QString ) ), this, slot ); + } + else if ( QSlider* w = qobject_cast( widget ) ) + { + connect( w, SIGNAL( valueChanged( int ) ), this, slot ); + } + else + { + QgsLogger::warning( QString( "Could not create connection for widget %1" ).arg( widget->objectName() ) ); + } + } +} + +void QgsTextFormatWidget::updateWidgetForFormat( const QgsTextFormat& format ) +{ + QgsTextBufferSettings buffer = format.buffer(); + QgsTextBackgroundSettings background = format.background(); + QgsTextShadowSettings shadow = format.shadow(); + + // buffer + mBufferDrawChkBx->setChecked( buffer.enabled() ); + spinBufferSize->setValue( buffer.size() ); + mBufferUnitWidget->setUnit( buffer.sizeUnit() ); + mBufferUnitWidget->setMapUnitScale( buffer.sizeMapUnitScale() ); + btnBufferColor->setColor( buffer.color() ); + mBufferTranspSpinBox->setValue( 100 - 100 * buffer.opacity() ); + mBufferJoinStyleComboBox->setPenJoinStyle( buffer.joinStyle() ); + mBufferTranspFillChbx->setChecked( buffer.fillBufferInterior() ); + comboBufferBlendMode->setBlendMode( buffer.blendMode() ); + + + mFontSizeUnitWidget->setUnit( format.sizeUnit() ); + mFontSizeUnitWidget->setMapUnitScale( format.sizeMapUnitScale() ); + mRefFont = format.font(); + mFontSizeSpinBox->setValue( format.size() ); + btnTextColor->setColor( format.color() ); + mFontTranspSpinBox->setValue( 100 - 100 * format.opacity() ); + comboBlendMode->setBlendMode( format.blendMode() ); + + mFontWordSpacingSpinBox->setValue( format.font().wordSpacing() ); + mFontLetterSpacingSpinBox->setValue( format.font().letterSpacing() ); + + QgsFontUtils::updateFontViaStyle( mRefFont, format.namedStyle() ); + updateFont( mRefFont ); + + // show 'font not found' if substitution has occurred (should come after updateFont()) + mFontMissingLabel->setVisible( !format.fontFound() ); + if ( !format.fontFound() ) + { + QString missingTxt = tr( "%1 not found. Default substituted." ); + QString txtPrepend = tr( "Chosen font" ); + if ( !format.resolvedFontFamily().isEmpty() ) + { + txtPrepend = QString( "'%1'" ).arg( format.resolvedFontFamily() ); + } + mFontMissingLabel->setText( missingTxt.arg( txtPrepend ) ); + + // ensure user is sent to 'Text style' section to see notice + mLabelingOptionsListWidget->setCurrentRow( 0 ); + } + mFontLineHeightSpinBox->setValue( format.lineHeight() ); + + // shape background + mShapeDrawChkBx->setChecked( background.enabled() ); + mShapeTypeCmbBx->blockSignals( true ); + mShapeTypeCmbBx->setCurrentIndex( background.type() ); + mShapeTypeCmbBx->blockSignals( false ); + mShapeSVGPathLineEdit->setText( background.svgFile() ); + + mShapeSizeCmbBx->setCurrentIndex( background.sizeType() ); + mShapeSizeXSpnBx->setValue( background.size().width() ); + mShapeSizeYSpnBx->setValue( background.size().height() ); + mShapeSizeUnitWidget->setUnit( background.sizeUnit() ); + mShapeSizeUnitWidget->setMapUnitScale( background.sizeMapUnitScale() ); + mShapeRotationCmbBx->setCurrentIndex( background.rotationType() ); + mShapeRotationDblSpnBx->setEnabled( background.rotationType() != QgsTextBackgroundSettings::RotationSync ); + mShapeRotationDDBtn->setEnabled( background.rotationType() != QgsTextBackgroundSettings::RotationSync ); + mShapeRotationDblSpnBx->setValue( background.rotation() ); + mShapeOffsetXSpnBx->setValue( background.offset().x() ); + mShapeOffsetYSpnBx->setValue( background.offset().y() ); + mShapeOffsetUnitWidget->setUnit( background.offsetUnit() ); + mShapeOffsetUnitWidget->setMapUnitScale( background.offsetMapUnitScale() ); + mShapeRadiusXDbSpnBx->setValue( background.radii().width() ); + mShapeRadiusYDbSpnBx->setValue( background.radii().height() ); + mShapeRadiusUnitWidget->setUnit( background.radiiUnit() ); + mShapeRadiusUnitWidget->setMapUnitScale( background.radiiMapUnitScale() ); + + mShapeFillColorBtn->setColor( background.fillColor() ); + mShapeBorderColorBtn->setColor( background.borderColor() ); + mShapeBorderWidthSpnBx->setValue( background.borderWidth() ); + mShapeBorderWidthUnitWidget->setUnit( background.borderWidthUnit() ); + mShapeBorderWidthUnitWidget->setMapUnitScale( background.borderWidthMapUnitScale() ); + mShapePenStyleCmbBx->setPenJoinStyle( background.joinStyle() ); + + mShapeTranspSpinBox->setValue( 100 - background.opacity() * 100.0 ); + mShapeBlendCmbBx->setBlendMode( background.blendMode() ); + + mLoadSvgParams = false; + on_mShapeTypeCmbBx_currentIndexChanged( background.type() ); // force update of shape background gui + + // drop shadow + mShadowDrawChkBx->setChecked( shadow.enabled() ); + mShadowUnderCmbBx->setCurrentIndex( shadow.shadowPlacement() ); + mShadowOffsetAngleSpnBx->setValue( shadow.offsetAngle() ); + mShadowOffsetSpnBx->setValue( shadow.offsetDistance() ); + mShadowOffsetUnitWidget->setUnit( shadow.offsetUnit() ); + mShadowOffsetUnitWidget->setMapUnitScale( shadow.offsetMapUnitScale() ); + mShadowOffsetGlobalChkBx->setChecked( shadow.offsetGlobal() ); + + mShadowRadiusDblSpnBx->setValue( shadow.blurRadius() ); + mShadowRadiusUnitWidget->setUnit( shadow.blurRadiusUnit() ); + mShadowRadiusUnitWidget->setMapUnitScale( shadow.blurRadiusMapUnitScale() ); + mShadowRadiusAlphaChkBx->setChecked( shadow.blurAlphaOnly() ); + mShadowTranspSpnBx->setValue( 100 - shadow.opacity() * 100.0 ); + mShadowScaleSpnBx->setValue( shadow.scale() ); + + mShadowColorBtn->setColor( shadow.color() ); + mShadowBlendCmbBx->setBlendMode( shadow.blendMode() ); + +} + +QgsTextFormatWidget::~QgsTextFormatWidget() +{ + QSettings settings; + settings.setValue( QString( "/Windows/Labeling/FontPreviewSplitState" ), mFontPreviewSplitter->saveState() ); + settings.setValue( QString( "/Windows/Labeling/OptionsSplitState" ), mLabelingOptionsSplitter->saveState() ); + settings.setValue( QString( "/Windows/Labeling/Tab" ), mLabelingOptionsListWidget->currentRow() ); +} + +QgsTextFormat QgsTextFormatWidget::format() const +{ + QgsTextFormat format; + format.setColor( btnTextColor->color() ); + format.setFont( mRefFont ); + format.setSize( mFontSizeSpinBox->value() ); + format.setNamedStyle( mFontStyleComboBox->currentText() ); + format.setOpacity( 1.0 - mFontTranspSpinBox->value() / 100.0 ); + format.setBlendMode( comboBlendMode->blendMode() ); + format.setSizeUnit( mFontSizeUnitWidget->unit() ); + format.setSizeMapUnitScale( mFontSizeUnitWidget->getMapUnitScale() ); + format.setLineHeight( mFontLineHeightSpinBox->value() ); + + // buffer + QgsTextBufferSettings buffer; + buffer.setEnabled( mBufferDrawChkBx->isChecked() ); + buffer.setSize( spinBufferSize->value() ); + buffer.setColor( btnBufferColor->color() ); + buffer.setOpacity( 1.0 - mBufferTranspSpinBox->value() / 100.0 ); + buffer.setSizeUnit( mBufferUnitWidget->unit() ); + buffer.setSizeMapUnitScale( mBufferUnitWidget->getMapUnitScale() ); + buffer.setJoinStyle( mBufferJoinStyleComboBox->penJoinStyle() ); + buffer.setFillBufferInterior( mBufferTranspFillChbx->isChecked() ); + buffer.setBlendMode( comboBufferBlendMode->blendMode() ); + format.setBuffer( buffer ); + + // shape background + QgsTextBackgroundSettings background; + background.setEnabled( mShapeDrawChkBx->isChecked() ); + background.setType(( QgsTextBackgroundSettings::ShapeType )mShapeTypeCmbBx->currentIndex() ); + background.setSvgFile( mShapeSVGPathLineEdit->text() ); + background.setSizeType(( QgsTextBackgroundSettings::SizeType )mShapeSizeCmbBx->currentIndex() ); + background.setSize( QSizeF( mShapeSizeXSpnBx->value(), mShapeSizeYSpnBx->value() ) ); + background.setSizeUnit( mShapeSizeUnitWidget->unit() ); + background.setSizeMapUnitScale( mShapeSizeUnitWidget->getMapUnitScale() ); + background.setRotationType(( QgsTextBackgroundSettings::RotationType )( mShapeRotationCmbBx->currentIndex() ) ); + background.setRotation( mShapeRotationDblSpnBx->value() ); + background.setOffset( QPointF( mShapeOffsetXSpnBx->value(), mShapeOffsetYSpnBx->value() ) ); + background.setOffsetUnit( mShapeOffsetUnitWidget->unit() ); + background.setOffsetMapUnitScale( mShapeOffsetUnitWidget->getMapUnitScale() ); + background.setRadii( QSizeF( mShapeRadiusXDbSpnBx->value(), mShapeRadiusYDbSpnBx->value() ) ); + background.setRadiiUnit( mShapeRadiusUnitWidget->unit() ); + background.setRadiiMapUnitScale( mShapeRadiusUnitWidget->getMapUnitScale() ); + + background.setFillColor( mShapeFillColorBtn->color() ); + background.setBorderColor( mShapeBorderColorBtn->color() ); + background.setBorderWidth( mShapeBorderWidthSpnBx->value() ); + background.setBorderWidthUnit( mShapeBorderWidthUnitWidget->unit() ); + background.setBorderWidthMapUnitScale( mShapeBorderWidthUnitWidget->getMapUnitScale() ); + background.setJoinStyle( mShapePenStyleCmbBx->penJoinStyle() ); + background.setOpacity( 1.0 - mShapeTranspSpinBox->value() / 100.0 ); + background.setBlendMode( mShapeBlendCmbBx->blendMode() ); + format.setBackground( background ); + + // drop shadow + QgsTextShadowSettings shadow; + shadow.setEnabled( mShadowDrawChkBx->isChecked() ); + shadow.setShadowPlacement(( QgsTextShadowSettings::ShadowPlacement )mShadowUnderCmbBx->currentIndex() ); + shadow.setOffsetAngle( mShadowOffsetAngleSpnBx->value() ); + shadow.setOffsetDistance( mShadowOffsetSpnBx->value() ); + shadow.setOffsetUnit( mShadowOffsetUnitWidget->unit() ); + shadow.setOffsetMapUnitScale( mShadowOffsetUnitWidget->getMapUnitScale() ); + shadow.setOffsetGlobal( mShadowOffsetGlobalChkBx->isChecked() ); + shadow.setBlurRadius( mShadowRadiusDblSpnBx->value() ); + shadow.setBlurRadiusUnit( mShadowRadiusUnitWidget->unit() ); + shadow.setBlurRadiusMapUnitScale( mShadowRadiusUnitWidget->getMapUnitScale() ); + shadow.setBlurAlphaOnly( mShadowRadiusAlphaChkBx->isChecked() ); + shadow.setOpacity( 1.0 - mShadowTranspSpnBx->value() / 100.0 ); + shadow.setScale( mShadowScaleSpnBx->value() ); + shadow.setColor( mShadowColorBtn->color() ); + shadow.setBlendMode( mShadowBlendCmbBx->blendMode() ); + format.setShadow( shadow ); + + return format; +} + +void QgsTextFormatWidget::optionsStackedWidget_CurrentChanged( int indx ) +{ + mLabelingOptionsListWidget->blockSignals( true ); + mLabelingOptionsListWidget->setCurrentRow( indx ); + mLabelingOptionsListWidget->blockSignals( false ); +} + +void QgsTextFormatWidget::collapseSample( bool collapse ) +{ + if ( collapse ) + { + QList splitSizes = mFontPreviewSplitter->sizes(); + if ( splitSizes[0] > groupBox_mPreview->height() ) + { + int delta = splitSizes[0] - groupBox_mPreview->height(); + splitSizes[0] -= delta; + splitSizes[1] += delta; + mFontPreviewSplitter->setSizes( splitSizes ); + } + } +} + +void QgsTextFormatWidget::changeTextColor( const QColor &color ) +{ + Q_UNUSED( color ) + updatePreview(); +} + +void QgsTextFormatWidget::updateFont( const QFont& font ) +{ + // update background reference font + if ( font != mRefFont ) + { + mRefFont = font; + } + + // test if font is actually available + // NOTE: QgsFontUtils::fontMatchOnSystem may fail here, just crosscheck family + mFontMissingLabel->setVisible( !QgsFontUtils::fontFamilyMatchOnSystem( mRefFont.family() ) ); + + mDirectSymbLeftLineEdit->setFont( mRefFont ); + mDirectSymbRightLineEdit->setFont( mRefFont ); + + blockFontChangeSignals( true ); + mFontFamilyCmbBx->setCurrentFont( mRefFont ); + populateFontStyleComboBox(); + int idx = mFontCapitalsComboBox->findData( QVariant(( unsigned int ) mRefFont.capitalization() ) ); + mFontCapitalsComboBox->setCurrentIndex( idx == -1 ? 0 : idx ); + mFontUnderlineBtn->setChecked( mRefFont.underline() ); + mFontStrikethroughBtn->setChecked( mRefFont.strikeOut() ); + blockFontChangeSignals( false ); + + // update font name with font face +// font.setPixelSize( 24 ); + + updatePreview(); +} + +void QgsTextFormatWidget::blockFontChangeSignals( bool blk ) +{ + mFontFamilyCmbBx->blockSignals( blk ); + mFontStyleComboBox->blockSignals( blk ); + mFontCapitalsComboBox->blockSignals( blk ); + mFontUnderlineBtn->blockSignals( blk ); + mFontStrikethroughBtn->blockSignals( blk ); + mFontWordSpacingSpinBox->blockSignals( blk ); + mFontLetterSpacingSpinBox->blockSignals( blk ); +} + +void QgsTextFormatWidget::updatePreview() +{ + // In dock mode we don't have a preview we + // just let stuff know we have changed because + // there might be live updates connected. + if ( mDockMode ) + { + emit widgetChanged(); + return; + } + + scrollPreview(); + lblFontPreview->setFormat( format() ); +} + +void QgsTextFormatWidget::scrollPreview() +{ + scrollArea_mPreview->ensureVisible( 0, 0, 0, 0 ); +} + +void QgsTextFormatWidget::setPreviewBackground( const QColor& color ) +{ + scrollArea_mPreview->widget()->setStyleSheet( QString( "background: rgb(%1, %2, %3);" ).arg( QString::number( color.red() ), + QString::number( color.green() ), + QString::number( color.blue() ) ) ); +} + +void QgsTextFormatWidget::changeBufferColor( const QColor &color ) +{ + Q_UNUSED( color ) + updatePreview(); +} + +void QgsTextFormatWidget::updatePlacementWidgets() +{ + QWidget* curWdgt = stackedPlacement->currentWidget(); + + bool showLineFrame = false; + bool showCentroidFrame = false; + bool showQuadrantFrame = false; + bool showFixedQuadrantFrame = false; + bool showPlacementPriorityFrame = false; + bool showOffsetTypeFrame = false; + bool showOffsetFrame = false; + bool showDistanceFrame = false; + bool showRotationFrame = false; + bool showMaxCharAngleFrame = false; + + bool enableMultiLinesFrame = true; + + if (( curWdgt == pagePoint && radAroundPoint->isChecked() ) + || ( curWdgt == pagePolygon && radAroundCentroid->isChecked() ) ) + { + showCentroidFrame = ( curWdgt == pagePolygon && radAroundCentroid->isChecked() ); + showDistanceFrame = true; + //showRotationFrame = true; // TODO: uncomment when supported + if ( curWdgt == pagePoint ) + { + showQuadrantFrame = true; + } + } + else if (( curWdgt == pagePoint && radOverPoint->isChecked() ) + || ( curWdgt == pagePolygon && radOverCentroid->isChecked() ) ) + { + showCentroidFrame = ( curWdgt == pagePolygon && radOverCentroid->isChecked() ); + showQuadrantFrame = true; + showFixedQuadrantFrame = true; + showOffsetFrame = true; + showRotationFrame = true; + } + else if ( curWdgt == pagePoint && radPredefinedOrder->isChecked() ) + { + showDistanceFrame = true; + showPlacementPriorityFrame = true; + showOffsetTypeFrame = true; + } + else if (( curWdgt == pageLine && radLineParallel->isChecked() ) + || ( curWdgt == pagePolygon && radPolygonPerimeter->isChecked() ) + || ( curWdgt == pageLine && radLineCurved->isChecked() ) + || ( curWdgt == pagePolygon && radPolygonPerimeterCurved->isChecked() ) ) + { + showLineFrame = true; + showDistanceFrame = true; + //showRotationFrame = true; // TODO: uncomment when supported + + bool offline = chkLineAbove->isChecked() || chkLineBelow->isChecked(); + chkLineOrientationDependent->setEnabled( offline ); + mPlacementDistanceFrame->setEnabled( offline ); + + bool isCurved = ( curWdgt == pageLine && radLineCurved->isChecked() ) + || ( curWdgt == pagePolygon && radPolygonPerimeterCurved->isChecked() ); + showMaxCharAngleFrame = isCurved; + // TODO: enable mMultiLinesFrame when supported for curved labels + enableMultiLinesFrame = !isCurved; + } + + mPlacementLineFrame->setVisible( showLineFrame ); + mPlacementCentroidFrame->setVisible( showCentroidFrame ); + mPlacementQuadrantFrame->setVisible( showQuadrantFrame ); + mPlacementFixedQuadrantFrame->setVisible( showFixedQuadrantFrame ); + mPlacementCartographicFrame->setVisible( showPlacementPriorityFrame ); + mPlacementOffsetFrame->setVisible( showOffsetFrame ); + mPlacementDistanceFrame->setVisible( showDistanceFrame ); + mPlacementOffsetTypeFrame->setVisible( showOffsetTypeFrame ); + mPlacementRotationFrame->setVisible( showRotationFrame ); + mPlacementRepeatDistanceFrame->setVisible( curWdgt == pageLine || ( curWdgt == pagePolygon && + ( radPolygonPerimeter->isChecked() || radPolygonPerimeterCurved->isChecked() ) ) ); + mPlacementMaxCharAngleFrame->setVisible( showMaxCharAngleFrame ); + + mMultiLinesFrame->setEnabled( enableMultiLinesFrame ); +} + +void QgsTextFormatWidget::populateFontCapitalsComboBox() +{ + mFontCapitalsComboBox->addItem( tr( "No change" ), QVariant( 0 ) ); + mFontCapitalsComboBox->addItem( tr( "All uppercase" ), QVariant( 1 ) ); + mFontCapitalsComboBox->addItem( tr( "All lowercase" ), QVariant( 2 ) ); + // Small caps doesn't work right with QPainterPath::addText() + // https://bugreports.qt-project.org/browse/QTBUG-13965 +// mFontCapitalsComboBox->addItem( tr( "Small caps" ), QVariant( 3 ) ); + mFontCapitalsComboBox->addItem( tr( "Capitalize first letter" ), QVariant( 4 ) ); +} + +void QgsTextFormatWidget::populateFontStyleComboBox() +{ + mFontStyleComboBox->clear(); + Q_FOREACH ( const QString &style, mFontDB.styles( mRefFont.family() ) ) + { + mFontStyleComboBox->addItem( style ); + } + + int curIndx = 0; + int stylIndx = mFontStyleComboBox->findText( mFontDB.styleString( mRefFont ) ); + if ( stylIndx > -1 ) + { + curIndx = stylIndx; + } + + mFontStyleComboBox->setCurrentIndex( curIndx ); +} + +void QgsTextFormatWidget::on_mFontSizeSpinBox_valueChanged( double d ) +{ + mRefFont.setPointSizeF( d ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontCapitalsComboBox_currentIndexChanged( int index ) +{ + int capitalsindex = mFontCapitalsComboBox->itemData( index ).toUInt(); + mRefFont.setCapitalization(( QFont::Capitalization ) capitalsindex ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontFamilyCmbBx_currentFontChanged( const QFont& f ) +{ + mRefFont.setFamily( f.family() ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontStyleComboBox_currentIndexChanged( const QString & text ) +{ + QgsFontUtils::updateFontViaStyle( mRefFont, text ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontUnderlineBtn_toggled( bool ckd ) +{ + mRefFont.setUnderline( ckd ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontStrikethroughBtn_toggled( bool ckd ) +{ + mRefFont.setStrikeOut( ckd ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontWordSpacingSpinBox_valueChanged( double spacing ) +{ + mRefFont.setWordSpacing( spacing ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontLetterSpacingSpinBox_valueChanged( double spacing ) +{ + mRefFont.setLetterSpacing( QFont::AbsoluteSpacing, spacing ); + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontSizeUnitWidget_changed() +{ + // disable pixel size limiting for labels defined in points + if ( mFontSizeUnitWidget->unit() != QgsUnitTypes::RenderMapUnits ) + { + mFontLimitPixelChkBox->setChecked( false ); + } + else if ( mMinPixelLimit == 0 ) + { + // initial minimum trigger value set, turn on pixel size limiting by default + // for labels defined in map units (ignored after first settings save) + mFontLimitPixelChkBox->setChecked( true ); + } + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mFontMinPixelSpinBox_valueChanged( int px ) +{ + // ensure max font pixel size for map unit labels can't be lower than min + mFontMaxPixelSpinBox->setMinimum( px ); + mFontMaxPixelSpinBox->update(); +} + +void QgsTextFormatWidget::on_mFontMaxPixelSpinBox_valueChanged( int px ) +{ + // ensure max font pixel size for map unit labels can't be lower than min + if ( px < mFontMinPixelSpinBox->value() ) + { + mFontMaxPixelSpinBox->blockSignals( true ); + mFontMaxPixelSpinBox->setValue( mFontMinPixelSpinBox->value() ); + mFontMaxPixelSpinBox->blockSignals( false ); + } + mFontMaxPixelSpinBox->setMinimum( mFontMinPixelSpinBox->value() ); +} + +void QgsTextFormatWidget::on_mBufferUnitWidget_changed() +{ + updateFont( mRefFont ); +} + +void QgsTextFormatWidget::on_mCoordXDDBtn_dataDefinedActivated( bool active ) +{ + if ( !active ) //no data defined alignment without data defined position + { + enableDataDefinedAlignment( false ); + } + else if ( mCoordYDDBtn->isActive() ) + { + enableDataDefinedAlignment( true ); + } +} + +void QgsTextFormatWidget::on_mCoordYDDBtn_dataDefinedActivated( bool active ) +{ + if ( !active ) //no data defined alignment without data defined position + { + enableDataDefinedAlignment( false ); + } + else if ( mCoordXDDBtn->isActive() ) + { + enableDataDefinedAlignment( true ); + } +} + +void QgsTextFormatWidget::on_mShapeTypeCmbBx_currentIndexChanged( int index ) +{ + // shape background + bool isRect = (( QgsTextBackgroundSettings::ShapeType )index == QgsTextBackgroundSettings::ShapeRectangle + || ( QgsTextBackgroundSettings::ShapeType )index == QgsTextBackgroundSettings::ShapeSquare ); + bool isSVG = (( QgsTextBackgroundSettings::ShapeType )index == QgsTextBackgroundSettings::ShapeSVG ); + + showBackgroundPenStyle( isRect ); + showBackgroundRadius( isRect ); + + mShapeSVGPathFrame->setVisible( isSVG ); + // symbology SVG renderer only supports size^2 scaling, so we only use the x size spinbox + mShapeSizeYLabel->setVisible( !isSVG ); + mShapeSizeYSpnBx->setVisible( !isSVG ); + mShapeSizeYDDBtn->setVisible( !isSVG ); + mShapeSizeXLabel->setText( tr( "Size%1" ).arg( !isSVG ? tr( " X" ) : "" ) ); + + // SVG parameter setting doesn't support color's alpha component yet + mShapeFillColorBtn->setAllowAlpha( !isSVG ); + mShapeFillColorBtn->setButtonBackground(); + mShapeBorderColorBtn->setAllowAlpha( !isSVG ); + mShapeBorderColorBtn->setButtonBackground(); + + // configure SVG parameter widgets + mShapeSVGParamsBtn->setVisible( isSVG ); + if ( isSVG ) + { + updateSvgWidgets( mShapeSVGPathLineEdit->text() ); + } + else + { + mShapeFillColorLabel->setEnabled( true ); + mShapeFillColorBtn->setEnabled( true ); + mShapeFillColorDDBtn->setEnabled( true ); + mShapeBorderColorLabel->setEnabled( true ); + mShapeBorderColorBtn->setEnabled( true ); + mShapeBorderColorDDBtn->setEnabled( true ); + mShapeBorderWidthLabel->setEnabled( true ); + mShapeBorderWidthSpnBx->setEnabled( true ); + mShapeBorderWidthDDBtn->setEnabled( true ); + } + // TODO: fix overriding SVG symbol's border width units in QgsSvgCache + // currently broken, fall back to symbol units only + mShapeBorderWidthUnitWidget->setVisible( !isSVG ); + mShapeSVGUnitsLabel->setVisible( isSVG ); + mShapeBorderUnitsDDBtn->setEnabled( !isSVG ); +} + +void QgsTextFormatWidget::on_mShapeSVGPathLineEdit_textChanged( const QString& text ) +{ + updateSvgWidgets( text ); +} + +void QgsTextFormatWidget::updateLinePlacementOptions() +{ + int numOptionsChecked = ( chkLineAbove->isChecked() ? 1 : 0 ) + + ( chkLineBelow->isChecked() ? 1 : 0 ) + + ( chkLineOn->isChecked() ? 1 : 0 ); + + if ( numOptionsChecked == 1 ) + { + //prevent unchecking last option + chkLineAbove->setEnabled( !chkLineAbove->isChecked() ); + chkLineBelow->setEnabled( !chkLineBelow->isChecked() ); + chkLineOn->setEnabled( !chkLineOn->isChecked() ); + } + else + { + chkLineAbove->setEnabled( true ); + chkLineBelow->setEnabled( true ); + chkLineOn->setEnabled( true ); + } +} + +void QgsTextFormatWidget::onSubstitutionsChanged( const QgsStringReplacementCollection& substitutions ) +{ + mSubstitutions = substitutions; + emit widgetChanged(); +} + +void QgsTextFormatWidget::previewScaleChanged( double scale ) +{ + lblFontPreview->setScale( scale ); +} + +void QgsTextFormatWidget::updateSvgWidgets( const QString& svgPath ) +{ + if ( mShapeSVGPathLineEdit->text() != svgPath ) + { + mShapeSVGPathLineEdit->setText( svgPath ); + } + + QString resolvedPath = QgsSymbolLayerUtils::symbolNameToPath( svgPath ); + bool validSVG = !resolvedPath.isNull(); + + // draw red text for path field if invalid (path can't be resolved) + mShapeSVGPathLineEdit->setStyleSheet( QString( !validSVG ? "QLineEdit{ color: rgb(225, 0, 0); }" : "" ) ); + mShapeSVGPathLineEdit->setToolTip( !validSVG ? tr( "File not found" ) : resolvedPath ); + + QColor fill, outline; + double outlineWidth = 0.0; + bool fillParam = false, outlineParam = false, outlineWidthParam = false; + if ( validSVG ) + { + QgsSvgCache::instance()->containsParams( resolvedPath, fillParam, fill, outlineParam, outline, outlineWidthParam, outlineWidth ); + } + + mShapeSVGParamsBtn->setEnabled( validSVG && ( fillParam || outlineParam || outlineWidthParam ) ); + + mShapeFillColorLabel->setEnabled( validSVG && fillParam ); + mShapeFillColorBtn->setEnabled( validSVG && fillParam ); + mShapeFillColorDDBtn->setEnabled( validSVG && fillParam ); + if ( mLoadSvgParams && validSVG && fillParam ) + mShapeFillColorBtn->setColor( fill ); + + mShapeBorderColorLabel->setEnabled( validSVG && outlineParam ); + mShapeBorderColorBtn->setEnabled( validSVG && outlineParam ); + mShapeBorderColorDDBtn->setEnabled( validSVG && outlineParam ); + if ( mLoadSvgParams && validSVG && outlineParam ) + mShapeBorderColorBtn->setColor( outline ); + + mShapeBorderWidthLabel->setEnabled( validSVG && outlineWidthParam ); + mShapeBorderWidthSpnBx->setEnabled( validSVG && outlineWidthParam ); + mShapeBorderWidthDDBtn->setEnabled( validSVG && outlineWidthParam ); + if ( mLoadSvgParams && validSVG && outlineWidthParam ) + mShapeBorderWidthSpnBx->setValue( outlineWidth ); + + // TODO: fix overriding SVG symbol's border width units in QgsSvgCache + // currently broken, fall back to symbol's + //mShapeBorderWidthUnitWidget->setEnabled( validSVG && outlineWidthParam ); + //mShapeBorderUnitsDDBtn->setEnabled( validSVG && outlineWidthParam ); + mShapeSVGUnitsLabel->setEnabled( validSVG && outlineWidthParam ); +} + +void QgsTextFormatWidget::on_mShapeSVGSelectorBtn_clicked() +{ + QgsSvgSelectorDialog svgDlg( this ); + svgDlg.setWindowTitle( tr( "Select SVG file" ) ); + svgDlg.svgSelector()->setSvgPath( mShapeSVGPathLineEdit->text().trimmed() ); + + if ( svgDlg.exec() == QDialog::Accepted ) + { + QString svgPath = svgDlg.svgSelector()->currentSvgPath(); + if ( !svgPath.isEmpty() ) + { + mShapeSVGPathLineEdit->setText( svgPath ); + } + } +} + +void QgsTextFormatWidget::on_mShapeSVGParamsBtn_clicked() +{ + QString svgPath = mShapeSVGPathLineEdit->text(); + mLoadSvgParams = true; + updateSvgWidgets( svgPath ); + mLoadSvgParams = false; +} + +void QgsTextFormatWidget::on_mShapeRotationCmbBx_currentIndexChanged( int index ) +{ + mShapeRotationDblSpnBx->setEnabled(( QgsTextBackgroundSettings::RotationType )index != QgsTextBackgroundSettings::RotationSync ); + mShapeRotationDDBtn->setEnabled(( QgsTextBackgroundSettings::RotationType )index != QgsTextBackgroundSettings::RotationSync ); +} + +void QgsTextFormatWidget::on_mPreviewTextEdit_textChanged( const QString & text ) +{ + lblFontPreview->setText( text ); + updatePreview(); +} + +void QgsTextFormatWidget::on_mPreviewTextBtn_clicked() +{ + mPreviewTextEdit->setText( QString( "Lorem Ipsum" ) ); + updatePreview(); +} + +void QgsTextFormatWidget::on_mPreviewBackgroundBtn_colorChanged( const QColor &color ) +{ + setPreviewBackground( color ); +} + +void QgsTextFormatWidget::on_mDirectSymbLeftToolBtn_clicked() +{ + bool gotChar = false; + QChar dirSymb = mCharDlg->selectCharacter( &gotChar, mRefFont, mFontDB.styleString( mRefFont ) ); + + if ( !gotChar ) + return; + + if ( !dirSymb.isNull() ) + mDirectSymbLeftLineEdit->setText( QString( dirSymb ) ); +} + +void QgsTextFormatWidget::on_mDirectSymbRightToolBtn_clicked() +{ + bool gotChar = false; + QChar dirSymb = mCharDlg->selectCharacter( &gotChar, mRefFont, mFontDB.styleString( mRefFont ) ); + + if ( !gotChar ) + return; + + if ( !dirSymb.isNull() ) + mDirectSymbRightLineEdit->setText( QString( dirSymb ) ); +} + +void QgsTextFormatWidget::on_mChkNoObstacle_toggled( bool active ) +{ + mPolygonObstacleTypeFrame->setEnabled( active ); + mObstaclePriorityFrame->setEnabled( active ); +} + +void QgsTextFormatWidget::on_chkLineOrientationDependent_toggled( bool active ) +{ + if ( active ) + { + chkLineAbove->setText( tr( "Left of line" ) ); + chkLineBelow->setText( tr( "Right of line" ) ); + } + else + { + chkLineAbove->setText( tr( "Above line" ) ); + chkLineBelow->setText( tr( "Below line" ) ); + } +} + + +void QgsTextFormatWidget::on_mToolButtonConfigureSubstitutes_clicked() +{ + QgsPanelWidget* panel = QgsPanelWidget::findParentPanel( this ); + if ( panel && panel->dockMode() ) + { + QgsSubstitutionListWidget* widget = new QgsSubstitutionListWidget( panel ); + widget->setPanelTitle( tr( "Substitutions" ) ); + widget->setSubstitutions( mSubstitutions ); + connect( widget, SIGNAL( substitutionsChanged( QgsStringReplacementCollection ) ), this, SLOT( onSubstitutionsChanged( QgsStringReplacementCollection ) ) ); + panel->openPanel( widget ); + return; + } + + QgsSubstitutionListDialog dlg( this ); + dlg.setSubstitutions( mSubstitutions ); + if ( dlg.exec() == QDialog::Accepted ) + { + mSubstitutions = dlg.substitutions(); + emit widgetChanged(); + } +} + +void QgsTextFormatWidget::showBackgroundRadius( bool show ) +{ + mShapeRadiusLabel->setVisible( show ); + mShapeRadiusXDbSpnBx->setVisible( show ); + + mShapeRadiusYDbSpnBx->setVisible( show ); + + mShapeRadiusUnitWidget->setVisible( show ); + + mShapeRadiusDDBtn->setVisible( show ); + mShapeRadiusUnitsDDBtn->setVisible( show ); +} + +void QgsTextFormatWidget::showBackgroundPenStyle( bool show ) +{ + mShapePenStyleLabel->setVisible( show ); + mShapePenStyleCmbBx->setVisible( show ); + + mShapePenStyleDDBtn->setVisible( show ); +} + +void QgsTextFormatWidget::enableDataDefinedAlignment( bool enable ) +{ + mCoordAlignmentFrame->setEnabled( enable ); +} + + diff --git a/src/gui/qgstextformatwidget.h b/src/gui/qgstextformatwidget.h new file mode 100644 index 000000000000..d7d38d937842 --- /dev/null +++ b/src/gui/qgstextformatwidget.h @@ -0,0 +1,198 @@ +/*************************************************************************** + qgstextformatwidget.h + --------------------- + begin : June 2009 + copyright : (C) Martin Dobias + email : wonder dot sk at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + + +#ifndef QGSTEXTFORMATWIDGET_H +#define QGSTEXTFORMATWIDGET_H + +#include +#include "qgstextrenderer.h" +#include "qgsstringutils.h" +#include + +class QgsMapCanvas; +class QgsCharacterSelectorDialog; + + +/** \class QgsTextFormatWidget + * \ingroup gui + * A widget for customising text formatting settings. + * + * QgsTextFormatWidget provides a widget for controlling the appearance of text rendered + * using QgsTextRenderer. The preview includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * Additionally, the widget can handle labeling settings due to the large overlap between + * the text renderer settings and the labeling settings. This mode is possible by + * subclassing QgsTextFormatWidget and calling the protected constructor with a mode + * of Labeling. + * + * @note Added in QGIS 3.0 + */ + +class GUI_EXPORT QgsTextFormatWidget : public QWidget, protected Ui::QgsTextFormatWidgetBase +{ + Q_OBJECT + Q_PROPERTY( QgsTextFormat format READ format ) + + public: + + /** Constructor for QgsTextFormatWidget. + * @param format initial formatting settings to show in widget + * @param mapCanvas associated map canvas + * @param parent parent widget + */ + QgsTextFormatWidget( const QgsTextFormat& format = QgsTextFormat(), QgsMapCanvas* mapCanvas = nullptr, QWidget* parent = nullptr ); + + ~QgsTextFormatWidget(); + + /** Returns the current formatting settings defined by the widget. + */ + QgsTextFormat format() const; + + public slots: + + /** Sets whether the widget should be shown in a compact dock mode. + * @param enabled set to true to show in dock mode. + */ + void setDockMode( bool enabled ); + + signals: + + //! Emitted when the text format defined by the widget changes + void widgetChanged(); + + protected: + + //! Widget mode + enum Mode + { + Text = 0, //!< Default mode, show text formatting settings only + Labeling, //!< Show labeling settings in addition to text formatting settings + }; + + /** Constructor for QgsTextFormatWidget. + * @param mapCanvas associated map canvas + * @param parent parent widget + * @param mode widget mode + */ + QgsTextFormatWidget( QgsMapCanvas* mapCanvas, QWidget* parent, Mode mode ); + + /** Updates the widget's state to reflect the settings in a QgsTextFormat. + * @param format source format + */ + void updateWidgetForFormat( const QgsTextFormat& format ); + + /** Sets the background color for the text preview widget. + * @param color background color + */ + void setPreviewBackground( const QColor& color ); + + /** Controls whether data defined alignment buttons are enabled. + * @param enable set to true to enable alignment controls + */ + void enableDataDefinedAlignment( bool enable ); + + //! Text substitution list + QgsStringReplacementCollection mSubstitutions; + //! Quadrant button group + QButtonGroup* mQuadrantBtnGrp; + //! Symbol direction button group + QButtonGroup* mDirectSymbBtnGrp; + //! Upside down labels button group + QButtonGroup* mUpsidedownBtnGrp; + //! Point placement button group + QButtonGroup* mPlacePointBtnGrp; + //! Line placement button group + QButtonGroup* mPlaceLineBtnGrp; + //! Polygon placement button group + QButtonGroup* mPlacePolygonBtnGrp; + //! Pixel size font limit + int mMinPixelLimit; + + protected slots: + + //! Updates line placement options to reflect current state of widget + void updateLinePlacementOptions(); + + //! Updates label placement options to reflect current state of widget + void updatePlacementWidgets(); + + private: + Mode mWidgetMode; + QgsMapCanvas* mMapCanvas; + QgsCharacterSelectorDialog* mCharDlg; + + QFontDatabase mFontDB; + + // background reference font + QFont mRefFont; + bool mDockMode; + + bool mLoadSvgParams; + + void initWidget(); + void setWidgetMode( Mode mode ); + void toggleDDButtons( bool visible ); + void blockFontChangeSignals( bool blk ); + void populateFontCapitalsComboBox(); + void populateFontStyleComboBox(); + void updateFont( const QFont& font ); + void connectValueChanged( const QList &widgets, const char* slot ); + + private slots: + void optionsStackedWidget_CurrentChanged( int indx ); + void showBackgroundRadius( bool show ); + void showBackgroundPenStyle( bool show ); + void on_mShapeSVGPathLineEdit_textChanged( const QString& text ); + void onSubstitutionsChanged( const QgsStringReplacementCollection& substitutions ); + void previewScaleChanged( double scale ); + void on_mFontSizeSpinBox_valueChanged( double d ); + void on_mFontCapitalsComboBox_currentIndexChanged( int index ); + void on_mFontFamilyCmbBx_currentFontChanged( const QFont& f ); + void on_mFontStyleComboBox_currentIndexChanged( const QString & text ); + void on_mFontUnderlineBtn_toggled( bool ckd ); + void on_mFontStrikethroughBtn_toggled( bool ckd ); + void on_mFontWordSpacingSpinBox_valueChanged( double spacing ); + void on_mFontLetterSpacingSpinBox_valueChanged( double spacing ); + void on_mFontSizeUnitWidget_changed(); + void on_mFontMinPixelSpinBox_valueChanged( int px ); + void on_mFontMaxPixelSpinBox_valueChanged( int px ); + void on_mBufferUnitWidget_changed(); + void on_mCoordXDDBtn_dataDefinedActivated( bool active ); + void on_mCoordYDDBtn_dataDefinedActivated( bool active ); + void on_mShapeTypeCmbBx_currentIndexChanged( int index ); + void on_mShapeRotationCmbBx_currentIndexChanged( int index ); + void on_mShapeSVGParamsBtn_clicked(); + void on_mShapeSVGSelectorBtn_clicked(); + void on_mPreviewTextEdit_textChanged( const QString & text ); + void on_mPreviewTextBtn_clicked(); + void on_mPreviewBackgroundBtn_colorChanged( const QColor &color ); + void on_mDirectSymbLeftToolBtn_clicked(); + void on_mDirectSymbRightToolBtn_clicked(); + void on_mChkNoObstacle_toggled( bool active ); + void on_chkLineOrientationDependent_toggled( bool active ); + void on_mToolButtonConfigureSubstitutes_clicked(); + void collapseSample( bool collapse ); + void changeTextColor( const QColor &color ); + void changeBufferColor( const QColor &color ); + void updatePreview(); + void scrollPreview(); + void updateSvgWidgets( const QString& svgPath ); +}; + +#endif //QGSTEXTFORMATWIDGET_H + + diff --git a/src/ui/qgslabelingguibase.ui b/src/ui/qgstextformatwidgetbase.ui similarity index 98% rename from src/ui/qgslabelingguibase.ui rename to src/ui/qgstextformatwidgetbase.ui index 32d69cce2203..9cbbe5c2fe53 100644 --- a/src/ui/qgslabelingguibase.ui +++ b/src/ui/qgstextformatwidgetbase.ui @@ -1,7 +1,7 @@ - QgsLabelingGuiBase - + QgsTextFormatWidgetBase + 0 @@ -29,7 +29,7 @@ 6 - + @@ -335,7 +335,7 @@ QTabWidget::Rounded - 0 + 1 @@ -664,86 +664,6 @@ 0 - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Available typeface styles - - - QComboBox::AdjustToContentsOnFirstShow - - - - - - - - - - 0 - 0 - - - - letter - - - - - - - - 0 - 0 - - - - Space in pixels or map units, relative to size unit choice - - - 4 - - - -1000.000000000000000 - - - 999999999.000000000000000 - - - 0.100000000000000 - - - true - - - - - - - ... - - - - - @@ -760,83 +680,30 @@ - - + + - + 0 0 - - Color - - - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + 120 + 0 + - - - - - - ... + + + 120 + 16777215 + - - - - - - - 0 - 0 - - - - word - - - - - - - - 0 - 0 - - - - Space in pixels or map units, relative to size unit choice - - - 4 - - - -1000.000000000000000 - - - 999999999.000000000000000 - - - 0.100000000000000 - - - true - - - - - - - ... - - - - - - - + + 0 @@ -844,34 +711,43 @@ - Size + Type case - - + + + + true + - ... + Transparency - - + + + + + 0 + 0 + + - ... + Color + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter - - + + - ... + Spacing - - - @@ -897,78 +773,339 @@ - - - - Spacing - - - - - - - - 0 - 0 - - - - Font - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - - - - - ... - - - - - - - - 0 - 0 - - - - - 120 - 0 - - - - - 120 - 16777215 - - - - - - - - - - - If enabled, the label text will automatically be modified using a preset list of substitutes - - - Apply label text substitutes - - - - + + + + + + true + + + + 24 + 24 + + + + + 24 + 24 + + + + + 13 + true + + + + Underlined text + + + U + + + true + + + + + + + ... + + + + + + + true + + + + 24 + 24 + + + + + 24 + 24 + + + + + 13 + true + + + + Strikeout text + + + S + + + true + + + + + + + ... + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + false + + + + 24 + 24 + + + + + 24 + 24 + + + + + 13 + + + + Bold text +(data defined only, overrides Style) + + + B + + + true + + + + + + + ... + + + + + + + false + + + + 24 + 24 + + + + + 24 + 24 + + + + + 13 + true + + + + Italic text +(data defined only, overrides Style) + + + I + + + true + + + + + + + + + + 0 + 0 + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + Available typeface styles + + + QComboBox::AdjustToContentsOnFirstShow + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + color: #990000; +font-style: italic; + + + Font is missing. + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + + + + + + + + 0 + 0 + + + + Font + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + ... + + + + + + + ... + + + + + + + ... + + + + + + + ... + + + + + + + ... + + + + + + + ... + + + + + + + + + + ... + + + + false + + + + ... + + + + + + + Blend mode + + + @@ -991,6 +1128,46 @@ + + + + ... + + + + + + + + 0 + 0 + + + + Size + + + + + + + ... + + + + + + + + 0 + 0 + + + + Style + + + @@ -1059,229 +1236,115 @@
                                                                                                                                                                                    - - - - true - - - Transparency - - - - - - - ... - - - - - - - - - true - - - - 24 - 24 - - - - - 24 - 24 - - - - - 13 - true - - - - Underlined text - - - U - - - true - - - - - - - ... - - - + + + + ... + + + + + - - - true - - - - 24 - 24 - - - - - 24 - 24 - - - - - 13 - true - - - - Strikeout text - - - S - - - true + + + + 0 + 0 + - - - - - ... + word - - - Qt::Horizontal - - - - 0 - 20 - - - - - - - - false + + + + 0 + 0 + - - - 24 - 24 - + + Space in pixels or map units, relative to size unit choice - - - 24 - 24 - + + 4 - - - 13 - + + -1000.000000000000000 - - Bold text -(data defined only, overrides Style) + + 999999999.000000000000000 - - B + + 0.100000000000000 - + true + + + + - + + + + 0 + 0 + + - ... + letter - - - false + + + + 0 + 0 + - - - 24 - 24 - + + Space in pixels or map units, relative to size unit choice - - - 24 - 24 - + + 4 - - - 13 - true - + + -1000.000000000000000 - - Italic text -(data defined only, overrides Style) + + 999999999.000000000000000 - - I + + 0.100000000000000 - + true - - - - ... - - - - - - - ... - - - - - - - Blend mode + + + + QFrame::NoFrame - - - - - - ... + + QFrame::Raised - - - - - + + + 0 + 0 @@ -1295,67 +1358,31 @@ 0 - - - - 0 - 0 - - - - color: #990000; -font-style: italic; + + + If enabled, the label text will automatically be modified using a preset list of substitutes - Font is missing. + Apply label text substitutes - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + false + + + Configure substitutes + + + ... - - - - - 0 - 0 - - - - Type case - - - - - - - - 0 - 0 - - - - Style - - - - - - - false - - - Configure substitutes - - - ... - - -
                                                                                                                                                                                    @@ -6292,9 +6319,9 @@ font-style: italic;
                                                                                                                                                                                    - + - + 0 @@ -6412,6 +6439,12 @@ font-style: italic; QWidget
                                                                                                                                                                                    qgsscalewidget.h
                                                                                                                                                                                    + + QgsPanelWidget + QWidget +
                                                                                                                                                                                    qgspanelwidget.h
                                                                                                                                                                                    + 1 +
                                                                                                                                                                                    scrollArea_mPreview @@ -6431,7 +6464,6 @@ font-style: italic; mFontBoldBtn mFontBoldDDBtn mFontItalicBtn - mFontItalicDDBtn mFontSizeSpinBox mFontSizeDDBtn mFontUnitsDDBtn @@ -6443,9 +6475,7 @@ font-style: italic; mFontCapitalsComboBox mFontCaseDDBtn mFontLetterSpacingSpinBox - mFontLetterSpacingDDBtn mFontWordSpacingSpinBox - mFontWordSpacingDDBtn comboBlendMode mFontBlendModeDDBtn scrollArea_5 diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 8bdada70b97f..8067b428e332 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -104,6 +104,7 @@ ADD_PYTHON_TEST(PyQgsSyntacticSugar test_syntactic_sugar.py) ADD_PYTHON_TEST(PyQgsStringUtils test_qgsstringutils.py) ADD_PYTHON_TEST(PyQgsSymbol test_qgssymbol.py) ADD_PYTHON_TEST(PyQgsSymbolLayerUtils test_qgssymbollayerutils.py) +ADD_PYTHON_TEST(PyQgsTextFormatWidget test_qgstextformatwidget.py) ADD_PYTHON_TEST(PyQgsTreeWidgetItem test_qgstreewidgetitem.py) ADD_PYTHON_TEST(PyQgsUnitTypes test_qgsunittypes.py) ADD_PYTHON_TEST(PyQgsVectorColorRamp test_qgsvectorcolorramp.py) diff --git a/tests/src/python/test_qgstextformatwidget.py b/tests/src/python/test_qgstextformatwidget.py new file mode 100644 index 000000000000..f8b3b3673fe5 --- /dev/null +++ b/tests/src/python/test_qgstextformatwidget.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsTextFormatWidget. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '2016-09' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA +import os + +from qgis.core import (QgsTextBufferSettings, + QgsTextBackgroundSettings, + QgsTextShadowSettings, + QgsTextFormat, + QgsUnitTypes, + QgsMapUnitScale) +from qgis.gui import (QgsTextFormatWidget) +from qgis.PyQt.QtGui import (QColor, QPainter, QFont, QImage, QBrush, QPen) +from qgis.PyQt.QtCore import (Qt, QSizeF, QPointF, QRectF, QDir) +from qgis.testing import unittest, start_app +from utilities import getTestFont, svgSymbolsPath + +start_app() + + +class PyQgsTextFormatWidget(unittest.TestCase): + + def createBufferSettings(self): + s = QgsTextBufferSettings() + s.setEnabled(True) + s.setSize(5) + s.setSizeUnit(QgsUnitTypes.RenderPixels) + s.setSizeMapUnitScale(QgsMapUnitScale(1, 2)) + s.setColor(QColor(255, 0, 0)) + s.setFillBufferInterior(True) + s.setOpacity(0.5) + s.setJoinStyle(Qt.RoundJoin) + s.setBlendMode(QPainter.CompositionMode_Difference) + return s + + def checkBufferSettings(self, s): + """ test QgsTextBufferSettings """ + self.assertTrue(s.enabled()) + self.assertEqual(s.size(), 5) + self.assertEqual(s.sizeUnit(), QgsUnitTypes.RenderPixels) + self.assertEqual(s.sizeMapUnitScale(), QgsMapUnitScale(1, 2)) + self.assertEqual(s.color(), QColor(255, 0, 0)) + self.assertTrue(s.fillBufferInterior()) + self.assertEqual(s.opacity(), 0.5) + self.assertEqual(s.joinStyle(), Qt.RoundJoin) + self.assertEqual(s.blendMode(), QPainter.CompositionMode_Difference) + + def createBackgroundSettings(self): + s = QgsTextBackgroundSettings() + s.setEnabled(True) + s.setType(QgsTextBackgroundSettings.ShapeEllipse) + s.setSvgFile('svg.svg') + s.setSizeType(QgsTextBackgroundSettings.SizeFixed) + s.setSize(QSizeF(1, 2)) + s.setSizeUnit(QgsUnitTypes.RenderPixels) + s.setSizeMapUnitScale(QgsMapUnitScale(1, 2)) + s.setRotationType(QgsTextBackgroundSettings.RotationFixed) + s.setRotation(45) + s.setOffset(QPointF(3, 4)) + s.setOffsetUnit(QgsUnitTypes.RenderMapUnits) + s.setOffsetMapUnitScale(QgsMapUnitScale(5, 6)) + s.setRadii(QSizeF(11, 12)) + s.setRadiiUnit(QgsUnitTypes.RenderPixels) + s.setRadiiMapUnitScale(QgsMapUnitScale(15, 16)) + s.setFillColor(QColor(255, 0, 0)) + s.setBorderColor(QColor(0, 255, 0)) + s.setOpacity(0.5) + s.setJoinStyle(Qt.RoundJoin) + s.setBlendMode(QPainter.CompositionMode_Difference) + s.setBorderWidth(7) + s.setBorderWidthUnit(QgsUnitTypes.RenderMapUnits) + s.setBorderWidthMapUnitScale(QgsMapUnitScale(QgsMapUnitScale(25, 26))) + return s + + def checkBackgroundSettings(self, s): + """ test QgsTextBackgroundSettings """ + self.assertTrue(s.enabled()) + self.assertEqual(s.type(), QgsTextBackgroundSettings.ShapeEllipse) + self.assertEqual(s.svgFile(), 'svg.svg') + self.assertEqual(s.sizeType(), QgsTextBackgroundSettings.SizeFixed) + self.assertEqual(s.size(), QSizeF(1, 2)) + self.assertEqual(s.sizeUnit(), QgsUnitTypes.RenderPixels) + self.assertEqual(s.sizeMapUnitScale(), QgsMapUnitScale(1, 2)) + self.assertEqual(s.rotationType(), QgsTextBackgroundSettings.RotationFixed) + self.assertEqual(s.rotation(), 45) + self.assertEqual(s.offset(), QPointF(3, 4)) + self.assertEqual(s.offsetUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(s.offsetMapUnitScale(), QgsMapUnitScale(5, 6)) + self.assertEqual(s.radii(), QSizeF(11, 12)) + self.assertEqual(s.radiiUnit(), QgsUnitTypes.RenderPixels) + self.assertEqual(s.radiiMapUnitScale(), QgsMapUnitScale(15, 16)) + self.assertEqual(s.fillColor(), QColor(255, 0, 0)) + self.assertEqual(s.borderColor(), QColor(0, 255, 0)) + self.assertEqual(s.opacity(), 0.5) + self.assertEqual(s.joinStyle(), Qt.RoundJoin) + self.assertEqual(s.blendMode(), QPainter.CompositionMode_Difference) + self.assertEqual(s.borderWidth(), 7) + self.assertEqual(s.borderWidthUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(s.borderWidthMapUnitScale(), QgsMapUnitScale(25, 26)) + + def createShadowSettings(self): + s = QgsTextShadowSettings() + s.setEnabled(True) + s.setShadowPlacement(QgsTextShadowSettings.ShadowBuffer) + s.setOffsetAngle(45) + s.setOffsetDistance(75) + s.setOffsetUnit(QgsUnitTypes.RenderMapUnits) + s.setOffsetMapUnitScale(QgsMapUnitScale(5, 6)) + s.setOffsetGlobal(True) + s.setBlurRadius(11) + s.setBlurRadiusUnit(QgsUnitTypes.RenderMapUnits) + s.setBlurRadiusMapUnitScale(QgsMapUnitScale(15, 16)) + s.setBlurAlphaOnly(True) + s.setColor(QColor(255, 0, 0)) + s.setOpacity(0.5) + s.setScale(123) + s.setBlendMode(QPainter.CompositionMode_Difference) + return s + + def checkShadowSettings(self, s): + """ test QgsTextShadowSettings """ + self.assertTrue(s.enabled()) + self.assertEqual(s.shadowPlacement(), QgsTextShadowSettings.ShadowBuffer) + self.assertEqual(s.offsetAngle(), 45) + self.assertEqual(s.offsetDistance(), 75) + self.assertEqual(s.offsetUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(s.offsetMapUnitScale(), QgsMapUnitScale(5, 6)) + self.assertTrue(s.offsetGlobal()) + self.assertEqual(s.blurRadius(), 11) + self.assertEqual(s.blurRadiusUnit(), QgsUnitTypes.RenderMapUnits) + self.assertEqual(s.blurRadiusMapUnitScale(), QgsMapUnitScale(15, 16)) + self.assertTrue(s.blurAlphaOnly()) + self.assertEqual(s.color(), QColor(255, 0, 0)) + self.assertEqual(s.opacity(), 0.5) + self.assertEqual(s.scale(), 123) + self.assertEqual(s.blendMode(), QPainter.CompositionMode_Difference) + + def createFormatSettings(self): + s = QgsTextFormat() + s.setBuffer(self.createBufferSettings()) + s.setBackground(self.createBackgroundSettings()) + s.setShadow(self.createShadowSettings()) + s.setFont(getTestFont()) + s.setNamedStyle('Roman') + s.setSize(5) + s.setSizeUnit(QgsUnitTypes.RenderPoints) + s.setSizeMapUnitScale(QgsMapUnitScale(1, 2)) + s.setColor(QColor(255, 0, 0)) + s.setOpacity(0.5) + s.setBlendMode(QPainter.CompositionMode_Difference) + s.setLineHeight(5) + return s + + def checkTextFormat(self, s): + """ test QgsTextFormat """ + self.checkBufferSettings(s.buffer()) + self.checkShadowSettings(s.shadow()) + self.checkBackgroundSettings(s.background()) + self.assertEqual(s.font().family(), 'QGIS Vera Sans') + self.assertEqual(s.namedStyle(), 'Roman') + self.assertEqual(s.size(), 5) + self.assertEqual(s.sizeUnit(), QgsUnitTypes.RenderPoints) + self.assertEqual(s.sizeMapUnitScale(), QgsMapUnitScale(1, 2)) + self.assertEqual(s.color(), QColor(255, 0, 0)) + self.assertEqual(s.opacity(), 0.5) + self.assertEqual(s.blendMode(), QPainter.CompositionMode_Difference) + self.assertEqual(s.lineHeight(), 5) + + def testSettings(self): + # test that widget correctly sets and returns matching settings + s = self.createFormatSettings() + w = QgsTextFormatWidget(s) + self.checkTextFormat(w.format()) + + +if __name__ == '__main__': + unittest.main() From 4282474c260be20701f627a309c8ca0a87087343 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 11:06:32 +1000 Subject: [PATCH 454/897] Respect render context antialiasing setting in text renderer --- src/core/qgstextrenderer.cpp | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/core/qgstextrenderer.cpp b/src/core/qgstextrenderer.cpp index dd1bd44d670a..8aad733add7e 100644 --- a/src/core/qgstextrenderer.cpp +++ b/src/core/qgstextrenderer.cpp @@ -1869,6 +1869,10 @@ void QgsTextRenderer::drawBuffer( QgsRenderContext& context, const QgsTextRender { p->setCompositionMode( buffer.blendMode() ); } + if ( context.flags() & QgsRenderContext::Antialiasing ) + { + p->setRenderHint( QPainter::Antialiasing ); + } // scale for any print output or image saving @ specific dpi p->scale( component.dpiRatio, component.dpiRatio ); @@ -2103,6 +2107,10 @@ void QgsTextRenderer::drawBackground( QgsRenderContext& context, QgsTextRenderer p->translate( QPointF( xoff, yoff ) ); p->rotate( component.rotationOffset ); p->translate( -sizeOut / 2, sizeOut / 2 ); + if ( context.flags() & QgsRenderContext::Antialiasing ) + { + p->setRenderHint( QPainter::Antialiasing ); + } drawShadow( context, component, format ); p->restore(); @@ -2121,6 +2129,10 @@ void QgsTextRenderer::drawBackground( QgsRenderContext& context, QgsTextRenderer { p->setCompositionMode( background.blendMode() ); } + if ( context.flags() & QgsRenderContext::Antialiasing ) + { + p->setRenderHint( QPainter::Antialiasing ); + } p->translate( component.center.x(), component.center.y() ); p->rotate( component.rotation ); double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); @@ -2185,6 +2197,10 @@ void QgsTextRenderer::drawBackground( QgsRenderContext& context, QgsTextRenderer return; p->save(); + if ( context.flags() & QgsRenderContext::Antialiasing ) + { + p->setRenderHint( QPainter::Antialiasing ); + } p->translate( QPointF( component.center.x(), component.center.y() ) ); p->rotate( component.rotation ); double xoff = QgsTextRenderer::scaleToPixelContext( background.offset().x(), context, background.offsetUnit(), false, background.offsetMapUnitScale() ); @@ -2353,7 +2369,11 @@ void QgsTextRenderer::drawShadow( QgsRenderContext& context, const QgsTextRender -offsetDist * sin( angleRad + M_PI / 2 ) ); p->save(); - p->setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); + p->setRenderHint( QPainter::SmoothPixmapTransform ); + if ( context.flags() & QgsRenderContext::Antialiasing ) + { + p->setRenderHint( QPainter::Antialiasing ); + } if ( context.useAdvancedEffects() ) { p->setCompositionMode( shadow.blendMode() ); @@ -2456,6 +2476,10 @@ void QgsTextRenderer::drawTextInternal( TextPart drawType, Q_FOREACH ( const QString& line, textLines ) { context.painter()->save(); + if ( context.flags() & QgsRenderContext::Antialiasing ) + { + context.painter()->setRenderHint( QPainter::Antialiasing ); + } context.painter()->translate( component.origin ); if ( !qgsDoubleNear( component.rotation, 0.0 ) ) context.painter()->rotate( -component.rotation * 180 / M_PI ); From 8fa8167d7bab0aee262f8b779360a34693732965 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 5 Oct 2016 11:07:51 +1000 Subject: [PATCH 455/897] Add a simple dialog for configuring text formatting --- python/gui/qgstextformatwidget.sip | 35 ++++++++++++++++- src/gui/qgstextformatwidget.cpp | 37 ++++++++++++++++++ src/gui/qgstextformatwidget.h | 40 +++++++++++++++++++- tests/src/python/test_qgstextformatwidget.py | 7 +++- 4 files changed, 116 insertions(+), 3 deletions(-) diff --git a/python/gui/qgstextformatwidget.sip b/python/gui/qgstextformatwidget.sip index 371e0f542554..9db2caa37a80 100644 --- a/python/gui/qgstextformatwidget.sip +++ b/python/gui/qgstextformatwidget.sip @@ -14,7 +14,7 @@ * @note Added in QGIS 3.0 */ -class QgsTextFormatWidget : public QgsPanelWidget +class QgsTextFormatWidget : QWidget { %TypeHeaderCode #include @@ -86,3 +86,36 @@ class QgsTextFormatWidget : public QgsPanelWidget //! Updates label placement options to reflect current state of widget void updatePlacementWidgets(); }; + +/** \class QgsTextFormatDialog + * \ingroup gui + * A simple dialog for customising text formatting settings. + * + * QgsTextFormatDialog provides a dialog for controlling the appearance of text rendered + * using QgsTextRenderer. The dialog includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * @note Added in QGIS 3.0 + */ + +class QgsTextFormatDialog : QDialog +{ +%TypeHeaderCode + #include +%End + public: + + /** Constructor for QgsTextFormatDialog. + * @param format initial format settings to show in dialog + * @param mapCanvas optional associated map canvas + * @param parent parent widget + * @param fl window flags for dialog + */ + QgsTextFormatDialog( const QgsTextFormat& format, QgsMapCanvas* mapCanvas = nullptr, QWidget* parent /TransferThis/ = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); + + virtual ~QgsTextFormatDialog(); + + /** Returns the current formatting settings defined by the widget. + */ + QgsTextFormat format() const; +}; diff --git a/src/gui/qgstextformatwidget.cpp b/src/gui/qgstextformatwidget.cpp index 934c7e2a9af8..295172010d8b 100644 --- a/src/gui/qgstextformatwidget.cpp +++ b/src/gui/qgstextformatwidget.cpp @@ -1376,3 +1376,40 @@ void QgsTextFormatWidget::enableDataDefinedAlignment( bool enable ) } +// +// QgsTextFormatDialog +// + +QgsTextFormatDialog::QgsTextFormatDialog( const QgsTextFormat& format, QgsMapCanvas* mapCanvas, QWidget* parent, Qt::WindowFlags fl ) + : QDialog( parent, fl ) +{ + setWindowTitle( tr( "Text settings" ) ); + + mFormatWidget = new QgsTextFormatWidget( format, mapCanvas, this ); + mFormatWidget->layout()->setContentsMargins( 0, 0, 0, 0 ); + + QVBoxLayout *layout = new QVBoxLayout( this ); + layout->addWidget( mFormatWidget ); + + QDialogButtonBox *buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this ); + layout->addWidget( buttonBox ); + + setLayout( layout ); + + QSettings settings; + restoreGeometry( settings.value( "/Windows/TextFormatDialog/geometry" ).toByteArray() ); + + connect( buttonBox->button( QDialogButtonBox::Ok ), SIGNAL( clicked() ), this, SLOT( accept() ) ); + connect( buttonBox->button( QDialogButtonBox::Cancel ), SIGNAL( clicked() ), this, SLOT( reject() ) ); +} + +QgsTextFormatDialog::~QgsTextFormatDialog() +{ + QSettings settings; + settings.setValue( "/Windows/TextFormatDialog/geometry", saveGeometry() ); +} + +QgsTextFormat QgsTextFormatDialog::format() const +{ + return mFormatWidget->format(); +} diff --git a/src/gui/qgstextformatwidget.h b/src/gui/qgstextformatwidget.h index d7d38d937842..526cbe4838fb 100644 --- a/src/gui/qgstextformatwidget.h +++ b/src/gui/qgstextformatwidget.h @@ -20,6 +20,7 @@ #include #include "qgstextrenderer.h" #include "qgsstringutils.h" +#include "qgisgui.h" #include class QgsMapCanvas; @@ -31,7 +32,7 @@ class QgsCharacterSelectorDialog; * A widget for customising text formatting settings. * * QgsTextFormatWidget provides a widget for controlling the appearance of text rendered - * using QgsTextRenderer. The preview includes all settings contained within + * using QgsTextRenderer. The widget includes all settings contained within * a QgsTextFormat, including shadow, background and buffer. * * Additionally, the widget can handle labeling settings due to the large overlap between @@ -193,6 +194,43 @@ class GUI_EXPORT QgsTextFormatWidget : public QWidget, protected Ui::QgsTextForm void updateSvgWidgets( const QString& svgPath ); }; + +/** \class QgsTextFormatDialog + * \ingroup gui + * A simple dialog for customising text formatting settings. + * + * QgsTextFormatDialog provides a dialog for controlling the appearance of text rendered + * using QgsTextRenderer. The dialog includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * @note Added in QGIS 3.0 + */ + +class GUI_EXPORT QgsTextFormatDialog : public QDialog +{ + Q_OBJECT + + public: + + /** Constructor for QgsTextFormatDialog. + * @param format initial format settings to show in dialog + * @param mapCanvas optional associated map canvas + * @param parent parent widget + * @param fl window flags for dialog + */ + QgsTextFormatDialog( const QgsTextFormat& format, QgsMapCanvas* mapCanvas = nullptr, QWidget* parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); + + virtual ~QgsTextFormatDialog(); + + /** Returns the current formatting settings defined by the widget. + */ + QgsTextFormat format() const; + + private: + + QgsTextFormatWidget* mFormatWidget; +}; + #endif //QGSTEXTFORMATWIDGET_H diff --git a/tests/src/python/test_qgstextformatwidget.py b/tests/src/python/test_qgstextformatwidget.py index f8b3b3673fe5..104bc9ca0b9f 100644 --- a/tests/src/python/test_qgstextformatwidget.py +++ b/tests/src/python/test_qgstextformatwidget.py @@ -21,7 +21,7 @@ QgsTextFormat, QgsUnitTypes, QgsMapUnitScale) -from qgis.gui import (QgsTextFormatWidget) +from qgis.gui import (QgsTextFormatWidget, QgsTextFormatDialog) from qgis.PyQt.QtGui import (QColor, QPainter, QFont, QImage, QBrush, QPen) from qgis.PyQt.QtCore import (Qt, QSizeF, QPointF, QRectF, QDir) from qgis.testing import unittest, start_app @@ -184,6 +184,11 @@ def testSettings(self): w = QgsTextFormatWidget(s) self.checkTextFormat(w.format()) + def testDialogSettings(self): + # test that dialog correctly sets and returns matching settings + s = self.createFormatSettings() + d = QgsTextFormatDialog(s) + self.checkTextFormat(d.format()) if __name__ == '__main__': unittest.main() From f6a344c2c159aa98f5d6d87eb84749d6b15e693c Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 12 Oct 2016 10:49:30 +1000 Subject: [PATCH 456/897] Add QgsTextFormatPanelWidget for text format control inside panel --- python/gui/qgstextformatwidget.sip | 33 ++++++++++++++++++++++++++++ src/gui/qgstextformatwidget.cpp | 18 +++++++++++++++ src/gui/qgstextformatwidget.h | 35 ++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) diff --git a/python/gui/qgstextformatwidget.sip b/python/gui/qgstextformatwidget.sip index 9db2caa37a80..d73284deac27 100644 --- a/python/gui/qgstextformatwidget.sip +++ b/python/gui/qgstextformatwidget.sip @@ -119,3 +119,36 @@ class QgsTextFormatDialog : QDialog */ QgsTextFormat format() const; }; + +/** \class QgsTextFormatPanelWidget + * \ingroup gui + * A panel widget for customising text formatting settings. + * + * QgsTextFormatPanelWidget provides a panel widget for controlling the appearance of text rendered + * using QgsTextRenderer. The dialog includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * @note Added in QGIS 3.0 + */ + +class QgsTextFormatPanelWidget : QgsPanelWidgetWrapper +{ +%TypeHeaderCode + #include +%End + public: + + /** Constructor for QgsTextFormatPanelWidget. + * @param format initial format settings to show in dialog + * @param mapCanvas optional associated map canvas + * @param parent parent widget + */ + QgsTextFormatPanelWidget( const QgsTextFormat& format, QgsMapCanvas* mapCanvas = nullptr, QWidget* parent /TransferThis/ = nullptr ); + + /** Returns the current formatting settings defined by the widget. + */ + QgsTextFormat format() const; + + virtual void setDockMode( bool dockMode ); + +}; diff --git a/src/gui/qgstextformatwidget.cpp b/src/gui/qgstextformatwidget.cpp index 295172010d8b..d0166c976274 100644 --- a/src/gui/qgstextformatwidget.cpp +++ b/src/gui/qgstextformatwidget.cpp @@ -1413,3 +1413,21 @@ QgsTextFormat QgsTextFormatDialog::format() const { return mFormatWidget->format(); } + +QgsTextFormatPanelWidget::QgsTextFormatPanelWidget( const QgsTextFormat& format, QgsMapCanvas* mapCanvas, QWidget* parent ) + : QgsPanelWidgetWrapper( new QgsTextFormatWidget( format, mapCanvas ), parent ) +{ + mFormatWidget = qobject_cast< QgsTextFormatWidget* >( widget() ); + connect( mFormatWidget, SIGNAL( widgetChanged() ), this, SIGNAL( widgetChanged() ) ); +} + +QgsTextFormat QgsTextFormatPanelWidget::format() const +{ + return mFormatWidget->format(); +} + +void QgsTextFormatPanelWidget::setDockMode( bool dockMode ) +{ + mFormatWidget->setDockMode( dockMode ); + QgsPanelWidgetWrapper::setDockMode( dockMode ); +} diff --git a/src/gui/qgstextformatwidget.h b/src/gui/qgstextformatwidget.h index 526cbe4838fb..5ea021168a99 100644 --- a/src/gui/qgstextformatwidget.h +++ b/src/gui/qgstextformatwidget.h @@ -231,6 +231,41 @@ class GUI_EXPORT QgsTextFormatDialog : public QDialog QgsTextFormatWidget* mFormatWidget; }; +/** \class QgsTextFormatPanelWidget + * \ingroup gui + * A panel widget for customising text formatting settings. + * + * QgsTextFormatPanelWidget provides a panel widget for controlling the appearance of text rendered + * using QgsTextRenderer. The dialog includes all settings contained within + * a QgsTextFormat, including shadow, background and buffer. + * + * @note Added in QGIS 3.0 + */ + +class GUI_EXPORT QgsTextFormatPanelWidget : public QgsPanelWidgetWrapper +{ + Q_OBJECT + + public: + + /** Constructor for QgsTextFormatPanelWidget. + * @param format initial format settings to show in dialog + * @param mapCanvas optional associated map canvas + * @param parent parent widget + */ + QgsTextFormatPanelWidget( const QgsTextFormat& format, QgsMapCanvas* mapCanvas = nullptr, QWidget* parent = nullptr ); + + /** Returns the current formatting settings defined by the widget. + */ + QgsTextFormat format() const; + + virtual void setDockMode( bool dockMode ) override; + + private: + + QgsTextFormatWidget* mFormatWidget; +}; + #endif //QGSTEXTFORMATWIDGET_H From 4166a3ea626e613dee13e40f5e3a9d759a38feb9 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 23 Oct 2016 08:30:26 +1000 Subject: [PATCH 457/897] Fix most clazy qstring-unneeded-heap-allocations warnings By flipping string literals to QStringLiteral/QLatin1String see https://woboq.com/blog/qstringliteral.html --- .../interpolation/DualEdgeTriangulation.cc | 12 +- src/analysis/network/qgsgraphbuilder.h | 2 +- src/analysis/network/qgsgraphbuilderintr.h | 2 +- .../network/qgslinevectorlayerdirector.cpp | 2 +- src/analysis/openstreetmap/qgsosmdatabase.cpp | 54 +- src/analysis/openstreetmap/qgsosmdownload.cpp | 6 +- src/analysis/openstreetmap/qgsosmimport.cpp | 38 +- src/analysis/raster/qgsalignraster.cpp | 8 +- src/analysis/raster/qgsruggednessfilter.cpp | 2 +- src/analysis/vector/qgsgeometryanalyzer.cpp | 26 +- src/analysis/vector/qgsoverlayanalyzer.cpp | 2 +- src/analysis/vector/qgspointsample.cpp | 14 +- src/analysis/vector/qgstransectsample.cpp | 62 +- src/analysis/vector/qgszonalstatistics.cpp | 30 +- src/analysis/vector/qgszonalstatistics.h | 2 +- .../composer/qgsatlascompositionwidget.cpp | 4 +- .../composer/qgsattributeselectiondialog.cpp | 8 +- src/app/composer/qgscomposer.cpp | 326 ++--- src/app/composer/qgscomposerarrowwidget.cpp | 16 +- .../qgscomposerattributetablewidget.cpp | 10 +- src/app/composer/qgscomposerhtmlwidget.cpp | 10 +- .../qgscomposerimageexportoptionsdialog.cpp | 4 +- src/app/composer/qgscomposeritemwidget.cpp | 6 +- src/app/composer/qgscomposerlabelwidget.cpp | 6 +- src/app/composer/qgscomposerlegendwidget.cpp | 24 +- src/app/composer/qgscomposermanager.cpp | 14 +- src/app/composer/qgscomposermapgridwidget.cpp | 18 +- src/app/composer/qgscomposermapwidget.cpp | 10 +- src/app/composer/qgscomposerpicturewidget.cpp | 28 +- .../composer/qgscomposerscalebarwidget.cpp | 26 +- ...qgscomposertablebackgroundcolorsdialog.cpp | 4 +- src/app/composer/qgscompositionwidget.cpp | 2 +- src/app/gps/qgsgpsinformationwidget.cpp | 98 +- src/app/gps/qgsgpsmarker.cpp | 4 +- src/app/main.cpp | 222 ++-- src/app/nodetool/qgsmaptoolnodetool.cpp | 32 +- src/app/nodetool/qgsselectedfeature.cpp | 2 +- src/app/ogr/qgsnewogrconnection.cpp | 8 +- src/app/ogr/qgsogrhelperfunctions.cpp | 76 +- src/app/ogr/qgsopenvectorlayerdialog.cpp | 38 +- src/app/ogr/qgsvectorlayersaveasdialog.cpp | 62 +- .../openstreetmap/qgsosmdownloaddialog.cpp | 6 +- src/app/openstreetmap/qgsosmexportdialog.cpp | 16 +- src/app/openstreetmap/qgsosmimportdialog.cpp | 10 +- .../qgsapppluginmanagerinterface.cpp | 4 +- .../pluginmanager/qgspluginitemdelegate.cpp | 4 +- src/app/pluginmanager/qgspluginmanager.cpp | 364 +++--- .../pluginmanager/qgspluginmanager_texts.cpp | 12 +- .../qgspluginsortfilterproxymodel.cpp | 6 +- .../qgspluginsortfilterproxymodel.h | 2 +- src/app/qgisapp.cpp | 1148 ++++++++--------- src/app/qgisapp.h | 2 +- src/app/qgisappstylesheet.cpp | 94 +- src/app/qgsabout.cpp | 26 +- src/app/qgsaddattrdialog.cpp | 4 +- src/app/qgsaddtaborgroup.cpp | 10 +- src/app/qgsalignrasterdialog.cpp | 8 +- src/app/qgsannotationwidget.cpp | 4 +- src/app/qgsapplayertreeviewmenuprovider.cpp | 32 +- src/app/qgsattributeactiondialog.cpp | 16 +- .../qgsattributeactionpropertiesdialog.cpp | 6 +- src/app/qgsattributetabledialog.cpp | 74 +- src/app/qgsattributetypedialog.cpp | 4 +- src/app/qgsbookmarks.cpp | 124 +- src/app/qgsbrowserdockwidget.cpp | 42 +- src/app/qgsclipboard.cpp | 16 +- src/app/qgscustomization.cpp | 68 +- src/app/qgscustomprojectiondialog.cpp | 36 +- src/app/qgsdecorationcopyright.cpp | 22 +- src/app/qgsdecorationcopyrightdialog.cpp | 6 +- src/app/qgsdecorationgrid.cpp | 66 +- src/app/qgsdecorationgriddialog.cpp | 2 +- src/app/qgsdecorationitem.cpp | 12 +- src/app/qgsdecorationnortharrow.cpp | 20 +- src/app/qgsdecorationnortharrowdialog.cpp | 8 +- src/app/qgsdecorationscalebar.cpp | 42 +- src/app/qgsdecorationscalebardialog.cpp | 6 +- src/app/qgsdelattrdialog.cpp | 10 +- src/app/qgsdiagramproperties.cpp | 30 +- src/app/qgsdisplayangle.cpp | 4 +- src/app/qgsdxfexportdialog.cpp | 54 +- src/app/qgsfeatureaction.cpp | 6 +- src/app/qgsfieldcalculator.cpp | 22 +- src/app/qgsfieldsproperties.cpp | 56 +- src/app/qgsformannotationdialog.cpp | 2 +- src/app/qgsguivectorlayertools.cpp | 4 +- src/app/qgshandlebadlayers.cpp | 42 +- src/app/qgshtmlannotationdialog.cpp | 2 +- src/app/qgsidentifyresultsdialog.cpp | 80 +- src/app/qgslabelinggui.cpp | 34 +- src/app/qgslabelingwidget.cpp | 4 +- src/app/qgslabelpropertydialog.cpp | 6 +- src/app/qgslayerstylingwidget.cpp | 36 +- src/app/qgsloadstylefromdbdialog.cpp | 20 +- src/app/qgsmaplayerstyleguiutils.cpp | 2 +- src/app/qgsmaptoolchangelabelproperties.cpp | 2 +- src/app/qgsmaptoolfeatureaction.cpp | 4 +- src/app/qgsmaptoolidentifyaction.cpp | 8 +- src/app/qgsmaptoollabel.cpp | 38 +- src/app/qgsmaptoolmeasureangle.cpp | 6 +- src/app/qgsmaptoolmovelabel.cpp | 2 +- src/app/qgsmaptooloffsetcurve.cpp | 10 +- src/app/qgsmaptooloffsetpointsymbol.cpp | 14 +- src/app/qgsmaptoolpinlabels.cpp | 10 +- src/app/qgsmaptoolrotatefeature.cpp | 6 +- src/app/qgsmaptoolrotatelabel.cpp | 4 +- src/app/qgsmaptoolshowhidelabels.cpp | 2 +- src/app/qgsmaptoolsimplify.cpp | 8 +- src/app/qgsmeasuredialog.cpp | 22 +- src/app/qgsmeasuretool.cpp | 8 +- src/app/qgsmergeattributesdialog.cpp | 30 +- src/app/qgsnewspatialitelayerdialog.cpp | 64 +- src/app/qgsoptions.cpp | 772 +++++------ src/app/qgspluginregistry.cpp | 42 +- src/app/qgspluginregistry.h | 2 +- src/app/qgspointrotationitem.cpp | 2 +- src/app/qgsprojectlayergroupdialog.cpp | 14 +- src/app/qgsprojectproperties.cpp | 420 +++--- src/app/qgsrastercalcdialog.cpp | 68 +- src/app/qgsrasterlayerproperties.cpp | 94 +- src/app/qgsrelationadddlg.cpp | 4 +- src/app/qgsrelationmanagerdialog.cpp | 4 +- src/app/qgsrulebasedlabelingwidget.cpp | 34 +- src/app/qgssavestyletodbdialog.cpp | 12 +- src/app/qgsselectbyformdialog.cpp | 4 +- src/app/qgssettingstree.cpp | 6 +- src/app/qgssnappinglayertreemodel.cpp | 6 +- src/app/qgssnappingwidget.cpp | 34 +- src/app/qgssponsors.cpp | 6 +- src/app/qgsstatisticalsummarydockwidget.cpp | 8 +- src/app/qgsstatusbarcoordinateswidget.cpp | 14 +- src/app/qgsstatusbarmagnifierwidget.cpp | 8 +- src/app/qgsstatusbarscalewidget.cpp | 4 +- src/app/qgstextannotationdialog.cpp | 2 +- src/app/qgstipfactory.cpp | 2 +- src/app/qgstipgui.cpp | 2 +- src/app/qgsundowidget.cpp | 16 +- src/app/qgsvariantdelegate.cpp | 38 +- src/app/qgsvectorlayerproperties.cpp | 40 +- src/app/qgsversioninfo.cpp | 6 +- src/app/qgswelcomepage.cpp | 6 +- src/app/qgswelcomepageitemsmodel.cpp | 8 +- src/auth/basic/qgsauthbasicedit.cpp | 12 +- src/auth/basic/qgsauthbasicmethod.cpp | 42 +- src/auth/identcert/qgsauthidentcertedit.cpp | 8 +- src/auth/identcert/qgsauthidentcertmethod.cpp | 26 +- src/auth/pkipaths/qgsauthpkipathsedit.cpp | 30 +- src/auth/pkipaths/qgsauthpkipathsmethod.cpp | 32 +- src/auth/pkipkcs12/qgsauthpkcs12edit.cpp | 28 +- src/auth/pkipkcs12/qgsauthpkcs12method.cpp | 32 +- src/browser/main.cpp | 30 +- src/browser/qgsbrowser.cpp | 26 +- src/core/auth/qgsauthcertutils.cpp | 44 +- src/core/auth/qgsauthconfig.cpp | 40 +- src/core/auth/qgsauthmanager.cpp | 224 ++-- src/core/auth/qgsauthmethodregistry.cpp | 8 +- src/core/composer/qgsatlascomposition.cpp | 56 +- src/core/composer/qgscomposerarrow.cpp | 92 +- .../composer/qgscomposerattributetablev2.cpp | 56 +- src/core/composer/qgscomposerframe.cpp | 28 +- src/core/composer/qgscomposerhtml.cpp | 38 +- src/core/composer/qgscomposeritem.cpp | 166 +-- src/core/composer/qgscomposeritemcommand.cpp | 2 +- src/core/composer/qgscomposeritemgroup.cpp | 12 +- src/core/composer/qgscomposerlabel.cpp | 66 +- src/core/composer/qgscomposerlegend.cpp | 164 +-- src/core/composer/qgscomposerlegenditem.cpp | 80 +- src/core/composer/qgscomposerlegenditem.h | 14 +- src/core/composer/qgscomposerlegendstyle.cpp | 58 +- src/core/composer/qgscomposermap.cpp | 242 ++-- src/core/composer/qgscomposermapgrid.cpp | 214 +-- src/core/composer/qgscomposermapitem.cpp | 12 +- src/core/composer/qgscomposermapoverview.cpp | 30 +- src/core/composer/qgscomposermodel.cpp | 12 +- src/core/composer/qgscomposermousehandles.cpp | 4 +- src/core/composer/qgscomposermultiframe.cpp | 6 +- .../composer/qgscomposermultiframecommand.cpp | 4 +- src/core/composer/qgscomposernodesitem.cpp | 34 +- src/core/composer/qgscomposerobject.cpp | 2 +- src/core/composer/qgscomposerpicture.cpp | 76 +- src/core/composer/qgscomposerpolygon.cpp | 16 +- src/core/composer/qgscomposerpolyline.cpp | 10 +- src/core/composer/qgscomposerscalebar.cpp | 198 +-- src/core/composer/qgscomposershape.cpp | 80 +- src/core/composer/qgscomposertablecolumn.cpp | 50 +- src/core/composer/qgscomposertablev2.cpp | 114 +- src/core/composer/qgscomposerutils.cpp | 78 +- src/core/composer/qgscomposition.cpp | 224 ++-- .../composer/qgsdoubleboxscalebarstyle.cpp | 2 +- src/core/composer/qgsnumericscalebarstyle.cpp | 6 +- .../composer/qgssingleboxscalebarstyle.cpp | 2 +- src/core/composer/qgsticksscalebarstyle.cpp | 8 +- src/core/dxf/qgsdxfexport.cpp | 356 ++--- src/core/dxf/qgsdxfpaintengine.cpp | 8 +- src/core/effects/qgsblureffect.cpp | 24 +- src/core/effects/qgsblureffect.h | 2 +- src/core/effects/qgscoloreffect.cpp | 48 +- src/core/effects/qgscoloreffect.h | 2 +- src/core/effects/qgseffectstack.cpp | 10 +- src/core/effects/qgseffectstack.h | 2 +- src/core/effects/qgsgloweffect.cpp | 42 +- src/core/effects/qgsgloweffect.h | 4 +- src/core/effects/qgspainteffect.cpp | 32 +- src/core/effects/qgspainteffect.h | 2 +- src/core/effects/qgspainteffectregistry.cpp | 20 +- src/core/effects/qgsshadoweffect.cpp | 42 +- src/core/effects/qgsshadoweffect.h | 4 +- src/core/effects/qgstransformeffect.cpp | 48 +- src/core/effects/qgstransformeffect.h | 2 +- src/core/geometry/qgsabstractgeometry.h | 4 +- src/core/geometry/qgscircularstring.cpp | 6 +- src/core/geometry/qgscircularstring.h | 6 +- src/core/geometry/qgscompoundcurve.cpp | 10 +- src/core/geometry/qgscompoundcurve.h | 6 +- src/core/geometry/qgscurvepolygon.cpp | 28 +- src/core/geometry/qgscurvepolygon.h | 6 +- src/core/geometry/qgsgeometry.cpp | 2 +- src/core/geometry/qgsgeometry.h | 2 +- src/core/geometry/qgsgeometrycollection.cpp | 18 +- src/core/geometry/qgsgeometrycollection.h | 6 +- src/core/geometry/qgsgeometryfactory.cpp | 24 +- src/core/geometry/qgsgeometryutils.cpp | 16 +- src/core/geometry/qgsgeometryutils.h | 2 +- src/core/geometry/qgsgeos.h | 2 +- src/core/geometry/qgslinestring.cpp | 8 +- src/core/geometry/qgslinestring.h | 6 +- src/core/geometry/qgsmulticurve.cpp | 16 +- src/core/geometry/qgsmulticurve.h | 6 +- src/core/geometry/qgsmultilinestring.cpp | 16 +- src/core/geometry/qgsmultilinestring.h | 6 +- src/core/geometry/qgsmultipoint.cpp | 16 +- src/core/geometry/qgsmultipoint.h | 6 +- src/core/geometry/qgsmultipolygon.cpp | 20 +- src/core/geometry/qgsmultipolygon.h | 6 +- src/core/geometry/qgsmultisurface.cpp | 20 +- src/core/geometry/qgsmultisurface.h | 6 +- src/core/geometry/qgspointv2.cpp | 10 +- src/core/geometry/qgspointv2.h | 6 +- src/core/geometry/qgspolygon.h | 2 +- src/core/geometry/qgswkbptr.cpp | 4 +- src/core/geometry/qgswkbtypes.cpp | 124 +- .../gps/qextserialport/qextserialport.cpp | 2 +- src/core/gps/qgsgpsdconnection.cpp | 2 +- src/core/gps/qgsgpsdetector.cpp | 6 +- src/core/gps/qgsnmeaconnection.cpp | 16 +- src/core/layertree/qgslayertreegroup.cpp | 28 +- src/core/layertree/qgslayertreelayer.cpp | 24 +- src/core/layertree/qgslayertreemodel.cpp | 36 +- .../layertree/qgslayertreemodellegendnode.cpp | 14 +- src/core/layertree/qgslayertreenode.cpp | 4 +- .../layertree/qgslayertreeregistrybridge.cpp | 4 +- src/core/layertree/qgslayertreeutils.cpp | 126 +- src/core/qgis.cpp | 34 +- src/core/qgsactionmanager.cpp | 40 +- src/core/qgsaggregatecalculator.cpp | 40 +- src/core/qgsapplication.cpp | 96 +- src/core/qgsapplication.h | 6 +- src/core/qgsattributeeditorelement.cpp | 16 +- src/core/qgsattributetableconfig.cpp | 46 +- src/core/qgsbrowsermodel.cpp | 8 +- src/core/qgscolorramp.cpp | 108 +- src/core/qgscolorramp.h | 17 +- src/core/qgscolorscheme.cpp | 34 +- src/core/qgscolorschemeregistry.cpp | 2 +- src/core/qgsconditionalstyle.cpp | 56 +- src/core/qgscoordinatereferencesystem.cpp | 196 +-- src/core/qgscoordinatereferencesystem.h | 18 +- src/core/qgscoordinatetransform.cpp | 36 +- src/core/qgscoordinatetransform.h | 6 +- src/core/qgscoordinatetransform_p.h | 28 +- src/core/qgscoordinateutils.cpp | 18 +- src/core/qgsdartmeasurement.cpp | 12 +- src/core/qgsdatadefined.cpp | 40 +- src/core/qgsdataitem.cpp | 106 +- src/core/qgsdataprovider.h | 11 +- src/core/qgsdatasourceuri.cpp | 156 +-- src/core/qgsdatumtransformstore.cpp | 28 +- src/core/qgsdiagramrenderer.cpp | 246 ++-- src/core/qgsdiagramrenderer.h | 4 +- src/core/qgsdistancearea.cpp | 16 +- src/core/qgseditformconfig.cpp | 110 +- src/core/qgserror.cpp | 20 +- src/core/qgsexpression.cpp | 790 ++++++------ src/core/qgsexpression.h | 2 +- src/core/qgsexpressioncontext.cpp | 172 +-- src/core/qgsexpressionfieldbuffer.cpp | 40 +- src/core/qgsfeaturerequest.cpp | 18 +- src/core/qgsfield.cpp | 2 +- src/core/qgsfontutils.cpp | 46 +- src/core/qgsfontutils.h | 2 +- src/core/qgsgeometryvalidator.cpp | 2 +- src/core/qgsgml.cpp | 36 +- src/core/qgsgmlschema.cpp | 100 +- src/core/qgsinterval.cpp | 14 +- src/core/qgsjsonutils.cpp | 56 +- src/core/qgslabelingengine.cpp | 88 +- src/core/qgslayerdefinition.cpp | 48 +- src/core/qgslegendrenderer.cpp | 22 +- src/core/qgslegendsettings.cpp | 2 +- src/core/qgslogger.cpp | 12 +- src/core/qgslogger.h | 4 +- src/core/qgsmaplayer.cpp | 328 ++--- src/core/qgsmaplayer.h | 4 +- src/core/qgsmaplayerlegend.cpp | 14 +- src/core/qgsmaplayerstylemanager.cpp | 16 +- src/core/qgsmaprenderercustompainterjob.cpp | 2 +- src/core/qgsmaprendererjob.cpp | 6 +- src/core/qgsmapsettings.cpp | 34 +- src/core/qgsmapthemecollection.cpp | 52 +- src/core/qgsmessageoutput.cpp | 8 +- src/core/qgsmimedatautils.cpp | 12 +- src/core/qgsmultirenderchecker.cpp | 4 +- src/core/qgsnetworkaccessmanager.cpp | 58 +- src/core/qgsnetworkreplyparser.cpp | 6 +- src/core/qgsobjectcustomproperties.cpp | 26 +- src/core/qgsofflineediting.cpp | 140 +- src/core/qgsogcutils.cpp | 506 ++++---- src/core/qgsogrutils.cpp | 4 +- src/core/qgsoptionalexpression.cpp | 4 +- src/core/qgsowsconnection.cpp | 16 +- src/core/qgspallabeling.cpp | 840 ++++++------ src/core/qgspallabeling.h | 4 +- src/core/qgspoint.cpp | 18 +- src/core/qgsproject.cpp | 230 ++-- src/core/qgsprojectbadlayerhandler.cpp | 14 +- src/core/qgsprojectfiletransform.cpp | 376 +++--- src/core/qgsprojectproperty.cpp | 8 +- src/core/qgsprojectproperty.h | 2 +- src/core/qgsprojectversion.cpp | 4 +- src/core/qgsprojectversion.h | 6 +- src/core/qgsproviderregistry.cpp | 8 +- src/core/qgsrectangle.cpp | 8 +- src/core/qgsrelation.cpp | 48 +- src/core/qgsrelationmanager.cpp | 6 +- src/core/qgsrenderchecker.cpp | 62 +- src/core/qgsrenderchecker.h | 6 +- src/core/qgsrulebasedlabeling.cpp | 44 +- src/core/qgsruntimeprofiler.cpp | 2 +- src/core/qgsscaleexpression.cpp | 4 +- src/core/qgsscaleutils.cpp | 20 +- src/core/qgssnappingconfig.cpp | 124 +- src/core/qgssnappingutils.cpp | 28 +- src/core/qgssqlexpressioncompiler.cpp | 56 +- src/core/qgssqliteexpressioncompiler.cpp | 6 +- src/core/qgssqlstatement.cpp | 72 +- src/core/qgsstringutils.cpp | 24 +- src/core/qgstextrenderer.cpp | 776 +++++------ src/core/qgstolerance.cpp | 12 +- src/core/qgsunittypes.cpp | 70 +- src/core/qgsvectordataprovider.cpp | 10 +- src/core/qgsvectorfilewriter.cpp | 724 +++++------ src/core/qgsvectorfilewriter.h | 10 +- src/core/qgsvectorlayer.cpp | 420 +++--- src/core/qgsvectorlayereditbuffer.cpp | 6 +- src/core/qgsvectorlayerfeatureiterator.cpp | 6 +- src/core/qgsvectorlayerimport.cpp | 10 +- src/core/qgsvectorlayerjoinbuffer.cpp | 52 +- src/core/qgsvectorlayerlabeling.cpp | 10 +- src/core/qgsvectorlayerlabelprovider.cpp | 4 +- src/core/qgsvectorlayerrenderer.cpp | 12 +- src/core/qgsvirtuallayerdefinition.cpp | 48 +- src/core/qgsvirtuallayerdefinition.h | 4 +- src/core/qgsvirtuallayerdefinitionutils.cpp | 10 +- src/core/qgsxmlutils.cpp | 22 +- src/core/raster/qgsbilinearrasterresampler.h | 2 +- .../raster/qgsbrightnesscontrastfilter.cpp | 10 +- src/core/raster/qgscolorrampshader.cpp | 12 +- src/core/raster/qgscontrastenhancement.cpp | 42 +- src/core/raster/qgscubicrasterresampler.h | 2 +- src/core/raster/qgshillshaderenderer.cpp | 24 +- src/core/raster/qgshuesaturationfilter.cpp | 30 +- src/core/raster/qgsmultibandcolorrenderer.cpp | 28 +- src/core/raster/qgspalettedrasterrenderer.cpp | 32 +- src/core/raster/qgsraster.cpp | 14 +- src/core/raster/qgsrasterblock.cpp | 2 +- src/core/raster/qgsrasterchecker.cpp | 106 +- src/core/raster/qgsrasterchecker.h | 2 +- src/core/raster/qgsrasterdataprovider.cpp | 26 +- src/core/raster/qgsrasterdataprovider.h | 40 +- src/core/raster/qgsrasterfilewriter.cpp | 106 +- src/core/raster/qgsrasterinterface.cpp | 2 +- src/core/raster/qgsrasterinterface.h | 2 +- src/core/raster/qgsrasterlayer.cpp | 254 ++-- src/core/raster/qgsrasterprojector.cpp | 6 +- src/core/raster/qgsrasterrenderer.cpp | 50 +- src/core/raster/qgsrasterrenderer.h | 6 +- src/core/raster/qgsrasterrendererregistry.cpp | 22 +- src/core/raster/qgsrasterresamplefilter.cpp | 20 +- src/core/raster/qgsrastershader.cpp | 34 +- src/core/raster/qgsrastertransparency.cpp | 50 +- .../raster/qgssinglebandcolordatarenderer.cpp | 8 +- src/core/raster/qgssinglebandgrayrenderer.cpp | 20 +- .../qgssinglebandpseudocolorrenderer.cpp | 22 +- src/core/symbology-ng/qgs25drenderer.cpp | 24 +- src/core/symbology-ng/qgsarrowsymbollayer.cpp | 140 +- .../qgscategorizedsymbolrenderer.cpp | 140 +- src/core/symbology-ng/qgscptcityarchive.cpp | 140 +- .../symbology-ng/qgsellipsesymbollayer.cpp | 256 ++-- src/core/symbology-ng/qgsfillsymbollayer.cpp | 744 +++++------ src/core/symbology-ng/qgsfillsymbollayer.h | 6 +- .../qgsgeometrygeneratorsymbollayer.cpp | 18 +- .../qgsgraduatedsymbolrenderer.cpp | 202 +-- src/core/symbology-ng/qgsheatmaprenderer.cpp | 50 +- .../qgsinvertedpolygonrenderer.cpp | 28 +- .../symbology-ng/qgsinvertedpolygonrenderer.h | 2 +- src/core/symbology-ng/qgslinesymbollayer.cpp | 284 ++-- .../symbology-ng/qgsmarkersymbollayer.cpp | 580 ++++----- .../symbology-ng/qgsnullsymbolrenderer.cpp | 6 +- .../symbology-ng/qgspointclusterrenderer.cpp | 42 +- .../qgspointdisplacementrenderer.cpp | 74 +- .../symbology-ng/qgspointdistancerenderer.h | 2 +- src/core/symbology-ng/qgsrenderer.cpp | 50 +- src/core/symbology-ng/qgsrenderer.h | 4 +- src/core/symbology-ng/qgsrendererregistry.cpp | 20 +- .../symbology-ng/qgsrulebasedrenderer.cpp | 180 +-- src/core/symbology-ng/qgsrulebasedrenderer.h | 4 +- .../symbology-ng/qgssinglesymbolrenderer.cpp | 70 +- src/core/symbology-ng/qgsstyle.cpp | 106 +- src/core/symbology-ng/qgsstyle.h | 2 +- src/core/symbology-ng/qgssvgcache.cpp | 72 +- src/core/symbology-ng/qgssymbol.cpp | 84 +- src/core/symbology-ng/qgssymbollayer.cpp | 138 +- src/core/symbology-ng/qgssymbollayer.h | 4 +- .../symbology-ng/qgssymbollayerregistry.cpp | 36 +- src/core/symbology-ng/qgssymbollayerutils.cpp | 786 +++++------ .../symbology-ng/qgssymbologyconversion.cpp | 148 +-- .../qgsvectorfieldsymbollayer.cpp | 90 +- .../symbology-ng/qgsvectorfieldsymbollayer.h | 2 +- .../attributetable/qgsattributetablemodel.cpp | 6 +- .../attributetable/qgsattributetableview.cpp | 10 +- src/gui/attributetable/qgsdualview.cpp | 16 +- .../attributetable/qgsfeaturelistmodel.cpp | 4 +- .../qgsfeaturelistviewdelegate.cpp | 4 +- .../qgsfieldconditionalformatwidget.cpp | 10 +- .../qgsorganizetablecolumnsdialog.cpp | 12 +- src/gui/auth/qgsauthauthoritieseditor.cpp | 30 +- src/gui/auth/qgsauthcertificateinfo.cpp | 58 +- .../auth/qgsauthcerttrustpolicycombobox.cpp | 8 +- src/gui/auth/qgsauthconfigedit.cpp | 2 +- src/gui/auth/qgsauthconfigeditor.cpp | 14 +- src/gui/auth/qgsauthconfigidedit.cpp | 6 +- src/gui/auth/qgsauthconfigselect.cpp | 2 +- src/gui/auth/qgsautheditorwidgets.cpp | 16 +- src/gui/auth/qgsauthguiutils.cpp | 16 +- src/gui/auth/qgsauthguiutils.h | 6 +- src/gui/auth/qgsauthidentitieseditor.cpp | 10 +- src/gui/auth/qgsauthimportcertdialog.cpp | 10 +- src/gui/auth/qgsauthimportidentitydialog.cpp | 24 +- src/gui/auth/qgsauthmasterpassresetdialog.cpp | 8 +- src/gui/auth/qgsauthserverseditor.cpp | 10 +- src/gui/auth/qgsauthsslconfigwidget.cpp | 16 +- src/gui/auth/qgsauthsslerrorsdialog.cpp | 12 +- src/gui/auth/qgsauthsslimportdialog.cpp | 20 +- src/gui/auth/qgsauthtrustedcasdialog.cpp | 10 +- .../core/qgseditorwidgetautoconf.cpp | 2 +- .../core/qgseditorwidgetregistry.cpp | 82 +- .../core/qgseditorwidgetwrapper.cpp | 6 +- .../core/qgssearchwidgetwrapper.cpp | 2 +- .../core/qgssearchwidgetwrapper.h | 2 +- .../editorwidgets/qgscheckboxconfigdlg.cpp | 8 +- .../qgscheckboxsearchwidgetwrapper.cpp | 6 +- .../qgscheckboxwidgetfactory.cpp | 8 +- .../qgscheckboxwidgetwrapper.cpp | 6 +- .../editorwidgets/qgscolorwidgetwrapper.cpp | 2 +- src/gui/editorwidgets/qgsdatetimeedit.cpp | 10 +- .../editorwidgets/qgsdatetimeeditconfig.cpp | 16 +- .../editorwidgets/qgsdatetimeeditfactory.cpp | 24 +- .../editorwidgets/qgsdatetimeeditwrapper.cpp | 16 +- .../qgsdatetimesearchwidgetwrapper.cpp | 10 +- .../qgsdefaultsearchwidgetwrapper.cpp | 26 +- .../qgsexternalresourceconfigdlg.cpp | 72 +- .../qgsexternalresourcewidgetfactory.cpp | 84 +- .../qgsexternalresourcewidgetwrapper.cpp | 46 +- .../qgsfilenamewidgetwrapper.cpp | 8 +- .../qgskeyvaluewidgetfactory.cpp | 2 +- .../editorwidgets/qgslistwidgetfactory.cpp | 2 +- .../editorwidgets/qgsmultiedittoolbutton.cpp | 8 +- src/gui/editorwidgets/qgsphotoconfigdlg.cpp | 8 +- .../editorwidgets/qgsphotowidgetfactory.cpp | 8 +- .../editorwidgets/qgsphotowidgetwrapper.cpp | 18 +- src/gui/editorwidgets/qgsrangeconfigdlg.cpp | 40 +- .../editorwidgets/qgsrangewidgetfactory.cpp | 28 +- .../editorwidgets/qgsrangewidgetwrapper.cpp | 32 +- .../qgsrelationreferenceconfigdlg.cpp | 40 +- .../qgsrelationreferencefactory.cpp | 54 +- ...gsrelationreferencesearchwidgetwrapper.cpp | 22 +- .../qgsrelationreferencewidget.cpp | 46 +- .../qgsrelationreferencewidgetwrapper.cpp | 22 +- .../qgsrelationwidgetwrapper.cpp | 2 +- .../qgssearchwidgettoolbutton.cpp | 2 +- .../editorwidgets/qgstexteditconfigdlg.cpp | 8 +- .../qgstexteditwidgetfactory.cpp | 8 +- src/gui/editorwidgets/qgstexteditwrapper.cpp | 16 +- .../qgsuniquevaluesconfigdlg.cpp | 4 +- .../qgsuniquevaluewidgetfactory.cpp | 4 +- .../qgsuniquevaluewidgetwrapper.cpp | 8 +- .../editorwidgets/qgsvaluemapconfigdlg.cpp | 14 +- .../qgsvaluemapsearchwidgetwrapper.cpp | 6 +- .../qgsvaluemapwidgetfactory.cpp | 14 +- .../qgsvaluemapwidgetwrapper.cpp | 4 +- .../qgsvaluerelationconfigdlg.cpp | 34 +- .../qgsvaluerelationsearchwidgetwrapper.cpp | 18 +- .../qgsvaluerelationwidgetfactory.cpp | 40 +- .../qgsvaluerelationwidgetwrapper.cpp | 20 +- src/gui/editorwidgets/qgswebviewconfigdlg.cpp | 8 +- .../editorwidgets/qgswebviewwidgetfactory.cpp | 8 +- .../editorwidgets/qgswebviewwidgetwrapper.cpp | 16 +- .../qgseffectstackpropertieswidget.cpp | 2 +- .../qgspainteffectpropertieswidget.cpp | 18 +- src/gui/effects/qgspainteffectwidget.cpp | 16 +- .../layertree/qgscustomlayerorderwidget.cpp | 8 +- .../qgslayertreeembeddedconfigwidget.cpp | 12 +- .../qgslayertreeembeddedwidgetsimpl.cpp | 4 +- .../layertree/qgslayertreemapcanvasbridge.cpp | 26 +- src/gui/layertree/qgslayertreeview.cpp | 12 +- .../qgslayertreeviewdefaultactions.cpp | 20 +- src/gui/qgisgui.cpp | 14 +- src/gui/qgsadvanceddigitizingdockwidget.cpp | 16 +- src/gui/qgsannotationitem.cpp | 68 +- src/gui/qgsattributeform.cpp | 46 +- src/gui/qgsattributeformeditorwidget.cpp | 4 +- src/gui/qgsattributeformlegacyinterface.cpp | 16 +- src/gui/qgsblendmodecombobox.cpp | 10 +- src/gui/qgsbrowsertreeview.cpp | 6 +- src/gui/qgsbusyindicatordialog.h | 2 +- src/gui/qgscharacterselectdialog.cpp | 2 +- src/gui/qgscodeeditor.cpp | 10 +- src/gui/qgscodeeditor.h | 2 +- src/gui/qgscodeeditorcss.cpp | 2 +- src/gui/qgscodeeditorhtml.cpp | 2 +- src/gui/qgscodeeditorpython.cpp | 2 +- src/gui/qgscollapsiblegroupbox.cpp | 46 +- src/gui/qgscolorbutton.cpp | 6 +- src/gui/qgscolorbutton.h | 2 +- src/gui/qgscolordialog.cpp | 8 +- src/gui/qgscolorschemelist.cpp | 26 +- src/gui/qgscolorswatchgrid.cpp | 2 +- src/gui/qgscolorwidgets.cpp | 16 +- src/gui/qgscomposerruler.cpp | 2 +- src/gui/qgscomposerview.cpp | 18 +- src/gui/qgscompoundcolorwidget.cpp | 90 +- src/gui/qgsconfigureshortcutsdialog.cpp | 34 +- src/gui/qgscredentialdialog.cpp | 12 +- src/gui/qgsdatadefinedbutton.cpp | 94 +- src/gui/qgsdatadefinedbutton.h | 14 +- src/gui/qgsdatumtransformdialog.cpp | 36 +- src/gui/qgsdetaileditemdelegate.cpp | 8 +- src/gui/qgsencodingfiledialog.cpp | 4 +- src/gui/qgserrordialog.cpp | 6 +- src/gui/qgsexpressionbuilderdialog.cpp | 4 +- src/gui/qgsexpressionbuilderdialog.h | 6 +- src/gui/qgsexpressionbuilderwidget.cpp | 130 +- src/gui/qgsexpressionbuilderwidget.h | 10 +- src/gui/qgsexpressionhighlighter.cpp | 4 +- src/gui/qgsexpressionlineedit.cpp | 4 +- src/gui/qgsexpressionselectiondialog.cpp | 18 +- src/gui/qgsexternalresourcewidget.cpp | 2 +- src/gui/qgsfieldcombobox.cpp | 2 +- src/gui/qgsfieldexpressionwidget.cpp | 6 +- src/gui/qgsfieldvalidator.cpp | 12 +- src/gui/qgsfieldvalidator.h | 7 +- src/gui/qgsfilewidget.cpp | 18 +- src/gui/qgsfilterlineedit.cpp | 2 +- src/gui/qgsformannotationitem.cpp | 22 +- src/gui/qgsgenericprojectionselector.cpp | 6 +- src/gui/qgsgenericprojectionselector.h | 2 +- src/gui/qgsgradientcolorrampdialog.cpp | 46 +- src/gui/qgsgradientstopeditor.cpp | 2 +- src/gui/qgshighlight.cpp | 4 +- src/gui/qgshistogramwidget.cpp | 8 +- src/gui/qgshtmlannotationitem.cpp | 30 +- src/gui/qgsidentifymenu.cpp | 34 +- src/gui/qgskeyvaluewidget.cpp | 2 +- src/gui/qgslegendfilterbutton.cpp | 4 +- src/gui/qgslonglongvalidator.h | 2 +- src/gui/qgsmanageconnectionsdialog.cpp | 414 +++--- src/gui/qgsmanageconnectionsdialog.h | 9 +- src/gui/qgsmapcanvas.cpp | 28 +- src/gui/qgsmapcanvas.h | 2 +- src/gui/qgsmapcanvassnapper.cpp | 38 +- src/gui/qgsmapcanvastracer.cpp | 4 +- src/gui/qgsmaplayerstylemanagerwidget.cpp | 22 +- src/gui/qgsmapoverviewcanvas.cpp | 4 +- src/gui/qgsmaptip.cpp | 2 +- src/gui/qgsmaptool.cpp | 2 +- src/gui/qgsmaptoolcapture.cpp | 6 +- src/gui/qgsmaptooledit.cpp | 30 +- src/gui/qgsmaptoolidentify.cpp | 40 +- src/gui/qgsmessagebar.cpp | 18 +- src/gui/qgsmessagebaritem.cpp | 24 +- src/gui/qgsmessagelogviewer.cpp | 4 +- src/gui/qgsmessageviewer.cpp | 6 +- src/gui/qgsnewgeopackagelayerdialog.cpp | 34 +- src/gui/qgsnewhttpconnection.cpp | 52 +- src/gui/qgsnewhttpconnection.h | 2 +- src/gui/qgsnewmemorylayerdialog.cpp | 30 +- src/gui/qgsnewnamedialog.cpp | 12 +- src/gui/qgsnewvectorlayerdialog.cpp | 40 +- src/gui/qgsoptionsdialogbase.cpp | 32 +- src/gui/qgsorderbydialog.cpp | 4 +- src/gui/qgsowssourceselect.cpp | 46 +- src/gui/qgspanelwidget.cpp | 2 +- src/gui/qgspanelwidgetstack.cpp | 2 +- src/gui/qgsprojectbadlayerguihandler.cpp | 4 +- src/gui/qgsprojectionselectionwidget.cpp | 6 +- src/gui/qgsprojectionselector.cpp | 70 +- src/gui/qgsquerybuilder.cpp | 56 +- src/gui/qgsrasterformatsaveoptionswidget.cpp | 104 +- src/gui/qgsrasterformatsaveoptionswidget.h | 7 +- src/gui/qgsrasterlayersaveasdialog.cpp | 28 +- src/gui/qgsrasterpyramidsoptionswidget.cpp | 12 +- src/gui/qgsrasterpyramidsoptionswidget.h | 6 +- src/gui/qgsrelationeditorwidget.cpp | 32 +- src/gui/qgsscalecombobox.cpp | 8 +- src/gui/qgsscalerangewidget.cpp | 8 +- src/gui/qgsscalewidget.cpp | 2 +- src/gui/qgssearchquerybuilder.cpp | 46 +- src/gui/qgsshortcutsmanager.cpp | 4 +- src/gui/qgsshortcutsmanager.h | 2 +- src/gui/qgssourceselectdialog.cpp | 30 +- src/gui/qgssqlcomposerdialog.cpp | 116 +- src/gui/qgssublayersdialog.cpp | 6 +- src/gui/qgssubstitutionlistwidget.cpp | 10 +- src/gui/qgssvgannotationitem.cpp | 8 +- src/gui/qgstextannotationitem.cpp | 8 +- src/gui/qgstextformatwidget.cpp | 42 +- src/gui/qgsvariableeditorwidget.cpp | 16 +- src/gui/raster/qgsrasterhistogramwidget.cpp | 66 +- src/gui/raster/qgsrasterminmaxwidget.cpp | 12 +- src/gui/raster/qgsrasterrendererwidget.cpp | 4 +- .../raster/qgsrastertransparencywidget.cpp | 10 +- .../qgsrendererrasterpropertieswidget.cpp | 22 +- ...qgssinglebandpseudocolorrendererwidget.cpp | 24 +- src/gui/symbology-ng/qgs25drendererwidget.cpp | 16 +- .../qgsarrowsymbollayerwidget.cpp | 16 +- .../qgscategorizedsymbolrendererwidget.cpp | 12 +- src/gui/symbology-ng/qgscolorrampcombobox.cpp | 20 +- .../qgscptcitycolorrampdialog.cpp | 78 +- src/gui/symbology-ng/qgsdashspacedialog.cpp | 4 +- .../qgsellipsesymbollayerwidget.cpp | 34 +- .../qgsgraduatedsymbolrendererwidget.cpp | 14 +- .../qgsinvertedpolygonrendererwidget.cpp | 2 +- .../symbology-ng/qgslayerpropertieswidget.cpp | 42 +- .../qgspointclusterrendererwidget.cpp | 2 +- .../qgspointdisplacementrendererwidget.cpp | 10 +- .../qgsrendererpropertiesdialog.cpp | 24 +- src/gui/symbology-ng/qgsrendererwidget.cpp | 2 +- .../qgsrulebasedrendererwidget.cpp | 50 +- .../qgssmartgroupeditordialog.cpp | 2 +- .../qgsstyleexportimportdialog.cpp | 34 +- .../qgsstylegroupselectiondialog.cpp | 22 +- .../symbology-ng/qgsstylemanagerdialog.cpp | 48 +- src/gui/symbology-ng/qgssvgselectorwidget.cpp | 18 +- src/gui/symbology-ng/qgssymbollayerwidget.cpp | 258 ++-- .../symbology-ng/qgssymbollevelsdialog.cpp | 4 +- .../symbology-ng/qgssymbolselectordialog.cpp | 12 +- src/gui/symbology-ng/qgssymbolslistwidget.cpp | 8 +- src/gui/symbology-ng/qgssymbolslistwidget.h | 2 +- .../qgsvectorfieldsymbollayerwidget.cpp | 8 +- src/helpviewer/main.cpp | 16 +- src/helpviewer/qgshelpviewer.cpp | 4 +- .../coordinate_capture/coordinatecapture.cpp | 12 +- src/plugins/dxf2shp_converter/builder.cpp | 2 +- .../dxf2shp_converter/dxf2shpconverter.cpp | 12 +- .../dxf2shp_converter/dxf2shpconvertergui.cpp | 24 +- .../evisdatabaseconnection.cpp | 40 +- .../evisdatabaseconnectiongui.cpp | 96 +- .../evisdatabaselayerfieldselectiongui.cpp | 4 +- .../evisquerydefinition.cpp | 12 +- .../databaseconnection/evisquerydefinition.h | 2 +- .../evis/eventbrowser/evisconfiguration.cpp | 22 +- .../evisgenericeventbrowsergui.cpp | 58 +- src/plugins/evis/evis.cpp | 20 +- .../checks/qgsgeometryanglecheck.h | 2 +- .../checks/qgsgeometryareacheck.h | 2 +- .../checks/qgsgeometrycontainedcheck.h | 2 +- .../qgsgeometrydegeneratepolygoncheck.h | 2 +- .../checks/qgsgeometryduplicatecheck.h | 4 +- .../checks/qgsgeometryduplicatenodescheck.h | 2 +- .../checks/qgsgeometrygapcheck.h | 2 +- .../checks/qgsgeometryholecheck.h | 2 +- .../checks/qgsgeometrymultipartcheck.h | 2 +- .../checks/qgsgeometryoverlapcheck.h | 2 +- .../checks/qgsgeometrysegmentlengthcheck.h | 2 +- .../checks/qgsgeometryselfintersectioncheck.h | 2 +- .../checks/qgsgeometrysliverpolygoncheck.h | 2 +- .../checks/qgsgeometrytypecheck.h | 4 +- .../qgsgeometrycheckerplugin.h | 2 +- .../qgsgeometrycheckfactory.cpp | 2 +- .../ui/qgsgeometrycheckerdialog.cpp | 4 +- .../ui/qgsgeometrycheckerfixsummarydialog.cpp | 4 +- .../ui/qgsgeometrycheckerresulttab.cpp | 28 +- .../ui/qgsgeometrycheckersetuptab.cpp | 20 +- .../ui/qgsgeometrycheckfixdialog.cpp | 2 +- .../qgsgeometrysnapperdialog.cpp | 22 +- .../qgsgeometrysnapperplugin.h | 2 +- .../georeferencer/qgsgcpcanvasitem.cpp | 10 +- src/plugins/georeferencer/qgsgcplistmodel.cpp | 8 +- .../georeferencer/qgsgeorefconfigdialog.cpp | 38 +- src/plugins/georeferencer/qgsgeorefplugin.cpp | 8 +- .../georeferencer/qgsgeorefplugingui.cpp | 224 ++-- .../georeferencer/qgsgeorefvalidators.cpp | 8 +- .../georeferencer/qgsmapcoordsdialog.cpp | 4 +- .../georeferencer/qgsresidualplotitem.cpp | 4 +- .../qgstransformsettingsdialog.cpp | 92 +- src/plugins/gps_importer/qgsbabelformat.cpp | 34 +- src/plugins/gps_importer/qgsbabelformat.h | 2 +- src/plugins/gps_importer/qgsgpsdevice.cpp | 36 +- .../gps_importer/qgsgpsdevicedialog.cpp | 34 +- src/plugins/gps_importer/qgsgpsdevicedialog.h | 2 +- src/plugins/gps_importer/qgsgpsplugin.cpp | 266 ++-- src/plugins/gps_importer/qgsgpsplugingui.cpp | 86 +- src/plugins/grass/qgsgrasseditrenderer.cpp | 40 +- src/plugins/grass/qgsgrassmapcalc.cpp | 204 +-- src/plugins/grass/qgsgrassmapcalc.h | 6 +- src/plugins/grass/qgsgrassmodule.cpp | 72 +- src/plugins/grass/qgsgrassmoduleinput.cpp | 64 +- src/plugins/grass/qgsgrassmoduleinput.h | 2 +- src/plugins/grass/qgsgrassmoduleoptions.cpp | 64 +- src/plugins/grass/qgsgrassmoduleparam.cpp | 202 +-- src/plugins/grass/qgsgrassnewmapset.cpp | 68 +- src/plugins/grass/qgsgrassplugin.cpp | 80 +- src/plugins/grass/qgsgrassselect.cpp | 16 +- src/plugins/grass/qgsgrassshell.cpp | 16 +- src/plugins/grass/qgsgrasstools.cpp | 44 +- src/plugins/grass/qgsgrassutils.cpp | 12 +- src/plugins/grass/qtermwidget/ColorScheme.cpp | 26 +- src/plugins/grass/qtermwidget/Filter.cpp | 12 +- .../grass/qtermwidget/KeyboardTranslator.cpp | 80 +- src/plugins/grass/qtermwidget/Pty.cpp | 4 +- src/plugins/grass/qtermwidget/Session.cpp | 6 +- .../qtermwidget/TerminalCharacterDecoder.cpp | 8 +- .../grass/qtermwidget/TerminalDisplay.cpp | 14 +- src/plugins/grass/qtermwidget/kprocess.cpp | 8 +- src/plugins/grass/qtermwidget/kptydevice.cpp | 10 +- src/plugins/grass/qtermwidget/qtermwidget.cpp | 10 +- src/plugins/grass/qtermwidget/tools.cpp | 4 +- src/plugins/heatmap/heatmap.cpp | 4 +- src/plugins/heatmap/heatmapgui.cpp | 70 +- .../interpolation/qgsinterpolationdialog.cpp | 18 +- .../interpolation/qgsinterpolationplugin.cpp | 4 +- .../qgstininterpolatordialog.cpp | 6 +- .../offline_editing_plugin.cpp | 8 +- .../offline_editing_plugin_gui.cpp | 14 +- .../oracle_raster/qgsoracle_plugin.cpp | 4 +- .../oracle_raster/qgsoracleconnect_ui.cpp | 4 +- .../oracle_raster/qgsselectgeoraster_ui.cpp | 34 +- src/plugins/qgisplugin.h | 8 +- .../qgsrasterterrainanalysisdialog.cpp | 48 +- .../qgsrasterterrainanalysisplugin.cpp | 14 +- src/plugins/roadgraph/exportdlg.cpp | 8 +- .../roadgraph/linevectorlayersettings.cpp | 40 +- .../roadgraph/linevectorlayerwidget.cpp | 4 +- src/plugins/roadgraph/roadgraphplugin.cpp | 20 +- src/plugins/roadgraph/shortestpathwidget.cpp | 6 +- src/plugins/roadgraph/units.cpp | 22 +- .../spatialquery/qgsspatialquerydialog.cpp | 40 +- .../spatialquery/qgsspatialqueryplugin.cpp | 8 +- src/plugins/topology/dockModel.cpp | 2 +- src/plugins/topology/rulesDialog.cpp | 30 +- src/plugins/topology/topol.cpp | 4 +- .../qgszonalstatisticsdialog.cpp | 12 +- .../qgszonalstatisticsplugin.cpp | 4 +- src/providers/arcgisrest/qgsafsdataitems.cpp | 26 +- src/providers/arcgisrest/qgsafsprovider.cpp | 64 +- src/providers/arcgisrest/qgsafsprovider.h | 2 +- .../arcgisrest/qgsafsproviderextern.cpp | 14 +- .../arcgisrest/qgsafssourceselect.cpp | 44 +- src/providers/arcgisrest/qgsamsdataitems.cpp | 26 +- src/providers/arcgisrest/qgsamsprovider.cpp | 126 +- src/providers/arcgisrest/qgsamsprovider.h | 4 +- .../arcgisrest/qgsamsproviderextern.cpp | 14 +- .../arcgisrest/qgsamssourceselect.cpp | 34 +- .../arcgisrest/qgsarcgisrestutils.cpp | 146 +-- src/providers/db2/qgsdb2dataitems.cpp | 30 +- .../db2/qgsdb2expressioncompiler.cpp | 36 +- src/providers/db2/qgsdb2featureiterator.cpp | 34 +- src/providers/db2/qgsdb2geometrycolumns.cpp | 10 +- src/providers/db2/qgsdb2newconnection.cpp | 14 +- src/providers/db2/qgsdb2provider.cpp | 186 +-- src/providers/db2/qgsdb2sourceselect.cpp | 46 +- src/providers/db2/qgsdb2tablemodel.cpp | 40 +- .../qgsdelimitedtextfeatureiterator.cpp | 6 +- .../delimitedtext/qgsdelimitedtextfile.cpp | 122 +- .../delimitedtext/qgsdelimitedtextfile.h | 2 +- .../qgsdelimitedtextprovider.cpp | 114 +- .../qgsdelimitedtextsourceselect.cpp | 60 +- src/providers/gdal/qgsgdaldataitems.cpp | 44 +- src/providers/gdal/qgsgdalprovider.cpp | 230 ++-- src/providers/gdal/qgsgdalprovider.h | 2 +- src/providers/gdal/qgsgdalproviderbase.cpp | 2 +- src/providers/gpx/gpsdata.cpp | 34 +- src/providers/gpx/gpsdata.h | 6 +- src/providers/gpx/qgsgpxprovider.cpp | 10 +- src/providers/grass/qgis.v.in.cpp | 4 +- src/providers/grass/qgsgrass.cpp | 260 ++-- src/providers/grass/qgsgrass.h | 2 +- .../grass/qgsgrassfeatureiterator.cpp | 2 +- src/providers/grass/qgsgrassimport.cpp | 42 +- src/providers/grass/qgsgrassoptions.cpp | 20 +- src/providers/grass/qgsgrassprovider.cpp | 46 +- .../grass/qgsgrassprovidermodule.cpp | 90 +- .../grass/qgsgrassrasterprovider.cpp | 46 +- .../grass/qgsgrassrasterprovidermodule.cpp | 4 +- src/providers/grass/qgsgrassvector.cpp | 8 +- src/providers/grass/qgsgrassvectormap.cpp | 6 +- src/providers/grass/qgsgrassvectormap.h | 2 +- .../grass/qgsgrassvectormaplayer.cpp | 74 +- src/providers/memory/qgsmemoryprovider.cpp | 106 +- src/providers/mssql/qgsmssqldataitems.cpp | 40 +- .../mssql/qgsmssqlexpressioncompiler.cpp | 4 +- .../mssql/qgsmssqlfeatureiterator.cpp | 32 +- src/providers/mssql/qgsmssqlnewconnection.cpp | 28 +- src/providers/mssql/qgsmssqlprovider.cpp | 358 ++--- src/providers/mssql/qgsmssqlsourceselect.cpp | 68 +- src/providers/mssql/qgsmssqltablemodel.cpp | 34 +- src/providers/ogr/qgsogrconnpool.h | 2 +- src/providers/ogr/qgsogrdataitems.cpp | 46 +- .../ogr/qgsogrexpressioncompiler.cpp | 12 +- src/providers/ogr/qgsogrfeatureiterator.cpp | 6 +- src/providers/ogr/qgsogrprovider.cpp | 548 ++++---- src/providers/ogr/qgsogrprovider.h | 2 +- src/providers/ows/qgsowsdataitems.cpp | 8 +- src/providers/ows/qgsowsprovider.cpp | 4 +- src/providers/postgres/qgspgnewconnection.cpp | 16 +- src/providers/postgres/qgspgsourceselect.cpp | 28 +- src/providers/postgres/qgspgtablemodel.cpp | 16 +- src/providers/postgres/qgspostgresconn.cpp | 268 ++-- src/providers/postgres/qgspostgresconn.h | 6 +- .../postgres/qgspostgresdataitems.cpp | 34 +- .../postgres/qgspostgresfeatureiterator.cpp | 56 +- .../postgres/qgspostgresprovider.cpp | 632 ++++----- src/providers/postgres/qgspostgresprovider.h | 2 +- .../postgres/qgspostgrestransaction.cpp | 10 +- .../spatialite/qgsspatialiteconnection.cpp | 22 +- .../spatialite/qgsspatialitedataitems.cpp | 30 +- .../qgsspatialitefeatureiterator.cpp | 66 +- .../spatialite/qgsspatialiteprovider.cpp | 270 ++-- .../spatialite/qgsspatialiteprovider.h | 4 +- .../spatialite/qgsspatialitesourceselect.cpp | 52 +- .../spatialite/qgsspatialitetablemodel.cpp | 18 +- .../qgsvirtuallayerfeatureiterator.cpp | 20 +- .../virtual/qgsvirtuallayerprovider.cpp | 42 +- .../virtual/qgsvirtuallayerprovider.h | 6 +- .../virtual/qgsvirtuallayerqueryparser.cpp | 34 +- .../virtual/qgsvirtuallayersourceselect.cpp | 22 +- .../virtual/qgsvirtuallayersqlitehelper.cpp | 6 +- .../virtual/qgsvirtuallayersqlitemodule.cpp | 50 +- src/providers/wcs/qgswcscapabilities.cpp | 204 +-- src/providers/wcs/qgswcsdataitems.cpp | 38 +- src/providers/wcs/qgswcsprovider.cpp | 210 +-- src/providers/wcs/qgswcsprovider.h | 2 +- src/providers/wcs/qgswcssourceselect.cpp | 18 +- src/providers/wfs/qgswfscapabilities.cpp | 242 ++-- src/providers/wfs/qgswfsconnection.cpp | 10 +- src/providers/wfs/qgswfsconstants.cpp | 58 +- src/providers/wfs/qgswfsdataitems.cpp | 16 +- src/providers/wfs/qgswfsdatasourceuri.cpp | 22 +- src/providers/wfs/qgswfsdatasourceuri.h | 2 +- .../wfs/qgswfsdescribefeaturetype.cpp | 6 +- src/providers/wfs/qgswfsfeatureiterator.cpp | 66 +- src/providers/wfs/qgswfsprovider.cpp | 206 +-- src/providers/wfs/qgswfsrequest.cpp | 26 +- src/providers/wfs/qgswfsshareddata.cpp | 138 +- src/providers/wfs/qgswfssourceselect.cpp | 38 +- .../wfs/qgswfstransactionrequest.cpp | 2 +- src/providers/wfs/qgswfsutils.cpp | 16 +- src/providers/wms/qgstilescalewidget.cpp | 18 +- src/providers/wms/qgswmscapabilities.cpp | 654 +++++----- src/providers/wms/qgswmscapabilities.h | 4 +- src/providers/wms/qgswmsconnection.cpp | 28 +- src/providers/wms/qgswmsdataitems.cpp | 44 +- src/providers/wms/qgswmsdataitems.h | 6 +- src/providers/wms/qgswmsprovider.cpp | 926 ++++++------- src/providers/wms/qgswmssourceselect.cpp | 70 +- src/providers/wms/qgswmtsdimensions.cpp | 4 +- src/providers/wms/qgsxyzconnection.cpp | 10 +- src/python/qgspythonutilsimpl.cpp | 66 +- src/server/qgis_map_serv.cpp | 2 +- src/server/qgsaccesscontrol.cpp | 4 +- src/server/qgsaccesscontrolfilter.cpp | 10 +- src/server/qgsconfigcache.cpp | 18 +- src/server/qgsconfigparserutils.cpp | 58 +- src/server/qgshostedrdsbuilder.cpp | 8 +- src/server/qgshostedvdsbuilder.cpp | 10 +- src/server/qgshttprequesthandler.cpp | 182 +-- src/server/qgsinterpolationlayerbuilder.cpp | 14 +- src/server/qgsmaprenderer.cpp | 50 +- src/server/qgsmslayerbuilder.cpp | 12 +- src/server/qgsmslayercache.cpp | 18 +- src/server/qgsmsutils.cpp | 8 +- src/server/qgsowsserver.cpp | 2 +- src/server/qgspostrequesthandler.cpp | 24 +- src/server/qgsremotedatasourcebuilder.cpp | 12 +- src/server/qgsremoteowsbuilder.cpp | 68 +- src/server/qgssentdatasourcebuilder.cpp | 12 +- src/server/qgsserver.cpp | 108 +- src/server/qgsserverplugins.cpp | 20 +- src/server/qgsserverprojectparser.cpp | 396 +++--- src/server/qgsserverstreamingdevice.cpp | 2 +- src/server/qgssldconfigparser.cpp | 144 +-- src/server/qgssoaprequesthandler.cpp | 318 ++--- src/server/qgswcsprojectparser.cpp | 146 +-- src/server/qgswcsserver.cpp | 160 +-- src/server/qgswfsprojectparser.cpp | 172 +-- src/server/qgswfsserver.cpp | 614 ++++----- src/server/qgswmsconfigparser.cpp | 92 +- src/server/qgswmsprojectparser.cpp | 664 +++++----- src/server/qgswmsserver.cpp | 816 ++++++------ src/server/qgswmsserver.h | 4 +- tests/bench/main.cpp | 38 +- tests/bench/qgsbench.cpp | 36 +- tests/src/analysis/testopenstreetmap.cpp | 4 +- tests/src/analysis/testqgsalignraster.cpp | 26 +- .../src/analysis/testqgsrastercalculator.cpp | 38 +- tests/src/analysis/testqgsvectoranalyzer.cpp | 12 +- tests/src/analysis/testqgszonalstatistics.cpp | 6 +- tests/src/app/testqgisappclipboard.cpp | 64 +- tests/src/app/testqgisapppython.cpp | 8 +- tests/src/app/testqgsattributetable.cpp | 24 +- tests/src/app/testqgsfieldcalculator.cpp | 24 +- .../src/app/testqgsmaptoolidentifyaction.cpp | 54 +- tests/src/app/testqgsmaptoolselect.cpp | 10 +- tests/src/app/testqgsmeasuretool.cpp | 14 +- .../app/testqgsvectorlayersaveasdialog.cpp | 10 +- tests/src/core/testcontrastenhancements.cpp | 2 +- tests/src/core/testqgis.cpp | 36 +- tests/src/core/testqgs25drenderer.cpp | 16 +- tests/src/core/testqgsapplication.cpp | 10 +- tests/src/core/testqgsatlascomposition.cpp | 52 +- tests/src/core/testqgsauthconfig.cpp | 46 +- tests/src/core/testqgsauthcrypto.cpp | 8 +- tests/src/core/testqgsauthmanager.cpp | 38 +- tests/src/core/testqgsblendmodes.cpp | 12 +- tests/src/core/testqgscentroidfillsymbol.cpp | 8 +- tests/src/core/testqgscolorscheme.cpp | 12 +- tests/src/core/testqgscolorschemeregistry.cpp | 10 +- tests/src/core/testqgscomposerdd.cpp | 10 +- tests/src/core/testqgscomposereffects.cpp | 10 +- tests/src/core/testqgscomposergroup.cpp | 8 +- tests/src/core/testqgscomposerhtml.cpp | 72 +- tests/src/core/testqgscomposerlabel.cpp | 60 +- tests/src/core/testqgscomposermap.cpp | 66 +- tests/src/core/testqgscomposermapgrid.cpp | 116 +- tests/src/core/testqgscomposermapoverview.cpp | 28 +- tests/src/core/testqgscomposermultiframe.cpp | 42 +- tests/src/core/testqgscomposerobject.cpp | 46 +- tests/src/core/testqgscomposerpaper.cpp | 22 +- tests/src/core/testqgscomposerpicture.cpp | 86 +- tests/src/core/testqgscomposerrotation.cpp | 22 +- tests/src/core/testqgscomposerscalebar.cpp | 36 +- tests/src/core/testqgscomposershapes.cpp | 22 +- tests/src/core/testqgscomposertablev2.cpp | 286 ++-- tests/src/core/testqgscomposerutils.cpp | 116 +- tests/src/core/testqgscomposition.cpp | 46 +- tests/src/core/testqgsconnectionpool.cpp | 10 +- .../core/testqgscoordinatereferencesystem.cpp | 94 +- tests/src/core/testqgsdatadefined.cpp | 68 +- tests/src/core/testqgsdataitem.cpp | 40 +- tests/src/core/testqgsdiagram.cpp | 10 +- tests/src/core/testqgsdistancearea.cpp | 38 +- tests/src/core/testqgsellipsemarker.cpp | 28 +- tests/src/core/testqgsexpression.cpp | 466 +++---- tests/src/core/testqgsexpressioncontext.cpp | 150 +-- tests/src/core/testqgsfeature.cpp | 46 +- tests/src/core/testqgsfield.cpp | 90 +- tests/src/core/testqgsfields.cpp | 116 +- tests/src/core/testqgsfilledmarker.cpp | 18 +- tests/src/core/testqgsfontmarker.cpp | 18 +- tests/src/core/testqgsfontutils.cpp | 16 +- tests/src/core/testqgsgeometry.cpp | 144 +-- tests/src/core/testqgsgml.cpp | 110 +- tests/src/core/testqgsgradients.cpp | 28 +- tests/src/core/testqgshistogram.cpp | 4 +- tests/src/core/testqgsimageoperation.cpp | 80 +- .../core/testqgsinvertedpolygonrenderer.cpp | 16 +- tests/src/core/testqgsjsonutils.cpp | 4 +- tests/src/core/testqgslabelingengine.cpp | 80 +- tests/src/core/testqgslayertree.cpp | 80 +- tests/src/core/testqgslegendrenderer.cpp | 108 +- tests/src/core/testqgslinefillsymbol.cpp | 24 +- tests/src/core/testqgsmaplayer.cpp | 2 +- .../src/core/testqgsmaplayerstylemanager.cpp | 16 +- tests/src/core/testqgsmaprendererjob.cpp | 52 +- tests/src/core/testqgsmaprotation.cpp | 14 +- tests/src/core/testqgsmapsettings.cpp | 2 +- .../testqgsmaptopixelgeometrysimplifier.cpp | 8 +- tests/src/core/testqgsmarkerlinesymbol.cpp | 26 +- .../src/core/testqgsnetworkcontentfetcher.cpp | 4 +- tests/src/core/testqgsogcutils.cpp | 144 +-- tests/src/core/testqgsogrutils.cpp | 50 +- tests/src/core/testqgspainteffect.cpp | 86 +- tests/src/core/testqgspainteffectregistry.cpp | 16 +- tests/src/core/testqgspoint.cpp | 508 ++++---- tests/src/core/testqgspointlocator.cpp | 2 +- .../core/testqgspointpatternfillsymbol.cpp | 24 +- tests/src/core/testqgsproject.cpp | 18 +- tests/src/core/testqgsrasterfilewriter.cpp | 16 +- tests/src/core/testqgsrasterfill.cpp | 28 +- tests/src/core/testqgsrasterlayer.cpp | 64 +- tests/src/core/testqgsrastersublayer.cpp | 38 +- tests/src/core/testqgsrenderers.cpp | 10 +- tests/src/core/testqgsrulebasedrenderer.cpp | 20 +- tests/src/core/testqgsscaleexpression.cpp | 20 +- tests/src/core/testqgsshapeburst.cpp | 22 +- tests/src/core/testqgssimplemarker.cpp | 42 +- tests/src/core/testqgssnappingutils.cpp | 4 +- tests/src/core/testqgsspatialindex.cpp | 2 +- tests/src/core/testqgsstyle.cpp | 102 +- tests/src/core/testqgssvgmarker.cpp | 14 +- tests/src/core/testqgssymbol.cpp | 294 ++--- tests/src/core/testqgstracer.cpp | 42 +- tests/src/core/testqgsvectordataprovider.cpp | 8 +- tests/src/core/testqgsvectorfilewriter.cpp | 18 +- tests/src/core/testqgsvectorlayer.cpp | 32 +- tests/src/core/testqgsvectorlayercache.cpp | 12 +- .../src/core/testqgsvectorlayerjoinbuffer.cpp | 164 +-- tests/src/core/testziplayer.cpp | 42 +- tests/src/gui/testprojectionissues.cpp | 2 +- tests/src/gui/testqgsattributeform.cpp | 44 +- tests/src/gui/testqgsdoublespinbox.cpp | 8 +- tests/src/gui/testqgsdualview.cpp | 118 +- tests/src/gui/testqgseditorwidgetregistry.cpp | 44 +- .../src/gui/testqgsfieldexpressionwidget.cpp | 42 +- tests/src/gui/testqgsfilewidget.cpp | 4 +- tests/src/gui/testqgsgui.cpp | 8 +- tests/src/gui/testqgskeyvaluewidget.cpp | 8 +- tests/src/gui/testqgslistwidget.cpp | 12 +- tests/src/gui/testqgsmapcanvas.cpp | 16 +- tests/src/gui/testqgsrubberband.cpp | 10 +- tests/src/gui/testqgsscalecombobox.cpp | 16 +- tests/src/gui/testqgsspinbox.cpp | 8 +- tests/src/gui/testqgssqlcomposerdialog.cpp | 108 +- .../providers/grass/testqgsgrassprovider.cpp | 286 ++-- tests/src/providers/testqgsgdalprovider.cpp | 20 +- tests/src/providers/testqgspostgresconn.cpp | 6 +- .../src/providers/testqgspostgresprovider.cpp | 24 +- tests/src/providers/testqgswcsprovider.cpp | 40 +- .../src/providers/testqgswcspublicservers.cpp | 200 +-- .../src/providers/testqgswmscapabilities.cpp | 2 +- tests/src/providers/testqgswmsprovider.cpp | 10 +- 1041 files changed, 25464 insertions(+), 25413 deletions(-) diff --git a/src/analysis/interpolation/DualEdgeTriangulation.cc b/src/analysis/interpolation/DualEdgeTriangulation.cc index ddd7962d1255..53e8700dfde4 100644 --- a/src/analysis/interpolation/DualEdgeTriangulation.cc +++ b/src/analysis/interpolation/DualEdgeTriangulation.cc @@ -3090,12 +3090,12 @@ bool DualEdgeTriangulation::saveAsShapefile( const QString& fileName ) const QString shapeFileName = fileName; QgsFields fields; - fields.append( QgsField( "type", QVariant::String, "String" ) ); + fields.append( QgsField( QStringLiteral( "type" ), QVariant::String, QStringLiteral( "String" ) ) ); // add the extension if not present - if ( shapeFileName.indexOf( ".shp" ) == -1 ) + if ( shapeFileName.indexOf( QLatin1String( ".shp" ) ) == -1 ) { - shapeFileName += ".shp"; + shapeFileName += QLatin1String( ".shp" ); } //delete already existing files @@ -3107,7 +3107,7 @@ bool DualEdgeTriangulation::saveAsShapefile( const QString& fileName ) const } } - QgsVectorFileWriter writer( shapeFileName, "Utf-8", fields, QgsWkbTypes::LineString ); + QgsVectorFileWriter writer( shapeFileName, QStringLiteral( "Utf-8" ), fields, QgsWkbTypes::LineString ); if ( writer.hasError() != QgsVectorFileWriter::NoError ) { return false; @@ -3147,11 +3147,11 @@ bool DualEdgeTriangulation::saveAsShapefile( const QString& fileName ) const { if ( currentEdge->getBreak() ) { - attributeString = "break line"; + attributeString = QStringLiteral( "break line" ); } else { - attributeString = "structure line"; + attributeString = QStringLiteral( "structure line" ); } } edgeLineFeature.setAttribute( 0, attributeString ); diff --git a/src/analysis/network/qgsgraphbuilder.h b/src/analysis/network/qgsgraphbuilder.h index 1a079a511b5d..7ced28204dad 100644 --- a/src/analysis/network/qgsgraphbuilder.h +++ b/src/analysis/network/qgsgraphbuilder.h @@ -39,7 +39,7 @@ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface /** * default constructor */ - QgsGraphBuilder( const QgsCoordinateReferenceSystem& crs, bool otfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ); + QgsGraphBuilder( const QgsCoordinateReferenceSystem& crs, bool otfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = QStringLiteral( "WGS84" ) ); ~QgsGraphBuilder(); diff --git a/src/analysis/network/qgsgraphbuilderintr.h b/src/analysis/network/qgsgraphbuilderintr.h index 011be8541df6..6ffcca88d493 100644 --- a/src/analysis/network/qgsgraphbuilderintr.h +++ b/src/analysis/network/qgsgraphbuilderintr.h @@ -41,7 +41,7 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface * @param topologyTolerance sqrt distance between source point as one graph vertex * @param ellipsoidID ellipsoid for edge measurement */ - QgsGraphBuilderInterface( const QgsCoordinateReferenceSystem& crs, bool ctfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ) + QgsGraphBuilderInterface( const QgsCoordinateReferenceSystem& crs, bool ctfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = QStringLiteral( "WGS84" ) ) : mCrs( crs ) , mCtfEnabled( ctfEnabled ) , mTopologyTolerance( topologyTolerance ) diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgslinevectorlayerdirector.cpp index 034bd659ea3b..d6be07f5c5d9 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgslinevectorlayerdirector.cpp @@ -123,7 +123,7 @@ QgsLineVectorLayerDirector::~QgsLineVectorLayerDirector() QString QgsLineVectorLayerDirector::name() const { - return QString( "Vector line" ); + return QStringLiteral( "Vector line" ); } void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, diff --git a/src/analysis/openstreetmap/qgsosmdatabase.cpp b/src/analysis/openstreetmap/qgsosmdatabase.cpp index 92fa34b5488e..8eb2a04fe43c 100644 --- a/src/analysis/openstreetmap/qgsosmdatabase.cpp +++ b/src/analysis/openstreetmap/qgsosmdatabase.cpp @@ -49,7 +49,7 @@ bool QgsOSMDatabase::open() int res = QgsSLConnect::sqlite3_open_v2( mDbFileName.toUtf8().data(), &mDatabase, SQLITE_OPEN_READWRITE, nullptr ); if ( res != SQLITE_OK ) { - mError = QString( "Failed to open database [%1]: %2" ).arg( res ).arg( mDbFileName ); + mError = QStringLiteral( "Failed to open database [%1]: %2" ).arg( res ).arg( mDbFileName ); close(); return false; } @@ -180,7 +180,7 @@ QList QgsOSMDatabase::usedTags( bool ways ) const { QList pairs; - QString sql = QString( "SELECT k, count(k) FROM %1_tags GROUP BY k" ).arg( ways ? "ways" : "nodes" ); + QString sql = QStringLiteral( "SELECT k, count(k) FROM %1_tags GROUP BY k" ).arg( ways ? "ways" : "nodes" ); sqlite3_stmt* stmt; if ( sqlite3_prepare_v2( mDatabase, sql.toUtf8().data(), -1, &stmt, nullptr ) != SQLITE_OK ) @@ -281,7 +281,7 @@ bool QgsOSMDatabase::prepareStatements() if ( sqlite3_prepare_v2( mDatabase, sql[i], -1, sqlite[i], nullptr ) != SQLITE_OK ) { const char* errMsg = sqlite3_errmsg( mDatabase ); // does not require free - mError = QString( "Error preparing SQL command:\n%1\nSQL:\n%2" ) + mError = QStringLiteral( "Error preparing SQL command:\n%1\nSQL:\n%2" ) .arg( QString::fromUtf8( errMsg ), QString::fromUtf8( sql[i] ) ); return false; } @@ -299,9 +299,9 @@ bool QgsOSMDatabase::exportSpatiaLite( ExportType type, const QString& tableName // create SpatiaLite table QString geometryType; - if ( type == Point ) geometryType = "POINT"; - else if ( type == Polyline ) geometryType = "LINESTRING"; - else if ( type == Polygon ) geometryType = "POLYGON"; + if ( type == Point ) geometryType = QStringLiteral( "POINT" ); + else if ( type == Polyline ) geometryType = QStringLiteral( "LINESTRING" ); + else if ( type == Polygon ) geometryType = QStringLiteral( "POLYGON" ); else Q_ASSERT( false && "Unknown export type" ); if ( !createSpatialTable( tableName, geometryType, tagKeys ) ) @@ -333,9 +333,9 @@ bool QgsOSMDatabase::exportSpatiaLite( ExportType type, const QString& tableName bool QgsOSMDatabase::createSpatialTable( const QString& tableName, const QString& geometryType, const QStringList& tagKeys ) { - QString sqlCreateTable = QString( "CREATE TABLE %1 (id INTEGER PRIMARY KEY" ).arg( quotedIdentifier( tableName ) ); + QString sqlCreateTable = QStringLiteral( "CREATE TABLE %1 (id INTEGER PRIMARY KEY" ).arg( quotedIdentifier( tableName ) ); for ( int i = 0; i < tagKeys.count(); ++i ) - sqlCreateTable += QString( ", %1 TEXT" ).arg( quotedIdentifier( tagKeys[i] ) ); + sqlCreateTable += QStringLiteral( ", %1 TEXT" ).arg( quotedIdentifier( tagKeys[i] ) ); sqlCreateTable += ')'; char *errMsg = nullptr; @@ -347,7 +347,7 @@ bool QgsOSMDatabase::createSpatialTable( const QString& tableName, const QString return false; } - QString sqlAddGeomColumn = QString( "SELECT AddGeometryColumn(%1, 'geometry', 4326, %2, 'XY')" ) + QString sqlAddGeomColumn = QStringLiteral( "SELECT AddGeometryColumn(%1, 'geometry', 4326, %2, 'XY')" ) .arg( quotedValue( tableName ), quotedValue( geometryType ) ); ret = sqlite3_exec( mDatabase, sqlAddGeomColumn.toUtf8().constData(), nullptr, nullptr, &errMsg ); @@ -364,7 +364,7 @@ bool QgsOSMDatabase::createSpatialTable( const QString& tableName, const QString bool QgsOSMDatabase::createSpatialIndex( const QString& tableName ) { - QString sqlSpatialIndex = QString( "SELECT CreateSpatialIndex(%1, 'geometry')" ).arg( quotedValue( tableName ) ); + QString sqlSpatialIndex = QStringLiteral( "SELECT CreateSpatialIndex(%1, 'geometry')" ).arg( quotedValue( tableName ) ); char *errMsg = nullptr; int ret = sqlite3_exec( mDatabase, sqlSpatialIndex.toUtf8().constData(), nullptr, nullptr, &errMsg ); if ( ret != SQLITE_OK ) @@ -380,14 +380,14 @@ bool QgsOSMDatabase::createSpatialIndex( const QString& tableName ) void QgsOSMDatabase::exportSpatiaLiteNodes( const QString& tableName, const QStringList& tagKeys, const QStringList& notNullTagKeys ) { - QString sqlInsertPoint = QString( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) ); + QString sqlInsertPoint = QStringLiteral( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) ); for ( int i = 0; i < tagKeys.count(); ++i ) - sqlInsertPoint += QString( ",?" ); - sqlInsertPoint += ", GeomFromWKB(?, 4326))"; + sqlInsertPoint += QStringLiteral( ",?" ); + sqlInsertPoint += QLatin1String( ", GeomFromWKB(?, 4326))" ); sqlite3_stmt* stmtInsert; if ( sqlite3_prepare_v2( mDatabase, sqlInsertPoint.toUtf8().constData(), -1, &stmtInsert, nullptr ) != SQLITE_OK ) { - mError = "Prepare SELECT FROM nodes failed."; + mError = QStringLiteral( "Prepare SELECT FROM nodes failed." ); return; } @@ -428,7 +428,7 @@ void QgsOSMDatabase::exportSpatiaLiteNodes( const QString& tableName, const QStr int insertRes = sqlite3_step( stmtInsert ); if ( insertRes != SQLITE_DONE ) { - mError = QString( "Error inserting node %1 [%2]" ).arg( n.id() ).arg( insertRes ); + mError = QStringLiteral( "Error inserting node %1 [%2]" ).arg( n.id() ).arg( insertRes ); break; } @@ -446,14 +446,14 @@ void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString& tableName { Q_UNUSED( tagKeys ); - QString sqlInsertLine = QString( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) ); + QString sqlInsertLine = QStringLiteral( "INSERT INTO %1 VALUES (?" ).arg( quotedIdentifier( tableName ) ); for ( int i = 0; i < tagKeys.count(); ++i ) - sqlInsertLine += QString( ",?" ); - sqlInsertLine += ", GeomFromWKB(?, 4326))"; + sqlInsertLine += QStringLiteral( ",?" ); + sqlInsertLine += QLatin1String( ", GeomFromWKB(?, 4326))" ); sqlite3_stmt* stmtInsert; if ( sqlite3_prepare_v2( mDatabase, sqlInsertLine.toUtf8().constData(), -1, &stmtInsert, nullptr ) != SQLITE_OK ) { - mError = "Prepare SELECT FROM ways failed."; + mError = QStringLiteral( "Prepare SELECT FROM ways failed." ); return; } @@ -470,11 +470,11 @@ void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString& tableName bool isArea = ( polyline.first() == polyline.last() ); // closed way? // filter out closed way that are not areas through tags - if ( isArea && ( t.contains( "highway" ) || t.contains( "barrier" ) ) ) + if ( isArea && ( t.contains( QStringLiteral( "highway" ) ) || t.contains( QStringLiteral( "barrier" ) ) ) ) { // make sure tags that indicate areas are taken into consideration when deciding on a closed way is or isn't an area // and allow for a closed way to be exported both as a polygon and a line in case both area and non-area tags are present - if (( t.value( "area" ) != "yes" && !t.contains( "amenity" ) && !t.contains( "landuse" ) && !t.contains( "building" ) && !t.contains( "natural" ) && !t.contains( "leisure" ) && !t.contains( "aeroway" ) ) || !closed ) + if (( t.value( QStringLiteral( "area" ) ) != QLatin1String( "yes" ) && !t.contains( QStringLiteral( "amenity" ) ) && !t.contains( QStringLiteral( "landuse" ) ) && !t.contains( QStringLiteral( "building" ) ) && !t.contains( QStringLiteral( "natural" ) ) && !t.contains( QStringLiteral( "leisure" ) ) && !t.contains( QStringLiteral( "aeroway" ) ) ) || !closed ) isArea = false; } @@ -511,7 +511,7 @@ void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString& tableName int insertRes = sqlite3_step( stmtInsert ); if ( insertRes != SQLITE_DONE ) { - mError = QString( "Error inserting way %1 [%2]" ).arg( w.id() ).arg( insertRes ); + mError = QStringLiteral( "Error inserting way %1 [%2]" ).arg( w.id() ).arg( insertRes ); break; } @@ -526,17 +526,17 @@ void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString& tableName QString QgsOSMDatabase::quotedIdentifier( QString id ) { - id.replace( '\"', "\"\"" ); - return QString( "\"%1\"" ).arg( id ); + id.replace( '\"', QLatin1String( "\"\"" ) ); + return QStringLiteral( "\"%1\"" ).arg( id ); } QString QgsOSMDatabase::quotedValue( QString value ) { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); - value.replace( '\'', "''" ); - return QString( "'%1'" ).arg( value ); + value.replace( '\'', QLatin1String( "''" ) ); + return QStringLiteral( "'%1'" ).arg( value ); } /////////////////////////////////// diff --git a/src/analysis/openstreetmap/qgsosmdownload.cpp b/src/analysis/openstreetmap/qgsosmdownload.cpp index 330b08db223d..6d1b4428d118 100644 --- a/src/analysis/openstreetmap/qgsosmdownload.cpp +++ b/src/analysis/openstreetmap/qgsosmdownload.cpp @@ -24,13 +24,13 @@ QString QgsOSMDownload::defaultServiceUrl() { - return "http://overpass-api.de/api/interpreter"; + return QStringLiteral( "http://overpass-api.de/api/interpreter" ); } QString QgsOSMDownload::queryFromRect( const QgsRectangle& rect ) { - return QString( "(node(%1,%2,%3,%4);<;);out;" ).arg( rect.yMinimum() ).arg( rect.xMinimum() ) + return QStringLiteral( "(node(%1,%2,%3,%4);<;);out;" ).arg( rect.yMinimum() ).arg( rect.xMinimum() ) .arg( rect.yMaximum() ).arg( rect.xMaximum() ); } @@ -77,7 +77,7 @@ bool QgsOSMDownload::start() QgsNetworkAccessManager* nwam = QgsNetworkAccessManager::instance(); QUrl url( mServiceUrl ); - url.addQueryItem( "data", mQuery ); + url.addQueryItem( QStringLiteral( "data" ), mQuery ); QNetworkRequest request( url ); request.setRawHeader( "User-Agent", "QGIS" ); diff --git a/src/analysis/openstreetmap/qgsosmimport.cpp b/src/analysis/openstreetmap/qgsosmimport.cpp index ff45054bb565..52cb87692707 100644 --- a/src/analysis/openstreetmap/qgsosmimport.cpp +++ b/src/analysis/openstreetmap/qgsosmimport.cpp @@ -41,7 +41,7 @@ bool QgsOSMXmlImport::import() mInputFile.setFileName( mXmlFileName ); if ( !mInputFile.open( QIODevice::ReadOnly ) ) { - mError = QString( "Cannot open input file: %1" ).arg( mXmlFileName ); + mError = QStringLiteral( "Cannot open input file: %1" ).arg( mXmlFileName ); return false; } @@ -51,7 +51,7 @@ bool QgsOSMXmlImport::import() { if ( !QFile( mDbFileName ).remove() ) { - mError = QString( "Database file cannot be overwritten: %1" ).arg( mDbFileName ); + mError = QStringLiteral( "Database file cannot be overwritten: %1" ).arg( mDbFileName ); return false; } } @@ -84,7 +84,7 @@ bool QgsOSMXmlImport::import() if ( xml.name() == "osm" ) readRoot( xml ); else - xml.raiseError( "Invalid root tag" ); + xml.raiseError( QStringLiteral( "Invalid root tag" ) ); } } @@ -96,7 +96,7 @@ bool QgsOSMXmlImport::import() if ( xml.hasError() ) { - mError = QString( "XML error: %1" ).arg( xml.errorString() ); + mError = QStringLiteral( "XML error: %1" ).arg( xml.errorString() ); return false; } @@ -120,7 +120,7 @@ bool QgsOSMXmlImport::createIndexes() int ret = sqlite3_exec( mDatabase, sqlIndexes[i], nullptr, nullptr, nullptr ); if ( ret != SQLITE_OK ) { - mError = "Error creating indexes!"; + mError = QStringLiteral( "Error creating indexes!" ); return false; } } @@ -168,7 +168,7 @@ bool QgsOSMXmlImport::createDatabase() char* errMsg; if ( sqlite3_exec( mDatabase, sqlInitStatements[i], nullptr, nullptr, &errMsg ) != SQLITE_OK ) { - mError = QString( "Error executing SQL command:\n%1\nSQL:\n%2" ) + mError = QStringLiteral( "Error executing SQL command:\n%1\nSQL:\n%2" ) .arg( QString::fromUtf8( errMsg ), QString::fromUtf8( sqlInitStatements[i] ) ); sqlite3_free( errMsg ); closeDatabase(); @@ -200,7 +200,7 @@ bool QgsOSMXmlImport::createDatabase() if ( sqlite3_prepare_v2( mDatabase, sqlInsertStatements[i], -1, sqliteInsertStatements[i], nullptr ) != SQLITE_OK ) { const char* errMsg = sqlite3_errmsg( mDatabase ); // does not require free - mError = QString( "Error preparing SQL command:\n%1\nSQL:\n%2" ) + mError = QStringLiteral( "Error preparing SQL command:\n%1\nSQL:\n%2" ) .arg( QString::fromUtf8( errMsg ), QString::fromUtf8( sqlInsertStatements[i] ) ); closeDatabase(); return false; @@ -280,9 +280,9 @@ void QgsOSMXmlImport::readNode( QXmlStreamReader& xml ) { // QXmlStreamAttributes attrs = xml.attributes(); - QgsOSMId id = attrs.value( "id" ).toString().toLongLong(); - double lat = attrs.value( "lat" ).toString().toDouble(); - double lon = attrs.value( "lon" ).toString().toDouble(); + QgsOSMId id = attrs.value( QStringLiteral( "id" ) ).toString().toLongLong(); + double lat = attrs.value( QStringLiteral( "lat" ) ).toString().toDouble(); + double lon = attrs.value( QStringLiteral( "lon" ) ).toString().toDouble(); // insert to DB sqlite3_bind_int64( mStmtInsertNode, 1, id ); @@ -291,7 +291,7 @@ void QgsOSMXmlImport::readNode( QXmlStreamReader& xml ) if ( sqlite3_step( mStmtInsertNode ) != SQLITE_DONE ) { - xml.raiseError( QString( "Storing node %1 failed." ).arg( id ) ); + xml.raiseError( QStringLiteral( "Storing node %1 failed." ).arg( id ) ); } sqlite3_reset( mStmtInsertNode ); @@ -308,7 +308,7 @@ void QgsOSMXmlImport::readNode( QXmlStreamReader& xml ) if ( xml.name() == "tag" ) readTag( false, id, xml ); else - xml.raiseError( "Invalid tag in " ); + xml.raiseError( QStringLiteral( "Invalid tag in " ) ); } } } @@ -316,8 +316,8 @@ void QgsOSMXmlImport::readNode( QXmlStreamReader& xml ) void QgsOSMXmlImport::readTag( bool way, QgsOSMId id, QXmlStreamReader& xml ) { QXmlStreamAttributes attrs = xml.attributes(); - QByteArray k = attrs.value( "k" ).toString().toUtf8(); - QByteArray v = attrs.value( "v" ).toString().toUtf8(); + QByteArray k = attrs.value( QStringLiteral( "k" ) ).toString().toUtf8(); + QByteArray v = attrs.value( QStringLiteral( "v" ) ).toString().toUtf8(); xml.skipCurrentElement(); sqlite3_stmt* stmtInsertTag = way ? mStmtInsertWayTag : mStmtInsertNodeTag; @@ -329,7 +329,7 @@ void QgsOSMXmlImport::readTag( bool way, QgsOSMId id, QXmlStreamReader& xml ) int res = sqlite3_step( stmtInsertTag ); if ( res != SQLITE_DONE ) { - xml.raiseError( QString( "Storing tag failed [%1]" ).arg( res ) ); + xml.raiseError( QStringLiteral( "Storing tag failed [%1]" ).arg( res ) ); } sqlite3_reset( stmtInsertTag ); @@ -350,14 +350,14 @@ void QgsOSMXmlImport::readWay( QXmlStreamReader& xml ) */ QXmlStreamAttributes attrs = xml.attributes(); - QgsOSMId id = attrs.value( "id" ).toString().toLongLong(); + QgsOSMId id = attrs.value( QStringLiteral( "id" ) ).toString().toLongLong(); // insert to DB sqlite3_bind_int64( mStmtInsertWay, 1, id ); if ( sqlite3_step( mStmtInsertWay ) != SQLITE_DONE ) { - xml.raiseError( QString( "Storing way %1 failed." ).arg( id ) ); + xml.raiseError( QStringLiteral( "Storing way %1 failed." ).arg( id ) ); } sqlite3_reset( mStmtInsertWay ); @@ -375,7 +375,7 @@ void QgsOSMXmlImport::readWay( QXmlStreamReader& xml ) { if ( xml.name() == "nd" ) { - QgsOSMId node_id = xml.attributes().value( "ref" ).toString().toLongLong(); + QgsOSMId node_id = xml.attributes().value( QStringLiteral( "ref" ) ).toString().toLongLong(); sqlite3_bind_int64( mStmtInsertWayNode, 1, id ); sqlite3_bind_int64( mStmtInsertWayNode, 2, node_id ); @@ -383,7 +383,7 @@ void QgsOSMXmlImport::readWay( QXmlStreamReader& xml ) if ( sqlite3_step( mStmtInsertWayNode ) != SQLITE_DONE ) { - xml.raiseError( QString( "Storing ways_nodes %1 - %2 failed." ).arg( id ).arg( node_id ) ); + xml.raiseError( QStringLiteral( "Storing ways_nodes %1 - %2 failed." ).arg( id ).arg( node_id ) ); } sqlite3_reset( mStmtInsertWayNode ); diff --git a/src/analysis/raster/qgsalignraster.cpp b/src/analysis/raster/qgsalignraster.cpp index 7acf8b7248d2..460cb07cea56 100644 --- a/src/analysis/raster/qgsalignraster.cpp +++ b/src/analysis/raster/qgsalignraster.cpp @@ -202,7 +202,7 @@ bool QgsAlignRaster::setParametersFromRaster( const RasterInfo& rasterInfo, cons QPointF go; if ( !suggestedWarpOutput( rasterInfo, customCRSWkt, &cs, &go ) ) { - mCrsWkt = "_error_"; + mCrsWkt = QStringLiteral( "_error_" ); mCellSizeX = mCellSizeY = 0; mGridOffsetX = mGridOffsetY = 0; return false; @@ -240,7 +240,7 @@ bool QgsAlignRaster::checkInputParameters() { mErrorMessage.clear(); - if ( mCrsWkt == "_error_" ) + if ( mCrsWkt == QLatin1String( "_error_" ) ) { mErrorMessage = QObject::tr( "Unable to reproject." ); return false; @@ -397,7 +397,7 @@ int QgsAlignRaster::suggestedReferenceLayer() const // using WGS84 as a destination CRS... but maybe some projected CRS // would be a better a choice to more accurately compute areas? // (Why earth is not flat???) - QgsCoordinateReferenceSystem destCRS( "EPSG:4326" ); + QgsCoordinateReferenceSystem destCRS( QStringLiteral( "EPSG:4326" ) ); QString destWkt = destCRS.toWkt(); Q_FOREACH ( const Item& raster, mRasters ) @@ -423,7 +423,7 @@ bool QgsAlignRaster::createAndWarp( const Item& raster ) GDALDriverH hDriver = GDALGetDriverByName( "GTiff" ); if ( !hDriver ) { - mErrorMessage = QString( "GDALGetDriverByName(GTiff) failed." ); + mErrorMessage = QStringLiteral( "GDALGetDriverByName(GTiff) failed." ); return false; } diff --git a/src/analysis/raster/qgsruggednessfilter.cpp b/src/analysis/raster/qgsruggednessfilter.cpp index 70d40d930b6d..3652c6ec58c9 100644 --- a/src/analysis/raster/qgsruggednessfilter.cpp +++ b/src/analysis/raster/qgsruggednessfilter.cpp @@ -22,7 +22,7 @@ QgsRuggednessFilter::QgsRuggednessFilter( const QString& inputFile, const QStrin } -QgsRuggednessFilter::QgsRuggednessFilter(): QgsNineCellFilter( "", "", "" ) +QgsRuggednessFilter::QgsRuggednessFilter(): QgsNineCellFilter( QLatin1String( "" ), QLatin1String( "" ), QLatin1String( "" ) ) { } diff --git a/src/analysis/vector/qgsgeometryanalyzer.cpp b/src/analysis/vector/qgsgeometryanalyzer.cpp index 5f89c48747b1..2fc8aad7b6e8 100644 --- a/src/analysis/vector/qgsgeometryanalyzer.cpp +++ b/src/analysis/vector/qgsgeometryanalyzer.cpp @@ -279,16 +279,16 @@ bool QgsGeometryAnalyzer::extent( QgsVectorLayer* layer, QgsCoordinateReferenceSystem crs = layer->crs(); QgsFields fields; - fields.append( QgsField( QString( "MINX" ), QVariant::Double ) ); - fields.append( QgsField( QString( "MINY" ), QVariant::Double ) ); - fields.append( QgsField( QString( "MAXX" ), QVariant::Double ) ); - fields.append( QgsField( QString( "MAXY" ), QVariant::Double ) ); - fields.append( QgsField( QString( "CNTX" ), QVariant::Double ) ); - fields.append( QgsField( QString( "CNTY" ), QVariant::Double ) ); - fields.append( QgsField( QString( "AREA" ), QVariant::Double ) ); - fields.append( QgsField( QString( "PERIM" ), QVariant::Double ) ); - fields.append( QgsField( QString( "HEIGHT" ), QVariant::Double ) ); - fields.append( QgsField( QString( "WIDTH" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "MINX" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "MINY" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "MAXX" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "MAXY" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "CNTX" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "CNTY" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "AREA" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "PERIM" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "HEIGHT" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "WIDTH" ), QVariant::Double ) ); QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), fields, outputType, crs ); @@ -381,9 +381,9 @@ bool QgsGeometryAnalyzer::convexHull( QgsVectorLayer* layer, const QString& shap useField = true; } QgsFields fields; - fields.append( QgsField( QString( "UID" ), QVariant::String ) ); - fields.append( QgsField( QString( "AREA" ), QVariant::Double ) ); - fields.append( QgsField( QString( "PERIM" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "UID" ), QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "AREA" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "PERIM" ), QVariant::Double ) ); QgsWkbTypes::Type outputType = QgsWkbTypes::Polygon; QgsCoordinateReferenceSystem crs = layer->crs(); diff --git a/src/analysis/vector/qgsoverlayanalyzer.cpp b/src/analysis/vector/qgsoverlayanalyzer.cpp index 5b42b135f672..0a8a44c4bd1f 100644 --- a/src/analysis/vector/qgsoverlayanalyzer.cpp +++ b/src/analysis/vector/qgsoverlayanalyzer.cpp @@ -179,7 +179,7 @@ void QgsOverlayAnalyzer::combineFieldLists( QgsFields& fieldListA, const QgsFiel int count = 0; while ( names.contains( field.name() ) ) { - QString name = QString( "%1_%2" ).arg( field.name() ).arg( count ); + QString name = QStringLiteral( "%1_%2" ).arg( field.name() ).arg( count ); field = QgsField( name, field.type() ); ++count; } diff --git a/src/analysis/vector/qgspointsample.cpp b/src/analysis/vector/qgspointsample.cpp index bad110c655c1..d3f114b711ba 100644 --- a/src/analysis/vector/qgspointsample.cpp +++ b/src/analysis/vector/qgspointsample.cpp @@ -56,10 +56,10 @@ int QgsPointSample::createRandomPoints( QProgressDialog* pd ) //create vector file writer QgsFields outputFields; - outputFields.append( QgsField( "id", QVariant::Int ) ); - outputFields.append( QgsField( "station_id", QVariant::Int ) ); - outputFields.append( QgsField( "stratum_id", QVariant::Int ) ); - QgsVectorFileWriter writer( mOutputLayer, "UTF-8", + outputFields.append( QgsField( QStringLiteral( "id" ), QVariant::Int ) ); + outputFields.append( QgsField( QStringLiteral( "station_id" ), QVariant::Int ) ); + outputFields.append( QgsField( QStringLiteral( "stratum_id" ), QVariant::Int ) ); + QgsVectorFileWriter writer( mOutputLayer, QStringLiteral( "UTF-8" ), outputFields, QgsWkbTypes::Point, mInputLayer->crs() ); @@ -124,9 +124,9 @@ void QgsPointSample::addSamplePoints( QgsFeature& inputFeature, QgsVectorFileWri { //add feature to writer QgsFeature f( mNCreatedPoints ); - f.setAttribute( "id", mNCreatedPoints + 1 ); - f.setAttribute( "station_id", points + 1 ); - f.setAttribute( "stratum_id", inputFeature.id() ); + f.setAttribute( QStringLiteral( "id" ), mNCreatedPoints + 1 ); + f.setAttribute( QStringLiteral( "station_id" ), points + 1 ); + f.setAttribute( QStringLiteral( "stratum_id" ), inputFeature.id() ); f.setGeometry( ptGeom ); writer.addFeature( f ); sIndex.insertFeature( f ); diff --git a/src/analysis/vector/qgstransectsample.cpp b/src/analysis/vector/qgstransectsample.cpp index b6cd1d52fbbd..286b62bb962e 100644 --- a/src/analysis/vector/qgstransectsample.cpp +++ b/src/analysis/vector/qgstransectsample.cpp @@ -82,22 +82,22 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) //create vector file writers for output QgsFields outputPointFields; - outputPointFields.append( QgsField( "id", stratumIdType ) ); - outputPointFields.append( QgsField( "station_id", QVariant::Int ) ); - outputPointFields.append( QgsField( "stratum_id", stratumIdType ) ); - outputPointFields.append( QgsField( "station_code", QVariant::String ) ); - outputPointFields.append( QgsField( "start_lat", QVariant::Double ) ); - outputPointFields.append( QgsField( "start_long", QVariant::Double ) ); - - QgsVectorFileWriter outputPointWriter( mOutputPointLayer, "utf-8", outputPointFields, QgsWkbTypes::Point, + outputPointFields.append( QgsField( QStringLiteral( "id" ), stratumIdType ) ); + outputPointFields.append( QgsField( QStringLiteral( "station_id" ), QVariant::Int ) ); + outputPointFields.append( QgsField( QStringLiteral( "stratum_id" ), stratumIdType ) ); + outputPointFields.append( QgsField( QStringLiteral( "station_code" ), QVariant::String ) ); + outputPointFields.append( QgsField( QStringLiteral( "start_lat" ), QVariant::Double ) ); + outputPointFields.append( QgsField( QStringLiteral( "start_long" ), QVariant::Double ) ); + + QgsVectorFileWriter outputPointWriter( mOutputPointLayer, QStringLiteral( "utf-8" ), outputPointFields, QgsWkbTypes::Point, mStrataLayer->crs() ); if ( outputPointWriter.hasError() != QgsVectorFileWriter::NoError ) { return 3; } - outputPointFields.append( QgsField( "bearing", QVariant::Double ) ); //add bearing attribute for lines - QgsVectorFileWriter outputLineWriter( mOutputLineLayer, "utf-8", outputPointFields, QgsWkbTypes::LineString, + outputPointFields.append( QgsField( QStringLiteral( "bearing" ), QVariant::Double ) ); //add bearing attribute for lines + QgsVectorFileWriter outputLineWriter( mOutputLineLayer, QStringLiteral( "utf-8" ), outputPointFields, QgsWkbTypes::LineString, mStrataLayer->crs() ); if ( outputLineWriter.hasError() != QgsVectorFileWriter::NoError ) { @@ -105,9 +105,9 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) } QgsFields usedBaselineFields; - usedBaselineFields.append( QgsField( "stratum_id", stratumIdType ) ); - usedBaselineFields.append( QgsField( "ok", QVariant::String ) ); - QgsVectorFileWriter usedBaselineWriter( mUsedBaselineLayer, "utf-8", usedBaselineFields, QgsWkbTypes::LineString, + usedBaselineFields.append( QgsField( QStringLiteral( "stratum_id" ), stratumIdType ) ); + usedBaselineFields.append( QgsField( QStringLiteral( "ok" ), QVariant::String ) ); + QgsVectorFileWriter usedBaselineWriter( mUsedBaselineLayer, QStringLiteral( "utf-8" ), usedBaselineFields, QgsWkbTypes::LineString, mStrataLayer->crs() ); if ( usedBaselineWriter.hasError() != QgsVectorFileWriter::NoError ) { @@ -118,8 +118,8 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) QFileInfo outputPointInfo( mOutputPointLayer ); QString bufferClipLineOutput = outputPointInfo.absolutePath() + "/out_buffer_clip_line.shp"; QgsFields bufferClipLineFields; - bufferClipLineFields.append( QgsField( "id", stratumIdType ) ); - QgsVectorFileWriter bufferClipLineWriter( bufferClipLineOutput, "utf-8", bufferClipLineFields, QgsWkbTypes::LineString, mStrataLayer->crs() ); + bufferClipLineFields.append( QgsField( QStringLiteral( "id" ), stratumIdType ) ); + QgsVectorFileWriter bufferClipLineWriter( bufferClipLineOutput, QStringLiteral( "utf-8" ), bufferClipLineFields, QgsWkbTypes::LineString, mStrataLayer->crs() ); //configure distanceArea depending on minDistance units and output CRS QgsDistanceArea distanceArea; @@ -200,8 +200,8 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) //save clipped baseline to file QgsFeature blFeature( usedBaselineFields ); blFeature.setGeometry( clippedBaseline ); - blFeature.setAttribute( "stratum_id", strataId ); - blFeature.setAttribute( "ok", "f" ); + blFeature.setAttribute( QStringLiteral( "stratum_id" ), strataId ); + blFeature.setAttribute( QStringLiteral( "ok" ), "f" ); usedBaselineWriter.addFeature( blFeature ); //start loop to create random points along the baseline @@ -227,12 +227,12 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) QgsFeature samplePointFeature( outputPointFields ); samplePointFeature.setGeometry( samplePoint ); - samplePointFeature.setAttribute( "id", nTotalTransects + 1 ); - samplePointFeature.setAttribute( "station_id", nCreatedTransects + 1 ); - samplePointFeature.setAttribute( "stratum_id", strataId ); - samplePointFeature.setAttribute( "station_code", strataId.toString() + '_' + QString::number( nCreatedTransects + 1 ) ); - samplePointFeature.setAttribute( "start_lat", latLongSamplePoint.y() ); - samplePointFeature.setAttribute( "start_long", latLongSamplePoint.x() ); + samplePointFeature.setAttribute( QStringLiteral( "id" ), nTotalTransects + 1 ); + samplePointFeature.setAttribute( QStringLiteral( "station_id" ), nCreatedTransects + 1 ); + samplePointFeature.setAttribute( QStringLiteral( "stratum_id" ), strataId ); + samplePointFeature.setAttribute( QStringLiteral( "station_code" ), strataId.toString() + '_' + QString::number( nCreatedTransects + 1 ) ); + samplePointFeature.setAttribute( QStringLiteral( "start_lat" ), latLongSamplePoint.y() ); + samplePointFeature.setAttribute( QStringLiteral( "start_long" ), latLongSamplePoint.x() ); //find closest point on clipped buffer line QgsPoint minDistPoint; @@ -290,13 +290,13 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) QgsFeatureId fid( nCreatedTransects ); QgsFeature sampleLineFeature( outputPointFields, fid ); sampleLineFeature.setGeometry( lineClipStratum ); - sampleLineFeature.setAttribute( "id", nTotalTransects + 1 ); - sampleLineFeature.setAttribute( "station_id", nCreatedTransects + 1 ); - sampleLineFeature.setAttribute( "stratum_id", strataId ); - sampleLineFeature.setAttribute( "station_code", strataId.toString() + '_' + QString::number( nCreatedTransects + 1 ) ); - sampleLineFeature.setAttribute( "start_lat", latLongSamplePoint.y() ); - sampleLineFeature.setAttribute( "start_long", latLongSamplePoint.x() ); - sampleLineFeature.setAttribute( "bearing", bearing ); + sampleLineFeature.setAttribute( QStringLiteral( "id" ), nTotalTransects + 1 ); + sampleLineFeature.setAttribute( QStringLiteral( "station_id" ), nCreatedTransects + 1 ); + sampleLineFeature.setAttribute( QStringLiteral( "stratum_id" ), strataId ); + sampleLineFeature.setAttribute( QStringLiteral( "station_code" ), strataId.toString() + '_' + QString::number( nCreatedTransects + 1 ) ); + sampleLineFeature.setAttribute( QStringLiteral( "start_lat" ), latLongSamplePoint.y() ); + sampleLineFeature.setAttribute( QStringLiteral( "start_long" ), latLongSamplePoint.x() ); + sampleLineFeature.setAttribute( QStringLiteral( "bearing" ), bearing ); outputLineWriter.addFeature( sampleLineFeature ); //add point to file writer here. @@ -313,7 +313,7 @@ int QgsTransectSample::createSample( QProgressDialog* pd ) QgsFeature bufferClipFeature; bufferClipFeature.setGeometry( *bufferLineClipped ); delete bufferLineClipped; - bufferClipFeature.setAttribute( "id", strataId ); + bufferClipFeature.setAttribute( QStringLiteral( "id" ), strataId ); bufferClipLineWriter.addFeature( bufferClipFeature ); //delete bufferLineClipped; diff --git a/src/analysis/vector/qgszonalstatistics.cpp b/src/analysis/vector/qgszonalstatistics.cpp index 2b0eb65e2b52..489d4689b007 100644 --- a/src/analysis/vector/qgszonalstatistics.cpp +++ b/src/analysis/vector/qgszonalstatistics.cpp @@ -117,77 +117,77 @@ int QgsZonalStatistics::calculateStatistics( QProgressDialog* p ) if ( mStatistics & QgsZonalStatistics::Count ) { countFieldName = getUniqueFieldName( mAttributePrefix + "count" ); - QgsField countField( countFieldName, QVariant::Double, "double precision" ); + QgsField countField( countFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( countField ); } QString sumFieldName; if ( mStatistics & QgsZonalStatistics::Sum ) { sumFieldName = getUniqueFieldName( mAttributePrefix + "sum" ); - QgsField sumField( sumFieldName, QVariant::Double, "double precision" ); + QgsField sumField( sumFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( sumField ); } QString meanFieldName; if ( mStatistics & QgsZonalStatistics::Mean ) { meanFieldName = getUniqueFieldName( mAttributePrefix + "mean" ); - QgsField meanField( meanFieldName, QVariant::Double, "double precision" ); + QgsField meanField( meanFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( meanField ); } QString medianFieldName; if ( mStatistics & QgsZonalStatistics::Median ) { medianFieldName = getUniqueFieldName( mAttributePrefix + "median" ); - QgsField medianField( medianFieldName, QVariant::Double, "double precision" ); + QgsField medianField( medianFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( medianField ); } QString stdevFieldName; if ( mStatistics & QgsZonalStatistics::StDev ) { stdevFieldName = getUniqueFieldName( mAttributePrefix + "stdev" ); - QgsField stdField( stdevFieldName, QVariant::Double, "double precision" ); + QgsField stdField( stdevFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( stdField ); } QString minFieldName; if ( mStatistics & QgsZonalStatistics::Min ) { minFieldName = getUniqueFieldName( mAttributePrefix + "min" ); - QgsField minField( minFieldName, QVariant::Double, "double precision" ); + QgsField minField( minFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( minField ); } QString maxFieldName; if ( mStatistics & QgsZonalStatistics::Max ) { maxFieldName = getUniqueFieldName( mAttributePrefix + "max" ); - QgsField maxField( maxFieldName, QVariant::Double, "double precision" ); + QgsField maxField( maxFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( maxField ); } QString rangeFieldName; if ( mStatistics & QgsZonalStatistics::Range ) { rangeFieldName = getUniqueFieldName( mAttributePrefix + "range" ); - QgsField rangeField( rangeFieldName, QVariant::Double, "double precision" ); + QgsField rangeField( rangeFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( rangeField ); } QString minorityFieldName; if ( mStatistics & QgsZonalStatistics::Minority ) { minorityFieldName = getUniqueFieldName( mAttributePrefix + "minority" ); - QgsField minorityField( minorityFieldName, QVariant::Double, "double precision" ); + QgsField minorityField( minorityFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( minorityField ); } QString majorityFieldName; if ( mStatistics & QgsZonalStatistics::Majority ) { majorityFieldName = getUniqueFieldName( mAttributePrefix + "majority" ); - QgsField majField( majorityFieldName, QVariant::Double, "double precision" ); + QgsField majField( majorityFieldName, QVariant::Double, QStringLiteral( "double precision" ) ); newFieldList.push_back( majField ); } QString varietyFieldName; if ( mStatistics & QgsZonalStatistics::Variety ) { varietyFieldName = getUniqueFieldName( mAttributePrefix + "variety" ); - QgsField varietyField( varietyFieldName, QVariant::Int, "int" ); + QgsField varietyField( varietyFieldName, QVariant::Int, QStringLiteral( "int" ) ); newFieldList.push_back( varietyField ); } vectorProvider->addAttributes( newFieldList ); @@ -529,7 +529,7 @@ QString QgsZonalStatistics::getUniqueFieldName( const QString& fieldName ) { QgsVectorDataProvider* dp = mPolygonLayer->dataProvider(); - if ( !dp->storageType().contains( "ESRI Shapefile" ) ) + if ( !dp->storageType().contains( QLatin1String( "ESRI Shapefile" ) ) ) { return fieldName; } @@ -553,7 +553,7 @@ QString QgsZonalStatistics::getUniqueFieldName( const QString& fieldName ) } int n = 1; - shortName = QString( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n ); + shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n ); found = true; while ( found ) { @@ -565,11 +565,11 @@ QString QgsZonalStatistics::getUniqueFieldName( const QString& fieldName ) n += 1; if ( n < 9 ) { - shortName = QString( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n ); + shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 8 ) ).arg( n ); } else { - shortName = QString( "%1_%2" ).arg( fieldName.mid( 0, 7 ) ).arg( n ); + shortName = QStringLiteral( "%1_%2" ).arg( fieldName.mid( 0, 7 ) ).arg( n ); } found = true; } diff --git a/src/analysis/vector/qgszonalstatistics.h b/src/analysis/vector/qgszonalstatistics.h index 5044708a9130..d91bdef1b8ca 100644 --- a/src/analysis/vector/qgszonalstatistics.h +++ b/src/analysis/vector/qgszonalstatistics.h @@ -55,7 +55,7 @@ class ANALYSIS_EXPORT QgsZonalStatistics /** * Constructor for QgsZonalStatistics. */ - QgsZonalStatistics( QgsVectorLayer* polygonLayer, const QString& rasterFile, const QString& attributePrefix = "", int rasterBand = 1, + QgsZonalStatistics( QgsVectorLayer* polygonLayer, const QString& rasterFile, const QString& attributePrefix = QLatin1String( "" ), int rasterBand = 1, Statistics stats = Statistics( Count | Sum | Mean ) ); /** Starts the calculation diff --git a/src/app/composer/qgsatlascompositionwidget.cpp b/src/app/composer/qgsatlascompositionwidget.cpp index 953a1303eb7f..4b0a95091699 100644 --- a/src/app/composer/qgsatlascompositionwidget.cpp +++ b/src/app/composer/qgsatlascompositionwidget.cpp @@ -122,7 +122,7 @@ void QgsAtlasCompositionWidget::on_mAtlasFilenameExpressionButton_clicked() } QgsExpressionContext context = mComposition->createExpressionContext(); - QgsExpressionBuilderDialog exprDlg( atlasMap->coverageLayer(), mAtlasFilenamePatternEdit->text(), this, "generic", context ); + QgsExpressionBuilderDialog exprDlg( atlasMap->coverageLayer(), mAtlasFilenamePatternEdit->text(), this, QStringLiteral( "generic" ), context ); exprDlg.setWindowTitle( tr( "Expression based filename" ) ); if ( exprDlg.exec() == QDialog::Accepted ) @@ -295,7 +295,7 @@ void QgsAtlasCompositionWidget::on_mAtlasFeatureFilterButton_clicked() } QgsExpressionContext context = mComposition->createExpressionContext(); - QgsExpressionBuilderDialog exprDlg( vl, mAtlasFeatureFilterEdit->text(), this, "generic", context ); + QgsExpressionBuilderDialog exprDlg( vl, mAtlasFeatureFilterEdit->text(), this, QStringLiteral( "generic" ), context ); exprDlg.setWindowTitle( tr( "Expression based filter" ) ); if ( exprDlg.exec() == QDialog::Accepted ) diff --git a/src/app/composer/qgsattributeselectiondialog.cpp b/src/app/composer/qgsattributeselectiondialog.cpp index dac84d550ad0..ef6ebb65de6e 100644 --- a/src/app/composer/qgsattributeselectiondialog.cpp +++ b/src/app/composer/qgsattributeselectiondialog.cpp @@ -105,8 +105,8 @@ QgsExpressionContext QgsComposerColumnSourceDelegate::createExpressionContext() } QgsExpressionContext expContext = mComposerObject->createExpressionContext(); - expContext.lastScope()->setVariable( "row_number", 1 ); - expContext.setHighlightedVariables( QStringList() << "row_number" ); + expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), 1 ); + expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) ); return expContext; } @@ -283,7 +283,7 @@ QgsAttributeSelectionDialog::QgsAttributeSelectionDialog( QgsComposerAttributeTa setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/AttributeSelectionDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/AttributeSelectionDialog/geometry" ) ).toByteArray() ); if ( mComposerTable ) { @@ -322,7 +322,7 @@ QgsAttributeSelectionDialog::QgsAttributeSelectionDialog( QgsComposerAttributeTa QgsAttributeSelectionDialog::~QgsAttributeSelectionDialog() { QSettings settings; - settings.setValue( "/Windows/AttributeSelectionDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/AttributeSelectionDialog/geometry" ), saveGeometry() ); } void QgsAttributeSelectionDialog::on_mRemoveColumnPushButton_clicked() diff --git a/src/app/composer/qgscomposer.cpp b/src/app/composer/qgscomposer.cpp index 4ed6dd4fa401..a7dc10736834 100644 --- a/src/app/composer/qgscomposer.cpp +++ b/src/app/composer/qgscomposer.cpp @@ -124,7 +124,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) QSettings settings; setStyleSheet( mQgis->styleSheet() ); - int size = settings.value( "/IconSize", QGIS_ICON_SIZE ).toInt(); + int size = settings.value( QStringLiteral( "/IconSize" ), QGIS_ICON_SIZE ).toInt(); setIconSize( QSize( size, size ) ); QToolButton* orderingToolButton = new QToolButton( this ); @@ -153,7 +153,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) mItemActionToolbar->addWidget( alignToolButton ); QToolButton* shapeToolButton = new QToolButton( mItemToolbar ); - shapeToolButton->setIcon( QgsApplication::getThemeIcon( "/mActionAddBasicShape.svg" ) ); + shapeToolButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddBasicShape.svg" ) ) ); shapeToolButton->setCheckable( true ); shapeToolButton->setPopupMode( QToolButton::InstantPopup ); shapeToolButton->setAutoRaise( true ); @@ -165,7 +165,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) mItemToolbar->insertWidget( mActionAddArrow, shapeToolButton ); QToolButton* nodesItemButton = new QToolButton( mItemToolbar ); - nodesItemButton->setIcon( QgsApplication::getThemeIcon( "/mActionAddNodesItem.svg" ) ); + nodesItemButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddNodesItem.svg" ) ) ); nodesItemButton->setCheckable( true ); nodesItemButton->setPopupMode( QToolButton::InstantPopup ); nodesItemButton->setAutoRaise( true ); @@ -236,7 +236,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) composerMenu->addAction( mActionComposerManager ); mPrintComposersMenu = new QMenu( tr( "Print &Composers" ), this ); - mPrintComposersMenu->setObjectName( "mPrintComposersMenu" ); + mPrintComposersMenu->setObjectName( QStringLiteral( "mPrintComposersMenu" ) ); connect( mPrintComposersMenu, SIGNAL( aboutToShow() ), this, SLOT( populatePrintComposersMenu() ) ); composerMenu->addMenu( mPrintComposersMenu ); @@ -259,19 +259,19 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) mActionCut = new QAction( tr( "Cu&t" ), this ); mActionCut->setShortcuts( QKeySequence::Cut ); mActionCut->setStatusTip( tr( "Cut" ) ); - mActionCut->setIcon( QgsApplication::getThemeIcon( "/mActionEditCut.svg" ) ); + mActionCut->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditCut.svg" ) ) ); connect( mActionCut, SIGNAL( triggered() ), this, SLOT( actionCutTriggered() ) ); mActionCopy = new QAction( tr( "&Copy" ), this ); mActionCopy->setShortcuts( QKeySequence::Copy ); mActionCopy->setStatusTip( tr( "Copy" ) ); - mActionCopy->setIcon( QgsApplication::getThemeIcon( "/mActionEditCopy.svg" ) ); + mActionCopy->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditCopy.svg" ) ) ); connect( mActionCopy, SIGNAL( triggered() ), this, SLOT( actionCopyTriggered() ) ); mActionPaste = new QAction( tr( "&Paste" ), this ); mActionPaste->setShortcuts( QKeySequence::Paste ); mActionPaste->setStatusTip( tr( "Paste" ) ); - mActionPaste->setIcon( QgsApplication::getThemeIcon( "/mActionEditPaste.svg" ) ); + mActionPaste->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditPaste.svg" ) ) ); connect( mActionPaste, SIGNAL( triggered() ), this, SLOT( actionPasteTriggered() ) ); QMenu *editMenu = menuBar()->addMenu( tr( "&Edit" ) ); @@ -280,7 +280,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) editMenu->addSeparator(); //Backspace should also trigger delete selection - QShortcut* backSpace = new QShortcut( QKeySequence( "Backspace" ), this ); + QShortcut* backSpace = new QShortcut( QKeySequence( QStringLiteral( "Backspace" ) ), this ); connect( backSpace, SIGNAL( activated() ), mActionDeleteSelection, SLOT( trigger() ) ); editMenu->addAction( mActionDeleteSelection ); editMenu->addSeparator(); @@ -329,13 +329,13 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) QMenu *viewMenu = menuBar()->addMenu( tr( "&View" ) ); //Ctrl+= should also trigger zoom in - QShortcut* ctrlEquals = new QShortcut( QKeySequence( "Ctrl+=" ), this ); + QShortcut* ctrlEquals = new QShortcut( QKeySequence( QStringLiteral( "Ctrl+=" ) ), this ); connect( ctrlEquals, SIGNAL( activated() ), mActionZoomIn, SLOT( trigger() ) ); #ifndef Q_OS_MAC //disabled for OSX - see #10761 //also see http://qt-project.org/forums/viewthread/3630 QGraphicsEffects are not well supported on OSX - QMenu *previewMenu = viewMenu->addMenu( "&Preview" ); + QMenu *previewMenu = viewMenu->addMenu( QStringLiteral( "&Preview" ) ); previewMenu->addAction( mActionPreviewModeOff ); previewMenu->addAction( mActionPreviewModeGrayscale ); previewMenu->addAction( mActionPreviewModeMono ); @@ -365,9 +365,9 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) // Panel and toolbar submenus mPanelMenu = new QMenu( tr( "P&anels" ), this ); - mPanelMenu->setObjectName( "mPanelMenu" ); + mPanelMenu->setObjectName( QStringLiteral( "mPanelMenu" ) ); mToolbarMenu = new QMenu( tr( "&Toolbars" ), this ); - mToolbarMenu->setObjectName( "mToolbarMenu" ); + mToolbarMenu->setObjectName( QStringLiteral( "mToolbarMenu" ) ); viewMenu->addSeparator(); viewMenu->addAction( mActionToggleFullScreen ); viewMenu->addAction( mActionHidePanels ); @@ -385,14 +385,14 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) layoutMenu->addAction( mActionAddNewScalebar ); layoutMenu->addAction( mActionAddNewLegend ); layoutMenu->addAction( mActionAddImage ); - QMenu *shapeMenu = layoutMenu->addMenu( "Add Shape" ); - shapeMenu->setIcon( QgsApplication::getThemeIcon( "/mActionAddBasicShape.svg" ) ); + QMenu *shapeMenu = layoutMenu->addMenu( QStringLiteral( "Add Shape" ) ); + shapeMenu->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddBasicShape.svg" ) ) ); shapeMenu->addAction( mActionAddRectangle ); shapeMenu->addAction( mActionAddTriangle ); shapeMenu->addAction( mActionAddEllipse ); - QMenu *nodesItemMenu = layoutMenu->addMenu( "Add Nodes Item" ); - nodesItemMenu->setIcon( QgsApplication::getThemeIcon( "/mActionAddNodesItem.svg" ) ); + QMenu *nodesItemMenu = layoutMenu->addMenu( QStringLiteral( "Add Nodes Item" ) ); + nodesItemMenu->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddNodesItem.svg" ) ) ); nodesItemMenu->addAction( mActionAddPolygon ); nodesItemMenu->addAction( mActionAddPolyline ); @@ -510,7 +510,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) mStatusAtlasLabel = new QLabel( mStatusBar ); //hide borders from child items in status bar under Windows - mStatusBar->setStyleSheet( "QStatusBar::item {border: none;}" ); + mStatusBar->setStyleSheet( QStringLiteral( "QStatusBar::item {border: none;}" ) ); mStatusBar->addWidget( mStatusCursorXLabel ); mStatusBar->addWidget( mStatusCursorYLabel ); @@ -538,7 +538,7 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) //initial state of rulers QSettings myQSettings; - bool showRulers = myQSettings.value( "/Composer/showRulers", true ).toBool(); + bool showRulers = myQSettings.value( QStringLiteral( "/Composer/showRulers" ), true ).toBool(); mActionShowRulers->blockSignals( true ); mActionShowRulers->setChecked( showRulers ); mHorizontalRuler->setVisible( showRulers ); @@ -573,25 +573,25 @@ QgsComposer::QgsComposer( QgisApp *qgis, const QString& title ) setTabPosition( Qt::AllDockWidgetAreas, QTabWidget::North ); mGeneralDock = new QgsDockWidget( tr( "Composition" ), this ); - mGeneralDock->setObjectName( "CompositionDock" ); + mGeneralDock->setObjectName( QStringLiteral( "CompositionDock" ) ); mGeneralDock->setMinimumWidth( minDockWidth ); mGeneralPropertiesStack = new QgsPanelWidgetStack(); mGeneralDock->setWidget( mGeneralPropertiesStack ); mPanelMenu->addAction( mGeneralDock->toggleViewAction() ); mItemDock = new QgsDockWidget( tr( "Item properties" ), this ); - mItemDock->setObjectName( "ItemDock" ); + mItemDock->setObjectName( QStringLiteral( "ItemDock" ) ); mItemDock->setMinimumWidth( minDockWidth ); mItemPropertiesStack = new QgsPanelWidgetStack(); mItemDock->setWidget( mItemPropertiesStack ); mPanelMenu->addAction( mItemDock->toggleViewAction() ); mUndoDock = new QgsDockWidget( tr( "Command history" ), this ); - mUndoDock->setObjectName( "CommandDock" ); + mUndoDock->setObjectName( QStringLiteral( "CommandDock" ) ); mPanelMenu->addAction( mUndoDock->toggleViewAction() ); mAtlasDock = new QgsDockWidget( tr( "Atlas generation" ), this ); - mAtlasDock->setObjectName( "AtlasDock" ); + mAtlasDock->setObjectName( QStringLiteral( "AtlasDock" ) ); mPanelMenu->addAction( mAtlasDock->toggleViewAction() ); mItemsDock = new QgsDockWidget( tr( "Items" ), this ); - mItemsDock->setObjectName( "ItemsDock" ); + mItemsDock->setObjectName( QStringLiteral( "ItemsDock" ) ); mPanelMenu->addAction( mItemsDock->toggleViewAction() ); QList docks = findChildren(); @@ -706,54 +706,54 @@ void QgsComposer::setupTheme() { //now set all the icons - getThemeIcon will fall back to default theme if its //missing from active theme - mActionQuit->setIcon( QgsApplication::getThemeIcon( "/mActionFileExit.png" ) ); - mActionSaveProject->setIcon( QgsApplication::getThemeIcon( "/mActionFileSave.svg" ) ); - mActionNewComposer->setIcon( QgsApplication::getThemeIcon( "/mActionNewComposer.svg" ) ); - mActionDuplicateComposer->setIcon( QgsApplication::getThemeIcon( "/mActionDuplicateComposer.svg" ) ); - mActionComposerManager->setIcon( QgsApplication::getThemeIcon( "/mActionComposerManager.svg" ) ); - mActionLoadFromTemplate->setIcon( QgsApplication::getThemeIcon( "/mActionFileOpen.svg" ) ); - mActionSaveAsTemplate->setIcon( QgsApplication::getThemeIcon( "/mActionFileSaveAs.svg" ) ); - mActionExportAsImage->setIcon( QgsApplication::getThemeIcon( "/mActionSaveMapAsImage.svg" ) ); - mActionExportAsSVG->setIcon( QgsApplication::getThemeIcon( "/mActionSaveAsSVG.svg" ) ); - mActionExportAsPDF->setIcon( QgsApplication::getThemeIcon( "/mActionSaveAsPDF.svg" ) ); - mActionPrint->setIcon( QgsApplication::getThemeIcon( "/mActionFilePrint.svg" ) ); - mActionZoomAll->setIcon( QgsApplication::getThemeIcon( "/mActionZoomFullExtent.svg" ) ); - mActionZoomIn->setIcon( QgsApplication::getThemeIcon( "/mActionZoomIn.svg" ) ); - mActionZoomOut->setIcon( QgsApplication::getThemeIcon( "/mActionZoomOut.svg" ) ); - mActionZoomActual->setIcon( QgsApplication::getThemeIcon( "/mActionZoomActual.svg" ) ); - mActionMouseZoom->setIcon( QgsApplication::getThemeIcon( "/mActionZoomToArea.svg" ) ); - mActionRefreshView->setIcon( QgsApplication::getThemeIcon( "/mActionDraw.svg" ) ); - mActionUndo->setIcon( QgsApplication::getThemeIcon( "/mActionUndo.svg" ) ); - mActionRedo->setIcon( QgsApplication::getThemeIcon( "/mActionRedo.svg" ) ); - mActionAddImage->setIcon( QgsApplication::getThemeIcon( "/mActionAddImage.svg" ) ); - mActionAddNewMap->setIcon( QgsApplication::getThemeIcon( "/mActionAddMap.svg" ) ); - mActionAddNewLabel->setIcon( QgsApplication::getThemeIcon( "/mActionLabel.svg" ) ); - mActionAddNewLegend->setIcon( QgsApplication::getThemeIcon( "/mActionAddLegend.svg" ) ); - mActionAddNewScalebar->setIcon( QgsApplication::getThemeIcon( "/mActionScaleBar.svg" ) ); - mActionAddRectangle->setIcon( QgsApplication::getThemeIcon( "/mActionAddBasicRectangle.svg" ) ); - mActionAddTriangle->setIcon( QgsApplication::getThemeIcon( "/mActionAddBasicTriangle.svg" ) ); - mActionAddEllipse->setIcon( QgsApplication::getThemeIcon( "/mActionAddBasicCircle.svg" ) ); - mActionAddPolygon->setIcon( QgsApplication::getThemeIcon( "/mActionAddPolygon.svg" ) ); - mActionAddPolyline->setIcon( QgsApplication::getThemeIcon( "/mActionAddPolyline.svg" ) ); - mActionAddArrow->setIcon( QgsApplication::getThemeIcon( "/mActionAddArrow.svg" ) ); - mActionAddTable->setIcon( QgsApplication::getThemeIcon( "/mActionAddTable.svg" ) ); - mActionAddAttributeTable->setIcon( QgsApplication::getThemeIcon( "/mActionAddTable.svg" ) ); - mActionAddHtml->setIcon( QgsApplication::getThemeIcon( "/mActionAddHtml.svg" ) ); - mActionSelectMoveItem->setIcon( QgsApplication::getThemeIcon( "/mActionSelect.svg" ) ); - mActionMoveItemContent->setIcon( QgsApplication::getThemeIcon( "/mActionMoveItemContent.svg" ) ); - mActionEditNodesItem->setIcon( QgsApplication::getThemeIcon( "/mActionEditNodesItem.svg" ) ); - mActionGroupItems->setIcon( QgsApplication::getThemeIcon( "/mActionGroupItems.svg" ) ); - mActionUngroupItems->setIcon( QgsApplication::getThemeIcon( "/mActionUngroupItems.svg" ) ); - mActionRaiseItems->setIcon( QgsApplication::getThemeIcon( "/mActionRaiseItems.svg" ) ); - mActionLowerItems->setIcon( QgsApplication::getThemeIcon( "/mActionLowerItems.svg" ) ); - mActionMoveItemsToTop->setIcon( QgsApplication::getThemeIcon( "/mActionMoveItemsToTop.svg" ) ); - mActionMoveItemsToBottom->setIcon( QgsApplication::getThemeIcon( "/mActionMoveItemsToBottom.svg" ) ); - mActionAlignLeft->setIcon( QgsApplication::getThemeIcon( "/mActionAlignLeft.svg" ) ); - mActionAlignHCenter->setIcon( QgsApplication::getThemeIcon( "/mActionAlignHCenter.svg" ) ); - mActionAlignRight->setIcon( QgsApplication::getThemeIcon( "/mActionAlignRight.svg" ) ); - mActionAlignTop->setIcon( QgsApplication::getThemeIcon( "/mActionAlignTop.svg" ) ); - mActionAlignVCenter->setIcon( QgsApplication::getThemeIcon( "/mActionAlignVCenter.svg" ) ); - mActionAlignBottom->setIcon( QgsApplication::getThemeIcon( "/mActionAlignBottom.svg" ) ); + mActionQuit->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileExit.png" ) ) ); + mActionSaveProject->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileSave.svg" ) ) ); + mActionNewComposer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewComposer.svg" ) ) ); + mActionDuplicateComposer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDuplicateComposer.svg" ) ) ); + mActionComposerManager->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionComposerManager.svg" ) ) ); + mActionLoadFromTemplate->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileOpen.svg" ) ) ); + mActionSaveAsTemplate->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileSaveAs.svg" ) ) ); + mActionExportAsImage->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveMapAsImage.svg" ) ) ); + mActionExportAsSVG->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveAsSVG.svg" ) ) ); + mActionExportAsPDF->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveAsPDF.svg" ) ) ); + mActionPrint->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFilePrint.svg" ) ) ); + mActionZoomAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomFullExtent.svg" ) ) ); + mActionZoomIn->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomIn.svg" ) ) ); + mActionZoomOut->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomOut.svg" ) ) ); + mActionZoomActual->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomActual.svg" ) ) ); + mActionMouseZoom->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomToArea.svg" ) ) ); + mActionRefreshView->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDraw.svg" ) ) ); + mActionUndo->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionUndo.svg" ) ) ); + mActionRedo->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRedo.svg" ) ) ); + mActionAddImage->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddImage.svg" ) ) ); + mActionAddNewMap->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddMap.svg" ) ) ); + mActionAddNewLabel->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionLabel.svg" ) ) ); + mActionAddNewLegend->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddLegend.svg" ) ) ); + mActionAddNewScalebar->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionScaleBar.svg" ) ) ); + mActionAddRectangle->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddBasicRectangle.svg" ) ) ); + mActionAddTriangle->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddBasicTriangle.svg" ) ) ); + mActionAddEllipse->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddBasicCircle.svg" ) ) ); + mActionAddPolygon->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddPolygon.svg" ) ) ); + mActionAddPolyline->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddPolyline.svg" ) ) ); + mActionAddArrow->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddArrow.svg" ) ) ); + mActionAddTable->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddTable.svg" ) ) ); + mActionAddAttributeTable->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddTable.svg" ) ) ); + mActionAddHtml->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddHtml.svg" ) ) ); + mActionSelectMoveItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelect.svg" ) ) ); + mActionMoveItemContent->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveItemContent.svg" ) ) ); + mActionEditNodesItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditNodesItem.svg" ) ) ); + mActionGroupItems->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionGroupItems.svg" ) ) ); + mActionUngroupItems->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionUngroupItems.svg" ) ) ); + mActionRaiseItems->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRaiseItems.svg" ) ) ); + mActionLowerItems->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionLowerItems.svg" ) ) ); + mActionMoveItemsToTop->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveItemsToTop.svg" ) ) ); + mActionMoveItemsToBottom->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveItemsToBottom.svg" ) ) ); + mActionAlignLeft->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAlignLeft.svg" ) ) ); + mActionAlignHCenter->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAlignHCenter.svg" ) ) ); + mActionAlignRight->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAlignRight.svg" ) ) ); + mActionAlignTop->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAlignTop.svg" ) ) ); + mActionAlignVCenter->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAlignVCenter.svg" ) ) ); + mActionAlignBottom->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAlignBottom.svg" ) ) ); } void QgsComposer::setIconSizes( int size ) @@ -1026,7 +1026,7 @@ void QgsComposer::showItemOptions( QgsComposerItem* item ) void QgsComposer::on_mActionOptions_triggered() { - mQgis->showOptionsDialog( this, QString( "mOptionsPageComposer" ) ); + mQgis->showOptionsDialog( this, QStringLiteral( "mOptionsPageComposer" ) ); } void QgsComposer::toggleAtlasControls( bool atlasEnabled ) @@ -1059,7 +1059,7 @@ void QgsComposer::updateAtlasPageComboBox( int pageCount ) for ( int i = 1; i <= pageCount && i < 500; ++i ) { QString name = mComposition->atlasComposition().nameForPage( i - 1 ); - QString fullName = ( !name.isEmpty() ? QString( "%1: %2" ).arg( i ).arg( name ) : QString::number( i ) ); + QString fullName = ( !name.isEmpty() ? QStringLiteral( "%1: %2" ).arg( i ).arg( name ) : QString::number( i ) ); mAtlasPageComboBox->addItem( fullName, i ); mAtlasPageComboBox->setItemData( i - 1, name, Qt::UserRole + 1 ); @@ -1089,12 +1089,12 @@ void QgsComposer::atlasFeatureChanged( QgsFeature *feature ) mAtlasPageComboBox->blockSignals( false ); //update expression context variables in map canvas to allow for previewing atlas feature based renderering - mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( "atlas_featurenumber", mComposition->atlasComposition().currentFeatureNumber() + 1, true ) ); - mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( "atlas_pagename", mComposition->atlasComposition().currentPageName(), true ) ); + mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_featurenumber" ), mComposition->atlasComposition().currentFeatureNumber() + 1, true ) ); + mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_pagename" ), mComposition->atlasComposition().currentPageName(), true ) ); QgsFeature atlasFeature = mComposition->atlasComposition().feature(); - mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( "atlas_feature", QVariant::fromValue( atlasFeature ), true ) ); - mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( "atlas_featureid", atlasFeature.id(), true ) ); - mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( "atlas_geometry", QVariant::fromValue( atlasFeature.geometry() ), true ) ); + mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_feature" ), QVariant::fromValue( atlasFeature ), true ) ); + mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_featureid" ), atlasFeature.id(), true ) ); + mapCanvas()->expressionContextScope().addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_geometry" ), QVariant::fromValue( atlasFeature.geometry() ), true ) ); } void QgsComposer::on_mActionAtlasPreview_triggered( bool checked ) @@ -1404,7 +1404,7 @@ void QgsComposer::toggleRulers( bool checked ) mRulerLayoutFix->setVisible( checked ); QSettings myQSettings; - myQSettings.setValue( "/Composer/showRulers", checked ); + myQSettings.setValue( QStringLiteral( "/Composer/showRulers" ), checked ); } void QgsComposer::on_mActionAtlasSettings_triggered() @@ -1654,7 +1654,7 @@ void QgsComposer::exportCompositionAsPDF( QgsComposer::OutputMode mode ) if ( mode == QgsComposer::Single || ( mode == QgsComposer::Atlas && atlasOnASingleFile ) ) { QSettings myQSettings; // where we keep last used filter in persistent state - QString lastUsedFile = myQSettings.value( "/UI/lastSaveAsPdfFile", "qgis.pdf" ).toString(); + QString lastUsedFile = myQSettings.value( QStringLiteral( "/UI/lastSaveAsPdfFile" ), "qgis.pdf" ).toString(); QFileInfo file( lastUsedFile ); if ( hasAnAtlas && !atlasOnASingleFile && @@ -1681,12 +1681,12 @@ void QgsComposer::exportCompositionAsPDF( QgsComposer::OutputMode mode ) return; } - if ( !outputFileName.endsWith( ".pdf", Qt::CaseInsensitive ) ) + if ( !outputFileName.endsWith( QLatin1String( ".pdf" ), Qt::CaseInsensitive ) ) { - outputFileName += ".pdf"; + outputFileName += QLatin1String( ".pdf" ); } - myQSettings.setValue( "/UI/lastSaveAsPdfFile", outputFileName ); + myQSettings.setValue( QStringLiteral( "/UI/lastSaveAsPdfFile" ), outputFileName ); } // else, we need to choose a directory else @@ -1701,11 +1701,11 @@ void QgsComposer::exportCompositionAsPDF( QgsComposer::OutputMode mode ) { return; } - atlasMap->setFilenamePattern( "'output_'||@atlas_featurenumber" ); + atlasMap->setFilenamePattern( QStringLiteral( "'output_'||@atlas_featurenumber" ) ); } QSettings myQSettings; - QString lastUsedDir = myQSettings.value( "/UI/lastSaveAtlasAsPdfDir", QDir::homePath() ).toString(); + QString lastUsedDir = myQSettings.value( QStringLiteral( "/UI/lastSaveAtlasAsPdfDir" ), QDir::homePath() ).toString(); outputDir = QFileDialog::getExistingDirectory( this, tr( "Export atlas to directory" ), lastUsedDir, @@ -1724,7 +1724,7 @@ void QgsComposer::exportCompositionAsPDF( QgsComposer::OutputMode mode ) return; } - myQSettings.setValue( "/UI/lastSaveAtlasAsPdfDir", outputDir ); + myQSettings.setValue( QStringLiteral( "/UI/lastSaveAtlasAsPdfDir" ), outputDir ); } mView->setPaintingEnabled( false ); @@ -2029,11 +2029,11 @@ void QgsComposer::exportCompositionAsImage( QgsComposer::OutputMode mode ) } //get some defaults from the composition - bool cropToContents = mComposition->customProperty( "imageCropToContents", false ).toBool(); - int marginTop = mComposition->customProperty( "imageCropMarginTop", 0 ).toInt(); - int marginRight = mComposition->customProperty( "imageCropMarginRight", 0 ).toInt(); - int marginBottom = mComposition->customProperty( "imageCropMarginBottom", 0 ).toInt(); - int marginLeft = mComposition->customProperty( "imageCropMarginLeft", 0 ).toInt(); + bool cropToContents = mComposition->customProperty( QStringLiteral( "imageCropToContents" ), false ).toBool(); + int marginTop = mComposition->customProperty( QStringLiteral( "imageCropMarginTop" ), 0 ).toInt(); + int marginRight = mComposition->customProperty( QStringLiteral( "imageCropMarginRight" ), 0 ).toInt(); + int marginBottom = mComposition->customProperty( QStringLiteral( "imageCropMarginBottom" ), 0 ).toInt(); + int marginLeft = mComposition->customProperty( QStringLiteral( "imageCropMarginLeft" ), 0 ).toInt(); QgsComposerImageExportOptionsDialog imageDlg( this ); imageDlg.setImageSize( QSizeF( mComposition->paperWidth(), mComposition->paperHeight() ) ); @@ -2048,7 +2048,7 @@ void QgsComposer::exportCompositionAsImage( QgsComposer::OutputMode mode ) if ( atlasMap->enabled() && mComposition->atlasMode() == QgsComposition::PreviewAtlas ) { - QString lastUsedDir = settings.value( "/UI/lastSaveAsImageDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastSaveAsImageDir" ), QDir::homePath() ).toString(); outputFileName = QDir( lastUsedDir ).filePath( atlasMap->currentFilename() ); } @@ -2069,11 +2069,11 @@ void QgsComposer::exportCompositionAsImage( QgsComposer::OutputMode mode ) cropToContents = imageDlg.cropToContents(); imageDlg.getCropMargins( marginTop, marginRight, marginBottom, marginLeft ); - mComposition->setCustomProperty( "imageCropToContents", cropToContents ); - mComposition->setCustomProperty( "imageCropMarginTop", marginTop ); - mComposition->setCustomProperty( "imageCropMarginRight", marginRight ); - mComposition->setCustomProperty( "imageCropMarginBottom", marginBottom ); - mComposition->setCustomProperty( "imageCropMarginLeft", marginLeft ); + mComposition->setCustomProperty( QStringLiteral( "imageCropToContents" ), cropToContents ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginTop" ), marginTop ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginRight" ), marginRight ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginBottom" ), marginBottom ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginLeft" ), marginLeft ); mView->setPaintingEnabled( false ); @@ -2195,12 +2195,12 @@ void QgsComposer::exportCompositionAsImage( QgsComposer::OutputMode mode ) { return; } - atlasMap->setFilenamePattern( "'output_'||@atlas_featurenumber" ); + atlasMap->setFilenamePattern( QStringLiteral( "'output_'||@atlas_featurenumber" ) ); } QSettings myQSettings; - QString lastUsedDir = myQSettings.value( "/UI/lastSaveAtlasAsImagesDir", QDir::homePath() ).toString(); - QString lastUsedFormat = myQSettings.value( "/UI/lastSaveAtlasAsImagesFormat", "jpg" ).toString(); + QString lastUsedDir = myQSettings.value( QStringLiteral( "/UI/lastSaveAtlasAsImagesDir" ), QDir::homePath() ).toString(); + QString lastUsedFormat = myQSettings.value( QStringLiteral( "/UI/lastSaveAtlasAsImagesFormat" ), "jpg" ).toString(); QFileDialog dlg( this, tr( "Export atlas to directory" ) ); dlg.setFileMode( QFileDialog::Directory ); @@ -2264,13 +2264,13 @@ void QgsComposer::exportCompositionAsImage( QgsComposer::OutputMode mode ) cropToContents = imageDlg.cropToContents(); imageDlg.getCropMargins( marginTop, marginRight, marginBottom, marginLeft ); - mComposition->setCustomProperty( "imageCropToContents", cropToContents ); - mComposition->setCustomProperty( "imageCropMarginTop", marginTop ); - mComposition->setCustomProperty( "imageCropMarginRight", marginRight ); - mComposition->setCustomProperty( "imageCropMarginBottom", marginBottom ); - mComposition->setCustomProperty( "imageCropMarginLeft", marginLeft ); + mComposition->setCustomProperty( QStringLiteral( "imageCropToContents" ), cropToContents ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginTop" ), marginTop ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginRight" ), marginRight ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginBottom" ), marginBottom ); + mComposition->setCustomProperty( QStringLiteral( "imageCropMarginLeft" ), marginLeft ); - myQSettings.setValue( "/UI/lastSaveAtlasAsImagesDir", dir ); + myQSettings.setValue( QStringLiteral( "/UI/lastSaveAtlasAsImagesDir" ), dir ); // So, now we can render the atlas mView->setPaintingEnabled( false ); @@ -2470,7 +2470,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) showWmsPrintingWarning(); } - QString settingsLabel = "/UI/displaySVGWarning"; + QString settingsLabel = QStringLiteral( "/UI/displaySVGWarning" ); QSettings settings; bool displaySVGWarning = settings.value( settingsLabel, true ).toBool(); @@ -2501,7 +2501,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) QString outputFileName; QString outputDir; bool groupLayers = false; - bool prevSettingLabelsAsOutlines = QgsProject::instance()->readBoolEntry( "PAL", "/DrawOutlineLabels", true ); + bool prevSettingLabelsAsOutlines = QgsProject::instance()->readBoolEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), true ); bool clipToContent = false; double marginTop = 0.0; double marginRight = 0.0; @@ -2510,7 +2510,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) if ( mode == QgsComposer::Single ) { - QString lastUsedFile = settings.value( "/UI/lastSaveAsSvgFile", "qgis.svg" ).toString(); + QString lastUsedFile = settings.value( QStringLiteral( "/UI/lastSaveAsSvgFile" ), "qgis.svg" ).toString(); QFileInfo file( lastUsedFile ); if ( atlasMap->enabled() && mComposition->atlasMode() == QgsComposition::PreviewAtlas ) @@ -2537,12 +2537,12 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) if ( outputFileName.isEmpty() ) return; - if ( !outputFileName.endsWith( ".svg", Qt::CaseInsensitive ) ) + if ( !outputFileName.endsWith( QLatin1String( ".svg" ), Qt::CaseInsensitive ) ) { - outputFileName += ".svg"; + outputFileName += QLatin1String( ".svg" ); } - settings.setValue( "/UI/lastSaveAsSvgFile", outputFileName ); + settings.setValue( QStringLiteral( "/UI/lastSaveAsSvgFile" ), outputFileName ); } else { @@ -2557,11 +2557,11 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) { return; } - atlasMap->setFilenamePattern( "'output_'||@atlas_featurenumber" ); + atlasMap->setFilenamePattern( QStringLiteral( "'output_'||@atlas_featurenumber" ) ); } QSettings myQSettings; - QString lastUsedDir = myQSettings.value( "/UI/lastSaveAtlasAsSvgDir", QDir::homePath() ).toString(); + QString lastUsedDir = myQSettings.value( QStringLiteral( "/UI/lastSaveAtlasAsSvgDir" ), QDir::homePath() ).toString(); // open file dialog outputDir = QFileDialog::getExistingDirectory( this, @@ -2582,7 +2582,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) QMessageBox::Ok ); return; } - myQSettings.setValue( "/UI/lastSaveAtlasAsSvgDir", outputDir ); + myQSettings.setValue( QStringLiteral( "/UI/lastSaveAtlasAsSvgDir" ), outputDir ); } // open options dialog @@ -2590,12 +2590,12 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) Ui::QgsSvgExportOptionsDialog options; options.setupUi( &dialog ); options.chkTextAsOutline->setChecked( prevSettingLabelsAsOutlines ); - options.chkMapLayersAsGroup->setChecked( mComposition->customProperty( "svgGroupLayers", false ).toBool() ); - options.mClipToContentGroupBox->setChecked( mComposition->customProperty( "svgCropToContents", false ).toBool() ); - options.mTopMarginSpinBox->setValue( mComposition->customProperty( "svgCropMarginTop", 0 ).toInt() ); - options.mRightMarginSpinBox->setValue( mComposition->customProperty( "svgCropMarginRight", 0 ).toInt() ); - options.mBottomMarginSpinBox->setValue( mComposition->customProperty( "svgCropMarginBottom", 0 ).toInt() ); - options.mLeftMarginSpinBox->setValue( mComposition->customProperty( "svgCropMarginLeft", 0 ).toInt() ); + options.chkMapLayersAsGroup->setChecked( mComposition->customProperty( QStringLiteral( "svgGroupLayers" ), false ).toBool() ); + options.mClipToContentGroupBox->setChecked( mComposition->customProperty( QStringLiteral( "svgCropToContents" ), false ).toBool() ); + options.mTopMarginSpinBox->setValue( mComposition->customProperty( QStringLiteral( "svgCropMarginTop" ), 0 ).toInt() ); + options.mRightMarginSpinBox->setValue( mComposition->customProperty( QStringLiteral( "svgCropMarginRight" ), 0 ).toInt() ); + options.mBottomMarginSpinBox->setValue( mComposition->customProperty( QStringLiteral( "svgCropMarginBottom" ), 0 ).toInt() ); + options.mLeftMarginSpinBox->setValue( mComposition->customProperty( QStringLiteral( "svgCropMarginLeft" ), 0 ).toInt() ); if ( dialog.exec() != QDialog::Accepted ) return; @@ -2608,15 +2608,15 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) marginLeft = options.mLeftMarginSpinBox->value(); //save dialog settings - mComposition->setCustomProperty( "svgGroupLayers", groupLayers ); - mComposition->setCustomProperty( "svgCropToContents", clipToContent ); - mComposition->setCustomProperty( "svgCropMarginTop", marginTop ); - mComposition->setCustomProperty( "svgCropMarginRight", marginRight ); - mComposition->setCustomProperty( "svgCropMarginBottom", marginBottom ); - mComposition->setCustomProperty( "svgCropMarginLeft", marginLeft ); + mComposition->setCustomProperty( QStringLiteral( "svgGroupLayers" ), groupLayers ); + mComposition->setCustomProperty( QStringLiteral( "svgCropToContents" ), clipToContent ); + mComposition->setCustomProperty( QStringLiteral( "svgCropMarginTop" ), marginTop ); + mComposition->setCustomProperty( QStringLiteral( "svgCropMarginRight" ), marginRight ); + mComposition->setCustomProperty( QStringLiteral( "svgCropMarginBottom" ), marginBottom ); + mComposition->setCustomProperty( QStringLiteral( "svgCropMarginLeft" ), marginLeft ); //temporarily override label draw outlines setting - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", options.chkTextAsOutline->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), options.chkTextAsOutline->isChecked() ); mView->setPaintingEnabled( false ); @@ -2631,7 +2631,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) QMessageBox::Ok, QMessageBox::Ok ); mView->setPaintingEnabled( true ); - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", prevSettingLabelsAsOutlines ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), prevSettingLabelsAsOutlines ); return; } } @@ -2660,7 +2660,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) QMessageBox::Ok, QMessageBox::Ok ); mView->setPaintingEnabled( true ); - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", prevSettingLabelsAsOutlines ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), prevSettingLabelsAsOutlines ); return; } outputFileName = QDir( outputDir ).filePath( atlasMap->currentFilename() ) + ".svg"; @@ -2728,7 +2728,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) QMessageBox::Ok, QMessageBox::Ok ); mView->setPaintingEnabled( true ); - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", prevSettingLabelsAsOutlines ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), prevSettingLabelsAsOutlines ); return; } @@ -2855,15 +2855,15 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) { svg = QDomDocument( doc.doctype() ); svg.appendChild( svg.importNode( doc.firstChild(), false ) ); - svgDocRoot = svg.importNode( doc.elementsByTagName( "svg" ).at( 0 ), false ); - svgDocRoot.toElement().setAttribute( "xmlns:inkscape", "http://www.inkscape.org/namespaces/inkscape" ); + svgDocRoot = svg.importNode( doc.elementsByTagName( QStringLiteral( "svg" ) ).at( 0 ), false ); + svgDocRoot.toElement().setAttribute( QStringLiteral( "xmlns:inkscape" ), QStringLiteral( "http://www.inkscape.org/namespaces/inkscape" ) ); svg.appendChild( svgDocRoot ); } - QDomNode mainGroup = svg.importNode( doc.elementsByTagName( "g" ).at( 0 ), true ); - mainGroup.toElement().setAttribute( "id", layerName ); - mainGroup.toElement().setAttribute( "inkscape:label", layerName ); - mainGroup.toElement().setAttribute( "inkscape:groupmode", "layer" ); - QDomNode defs = svg.importNode( doc.elementsByTagName( "defs" ).at( 0 ), true ); + QDomNode mainGroup = svg.importNode( doc.elementsByTagName( QStringLiteral( "g" ) ).at( 0 ), true ); + mainGroup.toElement().setAttribute( QStringLiteral( "id" ), layerName ); + mainGroup.toElement().setAttribute( QStringLiteral( "inkscape:label" ), layerName ); + mainGroup.toElement().setAttribute( QStringLiteral( "inkscape:groupmode" ), QStringLiteral( "layer" ) ); + QDomNode defs = svg.importNode( doc.elementsByTagName( QStringLiteral( "defs" ) ).at( 0 ), true ); svgDocRoot.appendChild( defs ); svgDocRoot.appendChild( mainGroup ); } @@ -2886,7 +2886,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) QMessageBox::Ok, QMessageBox::Ok ); mView->setPaintingEnabled( true ); - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", prevSettingLabelsAsOutlines ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), prevSettingLabelsAsOutlines ); return; } @@ -2901,7 +2901,7 @@ void QgsComposer::exportCompositionAsSVG( QgsComposer::OutputMode mode ) atlasMap->endRender(); mView->setPaintingEnabled( true ); - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", prevSettingLabelsAsOutlines ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), prevSettingLabelsAsOutlines ); } void QgsComposer::on_mActionSelectMoveItem_triggered() @@ -3077,7 +3077,7 @@ void QgsComposer::on_mActionSaveAsTemplate_triggered() { //show file dialog QSettings settings; - QString lastSaveDir = settings.value( "UI/lastComposerTemplateDir", QDir::homePath() ).toString(); + QString lastSaveDir = settings.value( QStringLiteral( "UI/lastComposerTemplateDir" ), QDir::homePath() ).toString(); #ifdef Q_OS_MAC mQgis->activateWindow(); this->raise(); @@ -3097,7 +3097,7 @@ void QgsComposer::on_mActionSaveAsTemplate_triggered() QString saveFileNameWithSuffix = saveFileName.append( ".qpt" ); saveFileInfo = QFileInfo( saveFileNameWithSuffix ); } - settings.setValue( "UI/lastComposerTemplateDir", saveFileInfo.absolutePath() ); + settings.setValue( QStringLiteral( "UI/lastComposerTemplateDir" ), saveFileInfo.absolutePath() ); QFile templateFile( saveFileName ); if ( !templateFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) @@ -3120,8 +3120,8 @@ void QgsComposer::on_mActionLoadFromTemplate_triggered() return; QSettings settings; - QString openFileDir = settings.value( "UI/lastComposerTemplateDir", QDir::homePath() ).toString(); - QString openFileString = QFileDialog::getOpenFileName( nullptr, tr( "Load template" ), openFileDir, "*.qpt" ); + QString openFileDir = settings.value( QStringLiteral( "UI/lastComposerTemplateDir" ), QDir::homePath() ).toString(); + QString openFileString = QFileDialog::getOpenFileName( nullptr, tr( "Load template" ), openFileDir, QStringLiteral( "*.qpt" ) ); if ( openFileString.isEmpty() ) { @@ -3129,7 +3129,7 @@ void QgsComposer::on_mActionLoadFromTemplate_triggered() } QFileInfo openFileInfo( openFileString ); - settings.setValue( "UI/LastComposerTemplateDir", openFileInfo.absolutePath() ); + settings.setValue( QStringLiteral( "UI/LastComposerTemplateDir" ), openFileInfo.absolutePath() ); QFile templateFile( openFileString ); if ( !templateFile.open( QIODevice::ReadOnly ) ) @@ -3427,9 +3427,9 @@ void QgsComposer::showEvent( QShowEvent* event ) void QgsComposer::saveWindowState() { QSettings settings; - settings.setValue( "/Composer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Composer/geometry" ), saveGeometry() ); // store the toolbar/dock widget settings using Qt4 settings API - settings.setValue( "/ComposerUI/state", saveState() ); + settings.setValue( QStringLiteral( "/ComposerUI/state" ), saveState() ); } #include "ui_defaults.h" @@ -3439,12 +3439,12 @@ void QgsComposer::restoreWindowState() // restore the toolbar and dock widgets postions using Qt4 settings API QSettings settings; - if ( !restoreState( settings.value( "/ComposerUI/state", QByteArray::fromRawData(( char * )defaultComposerUIstate, sizeof defaultComposerUIstate ) ).toByteArray() ) ) + if ( !restoreState( settings.value( QStringLiteral( "/ComposerUI/state" ), QByteArray::fromRawData(( char * )defaultComposerUIstate, sizeof defaultComposerUIstate ) ).toByteArray() ) ) { QgsDebugMsg( "restore of composer UI state failed" ); } // restore window geometry - if ( !restoreGeometry( settings.value( "/Composer/geometry", QByteArray::fromRawData(( char * )defaultComposerUIgeometry, sizeof defaultComposerUIgeometry ) ).toByteArray() ) ) + if ( !restoreGeometry( settings.value( QStringLiteral( "/Composer/geometry" ), QByteArray::fromRawData(( char * )defaultComposerUIgeometry, sizeof defaultComposerUIgeometry ) ).toByteArray() ) ) { QgsDebugMsg( "restore of composer UI geometry failed" ); } @@ -3453,7 +3453,7 @@ void QgsComposer::restoreWindowState() void QgsComposer::writeXml( QDomDocument& doc ) { - QDomNodeList nl = doc.elementsByTagName( "qgis" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "qgis" ) ); if ( nl.count() < 1 ) { return; @@ -3469,8 +3469,8 @@ void QgsComposer::writeXml( QDomDocument& doc ) void QgsComposer::writeXml( QDomNode& parentNode, QDomDocument& doc ) { - QDomElement composerElem = doc.createElement( "Composer" ); - composerElem.setAttribute( "title", mTitle ); + QDomElement composerElem = doc.createElement( QStringLiteral( "Composer" ) ); + composerElem.setAttribute( QStringLiteral( "title" ), mTitle ); //change preview mode of minimised / hidden maps before saving XML (show contents only on demand) QMap< QgsComposerMap*, int >::const_iterator mapIt = mMapsToRestore.constBegin(); @@ -3499,7 +3499,7 @@ void QgsComposer::templateXml( QDomDocument& doc ) void QgsComposer::readXml( const QDomDocument& doc ) { - QDomNodeList composerNodeList = doc.elementsByTagName( "Composer" ); + QDomNodeList composerNodeList = doc.elementsByTagName( QStringLiteral( "Composer" ) ); if ( composerNodeList.size() < 1 ) { return; @@ -3528,9 +3528,9 @@ void QgsComposer::readXml( const QDomElement& composerElem, const QDomDocument& // Set title only if reading from project file if ( !fromTemplate ) { - if ( composerElem.hasAttribute( "title" ) ) + if ( composerElem.hasAttribute( QStringLiteral( "title" ) ) ) { - setTitle( composerElem.attribute( "title", tr( "Composer" ) ) ); + setTitle( composerElem.attribute( QStringLiteral( "title" ), tr( "Composer" ) ) ); } } @@ -3545,7 +3545,7 @@ void QgsComposer::readXml( const QDomElement& composerElem, const QDomDocument& //read composition settings mComposition = new QgsComposition( mQgis->mapCanvas()->mapSettings() ); - QDomNodeList compositionNodeList = composerElem.elementsByTagName( "Composition" ); + QDomNodeList compositionNodeList = composerElem.elementsByTagName( QStringLiteral( "Composition" ) ); if ( compositionNodeList.size() > 0 ) { QDomElement compositionElem = compositionNodeList.at( 0 ).toElement(); @@ -3560,7 +3560,7 @@ void QgsComposer::readXml( const QDomElement& composerElem, const QDomDocument& if ( mComposition ) { // read atlas parameters - must be done before adding items - atlasElem = composerElem.firstChildElement( "Atlas" ); + atlasElem = composerElem.firstChildElement( QStringLiteral( "Atlas" ) ); mComposition->atlasComposition().readXml( atlasElem, doc ); mComposition->addItemsFromXml( composerElem, doc, &mMapsToRestore ); @@ -3851,7 +3851,7 @@ bool QgsComposer::containsAdvancedEffects() const void QgsComposer::showWmsPrintingWarning() { - QString myQSettingsLabel = "/UI/displayComposerWMSWarning"; + QString myQSettingsLabel = QStringLiteral( "/UI/displayComposerWMSWarning" ); QSettings myQSettings; bool displayWMSWarning = myQSettings.value( myQSettingsLabel, true ).toBool(); @@ -4120,7 +4120,7 @@ void QgsComposer::updateAtlasMapLayerAction( QgsVectorLayer *coverageLayer ) { mAtlasFeatureAction = new QgsMapLayerAction( QString( tr( "Set as atlas feature for %1" ) ).arg( mTitle ), this, coverageLayer, QgsMapLayerAction::SingleFeature , - QgsApplication::getThemeIcon( "/mIconAtlas.svg" ) ); + QgsApplication::getThemeIcon( QStringLiteral( "/mIconAtlas.svg" ) ) ); QgsMapLayerActionRegistry::instance()->addMapLayerAction( mAtlasFeatureAction ); connect( mAtlasFeatureAction, SIGNAL( triggeredForFeature( QgsMapLayer*, const QgsFeature& ) ), this, SLOT( setAtlasFeature( QgsMapLayer*, const QgsFeature& ) ) ); } @@ -4165,7 +4165,7 @@ void QgsComposer::updateAtlasMapLayerAction( bool atlasEnabled ) QgsAtlasComposition& atlas = mComposition->atlasComposition(); mAtlasFeatureAction = new QgsMapLayerAction( QString( tr( "Set as atlas feature for %1" ) ).arg( mTitle ), this, atlas.coverageLayer(), QgsMapLayerAction::SingleFeature , - QgsApplication::getThemeIcon( "/mIconAtlas.svg" ) ); + QgsApplication::getThemeIcon( QStringLiteral( "/mIconAtlas.svg" ) ) ); QgsMapLayerActionRegistry::instance()->addMapLayerAction( mAtlasFeatureAction ); connect( mAtlasFeatureAction, SIGNAL( triggeredForFeature( QgsMapLayer*, const QgsFeature& ) ), this, SLOT( setAtlasFeature( QgsMapLayer*, const QgsFeature& ) ) ); } @@ -4180,13 +4180,13 @@ void QgsComposer::loadAtlasPredefinedScalesFromProject() QgsAtlasComposition& atlasMap = mComposition->atlasComposition(); QVector pScales; // first look at project's scales - QStringList scales( QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ) ); - bool hasProjectScales( QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ) ); + QStringList scales( QgsProject::instance()->readListEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ) ) ); + bool hasProjectScales( QgsProject::instance()->readBoolEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ) ) ); if ( !hasProjectScales || scales.isEmpty() ) { // default to global map tool scales QSettings settings; - QString scalesStr( settings.value( "Map/scales", PROJECT_SCALES ).toString() ); + QString scalesStr( settings.value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString() ); scales = scalesStr.split( ',' ); } diff --git a/src/app/composer/qgscomposerarrowwidget.cpp b/src/app/composer/qgscomposerarrowwidget.cpp index 1c144604d5f2..ca7a5758d0b9 100644 --- a/src/app/composer/qgscomposerarrowwidget.cpp +++ b/src/app/composer/qgscomposerarrowwidget.cpp @@ -44,12 +44,12 @@ QgsComposerArrowWidget::QgsComposerArrowWidget( QgsComposerArrow* arrow ): QgsCo mArrowHeadOutlineColorButton->setColorDialogTitle( tr( "Select arrow head outline color" ) ); mArrowHeadOutlineColorButton->setAllowAlpha( true ); - mArrowHeadOutlineColorButton->setContext( "composer" ); + mArrowHeadOutlineColorButton->setContext( QStringLiteral( "composer" ) ); mArrowHeadOutlineColorButton->setNoColorString( tr( "Transparent outline" ) ); mArrowHeadOutlineColorButton->setShowNoColor( true ); mArrowHeadFillColorButton->setColorDialogTitle( tr( "Select arrow head fill color" ) ); mArrowHeadFillColorButton->setAllowAlpha( true ); - mArrowHeadFillColorButton->setContext( "composer" ); + mArrowHeadFillColorButton->setContext( QStringLiteral( "composer" ) ); mArrowHeadFillColorButton->setNoColorString( tr( "Transparent fill" ) ); mArrowHeadFillColorButton->setShowNoColor( true ); @@ -241,7 +241,7 @@ void QgsComposerArrowWidget::on_mStartMarkerLineEdit_textChanged( const QString } else { - mArrow->setStartMarker( "" ); + mArrow->setStartMarker( QLatin1String( "" ) ); } mArrow->update(); mArrow->endCommand(); @@ -260,7 +260,7 @@ void QgsComposerArrowWidget::on_mEndMarkerLineEdit_textChanged( const QString & } else { - mArrow->setEndMarker( "" ); + mArrow->setEndMarker( QLatin1String( "" ) ); } mArrow->update(); mArrow->endCommand(); @@ -280,14 +280,14 @@ void QgsComposerArrowWidget::on_mStartMarkerToolButton_clicked() if ( openDir.isEmpty() ) { - openDir = s.value( "/UI/lastComposerMarkerDir", QDir::homePath() ).toString(); + openDir = s.value( QStringLiteral( "/UI/lastComposerMarkerDir" ), QDir::homePath() ).toString(); } QString svgFileName = QFileDialog::getOpenFileName( this, tr( "Start marker svg file" ), openDir ); if ( !svgFileName.isNull() ) { QFileInfo fileInfo( svgFileName ); - s.setValue( "/UI/lastComposerMarkerDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastComposerMarkerDir" ), fileInfo.absolutePath() ); mArrow->beginCommand( tr( "Arrow start marker" ) ); mStartMarkerLineEdit->setText( svgFileName ); mArrow->endCommand(); @@ -307,14 +307,14 @@ void QgsComposerArrowWidget::on_mEndMarkerToolButton_clicked() if ( openDir.isEmpty() ) { - openDir = s.value( "/UI/lastComposerMarkerDir", QDir::homePath() ).toString(); + openDir = s.value( QStringLiteral( "/UI/lastComposerMarkerDir" ), QDir::homePath() ).toString(); } QString svgFileName = QFileDialog::getOpenFileName( this, tr( "End marker svg file" ), openDir ); if ( !svgFileName.isNull() ) { QFileInfo fileInfo( svgFileName ); - s.setValue( "/UI/lastComposerMarkerDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastComposerMarkerDir" ), fileInfo.absolutePath() ); mArrow->beginCommand( tr( "Arrow end marker" ) ); mEndMarkerLineEdit->setText( svgFileName ); mArrow->endCommand(); diff --git a/src/app/composer/qgscomposerattributetablewidget.cpp b/src/app/composer/qgscomposerattributetablewidget.cpp index 12ed6eaff16f..78dfea418bba 100644 --- a/src/app/composer/qgscomposerattributetablewidget.cpp +++ b/src/app/composer/qgscomposerattributetablewidget.cpp @@ -70,17 +70,17 @@ QgsComposerAttributeTableWidget::QgsComposerAttributeTableWidget( QgsComposerAtt mHeaderFontColorButton->setColorDialogTitle( tr( "Select header font color" ) ); mHeaderFontColorButton->setAllowAlpha( true ); - mHeaderFontColorButton->setContext( "composer" ); + mHeaderFontColorButton->setContext( QStringLiteral( "composer" ) ); mContentFontColorButton->setColorDialogTitle( tr( "Select content font color" ) ); mContentFontColorButton->setAllowAlpha( true ); - mContentFontColorButton->setContext( "composer" ); + mContentFontColorButton->setContext( QStringLiteral( "composer" ) ); mGridColorButton->setColorDialogTitle( tr( "Select grid color" ) ); mGridColorButton->setAllowAlpha( true ); - mGridColorButton->setContext( "composer" ); + mGridColorButton->setContext( QStringLiteral( "composer" ) ); mGridColorButton->setDefaultColor( Qt::black ); mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) ); mBackgroundColorButton->setAllowAlpha( true ); - mBackgroundColorButton->setContext( "composer" ); + mBackgroundColorButton->setContext( QStringLiteral( "composer" ) ); mBackgroundColorButton->setShowNoColor( true ); mBackgroundColorButton->setNoColorString( tr( "No background" ) ); @@ -785,7 +785,7 @@ void QgsComposerAttributeTableWidget::on_mFeatureFilterButton_clicked() } QgsExpressionContext context = mComposerTable->createExpressionContext(); - QgsExpressionBuilderDialog exprDlg( mComposerTable->sourceLayer(), mFeatureFilterEdit->text(), this, "generic", context ); + QgsExpressionBuilderDialog exprDlg( mComposerTable->sourceLayer(), mFeatureFilterEdit->text(), this, QStringLiteral( "generic" ), context ); exprDlg.setWindowTitle( tr( "Expression based filter" ) ); if ( exprDlg.exec() == QDialog::Accepted ) { diff --git a/src/app/composer/qgscomposerhtmlwidget.cpp b/src/app/composer/qgscomposerhtmlwidget.cpp index ca4c48eba1a7..2c058d9ea0c2 100644 --- a/src/app/composer/qgscomposerhtmlwidget.cpp +++ b/src/app/composer/qgscomposerhtmlwidget.cpp @@ -122,15 +122,15 @@ void QgsComposerHtmlWidget::on_mUrlLineEdit_editingFinished() void QgsComposerHtmlWidget::on_mFileToolButton_clicked() { QSettings s; - QString lastDir = s.value( "/UI/lastHtmlDir", QDir::homePath() ).toString(); - QString file = QFileDialog::getOpenFileName( this, tr( "Select HTML document" ), lastDir, "HTML (*.html *.htm);;All files (*.*)" ); + QString lastDir = s.value( QStringLiteral( "/UI/lastHtmlDir" ), QDir::homePath() ).toString(); + QString file = QFileDialog::getOpenFileName( this, tr( "Select HTML document" ), lastDir, QStringLiteral( "HTML (*.html *.htm);;All files (*.*)" ) ); if ( !file.isEmpty() ) { QUrl url = QUrl::fromLocalFile( file ); mUrlLineEdit->setText( url.toString() ); on_mUrlLineEdit_editingFinished(); mHtml->update(); - s.setValue( "/UI/lastHtmlDir", QFileInfo( file ).absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastHtmlDir" ), QFileInfo( file ).absolutePath() ); } } @@ -348,7 +348,7 @@ void QgsComposerHtmlWidget::on_mInsertExpressionButton_clicked() selText = mHtmlEditor->selectedText(); // edit the selected expression if there's one - if ( selText.startsWith( "[%" ) && selText.endsWith( "%]" ) ) + if ( selText.startsWith( QLatin1String( "[%" ) ) && selText.endsWith( QLatin1String( "%]" ) ) ) selText = selText.mid( 2, selText.size() - 4 ); } else @@ -359,7 +359,7 @@ void QgsComposerHtmlWidget::on_mInsertExpressionButton_clicked() // use the atlas coverage layer, if any QgsVectorLayer* coverageLayer = atlasCoverageLayer(); QgsExpressionContext context = mHtml->createExpressionContext(); - QgsExpressionBuilderDialog exprDlg( coverageLayer, selText, this, "generic", context ); + QgsExpressionBuilderDialog exprDlg( coverageLayer, selText, this, QStringLiteral( "generic" ), context ); exprDlg.setWindowTitle( tr( "Insert expression" ) ); if ( exprDlg.exec() == QDialog::Accepted ) { diff --git a/src/app/composer/qgscomposerimageexportoptionsdialog.cpp b/src/app/composer/qgscomposerimageexportoptionsdialog.cpp index 101930be10ef..1bd1242a5737 100644 --- a/src/app/composer/qgscomposerimageexportoptionsdialog.cpp +++ b/src/app/composer/qgscomposerimageexportoptionsdialog.cpp @@ -29,13 +29,13 @@ QgsComposerImageExportOptionsDialog::QgsComposerImageExportOptionsDialog( QWidge connect( mClipToContentGroupBox, SIGNAL( toggled( bool ) ), this, SLOT( clipToContentsToggled( bool ) ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ComposerImageExportOptionsDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ComposerImageExportOptionsDialog/geometry" ) ).toByteArray() ); } QgsComposerImageExportOptionsDialog::~QgsComposerImageExportOptionsDialog() { QSettings settings; - settings.setValue( "/Windows/ComposerImageExportOptionsDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ComposerImageExportOptionsDialog/geometry" ), saveGeometry() ); } void QgsComposerImageExportOptionsDialog::setResolution( int resolution ) diff --git a/src/app/composer/qgscomposeritemwidget.cpp b/src/app/composer/qgscomposeritemwidget.cpp index 30393dfdaf9d..11bea4e47093 100644 --- a/src/app/composer/qgscomposeritemwidget.cpp +++ b/src/app/composer/qgscomposeritemwidget.cpp @@ -82,7 +82,7 @@ void QgsComposerConfigObject::setDataDefinedProperty( const QgsDataDefinedButton } const QMap< QString, QString >& map = ddBtn->definedProperty(); - mComposerObject->setDataDefinedProperty( p, map.value( "active" ).toInt(), map.value( "useexpr" ).toInt(), map.value( "expression" ), map.value( "field" ) ); + mComposerObject->setDataDefinedProperty( p, map.value( QStringLiteral( "active" ) ).toInt(), map.value( QStringLiteral( "useexpr" ) ).toInt(), map.value( QStringLiteral( "expression" ) ), map.value( QStringLiteral( "field" ) ) ); } void QgsComposerConfigObject::registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, @@ -570,10 +570,10 @@ void QgsComposerItemWidget::setValuesForGuiElements() mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) ); mBackgroundColorButton->setAllowAlpha( true ); - mBackgroundColorButton->setContext( "composer" ); + mBackgroundColorButton->setContext( QStringLiteral( "composer" ) ); mFrameColorButton->setColorDialogTitle( tr( "Select frame color" ) ); mFrameColorButton->setAllowAlpha( true ); - mFrameColorButton->setContext( "composer" ); + mFrameColorButton->setContext( QStringLiteral( "composer" ) ); setValuesForGuiPositionElements(); setValuesForGuiNonPositionElements(); diff --git a/src/app/composer/qgscomposerlabelwidget.cpp b/src/app/composer/qgscomposerlabelwidget.cpp index 31d8b80fc969..2f1301855980 100644 --- a/src/app/composer/qgscomposerlabelwidget.cpp +++ b/src/app/composer/qgscomposerlabelwidget.cpp @@ -36,7 +36,7 @@ QgsComposerLabelWidget::QgsComposerLabelWidget( QgsComposerLabel* label ): QgsCo mainLayout->addWidget( itemPropertiesWidget ); mFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); - mFontColorButton->setContext( "composer" ); + mFontColorButton->setContext( QStringLiteral( "composer" ) ); mMarginXDoubleSpinBox->setClearValue( 0.0 ); mMarginYDoubleSpinBox->setClearValue( 0.0 ); @@ -141,13 +141,13 @@ void QgsComposerLabelWidget::on_mInsertExpressionButton_clicked() QString selText = mTextEdit->textCursor().selectedText(); // edit the selected expression if there's one - if ( selText.startsWith( "[%" ) && selText.endsWith( "%]" ) ) + if ( selText.startsWith( QLatin1String( "[%" ) ) && selText.endsWith( QLatin1String( "%]" ) ) ) selText = selText.mid( 2, selText.size() - 4 ); // use the atlas coverage layer, if any QgsVectorLayer* coverageLayer = atlasCoverageLayer(); QgsExpressionContext context = mComposerLabel->createExpressionContext(); - QgsExpressionBuilderDialog exprDlg( coverageLayer, selText, this, "generic", context ); + QgsExpressionBuilderDialog exprDlg( coverageLayer, selText, this, QStringLiteral( "generic" ), context ); exprDlg.setWindowTitle( tr( "Insert expression" ) ); if ( exprDlg.exec() == QDialog::Accepted ) diff --git a/src/app/composer/qgscomposerlegendwidget.cpp b/src/app/composer/qgscomposerlegendwidget.cpp index 6bd430175369..00462649b19c 100644 --- a/src/app/composer/qgscomposerlegendwidget.cpp +++ b/src/app/composer/qgscomposerlegendwidget.cpp @@ -58,11 +58,11 @@ QgsComposerLegendWidget::QgsComposerLegendWidget( QgsComposerLegend* legend ) mCountToolButton->setIcon( QIcon( QgsApplication::iconPath( "mActionSum.svg" ) ) ); mFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); - mFontColorButton->setContext( "composer" ); + mFontColorButton->setContext( QStringLiteral( "composer" ) ); mRasterBorderColorButton->setColorDialogTitle( tr( "Select border color" ) ); mRasterBorderColorButton->setAllowAlpha( true ); - mRasterBorderColorButton->setContext( "composer " ); + mRasterBorderColorButton->setContext( QStringLiteral( "composer " ) ); mMapComboBox->setComposition( legend->composition() ); mMapComboBox->setItemType( QgsComposerItem::ComposerMap ); @@ -470,7 +470,7 @@ void QgsComposerLegendWidget::on_mMoveDownToolButton_clicked() if ( !node && !legendNode ) return; - mLegend->beginCommand( "Moved legend item down" ); + mLegend->beginCommand( QStringLiteral( "Moved legend item down" ) ); if ( node ) { @@ -507,7 +507,7 @@ void QgsComposerLegendWidget::on_mMoveUpToolButton_clicked() if ( !node && !legendNode ) return; - mLegend->beginCommand( "Moved legend item up" ); + mLegend->beginCommand( QStringLiteral( "Moved legend item up" ) ); if ( node ) { @@ -529,7 +529,7 @@ void QgsComposerLegendWidget::on_mMoveUpToolButton_clicked() void QgsComposerLegendWidget::on_mCheckBoxAutoUpdate_stateChanged( int state ) { - mLegend->beginCommand( "Auto update changed" ); + mLegend->beginCommand( QStringLiteral( "Auto update changed" ) ); mLegend->setAutoUpdateModel( state == Qt::Checked ); @@ -654,7 +654,7 @@ void QgsComposerLegendWidget::on_mAddToolButton_clicked() QgsMapLayer* layer = addDialog.selectedLayer(); if ( layer ) { - mLegend->beginCommand( "Legend item added" ); + mLegend->beginCommand( QStringLiteral( "Legend item added" ) ); mLegend->model()->rootGroup()->addLayer( layer ); mLegend->endCommand(); } @@ -675,7 +675,7 @@ void QgsComposerLegendWidget::on_mRemoveToolButton_clicked() return; } - mLegend->beginCommand( "Legend item removed" ); + mLegend->beginCommand( QStringLiteral( "Legend item removed" ) ); QList indexes; Q_FOREACH ( const QModelIndex &index, selectionModel->selectedIndexes() ) @@ -762,7 +762,7 @@ void QgsComposerLegendWidget::resetLayerNodeToDefaults() Q_FOREACH ( const QString& key, nodeLayer->customProperties() ) { - if ( key.startsWith( "legend/" ) ) + if ( key.startsWith( QLatin1String( "legend/" ) ) ) nodeLayer->removeCustomProperty( key ); } @@ -793,7 +793,7 @@ void QgsComposerLegendWidget::on_mCountToolButton_clicked( bool checked ) return; mLegend->beginCommand( tr( "Legend updated" ) ); - currentNode->setCustomProperty( "showFeatureCount", checked ? 1 : 0 ); + currentNode->setCustomProperty( QStringLiteral( "showFeatureCount" ), checked ? 1 : 0 ); mLegend->updateItem(); mLegend->adjustBoxSize(); mLegend->endCommand(); @@ -932,7 +932,7 @@ void QgsComposerLegendWidget::selectedChanged( const QModelIndex & current, cons if ( !vl ) return; - mCountToolButton->setChecked( currentNode->customProperty( "showFeatureCount", 0 ).toInt() ); + mCountToolButton->setChecked( currentNode->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() ); mCountToolButton->setEnabled( true ); bool exprEnabled; @@ -980,7 +980,7 @@ void QgsComposerLegendWidget::on_mItemTreeView_doubleClicked( const QModelIndex else if ( QgsLayerTree::isLayer( currentNode ) ) { currentText = QgsLayerTree::toLayer( currentNode )->layerName(); - QVariant v = currentNode->customProperty( "legend/title-label" ); + QVariant v = currentNode->customProperty( QStringLiteral( "legend/title-label" ) ); if ( !v.isNull() ) currentText = v.toString(); } @@ -1003,7 +1003,7 @@ void QgsComposerLegendWidget::on_mItemTreeView_doubleClicked( const QModelIndex } else if ( QgsLayerTree::isLayer( currentNode ) ) { - currentNode->setCustomProperty( "legend/title-label", newText ); + currentNode->setCustomProperty( QStringLiteral( "legend/title-label" ), newText ); // force update of label of the legend node with embedded icon (a bit clumsy i know) QList nodes = model->layerLegendNodes( QgsLayerTree::toLayer( currentNode ) ); diff --git a/src/app/composer/qgscomposermanager.cpp b/src/app/composer/qgscomposermanager.cpp index e5fc62783922..c93518f44e4f 100644 --- a/src/app/composer/qgscomposermanager.cpp +++ b/src/app/composer/qgscomposermanager.cpp @@ -37,7 +37,7 @@ QgsComposerManager::QgsComposerManager( QWidget * parent, Qt::WindowFlags f ): Q setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ComposerManager/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ComposerManager/geometry" ) ).toByteArray() ); mComposerListWidget->setItemDelegate( new QgsComposerNameDelegate( mComposerListWidget ) ); @@ -77,7 +77,7 @@ QgsComposerManager::QgsComposerManager( QWidget * parent, Qt::WindowFlags f ): Q this->addTemplates( defaultTemplateMap ); this->addTemplates( this->otherTemplates() ); - mTemplatePathLineEdit->setText( settings.value( "/UI/ComposerManager/templatePath", QString() ).toString() ); + mTemplatePathLineEdit->setText( settings.value( QStringLiteral( "/UI/ComposerManager/templatePath" ), QString() ).toString() ); refreshComposers(); } @@ -85,7 +85,7 @@ QgsComposerManager::QgsComposerManager( QWidget * parent, Qt::WindowFlags f ): Q QgsComposerManager::~QgsComposerManager() { QSettings settings; - settings.setValue( "/Windows/ComposerManager/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ComposerManager/geometry" ), saveGeometry() ); } void QgsComposerManager::refreshComposers() @@ -229,7 +229,7 @@ QMap QgsComposerManager::templatesFromPath( const QString& pat QFileInfoList::const_iterator infoIt = fileInfoList.constBegin(); for ( ; infoIt != fileInfoList.constEnd(); ++infoIt ) { - if ( infoIt->suffix().toLower() == "qpt" ) + if ( infoIt->suffix().toLower() == QLatin1String( "qpt" ) ) { templateMap.insert( infoIt->baseName(), infoIt->absoluteFilePath() ); } @@ -313,7 +313,7 @@ void QgsComposerManager::on_mTemplate_currentIndexChanged( int indx ) void QgsComposerManager::on_mTemplatePathBtn_pressed() { QSettings settings; - QString lastTmplDir = settings.value( "/UI/lastComposerTemplateDir", QDir::homePath() ).toString(); + QString lastTmplDir = settings.value( QStringLiteral( "/UI/lastComposerTemplateDir" ), QDir::homePath() ).toString(); QString tmplPath = QFileDialog::getOpenFileName( this, tr( "Choose template" ), lastTmplDir, @@ -321,9 +321,9 @@ void QgsComposerManager::on_mTemplatePathBtn_pressed() if ( !tmplPath.isEmpty() ) { mTemplatePathLineEdit->setText( tmplPath ); - settings.setValue( "UI/ComposerManager/templatePath", tmplPath ); + settings.setValue( QStringLiteral( "UI/ComposerManager/templatePath" ), tmplPath ); QFileInfo tmplFileInfo( tmplPath ); - settings.setValue( "UI/lastComposerTemplateDir", tmplFileInfo.absolutePath() ); + settings.setValue( QStringLiteral( "UI/lastComposerTemplateDir" ), tmplFileInfo.absolutePath() ); } } diff --git a/src/app/composer/qgscomposermapgridwidget.cpp b/src/app/composer/qgscomposermapgridwidget.cpp index 49eddeb410df..9ee86981aabd 100644 --- a/src/app/composer/qgscomposermapgridwidget.cpp +++ b/src/app/composer/qgscomposermapgridwidget.cpp @@ -59,7 +59,7 @@ QgsComposerMapGridWidget::QgsComposerMapGridWidget( QgsComposerMapGrid* mapGrid, mAnnotationFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); mAnnotationFontColorButton->setAllowAlpha( true ); - mAnnotationFontColorButton->setContext( "composer" ); + mAnnotationFontColorButton->setContext( QStringLiteral( "composer" ) ); insertAnnotationDisplayEntries( mAnnotationDisplayLeftComboBox ); insertAnnotationDisplayEntries( mAnnotationDisplayRightComboBox ); @@ -78,19 +78,19 @@ QgsComposerMapGridWidget::QgsComposerMapGridWidget( QgsComposerMapGrid* mapGrid, mGridFramePenColorButton->setColorDialogTitle( tr( "Select grid frame color" ) ); mGridFramePenColorButton->setAllowAlpha( true ); - mGridFramePenColorButton->setContext( "composer" ); + mGridFramePenColorButton->setContext( QStringLiteral( "composer" ) ); mGridFramePenColorButton->setNoColorString( tr( "Transparent frame" ) ); mGridFramePenColorButton->setShowNoColor( true ); mGridFrameFill1ColorButton->setColorDialogTitle( tr( "Select grid frame fill color" ) ); mGridFrameFill1ColorButton->setAllowAlpha( true ); - mGridFrameFill1ColorButton->setContext( "composer" ); + mGridFrameFill1ColorButton->setContext( QStringLiteral( "composer" ) ); mGridFrameFill1ColorButton->setNoColorString( tr( "Transparent fill" ) ); mGridFrameFill1ColorButton->setShowNoColor( true ); mGridFrameFill2ColorButton->setColorDialogTitle( tr( "Select grid frame fill color" ) ); mGridFrameFill2ColorButton->setAllowAlpha( true ); - mGridFrameFill2ColorButton->setContext( "composer" ); + mGridFrameFill2ColorButton->setContext( QStringLiteral( "composer" ) ); mGridFrameFill2ColorButton->setNoColorString( tr( "Transparent fill" ) ); mGridFrameFill2ColorButton->setShowNoColor( true ); @@ -431,15 +431,15 @@ void QgsComposerMapGridWidget::initAnnotationDirectionBox( QComboBox* c, QgsComp bool QgsComposerMapGridWidget::hasPredefinedScales() const { // first look at project's scales - QStringList scales( QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ) ); - bool hasProjectScales( QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ) ); + QStringList scales( QgsProject::instance()->readListEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ) ) ); + bool hasProjectScales( QgsProject::instance()->readBoolEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ) ) ); if ( !hasProjectScales || scales.isEmpty() ) { // default to global map tool scales QSettings settings; - QString scalesStr( settings.value( "Map/scales", PROJECT_SCALES ).toString() ); + QString scalesStr( settings.value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString() ); QStringList myScalesList = scalesStr.split( ',' ); - return !myScalesList.isEmpty() && myScalesList[0] != ""; + return !myScalesList.isEmpty() && myScalesList[0] != QLatin1String( "" ); } return true; } @@ -1072,7 +1072,7 @@ void QgsComposerMapGridWidget::on_mAnnotationFormatButton_clicked() QgsExpressionContext expressionContext = mComposerMapGrid->createExpressionContext(); - QgsExpressionBuilderDialog exprDlg( nullptr, mComposerMapGrid->annotationExpression(), this, "generic", expressionContext ); + QgsExpressionBuilderDialog exprDlg( nullptr, mComposerMapGrid->annotationExpression(), this, QStringLiteral( "generic" ), expressionContext ); exprDlg.setWindowTitle( tr( "Expression based annotation" ) ); if ( exprDlg.exec() == QDialog::Accepted ) diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index e43ac8978ac5..fc6240f9b066 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -74,7 +74,7 @@ QgsComposerMapWidget::QgsComposerMapWidget( QgsComposerMap* composerMap ) // keep layers from preset button QMenu* menuKeepLayers = new QMenu( this ); mLayerListFromPresetButton->setMenu( menuKeepLayers ); - mLayerListFromPresetButton->setIcon( QgsApplication::getThemeIcon( "/mActionShowAllLayers.svg" ) ); + mLayerListFromPresetButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowAllLayers.svg" ) ) ); mLayerListFromPresetButton->setToolTip( tr( "Set layer list from a map theme" ) ); connect( menuKeepLayers, SIGNAL( aboutToShow() ), this, SLOT( aboutToShowKeepLayersVisibilityPresetsMenu() ) ); @@ -1038,15 +1038,15 @@ void QgsComposerMapWidget::atlasLayerChanged( QgsVectorLayer* layer ) bool QgsComposerMapWidget::hasPredefinedScales() const { // first look at project's scales - QStringList scales( QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ) ); - bool hasProjectScales( QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ) ); + QStringList scales( QgsProject::instance()->readListEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ) ) ); + bool hasProjectScales( QgsProject::instance()->readBoolEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ) ) ); if ( !hasProjectScales || scales.isEmpty() ) { // default to global map tool scales QSettings settings; - QString scalesStr( settings.value( "Map/scales", PROJECT_SCALES ).toString() ); + QString scalesStr( settings.value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString() ); QStringList myScalesList = scalesStr.split( ',' ); - return !myScalesList.isEmpty() && myScalesList[0] != ""; + return !myScalesList.isEmpty() && myScalesList[0] != QLatin1String( "" ); } return true; } diff --git a/src/app/composer/qgscomposerpicturewidget.cpp b/src/app/composer/qgscomposerpicturewidget.cpp index 458d0898407a..57ea1a536e66 100644 --- a/src/app/composer/qgscomposerpicturewidget.cpp +++ b/src/app/composer/qgscomposerpicturewidget.cpp @@ -40,10 +40,10 @@ QgsComposerPictureWidget::QgsComposerPictureWidget( QgsComposerPicture* picture mFillColorButton->setAllowAlpha( true ); mFillColorButton->setColorDialogTitle( tr( "Select fill color" ) ); - mFillColorButton->setContext( "composer" ); + mFillColorButton->setContext( QStringLiteral( "composer" ) ); mOutlineColorButton->setAllowAlpha( true ); mOutlineColorButton->setColorDialogTitle( tr( "Select outline color" ) ); - mOutlineColorButton->setContext( "composer" ); + mOutlineColorButton->setContext( QStringLiteral( "composer" ) ); mNorthTypeComboBox->blockSignals( true ); mNorthTypeComboBox->addItem( tr( "Grid north" ), QgsComposerPicture::GridNorth ); @@ -98,7 +98,7 @@ void QgsComposerPictureWidget::on_mPictureBrowseButton_clicked() if ( openDir.isEmpty() ) { - openDir = s.value( "/UI/lastComposerPictureDir", QDir::homePath() ).toString(); + openDir = s.value( QStringLiteral( "/UI/lastComposerPictureDir" ), QDir::homePath() ).toString(); } //show file dialog @@ -112,11 +112,11 @@ void QgsComposerPictureWidget::on_mPictureBrowseButton_clicked() QFileInfo fileInfo( filePath ); if ( !fileInfo.exists() || !fileInfo.isReadable() ) { - QMessageBox::critical( nullptr, "Invalid file", "Error, file does not exist or is not readable" ); + QMessageBox::critical( nullptr, QStringLiteral( "Invalid file" ), QStringLiteral( "Error, file does not exist or is not readable" ) ); return; } - s.setValue( "/UI/lastComposerPictureDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastComposerPictureDir" ), fileInfo.absolutePath() ); mPictureLineEdit->blockSignals( true ); mPictureLineEdit->setText( filePath ); @@ -191,12 +191,12 @@ void QgsComposerPictureWidget::on_mAddDirectoryButton_clicked() //update the image directory list in the settings QSettings s; - QStringList userDirList = s.value( "/Composer/PictureWidgetDirectories" ).toStringList(); + QStringList userDirList = s.value( QStringLiteral( "/Composer/PictureWidgetDirectories" ) ).toStringList(); if ( !userDirList.contains( directory ) ) { userDirList.append( directory ); } - s.setValue( "/Composer/PictureWidgetDirectories", userDirList ); + s.setValue( QStringLiteral( "/Composer/PictureWidgetDirectories" ), userDirList ); } void QgsComposerPictureWidget::on_mRemoveDirectoryButton_clicked() @@ -220,9 +220,9 @@ void QgsComposerPictureWidget::on_mRemoveDirectoryButton_clicked() //update the image directory list in the settings QSettings s; - QStringList userDirList = s.value( "/Composer/PictureWidgetDirectories" ).toStringList(); + QStringList userDirList = s.value( QStringLiteral( "/Composer/PictureWidgetDirectories" ) ).toStringList(); userDirList.removeOne( directoryToRemove ); - s.setValue( "/Composer/PictureWidgetDirectories", userDirList ); + s.setValue( QStringLiteral( "/Composer/PictureWidgetDirectories" ), userDirList ); } void QgsComposerPictureWidget::on_mResizeModeComboBox_currentIndexChanged( int index ) @@ -445,7 +445,7 @@ void QgsComposerPictureWidget::updateSvgParamGui( bool resetValues ) return; QString picturePath = mPicture->picturePath(); - if ( !picturePath.endsWith( ".svg", Qt::CaseInsensitive ) ) + if ( !picturePath.endsWith( QLatin1String( ".svg" ), Qt::CaseInsensitive ) ) { mFillColorButton->setEnabled( false ); mOutlineColorButton->setEnabled( false ); @@ -509,7 +509,7 @@ int QgsComposerPictureWidget::addDirectoryToPreview( const QString& path ) QFileInfoList fileList = directory.entryInfoList( QDir::Files ); QFileInfoList::const_iterator fileIt = fileList.constBegin(); - QProgressDialog progress( "Adding Icons...", "Abort", 0, fileList.size() - 1, this ); + QProgressDialog progress( QStringLiteral( "Adding Icons..." ), QStringLiteral( "Abort" ), 0, fileList.size() - 1, this ); //cancel button does not seem to work properly with modal dialog //progress.setWindowModality(Qt::WindowModal); @@ -564,7 +564,7 @@ int QgsComposerPictureWidget::addDirectoryToPreview( const QString& path ) listItem->setIcon( icon ); } - listItem->setText( "" ); + listItem->setText( QLatin1String( "" ) ); //store the absolute icon file path as user data listItem->setData( Qt::UserRole, fileIt->absoluteFilePath() ); ++counter; @@ -605,7 +605,7 @@ void QgsComposerPictureWidget::addStandardDirectoriesToPreview() //include additional user-defined directories for images QSettings s; - QStringList userDirList = s.value( "/Composer/PictureWidgetDirectories" ).toStringList(); + QStringList userDirList = s.value( QStringLiteral( "/Composer/PictureWidgetDirectories" ) ).toStringList(); QStringList::const_iterator userDirIt = userDirList.constBegin(); for ( ; userDirIt != userDirList.constEnd(); ++userDirIt ) { @@ -620,7 +620,7 @@ bool QgsComposerPictureWidget::testSvgFile( const QString& filename ) const { //QSvgRenderer crashes with some (non-svg) xml documents. //So at least we try to sort out the ones with different suffixes - if ( !filename.endsWith( ".svg" ) ) + if ( !filename.endsWith( QLatin1String( ".svg" ) ) ) { return false; } diff --git a/src/app/composer/qgscomposerscalebarwidget.cpp b/src/app/composer/qgscomposerscalebarwidget.cpp index 102b6dc1dffb..d205b041bd3f 100644 --- a/src/app/composer/qgscomposerscalebarwidget.cpp +++ b/src/app/composer/qgscomposerscalebarwidget.cpp @@ -62,23 +62,23 @@ QgsComposerScaleBarWidget::QgsComposerScaleBarWidget( QgsComposerScaleBar* scale mFillColorButton->setColorDialogTitle( tr( "Select fill color" ) ); mFillColorButton->setAllowAlpha( true ); - mFillColorButton->setContext( "composer" ); + mFillColorButton->setContext( QStringLiteral( "composer" ) ); mFillColorButton->setNoColorString( tr( "Transparent fill" ) ); mFillColorButton->setShowNoColor( true ); mFillColor2Button->setColorDialogTitle( tr( "Select alternate fill color" ) ); mFillColor2Button->setAllowAlpha( true ); - mFillColor2Button->setContext( "composer" ); + mFillColor2Button->setContext( QStringLiteral( "composer" ) ); mFillColor2Button->setNoColorString( tr( "Transparent fill" ) ); mFillColor2Button->setShowNoColor( true ); mFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); mFontColorButton->setAllowAlpha( true ); - mFontColorButton->setContext( "composer" ); + mFontColorButton->setContext( QStringLiteral( "composer" ) ); mStrokeColorButton->setColorDialogTitle( tr( "Select line color" ) ); mStrokeColorButton->setAllowAlpha( true ); - mStrokeColorButton->setContext( "composer" ); + mStrokeColorButton->setContext( QStringLiteral( "composer" ) ); mStrokeColorButton->setNoColorString( tr( "Transparent line" ) ); mStrokeColorButton->setShowNoColor( true ); @@ -364,31 +364,31 @@ void QgsComposerScaleBarWidget::on_mStyleComboBox_currentIndexChanged( const QSt QString untranslatedStyleName; if ( text == tr( "Single Box" ) ) { - untranslatedStyleName = "Single Box"; + untranslatedStyleName = QStringLiteral( "Single Box" ); } else if ( text == tr( "Double Box" ) ) { - untranslatedStyleName = "Double Box"; + untranslatedStyleName = QStringLiteral( "Double Box" ); } else if ( text == tr( "Line Ticks Middle" ) ) { - untranslatedStyleName = "Line Ticks Middle"; + untranslatedStyleName = QStringLiteral( "Line Ticks Middle" ); } else if ( text == tr( "Line Ticks Middle" ) ) { - untranslatedStyleName = "Line Ticks Middle"; + untranslatedStyleName = QStringLiteral( "Line Ticks Middle" ); } else if ( text == tr( "Line Ticks Down" ) ) { - untranslatedStyleName = "Line Ticks Down"; + untranslatedStyleName = QStringLiteral( "Line Ticks Down" ); } else if ( text == tr( "Line Ticks Up" ) ) { - untranslatedStyleName = "Line Ticks Up"; + untranslatedStyleName = QStringLiteral( "Line Ticks Up" ); } else if ( text == tr( "Numeric" ) ) { - untranslatedStyleName = "Numeric"; + untranslatedStyleName = QStringLiteral( "Numeric" ); } //disable or enable controls which apply to specific scale bar styles @@ -402,7 +402,7 @@ void QgsComposerScaleBarWidget::on_mStyleComboBox_currentIndexChanged( const QSt void QgsComposerScaleBarWidget::toggleStyleSpecificControls( const QString& style ) { - if ( style == "Numeric" ) + if ( style == QLatin1String( "Numeric" ) ) { //Disable controls which don't apply to numeric scale bars mGroupBoxUnits->setEnabled( false ); @@ -427,7 +427,7 @@ void QgsComposerScaleBarWidget::toggleStyleSpecificControls( const QString& styl mFillColorButton->setEnabled( true ); mFillColor2Button->setEnabled( true ); mStrokeColorButton->setEnabled( true ); - if ( style == "Single Box" || style == "Double Box" ) + if ( style == QLatin1String( "Single Box" ) || style == QLatin1String( "Double Box" ) ) { mLineJoinStyleCombo->setEnabled( true ); mLineCapStyleCombo->setEnabled( false ); diff --git a/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp b/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp index 33cc88a31d16..23f0678d468d 100644 --- a/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp +++ b/src/app/composer/qgscomposertablebackgroundcolorsdialog.cpp @@ -51,7 +51,7 @@ QgsComposerTableBackgroundColorsDialog::QgsComposerTableBackgroundColorsDialog( connect( buttonBox->button( QDialogButtonBox::Apply ), SIGNAL( clicked() ), this, SLOT( apply() ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ComposerTableBackgroundColorsDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ComposerTableBackgroundColorsDialog/geometry" ) ).toByteArray() ); setGuiElementValues(); } @@ -59,7 +59,7 @@ QgsComposerTableBackgroundColorsDialog::QgsComposerTableBackgroundColorsDialog( QgsComposerTableBackgroundColorsDialog::~QgsComposerTableBackgroundColorsDialog() { QSettings settings; - settings.setValue( "/Windows/ComposerTableBackgroundColorsDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ComposerTableBackgroundColorsDialog/geometry" ), saveGeometry() ); } void QgsComposerTableBackgroundColorsDialog::apply() diff --git a/src/app/composer/qgscompositionwidget.cpp b/src/app/composer/qgscompositionwidget.cpp index 873fe92b7440..13f91864560f 100644 --- a/src/app/composer/qgscompositionwidget.cpp +++ b/src/app/composer/qgscompositionwidget.cpp @@ -224,7 +224,7 @@ void QgsCompositionWidget::setDataDefinedProperty( const QgsDataDefinedButton* d } const QMap< QString, QString >& map = ddBtn->definedProperty(); - mComposition->setDataDefinedProperty( property, map.value( "active" ).toInt(), map.value( "useexpr" ).toInt(), map.value( "expression" ), map.value( "field" ) ); + mComposition->setDataDefinedProperty( property, map.value( QStringLiteral( "active" ) ).toInt(), map.value( QStringLiteral( "useexpr" ) ).toInt(), map.value( QStringLiteral( "expression" ) ), map.value( QStringLiteral( "field" ) ) ); } QgsComposerObject::DataDefinedProperty QgsCompositionWidget::ddPropertyForWidget( QgsDataDefinedButton *widget ) diff --git a/src/app/gps/qgsgpsinformationwidget.cpp b/src/app/gps/qgsgpsinformationwidget.cpp index 1513058472c1..cf9b948a1b35 100644 --- a/src/app/gps/qgsgpsinformationwidget.cpp +++ b/src/app/gps/qgsgpsinformationwidget.cpp @@ -172,33 +172,33 @@ QgsGPSInformationWidget::QgsGPSInformationWidget( QgsMapCanvas * thepCanvas, QWi // Restore state QSettings mySettings; - mGroupShowMarker->setChecked( mySettings.value( "/gps/showMarker", "true" ).toBool() ); - mSliderMarkerSize->setValue( mySettings.value( "/gps/markerSize", "12" ).toInt() ); - mSpinTrackWidth->setValue( mySettings.value( "/gps/trackWidth", "2" ).toInt() ); - mTrackColor = mySettings.value( "/gps/trackColor", QColor( Qt::red ) ).value(); - QString myPortMode = mySettings.value( "/gps/portMode", "scanPorts" ).toString(); + mGroupShowMarker->setChecked( mySettings.value( QStringLiteral( "/gps/showMarker" ), "true" ).toBool() ); + mSliderMarkerSize->setValue( mySettings.value( QStringLiteral( "/gps/markerSize" ), "12" ).toInt() ); + mSpinTrackWidth->setValue( mySettings.value( QStringLiteral( "/gps/trackWidth" ), "2" ).toInt() ); + mTrackColor = mySettings.value( QStringLiteral( "/gps/trackColor" ), QColor( Qt::red ) ).value(); + QString myPortMode = mySettings.value( QStringLiteral( "/gps/portMode" ), "scanPorts" ).toString(); - mSpinMapExtentMultiplier->setValue( mySettings.value( "/gps/mapExtentMultiplier", "50" ).toInt() ); - mDateTimeFormat = mySettings.value( "/gps/dateTimeFormat", "" ).toString(); // zero-length string signifies default format + mSpinMapExtentMultiplier->setValue( mySettings.value( QStringLiteral( "/gps/mapExtentMultiplier" ), "50" ).toInt() ); + mDateTimeFormat = mySettings.value( QStringLiteral( "/gps/dateTimeFormat" ), "" ).toString(); // zero-length string signifies default format - mGpsdHost->setText( mySettings.value( "/gps/gpsdHost", "localhost" ).toString() ); - mGpsdPort->setText( mySettings.value( "/gps/gpsdPort", 2947 ).toString() ); - mGpsdDevice->setText( mySettings.value( "/gps/gpsdDevice" ).toString() ); + mGpsdHost->setText( mySettings.value( QStringLiteral( "/gps/gpsdHost" ), "localhost" ).toString() ); + mGpsdPort->setText( mySettings.value( QStringLiteral( "/gps/gpsdPort" ), 2947 ).toString() ); + mGpsdDevice->setText( mySettings.value( QStringLiteral( "/gps/gpsdDevice" ) ).toString() ); //port mode - if ( myPortMode == "scanPorts" ) + if ( myPortMode == QLatin1String( "scanPorts" ) ) { mRadAutodetect->setChecked( true ); } - else if ( myPortMode == "internalGPS" ) + else if ( myPortMode == QLatin1String( "internalGPS" ) ) { mRadInternal->setChecked( true ); } - else if ( myPortMode == "explicitPort" ) + else if ( myPortMode == QLatin1String( "explicitPort" ) ) { mRadUserPath->setChecked( true ); } - else if ( myPortMode == "gpsd" ) + else if ( myPortMode == QLatin1String( "gpsd" ) ) { mRadGpsd->setChecked( true ); } @@ -209,17 +209,17 @@ QgsGPSInformationWidget::QgsGPSInformationWidget( QgsMapCanvas * thepCanvas, QWi #endif //auto digitising behaviour - mCbxAutoAddVertices->setChecked( mySettings.value( "/gps/autoAddVertices", "false" ).toBool() ); + mCbxAutoAddVertices->setChecked( mySettings.value( QStringLiteral( "/gps/autoAddVertices" ), "false" ).toBool() ); - mCbxAutoCommit->setChecked( mySettings.value( "/gps/autoCommit", "false" ).toBool() ); + mCbxAutoCommit->setChecked( mySettings.value( QStringLiteral( "/gps/autoCommit" ), "false" ).toBool() ); //pan mode - QString myPanMode = mySettings.value( "/gps/panMode", "recenterWhenNeeded" ).toString(); - if ( myPanMode == "none" ) + QString myPanMode = mySettings.value( QStringLiteral( "/gps/panMode" ), "recenterWhenNeeded" ).toString(); + if ( myPanMode == QLatin1String( "none" ) ) { radNeverRecenter->setChecked( true ); } - else if ( myPanMode == "recenterAlways" ) + else if ( myPanMode == QLatin1String( "recenterAlways" ) ) { radRecenterMap->setChecked( true ); } @@ -228,9 +228,9 @@ QgsGPSInformationWidget::QgsGPSInformationWidget( QgsMapCanvas * thepCanvas, QWi radRecenterWhenNeeded->setChecked( true ); } - mWgs84CRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); + mWgs84CRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); - mBtnDebug->setVisible( mySettings.value( "/gps/showDebug", "false" ).toBool() ); // use a registry setting to control - power users/devs could set it + mBtnDebug->setVisible( mySettings.value( QStringLiteral( "/gps/showDebug" ), "false" ).toBool() ); // use a registry setting to control - power users/devs could set it // status = unknown setStatusIndicator( NoData ); @@ -260,50 +260,50 @@ QgsGPSInformationWidget::~QgsGPSInformationWidget() #endif QSettings mySettings; - mySettings.setValue( "/gps/lastPort", mCboDevices->currentData().toString() ); - mySettings.setValue( "/gps/trackWidth", mSpinTrackWidth->value() ); - mySettings.setValue( "/gps/trackColor", mTrackColor ); - mySettings.setValue( "/gps/markerSize", mSliderMarkerSize->value() ); - mySettings.setValue( "/gps/showMarker", mGroupShowMarker->isChecked() ); - mySettings.setValue( "/gps/autoAddVertices", mCbxAutoAddVertices->isChecked() ); - mySettings.setValue( "/gps/autoCommit", mCbxAutoCommit->isChecked() ); + mySettings.setValue( QStringLiteral( "/gps/lastPort" ), mCboDevices->currentData().toString() ); + mySettings.setValue( QStringLiteral( "/gps/trackWidth" ), mSpinTrackWidth->value() ); + mySettings.setValue( QStringLiteral( "/gps/trackColor" ), mTrackColor ); + mySettings.setValue( QStringLiteral( "/gps/markerSize" ), mSliderMarkerSize->value() ); + mySettings.setValue( QStringLiteral( "/gps/showMarker" ), mGroupShowMarker->isChecked() ); + mySettings.setValue( QStringLiteral( "/gps/autoAddVertices" ), mCbxAutoAddVertices->isChecked() ); + mySettings.setValue( QStringLiteral( "/gps/autoCommit" ), mCbxAutoCommit->isChecked() ); - mySettings.setValue( "/gps/mapExtentMultiplier", mSpinMapExtentMultiplier->value() ); + mySettings.setValue( QStringLiteral( "/gps/mapExtentMultiplier" ), mSpinMapExtentMultiplier->value() ); // scan, explicit port or gpsd if ( mRadAutodetect->isChecked() ) { - mySettings.setValue( "/gps/portMode", "scanPorts" ); + mySettings.setValue( QStringLiteral( "/gps/portMode" ), "scanPorts" ); } else if ( mRadInternal->isChecked() ) { - mySettings.setValue( "/gps/portMode", "internalGPS" ); + mySettings.setValue( QStringLiteral( "/gps/portMode" ), "internalGPS" ); } else if ( mRadUserPath->isChecked() ) { - mySettings.setValue( "/gps/portMode", "explicitPort" ); + mySettings.setValue( QStringLiteral( "/gps/portMode" ), "explicitPort" ); } else { - mySettings.setValue( "/gps/portMode", "gpsd" ); + mySettings.setValue( QStringLiteral( "/gps/portMode" ), "gpsd" ); } - mySettings.setValue( "/gps/gpsdHost", mGpsdHost->text() ); - mySettings.setValue( "/gps/gpsdPort", mGpsdPort->text().toInt() ); - mySettings.setValue( "/gps/gpsdDevice", mGpsdDevice->text() ); + mySettings.setValue( QStringLiteral( "/gps/gpsdHost" ), mGpsdHost->text() ); + mySettings.setValue( QStringLiteral( "/gps/gpsdPort" ), mGpsdPort->text().toInt() ); + mySettings.setValue( QStringLiteral( "/gps/gpsdDevice" ), mGpsdDevice->text() ); // pan mode if ( radRecenterMap->isChecked() ) { - mySettings.setValue( "/gps/panMode", "recenterAlways" ); + mySettings.setValue( QStringLiteral( "/gps/panMode" ), "recenterAlways" ); } else if ( radRecenterWhenNeeded->isChecked() ) { - mySettings.setValue( "/gps/panMode", "recenterWhenNeeded" ); + mySettings.setValue( QStringLiteral( "/gps/panMode" ), "recenterWhenNeeded" ); } else { - mySettings.setValue( "/gps/panMode", "none" ); + mySettings.setValue( QStringLiteral( "/gps/panMode" ), "none" ); } } @@ -409,11 +409,11 @@ void QgsGPSInformationWidget::connectGps() } else if ( mRadGpsd->isChecked() ) { - port = QString( "%1:%2:%3" ).arg( mGpsdHost->text(), mGpsdPort->text(), mGpsdDevice->text() ); + port = QStringLiteral( "%1:%2:%3" ).arg( mGpsdHost->text(), mGpsdPort->text(), mGpsdDevice->text() ); } else if ( mRadInternal->isChecked() ) { - port = QLatin1String( "internalGPS" ); + port = QStringLiteral( "internalGPS" ); } mGPSPlainTextEdit->appendPlainText( tr( "Connecting..." ) ); @@ -670,17 +670,17 @@ void QgsGPSInformationWidget::displayGPSInformation( const QgsGPSInformation& in mTxtDateTime->setText( info.utcDateTime.toString( mDateTimeFormat ) ); //user specified format string for testing the millisecond part of time } mTxtSpeed->setText( tr( "%1 km/h" ).arg( info.speed, 0, 'f', 1 ) ); - mTxtDirection->setText( QString::number( info.direction, 'f', 1 ) + QString::fromUtf8( "°" ) ); + mTxtDirection->setText( QString::number( info.direction, 'f', 1 ) + QStringLiteral( "°" ) ); mTxtHdop->setText( QString::number( info.hdop, 'f', 1 ) ); mTxtVdop->setText( QString::number( info.vdop, 'f', 1 ) ); mTxtPdop->setText( QString::number( info.pdop, 'f', 1 ) ); mTxtHacc->setText( QString::number( info.hacc, 'f', 1 ) + "m" ); mTxtVacc->setText( QString::number( info.vacc, 'f', 1 ) + "m" ); - mTxtFixMode->setText( info.fixMode == 'A' ? tr( "Automatic" ) : info.fixMode == 'M' ? tr( "Manual" ) : "" ); // A=automatic 2d/3d, M=manual; allowing for anything else + mTxtFixMode->setText( info.fixMode == 'A' ? tr( "Automatic" ) : info.fixMode == 'M' ? tr( "Manual" ) : QLatin1String( "" ) ); // A=automatic 2d/3d, M=manual; allowing for anything else mTxtFixType->setText( info.fixType == 3 ? tr( "3D" ) : info.fixType == 2 ? tr( "2D" ) : info.fixType == 1 ? tr( "No fix" ) : QString::number( info.fixType ) ); // 1=no fix, 2=2D, 3=3D; allowing for anything else - mTxtQuality->setText( info.quality == 2 ? tr( "Differential" ) : info.quality == 1 ? tr( "Non-differential" ) : info.quality == 0 ? tr( "No position" ) : info.quality > 2 ? QString::number( info.quality ) : "" ); // allowing for anything else + mTxtQuality->setText( info.quality == 2 ? tr( "Differential" ) : info.quality == 1 ? tr( "Non-differential" ) : info.quality == 0 ? tr( "No position" ) : info.quality > 2 ? QString::number( info.quality ) : QLatin1String( "" ) ); // allowing for anything else mTxtSatellitesUsed->setText( QString::number( info.satellitesUsed ) ); - mTxtStatus->setText( info.status == 'A' ? tr( "Valid" ) : info.status == 'V' ? tr( "Invalid" ) : "" ); + mTxtStatus->setText( info.status == 'A' ? tr( "Valid" ) : info.status == 'V' ? tr( "Invalid" ) : QLatin1String( "" ) ); } //position // Avoid refreshing / panning if we havent moved @@ -843,7 +843,7 @@ void QgsGPSInformationWidget::on_mBtnCloseFeature_clicked() tr( "Error" ), tr( "Could not commit changes to layer %1\n\nErrors: %2\n" ) .arg( vlayer->name(), - vlayer->commitErrors().join( "\n " ) ) ); + vlayer->commitErrors().join( QStringLiteral( "\n " ) ) ) ); } vlayer->startEditing(); @@ -952,7 +952,7 @@ void QgsGPSInformationWidget::on_mBtnCloseFeature_clicked() tr( "Error" ), tr( "Could not commit changes to layer %1\n\nErrors: %2\n" ) .arg( vlayer->name(), - vlayer->commitErrors().join( "\n " ) ) ); + vlayer->commitErrors().join( QStringLiteral( "\n " ) ) ) ); } vlayer->startEditing(); @@ -1000,7 +1000,7 @@ void QgsGPSInformationWidget::populateDevices() // remember the last ports used QSettings settings; - QString lastPort = settings.value( "/gps/lastPort", "" ).toString(); + QString lastPort = settings.value( QStringLiteral( "/gps/lastPort" ), "" ).toString(); int idx = mCboDevices->findData( lastPort ); mCboDevices->setCurrentIndex( idx < 0 ? 0 : idx ); @@ -1024,7 +1024,7 @@ void QgsGPSInformationWidget::on_mBtnLogFile_clicked() // This does not allow for an extension other than ".nmea" // Retrieve last used log file dir from persistent settings QSettings settings; - QString settingPath( "/gps/lastLogFileDir" ); + QString settingPath( QStringLiteral( "/gps/lastLogFileDir" ) ); QString lastUsedDir = settings.value( settingPath, QDir::homePath() ).toString(); QString saveFilePath = QFileDialog::getSaveFileName( this, tr( "Save GPS log file as" ), lastUsedDir, tr( "NMEA files" ) + " (*.nmea)" ); if ( saveFilePath.isNull() ) //canceled diff --git a/src/app/gps/qgsgpsmarker.cpp b/src/app/gps/qgsgpsmarker.cpp index 71752eb90267..70d464cef075 100644 --- a/src/app/gps/qgsgpsmarker.cpp +++ b/src/app/gps/qgsgpsmarker.cpp @@ -24,8 +24,8 @@ QgsGpsMarker::QgsGpsMarker( QgsMapCanvas* mapCanvas ) : QgsMapCanvasItem( mapCanvas ) { mSize = 16; - mWgs84CRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); - mSvg.load( QString( ":/images/north_arrows/gpsarrow2.svg" ) ); + mWgs84CRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); + mSvg.load( QStringLiteral( ":/images/north_arrows/gpsarrow2.svg" ) ); if ( ! mSvg.isValid() ) { qDebug( "GPS marker not found!" ); diff --git a/src/app/main.cpp b/src/app/main.cpp index 1a53e6964224..e1fbfbe323d7 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -108,43 +108,43 @@ void usage( const QString& appName ) QStringList msg; msg - << "QGIS - " << VERSION << " '" << RELEASE_NAME << "' (" - << QGSVERSION << ")\n" - << "QGIS is a user friendly Open Source Geographic Information System.\n" - << "Usage: " << appName << " [OPTION] [FILE]\n" - << " OPTION:\n" - << "\t[--snapshot filename]\temit snapshot of loaded datasets to given file\n" - << "\t[--width width]\twidth of snapshot to emit\n" - << "\t[--height height]\theight of snapshot to emit\n" - << "\t[--lang language]\tuse language for interface text\n" - << "\t[--project projectfile]\tload the given QGIS project\n" - << "\t[--extent xmin,ymin,xmax,ymax]\tset initial map extent\n" - << "\t[--nologo]\thide splash screen\n" - << "\t[--noversioncheck]\tdon't check for new version of QGIS at startup\n" - << "\t[--noplugins]\tdon't restore plugins on startup\n" - << "\t[--nocustomization]\tdon't apply GUI customization\n" - << "\t[--customizationfile]\tuse the given ini file as GUI customization\n" - << "\t[--optionspath path]\tuse the given QSettings path\n" - << "\t[--configpath path]\tuse the given path for all user configuration\n" - << "\t[--authdbdirectory path] use the given directory for authentication database\n" - << "\t[--code path]\trun the given python file on load\n" - << "\t[--defaultui]\tstart by resetting user ui settings to default\n" - << "\t[--dxf-export filename.dxf]\temit dxf output of loaded datasets to given file\n" - << "\t[--dxf-extent xmin,ymin,xmax,ymax]\tset extent to export to dxf\n" - << "\t[--dxf-symbology-mode none|symbollayer|feature]\tsymbology mode for dxf output\n" - << "\t[--dxf-scale-denom scale]\tscale for dxf output\n" - << "\t[--dxf-encoding encoding]\tencoding to use for dxf output\n" - << "\t[--dxf-preset maptheme]\tmap theme to use for dxf output\n" - << "\t[--help]\t\tthis text\n" - << "\t[--]\t\ttreat all following arguments as FILEs\n\n" - << " FILE:\n" - << " Files specified on the command line can include rasters,\n" - << " vectors, and QGIS project files (.qgs): \n" - << " 1. Rasters - supported formats include GeoTiff, DEM \n" - << " and others supported by GDAL\n" - << " 2. Vectors - supported formats include ESRI Shapefiles\n" - << " and others supported by OGR and PostgreSQL layers using\n" - << " the PostGIS extension\n" ; // OK + << QStringLiteral( "QGIS - " ) << VERSION << QStringLiteral( " '" ) << RELEASE_NAME << QStringLiteral( "' (" ) + << QGSVERSION << QStringLiteral( ")\n" ) + << QStringLiteral( "QGIS is a user friendly Open Source Geographic Information System.\n" ) + << QStringLiteral( "Usage: " ) << appName << QStringLiteral( " [OPTION] [FILE]\n" ) + << QStringLiteral( " OPTION:\n" ) + << QStringLiteral( "\t[--snapshot filename]\temit snapshot of loaded datasets to given file\n" ) + << QStringLiteral( "\t[--width width]\twidth of snapshot to emit\n" ) + << QStringLiteral( "\t[--height height]\theight of snapshot to emit\n" ) + << QStringLiteral( "\t[--lang language]\tuse language for interface text\n" ) + << QStringLiteral( "\t[--project projectfile]\tload the given QGIS project\n" ) + << QStringLiteral( "\t[--extent xmin,ymin,xmax,ymax]\tset initial map extent\n" ) + << QStringLiteral( "\t[--nologo]\thide splash screen\n" ) + << QStringLiteral( "\t[--noversioncheck]\tdon't check for new version of QGIS at startup\n" ) + << QStringLiteral( "\t[--noplugins]\tdon't restore plugins on startup\n" ) + << QStringLiteral( "\t[--nocustomization]\tdon't apply GUI customization\n" ) + << QStringLiteral( "\t[--customizationfile]\tuse the given ini file as GUI customization\n" ) + << QStringLiteral( "\t[--optionspath path]\tuse the given QSettings path\n" ) + << QStringLiteral( "\t[--configpath path]\tuse the given path for all user configuration\n" ) + << QStringLiteral( "\t[--authdbdirectory path] use the given directory for authentication database\n" ) + << QStringLiteral( "\t[--code path]\trun the given python file on load\n" ) + << QStringLiteral( "\t[--defaultui]\tstart by resetting user ui settings to default\n" ) + << QStringLiteral( "\t[--dxf-export filename.dxf]\temit dxf output of loaded datasets to given file\n" ) + << QStringLiteral( "\t[--dxf-extent xmin,ymin,xmax,ymax]\tset extent to export to dxf\n" ) + << QStringLiteral( "\t[--dxf-symbology-mode none|symbollayer|feature]\tsymbology mode for dxf output\n" ) + << QStringLiteral( "\t[--dxf-scale-denom scale]\tscale for dxf output\n" ) + << QStringLiteral( "\t[--dxf-encoding encoding]\tencoding to use for dxf output\n" ) + << QStringLiteral( "\t[--dxf-preset maptheme]\tmap theme to use for dxf output\n" ) + << QStringLiteral( "\t[--help]\t\tthis text\n" ) + << QStringLiteral( "\t[--]\t\ttreat all following arguments as FILEs\n\n" ) + << QStringLiteral( " FILE:\n" ) + << QStringLiteral( " Files specified on the command line can include rasters,\n" ) + << QStringLiteral( " vectors, and QGIS project files (.qgs): \n" ) + << QStringLiteral( " 1. Rasters - supported formats include GeoTiff, DEM \n" ) + << QStringLiteral( " and others supported by GDAL\n" ) + << QStringLiteral( " 2. Vectors - supported formats include ESRI Shapefiles\n" ) + << QStringLiteral( " and others supported by OGR and PostgreSQL layers using\n" ) + << QStringLiteral( " the PostGIS extension\n" ) ; // OK #ifdef Q_OS_WIN MessageBox( nullptr, @@ -166,7 +166,7 @@ void usage( const QString& appName ) // AppleEvent handler as well as by the main routine argv processing // This behaviour will cause QGIS to autoload a project -static QString myProjectFileName = ""; +static QString myProjectFileName = QLatin1String( "" ); // This is the 'leftover' arguments collection static QStringList myFileList; @@ -392,7 +392,7 @@ void myMessageOutput( QtMsgType type, const char *msg ) { // TODO: Verify this code in action. dumpBacktrace( 20 ); - QgsMessageLog::logMessage( msg, "Qt" ); + QgsMessageLog::logMessage( msg, QStringLiteral( "Qt" ) ); } #endif @@ -400,7 +400,7 @@ void myMessageOutput( QtMsgType type, const char *msg ) if ( 0 == strncmp( msg, "libpng error:", 13 ) ) { // Let the user know - QgsMessageLog::logMessage( msg, "libpng" ); + QgsMessageLog::logMessage( msg, QStringLiteral( "libpng" ) ); } break; @@ -511,7 +511,7 @@ int main( int argc, char *argv[] ) // This behaviour is used to load the app, snapshot the map, // save the image to disk and then exit - QString mySnapshotFileName = ""; + QString mySnapshotFileName = QLatin1String( "" ); int mySnapshotWidth = 800; int mySnapshotHeight = 600; @@ -529,7 +529,7 @@ int main( int argc, char *argv[] ) QString dxfOutputFile; QgsDxfExport::SymbologyExport dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology; double dxfScaleDenom = 50000.0; - QString dxfEncoding = "CP1252"; + QString dxfEncoding = QStringLiteral( "CP1252" ); QString dxfPreset; QgsRectangle dxfExtent; @@ -537,9 +537,9 @@ int main( int argc, char *argv[] ) // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. - QString myInitialExtent = ""; + QString myInitialExtent = QLatin1String( "" ); if ( argc == 1 ) - myInitialExtent = "-1,-1,1,1"; + myInitialExtent = QStringLiteral( "-1,-1,1,1" ); // This behaviour will allow you to force the use of a translation file // which is useful for testing @@ -575,80 +575,80 @@ int main( int argc, char *argv[] ) { const QString &arg = args[i]; - if ( arg == "--help" || arg == "-?" ) + if ( arg == QLatin1String( "--help" ) || arg == QLatin1String( "-?" ) ) { usage( args[0] ); return 2; } - else if ( arg == "--nologo" || arg == "-n" ) + else if ( arg == QLatin1String( "--nologo" ) || arg == QLatin1String( "-n" ) ) { myHideSplash = true; } - else if ( arg == "--noversioncheck" || arg == "-V" ) + else if ( arg == QLatin1String( "--noversioncheck" ) || arg == QLatin1String( "-V" ) ) { mySkipVersionCheck = true; } - else if ( arg == "--noplugins" || arg == "-P" ) + else if ( arg == QLatin1String( "--noplugins" ) || arg == QLatin1String( "-P" ) ) { myRestorePlugins = false; } - else if ( arg == "--nocustomization" || arg == "-C" ) + else if ( arg == QLatin1String( "--nocustomization" ) || arg == QLatin1String( "-C" ) ) { myCustomization = false; } - else if ( i + 1 < argc && ( arg == "--snapshot" || arg == "-s" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--snapshot" ) || arg == QLatin1String( "-s" ) ) ) { mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } - else if ( i + 1 < argc && ( arg == "--width" || arg == "-w" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--width" ) || arg == QLatin1String( "-w" ) ) ) { mySnapshotWidth = QString( args[++i] ).toInt(); } - else if ( i + 1 < argc && ( arg == "--height" || arg == "-h" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--height" ) || arg == QLatin1String( "-h" ) ) ) { mySnapshotHeight = QString( args[++i] ).toInt(); } - else if ( i + 1 < argc && ( arg == "--lang" || arg == "-l" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--lang" ) || arg == QLatin1String( "-l" ) ) ) { myTranslationCode = args[++i]; } - else if ( i + 1 < argc && ( arg == "--project" || arg == "-p" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--project" ) || arg == QLatin1String( "-p" ) ) ) { myProjectFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } - else if ( i + 1 < argc && ( arg == "--extent" || arg == "-e" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--extent" ) || arg == QLatin1String( "-e" ) ) ) { myInitialExtent = args[++i]; } - else if ( i + 1 < argc && ( arg == "--optionspath" || arg == "-o" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--optionspath" ) || arg == QLatin1String( "-o" ) ) ) { optionpath = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() ); } - else if ( i + 1 < argc && ( arg == "--configpath" || arg == "-c" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--configpath" ) || arg == QLatin1String( "-c" ) ) ) { configpath = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() ); } - else if ( i + 1 < argc && ( arg == "--authdbdirectory" || arg == "-a" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--authdbdirectory" ) || arg == QLatin1String( "-a" ) ) ) { authdbdirectory = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() ); } - else if ( i + 1 < argc && ( arg == "--code" || arg == "-f" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--code" ) || arg == QLatin1String( "-f" ) ) ) { pythonfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } - else if ( i + 1 < argc && ( arg == "--customizationfile" || arg == "-z" ) ) + else if ( i + 1 < argc && ( arg == QLatin1String( "--customizationfile" ) || arg == QLatin1String( "-z" ) ) ) { customizationfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() ); } - else if ( arg == "--defaultui" || arg == "-d" ) + else if ( arg == QLatin1String( "--defaultui" ) || arg == QLatin1String( "-d" ) ) { myRestoreDefaultWindowState = true; } - else if ( arg == "--dxf-export" ) + else if ( arg == QLatin1String( "--dxf-export" ) ) { dxfOutputFile = args[++i]; } - else if ( arg == "--dxf-extent" ) + else if ( arg == QLatin1String( "--dxf-extent" ) ) { QgsLocaleNumC l; QString ext( args[++i] ); @@ -689,18 +689,18 @@ int main( int argc, char *argv[] ) } } } - else if ( arg == "--dxf-symbology-mode" ) + else if ( arg == QLatin1String( "--dxf-symbology-mode" ) ) { QString mode( args[++i] ); - if ( mode == "none" ) + if ( mode == QLatin1String( "none" ) ) { dxfSymbologyMode = QgsDxfExport::NoSymbology; } - else if ( mode == "symbollayer" ) + else if ( mode == QLatin1String( "symbollayer" ) ) { dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology; } - else if ( mode == "feature" ) + else if ( mode == QLatin1String( "feature" ) ) { dxfSymbologyMode = QgsDxfExport::FeatureSymbology; } @@ -710,7 +710,7 @@ int main( int argc, char *argv[] ) return 2; } } - else if ( arg == "--dxf-scale-denom" ) + else if ( arg == QLatin1String( "--dxf-scale-denom" ) ) { bool ok; QString scale( args[++i] ); @@ -721,15 +721,15 @@ int main( int argc, char *argv[] ) return 2; } } - else if ( arg == "--dxf-encoding" ) + else if ( arg == QLatin1String( "--dxf-encoding" ) ) { dxfEncoding = args[++i]; } - else if ( arg == "--dxf-preset" ) + else if ( arg == QLatin1String( "--dxf-preset" ) ) { dxfPreset = args[++i]; } - else if ( arg == "--" ) + else if ( arg == QLatin1String( "--" ) ) { for ( i++; i < args.size(); ++i ) myFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) ); @@ -753,7 +753,7 @@ int main( int argc, char *argv[] ) for ( int i = 0; i < args.size(); i++ ) { QString arg = QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ); - if ( arg.contains( ".qgs" ) ) + if ( arg.contains( QLatin1String( ".qgs" ) ) ) { myProjectFileName = arg; break; @@ -817,11 +817,11 @@ int main( int argc, char *argv[] ) QSettings::setDefaultFormat( QSettings::IniFormat ); QString path = optionpath.isEmpty() ? configpath : optionpath; QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, path ); - customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, "QGIS", "QGISCUSTOMIZATION2" ); + customizationsettings = new QSettings( QSettings::IniFormat, QSettings::UserScope, QStringLiteral( "QGIS" ), QStringLiteral( "QGISCUSTOMIZATION2" ) ); } else { - customizationsettings = new QSettings( "QGIS", "QGISCUSTOMIZATION2" ); + customizationsettings = new QSettings( QStringLiteral( "QGIS" ), QStringLiteral( "QGISCUSTOMIZATION2" ) ); } // Using the customizationfile option always overrides the option and config path options. @@ -866,24 +866,24 @@ int main( int argc, char *argv[] ) QSettings mySettings; // update any saved setting for older themes to new default 'gis' theme (2013-04-15) - if ( mySettings.contains( "/Themes" ) ) + if ( mySettings.contains( QStringLiteral( "/Themes" ) ) ) { - QString theme = mySettings.value( "/Themes", "default" ).toString(); - if ( theme == "gis" - || theme == "classic" - || theme == "nkids" ) + QString theme = mySettings.value( QStringLiteral( "/Themes" ), "default" ).toString(); + if ( theme == QLatin1String( "gis" ) + || theme == QLatin1String( "classic" ) + || theme == QLatin1String( "nkids" ) ) { - mySettings.setValue( "/Themes", QString( "default" ) ); + mySettings.setValue( QStringLiteral( "/Themes" ), QStringLiteral( "default" ) ); } } // custom environment variables QMap systemEnvVars = QgsApplication::systemEnvVars(); - bool useCustomVars = mySettings.value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool(); + bool useCustomVars = mySettings.value( QStringLiteral( "qgis/customEnvVarsUse" ), QVariant( false ) ).toBool(); if ( useCustomVars ) { - QStringList customVarsList = mySettings.value( "qgis/customEnvVars", "" ).toStringList(); + QStringList customVarsList = mySettings.value( QStringLiteral( "qgis/customEnvVars" ), "" ).toStringList(); if ( !customVarsList.isEmpty() ) { Q_FOREACH ( const QString &varStr, customVarsList ) @@ -901,17 +901,17 @@ int main( int argc, char *argv[] ) if ( systemEnvVars.contains( envVarName ) ) { - if ( envVarApply == "prepend" ) + if ( envVarApply == QLatin1String( "prepend" ) ) { envVarValue += systemEnvVars.value( envVarName ); } - else if ( envVarApply == "append" ) + else if ( envVarApply == QLatin1String( "append" ) ) { envVarValue = systemEnvVars.value( envVarName ) + envVarValue; } } - if ( systemEnvVars.contains( envVarName ) && envVarApply == "unset" ) + if ( systemEnvVars.contains( envVarName ) && envVarApply == QLatin1String( "unset" ) ) { #ifdef Q_OS_WIN putenv( envVarName.toUtf8().constData() ); @@ -925,7 +925,7 @@ int main( int argc, char *argv[] ) if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) ) putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() ); #else - setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == "undefined" ? 0 : 1 ); + setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == QLatin1String( "undefined" ) ? 0 : 1 ); #endif } } @@ -933,23 +933,23 @@ int main( int argc, char *argv[] ) } #ifdef QGISDEBUG - QgsFontUtils::loadStandardTestFonts( QStringList() << "Roman" << "Bold" ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Roman" ) << QStringLiteral( "Bold" ) ); #endif // Set the application style. If it's not set QT will use the platform style except on Windows // as it looks really ugly so we use QPlastiqueStyle. - QString style = mySettings.value( "/qgis/style" ).toString(); + QString style = mySettings.value( QStringLiteral( "/qgis/style" ) ).toString(); if ( !style.isNull() ) { QApplication::setStyle( style ); - mySettings.setValue( "/qgis/style", QApplication::style()->objectName() ); + mySettings.setValue( QStringLiteral( "/qgis/style" ), QApplication::style()->objectName() ); } /* Translation file for QGIS. */ QString i18nPath = QgsApplication::i18nPath(); - QString myUserLocale = mySettings.value( "locale/userLocale", "" ).toString(); - bool myLocaleOverrideFlag = mySettings.value( "locale/overrideFlag", false ).toBool(); + QString myUserLocale = mySettings.value( QStringLiteral( "locale/userLocale" ), "" ).toString(); + bool myLocaleOverrideFlag = mySettings.value( QStringLiteral( "locale/overrideFlag" ), false ).toBool(); // // Priority of translation is: @@ -962,7 +962,7 @@ int main( int argc, char *argv[] ) // if ( !myTranslationCode.isNull() && !myTranslationCode.isEmpty() ) { - mySettings.setValue( "locale/userLocale", myTranslationCode ); + mySettings.setValue( QStringLiteral( "locale/userLocale" ), myTranslationCode ); } else { @@ -971,7 +971,7 @@ int main( int argc, char *argv[] ) myTranslationCode = QLocale::system().name(); //setting the locale/userLocale when the --lang= option is not set will allow third party //plugins to always use the same locale as the QGIS, otherwise they can be out of sync - mySettings.setValue( "locale/userLocale", myTranslationCode ); + mySettings.setValue( QStringLiteral( "locale/userLocale" ), myTranslationCode ); } else { @@ -981,15 +981,15 @@ int main( int argc, char *argv[] ) QTranslator qgistor( nullptr ); QTranslator qttor( nullptr ); - if ( myTranslationCode != "C" ) + if ( myTranslationCode != QLatin1String( "C" ) ) { - if ( qgistor.load( QString( "qgis_" ) + myTranslationCode, i18nPath ) ) + if ( qgistor.load( QStringLiteral( "qgis_" ) + myTranslationCode, i18nPath ) ) { myApp.installTranslator( &qgistor ); } else { - qWarning( "loading of qgis translation failed [%s]", QString( "%1/qgis_%2" ).arg( i18nPath, myTranslationCode ).toLocal8Bit().constData() ); + qWarning( "loading of qgis translation failed [%s]", QStringLiteral( "%1/qgis_%2" ).arg( i18nPath, myTranslationCode ).toLocal8Bit().constData() ); } /* Translation file for Qt. @@ -997,13 +997,13 @@ int main( int argc, char *argv[] ) * the About, Preferences and Quit items to the Mac Application menu. * These items must be translated identically in both qt_ and qgis_ files. */ - if ( qttor.load( QString( "qt_" ) + myTranslationCode, QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) + if ( qttor.load( QStringLiteral( "qt_" ) + myTranslationCode, QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) { myApp.installTranslator( &qttor ); } else { - qWarning( "loading of qt translation failed [%s]", QString( "%1/qt_%2" ).arg( QLibraryInfo::location( QLibraryInfo::TranslationsPath ), myTranslationCode ).toLocal8Bit().constData() ); + qWarning( "loading of qt translation failed [%s]", QStringLiteral( "%1/qt_%2" ).arg( QLibraryInfo::location( QLibraryInfo::TranslationsPath ), myTranslationCode ).toLocal8Bit().constData() ); } } @@ -1045,13 +1045,13 @@ int main( int argc, char *argv[] ) //set up splash screen QString mySplashPath( QgsCustomization::instance()->splashPath() ); - QPixmap myPixmap( mySplashPath + QLatin1String( "splash.png" ) ); + QPixmap myPixmap( mySplashPath + QStringLiteral( "splash.png" ) ); int w = 600 * qApp->desktop()->logicalDpiX() / 96; int h = 300 * qApp->desktop()->logicalDpiY() / 96; QSplashScreen *mypSplash = new QSplashScreen( myPixmap.scaled( w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation ) ); - if ( !myHideSplash && !mySettings.value( "/qgis/hideSplash" ).toBool() ) + if ( !myHideSplash && !mySettings.value( QStringLiteral( "/qgis/hideSplash" ) ).toBool() ) { //for win and linux we can just automask and png transparency areas will be used mypSplash->setMask( myPixmap.mask() ); @@ -1060,19 +1060,19 @@ int main( int argc, char *argv[] ) // optionally restore default window state // use restoreDefaultWindowState setting only if NOT using command line (then it is set already) - if ( myRestoreDefaultWindowState || mySettings.value( "/qgis/restoreDefaultWindowState", false ).toBool() ) + if ( myRestoreDefaultWindowState || mySettings.value( QStringLiteral( "/qgis/restoreDefaultWindowState" ), false ).toBool() ) { QgsDebugMsg( "Resetting /UI/state settings!" ); - mySettings.remove( "/UI/state" ); - mySettings.remove( "/qgis/restoreDefaultWindowState" ); + mySettings.remove( QStringLiteral( "/UI/state" ) ); + mySettings.remove( QStringLiteral( "/qgis/restoreDefaultWindowState" ) ); } // set max. thread count // this should be done in QgsApplication::init() but it doesn't know the settings dir. - QgsApplication::setMaxThreads( QSettings().value( "/qgis/max_threads", -1 ).toInt() ); + QgsApplication::setMaxThreads( QSettings().value( QStringLiteral( "/qgis/max_threads" ), -1 ).toInt() ); QgisApp *qgis = new QgisApp( mypSplash, myRestorePlugins, mySkipVersionCheck ); // "QgisApp" used to find canonical instance - qgis->setObjectName( "QgisApp" ); + qgis->setObjectName( QStringLiteral( "QgisApp" ) ); myApp.connect( &myApp, SIGNAL( preNotify( QObject *, QEvent *, bool * ) ), @@ -1097,7 +1097,7 @@ int main( int argc, char *argv[] ) QgsDebugMsg( QString( "Trying to load file : %1" ).arg(( *myIterator ) ) ); QString myLayerName = *myIterator; // don't load anything with a .qgs extension - these are project files - if ( !myLayerName.contains( ".qgs" ) ) + if ( !myLayerName.contains( QLatin1String( ".qgs" ) ) ) { qgis->openLayer( myLayerName ); } @@ -1159,13 +1159,13 @@ int main( int argc, char *argv[] ) //replace backslashes with forward slashes pythonfile.replace( '\\', '/' ); #endif - QgsPythonRunner::run( QString( "exec(open('%1').read())" ).arg( pythonfile ) ); + QgsPythonRunner::run( QStringLiteral( "exec(open('%1').read())" ).arg( pythonfile ) ); } /////////////////////////////////`//////////////////////////////////// // Take a snapshot of the map view then exit if snapshot mode requested ///////////////////////////////////////////////////////////////////// - if ( mySnapshotFileName != "" ) + if ( mySnapshotFileName != QLatin1String( "" ) ) { /*You must have at least one paintEvent() delivered for the window to be rendered properly. @@ -1227,7 +1227,7 @@ int main( int argc, char *argv[] ) } QFile dxfFile; - if ( dxfOutputFile == "-" ) + if ( dxfOutputFile == QLatin1String( "-" ) ) { if ( !dxfFile.open( stdout, QIODevice::WriteOnly | QIODevice::Truncate ) ) { @@ -1237,8 +1237,8 @@ int main( int argc, char *argv[] ) } else { - if ( !dxfOutputFile.endsWith( ".dxf", Qt::CaseInsensitive ) ) - dxfOutputFile += ".dxf"; + if ( !dxfOutputFile.endsWith( QLatin1String( ".dxf" ), Qt::CaseInsensitive ) ) + dxfOutputFile += QLatin1String( ".dxf" ); dxfFile.setFileName( dxfOutputFile ); } diff --git a/src/app/nodetool/qgsmaptoolnodetool.cpp b/src/app/nodetool/qgsmaptoolnodetool.cpp index 7f98df300dee..46efdaaed8c2 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.cpp +++ b/src/app/nodetool/qgsmaptoolnodetool.cpp @@ -89,14 +89,14 @@ void QgsMapToolNodeTool::createTopologyRubberBands() QgsGeometryRubberBand* rb = new QgsGeometryRubberBand( mCanvas, feature.geometry().type() ); QSettings settings; QColor color( - settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(), - settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(), - settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt() ); - double myAlpha = settings.value( "/qgis/digitizing/line_color_alpha", 30 ).toInt() / 255.0 ; + settings.value( QStringLiteral( "/qgis/digitizing/line_color_red" ), 255 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_green" ), 0 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_blue" ), 0 ).toInt() ); + double myAlpha = settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), 30 ).toInt() / 255.0 ; color.setAlphaF( myAlpha ); rb->setOutlineColor( color ); rb->setBrushStyle( Qt::NoBrush ); - rb->setOutlineWidth( settings.value( "/qgis/digitizing/line_width", 1 ).toInt() ); + rb->setOutlineWidth( settings.value( QStringLiteral( "/qgis/digitizing/line_width" ), 1 ).toInt() ); QgsAbstractGeometry* rbGeom = feature.geometry().geometry()->clone(); if ( mCanvas->mapSettings().layerTransform( vlayer ).isValid() ) rbGeom->transform( mCanvas->mapSettings().layerTransform( vlayer ) ); @@ -124,7 +124,7 @@ void QgsMapToolNodeTool::canvasMoveEvent( QgsMapMouseEvent* e ) if ( mMoveRubberBands.empty() ) { QSettings settings; - bool ghostLine = settings.value( "/qgis/digitizing/line_ghost", false ).toBool(); + bool ghostLine = settings.value( QStringLiteral( "/qgis/digitizing/line_ghost" ), false ).toBool(); if ( !ghostLine ) { delete mSelectRubberBand; @@ -132,14 +132,14 @@ void QgsMapToolNodeTool::canvasMoveEvent( QgsMapMouseEvent* e ) } QgsGeometryRubberBand* rb = new QgsGeometryRubberBand( mCanvas, mSelectedFeature->geometry()->type() ); QColor color( - settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(), - settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(), - settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt() ); - double myAlpha = settings.value( "/qgis/digitizing/line_color_alpha", 30 ).toInt() / 255.0 ; + settings.value( QStringLiteral( "/qgis/digitizing/line_color_red" ), 255 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_green" ), 0 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_blue" ), 0 ).toInt() ); + double myAlpha = settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), 30 ).toInt() / 255.0 ; color.setAlphaF( myAlpha ); rb->setOutlineColor( color ); rb->setBrushStyle( Qt::NoBrush ); - rb->setOutlineWidth( settings.value( "/qgis/digitizing/line_width", 1 ).toInt() ); + rb->setOutlineWidth( settings.value( QStringLiteral( "/qgis/digitizing/line_width" ), 1 ).toInt() ); QgsAbstractGeometry* rbGeom = mSelectedFeature->geometry()->geometry()->clone(); if ( mCanvas->mapSettings().layerTransform( vlayer ).isValid() ) rbGeom->transform( mCanvas->mapSettings().layerTransform( vlayer ) ); @@ -396,10 +396,10 @@ void QgsMapToolNodeTool::updateSelectFeature( const QgsGeometry &geom ) QSettings settings; QColor color( - settings.value( "/qgis/digitizing/fill_color_red", 255 ).toInt(), - settings.value( "/qgis/digitizing/fill_color_green", 0 ).toInt(), - settings.value( "/qgis/digitizing/fill_color_blue", 0 ).toInt() ); - double myAlpha = settings.value( "/qgis/digitizing/fill_color_alpha", 30 ).toInt() / 255.0 ; + settings.value( QStringLiteral( "/qgis/digitizing/fill_color_red" ), 255 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/fill_color_green" ), 0 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/fill_color_blue" ), 0 ).toInt() ); + double myAlpha = settings.value( QStringLiteral( "/qgis/digitizing/fill_color_alpha" ), 30 ).toInt() / 255.0 ; color.setAlphaF( myAlpha ); mSelectRubberBand->setFillColor( color ); @@ -424,7 +424,7 @@ void QgsMapToolNodeTool::selectedFeatureDestroyed() void QgsMapToolNodeTool::geometryChanged( QgsFeatureId fid, const QgsGeometry &geom ) { QSettings settings; - bool ghostLine = settings.value( "/qgis/digitizing/line_ghost", false ).toBool(); + bool ghostLine = settings.value( QStringLiteral( "/qgis/digitizing/line_ghost" ), false ).toBool(); if ( !ghostLine && mSelectedFeature && ( mSelectedFeature->featureId() == fid ) ) { updateSelectFeature( geom ); diff --git a/src/app/nodetool/qgsselectedfeature.cpp b/src/app/nodetool/qgsselectedfeature.cpp index 62a93d575322..3e91448b0b70 100644 --- a/src/app/nodetool/qgsselectedfeature.cpp +++ b/src/app/nodetool/qgsselectedfeature.cpp @@ -159,7 +159,7 @@ void QgsSelectedFeature::geometryChanged( QgsFeatureId fid, const QgsGeometry &g void QgsSelectedFeature::validateGeometry( QgsGeometry *g ) { QSettings settings; - if ( settings.value( "/qgis/digitizing/validate_geometries", 1 ).toInt() == 0 ) + if ( settings.value( QStringLiteral( "/qgis/digitizing/validate_geometries" ), 1 ).toInt() == 0 ) return; if ( !g ) diff --git a/src/app/ogr/qgsnewogrconnection.cpp b/src/app/ogr/qgsnewogrconnection.cpp index 785fe14f7aa1..a387e91015bb 100644 --- a/src/app/ogr/qgsnewogrconnection.cpp +++ b/src/app/ogr/qgsnewogrconnection.cpp @@ -38,7 +38,7 @@ QgsNewOgrConnection::QgsNewOgrConnection( QWidget *parent, const QString& connTy setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/OGRDatabaseConnection/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/OGRDatabaseConnection/geometry" ) ).toByteArray() ); //add database drivers QStringList dbDrivers = QgsProviderRegistry::instance()->databaseDrivers().split( ';' ); @@ -59,7 +59,7 @@ QgsNewOgrConnection::QgsNewOgrConnection( QWidget *parent, const QString& connTy QString port = settings.value( key + "/port" ).toString(); txtPort->setText( port ); txtUsername->setText( settings.value( key + "/username" ).toString() ); - if ( settings.value( key + "/save" ).toString() == "true" ) + if ( settings.value( key + "/save" ).toString() == QLatin1String( "true" ) ) { txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); @@ -74,7 +74,7 @@ QgsNewOgrConnection::QgsNewOgrConnection( QWidget *parent, const QString& connTy QgsNewOgrConnection::~QgsNewOgrConnection() { QSettings settings; - settings.setValue( "/Windows/OGRDatabaseConnection/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/OGRDatabaseConnection/geometry" ), saveGeometry() ); } void QgsNewOgrConnection::testConnection() @@ -129,7 +129,7 @@ void QgsNewOgrConnection::accept() settings.setValue( baseKey + "/database", txtDatabase->text() ); settings.setValue( baseKey + "/port", txtPort->text() ); settings.setValue( baseKey + "/username", txtUsername->text() ); - settings.setValue( baseKey + "/password", chkStorePassword->isChecked() ? txtPassword->text() : "" ); + settings.setValue( baseKey + "/password", chkStorePassword->isChecked() ? txtPassword->text() : QLatin1String( "" ) ); settings.setValue( baseKey + "/save", chkStorePassword->isChecked() ? "true" : "false" ); QDialog::accept(); diff --git a/src/app/ogr/qgsogrhelperfunctions.cpp b/src/app/ogr/qgsogrhelperfunctions.cpp index d301d2b70a8f..d2acfca347e9 100644 --- a/src/app/ogr/qgsogrhelperfunctions.cpp +++ b/src/app/ogr/qgsogrhelperfunctions.cpp @@ -22,94 +22,94 @@ QString createDatabaseURI( const QString& connectionType, const QString& host, const QString& database, QString port, const QString& user, const QString& password ) { - QString uri = ""; + QString uri = QLatin1String( "" ); //todo:add default ports for all kind of databases - if ( connectionType == "ESRI Personal GeoDatabase" ) + if ( connectionType == QLatin1String( "ESRI Personal GeoDatabase" ) ) { uri = "PGeo:" + database; } - else if ( connectionType == "ESRI ArcSDE" ) + else if ( connectionType == QLatin1String( "ESRI ArcSDE" ) ) { if ( port.isEmpty() ) - port = "5151"; + port = QStringLiteral( "5151" ); uri = "SDE:" + host + ",PORT:" + port + ',' + database + ',' + user + ',' + password; } - else if ( connectionType == "Informix DataBlade" ) + else if ( connectionType == QLatin1String( "Informix DataBlade" ) ) { //not tested uri = "IDB:dbname=" + database; if ( !host.isEmpty() ) - uri += QString( " server=%1" ).arg( host ); + uri += QStringLiteral( " server=%1" ).arg( host ); if ( !user.isEmpty() ) { - uri += QString( " user=%1" ).arg( user ); + uri += QStringLiteral( " user=%1" ).arg( user ); if ( !password.isEmpty() ) - uri += QString( " pass=%1" ).arg( password ); + uri += QStringLiteral( " pass=%1" ).arg( password ); } } - else if ( connectionType == "Ingres" ) + else if ( connectionType == QLatin1String( "Ingres" ) ) { //not tested uri = "@driver=ingres,dbname=" + database; if ( !user.isEmpty() ) { - uri += QString( ",userid=%1" ).arg( user ); + uri += QStringLiteral( ",userid=%1" ).arg( user ); if ( !password.isEmpty() ) - uri += QString( ",password=%1" ).arg( password ); + uri += QStringLiteral( ",password=%1" ).arg( password ); } } - else if ( connectionType == "MySQL" ) + else if ( connectionType == QLatin1String( "MySQL" ) ) { uri = "MySQL:" + database; if ( !host.isEmpty() ) { - uri += QString( ",host=%1" ).arg( host ); + uri += QStringLiteral( ",host=%1" ).arg( host ); if ( !port.isEmpty() ) - uri += QString( ",port=%1" ).arg( port ); + uri += QStringLiteral( ",port=%1" ).arg( port ); } if ( !user.isEmpty() ) { - uri += QString( ",user=%1" ).arg( user ); + uri += QStringLiteral( ",user=%1" ).arg( user ); if ( !password.isEmpty() ) - uri += QString( ",password=%1" ).arg( password ); + uri += QStringLiteral( ",password=%1" ).arg( password ); } } - else if ( connectionType == "MSSQL" ) + else if ( connectionType == QLatin1String( "MSSQL" ) ) { - uri = "MSSQL:"; + uri = QStringLiteral( "MSSQL:" ); if ( !host.isEmpty() ) { - uri += QString( ";server=%1" ).arg( host ); + uri += QStringLiteral( ";server=%1" ).arg( host ); if ( !port.isEmpty() ) - uri += QString( ",%1" ).arg( port ); + uri += QStringLiteral( ",%1" ).arg( port ); } if ( !user.isEmpty() ) { - uri += QString( ";uid=%1" ).arg( user ); + uri += QStringLiteral( ";uid=%1" ).arg( user ); if ( !password.isEmpty() ) - uri += QString( ";pwd=%1" ).arg( password ); + uri += QStringLiteral( ";pwd=%1" ).arg( password ); } else - uri += ";trusted_connection=yes"; + uri += QLatin1String( ";trusted_connection=yes" ); if ( !database.isEmpty() ) - uri += QString( ";database=%1" ).arg( database ); + uri += QStringLiteral( ";database=%1" ).arg( database ); } - else if ( connectionType == "Oracle Spatial" ) + else if ( connectionType == QLatin1String( "Oracle Spatial" ) ) { uri = "OCI:" + user; @@ -140,7 +140,7 @@ QString createDatabaseURI( const QString& connectionType, const QString& host, c } } } - else if ( connectionType == "ODBC" ) + else if ( connectionType == QLatin1String( "ODBC" ) ) { if ( !user.isEmpty() ) { @@ -159,27 +159,27 @@ QString createDatabaseURI( const QString& connectionType, const QString& host, c uri = "ODBC:" + database; } } - else if ( connectionType == "OGDI Vectors" ) + else if ( connectionType == QLatin1String( "OGDI Vectors" ) ) { } - else if ( connectionType == "PostgreSQL" ) + else if ( connectionType == QLatin1String( "PostgreSQL" ) ) { uri = "PG:dbname='" + database + '\''; if ( !host.isEmpty() ) { - uri += QString( " host='%1'" ).arg( host ); + uri += QStringLiteral( " host='%1'" ).arg( host ); if ( !port.isEmpty() ) - uri += QString( " port='%1'" ).arg( port ); + uri += QStringLiteral( " port='%1'" ).arg( port ); } if ( !user.isEmpty() ) { - uri += QString( " user='%1'" ).arg( user ); + uri += QStringLiteral( " user='%1'" ).arg( user ); if ( !password.isEmpty() ) - uri += QString( " password='%1'" ).arg( password ); + uri += QStringLiteral( " password='%1'" ).arg( password ); } uri += ' '; @@ -192,18 +192,18 @@ QString createDatabaseURI( const QString& connectionType, const QString& host, c QString createProtocolURI( const QString& type, const QString& url ) { - QString uri = ""; - if ( type == "GeoJSON" ) + QString uri = QLatin1String( "" ); + if ( type == QLatin1String( "GeoJSON" ) ) { uri = url; } - else if ( type == "CouchDB" ) + else if ( type == QLatin1String( "CouchDB" ) ) { - uri = QString( "couchdb:%1" ).arg( url ); + uri = QStringLiteral( "couchdb:%1" ).arg( url ); } - else if ( type == "DODS/OPeNDAP" ) + else if ( type == QLatin1String( "DODS/OPeNDAP" ) ) { - uri = QString( "DODS:%1" ).arg( url ); + uri = QStringLiteral( "DODS:%1" ).arg( url ); } QgsDebugMsg( "Connection type is=" + type + " and uri=" + uri ); return uri; diff --git a/src/app/ogr/qgsopenvectorlayerdialog.cpp b/src/app/ogr/qgsopenvectorlayerdialog.cpp index b3dfb630c109..5649d5c1ca0c 100644 --- a/src/app/ogr/qgsopenvectorlayerdialog.cpp +++ b/src/app/ogr/qgsopenvectorlayerdialog.cpp @@ -40,15 +40,15 @@ QgsOpenVectorLayerDialog::QgsOpenVectorLayerDialog( QWidget* parent, Qt::WindowF cmbDatabaseTypes->blockSignals( true ); cmbConnections->blockSignals( true ); radioSrcFile->setChecked( true ); - mDataSourceType = "file"; + mDataSourceType = QStringLiteral( "file" ); //set encoding cmbEncodings->addItems( QgsVectorDataProvider::availableEncodings() ); QSettings settings; - QString enc = settings.value( "/UI/encoding", "System" ).toString(); + QString enc = settings.value( QStringLiteral( "/UI/encoding" ), "System" ).toString(); - restoreGeometry( settings.value( "/Windows/OpenVectorLayer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/OpenVectorLayer/geometry" ) ).toByteArray() ); // The specified decoding is added if not existing alread, and then set current. // This should select it. @@ -96,7 +96,7 @@ QgsOpenVectorLayerDialog::QgsOpenVectorLayerDialog( QWidget* parent, Qt::WindowF QgsOpenVectorLayerDialog::~QgsOpenVectorLayerDialog() { QSettings settings; - settings.setValue( "/Windows/OpenVectorLayer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/OpenVectorLayer/geometry" ), saveGeometry() ); } QStringList QgsOpenVectorLayerDialog::openFile() @@ -105,7 +105,7 @@ QStringList QgsOpenVectorLayerDialog::openFile() QgsDebugMsg( "Vector file filters: " + mVectorFileFilter ); QString enc = encoding(); QString title = tr( "Open an OGR Supported Vector Layer" ); - QgisGui::openFilesRememberingFilter( "lastVectorFileFilter", mVectorFileFilter, selectedFiles, enc, title ); + QgisGui::openFilesRememberingFilter( QStringLiteral( "lastVectorFileFilter" ), mVectorFileFilter, selectedFiles, enc, title ); return selectedFiles; } @@ -114,18 +114,18 @@ QString QgsOpenVectorLayerDialog::openDirectory() { QSettings settings; - bool haveLastUsedDir = settings.contains( "/UI/LastUsedDirectory" ); - QString lastUsedDir = settings.value( "/UI/LastUsedDirectory", QDir::homePath() ).toString(); + bool haveLastUsedDir = settings.contains( QStringLiteral( "/UI/LastUsedDirectory" ) ); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/LastUsedDirectory" ), QDir::homePath() ).toString(); if ( !haveLastUsedDir ) - lastUsedDir = ""; + lastUsedDir = QLatin1String( "" ); QString path = QFileDialog::getExistingDirectory( this, tr( "Open Directory" ), lastUsedDir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); - settings.setValue( "/UI/LastUsedDirectory", path ); + settings.setValue( QStringLiteral( "/UI/LastUsedDirectory" ), path ); //process path if it is grass - if ( cmbDirectoryTypes->currentText() == "Grass Vector" ) + if ( cmbDirectoryTypes->currentText() == QLatin1String( "Grass Vector" ) ) { #ifdef Q_OS_WIN //replace backslashes with forward slashes @@ -242,7 +242,7 @@ void QgsOpenVectorLayerDialog::setConnectionTypeListPosition() { QSettings settings; - QString toSelect = settings.value( "/ogr/connections/selectedtype" ).toString(); + QString toSelect = settings.value( QStringLiteral( "/ogr/connections/selectedtype" ) ).toString(); for ( int i = 0; i < cmbDatabaseTypes->count(); ++i ) if ( cmbDatabaseTypes->itemText( i ) == toSelect ) { @@ -254,7 +254,7 @@ void QgsOpenVectorLayerDialog::setConnectionTypeListPosition() void QgsOpenVectorLayerDialog::setSelectedConnectionType() { QSettings settings; - QString baseKey = "/ogr/connections/"; + QString baseKey = QStringLiteral( "/ogr/connections/" ); settings.setValue( baseKey + "selectedtype", cmbDatabaseTypes->currentText() ); QgsDebugMsg( "Setting selected type to" + cmbDatabaseTypes->currentText() ); } @@ -274,7 +274,7 @@ void QgsOpenVectorLayerDialog::on_buttonSelectSrc_clicked() QStringList selected = openFile(); if ( !selected.isEmpty() ) { - inputSrcDataset->setText( selected.join( ";" ) ); + inputSrcDataset->setText( selected.join( QStringLiteral( ";" ) ) ); buttonBox->button( QDialogButtonBox::Open )->setFocus(); } } @@ -321,7 +321,7 @@ void QgsOpenVectorLayerDialog::accept() bool makeConnection = false; if ( pass.isEmpty() ) { - if ( cmbDatabaseTypes->currentText() == "MSSQL" ) + if ( cmbDatabaseTypes->currentText() == QLatin1String( "MSSQL" ) ) makeConnection = true; else pass = QInputDialog::getText( this, @@ -381,7 +381,7 @@ void QgsOpenVectorLayerDialog::accept() } // Save the used encoding - settings.setValue( "/UI/encoding", encoding() ); + settings.setValue( QStringLiteral( "/UI/encoding" ), encoding() ); QDialog::accept(); } @@ -396,7 +396,7 @@ void QgsOpenVectorLayerDialog::on_radioSrcFile_toggled( bool checked ) dbGroupBox->hide(); protocolGroupBox->hide(); layout()->setSizeConstraint( QLayout::SetFixedSize ); - mDataSourceType = "file"; + mDataSourceType = QStringLiteral( "file" ); } } @@ -410,7 +410,7 @@ void QgsOpenVectorLayerDialog::on_radioSrcDirectory_toggled( bool checked ) dbGroupBox->hide(); protocolGroupBox->hide(); layout()->setSizeConstraint( QLayout::SetFixedSize ); - mDataSourceType = "directory"; + mDataSourceType = QStringLiteral( "directory" ); } } @@ -427,7 +427,7 @@ void QgsOpenVectorLayerDialog::on_radioSrcDatabase_toggled( bool checked ) setConnectionTypeListPosition(); populateConnectionList(); setConnectionListPosition(); - mDataSourceType = "database"; + mDataSourceType = QStringLiteral( "database" ); } } @@ -439,7 +439,7 @@ void QgsOpenVectorLayerDialog::on_radioSrcProtocol_toggled( bool checked ) dbGroupBox->hide(); protocolGroupBox->show(); layout()->setSizeConstraint( QLayout::SetFixedSize ); - mDataSourceType = "protocol"; + mDataSourceType = QStringLiteral( "protocol" ); } } diff --git a/src/app/ogr/qgsvectorlayersaveasdialog.cpp b/src/app/ogr/qgsvectorlayersaveasdialog.cpp index 3eb88086e5e3..f3a22ff0d319 100644 --- a/src/app/ogr/qgsvectorlayersaveasdialog.cpp +++ b/src/app/ogr/qgsvectorlayersaveasdialog.cpp @@ -72,7 +72,7 @@ void QgsVectorLayerSaveAsDialog::setup() { setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/VectorLayerSaveAs/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/VectorLayerSaveAs/geometry" ) ).toByteArray() ); QMap map = QgsVectorFileWriter::ogrDriverList(); mFormatComboBox->blockSignals( true ); @@ -81,7 +81,7 @@ void QgsVectorLayerSaveAsDialog::setup() mFormatComboBox->addItem( it.key(), it.value() ); } - QString format = settings.value( "/UI/lastVectorFormat", "ESRI Shapefile" ).toString(); + QString format = settings.value( QStringLiteral( "/UI/lastVectorFormat" ), "ESRI Shapefile" ).toString(); mFormatComboBox->setCurrentIndex( mFormatComboBox->findData( format ) ); mFormatComboBox->blockSignals( false ); @@ -96,7 +96,7 @@ void QgsVectorLayerSaveAsDialog::setup() mEncodingComboBox->addItems( QgsVectorDataProvider::availableEncodings() ); - QString enc = settings.value( "/UI/encoding", "System" ).toString(); + QString enc = settings.value( QStringLiteral( "/UI/encoding" ), "System" ).toString(); int idx = mEncodingComboBox->findText( enc ); if ( idx < 0 ) { @@ -195,8 +195,8 @@ QList > QgsVectorLayerSaveAsDialog::createControls( con if ( control ) { // Pack the tooltip in some html element, so it gets linebreaks. - label->setToolTip( QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( option->docString ) ); - control->setToolTip( QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( option->docString ) ); + label->setToolTip( QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( option->docString ) ); + control->setToolTip( QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( option->docString ) ); controls << QPair( label, control ); } @@ -208,7 +208,7 @@ QList > QgsVectorLayerSaveAsDialog::createControls( con QgsVectorLayerSaveAsDialog::~QgsVectorLayerSaveAsDialog() { QSettings settings; - settings.setValue( "/Windows/VectorLayerSaveAs/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/VectorLayerSaveAs/geometry" ), saveGeometry() ); } void QgsVectorLayerSaveAsDialog::accept() @@ -329,9 +329,9 @@ void QgsVectorLayerSaveAsDialog::accept() } QSettings settings; - settings.setValue( "/UI/lastVectorFileFilterDir", QFileInfo( filename() ).absolutePath() ); - settings.setValue( "/UI/lastVectorFormat", format() ); - settings.setValue( "/UI/encoding", encoding() ); + settings.setValue( QStringLiteral( "/UI/lastVectorFileFilterDir" ), QFileInfo( filename() ).absolutePath() ); + settings.setValue( QStringLiteral( "/UI/lastVectorFormat" ), format() ); + settings.setValue( QStringLiteral( "/UI/encoding" ), encoding() ); QDialog::accept(); } @@ -345,12 +345,12 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx bool fieldsAsDisplayedValues = false; const QString sFormat( format() ); - if ( sFormat == "KML" ) + if ( sFormat == QLatin1String( "KML" ) ) { mAttributesSelection->setEnabled( true ); selectAllFields = false; } - else if ( sFormat == "DXF" ) + else if ( sFormat == QLatin1String( "DXF" ) ) { mAttributesSelection->setEnabled( false ); selectAllFields = false; @@ -358,16 +358,16 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx else { mAttributesSelection->setEnabled( true ); - fieldsAsDisplayedValues = ( sFormat == "CSV" || sFormat == "XLS" || sFormat == "XLSX" || sFormat == "ODS" ); + fieldsAsDisplayedValues = ( sFormat == QLatin1String( "CSV" ) || sFormat == QLatin1String( "XLS" ) || sFormat == QLatin1String( "XLSX" ) || sFormat == QLatin1String( "ODS" ) ); } - leLayername->setEnabled( sFormat == "KML" || - sFormat == "GPKG" || - sFormat == "XLSX" || - sFormat == "ODS" || - sFormat == "FileGDB" || - sFormat == "SQLite" || - sFormat == "SpatiaLite" ); + leLayername->setEnabled( sFormat == QLatin1String( "KML" ) || + sFormat == QLatin1String( "GPKG" ) || + sFormat == QLatin1String( "XLSX" ) || + sFormat == QLatin1String( "ODS" ) || + sFormat == QLatin1String( "FileGDB" ) || + sFormat == QLatin1String( "SQLite" ) || + sFormat == QLatin1String( "SpatiaLite" ) ); if ( !leLayername->isEnabled() ) leLayername->setText( QString() ); else if ( leLayername->text().isEmpty() && @@ -385,7 +385,7 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx for ( int i = 0; i < mLayer->fields().size(); ++i ) { const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( mLayer, mLayer->fields()[i].name() ); - if ( setup.type() != "TextEdit" && + if ( setup.type() != QLatin1String( "TextEdit" ) && QgsEditorWidgetRegistry::instance()->factory( setup.type() ) ) { foundFieldThatCanBeExportedAsDisplayedValue = true; @@ -408,7 +408,7 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx for ( int i = 0; i < mLayer->fields().size(); ++i ) { QgsField fld = mLayer->fields().at( i ); - Qt::ItemFlags flags = mLayer->providerType() != "oracle" || !fld.typeName().contains( "SDO_GEOMETRY" ) ? Qt::ItemIsEnabled : Qt::NoItemFlags; + Qt::ItemFlags flags = mLayer->providerType() != QLatin1String( "oracle" ) || !fld.typeName().contains( QLatin1String( "SDO_GEOMETRY" ) ) ? Qt::ItemIsEnabled : Qt::NoItemFlags; QTableWidgetItem *item; item = new QTableWidgetItem( fld.name() ); item->setFlags( flags | Qt::ItemIsUserCheckable ); @@ -424,7 +424,7 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( mLayer, mLayer->fields()[i].name() ); QgsEditorWidgetFactory *factory = nullptr; if ( flags == Qt::ItemIsEnabled && - setup.type() != "TextEdit" && + setup.type() != QLatin1String( "TextEdit" ) && ( factory = QgsEditorWidgetRegistry::instance()->factory( setup.type() ) ) ) { item = new QTableWidgetItem( tr( "Use %1" ).arg( factory->name() ) ); @@ -633,7 +633,7 @@ void QgsVectorLayerSaveAsDialog::on_leFilename_textChanged( const QString& text void QgsVectorLayerSaveAsDialog::on_browseFilename_clicked() { QSettings settings; - QString dirName = leFilename->text().isEmpty() ? settings.value( "/UI/lastVectorFileFilterDir", QDir::homePath() ).toString() : leFilename->text(); + QString dirName = leFilename->text().isEmpty() ? settings.value( QStringLiteral( "/UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() : leFilename->text(); QString filterString = QgsVectorFileWriter::filterForDriver( format() ); QString outputFile = QFileDialog::getSaveFileName( nullptr, tr( "Save layer as..." ), dirName, filterString, nullptr, QFileDialog::DontConfirmOverwrite ); if ( !outputFile.isNull() ) @@ -691,7 +691,7 @@ QStringList QgsVectorLayerSaveAsDialog::datasourceOptions() const { QSpinBox* sb = mDatasourceOptionsGroupBox->findChild( it.key() ); if ( sb ) - options << QString( "%1=%2" ).arg( it.key() ).arg( sb->value() ); + options << QStringLiteral( "%1=%2" ).arg( it.key() ).arg( sb->value() ); break; } @@ -699,7 +699,7 @@ QStringList QgsVectorLayerSaveAsDialog::datasourceOptions() const { QComboBox* cb = mDatasourceOptionsGroupBox->findChild( it.key() ); if ( cb && !cb->currentData().isNull() ) - options << QString( "%1=%2" ).arg( it.key(), cb->currentText() ); + options << QStringLiteral( "%1=%2" ).arg( it.key(), cb->currentText() ); break; } @@ -707,7 +707,7 @@ QStringList QgsVectorLayerSaveAsDialog::datasourceOptions() const { QLineEdit* le = mDatasourceOptionsGroupBox->findChild( it.key() ); if ( le ) - options << QString( "%1=%2" ).arg( it.key(), le->text() ); + options << QStringLiteral( "%1=%2" ).arg( it.key(), le->text() ); break; } @@ -715,7 +715,7 @@ QStringList QgsVectorLayerSaveAsDialog::datasourceOptions() const { QgsVectorFileWriter::HiddenOption *opt = dynamic_cast( it.value() ); - options << QString( "%1=%2" ).arg( it.key(), opt->mValue ); + options << QStringLiteral( "%1=%2" ).arg( it.key(), opt->mValue ); break; } } @@ -743,7 +743,7 @@ QStringList QgsVectorLayerSaveAsDialog::layerOptions() const { QSpinBox* sb = mLayerOptionsGroupBox->findChild( it.key() ); if ( sb ) - options << QString( "%1=%2" ).arg( it.key() ).arg( sb->value() ); + options << QStringLiteral( "%1=%2" ).arg( it.key() ).arg( sb->value() ); break; } @@ -751,7 +751,7 @@ QStringList QgsVectorLayerSaveAsDialog::layerOptions() const { QComboBox* cb = mLayerOptionsGroupBox->findChild( it.key() ); if ( cb && !cb->currentData().isNull() ) - options << QString( "%1=%2" ).arg( it.key(), cb->currentText() ); + options << QStringLiteral( "%1=%2" ).arg( it.key(), cb->currentText() ); break; } @@ -759,7 +759,7 @@ QStringList QgsVectorLayerSaveAsDialog::layerOptions() const { QLineEdit* le = mLayerOptionsGroupBox->findChild( it.key() ); if ( le && !le->text().isEmpty() ) - options << QString( "%1=%2" ).arg( it.key(), le->text() ); + options << QStringLiteral( "%1=%2" ).arg( it.key(), le->text() ); break; } @@ -767,7 +767,7 @@ QStringList QgsVectorLayerSaveAsDialog::layerOptions() const { QgsVectorFileWriter::HiddenOption *opt = dynamic_cast( it.value() ); - options << QString( "%1=%2" ).arg( it.key(), opt->mValue ); + options << QStringLiteral( "%1=%2" ).arg( it.key(), opt->mValue ); break; } } diff --git a/src/app/openstreetmap/qgsosmdownloaddialog.cpp b/src/app/openstreetmap/qgsosmdownloaddialog.cpp index 460241e8a43c..d8ccbaba9502 100644 --- a/src/app/openstreetmap/qgsosmdownloaddialog.cpp +++ b/src/app/openstreetmap/qgsosmdownloaddialog.cpp @@ -155,13 +155,13 @@ void QgsOSMDownloadDialog::onCurrentLayerChanged( int index ) void QgsOSMDownloadDialog::onBrowseClicked() { QSettings settings; - QString lastDir = settings.value( "/osm/lastDir", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "/osm/lastDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getSaveFileName( this, QString(), lastDir, tr( "OpenStreetMap files (*.osm)" ) ); if ( fileName.isNull() ) return; - settings.setValue( "/osm/lastDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/osm/lastDir" ), QFileInfo( fileName ).absolutePath() ); editFileName->setText( fileName ); } @@ -211,5 +211,5 @@ void QgsOSMDownloadDialog::onDownloadProgress( qint64 bytesReceived, qint64 byte { Q_UNUSED( bytesTotal ); // it's -1 anyway (= unknown) double mbytesReceived = ( double )bytesReceived / ( 1024 * 1024 ); - editSize->setText( QString( "%1 MB" ).arg( QString::number( mbytesReceived, 'f', 1 ) ) ); + editSize->setText( QStringLiteral( "%1 MB" ).arg( QString::number( mbytesReceived, 'f', 1 ) ) ); } diff --git a/src/app/openstreetmap/qgsosmexportdialog.cpp b/src/app/openstreetmap/qgsosmexportdialog.cpp index aa380ee3dbdb..6e76fd2889a7 100644 --- a/src/app/openstreetmap/qgsosmexportdialog.cpp +++ b/src/app/openstreetmap/qgsosmexportdialog.cpp @@ -58,13 +58,13 @@ QgsOSMExportDialog::~QgsOSMExportDialog() void QgsOSMExportDialog::onBrowse() { QSettings settings; - QString lastDir = settings.value( "/osm/lastDir", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "/osm/lastDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, QString(), lastDir, tr( "SQLite databases (*.db)" ) ); if ( fileName.isNull() ) return; - settings.setValue( "/osm/lastDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/osm/lastDir" ), QFileInfo( fileName ).absolutePath() ); editDbFileName->setText( fileName ); } @@ -74,12 +74,12 @@ void QgsOSMExportDialog::updateLayerName() QString layerType; if ( radPoints->isChecked() ) - layerType = "points"; + layerType = QStringLiteral( "points" ); else if ( radPolylines->isChecked() ) - layerType = "polylines"; + layerType = QStringLiteral( "polylines" ); else - layerType = "polygons"; - editLayerName->setText( QString( "%1_%2" ).arg( baseName, layerType ) ); + layerType = QStringLiteral( "polygons" ); + editLayerName->setText( QStringLiteral( "%1_%2" ).arg( baseName, layerType ) ); } @@ -171,8 +171,8 @@ void QgsOSMExportDialog::onOK() { QgsDataSourceUri uri; uri.setDatabase( editDbFileName->text() ); - uri.setDataSource( QString(), editLayerName->text(), "geometry" ); - QgsVectorLayer* vlayer = new QgsVectorLayer( uri.uri(), editLayerName->text(), "spatialite" ); + uri.setDataSource( QString(), editLayerName->text(), QStringLiteral( "geometry" ) ); + QgsVectorLayer* vlayer = new QgsVectorLayer( uri.uri(), editLayerName->text(), QStringLiteral( "spatialite" ) ); if ( vlayer->isValid() ) QgsMapLayerRegistry::instance()->addMapLayer( vlayer ); } diff --git a/src/app/openstreetmap/qgsosmimportdialog.cpp b/src/app/openstreetmap/qgsosmimportdialog.cpp index b05ffe8fee79..369b3ba3815c 100644 --- a/src/app/openstreetmap/qgsosmimportdialog.cpp +++ b/src/app/openstreetmap/qgsosmimportdialog.cpp @@ -47,26 +47,26 @@ QgsOSMImportDialog::~QgsOSMImportDialog() void QgsOSMImportDialog::onBrowseXml() { QSettings settings; - QString lastDir = settings.value( "/osm/lastDir", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "/osm/lastDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, QString(), lastDir, tr( "OpenStreetMap files (*.osm)" ) ); if ( fileName.isNull() ) return; - settings.setValue( "/osm/lastDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/osm/lastDir" ), QFileInfo( fileName ).absolutePath() ); editXmlFileName->setText( fileName ); } void QgsOSMImportDialog::onBrowseDb() { QSettings settings; - QString lastDir = settings.value( "/osm/lastDir", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "/osm/lastDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getSaveFileName( this, QString(), lastDir, tr( "SQLite databases (*.db)" ) ); if ( fileName.isNull() ) return; - settings.setValue( "/osm/lastDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/osm/lastDir" ), QFileInfo( fileName ).absolutePath() ); editDbFileName->setText( fileName ); } @@ -114,7 +114,7 @@ void QgsOSMImportDialog::onOK() { // create connection - this is a bit hacky, sorry for that. QSettings settings; - settings.setValue( QString( "/SpatiaLite/connections/%1/sqlitepath" ).arg( editConnName->text() ), mImport->outputDbFileName() ); + settings.setValue( QStringLiteral( "/SpatiaLite/connections/%1/sqlitepath" ).arg( editConnName->text() ), mImport->outputDbFileName() ); } QMessageBox::information( this, tr( "OpenStreetMap import" ), tr( "Import has been successful." ) ); diff --git a/src/app/pluginmanager/qgsapppluginmanagerinterface.cpp b/src/app/pluginmanager/qgsapppluginmanagerinterface.cpp index 706e35e97b43..e2bd7296cfac 100644 --- a/src/app/pluginmanager/qgsapppluginmanagerinterface.cpp +++ b/src/app/pluginmanager/qgsapppluginmanagerinterface.cpp @@ -56,12 +56,12 @@ void QgsAppPluginManagerInterface::clearPythonPluginMetadata() //! add a single plugin to the metadata registry void QgsAppPluginManagerInterface::addPluginMetadata( const QMap& metadata ) { - if ( metadata.isEmpty() || !metadata.contains( "id" ) ) + if ( metadata.isEmpty() || !metadata.contains( QStringLiteral( "id" ) ) ) { QgsDebugMsg( "Warning: incomplete metadata" ); return; } - mPluginManager->addPluginMetadata( metadata.value( "id" ), metadata ); + mPluginManager->addPluginMetadata( metadata.value( QStringLiteral( "id" ) ), metadata ); } diff --git a/src/app/pluginmanager/qgspluginitemdelegate.cpp b/src/app/pluginmanager/qgspluginitemdelegate.cpp index 54aefc8826e4..f95d25fa7702 100644 --- a/src/app/pluginmanager/qgspluginitemdelegate.cpp +++ b/src/app/pluginmanager/qgspluginitemdelegate.cpp @@ -93,8 +93,8 @@ void QgsPluginItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem } if ( ! index.data( PLUGIN_ERROR_ROLE ).toString().isEmpty() - || index.data( PLUGIN_STATUS_ROLE ).toString() == "upgradeable" - || index.data( PLUGIN_STATUS_ROLE ).toString() == "new" ) + || index.data( PLUGIN_STATUS_ROLE ).toString() == QLatin1String( "upgradeable" ) + || index.data( PLUGIN_STATUS_ROLE ).toString() == QLatin1String( "new" ) ) { QFont font = painter->font(); font.setBold( true ); diff --git a/src/app/pluginmanager/qgspluginmanager.cpp b/src/app/pluginmanager/qgspluginmanager.cpp index 163567bb4dca..c8d3f4ff8d82 100644 --- a/src/app/pluginmanager/qgspluginmanager.cpp +++ b/src/app/pluginmanager/qgspluginmanager.cpp @@ -58,7 +58,7 @@ QgsPluginManager::QgsPluginManager( QWidget * parent, bool pluginsAreEnabled, Qt::WindowFlags fl ) - : QgsOptionsDialogBase( "PluginManager", parent, fl ) + : QgsOptionsDialogBase( QStringLiteral( "PluginManager" ), parent, fl ) { // initialize pointer mPythonUtils = nullptr; @@ -75,7 +75,7 @@ QgsPluginManager::QgsPluginManager( QWidget * parent, bool pluginsAreEnabled, Qt // Restiore UI state for widgets not handled by QgsOptionsDialogBase QSettings settings; - mPluginsDetailsSplitter->restoreState( settings.value( QString( "/Windows/PluginManager/secondSplitterState" ) ).toByteArray() ); + mPluginsDetailsSplitter->restoreState( settings.value( QStringLiteral( "/Windows/PluginManager/secondSplitterState" ) ).toByteArray() ); // load translated description strings from qgspluginmanager_texts initTabDescriptions(); @@ -137,7 +137,7 @@ QgsPluginManager::~QgsPluginManager() delete mModelPlugins; QSettings settings; - settings.setValue( QString( "/Windows/PluginManager/secondSplitterState" ), mPluginsDetailsSplitter->saveState() ); + settings.setValue( QStringLiteral( "/Windows/PluginManager/secondSplitterState" ), mPluginsDetailsSplitter->saveState() ); } @@ -184,7 +184,7 @@ void QgsPluginManager::setPythonUtils( QgsPythonUtils* pythonUtils ) // get the QSettings group from the installer QString settingsGroup; - QgsPythonRunner::eval( "pyplugin_installer.instance().exportSettingsGroup()", settingsGroup ); + QgsPythonRunner::eval( QStringLiteral( "pyplugin_installer.instance().exportSettingsGroup()" ), settingsGroup ); // Initialize list of allowed checking intervals mCheckingOnStartIntervals << 0 << 1 << 3 << 7 << 14 << 30; @@ -226,10 +226,10 @@ void QgsPluginManager::loadPlugin( const QString& id ) QApplication::setOverrideCursor( Qt::WaitCursor ); QgsPluginRegistry *pRegistry = QgsPluginRegistry::instance(); - QString library = plugin->value( "library" ); - if ( plugin->value( "pythonic" ) == "true" ) + QString library = plugin->value( QStringLiteral( "library" ) ); + if ( plugin->value( QStringLiteral( "pythonic" ) ) == QLatin1String( "true" ) ) { - library = plugin->value( "id" ); + library = plugin->value( QStringLiteral( "id" ) ); QgsDebugMsg( "Loading Python plugin: " + library ); pRegistry->loadPythonPlugin( library ); } @@ -255,11 +255,11 @@ void QgsPluginManager::unloadPlugin( const QString& id ) } QgsPluginRegistry *pRegistry = QgsPluginRegistry::instance(); - QString library = plugin->value( "library" ); + QString library = plugin->value( QStringLiteral( "library" ) ); - if ( plugin->value( "pythonic" ) == "true" ) + if ( plugin->value( QStringLiteral( "pythonic" ) ) == QLatin1String( "true" ) ) { - library = plugin->value( "id" ); + library = plugin->value( QStringLiteral( "id" ) ); QgsDebugMsg( "Unloading Python plugin: " + library ); pRegistry->unloadPythonPlugin( library ); } @@ -281,7 +281,7 @@ void QgsPluginManager::savePluginState( QString id, bool state ) } QSettings settings; - if ( plugin->value( "pythonic" ) == "true" ) + if ( plugin->value( QStringLiteral( "pythonic" ) ) == QLatin1String( "true" ) ) { // Python plugin settings.setValue( "/PythonPlugins/" + id, state ); @@ -303,7 +303,7 @@ void QgsPluginManager::getCppPluginsMetadata() #if defined(Q_OS_WIN) || defined(__CYGWIN__) sharedLibExtension = "*.dll"; #else - sharedLibExtension = "*.so*"; + sharedLibExtension = QStringLiteral( "*.so*" ); #endif // check all libs in the current ans user plugins directories, and get name and descriptions @@ -312,7 +312,7 @@ void QgsPluginManager::getCppPluginsMetadata() QStringList myPathList( pr->libraryDirectory().path() ); QSettings settings; - QString myPaths = settings.value( "plugins/searchPathsForPlugins", "" ).toString(); + QString myPaths = settings.value( QStringLiteral( "plugins/searchPathsForPlugins" ), "" ).toString(); if ( !myPaths.isEmpty() ) { myPathList.append( myPaths.split( '|' ) ); @@ -331,7 +331,7 @@ void QgsPluginManager::getCppPluginsMetadata() for ( uint i = 0; i < pluginDir.count(); i++ ) { - QString lib = QString( "%1/%2" ).arg( myPluginDir, pluginDir[i] ); + QString lib = QStringLiteral( "%1/%2" ).arg( myPluginDir, pluginDir[i] ); #ifdef TESTLIB // This doesn't work on windows and causes problems with plugins @@ -438,18 +438,18 @@ void QgsPluginManager::getCppPluginsMetadata() QString baseName = "cpp:" + QFileInfo( lib ).baseName(); QMap metadata; - metadata["id"] = baseName; - metadata["name"] = pName(); - metadata["description"] = pDesc(); - metadata["category"] = ( pCat ? pCat() : tr( "Plugins" ) ); - metadata["version_installed"] = pVersion(); - metadata["icon"] = ( pIcon ? pIcon() : QString() ); - metadata["library"] = myLib->fileName(); - metadata["pythonic"] = "false"; - metadata["installed"] = "true"; - metadata["readonly"] = "true"; - metadata["status"] = "orphan"; - metadata["experimental"] = ( pExperimental ? pExperimental() : QString() ); + metadata[QStringLiteral( "id" )] = baseName; + metadata[QStringLiteral( "name" )] = pName(); + metadata[QStringLiteral( "description" )] = pDesc(); + metadata[QStringLiteral( "category" )] = ( pCat ? pCat() : tr( "Plugins" ) ); + metadata[QStringLiteral( "version_installed" )] = pVersion(); + metadata[QStringLiteral( "icon" )] = ( pIcon ? pIcon() : QString() ); + metadata[QStringLiteral( "library" )] = myLib->fileName(); + metadata[QStringLiteral( "pythonic" )] = QStringLiteral( "false" ); + metadata[QStringLiteral( "installed" )] = QStringLiteral( "true" ); + metadata[QStringLiteral( "readonly" )] = QStringLiteral( "true" ); + metadata[QStringLiteral( "status" )] = QStringLiteral( "orphan" ); + metadata[QStringLiteral( "experimental" )] = ( pExperimental ? pExperimental() : QString() ); mPlugins.insert( baseName, metadata ); delete myLib; @@ -481,7 +481,7 @@ void QgsPluginManager::reloadModelData() if ( !mCurrentlyDisplayedPlugin.isEmpty() ) { - wvDetails->setHtml( "" ); + wvDetails->setHtml( QLatin1String( "" ) ); buttonInstall->setEnabled( false ); buttonUninstall->setEnabled( false ); } @@ -490,15 +490,15 @@ void QgsPluginManager::reloadModelData() it != mPlugins.constEnd(); ++it ) { - if ( ! it->value( "id" ).isEmpty() ) + if ( ! it->value( QStringLiteral( "id" ) ).isEmpty() ) { - QString baseName = it->value( "id" ); - QString pluginName = it->value( "name" ); - QString description = it->value( "description" ); - QString author = it->value( "author_name" ); - QString iconPath = it->value( "icon" ); - QString status = it->value( "status" ); - QString error = it->value( "error" ); + QString baseName = it->value( QStringLiteral( "id" ) ); + QString pluginName = it->value( QStringLiteral( "name" ) ); + QString description = it->value( QStringLiteral( "description" ) ); + QString author = it->value( QStringLiteral( "author_name" ) ); + QString iconPath = it->value( QStringLiteral( "icon" ) ); + QString status = it->value( QStringLiteral( "status" ) ); + QString error = it->value( QStringLiteral( "error" ) ); QStandardItem * mypDetailItem = new QStandardItem( pluginName.left( 32 ) ); @@ -507,11 +507,11 @@ void QgsPluginManager::reloadModelData() mypDetailItem->setData( error, PLUGIN_ERROR_ROLE ); mypDetailItem->setData( description, PLUGIN_DESCRIPTION_ROLE ); mypDetailItem->setData( author, PLUGIN_AUTHOR_ROLE ); - mypDetailItem->setData( it->value( "tags" ), PLUGIN_TAGS_ROLE ); - mypDetailItem->setData( it->value( "downloads" ).rightJustified( 10, '0' ), PLUGIN_DOWNLOADS_ROLE ); - mypDetailItem->setData( it->value( "zip_repository" ), PLUGIN_REPOSITORY_ROLE ); - mypDetailItem->setData( it->value( "average_vote" ), PLUGIN_VOTE_ROLE ); - mypDetailItem->setData( it->value( "trusted" ), PLUGIN_TRUSTED_ROLE ); + mypDetailItem->setData( it->value( QStringLiteral( "tags" ) ), PLUGIN_TAGS_ROLE ); + mypDetailItem->setData( it->value( QStringLiteral( "downloads" ) ).rightJustified( 10, '0' ), PLUGIN_DOWNLOADS_ROLE ); + mypDetailItem->setData( it->value( QStringLiteral( "zip_repository" ) ), PLUGIN_REPOSITORY_ROLE ); + mypDetailItem->setData( it->value( QStringLiteral( "average_vote" ) ), PLUGIN_VOTE_ROLE ); + mypDetailItem->setData( it->value( QStringLiteral( "trusted" ) ), PLUGIN_TRUSTED_ROLE ); if ( QFileInfo( iconPath ).isFile() ) { @@ -526,17 +526,17 @@ void QgsPluginManager::reloadModelData() // Set checkable if the plugin is installed and not disabled due to incompatibility. // Broken plugins are checkable to to allow disabling them - mypDetailItem->setCheckable( it->value( "installed" ) == "true" && it->value( "error" ) != "incompatible" ); + mypDetailItem->setCheckable( it->value( QStringLiteral( "installed" ) ) == QLatin1String( "true" ) && it->value( QStringLiteral( "error" ) ) != QLatin1String( "incompatible" ) ); // Set ckeckState depending on the plugin is loaded or not. // Initially mark all unchecked, then overwrite state of loaded ones with checked. // Only do it with installed plugins, not not initialize checkboxes of not installed plugins at all. - if ( it->value( "installed" ) == "true" ) + if ( it->value( QStringLiteral( "installed" ) ) == QLatin1String( "true" ) ) { mypDetailItem->setCheckState( Qt::Unchecked ); } - if ( isPluginEnabled( it->value( "id" ) ) ) + if ( isPluginEnabled( it->value( QStringLiteral( "id" ) ) ) ) { mypDetailItem->setCheckState( Qt::Checked ); } @@ -556,11 +556,11 @@ void QgsPluginManager::reloadModelData() if ( mPythonUtils && mPythonUtils->isEnabled() ) { // TODO: implement better sort method instead of these dummy -Z statuses - mModelPlugins->appendRow( createSpacerItem( tr( "Only locally available", "category: plugins that are only locally available" ), "orphanZ" ) ); - if ( hasReinstallablePlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Reinstallable", "category: plugins that are installed and available" ), "installedZ" ) ); - if ( hasUpgradeablePlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Upgradeable", "category: plugins that are installed and there is a newer version available" ), "upgradeableZ" ) ); - if ( hasNewerPlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Downgradeable", "category: plugins that are installed and there is an OLDER version available" ), "newerZ" ) ); - if ( hasAvailablePlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Installable", "category: plugins that are available for installation" ), "not installedZ" ) ); + mModelPlugins->appendRow( createSpacerItem( tr( "Only locally available", "category: plugins that are only locally available" ), QStringLiteral( "orphanZ" ) ) ); + if ( hasReinstallablePlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Reinstallable", "category: plugins that are installed and available" ), QStringLiteral( "installedZ" ) ) ); + if ( hasUpgradeablePlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Upgradeable", "category: plugins that are installed and there is a newer version available" ), QStringLiteral( "upgradeableZ" ) ) ); + if ( hasNewerPlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Downgradeable", "category: plugins that are installed and there is an OLDER version available" ), QStringLiteral( "newerZ" ) ) ); + if ( hasAvailablePlugins() ) mModelPlugins->appendRow( createSpacerItem( tr( "Installable", "category: plugins that are available for installation" ), QStringLiteral( "not installedZ" ) ) ); } updateWindowTitle(); @@ -612,7 +612,7 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) return; } - QString html = ""; + QString html = QLatin1String( "" ); html += ""; - if ( !metadata->value( "plugin_id" ).isEmpty() ) + if ( !metadata->value( QStringLiteral( "plugin_id" ) ).isEmpty() ) { #ifdef WITH_QTWEBKIT html += QString( @@ -642,7 +642,7 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) " width:%1px;" " height:16px;" " }" - "" ).arg( metadata->value( "average_vote" ).toFloat() / 5 * 92 ); + "" ).arg( metadata->value( QStringLiteral( "average_vote" ) ).toFloat() / 5 * 92 ); html += QString( "" ).arg( metadata->value( "plugin_id" ) ); + "" ).arg( metadata->value( QStringLiteral( "plugin_id" ) ) ); #else voteRating->show(); voteLabel->show(); @@ -704,55 +704,55 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) } #ifdef WITH_QTWEBKIT - html += ""; + html += QLatin1String( "" ); #else html += ""; #endif // First prepare message box(es) - if ( ! metadata->value( "error" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "error" ) ).isEmpty() ) { QString errorMsg; - if ( metadata->value( "error" ) == "incompatible" ) + if ( metadata->value( QStringLiteral( "error" ) ) == QLatin1String( "incompatible" ) ) { - errorMsg = QString( "%1
                                                                                                                                                                                    %2" ).arg( tr( "This plugin is incompatible with this version of QGIS" ), tr( "Plugin designed for QGIS %1", "compatible QGIS version(s)" ).arg( metadata->value( "error_details" ) ) ); + errorMsg = QStringLiteral( "%1
                                                                                                                                                                                    %2" ).arg( tr( "This plugin is incompatible with this version of QGIS" ), tr( "Plugin designed for QGIS %1", "compatible QGIS version(s)" ).arg( metadata->value( QStringLiteral( "error_details" ) ) ) ); } - else if ( metadata->value( "error" ) == "dependent" ) + else if ( metadata->value( QStringLiteral( "error" ) ) == QLatin1String( "dependent" ) ) { - errorMsg = QString( "%1:
                                                                                                                                                                                    %2" ).arg( tr( "This plugin requires a missing module" ), metadata->value( "error_details" ) ); + errorMsg = QStringLiteral( "%1:
                                                                                                                                                                                    %2" ).arg( tr( "This plugin requires a missing module" ), metadata->value( QStringLiteral( "error_details" ) ) ); } else { - errorMsg = QString( "%1
                                                                                                                                                                                    %2" ).arg( tr( "This plugin is broken" ), metadata->value( "error_details" ) ); + errorMsg = QStringLiteral( "%1
                                                                                                                                                                                    %2" ).arg( tr( "This plugin is broken" ), metadata->value( QStringLiteral( "error_details" ) ) ); } html += QString( "" " " "
                                                                                                                                                                                    %1
                                                                                                                                                                                    " ).arg( errorMsg ); } - if ( metadata->value( "status" ) == "upgradeable" ) + if ( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "upgradeable" ) ) { html += QString( "" " " "
                                                                                                                                                                                    %1
                                                                                                                                                                                    " ).arg( tr( "There is a new version available" ) ); } - if ( metadata->value( "status" ) == "new" ) + if ( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "new" ) ) { html += QString( "" " " "
                                                                                                                                                                                    %1
                                                                                                                                                                                    " ).arg( tr( "This is a new plugin" ) ); } - if ( metadata->value( "status" ) == "newer" ) + if ( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "newer" ) ) { html += QString( "" " " "
                                                                                                                                                                                    %1
                                                                                                                                                                                    " ).arg( tr( "Installed version of this plugin is higher than any version found in repository" ) ); } - if ( metadata->value( "experimental" ) == "true" ) + if ( metadata->value( QStringLiteral( "experimental" ) ) == QLatin1String( "true" ) ) { html += QString( "" "
                                                                                                                                                                                    " @@ -761,7 +761,7 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) "
                                                                                                                                                                                    " ).arg( tr( "This plugin is experimental" ) ); } - if ( metadata->value( "deprecated" ) == "true" ) + if ( metadata->value( QStringLiteral( "deprecated" ) ) == QLatin1String( "true" ) ) { html += QString( "" "
                                                                                                                                                                                    " @@ -770,7 +770,7 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) "
                                                                                                                                                                                    " ).arg( tr( "This plugin is deprecated" ) ); } - if ( metadata->value( "trusted" ) == "true" ) + if ( metadata->value( QStringLiteral( "trusted" ) ) == QLatin1String( "true" ) ) { html += QString( "" "
                                                                                                                                                                                    " @@ -781,12 +781,12 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) // Now the metadata - html += "
                                                                                                                                                                                    "; + html += QLatin1String( "
                                                                                                                                                                                    " ); - QString iconPath = metadata->value( "icon" ); + QString iconPath = metadata->value( QStringLiteral( "icon" ) ); if ( QFileInfo( iconPath ).isFile() ) { - if ( iconPath.contains( ":/" ) ) + if ( iconPath.contains( QLatin1String( ":/" ) ) ) { iconPath = "qrc" + iconPath; } @@ -794,124 +794,124 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) { iconPath = "file://" + iconPath; } - html += QString( "" ).arg( iconPath ); + html += QStringLiteral( "" ).arg( iconPath ); } - html += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( metadata->value( "name" ) ); + html += QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( metadata->value( QStringLiteral( "name" ) ) ); - html += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( metadata->value( "description" ) ); + html += QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( metadata->value( QStringLiteral( "description" ) ) ); - if ( ! metadata->value( "about" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "about" ) ).isEmpty() ) { - QString about = metadata->value( "about" ); - html += about.replace( '\n', "
                                                                                                                                                                                    " ); + QString about = metadata->value( QStringLiteral( "about" ) ); + html += about.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); } - html += "

                                                                                                                                                                                    "; + html += QLatin1String( "

                                                                                                                                                                                    " ); QString votes; #ifndef WITH_QTWEBKIT votes += tr( "Average rating %1" ).arg( metadata->value( "average_vote" ).toFloat(), 0, 'f', 1 ); #endif - if ( ! metadata->value( "rating_votes" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "rating_votes" ) ).isEmpty() ) { if ( !votes.isEmpty() ) - votes += ", "; - votes += tr( "%1 rating vote(s)" ).arg( metadata->value( "rating_votes" ) ); + votes += QLatin1String( ", " ); + votes += tr( "%1 rating vote(s)" ).arg( metadata->value( QStringLiteral( "rating_votes" ) ) ); } - if ( ! metadata->value( "downloads" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "downloads" ) ).isEmpty() ) { if ( !votes.isEmpty() ) - votes += ", "; - votes += tr( "%1 downloads" ).arg( metadata->value( "downloads" ) ); + votes += QLatin1String( ", " ); + votes += tr( "%1 downloads" ).arg( metadata->value( QStringLiteral( "downloads" ) ) ); } #ifdef WITH_QTWEBKIT - html += "
                                                                                                                                                                                    "; - html += "
                                                                                                                                                                                    "; + html += QLatin1String( "
                                                                                                                                                                                    "; - html += "
                                                                                                                                                                                    "; + html += QLatin1String( "
                                                                                                                                                                                    " ); + html += QLatin1String( "
                                                                                                                                                                                    " ); - if ( ! metadata->value( "category" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "category" ) ).isEmpty() ) { - html += QString( "%1: %2
                                                                                                                                                                                    " ).arg( tr( "Category" ), metadata->value( "category" ) ); + html += QStringLiteral( "%1: %2
                                                                                                                                                                                    " ).arg( tr( "Category" ), metadata->value( QStringLiteral( "category" ) ) ); } - if ( ! metadata->value( "tags" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "tags" ) ).isEmpty() ) { - html += QString( "%1: %2
                                                                                                                                                                                    " ).arg( tr( "Tags" ), metadata->value( "tags" ) ); + html += QStringLiteral( "%1: %2
                                                                                                                                                                                    " ).arg( tr( "Tags" ), metadata->value( QStringLiteral( "tags" ) ) ); } - if ( ! metadata->value( "homepage" ).isEmpty() || ! metadata->value( "tracker" ).isEmpty() || ! metadata->value( "code_repository" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "homepage" ) ).isEmpty() || ! metadata->value( QStringLiteral( "tracker" ) ).isEmpty() || ! metadata->value( QStringLiteral( "code_repository" ) ).isEmpty() ) { - html += QString( "%1: " ).arg( tr( "More info" ) ); - if ( ! metadata->value( "homepage" ).isEmpty() ) + html += QStringLiteral( "%1: " ).arg( tr( "More info" ) ); + if ( ! metadata->value( QStringLiteral( "homepage" ) ).isEmpty() ) { - html += QString( "%2   " ).arg( metadata->value( "homepage" ), tr( "homepage" ) ); + html += QStringLiteral( "%2   " ).arg( metadata->value( QStringLiteral( "homepage" ) ), tr( "homepage" ) ); } - if ( ! metadata->value( "tracker" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "tracker" ) ).isEmpty() ) { - html += QString( "%2   " ).arg( metadata->value( "tracker" ), tr( "bug_tracker" ) ); + html += QStringLiteral( "%2   " ).arg( metadata->value( QStringLiteral( "tracker" ) ), tr( "bug_tracker" ) ); } - if ( ! metadata->value( "code_repository" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "code_repository" ) ).isEmpty() ) { - html += QString( "%2" ).arg( metadata->value( "code_repository" ), tr( "code_repository" ) ); + html += QStringLiteral( "%2" ).arg( metadata->value( QStringLiteral( "code_repository" ) ), tr( "code_repository" ) ); } - html += "
                                                                                                                                                                                    "; + html += QLatin1String( "
                                                                                                                                                                                    " ); } - html += "
                                                                                                                                                                                    "; + html += QLatin1String( "
                                                                                                                                                                                    " ); - if ( ! metadata->value( "author_email" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "author_email" ) ).isEmpty() ) { - html += QString( "%1: %3" ).arg( tr( "Author" ), metadata->value( "author_email" ), metadata->value( "author_name" ) ); - html += "

                                                                                                                                                                                    "; + html += QStringLiteral( "%1: %3" ).arg( tr( "Author" ), metadata->value( QStringLiteral( "author_email" ) ), metadata->value( QStringLiteral( "author_name" ) ) ); + html += QLatin1String( "

                                                                                                                                                                                    " ); } - else if ( ! metadata->value( "author_name" ).isEmpty() ) + else if ( ! metadata->value( QStringLiteral( "author_name" ) ).isEmpty() ) { - html += QString( "%1: %2" ).arg( tr( "Author" ), metadata->value( "author_name" ) ); - html += "

                                                                                                                                                                                    "; + html += QStringLiteral( "%1: %2" ).arg( tr( "Author" ), metadata->value( QStringLiteral( "author_name" ) ) ); + html += QLatin1String( "

                                                                                                                                                                                    " ); } - if ( ! metadata->value( "version_installed" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "version_installed" ) ).isEmpty() ) { - QString ver = metadata->value( "version_installed" ); - if ( ver == "-1" ) ver = '?'; - html += tr( "Installed version: %1 (in %2)
                                                                                                                                                                                    " ).arg( ver, metadata->value( "library" ) ); + QString ver = metadata->value( QStringLiteral( "version_installed" ) ); + if ( ver == QLatin1String( "-1" ) ) ver = '?'; + html += tr( "Installed version: %1 (in %2)
                                                                                                                                                                                    " ).arg( ver, metadata->value( QStringLiteral( "library" ) ) ); } - if ( ! metadata->value( "version_available" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "version_available" ) ).isEmpty() ) { - html += tr( "Available version: %1 (in %2)
                                                                                                                                                                                    " ).arg( metadata->value( "version_available" ), metadata->value( "zip_repository" ) ); + html += tr( "Available version: %1 (in %2)
                                                                                                                                                                                    " ).arg( metadata->value( QStringLiteral( "version_available" ) ), metadata->value( QStringLiteral( "zip_repository" ) ) ); } - if ( ! metadata->value( "changelog" ).isEmpty() ) + if ( ! metadata->value( QStringLiteral( "changelog" ) ).isEmpty() ) { - html += "
                                                                                                                                                                                    "; - QString changelog = tr( "changelog:
                                                                                                                                                                                    %1
                                                                                                                                                                                    " ).arg( metadata->value( "changelog" ) ); - html += changelog.replace( '\n', "
                                                                                                                                                                                    " ); + html += QLatin1String( "
                                                                                                                                                                                    " ); + QString changelog = tr( "changelog:
                                                                                                                                                                                    %1
                                                                                                                                                                                    " ).arg( metadata->value( QStringLiteral( "changelog" ) ) ); + html += changelog.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); } - html += "
                                                                                                                                                                                    "; + html += QLatin1String( "
                                                                                                                                                                                    " ); - html += ""; + html += QLatin1String( "" ); wvDetails->setHtml( html ); // Set buttonInstall text (and sometimes focus) buttonInstall->setDefault( false ); - if ( metadata->value( "status" ) == "upgradeable" ) + if ( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "upgradeable" ) ) { buttonInstall->setText( tr( "Upgrade plugin" ) ); buttonInstall->setDefault( true ); } - else if ( metadata->value( "status" ) == "newer" ) + else if ( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "newer" ) ) { buttonInstall->setText( tr( "Downgrade plugin" ) ); } - else if ( metadata->value( "status" ) == "not installed" || metadata->value( "status" ) == "new" ) + else if ( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "not installed" ) || metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "new" ) ) { buttonInstall->setText( tr( "Install plugin" ) ); } @@ -922,12 +922,12 @@ void QgsPluginManager::showPluginDetails( QStandardItem * item ) } // Enable/disable buttons - buttonInstall->setEnabled( metadata->value( "pythonic" ).toUpper() == "TRUE" && metadata->value( "status" ) != "orphan" ); - buttonUninstall->setEnabled( metadata->value( "pythonic" ).toUpper() == "TRUE" && metadata->value( "readonly" ) != "true" && metadata->value( "status" ) != "not installed" && metadata->value( "status" ) != "new" ); - buttonUninstall->setHidden( metadata->value( "status" ) == "not installed" || metadata->value( "status" ) == "new" ); + buttonInstall->setEnabled( metadata->value( QStringLiteral( "pythonic" ) ).toUpper() == QLatin1String( "TRUE" ) && metadata->value( QStringLiteral( "status" ) ) != QLatin1String( "orphan" ) ); + buttonUninstall->setEnabled( metadata->value( QStringLiteral( "pythonic" ) ).toUpper() == QLatin1String( "TRUE" ) && metadata->value( QStringLiteral( "readonly" ) ) != QLatin1String( "true" ) && metadata->value( QStringLiteral( "status" ) ) != QLatin1String( "not installed" ) && metadata->value( QStringLiteral( "status" ) ) != QLatin1String( "new" ) ); + buttonUninstall->setHidden( metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "not installed" ) || metadata->value( QStringLiteral( "status" ) ) == QLatin1String( "new" ) ); // Store the id of the currently displayed plugin - mCurrentlyDisplayedPlugin = metadata->value( "id" ); + mCurrentlyDisplayedPlugin = metadata->value( QStringLiteral( "id" ) ); } @@ -945,7 +945,7 @@ void QgsPluginManager::clearPythonPluginMetadata() it != mPlugins.end(); ) { - if ( it->value( "pythonic" ) == "true" ) + if ( it->value( QStringLiteral( "pythonic" ) ) == QLatin1String( "true" ) ) { it = mPlugins.erase( it ); } @@ -1004,20 +1004,20 @@ void QgsPluginManager::addToRepositoryList( const QMap& reposi connect( actionEnableThisRepositoryOnly, SIGNAL( triggered() ), this, SLOT( setRepositoryFilter() ) ); treeRepositories->setContextMenuPolicy( Qt::ActionsContextMenu ); QAction* actionClearFilter = new QAction( tr( "Clear filter" ), treeRepositories ); - actionClearFilter->setEnabled( repository.value( "inspection_filter" ) == "true" ); + actionClearFilter->setEnabled( repository.value( QStringLiteral( "inspection_filter" ) ) == QLatin1String( "true" ) ); treeRepositories->addAction( actionClearFilter ); connect( actionClearFilter, SIGNAL( triggered() ), this, SLOT( clearRepositoryFilter() ) ); } - QString key = repository.value( "name" ); + QString key = repository.value( QStringLiteral( "name" ) ); if ( ! key.isEmpty() ) { QTreeWidgetItem * a = new QTreeWidgetItem( treeRepositories ); a->setText( 1, key ); - a->setText( 2, repository.value( "url" ) ); - if ( repository.value( "enabled" ) == "true" && repository.value( "valid" ) == "true" ) + a->setText( 2, repository.value( QStringLiteral( "url" ) ) ); + if ( repository.value( QStringLiteral( "enabled" ) ) == QLatin1String( "true" ) && repository.value( QStringLiteral( "valid" ) ) == QLatin1String( "true" ) ) { - if ( repository.value( "state" ) == "2" ) + if ( repository.value( QStringLiteral( "state" ) ) == QLatin1String( "2" ) ) { a->setText( 0, tr( "connected" ) ); a->setIcon( 0, QIcon( ":/images/themes/default/repositoryConnected.png" ) ); @@ -1034,7 +1034,7 @@ void QgsPluginManager::addToRepositoryList( const QMap& reposi { a->setText( 0, tr( "disabled" ) ); a->setIcon( 0, QIcon( ":/images/themes/default/repositoryDisabled.png" ) ); - if ( repository.value( "valid" ) == "true" ) + if ( repository.value( QStringLiteral( "valid" ) ) == QLatin1String( "true" ) ) { a->setToolTip( 0, tr( "The repository is disabled" ) ); } @@ -1068,11 +1068,11 @@ void QgsPluginManager::reject() { // get the QSettings group from the installer QString settingsGroup; - QgsPythonRunner::eval( "pyplugin_installer.instance().exportSettingsGroup()", settingsGroup ); + QgsPythonRunner::eval( QStringLiteral( "pyplugin_installer.instance().exportSettingsGroup()" ), settingsGroup ); QSettings settings; settings.setValue( settingsGroup + "/checkOnStart", QVariant( ckbCheckUpdates->isChecked() ) ); settings.setValue( settingsGroup + "/checkOnStartInterval", QVariant( mCheckingOnStartIntervals.value( comboInterval->currentIndex() ) ) ); - QgsPythonRunner::run( "pyplugin_installer.instance().onManagerClose()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().onManagerClose()" ) ); } done( 1 ); } @@ -1097,39 +1097,39 @@ void QgsPluginManager::setCurrentTab( int idx ) { case PLUGMAN_TAB_ALL: // all (statuses ends with Z are for spacers to always sort properly) - acceptedStatuses << "installed" << "not installed" << "new" << "orphan" << "newer" << "upgradeable" << "not installedZ" << "installedZ" << "upgradeableZ" << "orphanZ" << "newerZZ" << ""; - tabTitle = "all_plugins"; + acceptedStatuses << QStringLiteral( "installed" ) << QStringLiteral( "not installed" ) << QStringLiteral( "new" ) << QStringLiteral( "orphan" ) << QStringLiteral( "newer" ) << QStringLiteral( "upgradeable" ) << QStringLiteral( "not installedZ" ) << QStringLiteral( "installedZ" ) << QStringLiteral( "upgradeableZ" ) << QStringLiteral( "orphanZ" ) << QStringLiteral( "newerZZ" ) << QLatin1String( "" ); + tabTitle = QStringLiteral( "all_plugins" ); break; case PLUGMAN_TAB_INSTALLED: // installed (statuses ends with Z are for spacers to always sort properly) - acceptedStatuses << "installed" << "orphan" << "newer" << "upgradeable" << "installedZ" << "upgradeableZ" << "orphanZ" << "newerZZ" << ""; - tabTitle = "installed_plugins"; + acceptedStatuses << QStringLiteral( "installed" ) << QStringLiteral( "orphan" ) << QStringLiteral( "newer" ) << QStringLiteral( "upgradeable" ) << QStringLiteral( "installedZ" ) << QStringLiteral( "upgradeableZ" ) << QStringLiteral( "orphanZ" ) << QStringLiteral( "newerZZ" ) << QLatin1String( "" ); + tabTitle = QStringLiteral( "installed_plugins" ); break; case PLUGMAN_TAB_NOT_INSTALLED: // not installed (get more) - acceptedStatuses << "not installed" << "new"; - tabTitle = "not_installed_plugins"; + acceptedStatuses << QStringLiteral( "not installed" ) << QStringLiteral( "new" ); + tabTitle = QStringLiteral( "not_installed_plugins" ); break; case PLUGMAN_TAB_UPGRADEABLE: // upgradeable - acceptedStatuses << "upgradeable"; - tabTitle = "upgradeable_plugins"; + acceptedStatuses << QStringLiteral( "upgradeable" ); + tabTitle = QStringLiteral( "upgradeable_plugins" ); break; case PLUGMAN_TAB_NEW: // new - acceptedStatuses << "new"; - tabTitle = "new_plugins"; + acceptedStatuses << QStringLiteral( "new" ); + tabTitle = QStringLiteral( "new_plugins" ); break; case PLUGMAN_TAB_INVALID: // invalid - acceptedStatuses << "invalid"; - tabTitle = "invalid_plugins"; + acceptedStatuses << QStringLiteral( "invalid" ); + tabTitle = QStringLiteral( "invalid_plugins" ); break; } mModelProxy->setAcceptedStatuses( acceptedStatuses ); // load tab description HTML to the detail browser - QString tabInfoHTML = ""; + QString tabInfoHTML = QLatin1String( "" ); QMap::const_iterator it = mTabDescriptions.constFind( tabTitle ); if ( it != mTabDescriptions.constEnd() ) { @@ -1222,8 +1222,8 @@ void QgsPluginManager::submitVote() void QgsPluginManager::sendVote( int pluginId, int vote ) { QString response; - QgsPythonRunner::eval( QString( "pyplugin_installer.instance().sendVote('%1', '%2')" ).arg( pluginId ).arg( vote ), response ); - if ( response == "True" ) + QgsPythonRunner::eval( QStringLiteral( "pyplugin_installer.instance().sendVote('%1', '%2')" ).arg( pluginId ).arg( vote ), response ); + if ( response == QLatin1String( "True" ) ) { pushMessage( tr( "Vote sent successfully" ), QgsMessageBar::INFO ); } @@ -1235,9 +1235,9 @@ void QgsPluginManager::sendVote( int pluginId, int vote ) void QgsPluginManager::on_wvDetails_linkClicked( const QUrl & url ) { - if ( url.scheme() == "rpc2" ) + if ( url.scheme() == QLatin1String( "rpc2" ) ) { - if ( url.host() == "plugin.vote" ) + if ( url.host() == QLatin1String( "plugin.vote" ) ) { QString params = url.path(); sendVote( params.split( '/' )[1].toInt(), params.split( '/' )[2].toInt() ); @@ -1252,9 +1252,9 @@ void QgsPluginManager::on_wvDetails_linkClicked( const QUrl & url ) void QgsPluginManager::on_leFilter_textChanged( QString theText ) { - if ( theText.startsWith( "tag:", Qt::CaseInsensitive ) ) + if ( theText.startsWith( QLatin1String( "tag:" ), Qt::CaseInsensitive ) ) { - theText = theText.remove( "tag:" ); + theText = theText.remove( QStringLiteral( "tag:" ) ); mModelProxy->setFilterRole( PLUGIN_TAGS_ROLE ); QgsDebugMsg( "PluginManager TAG filter changed to :" + theText ); } @@ -1274,21 +1274,21 @@ void QgsPluginManager::on_leFilter_textChanged( QString theText ) void QgsPluginManager::on_buttonUpgradeAll_clicked() { - QgsPythonRunner::run( "pyplugin_installer.instance().upgradeAllUpgradeable()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().upgradeAllUpgradeable()" ) ); } void QgsPluginManager::on_buttonInstall_clicked() { - QgsPythonRunner::run( QString( "pyplugin_installer.instance().installPlugin('%1')" ).arg( mCurrentlyDisplayedPlugin ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().installPlugin('%1')" ).arg( mCurrentlyDisplayedPlugin ) ); } void QgsPluginManager::on_buttonUninstall_clicked() { - QgsPythonRunner::run( QString( "pyplugin_installer.instance().uninstallPlugin('%1')" ).arg( mCurrentlyDisplayedPlugin ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().uninstallPlugin('%1')" ).arg( mCurrentlyDisplayedPlugin ) ); } @@ -1314,9 +1314,9 @@ void QgsPluginManager::setRepositoryFilter() if ( current ) { QString key = current->text( 1 ); - key = key.replace( '\'', "\\\'" ).replace( '\"', "\\\"" ); + key = key.replace( '\'', QLatin1String( "\\\'" ) ).replace( '\"', QLatin1String( "\\\"" ) ); QgsDebugMsg( "Disabling all repositories but selected: " + key ); - QgsPythonRunner::run( QString( "pyplugin_installer.instance().setRepositoryInspectionFilter('%1')" ).arg( key ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().setRepositoryInspectionFilter('%1')" ).arg( key ) ); } } @@ -1325,7 +1325,7 @@ void QgsPluginManager::setRepositoryFilter() void QgsPluginManager::clearRepositoryFilter() { QgsDebugMsg( "Enabling all repositories back" ); - QgsPythonRunner::run( QString( "pyplugin_installer.instance().setRepositoryInspectionFilter()" ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().setRepositoryInspectionFilter()" ) ); } @@ -1333,7 +1333,7 @@ void QgsPluginManager::clearRepositoryFilter() void QgsPluginManager::on_buttonRefreshRepos_clicked() { QgsDebugMsg( "Refreshing repositories..." ); - QgsPythonRunner::run( "pyplugin_installer.instance().reloadAndExportData()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().reloadAndExportData()" ) ); } @@ -1341,7 +1341,7 @@ void QgsPluginManager::on_buttonRefreshRepos_clicked() void QgsPluginManager::on_buttonAddRep_clicked() { QgsDebugMsg( "Adding repository connection..." ); - QgsPythonRunner::run( "pyplugin_installer.instance().addRepository()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().addRepository()" ) ); } @@ -1352,9 +1352,9 @@ void QgsPluginManager::on_buttonEditRep_clicked() if ( current ) { QString key = current->text( 1 ); - key = key.replace( '\'', "\\\'" ).replace( '\"', "\\\"" ); + key = key.replace( '\'', QLatin1String( "\\\'" ) ).replace( '\"', QLatin1String( "\\\"" ) ); QgsDebugMsg( "Editing repository connection: " + key ); - QgsPythonRunner::run( QString( "pyplugin_installer.instance().editRepository('%1')" ).arg( key ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().editRepository('%1')" ).arg( key ) ); } } @@ -1366,9 +1366,9 @@ void QgsPluginManager::on_buttonDeleteRep_clicked() if ( current ) { QString key = current->text( 1 ); - key = key.replace( '\'', "\\\'" ).replace( '\"', "\\\"" ); + key = key.replace( '\'', QLatin1String( "\\\'" ) ).replace( '\"', QLatin1String( "\\\"" ) ); QgsDebugMsg( "Deleting repository connection: " + key ); - QgsPythonRunner::run( QString( "pyplugin_installer.instance().deleteRepository('%1')" ).arg( key ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().deleteRepository('%1')" ).arg( key ) ); } } @@ -1377,21 +1377,21 @@ void QgsPluginManager::on_buttonDeleteRep_clicked() void QgsPluginManager::on_ckbExperimental_toggled( bool state ) { QString settingsGroup; - QgsPythonRunner::eval( "pyplugin_installer.instance().exportSettingsGroup()", settingsGroup ); + QgsPythonRunner::eval( QStringLiteral( "pyplugin_installer.instance().exportSettingsGroup()" ), settingsGroup ); QSettings settings; settings.setValue( settingsGroup + "/allowExperimental", QVariant( state ) ); - QgsPythonRunner::run( "pyplugin_installer.installer_data.plugins.rebuild()" ); - QgsPythonRunner::run( "pyplugin_installer.instance().exportPluginsToManager()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.installer_data.plugins.rebuild()" ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().exportPluginsToManager()" ) ); } void QgsPluginManager::on_ckbDeprecated_toggled( bool state ) { QString settingsGroup; - QgsPythonRunner::eval( "pyplugin_installer.instance().exportSettingsGroup()", settingsGroup ); + QgsPythonRunner::eval( QStringLiteral( "pyplugin_installer.instance().exportSettingsGroup()" ), settingsGroup ); QSettings settings; settings.setValue( settingsGroup + "/allowDeprecated", QVariant( state ) ); - QgsPythonRunner::run( "pyplugin_installer.installer_data.plugins.rebuild()" ); - QgsPythonRunner::run( "pyplugin_installer.instance().exportPluginsToManager()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.installer_data.plugins.rebuild()" ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().exportPluginsToManager()" ) ); } @@ -1408,7 +1408,7 @@ bool QgsPluginManager::isPluginEnabled( QString key ) } QSettings mySettings; - if ( plugin->value( "pythonic" ) != "true" ) + if ( plugin->value( QStringLiteral( "pythonic" ) ) != QLatin1String( "true" ) ) { // Trim "cpp:" prefix from cpp plugin id key = key.mid( 4 ); @@ -1416,7 +1416,7 @@ bool QgsPluginManager::isPluginEnabled( QString key ) } else { - return ( plugin->value( "installed" ) == "true" && mySettings.value( "/PythonPlugins/" + key, QVariant( false ) ).toBool() ); + return ( plugin->value( QStringLiteral( "installed" ) ) == QLatin1String( "true" ) && mySettings.value( "/PythonPlugins/" + key, QVariant( false ) ).toBool() ); } } @@ -1428,7 +1428,7 @@ bool QgsPluginManager::hasAvailablePlugins() it != mPlugins.constEnd(); ++it ) { - if ( it->value( "status" ) == "not installed" || it->value( "status" ) == "new" ) + if ( it->value( QStringLiteral( "status" ) ) == QLatin1String( "not installed" ) || it->value( QStringLiteral( "status" ) ) == QLatin1String( "new" ) ) { return true; } @@ -1446,7 +1446,7 @@ bool QgsPluginManager::hasReinstallablePlugins() ++it ) { // plugins marked as "installed" are available for download (otherwise they are marked "orphans") - if ( it->value( "status" ) == "installed" ) + if ( it->value( QStringLiteral( "status" ) ) == QLatin1String( "installed" ) ) { return true; } @@ -1463,7 +1463,7 @@ bool QgsPluginManager::hasUpgradeablePlugins() it != mPlugins.constEnd(); ++it ) { - if ( it->value( "status" ) == "upgradeable" ) + if ( it->value( QStringLiteral( "status" ) ) == QLatin1String( "upgradeable" ) ) { return true; } @@ -1480,7 +1480,7 @@ bool QgsPluginManager::hasNewPlugins() it != mPlugins.constEnd(); ++it ) { - if ( it->value( "status" ) == "new" ) + if ( it->value( QStringLiteral( "status" ) ) == QLatin1String( "new" ) ) { return true; } @@ -1497,7 +1497,7 @@ bool QgsPluginManager::hasNewerPlugins() it != mPlugins.constEnd(); ++it ) { - if ( it->value( "status" ) == "newer" ) + if ( it->value( QStringLiteral( "status" ) ) == QLatin1String( "newer" ) ) { return true; } @@ -1514,7 +1514,7 @@ bool QgsPluginManager::hasInvalidPlugins() it != mPlugins.constEnd(); ++it ) { - if ( ! it->value( "error" ).isEmpty() ) + if ( ! it->value( QStringLiteral( "error" ) ).isEmpty() ) { return true; } @@ -1530,11 +1530,11 @@ void QgsPluginManager::updateWindowTitle() QListWidgetItem *curitem = mOptListWidget->currentItem(); if ( curitem ) { - QString title = QString( "%1 | %2" ).arg( tr( "Plugins" ), curitem->text() ); + QString title = QStringLiteral( "%1 | %2" ).arg( tr( "Plugins" ), curitem->text() ); if ( mOptionsListWidget->currentRow() < mOptionsListWidget->count() - 1 ) { // if it's not the Settings tab, add the plugin count - title += QString( " (%3)" ).arg( mModelProxy->countWithCurrentStatus() ); + title += QStringLiteral( " (%3)" ).arg( mModelProxy->countWithCurrentStatus() ); } setWindowTitle( title ); } diff --git a/src/app/pluginmanager/qgspluginmanager_texts.cpp b/src/app/pluginmanager/qgspluginmanager_texts.cpp index c8b42ec9db5f..40723f7b5c9d 100644 --- a/src/app/pluginmanager/qgspluginmanager_texts.cpp +++ b/src/app/pluginmanager/qgspluginmanager_texts.cpp @@ -8,7 +8,7 @@ void QgsPluginManager::initTabDescriptions() if ( !mTabDescriptions.isEmpty() ) return; - mTabDescriptions.insert( "all_plugins", tr( "

                                                                                                                                                                                    All Plugins

                                                                                                                                                                                    \ + mTabDescriptions.insert( QStringLiteral( "all_plugins" ), tr( "

                                                                                                                                                                                    All Plugins

                                                                                                                                                                                    \ \

                                                                                                                                                                                    \ On the left you see the list of all plugins available for your QGIS, both installed and available for download. \ @@ -28,7 +28,7 @@ on the 'Invalid' tab. Click on the plugin name to see more details, or to reinst - mTabDescriptions.insert( "installed_plugins", tr( "

                                                                                                                                                                                    Installed Plugins

                                                                                                                                                                                    \ + mTabDescriptions.insert( QStringLiteral( "installed_plugins" ), tr( "

                                                                                                                                                                                    Installed Plugins

                                                                                                                                                                                    \ \

                                                                                                                                                                                    \ Here you only see plugins installed on your QGIS.\ @@ -46,7 +46,7 @@ You can change the sorting via the context menu (right click).\ - mTabDescriptions.insert( "upgradeable_plugins", tr( "

                                                                                                                                                                                    Upgradable plugins

                                                                                                                                                                                    \ + mTabDescriptions.insert( QStringLiteral( "upgradeable_plugins" ), tr( "

                                                                                                                                                                                    Upgradable plugins

                                                                                                                                                                                    \ \

                                                                                                                                                                                    \ Here are upgradeable plugins. It means more recent versions of installed \ @@ -57,7 +57,7 @@ plugins are available in the repositories.\ - mTabDescriptions.insert( "not_installed_plugins", tr( "

                                                                                                                                                                                    Not installed plugins

                                                                                                                                                                                    \ + mTabDescriptions.insert( QStringLiteral( "not_installed_plugins" ), tr( "

                                                                                                                                                                                    Not installed plugins

                                                                                                                                                                                    \ \

                                                                                                                                                                                    \ Here you see the list of all plugins available in the repositories, but which are not yet installed.\ @@ -78,7 +78,7 @@ then click the 'Install plugin' button.\ - mTabDescriptions.insert( "new_plugins", tr( "

                                                                                                                                                                                    New plugins

                                                                                                                                                                                    \ + mTabDescriptions.insert( QStringLiteral( "new_plugins" ), tr( "

                                                                                                                                                                                    New plugins

                                                                                                                                                                                    \ \

                                                                                                                                                                                    \ Here you see brand new plugins which can be installed.\ @@ -89,7 +89,7 @@ Here you see brand new plugins which can be installed.\ - mTabDescriptions.insert( "invalid_plugins", tr( "

                                                                                                                                                                                    Invalid plugins

                                                                                                                                                                                    \ + mTabDescriptions.insert( QStringLiteral( "invalid_plugins" ), tr( "

                                                                                                                                                                                    Invalid plugins

                                                                                                                                                                                    \ \

                                                                                                                                                                                    \ Plugins in this list here are broken or incompatible with your version of QGIS.\ diff --git a/src/app/pluginmanager/qgspluginsortfilterproxymodel.cpp b/src/app/pluginmanager/qgspluginsortfilterproxymodel.cpp index 64ee085d34b5..107297156caf 100644 --- a/src/app/pluginmanager/qgspluginsortfilterproxymodel.cpp +++ b/src/app/pluginmanager/qgspluginsortfilterproxymodel.cpp @@ -58,7 +58,7 @@ void QgsPluginSortFilterProxyModel::setAcceptedSpacers( const QString& spacers ) bool QgsPluginSortFilterProxyModel::filterByStatus( QModelIndex &index ) const { - if ( mAcceptedStatuses.contains( "invalid" ) + if ( mAcceptedStatuses.contains( QStringLiteral( "invalid" ) ) && sourceModel()->data( index, PLUGIN_ERROR_ROLE ).toString().isEmpty() ) { // Don't accept if the "invalid" filter is set and the plugin is ok @@ -68,7 +68,7 @@ bool QgsPluginSortFilterProxyModel::filterByStatus( QModelIndex &index ) const QString status = sourceModel()->data( index, PLUGIN_STATUS_ROLE ).toString(); if ( status.endsWith( 'Z' ) ) status.chop( 1 ); if ( ! mAcceptedStatuses.isEmpty() - && ! mAcceptedStatuses.contains( "invalid" ) + && ! mAcceptedStatuses.contains( QStringLiteral( "invalid" ) ) && ! mAcceptedStatuses.contains( status ) ) { // Don't accept if the status doesn't match @@ -147,7 +147,7 @@ void QgsPluginSortFilterProxyModel::sortPluginsByVote() void QgsPluginSortFilterProxyModel::sortPluginsByStatus() { - setAcceptedSpacers( "status" ); + setAcceptedSpacers( QStringLiteral( "status" ) ); sort( 0, Qt::DescendingOrder ); setSortRole( PLUGIN_STATUS_ROLE ); } diff --git a/src/app/pluginmanager/qgspluginsortfilterproxymodel.h b/src/app/pluginmanager/qgspluginsortfilterproxymodel.h index 827800d2a5f0..4ee7807ec3b8 100644 --- a/src/app/pluginmanager/qgspluginsortfilterproxymodel.h +++ b/src/app/pluginmanager/qgspluginsortfilterproxymodel.h @@ -49,7 +49,7 @@ class QgsPluginSortFilterProxyModel : public QSortFilterProxyModel void setAcceptedStatuses( const QStringList& statuses ); //! (Re)configire the spacer filter - void setAcceptedSpacers( const QString& spacers = "" ); + void setAcceptedSpacers( const QString& spacers = QStringLiteral( "" ) ); //! Return number of item with status filter matching (no other filters are considered) int countWithCurrentStatus(); diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 273746e064d3..1b43237b6d99 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -375,9 +375,9 @@ static void setTitleBarText_( QWidget & qgisApp ) { QString caption = QgisApp::tr( "QGIS " ); - if ( Qgis::QGIS_VERSION.endsWith( "Master" ) ) + if ( Qgis::QGIS_VERSION.endsWith( QLatin1String( "Master" ) ) ) { - caption += QString( "%1" ).arg( Qgis::QGIS_DEV_VERSION ); + caption += QStringLiteral( "%1" ).arg( Qgis::QGIS_DEV_VERSION ); } else { @@ -430,7 +430,7 @@ void QgisApp::layerTreeViewDoubleClicked( const QModelIndex& index ) { Q_UNUSED( index ) QSettings settings; - switch ( settings.value( "/qgis/legendDoubleClickAction", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/qgis/legendDoubleClickAction" ), 0 ).toInt() ) { case 0: { @@ -502,8 +502,8 @@ void QgisApp::validateCrs( QgsCoordinateReferenceSystem &srs ) { static QString authid = QString::null; QSettings mySettings; - QString myDefaultProjectionOption = mySettings.value( "/Projections/defaultBehaviour", "prompt" ).toString(); - if ( myDefaultProjectionOption == "prompt" ) + QString myDefaultProjectionOption = mySettings.value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString(); + if ( myDefaultProjectionOption == QLatin1String( "prompt" ) ) { // @note this class is not a descendent of QWidget so we can't pass // it in the ctor of the layer projection selector @@ -535,7 +535,7 @@ void QgisApp::validateCrs( QgsCoordinateReferenceSystem &srs ) delete mySelector; } - else if ( myDefaultProjectionOption == "useProject" ) + else if ( myDefaultProjectionOption == QLatin1String( "useProject" ) ) { // XXX TODO: Change project to store selected CS as 'projectCRS' not 'selectedWkt' authid = QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs().authid(); @@ -545,7 +545,7 @@ void QgisApp::validateCrs( QgsCoordinateReferenceSystem &srs ) } else ///Projections/defaultBehaviour==useGlobal { - authid = mySettings.value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString(); + authid = mySettings.value( QStringLiteral( "/Projections/layerDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString(); srs.createFromOgcWmsCrs( authid ); QgsDebugMsg( "Layer srs set from default: " + authid ); messageBar()->pushMessage( tr( "CRS was undefined" ), tr( "defaulting to CRS %1 - %2" ).arg( authid, srs.description() ), QgsMessageBar::WARNING, messageTimeout() ); @@ -613,9 +613,9 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh namSetup(); // load GUI: actions, menus, toolbars - mProfiler->beginGroup( "qgisapp" ); - mProfiler->beginGroup( "startup" ); - startProfile( "Setting up UI" ); + mProfiler->beginGroup( QStringLiteral( "qgisapp" ) ); + mProfiler->beginGroup( QStringLiteral( "startup" ) ); + startProfile( QStringLiteral( "Setting up UI" ) ); setupUi( this ); endProfile(); @@ -625,7 +625,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh ////////// - startProfile( "Checking database" ); + startProfile( QStringLiteral( "Checking database" ) ); mSplash->showMessage( tr( "Checking database" ), Qt::AlignHCenter | Qt::AlignBottom ); qApp->processEvents(); // Do this early on before anyone else opens it and prevents us copying it @@ -636,7 +636,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh } endProfile(); - startProfile( "Initializing authentication" ); + startProfile( QStringLiteral( "Initializing authentication" ) ); mSplash->showMessage( tr( "Initializing authentication" ), Qt::AlignHCenter | Qt::AlignBottom ); qApp->processEvents(); QgsAuthManager::instance()->init( QgsApplication::pluginPath() ); @@ -647,7 +647,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh endProfile(); // Create the themes folder for the user - startProfile( "Creating theme folder" ); + startProfile( QStringLiteral( "Creating theme folder" ) ); QgsApplication::createThemeFolder(); endProfile(); @@ -659,7 +659,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QSettings settings; - startProfile( "Building style sheet" ); + startProfile( QStringLiteral( "Building style sheet" ) ); // set up stylesheet builder and apply saved or default style options mStyleSheetBuilder = new QgisAppStyleSheet( this ); connect( mStyleSheetBuilder, SIGNAL( appStyleSheetChanged( const QString& ) ), @@ -673,26 +673,26 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh centralLayout->setContentsMargins( 0, 0, 0, 0 ); // "theMapCanvas" used to find this canonical instance later - startProfile( "Creating map canvas" ); + startProfile( QStringLiteral( "Creating map canvas" ) ); mMapCanvas = new QgsMapCanvas( centralWidget ); - mMapCanvas->setObjectName( "theMapCanvas" ); + mMapCanvas->setObjectName( QStringLiteral( "theMapCanvas" ) ); connect( mMapCanvas, SIGNAL( messageEmitted( const QString&, const QString&, QgsMessageBar::MessageLevel ) ), this, SLOT( displayMessage( const QString&, const QString&, QgsMessageBar::MessageLevel ) ) ); mMapCanvas->setWhatsThis( tr( "Map canvas. This is where raster and vector " "layers are displayed when added to the map" ) ); // set canvas color right away - int myRed = settings.value( "/qgis/default_canvas_color_red", 255 ).toInt(); - int myGreen = settings.value( "/qgis/default_canvas_color_green", 255 ).toInt(); - int myBlue = settings.value( "/qgis/default_canvas_color_blue", 255 ).toInt(); + int myRed = settings.value( QStringLiteral( "/qgis/default_canvas_color_red" ), 255 ).toInt(); + int myGreen = settings.value( QStringLiteral( "/qgis/default_canvas_color_green" ), 255 ).toInt(); + int myBlue = settings.value( QStringLiteral( "/qgis/default_canvas_color_blue" ), 255 ).toInt(); mMapCanvas->setCanvasColor( QColor( myRed, myGreen, myBlue ) ); endProfile(); // what type of project to auto-open - mProjOpen = settings.value( "/qgis/projOpenAtLaunch", 0 ).toInt(); + mProjOpen = settings.value( QStringLiteral( "/qgis/projOpenAtLaunch" ), 0 ).toInt(); - startProfile( "Welcome page" ); + startProfile( QStringLiteral( "Welcome page" ) ); mWelcomePage = new QgsWelcomePage( skipVersionCheck ); endProfile(); @@ -707,95 +707,95 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh mCentralContainer->setCurrentIndex( mProjOpen ? 0 : 1 ); // a bar to warn the user with non-blocking messages - startProfile( "Message bar" ); + startProfile( QStringLiteral( "Message bar" ) ); mInfoBar = new QgsMessageBar( centralWidget ); mInfoBar->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed ); centralLayout->addWidget( mInfoBar, 0, 0, 1, 1 ); endProfile(); - startProfile( "User input dock" ); + startProfile( QStringLiteral( "User input dock" ) ); // User Input Dock Widget mUserInputDockWidget = new QgsUserInputDockWidget( this ); - mUserInputDockWidget->setObjectName( "UserInputDockWidget" ); + mUserInputDockWidget->setObjectName( QStringLiteral( "UserInputDockWidget" ) ); endProfile(); //set the focus to the map canvas mMapCanvas->setFocus(); - startProfile( "Layer tree" ); + startProfile( QStringLiteral( "Layer tree" ) ); mLayerTreeView = new QgsLayerTreeView( this ); - mLayerTreeView->setObjectName( "theLayerTreeView" ); // "theLayerTreeView" used to find this canonical instance later + mLayerTreeView->setObjectName( QStringLiteral( "theLayerTreeView" ) ); // "theLayerTreeView" used to find this canonical instance later endProfile(); // create undo widget - startProfile( "Undo dock" ); + startProfile( QStringLiteral( "Undo dock" ) ); mUndoDock = new QgsDockWidget( tr( "Undo/Redo Panel" ), this ); mUndoWidget = new QgsUndoWidget( mUndoDock, mMapCanvas ); - mUndoWidget->setObjectName( "Undo" ); + mUndoWidget->setObjectName( QStringLiteral( "Undo" ) ); mUndoDock->setWidget( mUndoWidget ); - mUndoDock->setObjectName( "undo/redo dock" ); + mUndoDock->setObjectName( QStringLiteral( "undo/redo dock" ) ); endProfile(); // Advanced Digitizing dock - startProfile( "Advanced digitize panel" ); + startProfile( QStringLiteral( "Advanced digitize panel" ) ); mAdvancedDigitizingDockWidget = new QgsAdvancedDigitizingDockWidget( mMapCanvas, this ); - mAdvancedDigitizingDockWidget->setObjectName( "AdvancedDigitizingTools" ); + mAdvancedDigitizingDockWidget->setObjectName( QStringLiteral( "AdvancedDigitizingTools" ) ); endProfile(); // Statistical Summary dock - startProfile( "Stats dock" ); + startProfile( QStringLiteral( "Stats dock" ) ); mStatisticalSummaryDockWidget = new QgsStatisticalSummaryDockWidget( this ); - mStatisticalSummaryDockWidget->setObjectName( "StatistalSummaryDockWidget" ); + mStatisticalSummaryDockWidget->setObjectName( QStringLiteral( "StatistalSummaryDockWidget" ) ); endProfile(); // Bookmarks dock - startProfile( "Bookmarks widget" ); + startProfile( QStringLiteral( "Bookmarks widget" ) ); mBookMarksDockWidget = new QgsBookmarks( this ); - mBookMarksDockWidget->setObjectName( "BookmarksDockWidget" ); + mBookMarksDockWidget->setObjectName( QStringLiteral( "BookmarksDockWidget" ) ); endProfile(); - startProfile( "Snapping utils" ); + startProfile( QStringLiteral( "Snapping utils" ) ); mSnappingUtils = new QgsMapCanvasSnappingUtils( mMapCanvas, this ); mMapCanvas->setSnappingUtils( mSnappingUtils ); connect( QgsProject::instance(), &QgsProject::snappingConfigChanged, this, &QgisApp::onSnappingConfigChanged ); endProfile(); - functionProfile( &QgisApp::createActions, this, "Create actions" ); - functionProfile( &QgisApp::createActionGroups, this, "Create action group" ); - functionProfile( &QgisApp::createMenus, this, "Create menus" ); - functionProfile( &QgisApp::createToolBars, this, "Toolbars" ); - functionProfile( &QgisApp::createStatusBar, this, "Status bar" ); - functionProfile( &QgisApp::createCanvasTools, this, "Create canvas tools" ); + functionProfile( &QgisApp::createActions, this, QStringLiteral( "Create actions" ) ); + functionProfile( &QgisApp::createActionGroups, this, QStringLiteral( "Create action group" ) ); + functionProfile( &QgisApp::createMenus, this, QStringLiteral( "Create menus" ) ); + functionProfile( &QgisApp::createToolBars, this, QStringLiteral( "Toolbars" ) ); + functionProfile( &QgisApp::createStatusBar, this, QStringLiteral( "Status bar" ) ); + functionProfile( &QgisApp::createCanvasTools, this, QStringLiteral( "Create canvas tools" ) ); mMapCanvas->freeze(); - functionProfile( &QgisApp::initLayerTreeView, this, "Init Layer tree view" ); - functionProfile( &QgisApp::createOverview, this, "Create overview" ); - functionProfile( &QgisApp::createMapTips, this, "Create map tips" ); - functionProfile( &QgisApp::createDecorations, this, "Create decorations" ); - functionProfile( &QgisApp::readSettings, this, "Read settings" ); - functionProfile( &QgisApp::updateRecentProjectPaths, this, "Update recent project paths" ); - functionProfile( &QgisApp::updateProjectFromTemplates, this, "Update project from templates" ); - functionProfile( &QgisApp::legendLayerSelectionChanged, this, "Legend layer selection changed" ); + functionProfile( &QgisApp::initLayerTreeView, this, QStringLiteral( "Init Layer tree view" ) ); + functionProfile( &QgisApp::createOverview, this, QStringLiteral( "Create overview" ) ); + functionProfile( &QgisApp::createMapTips, this, QStringLiteral( "Create map tips" ) ); + functionProfile( &QgisApp::createDecorations, this, QStringLiteral( "Create decorations" ) ); + functionProfile( &QgisApp::readSettings, this, QStringLiteral( "Read settings" ) ); + functionProfile( &QgisApp::updateRecentProjectPaths, this, QStringLiteral( "Update recent project paths" ) ); + functionProfile( &QgisApp::updateProjectFromTemplates, this, QStringLiteral( "Update project from templates" ) ); + functionProfile( &QgisApp::legendLayerSelectionChanged, this, QStringLiteral( "Legend layer selection changed" ) ); mSaveRollbackInProgress = false; QFileSystemWatcher* projectsTemplateWatcher = new QFileSystemWatcher( this ); - QString templateDirName = settings.value( "/qgis/projectTemplateDir", + QString templateDirName = settings.value( QStringLiteral( "/qgis/projectTemplateDir" ), QgsApplication::qgisSettingsDirPath() + "project_templates" ).toString(); projectsTemplateWatcher->addPath( templateDirName ); connect( projectsTemplateWatcher, SIGNAL( directoryChanged( QString ) ), this, SLOT( updateProjectFromTemplates() ) ); // initialize the plugin manager - startProfile( "Plugin manager" ); + startProfile( QStringLiteral( "Plugin manager" ) ); mPluginManager = new QgsPluginManager( this, restorePlugins ); endProfile(); addDockWidget( Qt::LeftDockWidgetArea, mUndoDock ); mUndoDock->hide(); - startProfile( "Layer Style dock" ); + startProfile( QStringLiteral( "Layer Style dock" ) ); mMapStylingDock = new QgsDockWidget( this ); mMapStylingDock->setWindowTitle( tr( "Layer Styling" ) ); - mMapStylingDock->setObjectName( "LayerStyling" ); + mMapStylingDock->setObjectName( QStringLiteral( "LayerStyling" ) ); mMapStyleWidget = new QgsLayerStylingWidget( mMapCanvas, mMapLayerPanelFactories ); mMapStylingDock->setWidget( mMapStyleWidget ); connect( mMapStyleWidget, SIGNAL( styleChanged( QgsMapLayer* ) ), this, SLOT( updateLabelToolButtons() ) ); @@ -805,15 +805,15 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh mMapStylingDock->hide(); endProfile(); - startProfile( "Snapping dialog" ); + startProfile( QStringLiteral( "Snapping dialog" ) ); mSnappingDialogWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, this ); - QString mainSnappingWidgetMode = QSettings().value( "/qgis/mainSnappingWidgetMode", "dialog" ).toString(); - if ( mainSnappingWidgetMode == "dock" ) + QString mainSnappingWidgetMode = QSettings().value( QStringLiteral( "/qgis/mainSnappingWidgetMode" ), "dialog" ).toString(); + if ( mainSnappingWidgetMode == QLatin1String( "dock" ) ) { QgsDockWidget* dock = new QgsDockWidget( tr( "Snapping and Digitizing Options" ), QgisApp::instance() ); dock->setAllowedAreas( Qt::AllDockWidgetAreas ); dock->setWidget( mSnappingDialogWidget ); - dock->setObjectName( "Snapping and Digitizing Options" ); + dock->setObjectName( QStringLiteral( "Snapping and Digitizing Options" ) ); addDockWidget( Qt::LeftDockWidgetArea, dock ); mSnappingDialogContainer = dock; dock->hide(); @@ -831,12 +831,12 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh endProfile(); mBrowserWidget = new QgsBrowserDockWidget( tr( "Browser Panel" ), this ); - mBrowserWidget->setObjectName( "Browser" ); + mBrowserWidget->setObjectName( QStringLiteral( "Browser" ) ); addDockWidget( Qt::LeftDockWidgetArea, mBrowserWidget ); mBrowserWidget->hide(); mBrowserWidget2 = new QgsBrowserDockWidget( tr( "Browser Panel (2)" ), this ); - mBrowserWidget2->setObjectName( "Browser2" ); + mBrowserWidget2->setObjectName( QStringLiteral( "Browser2" ) ); addDockWidget( Qt::LeftDockWidgetArea, mBrowserWidget2 ); mBrowserWidget2->hide(); @@ -856,7 +856,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh mpGpsWidget = new QgsGPSInformationWidget( mMapCanvas ); //create the dock widget mpGpsDock = new QgsDockWidget( tr( "GPS Information Panel" ), this ); - mpGpsDock->setObjectName( "GPSInformation" ); + mpGpsDock->setObjectName( QStringLiteral( "GPSInformation" ) ); mpGpsDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); addDockWidget( Qt::LeftDockWidgetArea, mpGpsDock ); // add to the Panel submenu @@ -869,7 +869,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh mLogViewer = new QgsMessageLogViewer( statusBar(), this ); mLogDock = new QgsDockWidget( tr( "Log Messages Panel" ), this ); - mLogDock->setObjectName( "MessageLog" ); + mLogDock->setObjectName( QStringLiteral( "MessageLog" ) ); mLogDock->setAllowedAreas( Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea ); addDockWidget( Qt::BottomDockWidgetArea, mLogDock ); mLogDock->setWidget( mLogViewer ); @@ -940,7 +940,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QgsPluginRegistry::instance()->restoreSessionPlugins( QgsApplication::pluginPath() ); // Also restore plugins from user specified plugin directories - QString myPaths = settings.value( "plugins/searchPathsForPlugins", "" ).toString(); + QString myPaths = settings.value( QStringLiteral( "plugins/searchPathsForPlugins" ), "" ).toString(); if ( !myPaths.isEmpty() ) { QStringList myPathList = myPaths.split( '|' ); @@ -950,10 +950,10 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh if ( mPythonUtils && mPythonUtils->isEnabled() ) { - startProfile( "initPluginInstaller" ); + startProfile( QStringLiteral( "initPluginInstaller" ) ); // initialize the plugin installer to start fetching repositories in background - QgsPythonRunner::run( "import pyplugin_installer" ); - QgsPythonRunner::run( "pyplugin_installer.initPluginInstaller()" ); + QgsPythonRunner::run( QStringLiteral( "import pyplugin_installer" ) ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.initPluginInstaller()" ) ); // enable Python in the Plugin Manager and pass the PythonUtils to it mPluginManager->setPythonUtils( mPythonUtils ); endProfile(); @@ -966,7 +966,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh } // Set icon size of toolbars - int size = settings.value( "/IconSize", QGIS_ICON_SIZE ).toInt(); + int size = settings.value( QStringLiteral( "/IconSize" ), QGIS_ICON_SIZE ).toInt(); setIconSizes( size ); mSplash->showMessage( tr( "Initializing file filters" ), Qt::AlignHCenter | Qt::AlignBottom ); @@ -999,12 +999,12 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh // mSplash->showMessage( tr( "Restoring window state" ), Qt::AlignHCenter | Qt::AlignBottom ); qApp->processEvents(); - startProfile( "Restore window state" ); + startProfile( QStringLiteral( "Restore window state" ) ); restoreWindowState(); endProfile(); // do main window customization - after window state has been restored, before the window is shown - startProfile( "Update customiziation on main window" ); + startProfile( QStringLiteral( "Update customiziation on main window" ) ); QgsCustomization::instance()->updateMainWindow( mToolbarMenu ); endProfile(); @@ -1016,7 +1016,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh mMapTipsVisible = false; // This turns on the map tip if they where active in the last session - if ( settings.value( "/qgis/enableMapTips", false ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/enableMapTips" ), false ).toBool() ) { toggleMapTips( true ); } @@ -1028,7 +1028,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh mFullScreenMode = false; mPrevScreenModeMaximized = false; - startProfile( "Show main window" ); + startProfile( QStringLiteral( "Show main window" ) ); show(); qApp->processEvents(); endProfile(); @@ -1039,25 +1039,25 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QShortcut* zoomInShortCut = new QShortcut( QKeySequence( tr( "Ctrl++" ) ), this ); connect( zoomInShortCut, SIGNAL( activated() ), mMapCanvas, SLOT( zoomIn() ) ); - zoomInShortCut->setObjectName( "ZoomInToCanvas" ); - zoomInShortCut->setWhatsThis( "Zoom in to canvas" ); + zoomInShortCut->setObjectName( QStringLiteral( "ZoomInToCanvas" ) ); + zoomInShortCut->setWhatsThis( QStringLiteral( "Zoom in to canvas" ) ); QShortcut* zoomShortCut2 = new QShortcut( QKeySequence( tr( "Ctrl+=" ) ), this ); connect( zoomShortCut2, SIGNAL( activated() ), mMapCanvas, SLOT( zoomIn() ) ); - zoomShortCut2->setObjectName( "ZoomInToCanvas2" ); - zoomShortCut2->setWhatsThis( "Zoom in to canvas (secondary)" ); + zoomShortCut2->setObjectName( QStringLiteral( "ZoomInToCanvas2" ) ); + zoomShortCut2->setWhatsThis( QStringLiteral( "Zoom in to canvas (secondary)" ) ); QShortcut* zoomOutShortCut = new QShortcut( QKeySequence( tr( "Ctrl+-" ) ), this ); connect( zoomOutShortCut, SIGNAL( activated() ), mMapCanvas, SLOT( zoomOut() ) ); - zoomOutShortCut->setObjectName( "ZoomOutOfCanvas" ); - zoomOutShortCut->setWhatsThis( "Zoom out of canvas" ); + zoomOutShortCut->setObjectName( QStringLiteral( "ZoomOutOfCanvas" ) ); + zoomOutShortCut->setWhatsThis( QStringLiteral( "Zoom out of canvas" ) ); //also make ctrl+alt+= a shortcut to switch to zoom in map tool QShortcut* zoomInToolShortCut = new QShortcut( QKeySequence( tr( "Ctrl+Alt+=" ) ), this ); connect( zoomInToolShortCut, SIGNAL( activated() ), this, SLOT( zoomIn() ) ); - zoomInToolShortCut->setObjectName( "ZoomIn2" ); - zoomInToolShortCut->setWhatsThis( "Zoom in (secondary)" ); + zoomInToolShortCut->setObjectName( QStringLiteral( "ZoomIn2" ) ); + zoomInToolShortCut->setWhatsThis( QStringLiteral( "Zoom in (secondary)" ) ); // Show a nice tip of the day - if ( settings.value( QString( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), true ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), true ).toBool() ) { mSplash->hide(); QgsTipGui myTip( this ); @@ -1088,7 +1088,7 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh // notify user if authentication system is disabled ( void )QgsAuthGuiUtils::isDisabled( messageBar() ); - startProfile( "New project" ); + startProfile( QStringLiteral( "New project" ) ); fileNewBlank(); // prepare empty project, also skips any default templates from loading endProfile(); @@ -1298,10 +1298,10 @@ QgisApp::~QgisApp() void QgisApp::dragEnterEvent( QDragEnterEvent *event ) { - if ( event->mimeData()->hasUrls() || event->mimeData()->hasFormat( "application/x-vnd.qgis.qgis.uri" ) ) + if ( event->mimeData()->hasUrls() || event->mimeData()->hasFormat( QStringLiteral( "application/x-vnd.qgis.qgis.uri" ) ) ) { // the mime data are coming from layer tree, so ignore that, do not import those layers again - if ( !event->mimeData()->hasFormat( "application/qgis.layertreemodeldata" ) ) + if ( !event->mimeData()->hasFormat( QStringLiteral( "application/qgis.layertreemodeldata" ) ) ) event->acceptProposedAction(); } } @@ -1428,19 +1428,19 @@ void QgisApp::handleDropUriList( const QgsMimeDataUtils::UriList& lst ) { QString uri = crsAndFormatAdjustedLayerUri( u.uri, u.supportedCrs, u.supportedFormats ); - if ( u.layerType == "vector" ) + if ( u.layerType == QLatin1String( "vector" ) ) { addVectorLayer( uri, u.name, u.providerKey ); } - else if ( u.layerType == "raster" ) + else if ( u.layerType == QLatin1String( "raster" ) ) { addRasterLayer( uri, u.name, u.providerKey ); } - else if ( u.layerType == "plugin" ) + else if ( u.layerType == QLatin1String( "plugin" ) ) { addPluginLayer( uri, u.name, u.providerKey ); } - else if ( u.layerType == "custom" ) + else if ( u.layerType == QLatin1String( "custom" ) ) { Q_FOREACH ( QgsCustomDropHandler* handler, mCustomDropHandlers ) { @@ -1489,18 +1489,18 @@ QgisAppStyleSheet* QgisApp::styleSheetBuilder() void QgisApp::readSettings() { QSettings settings; - QString themename = settings.value( "UI/UITheme", "default" ).toString(); + QString themename = settings.value( QStringLiteral( "UI/UITheme" ), "default" ).toString(); setTheme( themename ); // Read legacy settings mRecentProjects.clear(); - settings.beginGroup( "/UI" ); + settings.beginGroup( QStringLiteral( "/UI" ) ); // Migrate old recent projects if first time with new system - if ( !settings.childGroups().contains( "recentProjects" ) ) + if ( !settings.childGroups().contains( QStringLiteral( "recentProjects" ) ) ) { - QStringList oldRecentProjects = settings.value( "/UI/recentProjectsList" ).toStringList(); + QStringList oldRecentProjects = settings.value( QStringLiteral( "/UI/recentProjectsList" ) ).toStringList(); Q_FOREACH ( const QString& project, oldRecentProjects ) { @@ -1513,7 +1513,7 @@ void QgisApp::readSettings() } settings.endGroup(); - settings.beginGroup( "/UI/recentProjects" ); + settings.beginGroup( QStringLiteral( "/UI/recentProjects" ) ); QStringList projectKeysList = settings.childGroups(); //convert list to int values to obtain proper order @@ -1528,10 +1528,10 @@ void QgisApp::readSettings() { QgsWelcomePageItemsModel::RecentProjectData data; settings.beginGroup( QString::number( key ) ); - data.title = settings.value( "title" ).toString(); - data.path = settings.value( "path" ).toString(); - data.previewImagePath = settings.value( "previewImage" ).toString(); - data.crs = settings.value( "crs" ).toString(); + data.title = settings.value( QStringLiteral( "title" ) ).toString(); + data.path = settings.value( QStringLiteral( "path" ) ).toString(); + data.previewImagePath = settings.value( QStringLiteral( "previewImage" ) ).toString(); + data.crs = settings.value( QStringLiteral( "crs" ) ).toString(); settings.endGroup(); mRecentProjects.append( data ); } @@ -1539,9 +1539,9 @@ void QgisApp::readSettings() // this is a new session! reset enable macros value to "ask" // whether set to "just for this session" - if ( settings.value( "/qgis/enableMacros", 1 ).toInt() == 2 ) + if ( settings.value( QStringLiteral( "/qgis/enableMacros" ), 1 ).toInt() == 2 ) { - settings.setValue( "/qgis/enableMacros", 1 ); + settings.setValue( QStringLiteral( "/qgis/enableMacros" ), 1 ); } } @@ -1924,7 +1924,7 @@ void QgisApp::setAppStyleSheet( const QString& stylesheet ) int QgisApp::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } void QgisApp::createMenus() @@ -1956,9 +1956,9 @@ void QgisApp::createMenus() // Panel and Toolbar Submenus mPanelMenu = new QMenu( tr( "Panels" ), this ); - mPanelMenu->setObjectName( "mPanelMenu" ); + mPanelMenu->setObjectName( QStringLiteral( "mPanelMenu" ) ); mToolbarMenu = new QMenu( tr( "Toolbars" ), this ); - mToolbarMenu->setObjectName( "mToolbarMenu" ); + mToolbarMenu->setObjectName( QStringLiteral( "mToolbarMenu" ) ); // Get platform for menu layout customization (Gnome, Kde, Mac, Win) QDialogButtonBox::ButtonLayout layout = @@ -2032,17 +2032,17 @@ void QgisApp::createMenus() // Database Menu // don't add it yet, wait for a plugin mDatabaseMenu = new QMenu( tr( "&Database" ), menuBar() ); - mDatabaseMenu->setObjectName( "mDatabaseMenu" ); + mDatabaseMenu->setObjectName( QStringLiteral( "mDatabaseMenu" ) ); // Web Menu // don't add it yet, wait for a plugin mWebMenu = new QMenu( tr( "&Web" ), menuBar() ); - mWebMenu->setObjectName( "mWebMenu" ); + mWebMenu->setObjectName( QStringLiteral( "mWebMenu" ) ); // Help menu // add What's this button to it QAction* before = mActionHelpAPI; QAction* actionWhatsThis = QWhatsThis::createAction( this ); - actionWhatsThis->setIcon( QgsApplication::getThemeIcon( "/mActionWhatsThis.svg" ) ); + actionWhatsThis->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionWhatsThis.svg" ) ) ); mHelpMenu->insertAction( before, actionWhatsThis ); } @@ -2071,11 +2071,11 @@ void QgisApp::createToolBars() // snapping widget as tool bar - QString simpleSnappingWidgetMode = QSettings().value( "/qgis/simpleSnappingWidgetMode", "toolbar" ).toString(); - if ( simpleSnappingWidgetMode != "statusbar" ) + QString simpleSnappingWidgetMode = QSettings().value( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), "toolbar" ).toString(); + if ( simpleSnappingWidgetMode != QLatin1String( "statusbar" ) ) { mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, mSnappingToolBar ); - mSnappingWidget->setObjectName( "mSnappingWidget" ); + mSnappingWidget->setObjectName( QStringLiteral( "mSnappingWidget" ) ); //mSnappingWidget->setFont( myFont ); connect( mSnappingWidget, SIGNAL( snappingConfigChanged() ), QgsProject::instance(), SIGNAL( snappingConfigChanged() ) ); mSnappingToolBar->addWidget( mSnappingWidget ); @@ -2104,7 +2104,7 @@ void QgisApp::createToolBars() bt->addActions( selectActions ); bt->setDefaultAction( mActionSelectByExpression ); QAction* selectionAction = mAttributesToolBar->insertWidget( mActionDeselectAll, bt ); - selectionAction->setObjectName( "ActionSelection" ); + selectionAction->setObjectName( QStringLiteral( "ActionSelection" ) ); // select tool button @@ -2116,7 +2116,7 @@ void QgisApp::createToolBars() bt->addActions( selectionActions ); QAction* defSelectAction = mActionSelectFeatures; - switch ( settings.value( "/UI/selectTool", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/selectTool" ), 0 ).toInt() ) { case 0: defSelectAction = mActionSelectFeatures; @@ -2136,7 +2136,7 @@ void QgisApp::createToolBars() } bt->setDefaultAction( defSelectAction ); QAction* selectAction = mAttributesToolBar->insertWidget( selectionAction, bt ); - selectAction->setObjectName( "ActionSelect" ); + selectAction->setObjectName( QStringLiteral( "ActionSelect" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // feature action tool button @@ -2150,7 +2150,7 @@ void QgisApp::createToolBars() connect( mFeatureActionMenu, SIGNAL( aboutToShow() ), this, SLOT( refreshFeatureActions() ) ); bt->setMenu( mFeatureActionMenu ); QAction* featureActionAction = mAttributesToolBar->insertWidget( selectAction, bt ); - featureActionAction->setObjectName( "ActionFeatureAction" ); + featureActionAction->setObjectName( QStringLiteral( "ActionFeatureAction" ) ); // measure tool button @@ -2161,7 +2161,7 @@ void QgisApp::createToolBars() bt->addAction( mActionMeasureAngle ); QAction* defMeasureAction = mActionMeasure; - switch ( settings.value( "/UI/measureTool", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/measureTool" ), 0 ).toInt() ) { case 0: defMeasureAction = mActionMeasure; @@ -2175,7 +2175,7 @@ void QgisApp::createToolBars() } bt->setDefaultAction( defMeasureAction ); QAction* measureAction = mAttributesToolBar->insertWidget( mActionMapTips, bt ); - measureAction->setObjectName( "ActionMeasure" ); + measureAction->setObjectName( QStringLiteral( "ActionMeasure" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // annotation tool button @@ -2189,7 +2189,7 @@ void QgisApp::createToolBars() bt->addAction( mActionAnnotation ); QAction* defAnnotationAction = mActionTextAnnotation; - switch ( settings.value( "/UI/annotationTool", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/annotationTool" ), 0 ).toInt() ) { case 0: defAnnotationAction = mActionTextAnnotation; @@ -2210,7 +2210,7 @@ void QgisApp::createToolBars() } bt->setDefaultAction( defAnnotationAction ); QAction* annotationAction = mAttributesToolBar->addWidget( bt ); - annotationAction->setObjectName( "ActionAnnotation" ); + annotationAction->setObjectName( QStringLiteral( "ActionAnnotation" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // vector layer edits tool buttons @@ -2229,7 +2229,7 @@ void QgisApp::createToolBars() bt->addAction( mActionNewMemoryLayer ); QAction* defNewLayerAction = mActionNewVectorLayer; - switch ( settings.value( "/UI/defaultNewLayer", 1 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/defaultNewLayer" ), 1 ).toInt() ) { case 0: defNewLayerAction = mActionNewSpatiaLiteLayer; @@ -2249,7 +2249,7 @@ void QgisApp::createToolBars() bt->setDefaultAction( defNewLayerAction ); QAction* newLayerAction = mLayerToolBar->addWidget( bt ); - newLayerAction->setObjectName( "ActionNewLayer" ); + newLayerAction->setObjectName( QStringLiteral( "ActionNewLayer" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // map service tool button @@ -2258,7 +2258,7 @@ void QgisApp::createToolBars() bt->addAction( mActionAddWmsLayer ); bt->addAction( mActionAddAmsLayer ); QAction* defMapServiceAction = mActionAddWmsLayer; - switch ( settings.value( "/UI/defaultMapService", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/defaultMapService" ), 0 ).toInt() ) { case 0: defMapServiceAction = mActionAddWmsLayer; @@ -2270,7 +2270,7 @@ void QgisApp::createToolBars() bt->setDefaultAction( defMapServiceAction ); QAction* mapServiceAction = mLayerToolBar->insertWidget( mActionAddWmsLayer, bt ); mLayerToolBar->removeAction( mActionAddWmsLayer ); - mapServiceAction->setObjectName( "ActionMapService" ); + mapServiceAction->setObjectName( QStringLiteral( "ActionMapService" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // feature service tool button @@ -2279,7 +2279,7 @@ void QgisApp::createToolBars() bt->addAction( mActionAddWfsLayer ); bt->addAction( mActionAddAfsLayer ); QAction* defFeatureServiceAction = mActionAddWfsLayer; - switch ( settings.value( "/UI/defaultFeatureService", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/defaultFeatureService" ), 0 ).toInt() ) { case 0: defFeatureServiceAction = mActionAddWfsLayer; @@ -2291,7 +2291,7 @@ void QgisApp::createToolBars() bt->setDefaultAction( defFeatureServiceAction ); QAction* featureServiceAction = mLayerToolBar->insertWidget( mActionAddWfsLayer, bt ); mLayerToolBar->removeAction( mActionAddWfsLayer ); - featureServiceAction->setObjectName( "ActionFeatureService" ); + featureServiceAction->setObjectName( QStringLiteral( "ActionFeatureService" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // add db layer button @@ -2306,7 +2306,7 @@ void QgisApp::createToolBars() if ( mActionAddOracleLayer ) bt->addAction( mActionAddOracleLayer ); QAction* defAddDbLayerAction = mActionAddPgLayer; - switch ( settings.value( "/UI/defaultAddDbLayerAction", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/defaultAddDbLayerAction" ), 0 ).toInt() ) { case 0: defAddDbLayerAction = mActionAddPgLayer; @@ -2324,7 +2324,7 @@ void QgisApp::createToolBars() if ( defAddDbLayerAction ) bt->setDefaultAction( defAddDbLayerAction ); QAction* addDbLayerAction = mLayerToolBar->insertWidget( mapServiceAction, bt ); - addDbLayerAction->setObjectName( "ActionAddDbLayer" ); + addDbLayerAction->setObjectName( QStringLiteral( "ActionAddDbLayer" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); QLayout *layout = mLayerToolBar->layout(); @@ -2348,7 +2348,7 @@ void QgisApp::createToolBars() bt->addAction( mActionOffsetPointSymbol ); QAction* defPointSymbolAction = mActionRotatePointSymbols; - switch ( settings.value( "/UI/defaultPointSymbolAction", 0 ).toInt() ) + switch ( settings.value( QStringLiteral( "/UI/defaultPointSymbolAction" ), 0 ).toInt() ) { case 0: defPointSymbolAction = mActionRotatePointSymbols; @@ -2359,7 +2359,7 @@ void QgisApp::createToolBars() } bt->setDefaultAction( defPointSymbolAction ); QAction* pointSymbolAction = mAdvancedDigitizeToolBar->addWidget( bt ); - pointSymbolAction->setObjectName( "ActionPointSymbolTools" ); + pointSymbolAction->setObjectName( QStringLiteral( "ActionPointSymbolTools" ) ); connect( bt, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); // Cad toolbar @@ -2372,12 +2372,12 @@ void QgisApp::createToolBars() void QgisApp::createStatusBar() { //remove borders from children under Windows - statusBar()->setStyleSheet( "QStatusBar::item {border: none;}" ); + statusBar()->setStyleSheet( QStringLiteral( "QStatusBar::item {border: none;}" ) ); // Add a panel to the status bar for the scale, coords and progress // And also rendering suppression checkbox mProgressBar = new QProgressBar( statusBar() ); - mProgressBar->setObjectName( "mProgressBar" ); + mProgressBar->setObjectName( QStringLiteral( "mProgressBar" ) ); mProgressBar->setMaximumWidth( 100 ); mProgressBar->hide(); mProgressBar->setWhatsThis( tr( "Progress bar that displays the status " @@ -2390,34 +2390,34 @@ void QgisApp::createStatusBar() // Bumped the font up one point size since 8 was too // small on some platforms. A point size of 9 still provides // plenty of display space on 1024x768 resolutions - QFont myFont( "Arial", 9 ); + QFont myFont( QStringLiteral( "Arial" ), 9 ); statusBar()->setFont( myFont ); //coords status bar widget mCoordsEdit = new QgsStatusBarCoordinatesWidget( statusBar() ); - mCoordsEdit->setObjectName( "mCoordsEdit" ); + mCoordsEdit->setObjectName( QStringLiteral( "mCoordsEdit" ) ); mCoordsEdit->setMapCanvas( mMapCanvas ); mCoordsEdit->setFont( myFont ); statusBar()->addPermanentWidget( mCoordsEdit, 0 ); mScaleWidget = new QgsStatusBarScaleWidget( mMapCanvas, statusBar() ); - mScaleWidget->setObjectName( "mScaleWidget" ); + mScaleWidget->setObjectName( QStringLiteral( "mScaleWidget" ) ); mScaleWidget->setFont( myFont ); connect( mScaleWidget, SIGNAL( scaleLockChanged( bool ) ), mMapCanvas, SLOT( setScaleLocked( bool ) ) ); statusBar()->addPermanentWidget( mScaleWidget, 0 ); // zoom widget mMagnifierWidget = new QgsStatusBarMagnifierWidget( statusBar() ); - mMagnifierWidget->setObjectName( "mMagnifierWidget" ); + mMagnifierWidget->setObjectName( QStringLiteral( "mMagnifierWidget" ) ); mMagnifierWidget->setFont( myFont ); connect( mMapCanvas, SIGNAL( magnificationChanged( double ) ), mMagnifierWidget, SLOT( updateMagnification( double ) ) ); connect( mMagnifierWidget, SIGNAL( magnificationChanged( double ) ), mMapCanvas, SLOT( setMagnificationFactor( double ) ) ); - mMagnifierWidget->updateMagnification( QSettings().value( "/qgis/magnifier_factor_default", 1.0 ).toDouble() ); + mMagnifierWidget->updateMagnification( QSettings().value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble() ); statusBar()->addPermanentWidget( mMagnifierWidget, 0 ); // add a widget to show/set current rotation mRotationLabel = new QLabel( QString(), statusBar() ); - mRotationLabel->setObjectName( "mRotationLabel" ); + mRotationLabel->setObjectName( QStringLiteral( "mRotationLabel" ) ); mRotationLabel->setFont( myFont ); mRotationLabel->setMinimumWidth( 10 ); //mRotationLabel->setMaximumHeight( 20 ); @@ -2429,18 +2429,18 @@ void QgisApp::createStatusBar() statusBar()->addPermanentWidget( mRotationLabel, 0 ); // snapping widget - QString simpleSnappingWidgetMode = QSettings().value( "/qgis/simpleSnappingWidgetMode", "toolbar" ).toString(); - if ( simpleSnappingWidgetMode == "statusbar" ) + QString simpleSnappingWidgetMode = QSettings().value( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), "toolbar" ).toString(); + if ( simpleSnappingWidgetMode == QLatin1String( "statusbar" ) ) { mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, statusBar() ); - mSnappingWidget->setObjectName( "mSnappingWidget" ); + mSnappingWidget->setObjectName( QStringLiteral( "mSnappingWidget" ) ); mSnappingWidget->setFont( myFont ); connect( mSnappingWidget, SIGNAL( snappingConfigChanged() ), QgsProject::instance(), SIGNAL( snappingConfigChanged() ) ); statusBar()->addPermanentWidget( mSnappingWidget, 0 ); } mRotationEdit = new QgsDoubleSpinBox( statusBar() ); - mRotationEdit->setObjectName( "mRotationEdit" ); + mRotationEdit->setObjectName( QStringLiteral( "mRotationEdit" ) ); mRotationEdit->setClearValue( 0.0 ); mRotationEdit->setKeyboardTracking( false ); mRotationEdit->setMaximumWidth( 120 ); @@ -2460,7 +2460,7 @@ void QgisApp::createStatusBar() // render suppression status bar widget mRenderSuppressionCBox = new QCheckBox( tr( "Render" ), statusBar() ); - mRenderSuppressionCBox->setObjectName( "mRenderSuppressionCBox" ); + mRenderSuppressionCBox->setObjectName( QStringLiteral( "mRenderSuppressionCBox" ) ); mRenderSuppressionCBox->setChecked( true ); mRenderSuppressionCBox->setFont( myFont ); mRenderSuppressionCBox->setWhatsThis( tr( "When checked, the map layers " @@ -2475,11 +2475,11 @@ void QgisApp::createStatusBar() mOnTheFlyProjectionStatusButton = new QToolButton( statusBar() ); mOnTheFlyProjectionStatusButton->setAutoRaise( true ); mOnTheFlyProjectionStatusButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); - mOnTheFlyProjectionStatusButton->setObjectName( "mOntheFlyProjectionStatusButton" ); + mOnTheFlyProjectionStatusButton->setObjectName( QStringLiteral( "mOntheFlyProjectionStatusButton" ) ); // Maintain uniform widget height in status bar by setting button height same as labels // For Qt/Mac 3.3, the default toolbutton height is 30 and labels were expanding to match mOnTheFlyProjectionStatusButton->setMaximumHeight( mScaleWidget->height() ); - mOnTheFlyProjectionStatusButton->setIcon( QgsApplication::getThemeIcon( "mIconProjectionEnabled.png" ) ); + mOnTheFlyProjectionStatusButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconProjectionEnabled.png" ) ) ); mOnTheFlyProjectionStatusButton->setWhatsThis( tr( "This icon shows whether " "on the fly coordinate reference system transformation is enabled or not. " "Click the icon to bring up " @@ -2493,11 +2493,11 @@ void QgisApp::createStatusBar() mMessageButton = new QToolButton( statusBar() ); mMessageButton->setAutoRaise( true ); - mMessageButton->setIcon( QgsApplication::getThemeIcon( "/mMessageLogRead.svg" ) ); + mMessageButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mMessageLogRead.svg" ) ) ); mMessageButton->setToolTip( tr( "Messages" ) ); mMessageButton->setWhatsThis( tr( "Messages" ) ); mMessageButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); - mMessageButton->setObjectName( "mMessageLogViewerButton" ); + mMessageButton->setObjectName( QStringLiteral( "mMessageLogViewerButton" ) ); mMessageButton->setMaximumHeight( mScaleWidget->height() ); mMessageButton->setCheckable( true ); statusBar()->addPermanentWidget( mMessageButton, 0 ); @@ -2527,7 +2527,7 @@ void QgisApp::setIconSizes( int size ) Q_FOREACH ( QToolBar * toolbar, toolbars ) { QString className = toolbar->parent()->metaObject()->className(); - if ( className == "QgisApp" ) + if ( className == QLatin1String( "QgisApp" ) ) { toolbar->setIconSize( QSize( size, size ) ); } @@ -2567,148 +2567,148 @@ void QgisApp::setTheme( const QString& theThemeName ) */ QgsApplication::setUITheme( theThemeName ); //QgsDebugMsg("Setting theme to \n" + theThemeName); - mActionNewProject->setIcon( QgsApplication::getThemeIcon( "/mActionFileNew.svg" ) ); - mActionOpenProject->setIcon( QgsApplication::getThemeIcon( "/mActionFileOpen.svg" ) ); - mActionSaveProject->setIcon( QgsApplication::getThemeIcon( "/mActionFileSave.svg" ) ); - mActionSaveProjectAs->setIcon( QgsApplication::getThemeIcon( "/mActionFileSaveAs.svg" ) ); - mActionNewPrintComposer->setIcon( QgsApplication::getThemeIcon( "/mActionNewComposer.svg" ) ); - mActionShowComposerManager->setIcon( QgsApplication::getThemeIcon( "/mActionComposerManager.svg" ) ); - mActionSaveMapAsImage->setIcon( QgsApplication::getThemeIcon( "/mActionSaveMapAsImage.svg" ) ); - mActionExit->setIcon( QgsApplication::getThemeIcon( "/mActionFileExit.png" ) ); - mActionAddOgrLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddOgrLayer.svg" ) ); - mActionAddRasterLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddRasterLayer.svg" ) ); + mActionNewProject->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileNew.svg" ) ) ); + mActionOpenProject->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileOpen.svg" ) ) ); + mActionSaveProject->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileSave.svg" ) ) ); + mActionSaveProjectAs->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileSaveAs.svg" ) ) ); + mActionNewPrintComposer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewComposer.svg" ) ) ); + mActionShowComposerManager->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionComposerManager.svg" ) ) ); + mActionSaveMapAsImage->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveMapAsImage.svg" ) ) ); + mActionExit->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileExit.png" ) ) ); + mActionAddOgrLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddOgrLayer.svg" ) ) ); + mActionAddRasterLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddRasterLayer.svg" ) ) ); #ifdef HAVE_POSTGRESQL - mActionAddPgLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddPostgisLayer.svg" ) ); + mActionAddPgLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddPostgisLayer.svg" ) ) ); #endif - mActionNewSpatiaLiteLayer->setIcon( QgsApplication::getThemeIcon( "/mActionNewSpatiaLiteLayer.svg" ) ); - mActionAddSpatiaLiteLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddSpatiaLiteLayer.svg" ) ); - mActionAddMssqlLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddMssqlLayer.svg" ) ); - mActionAddDb2Layer->setIcon( QgsApplication::getThemeIcon( "/mActionAddDb2Layer.svg" ) ); + mActionNewSpatiaLiteLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewSpatiaLiteLayer.svg" ) ) ); + mActionAddSpatiaLiteLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddSpatiaLiteLayer.svg" ) ) ); + mActionAddMssqlLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddMssqlLayer.svg" ) ) ); + mActionAddDb2Layer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddDb2Layer.svg" ) ) ); #ifdef HAVE_ORACLE mActionAddOracleLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddOracleLayer.svg" ) ); #endif - mActionRemoveLayer->setIcon( QgsApplication::getThemeIcon( "/mActionRemoveLayer.svg" ) ); - mActionDuplicateLayer->setIcon( QgsApplication::getThemeIcon( "/mActionDuplicateLayer.svg" ) ); - mActionSetLayerCRS->setIcon( QgsApplication::getThemeIcon( "/mActionSetLayerCRS.png" ) ); - mActionSetProjectCRSFromLayer->setIcon( QgsApplication::getThemeIcon( "/mActionSetProjectCRSFromLayer.png" ) ); - mActionNewVectorLayer->setIcon( QgsApplication::getThemeIcon( "/mActionNewVectorLayer.svg" ) ); - mActionNewMemoryLayer->setIcon( QgsApplication::getThemeIcon( "/mActionCreateMemory.svg" ) ); - mActionAddAllToOverview->setIcon( QgsApplication::getThemeIcon( "/mActionAddAllToOverview.svg" ) ); - mActionHideAllLayers->setIcon( QgsApplication::getThemeIcon( "/mActionHideAllLayers.svg" ) ); - mActionShowAllLayers->setIcon( QgsApplication::getThemeIcon( "/mActionShowAllLayers.svg" ) ); - mActionHideSelectedLayers->setIcon( QgsApplication::getThemeIcon( "/mActionHideSelectedLayers.png" ) ); - mActionShowSelectedLayers->setIcon( QgsApplication::getThemeIcon( "/mActionShowSelectedLayers.png" ) ); - mActionRemoveAllFromOverview->setIcon( QgsApplication::getThemeIcon( "/mActionRemoveAllFromOverview.svg" ) ); - mActionToggleFullScreen->setIcon( QgsApplication::getThemeIcon( "/mActionToggleFullScreen.png" ) ); - mActionProjectProperties->setIcon( QgsApplication::getThemeIcon( "/mActionProjectProperties.png" ) ); - mActionManagePlugins->setIcon( QgsApplication::getThemeIcon( "/mActionShowPluginManager.svg" ) ); - mActionShowPythonDialog->setIcon( QgsApplication::getThemeIcon( "console/iconRunConsole.png" ) ); - mActionCheckQgisVersion->setIcon( QgsApplication::getThemeIcon( "/mActionCheckQgisVersion.png" ) ); - mActionOptions->setIcon( QgsApplication::getThemeIcon( "/mActionOptions.svg" ) ); - mActionConfigureShortcuts->setIcon( QgsApplication::getThemeIcon( "/mActionOptions.svg" ) ); - mActionCustomization->setIcon( QgsApplication::getThemeIcon( "/mActionOptions.svg" ) ); - mActionHelpContents->setIcon( QgsApplication::getThemeIcon( "/mActionHelpContents.svg" ) ); - mActionLocalHistogramStretch->setIcon( QgsApplication::getThemeIcon( "/mActionLocalHistogramStretch.svg" ) ); - mActionFullHistogramStretch->setIcon( QgsApplication::getThemeIcon( "/mActionFullHistogramStretch.svg" ) ); - mActionIncreaseBrightness->setIcon( QgsApplication::getThemeIcon( "/mActionIncreaseBrightness.svg" ) ); - mActionDecreaseBrightness->setIcon( QgsApplication::getThemeIcon( "/mActionDecreaseBrightness.svg" ) ); - mActionIncreaseContrast->setIcon( QgsApplication::getThemeIcon( "/mActionIncreaseContrast.svg" ) ); - mActionDecreaseContrast->setIcon( QgsApplication::getThemeIcon( "/mActionDecreaseContrast.svg" ) ); - mActionZoomActualSize->setIcon( QgsApplication::getThemeIcon( "/mActionZoomNative.png" ) ); - mActionQgisHomePage->setIcon( QgsApplication::getThemeIcon( "/mActionQgisHomePage.png" ) ); - mActionAbout->setIcon( QgsApplication::getThemeIcon( "/mActionHelpAbout.png" ) ); - mActionSponsors->setIcon( QgsApplication::getThemeIcon( "/mActionHelpSponsors.png" ) ); - mActionDraw->setIcon( QgsApplication::getThemeIcon( "/mActionDraw.svg" ) ); - mActionToggleEditing->setIcon( QgsApplication::getThemeIcon( "/mActionToggleEditing.svg" ) ); - mActionSaveLayerEdits->setIcon( QgsApplication::getThemeIcon( "/mActionSaveAllEdits.svg" ) ); - mActionAllEdits->setIcon( QgsApplication::getThemeIcon( "/mActionAllEdits.svg" ) ); - mActionSaveEdits->setIcon( QgsApplication::getThemeIcon( "/mActionSaveEdits.svg" ) ); - mActionSaveAllEdits->setIcon( QgsApplication::getThemeIcon( "/mActionSaveAllEdits.svg" ) ); - mActionRollbackEdits->setIcon( QgsApplication::getThemeIcon( "/mActionRollbackEdits.svg" ) ); - mActionRollbackAllEdits->setIcon( QgsApplication::getThemeIcon( "/mActionRollbackAllEdits.svg" ) ); - mActionCancelEdits->setIcon( QgsApplication::getThemeIcon( "/mActionCancelEdits.svg" ) ); - mActionCancelAllEdits->setIcon( QgsApplication::getThemeIcon( "/mActionCancelAllEdits.svg" ) ); - mActionCutFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionEditCut.svg" ) ); - mActionCopyFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionEditCopy.svg" ) ); - mActionPasteFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionEditPaste.svg" ) ); - mActionAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionCapturePoint.svg" ) ); - mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( "/mActionMoveFeaturePoint.svg" ) ); - mActionRotateFeature->setIcon( QgsApplication::getThemeIcon( "/mActionRotateFeature.svg" ) ); - mActionReshapeFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionReshape.svg" ) ); - mActionSplitFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionSplitFeatures.svg" ) ); - mActionSplitParts->setIcon( QgsApplication::getThemeIcon( "/mActionSplitParts.svg" ) ); - mActionDeleteSelected->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteSelected.svg" ) ); - mActionNodeTool->setIcon( QgsApplication::getThemeIcon( "/mActionNodeTool.svg" ) ); - mActionSimplifyFeature->setIcon( QgsApplication::getThemeIcon( "/mActionSimplify.svg" ) ); - mActionUndo->setIcon( QgsApplication::getThemeIcon( "/mActionUndo.svg" ) ); - mActionRedo->setIcon( QgsApplication::getThemeIcon( "/mActionRedo.svg" ) ); - mActionAddRing->setIcon( QgsApplication::getThemeIcon( "/mActionAddRing.svg" ) ); - mActionFillRing->setIcon( QgsApplication::getThemeIcon( "/mActionFillRing.svg" ) ); - mActionAddPart->setIcon( QgsApplication::getThemeIcon( "/mActionAddPart.svg" ) ); - mActionDeleteRing->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteRing.svg" ) ); - mActionDeletePart->setIcon( QgsApplication::getThemeIcon( "/mActionDeletePart.svg" ) ); - mActionMergeFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionMergeFeatures.svg" ) ); - mActionOffsetCurve->setIcon( QgsApplication::getThemeIcon( "/mActionOffsetCurve.svg" ) ); - mActionMergeFeatureAttributes->setIcon( QgsApplication::getThemeIcon( "/mActionMergeFeatureAttributes.svg" ) ); - mActionRotatePointSymbols->setIcon( QgsApplication::getThemeIcon( "mActionRotatePointSymbols.svg" ) ); - mActionOffsetPointSymbol->setIcon( QgsApplication::getThemeIcon( "mActionOffsetPointSymbols.svg" ) ); - mActionZoomIn->setIcon( QgsApplication::getThemeIcon( "/mActionZoomIn.svg" ) ); - mActionZoomOut->setIcon( QgsApplication::getThemeIcon( "/mActionZoomOut.svg" ) ); - mActionZoomFullExtent->setIcon( QgsApplication::getThemeIcon( "/mActionZoomFullExtent.svg" ) ); - mActionZoomToSelected->setIcon( QgsApplication::getThemeIcon( "/mActionZoomToSelected.svg" ) ); - mActionShowRasterCalculator->setIcon( QgsApplication::getThemeIcon( "/mActionShowRasterCalculator.png" ) ); + mActionRemoveLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemoveLayer.svg" ) ) ); + mActionDuplicateLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDuplicateLayer.svg" ) ) ); + mActionSetLayerCRS->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSetLayerCRS.png" ) ) ); + mActionSetProjectCRSFromLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSetProjectCRSFromLayer.png" ) ) ); + mActionNewVectorLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewVectorLayer.svg" ) ) ); + mActionNewMemoryLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCreateMemory.svg" ) ) ); + mActionAddAllToOverview->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddAllToOverview.svg" ) ) ); + mActionHideAllLayers->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHideAllLayers.svg" ) ) ); + mActionShowAllLayers->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowAllLayers.svg" ) ) ); + mActionHideSelectedLayers->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHideSelectedLayers.png" ) ) ); + mActionShowSelectedLayers->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowSelectedLayers.png" ) ) ); + mActionRemoveAllFromOverview->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemoveAllFromOverview.svg" ) ) ); + mActionToggleFullScreen->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleFullScreen.png" ) ) ); + mActionProjectProperties->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionProjectProperties.png" ) ) ); + mActionManagePlugins->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowPluginManager.svg" ) ) ); + mActionShowPythonDialog->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "console/iconRunConsole.png" ) ) ); + mActionCheckQgisVersion->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCheckQgisVersion.png" ) ) ); + mActionOptions->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOptions.svg" ) ) ); + mActionConfigureShortcuts->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOptions.svg" ) ) ); + mActionCustomization->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOptions.svg" ) ) ); + mActionHelpContents->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHelpContents.svg" ) ) ); + mActionLocalHistogramStretch->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionLocalHistogramStretch.svg" ) ) ); + mActionFullHistogramStretch->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFullHistogramStretch.svg" ) ) ); + mActionIncreaseBrightness->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionIncreaseBrightness.svg" ) ) ); + mActionDecreaseBrightness->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDecreaseBrightness.svg" ) ) ); + mActionIncreaseContrast->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionIncreaseContrast.svg" ) ) ); + mActionDecreaseContrast->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDecreaseContrast.svg" ) ) ); + mActionZoomActualSize->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomNative.png" ) ) ); + mActionQgisHomePage->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionQgisHomePage.png" ) ) ); + mActionAbout->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHelpAbout.png" ) ) ); + mActionSponsors->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHelpSponsors.png" ) ) ); + mActionDraw->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDraw.svg" ) ) ); + mActionToggleEditing->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) ); + mActionSaveLayerEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveAllEdits.svg" ) ) ); + mActionAllEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAllEdits.svg" ) ) ); + mActionSaveEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveEdits.svg" ) ) ); + mActionSaveAllEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveAllEdits.svg" ) ) ); + mActionRollbackEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRollbackEdits.svg" ) ) ); + mActionRollbackAllEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRollbackAllEdits.svg" ) ) ); + mActionCancelEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCancelEdits.svg" ) ) ); + mActionCancelAllEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCancelAllEdits.svg" ) ) ); + mActionCutFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditCut.svg" ) ) ); + mActionCopyFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditCopy.svg" ) ) ); + mActionPasteFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditPaste.svg" ) ) ); + mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePoint.svg" ) ) ); + mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeaturePoint.svg" ) ) ); + mActionRotateFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRotateFeature.svg" ) ) ); + mActionReshapeFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionReshape.svg" ) ) ); + mActionSplitFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSplitFeatures.svg" ) ) ); + mActionSplitParts->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSplitParts.svg" ) ) ); + mActionDeleteSelected->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteSelected.svg" ) ) ); + mActionNodeTool->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNodeTool.svg" ) ) ); + mActionSimplifyFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSimplify.svg" ) ) ); + mActionUndo->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionUndo.svg" ) ) ); + mActionRedo->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRedo.svg" ) ) ); + mActionAddRing->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddRing.svg" ) ) ); + mActionFillRing->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFillRing.svg" ) ) ); + mActionAddPart->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddPart.svg" ) ) ); + mActionDeleteRing->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteRing.svg" ) ) ); + mActionDeletePart->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeletePart.svg" ) ) ); + mActionMergeFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMergeFeatures.svg" ) ) ); + mActionOffsetCurve->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOffsetCurve.svg" ) ) ); + mActionMergeFeatureAttributes->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMergeFeatureAttributes.svg" ) ) ); + mActionRotatePointSymbols->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionRotatePointSymbols.svg" ) ) ); + mActionOffsetPointSymbol->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionOffsetPointSymbols.svg" ) ) ); + mActionZoomIn->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomIn.svg" ) ) ); + mActionZoomOut->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomOut.svg" ) ) ); + mActionZoomFullExtent->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomFullExtent.svg" ) ) ); + mActionZoomToSelected->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomToSelected.svg" ) ) ); + mActionShowRasterCalculator->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowRasterCalculator.png" ) ) ); #ifdef HAVE_TOUCH mActionTouch->setIcon( QgsApplication::getThemeIcon( "/mActionTouch.svg" ) ); #endif - mActionPan->setIcon( QgsApplication::getThemeIcon( "/mActionPan.svg" ) ); - mActionPanToSelected->setIcon( QgsApplication::getThemeIcon( "/mActionPanToSelected.svg" ) ); - mActionZoomLast->setIcon( QgsApplication::getThemeIcon( "/mActionZoomLast.svg" ) ); - mActionZoomNext->setIcon( QgsApplication::getThemeIcon( "/mActionZoomNext.svg" ) ); - mActionZoomToLayer->setIcon( QgsApplication::getThemeIcon( "/mActionZoomToLayer.svg" ) ); - mActionZoomActualSize->setIcon( QgsApplication::getThemeIcon( "/mActionZoomActual.svg" ) ); - mActionIdentify->setIcon( QgsApplication::getThemeIcon( "/mActionIdentify.svg" ) ); - mActionFeatureAction->setIcon( QgsApplication::getThemeIcon( "/mAction.svg" ) ); - mActionSelectFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionSelectRectangle.svg" ) ); - mActionSelectPolygon->setIcon( QgsApplication::getThemeIcon( "/mActionSelectPolygon.svg" ) ); - mActionSelectFreehand->setIcon( QgsApplication::getThemeIcon( "/mActionSelectFreehand.svg" ) ); - mActionSelectRadius->setIcon( QgsApplication::getThemeIcon( "/mActionSelectRadius.svg" ) ); - mActionDeselectAll->setIcon( QgsApplication::getThemeIcon( "/mActionDeselectAll.svg" ) ); - mActionSelectAll->setIcon( QgsApplication::getThemeIcon( "/mActionSelectAll.svg" ) ); - mActionInvertSelection->setIcon( QgsApplication::getThemeIcon( "/mActionInvertSelection.svg" ) ); - mActionSelectByExpression->setIcon( QgsApplication::getThemeIcon( "/mIconExpressionSelect.svg" ) ); - mActionSelectByForm->setIcon( QgsApplication::getThemeIcon( "/mIconFormSelect.svg" ) ); - mActionOpenTable->setIcon( QgsApplication::getThemeIcon( "/mActionOpenTable.svg" ) ); - mActionOpenFieldCalc->setIcon( QgsApplication::getThemeIcon( "/mActionCalculateField.svg" ) ); - mActionMeasure->setIcon( QgsApplication::getThemeIcon( "/mActionMeasure.svg" ) ); - mActionMeasureArea->setIcon( QgsApplication::getThemeIcon( "/mActionMeasureArea.svg" ) ); - mActionMeasureAngle->setIcon( QgsApplication::getThemeIcon( "/mActionMeasureAngle.svg" ) ); - mActionMapTips->setIcon( QgsApplication::getThemeIcon( "/mActionMapTips.svg" ) ); - mActionShowBookmarks->setIcon( QgsApplication::getThemeIcon( "/mActionShowBookmarks.svg" ) ); - mActionNewBookmark->setIcon( QgsApplication::getThemeIcon( "/mActionNewBookmark.svg" ) ); - mActionCustomProjection->setIcon( QgsApplication::getThemeIcon( "/mActionCustomProjection.svg" ) ); - mActionAddWmsLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddWmsLayer.svg" ) ); - mActionAddWcsLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddWcsLayer.svg" ) ); - mActionAddWfsLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddWfsLayer.svg" ) ); - mActionAddAfsLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddAfsLayer.svg" ) ); - mActionAddAmsLayer->setIcon( QgsApplication::getThemeIcon( "/mActionAddAmsLayer.svg" ) ); - mActionAddToOverview->setIcon( QgsApplication::getThemeIcon( "/mActionInOverview.svg" ) ); - mActionAnnotation->setIcon( QgsApplication::getThemeIcon( "/mActionAnnotation.svg" ) ); - mActionFormAnnotation->setIcon( QgsApplication::getThemeIcon( "/mActionFormAnnotation.svg" ) ); - mActionHtmlAnnotation->setIcon( QgsApplication::getThemeIcon( "/mActionHtmlAnnotation.svg" ) ); - mActionSvgAnnotation->setIcon( QgsApplication::getThemeIcon( "/mActionSvgAnnotation.svg" ) ); - mActionTextAnnotation->setIcon( QgsApplication::getThemeIcon( "/mActionTextAnnotation.svg" ) ); - mActionLabeling->setIcon( QgsApplication::getThemeIcon( "/mActionLabeling.svg" ) ); - mActionShowPinnedLabels->setIcon( QgsApplication::getThemeIcon( "/mActionShowPinnedLabels.svg" ) ); - mActionPinLabels->setIcon( QgsApplication::getThemeIcon( "/mActionPinLabels.svg" ) ); - mActionShowHideLabels->setIcon( QgsApplication::getThemeIcon( "/mActionShowHideLabels.svg" ) ); - mActionMoveLabel->setIcon( QgsApplication::getThemeIcon( "/mActionMoveLabel.svg" ) ); - mActionRotateLabel->setIcon( QgsApplication::getThemeIcon( "/mActionRotateLabel.svg" ) ); - mActionChangeLabelProperties->setIcon( QgsApplication::getThemeIcon( "/mActionChangeLabelProperties.svg" ) ); - mActionDiagramProperties->setIcon( QgsApplication::getThemeIcon( "/mActionDiagramProperties.svg" ) ); - mActionDecorationCopyright->setIcon( QgsApplication::getThemeIcon( "/copyright_label.png" ) ); - mActionDecorationNorthArrow->setIcon( QgsApplication::getThemeIcon( "/north_arrow.png" ) ); - mActionDecorationScaleBar->setIcon( QgsApplication::getThemeIcon( "/scale_bar.png" ) ); - mActionDecorationGrid->setIcon( QgsApplication::getThemeIcon( "/transformed.svg" ) ); + mActionPan->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPan.svg" ) ) ); + mActionPanToSelected->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPanToSelected.svg" ) ) ); + mActionZoomLast->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomLast.svg" ) ) ); + mActionZoomNext->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomNext.svg" ) ) ); + mActionZoomToLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomToLayer.svg" ) ) ); + mActionZoomActualSize->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomActual.svg" ) ) ); + mActionIdentify->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionIdentify.svg" ) ) ); + mActionFeatureAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ) ); + mActionSelectFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectRectangle.svg" ) ) ); + mActionSelectPolygon->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectPolygon.svg" ) ) ); + mActionSelectFreehand->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectFreehand.svg" ) ) ); + mActionSelectRadius->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectRadius.svg" ) ) ); + mActionDeselectAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeselectAll.svg" ) ) ); + mActionSelectAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectAll.svg" ) ) ); + mActionInvertSelection->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionInvertSelection.svg" ) ) ); + mActionSelectByExpression->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpressionSelect.svg" ) ) ); + mActionSelectByForm->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFormSelect.svg" ) ) ); + mActionOpenTable->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOpenTable.svg" ) ) ); + mActionOpenFieldCalc->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCalculateField.svg" ) ) ); + mActionMeasure->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMeasure.svg" ) ) ); + mActionMeasureArea->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMeasureArea.svg" ) ) ); + mActionMeasureAngle->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMeasureAngle.svg" ) ) ); + mActionMapTips->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMapTips.svg" ) ) ); + mActionShowBookmarks->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowBookmarks.svg" ) ) ); + mActionNewBookmark->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewBookmark.svg" ) ) ); + mActionCustomProjection->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCustomProjection.svg" ) ) ); + mActionAddWmsLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddWmsLayer.svg" ) ) ); + mActionAddWcsLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddWcsLayer.svg" ) ) ); + mActionAddWfsLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddWfsLayer.svg" ) ) ); + mActionAddAfsLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddAfsLayer.svg" ) ) ); + mActionAddAmsLayer->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddAmsLayer.svg" ) ) ); + mActionAddToOverview->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionInOverview.svg" ) ) ); + mActionAnnotation->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAnnotation.svg" ) ) ); + mActionFormAnnotation->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFormAnnotation.svg" ) ) ); + mActionHtmlAnnotation->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHtmlAnnotation.svg" ) ) ); + mActionSvgAnnotation->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSvgAnnotation.svg" ) ) ); + mActionTextAnnotation->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionTextAnnotation.svg" ) ) ); + mActionLabeling->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionLabeling.svg" ) ) ); + mActionShowPinnedLabels->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowPinnedLabels.svg" ) ) ); + mActionPinLabels->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPinLabels.svg" ) ) ); + mActionShowHideLabels->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowHideLabels.svg" ) ) ); + mActionMoveLabel->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveLabel.svg" ) ) ); + mActionRotateLabel->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRotateLabel.svg" ) ) ); + mActionChangeLabelProperties->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionChangeLabelProperties.svg" ) ) ); + mActionDiagramProperties->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDiagramProperties.svg" ) ) ); + mActionDecorationCopyright->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/copyright_label.png" ) ) ); + mActionDecorationNorthArrow->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/north_arrow.png" ) ) ); + mActionDecorationScaleBar->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/scale_bar.png" ) ) ); + mActionDecorationGrid->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/transformed.svg" ) ) ); //change themes of all composers QSet::const_iterator composerIt = mPrintComposers.constBegin(); @@ -2932,9 +2932,9 @@ void QgisApp::createOverview() //set canvas color to default QSettings settings; - int red = settings.value( "/qgis/default_canvas_color_red", 255 ).toInt(); - int green = settings.value( "/qgis/default_canvas_color_green", 255 ).toInt(); - int blue = settings.value( "/qgis/default_canvas_color_blue", 255 ).toInt(); + int red = settings.value( QStringLiteral( "/qgis/default_canvas_color_red" ), 255 ).toInt(); + int green = settings.value( QStringLiteral( "/qgis/default_canvas_color_green" ), 255 ).toInt(); + int blue = settings.value( QStringLiteral( "/qgis/default_canvas_color_blue" ), 255 ).toInt(); mOverviewCanvas->setBackgroundColor( QColor( red, green, blue ) ); mOverviewCanvas->setWhatsThis( tr( "Map overview canvas. This canvas can be used to display a locator map that shows the current extent of the map canvas. The current extent is shown as a red rectangle. Any layer on the map can be added to the overview canvas." ) ); @@ -2945,7 +2945,7 @@ void QgisApp::createOverview() // myOverviewLayout->addWidget(overviewCanvas); // overviewFrame->setLayout(myOverviewLayout); mOverviewDock = new QgsDockWidget( tr( "Overview Panel" ), this ); - mOverviewDock->setObjectName( "Overview" ); + mOverviewDock->setObjectName( QStringLiteral( "Overview" ) ); mOverviewDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); mOverviewDock->setWidget( mOverviewCanvas ); addDockWidget( Qt::LeftDockWidgetArea, mOverviewDock ); @@ -2957,16 +2957,16 @@ void QgisApp::createOverview() // moved here to set anti aliasing to both map canvas and overview QSettings mySettings; // Anti Aliasing enabled by default as of QGIS 1.7 - mMapCanvas->enableAntiAliasing( mySettings.value( "/qgis/enable_anti_aliasing", true ).toBool() ); + mMapCanvas->enableAntiAliasing( mySettings.value( QStringLiteral( "/qgis/enable_anti_aliasing" ), true ).toBool() ); - double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble(); + double zoomFactor = mySettings.value( QStringLiteral( "/qgis/zoom_factor" ), 2 ).toDouble(); mMapCanvas->setWheelFactor( zoomFactor ); - mMapCanvas->setCachingEnabled( mySettings.value( "/qgis/enable_render_caching", true ).toBool() ); + mMapCanvas->setCachingEnabled( mySettings.value( QStringLiteral( "/qgis/enable_render_caching" ), true ).toBool() ); - mMapCanvas->setParallelRenderingEnabled( mySettings.value( "/qgis/parallel_rendering", true ).toBool() ); + mMapCanvas->setParallelRenderingEnabled( mySettings.value( QStringLiteral( "/qgis/parallel_rendering" ), true ).toBool() ); - mMapCanvas->setMapUpdateInterval( mySettings.value( "/qgis/map_update_interval", 250 ).toInt() ); + mMapCanvas->setMapUpdateInterval( mySettings.value( QStringLiteral( "/qgis/map_update_interval" ), 250 ).toInt() ); } void QgisApp::addDockWidget( Qt::DockWidgetArea theArea, QDockWidget* thepDockWidget ) @@ -3036,11 +3036,11 @@ void QgisApp::toggleLogMessageIcon( bool hasLogMessage ) { if ( hasLogMessage && !mLogDock->isVisible() ) { - mMessageButton->setIcon( QgsApplication::getThemeIcon( "/mMessageLog.svg" ) ); + mMessageButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mMessageLog.svg" ) ) ); } else { - mMessageButton->setIcon( QgsApplication::getThemeIcon( "/mMessageLogRead.svg" ) ); + mMessageButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mMessageLogRead.svg" ) ) ); } } @@ -3060,7 +3060,7 @@ void QgisApp::initLayerTreeView() mLayerTreeView->setWhatsThis( tr( "Map legend that displays all the layers currently on the map canvas. Click on the check box to turn a layer on or off. Double click on a layer in the legend to customize its appearance and set other properties." ) ); mLayerTreeDock = new QgsDockWidget( tr( "Layers Panel" ), this ); - mLayerTreeDock->setObjectName( "Layers" ); + mLayerTreeDock->setObjectName( QStringLiteral( "Layers" ) ); mLayerTreeDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); QgsLayerTreeModel* model = new QgsLayerTreeModel( QgsProject::instance()->layerTreeRoot(), this ); @@ -3087,7 +3087,7 @@ void QgisApp::initLayerTreeView() // add group action QAction* actionAddGroup = new QAction( tr( "Add Group" ), this ); - actionAddGroup->setIcon( QgsApplication::getThemeIcon( "/mActionAddGroup.svg" ) ); + actionAddGroup->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddGroup.svg" ) ) ); actionAddGroup->setToolTip( tr( "Add Group" ) ); connect( actionAddGroup, SIGNAL( triggered( bool ) ), mLayerTreeView->defaultActions(), SLOT( addGroup() ) ); @@ -3095,7 +3095,7 @@ void QgisApp::initLayerTreeView() QToolButton* btnVisibilityPresets = new QToolButton; btnVisibilityPresets->setAutoRaise( true ); btnVisibilityPresets->setToolTip( tr( "Manage Map Themes" ) ); - btnVisibilityPresets->setIcon( QgsApplication::getThemeIcon( "/mActionShowAllLayers.svg" ) ); + btnVisibilityPresets->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowAllLayers.svg" ) ) ); btnVisibilityPresets->setPopupMode( QToolButton::InstantPopup ); btnVisibilityPresets->setMenu( QgsMapThemes::instance()->menu() ); @@ -3103,7 +3103,7 @@ void QgisApp::initLayerTreeView() mActionFilterLegend = new QAction( tr( "Filter Legend By Map Content" ), this ); mActionFilterLegend->setCheckable( true ); mActionFilterLegend->setToolTip( tr( "Filter Legend By Map Content" ) ); - mActionFilterLegend->setIcon( QgsApplication::getThemeIcon( "/mActionFilter2.svg" ) ); + mActionFilterLegend->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFilter2.svg" ) ) ); connect( mActionFilterLegend, SIGNAL( toggled( bool ) ), this, SLOT( updateFilterLegend() ) ); mLegendExpressionFilterButton = new QgsLegendFilterButton( this ); @@ -3113,17 +3113,17 @@ void QgisApp::initLayerTreeView() mActionStyleDock = new QAction( tr( "Layer Styling" ), this ); mActionStyleDock->setCheckable( true ); mActionStyleDock->setToolTip( tr( "Open the layer styling dock" ) ); - mActionStyleDock->setShortcut( QString( "F7" ) ); - mActionStyleDock->setIcon( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ) ); + mActionStyleDock->setShortcut( QStringLiteral( "F7" ) ); + mActionStyleDock->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/symbology.svg" ) ) ); connect( mActionStyleDock, SIGNAL( toggled( bool ) ), this, SLOT( mapStyleDock( bool ) ) ); // expand / collapse tool buttons QAction* actionExpandAll = new QAction( tr( "Expand All" ), this ); - actionExpandAll->setIcon( QgsApplication::getThemeIcon( "/mActionExpandTree.svg" ) ); + actionExpandAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionExpandTree.svg" ) ) ); actionExpandAll->setToolTip( tr( "Expand All" ) ); connect( actionExpandAll, SIGNAL( triggered( bool ) ), mLayerTreeView, SLOT( expandAll() ) ); QAction* actionCollapseAll = new QAction( tr( "Collapse All" ), this ); - actionCollapseAll->setIcon( QgsApplication::getThemeIcon( "/mActionCollapseTree.svg" ) ); + actionCollapseAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCollapseTree.svg" ) ) ); actionCollapseAll->setToolTip( tr( "Collapse All" ) ); connect( actionCollapseAll, SIGNAL( triggered( bool ) ), mLayerTreeView, SLOT( collapseAll() ) ); @@ -3157,15 +3157,15 @@ void QgisApp::initLayerTreeView() connect( QgsProject::instance(), SIGNAL( writeProject( QDomDocument& ) ), mLayerTreeCanvasBridge, SLOT( writeProject( QDomDocument& ) ) ); connect( QgsProject::instance(), SIGNAL( readProject( QDomDocument ) ), mLayerTreeCanvasBridge, SLOT( readProject( QDomDocument ) ) ); - bool otfTransformAutoEnable = QSettings().value( "/Projections/otfTransformAutoEnable", true ).toBool(); + bool otfTransformAutoEnable = QSettings().value( QStringLiteral( "/Projections/otfTransformAutoEnable" ), true ).toBool(); mLayerTreeCanvasBridge->setAutoEnableCrsTransform( otfTransformAutoEnable ); mMapLayerOrder = new QgsCustomLayerOrderWidget( mLayerTreeCanvasBridge, this ); - mMapLayerOrder->setObjectName( "theMapLayerOrder" ); + mMapLayerOrder->setObjectName( QStringLiteral( "theMapLayerOrder" ) ); mMapLayerOrder->setWhatsThis( tr( "Map layer list that displays all layers in drawing order." ) ); mLayerOrderDock = new QgsDockWidget( tr( "Layer Order Panel" ), this ); - mLayerOrderDock->setObjectName( "LayerOrder" ); + mLayerOrderDock->setObjectName( QStringLiteral( "LayerOrder" ) ); mLayerOrderDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); mLayerOrderDock->setWidget( mMapLayerOrder ); @@ -3180,11 +3180,11 @@ void QgisApp::setupLayerTreeViewFromSettings() QSettings s; QgsLayerTreeModel* model = mLayerTreeView->layerTreeModel(); - model->setFlag( QgsLayerTreeModel::ShowRasterPreviewIcon, s.value( "/qgis/createRasterLegendIcons", false ).toBool() ); + model->setFlag( QgsLayerTreeModel::ShowRasterPreviewIcon, s.value( QStringLiteral( "/qgis/createRasterLegendIcons" ), false ).toBool() ); QFont fontLayer, fontGroup; - fontLayer.setBold( s.value( "/qgis/legendLayersBold", true ).toBool() ); - fontGroup.setBold( s.value( "/qgis/legendGroupsBold", false ).toBool() ); + fontLayer.setBold( s.value( QStringLiteral( "/qgis/legendLayersBold" ), true ).toBool() ); + fontGroup.setBold( s.value( QStringLiteral( "/qgis/legendGroupsBold" ), false ).toBool() ); model->setLayerTreeNodeFont( QgsLayerTreeNode::NodeLayer, fontLayer ); model->setLayerTreeNodeFont( QgsLayerTreeNode::NodeGroup, fontGroup ); } @@ -3295,7 +3295,7 @@ void QgisApp::updateRecentProjectPaths() Q_FOREACH ( const QgsWelcomePageItemsModel::RecentProjectData& recentProject, mRecentProjects ) { - QAction* action = mRecentProjectsMenu->addAction( QString( "%1 (%2)" ).arg( recentProject.title != recentProject.path ? recentProject.title : QFileInfo( recentProject.path ).baseName(), recentProject.path ) ); + QAction* action = mRecentProjectsMenu->addAction( QStringLiteral( "%1 (%2)" ).arg( recentProject.title != recentProject.path ? recentProject.title : QFileInfo( recentProject.path ).baseName(), recentProject.path ) ); action->setEnabled( QFile::exists(( recentProject.path ) ) ); action->setData( recentProject.path ); } @@ -3323,8 +3323,8 @@ void QgisApp::saveRecentProjectPath( const QString& projectPath, bool savePrevie { // Generate a unique file name QString fileName( QCryptographicHash::hash(( projectData.path.toUtf8() ), QCryptographicHash::Md5 ).toHex() ); - QString previewDir = QString( "%1/previewImages" ).arg( QgsApplication::qgisSettingsDirPath() ); - projectData.previewImagePath = QString( "%1/%2.png" ).arg( previewDir, fileName ); + QString previewDir = QStringLiteral( "%1/previewImages" ).arg( QgsApplication::qgisSettingsDirPath() ); + projectData.previewImagePath = QStringLiteral( "%1/%2.png" ).arg( previewDir, fileName ); QDir().mkdir( previewDir ); // Render the map canvas @@ -3360,18 +3360,18 @@ void QgisApp::saveRecentProjectPath( const QString& projectPath, bool savePrevie QFile( mRecentProjects.takeLast().previewImagePath ).remove(); } - settings.remove( "/UI/recentProjects" ); + settings.remove( QStringLiteral( "/UI/recentProjects" ) ); int idx = 0; // Persist the list Q_FOREACH ( const QgsWelcomePageItemsModel::RecentProjectData& recentProject, mRecentProjects ) { ++idx; - settings.beginGroup( QString( "/UI/recentProjects/%1" ).arg( idx ) ); - settings.setValue( "title", recentProject.title ); - settings.setValue( "path", recentProject.path ); - settings.setValue( "previewImage", recentProject.previewImagePath ); - settings.setValue( "crs", recentProject.crs ); + settings.beginGroup( QStringLiteral( "/UI/recentProjects/%1" ).arg( idx ) ); + settings.setValue( QStringLiteral( "title" ), recentProject.title ); + settings.setValue( QStringLiteral( "path" ), recentProject.path ); + settings.setValue( QStringLiteral( "previewImage" ), recentProject.previewImagePath ); + settings.setValue( QStringLiteral( "crs" ), recentProject.crs ); settings.endGroup(); } @@ -3385,10 +3385,10 @@ void QgisApp::updateProjectFromTemplates() { // get list of project files in template dir QSettings settings; - QString templateDirName = settings.value( "/qgis/projectTemplateDir", + QString templateDirName = settings.value( QStringLiteral( "/qgis/projectTemplateDir" ), QgsApplication::qgisSettingsDirPath() + "project_templates" ).toString(); QDir templateDir( templateDirName ); - QStringList filters( "*.qgs" ); + QStringList filters( QStringLiteral( "*.qgs" ) ); templateDir.setNameFilters( filters ); QStringList templateFiles = templateDir.entryList( filters ); @@ -3402,7 +3402,7 @@ void QgisApp::updateProjectFromTemplates() } // add entry, which loads a blank template (regardless of "default template") - if ( settings.value( "/qgis/newProjectDefault", QVariant( false ) ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/newProjectDefault" ), QVariant( false ) ).toBool() ) mProjectFromTemplateMenu->addAction( tr( "< Blank >" ) ); } // QgisApp::updateProjectFromTemplates @@ -3412,10 +3412,10 @@ void QgisApp::saveWindowState() // store window and toolbar positions QSettings settings; // store the toolbar/dock widget settings using Qt4 settings API - settings.setValue( "/UI/state", saveState() ); + settings.setValue( QStringLiteral( "/UI/state" ), saveState() ); // store window geometry - settings.setValue( "/UI/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/UI/geometry" ), saveGeometry() ); QgsPluginRegistry::instance()->unloadAll(); } @@ -3427,13 +3427,13 @@ void QgisApp::restoreWindowState() // restore the toolbar and dock widgets positions using Qt4 settings API QSettings settings; - if ( !restoreState( settings.value( "/UI/state", QByteArray::fromRawData( reinterpret_cast< const char * >( defaultUIstate ), sizeof defaultUIstate ) ).toByteArray() ) ) + if ( !restoreState( settings.value( QStringLiteral( "/UI/state" ), QByteArray::fromRawData( reinterpret_cast< const char * >( defaultUIstate ), sizeof defaultUIstate ) ).toByteArray() ) ) { QgsDebugMsg( "restore of UI state failed" ); } // restore window geometry - if ( !restoreGeometry( settings.value( "/UI/geometry", QByteArray::fromRawData( reinterpret_cast< const char * >( defaultUIgeometry ), sizeof defaultUIgeometry ) ).toByteArray() ) ) + if ( !restoreGeometry( settings.value( QStringLiteral( "/UI/geometry" ), QByteArray::fromRawData( reinterpret_cast< const char * >( defaultUIgeometry ), sizeof defaultUIgeometry ) ).toByteArray() ) ) { QgsDebugMsg( "restore of UI geometry failed" ); } @@ -3455,38 +3455,38 @@ void QgisApp::about() { QApplication::setOverrideCursor( Qt::WaitCursor ); abt = new QgsAbout( this ); - QString versionString = "

                                                                                                                                                                                    "; + QString versionString = QStringLiteral( "
                                                                                                                                                                                    " ); - versionString += ""; + versionString += QLatin1String( "" ); versionString += "" ) + versionString += tr( "QGIS code branch" ) + QStringLiteral( "" ) .arg( Qgis::QGIS_VERSION_INT / 10000 ).arg( Qgis::QGIS_VERSION_INT / 100 % 100 ); } else { - versionString += tr( "QGIS code revision" ) + QString( "" ).arg( Qgis::QGIS_DEV_VERSION ); + versionString += tr( "QGIS code revision" ) + QStringLiteral( "" ).arg( Qgis::QGIS_DEV_VERSION ); } - versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; versionString += ""; - versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; versionString += ""; - versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; versionString += ""; - versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; + versionString += QLatin1String( "" ); - versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; versionString += ""; - versionString += ""; + versionString += QLatin1String( "" ); versionString += ""; @@ -3513,7 +3513,7 @@ void QgisApp::about() versionString += ""; #endif - versionString += "
                                                                                                                                                                                    " + tr( "QGIS version" ) + "" + Qgis::QGIS_VERSION + ""; - if ( QString( Qgis::QGIS_DEV_VERSION ) == "exported" ) + if ( QString( Qgis::QGIS_DEV_VERSION ) == QLatin1String( "exported" ) ) { - versionString += tr( "QGIS code branch" ) + QString( "Release %1.%2Release %1.%2%1%1
                                                                                                                                                                                    " + tr( "Compiled against Qt" ) + "" + QT_VERSION_STR + "" + tr( "Running against Qt" ) + "" + qVersion() + "
                                                                                                                                                                                    " + tr( "Compiled against GDAL/OGR" ) + "" + GDAL_RELEASE_NAME + "" + tr( "Running against GDAL/OGR" ) + "" + GDALVersionInfo( "RELEASE_NAME" ) + "
                                                                                                                                                                                    " + tr( "Compiled against GEOS" ) + "" + GEOS_CAPI_VERSION + "" + tr( "Running against GEOS" ) + "" + GEOSversion() + "
                                                                                                                                                                                    " + tr( "PostgreSQL Client Version" ) + ""; #ifdef HAVE_POSTGRESQL @@ -3494,18 +3494,18 @@ void QgisApp::about() #else versionString += tr( "No support." ); #endif - versionString += "" + tr( "SpatiaLite Version" ) + ""; versionString += spatialite_version(); - versionString += "
                                                                                                                                                                                    " + tr( "QWT Version" ) + "" + QWT_VERSION_STR + "" + tr( "PROJ.4 Version" ) + "" + QString::number( PJ_VERSION ) + "
                                                                                                                                                                                    " + tr( "QScintilla2 Version" ) + "" + QSCINTILLA_VERSION_STR + "" + tr( "This copy of QGIS writes debugging output." ) + "
                                                                                                                                                                                    "; + versionString += QLatin1String( "
                                                                                                                                                                                    " ); abt->setVersion( versionString ); @@ -3526,7 +3526,7 @@ void QgisApp::about() void QgisApp::addLayerDefinition() { - QString path = QFileDialog::getOpenFileName( this, "Add Layer Definition File", QDir::home().path(), "*.qlr" ); + QString path = QFileDialog::getOpenFileName( this, QStringLiteral( "Add Layer Definition File" ), QDir::home().path(), QStringLiteral( "*.qlr" ) ); if ( path.isEmpty() ) return; @@ -3551,7 +3551,7 @@ QString QgisApp::crsAndFormatAdjustedLayerUri( const QString &uri, const QString } // Use the last used image format - QString lastImageEncoding = QSettings().value( "/qgis/lastWmsImageEncoding", "image/png" ).toString(); + QString lastImageEncoding = QSettings().value( QStringLiteral( "/qgis/lastWmsImageEncoding" ), "image/png" ).toString(); Q_FOREACH ( const QString& fmt, supportedFormats ) { if ( fmt == lastImageEncoding ) @@ -3597,7 +3597,7 @@ bool QgisApp::addVectorLayers( const QStringList &theLayerQStringList, const QSt { src = src.trimmed(); QString base; - if ( dataSourceType == "file" ) + if ( dataSourceType == QLatin1String( "file" ) ) { QString srcWithoutLayername( src ); int posPipe = srcWithoutLayername.indexOf( '|' ); @@ -3608,14 +3608,14 @@ bool QgisApp::addVectorLayers( const QStringList &theLayerQStringList, const QSt // if needed prompt for zipitem layers QString vsiPrefix = QgsZipItem::vsiPrefix( src ); - if ( ! src.startsWith( "/vsi", Qt::CaseInsensitive ) && - ( vsiPrefix == "/vsizip/" || vsiPrefix == "/vsitar/" ) ) + if ( ! src.startsWith( QLatin1String( "/vsi" ), Qt::CaseInsensitive ) && + ( vsiPrefix == QLatin1String( "/vsizip/" ) || vsiPrefix == QLatin1String( "/vsitar/" ) ) ) { if ( askUserForZipItemLayers( src ) ) continue; } } - else if ( dataSourceType == "database" ) + else if ( dataSourceType == QLatin1String( "database" ) ) { base = src; } @@ -3629,7 +3629,7 @@ bool QgisApp::addVectorLayers( const QStringList &theLayerQStringList, const QSt // create the layer - QgsVectorLayer *layer = new QgsVectorLayer( src, base, "ogr", false ); + QgsVectorLayer *layer = new QgsVectorLayer( src, base, QStringLiteral( "ogr" ), false ); Q_CHECK_PTR( layer ); if ( ! layer ) @@ -3670,7 +3670,7 @@ bool QgisApp::addVectorLayers( const QStringList &theLayerQStringList, const QSt Q_ASSERT( elements.size() >= 4 ); if ( layer->name() != elements.at( 1 ) ) { - layer->setName( QString( "%1 %2 %3" ).arg( layer->name(), elements.at( 1 ), elements.at( 3 ) ) ); + layer->setName( QStringLiteral( "%1 %2 %3" ).arg( layer->name(), elements.at( 1 ), elements.at( 3 ) ) ); } myList << layer; @@ -3730,12 +3730,12 @@ bool QgisApp::askUserForZipItemLayers( const QString& path ) QVector childItems; QgsZipItem *zipItem = nullptr; QSettings settings; - int promptLayers = settings.value( "/qgis/promptForRasterSublayers", 1 ).toInt(); + int promptLayers = settings.value( QStringLiteral( "/qgis/promptForRasterSublayers" ), 1 ).toInt(); QgsDebugMsg( "askUserForZipItemLayers( " + path + ')' ); // if scanZipBrowser == no: skip to the next file - if ( settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString() == "no" ) + if ( settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString() == QLatin1String( "no" ) ) { return false; } @@ -3768,7 +3768,7 @@ bool QgisApp::askUserForZipItemLayers( const QString& path ) else { // We initialize a selection dialog and display it. - QgsSublayersDialog chooseSublayersDialog( QgsSublayersDialog::Vsifile, "vsi", this ); + QgsSublayersDialog chooseSublayersDialog( QgsSublayersDialog::Vsifile, QStringLiteral( "vsi" ), this ); QgsSublayersDialog::LayerDefinitionList layers; for ( int i = 0; i < zipItem->children().size(); i++ ) @@ -3783,11 +3783,11 @@ bool QgisApp::askUserForZipItemLayers( const QString& path ) QgsSublayersDialog::LayerDefinition def; def.layerId = i; def.layerName = item->name(); - if ( layerItem->providerKey() == "gdal" ) + if ( layerItem->providerKey() == QLatin1String( "gdal" ) ) { def.type = tr( "Raster" ); } - else if ( layerItem->providerKey() == "ogr" ) + else if ( layerItem->providerKey() == QLatin1String( "ogr" ) ) { def.type = tr( "Vector" ); } @@ -3819,14 +3819,14 @@ bool QgisApp::askUserForZipItemLayers( const QString& path ) continue; QgsDebugMsg( QString( "item path=%1 provider=%2" ).arg( item->path(), layerItem->providerKey() ) ); - if ( layerItem->providerKey() == "gdal" ) + if ( layerItem->providerKey() == QLatin1String( "gdal" ) ) { if ( addRasterLayer( item->path(), QFileInfo( item->name() ).completeBaseName() ) ) ok = true; } - else if ( layerItem->providerKey() == "ogr" ) + else if ( layerItem->providerKey() == QLatin1String( "ogr" ) ) { - if ( addVectorLayers( QStringList( item->path() ), "System", "file" ) ) + if ( addVectorLayers( QStringList( item->path() ), QStringLiteral( "System" ), QStringLiteral( "file" ) ) ) ok = true; } } @@ -3849,14 +3849,14 @@ void QgisApp::askUserForGDALSublayers( QgsRasterLayer *layer ) // if promptLayers=Load all, load all sublayers without prompting QSettings settings; - if ( settings.value( "/qgis/promptForRasterSublayers", 1 ).toInt() == 3 ) + if ( settings.value( QStringLiteral( "/qgis/promptForRasterSublayers" ), 1 ).toInt() == 3 ) { loadGDALSublayers( layer->source(), sublayers ); return; } // We initialize a selection dialog and display it. - QgsSublayersDialog chooseSublayersDialog( QgsSublayersDialog::Gdal, "gdal", this ); + QgsSublayersDialog chooseSublayersDialog( QgsSublayersDialog::Gdal, QStringLiteral( "gdal" ), this ); QgsSublayersDialog::LayerDefinitionList layers; QStringList names; @@ -3870,8 +3870,8 @@ void QgisApp::askUserForGDALSublayers( QgsRasterLayer *layer ) QString path = layer->source(); // if netcdf/hdf use all text after filename // for hdf4 it would be best to get description, because the subdataset_index is not very practical - if ( name.startsWith( "netcdf", Qt::CaseInsensitive ) || - name.startsWith( "hdf", Qt::CaseInsensitive ) ) + if ( name.startsWith( QLatin1String( "netcdf" ), Qt::CaseInsensitive ) || + name.startsWith( QLatin1String( "hdf" ), Qt::CaseInsensitive ) ) name = name.mid( name.indexOf( path ) + path.length() + 1 ); else { @@ -3935,11 +3935,11 @@ void QgisApp::askUserForGDALSublayers( QgsRasterLayer *layer ) bool QgisApp::shouldAskUserForGDALSublayers( QgsRasterLayer *layer ) { // return false if layer is empty or raster has no sublayers - if ( !layer || layer->providerType() != "gdal" || layer->subLayers().size() < 1 ) + if ( !layer || layer->providerType() != QLatin1String( "gdal" ) || layer->subLayers().size() < 1 ) return false; QSettings settings; - int promptLayers = settings.value( "/qgis/promptForRasterSublayers", 1 ).toInt(); + int promptLayers = settings.value( QStringLiteral( "/qgis/promptForRasterSublayers" ), 1 ).toInt(); // 0 = Always -> always ask (if there are existing sublayers) // 1 = If needed -> ask if layer has no bands, but has sublayers // 2 = Never -> never prompt, will not load anything @@ -3981,7 +3981,7 @@ void QgisApp::askUserForOGRSublayers( QgsVectorLayer *layer ) if ( !layer ) { layer = qobject_cast( activeLayer() ); - if ( !layer || layer->dataProvider()->name() != "ogr" ) + if ( !layer || layer->dataProvider()->name() != QLatin1String( "ogr" ) ) return; } @@ -3994,7 +3994,7 @@ void QgisApp::askUserForOGRSublayers( QgsVectorLayer *layer ) // OGR provider returns items in this format: // ::: - QStringList elements = sublayer.split( ":" ); + QStringList elements = sublayer.split( QStringLiteral( ":" ) ); // merge back parts of the name that may have been split while ( elements.size() > 4 ) { @@ -4019,7 +4019,7 @@ void QgisApp::askUserForOGRSublayers( QgsVectorLayer *layer ) // We initialize a selection dialog and display it. - QgsSublayersDialog chooseSublayersDialog( QgsSublayersDialog::Ogr, "ogr", this ); + QgsSublayersDialog chooseSublayersDialog( QgsSublayersDialog::Ogr, QStringLiteral( "ogr" ), this ); chooseSublayersDialog.populateLayerTable( list ); if ( !chooseSublayersDialog.exec() ) @@ -4056,7 +4056,7 @@ void QgisApp::askUserForOGRSublayers( QgsVectorLayer *layer ) QString name = fileName + " " + def.layerName; if ( !layerGeometryType.isEmpty() ) name += " " + layerGeometryType; - QgsVectorLayer *layer = new QgsVectorLayer( composedURI, name, "ogr", false ); + QgsVectorLayer *layer = new QgsVectorLayer( composedURI, name, QStringLiteral( "ogr" ), false ); if ( layer && layer->isValid() ) { myList << layer; @@ -4089,7 +4089,7 @@ void QgisApp::addDatabaseLayer() QgsDebugMsg( "about to addRasterLayer" ); // TODO: QDialog for now, switch to QWidget in future - QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "postgres", this ) ); + QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "postgres" ), this ) ); if ( !dbs ) { QMessageBox::warning( this, tr( "PostgreSQL" ), tr( "Cannot get PostgreSQL select dialog from provider." ) ); @@ -4179,7 +4179,7 @@ void QgisApp::addDatabaseLayers( QStringList const & layerPathList, QString cons void QgisApp::addSpatiaLiteLayer() { // show the SpatiaLite dialog - QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "spatialite", this ) ); + QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "spatialite" ), this ) ); if ( !dbs ) { QMessageBox::warning( this, tr( "SpatiaLite" ), tr( "Cannot get SpatiaLite select dialog from provider." ) ); @@ -4194,7 +4194,7 @@ void QgisApp::addSpatiaLiteLayer() void QgisApp::addDelimitedTextLayer() { // show the Delimited text dialog - QDialog *dts = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "delimitedtext", this ) ); + QDialog *dts = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "delimitedtext" ), this ) ); if ( !dts ) { QMessageBox::warning( this, tr( "Delimited Text" ), tr( "Cannot get Delimited Text select dialog from provider." ) ); @@ -4209,7 +4209,7 @@ void QgisApp::addDelimitedTextLayer() void QgisApp::addVirtualLayer() { // show the Delimited text dialog - QDialog *dts = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "virtual", this ) ); + QDialog *dts = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "virtual" ), this ) ); if ( !dts ) { QMessageBox::warning( this, tr( "Virtual layer" ), tr( "Cannot get virtual layer select dialog from provider." ) ); @@ -4250,7 +4250,7 @@ void QgisApp::replaceSelectedVectorLayer( const QString& oldId, const QString& u void QgisApp::addMssqlLayer() { // show the MSSQL dialog - QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "mssql", this ) ); + QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "mssql" ), this ) ); if ( !dbs ) { QMessageBox::warning( this, tr( "MSSQL" ), tr( "Cannot get MSSQL select dialog from provider." ) ); @@ -4266,7 +4266,7 @@ void QgisApp::addDb2Layer() { // show the DB2 dialog QgsDebugMsg( "Show dialog for DB2 " ); - QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "DB2", this ) ); + QDialog *dbs = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "DB2" ), this ) ); if ( !dbs ) { QMessageBox::warning( this, tr( "DB2" ), tr( "Cannot get DB2 select dialog from provider." ) ); @@ -4305,7 +4305,7 @@ void QgisApp::addWmsLayer() QgsDebugMsg( "about to addRasterLayer" ); // TODO: QDialog for now, switch to QWidget in future - QDialog *wmss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QString( "wms" ), this ) ); + QDialog *wmss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "wms" ), this ) ); if ( !wmss ) { QMessageBox::warning( this, tr( "WMS" ), tr( "Cannot get WMS select dialog from provider." ) ); @@ -4322,7 +4322,7 @@ void QgisApp::addWcsLayer() QgsDebugMsg( "about to addWcsLayer" ); // TODO: QDialog for now, switch to QWidget in future - QDialog *wcss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QString( "wcs" ), this ) ); + QDialog *wcss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "wcs" ), this ) ); if ( !wcss ) { QMessageBox::warning( this, tr( "WCS" ), tr( "Cannot get WCS select dialog from provider." ) ); @@ -4339,7 +4339,7 @@ void QgisApp::addWfsLayer() QgsDebugMsg( "about to addWfsLayer" ); // TODO: QDialog for now, switch to QWidget in future - QDialog *wfss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QString( "WFS" ), this ) ); + QDialog *wfss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "WFS" ), this ) ); if ( !wfss ) { QMessageBox::warning( this, tr( "WFS" ), tr( "Cannot get WFS select dialog from provider." ) ); @@ -4355,7 +4355,7 @@ void QgisApp::addWfsLayer() void QgisApp::addWfsLayer( const QString& uri, const QString& typeName ) { // TODO: this should be eventually moved to a more reasonable place - addVectorLayer( uri, typeName, "WFS" ); + addVectorLayer( uri, typeName, QStringLiteral( "WFS" ) ); } void QgisApp::addAfsLayer() @@ -4368,7 +4368,7 @@ void QgisApp::addAfsLayer() QgsDebugMsg( "about to addAfsLayer" ); // TODO: QDialog for now, switch to QWidget in future - QgsSourceSelectDialog *afss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "arcgisfeatureserver", this ) ); + QgsSourceSelectDialog *afss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "arcgisfeatureserver" ), this ) ); if ( !afss ) { QMessageBox::warning( this, tr( "ArcGIS Feature Server" ), tr( "Cannot get ArcGIS Feature Server select dialog from provider." ) ); @@ -4388,7 +4388,7 @@ void QgisApp::addAfsLayer() void QgisApp::addAfsLayer( const QString &uri, const QString &typeName ) { // TODO: this should be eventually moved to a more reasonable place - addVectorLayer( uri, typeName, "arcgisfeatureserver" ); + addVectorLayer( uri, typeName, QStringLiteral( "arcgisfeatureserver" ) ); } void QgisApp::addAmsLayer() @@ -4401,7 +4401,7 @@ void QgisApp::addAmsLayer() QgsDebugMsg( "about to addAmsLayer" ); // TODO: QDialog for now, switch to QWidget in future - QgsSourceSelectDialog *amss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( "arcgismapserver", this ) ); + QgsSourceSelectDialog *amss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "arcgismapserver" ), this ) ); if ( !amss ) { QMessageBox::warning( this, tr( "ArcGIS Map Server" ), tr( "Cannot get ArcGIS Map Server select dialog from provider." ) ); @@ -4421,7 +4421,7 @@ void QgisApp::addAmsLayer() void QgisApp::addAmsLayer( const QString& uri, const QString& typeName ) { // TODO: this should be eventually moved to a more reasonable place - addRasterLayer( uri, typeName, QString( "arcgismapserver" ) ); + addRasterLayer( uri, typeName, QStringLiteral( "arcgismapserver" ) ); } void QgisApp::fileExit() @@ -4466,32 +4466,32 @@ void QgisApp::fileNew( bool thePromptToSaveFlag, bool forceBlank ) QgsProject* prj = QgsProject::instance(); prj->clear(); - prj->layerTreeRegistryBridge()->setNewLayersVisible( settings.value( "/qgis/new_layers_visible", true ).toBool() ); + prj->layerTreeRegistryBridge()->setNewLayersVisible( settings.value( QStringLiteral( "/qgis/new_layers_visible" ), true ).toBool() ); mLayerTreeCanvasBridge->clear(); //set the color for selections //the default can be set in qgisoptions //use project properties to override the color on a per project basis - int myRed = settings.value( "/qgis/default_selection_color_red", 255 ).toInt(); - int myGreen = settings.value( "/qgis/default_selection_color_green", 255 ).toInt(); - int myBlue = settings.value( "/qgis/default_selection_color_blue", 0 ).toInt(); - int myAlpha = settings.value( "/qgis/default_selection_color_alpha", 255 ).toInt(); - prj->writeEntry( "Gui", "/SelectionColorRedPart", myRed ); - prj->writeEntry( "Gui", "/SelectionColorGreenPart", myGreen ); - prj->writeEntry( "Gui", "/SelectionColorBluePart", myBlue ); - prj->writeEntry( "Gui", "/SelectionColorAlphaPart", myAlpha ); + int myRed = settings.value( QStringLiteral( "/qgis/default_selection_color_red" ), 255 ).toInt(); + int myGreen = settings.value( QStringLiteral( "/qgis/default_selection_color_green" ), 255 ).toInt(); + int myBlue = settings.value( QStringLiteral( "/qgis/default_selection_color_blue" ), 0 ).toInt(); + int myAlpha = settings.value( QStringLiteral( "/qgis/default_selection_color_alpha" ), 255 ).toInt(); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorRedPart" ), myRed ); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorGreenPart" ), myGreen ); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorBluePart" ), myBlue ); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorAlphaPart" ), myAlpha ); mMapCanvas->setSelectionColor( QColor( myRed, myGreen, myBlue, myAlpha ) ); //set the canvas to the default background color //the default can be set in qgisoptions //use project properties to override the color on a per project basis - myRed = settings.value( "/qgis/default_canvas_color_red", 255 ).toInt(); - myGreen = settings.value( "/qgis/default_canvas_color_green", 255 ).toInt(); - myBlue = settings.value( "/qgis/default_canvas_color_blue", 255 ).toInt(); - prj->writeEntry( "Gui", "/CanvasColorRedPart", myRed ); - prj->writeEntry( "Gui", "/CanvasColorGreenPart", myGreen ); - prj->writeEntry( "Gui", "/CanvasColorBluePart", myBlue ); + myRed = settings.value( QStringLiteral( "/qgis/default_canvas_color_red" ), 255 ).toInt(); + myGreen = settings.value( QStringLiteral( "/qgis/default_canvas_color_green" ), 255 ).toInt(); + myBlue = settings.value( QStringLiteral( "/qgis/default_canvas_color_blue" ), 255 ).toInt(); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorRedPart" ), myRed ); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorGreenPart" ), myGreen ); + prj->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorBluePart" ), myBlue ); mMapCanvas->setCanvasColor( QColor( myRed, myGreen, myBlue ) ); mOverviewCanvas->setBackgroundColor( QColor( myRed, myGreen, myBlue ) ); @@ -4511,7 +4511,7 @@ void QgisApp::fileNew( bool thePromptToSaveFlag, bool forceBlank ) mScaleWidget->updateScales(); // set project CRS - QString defCrs = settings.value( "/Projections/projectDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString(); + QString defCrs = settings.value( QStringLiteral( "/Projections/projectDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString(); QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( defCrs ); mMapCanvas->setDestinationCrs( srs ); // write the projections _proj string_ to project settings @@ -4523,7 +4523,7 @@ void QgisApp::fileNew( bool thePromptToSaveFlag, bool forceBlank ) } // enable OTF CRS transformation if necessary - mMapCanvas->setCrsTransformEnabled( settings.value( "/Projections/otfTransformEnabled", 0 ).toBool() ); + mMapCanvas->setCrsTransformEnabled( settings.value( QStringLiteral( "/Projections/otfTransformEnabled" ), 0 ).toBool() ); updateCrsStatusBar(); @@ -4537,10 +4537,10 @@ void QgisApp::fileNew( bool thePromptToSaveFlag, bool forceBlank ) // don't open template if last auto-opening of a project failed if ( ! forceBlank ) { - forceBlank = ! settings.value( "/qgis/projOpenedOKAtLaunch", QVariant( true ) ).toBool(); + forceBlank = ! settings.value( QStringLiteral( "/qgis/projOpenedOKAtLaunch" ), QVariant( true ) ).toBool(); } - if ( ! forceBlank && settings.value( "/qgis/newProjectDefault", QVariant( false ) ).toBool() ) + if ( ! forceBlank && settings.value( QStringLiteral( "/qgis/newProjectDefault" ), QVariant( false ) ).toBool() ) { fileNewFromDefaultTemplate(); } @@ -4575,7 +4575,7 @@ bool QgisApp::fileNewFromTemplate( const QString& fileName ) void QgisApp::fileNewFromDefaultTemplate() { - QString projectTemplate = QgsApplication::qgisSettingsDirPath() + QLatin1String( "project_default.qgs" ); + QString projectTemplate = QgsApplication::qgisSettingsDirPath() + QStringLiteral( "project_default.qgs" ); QString msgTxt; if ( !projectTemplate.isEmpty() && QFile::exists( projectTemplate ) ) { @@ -4631,11 +4631,11 @@ void QgisApp::fileOpenAfterLaunch() } if ( mProjOpen == 2 ) // specific project { - projPath = settings.value( "/qgis/projOpenAtLaunchPath" ).toString(); + projPath = settings.value( QStringLiteral( "/qgis/projOpenAtLaunchPath" ) ).toString(); } // whether last auto-opening of a project failed - bool projOpenedOK = settings.value( "/qgis/projOpenedOKAtLaunch", QVariant( true ) ).toBool(); + bool projOpenedOK = settings.value( QStringLiteral( "/qgis/projOpenedOKAtLaunch" ), QVariant( true ) ).toBool(); // notify user if last attempt at auto-opening a project failed /** NOTE: Notification will not show if last auto-opened project failed but @@ -4645,10 +4645,10 @@ void QgisApp::fileOpenAfterLaunch() if ( !projOpenedOK ) { // only show the following 'auto-open project failed' message once, at launch - settings.setValue( "/qgis/projOpenedOKAtLaunch", QVariant( true ) ); + settings.setValue( QStringLiteral( "/qgis/projOpenedOKAtLaunch" ), QVariant( true ) ); // set auto-open project back to 'New' to avoid re-opening bad project - settings.setValue( "/qgis/projOpenAtLaunch", QVariant( 0 ) ); + settings.setValue( QStringLiteral( "/qgis/projOpenAtLaunch" ), QVariant( 0 ) ); messageBar()->pushMessage( autoOpenMsgTitle, tr( "Failed to open: %1" ).arg( projPath ), @@ -4659,7 +4659,7 @@ void QgisApp::fileOpenAfterLaunch() if ( mProjOpen == 3 ) // new project { // open default template, if defined - if ( settings.value( "/qgis/newProjectDefault", QVariant( false ) ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/newProjectDefault" ), QVariant( false ) ).toBool() ) { fileNewFromDefaultTemplate(); } @@ -4682,7 +4682,7 @@ void QgisApp::fileOpenAfterLaunch() if ( QFile::exists( projPath ) ) { // set flag to check on next app launch if the following project opened OK - settings.setValue( "/qgis/projOpenedOKAtLaunch", QVariant( false ) ); + settings.setValue( QStringLiteral( "/qgis/projOpenedOKAtLaunch" ), QVariant( false ) ); if ( !addProject( projPath ) ) { @@ -4709,7 +4709,7 @@ void QgisApp::fileOpenAfterLaunch() void QgisApp::fileOpenedOKAfterLaunch() { QSettings settings; - settings.setValue( "/qgis/projOpenedOKAtLaunch", QVariant( true ) ); + settings.setValue( QStringLiteral( "/qgis/projOpenedOKAtLaunch" ), QVariant( true ) ); } void QgisApp::fileNewFromTemplateAction( QAction * qAction ) @@ -4724,7 +4724,7 @@ void QgisApp::fileNewFromTemplateAction( QAction * qAction ) else { QSettings settings; - QString templateDirName = settings.value( "/qgis/projectTemplateDir", + QString templateDirName = settings.value( QStringLiteral( "/qgis/projectTemplateDir" ), QgsApplication::qgisSettingsDirPath() + "project_templates" ).toString(); fileNewFromTemplate( templateDirName + QDir::separator() + qAction->text() ); } @@ -4742,7 +4742,7 @@ void QgisApp::newVectorLayer() QStringList fileNames; fileNames.append( fileName ); //todo: the last parameter will change accordingly to layer type - addVectorLayers( fileNames, enc, "file" ); + addVectorLayers( fileNames, enc, QStringLiteral( "file" ) ); } else if ( fileName.isNull() ) { @@ -4850,7 +4850,7 @@ void QgisApp::fileOpen() { // Retrieve last used project dir from persistent settings QSettings settings; - QString lastUsedDir = settings.value( "/UI/lastProjectDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastProjectDir" ), QDir::homePath() ).toString(); QString fullPath = QFileDialog::getOpenFileName( this, tr( "Choose a QGIS project file to open" ), lastUsedDir, @@ -4866,7 +4866,7 @@ void QgisApp::fileOpen() QFileInfo myFI( fullPath ); QString myPath = myFI.path(); // Persist last used project dir - settings.setValue( "/UI/lastProjectDir", myPath ); + settings.setValue( QStringLiteral( "/UI/lastProjectDir" ), myPath ); // open the selected project addProject( fullPath ); @@ -4878,7 +4878,7 @@ void QgisApp::enableProjectMacros() mTrustedMacros = true; // load macros - QgsPythonRunner::run( "qgis.utils.reloadProjectMacros()" ); + QgsPythonRunner::run( QStringLiteral( "qgis.utils.reloadProjectMacros()" ) ); } /** @@ -4936,41 +4936,41 @@ bool QgisApp::addProject( const QString& projectFile ) mProjectLastModified = pfi.lastModified(); setTitleBarText_( *this ); - int myRedInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorRedPart", 255 ); - int myGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorGreenPart", 255 ); - int myBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorBluePart", 255 ); + int myRedInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorRedPart" ), 255 ); + int myGreenInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorGreenPart" ), 255 ); + int myBlueInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorBluePart" ), 255 ); QColor myColor = QColor( myRedInt, myGreenInt, myBlueInt ); mMapCanvas->setCanvasColor( myColor ); //this is fill color before rendering starts mOverviewCanvas->setBackgroundColor( myColor ); QgsDebugMsg( "Canvas background color restored..." ); - int myAlphaInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorAlphaPart", 255 ); - myRedInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorRedPart", 255 ); - myGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorGreenPart", 255 ); - myBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorBluePart", 0 ); + int myAlphaInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorAlphaPart" ), 255 ); + myRedInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorRedPart" ), 255 ); + myGreenInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorGreenPart" ), 255 ); + myBlueInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorBluePart" ), 0 ); myColor = QColor( myRedInt, myGreenInt, myBlueInt, myAlphaInt ); mMapCanvas->setSelectionColor( myColor ); //this is selection color before rendering starts //load project scales - bool projectScales = QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ); + bool projectScales = QgsProject::instance()->readBoolEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ) ); if ( projectScales ) { - mScaleWidget->updateScales( QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ) ); + mScaleWidget->updateScales( QgsProject::instance()->readListEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ) ) ); } mMapCanvas->updateScale(); QgsDebugMsg( "Scale restored..." ); - mActionFilterLegend->setChecked( QgsProject::instance()->readBoolEntry( "Legend", "filterByMap" ) ); + mActionFilterLegend->setChecked( QgsProject::instance()->readBoolEntry( QStringLiteral( "Legend" ), QStringLiteral( "filterByMap" ) ) ); QSettings settings; // does the project have any macros? if ( mPythonUtils && mPythonUtils->isEnabled() ) { - if ( !QgsProject::instance()->readEntry( "Macros", "/pythonCode", QString::null ).isEmpty() ) + if ( !QgsProject::instance()->readEntry( QStringLiteral( "Macros" ), QStringLiteral( "/pythonCode" ), QString::null ).isEmpty() ) { - int enableMacros = settings.value( "/qgis/enableMacros", 1 ).toInt(); + int enableMacros = settings.value( QStringLiteral( "/qgis/enableMacros" ), 1 ).toInt(); // 0 = never, 1 = ask, 2 = just for this session, 3 = always if ( enableMacros == 3 || enableMacros == 2 ) @@ -4984,7 +4984,7 @@ bool QgisApp::addProject( const QString& projectFile ) QToolButton *btnEnableMacros = new QToolButton(); btnEnableMacros->setText( tr( "Enable macros" ) ); - btnEnableMacros->setStyleSheet( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ); + btnEnableMacros->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) ); btnEnableMacros->setCursor( Qt::PointingHandCursor ); btnEnableMacros->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ); connect( btnEnableMacros, SIGNAL( clicked() ), mInfoBar, SLOT( popWidget() ) ); @@ -5031,7 +5031,7 @@ bool QgisApp::fileSave() { // Retrieve last used project dir from persistent settings QSettings settings; - QString lastUsedDir = settings.value( "/UI/lastProjectDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastProjectDir" ), QDir::homePath() ).toString(); QString path = QFileDialog::getSaveFileName( this, @@ -5099,7 +5099,7 @@ bool QgisApp::fileSave() // run the saved project macro if ( mTrustedMacros ) { - QgsPythonRunner::run( "qgis.utils.saveProjectMacro();" ); + QgsPythonRunner::run( QStringLiteral( "qgis.utils.saveProjectMacro();" ) ); } return true; @@ -5109,7 +5109,7 @@ void QgisApp::fileSaveAs() { // Retrieve last used project dir from persistent settings QSettings settings; - QString lastUsedDir = settings.value( "/UI/lastProjectDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastProjectDir" ), QDir::homePath() ).toString(); QString path = QFileDialog::getSaveFileName( this, tr( "Choose a file name to save the QGIS project file as" ), @@ -5120,7 +5120,7 @@ void QgisApp::fileSaveAs() QFileInfo fullPath( path ); - settings.setValue( "/UI/lastProjectDir", fullPath.path() ); + settings.setValue( QStringLiteral( "/UI/lastProjectDir" ), fullPath.path() ); // make sure the .qgs extension is included in the path name. if not, add it... if ( "qgs" != fullPath.suffix().toLower() ) @@ -5171,8 +5171,8 @@ void QgisApp::dxfExport() } QString fileName( d.saveFile() ); - if ( !fileName.endsWith( ".dxf", Qt::CaseInsensitive ) ) - fileName += ".dxf"; + if ( !fileName.endsWith( QLatin1String( ".dxf" ), Qt::CaseInsensitive ) ) + fileName += QLatin1String( ".dxf" ); QFile dxfFile( fileName ); QApplication::setOverrideCursor( Qt::BusyCursor ); if ( dxfExport.writeToFile( &dxfFile, d.encoding() ) == 0 ) @@ -5252,7 +5252,7 @@ void QgisApp::openProject( QAction *action ) //set the projections enabled icon in the status bar int myProjectionEnabledFlag = - QgsProject::instance()->readNumEntry( "SpatialRefSys", "/ProjectionsEnabled", 0 ); + QgsProject::instance()->readNumEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectionsEnabled" ), 0 ); mMapCanvas->setCrsTransformEnabled( myProjectionEnabledFlag ); } @@ -5297,7 +5297,7 @@ bool QgisApp::openLayer( const QString & fileName, bool allowInteractive ) // if needed prompt for zipitem layers QString vsiPrefix = QgsZipItem::vsiPrefix( fileName ); - if ( vsiPrefix == "/vsizip/" || vsiPrefix == "/vsitar/" ) + if ( vsiPrefix == QLatin1String( "/vsizip/" ) || vsiPrefix == QLatin1String( "/vsitar/" ) ) { if ( askUserForZipItemLayers( fileName ) ) { @@ -5310,7 +5310,7 @@ bool QgisApp::openLayer( const QString & fileName, bool allowInteractive ) if ( QgsRasterLayer::isValidRasterFileName( fileName ) ) { // open .adf as a directory - if ( fileName.endsWith( ".adf", Qt::CaseInsensitive ) ) + if ( fileName.endsWith( QLatin1String( ".adf" ), Qt::CaseInsensitive ) ) { QString dirName = fileInfo.path(); ok = addRasterLayer( dirName, QFileInfo( dirName ).completeBaseName() ); @@ -5331,11 +5331,11 @@ bool QgisApp::openLayer( const QString & fileName, bool allowInteractive ) { if ( allowInteractive ) { - ok = addVectorLayers( QStringList( fileName ), "System", "file" ); + ok = addVectorLayers( QStringList( fileName ), QStringLiteral( "System" ), QStringLiteral( "file" ) ); } else { - ok = addVectorLayer( fileName, fileInfo.completeBaseName(), "ogr" ); + ok = addVectorLayer( fileName, fileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); } } @@ -5356,20 +5356,20 @@ void QgisApp::openFile( const QString & fileName ) { // check to see if we are opening a project file QFileInfo fi( fileName ); - if ( fi.completeSuffix() == "qgs" ) + if ( fi.completeSuffix() == QLatin1String( "qgs" ) ) { QgsDebugMsg( "Opening project " + fileName ); openProject( fileName ); } - else if ( fi.completeSuffix() == "qlr" ) + else if ( fi.completeSuffix() == QLatin1String( "qlr" ) ) { openLayerDefinition( fileName ); } - else if ( fi.completeSuffix() == "qpt" ) + else if ( fi.completeSuffix() == QLatin1String( "qpt" ) ) { openTemplate( fileName ); } - else if ( fi.completeSuffix() == "py" ) + else if ( fi.completeSuffix() == QLatin1String( "py" ) ) { runScript( fileName ); } @@ -5471,7 +5471,7 @@ void QgisApp::updateFilterLegend() void QgisApp::saveMapAsImage() { QPair< QString, QString> myFileNameAndFilter = QgisGui::getSaveAsImageName( this, tr( "Choose a file name to save the map image as" ) ); - if ( myFileNameAndFilter.first != "" ) + if ( myFileNameAndFilter.first != QLatin1String( "" ) ) { //save the mapview to the selected file mMapCanvas->saveAsImage( myFileNameAndFilter.first, nullptr, myFileNameAndFilter.second ); @@ -5483,7 +5483,7 @@ void QgisApp::saveMapAsImage() //overloaded version of the above function void QgisApp::saveMapAsImage( const QString& theImageFileNameQString, QPixmap * theQPixmap ) { - if ( theImageFileNameQString == "" ) + if ( theImageFileNameQString == QLatin1String( "" ) ) { //no fileName chosen return; @@ -5503,7 +5503,7 @@ void QgisApp::addAllToOverview() if ( mLayerTreeView ) { Q_FOREACH ( QgsLayerTreeLayer* nodeL, mLayerTreeView->layerTreeModel()->rootGroup()->findLayers() ) - nodeL->setCustomProperty( "overview", 1 ); + nodeL->setCustomProperty( QStringLiteral( "overview" ), 1 ); } markDirty(); @@ -5515,7 +5515,7 @@ void QgisApp::removeAllFromOverview() if ( mLayerTreeView ) { Q_FOREACH ( QgsLayerTreeLayer* nodeL, mLayerTreeView->layerTreeModel()->rootGroup()->findLayers() ) - nodeL->setCustomProperty( "overview", 0 ); + nodeL->setCustomProperty( QStringLiteral( "overview" ), 0 ); } markDirty(); @@ -5744,7 +5744,7 @@ void QgisApp::updateDefaultFeatureAction( QAction *action ) if ( !vlayer ) return; - mActionFeatureAction->setIcon( QgsApplication::getThemeIcon( "/mAction.svg" ) ); + mActionFeatureAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ) ); mActionFeatureAction->setToolTip( tr( "No action selected" ) ); mFeatureActionMenu->setActiveAction( action ); @@ -5883,7 +5883,7 @@ void QgisApp::labelingFontNotFound( QgsVectorLayer* vlayer, const QString& fontf QString substitute = tr( "Default system font substituted." ); QToolButton* btnOpenPrefs = new QToolButton(); - btnOpenPrefs->setStyleSheet( "QToolButton{ background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline; }" ); + btnOpenPrefs->setStyleSheet( QStringLiteral( "QToolButton{ background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline; }" ) ); btnOpenPrefs->setCursor( Qt::PointingHandCursor ); btnOpenPrefs->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ); btnOpenPrefs->setToolButtonStyle( Qt::ToolButtonTextOnly ); @@ -5894,7 +5894,7 @@ void QgisApp::labelingFontNotFound( QgsVectorLayer* vlayer, const QString& fontf act->setText( tr( "Open labeling dialog" ) ); btnOpenPrefs->addAction( act ); btnOpenPrefs->setDefaultAction( act ); - btnOpenPrefs->setToolTip( "" ); + btnOpenPrefs->setToolTip( QLatin1String( "" ) ); connect( btnOpenPrefs, SIGNAL( triggered( QAction* ) ), this, SLOT( labelingDialogFontNotFound( QAction* ) ) ); // no timeout set, since notice needs attention and is only shown first time layer is labeled @@ -5914,7 +5914,7 @@ void QgisApp::commitError( QgsVectorLayer* vlayer ) mv->setWindowTitle( tr( "Commit errors" ) ); mv->setMessageAsPlainText( tr( "Could not commit changes to layer %1" ).arg( vlayer->name() ) + "\n\n" - + tr( "Errors: %1\n" ).arg( vlayer->commitErrors().join( "\n " ) ) + + tr( "Errors: %1\n" ).arg( vlayer->commitErrors().join( QStringLiteral( "\n " ) ) ) ); QToolButton *showMore = new QToolButton(); @@ -5922,7 +5922,7 @@ void QgisApp::commitError( QgsVectorLayer* vlayer ) QAction *act = new QAction( showMore ); act->setData( QVariant( QMetaType::QObjectStar, &vlayer ) ); act->setText( tr( "Show more" ) ); - showMore->setStyleSheet( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ); + showMore->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) ); showMore->setCursor( Qt::PointingHandCursor ); showMore->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ); showMore->addAction( act ); @@ -6088,7 +6088,7 @@ void QgisApp::saveAsRasterFile() return; QSettings settings; - settings.setValue( "/UI/lastRasterFileDir", QFileInfo( d.outputFileName() ).absolutePath() ); + settings.setValue( QStringLiteral( "/UI/lastRasterFileDir" ), QFileInfo( d.outputFileName() ).absolutePath() ); QgsRasterFileWriter fileWriter( d.outputFileName() ); if ( d.tileMode() ) @@ -6184,7 +6184,7 @@ void QgisApp::saveAsRasterFile() if ( d.tileMode() ) { QFileInfo outputInfo( fileName ); - fileName = QString( "%1/%2.vrt" ).arg( fileName, outputInfo.fileName() ); + fileName = QStringLiteral( "%1/%2.vrt" ).arg( fileName, outputInfo.fileName() ); } if ( d.addToCanvas() ) @@ -6218,7 +6218,7 @@ void QgisApp::saveAsFile() void QgisApp::saveAsLayerDefinition() { - QString path = QFileDialog::getSaveFileName( this, "Save as Layer Definition File", QDir::home().path(), "*.qlr" ); + QString path = QFileDialog::getSaveFileName( this, QStringLiteral( "Save as Layer Definition File" ), QDir::home().path(), QStringLiteral( "*.qlr" ) ); QgsDebugMsg( path ); if ( path.isEmpty() ) return; @@ -6324,7 +6324,7 @@ void QgisApp::saveAsVectorFileGeneral( QgsVectorLayer* vlayer, bool symbologyOpt //ask user about datum transformation QSettings settings; QList< QList< int > > dt = QgsCoordinateTransform::datumTransformations( vlayer->crs(), destCRS ); - if ( dt.size() > 1 && settings.value( "/Projections/showDatumTransformDialog", false ).toBool() ) + if ( dt.size() > 1 && settings.value( QStringLiteral( "/Projections/showDatumTransformDialog" ), false ).toBool() ) { QgsDatumTransformDialog d( vlayer->name(), dt ); if ( d.exec() == QDialog::Accepted ) @@ -6388,7 +6388,7 @@ void QgisApp::saveAsVectorFileGeneral( QgsVectorLayer* vlayer, bool symbologyOpt QString uri( newFilename ); if ( !dialog->layername().isEmpty() ) uri += "|layername=" + dialog->layername(); - addVectorLayers( QStringList( uri ), encoding, "file" ); + addVectorLayers( QStringList( uri ), encoding, QStringLiteral( "file" ) ); } emit layerSavedAs( vlayer, vectorFilename ); messageBar()->pushMessage( tr( "Saving done" ), @@ -6680,7 +6680,7 @@ QgsComposer* QgisApp::duplicateComposer( QgsComposer* currentComposer, QString t // test that current composer template write is valid QDomDocument currentDoc; currentComposer->templateXml( currentDoc ); - QDomElement compositionElem = currentDoc.documentElement().firstChildElement( "Composition" ); + QDomElement compositionElem = currentDoc.documentElement().firstChildElement( QStringLiteral( "Composition" ) ); if ( compositionElem.isNull() ) { QgsDebugMsg( "selected composer could not be stored as temporary template" ); @@ -6722,10 +6722,10 @@ bool QgisApp::loadComposersFromProject( const QDomDocument& doc ) } //restore each composer - QDomNodeList composerNodes = doc.elementsByTagName( "Composer" ); + QDomNodeList composerNodes = doc.elementsByTagName( QStringLiteral( "Composer" ) ); for ( int i = 0; i < composerNodes.size(); ++i ) { - QString title( composerNodes.at( i ).toElement().attribute( "title" ) ); + QString title( composerNodes.at( i ).toElement().attribute( QStringLiteral( "title" ) ) ); showStatusMessage( tr( "Loading composer %1" ).arg( title ) ); showProgress( i, composerNodes.size() ); ++mLastComposerId; @@ -6811,14 +6811,14 @@ bool QgisApp::loadAnnotationItemsFromProject( const QDomDocument& doc ) return false; } - QDomNodeList textItemList = doc.elementsByTagName( "TextAnnotationItem" ); + QDomNodeList textItemList = doc.elementsByTagName( QStringLiteral( "TextAnnotationItem" ) ); for ( int i = 0; i < textItemList.size(); ++i ) { QgsTextAnnotationItem* newTextItem = new QgsTextAnnotationItem( mMapCanvas ); newTextItem->readXml( doc, textItemList.at( i ).toElement() ); } - QDomNodeList formItemList = doc.elementsByTagName( "FormAnnotationItem" ); + QDomNodeList formItemList = doc.elementsByTagName( QStringLiteral( "FormAnnotationItem" ) ); for ( int i = 0; i < formItemList.size(); ++i ) { QgsFormAnnotationItem* newFormItem = new QgsFormAnnotationItem( mMapCanvas ); @@ -6826,7 +6826,7 @@ bool QgisApp::loadAnnotationItemsFromProject( const QDomDocument& doc ) } #ifdef WITH_QTWEBKIT - QDomNodeList htmlItemList = doc.elementsByTagName( "HtmlAnnotationItem" ); + QDomNodeList htmlItemList = doc.elementsByTagName( QStringLiteral( "HtmlAnnotationItem" ) ); for ( int i = 0; i < htmlItemList.size(); ++i ) { QgsHtmlAnnotationItem* newHtmlItem = new QgsHtmlAnnotationItem( mMapCanvas ); @@ -6834,7 +6834,7 @@ bool QgisApp::loadAnnotationItemsFromProject( const QDomDocument& doc ) } #endif - QDomNodeList svgItemList = doc.elementsByTagName( "SVGAnnotationItem" ); + QDomNodeList svgItemList = doc.elementsByTagName( QStringLiteral( "SVGAnnotationItem" ) ); for ( int i = 0; i < svgItemList.size(); ++i ) { QgsSvgAnnotationItem* newSvgItem = new QgsSvgAnnotationItem( mMapCanvas ); @@ -7513,7 +7513,7 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) { if ( !dstAttr.at( dst ).isNull() ) continue; - else if ( pasteVectorLayer->providerType() == "spatialite" ) + else if ( pasteVectorLayer->providerType() == QLatin1String( "spatialite" ) ) continue; } @@ -7672,7 +7672,7 @@ QgsVectorLayer *QgisApp::pasteToNewMemoryVector() QgsWkbTypes::Type wkbType = !typeCounts.isEmpty() ? typeCounts.keys().value( 0 ) : QgsWkbTypes::NoGeometry; - QString typeName = wkbType != QgsWkbTypes::NoGeometry ? QgsWkbTypes::displayString( wkbType ) : "none"; + QString typeName = wkbType != QgsWkbTypes::NoGeometry ? QgsWkbTypes::displayString( wkbType ) : QStringLiteral( "none" ); if ( features.isEmpty() ) { @@ -7689,10 +7689,10 @@ QgsVectorLayer *QgisApp::pasteToNewMemoryVector() QgsMessageBar::INFO, messageTimeout() ); } - typeName += QString( "?memoryid=%1" ).arg( QUuid::createUuid().toString() ); + typeName += QStringLiteral( "?memoryid=%1" ).arg( QUuid::createUuid().toString() ); QgsDebugMsg( QString( "output wkbType = %1 typeName = %2" ).arg( wkbType ).arg( typeName ) ); - QgsVectorLayer *layer = new QgsVectorLayer( typeName, "pasted_features", "memory" ); + QgsVectorLayer *layer = new QgsVectorLayer( typeName, QStringLiteral( "pasted_features" ), QStringLiteral( "memory" ) ); if ( !layer->isValid() || !layer->dataProvider() ) { @@ -7761,7 +7761,7 @@ void QgisApp::copyStyle( QgsMapLayer * sourceLayer ) if ( selectionLayer ) { QString errorMsg; - QDomDocument doc( "qgis" ); + QDomDocument doc( QStringLiteral( "qgis" ) ); selectionLayer->exportNamedStyle( doc, errorMsg ); @@ -7791,7 +7791,7 @@ void QgisApp::pasteStyle( QgsMapLayer * destinationLayer ) { if ( clipboard()->hasFormat( QGSCLIPBOARD_STYLE_MIME ) ) { - QDomDocument doc( "qgis" ); + QDomDocument doc( QStringLiteral( "qgis" ) ); QString errorMsg; int errorLine, errorColumn; if ( !doc.setContent( clipboard()->data( QGSCLIPBOARD_STYLE_MIME ), false, &errorMsg, &errorLine, &errorColumn ) ) @@ -7803,7 +7803,7 @@ void QgisApp::pasteStyle( QgsMapLayer * destinationLayer ) return; } - bool isVectorStyle = doc.elementsByTagName( "pipe" ).isEmpty(); + bool isVectorStyle = doc.elementsByTagName( QStringLiteral( "pipe" ) ).isEmpty(); if (( selectionLayer->type() == QgsMapLayer::RasterLayer && isVectorStyle ) || ( selectionLayer->type() == QgsMapLayer::VectorLayer && !isVectorStyle ) ) { @@ -7851,7 +7851,7 @@ void QgisApp::toggleMapTips( bool enabled ) { mMapTipsVisible = enabled; // Store if maptips are active - QSettings().setValue( "/qgis/enableMapTips", mMapTipsVisible ); + QSettings().setValue( QStringLiteral( "/qgis/enableMapTips" ), mMapTipsVisible ); // if off, stop the timer if ( !mMapTipsVisible ) @@ -7915,12 +7915,12 @@ bool QgisApp::toggleEditing( QgsMapLayer *layer, bool allowCancel ) vlayer->startEditing(); QSettings settings; - QString markerType = settings.value( "/qgis/digitizing/marker_style", "Cross" ).toString(); - bool markSelectedOnly = settings.value( "/qgis/digitizing/marker_only_for_selected", false ).toBool(); + QString markerType = settings.value( QStringLiteral( "/qgis/digitizing/marker_style" ), "Cross" ).toString(); + bool markSelectedOnly = settings.value( QStringLiteral( "/qgis/digitizing/marker_only_for_selected" ), false ).toBool(); // redraw only if markers will be drawn if (( !markSelectedOnly || vlayer->selectedFeatureCount() > 0 ) && - ( markerType == "Cross" || markerType == "SemiTransparentCircle" ) ) + ( markerType == QLatin1String( "Cross" ) || markerType == QLatin1String( "SemiTransparentCircle" ) ) ) { vlayer->triggerRepaint(); } @@ -8047,7 +8047,7 @@ void QgisApp::cancelEdits( QgsMapLayer *layer, bool leaveEditable, bool triggerR tr( "Could not %1 changes to layer %2\n\nErrors: %3\n" ) .arg( leaveEditable ? tr( "rollback" ) : tr( "cancel" ), vlayer->name(), - vlayer->commitErrors().join( "\n " ) ) ); + vlayer->commitErrors().join( QStringLiteral( "\n " ) ) ) ); } mMapCanvas->freeze( false ); @@ -8216,10 +8216,10 @@ void QgisApp::duplicateVectorStyle( QgsVectorLayer* srcLayer, QgsVectorLayer* de QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement rootNode = doc.createElement( "qgis" ); - rootNode.setAttribute( "version", Qgis::QGIS_VERSION ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); + rootNode.setAttribute( QStringLiteral( "version" ), Qgis::QGIS_VERSION ); doc.appendChild( rootNode ); QString errorMsg; srcLayer->writeSymbology( rootNode, doc, errorMsg ); @@ -8242,7 +8242,7 @@ void QgisApp::layerSubsetString() QMessageBox::Yes | QMessageBox::No ) == QMessageBox::Yes ) { QgsVirtualLayerDefinition def = QgsVirtualLayerDefinitionUtils::fromJoinedLayer( vlayer ); - QgsVectorLayer* newLayer = new QgsVectorLayer( def.toString(), vlayer->name() + " (virtual)", "virtual" ); + QgsVectorLayer* newLayer = new QgsVectorLayer( def.toString(), vlayer->name() + " (virtual)", QStringLiteral( "virtual" ) ); if ( newLayer->isValid() ) { duplicateVectorStyle( vlayer, newLayer ); @@ -8376,7 +8376,7 @@ void QgisApp::removeLayer() return; } - bool promptConfirmation = QSettings().value( "qgis/askToDeleteLayers", true ).toBool(); + bool promptConfirmation = QSettings().value( QStringLiteral( "qgis/askToDeleteLayers" ), true ).toBool(); bool shiftHeld = QApplication::queryKeyboardModifiers().testFlag( Qt::ShiftModifier ); //display a warning if ( !shiftHeld && promptConfirmation && QMessageBox::warning( this, tr( "Remove layers and groups" ), tr( "Remove %n legend entries?", "number of legend items to remove", selectedNodes.count() ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel ) @@ -8432,7 +8432,7 @@ void QgisApp::duplicateLayers( const QList& lyrList ) QgsVectorLayer *vlayer = qobject_cast( selectedLyr ); // TODO: add other layer types that can be duplicated // currently memory and plugin layers are skipped - if ( vlayer && vlayer->storageType() == "Memory storage" ) + if ( vlayer && vlayer->storageType() == QLatin1String( "Memory storage" ) ) { unSppType = tr( "Memory layer" ); } @@ -8445,8 +8445,8 @@ void QgisApp::duplicateLayers( const QList& lyrList ) } //add variables defined in layer properties - QStringList variableNames = vlayer->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = vlayer->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = vlayer->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = vlayer->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); int varIndex = 0; Q_FOREACH ( const QString& variableName, variableNames ) @@ -8500,7 +8500,7 @@ void QgisApp::duplicateLayers( const QList& lyrList ) tr( "Duplicate layer: " ), tr( "%1 (%2 type unsupported)" ) .arg( selectedLyr->name(), - !unSppType.isEmpty() ? QString( "'" ) + unSppType + "' " : "" ), + !unSppType.isEmpty() ? QStringLiteral( "'" ) + unSppType + "' " : QLatin1String( "" ) ), QgsMessageBar::WARNING, 0, mInfoBar ) ); @@ -8796,14 +8796,14 @@ void QgisApp::legendGroupSetWmsData() if ( !currentGroup ) return; QgsGroupWmsDataDialog* dlg = new QgsGroupWmsDataDialog( this ); - dlg->setGroupShortName( currentGroup->customProperty( "wmsShortName" ).toString() ); - dlg->setGroupTitle( currentGroup->customProperty( "wmsTitle" ).toString() ); - dlg->setGroupTitle( currentGroup->customProperty( "wmsAbstract" ).toString() ); + dlg->setGroupShortName( currentGroup->customProperty( QStringLiteral( "wmsShortName" ) ).toString() ); + dlg->setGroupTitle( currentGroup->customProperty( QStringLiteral( "wmsTitle" ) ).toString() ); + dlg->setGroupTitle( currentGroup->customProperty( QStringLiteral( "wmsAbstract" ) ).toString() ); if ( dlg->exec() ) { - currentGroup->setCustomProperty( "wmsShortName", dlg->groupShortName() ); - currentGroup->setCustomProperty( "wmsTitle", dlg->groupTitle() ); - currentGroup->setCustomProperty( "wmsAbstract", dlg->groupAbstract() ); + currentGroup->setCustomProperty( QStringLiteral( "wmsShortName" ), dlg->groupShortName() ); + currentGroup->setCustomProperty( QStringLiteral( "wmsTitle" ), dlg->groupTitle() ); + currentGroup->setCustomProperty( QStringLiteral( "wmsAbstract" ), dlg->groupAbstract() ); } delete dlg; } @@ -8819,7 +8819,7 @@ void QgisApp::showPluginManager() if ( mPythonUtils && mPythonUtils->isEnabled() ) { // Call pluginManagerInterface()->showPluginManager() as soon as the plugin installer says the remote data is fetched. - QgsPythonRunner::run( "pyplugin_installer.instance().showPluginManagerWhenReady()" ); + QgsPythonRunner::run( QStringLiteral( "pyplugin_installer.instance().showPluginManagerWhenReady()" ) ); } else { @@ -8858,14 +8858,14 @@ class QgsPythonRunnerImpl : public QgsPythonRunner void QgisApp::loadPythonSupport() { - QString pythonlibName( "qgispython" ); + QString pythonlibName( QStringLiteral( "qgispython" ) ); #if defined(Q_OS_MAC) || defined(Q_OS_LINUX) pythonlibName.prepend( QgsApplication::libraryPath() ); #endif #ifdef __MINGW32__ pythonlibName.prepend( "lib" ); #endif - QString version = QString( "%1.%2.%3" ).arg( Qgis::QGIS_VERSION_INT / 10000 ).arg( Qgis::QGIS_VERSION_INT / 100 % 100 ).arg( Qgis::QGIS_VERSION_INT % 100 ); + QString version = QStringLiteral( "%1.%2.%3" ).arg( Qgis::QGIS_VERSION_INT / 10000 ).arg( Qgis::QGIS_VERSION_INT / 100 % 100 ).arg( Qgis::QGIS_VERSION_INT % 100 ); QgsDebugMsg( QString( "load library %1 (%2)" ).arg( pythonlibName, version ) ); QLibrary pythonlib( pythonlibName, version ); // It's necessary to set these two load hints, otherwise Python library won't work correctly @@ -8942,7 +8942,7 @@ void QgisApp::versionReplyFinished() info = tr( "You are running the current version of QGIS" ); } - info = QString( "%1" ).arg( info ); + info = QStringLiteral( "%1" ).arg( info ); info += "
                                                                                                                                                                                    " + versionInfo->downloadInfo(); @@ -8977,9 +8977,9 @@ void QgisApp::options() void QgisApp::showOptionsDialog( QWidget *parent, const QString& currentPage ) { QSettings mySettings; - QString oldScales = mySettings.value( "Map/scales", PROJECT_SCALES ).toString(); + QString oldScales = mySettings.value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString(); - bool oldCapitalise = mySettings.value( "/qgis/capitaliseLayerName", QVariant( false ) ).toBool(); + bool oldCapitalise = mySettings.value( QStringLiteral( "/qgis/capitaliseLayerName" ), QVariant( false ) ).toBool(); QgsOptions *optionsDialog = new QgsOptions( parent ); if ( !currentPage.isEmpty() ) @@ -8989,22 +8989,22 @@ void QgisApp::showOptionsDialog( QWidget *parent, const QString& currentPage ) if ( optionsDialog->exec() ) { - QgsProject::instance()->layerTreeRegistryBridge()->setNewLayersVisible( mySettings.value( "/qgis/new_layers_visible", true ).toBool() ); + QgsProject::instance()->layerTreeRegistryBridge()->setNewLayersVisible( mySettings.value( QStringLiteral( "/qgis/new_layers_visible" ), true ).toBool() ); setupLayerTreeViewFromSettings(); - mMapCanvas->enableAntiAliasing( mySettings.value( "/qgis/enable_anti_aliasing" ).toBool() ); + mMapCanvas->enableAntiAliasing( mySettings.value( QStringLiteral( "/qgis/enable_anti_aliasing" ) ).toBool() ); - double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble(); + double zoomFactor = mySettings.value( QStringLiteral( "/qgis/zoom_factor" ), 2 ).toDouble(); mMapCanvas->setWheelFactor( zoomFactor ); - mMapCanvas->setCachingEnabled( mySettings.value( "/qgis/enable_render_caching", true ).toBool() ); + mMapCanvas->setCachingEnabled( mySettings.value( QStringLiteral( "/qgis/enable_render_caching" ), true ).toBool() ); - mMapCanvas->setParallelRenderingEnabled( mySettings.value( "/qgis/parallel_rendering", true ).toBool() ); + mMapCanvas->setParallelRenderingEnabled( mySettings.value( QStringLiteral( "/qgis/parallel_rendering" ), true ).toBool() ); - mMapCanvas->setMapUpdateInterval( mySettings.value( "/qgis/map_update_interval", 250 ).toInt() ); + mMapCanvas->setMapUpdateInterval( mySettings.value( QStringLiteral( "/qgis/map_update_interval" ), 250 ).toInt() ); - if ( oldCapitalise != mySettings.value( "/qgis/capitaliseLayerName", QVariant( false ) ).toBool() ) + if ( oldCapitalise != mySettings.value( QStringLiteral( "/qgis/capitaliseLayerName" ), QVariant( false ) ).toBool() ) { // if the layer capitalization has changed, we need to update all layer names Q_FOREACH ( QgsMapLayer* layer, QgsMapLayerRegistry::instance()->mapLayers() ) @@ -9027,7 +9027,7 @@ void QgisApp::showOptionsDialog( QWidget *parent, const QString& currentPage ) mRasterFileFilter = QgsProviderRegistry::instance()->fileRasterFilters(); - if ( oldScales != mySettings.value( "Map/scales", PROJECT_SCALES ).toString() ) + if ( oldScales != mySettings.value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString() ) { mScaleWidget->updateScales(); } @@ -9036,13 +9036,13 @@ void QgisApp::showOptionsDialog( QWidget *parent, const QString& currentPage ) qobject_cast( mMapTools.mMeasureArea )->updateSettings(); qobject_cast( mMapTools.mMeasureAngle )->updateSettings(); - bool otfTransformAutoEnable = mySettings.value( "/Projections/otfTransformAutoEnable", true ).toBool(); + bool otfTransformAutoEnable = mySettings.value( QStringLiteral( "/Projections/otfTransformAutoEnable" ), true ).toBool(); mLayerTreeCanvasBridge->setAutoEnableCrsTransform( otfTransformAutoEnable ); - mMapCanvas->setSegmentationTolerance( mySettings.value( "/qgis/segmentationTolerance", "0.01745" ).toDouble() ); - mMapCanvas->setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType( mySettings.value( "/qgis/segmentationToleranceType", "0" ).toInt() ) ); + mMapCanvas->setSegmentationTolerance( mySettings.value( QStringLiteral( "/qgis/segmentationTolerance" ), "0.01745" ).toDouble() ); + mMapCanvas->setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType( mySettings.value( QStringLiteral( "/qgis/segmentationToleranceType" ), "0" ).toInt() ) ); - double factor = mySettings.value( "/qgis/magnifier_factor_default", 1.0 ).toDouble(); + double factor = mySettings.value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble(); mMagnifierWidget->setDefaultFactor( factor ); mMagnifierWidget->updateMagnification( factor ); } @@ -9179,7 +9179,7 @@ void QgisApp::adjustBrightnessContrast( int delta, bool updateBrightness ) void QgisApp::helpContents() { // We should really ship the HTML version of the docs local too. - openURL( QString( "https://docs.qgis.org/%1.%2/%3/docs/user_manual/" ) + openURL( QStringLiteral( "https://docs.qgis.org/%1.%2/%3/docs/user_manual/" ) .arg( Qgis::QGIS_VERSION_INT / 10000 ) .arg( Qgis::QGIS_VERSION_INT / 100 % 100 ) .arg( tr( "en", "documentation language" ) ), @@ -9190,11 +9190,11 @@ void QgisApp::apiDocumentation() { if ( QFileInfo::exists( QgsApplication::pkgDataPath() + "/doc/api/index.html" ) ) { - openURL( "api/index.html" ); + openURL( QStringLiteral( "api/index.html" ) ); } else { - openURL( "https://qgis.org/api/", false ); + openURL( QStringLiteral( "https://qgis.org/api/" ), false ); } } @@ -9209,7 +9209,7 @@ void QgisApp::supportProviders() void QgisApp::helpQgisHomePage() { - openURL( "https://qgis.org", false ); + openURL( QStringLiteral( "https://qgis.org" ), false ); } void QgisApp::openURL( QString url, bool useQgisDocDirectory ) @@ -9454,7 +9454,7 @@ void QgisApp::setExtent( const QgsRectangle& theRect ) */ bool QgisApp::saveDirty() { - QString whyDirty = ""; + QString whyDirty = QLatin1String( "" ); bool hasUnsavedEdits = false; // extra check to see if there are any vector layers with unsaved provider edits // to ensure user has opportunity to save any editing @@ -9479,9 +9479,9 @@ bool QgisApp::saveDirty() if ( hasUnsavedEdits ) { markDirty(); - whyDirty = "

                                                                                                                                                                                    "; + whyDirty = QStringLiteral( "

                                                                                                                                                                                    " ); whyDirty += tr( "Project has layer(s) in edit mode with unsaved edits, which will NOT be saved!" ); - whyDirty += "

                                                                                                                                                                                    "; + whyDirty += QLatin1String( "

                                                                                                                                                                                    " ); } } @@ -9493,7 +9493,7 @@ bool QgisApp::saveDirty() //QgsDebugMsg(QString("Map canvas is %1dirty").arg(mMapCanvas->isDirty() ? "" : "not ")); QSettings settings; - bool askThem = settings.value( "qgis/askToSaveProjectChanges", true ).toBool(); + bool askThem = settings.value( QStringLiteral( "qgis/askToSaveProjectChanges" ), true ).toBool(); if ( askThem && QgsProject::instance()->isDirty() && QgsMapLayerRegistry::instance()->count() > 0 ) { @@ -9526,12 +9526,12 @@ void QgisApp::closeProject() // unload the project macros before changing anything if ( mTrustedMacros ) { - QgsPythonRunner::run( "qgis.utils.unloadProjectMacros();" ); + QgsPythonRunner::run( QStringLiteral( "qgis.utils.unloadProjectMacros();" ) ); } mTrustedMacros = false; - mLegendExpressionFilterButton->setExpressionText( "" ); + mLegendExpressionFilterButton->setExpressionText( QLatin1String( "" ) ); mLegendExpressionFilterButton->setChecked( false ); mActionFilterLegend->setChecked( false ); @@ -10128,13 +10128,13 @@ void QgisApp::updateCrsStatusBar() mOnTheFlyProjectionStatusButton->setText( tr( "%1 (OTF)" ).arg( mOnTheFlyProjectionStatusButton->text() ) ); mOnTheFlyProjectionStatusButton->setToolTip( tr( "Current CRS: %1 (OTF enabled)" ).arg( mMapCanvas->mapSettings().destinationCrs().description() ) ); - mOnTheFlyProjectionStatusButton->setIcon( QgsApplication::getThemeIcon( "mIconProjectionEnabled.png" ) ); + mOnTheFlyProjectionStatusButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconProjectionEnabled.png" ) ) ); } else { mOnTheFlyProjectionStatusButton->setToolTip( tr( "Current CRS: %1 (OTF disabled)" ).arg( mMapCanvas->mapSettings().destinationCrs().description() ) ); - mOnTheFlyProjectionStatusButton->setIcon( QgsApplication::getThemeIcon( "mIconProjectionDisabled.png" ) ); + mOnTheFlyProjectionStatusButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconProjectionDisabled.png" ) ) ); } } @@ -10146,7 +10146,7 @@ void QgisApp::destinationCrsChanged() void QgisApp::hasCrsTransformEnabled( bool theFlag ) { // save this information to project - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectionsEnabled", ( theFlag ? 1 : 0 ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectionsEnabled" ), ( theFlag ? 1 : 0 ) ); updateCrsStatusBar(); } @@ -10515,7 +10515,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) mActionSelectPolygon->setEnabled( false ); mActionSelectFreehand->setEnabled( false ); mActionSelectRadius->setEnabled( false ); - mActionIdentify->setEnabled( QSettings().value( "/Map/identifyMode", 0 ).toInt() != 0 ); + mActionIdentify->setEnabled( QSettings().value( QStringLiteral( "/Map/identifyMode" ), 0 ).toInt() != 0 ); mActionSelectByExpression->setEnabled( false ); mActionSelectByForm->setEnabled( false ); mActionLabeling->setEnabled( false ); @@ -10698,8 +10698,8 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) if ( vlayer->geometryType() == QgsWkbTypes::PointGeometry ) { - mActionAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionCapturePoint.svg" ) ); - mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( "/mActionMoveFeaturePoint.svg" ) ); + mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePoint.svg" ) ) ); + mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeaturePoint.svg" ) ) ); mActionAddRing->setEnabled( false ); mActionFillRing->setEnabled( false ); @@ -10726,8 +10726,8 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) } else if ( vlayer->geometryType() == QgsWkbTypes::LineGeometry ) { - mActionAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionCaptureLine.svg" ) ); - mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( "/mActionMoveFeatureLine.svg" ) ); + mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCaptureLine.svg" ) ) ); + mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeatureLine.svg" ) ) ); mActionReshapeFeatures->setEnabled( isEditable && canChangeGeometry ); mActionSplitFeatures->setEnabled( isEditable && canAddFeatures ); @@ -10741,8 +10741,8 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) } else if ( vlayer->geometryType() == QgsWkbTypes::PolygonGeometry ) { - mActionAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionCapturePolygon.svg" ) ); - mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( "/mActionMoveFeature.svg" ) ); + mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePolygon.svg" ) ) ); + mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeature.svg" ) ) ); mActionAddRing->setEnabled( isEditable && canChangeGeometry ); mActionFillRing->setEnabled( isEditable && canChangeGeometry ); @@ -10755,7 +10755,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) } else if ( vlayer->geometryType() == QgsWkbTypes::NullGeometry ) { - mActionAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionNewTableRow.svg" ) ); + mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewTableRow.svg" ) ) ); } mActionOpenFieldCalc->setEnabled( true ); @@ -10853,7 +10853,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) mActionIdentify->setEnabled( true ); QSettings settings; - int identifyMode = settings.value( "/Map/identifyMode", 0 ).toInt(); + int identifyMode = settings.value( QStringLiteral( "/Map/identifyMode" ), 0 ).toInt(); if ( identifyMode == 0 ) { const QgsRasterLayer *rlayer = qobject_cast( layer ); @@ -10910,7 +10910,7 @@ void QgisApp::addRasterLayer() QStringList selectedFiles; QString e;//only for parameter correctness QString title = tr( "Open a GDAL Supported Raster Data Source" ); - QgisGui::openFilesRememberingFilter( "lastRasterFileFilter", mRasterFileFilter, selectedFiles, e, + QgisGui::openFilesRememberingFilter( QStringLiteral( "lastRasterFileFilter" ), mRasterFileFilter, selectedFiles, e, title ); if ( selectedFiles.isEmpty() ) @@ -10976,11 +10976,11 @@ QgsRasterLayer* QgisApp::addRasterLayerPrivate( // XXX ya know QgsRasterLayer can snip out the basename on its own; // XXX why do we have to pass it in for it? // ET : we may not be getting "normal" files here, so we still need the baseName argument - if ( !providerKey.isEmpty() && uri.endsWith( ".adf", Qt::CaseInsensitive ) ) + if ( !providerKey.isEmpty() && uri.endsWith( QLatin1String( ".adf" ), Qt::CaseInsensitive ) ) { QFileInfo fileInfo( uri ); QString dirName = fileInfo.path(); - layer = new QgsRasterLayer( dirName, QFileInfo( dirName ).completeBaseName(), QString( "gdal" ) ); + layer = new QgsRasterLayer( dirName, QFileInfo( dirName ).completeBaseName(), QStringLiteral( "gdal" ) ); } else if ( providerKey.isEmpty() ) layer = new QgsRasterLayer( uri, baseName ); // fi.completeBaseName()); @@ -11104,8 +11104,8 @@ bool QgisApp::addRasterLayers( QStringList const &theFileNameQStringList, bool g // if needed prompt for zipitem layers QString vsiPrefix = QgsZipItem::vsiPrefix( *myIterator ); - if ( ! myIterator->startsWith( "/vsi", Qt::CaseInsensitive ) && - ( vsiPrefix == "/vsizip/" || vsiPrefix == "/vsitar/" ) ) + if ( ! myIterator->startsWith( QLatin1String( "/vsi" ), Qt::CaseInsensitive ) && + ( vsiPrefix == QLatin1String( "/vsizip/" ) || vsiPrefix == QLatin1String( "/vsitar/" ) ) ) { if ( askUserForZipItemLayers( *myIterator ) ) continue; @@ -11124,7 +11124,7 @@ bool QgisApp::addRasterLayers( QStringList const &theFileNameQStringList, bool g //time to prevent the user selecting all adfs in 1 dir which //actually represent 1 coverate, - if ( myFileInfo.fileName().toLower().endsWith( ".adf" ) ) + if ( myFileInfo.fileName().toLower().endsWith( QLatin1String( ".adf" ) ) ) { break; } @@ -11317,7 +11317,7 @@ void QgisApp::oldProjectVersionWarning( const QString& oldVersion ) Q_UNUSED( oldVersion ); QSettings settings; - if ( settings.value( "/qgis/warnOldProjectVersion", QVariant( true ) ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/warnOldProjectVersion" ), QVariant( true ) ).toBool() ) { QString smalltext = tr( "This project file was saved by an older version of QGIS." " When saving this project file, QGIS will update it to the latest version, " @@ -11369,13 +11369,13 @@ void QgisApp::projectChanged( const QDomDocument &doc ) if ( !prevProjectDir.isNull() ) { QString prev = prevProjectDir; - expr = QString( "sys.path.remove(u'%1'); " ).arg( prev.replace( '\'', "\\'" ) ); + expr = QStringLiteral( "sys.path.remove(u'%1'); " ).arg( prev.replace( '\'', QLatin1String( "\\'" ) ) ); } prevProjectDir = fi.canonicalPath(); QString prev = prevProjectDir; - expr += QString( "sys.path.append(u'%1')" ).arg( prev.replace( '\'', "\\'" ) ); + expr += QStringLiteral( "sys.path.append(u'%1')" ).arg( prev.replace( '\'', QLatin1String( "\\'" ) ) ); QgsPythonRunner::run( expr ); } @@ -11395,9 +11395,9 @@ void QgisApp::writeProject( QDomDocument &doc ) QDomElement oldLegendElem = QgsLayerTreeUtils::writeOldLegend( doc, QgsLayerTree::toGroup( clonedRoot ), mLayerTreeCanvasBridge->hasCustomLayerOrder(), mLayerTreeCanvasBridge->customLayerOrder() ); delete clonedRoot; - doc.firstChildElement( "qgis" ).appendChild( oldLegendElem ); + doc.firstChildElement( QStringLiteral( "qgis" ) ).appendChild( oldLegendElem ); - QgsProject::instance()->writeEntry( "Legend", "filterByMap", static_cast< bool >( layerTreeView()->layerTreeModel()->legendFilterMapSettings() ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "Legend" ), QStringLiteral( "filterByMap" ), static_cast< bool >( layerTreeView()->layerTreeModel()->legendFilterMapSettings() ) ); projectChanged( doc ); } @@ -11561,7 +11561,7 @@ void QgisApp::namAuthenticationRequired( QNetworkReply *inReply, QAuthenticator { QMutexLocker lock( QgsCredentials::instance()->mutex() ); ok = QgsCredentials::instance()->get( - QString( "%1 at %2" ).arg( auth->realm(), reply->url().host() ), + QStringLiteral( "%1 at %2" ).arg( auth->realm(), reply->url().host() ), username, password, tr( "Authentication required" ) ); } @@ -11578,7 +11578,7 @@ void QgisApp::namAuthenticationRequired( QNetworkReply *inReply, QAuthenticator { QMutexLocker lock( QgsCredentials::instance()->mutex() ); QgsCredentials::instance()->put( - QString( "%1 at %2" ).arg( auth->realm(), reply->url().host() ), + QStringLiteral( "%1 at %2" ).arg( auth->realm(), reply->url().host() ), username, QString::null ); } } @@ -11587,7 +11587,7 @@ void QgisApp::namAuthenticationRequired( QNetworkReply *inReply, QAuthenticator { QMutexLocker lock( QgsCredentials::instance()->mutex() ); QgsCredentials::instance()->put( - QString( "%1 at %2" ).arg( auth->realm(), reply->url().host() ), + QStringLiteral( "%1 at %2" ).arg( auth->realm(), reply->url().host() ), username, password ); } @@ -11599,10 +11599,10 @@ void QgisApp::namAuthenticationRequired( QNetworkReply *inReply, QAuthenticator void QgisApp::namProxyAuthenticationRequired( const QNetworkProxy &proxy, QAuthenticator *auth ) { QSettings settings; - if ( !settings.value( "proxy/proxyEnabled", false ).toBool() || - settings.value( "proxy/proxyType", "" ).toString() == "DefaultProxy" ) + if ( !settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool() || + settings.value( QStringLiteral( "proxy/proxyType" ), "" ).toString() == QLatin1String( "DefaultProxy" ) ) { - auth->setUser( "" ); + auth->setUser( QLatin1String( "" ) ); return; } @@ -11616,7 +11616,7 @@ void QgisApp::namProxyAuthenticationRequired( const QNetworkProxy &proxy, QAuthe { QMutexLocker lock( QgsCredentials::instance()->mutex() ); ok = QgsCredentials::instance()->get( - QString( "proxy %1:%2 [%3]" ).arg( proxy.hostName() ).arg( proxy.port() ).arg( auth->realm() ), + QStringLiteral( "proxy %1:%2 [%3]" ).arg( proxy.hostName() ).arg( proxy.port() ).arg( auth->realm() ), username, password, tr( "Proxy authentication required" ) ); } @@ -11630,7 +11630,7 @@ void QgisApp::namProxyAuthenticationRequired( const QNetworkProxy &proxy, QAuthe { QMutexLocker lock( QgsCredentials::instance()->mutex() ); QgsCredentials::instance()->put( - QString( "proxy %1:%2 [%3]" ).arg( proxy.hostName() ).arg( proxy.port() ).arg( auth->realm() ), + QStringLiteral( "proxy %1:%2 [%3]" ).arg( proxy.hostName() ).arg( proxy.port() ).arg( auth->realm() ), username, QString::null ); } } @@ -11638,7 +11638,7 @@ void QgisApp::namProxyAuthenticationRequired( const QNetworkProxy &proxy, QAuthe { QMutexLocker lock( QgsCredentials::instance()->mutex() ); QgsCredentials::instance()->put( - QString( "proxy %1:%2 [%3]" ).arg( proxy.hostName() ).arg( proxy.port() ).arg( auth->realm() ), + QStringLiteral( "proxy %1:%2 [%3]" ).arg( proxy.hostName() ).arg( proxy.port() ).arg( auth->realm() ), username, password ); } @@ -11652,7 +11652,7 @@ void QgisApp::namSslErrors( QNetworkReply *reply, const QList &errors { // stop the timeout timer, or app crashes if the user (or slot) takes longer than // singleshot timeout and tries to update the closed QNetworkReply - QTimer *timer = reply->findChild( "timeoutTimer" ); + QTimer *timer = reply->findChild( QStringLiteral( "timeoutTimer" ) ); if ( timer ) { QgsDebugMsg( "Stopping network reply timeout" ); @@ -11661,12 +11661,12 @@ void QgisApp::namSslErrors( QNetworkReply *reply, const QList &errors QgsDebugMsg( QString( "SSL errors occurred accessing URL:\n%1" ).arg( reply->request().url().toString() ) ); - QString hostport( QString( "%1:%2" ) + QString hostport( QStringLiteral( "%1:%2" ) .arg( reply->url().host() ) .arg( reply->url().port() != -1 ? reply->url().port() : 443 ) .trimmed() ); QString digest( QgsAuthCertUtils::shaHexForCert( reply->sslConfiguration().peerCertificate() ) ); - QString dgsthostport( QString( "%1:%2" ).arg( digest, hostport ) ); + QString dgsthostport( QStringLiteral( "%1:%2" ).arg( digest, hostport ) ); const QHash > &errscache( QgsAuthManager::instance()->getIgnoredSslErrorCache() ); @@ -11719,12 +11719,12 @@ void QgisApp::namSslErrors( QNetworkReply *reply, const QList &errors if ( reply ) { QSettings s; - QTimer *timer = reply->findChild( "timeoutTimer" ); + QTimer *timer = reply->findChild( QStringLiteral( "timeoutTimer" ) ); if ( timer ) { QgsDebugMsg( "Restarting network reply timeout" ); timer->setSingleShot( true ); - timer->start( s.value( "/qgis/networkAndProxy/networkTimeout", "60000" ).toInt() ); + timer->start( s.value( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), "60000" ).toInt() ); } } } @@ -11764,7 +11764,7 @@ void QgisApp::eraseAuthenticationDatabase() // Apparently, as of QGIS 2.9, the only way to query that the project is in a // layer-loading state is via a custom property of the project's layer tree. QgsLayerTreeGroup *layertree( QgsProject::instance()->layerTreeRoot() ); - if ( layertree && layertree->customProperty( "loading" ).toBool() ) + if ( layertree && layertree->customProperty( QStringLiteral( "loading" ) ).toBool() ) { QgsDebugMsg( "Project loading, skipping auth db erase" ); QgsAuthManager::instance()->setScheduledAuthDbEraseRequestEmitted( false ); @@ -11805,57 +11805,57 @@ void QgisApp::toolButtonActionTriggered( QAction *action ) QSettings settings; if ( action == mActionSelectFeatures ) - settings.setValue( "/UI/selectTool", 1 ); + settings.setValue( QStringLiteral( "/UI/selectTool" ), 1 ); else if ( action == mActionSelectRadius ) - settings.setValue( "/UI/selectTool", 2 ); + settings.setValue( QStringLiteral( "/UI/selectTool" ), 2 ); else if ( action == mActionSelectPolygon ) - settings.setValue( "/UI/selectTool", 3 ); + settings.setValue( QStringLiteral( "/UI/selectTool" ), 3 ); else if ( action == mActionSelectFreehand ) - settings.setValue( "/UI/selectTool", 4 ); + settings.setValue( QStringLiteral( "/UI/selectTool" ), 4 ); else if ( action == mActionMeasure ) - settings.setValue( "/UI/measureTool", 0 ); + settings.setValue( QStringLiteral( "/UI/measureTool" ), 0 ); else if ( action == mActionMeasureArea ) - settings.setValue( "/UI/measureTool", 1 ); + settings.setValue( QStringLiteral( "/UI/measureTool" ), 1 ); else if ( action == mActionMeasureAngle ) - settings.setValue( "/UI/measureTool", 2 ); + settings.setValue( QStringLiteral( "/UI/measureTool" ), 2 ); else if ( action == mActionTextAnnotation ) - settings.setValue( "/UI/annotationTool", 0 ); + settings.setValue( QStringLiteral( "/UI/annotationTool" ), 0 ); else if ( action == mActionFormAnnotation ) - settings.setValue( "/UI/annotationTool", 1 ); + settings.setValue( QStringLiteral( "/UI/annotationTool" ), 1 ); else if ( action == mActionHtmlAnnotation ) - settings.setValue( "/UI/annotationTool", 2 ); + settings.setValue( QStringLiteral( "/UI/annotationTool" ), 2 ); else if ( action == mActionSvgAnnotation ) - settings.setValue( "UI/annotationTool", 3 ); + settings.setValue( QStringLiteral( "UI/annotationTool" ), 3 ); else if ( action == mActionAnnotation ) - settings.setValue( "/UI/annotationTool", 4 ); + settings.setValue( QStringLiteral( "/UI/annotationTool" ), 4 ); else if ( action == mActionNewSpatiaLiteLayer ) - settings.setValue( "/UI/defaultNewLayer", 0 ); + settings.setValue( QStringLiteral( "/UI/defaultNewLayer" ), 0 ); else if ( action == mActionNewVectorLayer ) - settings.setValue( "/UI/defaultNewLayer", 1 ); + settings.setValue( QStringLiteral( "/UI/defaultNewLayer" ), 1 ); else if ( action == mActionNewMemoryLayer ) - settings.setValue( "/UI/defaultNewLayer", 2 ); + settings.setValue( QStringLiteral( "/UI/defaultNewLayer" ), 2 ); else if ( action == mActionNewGeoPackageLayer ) - settings.setValue( "/UI/defaultNewLayer", 3 ); + settings.setValue( QStringLiteral( "/UI/defaultNewLayer" ), 3 ); else if ( action == mActionRotatePointSymbols ) - settings.setValue( "/UI/defaultPointSymbolAction", 0 ); + settings.setValue( QStringLiteral( "/UI/defaultPointSymbolAction" ), 0 ); else if ( action == mActionOffsetPointSymbol ) - settings.setValue( "/UI/defaultPointSymbolAction", 1 ); + settings.setValue( QStringLiteral( "/UI/defaultPointSymbolAction" ), 1 ); else if ( mActionAddPgLayer && action == mActionAddPgLayer ) - settings.setValue( "/UI/defaultAddDbLayerAction", 0 ); + settings.setValue( QStringLiteral( "/UI/defaultAddDbLayerAction" ), 0 ); else if ( mActionAddMssqlLayer && action == mActionAddMssqlLayer ) - settings.setValue( "/UI/defaultAddDbLayerAction", 1 ); + settings.setValue( QStringLiteral( "/UI/defaultAddDbLayerAction" ), 1 ); else if ( mActionAddDb2Layer && action == mActionAddDb2Layer ) - settings.setValue( "/UI/defaultAddDbLayerAction", 2 ); + settings.setValue( QStringLiteral( "/UI/defaultAddDbLayerAction" ), 2 ); else if ( mActionAddOracleLayer && action == mActionAddOracleLayer ) - settings.setValue( "/UI/defaultAddDbLayerAction", 3 ); + settings.setValue( QStringLiteral( "/UI/defaultAddDbLayerAction" ), 3 ); else if ( action == mActionAddWfsLayer ) - settings.setValue( "/UI/defaultFeatureService", 0 ); + settings.setValue( QStringLiteral( "/UI/defaultFeatureService" ), 0 ); else if ( action == mActionAddAfsLayer ) - settings.setValue( "/UI/defaultFeatureService", 1 ); + settings.setValue( QStringLiteral( "/UI/defaultFeatureService" ), 1 ); else if ( action == mActionAddWmsLayer ) - settings.setValue( "/UI/defaultMapService", 0 ); + settings.setValue( QStringLiteral( "/UI/defaultMapService" ), 0 ); else if ( action == mActionAddAmsLayer ) - settings.setValue( "/UI/defaultMapService", 1 ); + settings.setValue( QStringLiteral( "/UI/defaultMapService" ), 1 ); bt->setDefaultAction( action ); } @@ -11889,7 +11889,7 @@ QMenu* QgisApp::createPopupMenu() qSort( panels.begin(), panels.end(), cmpByText_ ); QWidgetAction* panelstitle = new QWidgetAction( menu ); - QLabel* plabel = new QLabel( QString( "%1" ).arg( tr( "Panels" ) ) ); + QLabel* plabel = new QLabel( QStringLiteral( "%1" ).arg( tr( "Panels" ) ) ); plabel->setMargin( 3 ); plabel->setAlignment( Qt::AlignHCenter ); panelstitle->setDefaultWidget( plabel ); @@ -11900,7 +11900,7 @@ QMenu* QgisApp::createPopupMenu() } menu->addSeparator(); QWidgetAction* toolbarstitle = new QWidgetAction( menu ); - QLabel* tlabel = new QLabel( QString( "%1" ).arg( tr( "Toolbars" ) ) ); + QLabel* tlabel = new QLabel( QStringLiteral( "%1" ).arg( tr( "Toolbars" ) ) ); tlabel->setMargin( 3 ); tlabel->setAlignment( Qt::AlignHCenter ); toolbarstitle->setDefaultWidget( tlabel ); diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index 26b15e59b467..315cbe9d4dc0 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -230,7 +230,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void addUserInputWidget( QWidget* widget ); //! Set theme (icons) - void setTheme( const QString& themeName = "default" ); + void setTheme( const QString& themeName = QStringLiteral( "default" ) ); void setIconSizes( int size ); diff --git a/src/app/qgisappstylesheet.cpp b/src/app/qgisappstylesheet.cpp index 2c4295182fb6..247443833d24 100644 --- a/src/app/qgisappstylesheet.cpp +++ b/src/app/qgisappstylesheet.cpp @@ -49,10 +49,10 @@ QMap QgisAppStyleSheet::defaultOptions() QSettings settings; // handle move from old QSettings group (/) to new (/qgis/stylesheet) // NOTE: don't delete old QSettings keys, in case user is also running older QGIS - QVariant oldFontPointSize = settings.value( "/fontPointSize" ); - QVariant oldFontFamily = settings.value( "/fontFamily" ); + QVariant oldFontPointSize = settings.value( QStringLiteral( "/fontPointSize" ) ); + QVariant oldFontFamily = settings.value( QStringLiteral( "/fontFamily" ) ); - settings.beginGroup( "qgis/stylesheet" ); + settings.beginGroup( QStringLiteral( "qgis/stylesheet" ) ); int fontSize = mDefaultFont.pointSize(); if ( mAndroidOS ) @@ -60,19 +60,19 @@ QMap QgisAppStyleSheet::defaultOptions() // TODO: find a better default fontsize maybe using DPI detection or so (from Marco Bernasocchi commit) fontSize = 8; } - if ( oldFontPointSize.isValid() && !settings.value( "fontPointSize" ).isValid() ) + if ( oldFontPointSize.isValid() && !settings.value( QStringLiteral( "fontPointSize" ) ).isValid() ) { fontSize = oldFontPointSize.toInt(); } QgsDebugMsg( QString( "fontPointSize: %1" ).arg( fontSize ) ); - opts.insert( "fontPointSize", settings.value( "fontPointSize", QVariant( fontSize ) ) ); + opts.insert( QStringLiteral( "fontPointSize" ), settings.value( QStringLiteral( "fontPointSize" ), QVariant( fontSize ) ) ); QString fontFamily = mDefaultFont.family(); - if ( oldFontFamily.isValid() && !settings.value( "fontFamily" ).isValid() ) + if ( oldFontFamily.isValid() && !settings.value( QStringLiteral( "fontFamily" ) ).isValid() ) { fontFamily = oldFontFamily.toString(); } - fontFamily = settings.value( "fontFamily", QVariant( fontFamily ) ).toString(); + fontFamily = settings.value( QStringLiteral( "fontFamily" ), QVariant( fontFamily ) ).toString(); // make sure family exists on system if ( fontFamily != mDefaultFont.family() ) { @@ -85,14 +85,14 @@ QMap QgisAppStyleSheet::defaultOptions() delete tempFont; } QgsDebugMsg( QString( "fontFamily: %1" ).arg( fontFamily ) ); - opts.insert( "fontFamily", QVariant( fontFamily ) ); + opts.insert( QStringLiteral( "fontFamily" ), QVariant( fontFamily ) ); bool gbxCustom = ( mMacStyle ? true : false ); - opts.insert( "groupBoxCustom", settings.value( "groupBoxCustom", QVariant( gbxCustom ) ) ); + opts.insert( QStringLiteral( "groupBoxCustom" ), settings.value( QStringLiteral( "groupBoxCustom" ), QVariant( gbxCustom ) ) ); settings.endGroup(); // "qgis/stylesheet" - opts.insert( "iconSize", settings.value( "/IconSize", QGIS_ICON_SIZE ) ); + opts.insert( QStringLiteral( "iconSize" ), settings.value( QStringLiteral( "/IconSize" ), QGIS_ICON_SIZE ) ); return opts; } @@ -102,51 +102,51 @@ void QgisAppStyleSheet::buildStyleSheet( const QMap& opts ) QString ss; // QgisApp-wide font - QString fontSize = opts.value( "fontPointSize" ).toString(); + QString fontSize = opts.value( QStringLiteral( "fontPointSize" ) ).toString(); QgsDebugMsg( QString( "fontPointSize: %1" ).arg( fontSize ) ); if ( fontSize.isEmpty() ) { return; } - QString fontFamily = opts.value( "fontFamily" ).toString(); + QString fontFamily = opts.value( QStringLiteral( "fontFamily" ) ).toString(); QgsDebugMsg( QString( "fontFamily: %1" ).arg( fontFamily ) ); if ( fontFamily.isEmpty() ) { return; } - ss += QString( "* { font: %1pt \"%2\"} " ).arg( fontSize, fontFamily ); + ss += QStringLiteral( "* { font: %1pt \"%2\"} " ).arg( fontSize, fontFamily ); // QGroupBox and QgsCollapsibleGroupBox, mostly for Ubuntu and Mac - bool gbxCustom = opts.value( "groupBoxCustom" ).toBool(); + bool gbxCustom = opts.value( QStringLiteral( "groupBoxCustom" ) ).toBool(); QgsDebugMsg( QString( "groupBoxCustom: %1" ).arg( gbxCustom ) ); - ss += "QGroupBox{"; + ss += QLatin1String( "QGroupBox{" ); // doesn't work for QGroupBox::title - ss += QString( "color: rgb(%1,%1,%1);" ).arg( mMacStyle ? 25 : 60 ); - ss += "font-weight: bold;"; + ss += QStringLiteral( "color: rgb(%1,%1,%1);" ).arg( mMacStyle ? 25 : 60 ); + ss += QLatin1String( "font-weight: bold;" ); if ( gbxCustom ) { - ss += QString( "background-color: rgba(0,0,0,%1%);" ) - .arg( mWinOS && mStyle.startsWith( "windows" ) ? 0 : 3 ); - ss += "border: 1px solid rgba(0,0,0,20%);"; - ss += "border-radius: 5px;"; - ss += "margin-top: 2.5ex;"; - ss += QString( "margin-bottom: %1ex;" ).arg( mMacStyle ? 1.5 : 1 ); + ss += QStringLiteral( "background-color: rgba(0,0,0,%1%);" ) + .arg( mWinOS && mStyle.startsWith( QLatin1String( "windows" ) ) ? 0 : 3 ); + ss += QLatin1String( "border: 1px solid rgba(0,0,0,20%);" ); + ss += QLatin1String( "border-radius: 5px;" ); + ss += QLatin1String( "margin-top: 2.5ex;" ); + ss += QStringLiteral( "margin-bottom: %1ex;" ).arg( mMacStyle ? 1.5 : 1 ); } - ss += "} "; + ss += QLatin1String( "} " ); if ( gbxCustom ) { - ss += "QGroupBox:flat{"; - ss += "background-color: rgba(0,0,0,0);"; - ss += "border: rgba(0,0,0,0);"; - ss += "} "; - - ss += "QGroupBox::title{"; - ss += "subcontrol-origin: margin;"; - ss += "subcontrol-position: top left;"; - ss += "margin-left: 6px;"; - if ( !( mWinOS && mStyle.startsWith( "windows" ) ) && !mOxyStyle ) + ss += QLatin1String( "QGroupBox:flat{" ); + ss += QLatin1String( "background-color: rgba(0,0,0,0);" ); + ss += QLatin1String( "border: rgba(0,0,0,0);" ); + ss += QLatin1String( "} " ); + + ss += QLatin1String( "QGroupBox::title{" ); + ss += QLatin1String( "subcontrol-origin: margin;" ); + ss += QLatin1String( "subcontrol-position: top left;" ); + ss += QLatin1String( "margin-left: 6px;" ); + if ( !( mWinOS && mStyle.startsWith( QLatin1String( "windows" ) ) ) && !mOxyStyle ) { - ss += "background-color: rgba(0,0,0,0);"; + ss += QLatin1String( "background-color: rgba(0,0,0,0);" ); } - ss += "} "; + ss += QLatin1String( "} " ); } //sidebar style @@ -183,7 +183,7 @@ void QgisAppStyleSheet::buildStyleSheet( const QMap& opts ) void QgisAppStyleSheet::saveToSettings( const QMap& opts ) { QSettings settings; - settings.beginGroup( "qgis/stylesheet" ); + settings.beginGroup( QStringLiteral( "qgis/stylesheet" ) ); QMap::const_iterator opt = opts.constBegin(); while ( opt != opts.constEnd() ) @@ -199,16 +199,16 @@ void QgisAppStyleSheet::setActiveValues() mStyle = qApp->style()->objectName(); // active style name (lowercase) QgsDebugMsg( QString( "Style name: %1" ).arg( mStyle ) ); - mMotifStyle = mStyle.contains( "motif" ) ? true : false; // motif - mCdeStyle = mStyle.contains( "cde" ) ? true : false; // cde - mPlastqStyle = mStyle.contains( "plastique" ) ? true : false; // plastique - mCleanLkStyle = mStyle.contains( "cleanlooks" ) ? true : false; // cleanlooks - mGtkStyle = mStyle.contains( "gtk" ) ? true : false; // gtk+ - mWinStyle = mStyle.contains( "windows" ) ? true : false; // windows - mWinXpStyle = mStyle.contains( "windowsxp" ) ? true : false; // windowsxp - mWinVistaStyle = mStyle.contains( "windowsvista" ) ? true : false; // windowsvista - mMacStyle = mStyle.contains( "macintosh" ) ? true : false; // macintosh (aqua) - mOxyStyle = mStyle.contains( "oxygen" ) ? true : false; // oxygen + mMotifStyle = mStyle.contains( QLatin1String( "motif" ) ) ? true : false; // motif + mCdeStyle = mStyle.contains( QLatin1String( "cde" ) ) ? true : false; // cde + mPlastqStyle = mStyle.contains( QLatin1String( "plastique" ) ) ? true : false; // plastique + mCleanLkStyle = mStyle.contains( QLatin1String( "cleanlooks" ) ) ? true : false; // cleanlooks + mGtkStyle = mStyle.contains( QLatin1String( "gtk" ) ) ? true : false; // gtk+ + mWinStyle = mStyle.contains( QLatin1String( "windows" ) ) ? true : false; // windows + mWinXpStyle = mStyle.contains( QLatin1String( "windowsxp" ) ) ? true : false; // windowsxp + mWinVistaStyle = mStyle.contains( QLatin1String( "windowsvista" ) ) ? true : false; // windowsvista + mMacStyle = mStyle.contains( QLatin1String( "macintosh" ) ) ? true : false; // macintosh (aqua) + mOxyStyle = mStyle.contains( QLatin1String( "oxygen" ) ) ? true : false; // oxygen mDefaultFont = qApp->font(); // save before it is changed in any way diff --git a/src/app/qgsabout.cpp b/src/app/qgsabout.cpp index 83367c05e672..ba9538574faa 100644 --- a/src/app/qgsabout.cpp +++ b/src/app/qgsabout.cpp @@ -32,11 +32,11 @@ QgsAbout::QgsAbout( QWidget *parent ) : QgsOptionsDialogBase( "about", parent, Qt::WindowSystemMenuHint ) // Modeless dialog with close button only #else QgsAbout::QgsAbout( QWidget *parent ) - : QgsOptionsDialogBase( "about", parent ) // Normal dialog in non Mac-OS + : QgsOptionsDialogBase( QStringLiteral( "about" ), parent ) // Normal dialog in non Mac-OS #endif { setupUi( this ); - initOptionsBase( true, QString( "%1 - %2 Bit" ).arg( windowTitle() ).arg( QSysInfo::WordSize ) ); + initOptionsBase( true, QStringLiteral( "%1 - %2 Bit" ).arg( windowTitle() ).arg( QSysInfo::WordSize ) ); init(); } @@ -190,7 +190,7 @@ void QgsAbout::init() #endif if ( translatorFile.open( QIODevice::ReadOnly ) ) { - QString translatorHTML = ""; + QString translatorHTML = QLatin1String( "" ); QTextStream translatorStream( &translatorFile ); // Always use UTF-8 translatorStream.setCodec( "UTF-8" ); @@ -245,15 +245,15 @@ void QgsAbout::setPluginInfo() myString += QgsAuthMethodRegistry::instance()->pluginList( true ); //qt database plugins myString += "" + tr( "Available Qt Database Plugins" ) + "
                                                                                                                                                                                    "; - myString += "
                                                                                                                                                                                      \n
                                                                                                                                                                                    1. \n"; + myString += QLatin1String( "
                                                                                                                                                                                        \n
                                                                                                                                                                                      1. \n" ); QStringList myDbDriverList = QSqlDatabase::drivers(); - myString += myDbDriverList.join( "
                                                                                                                                                                                      2. \n
                                                                                                                                                                                      3. " ); - myString += "
                                                                                                                                                                                      4. \n
                                                                                                                                                                                      \n"; + myString += myDbDriverList.join( QStringLiteral( "
                                                                                                                                                                                    2. \n
                                                                                                                                                                                    3. " ) ); + myString += QLatin1String( "
                                                                                                                                                                                    4. \n
                                                                                                                                                                                    \n" ); //qt image plugins myString += "" + tr( "Available Qt Image Plugins" ) + "
                                                                                                                                                                                    "; myString += tr( "Qt Image Plugin Search Paths
                                                                                                                                                                                    " ); - myString += QApplication::libraryPaths().join( "
                                                                                                                                                                                    " ); - myString += "
                                                                                                                                                                                      \n
                                                                                                                                                                                    1. \n"; + myString += QApplication::libraryPaths().join( QStringLiteral( "
                                                                                                                                                                                      " ) ); + myString += QLatin1String( "
                                                                                                                                                                                        \n
                                                                                                                                                                                      1. \n" ); QList myImageFormats = QImageReader::supportedImageFormats(); QList::const_iterator myIterator = myImageFormats.begin(); while ( myIterator != myImageFormats.end() ) @@ -262,7 +262,7 @@ void QgsAbout::setPluginInfo() myString += myFormat + "
                                                                                                                                                                                      2. \n
                                                                                                                                                                                      3. "; ++myIterator; } - myString += "
                                                                                                                                                                                      4. \n
                                                                                                                                                                                      \n"; + myString += QLatin1String( "
                                                                                                                                                                                    2. \n
                                                                                                                                                                                    \n" ); QString myStyle = QgsApplication::reportStyleSheet(); txtProviders->clear(); @@ -272,12 +272,12 @@ void QgsAbout::setPluginInfo() void QgsAbout::on_btnQgisUser_clicked() { - openUrl( QString( "http://lists.osgeo.org/mailman/listinfo/qgis-user" ) ); + openUrl( QStringLiteral( "http://lists.osgeo.org/mailman/listinfo/qgis-user" ) ); } void QgsAbout::on_btnQgisHome_clicked() { - openUrl( QString( "http://qgis.org" ) ); + openUrl( QStringLiteral( "http://qgis.org" ) ); } void QgsAbout::openUrl( const QUrl &url ) @@ -303,14 +303,14 @@ QString QgsAbout::fileSystemSafe( const QString& fileName ) if ( c > 0x7f ) { - result = result + QString( "%1" ).arg( c, 2, 16, QChar( '0' ) ); + result = result + QStringLiteral( "%1" ).arg( c, 2, 16, QChar( '0' ) ); } else { result = result + QString( c ); } } - result.replace( QRegExp( "[^a-z0-9A-Z]" ), "_" ); + result.replace( QRegExp( "[^a-z0-9A-Z]" ), QStringLiteral( "_" ) ); QgsDebugMsg( result ); return result; diff --git a/src/app/qgsaddattrdialog.cpp b/src/app/qgsaddattrdialog.cpp index 1b29e33ba32e..e79814e27ef4 100644 --- a/src/app/qgsaddattrdialog.cpp +++ b/src/app/qgsaddattrdialog.cpp @@ -24,7 +24,7 @@ QgsAddAttrDialog::QgsAddAttrDialog( QgsVectorLayer *vlayer, QWidget *parent, Qt::WindowFlags fl ) : QDialog( parent, fl ) - , mIsShapeFile( vlayer && vlayer->providerType() == "ogr" && vlayer->storageType() == "ESRI Shapefile" ) + , mIsShapeFile( vlayer && vlayer->providerType() == QLatin1String( "ogr" ) && vlayer->storageType() == QLatin1String( "ESRI Shapefile" ) ) { setupUi( this ); @@ -91,7 +91,7 @@ void QgsAddAttrDialog::setPrecisionMinMax() void QgsAddAttrDialog::accept() { - if ( mIsShapeFile && mNameEdit->text().toLower() == "shape" ) + if ( mIsShapeFile && mNameEdit->text().toLower() == QLatin1String( "shape" ) ) { QMessageBox::warning( this, tr( "Warning" ), tr( "Invalid field name. This field name is reserved and cannot be used." ) ); diff --git a/src/app/qgsaddtaborgroup.cpp b/src/app/qgsaddtaborgroup.cpp index 00cfda280468..fcae83512225 100644 --- a/src/app/qgsaddtaborgroup.cpp +++ b/src/app/qgsaddtaborgroup.cpp @@ -52,7 +52,7 @@ QgsAddTabOrGroup::QgsAddTabOrGroup( QgsVectorLayer *lyr, const QList < TabPair > connect( mTabButton, SIGNAL( toggled( bool ) ), this, SLOT( on_mTabButton_toggled( bool ) ) ); connect( mGroupButton, SIGNAL( toggled( bool ) ), this, SLOT( on_mGroupButton_toggled( bool ) ) ); - mColumnCountSpinBox->setValue( QSettings().value( "/qgis/attributeForm/defaultTabColumnCount", 1 ).toInt() ); + mColumnCountSpinBox->setValue( QSettings().value( QStringLiteral( "/qgis/attributeForm/defaultTabColumnCount" ), 1 ).toInt() ); setWindowTitle( tr( "Add tab or group for %1" ).arg( mLayer->name() ) ); } // QgsVectorLayerProperties ctor @@ -88,11 +88,11 @@ void QgsAddTabOrGroup::accept() { if ( mGroupButton->isChecked() ) { - QSettings().setValue( "/qgis/attributeForm/defaultGroupColumnCount", mColumnCountSpinBox->value() ); + QSettings().setValue( QStringLiteral( "/qgis/attributeForm/defaultGroupColumnCount" ), mColumnCountSpinBox->value() ); } else { - QSettings().setValue( "/qgis/attributeForm/defaultTabColumnCount", mColumnCountSpinBox->value() ); + QSettings().setValue( QStringLiteral( "/qgis/attributeForm/defaultTabColumnCount" ), mColumnCountSpinBox->value() ); } } @@ -105,7 +105,7 @@ void QgsAddTabOrGroup::on_mGroupButton_toggled( bool checked ) if ( checked ) { - mColumnCountSpinBox->setValue( QSettings().value( "/qgis/attributeForm/defaultGroupColumnCount", 1 ).toInt() ); + mColumnCountSpinBox->setValue( QSettings().value( QStringLiteral( "/qgis/attributeForm/defaultGroupColumnCount" ), 1 ).toInt() ); } } @@ -113,5 +113,5 @@ void QgsAddTabOrGroup::on_mTabButton_toggled( bool checked ) { mTabList->setEnabled( !checked ); if ( checked ) - mColumnCountSpinBox->setValue( QSettings().value( "/qgis/attributeForm/defaultTabColumnCount", 1 ).toInt() ); + mColumnCountSpinBox->setValue( QSettings().value( QStringLiteral( "/qgis/attributeForm/defaultTabColumnCount" ), 1 ).toInt() ); } diff --git a/src/app/qgsalignrasterdialog.cpp b/src/app/qgsalignrasterdialog.cpp index 2d4437ff295c..14fb627beaa6 100644 --- a/src/app/qgsalignrasterdialog.cpp +++ b/src/app/qgsalignrasterdialog.cpp @@ -164,7 +164,7 @@ void QgsAlignRasterDialog::updateAlignedRasterInfo() } QSize size = mAlign->alignedRasterSize(); - QString msg = QString( "%1 x %2" ).arg( size.width() ).arg( size.height() ); + QString msg = QStringLiteral( "%1 x %2" ).arg( size.width() ).arg( size.height() ); mEditOutputSize->setText( msg ); } @@ -459,16 +459,16 @@ void QgsAlignRasterLayerConfigDialog::setItem( const QString& inputFilename, con void QgsAlignRasterLayerConfigDialog::browseOutputFilename() { QSettings settings; - QString dirName = editOutput->text().isEmpty() ? settings.value( "/UI/lastRasterFileDir", QDir::homePath() ).toString() : editOutput->text(); + QString dirName = editOutput->text().isEmpty() ? settings.value( QStringLiteral( "/UI/lastRasterFileDir" ), QDir::homePath() ).toString() : editOutput->text(); QString fileName = QFileDialog::getSaveFileName( this, tr( "Select output file" ), dirName, tr( "GeoTIFF" ) + " (*.tif *.tiff *.TIF *.TIFF)" ); if ( !fileName.isEmpty() ) { // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".tif", Qt::CaseInsensitive ) && !fileName.endsWith( ".tiff", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".tif" ), Qt::CaseInsensitive ) && !fileName.endsWith( QLatin1String( ".tiff" ), Qt::CaseInsensitive ) ) { - fileName += ".tif"; + fileName += QLatin1String( ".tif" ); } editOutput->setText( fileName ); } diff --git a/src/app/qgsannotationwidget.cpp b/src/app/qgsannotationwidget.cpp index fff1795135ee..0b86ef1a3e1d 100644 --- a/src/app/qgsannotationwidget.cpp +++ b/src/app/qgsannotationwidget.cpp @@ -44,13 +44,13 @@ QgsAnnotationWidget::QgsAnnotationWidget( QgsAnnotationItem* item, QWidget * par mFrameColorButton->setColor( mItem->frameColor() ); mFrameColorButton->setColorDialogTitle( tr( "Select frame color" ) ); mFrameColorButton->setAllowAlpha( true ); - mFrameColorButton->setContext( "symbology" ); + mFrameColorButton->setContext( QStringLiteral( "symbology" ) ); mFrameColorButton->setNoColorString( tr( "Transparent frame" ) ); mFrameColorButton->setShowNoColor( true ); mBackgroundColorButton->setColor( mItem->frameBackgroundColor() ); mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) ); mBackgroundColorButton->setAllowAlpha( true ); - mBackgroundColorButton->setContext( "symbology" ); + mBackgroundColorButton->setContext( QStringLiteral( "symbology" ) ); mBackgroundColorButton->setNoColorString( tr( "Transparent" ) ); mBackgroundColorButton->setShowNoColor( true ); diff --git a/src/app/qgsapplayertreeviewmenuprovider.cpp b/src/app/qgsapplayertreeviewmenuprovider.cpp index 6d78dab0b48f..24a498c8652d 100644 --- a/src/app/qgsapplayertreeviewmenuprovider.cpp +++ b/src/app/qgsapplayertreeviewmenuprovider.cpp @@ -58,8 +58,8 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() // global menu menu->addAction( actions->actionAddGroup( menu ) ); - menu->addAction( QgsApplication::getThemeIcon( "/mActionExpandTree.svg" ), tr( "&Expand All" ), mView, SLOT( expandAll() ) ); - menu->addAction( QgsApplication::getThemeIcon( "/mActionCollapseTree.svg" ), tr( "&Collapse All" ), mView, SLOT( collapseAll() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionExpandTree.svg" ) ), tr( "&Expand All" ), mView, SLOT( expandAll() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCollapseTree.svg" ) ), tr( "&Collapse All" ), mView, SLOT( collapseAll() ) ); // TODO: update drawing order } @@ -70,9 +70,9 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() { menu->addAction( actions->actionZoomToGroup( mCanvas, menu ) ); - menu->addAction( QgsApplication::getThemeIcon( "/mActionRemoveLayer.svg" ), tr( "&Remove" ), QgisApp::instance(), SLOT( removeLayer() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemoveLayer.svg" ) ), tr( "&Remove" ), QgisApp::instance(), SLOT( removeLayer() ) ); - menu->addAction( QgsApplication::getThemeIcon( "/mActionSetCRS.png" ), + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSetCRS.png" ) ), tr( "&Set Group CRS" ), QgisApp::instance(), SLOT( legendGroupSetCrs() ) ); menu->addAction( actions->actionRenameGroupOrLayer( menu ) ); @@ -104,16 +104,16 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() if ( rlayer ) { - menu->addAction( QgsApplication::getThemeIcon( "/mActionZoomActual.svg" ), tr( "&Zoom to Native Resolution (100%)" ), QgisApp::instance(), SLOT( legendLayerZoomNative() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomActual.svg" ) ), tr( "&Zoom to Native Resolution (100%)" ), QgisApp::instance(), SLOT( legendLayerZoomNative() ) ); if ( rlayer->rasterType() != QgsRasterLayer::Palette ) menu->addAction( tr( "&Stretch Using Current Extent" ), QgisApp::instance(), SLOT( legendLayerStretchUsingCurrentExtent() ) ); } - menu->addAction( QgsApplication::getThemeIcon( "/mActionRemoveLayer.svg" ), tr( "&Remove" ), QgisApp::instance(), SLOT( removeLayer() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemoveLayer.svg" ) ), tr( "&Remove" ), QgisApp::instance(), SLOT( removeLayer() ) ); // duplicate layer - QAction* duplicateLayersAction = menu->addAction( QgsApplication::getThemeIcon( "/mActionDuplicateLayer.svg" ), tr( "&Duplicate" ), QgisApp::instance(), SLOT( duplicateLayers() ) ); + QAction* duplicateLayersAction = menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDuplicateLayer.svg" ) ), tr( "&Duplicate" ), QgisApp::instance(), SLOT( duplicateLayers() ) ); if ( layer && layer->isSpatial() ) { @@ -124,10 +124,10 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() menu->addAction( tr( "Zoom to &Visible Scale" ), QgisApp::instance(), SLOT( zoomToLayerScale() ) ); // set layer crs - menu->addAction( QgsApplication::getThemeIcon( "/mActionSetCRS.png" ), tr( "Set Layer CRS" ), QgisApp::instance(), SLOT( setLayerCrs() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSetCRS.png" ) ), tr( "Set Layer CRS" ), QgisApp::instance(), SLOT( setLayerCrs() ) ); // assign layer crs to project - menu->addAction( QgsApplication::getThemeIcon( "/mActionSetProjectCRS.png" ), tr( "Set &Project CRS from Layer" ), QgisApp::instance(), SLOT( setProjectCrsFromLayer() ) ); + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSetProjectCRS.png" ) ), tr( "Set &Project CRS from Layer" ), QgisApp::instance(), SLOT( setProjectCrsFromLayer() ) ); } // style-related actions @@ -170,7 +170,7 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() QgsColorSchemeRegistry::instance()->schemes( recentSchemes ); if ( !recentSchemes.isEmpty() ) { - QgsColorSwatchGridAction* recentColorAction = new QgsColorSwatchGridAction( recentSchemes.at( 0 ), menuStyleManager, "symbology", menuStyleManager ); + QgsColorSwatchGridAction* recentColorAction = new QgsColorSwatchGridAction( recentSchemes.at( 0 ), menuStyleManager, QStringLiteral( "symbology" ), menuStyleManager ); recentColorAction->setProperty( "layerId", vlayer->id() ); recentColorAction->setDismissOnColorSelection( false ); menuStyleManager->addAction( recentColorAction ); @@ -205,7 +205,7 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() QAction *allEditsAction = QgisApp::instance()->actionAllEdits(); // attribute table - menu->addAction( QgsApplication::getThemeIcon( "/mActionOpenTable.svg" ), tr( "&Open Attribute Table" ), + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOpenTable.svg" ) ), tr( "&Open Attribute Table" ), QgisApp::instance(), SLOT( attributeTable() ) ); // allow editing @@ -227,7 +227,7 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() menu->addAction( allEditsAction ); // disable duplication of memory layers - if ( vlayer->storageType() == "Memory storage" && mView->selectedLayerNodes().count() == 1 ) + if ( vlayer->storageType() == QLatin1String( "Memory storage" ) && mView->selectedLayerNodes().count() == 1 ) duplicateLayersAction->setEnabled( false ); // save as vector file @@ -268,7 +268,7 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() if ( mView->selectedNodes( true ).count() >= 2 ) menu->addAction( actions->actionGroupSelected( menu ) ); - if ( layer && layer->type() == QgsMapLayer::VectorLayer && static_cast( layer )->providerType() == "virtual" ) + if ( layer && layer->type() == QgsMapLayer::VectorLayer && static_cast( layer )->providerType() == QLatin1String( "virtual" ) ) { menu->addAction( tr( "Edit virtual layer settings" ), QgisApp::instance(), SLOT( addVirtualLayer() ) ); } @@ -282,9 +282,9 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() // symbology item if ( symbolNode->flags() & Qt::ItemIsUserCheckable ) { - menu->addAction( QgsApplication::getThemeIcon( "/mActionShowAllLayers.svg" ), tr( "&Show All Items" ), + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowAllLayers.svg" ) ), tr( "&Show All Items" ), symbolNode, SLOT( checkAllItems() ) ); - menu->addAction( QgsApplication::getThemeIcon( "/mActionHideAllLayers.svg" ), tr( "&Hide All Items" ), + menu->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHideAllLayers.svg" ) ), tr( "&Hide All Items" ), symbolNode, SLOT( uncheckAllItems() ) ); menu->addSeparator(); } @@ -307,7 +307,7 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() QgsColorSchemeRegistry::instance()->schemes( recentSchemes ); if ( !recentSchemes.isEmpty() ) { - QgsColorSwatchGridAction* recentColorAction = new QgsColorSwatchGridAction( recentSchemes.at( 0 ), menu, "symbology", menu ); + QgsColorSwatchGridAction* recentColorAction = new QgsColorSwatchGridAction( recentSchemes.at( 0 ), menu, QStringLiteral( "symbology" ), menu ); recentColorAction->setProperty( "layerId", symbolNode->layerNode()->layerId() ); recentColorAction->setProperty( "ruleKey", symbolNode->data( QgsLayerTreeModelLegendNode::RuleKeyRole ).toString() ); recentColorAction->setDismissOnColorSelection( false ); diff --git a/src/app/qgsattributeactiondialog.cpp b/src/app/qgsattributeactiondialog.cpp index a27f750fd1d4..afedc85fdf3b 100644 --- a/src/app/qgsattributeactiondialog.cpp +++ b/src/app/qgsattributeactiondialog.cpp @@ -138,7 +138,7 @@ void QgsAttributeActionDialog::insertRow( int row, const QgsAction& action ) // Icon QIcon icon = action.icon(); - QTableWidgetItem* headerItem = new QTableWidgetItem( icon, "" ); + QTableWidgetItem* headerItem = new QTableWidgetItem( icon, QLatin1String( "" ) ); headerItem->setData( Qt::UserRole, action.iconPath() ); mAttributeActionTable->setVerticalHeaderItem( row, headerItem ); @@ -296,13 +296,13 @@ void QgsAttributeActionDialog::updateButtons() void QgsAttributeActionDialog::addDefaultActions() { int pos = 0; - insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), "echo \"[% \"MY_FIELD\" %]\"", "", true ); - insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"", "", true ); - insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), "QtGui.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")", "", false ); - insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), "QtGui.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")", "", false ); - insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), "QtGui.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")", "", false ); - insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), "[% \"PATH\" %]", "", false ); - insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]", "", false ); + insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), QStringLiteral( "echo \"[% \"MY_FIELD\" %]\"" ), QLatin1String( "" ), true ); + insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), QStringLiteral( "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"" ), QLatin1String( "" ), true ); + insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), QStringLiteral( "QtGui.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")" ), QLatin1String( "" ), false ); + insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), QStringLiteral( "QtGui.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")" ), QLatin1String( "" ), false ); + insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), QStringLiteral( "QtGui.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")" ), QLatin1String( "" ), false ); + insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false ); + insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false ); } void QgsAttributeActionDialog::itemDoubleClicked( QTableWidgetItem* item ) diff --git a/src/app/qgsattributeactionpropertiesdialog.cpp b/src/app/qgsattributeactionpropertiesdialog.cpp index f859dc0ca918..e495e53907ea 100644 --- a/src/app/qgsattributeactionpropertiesdialog.cpp +++ b/src/app/qgsattributeactionpropertiesdialog.cpp @@ -144,7 +144,7 @@ void QgsAttributeActionPropertiesDialog::insertExpressionOrField() QString selText = mActionText->selectedText(); // edit the selected expression if there's one - if ( selText.startsWith( "[%" ) && selText.endsWith( "%]" ) ) + if ( selText.startsWith( QLatin1String( "[%" ) ) && selText.endsWith( QLatin1String( "%]" ) ) ) selText = selText.mid( 2, selText.size() - 4 ); mActionText->insertText( "[%" + mFieldExpression->currentField() + "%]" ); @@ -155,9 +155,9 @@ void QgsAttributeActionPropertiesDialog::chooseIcon() QList list = QImageWriter::supportedImageFormats(); QStringList formatList; Q_FOREACH ( const QByteArray& format, list ) - formatList << QString( "*.%1" ).arg( QString( format ) ); + formatList << QStringLiteral( "*.%1" ).arg( QString( format ) ); - QString filter = tr( "Images( %1 ); All( *.* )" ).arg( formatList.join( " " ) ); + QString filter = tr( "Images( %1 ); All( *.* )" ).arg( formatList.join( QStringLiteral( " " ) ) ); QString icon = QFileDialog::getOpenFileName( this, tr( "Choose Icon..." ), mActionIcon->text(), filter ); if ( !icon.isNull() ) diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index e10005d4728d..98f01b7d7ef0 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -59,9 +59,9 @@ QgsExpressionContext QgsAttributeTableDialog::createExpressionContext() const if ( mLayer ) expContext << QgsExpressionContextUtils::layerScope( mLayer ); - expContext.lastScope()->setVariable( "row_number", 1 ); + expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), 1 ); - expContext.setHighlightedVariables( QStringList() << "row_number" ); + expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) ); return expContext; } @@ -104,7 +104,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid QSettings settings; - int size = settings.value( "/IconSize", 16 ).toInt(); + int size = settings.value( QStringLiteral( "/IconSize" ), 16 ).toInt(); if ( size > 32 ) { size -= 16; @@ -120,7 +120,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mToolbar->setIconSize( QSize( size, size ) ); // Initialize the window geometry - restoreGeometry( settings.value( "/Windows/BetterAttributeTable/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/BetterAttributeTable/geometry" ) ).toByteArray() ); myDa = new QgsDistanceArea(); @@ -133,7 +133,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid QgsFeatureRequest r; if ( mLayer->geometryType() != QgsWkbTypes::NullGeometry && - settings.value( "/qgis/attributeTableBehaviour", QgsAttributeTableFilterModel::ShowAll ).toInt() == QgsAttributeTableFilterModel::ShowVisible ) + settings.value( QStringLiteral( "/qgis/attributeTableBehaviour" ), QgsAttributeTableFilterModel::ShowAll ).toInt() == QgsAttributeTableFilterModel::ShowVisible ) { QgsMapCanvas *mc = QgisApp::instance()->mapCanvas(); QgsRectangle extent( mc->mapSettings().mapToLayerCoordinates( theLayer, mc->extent() ) ); @@ -195,7 +195,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid // info from table to application connect( this, SIGNAL( saveEdits( QgsMapLayer * ) ), QgisApp::instance(), SLOT( saveEdits( QgsMapLayer * ) ) ); - bool myDockFlag = settings.value( "/qgis/dockAttributeTable", false ).toBool(); + bool myDockFlag = settings.value( QStringLiteral( "/qgis/dockAttributeTable" ), false ).toBool(); if ( myDockFlag ) { mDock = new QgsAttributeTableDock( tr( "%1 (%n Feature(s))", "feature count", mMainView->featureCount() ).arg( mLayer->name() ), QgisApp::instance() ); @@ -207,24 +207,24 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid columnBoxInit(); updateTitle(); - mActionRemoveSelection->setIcon( QgsApplication::getThemeIcon( "/mActionDeselectAll.svg" ) ); - mActionSelectAll->setIcon( QgsApplication::getThemeIcon( "/mActionSelectAll.svg" ) ); - mActionSelectedToTop->setIcon( QgsApplication::getThemeIcon( "/mActionSelectedToTop.svg" ) ); - mActionCopySelectedRows->setIcon( QgsApplication::getThemeIcon( "/mActionEditCopy.svg" ) ); - mActionPasteFeatures->setIcon( QgsApplication::getThemeIcon( "/mActionEditPaste.svg" ) ); - mActionZoomMapToSelectedRows->setIcon( QgsApplication::getThemeIcon( "/mActionZoomToSelected.svg" ) ); - mActionPanMapToSelectedRows->setIcon( QgsApplication::getThemeIcon( "/mActionPanToSelected.svg" ) ); - mActionInvertSelection->setIcon( QgsApplication::getThemeIcon( "/mActionInvertSelection.svg" ) ); - mActionToggleEditing->setIcon( QgsApplication::getThemeIcon( "/mActionToggleEditing.svg" ) ); - mActionSaveEdits->setIcon( QgsApplication::getThemeIcon( "/mActionSaveEdits.svg" ) ); - mActionDeleteSelected->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteSelected.svg" ) ); - mActionOpenFieldCalculator->setIcon( QgsApplication::getThemeIcon( "/mActionCalculateField.svg" ) ); - mActionAddAttribute->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.svg" ) ); - mActionRemoveAttribute->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.svg" ) ); - mTableViewButton->setIcon( QgsApplication::getThemeIcon( "/mActionOpenTable.svg" ) ); - mAttributeViewButton->setIcon( QgsApplication::getThemeIcon( "/mActionFormView.svg" ) ); - mActionExpressionSelect->setIcon( QgsApplication::getThemeIcon( "/mIconExpressionSelect.svg" ) ); - mActionAddFeature->setIcon( QgsApplication::getThemeIcon( "/mActionNewTableRow.svg" ) ); + mActionRemoveSelection->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeselectAll.svg" ) ) ); + mActionSelectAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectAll.svg" ) ) ); + mActionSelectedToTop->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSelectedToTop.svg" ) ) ); + mActionCopySelectedRows->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditCopy.svg" ) ) ); + mActionPasteFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditPaste.svg" ) ) ); + mActionZoomMapToSelectedRows->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomToSelected.svg" ) ) ); + mActionPanMapToSelectedRows->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPanToSelected.svg" ) ) ); + mActionInvertSelection->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionInvertSelection.svg" ) ) ); + mActionToggleEditing->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) ); + mActionSaveEdits->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveEdits.svg" ) ) ); + mActionDeleteSelected->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteSelected.svg" ) ) ); + mActionOpenFieldCalculator->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCalculateField.svg" ) ) ); + mActionAddAttribute->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); + mActionRemoveAttribute->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); + mTableViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOpenTable.svg" ) ) ); + mAttributeViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFormView.svg" ) ) ); + mActionExpressionSelect->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpressionSelect.svg" ) ) ); + mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewTableRow.svg" ) ) ); // toggle editing bool canChangeAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues; @@ -256,7 +256,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mMainViewButtonGroup->setId( mAttributeViewButton, QgsDualView::AttributeEditor ); // Load default attribute table filter - QgsAttributeTableFilterModel::FilterMode defaultFilterMode = ( QgsAttributeTableFilterModel::FilterMode ) settings.value( "/qgis/attributeTableBehaviour", QgsAttributeTableFilterModel::ShowAll ).toInt(); + QgsAttributeTableFilterModel::FilterMode defaultFilterMode = ( QgsAttributeTableFilterModel::FilterMode ) settings.value( QStringLiteral( "/qgis/attributeTableBehaviour" ), QgsAttributeTableFilterModel::ShowAll ).toInt(); switch ( defaultFilterMode ) { @@ -286,10 +286,10 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mUpdateExpressionText->setLayer( mLayer ); mUpdateExpressionText->setLeftHandButtonStyle( true ); - int initialView = settings.value( "/qgis/attributeTableView", -1 ).toInt(); + int initialView = settings.value( QStringLiteral( "/qgis/attributeTableView" ), -1 ).toInt(); if ( initialView < 0 ) { - initialView = settings.value( "/qgis/attributeTableLastView", QgsDualView::AttributeTable ).toInt(); + initialView = settings.value( QStringLiteral( "/qgis/attributeTableLastView" ), QgsDualView::AttributeTable ).toInt(); } mMainView->setView( static_cast< QgsDualView::ViewMode >( initialView ) ); mMainViewButtonGroup->button( initialView )->setChecked( true ); @@ -324,7 +324,7 @@ void QgsAttributeTableDialog::updateTitle() .arg( mMainView->featureCount() ) .arg( mMainView->filteredFeatureCount() ) .arg( mLayer->selectedFeatureCount() ) - .arg( mRubberBand ? tr( ", spatially limited" ) : "" ) + .arg( mRubberBand ? tr( ", spatially limited" ) : QLatin1String( "" ) ) ); if ( mMainView->filterMode() == QgsAttributeTableFilterModel::ShowAll ) @@ -349,7 +349,7 @@ void QgsAttributeTableDialog::closeEvent( QCloseEvent* event ) if ( !mDock ) { QSettings settings; - settings.setValue( "/Windows/BetterAttributeTable/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/BetterAttributeTable/geometry" ), saveGeometry() ); } } @@ -391,7 +391,7 @@ void QgsAttributeTableDialog::columnBoxInit() if ( idx < 0 ) continue; - if ( QgsEditorWidgetRegistry::instance()->findBest( mLayer, field.name() ).type() != "Hidden" ) + if ( QgsEditorWidgetRegistry::instance()->findBest( mLayer, field.name() ).type() != QLatin1String( "Hidden" ) ) { QIcon icon = mLayer->fields().iconForField( idx ); QString alias = mLayer->attributeDisplayName( idx ); @@ -434,7 +434,7 @@ void QgsAttributeTableDialog::runFieldCalculation( QgsVectorLayer* layer, const { QApplication::setOverrideCursor( Qt::WaitCursor ); - mLayer->beginEditCommand( "Field calculator" ); + mLayer->beginEditCommand( QStringLiteral( "Field calculator" ) ); int fieldindex = layer->fields().indexFromName( fieldName ); @@ -471,7 +471,7 @@ void QgsAttributeTableDialog::runFieldCalculation( QgsVectorLayer* layer, const } context.setFeature( feature ); - context.lastScope()->setVariable( QString( "row_number" ), rownum ); + context.lastScope()->setVariable( QStringLiteral( "row_number" ), rownum ); QVariant value = exp.evaluate( &context ); fld.convertCompatible( value ); @@ -553,7 +553,7 @@ void QgsAttributeTableDialog::filterExpressionBuilder() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( mLayer ); - QgsExpressionBuilderDialog dlg( mLayer, mFilterQuery->text(), this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, mFilterQuery->text(), this, QStringLiteral( "generic" ), context ); dlg.setWindowTitle( tr( "Expression based filter" ) ); QgsDistanceArea myDa; @@ -725,7 +725,7 @@ void QgsAttributeTableDialog::on_mMainView_currentChanged( int viewMode ) mActionSearchForm->setChecked( false ); QSettings s; - s.setValue( "/qgis/attributeTableLastView", static_cast< int >( viewMode ) ); + s.setValue( QStringLiteral( "/qgis/attributeTableLastView" ), static_cast< int >( viewMode ) ); } void QgsAttributeTableDialog::on_mActionToggleEditing_toggled( bool ) @@ -881,11 +881,11 @@ void QgsAttributeTableDialog::setFilterExpression( const QString& filterString, break; case QgsAttributeForm::FilterAnd: - filter = QString( "(%1) AND (%2)" ).arg( mFilterQuery->text(), filterString ); + filter = QStringLiteral( "(%1) AND (%2)" ).arg( mFilterQuery->text(), filterString ); break; case QgsAttributeForm::FilterOr: - filter = QString( "(%1) OR (%2)" ).arg( mFilterQuery->text(), filterString ); + filter = QStringLiteral( "(%1) OR (%2)" ).arg( mFilterQuery->text(), filterString ); break; } } @@ -990,7 +990,7 @@ void QgsAttributeTableDialog::setFilterExpression( const QString& filterString, QgsAttributeTableDock::QgsAttributeTableDock( const QString& title, QWidget* parent, Qt::WindowFlags flags ) : QgsDockWidget( title, parent, flags ) { - setObjectName( "AttributeTable" ); // set object name so the position can be saved + setObjectName( QStringLiteral( "AttributeTable" ) ); // set object name so the position can be saved } void QgsAttributeTableDock::closeEvent( QCloseEvent* ev ) diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 4f242c61d2b2..94b119292726 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -72,7 +72,7 @@ QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl, int fieldIdx connect( mExpressionWidget, SIGNAL( expressionChanged( QString ) ), this, SLOT( defaultExpressionChanged() ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/QgsAttributeTypeDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsAttributeTypeDialog/geometry" ) ).toByteArray() ); constraintExpressionWidget->setLayer( vl ); } @@ -80,7 +80,7 @@ QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl, int fieldIdx QgsAttributeTypeDialog::~QgsAttributeTypeDialog() { QSettings settings; - settings.setValue( "/Windows/QgsAttributeTypeDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QgsAttributeTypeDialog/geometry" ), saveGeometry() ); qDeleteAll( mEditorConfigWidgets ); } diff --git a/src/app/qgsbookmarks.cpp b/src/app/qgsbookmarks.cpp index 0855465f6d07..3a9e2e03eb9f 100644 --- a/src/app/qgsbookmarks.cpp +++ b/src/app/qgsbookmarks.cpp @@ -49,14 +49,14 @@ QgsBookmarks::QgsBookmarks( QWidget *parent ) QToolButton* btnImpExp = new QToolButton; btnImpExp->setAutoRaise( true ); btnImpExp->setToolTip( tr( "Import/Export Bookmarks" ) ); - btnImpExp->setIcon( QgsApplication::getThemeIcon( "/mActionSharing.svg" ) ); + btnImpExp->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSharing.svg" ) ) ); btnImpExp->setPopupMode( QToolButton::InstantPopup ); QMenu *share = new QMenu( this ); QAction *btnExport = share->addAction( tr( "&Export" ) ); QAction *btnImport = share->addAction( tr( "&Import" ) ); - btnExport->setIcon( QgsApplication::getThemeIcon( "/mActionSharingExport.svg" ) ); - btnImport->setIcon( QgsApplication::getThemeIcon( "/mActionSharingImport.svg" ) ); + btnExport->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSharingExport.svg" ) ) ); + btnImport->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSharingImport.svg" ) ) ); connect( btnExport, SIGNAL( triggered() ), this, SLOT( exportToXml() ) ); connect( btnImport, SIGNAL( triggered() ), this, SLOT( importFromXml() ) ); btnImpExp->setMenu( share ); @@ -68,7 +68,7 @@ QgsBookmarks::QgsBookmarks( QWidget *parent ) mBookmarkToolbar->addWidget( btnImpExp ); // open the database - QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE", "bookmarks" ); + QSqlDatabase db = QSqlDatabase::addDatabase( QStringLiteral( "QSQLITE" ), QStringLiteral( "bookmarks" ) ); db.setDatabaseName( QgsApplication::qgisUserDbFilePath() ); if ( !db.open() ) { @@ -83,7 +83,7 @@ QgsBookmarks::QgsBookmarks( QWidget *parent ) } mQgisModel = new QSqlTableModel( this, db ); - mQgisModel->setTable( "tbl_bookmarks" ); + mQgisModel->setTable( QStringLiteral( "tbl_bookmarks" ) ); mQgisModel->setSort( 0, Qt::AscendingOrder ); mQgisModel->select(); mQgisModel->setEditStrategy( QSqlTableModel::OnFieldChange ); @@ -104,7 +104,7 @@ QgsBookmarks::QgsBookmarks( QWidget *parent ) lstBookmarks->setModel( mModel.data() ); QSettings settings; - lstBookmarks->header()->restoreState( settings.value( "/Windows/Bookmarks/headerstate" ).toByteArray() ); + lstBookmarks->header()->restoreState( settings.value( QStringLiteral( "/Windows/Bookmarks/headerstate" ) ).toByteArray() ); #ifndef QGISDEBUG lstBookmarks->setColumnHidden( 0, true ); @@ -115,21 +115,21 @@ QgsBookmarks::~QgsBookmarks() { delete mQgisModel; delete mProjectModel; - QSqlDatabase::removeDatabase( "bookmarks" ); + QSqlDatabase::removeDatabase( QStringLiteral( "bookmarks" ) ); saveWindowLocation(); } void QgsBookmarks::restorePosition() { QSettings settings; - restoreGeometry( settings.value( "/Windows/Bookmarks/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/Bookmarks/geometry" ) ).toByteArray() ); } void QgsBookmarks::saveWindowLocation() { QSettings settings; - settings.setValue( "/Windows/Bookmarks/geometry", saveGeometry() ); - settings.setValue( "/Windows/Bookmarks/headerstate", lstBookmarks->header()->saveState() ); + settings.setValue( QStringLiteral( "/Windows/Bookmarks/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/Bookmarks/headerstate" ), lstBookmarks->header()->saveState() ); } void QgsBookmarks::addClicked() @@ -144,7 +144,7 @@ void QgsBookmarks::addClicked() " VALUES (NULL,:name,:project_name,:xmin,:xmax,:ymin,:ymax,:projection_srid)", mQgisModel->database() ); - QString projStr( "" ); + QString projStr( QLatin1String( "" ) ); if ( QgsProject::instance() ) { if ( !QgsProject::instance()->title().isEmpty() ) @@ -154,17 +154,17 @@ void QgsBookmarks::addClicked() else if ( !QgsProject::instance()->fileName().isEmpty() ) { QFileInfo fi( QgsProject::instance()->fileName() ); - projStr = fi.exists() ? fi.fileName() : ""; + projStr = fi.exists() ? fi.fileName() : QLatin1String( "" ); } } - query.bindValue( ":name", tr( "New bookmark" ) ); - query.bindValue( ":project_name", projStr ); - query.bindValue( ":xmin", canvas->extent().xMinimum() ); - query.bindValue( ":ymin", canvas->extent().yMinimum() ); - query.bindValue( ":xmax", canvas->extent().xMaximum() ); - query.bindValue( ":ymax", canvas->extent().yMaximum() ); - query.bindValue( ":projection_srid", QVariant::fromValue( canvas->mapSettings().destinationCrs().srsid() ) ); + query.bindValue( QStringLiteral( ":name" ), tr( "New bookmark" ) ); + query.bindValue( QStringLiteral( ":project_name" ), projStr ); + query.bindValue( QStringLiteral( ":xmin" ), canvas->extent().xMinimum() ); + query.bindValue( QStringLiteral( ":ymin" ), canvas->extent().yMinimum() ); + query.bindValue( QStringLiteral( ":xmax" ), canvas->extent().xMaximum() ); + query.bindValue( QStringLiteral( ":ymax" ), canvas->extent().yMaximum() ); + query.bindValue( QStringLiteral( ":projection_srid" ), QVariant::fromValue( canvas->mapSettings().destinationCrs().srsid() ) ); if ( query.exec() ) { mQgisModel->setSort( 0, Qt::AscendingOrder ); @@ -252,7 +252,7 @@ void QgsBookmarks::importFromXml() { QSettings settings; - QString lastUsedDir = settings.value( "/Windows/Bookmarks/LastUsedDirectory", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/Windows/Bookmarks/LastUsedDirectory" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, tr( "Import Bookmarks" ), lastUsedDir, tr( "XML files (*.xml *XML)" ) ); if ( fileName.isEmpty() ) @@ -274,7 +274,7 @@ void QgsBookmarks::importFromXml() f.close(); QDomElement docElem = doc.documentElement(); - QDomNodeList nodeList = docElem.elementsByTagName( "bookmark" ); + QDomNodeList nodeList = docElem.elementsByTagName( QStringLiteral( "bookmark" ) ); Q_ASSERT( mModel ); @@ -283,13 +283,13 @@ void QgsBookmarks::importFromXml() for ( int i = 0;i < nodeList.count(); i++ ) { QDomNode bookmark = nodeList.at( i ); - QDomElement name = bookmark.firstChildElement( "name" ); - QDomElement prjname = bookmark.firstChildElement( "project" ); - QDomElement xmin = bookmark.firstChildElement( "xmin" ); - QDomElement xmax = bookmark.firstChildElement( "xmax" ); - QDomElement ymin = bookmark.firstChildElement( "ymin" ); - QDomElement ymax = bookmark.firstChildElement( "ymax" ); - QDomElement srid = bookmark.firstChildElement( "sr_id" ); + QDomElement name = bookmark.firstChildElement( QStringLiteral( "name" ) ); + QDomElement prjname = bookmark.firstChildElement( QStringLiteral( "project" ) ); + QDomElement xmin = bookmark.firstChildElement( QStringLiteral( "xmin" ) ); + QDomElement xmax = bookmark.firstChildElement( QStringLiteral( "xmax" ) ); + QDomElement ymin = bookmark.firstChildElement( QStringLiteral( "ymin" ) ); + QDomElement ymax = bookmark.firstChildElement( QStringLiteral( "ymax" ) ); + QDomElement srid = bookmark.firstChildElement( QStringLiteral( "sr_id" ) ); queries += "INSERT INTO tbl_bookmarks(bookmark_id,name,project_name,xmin,ymin,xmax,ymax,projection_srid)" " VALUES (NULL," @@ -327,7 +327,7 @@ void QgsBookmarks::exportToXml() { QSettings settings; - QString lastUsedDir = settings.value( "/Windows/Bookmarks/LastUsedDirectory", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/Windows/Bookmarks/LastUsedDirectory" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getSaveFileName( this, tr( "Export bookmarks" ), lastUsedDir, tr( "XML files( *.xml *.XML )" ) ); if ( fileName.isEmpty() ) @@ -336,25 +336,25 @@ void QgsBookmarks::exportToXml() } // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } - QDomDocument doc( "qgis_bookmarks" ); - QDomElement root = doc.createElement( "qgis_bookmarks" ); + QDomDocument doc( QStringLiteral( "qgis_bookmarks" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgis_bookmarks" ) ); doc.appendChild( root ); int rowCount = mModel->rowCount(); int colCount = mModel->columnCount(); QList headerList; - headerList << "id" << "name" << "project" << "xmin" - << "ymin" << "xmax" << "ymax" << "sr_id"; + headerList << QStringLiteral( "id" ) << QStringLiteral( "name" ) << QStringLiteral( "project" ) << QStringLiteral( "xmin" ) + << QStringLiteral( "ymin" ) << QStringLiteral( "xmax" ) << QStringLiteral( "ymax" ) << QStringLiteral( "sr_id" ); for ( int i = 0; i < rowCount; ++i ) { - QDomElement bookmark = doc.createElement( "bookmark" ); + QDomElement bookmark = doc.createElement( QStringLiteral( "bookmark" ) ); root.appendChild( bookmark ); for ( int j = 0; j < colCount; j++ ) { @@ -383,7 +383,7 @@ void QgsBookmarks::exportToXml() doc.save( out, 2 ); f.close(); - settings.setValue( "/Windows/Bookmarks/LastUsedDirectory", QFileInfo( fileName ).path() ); + settings.setValue( QStringLiteral( "/Windows/Bookmarks/LastUsedDirectory" ), QFileInfo( fileName ).path() ); } @@ -398,7 +398,7 @@ int QgsProjectBookmarksTableModel::rowCount( const QModelIndex& parent ) const { Q_UNUSED( parent ); - return QgsProject::instance()->readNumEntry( "Bookmarks", "/count" ); + return QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ) ); } int QgsProjectBookmarksTableModel::columnCount( const QModelIndex& parent ) const @@ -416,19 +416,19 @@ QVariant QgsProjectBookmarksTableModel::data( const QModelIndex& index, int role switch ( index.column() ) { case 1: - return QgsProject::instance()->readEntry( "Bookmarks", QString( "/Row-%1/Name" ).arg( index.row() ) ); + return QgsProject::instance()->readEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Name" ).arg( index.row() ) ); case 2: - return QgsProject::instance()->readEntry( "Bookmarks", QString( "/Row-%1/Project" ).arg( index.row() ) ); + return QgsProject::instance()->readEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Project" ).arg( index.row() ) ); case 3: - return QgsProject::instance()->readDoubleEntry( "Bookmarks", QString( "/Row-%1/MinX" ).arg( index.row() ) ); + return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinX" ).arg( index.row() ) ); case 4: - return QgsProject::instance()->readDoubleEntry( "Bookmarks", QString( "/Row-%1/MinY" ).arg( index.row() ) ); + return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinY" ).arg( index.row() ) ); case 5: - return QgsProject::instance()->readDoubleEntry( "Bookmarks", QString( "/Row-%1/MaxX" ).arg( index.row() ) ); + return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxX" ).arg( index.row() ) ); case 6: - return QgsProject::instance()->readDoubleEntry( "Bookmarks", QString( "/Row-%1/MaxY" ).arg( index.row() ) ); + return QgsProject::instance()->readDoubleEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxY" ).arg( index.row() ) ); case 7: - return QgsProject::instance()->readNumEntry( "Bookmarks", QString( "/Row-%1/SRID" ).arg( index.row() ) ); + return QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/SRID" ).arg( index.row() ) ); default: return QVariant(); } @@ -442,25 +442,25 @@ bool QgsProjectBookmarksTableModel::setData( const QModelIndex& index, const QVa switch ( index.column() ) { case 1: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/Name" ).arg( index.row() ), value.toString() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Name" ).arg( index.row() ), value.value() ); return true; case 2: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/Project" ).arg( index.row() ), value.toString() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/Project" ).arg( index.row() ), value.value() ); return true; case 3: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/MinX" ).arg( index.row() ), value.toDouble() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinX" ).arg( index.row() ), value.toDouble() ); return true; case 4: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/MinY" ).arg( index.row() ), value.toDouble() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MinY" ).arg( index.row() ), value.toDouble() ); return true; case 5: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/MaxX" ).arg( index.row() ), value.toDouble() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxX" ).arg( index.row() ), value.toDouble() ); return true; case 6: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/MaxY" ).arg( index.row() ), value.toDouble() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/MaxY" ).arg( index.row() ), value.toDouble() ); return true; case 7: - QgsProject::instance()->writeEntry( "Bookmarks", QString( "/Row-%1/SRID" ).arg( index.row() ), value.toInt() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1/SRID" ).arg( index.row() ), value.toInt() ); return true; default: return false; @@ -472,7 +472,7 @@ bool QgsProjectBookmarksTableModel::insertRows( int row, int count, const QModel Q_UNUSED( row ); Q_UNUSED( parent ); - return QgsProject::instance()->writeEntry( "Bookmarks", "/count", QgsProject::instance()->readNumEntry( "Bookmarks", "/count" ) + count ); + return QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ), QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ) ) + count ); } bool QgsProjectBookmarksTableModel::removeRows( int row, int count, const QModelIndex& parent ) @@ -488,10 +488,10 @@ bool QgsProjectBookmarksTableModel::removeRows( int row, int count, const QModel } for ( int newRow = rowCount() - count ; newRow < rowCount() ; newRow++ ) { - QgsProject::instance()->removeEntry( "Bookmarks", QString( "/Row-%1" ).arg( newRow ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/Row-%1" ).arg( newRow ) ); } - QgsProject::instance()->writeEntry( "Bookmarks", "/count", QgsProject::instance()->readNumEntry( "Bookmarks", "/count" ) - count ); + QgsProject::instance()->writeEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ), QgsProject::instance()->readNumEntry( QStringLiteral( "Bookmarks" ), QStringLiteral( "/count" ) ) - count ); return true; } @@ -674,13 +674,13 @@ void QgsMergedBookmarksTableModel::moveBookmark( QAbstractTableModel& modelFrom, " VALUES (NULL,:name,:project_name,:xmin,:xmax,:ymin,:ymax,:projection_srid)", qgisModel->database() ); - query.bindValue( ":name", modelFrom.data( modelFrom.index( row, 1 ) ).toString() ); - query.bindValue( ":project_name", modelFrom.data( modelFrom.index( row, 2 ) ).toString() ); - query.bindValue( ":xmin", modelFrom.data( modelFrom.index( row, 3 ) ).toDouble() ); - query.bindValue( ":ymin", modelFrom.data( modelFrom.index( row, 4 ) ).toDouble() ); - query.bindValue( ":xmax", modelFrom.data( modelFrom.index( row, 5 ) ).toDouble() ); - query.bindValue( ":ymax", modelFrom.data( modelFrom.index( row, 6 ) ).toDouble() ); - query.bindValue( ":projection_srid", modelFrom.data( modelFrom.index( row, 7 ) ).toInt() ); + query.bindValue( QStringLiteral( ":name" ), modelFrom.data( modelFrom.index( row, 1 ) ).toString() ); + query.bindValue( QStringLiteral( ":project_name" ), modelFrom.data( modelFrom.index( row, 2 ) ).toString() ); + query.bindValue( QStringLiteral( ":xmin" ), modelFrom.data( modelFrom.index( row, 3 ) ).toDouble() ); + query.bindValue( QStringLiteral( ":ymin" ), modelFrom.data( modelFrom.index( row, 4 ) ).toDouble() ); + query.bindValue( QStringLiteral( ":xmax" ), modelFrom.data( modelFrom.index( row, 5 ) ).toDouble() ); + query.bindValue( QStringLiteral( ":ymax" ), modelFrom.data( modelFrom.index( row, 6 ) ).toDouble() ); + query.bindValue( QStringLiteral( ":projection_srid" ), modelFrom.data( modelFrom.index( row, 7 ) ).toInt() ); if ( !query.exec() ) { diff --git a/src/app/qgsbrowserdockwidget.cpp b/src/app/qgsbrowserdockwidget.cpp index aefc06ce1260..be5541e025b7 100644 --- a/src/app/qgsbrowserdockwidget.cpp +++ b/src/app/qgsbrowserdockwidget.cpp @@ -125,10 +125,10 @@ void QgsBrowserLayerProperties::setItem( QgsDataItem* item ) // temporarily override /Projections/defaultBehaviour to avoid dialog prompt QSettings settings; - QString defaultProjectionOption = settings.value( "/Projections/defaultBehaviour", "prompt" ).toString(); - if ( settings.value( "/Projections/defaultBehaviour", "prompt" ).toString() == "prompt" ) + QString defaultProjectionOption = settings.value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString(); + if ( settings.value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString() == QLatin1String( "prompt" ) ) { - settings.setValue( "/Projections/defaultBehaviour", "useProject" ); + settings.setValue( QStringLiteral( "/Projections/defaultBehaviour" ), "useProject" ); } // find root item @@ -171,9 +171,9 @@ void QgsBrowserLayerProperties::setItem( QgsDataItem* item ) } // restore /Projections/defaultBehaviour - if ( defaultProjectionOption == "prompt" ) + if ( defaultProjectionOption == QLatin1String( "prompt" ) ) { - settings.setValue( "/Projections/defaultBehaviour", defaultProjectionOption ); + settings.setValue( QStringLiteral( "/Projections/defaultBehaviour" ), defaultProjectionOption ); } mNameLabel->setText( layerItem->name() ); @@ -184,7 +184,7 @@ void QgsBrowserLayerProperties::setItem( QgsDataItem* item ) mMetadataTextBrowser->setHtml( layerMetadata ); // report if layer was set to to project crs without prompt (may give a false positive) - if ( defaultProjectionOption == "prompt" ) + if ( defaultProjectionOption == QLatin1String( "prompt" ) ) { QgsCoordinateReferenceSystem defaultCrs = QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs(); @@ -384,7 +384,7 @@ void QgsBrowserDockWidget::showContextMenu( QPoint pt ) if ( item->type() == QgsDataItem::Directory ) { QSettings settings; - QStringList favDirs = settings.value( "/browser/favourites" ).toStringList(); + QStringList favDirs = settings.value( QStringLiteral( "/browser/favourites" ) ).toStringList(); bool inFavDirs = item->parent() && item->parent()->type() == QgsDataItem::Favourites; if ( item->parent() && !inFavDirs ) @@ -401,7 +401,7 @@ void QgsBrowserDockWidget::showContextMenu( QPoint pt ) menu->addAction( tr( "Hide from Browser" ), this, SLOT( hideItem() ) ); QAction *action = menu->addAction( tr( "Fast Scan this Directory" ), this, SLOT( toggleFastScan() ) ); action->setCheckable( true ); - action->setChecked( settings.value( "/qgis/scanItemsFastScanUris", + action->setChecked( settings.value( QStringLiteral( "/qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( item->path() ) ); } else if ( item->type() == QgsDataItem::Layer ) @@ -629,7 +629,7 @@ void QgsBrowserDockWidget::toggleFastScan() if ( item->type() == QgsDataItem::Directory ) { QSettings settings; - QStringList fastScanDirs = settings.value( "/qgis/scanItemsFastScanUris", + QStringList fastScanDirs = settings.value( QStringLiteral( "/qgis/scanItemsFastScanUris" ), QStringList() ).toStringList(); int idx = fastScanDirs.indexOf( item->path() ); if ( idx != -1 ) @@ -640,7 +640,7 @@ void QgsBrowserDockWidget::toggleFastScan() { fastScanDirs << item->path(); } - settings.setValue( "/qgis/scanItemsFastScanUris", fastScanDirs ); + settings.setValue( QStringLiteral( "/qgis/scanItemsFastScanUris" ), fastScanDirs ); } } @@ -769,8 +769,8 @@ void QgsDockBrowserTreeView::dragEnterEvent( QDragEnterEvent* e ) { // if this mime data come from layer tree, the proposed action will be MoveAction // but for browser we really need CopyAction - if ( e->mimeData()->hasFormat( "application/qgis.layertreemodeldata" ) && - e->mimeData()->hasFormat( "application/x-vnd.qgis.qgis.uri" ) ) + if ( e->mimeData()->hasFormat( QStringLiteral( "application/qgis.layertreemodeldata" ) ) && + e->mimeData()->hasFormat( QStringLiteral( "application/x-vnd.qgis.qgis.uri" ) ) ) e->setDropAction( Qt::CopyAction ); // accept drag enter so that our widget will not get ignored @@ -790,13 +790,13 @@ void QgsDockBrowserTreeView::dragMoveEvent( QDragMoveEvent* e ) // if this mime data come from layer tree, the proposed action will be MoveAction // but for browser we really need CopyAction - if ( e->mimeData()->hasFormat( "application/qgis.layertreemodeldata" ) && - e->mimeData()->hasFormat( "application/x-vnd.qgis.qgis.uri" ) ) + if ( e->mimeData()->hasFormat( QStringLiteral( "application/qgis.layertreemodeldata" ) ) && + e->mimeData()->hasFormat( QStringLiteral( "application/x-vnd.qgis.qgis.uri" ) ) ) e->setDropAction( Qt::CopyAction ); QTreeView::dragMoveEvent( e ); - if ( !e->mimeData()->hasFormat( "application/x-vnd.qgis.qgis.uri" ) ) + if ( !e->mimeData()->hasFormat( QStringLiteral( "application/x-vnd.qgis.qgis.uri" ) ) ) { e->ignore(); return; @@ -807,8 +807,8 @@ void QgsDockBrowserTreeView::dropEvent( QDropEvent *e ) { // if this mime data come from layer tree, the proposed action will be MoveAction // but for browser we really need CopyAction - if ( e->mimeData()->hasFormat( "application/qgis.layertreemodeldata" ) && - e->mimeData()->hasFormat( "application/x-vnd.qgis.qgis.uri" ) ) + if ( e->mimeData()->hasFormat( QStringLiteral( "application/qgis.layertreemodeldata" ) ) && + e->mimeData()->hasFormat( QStringLiteral( "application/x-vnd.qgis.qgis.uri" ) ) ) e->setDropAction( Qt::CopyAction ); QTreeView::dropEvent( e ); @@ -822,7 +822,7 @@ void QgsDockBrowserTreeView::dropEvent( QDropEvent *e ) QgsBrowserTreeFilterProxyModel::QgsBrowserTreeFilterProxyModel( QObject* parent ) : QSortFilterProxyModel( parent ) , mModel( nullptr ) - , mPatternSyntax( "normal" ) + , mPatternSyntax( QStringLiteral( "normal" ) ) , mCaseSensitivity( Qt::CaseInsensitive ) { setDynamicSortFilter( true ); @@ -862,7 +862,7 @@ void QgsBrowserTreeFilterProxyModel::updateFilter() { QgsDebugMsg( QString( "filter = %1 syntax = %2" ).arg( mFilter, mPatternSyntax ) ); mREList.clear(); - if ( mPatternSyntax == "normal" ) + if ( mPatternSyntax == QLatin1String( "normal" ) ) { Q_FOREACH ( const QString& f, mFilter.split( '|' ) ) { @@ -872,7 +872,7 @@ void QgsBrowserTreeFilterProxyModel::updateFilter() mREList.append( rx ); } } - else if ( mPatternSyntax == "wildcard" ) + else if ( mPatternSyntax == QLatin1String( "wildcard" ) ) { Q_FOREACH ( const QString& f, mFilter.split( '|' ) ) { @@ -894,7 +894,7 @@ void QgsBrowserTreeFilterProxyModel::updateFilter() bool QgsBrowserTreeFilterProxyModel::filterAcceptsString( const QString& value ) const { - if ( mPatternSyntax == "normal" || mPatternSyntax == "wildcard" ) + if ( mPatternSyntax == QLatin1String( "normal" ) || mPatternSyntax == QLatin1String( "wildcard" ) ) { Q_FOREACH ( const QRegExp& rx, mREList ) { diff --git a/src/app/qgsclipboard.cpp b/src/app/qgsclipboard.cpp index d53fe18a9586..89734ce39ee7 100644 --- a/src/app/qgsclipboard.cpp +++ b/src/app/qgsclipboard.cpp @@ -82,12 +82,12 @@ QString QgsClipboard::generateClipboardText() const { QSettings settings; CopyFormat format = AttributesWithWKT; - if ( settings.contains( "/qgis/copyFeatureFormat" ) ) - format = static_cast< CopyFormat >( settings.value( "/qgis/copyFeatureFormat", true ).toInt() ); + if ( settings.contains( QStringLiteral( "/qgis/copyFeatureFormat" ) ) ) + format = static_cast< CopyFormat >( settings.value( QStringLiteral( "/qgis/copyFeatureFormat" ), true ).toInt() ); else { //old format setting - format = settings.value( "/qgis/copyGeometryAsWKT", true ).toBool() ? AttributesWithWKT : AttributesOnly; + format = settings.value( QStringLiteral( "/qgis/copyGeometryAsWKT" ), true ).toBool() ? AttributesWithWKT : AttributesOnly; } switch ( format ) @@ -101,14 +101,14 @@ QString QgsClipboard::generateClipboardText() const // first do the field names if ( format == AttributesWithWKT ) { - textFields += "wkt_geom"; + textFields += QStringLiteral( "wkt_geom" ); } Q_FOREACH ( const QgsField& field, mFeatureFields ) { textFields += field.name(); } - textLines += textFields.join( "\t" ); + textLines += textFields.join( QStringLiteral( "\t" ) ); textFields.clear(); // then the field contents @@ -123,7 +123,7 @@ QString QgsClipboard::generateClipboardText() const textFields += it->geometry().exportToWkt(); else { - textFields += settings.value( "qgis/nullValue", "NULL" ).toString(); + textFields += settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } } @@ -134,11 +134,11 @@ QString QgsClipboard::generateClipboardText() const textFields += attributes.at( idx ).toString(); } - textLines += textFields.join( "\t" ); + textLines += textFields.join( QStringLiteral( "\t" ) ); textFields.clear(); } - return textLines.join( "\n" ); + return textLines.join( QStringLiteral( "\n" ) ); } case GeoJSON: { diff --git a/src/app/qgscustomization.cpp b/src/app/qgscustomization.cpp index 4bb4e488f7e8..d548840a9b09 100644 --- a/src/app/qgscustomization.cpp +++ b/src/app/qgscustomization.cpp @@ -48,14 +48,14 @@ QgsCustomizationDialog::QgsCustomizationDialog( QWidget *parent, QSettings* sett setupUi( this ); QSettings appSettings; - restoreGeometry( appSettings.value( "/Windows/Customization/geometry" ).toByteArray() ); + restoreGeometry( appSettings.value( QStringLiteral( "/Windows/Customization/geometry" ) ).toByteArray() ); init(); QStringList myHeaders; myHeaders << tr( "Object name" ) << tr( "Label" ) << tr( "Description" ); treeWidget->setHeaderLabels( myHeaders ); - mLastDirSettingsName = QLatin1String( "/UI/lastCustomizationDir" ); + mLastDirSettingsName = QStringLiteral( "/UI/lastCustomizationDir" ); //treeWidget->hideColumn(0) connect( buttonBox->button( QDialogButtonBox::Ok ), SIGNAL( clicked() ), this, SLOT( ok() ) ); connect( buttonBox->button( QDialogButtonBox::Apply ), SIGNAL( clicked() ), this, SLOT( apply() ) ); @@ -67,7 +67,7 @@ QgsCustomizationDialog::QgsCustomizationDialog( QWidget *parent, QSettings* sett QgsCustomizationDialog::~QgsCustomizationDialog() { QSettings settings; - settings.setValue( "/Windows/Customization/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/Customization/geometry" ), saveGeometry() ); } QTreeWidgetItem * QgsCustomizationDialog::item( const QString& thePath, QTreeWidgetItem *theItem ) @@ -76,7 +76,7 @@ QTreeWidgetItem * QgsCustomizationDialog::item( const QString& thePath, QTreeWid if ( path.startsWith( '/' ) ) path = path.mid( 1 ); // remove '/' QStringList names = path.split( '/' ); - path = QStringList( names.mid( 1 ) ).join( "/" ); + path = QStringList( names.mid( 1 ) ).join( QStringLiteral( "/" ) ); if ( ! theItem ) { @@ -171,7 +171,7 @@ void QgsCustomizationDialog::treeToSettings( QSettings *theSettings ) { for ( int i = 0; i < treeWidget->topLevelItemCount(); ++i ) { - itemToSettings( QString( "/Customization" ), treeWidget->topLevelItem( i ), theSettings ); + itemToSettings( QStringLiteral( "/Customization" ), treeWidget->topLevelItem( i ), theSettings ); } } @@ -179,7 +179,7 @@ void QgsCustomizationDialog::settingsToTree( QSettings *theSettings ) { for ( int i = 0; i < treeWidget->topLevelItemCount(); ++i ) { - settingsToItem( QString( "/Customization" ), treeWidget->topLevelItem( i ), theSettings ); + settingsToItem( QStringLiteral( "/Customization" ), treeWidget->topLevelItem( i ), theSettings ); } } @@ -189,7 +189,7 @@ void QgsCustomizationDialog::reset() settingsToTree( mSettings ); QSettings settings; - bool enabled = settings.value( "/UI/Customization/enabled", "false" ).toString() == "true"; + bool enabled = settings.value( QStringLiteral( "/UI/Customization/enabled" ), "false" ).toString() == QLatin1String( "true" ); mCustomizationEnabledCheckBox->setChecked( enabled ); treeWidget->setEnabled( enabled ); toolBar->setEnabled( enabled ); @@ -208,7 +208,7 @@ void QgsCustomizationDialog::apply() mSettings->sync(); QSettings settings; - settings.setValue( "/UI/Customization/enabled", mCustomizationEnabledCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/UI/Customization/enabled" ), mCustomizationEnabledCheckBox->isChecked() ); } void QgsCustomizationDialog::cancel() @@ -231,9 +231,9 @@ void QgsCustomizationDialog::on_actionSave_triggered( bool checked ) return; } - if ( !fileName.endsWith( ".ini", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".ini" ), Qt::CaseInsensitive ) ) { - fileName += ".ini"; + fileName += QLatin1String( ".ini" ); } QFileInfo fileInfo( fileName ); @@ -277,7 +277,7 @@ void QgsCustomizationDialog::on_actionCollapseAll_triggered( bool checked ) void QgsCustomizationDialog::on_actionSelectAll_triggered( bool checked ) { Q_UNUSED( checked ); - QList items = treeWidget->findItems( "*", Qt::MatchWildcard | Qt::MatchRecursive, 0 ); + QList items = treeWidget->findItems( QStringLiteral( "*" ), Qt::MatchWildcard | Qt::MatchRecursive, 0 ); Q_FOREACH ( QTreeWidgetItem* item, items ) item->setCheckState( 0, Qt::Checked ); @@ -313,7 +313,7 @@ void QgsCustomizationDialog::init() QTreeWidgetItem * QgsCustomizationDialog::createTreeItemWidgets() { - QDomDocument myDoc( "QgsWidgets" ); + QDomDocument myDoc( QStringLiteral( "QgsWidgets" ) ); QFile myFile( QgsApplication::pkgDataPath() + "/resources/customization.xml" ); if ( !myFile.open( QIODevice::ReadOnly ) ) { @@ -327,7 +327,7 @@ QTreeWidgetItem * QgsCustomizationDialog::createTreeItemWidgets() myFile.close(); QDomElement myRoot = myDoc.documentElement(); - if ( myRoot.tagName() != "qgiswidgets" ) + if ( myRoot.tagName() != QLatin1String( "qgiswidgets" ) ) { return nullptr; } @@ -342,17 +342,17 @@ QTreeWidgetItem * QgsCustomizationDialog::readWidgetsXmlNode( const QDomNode& th { QDomElement myElement = theNode.toElement(); - QString name = myElement.attribute( "objectName", "" ); + QString name = myElement.attribute( QStringLiteral( "objectName" ), QLatin1String( "" ) ); QStringList data( name ); - data << myElement.attribute( "label", name ); - data << myElement.attribute( "description", "" ); + data << myElement.attribute( QStringLiteral( "label" ), name ); + data << myElement.attribute( QStringLiteral( "description" ), QLatin1String( "" ) ); QTreeWidgetItem *myItem = new QTreeWidgetItem( data ); // It is nice to have icons for each Qt widget class, is it too heavy? // There are 47 png files, total 196K in qt/tools/designer/src/components/formeditor/images/ - QString iconName = myElement.attribute( "class", "" ).toLower().mid( 1 ) + ".png"; + QString iconName = myElement.attribute( QStringLiteral( "class" ), QLatin1String( "" ) ).toLower().mid( 1 ) + ".png"; QString iconPath = QgsApplication::iconPath( "/customization/" + iconName ); QgsDebugMsg( "iconPath = " + iconPath ); if ( QFile::exists( iconPath ) ) @@ -385,12 +385,12 @@ bool QgsCustomizationDialog::switchWidget( QWidget *widget, QMouseEvent *e ) QString path = widgetPath( widget ); QgsDebugMsg( "path = " + path ); - if ( path.contains( "/QgsCustomizationDialogBase" ) ) + if ( path.contains( QLatin1String( "/QgsCustomizationDialogBase" ) ) ) { // do not allow modification of this dialog return false; } - else if ( path.startsWith( "/QgisApp" ) ) + else if ( path.startsWith( QLatin1String( "/QgisApp" ) ) ) { // changes to main window // (work with toolbars, tool buttons) @@ -436,7 +436,7 @@ bool QgsCustomizationDialog::switchWidget( QWidget *widget, QMouseEvent *e ) QString style; if ( !on ) { - style = "background-color: #FFCCCC;"; + style = QStringLiteral( "background-color: #FFCCCC;" ); } widget->setStyleSheet( style ); } @@ -523,7 +523,7 @@ void QgsCustomization::addTreeItemMenu( QTreeWidgetItem* parentItem, QMenu* menu void QgsCustomization::createTreeItemMenus() { QStringList data; - data << "Menus"; + data << QStringLiteral( "Menus" ); QTreeWidgetItem *topItem = new QTreeWidgetItem( data ); @@ -543,7 +543,7 @@ void QgsCustomization::createTreeItemMenus() void QgsCustomization::createTreeItemToolbars() { QStringList data; - data << "Toolbars"; + data << QStringLiteral( "Toolbars" ); QTreeWidgetItem *topItem = new QTreeWidgetItem( data ); @@ -569,7 +569,7 @@ void QgsCustomization::createTreeItemToolbars() void QgsCustomization::createTreeItemDocks() { QStringList data; - data << "Panels"; + data << QStringLiteral( "Panels" ); QTreeWidgetItem *topItem = new QTreeWidgetItem( data ); @@ -593,7 +593,7 @@ void QgsCustomization::createTreeItemDocks() void QgsCustomization::createTreeItemStatus() { QStringList data; - data << "StatusBar"; + data << QStringLiteral( "StatusBar" ); QTreeWidgetItem *topItem = new QTreeWidgetItem( data ); topItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable ); @@ -615,7 +615,7 @@ void QgsCustomization::createTreeItemStatus() mMainWindowItems << topItem; } -QStringList QgsCustomization::mInternalWidgets = QStringList() << "qt_tabwidget_stackedwidget" << "qt_tabwidget_tabbar"; +QStringList QgsCustomization::mInternalWidgets = QStringList() << QStringLiteral( "qt_tabwidget_stackedwidget" ) << QStringLiteral( "qt_tabwidget_tabbar" ); QgsCustomization *QgsCustomization::pinstance = nullptr; QgsCustomization *QgsCustomization::instance() @@ -631,11 +631,11 @@ QgsCustomization::QgsCustomization() : pDialog( nullptr ) , mEnabled( false ) , mSettings( nullptr ) - , mStatusPath( "/Customization/status" ) + , mStatusPath( QStringLiteral( "/Customization/status" ) ) { QSettings settings; - mEnabled = settings.value( "/UI/Customization/enabled", "false" ).toString() == "true"; + mEnabled = settings.value( QStringLiteral( "/UI/Customization/enabled" ), "false" ).toString() == QLatin1String( "true" ); } QgsCustomization::~QgsCustomization() @@ -656,7 +656,7 @@ void QgsCustomization::updateMainWindow( QMenu * theToolBarMenu ) QMainWindow* mw = QgisApp::instance(); QMenuBar* menubar = mw->menuBar(); - mSettings->beginGroup( "Customization/Menus" ); + mSettings->beginGroup( QStringLiteral( "Customization/Menus" ) ); // hide menus and menu actions @@ -681,7 +681,7 @@ void QgsCustomization::updateMainWindow( QMenu * theToolBarMenu ) // remove toolbars, toolbar actions - mSettings->beginGroup( "Customization/Toolbars" ); + mSettings->beginGroup( QStringLiteral( "Customization/Toolbars" ) ); Q_FOREACH ( QObject* obj, mw->children() ) { if ( obj->inherits( "QToolBar" ) ) @@ -717,7 +717,7 @@ void QgsCustomization::updateMainWindow( QMenu * theToolBarMenu ) // remove dock widgets - mSettings->beginGroup( "Customization/Docks" ); + mSettings->beginGroup( QStringLiteral( "Customization/Docks" ) ); Q_FOREACH ( QObject* obj, mw->children() ) { if ( obj->inherits( "QDockWidget" ) ) @@ -734,9 +734,9 @@ void QgsCustomization::updateMainWindow( QMenu * theToolBarMenu ) // remove status bar widgets - if ( mSettings->value( "Customization/StatusBar", true ).toBool() ) + if ( mSettings->value( QStringLiteral( "Customization/StatusBar" ), true ).toBool() ) { - mSettings->beginGroup( "Customization/StatusBar" ); + mSettings->beginGroup( QStringLiteral( "Customization/StatusBar" ) ); QStatusBar* sb = mw->statusBar(); Q_FOREACH ( QObject* obj, sb->children() ) @@ -809,7 +809,7 @@ void QgsCustomization::customizeWidget( QWidget * widget, QEvent * event, QSetti QgsDebugMsg( QString( "objectName = %1 event type = %2" ).arg( widget->objectName() ).arg( event->type() ) ); QgsDebugMsg( QString( "%1 x %2" ).arg( widget->metaObject()->className(), QDialog::staticMetaObject.className() ) ); - QString path = "/Customization/Widgets/"; + QString path = QStringLiteral( "/Customization/Widgets/" ); QgsCustomization::customizeWidget( path, widget, settings ); } @@ -925,7 +925,7 @@ QString QgsCustomization::splashPath() { if ( isEnabled() ) { - QString path = mSettings->value( "/Customization/splashpath", QgsApplication::splashPath() ).toString(); + QString path = mSettings->value( QStringLiteral( "/Customization/splashpath" ), QgsApplication::splashPath() ).toString(); return path; } else diff --git a/src/app/qgscustomprojectiondialog.cpp b/src/app/qgscustomprojectiondialog.cpp index f859c1cf48ed..a105a463ea7d 100644 --- a/src/app/qgscustomprojectiondialog.cpp +++ b/src/app/qgscustomprojectiondialog.cpp @@ -49,7 +49,7 @@ QgsCustomProjectionDialog::QgsCustomProjectionDialog( QWidget *parent, Qt::Windo setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/CustomProjection/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/CustomProjection/geometry" ) ).toByteArray() ); // user database is created at QGIS startup in QgisApp::createDB // we just check whether there is our database [MD] @@ -75,7 +75,7 @@ QgsCustomProjectionDialog::QgsCustomProjectionDialog( QWidget *parent, Qt::Windo QgsCustomProjectionDialog::~QgsCustomProjectionDialog() { QSettings settings; - settings.setValue( "/Windows/CustomProjection/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/CustomProjection/geometry" ), saveGeometry() ); } @@ -95,7 +95,7 @@ void QgsCustomProjectionDialog::populateList() // database if it does not exist. Q_ASSERT( myResult == SQLITE_OK ); } - QString mySql = "select srs_id,description,parameters from tbl_srs"; + QString mySql = QStringLiteral( "select srs_id,description,parameters from tbl_srs" ); QgsDebugMsg( QString( "Query to populate existing list:%1" ).arg( mySql ) ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); // XXX Need to free memory from the error msg if one is set @@ -167,7 +167,7 @@ bool QgsCustomProjectionDialog::deleteCrs( const QString& id ) sqlite3_close( myDatabase ); QgsCoordinateReferenceSystem::invalidateCache(); - QgsCoordinateTransformCache::instance()->invalidateCrs( QString( "USER:%1" ).arg( id ) ); + QgsCoordinateTransformCache::instance()->invalidateCrs( QStringLiteral( "USER:%1" ).arg( id ) ); return myResult == SQLITE_OK; } @@ -293,7 +293,7 @@ bool QgsCustomProjectionDialog::saveCrs( QgsCoordinateReferenceSystem myCRS, con existingCRSnames[myId] = myName; QgsCoordinateReferenceSystem::invalidateCache(); - QgsCoordinateTransformCache::instance()->invalidateCrs( QString( "USER:%1" ).arg( myId ) ); + QgsCoordinateTransformCache::instance()->invalidateCrs( QStringLiteral( "USER:%1" ).arg( myId ) ); // If we have a projection acronym not in the user db previously, add it. // This is a must, or else we can't select it from the vw_srs table. @@ -307,7 +307,7 @@ bool QgsCustomProjectionDialog::saveCrs( QgsCoordinateReferenceSystem myCRS, con void QgsCustomProjectionDialog::on_pbnAdd_clicked() { QString name = tr( "new CRS" ); - QString id = ""; + QString id = QLatin1String( "" ); QgsCoordinateReferenceSystem parameters; QTreeWidgetItem* newItem = new QTreeWidgetItem( leNameList, QStringList() ); @@ -330,7 +330,7 @@ void QgsCustomProjectionDialog::on_pbnRemove_clicked() } QTreeWidgetItem* item = leNameList->takeTopLevelItem( i ); delete item; - if ( customCRSids[i] != "" ) + if ( customCRSids[i] != QLatin1String( "" ) ) { deletedCRSs.push_back( customCRSids[i] ); } @@ -360,8 +360,8 @@ void QgsCustomProjectionDialog::on_leNameList_currentItemChanged( QTreeWidgetIte else { //Can happen that current is null, for example if we just deleted the last element - leName->setText( "" ); - teParameters->setPlainText( "" ); + leName->setText( QLatin1String( "" ) ); + teParameters->setPlainText( QLatin1String( "" ) ); return; } return; @@ -417,9 +417,9 @@ void QgsCustomProjectionDialog::on_buttonBox_accepted() { CRS.createFromProj4( customCRSparameters[i] ); //Test if we just added this CRS (if it has no existing ID) - if ( customCRSids[i] == "" ) + if ( customCRSids[i] == QLatin1String( "" ) ) { - save_success &= saveCrs( CRS, customCRSnames[i], "", true ); + save_success &= saveCrs( CRS, customCRSnames[i], QLatin1String( "" ), true ); } else { @@ -464,8 +464,8 @@ void QgsCustomProjectionDialog::on_pbnCalculate_clicked() { QMessageBox::information( this, tr( "QGIS Custom Projection" ), tr( "This proj4 projection definition is not valid." ) ); - projectedX->setText( "" ); - projectedY->setText( "" ); + projectedX->setText( QLatin1String( "" ) ); + projectedY->setText( QLatin1String( "" ) ); pj_free( myProj ); return; @@ -479,8 +479,8 @@ void QgsCustomProjectionDialog::on_pbnCalculate_clicked() { QMessageBox::information( this, tr( "QGIS Custom Projection" ), tr( "Northing and Easthing must be in decimal form." ) ); - projectedX->setText( "" ); - projectedY->setText( "" ); + projectedX->setText( QLatin1String( "" ) ); + projectedY->setText( QLatin1String( "" ) ); pj_free( myProj ); return; } @@ -491,8 +491,8 @@ void QgsCustomProjectionDialog::on_pbnCalculate_clicked() { QMessageBox::information( this, tr( "QGIS Custom Projection" ), tr( "Internal Error (source projection invalid?)" ) ); - projectedX->setText( "" ); - projectedY->setText( "" ); + projectedX->setText( QLatin1String( "" ) ); + projectedY->setText( QLatin1String( "" ) ); pj_free( wgs84Proj ); return; } @@ -525,7 +525,7 @@ void QgsCustomProjectionDialog::on_pbnCalculate_clicked() QString QgsCustomProjectionDialog::quotedValue( QString value ) { - value.replace( '\'', "''" ); + value.replace( '\'', QLatin1String( "''" ) ); return value.prepend( '\'' ).append( '\'' ); } diff --git a/src/app/qgsdecorationcopyright.cpp b/src/app/qgsdecorationcopyright.cpp index 2f899a081437..e64893b1c073 100644 --- a/src/app/qgsdecorationcopyright.cpp +++ b/src/app/qgsdecorationcopyright.cpp @@ -62,28 +62,28 @@ void QgsDecorationCopyright::projectRead() QgsDecorationItem::projectRead(); QDate now = QDate::currentDate(); - QString defString = "© QGIS " + now.toString( "yyyy" ); + QString defString = "© QGIS " + now.toString( QStringLiteral( "yyyy" ) ); // there is no font setting in the UI, so just use the Qt/QGIS default font (what mQFont gets when created) // mQFont.setFamily( QgsProject::instance()->readEntry( "CopyrightLabel", "/FontName", "Sans Serif" ) ); // mQFont.setPointSize( QgsProject::instance()->readNumEntry( "CopyrightLabel", "/FontSize", 9 ) ); QgsProject* prj = QgsProject::instance(); - mLabelQString = prj->readEntry( mNameConfig, "/Label", defString ); - mMarginHorizontal = QgsProject::instance()->readNumEntry( mNameConfig, "/MarginH", 0 ); - mMarginVertical = QgsProject::instance()->readNumEntry( mNameConfig, "/MarginV", 0 ); - mLabelQColor.setNamedColor( prj->readEntry( mNameConfig, "/Color", "#000000" ) ); // default color is black + mLabelQString = prj->readEntry( mNameConfig, QStringLiteral( "/Label" ), defString ); + mMarginHorizontal = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MarginH" ), 0 ); + mMarginVertical = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MarginV" ), 0 ); + mLabelQColor.setNamedColor( prj->readEntry( mNameConfig, QStringLiteral( "/Color" ), QStringLiteral( "#000000" ) ) ); // default color is black } void QgsDecorationCopyright::saveToProject() { QgsDecorationItem::saveToProject(); QgsProject* prj = QgsProject::instance(); - prj->writeEntry( mNameConfig, "/FontName", mQFont.family() ); - prj->writeEntry( mNameConfig, "/FontSize", mQFont.pointSize() ); - prj->writeEntry( mNameConfig, "/Label", mLabelQString ); - prj->writeEntry( mNameConfig, "/Color", mLabelQColor.name() ); - prj->writeEntry( mNameConfig, "/MarginH", mMarginHorizontal ); - prj->writeEntry( mNameConfig, "/MarginV", mMarginVertical ); + prj->writeEntry( mNameConfig, QStringLiteral( "/FontName" ), mQFont.family() ); + prj->writeEntry( mNameConfig, QStringLiteral( "/FontSize" ), mQFont.pointSize() ); + prj->writeEntry( mNameConfig, QStringLiteral( "/Label" ), mLabelQString ); + prj->writeEntry( mNameConfig, QStringLiteral( "/Color" ), mLabelQColor.name() ); + prj->writeEntry( mNameConfig, QStringLiteral( "/MarginH" ), mMarginHorizontal ); + prj->writeEntry( mNameConfig, QStringLiteral( "/MarginV" ), mMarginVertical ); } // Slot called when the buffer menu item is activated diff --git a/src/app/qgsdecorationcopyrightdialog.cpp b/src/app/qgsdecorationcopyrightdialog.cpp index 43bc1fd4ea95..45bae8d34354 100644 --- a/src/app/qgsdecorationcopyrightdialog.cpp +++ b/src/app/qgsdecorationcopyrightdialog.cpp @@ -30,7 +30,7 @@ QgsDecorationCopyrightDialog::QgsDecorationCopyrightDialog( QgsDecorationCopyrig setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/DecorationCopyright/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/DecorationCopyright/geometry" ) ).toByteArray() ); QPushButton* applyButton = buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, SIGNAL( clicked() ), this, SLOT( apply() ) ); @@ -51,7 +51,7 @@ QgsDecorationCopyrightDialog::QgsDecorationCopyrightDialog( QgsDecorationCopyrig // color pbnColorChooser->setColor( mDeco.mLabelQColor ); - pbnColorChooser->setContext( "gui" ); + pbnColorChooser->setContext( QStringLiteral( "gui" ) ); pbnColorChooser->setColorDialogTitle( tr( "Select text color" ) ); QTextCursor cursor = txtCopyrightText->textCursor(); @@ -63,7 +63,7 @@ QgsDecorationCopyrightDialog::QgsDecorationCopyrightDialog( QgsDecorationCopyrig QgsDecorationCopyrightDialog::~QgsDecorationCopyrightDialog() { QSettings settings; - settings.setValue( "/Windows/DecorationCopyright/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/DecorationCopyright/geometry" ), saveGeometry() ); } void QgsDecorationCopyrightDialog::on_buttonBox_accepted() diff --git a/src/app/qgsdecorationgrid.cpp b/src/app/qgsdecorationgrid.cpp index e0eb667d0392..8a24c44c403d 100644 --- a/src/app/qgsdecorationgrid.cpp +++ b/src/app/qgsdecorationgrid.cpp @@ -92,24 +92,24 @@ void QgsDecorationGrid::projectRead() { QgsDecorationItem::projectRead(); - mEnabled = QgsProject::instance()->readBoolEntry( mNameConfig, "/Enabled", false ); - mMapUnits = static_cast< QgsUnitTypes::DistanceUnit >( QgsProject::instance()->readNumEntry( mNameConfig, "/MapUnits", + mEnabled = QgsProject::instance()->readBoolEntry( mNameConfig, QStringLiteral( "/Enabled" ), false ); + mMapUnits = static_cast< QgsUnitTypes::DistanceUnit >( QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MapUnits" ), QgsUnitTypes::DistanceUnknownUnit ) ); - mGridStyle = static_cast< GridStyle >( QgsProject::instance()->readNumEntry( mNameConfig, "/Style", + mGridStyle = static_cast< GridStyle >( QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/Style" ), QgsDecorationGrid::Line ) ); - mGridIntervalX = QgsProject::instance()->readDoubleEntry( mNameConfig, "/IntervalX", 10 ); - mGridIntervalY = QgsProject::instance()->readDoubleEntry( mNameConfig, "/IntervalY", 10 ); - mGridOffsetX = QgsProject::instance()->readDoubleEntry( mNameConfig, "/OffsetX", 0 ); - mGridOffsetY = QgsProject::instance()->readDoubleEntry( mNameConfig, "/OffsetY", 0 ); + mGridIntervalX = QgsProject::instance()->readDoubleEntry( mNameConfig, QStringLiteral( "/IntervalX" ), 10 ); + mGridIntervalY = QgsProject::instance()->readDoubleEntry( mNameConfig, QStringLiteral( "/IntervalY" ), 10 ); + mGridOffsetX = QgsProject::instance()->readDoubleEntry( mNameConfig, QStringLiteral( "/OffsetX" ), 0 ); + mGridOffsetY = QgsProject::instance()->readDoubleEntry( mNameConfig, QStringLiteral( "/OffsetY" ), 0 ); // mCrossLength = QgsProject::instance()->readDoubleEntry( mNameConfig, "/CrossLength", 3 ); - mShowGridAnnotation = QgsProject::instance()->readBoolEntry( mNameConfig, "/ShowAnnotation", false ); + mShowGridAnnotation = QgsProject::instance()->readBoolEntry( mNameConfig, QStringLiteral( "/ShowAnnotation" ), false ); // mGridAnnotationPosition = ( GridAnnotationPosition ) QgsProject::instance()->readNumEntry( mNameConfig, // "/AnnotationPosition", 0 ); mGridAnnotationPosition = InsideMapFrame; // don't allow outside frame, doesn't make sense mGridAnnotationDirection = static_cast< GridAnnotationDirection >( QgsProject::instance()->readNumEntry( mNameConfig, - "/AnnotationDirection", 0 ) ); - QString fontStr = QgsProject::instance()->readEntry( mNameConfig, "/AnnotationFont", "" ); - if ( fontStr != "" ) + QStringLiteral( "/AnnotationDirection" ), 0 ) ); + QString fontStr = QgsProject::instance()->readEntry( mNameConfig, QStringLiteral( "/AnnotationFont" ), QLatin1String( "" ) ); + if ( fontStr != QLatin1String( "" ) ) { mGridAnnotationFont.fromString( fontStr ); } @@ -119,8 +119,8 @@ void QgsDecorationGrid::projectRead() // TODO fix font scaling problem - put a slightly large font for now mGridAnnotationFont.setPointSize( 16 ); } - mAnnotationFrameDistance = QgsProject::instance()->readDoubleEntry( mNameConfig, "/AnnotationFrameDistance", 0 ); - mGridAnnotationPrecision = QgsProject::instance()->readNumEntry( mNameConfig, "/AnnotationPrecision", 0 ); + mAnnotationFrameDistance = QgsProject::instance()->readDoubleEntry( mNameConfig, QStringLiteral( "/AnnotationFrameDistance" ), 0 ); + mGridAnnotationPrecision = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/AnnotationPrecision" ), 0 ); // read symbol info from xml QDomDocument doc; @@ -129,8 +129,8 @@ void QgsDecorationGrid::projectRead() if ( mLineSymbol ) setLineSymbol( nullptr ); - xml = QgsProject::instance()->readEntry( mNameConfig, "/LineSymbol" ); - if ( xml != "" ) + xml = QgsProject::instance()->readEntry( mNameConfig, QStringLiteral( "/LineSymbol" ) ); + if ( xml != QLatin1String( "" ) ) { doc.setContent( xml ); elem = doc.documentElement(); @@ -141,8 +141,8 @@ void QgsDecorationGrid::projectRead() if ( mMarkerSymbol ) setMarkerSymbol( nullptr ); - xml = QgsProject::instance()->readEntry( mNameConfig, "/MarkerSymbol" ); - if ( xml != "" ) + xml = QgsProject::instance()->readEntry( mNameConfig, QStringLiteral( "/MarkerSymbol" ) ); + if ( xml != QLatin1String( "" ) ) { doc.setContent( xml ); elem = doc.documentElement(); @@ -161,38 +161,38 @@ void QgsDecorationGrid::projectRead() void QgsDecorationGrid::saveToProject() { QgsDecorationItem::saveToProject(); - QgsProject::instance()->writeEntry( mNameConfig, "/Enabled", mEnabled ); - QgsProject::instance()->writeEntry( mNameConfig, "/MapUnits", static_cast< int >( mMapUnits ) ); - QgsProject::instance()->writeEntry( mNameConfig, "/Style", static_cast< int >( mGridStyle ) ); - QgsProject::instance()->writeEntry( mNameConfig, "/IntervalX", mGridIntervalX ); - QgsProject::instance()->writeEntry( mNameConfig, "/IntervalY", mGridIntervalY ); - QgsProject::instance()->writeEntry( mNameConfig, "/OffsetX", mGridOffsetX ); - QgsProject::instance()->writeEntry( mNameConfig, "/OffsetY", mGridOffsetY ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Enabled" ), mEnabled ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MapUnits" ), static_cast< int >( mMapUnits ) ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Style" ), static_cast< int >( mGridStyle ) ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/IntervalX" ), mGridIntervalX ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/IntervalY" ), mGridIntervalY ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/OffsetX" ), mGridOffsetX ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/OffsetY" ), mGridOffsetY ); // QgsProject::instance()->writeEntry( mNameConfig, "/CrossLength", mCrossLength ); // missing mGridPen, but should use styles anyway - QgsProject::instance()->writeEntry( mNameConfig, "/ShowAnnotation", mShowGridAnnotation ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/ShowAnnotation" ), mShowGridAnnotation ); // QgsProject::instance()->writeEntry( mNameConfig, "/AnnotationPosition", ( int ) mGridAnnotationPosition ); - QgsProject::instance()->writeEntry( mNameConfig, "/AnnotationDirection", static_cast< int >( mGridAnnotationDirection ) ); - QgsProject::instance()->writeEntry( mNameConfig, "/AnnotationFont", mGridAnnotationFont.toString() ); - QgsProject::instance()->writeEntry( mNameConfig, "/AnnotationFrameDistance", mAnnotationFrameDistance ); - QgsProject::instance()->writeEntry( mNameConfig, "/AnnotationPrecision", mGridAnnotationPrecision ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/AnnotationDirection" ), static_cast< int >( mGridAnnotationDirection ) ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/AnnotationFont" ), mGridAnnotationFont.toString() ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/AnnotationFrameDistance" ), mAnnotationFrameDistance ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/AnnotationPrecision" ), mGridAnnotationPrecision ); // write symbol info to xml QDomDocument doc; QDomElement elem; if ( mLineSymbol ) { - elem = QgsSymbolLayerUtils::saveSymbol( "line symbol", mLineSymbol, doc ); + elem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "line symbol" ), mLineSymbol, doc ); doc.appendChild( elem ); // FIXME this works, but XML will not be valid as < is replaced by < - QgsProject::instance()->writeEntry( mNameConfig, "/LineSymbol", doc.toString() ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/LineSymbol" ), doc.toString() ); } if ( mMarkerSymbol ) { doc.setContent( QString() ); - elem = QgsSymbolLayerUtils::saveSymbol( "marker symbol", mMarkerSymbol, doc ); + elem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "marker symbol" ), mMarkerSymbol, doc ); doc.appendChild( elem ); - QgsProject::instance()->writeEntry( mNameConfig, "/MarkerSymbol", doc.toString() ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MarkerSymbol" ), doc.toString() ); } } diff --git a/src/app/qgsdecorationgriddialog.cpp b/src/app/qgsdecorationgriddialog.cpp index 57f4ec768896..cbb80dd34935 100644 --- a/src/app/qgsdecorationgriddialog.cpp +++ b/src/app/qgsdecorationgriddialog.cpp @@ -169,7 +169,7 @@ void QgsDecorationGridDialog::updateDecoFromGui() QgsDecorationGridDialog::~QgsDecorationGridDialog() { QSettings settings; - settings.setValue( "/Windows/DecorationGrid/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/DecorationGrid/geometry" ), saveGeometry() ); if ( mLineSymbol ) delete mLineSymbol; if ( mMarkerSymbol ) diff --git a/src/app/qgsdecorationitem.cpp b/src/app/qgsdecorationitem.cpp index 12b93899a9f8..4c97ba921bfa 100644 --- a/src/app/qgsdecorationitem.cpp +++ b/src/app/qgsdecorationitem.cpp @@ -64,16 +64,16 @@ void QgsDecorationItem::update() void QgsDecorationItem::projectRead() { - mEnabled = QgsProject::instance()->readBoolEntry( mNameConfig, "/Enabled", false ); - mPlacement = static_cast< Placement >( QgsProject::instance()->readNumEntry( mNameConfig, "/Placement", static_cast< int >( mPlacement ) ) ); - mMarginUnit = QgsUnitTypes::decodeRenderUnit( QgsProject::instance()->readEntry( mNameConfig, "/MarginUnit", QgsUnitTypes::encodeUnit( mMarginUnit ) ) ); + mEnabled = QgsProject::instance()->readBoolEntry( mNameConfig, QStringLiteral( "/Enabled" ), false ); + mPlacement = static_cast< Placement >( QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/Placement" ), static_cast< int >( mPlacement ) ) ); + mMarginUnit = QgsUnitTypes::decodeRenderUnit( QgsProject::instance()->readEntry( mNameConfig, QStringLiteral( "/MarginUnit" ), QgsUnitTypes::encodeUnit( mMarginUnit ) ) ); } void QgsDecorationItem::saveToProject() { - QgsProject::instance()->writeEntry( mNameConfig, "/Enabled", mEnabled ); - QgsProject::instance()->writeEntry( mNameConfig, "/Placement", static_cast< int >( mPlacement ) ); - QgsProject::instance()->writeEntry( mNameConfig, "/MarginUnit", QgsUnitTypes::encodeUnit( mMarginUnit ) ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Enabled" ), mEnabled ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Placement" ), static_cast< int >( mPlacement ) ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MarginUnit" ), QgsUnitTypes::encodeUnit( mMarginUnit ) ); } void QgsDecorationItem::setName( const char *name ) diff --git a/src/app/qgsdecorationnortharrow.cpp b/src/app/qgsdecorationnortharrow.cpp index 38ea3b0e612c..755762c963b8 100644 --- a/src/app/qgsdecorationnortharrow.cpp +++ b/src/app/qgsdecorationnortharrow.cpp @@ -75,19 +75,19 @@ QgsDecorationNorthArrow::~QgsDecorationNorthArrow() void QgsDecorationNorthArrow::projectRead() { QgsDecorationItem::projectRead(); - mRotationInt = QgsProject::instance()->readNumEntry( mNameConfig, "/Rotation", 0 ); - mAutomatic = QgsProject::instance()->readBoolEntry( mNameConfig, "/Automatic", true ); - mMarginHorizontal = QgsProject::instance()->readNumEntry( mNameConfig, "/MarginH", 0 ); - mMarginVertical = QgsProject::instance()->readNumEntry( mNameConfig, "/MarginV", 0 ); + mRotationInt = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/Rotation" ), 0 ); + mAutomatic = QgsProject::instance()->readBoolEntry( mNameConfig, QStringLiteral( "/Automatic" ), true ); + mMarginHorizontal = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MarginH" ), 0 ); + mMarginVertical = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MarginV" ), 0 ); } void QgsDecorationNorthArrow::saveToProject() { QgsDecorationItem::saveToProject(); - QgsProject::instance()->writeEntry( mNameConfig, "/Rotation", mRotationInt ); - QgsProject::instance()->writeEntry( mNameConfig, "/Automatic", mAutomatic ); - QgsProject::instance()->writeEntry( mNameConfig, "/MarginH", mMarginHorizontal ); - QgsProject::instance()->writeEntry( mNameConfig, "/MarginV", mMarginVertical ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Rotation" ), mRotationInt ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Automatic" ), mAutomatic ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MarginH" ), mMarginHorizontal ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MarginV" ), mMarginVertical ); } // Slot called when the buffer menu item is activated @@ -105,7 +105,7 @@ void QgsDecorationNorthArrow::render( QPainter * theQPainter ) { QPixmap myQPixmap; //to store the north arrow image in - QString myFileNameQString = ":/images/north_arrows/default.png"; + QString myFileNameQString = QStringLiteral( ":/images/north_arrows/default.png" ); if ( myQPixmap.load( myFileNameQString ) ) { @@ -200,7 +200,7 @@ void QgsDecorationNorthArrow::render( QPainter * theQPainter ) } else { - QFont myQFont( "time", 12, QFont::Bold ); + QFont myQFont( QStringLiteral( "time" ), 12, QFont::Bold ); theQPainter->setFont( myQFont ); theQPainter->setPen( Qt::black ); theQPainter->drawText( 10, 20, tr( "North arrow pixmap not found" ) ); diff --git a/src/app/qgsdecorationnortharrowdialog.cpp b/src/app/qgsdecorationnortharrowdialog.cpp index 896b287140fb..5194bba3ed1a 100644 --- a/src/app/qgsdecorationnortharrowdialog.cpp +++ b/src/app/qgsdecorationnortharrowdialog.cpp @@ -28,7 +28,7 @@ QgsDecorationNorthArrowDialog::QgsDecorationNorthArrowDialog( QgsDecorationNorth setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/DecorationNorthArrow/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/DecorationNorthArrow/geometry" ) ).toByteArray() ); QPushButton* applyButton = buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, SIGNAL( clicked() ), this, SLOT( apply() ) ); @@ -60,7 +60,7 @@ QgsDecorationNorthArrowDialog::QgsDecorationNorthArrowDialog( QgsDecorationNorth QgsDecorationNorthArrowDialog::~QgsDecorationNorthArrowDialog() { QSettings settings; - settings.setValue( "/Windows/DecorationNorthArrow/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/DecorationNorthArrow/geometry" ), saveGeometry() ); } void QgsDecorationNorthArrowDialog::on_buttonBox_helpRequested() @@ -105,7 +105,7 @@ void QgsDecorationNorthArrowDialog::apply() void QgsDecorationNorthArrowDialog::rotatePixmap( int theRotationInt ) { QPixmap myQPixmap; - QString myFileNameQString = ":/images/north_arrows/default.png"; + QString myFileNameQString = QStringLiteral( ":/images/north_arrows/default.png" ); // QgsDebugMsg(QString("Trying to load %1").arg(myFileNameQString)); if ( myQPixmap.load( myFileNameQString ) ) { @@ -152,7 +152,7 @@ void QgsDecorationNorthArrowDialog::rotatePixmap( int theRotationInt ) myPainterPixmap.fill(); QPainter myQPainter; myQPainter.begin( &myPainterPixmap ); - QFont myQFont( "time", 12, QFont::Bold ); + QFont myQFont( QStringLiteral( "time" ), 12, QFont::Bold ); myQPainter.setFont( myQFont ); myQPainter.setPen( Qt::red ); myQPainter.drawText( 10, 20, tr( "Pixmap not found" ) ); diff --git a/src/app/qgsdecorationscalebar.cpp b/src/app/qgsdecorationscalebar.cpp index 083e6288bf56..7e5130f4db28 100644 --- a/src/app/qgsdecorationscalebar.cpp +++ b/src/app/qgsdecorationscalebar.cpp @@ -71,28 +71,28 @@ QgsDecorationScaleBar::~QgsDecorationScaleBar() void QgsDecorationScaleBar::projectRead() { QgsDecorationItem::projectRead(); - mPreferredSize = QgsProject::instance()->readNumEntry( mNameConfig, "/PreferredSize", 30 ); - mStyleIndex = QgsProject::instance()->readNumEntry( mNameConfig, "/Style", 0 ); - mSnapping = QgsProject::instance()->readBoolEntry( mNameConfig, "/Snapping", true ); - int myRedInt = QgsProject::instance()->readNumEntry( mNameConfig, "/ColorRedPart", 0 ); - int myGreenInt = QgsProject::instance()->readNumEntry( mNameConfig, "/ColorGreenPart", 0 ); - int myBlueInt = QgsProject::instance()->readNumEntry( mNameConfig, "/ColorBluePart", 0 ); + mPreferredSize = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/PreferredSize" ), 30 ); + mStyleIndex = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/Style" ), 0 ); + mSnapping = QgsProject::instance()->readBoolEntry( mNameConfig, QStringLiteral( "/Snapping" ), true ); + int myRedInt = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/ColorRedPart" ), 0 ); + int myGreenInt = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/ColorGreenPart" ), 0 ); + int myBlueInt = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/ColorBluePart" ), 0 ); mColor = QColor( myRedInt, myGreenInt, myBlueInt ); - mMarginHorizontal = QgsProject::instance()->readNumEntry( mNameConfig, "/MarginH", 0 ); - mMarginVertical = QgsProject::instance()->readNumEntry( mNameConfig, "/MarginV", 0 ); + mMarginHorizontal = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MarginH" ), 0 ); + mMarginVertical = QgsProject::instance()->readNumEntry( mNameConfig, QStringLiteral( "/MarginV" ), 0 ); } void QgsDecorationScaleBar::saveToProject() { QgsDecorationItem::saveToProject(); - QgsProject::instance()->writeEntry( mNameConfig, "/PreferredSize", mPreferredSize ); - QgsProject::instance()->writeEntry( mNameConfig, "/Snapping", mSnapping ); - QgsProject::instance()->writeEntry( mNameConfig, "/Style", mStyleIndex ); - QgsProject::instance()->writeEntry( mNameConfig, "/ColorRedPart", mColor.red() ); - QgsProject::instance()->writeEntry( mNameConfig, "/ColorGreenPart", mColor.green() ); - QgsProject::instance()->writeEntry( mNameConfig, "/ColorBluePart", mColor.blue() ); - QgsProject::instance()->writeEntry( mNameConfig, "/MarginH", mMarginHorizontal ); - QgsProject::instance()->writeEntry( mNameConfig, "/MarginV", mMarginVertical ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/PreferredSize" ), mPreferredSize ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Snapping" ), mSnapping ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/Style" ), mStyleIndex ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/ColorRedPart" ), mColor.red() ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/ColorGreenPart" ), mColor.green() ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/ColorBluePart" ), mColor.blue() ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MarginH" ), mMarginHorizontal ); + QgsProject::instance()->writeEntry( mNameConfig, QStringLiteral( "/MarginV" ), mMarginVertical ); } @@ -133,7 +133,7 @@ void QgsDecorationScaleBar::render( QPainter * theQPainter ) QSettings settings; bool ok = false; - QgsUnitTypes::DistanceUnit myPreferredUnits = QgsUnitTypes::decodeDistanceUnit( settings.value( "/qgis/measure/displayunits" ).toString(), &ok ); + QgsUnitTypes::DistanceUnit myPreferredUnits = QgsUnitTypes::decodeDistanceUnit( settings.value( QStringLiteral( "/qgis/measure/displayunits" ) ).toString(), &ok ); if ( !ok ) myPreferredUnits = QgsUnitTypes::DistanceMeters; QgsUnitTypes::DistanceUnit myMapUnits = canvas->mapUnits(); @@ -240,7 +240,7 @@ void QgsDecorationScaleBar::render( QPainter * theQPainter ) //Set font and calculate width of unit label int myFontSize = 10; //we use this later for buffering - QFont myFont( "helvetica", myFontSize ); + QFont myFont( QStringLiteral( "helvetica" ), myFontSize ); theQPainter->setFont( myFont ); QFontMetrics myFontMetrics( myFont ); double myFontWidth = myFontMetrics.width( myScaleBarUnitLabel ); @@ -440,7 +440,7 @@ void QgsDecorationScaleBar::render( QPainter * theQPainter ) //Draw the minimum label buffer theQPainter->setPen( myBackColor ); - myFontWidth = myFontMetrics.width( "0" ); + myFontWidth = myFontMetrics.width( QStringLiteral( "0" ) ); myFontHeight = myFontMetrics.height(); for ( int i = 0 - myBufferSize; i <= myBufferSize; i++ ) @@ -449,7 +449,7 @@ void QgsDecorationScaleBar::render( QPainter * theQPainter ) { theQPainter->drawText( int( i + ( myOriginX - ( myFontWidth / 2 ) ) ), int( j + ( myOriginY - ( myFontHeight / 4 ) ) ), - "0" ); + QStringLiteral( "0" ) ); } } @@ -459,7 +459,7 @@ void QgsDecorationScaleBar::render( QPainter * theQPainter ) theQPainter->drawText( int( myOriginX - ( myFontWidth / 2 ) ), int( myOriginY - ( myFontHeight / 4 ) ), - "0" + QStringLiteral( "0" ) ); // diff --git a/src/app/qgsdecorationscalebardialog.cpp b/src/app/qgsdecorationscalebardialog.cpp index 9638b7a139aa..6a204f84ecc0 100644 --- a/src/app/qgsdecorationscalebardialog.cpp +++ b/src/app/qgsdecorationscalebardialog.cpp @@ -27,7 +27,7 @@ QgsDecorationScaleBarDialog::QgsDecorationScaleBarDialog( QgsDecorationScaleBar& setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/DecorationScaleBar/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/DecorationScaleBar/geometry" ) ).toByteArray() ); QPushButton* applyButton = buttonBox->button( QDialogButtonBox::Apply ); connect( applyButton, SIGNAL( clicked() ), this, SLOT( apply() ) ); @@ -72,14 +72,14 @@ QgsDecorationScaleBarDialog::QgsDecorationScaleBarDialog( QgsDecorationScaleBar& cboStyle->setCurrentIndex( mDeco.mStyleIndex ); pbnChangeColor->setColor( mDeco.mColor ); - pbnChangeColor->setContext( "gui" ); + pbnChangeColor->setContext( QStringLiteral( "gui" ) ); pbnChangeColor->setColorDialogTitle( tr( "Select scalebar color" ) ); } QgsDecorationScaleBarDialog::~QgsDecorationScaleBarDialog() { QSettings settings; - settings.setValue( "/Windows/DecorationScaleBar/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/DecorationScaleBar/geometry" ), saveGeometry() ); } void QgsDecorationScaleBarDialog::on_buttonBox_helpRequested() diff --git a/src/app/qgsdelattrdialog.cpp b/src/app/qgsdelattrdialog.cpp index 4256632bdbb3..3572d4760971 100644 --- a/src/app/qgsdelattrdialog.cpp +++ b/src/app/qgsdelattrdialog.cpp @@ -38,16 +38,16 @@ QgsDelAttrDialog::QgsDelAttrDialog( const QgsVectorLayer* vl ) switch ( vl->fields().fieldOrigin( idx ) ) { case QgsFields::OriginExpression: - item->setIcon( QgsApplication::getThemeIcon( "/mIconExpression.svg" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); break; case QgsFields::OriginJoin: - item->setIcon( QgsApplication::getThemeIcon( "/propertyicons/join.png" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/join.png" ) ) ); item->setFlags( item->flags() & ~Qt::ItemIsEnabled ); break; default: - item->setIcon( QgsApplication::getThemeIcon( "/propertyicons/attributes.png" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/attributes.png" ) ) ); if ( !vl->isEditable() || !canDeleteAttributes ) item->setFlags( item->flags() & ~Qt::ItemIsEnabled ); break; @@ -61,13 +61,13 @@ QgsDelAttrDialog::QgsDelAttrDialog( const QgsVectorLayer* vl ) } QSettings settings; - restoreGeometry( settings.value( "/Windows/QgsDelAttrDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsDelAttrDialog/geometry" ) ).toByteArray() ); } QgsDelAttrDialog::~QgsDelAttrDialog() { QSettings settings; - settings.setValue( "/Windows/QgsDelAttrDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QgsDelAttrDialog/geometry" ), saveGeometry() ); } QList QgsDelAttrDialog::selectedAttributes() diff --git a/src/app/qgsdiagramproperties.cpp b/src/app/qgsdiagramproperties.cpp index 6be3c268ba83..1edc9545a90f 100644 --- a/src/app/qgsdiagramproperties.cpp +++ b/src/app/qgsdiagramproperties.cpp @@ -71,13 +71,13 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare mDiagramOptionsListWidget->setAttribute( Qt::WA_MacShowFocusRect, false ); mDiagramTypeComboBox->blockSignals( true ); - QPixmap pix = QgsApplication::getThemePixmap( "diagramNone" ); + QPixmap pix = QgsApplication::getThemePixmap( QStringLiteral( "diagramNone" ) ); mDiagramTypeComboBox->addItem( pix, tr( "No diagrams" ), "None" ); - pix = QgsApplication::getThemePixmap( "pie-chart" ); + pix = QgsApplication::getThemePixmap( QStringLiteral( "pie-chart" ) ); mDiagramTypeComboBox->addItem( pix, tr( "Pie chart" ), DIAGRAM_NAME_PIE ); - pix = QgsApplication::getThemePixmap( "text" ); + pix = QgsApplication::getThemePixmap( QStringLiteral( "text" ) ); mDiagramTypeComboBox->addItem( pix, tr( "Text diagram" ), DIAGRAM_NAME_TEXT ); - pix = QgsApplication::getThemePixmap( "histogram" ); + pix = QgsApplication::getThemePixmap( QStringLiteral( "histogram" ) ); mDiagramTypeComboBox->addItem( pix, tr( "Histogram" ), DIAGRAM_NAME_HISTOGRAM ); mDiagramTypeComboBox->blockSignals( false ); @@ -86,12 +86,12 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare mBackgroundColorButton->setColorDialogTitle( tr( "Select background color" ) ); mBackgroundColorButton->setAllowAlpha( true ); - mBackgroundColorButton->setContext( "symbology" ); + mBackgroundColorButton->setContext( QStringLiteral( "symbology" ) ); mBackgroundColorButton->setShowNoColor( true ); mBackgroundColorButton->setNoColorString( tr( "Transparent background" ) ); mDiagramPenColorButton->setColorDialogTitle( tr( "Select pen color" ) ); mDiagramPenColorButton->setAllowAlpha( true ); - mDiagramPenColorButton->setContext( "symbology" ); + mDiagramPenColorButton->setContext( QStringLiteral( "symbology" ) ); mDiagramPenColorButton->setShowNoColor( true ); mDiagramPenColorButton->setNoColorString( tr( "Transparent outline" ) ); @@ -161,7 +161,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare QSizePolicy policy( mDiagramOptionsListFrame->sizePolicy() ); policy.setHorizontalStretch( 0 ); mDiagramOptionsListFrame->setSizePolicy( policy ); - if ( !settings.contains( QString( "/Windows/Diagrams/OptionsSplitState" ) ) ) + if ( !settings.contains( QStringLiteral( "/Windows/Diagrams/OptionsSplitState" ) ) ) { // set left list widget width on intial showing QList splitsizes; @@ -170,8 +170,8 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare } // restore dialog, splitters and current tab - mDiagramOptionsSplitter->restoreState( settings.value( QString( "/Windows/Diagrams/OptionsSplitState" ) ).toByteArray() ); - mDiagramOptionsListWidget->setCurrentRow( settings.value( QString( "/Windows/Diagrams/Tab" ), 0 ).toInt() ); + mDiagramOptionsSplitter->restoreState( settings.value( QStringLiteral( "/Windows/Diagrams/OptionsSplitState" ) ).toByteArray() ); + mDiagramOptionsListWidget->setCurrentRow( settings.value( QStringLiteral( "/Windows/Diagrams/Tab" ), 0 ).toInt() ); // field combo and expression button mSizeFieldExpressionWidget->setLayer( mLayer ); @@ -186,7 +186,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare for ( int idx = 0; idx < layerFields.count(); ++idx ) { QTreeWidgetItem *newItem = new QTreeWidgetItem( mAttributesTreeWidget ); - QString name = QString( "\"%1\"" ).arg( layerFields.at( idx ).name() ); + QString name = QStringLiteral( "\"%1\"" ).arg( layerFields.at( idx ).name() ); newItem->setText( 0, name ); newItem->setData( 0, RoleAttributeExpression, name ); newItem->setFlags( newItem->flags() & ~Qt::ItemIsDropEnabled ); @@ -246,7 +246,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare else // already a diagram renderer present { //single category renderer or interpolated one? - if ( dr->rendererName() == "SingleCategory" ) + if ( dr->rendererName() == QLatin1String( "SingleCategory" ) ) { mFixedSizeRadio->setChecked( true ); } @@ -355,7 +355,7 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare } } - if ( dr->rendererName() == "LinearlyInterpolated" ) + if ( dr->rendererName() == QLatin1String( "LinearlyInterpolated" ) ) { const QgsLinearlyInterpolatedDiagramRenderer* lidr = dynamic_cast( dr ); if ( lidr ) @@ -429,8 +429,8 @@ QgsDiagramProperties::QgsDiagramProperties( QgsVectorLayer* layer, QWidget* pare QgsDiagramProperties::~QgsDiagramProperties() { QSettings settings; - settings.setValue( QString( "/Windows/Diagrams/OptionsSplitState" ), mDiagramOptionsSplitter->saveState() ); - settings.setValue( QString( "/Windows/Diagrams/Tab" ), mDiagramOptionsListWidget->currentRow() ); + settings.setValue( QStringLiteral( "/Windows/Diagrams/OptionsSplitState" ), mDiagramOptionsSplitter->saveState() ); + settings.setValue( QStringLiteral( "/Windows/Diagrams/Tab" ), mDiagramOptionsListWidget->currentRow() ); } void QgsDiagramProperties::on_mDiagramTypeComboBox_currentIndexChanged( int index ) @@ -865,7 +865,7 @@ QString QgsDiagramProperties::showExpressionBuilder( const QString& initialExpre << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) << QgsExpressionContextUtils::layerScope( mLayer ); - QgsExpressionBuilderDialog dlg( mLayer, initialExpression, this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, initialExpression, this, QStringLiteral( "generic" ), context ); dlg.setWindowTitle( tr( "Expression based attribute" ) ); QgsDistanceArea myDa; diff --git a/src/app/qgsdisplayangle.cpp b/src/app/qgsdisplayangle.cpp index 2da5aeb7c55f..7964bd30c0c4 100644 --- a/src/app/qgsdisplayangle.cpp +++ b/src/app/qgsdisplayangle.cpp @@ -42,7 +42,7 @@ void QgsDisplayAngle::setValueInRadians( double value ) void QgsDisplayAngle::updateUi() { QSettings settings; - QgsUnitTypes::AngleUnit unit = QgsUnitTypes::decodeAngleUnit( settings.value( "/qgis/measure/angleunits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AngleDegrees ) ).toString() ); - int decimals = settings.value( "/qgis/measure/decimalplaces", "3" ).toInt(); + QgsUnitTypes::AngleUnit unit = QgsUnitTypes::decodeAngleUnit( settings.value( QStringLiteral( "/qgis/measure/angleunits" ), QgsUnitTypes::encodeUnit( QgsUnitTypes::AngleDegrees ) ).toString() ); + int decimals = settings.value( QStringLiteral( "/qgis/measure/decimalplaces" ), "3" ).toInt(); mAngleLineEdit->setText( QgsUnitTypes::formatAngle( mValue * QgsUnitTypes::fromUnitToUnitFactor( QgsUnitTypes::AngleRadians, unit ), decimals, unit ) ); } diff --git a/src/app/qgsdxfexportdialog.cpp b/src/app/qgsdxfexportdialog.cpp index 580b9d60708a..ec0b4a660c75 100644 --- a/src/app/qgsdxfexportdialog.cpp +++ b/src/app/qgsdxfexportdialog.cpp @@ -444,24 +444,24 @@ QgsDxfExportDialog::QgsDxfExportDialog( QWidget *parent, Qt::WindowFlags f ) //last dxf symbology mode QSettings s; - mSymbologyModeComboBox->setCurrentIndex( QgsProject::instance()->readEntry( "dxf", "/lastDxfSymbologyMode", s.value( "qgis/lastDxfSymbologyMode", "2" ).toString() ).toInt() ); + mSymbologyModeComboBox->setCurrentIndex( QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfSymbologyMode" ), s.value( QStringLiteral( "qgis/lastDxfSymbologyMode" ), "2" ).toString() ).toInt() ); //last symbol scale mScaleWidget->setMapCanvas( QgisApp::instance()->mapCanvas() ); - mScaleWidget->setScale( QgsProject::instance()->readEntry( "dxf", "/lastSymbologyExportScale", s.value( "qgis/lastSymbologyExportScale", "1/50000" ).toString() ).toDouble() ); - mLayerTitleAsName->setChecked( QgsProject::instance()->readEntry( "dxf", "/lastDxfLayerTitleAsName", s.value( "qgis/lastDxfLayerTitleAsName", "false" ).toString() ) != "false" ); - mMapExtentCheckBox->setChecked( QgsProject::instance()->readEntry( "dxf", "/lastDxfMapRectangle", s.value( "qgis/lastDxfMapRectangle", "false" ).toString() ) != "false" ); + mScaleWidget->setScale( QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastSymbologyExportScale" ), s.value( QStringLiteral( "qgis/lastSymbologyExportScale" ), "1/50000" ).toString() ).toDouble() ); + mLayerTitleAsName->setChecked( QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfLayerTitleAsName" ), s.value( QStringLiteral( "qgis/lastDxfLayerTitleAsName" ), "false" ).toString() ) != QLatin1String( "false" ) ); + mMapExtentCheckBox->setChecked( QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfMapRectangle" ), s.value( QStringLiteral( "qgis/lastDxfMapRectangle" ), "false" ).toString() ) != QLatin1String( "false" ) ); QStringList ids = QgsProject::instance()->mapThemeCollection()->mapThemes(); - ids.prepend( "" ); + ids.prepend( QLatin1String( "" ) ); mVisibilityPresets->addItems( ids ); - mVisibilityPresets->setCurrentIndex( mVisibilityPresets->findText( QgsProject::instance()->readEntry( "dxf", "/lastVisibliltyPreset", "" ) ) ); + mVisibilityPresets->setCurrentIndex( mVisibilityPresets->findText( QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastVisibliltyPreset" ), QLatin1String( "" ) ) ) ); buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); - restoreGeometry( s.value( "/Windows/DxfExport/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/Windows/DxfExport/geometry" ) ).toByteArray() ); - long crsid = QgsProject::instance()->readEntry( "dxf", "/lastDxfCrs", - s.value( "qgis/lastDxfCrs", QString::number( QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs().srsid() ) ).toString() + long crsid = QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfCrs" ), + s.value( QStringLiteral( "qgis/lastDxfCrs" ), QString::number( QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs().srsid() ) ).toString() ).toLong(); mCRS = QgsCoordinateReferenceSystem::fromSrsId( crsid ); mCrsSelector->setCrs( mCRS ); @@ -470,7 +470,7 @@ QgsDxfExportDialog::QgsDxfExportDialog( QWidget *parent, Qt::WindowFlags f ) "The data points will be transformed from the layer coordinate reference system." ) ); mEncoding->addItems( QgsDxfExport::encodings() ); - mEncoding->setCurrentIndex( mEncoding->findText( QgsProject::instance()->readEntry( "dxf", "/lastDxfEncoding", s.value( "qgis/lastDxfEncoding", "CP1252" ).toString() ) ) ); + mEncoding->setCurrentIndex( mEncoding->findText( QgsProject::instance()->readEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfEncoding" ), s.value( QStringLiteral( "qgis/lastDxfEncoding" ), "CP1252" ).toString() ) ) ); } @@ -478,7 +478,7 @@ QgsDxfExportDialog::~QgsDxfExportDialog() { delete mLayerTreeGroup; - QSettings().setValue( "/Windows/DxfExport/geometry", saveGeometry() ); + QSettings().setValue( QStringLiteral( "/Windows/DxfExport/geometry" ), saveGeometry() ); } void QgsDxfExportDialog::on_mVisibilityPresets_currentIndexChanged( int index ) @@ -567,7 +567,7 @@ void QgsDxfExportDialog::on_mFileSelectionButton_clicked() { //get last dxf save directory QSettings s; - QString lastSavePath = s.value( "qgis/lastDxfDir", QDir::homePath() ).toString(); + QString lastSavePath = s.value( QStringLiteral( "qgis/lastDxfDir" ), QDir::homePath() ).toString(); QString filePath = QFileDialog::getSaveFileName( nullptr, tr( "Export as DXF" ), lastSavePath, tr( "DXF files *.dxf *.DXF" ) ); if ( !filePath.isEmpty() ) @@ -606,21 +606,21 @@ void QgsDxfExportDialog::saveSettings() { QSettings s; QFileInfo dxfFileInfo( mFileLineEdit->text() ); - s.setValue( "qgis/lastDxfDir", dxfFileInfo.absolutePath() ); - s.setValue( "qgis/lastDxfSymbologyMode", mSymbologyModeComboBox->currentIndex() ); - s.setValue( "qgis/lastSymbologyExportScale", mScaleWidget->scale() ); - s.setValue( "qgis/lastDxfMapRectangle", mMapExtentCheckBox->isChecked() ); - s.setValue( "qgis/lastDxfLayerTitleAsName", mLayerTitleAsName->isChecked() ); - s.setValue( "qgis/lastDxfEncoding", mEncoding->currentText() ); - s.setValue( "qgis/lastDxfCrs", QString::number( mCRS.srsid() ) ); - - QgsProject::instance()->writeEntry( "dxf", "/lastDxfSymbologyMode", mSymbologyModeComboBox->currentIndex() ); - QgsProject::instance()->writeEntry( "dxf", "/lastSymbologyExportScale", mScaleWidget->scale() ); - QgsProject::instance()->writeEntry( "dxf", "/lastDxfLayerTitleAsName", mLayerTitleAsName->isChecked() ); - QgsProject::instance()->writeEntry( "dxf", "/lastDxfMapRectangle", mMapExtentCheckBox->isChecked() ); - QgsProject::instance()->writeEntry( "dxf", "/lastDxfEncoding", mEncoding->currentText() ); - QgsProject::instance()->writeEntry( "dxf", "/lastVisibilityPreset", mVisibilityPresets->currentText() ); - QgsProject::instance()->writeEntry( "dxf", "/lastDxfCrs", QString::number( mCRS.srsid() ) ); + s.setValue( QStringLiteral( "qgis/lastDxfDir" ), dxfFileInfo.absolutePath() ); + s.setValue( QStringLiteral( "qgis/lastDxfSymbologyMode" ), mSymbologyModeComboBox->currentIndex() ); + s.setValue( QStringLiteral( "qgis/lastSymbologyExportScale" ), mScaleWidget->scale() ); + s.setValue( QStringLiteral( "qgis/lastDxfMapRectangle" ), mMapExtentCheckBox->isChecked() ); + s.setValue( QStringLiteral( "qgis/lastDxfLayerTitleAsName" ), mLayerTitleAsName->isChecked() ); + s.setValue( QStringLiteral( "qgis/lastDxfEncoding" ), mEncoding->currentText() ); + s.setValue( QStringLiteral( "qgis/lastDxfCrs" ), QString::number( mCRS.srsid() ) ); + + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfSymbologyMode" ), mSymbologyModeComboBox->currentIndex() ); + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastSymbologyExportScale" ), mScaleWidget->scale() ); + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfLayerTitleAsName" ), mLayerTitleAsName->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfMapRectangle" ), mMapExtentCheckBox->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfEncoding" ), mEncoding->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastVisibilityPreset" ), mVisibilityPresets->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "dxf" ), QStringLiteral( "/lastDxfCrs" ), QString::number( mCRS.srsid() ) ); } diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index f57fda5d37dd..da2f8703c67b 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -142,7 +142,7 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo QgsAttributeList pkAttrList = mLayer->pkAttributeList(); QSettings settings; - bool reuseLastValues = settings.value( "/qgis/digitizing/reuseLastValues", false ).toBool(); + bool reuseLastValues = settings.value( QStringLiteral( "/qgis/digitizing/reuseLastValues" ), false ).toBool(); QgsDebugMsg( QString( "reuseLastValues: %1" ).arg( reuseLastValues ) ); QgsExpressionContext context = mLayer->createExpressionContext(); @@ -177,7 +177,7 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo //show the dialog to enter attribute values //only show if enabled in settings and layer has fields - bool isDisabledAttributeValuesDlg = ( fields.count() == 0 ) || settings.value( "/qgis/digitizing/disable_enter_attribute_values_dialog", false ).toBool(); + bool isDisabledAttributeValuesDlg = ( fields.count() == 0 ) || settings.value( QStringLiteral( "/qgis/digitizing/disable_enter_attribute_values_dialog" ), false ).toBool(); // override application-wide setting with any layer setting switch ( mLayer->editFormConfig().suppress() ) @@ -238,7 +238,7 @@ void QgsFeatureAction::onFeatureSaved( const QgsFeature& feature ) mFeatureSaved = true; QSettings settings; - bool reuseLastValues = settings.value( "/qgis/digitizing/reuseLastValues", false ).toBool(); + bool reuseLastValues = settings.value( QStringLiteral( "/qgis/digitizing/reuseLastValues" ), false ).toBool(); QgsDebugMsg( QString( "reuseLastValues: %1" ).arg( reuseLastValues ) ); if ( reuseLastValues ) diff --git a/src/app/qgsfieldcalculator.cpp b/src/app/qgsfieldcalculator.cpp index 75e15357ba98..4f223e37c79f 100644 --- a/src/app/qgsfieldcalculator.cpp +++ b/src/app/qgsfieldcalculator.cpp @@ -44,8 +44,8 @@ QgsFieldCalculator::QgsFieldCalculator( QgsVectorLayer* vl, QWidget* parent ) << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( mVectorLayer ); - expContext.lastScope()->setVariable( "row_number", 1 ); - expContext.setHighlightedVariables( QStringList() << "row_number" ); + expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), 1 ); + expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) ); builder->setLayer( vl ); builder->loadFieldNames(); @@ -68,7 +68,7 @@ QgsFieldCalculator::QgsFieldCalculator( QgsVectorLayer* vl, QWidget* parent ) mOutputFieldPrecisionSpinBox->setValue( 3 ); setPrecisionMinMax(); - if ( vl->providerType() == "ogr" && vl->storageType() == "ESRI Shapefile" ) + if ( vl->providerType() == QLatin1String( "ogr" ) && vl->storageType() == QLatin1String( "ESRI Shapefile" ) ) { mOutputFieldNameLineEdit->setMaxLength( 10 ); } @@ -132,25 +132,25 @@ QgsFieldCalculator::QgsFieldCalculator( QgsVectorLayer* vl, QWidget* parent ) mOnlyUpdateSelectedCheckBox->setEnabled( hasselection ); mOnlyUpdateSelectedCheckBox->setText( tr( "Only update %1 selected features" ).arg( vl->selectedFeatureCount() ) ); - builder->loadRecent( "fieldcalc" ); + builder->loadRecent( QStringLiteral( "fieldcalc" ) ); mInfoIcon->setPixmap( style()->standardPixmap( QStyle::SP_MessageBoxInformation ) ); setOkButtonState(); QSettings settings; - restoreGeometry( settings.value( "/Windows/QgsFieldCalculator/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsFieldCalculator/geometry" ) ).toByteArray() ); } QgsFieldCalculator::~QgsFieldCalculator() { QSettings settings; - settings.setValue( "/Windows/QgsFieldCalculator/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QgsFieldCalculator/geometry" ), saveGeometry() ); } void QgsFieldCalculator::accept() { - builder->saveToRecent( "fieldcalc" ); + builder->saveToRecent( QStringLiteral( "fieldcalc" ) ); if ( !mVectorLayer ) return; @@ -196,12 +196,12 @@ void QgsFieldCalculator::accept() QApplication::setOverrideCursor( Qt::WaitCursor ); - mVectorLayer->beginEditCommand( "Field calculator" ); + mVectorLayer->beginEditCommand( QStringLiteral( "Field calculator" ) ); //update existing field if ( mUpdateExistingGroupBox->isChecked() || !mNewFieldGroupBox->isEnabled() ) { - if ( mExistingFieldComboBox->currentData().toString() == "geom" ) + if ( mExistingFieldComboBox->currentData().toString() == QLatin1String( "geom" ) ) { //update geometry mAttributeId = -1; @@ -282,7 +282,7 @@ void QgsFieldCalculator::accept() while ( fit.nextFeature( feature ) ) { expContext.setFeature( feature ); - expContext.lastScope()->setVariable( QString( "row_number" ), rownum ); + expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), rownum ); QVariant value = exp.evaluate( &expContext ); if ( exp.hasEvalError() ) @@ -476,7 +476,7 @@ void QgsFieldCalculator::setOkButtonState() return; } - okButton->setToolTip( "" ); + okButton->setToolTip( QLatin1String( "" ) ); okButton->setEnabled( true ); } diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index 3cce7de4c89a..c644370df274 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -54,15 +54,15 @@ QgsFieldsProperties::QgsFieldsProperties( QgsVectorLayer *layer, QWidget* parent setupUi( this ); - mSplitter->restoreState( QSettings().value( "/Windows/VectorLayerProperties/FieldsProperties/SplitState" ).toByteArray() ); + mSplitter->restoreState( QSettings().value( QStringLiteral( "/Windows/VectorLayerProperties/FieldsProperties/SplitState" ) ).toByteArray() ); // Init as hidden by default, it will be enabled if project is set to mAttributeEditorOptionsWidget->setVisible( false ); - mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.svg" ) ); - mDeleteAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.svg" ) ); - mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( "/mActionToggleEditing.svg" ) ); - mCalculateFieldButton->setIcon( QgsApplication::getThemeIcon( "/mActionCalculateField.svg" ) ); + mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); + mDeleteAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); + mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) ); + mCalculateFieldButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCalculateField.svg" ) ) ); connect( mToggleEditingButton, SIGNAL( clicked() ), this, SIGNAL( toggleEditing() ) ); connect( mLayer, SIGNAL( editingStarted() ), this, SLOT( editingToggled() ) ); @@ -91,8 +91,8 @@ QgsFieldsProperties::QgsFieldsProperties( QgsVectorLayer *layer, QWidget* parent mFieldsList->setHorizontalHeaderItem( attrPrecCol, new QTableWidgetItem( tr( "Precision" ) ) ); mFieldsList->setHorizontalHeaderItem( attrCommentCol, new QTableWidgetItem( tr( "Comment" ) ) ); mFieldsList->setHorizontalHeaderItem( attrEditTypeCol, new QTableWidgetItem( tr( "Edit widget" ) ) ); - mFieldsList->setHorizontalHeaderItem( attrWMSCol, new QTableWidgetItem( "WMS" ) ); - mFieldsList->setHorizontalHeaderItem( attrWFSCol, new QTableWidgetItem( "WFS" ) ); + mFieldsList->setHorizontalHeaderItem( attrWMSCol, new QTableWidgetItem( QStringLiteral( "WMS" ) ) ); + mFieldsList->setHorizontalHeaderItem( attrWFSCol, new QTableWidgetItem( QStringLiteral( "WFS" ) ) ); mFieldsList->setHorizontalHeaderItem( attrAliasCol, new QTableWidgetItem( tr( "Alias" ) ) ); mFieldsList->setSortingEnabled( true ); @@ -131,7 +131,7 @@ QgsFieldsProperties::QgsFieldsProperties( QgsVectorLayer *layer, QWidget* parent QgsFieldsProperties::~QgsFieldsProperties() { - QSettings().setValue( "/Windows/VectorLayerProperties/FieldsProperties/SplitState", mSplitter->saveState() ); + QSettings().setValue( QStringLiteral( "/Windows/VectorLayerProperties/FieldsProperties/SplitState" ), mSplitter->saveState() ); } void QgsFieldsProperties::init() @@ -286,11 +286,11 @@ void QgsFieldsProperties::setRow( int row, int idx, const QgsField& field ) switch ( mLayer->fields().fieldOrigin( idx ) ) { case QgsFields::OriginExpression: - dataItem->setIcon( QgsApplication::getThemeIcon( "/mIconExpression.svg" ) ); + dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); break; case QgsFields::OriginJoin: - dataItem->setIcon( QgsApplication::getThemeIcon( "/propertyicons/join.png" ) ); + dataItem->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/join.png" ) ) ); break; default: @@ -310,7 +310,7 @@ void QgsFieldsProperties::setRow( int row, int idx, const QgsField& field ) expressionWidget->setLayout( new QHBoxLayout ); QToolButton* editExpressionButton = new QToolButton; editExpressionButton->setProperty( "Index", idx ); - editExpressionButton->setIcon( QgsApplication::getThemeIcon( "/mIconExpression.svg" ) ); + editExpressionButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); connect( editExpressionButton, SIGNAL( clicked() ), this, SLOT( updateExpression() ) ); expressionWidget->layout()->setContentsMargins( 0, 0, 0, 0 ); expressionWidget->layout()->addWidget( editExpressionButton ); @@ -376,7 +376,7 @@ void QgsFieldsProperties::loadRelations() QTableWidgetItem* item = new QTableWidgetItem( relation.name() ); item->setFlags( Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable ); - DesignerTreeItemData itemData( DesignerTreeItemData::Relation, QString( "%1" ).arg( relation.id() ) ); + DesignerTreeItemData itemData( DesignerTreeItemData::Relation, QStringLiteral( "%1" ).arg( relation.id() ) ); item->setData( DesignerTreeRole, itemData.asQVariant() ); mRelationsList->setItem( idx, RelNameCol, item ); @@ -397,11 +397,11 @@ void QgsFieldsProperties::loadRelations() Q_FOREACH ( const QgsRelation& nmrel, QgsProject::instance()->relationManager()->referencingRelations( relation.referencingLayer() ) ) { if ( nmrel.fieldPairs().at( 0 ).referencingField() != relation.fieldPairs().at( 0 ).referencingField() ) - nmCombo->addItem( QString( "%1 (%2)" ).arg( nmrel.referencedLayer()->name(), nmrel.fieldPairs().at( 0 ).referencedField() ), nmrel.id() ); + nmCombo->addItem( QStringLiteral( "%1 (%2)" ).arg( nmrel.referencedLayer()->name(), nmrel.fieldPairs().at( 0 ).referencedField() ), nmrel.id() ); const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( mLayer, relation.id() ); - const QVariant nmrelcfg = setup.config().value( "nm-rel" ); + const QVariant nmrelcfg = setup.config().value( QStringLiteral( "nm-rel" ) ); int idx = nmCombo->findData( nmrelcfg.toString() ); @@ -808,7 +808,7 @@ void QgsFieldsProperties::updateExpression() context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope(); - QgsExpressionBuilderDialog dlg( mLayer, exp, nullptr, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, exp, nullptr, QStringLiteral( "generic" ), context ); if ( dlg.exec() ) { @@ -896,14 +896,14 @@ QgsAttributeEditorElement* QgsFieldsProperties::createAttributeEditorWidget( QTr void QgsFieldsProperties::on_pbtnSelectInitFilePath_clicked() { QSettings myQSettings; - QString lastUsedDir = myQSettings.value( "style/lastInitFilePathDir", "." ).toString(); + QString lastUsedDir = myQSettings.value( QStringLiteral( "style/lastInitFilePathDir" ), "." ).toString(); QString pyfilename = QFileDialog::getOpenFileName( this, tr( "Select Python file" ), lastUsedDir, tr( "Python file" ) + " (*.py)" ); if ( pyfilename.isNull() ) return; QFileInfo fi( pyfilename ); - myQSettings.setValue( "style/lastInitFilePathDir", fi.path() ); + myQSettings.setValue( QStringLiteral( "style/lastInitFilePathDir" ), fi.path() ); mInitFilePathLineEdit->setText( pyfilename ); } @@ -911,14 +911,14 @@ void QgsFieldsProperties::on_pbtnSelectInitFilePath_clicked() void QgsFieldsProperties::on_pbnSelectEditForm_clicked() { QSettings myQSettings; - QString lastUsedDir = myQSettings.value( "style/lastUIDir", QDir::homePath() ).toString(); + QString lastUsedDir = myQSettings.value( QStringLiteral( "style/lastUIDir" ), QDir::homePath() ).toString(); QString uifilename = QFileDialog::getOpenFileName( this, tr( "Select edit form" ), lastUsedDir, tr( "UI file" ) + " (*.ui)" ); if ( uifilename.isNull() ) return; QFileInfo fi( uifilename ); - myQSettings.setValue( "style/lastUIDir", fi.path() ); + myQSettings.setValue( QStringLiteral( "style/lastUIDir" ), fi.path() ); mEditFormLineEdit->setText( uifilename ); } @@ -1006,7 +1006,7 @@ void QgsFieldsProperties::apply() if ( otherRelation.isValid() ) { - cfg["nm-rel"] = otherRelation.toString(); + cfg[QStringLiteral( "nm-rel" )] = otherRelation.toString(); } DesignerTreeItemData itemData = mRelationsList->item( i, RelNameCol )->data( DesignerTreeRole ).value(); @@ -1053,7 +1053,7 @@ QgsFieldsProperties::FieldConfig::FieldConfig( QgsVectorLayer* layer, int idx ) QStringList DragList::mimeTypes() const { - return QStringList() << QLatin1String( "application/x-qgsattributetabledesignerelement" ); + return QStringList() << QStringLiteral( "application/x-qgsattributetabledesignerelement" ); } QMimeData* DragList::mimeData( const QList items ) const @@ -1151,11 +1151,11 @@ void DesignerTree::dragMoveEvent( QDragMoveEvent *event ) { const QMimeData* data = event->mimeData(); - if ( data->hasFormat( "application/x-qgsattributetabledesignerelement" ) ) + if ( data->hasFormat( QStringLiteral( "application/x-qgsattributetabledesignerelement" ) ) ) { QgsFieldsProperties::DesignerTreeItemData itemElement; - QByteArray itemData = data->data( "application/x-qgsattributetabledesignerelement" ); + QByteArray itemData = data->data( QStringLiteral( "application/x-qgsattributetabledesignerelement" ) ); QDataStream stream( &itemData, QIODevice::ReadOnly ); stream >> itemElement; @@ -1183,9 +1183,9 @@ bool DesignerTree::dropMimeData( QTreeWidgetItem* parent, int index, const QMime { bDropSuccessful = true; } - else if ( data->hasFormat( "application/x-qgsattributetabledesignerelement" ) ) + else if ( data->hasFormat( QStringLiteral( "application/x-qgsattributetabledesignerelement" ) ) ) { - QByteArray itemData = data->data( "application/x-qgsattributetabledesignerelement" ); + QByteArray itemData = data->data( QStringLiteral( "application/x-qgsattributetabledesignerelement" ) ); QDataStream stream( &itemData, QIODevice::ReadOnly ); QgsFieldsProperties::DesignerTreeItemData itemElement; @@ -1211,7 +1211,7 @@ bool DesignerTree::dropMimeData( QTreeWidgetItem* parent, int index, const QMime void DesignerTree::dropEvent( QDropEvent* event ) { - if ( !event->mimeData()->hasFormat( "application/x-qgsattributetabledesignerelement" ) ) + if ( !event->mimeData()->hasFormat( QStringLiteral( "application/x-qgsattributetabledesignerelement" ) ) ) return; if ( event->source() == this ) @@ -1224,7 +1224,7 @@ void DesignerTree::dropEvent( QDropEvent* event ) QStringList DesignerTree::mimeTypes() const { - return QStringList() << QLatin1String( "application/x-qgsattributetabledesignerelement" ); + return QStringList() << QStringLiteral( "application/x-qgsattributetabledesignerelement" ); } QMimeData* DesignerTree::mimeData( const QList items ) const @@ -1266,7 +1266,7 @@ void DesignerTree::onItemDoubleClicked( QTreeWidgetItem* item, int column ) QFormLayout* baseLayout = new QFormLayout(); baseData->setLayout( baseLayout ); - QCheckBox* showLabelCheckbox = new QCheckBox( "Show label" ); + QCheckBox* showLabelCheckbox = new QCheckBox( QStringLiteral( "Show label" ) ); showLabelCheckbox->setChecked( itemData.showLabel() ); baseLayout->addWidget( showLabelCheckbox ); QWidget* baseWidget = new QWidget(); diff --git a/src/app/qgsformannotationdialog.cpp b/src/app/qgsformannotationdialog.cpp index 808573d139d3..5ad0dc20cd02 100644 --- a/src/app/qgsformannotationdialog.cpp +++ b/src/app/qgsformannotationdialog.cpp @@ -75,7 +75,7 @@ void QgsFormAnnotationDialog::on_mBrowseToolButton_clicked() { directory = fi.absolutePath(); } - QString filename = QFileDialog::getOpenFileName( nullptr, tr( "Qt designer file" ), directory, "*.ui" ); + QString filename = QFileDialog::getOpenFileName( nullptr, tr( "Qt designer file" ), directory, QStringLiteral( "*.ui" ) ); mFileLineEdit->setText( filename ); } diff --git a/src/app/qgsguivectorlayertools.cpp b/src/app/qgsguivectorlayertools.cpp index 1e55519da4ce..bcca09eacd84 100644 --- a/src/app/qgsguivectorlayertools.cpp +++ b/src/app/qgsguivectorlayertools.cpp @@ -164,7 +164,7 @@ void QgsGuiVectorLayerTools::commitError( QgsVectorLayer* vlayer ) const mv->setWindowTitle( tr( "Commit errors" ) ); mv->setMessageAsPlainText( tr( "Could not commit changes to layer %1" ).arg( vlayer->name() ) + "\n\n" - + tr( "Errors: %1\n" ).arg( vlayer->commitErrors().join( "\n " ) ) + + tr( "Errors: %1\n" ).arg( vlayer->commitErrors().join( QStringLiteral( "\n " ) ) ) ); QToolButton *showMore = new QToolButton(); @@ -172,7 +172,7 @@ void QgsGuiVectorLayerTools::commitError( QgsVectorLayer* vlayer ) const QAction *act = new QAction( showMore ); act->setData( QVariant( QMetaType::QObjectStar, &vlayer ) ); act->setText( tr( "Show more" ) ); - showMore->setStyleSheet( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ); + showMore->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) ); showMore->setCursor( Qt::PointingHandCursor ); showMore->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ); showMore->addAction( act ); diff --git a/src/app/qgshandlebadlayers.cpp b/src/app/qgshandlebadlayers.cpp index 7a2c87592526..daf56b84dbe8 100644 --- a/src/app/qgshandlebadlayers.cpp +++ b/src/app/qgshandlebadlayers.cpp @@ -95,11 +95,11 @@ QgsHandleBadLayers::QgsHandleBadLayers( const QList& layers ) { const QDomNode &node = mLayers[i]; - QString name = node.namedItem( "layername" ).toElement().text(); - QString type = node.toElement().attribute( "type" ); - QString datasource = node.namedItem( "datasource" ).toElement().text(); - QString provider = node.namedItem( "provider" ).toElement().text(); - QString vectorProvider = type == "vector" ? provider : tr( "none" ); + QString name = node.namedItem( QStringLiteral( "layername" ) ).toElement().text(); + QString type = node.toElement().attribute( QStringLiteral( "type" ) ); + QString datasource = node.namedItem( QStringLiteral( "datasource" ) ).toElement().text(); + QString provider = node.namedItem( QStringLiteral( "provider" ) ).toElement().text(); + QString vectorProvider = type == QLatin1String( "vector" ) ? provider : tr( "none" ); bool providerFileBased = ( QgsProviderRegistry::instance()->providerCapabilities( provider ) & QgsDataProvider::File ) != 0; QgsDebugMsg( QString( "name=%1 type=%2 provider=%3 datasource='%4'" ) @@ -138,7 +138,7 @@ QgsHandleBadLayers::QgsHandleBadLayers( const QList& layers ) } else { - item = new QTableWidgetItem( "" ); + item = new QTableWidgetItem( QLatin1String( "" ) ); mLayerList->setItem( j, 3, item ); } @@ -181,19 +181,19 @@ QString QgsHandleBadLayers::filename( int row ) QString provider = mLayerList->item( row, 2 )->text(); QString datasource = mLayerList->item( row, 4 )->text(); - if ( type == "vector" ) + if ( type == QLatin1String( "vector" ) ) { - if ( provider == "spatialite" ) + if ( provider == QLatin1String( "spatialite" ) ) { QgsDataSourceUri uri( datasource ); return uri.database(); } - else if ( provider == "ogr" ) + else if ( provider == QLatin1String( "ogr" ) ) { QStringList theURIParts = datasource.split( '|' ); return theURIParts[0]; } - else if ( provider == "delimitedtext" ) + else if ( provider == QLatin1String( "delimitedtext" ) ) { return QUrl::fromEncoded( datasource.toLatin1() ).toLocalFile(); } @@ -217,21 +217,21 @@ void QgsHandleBadLayers::setFilename( int row, const QString& filename ) QString datasource = item->text(); - if ( type == "vector" ) + if ( type == QLatin1String( "vector" ) ) { - if ( provider == "spatialite" ) + if ( provider == QLatin1String( "spatialite" ) ) { QgsDataSourceUri uri( datasource ); uri.setDatabase( filename ); datasource = uri.uri(); } - else if ( provider == "ogr" ) + else if ( provider == QLatin1String( "ogr" ) ) { QStringList theURIParts = datasource.split( '|' ); theURIParts[0] = filename; - datasource = theURIParts.join( "|" ); + datasource = theURIParts.join( QStringLiteral( "|" ) ); } - else if ( provider == "delimitedtext" ) + else if ( provider == QLatin1String( "delimitedtext" ) ) { QUrl uriSource = QUrl::fromEncoded( datasource.toLatin1() ); QUrl uriDest = QUrl::fromLocalFile( filename ); @@ -256,14 +256,14 @@ void QgsHandleBadLayers::browseClicked() QString type = mLayerList->item( row, 1 )->text(); QString memoryQualifier, fileFilter; - if ( type == "vector" ) + if ( type == QLatin1String( "vector" ) ) { - memoryQualifier = "lastVectorFileFilter"; + memoryQualifier = QStringLiteral( "lastVectorFileFilter" ); fileFilter = mVectorFileFilter; } else { - memoryQualifier = "lastRasterFileFilter"; + memoryQualifier = QStringLiteral( "lastRasterFileFilter" ); fileFilter = mRasterFileFilter; } @@ -289,7 +289,7 @@ void QgsHandleBadLayers::browseClicked() QString title = tr( "Select new directory of selected files" ); QSettings settings; - QString lastDir = settings.value( "/UI/missingDirectory", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "/UI/missingDirectory" ), QDir::homePath() ).toString(); QString selectedFolder = QFileDialog::getExistingDirectory( this, title, lastDir ); if ( selectedFolder.isEmpty() ) { @@ -339,7 +339,7 @@ void QgsHandleBadLayers::editAuthCfg() return; QString provider = mLayerList->item( row, 2 )->text(); - if ( provider == "none" ) + if ( provider == QLatin1String( "none" ) ) provider.clear(); QString prevuri = mLayerList->item( row, 4 )->text(); @@ -368,7 +368,7 @@ void QgsHandleBadLayers::apply() QTableWidgetItem *item = mLayerList->item( i, 4 ); QString datasource = item->text(); - node.namedItem( "datasource" ).toElement().firstChild().toText().setData( datasource ); + node.namedItem( QStringLiteral( "datasource" ) ).toElement().firstChild().toText().setData( datasource ); if ( QgsProject::instance()->read( node ) ) { mLayerList->removeRow( i-- ); diff --git a/src/app/qgshtmlannotationdialog.cpp b/src/app/qgshtmlannotationdialog.cpp index 727dc4648a5a..f5c2493da9b5 100644 --- a/src/app/qgshtmlannotationdialog.cpp +++ b/src/app/qgshtmlannotationdialog.cpp @@ -80,7 +80,7 @@ void QgsHtmlAnnotationDialog::on_mBrowseToolButton_clicked() { directory = QDir::homePath(); } - QString filename = QFileDialog::getOpenFileName( nullptr, tr( "html" ), directory, "HTML (*.html *.htm);;All files (*.*)" ); + QString filename = QFileDialog::getOpenFileName( nullptr, tr( "html" ), directory, QStringLiteral( "HTML (*.html *.htm);;All files (*.*)" ) ); mFileLineEdit->setText( filename ); } diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index 5d1e846cb232..d8da668f3641 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -266,7 +266,7 @@ QgsIdentifyResultsDialog::QgsIdentifyResultsDialog( QgsMapCanvas *canvas, QWidge QSettings mySettings; mDock = new QgsDockWidget( tr( "Identify Results" ), QgisApp::instance() ); - mDock->setObjectName( "IdentifyResultsDock" ); + mDock->setObjectName( QStringLiteral( "IdentifyResultsDock" ) ); mDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); mDock->setWidget( this ); if ( !QgisApp::instance()->restoreDockWidget( mDock ) ) @@ -274,7 +274,7 @@ QgsIdentifyResultsDialog::QgsIdentifyResultsDialog( QgsMapCanvas *canvas, QWidge else QgisApp::instance()->panelMenu()->addAction( mDock->toggleViewAction() ); - int size = mySettings.value( "/IconSize", 16 ).toInt(); + int size = mySettings.value( QStringLiteral( "/IconSize" ), 16 ).toInt(); if ( size > 32 ) { size -= 16; @@ -289,33 +289,33 @@ QgsIdentifyResultsDialog::QgsIdentifyResultsDialog( QgsMapCanvas *canvas, QWidge } mIdentifyToolbar->setIconSize( QSize( size, size ) ); - mExpandNewAction->setChecked( mySettings.value( "/Map/identifyExpand", false ).toBool() ); + mExpandNewAction->setChecked( mySettings.value( QStringLiteral( "/Map/identifyExpand" ), false ).toBool() ); mActionCopy->setEnabled( false ); lstResults->setColumnCount( 2 ); lstResults->sortByColumn( -1 ); setColumnText( 0, tr( "Feature" ) ); setColumnText( 1, tr( "Value" ) ); - int width = mySettings.value( "/Windows/Identify/columnWidth", "0" ).toInt(); + int width = mySettings.value( QStringLiteral( "/Windows/Identify/columnWidth" ), "0" ).toInt(); if ( width > 0 ) { lstResults->setColumnWidth( 0, width ); } - width = mySettings.value( "/Windows/Identify/columnWidthTable", "0" ).toInt(); + width = mySettings.value( QStringLiteral( "/Windows/Identify/columnWidthTable" ), "0" ).toInt(); if ( width > 0 ) { tblResults->setColumnWidth( 0, width ); } // retrieve mode before on_cmbIdentifyMode_currentIndexChanged resets it on addItem - int identifyMode = mySettings.value( "/Map/identifyMode", 0 ).toInt(); + int identifyMode = mySettings.value( QStringLiteral( "/Map/identifyMode" ), 0 ).toInt(); cmbIdentifyMode->addItem( tr( "Current layer" ), 0 ); cmbIdentifyMode->addItem( tr( "Top down, stop at first" ), 1 ); cmbIdentifyMode->addItem( tr( "Top down" ), 2 ); cmbIdentifyMode->addItem( tr( "Layer selection" ), 3 ); cmbIdentifyMode->setCurrentIndex( cmbIdentifyMode->findData( identifyMode ) ); - cbxAutoFeatureForm->setChecked( mySettings.value( "/Map/identifyAutoFeatureForm", false ).toBool() ); + cbxAutoFeatureForm->setChecked( mySettings.value( QStringLiteral( "/Map/identifyAutoFeatureForm" ), false ).toBool() ); // view modes cmbViewMode->addItem( tr( "Tree" ), 0 ); @@ -354,7 +354,7 @@ QgsIdentifyResultsDialog::~QgsIdentifyResultsDialog() clearHighlights(); QSettings settings; - settings.setValue( "/Windows/Identify/columnWidth", lstResults->columnWidth( 0 ) ); + settings.setValue( QStringLiteral( "/Windows/Identify/columnWidth" ), lstResults->columnWidth( 0 ) ); if ( mActionPopup ) delete mActionPopup; @@ -438,8 +438,8 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat if ( vlayer->fields().size() > 0 ) { - QTreeWidgetItem *editItem = new QTreeWidgetItem( QStringList() << "" << ( vlayer->isEditable() ? tr( "Edit feature form" ) : tr( "View feature form" ) ) ); - editItem->setIcon( 0, QgsApplication::getThemeIcon( "/mActionFormView.svg" ) ); + QTreeWidgetItem *editItem = new QTreeWidgetItem( QStringList() << QLatin1String( "" ) << ( vlayer->isEditable() ? tr( "Edit feature form" ) : tr( "View feature form" ) ) ); + editItem->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mActionFormView.svg" ) ) ); editItem->setData( 0, Qt::UserRole, "edit" ); actionItem->addChild( editItem ); } @@ -451,8 +451,8 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat if ( !action.runable() ) continue; - QTreeWidgetItem *twi = new QTreeWidgetItem( QStringList() << "" << action.name() ); - twi->setIcon( 0, QgsApplication::getThemeIcon( "/mAction.svg" ) ); + QTreeWidgetItem *twi = new QTreeWidgetItem( QStringList() << QLatin1String( "" ) << action.name() ); + twi->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ) ); twi->setData( 0, Qt::UserRole, "action" ); twi->setData( 0, Qt::UserRole + 1, QVariant::fromValue( i ) ); actionItem->addChild( twi ); @@ -462,8 +462,8 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat for ( int i = 0; i < registeredActions.size(); i++ ) { QgsMapLayerAction* action = registeredActions.at( i ); - QTreeWidgetItem *twi = new QTreeWidgetItem( QStringList() << "" << action->text() ); - twi->setIcon( 0, QgsApplication::getThemeIcon( "/mAction.svg" ) ); + QTreeWidgetItem *twi = new QTreeWidgetItem( QStringList() << QLatin1String( "" ) << action->text() ); + twi->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ) ); twi->setData( 0, Qt::UserRole, "map_layer_action" ); twi->setData( 0, Qt::UserRole + 1, qVariantFromValue( qobject_cast( action ) ) ); actionItem->addChild( twi ); @@ -482,7 +482,7 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat break; const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( vlayer, fields[i].name() ); - if ( setup.type() == "Hidden" ) + if ( setup.type() == QLatin1String( "Hidden" ) ) { continue; } @@ -710,7 +710,7 @@ void QgsIdentifyResultsDialog::addFeature( QgsRasterLayer *layer, QgsDebugMsg( QString( "feature.isValid() = %1" ).arg( feature.isValid() ) ); QTreeWidgetItem *layItem = layerItem( layer ); - QgsRaster::IdentifyFormat currentFormat = QgsRasterDataProvider::identifyFormatFromName( layer->customProperty( "identify/format" ).toString() ); + QgsRaster::IdentifyFormat currentFormat = QgsRasterDataProvider::identifyFormatFromName( layer->customProperty( QStringLiteral( "identify/format" ) ).toString() ); if ( !layItem ) { @@ -757,9 +757,9 @@ void QgsIdentifyResultsDialog::addFeature( QgsRasterLayer *layer, connect( layer, SIGNAL( crsChanged() ), this, SLOT( layerDestroyed() ) ); } // Set/reset getFeatureInfoUrl (currently only available for Feature, so it may change if format changes) - layItem->setData( 0, GetFeatureInfoUrlRole, params.value( "getFeatureInfoUrl" ) ); + layItem->setData( 0, GetFeatureInfoUrlRole, params.value( QStringLiteral( "getFeatureInfoUrl" ) ) ); - QgsIdentifyResultsFeatureItem *featItem = new QgsIdentifyResultsFeatureItem( fields, feature, layer->crs(), QStringList() << label << "" ); + QgsIdentifyResultsFeatureItem *featItem = new QgsIdentifyResultsFeatureItem( fields, feature, layer->crs(), QStringList() << label << QLatin1String( "" ) ); layItem->addChild( featItem ); // add feature attributes @@ -792,7 +792,7 @@ void QgsIdentifyResultsDialog::addFeature( QgsRasterLayer *layer, } else { - attrItem->setContent( tr( "No attributes." ).toUtf8(), "text/plain; charset=utf-8" ); + attrItem->setContent( tr( "No attributes." ).toUtf8(), QStringLiteral( "text/plain; charset=utf-8" ) ); } } else @@ -860,7 +860,7 @@ void QgsIdentifyResultsDialog::editingToggled() QTreeWidgetItem *featItem = layItem->child( i ); int j; - for ( j = 0; j < featItem->childCount() && featItem->child( j )->data( 0, Qt::UserRole ).toString() != "actions"; j++ ) + for ( j = 0; j < featItem->childCount() && featItem->child( j )->data( 0, Qt::UserRole ).toString() != QLatin1String( "actions" ); j++ ) QgsDebugMsg( QString( "%1: skipped %2" ).arg( featItem->child( j )->data( 0, Qt::UserRole ).toString() ) ); if ( j == featItem->childCount() || featItem->child( j )->childCount() < 1 ) @@ -868,7 +868,7 @@ void QgsIdentifyResultsDialog::editingToggled() QTreeWidgetItem *actions = featItem->child( j ); - for ( j = 0; i < actions->childCount() && actions->child( j )->data( 0, Qt::UserRole ).toString() != "edit"; j++ ) + for ( j = 0; i < actions->childCount() && actions->child( j )->data( 0, Qt::UserRole ).toString() != QLatin1String( "edit" ); j++ ) ; if ( j == actions->childCount() ) @@ -894,7 +894,7 @@ void QgsIdentifyResultsDialog::show() { lstResults->setCurrentItem( featItem ); - if ( QSettings().value( "/Map/identifyAutoFeatureForm", false ).toBool() ) + if ( QSettings().value( QStringLiteral( "/Map/identifyAutoFeatureForm" ), false ).toBool() ) { QgsVectorLayer *layer = qobject_cast( layItem->data( 0, Qt::UserRole ).value() ); if ( layer ) @@ -937,16 +937,16 @@ void QgsIdentifyResultsDialog::show() void QgsIdentifyResultsDialog::itemClicked( QTreeWidgetItem *item, int column ) { Q_UNUSED( column ); - if ( item->data( 0, Qt::UserRole ).toString() == "edit" ) + if ( item->data( 0, Qt::UserRole ).toString() == QLatin1String( "edit" ) ) { lstResults->setCurrentItem( item ); featureForm(); } - else if ( item->data( 0, Qt::UserRole ).toString() == "action" ) + else if ( item->data( 0, Qt::UserRole ).toString() == QLatin1String( "action" ) ) { doAction( item, item->data( 0, Qt::UserRole + 1 ).toInt() ); } - else if ( item->data( 0, Qt::UserRole ).toString() == "map_layer_action" ) + else if ( item->data( 0, Qt::UserRole ).toString() == QLatin1String( "map_layer_action" ) ) { QObject *action = item->data( 0, Qt::UserRole + 1 ).value(); doMapLayerAction( item, qobject_cast( action ) ); @@ -991,7 +991,7 @@ void QgsIdentifyResultsDialog::contextMenuEvent( QContextMenuEvent* event ) if ( vlayer ) { mActionPopup->addAction( - QgsApplication::getThemeIcon( "/mActionPropertyItem.svg" ), + QgsApplication::getThemeIcon( QStringLiteral( "/mActionPropertyItem.svg" ) ), vlayer->isEditable() ? tr( "Edit feature form" ) : tr( "View feature form" ), this, SLOT( featureForm() ) ); } @@ -1057,7 +1057,7 @@ void QgsIdentifyResultsDialog::contextMenuEvent( QContextMenuEvent* event ) continue; QgsFeatureAction *a = new QgsFeatureAction( action.name(), mFeatures[ featIdx ], vlayer, i, idx, this ); - mActionPopup->addAction( QgsApplication::getThemeIcon( "/mAction.svg" ), action.name(), a, SLOT( execute() ) ); + mActionPopup->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ), action.name(), a, SLOT( execute() ) ); } } @@ -1077,7 +1077,7 @@ void QgsIdentifyResultsDialog::contextMenuEvent( QContextMenuEvent* event ) for ( actionIt = registeredActions.begin(); actionIt != registeredActions.end(); ++actionIt ) { QgsIdentifyResultsDialogMapLayerAction *a = new QgsIdentifyResultsDialogMapLayerAction(( *actionIt )->text(), this, ( *actionIt ), vlayer, &( mFeatures[ featIdx ] ) ); - mActionPopup->addAction( QgsApplication::getThemeIcon( "/mAction.svg" ), ( *actionIt )->text(), a, SLOT( execute() ) ); + mActionPopup->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ), ( *actionIt )->text(), a, SLOT( execute() ) ); } } } @@ -1090,8 +1090,8 @@ void QgsIdentifyResultsDialog::saveWindowLocation() { QSettings settings; // first column width - settings.setValue( "/Windows/Identify/columnWidth", lstResults->columnWidth( 0 ) ); - settings.setValue( "/Windows/Identify/columnWidthTable", tblResults->columnWidth( 0 ) ); + settings.setValue( QStringLiteral( "/Windows/Identify/columnWidth" ), lstResults->columnWidth( 0 ) ); + settings.setValue( QStringLiteral( "/Windows/Identify/columnWidthTable" ), tblResults->columnWidth( 0 ) ); } void QgsIdentifyResultsDialog::setColumnText( int column, const QString & label ) @@ -1571,10 +1571,10 @@ void QgsIdentifyResultsDialog::highlightFeature( QTreeWidgetItem *item ) } QSettings settings; - QColor color = QColor( settings.value( "/Map/highlight/color", Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); - int alpha = settings.value( "/Map/highlight/colorAlpha", Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); - double buffer = settings.value( "/Map/highlight/buffer", Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); - double minWidth = settings.value( "/Map/highlight/minWidth", Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); + QColor color = QColor( settings.value( QStringLiteral( "/Map/highlight/color" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); + int alpha = settings.value( QStringLiteral( "/Map/highlight/colorAlpha" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); + double buffer = settings.value( QStringLiteral( "/Map/highlight/buffer" ), Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); + double minWidth = settings.value( QStringLiteral( "/Map/highlight/minWidth" ), Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); highlight->setColor( color ); // sets also fill with default alpha color.setAlpha( alpha ); @@ -1749,7 +1749,7 @@ void QgsIdentifyResultsDialog::copyFeatureAttributes() if ( attrIdx < 0 || attrIdx >= fields.count() ) continue; - text += QString( "%1: %2\n" ).arg( fields.at( attrIdx ).name(), it.value().toString() ); + text += QStringLiteral( "%1: %2\n" ).arg( fields.at( attrIdx ).name(), it.value().toString() ); } } else if ( rlayer ) @@ -1763,7 +1763,7 @@ void QgsIdentifyResultsDialog::copyFeatureAttributes() QTreeWidgetItem *item = featItem->child( i ); if ( item->childCount() > 0 ) continue; - text += QString( "%1: %2\n" ).arg( item->data( 0, Qt::DisplayRole ).toString(), item->data( 1, Qt::DisplayRole ).toString() ); + text += QStringLiteral( "%1: %2\n" ).arg( item->data( 0, Qt::DisplayRole ).toString(), item->data( 1, Qt::DisplayRole ).toString() ); } } @@ -1806,7 +1806,7 @@ void QgsIdentifyResultsDialog::printCurrentItem() void QgsIdentifyResultsDialog::on_cmbIdentifyMode_currentIndexChanged( int index ) { QSettings settings; - settings.setValue( "/Map/identifyMode", cmbIdentifyMode->itemData( index ).toInt() ); + settings.setValue( QStringLiteral( "/Map/identifyMode" ), cmbIdentifyMode->itemData( index ).toInt() ); } void QgsIdentifyResultsDialog::on_cmbViewMode_currentIndexChanged( int index ) @@ -1817,13 +1817,13 @@ void QgsIdentifyResultsDialog::on_cmbViewMode_currentIndexChanged( int index ) void QgsIdentifyResultsDialog::on_cbxAutoFeatureForm_toggled( bool checked ) { QSettings settings; - settings.setValue( "/Map/identifyAutoFeatureForm", checked ); + settings.setValue( QStringLiteral( "/Map/identifyAutoFeatureForm" ), checked ); } void QgsIdentifyResultsDialog::on_mExpandNewAction_triggered( bool checked ) { QSettings settings; - settings.setValue( "/Map/identifyExpand", checked ); + settings.setValue( QStringLiteral( "/Map/identifyExpand" ), checked ); } void QgsIdentifyResultsDialog::on_mActionCopy_triggered( bool checked ) @@ -1888,7 +1888,7 @@ void QgsIdentifyResultsDialog::formatChanged( int index ) } // Store selected identify format in layer - layer->setCustomProperty( "identify/format", QgsRasterDataProvider::identifyFormatName( format ) ); + layer->setCustomProperty( QStringLiteral( "identify/format" ), QgsRasterDataProvider::identifyFormatName( format ) ); // remove all childs of that layer from results, except the first (format) QTreeWidgetItem *layItem = layerItem( layer ); diff --git a/src/app/qgslabelinggui.cpp b/src/app/qgslabelinggui.cpp index 02943242428d..3fbed4d5f90b 100644 --- a/src/app/qgslabelinggui.cpp +++ b/src/app/qgslabelinggui.cpp @@ -551,7 +551,7 @@ QgsPalLayerSettings QgsLabelingGui::layerSettings() void QgsLabelingGui::setDataDefinedProperty( const QgsDataDefinedButton* ddBtn, QgsPalLayerSettings::DataDefinedProperties p, QgsPalLayerSettings& lyr ) { const QMap< QString, QString >& map = ddBtn->definedProperty(); - lyr.setDataDefinedProperty( p, map.value( "active" ).toInt(), map.value( "useexpr" ).toInt(), map.value( "expression" ), map.value( "field" ) ); + lyr.setDataDefinedProperty( p, map.value( QStringLiteral( "active" ) ).toInt(), map.value( QStringLiteral( "useexpr" ) ).toInt(), map.value( QStringLiteral( "expression" ) ), map.value( QStringLiteral( "field" ) ) ); } void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) @@ -604,8 +604,8 @@ void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) mFontCaseDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::FontCase ), QgsDataDefinedButton::String, - trString + QLatin1String( "[NoChange|Upper|
                                                                                                                                                                                    " - "Lower|Capitalize]" ) ); + trString + QStringLiteral( "[NoChange|Upper|
                                                                                                                                                                                    " + "Lower|Capitalize]" ) ); mFontLetterSpacingDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::FontLetterSpacing ), QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleDesc() ); @@ -668,8 +668,8 @@ void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) mShapeDrawDDBtn->registerCheckedWidget( mShapeDrawChkBx ); mShapeTypeDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::ShapeKind ), QgsDataDefinedButton::String, - trString + QLatin1String( "[Rectangle|Square|
                                                                                                                                                                                    " - "Ellipse|Circle|SVG]" ) ); + trString + QStringLiteral( "[Rectangle|Square|
                                                                                                                                                                                    " + "Ellipse|Circle|SVG]" ) ); mShapeSVGPathDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::ShapeSVGFile ), QgsDataDefinedButton::String, QgsDataDefinedButton::svgPathDesc() ); mShapeSizeTypeDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::ShapeSizeType ), @@ -715,8 +715,8 @@ void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) mShadowDrawDDBtn->registerCheckedWidget( mShadowDrawChkBx ); mShadowUnderDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::ShadowUnder ), QgsDataDefinedButton::String, - trString + QLatin1String( "[Lowest|Text|
                                                                                                                                                                                    " - "Buffer|Background]" ) ); + trString + QStringLiteral( "[Lowest|Text|
                                                                                                                                                                                    " + "Buffer|Background]" ) ); mShadowOffsetAngleDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::ShadowOffsetAngle ), QgsDataDefinedButton::AnyType, QgsDataDefinedButton::double180RotDesc() ); mShadowOffsetDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::ShadowOffsetDist ), @@ -742,17 +742,17 @@ void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) trString + "[Visible|Whole]" ); mPointQuadOffsetDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::OffsetQuad ), QgsDataDefinedButton::AnyType, - tr( "int
                                                                                                                                                                                    " ) + QLatin1String( "[0=Above Left|1=Above|2=Above Right|
                                                                                                                                                                                    " - "3=Left|4=Over|5=Right|
                                                                                                                                                                                    " - "6=Below Left|7=Below|8=Below Right]" ) ); + tr( "int
                                                                                                                                                                                    " ) + QStringLiteral( "[0=Above Left|1=Above|2=Above Right|
                                                                                                                                                                                    " + "3=Left|4=Over|5=Right|
                                                                                                                                                                                    " + "6=Below Left|7=Below|8=Below Right]" ) ); mPointPositionOrderDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::PredefinedPositionOrder ), QgsDataDefinedButton::String, tr( "Comma separated list of placements in order of priority
                                                                                                                                                                                    " ) - + QLatin1String( "[TL=Top left|TSL=Top, slightly left|T=Top middle|
                                                                                                                                                                                    " - "TSR=Top, slightly right|TR=Top right|
                                                                                                                                                                                    " - "L=Left|R=Right|
                                                                                                                                                                                    " - "BL=Bottom left|BSL=Bottom, slightly left|B=Bottom middle|
                                                                                                                                                                                    " - "BSR=Bottom, slightly right|BR=Bottom right]" ) ); + + QStringLiteral( "[TL=Top left|TSL=Top, slightly left|T=Top middle|
                                                                                                                                                                                    " + "TSR=Top, slightly right|TR=Top right|
                                                                                                                                                                                    " + "L=Left|R=Right|
                                                                                                                                                                                    " + "BL=Bottom left|BSL=Bottom, slightly left|B=Bottom middle|
                                                                                                                                                                                    " + "BSR=Bottom, slightly right|BR=Bottom right]" ) ); mPointOffsetDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::OffsetXY ), QgsDataDefinedButton::AnyType, QgsDataDefinedButton::doubleXYDesc() ); mPointOffsetUnitsDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::OffsetUnits ), @@ -790,8 +790,8 @@ void QgsLabelingGui::populateDataDefinedButtons( QgsPalLayerSettings& s ) mCoordAlignmentHDDBtn->setUsageInfo( ddPlaceInfo ); mCoordAlignmentVDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::Vali ), QgsDataDefinedButton::String, - trString + QLatin1String( "[Bottom|Base|
                                                                                                                                                                                    " - "Half|Cap|Top]" ) ); + trString + QStringLiteral( "[Bottom|Base|
                                                                                                                                                                                    " + "Half|Cap|Top]" ) ); mCoordAlignmentVDDBtn->setUsageInfo( ddPlaceInfo ); mCoordRotationDDBtn->init( mLayer, s.dataDefinedProperty( QgsPalLayerSettings::Rotation ), QgsDataDefinedButton::AnyType, QgsDataDefinedButton::double180RotDesc() ); diff --git a/src/app/qgslabelingwidget.cpp b/src/app/qgslabelingwidget.cpp index 1c56e3fac46a..56e511fd6791 100644 --- a/src/app/qgslabelingwidget.cpp +++ b/src/app/qgslabelingwidget.cpp @@ -48,7 +48,7 @@ void QgsLabelingWidget::resetSettings() { if ( mOldSettings.data() ) { - if ( mOldSettings->type() == "simple" ) + if ( mOldSettings->type() == QLatin1String( "simple" ) ) { mOldPalSettings.writeToLayer( mLayer ); } @@ -99,7 +99,7 @@ void QgsLabelingWidget::adaptToLayer() mLabelModeComboBox->setCurrentIndex( -1 ); // pick the right mode of the layer - if ( mLayer->labeling() && mLayer->labeling()->type() == "rule-based" ) + if ( mLayer->labeling() && mLayer->labeling()->type() == QLatin1String( "rule-based" ) ) { mLabelModeComboBox->setCurrentIndex( 2 ); } diff --git a/src/app/qgslabelpropertydialog.cpp b/src/app/qgslabelpropertydialog.cpp index d4c55f40e7d3..b91d4641ca35 100644 --- a/src/app/qgslabelpropertydialog.cpp +++ b/src/app/qgslabelpropertydialog.cpp @@ -42,13 +42,13 @@ QgsLabelPropertyDialog::QgsLabelPropertyDialog( const QString& layerId, const QS init( layerId, providerId, featureId, labelText ); QSettings settings; - restoreGeometry( settings.value( QString( "/Windows/ChangeLabelProps/geometry" ) ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ChangeLabelProps/geometry" ) ).toByteArray() ); } QgsLabelPropertyDialog::~QgsLabelPropertyDialog() { QSettings settings; - settings.setValue( QString( "/Windows/ChangeLabelProps/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ChangeLabelProps/geometry" ), saveGeometry() ); qDeleteAll( mDataDefinedProperties ); } @@ -95,7 +95,7 @@ void QgsLabelPropertyDialog::init( const QString& layerId, const QString& provid } else { - QString labelFieldName = vlayer->customProperty( "labeling/fieldName" ).toString(); + QString labelFieldName = vlayer->customProperty( QStringLiteral( "labeling/fieldName" ) ).toString(); if ( !labelFieldName.isEmpty() ) { mCurLabelField = vlayer->fields().lookupField( labelFieldName ); diff --git a/src/app/qgslayerstylingwidget.cpp b/src/app/qgslayerstylingwidget.cpp index 078f21080a1b..c868bd051d03 100644 --- a/src/app/qgslayerstylingwidget.cpp +++ b/src/app/qgslayerstylingwidget.cpp @@ -61,14 +61,14 @@ QgsLayerStylingWidget::QgsLayerStylingWidget( QgsMapCanvas* canvas, const QList< connect( QgsMapLayerRegistry::instance(), SIGNAL( layerWillBeRemoved( QgsMapLayer* ) ), this, SLOT( layerAboutToBeRemoved( QgsMapLayer* ) ) ); QSettings settings; - mLiveApplyCheck->setChecked( settings.value( "UI/autoApplyStyling", true ).toBool() ); + mLiveApplyCheck->setChecked( settings.value( QStringLiteral( "UI/autoApplyStyling" ), true ).toBool() ); mAutoApplyTimer = new QTimer( this ); mAutoApplyTimer->setSingleShot( true ); mUndoWidget = new QgsUndoWidget( this, mMapCanvas ); mUndoWidget->setAutoDelete( false ); - mUndoWidget->setObjectName( "Undo Styles" ); + mUndoWidget->setObjectName( QStringLiteral( "Undo Styles" ) ); mUndoWidget->hide(); mStyleManagerFactory = new QgsLayerStyleManagerWidgetFactory(); @@ -153,29 +153,29 @@ void QgsLayerStylingWidget::setLayer( QgsMapLayer *layer ) mUserPages.clear(); if ( layer->type() == QgsMapLayer::VectorLayer ) { - QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ), QString() ); + QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/symbology.svg" ) ), QString() ); symbolItem->setData( Qt::UserRole, Symbology ); symbolItem->setToolTip( tr( "Symbology" ) ); mOptionsListWidget->addItem( symbolItem ); - QListWidgetItem* labelItem = new QListWidgetItem( QgsApplication::getThemeIcon( "labelingSingle.svg" ), QString() ); + QListWidgetItem* labelItem = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "labelingSingle.svg" ) ), QString() ); labelItem->setData( Qt::UserRole, VectorLabeling ); labelItem->setToolTip( tr( "Labels" ) ); mOptionsListWidget->addItem( labelItem ); } else if ( layer->type() == QgsMapLayer::RasterLayer ) { - QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/symbology.svg" ), QString() ); + QListWidgetItem* symbolItem = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/symbology.svg" ) ), QString() ); symbolItem->setData( Qt::UserRole, Symbology ); symbolItem->setToolTip( tr( "Symbology" ) ); mOptionsListWidget->addItem( symbolItem ); - QListWidgetItem* transparencyItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/transparency.png" ), QString() ); + QListWidgetItem* transparencyItem = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/transparency.png" ) ), QString() ); transparencyItem->setToolTip( tr( "Transparency" ) ); transparencyItem->setData( Qt::UserRole, RasterTransparency ); mOptionsListWidget->addItem( transparencyItem ); if ( static_cast( layer )->dataProvider()->capabilities() & QgsRasterDataProvider::Size ) { - QListWidgetItem* histogramItem = new QListWidgetItem( QgsApplication::getThemeIcon( "propertyicons/histogram.png" ), QString() ); + QListWidgetItem* histogramItem = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/histogram.png" ) ), QString() ); histogramItem->setData( Qt::UserRole, RasterHistogram ); mOptionsListWidget->addItem( histogramItem ); histogramItem->setToolTip( tr( "Histogram" ) ); @@ -193,7 +193,7 @@ void QgsLayerStylingWidget::setLayer( QgsMapLayer *layer ) mUserPages[row] = factory; } } - QListWidgetItem* historyItem = new QListWidgetItem( QgsApplication::getThemeIcon( "mActionHistory.svg" ), QString() ); + QListWidgetItem* historyItem = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "mActionHistory.svg" ) ), QString() ); historyItem->setData( Qt::UserRole, History ); historyItem->setToolTip( tr( "History" ) ); mOptionsListWidget->addItem( historyItem ); @@ -211,8 +211,8 @@ void QgsLayerStylingWidget::setLayer( QgsMapLayer *layer ) mStackedWidget->setCurrentIndex( 1 ); QString errorMsg; - QDomDocument doc( "style" ); - mLastStyleXml = doc.createElement( "style" ); + QDomDocument doc( QStringLiteral( "style" ) ); + mLastStyleXml = doc.createElement( QStringLiteral( "style" ) ); doc.appendChild( mLastStyleXml ); mCurrentLayer->writeStyle( mLastStyleXml, doc, errorMsg ); } @@ -224,7 +224,7 @@ void QgsLayerStylingWidget::apply() disconnect( mCurrentLayer, SIGNAL( styleChanged() ), this, SLOT( updateCurrentWidgetLayer() ) ); - QString undoName = "Style Change"; + QString undoName = QStringLiteral( "Style Change" ); QWidget* current = mWidgetStack->mainPanel(); @@ -233,7 +233,7 @@ void QgsLayerStylingWidget::apply() { widget->apply(); styleWasChanged = true; - undoName = "Label Change"; + undoName = QStringLiteral( "Label Change" ); } if ( QgsPanelWidgetWrapper* wrapper = qobject_cast( current ) ) { @@ -242,7 +242,7 @@ void QgsLayerStylingWidget::apply() widget->apply(); QgsVectorLayer* layer = qobject_cast( mCurrentLayer ); QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( layer->renderer()->type() ); - undoName = QString( "Style Change - %1" ).arg( m->visibleName() ); + undoName = QStringLiteral( "Style Change - %1" ).arg( m->visibleName() ); styleWasChanged = true; } } @@ -456,14 +456,14 @@ void QgsLayerStylingWidget::layerAboutToBeRemoved( QgsMapLayer* layer ) void QgsLayerStylingWidget::liveApplyToggled( bool value ) { QSettings settings; - settings.setValue( "UI/autoApplyStyling", value ); + settings.setValue( QStringLiteral( "UI/autoApplyStyling" ), value ); } void QgsLayerStylingWidget::pushUndoItem( const QString &name ) { QString errorMsg; - QDomDocument doc( "style" ); - QDomElement rootNode = doc.createElement( "qgis" ); + QDomDocument doc( QStringLiteral( "style" ) ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); doc.appendChild( rootNode ); mCurrentLayer->writeStyle( rootNode, doc, errorMsg ); mCurrentLayer->undoStackStyles()->push( new QgsMapLayerStyleCommand( mCurrentLayer, name, rootNode, mLastStyleXml ) ); @@ -507,7 +507,7 @@ bool QgsMapLayerStyleCommand::mergeWith( const QUndoCommand* other ) // only merge commands if they are created shortly after each other // (e.g. user keeps modifying one property) QSettings settings; - int timeout = settings.value( "/UI/styleUndoMergeTimeout", 500 ).toInt(); + int timeout = settings.value( QStringLiteral( "/UI/styleUndoMergeTimeout" ), 500 ).toInt(); if ( mTime.msecsTo( otherCmd->mTime ) > timeout ) return false; @@ -518,7 +518,7 @@ bool QgsMapLayerStyleCommand::mergeWith( const QUndoCommand* other ) QgsLayerStyleManagerWidgetFactory::QgsLayerStyleManagerWidgetFactory() { - setIcon( QgsApplication::getThemeIcon( "propertyicons/stylepreset.svg" ) ); + setIcon( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/stylepreset.svg" ) ) ); setTitle( QObject::tr( "Style Manager" ) ); } diff --git a/src/app/qgsloadstylefromdbdialog.cpp b/src/app/qgsloadstylefromdbdialog.cpp index c2ef1e2dd585..5923eeccee0e 100644 --- a/src/app/qgsloadstylefromdbdialog.cpp +++ b/src/app/qgsloadstylefromdbdialog.cpp @@ -25,8 +25,8 @@ QgsLoadStyleFromDBDialog::QgsLoadStyleFromDBDialog( QWidget *parent ) , mSectionLimit( 0 ) { setupUi( this ); - setWindowTitle( "Load style from database" ); - mSelectedStyleId = ""; + setWindowTitle( QStringLiteral( "Load style from database" ) ); + mSelectedStyleId = QLatin1String( "" ); mLoadButton->setDisabled( true ); mRelatedTable->setEditTriggers( QTableWidget::NoEditTriggers ); @@ -51,14 +51,14 @@ QgsLoadStyleFromDBDialog::QgsLoadStyleFromDBDialog( QWidget *parent ) setTabOrder( mCancelButton, mLoadButton ); QSettings settings; - restoreGeometry( settings.value( "/Windows/loadStyleFromDb/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/loadStyleFromDb/geometry" ) ).toByteArray() ); } QgsLoadStyleFromDBDialog::~QgsLoadStyleFromDBDialog() { QSettings settings; - settings.setValue( "/Windows/loadStyleFromDb/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/loadStyleFromDb/geometry" ), saveGeometry() ); } void QgsLoadStyleFromDBDialog::initializeLists( const QStringList& ids, const QStringList& names, const QStringList& descriptions, int sectionLimit ) @@ -66,8 +66,8 @@ void QgsLoadStyleFromDBDialog::initializeLists( const QStringList& ids, const QS mSectionLimit = sectionLimit; int relatedTableNOfCols = sectionLimit > 0 ? 2 : 1; int othersTableNOfCols = ids.count() - sectionLimit > 0 ? 2 : 1; - QString twoColsHeader( "Name;Description" ); - QString oneColsHeader( "No styles found in the database" ); + QString twoColsHeader( QStringLiteral( "Name;Description" ) ); + QString oneColsHeader( QStringLiteral( "No styles found in the database" ) ); QString relatedTableHeader = relatedTableNOfCols == 1 ? oneColsHeader : twoColsHeader; QString othersTableHeader = othersTableNOfCols == 1 ? oneColsHeader : twoColsHeader; @@ -82,18 +82,18 @@ void QgsLoadStyleFromDBDialog::initializeLists( const QStringList& ids, const QS for ( int i = 0; i < sectionLimit; i++ ) { - QTableWidgetItem *item = new QTableWidgetItem( names.value( i, "" ) ); + QTableWidgetItem *item = new QTableWidgetItem( names.value( i, QLatin1String( "" ) ) ); item->setData( Qt::UserRole, ids[i] ); mRelatedTable->setItem( i, 0, item ); - mRelatedTable->setItem( i, 1, new QTableWidgetItem( descriptions.value( i, "" ) ) ); + mRelatedTable->setItem( i, 1, new QTableWidgetItem( descriptions.value( i, QLatin1String( "" ) ) ) ); } for ( int i = sectionLimit; i < ids.count(); i++ ) { int j = i - sectionLimit; - QTableWidgetItem *item = new QTableWidgetItem( names.value( i, "" ) ); + QTableWidgetItem *item = new QTableWidgetItem( names.value( i, QLatin1String( "" ) ) ); item->setData( Qt::UserRole, ids[i] ); mOthersTable->setItem( j, 0, item ); - mOthersTable->setItem( j, 1, new QTableWidgetItem( descriptions.value( i, "" ) ) ); + mOthersTable->setItem( j, 1, new QTableWidgetItem( descriptions.value( i, QLatin1String( "" ) ) ) ); } } diff --git a/src/app/qgsmaplayerstyleguiutils.cpp b/src/app/qgsmaplayerstyleguiutils.cpp index 95802f366453..86590bbb1a34 100644 --- a/src/app/qgsmaplayerstyleguiutils.cpp +++ b/src/app/qgsmaplayerstyleguiutils.cpp @@ -108,7 +108,7 @@ void QgsMapLayerStyleGuiUtils::addStyle() bool ok; QString text = QInputDialog::getText( nullptr, tr( "New style" ), tr( "Style name:" ), QLineEdit::Normal, - "new style", &ok ); + QStringLiteral( "new style" ), &ok ); if ( !ok || text.isEmpty() ) return; diff --git a/src/app/qgsmaptoolchangelabelproperties.cpp b/src/app/qgsmaptoolchangelabelproperties.cpp index fd11a4007c57..a92ddcd97e45 100644 --- a/src/app/qgsmaptoolchangelabelproperties.cpp +++ b/src/app/qgsmaptoolchangelabelproperties.cpp @@ -84,7 +84,7 @@ void QgsMapToolChangeLabelProperties::applyChanges( const QgsAttributeMap& chang if ( !changes.isEmpty() ) { - vlayer->beginEditCommand( tr( "Changed properties for label" ) + QString( " '%1'" ).arg( currentLabelText( 24 ) ) ); + vlayer->beginEditCommand( tr( "Changed properties for label" ) + QStringLiteral( " '%1'" ).arg( currentLabelText( 24 ) ) ); QgsAttributeMap::const_iterator changeIt = changes.constBegin(); for ( ; changeIt != changes.constEnd(); ++changeIt ) diff --git a/src/app/qgsmaptoolfeatureaction.cpp b/src/app/qgsmaptoolfeatureaction.cpp index 11b766a2f9a1..e3fe5bdb1fe7 100644 --- a/src/app/qgsmaptoolfeatureaction.cpp +++ b/src/app/qgsmaptoolfeatureaction.cpp @@ -143,8 +143,8 @@ bool QgsMapToolFeatureAction::doAction( QgsVectorLayer *layer, int x, int y ) << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::mapSettingsScope( mCanvas->mapSettings() ); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); - actionScope->setVariable( "click_x", point.x() ); - actionScope->setVariable( "click_y", point.y() ); + actionScope->setVariable( QStringLiteral( "click_x" ), point.x() ); + actionScope->setVariable( QStringLiteral( "click_y" ), point.y() ); context << actionScope; int actionIdx = layer->actions()->defaultAction(); diff --git a/src/app/qgsmaptoolidentifyaction.cpp b/src/app/qgsmaptoolidentifyaction.cpp index 9e09c83d644a..097af280805e 100644 --- a/src/app/qgsmaptoolidentifyaction.cpp +++ b/src/app/qgsmaptoolidentifyaction.cpp @@ -91,12 +91,12 @@ void QgsMapToolIdentifyAction::showAttributeTable( QgsMapLayer* layer, const QLi if ( !vl ) return; - QString filter = "$id IN ("; + QString filter = QStringLiteral( "$id IN (" ); Q_FOREACH ( const QgsFeature &feature, featureList ) { - filter.append( QString( "%1," ).arg( feature.id() ) ); + filter.append( QStringLiteral( "%1," ).arg( feature.id() ) ); } - filter = filter.replace( QRegExp( ",$" ), ")" ); + filter = filter.replace( QRegExp( ",$" ), QStringLiteral( ")" ) ); QgsAttributeTableDialog* tableDialog = new QgsAttributeTableDialog( vl ); tableDialog->setFilterExpression( filter ); @@ -142,7 +142,7 @@ void QgsMapToolIdentifyAction::canvasReleaseEvent( QgsMapMouseEvent* e ) { // Show the dialog before items are inserted so that items can resize themselves // according to dialog size also the first time, see also #9377 - if ( results.size() != 1 || !QSettings().value( "/Map/identifyAutoFeatureForm", false ).toBool() ) + if ( results.size() != 1 || !QSettings().value( QStringLiteral( "/Map/identifyAutoFeatureForm" ), false ).toBool() ) resultsDialog()->QDialog::show(); QList::const_iterator result; diff --git a/src/app/qgsmaptoollabel.cpp b/src/app/qgsmaptoollabel.cpp index 487a527f610c..18d17ff3d87d 100644 --- a/src/app/qgsmaptoollabel.cpp +++ b/src/app/qgsmaptoollabel.cpp @@ -88,10 +88,10 @@ void QgsMapToolLabel::createRubberBands() if ( !geom.isEmpty() ) { QSettings settings; - int r = settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(); - int g = settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(); - int b = settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt(); - int a = settings.value( "/qgis/digitizing/line_color_alpha", 200 ).toInt(); + int r = settings.value( QStringLiteral( "/qgis/digitizing/line_color_red" ), 255 ).toInt(); + int g = settings.value( QStringLiteral( "/qgis/digitizing/line_color_green" ), 0 ).toInt(); + int b = settings.value( QStringLiteral( "/qgis/digitizing/line_color_blue" ), 0 ).toInt(); + int a = settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), 200 ).toInt(); mFeatureRubberBand = new QgsRubberBand( mCanvas, geom.type() ); mFeatureRubberBand->setColor( QColor( r, g, b, a ) ); mFeatureRubberBand->setToGeometry( geom, vlayer ); @@ -136,7 +136,7 @@ QString QgsMapToolLabel::currentLabelText( int trunc ) { if ( !mCurrentLabel.valid ) { - return ""; + return QLatin1String( "" ); } QgsPalLayerSettings& labelSettings = mCurrentLabel.settings; @@ -147,7 +147,7 @@ QString QgsMapToolLabel::currentLabelText( int trunc ) if ( trunc > 0 && labelText.length() > trunc ) { labelText.truncate( trunc ); - labelText += "..."; + labelText += QLatin1String( "..." ); } return labelText; } @@ -156,10 +156,10 @@ QString QgsMapToolLabel::currentLabelText( int trunc ) QgsVectorLayer* vlayer = mCurrentLabel.layer; if ( !vlayer ) { - return ""; + return QLatin1String( "" ); } - QString labelField = vlayer->customProperty( "labeling/fieldName" ).toString(); + QString labelField = vlayer->customProperty( QStringLiteral( "labeling/fieldName" ) ).toString(); if ( !labelField.isEmpty() ) { int labelFieldId = vlayer->fields().lookupField( labelField ); @@ -170,19 +170,19 @@ QString QgsMapToolLabel::currentLabelText( int trunc ) if ( trunc > 0 && labelText.length() > trunc ) { labelText.truncate( trunc ); - labelText += "..."; + labelText += QLatin1String( "..." ); } return labelText; } } } - return ""; + return QLatin1String( "" ); } void QgsMapToolLabel::currentAlignment( QString& hali, QString& vali ) { - hali = "Left"; - vali = "Bottom"; + hali = QStringLiteral( "Left" ); + vali = QStringLiteral( "Bottom" ); QgsVectorLayer* vlayer = mCurrentLabel.layer; if ( !vlayer ) @@ -330,8 +330,8 @@ bool QgsMapToolLabel::currentLabelRotationPoint( QgsPoint& pos, bool ignoreUpsid // rotate unpinned labels (i.e. no hali/vali settings) as if hali/vali was Center/Half if ( rotatingUnpinned ) { - haliString = "Center"; - valiString = "Half"; + haliString = QStringLiteral( "Center" ); + valiString = QStringLiteral( "Half" ); } // QFont labelFont = labelFontCurrentFeature(); @@ -351,27 +351,27 @@ bool QgsMapToolLabel::currentLabelRotationPoint( QgsPoint& pos, bool ignoreUpsid double xdiff = 0; double ydiff = 0; - if ( haliString.compare( "Center", Qt::CaseInsensitive ) == 0 ) + if ( haliString.compare( QLatin1String( "Center" ), Qt::CaseInsensitive ) == 0 ) { xdiff = labelSizeX / 2.0; } - else if ( haliString.compare( "Right", Qt::CaseInsensitive ) == 0 ) + else if ( haliString.compare( QLatin1String( "Right" ), Qt::CaseInsensitive ) == 0 ) { xdiff = labelSizeX; } - if ( valiString.compare( "Top", Qt::CaseInsensitive ) == 0 || valiString.compare( "Cap", Qt::CaseInsensitive ) == 0 ) + if ( valiString.compare( QLatin1String( "Top" ), Qt::CaseInsensitive ) == 0 || valiString.compare( QLatin1String( "Cap" ), Qt::CaseInsensitive ) == 0 ) { ydiff = labelSizeY; } else { double descentRatio = 1 / labelFontMetrics.ascent() / labelFontMetrics.height(); - if ( valiString.compare( "Base", Qt::CaseInsensitive ) == 0 ) + if ( valiString.compare( QLatin1String( "Base" ), Qt::CaseInsensitive ) == 0 ) { ydiff = labelSizeY * descentRatio; } - else if ( valiString.compare( "Half", Qt::CaseInsensitive ) == 0 ) + else if ( valiString.compare( QLatin1String( "Half" ), Qt::CaseInsensitive ) == 0 ) { ydiff = labelSizeY * 0.5 * ( 1 - descentRatio ); } diff --git a/src/app/qgsmaptoolmeasureangle.cpp b/src/app/qgsmaptoolmeasureangle.cpp index 37e71af1ef69..032e5c59ccd6 100644 --- a/src/app/qgsmaptoolmeasureangle.cpp +++ b/src/app/qgsmaptoolmeasureangle.cpp @@ -135,9 +135,9 @@ void QgsMapToolMeasureAngle::createRubberBand() mRubberBand = new QgsRubberBand( mCanvas, QgsWkbTypes::LineGeometry ); QSettings settings; - int myRed = settings.value( "/qgis/default_measure_color_red", 180 ).toInt(); - int myGreen = settings.value( "/qgis/default_measure_color_green", 180 ).toInt(); - int myBlue = settings.value( "/qgis/default_measure_color_blue", 180 ).toInt(); + int myRed = settings.value( QStringLiteral( "/qgis/default_measure_color_red" ), 180 ).toInt(); + int myGreen = settings.value( QStringLiteral( "/qgis/default_measure_color_green" ), 180 ).toInt(); + int myBlue = settings.value( QStringLiteral( "/qgis/default_measure_color_blue" ), 180 ).toInt(); mRubberBand->setColor( QColor( myRed, myGreen, myBlue, 100 ) ); mRubberBand->setWidth( 3 ); } diff --git a/src/app/qgsmaptoolmovelabel.cpp b/src/app/qgsmaptoolmovelabel.cpp index 6d886eb0489c..72790d91261a 100644 --- a/src/app/qgsmaptoolmovelabel.cpp +++ b/src/app/qgsmaptoolmovelabel.cpp @@ -147,7 +147,7 @@ void QgsMapToolMoveLabel::canvasReleaseEvent( QgsMapMouseEvent* e ) } } - vlayer->beginEditCommand( tr( "Moved label" ) + QString( " '%1'" ).arg( currentLabelText( 24 ) ) ); + vlayer->beginEditCommand( tr( "Moved label" ) + QStringLiteral( " '%1'" ).arg( currentLabelText( 24 ) ) ); vlayer->changeAttributeValue( mCurrentLabel.pos.featureId, xCol, xPosNew ); vlayer->changeAttributeValue( mCurrentLabel.pos.featureId, yCol, yPosNew ); diff --git a/src/app/qgsmaptooloffsetcurve.cpp b/src/app/qgsmaptooloffsetcurve.cpp index 8722764e1b90..bebc5284530b 100644 --- a/src/app/qgsmaptooloffsetcurve.cpp +++ b/src/app/qgsmaptooloffsetcurve.cpp @@ -91,8 +91,8 @@ void QgsMapToolOffsetCurve::canvasReleaseEvent( QgsMapMouseEvent* e ) QSettings settings; config.setMode( QgsSnappingConfig::AllLayers ); config.setType( QgsSnappingConfig::Segment ); - config.setTolerance( settings.value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble() ); - config.setUnits( static_cast( settings.value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt() ) ); + config.setTolerance( settings.value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit" ), 10 ).toDouble() ); + config.setUnits( static_cast( settings.value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit_unit" ), QgsTolerance::Pixels ).toInt() ) ); snapping->setConfig( config ); QgsPointLocator::Match match = snapping->snapToMap( e->pos() ); @@ -372,9 +372,9 @@ void QgsMapToolOffsetCurve::setOffsetForRubberBand( double offset ) if ( geosGeom ) { QSettings s; - int joinStyle = s.value( "/qgis/digitizing/offset_join_style", 0 ).toInt(); - int quadSegments = s.value( "/qgis/digitizing/offset_quad_seg", 8 ).toInt(); - double mitreLimit = s.value( "/qgis/digitizing/offset_miter_limit", 5.0 ).toDouble(); + int joinStyle = s.value( QStringLiteral( "/qgis/digitizing/offset_join_style" ), 0 ).toInt(); + int quadSegments = s.value( QStringLiteral( "/qgis/digitizing/offset_quad_seg" ), 8 ).toInt(); + double mitreLimit = s.value( QStringLiteral( "/qgis/digitizing/offset_miter_limit" ), 5.0 ).toDouble(); GEOSGeometry* offsetGeom = GEOSOffsetCurve_r( QgsGeometry::getGEOSHandler(), geosGeom, offset, quadSegments, joinStyle, mitreLimit ); if ( !offsetGeom ) diff --git a/src/app/qgsmaptooloffsetpointsymbol.cpp b/src/app/qgsmaptooloffsetpointsymbol.cpp index 72effcaf01b8..b1057ce4a767 100644 --- a/src/app/qgsmaptooloffsetpointsymbol.cpp +++ b/src/app/qgsmaptooloffsetpointsymbol.cpp @@ -89,19 +89,19 @@ bool QgsMapToolOffsetPointSymbol::checkSymbolCompatibility( QgsMarkerSymbol* mar Q_FOREACH ( QgsSymbolLayer* layer, markerSymbol->symbolLayers() ) { - if ( !layer->hasDataDefinedProperty( "offset" ) ) + if ( !layer->hasDataDefinedProperty( QStringLiteral( "offset" ) ) ) continue; - if ( layer->getDataDefinedProperty( "offset" )->useExpression() ) + if ( layer->getDataDefinedProperty( QStringLiteral( "offset" ) )->useExpression() ) continue; ok = true; if ( mMarkerSymbol.isNull() ) { double symbolRotation = markerSymbol->angle(); - if ( layer->hasDataDefinedProperty( "angle" ) ) + if ( layer->hasDataDefinedProperty( QStringLiteral( "angle" ) ) ) { - QString rotationExp = layer->getDataDefinedProperty( "angle" )->expressionOrField(); + QString rotationExp = layer->getDataDefinedProperty( QStringLiteral( "angle" ) )->expressionOrField(); QgsExpression exp( rotationExp ); QVariant val = exp.evaluate( &context.expressionContext() ); bool convertOk = false; @@ -188,10 +188,10 @@ QMap QgsMapToolOffsetPointSymbol::calculateNewOffsetAttributes( c QMap newAttrValues; Q_FOREACH ( QgsSymbolLayer* layer, mMarkerSymbol->symbolLayers() ) { - if ( !layer->hasDataDefinedProperty( "offset" ) ) + if ( !layer->hasDataDefinedProperty( QStringLiteral( "offset" ) ) ) continue; - if ( layer->getDataDefinedProperty( "offset" )->useExpression() ) + if ( layer->getDataDefinedProperty( QStringLiteral( "offset" ) )->useExpression() ) continue; QgsMarkerSymbolLayer* ml = dynamic_cast< QgsMarkerSymbolLayer* >( layer ); @@ -199,7 +199,7 @@ QMap QgsMapToolOffsetPointSymbol::calculateNewOffsetAttributes( c continue; QPointF offset = calculateOffset( startPoint, endPoint, ml->offsetUnit() ); - int fieldIdx = mActiveLayer->fields().indexFromName( layer->getDataDefinedProperty( "offset" )->field() ); + int fieldIdx = mActiveLayer->fields().indexFromName( layer->getDataDefinedProperty( QStringLiteral( "offset" ) )->field() ); if ( fieldIdx >= 0 ) newAttrValues[ fieldIdx ] = QgsSymbolLayerUtils::encodePoint( offset ); } diff --git a/src/app/qgsmaptoolpinlabels.cpp b/src/app/qgsmaptoolpinlabels.cpp index cdc14aebea7e..d3a4297d3832 100644 --- a/src/app/qgsmaptoolpinlabels.cpp +++ b/src/app/qgsmaptoolpinlabels.cpp @@ -189,7 +189,7 @@ void QgsMapToolPinLabels::highlightPinnedLabels() if ( isPinned() ) { - QString labelStringID = QString( "%0|%1|%2" ).arg( QString::number( pos.isDiagram ), pos.layerID, QString::number( pos.featureId ) ); + QString labelStringID = QStringLiteral( "%0|%1|%2" ).arg( QString::number( pos.isDiagram ), pos.layerID, QString::number( pos.featureId ) ); // don't highlight again if ( mHighlights.contains( labelStringID ) ) @@ -370,7 +370,7 @@ bool QgsMapToolPinLabels::pinUnpinCurrentLabel( bool pin ) labelY = transformedPoint.y(); } - vlayer->beginEditCommand( tr( "Pinned label" ) + QString( " '%1'" ).arg( labelText ) ); + vlayer->beginEditCommand( tr( "Pinned label" ) + QStringLiteral( " '%1'" ).arg( labelText ) ); writeFailed = !vlayer->changeAttributeValue( fid, xCol, labelX ); if ( !vlayer->changeAttributeValue( fid, yCol, labelY ) ) writeFailed = true; @@ -383,7 +383,7 @@ bool QgsMapToolPinLabels::pinUnpinCurrentLabel( bool pin ) } else { - vlayer->beginEditCommand( tr( "Unpinned label" ) + QString( " '%1'" ).arg( labelText ) ); + vlayer->beginEditCommand( tr( "Unpinned label" ) + QStringLiteral( " '%1'" ).arg( labelText ) ); writeFailed = !vlayer->changeAttributeValue( fid, xCol, QVariant( QString::null ) ); if ( !vlayer->changeAttributeValue( fid, yCol, QVariant( QString::null ) ) ) writeFailed = true; @@ -464,7 +464,7 @@ bool QgsMapToolPinLabels::pinUnpinCurrentDiagram( bool pin ) labelY = transformedPoint.y(); } - vlayer->beginEditCommand( tr( "Pinned diagram" ) + QString( " '%1'" ).arg( labelText ) ); + vlayer->beginEditCommand( tr( "Pinned diagram" ) + QStringLiteral( " '%1'" ).arg( labelText ) ); writeFailed = !vlayer->changeAttributeValue( fid, xCol, labelX ); if ( !vlayer->changeAttributeValue( fid, yCol, labelY ) ) writeFailed = true; @@ -472,7 +472,7 @@ bool QgsMapToolPinLabels::pinUnpinCurrentDiagram( bool pin ) } else { - vlayer->beginEditCommand( tr( "Unpinned diagram" ) + QString( " '%1'" ).arg( labelText ) ); + vlayer->beginEditCommand( tr( "Unpinned diagram" ) + QStringLiteral( " '%1'" ).arg( labelText ) ); writeFailed = !vlayer->changeAttributeValue( fid, xCol, QVariant( QString::null ) ); if ( !vlayer->changeAttributeValue( fid, yCol, QVariant( QString::null ) ) ) writeFailed = true; diff --git a/src/app/qgsmaptoolrotatefeature.cpp b/src/app/qgsmaptoolrotatefeature.cpp index cb9d597b3e1c..8dda0c792cea 100644 --- a/src/app/qgsmaptoolrotatefeature.cpp +++ b/src/app/qgsmaptoolrotatefeature.cpp @@ -56,7 +56,7 @@ QgsAngleMagnetWidget::QgsAngleMagnetWidget( const QString& label , QWidget *pare mAngleSpinBox = new QgsDoubleSpinBox( this ); mAngleSpinBox->setMinimum( -360 ); mAngleSpinBox->setMaximum( 360 ); - mAngleSpinBox->setSuffix( QString::fromUtf8( "°" ) ); + mAngleSpinBox->setSuffix( QStringLiteral( "°" ) ); mAngleSpinBox->setSingleStep( 1 ); mAngleSpinBox->setValue( 0 ); mAngleSpinBox->setShowClearButton( false ); @@ -66,7 +66,7 @@ QgsAngleMagnetWidget::QgsAngleMagnetWidget( const QString& label , QWidget *pare mMagnetSpinBox->setMinimum( 0 ); mMagnetSpinBox->setMaximum( 180 ); mMagnetSpinBox->setPrefix( tr( "Snap to " ) ); - mMagnetSpinBox->setSuffix( QString::fromUtf8( "°" ) ); + mMagnetSpinBox->setSuffix( QStringLiteral( "°" ) ); mMagnetSpinBox->setSingleStep( 15 ); mMagnetSpinBox->setValue( 0 ); mMagnetSpinBox->setClearValue( 0, tr( "No snapping" ) ); @@ -462,7 +462,7 @@ void QgsMapToolRotateFeature::createRotationWidget() deleteRotationWidget(); - mRotationWidget = new QgsAngleMagnetWidget( "Rotation:" ); + mRotationWidget = new QgsAngleMagnetWidget( QStringLiteral( "Rotation:" ) ); QgisApp::instance()->addUserInputWidget( mRotationWidget ); mRotationWidget->setFocus( Qt::TabFocusReason ); diff --git a/src/app/qgsmaptoolrotatelabel.cpp b/src/app/qgsmaptoolrotatelabel.cpp index a822876112f5..11baa91ac648 100644 --- a/src/app/qgsmaptoolrotatelabel.cpp +++ b/src/app/qgsmaptoolrotatelabel.cpp @@ -93,7 +93,7 @@ void QgsMapToolRotateLabel::canvasPressEvent( QgsMapMouseEvent* e ) mRotationItem = new QgsPointRotationItem( mCanvas ); mRotationItem->setOrientation( QgsPointRotationItem::Counterclockwise ); - mRotationItem->setSymbol( QgsApplication::getThemePixmap( "mActionRotatePointSymbols.svg" ).toImage() ); + mRotationItem->setSymbol( QgsApplication::getThemePixmap( QStringLiteral( "mActionRotatePointSymbols.svg" ) ).toImage() ); mRotationItem->setPointLocation( mRotationPoint ); mRotationItem->setSymbolRotation( mCurrentRotation ); } @@ -170,7 +170,7 @@ void QgsMapToolRotateLabel::canvasReleaseEvent( QgsMapMouseEvent* e ) return; } - vlayer->beginEditCommand( tr( "Rotated label" ) + QString( " '%1'" ).arg( currentLabelText( 24 ) ) ); + vlayer->beginEditCommand( tr( "Rotated label" ) + QStringLiteral( " '%1'" ).arg( currentLabelText( 24 ) ) ); vlayer->changeAttributeValue( mCurrentLabel.pos.featureId, rotationCol, rotation ); vlayer->endEditCommand(); vlayer->triggerRepaint(); diff --git a/src/app/qgsmaptoolshowhidelabels.cpp b/src/app/qgsmaptoolshowhidelabels.cpp index ae74ba777b4d..a2e59bc0a200 100644 --- a/src/app/qgsmaptoolshowhidelabels.cpp +++ b/src/app/qgsmaptoolshowhidelabels.cpp @@ -213,7 +213,7 @@ bool QgsMapToolShowHideLabels::selectedFeatures( QgsVectorLayer* vlayer, { Q_UNUSED( cse ); // catch exception for 'invalid' point and leave existing selection unchanged - QgsLogger::warning( "Caught CRS exception " + QString( __FILE__ ) + ": " + QString::number( __LINE__ ) ); + QgsLogger::warning( "Caught CRS exception " + QStringLiteral( __FILE__ ) + ": " + QString::number( __LINE__ ) ); emit messageEmitted( tr( "CRS Exception: selection extends beyond layer's coordinate system." ), QgsMessageBar::WARNING ); return false; } diff --git a/src/app/qgsmaptoolsimplify.cpp b/src/app/qgsmaptoolsimplify.cpp index 6c22f3bc37a1..693b3f5f6310 100644 --- a/src/app/qgsmaptoolsimplify.cpp +++ b/src/app/qgsmaptoolsimplify.cpp @@ -72,8 +72,8 @@ QgsMapToolSimplify::QgsMapToolSimplify( QgsMapCanvas* canvas ) , mReducedHasErrors( false ) { QSettings settings; - mTolerance = settings.value( "/digitizing/simplify_tolerance", 1 ).toDouble(); - mToleranceUnits = ( QgsTolerance::UnitType ) settings.value( "/digitizing/simplify_tolerance_units", 0 ).toInt(); + mTolerance = settings.value( QStringLiteral( "/digitizing/simplify_tolerance" ), 1 ).toDouble(); + mToleranceUnits = ( QgsTolerance::UnitType ) settings.value( QStringLiteral( "/digitizing/simplify_tolerance_units" ), 0 ).toInt(); mSimplifyDialog = new QgsSimplifyDialog( this, canvas->topLevelWidget() ); } @@ -90,7 +90,7 @@ void QgsMapToolSimplify::setTolerance( double tolerance ) mTolerance = tolerance; QSettings settings; - settings.setValue( "/digitizing/simplify_tolerance", tolerance ); + settings.setValue( QStringLiteral( "/digitizing/simplify_tolerance" ), tolerance ); if ( !mSelectedFeatures.isEmpty() ) updateSimplificationPreview(); @@ -101,7 +101,7 @@ void QgsMapToolSimplify::setToleranceUnits( int units ) mToleranceUnits = ( QgsTolerance::UnitType ) units; QSettings settings; - settings.setValue( "/digitizing/simplify_tolerance_units", units ); + settings.setValue( QStringLiteral( "/digitizing/simplify_tolerance_units" ), units ); if ( !mSelectedFeatures.isEmpty() ) updateSimplificationPreview(); diff --git a/src/app/qgsmeasuredialog.cpp b/src/app/qgsmeasuredialog.cpp index 25d6e799a4ed..361af14f3d76 100644 --- a/src/app/qgsmeasuredialog.cpp +++ b/src/app/qgsmeasuredialog.cpp @@ -66,14 +66,14 @@ QgsMeasureDialog::QgsMeasureDialog( QgsMeasureTool* tool, Qt::WindowFlags f ) void QgsMeasureDialog::openConfigTab() { - QgisApp::instance()->showOptionsDialog( this, "mOptionsPageMapTools" ); + QgisApp::instance()->showOptionsDialog( this, QStringLiteral( "mOptionsPageMapTools" ) ); } void QgsMeasureDialog::updateSettings() { QSettings settings; - mDecimalPlaces = settings.value( "/qgis/measure/decimalplaces", "3" ).toInt(); + mDecimalPlaces = settings.value( QStringLiteral( "/qgis/measure/decimalplaces" ), "3" ).toInt(); mCanvasUnits = mTool->canvas()->mapUnits(); // Configure QgsDistanceArea mDistanceUnits = QgsProject::instance()->distanceUnits(); @@ -243,12 +243,12 @@ void QgsMeasureDialog::closeEvent( QCloseEvent *e ) void QgsMeasureDialog::restorePosition() { QSettings settings; - restoreGeometry( settings.value( "/Windows/Measure/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/Measure/geometry" ) ).toByteArray() ); int wh; if ( mMeasureArea ) - wh = settings.value( "/Windows/Measure/hNoTable", 70 ).toInt(); + wh = settings.value( QStringLiteral( "/Windows/Measure/hNoTable" ), 70 ).toInt(); else - wh = settings.value( "/Windows/Measure/h", 200 ).toInt(); + wh = settings.value( QStringLiteral( "/Windows/Measure/h" ), 200 ).toInt(); resize( width(), wh ); updateUi(); } @@ -256,7 +256,7 @@ void QgsMeasureDialog::restorePosition() void QgsMeasureDialog::saveWindowLocation() { QSettings settings; - settings.setValue( "/Windows/Measure/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/Measure/geometry" ), saveGeometry() ); const QString &key = mMeasureArea ? "/Windows/Measure/hNoTable" : "/Windows/Measure/h"; settings.setValue( key, height() ); } @@ -264,7 +264,7 @@ void QgsMeasureDialog::saveWindowLocation() QString QgsMeasureDialog::formatDistance( double distance, bool convertUnits ) const { QSettings settings; - bool baseUnit = settings.value( "/qgis/measure/keepbaseunit", true ).toBool(); + bool baseUnit = settings.value( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ).toBool(); if ( convertUnits ) distance = convertLength( distance, mDistanceUnits ); @@ -332,13 +332,13 @@ void QgsMeasureDialog::updateUi() if ( QgsUnitTypes::unitType( resultUnit ) == QgsUnitTypes::Geographic && QgsUnitTypes::unitType( mAreaUnits ) == QgsUnitTypes::Standard ) { - toolTip += "
                                                                                                                                                                                    * Area is roughly converted to square meters by using scale at equator (1 degree = 111319.49 meters)."; + toolTip += QLatin1String( "
                                                                                                                                                                                    * Area is roughly converted to square meters by using scale at equator (1 degree = 111319.49 meters)." ); resultUnit = QgsUnitTypes::AreaSquareMeters; } else if ( QgsUnitTypes::unitType( resultUnit ) == QgsUnitTypes::Standard && QgsUnitTypes::unitType( mAreaUnits ) == QgsUnitTypes::Geographic ) { - toolTip += "
                                                                                                                                                                                    * Area is roughly converted to square degrees by using scale at equator (1 degree = 111319.49 meters)."; + toolTip += QLatin1String( "
                                                                                                                                                                                    * Area is roughly converted to square degrees by using scale at equator (1 degree = 111319.49 meters)." ); resultUnit = QgsUnitTypes::AreaSquareDegrees; } @@ -406,13 +406,13 @@ void QgsMeasureDialog::updateUi() if ( QgsUnitTypes::unitType( resultUnit ) == QgsUnitTypes::Geographic && QgsUnitTypes::unitType( mDistanceUnits ) == QgsUnitTypes::Standard ) { - toolTip += "
                                                                                                                                                                                    * Distance is roughly converted to meters by using scale at equator (1 degree = 111319.49 meters)."; + toolTip += QLatin1String( "
                                                                                                                                                                                    * Distance is roughly converted to meters by using scale at equator (1 degree = 111319.49 meters)." ); resultUnit = QgsUnitTypes::DistanceMeters; } else if ( QgsUnitTypes::unitType( resultUnit ) == QgsUnitTypes::Standard && QgsUnitTypes::unitType( mDistanceUnits ) == QgsUnitTypes::Geographic ) { - toolTip += "
                                                                                                                                                                                    * Distance is roughly converted to degrees by using scale at equator (1 degree = 111319.49 meters)."; + toolTip += QLatin1String( "
                                                                                                                                                                                    * Distance is roughly converted to degrees by using scale at equator (1 degree = 111319.49 meters)." ); resultUnit = QgsUnitTypes::DistanceDegrees; } diff --git a/src/app/qgsmeasuretool.cpp b/src/app/qgsmeasuretool.cpp index 1b2e7d17a195..62e25b981d49 100644 --- a/src/app/qgsmeasuretool.cpp +++ b/src/app/qgsmeasuretool.cpp @@ -119,9 +119,9 @@ void QgsMeasureTool::updateSettings() { QSettings settings; - int myRed = settings.value( "/qgis/default_measure_color_red", 222 ).toInt(); - int myGreen = settings.value( "/qgis/default_measure_color_green", 155 ).toInt(); - int myBlue = settings.value( "/qgis/default_measure_color_blue", 67 ).toInt(); + int myRed = settings.value( QStringLiteral( "/qgis/default_measure_color_red" ), 222 ).toInt(); + int myGreen = settings.value( QStringLiteral( "/qgis/default_measure_color_green" ), 155 ).toInt(); + int myBlue = settings.value( QStringLiteral( "/qgis/default_measure_color_blue" ), 67 ).toInt(); mRubberBand->setColor( QColor( myRed, myGreen, myBlue, 100 ) ); mRubberBand->setWidth( 3 ); mRubberBandPoints->setIcon( QgsRubberBand::ICON_CIRCLE ); @@ -150,7 +150,7 @@ void QgsMeasureTool::updateSettings() } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught at the MeasureTool: %1" ).arg( cse.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught at the MeasureTool: %1" ).arg( cse.what() ) ); } } diff --git a/src/app/qgsmergeattributesdialog.cpp b/src/app/qgsmergeattributesdialog.cpp index 4731eac47a8e..de37fa0cb86e 100644 --- a/src/app/qgsmergeattributesdialog.cpp +++ b/src/app/qgsmergeattributesdialog.cpp @@ -68,11 +68,11 @@ QgsMergeAttributesDialog::QgsMergeAttributesDialog( const QgsFeatureList &featur mTableWidget->setSelectionBehavior( QAbstractItemView::SelectRows ); mTableWidget->setSelectionMode( QAbstractItemView::SingleSelection ); - mFromSelectedPushButton->setIcon( QgsApplication::getThemeIcon( "mActionFromSelectedFeature.png" ) ); - mRemoveFeatureFromSelectionButton->setIcon( QgsApplication::getThemeIcon( "mActionRemoveSelectedFeature.png" ) ); + mFromSelectedPushButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionFromSelectedFeature.png" ) ) ); + mRemoveFeatureFromSelectionButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionRemoveSelectedFeature.png" ) ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/MergeAttributes/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/MergeAttributes/geometry" ) ).toByteArray() ); connect( mSkipAllButton, SIGNAL( clicked() ), this, SLOT( setAllToSkip() ) ); connect( mTableWidget, SIGNAL( cellChanged( int, int ) ), this, SLOT( tableWidgetCellChanged( int, int ) ) ); @@ -87,13 +87,13 @@ QgsMergeAttributesDialog::QgsMergeAttributesDialog() setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/MergeAttributes/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/MergeAttributes/geometry" ) ).toByteArray() ); } QgsMergeAttributesDialog::~QgsMergeAttributesDialog() { QSettings settings; - settings.setValue( "/Windows/MergeAttributes/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/MergeAttributes/geometry" ), saveGeometry() ); delete mSelectionRubberBand; } @@ -118,7 +118,7 @@ void QgsMergeAttributesDialog::createTableWidgetContents() for ( int idx = 0; idx < mFields.count(); ++idx ) { const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( mVectorLayer, mFields.at( idx ).name() ); - if ( setup.type() == "Hidden" || setup.type() == "Immutable" ) + if ( setup.type() == QLatin1String( "Hidden" ) || setup.type() == QLatin1String( "Immutable" ) ) { mHiddenAttributes.insert( idx ); continue; @@ -184,7 +184,7 @@ QComboBox *QgsMergeAttributesDialog::createMergeComboBox( QVariant::Type columnT QgsFeatureList::const_iterator f_it = mFeatureList.constBegin(); for ( ; f_it != mFeatureList.constEnd(); ++f_it ) { - newComboBox->addItem( tr( "Feature %1" ).arg( f_it->id() ), QString( "f%1" ).arg( FID_TO_STRING( f_it->id() ) ) ); + newComboBox->addItem( tr( "Feature %1" ).arg( f_it->id() ), QStringLiteral( "f%1" ).arg( FID_TO_STRING( f_it->id() ) ) ); } switch ( columnType ) @@ -291,15 +291,15 @@ void QgsMergeAttributesDialog::refreshMergedValue( int col ) //evaluate behaviour (feature value or min / max / mean ) QString mergeBehaviourString = comboBox->currentData().toString(); QVariant mergeResult; // result to show in the merge result field - if ( mergeBehaviourString == "concat" ) + if ( mergeBehaviourString == QLatin1String( "concat" ) ) { mergeResult = concatenationAttribute( col ); } - else if ( mergeBehaviourString == "skip" ) + else if ( mergeBehaviourString == QLatin1String( "skip" ) ) { mergeResult = tr( "Skipped" ); } - else if ( mergeBehaviourString == "manual" ) + else if ( mergeBehaviourString == QLatin1String( "manual" ) ) { return; //nothing to do } @@ -379,7 +379,7 @@ QVariant QgsMergeAttributesDialog::concatenationAttribute( int col ) { concatString << mTableWidget->item( i + 1, col )->text(); } - return concatString.join( "," ); //todo: make separator user configurable + return concatString.join( QStringLiteral( "," ) ); //todo: make separator user configurable } void QgsMergeAttributesDialog::on_mFromSelectedPushButton_clicked() @@ -423,7 +423,7 @@ void QgsMergeAttributesDialog::on_mFromSelectedPushButton_clicked() QComboBox* currentComboBox = qobject_cast( mTableWidget->cellWidget( 0, i ) ); if ( currentComboBox ) { - currentComboBox->setCurrentIndex( currentComboBox->findData( QString( "f%1" ).arg( FID_TO_STRING( featureId ) ) ) ); + currentComboBox->setCurrentIndex( currentComboBox->findData( QStringLiteral( "f%1" ).arg( FID_TO_STRING( featureId ) ) ) ); } } } @@ -476,7 +476,7 @@ void QgsMergeAttributesDialog::on_mRemoveFeatureFromSelectionButton_clicked() continue; currentComboBox->blockSignals( true ); - currentComboBox->removeItem( currentComboBox->findData( QString( "f%1" ).arg( FID_TO_STRING( featureId ) ) ) ); + currentComboBox->removeItem( currentComboBox->findData( QStringLiteral( "f%1" ).arg( FID_TO_STRING( featureId ) ) ) ); currentComboBox->blockSignals( false ); } @@ -557,7 +557,7 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const if ( fieldIdx >= results.count() ) results.resize( fieldIdx + 1 ); // make sure the results vector is long enough (maybe not necessary) - if ( comboBox->currentData().toString() != "skip" ) + if ( comboBox->currentData().toString() != QLatin1String( "skip" ) ) { results[fieldIdx] = currentItem->data( Qt::DisplayRole ); } @@ -595,7 +595,7 @@ QSet QgsMergeAttributesDialog::skippedAttributeIndexes() const continue; } - if ( comboBox->currentData().toString() == "skip" ) + if ( comboBox->currentData().toString() == QLatin1String( "skip" ) ) { skipped << i; } diff --git a/src/app/qgsnewspatialitelayerdialog.cpp b/src/app/qgsnewspatialitelayerdialog.cpp index 889e99610699..e3f57fcedf06 100644 --- a/src/app/qgsnewspatialitelayerdialog.cpp +++ b/src/app/qgsnewspatialitelayerdialog.cpp @@ -47,17 +47,17 @@ QgsNewSpatialiteLayerDialog::QgsNewSpatialiteLayerDialog( QWidget *parent, Qt::W setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/NewSpatiaLiteLayer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/NewSpatiaLiteLayer/geometry" ) ).toByteArray() ); - mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.svg" ) ); - mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.svg" ) ); + mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); + mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); mTypeBox->addItem( tr( "Text data" ), "text" ); mTypeBox->addItem( tr( "Whole number" ), "integer" ); mTypeBox->addItem( tr( "Decimal number" ), "real" ); mPointRadioButton->setChecked( true ); // Populate the database list from the stored connections - settings.beginGroup( "/SpatiaLite/connections" ); + settings.beginGroup( QStringLiteral( "/SpatiaLite/connections" ) ); QStringList keys = settings.childGroups(); QStringList::Iterator it = keys.begin(); mDatabaseComboBox->clear(); @@ -74,7 +74,7 @@ QgsNewSpatialiteLayerDialog::QgsNewSpatialiteLayerDialog( QWidget *parent, Qt::W mOkButton->setEnabled( false ); // Set the SRID box to a default of WGS84 - QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString() ); + QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( QStringLiteral( "/Projections/layerDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString() ); srs.validate(); mCrsId = srs.authid(); leSRID->setText( srs.authid() + " - " + srs.description() ); @@ -94,7 +94,7 @@ QgsNewSpatialiteLayerDialog::QgsNewSpatialiteLayerDialog( QWidget *parent, Qt::W QgsNewSpatialiteLayerDialog::~QgsNewSpatialiteLayerDialog() { QSettings settings; - settings.setValue( "/Windows/NewSpatiaLiteLayer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/NewSpatiaLiteLayer/geometry" ), saveGeometry() ); } void QgsNewSpatialiteLayerDialog::on_mTypeBox_currentIndexChanged( int index ) @@ -119,9 +119,9 @@ void QgsNewSpatialiteLayerDialog::on_toolButtonNewDatabase_clicked() if ( fileName.isEmpty() ) return; - if ( !fileName.endsWith( ".sqlite", Qt::CaseInsensitive ) && !fileName.endsWith( ".db", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".sqlite" ), Qt::CaseInsensitive ) && !fileName.endsWith( QLatin1String( ".db" ), Qt::CaseInsensitive ) ) { - fileName += ".sqlite"; + fileName += QLatin1String( ".sqlite" ); } mDatabaseComboBox->insertItem( 0, fileName ); @@ -133,31 +133,31 @@ QString QgsNewSpatialiteLayerDialog::selectedType() const { if ( mPointRadioButton->isChecked() ) { - return "POINT"; + return QStringLiteral( "POINT" ); } else if ( mLineRadioButton->isChecked() ) { - return "LINESTRING"; + return QStringLiteral( "LINESTRING" ); } else if ( mPolygonRadioButton->isChecked() ) { - return "POLYGON"; + return QStringLiteral( "POLYGON" ); } else if ( mMultipointRadioButton->isChecked() ) { - return "MULTIPOINT"; + return QStringLiteral( "MULTIPOINT" ); } else if ( mMultilineRadioButton->isChecked() ) { - return "MULTILINESTRING"; + return QStringLiteral( "MULTILINESTRING" ); } else if ( mMultipolygonRadioButton->isChecked() ) { - return "MULTIPOLYGON"; + return QStringLiteral( "MULTIPOLYGON" ); } Q_ASSERT( !"no type selected" ); - return ""; + return QLatin1String( "" ); } void QgsNewSpatialiteLayerDialog::checkOk() @@ -206,7 +206,7 @@ void QgsNewSpatialiteLayerDialog::on_pbnFindSRID_clicked() // load up the srid table const char *pzTail; sqlite3_stmt *ppStmt; - QString sql = "select auth_name || ':' || auth_srid from spatial_ref_sys order by srid asc"; + QString sql = QStringLiteral( "select auth_name || ':' || auth_srid from spatial_ref_sys order by srid asc" ); QSet myCRSs; @@ -276,7 +276,7 @@ bool QgsNewSpatialiteLayerDialog::createDb() QString errCause; bool res = false; - QString spatialite_lib = QgsProviderRegistry::instance()->library( "spatialite" ); + QString spatialite_lib = QgsProviderRegistry::instance()->library( QStringLiteral( "spatialite" ) ); QLibrary* myLib = new QLibrary( spatialite_lib ); bool loaded = myLib->load(); if ( loaded ) @@ -291,7 +291,7 @@ bool QgsNewSpatialiteLayerDialog::createDb() } else { - errCause = "Resolving createDb(...) failed"; + errCause = QStringLiteral( "Resolving createDb(...) failed" ); } } delete myLib; @@ -315,7 +315,7 @@ bool QgsNewSpatialiteLayerDialog::createDb() QSettings settings; if ( !settings.contains( key ) ) { - settings.setValue( "/SpatiaLite/connections/selected", fi.fileName() + tr( "@" ) + fi.canonicalFilePath() ); + settings.setValue( QStringLiteral( "/SpatiaLite/connections/selected" ), fi.fileName() + tr( "@" ) + fi.canonicalFilePath() ); settings.setValue( key, fi.canonicalFilePath() ); QMessageBox::information( nullptr, tr( "SpatiaLite Database" ), tr( "Registered new database!" ) ); @@ -340,20 +340,20 @@ void QgsNewSpatialiteLayerDialog::on_buttonBox_rejected() bool QgsNewSpatialiteLayerDialog::apply() { // Build up the sql statement for creating the table - QString sql = QString( "create table %1(" ).arg( quotedIdentifier( leLayerName->text() ) ); - QString delim = ""; + QString sql = QStringLiteral( "create table %1(" ).arg( quotedIdentifier( leLayerName->text() ) ); + QString delim = QLatin1String( "" ); if ( checkBoxPrimaryKey->isChecked() ) { - sql += "pkuid integer primary key autoincrement"; - delim = ","; + sql += QLatin1String( "pkuid integer primary key autoincrement" ); + delim = QStringLiteral( "," ); } QTreeWidgetItemIterator it( mAttributeView ); while ( *it ) { - sql += delim + QString( "%1 %2" ).arg( quotedIdentifier(( *it )->text( 0 ) ), ( *it )->text( 1 ) ); - delim = ","; + sql += delim + QStringLiteral( "%1 %2" ).arg( quotedIdentifier(( *it )->text( 0 ) ), ( *it )->text( 1 ) ); + delim = QStringLiteral( "," ); ++it; } @@ -364,14 +364,14 @@ bool QgsNewSpatialiteLayerDialog::apply() QgsDebugMsg( sql ); // OK - QString sqlAddGeom = QString( "select AddGeometryColumn(%1,%2,%3,%4,2)" ) + QString sqlAddGeom = QStringLiteral( "select AddGeometryColumn(%1,%2,%3,%4,2)" ) .arg( quotedValue( leLayerName->text() ), quotedValue( leGeometryColumn->text() ) ) - .arg( mCrsId.split( ':' ).value( 1, "0" ).toInt() ) + .arg( mCrsId.split( ':' ).value( 1, QStringLiteral( "0" ) ).toInt() ) .arg( quotedValue( selectedType() ) ); QgsDebugMsg( sqlAddGeom ); // OK - QString sqlCreateIndex = QString( "select CreateSpatialIndex(%1,%2)" ) + QString sqlCreateIndex = QStringLiteral( "select CreateSpatialIndex(%1,%2)" ) .arg( quotedValue( leLayerName->text() ), quotedValue( leGeometryColumn->text() ) ); QgsDebugMsg( sqlCreateIndex ); // OK @@ -418,10 +418,10 @@ bool QgsNewSpatialiteLayerDialog::apply() sqlite3_free( errmsg ); } - QgsVectorLayer *layer = new QgsVectorLayer( QString( "dbname='%1' table='%2'(%3) sql=" ) + QgsVectorLayer *layer = new QgsVectorLayer( QStringLiteral( "dbname='%1' table='%2'(%3) sql=" ) .arg( mDatabaseComboBox->currentText(), leLayerName->text(), - leGeometryColumn->text() ), leLayerName->text(), "spatialite" ); + leGeometryColumn->text() ), leLayerName->text(), QStringLiteral( "spatialite" ) ); if ( layer->isValid() ) { // register this layer with the central layers registry @@ -449,13 +449,13 @@ bool QgsNewSpatialiteLayerDialog::apply() QString QgsNewSpatialiteLayerDialog::quotedIdentifier( QString id ) { - id.replace( '\"', "\"\"" ); + id.replace( '\"', QLatin1String( "\"\"" ) ); return id.prepend( '\"' ).append( '\"' ); } QString QgsNewSpatialiteLayerDialog::quotedValue( QString value ) { - value.replace( '\'', "''" ); + value.replace( '\'', QLatin1String( "''" ) ); return value.prepend( '\'' ).append( '\'' ); } diff --git a/src/app/qgsoptions.cpp b/src/app/qgsoptions.cpp index f954d7efe234..b246a59ac4f2 100644 --- a/src/app/qgsoptions.cpp +++ b/src/app/qgsoptions.cpp @@ -73,7 +73,7 @@ * Constructor */ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) - : QgsOptionsDialogBase( "Options", parent, fl ) + : QgsOptionsDialogBase( QStringLiteral( "Options" ), parent, fl ) , mSettings( nullptr ) { setupUi( this ); @@ -107,28 +107,28 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mIdentifyHighlightColorButton->setColorDialogTitle( tr( "Identify highlight color" ) ); mIdentifyHighlightColorButton->setAllowAlpha( true ); - mIdentifyHighlightColorButton->setContext( "gui" ); + mIdentifyHighlightColorButton->setContext( QStringLiteral( "gui" ) ); mIdentifyHighlightColorButton->setDefaultColor( Qgis::DEFAULT_HIGHLIGHT_COLOR ); mSettings = new QSettings(); - double identifyValue = mSettings->value( "/Map/searchRadiusMM", Qgis::DEFAULT_SEARCH_RADIUS_MM ).toDouble(); + double identifyValue = mSettings->value( QStringLiteral( "/Map/searchRadiusMM" ), Qgis::DEFAULT_SEARCH_RADIUS_MM ).toDouble(); QgsDebugMsg( QString( "Standard Identify radius setting read from settings file: %1" ).arg( identifyValue ) ); if ( identifyValue <= 0.0 ) identifyValue = Qgis::DEFAULT_SEARCH_RADIUS_MM; spinBoxIdentifyValue->setMinimum( 0.0 ); spinBoxIdentifyValue->setValue( identifyValue ); - QColor highlightColor = QColor( mSettings->value( "/Map/highlight/color", Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); - int highlightAlpha = mSettings->value( "/Map/highlight/colorAlpha", Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); + QColor highlightColor = QColor( mSettings->value( QStringLiteral( "/Map/highlight/color" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); + int highlightAlpha = mSettings->value( QStringLiteral( "/Map/highlight/colorAlpha" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); highlightColor.setAlpha( highlightAlpha ); mIdentifyHighlightColorButton->setColor( highlightColor ); - double highlightBuffer = mSettings->value( "/Map/highlight/buffer", Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); + double highlightBuffer = mSettings->value( QStringLiteral( "/Map/highlight/buffer" ), Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); mIdentifyHighlightBufferSpinBox->setValue( highlightBuffer ); - double highlightMinWidth = mSettings->value( "/Map/highlight/minWidth", Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); + double highlightMinWidth = mSettings->value( QStringLiteral( "/Map/highlight/minWidth" ), Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); mIdentifyHighlightMinWidthSpinBox->setValue( highlightMinWidth ); // custom environment variables - bool useCustomVars = mSettings->value( "qgis/customEnvVarsUse", QVariant( false ) ).toBool(); + bool useCustomVars = mSettings->value( QStringLiteral( "qgis/customEnvVarsUse" ), QVariant( false ) ).toBool(); mCustomVariablesChkBx->setChecked( useCustomVars ); if ( !useCustomVars ) { @@ -136,7 +136,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mRemoveCustomVarBtn->setEnabled( false ); mCustomVariablesTable->setEnabled( false ); } - QStringList customVarsList = mSettings->value( "qgis/customEnvVars", "" ).toStringList(); + QStringList customVarsList = mSettings->value( QStringLiteral( "qgis/customEnvVars" ), "" ).toStringList(); Q_FOREACH ( const QString &varStr, customVarsList ) { int pos = varStr.indexOf( QLatin1Char( '|' ) ); @@ -219,7 +219,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mCurrentVariablesTable->resizeColumnToContents( 0 ); //local directories to search when loading c++ plugins - QString myPaths = mSettings->value( "plugins/searchPathsForPlugins", "" ).toString(); + QString myPaths = mSettings->value( QStringLiteral( "plugins/searchPathsForPlugins" ), "" ).toString(); if ( !myPaths.isEmpty() ) { QStringList myPathList = myPaths.split( '|' ); @@ -258,7 +258,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) } } - QStringList hiddenItems = mSettings->value( "/browser/hiddenPaths", + QStringList hiddenItems = mSettings->value( QStringLiteral( "/browser/hiddenPaths" ), QStringList() ).toStringList(); QStringList::const_iterator pathIt = hiddenItems.constBegin(); for ( ; pathIt != hiddenItems.constEnd(); ++pathIt ) @@ -269,36 +269,36 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) } //Network timeout - mNetworkTimeoutSpinBox->setValue( mSettings->value( "/qgis/networkAndProxy/networkTimeout", "60000" ).toInt() ); - leUserAgent->setText( mSettings->value( "/qgis/networkAndProxy/userAgent", "Mozilla/5.0" ).toString() ); + mNetworkTimeoutSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), "60000" ).toInt() ); + leUserAgent->setText( mSettings->value( QStringLiteral( "/qgis/networkAndProxy/userAgent" ), "Mozilla/5.0" ).toString() ); // WMS capabilities expiry time - mDefaultCapabilitiesExpirySpinBox->setValue( mSettings->value( "/qgis/defaultCapabilitiesExpiry", "24" ).toInt() ); + mDefaultCapabilitiesExpirySpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/defaultCapabilitiesExpiry" ), "24" ).toInt() ); // WMS/WMS-C tile expiry time - mDefaultTileExpirySpinBox->setValue( mSettings->value( "/qgis/defaultTileExpiry", "24" ).toInt() ); + mDefaultTileExpirySpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/defaultTileExpiry" ), "24" ).toInt() ); // WMS/WMS-C default max retry in case of tile request errors - mDefaultTileMaxRetrySpinBox->setValue( mSettings->value( "/qgis/defaultTileMaxRetry", "3" ).toInt() ); + mDefaultTileMaxRetrySpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/defaultTileMaxRetry" ), "3" ).toInt() ); //Web proxy settings - grpProxy->setChecked( mSettings->value( "proxy/proxyEnabled", "0" ).toBool() ); - leProxyHost->setText( mSettings->value( "proxy/proxyHost", "" ).toString() ); - leProxyPort->setText( mSettings->value( "proxy/proxyPort", "" ).toString() ); - leProxyUser->setText( mSettings->value( "proxy/proxyUser", "" ).toString() ); - leProxyPassword->setText( mSettings->value( "proxy/proxyPassword", "" ).toString() ); + grpProxy->setChecked( mSettings->value( QStringLiteral( "proxy/proxyEnabled" ), "0" ).toBool() ); + leProxyHost->setText( mSettings->value( QStringLiteral( "proxy/proxyHost" ), "" ).toString() ); + leProxyPort->setText( mSettings->value( QStringLiteral( "proxy/proxyPort" ), "" ).toString() ); + leProxyUser->setText( mSettings->value( QStringLiteral( "proxy/proxyUser" ), "" ).toString() ); + leProxyPassword->setText( mSettings->value( QStringLiteral( "proxy/proxyPassword" ), "" ).toString() ); //available proxy types - mProxyTypeComboBox->insertItem( 0, "DefaultProxy" ); - mProxyTypeComboBox->insertItem( 1, "Socks5Proxy" ); - mProxyTypeComboBox->insertItem( 2, "HttpProxy" ); - mProxyTypeComboBox->insertItem( 3, "HttpCachingProxy" ); - mProxyTypeComboBox->insertItem( 4, "FtpCachingProxy" ); - QString settingProxyType = mSettings->value( "proxy/proxyType", "DefaultProxy" ).toString(); + mProxyTypeComboBox->insertItem( 0, QStringLiteral( "DefaultProxy" ) ); + mProxyTypeComboBox->insertItem( 1, QStringLiteral( "Socks5Proxy" ) ); + mProxyTypeComboBox->insertItem( 2, QStringLiteral( "HttpProxy" ) ); + mProxyTypeComboBox->insertItem( 3, QStringLiteral( "HttpCachingProxy" ) ); + mProxyTypeComboBox->insertItem( 4, QStringLiteral( "FtpCachingProxy" ) ); + QString settingProxyType = mSettings->value( QStringLiteral( "proxy/proxyType" ), "DefaultProxy" ).toString(); mProxyTypeComboBox->setCurrentIndex( mProxyTypeComboBox->findText( settingProxyType ) ); //URLs excluded not going through proxies - QString proxyExcludedURLs = mSettings->value( "proxy/proxyExcludedUrls", "" ).toString(); + QString proxyExcludedURLs = mSettings->value( QStringLiteral( "proxy/proxyExcludedUrls" ), "" ).toString(); if ( !proxyExcludedURLs.isEmpty() ) { QStringList splitUrls = proxyExcludedURLs.split( '|' ); @@ -313,31 +313,31 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) } // cache settings - mCacheDirectory->setText( mSettings->value( "cache/directory" ).toString() ); + mCacheDirectory->setText( mSettings->value( QStringLiteral( "cache/directory" ) ).toString() ); mCacheDirectory->setPlaceholderText( QDir( QgsApplication::qgisSettingsDirPath() ).canonicalPath() + QDir::separator() + "cache" ); mCacheSize->setMinimum( 0 ); mCacheSize->setMaximum( std::numeric_limits::max() ); mCacheSize->setSingleStep( 1024 ); - qint64 cacheSize = mSettings->value( "cache/size", 50 * 1024 * 1024 ).toULongLong(); + qint64 cacheSize = mSettings->value( QStringLiteral( "cache/size" ), 50 * 1024 * 1024 ).toULongLong(); mCacheSize->setValue(( int )( cacheSize / 1024 ) ); //wms search server - leWmsSearch->setText( mSettings->value( "/qgis/WMSSearchUrl", "http://geopole.org/wms/search?search=%1&type=rss" ).toString() ); + leWmsSearch->setText( mSettings->value( QStringLiteral( "/qgis/WMSSearchUrl" ), "http://geopole.org/wms/search?search=%1&type=rss" ).toString() ); // set the attribute table default filter cmbAttrTableBehaviour->clear(); cmbAttrTableBehaviour->addItem( tr( "Show all features" ), QgsAttributeTableFilterModel::ShowAll ); cmbAttrTableBehaviour->addItem( tr( "Show selected features" ), QgsAttributeTableFilterModel::ShowSelected ); cmbAttrTableBehaviour->addItem( tr( "Show features visible on map" ), QgsAttributeTableFilterModel::ShowVisible ); - cmbAttrTableBehaviour->setCurrentIndex( cmbAttrTableBehaviour->findData( mSettings->value( "/qgis/attributeTableBehaviour", QgsAttributeTableFilterModel::ShowAll ).toInt() ) ); + cmbAttrTableBehaviour->setCurrentIndex( cmbAttrTableBehaviour->findData( mSettings->value( QStringLiteral( "/qgis/attributeTableBehaviour" ), QgsAttributeTableFilterModel::ShowAll ).toInt() ) ); mAttrTableViewComboBox->clear(); mAttrTableViewComboBox->addItem( tr( "Remember last view" ), -1 ); mAttrTableViewComboBox->addItem( tr( "Table view" ), QgsDualView::AttributeTable ); mAttrTableViewComboBox->addItem( tr( "Form view" ), QgsDualView::AttributeEditor ); - mAttrTableViewComboBox->setCurrentIndex( mAttrTableViewComboBox->findData( mSettings->value( "/qgis/attributeTableView", -1 ).toInt() ) ); + mAttrTableViewComboBox->setCurrentIndex( mAttrTableViewComboBox->findData( mSettings->value( QStringLiteral( "/qgis/attributeTableView" ), -1 ).toInt() ) ); - spinBoxAttrTableRowCache->setValue( mSettings->value( "/qgis/attributeTableRowCache", 10000 ).toInt() ); + spinBoxAttrTableRowCache->setValue( mSettings->value( QStringLiteral( "/qgis/attributeTableRowCache" ), 10000 ).toInt() ); spinBoxAttrTableRowCache->setSpecialValueText( tr( "All" ) ); // set the prompt for raster sublayers @@ -350,13 +350,13 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) cmbPromptRasterSublayers->addItem( tr( "If needed" ) ); //this means, prompt if there are sublayers but no band in the main dataset cmbPromptRasterSublayers->addItem( tr( "Never" ) ); cmbPromptRasterSublayers->addItem( tr( "Load all" ) ); - cmbPromptRasterSublayers->setCurrentIndex( mSettings->value( "/qgis/promptForRasterSublayers", 0 ).toInt() ); + cmbPromptRasterSublayers->setCurrentIndex( mSettings->value( QStringLiteral( "/qgis/promptForRasterSublayers" ), 0 ).toInt() ); // Scan for valid items in the browser dock cmbScanItemsInBrowser->clear(); cmbScanItemsInBrowser->addItem( tr( "Check file contents" ), "contents" ); // 0 cmbScanItemsInBrowser->addItem( tr( "Check extension" ), "extension" ); // 1 - int index = cmbScanItemsInBrowser->findData( mSettings->value( "/qgis/scanItemsInBrowser2", "" ) ); + int index = cmbScanItemsInBrowser->findData( mSettings->value( QStringLiteral( "/qgis/scanItemsInBrowser2" ), "" ) ); if ( index == -1 ) index = 1; cmbScanItemsInBrowser->setCurrentIndex( index ); @@ -366,19 +366,19 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) // cmbScanZipInBrowser->addItem( tr( "Passthru" ) ); // 1 - removed cmbScanZipInBrowser->addItem( tr( "Basic scan" ), QVariant( "basic" ) ); cmbScanZipInBrowser->addItem( tr( "Full scan" ), QVariant( "full" ) ); - index = cmbScanZipInBrowser->findData( mSettings->value( "/qgis/scanZipInBrowser2", "" ) ); + index = cmbScanZipInBrowser->findData( mSettings->value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "" ) ); if ( index == -1 ) index = 1; cmbScanZipInBrowser->setCurrentIndex( index ); // log rendering events, for userspace debugging - mLogCanvasRefreshChkBx->setChecked( mSettings->value( "/Map/logCanvasRefreshEvent", false ).toBool() ); + mLogCanvasRefreshChkBx->setChecked( mSettings->value( QStringLiteral( "/Map/logCanvasRefreshEvent" ), false ).toBool() ); //set the default projection behaviour radio buttongs - if ( mSettings->value( "/Projections/defaultBehaviour", "prompt" ).toString() == "prompt" ) + if ( mSettings->value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString() == QLatin1String( "prompt" ) ) { radPromptForProjection->setChecked( true ); } - else if ( mSettings->value( "/Projections/defaultBehaviour", "prompt" ).toString() == "useProject" ) + else if ( mSettings->value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString() == QLatin1String( "useProject" ) ) { radUseProjectProjection->setChecked( true ); } @@ -386,17 +386,17 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) { radUseGlobalProjection->setChecked( true ); } - QString myLayerDefaultCrs = mSettings->value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString(); + QString myLayerDefaultCrs = mSettings->value( QStringLiteral( "/Projections/layerDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString(); mLayerDefaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( myLayerDefaultCrs ); leLayerGlobalCrs->setCrs( mLayerDefaultCrs ); //on the fly CRS transformation settings //it would be logical to have single settings value but originaly the radio buttons were checkboxes - if ( mSettings->value( "/Projections/otfTransformAutoEnable", true ).toBool() ) + if ( mSettings->value( QStringLiteral( "/Projections/otfTransformAutoEnable" ), true ).toBool() ) { radOtfAuto->setChecked( true ); } - else if ( mSettings->value( "/Projections/otfTransformEnabled", false ).toBool() ) + else if ( mSettings->value( QStringLiteral( "/Projections/otfTransformEnabled" ), false ).toBool() ) { radOtfTransform->setChecked( true ); } @@ -405,15 +405,15 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) radOtfNone->setChecked( true ); // default } - QString myDefaultCrs = mSettings->value( "/Projections/projectDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString(); + QString myDefaultCrs = mSettings->value( QStringLiteral( "/Projections/projectDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString(); mDefaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( myDefaultCrs ); leProjectGlobalCrs->setCrs( mDefaultCrs ); leProjectGlobalCrs->setOptionVisible( QgsProjectionSelectionWidget::DefaultCrs, false ); //default datum transformations - mSettings->beginGroup( "/Projections" ); + mSettings->beginGroup( QStringLiteral( "/Projections" ) ); - chkShowDatumTransformDialog->setChecked( mSettings->value( "showDatumTransformDialog", false ).toBool() ); + chkShowDatumTransformDialog->setChecked( mSettings->value( QStringLiteral( "showDatumTransformDialog" ), false ).toBool() ); QStringList projectionKeys = mSettings->allKeys(); @@ -422,7 +422,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) QStringList::const_iterator pkeyIt = projectionKeys.constBegin(); for ( ; pkeyIt != projectionKeys.constEnd(); ++pkeyIt ) { - if ( pkeyIt->contains( "srcTransform" ) || pkeyIt->contains( "destTransform" ) ) + if ( pkeyIt->contains( QLatin1String( "srcTransform" ) ) || pkeyIt->contains( QLatin1String( "destTransform" ) ) ) { QStringList split = pkeyIt->split( '/' ); QString srcAuthId, destAuthId; @@ -435,11 +435,11 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) destAuthId = split.at( 1 ).split( '_' ).at( 0 ); } - if ( pkeyIt->contains( "srcTransform" ) ) + if ( pkeyIt->contains( QLatin1String( "srcTransform" ) ) ) { transforms[ qMakePair( srcAuthId, destAuthId )].first = mSettings->value( *pkeyIt ).toInt(); } - else if ( pkeyIt->contains( "destTransform" ) ) + else if ( pkeyIt->contains( QLatin1String( "destTransform" ) ) ) { transforms[ qMakePair( srcAuthId, destAuthId )].second = mSettings->value( *pkeyIt ).toInt(); } @@ -470,7 +470,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mDistanceUnitsComboBox->addItem( tr( "Map units" ), QgsUnitTypes::DistanceUnknownUnit ); bool ok = false; - QgsUnitTypes::DistanceUnit distanceUnits = QgsUnitTypes::decodeDistanceUnit( mSettings->value( "/qgis/measure/displayunits" ).toString(), &ok ); + QgsUnitTypes::DistanceUnit distanceUnits = QgsUnitTypes::decodeDistanceUnit( mSettings->value( QStringLiteral( "/qgis/measure/displayunits" ) ).toString(), &ok ); if ( !ok ) distanceUnits = QgsUnitTypes::DistanceMeters; mDistanceUnitsComboBox->setCurrentIndex( mDistanceUnitsComboBox->findData( distanceUnits ) ); @@ -486,7 +486,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mAreaUnitsComboBox->addItem( tr( "Square degrees" ), QgsUnitTypes::AreaSquareDegrees ); mAreaUnitsComboBox->addItem( tr( "Map units" ), QgsUnitTypes::AreaUnknownUnit ); - QgsUnitTypes::AreaUnit areaUnits = QgsUnitTypes::decodeAreaUnit( mSettings->value( "/qgis/measure/areaunits" ).toString(), &ok ); + QgsUnitTypes::AreaUnit areaUnits = QgsUnitTypes::decodeAreaUnit( mSettings->value( QStringLiteral( "/qgis/measure/areaunits" ) ).toString(), &ok ); if ( !ok ) areaUnits = QgsUnitTypes::AreaSquareMeters; mAreaUnitsComboBox->setCurrentIndex( mAreaUnitsComboBox->findData( areaUnits ) ); @@ -498,16 +498,16 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mAngleUnitsComboBox->addItem( tr( "Seconds of arc" ), QgsUnitTypes::AngleSecondsOfArc ); mAngleUnitsComboBox->addItem( tr( "Turns/revolutions" ), QgsUnitTypes::AngleTurn ); - QgsUnitTypes::AngleUnit unit = QgsUnitTypes::decodeAngleUnit( mSettings->value( "/qgis/measure/angleunits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AngleDegrees ) ).toString() ); + QgsUnitTypes::AngleUnit unit = QgsUnitTypes::decodeAngleUnit( mSettings->value( QStringLiteral( "/qgis/measure/angleunits" ), QgsUnitTypes::encodeUnit( QgsUnitTypes::AngleDegrees ) ).toString() ); mAngleUnitsComboBox->setCurrentIndex( mAngleUnitsComboBox->findData( unit ) ); // set decimal places of the measure tool - int decimalPlaces = mSettings->value( "/qgis/measure/decimalplaces", "3" ).toInt(); + int decimalPlaces = mSettings->value( QStringLiteral( "/qgis/measure/decimalplaces" ), "3" ).toInt(); mDecimalPlacesSpinBox->setRange( 0, 12 ); mDecimalPlacesSpinBox->setValue( decimalPlaces ); // set if base unit of measure tool should be changed - bool baseUnit = mSettings->value( "qgis/measure/keepbaseunit", true ).toBool(); + bool baseUnit = mSettings->value( QStringLiteral( "qgis/measure/keepbaseunit" ), true ).toBool(); if ( baseUnit ) { mKeepBaseUnitCheckBox->setChecked( true ); @@ -517,7 +517,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mKeepBaseUnitCheckBox->setChecked( false ); } - cmbIconSize->setCurrentIndex( cmbIconSize->findText( mSettings->value( "/IconSize", QGIS_ICON_SIZE ).toString() ) ); + cmbIconSize->setCurrentIndex( cmbIconSize->findText( mSettings->value( QStringLiteral( "/IconSize" ), QGIS_ICON_SIZE ).toString() ) ); // set font size and family spinFontSize->blockSignals( true ); @@ -525,8 +525,8 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mFontFamilyRadioCustom->blockSignals( true ); mFontFamilyComboBox->blockSignals( true ); - spinFontSize->setValue( mStyleSheetOldOpts.value( "fontPointSize" ).toInt() ); - QString fontFamily = mStyleSheetOldOpts.value( "fontFamily" ).toString(); + spinFontSize->setValue( mStyleSheetOldOpts.value( QStringLiteral( "fontPointSize" ) ).toInt() ); + QString fontFamily = mStyleSheetOldOpts.value( QStringLiteral( "fontFamily" ) ).toString(); bool isQtDefault = ( fontFamily == mStyleSheetBuilder->defaultFont().family() ); mFontFamilyRadioQt->setChecked( isQtDefault ); mFontFamilyRadioCustom->setChecked( !isQtDefault ); @@ -548,46 +548,46 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mFontFamilyComboBox->blockSignals( false ); // custom group boxes - mCustomGroupBoxChkBx->setChecked( mStyleSheetOldOpts.value( "groupBoxCustom" ).toBool() ); + mCustomGroupBoxChkBx->setChecked( mStyleSheetOldOpts.value( QStringLiteral( "groupBoxCustom" ) ).toBool() ); - mMessageTimeoutSpnBx->setValue( mSettings->value( "/qgis/messageTimeout", 5 ).toInt() ); + mMessageTimeoutSpnBx->setValue( mSettings->value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt() ); - QString name = mSettings->value( "/qgis/style" ).toString(); + QString name = mSettings->value( QStringLiteral( "/qgis/style" ) ).toString(); cmbStyle->setCurrentIndex( cmbStyle->findText( name, Qt::MatchFixedString ) ); QString theme = QgsApplication::themeName(); cmbUITheme->setCurrentIndex( cmbUITheme->findText( theme, Qt::MatchFixedString ) ); - mNativeColorDialogsChkBx->setChecked( mSettings->value( "/qgis/native_color_dialogs", false ).toBool() ); - mLiveColorDialogsChkBx->setChecked( mSettings->value( "/qgis/live_color_dialogs", false ).toBool() ); + mNativeColorDialogsChkBx->setChecked( mSettings->value( QStringLiteral( "/qgis/native_color_dialogs" ), false ).toBool() ); + mLiveColorDialogsChkBx->setChecked( mSettings->value( QStringLiteral( "/qgis/live_color_dialogs" ), false ).toBool() ); //set the state of the checkboxes //Changed to default to true as of QGIS 1.7 - chkAntiAliasing->setChecked( mSettings->value( "/qgis/enable_anti_aliasing", true ).toBool() ); - chkUseRenderCaching->setChecked( mSettings->value( "/qgis/enable_render_caching", true ).toBool() ); - chkParallelRendering->setChecked( mSettings->value( "/qgis/parallel_rendering", true ).toBool() ); - spinMapUpdateInterval->setValue( mSettings->value( "/qgis/map_update_interval", 250 ).toInt() ); + chkAntiAliasing->setChecked( mSettings->value( QStringLiteral( "/qgis/enable_anti_aliasing" ), true ).toBool() ); + chkUseRenderCaching->setChecked( mSettings->value( QStringLiteral( "/qgis/enable_render_caching" ), true ).toBool() ); + chkParallelRendering->setChecked( mSettings->value( QStringLiteral( "/qgis/parallel_rendering" ), true ).toBool() ); + spinMapUpdateInterval->setValue( mSettings->value( QStringLiteral( "/qgis/map_update_interval" ), 250 ).toInt() ); chkMaxThreads->setChecked( QgsApplication::maxThreads() != -1 ); spinMaxThreads->setEnabled( chkMaxThreads->isChecked() ); spinMaxThreads->setRange( 1, QThread::idealThreadCount() ); spinMaxThreads->setValue( QgsApplication::maxThreads() ); // Default simplify drawing configuration - mSimplifyDrawingGroupBox->setChecked( mSettings->value( "/qgis/simplifyDrawingHints", ( int )QgsVectorSimplifyMethod::GeometrySimplification ).toInt() != QgsVectorSimplifyMethod::NoSimplification ); - mSimplifyDrawingSpinBox->setValue( mSettings->value( "/qgis/simplifyDrawingTol", Qgis::DEFAULT_MAPTOPIXEL_THRESHOLD ).toFloat() ); - mSimplifyDrawingAtProvider->setChecked( !mSettings->value( "/qgis/simplifyLocal", true ).toBool() ); + mSimplifyDrawingGroupBox->setChecked( mSettings->value( QStringLiteral( "/qgis/simplifyDrawingHints" ), ( int )QgsVectorSimplifyMethod::GeometrySimplification ).toInt() != QgsVectorSimplifyMethod::NoSimplification ); + mSimplifyDrawingSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/simplifyDrawingTol" ), Qgis::DEFAULT_MAPTOPIXEL_THRESHOLD ).toFloat() ); + mSimplifyDrawingAtProvider->setChecked( !mSettings->value( QStringLiteral( "/qgis/simplifyLocal" ), true ).toBool() ); //segmentation tolerance type mToleranceTypeComboBox->addItem( tr( "Maximum angle" ), 0 ); mToleranceTypeComboBox->addItem( tr( "Maximum difference" ), 1 ); - int toleranceType = mSettings->value( "/qgis/segmentationToleranceType", "0" ).toInt(); + int toleranceType = mSettings->value( QStringLiteral( "/qgis/segmentationToleranceType" ), "0" ).toInt(); int toleranceTypeIndex = mToleranceTypeComboBox->findData( toleranceType ); if ( toleranceTypeIndex != -1 ) { mToleranceTypeComboBox->setCurrentIndex( toleranceTypeIndex ); } - double tolerance = mSettings->value( "/qgis/segmentationTolerance", "0.01745" ).toDouble(); + double tolerance = mSettings->value( QStringLiteral( "/qgis/segmentationTolerance" ), "0.01745" ).toDouble(); if ( toleranceType == 0 ) { tolerance = tolerance * 180.0 / M_PI; //value shown to the user is degree, not rad @@ -595,126 +595,126 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mSegmentationToleranceSpinBox->setValue( tolerance ); QStringList myScalesList = PROJECT_SCALES.split( ',' ); - myScalesList.append( "1:1" ); + myScalesList.append( QStringLiteral( "1:1" ) ); mSimplifyMaximumScaleComboBox->updateScales( myScalesList ); - mSimplifyMaximumScaleComboBox->setScale( 1.0 / mSettings->value( "/qgis/simplifyMaxScale", 1 ).toFloat() ); + mSimplifyMaximumScaleComboBox->setScale( 1.0 / mSettings->value( QStringLiteral( "/qgis/simplifyMaxScale" ), 1 ).toFloat() ); // Magnifier - double magnifierMin = 100 * mSettings->value( "/qgis/magnifier_factor_min", 0.1 ).toDouble(); - double magnifierMax = 100 * mSettings->value( "/qgis/magnifier_factor_max", 10 ).toDouble(); - double magnifierVal = 100 * mSettings->value( "/qgis/magnifier_factor_default", 1.0 ).toDouble(); + double magnifierMin = 100 * mSettings->value( QStringLiteral( "/qgis/magnifier_factor_min" ), 0.1 ).toDouble(); + double magnifierMax = 100 * mSettings->value( QStringLiteral( "/qgis/magnifier_factor_max" ), 10 ).toDouble(); + double magnifierVal = 100 * mSettings->value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble(); doubleSpinBoxMagnifierDefault->setRange( magnifierMin, magnifierMax ); doubleSpinBoxMagnifierDefault->setSingleStep( 50 ); doubleSpinBoxMagnifierDefault->setDecimals( 0 ); - doubleSpinBoxMagnifierDefault->setSuffix( "%" ); + doubleSpinBoxMagnifierDefault->setSuffix( QStringLiteral( "%" ) ); doubleSpinBoxMagnifierDefault->setValue( magnifierVal ); // Default local simplification algorithm mSimplifyAlgorithmComboBox->addItem( tr( "Distance" ), ( int )QgsVectorSimplifyMethod::Distance ); mSimplifyAlgorithmComboBox->addItem( tr( "SnapToGrid" ), ( int )QgsVectorSimplifyMethod::SnapToGrid ); mSimplifyAlgorithmComboBox->addItem( tr( "Visvalingam" ), ( int )QgsVectorSimplifyMethod::Visvalingam ); - mSimplifyAlgorithmComboBox->setCurrentIndex( mSimplifyAlgorithmComboBox->findData( mSettings->value( "/qgis/simplifyAlgorithm", 0 ).toInt() ) ); + mSimplifyAlgorithmComboBox->setCurrentIndex( mSimplifyAlgorithmComboBox->findData( mSettings->value( QStringLiteral( "/qgis/simplifyAlgorithm" ), 0 ).toInt() ) ); // Slightly awkard here at the settings value is true to use QImage, // but the checkbox is true to use QPixmap - chkAddedVisibility->setChecked( mSettings->value( "/qgis/new_layers_visible", true ).toBool() ); - cbxLegendClassifiers->setChecked( mSettings->value( "/qgis/showLegendClassifiers", false ).toBool() ); - mLegendLayersBoldChkBx->setChecked( mSettings->value( "/qgis/legendLayersBold", true ).toBool() ); - mLegendGroupsBoldChkBx->setChecked( mSettings->value( "/qgis/legendGroupsBold", false ).toBool() ); - cbxHideSplash->setChecked( mSettings->value( "/qgis/hideSplash", false ).toBool() ); - cbxShowTips->setChecked( mSettings->value( QString( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), true ).toBool() ); - cbxCheckVersion->setChecked( mSettings->value( "/qgis/checkVersion", true ).toBool() ); - cbxAttributeTableDocked->setChecked( mSettings->value( "/qgis/dockAttributeTable", false ).toBool() ); - cbxAddPostgisDC->setChecked( mSettings->value( "/qgis/addPostgisDC", false ).toBool() ); - cbxAddOracleDC->setChecked( mSettings->value( "/qgis/addOracleDC", false ).toBool() ); - cbxCompileExpressions->setChecked( mSettings->value( "/qgis/compileExpressions", true ).toBool() ); - cbxCreateRasterLegendIcons->setChecked( mSettings->value( "/qgis/createRasterLegendIcons", false ).toBool() ); + chkAddedVisibility->setChecked( mSettings->value( QStringLiteral( "/qgis/new_layers_visible" ), true ).toBool() ); + cbxLegendClassifiers->setChecked( mSettings->value( QStringLiteral( "/qgis/showLegendClassifiers" ), false ).toBool() ); + mLegendLayersBoldChkBx->setChecked( mSettings->value( QStringLiteral( "/qgis/legendLayersBold" ), true ).toBool() ); + mLegendGroupsBoldChkBx->setChecked( mSettings->value( QStringLiteral( "/qgis/legendGroupsBold" ), false ).toBool() ); + cbxHideSplash->setChecked( mSettings->value( QStringLiteral( "/qgis/hideSplash" ), false ).toBool() ); + cbxShowTips->setChecked( mSettings->value( QStringLiteral( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), true ).toBool() ); + cbxCheckVersion->setChecked( mSettings->value( QStringLiteral( "/qgis/checkVersion" ), true ).toBool() ); + cbxAttributeTableDocked->setChecked( mSettings->value( QStringLiteral( "/qgis/dockAttributeTable" ), false ).toBool() ); + cbxAddPostgisDC->setChecked( mSettings->value( QStringLiteral( "/qgis/addPostgisDC" ), false ).toBool() ); + cbxAddOracleDC->setChecked( mSettings->value( QStringLiteral( "/qgis/addOracleDC" ), false ).toBool() ); + cbxCompileExpressions->setChecked( mSettings->value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ); + cbxCreateRasterLegendIcons->setChecked( mSettings->value( QStringLiteral( "/qgis/createRasterLegendIcons" ), false ).toBool() ); mComboCopyFeatureFormat->addItem( tr( "Plain text, no geometry" ), QgsClipboard::AttributesOnly ); mComboCopyFeatureFormat->addItem( tr( "Plain text, WKT geometry" ), QgsClipboard::AttributesWithWKT ); mComboCopyFeatureFormat->addItem( tr( "GeoJSON" ), QgsClipboard::GeoJSON ); - if ( mSettings->contains( "/qgis/copyFeatureFormat" ) ) - mComboCopyFeatureFormat->setCurrentIndex( mComboCopyFeatureFormat->findData( mSettings->value( "/qgis/copyFeatureFormat", true ).toInt() ) ); + if ( mSettings->contains( QStringLiteral( "/qgis/copyFeatureFormat" ) ) ) + mComboCopyFeatureFormat->setCurrentIndex( mComboCopyFeatureFormat->findData( mSettings->value( QStringLiteral( "/qgis/copyFeatureFormat" ), true ).toInt() ) ); else - mComboCopyFeatureFormat->setCurrentIndex( mComboCopyFeatureFormat->findData( mSettings->value( "/qgis/copyGeometryAsWKT", true ).toBool() ? + mComboCopyFeatureFormat->setCurrentIndex( mComboCopyFeatureFormat->findData( mSettings->value( QStringLiteral( "/qgis/copyGeometryAsWKT" ), true ).toBool() ? QgsClipboard::AttributesWithWKT : QgsClipboard::AttributesOnly ) ); - leNullValue->setText( mSettings->value( "qgis/nullValue", "NULL" ).toString() ); - cbxIgnoreShapeEncoding->setChecked( mSettings->value( "/qgis/ignoreShapeEncoding", true ).toBool() ); + leNullValue->setText( mSettings->value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); + cbxIgnoreShapeEncoding->setChecked( mSettings->value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ); - cmbLegendDoubleClickAction->setCurrentIndex( mSettings->value( "/qgis/legendDoubleClickAction", 0 ).toInt() ); + cmbLegendDoubleClickAction->setCurrentIndex( mSettings->value( QStringLiteral( "/qgis/legendDoubleClickAction" ), 0 ).toInt() ); // WMS getLegendGraphic setting - mLegendGraphicResolutionSpinBox->setValue( mSettings->value( "/qgis/defaultLegendGraphicResolution", 0 ).toInt() ); + mLegendGraphicResolutionSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/defaultLegendGraphicResolution" ), 0 ).toInt() ); // // Raster properties // - spnRed->setValue( mSettings->value( "/Raster/defaultRedBand", 1 ).toInt() ); - spnGreen->setValue( mSettings->value( "/Raster/defaultGreenBand", 2 ).toInt() ); - spnBlue->setValue( mSettings->value( "/Raster/defaultBlueBand", 3 ).toInt() ); + spnRed->setValue( mSettings->value( QStringLiteral( "/Raster/defaultRedBand" ), 1 ).toInt() ); + spnGreen->setValue( mSettings->value( QStringLiteral( "/Raster/defaultGreenBand" ), 2 ).toInt() ); + spnBlue->setValue( mSettings->value( QStringLiteral( "/Raster/defaultBlueBand" ), 3 ).toInt() ); - initContrastEnhancement( cboxContrastEnhancementAlgorithmSingleBand, "singleBand", "StretchToMinimumMaximum" ); - initContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandSingleByte, "multiBandSingleByte", "NoEnhancement" ); - initContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandMultiByte, "multiBandMultiByte", "StretchToMinimumMaximum" ); + initContrastEnhancement( cboxContrastEnhancementAlgorithmSingleBand, QStringLiteral( "singleBand" ), QStringLiteral( "StretchToMinimumMaximum" ) ); + initContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandSingleByte, QStringLiteral( "multiBandSingleByte" ), QStringLiteral( "NoEnhancement" ) ); + initContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandMultiByte, QStringLiteral( "multiBandMultiByte" ), QStringLiteral( "StretchToMinimumMaximum" ) ); cboxContrastEnhancementLimits->addItem( tr( "Cumulative pixel count cut" ), "CumulativeCut" ); cboxContrastEnhancementLimits->addItem( tr( "Minimum / maximum" ), "MinMax" ); cboxContrastEnhancementLimits->addItem( tr( "Mean +/- standard deviation" ), "StdDev" ); - QString contrastEnchacementLimits = mSettings->value( "/Raster/defaultContrastEnhancementLimits", "CumulativeCut" ).toString(); + QString contrastEnchacementLimits = mSettings->value( QStringLiteral( "/Raster/defaultContrastEnhancementLimits" ), "CumulativeCut" ).toString(); cboxContrastEnhancementLimits->setCurrentIndex( cboxContrastEnhancementLimits->findData( contrastEnchacementLimits ) ); - spnThreeBandStdDev->setValue( mSettings->value( "/Raster/defaultStandardDeviation", 2.0 ).toDouble() ); + spnThreeBandStdDev->setValue( mSettings->value( QStringLiteral( "/Raster/defaultStandardDeviation" ), 2.0 ).toDouble() ); - mRasterCumulativeCutLowerDoubleSpinBox->setValue( 100.0 * mSettings->value( "/Raster/cumulativeCutLower", QString::number( QgsRasterLayer::CUMULATIVE_CUT_LOWER ) ).toDouble() ); - mRasterCumulativeCutUpperDoubleSpinBox->setValue( 100.0 * mSettings->value( "/Raster/cumulativeCutUpper", QString::number( QgsRasterLayer::CUMULATIVE_CUT_UPPER ) ).toDouble() ); + mRasterCumulativeCutLowerDoubleSpinBox->setValue( 100.0 * mSettings->value( QStringLiteral( "/Raster/cumulativeCutLower" ), QString::number( QgsRasterLayer::CUMULATIVE_CUT_LOWER ) ).toDouble() ); + mRasterCumulativeCutUpperDoubleSpinBox->setValue( 100.0 * mSettings->value( QStringLiteral( "/Raster/cumulativeCutUpper" ), QString::number( QgsRasterLayer::CUMULATIVE_CUT_UPPER ) ).toDouble() ); //set the color for selections - int myRed = mSettings->value( "/qgis/default_selection_color_red", 255 ).toInt(); - int myGreen = mSettings->value( "/qgis/default_selection_color_green", 255 ).toInt(); - int myBlue = mSettings->value( "/qgis/default_selection_color_blue", 0 ).toInt(); - int myAlpha = mSettings->value( "/qgis/default_selection_color_alpha", 255 ).toInt(); + int myRed = mSettings->value( QStringLiteral( "/qgis/default_selection_color_red" ), 255 ).toInt(); + int myGreen = mSettings->value( QStringLiteral( "/qgis/default_selection_color_green" ), 255 ).toInt(); + int myBlue = mSettings->value( QStringLiteral( "/qgis/default_selection_color_blue" ), 0 ).toInt(); + int myAlpha = mSettings->value( QStringLiteral( "/qgis/default_selection_color_alpha" ), 255 ).toInt(); pbnSelectionColor->setColor( QColor( myRed, myGreen, myBlue, myAlpha ) ); pbnSelectionColor->setColorDialogTitle( tr( "Set selection color" ) ); pbnSelectionColor->setAllowAlpha( true ); - pbnSelectionColor->setContext( "gui" ); + pbnSelectionColor->setContext( QStringLiteral( "gui" ) ); pbnSelectionColor->setDefaultColor( QColor( 255, 255, 0, 255 ) ); //set the default color for canvas background - myRed = mSettings->value( "/qgis/default_canvas_color_red", 255 ).toInt(); - myGreen = mSettings->value( "/qgis/default_canvas_color_green", 255 ).toInt(); - myBlue = mSettings->value( "/qgis/default_canvas_color_blue", 255 ).toInt(); + myRed = mSettings->value( QStringLiteral( "/qgis/default_canvas_color_red" ), 255 ).toInt(); + myGreen = mSettings->value( QStringLiteral( "/qgis/default_canvas_color_green" ), 255 ).toInt(); + myBlue = mSettings->value( QStringLiteral( "/qgis/default_canvas_color_blue" ), 255 ).toInt(); pbnCanvasColor->setColor( QColor( myRed, myGreen, myBlue ) ); pbnCanvasColor->setColorDialogTitle( tr( "Set canvas color" ) ); - pbnCanvasColor->setContext( "gui" ); + pbnCanvasColor->setContext( QStringLiteral( "gui" ) ); pbnCanvasColor->setDefaultColor( Qt::white ); // set the default color for the measure tool - myRed = mSettings->value( "/qgis/default_measure_color_red", 222 ).toInt(); - myGreen = mSettings->value( "/qgis/default_measure_color_green", 155 ).toInt(); - myBlue = mSettings->value( "/qgis/default_measure_color_blue", 67 ).toInt(); + myRed = mSettings->value( QStringLiteral( "/qgis/default_measure_color_red" ), 222 ).toInt(); + myGreen = mSettings->value( QStringLiteral( "/qgis/default_measure_color_green" ), 155 ).toInt(); + myBlue = mSettings->value( QStringLiteral( "/qgis/default_measure_color_blue" ), 67 ).toInt(); pbnMeasureColor->setColor( QColor( myRed, myGreen, myBlue ) ); pbnMeasureColor->setColorDialogTitle( tr( "Set measuring tool color" ) ); - pbnMeasureColor->setContext( "gui" ); + pbnMeasureColor->setContext( QStringLiteral( "gui" ) ); pbnMeasureColor->setDefaultColor( QColor( 222, 155, 67 ) ); - capitaliseCheckBox->setChecked( mSettings->value( "/qgis/capitaliseLayerName", QVariant( false ) ).toBool() ); + capitaliseCheckBox->setChecked( mSettings->value( QStringLiteral( "/qgis/capitaliseLayerName" ), QVariant( false ) ).toBool() ); - int projOpen = mSettings->value( "/qgis/projOpenAtLaunch", 0 ).toInt(); + int projOpen = mSettings->value( QStringLiteral( "/qgis/projOpenAtLaunch" ), 0 ).toInt(); mProjectOnLaunchCmbBx->setCurrentIndex( projOpen ); - mProjectOnLaunchLineEdit->setText( mSettings->value( "/qgis/projOpenAtLaunchPath" ).toString() ); + mProjectOnLaunchLineEdit->setText( mSettings->value( QStringLiteral( "/qgis/projOpenAtLaunchPath" ) ).toString() ); mProjectOnLaunchLineEdit->setEnabled( projOpen == 2 ); mProjectOnLaunchPushBtn->setEnabled( projOpen == 2 ); - chbAskToSaveProjectChanges->setChecked( mSettings->value( "qgis/askToSaveProjectChanges", QVariant( true ) ).toBool() ); - mLayerDeleteConfirmationChkBx->setChecked( mSettings->value( "qgis/askToDeleteLayers", true ).toBool() ); - chbWarnOldProjectVersion->setChecked( mSettings->value( "/qgis/warnOldProjectVersion", QVariant( true ) ).toBool() ); - cmbEnableMacros->setCurrentIndex( mSettings->value( "/qgis/enableMacros", 1 ).toInt() ); + chbAskToSaveProjectChanges->setChecked( mSettings->value( QStringLiteral( "qgis/askToSaveProjectChanges" ), QVariant( true ) ).toBool() ); + mLayerDeleteConfirmationChkBx->setChecked( mSettings->value( QStringLiteral( "qgis/askToDeleteLayers" ), true ).toBool() ); + chbWarnOldProjectVersion->setChecked( mSettings->value( QStringLiteral( "/qgis/warnOldProjectVersion" ), QVariant( true ) ).toBool() ); + cmbEnableMacros->setCurrentIndex( mSettings->value( QStringLiteral( "/qgis/enableMacros" ), 1 ).toInt() ); // templates - cbxProjectDefaultNew->setChecked( mSettings->value( "/qgis/newProjectDefault", QVariant( false ) ).toBool() ); - QString templateDirName = mSettings->value( "/qgis/projectTemplateDir", + cbxProjectDefaultNew->setChecked( mSettings->value( QStringLiteral( "/qgis/newProjectDefault" ), QVariant( false ) ).toBool() ); + QString templateDirName = mSettings->value( QStringLiteral( "/qgis/projectTemplateDir" ), QgsApplication::qgisSettingsDirPath() + "project_templates" ).toString(); // make dir if it doesn't exists - should just be called once QDir templateDir; @@ -724,10 +724,10 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) } leTemplateFolder->setText( templateDirName ); - spinZoomFactor->setValue( mSettings->value( "/qgis/zoom_factor", 2 ).toDouble() ); + spinZoomFactor->setValue( mSettings->value( QStringLiteral( "/qgis/zoom_factor" ), 2 ).toDouble() ); // predefined scales for scale combobox - myPaths = mSettings->value( "Map/scales", PROJECT_SCALES ).toString(); + myPaths = mSettings->value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString(); if ( !myPaths.isEmpty() ) { QStringList myScalesList = myPaths.split( ',' ); @@ -762,7 +762,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) //default composer font mComposerFontComboBox->blockSignals( true ); - QString composerFontFamily = mSettings->value( "/Composer/defaultFont" ).toString(); + QString composerFontFamily = mSettings->value( QStringLiteral( "/Composer/defaultFont" ) ).toString(); QFont *tempComposerFont = new QFont( composerFontFamily ); // is exact family match returned from system? @@ -776,28 +776,28 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) //default composer grid color int gridRed, gridGreen, gridBlue, gridAlpha; - gridRed = mSettings->value( "/Composer/gridRed", 190 ).toInt(); - gridGreen = mSettings->value( "/Composer/gridGreen", 190 ).toInt(); - gridBlue = mSettings->value( "/Composer/gridBlue", 190 ).toInt(); - gridAlpha = mSettings->value( "/Composer/gridAlpha", 100 ).toInt(); + gridRed = mSettings->value( QStringLiteral( "/Composer/gridRed" ), 190 ).toInt(); + gridGreen = mSettings->value( QStringLiteral( "/Composer/gridGreen" ), 190 ).toInt(); + gridBlue = mSettings->value( QStringLiteral( "/Composer/gridBlue" ), 190 ).toInt(); + gridAlpha = mSettings->value( QStringLiteral( "/Composer/gridAlpha" ), 100 ).toInt(); QColor gridColor = QColor( gridRed, gridGreen, gridBlue, gridAlpha ); mGridColorButton->setColor( gridColor ); mGridColorButton->setColorDialogTitle( tr( "Select grid color" ) ); mGridColorButton->setAllowAlpha( true ); - mGridColorButton->setContext( "gui" ); + mGridColorButton->setContext( QStringLiteral( "gui" ) ); mGridColorButton->setDefaultColor( QColor( 190, 190, 190, 100 ) ); //default composer grid style QString gridStyleString; - gridStyleString = mSettings->value( "/Composer/gridStyle", "Dots" ).toString(); + gridStyleString = mSettings->value( QStringLiteral( "/Composer/gridStyle" ), "Dots" ).toString(); mGridStyleComboBox->insertItem( 0, tr( "Solid" ) ); mGridStyleComboBox->insertItem( 1, tr( "Dots" ) ); mGridStyleComboBox->insertItem( 2, tr( "Crosses" ) ); - if ( gridStyleString == "Solid" ) + if ( gridStyleString == QLatin1String( "Solid" ) ) { mGridStyleComboBox->setCurrentIndex( 0 ); } - else if ( gridStyleString == "Crosses" ) + else if ( gridStyleString == QLatin1String( "Crosses" ) ) { mGridStyleComboBox->setCurrentIndex( 2 ); } @@ -808,58 +808,58 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) } //grid and guide defaults - mGridResolutionSpinBox->setValue( mSettings->value( "/Composer/defaultSnapGridResolution", 10.0 ).toDouble() ); - mSnapToleranceSpinBox->setValue( mSettings->value( "/Composer/defaultSnapTolerancePixels", 5 ).toInt() ); - mOffsetXSpinBox->setValue( mSettings->value( "/Composer/defaultSnapGridOffsetX", 0 ).toDouble() ); - mOffsetYSpinBox->setValue( mSettings->value( "/Composer/defaultSnapGridOffsetY", 0 ).toDouble() ); + mGridResolutionSpinBox->setValue( mSettings->value( QStringLiteral( "/Composer/defaultSnapGridResolution" ), 10.0 ).toDouble() ); + mSnapToleranceSpinBox->setValue( mSettings->value( QStringLiteral( "/Composer/defaultSnapTolerancePixels" ), 5 ).toInt() ); + mOffsetXSpinBox->setValue( mSettings->value( QStringLiteral( "/Composer/defaultSnapGridOffsetX" ), 0 ).toDouble() ); + mOffsetYSpinBox->setValue( mSettings->value( QStringLiteral( "/Composer/defaultSnapGridOffsetY" ), 0 ).toDouble() ); // // Locale settings // QString mySystemLocale = QLocale::system().name(); lblSystemLocale->setText( tr( "Detected active locale on your system: %1" ).arg( mySystemLocale ) ); - QString myUserLocale = mSettings->value( "locale/userLocale", "" ).toString(); + QString myUserLocale = mSettings->value( QStringLiteral( "locale/userLocale" ), "" ).toString(); QStringList myI18nList = i18nList(); Q_FOREACH ( const QString& l, myI18nList ) { cboLocale->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( l ) ), QLocale( l ).nativeLanguageName(), l ); } cboLocale->setCurrentIndex( cboLocale->findData( myUserLocale ) ); - bool myLocaleOverrideFlag = mSettings->value( "locale/overrideFlag", false ).toBool(); + bool myLocaleOverrideFlag = mSettings->value( QStringLiteral( "locale/overrideFlag" ), false ).toBool(); grpLocale->setChecked( myLocaleOverrideFlag ); //set elements in digitizing tab - mLineWidthSpinBox->setValue( mSettings->value( "/qgis/digitizing/line_width", 1 ).toInt() ); - myRed = mSettings->value( "/qgis/digitizing/line_color_red", 255 ).toInt(); - myGreen = mSettings->value( "/qgis/digitizing/line_color_green", 0 ).toInt(); - myBlue = mSettings->value( "/qgis/digitizing/line_color_blue", 0 ).toInt(); - myAlpha = mSettings->value( "/qgis/digitizing/line_color_alpha", 200 ).toInt(); + mLineWidthSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/digitizing/line_width" ), 1 ).toInt() ); + myRed = mSettings->value( QStringLiteral( "/qgis/digitizing/line_color_red" ), 255 ).toInt(); + myGreen = mSettings->value( QStringLiteral( "/qgis/digitizing/line_color_green" ), 0 ).toInt(); + myBlue = mSettings->value( QStringLiteral( "/qgis/digitizing/line_color_blue" ), 0 ).toInt(); + myAlpha = mSettings->value( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), 200 ).toInt(); mLineColorToolButton->setColor( QColor( myRed, myGreen, myBlue, myAlpha ) ); mLineColorToolButton->setAllowAlpha( true ); - mLineColorToolButton->setContext( "gui" ); + mLineColorToolButton->setContext( QStringLiteral( "gui" ) ); mLineColorToolButton->setDefaultColor( QColor( 255, 0, 0, 200 ) ); - myRed = mSettings->value( "/qgis/digitizing/fill_color_red", 255 ).toInt(); - myGreen = mSettings->value( "/qgis/digitizing/fill_color_green", 0 ).toInt(); - myBlue = mSettings->value( "/qgis/digitizing/fill_color_blue", 0 ).toInt(); - myAlpha = mSettings->value( "/qgis/digitizing/fill_color_alpha", 30 ).toInt(); + myRed = mSettings->value( QStringLiteral( "/qgis/digitizing/fill_color_red" ), 255 ).toInt(); + myGreen = mSettings->value( QStringLiteral( "/qgis/digitizing/fill_color_green" ), 0 ).toInt(); + myBlue = mSettings->value( QStringLiteral( "/qgis/digitizing/fill_color_blue" ), 0 ).toInt(); + myAlpha = mSettings->value( QStringLiteral( "/qgis/digitizing/fill_color_alpha" ), 30 ).toInt(); mFillColorToolButton->setColor( QColor( myRed, myGreen, myBlue, myAlpha ) ); mFillColorToolButton->setAllowAlpha( true ); - mFillColorToolButton->setContext( "gui" ); + mFillColorToolButton->setContext( QStringLiteral( "gui" ) ); mFillColorToolButton->setDefaultColor( QColor( 255, 0, 0, 30 ) ); - mLineGhostCheckBox->setChecked( mSettings->value( "/qgis/digitizing/line_ghost", false ).toBool() ); + mLineGhostCheckBox->setChecked( mSettings->value( QStringLiteral( "/qgis/digitizing/line_ghost" ), false ).toBool() ); //default snap mode mDefaultSnapModeComboBox->insertItem( 0, tr( "To vertex" ), "to vertex" ); mDefaultSnapModeComboBox->insertItem( 1, tr( "To segment" ), "to segment" ); mDefaultSnapModeComboBox->insertItem( 2, tr( "To vertex and segment" ), "to vertex and segment" ); mDefaultSnapModeComboBox->insertItem( 3, tr( "Off" ), "off" ); - QString defaultSnapString = mSettings->value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); + QString defaultSnapString = mSettings->value( QStringLiteral( "/qgis/digitizing/default_snap_mode" ), "off" ).toString(); mDefaultSnapModeComboBox->setCurrentIndex( mDefaultSnapModeComboBox->findData( defaultSnapString ) ); - mDefaultSnappingToleranceSpinBox->setValue( mSettings->value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble() ); - mSearchRadiusVertexEditSpinBox->setValue( mSettings->value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble() ); - int defSnapUnits = mSettings->value( "/qgis/digitizing/default_snapping_tolerance_unit", QgsTolerance::ProjectUnits ).toInt(); + mDefaultSnappingToleranceSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), 0 ).toDouble() ); + mSearchRadiusVertexEditSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit" ), 10 ).toDouble() ); + int defSnapUnits = mSettings->value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), QgsTolerance::ProjectUnits ).toInt(); if ( defSnapUnits == QgsTolerance::ProjectUnits || defSnapUnits == QgsTolerance::LayerUnits ) { index = mDefaultSnappingToleranceComboBox->findText( tr( "map units" ) ); @@ -869,7 +869,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) index = mDefaultSnappingToleranceComboBox->findText( tr( "pixels" ) ); } mDefaultSnappingToleranceComboBox->setCurrentIndex( index ); - int defRadiusUnits = mSettings->value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt(); + int defRadiusUnits = mSettings->value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit_unit" ), QgsTolerance::Pixels ).toInt(); if ( defRadiusUnits == QgsTolerance::ProjectUnits || defRadiusUnits == QgsTolerance::LayerUnits ) { index = mSearchRadiusVertexEditComboBox->findText( tr( "map units" ) ); @@ -881,7 +881,7 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mSearchRadiusVertexEditComboBox->setCurrentIndex( index ); //vertex marker - mMarkersOnlyForSelectedCheckBox->setChecked( mSettings->value( "/qgis/digitizing/marker_only_for_selected", false ).toBool() ); + mMarkersOnlyForSelectedCheckBox->setChecked( mSettings->value( QStringLiteral( "/qgis/digitizing/marker_only_for_selected" ), false ).toBool() ); mMarkerStyleComboBox->addItem( tr( "Semi transparent circle" ) ); mMarkerStyleComboBox->addItem( tr( "Cross" ) ); @@ -892,40 +892,40 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mValidateGeometries->addItem( tr( "QGIS" ) ); mValidateGeometries->addItem( tr( "GEOS" ) ); - QString markerStyle = mSettings->value( "/qgis/digitizing/marker_style", "Cross" ).toString(); - if ( markerStyle == "SemiTransparentCircle" ) + QString markerStyle = mSettings->value( QStringLiteral( "/qgis/digitizing/marker_style" ), "Cross" ).toString(); + if ( markerStyle == QLatin1String( "SemiTransparentCircle" ) ) { mMarkerStyleComboBox->setCurrentIndex( mMarkerStyleComboBox->findText( tr( "Semi transparent circle" ) ) ); } - else if ( markerStyle == "Cross" ) + else if ( markerStyle == QLatin1String( "Cross" ) ) { mMarkerStyleComboBox->setCurrentIndex( mMarkerStyleComboBox->findText( tr( "Cross" ) ) ); } - else if ( markerStyle == "None" ) + else if ( markerStyle == QLatin1String( "None" ) ) { mMarkerStyleComboBox->setCurrentIndex( mMarkerStyleComboBox->findText( tr( "None" ) ) ); } - mMarkerSizeSpinBox->setValue( mSettings->value( "/qgis/digitizing/marker_size", 3 ).toInt() ); + mMarkerSizeSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/digitizing/marker_size" ), 3 ).toInt() ); - chkReuseLastValues->setChecked( mSettings->value( "/qgis/digitizing/reuseLastValues", false ).toBool() ); - chkDisableAttributeValuesDlg->setChecked( mSettings->value( "/qgis/digitizing/disable_enter_attribute_values_dialog", false ).toBool() ); - mValidateGeometries->setCurrentIndex( mSettings->value( "/qgis/digitizing/validate_geometries", 1 ).toInt() ); + chkReuseLastValues->setChecked( mSettings->value( QStringLiteral( "/qgis/digitizing/reuseLastValues" ), false ).toBool() ); + chkDisableAttributeValuesDlg->setChecked( mSettings->value( QStringLiteral( "/qgis/digitizing/disable_enter_attribute_values_dialog" ), false ).toBool() ); + mValidateGeometries->setCurrentIndex( mSettings->value( QStringLiteral( "/qgis/digitizing/validate_geometries" ), 1 ).toInt() ); mSnappingMainDialogComboBox->clear(); mSnappingMainDialogComboBox->addItem( tr( "dialog" ), "dialog" ); mSnappingMainDialogComboBox->addItem( tr( "dock" ), "dock" ); - mSnappingMainDialogComboBox->setCurrentIndex( mSnappingMainDialogComboBox->findData( mSettings->value( "/qgis/mainSnappingWidgetMode", "dialog" ).toString() ) ); + mSnappingMainDialogComboBox->setCurrentIndex( mSnappingMainDialogComboBox->findData( mSettings->value( QStringLiteral( "/qgis/mainSnappingWidgetMode" ), "dialog" ).toString() ) ); mSnappingSimplePanelComboBox->clear(); mSnappingSimplePanelComboBox->addItem( tr( "tool bar" ), "toolbar" ); mSnappingSimplePanelComboBox->addItem( tr( "status bar" ), "statusbar" ); - mSnappingSimplePanelComboBox->setCurrentIndex( mSnappingSimplePanelComboBox->findData( mSettings->value( "/qgis/simpleSnappingWidgetMode", "toolbar" ).toString() ) ); + mSnappingSimplePanelComboBox->setCurrentIndex( mSnappingSimplePanelComboBox->findData( mSettings->value( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), "toolbar" ).toString() ) ); mOffsetJoinStyleComboBox->addItem( tr( "Round" ), 0 ); mOffsetJoinStyleComboBox->addItem( tr( "Mitre" ), 1 ); mOffsetJoinStyleComboBox->addItem( tr( "Bevel" ), 2 ); - mOffsetJoinStyleComboBox->setCurrentIndex( mSettings->value( "/qgis/digitizing/offset_join_style", 0 ).toInt() ); - mOffsetQuadSegSpinBox->setValue( mSettings->value( "/qgis/digitizing/offset_quad_seg", 8 ).toInt() ); - mCurveOffsetMiterLimitComboBox->setValue( mSettings->value( "/qgis/digitizing/offset_miter_limit", 5.0 ).toDouble() ); + mOffsetJoinStyleComboBox->setCurrentIndex( mSettings->value( QStringLiteral( "/qgis/digitizing/offset_join_style" ), 0 ).toInt() ); + mOffsetQuadSegSpinBox->setValue( mSettings->value( QStringLiteral( "/qgis/digitizing/offset_quad_seg" ), 8 ).toInt() ); + mCurveOffsetMiterLimitComboBox->setValue( mSettings->value( QStringLiteral( "/qgis/digitizing/offset_miter_limit" ), 5.0 ).toDouble() ); // load gdal driver list only when gdal tab is first opened mLoadedGdalDriverList = false; @@ -972,7 +972,7 @@ void QgsOptions::on_cbxProjectDefaultNew_toggled( bool checked ) { if ( checked ) { - QString fileName = QgsApplication::qgisSettingsDirPath() + QLatin1String( "project_default.qgs" ); + QString fileName = QgsApplication::qgisSettingsDirPath() + QStringLiteral( "project_default.qgs" ); if ( ! QFile::exists( fileName ) ) { QMessageBox::information( nullptr, tr( "Save default project" ), tr( "You must set a default project" ) ); @@ -983,7 +983,7 @@ void QgsOptions::on_cbxProjectDefaultNew_toggled( bool checked ) void QgsOptions::on_pbnProjectDefaultSetCurrent_clicked() { - QString fileName = QgsApplication::qgisSettingsDirPath() + QLatin1String( "project_default.qgs" ); + QString fileName = QgsApplication::qgisSettingsDirPath() + QStringLiteral( "project_default.qgs" ); if ( QgsProject::instance()->write( QFileInfo( fileName ) ) ) { QMessageBox::information( nullptr, tr( "Save default project" ), tr( "Current project saved as default" ) ); @@ -996,7 +996,7 @@ void QgsOptions::on_pbnProjectDefaultSetCurrent_clicked() void QgsOptions::on_pbnProjectDefaultReset_clicked() { - QString fileName = QgsApplication::qgisSettingsDirPath() + QLatin1String( "project_default.qgs" ); + QString fileName = QgsApplication::qgisSettingsDirPath() + QStringLiteral( "project_default.qgs" ); if ( QFile::exists( fileName ) ) { QFile::remove( fileName ); @@ -1016,7 +1016,7 @@ void QgsOptions::on_pbnTemplateFolderBrowse_pressed() void QgsOptions::on_pbnTemplateFolderReset_pressed() { - leTemplateFolder->setText( QgsApplication::qgisSettingsDirPath() + QLatin1String( "project_templates" ) ); + leTemplateFolder->setText( QgsApplication::qgisSettingsDirPath() + QStringLiteral( "project_templates" ) ); } void QgsOptions::iconSizeChanged( const QString &iconSize ) @@ -1043,7 +1043,7 @@ void QgsOptions::on_mProjectOnLaunchPushBtn_pressed() { // Retrieve last used project dir from persistent settings QSettings settings; - QString lastUsedDir = mSettings->value( "/UI/lastProjectDir", QDir::homePath() ).toString(); + QString lastUsedDir = mSettings->value( QStringLiteral( "/UI/lastProjectDir" ), QDir::homePath() ).toString(); QString projPath = QFileDialog::getOpenFileName( this, tr( "Choose project file to open at launch" ), lastUsedDir, @@ -1058,10 +1058,10 @@ void QgsOptions::saveOptions() { QSettings settings; - mSettings->setValue( "UI/UITheme", cmbUITheme->currentText() ); + mSettings->setValue( QStringLiteral( "UI/UITheme" ), cmbUITheme->currentText() ); // custom environment variables - mSettings->setValue( "qgis/customEnvVarsUse", QVariant( mCustomVariablesChkBx->isChecked() ) ); + mSettings->setValue( QStringLiteral( "qgis/customEnvVarsUse" ), QVariant( mCustomVariablesChkBx->isChecked() ) ); QStringList customVars; for ( int i = 0; i < mCustomVariablesTable->rowCount(); ++i ) { @@ -1075,7 +1075,7 @@ void QgsOptions::saveOptions() customVar += mCustomVariablesTable->item( i, 2 )->text(); customVars << customVar; } - mSettings->setValue( "qgis/customEnvVars", QVariant( customVars ) ); + mSettings->setValue( QStringLiteral( "qgis/customEnvVars" ), QVariant( customVars ) ); //search directories for user plugins QString myPaths; @@ -1087,7 +1087,7 @@ void QgsOptions::saveOptions() } myPaths += mListPluginPaths->item( i )->text(); } - mSettings->setValue( "plugins/searchPathsForPlugins", myPaths ); + mSettings->setValue( QStringLiteral( "plugins/searchPathsForPlugins" ), myPaths ); //search directories for svgs myPaths.clear(); @@ -1099,7 +1099,7 @@ void QgsOptions::saveOptions() } myPaths += mListSVGPaths->item( i )->text(); } - mSettings->setValue( "svg/searchPathsForSVG", myPaths ); + mSettings->setValue( QStringLiteral( "svg/searchPathsForSVG" ), myPaths ); myPaths.clear(); for ( int i = 0; i < mListComposerTemplatePaths->count(); ++i ) @@ -1110,42 +1110,42 @@ void QgsOptions::saveOptions() } myPaths += mListComposerTemplatePaths->item( i )->text(); } - mSettings->setValue( "composer/searchPathsForTemplates", myPaths ); + mSettings->setValue( QStringLiteral( "composer/searchPathsForTemplates" ), myPaths ); QStringList paths; for ( int i = 0; i < mListHiddenBrowserPaths->count(); ++i ) { paths << mListHiddenBrowserPaths->item( i )->text(); } - mSettings->setValue( "/browser/hiddenPaths", paths ); + mSettings->setValue( QStringLiteral( "/browser/hiddenPaths" ), paths ); //Network timeout - mSettings->setValue( "/qgis/networkAndProxy/networkTimeout", mNetworkTimeoutSpinBox->value() ); - mSettings->setValue( "/qgis/networkAndProxy/userAgent", leUserAgent->text() ); + mSettings->setValue( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), mNetworkTimeoutSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/networkAndProxy/userAgent" ), leUserAgent->text() ); // WMS capabiltiies expiry time - mSettings->setValue( "/qgis/defaultCapabilitiesExpiry", mDefaultCapabilitiesExpirySpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/defaultCapabilitiesExpiry" ), mDefaultCapabilitiesExpirySpinBox->value() ); // WMS/WMS-C tile expiry time - mSettings->setValue( "/qgis/defaultTileExpiry", mDefaultTileExpirySpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/defaultTileExpiry" ), mDefaultTileExpirySpinBox->value() ); // WMS/WMS-C default max retry in case of tile request errors - mSettings->setValue( "/qgis/defaultTileMaxRetry", mDefaultTileMaxRetrySpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/defaultTileMaxRetry" ), mDefaultTileMaxRetrySpinBox->value() ); //Web proxy settings - mSettings->setValue( "proxy/proxyEnabled", grpProxy->isChecked() ); - mSettings->setValue( "proxy/proxyHost", leProxyHost->text() ); - mSettings->setValue( "proxy/proxyPort", leProxyPort->text() ); - mSettings->setValue( "proxy/proxyUser", leProxyUser->text() ); - mSettings->setValue( "proxy/proxyPassword", leProxyPassword->text() ); - mSettings->setValue( "proxy/proxyType", mProxyTypeComboBox->currentText() ); + mSettings->setValue( QStringLiteral( "proxy/proxyEnabled" ), grpProxy->isChecked() ); + mSettings->setValue( QStringLiteral( "proxy/proxyHost" ), leProxyHost->text() ); + mSettings->setValue( QStringLiteral( "proxy/proxyPort" ), leProxyPort->text() ); + mSettings->setValue( QStringLiteral( "proxy/proxyUser" ), leProxyUser->text() ); + mSettings->setValue( QStringLiteral( "proxy/proxyPassword" ), leProxyPassword->text() ); + mSettings->setValue( QStringLiteral( "proxy/proxyType" ), mProxyTypeComboBox->currentText() ); if ( !mCacheDirectory->text().isEmpty() ) - mSettings->setValue( "cache/directory", mCacheDirectory->text() ); + mSettings->setValue( QStringLiteral( "cache/directory" ), mCacheDirectory->text() ); else - mSettings->remove( "cache/directory" ); + mSettings->remove( QStringLiteral( "cache/directory" ) ); - mSettings->setValue( "cache/size", QVariant::fromValue( mCacheSize->value()*1024L ) ); + mSettings->setValue( QStringLiteral( "cache/size" ), QVariant::fromValue( mCacheSize->value()*1024L ) ); //url to exclude from proxys QString proxyExcludeString; @@ -1157,62 +1157,62 @@ void QgsOptions::saveOptions() } proxyExcludeString += mExcludeUrlListWidget->item( i )->text(); } - mSettings->setValue( "proxy/proxyExcludedUrls", proxyExcludeString ); + mSettings->setValue( QStringLiteral( "proxy/proxyExcludedUrls" ), proxyExcludeString ); QgisApp::instance()->namUpdate(); //wms search url - mSettings->setValue( "/qgis/WMSSearchUrl", leWmsSearch->text() ); + mSettings->setValue( QStringLiteral( "/qgis/WMSSearchUrl" ), leWmsSearch->text() ); //general settings - mSettings->setValue( "/Map/searchRadiusMM", spinBoxIdentifyValue->value() ); - mSettings->setValue( "/Map/highlight/color", mIdentifyHighlightColorButton->color().name() ); - mSettings->setValue( "/Map/highlight/colorAlpha", mIdentifyHighlightColorButton->color().alpha() ); - mSettings->setValue( "/Map/highlight/buffer", mIdentifyHighlightBufferSpinBox->value() ); - mSettings->setValue( "/Map/highlight/minWidth", mIdentifyHighlightMinWidthSpinBox->value() ); - - bool showLegendClassifiers = mSettings->value( "/qgis/showLegendClassifiers", false ).toBool(); - mSettings->setValue( "/qgis/showLegendClassifiers", cbxLegendClassifiers->isChecked() ); - bool legendLayersBold = mSettings->value( "/qgis/legendLayersBold", true ).toBool(); - mSettings->setValue( "/qgis/legendLayersBold", mLegendLayersBoldChkBx->isChecked() ); - bool legendGroupsBold = mSettings->value( "/qgis/legendGroupsBold", false ).toBool(); - mSettings->setValue( "/qgis/legendGroupsBold", mLegendGroupsBoldChkBx->isChecked() ); - mSettings->setValue( "/qgis/hideSplash", cbxHideSplash->isChecked() ); - mSettings->setValue( QString( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), cbxShowTips->isChecked() ); - mSettings->setValue( "/qgis/checkVersion", cbxCheckVersion->isChecked() ); - mSettings->setValue( "/qgis/dockAttributeTable", cbxAttributeTableDocked->isChecked() ); - mSettings->setValue( "/qgis/attributeTableBehaviour", cmbAttrTableBehaviour->currentData() ); - mSettings->setValue( "/qgis/attributeTableView", mAttrTableViewComboBox->currentData() ); - mSettings->setValue( "/qgis/attributeTableRowCache", spinBoxAttrTableRowCache->value() ); - mSettings->setValue( "/qgis/promptForRasterSublayers", cmbPromptRasterSublayers->currentIndex() ); - mSettings->setValue( "/qgis/scanItemsInBrowser2", + mSettings->setValue( QStringLiteral( "/Map/searchRadiusMM" ), spinBoxIdentifyValue->value() ); + mSettings->setValue( QStringLiteral( "/Map/highlight/color" ), mIdentifyHighlightColorButton->color().name() ); + mSettings->setValue( QStringLiteral( "/Map/highlight/colorAlpha" ), mIdentifyHighlightColorButton->color().alpha() ); + mSettings->setValue( QStringLiteral( "/Map/highlight/buffer" ), mIdentifyHighlightBufferSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/Map/highlight/minWidth" ), mIdentifyHighlightMinWidthSpinBox->value() ); + + bool showLegendClassifiers = mSettings->value( QStringLiteral( "/qgis/showLegendClassifiers" ), false ).toBool(); + mSettings->setValue( QStringLiteral( "/qgis/showLegendClassifiers" ), cbxLegendClassifiers->isChecked() ); + bool legendLayersBold = mSettings->value( QStringLiteral( "/qgis/legendLayersBold" ), true ).toBool(); + mSettings->setValue( QStringLiteral( "/qgis/legendLayersBold" ), mLegendLayersBoldChkBx->isChecked() ); + bool legendGroupsBold = mSettings->value( QStringLiteral( "/qgis/legendGroupsBold" ), false ).toBool(); + mSettings->setValue( QStringLiteral( "/qgis/legendGroupsBold" ), mLegendGroupsBoldChkBx->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/hideSplash" ), cbxHideSplash->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), cbxShowTips->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/checkVersion" ), cbxCheckVersion->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/dockAttributeTable" ), cbxAttributeTableDocked->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/attributeTableBehaviour" ), cmbAttrTableBehaviour->currentData() ); + mSettings->setValue( QStringLiteral( "/qgis/attributeTableView" ), mAttrTableViewComboBox->currentData() ); + mSettings->setValue( QStringLiteral( "/qgis/attributeTableRowCache" ), spinBoxAttrTableRowCache->value() ); + mSettings->setValue( QStringLiteral( "/qgis/promptForRasterSublayers" ), cmbPromptRasterSublayers->currentIndex() ); + mSettings->setValue( QStringLiteral( "/qgis/scanItemsInBrowser2" ), cmbScanItemsInBrowser->currentData().toString() ); - mSettings->setValue( "/qgis/scanZipInBrowser2", + mSettings->setValue( QStringLiteral( "/qgis/scanZipInBrowser2" ), cmbScanZipInBrowser->currentData().toString() ); - mSettings->setValue( "/qgis/ignoreShapeEncoding", cbxIgnoreShapeEncoding->isChecked() ); - mSettings->setValue( "/qgis/mainSnappingWidgetMode", mSnappingMainDialogComboBox->currentData() ); - mSettings->setValue( "/qgis/simpleSnappingWidgetMode", mSnappingSimplePanelComboBox->currentData() ); - - mSettings->setValue( "/qgis/addPostgisDC", cbxAddPostgisDC->isChecked() ); - mSettings->setValue( "/qgis/addOracleDC", cbxAddOracleDC->isChecked() ); - mSettings->setValue( "/qgis/compileExpressions", cbxCompileExpressions->isChecked() ); - mSettings->setValue( "/qgis/defaultLegendGraphicResolution", mLegendGraphicResolutionSpinBox->value() ); - bool createRasterLegendIcons = mSettings->value( "/qgis/createRasterLegendIcons", false ).toBool(); - mSettings->setValue( "/qgis/createRasterLegendIcons", cbxCreateRasterLegendIcons->isChecked() ); - mSettings->setValue( "/qgis/copyFeatureFormat", mComboCopyFeatureFormat->currentData().toInt() ); - - mSettings->setValue( "/qgis/new_layers_visible", chkAddedVisibility->isChecked() ); - mSettings->setValue( "/qgis/enable_anti_aliasing", chkAntiAliasing->isChecked() ); - mSettings->setValue( "/qgis/enable_render_caching", chkUseRenderCaching->isChecked() ); - mSettings->setValue( "/qgis/parallel_rendering", chkParallelRendering->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/ignoreShapeEncoding" ), cbxIgnoreShapeEncoding->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/mainSnappingWidgetMode" ), mSnappingMainDialogComboBox->currentData() ); + mSettings->setValue( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), mSnappingSimplePanelComboBox->currentData() ); + + mSettings->setValue( QStringLiteral( "/qgis/addPostgisDC" ), cbxAddPostgisDC->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/addOracleDC" ), cbxAddOracleDC->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/compileExpressions" ), cbxCompileExpressions->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/defaultLegendGraphicResolution" ), mLegendGraphicResolutionSpinBox->value() ); + bool createRasterLegendIcons = mSettings->value( QStringLiteral( "/qgis/createRasterLegendIcons" ), false ).toBool(); + mSettings->setValue( QStringLiteral( "/qgis/createRasterLegendIcons" ), cbxCreateRasterLegendIcons->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/copyFeatureFormat" ), mComboCopyFeatureFormat->currentData().toInt() ); + + mSettings->setValue( QStringLiteral( "/qgis/new_layers_visible" ), chkAddedVisibility->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/enable_anti_aliasing" ), chkAntiAliasing->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/enable_render_caching" ), chkUseRenderCaching->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/parallel_rendering" ), chkParallelRendering->isChecked() ); int maxThreads = chkMaxThreads->isChecked() ? spinMaxThreads->value() : -1; QgsApplication::setMaxThreads( maxThreads ); - mSettings->setValue( "/qgis/max_threads", maxThreads ); + mSettings->setValue( QStringLiteral( "/qgis/max_threads" ), maxThreads ); - mSettings->setValue( "/qgis/map_update_interval", spinMapUpdateInterval->value() ); - mSettings->setValue( "/qgis/legendDoubleClickAction", cmbLegendDoubleClickAction->currentIndex() ); - bool legendLayersCapitalise = mSettings->value( "/qgis/capitaliseLayerName", false ).toBool(); - mSettings->setValue( "/qgis/capitaliseLayerName", capitaliseCheckBox->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/map_update_interval" ), spinMapUpdateInterval->value() ); + mSettings->setValue( QStringLiteral( "/qgis/legendDoubleClickAction" ), cmbLegendDoubleClickAction->currentIndex() ); + bool legendLayersCapitalise = mSettings->value( QStringLiteral( "/qgis/capitaliseLayerName" ), false ).toBool(); + mSettings->setValue( QStringLiteral( "/qgis/capitaliseLayerName" ), capitaliseCheckBox->isChecked() ); // Default simplify drawing configuration QgsVectorSimplifyMethod::SimplifyHints simplifyHints = QgsVectorSimplifyMethod::NoSimplification; @@ -1221,182 +1221,182 @@ void QgsOptions::saveOptions() simplifyHints |= QgsVectorSimplifyMethod::GeometrySimplification; if ( mSimplifyDrawingSpinBox->value() > 1 ) simplifyHints |= QgsVectorSimplifyMethod::AntialiasingSimplification; } - mSettings->setValue( "/qgis/simplifyDrawingHints", ( int ) simplifyHints ); - mSettings->setValue( "/qgis/simplifyAlgorithm", mSimplifyAlgorithmComboBox->currentData().toInt() ); - mSettings->setValue( "/qgis/simplifyDrawingTol", mSimplifyDrawingSpinBox->value() ); - mSettings->setValue( "/qgis/simplifyLocal", !mSimplifyDrawingAtProvider->isChecked() ); - mSettings->setValue( "/qgis/simplifyMaxScale", 1.0 / mSimplifyMaximumScaleComboBox->scale() ); + mSettings->setValue( QStringLiteral( "/qgis/simplifyDrawingHints" ), ( int ) simplifyHints ); + mSettings->setValue( QStringLiteral( "/qgis/simplifyAlgorithm" ), mSimplifyAlgorithmComboBox->currentData().toInt() ); + mSettings->setValue( QStringLiteral( "/qgis/simplifyDrawingTol" ), mSimplifyDrawingSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/simplifyLocal" ), !mSimplifyDrawingAtProvider->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/simplifyMaxScale" ), 1.0 / mSimplifyMaximumScaleComboBox->scale() ); // magnification - mSettings->setValue( "/qgis/magnifier_factor_default", doubleSpinBoxMagnifierDefault->value() / 100 ); + mSettings->setValue( QStringLiteral( "/qgis/magnifier_factor_default" ), doubleSpinBoxMagnifierDefault->value() / 100 ); //curve segmentation int segmentationType = mToleranceTypeComboBox->currentData().toInt(); - mSettings->setValue( "/qgis/segmentationToleranceType", segmentationType ); + mSettings->setValue( QStringLiteral( "/qgis/segmentationToleranceType" ), segmentationType ); double segmentationTolerance = mSegmentationToleranceSpinBox->value(); if ( segmentationType == 0 ) { segmentationTolerance = segmentationTolerance / 180.0 * M_PI; //user sets angle tolerance in degrees, internal classes need value in rad } - mSettings->setValue( "/qgis/segmentationTolerance", segmentationTolerance ); + mSettings->setValue( QStringLiteral( "/qgis/segmentationTolerance" ), segmentationTolerance ); // project - mSettings->setValue( "/qgis/projOpenAtLaunch", mProjectOnLaunchCmbBx->currentIndex() ); - mSettings->setValue( "/qgis/projOpenAtLaunchPath", mProjectOnLaunchLineEdit->text() ); + mSettings->setValue( QStringLiteral( "/qgis/projOpenAtLaunch" ), mProjectOnLaunchCmbBx->currentIndex() ); + mSettings->setValue( QStringLiteral( "/qgis/projOpenAtLaunchPath" ), mProjectOnLaunchLineEdit->text() ); - mSettings->setValue( "/qgis/askToSaveProjectChanges", chbAskToSaveProjectChanges->isChecked() ); - mSettings->setValue( "qgis/askToDeleteLayers", mLayerDeleteConfirmationChkBx->isChecked() ); - mSettings->setValue( "/qgis/warnOldProjectVersion", chbWarnOldProjectVersion->isChecked() ); - if (( mSettings->value( "/qgis/projectTemplateDir" ).toString() != leTemplateFolder->text() ) || - ( mSettings->value( "/qgis/newProjectDefault" ).toBool() != cbxProjectDefaultNew->isChecked() ) ) + mSettings->setValue( QStringLiteral( "/qgis/askToSaveProjectChanges" ), chbAskToSaveProjectChanges->isChecked() ); + mSettings->setValue( QStringLiteral( "qgis/askToDeleteLayers" ), mLayerDeleteConfirmationChkBx->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/warnOldProjectVersion" ), chbWarnOldProjectVersion->isChecked() ); + if (( mSettings->value( QStringLiteral( "/qgis/projectTemplateDir" ) ).toString() != leTemplateFolder->text() ) || + ( mSettings->value( QStringLiteral( "/qgis/newProjectDefault" ) ).toBool() != cbxProjectDefaultNew->isChecked() ) ) { - mSettings->setValue( "/qgis/newProjectDefault", cbxProjectDefaultNew->isChecked() ); - mSettings->setValue( "/qgis/projectTemplateDir", leTemplateFolder->text() ); + mSettings->setValue( QStringLiteral( "/qgis/newProjectDefault" ), cbxProjectDefaultNew->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/projectTemplateDir" ), leTemplateFolder->text() ); QgisApp::instance()->updateProjectFromTemplates(); } - mSettings->setValue( "/qgis/enableMacros", cmbEnableMacros->currentIndex() ); + mSettings->setValue( QStringLiteral( "/qgis/enableMacros" ), cmbEnableMacros->currentIndex() ); - mSettings->setValue( "/qgis/nullValue", leNullValue->text() ); - mSettings->setValue( "/qgis/style", cmbStyle->currentText() ); - mSettings->setValue( "/IconSize", cmbIconSize->currentText() ); + mSettings->setValue( QStringLiteral( "/qgis/nullValue" ), leNullValue->text() ); + mSettings->setValue( QStringLiteral( "/qgis/style" ), cmbStyle->currentText() ); + mSettings->setValue( QStringLiteral( "/IconSize" ), cmbIconSize->currentText() ); - mSettings->setValue( "/qgis/messageTimeout", mMessageTimeoutSpnBx->value() ); + mSettings->setValue( QStringLiteral( "/qgis/messageTimeout" ), mMessageTimeoutSpnBx->value() ); - mSettings->setValue( "/qgis/native_color_dialogs", mNativeColorDialogsChkBx->isChecked() ); - mSettings->setValue( "/qgis/live_color_dialogs", mLiveColorDialogsChkBx->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/native_color_dialogs" ), mNativeColorDialogsChkBx->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/live_color_dialogs" ), mLiveColorDialogsChkBx->isChecked() ); // rasters settings - mSettings->setValue( "/Raster/defaultRedBand", spnRed->value() ); - mSettings->setValue( "/Raster/defaultGreenBand", spnGreen->value() ); - mSettings->setValue( "/Raster/defaultBlueBand", spnBlue->value() ); + mSettings->setValue( QStringLiteral( "/Raster/defaultRedBand" ), spnRed->value() ); + mSettings->setValue( QStringLiteral( "/Raster/defaultGreenBand" ), spnGreen->value() ); + mSettings->setValue( QStringLiteral( "/Raster/defaultBlueBand" ), spnBlue->value() ); - saveContrastEnhancement( cboxContrastEnhancementAlgorithmSingleBand, "singleBand" ); - saveContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandSingleByte, "multiBandSingleByte" ); - saveContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandMultiByte, "multiBandMultiByte" ); + saveContrastEnhancement( cboxContrastEnhancementAlgorithmSingleBand, QStringLiteral( "singleBand" ) ); + saveContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandSingleByte, QStringLiteral( "multiBandSingleByte" ) ); + saveContrastEnhancement( cboxContrastEnhancementAlgorithmMultiBandMultiByte, QStringLiteral( "multiBandMultiByte" ) ); QString contrastEnhancementLimits = cboxContrastEnhancementLimits->currentData().toString(); - mSettings->setValue( "/Raster/defaultContrastEnhancementLimits", contrastEnhancementLimits ); + mSettings->setValue( QStringLiteral( "/Raster/defaultContrastEnhancementLimits" ), contrastEnhancementLimits ); - mSettings->setValue( "/Raster/defaultStandardDeviation", spnThreeBandStdDev->value() ); + mSettings->setValue( QStringLiteral( "/Raster/defaultStandardDeviation" ), spnThreeBandStdDev->value() ); - mSettings->setValue( "/Raster/cumulativeCutLower", mRasterCumulativeCutLowerDoubleSpinBox->value() / 100.0 ); - mSettings->setValue( "/Raster/cumulativeCutUpper", mRasterCumulativeCutUpperDoubleSpinBox->value() / 100.0 ); + mSettings->setValue( QStringLiteral( "/Raster/cumulativeCutLower" ), mRasterCumulativeCutLowerDoubleSpinBox->value() / 100.0 ); + mSettings->setValue( QStringLiteral( "/Raster/cumulativeCutUpper" ), mRasterCumulativeCutUpperDoubleSpinBox->value() / 100.0 ); // log rendering events, for userspace debugging - mSettings->setValue( "/Map/logCanvasRefreshEvent", mLogCanvasRefreshChkBx->isChecked() ); + mSettings->setValue( QStringLiteral( "/Map/logCanvasRefreshEvent" ), mLogCanvasRefreshChkBx->isChecked() ); //check behaviour so default projection when new layer is added with no //projection defined... if ( radPromptForProjection->isChecked() ) { - mSettings->setValue( "/Projections/defaultBehaviour", "prompt" ); + mSettings->setValue( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ); } else if ( radUseProjectProjection->isChecked() ) { - mSettings->setValue( "/Projections/defaultBehaviour", "useProject" ); + mSettings->setValue( QStringLiteral( "/Projections/defaultBehaviour" ), "useProject" ); } else //assumes radUseGlobalProjection is checked { - mSettings->setValue( "/Projections/defaultBehaviour", "useGlobal" ); + mSettings->setValue( QStringLiteral( "/Projections/defaultBehaviour" ), "useGlobal" ); } - mSettings->setValue( "/Projections/layerDefaultCrs", mLayerDefaultCrs.authid() ); + mSettings->setValue( QStringLiteral( "/Projections/layerDefaultCrs" ), mLayerDefaultCrs.authid() ); // save 'on the fly' CRS transformation settings - mSettings->setValue( "/Projections/otfTransformAutoEnable", radOtfAuto->isChecked() ); - mSettings->setValue( "/Projections/otfTransformEnabled", radOtfTransform->isChecked() ); - mSettings->setValue( "/Projections/projectDefaultCrs", mDefaultCrs.authid() ); + mSettings->setValue( QStringLiteral( "/Projections/otfTransformAutoEnable" ), radOtfAuto->isChecked() ); + mSettings->setValue( QStringLiteral( "/Projections/otfTransformEnabled" ), radOtfTransform->isChecked() ); + mSettings->setValue( QStringLiteral( "/Projections/projectDefaultCrs" ), mDefaultCrs.authid() ); - mSettings->setValue( "/Projections/showDatumTransformDialog", chkShowDatumTransformDialog->isChecked() ); + mSettings->setValue( QStringLiteral( "/Projections/showDatumTransformDialog" ), chkShowDatumTransformDialog->isChecked() ); //measurement settings QgsUnitTypes::DistanceUnit distanceUnit = static_cast< QgsUnitTypes::DistanceUnit >( mDistanceUnitsComboBox->currentData().toInt() ); - mSettings->setValue( "/qgis/measure/displayunits", QgsUnitTypes::encodeUnit( distanceUnit ) ); + mSettings->setValue( QStringLiteral( "/qgis/measure/displayunits" ), QgsUnitTypes::encodeUnit( distanceUnit ) ); QgsUnitTypes::AreaUnit areaUnit = static_cast< QgsUnitTypes::AreaUnit >( mAreaUnitsComboBox->currentData().toInt() ); - mSettings->setValue( "/qgis/measure/areaunits", QgsUnitTypes::encodeUnit( areaUnit ) ); + mSettings->setValue( QStringLiteral( "/qgis/measure/areaunits" ), QgsUnitTypes::encodeUnit( areaUnit ) ); QgsUnitTypes::AngleUnit angleUnit = static_cast< QgsUnitTypes::AngleUnit >( mAngleUnitsComboBox->currentData().toInt() ); - mSettings->setValue( "/qgis/measure/angleunits", QgsUnitTypes::encodeUnit( angleUnit ) ); + mSettings->setValue( QStringLiteral( "/qgis/measure/angleunits" ), QgsUnitTypes::encodeUnit( angleUnit ) ); int decimalPlaces = mDecimalPlacesSpinBox->value(); - mSettings->setValue( "/qgis/measure/decimalplaces", decimalPlaces ); + mSettings->setValue( QStringLiteral( "/qgis/measure/decimalplaces" ), decimalPlaces ); bool baseUnit = mKeepBaseUnitCheckBox->isChecked(); - mSettings->setValue( "/qgis/measure/keepbaseunit", baseUnit ); + mSettings->setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), baseUnit ); //set the color for selections QColor myColor = pbnSelectionColor->color(); - mSettings->setValue( "/qgis/default_selection_color_red", myColor.red() ); - mSettings->setValue( "/qgis/default_selection_color_green", myColor.green() ); - mSettings->setValue( "/qgis/default_selection_color_blue", myColor.blue() ); - mSettings->setValue( "/qgis/default_selection_color_alpha", myColor.alpha() ); + mSettings->setValue( QStringLiteral( "/qgis/default_selection_color_red" ), myColor.red() ); + mSettings->setValue( QStringLiteral( "/qgis/default_selection_color_green" ), myColor.green() ); + mSettings->setValue( QStringLiteral( "/qgis/default_selection_color_blue" ), myColor.blue() ); + mSettings->setValue( QStringLiteral( "/qgis/default_selection_color_alpha" ), myColor.alpha() ); //set the default color for canvas background myColor = pbnCanvasColor->color(); - mSettings->setValue( "/qgis/default_canvas_color_red", myColor.red() ); - mSettings->setValue( "/qgis/default_canvas_color_green", myColor.green() ); - mSettings->setValue( "/qgis/default_canvas_color_blue", myColor.blue() ); + mSettings->setValue( QStringLiteral( "/qgis/default_canvas_color_red" ), myColor.red() ); + mSettings->setValue( QStringLiteral( "/qgis/default_canvas_color_green" ), myColor.green() ); + mSettings->setValue( QStringLiteral( "/qgis/default_canvas_color_blue" ), myColor.blue() ); //set the default color for the measure tool myColor = pbnMeasureColor->color(); - mSettings->setValue( "/qgis/default_measure_color_red", myColor.red() ); - mSettings->setValue( "/qgis/default_measure_color_green", myColor.green() ); - mSettings->setValue( "/qgis/default_measure_color_blue", myColor.blue() ); + mSettings->setValue( QStringLiteral( "/qgis/default_measure_color_red" ), myColor.red() ); + mSettings->setValue( QStringLiteral( "/qgis/default_measure_color_green" ), myColor.green() ); + mSettings->setValue( QStringLiteral( "/qgis/default_measure_color_blue" ), myColor.blue() ); - mSettings->setValue( "/qgis/zoom_factor", spinZoomFactor->value() ); + mSettings->setValue( QStringLiteral( "/qgis/zoom_factor" ), spinZoomFactor->value() ); //digitizing - mSettings->setValue( "/qgis/digitizing/line_width", mLineWidthSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/line_width" ), mLineWidthSpinBox->value() ); QColor digitizingColor = mLineColorToolButton->color(); - mSettings->setValue( "/qgis/digitizing/line_color_red", digitizingColor.red() ); - mSettings->setValue( "/qgis/digitizing/line_color_green", digitizingColor.green() ); - mSettings->setValue( "/qgis/digitizing/line_color_blue", digitizingColor.blue() ); - mSettings->setValue( "/qgis/digitizing/line_color_alpha", digitizingColor.alpha() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/line_color_red" ), digitizingColor.red() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/line_color_green" ), digitizingColor.green() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/line_color_blue" ), digitizingColor.blue() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), digitizingColor.alpha() ); digitizingColor = mFillColorToolButton->color(); - mSettings->setValue( "/qgis/digitizing/fill_color_red", digitizingColor.red() ); - mSettings->setValue( "/qgis/digitizing/fill_color_green", digitizingColor.green() ); - mSettings->setValue( "/qgis/digitizing/fill_color_blue", digitizingColor.blue() ); - mSettings->setValue( "/qgis/digitizing/fill_color_alpha", digitizingColor.alpha() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/fill_color_red" ), digitizingColor.red() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/fill_color_green" ), digitizingColor.green() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/fill_color_blue" ), digitizingColor.blue() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/fill_color_alpha" ), digitizingColor.alpha() ); - settings.setValue( "/qgis/digitizing/line_ghost", mLineGhostCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/qgis/digitizing/line_ghost" ), mLineGhostCheckBox->isChecked() ); //default snap mode QString defaultSnapModeString = mDefaultSnapModeComboBox->currentData().toString(); - mSettings->setValue( "/qgis/digitizing/default_snap_mode", defaultSnapModeString ); - mSettings->setValue( "/qgis/digitizing/default_snapping_tolerance", mDefaultSnappingToleranceSpinBox->value() ); - mSettings->setValue( "/qgis/digitizing/search_radius_vertex_edit", mSearchRadiusVertexEditSpinBox->value() ); - mSettings->setValue( "/qgis/digitizing/default_snapping_tolerance_unit", + mSettings->setValue( QStringLiteral( "/qgis/digitizing/default_snap_mode" ), defaultSnapModeString ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), mDefaultSnappingToleranceSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit" ), mSearchRadiusVertexEditSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), ( mDefaultSnappingToleranceComboBox->currentIndex() == 0 ? QgsTolerance::ProjectUnits : QgsTolerance::Pixels ) ); - mSettings->setValue( "/qgis/digitizing/search_radius_vertex_edit_unit", + mSettings->setValue( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit_unit" ), ( mSearchRadiusVertexEditComboBox->currentIndex() == 0 ? QgsTolerance::ProjectUnits : QgsTolerance::Pixels ) ); - mSettings->setValue( "/qgis/digitizing/marker_only_for_selected", mMarkersOnlyForSelectedCheckBox->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/marker_only_for_selected" ), mMarkersOnlyForSelectedCheckBox->isChecked() ); QString markerComboText = mMarkerStyleComboBox->currentText(); if ( markerComboText == tr( "Semi transparent circle" ) ) { - mSettings->setValue( "/qgis/digitizing/marker_style", "SemiTransparentCircle" ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/marker_style" ), "SemiTransparentCircle" ); } else if ( markerComboText == tr( "Cross" ) ) { - mSettings->setValue( "/qgis/digitizing/marker_style", "Cross" ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/marker_style" ), "Cross" ); } else if ( markerComboText == tr( "None" ) ) { - mSettings->setValue( "/qgis/digitizing/marker_style", "None" ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/marker_style" ), "None" ); } - mSettings->setValue( "/qgis/digitizing/marker_size", ( mMarkerSizeSpinBox->value() ) ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/marker_size" ), ( mMarkerSizeSpinBox->value() ) ); - mSettings->setValue( "/qgis/digitizing/reuseLastValues", chkReuseLastValues->isChecked() ); - mSettings->setValue( "/qgis/digitizing/disable_enter_attribute_values_dialog", chkDisableAttributeValuesDlg->isChecked() ); - mSettings->setValue( "/qgis/digitizing/validate_geometries", mValidateGeometries->currentIndex() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/reuseLastValues" ), chkReuseLastValues->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/disable_enter_attribute_values_dialog" ), chkDisableAttributeValuesDlg->isChecked() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/validate_geometries" ), mValidateGeometries->currentIndex() ); - mSettings->setValue( "/qgis/digitizing/offset_join_style", mOffsetJoinStyleComboBox->currentData().toInt() ); - mSettings->setValue( "/qgis/digitizing/offset_quad_seg", mOffsetQuadSegSpinBox->value() ); - mSettings->setValue( "/qgis/digitizing/offset_miter_limit", mCurveOffsetMiterLimitComboBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/offset_join_style" ), mOffsetJoinStyleComboBox->currentData().toInt() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/offset_quad_seg" ), mOffsetQuadSegSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/qgis/digitizing/offset_miter_limit" ), mCurveOffsetMiterLimitComboBox->value() ); // default scale list myPaths.clear(); @@ -1408,7 +1408,7 @@ void QgsOptions::saveOptions() } myPaths += mListGlobalScales->item( i )->text(); } - mSettings->setValue( "Map/scales", myPaths ); + mSettings->setValue( QStringLiteral( "Map/scales" ), myPaths ); // // Color palette @@ -1424,39 +1424,39 @@ void QgsOptions::saveOptions() //default font QString composerFont = mComposerFontComboBox->currentFont().family(); - mSettings->setValue( "/Composer/defaultFont", composerFont ); + mSettings->setValue( QStringLiteral( "/Composer/defaultFont" ), composerFont ); //grid color - mSettings->setValue( "/Composer/gridRed", mGridColorButton->color().red() ); - mSettings->setValue( "/Composer/gridGreen", mGridColorButton->color().green() ); - mSettings->setValue( "/Composer/gridBlue", mGridColorButton->color().blue() ); - mSettings->setValue( "/Composer/gridAlpha", mGridColorButton->color().alpha() ); + mSettings->setValue( QStringLiteral( "/Composer/gridRed" ), mGridColorButton->color().red() ); + mSettings->setValue( QStringLiteral( "/Composer/gridGreen" ), mGridColorButton->color().green() ); + mSettings->setValue( QStringLiteral( "/Composer/gridBlue" ), mGridColorButton->color().blue() ); + mSettings->setValue( QStringLiteral( "/Composer/gridAlpha" ), mGridColorButton->color().alpha() ); //grid style if ( mGridStyleComboBox->currentText() == tr( "Solid" ) ) { - mSettings->setValue( "/Composer/gridStyle", "Solid" ); + mSettings->setValue( QStringLiteral( "/Composer/gridStyle" ), "Solid" ); } else if ( mGridStyleComboBox->currentText() == tr( "Dots" ) ) { - mSettings->setValue( "/Composer/gridStyle", "Dots" ); + mSettings->setValue( QStringLiteral( "/Composer/gridStyle" ), "Dots" ); } else if ( mGridStyleComboBox->currentText() == tr( "Crosses" ) ) { - mSettings->setValue( "/Composer/gridStyle", "Crosses" ); + mSettings->setValue( QStringLiteral( "/Composer/gridStyle" ), "Crosses" ); } //grid and guide defaults - mSettings->setValue( "/Composer/defaultSnapGridResolution", mGridResolutionSpinBox->value() ); - mSettings->setValue( "/Composer/defaultSnapTolerancePixels", mSnapToleranceSpinBox->value() ); - mSettings->setValue( "/Composer/defaultSnapGridOffsetX", mOffsetXSpinBox->value() ); - mSettings->setValue( "/Composer/defaultSnapGridOffsetY", mOffsetYSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/Composer/defaultSnapGridResolution" ), mGridResolutionSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/Composer/defaultSnapTolerancePixels" ), mSnapToleranceSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/Composer/defaultSnapGridOffsetX" ), mOffsetXSpinBox->value() ); + mSettings->setValue( QStringLiteral( "/Composer/defaultSnapGridOffsetY" ), mOffsetYSpinBox->value() ); // // Locale settings // - mSettings->setValue( "locale/userLocale", cboLocale->currentData().toString() ); - mSettings->setValue( "locale/overrideFlag", grpLocale->isChecked() ); + mSettings->setValue( QStringLiteral( "locale/userLocale" ), cboLocale->currentData().toString() ); + mSettings->setValue( QStringLiteral( "locale/overrideFlag" ), grpLocale->isChecked() ); // Gdal skip driver list if ( mLoadedGdalDriverList ) @@ -1506,15 +1506,15 @@ void QgsOptions::rejectOptions() void QgsOptions::on_spinFontSize_valueChanged( int fontSize ) { - mStyleSheetNewOpts.insert( "fontPointSize", QVariant( fontSize ) ); + mStyleSheetNewOpts.insert( QStringLiteral( "fontPointSize" ), QVariant( fontSize ) ); mStyleSheetBuilder->buildStyleSheet( mStyleSheetNewOpts ); } void QgsOptions::on_mFontFamilyRadioQt_released() { - if ( mStyleSheetNewOpts.value( "fontFamily" ).toString() != mStyleSheetBuilder->defaultFont().family() ) + if ( mStyleSheetNewOpts.value( QStringLiteral( "fontFamily" ) ).toString() != mStyleSheetBuilder->defaultFont().family() ) { - mStyleSheetNewOpts.insert( "fontFamily", QVariant( mStyleSheetBuilder->defaultFont().family() ) ); + mStyleSheetNewOpts.insert( QStringLiteral( "fontFamily" ), QVariant( mStyleSheetBuilder->defaultFont().family() ) ); mStyleSheetBuilder->buildStyleSheet( mStyleSheetNewOpts ); } } @@ -1523,7 +1523,7 @@ void QgsOptions::on_mFontFamilyRadioCustom_released() { if ( mFontFamilyComboBox->currentFont().family() != mStyleSheetBuilder->defaultFont().family() ) { - mStyleSheetNewOpts.insert( "fontFamily", QVariant( mFontFamilyComboBox->currentFont().family() ) ); + mStyleSheetNewOpts.insert( QStringLiteral( "fontFamily" ), QVariant( mFontFamilyComboBox->currentFont().family() ) ); mStyleSheetBuilder->buildStyleSheet( mStyleSheetNewOpts ); } } @@ -1531,16 +1531,16 @@ void QgsOptions::on_mFontFamilyRadioCustom_released() void QgsOptions::on_mFontFamilyComboBox_currentFontChanged( const QFont& font ) { if ( mFontFamilyRadioCustom->isChecked() - && mStyleSheetNewOpts.value( "fontFamily" ).toString() != font.family() ) + && mStyleSheetNewOpts.value( QStringLiteral( "fontFamily" ) ).toString() != font.family() ) { - mStyleSheetNewOpts.insert( "fontFamily", QVariant( font.family() ) ); + mStyleSheetNewOpts.insert( QStringLiteral( "fontFamily" ), QVariant( font.family() ) ); mStyleSheetBuilder->buildStyleSheet( mStyleSheetNewOpts ); } } void QgsOptions::on_mCustomGroupBoxChkBx_clicked( bool chkd ) { - mStyleSheetNewOpts.insert( "groupBoxCustom", QVariant( chkd ) ); + mStyleSheetNewOpts.insert( QStringLiteral( "groupBoxCustom" ), QVariant( chkd ) ); mStyleSheetBuilder->buildStyleSheet( mStyleSheetNewOpts ); } @@ -1571,7 +1571,7 @@ void QgsOptions::on_pbnEditCreateOptions_pressed() void QgsOptions::on_pbnEditPyramidsOptions_pressed() { - editGdalDriver( "_pyramids" ); + editGdalDriver( QStringLiteral( "_pyramids" ) ); } void QgsOptions::editGdalDriver( const QString& driverName ) @@ -1582,13 +1582,13 @@ void QgsOptions::editGdalDriver( const QString& driverName ) QgsDialog dlg( this, 0, QDialogButtonBox::Ok | QDialogButtonBox::Cancel ); QVBoxLayout *layout = dlg.layout(); QString title = tr( "Create Options - %1 Driver" ).arg( driverName ); - if ( driverName == "_pyramids" ) + if ( driverName == QLatin1String( "_pyramids" ) ) title = tr( "Create Options - pyramids" ); dlg.setWindowTitle( title ); - if ( driverName == "_pyramids" ) + if ( driverName == QLatin1String( "_pyramids" ) ) { QgsRasterPyramidsOptionsWidget* optionsWidget = - new QgsRasterPyramidsOptionsWidget( &dlg, "gdal" ); + new QgsRasterPyramidsOptionsWidget( &dlg, QStringLiteral( "gdal" ) ); layout->addWidget( optionsWidget ); dlg.resize( 400, 400 ); if ( dlg.exec() == QDialog::Accepted ) @@ -1598,7 +1598,7 @@ void QgsOptions::editGdalDriver( const QString& driverName ) { QgsRasterFormatSaveOptionsWidget* optionsWidget = new QgsRasterFormatSaveOptionsWidget( &dlg, driverName, - QgsRasterFormatSaveOptionsWidget::Full, "gdal" ); + QgsRasterFormatSaveOptionsWidget::Full, QStringLiteral( "gdal" ) ); layout->addWidget( optionsWidget ); if ( dlg.exec() == QDialog::Accepted ) optionsWidget->apply(); @@ -1616,9 +1616,9 @@ bool QgsOptions::newVisible() QStringList QgsOptions::i18nList() { QStringList myList; - myList << "en_US"; //there is no qm file for this so we add it manually + myList << QStringLiteral( "en_US" ); //there is no qm file for this so we add it manually QString myI18nPath = QgsApplication::i18nPath(); - QDir myDir( myI18nPath, "qgis*.qm" ); + QDir myDir( myI18nPath, QStringLiteral( "qgis*.qm" ) ); QStringList myFileList = myDir.entryList(); QStringListIterator myIterator( myFileList ); while ( myIterator.hasNext() ) @@ -1626,9 +1626,9 @@ QStringList QgsOptions::i18nList() QString myFileName = myIterator.next(); // Ignore the 'en' translation file, already added as 'en_US'. - if ( myFileName.compare( "qgis_en.qm" ) == 0 ) continue; + if ( myFileName.compare( QLatin1String( "qgis_en.qm" ) ) == 0 ) continue; - myList << myFileName.remove( "qgis_" ).remove( ".qm" ); + myList << myFileName.remove( QStringLiteral( "qgis_" ) ).remove( QStringLiteral( ".qm" ) ); } return myList; } @@ -1638,7 +1638,7 @@ void QgsOptions::on_mRestoreDefaultWindowStateBtn_clicked() // richard if ( QMessageBox::warning( this, tr( "Restore UI defaults" ), tr( "Are you sure to reset the UI to default (needs restart)?" ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel ) return; - mSettings->setValue( "/qgis/restoreDefaultWindowState", true ); + mSettings->setValue( QStringLiteral( "/qgis/restoreDefaultWindowState" ), true ); } void QgsOptions::on_mCustomVariablesChkBx_toggled( bool chkd ) @@ -1701,7 +1701,7 @@ void QgsOptions::on_mCurrentVariablesQGISChxBx_toggled( bool qgisSpecific ) if ( qgisSpecific ) { QString itmTxt = mCurrentVariablesTable->item( i, 0 )->text(); - if ( !itmTxt.startsWith( "QGIS", Qt::CaseInsensitive ) ) + if ( !itmTxt.startsWith( QLatin1String( "QGIS" ), Qt::CaseInsensitive ) ) mCurrentVariablesTable->hideRow( i ); } else @@ -1805,7 +1805,7 @@ void QgsOptions::on_mBtnRemoveSVGPath_clicked() void QgsOptions::on_mAddUrlPushButton_clicked() { QListWidgetItem* newItem = new QListWidgetItem( mExcludeUrlListWidget ); - newItem->setText( "URL" ); + newItem->setText( QStringLiteral( "URL" ) ); newItem->setFlags( Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable ); mExcludeUrlListWidget->addItem( newItem ); mExcludeUrlListWidget->setCurrentItem( newItem ); @@ -1843,7 +1843,7 @@ void QgsOptions::on_mOptionsStackedWidget_currentChanged( int theIndx ) { Q_UNUSED( theIndx ); // load gdal driver list when gdal tab is first opened - if ( mOptionsStackedWidget->currentWidget()->objectName() == "mOptionsPageGDAL" + if ( mOptionsStackedWidget->currentWidget()->objectName() == QLatin1String( "mOptionsPageGDAL" ) && ! mLoadedGdalDriverList ) { loadGdalDriverList(); @@ -1909,7 +1909,7 @@ void QgsOptions::loadGdalDriverList() pszVirtualIO = "v"; else pszVirtualIO = ""; - myDriversFlags[myGdalDriverDescription] = QString( "%1%2" ).arg( pszRWFlag, pszVirtualIO ); + myDriversFlags[myGdalDriverDescription] = QStringLiteral( "%1%2" ).arg( pszRWFlag, pszVirtualIO ); // get driver extensions and long name // the gdal provider can override/add extensions but there is no interface to query this @@ -1919,7 +1919,7 @@ void QgsOptions::loadGdalDriverList() } // restore GDAL_SKIP just in case - CPLSetConfigOption( "GDAL_SKIP", mySkippedDrivers.join( " " ).toUtf8() ); + CPLSetConfigOption( "GDAL_SKIP", mySkippedDrivers.join( QStringLiteral( " " ) ).toUtf8() ); myDrivers.removeDuplicates(); // myDrivers.sort(); @@ -1960,8 +1960,8 @@ void QgsOptions::loadGdalDriverList() Q_FOREACH ( const QString& str, myGdalWriteDrivers ) strMap.insert( str.toLower(), str ); myGdalWriteDrivers = strMap.values(); - myGdalWriteDrivers.removeAll( "Gtiff" ); - myGdalWriteDrivers.prepend( "GTiff" ); + myGdalWriteDrivers.removeAll( QStringLiteral( "Gtiff" ) ); + myGdalWriteDrivers.prepend( QStringLiteral( "GTiff" ) ); cmbEditCreateOptions->clear(); Q_FOREACH ( const QString& myName, myGdalWriteDrivers ) { @@ -1984,7 +1984,7 @@ void QgsOptions::saveGdalDriverList() QgsApplication::restoreGdalDriver( mypItem->text( 0 ) ); } } - mSettings->setValue( "gdal/skipList", QgsApplication::skippedGdalDrivers().join( " " ) ); + mSettings->setValue( QStringLiteral( "gdal/skipList" ), QgsApplication::skippedGdalDrivers().join( QStringLiteral( " " ) ) ); } void QgsOptions::on_pbnAddScale_clicked() @@ -1999,7 +1999,7 @@ void QgsOptions::on_pbnAddScale_clicked() if ( myScale != -1 ) { - QListWidgetItem* newItem = addScaleToScaleList( QString( "1:%1" ).arg( myScale ) ); + QListWidgetItem* newItem = addScaleToScaleList( QStringLiteral( "1:%1" ).arg( myScale ) ); mListGlobalScales->setCurrentItem( newItem ); } } @@ -2054,9 +2054,9 @@ void QgsOptions::on_pbnExportScales_clicked() } // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } QStringList myScales; @@ -2110,10 +2110,10 @@ void QgsOptions::on_mRemoveDefaultTransformButton_clicked() void QgsOptions::on_mAddDefaultTransformButton_clicked() { QTreeWidgetItem* item = new QTreeWidgetItem(); - item->setText( 0, "" ); - item->setText( 1, "" ); - item->setText( 2, "" ); - item->setText( 3, "" ); + item->setText( 0, QLatin1String( "" ) ); + item->setText( 1, QLatin1String( "" ) ); + item->setText( 2, QLatin1String( "" ) ); + item->setText( 3, QLatin1String( "" ) ); item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable ); mDefaultDatumTransformTreeWidget->addTopLevelItem( item ); } @@ -2121,12 +2121,12 @@ void QgsOptions::on_mAddDefaultTransformButton_clicked() void QgsOptions::saveDefaultDatumTransformations() { QSettings s; - s.beginGroup( "/Projections" ); + s.beginGroup( QStringLiteral( "/Projections" ) ); QStringList groupKeys = s.allKeys(); QStringList::const_iterator groupKeyIt = groupKeys.constBegin(); for ( ; groupKeyIt != groupKeys.constEnd(); ++groupKeyIt ) { - if ( groupKeyIt->contains( "srcTransform" ) || groupKeyIt->contains( "destTransform" ) ) + if ( groupKeyIt->contains( QLatin1String( "srcTransform" ) ) || groupKeyIt->contains( QLatin1String( "destTransform" ) ) ) { s.remove( *groupKeyIt ); } @@ -2185,11 +2185,11 @@ void QgsOptions::addScaleToScaleList( QListWidgetItem* newItem ) QListWidgetItem* duplicateItem = mListGlobalScales->findItems( newItem->text(), Qt::MatchExactly ).value( 0 ); delete duplicateItem; - int newDenominator = newItem->text().split( ":" ).value( 1 ).toInt(); + int newDenominator = newItem->text().split( QStringLiteral( ":" ) ).value( 1 ).toInt(); int i; for ( i = 0; i < mListGlobalScales->count(); i++ ) { - int denominator = mListGlobalScales->item( i )->text().split( ":" ).value( 1 ).toInt(); + int denominator = mListGlobalScales->item( i )->text().split( QStringLiteral( ":" ) ).value( 1 ).toInt(); if ( newDenominator > denominator ) break; } @@ -2206,8 +2206,8 @@ void QgsOptions::scaleItemChanged( QListWidgetItem* changedScaleItem ) if ( regExp.exactMatch( changedScaleItem->text() ) ) { //Remove leading zeroes from the denominator - regExp.setPattern( "1:0*" ); - changedScaleItem->setText( changedScaleItem->text().replace( regExp, "1:" ) ); + regExp.setPattern( QStringLiteral( "1:0*" ) ); + changedScaleItem->setText( changedScaleItem->text().replace( regExp, QStringLiteral( "1:" ) ) ); } else { diff --git a/src/app/qgspluginregistry.cpp b/src/app/qgspluginregistry.cpp index b2454a6aa9b1..ba7bcf4e22d3 100644 --- a/src/app/qgspluginregistry.cpp +++ b/src/app/qgspluginregistry.cpp @@ -210,7 +210,7 @@ bool QgsPluginRegistry::checkQgisVersion( const QString& minVersion, const QStri // Parse qgisMaxVersion. Must be in form x.y.z or just x.y int maxVerMajor, maxVerMinor, maxVerBugfix = 99; - if ( maxVersion.isEmpty() || maxVersion == "__error__" ) + if ( maxVersion.isEmpty() || maxVersion == QLatin1String( "__error__" ) ) { maxVerMajor = minVerMajor; maxVerMinor = 99; @@ -246,13 +246,13 @@ bool QgsPluginRegistry::checkQgisVersion( const QString& minVersion, const QStri int qgisBugfix = qgisVersionParts.at( 2 ).toInt(); // build XxYyZz strings with trailing zeroes if needed - QString minVer = QString( "%1%2%3" ).arg( minVerMajor, 2, 10, QChar( '0' ) ) + QString minVer = QStringLiteral( "%1%2%3" ).arg( minVerMajor, 2, 10, QChar( '0' ) ) .arg( minVerMinor, 2, 10, QChar( '0' ) ) .arg( minVerBugfix, 2, 10, QChar( '0' ) ); - QString maxVer = QString( "%1%2%3" ).arg( maxVerMajor, 2, 10, QChar( '0' ) ) + QString maxVer = QStringLiteral( "%1%2%3" ).arg( maxVerMajor, 2, 10, QChar( '0' ) ) .arg( maxVerMinor, 2, 10, QChar( '0' ) ) .arg( maxVerBugfix, 2, 10, QChar( '0' ) ); - QString curVer = QString( "%1%2%3" ).arg( qgisMajor, 2, 10, QChar( '0' ) ) + QString curVer = QStringLiteral( "%1%2%3" ).arg( qgisMajor, 2, 10, QChar( '0' ) ) .arg( qgisMinor, 2, 10, QChar( '0' ) ) .arg( qgisBugfix, 2, 10, QChar( '0' ) ); @@ -288,7 +288,7 @@ void QgsPluginRegistry::loadPythonPlugin( const QString& packageName ) // TODO: test success - QString pluginName = mPythonUtils->getPluginMetadata( packageName, "name" ); + QString pluginName = mPythonUtils->getPluginMetadata( packageName, QStringLiteral( "name" ) ); // add to settings settings.setValue( "/PythonPlugins/" + packageName, true ); @@ -359,7 +359,7 @@ void QgsPluginRegistry::loadCppPlugin( const QString& theFullPathName ) baseName = baseName.mid( 3 ); #endif QgsDebugMsg( QString( "object name to %1" ).arg( baseName ) ); - o->setObjectName( QString( "qgis_plugin_%1" ).arg( baseName ) ); + o->setObjectName( QStringLiteral( "qgis_plugin_%1" ).arg( baseName ) ); QgsDebugMsg( QString( "plugin object name now: %1" ).arg( o->objectName() ) ); } @@ -460,7 +460,7 @@ void QgsPluginRegistry::restoreSessionPlugins( const QString& thePluginDirString #elif ANDROID QString pluginExt = "*plugin.so"; #else - QString pluginExt = "*.so*"; + QString pluginExt = QStringLiteral( "*.so*" ); #endif // check all libs in the current plugin directory and get name and descriptions @@ -474,16 +474,16 @@ void QgsPluginRegistry::restoreSessionPlugins( const QString& thePluginDirString // check if the plugin was active on last session QString baseName = QFileInfo( myFullPath ).baseName(); - if ( mySettings.value( QString( "/Plugins/watchDog/%1" ).arg( baseName ) ).isValid() ) + if ( mySettings.value( QStringLiteral( "/Plugins/watchDog/%1" ).arg( baseName ) ).isValid() ) { mQgisInterface->messageBar()->pushWarning( QObject::tr( "Plugin %1" ).arg( baseName ), QObject::tr( "The plugin will be disabled because it crashed QGIS during last startup. Please report an issue and re-enable the plugin when the problem has been solved." ) ); mySettings.setValue( "/Plugins/" + baseName, false ); } if ( mySettings.value( "/Plugins/" + baseName ).toBool() ) { - mySettings.setValue( QString( "/Plugins/watchDog/%1" ).arg( baseName ), true ); + mySettings.setValue( QStringLiteral( "/Plugins/watchDog/%1" ).arg( baseName ), true ); loadCppPlugin( myFullPath ); - mySettings.remove( QString( "/Plugins/watchDog/%1" ).arg( baseName ) ); + mySettings.remove( QStringLiteral( "/Plugins/watchDog/%1" ).arg( baseName ) ); } } } @@ -495,10 +495,10 @@ void QgsPluginRegistry::restoreSessionPlugins( const QString& thePluginDirString QgsDebugMsg( "Loading python plugins" ); QStringList corePlugins = QStringList(); - corePlugins << "GdalTools"; - corePlugins << "db_manager"; - corePlugins << "processing"; - corePlugins << "MetaSearch"; + corePlugins << QStringLiteral( "GdalTools" ); + corePlugins << QStringLiteral( "db_manager" ); + corePlugins << QStringLiteral( "processing" ); + corePlugins << QStringLiteral( "MetaSearch" ); // make the required core plugins enabled by default: Q_FOREACH ( const QString& corePlugin, corePlugins ) @@ -585,13 +585,13 @@ bool QgsPluginRegistry::checkPythonPlugin( const QString& packageName ) // get information from the plugin // if there are some problems, don't continue with metadata retreival - pluginName = mPythonUtils->getPluginMetadata( packageName, "name" ); - description = mPythonUtils->getPluginMetadata( packageName, "description" ); - version = mPythonUtils->getPluginMetadata( packageName, "version" ); + pluginName = mPythonUtils->getPluginMetadata( packageName, QStringLiteral( "name" ) ); + description = mPythonUtils->getPluginMetadata( packageName, QStringLiteral( "description" ) ); + version = mPythonUtils->getPluginMetadata( packageName, QStringLiteral( "version" ) ); // for Python plugins category still optional, by default used "Plugins" category //category = mPythonUtils->getPluginMetadata( packageName, "category" ); - if ( pluginName == "__error__" || description == "__error__" || version == "__error__" ) + if ( pluginName == QLatin1String( "__error__" ) || description == QLatin1String( "__error__" ) || version == QLatin1String( "__error__" ) ) { QgsMessageLog::logMessage( QObject::tr( "Error when reading metadata of plugin %1" ).arg( packageName ), QObject::tr( "Plugins" ) ); @@ -603,10 +603,10 @@ bool QgsPluginRegistry::checkPythonPlugin( const QString& packageName ) bool QgsPluginRegistry::isPythonPluginCompatible( const QString& packageName ) const { - QString minVersion = mPythonUtils->getPluginMetadata( packageName, "qgisMinimumVersion" ); + QString minVersion = mPythonUtils->getPluginMetadata( packageName, QStringLiteral( "qgisMinimumVersion" ) ); // try to read qgisMaximumVersion. Note checkQgisVersion can cope with "__error__" value. - QString maxVersion = mPythonUtils->getPluginMetadata( packageName, "qgisMaximumVersion" ); - return minVersion != "__error__" && checkQgisVersion( minVersion, maxVersion ); + QString maxVersion = mPythonUtils->getPluginMetadata( packageName, QStringLiteral( "qgisMaximumVersion" ) ); + return minVersion != QLatin1String( "__error__" ) && checkQgisVersion( minVersion, maxVersion ); } QList QgsPluginRegistry::pluginData() diff --git a/src/app/qgspluginregistry.h b/src/app/qgspluginregistry.h index 7403e8b60371..e5565573511a 100644 --- a/src/app/qgspluginregistry.h +++ b/src/app/qgspluginregistry.h @@ -104,7 +104,7 @@ class APP_EXPORT QgsPluginRegistry //! Check current QGIS version against requested minimal and optionally maximal QGIS version //! if maxVersion not specified, the default value is assumed: floor(minVersion) + 0.99.99 - bool checkQgisVersion( const QString& minVersion, const QString& maxVersion = "" ) const; + bool checkQgisVersion( const QString& minVersion, const QString& maxVersion = QLatin1String( "" ) ) const; private: static QgsPluginRegistry* _instance; diff --git a/src/app/qgspointrotationitem.cpp b/src/app/qgspointrotationitem.cpp index 5b3dd93d4c9b..e0cf0d8abee7 100644 --- a/src/app/qgspointrotationitem.cpp +++ b/src/app/qgspointrotationitem.cpp @@ -96,7 +96,7 @@ void QgsPointRotationItem::setSymbol( const QImage& symbolImage ) p.drawLine( halfItemWidth, 0, mPixmap.width() * 0.75, quarterItemHeight ); //set item size - mItemSize.setWidth( mPixmap.width() + fm.width( "360" ) ); + mItemSize.setWidth( mPixmap.width() + fm.width( QStringLiteral( "360" ) ) ); double pixmapHeight = mPixmap.height(); double fontHeight = fm.height(); if ( pixmapHeight >= fontHeight ) diff --git a/src/app/qgsprojectlayergroupdialog.cpp b/src/app/qgsprojectlayergroupdialog.cpp index 9e44619decfe..efa4c922ed0d 100644 --- a/src/app/qgsprojectlayergroupdialog.cpp +++ b/src/app/qgsprojectlayergroupdialog.cpp @@ -35,7 +35,7 @@ QgsProjectLayerGroupDialog::QgsProjectLayerGroupDialog( QWidget * parent, const setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/EmbedLayer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/EmbedLayer/geometry" ) ).toByteArray() ); if ( !projectFile.isEmpty() ) { @@ -53,7 +53,7 @@ QgsProjectLayerGroupDialog::QgsProjectLayerGroupDialog( QWidget * parent, const QgsProjectLayerGroupDialog::~QgsProjectLayerGroupDialog() { QSettings settings; - settings.setValue( "/Windows/EmbedLayer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/EmbedLayer/geometry" ), saveGeometry() ); delete mRootGroup; } @@ -115,7 +115,7 @@ void QgsProjectLayerGroupDialog::on_mBrowseFileToolButton_clicked() QSettings s; QString projectFile = QFileDialog::getOpenFileName( this, tr( "Select project file" ), - s.value( "/qgis/last_embedded_project_path", QDir::homePath() ).toString(), + s.value( QStringLiteral( "/qgis/last_embedded_project_path" ), QDir::homePath() ).toString(), tr( "QGIS files" ) + " (*.qgs *.QGS)" ); if ( !projectFile.isEmpty() ) { @@ -165,14 +165,14 @@ void QgsProjectLayerGroupDialog::changeProjectFile() mRootGroup->removeAllChildren(); - QDomElement layerTreeElem = projectDom.documentElement().firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = projectDom.documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) ); if ( !layerTreeElem.isNull() ) { mRootGroup->readChildrenFromXml( layerTreeElem ); } else { - QgsLayerTreeUtils::readOldLegend( mRootGroup, projectDom.documentElement().firstChildElement( "legend" ) ); + QgsLayerTreeUtils::readOldLegend( mRootGroup, projectDom.documentElement().firstChildElement( QStringLiteral( "legend" ) ) ); } if ( !mShowEmbeddedContent ) @@ -192,7 +192,7 @@ void QgsProjectLayerGroupDialog::removeEmbeddedNodes( QgsLayerTreeGroup* node ) QList childrenToRemove; Q_FOREACH ( QgsLayerTreeNode* child, node->children() ) { - if ( child->customProperty( "embedded" ).toInt() ) + if ( child->customProperty( QStringLiteral( "embedded" ) ).toInt() ) childrenToRemove << child; else if ( QgsLayerTree::isGroup( child ) ) removeEmbeddedNodes( QgsLayerTree::toGroup( child ) ); @@ -230,7 +230,7 @@ void QgsProjectLayerGroupDialog::on_mButtonBox_accepted() QFileInfo fi( mProjectPath ); if ( fi.exists() ) { - s.setValue( "/qgis/last_embedded_project_path", fi.absolutePath() ); + s.setValue( QStringLiteral( "/qgis/last_embedded_project_path" ), fi.absolutePath() ); } accept(); } diff --git a/src/app/qgsprojectproperties.cpp b/src/app/qgsprojectproperties.cpp index c3265b2e7c1a..697c4832f43b 100644 --- a/src/app/qgsprojectproperties.cpp +++ b/src/app/qgsprojectproperties.cpp @@ -68,7 +68,7 @@ const char * QgsProjectProperties::GEO_NONE_DESC = QT_TRANSLATE_NOOP( "QgsOption //stdc++ includes QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *parent, Qt::WindowFlags fl ) - : QgsOptionsDialogBase( "ProjectProperties", parent, fl ) + : QgsOptionsDialogBase( QStringLiteral( "ProjectProperties" ), parent, fl ) , mMapCanvas( mapCanvas ) , mEllipsoidList() , mEllipsoidIndex( 0 ) @@ -155,7 +155,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa // get the manner in which the number of decimal places in the mouse // position display is set (manual or automatic) - bool automaticPrecision = QgsProject::instance()->readBoolEntry( "PositionPrecision", "/Automatic", true ); + bool automaticPrecision = QgsProject::instance()->readBoolEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/Automatic" ), true ); if ( automaticPrecision ) { radAutomatic->setChecked( true ); @@ -168,22 +168,22 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa spinBoxDP->setEnabled( true ); labelDP->setEnabled( true ); } - int dp = QgsProject::instance()->readNumEntry( "PositionPrecision", "/DecimalPlaces" ); + int dp = QgsProject::instance()->readNumEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DecimalPlaces" ) ); spinBoxDP->setValue( dp ); - cbxAbsolutePath->setCurrentIndex( QgsProject::instance()->readBoolEntry( "Paths", "/Absolute", true ) ? 0 : 1 ); + cbxAbsolutePath->setCurrentIndex( QgsProject::instance()->readBoolEntry( QStringLiteral( "Paths" ), QStringLiteral( "/Absolute" ), true ) ? 0 : 1 ); // populate combo box with ellipsoids // selection of the ellipsoid from settings is defferred to a later point, because it would // be overridden in the meanwhile by the projection selector populateEllipsoidList(); - QString format = QgsProject::instance()->readEntry( "PositionPrecision", "/DegreeFormat", "MU" ); - if ( format == "MU" ) + QString format = QgsProject::instance()->readEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DegreeFormat" ), QStringLiteral( "MU" ) ); + if ( format == QLatin1String( "MU" ) ) mCoordinateDisplayComboBox->setCurrentIndex( mCoordinateDisplayComboBox->findData( MapUnits ) ); - else if ( format == "DM" ) + else if ( format == QLatin1String( "DM" ) ) mCoordinateDisplayComboBox->setCurrentIndex( mCoordinateDisplayComboBox->findData( DegreesMinutes ) ); - else if ( format == "DMS" ) + else if ( format == QLatin1String( "DMS" ) ) mCoordinateDisplayComboBox->setCurrentIndex( mCoordinateDisplayComboBox->findData( DegreesMinutesSeconds ) ); else mCoordinateDisplayComboBox->setCurrentIndex( mCoordinateDisplayComboBox->findData( DecimalDegrees ) ); @@ -192,38 +192,38 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa mAreaUnitsCombo->setCurrentIndex( mAreaUnitsCombo->findData( QgsProject::instance()->areaUnits() ) ); //get the color selections and set the button color accordingly - int myRedInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorRedPart", 255 ); - int myGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorGreenPart", 255 ); - int myBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorBluePart", 0 ); - int myAlphaInt = QgsProject::instance()->readNumEntry( "Gui", "/SelectionColorAlphaPart", 255 ); + int myRedInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorRedPart" ), 255 ); + int myGreenInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorGreenPart" ), 255 ); + int myBlueInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorBluePart" ), 0 ); + int myAlphaInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorAlphaPart" ), 255 ); QColor myColor = QColor( myRedInt, myGreenInt, myBlueInt, myAlphaInt ); - myRedInt = settings.value( "/qgis/default_selection_color_red", 255 ).toInt(); - myGreenInt = settings.value( "/qgis/default_selection_color_green", 255 ).toInt(); - myBlueInt = settings.value( "/qgis/default_selection_color_blue", 0 ).toInt(); - myAlphaInt = settings.value( "/qgis/default_selection_color_alpha", 255 ).toInt(); + myRedInt = settings.value( QStringLiteral( "/qgis/default_selection_color_red" ), 255 ).toInt(); + myGreenInt = settings.value( QStringLiteral( "/qgis/default_selection_color_green" ), 255 ).toInt(); + myBlueInt = settings.value( QStringLiteral( "/qgis/default_selection_color_blue" ), 0 ).toInt(); + myAlphaInt = settings.value( QStringLiteral( "/qgis/default_selection_color_alpha" ), 255 ).toInt(); QColor defaultSelectionColor = QColor( myRedInt, myGreenInt, myBlueInt, myAlphaInt ); - pbnSelectionColor->setContext( "gui" ); + pbnSelectionColor->setContext( QStringLiteral( "gui" ) ); pbnSelectionColor->setColor( myColor ); pbnSelectionColor->setDefaultColor( defaultSelectionColor ); pbnSelectionColor->setColorDialogTitle( tr( "Selection color" ) ); pbnSelectionColor->setAllowAlpha( true ); //get the color for map canvas background and set button color accordingly (default white) - myRedInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorRedPart", 255 ); - myGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorGreenPart", 255 ); - myBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorBluePart", 255 ); + myRedInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorRedPart" ), 255 ); + myGreenInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorGreenPart" ), 255 ); + myBlueInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorBluePart" ), 255 ); myColor = QColor( myRedInt, myGreenInt, myBlueInt ); - myRedInt = settings.value( "/qgis/default_canvas_color_red", 255 ).toInt(); - myGreenInt = settings.value( "/qgis/default_canvas_color_green", 255 ).toInt(); - myBlueInt = settings.value( "/qgis/default_canvas_color_blue", 255 ).toInt(); + myRedInt = settings.value( QStringLiteral( "/qgis/default_canvas_color_red" ), 255 ).toInt(); + myGreenInt = settings.value( QStringLiteral( "/qgis/default_canvas_color_green" ), 255 ).toInt(); + myBlueInt = settings.value( QStringLiteral( "/qgis/default_canvas_color_blue" ), 255 ).toInt(); QColor defaultCanvasColor = QColor( myRedInt, myGreenInt, myBlueInt ); - pbnCanvasColor->setContext( "gui" ); + pbnCanvasColor->setContext( QStringLiteral( "gui" ) ); pbnCanvasColor->setColor( myColor ); pbnCanvasColor->setDefaultColor( defaultCanvasColor ); //get project scales - QStringList myScales = QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ); + QStringList myScales = QgsProject::instance()->readListEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ) ); if ( !myScales.isEmpty() ) { Q_FOREACH ( const QString& scale, myScales ) @@ -233,7 +233,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa } connect( lstScales, SIGNAL( itemChanged( QListWidgetItem* ) ), this, SLOT( scaleItemChanged( QListWidgetItem* ) ) ); - grpProjectScales->setChecked( QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ) ); + grpProjectScales->setChecked( QgsProject::instance()->readBoolEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ) ) ); QgsMapLayer* currentLayer = nullptr; @@ -285,7 +285,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa { QgsRasterLayer *rl = qobject_cast( currentLayer ); - if ( rl && rl->providerType() == "wms" ) + if ( rl && rl->providerType() == QLatin1String( "wms" ) ) { type = tr( "WMS" ); } @@ -314,25 +314,25 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa twIdentifyLayers->setItem( i, 3, twi ); } - grpOWSServiceCapabilities->setChecked( QgsProject::instance()->readBoolEntry( "WMSServiceCapabilities", "/", false ) ); - mWMSTitle->setText( QgsProject::instance()->readEntry( "WMSServiceTitle", "/" ) ); - mWMSName->setText( QgsProject::instance()->readEntry( "WMSRootName", "/" ) ); - mWMSContactOrganization->setText( QgsProject::instance()->readEntry( "WMSContactOrganization", "/", "" ) ); - mWMSContactPerson->setText( QgsProject::instance()->readEntry( "WMSContactPerson", "/", "" ) ); - mWMSContactMail->setText( QgsProject::instance()->readEntry( "WMSContactMail", "/", "" ) ); - mWMSContactPhone->setText( QgsProject::instance()->readEntry( "WMSContactPhone", "/", "" ) ); - mWMSAbstract->setPlainText( QgsProject::instance()->readEntry( "WMSServiceAbstract", "/", "" ) ); - mWMSOnlineResourceLineEdit->setText( QgsProject::instance()->readEntry( "WMSOnlineResource", "/", "" ) ); - mWMSUrlLineEdit->setText( QgsProject::instance()->readEntry( "WMSUrl", "/", "" ) ); - mWMSKeywordList->setText( QgsProject::instance()->readListEntry( "WMSKeywordList", "/" ).join( ", " ) ); + grpOWSServiceCapabilities->setChecked( QgsProject::instance()->readBoolEntry( QStringLiteral( "WMSServiceCapabilities" ), QStringLiteral( "/" ), false ) ); + mWMSTitle->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSServiceTitle" ), QStringLiteral( "/" ) ) ); + mWMSName->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSRootName" ), QStringLiteral( "/" ) ) ); + mWMSContactOrganization->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSContactOrganization" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSContactPerson->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSContactPerson" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSContactMail->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSContactMail" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSContactPhone->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSContactPhone" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSAbstract->setPlainText( QgsProject::instance()->readEntry( QStringLiteral( "WMSServiceAbstract" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSOnlineResourceLineEdit->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSOnlineResource" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSUrlLineEdit->setText( QgsProject::instance()->readEntry( QStringLiteral( "WMSUrl" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + mWMSKeywordList->setText( QgsProject::instance()->readListEntry( QStringLiteral( "WMSKeywordList" ), QStringLiteral( "/" ) ).join( QStringLiteral( ", " ) ) ); // WMS Name validator QValidator *shortNameValidator = new QRegExpValidator( QgsApplication::shortNameRegExp(), this ); mWMSName->setValidator( shortNameValidator ); // WMS Contact Position - QString contactPositionText = QgsProject::instance()->readEntry( "WMSContactPosition", "/", "" ); - mWMSContactPositionCb->addItem( "" ); + QString contactPositionText = QgsProject::instance()->readEntry( QStringLiteral( "WMSContactPosition" ), QStringLiteral( "/" ), QLatin1String( "" ) ); + mWMSContactPositionCb->addItem( QLatin1String( "" ) ); mWMSContactPositionCb->addItem( tr( "Custodian" ), "custodian" ); mWMSContactPositionCb->addItem( tr( "Owner" ), "owner" ); mWMSContactPositionCb->addItem( tr( "User" ), "user" ); @@ -354,7 +354,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa } // WMS Fees - QString feesText = QgsProject::instance()->readEntry( "WMSFees", "/", "" ); + QString feesText = QgsProject::instance()->readEntry( QStringLiteral( "WMSFees" ), QStringLiteral( "/" ), QLatin1String( "" ) ); mWMSFeesCb->addItem( tr( "Conditions unknown" ), "conditions unknown" ); mWMSFeesCb->addItem( tr( "No conditions apply" ), "no conditions apply" ); int feesIndex = mWMSFeesCb->findData( feesText ); @@ -368,7 +368,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa } // WMS Access Constraints - QString accessConstraintsText = QgsProject::instance()->readEntry( "WMSAccessConstraints", "/", "" ); + QString accessConstraintsText = QgsProject::instance()->readEntry( QStringLiteral( "WMSAccessConstraints" ), QStringLiteral( "/" ), QLatin1String( "" ) ); mWMSAccessConstraintsCb->addItem( tr( "None" ), "None" ); mWMSAccessConstraintsCb->addItem( tr( "Copyright" ), "copyright" ); mWMSAccessConstraintsCb->addItem( tr( "Patent" ), "patent" ); @@ -388,79 +388,79 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa mWMSAccessConstraintsCb->setEditText( accessConstraintsText ); } - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "bg" ) ), QLocale( "bg" ).nativeLanguageName(), "bul" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "cs" ) ), QLocale( "cs" ).nativeLanguageName(), "cze" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "da" ) ), QLocale( "da" ).nativeLanguageName(), "dan" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "nl" ) ), QLocale( "nl" ).nativeLanguageName(), "dut" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "en_GB" ) ), QLocale( "en_GB" ).nativeLanguageName(), "eng" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "et" ) ), QLocale( "et" ).nativeLanguageName(), "est" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "fi" ) ), QLocale( "fi" ).nativeLanguageName(), "fin" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "fr" ) ), QLocale( "fr" ).nativeLanguageName(), "fre" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "de" ) ), QLocale( "de" ).nativeLanguageName(), "ger" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "ga" ) ), QLocale( "ga" ).nativeLanguageName(), "gle" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "el" ) ), QLocale( "el" ).nativeLanguageName(), "gre" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "hu" ) ), QLocale( "hu" ).nativeLanguageName(), "hun" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "it" ) ), QLocale( "it" ).nativeLanguageName(), "ita" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "lv" ) ), QLocale( "lv" ).nativeLanguageName(), "lav" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "lt" ) ), QLocale( "lt" ).nativeLanguageName(), "lit" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "mt" ) ), QLocale( "mt" ).nativeLanguageName(), "mlt" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "pl" ) ), QLocale( "pl" ).nativeLanguageName(), "pol" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "pt_PT" ) ), QLocale( "pt_PT" ).nativeLanguageName(), "por" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "ro" ) ), QLocale( "ro" ).nativeLanguageName(), "rum" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "sk" ) ), QLocale( "sk" ).nativeLanguageName(), "slo" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "sl" ) ), QLocale( "sl" ).nativeLanguageName(), "slv" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "es" ) ), QLocale( "es" ).nativeLanguageName(), "spa" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "sv" ) ), QLocale( "sv" ).nativeLanguageName(), "swe" ); - - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "eu" ) ), QLocale( "eu" ).nativeLanguageName(), "eus" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "ca" ) ), QLocale( "ca" ).nativeLanguageName(), "cat" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "gl" ) ), QLocale( "gl" ).nativeLanguageName(), "gal" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "gd" ) ), QLocale( "gd" ).nativeLanguageName(), "gla" ); - mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "cy" ) ), QLocale( "cy" ).nativeLanguageName(), "cym" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "bg" ) ), QLocale( QStringLiteral( "bg" ) ).nativeLanguageName(), "bul" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "cs" ) ), QLocale( QStringLiteral( "cs" ) ).nativeLanguageName(), "cze" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "da" ) ), QLocale( QStringLiteral( "da" ) ).nativeLanguageName(), "dan" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "nl" ) ), QLocale( QStringLiteral( "nl" ) ).nativeLanguageName(), "dut" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "en_GB" ) ), QLocale( QStringLiteral( "en_GB" ) ).nativeLanguageName(), "eng" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "et" ) ), QLocale( QStringLiteral( "et" ) ).nativeLanguageName(), "est" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "fi" ) ), QLocale( QStringLiteral( "fi" ) ).nativeLanguageName(), "fin" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "fr" ) ), QLocale( QStringLiteral( "fr" ) ).nativeLanguageName(), "fre" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "de" ) ), QLocale( QStringLiteral( "de" ) ).nativeLanguageName(), "ger" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "ga" ) ), QLocale( QStringLiteral( "ga" ) ).nativeLanguageName(), "gle" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "el" ) ), QLocale( QStringLiteral( "el" ) ).nativeLanguageName(), "gre" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "hu" ) ), QLocale( QStringLiteral( "hu" ) ).nativeLanguageName(), "hun" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "it" ) ), QLocale( QStringLiteral( "it" ) ).nativeLanguageName(), "ita" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "lv" ) ), QLocale( QStringLiteral( "lv" ) ).nativeLanguageName(), "lav" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "lt" ) ), QLocale( QStringLiteral( "lt" ) ).nativeLanguageName(), "lit" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "mt" ) ), QLocale( QStringLiteral( "mt" ) ).nativeLanguageName(), "mlt" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "pl" ) ), QLocale( QStringLiteral( "pl" ) ).nativeLanguageName(), "pol" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "pt_PT" ) ), QLocale( QStringLiteral( "pt_PT" ) ).nativeLanguageName(), "por" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "ro" ) ), QLocale( QStringLiteral( "ro" ) ).nativeLanguageName(), "rum" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "sk" ) ), QLocale( QStringLiteral( "sk" ) ).nativeLanguageName(), "slo" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "sl" ) ), QLocale( QStringLiteral( "sl" ) ).nativeLanguageName(), "slv" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "es" ) ), QLocale( QStringLiteral( "es" ) ).nativeLanguageName(), "spa" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "sv" ) ), QLocale( QStringLiteral( "sv" ) ).nativeLanguageName(), "swe" ); + + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "eu" ) ), QLocale( QStringLiteral( "eu" ) ).nativeLanguageName(), "eus" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "ca" ) ), QLocale( QStringLiteral( "ca" ) ).nativeLanguageName(), "cat" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "gl" ) ), QLocale( QStringLiteral( "gl" ) ).nativeLanguageName(), "gal" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "gd" ) ), QLocale( QStringLiteral( "gd" ) ).nativeLanguageName(), "gla" ); + mWMSInspireLanguage->addItem( QIcon( QString( ":/images/flags/%1.png" ).arg( "cy" ) ), QLocale( QStringLiteral( "cy" ) ).nativeLanguageName(), "cym" ); mWMSInspireLanguage->setCurrentIndex( mWMSInspireLanguage->findText( QLocale::system().nativeLanguageName() ) ); - bool addWMSInspire = QgsProject::instance()->readBoolEntry( "WMSInspire", "/activated" ); + bool addWMSInspire = QgsProject::instance()->readBoolEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/activated" ) ); if ( addWMSInspire ) { mWMSInspire->setChecked( addWMSInspire ); - QString inspireLanguage = QgsProject::instance()->readEntry( "WMSInspire", "/language", "" ); + QString inspireLanguage = QgsProject::instance()->readEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/language" ), QLatin1String( "" ) ); int inspireLanguageIndex = mWMSInspireLanguage->findData( inspireLanguage ); mWMSInspireLanguage->setCurrentIndex( inspireLanguageIndex ); - QString inspireMetadataUrl = QgsProject::instance()->readEntry( "WMSInspire", "/metadataUrl", "" ); + QString inspireMetadataUrl = QgsProject::instance()->readEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/metadataUrl" ), QLatin1String( "" ) ); if ( !inspireMetadataUrl.isEmpty() ) { mWMSInspireScenario1->setChecked( true ); mWMSInspireMetadataUrl->setText( inspireMetadataUrl ); mWMSInspireMetadataUrlType->setCurrentIndex( mWMSInspireMetadataUrlType->findText( - QgsProject::instance()->readEntry( "WMSInspire", "/metadataUrlType", "" ) + QgsProject::instance()->readEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/metadataUrlType" ), QLatin1String( "" ) ) ) ); } else { - QString inspireTemporalReference = QgsProject::instance()->readEntry( "WMSInspire", "/temporalReference", "" ); + QString inspireTemporalReference = QgsProject::instance()->readEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/temporalReference" ), QLatin1String( "" ) ); if ( !inspireTemporalReference.isEmpty() ) { mWMSInspireScenario2->setChecked( true ); - mWMSInspireTemporalReference->setDate( QDate::fromString( inspireTemporalReference, "yyyy-MM-dd" ) ); + mWMSInspireTemporalReference->setDate( QDate::fromString( inspireTemporalReference, QStringLiteral( "yyyy-MM-dd" ) ) ); } - QString inspireMetadataDate = QgsProject::instance()->readEntry( "WMSInspire", "/metadataDate", "" ); + QString inspireMetadataDate = QgsProject::instance()->readEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/metadataDate" ), QLatin1String( "" ) ); if ( !inspireMetadataDate.isEmpty() ) { mWMSInspireScenario2->setChecked( true ); - mWMSInspireMetadataDate->setDate( QDate::fromString( inspireMetadataDate, "yyyy-MM-dd" ) ); + mWMSInspireMetadataDate->setDate( QDate::fromString( inspireMetadataDate, QStringLiteral( "yyyy-MM-dd" ) ) ); } } } // WMS GetFeatureInfo precision - int WMSprecision = QgsProject::instance()->readNumEntry( "WMSPrecision", "/", -1 ); + int WMSprecision = QgsProject::instance()->readNumEntry( QStringLiteral( "WMSPrecision" ), QStringLiteral( "/" ), -1 ); if ( WMSprecision != -1 ) { mWMSPrecisionSpinBox->setValue( WMSprecision ); @@ -474,7 +474,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa mWMSExtMaxX->setValidator( new QDoubleValidator( mWMSExtMaxX ) ); mWMSExtMaxY->setValidator( new QDoubleValidator( mWMSExtMaxY ) ); - values = QgsProject::instance()->readListEntry( "WMSExtent", "/", QStringList(), &ok ); + values = QgsProject::instance()->readListEntry( QStringLiteral( "WMSExtent" ), QStringLiteral( "/" ), QStringList(), &ok ); grpWMSExt->setChecked( ok && values.size() == 4 ); if ( grpWMSExt->isChecked() ) { @@ -484,7 +484,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa mWMSExtMaxY->setText( values[3] ); } - values = QgsProject::instance()->readListEntry( "WMSCrsList", "/", QStringList(), &ok ); + values = QgsProject::instance()->readListEntry( QStringLiteral( "WMSCrsList" ), QStringLiteral( "/" ), QStringList(), &ok ); grpWMSList->setChecked( ok && !values.isEmpty() ); if ( grpWMSList->isChecked() ) { @@ -492,14 +492,14 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa } else { - values = QgsProject::instance()->readListEntry( "WMSEpsgList", "/", QStringList(), &ok ); + values = QgsProject::instance()->readListEntry( QStringLiteral( "WMSEpsgList" ), QStringLiteral( "/" ), QStringList(), &ok ); grpWMSList->setChecked( ok && !values.isEmpty() ); if ( grpWMSList->isChecked() ) { QStringList list; Q_FOREACH ( const QString& value, values ) { - list << QString( "EPSG:%1" ).arg( value ); + list << QStringLiteral( "EPSG:%1" ).arg( value ); } mWMSList->addItems( list ); @@ -509,7 +509,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa grpWMSList->setChecked( mWMSList->count() > 0 ); //composer restriction for WMS - values = QgsProject::instance()->readListEntry( "WMSRestrictedComposers", "/", QStringList(), &ok ); + values = QgsProject::instance()->readListEntry( QStringLiteral( "WMSRestrictedComposers" ), QStringLiteral( "/" ), QStringList(), &ok ); mWMSComposerGroupBox->setChecked( ok ); if ( ok ) { @@ -517,48 +517,48 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa } //layer restriction for WMS - values = QgsProject::instance()->readListEntry( "WMSRestrictedLayers", "/", QStringList(), &ok ); + values = QgsProject::instance()->readListEntry( QStringLiteral( "WMSRestrictedLayers" ), QStringLiteral( "/" ), QStringList(), &ok ); mLayerRestrictionsGroupBox->setChecked( ok ); if ( ok ) { mLayerRestrictionsListWidget->addItems( values ); } - bool addWktGeometry = QgsProject::instance()->readBoolEntry( "WMSAddWktGeometry", "/" ); + bool addWktGeometry = QgsProject::instance()->readBoolEntry( QStringLiteral( "WMSAddWktGeometry" ), QStringLiteral( "/" ) ); mAddWktGeometryCheckBox->setChecked( addWktGeometry ); - bool segmentizeFeatureInfoGeometry = QgsProject::instance()->readBoolEntry( "WMSSegmentizeFeatureInfoGeometry", "/" ); + bool segmentizeFeatureInfoGeometry = QgsProject::instance()->readBoolEntry( QStringLiteral( "WMSSegmentizeFeatureInfoGeometry" ), QStringLiteral( "/" ) ); mSegmentizeFeatureInfoGeometryCheckBox->setChecked( segmentizeFeatureInfoGeometry ); - bool useLayerIDs = QgsProject::instance()->readBoolEntry( "WMSUseLayerIDs", "/" ); + bool useLayerIDs = QgsProject::instance()->readBoolEntry( QStringLiteral( "WMSUseLayerIDs" ), QStringLiteral( "/" ) ); mWmsUseLayerIDs->setChecked( useLayerIDs ); //WMS maxWidth / maxHeight mMaxWidthLineEdit->setValidator( new QIntValidator( mMaxWidthLineEdit ) ); - int maxWidth = QgsProject::instance()->readNumEntry( "WMSMaxWidth", "/", -1 ); + int maxWidth = QgsProject::instance()->readNumEntry( QStringLiteral( "WMSMaxWidth" ), QStringLiteral( "/" ), -1 ); if ( maxWidth != -1 ) { mMaxWidthLineEdit->setText( QString::number( maxWidth ) ); } mMaxHeightLineEdit->setValidator( new QIntValidator( mMaxHeightLineEdit ) ); - int maxHeight = QgsProject::instance()->readNumEntry( "WMSMaxHeight", "/", -1 ); + int maxHeight = QgsProject::instance()->readNumEntry( QStringLiteral( "WMSMaxHeight" ), QStringLiteral( "/" ), -1 ); if ( maxHeight != -1 ) { mMaxHeightLineEdit->setText( QString::number( maxHeight ) ); } // WMS imageQuality - int imageQuality = QgsProject::instance()->readNumEntry( "WMSImageQuality", "/", -1 ); + int imageQuality = QgsProject::instance()->readNumEntry( QStringLiteral( "WMSImageQuality" ), QStringLiteral( "/" ), -1 ); if ( imageQuality != -1 ) { mWMSImageQualitySpinBox->setValue( imageQuality ); } - mWFSUrlLineEdit->setText( QgsProject::instance()->readEntry( "WFSUrl", "/", "" ) ); - QStringList wfsLayerIdList = QgsProject::instance()->readListEntry( "WFSLayers", "/" ); - QStringList wfstUpdateLayerIdList = QgsProject::instance()->readListEntry( "WFSTLayers", "Update" ); - QStringList wfstInsertLayerIdList = QgsProject::instance()->readListEntry( "WFSTLayers", "Insert" ); - QStringList wfstDeleteLayerIdList = QgsProject::instance()->readListEntry( "WFSTLayers", "Delete" ); + mWFSUrlLineEdit->setText( QgsProject::instance()->readEntry( QStringLiteral( "WFSUrl" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + QStringList wfsLayerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "WFSLayers" ), QStringLiteral( "/" ) ); + QStringList wfstUpdateLayerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "WFSTLayers" ), QStringLiteral( "Update" ) ); + QStringList wfstInsertLayerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "WFSTLayers" ), QStringLiteral( "Insert" ) ); + QStringList wfstDeleteLayerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "WFSTLayers" ), QStringLiteral( "Delete" ) ); QSignalMapper *smPublied = new QSignalMapper( this ); connect( smPublied, SIGNAL( mapped( int ) ), this, SLOT( cbxWFSPubliedStateChanged( int ) ) ); @@ -591,7 +591,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa connect( cbp, SIGNAL( stateChanged( int ) ), smPublied, SLOT( map() ) ); QSpinBox* psb = new QSpinBox(); - psb->setValue( QgsProject::instance()->readNumEntry( "WFSLayersPrecision", "/" + currentLayer->id(), 8 ) ); + psb->setValue( QgsProject::instance()->readNumEntry( QStringLiteral( "WFSLayersPrecision" ), "/" + currentLayer->id(), 8 ) ); twWFSLayers->setCellWidget( j, 2, psb ); QgsVectorLayer* vlayer = qobject_cast( currentLayer ); @@ -621,8 +621,8 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa twWFSLayers->setRowCount( j ); twWFSLayers->verticalHeader()->setResizeMode( QHeaderView::ResizeToContents ); - mWCSUrlLineEdit->setText( QgsProject::instance()->readEntry( "WCSUrl", "/", "" ) ); - QStringList wcsLayerIdList = QgsProject::instance()->readListEntry( "WCSLayers", "/" ); + mWCSUrlLineEdit->setText( QgsProject::instance()->readEntry( QStringLiteral( "WCSUrl" ), QStringLiteral( "/" ), QLatin1String( "" ) ) ); + QStringList wcsLayerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "WCSLayers" ), QStringLiteral( "/" ) ); QSignalMapper *smWcsPublied = new QSignalMapper( this ); connect( smWcsPublied, SIGNAL( mapped( int ) ), this, SLOT( cbxWCSPubliedStateChanged( int ) ) ); @@ -680,7 +680,7 @@ QgsProjectProperties::QgsProjectProperties( QgsMapCanvas* mapCanvas, QWidget *pa // Project macros - QString pythonMacros = QgsProject::instance()->readEntry( "Macros", "/pythonCode", QString::null ); + QString pythonMacros = QgsProject::instance()->readEntry( QStringLiteral( "Macros" ), QStringLiteral( "/pythonCode" ), QString::null ); grpPythonMacros->setChecked( !pythonMacros.isEmpty() ); if ( !pythonMacros.isEmpty() ) { @@ -809,26 +809,26 @@ void QgsProjectProperties::apply() // number of decimal places for the manual option // Note. Qt 3.2.3 and greater have a function selectedId() that // can be used instead of the two part technique here - QgsProject::instance()->writeEntry( "PositionPrecision", "/Automatic", radAutomatic->isChecked() ); - QgsProject::instance()->writeEntry( "PositionPrecision", "/DecimalPlaces", spinBoxDP->value() ); + QgsProject::instance()->writeEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/Automatic" ), radAutomatic->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DecimalPlaces" ), spinBoxDP->value() ); QString degreeFormat; switch ( static_cast< CoordinateFormat >( mCoordinateDisplayComboBox->currentData().toInt() ) ) { case DegreesMinutes: - degreeFormat = "DM"; + degreeFormat = QStringLiteral( "DM" ); break; case DegreesMinutesSeconds: - degreeFormat = "DMS"; + degreeFormat = QStringLiteral( "DMS" ); break; case MapUnits: - degreeFormat = "MU"; + degreeFormat = QStringLiteral( "MU" ); break; case DecimalDegrees: default: - degreeFormat = "D"; + degreeFormat = QStringLiteral( "D" ); break; } - QgsProject::instance()->writeEntry( "PositionPrecision", "/DegreeFormat", degreeFormat ); + QgsProject::instance()->writeEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DegreeFormat" ), degreeFormat ); // Announce that we may have a new display precision setting emit displayPrecisionChanged(); @@ -839,9 +839,9 @@ void QgsProjectProperties::apply() QgsUnitTypes::AreaUnit areaUnits = static_cast< QgsUnitTypes::AreaUnit >( mAreaUnitsCombo->currentData().toInt() ); QgsProject::instance()->setAreaUnits( areaUnits ); - QgsProject::instance()->writeEntry( "Paths", "/Absolute", cbxAbsolutePath->currentIndex() == 0 ); + QgsProject::instance()->writeEntry( QStringLiteral( "Paths" ), QStringLiteral( "/Absolute" ), cbxAbsolutePath->currentIndex() == 0 ); - if ( mEllipsoidList.at( mEllipsoidIndex ).acronym.startsWith( "PARAMETER" ) ) + if ( mEllipsoidList.at( mEllipsoidIndex ).acronym.startsWith( QLatin1String( "PARAMETER" ) ) ) { double major = mEllipsoidList.at( mEllipsoidIndex ).semiMajor; double minor = mEllipsoidList.at( mEllipsoidIndex ).semiMinor; @@ -852,7 +852,7 @@ void QgsProjectProperties::apply() major = QLocale::system().toDouble( leSemiMajor->text() ); minor = QLocale::system().toDouble( leSemiMinor->text() ); } - QgsProject::instance()->setEllipsoid( QString( "PARAMETER:%1:%2" ) + QgsProject::instance()->setEllipsoid( QStringLiteral( "PARAMETER:%1:%2" ) .arg( major, 0, 'g', 17 ) .arg( minor, 0, 'g', 17 ) ); } @@ -863,17 +863,17 @@ void QgsProjectProperties::apply() //set the color for selections QColor myColor = pbnSelectionColor->color(); - QgsProject::instance()->writeEntry( "Gui", "/SelectionColorRedPart", myColor.red() ); - QgsProject::instance()->writeEntry( "Gui", "/SelectionColorGreenPart", myColor.green() ); - QgsProject::instance()->writeEntry( "Gui", "/SelectionColorBluePart", myColor.blue() ); - QgsProject::instance()->writeEntry( "Gui", "/SelectionColorAlphaPart", myColor.alpha() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorRedPart" ), myColor.red() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorGreenPart" ), myColor.green() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorBluePart" ), myColor.blue() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorAlphaPart" ), myColor.alpha() ); mMapCanvas->setSelectionColor( myColor ); //set the color for canvas myColor = pbnCanvasColor->color(); - QgsProject::instance()->writeEntry( "Gui", "/CanvasColorRedPart", myColor.red() ); - QgsProject::instance()->writeEntry( "Gui", "/CanvasColorGreenPart", myColor.green() ); - QgsProject::instance()->writeEntry( "Gui", "/CanvasColorBluePart", myColor.blue() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorRedPart" ), myColor.red() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorGreenPart" ), myColor.green() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorBluePart" ), myColor.blue() ); mMapCanvas->setCanvasColor( myColor ); QgisApp::instance()->mapOverviewCanvas()->setBackgroundColor( myColor ); QgisApp::instance()->mapOverviewCanvas()->refresh(); @@ -888,12 +888,12 @@ void QgsProjectProperties::apply() if ( !myScales.isEmpty() ) { - QgsProject::instance()->writeEntry( "Scales", "/ScalesList", myScales ); - QgsProject::instance()->writeEntry( "Scales", "/useProjectScales", grpProjectScales->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ), myScales ); + QgsProject::instance()->writeEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ), grpProjectScales->isChecked() ); } else { - QgsProject::instance()->removeEntry( "Scales", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "Scales" ), QStringLiteral( "/" ) ); } //use global or project scales depending on checkbox state @@ -923,30 +923,30 @@ void QgsProjectProperties::apply() QgsProject::instance()->setNonIdentifiableLayers( noIdentifyLayerList ); - QgsProject::instance()->writeEntry( "WMSServiceCapabilities", "/", grpOWSServiceCapabilities->isChecked() ); - QgsProject::instance()->writeEntry( "WMSServiceTitle", "/", mWMSTitle->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSServiceCapabilities" ), QStringLiteral( "/" ), grpOWSServiceCapabilities->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSServiceTitle" ), QStringLiteral( "/" ), mWMSTitle->text() ); if ( !mWMSName->text().isEmpty() ) - QgsProject::instance()->writeEntry( "WMSRootName", "/", mWMSName->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSRootName" ), QStringLiteral( "/" ), mWMSName->text() ); - QgsProject::instance()->writeEntry( "WMSContactOrganization", "/", mWMSContactOrganization->text() ); - QgsProject::instance()->writeEntry( "WMSContactPerson", "/", mWMSContactPerson->text() ); - QgsProject::instance()->writeEntry( "WMSContactMail", "/", mWMSContactMail->text() ); - QgsProject::instance()->writeEntry( "WMSContactPhone", "/", mWMSContactPhone->text() ); - QgsProject::instance()->writeEntry( "WMSServiceAbstract", "/", mWMSAbstract->toPlainText() ); - QgsProject::instance()->writeEntry( "WMSOnlineResource", "/", mWMSOnlineResourceLineEdit->text() ); - QgsProject::instance()->writeEntry( "WMSUrl", "/", mWMSUrlLineEdit->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSContactOrganization" ), QStringLiteral( "/" ), mWMSContactOrganization->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSContactPerson" ), QStringLiteral( "/" ), mWMSContactPerson->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSContactMail" ), QStringLiteral( "/" ), mWMSContactMail->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSContactPhone" ), QStringLiteral( "/" ), mWMSContactPhone->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSServiceAbstract" ), QStringLiteral( "/" ), mWMSAbstract->toPlainText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSOnlineResource" ), QStringLiteral( "/" ), mWMSOnlineResourceLineEdit->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSUrl" ), QStringLiteral( "/" ), mWMSUrlLineEdit->text() ); // WMS Contact Position int contactPositionIndex = mWMSContactPositionCb->currentIndex(); QString contactPositionText = mWMSContactPositionCb->currentText(); if ( !contactPositionText.isEmpty() && contactPositionText == mWMSContactPositionCb->itemText( contactPositionIndex ) ) { - QgsProject::instance()->writeEntry( "WMSContactPosition", "/", mWMSContactPositionCb->itemData( contactPositionIndex ).toString() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSContactPosition" ), QStringLiteral( "/" ), mWMSContactPositionCb->itemData( contactPositionIndex ).toString() ); } else { - QgsProject::instance()->writeEntry( "WMSContactPosition", "/", contactPositionText ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSContactPosition" ), QStringLiteral( "/" ), contactPositionText ); } // WMS Fees @@ -954,11 +954,11 @@ void QgsProjectProperties::apply() QString feesText = mWMSFeesCb->currentText(); if ( !feesText.isEmpty() && feesText == mWMSFeesCb->itemText( feesIndex ) ) { - QgsProject::instance()->writeEntry( "WMSFees", "/", mWMSFeesCb->itemData( feesIndex ).toString() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSFees" ), QStringLiteral( "/" ), mWMSFeesCb->itemData( feesIndex ).toString() ); } else { - QgsProject::instance()->writeEntry( "WMSFees", "/", feesText ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSFees" ), QStringLiteral( "/" ), feesText ); } // WMS Access Constraints @@ -966,52 +966,52 @@ void QgsProjectProperties::apply() QString accessConstraintsText = mWMSAccessConstraintsCb->currentText(); if ( !accessConstraintsText.isEmpty() && accessConstraintsText == mWMSAccessConstraintsCb->itemText( accessConstraintsIndex ) ) { - QgsProject::instance()->writeEntry( "WMSAccessConstraints", "/", mWMSAccessConstraintsCb->itemData( accessConstraintsIndex ).toString() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSAccessConstraints" ), QStringLiteral( "/" ), mWMSAccessConstraintsCb->itemData( accessConstraintsIndex ).toString() ); } else { - QgsProject::instance()->writeEntry( "WMSAccessConstraints", "/", accessConstraintsText ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSAccessConstraints" ), QStringLiteral( "/" ), accessConstraintsText ); } //WMS keyword list QStringList keywordStringList = mWMSKeywordList->text().split( ',' ); if ( !keywordStringList.isEmpty() ) { - keywordStringList.replaceInStrings( QRegExp( "^\\s+" ), "" ).replaceInStrings( QRegExp( "\\s+$" ), "" ); - QgsProject::instance()->writeEntry( "WMSKeywordList", "/", keywordStringList ); + keywordStringList.replaceInStrings( QRegExp( "^\\s+" ), QLatin1String( "" ) ).replaceInStrings( QRegExp( "\\s+$" ), QLatin1String( "" ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSKeywordList" ), QStringLiteral( "/" ), keywordStringList ); } else { - QgsProject::instance()->removeEntry( "WMSKeywordList", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSKeywordList" ), QStringLiteral( "/" ) ); } // WMS INSPIRE configuration - QgsProject::instance()->removeEntry( "WMSInspire", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/" ) ); if ( mWMSInspire->isChecked() ) { - QgsProject::instance()->writeEntry( "WMSInspire", "/activated", mWMSInspire->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/activated" ), mWMSInspire->isChecked() ); int inspireLanguageIndex = mWMSInspireLanguage->currentIndex(); - QgsProject::instance()->writeEntry( "WMSInspire", "/language", mWMSInspireLanguage->itemData( inspireLanguageIndex ).toString() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/language" ), mWMSInspireLanguage->itemData( inspireLanguageIndex ).toString() ); if ( mWMSInspireScenario1->isChecked() ) { - QgsProject::instance()->writeEntry( "WMSInspire", "/metadataUrl", mWMSInspireMetadataUrl->text() ); - QgsProject::instance()->writeEntry( "WMSInspire", "/metadataUrlType", mWMSInspireMetadataUrlType->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/metadataUrl" ), mWMSInspireMetadataUrl->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/metadataUrlType" ), mWMSInspireMetadataUrlType->currentText() ); } else if ( mWMSInspireScenario2->isChecked() ) { - QgsProject::instance()->writeEntry( "WMSInspire", "/temporalReference", mWMSInspireTemporalReference->date().toString( "yyyy-MM-dd" ) ); - QgsProject::instance()->writeEntry( "WMSInspire", "/metadataDate", mWMSInspireMetadataDate->date().toString( "yyyy-MM-dd" ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/temporalReference" ), mWMSInspireTemporalReference->date().toString( QStringLiteral( "yyyy-MM-dd" ) ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSInspire" ), QStringLiteral( "/metadataDate" ), mWMSInspireMetadataDate->date().toString( QStringLiteral( "yyyy-MM-dd" ) ) ); } } // WMS GetFeatureInfo geometry precision (decimal places) - QgsProject::instance()->writeEntry( "WMSPrecision", "/", mWMSPrecisionSpinBox->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSPrecision" ), QStringLiteral( "/" ), mWMSPrecisionSpinBox->text() ); if ( grpWMSExt->isChecked() ) { - QgsProject::instance()->writeEntry( "WMSExtent", "/", + QgsProject::instance()->writeEntry( QStringLiteral( "WMSExtent" ), QStringLiteral( "/" ), QStringList() << mWMSExtMinX->text() << mWMSExtMinY->text() @@ -1020,7 +1020,7 @@ void QgsProjectProperties::apply() } else { - QgsProject::instance()->removeEntry( "WMSExtent", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSExtent" ), QStringLiteral( "/" ) ); } if ( grpWMSList->isChecked() && mWMSList->count() == 0 ) @@ -1029,7 +1029,7 @@ void QgsProjectProperties::apply() grpWMSList->setChecked( false ); } - QgsProject::instance()->removeEntry( "WMSEpsgList", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSEpsgList" ), QStringLiteral( "/" ) ); if ( grpWMSList->isChecked() ) { @@ -1039,11 +1039,11 @@ void QgsProjectProperties::apply() crslist << mWMSList->item( i )->text(); } - QgsProject::instance()->writeEntry( "WMSCrsList", "/", crslist ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSCrsList" ), QStringLiteral( "/" ), crslist ); } else { - QgsProject::instance()->removeEntry( "WMSCrsList", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSCrsList" ), QStringLiteral( "/" ) ); } //WMS composer restrictions @@ -1054,11 +1054,11 @@ void QgsProjectProperties::apply() { composerTitles << mComposerListWidget->item( i )->text(); } - QgsProject::instance()->writeEntry( "WMSRestrictedComposers", "/", composerTitles ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSRestrictedComposers" ), QStringLiteral( "/" ), composerTitles ); } else { - QgsProject::instance()->removeEntry( "WMSRestrictedComposers", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSRestrictedComposers" ), QStringLiteral( "/" ) ); } //WMS layer restrictions @@ -1069,48 +1069,48 @@ void QgsProjectProperties::apply() { layerNames << mLayerRestrictionsListWidget->item( i )->text(); } - QgsProject::instance()->writeEntry( "WMSRestrictedLayers", "/", layerNames ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSRestrictedLayers" ), QStringLiteral( "/" ), layerNames ); } else { - QgsProject::instance()->removeEntry( "WMSRestrictedLayers", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSRestrictedLayers" ), QStringLiteral( "/" ) ); } - QgsProject::instance()->writeEntry( "WMSAddWktGeometry", "/", mAddWktGeometryCheckBox->isChecked() ); - QgsProject::instance()->writeEntry( "WMSSegmentizeFeatureInfoGeometry", "/", mSegmentizeFeatureInfoGeometryCheckBox->isChecked() ); - QgsProject::instance()->writeEntry( "WMSUseLayerIDs", "/", mWmsUseLayerIDs->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSAddWktGeometry" ), QStringLiteral( "/" ), mAddWktGeometryCheckBox->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSSegmentizeFeatureInfoGeometry" ), QStringLiteral( "/" ), mSegmentizeFeatureInfoGeometryCheckBox->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSUseLayerIDs" ), QStringLiteral( "/" ), mWmsUseLayerIDs->isChecked() ); QString maxWidthText = mMaxWidthLineEdit->text(); if ( maxWidthText.isEmpty() ) { - QgsProject::instance()->removeEntry( "WMSMaxWidth", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSMaxWidth" ), QStringLiteral( "/" ) ); } else { - QgsProject::instance()->writeEntry( "WMSMaxWidth", "/", maxWidthText.toInt() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSMaxWidth" ), QStringLiteral( "/" ), maxWidthText.toInt() ); } QString maxHeightText = mMaxHeightLineEdit->text(); if ( maxHeightText.isEmpty() ) { - QgsProject::instance()->removeEntry( "WMSMaxHeight", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSMaxHeight" ), QStringLiteral( "/" ) ); } else { - QgsProject::instance()->writeEntry( "WMSMaxHeight", "/", maxHeightText.toInt() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSMaxHeight" ), QStringLiteral( "/" ), maxHeightText.toInt() ); } // WMS Image quality int imageQualityValue = mWMSImageQualitySpinBox->value(); if ( imageQualityValue == 0 ) { - QgsProject::instance()->removeEntry( "WMSImageQuality", "/" ); + QgsProject::instance()->removeEntry( QStringLiteral( "WMSImageQuality" ), QStringLiteral( "/" ) ); } else { - QgsProject::instance()->writeEntry( "WMSImageQuality", "/", imageQualityValue ); + QgsProject::instance()->writeEntry( QStringLiteral( "WMSImageQuality" ), QStringLiteral( "/" ), imageQualityValue ); } - QgsProject::instance()->writeEntry( "WFSUrl", "/", mWFSUrlLineEdit->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WFSUrl" ), QStringLiteral( "/" ), mWFSUrlLineEdit->text() ); QStringList wfsLayerList; QStringList wfstUpdateLayerList; QStringList wfstInsertLayerList; @@ -1125,7 +1125,7 @@ void QgsProjectProperties::apply() wfsLayerList << id; QSpinBox* sb = qobject_cast( twWFSLayers->cellWidget( i, 2 ) ); - QgsProject::instance()->writeEntry( "WFSLayersPrecision", "/" + id, sb->value() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WFSLayersPrecision" ), "/" + id, sb->value() ); cb = qobject_cast( twWFSLayers->cellWidget( i, 3 ) ); if ( cb && cb->isChecked() ) @@ -1144,12 +1144,12 @@ void QgsProjectProperties::apply() } } } - QgsProject::instance()->writeEntry( "WFSLayers", "/", wfsLayerList ); - QgsProject::instance()->writeEntry( "WFSTLayers", "Update", wfstUpdateLayerList ); - QgsProject::instance()->writeEntry( "WFSTLayers", "Insert", wfstInsertLayerList ); - QgsProject::instance()->writeEntry( "WFSTLayers", "Delete", wfstDeleteLayerList ); + QgsProject::instance()->writeEntry( QStringLiteral( "WFSLayers" ), QStringLiteral( "/" ), wfsLayerList ); + QgsProject::instance()->writeEntry( QStringLiteral( "WFSTLayers" ), QStringLiteral( "Update" ), wfstUpdateLayerList ); + QgsProject::instance()->writeEntry( QStringLiteral( "WFSTLayers" ), QStringLiteral( "Insert" ), wfstInsertLayerList ); + QgsProject::instance()->writeEntry( QStringLiteral( "WFSTLayers" ), QStringLiteral( "Delete" ), wfstDeleteLayerList ); - QgsProject::instance()->writeEntry( "WCSUrl", "/", mWCSUrlLineEdit->text() ); + QgsProject::instance()->writeEntry( QStringLiteral( "WCSUrl" ), QStringLiteral( "/" ), mWCSUrlLineEdit->text() ); QStringList wcsLayerList; for ( int i = 0; i < twWCSLayers->rowCount(); i++ ) { @@ -1161,15 +1161,15 @@ void QgsProjectProperties::apply() wcsLayerList << id; } } - QgsProject::instance()->writeEntry( "WCSLayers", "/", wcsLayerList ); + QgsProject::instance()->writeEntry( QStringLiteral( "WCSLayers" ), QStringLiteral( "/" ), wcsLayerList ); // Default Styles - QgsProject::instance()->writeEntry( "DefaultStyles", "/Marker", cboStyleMarker->currentText() ); - QgsProject::instance()->writeEntry( "DefaultStyles", "/Line", cboStyleLine->currentText() ); - QgsProject::instance()->writeEntry( "DefaultStyles", "/Fill", cboStyleFill->currentText() ); - QgsProject::instance()->writeEntry( "DefaultStyles", "/ColorRamp", cboStyleColorRamp->currentText() ); - QgsProject::instance()->writeEntry( "DefaultStyles", "/AlphaInt", ( int )( 255 - ( mTransparencySlider->value() * 2.55 ) ) ); - QgsProject::instance()->writeEntry( "DefaultStyles", "/RandomColors", cbxStyleRandomColors->isChecked() ); + QgsProject::instance()->writeEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Marker" ), cboStyleMarker->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Line" ), cboStyleLine->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Fill" ), cboStyleFill->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/ColorRamp" ), cboStyleColorRamp->currentText() ); + QgsProject::instance()->writeEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/AlphaInt" ), ( int )( 255 - ( mTransparencySlider->value() * 2.55 ) ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/RandomColors" ), cbxStyleRandomColors->isChecked() ); if ( mTreeProjectColors->isDirty() ) { mTreeProjectColors->saveColorsToScheme(); @@ -1182,7 +1182,7 @@ void QgsProjectProperties::apply() pythonMacros = QString::null; resetPythonMacros(); } - QgsProject::instance()->writeEntry( "Macros", "/pythonCode", pythonMacros ); + QgsProject::instance()->writeEntry( QStringLiteral( "Macros" ), QStringLiteral( "/pythonCode" ), pythonMacros ); QgsProject::instance()->relationManager()->setRelations( mRelationManagerDlg->relations() ); @@ -1554,7 +1554,7 @@ void QgsProjectProperties::on_pbnLaunchOWSChecker_clicked() { QString nameMessage = "

                                                                                                                                                                                    " + tr( "Some layers and groups have the same name or short name" ) + "

                                                                                                                                                                                    "; nameMessage += "

                                                                                                                                                                                    " + tr( "Duplicate names:" ) + "

                                                                                                                                                                                    "; - nameMessage += duplicateNames.join( "
                                                                                                                                                                                  • " ) + "
                                                                                                                                                                                  • "; + nameMessage += duplicateNames.join( QStringLiteral( "
                                                                                                                                                                                  • " ) ) + "
                                                                                                                                                                                  • "; teOWSChecker->setHtml( teOWSChecker->toHtml() + nameMessage ); } else @@ -1564,7 +1564,7 @@ void QgsProjectProperties::on_pbnLaunchOWSChecker_clicked() if ( regExpMessages.size() != 0 ) { - QString encodingMessage = "

                                                                                                                                                                                    " + tr( "Some layer short names have to be updated:" ) + "

                                                                                                                                                                                    • " + regExpMessages.join( "
                                                                                                                                                                                    • " ) + "
                                                                                                                                                                                    "; + QString encodingMessage = "

                                                                                                                                                                                    " + tr( "Some layer short names have to be updated:" ) + "

                                                                                                                                                                                    • " + regExpMessages.join( QStringLiteral( "
                                                                                                                                                                                    • " ) ) + "
                                                                                                                                                                                    "; teOWSChecker->setHtml( teOWSChecker->toHtml() + encodingMessage ); } else @@ -1574,7 +1574,7 @@ void QgsProjectProperties::on_pbnLaunchOWSChecker_clicked() if ( encodingMessages.size() != 0 ) { - QString encodingMessage = "

                                                                                                                                                                                    " + tr( "Some layer encodings are not set:" ) + "

                                                                                                                                                                                    • " + encodingMessages.join( "
                                                                                                                                                                                    • " ) + "
                                                                                                                                                                                    "; + QString encodingMessage = "

                                                                                                                                                                                    " + tr( "Some layer encodings are not set:" ) + "

                                                                                                                                                                                    • " + encodingMessages.join( QStringLiteral( "
                                                                                                                                                                                    • " ) ) + "
                                                                                                                                                                                    "; teOWSChecker->setHtml( teOWSChecker->toHtml() + encodingMessage ); } else @@ -1597,7 +1597,7 @@ void QgsProjectProperties::on_pbnAddScale_clicked() if ( myScale != -1 ) { - QListWidgetItem* newItem = addScaleToScaleList( QString( "1:%1" ).arg( myScale ) ); + QListWidgetItem* newItem = addScaleToScaleList( QStringLiteral( "1:%1" ).arg( myScale ) ); lstScales->setCurrentItem( newItem ); } } @@ -1641,9 +1641,9 @@ void QgsProjectProperties::on_pbnExportScales_clicked() } // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } QStringList myScales; @@ -1667,17 +1667,17 @@ void QgsProjectProperties::populateStyles() QStringList prefList; QList cboList; cboList << cboStyleMarker; - prefList << QgsProject::instance()->readEntry( "DefaultStyles", "/Marker", "" ); + prefList << QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Marker" ), QLatin1String( "" ) ); cboList << cboStyleLine; - prefList << QgsProject::instance()->readEntry( "DefaultStyles", "/Line", "" ); + prefList << QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Line" ), QLatin1String( "" ) ); cboList << cboStyleFill; - prefList << QgsProject::instance()->readEntry( "DefaultStyles", "/Fill", "" ); + prefList << QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Fill" ), QLatin1String( "" ) ); cboList << cboStyleColorRamp; - prefList << QgsProject::instance()->readEntry( "DefaultStyles", "/ColorRamp", "" ); + prefList << QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/ColorRamp" ), QLatin1String( "" ) ); for ( int i = 0; i < cboList.count(); i++ ) { cboList[i]->clear(); - cboList[i]->addItem( "" ); + cboList[i]->addItem( QLatin1String( "" ) ); } // populate symbols @@ -1729,10 +1729,10 @@ void QgsProjectProperties::populateStyles() } // random colors - cbxStyleRandomColors->setChecked( QgsProject::instance()->readBoolEntry( "DefaultStyles", "/RandomColors", true ) ); + cbxStyleRandomColors->setChecked( QgsProject::instance()->readBoolEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/RandomColors" ), true ) ); // alpha transparency - int transparencyInt = ( 255 - QgsProject::instance()->readNumEntry( "DefaultStyles", "/AlphaInt", 255 ) ) / 2.55; + int transparencyInt = ( 255 - QgsProject::instance()->readNumEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/AlphaInt" ), 255 ) ) / 2.55; mTransparencySlider->setValue( transparencyInt ); } @@ -1784,13 +1784,13 @@ void QgsProjectProperties::editSymbol( QComboBox* cbo ) QString symbolName = cbo->currentText(); if ( symbolName.isEmpty() ) { - QMessageBox::information( this, "", tr( "Select a valid symbol" ) ); + QMessageBox::information( this, QLatin1String( "" ), tr( "Select a valid symbol" ) ); return; } QgsSymbol* symbol = mStyle->symbol( symbolName ); if ( ! symbol ) { - QMessageBox::warning( this, "", tr( "Invalid symbol : " ) + symbolName ); + QMessageBox::warning( this, QLatin1String( "" ), tr( "Invalid symbol : " ) + symbolName ); return; } @@ -1827,7 +1827,7 @@ void QgsProjectProperties::checkOWS( QgsLayerTreeGroup* treeGroup, QStringList& if ( treeNode->nodeType() == QgsLayerTreeNode::NodeGroup ) { QgsLayerTreeGroup* treeGroupChild = static_cast( treeNode ); - QString shortName = treeGroupChild->customProperty( "wmsShortName" ).toString(); + QString shortName = treeGroupChild->customProperty( QStringLiteral( "wmsShortName" ) ).toString(); if ( shortName.isEmpty() ) owsNames << treeGroupChild->name(); else @@ -1846,7 +1846,7 @@ void QgsProjectProperties::checkOWS( QgsLayerTreeGroup* treeGroup, QStringList& if ( l->type() == QgsMapLayer::VectorLayer ) { QgsVectorLayer* vl = static_cast( l ); - if ( vl->dataProvider()->encoding() == "System" ) + if ( vl->dataProvider()->encoding() == QLatin1String( "System" ) ) encodingMessages << tr( "Update layer \"%1\" encoding" ).arg( l->name() ); } } @@ -1870,7 +1870,7 @@ void QgsProjectProperties::populateEllipsoidList() myItem.semiMinor = 0.0; mEllipsoidList.append( myItem ); - myItem.acronym = QLatin1String( "PARAMETER:6370997:6370997" ); + myItem.acronym = QStringLiteral( "PARAMETER:6370997:6370997" ); myItem.description = tr( "Parameters:" ); myItem.semiMajor = 6370997.0; myItem.semiMinor = 6370997.0; @@ -1887,7 +1887,7 @@ void QgsProjectProperties::populateEllipsoidList() } // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list - QString mySql = "select acronym, name, radius, parameter2 from tbl_ellipsoid order by name"; + QString mySql = QStringLiteral( "select acronym, name, radius, parameter2 from tbl_ellipsoid order by name" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); // XXX Need to free memory from the error msg if one is set if ( myResult == SQLITE_OK ) @@ -1908,11 +1908,11 @@ void QgsProjectProperties::populateEllipsoidList() para1 = ( const char * )sqlite3_column_text( myPreparedStatement, 2 ); para2 = ( const char * )sqlite3_column_text( myPreparedStatement, 3 ); myItem.semiMajor = para1.midRef( 2 ).toDouble(); - if ( para2.left( 2 ) == "b=" ) + if ( para2.left( 2 ) == QLatin1String( "b=" ) ) { myItem.semiMinor = para2.midRef( 2 ).toDouble(); } - else if ( para2.left( 3 ) == "rf=" ) + else if ( para2.left( 3 ) == QLatin1String( "rf=" ) ) { double invFlattening = para2.midRef( 3 ).toDouble(); if ( invFlattening != 0.0 ) @@ -1962,13 +1962,13 @@ void QgsProjectProperties::updateEllipsoidUI( int newIndex ) mEllipsoidIndex = newIndex; leSemiMajor->setEnabled( false ); leSemiMinor->setEnabled( false ); - leSemiMajor->setText( "" ); - leSemiMinor->setText( "" ); + leSemiMajor->setText( QLatin1String( "" ) ); + leSemiMinor->setText( QLatin1String( "" ) ); if ( cbxProjectionEnabled->isChecked() ) { cmbEllipsoid->setEnabled( true ); - cmbEllipsoid->setToolTip( "" ); - if ( mEllipsoidList.at( mEllipsoidIndex ).acronym.startsWith( "PARAMETER:" ) ) + cmbEllipsoid->setToolTip( QLatin1String( "" ) ); + if ( mEllipsoidList.at( mEllipsoidIndex ).acronym.startsWith( QLatin1String( "PARAMETER:" ) ) ) { leSemiMajor->setEnabled( true ); leSemiMinor->setEnabled( true ); @@ -2045,11 +2045,11 @@ void QgsProjectProperties::addScaleToScaleList( QListWidgetItem* newItem ) QListWidgetItem* duplicateItem = lstScales->findItems( newItem->text(), Qt::MatchExactly ).value( 0 ); delete duplicateItem; - int newDenominator = newItem->text().split( ":" ).value( 1 ).toInt(); + int newDenominator = newItem->text().split( QStringLiteral( ":" ) ).value( 1 ).toInt(); int i; for ( i = 0; i < lstScales->count(); i++ ) { - int denominator = lstScales->item( i )->text().split( ":" ).value( 1 ).toInt(); + int denominator = lstScales->item( i )->text().split( QStringLiteral( ":" ) ).value( 1 ).toInt(); if ( newDenominator > denominator ) break; } @@ -2066,8 +2066,8 @@ void QgsProjectProperties::scaleItemChanged( QListWidgetItem* changedScaleItem ) if ( regExp.exactMatch( changedScaleItem->text() ) ) { //Remove leading zeroes from the denominator - regExp.setPattern( "1:0*" ); - changedScaleItem->setText( changedScaleItem->text().replace( regExp, "1:" ) ); + regExp.setPattern( QStringLiteral( "1:0*" ) ); + changedScaleItem->setText( changedScaleItem->text().replace( regExp, QStringLiteral( "1:" ) ) ); } else { diff --git a/src/app/qgsrastercalcdialog.cpp b/src/app/qgsrastercalcdialog.cpp index 351a7db9dc03..e24cae0aa439 100644 --- a/src/app/qgsrastercalcdialog.cpp +++ b/src/app/qgsrastercalcdialog.cpp @@ -31,7 +31,7 @@ QgsRasterCalcDialog::QgsRasterCalcDialog( QWidget * parent, Qt::WindowFlags f ): setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/RasterCalc/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/RasterCalc/geometry" ) ).toByteArray() ); //add supported output formats insertAvailableOutputFormats(); @@ -47,7 +47,7 @@ QgsRasterCalcDialog::QgsRasterCalcDialog( QWidget * parent, Qt::WindowFlags f ): QgsRasterCalcDialog::~QgsRasterCalcDialog() { QSettings settings; - settings.setValue( "/Windows/RasterCalc/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/RasterCalc/geometry" ), saveGeometry() ); } QString QgsRasterCalcDialog::formulaString() const @@ -87,7 +87,7 @@ QString QgsRasterCalcDialog::outputFormat() const int index = mOutputFormatComboBox->currentIndex(); if ( index == -1 ) { - return ""; + return QLatin1String( "" ); } return mOutputFormatComboBox->itemData( index ).toString(); } @@ -128,7 +128,7 @@ void QgsRasterCalcDialog::insertAvailableRasterBands() for ( ; layerIt != layers.constEnd(); ++layerIt ) { QgsRasterLayer* rlayer = dynamic_cast( layerIt.value() ); - if ( rlayer && rlayer->dataProvider() && rlayer->dataProvider()->name() == "gdal" ) + if ( rlayer && rlayer->dataProvider() && rlayer->dataProvider()->name() == QLatin1String( "gdal" ) ) { if ( firstLayer ) //set bounding box / resolution of output to the values of the first possible input layer { @@ -170,7 +170,7 @@ void QgsRasterCalcDialog::insertAvailableOutputFormats() { QString driverShortName = GDALGetDriverShortName( driver ); QString driverLongName = GDALGetDriverLongName( driver ); - if ( driverShortName == "MEM" ) + if ( driverShortName == QLatin1String( "MEM" ) ) { // in memory rasters are not (yet) supported because the GDAL dataset handle // would need to be passed directly to QgsRasterLayer (it is not possible to @@ -190,7 +190,7 @@ void QgsRasterCalcDialog::insertAvailableOutputFormats() //and set last used driver in combo box QSettings s; - QString lastUsedDriver = s.value( "/RasterCalculator/lastOutputFormat", "GeoTIFF" ).toString(); + QString lastUsedDriver = s.value( QStringLiteral( "/RasterCalculator/lastOutputFormat" ), "GeoTIFF" ).toString(); int lastDriverIndex = mOutputFormatComboBox->findText( lastUsedDriver ); if ( lastDriverIndex != -1 ) { @@ -219,14 +219,14 @@ void QgsRasterCalcDialog::on_mButtonBox_accepted() { //save last output format QSettings s; - s.setValue( "/RasterCalculator/lastOutputFormat", QVariant( mOutputFormatComboBox->currentText() ) ); - s.setValue( "/RasterCalculator/lastOutputDir", QVariant( QFileInfo( mOutputLayerLineEdit->text() ).absolutePath() ) ); + s.setValue( QStringLiteral( "/RasterCalculator/lastOutputFormat" ), QVariant( mOutputFormatComboBox->currentText() ) ); + s.setValue( QStringLiteral( "/RasterCalculator/lastOutputDir" ), QVariant( QFileInfo( mOutputLayerLineEdit->text() ).absolutePath() ) ); } void QgsRasterCalcDialog::on_mOutputLayerPushButton_clicked() { QSettings s; - QString saveFileName = QFileDialog::getSaveFileName( nullptr, tr( "Enter result file" ), s.value( "/RasterCalculator/lastOutputDir", QDir::homePath() ).toString() ); + QString saveFileName = QFileDialog::getSaveFileName( nullptr, tr( "Enter result file" ), s.value( QStringLiteral( "/RasterCalculator/lastOutputDir" ), QDir::homePath() ).toString() ); if ( !saveFileName.isNull() ) { mOutputLayerLineEdit->setText( saveFileName ); @@ -329,129 +329,129 @@ void QgsRasterCalcDialog::on_mRasterBandsListWidget_itemDoubleClicked( QListWidg void QgsRasterCalcDialog::on_mPlusPushButton_clicked() { - mExpressionTextEdit->insertPlainText( " + " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " + " ) ); } void QgsRasterCalcDialog::on_mMinusPushButton_clicked() { - mExpressionTextEdit->insertPlainText( " - " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " - " ) ); } void QgsRasterCalcDialog::on_mMultiplyPushButton_clicked() { - mExpressionTextEdit->insertPlainText( " * " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " * " ) ); } void QgsRasterCalcDialog::on_mDividePushButton_clicked() { - mExpressionTextEdit->insertPlainText( " / " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " / " ) ); } void QgsRasterCalcDialog::on_mSqrtButton_clicked() { - mExpressionTextEdit->insertPlainText( " sqrt ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " sqrt ( " ) ); } void QgsRasterCalcDialog::on_mCosButton_clicked() { - mExpressionTextEdit->insertPlainText( " cos ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " cos ( " ) ); } void QgsRasterCalcDialog::on_mSinButton_clicked() { - mExpressionTextEdit->insertPlainText( " sin ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " sin ( " ) ); } void QgsRasterCalcDialog::on_mASinButton_clicked() { - mExpressionTextEdit->insertPlainText( " asin ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " asin ( " ) ); } void QgsRasterCalcDialog::on_mExpButton_clicked() { - mExpressionTextEdit->insertPlainText( " ^ " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " ^ " ) ); } void QgsRasterCalcDialog::on_mTanButton_clicked() { - mExpressionTextEdit->insertPlainText( " tan ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " tan ( " ) ); } void QgsRasterCalcDialog::on_mACosButton_clicked() { - mExpressionTextEdit->insertPlainText( " acos ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " acos ( " ) ); } void QgsRasterCalcDialog::on_mATanButton_clicked() { - mExpressionTextEdit->insertPlainText( " atan ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " atan ( " ) ); } void QgsRasterCalcDialog::on_mLnButton_clicked() { - mExpressionTextEdit->insertPlainText( " ln ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " ln ( " ) ); } void QgsRasterCalcDialog::on_mLogButton_clicked() { - mExpressionTextEdit->insertPlainText( " log10 ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " log10 ( " ) ); } void QgsRasterCalcDialog::on_mNotEqualButton_clicked() { - mExpressionTextEdit->insertPlainText( " != " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " != " ) ); } void QgsRasterCalcDialog::on_mOpenBracketPushButton_clicked() { - mExpressionTextEdit->insertPlainText( " ( " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " ( " ) ); } void QgsRasterCalcDialog::on_mCloseBracketPushButton_clicked() { - mExpressionTextEdit->insertPlainText( " ) " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " ) " ) ); } void QgsRasterCalcDialog::on_mLessButton_clicked() { - mExpressionTextEdit->insertPlainText( " < " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " < " ) ); } void QgsRasterCalcDialog::on_mGreaterButton_clicked() { - mExpressionTextEdit->insertPlainText( " > " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " > " ) ); } void QgsRasterCalcDialog::on_mEqualButton_clicked() { - mExpressionTextEdit->insertPlainText( " = " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " = " ) ); } void QgsRasterCalcDialog::on_mLesserEqualButton_clicked() { - mExpressionTextEdit->insertPlainText( " <= " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " <= " ) ); } void QgsRasterCalcDialog::on_mGreaterEqualButton_clicked() { - mExpressionTextEdit->insertPlainText( " >= " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " >= " ) ); } void QgsRasterCalcDialog::on_mAndButton_clicked() { - mExpressionTextEdit->insertPlainText( " AND " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " AND " ) ); } void QgsRasterCalcDialog::on_mOrButton_clicked() { - mExpressionTextEdit->insertPlainText( " OR " ); + mExpressionTextEdit->insertPlainText( QStringLiteral( " OR " ) ); } QString QgsRasterCalcDialog::quoteBandEntry( const QString& layerName ) { // '"' -> '\\"' QString quotedName = layerName; - quotedName.replace( '\"', "\\\"" ); + quotedName.replace( '\"', QLatin1String( "\\\"" ) ); quotedName.append( '\"' ); quotedName.prepend( '\"' ); return quotedName; diff --git a/src/app/qgsrasterlayerproperties.cpp b/src/app/qgsrasterlayerproperties.cpp index 3ae49b401e0f..30f419b68c17 100644 --- a/src/app/qgsrasterlayerproperties.cpp +++ b/src/app/qgsrasterlayerproperties.cpp @@ -71,7 +71,7 @@ #include QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanvas* theCanvas, QWidget *parent, Qt::WindowFlags fl ) - : QgsOptionsDialogBase( "RasterLayerProperties", parent, fl ) + : QgsOptionsDialogBase( QStringLiteral( "RasterLayerProperties" ), parent, fl ) // Constant that signals property not used. , TRSTRING_NOT_SET( tr( "Not Set" ) ) , mDefaultStandardDeviation( 0 ) @@ -151,12 +151,12 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv QIcon myPyramidPixmap( QgsApplication::getThemeIcon( "/mIconPyramid.png" ) ); QIcon myNoPyramidPixmap( QgsApplication::getThemeIcon( "/mIconNoPyramid.png" ) ); - pbnAddValuesManually->setIcon( QgsApplication::getThemeIcon( "/symbologyAdd.svg" ) ); - pbnAddValuesFromDisplay->setIcon( QgsApplication::getThemeIcon( "/mActionContextHelp.png" ) ); - pbnRemoveSelectedRow->setIcon( QgsApplication::getThemeIcon( "/symbologyRemove.svg" ) ); - pbnDefaultValues->setIcon( QgsApplication::getThemeIcon( "/mActionOpenTable.svg" ) ); - pbnImportTransparentPixelValues->setIcon( QgsApplication::getThemeIcon( "/mActionFileOpen.svg" ) ); - pbnExportTransparentPixelValues->setIcon( QgsApplication::getThemeIcon( "/mActionFileSave.svg" ) ); + pbnAddValuesManually->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/symbologyAdd.svg" ) ) ); + pbnAddValuesFromDisplay->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionContextHelp.png" ) ) ); + pbnRemoveSelectedRow->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/symbologyRemove.svg" ) ) ); + pbnDefaultValues->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOpenTable.svg" ) ) ); + pbnImportTransparentPixelValues->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileOpen.svg" ) ) ); + pbnExportTransparentPixelValues->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileSave.svg" ) ) ); mPixelSelectorTool = nullptr; if ( mMapCanvas ) @@ -207,13 +207,13 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv if ( myRasterPyramidIterator->exists ) { lbxPyramidResolutions->addItem( new QListWidgetItem( myPyramidPixmap, - QString::number( myRasterPyramidIterator->xDim ) + QLatin1String( " x " ) + + QString::number( myRasterPyramidIterator->xDim ) + QStringLiteral( " x " ) + QString::number( myRasterPyramidIterator->yDim ) ) ); } else { lbxPyramidResolutions->addItem( new QListWidgetItem( myNoPyramidPixmap, - QString::number( myRasterPyramidIterator->xDim ) + QLatin1String( " x " ) + + QString::number( myRasterPyramidIterator->xDim ) + QStringLiteral( " x " ) + QString::number( myRasterPyramidIterator->yDim ) ) ); } } @@ -238,7 +238,7 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv mCrsSelector->setCrs( mRasterLayer->crs() ); // Set text for pyramid info box - QString pyramidFormat( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    %2 %3 %4

                                                                                                                                                                                    %5

                                                                                                                                                                                    %6

                                                                                                                                                                                    " ); + QString pyramidFormat( QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    %2 %3 %4

                                                                                                                                                                                    %5

                                                                                                                                                                                    %6

                                                                                                                                                                                    " ) ); QString pyramidHeader = tr( "Description" ); QString pyramidSentence1 = tr( "Large resolution raster layers can slow navigation in QGIS." ); QString pyramidSentence2 = tr( "By creating lower resolution copies of the data (pyramids) performance can be considerably improved as QGIS selects the most suitable resolution to use depending on the level of zoom." ); @@ -269,11 +269,11 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv const QgsRasterResampler* zoomedInResampler = resampleFilter->zoomedInResampler(); if ( zoomedInResampler ) { - if ( zoomedInResampler->type() == "bilinear" ) + if ( zoomedInResampler->type() == QLatin1String( "bilinear" ) ) { mZoomedInResamplingComboBox->setCurrentIndex( 1 ); } - else if ( zoomedInResampler->type() == "cubic" ) + else if ( zoomedInResampler->type() == QLatin1String( "cubic" ) ) { mZoomedInResamplingComboBox->setCurrentIndex( 2 ); } @@ -286,7 +286,7 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv const QgsRasterResampler* zoomedOutResampler = resampleFilter->zoomedOutResampler(); if ( zoomedOutResampler ) { - if ( zoomedOutResampler->type() == "bilinear" ) //bilinear resampler does averaging when zooming out + if ( zoomedOutResampler->type() == QLatin1String( "bilinear" ) ) //bilinear resampler does averaging when zooming out { mZoomedOutResamplingComboBox->setCurrentIndex( 1 ); } @@ -299,7 +299,7 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv } btnColorizeColor->setColorDialogTitle( tr( "Select color" ) ); - btnColorizeColor->setContext( "symbology" ); + btnColorizeColor->setContext( QStringLiteral( "symbology" ) ); // Hue and saturation color control const QgsHueSaturationFilter* hueSaturationFilter = mRasterLayer->hueSaturationFilter(); @@ -333,9 +333,9 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv bandName = provider->generateBandName( i ); QString colorInterp = provider->colorInterpretationName( i ); - if ( colorInterp != "Undefined" ) + if ( colorInterp != QLatin1String( "Undefined" ) ) { - bandName.append( QString( " (%1)" ).arg( colorInterp ) ); + bandName.append( QStringLiteral( " (%1)" ).arg( colorInterp ) ); } cboxTransparencyBand->addItem( bandName, i ); } @@ -362,11 +362,11 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv } //insert renderer widgets into registry - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "paletted", QgsPalettedRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "multibandcolor", QgsMultiBandColorRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "singlebandpseudocolor", QgsSingleBandPseudoColorRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "singlebandgray", QgsSingleBandGrayRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "hillshade", QgsHillshadeRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "paletted" ), QgsPalettedRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "multibandcolor" ), QgsMultiBandColorRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "singlebandpseudocolor" ), QgsSingleBandPseudoColorRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "singlebandgray" ), QgsSingleBandGrayRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "hillshade" ), QgsHillshadeRendererWidget::create ); //fill available renderers into combo box QgsRasterRendererRegistryEntry entry; @@ -374,8 +374,8 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv { if ( QgsRasterRendererRegistry::instance()->rendererData( name, entry ) ) { - if (( mRasterLayer->rasterType() != QgsRasterLayer::ColorLayer && entry.name != "singlebandcolordata" ) || - ( mRasterLayer->rasterType() == QgsRasterLayer::ColorLayer && entry.name == "singlebandcolordata" ) ) + if (( mRasterLayer->rasterType() != QgsRasterLayer::ColorLayer && entry.name != QLatin1String( "singlebandcolordata" ) ) || + ( mRasterLayer->rasterType() == QgsRasterLayer::ColorLayer && entry.name == QLatin1String( "singlebandcolordata" ) ) ) { mRenderTypeComboBox->addItem( entry.visibleName, entry.name ); } @@ -403,7 +403,7 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv mRenderTypeComboBox->removeItem( mRenderTypeComboBox->findData( "singlebandcolordata" ) ); } #endif - if ( rendererType == "singlebandcolordata" && mRenderTypeComboBox->count() == 1 ) + if ( rendererType == QLatin1String( "singlebandcolordata" ) && mRenderTypeComboBox->count() == 1 ) { // no band rendering options for singlebandcolordata, so minimize group box QSizePolicy sizep = mBandRenderingGrpBx->sizePolicy(); @@ -421,13 +421,13 @@ QgsRasterLayerProperties::QgsRasterLayerProperties( QgsMapLayer* lyr, QgsMapCanv QSettings settings; // if dialog hasn't been opened/closed yet, default to Styles tab, which is used most often // this will be read by restoreOptionsBaseUi() - if ( !settings.contains( QString( "/Windows/RasterLayerProperties/tab" ) ) ) + if ( !settings.contains( QStringLiteral( "/Windows/RasterLayerProperties/tab" ) ) ) { - settings.setValue( QString( "/Windows/RasterLayerProperties/tab" ), + settings.setValue( QStringLiteral( "/Windows/RasterLayerProperties/tab" ), mOptStackedWidget->indexOf( mOptsPage_Style ) ); } - mResetColorRenderingBtn->setIcon( QgsApplication::getThemeIcon( "/mActionUndo.svg" ) ); + mResetColorRenderingBtn->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionUndo.svg" ) ) ); QString title = QString( tr( "Layer Properties - %1" ) ).arg( lyr->name() ); restoreOptionsBaseUi( title ); @@ -686,7 +686,7 @@ void QgsRasterLayerProperties::sync() } else { - leNoDataValue->insert( "" ); + leNoDataValue->insert( QLatin1String( "" ) ); } populateTransparencyTable( mRasterLayer->renderer() ); @@ -1035,28 +1035,28 @@ void QgsRasterLayerProperties::on_buttonBuildPyramids_clicked() disconnect( provider, SIGNAL( progressUpdate( int ) ), mPyramidProgress, SLOT( setValue( int ) ) ); if ( !res.isNull() ) { - if ( res == "ERROR_WRITE_ACCESS" ) + if ( res == QLatin1String( "ERROR_WRITE_ACCESS" ) ) { QMessageBox::warning( this, tr( "Write access denied" ), tr( "Write access denied. Adjust the file permissions and try again." ) ); } - else if ( res == "ERROR_WRITE_FORMAT" ) + else if ( res == QLatin1String( "ERROR_WRITE_FORMAT" ) ) { QMessageBox::warning( this, tr( "Building pyramids failed." ), tr( "The file was not writable. Some formats do not " "support pyramid overviews. Consult the GDAL documentation if in doubt." ) ); } - else if ( res == "FAILED_NOT_SUPPORTED" ) + else if ( res == QLatin1String( "FAILED_NOT_SUPPORTED" ) ) { QMessageBox::warning( this, tr( "Building pyramids failed." ), tr( "Building pyramid overviews is not supported on this type of raster." ) ); } - else if ( res == "ERROR_JPEG_COMPRESSION" ) + else if ( res == QLatin1String( "ERROR_JPEG_COMPRESSION" ) ) { QMessageBox::warning( this, tr( "Building pyramids failed." ), tr( "Building internal pyramid overviews is not supported on raster layers with JPEG compression and your current libtiff library." ) ); } - else if ( res == "ERROR_VIRTUAL" ) + else if ( res == QLatin1String( "ERROR_VIRTUAL" ) ) { QMessageBox::warning( this, tr( "Building pyramids failed." ), tr( "Building pyramid overviews is not supported on this type of raster." ) ); @@ -1081,13 +1081,13 @@ void QgsRasterLayerProperties::on_buttonBuildPyramids_clicked() if ( myRasterPyramidIterator->exists ) { lbxPyramidResolutions->addItem( new QListWidgetItem( myPyramidPixmap, - QString::number( myRasterPyramidIterator->xDim ) + QLatin1String( " x " ) + + QString::number( myRasterPyramidIterator->xDim ) + QStringLiteral( " x " ) + QString::number( myRasterPyramidIterator->yDim ) ) ); } else { lbxPyramidResolutions->addItem( new QListWidgetItem( myNoPyramidPixmap, - QString::number( myRasterPyramidIterator->xDim ) + QLatin1String( " x " ) + + QString::number( myRasterPyramidIterator->xDim ) + QStringLiteral( " x " ) + QString::number( myRasterPyramidIterator->yDim ) ) ); } } @@ -1271,11 +1271,11 @@ void QgsRasterLayerProperties::adjustTransparencyCellWidth( int row, int column void QgsRasterLayerProperties::on_pbnExportTransparentPixelValues_clicked() { QSettings myQSettings; - QString myLastDir = myQSettings.value( "lastRasterFileFilterDir", QDir::homePath() ).toString(); + QString myLastDir = myQSettings.value( QStringLiteral( "lastRasterFileFilterDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getSaveFileName( this, tr( "Save file" ), myLastDir, tr( "Textfile" ) + " (*.txt)" ); if ( !myFileName.isEmpty() ) { - if ( !myFileName.endsWith( ".txt", Qt::CaseInsensitive ) ) + if ( !myFileName.endsWith( QLatin1String( ".txt" ), Qt::CaseInsensitive ) ) { myFileName = myFileName + ".txt"; } @@ -1437,7 +1437,7 @@ void QgsRasterLayerProperties::on_pbnImportTransparentPixelValues_clicked() bool myImportError = false; QString myBadLines; QSettings myQSettings; - QString myLastDir = myQSettings.value( "lastRasterFileFilterDir", QDir::homePath() ).toString(); + QString myLastDir = myQSettings.value( QStringLiteral( "lastRasterFileFilterDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getOpenFileName( this, tr( "Open file" ), myLastDir, tr( "Textfile" ) + " (*.txt)" ); QFile myInputFile( myFileName ); if ( myInputFile.open( QFile::ReadOnly ) ) @@ -1730,7 +1730,7 @@ void QgsRasterLayerProperties::saveDefaultStyle_clicked() void QgsRasterLayerProperties::loadStyle_clicked() { QSettings settings; - QString lastUsedDir = settings.value( "style/lastStyleDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, @@ -1741,8 +1741,8 @@ void QgsRasterLayerProperties::loadStyle_clicked() return; // ensure the user never omits the extension from the file name - if ( !fileName.endsWith( ".qml", Qt::CaseInsensitive ) ) - fileName += ".qml"; + if ( !fileName.endsWith( QLatin1String( ".qml" ), Qt::CaseInsensitive ) ) + fileName += QLatin1String( ".qml" ); mOldStyle = mRasterLayer->styleManager()->style( mRasterLayer->styleManager()->currentStyle() ); @@ -1750,7 +1750,7 @@ void QgsRasterLayerProperties::loadStyle_clicked() QString message = mRasterLayer->loadNamedStyle( fileName, defaultLoadedFlag ); if ( defaultLoadedFlag ) { - settings.setValue( "style/lastStyleDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "style/lastStyleDir" ), QFileInfo( fileName ).absolutePath() ); syncToLayer(); } else @@ -1763,7 +1763,7 @@ void QgsRasterLayerProperties::loadStyle_clicked() void QgsRasterLayerProperties::saveStyleAs_clicked() { QSettings settings; - QString lastUsedDir = settings.value( "style/lastStyleDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString(); QString outputFileName = QFileDialog::getSaveFileName( this, @@ -1774,15 +1774,15 @@ void QgsRasterLayerProperties::saveStyleAs_clicked() return; // ensure the user never omits the extension from the file name - if ( !outputFileName.endsWith( ".qml", Qt::CaseInsensitive ) ) - outputFileName += ".qml"; + if ( !outputFileName.endsWith( QLatin1String( ".qml" ), Qt::CaseInsensitive ) ) + outputFileName += QLatin1String( ".qml" ); apply(); // make sure the style to save is uptodate bool defaultLoadedFlag = false; QString message = mRasterLayer->saveNamedStyle( outputFileName, defaultLoadedFlag ); if ( defaultLoadedFlag ) - settings.setValue( "style/lastStyleDir", QFileInfo( outputFileName ).absolutePath() ); + settings.setValue( QStringLiteral( "style/lastStyleDir" ), QFileInfo( outputFileName ).absolutePath() ); else QMessageBox::information( this, tr( "Saved Style" ), message ); } @@ -1821,7 +1821,7 @@ void QgsRasterLayerProperties::onCancel() { // need to reset style to previous - style applied directly to the layer (not in apply()) QString myMessage; - QDomDocument doc( "qgis" ); + QDomDocument doc( QStringLiteral( "qgis" ) ); int errorLine, errorColumn; doc.setContent( mOldStyle.xmlData(), false, &myMessage, &errorLine, &errorColumn ); mRasterLayer->importNamedStyle( doc, myMessage ); diff --git a/src/app/qgsrelationadddlg.cpp b/src/app/qgsrelationadddlg.cpp index 55e19e1d2af4..648411d893da 100644 --- a/src/app/qgsrelationadddlg.cpp +++ b/src/app/qgsrelationadddlg.cpp @@ -35,8 +35,8 @@ QgsRelationAddDlg::QgsRelationAddDlg( QWidget *parent ) void QgsRelationAddDlg::addLayers( const QList< QgsVectorLayer* >& layers ) { - mCbxReferencingLayer->addItem( "", "" ); - mCbxReferencedLayer->addItem( "", "" ); + mCbxReferencingLayer->addItem( QLatin1String( "" ), "" ); + mCbxReferencedLayer->addItem( QLatin1String( "" ), "" ); Q_FOREACH ( QgsVectorLayer* layer, layers ) { diff --git a/src/app/qgsrelationmanagerdialog.cpp b/src/app/qgsrelationmanagerdialog.cpp index 04314ada37cc..a707c58dfdb3 100644 --- a/src/app/qgsrelationmanagerdialog.cpp +++ b/src/app/qgsrelationmanagerdialog.cpp @@ -90,8 +90,8 @@ void QgsRelationManagerDialog::on_mBtnAddRelation_clicked() relation.setReferencingLayer( addDlg.referencingLayerId() ); relation.setReferencedLayer( addDlg.referencedLayerId() ); QString relationId = addDlg.relationId(); - if ( addDlg.relationId() == "" ) - relationId = QString( "%1_%2_%3_%4" ) + if ( addDlg.relationId() == QLatin1String( "" ) ) + relationId = QStringLiteral( "%1_%2_%3_%4" ) .arg( addDlg.referencingLayerId(), addDlg.references().at( 0 ).first, addDlg.referencedLayerId(), diff --git a/src/app/qgsrulebasedlabelingwidget.cpp b/src/app/qgsrulebasedlabelingwidget.cpp index 2b381b6bf730..c7aa3d84cb31 100644 --- a/src/app/qgsrulebasedlabelingwidget.cpp +++ b/src/app/qgsrulebasedlabelingwidget.cpp @@ -60,7 +60,7 @@ QgsRuleBasedLabelingWidget::QgsRuleBasedLabelingWidget( QgsVectorLayer* layer, Q connect( mPasteAction, SIGNAL( triggered( bool ) ), this, SLOT( paste() ) ); connect( mDeleteAction, SIGNAL( triggered( bool ) ), this, SLOT( removeRule() ) ); - if ( mLayer->labeling() && mLayer->labeling()->type() == "rule-based" ) + if ( mLayer->labeling() && mLayer->labeling()->type() == QLatin1String( "rule-based" ) ) { const QgsRuleBasedLabeling* rl = static_cast( mLayer->labeling() ); mRootRule = rl->rootRule()->clone(); @@ -86,7 +86,7 @@ QgsRuleBasedLabelingWidget::~QgsRuleBasedLabelingWidget() void QgsRuleBasedLabelingWidget::writeSettingsToLayer() { // also clear old-style labeling config - mLayer->removeCustomProperty( "labeling" ); + mLayer->removeCustomProperty( QStringLiteral( "labeling" ) ); mLayer->setLabeling( new QgsRuleBasedLabeling( mRootRule->clone() ) ); } @@ -202,7 +202,7 @@ static QString _formatScale( int denom ) { if ( denom != 0 ) { - QString txt = QString( "1:%L1" ).arg( denom ); + QString txt = QStringLiteral( "1:%L1" ).arg( denom ); return txt; } else @@ -418,7 +418,7 @@ Qt::DropActions QgsRuleBasedLabelingModel::supportedDropActions() const QStringList QgsRuleBasedLabelingModel::mimeTypes() const { QStringList types; - types << "application/vnd.text.list"; + types << QStringLiteral( "application/vnd.text.list" ); return types; } @@ -426,15 +426,15 @@ QStringList QgsRuleBasedLabelingModel::mimeTypes() const void _renderer2labelingRules( QDomElement& ruleElem ) { // labeling rules recognize only "description" - if ( ruleElem.hasAttribute( "label" ) ) - ruleElem.setAttribute( "description", ruleElem.attribute( "label" ) ); + if ( ruleElem.hasAttribute( QStringLiteral( "label" ) ) ) + ruleElem.setAttribute( QStringLiteral( "description" ), ruleElem.attribute( QStringLiteral( "label" ) ) ); // run recursively - QDomElement childRuleElem = ruleElem.firstChildElement( "rule" ); + QDomElement childRuleElem = ruleElem.firstChildElement( QStringLiteral( "rule" ) ); while ( !childRuleElem.isNull() ) { _renderer2labelingRules( childRuleElem ); - childRuleElem = childRuleElem.nextSiblingElement( "rule" ); + childRuleElem = childRuleElem.nextSiblingElement( QStringLiteral( "rule" ) ); } } @@ -456,8 +456,8 @@ QMimeData*QgsRuleBasedLabelingModel::mimeData( const QModelIndexList& indexes ) QgsRuleBasedLabeling::Rule* rule = ruleForIndex( index )->clone(); QDomDocument doc; - QDomElement rootElem = doc.createElement( "rule_mime" ); - rootElem.setAttribute( "type", "labeling" ); // for determining whether rules are from renderer or labeling + QDomElement rootElem = doc.createElement( QStringLiteral( "rule_mime" ) ); + rootElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "labeling" ) ); // for determining whether rules are from renderer or labeling QDomElement rulesElem = rule->save( doc ); rootElem.appendChild( rulesElem ); doc.appendChild( rootElem ); @@ -467,7 +467,7 @@ QMimeData*QgsRuleBasedLabelingModel::mimeData( const QModelIndexList& indexes ) stream << doc.toString( -1 ); } - mimeData->setData( "application/vnd.text.list", encodedData ); + mimeData->setData( QStringLiteral( "application/vnd.text.list" ), encodedData ); return mimeData; } @@ -478,13 +478,13 @@ bool QgsRuleBasedLabelingModel::dropMimeData( const QMimeData* data, Qt::DropAct if ( action == Qt::IgnoreAction ) return true; - if ( !data->hasFormat( "application/vnd.text.list" ) ) + if ( !data->hasFormat( QStringLiteral( "application/vnd.text.list" ) ) ) return false; if ( parent.column() > 0 ) return false; - QByteArray encodedData = data->data( "application/vnd.text.list" ); + QByteArray encodedData = data->data( QStringLiteral( "application/vnd.text.list" ) ); QDataStream stream( &encodedData, QIODevice::ReadOnly ); int rows = 0; @@ -503,10 +503,10 @@ bool QgsRuleBasedLabelingModel::dropMimeData( const QMimeData* data, Qt::DropAct if ( !doc.setContent( text ) ) continue; QDomElement rootElem = doc.documentElement(); - if ( rootElem.tagName() != "rule_mime" ) + if ( rootElem.tagName() != QLatin1String( "rule_mime" ) ) continue; - QDomElement ruleElem = rootElem.firstChildElement( "rule" ); - if ( rootElem.attribute( "type" ) == "renderer" ) + QDomElement ruleElem = rootElem.firstChildElement( QStringLiteral( "rule" ) ); + if ( rootElem.attribute( QStringLiteral( "type" ) ) == QLatin1String( "renderer" ) ) _renderer2labelingRules( ruleElem ); // do some modifications so that we load the rules more nicely QgsRuleBasedLabeling::Rule* rule = QgsRuleBasedLabeling::Rule::create( ruleElem ); @@ -704,7 +704,7 @@ void QgsLabelingRulePropsWidget::buildExpression() } context << QgsExpressionContextUtils::layerScope( mLayer ); - QgsExpressionBuilderDialog dlg( mLayer, editFilter->text(), this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, editFilter->text(), this, QStringLiteral( "generic" ), context ); if ( dlg.exec() ) editFilter->setText( dlg.expressionText() ); diff --git a/src/app/qgssavestyletodbdialog.cpp b/src/app/qgssavestyletodbdialog.cpp index 4152d6696eaf..14f636d7960f 100644 --- a/src/app/qgssavestyletodbdialog.cpp +++ b/src/app/qgssavestyletodbdialog.cpp @@ -25,20 +25,20 @@ QgsSaveStyleToDbDialog::QgsSaveStyleToDbDialog( QWidget *parent ) : QDialog( parent ) { setupUi( this ); - setWindowTitle( "Save style in database" ); + setWindowTitle( QStringLiteral( "Save style in database" ) ); mDescriptionEdit->setTabChangesFocus( true ); setTabOrder( mNameEdit, mDescriptionEdit ); setTabOrder( mDescriptionEdit, mUseAsDefault ); setTabOrder( mUseAsDefault, buttonBox ); QSettings settings; - restoreGeometry( settings.value( "/Windows/saveStyleToDb/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/saveStyleToDb/geometry" ) ).toByteArray() ); } QgsSaveStyleToDbDialog::~QgsSaveStyleToDbDialog() { QSettings settings; - settings.setValue( "/Windows/saveStyleToDb/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/saveStyleToDb/geometry" ), saveGeometry() ); } QString QgsSaveStyleToDbDialog::getName() @@ -74,7 +74,7 @@ void QgsSaveStyleToDbDialog::accept() void QgsSaveStyleToDbDialog::on_mFilePickButton_clicked() { QSettings myQSettings; // where we keep last used filter in persistent state - QString myLastUsedDir = myQSettings.value( "style/lastStyleDir", QDir::homePath() ).toString(); + QString myLastUsedDir = myQSettings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getOpenFileName( this, tr( "Attach Qt Designer UI file" ), myLastUsedDir, tr( "Qt Designer UI file .ui" ) + " (*.ui)" ); if ( myFileName.isNull() ) @@ -85,14 +85,14 @@ void QgsSaveStyleToDbDialog::on_mFilePickButton_clicked() QFile uiFile( myFI.filePath() ); QString myPath = myFI.path(); - myQSettings.setValue( "style/lastStyleDir", myPath ); + myQSettings.setValue( QStringLiteral( "style/lastStyleDir" ), myPath ); if ( uiFile.open( QIODevice::ReadOnly ) ) { QString content( uiFile.readAll() ); QDomDocument doc; - if ( !doc.setContent( content ) || doc.documentElement().tagName().compare( "ui" ) ) + if ( !doc.setContent( content ) || doc.documentElement().tagName().compare( QLatin1String( "ui" ) ) ) { QMessageBox::warning( this, tr( "Wrong file" ), tr( "The selected file does not appear to be a valid Qt Designer UI file." ) ); diff --git a/src/app/qgsselectbyformdialog.cpp b/src/app/qgsselectbyformdialog.cpp index fc57edc5c02c..c7536f204c1f 100644 --- a/src/app/qgsselectbyformdialog.cpp +++ b/src/app/qgsselectbyformdialog.cpp @@ -38,7 +38,7 @@ QgsSelectByFormDialog::QgsSelectByFormDialog( QgsVectorLayer* layer, const QgsAt connect( mForm, SIGNAL( closed() ), this, SLOT( close() ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/SelectByForm/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/SelectByForm/geometry" ) ).toByteArray() ); setWindowTitle( tr( "Select features by value" ) ); } @@ -46,7 +46,7 @@ QgsSelectByFormDialog::QgsSelectByFormDialog( QgsVectorLayer* layer, const QgsAt QgsSelectByFormDialog::~QgsSelectByFormDialog() { QSettings settings; - settings.setValue( "/Windows/SelectByForm/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/SelectByForm/geometry" ), saveGeometry() ); } void QgsSelectByFormDialog::setMessageBar( QgsMessageBar* messageBar ) diff --git a/src/app/qgssettingstree.cpp b/src/app/qgssettingstree.cpp index 56b8f50c41e9..19c1ced67f4b 100644 --- a/src/app/qgssettingstree.cpp +++ b/src/app/qgssettingstree.cpp @@ -192,8 +192,8 @@ void QgsSettingsTree::updateChildItems( QTreeWidgetItem *parent ) if ( childIndex != -1 ) { child = childAt( parent, childIndex ); - child->setText( 1, "" ); - child->setText( 2, "" ); + child->setText( 1, QLatin1String( "" ) ); + child->setText( 2, QLatin1String( "" ) ); child->setData( 2, Qt::UserRole, QVariant() ); moveItemForward( parent, childIndex, dividerIndex ); } @@ -238,7 +238,7 @@ void QgsSettingsTree::updateChildItems( QTreeWidgetItem *parent ) QVariant value = settings->value( key ); if ( value.type() == QVariant::Invalid ) { - child->setText( 1, "Invalid" ); + child->setText( 1, QStringLiteral( "Invalid" ) ); } else { diff --git a/src/app/qgssnappinglayertreemodel.cpp b/src/app/qgssnappinglayertreemodel.cpp index 0469ef3d0eaa..21c689e2f93f 100644 --- a/src/app/qgssnappinglayertreemodel.cpp +++ b/src/app/qgssnappinglayertreemodel.cpp @@ -40,9 +40,9 @@ QWidget* QgsSnappingLayerDelegate::createEditor( QWidget* parent, const QStyleOp if ( index.column() == QgsSnappingLayerTreeModel::TypeColumn ) { QComboBox* w = new QComboBox( parent ); - w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertex.svg" ) ), "Vertex", QgsSnappingConfig::Vertex ); - w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertexAndSegment.svg" ) ), "Vertex and segment", QgsSnappingConfig::VertexAndSegment ); - w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingSegment.svg" ) ), "Segment", QgsSnappingConfig::Segment ); + w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertex.svg" ) ), QStringLiteral( "Vertex" ), QgsSnappingConfig::Vertex ); + w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertexAndSegment.svg" ) ), QStringLiteral( "Vertex and segment" ), QgsSnappingConfig::VertexAndSegment ); + w->addItem( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingSegment.svg" ) ), QStringLiteral( "Segment" ), QgsSnappingConfig::Segment ); return w; } diff --git a/src/app/qgssnappingwidget.cpp b/src/app/qgssnappingwidget.cpp index 9d77e3d6f6fd..fc4f68be46ce 100644 --- a/src/app/qgssnappingwidget.cpp +++ b/src/app/qgssnappingwidget.cpp @@ -55,7 +55,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, if ( tb ) { mDisplayMode = ToolBar; - setObjectName( "SnappingOptionToolBar" ); + setObjectName( QStringLiteral( "SnappingOptionToolBar" ) ); } else { @@ -63,12 +63,12 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, if ( sb ) { mDisplayMode = StatusBar; - setObjectName( "SnappingOptionStatusBar" ); + setObjectName( QStringLiteral( "SnappingOptionStatusBar" ) ); } else { mDisplayMode = Widget; - setObjectName( "SnappingOptionDialog" ); + setObjectName( QStringLiteral( "SnappingOptionDialog" ) ); } } @@ -77,7 +77,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mEnabledAction->setCheckable( true ); mEnabledAction->setIcon( QIcon( QgsApplication::getThemeIcon( "/mIconSnapping.svg" ) ) ); mEnabledAction->setToolTip( tr( "Enable snapping" ) ); - mEnabledAction->setObjectName( "EnableSnappingAction" ); + mEnabledAction->setObjectName( QStringLiteral( "EnableSnappingAction" ) ); connect( mEnabledAction, SIGNAL( toggled( bool ) ) , this, SLOT( enableSnapping( bool ) ) ); // mode button @@ -85,14 +85,14 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mModeButton->setToolTip( tr( "Snapping mode" ) ); mModeButton->setPopupMode( QToolButton::InstantPopup ); QMenu *modeMenu = new QMenu( tr( "Set snapping mode" ), this ); - mAllLayersAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingAllLayers.svg" ) ), "All layers", modeMenu ); - mActiveLayerAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingActiveLayer.svg" ) ), "Active layer", modeMenu ); - mAdvancedModeAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingAdvanced.svg" ) ), "Advanced configuration", modeMenu ); + mAllLayersAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingAllLayers.svg" ) ), QStringLiteral( "All layers" ), modeMenu ); + mActiveLayerAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingActiveLayer.svg" ) ), QStringLiteral( "Active layer" ), modeMenu ); + mAdvancedModeAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingAdvanced.svg" ) ), QStringLiteral( "Advanced configuration" ), modeMenu ); modeMenu->addAction( mAllLayersAction ); modeMenu->addAction( mActiveLayerAction ); modeMenu->addAction( mAdvancedModeAction ); mModeButton->setMenu( modeMenu ); - mModeButton->setObjectName( "SnappingModeButton" ); + mModeButton->setObjectName( QStringLiteral( "SnappingModeButton" ) ); if ( mDisplayMode == Widget ) { mModeButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); @@ -104,14 +104,14 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mTypeButton->setToolTip( tr( "Snapping type" ) ); mTypeButton->setPopupMode( QToolButton::InstantPopup ); QMenu *typeMenu = new QMenu( tr( "Set snapping mode" ), this ); - mVertexAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertex.svg" ) ), "Vertex", typeMenu ); - mVertexAndSegmentAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertexAndSegment.svg" ) ), "Vertex and segment", typeMenu ); - mSegmentAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingSegment.svg" ) ), "Segment", typeMenu ); + mVertexAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertex.svg" ) ), QStringLiteral( "Vertex" ), typeMenu ); + mVertexAndSegmentAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingVertexAndSegment.svg" ) ), QStringLiteral( "Vertex and segment" ), typeMenu ); + mSegmentAction = new QAction( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingSegment.svg" ) ), QStringLiteral( "Segment" ), typeMenu ); typeMenu->addAction( mVertexAction ); typeMenu->addAction( mVertexAndSegmentAction ); typeMenu->addAction( mSegmentAction ); mTypeButton->setMenu( typeMenu ); - mTypeButton->setObjectName( "SnappingTypeButton" ); + mTypeButton->setObjectName( QStringLiteral( "SnappingTypeButton" ) ); if ( mDisplayMode == Widget ) { mTypeButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); @@ -121,7 +121,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, // tolerance mToleranceSpinBox = new QDoubleSpinBox(); mToleranceSpinBox->setToolTip( tr( "Snapping tolerance in defined units" ) ); - mToleranceSpinBox->setObjectName( "SnappingToleranceSpinBox" ); + mToleranceSpinBox->setObjectName( QStringLiteral( "SnappingToleranceSpinBox" ) ); connect( mToleranceSpinBox, SIGNAL( valueChanged( double ) ), this, SLOT( changeTolerance( double ) ) ); // units @@ -129,7 +129,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mUnitsComboBox->addItem( tr( "px" ), QgsTolerance::Pixels ); mUnitsComboBox->addItem( QgsUnitTypes::toString( QgsProject::instance()->distanceUnits() ), QgsTolerance::ProjectUnits ); mUnitsComboBox->setToolTip( tr( "Snapping unit type: pixels (px) or map units (mu)" ) ); - mUnitsComboBox->setObjectName( "SnappingUnitComboBox" ); + mUnitsComboBox->setObjectName( QStringLiteral( "SnappingUnitComboBox" ) ); connect( mUnitsComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( changeUnit( int ) ) ); // topological editing button @@ -137,7 +137,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mTopologicalEditingAction->setCheckable( true ); mTopologicalEditingAction->setIcon( QIcon( QgsApplication::getThemeIcon( "/mIconTopologicalEditing.svg" ) ) ); mTopologicalEditingAction->setToolTip( tr( "Enable topological editing" ) ); - mTopologicalEditingAction->setObjectName( "TopologicalEditingAction" ); + mTopologicalEditingAction->setObjectName( QStringLiteral( "TopologicalEditingAction" ) ); connect( mTopologicalEditingAction, SIGNAL( toggled( bool ) ) , this, SLOT( enableTopologicalEditing( bool ) ) ); // snapping on intersection button @@ -145,7 +145,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mIntersectionSnappingAction->setCheckable( true ); mIntersectionSnappingAction->setIcon( QIcon( QgsApplication::getThemeIcon( "/mIconSnappingIntersection.svg" ) ) ); mIntersectionSnappingAction->setToolTip( tr( "Enable snapping on intersection" ) ); - mIntersectionSnappingAction->setObjectName( "IntersectionSnappingAction" ); + mIntersectionSnappingAction->setObjectName( QStringLiteral( "IntersectionSnappingAction" ) ); connect( mIntersectionSnappingAction, SIGNAL( toggled( bool ) ) , this, SLOT( enableIntersectionSnapping( bool ) ) ); // layout @@ -239,7 +239,7 @@ QgsSnappingWidget::~QgsSnappingWidget() { if ( mDisplayMode == Widget ) { - QSettings().setValue( "/Windows/SnappingWidget/geometry", saveGeometry() ); + QSettings().setValue( QStringLiteral( "/Windows/SnappingWidget/geometry" ), saveGeometry() ); } } diff --git a/src/app/qgssponsors.cpp b/src/app/qgssponsors.cpp index 123f0ef7623a..6d43cc7bcef5 100644 --- a/src/app/qgssponsors.cpp +++ b/src/app/qgssponsors.cpp @@ -45,11 +45,11 @@ QgsSponsors::QgsSponsors( QWidget *parent ) "financially - a great big 'thank you' to you all!

                                                                                                                                                                                    " ); txtSponsors->setText( intro ); // read the SPONSORS file and populate the text widget - QFile sponsorsFile( QgsApplication::pkgDataPath() + QLatin1String( "/doc/release-sponsors.html" ) ); + QFile sponsorsFile( QgsApplication::pkgDataPath() + QStringLiteral( "/doc/release-sponsors.html" ) ); if ( sponsorsFile.open( QIODevice::ReadOnly ) ) { - QString path = "images/"; - QString newPath = QgsApplication::pkgDataPath() + QLatin1String( "/doc/images/" ); + QString path = QStringLiteral( "images/" ); + QString newPath = QgsApplication::pkgDataPath() + QStringLiteral( "/doc/images/" ); QTextStream sponsorsStream( &sponsorsFile ); // Always use UTF-8 sponsorsStream.setCodec( "UTF-8" ); diff --git a/src/app/qgsstatisticalsummarydockwidget.cpp b/src/app/qgsstatisticalsummarydockwidget.cpp index 0230b78b67cf..81bb31dafb05 100644 --- a/src/app/qgsstatisticalsummarydockwidget.cpp +++ b/src/app/qgsstatisticalsummarydockwidget.cpp @@ -96,7 +96,7 @@ QgsStatisticalSummaryDockWidget::QgsStatisticalSummaryDockWidget( QWidget *paren { QAction* action = new QAction( QgsStatisticalSummary::displayName( stat ), mOptionsToolButton ); action->setCheckable( true ); - bool checked = settings.value( QString( "/StatisticalSummaryDock/checked_%1" ).arg( stat ), true ).toBool(); + bool checked = settings.value( QStringLiteral( "/StatisticalSummaryDock/checked_%1" ).arg( stat ), true ).toBool(); action->setChecked( checked ); action->setData( stat ); mStatsActions.insert( stat, action ); @@ -107,7 +107,7 @@ QgsStatisticalSummaryDockWidget::QgsStatisticalSummaryDockWidget( QWidget *paren //count of null values statistic: QAction* nullCountAction = new QAction( tr( "Missing (null) values" ), mOptionsToolButton ); nullCountAction->setCheckable( true ); - bool checked = settings.value( QString( "/StatisticalSummaryDock/checked_missing_values" ), true ).toBool(); + bool checked = settings.value( QStringLiteral( "/StatisticalSummaryDock/checked_missing_values" ), true ).toBool(); nullCountAction->setChecked( checked ); nullCountAction->setData( MISSING_VALUES ); mStatsActions.insert( MISSING_VALUES, nullCountAction ); @@ -282,11 +282,11 @@ void QgsStatisticalSummaryDockWidget::statActionTriggered( bool checked ) QSettings settings; if ( stat >= 0 ) { - settings.setValue( QString( "/StatisticalSummaryDock/checked_%1" ).arg( stat ), checked ); + settings.setValue( QStringLiteral( "/StatisticalSummaryDock/checked_%1" ).arg( stat ), checked ); } else if ( stat == MISSING_VALUES ) { - settings.setValue( QString( "/StatisticalSummaryDock/checked_missing_values" ).arg( stat ), checked ); + settings.setValue( QStringLiteral( "/StatisticalSummaryDock/checked_missing_values" ).arg( stat ), checked ); } } diff --git a/src/app/qgsstatusbarcoordinateswidget.cpp b/src/app/qgsstatusbarcoordinateswidget.cpp index 69f2c4cd50c6..d6e15cfc01c6 100644 --- a/src/app/qgsstatusbarcoordinateswidget.cpp +++ b/src/app/qgsstatusbarcoordinateswidget.cpp @@ -37,7 +37,7 @@ QgsStatusBarCoordinatesWidget::QgsStatusBarCoordinatesWidget( QWidget *parent ) { // add a label to show current position mLabel = new QLabel( QString(), this ); - mLabel->setObjectName( "mCoordsLabel" ); + mLabel->setObjectName( QStringLiteral( "mCoordsLabel" ) ); mLabel->setMinimumWidth( 10 ); //mCoordsLabel->setMaximumHeight( 20 ); mLabel->setMargin( 3 ); @@ -64,7 +64,7 @@ QgsStatusBarCoordinatesWidget::QgsStatusBarCoordinatesWidget( QWidget *parent ) //toggle to switch between mouse pos and extents display in status bar widget mToggleExtentsViewButton = new QToolButton( this ); - mToggleExtentsViewButton->setIcon( QgsApplication::getThemeIcon( "tracking.svg" ) ); + mToggleExtentsViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "tracking.svg" ) ) ); mToggleExtentsViewButton->setToolTip( tr( "Toggle extents and mouse position display" ) ); mToggleExtentsViewButton->setCheckable( true ); mToggleExtentsViewButton->setAutoRaise( true ); @@ -116,7 +116,7 @@ void QgsStatusBarCoordinatesWidget::validateCoordinates() { return; } - if ( mLineEdit->text() == "dizzy" ) + if ( mLineEdit->text() == QLatin1String( "dizzy" ) ) { // sometimes you may feel a bit dizzy... if ( mDizzyTimer->isActive() ) @@ -131,7 +131,7 @@ void QgsStatusBarCoordinatesWidget::validateCoordinates() } return; } - else if ( mLineEdit->text() == "retro" ) + else if ( mLineEdit->text() == QLatin1String( "retro" ) ) { mMapCanvas->setProperty( "retro", !mMapCanvas->property( "retro" ).toBool() ); refreshMapCanvas(); @@ -142,7 +142,7 @@ void QgsStatusBarCoordinatesWidget::validateCoordinates() bool yOk = false; double x = 0., y = 0.; QString coordText = mLineEdit->text(); - coordText.replace( QRegExp( " {2,}" ), " " ); + coordText.replace( QRegExp( " {2,}" ), QStringLiteral( " " ) ); QStringList parts = coordText.split( ',' ); if ( parts.size() == 2 ) @@ -193,7 +193,7 @@ void QgsStatusBarCoordinatesWidget::extentsViewToggled( bool theFlag ) if ( theFlag ) { //extents view mode! - mToggleExtentsViewButton->setIcon( QgsApplication::getThemeIcon( "extents.svg" ) ); + mToggleExtentsViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "extents.svg" ) ) ); mLineEdit->setToolTip( tr( "Map coordinates for the current view extents" ) ); mLineEdit->setReadOnly( true ); showExtent(); @@ -201,7 +201,7 @@ void QgsStatusBarCoordinatesWidget::extentsViewToggled( bool theFlag ) else { //mouse cursor pos view mode! - mToggleExtentsViewButton->setIcon( QgsApplication::getThemeIcon( "tracking.svg" ) ); + mToggleExtentsViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "tracking.svg" ) ) ); mLineEdit->setToolTip( tr( "Map coordinates at mouse cursor position" ) ); mLineEdit->setReadOnly( false ); mLabel->setText( tr( "Coordinate:" ) ); diff --git a/src/app/qgsstatusbarmagnifierwidget.cpp b/src/app/qgsstatusbarmagnifierwidget.cpp index 0a3f971b907c..af83f0f29e20 100644 --- a/src/app/qgsstatusbarmagnifierwidget.cpp +++ b/src/app/qgsstatusbarmagnifierwidget.cpp @@ -27,9 +27,9 @@ QgsStatusBarMagnifierWidget::QgsStatusBarMagnifierWidget( QWidget* parent ) : QWidget( parent ) { QSettings settings; - int minimumFactor = ( int ) 100 * settings.value( "/qgis/magnifier_factor_min", 0.1 ).toDouble(); - int maximumFactor = ( int ) 100 * settings.value( "/qgis/magnifier_factor_max", 10 ).toDouble(); - int defaultFactor = ( int ) 100 * settings.value( "/qgis/magnifier_factor_default", 1.0 ).toDouble(); + int minimumFactor = ( int ) 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_min" ), 0.1 ).toDouble(); + int maximumFactor = ( int ) 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_max" ), 10 ).toDouble(); + int defaultFactor = ( int ) 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble(); // label mLabel = new QLabel(); @@ -41,7 +41,7 @@ QgsStatusBarMagnifierWidget::QgsStatusBarMagnifierWidget( QWidget* parent ) mLabel->setToolTip( tr( "Magnifier" ) ); mSpinBox = new QgsDoubleSpinBox(); - mSpinBox->setSuffix( "%" ); + mSpinBox->setSuffix( QStringLiteral( "%" ) ); mSpinBox->setKeyboardTracking( false ); mSpinBox->setMaximumWidth( 120 ); mSpinBox->setDecimals( 0 ); diff --git a/src/app/qgsstatusbarscalewidget.cpp b/src/app/qgsstatusbarscalewidget.cpp index f6cadfbab9e4..d860fcaee74c 100644 --- a/src/app/qgsstatusbarscalewidget.cpp +++ b/src/app/qgsstatusbarscalewidget.cpp @@ -31,7 +31,7 @@ QgsStatusBarScaleWidget::QgsStatusBarScaleWidget( QgsMapCanvas *canvas, QWidget { // add a label to show current scale mLabel = new QLabel(); - mLabel->setObjectName( "mScaleLabel" ); + mLabel->setObjectName( QStringLiteral( "mScaleLabel" ) ); mLabel->setMinimumWidth( 10 ); //mScaleLabel->setMaximumHeight( 20 ); mLabel->setMargin( 3 ); @@ -41,7 +41,7 @@ QgsStatusBarScaleWidget::QgsStatusBarScaleWidget( QgsMapCanvas *canvas, QWidget mLabel->setToolTip( tr( "Current map scale" ) ); mScale = new QgsScaleComboBox(); - mScale->setObjectName( "mScaleEdit" ); + mScale->setObjectName( QStringLiteral( "mScaleEdit" ) ); // seems setFont() change font only for popup not for line edit, // so we need to set font for it separately mScale->setMinimumWidth( 10 ); diff --git a/src/app/qgstextannotationdialog.cpp b/src/app/qgstextannotationdialog.cpp index d088e1b10da1..1e23c314f84a 100644 --- a/src/app/qgstextannotationdialog.cpp +++ b/src/app/qgstextannotationdialog.cpp @@ -37,7 +37,7 @@ QgsTextAnnotationDialog::QgsTextAnnotationDialog( QgsTextAnnotationItem* item, Q mFontColorButton->setColorDialogTitle( tr( "Select font color" ) ); mFontColorButton->setAllowAlpha( true ); - mFontColorButton->setContext( "symbology" ); + mFontColorButton->setContext( QStringLiteral( "symbology" ) ); setCurrentFontPropertiesToGui(); diff --git a/src/app/qgstipfactory.cpp b/src/app/qgstipfactory.cpp index a44aa682c4da..011194910578 100644 --- a/src/app/qgstipfactory.cpp +++ b/src/app/qgstipfactory.cpp @@ -157,7 +157,7 @@ QgsTipFactory::QgsTipFactory() : QObject() " intersecting lines together simply by enabling symbol levels." " The image below shows a before (left) and after (right) view of" " an intersection when symbol levels are enabled." ) + - QString( "

                                                                                                                                                                                    " ) + QStringLiteral( "

                                                                                                                                                                                    " ) ); addGuiTip( myTip ); // by Tim diff --git a/src/app/qgstipgui.cpp b/src/app/qgstipgui.cpp index da7389922a2c..7da96a0e5ee5 100644 --- a/src/app/qgstipgui.cpp +++ b/src/app/qgstipgui.cpp @@ -79,7 +79,7 @@ void QgsTipGui::on_cbxDisableTips_toggled( bool theFlag ) QSettings settings; //note the ! below as when the cbx is checked (true) we want to //change the setting to false - settings.setValue( QString( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), !theFlag ); + settings.setValue( QStringLiteral( "/qgis/showTips%1" ).arg( Qgis::QGIS_VERSION_INT / 100 ), !theFlag ); hide(); } diff --git a/src/app/qgsundowidget.cpp b/src/app/qgsundowidget.cpp index 836465f4a61b..d90ccfb4554c 100644 --- a/src/app/qgsundowidget.cpp +++ b/src/app/qgsundowidget.cpp @@ -135,7 +135,7 @@ void QgsUndoWidget::setUndoStack( QUndoStack* undoStack ) mUndoView = new QUndoView( dockWidgetContents ); mUndoView->setStack( undoStack ); - mUndoView->setObjectName( "undoView" ); + mUndoView->setObjectName( QStringLiteral( "undoView" ) ); gridLayout->addWidget( mUndoView, 0, 0, 1, 2 ); // setWidget( dockWidgetContents ); connect( mUndoStack, SIGNAL( canUndoChanged( bool ) ), this, SLOT( undoChanged( bool ) ) ); @@ -153,27 +153,27 @@ void QgsUndoWidget::setUndoStack( QUndoStack* undoStack ) void QgsUndoWidget::setupUi( QWidget *UndoWidget ) { if ( UndoWidget->objectName().isEmpty() ) - UndoWidget->setObjectName( QString::fromUtf8( "UndoWidget" ) ); + UndoWidget->setObjectName( QStringLiteral( "UndoWidget" ) ); UndoWidget->resize( 200, 223 ); UndoWidget->setMinimumSize( QSize( 200, 220 ) ); dockWidgetContents = new QWidget( UndoWidget ); - dockWidgetContents->setObjectName( QString::fromUtf8( "dockWidgetContents" ) ); + dockWidgetContents->setObjectName( QStringLiteral( "dockWidgetContents" ) ); gridLayout = new QGridLayout( dockWidgetContents ); - gridLayout->setObjectName( QString::fromUtf8( "gridLayout" ) ); + gridLayout->setObjectName( QStringLiteral( "gridLayout" ) ); gridLayout->setContentsMargins( 0, 0, 0, 0 ); spacerItem = new QSpacerItem( 20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding ); gridLayout->addItem( spacerItem, 0, 0, 1, 1 ); undoButton = new QPushButton( dockWidgetContents ); - undoButton->setObjectName( QString::fromUtf8( "undoButton" ) ); - undoButton->setIcon( QgsApplication::getThemeIcon( "mActionUndo.svg" ) ); + undoButton->setObjectName( QStringLiteral( "undoButton" ) ); + undoButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionUndo.svg" ) ) ); gridLayout->addWidget( undoButton, 1, 0, 1, 1 ); redoButton = new QPushButton( dockWidgetContents ); - redoButton->setObjectName( QString::fromUtf8( "redoButton" ) ); - redoButton->setIcon( QgsApplication::getThemeIcon( "mActionRedo.svg" ) ); + redoButton->setObjectName( QStringLiteral( "redoButton" ) ); + redoButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionRedo.svg" ) ) ); gridLayout->addWidget( redoButton, 1, 1, 1, 1 ); diff --git a/src/app/qgsvariantdelegate.cpp b/src/app/qgsvariantdelegate.cpp index 719fa0dd4d9f..3b907fcd2105 100644 --- a/src/app/qgsvariantdelegate.cpp +++ b/src/app/qgsvariantdelegate.cpp @@ -46,21 +46,21 @@ QgsVariantDelegate::QgsVariantDelegate( QObject* parent ) : QItemDelegate( parent ) { - mBoolExp.setPattern( "true|false" ); + mBoolExp.setPattern( QStringLiteral( "true|false" ) ); mBoolExp.setCaseSensitivity( Qt::CaseInsensitive ); - mByteArrayExp.setPattern( "[\\x00-\\xff]*" ); - mCharExp.setPattern( "." ); - mColorExp.setPattern( "\\(([0-9]*),([0-9]*),([0-9]*),([0-9]*)\\)" ); - mDoubleExp.setPattern( "" ); - mPointExp.setPattern( "\\((-?[0-9]*),(-?[0-9]*)\\)" ); - mRectExp.setPattern( "\\((-?[0-9]*),(-?[0-9]*),(-?[0-9]*),(-?[0-9]*)\\)" ); - mSignedIntegerExp.setPattern( "-?[0-9]*" ); + mByteArrayExp.setPattern( QStringLiteral( "[\\x00-\\xff]*" ) ); + mCharExp.setPattern( QStringLiteral( "." ) ); + mColorExp.setPattern( QStringLiteral( "\\(([0-9]*),([0-9]*),([0-9]*),([0-9]*)\\)" ) ); + mDoubleExp.setPattern( QLatin1String( "" ) ); + mPointExp.setPattern( QStringLiteral( "\\((-?[0-9]*),(-?[0-9]*)\\)" ) ); + mRectExp.setPattern( QStringLiteral( "\\((-?[0-9]*),(-?[0-9]*),(-?[0-9]*),(-?[0-9]*)\\)" ) ); + mSignedIntegerExp.setPattern( QStringLiteral( "-?[0-9]*" ) ); mSizeExp = mPointExp; - mUnsignedIntegerExp.setPattern( "[0-9]*" ); + mUnsignedIntegerExp.setPattern( QStringLiteral( "[0-9]*" ) ); - mDateExp.setPattern( "([0-9]{,4})-([0-9]{,2})-([0-9]{,2})" ); - mTimeExp.setPattern( "([0-9]{,2}):([0-9]{,2}):([0-9]{,2})" ); + mDateExp.setPattern( QStringLiteral( "([0-9]{,4})-([0-9]{,2})-([0-9]{,2})" ) ); + mTimeExp.setPattern( QStringLiteral( "([0-9]{,2}):([0-9]{,2}):([0-9]{,2})" ) ); mDateTimeExp.setPattern( mDateExp.pattern() + 'T' + mTimeExp.pattern() ); } @@ -288,7 +288,7 @@ QString QgsVariantDelegate::displayText( const QVariant& value ) case QVariant::Color: { QColor color = qvariant_cast( value ); - return QString( "(%1,%2,%3,%4)" ) + return QStringLiteral( "(%1,%2,%3,%4)" ) .arg( color.red() ).arg( color.green() ) .arg( color.blue() ).arg( color.alpha() ); } @@ -297,32 +297,32 @@ QString QgsVariantDelegate::displayText( const QVariant& value ) case QVariant::DateTime: return value.toDateTime().toString( Qt::ISODate ); case QVariant::Invalid: - return ""; + return QStringLiteral( "" ); case QVariant::Point: { QPoint point = value.toPoint(); - return QString( "(%1,%2)" ).arg( point.x() ).arg( point.y() ); + return QStringLiteral( "(%1,%2)" ).arg( point.x() ).arg( point.y() ); } case QVariant::Rect: { QRect rect = value.toRect(); - return QString( "(%1,%2,%3,%4)" ) + return QStringLiteral( "(%1,%2,%3,%4)" ) .arg( rect.x() ).arg( rect.y() ) .arg( rect.width() ).arg( rect.height() ); } case QVariant::Size: { QSize size = value.toSize(); - return QString( "(%1,%2)" ).arg( size.width() ).arg( size.height() ); + return QStringLiteral( "(%1,%2)" ).arg( size.width() ).arg( size.height() ); } case QVariant::StringList: - return value.toStringList().join( "," ); + return value.toStringList().join( QStringLiteral( "," ) ); case QVariant::Time: return value.toTime().toString( Qt::ISODate ); default: break; } - return QString( "<%1>" ).arg( value.toString() ); + return QStringLiteral( "<%1>" ).arg( value.toString() ); } @@ -336,7 +336,7 @@ QVariant::Type QgsVariantDelegate::type( const QVariant& value ) bool ok; // is this a bool (true,false) - regExp.setPattern( "true|false" ); + regExp.setPattern( QStringLiteral( "true|false" ) ); regExp.setCaseSensitivity( Qt::CaseInsensitive ); if ( regExp.indexIn( str ) != -1 ) return QVariant::Bool; diff --git a/src/app/qgsvectorlayerproperties.cpp b/src/app/qgsvectorlayerproperties.cpp index 9a371dbd3d11..a69813ed401d 100644 --- a/src/app/qgsvectorlayerproperties.cpp +++ b/src/app/qgsvectorlayerproperties.cpp @@ -75,7 +75,7 @@ QgsVectorLayerProperties::QgsVectorLayerProperties( QWidget * parent, Qt::WindowFlags fl ) - : QgsOptionsDialogBase( "VectorLayerProperties", parent, fl ) + : QgsOptionsDialogBase( QStringLiteral( "VectorLayerProperties" ), parent, fl ) , mLayer( lyr ) , mMetadataFilled( false ) , mOriginalSubsetSQL( lyr->subsetString() ) @@ -209,7 +209,7 @@ QgsVectorLayerProperties::QgsVectorLayerProperties( } cboProviderEncoding->setCurrentIndex( encindex ); } - else if ( mLayer->dataProvider()->name() == "ogr" ) + else if ( mLayer->dataProvider()->name() == QLatin1String( "ogr" ) ) { // if OGR_L_TestCapability(OLCStringsAsUTF8) returns true, OGR provider encoding can be set to only UTF-8 // so make encoding box grayed out @@ -284,9 +284,9 @@ QgsVectorLayerProperties::QgsVectorLayerProperties( QSettings settings; // if dialog hasn't been opened/closed yet, default to Styles tab, which is used most often // this will be read by restoreOptionsBaseUi() - if ( !settings.contains( QString( "/Windows/VectorLayerProperties/tab" ) ) ) + if ( !settings.contains( QStringLiteral( "/Windows/VectorLayerProperties/tab" ) ) ) { - settings.setValue( QString( "/Windows/VectorLayerProperties/tab" ), + settings.setValue( QStringLiteral( "/Windows/VectorLayerProperties/tab" ), mOptStackedWidget->indexOf( mOptsPage_Style ) ); } @@ -356,9 +356,9 @@ void QgsVectorLayerProperties::insertFieldOrExpression() { // Convert the selected field to an expression and // insert it into the action at the cursor position - QString expression = "[% \""; + QString expression = QStringLiteral( "[% \"" ); expression += mMapTipExpressionFieldWidget->asExpression(); - expression += "\" %]"; + expression += QLatin1String( "\" %]" ); mMapTipWidget->insertText( expression ); } @@ -400,7 +400,7 @@ void QgsVectorLayerProperties::syncToLayer() mSimplifyDrawingGroupBox->setChecked( simplifyMethod.simplifyHints() != QgsVectorSimplifyMethod::NoSimplification ); mSimplifyDrawingSpinBox->setValue( simplifyMethod.threshold() ); - QString remark = QString( " (%1)" ).arg( tr( "Not supported" ) ); + QString remark = QStringLiteral( " (%1)" ).arg( tr( "Not supported" ) ); if ( !( mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::SimplifyGeometries ) ) { mSimplifyDrawingAtProvider->setChecked( false ); @@ -434,7 +434,7 @@ void QgsVectorLayerProperties::syncToLayer() mSimplifyAlgorithmComboBox->setCurrentIndex( mSimplifyAlgorithmComboBox->findData(( int )simplifyMethod.simplifyAlgorithm() ) ); QStringList myScalesList = PROJECT_SCALES.split( ',' ); - myScalesList.append( "1:1" ); + myScalesList.append( QStringLiteral( "1:1" ) ); mSimplifyMaximumScaleComboBox->updateScales( myScalesList ); mSimplifyMaximumScaleComboBox->setScale( 1.0 / simplifyMethod.maximumScale() ); @@ -629,7 +629,7 @@ void QgsVectorLayerProperties::onCancel() { // need to reset style to previous - style applied directly to the layer (not in apply()) QString myMessage; - QDomDocument doc( "qgis" ); + QDomDocument doc( QStringLiteral( "qgis" ) ); int errorLine, errorColumn; doc.setContent( mOldStyle.xmlData(), false, &myMessage, &errorLine, &errorColumn ); mLayer->importNamedStyle( doc, myMessage ); @@ -769,7 +769,7 @@ void QgsVectorLayerProperties::saveDefaultStyle_clicked() case 0: return; case 2: - mLayer->saveStyleToDatabase( "", "", true, "", errorMsg ); + mLayer->saveStyleToDatabase( QLatin1String( "" ), QLatin1String( "" ), true, QLatin1String( "" ), errorMsg ); if ( errorMsg.isNull() ) { return; @@ -792,7 +792,7 @@ void QgsVectorLayerProperties::saveDefaultStyle_clicked() void QgsVectorLayerProperties::loadStyle_clicked() { QSettings myQSettings; // where we keep last used filter in persistent state - QString myLastUsedDir = myQSettings.value( "style/lastStyleDir", QDir::homePath() ).toString(); + QString myLastUsedDir = myQSettings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getOpenFileName( this, tr( "Load layer properties from style file" ), myLastUsedDir, tr( "QGIS Layer Style File" ) + " (*.qml);;" + tr( "SLD File" ) + " (*.sld)" ); @@ -806,7 +806,7 @@ void QgsVectorLayerProperties::loadStyle_clicked() QString myMessage; bool defaultLoadedFlag = false; - if ( myFileName.endsWith( ".sld", Qt::CaseInsensitive ) ) + if ( myFileName.endsWith( QLatin1String( ".sld" ), Qt::CaseInsensitive ) ) { // load from SLD myMessage = mLayer->loadSldStyle( myFileName, defaultLoadedFlag ); @@ -828,7 +828,7 @@ void QgsVectorLayerProperties::loadStyle_clicked() QFileInfo myFI( myFileName ); QString myPath = myFI.path(); - myQSettings.setValue( "style/lastStyleDir", myPath ); + myQSettings.setValue( QStringLiteral( "style/lastStyleDir" ), myPath ); activateWindow(); // set focus back to properties dialog } @@ -855,7 +855,7 @@ void QgsVectorLayerProperties::saveStyleAsMenuTriggered( QAction *action ) void QgsVectorLayerProperties::saveStyleAs( StyleType styleType ) { QSettings myQSettings; // where we keep last used filter in persistent state - QString myLastUsedDir = myQSettings.value( "style/lastStyleDir", QDir::homePath() ).toString(); + QString myLastUsedDir = myQSettings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString(); if ( styleType == DB ) { @@ -897,12 +897,12 @@ void QgsVectorLayerProperties::saveStyleAs( StyleType styleType ) if ( styleType == SLD ) { format = tr( "SLD File" ) + " (*.sld)"; - extension = ".sld"; + extension = QStringLiteral( ".sld" ); } else { format = tr( "QGIS Layer Style File" ) + " (*.qml)"; - extension = ".qml"; + extension = QStringLiteral( ".qml" ); } QString myOutputFileName = QFileDialog::getSaveFileName( this, tr( "Save layer properties as style file" ), @@ -947,7 +947,7 @@ void QgsVectorLayerProperties::saveStyleAs( StyleType styleType ) QFileInfo myFI( myOutputFileName ); QString myPath = myFI.path(); // Persist last used dir - myQSettings.setValue( "style/lastStyleDir", myPath ); + myQSettings.setValue( QStringLiteral( "style/lastStyleDir" ), myPath ); } } @@ -1029,7 +1029,7 @@ void QgsVectorLayerProperties::showListOfStylesFromDatabase() return; } - QDomDocument myDocument( "qgis" ); + QDomDocument myDocument( QStringLiteral( "qgis" ) ); myDocument.setContent( qmlStyle ); if ( mLayer->importNamedStyle( myDocument, errorMsg ) ) @@ -1184,7 +1184,7 @@ void QgsVectorLayerProperties::addJoinToTreeWidget( const QgsVectorJoinInfo& joi const QStringList* list = join.joinFieldNamesSubset(); if ( list ) { - joinItem->setText( 5, QString( "%1" ).arg( list->count() ) ); + joinItem->setText( 5, QStringLiteral( "%1" ).arg( list->count() ) ); } else { @@ -1214,7 +1214,7 @@ QgsExpressionContext QgsVectorLayerProperties::createExpressionContext() const void QgsVectorLayerProperties::openPanel( QgsPanelWidget *panel ) { QDialog* dlg = new QDialog(); - QString key = QString( "/UI/paneldialog/%1" ).arg( panel->panelTitle() ); + QString key = QStringLiteral( "/UI/paneldialog/%1" ).arg( panel->panelTitle() ); QSettings settings; dlg->restoreGeometry( settings.value( key ).toByteArray() ); dlg->setWindowTitle( panel->panelTitle() ); diff --git a/src/app/qgsversioninfo.cpp b/src/app/qgsversioninfo.cpp index 2a29e50d1294..973289e67dfd 100644 --- a/src/app/qgsversioninfo.cpp +++ b/src/app/qgsversioninfo.cpp @@ -28,7 +28,7 @@ QgsVersionInfo::QgsVersionInfo( QObject *parent ) void QgsVersionInfo::checkVersion() { - QNetworkReply *reply = QgsNetworkAccessManager::instance()->get( QNetworkRequest( QUrl( "https://ubuntu.qgis.org/version.txt" ) ) ); + QNetworkReply *reply = QgsNetworkAccessManager::instance()->get( QNetworkRequest( QUrl( QStringLiteral( "https://ubuntu.qgis.org/version.txt" ) ) ) ); connect( reply, SIGNAL( finished() ), this, SLOT( versionReplyFinished() ) ); } @@ -55,7 +55,7 @@ void QgsVersionInfo::versionReplyFinished() QString versionMessage = reply->readAll(); // strip the header - QString contentFlag = "#QGIS Version"; + QString contentFlag = QStringLiteral( "#QGIS Version" ); int pos = versionMessage.indexOf( contentFlag ); if ( pos > -1 ) @@ -81,7 +81,7 @@ void QgsVersionInfo::versionReplyFinished() mErrorString = tr( "The host name %1 could not be resolved. Check your DNS settings or contact your system administrator." ).arg( reply->request().url().host() ); break; case QNetworkReply::NoError: - mErrorString = ""; + mErrorString = QLatin1String( "" ); break; default: mErrorString = reply->errorString(); diff --git a/src/app/qgswelcomepage.cpp b/src/app/qgswelcomepage.cpp index 1104dd656ead..59a9578949a1 100644 --- a/src/app/qgswelcomepage.cpp +++ b/src/app/qgswelcomepage.cpp @@ -41,7 +41,7 @@ QgsWelcomePage::QgsWelcomePage( bool skipVersionCheck, QWidget* parent ) QWidget* recentProjctsContainer = new QWidget; recentProjctsContainer->setLayout( new QVBoxLayout ); recentProjctsContainer->layout()->setContentsMargins( 3, 3, 3, 0 ); - QLabel* recentProjectsTitle = new QLabel( QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( tr( "Recent Projects" ) ) ); + QLabel* recentProjectsTitle = new QLabel( QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( tr( "Recent Projects" ) ) ); recentProjctsContainer->layout()->addWidget( recentProjectsTitle ); QListView* recentProjectsListView = new QListView(); @@ -60,7 +60,7 @@ QgsWelcomePage::QgsWelcomePage( bool skipVersionCheck, QWidget* parent ) mVersionInformation->setVisible( false ); mVersionInfo = new QgsVersionInfo(); - if ( !QgsApplication::isRunningFromBuildDir() && settings.value( "/qgis/checkVersion", true ).toBool() && !skipVersionCheck ) + if ( !QgsApplication::isRunningFromBuildDir() && settings.value( QStringLiteral( "/qgis/checkVersion" ), true ).toBool() && !skipVersionCheck ) { connect( mVersionInfo, SIGNAL( versionInfoAvailable() ), this, SLOT( versionInfoReceived() ) ); mVersionInfo->checkVersion(); @@ -92,7 +92,7 @@ void QgsWelcomePage::versionInfoReceived() if ( versionInfo->newVersionAvailable() ) { mVersionInformation->setVisible( true ); - mVersionInformation->setText( QString( "%1: %2" ) + mVersionInformation->setText( QStringLiteral( "%1: %2" ) .arg( tr( "There is a new QGIS version available" ), versionInfo->downloadInfo() ) ); mVersionInformation->setStyleSheet( "QLabel{" diff --git a/src/app/qgswelcomepageitemsmodel.cpp b/src/app/qgswelcomepageitemsmodel.cpp index ddafe69724f7..585f00fb75f6 100644 --- a/src/app/qgswelcomepageitemsmodel.cpp +++ b/src/app/qgswelcomepageitemsmodel.cpp @@ -72,7 +72,7 @@ void QgsWelcomePageItemDelegate::paint( QPainter* painter, const QStyleOptionVie int titleSize = QApplication::fontMetrics().height() * 1.1; int textSize = titleSize * 0.85; - doc.setHtml( QString( "
                                                                                                                                                                                    %3
                                                                                                                                                                                    %4
                                                                                                                                                                                    %5
                                                                                                                                                                                    " ).arg( textSize ).arg( titleSize ) + doc.setHtml( QStringLiteral( "
                                                                                                                                                                                    %3
                                                                                                                                                                                    %4
                                                                                                                                                                                    %5
                                                                                                                                                                                    " ).arg( textSize ).arg( titleSize ) .arg( index.data( QgsWelcomePageItemsModel::TitleRole ).toString(), index.data( QgsWelcomePageItemsModel::PathRole ).toString(), index.data( QgsWelcomePageItemsModel::CrsRole ).toString() ) ); @@ -108,7 +108,7 @@ QSize QgsWelcomePageItemDelegate::sizeHint( const QStyleOptionViewItem & option, int titleSize = QApplication::fontMetrics().height() * 1.1; int textSize = titleSize * 0.85; - doc.setHtml( QString( "
                                                                                                                                                                                    %3
                                                                                                                                                                                    %4
                                                                                                                                                                                    %5
                                                                                                                                                                                    " ).arg( textSize ).arg( titleSize ) + doc.setHtml( QStringLiteral( "
                                                                                                                                                                                    %3
                                                                                                                                                                                    %4
                                                                                                                                                                                    %5
                                                                                                                                                                                    " ).arg( textSize ).arg( titleSize ) .arg( index.data( QgsWelcomePageItemsModel::TitleRole ).toString(), index.data( QgsWelcomePageItemsModel::PathRole ).toString(), index.data( QgsWelcomePageItemsModel::CrsRole ).toString() ) ); @@ -147,10 +147,10 @@ QVariant QgsWelcomePageItemsModel::data( const QModelIndex& index, int role ) co case PathRole: return mRecentProjects.at( index.row() ).path; case CrsRole: - if ( mRecentProjects.at( index.row() ).crs != "" ) + if ( mRecentProjects.at( index.row() ).crs != QLatin1String( "" ) ) { QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mRecentProjects.at( index.row() ).crs ); - return QString( "%1 (%2)" ).arg( mRecentProjects.at( index.row() ).crs, crs.description() ); + return QStringLiteral( "%1 (%2)" ).arg( mRecentProjects.at( index.row() ).crs, crs.description() ); } else { diff --git a/src/auth/basic/qgsauthbasicedit.cpp b/src/auth/basic/qgsauthbasicedit.cpp index b13341333db0..980db3e28956 100644 --- a/src/auth/basic/qgsauthbasicedit.cpp +++ b/src/auth/basic/qgsauthbasicedit.cpp @@ -43,9 +43,9 @@ bool QgsAuthBasicEdit::validateConfig() QgsStringMap QgsAuthBasicEdit::configMap() const { QgsStringMap config; - config.insert( "username", leUsername->text() ); - config.insert( "password", lePassword->text() ); - config.insert( "realm", leRealm->text() ); + config.insert( QStringLiteral( "username" ), leUsername->text() ); + config.insert( QStringLiteral( "password" ), lePassword->text() ); + config.insert( QStringLiteral( "realm" ), leRealm->text() ); return config; } @@ -55,9 +55,9 @@ void QgsAuthBasicEdit::loadConfig( const QgsStringMap &configmap ) clearConfig(); mConfigMap = configmap; - leUsername->setText( configmap.value( "username" ) ); - lePassword->setText( configmap.value( "password" ) ); - leRealm->setText( configmap.value( "realm" ) ); + leUsername->setText( configmap.value( QStringLiteral( "username" ) ) ); + lePassword->setText( configmap.value( QStringLiteral( "password" ) ) ); + leRealm->setText( configmap.value( QStringLiteral( "realm" ) ) ); validateConfig(); } diff --git a/src/auth/basic/qgsauthbasicmethod.cpp b/src/auth/basic/qgsauthbasicmethod.cpp index 7552546a294b..069b413f6fb7 100644 --- a/src/auth/basic/qgsauthbasicmethod.cpp +++ b/src/auth/basic/qgsauthbasicmethod.cpp @@ -20,8 +20,8 @@ #include "qgsauthmanager.h" #include "qgslogger.h" -static const QString AUTH_METHOD_KEY = "Basic"; -static const QString AUTH_METHOD_DESCRIPTION = "Basic authentication"; +static const QString AUTH_METHOD_KEY = QStringLiteral( "Basic" ); +static const QString AUTH_METHOD_DESCRIPTION = QStringLiteral( "Basic authentication" ); QMap QgsAuthBasicMethod::mAuthConfigCache = QMap(); @@ -32,12 +32,12 @@ QgsAuthBasicMethod::QgsAuthBasicMethod() setVersion( 2 ); setExpansions( QgsAuthMethod::NetworkRequest | QgsAuthMethod::DataSourceUri ); setDataProviders( QStringList() - << "postgres" - << "db2" - << "ows" - << "wfs" // convert to lowercase - << "wcs" - << "wms" ); + << QStringLiteral( "postgres" ) + << QStringLiteral( "db2" ) + << QStringLiteral( "ows" ) + << QStringLiteral( "wfs" ) // convert to lowercase + << QStringLiteral( "wcs" ) + << QStringLiteral( "wms" ) ); } QgsAuthBasicMethod::~QgsAuthBasicMethod() @@ -71,12 +71,12 @@ bool QgsAuthBasicMethod::updateNetworkRequest( QNetworkRequest &request, const Q return false; } - QString username = mconfig.config( "username" ); - QString password = mconfig.config( "password" ); + QString username = mconfig.config( QStringLiteral( "username" ) ); + QString password = mconfig.config( QStringLiteral( "password" ) ); if ( !username.isEmpty() ) { - request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( username, password ).toLatin1().toBase64() ); + request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( username, password ).toLatin1().toBase64() ); } return true; } @@ -92,8 +92,8 @@ bool QgsAuthBasicMethod::updateDataSourceUriItems( QStringList &connectionItems, return false; } - QString username = mconfig.config( "username" ); - QString password = mconfig.config( "password" ); + QString username = mconfig.config( QStringLiteral( "username" ) ); + QString password = mconfig.config( QStringLiteral( "password" ) ); if ( username.isEmpty() ) { @@ -128,15 +128,15 @@ bool QgsAuthBasicMethod::updateDataSourceUriItems( QStringList &connectionItems, void QgsAuthBasicMethod::updateMethodConfig( QgsAuthMethodConfig &mconfig ) { - if ( mconfig.hasConfig( "oldconfigstyle" ) ) + if ( mconfig.hasConfig( QStringLiteral( "oldconfigstyle" ) ) ) { QgsDebugMsg( "Updating old style auth method config" ); - QStringList conflist = mconfig.config( "oldconfigstyle" ).split( "|||" ); - mconfig.setConfig( "realm", conflist.at( 0 ) ); - mconfig.setConfig( "username", conflist.at( 1 ) ); - mconfig.setConfig( "password", conflist.at( 2 ) ); - mconfig.removeConfig( "oldconfigstyle" ); + QStringList conflist = mconfig.config( QStringLiteral( "oldconfigstyle" ) ).split( QStringLiteral( "|||" ) ); + mconfig.setConfig( QStringLiteral( "realm" ), conflist.at( 0 ) ); + mconfig.setConfig( QStringLiteral( "username" ), conflist.at( 1 ) ); + mconfig.setConfig( QStringLiteral( "password" ), conflist.at( 2 ) ); + mconfig.removeConfig( QStringLiteral( "oldconfigstyle" ) ); } // TODO: add updates as method version() increases due to config storage changes @@ -191,8 +191,8 @@ QString QgsAuthBasicMethod::escapeUserPass( const QString &theVal, QChar delim ) { QString val = theVal; - val.replace( '\\', "\\\\" ); - val.replace( delim, QString( "\\%1" ).arg( delim ) ); + val.replace( '\\', QLatin1String( "\\\\" ) ); + val.replace( delim, QStringLiteral( "\\%1" ).arg( delim ) ); return val; } diff --git a/src/auth/identcert/qgsauthidentcertedit.cpp b/src/auth/identcert/qgsauthidentcertedit.cpp index dfd80277835d..0ba27fb221c1 100644 --- a/src/auth/identcert/qgsauthidentcertedit.cpp +++ b/src/auth/identcert/qgsauthidentcertedit.cpp @@ -49,7 +49,7 @@ bool QgsAuthIdentCertEdit::validateConfig() QgsStringMap QgsAuthIdentCertEdit::configMap() const { QgsStringMap config; - config.insert( "certid", cmbIdentityCert->currentData().toString() ); + config.insert( QStringLiteral( "certid" ), cmbIdentityCert->currentData().toString() ); return config; } @@ -59,7 +59,7 @@ void QgsAuthIdentCertEdit::loadConfig( const QgsStringMap &configmap ) clearConfig(); mConfigMap = configmap; - int indx = cmbIdentityCert->findData( configmap.value( "certid" ) ); + int indx = cmbIdentityCert->findData( configmap.value( QStringLiteral( "certid" ) ) ); cmbIdentityCert->setCurrentIndex( indx == -1 ? 0 : indx ); validateConfig(); @@ -89,13 +89,13 @@ void QgsAuthIdentCertEdit::populateIdentityComboBox() QString org( SSL_SUBJECT_INFO( cert, QSslCertificate::Organization ) ); if ( org.isEmpty() ) org = tr( "Organization not defined" ); - idents.insert( QString( "%1 (%2)" ).arg( QgsAuthCertUtils::resolvedCertName( cert ), org ), + idents.insert( QStringLiteral( "%1 (%2)" ).arg( QgsAuthCertUtils::resolvedCertName( cert ), org ), QgsAuthCertUtils::shaHexForCert( cert ) ); } QgsStringMap::const_iterator it = idents.constBegin(); for ( ; it != idents.constEnd(); ++it ) { - cmbIdentityCert->addItem( QgsApplication::getThemeIcon( "/mIconCertificate.svg" ), + cmbIdentityCert->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificate.svg" ) ), it.key(), it.value() ); } } diff --git a/src/auth/identcert/qgsauthidentcertmethod.cpp b/src/auth/identcert/qgsauthidentcertmethod.cpp index 040c917b5c8d..a94d524fa017 100644 --- a/src/auth/identcert/qgsauthidentcertmethod.cpp +++ b/src/auth/identcert/qgsauthidentcertmethod.cpp @@ -30,8 +30,8 @@ #include "qgsauthmanager.h" #include "qgslogger.h" -static const QString AUTH_METHOD_KEY = "Identity-Cert"; -static const QString AUTH_METHOD_DESCRIPTION = "Identity certificate authentication"; +static const QString AUTH_METHOD_KEY = QStringLiteral( "Identity-Cert" ); +static const QString AUTH_METHOD_DESCRIPTION = QStringLiteral( "Identity certificate authentication" ); QMap QgsAuthIdentCertMethod::mPkiConfigBundleCache = QMap(); @@ -42,11 +42,11 @@ QgsAuthIdentCertMethod::QgsAuthIdentCertMethod() setVersion( 2 ); setExpansions( QgsAuthMethod::NetworkRequest | QgsAuthMethod::DataSourceUri ); setDataProviders( QStringList() - << "ows" - << "wfs" // convert to lowercase - << "wcs" - << "wms" - << "postgres" ); + << QStringLiteral( "ows" ) + << QStringLiteral( "wfs" ) // convert to lowercase + << QStringLiteral( "wcs" ) + << QStringLiteral( "wms" ) + << QStringLiteral( "postgres" ) ); } QgsAuthIdentCertMethod::~QgsAuthIdentCertMethod() @@ -119,7 +119,7 @@ bool QgsAuthIdentCertMethod::updateDataSourceUriItems( QStringList &connectionIt } QgsDebugMsg( "Update URI items: PKI bundle valid" ); - QString pkiTempFileBase = "tmppki_%1.pem"; + QString pkiTempFileBase = QStringLiteral( "tmppki_%1.pem" ); // save client cert to temp file QString certFilePath = QgsAuthCertUtils::pemTextToTempFile( @@ -206,13 +206,13 @@ void QgsAuthIdentCertMethod::clearCachedConfig( const QString &authcfg ) void QgsAuthIdentCertMethod::updateMethodConfig( QgsAuthMethodConfig &mconfig ) { - if ( mconfig.hasConfig( "oldconfigstyle" ) ) + if ( mconfig.hasConfig( QStringLiteral( "oldconfigstyle" ) ) ) { QgsDebugMsg( "Updating old style auth method config" ); - QStringList conflist = mconfig.config( "oldconfigstyle" ).split( "|||" ); - mconfig.setConfig( "certid", conflist.at( 0 ) ); - mconfig.removeConfig( "oldconfigstyle" ); + QStringList conflist = mconfig.config( QStringLiteral( "oldconfigstyle" ) ).split( QStringLiteral( "|||" ) ); + mconfig.setConfig( QStringLiteral( "certid" ), conflist.at( 0 ) ); + mconfig.removeConfig( QStringLiteral( "oldconfigstyle" ) ); } // TODO: add updates as method version() increases due to config storage changes @@ -243,7 +243,7 @@ QgsPkiConfigBundle *QgsAuthIdentCertMethod::getPkiConfigBundle( const QString &a } // get identity from database - QPair cibundle( QgsAuthManager::instance()->getCertIdentityBundle( mconfig.config( "certid" ) ) ); + QPair cibundle( QgsAuthManager::instance()->getCertIdentityBundle( mconfig.config( QStringLiteral( "certid" ) ) ) ); // init client cert // Note: if this is not valid, no sense continuing diff --git a/src/auth/pkipaths/qgsauthpkipathsedit.cpp b/src/auth/pkipaths/qgsauthpkipathsedit.cpp index 02541090997a..3530e3a37195 100644 --- a/src/auth/pkipaths/qgsauthpkipathsedit.cpp +++ b/src/auth/pkipaths/qgsauthpkipathsedit.cpp @@ -71,7 +71,7 @@ bool QgsAuthPkiPathsEdit::validateConfig() QFile::OpenMode openflags( QIODevice::ReadOnly ); QSsl::EncodingFormat encformat( QSsl::Der ); - if ( ext == ".pem" ) + if ( ext == QLatin1String( ".pem" ) ) { openflags |= QIODevice::Text; encformat = QSsl::Pem; @@ -108,9 +108,9 @@ bool QgsAuthPkiPathsEdit::validateConfig() QgsStringMap QgsAuthPkiPathsEdit::configMap() const { QgsStringMap config; - config.insert( "certpath", lePkiPathsCert->text() ); - config.insert( "keypath", lePkiPathsKey->text() ); - config.insert( "keypass", lePkiPathsKeyPass->text() ); + config.insert( QStringLiteral( "certpath" ), lePkiPathsCert->text() ); + config.insert( QStringLiteral( "keypath" ), lePkiPathsKey->text() ); + config.insert( QStringLiteral( "keypass" ), lePkiPathsKeyPass->text() ); return config; } @@ -120,9 +120,9 @@ void QgsAuthPkiPathsEdit::loadConfig( const QgsStringMap &configmap ) clearConfig(); mConfigMap = configmap; - lePkiPathsCert->setText( configmap.value( "certpath" ) ); - lePkiPathsKey->setText( configmap.value( "keypath" ) ); - lePkiPathsKeyPass->setText( configmap.value( "keypass" ) ); + lePkiPathsCert->setText( configmap.value( QStringLiteral( "certpath" ) ) ); + lePkiPathsKey->setText( configmap.value( QStringLiteral( "keypath" ) ) ); + lePkiPathsKeyPass->setText( configmap.value( QStringLiteral( "keypass" ) ) ); validateConfig(); } @@ -145,7 +145,7 @@ void QgsAuthPkiPathsEdit::clearConfig() void QgsAuthPkiPathsEdit::clearPkiMessage( QLineEdit *lineedit ) { lineedit->clear(); - lineedit->setStyleSheet( "" ); + lineedit->setStyleSheet( QLatin1String( "" ) ); } void QgsAuthPkiPathsEdit::writePkiMessage( QLineEdit *lineedit, const QString &msg, Validity valid ) @@ -155,18 +155,18 @@ void QgsAuthPkiPathsEdit::writePkiMessage( QLineEdit *lineedit, const QString &m switch ( valid ) { case Valid: - ss = QgsAuthGuiUtils::greenTextStyleSheet( "QLineEdit" ); + ss = QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QLineEdit" ) ); txt = tr( "Valid: %1" ).arg( msg ); break; case Invalid: - ss = QgsAuthGuiUtils::redTextStyleSheet( "QLineEdit" ); + ss = QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QLineEdit" ) ); txt = tr( "Invalid: %1" ).arg( msg ); break; case Unknown: - ss = ""; + ss = QLatin1String( "" ); break; default: - ss = ""; + ss = QLatin1String( "" ); } lineedit->setStyleSheet( ss ); lineedit->setText( txt ); @@ -176,20 +176,20 @@ void QgsAuthPkiPathsEdit::writePkiMessage( QLineEdit *lineedit, const QString &m void QgsAuthPkiPathsEdit::clearPkiPathsCertPath() { lePkiPathsCert->clear(); - lePkiPathsCert->setStyleSheet( "" ); + lePkiPathsCert->setStyleSheet( QLatin1String( "" ) ); } void QgsAuthPkiPathsEdit::clearPkiPathsKeyPath() { lePkiPathsKey->clear(); - lePkiPathsKey->setStyleSheet( "" ); + lePkiPathsKey->setStyleSheet( QLatin1String( "" ) ); } void QgsAuthPkiPathsEdit::clearPkiPathsKeyPass() { lePkiPathsKeyPass->clear(); - lePkiPathsKeyPass->setStyleSheet( "" ); + lePkiPathsKeyPass->setStyleSheet( QLatin1String( "" ) ); chkPkiPathsPassShow->setChecked( false ); } diff --git a/src/auth/pkipaths/qgsauthpkipathsmethod.cpp b/src/auth/pkipaths/qgsauthpkipathsmethod.cpp index 4520576ced20..92c1897b2181 100644 --- a/src/auth/pkipaths/qgsauthpkipathsmethod.cpp +++ b/src/auth/pkipaths/qgsauthpkipathsmethod.cpp @@ -31,8 +31,8 @@ #include "qgslogger.h" -static const QString AUTH_METHOD_KEY = "PKI-Paths"; -static const QString AUTH_METHOD_DESCRIPTION = "PKI paths authentication"; +static const QString AUTH_METHOD_KEY = QStringLiteral( "PKI-Paths" ); +static const QString AUTH_METHOD_DESCRIPTION = QStringLiteral( "PKI paths authentication" ); QMap QgsAuthPkiPathsMethod::mPkiConfigBundleCache = QMap(); @@ -43,11 +43,11 @@ QgsAuthPkiPathsMethod::QgsAuthPkiPathsMethod() setVersion( 2 ); setExpansions( QgsAuthMethod::NetworkRequest | QgsAuthMethod::DataSourceUri ); setDataProviders( QStringList() - << "ows" - << "wfs" // convert to lowercase - << "wcs" - << "wms" - << "postgres" ); + << QStringLiteral( "ows" ) + << QStringLiteral( "wfs" ) // convert to lowercase + << QStringLiteral( "wcs" ) + << QStringLiteral( "wms" ) + << QStringLiteral( "postgres" ) ); } QgsAuthPkiPathsMethod::~QgsAuthPkiPathsMethod() @@ -120,7 +120,7 @@ bool QgsAuthPkiPathsMethod::updateDataSourceUriItems( QStringList &connectionIte } QgsDebugMsg( "Update URI items: PKI bundle valid" ); - QString pkiTempFileBase = "tmppki_%1.pem"; + QString pkiTempFileBase = QStringLiteral( "tmppki_%1.pem" ); // save client cert to temp file QString certFilePath = QgsAuthCertUtils::pemTextToTempFile( @@ -208,15 +208,15 @@ void QgsAuthPkiPathsMethod::clearCachedConfig( const QString &authcfg ) void QgsAuthPkiPathsMethod::updateMethodConfig( QgsAuthMethodConfig &mconfig ) { - if ( mconfig.hasConfig( "oldconfigstyle" ) ) + if ( mconfig.hasConfig( QStringLiteral( "oldconfigstyle" ) ) ) { QgsDebugMsg( "Updating old style auth method config" ); - QStringList conflist = mconfig.config( "oldconfigstyle" ).split( "|||" ); - mconfig.setConfig( "certpath", conflist.at( 0 ) ); - mconfig.setConfig( "keypath", conflist.at( 1 ) ); - mconfig.setConfig( "keypass", conflist.at( 2 ) ); - mconfig.removeConfig( "oldconfigstyle" ); + QStringList conflist = mconfig.config( QStringLiteral( "oldconfigstyle" ) ).split( QStringLiteral( "|||" ) ); + mconfig.setConfig( QStringLiteral( "certpath" ), conflist.at( 0 ) ); + mconfig.setConfig( QStringLiteral( "keypath" ), conflist.at( 1 ) ); + mconfig.setConfig( QStringLiteral( "keypass" ), conflist.at( 2 ) ); + mconfig.removeConfig( QStringLiteral( "oldconfigstyle" ) ); } // TODO: add updates as method version() increases due to config storage changes @@ -248,7 +248,7 @@ QgsPkiConfigBundle *QgsAuthPkiPathsMethod::getPkiConfigBundle( const QString &au // init client cert // Note: if this is not valid, no sense continuing - QSslCertificate clientcert( QgsAuthCertUtils::certFromFile( mconfig.config( "certpath" ) ) ); + QSslCertificate clientcert( QgsAuthCertUtils::certFromFile( mconfig.config( QStringLiteral( "certpath" ) ) ) ); if ( !clientcert.isValid() ) { QgsDebugMsg( QString( "PKI bundle for authcfg %1: insert FAILED, client cert is not valid" ).arg( authcfg ) ); @@ -256,7 +256,7 @@ QgsPkiConfigBundle *QgsAuthPkiPathsMethod::getPkiConfigBundle( const QString &au } // init key - QSslKey clientkey = QgsAuthCertUtils::keyFromFile( mconfig.config( "keypath" ), mconfig.config( "keypass" ) ); + QSslKey clientkey = QgsAuthCertUtils::keyFromFile( mconfig.config( QStringLiteral( "keypath" ) ), mconfig.config( QStringLiteral( "keypass" ) ) ); if ( clientkey.isNull() ) { diff --git a/src/auth/pkipkcs12/qgsauthpkcs12edit.cpp b/src/auth/pkipkcs12/qgsauthpkcs12edit.cpp index 6d5d545d9c98..76a2bf5e097d 100644 --- a/src/auth/pkipkcs12/qgsauthpkcs12edit.cpp +++ b/src/auth/pkipkcs12/qgsauthpkcs12edit.cpp @@ -67,7 +67,7 @@ bool QgsAuthPkcs12Edit::validateConfig() passarray = QCA::SecureArray( lePkcs12KeyPass->text().toUtf8() ); QCA::ConvertResult res; - QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QString( "qca-ossl" ) ) ); + QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QStringLiteral( "qca-ossl" ) ) ); if ( res == QCA::ErrorFile ) { @@ -77,7 +77,7 @@ bool QgsAuthPkcs12Edit::validateConfig() else if ( res == QCA::ErrorPassphrase ) { writePkiMessage( lePkcs12Msg, tr( "Incorrect bundle password" ), Invalid ); - lePkcs12KeyPass->setPlaceholderText( QString( "Required passphrase" ) ); + lePkcs12KeyPass->setPlaceholderText( QStringLiteral( "Required passphrase" ) ); return validityChange( false ); } else if ( res == QCA::ErrorDecode ) @@ -116,8 +116,8 @@ bool QgsAuthPkcs12Edit::validateConfig() QgsStringMap QgsAuthPkcs12Edit::configMap() const { QgsStringMap config; - config.insert( "bundlepath", lePkcs12Bundle->text() ); - config.insert( "bundlepass", lePkcs12KeyPass->text() ); + config.insert( QStringLiteral( "bundlepath" ), lePkcs12Bundle->text() ); + config.insert( QStringLiteral( "bundlepass" ), lePkcs12KeyPass->text() ); return config; } @@ -127,8 +127,8 @@ void QgsAuthPkcs12Edit::loadConfig( const QgsStringMap &configmap ) clearConfig(); mConfigMap = configmap; - lePkcs12Bundle->setText( configmap.value( "bundlepath" ) ); - lePkcs12KeyPass->setText( configmap.value( "bundlepass" ) ); + lePkcs12Bundle->setText( configmap.value( QStringLiteral( "bundlepath" ) ) ); + lePkcs12KeyPass->setText( configmap.value( QStringLiteral( "bundlepass" ) ) ); validateConfig(); } @@ -150,7 +150,7 @@ void QgsAuthPkcs12Edit::clearConfig() void QgsAuthPkcs12Edit::clearPkiMessage( QLineEdit *lineedit ) { lineedit->clear(); - lineedit->setStyleSheet( "" ); + lineedit->setStyleSheet( QLatin1String( "" ) ); } void QgsAuthPkcs12Edit::writePkiMessage( QLineEdit *lineedit, const QString &msg, Validity valid ) @@ -160,18 +160,18 @@ void QgsAuthPkcs12Edit::writePkiMessage( QLineEdit *lineedit, const QString &msg switch ( valid ) { case Valid: - ss = QgsAuthGuiUtils::greenTextStyleSheet( "QLineEdit" ); + ss = QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QLineEdit" ) ); txt = tr( "Valid: %1" ).arg( msg ); break; case Invalid: - ss = QgsAuthGuiUtils::redTextStyleSheet( "QLineEdit" ); + ss = QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QLineEdit" ) ); txt = tr( "Invalid: %1" ).arg( msg ); break; case Unknown: - ss = ""; + ss = QLatin1String( "" ); break; default: - ss = ""; + ss = QLatin1String( "" ); } lineedit->setStyleSheet( ss ); lineedit->setText( txt ); @@ -181,14 +181,14 @@ void QgsAuthPkcs12Edit::writePkiMessage( QLineEdit *lineedit, const QString &msg void QgsAuthPkcs12Edit::clearPkcs12BundlePath() { lePkcs12Bundle->clear(); - lePkcs12Bundle->setStyleSheet( "" ); + lePkcs12Bundle->setStyleSheet( QLatin1String( "" ) ); } void QgsAuthPkcs12Edit::clearPkcs12BundlePass() { lePkcs12KeyPass->clear(); - lePkcs12KeyPass->setStyleSheet( "" ); - lePkcs12KeyPass->setPlaceholderText( QString( "Optional passphrase" ) ); + lePkcs12KeyPass->setStyleSheet( QLatin1String( "" ) ); + lePkcs12KeyPass->setPlaceholderText( QStringLiteral( "Optional passphrase" ) ); chkPkcs12PassShow->setChecked( false ); } diff --git a/src/auth/pkipkcs12/qgsauthpkcs12method.cpp b/src/auth/pkipkcs12/qgsauthpkcs12method.cpp index 15720e98aa3c..b0d0b0651f02 100644 --- a/src/auth/pkipkcs12/qgsauthpkcs12method.cpp +++ b/src/auth/pkipkcs12/qgsauthpkcs12method.cpp @@ -31,8 +31,8 @@ #include "qgslogger.h" -static const QString AUTH_METHOD_KEY = "PKI-PKCS#12"; -static const QString AUTH_METHOD_DESCRIPTION = "PKI PKCS#12 authentication"; +static const QString AUTH_METHOD_KEY = QStringLiteral( "PKI-PKCS#12" ); +static const QString AUTH_METHOD_DESCRIPTION = QStringLiteral( "PKI PKCS#12 authentication" ); QMap QgsAuthPkcs12Method::mPkiConfigBundleCache = QMap(); @@ -43,11 +43,11 @@ QgsAuthPkcs12Method::QgsAuthPkcs12Method() setVersion( 2 ); setExpansions( QgsAuthMethod::NetworkRequest | QgsAuthMethod::DataSourceUri ); setDataProviders( QStringList() - << "ows" - << "wfs" // convert to lowercase - << "wcs" - << "wms" - << "postgres" ); + << QStringLiteral( "ows" ) + << QStringLiteral( "wfs" ) // convert to lowercase + << QStringLiteral( "wcs" ) + << QStringLiteral( "wms" ) + << QStringLiteral( "postgres" ) ); } QgsAuthPkcs12Method::~QgsAuthPkcs12Method() @@ -120,7 +120,7 @@ bool QgsAuthPkcs12Method::updateDataSourceUriItems( QStringList &connectionItems } QgsDebugMsg( "Update URI items: PKI bundle valid" ); - QString pkiTempFileBase = "tmppki_%1.pem"; + QString pkiTempFileBase = QStringLiteral( "tmppki_%1.pem" ); // save client cert to temp file QString certFilePath = QgsAuthCertUtils::pemTextToTempFile( @@ -207,14 +207,14 @@ void QgsAuthPkcs12Method::clearCachedConfig( const QString &authcfg ) void QgsAuthPkcs12Method::updateMethodConfig( QgsAuthMethodConfig &mconfig ) { - if ( mconfig.hasConfig( "oldconfigstyle" ) ) + if ( mconfig.hasConfig( QStringLiteral( "oldconfigstyle" ) ) ) { QgsDebugMsg( "Updating old style auth method config" ); - QStringList conflist = mconfig.config( "oldconfigstyle" ).split( "|||" ); - mconfig.setConfig( "bundlepath", conflist.at( 0 ) ); - mconfig.setConfig( "bundlepass", conflist.at( 1 ) ); - mconfig.removeConfig( "oldconfigstyle" ); + QStringList conflist = mconfig.config( QStringLiteral( "oldconfigstyle" ) ).split( QStringLiteral( "|||" ) ); + mconfig.setConfig( QStringLiteral( "bundlepath" ), conflist.at( 0 ) ); + mconfig.setConfig( QStringLiteral( "bundlepass" ), conflist.at( 1 ) ); + mconfig.removeConfig( QStringLiteral( "oldconfigstyle" ) ); } // TODO: add updates as method version() increases due to config storage changes @@ -244,8 +244,8 @@ QgsPkiConfigBundle *QgsAuthPkcs12Method::getPkiConfigBundle( const QString &auth return bundle; } - QStringList bundlelist = QgsAuthCertUtils::pkcs12BundleToPem( mconfig.config( "bundlepath" ), - mconfig.config( "bundlepass" ), false ); + QStringList bundlelist = QgsAuthCertUtils::pkcs12BundleToPem( mconfig.config( QStringLiteral( "bundlepath" ) ), + mconfig.config( QStringLiteral( "bundlepass" ) ), false ); // init client cert // Note: if this is not valid, no sense continuing @@ -261,7 +261,7 @@ QgsPkiConfigBundle *QgsAuthPkcs12Method::getPkiConfigBundle( const QString &auth QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, - !mconfig.config( "bundlepass" ).isNull() ? mconfig.config( "bundlepass" ).toUtf8() : QByteArray() ); + !mconfig.config( QStringLiteral( "bundlepass" ) ).isNull() ? mconfig.config( QStringLiteral( "bundlepass" ) ).toUtf8() : QByteArray() ); if ( clientkey.isNull() ) diff --git a/src/browser/main.cpp b/src/browser/main.cpp index 5fb4d3182ca5..c4f4df0db7f0 100644 --- a/src/browser/main.cpp +++ b/src/browser/main.cpp @@ -37,21 +37,21 @@ int main( int argc, char ** argv ) QgsApplication a( argc, argv, true ); // update any saved setting for older themes to new default 'gis' theme (2013-04-15) - QString theme = settings.value( "/Themes", "default" ).toString(); - if ( theme == "gis" - || theme == "classic" - || theme == "nkids" ) + QString theme = settings.value( QStringLiteral( "/Themes" ), "default" ).toString(); + if ( theme == QLatin1String( "gis" ) + || theme == QLatin1String( "classic" ) + || theme == QLatin1String( "nkids" ) ) { - theme = QLatin1String( "default" ); + theme = QStringLiteral( "default" ); } a.setThemeName( theme ); a.initQgis(); a.setWindowIcon( QIcon( QgsApplication::iconsPath() + "qbrowser-icon-60x60.png" ) ); // Set up the QSettings environment must be done after qapp is created - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS3" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS3" ) ); #ifdef Q_OS_MACX // If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH @@ -82,21 +82,21 @@ int main( int argc, char ** argv ) #endif QString i18nPath = QgsApplication::i18nPath(); - bool myLocaleOverrideFlag = settings.value( "locale/overrideFlag", false ).toBool(); - QString myUserLocale = settings.value( "locale/userLocale", "" ).toString(); + bool myLocaleOverrideFlag = settings.value( QStringLiteral( "locale/overrideFlag" ), false ).toBool(); + QString myUserLocale = settings.value( QStringLiteral( "locale/userLocale" ), "" ).toString(); QString myTranslationCode = !myLocaleOverrideFlag || myUserLocale.isEmpty() ? QLocale::system().name() : myUserLocale; QTranslator qgistor( nullptr ); QTranslator qttor( nullptr ); - if ( myTranslationCode != "C" ) + if ( myTranslationCode != QLatin1String( "C" ) ) { - if ( qgistor.load( QString( "qgis_" ) + myTranslationCode, i18nPath ) ) + if ( qgistor.load( QStringLiteral( "qgis_" ) + myTranslationCode, i18nPath ) ) { a.installTranslator( &qgistor ); } else { - qWarning( "loading of qgis translation failed [%s]", QString( "%1/qgis_%2" ).arg( i18nPath, myTranslationCode ).toLocal8Bit().constData() ); + qWarning( "loading of qgis translation failed [%s]", QStringLiteral( "%1/qgis_%2" ).arg( i18nPath, myTranslationCode ).toLocal8Bit().constData() ); } /* Translation file for Qt. @@ -104,13 +104,13 @@ int main( int argc, char ** argv ) * the About, Preferences and Quit items to the Mac Application menu. * These items must be translated identically in both qt_ and qgis_ files. */ - if ( qttor.load( QString( "qt_" ) + myTranslationCode, QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) + if ( qttor.load( QStringLiteral( "qt_" ) + myTranslationCode, QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) { a.installTranslator( &qttor ); } else { - qWarning( "loading of qt translation failed [%s]", QString( "%1/qt_%2" ).arg( QLibraryInfo::location( QLibraryInfo::TranslationsPath ), myTranslationCode ).toLocal8Bit().constData() ); + qWarning( "loading of qt translation failed [%s]", QStringLiteral( "%1/qt_%2" ).arg( QLibraryInfo::location( QLibraryInfo::TranslationsPath ), myTranslationCode ).toLocal8Bit().constData() ); } } diff --git a/src/browser/qgsbrowser.cpp b/src/browser/qgsbrowser.cpp index b5a07b8b0afc..e62ab99822d7 100644 --- a/src/browser/qgsbrowser.cpp +++ b/src/browser/qgsbrowser.cpp @@ -82,7 +82,7 @@ QgsBrowser::QgsBrowser( QWidget *parent, Qt::WindowFlags flags ) //Set the icon size of for all the toolbars created in the future. QSettings settings; - int size = settings.value( "/IconSize", QGIS_ICON_SIZE ).toInt(); + int size = settings.value( QStringLiteral( "/IconSize" ), QGIS_ICON_SIZE ).toInt(); setIconSize( QSize( size, size ) ); //Change all current icon sizes. @@ -224,7 +224,7 @@ bool QgsBrowser::layerClicked( QgsLayerItem *item ) } if ( type == QgsMapLayer::RasterLayer ) { - mLayer = new QgsRasterLayer( uri, "", providerKey ); + mLayer = new QgsRasterLayer( uri, QLatin1String( "" ), providerKey ); } } @@ -263,7 +263,7 @@ void QgsBrowser::newVectorLayer() if ( dirItem ) { QSettings settings; - settings.setValue( "/UI/lastVectorFileFilterDir", dirItem->dirPath() ); + settings.setValue( QStringLiteral( "/UI/lastVectorFileFilterDir" ), dirItem->dirPath() ); } } @@ -281,7 +281,7 @@ void QgsBrowser::newVectorLayer() void QgsBrowser::on_mActionWmsConnections_triggered() { - QDialog *wmss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QString( "wms" ), this ) ); + QDialog *wmss = dynamic_cast( QgsProviderRegistry::instance()->selectWidget( QStringLiteral( "wms" ), this ) ); if ( !wmss ) { QMessageBox::warning( this, tr( "WMS" ), tr( "Cannot get WMS select dialog from provider." ) ); @@ -334,30 +334,30 @@ void QgsBrowser::on_mActionSetProjection_triggered() void QgsBrowser::saveWindowState() { QSettings settings; - settings.setValue( "/Windows/Browser/state", saveState() ); - settings.setValue( "/Windows/Browser/geometry", saveGeometry() ); - settings.setValue( "/Windows/Browser/sizes/0", splitter->sizes().at( 0 ) ); - settings.setValue( "/Windows/Browser/sizes/1", splitter->sizes().at( 1 ) ); + settings.setValue( QStringLiteral( "/Windows/Browser/state" ), saveState() ); + settings.setValue( QStringLiteral( "/Windows/Browser/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/Browser/sizes/0" ), splitter->sizes().at( 0 ) ); + settings.setValue( QStringLiteral( "/Windows/Browser/sizes/1" ), splitter->sizes().at( 1 ) ); } void QgsBrowser::restoreWindowState() { QSettings settings; - if ( !restoreState( settings.value( "/Windows/Browser/state" ).toByteArray() ) ) + if ( !restoreState( settings.value( QStringLiteral( "/Windows/Browser/state" ) ).toByteArray() ) ) { QgsDebugMsg( "restore of UI state failed" ); } - if ( !restoreGeometry( settings.value( "/Windows/Browser/geometry" ).toByteArray() ) ) + if ( !restoreGeometry( settings.value( QStringLiteral( "/Windows/Browser/geometry" ) ).toByteArray() ) ) { QgsDebugMsg( "restore of UI geometry failed" ); } - int size0 = settings.value( "/Windows/Browser/sizes/0" ).toInt(); + int size0 = settings.value( QStringLiteral( "/Windows/Browser/sizes/0" ) ).toInt(); if ( size0 > 0 ) { QList sizes; sizes << size0; - sizes << settings.value( "/Windows/Browser/sizes/1" ).toInt(); + sizes << settings.value( QStringLiteral( "/Windows/Browser/sizes/1" ) ).toInt(); QgsDebugMsg( QString( "set splitter sizes to %1 %2" ).arg( sizes[0] ).arg( sizes[1] ) ); splitter->setSizes( sizes ); } @@ -528,7 +528,7 @@ void QgsBrowser::setLayer( QgsVectorLayer* vLayer ) { // Initialize the cache QSettings settings; - int cacheSize = qMax( 1, settings.value( "/qgis/attributeTableRowCache", "10000" ).toInt() ); + int cacheSize = qMax( 1, settings.value( QStringLiteral( "/qgis/attributeTableRowCache" ), "10000" ).toInt() ); QgsVectorLayerCache* layerCache = new QgsVectorLayerCache( vLayer, cacheSize, this ); layerCache->setCacheGeometry( false ); diff --git a/src/core/auth/qgsauthcertutils.cpp b/src/core/auth/qgsauthcertutils.cpp index af7262e49278..fd0d4ae2c242 100644 --- a/src/core/auth/qgsauthcertutils.cpp +++ b/src/core/auth/qgsauthcertutils.cpp @@ -62,7 +62,7 @@ QMap > QgsAuthCertUtils::certsGroupedByOrg( cons { QString org( SSL_SUBJECT_INFO( cert, QSslCertificate::Organization ) ); if ( org.isEmpty() ) - org = "(Organization not defined)"; + org = QStringLiteral( "(Organization not defined)" ); QList valist = orgcerts.contains( org ) ? orgcerts.value( org ) : QList(); orgcerts.insert( org, valist << cert ); } @@ -116,7 +116,7 @@ static QByteArray fileData_( const QString& path, bool astext = false ) QList QgsAuthCertUtils::certsFromFile( const QString &certspath ) { QList certs; - bool pem = certspath.endsWith( ".pem", Qt::CaseInsensitive ); + bool pem = certspath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ); certs = QSslCertificate::fromData( fileData_( certspath, pem ), pem ? QSsl::Pem : QSsl::Der ); if ( certs.isEmpty() ) { @@ -144,7 +144,7 @@ QSslKey QgsAuthCertUtils::keyFromFile( const QString &keypath, const QString &keypass, QString *algtype ) { - bool pem = keypath.endsWith( ".pem", Qt::CaseInsensitive ); + bool pem = keypath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ); QByteArray keydata( fileData_( keypath, pem ) ); QSslKey clientkey; @@ -166,12 +166,12 @@ QSslKey QgsAuthCertUtils::keyFromFile( const QString &keypath, return QSslKey(); } if ( algtype ) - *algtype = "dsa"; + *algtype = QStringLiteral( "dsa" ); } else { if ( algtype ) - *algtype = "rsa"; + *algtype = QStringLiteral( "rsa" ); } return clientkey; @@ -232,15 +232,15 @@ QStringList QgsAuthCertUtils::pkcs12BundleToPem( const QString &bundlepath, QString algtype; if ( bundle.privateKey().isRSA() ) { - algtype = "rsa"; + algtype = QStringLiteral( "rsa" ); } else if ( bundle.privateKey().isDSA() ) { - algtype = "dsa"; + algtype = QStringLiteral( "dsa" ); } else if ( bundle.privateKey().isDH() ) { - algtype = "dh"; + algtype = QStringLiteral( "dh" ); } return QStringList() << bundle.certificateChain().primary().toPEM() << bundle.privateKey().toPEM( passarray ) << algtype; @@ -326,7 +326,7 @@ void QgsAuthCertUtils::appendDirSegment_( QStringList &dirname, { if ( !value.isEmpty() ) { - dirname.append( segment + '=' + value.replace( ',', "\\," ) ); + dirname.append( segment + '=' + value.replace( ',', QLatin1String( "\\," ) ) ); } } @@ -340,7 +340,7 @@ QString QgsAuthCertUtils::getCertDistinguishedName( const QSslCertificate &qcert if ( acert.isNull() ) { QCA::ConvertResult res; - QCA::Certificate acert( QCA::Certificate::fromPEM( qcert.toPem(), &res, QString( "qca-ossl" ) ) ); + QCA::Certificate acert( QCA::Certificate::fromPEM( qcert.toPem(), &res, QStringLiteral( "qca-ossl" ) ) ); if ( res != QCA::ConvertGood || acert.isNull() ) { QgsDebugMsg( "Certificate could not be converted to QCA cert" ); @@ -356,28 +356,28 @@ QString QgsAuthCertUtils::getCertDistinguishedName( const QSslCertificate &qcert // C=US QStringList dirname; QgsAuthCertUtils::appendDirSegment_( - dirname, "E", issuer ? acert.issuerInfo().value( QCA::Email ) + dirname, QStringLiteral( "E" ), issuer ? acert.issuerInfo().value( QCA::Email ) : acert.subjectInfo().value( QCA::Email ) ); QgsAuthCertUtils::appendDirSegment_( - dirname, "CN", issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::CommonName ) + dirname, QStringLiteral( "CN" ), issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::CommonName ) : SSL_SUBJECT_INFO( qcert, QSslCertificate::CommonName ) ); QgsAuthCertUtils::appendDirSegment_( - dirname, "OU", issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::OrganizationalUnitName ) + dirname, QStringLiteral( "OU" ), issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::OrganizationalUnitName ) : SSL_SUBJECT_INFO( qcert, QSslCertificate::OrganizationalUnitName ) ); QgsAuthCertUtils::appendDirSegment_( - dirname, "O", issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::Organization ) + dirname, QStringLiteral( "O" ), issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::Organization ) : SSL_SUBJECT_INFO( qcert, QSslCertificate::Organization ) ); QgsAuthCertUtils::appendDirSegment_( - dirname, "L", issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::LocalityName ) + dirname, QStringLiteral( "L" ), issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::LocalityName ) : SSL_SUBJECT_INFO( qcert, QSslCertificate::LocalityName ) ); QgsAuthCertUtils::appendDirSegment_( - dirname, "ST", issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::StateOrProvinceName ) + dirname, QStringLiteral( "ST" ), issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::StateOrProvinceName ) : SSL_SUBJECT_INFO( qcert, QSslCertificate::StateOrProvinceName ) ); QgsAuthCertUtils::appendDirSegment_( - dirname, "C", issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::CountryName ) + dirname, QStringLiteral( "C" ), issuer ? SSL_ISSUER_INFO( qcert, QSslCertificate::CountryName ) : SSL_SUBJECT_INFO( qcert, QSslCertificate::CountryName ) ); - return dirname.join( "," ); + return dirname.join( QStringLiteral( "," ) ); } QString QgsAuthCertUtils::getCertTrustName( QgsAuthCertUtils::CertTrustPolicy trust ) @@ -405,7 +405,7 @@ QString QgsAuthCertUtils::getColonDelimited( const QString &txt ) { sl << txt.mid( i, ( i + 2 > txt.size() ) ? -1 : 2 ); } - return sl.join( ":" ); + return sl.join( QStringLiteral( ":" ) ); } QString QgsAuthCertUtils::shaHexForCert( const QSslCertificate& cert, bool formatted ) @@ -424,7 +424,7 @@ QCA::Certificate QgsAuthCertUtils::qtCertToQcaCert( const QSslCertificate &cert return QCA::Certificate(); QCA::ConvertResult res; - QCA::Certificate qcacert( QCA::Certificate::fromPEM( cert.toPem(), &res, QString( "qca-ossl" ) ) ); + QCA::Certificate qcacert( QCA::Certificate::fromPEM( cert.toPem(), &res, QStringLiteral( "qca-ossl" ) ) ); if ( res != QCA::ConvertGood || qcacert.isNull() ) { QgsDebugMsg( "Certificate could not be converted to QCA cert" ); @@ -457,7 +457,7 @@ QCA::KeyBundle QgsAuthCertUtils::qcaKeyBundle( const QString &path, const QStrin passarray = QCA::SecureArray( pass.toUtf8() ); QCA::ConvertResult res; - QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( path, passarray, &res, QString( "qca-ossl" ) ) ); + QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( path, passarray, &res, QStringLiteral( "qca-ossl" ) ) ); return ( res == QCA::ConvertGood ? bundle : QCA::KeyBundle() ); } @@ -609,7 +609,7 @@ QList QgsAuthCertUtils::certificateUsageTypes( return usages; QCA::ConvertResult res; - QCA::Certificate qcacert( QCA::Certificate::fromPEM( cert.toPem(), &res, QString( "qca-ossl" ) ) ); + QCA::Certificate qcacert( QCA::Certificate::fromPEM( cert.toPem(), &res, QStringLiteral( "qca-ossl" ) ) ); if ( res != QCA::ConvertGood || qcacert.isNull() ) { QgsDebugMsg( "Certificate could not be converted to QCA cert" ); diff --git a/src/core/auth/qgsauthconfig.cpp b/src/core/auth/qgsauthconfig.cpp index bbde9946f683..9036c37f1e44 100644 --- a/src/core/auth/qgsauthconfig.cpp +++ b/src/core/auth/qgsauthconfig.cpp @@ -29,9 +29,9 @@ // QgsAuthMethodConfig ////////////////////////////////////////////// -const QString QgsAuthMethodConfig::mConfigSep = "|||"; -const QString QgsAuthMethodConfig::mConfigKeySep = ":::"; -const QString QgsAuthMethodConfig::mConfigListSep = "```"; +const QString QgsAuthMethodConfig::mConfigSep = QStringLiteral( "|||" ); +const QString QgsAuthMethodConfig::mConfigKeySep = QStringLiteral( ":::" ); +const QString QgsAuthMethodConfig::mConfigListSep = QStringLiteral( "```" ); const int QgsAuthMethodConfig::mConfigVersion = 1; @@ -105,7 +105,7 @@ void QgsAuthMethodConfig::loadConfigString( const QString &configstr ) if ( configMap().empty() ) { - setConfig( "oldconfigstyle", configstr ); + setConfig( QStringLiteral( "oldconfigstyle" ), configstr ); } } @@ -147,8 +147,8 @@ bool QgsAuthMethodConfig::uriToResource( const QString &accessurl, QString *reso QUrl url( accessurl ); if ( url.isValid() ) { - res = QString( "%1://%2:%3%4" ).arg( url.scheme(), url.host() ) - .arg( url.port() ).arg( withpath ? url.path() : "" ); + res = QStringLiteral( "%1://%2:%3%4" ).arg( url.scheme(), url.host() ) + .arg( url.port() ).arg( withpath ? url.path() : QLatin1String( "" ) ); } } *resource = res; @@ -199,20 +199,20 @@ const QgsPkiBundle QgsPkiBundle::fromPemPaths( const QString &certPath, { QgsPkiBundle pkibundle; if ( !certPath.isEmpty() && !keyPath.isEmpty() - && ( certPath.endsWith( ".pem", Qt::CaseInsensitive ) - || certPath.endsWith( ".der", Qt::CaseInsensitive ) ) - && ( keyPath.endsWith( ".pem", Qt::CaseInsensitive ) - || keyPath.endsWith( ".der", Qt::CaseInsensitive ) ) + && ( certPath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ) + || certPath.endsWith( QLatin1String( ".der" ), Qt::CaseInsensitive ) ) + && ( keyPath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ) + || keyPath.endsWith( QLatin1String( ".der" ), Qt::CaseInsensitive ) ) && QFile::exists( certPath ) && QFile::exists( keyPath ) ) { // client cert - bool pem = certPath.endsWith( ".pem", Qt::CaseInsensitive ); + bool pem = certPath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ); QSslCertificate clientcert( fileData_( certPath, pem ), pem ? QSsl::Pem : QSsl::Der ); pkibundle.setClientCert( clientcert ); // client key - bool pem_key = keyPath.endsWith( ".pem", Qt::CaseInsensitive ); + bool pem_key = keyPath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ); QByteArray keydata( fileData_( keyPath, pem_key ) ); QSslKey clientkey; @@ -245,15 +245,15 @@ const QgsPkiBundle QgsPkiBundle::fromPkcs12Paths( const QString &bundlepath, QgsPkiBundle pkibundle; if ( QCA::isSupported( "pkcs12" ) && !bundlepath.isEmpty() - && ( bundlepath.endsWith( ".p12", Qt::CaseInsensitive ) - || bundlepath.endsWith( ".pfx", Qt::CaseInsensitive ) ) + && ( bundlepath.endsWith( QLatin1String( ".p12" ), Qt::CaseInsensitive ) + || bundlepath.endsWith( QLatin1String( ".pfx" ), Qt::CaseInsensitive ) ) && QFile::exists( bundlepath ) ) { QCA::SecureArray passarray; if ( !bundlepass.isNull() ) passarray = QCA::SecureArray( bundlepass.toUtf8() ); QCA::ConvertResult res; - QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QString( "qca-ossl" ) ) ); + QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QStringLiteral( "qca-ossl" ) ) ); if ( res == QCA::ConvertGood && !bundle.isNull() ) { QCA::CertificateChain cert_chain( bundle.certificateChain() ); @@ -347,7 +347,7 @@ bool QgsPkiConfigBundle::isValid() // QgsAuthConfigSslServer ////////////////////////////////////////////// -const QString QgsAuthConfigSslServer::mConfSep = "|||"; +const QString QgsAuthConfigSslServer::mConfSep = QStringLiteral( "|||" ); QgsAuthConfigSslServer::QgsAuthConfigSslServer() : mSslHostPort( QString() ) @@ -394,9 +394,9 @@ const QString QgsAuthConfigSslServer::configString() const { errs << QString::number( static_cast< int >( err ) ); } - configlist << errs.join( "~~" ); + configlist << errs.join( QStringLiteral( "~~" ) ); - configlist << QString( "%1~~%2" ).arg( static_cast< int >( mSslPeerVerifyMode ) ).arg( mSslPeerVerifyDepth ); + configlist << QStringLiteral( "%1~~%2" ).arg( static_cast< int >( mSslPeerVerifyMode ) ).arg( mSslPeerVerifyDepth ); return configlist.join( mConfSep ); } @@ -417,13 +417,13 @@ void QgsAuthConfigSslServer::loadConfigString( const QString &config ) mSslProtocol = static_cast< QSsl::SslProtocol >( configlist.at( 2 ).toInt() ); mSslIgnoredErrors.clear(); - QStringList errs( configlist.at( 3 ).split( "~~" ) ); + QStringList errs( configlist.at( 3 ).split( QStringLiteral( "~~" ) ) ); Q_FOREACH ( const QString& err, errs ) { mSslIgnoredErrors.append( static_cast< QSslError::SslError >( err.toInt() ) ); } - QStringList peerverify( configlist.at( 4 ).split( "~~" ) ); + QStringList peerverify( configlist.at( 4 ).split( QStringLiteral( "~~" ) ) ); mSslPeerVerifyMode = static_cast< QSslSocket::PeerVerifyMode >( peerverify.at( 0 ).toInt() ); mSslPeerVerifyDepth = peerverify.at( 1 ).toInt(); } diff --git a/src/core/auth/qgsauthmanager.cpp b/src/core/auth/qgsauthmanager.cpp index 811c2a56d222..9516d63133a4 100644 --- a/src/core/auth/qgsauthmanager.cpp +++ b/src/core/auth/qgsauthmanager.cpp @@ -48,15 +48,15 @@ QgsAuthManager *QgsAuthManager::smInstance = nullptr; -const QString QgsAuthManager::smAuthConfigTable = "auth_configs"; -const QString QgsAuthManager::smAuthPassTable = "auth_pass"; -const QString QgsAuthManager::smAuthSettingsTable = "auth_settings"; -const QString QgsAuthManager::smAuthIdentitiesTable = "auth_identities"; -const QString QgsAuthManager::smAuthServersTable = "auth_servers"; -const QString QgsAuthManager::smAuthAuthoritiesTable = "auth_authorities"; -const QString QgsAuthManager::smAuthTrustTable = "auth_trust"; +const QString QgsAuthManager::smAuthConfigTable = QStringLiteral( "auth_configs" ); +const QString QgsAuthManager::smAuthPassTable = QStringLiteral( "auth_pass" ); +const QString QgsAuthManager::smAuthSettingsTable = QStringLiteral( "auth_settings" ); +const QString QgsAuthManager::smAuthIdentitiesTable = QStringLiteral( "auth_identities" ); +const QString QgsAuthManager::smAuthServersTable = QStringLiteral( "auth_servers" ); +const QString QgsAuthManager::smAuthAuthoritiesTable = QStringLiteral( "auth_authorities" ); +const QString QgsAuthManager::smAuthTrustTable = QStringLiteral( "auth_trust" ); const QString QgsAuthManager::smAuthManTag = QObject::tr( "Authentication Manager" ); -const QString QgsAuthManager::smAuthCfgRegex = "authcfg=([a-z]|[A-Z]|[0-9]){7}"; +const QString QgsAuthManager::smAuthCfgRegex = QStringLiteral( "authcfg=([a-z]|[A-Z]|[0-9]){7}" ); QgsAuthManager *QgsAuthManager::instance() @@ -74,10 +74,10 @@ QSqlDatabase QgsAuthManager::authDbConnection() const if ( isDisabled() ) return authdb; - QString connectionname = "authentication.configs"; + QString connectionname = QStringLiteral( "authentication.configs" ); if ( !QSqlDatabase::contains( connectionname ) ) { - authdb = QSqlDatabase::addDatabase( "QSQLITE", connectionname ); + authdb = QSqlDatabase::addDatabase( QStringLiteral( "QSQLITE" ), connectionname ); authdb.setDatabaseName( authenticationDbPath() ); } else @@ -116,7 +116,7 @@ bool QgsAuthManager::init( const QString& pluginPath ) QgsDebugMsg( QString( "QCA supports: %1" ).arg( capabilities.join( "," ) ) ); // do run-time check for qca-ossl plugin - if ( !QCA::isSupported( "cert", "qca-ossl" ) ) + if ( !QCA::isSupported( "cert", QStringLiteral( "qca-ossl" ) ) ) { mAuthDisabled = true; mAuthDisabledMessage = tr( "QCA's OpenSSL plugin (qca-ossl) is missing" ); @@ -135,7 +135,7 @@ bool QgsAuthManager::init( const QString& pluginPath ) pr = QCA::providerPriority( pn ) + 1; } QCA::setProviderPriority( pn, pr ); - prlist << QString( "%1:%2" ).arg( pn ).arg( QCA::providerPriority( pn ) ); + prlist << QStringLiteral( "%1:%2" ).arg( pn ).arg( QCA::providerPriority( pn ) ); } QgsDebugMsg( QString( "QCA provider priorities: %1" ).arg( prlist.join( ", " ) ) ); @@ -302,13 +302,13 @@ bool QgsAuthManager::createConfigTables() return false; query.clear(); - qstr = QString( "CREATE UNIQUE INDEX 'id_index' on %1 (id ASC);" ).arg( authDbConfigTable() ); + qstr = QStringLiteral( "CREATE UNIQUE INDEX 'id_index' on %1 (id ASC);" ).arg( authDbConfigTable() ); query.prepare( qstr ); if ( !authDbQuery( &query ) ) return false; query.clear(); - qstr = QString( "CREATE INDEX 'uri_index' on %1 (uri ASC);" ).arg( authDbConfigTable() ); + qstr = QStringLiteral( "CREATE INDEX 'uri_index' on %1 (uri ASC);" ).arg( authDbConfigTable() ); query.prepare( qstr ); if ( !authDbQuery( &query ) ) return false; @@ -345,7 +345,7 @@ bool QgsAuthManager::createCertTables() return false; query.clear(); - qstr = QString( "CREATE UNIQUE INDEX IF NOT EXISTS 'id_index' on %1 (id ASC);" ).arg( authDbIdentitiesTable() ); + qstr = QStringLiteral( "CREATE UNIQUE INDEX IF NOT EXISTS 'id_index' on %1 (id ASC);" ).arg( authDbIdentitiesTable() ); query.prepare( qstr ); if ( !authDbQuery( &query ) ) return false; @@ -362,7 +362,7 @@ bool QgsAuthManager::createCertTables() return false; query.clear(); - qstr = QString( "CREATE UNIQUE INDEX IF NOT EXISTS 'host_index' on %1 (host ASC);" ).arg( authDbServersTable() ); + qstr = QStringLiteral( "CREATE UNIQUE INDEX IF NOT EXISTS 'host_index' on %1 (host ASC);" ).arg( authDbServersTable() ); query.prepare( qstr ); if ( !authDbQuery( &query ) ) return false; @@ -377,7 +377,7 @@ bool QgsAuthManager::createCertTables() return false; query.clear(); - qstr = QString( "CREATE UNIQUE INDEX IF NOT EXISTS 'id_index' on %1 (id ASC);" ).arg( authDbAuthoritiesTable() ); + qstr = QStringLiteral( "CREATE UNIQUE INDEX IF NOT EXISTS 'id_index' on %1 (id ASC);" ).arg( authDbAuthoritiesTable() ); query.prepare( qstr ); if ( !authDbQuery( &query ) ) return false; @@ -391,7 +391,7 @@ bool QgsAuthManager::createCertTables() return false; query.clear(); - qstr = QString( "CREATE UNIQUE INDEX IF NOT EXISTS 'id_index' on %1 (id ASC);" ).arg( authDbTrustTable() ); + qstr = QStringLiteral( "CREATE UNIQUE INDEX IF NOT EXISTS 'id_index' on %1 (id ASC);" ).arg( authDbTrustTable() ); query.prepare( qstr ); if ( !authDbQuery( &query ) ) return false; @@ -779,7 +779,7 @@ const QString QgsAuthManager::uniqueConfigId() const while ( true ) { - id = ""; + id = QLatin1String( "" ); for ( int i = 0; i < len; i++ ) { switch ( qrand() % 2 ) @@ -837,7 +837,7 @@ QgsAuthMethodConfigsMap QgsAuthManager::availableAuthMethodConfigs( const QStrin return baseConfigs; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, name, uri, type, version FROM %1" ).arg( authDbConfigTable() ) ); + query.prepare( QStringLiteral( "SELECT id, name, uri, type, version FROM %1" ).arg( authDbConfigTable() ) ); if ( !authDbQuery( &query ) ) { @@ -873,7 +873,7 @@ void QgsAuthManager::updateConfigAuthMethods() return; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, type FROM %1" ).arg( authDbConfigTable() ) ); + query.prepare( QStringLiteral( "SELECT id, type FROM %1" ).arg( authDbConfigTable() ) ); if ( !authDbQuery( &query ) ) { @@ -889,7 +889,7 @@ void QgsAuthManager::updateConfigAuthMethods() { mConfigAuthMethods.insert( query.value( 0 ).toString(), query.value( 1 ).toString() ); - cfgmethods << QString( "%1=%2" ).arg( query.value( 0 ).toString(), query.value( 1 ).toString() ); + cfgmethods << QStringLiteral( "%1=%2" ).arg( query.value( 0 ).toString(), query.value( 1 ).toString() ); } QgsDebugMsg( QString( "Stored auth config/methods:\n%1" ).arg( cfgmethods.join( ", " ) ) ); } @@ -948,7 +948,7 @@ QgsAuthMethodsMap QgsAuthManager::authMethodsMap( const QString &dataprovider ) while ( i != mAuthMethods.constEnd() ) { if ( i.value() - && ( i.value()->supportedDataProviders().contains( "all" ) + && ( i.value()->supportedDataProviders().contains( QStringLiteral( "all" ) ) || i.value()->supportedDataProviders().contains( dataprovider ) ) ) { filteredmap.insert( i.key(), i.value() ); @@ -1025,12 +1025,12 @@ bool QgsAuthManager::storeAuthenticationConfig( QgsAuthMethodConfig &mconfig ) query.prepare( QString( "INSERT INTO %1 (id, name, uri, type, version, config) " "VALUES (:id, :name, :uri, :type, :version, :config)" ).arg( authDbConfigTable() ) ); - query.bindValue( ":id", uid ); - query.bindValue( ":name", mconfig.name() ); - query.bindValue( ":uri", mconfig.uri() ); - query.bindValue( ":type", mconfig.method() ); - query.bindValue( ":version", mconfig.version() ); - query.bindValue( ":config", QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring ) ); + query.bindValue( QStringLiteral( ":id" ), uid ); + query.bindValue( QStringLiteral( ":name" ), mconfig.name() ); + query.bindValue( QStringLiteral( ":uri" ), mconfig.uri() ); + query.bindValue( QStringLiteral( ":type" ), mconfig.method() ); + query.bindValue( QStringLiteral( ":version" ), mconfig.version() ); + query.bindValue( QStringLiteral( ":config" ), QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring ) ); if ( !authDbStartTransaction() ) return false; @@ -1096,12 +1096,12 @@ bool QgsAuthManager::updateAuthenticationConfig( const QgsAuthMethodConfig &conf return false; } - query.bindValue( ":id", config.id() ); - query.bindValue( ":name", config.name() ); - query.bindValue( ":uri", config.uri() ); - query.bindValue( ":type", config.method() ); - query.bindValue( ":version", config.version() ); - query.bindValue( ":config", QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring ) ); + query.bindValue( QStringLiteral( ":id" ), config.id() ); + query.bindValue( QStringLiteral( ":name" ), config.name() ); + query.bindValue( QStringLiteral( ":uri" ), config.uri() ); + query.bindValue( QStringLiteral( ":type" ), config.method() ); + query.bindValue( QStringLiteral( ":version" ), config.version() ); + query.bindValue( QStringLiteral( ":config" ), QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring ) ); if ( !authDbStartTransaction() ) return false; @@ -1142,7 +1142,7 @@ bool QgsAuthManager::loadAuthenticationConfig( const QString &authcfg, QgsAuthMe "WHERE id = :id" ).arg( authDbConfigTable() ) ); } - query.bindValue( ":id", authcfg ); + query.bindValue( QStringLiteral( ":id" ), authcfg ); if ( !authDbQuery( &query ) ) { @@ -1198,9 +1198,9 @@ bool QgsAuthManager::removeAuthenticationConfig( const QString& authcfg ) QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1 WHERE id = :id" ).arg( authDbConfigTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1 WHERE id = :id" ).arg( authDbConfigTable() ) ); - query.bindValue( ":id", authcfg ); + query.bindValue( QStringLiteral( ":id" ), authcfg ); if ( !authDbStartTransaction() ) return false; @@ -1226,7 +1226,7 @@ bool QgsAuthManager::removeAllAuthenticationConfigs() return false; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1" ).arg( authDbConfigTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1" ).arg( authDbConfigTable() ) ); bool res = authDbTransactionQuery( &query ); if ( res ) @@ -1256,9 +1256,9 @@ bool QgsAuthManager::backupAuthenticationDatabase( QString *backuppath ) authConn.close(); // duplicate current db file to 'qgis-auth_YYYY-MM-DD-HHMMSS.db' backup - QString datestamp( QDateTime::currentDateTime().toString( "yyyy-MM-dd-hhmmss" ) ); + QString datestamp( QDateTime::currentDateTime().toString( QStringLiteral( "yyyy-MM-dd-hhmmss" ) ) ); QString dbbackup( authenticationDbPath() ); - dbbackup.replace( QLatin1String( ".db" ), QString( "_%1.db" ).arg( datestamp ) ); + dbbackup.replace( QLatin1String( ".db" ), QStringLiteral( "_%1.db" ).arg( datestamp ) ); if ( !QFile::copy( authenticationDbPath(), dbbackup ) ) { @@ -1456,8 +1456,8 @@ bool QgsAuthManager::storeAuthSetting( const QString &key, const QVariant& value query.prepare( QString( "INSERT INTO %1 (setting, value) " "VALUES (:setting, :value)" ).arg( authDbSettingsTable() ) ); - query.bindValue( ":setting", key ); - query.bindValue( ":value", storeval ); + query.bindValue( QStringLiteral( ":setting" ), key ); + query.bindValue( QStringLiteral( ":value" ), storeval ); if ( !authDbStartTransaction() ) return false; @@ -1485,7 +1485,7 @@ QVariant QgsAuthManager::getAuthSetting( const QString &key, const QVariant& def query.prepare( QString( "SELECT value FROM %1 " "WHERE setting = :setting" ).arg( authDbSettingsTable() ) ); - query.bindValue( ":setting", key ); + query.bindValue( QStringLiteral( ":setting" ), key ); if ( !authDbQuery( &query ) ) return QVariant(); @@ -1523,7 +1523,7 @@ bool QgsAuthManager::existsAuthSetting( const QString& key ) query.prepare( QString( "SELECT value FROM %1 " "WHERE setting = :setting" ).arg( authDbSettingsTable() ) ); - query.bindValue( ":setting", key ); + query.bindValue( QStringLiteral( ":setting" ), key ); if ( !authDbQuery( &query ) ) return false; @@ -1553,9 +1553,9 @@ bool QgsAuthManager::removeAuthSetting( const QString& key ) QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1 WHERE setting = :setting" ).arg( authDbSettingsTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1 WHERE setting = :setting" ).arg( authDbSettingsTable() ) ); - query.bindValue( ":setting", key ); + query.bindValue( QStringLiteral( ":setting" ), key ); if ( !authDbStartTransaction() ) return false; @@ -1614,9 +1614,9 @@ bool QgsAuthManager::storeCertIdentity( const QSslCertificate &cert, const QSslK query.prepare( QString( "INSERT INTO %1 (id, key, cert) " "VALUES (:id, :key, :cert)" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":key", keypem ); - query.bindValue( ":cert", certpem ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":key" ), keypem ); + query.bindValue( QStringLiteral( ":cert" ), certpem ); if ( !authDbStartTransaction() ) return false; @@ -1642,7 +1642,7 @@ const QSslCertificate QgsAuthManager::getCertIdentity( const QString &id ) query.prepare( QString( "SELECT cert FROM %1 " "WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbQuery( &query ) ) return emptycert; @@ -1677,7 +1677,7 @@ const QPair QgsAuthManager::getCertIdentityBundle( con query.prepare( QString( "SELECT key, cert FROM %1 " "WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbQuery( &query ) ) return bundle; @@ -1733,7 +1733,7 @@ const QList QgsAuthManager::getCertIdentities() QList certs; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, cert FROM %1" ).arg( authDbIdentitiesTable() ) ); + query.prepare( QStringLiteral( "SELECT id, cert FROM %1" ).arg( authDbIdentitiesTable() ) ); if ( !authDbQuery( &query ) ) return certs; @@ -1757,7 +1757,7 @@ QStringList QgsAuthManager::getCertIdentityIds() const return identityids; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id FROM %1" ).arg( authDbIdentitiesTable() ) ); + query.prepare( QStringLiteral( "SELECT id FROM %1" ).arg( authDbIdentitiesTable() ) ); if ( !authDbQuery( &query ) ) { @@ -1783,7 +1783,7 @@ bool QgsAuthManager::existsCertIdentity( const QString &id ) query.prepare( QString( "SELECT cert FROM %1 " "WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbQuery( &query ) ) return false; @@ -1816,9 +1816,9 @@ bool QgsAuthManager::removeCertIdentity( const QString &id ) QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1 WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1 WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbStartTransaction() ) return false; @@ -1852,10 +1852,10 @@ bool QgsAuthManager::storeSslCertCustomConfig( const QgsAuthConfigSslServer &con query.prepare( QString( "INSERT INTO %1 (id, host, cert, config) " "VALUES (:id, :host, :cert, :config)" ).arg( authDbServersTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":host", config.sslHostPort().trimmed() ); - query.bindValue( ":cert", certpem ); - query.bindValue( ":config", config.configString() ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":host" ), config.sslHostPort().trimmed() ); + query.bindValue( QStringLiteral( ":cert" ), certpem ); + query.bindValue( QStringLiteral( ":config" ), config.configString() ); if ( !authDbStartTransaction() ) return false; @@ -1888,8 +1888,8 @@ const QgsAuthConfigSslServer QgsAuthManager::getSslCertCustomConfig( const QStri query.prepare( QString( "SELECT id, host, cert, config FROM %1 " "WHERE id = :id AND host = :host" ).arg( authDbServersTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":host", hostport.trimmed() ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":host" ), hostport.trimmed() ); if ( !authDbQuery( &query ) ) return config; @@ -1929,7 +1929,7 @@ const QgsAuthConfigSslServer QgsAuthManager::getSslCertCustomConfigByHost( const query.prepare( QString( "SELECT id, host, cert, config FROM %1 " "WHERE host = :host" ).arg( authDbServersTable() ) ); - query.bindValue( ":host", hostport.trimmed() ); + query.bindValue( QStringLiteral( ":host" ), hostport.trimmed() ); if ( !authDbQuery( &query ) ) return config; @@ -1960,7 +1960,7 @@ const QList QgsAuthManager::getSslCertCustomConfigs() QList configs; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, host, cert, config FROM %1" ).arg( authDbServersTable() ) ); + query.prepare( QStringLiteral( "SELECT id, host, cert, config FROM %1" ).arg( authDbServersTable() ) ); if ( !authDbQuery( &query ) ) return configs; @@ -1993,8 +1993,8 @@ bool QgsAuthManager::existsSslCertCustomConfig( const QString &id , const QStrin query.prepare( QString( "SELECT cert FROM %1 " "WHERE id = :id AND host = :host" ).arg( authDbServersTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":host", hostport.trimmed() ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":host" ), hostport.trimmed() ); if ( !authDbQuery( &query ) ) return false; @@ -2028,10 +2028,10 @@ bool QgsAuthManager::removeSslCertCustomConfig( const QString &id, const QString QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1 WHERE id = :id AND host = :host" ).arg( authDbServersTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1 WHERE id = :id AND host = :host" ).arg( authDbServersTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":host", hostport.trimmed() ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":host" ), hostport.trimmed() ); if ( !authDbStartTransaction() ) return false; @@ -2042,7 +2042,7 @@ bool QgsAuthManager::removeSslCertCustomConfig( const QString &id, const QString if ( !authDbCommit() ) return false; - QString shahostport( QString( "%1:%2" ).arg( id, hostport ) ); + QString shahostport( QStringLiteral( "%1:%2" ).arg( id, hostport ) ); if ( mIgnoredSslErrorsCache.contains( shahostport ) ) { mIgnoredSslErrorsCache.remove( shahostport ); @@ -2084,7 +2084,7 @@ bool QgsAuthManager::updateIgnoredSslErrorsCacheFromConfig( const QgsAuthConfigS return false; } - QString shahostport( QString( "%1:%2" ) + QString shahostport( QStringLiteral( "%1:%2" ) .arg( QgsAuthCertUtils::shaHexForCert( config.sslCertificate() ).trimmed(), config.sslHostPort().trimmed() ) ); if ( mIgnoredSslErrorsCache.contains( shahostport ) ) @@ -2153,7 +2153,7 @@ bool QgsAuthManager::rebuildIgnoredSslErrorCache() QHash > nextcache; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, host, config FROM %1" ).arg( authDbServersTable() ) ); + query.prepare( QStringLiteral( "SELECT id, host, config FROM %1" ).arg( authDbServersTable() ) ); if ( !authDbQuery( &query ) ) { @@ -2165,7 +2165,7 @@ bool QgsAuthManager::rebuildIgnoredSslErrorCache() { while ( query.next() ) { - QString shahostport( QString( "%1:%2" ) + QString shahostport( QStringLiteral( "%1:%2" ) .arg( query.value( 0 ).toString().trimmed(), query.value( 1 ).toString().trimmed() ) ); QgsAuthConfigSslServer config; @@ -2243,8 +2243,8 @@ bool QgsAuthManager::storeCertAuthority( const QSslCertificate& cert ) query.prepare( QString( "INSERT INTO %1 (id, cert) " "VALUES (:id, :cert)" ).arg( authDbAuthoritiesTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":cert", pem ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":cert" ), pem ); if ( !authDbStartTransaction() ) return false; @@ -2270,7 +2270,7 @@ const QSslCertificate QgsAuthManager::getCertAuthority( const QString &id ) query.prepare( QString( "SELECT cert FROM %1 " "WHERE id = :id" ).arg( authDbAuthoritiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbQuery( &query ) ) return emptycert; @@ -2306,7 +2306,7 @@ bool QgsAuthManager::existsCertAuthority( const QSslCertificate& cert ) query.prepare( QString( "SELECT value FROM %1 " "WHERE id = :id" ).arg( authDbAuthoritiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbQuery( &query ) ) return false; @@ -2341,9 +2341,9 @@ bool QgsAuthManager::removeCertAuthority( const QSslCertificate& cert ) QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1 WHERE id = :id" ).arg( authDbAuthoritiesTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1 WHERE id = :id" ).arg( authDbAuthoritiesTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbStartTransaction() ) return false; @@ -2372,11 +2372,11 @@ const QList QgsAuthManager::getExtraFileCAs() { QList certs; QList filecerts; - QVariant cafileval = QgsAuthManager::instance()->getAuthSetting( QString( "cafile" ) ); + QVariant cafileval = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "cafile" ) ); if ( cafileval.isNull() ) return certs; - QVariant allowinvalid = QgsAuthManager::instance()->getAuthSetting( QString( "cafileallowinvalid" ), QVariant( false ) ); + QVariant allowinvalid = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "cafileallowinvalid" ), QVariant( false ) ); if ( allowinvalid.isNull() ) return certs; @@ -2406,7 +2406,7 @@ const QList QgsAuthManager::getDatabaseCAs() QList certs; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, cert FROM %1" ).arg( authDbAuthoritiesTable() ) ); + query.prepare( QStringLiteral( "SELECT id, cert FROM %1" ).arg( authDbAuthoritiesTable() ) ); if ( !authDbQuery( &query ) ) return certs; @@ -2462,8 +2462,8 @@ bool QgsAuthManager::storeCertTrustPolicy( const QSslCertificate &cert, QgsAuthC query.prepare( QString( "INSERT INTO %1 (id, policy) " "VALUES (:id, :policy)" ).arg( authDbTrustTable() ) ); - query.bindValue( ":id", id ); - query.bindValue( ":policy", static_cast< int >( policy ) ); + query.bindValue( QStringLiteral( ":id" ), id ); + query.bindValue( QStringLiteral( ":policy" ), static_cast< int >( policy ) ); if ( !authDbStartTransaction() ) return false; @@ -2492,7 +2492,7 @@ QgsAuthCertUtils::CertTrustPolicy QgsAuthManager::getCertTrustPolicy( const QSsl query.prepare( QString( "SELECT policy FROM %1 " "WHERE id = :id" ).arg( authDbTrustTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbQuery( &query ) ) return QgsAuthCertUtils::DefaultTrust; @@ -2543,9 +2543,9 @@ bool QgsAuthManager::removeCertTrustPolicy( const QSslCertificate &cert ) QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1 WHERE id = :id" ).arg( authDbTrustTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1 WHERE id = :id" ).arg( authDbTrustTable() ) ); - query.bindValue( ":id", id ); + query.bindValue( QStringLiteral( ":id" ), id ); if ( !authDbStartTransaction() ) return false; @@ -2589,14 +2589,14 @@ bool QgsAuthManager::setDefaultCertTrustPolicy( QgsAuthCertUtils::CertTrustPolic if ( policy == QgsAuthCertUtils::DefaultTrust ) { // set default trust policy to Trusted by removing setting - return removeAuthSetting( "certdefaulttrust" ); + return removeAuthSetting( QStringLiteral( "certdefaulttrust" ) ); } - return storeAuthSetting( "certdefaulttrust", static_cast< int >( policy ) ); + return storeAuthSetting( QStringLiteral( "certdefaulttrust" ), static_cast< int >( policy ) ); } QgsAuthCertUtils::CertTrustPolicy QgsAuthManager::defaultCertTrustPolicy() { - QVariant policy( getAuthSetting( "certdefaulttrust" ) ); + QVariant policy( getAuthSetting( QStringLiteral( "certdefaulttrust" ) ) ); if ( policy.isNull() ) { return QgsAuthCertUtils::Trusted; @@ -2609,7 +2609,7 @@ bool QgsAuthManager::rebuildCertTrustCache() mCertTrustCache.clear(); QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, policy FROM %1" ).arg( authDbTrustTable() ) ); + query.prepare( QStringLiteral( "SELECT id, policy FROM %1" ).arg( authDbTrustTable() ) ); if ( !authDbQuery( &query ) ) { @@ -2714,7 +2714,7 @@ const QByteArray QgsAuthManager::getTrustedCaCertsPemText() { certslist << cert.toPem(); } - capem = certslist.join( "\n" ).toLatin1(); //+ "\n"; + capem = certslist.join( QStringLiteral( "\n" ) ).toLatin1(); //+ "\n"; } return capem; } @@ -2761,10 +2761,10 @@ void QgsAuthManager::writeToConsole( const QString &message, switch ( level ) { case QgsAuthManager::WARNING: - msg += "WARNING: "; + msg += QLatin1String( "WARNING: " ); break; case QgsAuthManager::CRITICAL: - msg += "ERROR: "; + msg += QLatin1String( "ERROR: " ); break; default: break; @@ -2844,7 +2844,7 @@ QgsAuthManager::~QgsAuthManager() mScheduledDbEraseTimer = nullptr; delete mQcaInitializer; mQcaInitializer = nullptr; - QSqlDatabase::removeDatabase( "authentication.configs" ); + QSqlDatabase::removeDatabase( QStringLiteral( "authentication.configs" ) ); } bool QgsAuthManager::masterPasswordInput() @@ -2872,7 +2872,7 @@ bool QgsAuthManager::masterPasswordRowsInDb( int *rows ) const return false; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT Count(*) FROM %1" ).arg( authDbPassTable() ) ); + query.prepare( QStringLiteral( "SELECT Count(*) FROM %1" ).arg( authDbPassTable() ) ); bool ok = authDbQuery( &query ); if ( query.first() ) @@ -2908,7 +2908,7 @@ bool QgsAuthManager::masterPasswordCheckAgainstDb( const QString &compare ) cons // first verify there is only one row in auth db (uses first found) QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT salt, hash FROM %1" ).arg( authDbPassTable() ) ); + query.prepare( QStringLiteral( "SELECT salt, hash FROM %1" ).arg( authDbPassTable() ) ); if ( !authDbQuery( &query ) ) return false; @@ -2930,11 +2930,11 @@ bool QgsAuthManager::masterPasswordStoreInDb() const QgsAuthCrypto::passwordKeyHash( mMasterPass, &salt, &hash, &civ ); QSqlQuery query( authDbConnection() ); - query.prepare( QString( "INSERT INTO %1 (salt, hash, civ) VALUES (:salt, :hash, :civ)" ).arg( authDbPassTable() ) ); + query.prepare( QStringLiteral( "INSERT INTO %1 (salt, hash, civ) VALUES (:salt, :hash, :civ)" ).arg( authDbPassTable() ) ); - query.bindValue( ":salt", salt ); - query.bindValue( ":hash", hash ); - query.bindValue( ":civ", civ ); + query.bindValue( QStringLiteral( ":salt" ), salt ); + query.bindValue( QStringLiteral( ":hash" ), hash ); + query.bindValue( QStringLiteral( ":civ" ), civ ); if ( !authDbStartTransaction() ) return false; @@ -2954,7 +2954,7 @@ bool QgsAuthManager::masterPasswordClearDb() return false; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "DELETE FROM %1" ).arg( authDbPassTable() ) ); + query.prepare( QStringLiteral( "DELETE FROM %1" ).arg( authDbPassTable() ) ); bool res = authDbTransactionQuery( &query ); if ( res ) clearMasterPassword(); @@ -2967,7 +2967,7 @@ const QString QgsAuthManager::masterPasswordCiv() const return QString(); QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT civ FROM %1" ).arg( authDbPassTable() ) ); + query.prepare( QStringLiteral( "SELECT civ FROM %1" ).arg( authDbPassTable() ) ); if ( !authDbQuery( &query ) ) return QString(); @@ -2985,7 +2985,7 @@ QStringList QgsAuthManager::configIds() const return configids; QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id FROM %1" ).arg( authDbConfigTable() ) ); + query.prepare( QStringLiteral( "SELECT id FROM %1" ).arg( authDbConfigTable() ) ); if ( !authDbQuery( &query ) ) { @@ -3011,7 +3011,7 @@ bool QgsAuthManager::verifyPasswordCanDecryptConfigs() const QSqlQuery query( authDbConnection() ); - query.prepare( QString( "SELECT id, config FROM %1" ).arg( authDbConfigTable() ) ); + query.prepare( QStringLiteral( "SELECT id, config FROM %1" ).arg( authDbConfigTable() ) ); if ( !authDbQuery( &query ) ) return false; @@ -3064,7 +3064,7 @@ bool QgsAuthManager::reencryptAuthenticationConfig( const QString &authcfg, cons query.prepare( QString( "SELECT config FROM %1 " "WHERE id = :id" ).arg( authDbConfigTable() ) ); - query.bindValue( ":id", authcfg ); + query.bindValue( QStringLiteral( ":id" ), authcfg ); if ( !authDbQuery( &query ) ) return false; @@ -3092,8 +3092,8 @@ bool QgsAuthManager::reencryptAuthenticationConfig( const QString &authcfg, cons "SET config = :config " "WHERE id = :id" ).arg( authDbConfigTable() ) ); - query.bindValue( ":id", authcfg ); - query.bindValue( ":config", QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring ) ); + query.bindValue( QStringLiteral( ":id" ), authcfg ); + query.bindValue( QStringLiteral( ":config" ), QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), configstring ) ); if ( !authDbStartTransaction() ) return false; @@ -3228,7 +3228,7 @@ bool QgsAuthManager::reencryptAuthenticationIdentity( query.prepare( QString( "SELECT key FROM %1 " "WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", identid ); + query.bindValue( QStringLiteral( ":id" ), identid ); if ( !authDbQuery( &query ) ) return false; @@ -3256,8 +3256,8 @@ bool QgsAuthManager::reencryptAuthenticationIdentity( "SET key = :key " "WHERE id = :id" ).arg( authDbIdentitiesTable() ) ); - query.bindValue( ":id", identid ); - query.bindValue( ":key", QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), keystring ) ); + query.bindValue( QStringLiteral( ":id" ), identid ); + query.bindValue( QStringLiteral( ":key" ), QgsAuthCrypto::encrypt( mMasterPass, masterPasswordCiv(), keystring ) ); if ( !authDbStartTransaction() ) return false; diff --git a/src/core/auth/qgsauthmethodregistry.cpp b/src/core/auth/qgsauthmethodregistry.cpp index 148cb7ebfab1..62bc0381ea46 100644 --- a/src/core/auth/qgsauthmethodregistry.cpp +++ b/src/core/auth/qgsauthmethodregistry.cpp @@ -60,7 +60,7 @@ QgsAuthMethodRegistry::QgsAuthMethodRegistry( const QString& pluginPath ) #if defined(Q_OS_WIN) || defined(__CYGWIN__) mLibraryDirectory.setNameFilters( QStringList( "*authmethod.dll" ) ); #else - mLibraryDirectory.setNameFilters( QStringList( "*authmethod.so" ) ); + mLibraryDirectory.setNameFilters( QStringList( QStringLiteral( "*authmethod.so" ) ) ); #endif QgsDebugMsg( QString( "Checking for auth method plugins in: %1" ).arg( mLibraryDirectory.path() ) ); @@ -214,14 +214,14 @@ QString QgsAuthMethodRegistry::pluginList( bool asHtml ) const if ( asHtml ) { - list += "
                                                                                                                                                                                      "; + list += QLatin1String( "
                                                                                                                                                                                        " ); } while ( it != mAuthMethods.end() ) { if ( asHtml ) { - list += "
                                                                                                                                                                                      1. "; + list += QLatin1String( "
                                                                                                                                                                                      2. " ); } list += it->second->description(); @@ -240,7 +240,7 @@ QString QgsAuthMethodRegistry::pluginList( bool asHtml ) const if ( asHtml ) { - list += "
                                                                                                                                                                                      "; + list += QLatin1String( "
                                                                                                                                                                                    " ); } return list; diff --git a/src/core/composer/qgsatlascomposition.cpp b/src/core/composer/qgsatlascomposition.cpp index 1cea67e96db0..5d2d8c739e0c 100644 --- a/src/core/composer/qgsatlascomposition.cpp +++ b/src/core/composer/qgsatlascomposition.cpp @@ -36,7 +36,7 @@ QgsAtlasComposition::QgsAtlasComposition( QgsComposition* composition ) : mComposition( composition ) , mEnabled( false ) , mHideCoverage( false ) - , mFilenamePattern( "'output_'||@atlas_featurenumber" ) + , mFilenamePattern( QStringLiteral( "'output_'||@atlas_featurenumber" ) ) , mCoverageLayer( nullptr ) , mSingleFile( false ) , mSortFeatures( false ) @@ -582,8 +582,8 @@ QString QgsAtlasComposition::currentFilename() const void QgsAtlasComposition::writeXml( QDomElement& elem, QDomDocument& doc ) const { - QDomElement atlasElem = doc.createElement( "Atlas" ); - atlasElem.setAttribute( "enabled", mEnabled ? "true" : "false" ); + QDomElement atlasElem = doc.createElement( QStringLiteral( "Atlas" ) ); + atlasElem.setAttribute( QStringLiteral( "enabled" ), mEnabled ? "true" : "false" ); if ( !mEnabled ) { return; @@ -591,28 +591,28 @@ void QgsAtlasComposition::writeXml( QDomElement& elem, QDomDocument& doc ) const if ( mCoverageLayer ) { - atlasElem.setAttribute( "coverageLayer", mCoverageLayer->id() ); + atlasElem.setAttribute( QStringLiteral( "coverageLayer" ), mCoverageLayer->id() ); } else { - atlasElem.setAttribute( "coverageLayer", "" ); + atlasElem.setAttribute( QStringLiteral( "coverageLayer" ), QLatin1String( "" ) ); } - atlasElem.setAttribute( "hideCoverage", mHideCoverage ? "true" : "false" ); - atlasElem.setAttribute( "singleFile", mSingleFile ? "true" : "false" ); - atlasElem.setAttribute( "filenamePattern", mFilenamePattern ); - atlasElem.setAttribute( "pageNameExpression", mPageNameExpression ); + atlasElem.setAttribute( QStringLiteral( "hideCoverage" ), mHideCoverage ? "true" : "false" ); + atlasElem.setAttribute( QStringLiteral( "singleFile" ), mSingleFile ? "true" : "false" ); + atlasElem.setAttribute( QStringLiteral( "filenamePattern" ), mFilenamePattern ); + atlasElem.setAttribute( QStringLiteral( "pageNameExpression" ), mPageNameExpression ); - atlasElem.setAttribute( "sortFeatures", mSortFeatures ? "true" : "false" ); + atlasElem.setAttribute( QStringLiteral( "sortFeatures" ), mSortFeatures ? "true" : "false" ); if ( mSortFeatures ) { - atlasElem.setAttribute( "sortKey", mSortKeyAttributeName ); - atlasElem.setAttribute( "sortAscending", mSortAscending ? "true" : "false" ); + atlasElem.setAttribute( QStringLiteral( "sortKey" ), mSortKeyAttributeName ); + atlasElem.setAttribute( QStringLiteral( "sortAscending" ), mSortAscending ? "true" : "false" ); } - atlasElem.setAttribute( "filterFeatures", mFilterFeatures ? "true" : "false" ); + atlasElem.setAttribute( QStringLiteral( "filterFeatures" ), mFilterFeatures ? "true" : "false" ); if ( mFilterFeatures ) { - atlasElem.setAttribute( "featureFilter", mFeatureFilter ); + atlasElem.setAttribute( QStringLiteral( "featureFilter" ), mFeatureFilter ); } elem.appendChild( atlasElem ); @@ -620,7 +620,7 @@ void QgsAtlasComposition::writeXml( QDomElement& elem, QDomDocument& doc ) const void QgsAtlasComposition::readXml( const QDomElement& atlasElem, const QDomDocument& ) { - mEnabled = atlasElem.attribute( "enabled", "false" ) == "true" ? true : false; + mEnabled = atlasElem.attribute( QStringLiteral( "enabled" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; emit toggled( mEnabled ); if ( !mEnabled ) { @@ -633,21 +633,21 @@ void QgsAtlasComposition::readXml( const QDomElement& atlasElem, const QDomDocum QMap layers = QgsMapLayerRegistry::instance()->mapLayers(); for ( QMap::const_iterator it = layers.begin(); it != layers.end(); ++it ) { - if ( it.key() == atlasElem.attribute( "coverageLayer" ) ) + if ( it.key() == atlasElem.attribute( QStringLiteral( "coverageLayer" ) ) ) { mCoverageLayer = dynamic_cast( it.value() ); break; } } - mPageNameExpression = atlasElem.attribute( "pageNameExpression", QString() ); - mSingleFile = atlasElem.attribute( "singleFile", "false" ) == "true" ? true : false; - mFilenamePattern = atlasElem.attribute( "filenamePattern", "" ); + mPageNameExpression = atlasElem.attribute( QStringLiteral( "pageNameExpression" ), QString() ); + mSingleFile = atlasElem.attribute( QStringLiteral( "singleFile" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; + mFilenamePattern = atlasElem.attribute( QStringLiteral( "filenamePattern" ), QLatin1String( "" ) ); - mSortFeatures = atlasElem.attribute( "sortFeatures", "false" ) == "true" ? true : false; + mSortFeatures = atlasElem.attribute( QStringLiteral( "sortFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; if ( mSortFeatures ) { - mSortKeyAttributeName = atlasElem.attribute( "sortKey", "" ); + mSortKeyAttributeName = atlasElem.attribute( QStringLiteral( "sortKey" ), QLatin1String( "" ) ); // since 2.3, the field name is saved instead of the field index // following code keeps compatibility with version 2.2 projects // to be removed in QGIS 3.0 @@ -661,15 +661,15 @@ void QgsAtlasComposition::readXml( const QDomElement& atlasElem, const QDomDocum mSortKeyAttributeName = fields.at( idx ).name(); } } - mSortAscending = atlasElem.attribute( "sortAscending", "true" ) == "true" ? true : false; + mSortAscending = atlasElem.attribute( QStringLiteral( "sortAscending" ), QStringLiteral( "true" ) ) == QLatin1String( "true" ) ? true : false; } - mFilterFeatures = atlasElem.attribute( "filterFeatures", "false" ) == "true" ? true : false; + mFilterFeatures = atlasElem.attribute( QStringLiteral( "filterFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; if ( mFilterFeatures ) { - mFeatureFilter = atlasElem.attribute( "featureFilter", "" ); + mFeatureFilter = atlasElem.attribute( QStringLiteral( "featureFilter" ), QLatin1String( "" ) ); } - mHideCoverage = atlasElem.attribute( "hideCoverage", "false" ) == "true" ? true : false; + mHideCoverage = atlasElem.attribute( QStringLiteral( "hideCoverage" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; emit parameterChanged(); } @@ -678,7 +678,7 @@ void QgsAtlasComposition::readXmlMapSettings( const QDomElement &elem, const QDo { Q_UNUSED( doc ); //look for stored composer map, to upgrade pre 2.1 projects - int composerMapNo = elem.attribute( "composerMap", "-1" ).toInt(); + int composerMapNo = elem.attribute( QStringLiteral( "composerMap" ), QStringLiteral( "-1" ) ).toInt(); QgsComposerMap * composerMap = nullptr; if ( composerMapNo != -1 ) { @@ -696,12 +696,12 @@ void QgsAtlasComposition::readXmlMapSettings( const QDomElement &elem, const QDo } //upgrade pre 2.1 projects - double margin = elem.attribute( "margin", "0.0" ).toDouble(); + double margin = elem.attribute( QStringLiteral( "margin" ), QStringLiteral( "0.0" ) ).toDouble(); if ( composerMap && !qgsDoubleNear( margin, 0.0 ) ) { composerMap->setAtlasMargin( margin ); } - bool fixedScale = elem.attribute( "fixedScale", "false" ) == "true" ? true : false; + bool fixedScale = elem.attribute( QStringLiteral( "fixedScale" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; if ( composerMap && fixedScale ) { composerMap->setAtlasScalingMode( QgsComposerMap::Fixed ); diff --git a/src/core/composer/qgscomposerarrow.cpp b/src/core/composer/qgscomposerarrow.cpp index 977978acafe0..9b7109940826 100644 --- a/src/core/composer/qgscomposerarrow.cpp +++ b/src/core/composer/qgscomposerarrow.cpp @@ -82,9 +82,9 @@ void QgsComposerArrow::createDefaultLineSymbol() { delete mLineSymbol; QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "width", "1" ); - properties.insert( "capstyle", "square" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "width" ), QStringLiteral( "1" ) ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "square" ) ); mLineSymbol = QgsLineSymbol::createSimple( properties ); } @@ -426,31 +426,31 @@ void QgsComposerArrow::setMarkerMode( MarkerMode mode ) bool QgsComposerArrow::writeXml( QDomElement& elem, QDomDocument & doc ) const { - QDomElement composerArrowElem = doc.createElement( "ComposerArrow" ); - composerArrowElem.setAttribute( "arrowHeadWidth", QString::number( mArrowHeadWidth ) ); - composerArrowElem.setAttribute( "arrowHeadFillColor", QgsSymbolLayerUtils::encodeColor( mArrowHeadFillColor ) ); - composerArrowElem.setAttribute( "arrowHeadOutlineColor", QgsSymbolLayerUtils::encodeColor( mArrowHeadOutlineColor ) ); - composerArrowElem.setAttribute( "outlineWidth", QString::number( mArrowHeadOutlineWidth ) ); - composerArrowElem.setAttribute( "markerMode", mMarkerMode ); - composerArrowElem.setAttribute( "startMarkerFile", mStartMarkerFile ); - composerArrowElem.setAttribute( "endMarkerFile", mEndMarkerFile ); - composerArrowElem.setAttribute( "boundsBehaviourVersion", QString::number( mBoundsBehaviour ) ); - - QDomElement styleElem = doc.createElement( "lineStyle" ); + QDomElement composerArrowElem = doc.createElement( QStringLiteral( "ComposerArrow" ) ); + composerArrowElem.setAttribute( QStringLiteral( "arrowHeadWidth" ), QString::number( mArrowHeadWidth ) ); + composerArrowElem.setAttribute( QStringLiteral( "arrowHeadFillColor" ), QgsSymbolLayerUtils::encodeColor( mArrowHeadFillColor ) ); + composerArrowElem.setAttribute( QStringLiteral( "arrowHeadOutlineColor" ), QgsSymbolLayerUtils::encodeColor( mArrowHeadOutlineColor ) ); + composerArrowElem.setAttribute( QStringLiteral( "outlineWidth" ), QString::number( mArrowHeadOutlineWidth ) ); + composerArrowElem.setAttribute( QStringLiteral( "markerMode" ), mMarkerMode ); + composerArrowElem.setAttribute( QStringLiteral( "startMarkerFile" ), mStartMarkerFile ); + composerArrowElem.setAttribute( QStringLiteral( "endMarkerFile" ), mEndMarkerFile ); + composerArrowElem.setAttribute( QStringLiteral( "boundsBehaviourVersion" ), QString::number( mBoundsBehaviour ) ); + + QDomElement styleElem = doc.createElement( QStringLiteral( "lineStyle" ) ); QDomElement lineStyleElem = QgsSymbolLayerUtils::saveSymbol( QString(), mLineSymbol, doc ); styleElem.appendChild( lineStyleElem ); composerArrowElem.appendChild( styleElem ); //start point - QDomElement startPointElem = doc.createElement( "StartPoint" ); - startPointElem.setAttribute( "x", QString::number( mStartPoint.x() ) ); - startPointElem.setAttribute( "y", QString::number( mStartPoint.y() ) ); + QDomElement startPointElem = doc.createElement( QStringLiteral( "StartPoint" ) ); + startPointElem.setAttribute( QStringLiteral( "x" ), QString::number( mStartPoint.x() ) ); + startPointElem.setAttribute( QStringLiteral( "y" ), QString::number( mStartPoint.y() ) ); composerArrowElem.appendChild( startPointElem ); //stop point - QDomElement stopPointElem = doc.createElement( "StopPoint" ); - stopPointElem.setAttribute( "x", QString::number( mStopPoint.x() ) ); - stopPointElem.setAttribute( "y", QString::number( mStopPoint.y() ) ); + QDomElement stopPointElem = doc.createElement( QStringLiteral( "StopPoint" ) ); + stopPointElem.setAttribute( QStringLiteral( "x" ), QString::number( mStopPoint.x() ) ); + stopPointElem.setAttribute( QStringLiteral( "y" ), QString::number( mStopPoint.y() ) ); composerArrowElem.appendChild( stopPointElem ); elem.appendChild( composerArrowElem ); @@ -459,21 +459,21 @@ bool QgsComposerArrow::writeXml( QDomElement& elem, QDomDocument & doc ) const bool QgsComposerArrow::readXml( const QDomElement& itemElem, const QDomDocument& doc ) { - mArrowHeadWidth = itemElem.attribute( "arrowHeadWidth", "2.0" ).toDouble(); - mArrowHeadFillColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "arrowHeadFillColor", "0,0,0,255" ) ); - mArrowHeadOutlineColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "arrowHeadOutlineColor", "0,0,0,255" ) ); - mArrowHeadOutlineWidth = itemElem.attribute( "outlineWidth", "1.0" ).toDouble(); - setStartMarker( itemElem.attribute( "startMarkerFile", "" ) ); - setEndMarker( itemElem.attribute( "endMarkerFile", "" ) ); - mMarkerMode = QgsComposerArrow::MarkerMode( itemElem.attribute( "markerMode", "0" ).toInt() ); + mArrowHeadWidth = itemElem.attribute( QStringLiteral( "arrowHeadWidth" ), QStringLiteral( "2.0" ) ).toDouble(); + mArrowHeadFillColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "arrowHeadFillColor" ), QStringLiteral( "0,0,0,255" ) ) ); + mArrowHeadOutlineColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "arrowHeadOutlineColor" ), QStringLiteral( "0,0,0,255" ) ) ); + mArrowHeadOutlineWidth = itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "1.0" ) ).toDouble(); + setStartMarker( itemElem.attribute( QStringLiteral( "startMarkerFile" ), QLatin1String( "" ) ) ); + setEndMarker( itemElem.attribute( QStringLiteral( "endMarkerFile" ), QLatin1String( "" ) ) ); + mMarkerMode = QgsComposerArrow::MarkerMode( itemElem.attribute( QStringLiteral( "markerMode" ), QStringLiteral( "0" ) ).toInt() ); //if bounds behaviour version is not set, default to 2.2 behaviour - mBoundsBehaviour = itemElem.attribute( "boundsBehaviourVersion", "22" ).toInt(); + mBoundsBehaviour = itemElem.attribute( QStringLiteral( "boundsBehaviourVersion" ), QStringLiteral( "22" ) ).toInt(); //arrow style - QDomElement styleElem = itemElem.firstChildElement( "lineStyle" ); + QDomElement styleElem = itemElem.firstChildElement( QStringLiteral( "lineStyle" ) ); if ( !styleElem.isNull() ) { - QDomElement lineStyleElem = styleElem.firstChildElement( "symbol" ); + QDomElement lineStyleElem = styleElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !lineStyleElem.isNull() ) { delete mLineSymbol; @@ -486,34 +486,34 @@ bool QgsComposerArrow::readXml( const QDomElement& itemElem, const QDomDocument& delete mLineSymbol; QgsStringMap properties; - properties.insert( "width", itemElem.attribute( "outlineWidth", "1.0" ) ); + properties.insert( QStringLiteral( "width" ), itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "1.0" ) ) ); if ( mBoundsBehaviour == 22 ) { //if arrow was created in versions prior to 2.4, use the old rendering style - properties.insert( "capstyle", "flat" ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "flat" ) ); } else { - properties.insert( "capstyle", "square" ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "square" ) ); } int red = 0; int blue = 0; int green = 0; int alpha = 255; - QDomNodeList arrowColorList = itemElem.elementsByTagName( "ArrowColor" ); + QDomNodeList arrowColorList = itemElem.elementsByTagName( QStringLiteral( "ArrowColor" ) ); if ( !arrowColorList.isEmpty() ) { QDomElement arrowColorElem = arrowColorList.at( 0 ).toElement(); - red = arrowColorElem.attribute( "red", "0" ).toInt(); - green = arrowColorElem.attribute( "green", "0" ).toInt(); - blue = arrowColorElem.attribute( "blue", "0" ).toInt(); - alpha = arrowColorElem.attribute( "alpha", "255" ).toInt(); + red = arrowColorElem.attribute( QStringLiteral( "red" ), QStringLiteral( "0" ) ).toInt(); + green = arrowColorElem.attribute( QStringLiteral( "green" ), QStringLiteral( "0" ) ).toInt(); + blue = arrowColorElem.attribute( QStringLiteral( "blue" ), QStringLiteral( "0" ) ).toInt(); + alpha = arrowColorElem.attribute( QStringLiteral( "alpha" ), QStringLiteral( "255" ) ).toInt(); mArrowHeadFillColor = QColor( red, green, blue, alpha ); mArrowHeadOutlineColor = QColor( red, green, blue, alpha ); } - properties.insert( "color", QString( "%1,%2,%3,%4" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "%1,%2,%3,%4" ).arg( red ).arg( green ).arg( blue ).arg( alpha ) ); mLineSymbol = QgsLineSymbol::createSimple( properties ); } @@ -523,7 +523,7 @@ bool QgsComposerArrow::readXml( const QDomElement& itemElem, const QDomDocument& //restore general composer item properties //needs to be before start point / stop point because setSceneRect() - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); @@ -531,21 +531,21 @@ bool QgsComposerArrow::readXml( const QDomElement& itemElem, const QDomDocument& } //start point - QDomNodeList startPointList = itemElem.elementsByTagName( "StartPoint" ); + QDomNodeList startPointList = itemElem.elementsByTagName( QStringLiteral( "StartPoint" ) ); if ( !startPointList.isEmpty() ) { QDomElement startPointElem = startPointList.at( 0 ).toElement(); - mStartPoint.setX( startPointElem.attribute( "x", "0.0" ).toDouble() ); - mStartPoint.setY( startPointElem.attribute( "y", "0.0" ).toDouble() ); + mStartPoint.setX( startPointElem.attribute( QStringLiteral( "x" ), QStringLiteral( "0.0" ) ).toDouble() ); + mStartPoint.setY( startPointElem.attribute( QStringLiteral( "y" ), QStringLiteral( "0.0" ) ).toDouble() ); } //stop point - QDomNodeList stopPointList = itemElem.elementsByTagName( "StopPoint" ); + QDomNodeList stopPointList = itemElem.elementsByTagName( QStringLiteral( "StopPoint" ) ); if ( !stopPointList.isEmpty() ) { QDomElement stopPointElem = stopPointList.at( 0 ).toElement(); - mStopPoint.setX( stopPointElem.attribute( "x", "0.0" ).toDouble() ); - mStopPoint.setY( stopPointElem.attribute( "y", "0.0" ).toDouble() ); + mStopPoint.setX( stopPointElem.attribute( QStringLiteral( "x" ), QStringLiteral( "0.0" ) ).toDouble() ); + mStopPoint.setY( stopPointElem.attribute( QStringLiteral( "y" ), QStringLiteral( "0.0" ) ).toDouble() ); } mStartXIdx = mStopPoint.x() < mStartPoint.x(); diff --git a/src/core/composer/qgscomposerattributetablev2.cpp b/src/core/composer/qgscomposerattributetablev2.cpp index a8062962dc45..1c88e4fe8530 100644 --- a/src/core/composer/qgscomposerattributetablev2.cpp +++ b/src/core/composer/qgscomposerattributetablev2.cpp @@ -60,7 +60,7 @@ QgsComposerAttributeTableV2::QgsComposerAttributeTableV2( QgsComposition* compos , mShowOnlyVisibleFeatures( false ) , mFilterToAtlasIntersection( false ) , mFilterFeatures( false ) - , mFeatureFilter( "" ) + , mFeatureFilter( QLatin1String( "" ) ) { //set first vector layer from layer registry as default one QMap layerMap = QgsMapLayerRegistry::instance()->mapLayers(); @@ -508,7 +508,7 @@ bool QgsComposerAttributeTableV2::getTableContents( QgsComposerTableContents &co { // Lets assume it's an expression QgsExpression* expression = new QgsExpression(( *columnIt )->attribute() ); - context.lastScope()->setVariable( QString( "row_number" ), counter + 1 ); + context.lastScope()->setVariable( QStringLiteral( "row_number" ), counter + 1 ); expression->prepare( &context ); QVariant value = expression->evaluate( &context ); currentRow << value; @@ -555,7 +555,7 @@ QVariant QgsComposerAttributeTableV2::replaceWrapChar( const QVariant &variant ) return variant; QString replaced = variant.toString(); - replaced.replace( mWrapString, "\n" ); + replaced.replace( mWrapString, QLatin1String( "\n" ) ); return replaced; } @@ -639,28 +639,28 @@ void QgsComposerAttributeTableV2::setWrapString( const QString &wrapString ) bool QgsComposerAttributeTableV2::writeXml( QDomElement& elem, QDomDocument & doc, bool ignoreFrames ) const { - QDomElement composerTableElem = doc.createElement( "ComposerAttributeTableV2" ); - composerTableElem.setAttribute( "source", QString::number( static_cast< int >( mSource ) ) ); - composerTableElem.setAttribute( "relationId", mRelationId ); - composerTableElem.setAttribute( "showUniqueRowsOnly", mShowUniqueRowsOnly ); - composerTableElem.setAttribute( "showOnlyVisibleFeatures", mShowOnlyVisibleFeatures ); - composerTableElem.setAttribute( "filterToAtlasIntersection", mFilterToAtlasIntersection ); - composerTableElem.setAttribute( "maxFeatures", mMaximumNumberOfFeatures ); - composerTableElem.setAttribute( "filterFeatures", mFilterFeatures ? "true" : "false" ); - composerTableElem.setAttribute( "featureFilter", mFeatureFilter ); - composerTableElem.setAttribute( "wrapString", mWrapString ); + QDomElement composerTableElem = doc.createElement( QStringLiteral( "ComposerAttributeTableV2" ) ); + composerTableElem.setAttribute( QStringLiteral( "source" ), QString::number( static_cast< int >( mSource ) ) ); + composerTableElem.setAttribute( QStringLiteral( "relationId" ), mRelationId ); + composerTableElem.setAttribute( QStringLiteral( "showUniqueRowsOnly" ), mShowUniqueRowsOnly ); + composerTableElem.setAttribute( QStringLiteral( "showOnlyVisibleFeatures" ), mShowOnlyVisibleFeatures ); + composerTableElem.setAttribute( QStringLiteral( "filterToAtlasIntersection" ), mFilterToAtlasIntersection ); + composerTableElem.setAttribute( QStringLiteral( "maxFeatures" ), mMaximumNumberOfFeatures ); + composerTableElem.setAttribute( QStringLiteral( "filterFeatures" ), mFilterFeatures ? "true" : "false" ); + composerTableElem.setAttribute( QStringLiteral( "featureFilter" ), mFeatureFilter ); + composerTableElem.setAttribute( QStringLiteral( "wrapString" ), mWrapString ); if ( mComposerMap ) { - composerTableElem.setAttribute( "composerMap", mComposerMap->id() ); + composerTableElem.setAttribute( QStringLiteral( "composerMap" ), mComposerMap->id() ); } else { - composerTableElem.setAttribute( "composerMap", -1 ); + composerTableElem.setAttribute( QStringLiteral( "composerMap" ), -1 ); } if ( mVectorLayer ) { - composerTableElem.setAttribute( "vectorLayer", mVectorLayer->id() ); + composerTableElem.setAttribute( QStringLiteral( "vectorLayer" ), mVectorLayer->id() ); } bool ok = QgsComposerTableV2::writeXml( composerTableElem, doc, ignoreFrames ); @@ -690,24 +690,24 @@ bool QgsComposerAttributeTableV2::readXml( const QDomElement& itemElem, const QD disconnect( prevLayer, SIGNAL( layerModified() ), this, SLOT( refreshAttributes() ) ); } - mSource = QgsComposerAttributeTableV2::ContentSource( itemElem.attribute( "source", "0" ).toInt() ); - mRelationId = itemElem.attribute( "relationId", "" ); + mSource = QgsComposerAttributeTableV2::ContentSource( itemElem.attribute( QStringLiteral( "source" ), QStringLiteral( "0" ) ).toInt() ); + mRelationId = itemElem.attribute( QStringLiteral( "relationId" ), QLatin1String( "" ) ); if ( mSource == QgsComposerAttributeTableV2::AtlasFeature ) { mCurrentAtlasLayer = mComposition->atlasComposition().coverageLayer(); } - mShowUniqueRowsOnly = itemElem.attribute( "showUniqueRowsOnly", "0" ).toInt(); - mShowOnlyVisibleFeatures = itemElem.attribute( "showOnlyVisibleFeatures", "1" ).toInt(); - mFilterToAtlasIntersection = itemElem.attribute( "filterToAtlasIntersection", "0" ).toInt(); - mFilterFeatures = itemElem.attribute( "filterFeatures", "false" ) == "true" ? true : false; - mFeatureFilter = itemElem.attribute( "featureFilter", "" ); - mMaximumNumberOfFeatures = itemElem.attribute( "maxFeatures", "5" ).toInt(); - mWrapString = itemElem.attribute( "wrapString" ); + mShowUniqueRowsOnly = itemElem.attribute( QStringLiteral( "showUniqueRowsOnly" ), QStringLiteral( "0" ) ).toInt(); + mShowOnlyVisibleFeatures = itemElem.attribute( QStringLiteral( "showOnlyVisibleFeatures" ), QStringLiteral( "1" ) ).toInt(); + mFilterToAtlasIntersection = itemElem.attribute( QStringLiteral( "filterToAtlasIntersection" ), QStringLiteral( "0" ) ).toInt(); + mFilterFeatures = itemElem.attribute( QStringLiteral( "filterFeatures" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; + mFeatureFilter = itemElem.attribute( QStringLiteral( "featureFilter" ), QLatin1String( "" ) ); + mMaximumNumberOfFeatures = itemElem.attribute( QStringLiteral( "maxFeatures" ), QStringLiteral( "5" ) ).toInt(); + mWrapString = itemElem.attribute( QStringLiteral( "wrapString" ) ); //composer map - int composerMapId = itemElem.attribute( "composerMap", "-1" ).toInt(); + int composerMapId = itemElem.attribute( QStringLiteral( "composerMap" ), QStringLiteral( "-1" ) ).toInt(); if ( composerMapId == -1 ) { mComposerMap = nullptr; @@ -729,8 +729,8 @@ bool QgsComposerAttributeTableV2::readXml( const QDomElement& itemElem, const QD } //vector layer - QString layerId = itemElem.attribute( "vectorLayer", "not_existing" ); - if ( layerId == "not_existing" ) + QString layerId = itemElem.attribute( QStringLiteral( "vectorLayer" ), QStringLiteral( "not_existing" ) ); + if ( layerId == QLatin1String( "not_existing" ) ) { mVectorLayer = nullptr; } diff --git a/src/core/composer/qgscomposerframe.cpp b/src/core/composer/qgscomposerframe.cpp index 6f0916afe366..6efc2194901e 100644 --- a/src/core/composer/qgscomposerframe.cpp +++ b/src/core/composer/qgscomposerframe.cpp @@ -52,13 +52,13 @@ QgsComposerFrame::~QgsComposerFrame() bool QgsComposerFrame::writeXml( QDomElement& elem, QDomDocument & doc ) const { - QDomElement frameElem = doc.createElement( "ComposerFrame" ); - frameElem.setAttribute( "sectionX", QString::number( mSection.x() ) ); - frameElem.setAttribute( "sectionY", QString::number( mSection.y() ) ); - frameElem.setAttribute( "sectionWidth", QString::number( mSection.width() ) ); - frameElem.setAttribute( "sectionHeight", QString::number( mSection.height() ) ); - frameElem.setAttribute( "hidePageIfEmpty", mHidePageIfEmpty ); - frameElem.setAttribute( "hideBackgroundIfEmpty", mHideBackgroundIfEmpty ); + QDomElement frameElem = doc.createElement( QStringLiteral( "ComposerFrame" ) ); + frameElem.setAttribute( QStringLiteral( "sectionX" ), QString::number( mSection.x() ) ); + frameElem.setAttribute( QStringLiteral( "sectionY" ), QString::number( mSection.y() ) ); + frameElem.setAttribute( QStringLiteral( "sectionWidth" ), QString::number( mSection.width() ) ); + frameElem.setAttribute( QStringLiteral( "sectionHeight" ), QString::number( mSection.height() ) ); + frameElem.setAttribute( QStringLiteral( "hidePageIfEmpty" ), mHidePageIfEmpty ); + frameElem.setAttribute( QStringLiteral( "hideBackgroundIfEmpty" ), mHideBackgroundIfEmpty ); elem.appendChild( frameElem ); return _writeXml( frameElem, doc ); @@ -66,14 +66,14 @@ bool QgsComposerFrame::writeXml( QDomElement& elem, QDomDocument & doc ) const bool QgsComposerFrame::readXml( const QDomElement& itemElem, const QDomDocument& doc ) { - double x = itemElem.attribute( "sectionX" ).toDouble(); - double y = itemElem.attribute( "sectionY" ).toDouble(); - double width = itemElem.attribute( "sectionWidth" ).toDouble(); - double height = itemElem.attribute( "sectionHeight" ).toDouble(); + double x = itemElem.attribute( QStringLiteral( "sectionX" ) ).toDouble(); + double y = itemElem.attribute( QStringLiteral( "sectionY" ) ).toDouble(); + double width = itemElem.attribute( QStringLiteral( "sectionWidth" ) ).toDouble(); + double height = itemElem.attribute( QStringLiteral( "sectionHeight" ) ).toDouble(); mSection = QRectF( x, y, width, height ); - mHidePageIfEmpty = itemElem.attribute( "hidePageIfEmpty", "0" ).toInt(); - mHideBackgroundIfEmpty = itemElem.attribute( "hideBackgroundIfEmpty", "0" ).toInt(); - QDomElement composerItem = itemElem.firstChildElement( "ComposerItem" ); + mHidePageIfEmpty = itemElem.attribute( QStringLiteral( "hidePageIfEmpty" ), QStringLiteral( "0" ) ).toInt(); + mHideBackgroundIfEmpty = itemElem.attribute( QStringLiteral( "hideBackgroundIfEmpty" ), QStringLiteral( "0" ) ).toInt(); + QDomElement composerItem = itemElem.firstChildElement( QStringLiteral( "ComposerItem" ) ); if ( composerItem.isNull() ) { return false; diff --git a/src/core/composer/qgscomposerhtml.cpp b/src/core/composer/qgscomposerhtml.cpp index 5a6d113c8e25..18bbbc2059e6 100644 --- a/src/core/composer/qgscomposerhtml.cpp +++ b/src/core/composer/qgscomposerhtml.cpp @@ -71,7 +71,7 @@ QgsComposerHtml::QgsComposerHtml( QgsComposition* c, bool createUndoCommands ) } // data defined strings - mDataDefinedNames.insert( QgsComposerObject::SourceUrl, QString( "dataDefinedSourceUrl" ) ); + mDataDefinedNames.insert( QgsComposerObject::SourceUrl, QStringLiteral( "dataDefinedSourceUrl" ) ); if ( mComposition && mComposition->atlasMode() == QgsComposition::PreviewAtlas ) { @@ -210,7 +210,7 @@ void QgsComposerHtml::loadHtml( const bool useCache, const QgsExpressionContext //inject JSON feature if ( !mAtlasFeatureJSON.isEmpty() ) { - mWebPage->mainFrame()->evaluateJavaScript( QString( "if ( typeof setFeature === \"function\" ) { setFeature(%1); }" ).arg( mAtlasFeatureJSON ) ); + mWebPage->mainFrame()->evaluateJavaScript( QStringLiteral( "if ( typeof setFeature === \"function\" ) { setFeature(%1); }" ).arg( mAtlasFeatureJSON ) ); //needs an extra process events here to give javascript a chance to execute qApp->processEvents(); } @@ -475,15 +475,15 @@ QString QgsComposerHtml::displayName() const bool QgsComposerHtml::writeXml( QDomElement& elem, QDomDocument & doc, bool ignoreFrames ) const { - QDomElement htmlElem = doc.createElement( "ComposerHtml" ); - htmlElem.setAttribute( "contentMode", QString::number( static_cast< int >( mContentMode ) ) ); - htmlElem.setAttribute( "url", mUrl.toString() ); - htmlElem.setAttribute( "html", mHtml ); - htmlElem.setAttribute( "evaluateExpressions", mEvaluateExpressions ? "true" : "false" ); - htmlElem.setAttribute( "useSmartBreaks", mUseSmartBreaks ? "true" : "false" ); - htmlElem.setAttribute( "maxBreakDistance", QString::number( mMaxBreakDistance ) ); - htmlElem.setAttribute( "stylesheet", mUserStylesheet ); - htmlElem.setAttribute( "stylesheetEnabled", mEnableUserStylesheet ? "true" : "false" ); + QDomElement htmlElem = doc.createElement( QStringLiteral( "ComposerHtml" ) ); + htmlElem.setAttribute( QStringLiteral( "contentMode" ), QString::number( static_cast< int >( mContentMode ) ) ); + htmlElem.setAttribute( QStringLiteral( "url" ), mUrl.toString() ); + htmlElem.setAttribute( QStringLiteral( "html" ), mHtml ); + htmlElem.setAttribute( QStringLiteral( "evaluateExpressions" ), mEvaluateExpressions ? "true" : "false" ); + htmlElem.setAttribute( QStringLiteral( "useSmartBreaks" ), mUseSmartBreaks ? "true" : "false" ); + htmlElem.setAttribute( QStringLiteral( "maxBreakDistance" ), QString::number( mMaxBreakDistance ) ); + htmlElem.setAttribute( QStringLiteral( "stylesheet" ), mUserStylesheet ); + htmlElem.setAttribute( QStringLiteral( "stylesheetEnabled" ), mEnableUserStylesheet ? "true" : "false" ); bool state = _writeXml( htmlElem, doc, ignoreFrames ); elem.appendChild( htmlElem ); @@ -504,20 +504,20 @@ bool QgsComposerHtml::readXml( const QDomElement& itemElem, const QDomDocument& } bool contentModeOK; - mContentMode = static_cast< QgsComposerHtml::ContentMode >( itemElem.attribute( "contentMode" ).toInt( &contentModeOK ) ); + mContentMode = static_cast< QgsComposerHtml::ContentMode >( itemElem.attribute( QStringLiteral( "contentMode" ) ).toInt( &contentModeOK ) ); if ( !contentModeOK ) { mContentMode = QgsComposerHtml::Url; } - mEvaluateExpressions = itemElem.attribute( "evaluateExpressions", "true" ) == "true" ? true : false; - mUseSmartBreaks = itemElem.attribute( "useSmartBreaks", "true" ) == "true" ? true : false; - mMaxBreakDistance = itemElem.attribute( "maxBreakDistance", "10" ).toDouble(); - mHtml = itemElem.attribute( "html" ); - mUserStylesheet = itemElem.attribute( "stylesheet" ); - mEnableUserStylesheet = itemElem.attribute( "stylesheetEnabled", "false" ) == "true" ? true : false; + mEvaluateExpressions = itemElem.attribute( QStringLiteral( "evaluateExpressions" ), QStringLiteral( "true" ) ) == QLatin1String( "true" ) ? true : false; + mUseSmartBreaks = itemElem.attribute( QStringLiteral( "useSmartBreaks" ), QStringLiteral( "true" ) ) == QLatin1String( "true" ) ? true : false; + mMaxBreakDistance = itemElem.attribute( QStringLiteral( "maxBreakDistance" ), QStringLiteral( "10" ) ).toDouble(); + mHtml = itemElem.attribute( QStringLiteral( "html" ) ); + mUserStylesheet = itemElem.attribute( QStringLiteral( "stylesheet" ) ); + mEnableUserStylesheet = itemElem.attribute( QStringLiteral( "stylesheetEnabled" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ) ? true : false; //finally load the set url - QString urlString = itemElem.attribute( "url" ); + QString urlString = itemElem.attribute( QStringLiteral( "url" ) ); if ( !urlString.isEmpty() ) { mUrl = urlString; diff --git a/src/core/composer/qgscomposeritem.cpp b/src/core/composer/qgscomposeritem.cpp index 2d7f38961852..58a93b312a38 100644 --- a/src/core/composer/qgscomposeritem.cpp +++ b/src/core/composer/qgscomposeritem.cpp @@ -68,7 +68,7 @@ QgsComposerItem::QgsComposerItem( QgsComposition* composition, bool manageZValue , mLastUsedPositionMode( UpperLeft ) , mIsGroupMember( false ) , mCurrentExportLayer( -1 ) - , mId( "" ) + , mId( QLatin1String( "" ) ) , mUuid( QUuid::createUuid().toString() ) { init( manageZValue ); @@ -97,7 +97,7 @@ QgsComposerItem::QgsComposerItem( qreal x, qreal y, qreal width, qreal height, Q , mLastUsedPositionMode( UpperLeft ) , mIsGroupMember( false ) , mCurrentExportLayer( -1 ) - , mId( "" ) + , mId( QLatin1String( "" ) ) , mUuid( QUuid::createUuid().toString() ) { init( manageZValue ); @@ -129,15 +129,15 @@ void QgsComposerItem::init( const bool manageZValue ) setGraphicsEffect( mEffect ); // data defined strings - mDataDefinedNames.insert( QgsComposerObject::PageNumber, QString( "dataDefinedPageNumber" ) ); - mDataDefinedNames.insert( QgsComposerObject::PositionX, QString( "dataDefinedPositionX" ) ); - mDataDefinedNames.insert( QgsComposerObject::PositionY, QString( "dataDefinedPositionY" ) ); - mDataDefinedNames.insert( QgsComposerObject::ItemWidth, QString( "dataDefinedWidth" ) ); - mDataDefinedNames.insert( QgsComposerObject::ItemHeight, QString( "dataDefinedHeight" ) ); - mDataDefinedNames.insert( QgsComposerObject::ItemRotation, QString( "dataDefinedRotation" ) ); - mDataDefinedNames.insert( QgsComposerObject::Transparency, QString( "dataDefinedTransparency" ) ); - mDataDefinedNames.insert( QgsComposerObject::BlendMode, QString( "dataDefinedBlendMode" ) ); - mDataDefinedNames.insert( QgsComposerObject::ExcludeFromExports, QString( "dataDefinedExcludeExports" ) ); + mDataDefinedNames.insert( QgsComposerObject::PageNumber, QStringLiteral( "dataDefinedPageNumber" ) ); + mDataDefinedNames.insert( QgsComposerObject::PositionX, QStringLiteral( "dataDefinedPositionX" ) ); + mDataDefinedNames.insert( QgsComposerObject::PositionY, QStringLiteral( "dataDefinedPositionY" ) ); + mDataDefinedNames.insert( QgsComposerObject::ItemWidth, QStringLiteral( "dataDefinedWidth" ) ); + mDataDefinedNames.insert( QgsComposerObject::ItemHeight, QStringLiteral( "dataDefinedHeight" ) ); + mDataDefinedNames.insert( QgsComposerObject::ItemRotation, QStringLiteral( "dataDefinedRotation" ) ); + mDataDefinedNames.insert( QgsComposerObject::Transparency, QStringLiteral( "dataDefinedTransparency" ) ); + mDataDefinedNames.insert( QgsComposerObject::BlendMode, QStringLiteral( "dataDefinedBlendMode" ) ); + mDataDefinedNames.insert( QgsComposerObject::ExcludeFromExports, QStringLiteral( "dataDefinedExcludeExports" ) ); } QgsComposerItem::~QgsComposerItem() @@ -171,82 +171,82 @@ bool QgsComposerItem::_writeXml( QDomElement& itemElem, QDomDocument& doc ) cons return false; } - QDomElement composerItemElem = doc.createElement( "ComposerItem" ); + QDomElement composerItemElem = doc.createElement( QStringLiteral( "ComposerItem" ) ); //frame if ( mFrame ) { - composerItemElem.setAttribute( "frame", "true" ); + composerItemElem.setAttribute( QStringLiteral( "frame" ), QStringLiteral( "true" ) ); } else { - composerItemElem.setAttribute( "frame", "false" ); + composerItemElem.setAttribute( QStringLiteral( "frame" ), QStringLiteral( "false" ) ); } //background if ( mBackground ) { - composerItemElem.setAttribute( "background", "true" ); + composerItemElem.setAttribute( QStringLiteral( "background" ), QStringLiteral( "true" ) ); } else { - composerItemElem.setAttribute( "background", "false" ); + composerItemElem.setAttribute( QStringLiteral( "background" ), QStringLiteral( "false" ) ); } //scene rect QPointF pagepos = pagePos(); - composerItemElem.setAttribute( "x", QString::number( pos().x() ) ); - composerItemElem.setAttribute( "y", QString::number( pos().y() ) ); - composerItemElem.setAttribute( "page", page() ); - composerItemElem.setAttribute( "pagex", QString::number( pagepos.x() ) ); - composerItemElem.setAttribute( "pagey", QString::number( pagepos.y() ) ); - composerItemElem.setAttribute( "width", QString::number( rect().width() ) ); - composerItemElem.setAttribute( "height", QString::number( rect().height() ) ); - composerItemElem.setAttribute( "positionMode", QString::number( static_cast< int >( mLastUsedPositionMode ) ) ); - composerItemElem.setAttribute( "zValue", QString::number( zValue() ) ); - composerItemElem.setAttribute( "outlineWidth", QString::number( pen().widthF() ) ); - composerItemElem.setAttribute( "frameJoinStyle", QgsSymbolLayerUtils::encodePenJoinStyle( mFrameJoinStyle ) ); - composerItemElem.setAttribute( "itemRotation", QString::number( mItemRotation ) ); - composerItemElem.setAttribute( "uuid", mUuid ); - composerItemElem.setAttribute( "id", mId ); - composerItemElem.setAttribute( "visibility", isVisible() ); + composerItemElem.setAttribute( QStringLiteral( "x" ), QString::number( pos().x() ) ); + composerItemElem.setAttribute( QStringLiteral( "y" ), QString::number( pos().y() ) ); + composerItemElem.setAttribute( QStringLiteral( "page" ), page() ); + composerItemElem.setAttribute( QStringLiteral( "pagex" ), QString::number( pagepos.x() ) ); + composerItemElem.setAttribute( QStringLiteral( "pagey" ), QString::number( pagepos.y() ) ); + composerItemElem.setAttribute( QStringLiteral( "width" ), QString::number( rect().width() ) ); + composerItemElem.setAttribute( QStringLiteral( "height" ), QString::number( rect().height() ) ); + composerItemElem.setAttribute( QStringLiteral( "positionMode" ), QString::number( static_cast< int >( mLastUsedPositionMode ) ) ); + composerItemElem.setAttribute( QStringLiteral( "zValue" ), QString::number( zValue() ) ); + composerItemElem.setAttribute( QStringLiteral( "outlineWidth" ), QString::number( pen().widthF() ) ); + composerItemElem.setAttribute( QStringLiteral( "frameJoinStyle" ), QgsSymbolLayerUtils::encodePenJoinStyle( mFrameJoinStyle ) ); + composerItemElem.setAttribute( QStringLiteral( "itemRotation" ), QString::number( mItemRotation ) ); + composerItemElem.setAttribute( QStringLiteral( "uuid" ), mUuid ); + composerItemElem.setAttribute( QStringLiteral( "id" ), mId ); + composerItemElem.setAttribute( QStringLiteral( "visibility" ), isVisible() ); //position lock for mouse moves/resizes if ( mItemPositionLocked ) { - composerItemElem.setAttribute( "positionLock", "true" ); + composerItemElem.setAttribute( QStringLiteral( "positionLock" ), QStringLiteral( "true" ) ); } else { - composerItemElem.setAttribute( "positionLock", "false" ); + composerItemElem.setAttribute( QStringLiteral( "positionLock" ), QStringLiteral( "false" ) ); } - composerItemElem.setAttribute( "lastValidViewScaleFactor", QString::number( mLastValidViewScaleFactor ) ); + composerItemElem.setAttribute( QStringLiteral( "lastValidViewScaleFactor" ), QString::number( mLastValidViewScaleFactor ) ); //frame color - QDomElement frameColorElem = doc.createElement( "FrameColor" ); + QDomElement frameColorElem = doc.createElement( QStringLiteral( "FrameColor" ) ); QColor frameColor = pen().color(); - frameColorElem.setAttribute( "red", QString::number( frameColor.red() ) ); - frameColorElem.setAttribute( "green", QString::number( frameColor.green() ) ); - frameColorElem.setAttribute( "blue", QString::number( frameColor.blue() ) ); - frameColorElem.setAttribute( "alpha", QString::number( frameColor.alpha() ) ); + frameColorElem.setAttribute( QStringLiteral( "red" ), QString::number( frameColor.red() ) ); + frameColorElem.setAttribute( QStringLiteral( "green" ), QString::number( frameColor.green() ) ); + frameColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( frameColor.blue() ) ); + frameColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( frameColor.alpha() ) ); composerItemElem.appendChild( frameColorElem ); //background color - QDomElement bgColorElem = doc.createElement( "BackgroundColor" ); + QDomElement bgColorElem = doc.createElement( QStringLiteral( "BackgroundColor" ) ); QColor bgColor = brush().color(); - bgColorElem.setAttribute( "red", QString::number( bgColor.red() ) ); - bgColorElem.setAttribute( "green", QString::number( bgColor.green() ) ); - bgColorElem.setAttribute( "blue", QString::number( bgColor.blue() ) ); - bgColorElem.setAttribute( "alpha", QString::number( bgColor.alpha() ) ); + bgColorElem.setAttribute( QStringLiteral( "red" ), QString::number( bgColor.red() ) ); + bgColorElem.setAttribute( QStringLiteral( "green" ), QString::number( bgColor.green() ) ); + bgColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( bgColor.blue() ) ); + bgColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( bgColor.alpha() ) ); composerItemElem.appendChild( bgColorElem ); //blend mode - composerItemElem.setAttribute( "blendMode", QgsPainting::getBlendModeEnum( mBlendMode ) ); + composerItemElem.setAttribute( QStringLiteral( "blendMode" ), QgsPainting::getBlendModeEnum( mBlendMode ) ); //transparency - composerItemElem.setAttribute( "transparency", QString::number( mTransparency ) ); + composerItemElem.setAttribute( QStringLiteral( "transparency" ), QString::number( mTransparency ) ); - composerItemElem.setAttribute( "excludeFromExports", mExcludeFromExports ); + composerItemElem.setAttribute( QStringLiteral( "excludeFromExports" ), mExcludeFromExports ); QgsComposerObject::writeXml( composerItemElem, doc ); itemElem.appendChild( composerItemElem ); @@ -265,21 +265,21 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& QgsComposerObject::readXml( itemElem, doc ); //rotation - setItemRotation( itemElem.attribute( "itemRotation", "0" ).toDouble() ); + setItemRotation( itemElem.attribute( QStringLiteral( "itemRotation" ), QStringLiteral( "0" ) ).toDouble() ); //uuid - mUuid = itemElem.attribute( "uuid", QUuid::createUuid().toString() ); + mUuid = itemElem.attribute( QStringLiteral( "uuid" ), QUuid::createUuid().toString() ); // temporary for groups imported from templates - mTemplateUuid = itemElem.attribute( "templateUuid" ); + mTemplateUuid = itemElem.attribute( QStringLiteral( "templateUuid" ) ); //id - QString id = itemElem.attribute( "id", "" ); + QString id = itemElem.attribute( QStringLiteral( "id" ), QLatin1String( "" ) ); setId( id ); //frame - QString frame = itemElem.attribute( "frame" ); - if ( frame.compare( "true", Qt::CaseInsensitive ) == 0 ) + QString frame = itemElem.attribute( QStringLiteral( "frame" ) ); + if ( frame.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { mFrame = true; } @@ -289,8 +289,8 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& } //frame - QString background = itemElem.attribute( "background" ); - if ( background.compare( "true", Qt::CaseInsensitive ) == 0 ) + QString background = itemElem.attribute( QStringLiteral( "background" ) ); + if ( background.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { mBackground = true; } @@ -300,8 +300,8 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& } //position lock for mouse moves/resizes - QString positionLock = itemElem.attribute( "positionLock" ); - if ( positionLock.compare( "true", Qt::CaseInsensitive ) == 0 ) + QString positionLock = itemElem.attribute( QStringLiteral( "positionLock" ) ); + if ( positionLock.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { setPositionLock( true ); } @@ -311,21 +311,21 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& } //visibility - setVisibility( itemElem.attribute( "visibility", "1" ) != "0" ); + setVisibility( itemElem.attribute( QStringLiteral( "visibility" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); //position int page; double x, y, pagex, pagey, width, height; bool xOk, yOk, pageOk, pagexOk, pageyOk, widthOk, heightOk, positionModeOK; - x = itemElem.attribute( "x" ).toDouble( &xOk ); - y = itemElem.attribute( "y" ).toDouble( &yOk ); - page = itemElem.attribute( "page" ).toInt( &pageOk ); - pagex = itemElem.attribute( "pagex" ).toDouble( &pagexOk ); - pagey = itemElem.attribute( "pagey" ).toDouble( &pageyOk ); - width = itemElem.attribute( "width" ).toDouble( &widthOk ); - height = itemElem.attribute( "height" ).toDouble( &heightOk ); - mLastUsedPositionMode = static_cast< ItemPositionMode >( itemElem.attribute( "positionMode" ).toInt( &positionModeOK ) ); + x = itemElem.attribute( QStringLiteral( "x" ) ).toDouble( &xOk ); + y = itemElem.attribute( QStringLiteral( "y" ) ).toDouble( &yOk ); + page = itemElem.attribute( QStringLiteral( "page" ) ).toInt( &pageOk ); + pagex = itemElem.attribute( QStringLiteral( "pagex" ) ).toDouble( &pagexOk ); + pagey = itemElem.attribute( QStringLiteral( "pagey" ) ).toDouble( &pageyOk ); + width = itemElem.attribute( QStringLiteral( "width" ) ).toDouble( &widthOk ); + height = itemElem.attribute( QStringLiteral( "height" ) ).toDouble( &heightOk ); + mLastUsedPositionMode = static_cast< ItemPositionMode >( itemElem.attribute( QStringLiteral( "positionMode" ) ).toInt( &positionModeOK ) ); if ( !positionModeOK ) { mLastUsedPositionMode = UpperLeft; @@ -343,12 +343,12 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& return false; } - mLastValidViewScaleFactor = itemElem.attribute( "lastValidViewScaleFactor", "-1" ).toDouble(); + mLastValidViewScaleFactor = itemElem.attribute( QStringLiteral( "lastValidViewScaleFactor" ), QStringLiteral( "-1" ) ).toDouble(); - setZValue( itemElem.attribute( "zValue" ).toDouble() ); + setZValue( itemElem.attribute( QStringLiteral( "zValue" ) ).toDouble() ); //pen - QDomNodeList frameColorList = itemElem.elementsByTagName( "FrameColor" ); + QDomNodeList frameColorList = itemElem.elementsByTagName( QStringLiteral( "FrameColor" ) ); if ( !frameColorList.isEmpty() ) { QDomElement frameColorElem = frameColorList.at( 0 ).toElement(); @@ -356,12 +356,12 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& int penRed, penGreen, penBlue, penAlpha; double penWidth; - penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk ); - penRed = frameColorElem.attribute( "red" ).toDouble( &redOk ); - penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk ); - penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk ); - penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk ); - mFrameJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( "frameJoinStyle", "miter" ) ); + penWidth = itemElem.attribute( QStringLiteral( "outlineWidth" ) ).toDouble( &widthOk ); + penRed = frameColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + penGreen = frameColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + penBlue = frameColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + penAlpha = frameColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); + mFrameJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( QStringLiteral( "frameJoinStyle" ), QStringLiteral( "miter" ) ) ); if ( redOk && greenOk && blueOk && alphaOk && widthOk ) { @@ -373,16 +373,16 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& } //brush - QDomNodeList bgColorList = itemElem.elementsByTagName( "BackgroundColor" ); + QDomNodeList bgColorList = itemElem.elementsByTagName( QStringLiteral( "BackgroundColor" ) ); if ( !bgColorList.isEmpty() ) { QDomElement bgColorElem = bgColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int bgRed, bgGreen, bgBlue, bgAlpha; - bgRed = bgColorElem.attribute( "red" ).toDouble( &redOk ); - bgGreen = bgColorElem.attribute( "green" ).toDouble( &greenOk ); - bgBlue = bgColorElem.attribute( "blue" ).toDouble( &blueOk ); - bgAlpha = bgColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + bgRed = bgColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + bgGreen = bgColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + bgBlue = bgColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + bgAlpha = bgColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { QColor brushColor( bgRed, bgGreen, bgBlue, bgAlpha ); @@ -391,12 +391,12 @@ bool QgsComposerItem::_readXml( const QDomElement& itemElem, const QDomDocument& } //blend mode - setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( "blendMode", "0" ).toUInt() ) ) ); + setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( QStringLiteral( "blendMode" ), QStringLiteral( "0" ) ).toUInt() ) ) ); //transparency - setTransparency( itemElem.attribute( "transparency", "0" ).toInt() ); + setTransparency( itemElem.attribute( QStringLiteral( "transparency" ), QStringLiteral( "0" ) ).toInt() ); - mExcludeFromExports = itemElem.attribute( "excludeFromExports", "0" ).toInt(); + mExcludeFromExports = itemElem.attribute( QStringLiteral( "excludeFromExports" ), QStringLiteral( "0" ) ).toInt(); mEvaluatedExcludeFromExports = mExcludeFromExports; QRectF evaluatedRect = evalItemRect( QRectF( x, y, width, height ) ); diff --git a/src/core/composer/qgscomposeritemcommand.cpp b/src/core/composer/qgscomposeritemcommand.cpp index ce662eae4fe4..8c29729d9415 100644 --- a/src/core/composer/qgscomposeritemcommand.cpp +++ b/src/core/composer/qgscomposeritemcommand.cpp @@ -103,7 +103,7 @@ void QgsComposerItemCommand::saveState( QDomDocument& stateDoc ) const } stateDoc.clear(); - QDomElement documentElement = stateDoc.createElement( "ComposerItemState" ); + QDomElement documentElement = stateDoc.createElement( QStringLiteral( "ComposerItemState" ) ); source->writeXml( documentElement, stateDoc ); stateDoc.appendChild( documentElement ); } diff --git a/src/core/composer/qgscomposeritemgroup.cpp b/src/core/composer/qgscomposeritemgroup.cpp index 97a0be167422..ad79d7e7d850 100644 --- a/src/core/composer/qgscomposeritemgroup.cpp +++ b/src/core/composer/qgscomposeritemgroup.cpp @@ -176,13 +176,13 @@ void QgsComposerItemGroup::drawFrame( QPainter* p ) bool QgsComposerItemGroup::writeXml( QDomElement& elem, QDomDocument & doc ) const { - QDomElement group = doc.createElement( "ComposerItemGroup" ); + QDomElement group = doc.createElement( QStringLiteral( "ComposerItemGroup" ) ); QSet::const_iterator itemIt = mItems.begin(); for ( ; itemIt != mItems.end(); ++itemIt ) { - QDomElement item = doc.createElement( "ComposerItemGroupElement" ); - item.setAttribute( "uuid", ( *itemIt )->uuid() ); + QDomElement item = doc.createElement( QStringLiteral( "ComposerItemGroupElement" ) ); + item.setAttribute( QStringLiteral( "uuid" ), ( *itemIt )->uuid() ); group.appendChild( item ); } @@ -194,7 +194,7 @@ bool QgsComposerItemGroup::writeXml( QDomElement& elem, QDomDocument & doc ) con bool QgsComposerItemGroup::readXml( const QDomElement& itemElem, const QDomDocument& doc ) { //restore general composer item properties - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); @@ -203,14 +203,14 @@ bool QgsComposerItemGroup::readXml( const QDomElement& itemElem, const QDomDocum QList items = mComposition->items(); - QDomNodeList elementNodes = itemElem.elementsByTagName( "ComposerItemGroupElement" ); + QDomNodeList elementNodes = itemElem.elementsByTagName( QStringLiteral( "ComposerItemGroupElement" ) ); for ( int i = 0; i < elementNodes.count(); ++i ) { QDomNode elementNode = elementNodes.at( i ); if ( !elementNode.isElement() ) continue; - QString uuid = elementNode.toElement().attribute( "uuid" ); + QString uuid = elementNode.toElement().attribute( QStringLiteral( "uuid" ) ); for ( QList::iterator it = items.begin(); it != items.end(); ++it ) { diff --git a/src/core/composer/qgscomposerlabel.cpp b/src/core/composer/qgscomposerlabel.cpp index 41e101eef243..f76f07deacab 100644 --- a/src/core/composer/qgscomposerlabel.cpp +++ b/src/core/composer/qgscomposerlabel.cpp @@ -58,7 +58,7 @@ QgsComposerLabel::QgsComposerLabel( QgsComposition *composition ) //get default composer font from settings QSettings settings; - QString defaultFontString = settings.value( "/Composer/defaultFont" ).toString(); + QString defaultFontString = settings.value( QStringLiteral( "/Composer/defaultFont" ) ).toString(); if ( !defaultFontString.isEmpty() ) { mFont.setFamily( defaultFontString ); @@ -289,7 +289,7 @@ QString QgsComposerLabel::displayText() const void QgsComposerLabel::replaceDateText( QString& text ) const { - QString constant = "$CURRENT_DATE"; + QString constant = QStringLiteral( "$CURRENT_DATE" ); int currentDatePos = text.indexOf( constant ); if ( currentDatePos != -1 ) { @@ -307,7 +307,7 @@ void QgsComposerLabel::replaceDateText( QString& text ) const } else //no bracket { - text.replace( "$CURRENT_DATE", QDate::currentDate().toString() ); + text.replace( QLatin1String( "$CURRENT_DATE" ), QDate::currentDate().toString() ); } } } @@ -368,25 +368,25 @@ bool QgsComposerLabel::writeXml( QDomElement& elem, QDomDocument & doc ) const return false; } - QDomElement composerLabelElem = doc.createElement( "ComposerLabel" ); + QDomElement composerLabelElem = doc.createElement( QStringLiteral( "ComposerLabel" ) ); - composerLabelElem.setAttribute( "htmlState", mHtmlState ); + composerLabelElem.setAttribute( QStringLiteral( "htmlState" ), mHtmlState ); - composerLabelElem.setAttribute( "labelText", mText ); - composerLabelElem.setAttribute( "marginX", QString::number( mMarginX ) ); - composerLabelElem.setAttribute( "marginY", QString::number( mMarginY ) ); - composerLabelElem.setAttribute( "halign", mHAlignment ); - composerLabelElem.setAttribute( "valign", mVAlignment ); + composerLabelElem.setAttribute( QStringLiteral( "labelText" ), mText ); + composerLabelElem.setAttribute( QStringLiteral( "marginX" ), QString::number( mMarginX ) ); + composerLabelElem.setAttribute( QStringLiteral( "marginY" ), QString::number( mMarginY ) ); + composerLabelElem.setAttribute( QStringLiteral( "halign" ), mHAlignment ); + composerLabelElem.setAttribute( QStringLiteral( "valign" ), mVAlignment ); //font - QDomElement labelFontElem = QgsFontUtils::toXmlElement( mFont, doc, "LabelFont" ); + QDomElement labelFontElem = QgsFontUtils::toXmlElement( mFont, doc, QStringLiteral( "LabelFont" ) ); composerLabelElem.appendChild( labelFontElem ); //font color - QDomElement fontColorElem = doc.createElement( "FontColor" ); - fontColorElem.setAttribute( "red", mFontColor.red() ); - fontColorElem.setAttribute( "green", mFontColor.green() ); - fontColorElem.setAttribute( "blue", mFontColor.blue() ); + QDomElement fontColorElem = doc.createElement( QStringLiteral( "FontColor" ) ); + fontColorElem.setAttribute( QStringLiteral( "red" ), mFontColor.red() ); + fontColorElem.setAttribute( QStringLiteral( "green" ), mFontColor.green() ); + fontColorElem.setAttribute( QStringLiteral( "blue" ), mFontColor.blue() ); composerLabelElem.appendChild( fontColorElem ); elem.appendChild( composerLabelElem ); @@ -403,41 +403,41 @@ bool QgsComposerLabel::readXml( const QDomElement& itemElem, const QDomDocument& //restore label specific properties //text - mText = itemElem.attribute( "labelText" ); + mText = itemElem.attribute( QStringLiteral( "labelText" ) ); //html state - mHtmlState = itemElem.attribute( "htmlState" ).toInt(); + mHtmlState = itemElem.attribute( QStringLiteral( "htmlState" ) ).toInt(); //margin bool marginXOk = false; bool marginYOk = false; - mMarginX = itemElem.attribute( "marginX" ).toDouble( &marginXOk ); - mMarginY = itemElem.attribute( "marginY" ).toDouble( &marginYOk ); + mMarginX = itemElem.attribute( QStringLiteral( "marginX" ) ).toDouble( &marginXOk ); + mMarginY = itemElem.attribute( QStringLiteral( "marginY" ) ).toDouble( &marginYOk ); if ( !marginXOk || !marginYOk ) { //upgrade old projects where margins where stored in a single attribute - double margin = itemElem.attribute( "margin", "1.0" ).toDouble(); + double margin = itemElem.attribute( QStringLiteral( "margin" ), QStringLiteral( "1.0" ) ).toDouble(); mMarginX = margin; mMarginY = margin; } //Horizontal alignment - mHAlignment = static_cast< Qt::AlignmentFlag >( itemElem.attribute( "halign" ).toInt() ); + mHAlignment = static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "halign" ) ).toInt() ); //Vertical alignment - mVAlignment = static_cast< Qt::AlignmentFlag >( itemElem.attribute( "valign" ).toInt() ); + mVAlignment = static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "valign" ) ).toInt() ); //font - QgsFontUtils::setFromXmlChildNode( mFont, itemElem, "LabelFont" ); + QgsFontUtils::setFromXmlChildNode( mFont, itemElem, QStringLiteral( "LabelFont" ) ); //font color - QDomNodeList fontColorList = itemElem.elementsByTagName( "FontColor" ); + QDomNodeList fontColorList = itemElem.elementsByTagName( QStringLiteral( "FontColor" ) ); if ( !fontColorList.isEmpty() ) { QDomElement fontColorElem = fontColorList.at( 0 ).toElement(); - int red = fontColorElem.attribute( "red", "0" ).toInt(); - int green = fontColorElem.attribute( "green", "0" ).toInt(); - int blue = fontColorElem.attribute( "blue", "0" ).toInt(); + int red = fontColorElem.attribute( QStringLiteral( "red" ), QStringLiteral( "0" ) ).toInt(); + int green = fontColorElem.attribute( QStringLiteral( "green" ), QStringLiteral( "0" ) ).toInt(); + int blue = fontColorElem.attribute( QStringLiteral( "blue" ), QStringLiteral( "0" ) ).toInt(); mFontColor = QColor( red, green, blue ); } else @@ -446,16 +446,16 @@ bool QgsComposerLabel::readXml( const QDomElement& itemElem, const QDomDocument& } //restore general composer item properties - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); //rotation - if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) ) + if ( !qgsDoubleNear( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { //check for old (pre 2.1) rotation attribute - setItemRotation( composerItemElem.attribute( "rotation", "0" ).toDouble() ); + setItemRotation( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble() ); } _readXml( composerItemElem, doc ); @@ -612,10 +612,10 @@ void QgsComposerLabel::itemShiftAdjustSize( double newWidth, double newHeight, d QUrl QgsComposerLabel::createStylesheetUrl() const { QString stylesheet; - stylesheet += QString( "body { margin: %1 %2;" ).arg( qMax( mMarginY * mHtmlUnitsToMM, 0.0 ) ).arg( qMax( mMarginX * mHtmlUnitsToMM, 0.0 ) ); + stylesheet += QStringLiteral( "body { margin: %1 %2;" ).arg( qMax( mMarginY * mHtmlUnitsToMM, 0.0 ) ).arg( qMax( mMarginX * mHtmlUnitsToMM, 0.0 ) ); stylesheet += QgsFontUtils::asCSS( mFont, 0.352778 * mHtmlUnitsToMM ); - stylesheet += QString( "color: %1;" ).arg( mFontColor.name() ); - stylesheet += QString( "text-align: %1; }" ).arg( mHAlignment == Qt::AlignLeft ? "left" : mHAlignment == Qt::AlignRight ? "right" : "center" ); + stylesheet += QStringLiteral( "color: %1;" ).arg( mFontColor.name() ); + stylesheet += QStringLiteral( "text-align: %1; }" ).arg( mHAlignment == Qt::AlignLeft ? "left" : mHAlignment == Qt::AlignRight ? "right" : "center" ); QByteArray ba; ba.append( stylesheet.toUtf8() ); diff --git a/src/core/composer/qgscomposerlegend.cpp b/src/core/composer/qgscomposerlegend.cpp index 04e45165ea3f..2bdb645466b2 100644 --- a/src/core/composer/qgscomposerlegend.cpp +++ b/src/core/composer/qgscomposerlegend.cpp @@ -357,46 +357,46 @@ bool QgsComposerLegend::writeXml( QDomElement& elem, QDomDocument & doc ) const return false; } - QDomElement composerLegendElem = doc.createElement( "ComposerLegend" ); + QDomElement composerLegendElem = doc.createElement( QStringLiteral( "ComposerLegend" ) ); elem.appendChild( composerLegendElem ); //write general properties - composerLegendElem.setAttribute( "title", mSettings.title() ); - composerLegendElem.setAttribute( "titleAlignment", QString::number( static_cast< int >( mSettings.titleAlignment() ) ) ); - composerLegendElem.setAttribute( "columnCount", QString::number( mSettings.columnCount() ) ); - composerLegendElem.setAttribute( "splitLayer", QString::number( mSettings.splitLayer() ) ); - composerLegendElem.setAttribute( "equalColumnWidth", QString::number( mSettings.equalColumnWidth() ) ); + composerLegendElem.setAttribute( QStringLiteral( "title" ), mSettings.title() ); + composerLegendElem.setAttribute( QStringLiteral( "titleAlignment" ), QString::number( static_cast< int >( mSettings.titleAlignment() ) ) ); + composerLegendElem.setAttribute( QStringLiteral( "columnCount" ), QString::number( mSettings.columnCount() ) ); + composerLegendElem.setAttribute( QStringLiteral( "splitLayer" ), QString::number( mSettings.splitLayer() ) ); + composerLegendElem.setAttribute( QStringLiteral( "equalColumnWidth" ), QString::number( mSettings.equalColumnWidth() ) ); - composerLegendElem.setAttribute( "boxSpace", QString::number( mSettings.boxSpace() ) ); - composerLegendElem.setAttribute( "columnSpace", QString::number( mSettings.columnSpace() ) ); + composerLegendElem.setAttribute( QStringLiteral( "boxSpace" ), QString::number( mSettings.boxSpace() ) ); + composerLegendElem.setAttribute( QStringLiteral( "columnSpace" ), QString::number( mSettings.columnSpace() ) ); - composerLegendElem.setAttribute( "symbolWidth", QString::number( mSettings.symbolSize().width() ) ); - composerLegendElem.setAttribute( "symbolHeight", QString::number( mSettings.symbolSize().height() ) ); + composerLegendElem.setAttribute( QStringLiteral( "symbolWidth" ), QString::number( mSettings.symbolSize().width() ) ); + composerLegendElem.setAttribute( QStringLiteral( "symbolHeight" ), QString::number( mSettings.symbolSize().height() ) ); - composerLegendElem.setAttribute( "rasterBorder", mSettings.drawRasterBorder() ); - composerLegendElem.setAttribute( "rasterBorderColor", QgsSymbolLayerUtils::encodeColor( mSettings.rasterBorderColor() ) ); - composerLegendElem.setAttribute( "rasterBorderWidth", QString::number( mSettings.rasterBorderWidth() ) ); + composerLegendElem.setAttribute( QStringLiteral( "rasterBorder" ), mSettings.drawRasterBorder() ); + composerLegendElem.setAttribute( QStringLiteral( "rasterBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSettings.rasterBorderColor() ) ); + composerLegendElem.setAttribute( QStringLiteral( "rasterBorderWidth" ), QString::number( mSettings.rasterBorderWidth() ) ); - composerLegendElem.setAttribute( "wmsLegendWidth", QString::number( mSettings.wmsLegendSize().width() ) ); - composerLegendElem.setAttribute( "wmsLegendHeight", QString::number( mSettings.wmsLegendSize().height() ) ); - composerLegendElem.setAttribute( "wrapChar", mSettings.wrapChar() ); - composerLegendElem.setAttribute( "fontColor", mSettings.fontColor().name() ); + composerLegendElem.setAttribute( QStringLiteral( "wmsLegendWidth" ), QString::number( mSettings.wmsLegendSize().width() ) ); + composerLegendElem.setAttribute( QStringLiteral( "wmsLegendHeight" ), QString::number( mSettings.wmsLegendSize().height() ) ); + composerLegendElem.setAttribute( QStringLiteral( "wrapChar" ), mSettings.wrapChar() ); + composerLegendElem.setAttribute( QStringLiteral( "fontColor" ), mSettings.fontColor().name() ); - composerLegendElem.setAttribute( "resizeToContents", mSizeToContents ); + composerLegendElem.setAttribute( QStringLiteral( "resizeToContents" ), mSizeToContents ); if ( mComposerMap ) { - composerLegendElem.setAttribute( "map", mComposerMap->id() ); + composerLegendElem.setAttribute( QStringLiteral( "map" ), mComposerMap->id() ); } - QDomElement composerLegendStyles = doc.createElement( "styles" ); + QDomElement composerLegendStyles = doc.createElement( QStringLiteral( "styles" ) ); composerLegendElem.appendChild( composerLegendStyles ); - style( QgsComposerLegendStyle::Title ).writeXml( "title", composerLegendStyles, doc ); - style( QgsComposerLegendStyle::Group ).writeXml( "group", composerLegendStyles, doc ); - style( QgsComposerLegendStyle::Subgroup ).writeXml( "subgroup", composerLegendStyles, doc ); - style( QgsComposerLegendStyle::Symbol ).writeXml( "symbol", composerLegendStyles, doc ); - style( QgsComposerLegendStyle::SymbolLabel ).writeXml( "symbolLabel", composerLegendStyles, doc ); + style( QgsComposerLegendStyle::Title ).writeXml( QStringLiteral( "title" ), composerLegendStyles, doc ); + style( QgsComposerLegendStyle::Group ).writeXml( QStringLiteral( "group" ), composerLegendStyles, doc ); + style( QgsComposerLegendStyle::Subgroup ).writeXml( QStringLiteral( "subgroup" ), composerLegendStyles, doc ); + style( QgsComposerLegendStyle::Symbol ).writeXml( QStringLiteral( "symbol" ), composerLegendStyles, doc ); + style( QgsComposerLegendStyle::SymbolLabel ).writeXml( QStringLiteral( "symbolLabel" ), composerLegendStyles, doc ); if ( mCustomLayerTree ) { @@ -406,7 +406,7 @@ bool QgsComposerLegend::writeXml( QDomElement& elem, QDomDocument & doc ) const if ( mLegendFilterByMap ) { - composerLegendElem.setAttribute( "legendFilterByMap", "1" ); + composerLegendElem.setAttribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "1" ) ); } return _writeXml( composerLegendElem, doc ); @@ -419,31 +419,31 @@ static void _readOldLegendGroup( QDomElement& elem, QgsLayerTreeGroup* parentGro while ( !itemElem.isNull() ) { - if ( itemElem.tagName() == "LayerItem" ) + if ( itemElem.tagName() == QLatin1String( "LayerItem" ) ) { - QString layerId = itemElem.attribute( "layerId" ); + QString layerId = itemElem.attribute( QStringLiteral( "layerId" ) ); if ( QgsMapLayer* layer = QgsMapLayerRegistry::instance()->mapLayer( layerId ) ) { QgsLayerTreeLayer* nodeLayer = parentGroup->addLayer( layer ); - QString userText = itemElem.attribute( "userText" ); + QString userText = itemElem.attribute( QStringLiteral( "userText" ) ); if ( !userText.isEmpty() ) - nodeLayer->setCustomProperty( "legend/title-label", userText ); - QString style = itemElem.attribute( "style" ); + nodeLayer->setCustomProperty( QStringLiteral( "legend/title-label" ), userText ); + QString style = itemElem.attribute( QStringLiteral( "style" ) ); if ( !style.isEmpty() ) - nodeLayer->setCustomProperty( "legend/title-style", style ); - QString showFeatureCount = itemElem.attribute( "showFeatureCount" ); + nodeLayer->setCustomProperty( QStringLiteral( "legend/title-style" ), style ); + QString showFeatureCount = itemElem.attribute( QStringLiteral( "showFeatureCount" ) ); if ( showFeatureCount.toInt() ) - nodeLayer->setCustomProperty( "showFeatureCount", 1 ); + nodeLayer->setCustomProperty( QStringLiteral( "showFeatureCount" ), 1 ); // support for individual legend items (user text, order) not implemented yet } } - else if ( itemElem.tagName() == "GroupItem" ) + else if ( itemElem.tagName() == QLatin1String( "GroupItem" ) ) { - QgsLayerTreeGroup* nodeGroup = parentGroup->addGroup( itemElem.attribute( "userText" ) ); - QString style = itemElem.attribute( "style" ); + QgsLayerTreeGroup* nodeGroup = parentGroup->addGroup( itemElem.attribute( QStringLiteral( "userText" ) ) ); + QString style = itemElem.attribute( QStringLiteral( "style" ) ); if ( !style.isEmpty() ) - nodeGroup->setCustomProperty( "legend/title-style", style ); + nodeGroup->setCustomProperty( QStringLiteral( "legend/title-style" ), style ); _readOldLegendGroup( itemElem, nodeGroup ); } @@ -460,18 +460,18 @@ bool QgsComposerLegend::readXml( const QDomElement& itemElem, const QDomDocument } //read general properties - mSettings.setTitle( itemElem.attribute( "title" ) ); - if ( !itemElem.attribute( "titleAlignment" ).isEmpty() ) + mSettings.setTitle( itemElem.attribute( QStringLiteral( "title" ) ) ); + if ( !itemElem.attribute( QStringLiteral( "titleAlignment" ) ).isEmpty() ) { - mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( "titleAlignment" ).toInt() ) ); + mSettings.setTitleAlignment( static_cast< Qt::AlignmentFlag >( itemElem.attribute( QStringLiteral( "titleAlignment" ) ).toInt() ) ); } - int colCount = itemElem.attribute( "columnCount", "1" ).toInt(); + int colCount = itemElem.attribute( QStringLiteral( "columnCount" ), QStringLiteral( "1" ) ).toInt(); if ( colCount < 1 ) colCount = 1; mSettings.setColumnCount( colCount ); - mSettings.setSplitLayer( itemElem.attribute( "splitLayer", "0" ).toInt() == 1 ); - mSettings.setEqualColumnWidth( itemElem.attribute( "equalColumnWidth", "0" ).toInt() == 1 ); + mSettings.setSplitLayer( itemElem.attribute( QStringLiteral( "splitLayer" ), QStringLiteral( "0" ) ).toInt() == 1 ); + mSettings.setEqualColumnWidth( itemElem.attribute( QStringLiteral( "equalColumnWidth" ), QStringLiteral( "0" ) ).toInt() == 1 ); - QDomNodeList stylesNodeList = itemElem.elementsByTagName( "styles" ); + QDomNodeList stylesNodeList = itemElem.elementsByTagName( QStringLiteral( "styles" ) ); if ( !stylesNodeList.isEmpty() ) { QDomNode stylesNode = stylesNodeList.at( 0 ); @@ -480,13 +480,13 @@ bool QgsComposerLegend::readXml( const QDomElement& itemElem, const QDomDocument QDomElement styleElem = stylesNode.childNodes().at( i ).toElement(); QgsComposerLegendStyle style; style.readXml( styleElem, doc ); - QString name = styleElem.attribute( "name" ); + QString name = styleElem.attribute( QStringLiteral( "name" ) ); QgsComposerLegendStyle::Style s; - if ( name == "title" ) s = QgsComposerLegendStyle::Title; - else if ( name == "group" ) s = QgsComposerLegendStyle::Group; - else if ( name == "subgroup" ) s = QgsComposerLegendStyle::Subgroup; - else if ( name == "symbol" ) s = QgsComposerLegendStyle::Symbol; - else if ( name == "symbolLabel" ) s = QgsComposerLegendStyle::SymbolLabel; + if ( name == QLatin1String( "title" ) ) s = QgsComposerLegendStyle::Title; + else if ( name == QLatin1String( "group" ) ) s = QgsComposerLegendStyle::Group; + else if ( name == QLatin1String( "subgroup" ) ) s = QgsComposerLegendStyle::Subgroup; + else if ( name == QLatin1String( "symbol" ) ) s = QgsComposerLegendStyle::Symbol; + else if ( name == QLatin1String( "symbolLabel" ) ) s = QgsComposerLegendStyle::SymbolLabel; else continue; setStyle( s, style ); } @@ -494,32 +494,32 @@ bool QgsComposerLegend::readXml( const QDomElement& itemElem, const QDomDocument //font color QColor fontClr; - fontClr.setNamedColor( itemElem.attribute( "fontColor", "#000000" ) ); + fontClr.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) ); mSettings.setFontColor( fontClr ); //spaces - mSettings.setBoxSpace( itemElem.attribute( "boxSpace", "2.0" ).toDouble() ); - mSettings.setColumnSpace( itemElem.attribute( "columnSpace", "2.0" ).toDouble() ); + mSettings.setBoxSpace( itemElem.attribute( QStringLiteral( "boxSpace" ), QStringLiteral( "2.0" ) ).toDouble() ); + mSettings.setColumnSpace( itemElem.attribute( QStringLiteral( "columnSpace" ), QStringLiteral( "2.0" ) ).toDouble() ); - mSettings.setSymbolSize( QSizeF( itemElem.attribute( "symbolWidth", "7.0" ).toDouble(), itemElem.attribute( "symbolHeight", "14.0" ).toDouble() ) ); - mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( "wmsLegendWidth", "50" ).toDouble(), itemElem.attribute( "wmsLegendHeight", "25" ).toDouble() ) ); + mSettings.setSymbolSize( QSizeF( itemElem.attribute( QStringLiteral( "symbolWidth" ), QStringLiteral( "7.0" ) ).toDouble(), itemElem.attribute( QStringLiteral( "symbolHeight" ), QStringLiteral( "14.0" ) ).toDouble() ) ); + mSettings.setWmsLegendSize( QSizeF( itemElem.attribute( QStringLiteral( "wmsLegendWidth" ), QStringLiteral( "50" ) ).toDouble(), itemElem.attribute( QStringLiteral( "wmsLegendHeight" ), QStringLiteral( "25" ) ).toDouble() ) ); - mSettings.setDrawRasterBorder( itemElem.attribute( "rasterBorder", "1" ) != "0" ); - mSettings.setRasterBorderColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "rasterBorderColor", "0,0,0" ) ) ); - mSettings.setRasterBorderWidth( itemElem.attribute( "rasterBorderWidth", "0" ).toDouble() ); + mSettings.setDrawRasterBorder( itemElem.attribute( QStringLiteral( "rasterBorder" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); + mSettings.setRasterBorderColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "rasterBorderColor" ), QStringLiteral( "0,0,0" ) ) ) ); + mSettings.setRasterBorderWidth( itemElem.attribute( QStringLiteral( "rasterBorderWidth" ), QStringLiteral( "0" ) ).toDouble() ); - mSettings.setWrapChar( itemElem.attribute( "wrapChar" ) ); + mSettings.setWrapChar( itemElem.attribute( QStringLiteral( "wrapChar" ) ) ); - mSizeToContents = itemElem.attribute( "resizeToContents", "1" ) != "0"; + mSizeToContents = itemElem.attribute( QStringLiteral( "resizeToContents" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ); //composer map - mLegendFilterByMap = itemElem.attribute( "legendFilterByMap", "0" ).toInt(); - if ( !itemElem.attribute( "map" ).isEmpty() ) + mLegendFilterByMap = itemElem.attribute( QStringLiteral( "legendFilterByMap" ), QStringLiteral( "0" ) ).toInt(); + if ( !itemElem.attribute( QStringLiteral( "map" ) ).isEmpty() ) { - setComposerMap( mComposition->getComposerMapById( itemElem.attribute( "map" ).toInt() ) ); + setComposerMap( mComposition->getComposerMapById( itemElem.attribute( QStringLiteral( "map" ) ).toInt() ) ); } - QDomElement oldLegendModelElem = itemElem.firstChildElement( "Model" ); + QDomElement oldLegendModelElem = itemElem.firstChildElement( QStringLiteral( "Model" ) ); if ( !oldLegendModelElem.isNull() ) { // QGIS <= 2.4 @@ -530,12 +530,12 @@ bool QgsComposerLegend::readXml( const QDomElement& itemElem, const QDomDocument else { // QGIS >= 2.6 - QDomElement layerTreeElem = itemElem.firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = itemElem.firstChildElement( QStringLiteral( "layer-tree-group" ) ); setCustomLayerTree( QgsLayerTreeGroup::readXml( layerTreeElem ) ); } //restore general composer item properties - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); @@ -544,43 +544,43 @@ bool QgsComposerLegend::readXml( const QDomElement& itemElem, const QDomDocument // < 2.0 projects backward compatibility >>>>> //title font - QString titleFontString = itemElem.attribute( "titleFont" ); + QString titleFontString = itemElem.attribute( QStringLiteral( "titleFont" ) ); if ( !titleFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::Title ).rfont().fromString( titleFontString ); } //group font - QString groupFontString = itemElem.attribute( "groupFont" ); + QString groupFontString = itemElem.attribute( QStringLiteral( "groupFont" ) ); if ( !groupFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::Group ).rfont().fromString( groupFontString ); } //layer font - QString layerFontString = itemElem.attribute( "layerFont" ); + QString layerFontString = itemElem.attribute( QStringLiteral( "layerFont" ) ); if ( !layerFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::Subgroup ).rfont().fromString( layerFontString ); } //item font - QString itemFontString = itemElem.attribute( "itemFont" ); + QString itemFontString = itemElem.attribute( QStringLiteral( "itemFont" ) ); if ( !itemFontString.isEmpty() ) { rstyle( QgsComposerLegendStyle::SymbolLabel ).rfont().fromString( itemFontString ); } - if ( !itemElem.attribute( "groupSpace" ).isEmpty() ) + if ( !itemElem.attribute( QStringLiteral( "groupSpace" ) ).isEmpty() ) { - rstyle( QgsComposerLegendStyle::Group ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "groupSpace", "3.0" ).toDouble() ); + rstyle( QgsComposerLegendStyle::Group ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( QStringLiteral( "groupSpace" ), QStringLiteral( "3.0" ) ).toDouble() ); } - if ( !itemElem.attribute( "layerSpace" ).isEmpty() ) + if ( !itemElem.attribute( QStringLiteral( "layerSpace" ) ).isEmpty() ) { - rstyle( QgsComposerLegendStyle::Subgroup ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "layerSpace", "3.0" ).toDouble() ); + rstyle( QgsComposerLegendStyle::Subgroup ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( QStringLiteral( "layerSpace" ), QStringLiteral( "3.0" ) ).toDouble() ); } - if ( !itemElem.attribute( "symbolSpace" ).isEmpty() ) + if ( !itemElem.attribute( QStringLiteral( "symbolSpace" ) ).isEmpty() ) { - rstyle( QgsComposerLegendStyle::Symbol ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "symbolSpace", "2.0" ).toDouble() ); - rstyle( QgsComposerLegendStyle::SymbolLabel ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( "symbolSpace", "2.0" ).toDouble() ); + rstyle( QgsComposerLegendStyle::Symbol ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( QStringLiteral( "symbolSpace" ), QStringLiteral( "2.0" ) ).toDouble() ); + rstyle( QgsComposerLegendStyle::SymbolLabel ).setMargin( QgsComposerLegendStyle::Top, itemElem.attribute( QStringLiteral( "symbolSpace" ), QStringLiteral( "2.0" ) ).toDouble() ); } // <<<<<<< < 2.0 projects backward compatibility @@ -751,15 +751,15 @@ QVariant QgsLegendModelV2::data( const QModelIndex& index, int role ) const // handle custom layer node labels if ( QgsLayerTreeNode* node = index2node( index ) ) { - if ( QgsLayerTree::isLayer( node ) && ( role == Qt::DisplayRole || role == Qt::EditRole ) && !node->customProperty( "legend/title-label" ).isNull() ) + if ( QgsLayerTree::isLayer( node ) && ( role == Qt::DisplayRole || role == Qt::EditRole ) && !node->customProperty( QStringLiteral( "legend/title-label" ) ).isNull() ) { QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node ); - QString name = node->customProperty( "legend/title-label" ).toString(); - if ( nodeLayer->customProperty( "showFeatureCount", 0 ).toInt() && role == Qt::DisplayRole ) + QString name = node->customProperty( QStringLiteral( "legend/title-label" ) ).toString(); + if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() && role == Qt::DisplayRole ) { QgsVectorLayer* vlayer = qobject_cast( nodeLayer->layer() ); if ( vlayer && vlayer->featureCount() >= 0 ) - name += QString( " [%1]" ).arg( vlayer->featureCount() ); + name += QStringLiteral( " [%1]" ).arg( vlayer->featureCount() ); } return name; } diff --git a/src/core/composer/qgscomposerlegenditem.cpp b/src/core/composer/qgscomposerlegenditem.cpp index 2408d87bc0bf..82c4cb6f9de1 100644 --- a/src/core/composer/qgscomposerlegenditem.cpp +++ b/src/core/composer/qgscomposerlegenditem.cpp @@ -95,16 +95,16 @@ QStandardItem* QgsComposerSymbolItem::clone() const void QgsComposerSymbolItem::writeXml( QDomElement& elem, QDomDocument& doc ) const { - QDomElement vectorClassElem = doc.createElement( "VectorClassificationItemNg" ); + QDomElement vectorClassElem = doc.createElement( QStringLiteral( "VectorClassificationItemNg" ) ); if ( mSymbol ) { QgsSymbolMap saveSymbolMap; - saveSymbolMap.insert( "classificationSymbol", mSymbol ); - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( saveSymbolMap, "symbols", doc ); + saveSymbolMap.insert( QStringLiteral( "classificationSymbol" ), mSymbol ); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( saveSymbolMap, QStringLiteral( "symbols" ), doc ); vectorClassElem.appendChild( symbolsElem ); } - vectorClassElem.setAttribute( "text", text() ); - vectorClassElem.setAttribute( "userText", userText() ); + vectorClassElem.setAttribute( QStringLiteral( "text" ), text() ); + vectorClassElem.setAttribute( QStringLiteral( "userText" ), userText() ); elem.appendChild( vectorClassElem ); } @@ -115,9 +115,9 @@ void QgsComposerSymbolItem::readXml( const QDomElement& itemElem, bool xServerAv return; } - setText( itemElem.attribute( "text", "" ) ); - setUserText( itemElem.attribute( "userText", "" ) ); - QDomElement symbolsElem = itemElem.firstChildElement( "symbols" ); + setText( itemElem.attribute( QStringLiteral( "text" ), QLatin1String( "" ) ) ); + setUserText( itemElem.attribute( QStringLiteral( "userText" ), QLatin1String( "" ) ) ); + QDomElement symbolsElem = itemElem.firstChildElement( QStringLiteral( "symbols" ) ); if ( !symbolsElem.isNull() ) { QgsSymbolMap loadSymbolMap = QgsSymbolLayerUtils::loadSymbols( symbolsElem ); @@ -172,11 +172,11 @@ QStandardItem* QgsComposerRasterSymbolItem::clone() const void QgsComposerRasterSymbolItem::writeXml( QDomElement& elem, QDomDocument& doc ) const { - QDomElement rasterClassElem = doc.createElement( "RasterClassificationItem" ); - rasterClassElem.setAttribute( "layerId", mLayerID ); - rasterClassElem.setAttribute( "text", text() ); - rasterClassElem.setAttribute( "userText", userText() ); - rasterClassElem.setAttribute( "color", mColor.name() ); + QDomElement rasterClassElem = doc.createElement( QStringLiteral( "RasterClassificationItem" ) ); + rasterClassElem.setAttribute( QStringLiteral( "layerId" ), mLayerID ); + rasterClassElem.setAttribute( QStringLiteral( "text" ), text() ); + rasterClassElem.setAttribute( QStringLiteral( "userText" ), userText() ); + rasterClassElem.setAttribute( QStringLiteral( "color" ), mColor.name() ); elem.appendChild( rasterClassElem ); } @@ -186,10 +186,10 @@ void QgsComposerRasterSymbolItem::readXml( const QDomElement& itemElem, bool xSe { return; } - setText( itemElem.attribute( "text", "" ) ); - setUserText( itemElem.attribute( "userText", "" ) ); - setLayerId( itemElem.attribute( "layerId", "" ) ); - setColor( QColor( itemElem.attribute( "color" ) ) ); + setText( itemElem.attribute( QStringLiteral( "text" ), QLatin1String( "" ) ) ); + setUserText( itemElem.attribute( QStringLiteral( "userText" ), QLatin1String( "" ) ) ); + setLayerId( itemElem.attribute( QStringLiteral( "layerId" ), QLatin1String( "" ) ) ); + setColor( QColor( itemElem.attribute( QStringLiteral( "color" ) ) ) ); if ( xServerAvailable ) { @@ -225,12 +225,12 @@ QStandardItem* QgsComposerLayerItem::clone() const void QgsComposerLayerItem::writeXml( QDomElement& elem, QDomDocument& doc ) const { - QDomElement layerItemElem = doc.createElement( "LayerItem" ); - layerItemElem.setAttribute( "layerId", mLayerID ); - layerItemElem.setAttribute( "text", text() ); - layerItemElem.setAttribute( "userText", userText() ); - layerItemElem.setAttribute( "showFeatureCount", showFeatureCount() ); - layerItemElem.setAttribute( "style", QgsComposerLegendStyle::styleName( mStyle ) ); + QDomElement layerItemElem = doc.createElement( QStringLiteral( "LayerItem" ) ); + layerItemElem.setAttribute( QStringLiteral( "layerId" ), mLayerID ); + layerItemElem.setAttribute( QStringLiteral( "text" ), text() ); + layerItemElem.setAttribute( QStringLiteral( "userText" ), userText() ); + layerItemElem.setAttribute( QStringLiteral( "showFeatureCount" ), showFeatureCount() ); + layerItemElem.setAttribute( QStringLiteral( "style" ), QgsComposerLegendStyle::styleName( mStyle ) ); writeXmlChildren( layerItemElem, doc ); elem.appendChild( layerItemElem ); } @@ -241,11 +241,11 @@ void QgsComposerLayerItem::readXml( const QDomElement& itemElem, bool xServerAva { return; } - setText( itemElem.attribute( "text", "" ) ); - setUserText( itemElem.attribute( "userText", "" ) ); - setLayerId( itemElem.attribute( "layerId", "" ) ); - setShowFeatureCount( itemElem.attribute( "showFeatureCount", "" ) == "1" ? true : false ); - setStyle( QgsComposerLegendStyle::styleFromName( itemElem.attribute( "style", "subgroup" ) ) ); + setText( itemElem.attribute( QStringLiteral( "text" ), QLatin1String( "" ) ) ); + setUserText( itemElem.attribute( QStringLiteral( "userText" ), QLatin1String( "" ) ) ); + setLayerId( itemElem.attribute( QStringLiteral( "layerId" ), QLatin1String( "" ) ) ); + setShowFeatureCount( itemElem.attribute( QStringLiteral( "showFeatureCount" ), QLatin1String( "" ) ) == QLatin1String( "1" ) ? true : false ); + setStyle( QgsComposerLegendStyle::styleFromName( itemElem.attribute( QStringLiteral( "style" ), QStringLiteral( "subgroup" ) ) ) ); //now call readXml for all the child items QDomNodeList childList = itemElem.childNodes(); @@ -264,15 +264,15 @@ void QgsComposerLayerItem::readXml( const QDomElement& itemElem, bool xServerAva currentElem = currentNode.toElement(); QString elemTag = currentElem.tagName(); - if ( elemTag == "VectorClassificationItem" ) + if ( elemTag == QLatin1String( "VectorClassificationItem" ) ) { continue; // legacy - unsupported } - else if ( elemTag == "VectorClassificationItemNg" ) + else if ( elemTag == QLatin1String( "VectorClassificationItemNg" ) ) { currentChildItem = new QgsComposerSymbolItem(); } - else if ( elemTag == "RasterClassificationItem" ) + else if ( elemTag == QLatin1String( "RasterClassificationItem" ) ) { currentChildItem = new QgsComposerRasterSymbolItem(); } @@ -331,11 +331,11 @@ QStandardItem* QgsComposerGroupItem::clone() const void QgsComposerGroupItem::writeXml( QDomElement& elem, QDomDocument& doc ) const { - QDomElement layerGroupElem = doc.createElement( "GroupItem" ); + QDomElement layerGroupElem = doc.createElement( QStringLiteral( "GroupItem" ) ); // text is always user text, but for forward compatibility for now write both - layerGroupElem.setAttribute( "text", text() ); - layerGroupElem.setAttribute( "userText", userText() ); - layerGroupElem.setAttribute( "style", QgsComposerLegendStyle::styleName( mStyle ) ); + layerGroupElem.setAttribute( QStringLiteral( "text" ), text() ); + layerGroupElem.setAttribute( QStringLiteral( "userText" ), userText() ); + layerGroupElem.setAttribute( QStringLiteral( "style" ), QgsComposerLegendStyle::styleName( mStyle ) ); writeXmlChildren( layerGroupElem, doc ); elem.appendChild( layerGroupElem ); } @@ -347,15 +347,15 @@ void QgsComposerGroupItem::readXml( const QDomElement& itemElem, bool xServerAva return; } // text is always user text but for backward compatibility we read also text - QString userText = itemElem.attribute( "userText", "" ); + QString userText = itemElem.attribute( QStringLiteral( "userText" ), QLatin1String( "" ) ); if ( userText.isEmpty() ) { - userText = itemElem.attribute( "text", "" ); + userText = itemElem.attribute( QStringLiteral( "text" ), QLatin1String( "" ) ); } setText( userText ); setUserText( userText ); - setStyle( QgsComposerLegendStyle::styleFromName( itemElem.attribute( "style", "group" ) ) ); + setStyle( QgsComposerLegendStyle::styleFromName( itemElem.attribute( QStringLiteral( "style" ), QStringLiteral( "group" ) ) ) ); //now call readXml for all the child items QDomNodeList childList = itemElem.childNodes(); @@ -375,11 +375,11 @@ void QgsComposerGroupItem::readXml( const QDomElement& itemElem, bool xServerAva currentElem = currentNode.toElement(); QString elemTag = currentElem.tagName(); - if ( elemTag == "GroupItem" ) + if ( elemTag == QLatin1String( "GroupItem" ) ) { currentChildItem = new QgsComposerGroupItem(); } - else if ( elemTag == "LayerItem" ) + else if ( elemTag == QLatin1String( "LayerItem" ) ) { currentChildItem = new QgsComposerLayerItem(); } diff --git a/src/core/composer/qgscomposerlegenditem.h b/src/core/composer/qgscomposerlegenditem.h index 3a0539e6ff35..9a8571c7183b 100644 --- a/src/core/composer/qgscomposerlegenditem.h +++ b/src/core/composer/qgscomposerlegenditem.h @@ -142,13 +142,25 @@ class CORE_EXPORT QgsComposerLayerItem : public QgsComposerLegendItem ItemType itemType() const override { return LayerItem; } + /** + * Sets the associated layer ID. + * @see layerId() + */ void setLayerId( const QString& id ) { mLayerID = id; } + + /** + * Returns the ID of the associated layer. + * @see setLayerId() + */ QString layerId() const { return mLayerID; } void setShowFeatureCount( bool show ) { mShowFeatureCount = show; } bool showFeatureCount() const { return mShowFeatureCount; } - void setDefaultStyle( double scaleDenominator = -1, const QString& rule = "" ); + /** + * Sets the legend layer item to the appropriate default style for the specified legend rule. + */ + void setDefaultStyle( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ); private: QString mLayerID; diff --git a/src/core/composer/qgscomposerlegendstyle.cpp b/src/core/composer/qgscomposerlegendstyle.cpp index 2356aaf410fe..39120bac4ecc 100644 --- a/src/core/composer/qgscomposerlegendstyle.cpp +++ b/src/core/composer/qgscomposerlegendstyle.cpp @@ -30,7 +30,7 @@ QgsComposerLegendStyle::QgsComposerLegendStyle() { //get default composer font from settings QSettings settings; - QString defaultFontString = settings.value( "/Composer/defaultFont" ).toString(); + QString defaultFontString = settings.value( QStringLiteral( "/Composer/defaultFont" ) ).toString(); if ( !defaultFontString.isEmpty() ) { mFont.setFamily( defaultFontString ); @@ -49,16 +49,16 @@ void QgsComposerLegendStyle::writeXml( const QString& name, QDomElement& elem, Q { if ( elem.isNull() ) return; - QDomElement styleElem = doc.createElement( "style" ); + QDomElement styleElem = doc.createElement( QStringLiteral( "style" ) ); - styleElem.setAttribute( "name", name ); + styleElem.setAttribute( QStringLiteral( "name" ), name ); - if ( !qgsDoubleNear( mMarginMap[Top], 0.0 ) ) styleElem.setAttribute( "marginTop", QString::number( mMarginMap[Top] ) ); - if ( !qgsDoubleNear( mMarginMap[Bottom], 0.0 ) ) styleElem.setAttribute( "marginBottom", QString::number( mMarginMap[Bottom] ) ); - if ( !qgsDoubleNear( mMarginMap[Left], 0.0 ) ) styleElem.setAttribute( "marginLeft", QString::number( mMarginMap[Left] ) ); - if ( !qgsDoubleNear( mMarginMap[Right], 0.0 ) ) styleElem.setAttribute( "marginRight", QString::number( mMarginMap[Right] ) ); + if ( !qgsDoubleNear( mMarginMap[Top], 0.0 ) ) styleElem.setAttribute( QStringLiteral( "marginTop" ), QString::number( mMarginMap[Top] ) ); + if ( !qgsDoubleNear( mMarginMap[Bottom], 0.0 ) ) styleElem.setAttribute( QStringLiteral( "marginBottom" ), QString::number( mMarginMap[Bottom] ) ); + if ( !qgsDoubleNear( mMarginMap[Left], 0.0 ) ) styleElem.setAttribute( QStringLiteral( "marginLeft" ), QString::number( mMarginMap[Left] ) ); + if ( !qgsDoubleNear( mMarginMap[Right], 0.0 ) ) styleElem.setAttribute( QStringLiteral( "marginRight" ), QString::number( mMarginMap[Right] ) ); - styleElem.appendChild( QgsFontUtils::toXmlElement( mFont, doc, "styleFont" ) ); + styleElem.appendChild( QgsFontUtils::toXmlElement( mFont, doc, QStringLiteral( "styleFont" ) ) ); elem.appendChild( styleElem ); } @@ -68,15 +68,15 @@ void QgsComposerLegendStyle::readXml( const QDomElement& elem, const QDomDocumen Q_UNUSED( doc ); if ( elem.isNull() ) return; - if ( !QgsFontUtils::setFromXmlChildNode( mFont, elem, "styleFont" ) ) + if ( !QgsFontUtils::setFromXmlChildNode( mFont, elem, QStringLiteral( "styleFont" ) ) ) { - mFont.fromString( elem.attribute( "font" ) ); + mFont.fromString( elem.attribute( QStringLiteral( "font" ) ) ); } - mMarginMap[Top] = elem.attribute( "marginTop", "0" ).toDouble(); - mMarginMap[Bottom] = elem.attribute( "marginBottom", "0" ).toDouble(); - mMarginMap[Left] = elem.attribute( "marginLeft", "0" ).toDouble(); - mMarginMap[Right] = elem.attribute( "marginRight", "0" ).toDouble(); + mMarginMap[Top] = elem.attribute( QStringLiteral( "marginTop" ), QStringLiteral( "0" ) ).toDouble(); + mMarginMap[Bottom] = elem.attribute( QStringLiteral( "marginBottom" ), QStringLiteral( "0" ) ).toDouble(); + mMarginMap[Left] = elem.attribute( QStringLiteral( "marginLeft" ), QStringLiteral( "0" ) ).toDouble(); + mMarginMap[Right] = elem.attribute( QStringLiteral( "marginRight" ), QStringLiteral( "0" ) ).toDouble(); } QString QgsComposerLegendStyle::styleName( Style s ) @@ -84,31 +84,31 @@ QString QgsComposerLegendStyle::styleName( Style s ) switch ( s ) { case Undefined: - return ""; + return QLatin1String( "" ); case Hidden: - return "hidden"; + return QStringLiteral( "hidden" ); case Title: - return "title"; + return QStringLiteral( "title" ); case Group: - return "group"; + return QStringLiteral( "group" ); case Subgroup: - return "subgroup"; + return QStringLiteral( "subgroup" ); case Symbol: - return "symbol"; + return QStringLiteral( "symbol" ); case SymbolLabel: - return "symbolLabel"; + return QStringLiteral( "symbolLabel" ); } - return ""; + return QLatin1String( "" ); } QgsComposerLegendStyle::Style QgsComposerLegendStyle::styleFromName( const QString& styleName ) { - if ( styleName == "hidden" ) return Hidden; - else if ( styleName == "title" ) return Title; - else if ( styleName == "group" ) return Group; - else if ( styleName == "subgroup" ) return Subgroup; - else if ( styleName == "symbol" ) return Symbol; - else if ( styleName == "symbolLabel" ) return SymbolLabel; + if ( styleName == QLatin1String( "hidden" ) ) return Hidden; + else if ( styleName == QLatin1String( "title" ) ) return Title; + else if ( styleName == QLatin1String( "group" ) ) return Group; + else if ( styleName == QLatin1String( "subgroup" ) ) return Subgroup; + else if ( styleName == QLatin1String( "symbol" ) ) return Symbol; + else if ( styleName == QLatin1String( "symbolLabel" ) ) return SymbolLabel; return Undefined; } @@ -131,5 +131,5 @@ QString QgsComposerLegendStyle::styleLabel( Style s ) case SymbolLabel: return QObject::tr( "Symbol label" ); } - return ""; + return QLatin1String( "" ); } diff --git a/src/core/composer/qgscomposermap.cpp b/src/core/composer/qgscomposermap.cpp index 2e08a373cc20..4f2bcc46dcb9 100644 --- a/src/core/composer/qgscomposermap.cpp +++ b/src/core/composer/qgscomposermap.cpp @@ -78,9 +78,9 @@ QgsComposerMap::QgsComposerMap( QgsComposition *composition, int x, int y, int w mYOffset = 0.0; //get the color for map canvas background and set map background color accordingly - int bgRedInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorRedPart", 255 ); - int bgGreenInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorGreenPart", 255 ); - int bgBlueInt = QgsProject::instance()->readNumEntry( "Gui", "/CanvasColorBluePart", 255 ); + int bgRedInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorRedPart" ), 255 ); + int bgGreenInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorGreenPart" ), 255 ); + int bgBlueInt = QgsProject::instance()->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/CanvasColorBluePart" ), 255 ); setBackgroundColor( QColor( bgRedInt, bgGreenInt, bgBlueInt ) ); //calculate mExtent based on width/height ratio and map canvas extent @@ -127,15 +127,15 @@ void QgsComposerMap::init() connectUpdateSlot(); // data defined strings - mDataDefinedNames.insert( QgsComposerObject::MapRotation, QString( "dataDefinedMapRotation" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapScale, QString( "dataDefinedMapScale" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapXMin, QString( "dataDefinedMapXMin" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapYMin, QString( "dataDefinedMapYMin" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapXMax, QString( "dataDefinedMapXMax" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapYMax, QString( "dataDefinedMapYMax" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapAtlasMargin, QString( "dataDefinedMapAtlasMargin" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapLayers, QString( "dataDefinedMapLayers" ) ); - mDataDefinedNames.insert( QgsComposerObject::MapStylePreset, QString( "dataDefinedMapStylePreset" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapRotation, QStringLiteral( "dataDefinedMapRotation" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapScale, QStringLiteral( "dataDefinedMapScale" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapXMin, QStringLiteral( "dataDefinedMapXMin" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapYMin, QStringLiteral( "dataDefinedMapYMin" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapXMax, QStringLiteral( "dataDefinedMapXMax" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapYMax, QStringLiteral( "dataDefinedMapYMax" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapAtlasMargin, QStringLiteral( "dataDefinedMapAtlasMargin" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapLayers, QStringLiteral( "dataDefinedMapLayers" ) ); + mDataDefinedNames.insert( QgsComposerObject::MapStylePreset, QStringLiteral( "dataDefinedMapStylePreset" ) ); } void QgsComposerMap::updateToolTip() @@ -340,7 +340,7 @@ void QgsComposerMap::paint( QPainter* painter, const QStyleOptionGraphicsItem* i { // Fill with background color drawBackground( painter ); - QFont messageFont( "", 12 ); + QFont messageFont( QLatin1String( "" ), 12 ); painter->setFont( messageFont ); painter->setPen( QColor( 0, 0, 0, 125 ) ); painter->drawText( thisPaintRect, tr( "Map will be printed here" ) ); @@ -1135,7 +1135,7 @@ bool QgsComposerMap::containsWmsLayer() const const QgsRasterDataProvider* rasterProvider = nullptr; if (( rasterProvider = currentRasterLayer->dataProvider() ) ) { - if ( rasterProvider->name() == "wms" ) + if ( rasterProvider->name() == QLatin1String( "wms" ) ) { return true; } @@ -1224,62 +1224,62 @@ bool QgsComposerMap::writeXml( QDomElement& elem, QDomDocument & doc ) const return false; } - QDomElement composerMapElem = doc.createElement( "ComposerMap" ); - composerMapElem.setAttribute( "id", mId ); + QDomElement composerMapElem = doc.createElement( QStringLiteral( "ComposerMap" ) ); + composerMapElem.setAttribute( QStringLiteral( "id" ), mId ); //previewMode if ( mPreviewMode == Cache ) { - composerMapElem.setAttribute( "previewMode", "Cache" ); + composerMapElem.setAttribute( QStringLiteral( "previewMode" ), QStringLiteral( "Cache" ) ); } else if ( mPreviewMode == Render ) { - composerMapElem.setAttribute( "previewMode", "Render" ); + composerMapElem.setAttribute( QStringLiteral( "previewMode" ), QStringLiteral( "Render" ) ); } else //rectangle { - composerMapElem.setAttribute( "previewMode", "Rectangle" ); + composerMapElem.setAttribute( QStringLiteral( "previewMode" ), QStringLiteral( "Rectangle" ) ); } if ( mKeepLayerSet ) { - composerMapElem.setAttribute( "keepLayerSet", "true" ); + composerMapElem.setAttribute( QStringLiteral( "keepLayerSet" ), QStringLiteral( "true" ) ); } else { - composerMapElem.setAttribute( "keepLayerSet", "false" ); + composerMapElem.setAttribute( QStringLiteral( "keepLayerSet" ), QStringLiteral( "false" ) ); } if ( mDrawCanvasItems ) { - composerMapElem.setAttribute( "drawCanvasItems", "true" ); + composerMapElem.setAttribute( QStringLiteral( "drawCanvasItems" ), QStringLiteral( "true" ) ); } else { - composerMapElem.setAttribute( "drawCanvasItems", "false" ); + composerMapElem.setAttribute( QStringLiteral( "drawCanvasItems" ), QStringLiteral( "false" ) ); } //extent - QDomElement extentElem = doc.createElement( "Extent" ); - extentElem.setAttribute( "xmin", qgsDoubleToString( mExtent.xMinimum() ) ); - extentElem.setAttribute( "xmax", qgsDoubleToString( mExtent.xMaximum() ) ); - extentElem.setAttribute( "ymin", qgsDoubleToString( mExtent.yMinimum() ) ); - extentElem.setAttribute( "ymax", qgsDoubleToString( mExtent.yMaximum() ) ); + QDomElement extentElem = doc.createElement( QStringLiteral( "Extent" ) ); + extentElem.setAttribute( QStringLiteral( "xmin" ), qgsDoubleToString( mExtent.xMinimum() ) ); + extentElem.setAttribute( QStringLiteral( "xmax" ), qgsDoubleToString( mExtent.xMaximum() ) ); + extentElem.setAttribute( QStringLiteral( "ymin" ), qgsDoubleToString( mExtent.yMinimum() ) ); + extentElem.setAttribute( QStringLiteral( "ymax" ), qgsDoubleToString( mExtent.yMaximum() ) ); composerMapElem.appendChild( extentElem ); // follow map theme - composerMapElem.setAttribute( "followPreset", mFollowVisibilityPreset ? "true" : "false" ); - composerMapElem.setAttribute( "followPresetName", mFollowVisibilityPresetName ); + composerMapElem.setAttribute( QStringLiteral( "followPreset" ), mFollowVisibilityPreset ? "true" : "false" ); + composerMapElem.setAttribute( QStringLiteral( "followPresetName" ), mFollowVisibilityPresetName ); //map rotation - composerMapElem.setAttribute( "mapRotation", QString::number( mMapRotation ) ); + composerMapElem.setAttribute( QStringLiteral( "mapRotation" ), QString::number( mMapRotation ) ); //layer set - QDomElement layerSetElem = doc.createElement( "LayerSet" ); + QDomElement layerSetElem = doc.createElement( QStringLiteral( "LayerSet" ) ); QStringList::const_iterator layerIt = mLayerSet.constBegin(); for ( ; layerIt != mLayerSet.constEnd(); ++layerIt ) { - QDomElement layerElem = doc.createElement( "Layer" ); + QDomElement layerElem = doc.createElement( QStringLiteral( "Layer" ) ); QDomText layerIdText = doc.createTextNode( *layerIt ); layerElem.appendChild( layerIdText ); layerSetElem.appendChild( layerElem ); @@ -1289,12 +1289,12 @@ bool QgsComposerMap::writeXml( QDomElement& elem, QDomDocument & doc ) const // override styles if ( mKeepLayerStyles ) { - QDomElement stylesElem = doc.createElement( "LayerStyles" ); + QDomElement stylesElem = doc.createElement( QStringLiteral( "LayerStyles" ) ); QMap::const_iterator styleIt = mLayerStyleOverrides.constBegin(); for ( ; styleIt != mLayerStyleOverrides.constEnd(); ++styleIt ) { - QDomElement styleElem = doc.createElement( "LayerStyle" ); - styleElem.setAttribute( "layerid", styleIt.key() ); + QDomElement styleElem = doc.createElement( QStringLiteral( "LayerStyle" ) ); + styleElem.setAttribute( QStringLiteral( "layerid" ), styleIt.key() ); QgsMapLayerStyle style( styleIt.value() ); style.writeXml( styleElem ); stylesElem.appendChild( styleElem ); @@ -1303,7 +1303,7 @@ bool QgsComposerMap::writeXml( QDomElement& elem, QDomDocument & doc ) const } //write a dummy "Grid" element to prevent crashes on pre 2.5 versions (refs #10905) - QDomElement gridElem = doc.createElement( "Grid" ); + QDomElement gridElem = doc.createElement( QStringLiteral( "Grid" ) ); composerMapElem.appendChild( gridElem ); //grids @@ -1313,10 +1313,10 @@ bool QgsComposerMap::writeXml( QDomElement& elem, QDomDocument & doc ) const mOverviewStack->writeXml( composerMapElem, doc ); //atlas - QDomElement atlasElem = doc.createElement( "AtlasMap" ); - atlasElem.setAttribute( "atlasDriven", mAtlasDriven ); - atlasElem.setAttribute( "scalingMode", mAtlasScalingMode ); - atlasElem.setAttribute( "margin", qgsDoubleToString( mAtlasMargin ) ); + QDomElement atlasElem = doc.createElement( QStringLiteral( "AtlasMap" ) ); + atlasElem.setAttribute( QStringLiteral( "atlasDriven" ), mAtlasDriven ); + atlasElem.setAttribute( QStringLiteral( "scalingMode" ), mAtlasScalingMode ); + atlasElem.setAttribute( QStringLiteral( "margin" ), qgsDoubleToString( mAtlasMargin ) ); composerMapElem.appendChild( atlasElem ); elem.appendChild( composerMapElem ); @@ -1330,8 +1330,8 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d return false; } - QString idRead = itemElem.attribute( "id", "not found" ); - if ( idRead != "not found" ) + QString idRead = itemElem.attribute( QStringLiteral( "id" ), QStringLiteral( "not found" ) ); + if ( idRead != QLatin1String( "not found" ) ) { mId = idRead.toInt(); updateToolTip(); @@ -1339,12 +1339,12 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d mPreviewMode = Rectangle; //previewMode - QString previewMode = itemElem.attribute( "previewMode" ); - if ( previewMode == "Cache" ) + QString previewMode = itemElem.attribute( QStringLiteral( "previewMode" ) ); + if ( previewMode == QLatin1String( "Cache" ) ) { mPreviewMode = Cache; } - else if ( previewMode == "Render" ) + else if ( previewMode == QLatin1String( "Render" ) ) { mPreviewMode = Render; } @@ -1354,31 +1354,31 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d } //extent - QDomNodeList extentNodeList = itemElem.elementsByTagName( "Extent" ); + QDomNodeList extentNodeList = itemElem.elementsByTagName( QStringLiteral( "Extent" ) ); if ( !extentNodeList.isEmpty() ) { QDomElement extentElem = extentNodeList.at( 0 ).toElement(); double xmin, xmax, ymin, ymax; - xmin = extentElem.attribute( "xmin" ).toDouble(); - xmax = extentElem.attribute( "xmax" ).toDouble(); - ymin = extentElem.attribute( "ymin" ).toDouble(); - ymax = extentElem.attribute( "ymax" ).toDouble(); + xmin = extentElem.attribute( QStringLiteral( "xmin" ) ).toDouble(); + xmax = extentElem.attribute( QStringLiteral( "xmax" ) ).toDouble(); + ymin = extentElem.attribute( QStringLiteral( "ymin" ) ).toDouble(); + ymax = extentElem.attribute( QStringLiteral( "ymax" ) ).toDouble(); setNewExtent( QgsRectangle( xmin, ymin, xmax, ymax ) ); } //map rotation - if ( !qgsDoubleNear( itemElem.attribute( "mapRotation", "0" ).toDouble(), 0.0 ) ) + if ( !qgsDoubleNear( itemElem.attribute( QStringLiteral( "mapRotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { - mMapRotation = itemElem.attribute( "mapRotation", "0" ).toDouble(); + mMapRotation = itemElem.attribute( QStringLiteral( "mapRotation" ), QStringLiteral( "0" ) ).toDouble(); } // follow map theme - mFollowVisibilityPreset = itemElem.attribute( "followPreset" ).compare( "true" ) == 0; - mFollowVisibilityPresetName = itemElem.attribute( "followPresetName" ); + mFollowVisibilityPreset = itemElem.attribute( QStringLiteral( "followPreset" ) ).compare( QLatin1String( "true" ) ) == 0; + mFollowVisibilityPresetName = itemElem.attribute( QStringLiteral( "followPresetName" ) ); //mKeepLayerSet flag - QString keepLayerSetFlag = itemElem.attribute( "keepLayerSet" ); - if ( keepLayerSetFlag.compare( "true", Qt::CaseInsensitive ) == 0 ) + QString keepLayerSetFlag = itemElem.attribute( QStringLiteral( "keepLayerSet" ) ); + if ( keepLayerSetFlag.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { mKeepLayerSet = true; } @@ -1387,8 +1387,8 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d mKeepLayerSet = false; } - QString drawCanvasItemsFlag = itemElem.attribute( "drawCanvasItems", "true" ); - if ( drawCanvasItemsFlag.compare( "true", Qt::CaseInsensitive ) == 0 ) + QString drawCanvasItemsFlag = itemElem.attribute( QStringLiteral( "drawCanvasItems" ), QStringLiteral( "true" ) ); + if ( drawCanvasItemsFlag.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { mDrawCanvasItems = true; } @@ -1400,12 +1400,12 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d mLayerStyleOverrides.clear(); //mLayerSet - QDomNodeList layerSetNodeList = itemElem.elementsByTagName( "LayerSet" ); + QDomNodeList layerSetNodeList = itemElem.elementsByTagName( QStringLiteral( "LayerSet" ) ); QStringList layerSet; if ( !layerSetNodeList.isEmpty() ) { QDomElement layerSetElem = layerSetNodeList.at( 0 ).toElement(); - QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( "Layer" ); + QDomNodeList layerIdNodeList = layerSetElem.elementsByTagName( QStringLiteral( "Layer" ) ); layerSet.reserve( layerIdNodeList.size() ); for ( int i = 0; i < layerIdNodeList.size(); ++i ) { @@ -1416,16 +1416,16 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d mLayerSet = layerSet; // override styles - QDomNodeList layerStylesNodeList = itemElem.elementsByTagName( "LayerStyles" ); + QDomNodeList layerStylesNodeList = itemElem.elementsByTagName( QStringLiteral( "LayerStyles" ) ); mKeepLayerStyles = !layerStylesNodeList.isEmpty(); if ( mKeepLayerStyles ) { QDomElement layerStylesElem = layerStylesNodeList.at( 0 ).toElement(); - QDomNodeList layerStyleNodeList = layerStylesElem.elementsByTagName( "LayerStyle" ); + QDomNodeList layerStyleNodeList = layerStylesElem.elementsByTagName( QStringLiteral( "LayerStyle" ) ); for ( int i = 0; i < layerStyleNodeList.size(); ++i ) { const QDomElement& layerStyleElement = layerStyleNodeList.at( i ).toElement(); - QString layerId = layerStyleElement.attribute( "layerid" ); + QString layerId = layerStyleElement.attribute( QStringLiteral( "layerid" ) ); QgsMapLayerStyle style; style.readXml( layerStyleElement ); mLayerStyleOverrides.insert( layerId, style.xmlData() ); @@ -1445,35 +1445,35 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d //load grid / grid annotation in old xml format //only do this if the grid stack didn't load any grids, otherwise this will //be the dummy element created by QGIS >= 2.5 (refs #10905) - QDomNodeList gridNodeList = itemElem.elementsByTagName( "Grid" ); + QDomNodeList gridNodeList = itemElem.elementsByTagName( QStringLiteral( "Grid" ) ); if ( mGridStack->size() == 0 && !gridNodeList.isEmpty() ) { QDomElement gridElem = gridNodeList.at( 0 ).toElement(); QgsComposerMapGrid* mapGrid = new QgsComposerMapGrid( tr( "Grid %1" ).arg( 1 ), this ); - mapGrid->setEnabled( gridElem.attribute( "show", "0" ) != "0" ); - mapGrid->setStyle( QgsComposerMapGrid::GridStyle( gridElem.attribute( "gridStyle", "0" ).toInt() ) ); - mapGrid->setIntervalX( gridElem.attribute( "intervalX", "0" ).toDouble() ); - mapGrid->setIntervalY( gridElem.attribute( "intervalY", "0" ).toDouble() ); - mapGrid->setOffsetX( gridElem.attribute( "offsetX", "0" ).toDouble() ); - mapGrid->setOffsetY( gridElem.attribute( "offsetY", "0" ).toDouble() ); - mapGrid->setCrossLength( gridElem.attribute( "crossLength", "3" ).toDouble() ); - mapGrid->setFrameStyle( static_cast< QgsComposerMapGrid::FrameStyle >( gridElem.attribute( "gridFrameStyle", "0" ).toInt() ) ); - mapGrid->setFrameWidth( gridElem.attribute( "gridFrameWidth", "2.0" ).toDouble() ); - mapGrid->setFramePenSize( gridElem.attribute( "gridFramePenThickness", "0.5" ).toDouble() ); - mapGrid->setFramePenColor( QgsSymbolLayerUtils::decodeColor( gridElem.attribute( "framePenColor", "0,0,0" ) ) ); - mapGrid->setFrameFillColor1( QgsSymbolLayerUtils::decodeColor( gridElem.attribute( "frameFillColor1", "255,255,255,255" ) ) ); - mapGrid->setFrameFillColor2( QgsSymbolLayerUtils::decodeColor( gridElem.attribute( "frameFillColor2", "0,0,0,255" ) ) ); - mapGrid->setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( "gridBlendMode", "0" ).toUInt() ) ) ); - QDomElement gridSymbolElem = gridElem.firstChildElement( "symbol" ); + mapGrid->setEnabled( gridElem.attribute( QStringLiteral( "show" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); + mapGrid->setStyle( QgsComposerMapGrid::GridStyle( gridElem.attribute( QStringLiteral( "gridStyle" ), QStringLiteral( "0" ) ).toInt() ) ); + mapGrid->setIntervalX( gridElem.attribute( QStringLiteral( "intervalX" ), QStringLiteral( "0" ) ).toDouble() ); + mapGrid->setIntervalY( gridElem.attribute( QStringLiteral( "intervalY" ), QStringLiteral( "0" ) ).toDouble() ); + mapGrid->setOffsetX( gridElem.attribute( QStringLiteral( "offsetX" ), QStringLiteral( "0" ) ).toDouble() ); + mapGrid->setOffsetY( gridElem.attribute( QStringLiteral( "offsetY" ), QStringLiteral( "0" ) ).toDouble() ); + mapGrid->setCrossLength( gridElem.attribute( QStringLiteral( "crossLength" ), QStringLiteral( "3" ) ).toDouble() ); + mapGrid->setFrameStyle( static_cast< QgsComposerMapGrid::FrameStyle >( gridElem.attribute( QStringLiteral( "gridFrameStyle" ), QStringLiteral( "0" ) ).toInt() ) ); + mapGrid->setFrameWidth( gridElem.attribute( QStringLiteral( "gridFrameWidth" ), QStringLiteral( "2.0" ) ).toDouble() ); + mapGrid->setFramePenSize( gridElem.attribute( QStringLiteral( "gridFramePenThickness" ), QStringLiteral( "0.5" ) ).toDouble() ); + mapGrid->setFramePenColor( QgsSymbolLayerUtils::decodeColor( gridElem.attribute( QStringLiteral( "framePenColor" ), QStringLiteral( "0,0,0" ) ) ) ); + mapGrid->setFrameFillColor1( QgsSymbolLayerUtils::decodeColor( gridElem.attribute( QStringLiteral( "frameFillColor1" ), QStringLiteral( "255,255,255,255" ) ) ) ); + mapGrid->setFrameFillColor2( QgsSymbolLayerUtils::decodeColor( gridElem.attribute( QStringLiteral( "frameFillColor2" ), QStringLiteral( "0,0,0,255" ) ) ) ); + mapGrid->setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( QStringLiteral( "gridBlendMode" ), QStringLiteral( "0" ) ).toUInt() ) ) ); + QDomElement gridSymbolElem = gridElem.firstChildElement( QStringLiteral( "symbol" ) ); QgsLineSymbol* lineSymbol = nullptr; if ( gridSymbolElem.isNull() ) { //old project file, read penWidth /penColorRed, penColorGreen, penColorBlue lineSymbol = QgsLineSymbol::createSimple( QgsStringMap() ); - lineSymbol->setWidth( gridElem.attribute( "penWidth", "0" ).toDouble() ); - lineSymbol->setColor( QColor( gridElem.attribute( "penColorRed", "0" ).toInt(), - gridElem.attribute( "penColorGreen", "0" ).toInt(), - gridElem.attribute( "penColorBlue", "0" ).toInt() ) ); + lineSymbol->setWidth( gridElem.attribute( QStringLiteral( "penWidth" ), QStringLiteral( "0" ) ).toDouble() ); + lineSymbol->setColor( QColor( gridElem.attribute( QStringLiteral( "penColorRed" ), QStringLiteral( "0" ) ).toInt(), + gridElem.attribute( QStringLiteral( "penColorGreen" ), QStringLiteral( "0" ) ).toInt(), + gridElem.attribute( QStringLiteral( "penColorBlue" ), QStringLiteral( "0" ) ).toInt() ) ); } else { @@ -1482,44 +1482,44 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d mapGrid->setLineSymbol( lineSymbol ); //annotation - QDomNodeList annotationNodeList = gridElem.elementsByTagName( "Annotation" ); + QDomNodeList annotationNodeList = gridElem.elementsByTagName( QStringLiteral( "Annotation" ) ); if ( !annotationNodeList.isEmpty() ) { QDomElement annotationElem = annotationNodeList.at( 0 ).toElement(); - mapGrid->setAnnotationEnabled( annotationElem.attribute( "show", "0" ) != "0" ); - mapGrid->setAnnotationFormat( QgsComposerMapGrid::AnnotationFormat( annotationElem.attribute( "format", "0" ).toInt() ) ); - mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( "leftPosition", "0" ).toInt() ), QgsComposerMapGrid::Left ); - mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( "rightPosition", "0" ).toInt() ), QgsComposerMapGrid::Right ); - mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( "topPosition", "0" ).toInt() ), QgsComposerMapGrid::Top ); - mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( "bottomPosition", "0" ).toInt() ), QgsComposerMapGrid::Bottom ); - mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( "leftDirection", "0" ).toInt() ), QgsComposerMapGrid::Left ); - mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( "rightDirection", "0" ).toInt() ), QgsComposerMapGrid::Right ); - mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( "topDirection", "0" ).toInt() ), QgsComposerMapGrid::Top ); - mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( "bottomDirection", "0" ).toInt() ), QgsComposerMapGrid::Bottom ); - mapGrid->setAnnotationFrameDistance( annotationElem.attribute( "frameDistance", "0" ).toDouble() ); + mapGrid->setAnnotationEnabled( annotationElem.attribute( QStringLiteral( "show" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); + mapGrid->setAnnotationFormat( QgsComposerMapGrid::AnnotationFormat( annotationElem.attribute( QStringLiteral( "format" ), QStringLiteral( "0" ) ).toInt() ) ); + mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( QStringLiteral( "leftPosition" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Left ); + mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( QStringLiteral( "rightPosition" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Right ); + mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( QStringLiteral( "topPosition" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Top ); + mapGrid->setAnnotationPosition( QgsComposerMapGrid::AnnotationPosition( annotationElem.attribute( QStringLiteral( "bottomPosition" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Bottom ); + mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( QStringLiteral( "leftDirection" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Left ); + mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( QStringLiteral( "rightDirection" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Right ); + mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( QStringLiteral( "topDirection" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Top ); + mapGrid->setAnnotationDirection( QgsComposerMapGrid::AnnotationDirection( annotationElem.attribute( QStringLiteral( "bottomDirection" ), QStringLiteral( "0" ) ).toInt() ), QgsComposerMapGrid::Bottom ); + mapGrid->setAnnotationFrameDistance( annotationElem.attribute( QStringLiteral( "frameDistance" ), QStringLiteral( "0" ) ).toDouble() ); QFont annotationFont; - annotationFont.fromString( annotationElem.attribute( "font", "" ) ); + annotationFont.fromString( annotationElem.attribute( QStringLiteral( "font" ), QLatin1String( "" ) ) ); mapGrid->setAnnotationFont( annotationFont ); - mapGrid->setAnnotationFontColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "fontColor", "0,0,0,255" ) ) ); + mapGrid->setAnnotationFontColor( QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "0,0,0,255" ) ) ) ); - mapGrid->setAnnotationPrecision( annotationElem.attribute( "precision", "3" ).toInt() ); + mapGrid->setAnnotationPrecision( annotationElem.attribute( QStringLiteral( "precision" ), QStringLiteral( "3" ) ).toInt() ); } mGridStack->addGrid( mapGrid ); } //load overview in old xml format - QDomElement overviewFrameElem = itemElem.firstChildElement( "overviewFrame" ); + QDomElement overviewFrameElem = itemElem.firstChildElement( QStringLiteral( "overviewFrame" ) ); if ( !overviewFrameElem.isNull() ) { QgsComposerMapOverview* mapOverview = new QgsComposerMapOverview( tr( "Overview %1" ).arg( mOverviewStack->size() + 1 ), this ); - mapOverview->setFrameMap( overviewFrameElem.attribute( "overviewFrameMap", "-1" ).toInt() ); - mapOverview->setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( overviewFrameElem.attribute( "overviewBlendMode", "0" ).toUInt() ) ) ); - mapOverview->setInverted( overviewFrameElem.attribute( "overviewInverted" ).compare( "true", Qt::CaseInsensitive ) == 0 ); - mapOverview->setCentered( overviewFrameElem.attribute( "overviewCentered" ).compare( "true", Qt::CaseInsensitive ) == 0 ); + mapOverview->setFrameMap( overviewFrameElem.attribute( QStringLiteral( "overviewFrameMap" ), QStringLiteral( "-1" ) ).toInt() ); + mapOverview->setBlendMode( QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( overviewFrameElem.attribute( QStringLiteral( "overviewBlendMode" ), QStringLiteral( "0" ) ).toUInt() ) ) ); + mapOverview->setInverted( overviewFrameElem.attribute( QStringLiteral( "overviewInverted" ) ).compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); + mapOverview->setCentered( overviewFrameElem.attribute( QStringLiteral( "overviewCentered" ) ).compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); QgsFillSymbol* fillSymbol = nullptr; - QDomElement overviewFrameSymbolElem = overviewFrameElem.firstChildElement( "symbol" ); + QDomElement overviewFrameSymbolElem = overviewFrameElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !overviewFrameSymbolElem.isNull() ) { fillSymbol = QgsSymbolLayerUtils::loadSymbol( overviewFrameSymbolElem ); @@ -1529,32 +1529,32 @@ bool QgsComposerMap::readXml( const QDomElement& itemElem, const QDomDocument& d } //atlas - QDomNodeList atlasNodeList = itemElem.elementsByTagName( "AtlasMap" ); + QDomNodeList atlasNodeList = itemElem.elementsByTagName( QStringLiteral( "AtlasMap" ) ); if ( !atlasNodeList.isEmpty() ) { QDomElement atlasElem = atlasNodeList.at( 0 ).toElement(); - mAtlasDriven = ( atlasElem.attribute( "atlasDriven", "0" ) != "0" ); - if ( atlasElem.hasAttribute( "fixedScale" ) ) // deprecated XML + mAtlasDriven = ( atlasElem.attribute( QStringLiteral( "atlasDriven" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); + if ( atlasElem.hasAttribute( QStringLiteral( "fixedScale" ) ) ) // deprecated XML { - mAtlasScalingMode = ( atlasElem.attribute( "fixedScale", "0" ) != "0" ) ? Fixed : Auto; + mAtlasScalingMode = ( atlasElem.attribute( QStringLiteral( "fixedScale" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ) ? Fixed : Auto; } - else if ( atlasElem.hasAttribute( "scalingMode" ) ) + else if ( atlasElem.hasAttribute( QStringLiteral( "scalingMode" ) ) ) { - mAtlasScalingMode = static_cast( atlasElem.attribute( "scalingMode" ).toInt() ); + mAtlasScalingMode = static_cast( atlasElem.attribute( QStringLiteral( "scalingMode" ) ).toInt() ); } - mAtlasMargin = atlasElem.attribute( "margin", "0.1" ).toDouble(); + mAtlasMargin = atlasElem.attribute( QStringLiteral( "margin" ), QStringLiteral( "0.1" ) ).toDouble(); } //restore general composer item properties - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); - if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) ) + if ( !qgsDoubleNear( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { //in versions prior to 2.1 map rotation was stored in the rotation attribute - mMapRotation = composerItemElem.attribute( "rotation", "0" ).toDouble(); + mMapRotation = composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(); } _readXml( composerItemElem, doc ); @@ -1815,15 +1815,15 @@ QgsExpressionContext QgsComposerMap::createExpressionContext() const QgsExpressionContextScope* scope = new QgsExpressionContextScope( tr( "Map Settings" ) ); //use QgsComposerItem's id, not map item's ID, since that is user-definable - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_id", QgsComposerItem::id(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_rotation", mMapRotation, true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_scale", scale(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_id" ), QgsComposerItem::id(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_rotation" ), mMapRotation, true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_scale" ), scale(), true ) ); QgsRectangle extent( *currentMapExtent() ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_width", extent.width(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_height", extent.height(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_width" ), extent.width(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_height" ), extent.height(), true ) ); QgsGeometry centerPoint = QgsGeometry::fromPoint( extent.center() ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_center", QVariant::fromValue( centerPoint ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_center" ), QVariant::fromValue( centerPoint ), true ) ); context.appendScope( scope ); diff --git a/src/core/composer/qgscomposermapgrid.cpp b/src/core/composer/qgscomposermapgrid.cpp index 230d53743d56..9faebcf3b1c6 100644 --- a/src/core/composer/qgscomposermapgrid.cpp +++ b/src/core/composer/qgscomposermapgrid.cpp @@ -111,11 +111,11 @@ bool QgsComposerMapGridStack::readXml( const QDomElement &elem, const QDomDocume removeItems(); //read grid stack - QDomNodeList mapGridNodeList = elem.elementsByTagName( "ComposerMapGrid" ); + QDomNodeList mapGridNodeList = elem.elementsByTagName( QStringLiteral( "ComposerMapGrid" ) ); for ( int i = 0; i < mapGridNodeList.size(); ++i ) { QDomElement mapGridElem = mapGridNodeList.at( i ).toElement(); - QgsComposerMapGrid* mapGrid = new QgsComposerMapGrid( mapGridElem.attribute( "name" ), mComposerMap ); + QgsComposerMapGrid* mapGrid = new QgsComposerMapGrid( mapGridElem.attribute( QStringLiteral( "name" ) ), mComposerMap ); mapGrid->readXml( mapGridElem, doc ); mItems.append( mapGrid ); } @@ -221,7 +221,7 @@ void QgsComposerMapGrid::init() //get default composer font from settings QSettings settings; - QString defaultFontString = settings.value( "/Composer/defaultFont" ).toString(); + QString defaultFontString = settings.value( QStringLiteral( "/Composer/defaultFont" ) ).toString(); if ( !defaultFontString.isEmpty() ) { mGridAnnotationFont.setFamily( defaultFontString ); @@ -241,9 +241,9 @@ void QgsComposerMapGrid::createDefaultGridLineSymbol() { delete mGridLineSymbol; QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "width", "0.3" ); - properties.insert( "capstyle", "flat" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "width" ), QStringLiteral( "0.3" ) ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "flat" ) ); mGridLineSymbol = QgsLineSymbol::createSimple( properties ); } @@ -251,9 +251,9 @@ void QgsComposerMapGrid::createDefaultGridMarkerSymbol() { delete mGridMarkerSymbol; QgsStringMap properties; - properties.insert( "name", "circle" ); - properties.insert( "size", "2.0" ); - properties.insert( "color", "0,0,0,255" ); + properties.insert( QStringLiteral( "name" ), QStringLiteral( "circle" ) ); + properties.insert( QStringLiteral( "size" ), QStringLiteral( "2.0" ) ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); mGridMarkerSymbol = QgsMarkerSymbol::createSimple( properties ); } @@ -280,61 +280,61 @@ bool QgsComposerMapGrid::writeXml( QDomElement& elem, QDomDocument& doc ) const return false; } - QDomElement mapGridElem = doc.createElement( "ComposerMapGrid" ); - mapGridElem.setAttribute( "gridStyle", mGridStyle ); - mapGridElem.setAttribute( "intervalX", qgsDoubleToString( mGridIntervalX ) ); - mapGridElem.setAttribute( "intervalY", qgsDoubleToString( mGridIntervalY ) ); - mapGridElem.setAttribute( "offsetX", qgsDoubleToString( mGridOffsetX ) ); - mapGridElem.setAttribute( "offsetY", qgsDoubleToString( mGridOffsetY ) ); - mapGridElem.setAttribute( "crossLength", qgsDoubleToString( mCrossLength ) ); + QDomElement mapGridElem = doc.createElement( QStringLiteral( "ComposerMapGrid" ) ); + mapGridElem.setAttribute( QStringLiteral( "gridStyle" ), mGridStyle ); + mapGridElem.setAttribute( QStringLiteral( "intervalX" ), qgsDoubleToString( mGridIntervalX ) ); + mapGridElem.setAttribute( QStringLiteral( "intervalY" ), qgsDoubleToString( mGridIntervalY ) ); + mapGridElem.setAttribute( QStringLiteral( "offsetX" ), qgsDoubleToString( mGridOffsetX ) ); + mapGridElem.setAttribute( QStringLiteral( "offsetY" ), qgsDoubleToString( mGridOffsetY ) ); + mapGridElem.setAttribute( QStringLiteral( "crossLength" ), qgsDoubleToString( mCrossLength ) ); - QDomElement lineStyleElem = doc.createElement( "lineStyle" ); + QDomElement lineStyleElem = doc.createElement( QStringLiteral( "lineStyle" ) ); QDomElement gridLineStyleElem = QgsSymbolLayerUtils::saveSymbol( QString(), mGridLineSymbol, doc ); lineStyleElem.appendChild( gridLineStyleElem ); mapGridElem.appendChild( lineStyleElem ); - QDomElement markerStyleElem = doc.createElement( "markerStyle" ); + QDomElement markerStyleElem = doc.createElement( QStringLiteral( "markerStyle" ) ); QDomElement gridMarkerStyleElem = QgsSymbolLayerUtils::saveSymbol( QString(), mGridMarkerSymbol, doc ); markerStyleElem.appendChild( gridMarkerStyleElem ); mapGridElem.appendChild( markerStyleElem ); - mapGridElem.setAttribute( "gridFrameStyle", mGridFrameStyle ); - mapGridElem.setAttribute( "gridFrameSideFlags", mGridFrameSides ); - mapGridElem.setAttribute( "gridFrameWidth", qgsDoubleToString( mGridFrameWidth ) ); - mapGridElem.setAttribute( "gridFramePenThickness", qgsDoubleToString( mGridFramePenThickness ) ); - mapGridElem.setAttribute( "gridFramePenColor", QgsSymbolLayerUtils::encodeColor( mGridFramePenColor ) ); - mapGridElem.setAttribute( "frameFillColor1", QgsSymbolLayerUtils::encodeColor( mGridFrameFillColor1 ) ); - mapGridElem.setAttribute( "frameFillColor2", QgsSymbolLayerUtils::encodeColor( mGridFrameFillColor2 ) ); - mapGridElem.setAttribute( "leftFrameDivisions", mLeftFrameDivisions ); - mapGridElem.setAttribute( "rightFrameDivisions", mRightFrameDivisions ); - mapGridElem.setAttribute( "topFrameDivisions", mTopFrameDivisions ); - mapGridElem.setAttribute( "bottomFrameDivisions", mBottomFrameDivisions ); + mapGridElem.setAttribute( QStringLiteral( "gridFrameStyle" ), mGridFrameStyle ); + mapGridElem.setAttribute( QStringLiteral( "gridFrameSideFlags" ), mGridFrameSides ); + mapGridElem.setAttribute( QStringLiteral( "gridFrameWidth" ), qgsDoubleToString( mGridFrameWidth ) ); + mapGridElem.setAttribute( QStringLiteral( "gridFramePenThickness" ), qgsDoubleToString( mGridFramePenThickness ) ); + mapGridElem.setAttribute( QStringLiteral( "gridFramePenColor" ), QgsSymbolLayerUtils::encodeColor( mGridFramePenColor ) ); + mapGridElem.setAttribute( QStringLiteral( "frameFillColor1" ), QgsSymbolLayerUtils::encodeColor( mGridFrameFillColor1 ) ); + mapGridElem.setAttribute( QStringLiteral( "frameFillColor2" ), QgsSymbolLayerUtils::encodeColor( mGridFrameFillColor2 ) ); + mapGridElem.setAttribute( QStringLiteral( "leftFrameDivisions" ), mLeftFrameDivisions ); + mapGridElem.setAttribute( QStringLiteral( "rightFrameDivisions" ), mRightFrameDivisions ); + mapGridElem.setAttribute( QStringLiteral( "topFrameDivisions" ), mTopFrameDivisions ); + mapGridElem.setAttribute( QStringLiteral( "bottomFrameDivisions" ), mBottomFrameDivisions ); if ( mCRS.isValid() ) { mCRS.writeXml( mapGridElem, doc ); } - mapGridElem.setAttribute( "annotationFormat", mGridAnnotationFormat ); - mapGridElem.setAttribute( "showAnnotation", mShowGridAnnotation ); - mapGridElem.setAttribute( "annotationExpression", mGridAnnotationExpressionString ); - mapGridElem.setAttribute( "leftAnnotationDisplay", mLeftGridAnnotationDisplay ); - mapGridElem.setAttribute( "rightAnnotationDisplay", mRightGridAnnotationDisplay ); - mapGridElem.setAttribute( "topAnnotationDisplay", mTopGridAnnotationDisplay ); - mapGridElem.setAttribute( "bottomAnnotationDisplay", mBottomGridAnnotationDisplay ); - mapGridElem.setAttribute( "leftAnnotationPosition", mLeftGridAnnotationPosition ); - mapGridElem.setAttribute( "rightAnnotationPosition", mRightGridAnnotationPosition ); - mapGridElem.setAttribute( "topAnnotationPosition", mTopGridAnnotationPosition ); - mapGridElem.setAttribute( "bottomAnnotationPosition", mBottomGridAnnotationPosition ); - mapGridElem.setAttribute( "leftAnnotationDirection", mLeftGridAnnotationDirection ); - mapGridElem.setAttribute( "rightAnnotationDirection", mRightGridAnnotationDirection ); - mapGridElem.setAttribute( "topAnnotationDirection", mTopGridAnnotationDirection ); - mapGridElem.setAttribute( "bottomAnnotationDirection", mBottomGridAnnotationDirection ); - mapGridElem.setAttribute( "frameAnnotationDistance", QString::number( mAnnotationFrameDistance ) ); - mapGridElem.appendChild( QgsFontUtils::toXmlElement( mGridAnnotationFont, doc, "annotationFontProperties" ) ); - mapGridElem.setAttribute( "annotationFontColor", QgsSymbolLayerUtils::encodeColor( mGridAnnotationFontColor ) ); - mapGridElem.setAttribute( "annotationPrecision", mGridAnnotationPrecision ); - mapGridElem.setAttribute( "unit", mGridUnit ); - mapGridElem.setAttribute( "blendMode", mBlendMode ); + mapGridElem.setAttribute( QStringLiteral( "annotationFormat" ), mGridAnnotationFormat ); + mapGridElem.setAttribute( QStringLiteral( "showAnnotation" ), mShowGridAnnotation ); + mapGridElem.setAttribute( QStringLiteral( "annotationExpression" ), mGridAnnotationExpressionString ); + mapGridElem.setAttribute( QStringLiteral( "leftAnnotationDisplay" ), mLeftGridAnnotationDisplay ); + mapGridElem.setAttribute( QStringLiteral( "rightAnnotationDisplay" ), mRightGridAnnotationDisplay ); + mapGridElem.setAttribute( QStringLiteral( "topAnnotationDisplay" ), mTopGridAnnotationDisplay ); + mapGridElem.setAttribute( QStringLiteral( "bottomAnnotationDisplay" ), mBottomGridAnnotationDisplay ); + mapGridElem.setAttribute( QStringLiteral( "leftAnnotationPosition" ), mLeftGridAnnotationPosition ); + mapGridElem.setAttribute( QStringLiteral( "rightAnnotationPosition" ), mRightGridAnnotationPosition ); + mapGridElem.setAttribute( QStringLiteral( "topAnnotationPosition" ), mTopGridAnnotationPosition ); + mapGridElem.setAttribute( QStringLiteral( "bottomAnnotationPosition" ), mBottomGridAnnotationPosition ); + mapGridElem.setAttribute( QStringLiteral( "leftAnnotationDirection" ), mLeftGridAnnotationDirection ); + mapGridElem.setAttribute( QStringLiteral( "rightAnnotationDirection" ), mRightGridAnnotationDirection ); + mapGridElem.setAttribute( QStringLiteral( "topAnnotationDirection" ), mTopGridAnnotationDirection ); + mapGridElem.setAttribute( QStringLiteral( "bottomAnnotationDirection" ), mBottomGridAnnotationDirection ); + mapGridElem.setAttribute( QStringLiteral( "frameAnnotationDistance" ), QString::number( mAnnotationFrameDistance ) ); + mapGridElem.appendChild( QgsFontUtils::toXmlElement( mGridAnnotationFont, doc, QStringLiteral( "annotationFontProperties" ) ) ); + mapGridElem.setAttribute( QStringLiteral( "annotationFontColor" ), QgsSymbolLayerUtils::encodeColor( mGridAnnotationFontColor ) ); + mapGridElem.setAttribute( QStringLiteral( "annotationPrecision" ), mGridAnnotationPrecision ); + mapGridElem.setAttribute( QStringLiteral( "unit" ), mGridUnit ); + mapGridElem.setAttribute( QStringLiteral( "blendMode" ), mBlendMode ); bool ok = QgsComposerMapItem::writeXml( mapGridElem, doc ); elem.appendChild( mapGridElem ); @@ -352,28 +352,28 @@ bool QgsComposerMapGrid::readXml( const QDomElement& itemElem, const QDomDocumen bool ok = QgsComposerMapItem::readXml( itemElem, doc ); //grid - mGridStyle = QgsComposerMapGrid::GridStyle( itemElem.attribute( "gridStyle", "0" ).toInt() ); - mGridIntervalX = itemElem.attribute( "intervalX", "0" ).toDouble(); - mGridIntervalY = itemElem.attribute( "intervalY", "0" ).toDouble(); - mGridOffsetX = itemElem.attribute( "offsetX", "0" ).toDouble(); - mGridOffsetY = itemElem.attribute( "offsetY", "0" ).toDouble(); - mCrossLength = itemElem.attribute( "crossLength", "3" ).toDouble(); - mGridFrameStyle = static_cast< QgsComposerMapGrid::FrameStyle >( itemElem.attribute( "gridFrameStyle", "0" ).toInt() ); - mGridFrameSides = static_cast< QgsComposerMapGrid::FrameSideFlags >( itemElem.attribute( "gridFrameSideFlags", "15" ).toInt() ); - mGridFrameWidth = itemElem.attribute( "gridFrameWidth", "2.0" ).toDouble(); - mGridFramePenThickness = itemElem.attribute( "gridFramePenThickness", "0.3" ).toDouble(); - mGridFramePenColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "gridFramePenColor", "0,0,0" ) ); - mGridFrameFillColor1 = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "frameFillColor1", "255,255,255,255" ) ); - mGridFrameFillColor2 = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "frameFillColor2", "0,0,0,255" ) ); - mLeftFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "leftFrameDivisions", "0" ).toInt() ); - mRightFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "rightFrameDivisions", "0" ).toInt() ); - mTopFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "topFrameDivisions", "0" ).toInt() ); - mBottomFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "bottomFrameDivisions", "0" ).toInt() ); - - QDomElement lineStyleElem = itemElem.firstChildElement( "lineStyle" ); + mGridStyle = QgsComposerMapGrid::GridStyle( itemElem.attribute( QStringLiteral( "gridStyle" ), QStringLiteral( "0" ) ).toInt() ); + mGridIntervalX = itemElem.attribute( QStringLiteral( "intervalX" ), QStringLiteral( "0" ) ).toDouble(); + mGridIntervalY = itemElem.attribute( QStringLiteral( "intervalY" ), QStringLiteral( "0" ) ).toDouble(); + mGridOffsetX = itemElem.attribute( QStringLiteral( "offsetX" ), QStringLiteral( "0" ) ).toDouble(); + mGridOffsetY = itemElem.attribute( QStringLiteral( "offsetY" ), QStringLiteral( "0" ) ).toDouble(); + mCrossLength = itemElem.attribute( QStringLiteral( "crossLength" ), QStringLiteral( "3" ) ).toDouble(); + mGridFrameStyle = static_cast< QgsComposerMapGrid::FrameStyle >( itemElem.attribute( QStringLiteral( "gridFrameStyle" ), QStringLiteral( "0" ) ).toInt() ); + mGridFrameSides = static_cast< QgsComposerMapGrid::FrameSideFlags >( itemElem.attribute( QStringLiteral( "gridFrameSideFlags" ), QStringLiteral( "15" ) ).toInt() ); + mGridFrameWidth = itemElem.attribute( QStringLiteral( "gridFrameWidth" ), QStringLiteral( "2.0" ) ).toDouble(); + mGridFramePenThickness = itemElem.attribute( QStringLiteral( "gridFramePenThickness" ), QStringLiteral( "0.3" ) ).toDouble(); + mGridFramePenColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "gridFramePenColor" ), QStringLiteral( "0,0,0" ) ) ); + mGridFrameFillColor1 = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "frameFillColor1" ), QStringLiteral( "255,255,255,255" ) ) ); + mGridFrameFillColor2 = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "frameFillColor2" ), QStringLiteral( "0,0,0,255" ) ) ); + mLeftFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "leftFrameDivisions" ), QStringLiteral( "0" ) ).toInt() ); + mRightFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "rightFrameDivisions" ), QStringLiteral( "0" ) ).toInt() ); + mTopFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "topFrameDivisions" ), QStringLiteral( "0" ) ).toInt() ); + mBottomFrameDivisions = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "bottomFrameDivisions" ), QStringLiteral( "0" ) ).toInt() ); + + QDomElement lineStyleElem = itemElem.firstChildElement( QStringLiteral( "lineStyle" ) ); if ( !lineStyleElem.isNull() ) { - QDomElement symbolElem = lineStyleElem.firstChildElement( "symbol" ); + QDomElement symbolElem = lineStyleElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !symbolElem.isNull() ) { delete mGridLineSymbol; @@ -384,16 +384,16 @@ bool QgsComposerMapGrid::readXml( const QDomElement& itemElem, const QDomDocumen { //old project file, read penWidth /penColorRed, penColorGreen, penColorBlue mGridLineSymbol = QgsLineSymbol::createSimple( QgsStringMap() ); - mGridLineSymbol->setWidth( itemElem.attribute( "penWidth", "0" ).toDouble() ); - mGridLineSymbol->setColor( QColor( itemElem.attribute( "penColorRed", "0" ).toInt(), - itemElem.attribute( "penColorGreen", "0" ).toInt(), - itemElem.attribute( "penColorBlue", "0" ).toInt() ) ); + mGridLineSymbol->setWidth( itemElem.attribute( QStringLiteral( "penWidth" ), QStringLiteral( "0" ) ).toDouble() ); + mGridLineSymbol->setColor( QColor( itemElem.attribute( QStringLiteral( "penColorRed" ), QStringLiteral( "0" ) ).toInt(), + itemElem.attribute( QStringLiteral( "penColorGreen" ), QStringLiteral( "0" ) ).toInt(), + itemElem.attribute( QStringLiteral( "penColorBlue" ), QStringLiteral( "0" ) ).toInt() ) ); } - QDomElement markerStyleElem = itemElem.firstChildElement( "markerStyle" ); + QDomElement markerStyleElem = itemElem.firstChildElement( QStringLiteral( "markerStyle" ) ); if ( !markerStyleElem.isNull() ) { - QDomElement symbolElem = markerStyleElem.firstChildElement( "symbol" ); + QDomElement symbolElem = markerStyleElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !symbolElem.isNull() ) { delete mGridMarkerSymbol; @@ -404,34 +404,34 @@ bool QgsComposerMapGrid::readXml( const QDomElement& itemElem, const QDomDocumen if ( !mCRS.readXml( itemElem ) ) mCRS = QgsCoordinateReferenceSystem(); - mBlendMode = static_cast< QPainter::CompositionMode >( itemElem.attribute( "blendMode", "0" ).toUInt() ); + mBlendMode = static_cast< QPainter::CompositionMode >( itemElem.attribute( QStringLiteral( "blendMode" ), QStringLiteral( "0" ) ).toUInt() ); //annotation - mShowGridAnnotation = ( itemElem.attribute( "showAnnotation", "0" ) != "0" ); - mGridAnnotationFormat = QgsComposerMapGrid::AnnotationFormat( itemElem.attribute( "annotationFormat", "0" ).toInt() ); - mGridAnnotationExpressionString = itemElem.attribute( "annotationExpression" ); + mShowGridAnnotation = ( itemElem.attribute( QStringLiteral( "showAnnotation" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); + mGridAnnotationFormat = QgsComposerMapGrid::AnnotationFormat( itemElem.attribute( QStringLiteral( "annotationFormat" ), QStringLiteral( "0" ) ).toInt() ); + mGridAnnotationExpressionString = itemElem.attribute( QStringLiteral( "annotationExpression" ) ); mGridAnnotationExpression.reset(); - mLeftGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( "leftAnnotationPosition", "0" ).toInt() ); - mRightGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( "rightAnnotationPosition", "0" ).toInt() ); - mTopGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( "topAnnotationPosition", "0" ).toInt() ); - mBottomGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( "bottomAnnotationPosition", "0" ).toInt() ); - mLeftGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "leftAnnotationDisplay", "0" ).toInt() ); - mRightGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "rightAnnotationDisplay", "0" ).toInt() ); - mTopGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "topAnnotationDisplay", "0" ).toInt() ); - mBottomGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( "bottomAnnotationDisplay", "0" ).toInt() ); - - mLeftGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( "leftAnnotationDirection", "0" ).toInt() ); - mRightGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( "rightAnnotationDirection", "0" ).toInt() ); - mTopGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( "topAnnotationDirection", "0" ).toInt() ); - mBottomGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( "bottomAnnotationDirection", "0" ).toInt() ); - mAnnotationFrameDistance = itemElem.attribute( "frameAnnotationDistance", "0" ).toDouble(); - if ( !QgsFontUtils::setFromXmlChildNode( mGridAnnotationFont, itemElem, "annotationFontProperties" ) ) - { - mGridAnnotationFont.fromString( itemElem.attribute( "annotationFont", "" ) ); - } - mGridAnnotationFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "annotationFontColor", "0,0,0,255" ) ); - mGridAnnotationPrecision = itemElem.attribute( "annotationPrecision", "3" ).toInt(); - int gridUnitInt = itemElem.attribute( "unit", QString::number( MapUnit ) ).toInt(); + mLeftGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( QStringLiteral( "leftAnnotationPosition" ), QStringLiteral( "0" ) ).toInt() ); + mRightGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( QStringLiteral( "rightAnnotationPosition" ), QStringLiteral( "0" ) ).toInt() ); + mTopGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( QStringLiteral( "topAnnotationPosition" ), QStringLiteral( "0" ) ).toInt() ); + mBottomGridAnnotationPosition = QgsComposerMapGrid::AnnotationPosition( itemElem.attribute( QStringLiteral( "bottomAnnotationPosition" ), QStringLiteral( "0" ) ).toInt() ); + mLeftGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "leftAnnotationDisplay" ), QStringLiteral( "0" ) ).toInt() ); + mRightGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "rightAnnotationDisplay" ), QStringLiteral( "0" ) ).toInt() ); + mTopGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "topAnnotationDisplay" ), QStringLiteral( "0" ) ).toInt() ); + mBottomGridAnnotationDisplay = QgsComposerMapGrid::DisplayMode( itemElem.attribute( QStringLiteral( "bottomAnnotationDisplay" ), QStringLiteral( "0" ) ).toInt() ); + + mLeftGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( QStringLiteral( "leftAnnotationDirection" ), QStringLiteral( "0" ) ).toInt() ); + mRightGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( QStringLiteral( "rightAnnotationDirection" ), QStringLiteral( "0" ) ).toInt() ); + mTopGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( QStringLiteral( "topAnnotationDirection" ), QStringLiteral( "0" ) ).toInt() ); + mBottomGridAnnotationDirection = QgsComposerMapGrid::AnnotationDirection( itemElem.attribute( QStringLiteral( "bottomAnnotationDirection" ), QStringLiteral( "0" ) ).toInt() ); + mAnnotationFrameDistance = itemElem.attribute( QStringLiteral( "frameAnnotationDistance" ), QStringLiteral( "0" ) ).toDouble(); + if ( !QgsFontUtils::setFromXmlChildNode( mGridAnnotationFont, itemElem, QStringLiteral( "annotationFontProperties" ) ) ) + { + mGridAnnotationFont.fromString( itemElem.attribute( QStringLiteral( "annotationFont" ), QLatin1String( "" ) ) ); + } + mGridAnnotationFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "annotationFontColor" ), QStringLiteral( "0,0,0,255" ) ) ); + mGridAnnotationPrecision = itemElem.attribute( QStringLiteral( "annotationPrecision" ), QStringLiteral( "3" ) ).toInt(); + int gridUnitInt = itemElem.attribute( QStringLiteral( "unit" ), QString::number( MapUnit ) ).toInt(); mGridUnit = ( gridUnitInt <= static_cast< int >( CM ) ) ? static_cast< GridUnit >( gridUnitInt ) : MapUnit; return ok; } @@ -1475,8 +1475,8 @@ QString QgsComposerMapGrid::gridAnnotationString( double value, QgsComposerMapGr } else if ( mGridAnnotationFormat == CustomFormat ) { - expressionContext.lastScope()->setVariable( "grid_number", value ); - expressionContext.lastScope()->setVariable( "grid_axis", coord == QgsComposerMapGrid::Longitude ? "x" : "y" ); + expressionContext.lastScope()->setVariable( QStringLiteral( "grid_number" ), value ); + expressionContext.lastScope()->setVariable( QStringLiteral( "grid_axis" ), coord == QgsComposerMapGrid::Longitude ? "x" : "y" ); if ( !mGridAnnotationExpression.data() ) { mGridAnnotationExpression.reset( new QgsExpression( mGridAnnotationExpressionString ) ); @@ -1524,7 +1524,7 @@ QString QgsComposerMapGrid::gridAnnotationString( double value, QgsComposerMapGr { if ( split.size() < 2 ) { - return ""; + return QLatin1String( "" ); } return split.at( 1 ); } @@ -2210,9 +2210,9 @@ QgsExpressionContext QgsComposerMapGrid::createExpressionContext() const { QgsExpressionContext context = QgsComposerObject::createExpressionContext(); context.appendScope( new QgsExpressionContextScope( tr( "Grid" ) ) ); - context.lastScope()->setVariable( "grid_number", 0 ); - context.lastScope()->setVariable( "grid_axis", "x" ); - context.setHighlightedVariables( QStringList() << "grid_number" << "grid_axis" ); + context.lastScope()->setVariable( QStringLiteral( "grid_number" ), 0 ); + context.lastScope()->setVariable( QStringLiteral( "grid_axis" ), "x" ); + context.setHighlightedVariables( QStringList() << QStringLiteral( "grid_number" ) << QStringLiteral( "grid_axis" ) ); return context; } diff --git a/src/core/composer/qgscomposermapitem.cpp b/src/core/composer/qgscomposermapitem.cpp index da42b327d882..b14254216c88 100644 --- a/src/core/composer/qgscomposermapitem.cpp +++ b/src/core/composer/qgscomposermapitem.cpp @@ -37,18 +37,18 @@ QgsComposerMapItem::~QgsComposerMapItem() bool QgsComposerMapItem::writeXml( QDomElement &elem, QDomDocument &doc ) const { Q_UNUSED( doc ); - elem.setAttribute( "uuid", mUuid ); - elem.setAttribute( "name", mName ); - elem.setAttribute( "show", mEnabled ); + elem.setAttribute( QStringLiteral( "uuid" ), mUuid ); + elem.setAttribute( QStringLiteral( "name" ), mName ); + elem.setAttribute( QStringLiteral( "show" ), mEnabled ); return true; } bool QgsComposerMapItem::readXml( const QDomElement &itemElem, const QDomDocument &doc ) { Q_UNUSED( doc ); - mUuid = itemElem.attribute( "uuid" ); - mName = itemElem.attribute( "name" ); - mEnabled = ( itemElem.attribute( "show", "0" ) != "0" ); + mUuid = itemElem.attribute( QStringLiteral( "uuid" ) ); + mName = itemElem.attribute( QStringLiteral( "name" ) ); + mEnabled = ( itemElem.attribute( QStringLiteral( "show" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); return true; } diff --git a/src/core/composer/qgscomposermapoverview.cpp b/src/core/composer/qgscomposermapoverview.cpp index a661d072d1c0..427f865e1552 100644 --- a/src/core/composer/qgscomposermapoverview.cpp +++ b/src/core/composer/qgscomposermapoverview.cpp @@ -50,9 +50,9 @@ void QgsComposerMapOverview::createDefaultFrameSymbol() { delete mFrameSymbol; QgsStringMap properties; - properties.insert( "color", "255,0,0,255" ); - properties.insert( "style", "solid" ); - properties.insert( "style_border", "no" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "255,0,0,255" ) ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "solid" ) ); + properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "no" ) ); mFrameSymbol = QgsFillSymbol::createSimple( properties ); mFrameSymbol->setAlpha( 0.3 ); } @@ -158,12 +158,12 @@ bool QgsComposerMapOverview::writeXml( QDomElement &elem, QDomDocument &doc ) co } //overview map frame - QDomElement overviewFrameElem = doc.createElement( "ComposerMapOverview" ); + QDomElement overviewFrameElem = doc.createElement( QStringLiteral( "ComposerMapOverview" ) ); - overviewFrameElem.setAttribute( "frameMap", mFrameMapId ); - overviewFrameElem.setAttribute( "blendMode", QgsPainting::getBlendModeEnum( mBlendMode ) ); - overviewFrameElem.setAttribute( "inverted", mInverted ); - overviewFrameElem.setAttribute( "centered", mCentered ); + overviewFrameElem.setAttribute( QStringLiteral( "frameMap" ), mFrameMapId ); + overviewFrameElem.setAttribute( QStringLiteral( "blendMode" ), QgsPainting::getBlendModeEnum( mBlendMode ) ); + overviewFrameElem.setAttribute( QStringLiteral( "inverted" ), mInverted ); + overviewFrameElem.setAttribute( QStringLiteral( "centered" ), mCentered ); QDomElement frameStyleElem = QgsSymbolLayerUtils::saveSymbol( QString(), mFrameSymbol, doc ); overviewFrameElem.appendChild( frameStyleElem ); @@ -183,12 +183,12 @@ bool QgsComposerMapOverview::readXml( const QDomElement &itemElem, const QDomDoc bool ok = QgsComposerMapItem::readXml( itemElem, doc ); - setFrameMap( itemElem.attribute( "frameMap", "-1" ).toInt() ); - mBlendMode = QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( "blendMode", "0" ).toUInt() ) ); - mInverted = ( itemElem.attribute( "inverted", "0" ) != "0" ); - mCentered = ( itemElem.attribute( "centered", "0" ) != "0" ); + setFrameMap( itemElem.attribute( QStringLiteral( "frameMap" ), QStringLiteral( "-1" ) ).toInt() ); + mBlendMode = QgsPainting::getCompositionMode( static_cast< QgsPainting::BlendMode >( itemElem.attribute( QStringLiteral( "blendMode" ), QStringLiteral( "0" ) ).toUInt() ) ); + mInverted = ( itemElem.attribute( QStringLiteral( "inverted" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); + mCentered = ( itemElem.attribute( QStringLiteral( "centered" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); - QDomElement frameStyleElem = itemElem.firstChildElement( "symbol" ); + QDomElement frameStyleElem = itemElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !frameStyleElem.isNull() ) { delete mFrameSymbol; @@ -384,11 +384,11 @@ bool QgsComposerMapOverviewStack::readXml( const QDomElement &elem, const QDomDo removeItems(); //read overview stack - QDomNodeList mapOverviewNodeList = elem.elementsByTagName( "ComposerMapOverview" ); + QDomNodeList mapOverviewNodeList = elem.elementsByTagName( QStringLiteral( "ComposerMapOverview" ) ); for ( int i = 0; i < mapOverviewNodeList.size(); ++i ) { QDomElement mapOverviewElem = mapOverviewNodeList.at( i ).toElement(); - QgsComposerMapOverview* mapOverview = new QgsComposerMapOverview( mapOverviewElem.attribute( "name" ), mComposerMap ); + QgsComposerMapOverview* mapOverview = new QgsComposerMapOverview( mapOverviewElem.attribute( QStringLiteral( "name" ) ), mComposerMap ); mapOverview->readXml( mapOverviewElem, doc ); mItems.append( mapOverview ); } diff --git a/src/core/composer/qgscomposermodel.cpp b/src/core/composer/qgscomposermodel.cpp index 9d051ed91bea..53abef4ed089 100644 --- a/src/core/composer/qgscomposermodel.cpp +++ b/src/core/composer/qgscomposermodel.cpp @@ -230,10 +230,10 @@ QVariant QgsComposerModel::headerData( int section, Qt::Orientation orientation, { static QIcon lockIcon; if ( lockIcon.isNull() ) - lockIcon = QgsApplication::getThemeIcon( "/locked.svg" ); + lockIcon = QgsApplication::getThemeIcon( QStringLiteral( "/locked.svg" ) ); static QIcon showIcon; if ( showIcon.isNull() ) - showIcon = QgsApplication::getThemeIcon( "/mActionShowAllLayers.svg" ); + showIcon = QgsApplication::getThemeIcon( QStringLiteral( "/mActionShowAllLayers.svg" ) ); switch ( role ) { @@ -277,7 +277,7 @@ Qt::DropActions QgsComposerModel::supportedDropActions() const QStringList QgsComposerModel::mimeTypes() const { QStringList types; - types << "application/x-vnd.qgis.qgis.composeritemid"; + types << QStringLiteral( "application/x-vnd.qgis.qgis.composeritemid" ); return types; } @@ -302,7 +302,7 @@ QMimeData* QgsComposerModel::mimeData( const QModelIndexList &indexes ) const } } - mimeData->setData( "application/x-vnd.qgis.qgis.composeritemid", encodedData ); + mimeData->setData( QStringLiteral( "application/x-vnd.qgis.qgis.composeritemid" ), encodedData ); return mimeData; } @@ -324,7 +324,7 @@ bool QgsComposerModel::dropMimeData( const QMimeData *data, return true; } - if ( !data->hasFormat( "application/x-vnd.qgis.qgis.composeritemid" ) ) + if ( !data->hasFormat( QStringLiteral( "application/x-vnd.qgis.qgis.composeritemid" ) ) ) { return false; } @@ -336,7 +336,7 @@ bool QgsComposerModel::dropMimeData( const QMimeData *data, int beginRow = row != -1 ? row : rowCount( QModelIndex() ); - QByteArray encodedData = data->data( "application/x-vnd.qgis.qgis.composeritemid" ); + QByteArray encodedData = data->data( QStringLiteral( "application/x-vnd.qgis.qgis.composeritemid" ) ); QDataStream stream( &encodedData, QIODevice::ReadOnly ); QList droppedItems; int rows = 0; diff --git a/src/core/composer/qgscomposermousehandles.cpp b/src/core/composer/qgscomposermousehandles.cpp index acc5573ab357..722a9cc58114 100644 --- a/src/core/composer/qgscomposermousehandles.cpp +++ b/src/core/composer/qgscomposermousehandles.cpp @@ -623,7 +623,7 @@ void QgsComposerMouseHandles::mouseReleaseEvent( QGraphicsSceneMouseEvent* event //don't move locked items continue; } - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *itemIter )->move( mEndHandleMovePos.x() - mBeginHandlePos.x(), mEndHandleMovePos.y() - mBeginHandlePos.y() ); subcommand->saveAfterState(); @@ -646,7 +646,7 @@ void QgsComposerMouseHandles::mouseReleaseEvent( QGraphicsSceneMouseEvent* event //don't resize locked items or unselectable items (eg, items which make up an item group) continue; } - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); QRectF itemRect; diff --git a/src/core/composer/qgscomposermultiframe.cpp b/src/core/composer/qgscomposermultiframe.cpp index 38aa2a08942a..6ac757556698 100644 --- a/src/core/composer/qgscomposermultiframe.cpp +++ b/src/core/composer/qgscomposermultiframe.cpp @@ -342,7 +342,7 @@ int QgsComposerMultiFrame::frameIndex( QgsComposerFrame *frame ) const bool QgsComposerMultiFrame::_writeXml( QDomElement& elem, QDomDocument& doc, bool ignoreFrames ) const { - elem.setAttribute( "resizeMode", mResizeMode ); + elem.setAttribute( QStringLiteral( "resizeMode" ), mResizeMode ); if ( !ignoreFrames ) { QList::const_iterator frameIt = mFrameItems.constBegin(); @@ -359,10 +359,10 @@ bool QgsComposerMultiFrame::_readXml( const QDomElement& itemElem, const QDomDoc { QgsComposerObject::readXml( itemElem, doc ); - mResizeMode = static_cast< ResizeMode >( itemElem.attribute( "resizeMode", "0" ).toInt() ); + mResizeMode = static_cast< ResizeMode >( itemElem.attribute( QStringLiteral( "resizeMode" ), QStringLiteral( "0" ) ).toInt() ); if ( !ignoreFrames ) { - QDomNodeList frameList = itemElem.elementsByTagName( "ComposerFrame" ); + QDomNodeList frameList = itemElem.elementsByTagName( QStringLiteral( "ComposerFrame" ) ); for ( int i = 0; i < frameList.size(); ++i ) { QDomElement frameElem = frameList.at( i ).toElement(); diff --git a/src/core/composer/qgscomposermultiframecommand.cpp b/src/core/composer/qgscomposermultiframecommand.cpp index 220789aa8688..3e423e3c84e8 100644 --- a/src/core/composer/qgscomposermultiframecommand.cpp +++ b/src/core/composer/qgscomposermultiframecommand.cpp @@ -24,7 +24,7 @@ QgsComposerMultiFrameCommand::QgsComposerMultiFrameCommand( QgsComposerMultiFram { } -QgsComposerMultiFrameCommand::QgsComposerMultiFrameCommand(): QUndoCommand( "", nullptr ), mMultiFrame( nullptr ), mFirstRun( false ) +QgsComposerMultiFrameCommand::QgsComposerMultiFrameCommand(): QUndoCommand( QLatin1String( "" ), nullptr ), mMultiFrame( nullptr ), mFirstRun( false ) { } @@ -61,7 +61,7 @@ void QgsComposerMultiFrameCommand::saveState( QDomDocument& stateDoc ) if ( mMultiFrame ) { stateDoc.clear(); - QDomElement documentElement = stateDoc.createElement( "ComposerMultiFrameState" ); + QDomElement documentElement = stateDoc.createElement( QStringLiteral( "ComposerMultiFrameState" ) ); mMultiFrame->writeXml( documentElement, stateDoc ); stateDoc.appendChild( documentElement ); } diff --git a/src/core/composer/qgscomposernodesitem.cpp b/src/core/composer/qgscomposernodesitem.cpp index bc175e85583d..7b6704b1e40e 100644 --- a/src/core/composer/qgscomposernodesitem.cpp +++ b/src/core/composer/qgscomposernodesitem.cpp @@ -133,8 +133,8 @@ void QgsComposerNodesItem::drawNodes( QPainter *painter ) const double rectSize = 3.0 / horizontalViewScaleFactor(); QgsStringMap properties; - properties.insert( "name", "cross" ); - properties.insert( "color_border", "red" ); + properties.insert( QStringLiteral( "name" ), QStringLiteral( "cross" ) ); + properties.insert( QStringLiteral( "color_border" ), QStringLiteral( "red" ) ); QScopedPointer symbol; symbol.reset( QgsMarkerSymbol::createSimple( properties ) ); @@ -167,10 +167,10 @@ void QgsComposerNodesItem::drawSelectedNode( QPainter *painter ) const double rectSize = 3.0 / horizontalViewScaleFactor(); QgsStringMap properties; - properties.insert( "name", "square" ); - properties.insert( "color", "0, 0, 0, 0" ); - properties.insert( "color_border", "blue" ); - properties.insert( "width_border", "4" ); + properties.insert( QStringLiteral( "name" ), QStringLiteral( "square" ) ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0, 0, 0, 0" ) ); + properties.insert( QStringLiteral( "color_border" ), QStringLiteral( "blue" ) ); + properties.insert( QStringLiteral( "width_border" ), QStringLiteral( "4" ) ); QScopedPointer symbol; symbol.reset( QgsMarkerSymbol::createSimple( properties ) ); @@ -280,31 +280,31 @@ bool QgsComposerNodesItem::readXml( const QDomElement& itemElem, const QDomDocument& doc ) { // restore general composer item properties - const QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + const QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); - if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) ) - setItemRotation( composerItemElem.attribute( "rotation", "0" ).toDouble() ); + if ( !qgsDoubleNear( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) + setItemRotation( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble() ); _readXml( composerItemElem, doc ); } // restore style - QDomElement styleSymbolElem = itemElem.firstChildElement( "symbol" ); + QDomElement styleSymbolElem = itemElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !styleSymbolElem.isNull() ) _readXmlStyle( styleSymbolElem ); // restore nodes mPolygon.clear(); - QDomNodeList nodesList = itemElem.elementsByTagName( "node" ); + QDomNodeList nodesList = itemElem.elementsByTagName( QStringLiteral( "node" ) ); for ( int i = 0; i < nodesList.size(); i++ ) { QDomElement nodeElem = nodesList.at( i ).toElement(); QPointF newPt; - newPt.setX( nodeElem.attribute( "x" ).toDouble() ); - newPt.setY( nodeElem.attribute( "y" ).toDouble() ); + newPt.setX( nodeElem.attribute( QStringLiteral( "x" ) ).toDouble() ); + newPt.setY( nodeElem.attribute( QStringLiteral( "y" ) ).toDouble() ); mPolygon.append( newPt ); } @@ -365,12 +365,12 @@ bool QgsComposerNodesItem::writeXml( QDomElement& elem, QDomDocument & doc ) con _writeXmlStyle( doc, composerPolygonElem ); // write nodes - QDomElement nodesElem = doc.createElement( "nodes" ); + QDomElement nodesElem = doc.createElement( QStringLiteral( "nodes" ) ); Q_FOREACH ( QPointF pt, mPolygon ) { - QDomElement nodeElem = doc.createElement( "node" ); - nodeElem.setAttribute( "x", QString::number( pt.x() ) ); - nodeElem.setAttribute( "y", QString::number( pt.y() ) ); + QDomElement nodeElem = doc.createElement( QStringLiteral( "node" ) ); + nodeElem.setAttribute( QStringLiteral( "x" ), QString::number( pt.x() ) ); + nodeElem.setAttribute( QStringLiteral( "y" ), QString::number( pt.y() ) ); nodesElem.appendChild( nodeElem ); } composerPolygonElem.appendChild( nodesElem ); diff --git a/src/core/composer/qgscomposerobject.cpp b/src/core/composer/qgscomposerobject.cpp index 9acdd1da4eca..b0bd75cf010e 100644 --- a/src/core/composer/qgscomposerobject.cpp +++ b/src/core/composer/qgscomposerobject.cpp @@ -28,7 +28,7 @@ QgsComposerObject::QgsComposerObject( QgsComposition* composition ) { // data defined strings - mDataDefinedNames.insert( QgsComposerObject::TestProperty, QString( "dataDefinedTestProperty" ) ); + mDataDefinedNames.insert( QgsComposerObject::TestProperty, QStringLiteral( "dataDefinedTestProperty" ) ); if ( mComposition ) { diff --git a/src/core/composer/qgscomposerpicture.cpp b/src/core/composer/qgscomposerpicture.cpp index b3824efb31f2..5600e6805270 100644 --- a/src/core/composer/qgscomposerpicture.cpp +++ b/src/core/composer/qgscomposerpicture.cpp @@ -87,7 +87,7 @@ void QgsComposerPicture::init() setBackgroundEnabled( false ); //data defined strings - mDataDefinedNames.insert( QgsComposerObject::PictureSource, QString( "dataDefinedSource" ) ); + mDataDefinedNames.insert( QgsComposerObject::PictureSource, QStringLiteral( "dataDefinedSource" ) ); //connect some signals @@ -374,7 +374,7 @@ void QgsComposerPicture::loadLocalPicture( const QString &path ) { QFileInfo sourceFileInfo( pic ); QString sourceFileSuffix = sourceFileInfo.suffix(); - if ( sourceFileSuffix.compare( "svg", Qt::CaseInsensitive ) == 0 ) + if ( sourceFileSuffix.compare( QLatin1String( "svg" ), Qt::CaseInsensitive ) == 0 ) { //try to open svg const QByteArray &svgContent = QgsSvgCache::instance()->svgContent( pic.fileName(), rect().width(), mSvgFillColor, mSvgBorderColor, mSvgBorderWidth, @@ -453,7 +453,7 @@ void QgsComposerPicture::updateMapRotation() void QgsComposerPicture::loadPicture( const QString &path ) { - if ( path.startsWith( "http" ) ) + if ( path.startsWith( QLatin1String( "http" ) ) ) { //remote location loadRemotePicture( path ); @@ -471,7 +471,7 @@ void QgsComposerPicture::loadPicture( const QString &path ) { //trying to load an invalid file or bad expression, show cross picture mMode = SVG; - QString badFile( ":/images/composer/missing_image.svg" ); + QString badFile( QStringLiteral( ":/images/composer/missing_image.svg" ) ); mSVG.load( badFile ); if ( mSVG.isValid() ) { @@ -748,28 +748,28 @@ bool QgsComposerPicture::writeXml( QDomElement& elem, QDomDocument & doc ) const { return false; } - QDomElement composerPictureElem = doc.createElement( "ComposerPicture" ); - composerPictureElem.setAttribute( "file", QgsProject::instance()->writePath( mSourcePath ) ); - composerPictureElem.setAttribute( "pictureWidth", QString::number( mPictureWidth ) ); - composerPictureElem.setAttribute( "pictureHeight", QString::number( mPictureHeight ) ); - composerPictureElem.setAttribute( "resizeMode", QString::number( static_cast< int >( mResizeMode ) ) ); - composerPictureElem.setAttribute( "anchorPoint", QString::number( static_cast< int >( mPictureAnchor ) ) ); - composerPictureElem.setAttribute( "svgFillColor", QgsSymbolLayerUtils::encodeColor( mSvgFillColor ) ); - composerPictureElem.setAttribute( "svgBorderColor", QgsSymbolLayerUtils::encodeColor( mSvgBorderColor ) ); - composerPictureElem.setAttribute( "svgBorderWidth", QString::number( mSvgBorderWidth ) ); + QDomElement composerPictureElem = doc.createElement( QStringLiteral( "ComposerPicture" ) ); + composerPictureElem.setAttribute( QStringLiteral( "file" ), QgsProject::instance()->writePath( mSourcePath ) ); + composerPictureElem.setAttribute( QStringLiteral( "pictureWidth" ), QString::number( mPictureWidth ) ); + composerPictureElem.setAttribute( QStringLiteral( "pictureHeight" ), QString::number( mPictureHeight ) ); + composerPictureElem.setAttribute( QStringLiteral( "resizeMode" ), QString::number( static_cast< int >( mResizeMode ) ) ); + composerPictureElem.setAttribute( QStringLiteral( "anchorPoint" ), QString::number( static_cast< int >( mPictureAnchor ) ) ); + composerPictureElem.setAttribute( QStringLiteral( "svgFillColor" ), QgsSymbolLayerUtils::encodeColor( mSvgFillColor ) ); + composerPictureElem.setAttribute( QStringLiteral( "svgBorderColor" ), QgsSymbolLayerUtils::encodeColor( mSvgBorderColor ) ); + composerPictureElem.setAttribute( QStringLiteral( "svgBorderWidth" ), QString::number( mSvgBorderWidth ) ); //rotation - composerPictureElem.setAttribute( "pictureRotation", QString::number( mPictureRotation ) ); + composerPictureElem.setAttribute( QStringLiteral( "pictureRotation" ), QString::number( mPictureRotation ) ); if ( !mRotationMap ) { - composerPictureElem.setAttribute( "mapId", -1 ); + composerPictureElem.setAttribute( QStringLiteral( "mapId" ), -1 ); } else { - composerPictureElem.setAttribute( "mapId", mRotationMap->id() ); + composerPictureElem.setAttribute( QStringLiteral( "mapId" ), mRotationMap->id() ); } - composerPictureElem.setAttribute( "northMode", mNorthMode ); - composerPictureElem.setAttribute( "northOffset", mNorthOffset ); + composerPictureElem.setAttribute( QStringLiteral( "northMode" ), mNorthMode ); + composerPictureElem.setAttribute( QStringLiteral( "northOffset" ), mNorthOffset ); _writeXml( composerPictureElem, doc ); elem.appendChild( composerPictureElem ); @@ -783,25 +783,25 @@ bool QgsComposerPicture::readXml( const QDomElement& itemElem, const QDomDocumen return false; } - mPictureWidth = itemElem.attribute( "pictureWidth", "10" ).toDouble(); - mPictureHeight = itemElem.attribute( "pictureHeight", "10" ).toDouble(); - mResizeMode = QgsComposerPicture::ResizeMode( itemElem.attribute( "resizeMode", "0" ).toInt() ); + mPictureWidth = itemElem.attribute( QStringLiteral( "pictureWidth" ), QStringLiteral( "10" ) ).toDouble(); + mPictureHeight = itemElem.attribute( QStringLiteral( "pictureHeight" ), QStringLiteral( "10" ) ).toDouble(); + mResizeMode = QgsComposerPicture::ResizeMode( itemElem.attribute( QStringLiteral( "resizeMode" ), QStringLiteral( "0" ) ).toInt() ); //when loading from xml, default to anchor point of middle to match pre 2.4 behaviour - mPictureAnchor = static_cast< QgsComposerItem::ItemPositionMode >( itemElem.attribute( "anchorPoint", QString::number( QgsComposerItem::Middle ) ).toInt() ); + mPictureAnchor = static_cast< QgsComposerItem::ItemPositionMode >( itemElem.attribute( QStringLiteral( "anchorPoint" ), QString::number( QgsComposerItem::Middle ) ).toInt() ); - mSvgFillColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "svgFillColor", QgsSymbolLayerUtils::encodeColor( QColor( 255, 255, 255 ) ) ) ); - mSvgBorderColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "svgBorderColor", QgsSymbolLayerUtils::encodeColor( QColor( 0, 0, 0 ) ) ) ); - mSvgBorderWidth = itemElem.attribute( "svgBorderWidth", "0.2" ).toDouble(); + mSvgFillColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "svgFillColor" ), QgsSymbolLayerUtils::encodeColor( QColor( 255, 255, 255 ) ) ) ); + mSvgBorderColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "svgBorderColor" ), QgsSymbolLayerUtils::encodeColor( QColor( 0, 0, 0 ) ) ) ); + mSvgBorderWidth = itemElem.attribute( QStringLiteral( "svgBorderWidth" ), QStringLiteral( "0.2" ) ).toDouble(); - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); - if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) ) + if ( !qgsDoubleNear( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { //in versions prior to 2.1 picture rotation was stored in the rotation attribute - mPictureRotation = composerItemElem.attribute( "rotation", "0" ).toDouble(); + mPictureRotation = composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(); } _readXml( composerItemElem, doc ); @@ -809,13 +809,13 @@ bool QgsComposerPicture::readXml( const QDomElement& itemElem, const QDomDocumen mDefaultSvgSize = QSize( 0, 0 ); - if ( itemElem.hasAttribute( "sourceExpression" ) ) + if ( itemElem.hasAttribute( QStringLiteral( "sourceExpression" ) ) ) { //update pre 2.5 picture expression to use data defined expression - QString sourceExpression = itemElem.attribute( "sourceExpression", "" ); - QString useExpression = itemElem.attribute( "useExpression" ); + QString sourceExpression = itemElem.attribute( QStringLiteral( "sourceExpression" ), QLatin1String( "" ) ); + QString useExpression = itemElem.attribute( QStringLiteral( "useExpression" ) ); bool expressionActive; - if ( useExpression.compare( "true", Qt::CaseInsensitive ) == 0 ) + if ( useExpression.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { expressionActive = true; } @@ -827,19 +827,19 @@ bool QgsComposerPicture::readXml( const QDomElement& itemElem, const QDomDocumen setDataDefinedProperty( QgsComposerObject::PictureSource, expressionActive, true, sourceExpression, QString() ); } - mSourcePath = QgsProject::instance()->readPath( itemElem.attribute( "file" ) ); + mSourcePath = QgsProject::instance()->readPath( itemElem.attribute( QStringLiteral( "file" ) ) ); //picture rotation - if ( !qgsDoubleNear( itemElem.attribute( "pictureRotation", "0" ).toDouble(), 0.0 ) ) + if ( !qgsDoubleNear( itemElem.attribute( QStringLiteral( "pictureRotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { - mPictureRotation = itemElem.attribute( "pictureRotation", "0" ).toDouble(); + mPictureRotation = itemElem.attribute( QStringLiteral( "pictureRotation" ), QStringLiteral( "0" ) ).toDouble(); } //rotation map - mNorthMode = static_cast< NorthMode >( itemElem.attribute( "northMode", "0" ).toInt() ); - mNorthOffset = itemElem.attribute( "northOffset", "0" ).toDouble(); + mNorthMode = static_cast< NorthMode >( itemElem.attribute( QStringLiteral( "northMode" ), QStringLiteral( "0" ) ).toInt() ); + mNorthOffset = itemElem.attribute( QStringLiteral( "northOffset" ), QStringLiteral( "0" ) ).toDouble(); - int rotationMapId = itemElem.attribute( "mapId", "-1" ).toInt(); + int rotationMapId = itemElem.attribute( QStringLiteral( "mapId" ), QStringLiteral( "-1" ) ).toInt(); if ( rotationMapId == -1 ) { mRotationMap = nullptr; diff --git a/src/core/composer/qgscomposerpolygon.cpp b/src/core/composer/qgscomposerpolygon.cpp index c0f87faafba0..88dd30a36e7c 100644 --- a/src/core/composer/qgscomposerpolygon.cpp +++ b/src/core/composer/qgscomposerpolygon.cpp @@ -23,14 +23,14 @@ #include QgsComposerPolygon::QgsComposerPolygon( QgsComposition* c ) - : QgsComposerNodesItem( "ComposerPolygon", c ) + : QgsComposerNodesItem( QStringLiteral( "ComposerPolygon" ), c ) , mPolygonStyleSymbol( nullptr ) { createDefaultPolygonStyleSymbol(); } QgsComposerPolygon::QgsComposerPolygon( const QPolygonF& polygon, QgsComposition* c ) - : QgsComposerNodesItem( "ComposerPolygon", polygon, c ) + : QgsComposerNodesItem( QStringLiteral( "ComposerPolygon" ), polygon, c ) , mPolygonStyleSymbol( nullptr ) { createDefaultPolygonStyleSymbol(); @@ -52,12 +52,12 @@ bool QgsComposerPolygon::_addNode( const int indexPoint, void QgsComposerPolygon::createDefaultPolygonStyleSymbol() { QgsStringMap properties; - properties.insert( "color", "white" ); - properties.insert( "style", "solid" ); - properties.insert( "style_border", "solid" ); - properties.insert( "color_border", "black" ); - properties.insert( "width_border", "0.3" ); - properties.insert( "joinstyle", "miter" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "white" ) ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "solid" ) ); + properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "solid" ) ); + properties.insert( QStringLiteral( "color_border" ), QStringLiteral( "black" ) ); + properties.insert( QStringLiteral( "width_border" ), QStringLiteral( "0.3" ) ); + properties.insert( QStringLiteral( "joinstyle" ), QStringLiteral( "miter" ) ); mPolygonStyleSymbol.reset( QgsFillSymbol::createSimple( properties ) ); diff --git a/src/core/composer/qgscomposerpolyline.cpp b/src/core/composer/qgscomposerpolyline.cpp index 21491d1a9077..02005bc6ec48 100644 --- a/src/core/composer/qgscomposerpolyline.cpp +++ b/src/core/composer/qgscomposerpolyline.cpp @@ -23,14 +23,14 @@ #include QgsComposerPolyline::QgsComposerPolyline( QgsComposition* c ) - : QgsComposerNodesItem( "ComposerPolyline", c ) + : QgsComposerNodesItem( QStringLiteral( "ComposerPolyline" ), c ) , mPolylineStyleSymbol( nullptr ) { createDefaultPolylineStyleSymbol(); } QgsComposerPolyline::QgsComposerPolyline( const QPolygonF& polyline, QgsComposition* c ) - : QgsComposerNodesItem( "ComposerPolyline", polyline, c ) + : QgsComposerNodesItem( QStringLiteral( "ComposerPolyline" ), polyline, c ) , mPolylineStyleSymbol( nullptr ) { createDefaultPolylineStyleSymbol(); @@ -83,9 +83,9 @@ bool QgsComposerPolyline::_removeNode( const int index ) void QgsComposerPolyline::createDefaultPolylineStyleSymbol() { QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "width", "0.3" ); - properties.insert( "capstyle", "square" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "width" ), QStringLiteral( "0.3" ) ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "square" ) ); mPolylineStyleSymbol.reset( QgsLineSymbol::createSimple( properties ) ); diff --git a/src/core/composer/qgscomposerscalebar.cpp b/src/core/composer/qgscomposerscalebar.cpp index a84fa4398031..f4507eb7dde0 100644 --- a/src/core/composer/qgscomposerscalebar.cpp +++ b/src/core/composer/qgscomposerscalebar.cpp @@ -398,7 +398,7 @@ void QgsComposerScaleBar::applyDefaultSettings() //get default composer font from settings QSettings settings; - QString defaultFontString = settings.value( "/Composer/defaultFont" ).toString(); + QString defaultFontString = settings.value( QStringLiteral( "/Composer/defaultFont" ) ).toString(); if ( !defaultFontString.isEmpty() ) { mFont.setFamily( defaultFontString ); @@ -545,7 +545,7 @@ void QgsComposerScaleBar::setSceneRect( const QRectF& rectangle ) void QgsComposerScaleBar::update() { //Don't adjust box size for numeric scale bars: - if ( mStyle && mStyle->name() != "Numeric" ) + if ( mStyle && mStyle->name() != QLatin1String( "Numeric" ) ) { adjustBoxSize(); } @@ -593,32 +593,32 @@ void QgsComposerScaleBar::setStyle( const QString& styleName ) mStyle = nullptr; //switch depending on style name - if ( styleName == "Single Box" ) + if ( styleName == QLatin1String( "Single Box" ) ) { mStyle = new QgsSingleBoxScaleBarStyle( this ); } - else if ( styleName == "Double Box" ) + else if ( styleName == QLatin1String( "Double Box" ) ) { mStyle = new QgsDoubleBoxScaleBarStyle( this ); } - else if ( styleName == "Line Ticks Middle" || styleName == "Line Ticks Down" || styleName == "Line Ticks Up" ) + else if ( styleName == QLatin1String( "Line Ticks Middle" ) || styleName == QLatin1String( "Line Ticks Down" ) || styleName == QLatin1String( "Line Ticks Up" ) ) { QgsTicksScaleBarStyle* tickStyle = new QgsTicksScaleBarStyle( this ); - if ( styleName == "Line Ticks Middle" ) + if ( styleName == QLatin1String( "Line Ticks Middle" ) ) { tickStyle->setTickPosition( QgsTicksScaleBarStyle::TicksMiddle ); } - else if ( styleName == "Line Ticks Down" ) + else if ( styleName == QLatin1String( "Line Ticks Down" ) ) { tickStyle->setTickPosition( QgsTicksScaleBarStyle::TicksDown ); } - else if ( styleName == "Line Ticks Up" ) + else if ( styleName == QLatin1String( "Line Ticks Up" ) ) { tickStyle->setTickPosition( QgsTicksScaleBarStyle::TicksUp ); } mStyle = tickStyle; } - else if ( styleName == "Numeric" ) + else if ( styleName == QLatin1String( "Numeric" ) ) { mStyle = new QgsNumericScaleBarStyle( this ); } @@ -633,7 +633,7 @@ QString QgsComposerScaleBar::style() const } else { - return ""; + return QLatin1String( "" ); } } @@ -645,7 +645,7 @@ QString QgsComposerScaleBar::firstLabelString() const } else { - return "0"; + return QStringLiteral( "0" ); } } @@ -668,76 +668,76 @@ bool QgsComposerScaleBar::writeXml( QDomElement& elem, QDomDocument & doc ) cons return false; } - QDomElement composerScaleBarElem = doc.createElement( "ComposerScaleBar" ); - composerScaleBarElem.setAttribute( "height", QString::number( mHeight ) ); - composerScaleBarElem.setAttribute( "labelBarSpace", QString::number( mLabelBarSpace ) ); - composerScaleBarElem.setAttribute( "boxContentSpace", QString::number( mBoxContentSpace ) ); - composerScaleBarElem.setAttribute( "numSegments", mNumSegments ); - composerScaleBarElem.setAttribute( "numSegmentsLeft", mNumSegmentsLeft ); - composerScaleBarElem.setAttribute( "numUnitsPerSegment", QString::number( mNumUnitsPerSegment ) ); - composerScaleBarElem.setAttribute( "segmentSizeMode", mSegmentSizeMode ); - composerScaleBarElem.setAttribute( "minBarWidth", mMinBarWidth ); - composerScaleBarElem.setAttribute( "maxBarWidth", mMaxBarWidth ); - composerScaleBarElem.setAttribute( "segmentMillimeters", QString::number( mSegmentMillimeters ) ); - composerScaleBarElem.setAttribute( "numMapUnitsPerScaleBarUnit", QString::number( mNumMapUnitsPerScaleBarUnit ) ); - composerScaleBarElem.appendChild( QgsFontUtils::toXmlElement( mFont, doc, "scaleBarFont" ) ); - composerScaleBarElem.setAttribute( "outlineWidth", QString::number( mPen.widthF() ) ); - composerScaleBarElem.setAttribute( "unitLabel", mUnitLabeling ); - composerScaleBarElem.setAttribute( "units", mUnits ); - composerScaleBarElem.setAttribute( "lineJoinStyle", QgsSymbolLayerUtils::encodePenJoinStyle( mLineJoinStyle ) ); - composerScaleBarElem.setAttribute( "lineCapStyle", QgsSymbolLayerUtils::encodePenCapStyle( mLineCapStyle ) ); + QDomElement composerScaleBarElem = doc.createElement( QStringLiteral( "ComposerScaleBar" ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "height" ), QString::number( mHeight ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "labelBarSpace" ), QString::number( mLabelBarSpace ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "boxContentSpace" ), QString::number( mBoxContentSpace ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "numSegments" ), mNumSegments ); + composerScaleBarElem.setAttribute( QStringLiteral( "numSegmentsLeft" ), mNumSegmentsLeft ); + composerScaleBarElem.setAttribute( QStringLiteral( "numUnitsPerSegment" ), QString::number( mNumUnitsPerSegment ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "segmentSizeMode" ), mSegmentSizeMode ); + composerScaleBarElem.setAttribute( QStringLiteral( "minBarWidth" ), mMinBarWidth ); + composerScaleBarElem.setAttribute( QStringLiteral( "maxBarWidth" ), mMaxBarWidth ); + composerScaleBarElem.setAttribute( QStringLiteral( "segmentMillimeters" ), QString::number( mSegmentMillimeters ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "numMapUnitsPerScaleBarUnit" ), QString::number( mNumMapUnitsPerScaleBarUnit ) ); + composerScaleBarElem.appendChild( QgsFontUtils::toXmlElement( mFont, doc, QStringLiteral( "scaleBarFont" ) ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "outlineWidth" ), QString::number( mPen.widthF() ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "unitLabel" ), mUnitLabeling ); + composerScaleBarElem.setAttribute( QStringLiteral( "units" ), mUnits ); + composerScaleBarElem.setAttribute( QStringLiteral( "lineJoinStyle" ), QgsSymbolLayerUtils::encodePenJoinStyle( mLineJoinStyle ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "lineCapStyle" ), QgsSymbolLayerUtils::encodePenCapStyle( mLineCapStyle ) ); //style if ( mStyle ) { - composerScaleBarElem.setAttribute( "style", mStyle->name() ); + composerScaleBarElem.setAttribute( QStringLiteral( "style" ), mStyle->name() ); } //map id if ( mComposerMap ) { - composerScaleBarElem.setAttribute( "mapId", mComposerMap->id() ); + composerScaleBarElem.setAttribute( QStringLiteral( "mapId" ), mComposerMap->id() ); } //colors //fill color - QDomElement fillColorElem = doc.createElement( "fillColor" ); + QDomElement fillColorElem = doc.createElement( QStringLiteral( "fillColor" ) ); QColor fillColor = mBrush.color(); - fillColorElem.setAttribute( "red", QString::number( fillColor.red() ) ); - fillColorElem.setAttribute( "green", QString::number( fillColor.green() ) ); - fillColorElem.setAttribute( "blue", QString::number( fillColor.blue() ) ); - fillColorElem.setAttribute( "alpha", QString::number( fillColor.alpha() ) ); + fillColorElem.setAttribute( QStringLiteral( "red" ), QString::number( fillColor.red() ) ); + fillColorElem.setAttribute( QStringLiteral( "green" ), QString::number( fillColor.green() ) ); + fillColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( fillColor.blue() ) ); + fillColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( fillColor.alpha() ) ); composerScaleBarElem.appendChild( fillColorElem ); //fill color 2 - QDomElement fillColor2Elem = doc.createElement( "fillColor2" ); + QDomElement fillColor2Elem = doc.createElement( QStringLiteral( "fillColor2" ) ); QColor fillColor2 = mBrush2.color(); - fillColor2Elem.setAttribute( "red", QString::number( fillColor2.red() ) ); - fillColor2Elem.setAttribute( "green", QString::number( fillColor2.green() ) ); - fillColor2Elem.setAttribute( "blue", QString::number( fillColor2.blue() ) ); - fillColor2Elem.setAttribute( "alpha", QString::number( fillColor2.alpha() ) ); + fillColor2Elem.setAttribute( QStringLiteral( "red" ), QString::number( fillColor2.red() ) ); + fillColor2Elem.setAttribute( QStringLiteral( "green" ), QString::number( fillColor2.green() ) ); + fillColor2Elem.setAttribute( QStringLiteral( "blue" ), QString::number( fillColor2.blue() ) ); + fillColor2Elem.setAttribute( QStringLiteral( "alpha" ), QString::number( fillColor2.alpha() ) ); composerScaleBarElem.appendChild( fillColor2Elem ); //pen color - QDomElement strokeColorElem = doc.createElement( "strokeColor" ); + QDomElement strokeColorElem = doc.createElement( QStringLiteral( "strokeColor" ) ); QColor strokeColor = mPen.color(); - strokeColorElem.setAttribute( "red", QString::number( strokeColor.red() ) ); - strokeColorElem.setAttribute( "green", QString::number( strokeColor.green() ) ); - strokeColorElem.setAttribute( "blue", QString::number( strokeColor.blue() ) ); - strokeColorElem.setAttribute( "alpha", QString::number( strokeColor.alpha() ) ); + strokeColorElem.setAttribute( QStringLiteral( "red" ), QString::number( strokeColor.red() ) ); + strokeColorElem.setAttribute( QStringLiteral( "green" ), QString::number( strokeColor.green() ) ); + strokeColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( strokeColor.blue() ) ); + strokeColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( strokeColor.alpha() ) ); composerScaleBarElem.appendChild( strokeColorElem ); //font color - QDomElement fontColorElem = doc.createElement( "textColor" ); - fontColorElem.setAttribute( "red", QString::number( mFontColor.red() ) ); - fontColorElem.setAttribute( "green", QString::number( mFontColor.green() ) ); - fontColorElem.setAttribute( "blue", QString::number( mFontColor.blue() ) ); - fontColorElem.setAttribute( "alpha", QString::number( mFontColor.alpha() ) ); + QDomElement fontColorElem = doc.createElement( QStringLiteral( "textColor" ) ); + fontColorElem.setAttribute( QStringLiteral( "red" ), QString::number( mFontColor.red() ) ); + fontColorElem.setAttribute( QStringLiteral( "green" ), QString::number( mFontColor.green() ) ); + fontColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( mFontColor.blue() ) ); + fontColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( mFontColor.alpha() ) ); composerScaleBarElem.appendChild( fontColorElem ); //alignment - composerScaleBarElem.setAttribute( "alignment", QString::number( static_cast< int >( mAlignment ) ) ); + composerScaleBarElem.setAttribute( QStringLiteral( "alignment" ), QString::number( static_cast< int >( mAlignment ) ) ); elem.appendChild( composerScaleBarElem ); return _writeXml( composerScaleBarElem, doc ); @@ -750,41 +750,41 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume return false; } - mHeight = itemElem.attribute( "height", "5.0" ).toDouble(); - mLabelBarSpace = itemElem.attribute( "labelBarSpace", "3.0" ).toDouble(); - mBoxContentSpace = itemElem.attribute( "boxContentSpace", "1.0" ).toDouble(); - mNumSegments = itemElem.attribute( "numSegments", "2" ).toInt(); - mNumSegmentsLeft = itemElem.attribute( "numSegmentsLeft", "0" ).toInt(); - mNumUnitsPerSegment = itemElem.attribute( "numUnitsPerSegment", "1.0" ).toDouble(); - mSegmentSizeMode = static_cast( itemElem.attribute( "segmentSizeMode", "0" ).toInt() ); - mMinBarWidth = itemElem.attribute( "minBarWidth", "50" ).toInt(); - mMaxBarWidth = itemElem.attribute( "maxBarWidth", "150" ).toInt(); - mSegmentMillimeters = itemElem.attribute( "segmentMillimeters", "0.0" ).toDouble(); - mNumMapUnitsPerScaleBarUnit = itemElem.attribute( "numMapUnitsPerScaleBarUnit", "1.0" ).toDouble(); - mPen.setWidthF( itemElem.attribute( "outlineWidth", "0.3" ).toDouble() ); - mUnitLabeling = itemElem.attribute( "unitLabel" ); - mLineJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( "lineJoinStyle", "miter" ) ); + mHeight = itemElem.attribute( QStringLiteral( "height" ), QStringLiteral( "5.0" ) ).toDouble(); + mLabelBarSpace = itemElem.attribute( QStringLiteral( "labelBarSpace" ), QStringLiteral( "3.0" ) ).toDouble(); + mBoxContentSpace = itemElem.attribute( QStringLiteral( "boxContentSpace" ), QStringLiteral( "1.0" ) ).toDouble(); + mNumSegments = itemElem.attribute( QStringLiteral( "numSegments" ), QStringLiteral( "2" ) ).toInt(); + mNumSegmentsLeft = itemElem.attribute( QStringLiteral( "numSegmentsLeft" ), QStringLiteral( "0" ) ).toInt(); + mNumUnitsPerSegment = itemElem.attribute( QStringLiteral( "numUnitsPerSegment" ), QStringLiteral( "1.0" ) ).toDouble(); + mSegmentSizeMode = static_cast( itemElem.attribute( QStringLiteral( "segmentSizeMode" ), QStringLiteral( "0" ) ).toInt() ); + mMinBarWidth = itemElem.attribute( QStringLiteral( "minBarWidth" ), QStringLiteral( "50" ) ).toInt(); + mMaxBarWidth = itemElem.attribute( QStringLiteral( "maxBarWidth" ), QStringLiteral( "150" ) ).toInt(); + mSegmentMillimeters = itemElem.attribute( QStringLiteral( "segmentMillimeters" ), QStringLiteral( "0.0" ) ).toDouble(); + mNumMapUnitsPerScaleBarUnit = itemElem.attribute( QStringLiteral( "numMapUnitsPerScaleBarUnit" ), QStringLiteral( "1.0" ) ).toDouble(); + mPen.setWidthF( itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "0.3" ) ).toDouble() ); + mUnitLabeling = itemElem.attribute( QStringLiteral( "unitLabel" ) ); + mLineJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( QStringLiteral( "lineJoinStyle" ), QStringLiteral( "miter" ) ) ); mPen.setJoinStyle( mLineJoinStyle ); - mLineCapStyle = QgsSymbolLayerUtils::decodePenCapStyle( itemElem.attribute( "lineCapStyle", "square" ) ); + mLineCapStyle = QgsSymbolLayerUtils::decodePenCapStyle( itemElem.attribute( QStringLiteral( "lineCapStyle" ), QStringLiteral( "square" ) ) ); mPen.setCapStyle( mLineCapStyle ); - if ( !QgsFontUtils::setFromXmlChildNode( mFont, itemElem, "scaleBarFont" ) ) + if ( !QgsFontUtils::setFromXmlChildNode( mFont, itemElem, QStringLiteral( "scaleBarFont" ) ) ) { - mFont.fromString( itemElem.attribute( "font", "" ) ); + mFont.fromString( itemElem.attribute( QStringLiteral( "font" ), QLatin1String( "" ) ) ); } //colors //fill color - QDomNodeList fillColorList = itemElem.elementsByTagName( "fillColor" ); + QDomNodeList fillColorList = itemElem.elementsByTagName( QStringLiteral( "fillColor" ) ); if ( !fillColorList.isEmpty() ) { QDomElement fillColorElem = fillColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; - fillRed = fillColorElem.attribute( "red" ).toDouble( &redOk ); - fillGreen = fillColorElem.attribute( "green" ).toDouble( &greenOk ); - fillBlue = fillColorElem.attribute( "blue" ).toDouble( &blueOk ); - fillAlpha = fillColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + fillRed = fillColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + fillGreen = fillColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + fillBlue = fillColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + fillAlpha = fillColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { @@ -793,21 +793,21 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume } else { - mBrush.setColor( QColor( itemElem.attribute( "brushColor", "#000000" ) ) ); + mBrush.setColor( QColor( itemElem.attribute( QStringLiteral( "brushColor" ), QStringLiteral( "#000000" ) ) ) ); } //fill color 2 - QDomNodeList fillColor2List = itemElem.elementsByTagName( "fillColor2" ); + QDomNodeList fillColor2List = itemElem.elementsByTagName( QStringLiteral( "fillColor2" ) ); if ( !fillColor2List.isEmpty() ) { QDomElement fillColor2Elem = fillColor2List.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; - fillRed = fillColor2Elem.attribute( "red" ).toDouble( &redOk ); - fillGreen = fillColor2Elem.attribute( "green" ).toDouble( &greenOk ); - fillBlue = fillColor2Elem.attribute( "blue" ).toDouble( &blueOk ); - fillAlpha = fillColor2Elem.attribute( "alpha" ).toDouble( &alphaOk ); + fillRed = fillColor2Elem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + fillGreen = fillColor2Elem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + fillBlue = fillColor2Elem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + fillAlpha = fillColor2Elem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { @@ -816,21 +816,21 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume } else { - mBrush2.setColor( QColor( itemElem.attribute( "brush2Color", "#ffffff" ) ) ); + mBrush2.setColor( QColor( itemElem.attribute( QStringLiteral( "brush2Color" ), QStringLiteral( "#ffffff" ) ) ) ); } //stroke color - QDomNodeList strokeColorList = itemElem.elementsByTagName( "strokeColor" ); + QDomNodeList strokeColorList = itemElem.elementsByTagName( QStringLiteral( "strokeColor" ) ); if ( !strokeColorList.isEmpty() ) { QDomElement strokeColorElem = strokeColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int strokeRed, strokeGreen, strokeBlue, strokeAlpha; - strokeRed = strokeColorElem.attribute( "red" ).toDouble( &redOk ); - strokeGreen = strokeColorElem.attribute( "green" ).toDouble( &greenOk ); - strokeBlue = strokeColorElem.attribute( "blue" ).toDouble( &blueOk ); - strokeAlpha = strokeColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + strokeRed = strokeColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + strokeGreen = strokeColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + strokeBlue = strokeColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + strokeAlpha = strokeColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { @@ -839,21 +839,21 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume } else { - mPen.setColor( QColor( itemElem.attribute( "penColor", "#000000" ) ) ); + mPen.setColor( QColor( itemElem.attribute( QStringLiteral( "penColor" ), QStringLiteral( "#000000" ) ) ) ); } //font color - QDomNodeList textColorList = itemElem.elementsByTagName( "textColor" ); + QDomNodeList textColorList = itemElem.elementsByTagName( QStringLiteral( "textColor" ) ); if ( !textColorList.isEmpty() ) { QDomElement textColorElem = textColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int textRed, textGreen, textBlue, textAlpha; - textRed = textColorElem.attribute( "red" ).toDouble( &redOk ); - textGreen = textColorElem.attribute( "green" ).toDouble( &greenOk ); - textBlue = textColorElem.attribute( "blue" ).toDouble( &blueOk ); - textAlpha = textColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + textRed = textColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + textGreen = textColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + textBlue = textColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + textAlpha = textColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { @@ -862,20 +862,20 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume } else { - mFontColor.setNamedColor( itemElem.attribute( "fontColor", "#000000" ) ); + mFontColor.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) ); } //style delete mStyle; mStyle = nullptr; - QString styleString = itemElem.attribute( "style", "" ); + QString styleString = itemElem.attribute( QStringLiteral( "style" ), QLatin1String( "" ) ); setStyle( tr( styleString.toLocal8Bit().data() ) ); - mUnits = static_cast< ScaleBarUnits >( itemElem.attribute( "units" ).toInt() ); - mAlignment = static_cast< Alignment >( itemElem.attribute( "alignment", "0" ).toInt() ); + mUnits = static_cast< ScaleBarUnits >( itemElem.attribute( QStringLiteral( "units" ) ).toInt() ); + mAlignment = static_cast< Alignment >( itemElem.attribute( QStringLiteral( "alignment" ), QStringLiteral( "0" ) ).toInt() ); //map - int mapId = itemElem.attribute( "mapId", "-1" ).toInt(); + int mapId = itemElem.attribute( QStringLiteral( "mapId" ), QStringLiteral( "-1" ) ).toInt(); if ( mapId >= 0 ) { const QgsComposerMap* composerMap = mComposition->getComposerMapById( mapId ); @@ -890,7 +890,7 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume updateSegmentSize(); //restore general composer item properties - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); @@ -903,7 +903,7 @@ bool QgsComposerScaleBar::readXml( const QDomElement& itemElem, const QDomDocume void QgsComposerScaleBar::correctXPositionAlignment( double width, double widthAfter ) { //Don't adjust position for numeric scale bars: - if ( mStyle->name() == "Numeric" ) + if ( mStyle->name() == QLatin1String( "Numeric" ) ) { return; } diff --git a/src/core/composer/qgscomposershape.cpp b/src/core/composer/qgscomposershape.cpp index b6ad5de9bcab..1b5468e18c23 100644 --- a/src/core/composer/qgscomposershape.cpp +++ b/src/core/composer/qgscomposershape.cpp @@ -93,12 +93,12 @@ void QgsComposerShape::createDefaultShapeStyleSymbol() { delete mShapeStyleSymbol; QgsStringMap properties; - properties.insert( "color", "white" ); - properties.insert( "style", "solid" ); - properties.insert( "style_border", "solid" ); - properties.insert( "color_border", "black" ); - properties.insert( "width_border", "0.3" ); - properties.insert( "joinstyle", "miter" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "white" ) ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "solid" ) ); + properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "solid" ) ); + properties.insert( QStringLiteral( "color_border" ), QStringLiteral( "black" ) ); + properties.insert( QStringLiteral( "width_border" ), QStringLiteral( "0.3" ) ); + properties.insert( QStringLiteral( "joinstyle" ), QStringLiteral( "miter" ) ); mShapeStyleSymbol = QgsFillSymbol::createSimple( properties ); mMaxSymbolBleed = QgsSymbolLayerUtils::estimateMaxSymbolBleed( mShapeStyleSymbol ); @@ -273,9 +273,9 @@ double QgsComposerShape::estimatedFrameBleed() const bool QgsComposerShape::writeXml( QDomElement& elem, QDomDocument & doc ) const { - QDomElement composerShapeElem = doc.createElement( "ComposerShape" ); - composerShapeElem.setAttribute( "shapeType", mShape ); - composerShapeElem.setAttribute( "cornerRadius", mCornerRadius ); + QDomElement composerShapeElem = doc.createElement( QStringLiteral( "ComposerShape" ) ); + composerShapeElem.setAttribute( QStringLiteral( "shapeType" ), mShape ); + composerShapeElem.setAttribute( QStringLiteral( "cornerRadius" ), mCornerRadius ); QDomElement shapeStyleElem = QgsSymbolLayerUtils::saveSymbol( QString(), mShapeStyleSymbol, doc ); composerShapeElem.appendChild( shapeStyleElem ); @@ -286,26 +286,26 @@ bool QgsComposerShape::writeXml( QDomElement& elem, QDomDocument & doc ) const bool QgsComposerShape::readXml( const QDomElement& itemElem, const QDomDocument& doc ) { - mShape = QgsComposerShape::Shape( itemElem.attribute( "shapeType", "0" ).toInt() ); - mCornerRadius = itemElem.attribute( "cornerRadius", "0" ).toDouble(); + mShape = QgsComposerShape::Shape( itemElem.attribute( QStringLiteral( "shapeType" ), QStringLiteral( "0" ) ).toInt() ); + mCornerRadius = itemElem.attribute( QStringLiteral( "cornerRadius" ), QStringLiteral( "0" ) ).toDouble(); //restore general composer item properties - QDomNodeList composerItemList = itemElem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = itemElem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); if ( !composerItemList.isEmpty() ) { QDomElement composerItemElem = composerItemList.at( 0 ).toElement(); //rotation - if ( !qgsDoubleNear( composerItemElem.attribute( "rotation", "0" ).toDouble(), 0.0 ) ) + if ( !qgsDoubleNear( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble(), 0.0 ) ) { //check for old (pre 2.1) rotation attribute - setItemRotation( composerItemElem.attribute( "rotation", "0" ).toDouble() ); + setItemRotation( composerItemElem.attribute( QStringLiteral( "rotation" ), QStringLiteral( "0" ) ).toDouble() ); } _readXml( composerItemElem, doc ); } - QDomElement shapeStyleSymbolElem = itemElem.firstChildElement( "symbol" ); + QDomElement shapeStyleSymbolElem = itemElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !shapeStyleSymbolElem.isNull() ) { delete mShapeStyleSymbol; @@ -316,28 +316,28 @@ bool QgsComposerShape::readXml( const QDomElement& itemElem, const QDomDocument& //upgrade project file from 2.0 to use symbol styling delete mShapeStyleSymbol; QgsStringMap properties; - properties.insert( "color", QgsSymbolLayerUtils::encodeColor( brush().color() ) ); + properties.insert( QStringLiteral( "color" ), QgsSymbolLayerUtils::encodeColor( brush().color() ) ); if ( hasBackground() ) { - properties.insert( "style", "solid" ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "solid" ) ); } else { - properties.insert( "style", "no" ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "no" ) ); } if ( hasFrame() ) { - properties.insert( "style_border", "solid" ); + properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "solid" ) ); } else { - properties.insert( "style_border", "no" ); + properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "no" ) ); } - properties.insert( "color_border", QgsSymbolLayerUtils::encodeColor( pen().color() ) ); - properties.insert( "width_border", QString::number( pen().widthF() ) ); + properties.insert( QStringLiteral( "color_border" ), QgsSymbolLayerUtils::encodeColor( pen().color() ) ); + properties.insert( QStringLiteral( "width_border" ), QString::number( pen().widthF() ) ); //for pre 2.0 projects, shape color and outline were specified in a different element... - QDomNodeList outlineColorList = itemElem.elementsByTagName( "OutlineColor" ); + QDomNodeList outlineColorList = itemElem.elementsByTagName( QStringLiteral( "OutlineColor" ) ); if ( !outlineColorList.isEmpty() ) { QDomElement frameColorElem = outlineColorList.at( 0 ).toElement(); @@ -345,43 +345,43 @@ bool QgsComposerShape::readXml( const QDomElement& itemElem, const QDomDocument& int penRed, penGreen, penBlue, penAlpha; double penWidth; - penWidth = itemElem.attribute( "outlineWidth" ).toDouble( &widthOk ); - penRed = frameColorElem.attribute( "red" ).toDouble( &redOk ); - penGreen = frameColorElem.attribute( "green" ).toDouble( &greenOk ); - penBlue = frameColorElem.attribute( "blue" ).toDouble( &blueOk ); - penAlpha = frameColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + penWidth = itemElem.attribute( QStringLiteral( "outlineWidth" ) ).toDouble( &widthOk ); + penRed = frameColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + penGreen = frameColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + penBlue = frameColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + penAlpha = frameColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk && widthOk ) { - properties.insert( "color_border", QgsSymbolLayerUtils::encodeColor( QColor( penRed, penGreen, penBlue, penAlpha ) ) ); - properties.insert( "width_border", QString::number( penWidth ) ); + properties.insert( QStringLiteral( "color_border" ), QgsSymbolLayerUtils::encodeColor( QColor( penRed, penGreen, penBlue, penAlpha ) ) ); + properties.insert( QStringLiteral( "width_border" ), QString::number( penWidth ) ); } } - QDomNodeList fillColorList = itemElem.elementsByTagName( "FillColor" ); + QDomNodeList fillColorList = itemElem.elementsByTagName( QStringLiteral( "FillColor" ) ); if ( !fillColorList.isEmpty() ) { QDomElement fillColorElem = fillColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; - fillRed = fillColorElem.attribute( "red" ).toDouble( &redOk ); - fillGreen = fillColorElem.attribute( "green" ).toDouble( &greenOk ); - fillBlue = fillColorElem.attribute( "blue" ).toDouble( &blueOk ); - fillAlpha = fillColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + fillRed = fillColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + fillGreen = fillColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + fillBlue = fillColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + fillAlpha = fillColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { - properties.insert( "color", QgsSymbolLayerUtils::encodeColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ) ); - properties.insert( "style", "solid" ); + properties.insert( QStringLiteral( "color" ), QgsSymbolLayerUtils::encodeColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ) ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "solid" ) ); } } - if ( itemElem.hasAttribute( "transparentFill" ) ) + if ( itemElem.hasAttribute( QStringLiteral( "transparentFill" ) ) ) { //old style (pre 2.0) of specifying that shapes had no fill - bool hasOldTransparentFill = itemElem.attribute( "transparentFill", "0" ).toInt(); + bool hasOldTransparentFill = itemElem.attribute( QStringLiteral( "transparentFill" ), QStringLiteral( "0" ) ).toInt(); if ( hasOldTransparentFill ) { - properties.insert( "style", "no" ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "no" ) ); } } diff --git a/src/core/composer/qgscomposertablecolumn.cpp b/src/core/composer/qgscomposertablecolumn.cpp index 4a5e0da2f574..b78a19d3b06f 100644 --- a/src/core/composer/qgscomposertablecolumn.cpp +++ b/src/core/composer/qgscomposertablecolumn.cpp @@ -38,47 +38,47 @@ QgsComposerTableColumn::~QgsComposerTableColumn() bool QgsComposerTableColumn::writeXml( QDomElement& columnElem, QDomDocument& doc ) const { //background color - QDomElement bgColorElem = doc.createElement( "backgroundColor" ); - bgColorElem.setAttribute( "red", QString::number( mBackgroundColor.red() ) ); - bgColorElem.setAttribute( "green", QString::number( mBackgroundColor.green() ) ); - bgColorElem.setAttribute( "blue", QString::number( mBackgroundColor.blue() ) ); - bgColorElem.setAttribute( "alpha", QString::number( mBackgroundColor.alpha() ) ); + QDomElement bgColorElem = doc.createElement( QStringLiteral( "backgroundColor" ) ); + bgColorElem.setAttribute( QStringLiteral( "red" ), QString::number( mBackgroundColor.red() ) ); + bgColorElem.setAttribute( QStringLiteral( "green" ), QString::number( mBackgroundColor.green() ) ); + bgColorElem.setAttribute( QStringLiteral( "blue" ), QString::number( mBackgroundColor.blue() ) ); + bgColorElem.setAttribute( QStringLiteral( "alpha" ), QString::number( mBackgroundColor.alpha() ) ); columnElem.appendChild( bgColorElem ); - columnElem.setAttribute( "hAlignment", mHAlignment ); - columnElem.setAttribute( "vAlignment", mVAlignment ); + columnElem.setAttribute( QStringLiteral( "hAlignment" ), mHAlignment ); + columnElem.setAttribute( QStringLiteral( "vAlignment" ), mVAlignment ); - columnElem.setAttribute( "heading", mHeading ); - columnElem.setAttribute( "attribute", mAttribute ); + columnElem.setAttribute( QStringLiteral( "heading" ), mHeading ); + columnElem.setAttribute( QStringLiteral( "attribute" ), mAttribute ); - columnElem.setAttribute( "sortByRank", QString::number( mSortByRank ) ); - columnElem.setAttribute( "sortOrder", QString::number( mSortOrder ) ); + columnElem.setAttribute( QStringLiteral( "sortByRank" ), QString::number( mSortByRank ) ); + columnElem.setAttribute( QStringLiteral( "sortOrder" ), QString::number( mSortOrder ) ); - columnElem.setAttribute( "width", QString::number( mWidth ) ); + columnElem.setAttribute( QStringLiteral( "width" ), QString::number( mWidth ) ); return true; } bool QgsComposerTableColumn::readXml( const QDomElement& columnElem ) { - mHAlignment = static_cast< Qt::AlignmentFlag >( columnElem.attribute( "hAlignment", QString::number( Qt::AlignLeft ) ).toInt() ); - mVAlignment = static_cast< Qt::AlignmentFlag >( columnElem.attribute( "vAlignment", QString::number( Qt::AlignVCenter ) ).toInt() ); - mHeading = columnElem.attribute( "heading", "" ); - mAttribute = columnElem.attribute( "attribute", "" ); - mSortByRank = columnElem.attribute( "sortByRank", "0" ).toInt(); - mSortOrder = static_cast< Qt::SortOrder >( columnElem.attribute( "sortOrder", QString::number( Qt::AscendingOrder ) ).toInt() ); - mWidth = columnElem.attribute( "width", "0.0" ).toDouble(); - - QDomNodeList bgColorList = columnElem.elementsByTagName( "backgroundColor" ); + mHAlignment = static_cast< Qt::AlignmentFlag >( columnElem.attribute( QStringLiteral( "hAlignment" ), QString::number( Qt::AlignLeft ) ).toInt() ); + mVAlignment = static_cast< Qt::AlignmentFlag >( columnElem.attribute( QStringLiteral( "vAlignment" ), QString::number( Qt::AlignVCenter ) ).toInt() ); + mHeading = columnElem.attribute( QStringLiteral( "heading" ), QLatin1String( "" ) ); + mAttribute = columnElem.attribute( QStringLiteral( "attribute" ), QLatin1String( "" ) ); + mSortByRank = columnElem.attribute( QStringLiteral( "sortByRank" ), QStringLiteral( "0" ) ).toInt(); + mSortOrder = static_cast< Qt::SortOrder >( columnElem.attribute( QStringLiteral( "sortOrder" ), QString::number( Qt::AscendingOrder ) ).toInt() ); + mWidth = columnElem.attribute( QStringLiteral( "width" ), QStringLiteral( "0.0" ) ).toDouble(); + + QDomNodeList bgColorList = columnElem.elementsByTagName( QStringLiteral( "backgroundColor" ) ); if ( !bgColorList.isEmpty() ) { QDomElement bgColorElem = bgColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int bgRed, bgGreen, bgBlue, bgAlpha; - bgRed = bgColorElem.attribute( "red" ).toDouble( &redOk ); - bgGreen = bgColorElem.attribute( "green" ).toDouble( &greenOk ); - bgBlue = bgColorElem.attribute( "blue" ).toDouble( &blueOk ); - bgAlpha = bgColorElem.attribute( "alpha" ).toDouble( &alphaOk ); + bgRed = bgColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); + bgGreen = bgColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); + bgBlue = bgColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); + bgAlpha = bgColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mBackgroundColor = QColor( bgRed, bgGreen, bgBlue, bgAlpha ); diff --git a/src/core/composer/qgscomposertablev2.cpp b/src/core/composer/qgscomposertablev2.cpp index f28c4523bc2e..8298e704212f 100644 --- a/src/core/composer/qgscomposertablev2.cpp +++ b/src/core/composer/qgscomposertablev2.cpp @@ -29,15 +29,15 @@ bool QgsComposerTableStyle::writeXml( QDomElement& styleElem, QDomDocument& doc ) const { Q_UNUSED( doc ); - styleElem.setAttribute( "cellBackgroundColor", QgsSymbolLayerUtils::encodeColor( cellBackgroundColor ) ); - styleElem.setAttribute( "enabled", enabled ); + styleElem.setAttribute( QStringLiteral( "cellBackgroundColor" ), QgsSymbolLayerUtils::encodeColor( cellBackgroundColor ) ); + styleElem.setAttribute( QStringLiteral( "enabled" ), enabled ); return true; } bool QgsComposerTableStyle::readXml( const QDomElement& styleElem ) { - cellBackgroundColor = QgsSymbolLayerUtils::decodeColor( styleElem.attribute( "cellBackgroundColor", "255,255,255,255" ) ); - enabled = ( styleElem.attribute( "enabled", "0" ) != "0" ); + cellBackgroundColor = QgsSymbolLayerUtils::decodeColor( styleElem.attribute( QStringLiteral( "cellBackgroundColor" ), QStringLiteral( "255,255,255,255" ) ) ); + enabled = ( styleElem.attribute( QStringLiteral( "enabled" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); return true; } @@ -71,7 +71,7 @@ QgsComposerTableV2::QgsComposerTableV2( QgsComposition *composition, bool create //get default composer font from settings QSettings settings; - QString defaultFontString = settings.value( "/Composer/defaultFont" ).toString(); + QString defaultFontString = settings.value( QStringLiteral( "/Composer/defaultFont" ) ).toString(); if ( !defaultFontString.isEmpty() ) { mHeaderFont.setFamily( defaultFontString ); @@ -110,37 +110,37 @@ QgsComposerTableV2::~QgsComposerTableV2() bool QgsComposerTableV2::writeXml( QDomElement& elem, QDomDocument & doc, bool ignoreFrames ) const { - elem.setAttribute( "cellMargin", QString::number( mCellMargin ) ); - elem.setAttribute( "emptyTableMode", QString::number( static_cast< int >( mEmptyTableMode ) ) ); - elem.setAttribute( "emptyTableMessage", mEmptyTableMessage ); - elem.setAttribute( "showEmptyRows", mShowEmptyRows ); - elem.appendChild( QgsFontUtils::toXmlElement( mHeaderFont, doc, "headerFontProperties" ) ); - elem.setAttribute( "headerFontColor", QgsSymbolLayerUtils::encodeColor( mHeaderFontColor ) ); - elem.setAttribute( "headerHAlignment", QString::number( static_cast< int >( mHeaderHAlignment ) ) ); - elem.setAttribute( "headerMode", QString::number( static_cast< int >( mHeaderMode ) ) ); - elem.appendChild( QgsFontUtils::toXmlElement( mContentFont, doc, "contentFontProperties" ) ); - elem.setAttribute( "contentFontColor", QgsSymbolLayerUtils::encodeColor( mContentFontColor ) ); - elem.setAttribute( "gridStrokeWidth", QString::number( mGridStrokeWidth ) ); - elem.setAttribute( "gridColor", QgsSymbolLayerUtils::encodeColor( mGridColor ) ); - elem.setAttribute( "horizontalGrid", mHorizontalGrid ); - elem.setAttribute( "verticalGrid", mVerticalGrid ); - elem.setAttribute( "showGrid", mShowGrid ); - elem.setAttribute( "backgroundColor", QgsSymbolLayerUtils::encodeColor( mBackgroundColor ) ); - elem.setAttribute( "wrapBehaviour", QString::number( static_cast< int >( mWrapBehaviour ) ) ); + elem.setAttribute( QStringLiteral( "cellMargin" ), QString::number( mCellMargin ) ); + elem.setAttribute( QStringLiteral( "emptyTableMode" ), QString::number( static_cast< int >( mEmptyTableMode ) ) ); + elem.setAttribute( QStringLiteral( "emptyTableMessage" ), mEmptyTableMessage ); + elem.setAttribute( QStringLiteral( "showEmptyRows" ), mShowEmptyRows ); + elem.appendChild( QgsFontUtils::toXmlElement( mHeaderFont, doc, QStringLiteral( "headerFontProperties" ) ) ); + elem.setAttribute( QStringLiteral( "headerFontColor" ), QgsSymbolLayerUtils::encodeColor( mHeaderFontColor ) ); + elem.setAttribute( QStringLiteral( "headerHAlignment" ), QString::number( static_cast< int >( mHeaderHAlignment ) ) ); + elem.setAttribute( QStringLiteral( "headerMode" ), QString::number( static_cast< int >( mHeaderMode ) ) ); + elem.appendChild( QgsFontUtils::toXmlElement( mContentFont, doc, QStringLiteral( "contentFontProperties" ) ) ); + elem.setAttribute( QStringLiteral( "contentFontColor" ), QgsSymbolLayerUtils::encodeColor( mContentFontColor ) ); + elem.setAttribute( QStringLiteral( "gridStrokeWidth" ), QString::number( mGridStrokeWidth ) ); + elem.setAttribute( QStringLiteral( "gridColor" ), QgsSymbolLayerUtils::encodeColor( mGridColor ) ); + elem.setAttribute( QStringLiteral( "horizontalGrid" ), mHorizontalGrid ); + elem.setAttribute( QStringLiteral( "verticalGrid" ), mVerticalGrid ); + elem.setAttribute( QStringLiteral( "showGrid" ), mShowGrid ); + elem.setAttribute( QStringLiteral( "backgroundColor" ), QgsSymbolLayerUtils::encodeColor( mBackgroundColor ) ); + elem.setAttribute( QStringLiteral( "wrapBehaviour" ), QString::number( static_cast< int >( mWrapBehaviour ) ) ); //columns - QDomElement displayColumnsElem = doc.createElement( "displayColumns" ); + QDomElement displayColumnsElem = doc.createElement( QStringLiteral( "displayColumns" ) ); QList::const_iterator columnIt = mColumns.constBegin(); for ( ; columnIt != mColumns.constEnd(); ++columnIt ) { - QDomElement columnElem = doc.createElement( "column" ); + QDomElement columnElem = doc.createElement( QStringLiteral( "column" ) ); ( *columnIt )->writeXml( columnElem, doc ); displayColumnsElem.appendChild( columnElem ); } elem.appendChild( displayColumnsElem ); //cell styles - QDomElement stylesElem = doc.createElement( "cellStyles" ); + QDomElement stylesElem = doc.createElement( QStringLiteral( "cellStyles" ) ); QMap< CellStyleGroup, QString >::const_iterator it = mCellStyleNames.constBegin(); for ( ; it != mCellStyleNames.constEnd(); ++it ) { @@ -174,38 +174,38 @@ bool QgsComposerTableV2::readXml( const QDomElement &itemElem, const QDomDocumen return false; } - mEmptyTableMode = QgsComposerTableV2::EmptyTableMode( itemElem.attribute( "emptyTableMode", "0" ).toInt() ); - mEmptyTableMessage = itemElem.attribute( "emptyTableMessage", tr( "No matching records" ) ); - mShowEmptyRows = itemElem.attribute( "showEmptyRows", "0" ).toInt(); - if ( !QgsFontUtils::setFromXmlChildNode( mHeaderFont, itemElem, "headerFontProperties" ) ) + mEmptyTableMode = QgsComposerTableV2::EmptyTableMode( itemElem.attribute( QStringLiteral( "emptyTableMode" ), QStringLiteral( "0" ) ).toInt() ); + mEmptyTableMessage = itemElem.attribute( QStringLiteral( "emptyTableMessage" ), tr( "No matching records" ) ); + mShowEmptyRows = itemElem.attribute( QStringLiteral( "showEmptyRows" ), QStringLiteral( "0" ) ).toInt(); + if ( !QgsFontUtils::setFromXmlChildNode( mHeaderFont, itemElem, QStringLiteral( "headerFontProperties" ) ) ) { - mHeaderFont.fromString( itemElem.attribute( "headerFont", "" ) ); + mHeaderFont.fromString( itemElem.attribute( QStringLiteral( "headerFont" ), QLatin1String( "" ) ) ); } - mHeaderFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "headerFontColor", "0,0,0,255" ) ); - mHeaderHAlignment = QgsComposerTableV2::HeaderHAlignment( itemElem.attribute( "headerHAlignment", "0" ).toInt() ); - mHeaderMode = QgsComposerTableV2::HeaderMode( itemElem.attribute( "headerMode", "0" ).toInt() ); - if ( !QgsFontUtils::setFromXmlChildNode( mContentFont, itemElem, "contentFontProperties" ) ) + mHeaderFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "headerFontColor" ), QStringLiteral( "0,0,0,255" ) ) ); + mHeaderHAlignment = QgsComposerTableV2::HeaderHAlignment( itemElem.attribute( QStringLiteral( "headerHAlignment" ), QStringLiteral( "0" ) ).toInt() ); + mHeaderMode = QgsComposerTableV2::HeaderMode( itemElem.attribute( QStringLiteral( "headerMode" ), QStringLiteral( "0" ) ).toInt() ); + if ( !QgsFontUtils::setFromXmlChildNode( mContentFont, itemElem, QStringLiteral( "contentFontProperties" ) ) ) { - mContentFont.fromString( itemElem.attribute( "contentFont", "" ) ); + mContentFont.fromString( itemElem.attribute( QStringLiteral( "contentFont" ), QLatin1String( "" ) ) ); } - mContentFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "contentFontColor", "0,0,0,255" ) ); - mCellMargin = itemElem.attribute( "cellMargin", "1.0" ).toDouble(); - mGridStrokeWidth = itemElem.attribute( "gridStrokeWidth", "0.5" ).toDouble(); - mHorizontalGrid = itemElem.attribute( "horizontalGrid", "1" ).toInt(); - mVerticalGrid = itemElem.attribute( "verticalGrid", "1" ).toInt(); - mShowGrid = itemElem.attribute( "showGrid", "1" ).toInt(); - mGridColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "gridColor", "0,0,0,255" ) ); - mBackgroundColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "backgroundColor", "255,255,255,0" ) ); - mWrapBehaviour = QgsComposerTableV2::WrapBehaviour( itemElem.attribute( "wrapBehaviour", "0" ).toInt() ); + mContentFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "contentFontColor" ), QStringLiteral( "0,0,0,255" ) ) ); + mCellMargin = itemElem.attribute( QStringLiteral( "cellMargin" ), QStringLiteral( "1.0" ) ).toDouble(); + mGridStrokeWidth = itemElem.attribute( QStringLiteral( "gridStrokeWidth" ), QStringLiteral( "0.5" ) ).toDouble(); + mHorizontalGrid = itemElem.attribute( QStringLiteral( "horizontalGrid" ), QStringLiteral( "1" ) ).toInt(); + mVerticalGrid = itemElem.attribute( QStringLiteral( "verticalGrid" ), QStringLiteral( "1" ) ).toInt(); + mShowGrid = itemElem.attribute( QStringLiteral( "showGrid" ), QStringLiteral( "1" ) ).toInt(); + mGridColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "gridColor" ), QStringLiteral( "0,0,0,255" ) ) ); + mBackgroundColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( QStringLiteral( "backgroundColor" ), QStringLiteral( "255,255,255,0" ) ) ); + mWrapBehaviour = QgsComposerTableV2::WrapBehaviour( itemElem.attribute( QStringLiteral( "wrapBehaviour" ), QStringLiteral( "0" ) ).toInt() ); //restore column specifications qDeleteAll( mColumns ); mColumns.clear(); - QDomNodeList columnsList = itemElem.elementsByTagName( "displayColumns" ); + QDomNodeList columnsList = itemElem.elementsByTagName( QStringLiteral( "displayColumns" ) ); if ( !columnsList.isEmpty() ) { QDomElement columnsElem = columnsList.at( 0 ).toElement(); - QDomNodeList columnEntryList = columnsElem.elementsByTagName( "column" ); + QDomNodeList columnEntryList = columnsElem.elementsByTagName( QStringLiteral( "column" ) ); for ( int i = 0; i < columnEntryList.size(); ++i ) { QDomElement columnElem = columnEntryList.at( i ).toElement(); @@ -216,7 +216,7 @@ bool QgsComposerTableV2::readXml( const QDomElement &itemElem, const QDomDocumen } //restore cell styles - QDomNodeList stylesList = itemElem.elementsByTagName( "cellStyles" ); + QDomNodeList stylesList = itemElem.elementsByTagName( QStringLiteral( "cellStyles" ) ); if ( !stylesList.isEmpty() ) { QDomElement stylesElem = stylesList.at( 0 ).toElement(); @@ -884,15 +884,15 @@ void QgsComposerTableV2::initStyles() mCellStyles.insert( FirstRow, new QgsComposerTableStyle() ); mCellStyles.insert( LastRow, new QgsComposerTableStyle() ); - mCellStyleNames.insert( OddColumns, "oddColumns" ); - mCellStyleNames.insert( EvenColumns, "evenColumns" ); - mCellStyleNames.insert( OddRows, "oddRows" ); - mCellStyleNames.insert( EvenRows, "evenRows" ); - mCellStyleNames.insert( FirstColumn, "firstColumn" ); - mCellStyleNames.insert( LastColumn, "lastColumn" ); - mCellStyleNames.insert( HeaderRow, "headerRow" ); - mCellStyleNames.insert( FirstRow, "firstRow" ); - mCellStyleNames.insert( LastRow, "lastRow" ); + mCellStyleNames.insert( OddColumns, QStringLiteral( "oddColumns" ) ); + mCellStyleNames.insert( EvenColumns, QStringLiteral( "evenColumns" ) ); + mCellStyleNames.insert( OddRows, QStringLiteral( "oddRows" ) ); + mCellStyleNames.insert( EvenRows, QStringLiteral( "evenRows" ) ); + mCellStyleNames.insert( FirstColumn, QStringLiteral( "firstColumn" ) ); + mCellStyleNames.insert( LastColumn, QStringLiteral( "lastColumn" ) ); + mCellStyleNames.insert( HeaderRow, QStringLiteral( "headerRow" ) ); + mCellStyleNames.insert( FirstRow, QStringLiteral( "firstRow" ) ); + mCellStyleNames.insert( LastRow, QStringLiteral( "lastRow" ) ); } bool QgsComposerTableV2::calculateMaxColumnWidths() @@ -1217,7 +1217,7 @@ QString QgsComposerTableV2::wrappedText( const QString &value, double columnWidt } } - return outLines.join( "\n" ); + return outLines.join( QStringLiteral( "\n" ) ); } QColor QgsComposerTableV2::backgroundColor( int row, int column ) const diff --git a/src/core/composer/qgscomposerutils.cpp b/src/core/composer/qgscomposerutils.cpp index f1dfdc12007a..b1f3fcf61d83 100644 --- a/src/core/composer/qgscomposerutils.cpp +++ b/src/core/composer/qgscomposerutils.cpp @@ -261,12 +261,12 @@ double QgsComposerUtils::relativePosition( const double position, const double b QgsComposition::PaperOrientation QgsComposerUtils::decodePaperOrientation( const QString& orientationString, bool &ok ) { - if ( orientationString.compare( "Portrait", Qt::CaseInsensitive ) == 0 ) + if ( orientationString.compare( QLatin1String( "Portrait" ), Qt::CaseInsensitive ) == 0 ) { ok = true; return QgsComposition::Portrait; } - if ( orientationString.compare( "Landscape", Qt::CaseInsensitive ) == 0 ) + if ( orientationString.compare( QLatin1String( "Landscape" ), Qt::CaseInsensitive ) == 0 ) { ok = true; return QgsComposition::Landscape; @@ -278,32 +278,32 @@ QgsComposition::PaperOrientation QgsComposerUtils::decodePaperOrientation( const bool QgsComposerUtils::decodePresetPaperSize( const QString& presetString, double &width, double &height ) { QList< QPair< QString, QSizeF > > presets; - presets << qMakePair( QString( "A5" ), QSizeF( 148, 210 ) ); - presets << qMakePair( QString( "A4" ), QSizeF( 210, 297 ) ); - presets << qMakePair( QString( "A3" ), QSizeF( 297, 420 ) ); - presets << qMakePair( QString( "A2" ), QSizeF( 420, 594 ) ); - presets << qMakePair( QString( "A1" ), QSizeF( 594, 841 ) ); - presets << qMakePair( QString( "A0" ), QSizeF( 841, 1189 ) ); - presets << qMakePair( QString( "B5" ), QSizeF( 176, 250 ) ); - presets << qMakePair( QString( "B4" ), QSizeF( 250, 353 ) ); - presets << qMakePair( QString( "B3" ), QSizeF( 353, 500 ) ); - presets << qMakePair( QString( "B2" ), QSizeF( 500, 707 ) ); - presets << qMakePair( QString( "B1" ), QSizeF( 707, 1000 ) ); - presets << qMakePair( QString( "B0" ), QSizeF( 1000, 1414 ) ); + presets << qMakePair( QStringLiteral( "A5" ), QSizeF( 148, 210 ) ); + presets << qMakePair( QStringLiteral( "A4" ), QSizeF( 210, 297 ) ); + presets << qMakePair( QStringLiteral( "A3" ), QSizeF( 297, 420 ) ); + presets << qMakePair( QStringLiteral( "A2" ), QSizeF( 420, 594 ) ); + presets << qMakePair( QStringLiteral( "A1" ), QSizeF( 594, 841 ) ); + presets << qMakePair( QStringLiteral( "A0" ), QSizeF( 841, 1189 ) ); + presets << qMakePair( QStringLiteral( "B5" ), QSizeF( 176, 250 ) ); + presets << qMakePair( QStringLiteral( "B4" ), QSizeF( 250, 353 ) ); + presets << qMakePair( QStringLiteral( "B3" ), QSizeF( 353, 500 ) ); + presets << qMakePair( QStringLiteral( "B2" ), QSizeF( 500, 707 ) ); + presets << qMakePair( QStringLiteral( "B1" ), QSizeF( 707, 1000 ) ); + presets << qMakePair( QStringLiteral( "B0" ), QSizeF( 1000, 1414 ) ); // North american formats - presets << qMakePair( QString( "Legal" ), QSizeF( 215.9, 355.6 ) ); - presets << qMakePair( QString( "Letter" ), QSizeF( 215.9, 279.4 ) ); - presets << qMakePair( QString( "ANSI A" ), QSizeF( 215.9, 279.4 ) ); - presets << qMakePair( QString( "ANSI B" ), QSizeF( 279.4, 431.8 ) ); - presets << qMakePair( QString( "ANSI C" ), QSizeF( 431.8, 558.8 ) ); - presets << qMakePair( QString( "ANSI D" ), QSizeF( 558.8, 863.6 ) ); - presets << qMakePair( QString( "ANSI E" ), QSizeF( 863.6, 1117.6 ) ); - presets << qMakePair( QString( "Arch A" ), QSizeF( 228.6, 304.8 ) ); - presets << qMakePair( QString( "Arch B" ), QSizeF( 304.8, 457.2 ) ); - presets << qMakePair( QString( "Arch C" ), QSizeF( 457.2, 609.6 ) ); - presets << qMakePair( QString( "Arch D" ), QSizeF( 609.6, 914.4 ) ); - presets << qMakePair( QString( "Arch E" ), QSizeF( 914.4, 1219.2 ) ); - presets << qMakePair( QString( "Arch E1" ), QSizeF( 762, 1066.8 ) ); + presets << qMakePair( QStringLiteral( "Legal" ), QSizeF( 215.9, 355.6 ) ); + presets << qMakePair( QStringLiteral( "Letter" ), QSizeF( 215.9, 279.4 ) ); + presets << qMakePair( QStringLiteral( "ANSI A" ), QSizeF( 215.9, 279.4 ) ); + presets << qMakePair( QStringLiteral( "ANSI B" ), QSizeF( 279.4, 431.8 ) ); + presets << qMakePair( QStringLiteral( "ANSI C" ), QSizeF( 431.8, 558.8 ) ); + presets << qMakePair( QStringLiteral( "ANSI D" ), QSizeF( 558.8, 863.6 ) ); + presets << qMakePair( QStringLiteral( "ANSI E" ), QSizeF( 863.6, 1117.6 ) ); + presets << qMakePair( QStringLiteral( "Arch A" ), QSizeF( 228.6, 304.8 ) ); + presets << qMakePair( QStringLiteral( "Arch B" ), QSizeF( 304.8, 457.2 ) ); + presets << qMakePair( QStringLiteral( "Arch C" ), QSizeF( 457.2, 609.6 ) ); + presets << qMakePair( QStringLiteral( "Arch D" ), QSizeF( 609.6, 914.4 ) ); + presets << qMakePair( QStringLiteral( "Arch E" ), QSizeF( 914.4, 1219.2 ) ); + presets << qMakePair( QStringLiteral( "Arch E1" ), QSizeF( 762, 1066.8 ) ); QList< QPair< QString, QSizeF > >::const_iterator presetIt = presets.constBegin(); for ( ;presetIt != presets.constEnd(); ++presetIt ) @@ -356,8 +356,8 @@ void QgsComposerUtils::readDataDefinedProperty( const QgsComposerObject::DataDef } //set values for QgsDataDefined - QString active = ddElem.attribute( "active" ); - if ( active.compare( "true", Qt::CaseInsensitive ) == 0 ) + QString active = ddElem.attribute( QStringLiteral( "active" ) ); + if ( active.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { dd->setActive( true ); } @@ -365,10 +365,10 @@ void QgsComposerUtils::readDataDefinedProperty( const QgsComposerObject::DataDef { dd->setActive( false ); } - dd->setField( ddElem.attribute( "field" ) ); - dd->setExpressionString( ddElem.attribute( "expr" ) ); - QString useExpr = ddElem.attribute( "useExpr" ); - if ( useExpr.compare( "true", Qt::CaseInsensitive ) == 0 ) + dd->setField( ddElem.attribute( QStringLiteral( "field" ) ) ); + dd->setExpressionString( ddElem.attribute( QStringLiteral( "expr" ) ) ); + QString useExpr = ddElem.attribute( QStringLiteral( "useExpr" ) ); + if ( useExpr.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { dd->setUseExpression( true ); } @@ -403,22 +403,22 @@ void QgsComposerUtils::writeDataDefinedPropertyMap( QDomElement &itemElem, QDomD QDomElement ddElem = doc.createElement( newElemName ); if ( active ) { - ddElem.setAttribute( "active", "true" ); + ddElem.setAttribute( QStringLiteral( "active" ), QStringLiteral( "true" ) ); } else { - ddElem.setAttribute( "active", "false" ); + ddElem.setAttribute( QStringLiteral( "active" ), QStringLiteral( "false" ) ); } if ( useExpr ) { - ddElem.setAttribute( "useExpr", "true" ); + ddElem.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "true" ) ); } else { - ddElem.setAttribute( "useExpr", "false" ); + ddElem.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "false" ) ); } - ddElem.setAttribute( "expr", expr ); - ddElem.setAttribute( "field", field ); + ddElem.setAttribute( QStringLiteral( "expr" ), expr ); + ddElem.setAttribute( QStringLiteral( "field" ), field ); itemElem.appendChild( ddElem ); } } diff --git a/src/core/composer/qgscomposition.cpp b/src/core/composer/qgscomposition.cpp index fc9d2dad60b2..0dd16f92f5dc 100644 --- a/src/core/composer/qgscomposition.cpp +++ b/src/core/composer/qgscomposition.cpp @@ -105,11 +105,11 @@ void QgsComposition::init() mResizeToContentsMarginLeft = 0; //data defined strings - mDataDefinedNames.insert( QgsComposerObject::PresetPaperSize, QString( "dataDefinedPaperSize" ) ); - mDataDefinedNames.insert( QgsComposerObject::PaperWidth, QString( "dataDefinedPaperWidth" ) ); - mDataDefinedNames.insert( QgsComposerObject::PaperHeight, QString( "dataDefinedPaperHeight" ) ); - mDataDefinedNames.insert( QgsComposerObject::NumPages, QString( "dataDefinedNumPages" ) ); - mDataDefinedNames.insert( QgsComposerObject::PaperOrientation, QString( "dataDefinedPaperOrientation" ) ); + mDataDefinedNames.insert( QgsComposerObject::PresetPaperSize, QStringLiteral( "dataDefinedPaperSize" ) ); + mDataDefinedNames.insert( QgsComposerObject::PaperWidth, QStringLiteral( "dataDefinedPaperWidth" ) ); + mDataDefinedNames.insert( QgsComposerObject::PaperHeight, QStringLiteral( "dataDefinedPaperHeight" ) ); + mDataDefinedNames.insert( QgsComposerObject::NumPages, QStringLiteral( "dataDefinedNumPages" ) ); + mDataDefinedNames.insert( QgsComposerObject::PaperOrientation, QStringLiteral( "dataDefinedPaperOrientation" ) ); //connect to atlas toggling on/off and coverage layer and feature changes //to update data defined values @@ -174,10 +174,10 @@ QgsComposition::~QgsComposition() void QgsComposition::loadDefaults() { QSettings settings; - mSnapGridResolution = settings.value( "/Composer/defaultSnapGridResolution", 10.0 ).toDouble(); - mSnapGridOffsetX = settings.value( "/Composer/defaultSnapGridOffsetX", 0 ).toDouble(); - mSnapGridOffsetY = settings.value( "/Composer/defaultSnapGridOffsetY", 0 ).toDouble(); - mSnapTolerance = settings.value( "/Composer/defaultSnapTolerancePixels", 5 ).toInt(); + mSnapGridResolution = settings.value( QStringLiteral( "/Composer/defaultSnapGridResolution" ), 10.0 ).toDouble(); + mSnapGridOffsetX = settings.value( QStringLiteral( "/Composer/defaultSnapGridOffsetX" ), 0 ).toDouble(); + mSnapGridOffsetY = settings.value( QStringLiteral( "/Composer/defaultSnapGridOffsetY" ), 0 ).toDouble(); + mSnapTolerance = settings.value( QStringLiteral( "/Composer/defaultSnapTolerancePixels" ), 5 ).toInt(); } void QgsComposition::updateBounds() @@ -562,10 +562,10 @@ void QgsComposition::createDefaultPageStyleSymbol() { delete mPageStyleSymbol; QgsStringMap properties; - properties.insert( "color", "white" ); - properties.insert( "style", "solid" ); - properties.insert( "style_border", "no" ); - properties.insert( "joinstyle", "miter" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "white" ) ); + properties.insert( QStringLiteral( "style" ), QStringLiteral( "solid" ) ); + properties.insert( QStringLiteral( "style_border" ), QStringLiteral( "no" ) ); + properties.insert( QStringLiteral( "joinstyle" ), QStringLiteral( "miter" ) ); mPageStyleSymbol = QgsFillSymbol::createSimple( properties ); } @@ -818,10 +818,10 @@ bool QgsComposition::writeXml( QDomElement& composerElem, QDomDocument& doc ) return false; } - QDomElement compositionElem = doc.createElement( "Composition" ); - compositionElem.setAttribute( "paperWidth", QString::number( mPageWidth ) ); - compositionElem.setAttribute( "paperHeight", QString::number( mPageHeight ) ); - compositionElem.setAttribute( "numPages", mPages.size() ); + QDomElement compositionElem = doc.createElement( QStringLiteral( "Composition" ) ); + compositionElem.setAttribute( QStringLiteral( "paperWidth" ), QString::number( mPageWidth ) ); + compositionElem.setAttribute( QStringLiteral( "paperHeight" ), QString::number( mPageHeight ) ); + compositionElem.setAttribute( QStringLiteral( "numPages" ), mPages.size() ); QDomElement pageStyleElem = QgsSymbolLayerUtils::saveSymbol( QString(), mPageStyleSymbol, doc ); compositionElem.appendChild( pageStyleElem ); @@ -829,54 +829,54 @@ bool QgsComposition::writeXml( QDomElement& composerElem, QDomDocument& doc ) //snapping if ( mSnapToGrid ) { - compositionElem.setAttribute( "snapping", "1" ); + compositionElem.setAttribute( QStringLiteral( "snapping" ), QStringLiteral( "1" ) ); } else { - compositionElem.setAttribute( "snapping", "0" ); + compositionElem.setAttribute( QStringLiteral( "snapping" ), QStringLiteral( "0" ) ); } if ( mGridVisible ) { - compositionElem.setAttribute( "gridVisible", "1" ); + compositionElem.setAttribute( QStringLiteral( "gridVisible" ), QStringLiteral( "1" ) ); } else { - compositionElem.setAttribute( "gridVisible", "0" ); + compositionElem.setAttribute( QStringLiteral( "gridVisible" ), QStringLiteral( "0" ) ); } - compositionElem.setAttribute( "snapGridResolution", QString::number( mSnapGridResolution ) ); - compositionElem.setAttribute( "snapGridOffsetX", QString::number( mSnapGridOffsetX ) ); - compositionElem.setAttribute( "snapGridOffsetY", QString::number( mSnapGridOffsetY ) ); + compositionElem.setAttribute( QStringLiteral( "snapGridResolution" ), QString::number( mSnapGridResolution ) ); + compositionElem.setAttribute( QStringLiteral( "snapGridOffsetX" ), QString::number( mSnapGridOffsetX ) ); + compositionElem.setAttribute( QStringLiteral( "snapGridOffsetY" ), QString::number( mSnapGridOffsetY ) ); - compositionElem.setAttribute( "showPages", mPagesVisible ); + compositionElem.setAttribute( QStringLiteral( "showPages" ), mPagesVisible ); //custom snap lines QList< QGraphicsLineItem* >::const_iterator snapLineIt = mSnapLines.constBegin(); for ( ; snapLineIt != mSnapLines.constEnd(); ++snapLineIt ) { - QDomElement snapLineElem = doc.createElement( "SnapLine" ); + QDomElement snapLineElem = doc.createElement( QStringLiteral( "SnapLine" ) ); QLineF line = ( *snapLineIt )->line(); - snapLineElem.setAttribute( "x1", QString::number( line.x1() ) ); - snapLineElem.setAttribute( "y1", QString::number( line.y1() ) ); - snapLineElem.setAttribute( "x2", QString::number( line.x2() ) ); - snapLineElem.setAttribute( "y2", QString::number( line.y2() ) ); + snapLineElem.setAttribute( QStringLiteral( "x1" ), QString::number( line.x1() ) ); + snapLineElem.setAttribute( QStringLiteral( "y1" ), QString::number( line.y1() ) ); + snapLineElem.setAttribute( QStringLiteral( "x2" ), QString::number( line.x2() ) ); + snapLineElem.setAttribute( QStringLiteral( "y2" ), QString::number( line.y2() ) ); compositionElem.appendChild( snapLineElem ); } - compositionElem.setAttribute( "printResolution", mPrintResolution ); - compositionElem.setAttribute( "printAsRaster", mPrintAsRaster ); + compositionElem.setAttribute( QStringLiteral( "printResolution" ), mPrintResolution ); + compositionElem.setAttribute( QStringLiteral( "printAsRaster" ), mPrintAsRaster ); - compositionElem.setAttribute( "generateWorldFile", mGenerateWorldFile ? 1 : 0 ); - compositionElem.setAttribute( "worldFileMap", mWorldFileMapId ); + compositionElem.setAttribute( QStringLiteral( "generateWorldFile" ), mGenerateWorldFile ? 1 : 0 ); + compositionElem.setAttribute( QStringLiteral( "worldFileMap" ), mWorldFileMapId ); - compositionElem.setAttribute( "alignmentSnap", mAlignmentSnap ? 1 : 0 ); - compositionElem.setAttribute( "guidesVisible", mGuidesVisible ? 1 : 0 ); - compositionElem.setAttribute( "smartGuides", mSmartGuides ? 1 : 0 ); - compositionElem.setAttribute( "snapTolerancePixels", mSnapTolerance ); + compositionElem.setAttribute( QStringLiteral( "alignmentSnap" ), mAlignmentSnap ? 1 : 0 ); + compositionElem.setAttribute( QStringLiteral( "guidesVisible" ), mGuidesVisible ? 1 : 0 ); + compositionElem.setAttribute( QStringLiteral( "smartGuides" ), mSmartGuides ? 1 : 0 ); + compositionElem.setAttribute( QStringLiteral( "snapTolerancePixels" ), mSnapTolerance ); - compositionElem.setAttribute( "resizeToContentsMarginTop", mResizeToContentsMarginTop ); - compositionElem.setAttribute( "resizeToContentsMarginRight", mResizeToContentsMarginRight ); - compositionElem.setAttribute( "resizeToContentsMarginBottom", mResizeToContentsMarginBottom ); - compositionElem.setAttribute( "resizeToContentsMarginLeft", mResizeToContentsMarginLeft ); + compositionElem.setAttribute( QStringLiteral( "resizeToContentsMarginTop" ), mResizeToContentsMarginTop ); + compositionElem.setAttribute( QStringLiteral( "resizeToContentsMarginRight" ), mResizeToContentsMarginRight ); + compositionElem.setAttribute( QStringLiteral( "resizeToContentsMarginBottom" ), mResizeToContentsMarginBottom ); + compositionElem.setAttribute( QStringLiteral( "resizeToContentsMarginLeft" ), mResizeToContentsMarginLeft ); //save items except paper items and frame items (they are saved with the corresponding multiframe) QList itemList = items(); @@ -920,12 +920,12 @@ bool QgsComposition::readXml( const QDomElement& compositionElem, const QDomDocu //create pages bool widthConversionOk, heightConversionOk; - mPageWidth = compositionElem.attribute( "paperWidth" ).toDouble( &widthConversionOk ); - mPageHeight = compositionElem.attribute( "paperHeight" ).toDouble( &heightConversionOk ); + mPageWidth = compositionElem.attribute( QStringLiteral( "paperWidth" ) ).toDouble( &widthConversionOk ); + mPageHeight = compositionElem.attribute( QStringLiteral( "paperHeight" ) ).toDouble( &heightConversionOk ); emit paperSizeChanged(); - int numPages = compositionElem.attribute( "numPages", "1" ).toInt(); + int numPages = compositionElem.attribute( QStringLiteral( "numPages" ), QStringLiteral( "1" ) ).toInt(); - QDomElement pageStyleSymbolElem = compositionElem.firstChildElement( "symbol" ); + QDomElement pageStyleSymbolElem = compositionElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !pageStyleSymbolElem.isNull() ) { delete mPageStyleSymbol; @@ -942,42 +942,42 @@ bool QgsComposition::readXml( const QDomElement& compositionElem, const QDomDocu } //snapping - mSnapToGrid = compositionElem.attribute( "snapping", "0" ).toInt() == 0 ? false : true; - mGridVisible = compositionElem.attribute( "gridVisible", "0" ).toInt() == 0 ? false : true; + mSnapToGrid = compositionElem.attribute( QStringLiteral( "snapping" ), QStringLiteral( "0" ) ).toInt() == 0 ? false : true; + mGridVisible = compositionElem.attribute( QStringLiteral( "gridVisible" ), QStringLiteral( "0" ) ).toInt() == 0 ? false : true; - mSnapGridResolution = compositionElem.attribute( "snapGridResolution" ).toDouble(); - mSnapGridOffsetX = compositionElem.attribute( "snapGridOffsetX" ).toDouble(); - mSnapGridOffsetY = compositionElem.attribute( "snapGridOffsetY" ).toDouble(); + mSnapGridResolution = compositionElem.attribute( QStringLiteral( "snapGridResolution" ) ).toDouble(); + mSnapGridOffsetX = compositionElem.attribute( QStringLiteral( "snapGridOffsetX" ) ).toDouble(); + mSnapGridOffsetY = compositionElem.attribute( QStringLiteral( "snapGridOffsetY" ) ).toDouble(); - mAlignmentSnap = compositionElem.attribute( "alignmentSnap", "1" ).toInt() == 0 ? false : true; - mGuidesVisible = compositionElem.attribute( "guidesVisible", "1" ).toInt() == 0 ? false : true; - mSmartGuides = compositionElem.attribute( "smartGuides", "1" ).toInt() == 0 ? false : true; - mSnapTolerance = compositionElem.attribute( "snapTolerancePixels", "10" ).toInt(); + mAlignmentSnap = compositionElem.attribute( QStringLiteral( "alignmentSnap" ), QStringLiteral( "1" ) ).toInt() == 0 ? false : true; + mGuidesVisible = compositionElem.attribute( QStringLiteral( "guidesVisible" ), QStringLiteral( "1" ) ).toInt() == 0 ? false : true; + mSmartGuides = compositionElem.attribute( QStringLiteral( "smartGuides" ), QStringLiteral( "1" ) ).toInt() == 0 ? false : true; + mSnapTolerance = compositionElem.attribute( QStringLiteral( "snapTolerancePixels" ), QStringLiteral( "10" ) ).toInt(); - mResizeToContentsMarginTop = compositionElem.attribute( "resizeToContentsMarginTop", "0" ).toDouble(); - mResizeToContentsMarginRight = compositionElem.attribute( "resizeToContentsMarginRight", "0" ).toDouble(); - mResizeToContentsMarginBottom = compositionElem.attribute( "resizeToContentsMarginBottom", "0" ).toDouble(); - mResizeToContentsMarginLeft = compositionElem.attribute( "resizeToContentsMarginLeft", "0" ).toDouble(); + mResizeToContentsMarginTop = compositionElem.attribute( QStringLiteral( "resizeToContentsMarginTop" ), QStringLiteral( "0" ) ).toDouble(); + mResizeToContentsMarginRight = compositionElem.attribute( QStringLiteral( "resizeToContentsMarginRight" ), QStringLiteral( "0" ) ).toDouble(); + mResizeToContentsMarginBottom = compositionElem.attribute( QStringLiteral( "resizeToContentsMarginBottom" ), QStringLiteral( "0" ) ).toDouble(); + mResizeToContentsMarginLeft = compositionElem.attribute( QStringLiteral( "resizeToContentsMarginLeft" ), QStringLiteral( "0" ) ).toDouble(); //custom snap lines - QDomNodeList snapLineNodes = compositionElem.elementsByTagName( "SnapLine" ); + QDomNodeList snapLineNodes = compositionElem.elementsByTagName( QStringLiteral( "SnapLine" ) ); for ( int i = 0; i < snapLineNodes.size(); ++i ) { QDomElement snapLineElem = snapLineNodes.at( i ).toElement(); QGraphicsLineItem* snapItem = addSnapLine(); - double x1 = snapLineElem.attribute( "x1" ).toDouble(); - double y1 = snapLineElem.attribute( "y1" ).toDouble(); - double x2 = snapLineElem.attribute( "x2" ).toDouble(); - double y2 = snapLineElem.attribute( "y2" ).toDouble(); + double x1 = snapLineElem.attribute( QStringLiteral( "x1" ) ).toDouble(); + double y1 = snapLineElem.attribute( QStringLiteral( "y1" ) ).toDouble(); + double x2 = snapLineElem.attribute( QStringLiteral( "x2" ) ).toDouble(); + double y2 = snapLineElem.attribute( QStringLiteral( "y2" ) ).toDouble(); snapItem->setLine( x1, y1, x2, y2 ); } - mPagesVisible = ( compositionElem.attribute( "showPages", "1" ) != "0" ); - mPrintAsRaster = compositionElem.attribute( "printAsRaster" ).toInt(); - mPrintResolution = compositionElem.attribute( "printResolution", "300" ).toInt(); + mPagesVisible = ( compositionElem.attribute( QStringLiteral( "showPages" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); + mPrintAsRaster = compositionElem.attribute( QStringLiteral( "printAsRaster" ) ).toInt(); + mPrintResolution = compositionElem.attribute( QStringLiteral( "printResolution" ), QStringLiteral( "300" ) ).toInt(); - mGenerateWorldFile = compositionElem.attribute( "generateWorldFile", "0" ).toInt() == 1 ? true : false; - mWorldFileMapId = compositionElem.attribute( "worldFileMap" ); + mGenerateWorldFile = compositionElem.attribute( QStringLiteral( "generateWorldFile" ), QStringLiteral( "0" ) ).toInt() == 1 ? true : false; + mWorldFileMapId = compositionElem.attribute( QStringLiteral( "worldFileMap" ) ); //data defined properties QgsComposerUtils::readDataDefinedPropertyMap( compositionElem, &mDataDefinedNames, &mDataDefinedProperties ); @@ -1046,7 +1046,7 @@ bool QgsComposition::loadFromTemplate( const QDomDocument& doc, QMap::max(); double minY = std::numeric_limits::max(); - QDomNodeList composerItemList = elem.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemList = elem.elementsByTagName( QStringLiteral( "ComposerItem" ) ); for ( int i = 0; i < composerItemList.size(); ++i ) { QDomElement currentComposerItemElem = composerItemList.at( i ).toElement(); double x, y; bool xOk, yOk; - x = currentComposerItemElem.attribute( "x" ).toDouble( &xOk ); - y = currentComposerItemElem.attribute( "y" ).toDouble( &yOk ); + x = currentComposerItemElem.attribute( QStringLiteral( "x" ) ).toDouble( &xOk ); + y = currentComposerItemElem.attribute( QStringLiteral( "y" ) ).toDouble( &yOk ); if ( !xOk || !yOk ) { continue; @@ -1146,7 +1146,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen pasteInPlacePt = new QPointF( 0, pageNumberAt( *pos ) * ( mPageHeight + mSpaceBetweenPages ) ); } } - QDomNodeList composerLabelList = elem.elementsByTagName( "ComposerLabel" ); + QDomNodeList composerLabelList = elem.elementsByTagName( QStringLiteral( "ComposerLabel" ) ); for ( int i = 0; i < composerLabelList.size(); ++i ) { QDomElement currentComposerLabelElem = composerLabelList.at( i ).toElement(); @@ -1174,7 +1174,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } } // map - QDomNodeList composerMapList = elem.elementsByTagName( "ComposerMap" ); + QDomNodeList composerMapList = elem.elementsByTagName( QStringLiteral( "ComposerMap" ) ); for ( int i = 0; i < composerMapList.size(); ++i ) { QDomElement currentComposerMapElem = composerMapList.at( i ).toElement(); @@ -1234,7 +1234,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } // arrow - QDomNodeList composerArrowList = elem.elementsByTagName( "ComposerArrow" ); + QDomNodeList composerArrowList = elem.elementsByTagName( QStringLiteral( "ComposerArrow" ) ); for ( int i = 0; i < composerArrowList.size(); ++i ) { QDomElement currentComposerArrowElem = composerArrowList.at( i ).toElement(); @@ -1262,7 +1262,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } } // scalebar - QDomNodeList composerScaleBarList = elem.elementsByTagName( "ComposerScaleBar" ); + QDomNodeList composerScaleBarList = elem.elementsByTagName( QStringLiteral( "ComposerScaleBar" ) ); for ( int i = 0; i < composerScaleBarList.size(); ++i ) { QDomElement currentComposerScaleBarElem = composerScaleBarList.at( i ).toElement(); @@ -1290,7 +1290,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } } // shape - QDomNodeList composerShapeList = elem.elementsByTagName( "ComposerShape" ); + QDomNodeList composerShapeList = elem.elementsByTagName( QStringLiteral( "ComposerShape" ) ); for ( int i = 0; i < composerShapeList.size(); ++i ) { QDomElement currentComposerShapeElem = composerShapeList.at( i ).toElement(); @@ -1321,7 +1321,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } // polygon - QDomNodeList composerPolygonList = elem.elementsByTagName( "ComposerPolygon" ); + QDomNodeList composerPolygonList = elem.elementsByTagName( QStringLiteral( "ComposerPolygon" ) ); for ( int i = 0; i < composerPolygonList.size(); ++i ) { QDomElement currentComposerPolygonElem = composerPolygonList.at( i ).toElement(); @@ -1352,7 +1352,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } // polyline - QDomNodeList addComposerPolylineList = elem.elementsByTagName( "ComposerPolyline" ); + QDomNodeList addComposerPolylineList = elem.elementsByTagName( QStringLiteral( "ComposerPolyline" ) ); for ( int i = 0; i < addComposerPolylineList.size(); ++i ) { QDomElement currentComposerPolylineElem = addComposerPolylineList.at( i ).toElement(); @@ -1383,7 +1383,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } // picture - QDomNodeList composerPictureList = elem.elementsByTagName( "ComposerPicture" ); + QDomNodeList composerPictureList = elem.elementsByTagName( QStringLiteral( "ComposerPicture" ) ); for ( int i = 0; i < composerPictureList.size(); ++i ) { QDomElement currentComposerPictureElem = composerPictureList.at( i ).toElement(); @@ -1411,7 +1411,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen } } // legend - QDomNodeList composerLegendList = elem.elementsByTagName( "ComposerLegend" ); + QDomNodeList composerLegendList = elem.elementsByTagName( QStringLiteral( "ComposerLegend" ) ); for ( int i = 0; i < composerLegendList.size(); ++i ) { QDomElement currentComposerLegendElem = composerLegendList.at( i ).toElement(); @@ -1441,7 +1441,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen // html //TODO - fix this. pasting multiframe frame items has no effect - QDomNodeList composerHtmlList = elem.elementsByTagName( "ComposerHtml" ); + QDomNodeList composerHtmlList = elem.elementsByTagName( QStringLiteral( "ComposerHtml" ) ); for ( int i = 0; i < composerHtmlList.size(); ++i ) { QDomElement currentHtmlElem = composerHtmlList.at( i ).toElement(); @@ -1458,7 +1458,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen frame->setZValue( frame->zValue() + zOrderOffset ); }*/ } - QDomNodeList composerAttributeTableV2List = elem.elementsByTagName( "ComposerAttributeTableV2" ); + QDomNodeList composerAttributeTableV2List = elem.elementsByTagName( QStringLiteral( "ComposerAttributeTableV2" ) ); for ( int i = 0; i < composerAttributeTableV2List.size(); ++i ) { QDomElement currentTableElem = composerAttributeTableV2List.at( i ).toElement(); @@ -1479,7 +1479,7 @@ void QgsComposition::addItemsFromXml( const QDomElement& elem, const QDomDocumen // groups (must be last as it references uuids of above items) //TODO - pasted groups lose group properties, since the uuids of group items //changes - QDomNodeList groupList = elem.elementsByTagName( "ComposerItemGroup" ); + QDomNodeList groupList = elem.elementsByTagName( QStringLiteral( "ComposerItemGroup" ) ); for ( int i = 0; i < groupList.size(); ++i ) { QDomElement groupElem = groupList.at( i ).toElement(); @@ -1705,7 +1705,7 @@ void QgsComposition::alignSelectedItemsLeft() QList::iterator align_it = selectedItems.begin(); for ( ; align_it != selectedItems.end(); ++align_it ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *align_it )->setPos( minXCoordinate, ( *align_it )->pos().y() ); subcommand->saveAfterState(); @@ -1735,7 +1735,7 @@ void QgsComposition::alignSelectedItemsHCenter() QList::iterator align_it = selectedItems.begin(); for ( ; align_it != selectedItems.end(); ++align_it ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *align_it )->setPos( averageXCoord - ( *align_it )->rect().width() / 2.0, ( *align_it )->pos().y() ); subcommand->saveAfterState(); @@ -1765,7 +1765,7 @@ void QgsComposition::alignSelectedItemsRight() QList::iterator align_it = selectedItems.begin(); for ( ; align_it != selectedItems.end(); ++align_it ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *align_it )->setPos( maxXCoordinate - ( *align_it )->rect().width(), ( *align_it )->pos().y() ); subcommand->saveAfterState(); @@ -1794,7 +1794,7 @@ void QgsComposition::alignSelectedItemsTop() QList::iterator align_it = selectedItems.begin(); for ( ; align_it != selectedItems.end(); ++align_it ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *align_it )->setPos(( *align_it )->pos().x(), minYCoordinate ); subcommand->saveAfterState(); @@ -1822,7 +1822,7 @@ void QgsComposition::alignSelectedItemsVCenter() QList::iterator align_it = selectedItems.begin(); for ( ; align_it != selectedItems.end(); ++align_it ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *align_it )->setPos(( *align_it )->pos().x(), averageYCoord - ( *align_it )->rect().height() / 2 ); subcommand->saveAfterState(); @@ -1850,7 +1850,7 @@ void QgsComposition::alignSelectedItemsBottom() QList::iterator align_it = selectedItems.begin(); for ( ; align_it != selectedItems.end(); ++align_it ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *align_it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *align_it )->setPos(( *align_it )->pos().x(), maxYCoord - ( *align_it )->rect().height() ); subcommand->saveAfterState(); @@ -1866,7 +1866,7 @@ void QgsComposition::lockSelectedItems() QList::iterator itemIter = selectionList.begin(); for ( ; itemIter != selectionList.end(); ++itemIter ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( *itemIter, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); ( *itemIter )->setPositionLock( true ); subcommand->saveAfterState(); @@ -1893,7 +1893,7 @@ void QgsComposition::unlockAllItems() QgsComposerItem* mypItem = dynamic_cast( *itemIt ); if ( mypItem && mypItem->positionLock() ) { - QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( mypItem, "", parentCommand ); + QgsComposerItemCommand* subcommand = new QgsComposerItemCommand( mypItem, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); mypItem->setPositionLock( false ); //select unlocked items, same behaviour as illustrator @@ -1993,7 +1993,7 @@ void QgsComposition::updateZValues( const bool addUndoCommands ) QgsComposerItemCommand* subcommand = nullptr; if ( addUndoCommands ) { - subcommand = new QgsComposerItemCommand( *it, "", parentCommand ); + subcommand = new QgsComposerItemCommand( *it, QLatin1String( "" ), parentCommand ); subcommand->savePreviousState(); } currentItem->setZValue( counter ); @@ -2302,23 +2302,23 @@ void QgsComposition::loadSettings() QSettings s; QString gridStyleString; - gridStyleString = s.value( "/Composer/gridStyle", "Dots" ).toString(); + gridStyleString = s.value( QStringLiteral( "/Composer/gridStyle" ), "Dots" ).toString(); int gridRed, gridGreen, gridBlue, gridAlpha; - gridRed = s.value( "/Composer/gridRed", 190 ).toInt(); - gridGreen = s.value( "/Composer/gridGreen", 190 ).toInt(); - gridBlue = s.value( "/Composer/gridBlue", 190 ).toInt(); - gridAlpha = s.value( "/Composer/gridAlpha", 100 ).toInt(); + gridRed = s.value( QStringLiteral( "/Composer/gridRed" ), 190 ).toInt(); + gridGreen = s.value( QStringLiteral( "/Composer/gridGreen" ), 190 ).toInt(); + gridBlue = s.value( QStringLiteral( "/Composer/gridBlue" ), 190 ).toInt(); + gridAlpha = s.value( QStringLiteral( "/Composer/gridAlpha" ), 100 ).toInt(); QColor gridColor = QColor( gridRed, gridGreen, gridBlue, gridAlpha ); mGridPen.setColor( gridColor ); mGridPen.setWidthF( 0 ); - if ( gridStyleString == "Dots" ) + if ( gridStyleString == QLatin1String( "Dots" ) ) { mGridStyle = Dots; } - else if ( gridStyleString == "Crosses" ) + else if ( gridStyleString == QLatin1String( "Crosses" ) ) { mGridStyle = Crosses; } @@ -2584,7 +2584,7 @@ void QgsComposition::removeComposerItem( QgsComposerItem* item, const bool creat { mItemsModel->setItemRemoved( *it ); removeItem( *it ); - QgsAddRemoveItemCommand* subcommand = new QgsAddRemoveItemCommand( QgsAddRemoveItemCommand::Removed, *it, this, "", parentCommand ); + QgsAddRemoveItemCommand* subcommand = new QgsAddRemoveItemCommand( QgsAddRemoveItemCommand::Removed, *it, this, QLatin1String( "" ), parentCommand ); connectAddRemoveCommandSignals( subcommand ); emit itemRemoved( *it ); } @@ -3120,11 +3120,11 @@ double* QgsComposition::computeGeoTransform( const QgsComposerMap* map, const QR QString QgsComposition::encodeStringForXml( const QString& str ) { QString modifiedStr( str ); - modifiedStr.replace( '&', "&" ); - modifiedStr.replace( '\"', """ ); - modifiedStr.replace( '\'', "'" ); - modifiedStr.replace( '<', "<" ); - modifiedStr.replace( '>', ">" ); + modifiedStr.replace( '&', QLatin1String( "&" ) ); + modifiedStr.replace( '\"', QLatin1String( """ ) ); + modifiedStr.replace( '\'', QLatin1String( "'" ) ); + modifiedStr.replace( '<', QLatin1String( "<" ) ); + modifiedStr.replace( '>', QLatin1String( ">" ) ); return modifiedStr; } @@ -3381,7 +3381,7 @@ void QgsComposition::setCustomProperty( const QString& key, const QVariant& valu { mCustomProperties.setValue( key, value ); - if ( key.startsWith( "variable" ) ) + if ( key.startsWith( QLatin1String( "variable" ) ) ) emit variablesChanged(); } diff --git a/src/core/composer/qgsdoubleboxscalebarstyle.cpp b/src/core/composer/qgsdoubleboxscalebarstyle.cpp index 2f820251410d..7588bbcd343c 100644 --- a/src/core/composer/qgsdoubleboxscalebarstyle.cpp +++ b/src/core/composer/qgsdoubleboxscalebarstyle.cpp @@ -37,7 +37,7 @@ QgsDoubleBoxScaleBarStyle::~QgsDoubleBoxScaleBarStyle() QString QgsDoubleBoxScaleBarStyle::name() const { - return "Double Box"; + return QStringLiteral( "Double Box" ); } void QgsDoubleBoxScaleBarStyle::draw( QPainter* p, double xOffset ) const diff --git a/src/core/composer/qgsnumericscalebarstyle.cpp b/src/core/composer/qgsnumericscalebarstyle.cpp index dbeb519b70e2..793351208a82 100644 --- a/src/core/composer/qgsnumericscalebarstyle.cpp +++ b/src/core/composer/qgsnumericscalebarstyle.cpp @@ -38,7 +38,7 @@ QgsNumericScaleBarStyle::~QgsNumericScaleBarStyle() QString QgsNumericScaleBarStyle::name() const { - return "Numeric"; + return QStringLiteral( "Numeric" ); } void QgsNumericScaleBarStyle::draw( QPainter* p, double xOffset ) const @@ -120,9 +120,9 @@ QString QgsNumericScaleBarStyle::scaleText() const if ( composerMap ) { scaleDenominator = composerMap->scale(); - scaleBarText = "1:" + QString( "%L1" ).arg( scaleDenominator, 0, 'f', 0 ); + scaleBarText = "1:" + QStringLiteral( "%L1" ).arg( scaleDenominator, 0, 'f', 0 ); } - scaleBarText = "1:" + QString( "%L1" ).arg( scaleDenominator, 0, 'f', 0 ); + scaleBarText = "1:" + QStringLiteral( "%L1" ).arg( scaleDenominator, 0, 'f', 0 ); } return scaleBarText; } diff --git a/src/core/composer/qgssingleboxscalebarstyle.cpp b/src/core/composer/qgssingleboxscalebarstyle.cpp index a9bd11b0feff..66dfa900b151 100644 --- a/src/core/composer/qgssingleboxscalebarstyle.cpp +++ b/src/core/composer/qgssingleboxscalebarstyle.cpp @@ -78,6 +78,6 @@ void QgsSingleBoxScaleBarStyle::draw( QPainter* p, double xOffset ) const QString QgsSingleBoxScaleBarStyle::name() const { - return "Single Box"; + return QStringLiteral( "Single Box" ); } diff --git a/src/core/composer/qgsticksscalebarstyle.cpp b/src/core/composer/qgsticksscalebarstyle.cpp index 9a654bbcc7a0..795708da3cb8 100644 --- a/src/core/composer/qgsticksscalebarstyle.cpp +++ b/src/core/composer/qgsticksscalebarstyle.cpp @@ -39,13 +39,13 @@ QString QgsTicksScaleBarStyle::name() const switch ( mTickPosition ) { case TicksUp: - return "Line Ticks Up"; + return QStringLiteral( "Line Ticks Up" ); case TicksDown: - return "Line Ticks Down"; + return QStringLiteral( "Line Ticks Down" ); case TicksMiddle: - return "Line Ticks Middle"; + return QStringLiteral( "Line Ticks Middle" ); } - return ""; // to make gcc happy + return QLatin1String( "" ); // to make gcc happy } void QgsTicksScaleBarStyle::draw( QPainter* p, double xOffset ) const diff --git a/src/core/dxf/qgsdxfexport.cpp b/src/core/dxf/qgsdxfexport.cpp index 22bf3c864ec2..d9dbd5cba5c4 100644 --- a/src/core/dxf/qgsdxfexport.cpp +++ b/src/core/dxf/qgsdxfexport.cpp @@ -461,19 +461,19 @@ void QgsDxfExport::writeGroup( const QColor& color, int exactMatchCode, int rgbC void QgsDxfExport::writeGroupCode( int code ) { - mTextStream << QString( "%1\n" ).arg( code, 3, 10, QChar( ' ' ) ); + mTextStream << QStringLiteral( "%1\n" ).arg( code, 3, 10, QChar( ' ' ) ); } void QgsDxfExport::writeInt( int i ) { - mTextStream << QString( "%1\n" ).arg( i, 6, 10, QChar( ' ' ) ); + mTextStream << QStringLiteral( "%1\n" ).arg( i, 6, 10, QChar( ' ' ) ); } void QgsDxfExport::writeDouble( double d ) { QString s( qgsDoubleToString( d ) ); if ( !s.contains( '.' ) ) - s += ".0"; + s += QLatin1String( ".0" ); mTextStream << s << '\n'; } @@ -541,43 +541,43 @@ int QgsDxfExport::writeToFile( QIODevice* d, const QString& encoding ) void QgsDxfExport::writeHeader( const QString& codepage ) { - writeGroup( 999, "DXF created from QGIS" ); + writeGroup( 999, QStringLiteral( "DXF created from QGIS" ) ); startSection(); - writeGroup( 2, "HEADER" ); + writeGroup( 2, QStringLiteral( "HEADER" ) ); // ACADVER - writeGroup( 9, "$ACADVER" ); - writeGroup( 1, "AC1015" ); + writeGroup( 9, QStringLiteral( "$ACADVER" ) ); + writeGroup( 1, QStringLiteral( "AC1015" ) ); // EXTMIN - writeGroup( 9, "$EXTMIN" ); + writeGroup( 9, QStringLiteral( "$EXTMIN" ) ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ, mExtent.xMinimum(), mExtent.yMinimum() ) ); // EXTMAX - writeGroup( 9, "$EXTMAX" ); + writeGroup( 9, QStringLiteral( "$EXTMAX" ) ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ, mExtent.xMaximum(), mExtent.yMaximum() ) ); // Global linetype scale - writeGroup( 9, "$LTSCALE" ); + writeGroup( 9, QStringLiteral( "$LTSCALE" ) ); writeGroup( 40, 1.0 ); // Point display mode (33 = circle) - writeGroup( 9, "$PDMODE" ); + writeGroup( 9, QStringLiteral( "$PDMODE" ) ); writeGroup( 70, 33 ); // Point display size - writeGroup( 9, "$PDSIZE" ); + writeGroup( 9, QStringLiteral( "$PDSIZE" ) ); writeGroup( 40, 1 ); // Controls paper space linetype scaling (1 = No special linetype scaling, 0 = Viewport scaling governs linetype scaling) - writeGroup( 9, "$PSLTSCALE" ); + writeGroup( 9, QStringLiteral( "$PSLTSCALE" ) ); writeGroup( 70, 0 ); - writeGroup( 9, "$HANDSEED" ); + writeGroup( 9, QStringLiteral( "$HANDSEED" ) ); writeGroup( 5, DXF_HANDMAX ); - writeGroup( 9, "$DWGCODEPAGE" ); + writeGroup( 9, QStringLiteral( "$DWGCODEPAGE" ) ); writeGroup( 3, codepage ); endSection(); @@ -590,14 +590,14 @@ int QgsDxfExport::writeHandle( int code, int handle ) Q_ASSERT_X( handle < DXF_HANDMAX, "QgsDxfExport::writeHandle(int, int)", "DXF handle too large" ); - writeGroup( code, QString( "%1" ).arg( handle, 0, 16 ) ); + writeGroup( code, QStringLiteral( "%1" ).arg( handle, 0, 16 ) ); return handle; } void QgsDxfExport::writeTables() { startSection(); - writeGroup( 2, "TABLES" ); + writeGroup( 2, QStringLiteral( "TABLES" ) ); // Iterate through all layers and get symbol layer pointers QgsRenderContext context = renderContext(); @@ -609,10 +609,10 @@ void QgsDxfExport::writeTables() // Line types mLineStyles.clear(); - writeGroup( 0, "TABLE" ); - writeGroup( 2, "LTYPE" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "LTYPE" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, nLineTypes( slList ) + 5 ); writeDefaultLinetypes(); @@ -624,22 +624,22 @@ void QgsDxfExport::writeTables() writeSymbolLayerLinetype( slIt->first ); } - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // BLOCK_RECORD - writeGroup( 0, "TABLE" ); - writeGroup( 2, "BLOCK_RECORD" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "BLOCK_RECORD" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, 0 ); Q_FOREACH ( const QString& block, QStringList() << "*Model_Space" << "*Paper_Space" << "*Paper_Space0" ) { - writeGroup( 0, "BLOCK_RECORD" ); + writeGroup( 0, QStringLiteral( "BLOCK_RECORD" ) ); mBlockHandles.insert( block, writeHandle() ); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbBlockTableRecord" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockTableRecord" ) ); writeGroup( 2, block ); } @@ -654,57 +654,57 @@ void QgsDxfExport::writeTables() if ( hasDataDefinedProperties( ml, slIt->second ) ) continue; - QString name = QString( "symbolLayer%1" ).arg( i++ ); - writeGroup( 0, "BLOCK_RECORD" ); + QString name = QStringLiteral( "symbolLayer%1" ).arg( i++ ); + writeGroup( 0, QStringLiteral( "BLOCK_RECORD" ) ); mBlockHandles.insert( name, writeHandle() ); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbBlockTableRecord" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockTableRecord" ) ); writeGroup( 2, name ); } - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // APPID - writeGroup( 0, "TABLE" ); - writeGroup( 2, "APPID" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "APPID" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, 1 ); - writeGroup( 0, "APPID" ); + writeGroup( 0, QStringLiteral( "APPID" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbRegAppTableRecord" ); - writeGroup( 2, "ACAD" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbRegAppTableRecord" ) ); + writeGroup( 2, QStringLiteral( "ACAD" ) ); writeGroup( 70, 0 ); - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // VIEW - writeGroup( 0, "TABLE" ); - writeGroup( 2, "VIEW" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "VIEW" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, 0 ); - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // UCS - writeGroup( 0, "TABLE" ); - writeGroup( 2, "UCS" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "UCS" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, 0 ); - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // VPORT - writeGroup( 0, "TABLE" ); - writeGroup( 2, "VPORT" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "VPORT" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); - writeGroup( 0, "VPORT" ); + writeGroup( 0, QStringLiteral( "VPORT" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbViewportTableRecord" ); - writeGroup( 2, "*ACTIVE" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbViewportTableRecord" ) ); + writeGroup( 2, QStringLiteral( "*ACTIVE" ) ); writeGroup( 70, 0 ); // flags writeGroup( 0, QgsPointV2( 0.0, 0.0 ) ); // lower left writeGroup( 1, QgsPointV2( 1.0, 1.0 ) ); // upper right @@ -738,16 +738,16 @@ void QgsDxfExport::writeTables() writeGroup( 146, 0.0 ); // Elevation writeGroup( 70, 0 ); - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // DIMSTYLE - writeGroup( 0, "TABLE" ); - writeGroup( 2, "DIMSTYLE" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "DIMSTYLE" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); - writeGroup( 100, "AcDbDimStyleTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); + writeGroup( 100, QStringLiteral( "AcDbDimStyleTable" ) ); writeGroup( 70, 0 ); - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); QList< QPair >::const_iterator layerIt = mLayers.constBegin(); QSet layerNames; @@ -776,59 +776,59 @@ void QgsDxfExport::writeTables() // Layers // TODO: iterate features of all layer to produce a data-defined layer list - writeGroup( 0, "TABLE" ); - writeGroup( 2, "LAYER" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "LAYER" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, layerNames.size() + 1 ); - writeGroup( 0, "LAYER" ); + writeGroup( 0, QStringLiteral( "LAYER" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbLayerTableRecord" ); - writeGroup( 2, "0" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbLayerTableRecord" ) ); + writeGroup( 2, QStringLiteral( "0" ) ); writeGroup( 70, 64 ); writeGroup( 62, 1 ); - writeGroup( 6, "CONTINUOUS" ); + writeGroup( 6, QStringLiteral( "CONTINUOUS" ) ); writeHandle( 390, DXF_HANDPLOTSTYLE ); Q_FOREACH ( const QString& layerName, layerNames ) { - writeGroup( 0, "LAYER" ); + writeGroup( 0, QStringLiteral( "LAYER" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbLayerTableRecord" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbLayerTableRecord" ) ); writeGroup( 2, layerName ); writeGroup( 70, 64 ); writeGroup( 62, 1 ); - writeGroup( 6, "CONTINUOUS" ); + writeGroup( 6, QStringLiteral( "CONTINUOUS" ) ); writeHandle( 390, DXF_HANDPLOTSTYLE ); } - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); // Text styles - writeGroup( 0, "TABLE" ); - writeGroup( 2, "STYLE" ); + writeGroup( 0, QStringLiteral( "TABLE" ) ); + writeGroup( 2, QStringLiteral( "STYLE" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTable" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTable" ) ); writeGroup( 70, 1 ); // Provide only standard font for the moment - writeGroup( 0, "STYLE" ); + writeGroup( 0, QStringLiteral( "STYLE" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbTextStyleTableRecord" ); - writeGroup( 2, "STANDARD" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbTextStyleTableRecord" ) ); + writeGroup( 2, QStringLiteral( "STANDARD" ) ); writeGroup( 70, 64 ); writeGroup( 40, 0.0 ); writeGroup( 41, 1.0 ); writeGroup( 50, 0.0 ); writeGroup( 71, 0 ); writeGroup( 42, 5.0 ); - writeGroup( 3, "romans.shx" ); - writeGroup( 4, "" ); + writeGroup( 3, QStringLiteral( "romans.shx" ) ); + writeGroup( 4, QLatin1String( "" ) ); - writeGroup( 0, "ENDTAB" ); + writeGroup( 0, QStringLiteral( "ENDTAB" ) ); endSection(); } @@ -836,26 +836,26 @@ void QgsDxfExport::writeTables() void QgsDxfExport::writeBlocks() { startSection(); - writeGroup( 2, "BLOCKS" ); + writeGroup( 2, QStringLiteral( "BLOCKS" ) ); Q_FOREACH ( const QString& block, QStringList() << "*Model_Space" << "*Paper_Space" << "*Paper_Space0" ) { - writeGroup( 0, "BLOCK" ); + writeGroup( 0, QStringLiteral( "BLOCK" ) ); writeHandle(); - writeGroup( 330, QString( "%1" ).arg( mBlockHandles[ block ], 0, 16 ) ); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 8, "0" ); - writeGroup( 100, "AcDbBlockBegin" ); + writeGroup( 330, QStringLiteral( "%1" ).arg( mBlockHandles[ block ], 0, 16 ) ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 8, QStringLiteral( "0" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockBegin" ) ); writeGroup( 2, block ); writeGroup( 70, 0 ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ ) ); writeGroup( 3, block ); - writeGroup( 1, "" ); - writeGroup( 0, "ENDBLK" ); + writeGroup( 1, QLatin1String( "" ) ); + writeGroup( 0, QStringLiteral( "ENDBLK" ) ); writeHandle(); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 8, "0" ); - writeGroup( 100, "AcDbBlockEnd" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 8, QStringLiteral( "0" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockEnd" ) ); } QgsRenderContext ct = renderContext(); @@ -885,15 +885,15 @@ void QgsDxfExport::writeBlocks() // ml->stopRender( ctx ); } - QString block( QString( "symbolLayer%1" ).arg( mBlockCounter++ ) ); - mBlockHandle = QString( "%1" ).arg( mBlockHandles[ block ], 0, 16 ); + QString block( QStringLiteral( "symbolLayer%1" ).arg( mBlockCounter++ ) ); + mBlockHandle = QStringLiteral( "%1" ).arg( mBlockHandles[ block ], 0, 16 ); - writeGroup( 0, "BLOCK" ); + writeGroup( 0, QStringLiteral( "BLOCK" ) ); writeHandle(); writeGroup( 330, mBlockHandle ); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 8, "0" ); - writeGroup( 100, "AcDbBlockBegin" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 8, QStringLiteral( "0" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockBegin" ) ); writeGroup( 2, block ); writeGroup( 70, 0 ); @@ -903,16 +903,16 @@ void QgsDxfExport::writeBlocks() // size *= mapUnitScaleFactor( mSymbologyScaleDenominator, ml->sizeUnit(), mMapUnits ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ ) ); writeGroup( 3, block ); - writeGroup( 1, "" ); + writeGroup( 1, QLatin1String( "" ) ); // maplayer 0 -> block receives layer from INSERT statement - ml->writeDxf( *this, mapUnitScaleFactor( mSymbologyScaleDenominator, ml->sizeUnit(), mMapUnits ), "0", ctx ); + ml->writeDxf( *this, mapUnitScaleFactor( mSymbologyScaleDenominator, ml->sizeUnit(), mMapUnits ), QStringLiteral( "0" ), ctx ); - writeGroup( 0, "ENDBLK" ); + writeGroup( 0, QStringLiteral( "ENDBLK" ) ); writeHandle(); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 8, "0" ); - writeGroup( 100, "AcDbBlockEnd" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 8, QStringLiteral( "0" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockEnd" ) ); mPointSymbolBlocks.insert( ml, block ); ml->stopRender( ctx ); @@ -924,9 +924,9 @@ void QgsDxfExport::writeBlocks() void QgsDxfExport::writeEntities() { startSection(); - writeGroup( 2, "ENTITIES" ); + writeGroup( 2, QStringLiteral( "ENTITIES" ) ); - mBlockHandle = QString( "%1" ).arg( mBlockHandles[ "*Model_Space" ], 0, 16 ); + mBlockHandle = QStringLiteral( "%1" ).arg( mBlockHandles[ QStringLiteral( "*Model_Space" )], 0, 16 ); QImage image( 10, 10, QImage::Format_ARGB32_Premultiplied ); image.setDotsPerMeterX( 96 / 25.4 * 1000 ); @@ -3341,17 +3341,17 @@ AcDbSavedByObjectVersion\n\ ENDSEC\n\ "; - writeGroup( 0, "EOF" ); + writeGroup( 0, QStringLiteral( "EOF" ) ); } void QgsDxfExport::startSection() { - writeGroup( 0, "SECTION" ); + writeGroup( 0, QStringLiteral( "SECTION" ) ); } void QgsDxfExport::endSection() { - writeGroup( 0, "ENDSEC" ); + writeGroup( 0, QStringLiteral( "ENDSEC" ) ); } void QgsDxfExport::writePoint( const QgsPointV2 &pt, const QString& layer, const QColor& color, QgsSymbolRenderContext &ctx, const QgsSymbolLayer* symbolLayer, const QgsSymbol* symbol, double angle ) @@ -3391,10 +3391,10 @@ void QgsDxfExport::writePoint( const QgsPointV2 &pt, const QString& layer, const else { // insert block reference - writeGroup( 0, "INSERT" ); + writeGroup( 0, QStringLiteral( "INSERT" ) ); writeHandle(); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 100, "AcDbBlockReference" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 100, QStringLiteral( "AcDbBlockReference" ) ); writeGroup( 8, layer ); writeGroup( 2, blockIt.value() ); // Block name writeGroup( 50, angle ); // angle @@ -3422,11 +3422,11 @@ void QgsDxfExport::writePolyline( const QgsPointSequence &line, const QString& l if ( !line.at( 0 ).is3D() ) { - writeGroup( 0, "LWPOLYLINE" ); + writeGroup( 0, QStringLiteral( "LWPOLYLINE" ) ); writeHandle(); writeGroup( 8, layer ); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 100, "AcDbPolyline" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 100, QStringLiteral( "AcDbPolyline" ) ); writeGroup( 6, lineStyleName ); writeGroup( color ); @@ -3439,35 +3439,35 @@ void QgsDxfExport::writePolyline( const QgsPointSequence &line, const QString& l } else { - writeGroup( 0, "POLYLINE" ); + writeGroup( 0, QStringLiteral( "POLYLINE" ) ); int plHandle = writeHandle(); writeGroup( 330, mBlockHandle ); - writeGroup( 100, "AcDbEntity" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); writeGroup( 8, layer ); writeGroup( 6, lineStyleName ); writeGroup( color ); - writeGroup( 100, "AcDb3dPolyline" ); + writeGroup( 100, QStringLiteral( "AcDb3dPolyline" ) ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ ) ); writeGroup( 70, 8 ); for ( int i = 0; i < n; i++ ) { - writeGroup( 0, "VERTEX" ); + writeGroup( 0, QStringLiteral( "VERTEX" ) ); writeHandle(); writeGroup( 330, plHandle ); - writeGroup( 100, "AcDbEntity" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); writeGroup( 8, layer ); writeGroup( color ); - writeGroup( 100, "AcDbVertex" ); - writeGroup( 100, "AcDb3dPolylineVertex" ); + writeGroup( 100, QStringLiteral( "AcDbVertex" ) ); + writeGroup( 100, QStringLiteral( "AcDb3dPolylineVertex" ) ); writeGroup( 0, line[i] ); writeGroup( 70, 32 ); } - writeGroup( 0, "SEQEND" ); + writeGroup( 0, QStringLiteral( "SEQEND" ) ); writeHandle(); writeGroup( 330, plHandle ); - writeGroup( 100, "AcDbEntity" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); writeGroup( 8, layer ); writeGroup( color ); } @@ -3475,19 +3475,19 @@ void QgsDxfExport::writePolyline( const QgsPointSequence &line, const QString& l void QgsDxfExport::writePolygon( const QgsRingSequence &polygon, const QString& layer, const QString& hatchPattern, const QColor& color ) { - writeGroup( 0, "HATCH" ); // Entity type + writeGroup( 0, QStringLiteral( "HATCH" ) ); // Entity type writeHandle(); writeGroup( 330, mBlockHandle ); - writeGroup( 100, "AcDbEntity" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); writeGroup( 8, layer ); // Layer name writeGroup( color ); // Color - writeGroup( 100, "AcDbHatch" ); + writeGroup( 100, QStringLiteral( "AcDbHatch" ) ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ ) ); // Elevation point (in OCS) writeGroup( 200, QgsPointV2( QgsWkbTypes::PointZ, 0.0, 0.0, 1.0 ) ); writeGroup( 2, hatchPattern ); // Hatch pattern name - writeGroup( 70, hatchPattern == "SOLID" ); // Solid fill flag (solid fill = 1; pattern fill = 0) + writeGroup( 70, hatchPattern == QLatin1String( "SOLID" ) ); // Solid fill flag (solid fill = 1; pattern fill = 0) writeGroup( 71, 0 ); // Associativity flag (associative = 1; non-associative = 0) writeGroup( 91, polygon.size() ); // Number of boundary paths (loops) @@ -3519,10 +3519,10 @@ void QgsDxfExport::writeLine( const QgsPointV2& pt1, const QgsPointV2& pt2, cons void QgsDxfExport::writePoint( const QString& layer, const QColor& color, const QgsPointV2 &pt ) { - writeGroup( 0, "POINT" ); + writeGroup( 0, QStringLiteral( "POINT" ) ); writeHandle(); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 100, "AcDbPoint" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 100, QStringLiteral( "AcDbPoint" ) ); writeGroup( 8, layer ); writeGroup( color ); writeGroup( 0, pt ); @@ -3530,18 +3530,18 @@ void QgsDxfExport::writePoint( const QString& layer, const QColor& color, const void QgsDxfExport::writeFilledCircle( const QString &layer, const QColor& color, const QgsPointV2 &pt, double radius ) { - writeGroup( 0, "HATCH" ); // Entity type + writeGroup( 0, QStringLiteral( "HATCH" ) ); // Entity type writeHandle(); writeGroup( 330, mBlockHandle ); - writeGroup( 100, "AcDbEntity" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); writeGroup( 8, layer ); // Layer name writeGroup( color ); // Color (0 by block, 256 by layer) - writeGroup( 100, "AcDbHatch" ); + writeGroup( 100, QStringLiteral( "AcDbHatch" ) ); writeGroup( 0, QgsPointV2( QgsWkbTypes::PointZ ) ); // Elevation point (in OCS) writeGroup( 200, QgsPointV2( QgsWkbTypes::PointZ, 0.0, 0.0, 1.0 ) ); - writeGroup( 2, "SOLID" ); // Hatch pattern name + writeGroup( 2, QStringLiteral( "SOLID" ) ); // Hatch pattern name writeGroup( 70, 1 ); // Solid fill flag (solid fill = 1; pattern fill = 0) writeGroup( 71, 0 ); // Associativity flag (associative = 1; non-associative = 0) @@ -3567,12 +3567,12 @@ void QgsDxfExport::writeFilledCircle( const QString &layer, const QColor& color, void QgsDxfExport::writeCircle( const QString& layer, const QColor& color, const QgsPointV2 &pt, double radius, const QString &lineStyleName, double width ) { - writeGroup( 0, "LWPOLYLINE" ); + writeGroup( 0, QStringLiteral( "LWPOLYLINE" ) ); writeHandle(); writeGroup( 330, mBlockHandle ); writeGroup( 8, layer ); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 100, "AcDbPolyline" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 100, QStringLiteral( "AcDbPolyline" ) ); writeGroup( 6, lineStyleName ); writeGroup( color ); @@ -3589,17 +3589,17 @@ void QgsDxfExport::writeCircle( const QString& layer, const QColor& color, const void QgsDxfExport::writeText( const QString& layer, const QString& text, const QgsPointV2 &pt, double size, double angle, const QColor& color ) { - writeGroup( 0, "TEXT" ); + writeGroup( 0, QStringLiteral( "TEXT" ) ); writeHandle(); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 100, "AcDbText" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 100, QStringLiteral( "AcDbText" ) ); writeGroup( 8, layer ); writeGroup( color ); writeGroup( 0, pt ); writeGroup( 40, size ); writeGroup( 1, text ); writeGroup( 50, angle ); - writeGroup( 7, "STANDARD" ); // so far only support for standard font + writeGroup( 7, QStringLiteral( "STANDARD" ) ); // so far only support for standard font } void QgsDxfExport::writeMText( const QString& layer, const QString& text, const QgsPointV2 &pt, double width, double angle, const QColor& color ) @@ -3611,10 +3611,10 @@ void QgsDxfExport::writeMText( const QString& layer, const QString& text, const return; } - writeGroup( 0, "MTEXT" ); + writeGroup( 0, QStringLiteral( "MTEXT" ) ); writeHandle(); - writeGroup( 100, "AcDbEntity" ); - writeGroup( 100, "AcDbMText" ); + writeGroup( 100, QStringLiteral( "AcDbEntity" ) ); + writeGroup( 100, QStringLiteral( "AcDbMText" ) ); writeGroup( 8, layer ); writeGroup( color ); @@ -3637,7 +3637,7 @@ void QgsDxfExport::writeMText( const QString& layer, const QString& text, const // 7 8 9 writeGroup( 71, 7 ); - writeGroup( 7, "STANDARD" ); // so far only support for standard font + writeGroup( 7, QStringLiteral( "STANDARD" ) ); // so far only support for standard font } void QgsDxfExport::addFeature( QgsSymbolRenderContext& ctx, const QgsCoordinateTransform& ct, const QString& layer, const QgsSymbolLayer* symbolLayer, const QgsSymbol* symbol ) @@ -3682,7 +3682,7 @@ void QgsDxfExport::addFeature( QgsSymbolRenderContext& ctx, const QgsCoordinateT offset = 0.0; } - QString lineStyleName = "CONTINUOUS"; + QString lineStyleName = QStringLiteral( "CONTINUOUS" ); if ( mSymbologyExport != NoSymbology ) { lineStyleName = lineStyleFromSymbolLayer( symbolLayer ); @@ -3816,7 +3816,7 @@ void QgsDxfExport::addFeature( QgsSymbolRenderContext& ctx, const QgsCoordinateT tempGeom = tempGeom->segmentize(); FALLTHROUGH; case QgsWkbTypes::Polygon: - writePolygon( tempGeom->coordinateSequence().at( 0 ), layer, "SOLID", brushColor ); + writePolygon( tempGeom->coordinateSequence().at( 0 ), layer, QStringLiteral( "SOLID" ), brushColor ); break; case QgsWkbTypes::MultiPolygon: @@ -3824,7 +3824,7 @@ void QgsDxfExport::addFeature( QgsSymbolRenderContext& ctx, const QgsCoordinateT const QgsCoordinateSequence &cs = geom->coordinateSequence(); for ( int i = 0; i < cs.size(); i++ ) { - writePolygon( cs.at( i ), layer, "SOLID", brushColor ); + writePolygon( cs.at( i ), layer, QStringLiteral( "SOLID" ), brushColor ); } break; } @@ -3849,7 +3849,7 @@ QColor QgsDxfExport::colorFromSymbolLayer( const QgsSymbolLayer* symbolLayer, Qg QString QgsDxfExport::lineStyleFromSymbolLayer( const QgsSymbolLayer* symbolLayer ) { - QString lineStyleName = "CONTINUOUS"; + QString lineStyleName = QStringLiteral( "CONTINUOUS" ); if ( !symbolLayer ) { return lineStyleName; @@ -3975,13 +3975,13 @@ void QgsDxfExport::writeDefaultLinetypes() // continuous (Qt solid line) Q_FOREACH ( const QString& ltype, QStringList() << "ByLayer" << "ByBlock" << "CONTINUOUS" ) { - writeGroup( 0, "LTYPE" ); + writeGroup( 0, QStringLiteral( "LTYPE" ) ); writeHandle(); - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbLinetypeTableRecord" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbLinetypeTableRecord" ) ); writeGroup( 2, ltype ); writeGroup( 70, 64 ); - writeGroup( 3, "Defaultstyle" ); + writeGroup( 3, QStringLiteral( "Defaultstyle" ) ); writeGroup( 72, 65 ); writeGroup( 73, 0 ); writeGroup( 40, 0.0 ); @@ -3994,19 +3994,19 @@ void QgsDxfExport::writeDefaultLinetypes() QVector dashVector( 2 ); dashVector[0] = das; dashVector[1] = dss; - writeLinetype( "DASH", dashVector, QgsUnitTypes::RenderMapUnits ); + writeLinetype( QStringLiteral( "DASH" ), dashVector, QgsUnitTypes::RenderMapUnits ); QVector dotVector( 2 ); dotVector[0] = dos; dotVector[1] = dss; - writeLinetype( "DOT", dotVector, QgsUnitTypes::RenderMapUnits ); + writeLinetype( QStringLiteral( "DOT" ), dotVector, QgsUnitTypes::RenderMapUnits ); QVector dashDotVector( 4 ); dashDotVector[0] = das; dashDotVector[1] = dss; dashDotVector[2] = dos; dashDotVector[3] = dss; - writeLinetype( "DASHDOT", dashDotVector, QgsUnitTypes::RenderMapUnits ); + writeLinetype( QStringLiteral( "DASHDOT" ), dashDotVector, QgsUnitTypes::RenderMapUnits ); QVector dashDotDotVector( 6 ); dashDotDotVector[0] = das; @@ -4015,7 +4015,7 @@ void QgsDxfExport::writeDefaultLinetypes() dashDotDotVector[3] = dss; dashDotDotVector[4] = dos; dashDotDotVector[5] = dss; - writeLinetype( "DASHDOTDOT", dashDotDotVector, QgsUnitTypes::RenderMapUnits ); + writeLinetype( QStringLiteral( "DASHDOTDOT" ), dashDotDotVector, QgsUnitTypes::RenderMapUnits ); } void QgsDxfExport::writeSymbolLayerLinetype( const QgsSymbolLayer* symbolLayer ) @@ -4029,7 +4029,7 @@ void QgsDxfExport::writeSymbolLayerLinetype( const QgsSymbolLayer* symbolLayer ) QVector customLinestyle = symbolLayer->dxfCustomDashPattern( unit ); if ( !customLinestyle.isEmpty() ) { - QString name = QString( "symbolLayer%1" ).arg( mSymbolLayerCounter++ ); + QString name = QStringLiteral( "symbolLayer%1" ).arg( mSymbolLayerCounter++ ); writeLinetype( name, customLinestyle, unit ); mLineStyles.insert( symbolLayer, name ); } @@ -4062,14 +4062,14 @@ void QgsDxfExport::writeLinetype( const QString& styleName, const QVector length += ( *dashIt * mapUnitScaleFactor( mSymbologyScaleDenominator, u, mMapUnits ) ); } - writeGroup( 0, "LTYPE" ); + writeGroup( 0, QStringLiteral( "LTYPE" ) ); writeHandle(); // 330 5 - writeGroup( 100, "AcDbSymbolTableRecord" ); - writeGroup( 100, "AcDbLinetypeTableRecord" ); + writeGroup( 100, QStringLiteral( "AcDbSymbolTableRecord" ) ); + writeGroup( 100, QStringLiteral( "AcDbLinetypeTableRecord" ) ); writeGroup( 2, styleName ); writeGroup( 70, 64 ); // 0? - writeGroup( 3, "" ); + writeGroup( 3, QLatin1String( "" ) ); writeGroup( 72, 65 ); writeGroup( 73, pattern.size() ); writeGroup( 40, length ); @@ -4131,23 +4131,23 @@ QString QgsDxfExport::lineNameFromPenStyle( Qt::PenStyle style ) switch ( style ) { case Qt::DashLine: - return "DASH"; + return QStringLiteral( "DASH" ); case Qt::DotLine: - return "DOT"; + return QStringLiteral( "DOT" ); case Qt::DashDotLine: - return "DASHDOT"; + return QStringLiteral( "DASHDOT" ); case Qt::DashDotDotLine: - return "DASHDOTDOT"; + return QStringLiteral( "DASHDOTDOT" ); case Qt::SolidLine: default: - return "CONTINUOUS"; + return QStringLiteral( "CONTINUOUS" ); } } QString QgsDxfExport::dxfLayerName( const QString& name ) { if ( name.isEmpty() ) - return "0"; + return QStringLiteral( "0" ); // dxf layers can be max 255 characters long QString layerName = name.left( 255 ); @@ -4169,7 +4169,7 @@ QString QgsDxfExport::dxfLayerName( const QString& name ) layerName.replace( '\'', '_' ); // also remove newline characters (#15067) - layerName.replace( "\r\n", "_" ); + layerName.replace( QLatin1String( "\r\n" ), QLatin1String( "_" ) ); layerName.replace( '\r', '_' ); layerName.replace( '\n', '_' ); @@ -4198,7 +4198,7 @@ QString QgsDxfExport::layerName( const QString &id, const QgsFeature &f ) const } } - return "0"; + return QStringLiteral( "0" ); } QString QgsDxfExport::dxfEncoding( const QString &name ) @@ -4306,7 +4306,7 @@ void QgsDxfExport::drawLabel( const QString& layerId, QgsRenderContext& context, QgsFeatureId fid = label->getFeaturePart()->featureId(); QString dxfLayer = mDxfLayerNames[layerId][fid]; - QString wrapchr = tmpLyr.wrapChar.isEmpty() ? "\n" : tmpLyr.wrapChar; + QString wrapchr = tmpLyr.wrapChar.isEmpty() ? QStringLiteral( "\n" ) : tmpLyr.wrapChar; //add the direction symbol if needed if ( !txt.isEmpty() && tmpLyr.placement == QgsPalLayerSettings::Line && tmpLyr.addDirectionSymbol ) @@ -4355,7 +4355,7 @@ void QgsDxfExport::drawLabel( const QString& layerId, QgsRenderContext& context, } } - txt = txt.replace( wrapchr, "\\P" ); + txt = txt.replace( wrapchr, QLatin1String( "\\P" ) ); if ( tmpLyr.format().font().underline() ) { @@ -4372,11 +4372,11 @@ void QgsDxfExport::drawLabel( const QString& layerId, QgsRenderContext& context, txt.prepend( "\\K" ).append( "\\k" ); } - txt.prepend( QString( "\\f%1|i%2|b%3;\\H%4;" ) + txt.prepend( QStringLiteral( "\\f%1|i%2|b%3;\\H%4;" ) .arg( tmpLyr.format().font().family() ) .arg( tmpLyr.format().font().italic() ? 1 : 0 ) .arg( tmpLyr.format().font().bold() ? 1 : 0 ) - .arg( label->getHeight() / ( 1 + txt.count( "\\P" ) ) * 0.75 ) ); + .arg( label->getHeight() / ( 1 + txt.count( QStringLiteral( "\\P" ) ) ) * 0.75 ) ); writeMText( dxfLayer, txt, QgsPointV2( label->getX(), label->getY() ), label->getWidth(), label->getAlpha() * 180.0 / M_PI, tmpLyr.format().color() ); } diff --git a/src/core/dxf/qgsdxfpaintengine.cpp b/src/core/dxf/qgsdxfpaintengine.cpp index 8746648e8d0c..0e92a1d5e68b 100644 --- a/src/core/dxf/qgsdxfpaintengine.cpp +++ b/src/core/dxf/qgsdxfpaintengine.cpp @@ -86,12 +86,12 @@ void QgsDxfPaintEngine::drawPolygon( const QPointF *points, int pointCount, Poly if ( mode == QPaintEngine::PolylineMode ) { if ( mPen.style() != Qt::NoPen && mPen.brush().style() != Qt::NoBrush ) - mDxf->writePolyline( polygon.at( 0 ), mLayer, "CONTINUOUS", mPen.color(), currentWidth() ); + mDxf->writePolyline( polygon.at( 0 ), mLayer, QStringLiteral( "CONTINUOUS" ), mPen.color(), currentWidth() ); } else { if ( mBrush.style() != Qt::NoBrush ) - mDxf->writePolygon( polygon, mLayer, "SOLID", mBrush.color() ); + mDxf->writePolygon( polygon, mLayer, QStringLiteral( "SOLID" ), mBrush.color() ); } } @@ -122,7 +122,7 @@ void QgsDxfPaintEngine::drawPath( const QPainterPath& path ) endPolygon(); if ( !mPolygon.isEmpty() && mBrush.style() != Qt::NoBrush ) - mDxf->writePolygon( mPolygon, mLayer, "SOLID", mBrush.color() ); + mDxf->writePolygon( mPolygon, mLayer, QStringLiteral( "SOLID" ), mBrush.color() ); mPolygon.clear(); } @@ -198,7 +198,7 @@ void QgsDxfPaintEngine::drawLines( const QLineF* lines, int lineCount ) { mDxf->writeLine( toDxfCoordinates( lines[i].p1() ), toDxfCoordinates( lines[i].p2() ), - mLayer, "CONTINUOUS", mPen.color(), currentWidth() ); + mLayer, QStringLiteral( "CONTINUOUS" ), mPen.color(), currentWidth() ); } } diff --git a/src/core/effects/qgsblureffect.cpp b/src/core/effects/qgsblureffect.cpp index cfe218389206..3f4625523980 100644 --- a/src/core/effects/qgsblureffect.cpp +++ b/src/core/effects/qgsblureffect.cpp @@ -86,36 +86,36 @@ void QgsBlurEffect::drawBlurredImage( QgsRenderContext& context, QImage& image ) QgsStringMap QgsBlurEffect::properties() const { QgsStringMap props; - props.insert( "enabled", mEnabled ? "1" : "0" ); - props.insert( "draw_mode", QString::number( static_cast< int >( mDrawMode ) ) ); - props.insert( "blend_mode", QString::number( static_cast< int >( mBlendMode ) ) ); - props.insert( "transparency", QString::number( mTransparency ) ); - props.insert( "blur_level", QString::number( mBlurLevel ) ); - props.insert( "blur_method", QString::number( static_cast< int >( mBlurMethod ) ) ); + props.insert( QStringLiteral( "enabled" ), mEnabled ? "1" : "0" ); + props.insert( QStringLiteral( "draw_mode" ), QString::number( static_cast< int >( mDrawMode ) ) ); + props.insert( QStringLiteral( "blend_mode" ), QString::number( static_cast< int >( mBlendMode ) ) ); + props.insert( QStringLiteral( "transparency" ), QString::number( mTransparency ) ); + props.insert( QStringLiteral( "blur_level" ), QString::number( mBlurLevel ) ); + props.insert( QStringLiteral( "blur_method" ), QString::number( static_cast< int >( mBlurMethod ) ) ); return props; } void QgsBlurEffect::readProperties( const QgsStringMap &props ) { bool ok; - QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( "blend_mode" ).toInt( &ok ) ); + QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( QStringLiteral( "blend_mode" ) ).toInt( &ok ) ); if ( ok ) { mBlendMode = mode; } - double transparency = props.value( "transparency" ).toDouble( &ok ); + double transparency = props.value( QStringLiteral( "transparency" ) ).toDouble( &ok ); if ( ok ) { mTransparency = transparency; } - mEnabled = props.value( "enabled", "1" ).toInt(); - mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( "draw_mode", "2" ).toInt() ); - int level = props.value( "blur_level" ).toInt( &ok ); + mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); + int level = props.value( QStringLiteral( "blur_level" ) ).toInt( &ok ); if ( ok ) { mBlurLevel = level; } - QgsBlurEffect::BlurMethod method = static_cast< QgsBlurEffect::BlurMethod >( props.value( "blur_method" ).toInt( &ok ) ); + QgsBlurEffect::BlurMethod method = static_cast< QgsBlurEffect::BlurMethod >( props.value( QStringLiteral( "blur_method" ) ).toInt( &ok ) ); if ( ok ) { mBlurMethod = method; diff --git a/src/core/effects/qgsblureffect.h b/src/core/effects/qgsblureffect.h index 6cc654f341d6..b05094692ebc 100644 --- a/src/core/effects/qgsblureffect.h +++ b/src/core/effects/qgsblureffect.h @@ -50,7 +50,7 @@ class CORE_EXPORT QgsBlurEffect : public QgsPaintEffect QgsBlurEffect(); virtual ~QgsBlurEffect(); - virtual QString type() const override { return QString( "blur" ); } + virtual QString type() const override { return QStringLiteral( "blur" ); } virtual QgsStringMap properties() const override; virtual void readProperties( const QgsStringMap& props ) override; virtual QgsBlurEffect* clone() const override; diff --git a/src/core/effects/qgscoloreffect.cpp b/src/core/effects/qgscoloreffect.cpp index f7cf1dd4bf19..a23df4a741bd 100644 --- a/src/core/effects/qgscoloreffect.cpp +++ b/src/core/effects/qgscoloreffect.cpp @@ -74,17 +74,17 @@ void QgsColorEffect::draw( QgsRenderContext &context ) QgsStringMap QgsColorEffect::properties() const { QgsStringMap props; - props.insert( "enabled", mEnabled ? "1" : "0" ); - props.insert( "draw_mode", QString::number( int( mDrawMode ) ) ); - props.insert( "blend_mode", QString::number( int( mBlendMode ) ) ); - props.insert( "transparency", QString::number( mTransparency ) ); - props.insert( "brightness", QString::number( mBrightness ) ); - props.insert( "contrast", QString::number( mContrast ) ); - props.insert( "saturation", QString::number( mSaturation ) ); - props.insert( "grayscale_mode", QString::number( int( mGrayscaleMode ) ) ); - props.insert( "colorize", mColorizeOn ? "1" : "0" ); - props.insert( "colorize_color", QgsSymbolLayerUtils::encodeColor( mColorizeColor ) ); - props.insert( "colorize_strength", QString::number( mColorizeStrength ) ); + props.insert( QStringLiteral( "enabled" ), mEnabled ? "1" : "0" ); + props.insert( QStringLiteral( "draw_mode" ), QString::number( int( mDrawMode ) ) ); + props.insert( QStringLiteral( "blend_mode" ), QString::number( int( mBlendMode ) ) ); + props.insert( QStringLiteral( "transparency" ), QString::number( mTransparency ) ); + props.insert( QStringLiteral( "brightness" ), QString::number( mBrightness ) ); + props.insert( QStringLiteral( "contrast" ), QString::number( mContrast ) ); + props.insert( QStringLiteral( "saturation" ), QString::number( mSaturation ) ); + props.insert( QStringLiteral( "grayscale_mode" ), QString::number( int( mGrayscaleMode ) ) ); + props.insert( QStringLiteral( "colorize" ), mColorizeOn ? "1" : "0" ); + props.insert( QStringLiteral( "colorize_color" ), QgsSymbolLayerUtils::encodeColor( mColorizeColor ) ); + props.insert( QStringLiteral( "colorize_strength" ), QString::number( mColorizeStrength ) ); return props; } @@ -92,29 +92,29 @@ QgsStringMap QgsColorEffect::properties() const void QgsColorEffect::readProperties( const QgsStringMap &props ) { bool ok; - QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( "blend_mode" ).toInt( &ok ) ); + QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( QStringLiteral( "blend_mode" ) ).toInt( &ok ) ); if ( ok ) { mBlendMode = mode; } - double transparency = props.value( "transparency" ).toDouble( &ok ); + double transparency = props.value( QStringLiteral( "transparency" ) ).toDouble( &ok ); if ( ok ) { mTransparency = transparency; } - mEnabled = props.value( "enabled", "1" ).toInt(); - mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( "draw_mode", "2" ).toInt() ); - - mBrightness = props.value( "brightness", "0" ).toInt(); - mContrast = props.value( "contrast", "0" ).toInt(); - mSaturation = props.value( "saturation", "1.0" ).toDouble(); - mGrayscaleMode = static_cast< QgsImageOperation::GrayscaleMode >( props.value( "grayscale_mode", "0" ).toInt() ); - mColorizeOn = props.value( "colorize", "0" ).toInt(); - if ( props.contains( "colorize_color" ) ) + mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); + + mBrightness = props.value( QStringLiteral( "brightness" ), QStringLiteral( "0" ) ).toInt(); + mContrast = props.value( QStringLiteral( "contrast" ), QStringLiteral( "0" ) ).toInt(); + mSaturation = props.value( QStringLiteral( "saturation" ), QStringLiteral( "1.0" ) ).toDouble(); + mGrayscaleMode = static_cast< QgsImageOperation::GrayscaleMode >( props.value( QStringLiteral( "grayscale_mode" ), QStringLiteral( "0" ) ).toInt() ); + mColorizeOn = props.value( QStringLiteral( "colorize" ), QStringLiteral( "0" ) ).toInt(); + if ( props.contains( QStringLiteral( "colorize_color" ) ) ) { - setColorizeColor( QgsSymbolLayerUtils::decodeColor( props.value( "colorize_color" ) ) ); + setColorizeColor( QgsSymbolLayerUtils::decodeColor( props.value( QStringLiteral( "colorize_color" ) ) ) ); } - mColorizeStrength = props.value( "colorize_strength", "100" ).toInt(); + mColorizeStrength = props.value( QStringLiteral( "colorize_strength" ), QStringLiteral( "100" ) ).toInt(); } QgsColorEffect* QgsColorEffect::clone() const diff --git a/src/core/effects/qgscoloreffect.h b/src/core/effects/qgscoloreffect.h index 4f4cbbd7705f..8a8e1b8a284d 100644 --- a/src/core/effects/qgscoloreffect.h +++ b/src/core/effects/qgscoloreffect.h @@ -44,7 +44,7 @@ class CORE_EXPORT QgsColorEffect : public QgsPaintEffect QgsColorEffect(); virtual ~QgsColorEffect(); - virtual QString type() const override { return QString( "color" ); } + virtual QString type() const override { return QStringLiteral( "color" ); } virtual QgsStringMap properties() const override; virtual void readProperties( const QgsStringMap& props ) override; virtual QgsColorEffect* clone() const override; diff --git a/src/core/effects/qgseffectstack.cpp b/src/core/effects/qgseffectstack.cpp index a438d9f4d47a..a591a509f077 100644 --- a/src/core/effects/qgseffectstack.cpp +++ b/src/core/effects/qgseffectstack.cpp @@ -88,7 +88,7 @@ void QgsEffectStack::draw( QgsRenderContext &context ) } QPicture* pic; - if ( effect->type() == "drawSource" ) + if ( effect->type() == QLatin1String( "drawSource" ) ) { //draw source is always the original source, regardless of previous effect results pic = sourcePic; @@ -152,9 +152,9 @@ bool QgsEffectStack::saveProperties( QDomDocument &doc, QDomElement &element ) c return false; } - QDomElement effectElement = doc.createElement( "effect" ); - effectElement.setAttribute( QString( "type" ), type() ); - effectElement.setAttribute( QString( "enabled" ), mEnabled ); + QDomElement effectElement = doc.createElement( QStringLiteral( "effect" ) ); + effectElement.setAttribute( QStringLiteral( "type" ), type() ); + effectElement.setAttribute( QStringLiteral( "enabled" ), mEnabled ); bool ok = true; Q_FOREACH ( QgsPaintEffect* effect, mEffectList ) @@ -174,7 +174,7 @@ bool QgsEffectStack::readProperties( const QDomElement &element ) return false; } - mEnabled = ( element.attribute( "enabled", "0" ) != "0" ); + mEnabled = ( element.attribute( QStringLiteral( "enabled" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); clearStack(); diff --git a/src/core/effects/qgseffectstack.h b/src/core/effects/qgseffectstack.h index bf69fc4b9d74..ae581e0222a6 100644 --- a/src/core/effects/qgseffectstack.h +++ b/src/core/effects/qgseffectstack.h @@ -62,7 +62,7 @@ class CORE_EXPORT QgsEffectStack : public QgsPaintEffect virtual ~QgsEffectStack(); - virtual QString type() const override { return QString( "effectStack" ); } + virtual QString type() const override { return QStringLiteral( "effectStack" ); } virtual QgsEffectStack* clone() const override; virtual bool saveProperties( QDomDocument& doc, QDomElement& element ) const override; virtual bool readProperties( const QDomElement& element ) override; diff --git a/src/core/effects/qgsgloweffect.cpp b/src/core/effects/qgsgloweffect.cpp index f8ee4ffe5a65..d960b4d0224d 100644 --- a/src/core/effects/qgsgloweffect.cpp +++ b/src/core/effects/qgsgloweffect.cpp @@ -118,16 +118,16 @@ void QgsGlowEffect::draw( QgsRenderContext &context ) QgsStringMap QgsGlowEffect::properties() const { QgsStringMap props; - props.insert( "enabled", mEnabled ? "1" : "0" ); - props.insert( "draw_mode", QString::number( int( mDrawMode ) ) ); - props.insert( "blend_mode", QString::number( int( mBlendMode ) ) ); - props.insert( "transparency", QString::number( mTransparency ) ); - props.insert( "blur_level", QString::number( mBlurLevel ) ); - props.insert( "spread", QString::number( mSpread ) ); - props.insert( "spread_unit", QgsUnitTypes::encodeUnit( mSpreadUnit ) ); - props.insert( "spread_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mSpreadMapUnitScale ) ); - props.insert( "color_type", QString::number( static_cast< int >( mColorType ) ) ); - props.insert( "single_color", QgsSymbolLayerUtils::encodeColor( mColor ) ); + props.insert( QStringLiteral( "enabled" ), mEnabled ? "1" : "0" ); + props.insert( QStringLiteral( "draw_mode" ), QString::number( int( mDrawMode ) ) ); + props.insert( QStringLiteral( "blend_mode" ), QString::number( int( mBlendMode ) ) ); + props.insert( QStringLiteral( "transparency" ), QString::number( mTransparency ) ); + props.insert( QStringLiteral( "blur_level" ), QString::number( mBlurLevel ) ); + props.insert( QStringLiteral( "spread" ), QString::number( mSpread ) ); + props.insert( QStringLiteral( "spread_unit" ), QgsUnitTypes::encodeUnit( mSpreadUnit ) ); + props.insert( QStringLiteral( "spread_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mSpreadMapUnitScale ) ); + props.insert( QStringLiteral( "color_type" ), QString::number( static_cast< int >( mColorType ) ) ); + props.insert( QStringLiteral( "single_color" ), QgsSymbolLayerUtils::encodeColor( mColor ) ); if ( mRamp ) { @@ -140,38 +140,38 @@ QgsStringMap QgsGlowEffect::properties() const void QgsGlowEffect::readProperties( const QgsStringMap &props ) { bool ok; - QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( "blend_mode" ).toInt( &ok ) ); + QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( QStringLiteral( "blend_mode" ) ).toInt( &ok ) ); if ( ok ) { mBlendMode = mode; } - double transparency = props.value( "transparency" ).toDouble( &ok ); + double transparency = props.value( QStringLiteral( "transparency" ) ).toDouble( &ok ); if ( ok ) { mTransparency = transparency; } - mEnabled = props.value( "enabled", "1" ).toInt(); - mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( "draw_mode", "2" ).toInt() ); - int level = props.value( "blur_level" ).toInt( &ok ); + mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); + int level = props.value( QStringLiteral( "blur_level" ) ).toInt( &ok ); if ( ok ) { mBlurLevel = level; } - double spread = props.value( "spread" ).toDouble( &ok ); + double spread = props.value( QStringLiteral( "spread" ) ).toDouble( &ok ); if ( ok ) { mSpread = spread; } - mSpreadUnit = QgsUnitTypes::decodeRenderUnit( props.value( "spread_unit" ) ); - mSpreadMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( props.value( "spread_unit_scale" ) ); - QgsGlowEffect::GlowColorType type = static_cast< QgsGlowEffect::GlowColorType >( props.value( "color_type" ).toInt( &ok ) ); + mSpreadUnit = QgsUnitTypes::decodeRenderUnit( props.value( QStringLiteral( "spread_unit" ) ) ); + mSpreadMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( props.value( QStringLiteral( "spread_unit_scale" ) ) ); + QgsGlowEffect::GlowColorType type = static_cast< QgsGlowEffect::GlowColorType >( props.value( QStringLiteral( "color_type" ) ).toInt( &ok ) ); if ( ok ) { mColorType = type; } - if ( props.contains( "single_color" ) ) + if ( props.contains( QStringLiteral( "single_color" ) ) ) { - mColor = QgsSymbolLayerUtils::decodeColor( props.value( "single_color" ) ); + mColor = QgsSymbolLayerUtils::decodeColor( props.value( QStringLiteral( "single_color" ) ) ); } //attempt to create color ramp from props diff --git a/src/core/effects/qgsgloweffect.h b/src/core/effects/qgsgloweffect.h index d7661bade7ac..779196d589be 100644 --- a/src/core/effects/qgsgloweffect.h +++ b/src/core/effects/qgsgloweffect.h @@ -242,7 +242,7 @@ class CORE_EXPORT QgsOuterGlowEffect : public QgsGlowEffect QgsOuterGlowEffect(); virtual ~QgsOuterGlowEffect(); - virtual QString type() const override { return QString( "outerGlow" ); } + virtual QString type() const override { return QStringLiteral( "outerGlow" ); } virtual QgsOuterGlowEffect* clone() const override; protected: @@ -273,7 +273,7 @@ class CORE_EXPORT QgsInnerGlowEffect : public QgsGlowEffect QgsInnerGlowEffect(); virtual ~QgsInnerGlowEffect(); - virtual QString type() const override { return QString( "innerGlow" ); } + virtual QString type() const override { return QStringLiteral( "innerGlow" ); } virtual QgsInnerGlowEffect* clone() const override; protected: diff --git a/src/core/effects/qgspainteffect.cpp b/src/core/effects/qgspainteffect.cpp index 258fa8ef5747..b2643b3cac01 100644 --- a/src/core/effects/qgspainteffect.cpp +++ b/src/core/effects/qgspainteffect.cpp @@ -79,15 +79,15 @@ bool QgsPaintEffect::saveProperties( QDomDocument &doc, QDomElement &element ) c return false; } - QDomElement effectElement = doc.createElement( "effect" ); - effectElement.setAttribute( QString( "type" ), type() ); + QDomElement effectElement = doc.createElement( QStringLiteral( "effect" ) ); + effectElement.setAttribute( QStringLiteral( "type" ), type() ); QgsStringMap props = properties(); for ( QgsStringMap::iterator it = props.begin(); it != props.end(); ++it ) { - QDomElement propEl = doc.createElement( "prop" ); - propEl.setAttribute( "k", it.key() ); - propEl.setAttribute( "v", it.value() ); + QDomElement propEl = doc.createElement( QStringLiteral( "prop" ) ); + propEl.setAttribute( QStringLiteral( "k" ), it.key() ); + propEl.setAttribute( QStringLiteral( "v" ), it.value() ); effectElement.appendChild( propEl ); } @@ -108,14 +108,14 @@ bool QgsPaintEffect::readProperties( const QDomElement &element ) QDomElement e = element.firstChildElement(); while ( !e.isNull() ) { - if ( e.tagName() != "prop" ) + if ( e.tagName() != QLatin1String( "prop" ) ) { QgsDebugMsg( "unknown tag " + e.tagName() ); } else { - QString propKey = e.attribute( "k" ); - QString propValue = e.attribute( "v" ); + QString propKey = e.attribute( QStringLiteral( "k" ) ); + QString propValue = e.attribute( QStringLiteral( "v" ) ); props[propKey] = propValue; } e = e.nextSiblingElement(); @@ -299,26 +299,26 @@ QgsDrawSourceEffect* QgsDrawSourceEffect::clone() const QgsStringMap QgsDrawSourceEffect::properties() const { QgsStringMap props; - props.insert( "enabled", mEnabled ? "1" : "0" ); - props.insert( "draw_mode", QString::number( int( mDrawMode ) ) ); - props.insert( "blend_mode", QString::number( int( mBlendMode ) ) ); - props.insert( "transparency", QString::number( mTransparency ) ); + props.insert( QStringLiteral( "enabled" ), mEnabled ? "1" : "0" ); + props.insert( QStringLiteral( "draw_mode" ), QString::number( int( mDrawMode ) ) ); + props.insert( QStringLiteral( "blend_mode" ), QString::number( int( mBlendMode ) ) ); + props.insert( QStringLiteral( "transparency" ), QString::number( mTransparency ) ); return props; } void QgsDrawSourceEffect::readProperties( const QgsStringMap &props ) { bool ok; - QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( "blend_mode" ).toInt( &ok ) ); + QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( QStringLiteral( "blend_mode" ) ).toInt( &ok ) ); if ( ok ) { mBlendMode = mode; } - double transparency = props.value( "transparency" ).toDouble( &ok ); + double transparency = props.value( QStringLiteral( "transparency" ) ).toDouble( &ok ); if ( ok ) { mTransparency = transparency; } - mEnabled = props.value( "enabled", "1" ).toInt(); - mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( "draw_mode", "2" ).toInt() ); + mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); } diff --git a/src/core/effects/qgspainteffect.h b/src/core/effects/qgspainteffect.h index 84b52c175972..60674195d937 100644 --- a/src/core/effects/qgspainteffect.h +++ b/src/core/effects/qgspainteffect.h @@ -266,7 +266,7 @@ class CORE_EXPORT QgsDrawSourceEffect : public QgsPaintEffect */ static QgsPaintEffect* create( const QgsStringMap& map ); - virtual QString type() const override { return QString( "drawSource" ); } + virtual QString type() const override { return QStringLiteral( "drawSource" ); } virtual QgsDrawSourceEffect* clone() const override; virtual QgsStringMap properties() const override; virtual void readProperties( const QgsStringMap& props ) override; diff --git a/src/core/effects/qgspainteffectregistry.cpp b/src/core/effects/qgspainteffectregistry.cpp index 382024f72156..2425fe7fbcda 100644 --- a/src/core/effects/qgspainteffectregistry.cpp +++ b/src/core/effects/qgspainteffectregistry.cpp @@ -31,23 +31,23 @@ QgsPaintEffectAbstractMetadata::QgsPaintEffectAbstractMetadata( const QString& n QgsPaintEffectRegistry::QgsPaintEffectRegistry() { //init registry with known effects - addEffectType( new QgsPaintEffectMetadata( "blur", QObject::tr( "Blur" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "blur" ), QObject::tr( "Blur" ), QgsBlurEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "dropShadow", QObject::tr( "Drop Shadow" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "dropShadow" ), QObject::tr( "Drop Shadow" ), QgsDropShadowEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "innerShadow", QObject::tr( "Inner Shadow" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "innerShadow" ), QObject::tr( "Inner Shadow" ), QgsInnerShadowEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "effectStack", QObject::tr( "Stack" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "effectStack" ), QObject::tr( "Stack" ), QgsEffectStack::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "outerGlow", QObject::tr( "Outer Glow" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "outerGlow" ), QObject::tr( "Outer Glow" ), QgsOuterGlowEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "innerGlow", QObject::tr( "Inner Glow" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "innerGlow" ), QObject::tr( "Inner Glow" ), QgsInnerGlowEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "drawSource", QObject::tr( "Source" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "drawSource" ), QObject::tr( "Source" ), QgsDrawSourceEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "transform", QObject::tr( "Transform" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "transform" ), QObject::tr( "Transform" ), QgsTransformEffect::create, nullptr ) ); - addEffectType( new QgsPaintEffectMetadata( "color", QObject::tr( "Colorise" ), + addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "color" ), QObject::tr( "Colorise" ), QgsColorEffect::create, nullptr ) ); } @@ -95,7 +95,7 @@ QgsPaintEffect *QgsPaintEffectRegistry::createEffect( const QDomElement &element return nullptr; } - QString type = element.attribute( QString( "type" ) ); + QString type = element.attribute( QStringLiteral( "type" ) ); QgsPaintEffect* effect = instance()->createEffect( type ); if ( !effect ) diff --git a/src/core/effects/qgsshadoweffect.cpp b/src/core/effects/qgsshadoweffect.cpp index bc734a54cceb..d289bd0e3189 100644 --- a/src/core/effects/qgsshadoweffect.cpp +++ b/src/core/effects/qgsshadoweffect.cpp @@ -96,54 +96,54 @@ void QgsShadowEffect::draw( QgsRenderContext &context ) QgsStringMap QgsShadowEffect::properties() const { QgsStringMap props; - props.insert( "enabled", mEnabled ? "1" : "0" ); - props.insert( "draw_mode", QString::number( int( mDrawMode ) ) ); - props.insert( "blend_mode", QString::number( int( mBlendMode ) ) ); - props.insert( "transparency", QString::number( mTransparency ) ); - props.insert( "blur_level", QString::number( mBlurLevel ) ); - props.insert( "offset_angle", QString::number( mOffsetAngle ) ); - props.insert( "offset_distance", QString::number( mOffsetDist ) ); - props.insert( "offset_unit", QgsUnitTypes::encodeUnit( mOffsetUnit ) ); - props.insert( "offset_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ) ); - props.insert( "color", QgsSymbolLayerUtils::encodeColor( mColor ) ); + props.insert( QStringLiteral( "enabled" ), mEnabled ? "1" : "0" ); + props.insert( QStringLiteral( "draw_mode" ), QString::number( int( mDrawMode ) ) ); + props.insert( QStringLiteral( "blend_mode" ), QString::number( int( mBlendMode ) ) ); + props.insert( QStringLiteral( "transparency" ), QString::number( mTransparency ) ); + props.insert( QStringLiteral( "blur_level" ), QString::number( mBlurLevel ) ); + props.insert( QStringLiteral( "offset_angle" ), QString::number( mOffsetAngle ) ); + props.insert( QStringLiteral( "offset_distance" ), QString::number( mOffsetDist ) ); + props.insert( QStringLiteral( "offset_unit" ), QgsUnitTypes::encodeUnit( mOffsetUnit ) ); + props.insert( QStringLiteral( "offset_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ) ); + props.insert( QStringLiteral( "color" ), QgsSymbolLayerUtils::encodeColor( mColor ) ); return props; } void QgsShadowEffect::readProperties( const QgsStringMap &props ) { bool ok; - QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( "blend_mode" ).toInt( &ok ) ); + QPainter::CompositionMode mode = static_cast< QPainter::CompositionMode >( props.value( QStringLiteral( "blend_mode" ) ).toInt( &ok ) ); if ( ok ) { mBlendMode = mode; } - double transparency = props.value( "transparency" ).toDouble( &ok ); + double transparency = props.value( QStringLiteral( "transparency" ) ).toDouble( &ok ); if ( ok ) { mTransparency = transparency; } - mEnabled = props.value( "enabled", "1" ).toInt(); - mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( "draw_mode", "2" ).toInt() ); - int level = props.value( "blur_level" ).toInt( &ok ); + mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); + int level = props.value( QStringLiteral( "blur_level" ) ).toInt( &ok ); if ( ok ) { mBlurLevel = level; } - int angle = props.value( "offset_angle" ).toInt( &ok ); + int angle = props.value( QStringLiteral( "offset_angle" ) ).toInt( &ok ); if ( ok ) { mOffsetAngle = angle; } - double distance = props.value( "offset_distance" ).toDouble( &ok ); + double distance = props.value( QStringLiteral( "offset_distance" ) ).toDouble( &ok ); if ( ok ) { mOffsetDist = distance; } - mOffsetUnit = QgsUnitTypes::decodeRenderUnit( props.value( "offset_unit" ) ); - mOffsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( props.value( "offset_unit_scale" ) ); - if ( props.contains( "color" ) ) + mOffsetUnit = QgsUnitTypes::decodeRenderUnit( props.value( QStringLiteral( "offset_unit" ) ) ); + mOffsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( props.value( QStringLiteral( "offset_unit_scale" ) ) ); + if ( props.contains( QStringLiteral( "color" ) ) ) { - mColor = QgsSymbolLayerUtils::decodeColor( props.value( "color" ) ); + mColor = QgsSymbolLayerUtils::decodeColor( props.value( QStringLiteral( "color" ) ) ); } } diff --git a/src/core/effects/qgsshadoweffect.h b/src/core/effects/qgsshadoweffect.h index a5a5e8d55907..75d2fb5139e1 100644 --- a/src/core/effects/qgsshadoweffect.h +++ b/src/core/effects/qgsshadoweffect.h @@ -200,7 +200,7 @@ class CORE_EXPORT QgsDropShadowEffect : public QgsShadowEffect QgsDropShadowEffect(); virtual ~QgsDropShadowEffect(); - virtual QString type() const override { return QString( "dropShadow" ); } + virtual QString type() const override { return QStringLiteral( "dropShadow" ); } virtual QgsDropShadowEffect* clone() const override; protected: @@ -230,7 +230,7 @@ class CORE_EXPORT QgsInnerShadowEffect : public QgsShadowEffect QgsInnerShadowEffect(); virtual ~QgsInnerShadowEffect(); - virtual QString type() const override { return QString( "innerShadow" ); } + virtual QString type() const override { return QStringLiteral( "innerShadow" ); } virtual QgsInnerShadowEffect* clone() const override; protected: diff --git a/src/core/effects/qgstransformeffect.cpp b/src/core/effects/qgstransformeffect.cpp index b705e158f9d2..a1cc6c38bd06 100644 --- a/src/core/effects/qgstransformeffect.cpp +++ b/src/core/effects/qgstransformeffect.cpp @@ -69,35 +69,35 @@ void QgsTransformEffect::draw( QgsRenderContext &context ) QgsStringMap QgsTransformEffect::properties() const { QgsStringMap props; - props.insert( "reflect_x", mReflectX ? "1" : "0" ); - props.insert( "reflect_y", mReflectY ? "1" : "0" ); - props.insert( "scale_x", QString::number( mScaleX ) ); - props.insert( "scale_y", QString::number( mScaleY ) ); - props.insert( "rotation", QString::number( mRotation ) ); - props.insert( "shear_x", QString::number( mShearX ) ); - props.insert( "shear_y", QString::number( mShearY ) ); - props.insert( "translate_x", QString::number( mTranslateX ) ); - props.insert( "translate_y", QString::number( mTranslateY ) ); - props.insert( "translate_unit", QgsUnitTypes::encodeUnit( mTranslateUnit ) ); - props.insert( "translate_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mTranslateMapUnitScale ) ); - props.insert( "enabled", mEnabled ? "1" : "0" ); - props.insert( "draw_mode", QString::number( int( mDrawMode ) ) ); + props.insert( QStringLiteral( "reflect_x" ), mReflectX ? "1" : "0" ); + props.insert( QStringLiteral( "reflect_y" ), mReflectY ? "1" : "0" ); + props.insert( QStringLiteral( "scale_x" ), QString::number( mScaleX ) ); + props.insert( QStringLiteral( "scale_y" ), QString::number( mScaleY ) ); + props.insert( QStringLiteral( "rotation" ), QString::number( mRotation ) ); + props.insert( QStringLiteral( "shear_x" ), QString::number( mShearX ) ); + props.insert( QStringLiteral( "shear_y" ), QString::number( mShearY ) ); + props.insert( QStringLiteral( "translate_x" ), QString::number( mTranslateX ) ); + props.insert( QStringLiteral( "translate_y" ), QString::number( mTranslateY ) ); + props.insert( QStringLiteral( "translate_unit" ), QgsUnitTypes::encodeUnit( mTranslateUnit ) ); + props.insert( QStringLiteral( "translate_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mTranslateMapUnitScale ) ); + props.insert( QStringLiteral( "enabled" ), mEnabled ? "1" : "0" ); + props.insert( QStringLiteral( "draw_mode" ), QString::number( int( mDrawMode ) ) ); return props; } void QgsTransformEffect::readProperties( const QgsStringMap &props ) { - mEnabled = props.value( "enabled", "1" ).toInt(); - mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( "draw_mode", "2" ).toInt() ); - mReflectX = props.value( "reflect_x", "0" ).toInt(); - mReflectY = props.value( "reflect_y", "0" ).toInt(); - mScaleX = props.value( "scale_x", "1.0" ).toDouble(); - mScaleY = props.value( "scale_y", "1.0" ).toDouble(); - mRotation = props.value( "rotation", "0.0" ).toDouble(); - mTranslateX = props.value( "translate_x", "0.0" ).toDouble(); - mTranslateY = props.value( "translate_y", "0.0" ).toDouble(); - mTranslateUnit = QgsUnitTypes::decodeRenderUnit( props.value( "translate_unit" ) ); - mTranslateMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( props.value( "translate_unit_scale" ) ); + mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); + mReflectX = props.value( QStringLiteral( "reflect_x" ), QStringLiteral( "0" ) ).toInt(); + mReflectY = props.value( QStringLiteral( "reflect_y" ), QStringLiteral( "0" ) ).toInt(); + mScaleX = props.value( QStringLiteral( "scale_x" ), QStringLiteral( "1.0" ) ).toDouble(); + mScaleY = props.value( QStringLiteral( "scale_y" ), QStringLiteral( "1.0" ) ).toDouble(); + mRotation = props.value( QStringLiteral( "rotation" ), QStringLiteral( "0.0" ) ).toDouble(); + mTranslateX = props.value( QStringLiteral( "translate_x" ), QStringLiteral( "0.0" ) ).toDouble(); + mTranslateY = props.value( QStringLiteral( "translate_y" ), QStringLiteral( "0.0" ) ).toDouble(); + mTranslateUnit = QgsUnitTypes::decodeRenderUnit( props.value( QStringLiteral( "translate_unit" ) ) ); + mTranslateMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( props.value( QStringLiteral( "translate_unit_scale" ) ) ); } QgsTransformEffect* QgsTransformEffect::clone() const diff --git a/src/core/effects/qgstransformeffect.h b/src/core/effects/qgstransformeffect.h index b0866019fd26..942adac0a57a 100644 --- a/src/core/effects/qgstransformeffect.h +++ b/src/core/effects/qgstransformeffect.h @@ -44,7 +44,7 @@ class CORE_EXPORT QgsTransformEffect : public QgsPaintEffect QgsTransformEffect(); virtual ~QgsTransformEffect(); - virtual QString type() const override { return QString( "transform" ); } + virtual QString type() const override { return QStringLiteral( "transform" ); } virtual QgsStringMap properties() const override; virtual void readProperties( const QgsStringMap& props ) override; virtual QgsTransformEffect* clone() const override; diff --git a/src/core/geometry/qgsabstractgeometry.h b/src/core/geometry/qgsabstractgeometry.h index 9db4b2f440d2..6f69bdaf36ba 100644 --- a/src/core/geometry/qgsabstractgeometry.h +++ b/src/core/geometry/qgsabstractgeometry.h @@ -168,7 +168,7 @@ class CORE_EXPORT QgsAbstractGeometry * @see asGML3 * @see asJSON */ - virtual QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const = 0; + virtual QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const = 0; /** Returns a GML3 representation of the geometry. * @param doc DOM document @@ -179,7 +179,7 @@ class CORE_EXPORT QgsAbstractGeometry * @see asGML2 * @see asJSON */ - virtual QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const = 0; + virtual QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const = 0; /** Returns a GeoJSON representation of the geometry. * @param precision number of decimal places for coordinates diff --git a/src/core/geometry/qgscircularstring.cpp b/src/core/geometry/qgscircularstring.cpp index 187706bfdd6e..d28e9f131ff0 100644 --- a/src/core/geometry/qgscircularstring.cpp +++ b/src/core/geometry/qgscircularstring.cpp @@ -303,9 +303,9 @@ QDomElement QgsCircularString::asGML3( QDomDocument& doc, int precision, const Q QgsPointSequence pts; points( pts ); - QDomElement elemCurve = doc.createElementNS( ns, "Curve" ); - QDomElement elemSegments = doc.createElementNS( ns, "segments" ); - QDomElement elemArcString = doc.createElementNS( ns, "ArcString" ); + QDomElement elemCurve = doc.createElementNS( ns, QStringLiteral( "Curve" ) ); + QDomElement elemSegments = doc.createElementNS( ns, QStringLiteral( "segments" ) ); + QDomElement elemArcString = doc.createElementNS( ns, QStringLiteral( "ArcString" ) ); elemArcString.appendChild( QgsGeometryUtils::pointsToGML3( pts, doc, precision, ns, is3D() ) ); elemSegments.appendChild( elemArcString ); elemCurve.appendChild( elemSegments ); diff --git a/src/core/geometry/qgscircularstring.h b/src/core/geometry/qgscircularstring.h index 7a3b3e3d4246..0fe51cf6920e 100644 --- a/src/core/geometry/qgscircularstring.h +++ b/src/core/geometry/qgscircularstring.h @@ -36,7 +36,7 @@ class CORE_EXPORT QgsCircularString: public QgsCurve virtual bool operator==( const QgsCurve& other ) const override; virtual bool operator!=( const QgsCurve& other ) const override; - virtual QString geometryType() const override { return "CircularString"; } + virtual QString geometryType() const override { return QStringLiteral( "CircularString" ); } virtual int dimension() const override { return 1; } virtual QgsCircularString* clone() const override; virtual void clear() override; @@ -47,8 +47,8 @@ class CORE_EXPORT QgsCircularString: public QgsCurve int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; int numPoints() const override; diff --git a/src/core/geometry/qgscompoundcurve.cpp b/src/core/geometry/qgscompoundcurve.cpp index d16e40ac85fe..5e6f26734ddf 100644 --- a/src/core/geometry/qgscompoundcurve.cpp +++ b/src/core/geometry/qgscompoundcurve.cpp @@ -154,7 +154,7 @@ bool QgsCompoundCurve::fromWkt( const QString& wkt ) return false; mWkbType = parts.first; - QString defaultChildWkbType = QString( "LineString%1%2" ).arg( is3D() ? "Z" : "", isMeasure() ? "M" : "" ); + QString defaultChildWkbType = QStringLiteral( "LineString%1%2" ).arg( is3D() ? "Z" : "", isMeasure() ? "M" : "" ); Q_FOREACH ( const QString& childWkt, QgsGeometryUtils::wktGetChildBlocks( parts.second, defaultChildWkbType ) ) { @@ -256,9 +256,9 @@ QDomElement QgsCompoundCurve::asGML2( QDomDocument& doc, int precision, const QS QDomElement QgsCompoundCurve::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemCurve = doc.createElementNS( ns, "Curve" ); + QDomElement elemCurve = doc.createElementNS( ns, QStringLiteral( "Curve" ) ); - QDomElement elemSegments = doc.createElementNS( ns, "segments" ); + QDomElement elemSegments = doc.createElementNS( ns, QStringLiteral( "segments" ) ); Q_FOREACH ( const QgsCurve* curve, mCurves ) { @@ -267,7 +267,7 @@ QDomElement QgsCompoundCurve::asGML3( QDomDocument& doc, int precision, const QS QgsPointSequence pts; curve->points( pts ); - QDomElement elemLineStringSegment = doc.createElementNS( ns, "LineStringSegment" ); + QDomElement elemLineStringSegment = doc.createElementNS( ns, QStringLiteral( "LineStringSegment" ) ); elemLineStringSegment.appendChild( QgsGeometryUtils::pointsToGML3( pts, doc, precision, ns, is3D() ) ); elemSegments.appendChild( elemLineStringSegment ); } @@ -276,7 +276,7 @@ QDomElement QgsCompoundCurve::asGML3( QDomDocument& doc, int precision, const QS QgsPointSequence pts; curve->points( pts ); - QDomElement elemArcString = doc.createElementNS( ns, "ArcString" ); + QDomElement elemArcString = doc.createElementNS( ns, QStringLiteral( "ArcString" ) ); elemArcString.appendChild( QgsGeometryUtils::pointsToGML3( pts, doc, precision, ns, is3D() ) ); elemSegments.appendChild( elemArcString ); } diff --git a/src/core/geometry/qgscompoundcurve.h b/src/core/geometry/qgscompoundcurve.h index a7100d7f42a5..8dc973ac4a3d 100644 --- a/src/core/geometry/qgscompoundcurve.h +++ b/src/core/geometry/qgscompoundcurve.h @@ -37,7 +37,7 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve virtual bool operator==( const QgsCurve& other ) const override; virtual bool operator!=( const QgsCurve& other ) const override; - virtual QString geometryType() const override { return "CompoundCurve"; } + virtual QString geometryType() const override { return QStringLiteral( "CompoundCurve" ); } virtual int dimension() const override { return 1; } virtual QgsCompoundCurve* clone() const override; virtual void clear() override; @@ -48,8 +48,8 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; //curve interface diff --git a/src/core/geometry/qgscurvepolygon.cpp b/src/core/geometry/qgscurvepolygon.cpp index 103bdb1549dc..6112a9582e99 100644 --- a/src/core/geometry/qgscurvepolygon.cpp +++ b/src/core/geometry/qgscurvepolygon.cpp @@ -155,7 +155,7 @@ bool QgsCurvePolygon::fromWkt( const QString& wkt ) mWkbType = parts.first; - QString defaultChildWkbType = QString( "LineString%1%2" ).arg( is3D() ? "Z" : "", isMeasure() ? "M" : "" ); + QString defaultChildWkbType = QStringLiteral( "LineString%1%2" ).arg( is3D() ? "Z" : "", isMeasure() ? "M" : "" ); Q_FOREACH ( const QString& childWkt, QgsGeometryUtils::wktGetChildBlocks( parts.second, defaultChildWkbType ) ) { @@ -295,20 +295,20 @@ QString QgsCurvePolygon::asWkt( int precision ) const QDomElement QgsCurvePolygon::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { // GML2 does not support curves - QDomElement elemPolygon = doc.createElementNS( ns, "Polygon" ); - QDomElement elemOuterBoundaryIs = doc.createElementNS( ns, "outerBoundaryIs" ); + QDomElement elemPolygon = doc.createElementNS( ns, QStringLiteral( "Polygon" ) ); + QDomElement elemOuterBoundaryIs = doc.createElementNS( ns, QStringLiteral( "outerBoundaryIs" ) ); QgsLineString* exteriorLineString = exteriorRing()->curveToLine(); QDomElement outerRing = exteriorLineString->asGML2( doc, precision, ns ); - outerRing.toElement().setTagName( "LinearRing" ); + outerRing.toElement().setTagName( QStringLiteral( "LinearRing" ) ); elemOuterBoundaryIs.appendChild( outerRing ); delete exteriorLineString; elemPolygon.appendChild( elemOuterBoundaryIs ); - QDomElement elemInnerBoundaryIs = doc.createElementNS( ns, "innerBoundaryIs" ); + QDomElement elemInnerBoundaryIs = doc.createElementNS( ns, QStringLiteral( "innerBoundaryIs" ) ); for ( int i = 0, n = numInteriorRings(); i < n; ++i ) { QgsLineString* interiorLineString = interiorRing( i )->curveToLine(); QDomElement innerRing = interiorLineString->asGML2( doc, precision, ns ); - innerRing.toElement().setTagName( "LinearRing" ); + innerRing.toElement().setTagName( QStringLiteral( "LinearRing" ) ); elemInnerBoundaryIs.appendChild( innerRing ); delete interiorLineString; } @@ -318,17 +318,17 @@ QDomElement QgsCurvePolygon::asGML2( QDomDocument& doc, int precision, const QSt QDomElement QgsCurvePolygon::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemCurvePolygon = doc.createElementNS( ns, "Polygon" ); - QDomElement elemExterior = doc.createElementNS( ns, "exterior" ); + QDomElement elemCurvePolygon = doc.createElementNS( ns, QStringLiteral( "Polygon" ) ); + QDomElement elemExterior = doc.createElementNS( ns, QStringLiteral( "exterior" ) ); QDomElement outerRing = exteriorRing()->asGML2( doc, precision, ns ); - outerRing.toElement().setTagName( "LinearRing" ); + outerRing.toElement().setTagName( QStringLiteral( "LinearRing" ) ); elemExterior.appendChild( outerRing ); elemCurvePolygon.appendChild( elemExterior ); - QDomElement elemInterior = doc.createElementNS( ns, "interior" ); + QDomElement elemInterior = doc.createElementNS( ns, QStringLiteral( "interior" ) ); for ( int i = 0, n = numInteriorRings(); i < n; ++i ) { QDomElement innerRing = interiorRing( i )->asGML2( doc, precision, ns ); - innerRing.toElement().setTagName( "LinearRing" ); + innerRing.toElement().setTagName( QStringLiteral( "LinearRing" ) ); elemInterior.appendChild( innerRing ); } elemCurvePolygon.appendChild( elemInterior ); @@ -338,7 +338,7 @@ QDomElement QgsCurvePolygon::asGML3( QDomDocument& doc, int precision, const QSt QString QgsCurvePolygon::asJSON( int precision ) const { // GeoJSON does not support curves - QString json = "{\"type\": \"Polygon\", \"coordinates\": ["; + QString json = QStringLiteral( "{\"type\": \"Polygon\", \"coordinates\": [" ); QgsLineString* exteriorLineString = exteriorRing()->curveToLine(); QgsPointSequence exteriorPts; @@ -354,11 +354,11 @@ QString QgsCurvePolygon::asJSON( int precision ) const json += QgsGeometryUtils::pointsToJSON( interiorPts, precision ) + ", "; delete interiorLineString; } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "] }"; + json += QLatin1String( "] }" ); return json; } diff --git a/src/core/geometry/qgscurvepolygon.h b/src/core/geometry/qgscurvepolygon.h index 818ebd807931..8230a4e8695c 100644 --- a/src/core/geometry/qgscurvepolygon.h +++ b/src/core/geometry/qgscurvepolygon.h @@ -36,7 +36,7 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface QgsCurvePolygon& operator=( const QgsCurvePolygon& p ); ~QgsCurvePolygon(); - virtual QString geometryType() const override { return "CurvePolygon"; } + virtual QString geometryType() const override { return QStringLiteral( "CurvePolygon" ); } virtual int dimension() const override { return 2; } virtual QgsCurvePolygon* clone() const override; void clear() override; @@ -47,8 +47,8 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; //surface interface diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index 142b2251bafc..70e70af21022 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -1011,7 +1011,7 @@ QString QgsGeometry::exportToGeoJSON( int precision ) const { if ( !d->geometry ) { - return QString( "null" ); + return QStringLiteral( "null" ); } return d->geometry->asJSON( precision ); } diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 5d3a25a1f1db..cce70ca030ee 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -747,7 +747,7 @@ class CORE_EXPORT QgsGeometry QgsPoint location; bool hasLocation; public: - Error() : message( "none" ), hasLocation( false ) {} + Error() : message( QStringLiteral( "none" ) ), hasLocation( false ) {} explicit Error( const QString& m ) : message( m ), hasLocation( false ) {} Error( const QString& m, const QgsPoint& p ) : message( m ), location( p ), hasLocation( true ) {} diff --git a/src/core/geometry/qgsgeometrycollection.cpp b/src/core/geometry/qgsgeometrycollection.cpp index 33c22c35f9d4..9a4823b9ade6 100644 --- a/src/core/geometry/qgsgeometrycollection.cpp +++ b/src/core/geometry/qgsgeometrycollection.cpp @@ -227,7 +227,7 @@ bool QgsGeometryCollection::fromWkt( const QString& wkt ) << new QgsCurvePolygon << new QgsMultiPointV2 << new QgsMultiLineString << new QgsMultiPolygonV2 << new QgsGeometryCollection - << new QgsMultiCurve << new QgsMultiSurface, "GeometryCollection" ); + << new QgsMultiCurve << new QgsMultiSurface, QStringLiteral( "GeometryCollection" ) ); } int QgsGeometryCollection::wkbSize() const @@ -287,10 +287,10 @@ QString QgsGeometryCollection::asWkt( int precision ) const QDomElement QgsGeometryCollection::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiGeometry = doc.createElementNS( ns, "MultiGeometry" ); + QDomElement elemMultiGeometry = doc.createElementNS( ns, QStringLiteral( "MultiGeometry" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { - QDomElement elemGeometryMember = doc.createElementNS( ns, "geometryMember" ); + QDomElement elemGeometryMember = doc.createElementNS( ns, QStringLiteral( "geometryMember" ) ); elemGeometryMember.appendChild( geom->asGML2( doc, precision, ns ) ); elemMultiGeometry.appendChild( elemGeometryMember ); } @@ -299,10 +299,10 @@ QDomElement QgsGeometryCollection::asGML2( QDomDocument& doc, int precision, con QDomElement QgsGeometryCollection::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiGeometry = doc.createElementNS( ns, "MultiGeometry" ); + QDomElement elemMultiGeometry = doc.createElementNS( ns, QStringLiteral( "MultiGeometry" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { - QDomElement elemGeometryMember = doc.createElementNS( ns, "geometryMember" ); + QDomElement elemGeometryMember = doc.createElementNS( ns, QStringLiteral( "geometryMember" ) ); elemGeometryMember.appendChild( geom->asGML3( doc, precision, ns ) ); elemMultiGeometry.appendChild( elemGeometryMember ); } @@ -311,16 +311,16 @@ QDomElement QgsGeometryCollection::asGML3( QDomDocument& doc, int precision, con QString QgsGeometryCollection::asJSON( int precision ) const { - QString json = "{\"type\": \"GeometryCollection\", \"geometries\": ["; + QString json = QStringLiteral( "{\"type\": \"GeometryCollection\", \"geometries\": [" ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { json += geom->asJSON( precision ) + ", "; } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "] }"; + json += QLatin1String( "] }" ); return json; } @@ -503,7 +503,7 @@ bool QgsGeometryCollection::fromCollectionWkt( const QString &wkt, const QList() << new QgsLineString << new QgsCircularString << new QgsCompoundCurve, - "LineString" ); + QStringLiteral( "LineString" ) ); } QDomElement QgsMultiCurve::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { // GML2 does not support curves - QDomElement elemMultiLineString = doc.createElementNS( ns, "MultiLineString" ); + QDomElement elemMultiLineString = doc.createElementNS( ns, QStringLiteral( "MultiLineString" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { QgsLineString* lineString = static_cast( geom )->curveToLine(); - QDomElement elemLineStringMember = doc.createElementNS( ns, "lineStringMember" ); + QDomElement elemLineStringMember = doc.createElementNS( ns, QStringLiteral( "lineStringMember" ) ); elemLineStringMember.appendChild( lineString->asGML2( doc, precision, ns ) ); elemMultiLineString.appendChild( elemLineStringMember ); @@ -63,14 +63,14 @@ QDomElement QgsMultiCurve::asGML2( QDomDocument& doc, int precision, const QStri QDomElement QgsMultiCurve::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiCurve = doc.createElementNS( ns, "MultiCurve" ); + QDomElement elemMultiCurve = doc.createElementNS( ns, QStringLiteral( "MultiCurve" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { const QgsCurve* curve = static_cast( geom ); - QDomElement elemCurveMember = doc.createElementNS( ns, "curveMember" ); + QDomElement elemCurveMember = doc.createElementNS( ns, QStringLiteral( "curveMember" ) ); elemCurveMember.appendChild( curve->asGML3( doc, precision, ns ) ); elemMultiCurve.appendChild( elemCurveMember ); } @@ -82,7 +82,7 @@ QDomElement QgsMultiCurve::asGML3( QDomDocument& doc, int precision, const QStri QString QgsMultiCurve::asJSON( int precision ) const { // GeoJSON does not support curves - QString json = "{\"type\": \"MultiLineString\", \"coordinates\": ["; + QString json = QStringLiteral( "{\"type\": \"MultiLineString\", \"coordinates\": [" ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) @@ -94,11 +94,11 @@ QString QgsMultiCurve::asJSON( int precision ) const delete lineString; } } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "] }"; + json += QLatin1String( "] }" ); return json; } diff --git a/src/core/geometry/qgsmulticurve.h b/src/core/geometry/qgsmulticurve.h index c30dfb1b3067..306e858ccd69 100644 --- a/src/core/geometry/qgsmulticurve.h +++ b/src/core/geometry/qgsmulticurve.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsMultiCurve: public QgsGeometryCollection { public: QgsMultiCurve(); - virtual QString geometryType() const override { return "MultiCurve"; } + virtual QString geometryType() const override { return QStringLiteral( "MultiCurve" ); } QgsMultiCurve* clone() const override; bool fromWkt( const QString& wkt ) override; @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiCurve: public QgsGeometryCollection // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; /** Adds a geometry and takes ownership. Returns true in case of success*/ diff --git a/src/core/geometry/qgsmultilinestring.cpp b/src/core/geometry/qgsmultilinestring.cpp index 6f39a244e0e4..94d6d3d74ae2 100644 --- a/src/core/geometry/qgsmultilinestring.cpp +++ b/src/core/geometry/qgsmultilinestring.cpp @@ -35,19 +35,19 @@ QgsMultiLineString* QgsMultiLineString::clone() const bool QgsMultiLineString::fromWkt( const QString& wkt ) { - return fromCollectionWkt( wkt, QList() << new QgsLineString, "LineString" ); + return fromCollectionWkt( wkt, QList() << new QgsLineString, QStringLiteral( "LineString" ) ); } QDomElement QgsMultiLineString::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiLineString = doc.createElementNS( ns, "MultiLineString" ); + QDomElement elemMultiLineString = doc.createElementNS( ns, QStringLiteral( "MultiLineString" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { const QgsLineString* lineString = static_cast( geom ); - QDomElement elemLineStringMember = doc.createElementNS( ns, "lineStringMember" ); + QDomElement elemLineStringMember = doc.createElementNS( ns, QStringLiteral( "lineStringMember" ) ); elemLineStringMember.appendChild( lineString->asGML2( doc, precision, ns ) ); elemMultiLineString.appendChild( elemLineStringMember ); @@ -60,14 +60,14 @@ QDomElement QgsMultiLineString::asGML2( QDomDocument& doc, int precision, const QDomElement QgsMultiLineString::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiCurve = doc.createElementNS( ns, "MultiLineString" ); + QDomElement elemMultiCurve = doc.createElementNS( ns, QStringLiteral( "MultiLineString" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { const QgsLineString* lineString = static_cast( geom ); - QDomElement elemCurveMember = doc.createElementNS( ns, "curveMember" ); + QDomElement elemCurveMember = doc.createElementNS( ns, QStringLiteral( "curveMember" ) ); elemCurveMember.appendChild( lineString->asGML3( doc, precision, ns ) ); elemMultiCurve.appendChild( elemCurveMember ); } @@ -78,7 +78,7 @@ QDomElement QgsMultiLineString::asGML3( QDomDocument& doc, int precision, const QString QgsMultiLineString::asJSON( int precision ) const { - QString json = "{\"type\": \"MultiLineString\", \"coordinates\": ["; + QString json = QStringLiteral( "{\"type\": \"MultiLineString\", \"coordinates\": [" ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) @@ -89,11 +89,11 @@ QString QgsMultiLineString::asJSON( int precision ) const json += QgsGeometryUtils::pointsToJSON( pts, precision ) + ", "; } } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "] }"; + json += QLatin1String( "] }" ); return json; } diff --git a/src/core/geometry/qgsmultilinestring.h b/src/core/geometry/qgsmultilinestring.h index cc4f3f881656..7da12d5b7708 100644 --- a/src/core/geometry/qgsmultilinestring.h +++ b/src/core/geometry/qgsmultilinestring.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsMultiLineString: public QgsMultiCurve { public: QgsMultiLineString(); - virtual QString geometryType() const override { return "MultiLineString"; } + virtual QString geometryType() const override { return QStringLiteral( "MultiLineString" ); } QgsMultiLineString* clone() const override; bool fromWkt( const QString& wkt ) override; @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiLineString: public QgsMultiCurve // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; /** Adds a geometry and takes ownership. Returns true in case of success*/ diff --git a/src/core/geometry/qgsmultipoint.cpp b/src/core/geometry/qgsmultipoint.cpp index 9ebca69c999e..5ab83cfcf672 100644 --- a/src/core/geometry/qgsmultipoint.cpp +++ b/src/core/geometry/qgsmultipoint.cpp @@ -39,20 +39,20 @@ bool QgsMultiPointV2::fromWkt( const QString& wkt ) if ( regex.indexIn( collectionWkt ) >= 0 ) { //alternate style without extra brackets, upgrade to standard - collectionWkt.replace( '(', "((" ).replace( ')', "))" ).replace( ',', "),(" ); + collectionWkt.replace( '(', QLatin1String( "((" ) ).replace( ')', QLatin1String( "))" ) ).replace( ',', QLatin1String( "),(" ) ); } - return fromCollectionWkt( collectionWkt, QList() << new QgsPointV2, "Point" ); + return fromCollectionWkt( collectionWkt, QList() << new QgsPointV2, QStringLiteral( "Point" ) ); } QDomElement QgsMultiPointV2::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiPoint = doc.createElementNS( ns, "MultiPoint" ); + QDomElement elemMultiPoint = doc.createElementNS( ns, QStringLiteral( "MultiPoint" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { - QDomElement elemPointMember = doc.createElementNS( ns, "pointMember" ); + QDomElement elemPointMember = doc.createElementNS( ns, QStringLiteral( "pointMember" ) ); elemPointMember.appendChild( geom->asGML2( doc, precision, ns ) ); elemMultiPoint.appendChild( elemPointMember ); } @@ -63,12 +63,12 @@ QDomElement QgsMultiPointV2::asGML2( QDomDocument& doc, int precision, const QSt QDomElement QgsMultiPointV2::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiPoint = doc.createElementNS( ns, "MultiPoint" ); + QDomElement elemMultiPoint = doc.createElementNS( ns, QStringLiteral( "MultiPoint" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { - QDomElement elemPointMember = doc.createElementNS( ns, "pointMember" ); + QDomElement elemPointMember = doc.createElementNS( ns, QStringLiteral( "pointMember" ) ); elemPointMember.appendChild( geom->asGML3( doc, precision, ns ) ); elemMultiPoint.appendChild( elemPointMember ); } @@ -79,7 +79,7 @@ QDomElement QgsMultiPointV2::asGML3( QDomDocument& doc, int precision, const QSt QString QgsMultiPointV2::asJSON( int precision ) const { - QString json = "{\"type\": \"MultiPoint\", \"coordinates\": "; + QString json = QStringLiteral( "{\"type\": \"MultiPoint\", \"coordinates\": " ); QgsPointSequence pts; Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) @@ -91,7 +91,7 @@ QString QgsMultiPointV2::asJSON( int precision ) const } } json += QgsGeometryUtils::pointsToJSON( pts, precision ); - json += " }"; + json += QLatin1String( " }" ); return json; } diff --git a/src/core/geometry/qgsmultipoint.h b/src/core/geometry/qgsmultipoint.h index aea6fc5c5128..996102601fc7 100644 --- a/src/core/geometry/qgsmultipoint.h +++ b/src/core/geometry/qgsmultipoint.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsMultiPointV2: public QgsGeometryCollection { public: QgsMultiPointV2(); - virtual QString geometryType() const override { return "MultiPoint"; } + virtual QString geometryType() const override { return QStringLiteral( "MultiPoint" ); } QgsMultiPointV2* clone() const override; bool fromWkt( const QString& wkt ) override; @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiPointV2: public QgsGeometryCollection // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; diff --git a/src/core/geometry/qgsmultipolygon.cpp b/src/core/geometry/qgsmultipolygon.cpp index ffa518de7d6c..b0125e98d1b1 100644 --- a/src/core/geometry/qgsmultipolygon.cpp +++ b/src/core/geometry/qgsmultipolygon.cpp @@ -35,18 +35,18 @@ QgsMultiPolygonV2 *QgsMultiPolygonV2::clone() const bool QgsMultiPolygonV2::fromWkt( const QString& wkt ) { - return fromCollectionWkt( wkt, QList() << new QgsPolygonV2, "Polygon" ); + return fromCollectionWkt( wkt, QList() << new QgsPolygonV2, QStringLiteral( "Polygon" ) ); } QDomElement QgsMultiPolygonV2::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { // GML2 does not support curves - QDomElement elemMultiPolygon = doc.createElementNS( ns, "MultiPolygon" ); + QDomElement elemMultiPolygon = doc.createElementNS( ns, QStringLiteral( "MultiPolygon" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { - QDomElement elemPolygonMember = doc.createElementNS( ns, "polygonMember" ); + QDomElement elemPolygonMember = doc.createElementNS( ns, QStringLiteral( "polygonMember" ) ); elemPolygonMember.appendChild( geom->asGML2( doc, precision, ns ) ); elemMultiPolygon.appendChild( elemPolygonMember ); } @@ -57,12 +57,12 @@ QDomElement QgsMultiPolygonV2::asGML2( QDomDocument& doc, int precision, const Q QDomElement QgsMultiPolygonV2::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiSurface = doc.createElementNS( ns, "MultiPolygon" ); + QDomElement elemMultiSurface = doc.createElementNS( ns, QStringLiteral( "MultiPolygon" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { - QDomElement elemSurfaceMember = doc.createElementNS( ns, "polygonMember" ); + QDomElement elemSurfaceMember = doc.createElementNS( ns, QStringLiteral( "polygonMember" ) ); elemSurfaceMember.appendChild( geom->asGML3( doc, precision, ns ) ); elemMultiSurface.appendChild( elemSurfaceMember ); } @@ -74,7 +74,7 @@ QDomElement QgsMultiPolygonV2::asGML3( QDomDocument& doc, int precision, const Q QString QgsMultiPolygonV2::asJSON( int precision ) const { // GeoJSON does not support curves - QString json = "{\"type\": \"MultiPolygon\", \"coordinates\": ["; + QString json = QStringLiteral( "{\"type\": \"MultiPolygon\", \"coordinates\": [" ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) @@ -97,19 +97,19 @@ QString QgsMultiPolygonV2::asJSON( int precision ) const json += QgsGeometryUtils::pointsToJSON( interiorPts, precision ) + ", "; delete interiorLineString; } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "], "; + json += QLatin1String( "], " ); } } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "] }"; + json += QLatin1String( "] }" ); return json; } diff --git a/src/core/geometry/qgsmultipolygon.h b/src/core/geometry/qgsmultipolygon.h index 080c8bd9470b..1b72ac540104 100644 --- a/src/core/geometry/qgsmultipolygon.h +++ b/src/core/geometry/qgsmultipolygon.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsMultiPolygonV2: public QgsMultiSurface { public: QgsMultiPolygonV2(); - virtual QString geometryType() const override { return "MultiPolygon"; } + virtual QString geometryType() const override { return QStringLiteral( "MultiPolygon" ); } QgsMultiPolygonV2* clone() const override; bool fromWkt( const QString& wkt ) override; @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiPolygonV2: public QgsMultiSurface // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; /** Adds a geometry and takes ownership. Returns true in case of success*/ diff --git a/src/core/geometry/qgsmultisurface.cpp b/src/core/geometry/qgsmultisurface.cpp index 8f545e21efcc..c2c793768cf6 100644 --- a/src/core/geometry/qgsmultisurface.cpp +++ b/src/core/geometry/qgsmultisurface.cpp @@ -38,20 +38,20 @@ bool QgsMultiSurface::fromWkt( const QString& wkt ) { return fromCollectionWkt( wkt, QList() << new QgsPolygonV2 << new QgsCurvePolygon, - "Polygon" ); + QStringLiteral( "Polygon" ) ); } QDomElement QgsMultiSurface::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { // GML2 does not support curves - QDomElement elemMultiPolygon = doc.createElementNS( ns, "MultiPolygon" ); + QDomElement elemMultiPolygon = doc.createElementNS( ns, QStringLiteral( "MultiPolygon" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { QgsPolygonV2* polygon = static_cast( geom )->surfaceToPolygon(); - QDomElement elemPolygonMember = doc.createElementNS( ns, "polygonMember" ); + QDomElement elemPolygonMember = doc.createElementNS( ns, QStringLiteral( "polygonMember" ) ); elemPolygonMember.appendChild( polygon->asGML2( doc, precision, ns ) ); elemMultiPolygon.appendChild( elemPolygonMember ); @@ -64,12 +64,12 @@ QDomElement QgsMultiSurface::asGML2( QDomDocument& doc, int precision, const QSt QDomElement QgsMultiSurface::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemMultiSurface = doc.createElementNS( ns, "MultiSurface" ); + QDomElement elemMultiSurface = doc.createElementNS( ns, QStringLiteral( "MultiSurface" ) ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) { - QDomElement elemSurfaceMember = doc.createElementNS( ns, "surfaceMember" ); + QDomElement elemSurfaceMember = doc.createElementNS( ns, QStringLiteral( "surfaceMember" ) ); elemSurfaceMember.appendChild( geom->asGML3( doc, precision, ns ) ); elemMultiSurface.appendChild( elemSurfaceMember ); } @@ -81,7 +81,7 @@ QDomElement QgsMultiSurface::asGML3( QDomDocument& doc, int precision, const QSt QString QgsMultiSurface::asJSON( int precision ) const { // GeoJSON does not support curves - QString json = "{\"type\": \"MultiPolygon\", \"coordinates\": ["; + QString json = QStringLiteral( "{\"type\": \"MultiPolygon\", \"coordinates\": [" ); Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( dynamic_cast( geom ) ) @@ -104,21 +104,21 @@ QString QgsMultiSurface::asJSON( int precision ) const json += QgsGeometryUtils::pointsToJSON( interiorPts, precision ) + ", "; delete interiorLineString; } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } delete polygon; - json += "], "; + json += QLatin1String( "], " ); } } - if ( json.endsWith( ", " ) ) + if ( json.endsWith( QLatin1String( ", " ) ) ) { json.chop( 2 ); // Remove last ", " } - json += "] }"; + json += QLatin1String( "] }" ); return json; } diff --git a/src/core/geometry/qgsmultisurface.h b/src/core/geometry/qgsmultisurface.h index ff2d0a3ea254..73dbab458312 100644 --- a/src/core/geometry/qgsmultisurface.h +++ b/src/core/geometry/qgsmultisurface.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsMultiSurface: public QgsGeometryCollection { public: QgsMultiSurface(); - virtual QString geometryType() const override { return "MultiSurface"; } + virtual QString geometryType() const override { return QStringLiteral( "MultiSurface" ); } QgsMultiSurface* clone() const override; bool fromWkt( const QString& wkt ) override; @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiSurface: public QgsGeometryCollection // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; diff --git a/src/core/geometry/qgspointv2.cpp b/src/core/geometry/qgspointv2.cpp index d4789d49c7d0..246ee968380d 100644 --- a/src/core/geometry/qgspointv2.cpp +++ b/src/core/geometry/qgspointv2.cpp @@ -211,8 +211,8 @@ QString QgsPointV2::asWkt( int precision ) const QDomElement QgsPointV2::asGML2( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemPoint = doc.createElementNS( ns, "Point" ); - QDomElement elemCoordinates = doc.createElementNS( ns, "coordinates" ); + QDomElement elemPoint = doc.createElementNS( ns, QStringLiteral( "Point" ) ); + QDomElement elemCoordinates = doc.createElementNS( ns, QStringLiteral( "coordinates" ) ); QString strCoordinates = qgsDoubleToString( mX, precision ) + ',' + qgsDoubleToString( mY, precision ); elemCoordinates.appendChild( doc.createTextNode( strCoordinates ) ); elemPoint.appendChild( elemCoordinates ); @@ -221,9 +221,9 @@ QDomElement QgsPointV2::asGML2( QDomDocument& doc, int precision, const QString& QDomElement QgsPointV2::asGML3( QDomDocument& doc, int precision, const QString& ns ) const { - QDomElement elemPoint = doc.createElementNS( ns, "Point" ); - QDomElement elemPosList = doc.createElementNS( ns, "pos" ); - elemPosList.setAttribute( "srsDimension", is3D() ? 3 : 2 ); + QDomElement elemPoint = doc.createElementNS( ns, QStringLiteral( "Point" ) ); + QDomElement elemPosList = doc.createElementNS( ns, QStringLiteral( "pos" ) ); + elemPosList.setAttribute( QStringLiteral( "srsDimension" ), is3D() ? 3 : 2 ); QString strCoordinates = qgsDoubleToString( mX, precision ) + ' ' + qgsDoubleToString( mY, precision ); if ( is3D() ) strCoordinates += ' ' + qgsDoubleToString( mZ, precision ); diff --git a/src/core/geometry/qgspointv2.h b/src/core/geometry/qgspointv2.h index 9b576d3aa53e..167b0faed009 100644 --- a/src/core/geometry/qgspointv2.h +++ b/src/core/geometry/qgspointv2.h @@ -153,7 +153,7 @@ class CORE_EXPORT QgsPointV2: public QgsAbstractGeometry //implementation of inherited methods virtual QgsRectangle boundingBox() const override { return QgsRectangle( mX, mY, mX, mY ); } - virtual QString geometryType() const override { return "Point"; } + virtual QString geometryType() const override { return QStringLiteral( "Point" ); } virtual int dimension() const override { return 0; } virtual QgsPointV2* clone() const override; void clear() override; @@ -162,8 +162,8 @@ class CORE_EXPORT QgsPointV2: public QgsAbstractGeometry int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; QString asJSON( int precision = 17 ) const override; void draw( QPainter& p ) const override; void transform( const QgsCoordinateTransform& ct, QgsCoordinateTransform::TransformDirection d = QgsCoordinateTransform::ForwardTransform, diff --git a/src/core/geometry/qgspolygon.h b/src/core/geometry/qgspolygon.h index 40b366e34e97..a1ce6dfe1add 100644 --- a/src/core/geometry/qgspolygon.h +++ b/src/core/geometry/qgspolygon.h @@ -34,7 +34,7 @@ class CORE_EXPORT QgsPolygonV2: public QgsCurvePolygon bool operator==( const QgsPolygonV2& other ) const; bool operator!=( const QgsPolygonV2& other ) const; - virtual QString geometryType() const override { return "Polygon"; } + virtual QString geometryType() const override { return QStringLiteral( "Polygon" ); } virtual QgsPolygonV2* clone() const override; void clear() override; diff --git a/src/core/geometry/qgswkbptr.cpp b/src/core/geometry/qgswkbptr.cpp index d2cdf442563b..d91b278a115f 100644 --- a/src/core/geometry/qgswkbptr.cpp +++ b/src/core/geometry/qgswkbptr.cpp @@ -24,7 +24,7 @@ QgsWkbPtr::QgsWkbPtr( unsigned char *p, int size ) void QgsWkbPtr::verifyBound( int size ) const { if ( !mP || mP + size > mEnd ) - throw QgsWkbException( "wkb access out of bounds" ); + throw QgsWkbException( QStringLiteral( "wkb access out of bounds" ) ); } QgsConstWkbPtr::QgsConstWkbPtr( const unsigned char *p, int size ) @@ -54,7 +54,7 @@ QgsWkbTypes::Type QgsConstWkbPtr::readHeader() const void QgsConstWkbPtr::verifyBound( int size ) const { if ( !mP || mP + size > mEnd ) - throw QgsWkbException( "wkb access out of bounds" ); + throw QgsWkbException( QStringLiteral( "wkb access out of bounds" ) ); } const QgsConstWkbPtr &QgsConstWkbPtr::operator>>( QPointF &point ) const diff --git a/src/core/geometry/qgswkbtypes.cpp b/src/core/geometry/qgswkbtypes.cpp index 00f0ceac80da..eec5dc43f0bc 100644 --- a/src/core/geometry/qgswkbtypes.cpp +++ b/src/core/geometry/qgswkbtypes.cpp @@ -61,17 +61,17 @@ QString QgsWkbTypes::geometryDisplayString( QgsWkbTypes::GeometryType type ) switch ( type ) { case PointGeometry: - return "Point"; + return QStringLiteral( "Point" ); case LineGeometry: - return "Line"; + return QStringLiteral( "Line" ); case PolygonGeometry: - return "Polygon"; + return QStringLiteral( "Polygon" ); case UnknownGeometry: - return "Unknown geometry"; + return QStringLiteral( "Unknown geometry" ); case NullGeometry: - return "No geometry"; + return QStringLiteral( "No geometry" ); default: - return "Invalid type"; + return QStringLiteral( "Invalid type" ); } @@ -87,73 +87,73 @@ QMap QgsWkbTypes::registerTypes() { QMap entries; //register the known wkb types - entries.insert( Unknown, wkbEntry( "Unknown", false, Unknown, Unknown, Unknown, UnknownGeometry, false, false ) ); - entries.insert( NoGeometry, wkbEntry( "NoGeometry", false, NoGeometry, NoGeometry, NoGeometry, NullGeometry, false, false ) ); + entries.insert( Unknown, wkbEntry( QStringLiteral( "Unknown" ), false, Unknown, Unknown, Unknown, UnknownGeometry, false, false ) ); + entries.insert( NoGeometry, wkbEntry( QStringLiteral( "NoGeometry" ), false, NoGeometry, NoGeometry, NoGeometry, NullGeometry, false, false ) ); //point - entries.insert( Point, wkbEntry( "Point", false, MultiPoint, Point, Point, PointGeometry, false, false ) ); - entries.insert( PointZ, wkbEntry( "PointZ", false, MultiPointZ, PointZ, Point, PointGeometry, true, false ) ); - entries.insert( PointM, wkbEntry( "PointM", false, MultiPointM, PointM, Point, PointGeometry, false, true ) ); - entries.insert( PointZM, wkbEntry( "PointZM", false, MultiPointZM, PointZM, Point, PointGeometry, true, true ) ); - entries.insert( Point25D, wkbEntry( "Point25D", false, MultiPoint25D, Point25D, Point, PointGeometry, true, false ) ); + entries.insert( Point, wkbEntry( QStringLiteral( "Point" ), false, MultiPoint, Point, Point, PointGeometry, false, false ) ); + entries.insert( PointZ, wkbEntry( QStringLiteral( "PointZ" ), false, MultiPointZ, PointZ, Point, PointGeometry, true, false ) ); + entries.insert( PointM, wkbEntry( QStringLiteral( "PointM" ), false, MultiPointM, PointM, Point, PointGeometry, false, true ) ); + entries.insert( PointZM, wkbEntry( QStringLiteral( "PointZM" ), false, MultiPointZM, PointZM, Point, PointGeometry, true, true ) ); + entries.insert( Point25D, wkbEntry( QStringLiteral( "Point25D" ), false, MultiPoint25D, Point25D, Point, PointGeometry, true, false ) ); //linestring - entries.insert( LineString, wkbEntry( "LineString", false, MultiLineString, LineString, LineString, LineGeometry, false, false ) ); - entries.insert( LineStringZ, wkbEntry( "LineStringZ", false, MultiLineStringZ, LineStringZ, LineString, LineGeometry, true, false ) ); - entries.insert( LineStringM, wkbEntry( "LineStringM", false, MultiLineStringM, LineStringM, LineString, LineGeometry, false, true ) ); - entries.insert( LineStringZM, wkbEntry( "LineStringZM", false, MultiLineStringZM, LineStringZM, LineString, LineGeometry, true, true ) ); - entries.insert( LineString25D, wkbEntry( "LineString25D", false, MultiLineString25D, LineString25D, LineString, LineGeometry, true, false ) ); + entries.insert( LineString, wkbEntry( QStringLiteral( "LineString" ), false, MultiLineString, LineString, LineString, LineGeometry, false, false ) ); + entries.insert( LineStringZ, wkbEntry( QStringLiteral( "LineStringZ" ), false, MultiLineStringZ, LineStringZ, LineString, LineGeometry, true, false ) ); + entries.insert( LineStringM, wkbEntry( QStringLiteral( "LineStringM" ), false, MultiLineStringM, LineStringM, LineString, LineGeometry, false, true ) ); + entries.insert( LineStringZM, wkbEntry( QStringLiteral( "LineStringZM" ), false, MultiLineStringZM, LineStringZM, LineString, LineGeometry, true, true ) ); + entries.insert( LineString25D, wkbEntry( QStringLiteral( "LineString25D" ), false, MultiLineString25D, LineString25D, LineString, LineGeometry, true, false ) ); //circularstring - entries.insert( CircularString, wkbEntry( "CircularString", false, MultiCurve, CircularString, CircularString, LineGeometry, false, false ) ); - entries.insert( CircularStringZ, wkbEntry( "CircularStringZ", false, MultiCurveZ, CircularStringZ, CircularString, LineGeometry, true, false ) ); - entries.insert( CircularStringM, wkbEntry( "CircularStringM", false, MultiCurveM, CircularStringM, CircularString, LineGeometry, false, true ) ); - entries.insert( CircularStringZM, wkbEntry( "CircularStringZM", false, MultiCurveZM, CircularStringZM, CircularString, LineGeometry, true, true ) ); + entries.insert( CircularString, wkbEntry( QStringLiteral( "CircularString" ), false, MultiCurve, CircularString, CircularString, LineGeometry, false, false ) ); + entries.insert( CircularStringZ, wkbEntry( QStringLiteral( "CircularStringZ" ), false, MultiCurveZ, CircularStringZ, CircularString, LineGeometry, true, false ) ); + entries.insert( CircularStringM, wkbEntry( QStringLiteral( "CircularStringM" ), false, MultiCurveM, CircularStringM, CircularString, LineGeometry, false, true ) ); + entries.insert( CircularStringZM, wkbEntry( QStringLiteral( "CircularStringZM" ), false, MultiCurveZM, CircularStringZM, CircularString, LineGeometry, true, true ) ); //compoundcurve - entries.insert( CompoundCurve, wkbEntry( "CompoundCurve", false, MultiCurve, CompoundCurve, CompoundCurve, LineGeometry, false, false ) ); - entries.insert( CompoundCurveZ, wkbEntry( "CompoundCurveZ", false, MultiCurveZ, CompoundCurveZ, CompoundCurve, LineGeometry, true, false ) ); - entries.insert( CompoundCurveM, wkbEntry( "CompoundCurveM", false, MultiCurveM, CompoundCurveM, CompoundCurve, LineGeometry, false, true ) ); - entries.insert( CompoundCurveZM, wkbEntry( "CompoundCurveZM", false, MultiCurveZM, CompoundCurveZM, CompoundCurve, LineGeometry, true, true ) ); + entries.insert( CompoundCurve, wkbEntry( QStringLiteral( "CompoundCurve" ), false, MultiCurve, CompoundCurve, CompoundCurve, LineGeometry, false, false ) ); + entries.insert( CompoundCurveZ, wkbEntry( QStringLiteral( "CompoundCurveZ" ), false, MultiCurveZ, CompoundCurveZ, CompoundCurve, LineGeometry, true, false ) ); + entries.insert( CompoundCurveM, wkbEntry( QStringLiteral( "CompoundCurveM" ), false, MultiCurveM, CompoundCurveM, CompoundCurve, LineGeometry, false, true ) ); + entries.insert( CompoundCurveZM, wkbEntry( QStringLiteral( "CompoundCurveZM" ), false, MultiCurveZM, CompoundCurveZM, CompoundCurve, LineGeometry, true, true ) ); //polygon - entries.insert( Polygon, wkbEntry( "Polygon", false, MultiPolygon, Polygon, Polygon, PolygonGeometry, false, false ) ); - entries.insert( PolygonZ, wkbEntry( "PolygonZ", false, MultiPolygonZ, PolygonZ, Polygon, PolygonGeometry, true, false ) ); - entries.insert( PolygonM, wkbEntry( "PolygonM", false, MultiPolygonM, PolygonM, Polygon, PolygonGeometry, false, true ) ); - entries.insert( PolygonZM, wkbEntry( "PolygonZM", false, MultiPolygonZM, PolygonZM, Polygon, PolygonGeometry, true, true ) ); - entries.insert( Polygon25D, wkbEntry( "Polygon25D", false, MultiPolygon25D, Polygon25D, Polygon, PolygonGeometry, true, false ) ); + entries.insert( Polygon, wkbEntry( QStringLiteral( "Polygon" ), false, MultiPolygon, Polygon, Polygon, PolygonGeometry, false, false ) ); + entries.insert( PolygonZ, wkbEntry( QStringLiteral( "PolygonZ" ), false, MultiPolygonZ, PolygonZ, Polygon, PolygonGeometry, true, false ) ); + entries.insert( PolygonM, wkbEntry( QStringLiteral( "PolygonM" ), false, MultiPolygonM, PolygonM, Polygon, PolygonGeometry, false, true ) ); + entries.insert( PolygonZM, wkbEntry( QStringLiteral( "PolygonZM" ), false, MultiPolygonZM, PolygonZM, Polygon, PolygonGeometry, true, true ) ); + entries.insert( Polygon25D, wkbEntry( QStringLiteral( "Polygon25D" ), false, MultiPolygon25D, Polygon25D, Polygon, PolygonGeometry, true, false ) ); //curvepolygon - entries.insert( CurvePolygon, wkbEntry( "CurvePolygon", false, MultiSurface, CurvePolygon, CurvePolygon, PolygonGeometry, false, false ) ); - entries.insert( CurvePolygonZ, wkbEntry( "CurvePolygonZ", false, MultiSurfaceZ, CurvePolygonZ, CurvePolygon, PolygonGeometry, true, false ) ); - entries.insert( CurvePolygonM, wkbEntry( "CurvePolygonM", false, MultiSurfaceM, CurvePolygonM, CurvePolygon, PolygonGeometry, false, true ) ); - entries.insert( CurvePolygonZM, wkbEntry( "CurvePolygonZM", false, MultiSurfaceZM, CurvePolygonZM, CurvePolygon, PolygonGeometry, true, true ) ); + entries.insert( CurvePolygon, wkbEntry( QStringLiteral( "CurvePolygon" ), false, MultiSurface, CurvePolygon, CurvePolygon, PolygonGeometry, false, false ) ); + entries.insert( CurvePolygonZ, wkbEntry( QStringLiteral( "CurvePolygonZ" ), false, MultiSurfaceZ, CurvePolygonZ, CurvePolygon, PolygonGeometry, true, false ) ); + entries.insert( CurvePolygonM, wkbEntry( QStringLiteral( "CurvePolygonM" ), false, MultiSurfaceM, CurvePolygonM, CurvePolygon, PolygonGeometry, false, true ) ); + entries.insert( CurvePolygonZM, wkbEntry( QStringLiteral( "CurvePolygonZM" ), false, MultiSurfaceZM, CurvePolygonZM, CurvePolygon, PolygonGeometry, true, true ) ); //multipoint - entries.insert( MultiPoint, wkbEntry( "MultiPoint", true, MultiPoint, Point, MultiPoint, PointGeometry, false, false ) ); - entries.insert( MultiPointZ, wkbEntry( "MultiPointZ", true, MultiPointZ, PointZ, MultiPoint, PointGeometry, true, false ) ); - entries.insert( MultiPointM, wkbEntry( "MultiPointM", true, MultiPointM, PointM, MultiPoint, PointGeometry, false, true ) ); - entries.insert( MultiPointZM, wkbEntry( "MultiPointZM", true, MultiPointZM, PointZM, MultiPoint, PointGeometry, true, true ) ); - entries.insert( MultiPoint25D, wkbEntry( "MultiPoint25D", true, MultiPoint25D, Point25D, MultiPoint, PointGeometry, true, false ) ); + entries.insert( MultiPoint, wkbEntry( QStringLiteral( "MultiPoint" ), true, MultiPoint, Point, MultiPoint, PointGeometry, false, false ) ); + entries.insert( MultiPointZ, wkbEntry( QStringLiteral( "MultiPointZ" ), true, MultiPointZ, PointZ, MultiPoint, PointGeometry, true, false ) ); + entries.insert( MultiPointM, wkbEntry( QStringLiteral( "MultiPointM" ), true, MultiPointM, PointM, MultiPoint, PointGeometry, false, true ) ); + entries.insert( MultiPointZM, wkbEntry( QStringLiteral( "MultiPointZM" ), true, MultiPointZM, PointZM, MultiPoint, PointGeometry, true, true ) ); + entries.insert( MultiPoint25D, wkbEntry( QStringLiteral( "MultiPoint25D" ), true, MultiPoint25D, Point25D, MultiPoint, PointGeometry, true, false ) ); //multiline - entries.insert( MultiLineString, wkbEntry( "MultiLineString", true, MultiLineString, LineString, MultiLineString, LineGeometry, false, false ) ); - entries.insert( MultiLineStringZ, wkbEntry( "MultiLineStringZ", true, MultiLineStringZ, LineStringZ, MultiLineString, LineGeometry, true, false ) ); - entries.insert( MultiLineStringM, wkbEntry( "MultiLineStringM", true, MultiLineStringM, LineStringM, MultiLineString, LineGeometry, false, true ) ); - entries.insert( MultiLineStringZM, wkbEntry( "MultiLineStringZM", true, MultiLineStringZM, LineStringZM, MultiLineString, LineGeometry, true, true ) ); - entries.insert( MultiLineString25D, wkbEntry( "MultiLineString25D", true, MultiLineString25D, LineString25D, MultiLineString, LineGeometry, true, false ) ); + entries.insert( MultiLineString, wkbEntry( QStringLiteral( "MultiLineString" ), true, MultiLineString, LineString, MultiLineString, LineGeometry, false, false ) ); + entries.insert( MultiLineStringZ, wkbEntry( QStringLiteral( "MultiLineStringZ" ), true, MultiLineStringZ, LineStringZ, MultiLineString, LineGeometry, true, false ) ); + entries.insert( MultiLineStringM, wkbEntry( QStringLiteral( "MultiLineStringM" ), true, MultiLineStringM, LineStringM, MultiLineString, LineGeometry, false, true ) ); + entries.insert( MultiLineStringZM, wkbEntry( QStringLiteral( "MultiLineStringZM" ), true, MultiLineStringZM, LineStringZM, MultiLineString, LineGeometry, true, true ) ); + entries.insert( MultiLineString25D, wkbEntry( QStringLiteral( "MultiLineString25D" ), true, MultiLineString25D, LineString25D, MultiLineString, LineGeometry, true, false ) ); //multicurve - entries.insert( MultiCurve, wkbEntry( "MultiCurve", true, MultiCurve, CompoundCurve, MultiCurve, LineGeometry, false, false ) ); - entries.insert( MultiCurveZ, wkbEntry( "MultiCurveZ", true, MultiCurveZ, CompoundCurveZ, MultiCurve, LineGeometry, true, false ) ); - entries.insert( MultiCurveM, wkbEntry( "MultiCurveM", true, MultiCurveM, CompoundCurveM, MultiCurve, LineGeometry, false, true ) ); - entries.insert( MultiCurveZM, wkbEntry( "MultiCurveZM", true, MultiCurveZM, CompoundCurveZM, MultiCurve, LineGeometry, true, true ) ); + entries.insert( MultiCurve, wkbEntry( QStringLiteral( "MultiCurve" ), true, MultiCurve, CompoundCurve, MultiCurve, LineGeometry, false, false ) ); + entries.insert( MultiCurveZ, wkbEntry( QStringLiteral( "MultiCurveZ" ), true, MultiCurveZ, CompoundCurveZ, MultiCurve, LineGeometry, true, false ) ); + entries.insert( MultiCurveM, wkbEntry( QStringLiteral( "MultiCurveM" ), true, MultiCurveM, CompoundCurveM, MultiCurve, LineGeometry, false, true ) ); + entries.insert( MultiCurveZM, wkbEntry( QStringLiteral( "MultiCurveZM" ), true, MultiCurveZM, CompoundCurveZM, MultiCurve, LineGeometry, true, true ) ); //multipolygon - entries.insert( MultiPolygon, wkbEntry( "MultiPolygon", true, MultiPolygon, Polygon, MultiPolygon, PolygonGeometry, false, false ) ); - entries.insert( MultiPolygonZ, wkbEntry( "MultiPolygonZ", true, MultiPolygonZ, PolygonZ, MultiPolygon, PolygonGeometry, true, false ) ); - entries.insert( MultiPolygonM, wkbEntry( "MultiPolygonM", true, MultiPolygonM, PolygonM, MultiPolygon, PolygonGeometry, false, true ) ); - entries.insert( MultiPolygonZM, wkbEntry( "MultiPolygonZM", true, MultiPolygonZM, PolygonZM, MultiPolygon, PolygonGeometry, true, true ) ); - entries.insert( MultiPolygon25D, wkbEntry( "MultiPolygon25D", true, MultiPolygon25D, Polygon25D, MultiPolygon, PolygonGeometry, true, false ) ); + entries.insert( MultiPolygon, wkbEntry( QStringLiteral( "MultiPolygon" ), true, MultiPolygon, Polygon, MultiPolygon, PolygonGeometry, false, false ) ); + entries.insert( MultiPolygonZ, wkbEntry( QStringLiteral( "MultiPolygonZ" ), true, MultiPolygonZ, PolygonZ, MultiPolygon, PolygonGeometry, true, false ) ); + entries.insert( MultiPolygonM, wkbEntry( QStringLiteral( "MultiPolygonM" ), true, MultiPolygonM, PolygonM, MultiPolygon, PolygonGeometry, false, true ) ); + entries.insert( MultiPolygonZM, wkbEntry( QStringLiteral( "MultiPolygonZM" ), true, MultiPolygonZM, PolygonZM, MultiPolygon, PolygonGeometry, true, true ) ); + entries.insert( MultiPolygon25D, wkbEntry( QStringLiteral( "MultiPolygon25D" ), true, MultiPolygon25D, Polygon25D, MultiPolygon, PolygonGeometry, true, false ) ); //multisurface - entries.insert( MultiSurface, wkbEntry( "MultiSurface", true, MultiSurface, CurvePolygon, MultiSurface, PolygonGeometry, false, false ) ); - entries.insert( MultiSurfaceZ, wkbEntry( "MultiSurfaceZ", true, MultiSurfaceZ, CurvePolygonZ, MultiSurface, PolygonGeometry, true, false ) ); - entries.insert( MultiSurfaceM, wkbEntry( "MultiSurfaceM", true, MultiSurfaceM, CurvePolygonM, MultiSurface, PolygonGeometry, false, true ) ); - entries.insert( MultiSurfaceZM, wkbEntry( "MultiSurfaceZM", true, MultiSurfaceZM, CurvePolygonZM, MultiSurface, PolygonGeometry, true, true ) ); + entries.insert( MultiSurface, wkbEntry( QStringLiteral( "MultiSurface" ), true, MultiSurface, CurvePolygon, MultiSurface, PolygonGeometry, false, false ) ); + entries.insert( MultiSurfaceZ, wkbEntry( QStringLiteral( "MultiSurfaceZ" ), true, MultiSurfaceZ, CurvePolygonZ, MultiSurface, PolygonGeometry, true, false ) ); + entries.insert( MultiSurfaceM, wkbEntry( QStringLiteral( "MultiSurfaceM" ), true, MultiSurfaceM, CurvePolygonM, MultiSurface, PolygonGeometry, false, true ) ); + entries.insert( MultiSurfaceZM, wkbEntry( QStringLiteral( "MultiSurfaceZM" ), true, MultiSurfaceZM, CurvePolygonZM, MultiSurface, PolygonGeometry, true, true ) ); //geometrycollection - entries.insert( GeometryCollection, wkbEntry( "GeometryCollection", true, GeometryCollection, Unknown, GeometryCollection, UnknownGeometry, false, false ) ); - entries.insert( GeometryCollectionZ, wkbEntry( "GeometryCollectionZ", true, GeometryCollectionZ, Unknown, GeometryCollection, UnknownGeometry, true, false ) ); - entries.insert( GeometryCollectionM, wkbEntry( "GeometryCollectionM", true, GeometryCollectionM, Unknown, GeometryCollection, UnknownGeometry, false, true ) ); - entries.insert( GeometryCollectionZM, wkbEntry( "GeometryCollectionZM", true, GeometryCollectionZM, Unknown, GeometryCollection, UnknownGeometry, true, true ) ); + entries.insert( GeometryCollection, wkbEntry( QStringLiteral( "GeometryCollection" ), true, GeometryCollection, Unknown, GeometryCollection, UnknownGeometry, false, false ) ); + entries.insert( GeometryCollectionZ, wkbEntry( QStringLiteral( "GeometryCollectionZ" ), true, GeometryCollectionZ, Unknown, GeometryCollection, UnknownGeometry, true, false ) ); + entries.insert( GeometryCollectionM, wkbEntry( QStringLiteral( "GeometryCollectionM" ), true, GeometryCollectionM, Unknown, GeometryCollection, UnknownGeometry, false, true ) ); + entries.insert( GeometryCollectionZM, wkbEntry( QStringLiteral( "GeometryCollectionZM" ), true, GeometryCollectionZM, Unknown, GeometryCollection, UnknownGeometry, true, true ) ); return entries; } diff --git a/src/core/gps/qextserialport/qextserialport.cpp b/src/core/gps/qextserialport/qextserialport.cpp index f42f890f6baf..202b95d21b38 100644 --- a/src/core/gps/qextserialport/qextserialport.cpp +++ b/src/core/gps/qextserialport/qextserialport.cpp @@ -52,7 +52,7 @@ QextSerialPort::QextSerialPort(QextSerialPort::QueryMode mode) setPortName("/dev/tty00"); #else - setPortName("/dev/ttyS0"); + setPortName(QStringLiteral("/dev/ttyS0")); #endif construct(); diff --git a/src/core/gps/qgsgpsdconnection.cpp b/src/core/gps/qgsgpsdconnection.cpp index c8c66ece462d..141713ce0662 100644 --- a/src/core/gps/qgsgpsdconnection.cpp +++ b/src/core/gps/qgsgpsdconnection.cpp @@ -40,7 +40,7 @@ void QgsGpsdConnection::connected() { QgsDebugMsg( "connected!" ); QTcpSocket *socket = qobject_cast< QTcpSocket * >( mSource ); - socket->write( QString( "?WATCH={\"enable\":true,\"nmea\":true,\"raw\":true%1};" ).arg( mDevice.isEmpty() ? mDevice : QString( ",\"device\":%1" ).arg( mDevice ) ).toUtf8() ); + socket->write( QStringLiteral( "?WATCH={\"enable\":true,\"nmea\":true,\"raw\":true%1};" ).arg( mDevice.isEmpty() ? mDevice : QStringLiteral( ",\"device\":%1" ).arg( mDevice ) ).toUtf8() ); } void QgsGpsdConnection::error( QAbstractSocket::SocketError socketError ) diff --git a/src/core/gps/qgsgpsdetector.cpp b/src/core/gps/qgsgpsdetector.cpp index be80a44ef93f..279e95af876a 100644 --- a/src/core/gps/qgsgpsdetector.cpp +++ b/src/core/gps/qgsgpsdetector.cpp @@ -36,11 +36,11 @@ QList< QPair > QgsGPSDetector::availablePorts() // try local QtLocation first #if defined(HAVE_QT_MOBILITY_LOCATION ) || defined(QT_POSITIONING_LIB) - devs << QPair( "internalGPS", tr( "internal GPS" ) ); + devs << QPair( QStringLiteral( "internalGPS" ), tr( "internal GPS" ) ); #endif // try local gpsd first - devs << QPair( "localhost:2947:", tr( "local gpsd" ) ); + devs << QPair( QStringLiteral( "localhost:2947:" ), tr( "local gpsd" ) ); #ifdef Q_OS_LINUX // look for linux serial devices @@ -154,7 +154,7 @@ void QgsGPSDetector::advance() mConn = new QgsGpsdConnection( gpsParams[0], gpsParams[1].toShort(), gpsParams[2] ); } - else if ( mPortList.at( mPortIndex ).first.contains( "internalGPS" ) ) + else if ( mPortList.at( mPortIndex ).first.contains( QLatin1String( "internalGPS" ) ) ) { #if defined(HAVE_QT_MOBILITY_LOCATION ) || defined(QT_POSITIONING_LIB) mConn = new QgsQtLocationConnection(); diff --git a/src/core/gps/qgsnmeaconnection.cpp b/src/core/gps/qgsnmeaconnection.cpp index f116010f4315..4d43eec289c3 100644 --- a/src/core/gps/qgsnmeaconnection.cpp +++ b/src/core/gps/qgsnmeaconnection.cpp @@ -79,11 +79,11 @@ void QgsNMEAConnection::processStringBuffer() int endSentenceIndex = 0; int dollarIndex; - while (( endSentenceIndex = mStringBuffer.indexOf( "\r\n" ) ) && endSentenceIndex != -1 ) + while (( endSentenceIndex = mStringBuffer.indexOf( QLatin1String( "\r\n" ) ) ) && endSentenceIndex != -1 ) { - endSentenceIndex = mStringBuffer.indexOf( "\r\n" ); + endSentenceIndex = mStringBuffer.indexOf( QLatin1String( "\r\n" ) ); - dollarIndex = mStringBuffer.indexOf( "$" ); + dollarIndex = mStringBuffer.indexOf( QLatin1String( "$" ) ); if ( endSentenceIndex == -1 ) { break; @@ -96,35 +96,35 @@ void QgsNMEAConnection::processStringBuffer() { QString substring = mStringBuffer.mid( dollarIndex, endSentenceIndex ); QByteArray ba = substring.toLocal8Bit(); - if ( substring.startsWith( "$GPGGA" ) ) + if ( substring.startsWith( QLatin1String( "$GPGGA" ) ) ) { QgsDebugMsg( substring ); processGGASentence( ba.data(), ba.length() ); mStatus = GPSDataReceived; QgsDebugMsg( "*******************GPS data received****************" ); } - else if ( substring.startsWith( "$GPRMC" ) || substring.startsWith( "$GNRMC" ) ) + else if ( substring.startsWith( QLatin1String( "$GPRMC" ) ) || substring.startsWith( QLatin1String( "$GNRMC" ) ) ) { QgsDebugMsg( substring ); processRMCSentence( ba.data(), ba.length() ); mStatus = GPSDataReceived; QgsDebugMsg( "*******************GPS data received****************" ); } - else if ( substring.startsWith( "$GPGSV" ) ) + else if ( substring.startsWith( QLatin1String( "$GPGSV" ) ) ) { QgsDebugMsg( substring ); processGSVSentence( ba.data(), ba.length() ); mStatus = GPSDataReceived; QgsDebugMsg( "*******************GPS data received****************" ); } - else if ( substring.startsWith( "$GPVTG" ) ) + else if ( substring.startsWith( QLatin1String( "$GPVTG" ) ) ) { QgsDebugMsg( substring ); processVTGSentence( ba.data(), ba.length() ); mStatus = GPSDataReceived; QgsDebugMsg( "*******************GPS data received****************" ); } - else if ( substring.startsWith( "$GPGSA" ) ) + else if ( substring.startsWith( QLatin1String( "$GPGSA" ) ) ) { QgsDebugMsg( substring ); processGSASentence( ba.data(), ba.length() ); diff --git a/src/core/layertree/qgslayertreegroup.cpp b/src/core/layertree/qgslayertreegroup.cpp index c7b7ca36e0bd..71d194029e23 100644 --- a/src/core/layertree/qgslayertreegroup.cpp +++ b/src/core/layertree/qgslayertreegroup.cpp @@ -242,14 +242,14 @@ QgsLayerTreeGroup* QgsLayerTreeGroup::findGroup( const QString& name ) QgsLayerTreeGroup* QgsLayerTreeGroup::readXml( QDomElement& element ) { - if ( element.tagName() != "layer-tree-group" ) + if ( element.tagName() != QLatin1String( "layer-tree-group" ) ) return nullptr; - QString name = element.attribute( "name" ); - bool isExpanded = ( element.attribute( "expanded", "1" ) == "1" ); - Qt::CheckState checked = QgsLayerTreeUtils::checkStateFromXml( element.attribute( "checked" ) ); - bool isMutuallyExclusive = element.attribute( "mutually-exclusive", "0" ) == "1"; - int mutuallyExclusiveChildIndex = element.attribute( "mutually-exclusive-child", "-1" ).toInt(); + QString name = element.attribute( QStringLiteral( "name" ) ); + bool isExpanded = ( element.attribute( QStringLiteral( "expanded" ), QStringLiteral( "1" ) ) == QLatin1String( "1" ) ); + Qt::CheckState checked = QgsLayerTreeUtils::checkStateFromXml( element.attribute( QStringLiteral( "checked" ) ) ); + bool isMutuallyExclusive = element.attribute( QStringLiteral( "mutually-exclusive" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ); + int mutuallyExclusiveChildIndex = element.attribute( QStringLiteral( "mutually-exclusive-child" ), QStringLiteral( "-1" ) ).toInt(); QgsLayerTreeGroup* groupNode = new QgsLayerTreeGroup( name, checked ); groupNode->setExpanded( isExpanded ); @@ -266,14 +266,14 @@ QgsLayerTreeGroup* QgsLayerTreeGroup::readXml( QDomElement& element ) void QgsLayerTreeGroup::writeXml( QDomElement& parentElement ) { QDomDocument doc = parentElement.ownerDocument(); - QDomElement elem = doc.createElement( "layer-tree-group" ); - elem.setAttribute( "name", mName ); - elem.setAttribute( "expanded", mExpanded ? "1" : "0" ); - elem.setAttribute( "checked", QgsLayerTreeUtils::checkStateToXml( mChecked ) ); + QDomElement elem = doc.createElement( QStringLiteral( "layer-tree-group" ) ); + elem.setAttribute( QStringLiteral( "name" ), mName ); + elem.setAttribute( QStringLiteral( "expanded" ), mExpanded ? "1" : "0" ); + elem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( mChecked ) ); if ( mMutuallyExclusive ) { - elem.setAttribute( "mutually-exclusive", "1" ); - elem.setAttribute( "mutually-exclusive-child", mMutuallyExclusiveChildIndex ); + elem.setAttribute( QStringLiteral( "mutually-exclusive" ), QStringLiteral( "1" ) ); + elem.setAttribute( QStringLiteral( "mutually-exclusive-child" ), mMutuallyExclusiveChildIndex ); } writeCommonXml( elem ); @@ -302,13 +302,13 @@ void QgsLayerTreeGroup::readChildrenFromXml( QDomElement& element ) QString QgsLayerTreeGroup::dump() const { - QString header = QString( "GROUP: %1 visible=%2 expanded=%3\n" ).arg( name() ).arg( mChecked ).arg( mExpanded ); + QString header = QStringLiteral( "GROUP: %1 visible=%2 expanded=%3\n" ).arg( name() ).arg( mChecked ).arg( mExpanded ); QStringList childrenDump; Q_FOREACH ( QgsLayerTreeNode* node, mChildren ) childrenDump << node->dump().split( '\n' ); for ( int i = 0; i < childrenDump.count(); ++i ) childrenDump[i].prepend( " " ); - return header + childrenDump.join( "\n" ); + return header + childrenDump.join( QStringLiteral( "\n" ) ); } QgsLayerTreeGroup* QgsLayerTreeGroup::clone() const diff --git a/src/core/layertree/qgslayertreelayer.cpp b/src/core/layertree/qgslayertreelayer.cpp index 1b64660e1c52..4900006f13f5 100644 --- a/src/core/layertree/qgslayertreelayer.cpp +++ b/src/core/layertree/qgslayertreelayer.cpp @@ -64,7 +64,7 @@ void QgsLayerTreeLayer::attachToLayer() else { if ( mLayerName.isEmpty() ) - mLayerName = "(?)"; + mLayerName = QStringLiteral( "(?)" ); // wait for the layer to be eventually loaded connect( QgsMapLayerRegistry::instance(), SIGNAL( layersAdded( QList ) ), this, SLOT( registryLayersAdded( QList ) ) ); } @@ -95,13 +95,13 @@ void QgsLayerTreeLayer::setVisible( Qt::CheckState state ) QgsLayerTreeLayer* QgsLayerTreeLayer::readXml( QDomElement& element ) { - if ( element.tagName() != "layer-tree-layer" ) + if ( element.tagName() != QLatin1String( "layer-tree-layer" ) ) return nullptr; - QString layerID = element.attribute( "id" ); - QString layerName = element.attribute( "name" ); - Qt::CheckState checked = QgsLayerTreeUtils::checkStateFromXml( element.attribute( "checked" ) ); - bool isExpanded = ( element.attribute( "expanded", "1" ) == "1" ); + QString layerID = element.attribute( QStringLiteral( "id" ) ); + QString layerName = element.attribute( QStringLiteral( "name" ) ); + Qt::CheckState checked = QgsLayerTreeUtils::checkStateFromXml( element.attribute( QStringLiteral( "checked" ) ) ); + bool isExpanded = ( element.attribute( QStringLiteral( "expanded" ), QStringLiteral( "1" ) ) == QLatin1String( "1" ) ); QgsLayerTreeLayer* nodeLayer = nullptr; @@ -122,11 +122,11 @@ QgsLayerTreeLayer* QgsLayerTreeLayer::readXml( QDomElement& element ) void QgsLayerTreeLayer::writeXml( QDomElement& parentElement ) { QDomDocument doc = parentElement.ownerDocument(); - QDomElement elem = doc.createElement( "layer-tree-layer" ); - elem.setAttribute( "id", mLayerId ); - elem.setAttribute( "name", layerName() ); - elem.setAttribute( "checked", QgsLayerTreeUtils::checkStateToXml( mVisible ) ); - elem.setAttribute( "expanded", mExpanded ? "1" : "0" ); + QDomElement elem = doc.createElement( QStringLiteral( "layer-tree-layer" ) ); + elem.setAttribute( QStringLiteral( "id" ), mLayerId ); + elem.setAttribute( QStringLiteral( "name" ), layerName() ); + elem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( mVisible ) ); + elem.setAttribute( QStringLiteral( "expanded" ), mExpanded ? "1" : "0" ); writeCommonXml( elem ); @@ -135,7 +135,7 @@ void QgsLayerTreeLayer::writeXml( QDomElement& parentElement ) QString QgsLayerTreeLayer::dump() const { - return QString( "LAYER: %1 visible=%2 expanded=%3 id=%4\n" ).arg( layerName() ).arg( mVisible ).arg( mExpanded ).arg( layerId() ); + return QStringLiteral( "LAYER: %1 visible=%2 expanded=%3 id=%4\n" ).arg( layerName() ).arg( mVisible ).arg( mExpanded ).arg( layerId() ); } QgsLayerTreeLayer* QgsLayerTreeLayer::clone() const diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index 8f2dc19d2b86..2fc0cf86be07 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -192,11 +192,11 @@ QVariant QgsLayerTreeModel::data( const QModelIndex &index, int role ) const { QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node ); QString name = nodeLayer->layerName(); - if ( nodeLayer->customProperty( "showFeatureCount", 0 ).toInt() && role == Qt::DisplayRole ) + if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() && role == Qt::DisplayRole ) { QgsVectorLayer* vlayer = qobject_cast( nodeLayer->layer() ); if ( vlayer && vlayer->featureCount() >= 0 ) - name += QString( " [%1]" ).arg( vlayer->featureCount() ); + name += QStringLiteral( " [%1]" ).arg( vlayer->featureCount() ); } return name; } @@ -288,7 +288,7 @@ QVariant QgsLayerTreeModel::data( const QModelIndex &index, int role ) const else if ( role == Qt::FontRole ) { QFont f( QgsLayerTree::isLayer( node ) ? mFontLayer : ( QgsLayerTree::isGroup( node ) ? mFontGroup : QFont() ) ); - if ( node->customProperty( "embedded" ).toInt() ) + if ( node->customProperty( QStringLiteral( "embedded" ) ).toInt() ) f.setItalic( true ); if ( index == mCurrentIndex ) f.setUnderline( true ); @@ -316,7 +316,7 @@ QVariant QgsLayerTreeModel::data( const QModelIndex &index, int role ) const QString tooltip = "" + ( layer->title().isEmpty() ? layer->shortName() : layer->title() ) + ""; if ( !layer->abstract().isEmpty() ) - tooltip += "
                                                                                                                                                                                    " + layer->abstract().replace( "\n", "
                                                                                                                                                                                    " ); + tooltip += "
                                                                                                                                                                                    " + layer->abstract().replace( QLatin1String( "\n" ), QLatin1String( "
                                                                                                                                                                                    " ) ); tooltip += "
                                                                                                                                                                                    " + layer->publicSource() + ""; return tooltip; } @@ -346,12 +346,12 @@ Qt::ItemFlags QgsLayerTreeModel::flags( const QModelIndex& index ) const f |= Qt::ItemIsEditable; QgsLayerTreeNode* node = index2node( index ); - bool isEmbedded = node->customProperty( "embedded" ).toInt(); + bool isEmbedded = node->customProperty( QStringLiteral( "embedded" ) ).toInt(); if ( testFlag( AllowNodeReorder ) ) { // only root embedded nodes can be reordered - if ( !isEmbedded || ( isEmbedded && node->parent() && !node->parent()->customProperty( "embedded" ).toInt() ) ) + if ( !isEmbedded || ( isEmbedded && node->parent() && !node->parent()->customProperty( QStringLiteral( "embedded" ) ).toInt() ) ) f |= Qt::ItemIsDragEnabled; } @@ -738,7 +738,7 @@ void QgsLayerTreeModel::nodeVisibilityChanged( QgsLayerTreeNode* node ) void QgsLayerTreeModel::nodeCustomPropertyChanged( QgsLayerTreeNode* node, const QString& key ) { - if ( QgsLayerTree::isLayer( node ) && key == "showFeatureCount" ) + if ( QgsLayerTree::isLayer( node ) && key == QLatin1String( "showFeatureCount" ) ) refreshLayerLegend( QgsLayerTree::toLayer( node ) ); } @@ -794,7 +794,7 @@ void QgsLayerTreeModel::layerNeedsUpdate() QModelIndex index = node2index( nodeLayer ); emit dataChanged( index, index ); - if ( nodeLayer->customProperty( "showFeatureCount" ).toInt() ) + if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ) ).toInt() ) refreshLayerLegend( nodeLayer ); } @@ -829,7 +829,7 @@ void QgsLayerTreeModel::connectToLayer( QgsLayerTreeLayer* nodeLayer ) addLegendToLayer( nodeLayer ); // automatic collapse of legend nodes - useful if a layer has many legend nodes - if ( !mRootNode->customProperty( "loading" ).toBool() ) + if ( !mRootNode->customProperty( QStringLiteral( "loading" ) ).toBool() ) { if ( mAutoCollapseLegendNodesCount != -1 && rowCount( node2index( nodeLayer ) ) >= mAutoCollapseLegendNodesCount ) nodeLayer->setExpanded( false ); @@ -974,7 +974,7 @@ Qt::DropActions QgsLayerTreeModel::supportedDropActions() const QStringList QgsLayerTreeModel::mimeTypes() const { QStringList types; - types << "application/qgis.layertreemodeldata"; + types << QStringLiteral( "application/qgis.layertreemodeldata" ); return types; } @@ -993,15 +993,15 @@ QMimeData* QgsLayerTreeModel::mimeData( const QModelIndexList& indexes ) const QMimeData *mimeData = new QMimeData(); QDomDocument doc; - QDomElement rootElem = doc.createElement( "layer_tree_model_data" ); + QDomElement rootElem = doc.createElement( QStringLiteral( "layer_tree_model_data" ) ); Q_FOREACH ( QgsLayerTreeNode* node, nodesFinal ) node->writeXml( rootElem ); doc.appendChild( rootElem ); QString txt = doc.toString(); - mimeData->setData( "application/qgis.layertreemodeldata", txt.toUtf8() ); + mimeData->setData( QStringLiteral( "application/qgis.layertreemodeldata" ), txt.toUtf8() ); - mimeData->setData( "application/x-vnd.qgis.qgis.uri", QgsMimeDataUtils::layerTreeNodesToUriList( nodesFinal ) ); + mimeData->setData( QStringLiteral( "application/x-vnd.qgis.qgis.uri" ), QgsMimeDataUtils::layerTreeNodesToUriList( nodesFinal ) ); return mimeData; } @@ -1011,7 +1011,7 @@ bool QgsLayerTreeModel::dropMimeData( const QMimeData* data, Qt::DropAction acti if ( action == Qt::IgnoreAction ) return true; - if ( !data->hasFormat( "application/qgis.layertreemodeldata" ) ) + if ( !data->hasFormat( QStringLiteral( "application/qgis.layertreemodeldata" ) ) ) return false; if ( column >= columnCount( parent ) ) @@ -1021,14 +1021,14 @@ bool QgsLayerTreeModel::dropMimeData( const QMimeData* data, Qt::DropAction acti if ( !QgsLayerTree::isGroup( nodeParent ) ) return false; - QByteArray encodedData = data->data( "application/qgis.layertreemodeldata" ); + QByteArray encodedData = data->data( QStringLiteral( "application/qgis.layertreemodeldata" ) ); QDomDocument doc; if ( !doc.setContent( QString::fromUtf8( encodedData ) ) ) return false; QDomElement rootElem = doc.documentElement(); - if ( rootElem.tagName() != "layer_tree_model_data" ) + if ( rootElem.tagName() != QLatin1String( "layer_tree_model_data" ) ) return false; QList nodes; @@ -1093,7 +1093,7 @@ const QIcon& QgsLayerTreeModel::iconGroup() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mActionFolder.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mActionFolder.svg" ) ); return icon; } @@ -1186,7 +1186,7 @@ void QgsLayerTreeModel::addLegendToLayer( QgsLayerTreeLayer* nodeL ) if ( testFlag( UseEmbeddedWidgets ) ) { // generate placeholder legend nodes that will be replaced by widgets in QgsLayerTreeView - int widgetsCount = ml->customProperty( "embeddedWidgets/count", 0 ).toInt(); + int widgetsCount = ml->customProperty( QStringLiteral( "embeddedWidgets/count" ), 0 ).toInt(); while ( widgetsCount > 0 ) { lstNew.insert( 0, new EmbeddedWidgetLegendNode( nodeL ) ); diff --git a/src/core/layertree/qgslayertreemodellegendnode.cpp b/src/core/layertree/qgslayertreemodellegendnode.cpp index fc232c010c8d..e4d687823404 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.cpp +++ b/src/core/layertree/qgslayertreemodellegendnode.cpp @@ -452,24 +452,24 @@ void QgsSymbolLegendNode::invalidateMapBasedData() void QgsSymbolLegendNode::updateLabel() { - bool showFeatureCount = mLayerNode->customProperty( "showFeatureCount", 0 ).toBool(); + bool showFeatureCount = mLayerNode->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toBool(); QgsVectorLayer* vl = qobject_cast( mLayerNode->layer() ); if ( mEmbeddedInParent ) { QString layerName = mLayerNode->layerName(); - if ( !mLayerNode->customProperty( "legend/title-label" ).isNull() ) - layerName = mLayerNode->customProperty( "legend/title-label" ).toString(); + if ( !mLayerNode->customProperty( QStringLiteral( "legend/title-label" ) ).isNull() ) + layerName = mLayerNode->customProperty( QStringLiteral( "legend/title-label" ) ).toString(); mLabel = mUserLabel.isEmpty() ? layerName : mUserLabel; if ( showFeatureCount && vl && vl->featureCount() >= 0 ) - mLabel += QString( " [%1]" ).arg( vl->featureCount() ); + mLabel += QStringLiteral( " [%1]" ).arg( vl->featureCount() ); } else { mLabel = mUserLabel.isEmpty() ? mItem.label() : mUserLabel; if ( showFeatureCount && vl && mItem.legacyRuleKey() ) - mLabel += QString( " [%1]" ).arg( vl->featureCount( mItem.legacyRuleKey() ) ); + mLabel += QStringLiteral( " [%1]" ).arg( vl->featureCount( mItem.legacyRuleKey() ) ); } } @@ -665,7 +665,7 @@ QImage QgsWmsLegendNode::renderMessage( const QString& msg ) const QPainter painter; painter.begin( &theImage ); painter.setPen( QColor( 255, 0, 0 ) ); - painter.setFont( QFont( "Chicago", fontHeight ) ); + painter.setFont( QFont( QStringLiteral( "Chicago" ), fontHeight ) ); painter.fillRect( 0, 0, w, h, QColor( 255, 255, 255 ) ); painter.drawText( 0, margin + fontHeight, msg ); //painter.drawText(0,2*(margin+fontHeight),QString("retrying in 5 seconds...")); @@ -676,7 +676,7 @@ QImage QgsWmsLegendNode::renderMessage( const QString& msg ) const void QgsWmsLegendNode::getLegendGraphicProgress( qint64 cur, qint64 tot ) { - QString msg = QString( "Downloading... %1/%2" ).arg( cur ).arg( tot ); + QString msg = QStringLiteral( "Downloading... %1/%2" ).arg( cur ).arg( tot ); //QgsDebugMsg ( QString("XXX %1").arg(msg) ); mImage = renderMessage( msg ); emit dataChanged(); diff --git a/src/core/layertree/qgslayertreenode.cpp b/src/core/layertree/qgslayertreenode.cpp index 612d9e19cb77..9ffd0de7143a 100644 --- a/src/core/layertree/qgslayertreenode.cpp +++ b/src/core/layertree/qgslayertreenode.cpp @@ -50,9 +50,9 @@ QgsLayerTreeNode::~QgsLayerTreeNode() QgsLayerTreeNode* QgsLayerTreeNode::readXml( QDomElement& element ) { QgsLayerTreeNode* node = nullptr; - if ( element.tagName() == "layer-tree-group" ) + if ( element.tagName() == QLatin1String( "layer-tree-group" ) ) node = QgsLayerTreeGroup::readXml( element ); - else if ( element.tagName() == "layer-tree-layer" ) + else if ( element.tagName() == QLatin1String( "layer-tree-layer" ) ) node = QgsLayerTreeLayer::readXml( element ); return node; diff --git a/src/core/layertree/qgslayertreeregistrybridge.cpp b/src/core/layertree/qgslayertreeregistrybridge.cpp index 627c57492043..abd587866d94 100644 --- a/src/core/layertree/qgslayertreeregistrybridge.cpp +++ b/src/core/layertree/qgslayertreeregistrybridge.cpp @@ -61,8 +61,8 @@ void QgsLayerTreeRegistryBridge::layersAdded( const QList& layers QString projectFile = QgsProject::instance()->layerIsEmbedded( nodeLayer->layerId() ); if ( !projectFile.isEmpty() ) { - nodeLayer->setCustomProperty( "embedded", 1 ); - nodeLayer->setCustomProperty( "embedded_project", projectFile ); + nodeLayer->setCustomProperty( QStringLiteral( "embedded" ), 1 ); + nodeLayer->setCustomProperty( QStringLiteral( "embedded_project" ), projectFile ); } } diff --git a/src/core/layertree/qgslayertreeutils.cpp b/src/core/layertree/qgslayertreeutils.cpp index c9debfac1651..935beaeb2c44 100644 --- a/src/core/layertree/qgslayertreeutils.cpp +++ b/src/core/layertree/qgslayertreeutils.cpp @@ -35,11 +35,11 @@ bool QgsLayerTreeUtils::readOldLegend( QgsLayerTreeGroup* root, const QDomElemen for ( int i = 0; i < legendChildren.size(); ++i ) { QDomElement currentChildElem = legendChildren.at( i ).toElement(); - if ( currentChildElem.tagName() == "legendlayer" ) + if ( currentChildElem.tagName() == QLatin1String( "legendlayer" ) ) { _readOldLegendLayer( currentChildElem, root ); } - else if ( currentChildElem.tagName() == "legendgroup" ) + else if ( currentChildElem.tagName() == QLatin1String( "legendgroup" ) ) { _readOldLegendGroup( currentChildElem, root ); } @@ -57,16 +57,16 @@ static bool _readOldLegendLayerOrderGroup( const QDomElement& groupElem, QMap layerIndexes; @@ -109,21 +109,21 @@ static QDomElement _writeOldLegendLayer( QDomDocument& doc, QgsLayerTreeLayer* n if ( hasCustomOrder ) drawingOrder = order.indexOf( nodeLayer->layerId() ); - QDomElement layerElem = doc.createElement( "legendlayer" ); - layerElem.setAttribute( "drawingOrder", drawingOrder ); - layerElem.setAttribute( "open", nodeLayer->isExpanded() ? "true" : "false" ); - layerElem.setAttribute( "checked", QgsLayerTreeUtils::checkStateToXml( nodeLayer->isVisible() ) ); - layerElem.setAttribute( "name", nodeLayer->layerName() ); - layerElem.setAttribute( "showFeatureCount", nodeLayer->customProperty( "showFeatureCount" ).toInt() ); + QDomElement layerElem = doc.createElement( QStringLiteral( "legendlayer" ) ); + layerElem.setAttribute( QStringLiteral( "drawingOrder" ), drawingOrder ); + layerElem.setAttribute( QStringLiteral( "open" ), nodeLayer->isExpanded() ? "true" : "false" ); + layerElem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( nodeLayer->isVisible() ) ); + layerElem.setAttribute( QStringLiteral( "name" ), nodeLayer->layerName() ); + layerElem.setAttribute( QStringLiteral( "showFeatureCount" ), nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ) ).toInt() ); - QDomElement fileGroupElem = doc.createElement( "filegroup" ); - fileGroupElem.setAttribute( "open", nodeLayer->isExpanded() ? "true" : "false" ); - fileGroupElem.setAttribute( "hidden", "false" ); + QDomElement fileGroupElem = doc.createElement( QStringLiteral( "filegroup" ) ); + fileGroupElem.setAttribute( QStringLiteral( "open" ), nodeLayer->isExpanded() ? "true" : "false" ); + fileGroupElem.setAttribute( QStringLiteral( "hidden" ), QStringLiteral( "false" ) ); - QDomElement layerFileElem = doc.createElement( "legendlayerfile" ); - layerFileElem.setAttribute( "isInOverview", nodeLayer->customProperty( "overview" ).toInt() ); - layerFileElem.setAttribute( "layerid", nodeLayer->layerId() ); - layerFileElem.setAttribute( "visible", nodeLayer->isVisible() == Qt::Checked ? 1 : 0 ); + QDomElement layerFileElem = doc.createElement( QStringLiteral( "legendlayerfile" ) ); + layerFileElem.setAttribute( QStringLiteral( "isInOverview" ), nodeLayer->customProperty( QStringLiteral( "overview" ) ).toInt() ); + layerFileElem.setAttribute( QStringLiteral( "layerid" ), nodeLayer->layerId() ); + layerFileElem.setAttribute( QStringLiteral( "visible" ), nodeLayer->isVisible() == Qt::Checked ? 1 : 0 ); layerElem.appendChild( fileGroupElem ); fileGroupElem.appendChild( layerFileElem ); @@ -135,15 +135,15 @@ static void _writeOldLegendGroupChildren( QDomDocument& doc, QDomElement& groupE static QDomElement _writeOldLegendGroup( QDomDocument& doc, QgsLayerTreeGroup* nodeGroup, bool hasCustomOrder, const QStringList& order ) { - QDomElement groupElem = doc.createElement( "legendgroup" ); - groupElem.setAttribute( "open", nodeGroup->isExpanded() ? "true" : "false" ); - groupElem.setAttribute( "name", nodeGroup->name() ); - groupElem.setAttribute( "checked", QgsLayerTreeUtils::checkStateToXml( nodeGroup->isVisible() ) ); + QDomElement groupElem = doc.createElement( QStringLiteral( "legendgroup" ) ); + groupElem.setAttribute( QStringLiteral( "open" ), nodeGroup->isExpanded() ? "true" : "false" ); + groupElem.setAttribute( QStringLiteral( "name" ), nodeGroup->name() ); + groupElem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( nodeGroup->isVisible() ) ); - if ( nodeGroup->customProperty( "embedded" ).toInt() ) + if ( nodeGroup->customProperty( QStringLiteral( "embedded" ) ).toInt() ) { - groupElem.setAttribute( "embedded", 1 ); - groupElem.setAttribute( "project", nodeGroup->customProperty( "embedded_project" ).toString() ); + groupElem.setAttribute( QStringLiteral( "embedded" ), 1 ); + groupElem.setAttribute( QStringLiteral( "project" ), nodeGroup->customProperty( QStringLiteral( "embedded_project" ) ).toString() ); } _writeOldLegendGroupChildren( doc, groupElem, nodeGroup, hasCustomOrder, order ); @@ -169,8 +169,8 @@ static void _writeOldLegendGroupChildren( QDomDocument& doc, QDomElement& groupE QDomElement QgsLayerTreeUtils::writeOldLegend( QDomDocument& doc, QgsLayerTreeGroup* root, bool hasCustomOrder, const QStringList& order ) { - QDomElement legendElem = doc.createElement( "legend" ); - legendElem.setAttribute( "updateDrawingOrder", hasCustomOrder ? "false" : "true" ); + QDomElement legendElem = doc.createElement( QStringLiteral( "legend" ) ); + legendElem.setAttribute( QStringLiteral( "updateDrawingOrder" ), hasCustomOrder ? "false" : "true" ); _writeOldLegendGroupChildren( doc, legendElem, root, hasCustomOrder, order ); @@ -183,20 +183,20 @@ QString QgsLayerTreeUtils::checkStateToXml( Qt::CheckState state ) switch ( state ) { case Qt::Unchecked: - return "Qt::Unchecked"; + return QStringLiteral( "Qt::Unchecked" ); case Qt::PartiallyChecked: - return "Qt::PartiallyChecked"; + return QStringLiteral( "Qt::PartiallyChecked" ); case Qt::Checked: default: - return "Qt::Checked"; + return QStringLiteral( "Qt::Checked" ); } } Qt::CheckState QgsLayerTreeUtils::checkStateFromXml( const QString& txt ) { - if ( txt == "Qt::Unchecked" ) + if ( txt == QLatin1String( "Qt::Unchecked" ) ) return Qt::Unchecked; - else if ( txt == "Qt::PartiallyChecked" ) + else if ( txt == QLatin1String( "Qt::PartiallyChecked" ) ) return Qt::PartiallyChecked; else // "Qt::Checked" return Qt::Checked; @@ -208,25 +208,25 @@ static void _readOldLegendGroup( const QDomElement& groupElem, QgsLayerTreeGroup { QDomNodeList groupChildren = groupElem.childNodes(); - QgsLayerTreeGroup* groupNode = new QgsLayerTreeGroup( groupElem.attribute( "name" ) ); + QgsLayerTreeGroup* groupNode = new QgsLayerTreeGroup( groupElem.attribute( QStringLiteral( "name" ) ) ); - groupNode->setVisible( QgsLayerTreeUtils::checkStateFromXml( groupElem.attribute( "checked" ) ) ); - groupNode->setExpanded( groupElem.attribute( "open" ) == "true" ); + groupNode->setVisible( QgsLayerTreeUtils::checkStateFromXml( groupElem.attribute( QStringLiteral( "checked" ) ) ) ); + groupNode->setExpanded( groupElem.attribute( QStringLiteral( "open" ) ) == QLatin1String( "true" ) ); - if ( groupElem.attribute( "embedded" ) == "1" ) + if ( groupElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { - groupNode->setCustomProperty( "embedded", 1 ); - groupNode->setCustomProperty( "embedded_project", groupElem.attribute( "project" ) ); + groupNode->setCustomProperty( QStringLiteral( "embedded" ), 1 ); + groupNode->setCustomProperty( QStringLiteral( "embedded_project" ), groupElem.attribute( QStringLiteral( "project" ) ) ); } for ( int i = 0; i < groupChildren.size(); ++i ) { QDomElement currentChildElem = groupChildren.at( i ).toElement(); - if ( currentChildElem.tagName() == "legendlayer" ) + if ( currentChildElem.tagName() == QLatin1String( "legendlayer" ) ) { _readOldLegendLayer( currentChildElem, groupNode ); } - else if ( currentChildElem.tagName() == "legendgroup" ) + else if ( currentChildElem.tagName() == QLatin1String( "legendgroup" ) ) { _readOldLegendGroup( currentChildElem, groupNode ); } @@ -237,21 +237,21 @@ static void _readOldLegendGroup( const QDomElement& groupElem, QgsLayerTreeGroup static void _readOldLegendLayer( const QDomElement& layerElem, QgsLayerTreeGroup* parent ) { - QDomElement layerFileElem = layerElem.firstChildElement( "filegroup" ).firstChildElement( "legendlayerfile" ); - QString layerId = layerFileElem.attribute( "layerid" ); - QgsLayerTreeLayer* layerNode = new QgsLayerTreeLayer( layerId, layerElem.attribute( "name" ) ); + QDomElement layerFileElem = layerElem.firstChildElement( QStringLiteral( "filegroup" ) ).firstChildElement( QStringLiteral( "legendlayerfile" ) ); + QString layerId = layerFileElem.attribute( QStringLiteral( "layerid" ) ); + QgsLayerTreeLayer* layerNode = new QgsLayerTreeLayer( layerId, layerElem.attribute( QStringLiteral( "name" ) ) ); - layerNode->setVisible( QgsLayerTreeUtils::checkStateFromXml( layerElem.attribute( "checked" ) ) ); - layerNode->setExpanded( layerElem.attribute( "open" ) == "true" ); + layerNode->setVisible( QgsLayerTreeUtils::checkStateFromXml( layerElem.attribute( QStringLiteral( "checked" ) ) ) ); + layerNode->setExpanded( layerElem.attribute( QStringLiteral( "open" ) ) == QLatin1String( "true" ) ); - if ( layerFileElem.attribute( "isInOverview" ) == "1" ) - layerNode->setCustomProperty( "overview", 1 ); + if ( layerFileElem.attribute( QStringLiteral( "isInOverview" ) ) == QLatin1String( "1" ) ) + layerNode->setCustomProperty( QStringLiteral( "overview" ), 1 ); - if ( layerElem.attribute( "embedded" ) == "1" ) - layerNode->setCustomProperty( "embedded", 1 ); + if ( layerElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) + layerNode->setCustomProperty( QStringLiteral( "embedded" ), 1 ); - if ( layerElem.attribute( "showFeatureCount" ) == "1" ) - layerNode->setCustomProperty( "showFeatureCount", 1 ); + if ( layerElem.attribute( QStringLiteral( "showFeatureCount" ) ) == QLatin1String( "1" ) ) + layerNode->setCustomProperty( QStringLiteral( "showFeatureCount" ), 1 ); // drawing order is handled by readOldLegendLayerOrder() @@ -334,9 +334,9 @@ void QgsLayerTreeUtils::replaceChildrenOfEmbeddedGroups( QgsLayerTreeGroup* grou { if ( QgsLayerTree::isGroup( child ) ) { - if ( child->customProperty( "embedded" ).toInt() ) + if ( child->customProperty( QStringLiteral( "embedded" ) ).toInt() ) { - child->setCustomProperty( "embedded-invisible-layers", invisibleLayerList( child ) ); + child->setCustomProperty( QStringLiteral( "embedded-invisible-layers" ), invisibleLayerList( child ) ); QgsLayerTree::toGroup( child )->removeAllChildren(); } else @@ -352,11 +352,11 @@ void QgsLayerTreeUtils::updateEmbeddedGroupsProjectPath( QgsLayerTreeGroup* grou { Q_FOREACH ( QgsLayerTreeNode* node, group->children() ) { - if ( !node->customProperty( "embedded_project" ).toString().isEmpty() ) + if ( !node->customProperty( QStringLiteral( "embedded_project" ) ).toString().isEmpty() ) { // may change from absolute path to relative path - QString newPath = QgsProject::instance()->writePath( node->customProperty( "embedded_project" ).toString() ); - node->setCustomProperty( "embedded_project", newPath ); + QString newPath = QgsProject::instance()->writePath( node->customProperty( QStringLiteral( "embedded_project" ) ).toString() ); + node->setCustomProperty( QStringLiteral( "embedded_project" ), newPath ); } if ( QgsLayerTree::isGroup( node ) ) @@ -368,15 +368,15 @@ void QgsLayerTreeUtils::updateEmbeddedGroupsProjectPath( QgsLayerTreeGroup* grou void QgsLayerTreeUtils::setLegendFilterByExpression( QgsLayerTreeLayer& layer, const QString& expr, bool enabled ) { - layer.setCustomProperty( "legend/expressionFilter", expr ); - layer.setCustomProperty( "legend/expressionFilterEnabled", enabled ); + layer.setCustomProperty( QStringLiteral( "legend/expressionFilter" ), expr ); + layer.setCustomProperty( QStringLiteral( "legend/expressionFilterEnabled" ), enabled ); } QString QgsLayerTreeUtils::legendFilterByExpression( const QgsLayerTreeLayer& layer, bool* enabled ) { if ( enabled ) - *enabled = layer.customProperty( "legend/expressionFilterEnabled", "" ).toBool(); - return layer.customProperty( "legend/expressionFilter", "" ).toString(); + *enabled = layer.customProperty( QStringLiteral( "legend/expressionFilterEnabled" ), "" ).toBool(); + return layer.customProperty( QStringLiteral( "legend/expressionFilter" ), "" ).toString(); } bool QgsLayerTreeUtils::hasLegendFilterExpression( const QgsLayerTreeGroup& group ) diff --git a/src/core/qgis.cpp b/src/core/qgis.cpp index f5ce8f2affd1..3693e2578686 100644 --- a/src/core/qgis.cpp +++ b/src/core/qgis.cpp @@ -35,7 +35,7 @@ // // Version string -QString Qgis::QGIS_VERSION( QString::fromUtf8( VERSION ) ); +QString Qgis::QGIS_VERSION( QStringLiteral( VERSION ) ); // development version const char* Qgis::QGIS_DEV_VERSION = QGSVERSION; @@ -45,10 +45,10 @@ const char* Qgis::QGIS_DEV_VERSION = QGSVERSION; const int Qgis::QGIS_VERSION_INT = VERSION_INT; // Release name -QString Qgis::QGIS_RELEASE_NAME( QString::fromUtf8( RELEASE_NAME ) ); +QString Qgis::QGIS_RELEASE_NAME( QStringLiteral( RELEASE_NAME ) ); #if GDAL_VERSION_NUM >= 1800 -const QString GEOPROJ4 = "+proj=longlat +datum=WGS84 +no_defs"; +const QString GEOPROJ4 = QStringLiteral( "+proj=longlat +datum=WGS84 +no_defs" ); #else const QString GEOPROJ4 = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"; #endif @@ -70,9 +70,9 @@ const QString PROJECT_SCALES = "1:1000000,1:500000,1:250000,1:100000,1:50000,1:25000," "1:10000,1:5000,1:2500,1:1000,1:500"; -const QString GEO_EPSG_CRS_AUTHID = "EPSG:4326"; +const QString GEO_EPSG_CRS_AUTHID = QStringLiteral( "EPSG:4326" ); -const QString GEO_NONE = "NONE"; +const QString GEO_NONE = QStringLiteral( "NONE" ); const double Qgis::DEFAULT_SEARCH_RADIUS_MM = 2.; @@ -212,17 +212,17 @@ bool qgsVariantGreaterThan( const QVariant& lhs, const QVariant& rhs ) QString qgsVsiPrefix( const QString& path ) { - if ( path.startsWith( "/vsizip/", Qt::CaseInsensitive ) || - path.endsWith( ".zip", Qt::CaseInsensitive ) ) - return "/vsizip/"; - else if ( path.startsWith( "/vsitar/", Qt::CaseInsensitive ) || - path.endsWith( ".tar", Qt::CaseInsensitive ) || - path.endsWith( ".tar.gz", Qt::CaseInsensitive ) || - path.endsWith( ".tgz", Qt::CaseInsensitive ) ) - return "/vsitar/"; - else if ( path.startsWith( "/vsigzip/", Qt::CaseInsensitive ) || - path.endsWith( ".gz", Qt::CaseInsensitive ) ) - return "/vsigzip/"; + if ( path.startsWith( QLatin1String( "/vsizip/" ), Qt::CaseInsensitive ) || + path.endsWith( QLatin1String( ".zip" ), Qt::CaseInsensitive ) ) + return QStringLiteral( "/vsizip/" ); + else if ( path.startsWith( QLatin1String( "/vsitar/" ), Qt::CaseInsensitive ) || + path.endsWith( QLatin1String( ".tar" ), Qt::CaseInsensitive ) || + path.endsWith( QLatin1String( ".tar.gz" ), Qt::CaseInsensitive ) || + path.endsWith( QLatin1String( ".tgz" ), Qt::CaseInsensitive ) ) + return QStringLiteral( "/vsitar/" ); + else if ( path.startsWith( QLatin1String( "/vsigzip/" ), Qt::CaseInsensitive ) || + path.endsWith( QLatin1String( ".gz" ), Qt::CaseInsensitive ) ) + return QStringLiteral( "/vsigzip/" ); else - return ""; + return QLatin1String( "" ); } diff --git a/src/core/qgsactionmanager.cpp b/src/core/qgsactionmanager.cpp index b20d732fe9d8..e9cd102f27ae 100644 --- a/src/core/qgsactionmanager.cpp +++ b/src/core/qgsactionmanager.cpp @@ -67,7 +67,7 @@ void QgsActionManager::doAction( int index, const QgsFeature& feat, int defaultV { QgsExpressionContext context = createExpressionContext(); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); - actionScope->setVariable( "current_field", feat.attribute( defaultValueIndex ) ); + actionScope->setVariable( QStringLiteral( "current_field" ), feat.attribute( defaultValueIndex ) ); context << actionScope; doAction( index, feat, context ); } @@ -154,19 +154,19 @@ QgsExpressionContext QgsActionManager::createExpressionContext() const bool QgsActionManager::writeXml( QDomNode& layer_node, QDomDocument& doc ) const { - QDomElement aActions = doc.createElement( "attributeactions" ); - aActions.setAttribute( "default", mDefaultAction ); + QDomElement aActions = doc.createElement( QStringLiteral( "attributeactions" ) ); + aActions.setAttribute( QStringLiteral( "default" ), mDefaultAction ); Q_FOREACH ( const QgsAction& action, mActions ) { - QDomElement actionSetting = doc.createElement( "actionsetting" ); - actionSetting.setAttribute( "type", action.type() ); - actionSetting.setAttribute( "name", action.name() ); - actionSetting.setAttribute( "shortTitle", action.shortTitle() ); - actionSetting.setAttribute( "icon", action.iconPath() ); - actionSetting.setAttribute( "action", action.action() ); - actionSetting.setAttribute( "capture", action.capture() ); - actionSetting.setAttribute( "showInAttributeTable", action.showInAttributeTable() ); + QDomElement actionSetting = doc.createElement( QStringLiteral( "actionsetting" ) ); + actionSetting.setAttribute( QStringLiteral( "type" ), action.type() ); + actionSetting.setAttribute( QStringLiteral( "name" ), action.name() ); + actionSetting.setAttribute( QStringLiteral( "shortTitle" ), action.shortTitle() ); + actionSetting.setAttribute( QStringLiteral( "icon" ), action.iconPath() ); + actionSetting.setAttribute( QStringLiteral( "action" ), action.action() ); + actionSetting.setAttribute( QStringLiteral( "capture" ), action.capture() ); + actionSetting.setAttribute( QStringLiteral( "showInAttributeTable" ), action.showInAttributeTable() ); aActions.appendChild( actionSetting ); } layer_node.appendChild( aActions ); @@ -178,24 +178,24 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) { mActions.clear(); - QDomNode aaNode = layer_node.namedItem( "attributeactions" ); + QDomNode aaNode = layer_node.namedItem( QStringLiteral( "attributeactions" ) ); if ( !aaNode.isNull() ) { - mDefaultAction = aaNode.toElement().attribute( "default", 0 ).toInt(); + mDefaultAction = aaNode.toElement().attribute( QStringLiteral( "default" ), 0 ).toInt(); QDomNodeList actionsettings = aaNode.childNodes(); for ( int i = 0; i < actionsettings.size(); ++i ) { QDomElement setting = actionsettings.item( i ).toElement(); mActions.append( - QgsAction( static_cast< QgsAction::ActionType >( setting.attributeNode( "type" ).value().toInt() ), - setting.attributeNode( "name" ).value(), - setting.attributeNode( "action" ).value(), - setting.attributeNode( "icon" ).value(), - setting.attributeNode( "capture" ).value().toInt() != 0, - !setting.attributes().contains( "showInAttributeTable" ) || setting.attributeNode( "showInAttributeTable" ).value().toInt() != 0, - setting.attributeNode( "shortTitle" ).value() + QgsAction( static_cast< QgsAction::ActionType >( setting.attributeNode( QStringLiteral( "type" ) ).value().toInt() ), + setting.attributeNode( QStringLiteral( "name" ) ).value(), + setting.attributeNode( QStringLiteral( "action" ) ).value(), + setting.attributeNode( QStringLiteral( "icon" ) ).value(), + setting.attributeNode( QStringLiteral( "capture" ) ).value().toInt() != 0, + !setting.attributes().contains( QStringLiteral( "showInAttributeTable" ) ) || setting.attributeNode( QStringLiteral( "showInAttributeTable" ) ).value().toInt() != 0, + setting.attributeNode( QStringLiteral( "shortTitle" ) ).value() ) ); } diff --git a/src/core/qgsaggregatecalculator.cpp b/src/core/qgsaggregatecalculator.cpp index 59d32584ec07..4e6524b76f6c 100644 --- a/src/core/qgsaggregatecalculator.cpp +++ b/src/core/qgsaggregatecalculator.cpp @@ -125,45 +125,45 @@ QgsAggregateCalculator::Aggregate QgsAggregateCalculator::stringToAggregate( con if ( ok ) *ok = true; - if ( normalized == "count" ) + if ( normalized == QLatin1String( "count" ) ) return Count; - else if ( normalized == "count_distinct" ) + else if ( normalized == QLatin1String( "count_distinct" ) ) return CountDistinct; - else if ( normalized == "count_missing" ) + else if ( normalized == QLatin1String( "count_missing" ) ) return CountMissing; - else if ( normalized == "min" ) + else if ( normalized == QLatin1String( "min" ) ) return Min; - else if ( normalized == "max" ) + else if ( normalized == QLatin1String( "max" ) ) return Max; - else if ( normalized == "sum" ) + else if ( normalized == QLatin1String( "sum" ) ) return Sum; - else if ( normalized == "mean" ) + else if ( normalized == QLatin1String( "mean" ) ) return Mean; - else if ( normalized == "median" ) + else if ( normalized == QLatin1String( "median" ) ) return Median; - else if ( normalized == "stdev" ) + else if ( normalized == QLatin1String( "stdev" ) ) return StDev; - else if ( normalized == "stdevsample" ) + else if ( normalized == QLatin1String( "stdevsample" ) ) return StDevSample; - else if ( normalized == "range" ) + else if ( normalized == QLatin1String( "range" ) ) return Range; - else if ( normalized == "minority" ) + else if ( normalized == QLatin1String( "minority" ) ) return Minority; - else if ( normalized == "majority" ) + else if ( normalized == QLatin1String( "majority" ) ) return Majority; - else if ( normalized == "q1" ) + else if ( normalized == QLatin1String( "q1" ) ) return FirstQuartile; - else if ( normalized == "q3" ) + else if ( normalized == QLatin1String( "q3" ) ) return ThirdQuartile; - else if ( normalized == "iqr" ) + else if ( normalized == QLatin1String( "iqr" ) ) return InterQuartileRange; - else if ( normalized == "min_length" ) + else if ( normalized == QLatin1String( "min_length" ) ) return StringMinimumLength; - else if ( normalized == "max_length" ) + else if ( normalized == QLatin1String( "max_length" ) ) return StringMaximumLength; - else if ( normalized == "concatenate" ) + else if ( normalized == QLatin1String( "concatenate" ) ) return StringConcatenate; - else if ( normalized == "collect" ) + else if ( normalized == QLatin1String( "collect" ) ) return GeometryCollect; if ( ok ) diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 898f9371e4ec..1502c107cc23 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -79,7 +79,7 @@ QString ABISYM( QgsApplication::mAuthDbDirPath ); QString QgsApplication::sUserName; QString QgsApplication::sUserFullName; -QString QgsApplication::sPlatformName = "desktop"; +QString QgsApplication::sPlatformName = QStringLiteral( "desktop" ); const char* QgsApplication::QGIS_ORGANIZATION_NAME = "QGIS"; const char* QgsApplication::QGIS_ORGANIZATION_DOMAIN = "qgis.org"; @@ -116,7 +116,7 @@ void QgsApplication::init( QString customConfigPath ) } else { - customConfigPath = QString( "%1/.qgis3/" ).arg( QDir::homePath() ); + customConfigPath = QStringLiteral( "%1/.qgis3/" ).arg( QDir::homePath() ); } } @@ -155,7 +155,7 @@ void QgsApplication::init( QString customConfigPath ) #if defined(_MSC_VER) && !defined(USING_NMAKE) && !defined(USING_NINJA) setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QString( QGIS_PLUGIN_SUBDIR ) + '/' + ABISYM( mCfgIntDir ) ); #else - setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QString( QGIS_PLUGIN_SUBDIR ) ); + setPluginPath( ABISYM( mBuildOutputPath ) + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) ); #endif setPkgDataPath( ABISYM( mBuildSourcePath ) ); // directly source path - used for: doc, resources, svg ABISYM( mLibraryPath ) = ABISYM( mBuildOutputPath ) + '/' + QGIS_LIB_SUBDIR + '/'; @@ -196,7 +196,7 @@ void QgsApplication::init( QString customConfigPath ) ABISYM( mConfigPath ) = customConfigPath + '/'; // make sure trailing slash is included } - ABISYM( mDefaultSvgPaths ) << qgisSettingsDirPath() + QLatin1String( "svg/" ); + ABISYM( mDefaultSvgPaths ) << qgisSettingsDirPath() + QStringLiteral( "svg/" ); ABISYM( mAuthDbDirPath ) = qgisSettingsDirPath(); if ( getenv( "QGIS_AUTH_DB_DIR_PATH" ) ) @@ -207,7 +207,7 @@ void QgsApplication::init( QString customConfigPath ) // store system environment variables passed to application, before they are adjusted QMap systemEnvVarMap; - QString passfile( "QGIS_AUTH_PASSWORD_FILE" ); // QString, for comparison + QString passfile( QStringLiteral( "QGIS_AUTH_PASSWORD_FILE" ) ); // QString, for comparison Q_FOREACH ( const QString &varStr, QProcess::systemEnvironment() ) { int pos = varStr.indexOf( QLatin1Char( '=' ) ); @@ -329,8 +329,8 @@ void QgsApplication::setPrefixPath( const QString &thePrefixPath, bool useDefaul #endif if ( useDefaultPaths && !ABISYM( mRunningFromBuildDir ) ) { - setPluginPath( ABISYM( mPrefixPath ) + '/' + QString( QGIS_PLUGIN_SUBDIR ) ); - setPkgDataPath( ABISYM( mPrefixPath ) + '/' + QString( QGIS_DATA_SUBDIR ) ); + setPluginPath( ABISYM( mPrefixPath ) + '/' + QStringLiteral( QGIS_PLUGIN_SUBDIR ) ); + setPkgDataPath( ABISYM( mPrefixPath ) + '/' + QStringLiteral( QGIS_DATA_SUBDIR ) ); } ABISYM( mLibraryPath ) = ABISYM( mPrefixPath ) + '/' + QGIS_LIB_SUBDIR + '/'; ABISYM( mLibexecPath ) = ABISYM( mPrefixPath ) + '/' + QGIS_LIBEXEC_SUBDIR + '/'; @@ -386,7 +386,7 @@ QString QgsApplication::pkgDataPath() } QString QgsApplication::defaultThemePath() { - return ":/images/themes/default/"; + return QStringLiteral( ":/images/themes/default/" ); } QString QgsApplication::activeThemePath() { @@ -395,7 +395,7 @@ QString QgsApplication::activeThemePath() QString QgsApplication::appIconPath() { - return iconsPath() + ( QDate::currentDate().month() == 12 ? tr( "qgis-icon-60x60_xmas.png", "December application icon" ) : QString( "qgis-icon-60x60.png" ) ); + return iconsPath() + ( QDate::currentDate().month() == 12 ? tr( "qgis-icon-60x60_xmas.png", "December application icon" ) : QStringLiteral( "qgis-icon-60x60.png" ) ); } QString QgsApplication::iconPath( const QString& iconFile ) @@ -477,7 +477,7 @@ void QgsApplication::setUITheme( const QString &themeName ) QHash themes = QgsApplication::uiThemes(); QString themename = themeName; if ( !themes.contains( themename ) ) - themename = "default"; + themename = QStringLiteral( "default" ); QString path = themes[themename]; QString stylesheetname = path + "/style.qss"; @@ -519,7 +519,7 @@ void QgsApplication::setUITheme( const QString &themeName ) stylesheetname = autostylesheet; } - QString styleSheet = QLatin1String( "file:///" ); + QString styleSheet = QStringLiteral( "file:///" ); styleSheet.append( stylesheetname ); qApp->setStyleSheet( styleSheet ); setThemeName( themename ); @@ -529,7 +529,7 @@ QHash QgsApplication::uiThemes() { QStringList paths = QStringList() << userThemesFolder(); QHash mapping; - mapping.insert( "default", "" ); + mapping.insert( QStringLiteral( "default" ), QLatin1String( "" ) ); Q_FOREACH ( const QString& path, paths ) { QDir folder( path ); @@ -553,18 +553,18 @@ QHash QgsApplication::uiThemes() */ QString QgsApplication::authorsFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/AUTHORS" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/AUTHORS" ); } /*! Returns the path to the contributors file. */ QString QgsApplication::contributorsFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/CONTRIBUTORS" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/CONTRIBUTORS" ); } QString QgsApplication::developersMapFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/developersmap.html" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/developersmap.html" ); } /*! @@ -572,7 +572,7 @@ QString QgsApplication::developersMapFilePath() */ QString QgsApplication::sponsorsFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/SPONSORS" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/SPONSORS" ); } /*! @@ -580,19 +580,19 @@ QString QgsApplication::sponsorsFilePath() */ QString QgsApplication::donorsFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/DONORS" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/DONORS" ); } /** Returns the path to the sponsors file. */ QString QgsApplication::translatorsFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/TRANSLATORS" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/TRANSLATORS" ); } /** Returns the path to the licence file. */ QString QgsApplication::licenceFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/doc/LICENSE" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/LICENSE" ); } /*! @@ -606,7 +606,7 @@ QString QgsApplication::helpAppPath() #else helpAppPath = libexecPath(); #endif - helpAppPath += "/qgis_help"; + helpAppPath += QLatin1String( "/qgis_help" ); #ifdef Q_OS_WIN helpAppPath += ".exe"; #endif @@ -618,9 +618,9 @@ QString QgsApplication::helpAppPath() QString QgsApplication::i18nPath() { if ( ABISYM( mRunningFromBuildDir ) ) - return ABISYM( mBuildOutputPath ) + QLatin1String( "/i18n" ); + return ABISYM( mBuildOutputPath ) + QStringLiteral( "/i18n" ); else - return ABISYM( mPkgDataPath ) + QLatin1String( "/i18n/" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/i18n/" ); } /*! @@ -628,7 +628,7 @@ QString QgsApplication::i18nPath() */ QString QgsApplication::qgisMasterDbFilePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/resources/qgis.db" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/resources/qgis.db" ); } /*! @@ -644,7 +644,7 @@ QString QgsApplication::qgisSettingsDirPath() */ QString QgsApplication::qgisUserDbFilePath() { - return qgisSettingsDirPath() + QLatin1String( "qgis.db" ); + return qgisSettingsDirPath() + QStringLiteral( "qgis.db" ); } /*! @@ -652,7 +652,7 @@ QString QgsApplication::qgisUserDbFilePath() */ QString QgsApplication::qgisAuthDbFilePath() { - return ABISYM( mAuthDbDirPath ) + QLatin1String( "qgis-auth.db" ); + return ABISYM( mAuthDbDirPath ) + QStringLiteral( "qgis-auth.db" ); } /*! @@ -660,7 +660,7 @@ QString QgsApplication::qgisAuthDbFilePath() */ QString QgsApplication::splashPath() { - return QString( ":/images/splash/" ); + return QStringLiteral( ":/images/splash/" ); } /*! @@ -668,7 +668,7 @@ QString QgsApplication::splashPath() */ QString QgsApplication::iconsPath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/images/icons/" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/images/icons/" ); } /*! Returns the path to the srs.db file. @@ -692,7 +692,7 @@ QString QgsApplication::srsDbFilePath() } else { - return ABISYM( mPkgDataPath ) + QLatin1String( "/resources/srs.db" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/resources/srs.db" ); } } @@ -705,7 +705,7 @@ QStringList QgsApplication::svgPaths() //defined by user in options dialog QSettings settings; QStringList myPathList; - QString myPaths = settings.value( "svg/searchPathsForSVG", QString() ).toString(); + QString myPaths = settings.value( QStringLiteral( "svg/searchPathsForSVG" ), QString() ).toString(); if ( !myPaths.isEmpty() ) { myPathList = myPaths.split( '|' ); @@ -736,7 +736,7 @@ QStringList QgsApplication::composerTemplatePaths() //defined by user in options dialog QSettings settings; QStringList myPathList; - QString myPaths = settings.value( "composer/searchPathsForTemplates", QString() ).toString(); + QString myPaths = settings.value( QStringLiteral( "composer/searchPathsForTemplates" ), QString() ).toString(); if ( !myPaths.isEmpty() ) { myPathList = myPaths.split( '|' ); @@ -747,7 +747,7 @@ QStringList QgsApplication::composerTemplatePaths() QString QgsApplication::userStylePath() { - return qgisSettingsDirPath() + QLatin1String( "symbology-ng-style.db" ); + return qgisSettingsDirPath() + QStringLiteral( "symbology-ng-style.db" ); } QRegExp QgsApplication::shortNameRegExp() @@ -772,7 +772,7 @@ QString QgsApplication::userLoginName() #else QProcess process; - process.start( "whoami" ); + process.start( QStringLiteral( "whoami" ) ); process.waitForFinished(); sUserName = process.readAllStandardOutput().trimmed(); #endif @@ -833,7 +833,7 @@ QString QgsApplication::osName() #elif defined(Q_OS_WIN) return QLatin1String( "windows" ); #elif defined(Q_OS_LINUX) - return QLatin1String( "linux" ); + return QStringLiteral( "linux" ); #else return QLatin1String( "unknown" ); #endif @@ -846,17 +846,17 @@ QString QgsApplication::platform() QString QgsApplication::userThemesFolder() { - return qgisSettingsDirPath() + QLatin1String( "/themes" ); + return qgisSettingsDirPath() + QStringLiteral( "/themes" ); } QString QgsApplication::defaultStylePath() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/resources/symbology-ng-style.db" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/resources/symbology-ng-style.db" ); } QString QgsApplication::defaultThemesFolder() { - return ABISYM( mPkgDataPath ) + QLatin1String( "/resources/themes" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/resources/themes" ); } QString QgsApplication::libraryPath() @@ -1076,8 +1076,8 @@ QString QgsApplication::absolutePathToRelativePath( const QString& aPath, const QStringList targetElems = tPathUrl.split( '/', QString::SkipEmptyParts ); QStringList aPathElems = aPathUrl.split( '/', QString::SkipEmptyParts ); - targetElems.removeAll( "." ); - aPathElems.removeAll( "." ); + targetElems.removeAll( QStringLiteral( "." ) ); + aPathElems.removeAll( QStringLiteral( "." ) ); // remove common part int n = 0; @@ -1101,23 +1101,23 @@ QString QgsApplication::absolutePathToRelativePath( const QString& aPath, const // go up to the common directory for ( int i = 0; i < targetElems.size(); i++ ) { - aPathElems.insert( 0, ".." ); + aPathElems.insert( 0, QStringLiteral( ".." ) ); } } else { // let it start with . nevertheless, // so relative path always start with either ./ or ../ - aPathElems.insert( 0, "." ); + aPathElems.insert( 0, QStringLiteral( "." ) ); } - return aPathElems.join( "/" ); + return aPathElems.join( QStringLiteral( "/" ) ); } QString QgsApplication::relativePathToAbsolutePath( const QString& rpath, const QString& targetPath ) { // relative path should always start with ./ or ../ - if ( !rpath.startsWith( "./" ) && !rpath.startsWith( "../" ) ) + if ( !rpath.startsWith( QLatin1String( "./" ) ) && !rpath.startsWith( QLatin1String( "../" ) ) ) { return rpath; } @@ -1145,11 +1145,11 @@ QString QgsApplication::relativePathToAbsolutePath( const QString& rpath, const // append source path elements targetElems << srcElems; - targetElems.removeAll( "." ); + targetElems.removeAll( QStringLiteral( "." ) ); // resolve .. int pos; - while (( pos = targetElems.indexOf( ".." ) ) > 0 ) + while (( pos = targetElems.indexOf( QStringLiteral( ".." ) ) ) > 0 ) { // remove preceding element and .. targetElems.removeAt( pos - 1 ); @@ -1158,10 +1158,10 @@ QString QgsApplication::relativePathToAbsolutePath( const QString& rpath, const #if !defined(Q_OS_WIN) // make path absolute - targetElems.prepend( "" ); + targetElems.prepend( QLatin1String( "" ) ); #endif - return targetElems.join( "/" ); + return targetElems.join( QStringLiteral( "/" ) ); } void QgsApplication::skipGdalDriver( const QString& theDriver ) @@ -1191,7 +1191,7 @@ void QgsApplication::restoreGdalDriver( const QString& theDriver ) void QgsApplication::applyGdalSkippedDrivers() { ABISYM( mGdalSkipList ).removeDuplicates(); - QString myDriverList = ABISYM( mGdalSkipList ).join( " " ); + QString myDriverList = ABISYM( mGdalSkipList ).join( QStringLiteral( " " ) ); QgsDebugMsg( "Gdal Skipped driver list set to:" ); QgsDebugMsg( myDriverList ); CPLSetConfigOption( "GDAL_SKIP", myDriverList.toUtf8() ); @@ -1235,7 +1235,7 @@ bool QgsApplication::createDB( QString *errorMessage ) // set a working directory up for gdal to write .aux.xml files into // for cases where the raster dir is read only to the user // if the env var is already set it will be used preferentially - QString myPamPath = qgisSettingsDirPath() + QLatin1String( "gdal_pam/" ); + QString myPamPath = qgisSettingsDirPath() + QStringLiteral( "gdal_pam/" ); QDir myDir( myPamPath ); if ( !myDir.exists() ) { diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index cb468852a3fd..f64d46f057c5 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -38,7 +38,11 @@ class CORE_EXPORT QgsApplication : public QApplication static const char* QGIS_ORGANIZATION_NAME; static const char* QGIS_ORGANIZATION_DOMAIN; static const char* QGIS_APPLICATION_NAME; - QgsApplication( int & argc, char ** argv, bool GUIenabled, const QString& customConfigPath = QString(), const QString& platformName = "desktop" ); + + /** + * Constructor for QgsApplication. + */ + QgsApplication( int & argc, char ** argv, bool GUIenabled, const QString& customConfigPath = QString(), const QString& platformName = QStringLiteral( "desktop" ) ); virtual ~QgsApplication(); /** This method initialises paths etc for QGIS. Called by the ctor or call it manually diff --git a/src/core/qgsattributeeditorelement.cpp b/src/core/qgsattributeeditorelement.cpp index fc9fe52f3fa8..c361e232462b 100644 --- a/src/core/qgsattributeeditorelement.cpp +++ b/src/core/qgsattributeeditorelement.cpp @@ -91,19 +91,19 @@ QgsAttributeEditorElement* QgsAttributeEditorRelation::clone( QgsAttributeEditor } void QgsAttributeEditorField::saveConfiguration( QDomElement &elem ) const { - elem.setAttribute( "index", mIdx ); + elem.setAttribute( QStringLiteral( "index" ), mIdx ); } QString QgsAttributeEditorField::typeIdentifier() const { - return "attributeEditorField"; + return QStringLiteral( "attributeEditorField" ); } QDomElement QgsAttributeEditorElement::toDomElement( QDomDocument& doc ) const { QDomElement elem = doc.createElement( typeIdentifier() ); - elem.setAttribute( "name", mName ); - elem.setAttribute( "showLabel", mShowLabel ); + elem.setAttribute( QStringLiteral( "name" ), mName ); + elem.setAttribute( QStringLiteral( "showLabel" ), mShowLabel ); saveConfiguration( elem ); return elem; @@ -121,14 +121,14 @@ void QgsAttributeEditorElement::setShowLabel( bool showLabel ) void QgsAttributeEditorRelation::saveConfiguration( QDomElement& elem ) const { - elem.setAttribute( "relation", mRelation.id() ); - elem.setAttribute( "showLinkButton", mShowLinkButton ); - elem.setAttribute( "showUnlinkButton", mShowUnlinkButton ); + elem.setAttribute( QStringLiteral( "relation" ), mRelation.id() ); + elem.setAttribute( QStringLiteral( "showLinkButton" ), mShowLinkButton ); + elem.setAttribute( QStringLiteral( "showUnlinkButton" ), mShowUnlinkButton ); } QString QgsAttributeEditorRelation::typeIdentifier() const { - return "attributeEditorRelation"; + return QStringLiteral( "attributeEditorRelation" ); } bool QgsAttributeEditorRelation::showLinkButton() const diff --git a/src/core/qgsattributetableconfig.cpp b/src/core/qgsattributetableconfig.cpp index 5752bf5b2b00..e44583534dc3 100644 --- a/src/core/qgsattributetableconfig.cpp +++ b/src/core/qgsattributetableconfig.cpp @@ -140,10 +140,10 @@ void QgsAttributeTableConfig::readXml( const QDomNode& node ) { mColumns.clear(); - QDomNode configNode = node.namedItem( "attributetableconfig" ); + QDomNode configNode = node.namedItem( QStringLiteral( "attributetableconfig" ) ); if ( !configNode.isNull() ) { - QDomNode columnsNode = configNode.toElement().namedItem( "columns" ); + QDomNode columnsNode = configNode.toElement().namedItem( QStringLiteral( "columns" ) ); QDomNodeList columns = columnsNode.childNodes(); @@ -153,23 +153,23 @@ void QgsAttributeTableConfig::readXml( const QDomNode& node ) ColumnConfig column; - if ( columnElement.attribute( "type" ) == "actions" ) + if ( columnElement.attribute( QStringLiteral( "type" ) ) == QLatin1String( "actions" ) ) { column.type = Action; } else { column.type = Field; - column.name = columnElement.attribute( "name" ); + column.name = columnElement.attribute( QStringLiteral( "name" ) ); } - column.hidden = columnElement.attribute( "hidden" ) == "1"; - column.width = columnElement.attribute( "width", "-1" ).toDouble(); + column.hidden = columnElement.attribute( QStringLiteral( "hidden" ) ) == QLatin1String( "1" ); + column.width = columnElement.attribute( QStringLiteral( "width" ), QStringLiteral( "-1" ) ).toDouble(); mColumns.append( column ); } - if ( configNode.toElement().attribute( "actionWidgetStyle" ) == "buttonList" ) + if ( configNode.toElement().attribute( QStringLiteral( "actionWidgetStyle" ) ) == QLatin1String( "buttonList" ) ) mActionWidgetStyle = ButtonList; else mActionWidgetStyle = DropDown; @@ -178,17 +178,17 @@ void QgsAttributeTableConfig::readXml( const QDomNode& node ) { // Before QGIS 2.16 the attribute table would hide "Hidden" widgets. // They are migrated to hidden columns here. - QDomNodeList editTypeNodes = node.namedItem( "edittypes" ).childNodes(); + QDomNodeList editTypeNodes = node.namedItem( QStringLiteral( "edittypes" ) ).childNodes(); for ( int i = 0; i < editTypeNodes.size(); i++ ) { QDomElement editTypeElement = editTypeNodes.at( i ).toElement(); - if ( editTypeElement.attribute( "widgetv2type" ) == "Hidden" ) + if ( editTypeElement.attribute( QStringLiteral( "widgetv2type" ) ) == QLatin1String( "Hidden" ) ) { ColumnConfig column; - column.name = editTypeElement.attribute( "name" ); + column.name = editTypeElement.attribute( QStringLiteral( "name" ) ); column.hidden = true; column.type = Field; mColumns.append( column ); @@ -196,8 +196,8 @@ void QgsAttributeTableConfig::readXml( const QDomNode& node ) } } - mSortExpression = configNode.toElement().attribute( "sortExpression" ); - mSortOrder = static_cast( configNode.toElement().attribute( "sortOrder" ).toInt() ); + mSortExpression = configNode.toElement().attribute( QStringLiteral( "sortExpression" ) ); + mSortOrder = static_cast( configNode.toElement().attribute( QStringLiteral( "sortOrder" ) ).toInt() ); } QString QgsAttributeTableConfig::sortExpression() const @@ -249,31 +249,31 @@ void QgsAttributeTableConfig::writeXml( QDomNode& node ) const { QDomDocument doc( node.ownerDocument() ); - QDomElement configElement = doc.createElement( "attributetableconfig" ); - configElement.setAttribute( "actionWidgetStyle", mActionWidgetStyle == ButtonList ? "buttonList" : "dropDown" ); + QDomElement configElement = doc.createElement( QStringLiteral( "attributetableconfig" ) ); + configElement.setAttribute( QStringLiteral( "actionWidgetStyle" ), mActionWidgetStyle == ButtonList ? "buttonList" : "dropDown" ); - configElement.setAttribute( "sortExpression", mSortExpression ); + configElement.setAttribute( QStringLiteral( "sortExpression" ), mSortExpression ); - configElement.setAttribute( "sortOrder", mSortOrder ); + configElement.setAttribute( QStringLiteral( "sortOrder" ), mSortOrder ); - QDomElement columnsElement = doc.createElement( "columns" ); + QDomElement columnsElement = doc.createElement( QStringLiteral( "columns" ) ); Q_FOREACH ( const ColumnConfig& column, mColumns ) { - QDomElement columnElement = doc.createElement( "column" ); + QDomElement columnElement = doc.createElement( QStringLiteral( "column" ) ); if ( column.type == Action ) { - columnElement.setAttribute( "type", "actions" ); + columnElement.setAttribute( QStringLiteral( "type" ), QStringLiteral( "actions" ) ); } else { - columnElement.setAttribute( "type", "field" ); - columnElement.setAttribute( "name", column.name ); + columnElement.setAttribute( QStringLiteral( "type" ), QStringLiteral( "field" ) ); + columnElement.setAttribute( QStringLiteral( "name" ), column.name ); } - columnElement.setAttribute( "hidden", column.hidden ); - columnElement.setAttribute( "width", QString::number( column.width ) ); + columnElement.setAttribute( QStringLiteral( "hidden" ), column.hidden ); + columnElement.setAttribute( QStringLiteral( "width" ), QString::number( column.width ) ); columnsElement.appendChild( columnElement ); } diff --git a/src/core/qgsbrowsermodel.cpp b/src/core/qgsbrowsermodel.cpp index c82ad00b54bf..1657b743e100 100644 --- a/src/core/qgsbrowsermodel.cpp +++ b/src/core/qgsbrowsermodel.cpp @@ -142,7 +142,7 @@ void QgsBrowserModel::addRootItems() continue; } - QgsDataItem *item = pr->createDataItem( "", nullptr ); // empty path -> top level + QgsDataItem *item = pr->createDataItem( QLatin1String( "" ), nullptr ); // empty path -> top level if ( item ) { QgsDebugMsg( "Add new top level item : " + item->name() ); @@ -438,7 +438,7 @@ QStringList QgsBrowserModel::mimeTypes() const QStringList types; // In theory the mime type convention is: application/x-vnd... // but it seems a bit over formalized. Would be an application/x-qgis-uri better? - types << "application/x-vnd.qgis.qgis.uri"; + types << QStringLiteral( "application/x-vnd.qgis.qgis.uri" ); return types; } @@ -548,7 +548,7 @@ void QgsBrowserModel::removeFavourite( const QModelIndex &index ) void QgsBrowserModel::hidePath( QgsDataItem *item ) { QSettings settings; - QStringList hiddenItems = settings.value( "/browser/hiddenPaths", + QStringList hiddenItems = settings.value( QStringLiteral( "/browser/hiddenPaths" ), QStringList() ).toStringList(); int idx = hiddenItems.indexOf( item->path() ); if ( idx != -1 ) @@ -559,7 +559,7 @@ void QgsBrowserModel::hidePath( QgsDataItem *item ) { hiddenItems << item->path(); } - settings.setValue( "/browser/hiddenPaths", hiddenItems ); + settings.setValue( QStringLiteral( "/browser/hiddenPaths" ), hiddenItems ); if ( item->parent() ) { item->parent()->deleteChildItem( item ); diff --git a/src/core/qgscolorramp.cpp b/src/core/qgscolorramp.cpp index 907bad4e558f..9057526aa341 100644 --- a/src/core/qgscolorramp.cpp +++ b/src/core/qgscolorramp.cpp @@ -56,14 +56,14 @@ QgsColorRamp* QgsGradientColorRamp::create( const QgsStringMap& props ) // color1 and color2 QColor color1 = DEFAULT_GRADIENT_COLOR1; QColor color2 = DEFAULT_GRADIENT_COLOR2; - if ( props.contains( "color1" ) ) - color1 = QgsSymbolLayerUtils::decodeColor( props["color1"] ); - if ( props.contains( "color2" ) ) - color2 = QgsSymbolLayerUtils::decodeColor( props["color2"] ); + if ( props.contains( QStringLiteral( "color1" ) ) ) + color1 = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color1" )] ); + if ( props.contains( QStringLiteral( "color2" ) ) ) + color2 = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color2" )] ); //stops QgsGradientStopsList stops; - if ( props.contains( "stops" ) ) + if ( props.contains( QStringLiteral( "stops" ) ) ) { Q_FOREACH ( const QString& stop, props["stops"].split( ':' ) ) { @@ -78,9 +78,9 @@ QgsColorRamp* QgsGradientColorRamp::create( const QgsStringMap& props ) // discrete vs. continuous bool discrete = false; - if ( props.contains( "discrete" ) ) + if ( props.contains( QStringLiteral( "discrete" ) ) ) { - if ( props["discrete"] == "1" ) + if ( props[QStringLiteral( "discrete" )] == QLatin1String( "1" ) ) discrete = true; } @@ -89,7 +89,7 @@ QgsColorRamp* QgsGradientColorRamp::create( const QgsStringMap& props ) for ( QgsStringMap::const_iterator it = props.constBegin(); it != props.constEnd(); ++it ) { - if ( it.key().startsWith( "info_" ) ) + if ( it.key().startsWith( QLatin1String( "info_" ) ) ) info[ it.key().mid( 5 )] = it.value(); } @@ -171,19 +171,19 @@ QgsGradientColorRamp* QgsGradientColorRamp::clone() const QgsStringMap QgsGradientColorRamp::properties() const { QgsStringMap map; - map["color1"] = QgsSymbolLayerUtils::encodeColor( mColor1 ); - map["color2"] = QgsSymbolLayerUtils::encodeColor( mColor2 ); + map[QStringLiteral( "color1" )] = QgsSymbolLayerUtils::encodeColor( mColor1 ); + map[QStringLiteral( "color2" )] = QgsSymbolLayerUtils::encodeColor( mColor2 ); if ( !mStops.isEmpty() ) { QStringList lst; for ( QgsGradientStopsList::const_iterator it = mStops.begin(); it != mStops.end(); ++it ) { - lst.append( QString( "%1;%2" ).arg( it->offset ).arg( QgsSymbolLayerUtils::encodeColor( it->color ) ) ); + lst.append( QStringLiteral( "%1;%2" ).arg( it->offset ).arg( QgsSymbolLayerUtils::encodeColor( it->color ) ) ); } - map["stops"] = lst.join( ":" ); + map[QStringLiteral( "stops" )] = lst.join( QStringLiteral( ":" ) ); } - map["discrete"] = mDiscrete ? "1" : "0"; + map[QStringLiteral( "discrete" )] = mDiscrete ? "1" : "0"; for ( QgsStringMap::const_iterator it = mInfo.constBegin(); it != mInfo.constEnd(); ++it ) @@ -294,13 +294,13 @@ QgsColorRamp* QgsLimitedRandomColorRamp::create( const QgsStringMap& props ) int satMin = DEFAULT_RANDOM_SAT_MIN, satMax = DEFAULT_RANDOM_SAT_MAX; int valMin = DEFAULT_RANDOM_VAL_MIN, valMax = DEFAULT_RANDOM_VAL_MAX; - if ( props.contains( "count" ) ) count = props["count"].toInt(); - if ( props.contains( "hueMin" ) ) hueMin = props["hueMin"].toInt(); - if ( props.contains( "hueMax" ) ) hueMax = props["hueMax"].toInt(); - if ( props.contains( "satMin" ) ) satMin = props["satMin"].toInt(); - if ( props.contains( "satMax" ) ) satMax = props["satMax"].toInt(); - if ( props.contains( "valMin" ) ) valMin = props["valMin"].toInt(); - if ( props.contains( "valMax" ) ) valMax = props["valMax"].toInt(); + if ( props.contains( QStringLiteral( "count" ) ) ) count = props[QStringLiteral( "count" )].toInt(); + if ( props.contains( QStringLiteral( "hueMin" ) ) ) hueMin = props[QStringLiteral( "hueMin" )].toInt(); + if ( props.contains( QStringLiteral( "hueMax" ) ) ) hueMax = props[QStringLiteral( "hueMax" )].toInt(); + if ( props.contains( QStringLiteral( "satMin" ) ) ) satMin = props[QStringLiteral( "satMin" )].toInt(); + if ( props.contains( QStringLiteral( "satMax" ) ) ) satMax = props[QStringLiteral( "satMax" )].toInt(); + if ( props.contains( QStringLiteral( "valMin" ) ) ) valMin = props[QStringLiteral( "valMin" )].toInt(); + if ( props.contains( QStringLiteral( "valMax" ) ) ) valMax = props[QStringLiteral( "valMax" )].toInt(); return new QgsLimitedRandomColorRamp( count, hueMin, hueMax, satMin, satMax, valMin, valMax ); } @@ -333,13 +333,13 @@ QgsLimitedRandomColorRamp* QgsLimitedRandomColorRamp::clone() const QgsStringMap QgsLimitedRandomColorRamp::properties() const { QgsStringMap map; - map["count"] = QString::number( mCount ); - map["hueMin"] = QString::number( mHueMin ); - map["hueMax"] = QString::number( mHueMax ); - map["satMin"] = QString::number( mSatMin ); - map["satMax"] = QString::number( mSatMax ); - map["valMin"] = QString::number( mValMin ); - map["valMax"] = QString::number( mValMax ); + map[QStringLiteral( "count" )] = QString::number( mCount ); + map[QStringLiteral( "hueMin" )] = QString::number( mHueMin ); + map[QStringLiteral( "hueMax" )] = QString::number( mHueMax ); + map[QStringLiteral( "satMin" )] = QString::number( mSatMin ); + map[QStringLiteral( "satMax" )] = QString::number( mSatMax ); + map[QStringLiteral( "valMin" )] = QString::number( mValMin ); + map[QStringLiteral( "valMax" )] = QString::number( mValMax ); return map; } @@ -458,7 +458,7 @@ void QgsRandomColorRamp::setTotalColorCount( const int colorCount ) QString QgsRandomColorRamp::type() const { - return "randomcolors"; + return QStringLiteral( "randomcolors" ); } QgsRandomColorRamp* QgsRandomColorRamp::clone() const @@ -485,10 +485,10 @@ QgsColorRamp* QgsColorBrewerColorRamp::create( const QgsStringMap& props ) QString schemeName = DEFAULT_COLORBREWER_SCHEMENAME; int colors = DEFAULT_COLORBREWER_COLORS; - if ( props.contains( "schemeName" ) ) - schemeName = props["schemeName"]; - if ( props.contains( "colors" ) ) - colors = props["colors"].toInt(); + if ( props.contains( QStringLiteral( "schemeName" ) ) ) + schemeName = props[QStringLiteral( "schemeName" )]; + if ( props.contains( QStringLiteral( "colors" ) ) ) + colors = props[QStringLiteral( "colors" )].toInt(); return new QgsColorBrewerColorRamp( schemeName, colors ); } @@ -533,8 +533,8 @@ QgsColorBrewerColorRamp* QgsColorBrewerColorRamp::clone() const QgsStringMap QgsColorBrewerColorRamp::properties() const { QgsStringMap map; - map["schemeName"] = mSchemeName; - map["colors"] = QString::number( mColors ); + map[QStringLiteral( "schemeName" )] = mSchemeName; + map[QStringLiteral( "colors" )] = QString::number( mColors ); return map; } @@ -573,17 +573,17 @@ QgsColorRamp* QgsCptCityColorRamp::create( const QgsStringMap& props ) QString schemeName = DEFAULT_CPTCITY_SCHEMENAME; QString variantName = DEFAULT_CPTCITY_VARIANTNAME; - if ( props.contains( "schemeName" ) ) - schemeName = props["schemeName"]; - if ( props.contains( "variantName" ) ) - variantName = props["variantName"]; + if ( props.contains( QStringLiteral( "schemeName" ) ) ) + schemeName = props[QStringLiteral( "schemeName" )]; + if ( props.contains( QStringLiteral( "variantName" ) ) ) + variantName = props[QStringLiteral( "variantName" )]; return new QgsCptCityColorRamp( schemeName, variantName ); } QgsCptCityColorRamp* QgsCptCityColorRamp::clone() const { - QgsCptCityColorRamp* ramp = new QgsCptCityColorRamp( "", "", false ); + QgsCptCityColorRamp* ramp = new QgsCptCityColorRamp( QLatin1String( "" ), QLatin1String( "" ), false ); ramp->copy( this ); return ramp; } @@ -609,10 +609,10 @@ QgsGradientColorRamp* QgsCptCityColorRamp::cloneGradientRamp() const // add author and copyright information // TODO also add COPYING.xml file/link? QgsStringMap info = copyingInfo(); - info["cpt-city-gradient"] = "/" + mSchemeName + mVariantName + ".svg"; + info[QStringLiteral( "cpt-city-gradient" )] = "/" + mSchemeName + mVariantName + ".svg"; QString copyingFilename = copyingFileName(); copyingFilename.remove( QgsCptCityArchive::defaultBaseDir() ); - info["cpt-city-license"] = "" + copyingFilename; + info[QStringLiteral( "cpt-city-license" )] = "" + copyingFilename; ramp->setInfo( info ); return ramp; } @@ -621,15 +621,15 @@ QgsGradientColorRamp* QgsCptCityColorRamp::cloneGradientRamp() const QgsStringMap QgsCptCityColorRamp::properties() const { QgsStringMap map; - map["schemeName"] = mSchemeName; - map["variantName"] = mVariantName; + map[QStringLiteral( "schemeName" )] = mSchemeName; + map[QStringLiteral( "variantName" )] = mVariantName; return map; } QString QgsCptCityColorRamp::fileName() const { - if ( mSchemeName == "" ) + if ( mSchemeName == QLatin1String( "" ) ) return QString(); else { @@ -639,13 +639,13 @@ QString QgsCptCityColorRamp::fileName() const QString QgsCptCityColorRamp::copyingFileName() const { - return QgsCptCityArchive::findFileName( "COPYING.xml", QFileInfo( fileName() ).dir().path(), + return QgsCptCityArchive::findFileName( QStringLiteral( "COPYING.xml" ), QFileInfo( fileName() ).dir().path(), QgsCptCityArchive::defaultBaseDir() ); } QString QgsCptCityColorRamp::descFileName() const { - return QgsCptCityArchive::findFileName( "DESC.xml", QFileInfo( fileName() ).dir().path(), + return QgsCptCityArchive::findFileName( QStringLiteral( "DESC.xml" ), QFileInfo( fileName() ).dir().path(), QgsCptCityArchive::defaultBaseDir() ); } @@ -752,7 +752,7 @@ QgsPresetSchemeColorRamp::QgsPresetSchemeColorRamp( const QList& colors } // need at least one color if ( mColors.isEmpty() ) - mColors << qMakePair( QColor( 250, 75, 60 ), QString( "#fa4b3c" ) ); + mColors << qMakePair( QColor( 250, 75, 60 ), QStringLiteral( "#fa4b3c" ) ); } QgsPresetSchemeColorRamp::QgsPresetSchemeColorRamp( const QgsNamedColorList& colors ) @@ -760,7 +760,7 @@ QgsPresetSchemeColorRamp::QgsPresetSchemeColorRamp( const QgsNamedColorList& col { // need at least one color if ( mColors.isEmpty() ) - mColors << qMakePair( QColor( 250, 75, 60 ), QString( "#fa4b3c" ) ); + mColors << qMakePair( QColor( 250, 75, 60 ), QStringLiteral( "#fa4b3c" ) ); } QgsColorRamp* QgsPresetSchemeColorRamp::create( const QgsStringMap& properties ) @@ -768,14 +768,14 @@ QgsColorRamp* QgsPresetSchemeColorRamp::create( const QgsStringMap& properties ) QgsNamedColorList colors; int i = 0; - QString colorString = properties.value( QString( "preset_color_%1" ).arg( i ), QString() ); - QString colorName = properties.value( QString( "preset_color_name_%1" ).arg( i ), QString() ); + QString colorString = properties.value( QStringLiteral( "preset_color_%1" ).arg( i ), QString() ); + QString colorName = properties.value( QStringLiteral( "preset_color_name_%1" ).arg( i ), QString() ); while ( !colorString.isEmpty() ) { colors << qMakePair( QgsSymbolLayerUtils::decodeColor( colorString ), colorName ); i++; - colorString = properties.value( QString( "preset_color_%1" ).arg( i ), QString() ); - colorName = properties.value( QString( "preset_color_name_%1" ).arg( i ), QString() ); + colorString = properties.value( QStringLiteral( "preset_color_%1" ).arg( i ), QString() ); + colorName = properties.value( QStringLiteral( "preset_color_name_%1" ).arg( i ), QString() ); } return new QgsPresetSchemeColorRamp( colors ); @@ -823,8 +823,8 @@ QgsStringMap QgsPresetSchemeColorRamp::properties() const QgsStringMap props; for ( int i = 0; i < mColors.count(); ++i ) { - props.insert( QString( "preset_color_%1" ).arg( i ), QgsSymbolLayerUtils::encodeColor( mColors.at( i ).first ) ); - props.insert( QString( "preset_color_name_%1" ).arg( i ), mColors.at( i ).second ); + props.insert( QStringLiteral( "preset_color_%1" ).arg( i ), QgsSymbolLayerUtils::encodeColor( mColors.at( i ).first ) ); + props.insert( QStringLiteral( "preset_color_name_%1" ).arg( i ), mColors.at( i ).second ); } return props; } diff --git a/src/core/qgscolorramp.h b/src/core/qgscolorramp.h index ce70276991ee..6543d2ebf1e4 100644 --- a/src/core/qgscolorramp.h +++ b/src/core/qgscolorramp.h @@ -122,7 +122,7 @@ class CORE_EXPORT QgsGradientColorRamp : public QgsColorRamp virtual int count() const override { return mStops.count() + 2; } virtual double value( int index ) const override; virtual QColor color( double value ) const override; - virtual QString type() const override { return "gradient"; } + virtual QString type() const override { return QStringLiteral( "gradient" ); } virtual QgsGradientColorRamp* clone() const override; virtual QgsStringMap properties() const override; @@ -254,7 +254,7 @@ class CORE_EXPORT QgsLimitedRandomColorRamp : public QgsColorRamp virtual double value( int index ) const override; virtual QColor color( double value ) const override; - virtual QString type() const override { return "random"; } + virtual QString type() const override { return QStringLiteral( "random" ); } virtual QgsLimitedRandomColorRamp* clone() const override; virtual QgsStringMap properties() const override; int count() const override { return mCount; } @@ -423,13 +423,13 @@ class CORE_EXPORT QgsPresetSchemeColorRamp : public QgsColorRamp, public QgsColo // QgsColorRamp interface virtual double value( int index ) const override; virtual QColor color( double value ) const override; - virtual QString type() const override { return "preset"; } + virtual QString type() const override { return QStringLiteral( "preset" ); } virtual QgsPresetSchemeColorRamp* clone() const override; virtual QgsStringMap properties() const override; int count() const override; // QgsColorScheme interface - QString schemeName() const override { return "preset"; } + QString schemeName() const override { return QStringLiteral( "preset" ); } QgsNamedColorList fetchColors( const QString &context = QString(), const QColor &baseColor = QColor() ) override; bool isEditable() const override { return true; } @@ -468,7 +468,7 @@ class CORE_EXPORT QgsColorBrewerColorRamp : public QgsColorRamp virtual double value( int index ) const override; virtual QColor color( double value ) const override; - virtual QString type() const override { return "colorbrewer"; } + virtual QString type() const override { return QStringLiteral( "colorbrewer" ); } virtual QgsColorBrewerColorRamp* clone() const override; virtual QgsStringMap properties() const override; virtual int count() const override { return mColors; } @@ -537,7 +537,7 @@ class CORE_EXPORT QgsCptCityColorRamp : public QgsGradientColorRamp static QgsColorRamp* create( const QgsStringMap& properties = QgsStringMap() ); - virtual QString type() const override { return "cpt-city"; } + virtual QString type() const override { return QStringLiteral( "cpt-city" ); } virtual QgsCptCityColorRamp* clone() const override; void copy( const QgsCptCityColorRamp* other ); @@ -553,7 +553,10 @@ class CORE_EXPORT QgsCptCityColorRamp : public QgsGradientColorRamp void setSchemeName( const QString& schemeName ) { mSchemeName = schemeName; mFileLoaded = false; } void setVariantName( const QString& variantName ) { mVariantName = variantName; mFileLoaded = false; } void setVariantList( const QStringList& variantList ) { mVariantList = variantList; } - void setName( const QString& schemeName, const QString& variantName = "", const QStringList& variantList = QStringList() ) + /** + * Sets the name for the color ramp, based on a scheme, variant and list of variants. + */ + void setName( const QString& schemeName, const QString& variantName = QLatin1String( "" ), const QStringList& variantList = QStringList() ) { mSchemeName = schemeName; mVariantName = variantName; mVariantList = variantList; mFileLoaded = false; } void loadPalette() { loadFile(); } diff --git a/src/core/qgscolorscheme.cpp b/src/core/qgscolorscheme.cpp index 28d7f419508e..60ee6e7d8ae1 100644 --- a/src/core/qgscolorscheme.cpp +++ b/src/core/qgscolorscheme.cpp @@ -65,7 +65,7 @@ QgsNamedColorList QgsRecentColorScheme::fetchColors( const QString &context, con //fetch recent colors QSettings settings; - QList< QVariant > recentColorVariants = settings.value( QString( "/colors/recent" ) ).toList(); + QList< QVariant > recentColorVariants = settings.value( QStringLiteral( "/colors/recent" ) ).toList(); //generate list from recent colors QgsNamedColorList colorList; @@ -93,7 +93,7 @@ void QgsRecentColorScheme::addRecentColor( const QColor& color ) opaqueColor.setAlpha( 255 ); QSettings settings; - QList< QVariant > recentColorVariants = settings.value( QString( "/colors/recent" ) ).toList(); + QList< QVariant > recentColorVariants = settings.value( QStringLiteral( "/colors/recent" ) ).toList(); //remove colors by name for ( int colorIdx = recentColorVariants.length() - 1; colorIdx >= 0; --colorIdx ) @@ -114,14 +114,14 @@ void QgsRecentColorScheme::addRecentColor( const QColor& color ) recentColorVariants.pop_back(); } - settings.setValue( QString( "/colors/recent" ), recentColorVariants ); + settings.setValue( QStringLiteral( "/colors/recent" ), recentColorVariants ); } QColor QgsRecentColorScheme::lastUsedColor() { //fetch recent colors QSettings settings; - QList< QVariant > recentColorVariants = settings.value( QString( "/colors/recent" ) ).toList(); + QList< QVariant > recentColorVariants = settings.value( QStringLiteral( "/colors/recent" ) ).toList(); if ( recentColorVariants.isEmpty() ) return QColor(); @@ -150,7 +150,7 @@ QgsNamedColorList QgsCustomColorScheme::fetchColors( const QString &context, con QSettings settings; //check if settings contains custom palette - if ( !settings.contains( QString( "/colors/palettecolors" ) ) ) + if ( !settings.contains( QStringLiteral( "/colors/palettecolors" ) ) ) { //no custom palette, return default colors colorList.append( qMakePair( QColor( "#000000" ), QString() ) ); @@ -167,8 +167,8 @@ QgsNamedColorList QgsCustomColorScheme::fetchColors( const QString &context, con return colorList; } - QList< QVariant > customColorVariants = settings.value( QString( "/colors/palettecolors" ) ).toList(); - QList< QVariant > customColorLabels = settings.value( QString( "/colors/palettelabels" ) ).toList(); + QList< QVariant > customColorVariants = settings.value( QStringLiteral( "/colors/palettecolors" ) ).toList(); + QList< QVariant > customColorLabels = settings.value( QStringLiteral( "/colors/palettelabels" ) ).toList(); //generate list from custom colors int colorIndex = 0; @@ -207,8 +207,8 @@ bool QgsCustomColorScheme::setColors( const QgsNamedColorList &colors, const QSt customColors.append( color ); customColorLabels.append( label ); } - settings.setValue( QString( "/colors/palettecolors" ), customColors ); - settings.setValue( QString( "/colors/palettelabels" ), customColorLabels ); + settings.setValue( QStringLiteral( "/colors/palettecolors" ), customColors ); + settings.setValue( QStringLiteral( "/colors/palettelabels" ), customColorLabels ); return true; } @@ -235,8 +235,8 @@ QgsNamedColorList QgsProjectColorScheme::fetchColors( const QString &context, co QgsNamedColorList colorList; - QStringList colorStrings = QgsProject::instance()->readListEntry( "Palette", "/Colors" ); - QStringList colorLabels = QgsProject::instance()->readListEntry( "Palette", "/Labels" ); + QStringList colorStrings = QgsProject::instance()->readListEntry( QStringLiteral( "Palette" ), QStringLiteral( "/Colors" ) ); + QStringList colorLabels = QgsProject::instance()->readListEntry( QStringLiteral( "Palette" ), QStringLiteral( "/Labels" ) ); //generate list from custom colors int colorIndex = 0; @@ -274,8 +274,8 @@ bool QgsProjectColorScheme::setColors( const QgsNamedColorList &colors, const QS customColors.append( color ); customColorLabels.append( label ); } - QgsProject::instance()->writeEntry( "Palette", "/Colors", customColors ); - QgsProject::instance()->writeEntry( "Palette", "/Labels", customColorLabels ); + QgsProject::instance()->writeEntry( QStringLiteral( "Palette" ), QStringLiteral( "/Colors" ), customColors ); + QgsProject::instance()->writeEntry( QStringLiteral( "Palette" ), QStringLiteral( "/Labels" ), customColorLabels ); return true; } @@ -351,7 +351,7 @@ QgsUserColorScheme::QgsUserColorScheme( const QString &filename ) //find name line QString line; - while ( !in.atEnd() && !line.startsWith( "Name:" ) ) + while ( !in.atEnd() && !line.startsWith( QLatin1String( "Name:" ) ) ) { line = in.readLine(); } @@ -390,7 +390,7 @@ QgsColorScheme::SchemeFlags QgsUserColorScheme::flags() const QgsColorScheme::SchemeFlags f = QgsGplColorScheme::flags(); QSettings s; - QStringList showInMenuSchemes = s.value( QString( "/colors/showInMenuList" ) ).toStringList(); + QStringList showInMenuSchemes = s.value( QStringLiteral( "/colors/showInMenuList" ) ).toStringList(); if ( showInMenuSchemes.contains( mName ) ) { @@ -415,7 +415,7 @@ bool QgsUserColorScheme::erase() void QgsUserColorScheme::setShowSchemeInMenu( bool show ) { QSettings s; - QStringList showInMenuSchemes = s.value( QString( "/colors/showInMenuList" ) ).toStringList(); + QStringList showInMenuSchemes = s.value( QStringLiteral( "/colors/showInMenuList" ) ).toStringList(); if ( show && !showInMenuSchemes.contains( mName ) ) { @@ -426,7 +426,7 @@ void QgsUserColorScheme::setShowSchemeInMenu( bool show ) showInMenuSchemes.removeAll( mName ); } - s.setValue( "/colors/showInMenuList", showInMenuSchemes ); + s.setValue( QStringLiteral( "/colors/showInMenuList" ), showInMenuSchemes ); } QString QgsUserColorScheme::gplFilePath() diff --git a/src/core/qgscolorschemeregistry.cpp b/src/core/qgscolorschemeregistry.cpp index f99cf63cdd49..27764dbe5b92 100644 --- a/src/core/qgscolorschemeregistry.cpp +++ b/src/core/qgscolorschemeregistry.cpp @@ -86,7 +86,7 @@ void QgsColorSchemeRegistry::addUserSchemes() return; } - QFileInfoList fileInfoList = QDir( palettesDir ).entryInfoList( QStringList( "*.gpl" ), QDir::Files ); + QFileInfoList fileInfoList = QDir( palettesDir ).entryInfoList( QStringList( QStringLiteral( "*.gpl" ) ), QDir::Files ); QFileInfoList::const_iterator infoIt = fileInfoList.constBegin(); for ( ; infoIt != fileInfoList.constEnd(); ++infoIt ) { diff --git a/src/core/qgsconditionalstyle.cpp b/src/core/qgsconditionalstyle.cpp index 57cef585bd7c..6053e7b996f5 100644 --- a/src/core/qgsconditionalstyle.cpp +++ b/src/core/qgsconditionalstyle.cpp @@ -50,8 +50,8 @@ QList QgsConditionalLayerStyles::fieldStyles( const QString bool QgsConditionalLayerStyles::writeXml( QDomNode &node, QDomDocument &doc ) const { - QDomElement stylesel = doc.createElement( "conditionalstyles" ); - QDomElement rowel = doc.createElement( "rowstyles" ); + QDomElement stylesel = doc.createElement( QStringLiteral( "conditionalstyles" ) ); + QDomElement rowel = doc.createElement( QStringLiteral( "rowstyles" ) ); Q_FOREACH ( const QgsConditionalStyle& style, mRowStyles ) { style.writeXml( rowel, doc ); @@ -59,12 +59,12 @@ bool QgsConditionalLayerStyles::writeXml( QDomNode &node, QDomDocument &doc ) co stylesel.appendChild( rowel ); - QDomElement fieldsel = doc.createElement( "fieldstyles" ); + QDomElement fieldsel = doc.createElement( QStringLiteral( "fieldstyles" ) ); QHash::const_iterator it = mFieldStyles.constBegin(); for ( ; it != mFieldStyles.constEnd(); ++it ) { - QDomElement fieldel = doc.createElement( "fieldstyle" ); - fieldel.setAttribute( "fieldname", it.key() ); + QDomElement fieldel = doc.createElement( QStringLiteral( "fieldstyle" ) ); + fieldel.setAttribute( QStringLiteral( "fieldname" ), it.key() ); QgsConditionalStyles styles = it.value(); Q_FOREACH ( const QgsConditionalStyle& style, styles ) { @@ -81,11 +81,11 @@ bool QgsConditionalLayerStyles::writeXml( QDomNode &node, QDomDocument &doc ) co bool QgsConditionalLayerStyles::readXml( const QDomNode &node ) { - QDomElement condel = node.firstChildElement( "conditionalstyles" ); + QDomElement condel = node.firstChildElement( QStringLiteral( "conditionalstyles" ) ); mRowStyles.clear(); mFieldStyles.clear(); - QDomElement rowstylesel = condel.firstChildElement( "rowstyles" ); - QDomNodeList nodelist = rowstylesel.toElement().elementsByTagName( "style" ); + QDomElement rowstylesel = condel.firstChildElement( QStringLiteral( "rowstyles" ) ); + QDomNodeList nodelist = rowstylesel.toElement().elementsByTagName( QStringLiteral( "style" ) ); for ( int i = 0;i < nodelist.count(); i++ ) { QDomElement styleElm = nodelist.at( i ).toElement(); @@ -94,15 +94,15 @@ bool QgsConditionalLayerStyles::readXml( const QDomNode &node ) mRowStyles.append( style ); } - QDomElement fieldstylesel = condel.firstChildElement( "fieldstyles" ); - nodelist = fieldstylesel.toElement().elementsByTagName( "fieldstyle" ); + QDomElement fieldstylesel = condel.firstChildElement( QStringLiteral( "fieldstyles" ) ); + nodelist = fieldstylesel.toElement().elementsByTagName( QStringLiteral( "fieldstyle" ) ); QList styles; for ( int i = 0;i < nodelist.count(); i++ ) { styles.clear(); QDomElement fieldel = nodelist.at( i ).toElement(); - QString fieldName = fieldel.attribute( "fieldname" ); - QDomNodeList stylenodelist = fieldel.toElement().elementsByTagName( "style" ); + QString fieldName = fieldel.attribute( QStringLiteral( "fieldname" ) ); + QDomNodeList stylenodelist = fieldel.toElement().elementsByTagName( QStringLiteral( "style" ) ); styles.reserve( stylenodelist.count() ); for ( int i = 0;i < stylenodelist.count(); i++ ) { @@ -175,7 +175,7 @@ QString QgsConditionalStyle::displayText() const if ( name().isEmpty() ) return rule(); else - return QString( "%1 \n%2" ).arg( name(), rule() ); + return QStringLiteral( "%1 \n%2" ).arg( name(), rule() ); } void QgsConditionalStyle::setSymbol( QgsSymbol* value ) @@ -195,7 +195,7 @@ void QgsConditionalStyle::setSymbol( QgsSymbol* value ) bool QgsConditionalStyle::matches( const QVariant& value, QgsExpressionContext& context ) const { QgsExpression exp( mRule ); - context.lastScope()->setVariable( "value", value ); + context.lastScope()->setVariable( QStringLiteral( "value" ), value ); return exp.evaluate( &context ).toBool(); } @@ -223,7 +223,7 @@ QPixmap QgsConditionalStyle::renderPreview() const painter.setRenderHint( QPainter::HighQualityAntialiasing ); painter.setFont( font() ); rect = QRect( 32, 0, 32, 32 ); - painter.drawText( rect, Qt::AlignCenter, "abc\n123" ); + painter.drawText( rect, Qt::AlignCenter, QStringLiteral( "abc\n123" ) ); painter.end(); return pixmap; } @@ -277,16 +277,16 @@ QgsConditionalStyle QgsConditionalStyle::compressStyles( const QList( symbolElm ); diff --git a/src/core/qgscoordinatereferencesystem.cpp b/src/core/qgscoordinatereferencesystem.cpp index dbac9726c632..0e169542daa5 100644 --- a/src/core/qgscoordinatereferencesystem.cpp +++ b/src/core/qgscoordinatereferencesystem.cpp @@ -139,7 +139,7 @@ bool QgsCoordinateReferenceSystem::createFromId( const long theId, CrsType theTy result = createFromSrid( theId ); break; case EpsgCrsId: - result = createFromOgcWmsCrs( QString( "EPSG:%1" ).arg( theId ) ); + result = createFromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( theId ) ); break; default: //THIS IS BAD...THIS PART OF CODE SHOULD NEVER BE REACHED... @@ -167,9 +167,9 @@ bool QgsCoordinateReferenceSystem::createFromString( const QString &theDefinitio { QString authName = reCrsId.cap( 1 ).toLower(); CrsType type = InternalCrsId; - if ( authName == "epsg" ) + if ( authName == QLatin1String( "epsg" ) ) type = EpsgCrsId; - if ( authName == "postgis" ) + if ( authName == QLatin1String( "postgis" ) ) type = PostgisCrsId; long id = reCrsId.cap( 2 ).toLong(); result = createFromId( id, type ); @@ -179,7 +179,7 @@ bool QgsCoordinateReferenceSystem::createFromString( const QString &theDefinitio QRegExp reCrsStr( "^(?:(wkt|proj4)\\:)?(.+)$", Qt::CaseInsensitive ); if ( reCrsStr.indexIn( theDefinition ) == 0 ) { - if ( reCrsStr.cap( 1 ).toLower() == "proj4" ) + if ( reCrsStr.cap( 1 ).toLower() == QLatin1String( "proj4" ) ) { result = createFromProj4( reCrsStr.cap( 2 ) ); //TODO: createFromProj4 used to save to the user database any new CRS @@ -188,7 +188,7 @@ bool QgsCoordinateReferenceSystem::createFromString( const QString &theDefinitio // familiar with the code (should also give a more descriptive name to the generated CRS) if ( srsid() == 0 ) { - QString myName = QString( " * %1 (%2)" ) + QString myName = QStringLiteral( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), toProj4() ); saveAsUserCrs( myName ); @@ -215,7 +215,7 @@ bool QgsCoordinateReferenceSystem::createFromUserInput( const QString &theDefini // make sure towgs84 parameter is loaded if using an ESRI definition and gdal >= 1.9 #if GDAL_VERSION_NUM >= 1900 - if ( theDefinition.startsWith( "ESRI::" ) ) + if ( theDefinition.startsWith( QLatin1String( "ESRI::" ) ) ) { setupESRIWktFix(); } @@ -246,7 +246,7 @@ void QgsCoordinateReferenceSystem::setupESRIWktFix() { CPLSetConfigOption( "GDAL_FIX_ESRI_WKT", configNew ); if ( strcmp( configNew, CPLGetConfigOption( "GDAL_FIX_ESRI_WKT", "" ) ) != 0 ) - QgsLogger::warning( QString( "GDAL_FIX_ESRI_WKT could not be set to %1 : %2" ) + QgsLogger::warning( QStringLiteral( "GDAL_FIX_ESRI_WKT could not be set to %1 : %2" ) .arg( configNew, CPLGetConfigOption( "GDAL_FIX_ESRI_WKT", "" ) ) ); QgsDebugMsg( QString( "set GDAL_FIX_ESRI_WKT : %1" ).arg( configNew ) ); } @@ -279,7 +279,7 @@ bool QgsCoordinateReferenceSystem::createFromOgcWmsCrs( const QString& theCrs ) } else { - re.setPattern( "(user|custom|qgis):(\\d+)" ); + re.setPattern( QStringLiteral( "(user|custom|qgis):(\\d+)" ) ); if ( re.exactMatch( wmsCrs ) && createFromSrsId( re.cap( 2 ).toInt() ) ) { mOgcLock.lockForWrite(); @@ -289,7 +289,7 @@ bool QgsCoordinateReferenceSystem::createFromOgcWmsCrs( const QString& theCrs ) } } - if ( loadFromDb( QgsApplication::srsDbFilePath(), "lower(auth_name||':'||auth_id)", wmsCrs.toLower() ) ) + if ( loadFromDb( QgsApplication::srsDbFilePath(), QStringLiteral( "lower(auth_name||':'||auth_id)" ), wmsCrs.toLower() ) ) { mOgcLock.lockForWrite(); mOgcCache.insert( theCrs, *this ); @@ -298,26 +298,26 @@ bool QgsCoordinateReferenceSystem::createFromOgcWmsCrs( const QString& theCrs ) } // NAD27 - if ( wmsCrs.compare( "CRS:27", Qt::CaseInsensitive ) == 0 || - wmsCrs.compare( "OGC:CRS27", Qt::CaseInsensitive ) == 0 ) + if ( wmsCrs.compare( QLatin1String( "CRS:27" ), Qt::CaseInsensitive ) == 0 || + wmsCrs.compare( QLatin1String( "OGC:CRS27" ), Qt::CaseInsensitive ) == 0 ) { // TODO: verify same axis orientation - return createFromOgcWmsCrs( "EPSG:4267" ); + return createFromOgcWmsCrs( QStringLiteral( "EPSG:4267" ) ); } // NAD83 - if ( wmsCrs.compare( "CRS:83", Qt::CaseInsensitive ) == 0 || - wmsCrs.compare( "OGC:CRS83", Qt::CaseInsensitive ) == 0 ) + if ( wmsCrs.compare( QLatin1String( "CRS:83" ), Qt::CaseInsensitive ) == 0 || + wmsCrs.compare( QLatin1String( "OGC:CRS83" ), Qt::CaseInsensitive ) == 0 ) { // TODO: verify same axis orientation - return createFromOgcWmsCrs( "EPSG:4269" ); + return createFromOgcWmsCrs( QStringLiteral( "EPSG:4269" ) ); } // WGS84 - if ( wmsCrs.compare( "CRS:84", Qt::CaseInsensitive ) == 0 || - wmsCrs.compare( "OGC:CRS84", Qt::CaseInsensitive ) == 0 ) + if ( wmsCrs.compare( QLatin1String( "CRS:84" ), Qt::CaseInsensitive ) == 0 || + wmsCrs.compare( QLatin1String( "OGC:CRS84" ), Qt::CaseInsensitive ) == 0 ) { - createFromOgcWmsCrs( "EPSG:4326" ); + createFromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); d.detach(); d->mAxisInverted = false; @@ -369,7 +369,7 @@ bool QgsCoordinateReferenceSystem::createFromSrid( long id ) } mSrIdCacheLock.unlock(); - bool result = loadFromDb( QgsApplication::srsDbFilePath(), "srid", QString::number( id ) ); + bool result = loadFromDb( QgsApplication::srsDbFilePath(), QStringLiteral( "srid" ), QString::number( id ) ); mSrIdCacheLock.lockForWrite(); mSrIdCache.insert( id, *this ); @@ -393,7 +393,7 @@ bool QgsCoordinateReferenceSystem::createFromSrsId( long id ) bool result = loadFromDb( id < USER_CRS_START_ID ? QgsApplication::srsDbFilePath() : QgsApplication::qgisUserDbFilePath(), - "srs_id", QString::number( id ) ); + QStringLiteral( "srs_id" ), QString::number( id ) ); mCRSSrsIdLock.lockForWrite(); mSrsIdCache.insert( id, *this ); @@ -464,9 +464,9 @@ bool QgsCoordinateReferenceSystem::loadFromDb( const QString& db, const QString& if ( d->mSrsId >= USER_CRS_START_ID && d->mAuthId.isEmpty() ) { - d->mAuthId = QString( "USER:%1" ).arg( d->mSrsId ); + d->mAuthId = QStringLiteral( "USER:%1" ).arg( d->mSrsId ); } - else if ( d->mAuthId.startsWith( "EPSG:", Qt::CaseInsensitive ) ) + else if ( d->mAuthId.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) ) { OSRDestroySpatialReference( d->mCRS ); d->mCRS = OSRNewSpatialReference( nullptr ); @@ -496,7 +496,7 @@ bool QgsCoordinateReferenceSystem::hasAxisInverted() const OSRGetAxis( d->mCRS, OSRIsGeographic( d->mCRS ) ? "GEOGCS" : "PROJCS", 0, &orientation ); // If axis orientation is unknown, try again with OSRImportFromEPSGA for EPSG crs - if ( orientation == OAO_Other && d->mAuthId.startsWith( "EPSG:", Qt::CaseInsensitive ) ) + if ( orientation == OAO_Other && d->mAuthId.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) ) { OGRSpatialReferenceH crs = OSRNewSpatialReference( nullptr ); @@ -561,7 +561,7 @@ bool QgsCoordinateReferenceSystem::createFromWkt( const QString &theWkt ) if ( OSRAutoIdentifyEPSG( d->mCRS ) == OGRERR_NONE ) { - QString authid = QString( "%1:%2" ) + QString authid = QStringLiteral( "%1:%2" ) .arg( OSRGetAuthorityName( d->mCRS, nullptr ), OSRGetAuthorityCode( d->mCRS, nullptr ) ); QgsDebugMsg( "authid recognized as " + authid ); @@ -600,7 +600,7 @@ bool QgsCoordinateReferenceSystem::createFromWkt( const QString &theWkt ) // familiar with the code (should also give a more descriptive name to the generated CRS) if ( d->mSrsId == 0 ) { - QString myName = QString( " * %1 (%2)" ) + QString myName = QStringLiteral( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), toProj4() ); saveAsUserCrs( myName ); @@ -702,8 +702,8 @@ bool QgsCoordinateReferenceSystem::createFromProj4( const QString &theProj4Strin int myLength1 = 0; int myStart2 = 0; int myLength2 = 0; - QString lat1Str = ""; - QString lat2Str = ""; + QString lat1Str = QLatin1String( "" ); + QString lat2Str = QLatin1String( "" ); myStart1 = myLat1RegExp.indexIn( myProj4String, myStart1 ); myStart2 = myLat2RegExp.indexIn( myProj4String, myStart2 ); if ( myStart1 != -1 && myStart2 != -1 ) @@ -714,7 +714,7 @@ bool QgsCoordinateReferenceSystem::createFromProj4( const QString &theProj4Strin lat2Str = myProj4String.mid( myStart2 + LAT_PREFIX_LEN, myLength2 - LAT_PREFIX_LEN ); } // If we found the lat_1 and lat_2 we need to swap and check to see if we can find it... - if ( lat1Str != "" && lat2Str != "" ) + if ( lat1Str != QLatin1String( "" ) && lat2Str != QLatin1String( "" ) ) { // Make our new string to check... QString theProj4StringModified = myProj4String; @@ -736,8 +736,8 @@ bool QgsCoordinateReferenceSystem::createFromProj4( const QString &theProj4Strin // - found definition may have more parameters (like +towgs84 in GDAL) // - retry without datum, if no match is found (looks like +datum<>WGS84 was dropped in GDAL) - QString sql = "SELECT * FROM tbl_srs WHERE "; - QString delim = ""; + QString sql = QStringLiteral( "SELECT * FROM tbl_srs WHERE " ); + QString delim = QLatin1String( "" ); QString datum; // split on spaces followed by a plus sign (+) to deal @@ -746,15 +746,15 @@ bool QgsCoordinateReferenceSystem::createFromProj4( const QString &theProj4Strin QStringList myParams; Q_FOREACH ( const QString& param, myProj4String.split( QRegExp( "\\s+(?=\\+)" ), QString::SkipEmptyParts ) ) { - QString arg = QString( "' '||parameters||' ' LIKE %1" ).arg( quotedValue( QString( "% %1 %" ).arg( param.trimmed() ) ) ); - if ( param.startsWith( "+datum=" ) ) + QString arg = QStringLiteral( "' '||parameters||' ' LIKE %1" ).arg( quotedValue( QStringLiteral( "% %1 %" ).arg( param.trimmed() ) ) ); + if ( param.startsWith( QLatin1String( "+datum=" ) ) ) { datum = arg; } else { sql += delim + arg; - delim = " AND "; + delim = QStringLiteral( " AND " ); myParams << param.trimmed(); } } @@ -776,7 +776,7 @@ bool QgsCoordinateReferenceSystem::createFromProj4( const QString &theProj4Strin QStringList foundParams; Q_FOREACH ( const QString& param, myRecord["parameters"].split( QRegExp( "\\s+(?=\\+)" ), QString::SkipEmptyParts ) ) { - if ( !param.startsWith( "+datum=" ) ) + if ( !param.startsWith( QLatin1String( "+datum=" ) ) ) foundParams << param.trimmed(); } @@ -792,7 +792,7 @@ bool QgsCoordinateReferenceSystem::createFromProj4( const QString &theProj4Strin if ( !myRecord.empty() ) { - mySrsId = myRecord["srs_id"].toLong(); + mySrsId = myRecord[QStringLiteral( "srs_id" )].toLong(); QgsDebugMsg( "proj4string param match search for srsid returned srsid: " + QString::number( mySrsId ) ); if ( mySrsId > 0 ) { @@ -966,7 +966,7 @@ QString QgsCoordinateReferenceSystem::description() const { if ( d->mDescription.isNull() ) { - return ""; + return QLatin1String( "" ); } else { @@ -978,7 +978,7 @@ QString QgsCoordinateReferenceSystem::projectionAcronym() const { if ( d->mProjectionAcronym.isNull() ) { - return ""; + return QLatin1String( "" ); } else { @@ -990,7 +990,7 @@ QString QgsCoordinateReferenceSystem::ellipsoidAcronym() const { if ( d->mEllipsoidAcronym.isNull() ) { - return ""; + return QLatin1String( "" ); } else { @@ -1001,7 +1001,7 @@ QString QgsCoordinateReferenceSystem::ellipsoidAcronym() const QString QgsCoordinateReferenceSystem::toProj4() const { if ( !d->mIsValid ) - return ""; + return QLatin1String( "" ); if ( d->mProj4.isEmpty() ) { @@ -1087,7 +1087,7 @@ void QgsCoordinateReferenceSystem::setGeographicFlag( bool theGeoFlag ) void QgsCoordinateReferenceSystem::setEpsg( long theEpsg ) { d.detach(); - d->mAuthId = QString( "EPSG:%1" ).arg( theEpsg ); + d->mAuthId = QStringLiteral( "EPSG:%1" ).arg( theEpsg ); } void QgsCoordinateReferenceSystem::setProjectionAcronym( const QString& theProjectionAcronym ) { @@ -1129,13 +1129,13 @@ void QgsCoordinateReferenceSystem::setMapUnits() static const double smallNum = 1e-3; if ( qAbs( toMeter - feetToMeter ) < smallNum ) - unit = "Foot"; + unit = QStringLiteral( "Foot" ); QgsDebugMsg( "Projection has linear units of " + unit ); if ( qgsDoubleNear( toMeter, 1.0 ) ) //Unit name for meters would be "metre" d->mMapUnits = QgsUnitTypes::DistanceMeters; - else if ( unit == "Foot" ) + else if ( unit == QLatin1String( "Foot" ) ) d->mMapUnits = QgsUnitTypes::DistanceFeet; else { @@ -1147,7 +1147,7 @@ void QgsCoordinateReferenceSystem::setMapUnits() { OSRGetAngularUnits( d->mCRS, &unitName ); QString unit( unitName ); - if ( unit == "degree" ) + if ( unit == QLatin1String( "degree" ) ) d->mMapUnits = QgsUnitTypes::DistanceDegrees; else { @@ -1291,19 +1291,19 @@ bool QgsCoordinateReferenceSystem::readXml( const QDomNode & theNode ) d.detach(); QgsDebugMsg( "Reading Spatial Ref Sys from xml ------------------------!" ); bool result = true; - QDomNode srsNode = theNode.namedItem( "spatialrefsys" ); + QDomNode srsNode = theNode.namedItem( QStringLiteral( "spatialrefsys" ) ); if ( ! srsNode.isNull() ) { bool initialized = false; - long srsid = srsNode.namedItem( "srsid" ).toElement().text().toLong(); + long srsid = srsNode.namedItem( QStringLiteral( "srsid" ) ).toElement().text().toLong(); QDomNode myNode; if ( srsid < USER_CRS_START_ID ) { - myNode = srsNode.namedItem( "authid" ); + myNode = srsNode.namedItem( QStringLiteral( "authid" ) ); if ( !myNode.isNull() ) { operator=( QgsCoordinateReferenceSystem::fromOgcWmsCrs( myNode.toElement().text() ) ); @@ -1315,7 +1315,7 @@ bool QgsCoordinateReferenceSystem::readXml( const QDomNode & theNode ) if ( !initialized ) { - myNode = srsNode.namedItem( "epsg" ); + myNode = srsNode.namedItem( QStringLiteral( "epsg" ) ); if ( !myNode.isNull() ) { operator=( QgsCoordinateReferenceSystem::fromEpsgId( myNode.toElement().text().toLong() ) ); @@ -1337,7 +1337,7 @@ bool QgsCoordinateReferenceSystem::readXml( const QDomNode & theNode ) } else { - myNode = srsNode.namedItem( "proj4" ); + myNode = srsNode.namedItem( QStringLiteral( "proj4" ) ); if ( createFromProj4( myNode.toElement().text() ) ) { @@ -1348,29 +1348,29 @@ bool QgsCoordinateReferenceSystem::readXml( const QDomNode & theNode ) { QgsDebugMsg( "Setting from elements one by one" ); - myNode = srsNode.namedItem( "proj4" ); + myNode = srsNode.namedItem( QStringLiteral( "proj4" ) ); setProj4String( myNode.toElement().text() ); - myNode = srsNode.namedItem( "srsid" ); + myNode = srsNode.namedItem( QStringLiteral( "srsid" ) ); setInternalId( myNode.toElement().text().toLong() ); - myNode = srsNode.namedItem( "srid" ); + myNode = srsNode.namedItem( QStringLiteral( "srid" ) ); setSrid( myNode.toElement().text().toLong() ); - myNode = srsNode.namedItem( "authid" ); + myNode = srsNode.namedItem( QStringLiteral( "authid" ) ); setAuthId( myNode.toElement().text() ); - myNode = srsNode.namedItem( "description" ); + myNode = srsNode.namedItem( QStringLiteral( "description" ) ); setDescription( myNode.toElement().text() ); - myNode = srsNode.namedItem( "projectionacronym" ); + myNode = srsNode.namedItem( QStringLiteral( "projectionacronym" ) ); setProjectionAcronym( myNode.toElement().text() ); - myNode = srsNode.namedItem( "ellipsoidacronym" ); + myNode = srsNode.namedItem( QStringLiteral( "ellipsoidacronym" ) ); setEllipsoidAcronym( myNode.toElement().text() ); - myNode = srsNode.namedItem( "geographicflag" ); - if ( myNode.toElement().text().compare( "true" ) ) + myNode = srsNode.namedItem( QStringLiteral( "geographicflag" ) ); + if ( myNode.toElement().text().compare( QLatin1String( "true" ) ) ) { setGeographicFlag( true ); } @@ -1391,7 +1391,7 @@ bool QgsCoordinateReferenceSystem::readXml( const QDomNode & theNode ) // familiar with the code (should also give a more descriptive name to the generated CRS) if ( d->mSrsId == 0 ) { - QString myName = QString( " * %1 (%2)" ) + QString myName = QStringLiteral( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), toProj4() ); saveAsUserCrs( myName ); @@ -1412,41 +1412,41 @@ bool QgsCoordinateReferenceSystem::writeXml( QDomNode & theNode, QDomDocument & { QDomElement myLayerNode = theNode.toElement(); - QDomElement mySrsElement = theDoc.createElement( "spatialrefsys" ); + QDomElement mySrsElement = theDoc.createElement( QStringLiteral( "spatialrefsys" ) ); - QDomElement myProj4Element = theDoc.createElement( "proj4" ); + QDomElement myProj4Element = theDoc.createElement( QStringLiteral( "proj4" ) ); myProj4Element.appendChild( theDoc.createTextNode( toProj4() ) ); mySrsElement.appendChild( myProj4Element ); - QDomElement mySrsIdElement = theDoc.createElement( "srsid" ); + QDomElement mySrsIdElement = theDoc.createElement( QStringLiteral( "srsid" ) ); mySrsIdElement.appendChild( theDoc.createTextNode( QString::number( srsid() ) ) ); mySrsElement.appendChild( mySrsIdElement ); - QDomElement mySridElement = theDoc.createElement( "srid" ); + QDomElement mySridElement = theDoc.createElement( QStringLiteral( "srid" ) ); mySridElement.appendChild( theDoc.createTextNode( QString::number( postgisSrid() ) ) ); mySrsElement.appendChild( mySridElement ); - QDomElement myEpsgElement = theDoc.createElement( "authid" ); + QDomElement myEpsgElement = theDoc.createElement( QStringLiteral( "authid" ) ); myEpsgElement.appendChild( theDoc.createTextNode( authid() ) ); mySrsElement.appendChild( myEpsgElement ); - QDomElement myDescriptionElement = theDoc.createElement( "description" ); + QDomElement myDescriptionElement = theDoc.createElement( QStringLiteral( "description" ) ); myDescriptionElement.appendChild( theDoc.createTextNode( description() ) ); mySrsElement.appendChild( myDescriptionElement ); - QDomElement myProjectionAcronymElement = theDoc.createElement( "projectionacronym" ); + QDomElement myProjectionAcronymElement = theDoc.createElement( QStringLiteral( "projectionacronym" ) ); myProjectionAcronymElement.appendChild( theDoc.createTextNode( projectionAcronym() ) ); mySrsElement.appendChild( myProjectionAcronymElement ); - QDomElement myEllipsoidAcronymElement = theDoc.createElement( "ellipsoidacronym" ); + QDomElement myEllipsoidAcronymElement = theDoc.createElement( QStringLiteral( "ellipsoidacronym" ) ); myEllipsoidAcronymElement.appendChild( theDoc.createTextNode( ellipsoidAcronym() ) ); mySrsElement.appendChild( myEllipsoidAcronymElement ); - QDomElement myGeographicFlagElement = theDoc.createElement( "geographicflag" ); - QString myGeoFlagText = "false"; + QDomElement myGeographicFlagElement = theDoc.createElement( QStringLiteral( "geographicflag" ) ); + QString myGeoFlagText = QStringLiteral( "false" ); if ( isGeographic() ) { - myGeoFlagText = "true"; + myGeoFlagText = QStringLiteral( "true" ); } myGeographicFlagElement.appendChild( theDoc.createTextNode( myGeoFlagText ) ); @@ -1471,7 +1471,7 @@ QString QgsCoordinateReferenceSystem::proj4FromSrsId( const int theSrsId ) QString myDatabaseFileName; QString myProjString; - QString mySql = QString( "select parameters from tbl_srs where srs_id = %1 order by deprecated" ).arg( theSrsId ); + QString mySql = QStringLiteral( "select parameters from tbl_srs where srs_id = %1 order by deprecated" ).arg( theSrsId ); QgsDebugMsg( "mySrsId = " + QString::number( theSrsId ) ); QgsDebugMsg( "USER_CRS_START_ID = " + QString::number( USER_CRS_START_ID ) ); @@ -1661,14 +1661,14 @@ bool QgsCoordinateReferenceSystem::saveAsUserCrs( const QString& name ) //We add the just created user CRS to the list of recently used CRS QSettings settings; //QStringList recentProjections = settings.value( "/UI/recentProjections" ).toStringList(); - QStringList projectionsProj4 = settings.value( "/UI/recentProjectionsProj4" ).toStringList(); - QStringList projectionsAuthId = settings.value( "/UI/recentProjectionsAuthId" ).toStringList(); + QStringList projectionsProj4 = settings.value( QStringLiteral( "/UI/recentProjectionsProj4" ) ).toStringList(); + QStringList projectionsAuthId = settings.value( QStringLiteral( "/UI/recentProjectionsAuthId" ) ).toStringList(); //recentProjections.append(); //settings.setValue( "/UI/recentProjections", recentProjections ); projectionsProj4.append( toProj4() ); projectionsAuthId.append( authid() ); - settings.setValue( "/UI/recentProjectionsProj4", projectionsProj4 ); - settings.setValue( "/UI/recentProjectionsAuthId", projectionsAuthId ); + settings.setValue( QStringLiteral( "/UI/recentProjectionsProj4" ), projectionsProj4 ); + settings.setValue( QStringLiteral( "/UI/recentProjectionsAuthId" ), projectionsAuthId ); } else @@ -1691,7 +1691,7 @@ long QgsCoordinateReferenceSystem::getRecordCount() return 0; } // Set up the query to retrieve the projection information needed to populate the ELLIPSOID list - QString mySql = "select count(*) from tbl_srs"; + QString mySql = QStringLiteral( "select count(*) from tbl_srs" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); // XXX Need to free memory from the error msg if one is set if ( myResult == SQLITE_OK ) @@ -1710,7 +1710,7 @@ long QgsCoordinateReferenceSystem::getRecordCount() QString QgsCoordinateReferenceSystem::quotedValue( QString value ) { - value.replace( '\'', "''" ); + value.replace( '\'', QLatin1String( "''" ) ); return value.prepend( '\'' ).append( '\'' ); } @@ -1738,7 +1738,7 @@ bool QgsCoordinateReferenceSystem::loadWkts( QHash &wkts, const ch { continue; } - else if ( line.startsWith( "include " ) ) + else if ( line.startsWith( QLatin1String( "include " ) ) ) { if ( !loadWkts( wkts, line.mid( 8 ).toUtf8() ) ) break; @@ -1896,7 +1896,7 @@ int QgsCoordinateReferenceSystem::syncDb() if ( proj4.isEmpty() ) continue; - sql = QString( "SELECT parameters,noupdate FROM tbl_srs WHERE auth_name='EPSG' AND auth_id='%1'" ).arg( it.key() ); + sql = QStringLiteral( "SELECT parameters,noupdate FROM tbl_srs WHERE auth_name='EPSG' AND auth_id='%1'" ).arg( it.key() ); if ( sqlite3_prepare( database, sql.toLatin1(), sql.size(), &select, &tail ) != SQLITE_OK ) { qCritical( "Could not prepare: %s [%s]\n", sql.toLatin1().constData(), sqlite3_errmsg( database ) ); @@ -1919,7 +1919,7 @@ int QgsCoordinateReferenceSystem::syncDb() if ( proj4 != srsProj4 ) { errMsg = nullptr; - sql = QString( "UPDATE tbl_srs SET parameters=%1 WHERE auth_name='EPSG' AND auth_id=%2" ).arg( quotedValue( proj4 ) ).arg( it.key() ); + sql = QStringLiteral( "UPDATE tbl_srs SET parameters=%1 WHERE auth_name='EPSG' AND auth_id=%2" ).arg( quotedValue( proj4 ) ).arg( it.key() ); if ( sqlite3_exec( database, sql.toUtf8(), nullptr, nullptr, &errMsg ) != SQLITE_OK ) { @@ -1956,7 +1956,7 @@ int QgsCoordinateReferenceSystem::syncDb() if ( name.isEmpty() ) name = QObject::tr( "Imported from GDAL" ); - sql = QString( "INSERT INTO tbl_srs(description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name,auth_id,is_geo,deprecated) VALUES (%1,%2,%3,%4,%5,'EPSG',%5,%6,0)" ) + sql = QStringLiteral( "INSERT INTO tbl_srs(description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name,auth_id,is_geo,deprecated) VALUES (%1,%2,%3,%4,%5,'EPSG',%5,%6,0)" ) .arg( quotedValue( name ), quotedValue( projRegExp.cap( 1 ) ), quotedValue( ellps ), @@ -1983,7 +1983,7 @@ int QgsCoordinateReferenceSystem::syncDb() } } - sql = "DELETE FROM tbl_srs WHERE auth_name='EPSG' AND NOT auth_id IN ("; + sql = QStringLiteral( "DELETE FROM tbl_srs WHERE auth_name='EPSG' AND NOT auth_id IN (" ); QString delim; QHash::const_iterator it = wkts.constBegin(); for ( ; it != wkts.constEnd(); ++it ) @@ -1991,7 +1991,7 @@ int QgsCoordinateReferenceSystem::syncDb() sql += delim + QString::number( it.key() ); delim = ','; } - sql += ") AND NOT noupdate"; + sql += QLatin1String( ") AND NOT noupdate" ); if ( sqlite3_exec( database, sql.toUtf8(), nullptr, nullptr, nullptr ) == SQLITE_OK ) { @@ -2006,7 +2006,7 @@ int QgsCoordinateReferenceSystem::syncDb() } #if !defined(PJ_VERSION) || PJ_VERSION!=470 - sql = QString( "select auth_name,auth_id,parameters from tbl_srs WHERE auth_name<>'EPSG' AND NOT deprecated AND NOT noupdate" ); + sql = QStringLiteral( "select auth_name,auth_id,parameters from tbl_srs WHERE auth_name<>'EPSG' AND NOT deprecated AND NOT noupdate" ); if ( sqlite3_prepare( database, sql.toLatin1(), sql.size(), &select, &tail ) == SQLITE_OK ) { while ( sqlite3_step( select ) == SQLITE_ROW ) @@ -2015,11 +2015,11 @@ int QgsCoordinateReferenceSystem::syncDb() const char *auth_id = reinterpret_cast< const char * >( sqlite3_column_text( select, 1 ) ); const char *params = reinterpret_cast< const char * >( sqlite3_column_text( select, 2 ) ); - QString input = QString( "+init=%1:%2" ).arg( QString( auth_name ).toLower(), auth_id ); + QString input = QStringLiteral( "+init=%1:%2" ).arg( QString( auth_name ).toLower(), auth_id ); projPJ pj = pj_init_plus( input.toLatin1() ); if ( !pj ) { - input = QString( "+init=%1:%2" ).arg( QString( auth_name ).toUpper(), auth_id ); + input = QStringLiteral( "+init=%1:%2" ).arg( QString( auth_name ).toUpper(), auth_id ); pj = pj_init_plus( input.toLatin1() ); } @@ -2040,7 +2040,7 @@ int QgsCoordinateReferenceSystem::syncDb() if ( proj4 != params ) { - sql = QString( "UPDATE tbl_srs SET parameters=%1 WHERE auth_name=%2 AND auth_id=%3" ) + sql = QStringLiteral( "UPDATE tbl_srs SET parameters=%1 WHERE auth_name=%2 AND auth_id=%3" ) .arg( quotedValue( proj4 ), quotedValue( auth_name ), quotedValue( auth_id ) ); @@ -2144,7 +2144,7 @@ bool QgsCoordinateReferenceSystem::syncDatumTransform( const QString& dbPath ) { "COORD_OP_CODE", "coord_op_code", -1 }, }; - QString update = "UPDATE tbl_datum_transform SET "; + QString update = QStringLiteral( "UPDATE tbl_datum_transform SET " ); QString insert, values; int n = CSLCount( fieldnames ); @@ -2181,7 +2181,7 @@ bool QgsCoordinateReferenceSystem::syncDatumTransform( const QString& dbPath ) if ( last ) { - update += " WHERE "; + update += QLatin1String( " WHERE " ); } else { @@ -2189,10 +2189,10 @@ bool QgsCoordinateReferenceSystem::syncDatumTransform( const QString& dbPath ) } } - update += QString( "%1=%%2" ).arg( map[i].dst ).arg( i + 1 ); + update += QStringLiteral( "%1=%%2" ).arg( map[i].dst ).arg( i + 1 ); insert += map[i].dst; - values += QString( "%%1" ).arg( i + 1 ); + values += QStringLiteral( "%%1" ).arg( i + 1 ); } insert = "INSERT INTO tbl_datum_transform(" + insert + ") VALUES (" + values + ')'; @@ -2243,13 +2243,13 @@ bool QgsCoordinateReferenceSystem::syncDatumTransform( const QString& dbPath ) int idx = map[i].idx; Q_ASSERT( idx != -1 ); Q_ASSERT( idx < n ); - v.insert( i, *values[ idx ] ? quotedValue( values[idx] ) : "NULL" ); + v.insert( i, *values[ idx ] ? quotedValue( values[idx] ) : QStringLiteral( "NULL" ) ); } //switch sign of rotation parameters. See http://trac.osgeo.org/proj/wiki/GenParms#towgs84-DatumtransformationtoWGS84 if ( v.at( idxmcode ).compare( QLatin1String( "'9607'" ) ) == 0 ) { - v[ idxmcode ] = "'9606'"; + v[ idxmcode ] = QStringLiteral( "'9606'" ); v[ idxrx ] = '\'' + qgsDoubleToString( -( v[ idxrx ].remove( '\'' ).toDouble() ) ) + '\''; v[ idxry ] = '\'' + qgsDoubleToString( -( v[ idxry ].remove( '\'' ).toDouble() ) ) + '\''; v[ idxrz ] = '\'' + qgsDoubleToString( -( v[ idxrz ].remove( '\'' ).toDouble() ) ) + '\''; @@ -2258,7 +2258,7 @@ bool QgsCoordinateReferenceSystem::syncDatumTransform( const QString& dbPath ) //entry already in db? sqlite3_stmt *stmt; QString cOpCode; - QString sql = QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE coord_op_code=%1" ).arg( v[ idxid ] ); + QString sql = QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE coord_op_code=%1" ).arg( v[ idxid ] ); int prepareRes = sqlite3_prepare( db, sql.toLatin1(), sql.size(), &stmt, nullptr ); if ( prepareRes != SQLITE_OK ) continue; @@ -2300,11 +2300,11 @@ QString QgsCoordinateReferenceSystem::geographicCrsAuthId() const } else if ( d->mCRS ) { - return OSRGetAuthorityName( d->mCRS, "GEOGCS" ) + QLatin1String( ":" ) + OSRGetAuthorityCode( d->mCRS, "GEOGCS" ); + return OSRGetAuthorityName( d->mCRS, "GEOGCS" ) + QStringLiteral( ":" ) + OSRGetAuthorityCode( d->mCRS, "GEOGCS" ); } else { - return ""; + return QLatin1String( "" ); } } @@ -2314,12 +2314,12 @@ QStringList QgsCoordinateReferenceSystem::recentProjections() // Read settings from persistent storage QSettings settings; - projections = settings.value( "/UI/recentProjections" ).toStringList(); + projections = settings.value( QStringLiteral( "/UI/recentProjections" ) ).toStringList(); /*** The reading (above) of internal id from persistent storage should be removed sometime in the future */ /*** This is kept now for backwards compatibility */ - QStringList projectionsProj4 = settings.value( "/UI/recentProjectionsProj4" ).toStringList(); - QStringList projectionsAuthId = settings.value( "/UI/recentProjectionsAuthId" ).toStringList(); + QStringList projectionsProj4 = settings.value( QStringLiteral( "/UI/recentProjectionsProj4" ) ).toStringList(); + QStringList projectionsAuthId = settings.value( QStringLiteral( "/UI/recentProjectionsAuthId" ) ).toStringList(); if ( projectionsAuthId.size() >= projections.size() ) { // We had saved state with AuthId and Proj4. Use that instead diff --git a/src/core/qgscoordinatereferencesystem.h b/src/core/qgscoordinatereferencesystem.h index 954c052f3bde..330ad0e9e1c5 100644 --- a/src/core/qgscoordinatereferencesystem.h +++ b/src/core/qgscoordinatereferencesystem.h @@ -697,44 +697,44 @@ class CORE_EXPORT QgsCoordinateReferenceSystem //! Output stream operator inline std::ostream& operator << ( std::ostream& os, const QgsCoordinateReferenceSystem &r ) { - QString mySummary( "\n\tSpatial Reference System:" ); - mySummary += "\n\t\tDescription : "; + QString mySummary( QStringLiteral( "\n\tSpatial Reference System:" ) ); + mySummary += QLatin1String( "\n\t\tDescription : " ); if ( !r.description().isNull() ) { mySummary += r.description(); } else { - mySummary += "Undefined"; + mySummary += QLatin1String( "Undefined" ); } - mySummary += "\n\t\tProjection : "; + mySummary += QLatin1String( "\n\t\tProjection : " ); if ( !r.projectionAcronym().isNull() ) { mySummary += r.projectionAcronym(); } else { - mySummary += "Undefined"; + mySummary += QLatin1String( "Undefined" ); } - mySummary += "\n\t\tEllipsoid : "; + mySummary += QLatin1String( "\n\t\tEllipsoid : " ); if ( !r.ellipsoidAcronym().isNull() ) { mySummary += r.ellipsoidAcronym(); } else { - mySummary += "Undefined"; + mySummary += QLatin1String( "Undefined" ); } - mySummary += "\n\t\tProj4String : "; + mySummary += QLatin1String( "\n\t\tProj4String : " ); if ( !r.toProj4().isNull() ) { mySummary += r.toProj4(); } else { - mySummary += "Undefined"; + mySummary += QLatin1String( "Undefined" ); } // Using streams we need to use local 8 Bit return os << mySummary.toLocal8Bit().data() << std::endl; diff --git a/src/core/qgscoordinatetransform.cpp b/src/core/qgscoordinatetransform.cpp index 1e611bb8b959..134c4086d681 100644 --- a/src/core/qgscoordinatetransform.cpp +++ b/src/core/qgscoordinatetransform.cpp @@ -508,11 +508,11 @@ void QgsCoordinateTransform::transformCoords( int numPoints, double *x, double * { if ( direction == ForwardTransform ) { - points += QString( "(%1, %2)\n" ).arg( x[i], 0, 'f' ).arg( y[i], 0, 'f' ); + points += QStringLiteral( "(%1, %2)\n" ).arg( x[i], 0, 'f' ).arg( y[i], 0, 'f' ); } else { - points += QString( "(%1, %2)\n" ).arg( x[i] * RAD_TO_DEG, 0, 'f' ).arg( y[i] * RAD_TO_DEG, 0, 'f' ); + points += QStringLiteral( "(%1, %2)\n" ).arg( x[i] * RAD_TO_DEG, 0, 'f' ).arg( y[i] * RAD_TO_DEG, 0, 'f' ); } } @@ -573,14 +573,14 @@ bool QgsCoordinateTransform::readXml( const QDomNode & theNode ) QgsDebugMsg( "Reading Coordinate Transform from xml ------------------------!" ); - QDomNode mySrcNode = theNode.namedItem( "sourcesrs" ); + QDomNode mySrcNode = theNode.namedItem( QStringLiteral( "sourcesrs" ) ); d->mSourceCRS.readXml( mySrcNode ); - QDomNode myDestNode = theNode.namedItem( "destinationsrs" ); + QDomNode myDestNode = theNode.namedItem( QStringLiteral( "destinationsrs" ) ); d->mDestCRS.readXml( myDestNode ); - d->mSourceDatumTransform = theNode.toElement().attribute( "sourceDatumTransform", "-1" ).toInt(); - d->mDestinationDatumTransform = theNode.toElement().attribute( "destinationDatumTransform", "-1" ).toInt(); + d->mSourceDatumTransform = theNode.toElement().attribute( QStringLiteral( "sourceDatumTransform" ), QStringLiteral( "-1" ) ).toInt(); + d->mDestinationDatumTransform = theNode.toElement().attribute( QStringLiteral( "destinationDatumTransform" ), QStringLiteral( "-1" ) ).toInt(); return d->initialise(); } @@ -588,15 +588,15 @@ bool QgsCoordinateTransform::readXml( const QDomNode & theNode ) bool QgsCoordinateTransform::writeXml( QDomNode & theNode, QDomDocument & theDoc ) const { QDomElement myNodeElement = theNode.toElement(); - QDomElement myTransformElement = theDoc.createElement( "coordinatetransform" ); - myTransformElement.setAttribute( "sourceDatumTransform", QString::number( d->mSourceDatumTransform ) ); - myTransformElement.setAttribute( "destinationDatumTransform", QString::number( d->mDestinationDatumTransform ) ); + QDomElement myTransformElement = theDoc.createElement( QStringLiteral( "coordinatetransform" ) ); + myTransformElement.setAttribute( QStringLiteral( "sourceDatumTransform" ), QString::number( d->mSourceDatumTransform ) ); + myTransformElement.setAttribute( QStringLiteral( "destinationDatumTransform" ), QString::number( d->mDestinationDatumTransform ) ); - QDomElement mySourceElement = theDoc.createElement( "sourcesrs" ); + QDomElement mySourceElement = theDoc.createElement( QStringLiteral( "sourcesrs" ) ); d->mSourceCRS.writeXml( mySourceElement, theDoc ); myTransformElement.appendChild( mySourceElement ); - QDomElement myDestElement = theDoc.createElement( "destinationsrs" ); + QDomElement myDestElement = theDoc.createElement( QStringLiteral( "destinationsrs" ) ); d->mDestCRS.writeXml( myDestElement, theDoc ); myTransformElement.appendChild( myDestElement ); @@ -648,16 +648,16 @@ QList< QList< int > > QgsCoordinateTransform::datumTransformations( const QgsCoo } QList directTransforms; - searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code=%1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( destAuthCode ), + searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code=%1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( destAuthCode ), directTransforms ); QList reverseDirectTransforms; - searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code = %1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( srcAuthCode ), + searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE source_crs_code = %1 AND target_crs_code=%2 ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( srcAuthCode ), reverseDirectTransforms ); QList srcToWgs84; - searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( 4326 ), + searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( srcAuthCode ).arg( 4326 ), srcToWgs84 ); QList destToWgs84; - searchDatumTransform( QString( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( 4326 ), + searchDatumTransform( QStringLiteral( "SELECT coord_op_code FROM tbl_datum_transform WHERE (source_crs_code=%1 AND target_crs_code=%2) OR (source_crs_code=%2 AND target_crs_code=%1) ORDER BY deprecated ASC,preferred DESC" ).arg( destAuthCode ).arg( 4326 ), destToWgs84 ); //add direct datum transformations @@ -732,7 +732,7 @@ bool QgsCoordinateTransform::datumTransformCrsInfo( int datumTransform, int& eps } sqlite3_stmt* stmt; - QString sql = QString( "SELECT epsg_nr,source_crs_code,target_crs_code,remarks,scope,preferred,deprecated FROM tbl_datum_transform WHERE coord_op_code=%1" ).arg( datumTransform ); + QString sql = QStringLiteral( "SELECT epsg_nr,source_crs_code,target_crs_code,remarks,scope,preferred,deprecated FROM tbl_datum_transform WHERE coord_op_code=%1" ).arg( datumTransform ); int prepareRes = sqlite3_prepare( db, sql.toLatin1(), sql.size(), &stmt, nullptr ); if ( prepareRes != SQLITE_OK ) { @@ -757,9 +757,9 @@ bool QgsCoordinateTransform::datumTransformCrsInfo( int datumTransform, int& eps preferred = sqlite3_column_int( stmt, 5 ) != 0; deprecated = sqlite3_column_int( stmt, 6 ) != 0; - QgsCoordinateReferenceSystem srcCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( srcCrsId ) ); + QgsCoordinateReferenceSystem srcCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( srcCrsId ) ); srcProjection = srcCrs.description(); - QgsCoordinateReferenceSystem destCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( destCrsId ) ); + QgsCoordinateReferenceSystem destCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( destCrsId ) ); dstProjection = destCrs.description(); sqlite3_finalize( stmt ); diff --git a/src/core/qgscoordinatetransform.h b/src/core/qgscoordinatetransform.h index 9446f4fff2b5..0ebfb86a2c4f 100644 --- a/src/core/qgscoordinatetransform.h +++ b/src/core/qgscoordinatetransform.h @@ -281,8 +281,8 @@ class CORE_EXPORT QgsCoordinateTransform //! Output stream operator inline std::ostream& operator << ( std::ostream& os, const QgsCoordinateTransform &r ) { - QString mySummary( "\n%%%%%%%%%%%%%%%%%%%%%%%%\nCoordinate Transform def begins:" ); - mySummary += "\n\tInitialised? : "; + QString mySummary( QStringLiteral( "\n%%%%%%%%%%%%%%%%%%%%%%%%\nCoordinate Transform def begins:" ) ); + mySummary += QLatin1String( "\n\tInitialised? : " ); //prevent warnings if ( r.isValid() ) { @@ -329,7 +329,7 @@ inline std::ostream& operator << ( std::ostream& os, const QgsCoordinateTransfor } #endif - mySummary += ( "\nCoordinate Transform def ends \n%%%%%%%%%%%%%%%%%%%%%%%%\n" ); + mySummary += QLatin1String( "\nCoordinate Transform def ends \n%%%%%%%%%%%%%%%%%%%%%%%%\n" ); return os << mySummary.toLocal8Bit().data() << std::endl; } diff --git a/src/core/qgscoordinatetransform_p.h b/src/core/qgscoordinatetransform_p.h index 007ae59cbe05..4c98d1dfbe41 100644 --- a/src/core/qgscoordinatetransform_p.h +++ b/src/core/qgscoordinatetransform_p.h @@ -219,8 +219,8 @@ class QgsCoordinateTransformPrivate : public QSharedData for ( int i = 0; i < parameterSplit.size(); ++i ) { currentParameter = parameterSplit.at( i ); - if ( !currentParameter.startsWith( "towgs84", Qt::CaseInsensitive ) - && !currentParameter.startsWith( "nadgrids", Qt::CaseInsensitive ) ) + if ( !currentParameter.startsWith( QLatin1String( "towgs84" ), Qt::CaseInsensitive ) + && !currentParameter.startsWith( QLatin1String( "nadgrids" ), Qt::CaseInsensitive ) ) { newProjString.append( '+' ); newProjString.append( currentParameter ); @@ -243,7 +243,7 @@ class QgsCoordinateTransformPrivate : public QSharedData } sqlite3_stmt* stmt; - QString sql = QString( "SELECT coord_op_method_code,p1,p2,p3,p4,p5,p6,p7 FROM tbl_datum_transform WHERE coord_op_code=%1" ).arg( datumTransform ); + QString sql = QStringLiteral( "SELECT coord_op_method_code,p1,p2,p3,p4,p5,p6,p7 FROM tbl_datum_transform WHERE coord_op_code=%1" ).arg( datumTransform ); int prepareRes = sqlite3_prepare( db, sql.toLatin1(), sql.size(), &stmt, nullptr ); if ( prepareRes != SQLITE_OK ) { @@ -262,7 +262,7 @@ class QgsCoordinateTransformPrivate : public QSharedData } else if ( methodCode == 9603 || methodCode == 9606 || methodCode == 9607 ) { - transformString += "+towgs84="; + transformString += QLatin1String( "+towgs84=" ); double p1 = sqlite3_column_double( stmt, 1 ); double p2 = sqlite3_column_double( stmt, 2 ); double p3 = sqlite3_column_double( stmt, 3 ); @@ -272,11 +272,11 @@ class QgsCoordinateTransformPrivate : public QSharedData double p7 = sqlite3_column_double( stmt, 7 ); if ( methodCode == 9603 ) //3 parameter transformation { - transformString += QString( "%1,%2,%3" ).arg( p1 ).arg( p2 ).arg( p3 ); + transformString += QStringLiteral( "%1,%2,%3" ).arg( p1 ).arg( p2 ).arg( p3 ); } else //7 parameter transformation { - transformString += QString( "%1,%2,%3,%4,%5,%6,%7" ).arg( p1 ).arg( p2 ).arg( p3 ).arg( p4 ).arg( p5 ).arg( p6 ).arg( p7 ); + transformString += QStringLiteral( "%1,%2,%3,%4,%5,%6,%7" ).arg( p1 ).arg( p2 ).arg( p3 ).arg( p4 ).arg( p5 ).arg( p6 ).arg( p7 ); } } } @@ -290,26 +290,26 @@ class QgsCoordinateTransformPrivate : public QSharedData void addNullGridShifts( QString& srcProjString, QString& destProjString ) const { //if one transformation uses ntv2, the other one needs to be null grid shift - if ( mDestinationDatumTransform == -1 && srcProjString.contains( "+nadgrids" ) ) //add null grid if source transformation is ntv2 + if ( mDestinationDatumTransform == -1 && srcProjString.contains( QLatin1String( "+nadgrids" ) ) ) //add null grid if source transformation is ntv2 { - destProjString += " +nadgrids=@null"; + destProjString += QLatin1String( " +nadgrids=@null" ); return; } - if ( mSourceDatumTransform == -1 && destProjString.contains( "+nadgrids" ) ) + if ( mSourceDatumTransform == -1 && destProjString.contains( QLatin1String( "+nadgrids" ) ) ) { - srcProjString += " +nadgrids=@null"; + srcProjString += QLatin1String( " +nadgrids=@null" ); return; } //add null shift grid for google mercator //(see e.g. http://trac.osgeo.org/proj/wiki/FAQ#ChangingEllipsoidWhycantIconvertfromWGS84toGoogleEarthVirtualGlobeMercator) - if ( mSourceCRS.authid().compare( "EPSG:3857", Qt::CaseInsensitive ) == 0 && mSourceDatumTransform == -1 ) + if ( mSourceCRS.authid().compare( QLatin1String( "EPSG:3857" ), Qt::CaseInsensitive ) == 0 && mSourceDatumTransform == -1 ) { - srcProjString += " +nadgrids=@null"; + srcProjString += QLatin1String( " +nadgrids=@null" ); } - if ( mDestCRS.authid().compare( "EPSG:3857", Qt::CaseInsensitive ) == 0 && mDestinationDatumTransform == -1 ) + if ( mDestCRS.authid().compare( QLatin1String( "EPSG:3857" ), Qt::CaseInsensitive ) == 0 && mDestinationDatumTransform == -1 ) { - destProjString += " +nadgrids=@null"; + destProjString += QLatin1String( " +nadgrids=@null" ); } } diff --git a/src/core/qgscoordinateutils.cpp b/src/core/qgscoordinateutils.cpp index 4f364a6c393c..c6ade6decb81 100644 --- a/src/core/qgscoordinateutils.cpp +++ b/src/core/qgscoordinateutils.cpp @@ -27,13 +27,13 @@ int QgsCoordinateUtils::calculateCoordinatePrecision( double mapUnitsPerPixel, const QgsCoordinateReferenceSystem& mapCrs ) { // Get the display precision from the project settings - bool automatic = QgsProject::instance()->readBoolEntry( "PositionPrecision", "/Automatic" ); + bool automatic = QgsProject::instance()->readBoolEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/Automatic" ) ); int dp = 0; if ( automatic ) { - QString format = QgsProject::instance()->readEntry( "PositionPrecision", "/DegreeFormat", "MU" ); - bool formatGeographic = ( format == "DM" || format == "DMS" || format == "D" ); + QString format = QgsProject::instance()->readEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DegreeFormat" ), QStringLiteral( "MU" ) ); + bool formatGeographic = ( format == QLatin1String( "DM" ) || format == QLatin1String( "DMS" ) || format == QLatin1String( "D" ) ); // we can only calculate an automatic precision if one of these is true: // - both map CRS and format are geographic @@ -49,11 +49,11 @@ int QgsCoordinateUtils::calculateCoordinatePrecision( double mapUnitsPerPixel, c } else { - dp = format == "D" ? 4 : 2; //guess sensible fallback + dp = format == QLatin1String( "D" ) ? 4 : 2; //guess sensible fallback } } else - dp = QgsProject::instance()->readNumEntry( "PositionPrecision", "/DecimalPlaces" ); + dp = QgsProject::instance()->readNumEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DecimalPlaces" ) ); // Keep dp sensible if ( dp < 0 ) @@ -64,10 +64,10 @@ int QgsCoordinateUtils::calculateCoordinatePrecision( double mapUnitsPerPixel, c QString QgsCoordinateUtils::formatCoordinateForProject( const QgsPoint& point, const QgsCoordinateReferenceSystem& destCrs, int precision ) { - QString format = QgsProject::instance()->readEntry( "PositionPrecision", "/DegreeFormat", "MU" ); + QString format = QgsProject::instance()->readEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DegreeFormat" ), QStringLiteral( "MU" ) ); QgsPoint geo = point; - if ( format == "DM" || format == "DMS" || format == "D" ) + if ( format == QLatin1String( "DM" ) || format == QLatin1String( "DMS" ) || format == QLatin1String( "D" ) ) { // degrees if ( destCrs.isValid() && !destCrs.isGeographic() ) @@ -84,9 +84,9 @@ QString QgsCoordinateUtils::formatCoordinateForProject( const QgsPoint& point, c } } - if ( format == "DM" ) + if ( format == QLatin1String( "DM" ) ) return geo.toDegreesMinutes( precision, true, true ); - else if ( format == "DMS" ) + else if ( format == QLatin1String( "DMS" ) ) return geo.toDegreesMinutesSeconds( precision, true, true ); else return geo.toString( precision ); diff --git a/src/core/qgsdartmeasurement.cpp b/src/core/qgsdartmeasurement.cpp index 1f11af31fa7f..15ac20f07c72 100644 --- a/src/core/qgsdartmeasurement.cpp +++ b/src/core/qgsdartmeasurement.cpp @@ -26,13 +26,13 @@ QgsDartMeasurement::QgsDartMeasurement( const QString& name, Type type, const QS const QString QgsDartMeasurement::toString() const { - QString elementName = "DartMeasurement"; + QString elementName = QStringLiteral( "DartMeasurement" ); if ( mType == ImagePng ) { - elementName = "DartMeasurementFile"; + elementName = QStringLiteral( "DartMeasurementFile" ); } - QString dashMessage = QString( "<%1 name=\"%2\" type=\"%3\">%4" ) + QString dashMessage = QStringLiteral( "<%1 name=\"%2\" type=\"%3\">%4" ) .arg( elementName, mName, typeToString( mType ), @@ -53,15 +53,15 @@ const QString QgsDartMeasurement::typeToString( QgsDartMeasurement::Type type ) switch ( type ) { case Text: - str = "text/text"; + str = QStringLiteral( "text/text" ); break; case ImagePng: - str = "image/png"; + str = QStringLiteral( "image/png" ); break; case Integer: - str = "numeric/integer"; + str = QStringLiteral( "numeric/integer" ); break; } diff --git a/src/core/qgsdatadefined.cpp b/src/core/qgsdatadefined.cpp index 8600a4bca7fc..44206a0b36e6 100644 --- a/src/core/qgsdatadefined.cpp +++ b/src/core/qgsdatadefined.cpp @@ -50,19 +50,19 @@ QgsDataDefined* QgsDataDefined::fromMap( const QgsStringMap &map, const QString QString prefix; if ( !baseName.isEmpty() ) { - prefix.append( QString( "%1_dd_" ).arg( baseName ) ); + prefix.append( QStringLiteral( "%1_dd_" ).arg( baseName ) ); } - if ( !map.contains( QString( "%1expression" ).arg( prefix ) ) ) + if ( !map.contains( QStringLiteral( "%1expression" ).arg( prefix ) ) ) { //requires at least the expression value return nullptr; } - bool active = ( map.value( QString( "%1active" ).arg( prefix ), "1" ) != QLatin1String( "0" ) ); - QString expression = map.value( QString( "%1expression" ).arg( prefix ) ); - bool useExpression = ( map.value( QString( "%1useexpr" ).arg( prefix ), "1" ) != QLatin1String( "0" ) ); - QString field = map.value( QString( "%1field" ).arg( prefix ), QString() ); + bool active = ( map.value( QStringLiteral( "%1active" ).arg( prefix ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); + QString expression = map.value( QStringLiteral( "%1expression" ).arg( prefix ) ); + bool useExpression = ( map.value( QStringLiteral( "%1useexpr" ).arg( prefix ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); + QString field = map.value( QStringLiteral( "%1field" ).arg( prefix ), QString() ); return new QgsDataDefined( active, useExpression, expression, field ); } @@ -139,7 +139,7 @@ void QgsDataDefined::setExpressionString( const QString &expr ) QString QgsDataDefined::expressionOrField() const { - return d->useExpression ? d->expressionString : QString( "\"%1\"" ).arg( d->field ); + return d->useExpression ? d->expressionString : QStringLiteral( "\"%1\"" ).arg( d->field ); } bool QgsDataDefined::prepareExpression( const QgsExpressionContext& context ) @@ -232,13 +232,13 @@ QgsStringMap QgsDataDefined::toMap( const QString &baseName ) const QString prefix; if ( !baseName.isEmpty() ) { - prefix.append( QString( "%1_dd_" ).arg( baseName ) ); + prefix.append( QStringLiteral( "%1_dd_" ).arg( baseName ) ); } - map.insert( QString( "%1active" ).arg( prefix ), ( d->active ? "1" : "0" ) ); - map.insert( QString( "%1useexpr" ).arg( prefix ), ( d->useExpression ? "1" : "0" ) ); - map.insert( QString( "%1expression" ).arg( prefix ), d->expressionString ); - map.insert( QString( "%1field" ).arg( prefix ), d->field ); + map.insert( QStringLiteral( "%1active" ).arg( prefix ), ( d->active ? "1" : "0" ) ); + map.insert( QStringLiteral( "%1useexpr" ).arg( prefix ), ( d->useExpression ? "1" : "0" ) ); + map.insert( QStringLiteral( "%1expression" ).arg( prefix ), d->expressionString ); + map.insert( QStringLiteral( "%1field" ).arg( prefix ), d->field ); return map; } @@ -246,10 +246,10 @@ QgsStringMap QgsDataDefined::toMap( const QString &baseName ) const QDomElement QgsDataDefined::toXmlElement( QDomDocument &document, const QString& elementName ) const { QDomElement element = document.createElement( elementName ); - element.setAttribute( "active", d->active ? "true" : "false" ); - element.setAttribute( "useExpr", d->useExpression ? "true" : "false" ); - element.setAttribute( "expr", d->expressionString ); - element.setAttribute( "field", d->field ); + element.setAttribute( QStringLiteral( "active" ), d->active ? "true" : "false" ); + element.setAttribute( QStringLiteral( "useExpr" ), d->useExpression ? "true" : "false" ); + element.setAttribute( QStringLiteral( "expr" ), d->expressionString ); + element.setAttribute( QStringLiteral( "field" ), d->field ); return element; } @@ -261,10 +261,10 @@ bool QgsDataDefined::setFromXmlElement( const QDomElement &element ) } d.detach(); - d->active = element.attribute( "active" ).compare( "true", Qt::CaseInsensitive ) == 0; - d->useExpression = element.attribute( "useExpr" ).compare( "true", Qt::CaseInsensitive ) == 0; - d->field = element.attribute( "field" ); - d->expressionString = element.attribute( "expr" ); + d->active = element.attribute( QStringLiteral( "active" ) ).compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0; + d->useExpression = element.attribute( QStringLiteral( "useExpr" ) ).compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0; + d->field = element.attribute( QStringLiteral( "field" ) ); + d->expressionString = element.attribute( QStringLiteral( "expr" ) ); d->expressionPrepared = false; d->exprRefColumns.clear(); return true; diff --git a/src/core/qgsdataitem.cpp b/src/core/qgsdataitem.cpp index f481e80f2897..783f6348e8d7 100644 --- a/src/core/qgsdataitem.cpp +++ b/src/core/qgsdataitem.cpp @@ -101,7 +101,7 @@ const QIcon &QgsLayerItem::iconPoint() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconPointLayer.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconPointLayer.svg" ) ); return icon; } @@ -111,7 +111,7 @@ const QIcon &QgsLayerItem::iconLine() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconLineLayer.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconLineLayer.svg" ) ); return icon; } @@ -121,7 +121,7 @@ const QIcon &QgsLayerItem::iconPolygon() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconPolygonLayer.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconPolygonLayer.svg" ) ); return icon; } @@ -131,7 +131,7 @@ const QIcon &QgsLayerItem::iconTable() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconTableLayer.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconTableLayer.svg" ) ); return icon; } @@ -141,7 +141,7 @@ const QIcon &QgsLayerItem::iconRaster() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconRaster.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconRaster.svg" ) ); return icon; } @@ -151,7 +151,7 @@ const QIcon &QgsLayerItem::iconDefault() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconLayer.png" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconLayer.png" ) ); return icon; } @@ -161,7 +161,7 @@ const QIcon &QgsDataCollectionItem::iconDataCollection() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconDbSchema.png" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDbSchema.png" ) ); return icon; } @@ -187,7 +187,7 @@ const QIcon &QgsFavouritesItem::iconFavourites() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconFavourites.png" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconFavourites.png" ) ); return icon; } @@ -197,7 +197,7 @@ const QIcon &QgsZipItem::iconZip() static QIcon icon; if ( icon.isNull() ) - icon = QgsApplication::getThemeIcon( "/mIconZip.png" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconZip.png" ) ); // icon from http://www.softicons.com/free-icons/application-icons/mega-pack-icons-1-by-nikolay-verin/winzip-folder-icon return icon; @@ -243,7 +243,7 @@ QgsDataItem::~QgsDataItem() QString QgsDataItem::pathComponent( const QString &string ) { - return QString( string ).replace( QRegExp( "[\\\\/]" ), "|" ); + return QString( string ).replace( QRegExp( "[\\\\/]" ), QStringLiteral( "|" ) ); } void QgsDataItem::deleteLater() @@ -619,7 +619,7 @@ void QgsDataItem::setState( State state ) if ( !mPopulatingIcon ) { // TODO: ensure that QgsAnimatedIcon is created on UI thread only - mPopulatingIcon = new QgsAnimatedIcon( QgsApplication::iconPath( "/mIconLoading.gif" ) ); + mPopulatingIcon = new QgsAnimatedIcon( QgsApplication::iconPath( QStringLiteral( "/mIconLoading.gif" ) ) ); } mPopulatingIcon->connectFrameChanged( this, SLOT( emitDataChanged() ) ); } @@ -646,26 +646,26 @@ QgsLayerItem::QgsLayerItem( QgsDataItem* parent, const QString& name, const QStr switch ( layerType ) { case Point: - mIconName = "/mIconPointLayer.svg"; + mIconName = QStringLiteral( "/mIconPointLayer.svg" ); break; case Line: - mIconName = "/mIconLineLayer.svg"; + mIconName = QStringLiteral( "/mIconLineLayer.svg" ); break; case Polygon: - mIconName = "/mIconPolygonLayer.svg"; + mIconName = QStringLiteral( "/mIconPolygonLayer.svg" ); break; // TODO add a new icon for generic Vector layers case Vector : - mIconName = "/mIconPolygonLayer.svg"; + mIconName = QStringLiteral( "/mIconPolygonLayer.svg" ); break; case TableLayer: - mIconName = "/mIconTableLayer.svg"; + mIconName = QStringLiteral( "/mIconTableLayer.svg" ); break; case Raster: - mIconName = "/mIconRaster.svg"; + mIconName = QStringLiteral( "/mIconRaster.svg" ); break; default: - mIconName = "/mIconLayer.png"; + mIconName = QStringLiteral( "/mIconLayer.png" ); break; } } @@ -701,13 +701,13 @@ QgsMimeDataUtils::Uri QgsLayerItem::mimeUri() const switch ( mapLayerType() ) { case QgsMapLayer::VectorLayer: - u.layerType = "vector"; + u.layerType = QStringLiteral( "vector" ); break; case QgsMapLayer::RasterLayer: - u.layerType = "raster"; + u.layerType = QStringLiteral( "raster" ); break; case QgsMapLayer::PluginLayer: - u.layerType = "plugin"; + u.layerType = QStringLiteral( "plugin" ); break; default: return u; // invalid URI @@ -726,7 +726,7 @@ QgsDataCollectionItem::QgsDataCollectionItem( QgsDataItem* parent, const QString : QgsDataItem( Collection, parent, name, path ) { mCapabilities = Fertile; - mIconName = "/mIconDbSchema.png"; + mIconName = QStringLiteral( "/mIconDbSchema.png" ); } QgsDataCollectionItem::~QgsDataCollectionItem() @@ -820,7 +820,7 @@ QVector QgsDirectoryItem::createChildren() QString path = dir.absoluteFilePath( name ); QFileInfo fileInfo( path ); - if ( fileInfo.suffix() == "qgs" ) + if ( fileInfo.suffix() == QLatin1String( "qgs" ) ) { QgsDataItem * item = new QgsProjectItem( this, name, path ); children.append( item ); @@ -899,7 +899,7 @@ void QgsDirectoryItem::directoryChanged() bool QgsDirectoryItem::hiddenPath( const QString& path ) { QSettings settings; - QStringList hiddenItems = settings.value( "/browser/hiddenPaths", + QStringList hiddenItems = settings.value( QStringLiteral( "/browser/hiddenPaths" ), QStringList() ).toStringList(); int idx = hiddenItems.indexOf( path ); return ( idx > -1 ); @@ -974,7 +974,7 @@ QgsDirectoryParamWidget::QgsDirectoryParamWidget( const QString& path, QWidget* } else { - size = QString( "%1 B" ).arg( fi.size() ); + size = QStringLiteral( "%1 B" ).arg( fi.size() ); } texts << size; texts << fi.lastModified().toString( Qt::SystemLocaleShortDate ); @@ -1028,7 +1028,7 @@ QgsDirectoryParamWidget::QgsDirectoryParamWidget( const QString& path, QWidget* // hide columns that are not requested QSettings settings; - QList lst = settings.value( "/dataitem/directoryHiddenColumns" ).toList(); + QList lst = settings.value( QStringLiteral( "/dataitem/directoryHiddenColumns" ) ).toList(); Q_FOREACH ( const QVariant& colVariant, lst ) { setColumnHidden( colVariant.toInt(), true ); @@ -1073,13 +1073,13 @@ void QgsDirectoryParamWidget::showHideColumn() if ( isColumnHidden( i ) ) lst.append( QVariant( i ) ); } - settings.setValue( "/dataitem/directoryHiddenColumns", lst ); + settings.setValue( QStringLiteral( "/dataitem/directoryHiddenColumns" ), lst ); } QgsProjectItem::QgsProjectItem( QgsDataItem* parent, const QString &name, const QString& path ) : QgsDataItem( QgsDataItem::Project, parent, name, path ) { - mIconName = ":/images/icons/qgis-icon-16x16.png"; + mIconName = QStringLiteral( ":/images/icons/qgis-icon-16x16.png" ); setState( Populated ); // no more children } @@ -1091,7 +1091,7 @@ QgsProjectItem::~QgsProjectItem() QgsErrorItem::QgsErrorItem( QgsDataItem* parent, const QString& error, const QString& path ) : QgsDataItem( QgsDataItem::Error, parent, error, path ) { - mIconName = "/mIconDelete.png"; + mIconName = QStringLiteral( "/mIconDelete.png" ); setState( Populated ); // no more children } @@ -1101,12 +1101,12 @@ QgsErrorItem::~QgsErrorItem() } QgsFavouritesItem::QgsFavouritesItem( QgsDataItem* parent, const QString& name, const QString& path ) - : QgsDataCollectionItem( parent, name, "favourites:" ) + : QgsDataCollectionItem( parent, name, QStringLiteral( "favourites:" ) ) { Q_UNUSED( path ); mCapabilities |= Fast; mType = Favourites; - mIconName = "/mIconFavourites.png"; + mIconName = QStringLiteral( "/mIconFavourites.png" ); populate(); } @@ -1119,7 +1119,7 @@ QVector QgsFavouritesItem::createChildren() QVector children; QSettings settings; - QStringList favDirs = settings.value( "/browser/favourites", QVariant() ).toStringList(); + QStringList favDirs = settings.value( QStringLiteral( "/browser/favourites" ), QVariant() ).toStringList(); Q_FOREACH ( const QString& favDir, favDirs ) { @@ -1132,9 +1132,9 @@ QVector QgsFavouritesItem::createChildren() void QgsFavouritesItem::addDirectory( const QString& favDir ) { QSettings settings; - QStringList favDirs = settings.value( "/browser/favourites" ).toStringList(); + QStringList favDirs = settings.value( QStringLiteral( "/browser/favourites" ) ).toStringList(); favDirs.append( favDir ); - settings.setValue( "/browser/favourites", favDirs ); + settings.setValue( QStringLiteral( "/browser/favourites" ), favDirs ); if ( state() == Populated ) { @@ -1152,9 +1152,9 @@ void QgsFavouritesItem::removeDirectory( QgsDirectoryItem *item ) return; QSettings settings; - QStringList favDirs = settings.value( "/browser/favourites" ).toStringList(); + QStringList favDirs = settings.value( QStringLiteral( "/browser/favourites" ) ).toStringList(); favDirs.removeAll( item->dirPath() ); - settings.setValue( "/browser/favourites", favDirs ); + settings.setValue( QStringLiteral( "/browser/favourites" ), favDirs ); int idx = findItem( mChildren, item ); if ( idx < 0 ) @@ -1218,7 +1218,7 @@ QgsZipItem::QgsZipItem( QgsDataItem* parent, const QString& name, const QString& void QgsZipItem::init() { mType = Collection; //Zip?? - mIconName = "/mIconZip.png"; + mIconName = QStringLiteral( "/mIconZip.png" ); mVsiPrefix = vsiPrefix( mFilePath ); if ( mProviderNames.isEmpty() ) @@ -1227,7 +1227,7 @@ void QgsZipItem::init() // only use GDAL and OGR providers as we use the VSIFILE mechanism QStringList keys; // keys << "ogr" << "gdal"; - keys << "gdal" << "ogr"; + keys << QStringLiteral( "gdal" ) << QStringLiteral( "ogr" ); QStringList::const_iterator i; for ( i = keys.begin(); i != keys.end(); ++i ) @@ -1352,14 +1352,14 @@ QVector QgsZipItem::createChildren() QVector children; QString tmpPath; QSettings settings; - QString scanZipSetting = settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString(); + QString scanZipSetting = settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString(); mZipFileList.clear(); QgsDebugMsgLevel( QString( "mFilePath = %1 path = %2 name= %3 scanZipSetting= %4 vsiPrefix= %5" ).arg( mFilePath, path(), name(), scanZipSetting, mVsiPrefix ), 2 ); // if scanZipBrowser == no: skip to the next file - if ( scanZipSetting == "no" ) + if ( scanZipSetting == QLatin1String( "no" ) ) { return children; } @@ -1378,14 +1378,14 @@ QVector QgsZipItem::createChildren() for ( int i = 0; i < mProviderNames.size(); i++ ) { // ugly hack to remove .dbf file if there is a .shp file - if ( mProviderNames[i] == "ogr" ) + if ( mProviderNames[i] == QLatin1String( "ogr" ) ) { - if ( info.suffix().toLower() == "dbf" ) + if ( info.suffix().toLower() == QLatin1String( "dbf" ) ) { if ( mZipFileList.indexOf( fileName.left( fileName.count() - 4 ) + ".shp" ) != -1 ) continue; } - if ( info.completeSuffix().toLower() == "shp.xml" ) + if ( info.completeSuffix().toLower() == QLatin1String( "shp.xml" ) ) { continue; } @@ -1425,7 +1425,7 @@ QgsDataItem* QgsZipItem::itemFromPath( QgsDataItem* parent, const QString& path, QgsDataItem* QgsZipItem::itemFromPath( QgsDataItem* parent, const QString& filePath, const QString& name, const QString& path ) { QSettings settings; - QString scanZipSetting = settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString(); + QString scanZipSetting = settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString(); int zipFileCount = 0; QStringList zipFileList; QString vsiPrefix = QgsZipItem::vsiPrefix( filePath ); @@ -1435,11 +1435,11 @@ QgsDataItem* QgsZipItem::itemFromPath( QgsDataItem* parent, const QString& fileP QgsDebugMsgLevel( QString( "path = %1 name= %2 scanZipSetting= %3 vsiPrefix= %4" ).arg( path, name, scanZipSetting, vsiPrefix ), 3 ); // don't scan if scanZipBrowser == no - if ( scanZipSetting == "no" ) + if ( scanZipSetting == QLatin1String( "no" ) ) return nullptr; // don't scan if this file is not a /vsizip/ or /vsitar/ item - if (( vsiPrefix != "/vsizip/" && vsiPrefix != "/vsitar/" ) ) + if (( vsiPrefix != QLatin1String( "/vsizip/" ) && vsiPrefix != QLatin1String( "/vsitar/" ) ) ) return nullptr; zipItem = new QgsZipItem( parent, name, filePath, path ); @@ -1452,8 +1452,8 @@ QgsDataItem* QgsZipItem::itemFromPath( QgsDataItem* parent, const QString& fileP // could also accept all files smaller than a certain size and add options for file count and/or size // first get list of files inside .zip or .tar files - if ( path.endsWith( ".zip", Qt::CaseInsensitive ) || - path.endsWith( ".tar", Qt::CaseInsensitive ) ) + if ( path.endsWith( QLatin1String( ".zip" ), Qt::CaseInsensitive ) || + path.endsWith( QLatin1String( ".tar" ), Qt::CaseInsensitive ) ) { zipFileList = zipItem->getZipFileList(); } @@ -1506,8 +1506,8 @@ QgsDataItem* QgsZipItem::itemFromPath( QgsDataItem* parent, const QString& fileP // try first with normal path (Passthru) // this is to simplify .qml handling, and without this some tests will fail // (e.g. testZipItemVectorTransparency(), second test) - if (( mProviderNames.at( i ) == "ogr" ) || - ( mProviderNames.at( i ) == "gdal" && zipFileCount == 1 ) ) + if (( mProviderNames.at( i ) == QLatin1String( "ogr" ) ) || + ( mProviderNames.at( i ) == QLatin1String( "gdal" ) && zipFileCount == 1 ) ) item = dataItem( filePath, parent ); // try with /vsizip/ if ( ! item ) @@ -1528,12 +1528,12 @@ const QStringList &QgsZipItem::getZipFileList() QString tmpPath; QSettings settings; - QString scanZipSetting = settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString(); + QString scanZipSetting = settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString(); QgsDebugMsgLevel( QString( "mFilePath = %1 name= %2 scanZipSetting= %3 vsiPrefix= %4" ).arg( mFilePath, name(), scanZipSetting, mVsiPrefix ), 3 ); // if scanZipBrowser == no: skip to the next file - if ( scanZipSetting == "no" ) + if ( scanZipSetting == QLatin1String( "no" ) ) { return mZipFileList; } @@ -1548,7 +1548,7 @@ const QStringList &QgsZipItem::getZipFileList() tmpPath = papszSiblingFiles[i]; QgsDebugMsgLevel( QString( "Read file %1" ).arg( tmpPath ), 3 ); // skip directories (files ending with /) - if ( tmpPath.right( 1 ) != "/" ) + if ( tmpPath.right( 1 ) != QLatin1String( "/" ) ) mZipFileList << tmpPath; } CSLDestroy( papszSiblingFiles ); diff --git a/src/core/qgsdataprovider.h b/src/core/qgsdataprovider.h index 256b5a6488b5..e682f03873ca 100644 --- a/src/core/qgsdataprovider.h +++ b/src/core/qgsdataprovider.h @@ -74,7 +74,10 @@ class CORE_EXPORT QgsDataProvider : public QObject CustomData = 3000 //!< Custom properties for 3rd party providers or very provider-specific properties which are not expected to be of interest for other providers can be added starting from this value up. }; - QgsDataProvider( QString const & uri = "" ) + /** + * Constructor for QgsDataProvider. + */ + QgsDataProvider( QString const & uri = QLatin1String( "" ) ) : mDataSourceURI( uri ) {} @@ -112,7 +115,7 @@ class CORE_EXPORT QgsDataProvider : public QObject */ virtual QString dataSourceUri( bool expandAuthConfig = false ) const { - if ( expandAuthConfig && mDataSourceURI.contains( "authcfg" ) ) + if ( expandAuthConfig && mDataSourceURI.contains( QLatin1String( "authcfg" ) ) ) { QgsDataSourceUri uri( mDataSourceURI ); return uri.uri( expandAuthConfig ); @@ -284,7 +287,7 @@ class CORE_EXPORT QgsDataProvider : public QObject */ virtual QString fileVectorFilters() const { - return ""; + return QLatin1String( "" ); } @@ -299,7 +302,7 @@ class CORE_EXPORT QgsDataProvider : public QObject */ virtual QString fileRasterFilters() const { - return ""; + return QLatin1String( "" ); } /** Reloads the data from the source. Needs to be implemented by providers with data caches to diff --git a/src/core/qgsdatasourceuri.cpp b/src/core/qgsdatasourceuri.cpp index 854f7bac747c..ec81c21f56a4 100644 --- a/src/core/qgsdatasourceuri.cpp +++ b/src/core/qgsdatasourceuri.cpp @@ -27,7 +27,7 @@ QgsDataSourceUri::QgsDataSourceUri() : mSSLmode( SslPrefer ) - , mKeyColumn( "" ) + , mKeyColumn( QLatin1String( "" ) ) , mUseEstimatedMetadata( false ) , mSelectAtIdDisabled( false ) , mWkbType( QgsWkbTypes::Unknown ) @@ -37,7 +37,7 @@ QgsDataSourceUri::QgsDataSourceUri() QgsDataSourceUri::QgsDataSourceUri( QString uri ) : mSSLmode( SslPrefer ) - , mKeyColumn( "" ) + , mKeyColumn( QLatin1String( "" ) ) , mUseEstimatedMetadata( false ) , mSelectAtIdDisabled( false ) , mWkbType( QgsWkbTypes::Unknown ) @@ -71,7 +71,7 @@ QgsDataSourceUri::QgsDataSourceUri( QString uri ) i++; - if ( pname == "sql" ) + if ( pname == QLatin1String( "sql" ) ) { // rest of line is a sql where clause skipBlanks( uri, i ); @@ -82,7 +82,7 @@ QgsDataSourceUri::QgsDataSourceUri( QString uri ) { QString pval = getValue( uri, i ); - if ( pname == "table" ) + if ( pname == QLatin1String( "table" ) ) { if ( uri[i] == '.' ) { @@ -93,7 +93,7 @@ QgsDataSourceUri::QgsDataSourceUri( QString uri ) } else { - mSchema = ""; + mSchema = QLatin1String( "" ); mTable = pval; } @@ -115,8 +115,8 @@ QgsDataSourceUri::QgsDataSourceUri( QString uri ) } mGeometryColumn = uri.mid( start, i - start ); - mGeometryColumn.replace( "\\)", ")" ); - mGeometryColumn.replace( "\\\\", "\\" ); + mGeometryColumn.replace( QLatin1String( "\\)" ), QLatin1String( ")" ) ); + mGeometryColumn.replace( QLatin1String( "\\\\" ), QLatin1String( "\\" ) ); i++; } @@ -125,101 +125,101 @@ QgsDataSourceUri::QgsDataSourceUri( QString uri ) mGeometryColumn = QString::null; } } - else if ( pname == "key" ) + else if ( pname == QLatin1String( "key" ) ) { mKeyColumn = pval; } - else if ( pname == "estimatedmetadata" ) + else if ( pname == QLatin1String( "estimatedmetadata" ) ) { - mUseEstimatedMetadata = pval == "true"; + mUseEstimatedMetadata = pval == QLatin1String( "true" ); } - else if ( pname == "srid" ) + else if ( pname == QLatin1String( "srid" ) ) { mSrid = pval; } - else if ( pname == "type" ) + else if ( pname == QLatin1String( "type" ) ) { mWkbType = QgsWkbTypes::parseType( pval ); } - else if ( pname == "selectatid" ) + else if ( pname == QLatin1String( "selectatid" ) ) { - mSelectAtIdDisabled = pval == "false"; + mSelectAtIdDisabled = pval == QLatin1String( "false" ); } - else if ( pname == "service" ) + else if ( pname == QLatin1String( "service" ) ) { mService = pval; } - else if ( pname == "authcfg" ) + else if ( pname == QLatin1String( "authcfg" ) ) { mAuthConfigId = pval; } - else if ( pname == "user" ) + else if ( pname == QLatin1String( "user" ) ) { mUsername = pval; } - else if ( pname == "password" ) + else if ( pname == QLatin1String( "password" ) ) { mPassword = pval; } - else if ( pname == "connect_timeout" ) + else if ( pname == QLatin1String( "connect_timeout" ) ) { QgsDebugMsg( "connection timeout ignored" ); } - else if ( pname == "dbname" ) + else if ( pname == QLatin1String( "dbname" ) ) { mDatabase = pval; } - else if ( pname == "host" ) + else if ( pname == QLatin1String( "host" ) ) { mHost = pval; } - else if ( pname == "hostaddr" ) + else if ( pname == QLatin1String( "hostaddr" ) ) { QgsDebugMsg( "database host ip address ignored" ); } - else if ( pname == "port" ) + else if ( pname == QLatin1String( "port" ) ) { mPort = pval; } - else if ( pname == "driver" ) + else if ( pname == QLatin1String( "driver" ) ) { mDriver = pval; } - else if ( pname == "tty" ) + else if ( pname == QLatin1String( "tty" ) ) { QgsDebugMsg( "backend debug tty ignored" ); } - else if ( pname == "options" ) + else if ( pname == QLatin1String( "options" ) ) { QgsDebugMsg( "backend debug options ignored" ); } - else if ( pname == "sslmode" ) + else if ( pname == QLatin1String( "sslmode" ) ) { - if ( pval == "disable" ) + if ( pval == QLatin1String( "disable" ) ) mSSLmode = SslDisable; - else if ( pval == "allow" ) + else if ( pval == QLatin1String( "allow" ) ) mSSLmode = SslAllow; - else if ( pval == "prefer" ) + else if ( pval == QLatin1String( "prefer" ) ) mSSLmode = SslPrefer; - else if ( pval == "require" ) + else if ( pval == QLatin1String( "require" ) ) mSSLmode = SslRequire; - else if ( pval == "verify-ca" ) + else if ( pval == QLatin1String( "verify-ca" ) ) mSSLmode = SslVerifyCa; - else if ( pval == "verify-full" ) + else if ( pval == QLatin1String( "verify-full" ) ) mSSLmode = SslVerifyFull; } - else if ( pname == "requiressl" ) + else if ( pname == QLatin1String( "requiressl" ) ) { - if ( pval == "0" ) + if ( pval == QLatin1String( "0" ) ) mSSLmode = SslDisable; else mSSLmode = SslPrefer; } - else if ( pname == "krbsrvname" ) + else if ( pname == QLatin1String( "krbsrvname" ) ) { QgsDebugMsg( "kerberos server name ignored" ); } - else if ( pname == "gsslib" ) + else if ( pname == QLatin1String( "gsslib" ) ) { QgsDebugMsg( "gsslib ignored" ); } @@ -237,28 +237,28 @@ QString QgsDataSourceUri::removePassword( const QString& aUri ) QRegExp regexp; regexp.setMinimal( true ); QString safeName( aUri ); - if ( aUri.contains( " password=" ) ) + if ( aUri.contains( QLatin1String( " password=" ) ) ) { - regexp.setPattern( " password=.* " ); - safeName.replace( regexp, " " ); + regexp.setPattern( QStringLiteral( " password=.* " ) ); + safeName.replace( regexp, QStringLiteral( " " ) ); } - else if ( aUri.contains( ",password=" ) ) + else if ( aUri.contains( QLatin1String( ",password=" ) ) ) { - regexp.setPattern( ",password=.*," ); - safeName.replace( regexp, "," ); + regexp.setPattern( QStringLiteral( ",password=.*," ) ); + safeName.replace( regexp, QStringLiteral( "," ) ); } - else if ( aUri.contains( "IDB:" ) ) + else if ( aUri.contains( QLatin1String( "IDB:" ) ) ) { - regexp.setPattern( " pass=.* " ); - safeName.replace( regexp, " " ); + regexp.setPattern( QStringLiteral( " pass=.* " ) ); + safeName.replace( regexp, QStringLiteral( " " ) ); } - else if (( aUri.contains( "OCI:" ) ) - || ( aUri.contains( "ODBC:" ) ) ) + else if (( aUri.contains( QLatin1String( "OCI:" ) ) ) + || ( aUri.contains( QLatin1String( "ODBC:" ) ) ) ) { - regexp.setPattern( "/.*@" ); - safeName.replace( regexp, "/@" ); + regexp.setPattern( QStringLiteral( "/.*@" ) ); + safeName.replace( regexp, QStringLiteral( "/@" ) ); } - else if ( aUri.contains( "SDE:" ) ) + else if ( aUri.contains( QLatin1String( "SDE:" ) ) ) { QStringList strlist = aUri.split( ',' ); safeName = strlist[0] + ',' + strlist[1] + ',' + strlist[2] + ',' + strlist[3]; @@ -386,7 +386,7 @@ void QgsDataSourceUri::setSql( const QString& sql ) void QgsDataSourceUri::clearSchema() { - mSchema = ""; + mSchema = QLatin1String( "" ); } void QgsDataSourceUri::setSchema( const QString& schema ) @@ -398,8 +398,8 @@ QString QgsDataSourceUri::escape( const QString &theVal, QChar delim = '\'' ) co { QString val = theVal; - val.replace( '\\', "\\\\" ); - val.replace( delim, QString( "\\%1" ).arg( delim ) ); + val.replace( '\\', QLatin1String( "\\\\" ) ); + val.replace( delim, QStringLiteral( "\\%1" ).arg( delim ) ); return val; } @@ -482,55 +482,55 @@ QString QgsDataSourceUri::connectionInfo( bool expandAuthConfig ) const { QStringList connectionItems; - if ( mDatabase != "" ) + if ( mDatabase != QLatin1String( "" ) ) { connectionItems << "dbname='" + escape( mDatabase ) + '\''; } - if ( mService != "" ) + if ( mService != QLatin1String( "" ) ) { connectionItems << "service='" + escape( mService ) + '\''; } - else if ( mHost != "" ) + else if ( mHost != QLatin1String( "" ) ) { connectionItems << "host=" + mHost; } if ( mService.isEmpty() ) { - if ( mPort != "" ) + if ( mPort != QLatin1String( "" ) ) connectionItems << "port=" + mPort; } - if ( mDriver != "" ) + if ( mDriver != QLatin1String( "" ) ) { connectionItems << "driver='" + escape( mDriver ) + '\''; } - if ( mUsername != "" ) + if ( mUsername != QLatin1String( "" ) ) { connectionItems << "user='" + escape( mUsername ) + '\''; - if ( mPassword != "" ) + if ( mPassword != QLatin1String( "" ) ) { connectionItems << "password='" + escape( mPassword ) + '\''; } } if ( mSSLmode == SslDisable ) - connectionItems << "sslmode=disable"; + connectionItems << QStringLiteral( "sslmode=disable" ); else if ( mSSLmode == SslAllow ) - connectionItems << "sslmode=allow"; + connectionItems << QStringLiteral( "sslmode=allow" ); else if ( mSSLmode == SslRequire ) - connectionItems << "sslmode=require"; + connectionItems << QStringLiteral( "sslmode=require" ); #if 0 else if ( mSSLmode == SSLprefer ) // no need to output the default connectionItems << "sslmode=prefer"; #endif else if ( mSSLmode == SslVerifyCa ) - connectionItems << "sslmode=verify-ca"; + connectionItems << QStringLiteral( "sslmode=verify-ca" ); else if ( mSSLmode == SslVerifyFull ) - connectionItems << "sslmode=verify-full"; + connectionItems << QStringLiteral( "sslmode=verify-full" ); if ( !mAuthConfigId.isEmpty() ) { @@ -547,7 +547,7 @@ QString QgsDataSourceUri::connectionInfo( bool expandAuthConfig ) const } } - return connectionItems.join( " " ); + return connectionItems.join( QStringLiteral( " " ) ); } QString QgsDataSourceUri::uri( bool expandAuthConfig ) const @@ -556,28 +556,28 @@ QString QgsDataSourceUri::uri( bool expandAuthConfig ) const if ( !mKeyColumn.isEmpty() ) { - theUri += QString( " key='%1'" ).arg( escape( mKeyColumn ) ); + theUri += QStringLiteral( " key='%1'" ).arg( escape( mKeyColumn ) ); } if ( mUseEstimatedMetadata ) { - theUri += QString( " estimatedmetadata=true" ); + theUri += QStringLiteral( " estimatedmetadata=true" ); } if ( !mSrid.isEmpty() ) { - theUri += QString( " srid=%1" ).arg( mSrid ); + theUri += QStringLiteral( " srid=%1" ).arg( mSrid ); } if ( mWkbType != QgsWkbTypes::Unknown && mWkbType != QgsWkbTypes::NoGeometry ) { - theUri += " type="; + theUri += QLatin1String( " type=" ); theUri += QgsWkbTypes::displayString( mWkbType ); } if ( mSelectAtIdDisabled ) { - theUri += QString( " selectatid=false" ); + theUri += QStringLiteral( " selectatid=false" ); } for ( QMap::const_iterator it = mParams.begin(); it != mParams.end(); ++it ) @@ -592,12 +592,12 @@ QString QgsDataSourceUri::uri( bool expandAuthConfig ) const } QString columnName( mGeometryColumn ); - columnName.replace( '\\', "\\\\" ); - columnName.replace( ')', "\\)" ); + columnName.replace( '\\', QLatin1String( "\\\\" ) ); + columnName.replace( ')', QLatin1String( "\\)" ) ); - theUri += QString( " table=%1%2 sql=%3" ) + theUri += QStringLiteral( " table=%1%2 sql=%3" ) .arg( quotedTablename(), - mGeometryColumn.isNull() ? QString() : QString( " (%1)" ).arg( columnName ), + mGeometryColumn.isNull() ? QString() : QStringLiteral( " (%1)" ).arg( columnName ), mSql ); return theUri; @@ -636,11 +636,11 @@ void QgsDataSourceUri::setEncodedUri( const QString & uri ) QString QgsDataSourceUri::quotedTablename() const { if ( !mSchema.isEmpty() ) - return QString( "\"%1\".\"%2\"" ) + return QStringLiteral( "\"%1\".\"%2\"" ) .arg( escape( mSchema, '"' ), escape( mTable, '"' ) ); else - return QString( "\"%1\"" ) + return QStringLiteral( "\"%1\"" ) .arg( escape( mTable, '"' ) ); } diff --git a/src/core/qgsdatumtransformstore.cpp b/src/core/qgsdatumtransformstore.cpp index f4d26f778514..311d2c6ad874 100644 --- a/src/core/qgsdatumtransformstore.cpp +++ b/src/core/qgsdatumtransformstore.cpp @@ -78,25 +78,25 @@ void QgsDatumTransformStore::readXml( const QDomNode& parentNode ) { clear(); - QDomElement layerCoordTransformInfoElem = parentNode.firstChildElement( "layer_coordinate_transform_info" ); + QDomElement layerCoordTransformInfoElem = parentNode.firstChildElement( QStringLiteral( "layer_coordinate_transform_info" ) ); if ( !layerCoordTransformInfoElem.isNull() ) { - QDomNodeList layerCoordinateTransformList = layerCoordTransformInfoElem.elementsByTagName( "layer_coordinate_transform" ); + QDomNodeList layerCoordinateTransformList = layerCoordTransformInfoElem.elementsByTagName( QStringLiteral( "layer_coordinate_transform" ) ); QDomElement layerCoordTransformElem; for ( int i = 0; i < layerCoordinateTransformList.size(); ++i ) { layerCoordTransformElem = layerCoordinateTransformList.at( i ).toElement(); - QString layerId = layerCoordTransformElem.attribute( "layerid" ); + QString layerId = layerCoordTransformElem.attribute( QStringLiteral( "layerid" ) ); if ( layerId.isEmpty() ) { continue; } addEntry( layerId, - layerCoordTransformElem.attribute( "srcAuthId" ), - layerCoordTransformElem.attribute( "destAuthId" ), - layerCoordTransformElem.attribute( "srcDatumTransform", "-1" ).toInt(), - layerCoordTransformElem.attribute( "destDatumTransform", "-1" ).toInt() + layerCoordTransformElem.attribute( QStringLiteral( "srcAuthId" ) ), + layerCoordTransformElem.attribute( QStringLiteral( "destAuthId" ) ), + layerCoordTransformElem.attribute( QStringLiteral( "srcDatumTransform" ), QStringLiteral( "-1" ) ).toInt(), + layerCoordTransformElem.attribute( QStringLiteral( "destDatumTransform" ), QStringLiteral( "-1" ) ).toInt() ); } } @@ -105,16 +105,16 @@ void QgsDatumTransformStore::readXml( const QDomNode& parentNode ) void QgsDatumTransformStore::writeXml( QDomNode& parentNode, QDomDocument& theDoc ) const { // layer coordinate transform infos - QDomElement layerCoordTransformInfo = theDoc.createElement( "layer_coordinate_transform_info" ); + QDomElement layerCoordTransformInfo = theDoc.createElement( QStringLiteral( "layer_coordinate_transform_info" ) ); for ( QHash< QString, Entry >::const_iterator coordIt = mEntries.constBegin(); coordIt != mEntries.constEnd(); ++coordIt ) { - QDomElement layerCoordTransformElem = theDoc.createElement( "layer_coordinate_transform" ); - layerCoordTransformElem.setAttribute( "layerid", coordIt.key() ); - layerCoordTransformElem.setAttribute( "srcAuthId", coordIt->srcAuthId ); - layerCoordTransformElem.setAttribute( "destAuthId", coordIt->destAuthId ); - layerCoordTransformElem.setAttribute( "srcDatumTransform", QString::number( coordIt->srcDatumTransform ) ); - layerCoordTransformElem.setAttribute( "destDatumTransform", QString::number( coordIt->destDatumTransform ) ); + QDomElement layerCoordTransformElem = theDoc.createElement( QStringLiteral( "layer_coordinate_transform" ) ); + layerCoordTransformElem.setAttribute( QStringLiteral( "layerid" ), coordIt.key() ); + layerCoordTransformElem.setAttribute( QStringLiteral( "srcAuthId" ), coordIt->srcAuthId ); + layerCoordTransformElem.setAttribute( QStringLiteral( "destAuthId" ), coordIt->destAuthId ); + layerCoordTransformElem.setAttribute( QStringLiteral( "srcDatumTransform" ), QString::number( coordIt->srcDatumTransform ) ); + layerCoordTransformElem.setAttribute( QStringLiteral( "destDatumTransform" ), QString::number( coordIt->destDatumTransform ) ); layerCoordTransformInfo.appendChild( layerCoordTransformElem ); } parentNode.appendChild( layerCoordTransformInfo ); diff --git a/src/core/qgsdiagramrenderer.cpp b/src/core/qgsdiagramrenderer.cpp index 2c4cda6185be..b23d34d2b425 100644 --- a/src/core/qgsdiagramrenderer.cpp +++ b/src/core/qgsdiagramrenderer.cpp @@ -104,33 +104,33 @@ void QgsDiagramLayerSettings::readXml( const QDomElement& elem, const QgsVectorL { Q_UNUSED( layer ) - placement = static_cast< Placement >( elem.attribute( "placement" ).toInt() ); - placementFlags = static_cast< LinePlacementFlags >( elem.attribute( "linePlacementFlags" ).toInt() ); - priority = elem.attribute( "priority" ).toInt(); - zIndex = elem.attribute( "zIndex" ).toDouble(); - obstacle = elem.attribute( "obstacle" ).toInt(); - dist = elem.attribute( "dist" ).toDouble(); - xPosColumn = elem.attribute( "xPosColumn" ).toInt(); - yPosColumn = elem.attribute( "yPosColumn" ).toInt(); - showColumn = elem.attribute( "showColumn" ).toInt(); - showAll = ( elem.attribute( "showAll", "0" ) != "0" ); + placement = static_cast< Placement >( elem.attribute( QStringLiteral( "placement" ) ).toInt() ); + placementFlags = static_cast< LinePlacementFlags >( elem.attribute( QStringLiteral( "linePlacementFlags" ) ).toInt() ); + priority = elem.attribute( QStringLiteral( "priority" ) ).toInt(); + zIndex = elem.attribute( QStringLiteral( "zIndex" ) ).toDouble(); + obstacle = elem.attribute( QStringLiteral( "obstacle" ) ).toInt(); + dist = elem.attribute( QStringLiteral( "dist" ) ).toDouble(); + xPosColumn = elem.attribute( QStringLiteral( "xPosColumn" ) ).toInt(); + yPosColumn = elem.attribute( QStringLiteral( "yPosColumn" ) ).toInt(); + showColumn = elem.attribute( QStringLiteral( "showColumn" ) ).toInt(); + showAll = ( elem.attribute( QStringLiteral( "showAll" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); } void QgsDiagramLayerSettings::writeXml( QDomElement& layerElem, QDomDocument& doc, const QgsVectorLayer* layer ) const { Q_UNUSED( layer ) - QDomElement diagramLayerElem = doc.createElement( "DiagramLayerSettings" ); - diagramLayerElem.setAttribute( "placement", placement ); - diagramLayerElem.setAttribute( "linePlacementFlags", placementFlags ); - diagramLayerElem.setAttribute( "priority", priority ); - diagramLayerElem.setAttribute( "zIndex", zIndex ); - diagramLayerElem.setAttribute( "obstacle", obstacle ); - diagramLayerElem.setAttribute( "dist", QString::number( dist ) ); - diagramLayerElem.setAttribute( "xPosColumn", xPosColumn ); - diagramLayerElem.setAttribute( "yPosColumn", yPosColumn ); - diagramLayerElem.setAttribute( "showColumn", showColumn ); - diagramLayerElem.setAttribute( "showAll", showAll ); + QDomElement diagramLayerElem = doc.createElement( QStringLiteral( "DiagramLayerSettings" ) ); + diagramLayerElem.setAttribute( QStringLiteral( "placement" ), placement ); + diagramLayerElem.setAttribute( QStringLiteral( "linePlacementFlags" ), placementFlags ); + diagramLayerElem.setAttribute( QStringLiteral( "priority" ), priority ); + diagramLayerElem.setAttribute( QStringLiteral( "zIndex" ), zIndex ); + diagramLayerElem.setAttribute( QStringLiteral( "obstacle" ), obstacle ); + diagramLayerElem.setAttribute( QStringLiteral( "dist" ), QString::number( dist ) ); + diagramLayerElem.setAttribute( QStringLiteral( "xPosColumn" ), xPosColumn ); + diagramLayerElem.setAttribute( QStringLiteral( "yPosColumn" ), yPosColumn ); + diagramLayerElem.setAttribute( QStringLiteral( "showColumn" ), showColumn ); + diagramLayerElem.setAttribute( QStringLiteral( "showAll" ), showAll ); layerElem.appendChild( diagramLayerElem ); } @@ -157,26 +157,26 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* { Q_UNUSED( layer ); - enabled = ( elem.attribute( "enabled", "1" ) != "0" ); - if ( !QgsFontUtils::setFromXmlChildNode( font, elem, "fontProperties" ) ) + enabled = ( elem.attribute( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); + if ( !QgsFontUtils::setFromXmlChildNode( font, elem, QStringLiteral( "fontProperties" ) ) ) { - font.fromString( elem.attribute( "font" ) ); + font.fromString( elem.attribute( QStringLiteral( "font" ) ) ); } - backgroundColor.setNamedColor( elem.attribute( "backgroundColor" ) ); - backgroundColor.setAlpha( elem.attribute( "backgroundAlpha" ).toInt() ); - size.setWidth( elem.attribute( "width" ).toDouble() ); - size.setHeight( elem.attribute( "height" ).toDouble() ); - transparency = elem.attribute( "transparency", "0" ).toInt(); - penColor.setNamedColor( elem.attribute( "penColor" ) ); - int penAlpha = elem.attribute( "penAlpha", "255" ).toInt(); + backgroundColor.setNamedColor( elem.attribute( QStringLiteral( "backgroundColor" ) ) ); + backgroundColor.setAlpha( elem.attribute( QStringLiteral( "backgroundAlpha" ) ).toInt() ); + size.setWidth( elem.attribute( QStringLiteral( "width" ) ).toDouble() ); + size.setHeight( elem.attribute( QStringLiteral( "height" ) ).toDouble() ); + transparency = elem.attribute( QStringLiteral( "transparency" ), QStringLiteral( "0" ) ).toInt(); + penColor.setNamedColor( elem.attribute( QStringLiteral( "penColor" ) ) ); + int penAlpha = elem.attribute( QStringLiteral( "penAlpha" ), QStringLiteral( "255" ) ).toInt(); penColor.setAlpha( penAlpha ); - penWidth = elem.attribute( "penWidth" ).toDouble(); + penWidth = elem.attribute( QStringLiteral( "penWidth" ) ).toDouble(); - minScaleDenominator = elem.attribute( "minScaleDenominator", "-1" ).toDouble(); - maxScaleDenominator = elem.attribute( "maxScaleDenominator", "-1" ).toDouble(); - if ( elem.hasAttribute( "scaleBasedVisibility" ) ) + minScaleDenominator = elem.attribute( QStringLiteral( "minScaleDenominator" ), QStringLiteral( "-1" ) ).toDouble(); + maxScaleDenominator = elem.attribute( QStringLiteral( "maxScaleDenominator" ), QStringLiteral( "-1" ) ).toDouble(); + if ( elem.hasAttribute( QStringLiteral( "scaleBasedVisibility" ) ) ) { - scaleBasedVisibility = ( elem.attribute( "scaleBasedVisibility", "1" ) != "0" ); + scaleBasedVisibility = ( elem.attribute( QStringLiteral( "scaleBasedVisibility" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); } else { @@ -184,23 +184,23 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* } //diagram size unit type and scale - if ( elem.attribute( "sizeType" ) == "MapUnits" ) + if ( elem.attribute( QStringLiteral( "sizeType" ) ) == QLatin1String( "MapUnits" ) ) { //compatibility with pre-2.16 project files sizeType = QgsUnitTypes::RenderMapUnits; } else { - sizeType = QgsUnitTypes::decodeRenderUnit( elem.attribute( "sizeType" ) ); + sizeType = QgsUnitTypes::decodeRenderUnit( elem.attribute( QStringLiteral( "sizeType" ) ) ); } - sizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( "sizeScale" ) ); + sizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( QStringLiteral( "sizeScale" ) ) ); //line width unit type and scale - lineSizeUnit = QgsUnitTypes::decodeRenderUnit( elem.attribute( "lineSizeType" ) ); - lineSizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( "lineSizeScale" ) ); + lineSizeUnit = QgsUnitTypes::decodeRenderUnit( elem.attribute( QStringLiteral( "lineSizeType" ) ) ); + lineSizeScale = QgsSymbolLayerUtils::decodeMapUnitScale( elem.attribute( QStringLiteral( "lineSizeScale" ) ) ); //label placement method - if ( elem.attribute( "labelPlacementMethod" ) == "Height" ) + if ( elem.attribute( QStringLiteral( "labelPlacementMethod" ) ) == QLatin1String( "Height" ) ) { labelPlacementMethod = Height; } @@ -210,15 +210,15 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* } // orientation - if ( elem.attribute( "diagramOrientation" ) == "Left" ) + if ( elem.attribute( QStringLiteral( "diagramOrientation" ) ) == QLatin1String( "Left" ) ) { diagramOrientation = Left; } - else if ( elem.attribute( "diagramOrientation" ) == "Right" ) + else if ( elem.attribute( QStringLiteral( "diagramOrientation" ) ) == QLatin1String( "Right" ) ) { diagramOrientation = Right; } - else if ( elem.attribute( "diagramOrientation" ) == "Down" ) + else if ( elem.attribute( QStringLiteral( "diagramOrientation" ) ) == QLatin1String( "Down" ) ) { diagramOrientation = Down; } @@ -228,7 +228,7 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* } // scale dependency - if ( elem.attribute( "scaleDependency" ) == "Diameter" ) + if ( elem.attribute( QStringLiteral( "scaleDependency" ) ) == QLatin1String( "Diameter" ) ) { scaleByArea = false; } @@ -237,26 +237,26 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* scaleByArea = true; } - barWidth = elem.attribute( "barWidth" ).toDouble(); + barWidth = elem.attribute( QStringLiteral( "barWidth" ) ).toDouble(); - angleOffset = elem.attribute( "angleOffset" ).toInt(); + angleOffset = elem.attribute( QStringLiteral( "angleOffset" ) ).toInt(); - minimumSize = elem.attribute( "minimumSize" ).toDouble(); + minimumSize = elem.attribute( QStringLiteral( "minimumSize" ) ).toDouble(); //colors categoryColors.clear(); - QDomNodeList attributes = elem.elementsByTagName( "attribute" ); + QDomNodeList attributes = elem.elementsByTagName( QStringLiteral( "attribute" ) ); if ( attributes.length() > 0 ) { for ( int i = 0; i < attributes.size(); i++ ) { QDomElement attrElem = attributes.at( i ).toElement(); - QColor newColor( attrElem.attribute( "color" ) ); + QColor newColor( attrElem.attribute( QStringLiteral( "color" ) ) ); newColor.setAlpha( 255 - transparency ); categoryColors.append( newColor ); - categoryAttributes.append( attrElem.attribute( "field" ) ); - categoryLabels.append( attrElem.attribute( "label" ) ); + categoryAttributes.append( attrElem.attribute( QStringLiteral( "field" ) ) ); + categoryLabels.append( attrElem.attribute( QStringLiteral( "label" ) ) ); if ( categoryLabels.back().isEmpty() ) { categoryLabels.back() = categoryAttributes.back(); @@ -267,7 +267,7 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* { // Restore old format attributes and colors - QStringList colorList = elem.attribute( "colors" ).split( '/' ); + QStringList colorList = elem.attribute( QStringLiteral( "colors" ) ).split( '/' ); QStringList::const_iterator colorIt = colorList.constBegin(); for ( ; colorIt != colorList.constEnd(); ++colorIt ) { @@ -278,7 +278,7 @@ void QgsDiagramSettings::readXml( const QDomElement& elem, const QgsVectorLayer* //attribute indices categoryAttributes.clear(); - QStringList catList = elem.attribute( "categories" ).split( '/' ); + QStringList catList = elem.attribute( QStringLiteral( "categories" ) ).split( '/' ); QStringList::const_iterator catIt = catList.constBegin(); for ( ; catIt != catList.constEnd(); ++catIt ) { @@ -292,84 +292,84 @@ void QgsDiagramSettings::writeXml( QDomElement& rendererElem, QDomDocument& doc, { Q_UNUSED( layer ); - QDomElement categoryElem = doc.createElement( "DiagramCategory" ); - categoryElem.setAttribute( "enabled", enabled ); - categoryElem.appendChild( QgsFontUtils::toXmlElement( font, doc, "fontProperties" ) ); - categoryElem.setAttribute( "backgroundColor", backgroundColor.name() ); - categoryElem.setAttribute( "backgroundAlpha", backgroundColor.alpha() ); - categoryElem.setAttribute( "width", QString::number( size.width() ) ); - categoryElem.setAttribute( "height", QString::number( size.height() ) ); - categoryElem.setAttribute( "penColor", penColor.name() ); - categoryElem.setAttribute( "penAlpha", penColor.alpha() ); - categoryElem.setAttribute( "penWidth", QString::number( penWidth ) ); - categoryElem.setAttribute( "scaleBasedVisibility", scaleBasedVisibility ); - categoryElem.setAttribute( "minScaleDenominator", QString::number( minScaleDenominator ) ); - categoryElem.setAttribute( "maxScaleDenominator", QString::number( maxScaleDenominator ) ); - categoryElem.setAttribute( "transparency", QString::number( transparency ) ); + QDomElement categoryElem = doc.createElement( QStringLiteral( "DiagramCategory" ) ); + categoryElem.setAttribute( QStringLiteral( "enabled" ), enabled ); + categoryElem.appendChild( QgsFontUtils::toXmlElement( font, doc, QStringLiteral( "fontProperties" ) ) ); + categoryElem.setAttribute( QStringLiteral( "backgroundColor" ), backgroundColor.name() ); + categoryElem.setAttribute( QStringLiteral( "backgroundAlpha" ), backgroundColor.alpha() ); + categoryElem.setAttribute( QStringLiteral( "width" ), QString::number( size.width() ) ); + categoryElem.setAttribute( QStringLiteral( "height" ), QString::number( size.height() ) ); + categoryElem.setAttribute( QStringLiteral( "penColor" ), penColor.name() ); + categoryElem.setAttribute( QStringLiteral( "penAlpha" ), penColor.alpha() ); + categoryElem.setAttribute( QStringLiteral( "penWidth" ), QString::number( penWidth ) ); + categoryElem.setAttribute( QStringLiteral( "scaleBasedVisibility" ), scaleBasedVisibility ); + categoryElem.setAttribute( QStringLiteral( "minScaleDenominator" ), QString::number( minScaleDenominator ) ); + categoryElem.setAttribute( QStringLiteral( "maxScaleDenominator" ), QString::number( maxScaleDenominator ) ); + categoryElem.setAttribute( QStringLiteral( "transparency" ), QString::number( transparency ) ); //diagram size unit type and scale - categoryElem.setAttribute( "sizeType", QgsUnitTypes::encodeUnit( sizeType ) ); - categoryElem.setAttribute( "sizeScale", QgsSymbolLayerUtils::encodeMapUnitScale( sizeScale ) ); + categoryElem.setAttribute( QStringLiteral( "sizeType" ), QgsUnitTypes::encodeUnit( sizeType ) ); + categoryElem.setAttribute( QStringLiteral( "sizeScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( sizeScale ) ); //line width unit type and scale - categoryElem.setAttribute( "lineSizeType", QgsUnitTypes::encodeUnit( lineSizeUnit ) ); - categoryElem.setAttribute( "lineSizeScale", QgsSymbolLayerUtils::encodeMapUnitScale( lineSizeScale ) ); + categoryElem.setAttribute( QStringLiteral( "lineSizeType" ), QgsUnitTypes::encodeUnit( lineSizeUnit ) ); + categoryElem.setAttribute( QStringLiteral( "lineSizeScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( lineSizeScale ) ); // label placement method (text diagram) if ( labelPlacementMethod == Height ) { - categoryElem.setAttribute( "labelPlacementMethod", "Height" ); + categoryElem.setAttribute( QStringLiteral( "labelPlacementMethod" ), QStringLiteral( "Height" ) ); } else { - categoryElem.setAttribute( "labelPlacementMethod", "XHeight" ); + categoryElem.setAttribute( QStringLiteral( "labelPlacementMethod" ), QStringLiteral( "XHeight" ) ); } if ( scaleByArea ) { - categoryElem.setAttribute( "scaleDependency", "Area" ); + categoryElem.setAttribute( QStringLiteral( "scaleDependency" ), QStringLiteral( "Area" ) ); } else { - categoryElem.setAttribute( "scaleDependency", "Diameter" ); + categoryElem.setAttribute( QStringLiteral( "scaleDependency" ), QStringLiteral( "Diameter" ) ); } // orientation (histogram) switch ( diagramOrientation ) { case Left: - categoryElem.setAttribute( "diagramOrientation", "Left" ); + categoryElem.setAttribute( QStringLiteral( "diagramOrientation" ), QStringLiteral( "Left" ) ); break; case Right: - categoryElem.setAttribute( "diagramOrientation", "Right" ); + categoryElem.setAttribute( QStringLiteral( "diagramOrientation" ), QStringLiteral( "Right" ) ); break; case Down: - categoryElem.setAttribute( "diagramOrientation", "Down" ); + categoryElem.setAttribute( QStringLiteral( "diagramOrientation" ), QStringLiteral( "Down" ) ); break; case Up: - categoryElem.setAttribute( "diagramOrientation", "Up" ); + categoryElem.setAttribute( QStringLiteral( "diagramOrientation" ), QStringLiteral( "Up" ) ); break; default: - categoryElem.setAttribute( "diagramOrientation", "Up" ); + categoryElem.setAttribute( QStringLiteral( "diagramOrientation" ), QStringLiteral( "Up" ) ); break; } - categoryElem.setAttribute( "barWidth", QString::number( barWidth ) ); - categoryElem.setAttribute( "minimumSize", QString::number( minimumSize ) ); - categoryElem.setAttribute( "angleOffset", QString::number( angleOffset ) ); + categoryElem.setAttribute( QStringLiteral( "barWidth" ), QString::number( barWidth ) ); + categoryElem.setAttribute( QStringLiteral( "minimumSize" ), QString::number( minimumSize ) ); + categoryElem.setAttribute( QStringLiteral( "angleOffset" ), QString::number( angleOffset ) ); int nCats = qMin( categoryColors.size(), categoryAttributes.size() ); for ( int i = 0; i < nCats; ++i ) { - QDomElement attributeElem = doc.createElement( "attribute" ); + QDomElement attributeElem = doc.createElement( QStringLiteral( "attribute" ) ); - attributeElem.setAttribute( "field", categoryAttributes.at( i ) ); - attributeElem.setAttribute( "color", categoryColors.at( i ).name() ); - attributeElem.setAttribute( "label", categoryLabels.at( i ) ); + attributeElem.setAttribute( QStringLiteral( "field" ), categoryAttributes.at( i ) ); + attributeElem.setAttribute( QStringLiteral( "color" ), categoryColors.at( i ).name() ); + attributeElem.setAttribute( QStringLiteral( "label" ), categoryLabels.at( i ) ); categoryElem.appendChild( attributeElem ); } @@ -496,16 +496,16 @@ void QgsDiagramRenderer::_readXml( const QDomElement& elem, const QgsVectorLayer Q_UNUSED( layer ) delete mDiagram; - QString diagramType = elem.attribute( "diagramType" ); - if ( diagramType == "Pie" ) + QString diagramType = elem.attribute( QStringLiteral( "diagramType" ) ); + if ( diagramType == QLatin1String( "Pie" ) ) { mDiagram = new QgsPieDiagram(); } - else if ( diagramType == "Text" ) + else if ( diagramType == QLatin1String( "Text" ) ) { mDiagram = new QgsTextDiagram(); } - else if ( diagramType == "Histogram" ) + else if ( diagramType == QLatin1String( "Histogram" ) ) { mDiagram = new QgsHistogramDiagram(); } @@ -513,10 +513,10 @@ void QgsDiagramRenderer::_readXml( const QDomElement& elem, const QgsVectorLayer { mDiagram = nullptr; } - mShowAttributeLegend = ( elem.attribute( "attributeLegend", "1" ) != "0" ); - mShowSizeLegend = ( elem.attribute( "sizeLegend", "0" ) != "0" ); - QDomElement sizeLegendSymbolElem = elem.firstChildElement( "symbol" ); - if ( !sizeLegendSymbolElem.isNull() && sizeLegendSymbolElem.attribute( "name" ) == "sizeSymbol" ) + mShowAttributeLegend = ( elem.attribute( QStringLiteral( "attributeLegend" ), QStringLiteral( "1" ) ) != QLatin1String( "0" ) ); + mShowSizeLegend = ( elem.attribute( QStringLiteral( "sizeLegend" ), QStringLiteral( "0" ) ) != QLatin1String( "0" ) ); + QDomElement sizeLegendSymbolElem = elem.firstChildElement( QStringLiteral( "symbol" ) ); + if ( !sizeLegendSymbolElem.isNull() && sizeLegendSymbolElem.attribute( QStringLiteral( "name" ) ) == QLatin1String( "sizeSymbol" ) ) { mSizeLegendSymbol.reset( QgsSymbolLayerUtils::loadSymbol( sizeLegendSymbolElem ) ); } @@ -529,11 +529,11 @@ void QgsDiagramRenderer::_writeXml( QDomElement& rendererElem, QDomDocument& doc if ( mDiagram ) { - rendererElem.setAttribute( "diagramType", mDiagram->diagramName() ); + rendererElem.setAttribute( QStringLiteral( "diagramType" ), mDiagram->diagramName() ); } - rendererElem.setAttribute( "attributeLegend", mShowAttributeLegend ); - rendererElem.setAttribute( "sizeLegend", mShowSizeLegend ); - QDomElement sizeLegendSymbolElem = QgsSymbolLayerUtils::saveSymbol( "sizeSymbol", mSizeLegendSymbol.data(), doc ); + rendererElem.setAttribute( QStringLiteral( "attributeLegend" ), mShowAttributeLegend ); + rendererElem.setAttribute( QStringLiteral( "sizeLegend" ), mShowSizeLegend ); + QDomElement sizeLegendSymbolElem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "sizeSymbol" ), mSizeLegendSymbol.data(), doc ); rendererElem.appendChild( sizeLegendSymbolElem ); } @@ -571,7 +571,7 @@ QList QgsSingleCategoryDiagramRenderer::diagramSettings() co void QgsSingleCategoryDiagramRenderer::readXml( const QDomElement& elem, const QgsVectorLayer* layer ) { - QDomElement categoryElem = elem.firstChildElement( "DiagramCategory" ); + QDomElement categoryElem = elem.firstChildElement( QStringLiteral( "DiagramCategory" ) ); if ( categoryElem.isNull() ) { return; @@ -583,7 +583,7 @@ void QgsSingleCategoryDiagramRenderer::readXml( const QDomElement& elem, const Q void QgsSingleCategoryDiagramRenderer::writeXml( QDomElement& layerElem, QDomDocument& doc, const QgsVectorLayer* layer ) const { - QDomElement rendererElem = doc.createElement( "SingleCategoryDiagramRenderer" ); + QDomElement rendererElem = doc.createElement( QStringLiteral( "SingleCategoryDiagramRenderer" ) ); mSettings.writeXml( rendererElem, doc, layer ); _writeXml( rendererElem, doc, layer ); layerElem.appendChild( rendererElem ); @@ -648,22 +648,22 @@ QSizeF QgsLinearlyInterpolatedDiagramRenderer::diagramSize( const QgsFeature& fe void QgsLinearlyInterpolatedDiagramRenderer::readXml( const QDomElement& elem, const QgsVectorLayer* layer ) { - mInterpolationSettings.lowerValue = elem.attribute( "lowerValue" ).toDouble(); - mInterpolationSettings.upperValue = elem.attribute( "upperValue" ).toDouble(); - mInterpolationSettings.lowerSize.setWidth( elem.attribute( "lowerWidth" ).toDouble() ); - mInterpolationSettings.lowerSize.setHeight( elem.attribute( "lowerHeight" ).toDouble() ); - mInterpolationSettings.upperSize.setWidth( elem.attribute( "upperWidth" ).toDouble() ); - mInterpolationSettings.upperSize.setHeight( elem.attribute( "upperHeight" ).toDouble() ); - mInterpolationSettings.classificationAttributeIsExpression = elem.hasAttribute( "classificationAttributeExpression" ); + mInterpolationSettings.lowerValue = elem.attribute( QStringLiteral( "lowerValue" ) ).toDouble(); + mInterpolationSettings.upperValue = elem.attribute( QStringLiteral( "upperValue" ) ).toDouble(); + mInterpolationSettings.lowerSize.setWidth( elem.attribute( QStringLiteral( "lowerWidth" ) ).toDouble() ); + mInterpolationSettings.lowerSize.setHeight( elem.attribute( QStringLiteral( "lowerHeight" ) ).toDouble() ); + mInterpolationSettings.upperSize.setWidth( elem.attribute( QStringLiteral( "upperWidth" ) ).toDouble() ); + mInterpolationSettings.upperSize.setHeight( elem.attribute( QStringLiteral( "upperHeight" ) ).toDouble() ); + mInterpolationSettings.classificationAttributeIsExpression = elem.hasAttribute( QStringLiteral( "classificationAttributeExpression" ) ); if ( mInterpolationSettings.classificationAttributeIsExpression ) { - mInterpolationSettings.classificationAttributeExpression = elem.attribute( "classificationAttributeExpression" ); + mInterpolationSettings.classificationAttributeExpression = elem.attribute( QStringLiteral( "classificationAttributeExpression" ) ); } else { - mInterpolationSettings.classificationAttribute = elem.attribute( "classificationAttribute" ).toInt(); + mInterpolationSettings.classificationAttribute = elem.attribute( QStringLiteral( "classificationAttribute" ) ).toInt(); } - QDomElement settingsElem = elem.firstChildElement( "DiagramCategory" ); + QDomElement settingsElem = elem.firstChildElement( QStringLiteral( "DiagramCategory" ) ); if ( !settingsElem.isNull() ) { mSettings.readXml( settingsElem, layer ); @@ -673,20 +673,20 @@ void QgsLinearlyInterpolatedDiagramRenderer::readXml( const QDomElement& elem, c void QgsLinearlyInterpolatedDiagramRenderer::writeXml( QDomElement& layerElem, QDomDocument& doc, const QgsVectorLayer* layer ) const { - QDomElement rendererElem = doc.createElement( "LinearlyInterpolatedDiagramRenderer" ); - rendererElem.setAttribute( "lowerValue", QString::number( mInterpolationSettings.lowerValue ) ); - rendererElem.setAttribute( "upperValue", QString::number( mInterpolationSettings.upperValue ) ); - rendererElem.setAttribute( "lowerWidth", QString::number( mInterpolationSettings.lowerSize.width() ) ); - rendererElem.setAttribute( "lowerHeight", QString::number( mInterpolationSettings.lowerSize.height() ) ); - rendererElem.setAttribute( "upperWidth", QString::number( mInterpolationSettings.upperSize.width() ) ); - rendererElem.setAttribute( "upperHeight", QString::number( mInterpolationSettings.upperSize.height() ) ); + QDomElement rendererElem = doc.createElement( QStringLiteral( "LinearlyInterpolatedDiagramRenderer" ) ); + rendererElem.setAttribute( QStringLiteral( "lowerValue" ), QString::number( mInterpolationSettings.lowerValue ) ); + rendererElem.setAttribute( QStringLiteral( "upperValue" ), QString::number( mInterpolationSettings.upperValue ) ); + rendererElem.setAttribute( QStringLiteral( "lowerWidth" ), QString::number( mInterpolationSettings.lowerSize.width() ) ); + rendererElem.setAttribute( QStringLiteral( "lowerHeight" ), QString::number( mInterpolationSettings.lowerSize.height() ) ); + rendererElem.setAttribute( QStringLiteral( "upperWidth" ), QString::number( mInterpolationSettings.upperSize.width() ) ); + rendererElem.setAttribute( QStringLiteral( "upperHeight" ), QString::number( mInterpolationSettings.upperSize.height() ) ); if ( mInterpolationSettings.classificationAttributeIsExpression ) { - rendererElem.setAttribute( "classificationAttributeExpression", mInterpolationSettings.classificationAttributeExpression ); + rendererElem.setAttribute( QStringLiteral( "classificationAttributeExpression" ), mInterpolationSettings.classificationAttributeExpression ); } else { - rendererElem.setAttribute( "classificationAttribute", mInterpolationSettings.classificationAttribute ); + rendererElem.setAttribute( QStringLiteral( "classificationAttribute" ), mInterpolationSettings.classificationAttribute ); } mSettings.writeXml( rendererElem, doc, layer ); _writeXml( rendererElem, doc, layer ); @@ -701,7 +701,7 @@ QList< QgsLayerTreeModelLegendNode* > QgsDiagramSettings::legendItems( QgsLayerT { QPixmap pix( 16, 16 ); pix.fill( categoryColors[i] ); - list << new QgsSimpleLegendNode( nodeLayer, categoryLabels[i], QIcon( pix ), nullptr, QString( "diagram_%1" ).arg( QString::number( i ) ) ); + list << new QgsSimpleLegendNode( nodeLayer, categoryLabels[i], QIcon( pix ), nullptr, QStringLiteral( "diagram_%1" ).arg( QString::number( i ) ) ); } return list; } diff --git a/src/core/qgsdiagramrenderer.h b/src/core/qgsdiagramrenderer.h index 185f3d0e0d79..b93b67ebcb9f 100644 --- a/src/core/qgsdiagramrenderer.h +++ b/src/core/qgsdiagramrenderer.h @@ -543,7 +543,7 @@ class CORE_EXPORT QgsSingleCategoryDiagramRenderer : public QgsDiagramRenderer QgsSingleCategoryDiagramRenderer* clone() const override; - QString rendererName() const override { return "SingleCategory"; } + QString rendererName() const override { return QStringLiteral( "SingleCategory" ); } QList diagramAttributes() const override { return mSettings.categoryAttributes; } @@ -585,7 +585,7 @@ class CORE_EXPORT QgsLinearlyInterpolatedDiagramRenderer : public QgsDiagramRend virtual QSet< QString > referencedFields( const QgsExpressionContext& context = QgsExpressionContext(), const QgsFields& fields = QgsFields() ) const override; - QString rendererName() const override { return "LinearlyInterpolated"; } + QString rendererName() const override { return QStringLiteral( "LinearlyInterpolated" ); } void setLowerValue( double val ) { mInterpolationSettings.lowerValue = val; } double lowerValue() const { return mInterpolationSettings.lowerValue; } diff --git a/src/core/qgsdistancearea.cpp b/src/core/qgsdistancearea.cpp index 6dd88dbf0458..259bc3fddbf4 100644 --- a/src/core/qgsdistancearea.cpp +++ b/src/core/qgsdistancearea.cpp @@ -139,7 +139,7 @@ bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) // Format is "PARAMETER:: // Numbers must be with (optional) decimal point and no other separators (C locale) // Distances in meters. Flattening is calculated. - if ( ellipsoid.startsWith( "PARAMETER" ) ) + if ( ellipsoid.startsWith( QLatin1String( "PARAMETER" ) ) ) { QStringList paramList = ellipsoid.split( ':' ); bool semiMajorOk, semiMinorOk; @@ -190,7 +190,7 @@ bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) } // get major semiaxis - if ( radius.left( 2 ) == "a=" ) + if ( radius.left( 2 ) == QLatin1String( "a=" ) ) mSemiMajor = radius.midRef( 2 ).toDouble(); else { @@ -201,12 +201,12 @@ bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) // get second parameter // one of values 'b' or 'f' is in field parameter2 // second one must be computed using formula: invf = a/(a-b) - if ( parameter2.left( 2 ) == "b=" ) + if ( parameter2.left( 2 ) == QLatin1String( "b=" ) ) { mSemiMinor = parameter2.midRef( 2 ).toDouble(); mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor ); } - else if ( parameter2.left( 3 ) == "rf=" ) + else if ( parameter2.left( 3 ) == QLatin1String( "rf=" ) ) { mInvFlattening = parameter2.midRef( 3 ).toDouble(); mSemiMinor = mSemiMajor - ( mSemiMajor / mInvFlattening ); @@ -229,7 +229,7 @@ bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) // familiar with the code (should also give a more descriptive name to the generated CRS) if ( destCRS.srsid() == 0 ) { - QString myName = QString( " * %1 (%2)" ) + QString myName = QStringLiteral( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), destCRS.toProj4() ); destCRS.saveAsUserCrs( myName ); @@ -252,7 +252,7 @@ bool QgsDistanceArea::setEllipsoid( const QString& ellipsoid ) // Also, b = a-(a/invf) bool QgsDistanceArea::setEllipsoid( double semiMajor, double semiMinor ) { - mEllipsoid = QString( "PARAMETER:%1:%2" ).arg( semiMajor ).arg( semiMinor ); + mEllipsoid = QStringLiteral( "PARAMETER:%1:%2" ).arg( semiMajor ).arg( semiMinor ); mSemiMajor = semiMajor; mSemiMinor = semiMinor; mInvFlattening = mSemiMajor / ( mSemiMajor - mSemiMinor ); @@ -1083,7 +1083,7 @@ QString QgsDistanceArea::formatDistance( double distance, int decimals, QgsUnitT break; } - return QString( "%L1%2" ).arg( distance, 0, 'f', decimals ).arg( unitLabel ); + return QStringLiteral( "%L1%2" ).arg( distance, 0, 'f', decimals ).arg( unitLabel ); } QString QgsDistanceArea::formatArea( double area, int decimals, QgsUnitTypes::AreaUnit unit, bool keepBaseUnit ) @@ -1218,7 +1218,7 @@ QString QgsDistanceArea::formatArea( double area, int decimals, QgsUnitTypes::Ar } } - return QString( "%L1%2" ).arg( area, 0, 'f', decimals ).arg( unitLabel ); + return QStringLiteral( "%L1%2" ).arg( area, 0, 'f', decimals ).arg( unitLabel ); } double QgsDistanceArea::convertLengthMeasurement( double length, QgsUnitTypes::DistanceUnit toUnits ) const diff --git a/src/core/qgseditformconfig.cpp b/src/core/qgseditformconfig.cpp index 42a4a8f09ab9..2ea90c33ca79 100644 --- a/src/core/qgseditformconfig.cpp +++ b/src/core/qgseditformconfig.cpp @@ -313,26 +313,26 @@ void QgsEditFormConfig::setNotNull( int idx, bool notnull ) void QgsEditFormConfig::readXml( const QDomNode& node ) { d.detach(); - QDomNode editFormNode = node.namedItem( "editform" ); + QDomNode editFormNode = node.namedItem( QStringLiteral( "editform" ) ); if ( !editFormNode.isNull() ) { QDomElement e = editFormNode.toElement(); d->mUiFormPath = QgsProject::instance()->readPath( e.text() ); } - QDomNode editFormInitNode = node.namedItem( "editforminit" ); + QDomNode editFormInitNode = node.namedItem( QStringLiteral( "editforminit" ) ); if ( !editFormInitNode.isNull() ) { d->mInitFunction = editFormInitNode.toElement().text(); } - QDomNode editFormInitCodeSourceNode = node.namedItem( "editforminitcodesource" ); + QDomNode editFormInitCodeSourceNode = node.namedItem( QStringLiteral( "editforminitcodesource" ) ); if ( !editFormInitCodeSourceNode.isNull() || ( !editFormInitCodeSourceNode.isNull() && !editFormInitCodeSourceNode.toElement().text().isEmpty() ) ) { setInitCodeSource( static_cast< QgsEditFormConfig::PythonInitCodeSource >( editFormInitCodeSourceNode.toElement().text().toInt() ) ); } - QDomNode editFormInitCodeNode = node.namedItem( "editforminitcode" ); + QDomNode editFormInitCodeNode = node.namedItem( QStringLiteral( "editforminitcode" ) ); if ( !editFormInitCodeNode.isNull() ) { setInitCode( editFormInitCodeNode.toElement().text() ); @@ -347,17 +347,17 @@ void QgsEditFormConfig::readXml( const QDomNode& node ) if ( dotPos >= 0 ) // It's a module { setInitCodeSource( QgsEditFormConfig::CodeSourceDialog ); - setInitCode( QString( "from %1 import %2\n" ).arg( d->mInitFunction.left( dotPos ), d->mInitFunction.mid( dotPos + 1 ) ) ); + setInitCode( QStringLiteral( "from %1 import %2\n" ).arg( d->mInitFunction.left( dotPos ), d->mInitFunction.mid( dotPos + 1 ) ) ); setInitFunction( d->mInitFunction.mid( dotPos + 1 ) ); } - QDomNode editFormInitFilePathNode = node.namedItem( "editforminitfilepath" ); + QDomNode editFormInitFilePathNode = node.namedItem( QStringLiteral( "editforminitfilepath" ) ); if ( !editFormInitFilePathNode.isNull() || ( !editFormInitFilePathNode.isNull() && !editFormInitFilePathNode.toElement().text().isEmpty() ) ) { setInitFilePath( QgsProject::instance()->readPath( editFormInitFilePathNode.toElement().text() ) ); } - QDomNode fFSuppNode = node.namedItem( "featformsuppress" ); + QDomNode fFSuppNode = node.namedItem( QStringLiteral( "featformsuppress" ) ); if ( fFSuppNode.isNull() ) { d->mSuppressForm = QgsEditFormConfig::SuppressDefault; @@ -369,18 +369,18 @@ void QgsEditFormConfig::readXml( const QDomNode& node ) } // tab display - QDomNode editorLayoutNode = node.namedItem( "editorlayout" ); + QDomNode editorLayoutNode = node.namedItem( QStringLiteral( "editorlayout" ) ); if ( editorLayoutNode.isNull() ) { d->mEditorLayout = QgsEditFormConfig::GeneratedLayout; } else { - if ( editorLayoutNode.toElement().text() == "uifilelayout" ) + if ( editorLayoutNode.toElement().text() == QLatin1String( "uifilelayout" ) ) { d->mEditorLayout = QgsEditFormConfig::UiFileLayout; } - else if ( editorLayoutNode.toElement().text() == "tablayout" ) + else if ( editorLayoutNode.toElement().text() == QLatin1String( "tablayout" ) ) { d->mEditorLayout = QgsEditFormConfig::TabLayout; } @@ -391,7 +391,7 @@ void QgsEditFormConfig::readXml( const QDomNode& node ) } // tabs and groups display info - QDomNode attributeEditorFormNode = node.namedItem( "attributeEditorForm" ); + QDomNode attributeEditorFormNode = node.namedItem( QStringLiteral( "attributeEditorForm" ) ); if ( !attributeEditorFormNode.isNull() ) { QDomNodeList attributeEditorFormNodeList = attributeEditorFormNode.toElement().childNodes(); @@ -412,16 +412,16 @@ void QgsEditFormConfig::readXml( const QDomNode& node ) } - QDomElement widgetsElem = node.namedItem( "widgets" ).toElement(); + QDomElement widgetsElem = node.namedItem( QStringLiteral( "widgets" ) ).toElement(); QDomNodeList widgetConfigsElems = widgetsElem.childNodes(); for ( int i = 0; i < widgetConfigsElems.size(); ++i ) { const QDomElement wdgElem = widgetConfigsElems.at( i ).toElement(); - const QDomElement cfgElem = wdgElem.namedItem( "config" ).toElement(); + const QDomElement cfgElem = wdgElem.namedItem( QStringLiteral( "config" ) ).toElement(); const QgsEditorWidgetConfig widgetConfig = parseEditorWidgetConfig( cfgElem ); - setWidgetConfig( wdgElem.attribute( "name" ), widgetConfig ); + setWidgetConfig( wdgElem.attribute( QStringLiteral( "name" ) ), widgetConfig ); } } @@ -436,12 +436,12 @@ QgsEditorWidgetConfig QgsEditFormConfig::parseEditorWidgetConfig( const QDomElem cfg.insert( attr.name(), attr.value() ); } - const QDomNodeList optionElements = cfgElem.elementsByTagName( "option" ); + const QDomNodeList optionElements = cfgElem.elementsByTagName( QStringLiteral( "option" ) ); for ( int j = 0; j < optionElements.size(); ++j ) { const QDomElement option = optionElements.at( j ).toElement(); - const QString key = option.attribute( "key" ); - const QString value = option.attribute( "value" ); + const QString key = option.attribute( QStringLiteral( "key" ) ); + const QString value = option.attribute( QStringLiteral( "value" ) ); cfg.insert( key, value ); } //// END TODO @@ -452,48 +452,48 @@ void QgsEditFormConfig::writeXml( QDomNode& node ) const { QDomDocument doc( node.ownerDocument() ); - QDomElement efField = doc.createElement( "editform" ); + QDomElement efField = doc.createElement( QStringLiteral( "editform" ) ); QDomText efText = doc.createTextNode( QgsProject::instance()->writePath( uiForm() ) ); efField.appendChild( efText ); node.appendChild( efField ); - QDomElement efiField = doc.createElement( "editforminit" ); + QDomElement efiField = doc.createElement( QStringLiteral( "editforminit" ) ); if ( !initFunction().isEmpty() ) efiField.appendChild( doc.createTextNode( initFunction() ) ); node.appendChild( efiField ); - QDomElement eficsField = doc.createElement( "editforminitcodesource" ); + QDomElement eficsField = doc.createElement( QStringLiteral( "editforminitcodesource" ) ); eficsField.appendChild( doc.createTextNode( QString::number( initCodeSource() ) ) ); node.appendChild( eficsField ); - QDomElement efifpField = doc.createElement( "editforminitfilepath" ); + QDomElement efifpField = doc.createElement( QStringLiteral( "editforminitfilepath" ) ); efifpField.appendChild( doc.createTextNode( QgsProject::instance()->writePath( initFilePath() ) ) ); node.appendChild( efifpField ); - QDomElement eficField = doc.createElement( "editforminitcode" ); + QDomElement eficField = doc.createElement( QStringLiteral( "editforminitcode" ) ); eficField.appendChild( doc.createCDATASection( initCode() ) ); node.appendChild( eficField ); - QDomElement fFSuppElem = doc.createElement( "featformsuppress" ); + QDomElement fFSuppElem = doc.createElement( QStringLiteral( "featformsuppress" ) ); QDomText fFSuppText = doc.createTextNode( QString::number( suppress() ) ); fFSuppElem.appendChild( fFSuppText ); node.appendChild( fFSuppElem ); // tab display - QDomElement editorLayoutElem = doc.createElement( "editorlayout" ); + QDomElement editorLayoutElem = doc.createElement( QStringLiteral( "editorlayout" ) ); switch ( layout() ) { case QgsEditFormConfig::UiFileLayout: - editorLayoutElem.appendChild( doc.createTextNode( "uifilelayout" ) ); + editorLayoutElem.appendChild( doc.createTextNode( QStringLiteral( "uifilelayout" ) ) ); break; case QgsEditFormConfig::TabLayout: - editorLayoutElem.appendChild( doc.createTextNode( "tablayout" ) ); + editorLayoutElem.appendChild( doc.createTextNode( QStringLiteral( "tablayout" ) ) ); break; case QgsEditFormConfig::GeneratedLayout: default: - editorLayoutElem.appendChild( doc.createTextNode( "generatedlayout" ) ); + editorLayoutElem.appendChild( doc.createTextNode( QStringLiteral( "generatedlayout" ) ) ); break; } @@ -502,7 +502,7 @@ void QgsEditFormConfig::writeXml( QDomNode& node ) const // tabs and groups of edit form if ( tabs().size() > 0 && d->mConfiguredRootContainer ) { - QDomElement tabsElem = doc.createElement( "attributeEditorForm" ); + QDomElement tabsElem = doc.createElement( QStringLiteral( "attributeEditorForm" ) ); QDomElement rootElem = d->mInvisibleRootContainer->toDomElement( doc ); QDomNodeList elemList = rootElem.childNodes(); @@ -518,7 +518,7 @@ void QgsEditFormConfig::writeXml( QDomNode& node ) const //// TODO: MAKE THIS MORE GENERIC, SO INDIVIDUALL WIDGETS CAN NOT ONLY SAVE STRINGS /// SEE QgsEditorWidgetFactory::writeConfig - QDomElement widgetsElem = doc.createElement( "widgets" ); + QDomElement widgetsElem = doc.createElement( QStringLiteral( "widgets" ) ); QMap::ConstIterator configIt( d->mWidgetConfigs.constBegin() ); @@ -526,20 +526,20 @@ void QgsEditFormConfig::writeXml( QDomNode& node ) const { if ( d->mFields.indexFromName( configIt.key() ) == -1 ) { - QDomElement widgetElem = doc.createElement( "widget" ); - widgetElem.setAttribute( "name", configIt.key() ); + QDomElement widgetElem = doc.createElement( QStringLiteral( "widget" ) ); + widgetElem.setAttribute( QStringLiteral( "name" ), configIt.key() ); // widgetElem.setAttribute( "notNull", ); - QDomElement configElem = doc.createElement( "config" ); + QDomElement configElem = doc.createElement( QStringLiteral( "config" ) ); widgetElem.appendChild( configElem ); QgsEditorWidgetConfig::ConstIterator cfgIt( configIt.value().constBegin() ); while ( cfgIt != configIt.value().constEnd() ) { - QDomElement optionElem = doc.createElement( "option" ); - optionElem.setAttribute( "key", cfgIt.key() ); - optionElem.setAttribute( "value", cfgIt.value().toString() ); + QDomElement optionElem = doc.createElement( QStringLiteral( "option" ) ); + optionElem.setAttribute( QStringLiteral( "key" ), cfgIt.key() ); + optionElem.setAttribute( QStringLiteral( "value" ), cfgIt.value().toString() ); configElem.appendChild( optionElem ); ++cfgIt; } @@ -558,27 +558,27 @@ QgsAttributeEditorElement* QgsEditFormConfig::attributeEditorElementFromDomEleme { QgsAttributeEditorElement* newElement = nullptr; - if ( elem.tagName() == "attributeEditorContainer" ) + if ( elem.tagName() == QLatin1String( "attributeEditorContainer" ) ) { - QgsAttributeEditorContainer* container = new QgsAttributeEditorContainer( elem.attribute( "name" ), parent ); + QgsAttributeEditorContainer* container = new QgsAttributeEditorContainer( elem.attribute( QStringLiteral( "name" ) ), parent ); bool ok; - int cc = elem.attribute( "columnCount" ).toInt( &ok ); + int cc = elem.attribute( QStringLiteral( "columnCount" ) ).toInt( &ok ); if ( !ok ) cc = 0; container->setColumnCount( cc ); - bool isGroupBox = elem.attribute( "groupBox" ).toInt( &ok ); + bool isGroupBox = elem.attribute( QStringLiteral( "groupBox" ) ).toInt( &ok ); if ( ok ) container->setIsGroupBox( isGroupBox ); else container->setIsGroupBox( parent ); - bool visibilityExpressionEnabled = elem.attribute( "visibilityExpressionEnabled" ).toInt( &ok ); + bool visibilityExpressionEnabled = elem.attribute( QStringLiteral( "visibilityExpressionEnabled" ) ).toInt( &ok ); QgsOptionalExpression visibilityExpression; if ( ok ) { visibilityExpression.setEnabled( visibilityExpressionEnabled ); - visibilityExpression.setData( QgsExpression( elem.attribute( "visibilityExpression" ) ) ); + visibilityExpression.setData( QgsExpression( elem.attribute( QStringLiteral( "visibilityExpression" ) ) ) ); } container->setVisibilityExpression( visibilityExpression ); @@ -594,25 +594,25 @@ QgsAttributeEditorElement* QgsEditFormConfig::attributeEditorElementFromDomEleme newElement = container; } - else if ( elem.tagName() == "attributeEditorField" ) + else if ( elem.tagName() == QLatin1String( "attributeEditorField" ) ) { - QString name = elem.attribute( "name" ); + QString name = elem.attribute( QStringLiteral( "name" ) ); int idx = d->mFields.lookupField( name ); newElement = new QgsAttributeEditorField( name, idx, parent ); } - else if ( elem.tagName() == "attributeEditorRelation" ) + else if ( elem.tagName() == QLatin1String( "attributeEditorRelation" ) ) { // At this time, the relations are not loaded // So we only grab the id and delegate the rest to onRelationsLoaded() - QString name = elem.attribute( "name" ); - QgsAttributeEditorRelation* relElement = new QgsAttributeEditorRelation( name, elem.attribute( "relation", "[None]" ), parent ); - relElement->setShowLinkButton( elem.attribute( "showLinkButton", "1" ).toInt() ); - relElement->setShowUnlinkButton( elem.attribute( "showUnlinkButton", "1" ).toInt() ); + QString name = elem.attribute( QStringLiteral( "name" ) ); + QgsAttributeEditorRelation* relElement = new QgsAttributeEditorRelation( name, elem.attribute( QStringLiteral( "relation" ), QStringLiteral( "[None]" ) ), parent ); + relElement->setShowLinkButton( elem.attribute( QStringLiteral( "showLinkButton" ), QStringLiteral( "1" ) ).toInt() ); + relElement->setShowUnlinkButton( elem.attribute( QStringLiteral( "showUnlinkButton" ), QStringLiteral( "1" ) ).toInt() ); newElement = relElement; } - if ( elem.hasAttribute( "showLabel" ) ) - newElement->setShowLabel( elem.attribute( "showLabel" ).toInt() ); + if ( elem.hasAttribute( QStringLiteral( "showLabel" ) ) ) + newElement->setShowLabel( elem.attribute( QStringLiteral( "showLabel" ) ).toInt() ); else newElement->setShowLabel( true ); @@ -646,10 +646,10 @@ QgsAttributeEditorElement* QgsAttributeEditorContainer::clone( QgsAttributeEdito void QgsAttributeEditorContainer::saveConfiguration( QDomElement& elem ) const { - elem.setAttribute( "columnCount", mColumnCount ); - elem.setAttribute( "groupBox", mIsGroupBox ? 1 : 0 ); - elem.setAttribute( "visibilityExpressionEnabled", mVisibilityExpression.enabled() ? 1 : 0 ); - elem.setAttribute( "visibilityExpression", mVisibilityExpression->expression() ); + elem.setAttribute( QStringLiteral( "columnCount" ), mColumnCount ); + elem.setAttribute( QStringLiteral( "groupBox" ), mIsGroupBox ? 1 : 0 ); + elem.setAttribute( QStringLiteral( "visibilityExpressionEnabled" ), mVisibilityExpression.enabled() ? 1 : 0 ); + elem.setAttribute( QStringLiteral( "visibilityExpression" ), mVisibilityExpression->expression() ); Q_FOREACH ( QgsAttributeEditorElement* child, mChildren ) { @@ -660,5 +660,5 @@ void QgsAttributeEditorContainer::saveConfiguration( QDomElement& elem ) const QString QgsAttributeEditorContainer::typeIdentifier() const { - return "attributeEditorContainer"; + return QStringLiteral( "attributeEditorContainer" ); } diff --git a/src/core/qgserror.cpp b/src/core/qgserror.cpp index 69c7bf955aa1..2bdae5c4ad3d 100644 --- a/src/core/qgserror.cpp +++ b/src/core/qgserror.cpp @@ -59,10 +59,10 @@ QString QgsError::message( QgsErrorMessage::Format theFormat ) const // TODO: verify if we are not ahead to origin (remote hash does not exist) // and there are no local not commited changes QString hash = QString( Qgis::QGIS_DEV_VERSION ); - QString remote = QString( QGS_GIT_REMOTE_URL ); - if ( !hash.isEmpty() && !remote.isEmpty() && remote.contains( "github.com" ) ) + QString remote = QStringLiteral( QGS_GIT_REMOTE_URL ); + if ( !hash.isEmpty() && !remote.isEmpty() && remote.contains( QLatin1String( "github.com" ) ) ) { - QString path = remote.remove( QRegExp( ".*github.com[:/]" ) ).remove( ".git" ); + QString path = remote.remove( QRegExp( ".*github.com[:/]" ) ).remove( QStringLiteral( ".git" ) ); srcUrl = "https://github.com/" + path + "/blob/" + hash; } #endif @@ -94,15 +94,15 @@ QString QgsError::message( QgsErrorMessage::Format theFormat ) const QString where; if ( !file.isEmpty() ) { - where += QString( "file: %1 row: %2" ).arg( file ).arg( m.line() ); + where += QStringLiteral( "file: %1 row: %2" ).arg( file ).arg( m.line() ); } if ( !m.function().isEmpty() ) { - where += QString( "function %1:" ).arg( m.function() ); + where += QStringLiteral( "function %1:" ).arg( m.function() ); } if ( !where.isEmpty() ) { - str += QString( " (%1)" ).arg( where ); + str += QStringLiteral( " (%1)" ).arg( where ); } #endif } @@ -110,15 +110,15 @@ QString QgsError::message( QgsErrorMessage::Format theFormat ) const { str += "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n

                                                                                                                                                                                    %2

                                                                                                                                                                                    " ) + QString helpContents( QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n

                                                                                                                                                                                    %2

                                                                                                                                                                                    " ) .arg( tr( "%1 %2" ).arg( f.mType, name ), f.mDescription ) ); @@ -5122,28 +5122,28 @@ QString QgsExpression::helpText( QString name ) { if ( f.mVariants.size() > 1 ) { - helpContents += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n
                                                                                                                                                                                    %2

                                                                                                                                                                                    " ).arg( v.mName, v.mDescription ); + helpContents += QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n
                                                                                                                                                                                    %2

                                                                                                                                                                                    " ).arg( v.mName, v.mDescription ); } if ( f.mType != tr( "group" ) && f.mType != tr( "expression" ) ) - helpContents += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n

                                                                                                                                                                                    " + m.tag() + ": " + m.message(); #ifdef QGISDEBUG - QString location = QString( "%1 : %2 : %3" ).arg( file ).arg( m.line() ).arg( m.function() ); + QString location = QStringLiteral( "%1 : %2 : %3" ).arg( file ).arg( m.line() ).arg( m.function() ); if ( !srcUrl.isEmpty() ) { - QString url = QString( "%1/%2#L%3" ).arg( srcUrl, file ).arg( m.line() ); - str += QString( "
                                                                                                                                                                                    (
                                                                                                                                                                                    %2)" ).arg( url, location ); + QString url = QStringLiteral( "%1/%2#L%3" ).arg( srcUrl, file ).arg( m.line() ); + str += QStringLiteral( "
                                                                                                                                                                                    (%2)" ).arg( url, location ); } else { - str += QString( "
                                                                                                                                                                                    (%1)" ).arg( location ); + str += QStringLiteral( "
                                                                                                                                                                                    (%1)" ).arg( location ); } #endif } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 728eb37f1d2a..dddee79d8e3f 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -285,7 +285,7 @@ static QgsGeometry getGeometry( const QVariant& value, QgsExpression* parent ) if ( value.canConvert() ) return value.value(); - parent->setEvalErrorString( "Cannot convert to QgsGeometry" ); + parent->setEvalErrorString( QStringLiteral( "Cannot convert to QgsGeometry" ) ); return QgsGeometry(); } @@ -294,7 +294,7 @@ static QgsFeature getFeature( const QVariant& value, QgsExpression* parent ) if ( value.canConvert() ) return value.value(); - parent->setEvalErrorString( "Cannot convert to QgsFeature" ); + parent->setEvalErrorString( QStringLiteral( "Cannot convert to QgsFeature" ) ); return 0; } @@ -306,7 +306,7 @@ static QgsExpression::Node* getNode( const QVariant& value, QgsExpression* paren if ( value.canConvert() ) return value.value(); - parent->setEvalErrorString( "Cannot convert to Node" ); + parent->setEvalErrorString( QStringLiteral( "Cannot convert to Node" ) ); return nullptr; } @@ -672,7 +672,7 @@ static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionCon parameters.delimiter = value.toString(); } - QString cacheKey = QString( "aggfcn:%1:%2:%3:%4" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter ); + QString cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter ); if ( context && context->hasCachedValue( cacheKey ) ) return context->cachedValue( cacheKey ); @@ -707,7 +707,7 @@ static QVariant fcnAggregateRelation( const QVariantList& values, const QgsExpre } // first step - find current layer - QString layerId = context->variable( "layer_id" ).toString(); + QString layerId = context->variable( QStringLiteral( "layer_id" ) ).toString(); QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerId ) ); if ( !vl ) { @@ -774,7 +774,7 @@ static QVariant fcnAggregateRelation( const QVariantList& values, const QgsExpre FEAT_FROM_CONTEXT( context, f ); parameters.filter = relation.getRelatedFeaturesFilter( f ); - QString cacheKey = QString( "relagg:%1:%2:%3:%4" ).arg( vl->id(), + QString cacheKey = QStringLiteral( "relagg:%1:%2:%3:%4" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter ); @@ -810,7 +810,7 @@ static QVariant fcnAggregateGeneric( QgsAggregateCalculator::Aggregate aggregate } // first step - find current layer - QString layerId = context->variable( "layer_id" ).toString(); + QString layerId = context->variable( QStringLiteral( "layer_id" ) ).toString(); QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerId ) ); if ( !vl ) { @@ -854,12 +854,12 @@ static QVariant fcnAggregateGeneric( QgsAggregateCalculator::Aggregate aggregate QgsExpression groupByExp( groupBy ); QVariant groupByValue = groupByExp.evaluate( context ); if ( !parameters.filter.isEmpty() ) - parameters.filter = QString( "(%1) AND (%2=%3)" ).arg( parameters.filter, groupBy, QgsExpression::quotedValue( groupByValue ) ); + parameters.filter = QStringLiteral( "(%1) AND (%2=%3)" ).arg( parameters.filter, groupBy, QgsExpression::quotedValue( groupByValue ) ); else - parameters.filter = QString( "(%2 = %3)" ).arg( groupBy, QgsExpression::quotedValue( groupByValue ) ); + parameters.filter = QStringLiteral( "(%2 = %3)" ).arg( groupBy, QgsExpression::quotedValue( groupByValue ) ); } - QString cacheKey = QString( "agg:%1:%2:%3:%4" ).arg( vl->id(), + QString cacheKey = QStringLiteral( "agg:%1:%2:%3:%4" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter ); @@ -1072,7 +1072,7 @@ static QVariant fcnTitle( const QVariantList& values, const QgsExpressionContext if ( elems[i].size() > 1 ) elems[i] = elems[i].at( 0 ).toUpper() + elems[i].mid( 1 ).toLower(); } - return QVariant( elems.join( " " ) ); + return QVariant( elems.join( QStringLiteral( " " ) ) ); } static QVariant fcnTrim( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) @@ -1138,7 +1138,7 @@ static QVariant fcnWordwrap( const QVariantList& values, const QgsExpressionCont else { // \x200B is a ZERO-WIDTH SPACE, needed for worwrap to support a number of complex scripts (Indic, Arabic, etc.) - rx.setPattern( "[\\s\\x200B]" ); + rx.setPattern( QStringLiteral( "[\\s\\x200B]" ) ); delimiterlength = 1; } @@ -2525,7 +2525,7 @@ static QVariant fcnProject( const QVariantList& values, const QgsExpressionConte if ( geom.type() != QgsWkbTypes::PointGeometry ) { - parent->setEvalErrorString( "'project' requires a point geometry" ); + parent->setEvalErrorString( QStringLiteral( "'project' requires a point geometry" ) ); return QVariant(); } @@ -2719,7 +2719,7 @@ static QVariant fcnFormatNumber( const QVariantList& values, const QgsExpression parent->setEvalErrorString( QObject::tr( "Number of places must be positive" ) ); return QVariant(); } - return QString( "%L1" ).arg( value, 0, 'f', places ); + return QStringLiteral( "%L1" ).arg( value, 0, 'f', places ); } static QVariant fcnFormatDate( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) @@ -2741,7 +2741,7 @@ static QVariant fcnColorRgb( const QVariantList &values, const QgsExpressionCont color = QColor( 0, 0, 0 ); } - return QString( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); + return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); } static QVariant fcnIf( const QVariantList &values, const QgsExpressionContext *context, QgsExpression *parent ) @@ -2813,7 +2813,7 @@ static QVariant fcnColorHsl( const QVariantList &values, const QgsExpressionCont color = QColor( 0, 0, 0 ); } - return QString( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); + return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); } static QVariant fncColorHsla( const QVariantList &values, const QgsExpressionContext*, QgsExpression *parent ) @@ -2853,7 +2853,7 @@ static QVariant fcnColorHsv( const QVariantList &values, const QgsExpressionCont color = QColor( 0, 0, 0 ); } - return QString( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); + return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); } static QVariant fncColorHsva( const QVariantList &values, const QgsExpressionContext*, QgsExpression *parent ) @@ -2895,7 +2895,7 @@ static QVariant fcnColorCmyk( const QVariantList &values, const QgsExpressionCon color = QColor( 0, 0, 0 ); } - return QString( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); + return QStringLiteral( "%1,%2,%3" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ); } static QVariant fncColorCmyka( const QVariantList &values, const QgsExpressionContext*, QgsExpression *parent ) @@ -3068,7 +3068,7 @@ static QVariant fcnTransformGeometry( const QVariantList& values, const QgsExpre } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught in transform() function: %1" ).arg( cse.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught in transform() function: %1" ).arg( cse.what() ) ); return QVariant(); } return QVariant(); @@ -3095,7 +3095,7 @@ static QVariant fcnGetFeature( const QVariantList& values, const QgsExpressionCo const QVariant& attVal = values.at( 2 ); QgsFeatureRequest req; - req.setFilterExpression( QString( "%1=%2" ).arg( QgsExpression::quotedColumnRef( attribute ), + req.setFilterExpression( QStringLiteral( "%1=%2" ).arg( QgsExpression::quotedColumnRef( attribute ), QgsExpression::quotedString( attVal.toString() ) ) ); req.setLimit( 1 ); if ( !parent->needsGeometry() ) @@ -3130,39 +3130,39 @@ static QVariant fcnGetLayerProperty( const QVariantList& values, const QgsExpres return QVariant(); QString layerProperty = getStringValue( values.at( 1 ), parent ); - if ( QString::compare( layerProperty, QString( "name" ), Qt::CaseInsensitive ) == 0 ) + if ( QString::compare( layerProperty, QStringLiteral( "name" ), Qt::CaseInsensitive ) == 0 ) return layer->name(); - else if ( QString::compare( layerProperty, QString( "id" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "id" ), Qt::CaseInsensitive ) == 0 ) return layer->id(); - else if ( QString::compare( layerProperty, QString( "title" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "title" ), Qt::CaseInsensitive ) == 0 ) return layer->title(); - else if ( QString::compare( layerProperty, QString( "abstract" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "abstract" ), Qt::CaseInsensitive ) == 0 ) return layer->abstract(); - else if ( QString::compare( layerProperty, QString( "keywords" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "keywords" ), Qt::CaseInsensitive ) == 0 ) return layer->keywordList(); - else if ( QString::compare( layerProperty, QString( "data_url" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "data_url" ), Qt::CaseInsensitive ) == 0 ) return layer->dataUrl(); - else if ( QString::compare( layerProperty, QString( "attribution" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "attribution" ), Qt::CaseInsensitive ) == 0 ) return layer->attribution(); - else if ( QString::compare( layerProperty, QString( "attribution_url" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "attribution_url" ), Qt::CaseInsensitive ) == 0 ) return layer->attributionUrl(); - else if ( QString::compare( layerProperty, QString( "source" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "source" ), Qt::CaseInsensitive ) == 0 ) return layer->publicSource(); - else if ( QString::compare( layerProperty, QString( "min_scale" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "min_scale" ), Qt::CaseInsensitive ) == 0 ) return layer->minimumScale(); - else if ( QString::compare( layerProperty, QString( "max_scale" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "max_scale" ), Qt::CaseInsensitive ) == 0 ) return layer->maximumScale(); - else if ( QString::compare( layerProperty, QString( "crs" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "crs" ), Qt::CaseInsensitive ) == 0 ) return layer->crs().authid(); - else if ( QString::compare( layerProperty, QString( "crs_definition" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "crs_definition" ), Qt::CaseInsensitive ) == 0 ) return layer->crs().toProj4(); - else if ( QString::compare( layerProperty, QString( "extent" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "extent" ), Qt::CaseInsensitive ) == 0 ) { QgsGeometry extentGeom = QgsGeometry::fromRect( layer->extent() ); QVariant result = QVariant::fromValue( extentGeom ); return result; } - else if ( QString::compare( layerProperty, QString( "type" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "type" ), Qt::CaseInsensitive ) == 0 ) { switch ( layer->type() ) { @@ -3180,11 +3180,11 @@ static QVariant fcnGetLayerProperty( const QVariantList& values, const QgsExpres QgsVectorLayer* vLayer = dynamic_cast< QgsVectorLayer* >( layer ); if ( vLayer ) { - if ( QString::compare( layerProperty, QString( "storage_type" ), Qt::CaseInsensitive ) == 0 ) + if ( QString::compare( layerProperty, QStringLiteral( "storage_type" ), Qt::CaseInsensitive ) == 0 ) return vLayer->storageType(); - else if ( QString::compare( layerProperty, QString( "geometry_type" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "geometry_type" ), Qt::CaseInsensitive ) == 0 ) return QgsWkbTypes::geometryDisplayString( vLayer->geometryType() ); - else if ( QString::compare( layerProperty, QString( "feature_count" ), Qt::CaseInsensitive ) == 0 ) + else if ( QString::compare( layerProperty, QStringLiteral( "feature_count" ), Qt::CaseInsensitive ) == 0 ) return QVariant::fromValue( vLayer->featureCount() ); } } @@ -3400,255 +3400,255 @@ const QList& QgsExpression::Functions() if ( gmFunctions.isEmpty() ) { - ParameterList aggParams = ParameterList() << Parameter( "expression" ) - << Parameter( "group_by", true ) - << Parameter( "filter", true ); + ParameterList aggParams = ParameterList() << Parameter( QStringLiteral( "expression" ) ) + << Parameter( QStringLiteral( "group_by" ), true ) + << Parameter( QStringLiteral( "filter" ), true ); gmFunctions - << new StaticFunction( "sqrt", ParameterList() << Parameter( "value" ), fcnSqrt, "Math" ) - << new StaticFunction( "radians", ParameterList() << Parameter( "degrees" ), fcnRadians, "Math" ) - << new StaticFunction( "degrees", ParameterList() << Parameter( "radians" ), fcnDegrees, "Math" ) - << new StaticFunction( "azimuth", ParameterList() << Parameter( "point_a" ) << Parameter( "point_b" ), fcnAzimuth, QStringList() << "Math" << "GeometryGroup" ) - << new StaticFunction( "project", ParameterList() << Parameter( "point" ) << Parameter( "distance" ) << Parameter( "bearing" ), fcnProject, "GeometryGroup" ) - << new StaticFunction( "abs", ParameterList() << Parameter( "value" ), fcnAbs, "Math" ) - << new StaticFunction( "cos", ParameterList() << Parameter( "angle" ), fcnCos, "Math" ) - << new StaticFunction( "sin", ParameterList() << Parameter( "angle" ), fcnSin, "Math" ) - << new StaticFunction( "tan", ParameterList() << Parameter( "angle" ), fcnTan, "Math" ) - << new StaticFunction( "asin", ParameterList() << Parameter( "value" ), fcnAsin, "Math" ) - << new StaticFunction( "acos", ParameterList() << Parameter( "value" ), fcnAcos, "Math" ) - << new StaticFunction( "atan", ParameterList() << Parameter( "value" ), fcnAtan, "Math" ) - << new StaticFunction( "atan2", ParameterList() << Parameter( "dx" ) << Parameter( "dy" ), fcnAtan2, "Math" ) - << new StaticFunction( "exp", ParameterList() << Parameter( "value" ), fcnExp, "Math" ) - << new StaticFunction( "ln", ParameterList() << Parameter( "value" ), fcnLn, "Math" ) - << new StaticFunction( "log10", ParameterList() << Parameter( "value" ), fcnLog10, "Math" ) - << new StaticFunction( "log", ParameterList() << Parameter( "base" ) << Parameter( "value" ), fcnLog, "Math" ) - << new StaticFunction( "round", ParameterList() << Parameter( "value" ) << Parameter( "places", true, 0 ), fcnRound, "Math" ) - << new StaticFunction( "rand", ParameterList() << Parameter( "min" ) << Parameter( "max" ), fcnRnd, "Math" ) - << new StaticFunction( "randf", ParameterList() << Parameter( "min", true, 0.0 ) << Parameter( "max", true, 1.0 ), fcnRndF, "Math" ) - << new StaticFunction( "max", -1, fcnMax, "Math" ) - << new StaticFunction( "min", -1, fcnMin, "Math" ) - << new StaticFunction( "clamp", ParameterList() << Parameter( "min" ) << Parameter( "value" ) << Parameter( "max" ), fcnClamp, "Math" ) - << new StaticFunction( "scale_linear", 5, fcnLinearScale, "Math" ) - << new StaticFunction( "scale_exp", 6, fcnExpScale, "Math" ) - << new StaticFunction( "floor", 1, fcnFloor, "Math" ) - << new StaticFunction( "ceil", 1, fcnCeil, "Math" ) - << new StaticFunction( "pi", 0, fcnPi, "Math", QString(), false, QSet(), false, QStringList() << "$pi" ) - << new StaticFunction( "to_int", ParameterList() << Parameter( "value" ), fcnToInt, "Conversions", QString(), false, QSet(), false, QStringList() << "toint" ) - << new StaticFunction( "to_real", ParameterList() << Parameter( "value" ), fcnToReal, "Conversions", QString(), false, QSet(), false, QStringList() << "toreal" ) - << new StaticFunction( "to_string", ParameterList() << Parameter( "value" ), fcnToString, QStringList() << "Conversions" << "String", QString(), false, QSet(), false, QStringList() << "tostring" ) - << new StaticFunction( "to_datetime", ParameterList() << Parameter( "value" ), fcnToDateTime, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "todatetime" ) - << new StaticFunction( "to_date", ParameterList() << Parameter( "value" ), fcnToDate, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "todate" ) - << new StaticFunction( "to_time", ParameterList() << Parameter( "value" ), fcnToTime, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "totime" ) - << new StaticFunction( "to_interval", ParameterList() << Parameter( "value" ), fcnToInterval, QStringList() << "Conversions" << "Date and Time", QString(), false, QSet(), false, QStringList() << "tointerval" ) - << new StaticFunction( "coalesce", -1, fcnCoalesce, "Conditionals", QString(), false, QSet(), false, QStringList(), true ) - << new StaticFunction( "if", 3, fcnIf, "Conditionals", QString(), False, QSet(), true ) - << new StaticFunction( "aggregate", ParameterList() << Parameter( "layer" ) << Parameter( "aggregate" ) << Parameter( "expression" ) - << Parameter( "filter", true ) << Parameter( "concatenator", true ), fcnAggregate, "Aggregates", QString(), false, QSet(), true ) - << new StaticFunction( "relation_aggregate", ParameterList() << Parameter( "relation" ) << Parameter( "aggregate" ) << Parameter( "expression" ) << Parameter( "concatenator", true ), - fcnAggregateRelation, "Aggregates", QString(), False, QSet() << QgsFeatureRequest::AllAttributes, true ) - - << new StaticFunction( "count", aggParams, fcnAggregateCount, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "count_distinct", aggParams, fcnAggregateCountDistinct, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "count_missing", aggParams, fcnAggregateCountMissing, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "minimum", aggParams, fcnAggregateMin, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "maximum", aggParams, fcnAggregateMax, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "sum", aggParams, fcnAggregateSum, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "mean", aggParams, fcnAggregateMean, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "median", aggParams, fcnAggregateMedian, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "stdev", aggParams, fcnAggregateStdev, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "range", aggParams, fcnAggregateRange, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "minority", aggParams, fcnAggregateMinority, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "majority", aggParams, fcnAggregateMajority, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "q1", aggParams, fcnAggregateQ1, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "q3", aggParams, fcnAggregateQ3, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "iqr", aggParams, fcnAggregateIQR, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "min_length", aggParams, fcnAggregateMinLength, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "max_length", aggParams, fcnAggregateMaxLength, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "collect", aggParams, fcnAggregateCollectGeometry, "Aggregates", QString(), False, QSet(), true ) - << new StaticFunction( "concatenate", aggParams << Parameter( "concatenator", true ), fcnAggregateStringConcat, "Aggregates", QString(), False, QSet(), true ) - - << new StaticFunction( "regexp_match", ParameterList() << Parameter( "string" ) << Parameter( "regex" ), fcnRegexpMatch, QStringList() << "Conditionals" << "String" ) - << new StaticFunction( "now", 0, fcnNow, "Date and Time", QString(), false, QSet(), false, QStringList() << "$now" ) - << new StaticFunction( "age", 2, fcnAge, "Date and Time" ) - << new StaticFunction( "year", 1, fcnYear, "Date and Time" ) - << new StaticFunction( "month", 1, fcnMonth, "Date and Time" ) - << new StaticFunction( "week", 1, fcnWeek, "Date and Time" ) - << new StaticFunction( "day", 1, fcnDay, "Date and Time" ) - << new StaticFunction( "hour", 1, fcnHour, "Date and Time" ) - << new StaticFunction( "minute", 1, fcnMinute, "Date and Time" ) - << new StaticFunction( "second", 1, fcnSeconds, "Date and Time" ) - << new StaticFunction( "day_of_week", 1, fcnDayOfWeek, "Date and Time" ) - << new StaticFunction( "lower", 1, fcnLower, "String" ) - << new StaticFunction( "upper", 1, fcnUpper, "String" ) - << new StaticFunction( "title", 1, fcnTitle, "String" ) - << new StaticFunction( "trim", 1, fcnTrim, "String" ) - << new StaticFunction( "levenshtein", 2, fcnLevenshtein, "Fuzzy Matching" ) - << new StaticFunction( "longest_common_substring", 2, fcnLCS, "Fuzzy Matching" ) - << new StaticFunction( "hamming_distance", 2, fcnHamming, "Fuzzy Matching" ) - << new StaticFunction( "soundex", 1, fcnSoundex, "Fuzzy Matching" ) - << new StaticFunction( "char", 1, fcnChar, "String" ) - << new StaticFunction( "wordwrap", ParameterList() << Parameter( "text" ) << Parameter( "length" ) << Parameter( "delimiter", true, "" ), fcnWordwrap, "String" ) - << new StaticFunction( "length", ParameterList() << Parameter( "text", true, "" ), fcnLength, QStringList() << "String" << "GeometryGroup" ) - << new StaticFunction( "replace", 3, fcnReplace, "String" ) - << new StaticFunction( "regexp_replace", 3, fcnRegexpReplace, "String" ) - << new StaticFunction( "regexp_substr", 2, fcnRegexpSubstr, "String" ) - << new StaticFunction( "substr", 3, fcnSubstr, "String" ) - << new StaticFunction( "concat", -1, fcnConcat, "String", QString(), false, QSet(), false, QStringList(), true ) - << new StaticFunction( "strpos", 2, fcnStrpos, "String" ) - << new StaticFunction( "left", 2, fcnLeft, "String" ) - << new StaticFunction( "right", 2, fcnRight, "String" ) - << new StaticFunction( "rpad", 3, fcnRPad, "String" ) - << new StaticFunction( "lpad", 3, fcnLPad, "String" ) - << new StaticFunction( "format", -1, fcnFormatString, "String" ) - << new StaticFunction( "format_number", 2, fcnFormatNumber, "String" ) - << new StaticFunction( "format_date", ParameterList() << Parameter( "date" ) << Parameter( "format" ), fcnFormatDate, QStringList() << "String" << "Date and Time" ) - << new StaticFunction( "color_rgb", 3, fcnColorRgb, "Color" ) - << new StaticFunction( "color_rgba", 4, fncColorRgba, "Color" ) - << new StaticFunction( "ramp_color", 2, fcnRampColor, "Color" ) - << new StaticFunction( "color_hsl", 3, fcnColorHsl, "Color" ) - << new StaticFunction( "color_hsla", 4, fncColorHsla, "Color" ) - << new StaticFunction( "color_hsv", 3, fcnColorHsv, "Color" ) - << new StaticFunction( "color_hsva", 4, fncColorHsva, "Color" ) - << new StaticFunction( "color_cmyk", 4, fcnColorCmyk, "Color" ) - << new StaticFunction( "color_cmyka", 5, fncColorCmyka, "Color" ) - << new StaticFunction( "color_part", 2, fncColorPart, "Color" ) - << new StaticFunction( "darker", 2, fncDarker, "Color" ) - << new StaticFunction( "lighter", 2, fncLighter, "Color" ) - << new StaticFunction( "set_color_part", 3, fncSetColorPart, "Color" ) - << new StaticFunction( "$geometry", 0, fcnGeometry, "GeometryGroup", QString(), true ) - << new StaticFunction( "$area", 0, fcnGeomArea, "GeometryGroup", QString(), true ) - << new StaticFunction( "area", 1, fcnArea, "GeometryGroup" ) - << new StaticFunction( "$length", 0, fcnGeomLength, "GeometryGroup", QString(), true ) - << new StaticFunction( "$perimeter", 0, fcnGeomPerimeter, "GeometryGroup", QString(), true ) - << new StaticFunction( "perimeter", 1, fcnPerimeter, "GeometryGroup" ) - << new StaticFunction( "$x", 0, fcnX, "GeometryGroup", QString(), true ) - << new StaticFunction( "$y", 0, fcnY, "GeometryGroup", QString(), true ) - << new StaticFunction( "x", 1, fcnGeomX, "GeometryGroup" ) - << new StaticFunction( "y", 1, fcnGeomY, "GeometryGroup" ) - << new StaticFunction( "z", 1, fcnGeomZ, "GeometryGroup" ) - << new StaticFunction( "m", 1, fcnGeomM, "GeometryGroup" ) - << new StaticFunction( "point_n", 2, fcnPointN, "GeometryGroup" ) - << new StaticFunction( "start_point", 1, fcnStartPoint, "GeometryGroup" ) - << new StaticFunction( "end_point", 1, fcnEndPoint, "GeometryGroup" ) - << new StaticFunction( "nodes_to_points", -1, fcnNodesToPoints, "GeometryGroup" ) - << new StaticFunction( "segments_to_lines", 1, fcnSegmentsToLines, "GeometryGroup" ) - << new StaticFunction( "make_point", -1, fcnMakePoint, "GeometryGroup" ) - << new StaticFunction( "make_point_m", 3, fcnMakePointM, "GeometryGroup" ) - << new StaticFunction( "make_line", -1, fcnMakeLine, "GeometryGroup" ) - << new StaticFunction( "make_polygon", -1, fcnMakePolygon, "GeometryGroup" ) - << new StaticFunction( "$x_at", 1, fcnXat, "GeometryGroup", QString(), true, QSet(), false, QStringList() << "xat" << "x_at" ) - << new StaticFunction( "$y_at", 1, fcnYat, "GeometryGroup", QString(), true, QSet(), false, QStringList() << "yat" << "y_at" ) - << new StaticFunction( "x_min", 1, fcnXMin, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "xmin" ) - << new StaticFunction( "x_max", 1, fcnXMax, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "xmax" ) - << new StaticFunction( "y_min", 1, fcnYMin, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "ymin" ) - << new StaticFunction( "y_max", 1, fcnYMax, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "ymax" ) - << new StaticFunction( "geom_from_wkt", 1, fcnGeomFromWKT, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "geomFromWKT" ) - << new StaticFunction( "geom_from_gml", 1, fcnGeomFromGML, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "geomFromGML" ) - << new StaticFunction( "relate", -1, fcnRelate, "GeometryGroup" ) - << new StaticFunction( "intersects_bbox", 2, fcnBbox, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "bbox" ) - << new StaticFunction( "disjoint", 2, fcnDisjoint, "GeometryGroup" ) - << new StaticFunction( "intersects", 2, fcnIntersects, "GeometryGroup" ) - << new StaticFunction( "touches", 2, fcnTouches, "GeometryGroup" ) - << new StaticFunction( "crosses", 2, fcnCrosses, "GeometryGroup" ) - << new StaticFunction( "contains", 2, fcnContains, "GeometryGroup" ) - << new StaticFunction( "overlaps", 2, fcnOverlaps, "GeometryGroup" ) - << new StaticFunction( "within", 2, fcnWithin, "GeometryGroup" ) - << new StaticFunction( "translate", 3, fcnTranslate, "GeometryGroup" ) - << new StaticFunction( "buffer", -1, fcnBuffer, "GeometryGroup" ) - << new StaticFunction( "offset_curve", ParameterList() << Parameter( "geometry" ) - << Parameter( "distance" ) - << Parameter( "segments", true, 8.0 ) - << Parameter( "join", true, QgsGeometry::JoinStyleRound ) - << Parameter( "mitre_limit", true, 2.0 ), - fcnOffsetCurve, "GeometryGroup" ) - << new StaticFunction( "single_sided_buffer", ParameterList() << Parameter( "geometry" ) - << Parameter( "distance" ) - << Parameter( "segments", true, 8.0 ) - << Parameter( "join", true, QgsGeometry::JoinStyleRound ) - << Parameter( "mitre_limit", true, 2.0 ), - fcnSingleSidedBuffer, "GeometryGroup" ) - << new StaticFunction( "centroid", 1, fcnCentroid, "GeometryGroup" ) - << new StaticFunction( "point_on_surface", 1, fcnPointOnSurface, "GeometryGroup" ) - << new StaticFunction( "reverse", 1, fcnReverse, "GeometryGroup" ) - << new StaticFunction( "exterior_ring", 1, fcnExteriorRing, "GeometryGroup" ) - << new StaticFunction( "interior_ring_n", 2, fcnInteriorRingN, "GeometryGroup" ) - << new StaticFunction( "geometry_n", 2, fcnGeometryN, "GeometryGroup" ) - << new StaticFunction( "boundary", ParameterList() << Parameter( "geometry" ), fcnBoundary, "GeometryGroup" ) - << new StaticFunction( "line_merge", ParameterList() << Parameter( "geometry" ), fcnLineMerge, "GeometryGroup" ) - << new StaticFunction( "bounds", 1, fcnBounds, "GeometryGroup" ) - << new StaticFunction( "simplify", ParameterList() << Parameter( "geometry" ) << Parameter( "tolerance" ), fcnSimplify, "GeometryGroup" ) - << new StaticFunction( "simplify_vw", ParameterList() << Parameter( "geometry" ) << Parameter( "tolerance" ), fcnSimplifyVW, "GeometryGroup" ) - << new StaticFunction( "smooth", ParameterList() << Parameter( "geometry" ) << Parameter( "iterations", true, 1 ) - << Parameter( "offset", true, 0.25 ) - << Parameter( "min_length", true, -1 ) - << Parameter( "max_angle", true, 180 ), fcnSmooth, "GeometryGroup" ) - << new StaticFunction( "num_points", 1, fcnGeomNumPoints, "GeometryGroup" ) - << new StaticFunction( "num_interior_rings", 1, fcnGeomNumInteriorRings, "GeometryGroup" ) - << new StaticFunction( "num_rings", 1, fcnGeomNumRings, "GeometryGroup" ) - << new StaticFunction( "num_geometries", 1, fcnGeomNumGeometries, "GeometryGroup" ) - << new StaticFunction( "bounds_width", 1, fcnBoundsWidth, "GeometryGroup" ) - << new StaticFunction( "bounds_height", 1, fcnBoundsHeight, "GeometryGroup" ) - << new StaticFunction( "is_closed", 1, fcnIsClosed, "GeometryGroup" ) - << new StaticFunction( "convex_hull", 1, fcnConvexHull, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "convexHull" ) - << new StaticFunction( "difference", 2, fcnDifference, "GeometryGroup" ) - << new StaticFunction( "distance", 2, fcnDistance, "GeometryGroup" ) - << new StaticFunction( "intersection", 2, fcnIntersection, "GeometryGroup" ) - << new StaticFunction( "sym_difference", 2, fcnSymDifference, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "symDifference" ) - << new StaticFunction( "combine", 2, fcnCombine, "GeometryGroup" ) - << new StaticFunction( "union", 2, fcnCombine, "GeometryGroup" ) - << new StaticFunction( "geom_to_wkt", -1, fcnGeomToWKT, "GeometryGroup", QString(), false, QSet(), false, QStringList() << "geomToWKT" ) - << new StaticFunction( "geometry", 1, fcnGetGeometry, "GeometryGroup", QString(), true ) - << new StaticFunction( "transform", 3, fcnTransformGeometry, "GeometryGroup" ) - << new StaticFunction( "extrude", 3, fcnExtrude, "GeometryGroup", QString() ) - << new StaticFunction( "order_parts", 3, fcnOrderParts, "GeometryGroup", QString() ) - << new StaticFunction( "closest_point", 2, fcnClosestPoint, "GeometryGroup" ) - << new StaticFunction( "shortest_line", 2, fcnShortestLine, "GeometryGroup" ) - << new StaticFunction( "line_interpolate_point", ParameterList() << Parameter( "geometry" ) - << Parameter( "distance" ), fcnLineInterpolatePoint, "GeometryGroup" ) - << new StaticFunction( "line_interpolate_angle", ParameterList() << Parameter( "geometry" ) - << Parameter( "distance" ), fcnLineInterpolateAngle, "GeometryGroup" ) - << new StaticFunction( "line_locate_point", ParameterList() << Parameter( "geometry" ) - << Parameter( "point" ), fcnLineLocatePoint, "GeometryGroup" ) - << new StaticFunction( "angle_at_vertex", ParameterList() << Parameter( "geometry" ) - << Parameter( "vertex" ), fcnAngleAtVertex, "GeometryGroup" ) - << new StaticFunction( "distance_to_vertex", ParameterList() << Parameter( "geometry" ) - << Parameter( "vertex" ), fcnDistanceToVertex, "GeometryGroup" ) - << new StaticFunction( "$id", 0, fcnFeatureId, "Record" ) - << new StaticFunction( "$currentfeature", 0, fcnFeature, "Record" ) - << new StaticFunction( "uuid", 0, fcnUuid, "Record", QString(), false, QSet(), false, QStringList() << "$uuid" ) - << new StaticFunction( "get_feature", 3, fcnGetFeature, "Record", QString(), false, QSet(), false, QStringList() << "getFeature" ) - << new StaticFunction( "layer_property", 2, fcnGetLayerProperty, "General" ) - << new StaticFunction( "var", 1, fcnGetVariable, "General" ) + << new StaticFunction( QStringLiteral( "sqrt" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnSqrt, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "radians" ), ParameterList() << Parameter( QStringLiteral( "degrees" ) ), fcnRadians, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "degrees" ), ParameterList() << Parameter( QStringLiteral( "radians" ) ), fcnDegrees, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "azimuth" ), ParameterList() << Parameter( QStringLiteral( "point_a" ) ) << Parameter( QStringLiteral( "point_b" ) ), fcnAzimuth, QStringList() << QStringLiteral( "Math" ) << QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "project" ), ParameterList() << Parameter( QStringLiteral( "point" ) ) << Parameter( QStringLiteral( "distance" ) ) << Parameter( QStringLiteral( "bearing" ) ), fcnProject, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "abs" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnAbs, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "cos" ), ParameterList() << Parameter( QStringLiteral( "angle" ) ), fcnCos, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "sin" ), ParameterList() << Parameter( QStringLiteral( "angle" ) ), fcnSin, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "tan" ), ParameterList() << Parameter( QStringLiteral( "angle" ) ), fcnTan, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "asin" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnAsin, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "acos" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnAcos, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "atan" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnAtan, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "atan2" ), ParameterList() << Parameter( QStringLiteral( "dx" ) ) << Parameter( QStringLiteral( "dy" ) ), fcnAtan2, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "exp" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnExp, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "ln" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnLn, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "log10" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnLog10, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "log" ), ParameterList() << Parameter( QStringLiteral( "base" ) ) << Parameter( QStringLiteral( "value" ) ), fcnLog, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "round" ), ParameterList() << Parameter( QStringLiteral( "value" ) ) << Parameter( QStringLiteral( "places" ), true, 0 ), fcnRound, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "rand" ), ParameterList() << Parameter( QStringLiteral( "min" ) ) << Parameter( QStringLiteral( "max" ) ), fcnRnd, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "randf" ), ParameterList() << Parameter( QStringLiteral( "min" ), true, 0.0 ) << Parameter( QStringLiteral( "max" ), true, 1.0 ), fcnRndF, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "max" ), -1, fcnMax, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "min" ), -1, fcnMin, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "clamp" ), ParameterList() << Parameter( QStringLiteral( "min" ) ) << Parameter( QStringLiteral( "value" ) ) << Parameter( QStringLiteral( "max" ) ), fcnClamp, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "scale_linear" ), 5, fcnLinearScale, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "scale_exp" ), 6, fcnExpScale, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "floor" ), 1, fcnFloor, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "ceil" ), 1, fcnCeil, QStringLiteral( "Math" ) ) + << new StaticFunction( QStringLiteral( "pi" ), 0, fcnPi, QStringLiteral( "Math" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "$pi" ) ) + << new StaticFunction( QStringLiteral( "to_int" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToInt, QStringLiteral( "Conversions" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "toint" ) ) + << new StaticFunction( QStringLiteral( "to_real" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToReal, QStringLiteral( "Conversions" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "toreal" ) ) + << new StaticFunction( QStringLiteral( "to_string" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToString, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "String" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "tostring" ) ) + << new StaticFunction( QStringLiteral( "to_datetime" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToDateTime, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "todatetime" ) ) + << new StaticFunction( QStringLiteral( "to_date" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToDate, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "todate" ) ) + << new StaticFunction( QStringLiteral( "to_time" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToTime, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "totime" ) ) + << new StaticFunction( QStringLiteral( "to_interval" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToInterval, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "tointerval" ) ) + << new StaticFunction( QStringLiteral( "coalesce" ), -1, fcnCoalesce, QStringLiteral( "Conditionals" ), QString(), false, QSet(), false, QStringList(), true ) + << new StaticFunction( QStringLiteral( "if" ), 3, fcnIf, QStringLiteral( "Conditionals" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "aggregate" ), ParameterList() << Parameter( QStringLiteral( "layer" ) ) << Parameter( QStringLiteral( "aggregate" ) ) << Parameter( QStringLiteral( "expression" ) ) + << Parameter( QStringLiteral( "filter" ), true ) << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregate, QStringLiteral( "Aggregates" ), QString(), false, QSet(), true ) + << new StaticFunction( QStringLiteral( "relation_aggregate" ), ParameterList() << Parameter( QStringLiteral( "relation" ) ) << Parameter( QStringLiteral( "aggregate" ) ) << Parameter( QStringLiteral( "expression" ) ) << Parameter( QStringLiteral( "concatenator" ), true ), + fcnAggregateRelation, QStringLiteral( "Aggregates" ), QString(), False, QSet() << QgsFeatureRequest::AllAttributes, true ) + + << new StaticFunction( QStringLiteral( "count" ), aggParams, fcnAggregateCount, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "count_distinct" ), aggParams, fcnAggregateCountDistinct, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "count_missing" ), aggParams, fcnAggregateCountMissing, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "minimum" ), aggParams, fcnAggregateMin, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "maximum" ), aggParams, fcnAggregateMax, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "sum" ), aggParams, fcnAggregateSum, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "mean" ), aggParams, fcnAggregateMean, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "median" ), aggParams, fcnAggregateMedian, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "stdev" ), aggParams, fcnAggregateStdev, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "range" ), aggParams, fcnAggregateRange, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "minority" ), aggParams, fcnAggregateMinority, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "majority" ), aggParams, fcnAggregateMajority, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "q1" ), aggParams, fcnAggregateQ1, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "q3" ), aggParams, fcnAggregateQ3, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "iqr" ), aggParams, fcnAggregateIQR, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "min_length" ), aggParams, fcnAggregateMinLength, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "max_length" ), aggParams, fcnAggregateMaxLength, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "collect" ), aggParams, fcnAggregateCollectGeometry, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "concatenate" ), aggParams << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregateStringConcat, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) + + << new StaticFunction( QStringLiteral( "regexp_match" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "regex" ) ), fcnRegexpMatch, QStringList() << QStringLiteral( "Conditionals" ) << QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "now" ), 0, fcnNow, QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "$now" ) ) + << new StaticFunction( QStringLiteral( "age" ), 2, fcnAge, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "year" ), 1, fcnYear, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "month" ), 1, fcnMonth, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "week" ), 1, fcnWeek, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "day" ), 1, fcnDay, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "hour" ), 1, fcnHour, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "minute" ), 1, fcnMinute, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "second" ), 1, fcnSeconds, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "day_of_week" ), 1, fcnDayOfWeek, QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "lower" ), 1, fcnLower, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "upper" ), 1, fcnUpper, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "title" ), 1, fcnTitle, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "trim" ), 1, fcnTrim, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "levenshtein" ), 2, fcnLevenshtein, QStringLiteral( "Fuzzy Matching" ) ) + << new StaticFunction( QStringLiteral( "longest_common_substring" ), 2, fcnLCS, QStringLiteral( "Fuzzy Matching" ) ) + << new StaticFunction( QStringLiteral( "hamming_distance" ), 2, fcnHamming, QStringLiteral( "Fuzzy Matching" ) ) + << new StaticFunction( QStringLiteral( "soundex" ), 1, fcnSoundex, QStringLiteral( "Fuzzy Matching" ) ) + << new StaticFunction( QStringLiteral( "char" ), 1, fcnChar, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "wordwrap" ), ParameterList() << Parameter( QStringLiteral( "text" ) ) << Parameter( QStringLiteral( "length" ) ) << Parameter( QStringLiteral( "delimiter" ), true, "" ), fcnWordwrap, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "length" ), ParameterList() << Parameter( QStringLiteral( "text" ), true, "" ), fcnLength, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "replace" ), 3, fcnReplace, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "regexp_replace" ), 3, fcnRegexpReplace, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "regexp_substr" ), 2, fcnRegexpSubstr, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "substr" ), 3, fcnSubstr, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "concat" ), -1, fcnConcat, QStringLiteral( "String" ), QString(), false, QSet(), false, QStringList(), true ) + << new StaticFunction( QStringLiteral( "strpos" ), 2, fcnStrpos, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "left" ), 2, fcnLeft, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "right" ), 2, fcnRight, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "rpad" ), 3, fcnRPad, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "lpad" ), 3, fcnLPad, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "format" ), -1, fcnFormatString, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "format_number" ), 2, fcnFormatNumber, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "format_date" ), ParameterList() << Parameter( QStringLiteral( "date" ) ) << Parameter( QStringLiteral( "format" ) ), fcnFormatDate, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "Date and Time" ) ) + << new StaticFunction( QStringLiteral( "color_rgb" ), 3, fcnColorRgb, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_rgba" ), 4, fncColorRgba, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "ramp_color" ), 2, fcnRampColor, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_hsl" ), 3, fcnColorHsl, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_hsla" ), 4, fncColorHsla, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_hsv" ), 3, fcnColorHsv, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_hsva" ), 4, fncColorHsva, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_cmyk" ), 4, fcnColorCmyk, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_cmyka" ), 5, fncColorCmyka, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "color_part" ), 2, fncColorPart, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "darker" ), 2, fncDarker, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "lighter" ), 2, fncLighter, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "set_color_part" ), 3, fncSetColorPart, QStringLiteral( "Color" ) ) + << new StaticFunction( QStringLiteral( "$geometry" ), 0, fcnGeometry, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "$area" ), 0, fcnGeomArea, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "area" ), 1, fcnArea, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "$length" ), 0, fcnGeomLength, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "$perimeter" ), 0, fcnGeomPerimeter, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "perimeter" ), 1, fcnPerimeter, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "$x" ), 0, fcnX, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "$y" ), 0, fcnY, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "x" ), 1, fcnGeomX, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "y" ), 1, fcnGeomY, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "z" ), 1, fcnGeomZ, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "m" ), 1, fcnGeomM, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "point_n" ), 2, fcnPointN, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "start_point" ), 1, fcnStartPoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "end_point" ), 1, fcnEndPoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "nodes_to_points" ), -1, fcnNodesToPoints, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "segments_to_lines" ), 1, fcnSegmentsToLines, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "make_point" ), -1, fcnMakePoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "make_point_m" ), 3, fcnMakePointM, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "make_line" ), -1, fcnMakeLine, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "make_polygon" ), -1, fcnMakePolygon, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "$x_at" ), 1, fcnXat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet(), false, QStringList() << QStringLiteral( "xat" ) << QStringLiteral( "x_at" ) ) + << new StaticFunction( QStringLiteral( "$y_at" ), 1, fcnYat, QStringLiteral( "GeometryGroup" ), QString(), true, QSet(), false, QStringList() << QStringLiteral( "yat" ) << QStringLiteral( "y_at" ) ) + << new StaticFunction( QStringLiteral( "x_min" ), 1, fcnXMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "xmin" ) ) + << new StaticFunction( QStringLiteral( "x_max" ), 1, fcnXMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "xmax" ) ) + << new StaticFunction( QStringLiteral( "y_min" ), 1, fcnYMin, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "ymin" ) ) + << new StaticFunction( QStringLiteral( "y_max" ), 1, fcnYMax, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "ymax" ) ) + << new StaticFunction( QStringLiteral( "geom_from_wkt" ), 1, fcnGeomFromWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "geomFromWKT" ) ) + << new StaticFunction( QStringLiteral( "geom_from_gml" ), 1, fcnGeomFromGML, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "geomFromGML" ) ) + << new StaticFunction( QStringLiteral( "relate" ), -1, fcnRelate, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "intersects_bbox" ), 2, fcnBbox, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "bbox" ) ) + << new StaticFunction( QStringLiteral( "disjoint" ), 2, fcnDisjoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "intersects" ), 2, fcnIntersects, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "touches" ), 2, fcnTouches, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "crosses" ), 2, fcnCrosses, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "contains" ), 2, fcnContains, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "overlaps" ), 2, fcnOverlaps, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "within" ), 2, fcnWithin, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "translate" ), 3, fcnTranslate, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "buffer" ), -1, fcnBuffer, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "offset_curve" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "distance" ) ) + << Parameter( QStringLiteral( "segments" ), true, 8.0 ) + << Parameter( QStringLiteral( "join" ), true, QgsGeometry::JoinStyleRound ) + << Parameter( QStringLiteral( "mitre_limit" ), true, 2.0 ), + fcnOffsetCurve, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "single_sided_buffer" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "distance" ) ) + << Parameter( QStringLiteral( "segments" ), true, 8.0 ) + << Parameter( QStringLiteral( "join" ), true, QgsGeometry::JoinStyleRound ) + << Parameter( QStringLiteral( "mitre_limit" ), true, 2.0 ), + fcnSingleSidedBuffer, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "centroid" ), 1, fcnCentroid, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "point_on_surface" ), 1, fcnPointOnSurface, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "reverse" ), 1, fcnReverse, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "exterior_ring" ), 1, fcnExteriorRing, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "interior_ring_n" ), 2, fcnInteriorRingN, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "geometry_n" ), 2, fcnGeometryN, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "boundary" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ), fcnBoundary, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "line_merge" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ), fcnLineMerge, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "bounds" ), 1, fcnBounds, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "simplify" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) << Parameter( QStringLiteral( "tolerance" ) ), fcnSimplify, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "simplify_vw" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) << Parameter( QStringLiteral( "tolerance" ) ), fcnSimplifyVW, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "smooth" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) << Parameter( QStringLiteral( "iterations" ), true, 1 ) + << Parameter( QStringLiteral( "offset" ), true, 0.25 ) + << Parameter( QStringLiteral( "min_length" ), true, -1 ) + << Parameter( QStringLiteral( "max_angle" ), true, 180 ), fcnSmooth, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "num_points" ), 1, fcnGeomNumPoints, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "num_interior_rings" ), 1, fcnGeomNumInteriorRings, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "num_rings" ), 1, fcnGeomNumRings, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "num_geometries" ), 1, fcnGeomNumGeometries, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "bounds_width" ), 1, fcnBoundsWidth, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "bounds_height" ), 1, fcnBoundsHeight, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "is_closed" ), 1, fcnIsClosed, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "convex_hull" ), 1, fcnConvexHull, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "convexHull" ) ) + << new StaticFunction( QStringLiteral( "difference" ), 2, fcnDifference, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "distance" ), 2, fcnDistance, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "intersection" ), 2, fcnIntersection, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "sym_difference" ), 2, fcnSymDifference, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "symDifference" ) ) + << new StaticFunction( QStringLiteral( "combine" ), 2, fcnCombine, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "union" ), 2, fcnCombine, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "geom_to_wkt" ), -1, fcnGeomToWKT, QStringLiteral( "GeometryGroup" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "geomToWKT" ) ) + << new StaticFunction( QStringLiteral( "geometry" ), 1, fcnGetGeometry, QStringLiteral( "GeometryGroup" ), QString(), true ) + << new StaticFunction( QStringLiteral( "transform" ), 3, fcnTransformGeometry, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "extrude" ), 3, fcnExtrude, QStringLiteral( "GeometryGroup" ), QString() ) + << new StaticFunction( QStringLiteral( "order_parts" ), 3, fcnOrderParts, QStringLiteral( "GeometryGroup" ), QString() ) + << new StaticFunction( QStringLiteral( "closest_point" ), 2, fcnClosestPoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "shortest_line" ), 2, fcnShortestLine, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "line_interpolate_point" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolatePoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "line_interpolate_angle" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "distance" ) ), fcnLineInterpolateAngle, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "line_locate_point" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "point" ) ), fcnLineLocatePoint, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "angle_at_vertex" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "vertex" ) ), fcnAngleAtVertex, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "distance_to_vertex" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "vertex" ) ), fcnDistanceToVertex, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "$id" ), 0, fcnFeatureId, QStringLiteral( "Record" ) ) + << new StaticFunction( QStringLiteral( "$currentfeature" ), 0, fcnFeature, QStringLiteral( "Record" ) ) + << new StaticFunction( QStringLiteral( "uuid" ), 0, fcnUuid, QStringLiteral( "Record" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "$uuid" ) ) + << new StaticFunction( QStringLiteral( "get_feature" ), 3, fcnGetFeature, QStringLiteral( "Record" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "getFeature" ) ) + << new StaticFunction( QStringLiteral( "layer_property" ), 2, fcnGetLayerProperty, QStringLiteral( "General" ) ) + << new StaticFunction( QStringLiteral( "var" ), 1, fcnGetVariable, QStringLiteral( "General" ) ) //return all attributes string for referencedColumns - this is caught by // QgsFeatureRequest::setSubsetOfAttributes and causes all attributes to be fetched by the // feature request - << new StaticFunction( "eval", 1, fcnEval, "General", QString(), true, QSet() << QgsFeatureRequest::AllAttributes ) - << new StaticFunction( "attribute", 2, fcnAttribute, "Record", QString(), false, QSet() << QgsFeatureRequest::AllAttributes ) + << new StaticFunction( QStringLiteral( "eval" ), 1, fcnEval, QStringLiteral( "General" ), QString(), true, QSet() << QgsFeatureRequest::AllAttributes ) + << new StaticFunction( QStringLiteral( "attribute" ), 2, fcnAttribute, QStringLiteral( "Record" ), QString(), false, QSet() << QgsFeatureRequest::AllAttributes ) // functions for arrays - << new StaticFunction( "array", -1, fcnArray, "Arrays" ) - << new StaticFunction( "array_length", 1, fcnArrayLength, "Arrays" ) - << new StaticFunction( "array_contains", ParameterList() << Parameter( "array" ) << Parameter( "value" ), fcnArrayContains, "Arrays" ) - << new StaticFunction( "array_find", ParameterList() << Parameter( "array" ) << Parameter( "value" ), fcnArrayFind, "Arrays" ) - << new StaticFunction( "array_get", ParameterList() << Parameter( "array" ) << Parameter( "pos" ), fcnArrayGet, "Arrays" ) - << new StaticFunction( "array_append", ParameterList() << Parameter( "array" ) << Parameter( "value" ), fcnArrayAppend, "Arrays" ) - << new StaticFunction( "array_prepend", ParameterList() << Parameter( "array" ) << Parameter( "value" ), fcnArrayPrepend, "Arrays" ) - << new StaticFunction( "array_insert", ParameterList() << Parameter( "array" ) << Parameter( "pos" ) << Parameter( "value" ), fcnArrayInsert, "Arrays" ) - << new StaticFunction( "array_remove_at", ParameterList() << Parameter( "array" ) << Parameter( "pos" ), fcnArrayRemoveAt, "Arrays" ) - << new StaticFunction( "array_remove_all", ParameterList() << Parameter( "array" ) << Parameter( "value" ), fcnArrayRemoveAll, "Arrays" ) - << new StaticFunction( "array_cat", -1, fcnArrayCat, "Arrays" ) - << new StaticFunction( "array_intersect", ParameterList() << Parameter( "array1" ) << Parameter( "array2" ), fcnArrayIntersect, "Arrays" ) + << new StaticFunction( QStringLiteral( "array" ), -1, fcnArray, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_length" ), 1, fcnArrayLength, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_contains" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayContains, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_find" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayFind, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_get" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "pos" ) ), fcnArrayGet, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_append" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayAppend, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_prepend" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayPrepend, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_insert" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "pos" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayInsert, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_remove_at" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "pos" ) ), fcnArrayRemoveAt, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_remove_all" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayRemoveAll, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_cat" ), -1, fcnArrayCat, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_intersect" ), ParameterList() << Parameter( QStringLiteral( "array1" ) ) << Parameter( QStringLiteral( "array2" ) ), fcnArrayIntersect, QStringLiteral( "Arrays" ) ) //functions for maps - << new StaticFunction( "map", -1, fcnMap, "Maps" ) - << new StaticFunction( "map_get", ParameterList() << Parameter( "map" ) << Parameter( "key" ), fcnMapGet, "Maps" ) - << new StaticFunction( "map_exist", ParameterList() << Parameter( "map" ) << Parameter( "key" ), fcnMapExist, "Maps" ) - << new StaticFunction( "map_delete", ParameterList() << Parameter( "map" ) << Parameter( "key" ), fcnMapDelete, "Maps" ) - << new StaticFunction( "map_insert", ParameterList() << Parameter( "map" ) << Parameter( "key" ) << Parameter( "value" ), fcnMapInsert, "Maps" ) - << new StaticFunction( "map_concat", -1, fcnMapConcat, "Maps" ) - << new StaticFunction( "map_akeys", ParameterList() << Parameter( "map" ), fcnMapAKeys, "Maps" ) - << new StaticFunction( "map_avals", ParameterList() << Parameter( "map" ), fcnMapAVals, "Maps" ) + << new StaticFunction( QStringLiteral( "map" ), -1, fcnMap, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_get" ), ParameterList() << Parameter( QStringLiteral( "map" ) ) << Parameter( QStringLiteral( "key" ) ), fcnMapGet, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_exist" ), ParameterList() << Parameter( QStringLiteral( "map" ) ) << Parameter( QStringLiteral( "key" ) ), fcnMapExist, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_delete" ), ParameterList() << Parameter( QStringLiteral( "map" ) ) << Parameter( QStringLiteral( "key" ) ), fcnMapDelete, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_insert" ), ParameterList() << Parameter( QStringLiteral( "map" ) ) << Parameter( QStringLiteral( "key" ) ) << Parameter( QStringLiteral( "value" ) ), fcnMapInsert, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_concat" ), -1, fcnMapConcat, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_akeys" ), ParameterList() << Parameter( QStringLiteral( "map" ) ), fcnMapAKeys, QStringLiteral( "Maps" ) ) + << new StaticFunction( QStringLiteral( "map_avals" ), ParameterList() << Parameter( QStringLiteral( "map" ) ), fcnMapAVals, QStringLiteral( "Maps" ) ) ; QgsExpressionContextUtils::registerContextFunctions(); @@ -3690,16 +3690,16 @@ QString QgsExpression::expression() const QString QgsExpression::quotedColumnRef( QString name ) { - return QString( "\"%1\"" ).arg( name.replace( '\"', "\"\"" ) ); + return QStringLiteral( "\"%1\"" ).arg( name.replace( '\"', QLatin1String( "\"\"" ) ) ); } QString QgsExpression::quotedString( QString text ) { - text.replace( '\'', "''" ); - text.replace( '\\', "\\\\" ); - text.replace( '\n', "\\n" ); - text.replace( '\t', "\\t" ); - return QString( "'%1'" ).arg( text ); + text.replace( '\'', QLatin1String( "''" ) ); + text.replace( '\\', QLatin1String( "\\\\" ) ); + text.replace( '\n', QLatin1String( "\\n" ) ); + text.replace( '\t', QLatin1String( "\\t" ) ); + return QStringLiteral( "'%1'" ).arg( text ); } QString QgsExpression::quotedValue( const QVariant &value ) @@ -3710,7 +3710,7 @@ QString QgsExpression::quotedValue( const QVariant &value ) QString QgsExpression::quotedValue( const QVariant& value, QVariant::Type type ) { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( type ) { @@ -4078,7 +4078,7 @@ QString QgsExpression::NodeList::dump() const bool first = true; Q_FOREACH ( Node* n, mList ) { - if ( !first ) msg += ", "; + if ( !first ) msg += QLatin1String( ", " ); else first = false; msg += n->dump(); } @@ -4122,7 +4122,7 @@ bool QgsExpression::NodeUnaryOperator::prepare( QgsExpression *parent, const Qgs QString QgsExpression::NodeUnaryOperator::dump() const { - return QString( "%1 %2" ).arg( UnaryOperatorText[mOp], mOperand->dump() ); + return QStringLiteral( "%1 %2" ).arg( UnaryOperatorText[mOp], mOperand->dump() ); } QgsExpression::Node*QgsExpression::NodeUnaryOperator::clone() const @@ -4353,30 +4353,30 @@ QVariant QgsExpression::NodeBinaryOperator::eval( QgsExpression *parent, const Q // manage escape % and _ if ( esc_regexp.startsWith( '%' ) ) { - esc_regexp.replace( 0, 1, ".*" ); + esc_regexp.replace( 0, 1, QStringLiteral( ".*" ) ); } QRegExp rx( "[^\\\\](%)" ); int pos = 0; while (( pos = rx.indexIn( esc_regexp, pos ) ) != -1 ) { - esc_regexp.replace( pos + 1, 1, ".*" ); + esc_regexp.replace( pos + 1, 1, QStringLiteral( ".*" ) ); pos += 1; } - rx.setPattern( "\\\\%" ); - esc_regexp.replace( rx, "%" ); + rx.setPattern( QStringLiteral( "\\\\%" ) ); + esc_regexp.replace( rx, QStringLiteral( "%" ) ); if ( esc_regexp.startsWith( '_' ) ) { - esc_regexp.replace( 0, 1, "." ); + esc_regexp.replace( 0, 1, QStringLiteral( "." ) ); } - rx.setPattern( "[^\\\\](_)" ); + rx.setPattern( QStringLiteral( "[^\\\\](_)" ) ); pos = 0; while (( pos = rx.indexIn( esc_regexp, pos ) ) != -1 ) { esc_regexp.replace( pos + 1, 1, '.' ); pos += 1; } - rx.setPattern( "\\\\_" ); - esc_regexp.replace( rx, "_" ); + rx.setPattern( QStringLiteral( "\\\\_" ) ); + esc_regexp.replace( rx, QStringLiteral( "_" ) ); matches = QRegExp( esc_regexp, mOp == boLike || mOp == boNotLike ? Qt::CaseSensitive : Qt::CaseInsensitive ).exactMatch( str ); } else @@ -4594,13 +4594,13 @@ QString QgsExpression::NodeBinaryOperator::dump() const if ( leftAssociative() ) { fmt += lOp && ( lOp->precedence() < precedence() ) ? "(%1)" : "%1"; - fmt += " %2 "; + fmt += QLatin1String( " %2 " ); fmt += rOp && ( rOp->precedence() <= precedence() ) ? "(%3)" : "%3"; } else { fmt += lOp && ( lOp->precedence() <= precedence() ) ? "(%1)" : "%1"; - fmt += " %2 "; + fmt += QLatin1String( " %2 " ); fmt += rOp && ( rOp->precedence() < precedence() ) ? "(%3)" : "%3"; } @@ -4686,7 +4686,7 @@ bool QgsExpression::NodeInOperator::prepare( QgsExpression *parent, const QgsExp QString QgsExpression::NodeInOperator::dump() const { - return QString( "%1 %2 IN (%3)" ).arg( mNode->dump(), mNotIn ? "NOT" : "", mList->dump() ); + return QStringLiteral( "%1 %2 IN (%3)" ).arg( mNode->dump(), mNotIn ? "NOT" : "", mList->dump() ); } QgsExpression::Node*QgsExpression::NodeInOperator::clone() const @@ -4791,9 +4791,9 @@ QString QgsExpression::NodeFunction::dump() const { Function* fd = Functions()[mFnIndex]; if ( fd->params() == 0 ) - return QString( "%1%2" ).arg( fd->name(), fd->name().startsWith( '$' ) ? "" : "()" ); // special column + return QStringLiteral( "%1%2" ).arg( fd->name(), fd->name().startsWith( '$' ) ? "" : "()" ); // special column else - return QString( "%1(%2)" ).arg( fd->name(), mArgs ? mArgs->dump() : QString() ); // function + return QStringLiteral( "%1(%2)" ).arg( fd->name(), mArgs ? mArgs->dump() : QString() ); // function } QSet QgsExpression::NodeFunction::referencedColumns() const @@ -4839,7 +4839,7 @@ bool QgsExpression::NodeFunction::validateParams( int fnIndex, QgsExpression::No const ParameterList& functionParams = Functions()[fnIndex]->parameters(); if ( functionParams.isEmpty() ) { - error = QString( "%1 does not supported named parameters" ).arg( Functions()[fnIndex]->name() ); + error = QStringLiteral( "%1 does not supported named parameters" ).arg( Functions()[fnIndex]->name() ); return false; } else @@ -4863,7 +4863,7 @@ bool QgsExpression::NodeFunction::validateParams( int fnIndex, QgsExpression::No { if ( !functionParams.at( idx ).optional() ) { - error = QString( "No value specified for parameter '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); + error = QStringLiteral( "No value specified for parameter '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); return false; } } @@ -4871,7 +4871,7 @@ bool QgsExpression::NodeFunction::validateParams( int fnIndex, QgsExpression::No { if ( providedArgs.contains( idx ) ) { - error = QString( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); + error = QStringLiteral( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( idx ).name(), Functions()[fnIndex]->name() ); return false; } } @@ -4885,7 +4885,7 @@ bool QgsExpression::NodeFunction::validateParams( int fnIndex, QgsExpression::No { if ( !name.isEmpty() && !functionParams.contains( name ) ) { - error = QString( "Invalid parameter name '%1' for %2" ).arg( name, Functions()[fnIndex]->name() ); + error = QStringLiteral( "Invalid parameter name '%1' for %2" ).arg( name, Functions()[fnIndex]->name() ); return false; } if ( !name.isEmpty() && !handledArgs.contains( idx ) ) @@ -4893,7 +4893,7 @@ bool QgsExpression::NodeFunction::validateParams( int fnIndex, QgsExpression::No int functionIdx = functionParams.indexOf( name ); if ( providedArgs.contains( functionIdx ) ) { - error = QString( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( functionIdx ).name(), Functions()[fnIndex]->name() ); + error = QStringLiteral( "Duplicate parameter specified for '%1' for %2" ).arg( functionParams.at( functionIdx ).name(), Functions()[fnIndex]->name() ); return false; } } @@ -4924,7 +4924,7 @@ bool QgsExpression::NodeLiteral::prepare( QgsExpression *parent, const QgsExpres QString QgsExpression::NodeLiteral::dump() const { if ( mValue.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( mValue.type() ) { @@ -5050,14 +5050,14 @@ bool QgsExpression::NodeCondition::prepare( QgsExpression *parent, const QgsExpr QString QgsExpression::NodeCondition::dump() const { - QString msg( "CASE" ); + QString msg( QStringLiteral( "CASE" ) ); Q_FOREACH ( WhenThen* cond, mConditions ) { - msg += QString( " WHEN %1 THEN %2" ).arg( cond->mWhenExp->dump(), cond->mThenExp->dump() ); + msg += QStringLiteral( " WHEN %1 THEN %2" ).arg( cond->mWhenExp->dump(), cond->mThenExp->dump() ); } if ( mElseExp ) - msg += QString( " ELSE %1" ).arg( mElseExp->dump() ); - msg += QString( " END" ); + msg += QStringLiteral( " ELSE %1" ).arg( mElseExp->dump() ); + msg += QStringLiteral( " END" ); return msg; } @@ -5114,7 +5114,7 @@ QString QgsExpression::helpText( QString name ) name = name.toHtmlEscaped(); - QString helpContents( QString( "

                                                                                                                                                                                    \n" ).arg( tr( "Syntax" ) ); + helpContents += QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n
                                                                                                                                                                                    \n" ).arg( tr( "Syntax" ) ); if ( f.mType == tr( "operator" ) ) { if ( v.mArguments.size() == 1 ) { - helpContents += QString( "%1 %2" ) + helpContents += QStringLiteral( "%1 %2" ) .arg( name, v.mArguments[0].mArg ); } else if ( v.mArguments.size() == 2 ) { - helpContents += QString( "%1 %2 %3" ) + helpContents += QStringLiteral( "%1 %2 %3" ) .arg( v.mArguments[0].mArg, name, v.mArguments[1].mArg ); } } else if ( f.mType != tr( "group" ) && f.mType != tr( "expression" ) ) { - helpContents += QString( "%1" ).arg( name ); + helpContents += QStringLiteral( "%1" ).arg( name ); if ( f.mType == tr( "function" ) && ( f.mName[0] != '$' || !v.mArguments.isEmpty() || v.mVariableLenArguments ) ) { @@ -5153,60 +5153,60 @@ QString QgsExpression::helpText( QString name ) Q_FOREACH ( const HelpArg &a, v.mArguments ) { helpContents += delim; - delim = ", "; + delim = QStringLiteral( ", " ); if ( !a.mDescOnly ) { - helpContents += QString( "%2%3" ).arg( a.mOptional ? "optional" : "", a.mArg, - a.mDefaultVal.isEmpty() ? "" : '=' + a.mDefaultVal ); + helpContents += QStringLiteral( "%2%3" ).arg( a.mOptional ? "optional" : "", a.mArg, + a.mDefaultVal.isEmpty() ? QLatin1String( "" ) : '=' + a.mDefaultVal ); } } if ( v.mVariableLenArguments ) { - helpContents += "..."; + helpContents += QLatin1String( "..." ); } helpContents += ')'; } - helpContents += ""; + helpContents += QLatin1String( "" ); } if ( !v.mArguments.isEmpty() ) { - helpContents += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n
                                                                                                                                                                                    \n" ).arg( tr( "Arguments" ) ); + helpContents += QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n
                                                                                                                                                                                    \n
                                                                                                                                                                                    " ).arg( tr( "Arguments" ) ); Q_FOREACH ( const HelpArg &a, v.mArguments ) { if ( a.mSyntaxOnly ) continue; - helpContents += QString( "" ).arg( a.mArg, a.mDescription ); + helpContents += QStringLiteral( "" ).arg( a.mArg, a.mDescription ); } - helpContents += "
                                                                                                                                                                                    %1%2
                                                                                                                                                                                    %1%2
                                                                                                                                                                                    \n
                                                                                                                                                                                    \n"; + helpContents += QLatin1String( "\n
                                                                                                                                                                                    \n" ); } if ( !v.mExamples.isEmpty() ) { - helpContents += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n
                                                                                                                                                                                    \n
                                                                                                                                                                                      \n" ).arg( tr( "Examples" ) ); + helpContents += QStringLiteral( "

                                                                                                                                                                                      %1

                                                                                                                                                                                      \n
                                                                                                                                                                                      \n
                                                                                                                                                                                        \n" ).arg( tr( "Examples" ) ); Q_FOREACH ( const HelpExample &e, v.mExamples ) { helpContents += "
                                                                                                                                                                                      • " + e.mExpression + "" + e.mReturns + ""; if ( !e.mNote.isEmpty() ) - helpContents += QString( " (%1)" ).arg( e.mNote ); + helpContents += QStringLiteral( " (%1)" ).arg( e.mNote ); - helpContents += "
                                                                                                                                                                                      • \n"; + helpContents += QLatin1String( "\n" ); } - helpContents += "
                                                                                                                                                                                      \n
                                                                                                                                                                                      \n"; + helpContents += QLatin1String( "
                                                                                                                                                                                    \n
                                                                                                                                                                                    \n" ); } if ( !v.mNotes.isEmpty() ) { - helpContents += QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n

                                                                                                                                                                                    %2

                                                                                                                                                                                    \n" ).arg( tr( "Notes" ), v.mNotes ); + helpContents += QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    \n

                                                                                                                                                                                    %2

                                                                                                                                                                                    \n" ).arg( tr( "Notes" ), v.mNotes ); } } @@ -5221,78 +5221,78 @@ void QgsExpression::initVariableHelp() return; //global variables - gVariableHelpTexts.insert( "qgis_version", QCoreApplication::translate( "variable_help", "Current QGIS version string." ) ); - gVariableHelpTexts.insert( "qgis_version_no", QCoreApplication::translate( "variable_help", "Current QGIS version number." ) ); - gVariableHelpTexts.insert( "qgis_release_name", QCoreApplication::translate( "variable_help", "Current QGIS release name." ) ); - gVariableHelpTexts.insert( "qgis_os_name", QCoreApplication::translate( "variable_help", "Operating system name, eg 'windows', 'linux' or 'osx'." ) ); - gVariableHelpTexts.insert( "qgis_platform", QCoreApplication::translate( "variable_help", "QGIS platform, eg 'desktop' or 'server'." ) ); - gVariableHelpTexts.insert( "user_account_name", QCoreApplication::translate( "variable_help", "Current user's operating system account name." ) ); - gVariableHelpTexts.insert( "user_full_name", QCoreApplication::translate( "variable_help", "Current user's operating system user name (if available)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "qgis_version" ), QCoreApplication::translate( "variable_help", "Current QGIS version string." ) ); + gVariableHelpTexts.insert( QStringLiteral( "qgis_version_no" ), QCoreApplication::translate( "variable_help", "Current QGIS version number." ) ); + gVariableHelpTexts.insert( QStringLiteral( "qgis_release_name" ), QCoreApplication::translate( "variable_help", "Current QGIS release name." ) ); + gVariableHelpTexts.insert( QStringLiteral( "qgis_os_name" ), QCoreApplication::translate( "variable_help", "Operating system name, eg 'windows', 'linux' or 'osx'." ) ); + gVariableHelpTexts.insert( QStringLiteral( "qgis_platform" ), QCoreApplication::translate( "variable_help", "QGIS platform, eg 'desktop' or 'server'." ) ); + gVariableHelpTexts.insert( QStringLiteral( "user_account_name" ), QCoreApplication::translate( "variable_help", "Current user's operating system account name." ) ); + gVariableHelpTexts.insert( QStringLiteral( "user_full_name" ), QCoreApplication::translate( "variable_help", "Current user's operating system user name (if available)." ) ); //project variables - gVariableHelpTexts.insert( "project_title", QCoreApplication::translate( "variable_help", "Title of current project." ) ); - gVariableHelpTexts.insert( "project_path", QCoreApplication::translate( "variable_help", "Full path (including file name) of current project." ) ); - gVariableHelpTexts.insert( "project_folder", QCoreApplication::translate( "variable_help", "Folder for current project." ) ); - gVariableHelpTexts.insert( "project_filename", QCoreApplication::translate( "variable_help", "Filename of current project." ) ); + gVariableHelpTexts.insert( QStringLiteral( "project_title" ), QCoreApplication::translate( "variable_help", "Title of current project." ) ); + gVariableHelpTexts.insert( QStringLiteral( "project_path" ), QCoreApplication::translate( "variable_help", "Full path (including file name) of current project." ) ); + gVariableHelpTexts.insert( QStringLiteral( "project_folder" ), QCoreApplication::translate( "variable_help", "Folder for current project." ) ); + gVariableHelpTexts.insert( QStringLiteral( "project_filename" ), QCoreApplication::translate( "variable_help", "Filename of current project." ) ); //layer variables - gVariableHelpTexts.insert( "layer_name", QCoreApplication::translate( "variable_help", "Name of current layer." ) ); - gVariableHelpTexts.insert( "layer_id", QCoreApplication::translate( "variable_help", "ID of current layer." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layer_name" ), QCoreApplication::translate( "variable_help", "Name of current layer." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layer_id" ), QCoreApplication::translate( "variable_help", "ID of current layer." ) ); //composition variables - gVariableHelpTexts.insert( "layout_numpages", QCoreApplication::translate( "variable_help", "Number of pages in composition." ) ); - gVariableHelpTexts.insert( "layout_page", QCoreApplication::translate( "variable_help", "Current page number in composition." ) ); - gVariableHelpTexts.insert( "layout_pageheight", QCoreApplication::translate( "variable_help", "Composition page height in mm." ) ); - gVariableHelpTexts.insert( "layout_pagewidth", QCoreApplication::translate( "variable_help", "Composition page width in mm." ) ); - gVariableHelpTexts.insert( "layout_dpi", QCoreApplication::translate( "variable_help", "Composition resolution (DPI)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layout_numpages" ), QCoreApplication::translate( "variable_help", "Number of pages in composition." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layout_page" ), QCoreApplication::translate( "variable_help", "Current page number in composition." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layout_pageheight" ), QCoreApplication::translate( "variable_help", "Composition page height in mm." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layout_pagewidth" ), QCoreApplication::translate( "variable_help", "Composition page width in mm." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layout_dpi" ), QCoreApplication::translate( "variable_help", "Composition resolution (DPI)." ) ); //atlas variables - gVariableHelpTexts.insert( "atlas_totalfeatures", QCoreApplication::translate( "variable_help", "Total number of features in atlas." ) ); - gVariableHelpTexts.insert( "atlas_featurenumber", QCoreApplication::translate( "variable_help", "Current atlas feature number." ) ); - gVariableHelpTexts.insert( "atlas_filename", QCoreApplication::translate( "variable_help", "Current atlas file name." ) ); - gVariableHelpTexts.insert( "atlas_pagename", QCoreApplication::translate( "variable_help", "Current atlas page name." ) ); - gVariableHelpTexts.insert( "atlas_feature", QCoreApplication::translate( "variable_help", "Current atlas feature (as feature object)." ) ); - gVariableHelpTexts.insert( "atlas_featureid", QCoreApplication::translate( "variable_help", "Current atlas feature ID." ) ); - gVariableHelpTexts.insert( "atlas_geometry", QCoreApplication::translate( "variable_help", "Current atlas feature geometry." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_totalfeatures" ), QCoreApplication::translate( "variable_help", "Total number of features in atlas." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_featurenumber" ), QCoreApplication::translate( "variable_help", "Current atlas feature number." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_filename" ), QCoreApplication::translate( "variable_help", "Current atlas file name." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_pagename" ), QCoreApplication::translate( "variable_help", "Current atlas page name." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_feature" ), QCoreApplication::translate( "variable_help", "Current atlas feature (as feature object)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_featureid" ), QCoreApplication::translate( "variable_help", "Current atlas feature ID." ) ); + gVariableHelpTexts.insert( QStringLiteral( "atlas_geometry" ), QCoreApplication::translate( "variable_help", "Current atlas feature geometry." ) ); //composer item variables - gVariableHelpTexts.insert( "item_id", QCoreApplication::translate( "variable_help", "Composer item user ID (not necessarily unique)." ) ); - gVariableHelpTexts.insert( "item_uuid", QCoreApplication::translate( "variable_help", "Composer item unique ID." ) ); - gVariableHelpTexts.insert( "item_left", QCoreApplication::translate( "variable_help", "Left position of composer item (in mm)." ) ); - gVariableHelpTexts.insert( "item_top", QCoreApplication::translate( "variable_help", "Top position of composer item (in mm)." ) ); - gVariableHelpTexts.insert( "item_width", QCoreApplication::translate( "variable_help", "Width of composer item (in mm)." ) ); - gVariableHelpTexts.insert( "item_height", QCoreApplication::translate( "variable_help", "Height of composer item (in mm)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "item_id" ), QCoreApplication::translate( "variable_help", "Composer item user ID (not necessarily unique)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "item_uuid" ), QCoreApplication::translate( "variable_help", "Composer item unique ID." ) ); + gVariableHelpTexts.insert( QStringLiteral( "item_left" ), QCoreApplication::translate( "variable_help", "Left position of composer item (in mm)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "item_top" ), QCoreApplication::translate( "variable_help", "Top position of composer item (in mm)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "item_width" ), QCoreApplication::translate( "variable_help", "Width of composer item (in mm)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "item_height" ), QCoreApplication::translate( "variable_help", "Height of composer item (in mm)." ) ); //map settings item variables - gVariableHelpTexts.insert( "map_id", QCoreApplication::translate( "variable_help", "ID of current map destination. This will be 'canvas' for canvas renders, and the item ID for composer map renders." ) ); - gVariableHelpTexts.insert( "map_rotation", QCoreApplication::translate( "variable_help", "Current rotation of map." ) ); - gVariableHelpTexts.insert( "map_scale", QCoreApplication::translate( "variable_help", "Current scale of map." ) ); - gVariableHelpTexts.insert( "map_extent_center", QCoreApplication::translate( "variable_help", "Center of map." ) ); - gVariableHelpTexts.insert( "map_extent_width", QCoreApplication::translate( "variable_help", "Width of map." ) ); - gVariableHelpTexts.insert( "map_extent_height", QCoreApplication::translate( "variable_help", "Height of map." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_id" ), QCoreApplication::translate( "variable_help", "ID of current map destination. This will be 'canvas' for canvas renders, and the item ID for composer map renders." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_rotation" ), QCoreApplication::translate( "variable_help", "Current rotation of map." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_scale" ), QCoreApplication::translate( "variable_help", "Current scale of map." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_extent_center" ), QCoreApplication::translate( "variable_help", "Center of map." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_extent_width" ), QCoreApplication::translate( "variable_help", "Width of map." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_extent_height" ), QCoreApplication::translate( "variable_help", "Height of map." ) ); - gVariableHelpTexts.insert( "row_number", QCoreApplication::translate( "variable_help", "Stores the number of the current row." ) ); - gVariableHelpTexts.insert( "grid_number", QCoreApplication::translate( "variable_help", "Current grid annotation value." ) ); - gVariableHelpTexts.insert( "grid_axis", QCoreApplication::translate( "variable_help", "Current grid annotation axis (eg, 'x' for longitude, 'y' for latitude)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "row_number" ), QCoreApplication::translate( "variable_help", "Stores the number of the current row." ) ); + gVariableHelpTexts.insert( QStringLiteral( "grid_number" ), QCoreApplication::translate( "variable_help", "Current grid annotation value." ) ); + gVariableHelpTexts.insert( QStringLiteral( "grid_axis" ), QCoreApplication::translate( "variable_help", "Current grid annotation axis (eg, 'x' for longitude, 'y' for latitude)." ) ); //symbol variables - gVariableHelpTexts.insert( "geometry_part_count", QCoreApplication::translate( "variable_help", "Number of parts in rendered feature's geometry." ) ); - gVariableHelpTexts.insert( "geometry_part_num", QCoreApplication::translate( "variable_help", "Current geometry part number for feature being rendered." ) ); - gVariableHelpTexts.insert( "geometry_point_count", QCoreApplication::translate( "variable_help", "Number of points in the rendered geometry's part. It is only meaningful for line geometries and for symbol layers that set this variable." ) ); - gVariableHelpTexts.insert( "geometry_point_num", QCoreApplication::translate( "variable_help", "Current point number in the rendered geometry's part. It is only meaningful for line geometries and for symbol layers that set this variable." ) ); + gVariableHelpTexts.insert( QStringLiteral( "geometry_part_count" ), QCoreApplication::translate( "variable_help", "Number of parts in rendered feature's geometry." ) ); + gVariableHelpTexts.insert( QStringLiteral( "geometry_part_num" ), QCoreApplication::translate( "variable_help", "Current geometry part number for feature being rendered." ) ); + gVariableHelpTexts.insert( QStringLiteral( "geometry_point_count" ), QCoreApplication::translate( "variable_help", "Number of points in the rendered geometry's part. It is only meaningful for line geometries and for symbol layers that set this variable." ) ); + gVariableHelpTexts.insert( QStringLiteral( "geometry_point_num" ), QCoreApplication::translate( "variable_help", "Current point number in the rendered geometry's part. It is only meaningful for line geometries and for symbol layers that set this variable." ) ); - gVariableHelpTexts.insert( "symbol_color", QCoreApplication::translate( "symbol_color", "Color of symbol used to render the feature." ) ); - gVariableHelpTexts.insert( "symbol_angle", QCoreApplication::translate( "symbol_angle", "Angle of symbol used to render the feature (valid for marker symbols only)." ) ); + gVariableHelpTexts.insert( QStringLiteral( "symbol_color" ), QCoreApplication::translate( "symbol_color", "Color of symbol used to render the feature." ) ); + gVariableHelpTexts.insert( QStringLiteral( "symbol_angle" ), QCoreApplication::translate( "symbol_angle", "Angle of symbol used to render the feature (valid for marker symbols only)." ) ); //cluster variables - gVariableHelpTexts.insert( "cluster_color", QCoreApplication::translate( "cluster_color", "Color of symbols within a cluster, or NULL if symbols have mixed colors." ) ); - gVariableHelpTexts.insert( "cluster_size", QCoreApplication::translate( "cluster_size", "Number of symbols contained within a cluster." ) ); + gVariableHelpTexts.insert( QStringLiteral( "cluster_color" ), QCoreApplication::translate( "cluster_color", "Color of symbols within a cluster, or NULL if symbols have mixed colors." ) ); + gVariableHelpTexts.insert( QStringLiteral( "cluster_size" ), QCoreApplication::translate( "cluster_size", "Number of symbols contained within a cluster." ) ); } QString QgsExpression::variableHelpText( const QString &variableName, bool showValue, const QVariant &value ) { QgsExpression::initVariableHelp(); - QString text = gVariableHelpTexts.contains( variableName ) ? QString( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( gVariableHelpTexts.value( variableName ) ) : QString(); + QString text = gVariableHelpTexts.contains( variableName ) ? QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( gVariableHelpTexts.value( variableName ) ) : QString(); if ( showValue ) { QString valueString; @@ -5302,7 +5302,7 @@ QString QgsExpression::variableHelpText( const QString &variableName, bool showV } else { - valueString = QString( "%1" ).arg( formatPreviewString( value ) ); + valueString = QStringLiteral( "%1" ).arg( formatPreviewString( value ) ); } text.append( QCoreApplication::translate( "variable_help", "

                                                                                                                                                                                    Current value: %1

                                                                                                                                                                                    " ).arg( valueString ) ); } @@ -5315,20 +5315,20 @@ QString QgsExpression::group( const QString& name ) { if ( gGroups.isEmpty() ) { - gGroups.insert( "General", tr( "General" ) ); - gGroups.insert( "Operators", tr( "Operators" ) ); - gGroups.insert( "Conditionals", tr( "Conditionals" ) ); - gGroups.insert( "Fields and Values", tr( "Fields and Values" ) ); - gGroups.insert( "Math", tr( "Math" ) ); - gGroups.insert( "Conversions", tr( "Conversions" ) ); - gGroups.insert( "Date and Time", tr( "Date and Time" ) ); - gGroups.insert( "String", tr( "String" ) ); - gGroups.insert( "Color", tr( "Color" ) ); - gGroups.insert( "GeometryGroup", tr( "Geometry" ) ); - gGroups.insert( "Record", tr( "Record" ) ); - gGroups.insert( "Variables", tr( "Variables" ) ); - gGroups.insert( "Fuzzy Matching", tr( "Fuzzy Matching" ) ); - gGroups.insert( "Recent (%1)", tr( "Recent (%1)" ) ); + gGroups.insert( QStringLiteral( "General" ), tr( "General" ) ); + gGroups.insert( QStringLiteral( "Operators" ), tr( "Operators" ) ); + gGroups.insert( QStringLiteral( "Conditionals" ), tr( "Conditionals" ) ); + gGroups.insert( QStringLiteral( "Fields and Values" ), tr( "Fields and Values" ) ); + gGroups.insert( QStringLiteral( "Math" ), tr( "Math" ) ); + gGroups.insert( QStringLiteral( "Conversions" ), tr( "Conversions" ) ); + gGroups.insert( QStringLiteral( "Date and Time" ), tr( "Date and Time" ) ); + gGroups.insert( QStringLiteral( "String" ), tr( "String" ) ); + gGroups.insert( QStringLiteral( "Color" ), tr( "Color" ) ); + gGroups.insert( QStringLiteral( "GeometryGroup" ), tr( "Geometry" ) ); + gGroups.insert( QStringLiteral( "Record" ), tr( "Record" ) ); + gGroups.insert( QStringLiteral( "Variables" ), tr( "Variables" ) ); + gGroups.insert( QStringLiteral( "Fuzzy Matching" ), tr( "Fuzzy Matching" ) ); + gGroups.insert( QStringLiteral( "Recent (%1)" ), tr( "Recent (%1)" ) ); } //return the translated name for this group. If group does not @@ -5365,17 +5365,17 @@ QString QgsExpression::formatPreviewString( const QVariant& value ) else if ( value.type() == QVariant::Date ) { QDate dt = value.toDate(); - return tr( "<date: %1>" ).arg( dt.toString( "yyyy-MM-dd" ) ); + return tr( "<date: %1>" ).arg( dt.toString( QStringLiteral( "yyyy-MM-dd" ) ) ); } else if ( value.type() == QVariant::Time ) { QTime tm = value.toTime(); - return tr( "<time: %1>" ).arg( tm.toString( "hh:mm:ss" ) ); + return tr( "<time: %1>" ).arg( tm.toString( QStringLiteral( "hh:mm:ss" ) ) ); } else if ( value.type() == QVariant::DateTime ) { QDateTime dt = value.toDateTime(); - return tr( "<datetime: %1>" ).arg( dt.toString( "yyyy-MM-dd hh:mm:ss" ) ); + return tr( "<datetime: %1>" ).arg( dt.toString( QStringLiteral( "yyyy-MM-dd hh:mm:ss" ) ) ); } else if ( value.type() == QVariant::String ) { diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index 0e3f07426197..d81600210ea2 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -593,7 +593,7 @@ class CORE_EXPORT QgsExpression * to users in expression builders. * @note added in QGIS 3.0 */ - virtual bool isDeprecated() const { return mGroups.isEmpty() ? false : mGroups.contains( "deprecated" ); } + virtual bool isDeprecated() const { return mGroups.isEmpty() ? false : mGroups.contains( QStringLiteral( "deprecated" ) ); } /** Returns the first group which the function belongs to. * @note consider using groups() instead, as some functions naturally belong in multiple groups diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index 79997d2a6f41..67cd7d3e769a 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -31,17 +31,17 @@ #include -const QString QgsExpressionContext::EXPR_FIELDS( "_fields_" ); -const QString QgsExpressionContext::EXPR_FEATURE( "_feature_" ); -const QString QgsExpressionContext::EXPR_ORIGINAL_VALUE( "value" ); -const QString QgsExpressionContext::EXPR_SYMBOL_COLOR( "symbol_color" ); -const QString QgsExpressionContext::EXPR_SYMBOL_ANGLE( "symbol_angle" ); -const QString QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT( "geometry_part_count" ); -const QString QgsExpressionContext::EXPR_GEOMETRY_PART_NUM( "geometry_part_num" ); -const QString QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT( "geometry_point_count" ); -const QString QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM( "geometry_point_num" ); -const QString QgsExpressionContext::EXPR_CLUSTER_SIZE( "cluster_size" ); -const QString QgsExpressionContext::EXPR_CLUSTER_COLOR( "cluster_color" ); +const QString QgsExpressionContext::EXPR_FIELDS( QStringLiteral( "_fields_" ) ); +const QString QgsExpressionContext::EXPR_FEATURE( QStringLiteral( "_feature_" ) ); +const QString QgsExpressionContext::EXPR_ORIGINAL_VALUE( QStringLiteral( "value" ) ); +const QString QgsExpressionContext::EXPR_SYMBOL_COLOR( QStringLiteral( "symbol_color" ) ); +const QString QgsExpressionContext::EXPR_SYMBOL_ANGLE( QStringLiteral( "symbol_angle" ) ); +const QString QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT( QStringLiteral( "geometry_part_count" ) ); +const QString QgsExpressionContext::EXPR_GEOMETRY_PART_NUM( QStringLiteral( "geometry_part_num" ) ); +const QString QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT( QStringLiteral( "geometry_point_count" ) ); +const QString QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM( QStringLiteral( "geometry_point_num" ) ); +const QString QgsExpressionContext::EXPR_CLUSTER_SIZE( QStringLiteral( "cluster_size" ) ); +const QString QgsExpressionContext::EXPR_CLUSTER_COLOR( QStringLiteral( "cluster_color" ) ); // // QgsExpressionContextScope @@ -505,10 +505,10 @@ QgsExpressionContextScope* QgsExpressionContextUtils::globalScope() QSettings settings; //check if settings contains any variables - if ( settings.contains( QString( "/variables/values" ) ) ) + if ( settings.contains( QStringLiteral( "/variables/values" ) ) ) { - QList< QVariant > customVariableVariants = settings.value( QString( "/variables/values" ) ).toList(); - QList< QVariant > customVariableNames = settings.value( QString( "/variables/names" ) ).toList(); + QList< QVariant > customVariableVariants = settings.value( QStringLiteral( "/variables/values" ) ).toList(); + QList< QVariant > customVariableNames = settings.value( QStringLiteral( "/variables/names" ) ).toList(); int variableIndex = 0; for ( QList< QVariant >::const_iterator it = customVariableVariants.constBegin(); it != customVariableVariants.constEnd(); ++it ) @@ -527,13 +527,13 @@ QgsExpressionContextScope* QgsExpressionContextUtils::globalScope() } //add some extra global variables - scope->addVariable( QgsExpressionContextScope::StaticVariable( "qgis_version", Qgis::QGIS_VERSION, true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "qgis_version_no", Qgis::QGIS_VERSION_INT, true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "qgis_release_name", Qgis::QGIS_RELEASE_NAME, true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "qgis_platform", QgsApplication::platform(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "qgis_os_name", QgsApplication::osName(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "user_account_name", QgsApplication::userLoginName(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "user_full_name", QgsApplication::userFullName(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "qgis_version" ), Qgis::QGIS_VERSION, true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "qgis_version_no" ), Qgis::QGIS_VERSION_INT, true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "qgis_release_name" ), Qgis::QGIS_RELEASE_NAME, true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "qgis_platform" ), QgsApplication::platform(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "qgis_os_name" ), QgsApplication::osName(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "user_account_name" ), QgsApplication::userLoginName(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "user_full_name" ), QgsApplication::userFullName(), true ) ); return scope; } @@ -543,14 +543,14 @@ void QgsExpressionContextUtils::setGlobalVariable( const QString& name, const QV // save variable to settings QSettings settings; - QList< QVariant > customVariableVariants = settings.value( QString( "/variables/values" ) ).toList(); - QList< QVariant > customVariableNames = settings.value( QString( "/variables/names" ) ).toList(); + QList< QVariant > customVariableVariants = settings.value( QStringLiteral( "/variables/values" ) ).toList(); + QList< QVariant > customVariableNames = settings.value( QStringLiteral( "/variables/names" ) ).toList(); customVariableVariants << value; customVariableNames << name; - settings.setValue( QString( "/variables/names" ), customVariableNames ); - settings.setValue( QString( "/variables/values" ), customVariableVariants ); + settings.setValue( QStringLiteral( "/variables/names" ), customVariableNames ); + settings.setValue( QStringLiteral( "/variables/values" ), customVariableVariants ); } void QgsExpressionContextUtils::setGlobalVariables( const QgsStringMap &variables ) @@ -567,8 +567,8 @@ void QgsExpressionContextUtils::setGlobalVariables( const QgsStringMap &variable customVariableVariants << it.value(); } - settings.setValue( QString( "/variables/names" ), customVariableNames ); - settings.setValue( QString( "/variables/values" ), customVariableVariants ); + settings.setValue( QStringLiteral( "/variables/names" ), customVariableNames ); + settings.setValue( QStringLiteral( "/variables/values" ), customVariableVariants ); } /// @cond PRIVATE @@ -577,11 +577,11 @@ class GetNamedProjectColor : public QgsScopedExpressionFunction { public: GetNamedProjectColor() - : QgsScopedExpressionFunction( "project_color", 1, "Color" ) + : QgsScopedExpressionFunction( QStringLiteral( "project_color" ), 1, QStringLiteral( "Color" ) ) { //build up color list from project. Do this in advance for speed - QStringList colorStrings = QgsProject::instance()->readListEntry( "Palette", "/Colors" ); - QStringList colorLabels = QgsProject::instance()->readListEntry( "Palette", "/Labels" ); + QStringList colorStrings = QgsProject::instance()->readListEntry( QStringLiteral( "Palette" ), QStringLiteral( "/Colors" ) ); + QStringList colorLabels = QgsProject::instance()->readListEntry( QStringLiteral( "Palette" ), QStringLiteral( "/Labels" ) ); //generate list from custom colors int colorIndex = 0; @@ -605,7 +605,7 @@ class GetNamedProjectColor : public QgsScopedExpressionFunction QString colorName = values.at( 0 ).toString().toLower(); if ( mColors.contains( colorName ) ) { - return QString( "%1,%2,%3" ).arg( mColors.value( colorName ).red() ).arg( mColors.value( colorName ).green() ).arg( mColors.value( colorName ).blue() ); + return QStringLiteral( "%1,%2,%3" ).arg( mColors.value( colorName ).red() ).arg( mColors.value( colorName ).green() ).arg( mColors.value( colorName ).blue() ); } else return QVariant(); @@ -640,12 +640,12 @@ QgsExpressionContextScope* QgsExpressionContextUtils::projectScope() } //add other known project variables - scope->addVariable( QgsExpressionContextScope::StaticVariable( "project_title", project->title(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "project_path", project->fileInfo().filePath(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "project_folder", project->fileInfo().dir().path(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "project_filename", project->fileInfo().fileName(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_title" ), project->title(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_path" ), project->fileInfo().filePath(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_folder" ), project->fileInfo().dir().path(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_filename" ), project->fileInfo().fileName(), true ) ); - scope->addFunction( "project_color", new GetNamedProjectColor() ); + scope->addFunction( QStringLiteral( "project_color" ), new GetNamedProjectColor() ); return scope; } @@ -673,8 +673,8 @@ QgsExpressionContextScope* QgsExpressionContextUtils::layerScope( const QgsMapLa return scope; //add variables defined in layer properties - QStringList variableNames = layer->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = layer->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = layer->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = layer->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); int varIndex = 0; Q_FOREACH ( const QString& variableName, variableNames ) @@ -689,8 +689,8 @@ QgsExpressionContextScope* QgsExpressionContextUtils::layerScope( const QgsMapLa scope->setVariable( variableName, varValue ); } - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layer_name", layer->name(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layer_id", layer->id(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer_name" ), layer->name(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer_id" ), layer->id(), true ) ); const QgsVectorLayer* vLayer = dynamic_cast< const QgsVectorLayer* >( layer ); if ( vLayer ) @@ -711,14 +711,14 @@ void QgsExpressionContextUtils::setLayerVariable( QgsMapLayer* layer, const QStr return; //write variable to layer - QStringList variableNames = layer->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = layer->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = layer->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = layer->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); variableNames << name; variableValues << value.toString(); - layer->setCustomProperty( "variableNames", variableNames ); - layer->setCustomProperty( "variableValues", variableValues ); + layer->setCustomProperty( QStringLiteral( "variableNames" ), variableNames ); + layer->setCustomProperty( QStringLiteral( "variableValues" ), variableValues ); } void QgsExpressionContextUtils::setLayerVariables( QgsMapLayer* layer, const QgsStringMap& variables ) @@ -736,8 +736,8 @@ void QgsExpressionContextUtils::setLayerVariables( QgsMapLayer* layer, const Qgs variableValues << it.value(); } - layer->setCustomProperty( "variableNames", variableNames ); - layer->setCustomProperty( "variableValues", variableValues ); + layer->setCustomProperty( QStringLiteral( "variableNames" ), variableNames ); + layer->setCustomProperty( QStringLiteral( "variableValues" ), variableValues ); } QgsExpressionContextScope* QgsExpressionContextUtils::mapSettingsScope( const QgsMapSettings& mapSettings ) @@ -748,13 +748,13 @@ QgsExpressionContextScope* QgsExpressionContextUtils::mapSettingsScope( const Qg QgsExpressionContextScope* scope = new QgsExpressionContextScope( QObject::tr( "Map Settings" ) ); //add known map settings context variables - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_id", "canvas", true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_rotation", mapSettings.rotation(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_scale", mapSettings.scale(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_width", mapSettings.visibleExtent().width(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_height", mapSettings.visibleExtent().height(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_id" ), "canvas", true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_rotation" ), mapSettings.rotation(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_scale" ), mapSettings.scale(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_width" ), mapSettings.visibleExtent().width(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_height" ), mapSettings.visibleExtent().height(), true ) ); QgsGeometry centerPoint = QgsGeometry::fromPoint( mapSettings.visibleExtent().center() ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "map_extent_center", QVariant::fromValue( centerPoint ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_center" ), QVariant::fromValue( centerPoint ), true ) ); return scope; } @@ -784,8 +784,8 @@ QgsExpressionContextScope *QgsExpressionContextUtils::compositionScope( const Qg return scope; //add variables defined in composition properties - QStringList variableNames = composition->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = composition->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = composition->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = composition->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); int varIndex = 0; Q_FOREACH ( const QString& variableName, variableNames ) @@ -801,10 +801,10 @@ QgsExpressionContextScope *QgsExpressionContextUtils::compositionScope( const Qg } //add known composition context variables - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layout_numpages", composition->numPages(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layout_pageheight", composition->paperHeight(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layout_pagewidth", composition->paperWidth(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layout_dpi", composition->printResolution(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layout_numpages" ), composition->numPages(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layout_pageheight" ), composition->paperHeight(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layout_pagewidth" ), composition->paperWidth(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layout_dpi" ), composition->printResolution(), true ) ); return scope; } @@ -815,14 +815,14 @@ void QgsExpressionContextUtils::setCompositionVariable( QgsComposition* composit return; //write variable to composition - QStringList variableNames = composition->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = composition->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = composition->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = composition->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); variableNames << name; variableValues << value.toString(); - composition->setCustomProperty( "variableNames", variableNames ); - composition->setCustomProperty( "variableValues", variableValues ); + composition->setCustomProperty( QStringLiteral( "variableNames" ), variableNames ); + composition->setCustomProperty( QStringLiteral( "variableValues" ), variableValues ); } void QgsExpressionContextUtils::setCompositionVariables( QgsComposition* composition, const QgsStringMap& variables ) @@ -840,8 +840,8 @@ void QgsExpressionContextUtils::setCompositionVariables( QgsComposition* composi variableValues << it.value(); } - composition->setCustomProperty( "variableNames", variableNames ); - composition->setCustomProperty( "variableValues", variableValues ); + composition->setCustomProperty( QStringLiteral( "variableNames" ), variableNames ); + composition->setCustomProperty( QStringLiteral( "variableValues" ), variableValues ); } QgsExpressionContextScope* QgsExpressionContextUtils::atlasScope( const QgsAtlasComposition* atlas ) @@ -851,18 +851,18 @@ QgsExpressionContextScope* QgsExpressionContextUtils::atlasScope( const QgsAtlas { //add some dummy atlas variables. This is done so that as in certain contexts we want to show //users that these variables are available even if they have no current value - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_pagename", QString(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_feature", QVariant::fromValue( QgsFeature() ), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_featureid", 0, true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_geometry", QVariant::fromValue( QgsGeometry() ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_pagename" ), QString(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_feature" ), QVariant::fromValue( QgsFeature() ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_featureid" ), 0, true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_geometry" ), QVariant::fromValue( QgsGeometry() ), true ) ); return scope; } //add known atlas variables - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_totalfeatures", atlas->numFeatures(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_featurenumber", atlas->currentFeatureNumber() + 1, true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_filename", atlas->currentFilename(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_pagename", atlas->currentPageName(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_totalfeatures" ), atlas->numFeatures(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_featurenumber" ), atlas->currentFeatureNumber() + 1, true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_filename" ), atlas->currentFilename(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_pagename" ), atlas->currentPageName(), true ) ); if ( atlas->enabled() && atlas->coverageLayer() ) { @@ -873,9 +873,9 @@ QgsExpressionContextScope* QgsExpressionContextUtils::atlasScope( const QgsAtlas { QgsFeature atlasFeature = atlas->feature(); scope->setFeature( atlasFeature ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_feature", QVariant::fromValue( atlasFeature ), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_featureid", atlasFeature.id(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "atlas_geometry", QVariant::fromValue( atlasFeature.geometry() ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_feature" ), QVariant::fromValue( atlasFeature ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_featureid" ), atlasFeature.id(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "atlas_geometry" ), QVariant::fromValue( atlasFeature.geometry() ), true ) ); } return scope; @@ -888,8 +888,8 @@ QgsExpressionContextScope *QgsExpressionContextUtils::composerItemScope( const Q return scope; //add variables defined in composer item properties - QStringList variableNames = composerItem->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = composerItem->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = composerItem->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = composerItem->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); int varIndex = 0; Q_FOREACH ( const QString& variableName, variableNames ) @@ -905,9 +905,9 @@ QgsExpressionContextScope *QgsExpressionContextUtils::composerItemScope( const Q } //add known composer item context variables - scope->addVariable( QgsExpressionContextScope::StaticVariable( "item_id", composerItem->id(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "item_uuid", composerItem->uuid(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( "layout_page", composerItem->page(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "item_id" ), composerItem->id(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "item_uuid" ), composerItem->uuid(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layout_page" ), composerItem->page(), true ) ); return scope; } @@ -918,14 +918,14 @@ void QgsExpressionContextUtils::setComposerItemVariable( QgsComposerItem* compos return; //write variable to composer item - QStringList variableNames = composerItem->customProperty( "variableNames" ).toStringList(); - QStringList variableValues = composerItem->customProperty( "variableValues" ).toStringList(); + QStringList variableNames = composerItem->customProperty( QStringLiteral( "variableNames" ) ).toStringList(); + QStringList variableValues = composerItem->customProperty( QStringLiteral( "variableValues" ) ).toStringList(); variableNames << name; variableValues << value.toString(); - composerItem->setCustomProperty( "variableNames", variableNames ); - composerItem->setCustomProperty( "variableValues", variableValues ); + composerItem->setCustomProperty( QStringLiteral( "variableNames" ), variableNames ); + composerItem->setCustomProperty( QStringLiteral( "variableValues" ), variableValues ); } void QgsExpressionContextUtils::setComposerItemVariables( QgsComposerItem* composerItem, const QgsStringMap& variables ) @@ -943,8 +943,8 @@ void QgsExpressionContextUtils::setComposerItemVariables( QgsComposerItem* compo variableValues << it.value(); } - composerItem->setCustomProperty( "variableNames", variableNames ); - composerItem->setCustomProperty( "variableValues", variableValues ); + composerItem->setCustomProperty( QStringLiteral( "variableNames" ), variableNames ); + composerItem->setCustomProperty( QStringLiteral( "variableValues" ), variableValues ); } QgsExpressionContext QgsExpressionContextUtils::createFeatureBasedContext( const QgsFeature &feature, const QgsFields &fields ) diff --git a/src/core/qgsexpressionfieldbuffer.cpp b/src/core/qgsexpressionfieldbuffer.cpp index 9b73009998e0..c6f72f0dec75 100644 --- a/src/core/qgsexpressionfieldbuffer.cpp +++ b/src/core/qgsexpressionfieldbuffer.cpp @@ -45,21 +45,21 @@ void QgsExpressionFieldBuffer::updateExpression( int index, const QString& exp ) void QgsExpressionFieldBuffer::writeXml( QDomNode& layerNode, QDomDocument& document ) const { - QDomElement expressionFieldsElem = document.createElement( "expressionfields" ); + QDomElement expressionFieldsElem = document.createElement( QStringLiteral( "expressionfields" ) ); layerNode.appendChild( expressionFieldsElem ); Q_FOREACH ( const ExpressionField& fld, mExpressions ) { - QDomElement fldElem = document.createElement( "field" ); + QDomElement fldElem = document.createElement( QStringLiteral( "field" ) ); - fldElem.setAttribute( "expression", fld.cachedExpression.expression() ); - fldElem.setAttribute( "name", fld.field.name() ); - fldElem.setAttribute( "precision", fld.field.precision() ); - fldElem.setAttribute( "comment", fld.field.comment() ); - fldElem.setAttribute( "length", fld.field.length() ); - fldElem.setAttribute( "type", fld.field.type() ); - fldElem.setAttribute( "subType", fld.field.subType() ); - fldElem.setAttribute( "typeName", fld.field.typeName() ); + fldElem.setAttribute( QStringLiteral( "expression" ), fld.cachedExpression.expression() ); + fldElem.setAttribute( QStringLiteral( "name" ), fld.field.name() ); + fldElem.setAttribute( QStringLiteral( "precision" ), fld.field.precision() ); + fldElem.setAttribute( QStringLiteral( "comment" ), fld.field.comment() ); + fldElem.setAttribute( QStringLiteral( "length" ), fld.field.length() ); + fldElem.setAttribute( QStringLiteral( "type" ), fld.field.type() ); + fldElem.setAttribute( QStringLiteral( "subType" ), fld.field.subType() ); + fldElem.setAttribute( QStringLiteral( "typeName" ), fld.field.typeName() ); expressionFieldsElem.appendChild( fldElem ); } @@ -69,23 +69,23 @@ void QgsExpressionFieldBuffer::readXml( const QDomNode& layerNode ) { mExpressions.clear(); - const QDomElement expressionFieldsElem = layerNode.firstChildElement( "expressionfields" ); + const QDomElement expressionFieldsElem = layerNode.firstChildElement( QStringLiteral( "expressionfields" ) ); if ( !expressionFieldsElem.isNull() ) { - QDomNodeList fields = expressionFieldsElem.elementsByTagName( "field" ); + QDomNodeList fields = expressionFieldsElem.elementsByTagName( QStringLiteral( "field" ) ); for ( int i = 0; i < fields.size(); ++i ) { QDomElement field = fields.at( i ).toElement(); - QString exp = field.attribute( "expression" ); - QString name = field.attribute( "name" ); - QString comment = field.attribute( "comment" ); - int precision = field.attribute( "precision" ).toInt(); - int length = field.attribute( "length" ).toInt(); - QVariant::Type type = static_cast< QVariant::Type >( field.attribute( "type" ).toInt() ); - QVariant::Type subType = static_cast< QVariant::Type >( field.attribute( "subType", 0 ).toInt() ); - QString typeName = field.attribute( "typeName" ); + QString exp = field.attribute( QStringLiteral( "expression" ) ); + QString name = field.attribute( QStringLiteral( "name" ) ); + QString comment = field.attribute( QStringLiteral( "comment" ) ); + int precision = field.attribute( QStringLiteral( "precision" ) ).toInt(); + int length = field.attribute( QStringLiteral( "length" ) ).toInt(); + QVariant::Type type = static_cast< QVariant::Type >( field.attribute( QStringLiteral( "type" ) ).toInt() ); + QVariant::Type subType = static_cast< QVariant::Type >( field.attribute( QStringLiteral( "subType" ), 0 ).toInt() ); + QString typeName = field.attribute( QStringLiteral( "typeName" ) ); mExpressions.append( ExpressionField( exp, QgsField( name, type, typeName, length, precision, comment, subType ) ) ); } diff --git a/src/core/qgsfeaturerequest.cpp b/src/core/qgsfeaturerequest.cpp index f0f2a7259c31..796be15dc517 100644 --- a/src/core/qgsfeaturerequest.cpp +++ b/src/core/qgsfeaturerequest.cpp @@ -20,7 +20,7 @@ #include //constants -const QString QgsFeatureRequest::AllAttributes = QString( "#!allattributes!#" ); +const QString QgsFeatureRequest::AllAttributes = QStringLiteral( "#!allattributes!#" ); QgsFeatureRequest::QgsFeatureRequest() : mFilter( FilterNone ) @@ -138,7 +138,7 @@ QgsFeatureRequest& QgsFeatureRequest::combineFilterExpression( const QString& ex { if ( mFilterExpression ) { - setFilterExpression( QString( "(%1) AND (%2)" ).arg( mFilterExpression->expression(), expression ) ); + setFilterExpression( QStringLiteral( "(%1) AND (%2)" ).arg( mFilterExpression->expression(), expression ) ); } else { @@ -342,7 +342,7 @@ void QgsFeatureRequest::OrderByClause::setNullsFirst( bool nullsFirst ) QString QgsFeatureRequest::OrderByClause::dump() const { - return QString( "%1 %2 %3" ) + return QStringLiteral( "%1 %2 %3" ) .arg( mExpression.expression(), mAscending ? "ASC" : "DESC", mNullsFirst ? "NULLS FIRST" : "NULLS LAST" ); @@ -373,9 +373,9 @@ void QgsFeatureRequest::OrderBy::save( QDomElement& elem ) const for ( it = constBegin(); it != constEnd(); ++it ) { const OrderByClause& clause = *it; - QDomElement clauseElem = doc.createElement( "orderByClause" ); - clauseElem.setAttribute( "asc", clause.ascending() ); - clauseElem.setAttribute( "nullsFirst", clause.nullsFirst() ); + QDomElement clauseElem = doc.createElement( QStringLiteral( "orderByClause" ) ); + clauseElem.setAttribute( QStringLiteral( "asc" ), clause.ascending() ); + clauseElem.setAttribute( QStringLiteral( "nullsFirst" ), clause.nullsFirst() ); clauseElem.appendChild( doc.createTextNode( clause.expression().expression() ) ); elem.appendChild( clauseElem ); @@ -392,8 +392,8 @@ void QgsFeatureRequest::OrderBy::load( const QDomElement& elem ) { QDomElement clauseElem = clauses.at( i ).toElement(); QString expression = clauseElem.text(); - bool asc = clauseElem.attribute( "asc" ).toInt() != 0; - bool nullsFirst = clauseElem.attribute( "nullsFirst" ).toInt() != 0; + bool asc = clauseElem.attribute( QStringLiteral( "asc" ) ).toInt() != 0; + bool nullsFirst = clauseElem.attribute( QStringLiteral( "nullsFirst" ) ).toInt() != 0; append( OrderByClause( expression, asc, nullsFirst ) ); } @@ -426,5 +426,5 @@ QString QgsFeatureRequest::OrderBy::dump() const results << clause.dump(); } - return results.join( ", " ); + return results.join( QStringLiteral( ", " ) ); } diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index 95ccee0e8646..ec1611ddecb7 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -201,7 +201,7 @@ QString QgsField::displayString( const QVariant& v ) const if ( v.isNull() ) { QSettings settings; - return settings.value( "qgis/nullValue", "NULL" ).toString(); + return settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } if ( d->type == QVariant::Double && d->precision > 0 ) diff --git a/src/core/qgsfontutils.cpp b/src/core/qgsfontutils.cpp index 9d4c30b4ccec..471e720a4ce2 100644 --- a/src/core/qgsfontutils.cpp +++ b/src/core/qgsfontutils.cpp @@ -215,7 +215,7 @@ bool QgsFontUtils::updateFontViaStyle( QFont& f, const QString& fontstyle, bool QString QgsFontUtils::standardTestFontFamily() { - return "QGIS Vera Sans"; + return QStringLiteral( "QGIS Vera Sans" ); } bool QgsFontUtils::loadStandardTestFonts( const QStringList& loadstyles ) @@ -225,17 +225,17 @@ bool QgsFontUtils::loadStandardTestFonts( const QStringList& loadstyles ) QString fontFamily = standardTestFontFamily(); QMap fontStyles; - fontStyles.insert( "Roman", "QGIS-Vera/QGIS-Vera.ttf" ); - fontStyles.insert( "Oblique", "QGIS-Vera/QGIS-VeraIt.ttf" ); - fontStyles.insert( "Bold", "QGIS-Vera/QGIS-VeraBd.ttf" ); - fontStyles.insert( "Bold Oblique", "QGIS-Vera/QGIS-VeraBI.ttf" ); + fontStyles.insert( QStringLiteral( "Roman" ), QStringLiteral( "QGIS-Vera/QGIS-Vera.ttf" ) ); + fontStyles.insert( QStringLiteral( "Oblique" ), QStringLiteral( "QGIS-Vera/QGIS-VeraIt.ttf" ) ); + fontStyles.insert( QStringLiteral( "Bold" ), QStringLiteral( "QGIS-Vera/QGIS-VeraBd.ttf" ) ); + fontStyles.insert( QStringLiteral( "Bold Oblique" ), QStringLiteral( "QGIS-Vera/QGIS-VeraBI.ttf" ) ); QMap::const_iterator f = fontStyles.constBegin(); for ( ; f != fontStyles.constEnd(); ++f ) { QString fontstyle( f.key() ); QString fontpath( f.value() ); - if ( !( loadstyles.contains( fontstyle ) || loadstyles.contains( "All" ) ) ) + if ( !( loadstyles.contains( fontstyle ) || loadstyles.contains( QStringLiteral( "All" ) ) ) ) { continue; } @@ -312,8 +312,8 @@ QFont QgsFontUtils::getStandardTestFont( const QString& style, int pointsize ) } #endif // in case above statement fails to set style - f.setBold( style.contains( "Bold" ) ); - f.setItalic( style.contains( "Oblique" ) || style.contains( "Italic" ) ); + f.setBold( style.contains( QLatin1String( "Bold" ) ) ); + f.setItalic( style.contains( QLatin1String( "Oblique" ) ) || style.contains( QLatin1String( "Italic" ) ) ); return f; } @@ -321,8 +321,8 @@ QFont QgsFontUtils::getStandardTestFont( const QString& style, int pointsize ) QDomElement QgsFontUtils::toXmlElement( const QFont& font, QDomDocument& document, const QString& elementName ) { QDomElement fontElem = document.createElement( elementName ); - fontElem.setAttribute( "description", font.toString() ); - fontElem.setAttribute( "style", untranslateNamedStyle( font.styleName() ) ); + fontElem.setAttribute( QStringLiteral( "description" ), font.toString() ); + fontElem.setAttribute( QStringLiteral( "style" ), untranslateNamedStyle( font.styleName() ) ); return fontElem; } @@ -333,10 +333,10 @@ bool QgsFontUtils::setFromXmlElement( QFont& font, const QDomElement& element ) return false; } - font.fromString( element.attribute( "description" ) ); - if ( element.hasAttribute( "style" ) ) + font.fromString( element.attribute( QStringLiteral( "description" ) ) ); + if ( element.hasAttribute( QStringLiteral( "style" ) ) ) { - ( void )updateFontViaStyle( font, translateNamedStyle( element.attribute( "style" ) ) ); + ( void )updateFontViaStyle( font, translateNamedStyle( element.attribute( QStringLiteral( "style" ) ) ) ); } return true; @@ -364,7 +364,7 @@ bool QgsFontUtils::setFromXmlChildNode( QFont& font, const QDomElement& element, static QMap createTranslatedStyleMap() { QMap translatedStyleMap; - QStringList words = QStringList() << "Normal" << "Light" << "Bold" << "Black" << "Demi" << "Italic" << "Oblique"; + QStringList words = QStringList() << QStringLiteral( "Normal" ) << QStringLiteral( "Light" ) << QStringLiteral( "Bold" ) << QStringLiteral( "Black" ) << QStringLiteral( "Demi" ) << QStringLiteral( "Italic" ) << QStringLiteral( "Oblique" ); Q_FOREACH ( const QString& word, words ) { translatedStyleMap.insert( QCoreApplication::translate( "QFontDatabase", qPrintable( word ) ), word ); @@ -379,7 +379,7 @@ QString QgsFontUtils::translateNamedStyle( const QString& namedStyle ) { words[i] = QCoreApplication::translate( "QFontDatabase", words[i].toUtf8(), nullptr, QCoreApplication::UnicodeUTF8 ); } - return words.join( " " ); + return words.join( QStringLiteral( " " ) ); } QString QgsFontUtils::untranslateNamedStyle( const QString& namedStyle ) @@ -397,25 +397,25 @@ QString QgsFontUtils::untranslateNamedStyle( const QString& namedStyle ) QgsDebugMsg( QString( "Warning: style map does not contain %1" ).arg( words[i] ) ); } } - return words.join( " " ); + return words.join( QStringLiteral( " " ) ); } QString QgsFontUtils::asCSS( const QFont& font, double pointToPixelScale ) { - QString css = QString( "font-family: " ) + font.family() + ';'; + QString css = QStringLiteral( "font-family: " ) + font.family() + ';'; //style - css += "font-style: "; + css += QLatin1String( "font-style: " ); switch ( font.style() ) { case QFont::StyleNormal: - css += "normal"; + css += QLatin1String( "normal" ); break; case QFont::StyleItalic: - css += "italic"; + css += QLatin1String( "italic" ); break; case QFont::StyleOblique: - css += "oblique"; + css += QLatin1String( "oblique" ); break; } css += ';'; @@ -454,10 +454,10 @@ QString QgsFontUtils::asCSS( const QFont& font, double pointToPixelScale ) break; #endif } - css += QString( "font-weight: %1;" ).arg( cssWeight ); + css += QStringLiteral( "font-weight: %1;" ).arg( cssWeight ); //size - css += QString( "font-size: %1px;" ).arg( font.pointSizeF() >= 0 ? font.pointSizeF() * pointToPixelScale : font.pixelSize() ); + css += QStringLiteral( "font-size: %1px;" ).arg( font.pointSizeF() >= 0 ? font.pointSizeF() * pointToPixelScale : font.pixelSize() ); return css; } diff --git a/src/core/qgsfontutils.h b/src/core/qgsfontutils.h index c0956b98be5a..9e37aad8a75c 100644 --- a/src/core/qgsfontutils.h +++ b/src/core/qgsfontutils.h @@ -82,7 +82,7 @@ class CORE_EXPORT QgsFontUtils * @returns QFont * @note Added in QGIS 2.1 */ - static QFont getStandardTestFont( const QString& style = "Roman", int pointsize = 12 ); + static QFont getStandardTestFont( const QString& style = QStringLiteral( "Roman" ), int pointsize = 12 ); /** Returns a DOM element containing the properties of the font. * @param font font diff --git a/src/core/qgsgeometryvalidator.cpp b/src/core/qgsgeometryvalidator.cpp index a6b8e77abbbc..571dee051071 100644 --- a/src/core/qgsgeometryvalidator.cpp +++ b/src/core/qgsgeometryvalidator.cpp @@ -217,7 +217,7 @@ void QgsGeometryValidator::run() { mErrorCount = 0; QSettings settings; - if ( settings.value( "/qgis/digitizing/validate_geometries", 1 ).toInt() == 2 ) + if ( settings.value( QStringLiteral( "/qgis/digitizing/validate_geometries" ), 1 ).toInt() == 2 ) { char *r = nullptr; const GEOSGeometry *g0 = mG.asGeos(); diff --git a/src/core/qgsgml.cpp b/src/core/qgsgml.cpp index b01e4014d023..95f4abaaec2d 100644 --- a/src/core/qgsgml.cpp +++ b/src/core/qgsgml.cpp @@ -79,7 +79,7 @@ int QgsGml::getFeatures( const QString& uri, QgsWkbTypes::Type* wkbType, QgsRect } else if ( !userName.isNull() || !password.isNull() ) { - request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( userName, password ).toLatin1().toBase64() ); + request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( userName, password ).toLatin1().toBase64() ); } QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); @@ -106,7 +106,7 @@ int QgsGml::getFeatures( const QString& uri, QgsWkbTypes::Type* wkbType, QgsRect QWidgetList topLevelWidgets = qApp->topLevelWidgets(); for ( QWidgetList::const_iterator it = topLevelWidgets.constBegin(); it != topLevelWidgets.constEnd(); ++it ) { - if (( *it )->objectName() == "QgisApp" ) + if (( *it )->objectName() == QLatin1String( "QgisApp" ) ) { mainWindow = *it; break; @@ -264,7 +264,7 @@ QgsCoordinateReferenceSystem QgsGml::crs() const QgsCoordinateReferenceSystem crs; if ( mParser.getEPSGCode() != 0 ) { - crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( mParser.getEPSGCode() ) ); + crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( mParser.getEPSGCode() ) ); } return crs; } @@ -518,12 +518,12 @@ void QgsGmlStreamingParser::startElement( const XML_Char* el, const XML_Char** a mParseModeStack.push( coordinate ); mCoorMode = QgsGmlStreamingParser::coordinate; mStringCash.clear(); - mCoordinateSeparator = readAttribute( "cs", attr ); + mCoordinateSeparator = readAttribute( QStringLiteral( "cs" ), attr ); if ( mCoordinateSeparator.isEmpty() ) { mCoordinateSeparator = ','; } - mTupleSeparator = readAttribute( "ts", attr ); + mTupleSeparator = readAttribute( QStringLiteral( "ts" ), attr ); if ( mTupleSeparator.isEmpty() ) { mTupleSeparator = ' '; @@ -537,7 +537,7 @@ void QgsGmlStreamingParser::startElement( const XML_Char* el, const XML_Char** a mStringCash.clear(); if ( mDimension == 0 ) { - QString srsDimension = readAttribute( "srsDimension", attr ); + QString srsDimension = readAttribute( QStringLiteral( "srsDimension" ), attr ); bool ok; int dimension = srsDimension.toInt( &ok ); if ( ok ) @@ -646,7 +646,7 @@ void QgsGmlStreamingParser::startElement( const XML_Char* el, const XML_Char** a QgsAttributes attributes( mThematicAttributes.size() ); //add empty attributes mCurrentFeature->setAttributes( attributes ); mParseModeStack.push( QgsGmlStreamingParser::feature ); - mCurrentFeatureId = readAttribute( "fid", attr ); + mCurrentFeatureId = readAttribute( QStringLiteral( "fid" ), attr ); if ( mCurrentFeatureId.isEmpty() ) { // Figure out if the GML namespace is GML_NAMESPACE or GML32_NAMESPACE @@ -735,12 +735,12 @@ void QgsGmlStreamingParser::startElement( const XML_Char* el, const XML_Char** a { // QGIS server (2.2) is using: // - if ( localName.compare( "attribute", Qt::CaseInsensitive ) == 0 ) + if ( localName.compare( QLatin1String( "attribute" ), Qt::CaseInsensitive ) == 0 ) { - QString name = readAttribute( "name", attr ); + QString name = readAttribute( QStringLiteral( "name" ), attr ); if ( mThematicAttributes.contains( name ) ) { - QString value = readAttribute( "value", attr ); + QString value = readAttribute( QStringLiteral( "value" ), attr ); setAttribute( name, value ); } } @@ -748,15 +748,15 @@ void QgsGmlStreamingParser::startElement( const XML_Char* el, const XML_Char** a } else if ( mParseDepth == 0 && LOCALNAME_EQUALS( "FeatureCollection" ) ) { - QString numberReturned = readAttribute( "numberReturned", attr ); // WFS 2.0 + QString numberReturned = readAttribute( QStringLiteral( "numberReturned" ), attr ); // WFS 2.0 if ( numberReturned.isEmpty() ) - numberReturned = readAttribute( "numberOfFeatures", attr ); // WFS 1.1 + numberReturned = readAttribute( QStringLiteral( "numberOfFeatures" ), attr ); // WFS 1.1 bool conversionOk; mNumberReturned = numberReturned.toInt( &conversionOk ); if ( !conversionOk ) mNumberReturned = -1; - QString numberMatched = readAttribute( "numberMatched", attr ); // WFS 2.0 + QString numberMatched = readAttribute( QStringLiteral( "numberMatched" ), attr ); // WFS 2.0 mNumberMatched = numberMatched.toInt( &conversionOk ); if ( !conversionOk ) // likely since numberMatched="unknown" is legal mNumberMatched = -1; @@ -802,7 +802,7 @@ void QgsGmlStreamingParser::startElement( const XML_Char* el, const XML_Char** a { // srsDimension can also be set on the top geometry element // e.g. https://data.linz.govt.nz/services;key=XXXXXXXX/wfs?SERVICE=WFS&REQUEST=GetFeature&VERSION=2.0.0&TYPENAMES=data.linz.govt.nz:layer-524 - QString srsDimension = readAttribute( "srsDimension", attr ); + QString srsDimension = readAttribute( QStringLiteral( "srsDimension" ), attr ); bool ok; int dimension = srsDimension.toInt( &ok ); if ( ok ) @@ -1194,13 +1194,13 @@ int QgsGmlStreamingParser::readEpsgFromAttribute( int& epsgNr, const XML_Char** QString epsgString( attr[i+1] ); QString epsgNrString; bool bIsUrn = false; - if ( epsgString.startsWith( "http" ) ) //e.g. geoserver: "http://www.opengis.net/gml/srs/epsg.xml#4326" + if ( epsgString.startsWith( QLatin1String( "http" ) ) ) //e.g. geoserver: "http://www.opengis.net/gml/srs/epsg.xml#4326" { epsgNrString = epsgString.section( '#', 1, 1 ); } // WFS >= 1.1 - else if ( epsgString.startsWith( "urn:ogc:def:crs:EPSG:" ) || - epsgString.startsWith( "urn:x-ogc:def:crs:EPSG:" ) ) + else if ( epsgString.startsWith( QLatin1String( "urn:ogc:def:crs:EPSG:" ) ) || + epsgString.startsWith( QLatin1String( "urn:x-ogc:def:crs:EPSG:" ) ) ) { bIsUrn = true; epsgNrString = epsgString.split( ':' ).last(); @@ -1218,7 +1218,7 @@ int QgsGmlStreamingParser::readEpsgFromAttribute( int& epsgNr, const XML_Char** epsgNr = eNr; mSrsName = epsgString; - QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( epsgNr ) ); + QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( epsgNr ) ); if ( crs.isValid() ) { if ((( mAxisOrientationLogic == Honour_EPSG_if_urn && bIsUrn ) || diff --git a/src/core/qgsgmlschema.cpp b/src/core/qgsgmlschema.cpp index 70bf310c2a80..1026305f5b94 100644 --- a/src/core/qgsgmlschema.cpp +++ b/src/core/qgsgmlschema.cpp @@ -31,7 +31,7 @@ #include const char NS_SEPARATOR = '?'; -const QString GML_NAMESPACE = "http://www.opengis.net/gml"; +const QString GML_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml" ); QgsGmlFeatureClass::QgsGmlFeatureClass() { @@ -60,9 +60,9 @@ QgsGmlSchema::QgsGmlSchema() , mLevel( 0 ) , mSkipLevel( std::numeric_limits::max() ) { - mGeometryTypes << "Point" << "MultiPoint" - << "LineString" << "MultiLineString" - << "Polygon" << "MultiPolygon"; + mGeometryTypes << QStringLiteral( "Point" ) << QStringLiteral( "MultiPoint" ) + << QStringLiteral( "LineString" ) << QStringLiteral( "MultiLineString" ) + << QStringLiteral( "Polygon" ) << QStringLiteral( "MultiPolygon" ); } QgsGmlSchema::~QgsGmlSchema() @@ -98,14 +98,14 @@ bool QgsGmlSchema::parseXSD( const QByteArray &xml ) QDomElement docElem = dom.documentElement(); - QList elementElements = domElements( docElem, "element" ); + QList elementElements = domElements( docElem, QStringLiteral( "element" ) ); //QgsDebugMsg( QString( "%1 elemets read" ).arg( elementElements.size() ) ); Q_FOREACH ( const QDomElement& elementElement, elementElements ) { - QString name = elementElement.attribute( "name" ); - QString type = elementElement.attribute( "type" ); + QString name = elementElement.attribute( QStringLiteral( "name" ) ); + QString type = elementElement.attribute( QStringLiteral( "type" ) ); QString gmlBaseType = xsdComplexTypeGmlBaseType( docElem, stripNS( type ) ); //QgsDebugMsg( QString( "gmlBaseType = %1" ).arg( gmlBaseType ) ); @@ -114,10 +114,10 @@ bool QgsGmlSchema::parseXSD( const QByteArray &xml ) // ancestor listed in gml:FeatureAssociationType (featureMember) descendant // But we could only loose some data if XSD was not correct, I think. - if ( gmlBaseType == "AbstractFeatureType" ) + if ( gmlBaseType == QLatin1String( "AbstractFeatureType" ) ) { // Get feature type definition - QgsGmlFeatureClass featureClass( name, "" ); + QgsGmlFeatureClass featureClass( name, QLatin1String( "" ) ); xsdFeatureClass( docElem, stripNS( type ), featureClass ); mFeatureClassMap.insert( name, featureClass ); } @@ -130,19 +130,19 @@ bool QgsGmlSchema::parseXSD( const QByteArray &xml ) bool QgsGmlSchema::xsdFeatureClass( const QDomElement &element, const QString & typeName, QgsGmlFeatureClass & featureClass ) { //QgsDebugMsg("typeName = " + typeName ); - QDomElement complexTypeElement = domElement( element, "complexType", "name", typeName ); + QDomElement complexTypeElement = domElement( element, QStringLiteral( "complexType" ), QStringLiteral( "name" ), typeName ); if ( complexTypeElement.isNull() ) return false; // extension or restriction - QDomElement extrest = domElement( complexTypeElement, "complexContent.extension" ); + QDomElement extrest = domElement( complexTypeElement, QStringLiteral( "complexContent.extension" ) ); if ( extrest.isNull() ) { - extrest = domElement( complexTypeElement, "complexContent.restriction" ); + extrest = domElement( complexTypeElement, QStringLiteral( "complexContent.restriction" ) ); } if ( extrest.isNull() ) return false; - QString extrestName = extrest.attribute( "base" ); - if ( extrestName == "gml:AbstractFeatureType" ) + QString extrestName = extrest.attribute( QStringLiteral( "base" ) ); + if ( extrestName == QLatin1String( "gml:AbstractFeatureType" ) ) { // In theory we should add gml:AbstractFeatureType default attributes gml:description // and gml:name but it does not seem to be a common practice and we would probably @@ -162,23 +162,23 @@ bool QgsGmlSchema::xsdFeatureClass( const QDomElement &element, const QString & } QStringList geometryAliases; - geometryAliases << "location" << "centerOf" << "position" << "extentOf" - << "coverage" << "edgeOf" << "centerLineOf" << "multiLocation" - << "multiCenterOf" << "multiPosition" << "multiCenterLineOf" - << "multiEdgeOf" << "multiCoverage" << "multiExtentOf"; + geometryAliases << QStringLiteral( "location" ) << QStringLiteral( "centerOf" ) << QStringLiteral( "position" ) << QStringLiteral( "extentOf" ) + << QStringLiteral( "coverage" ) << QStringLiteral( "edgeOf" ) << QStringLiteral( "centerLineOf" ) << QStringLiteral( "multiLocation" ) + << QStringLiteral( "multiCenterOf" ) << QStringLiteral( "multiPosition" ) << QStringLiteral( "multiCenterLineOf" ) + << QStringLiteral( "multiEdgeOf" ) << QStringLiteral( "multiCoverage" ) << QStringLiteral( "multiExtentOf" ); // Add attributes from current comple type - QList sequenceElements = domElements( extrest, "sequence.element" ); + QList sequenceElements = domElements( extrest, QStringLiteral( "sequence.element" ) ); Q_FOREACH ( const QDomElement& sequenceElement, sequenceElements ) { - QString fieldName = sequenceElement.attribute( "name" ); - QString fieldTypeName = stripNS( sequenceElement.attribute( "type" ) ); - QString ref = sequenceElement.attribute( "ref" ); + QString fieldName = sequenceElement.attribute( QStringLiteral( "name" ) ); + QString fieldTypeName = stripNS( sequenceElement.attribute( QStringLiteral( "type" ) ) ); + QString ref = sequenceElement.attribute( QStringLiteral( "ref" ) ); //QgsDebugMsg ( QString("fieldName = %1 fieldTypeName = %2 ref = %3").arg(fieldName).arg(fieldTypeName).arg(ref) ); if ( !ref.isEmpty() ) { - if ( ref.startsWith( "gml:" ) ) + if ( ref.startsWith( QLatin1String( "gml:" ) ) ) { if ( geometryAliases.contains( stripNS( ref ) ) ) { @@ -207,8 +207,8 @@ bool QgsGmlSchema::xsdFeatureClass( const QDomElement &element, const QString & if ( fieldTypeName.isEmpty() ) { // or type is inheriting from xs:simpleType - QDomElement sequenceElementRestriction = domElement( sequenceElement, "simpleType.restriction" ); - fieldTypeName = stripNS( sequenceElementRestriction.attribute( "base" ) ); + QDomElement sequenceElementRestriction = domElement( sequenceElement, QStringLiteral( "simpleType.restriction" ) ); + fieldTypeName = stripNS( sequenceElementRestriction.attribute( QStringLiteral( "base" ) ) ); } QVariant::Type fieldType = QVariant::String; @@ -225,11 +225,11 @@ bool QgsGmlSchema::xsdFeatureClass( const QDomElement &element, const QString & continue; } - if ( fieldTypeName == "decimal" ) + if ( fieldTypeName == QLatin1String( "decimal" ) ) { fieldType = QVariant::Double; } - else if ( fieldTypeName == "integer" ) + else if ( fieldTypeName == QLatin1String( "integer" ) ) { fieldType = QVariant::Int; } @@ -245,18 +245,18 @@ bool QgsGmlSchema::xsdFeatureClass( const QDomElement &element, const QString & QString QgsGmlSchema::xsdComplexTypeGmlBaseType( const QDomElement &element, const QString & name ) { //QgsDebugMsg("name = " + name ); - QDomElement complexTypeElement = domElement( element, "complexType", "name", name ); - if ( complexTypeElement.isNull() ) return ""; + QDomElement complexTypeElement = domElement( element, QStringLiteral( "complexType" ), QStringLiteral( "name" ), name ); + if ( complexTypeElement.isNull() ) return QLatin1String( "" ); - QDomElement extrest = domElement( complexTypeElement, "complexContent.extension" ); + QDomElement extrest = domElement( complexTypeElement, QStringLiteral( "complexContent.extension" ) ); if ( extrest.isNull() ) { - extrest = domElement( complexTypeElement, "complexContent.restriction" ); + extrest = domElement( complexTypeElement, QStringLiteral( "complexContent.restriction" ) ); } - if ( extrest.isNull() ) return ""; + if ( extrest.isNull() ) return QLatin1String( "" ); - QString extrestName = extrest.attribute( "base" ); - if ( extrestName.startsWith( "gml:" ) ) + QString extrestName = extrest.attribute( QStringLiteral( "base" ) ); + if ( extrestName.startsWith( QLatin1String( "gml:" ) ) ) { // GML base type found return stripNS( extrestName ); @@ -294,7 +294,7 @@ QList QgsGmlSchema::domElements( const QDomElement &element, const } else { - list.append( domElements( el, names.join( "." ) ) ); + list.append( domElements( el, names.join( QStringLiteral( "." ) ) ) ); } } } @@ -343,7 +343,7 @@ bool QgsGmlSchema::guessSchema( const QByteArray &data ) { QString err = QString( XML_ErrorString( XML_GetErrorCode( p ) ) ); QgsDebugMsg( QString( "XML_Parse returned %1 error %2" ).arg( res ).arg( err ) ); - mError = QgsError( err, "GML schema" ); + mError = QgsError( err, QStringLiteral( "GML schema" ) ); mError.append( tr( "Cannot guess schema" ) ); } @@ -365,22 +365,22 @@ void QgsGmlSchema::startElement( const XML_Char* el, const XML_Char** attr ) } mParsePathStack.append( elementName ); - QString path = mParsePathStack.join( "." ); + QString path = mParsePathStack.join( QStringLiteral( "." ) ); QStringList splitName = elementName.split( NS_SEPARATOR ); QString localName = splitName.last(); - QString ns = splitName.size() > 1 ? splitName.first() : ""; + QString ns = splitName.size() > 1 ? splitName.first() : QLatin1String( "" ); //QgsDebugMsg( "ns = " + ns + " localName = " + localName ); ParseMode parseMode = modeStackTop(); //QgsDebugMsg ( QString("localName = %1 parseMode = %2").arg(localName).arg(parseMode) ); - if ( ns == GML_NAMESPACE && localName == "boundedBy" ) + if ( ns == GML_NAMESPACE && localName == QLatin1String( "boundedBy" ) ) { // gml:boundedBy in feature or feature collection -> skip mSkipLevel = mLevel + 1; } - else if ( localName.compare( "featureMembers", Qt::CaseInsensitive ) == 0 ) + else if ( localName.compare( QLatin1String( "featureMembers" ), Qt::CaseInsensitive ) == 0 ) { mParseModeStack.push( QgsGmlSchema::featureMembers ); } @@ -389,12 +389,12 @@ void QgsGmlSchema::startElement( const XML_Char* el, const XML_Char** attr ) // that the names ends with 'Member', e.g.: osgb:topographicMember, cityMember,... // so this is really fail if the name does not contain 'Member' - else if ( localName.endsWith( "member", Qt::CaseInsensitive ) ) + else if ( localName.endsWith( QLatin1String( "member" ), Qt::CaseInsensitive ) ) { mParseModeStack.push( QgsGmlSchema::featureMember ); } // UMN Mapserver simple GetFeatureInfo response layer element (ends with _layer) - else if ( elementName.endsWith( "_layer" ) ) + else if ( elementName.endsWith( QLatin1String( "_layer" ) ) ) { // do nothing, we catch _feature children } @@ -402,10 +402,10 @@ void QgsGmlSchema::startElement( const XML_Char* el, const XML_Char** attr ) // or featureMember children. // QGIS mapserver 2.2 GetFeatureInfo is using for feature member, // without any feature class distinction. - else if ( elementName.endsWith( "_feature" ) + else if ( elementName.endsWith( QLatin1String( "_feature" ) ) || parseMode == QgsGmlSchema::featureMember || parseMode == QgsGmlSchema::featureMembers - || localName.compare( "feature", Qt::CaseInsensitive ) == 0 ) + || localName.compare( QLatin1String( "feature" ), Qt::CaseInsensitive ) == 0 ) { QgsDebugMsg( "is feature path = " + path ); if ( mFeatureClassMap.count( localName ) == 0 ) @@ -434,12 +434,12 @@ void QgsGmlSchema::startElement( const XML_Char* el, const XML_Char** attr ) // My description // but QGIS server (2.2) is using: // - QString name = readAttribute( "name", attr ); + QString name = readAttribute( QStringLiteral( "name" ), attr ); //QgsDebugMsg ( "attribute name = " + name ); - if ( localName.compare( "attribute", Qt::CaseInsensitive ) == 0 + if ( localName.compare( QLatin1String( "attribute" ), Qt::CaseInsensitive ) == 0 && !name.isEmpty() ) { - QString value = readAttribute( "value", attr ); + QString value = readAttribute( QStringLiteral( "value" ), attr ); //QgsDebugMsg ( "attribute value = " + value ); addAttribute( name, value ); } @@ -471,7 +471,7 @@ void QgsGmlSchema::endElement( const XML_Char* el ) QStringList splitName = elementName.split( NS_SEPARATOR ); QString localName = splitName.last(); - QString ns = splitName.size() > 1 ? splitName.first() : ""; + QString ns = splitName.size() > 1 ? splitName.first() : QLatin1String( "" ); QgsGmlSchema::ParseMode parseMode = modeStackTop(); @@ -490,11 +490,11 @@ void QgsGmlSchema::endElement( const XML_Char* el ) addAttribute( mAttributeName, mStringCash ); } } - else if ( ns == GML_NAMESPACE && localName == "boundedBy" ) + else if ( ns == GML_NAMESPACE && localName == QLatin1String( "boundedBy" ) ) { // was skipped } - else if ( localName.endsWith( "member", Qt::CaseInsensitive ) ) + else if ( localName.endsWith( QLatin1String( "member" ), Qt::CaseInsensitive ) ) { modeStackPop(); } diff --git a/src/core/qgsinterval.cpp b/src/core/qgsinterval.cpp index 30152c327c33..538ad9d9bcc7 100644 --- a/src/core/qgsinterval.cpp +++ b/src/core/qgsinterval.cpp @@ -63,13 +63,13 @@ QgsInterval QgsInterval::fromString( const QString& string ) } QMap map; - map.insert( 1, QStringList() << "second" << "seconds" << QObject::tr( "second|seconds", "list of words separated by | which reference years" ).split( '|' ) ); - map.insert( 0 + MINUTE, QStringList() << "minute" << "minutes" << QObject::tr( "minute|minutes", "list of words separated by | which reference minutes" ).split( '|' ) ); - map.insert( 0 + HOUR, QStringList() << "hour" << "hours" << QObject::tr( "hour|hours", "list of words separated by | which reference minutes hours" ).split( '|' ) ); - map.insert( 0 + DAY, QStringList() << "day" << "days" << QObject::tr( "day|days", "list of words separated by | which reference days" ).split( '|' ) ); - map.insert( 0 + WEEKS, QStringList() << "week" << "weeks" << QObject::tr( "week|weeks", "wordlist separated by | which reference weeks" ).split( '|' ) ); - map.insert( 0 + MONTHS, QStringList() << "month" << "months" << QObject::tr( "month|months", "list of words separated by | which reference months" ).split( '|' ) ); - map.insert( 0 + YEARS, QStringList() << "year" << "years" << QObject::tr( "year|years", "list of words separated by | which reference years" ).split( '|' ) ); + map.insert( 1, QStringList() << QStringLiteral( "second" ) << QStringLiteral( "seconds" ) << QObject::tr( "second|seconds", "list of words separated by | which reference years" ).split( '|' ) ); + map.insert( 0 + MINUTE, QStringList() << QStringLiteral( "minute" ) << QStringLiteral( "minutes" ) << QObject::tr( "minute|minutes", "list of words separated by | which reference minutes" ).split( '|' ) ); + map.insert( 0 + HOUR, QStringList() << QStringLiteral( "hour" ) << QStringLiteral( "hours" ) << QObject::tr( "hour|hours", "list of words separated by | which reference minutes hours" ).split( '|' ) ); + map.insert( 0 + DAY, QStringList() << QStringLiteral( "day" ) << QStringLiteral( "days" ) << QObject::tr( "day|days", "list of words separated by | which reference days" ).split( '|' ) ); + map.insert( 0 + WEEKS, QStringList() << QStringLiteral( "week" ) << QStringLiteral( "weeks" ) << QObject::tr( "week|weeks", "wordlist separated by | which reference weeks" ).split( '|' ) ); + map.insert( 0 + MONTHS, QStringList() << QStringLiteral( "month" ) << QStringLiteral( "months" ) << QObject::tr( "month|months", "list of words separated by | which reference months" ).split( '|' ) ); + map.insert( 0 + YEARS, QStringList() << QStringLiteral( "year" ) << QStringLiteral( "years" ) << QObject::tr( "year|years", "list of words separated by | which reference years" ).split( '|' ) ); Q_FOREACH ( const QString& match, list ) { diff --git a/src/core/qgsjsonutils.cpp b/src/core/qgsjsonutils.cpp index 680d161b63d3..fc3f0a18be3a 100644 --- a/src/core/qgsjsonutils.cpp +++ b/src/core/qgsjsonutils.cpp @@ -72,10 +72,10 @@ QgsCoordinateReferenceSystem QgsJSONExporter::sourceCrs() const QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVariantMap& extraProperties, const QVariant& id ) const { - QString s = "{\n \"type\":\"Feature\",\n"; + QString s = QStringLiteral( "{\n \"type\":\"Feature\",\n" ); // ID - s += QString( " \"id\":%1,\n" ).arg( !id.isValid() ? QString::number( feature.id() ) : QgsJSONUtils::encodeValue( id ) ); + s += QStringLiteral( " \"id\":%1,\n" ).arg( !id.isValid() ? QString::number( feature.id() ) : QgsJSONUtils::encodeValue( id ) ); QgsGeometry geom = feature.geometry(); if ( !geom.isEmpty() && mIncludeGeometry ) @@ -97,18 +97,18 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian if ( QgsWkbTypes::flatType( geom.geometry()->wkbType() ) != QgsWkbTypes::Point ) { - s += QString( " \"bbox\":[%1, %2, %3, %4],\n" ).arg( qgsDoubleToString( box.xMinimum(), mPrecision ), + s += QStringLiteral( " \"bbox\":[%1, %2, %3, %4],\n" ).arg( qgsDoubleToString( box.xMinimum(), mPrecision ), qgsDoubleToString( box.yMinimum(), mPrecision ), qgsDoubleToString( box.xMaximum(), mPrecision ), qgsDoubleToString( box.yMaximum(), mPrecision ) ); } - s += " \"geometry\":\n "; + s += QLatin1String( " \"geometry\":\n " ); s += geom.exportToGeoJSON( mPrecision ); - s += ",\n"; + s += QLatin1String( ",\n" ); } else { - s += " \"geometry\":null,\n"; + s += QLatin1String( " \"geometry\":null,\n" ); } // build up properties element @@ -128,10 +128,10 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian continue; if ( attributeCounter > 0 ) - properties += ",\n"; + properties += QLatin1String( ",\n" ); QVariant val = feature.attributes().at( i ); - properties += QString( " \"%1\":%2" ).arg( fields.at( i ).name(), QgsJSONUtils::encodeValue( val ) ); + properties += QStringLiteral( " \"%1\":%2" ).arg( fields.at( i ).name(), QgsJSONUtils::encodeValue( val ) ); ++attributeCounter; } @@ -143,9 +143,9 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian for ( ; it != extraProperties.constEnd(); ++it ) { if ( attributeCounter > 0 ) - properties += ",\n"; + properties += QLatin1String( ",\n" ); - properties += QString( " \"%1\":%2" ).arg( it.key(), QgsJSONUtils::encodeValue( it.value() ) ); + properties += QStringLiteral( " \"%1\":%2" ).arg( it.key(), QgsJSONUtils::encodeValue( it.value() ) ); ++attributeCounter; } @@ -159,7 +159,7 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian Q_FOREACH ( const QgsRelation& relation, relations ) { if ( attributeCounter > 0 ) - properties += ",\n"; + properties += QLatin1String( ",\n" ); QgsFeatureRequest req = relation.getRelatedFeaturesRequest( feature ); req.setFlags( QgsFeatureRequest::NoGeometry ); @@ -173,7 +173,7 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian while ( it.nextFeature( relatedFet ) ) { if ( relationFeatures > 0 ) - relatedFeatureAttributes += ",\n"; + relatedFeatureAttributes += QLatin1String( ",\n" ); relatedFeatureAttributes += QgsJSONUtils::exportAttributes( relatedFet ); relationFeatures++; @@ -181,7 +181,7 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian } relatedFeatureAttributes.prepend( '[' ).append( ']' ); - properties += QString( " \"%1\":%2" ).arg( relation.name(), relatedFeatureAttributes ); + properties += QStringLiteral( " \"%1\":%2" ).arg( relation.name(), relatedFeatureAttributes ); attributeCounter++; } } @@ -189,7 +189,7 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian bool hasProperties = attributeCounter > 0; - s += " \"properties\":"; + s += QLatin1String( " \"properties\":" ); if ( hasProperties ) { //read all attribute values from the feature @@ -197,7 +197,7 @@ QString QgsJSONExporter::exportFeature( const QgsFeature& feature, const QVarian } else { - s += "null\n"; + s += QLatin1String( "null\n" ); } s += '}'; @@ -213,7 +213,7 @@ QString QgsJSONExporter::exportFeatures( const QgsFeatureList& features ) const featureJSON << exportFeature( feature ); } - return QString( "{ \"type\": \"FeatureCollection\",\n \"features\":[\n%1\n]}" ).arg( featureJSON.join( ",\n" ) ); + return QStringLiteral( "{ \"type\": \"FeatureCollection\",\n \"features\":[\n%1\n]}" ).arg( featureJSON.join( QStringLiteral( ",\n" ) ) ); } @@ -235,7 +235,7 @@ QgsFields QgsJSONUtils::stringToFields( const QString &string, QTextCodec *encod QString QgsJSONUtils::encodeValue( const QVariant &value ) { if ( value.isNull() ) - return "null"; + return QStringLiteral( "null" ); switch ( value.type() ) { @@ -257,13 +257,13 @@ QString QgsJSONUtils::encodeValue( const QVariant &value ) default: case QVariant::String: QString v = value.toString() - .replace( '\\', "\\\\" ) - .replace( '"', "\\\"" ) - .replace( '\r', "\\r" ) - .replace( '\b', "\\b" ) - .replace( '\t', "\\t" ) - .replace( '/', "\\/" ) - .replace( '\n', "\\n" ); + .replace( '\\', QLatin1String( "\\\\" ) ) + .replace( '"', QLatin1String( "\\\"" ) ) + .replace( '\r', QLatin1String( "\\r" ) ) + .replace( '\b', QLatin1String( "\\b" ) ) + .replace( '\t', QLatin1String( "\\t" ) ) + .replace( '/', QLatin1String( "\\/" ) ) + .replace( '\n', QLatin1String( "\\n" ) ); return v.prepend( '"' ).append( '"' ); } @@ -276,7 +276,7 @@ QString QgsJSONUtils::exportAttributes( const QgsFeature& feature ) for ( int i = 0; i < fields.count(); ++i ) { if ( i > 0 ) - attrs += ",\n"; + attrs += QLatin1String( ",\n" ); QVariant val = feature.attributes().at( i ); attrs += encodeValue( fields.at( i ).name() ) + ':' + encodeValue( val ); @@ -291,12 +291,12 @@ QVariantList QgsJSONUtils::parseArray( const QString& json, QVariant::Type type QVariantList result; if ( error.error != QJsonParseError::NoError ) { - QgsLogger::warning( QString( "Cannot parse json (%1): %2" ).arg( error.errorString(), json ) ); + QgsLogger::warning( QStringLiteral( "Cannot parse json (%1): %2" ).arg( error.errorString(), json ) ); return result; } if ( !jsonDoc.isArray() ) { - QgsLogger::warning( QString( "Cannot parse json (%1) as array: %2" ).arg( error.errorString(), json ) ); + QgsLogger::warning( QStringLiteral( "Cannot parse json (%1) as array: %2" ).arg( error.errorString(), json ) ); return result; } Q_FOREACH ( const QJsonValue& cur, jsonDoc.array() ) @@ -305,7 +305,7 @@ QVariantList QgsJSONUtils::parseArray( const QString& json, QVariant::Type type if ( curVariant.convert( type ) ) result.append( curVariant ); else - QgsLogger::warning( QString( "Cannot convert json array element: %1" ).arg( cur.toString() ) ); + QgsLogger::warning( QStringLiteral( "Cannot convert json array element: %1" ).arg( cur.toString() ) ); } return result; } diff --git a/src/core/qgslabelingengine.cpp b/src/core/qgslabelingengine.cpp index 8819c97a22bd..8fa2c4d478ef 100644 --- a/src/core/qgslabelingengine.cpp +++ b/src/core/qgslabelingengine.cpp @@ -341,31 +341,31 @@ void QgsLabelingEngine::readSettingsFromProject() { bool saved = false; QgsProject* prj = QgsProject::instance(); - mSearchMethod = static_cast< QgsPalLabeling::Search >( prj->readNumEntry( "PAL", "/SearchMethod", static_cast< int >( QgsPalLabeling::Chain ), &saved ) ); - mCandPoint = prj->readNumEntry( "PAL", "/CandidatesPoint", 16, &saved ); - mCandLine = prj->readNumEntry( "PAL", "/CandidatesLine", 50, &saved ); - mCandPolygon = prj->readNumEntry( "PAL", "/CandidatesPolygon", 30, &saved ); + mSearchMethod = static_cast< QgsPalLabeling::Search >( prj->readNumEntry( QStringLiteral( "PAL" ), QStringLiteral( "/SearchMethod" ), static_cast< int >( QgsPalLabeling::Chain ), &saved ) ); + mCandPoint = prj->readNumEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesPoint" ), 16, &saved ); + mCandLine = prj->readNumEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesLine" ), 50, &saved ); + mCandPolygon = prj->readNumEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesPolygon" ), 30, &saved ); mFlags = 0; - if ( prj->readBoolEntry( "PAL", "/ShowingCandidates", false, &saved ) ) mFlags |= DrawCandidates; - if ( prj->readBoolEntry( "PAL", "/DrawRectOnly", false, &saved ) ) mFlags |= DrawLabelRectOnly; - if ( prj->readBoolEntry( "PAL", "/ShowingAllLabels", false, &saved ) ) mFlags |= UseAllLabels; - if ( prj->readBoolEntry( "PAL", "/ShowingPartialsLabels", true, &saved ) ) mFlags |= UsePartialCandidates; - if ( prj->readBoolEntry( "PAL", "/DrawOutlineLabels", true, &saved ) ) mFlags |= RenderOutlineLabels; + if ( prj->readBoolEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingCandidates" ), false, &saved ) ) mFlags |= DrawCandidates; + if ( prj->readBoolEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawRectOnly" ), false, &saved ) ) mFlags |= DrawLabelRectOnly; + if ( prj->readBoolEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingAllLabels" ), false, &saved ) ) mFlags |= UseAllLabels; + if ( prj->readBoolEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingPartialsLabels" ), true, &saved ) ) mFlags |= UsePartialCandidates; + if ( prj->readBoolEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), true, &saved ) ) mFlags |= RenderOutlineLabels; } void QgsLabelingEngine::writeSettingsToProject() { - QgsProject::instance()->writeEntry( "PAL", "/SearchMethod", static_cast< int >( mSearchMethod ) ); - QgsProject::instance()->writeEntry( "PAL", "/CandidatesPoint", mCandPoint ); - QgsProject::instance()->writeEntry( "PAL", "/CandidatesLine", mCandLine ); - QgsProject::instance()->writeEntry( "PAL", "/CandidatesPolygon", mCandPolygon ); - - QgsProject::instance()->writeEntry( "PAL", "/ShowingCandidates", mFlags.testFlag( DrawCandidates ) ); - QgsProject::instance()->writeEntry( "PAL", "/DrawRectOnly", mFlags.testFlag( DrawLabelRectOnly ) ); - QgsProject::instance()->writeEntry( "PAL", "/ShowingAllLabels", mFlags.testFlag( UseAllLabels ) ); - QgsProject::instance()->writeEntry( "PAL", "/ShowingPartialsLabels", mFlags.testFlag( UsePartialCandidates ) ); - QgsProject::instance()->writeEntry( "PAL", "/DrawOutlineLabels", mFlags.testFlag( RenderOutlineLabels ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/SearchMethod" ), static_cast< int >( mSearchMethod ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesPoint" ), mCandPoint ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesLine" ), mCandLine ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesPolygon" ), mCandPolygon ); + + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingCandidates" ), mFlags.testFlag( DrawCandidates ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawRectOnly" ), mFlags.testFlag( DrawLabelRectOnly ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingAllLabels" ), mFlags.testFlag( UseAllLabels ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingPartialsLabels" ), mFlags.testFlag( UsePartialCandidates ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ), mFlags.testFlag( RenderOutlineLabels ) ); } @@ -404,44 +404,44 @@ QString QgsLabelingUtils::encodePredefinedPositionOrder( const QVector QgsLabelingUtils::decodePredefinedPositionOrder( const QString& positionString ) @@ -451,29 +451,29 @@ QVector QgsLabelingUtils::decodePr Q_FOREACH ( const QString& position, predefinedOrderList ) { QString cleaned = position.trimmed().toUpper(); - if ( cleaned == "TL" ) + if ( cleaned == QLatin1String( "TL" ) ) result << QgsPalLayerSettings::TopLeft; - else if ( cleaned == "TSL" ) + else if ( cleaned == QLatin1String( "TSL" ) ) result << QgsPalLayerSettings::TopSlightlyLeft; - else if ( cleaned == "T" ) + else if ( cleaned == QLatin1String( "T" ) ) result << QgsPalLayerSettings::TopMiddle; - else if ( cleaned == "TSR" ) + else if ( cleaned == QLatin1String( "TSR" ) ) result << QgsPalLayerSettings::TopSlightlyRight; - else if ( cleaned == "TR" ) + else if ( cleaned == QLatin1String( "TR" ) ) result << QgsPalLayerSettings::TopRight; - else if ( cleaned == "L" ) + else if ( cleaned == QLatin1String( "L" ) ) result << QgsPalLayerSettings::MiddleLeft; - else if ( cleaned == "R" ) + else if ( cleaned == QLatin1String( "R" ) ) result << QgsPalLayerSettings::MiddleRight; - else if ( cleaned == "BL" ) + else if ( cleaned == QLatin1String( "BL" ) ) result << QgsPalLayerSettings::BottomLeft; - else if ( cleaned == "BSL" ) + else if ( cleaned == QLatin1String( "BSL" ) ) result << QgsPalLayerSettings::BottomSlightlyLeft; - else if ( cleaned == "B" ) + else if ( cleaned == QLatin1String( "B" ) ) result << QgsPalLayerSettings::BottomMiddle; - else if ( cleaned == "BSR" ) + else if ( cleaned == QLatin1String( "BSR" ) ) result << QgsPalLayerSettings::BottomSlightlyRight; - else if ( cleaned == "BR" ) + else if ( cleaned == QLatin1String( "BR" ) ) result << QgsPalLayerSettings::BottomRight; } return result; diff --git a/src/core/qgslayerdefinition.cpp b/src/core/qgslayerdefinition.cpp index 18248f678d85..b2b16b2777bc 100644 --- a/src/core/qgslayerdefinition.cpp +++ b/src/core/qgslayerdefinition.cpp @@ -30,7 +30,7 @@ bool QgsLayerDefinition::loadLayerDefinition( const QString &path, QgsLayerTreeG QFile file( path ); if ( !file.open( QIODevice::ReadOnly ) ) { - errorMessage = QLatin1String( "Can not open file" ); + errorMessage = QStringLiteral( "Can not open file" ); return false; } @@ -65,7 +65,7 @@ bool QgsLayerDefinition::loadLayerDefinition( QDomDocument doc, QgsLayerTreeGrou { clonedSorted << node.cloneNode(); } - QDomNode layersNode = doc.elementsByTagName( "maplayers" ).at( 0 ); + QDomNode layersNode = doc.elementsByTagName( QStringLiteral( "maplayers" ) ).at( 0 ); // replace old children with new ones QDomNodeList childNodes = layersNode.childNodes(); for ( int i = 0; i < childNodes.size(); i++ ) @@ -77,7 +77,7 @@ bool QgsLayerDefinition::loadLayerDefinition( QDomDocument doc, QgsLayerTreeGrou // IDs of layers should be changed otherwise we may have more then one layer with the same id // We have to replace the IDs before we load them because it's too late once they are loaded - QDomNodeList ids = doc.elementsByTagName( "id" ); + QDomNodeList ids = doc.elementsByTagName( QStringLiteral( "id" ) ); for ( int i = 0; i < ids.size(); ++i ) { QDomNode idnode = ids.at( i ); @@ -86,50 +86,50 @@ bool QgsLayerDefinition::loadLayerDefinition( QDomDocument doc, QgsLayerTreeGrou // Strip the date part because we will replace it. QString layername = oldid.left( oldid.length() - 17 ); QDateTime dt = QDateTime::currentDateTime(); - QString newid = layername + dt.toString( "yyyyMMddhhmmsszzz" ) + QString::number( qrand() ); + QString newid = layername + dt.toString( QStringLiteral( "yyyyMMddhhmmsszzz" ) ) + QString::number( qrand() ); idElem.firstChild().setNodeValue( newid ); - QDomNodeList treeLayerNodes = doc.elementsByTagName( "layer-tree-layer" ); + QDomNodeList treeLayerNodes = doc.elementsByTagName( QStringLiteral( "layer-tree-layer" ) ); for ( int i = 0; i < treeLayerNodes.count(); ++i ) { QDomNode layerNode = treeLayerNodes.at( i ); QDomElement layerElem = layerNode.toElement(); - if ( layerElem.attribute( "id" ) == oldid ) + if ( layerElem.attribute( QStringLiteral( "id" ) ) == oldid ) { - layerNode.toElement().setAttribute( "id", newid ); + layerNode.toElement().setAttribute( QStringLiteral( "id" ), newid ); } } // change layer IDs for vector joins - QDomNodeList vectorJoinNodes = doc.elementsByTagName( "join" ); // TODO: Find a better way of searching for vectorjoins, there might be other elements within the project. + QDomNodeList vectorJoinNodes = doc.elementsByTagName( QStringLiteral( "join" ) ); // TODO: Find a better way of searching for vectorjoins, there might be other elements within the project. for ( int j = 0; j < vectorJoinNodes.size(); ++j ) { QDomNode joinNode = vectorJoinNodes.at( j ); QDomElement joinElement = joinNode.toElement(); - if ( joinElement.attribute( "joinLayerId" ) == oldid ) + if ( joinElement.attribute( QStringLiteral( "joinLayerId" ) ) == oldid ) { - joinNode.toElement().setAttribute( "joinLayerId", newid ); + joinNode.toElement().setAttribute( QStringLiteral( "joinLayerId" ), newid ); } } // change IDs of dependencies - QDomNodeList dataDeps = doc.elementsByTagName( "dataDependencies" ); + QDomNodeList dataDeps = doc.elementsByTagName( QStringLiteral( "dataDependencies" ) ); for ( int i = 0; i < dataDeps.size(); i++ ) { QDomNodeList layers = dataDeps.at( i ).childNodes(); for ( int j = 0; j < layers.size(); j++ ) { QDomElement elt = layers.at( j ).toElement(); - if ( elt.attribute( "id" ) == oldid ) + if ( elt.attribute( QStringLiteral( "id" ) ) == oldid ) { - elt.setAttribute( "id", newid ); + elt.setAttribute( QStringLiteral( "id" ), newid ); } } } } - QDomElement layerTreeElem = doc.documentElement().firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = doc.documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) ); bool loadInLegend = true; if ( !layerTreeElem.isNull() ) { @@ -163,7 +163,7 @@ bool QgsLayerDefinition::loadLayerDefinition( QDomDocument doc, QgsLayerTreeGrou bool QgsLayerDefinition::exportLayerDefinition( QString path, const QList& selectedTreeNodes, QString &errorMessage ) { - if ( !path.endsWith( ".qlr" ) ) + if ( !path.endsWith( QLatin1String( ".qlr" ) ) ) path = path.append( ".qlr" ); QFile file( path ); @@ -176,7 +176,7 @@ bool QgsLayerDefinition::exportLayerDefinition( QString path, const QList& selectedTreeNodes, QString &errorMessage, const QString& relativeBasePath ) { Q_UNUSED( errorMessage ); - QDomElement qgiselm = doc.createElement( "qlr" ); + QDomElement qgiselm = doc.createElement( QStringLiteral( "qlr" ) ); doc.appendChild( qgiselm ); QList nodes = selectedTreeNodes; QgsLayerTreeGroup* root = new QgsLayerTreeGroup; @@ -199,11 +199,11 @@ bool QgsLayerDefinition::exportLayerDefinition( QDomDocument doc, const QListwriteXml( qgiselm ); - QDomElement layerselm = doc.createElement( "maplayers" ); + QDomElement layerselm = doc.createElement( QStringLiteral( "maplayers" ) ); QList layers = root->findLayers(); Q_FOREACH ( QgsLayerTreeLayer* layer, layers ) { - QDomElement layerelm = doc.createElement( "maplayer" ); + QDomElement layerelm = doc.createElement( QStringLiteral( "maplayer" ) ); layer->layer()->writeLayerXml( layerelm, doc, relativeBasePath ); layerselm.appendChild( layerelm ); } @@ -219,7 +219,7 @@ void QgsLayerDefinition::DependencySorter::init( const QDomDocument& doc ) QList< QPair > layersToSort; QStringList layerIds; - QDomNodeList nl = doc.elementsByTagName( "maplayer" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "maplayer" ) ); layerIds.reserve( nl.count() ); QVector deps; //avoid expensive allocation for list for every iteration for ( int i = 0; i < nl.count(); i++ ) @@ -227,18 +227,18 @@ void QgsLayerDefinition::DependencySorter::init( const QDomDocument& doc ) deps.resize( 0 ); // preserve capacity - don't use clear QDomNode node = nl.item( i ); - QString id = node.namedItem( "id" ).toElement().text(); + QString id = node.namedItem( QStringLiteral( "id" ) ).toElement().text(); layerIds << id; // dependencies for this layer - QDomElement layerDependenciesElem = node.firstChildElement( "layerDependencies" ); + QDomElement layerDependenciesElem = node.firstChildElement( QStringLiteral( "layerDependencies" ) ); if ( !layerDependenciesElem.isNull() ) { - QDomNodeList dependencyList = layerDependenciesElem.elementsByTagName( "layer" ); + QDomNodeList dependencyList = layerDependenciesElem.elementsByTagName( QStringLiteral( "layer" ) ); for ( int j = 0; j < dependencyList.size(); ++j ) { QDomElement depElem = dependencyList.at( j ).toElement(); - deps << depElem.attribute( "id" ); + deps << depElem.attribute( QStringLiteral( "id" ) ); } } dependencies[id] = deps; diff --git a/src/core/qgslegendrenderer.cpp b/src/core/qgslegendrenderer.cpp index 48875f229a08..8df06f55b592 100644 --- a/src/core/qgslegendrenderer.cpp +++ b/src/core/qgslegendrenderer.cpp @@ -333,7 +333,7 @@ void QgsLegendRenderer::setColumns( QList& atomList ) { if ( QgsLayerTreeModelLegendNode* legendNode = qobject_cast( atom.nucleons.at( j ).item ) ) { - QString key = QString( "%1-%2" ).arg( reinterpret_cast< qulonglong >( legendNode->layerNode() ) ).arg( atom.column ); + QString key = QStringLiteral( "%1-%2" ).arg( reinterpret_cast< qulonglong >( legendNode->layerNode() ) ).arg( atom.column ); maxSymbolWidth[key] = qMax( atom.nucleons.at( j ).symbolSize.width(), maxSymbolWidth[key] ); } } @@ -345,7 +345,7 @@ void QgsLegendRenderer::setColumns( QList& atomList ) { if ( QgsLayerTreeModelLegendNode* legendNode = qobject_cast( atom.nucleons.at( j ).item ) ) { - QString key = QString( "%1-%2" ).arg( reinterpret_cast< qulonglong >( legendNode->layerNode() ) ).arg( atom.column ); + QString key = QStringLiteral( "%1-%2" ).arg( reinterpret_cast< qulonglong >( legendNode->layerNode() ) ).arg( atom.column ); double space = mSettings.style( QgsComposerLegendStyle::Symbol ).margin( QgsComposerLegendStyle::Right ) + mSettings.style( QgsComposerLegendStyle::SymbolLabel ).margin( QgsComposerLegendStyle::Left ); atom.nucleons[j].labelXOffset = maxSymbolWidth[key] + space; @@ -580,12 +580,12 @@ QSizeF QgsLegendRenderer::drawGroupTitle( QgsLayerTreeGroup* nodeGroup, QPainter QgsComposerLegendStyle::Style QgsLegendRenderer::nodeLegendStyle( QgsLayerTreeNode* node, QgsLayerTreeModel* model ) { - QString style = node->customProperty( "legend/title-style" ).toString(); - if ( style == "hidden" ) + QString style = node->customProperty( QStringLiteral( "legend/title-style" ) ).toString(); + if ( style == QLatin1String( "hidden" ) ) return QgsComposerLegendStyle::Hidden; - else if ( style == "group" ) + else if ( style == QLatin1String( "group" ) ) return QgsComposerLegendStyle::Group; - else if ( style == "subgroup" ) + else if ( style == QLatin1String( "subgroup" ) ) return QgsComposerLegendStyle::Subgroup; // use a default otherwise @@ -613,20 +613,20 @@ void QgsLegendRenderer::setNodeLegendStyle( QgsLayerTreeNode* node, QgsComposerL switch ( style ) { case QgsComposerLegendStyle::Hidden: - str = "hidden"; + str = QStringLiteral( "hidden" ); break; case QgsComposerLegendStyle::Group: - str = "group"; + str = QStringLiteral( "group" ); break; case QgsComposerLegendStyle::Subgroup: - str = "subgroup"; + str = QStringLiteral( "subgroup" ); break; default: break; // nothing } if ( !str.isEmpty() ) - node->setCustomProperty( "legend/title-style", str ); + node->setCustomProperty( QStringLiteral( "legend/title-style" ), str ); else - node->removeCustomProperty( "legend/title-style" ); + node->removeCustomProperty( QStringLiteral( "legend/title-style" ) ); } diff --git a/src/core/qgslegendsettings.cpp b/src/core/qgslegendsettings.cpp index 92ea99b7d01b..c7309a31e258 100644 --- a/src/core/qgslegendsettings.cpp +++ b/src/core/qgslegendsettings.cpp @@ -20,7 +20,7 @@ QgsLegendSettings::QgsLegendSettings() : mTitle( QObject::tr( "Legend" ) ) , mTitleAlignment( Qt::AlignLeft ) - , mWrapChar( "" ) + , mWrapChar( QLatin1String( "" ) ) , mFontColor( QColor( 0, 0, 0 ) ) , mBoxSpace( 2 ) , mSymbolSize( 7, 4 ) diff --git a/src/core/qgslogger.cpp b/src/core/qgslogger.cpp index 2f3709ea7d96..ef0d9b0469a0 100644 --- a/src/core/qgslogger.cpp +++ b/src/core/qgslogger.cpp @@ -74,21 +74,21 @@ void QgsLogger::debug( const QString& msg, int debuglevel, const char* file, con { if ( qApp && qApp->thread() != QThread::currentThread() ) { - m.prepend( QString( "[thread:0x%1] " ).arg( reinterpret_cast< qint64 >( QThread::currentThread() ), 0, 16 ) ); + m.prepend( QStringLiteral( "[thread:0x%1] " ).arg( reinterpret_cast< qint64 >( QThread::currentThread() ), 0, 16 ) ); } - m.prepend( QString( "[%1ms] " ).arg( sTime.elapsed() ) ); + m.prepend( QStringLiteral( "[%1ms] " ).arg( sTime.elapsed() ) ); sTime.restart(); if ( function ) { - m.prepend( QString( " (%1) " ).arg( function ) ); + m.prepend( QStringLiteral( " (%1) " ).arg( function ) ); } if ( line != -1 ) { #ifndef _MSC_VER - m.prepend( QString( ": %1:" ).arg( line ) ); + m.prepend( QStringLiteral( ": %1:" ).arg( line ) ); #else m.prepend( QString( "(%1) :" ).arg( line ) ); #endif @@ -113,12 +113,12 @@ void QgsLogger::debug( const QString& msg, int debuglevel, const char* file, con void QgsLogger::debug( const QString& var, int val, int debuglevel, const char* file, const char* function, int line ) { - debug( QString( "%1: %2" ).arg( var ).arg( val ), debuglevel, file, function, line ); + debug( QStringLiteral( "%1: %2" ).arg( var ).arg( val ), debuglevel, file, function, line ); } void QgsLogger::debug( const QString& var, double val, int debuglevel, const char* file, const char* function, int line ) { - debug( QString( "%1: %2" ).arg( var ).arg( val ), debuglevel, file, function, line ); + debug( QStringLiteral( "%1: %2" ).arg( var ).arg( val ), debuglevel, file, function, line ); } void QgsLogger::warning( const QString& msg ) diff --git a/src/core/qgslogger.h b/src/core/qgslogger.h index 4e9b4016c964..714df4954c3d 100644 --- a/src/core/qgslogger.h +++ b/src/core/qgslogger.h @@ -120,11 +120,11 @@ class QgsScopeLogger // clazy:exclude=rule-of-three , _func( func ) , _line( line ) { - QgsLogger::debug( "Entering.", 1, _file, _func, _line ); + QgsLogger::debug( QStringLiteral( "Entering." ), 1, _file, _func, _line ); } ~QgsScopeLogger() { - QgsLogger::debug( "Leaving.", 1, _file, _func, _line ); + QgsLogger::debug( QStringLiteral( "Leaving." ), 1, _file, _func, _line ); } private: const char *_file; diff --git a/src/core/qgsmaplayer.cpp b/src/core/qgsmaplayer.cpp index 243b54479494..7322ba409c80 100644 --- a/src/core/qgsmaplayer.cpp +++ b/src/core/qgsmaplayer.cpp @@ -57,7 +57,7 @@ QgsMapLayer::QgsMapLayer( QgsMapLayer::LayerType type, : mValid( false ) // assume the layer is invalid , mDataSource( source ) , mLayerOrigName( lyrname ) // store the original name - , mID( "" ) + , mID( QLatin1String( "" ) ) , mLayerType( type ) , mBlendMode( QPainter::CompositionMode_SourceOver ) // Default to normal blending , mLegend( nullptr ) @@ -66,19 +66,19 @@ QgsMapLayer::QgsMapLayer( QgsMapLayer::LayerType type, // Set the display name = internal name mLayerName = capitaliseLayerName( mLayerOrigName ); - mShortName = ""; + mShortName = QLatin1String( "" ); //mShortName.replace( QRegExp( "[\\W]" ), "_" ); // Generate the unique ID of this layer QDateTime dt = QDateTime::currentDateTime(); - mID = lyrname + dt.toString( "yyyyMMddhhmmsszzz" ); + mID = lyrname + dt.toString( QStringLiteral( "yyyyMMddhhmmsszzz" ) ); // Tidy the ID up to avoid characters that may cause problems // elsewhere (e.g in some parts of XML). Replaces every non-word // character (word characters are the alphabet, numbers and // underscore) with an underscore. // Note that the first backslashe in the regular expression is // there for the compiler, so the pattern is actually \W - mID.replace( QRegExp( "[\\W]" ), "_" ); + mID.replace( QRegExp( "[\\W]" ), QStringLiteral( "_" ) ); //set some generous defaults for scale based visibility mMinScale = 0; @@ -164,12 +164,12 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) // read provider QString provider; - mnl = layerElement.namedItem( "provider" ); + mnl = layerElement.namedItem( QStringLiteral( "provider" ) ); mne = mnl.toElement(); provider = mne.text(); // set data source - mnl = layerElement.namedItem( "datasource" ); + mnl = layerElement.namedItem( QStringLiteral( "datasource" ) ); mne = mnl.toElement(); mDataSource = mne.text(); @@ -183,32 +183,32 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) // TODO: this should go to providers // see also QgsProject::createEmbeddedLayer - if ( provider == "spatialite" ) + if ( provider == QLatin1String( "spatialite" ) ) { QgsDataSourceUri uri( mDataSource ); uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) ); mDataSource = uri.uri(); } - else if ( provider == "ogr" ) + else if ( provider == QLatin1String( "ogr" ) ) { QStringList theURIParts = mDataSource.split( '|' ); theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] ); - mDataSource = theURIParts.join( "|" ); + mDataSource = theURIParts.join( QStringLiteral( "|" ) ); } - else if ( provider == "gpx" ) + else if ( provider == QLatin1String( "gpx" ) ) { QStringList theURIParts = mDataSource.split( '?' ); theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] ); - mDataSource = theURIParts.join( "?" ); + mDataSource = theURIParts.join( QStringLiteral( "?" ) ); } - else if ( provider == "delimitedtext" ) + else if ( provider == QLatin1String( "delimitedtext" ) ) { QUrl urlSource = QUrl::fromEncoded( mDataSource.toLatin1() ); - if ( !mDataSource.startsWith( "file:" ) ) + if ( !mDataSource.startsWith( QLatin1String( "file:" ) ) ) { QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( '?' ) ) ); - urlSource.setScheme( "file" ); + urlSource.setScheme( QStringLiteral( "file" ) ); urlSource.setPath( file.path() ); } @@ -216,7 +216,7 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) urlDest.setQueryItems( urlSource.queryItems() ); mDataSource = QString::fromAscii( urlDest.toEncoded() ); } - else if ( provider == "wms" ) + else if ( provider == QLatin1String( "wms" ) ) { // >>> BACKWARD COMPATIBILITY < 1.9 // For project file backward compatibility we must support old format: @@ -230,27 +230,27 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) // The new format has always params crs,format,layers,styles and that params // should not appear in old format url -> use them to identify version // XYZ tile layers do not need to contain crs,format params, but they have type=xyz - if ( !mDataSource.contains( "type=" ) && - !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) ) + if ( !mDataSource.contains( QLatin1String( "type=" ) ) && + !mDataSource.contains( QLatin1String( "crs=" ) ) && !mDataSource.contains( QLatin1String( "format=" ) ) ) { QgsDebugMsg( "Old WMS URI format detected -> converting to new format" ); QgsDataSourceUri uri; - if ( !mDataSource.startsWith( "http:" ) ) + if ( !mDataSource.startsWith( QLatin1String( "http:" ) ) ) { QStringList parts = mDataSource.split( ',' ); QStringListIterator iter( parts ); while ( iter.hasNext() ) { QString item = iter.next(); - if ( item.startsWith( "username=" ) ) + if ( item.startsWith( QLatin1String( "username=" ) ) ) { - uri.setParam( "username", item.mid( 9 ) ); + uri.setParam( QStringLiteral( "username" ), item.mid( 9 ) ); } - else if ( item.startsWith( "password=" ) ) + else if ( item.startsWith( QLatin1String( "password=" ) ) ) { - uri.setParam( "password", item.mid( 9 ) ); + uri.setParam( QStringLiteral( "password" ), item.mid( 9 ) ); } - else if ( item.startsWith( "tiled=" ) ) + else if ( item.startsWith( QLatin1String( "tiled=" ) ) ) { // in < 1.9 tiled= may apper in to variants: // tiled=width;height - non tiled mode, specifies max width and max height @@ -260,33 +260,33 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) if ( params.size() == 2 ) // non tiled mode { - uri.setParam( "maxWidth", params.takeFirst() ); - uri.setParam( "maxHeight", params.takeFirst() ); + uri.setParam( QStringLiteral( "maxWidth" ), params.takeFirst() ); + uri.setParam( QStringLiteral( "maxHeight" ), params.takeFirst() ); } else if ( params.size() > 2 ) // tiled mode { // resolutions are no more needed and size limit is not used for tiles // we have to tell to the provider however that it is tiled - uri.setParam( "tileMatrixSet", "" ); + uri.setParam( QStringLiteral( "tileMatrixSet" ), QLatin1String( "" ) ); } } - else if ( item.startsWith( "featureCount=" ) ) + else if ( item.startsWith( QLatin1String( "featureCount=" ) ) ) { - uri.setParam( "featureCount", item.mid( 13 ) ); + uri.setParam( QStringLiteral( "featureCount" ), item.mid( 13 ) ); } - else if ( item.startsWith( "url=" ) ) + else if ( item.startsWith( QLatin1String( "url=" ) ) ) { - uri.setParam( "url", item.mid( 4 ) ); + uri.setParam( QStringLiteral( "url" ), item.mid( 4 ) ); } - else if ( item.startsWith( "ignoreUrl=" ) ) + else if ( item.startsWith( QLatin1String( "ignoreUrl=" ) ) ) { - uri.setParam( "ignoreUrl", item.mid( 10 ).split( ';' ) ); + uri.setParam( QStringLiteral( "ignoreUrl" ), item.mid( 10 ).split( ';' ) ); } } } else { - uri.setParam( "url", mDataSource ); + uri.setParam( QStringLiteral( "url" ), mDataSource ); } mDataSource = uri.encodedUri(); // At this point, the URI is obviously incomplete, we add additional params @@ -298,9 +298,9 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) { bool handled = false; - if ( provider == "gdal" ) + if ( provider == QLatin1String( "gdal" ) ) { - if ( mDataSource.startsWith( "NETCDF:" ) ) + if ( mDataSource.startsWith( QLatin1String( "NETCDF:" ) ) ) { // NETCDF:filename:variable // filename can be quoted with " as it can contain colons @@ -314,7 +314,7 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) handled = true; } } - else if ( mDataSource.startsWith( "HDF4_SDS:" ) ) + else if ( mDataSource.startsWith( QLatin1String( "HDF4_SDS:" ) ) ) { // HDF4_SDS:subdataset_type:file_name:subdataset_index // filename can be quoted with " as it can contain colons @@ -328,7 +328,7 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) handled = true; } } - else if ( mDataSource.startsWith( "HDF5:" ) ) + else if ( mDataSource.startsWith( QLatin1String( "HDF5:" ) ) ) { // HDF5:file_name:subdataset // filename can be quoted with " as it can contain colons @@ -363,13 +363,13 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) // Make it the saved CRS to have WMS layer projected correctly. // We will still overwrite whatever GDAL etc picks up anyway // further down this function. - mnl = layerElement.namedItem( "layername" ); + mnl = layerElement.namedItem( QStringLiteral( "layername" ) ); mne = mnl.toElement(); QgsCoordinateReferenceSystem savedCRS; CUSTOM_CRS_VALIDATION savedValidation; - QDomNode srsNode = layerElement.namedItem( "srs" ); + QDomNode srsNode = layerElement.namedItem( QStringLiteral( "srs" ) ); mCRS.readXml( srsNode ); mCRS.setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) ); mCRS.validate(); @@ -400,7 +400,7 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) //internalName = dataSourceFileInfo.baseName(); // set ID - mnl = layerElement.namedItem( "id" ); + mnl = layerElement.namedItem( QStringLiteral( "id" ) ); if ( ! mnl.isNull() ) { mne = mnl.toElement(); @@ -411,44 +411,44 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) } // use scale dependent visibility flag - setScaleBasedVisibility( layerElement.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 ); - setMinimumScale( layerElement.attribute( "minimumScale" ).toDouble() ); - setMaximumScale( layerElement.attribute( "maximumScale" ).toDouble() ); + setScaleBasedVisibility( layerElement.attribute( QStringLiteral( "hasScaleBasedVisibilityFlag" ) ).toInt() == 1 ); + setMinimumScale( layerElement.attribute( QStringLiteral( "minimumScale" ) ).toDouble() ); + setMaximumScale( layerElement.attribute( QStringLiteral( "maximumScale" ) ).toDouble() ); - QDomNode extentNode = layerElement.namedItem( "extent" ); + QDomNode extentNode = layerElement.namedItem( QStringLiteral( "extent" ) ); if ( !extentNode.isNull() ) { setExtent( QgsXmlUtils::readRectangle( extentNode.toElement() ) ); } // set name - mnl = layerElement.namedItem( "layername" ); + mnl = layerElement.namedItem( QStringLiteral( "layername" ) ); mne = mnl.toElement(); setName( mne.text() ); //short name - QDomElement shortNameElem = layerElement.firstChildElement( "shortname" ); + QDomElement shortNameElem = layerElement.firstChildElement( QStringLiteral( "shortname" ) ); if ( !shortNameElem.isNull() ) { mShortName = shortNameElem.text(); } //title - QDomElement titleElem = layerElement.firstChildElement( "title" ); + QDomElement titleElem = layerElement.firstChildElement( QStringLiteral( "title" ) ); if ( !titleElem.isNull() ) { mTitle = titleElem.text(); } //abstract - QDomElement abstractElem = layerElement.firstChildElement( "abstract" ); + QDomElement abstractElem = layerElement.firstChildElement( QStringLiteral( "abstract" ) ); if ( !abstractElem.isNull() ) { mAbstract = abstractElem.text(); } //keywordList - QDomElement keywordListElem = layerElement.firstChildElement( "keywordList" ); + QDomElement keywordListElem = layerElement.firstChildElement( QStringLiteral( "keywordList" ) ); if ( !keywordListElem.isNull() ) { QStringList kwdList; @@ -456,40 +456,40 @@ bool QgsMapLayer::readLayerXml( const QDomElement& layerElement ) { kwdList << n.toElement().text(); } - mKeywordList = kwdList.join( ", " ); + mKeywordList = kwdList.join( QStringLiteral( ", " ) ); } //metadataUrl - QDomElement dataUrlElem = layerElement.firstChildElement( "dataUrl" ); + QDomElement dataUrlElem = layerElement.firstChildElement( QStringLiteral( "dataUrl" ) ); if ( !dataUrlElem.isNull() ) { mDataUrl = dataUrlElem.text(); - mDataUrlFormat = dataUrlElem.attribute( "format", "" ); + mDataUrlFormat = dataUrlElem.attribute( QStringLiteral( "format" ), QLatin1String( "" ) ); } //legendUrl - QDomElement legendUrlElem = layerElement.firstChildElement( "legendUrl" ); + QDomElement legendUrlElem = layerElement.firstChildElement( QStringLiteral( "legendUrl" ) ); if ( !legendUrlElem.isNull() ) { mLegendUrl = legendUrlElem.text(); - mLegendUrlFormat = legendUrlElem.attribute( "format", "" ); + mLegendUrlFormat = legendUrlElem.attribute( QStringLiteral( "format" ), QLatin1String( "" ) ); } //attribution - QDomElement attribElem = layerElement.firstChildElement( "attribution" ); + QDomElement attribElem = layerElement.firstChildElement( QStringLiteral( "attribution" ) ); if ( !attribElem.isNull() ) { mAttribution = attribElem.text(); - mAttributionUrl = attribElem.attribute( "href", "" ); + mAttributionUrl = attribElem.attribute( QStringLiteral( "href" ), QLatin1String( "" ) ); } //metadataUrl - QDomElement metaUrlElem = layerElement.firstChildElement( "metadataUrl" ); + QDomElement metaUrlElem = layerElement.firstChildElement( QStringLiteral( "metadataUrl" ) ); if ( !metaUrlElem.isNull() ) { mMetadataUrl = metaUrlElem.text(); - mMetadataUrlType = metaUrlElem.attribute( "type", "" ); - mMetadataUrlFormat = metaUrlElem.attribute( "format", "" ); + mMetadataUrlType = metaUrlElem.attribute( QStringLiteral( "type" ), QLatin1String( "" ) ); + mMetadataUrlFormat = metaUrlElem.attribute( QStringLiteral( "format" ), QLatin1String( "" ) ); } #if 0 @@ -523,9 +523,9 @@ bool QgsMapLayer::readXml( const QDomNode& layer_node ) bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& document, const QString& relativeBasePath ) const { // use scale dependent visibility flag - layerElement.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 ); - layerElement.setAttribute( "minimumScale", QString::number( minimumScale() ) ); - layerElement.setAttribute( "maximumScale", QString::number( maximumScale() ) ); + layerElement.setAttribute( QStringLiteral( "hasScaleBasedVisibilityFlag" ), hasScaleBasedVisibility() ? 1 : 0 ); + layerElement.setAttribute( QStringLiteral( "minimumScale" ), QString::number( minimumScale() ) ); + layerElement.setAttribute( QStringLiteral( "maximumScale" ), QString::number( maximumScale() ) ); if ( !mExtent.isNull() ) { @@ -533,46 +533,46 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume } // ID - QDomElement layerId = document.createElement( "id" ); + QDomElement layerId = document.createElement( QStringLiteral( "id" ) ); QDomText layerIdText = document.createTextNode( id() ); layerId.appendChild( layerIdText ); layerElement.appendChild( layerId ); // data source - QDomElement dataSource = document.createElement( "datasource" ); + QDomElement dataSource = document.createElement( QStringLiteral( "datasource" ) ); QString src = source(); const QgsVectorLayer *vlayer = qobject_cast( this ); // TODO: what about postgres, mysql and others, they should not go through writePath() - if ( vlayer && vlayer->providerType() == "spatialite" ) + if ( vlayer && vlayer->providerType() == QLatin1String( "spatialite" ) ) { QgsDataSourceUri uri( src ); QString database = QgsProject::instance()->writePath( uri.database(), relativeBasePath ); uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() ); src = uri.uri(); } - else if ( vlayer && vlayer->providerType() == "ogr" ) + else if ( vlayer && vlayer->providerType() == QLatin1String( "ogr" ) ) { QStringList theURIParts = src.split( '|' ); theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0], relativeBasePath ); - src = theURIParts.join( "|" ); + src = theURIParts.join( QStringLiteral( "|" ) ); } - else if ( vlayer && vlayer->providerType() == "gpx" ) + else if ( vlayer && vlayer->providerType() == QLatin1String( "gpx" ) ) { QStringList theURIParts = src.split( '?' ); theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0], relativeBasePath ); - src = theURIParts.join( "?" ); + src = theURIParts.join( QStringLiteral( "?" ) ); } - else if ( vlayer && vlayer->providerType() == "delimitedtext" ) + else if ( vlayer && vlayer->providerType() == QLatin1String( "delimitedtext" ) ) { QUrl urlSource = QUrl::fromEncoded( src.toLatin1() ); QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile(), relativeBasePath ) ); urlDest.setQueryItems( urlSource.queryItems() ); src = QString::fromAscii( urlDest.toEncoded() ); } - else if ( vlayer && vlayer->providerType() == "memory" ) + else if ( vlayer && vlayer->providerType() == QLatin1String( "memory" ) ) { // Refetch the source from the provider, because adding fields actually changes the source for this provider. src = vlayer->dataProvider()->dataSourceUri(); @@ -585,9 +585,9 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume { const QgsRasterLayer *rlayer = qobject_cast( this ); // Update path for subdataset - if ( rlayer && rlayer->providerType() == "gdal" ) + if ( rlayer && rlayer->providerType() == QLatin1String( "gdal" ) ) { - if ( src.startsWith( "NETCDF:" ) ) + if ( src.startsWith( QLatin1String( "NETCDF:" ) ) ) { // NETCDF:filename:variable // filename can be quoted with " as it can contain colons @@ -601,7 +601,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume handled = true; } } - else if ( src.startsWith( "HDF4_SDS:" ) ) + else if ( src.startsWith( QLatin1String( "HDF4_SDS:" ) ) ) { // HDF4_SDS:subdataset_type:file_name:subdataset_index // filename can be quoted with " as it can contain colons @@ -615,7 +615,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume handled = true; } } - else if ( src.startsWith( "HDF5:" ) ) + else if ( src.startsWith( QLatin1String( "HDF5:" ) ) ) { // HDF5:file_name:subdataset // filename can be quoted with " as it can contain colons @@ -654,7 +654,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume // layer name - QDomElement layerName = document.createElement( "layername" ); + QDomElement layerName = document.createElement( QStringLiteral( "layername" ) ); QDomText layerNameText = document.createTextNode( originalName() ); layerName.appendChild( layerNameText ); layerElement.appendChild( layerName ); @@ -662,7 +662,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume // layer short name if ( !mShortName.isEmpty() ) { - QDomElement layerShortName = document.createElement( "shortname" ); + QDomElement layerShortName = document.createElement( QStringLiteral( "shortname" ) ); QDomText layerShortNameText = document.createTextNode( mShortName ); layerShortName.appendChild( layerShortNameText ); layerElement.appendChild( layerShortName ); @@ -671,7 +671,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume // layer title if ( !mTitle.isEmpty() ) { - QDomElement layerTitle = document.createElement( "title" ); + QDomElement layerTitle = document.createElement( QStringLiteral( "title" ) ); QDomText layerTitleText = document.createTextNode( mTitle ); layerTitle.appendChild( layerTitleText ); layerElement.appendChild( layerTitle ); @@ -680,7 +680,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume // layer abstract if ( !mAbstract.isEmpty() ) { - QDomElement layerAbstract = document.createElement( "abstract" ); + QDomElement layerAbstract = document.createElement( QStringLiteral( "abstract" ) ); QDomText layerAbstractText = document.createTextNode( mAbstract ); layerAbstract.appendChild( layerAbstractText ); layerElement.appendChild( layerAbstract ); @@ -690,10 +690,10 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume QStringList keywordStringList = keywordList().split( ',' ); if ( !keywordStringList.isEmpty() ) { - QDomElement layerKeywordList = document.createElement( "keywordList" ); + QDomElement layerKeywordList = document.createElement( QStringLiteral( "keywordList" ) ); for ( int i = 0; i < keywordStringList.size(); ++i ) { - QDomElement layerKeywordValue = document.createElement( "value" ); + QDomElement layerKeywordValue = document.createElement( QStringLiteral( "value" ) ); QDomText layerKeywordText = document.createTextNode( keywordStringList.at( i ).trimmed() ); layerKeywordValue.appendChild( layerKeywordText ); layerKeywordList.appendChild( layerKeywordValue ); @@ -705,10 +705,10 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume QString aDataUrl = dataUrl(); if ( !aDataUrl.isEmpty() ) { - QDomElement layerDataUrl = document.createElement( "dataUrl" ); + QDomElement layerDataUrl = document.createElement( QStringLiteral( "dataUrl" ) ); QDomText layerDataUrlText = document.createTextNode( aDataUrl ); layerDataUrl.appendChild( layerDataUrlText ); - layerDataUrl.setAttribute( "format", dataUrlFormat() ); + layerDataUrl.setAttribute( QStringLiteral( "format" ), dataUrlFormat() ); layerElement.appendChild( layerDataUrl ); } @@ -716,10 +716,10 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume QString aLegendUrl = legendUrl(); if ( !aLegendUrl.isEmpty() ) { - QDomElement layerLegendUrl = document.createElement( "legendUrl" ); + QDomElement layerLegendUrl = document.createElement( QStringLiteral( "legendUrl" ) ); QDomText layerLegendUrlText = document.createTextNode( aLegendUrl ); layerLegendUrl.appendChild( layerLegendUrlText ); - layerLegendUrl.setAttribute( "format", legendUrlFormat() ); + layerLegendUrl.setAttribute( QStringLiteral( "format" ), legendUrlFormat() ); layerElement.appendChild( layerLegendUrl ); } @@ -727,10 +727,10 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume QString aAttribution = attribution(); if ( !aAttribution.isEmpty() ) { - QDomElement layerAttribution = document.createElement( "attribution" ); + QDomElement layerAttribution = document.createElement( QStringLiteral( "attribution" ) ); QDomText layerAttributionText = document.createTextNode( aAttribution ); layerAttribution.appendChild( layerAttributionText ); - layerAttribution.setAttribute( "href", attributionUrl() ); + layerAttribution.setAttribute( QStringLiteral( "href" ), attributionUrl() ); layerElement.appendChild( layerAttribution ); } @@ -738,18 +738,18 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume QString aMetadataUrl = metadataUrl(); if ( !aMetadataUrl.isEmpty() ) { - QDomElement layerMetadataUrl = document.createElement( "metadataUrl" ); + QDomElement layerMetadataUrl = document.createElement( QStringLiteral( "metadataUrl" ) ); QDomText layerMetadataUrlText = document.createTextNode( aMetadataUrl ); layerMetadataUrl.appendChild( layerMetadataUrlText ); - layerMetadataUrl.setAttribute( "type", metadataUrlType() ); - layerMetadataUrl.setAttribute( "format", metadataUrlFormat() ); + layerMetadataUrl.setAttribute( QStringLiteral( "type" ), metadataUrlType() ); + layerMetadataUrl.setAttribute( QStringLiteral( "format" ), metadataUrlFormat() ); layerElement.appendChild( layerMetadataUrl ); } // timestamp if supported if ( timestamp() > QDateTime() ) { - QDomElement stamp = document.createElement( "timestamp" ); + QDomElement stamp = document.createElement( QStringLiteral( "timestamp" ) ); QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) ); stamp.appendChild( stampText ); layerElement.appendChild( stamp ); @@ -762,7 +762,7 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume // are written and read in the proper order. // spatial reference system id - QDomElement mySrsElement = document.createElement( "srs" ); + QDomElement mySrsElement = document.createElement( QStringLiteral( "srs" ) ); mCRS.writeXml( mySrsElement, document ); layerElement.appendChild( mySrsElement ); @@ -784,13 +784,13 @@ bool QgsMapLayer::writeLayerXml( QDomElement& layerElement, QDomDocument& docume QDomDocument QgsMapLayer::asLayerDefinition( const QList& layers, const QString& relativeBasePath ) { - QDomDocument doc( "qgis-layer-definition" ); - QDomElement qgiselm = doc.createElement( "qlr" ); + QDomDocument doc( QStringLiteral( "qgis-layer-definition" ) ); + QDomElement qgiselm = doc.createElement( QStringLiteral( "qlr" ) ); doc.appendChild( qgiselm ); - QDomElement layerselm = doc.createElement( "maplayers" ); + QDomElement layerselm = doc.createElement( QStringLiteral( "maplayers" ) ); Q_FOREACH ( QgsMapLayer* layer, layers ) { - QDomElement layerelm = doc.createElement( "maplayer" ); + QDomElement layerelm = doc.createElement( QStringLiteral( "maplayer" ) ); layer->writeLayerXml( layerelm, doc, relativeBasePath ); layerselm.appendChild( layerelm ); } @@ -801,27 +801,27 @@ QDomDocument QgsMapLayer::asLayerDefinition( const QList& layers, QList QgsMapLayer::fromLayerDefinition( QDomDocument& document, bool addToRegistry, bool addToLegend ) { QList layers; - QDomNodeList layernodes = document.elementsByTagName( "maplayer" ); + QDomNodeList layernodes = document.elementsByTagName( QStringLiteral( "maplayer" ) ); for ( int i = 0; i < layernodes.size(); ++i ) { QDomNode layernode = layernodes.at( i ); QDomElement layerElem = layernode.toElement(); - QString type = layerElem.attribute( "type" ); + QString type = layerElem.attribute( QStringLiteral( "type" ) ); QgsDebugMsg( type ); QgsMapLayer *layer = nullptr; - if ( type == "vector" ) + if ( type == QLatin1String( "vector" ) ) { layer = new QgsVectorLayer; } - else if ( type == "raster" ) + else if ( type == QLatin1String( "raster" ) ) { layer = new QgsRasterLayer; } - else if ( type == "plugin" ) + else if ( type == QLatin1String( "plugin" ) ) { - QString typeName = layerElem.attribute( "name" ); + QString typeName = layerElem.attribute( QStringLiteral( "name" ) ); layer = QgsPluginLayerRegistry::instance()->createLayer( typeName ); } @@ -883,7 +883,7 @@ void QgsMapLayer::writeCustomProperties( QDomNode &layerNode, QDomDocument &doc void QgsMapLayer::readStyleManager( const QDomNode& layerNode ) { - QDomElement styleMgrElem = layerNode.firstChildElement( "map-layer-style-manager" ); + QDomElement styleMgrElem = layerNode.firstChildElement( QStringLiteral( "map-layer-style-manager" ) ); if ( !styleMgrElem.isNull() ) mStyleManager->readXml( styleMgrElem ); else @@ -894,7 +894,7 @@ void QgsMapLayer::writeStyleManager( QDomNode& layerNode, QDomDocument& doc ) co { if ( mStyleManager ) { - QDomElement styleMgrElem = doc.createElement( "map-layer-style-manager" ); + QDomElement styleMgrElem = doc.createElement( QStringLiteral( "map-layer-style-manager" ) ); mStyleManager->writeXml( styleMgrElem ); layerNode.appendChild( styleMgrElem ); } @@ -998,7 +998,7 @@ QString QgsMapLayer::capitaliseLayerName( const QString& name ) // Capitalise the first letter of the layer name if requested QSettings settings; bool capitaliseLayerName = - settings.value( "/qgis/capitaliseLayerName", QVariant( false ) ).toBool(); + settings.value( QStringLiteral( "/qgis/capitaliseLayerName" ), QVariant( false ) ).toBool(); QString layerName( name ); @@ -1013,20 +1013,20 @@ QString QgsMapLayer::styleURI() const QString myURI = publicSource(); // if file is using the VSIFILE mechanism, remove the prefix - if ( myURI.startsWith( "/vsigzip/", Qt::CaseInsensitive ) ) + if ( myURI.startsWith( QLatin1String( "/vsigzip/" ), Qt::CaseInsensitive ) ) { myURI.remove( 0, 9 ); } - else if ( myURI.startsWith( "/vsizip/", Qt::CaseInsensitive ) && - myURI.endsWith( ".zip", Qt::CaseInsensitive ) ) + else if ( myURI.startsWith( QLatin1String( "/vsizip/" ), Qt::CaseInsensitive ) && + myURI.endsWith( QLatin1String( ".zip" ), Qt::CaseInsensitive ) ) { // ideally we should look for .qml file inside zip file myURI.remove( 0, 8 ); } - else if ( myURI.startsWith( "/vsitar/", Qt::CaseInsensitive ) && - ( myURI.endsWith( ".tar", Qt::CaseInsensitive ) || - myURI.endsWith( ".tar.gz", Qt::CaseInsensitive ) || - myURI.endsWith( ".tgz", Qt::CaseInsensitive ) ) ) + else if ( myURI.startsWith( QLatin1String( "/vsitar/" ), Qt::CaseInsensitive ) && + ( myURI.endsWith( QLatin1String( ".tar" ), Qt::CaseInsensitive ) || + myURI.endsWith( QLatin1String( ".tar.gz" ), Qt::CaseInsensitive ) || + myURI.endsWith( QLatin1String( ".tgz" ), Qt::CaseInsensitive ) ) ) { // ideally we should look for .qml file inside tar file myURI.remove( 0, 8 ); @@ -1038,15 +1038,15 @@ QString QgsMapLayer::styleURI() const if ( myFileInfo.exists() ) { // if file is using the /vsizip/ or /vsigzip/ mechanism, cleanup the name - if ( myURI.endsWith( ".gz", Qt::CaseInsensitive ) ) + if ( myURI.endsWith( QLatin1String( ".gz" ), Qt::CaseInsensitive ) ) myURI.chop( 3 ); - else if ( myURI.endsWith( ".zip", Qt::CaseInsensitive ) ) + else if ( myURI.endsWith( QLatin1String( ".zip" ), Qt::CaseInsensitive ) ) myURI.chop( 4 ); - else if ( myURI.endsWith( ".tar", Qt::CaseInsensitive ) ) + else if ( myURI.endsWith( QLatin1String( ".tar" ), Qt::CaseInsensitive ) ) myURI.chop( 4 ); - else if ( myURI.endsWith( ".tar.gz", Qt::CaseInsensitive ) ) + else if ( myURI.endsWith( QLatin1String( ".tar.gz" ), Qt::CaseInsensitive ) ) myURI.chop( 7 ); - else if ( myURI.endsWith( ".tgz", Qt::CaseInsensitive ) ) + else if ( myURI.endsWith( QLatin1String( ".tgz" ), Qt::CaseInsensitive ) ) myURI.chop( 4 ); myFileInfo.setFile( myURI ); // get the file name for our .qml style file @@ -1088,7 +1088,7 @@ bool QgsMapLayer::loadNamedStyleFromDb( const QString &db, const QString &uri, Q return false; } - QString mySql = "select qml from tbl_styles where style=?"; + QString mySql = QStringLiteral( "select qml from tbl_styles where style=?" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); if ( myResult == SQLITE_OK ) { @@ -1116,7 +1116,7 @@ QString QgsMapLayer::loadNamedStyle( const QString &uri, bool &resultFlag ) resultFlag = false; - QDomDocument myDocument( "qgis" ); + QDomDocument myDocument( QStringLiteral( "qgis" ) ); // location of problem associated with errorMsg int line, column; @@ -1137,9 +1137,9 @@ QString QgsMapLayer::loadNamedStyle( const QString &uri, bool &resultFlag ) QgsDebugMsg( QString( "project fileName: %1" ).arg( project.absoluteFilePath() ) ); QString qml; - if ( loadNamedStyleFromDb( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ), uri, qml ) || + if ( loadNamedStyleFromDb( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( QStringLiteral( "qgis.qmldb" ) ), uri, qml ) || ( project.exists() && loadNamedStyleFromDb( project.absoluteDir().absoluteFilePath( project.baseName() + ".qmldb" ), uri, qml ) ) || - loadNamedStyleFromDb( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( "resources/qgis.qmldb" ), uri, qml ) ) + loadNamedStyleFromDb( QDir( QgsApplication::pkgDataPath() ).absoluteFilePath( QStringLiteral( "resources/qgis.qmldb" ) ), uri, qml ) ) { resultFlag = myDocument.setContent( qml, &myErrorMessage, &line, &column ); if ( !resultFlag ) @@ -1168,7 +1168,7 @@ QString QgsMapLayer::loadNamedStyle( const QString &uri, bool &resultFlag ) bool QgsMapLayer::importNamedStyle( QDomDocument& myDocument, QString& myErrorMessage ) { - QDomElement myRoot = myDocument.firstChildElement( "qgis" ); + QDomElement myRoot = myDocument.firstChildElement( QStringLiteral( "qgis" ) ); if ( myRoot.isNull() ) { myErrorMessage = tr( "Root element could not be found" ); @@ -1176,7 +1176,7 @@ bool QgsMapLayer::importNamedStyle( QDomDocument& myDocument, QString& myErrorMe } // get style file version string, if any - QgsProjectVersion fileVersion( myRoot.attribute( "version" ) ); + QgsProjectVersion fileVersion( myRoot.attribute( QStringLiteral( "version" ) ) ); QgsProjectVersion thisVersion( Qgis::QGIS_VERSION ); if ( thisVersion > fileVersion ) @@ -1186,10 +1186,10 @@ bool QgsMapLayer::importNamedStyle( QDomDocument& myDocument, QString& myErrorMe } //Test for matching geometry type on vector layers when applying, if geometry type is given in the style - if ( type() == QgsMapLayer::VectorLayer && !myRoot.firstChildElement( "layerGeometryType" ).isNull() ) + if ( type() == QgsMapLayer::VectorLayer && !myRoot.firstChildElement( QStringLiteral( "layerGeometryType" ) ).isNull() ) { QgsVectorLayer *vl = qobject_cast( this ); - QgsWkbTypes::GeometryType importLayerGeometryType = static_cast( myRoot.firstChildElement( "layerGeometryType" ).text().toInt() ); + QgsWkbTypes::GeometryType importLayerGeometryType = static_cast( myRoot.firstChildElement( QStringLiteral( "layerGeometryType" ) ).text().toInt() ); if ( vl->geometryType() != importLayerGeometryType ) { myErrorMessage = tr( "Cannot apply style to layer with a different geometry type" ); @@ -1198,9 +1198,9 @@ bool QgsMapLayer::importNamedStyle( QDomDocument& myDocument, QString& myErrorMe } // use scale dependent visibility flag - setScaleBasedVisibility( myRoot.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 ); - setMinimumScale( myRoot.attribute( "minimumScale" ).toDouble() ); - setMaximumScale( myRoot.attribute( "maximumScale" ).toDouble() ); + setScaleBasedVisibility( myRoot.attribute( QStringLiteral( "hasScaleBasedVisibilityFlag" ) ).toInt() == 1 ); + setMinimumScale( myRoot.attribute( QStringLiteral( "minimumScale" ) ).toDouble() ); + setMaximumScale( myRoot.attribute( QStringLiteral( "maximumScale" ) ).toDouble() ); #if 0 //read transparency level @@ -1220,16 +1220,16 @@ bool QgsMapLayer::importNamedStyle( QDomDocument& myDocument, QString& myErrorMe void QgsMapLayer::exportNamedStyle( QDomDocument &doc, QString &errorMsg ) const { QDomImplementation DomImplementation; - QDomDocumentType documentType = DomImplementation.createDocumentType( "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QDomDocumentType documentType = DomImplementation.createDocumentType( QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument myDocument( documentType ); - QDomElement myRootNode = myDocument.createElement( "qgis" ); - myRootNode.setAttribute( "version", Qgis::QGIS_VERSION ); + QDomElement myRootNode = myDocument.createElement( QStringLiteral( "qgis" ) ); + myRootNode.setAttribute( QStringLiteral( "version" ), Qgis::QGIS_VERSION ); myDocument.appendChild( myRootNode ); - myRootNode.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 ); - myRootNode.setAttribute( "minimumScale", QString::number( minimumScale() ) ); - myRootNode.setAttribute( "maximumScale", QString::number( maximumScale() ) ); + myRootNode.setAttribute( QStringLiteral( "hasScaleBasedVisibilityFlag" ), hasScaleBasedVisibility() ? 1 : 0 ); + myRootNode.setAttribute( QStringLiteral( "minimumScale" ), QString::number( minimumScale() ) ); + myRootNode.setAttribute( QStringLiteral( "maximumScale" ), QString::number( maximumScale() ) ); #if 0 // @@ -1256,7 +1256,7 @@ void QgsMapLayer::exportNamedStyle( QDomDocument &doc, QString &errorMsg ) const QString geoType = QString::number( vl->geometryType() ); //Adding geometryinformation - QDomElement layerGeometryType = myDocument.createElement( "layerGeometryType" ); + QDomElement layerGeometryType = myDocument.createElement( QStringLiteral( "layerGeometryType" ) ); QDomText type = myDocument.createTextNode( geoType ); layerGeometryType.appendChild( type ); @@ -1283,17 +1283,17 @@ QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag ) QString filename; QgsVectorLayer *vlayer = qobject_cast( this ); - if ( vlayer && vlayer->providerType() == "ogr" ) + if ( vlayer && vlayer->providerType() == QLatin1String( "ogr" ) ) { QStringList theURIParts = uri.split( '|' ); filename = theURIParts[0]; } - else if ( vlayer && vlayer->providerType() == "gpx" ) + else if ( vlayer && vlayer->providerType() == QLatin1String( "gpx" ) ) { QStringList theURIParts = uri.split( '?' ); filename = theURIParts[0]; } - else if ( vlayer && vlayer->providerType() == "delimitedtext" ) + else if ( vlayer && vlayer->providerType() == QLatin1String( "delimitedtext" ) ) { filename = QUrl::fromEncoded( uri.toLatin1() ).toLocalFile(); // toLocalFile() returns an empty string if theURI is a plain Windows-path, e.g. "C:/style.qml" @@ -1306,7 +1306,7 @@ QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag ) } QFileInfo myFileInfo( filename ); - if ( myFileInfo.exists() || filename.endsWith( ".qml", Qt::CaseInsensitive ) ) + if ( myFileInfo.exists() || filename.endsWith( QLatin1String( ".qml" ), Qt::CaseInsensitive ) ) { QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name if ( !myDirInfo.isWritable() ) @@ -1343,7 +1343,7 @@ QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag ) const char *myTail; int myResult; - myResult = sqlite3_open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( "qgis.qmldb" ).toUtf8().data(), &myDatabase ); + myResult = sqlite3_open( QDir( QgsApplication::qgisSettingsDirPath() ).absoluteFilePath( QStringLiteral( "qgis.qmldb" ) ).toUtf8().data(), &myDatabase ); if ( myResult != SQLITE_OK ) { return tr( "User database could not be opened." ); @@ -1352,7 +1352,7 @@ QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag ) QByteArray param0 = uri.toUtf8(); QByteArray param1 = qml.toUtf8(); - QString mySql = "create table if not exists tbl_styles(style varchar primary key,qml varchar)"; + QString mySql = QStringLiteral( "create table if not exists tbl_styles(style varchar primary key,qml varchar)" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); if ( myResult == SQLITE_OK ) { @@ -1367,7 +1367,7 @@ QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag ) sqlite3_finalize( myPreparedStatement ); - mySql = "insert into tbl_styles(style,qml) values (?,?)"; + mySql = QStringLiteral( "insert into tbl_styles(style,qml) values (?,?)" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); if ( myResult == SQLITE_OK ) { @@ -1384,7 +1384,7 @@ QString QgsMapLayer::saveNamedStyle( const QString &uri, bool &resultFlag ) if ( !resultFlag ) { - QString mySql = "update tbl_styles set qml=? where style=?"; + QString mySql = QStringLiteral( "update tbl_styles set qml=? where style=?" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8().data(), mySql.toUtf8().length(), &myPreparedStatement, &myTail ); if ( myResult == SQLITE_OK ) { @@ -1420,36 +1420,36 @@ void QgsMapLayer::exportSldStyle( QDomDocument &doc, QString &errorMsg ) const { QDomDocument myDocument = QDomDocument(); - QDomNode header = myDocument.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" ); + QDomNode header = myDocument.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"UTF-8\"" ) ); myDocument.appendChild( header ); // Create the root element - QDomElement root = myDocument.createElementNS( "http://www.opengis.net/sld", "StyledLayerDescriptor" ); - root.setAttribute( "version", "1.1.0" ); - root.setAttribute( "xsi:schemaLocation", "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" ); - root.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" ); - root.setAttribute( "xmlns:se", "http://www.opengis.net/se" ); - root.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + QDomElement root = myDocument.createElementNS( QStringLiteral( "http://www.opengis.net/sld" ), QStringLiteral( "StyledLayerDescriptor" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.1.0" ) ); + root.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" ) ); + root.setAttribute( QStringLiteral( "xmlns:ogc" ), QStringLiteral( "http://www.opengis.net/ogc" ) ); + root.setAttribute( QStringLiteral( "xmlns:se" ), QStringLiteral( "http://www.opengis.net/se" ) ); + root.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + root.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); myDocument.appendChild( root ); // Create the NamedLayer element - QDomElement namedLayerNode = myDocument.createElement( "NamedLayer" ); + QDomElement namedLayerNode = myDocument.createElement( QStringLiteral( "NamedLayer" ) ); root.appendChild( namedLayerNode ); const QgsVectorLayer *vlayer = qobject_cast( this ); if ( !vlayer ) { errorMsg = tr( "Could not save symbology because:\n%1" ) - .arg( "Non-vector layers not supported yet" ); + .arg( QStringLiteral( "Non-vector layers not supported yet" ) ); return; } QgsStringMap props; if ( hasScaleBasedVisibility() ) { - props[ "scaleMinDenom" ] = QString::number( mMinScale ); - props[ "scaleMaxDenom" ] = QString::number( mMaxScale ); + props[ QStringLiteral( "scaleMinDenom" )] = QString::number( mMinScale ); + props[ QStringLiteral( "scaleMaxDenom" )] = QString::number( mMaxScale ); } if ( !vlayer->writeSld( namedLayerNode, myDocument, errorMsg, props ) ) { @@ -1475,17 +1475,17 @@ QString QgsMapLayer::saveSldStyle( const QString &uri, bool &resultFlag ) const // check if the uri is a file or ends with .sld, // which indicates that it should become one QString filename; - if ( vlayer->providerType() == "ogr" ) + if ( vlayer->providerType() == QLatin1String( "ogr" ) ) { QStringList theURIParts = uri.split( '|' ); filename = theURIParts[0]; } - else if ( vlayer->providerType() == "gpx" ) + else if ( vlayer->providerType() == QLatin1String( "gpx" ) ) { QStringList theURIParts = uri.split( '?' ); filename = theURIParts[0]; } - else if ( vlayer->providerType() == "delimitedtext" ) + else if ( vlayer->providerType() == QLatin1String( "delimitedtext" ) ) { filename = QUrl::fromEncoded( uri.toLatin1() ).toLocalFile(); // toLocalFile() returns an empty string if theURI is a plain Windows-path, e.g. "C:/style.qml" @@ -1498,7 +1498,7 @@ QString QgsMapLayer::saveSldStyle( const QString &uri, bool &resultFlag ) const } QFileInfo myFileInfo( filename ); - if ( myFileInfo.exists() || filename.endsWith( ".sld", Qt::CaseInsensitive ) ) + if ( myFileInfo.exists() || filename.endsWith( QLatin1String( ".sld" ), Qt::CaseInsensitive ) ) { QFileInfo myDirInfo( myFileInfo.path() ); //excludes file name if ( !myDirInfo.isWritable() ) @@ -1557,20 +1557,20 @@ QString QgsMapLayer::loadSldStyle( const QString &uri, bool &resultFlag ) } // check for root SLD element - QDomElement myRoot = myDocument.firstChildElement( "StyledLayerDescriptor" ); + QDomElement myRoot = myDocument.firstChildElement( QStringLiteral( "StyledLayerDescriptor" ) ); if ( myRoot.isNull() ) { - myErrorMessage = QString( "Error: StyledLayerDescriptor element not found in %1" ).arg( uri ); + myErrorMessage = QStringLiteral( "Error: StyledLayerDescriptor element not found in %1" ).arg( uri ); resultFlag = false; return myErrorMessage; } // now get the style node out and pass it over to the layer // to deserialise... - QDomElement namedLayerElem = myRoot.firstChildElement( "NamedLayer" ); + QDomElement namedLayerElem = myRoot.firstChildElement( QStringLiteral( "NamedLayer" ) ); if ( namedLayerElem.isNull() ) { - myErrorMessage = QLatin1String( "Info: NamedLayer element not found." ); + myErrorMessage = QStringLiteral( "Info: NamedLayer element not found." ); resultFlag = false; return myErrorMessage; } @@ -1583,7 +1583,7 @@ QString QgsMapLayer::loadSldStyle( const QString &uri, bool &resultFlag ) return myErrorMessage; } - return ""; + return QLatin1String( "" ); } bool QgsMapLayer::readStyle( const QDomNode& node, QString& errorMessage ) diff --git a/src/core/qgsmaplayer.h b/src/core/qgsmaplayer.h index 30b5c2238737..848572cbd24e 100644 --- a/src/core/qgsmaplayer.h +++ b/src/core/qgsmaplayer.h @@ -532,7 +532,7 @@ class CORE_EXPORT QgsMapLayer : public QObject virtual QString loadSldStyle( const QString &uri, bool &resultFlag ); virtual bool readSld( const QDomNode &node, QString &errorMessage ) - { Q_UNUSED( node ); errorMessage = QString( "Layer type %1 not supported" ).arg( type() ); return false; } + { Q_UNUSED( node ); errorMessage = QStringLiteral( "Layer type %1 not supported" ).arg( type() ); return false; } @@ -790,7 +790,7 @@ class CORE_EXPORT QgsMapLayer : public QObject /** Read custom properties from project file. @param layerNode note to read from @param keyStartsWith reads only properties starting with the specified string (or all if the string is empty)*/ - void readCustomProperties( const QDomNode& layerNode, const QString& keyStartsWith = "" ); + void readCustomProperties( const QDomNode& layerNode, const QString& keyStartsWith = QLatin1String( "" ) ); /** Write custom properties to project file. */ void writeCustomProperties( QDomNode & layerNode, QDomDocument & doc ) const; diff --git a/src/core/qgsmaplayerlegend.cpp b/src/core/qgsmaplayerlegend.cpp index 1cbfa82d5893..a1041b7179e1 100644 --- a/src/core/qgsmaplayerlegend.cpp +++ b/src/core/qgsmaplayerlegend.cpp @@ -54,9 +54,9 @@ void QgsMapLayerLegendUtils::setLegendNodeOrder( QgsLayerTreeLayer* nodeLayer, c QStringList orderStr; Q_FOREACH ( int id, order ) orderStr << QString::number( id ); - QString str = orderStr.isEmpty() ? "empty" : orderStr.join( "," ); + QString str = orderStr.isEmpty() ? QStringLiteral( "empty" ) : orderStr.join( QStringLiteral( "," ) ); - nodeLayer->setCustomProperty( "legend/node-order", str ); + nodeLayer->setCustomProperty( QStringLiteral( "legend/node-order" ), str ); } static int _originalLegendNodeCount( QgsLayerTreeLayer* nodeLayer ) @@ -87,12 +87,12 @@ static QList _makeNodeOrder( QgsLayerTreeLayer* nodeLayer ) QList QgsMapLayerLegendUtils::legendNodeOrder( QgsLayerTreeLayer* nodeLayer ) { - QString orderStr = nodeLayer->customProperty( "legend/node-order" ).toString(); + QString orderStr = nodeLayer->customProperty( QStringLiteral( "legend/node-order" ) ).toString(); if ( orderStr.isEmpty() ) return _makeNodeOrder( nodeLayer ); - if ( orderStr == "empty" ) + if ( orderStr == QLatin1String( "empty" ) ) return QList(); int numNodes = _originalLegendNodeCount( nodeLayer ); @@ -113,7 +113,7 @@ QList QgsMapLayerLegendUtils::legendNodeOrder( QgsLayerTreeLayer* nodeLayer bool QgsMapLayerLegendUtils::hasLegendNodeOrder( QgsLayerTreeLayer* nodeLayer ) { - return nodeLayer->customProperties().contains( "legend/node-order" ); + return nodeLayer->customProperties().contains( QStringLiteral( "legend/node-order" ) ); } void QgsMapLayerLegendUtils::setLegendNodeUserLabel( QgsLayerTreeLayer* nodeLayer, int originalIndex, const QString& newLabel ) @@ -191,11 +191,11 @@ QList QgsDefaultVectorLayerLegend::createLayerTree if ( !r ) return nodes; - if ( nodeLayer->customProperty( "showFeatureCount", 0 ).toBool() ) + if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toBool() ) mLayer->countSymbolFeatures(); QSettings settings; - if ( settings.value( "/qgis/showLegendClassifiers", false ).toBool() && !r->legendClassificationAttribute().isEmpty() ) + if ( settings.value( QStringLiteral( "/qgis/showLegendClassifiers" ), false ).toBool() && !r->legendClassificationAttribute().isEmpty() ) { nodes.append( new QgsSimpleLegendNode( nodeLayer, r->legendClassificationAttribute() ) ); } diff --git a/src/core/qgsmaplayerstylemanager.cpp b/src/core/qgsmaplayerstylemanager.cpp index 715de4ccd893..0242862bf4a4 100644 --- a/src/core/qgsmaplayerstylemanager.cpp +++ b/src/core/qgsmaplayerstylemanager.cpp @@ -36,30 +36,30 @@ void QgsMapLayerStyleManager::reset() void QgsMapLayerStyleManager::readXml( const QDomElement& mgrElement ) { - mCurrentStyle = mgrElement.attribute( "current" ); + mCurrentStyle = mgrElement.attribute( QStringLiteral( "current" ) ); mStyles.clear(); - QDomElement ch = mgrElement.firstChildElement( "map-layer-style" ); + QDomElement ch = mgrElement.firstChildElement( QStringLiteral( "map-layer-style" ) ); while ( !ch.isNull() ) { - QString name = ch.attribute( "name" ); + QString name = ch.attribute( QStringLiteral( "name" ) ); QgsMapLayerStyle style; style.readXml( ch ); mStyles.insert( name, style ); - ch = ch.nextSiblingElement( "map-layer-style" ); + ch = ch.nextSiblingElement( QStringLiteral( "map-layer-style" ) ); } } void QgsMapLayerStyleManager::writeXml( QDomElement& mgrElement ) const { QDomDocument doc = mgrElement.ownerDocument(); - mgrElement.setAttribute( "current", mCurrentStyle ); + mgrElement.setAttribute( QStringLiteral( "current" ), mCurrentStyle ); Q_FOREACH ( const QString& name, styles() ) { - QDomElement ch = doc.createElement( "map-layer-style" ); - ch.setAttribute( "name", name ); + QDomElement ch = doc.createElement( QStringLiteral( "map-layer-style" ) ); + ch.setAttribute( QStringLiteral( "name" ), name ); mStyles[name].writeXml( ch ); mgrElement.appendChild( ch ); } @@ -248,7 +248,7 @@ void QgsMapLayerStyle::readFromLayer( QgsMapLayer* layer ) void QgsMapLayerStyle::writeToLayer( QgsMapLayer* layer ) const { - QDomDocument doc( "qgis" ); + QDomDocument doc( QStringLiteral( "qgis" ) ); if ( !doc.setContent( mXmlData ) ) { QgsDebugMsg( "Failed to parse XML of previously stored XML data - this should not happen!" ); diff --git a/src/core/qgsmaprenderercustompainterjob.cpp b/src/core/qgsmaprenderercustompainterjob.cpp index 8222ce4ef907..3bde891c87ef 100644 --- a/src/core/qgsmaprenderercustompainterjob.cpp +++ b/src/core/qgsmaprenderercustompainterjob.cpp @@ -69,7 +69,7 @@ void QgsMapRendererCustomPainterJob::start() #ifndef QT_NO_DEBUG QPaintDevice* thePaintDevice = mPainter->device(); - QString errMsg = QString( "pre-set DPI not equal to painter's DPI (%1 vs %2)" ).arg( thePaintDevice->logicalDpiX() ).arg( mSettings.outputDpi() ); + QString errMsg = QStringLiteral( "pre-set DPI not equal to painter's DPI (%1 vs %2)" ).arg( thePaintDevice->logicalDpiX() ).arg( mSettings.outputDpi() ); Q_ASSERT_X( qgsDoubleNear( thePaintDevice->logicalDpiX(), mSettings.outputDpi() ), "Job::startRender()", errMsg.toLatin1().data() ); #endif diff --git a/src/core/qgsmaprendererjob.cpp b/src/core/qgsmaprendererjob.cpp index 5ea92d336fab..5654a10f78ee 100644 --- a/src/core/qgsmaprendererjob.cpp +++ b/src/core/qgsmaprendererjob.cpp @@ -379,7 +379,7 @@ QImage QgsMapRendererJob::composeImage( const QgsMapSettings& settings, const La void QgsMapRendererJob::logRenderingTime( const LayerRenderJobs& jobs ) { QSettings settings; - if ( !settings.value( "/Map/logCanvasRefreshEvent", false ).toBool() ) + if ( !settings.value( QStringLiteral( "/Map/logCanvasRefreshEvent" ), false ).toBool() ) return; QMultiMap elapsed; @@ -390,7 +390,7 @@ void QgsMapRendererJob::logRenderingTime( const LayerRenderJobs& jobs ) qSort( tt.begin(), tt.end(), qGreater() ); Q_FOREACH ( int t, tt ) { - QgsMessageLog::logMessage( tr( "%1 ms: %2" ).arg( t ).arg( QStringList( elapsed.values( t ) ).join( ", " ) ), tr( "Rendering" ) ); + QgsMessageLog::logMessage( tr( "%1 ms: %2" ).arg( t ).arg( QStringList( elapsed.values( t ) ).join( QStringLiteral( ", " ) ) ), tr( "Rendering" ) ); } - QgsMessageLog::logMessage( "---", tr( "Rendering" ) ); + QgsMessageLog::logMessage( QStringLiteral( "---" ), tr( "Rendering" ) ); } diff --git a/src/core/qgsmapsettings.cpp b/src/core/qgsmapsettings.cpp index ad521dcbcaa0..f44c9447a8dc 100644 --- a/src/core/qgsmapsettings.cpp +++ b/src/core/qgsmapsettings.cpp @@ -406,7 +406,7 @@ QgsRectangle QgsMapSettings::layerExtentToOutputExtent( QgsMapLayer* theLayer, Q } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ), "CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ), QStringLiteral( "CRS" ) ); } } @@ -433,7 +433,7 @@ QgsRectangle QgsMapSettings::outputExtentToLayerExtent( QgsMapLayer* theLayer, Q } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ), "CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ), QStringLiteral( "CRS" ) ); } } @@ -455,7 +455,7 @@ QgsPoint QgsMapSettings::layerToMapCoordinates( QgsMapLayer* theLayer, QgsPoint } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ), "CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ), QStringLiteral( "CRS" ) ); } } else @@ -478,7 +478,7 @@ QgsRectangle QgsMapSettings::layerToMapCoordinates( QgsMapLayer* theLayer, QgsRe } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ), "CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ), QStringLiteral( "CRS" ) ); } } else @@ -501,7 +501,7 @@ QgsPoint QgsMapSettings::mapToLayerCoordinates( QgsMapLayer* theLayer, QgsPoint } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ), "CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ), QStringLiteral( "CRS" ) ); } } else @@ -524,7 +524,7 @@ QgsRectangle QgsMapSettings::mapToLayerCoordinates( QgsMapLayer* theLayer, QgsRe } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ), "CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ), QStringLiteral( "CRS" ) ); } } return rect; @@ -607,27 +607,27 @@ QgsRectangle QgsMapSettings::fullExtent() const void QgsMapSettings::readXml( QDomNode& theNode ) { // set units - QDomNode mapUnitsNode = theNode.namedItem( "units" ); + QDomNode mapUnitsNode = theNode.namedItem( QStringLiteral( "units" ) ); QgsUnitTypes::DistanceUnit units = QgsXmlUtils::readMapUnits( mapUnitsNode.toElement() ); setMapUnits( units ); // set projections flag - QDomNode projNode = theNode.namedItem( "projections" ); + QDomNode projNode = theNode.namedItem( QStringLiteral( "projections" ) ); setCrsTransformEnabled( projNode.toElement().text().toInt() ); // set destination CRS QgsCoordinateReferenceSystem srs; - QDomNode srsNode = theNode.namedItem( "destinationsrs" ); + QDomNode srsNode = theNode.namedItem( QStringLiteral( "destinationsrs" ) ); srs.readXml( srsNode ); setDestinationCrs( srs ); // set extent - QDomNode extentNode = theNode.namedItem( "extent" ); + QDomNode extentNode = theNode.namedItem( QStringLiteral( "extent" ) ); QgsRectangle aoi = QgsXmlUtils::readRectangle( extentNode.toElement() ); setExtent( aoi ); // set rotation - QDomNode rotationNode = theNode.namedItem( "rotation" ); + QDomNode rotationNode = theNode.namedItem( QStringLiteral( "rotation" ) ); QString rotationVal = rotationNode.toElement().text(); if ( ! rotationVal.isEmpty() ) { @@ -636,10 +636,10 @@ void QgsMapSettings::readXml( QDomNode& theNode ) } //render map tile - QDomElement renderMapTileElem = theNode.firstChildElement( "rendermaptile" ); + QDomElement renderMapTileElem = theNode.firstChildElement( QStringLiteral( "rendermaptile" ) ); if ( !renderMapTileElem.isNull() ) { - setFlag( QgsMapSettings::RenderMapTile, renderMapTileElem.text() == "1" ? true : false ); + setFlag( QgsMapSettings::RenderMapTile, renderMapTileElem.text() == QLatin1String( "1" ) ? true : false ); } mDatumTransformStore.readXml( theNode ); @@ -656,24 +656,24 @@ void QgsMapSettings::writeXml( QDomNode& theNode, QDomDocument& theDoc ) theNode.appendChild( QgsXmlUtils::writeRectangle( extent(), theDoc ) ); // Write current view rotation - QDomElement rotNode = theDoc.createElement( "rotation" ); + QDomElement rotNode = theDoc.createElement( QStringLiteral( "rotation" ) ); rotNode.appendChild( theDoc.createTextNode( qgsDoubleToString( rotation() ) ) ); theNode.appendChild( rotNode ); // projections enabled - QDomElement projNode = theDoc.createElement( "projections" ); + QDomElement projNode = theDoc.createElement( QStringLiteral( "projections" ) ); projNode.appendChild( theDoc.createTextNode( QString::number( hasCrsTransformEnabled() ) ) ); theNode.appendChild( projNode ); // destination CRS - QDomElement srsNode = theDoc.createElement( "destinationsrs" ); + QDomElement srsNode = theDoc.createElement( QStringLiteral( "destinationsrs" ) ); theNode.appendChild( srsNode ); destinationCrs().writeXml( srsNode, theDoc ); //render map tile - QDomElement renderMapTileElem = theDoc.createElement( "rendermaptile" ); + QDomElement renderMapTileElem = theDoc.createElement( QStringLiteral( "rendermaptile" ) ); QDomText renderMapTileText = theDoc.createTextNode( testFlag( QgsMapSettings::RenderMapTile ) ? "1" : "0" ); renderMapTileElem.appendChild( renderMapTileText ); theNode.appendChild( renderMapTileElem ); diff --git a/src/core/qgsmapthemecollection.cpp b/src/core/qgsmapthemecollection.cpp index 41e742ef2e55..5872701c48f8 100644 --- a/src/core/qgsmapthemecollection.cpp +++ b/src/core/qgsmapthemecollection.cpp @@ -189,49 +189,49 @@ void QgsMapThemeCollection::readXml( const QDomDocument& doc ) { clear(); - QDomElement visPresetsElem = doc.firstChildElement( "qgis" ).firstChildElement( "visibility-presets" ); + QDomElement visPresetsElem = doc.firstChildElement( QStringLiteral( "qgis" ) ).firstChildElement( QStringLiteral( "visibility-presets" ) ); if ( visPresetsElem.isNull() ) return; - QDomElement visPresetElem = visPresetsElem.firstChildElement( "visibility-preset" ); + QDomElement visPresetElem = visPresetsElem.firstChildElement( QStringLiteral( "visibility-preset" ) ); while ( !visPresetElem.isNull() ) { - QString presetName = visPresetElem.attribute( "name" ); + QString presetName = visPresetElem.attribute( QStringLiteral( "name" ) ); MapThemeRecord rec; - QDomElement visPresetLayerElem = visPresetElem.firstChildElement( "layer" ); + QDomElement visPresetLayerElem = visPresetElem.firstChildElement( QStringLiteral( "layer" ) ); while ( !visPresetLayerElem.isNull() ) { - QString layerID = visPresetLayerElem.attribute( "id" ); + QString layerID = visPresetLayerElem.attribute( QStringLiteral( "id" ) ); if ( QgsMapLayerRegistry::instance()->mapLayer( layerID ) ) { rec.mVisibleLayerIds << layerID; // only use valid layer IDs - if ( visPresetLayerElem.hasAttribute( "style" ) ) - rec.mPerLayerCurrentStyle[layerID] = visPresetLayerElem.attribute( "style" ); + if ( visPresetLayerElem.hasAttribute( QStringLiteral( "style" ) ) ) + rec.mPerLayerCurrentStyle[layerID] = visPresetLayerElem.attribute( QStringLiteral( "style" ) ); } - visPresetLayerElem = visPresetLayerElem.nextSiblingElement( "layer" ); + visPresetLayerElem = visPresetLayerElem.nextSiblingElement( QStringLiteral( "layer" ) ); } - QDomElement checkedLegendNodesElem = visPresetElem.firstChildElement( "checked-legend-nodes" ); + QDomElement checkedLegendNodesElem = visPresetElem.firstChildElement( QStringLiteral( "checked-legend-nodes" ) ); while ( !checkedLegendNodesElem.isNull() ) { QSet checkedLegendNodes; - QDomElement checkedLegendNodeElem = checkedLegendNodesElem.firstChildElement( "checked-legend-node" ); + QDomElement checkedLegendNodeElem = checkedLegendNodesElem.firstChildElement( QStringLiteral( "checked-legend-node" ) ); while ( !checkedLegendNodeElem.isNull() ) { - checkedLegendNodes << checkedLegendNodeElem.attribute( "id" ); - checkedLegendNodeElem = checkedLegendNodeElem.nextSiblingElement( "checked-legend-node" ); + checkedLegendNodes << checkedLegendNodeElem.attribute( QStringLiteral( "id" ) ); + checkedLegendNodeElem = checkedLegendNodeElem.nextSiblingElement( QStringLiteral( "checked-legend-node" ) ); } - QString layerID = checkedLegendNodesElem.attribute( "id" ); + QString layerID = checkedLegendNodesElem.attribute( QStringLiteral( "id" ) ); if ( QgsMapLayerRegistry::instance()->mapLayer( layerID ) ) // only use valid IDs rec.mPerLayerCheckedLegendSymbols.insert( layerID, checkedLegendNodes ); - checkedLegendNodesElem = checkedLegendNodesElem.nextSiblingElement( "checked-legend-nodes" ); + checkedLegendNodesElem = checkedLegendNodesElem.nextSiblingElement( QStringLiteral( "checked-legend-nodes" ) ); } mMapThemes.insert( presetName, rec ); - visPresetElem = visPresetElem.nextSiblingElement( "visibility-preset" ); + visPresetElem = visPresetElem.nextSiblingElement( QStringLiteral( "visibility-preset" ) ); } reconnectToLayersStyleManager(); @@ -240,20 +240,20 @@ void QgsMapThemeCollection::readXml( const QDomDocument& doc ) void QgsMapThemeCollection::writeXml( QDomDocument& doc ) { - QDomElement visPresetsElem = doc.createElement( "visibility-presets" ); + QDomElement visPresetsElem = doc.createElement( QStringLiteral( "visibility-presets" ) ); MapThemeRecordMap::const_iterator it = mMapThemes.constBegin(); for ( ; it != mMapThemes.constEnd(); ++ it ) { QString grpName = it.key(); const MapThemeRecord& rec = it.value(); - QDomElement visPresetElem = doc.createElement( "visibility-preset" ); - visPresetElem.setAttribute( "name", grpName ); + QDomElement visPresetElem = doc.createElement( QStringLiteral( "visibility-preset" ) ); + visPresetElem.setAttribute( QStringLiteral( "name" ), grpName ); Q_FOREACH ( const QString& layerID, rec.mVisibleLayerIds ) { - QDomElement layerElem = doc.createElement( "layer" ); - layerElem.setAttribute( "id", layerID ); + QDomElement layerElem = doc.createElement( QStringLiteral( "layer" ) ); + layerElem.setAttribute( QStringLiteral( "id" ), layerID ); if ( rec.mPerLayerCurrentStyle.contains( layerID ) ) - layerElem.setAttribute( "style", rec.mPerLayerCurrentStyle[layerID] ); + layerElem.setAttribute( QStringLiteral( "style" ), rec.mPerLayerCurrentStyle[layerID] ); visPresetElem.appendChild( layerElem ); } @@ -261,12 +261,12 @@ void QgsMapThemeCollection::writeXml( QDomDocument& doc ) for ( ; layerIt != rec.mPerLayerCheckedLegendSymbols.constEnd(); ++layerIt ) { QString layerID = layerIt.key(); - QDomElement checkedLegendNodesElem = doc.createElement( "checked-legend-nodes" ); - checkedLegendNodesElem.setAttribute( "id", layerID ); + QDomElement checkedLegendNodesElem = doc.createElement( QStringLiteral( "checked-legend-nodes" ) ); + checkedLegendNodesElem.setAttribute( QStringLiteral( "id" ), layerID ); Q_FOREACH ( const QString& checkedLegendNode, layerIt.value() ) { - QDomElement checkedLegendNodeElem = doc.createElement( "checked-legend-node" ); - checkedLegendNodeElem.setAttribute( "id", checkedLegendNode ); + QDomElement checkedLegendNodeElem = doc.createElement( QStringLiteral( "checked-legend-node" ) ); + checkedLegendNodeElem.setAttribute( QStringLiteral( "id" ), checkedLegendNode ); checkedLegendNodesElem.appendChild( checkedLegendNodeElem ); } visPresetElem.appendChild( checkedLegendNodesElem ); @@ -275,7 +275,7 @@ void QgsMapThemeCollection::writeXml( QDomDocument& doc ) visPresetsElem.appendChild( visPresetElem ); } - doc.firstChildElement( "qgis" ).appendChild( visPresetsElem ); + doc.firstChildElement( QStringLiteral( "qgis" ) ).appendChild( visPresetsElem ); } void QgsMapThemeCollection::registryLayersRemoved( const QStringList& layerIDs ) diff --git a/src/core/qgsmessageoutput.cpp b/src/core/qgsmessageoutput.cpp index 9f69b85c6ef0..e8aafac982ac 100644 --- a/src/core/qgsmessageoutput.cpp +++ b/src/core/qgsmessageoutput.cpp @@ -55,7 +55,7 @@ void QgsMessageOutput::showMessage( const QString& title, const QString& message // QgsMessageOutputConsole QgsMessageOutputConsole::QgsMessageOutputConsole() - : mMessage( "" ) + : mMessage( QLatin1String( "" ) ) , mMsgType( MessageText ) { } @@ -75,9 +75,9 @@ void QgsMessageOutputConsole::showMessage( bool ) { if ( mMsgType == MessageHtml ) { - mMessage.replace( "
                                                                                                                                                                                    ", "\n" ); - mMessage.replace( " ", " " ); - mMessage.replace( QRegExp( "]+>" ), "" ); + mMessage.replace( QLatin1String( "
                                                                                                                                                                                    " ), QLatin1String( "\n" ) ); + mMessage.replace( QLatin1String( " " ), QLatin1String( " " ) ); + mMessage.replace( QRegExp( "]+>" ), QLatin1String( "" ) ); } QgsMessageLog::logMessage( mMessage, mTitle.isNull() ? QObject::tr( "Console" ) : mTitle ); emit destroyed(); diff --git a/src/core/qgsmimedatautils.cpp b/src/core/qgsmimedatautils.cpp index 4bd4ec9611e0..777d2e19eb36 100644 --- a/src/core/qgsmimedatautils.cpp +++ b/src/core/qgsmimedatautils.cpp @@ -44,7 +44,7 @@ QgsMimeDataUtils::Uri::Uri( QString& encData ) name = decoded[2]; uri = decoded[3]; - if ( layerType == "raster" && decoded.size() == 6 ) + if ( layerType == QLatin1String( "raster" ) && decoded.size() == 6 ) { supportedCrs = decode( decoded[4] ); supportedFormats = decode( decoded[5] ); @@ -114,14 +114,14 @@ static void _addLayerTreeNodeToUriList( QgsLayerTreeNode* node, QgsMimeDataUtils QgsMimeDataUtils::Uri uri; if ( QgsVectorLayer* vlayer = qobject_cast( nodeLayer->layer() ) ) { - uri.layerType = "vector"; + uri.layerType = QStringLiteral( "vector" ); uri.name = vlayer->name(); uri.providerKey = vlayer->dataProvider()->name(); uri.uri = vlayer->dataProvider()->dataSourceUri(); } else if ( QgsRasterLayer* rlayer = qobject_cast( nodeLayer->layer() ) ) { - uri.layerType = "raster"; + uri.layerType = QStringLiteral( "raster" ); uri.name = rlayer->name(); uri.providerKey = rlayer->dataProvider()->name(); uri.uri = rlayer->dataProvider()->dataSourceUri(); @@ -149,8 +149,8 @@ QString QgsMimeDataUtils::encode( const QStringList& items ) Q_FOREACH ( const QString& item, items ) { QString str = item; - str.replace( '\\', "\\\\" ); - str.replace( ':', "\\:" ); + str.replace( '\\', QLatin1String( "\\\\" ) ); + str.replace( ':', QLatin1String( "\\:" ) ); encoded += str + ':'; } return encoded.left( encoded.length() - 1 ); @@ -174,7 +174,7 @@ QStringList QgsMimeDataUtils::decode( const QString& encoded ) else if ( c == ':' && !inEscape ) { items.append( item ); - item = ""; + item = QLatin1String( "" ); } else { diff --git a/src/core/qgsmultirenderchecker.cpp b/src/core/qgsmultirenderchecker.cpp index d293f4908a2f..840f701c24ba 100644 --- a/src/core/qgsmultirenderchecker.cpp +++ b/src/core/qgsmultirenderchecker.cpp @@ -47,7 +47,7 @@ bool QgsMultiRenderChecker::runTest( const QString& theTestName, unsigned int th if ( subDirs.isEmpty() ) { - subDirs << ""; + subDirs << QLatin1String( "" ); } QVector dartMeasurements; @@ -87,7 +87,7 @@ bool QgsMultiRenderChecker::runTest( const QString& theTestName, unsigned int th Q_FOREACH ( const QgsDartMeasurement& measurement, dartMeasurements ) measurement.send(); - QgsDartMeasurement msg( "Image not accepted by test", QgsDartMeasurement::Text, "This may be caused because the test is supposed to fail or rendering inconsistencies." + QgsDartMeasurement msg( QStringLiteral( "Image not accepted by test" ), QgsDartMeasurement::Text, "This may be caused because the test is supposed to fail or rendering inconsistencies." "If this is a rendering inconsistency, please add another control image folder, add an anomaly image or increase the color tolerance." ); msg.send(); } diff --git a/src/core/qgsnetworkaccessmanager.cpp b/src/core/qgsnetworkaccessmanager.cpp index 1c992c82b9f6..f5faafe33056 100644 --- a/src/core/qgsnetworkaccessmanager.cpp +++ b/src/core/qgsnetworkaccessmanager.cpp @@ -176,14 +176,14 @@ QNetworkReply *QgsNetworkAccessManager::createRequest( QNetworkAccessManager::Op QNetworkRequest *pReq( const_cast< QNetworkRequest * >( &req ) ); // hack user agent - QString userAgent = s.value( "/qgis/networkAndProxy/userAgent", "Mozilla/5.0" ).toString(); + QString userAgent = s.value( QStringLiteral( "/qgis/networkAndProxy/userAgent" ), "Mozilla/5.0" ).toString(); if ( !userAgent.isEmpty() ) userAgent += ' '; - userAgent += QString( "QGIS/%1" ).arg( Qgis::QGIS_VERSION ); + userAgent += QStringLiteral( "QGIS/%1" ).arg( Qgis::QGIS_VERSION ); pReq->setRawHeader( "User-Agent", userAgent.toUtf8() ); #ifndef QT_NO_OPENSSL - bool ishttps = pReq->url().scheme().toLower() == "https"; + bool ishttps = pReq->url().scheme().toLower() == QLatin1String( "https" ); if ( ishttps && !QgsAuthManager::instance()->isDisabled() ) { QgsDebugMsg( "Adding trusted CA certs to request" ); @@ -191,7 +191,7 @@ QNetworkReply *QgsNetworkAccessManager::createRequest( QNetworkAccessManager::Op sslconfig.setCaCertificates( QgsAuthManager::instance()->getTrustedCaCertsCache() ); // check for SSL cert custom config - QString hostport( QString( "%1:%2" ) + QString hostport( QStringLiteral( "%1:%2" ) .arg( pReq->url().host().trimmed() ) .arg( pReq->url().port() != -1 ? pReq->url().port() : 443 ) ); QgsAuthConfigSslServer servconfig = QgsAuthManager::instance()->getSslCertCustomConfigByHost( hostport.trimmed() ); @@ -216,10 +216,10 @@ QNetworkReply *QgsNetworkAccessManager::createRequest( QNetworkAccessManager::Op // The timer is stopped by the finished signal and is restarted on downloadProgress and // uploadProgress. QTimer *timer = new QTimer( reply ); - timer->setObjectName( "timeoutTimer" ); + timer->setObjectName( QStringLiteral( "timeoutTimer" ) ); connect( timer, SIGNAL( timeout() ), this, SLOT( abortRequest() ) ); timer->setSingleShot( true ); - timer->start( s.value( "/qgis/networkAndProxy/networkTimeout", "60000" ).toInt() ); + timer->start( s.value( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), "60000" ).toInt() ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), timer, SLOT( start() ) ); connect( reply, SIGNAL( uploadProgress( qint64, qint64 ) ), timer, SLOT( start() ) ); @@ -251,34 +251,34 @@ QString QgsNetworkAccessManager::cacheLoadControlName( QNetworkRequest::CacheLoa switch ( theControl ) { case QNetworkRequest::AlwaysNetwork: - return "AlwaysNetwork"; + return QStringLiteral( "AlwaysNetwork" ); case QNetworkRequest::PreferNetwork: - return "PreferNetwork"; + return QStringLiteral( "PreferNetwork" ); case QNetworkRequest::PreferCache: - return "PreferCache"; + return QStringLiteral( "PreferCache" ); case QNetworkRequest::AlwaysCache: - return "AlwaysCache"; + return QStringLiteral( "AlwaysCache" ); default: break; } - return "PreferNetwork"; + return QStringLiteral( "PreferNetwork" ); } QNetworkRequest::CacheLoadControl QgsNetworkAccessManager::cacheLoadControlFromName( const QString &theName ) { - if ( theName == "AlwaysNetwork" ) + if ( theName == QLatin1String( "AlwaysNetwork" ) ) { return QNetworkRequest::AlwaysNetwork; } - else if ( theName == "PreferNetwork" ) + else if ( theName == QLatin1String( "PreferNetwork" ) ) { return QNetworkRequest::PreferNetwork; } - else if ( theName == "PreferCache" ) + else if ( theName == QLatin1String( "PreferCache" ) ) { return QNetworkRequest::PreferCache; } - else if ( theName == "AlwaysCache" ) + else if ( theName == QLatin1String( "AlwaysCache" ) ) { return QNetworkRequest::AlwaysCache; } @@ -317,20 +317,20 @@ void QgsNetworkAccessManager::setupDefaultProxyAndCache() QNetworkProxy proxy; QStringList excludes; - bool proxyEnabled = settings.value( "proxy/proxyEnabled", false ).toBool(); + bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool(); if ( proxyEnabled ) { - excludes = settings.value( "proxy/proxyExcludedUrls", "" ).toString().split( '|', QString::SkipEmptyParts ); + excludes = settings.value( QStringLiteral( "proxy/proxyExcludedUrls" ), "" ).toString().split( '|', QString::SkipEmptyParts ); //read type, host, port, user, passw from settings - QString proxyHost = settings.value( "proxy/proxyHost", "" ).toString(); - int proxyPort = settings.value( "proxy/proxyPort", "" ).toString().toInt(); - QString proxyUser = settings.value( "proxy/proxyUser", "" ).toString(); - QString proxyPassword = settings.value( "proxy/proxyPassword", "" ).toString(); + QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), "" ).toString(); + int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), "" ).toString().toInt(); + QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), "" ).toString(); + QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), "" ).toString(); - QString proxyTypeString = settings.value( "proxy/proxyType", "" ).toString(); + QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), "" ).toString(); - if ( proxyTypeString == "DefaultProxy" ) + if ( proxyTypeString == QLatin1String( "DefaultProxy" ) ) { mUseSystemProxy = true; QNetworkProxyFactory::setUseSystemConfiguration( true ); @@ -344,19 +344,19 @@ void QgsNetworkAccessManager::setupDefaultProxyAndCache() else { QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy; - if ( proxyTypeString == "Socks5Proxy" ) + if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) ) { proxyType = QNetworkProxy::Socks5Proxy; } - else if ( proxyTypeString == "HttpProxy" ) + else if ( proxyTypeString == QLatin1String( "HttpProxy" ) ) { proxyType = QNetworkProxy::HttpProxy; } - else if ( proxyTypeString == "HttpCachingProxy" ) + else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) ) { proxyType = QNetworkProxy::HttpCachingProxy; } - else if ( proxyTypeString == "FtpCachingProxy" ) + else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) ) { proxyType = QNetworkProxy::FtpCachingProxy; } @@ -375,10 +375,10 @@ void QgsNetworkAccessManager::setupDefaultProxyAndCache() if ( !newcache ) newcache = new QgsNetworkDiskCache( this ); - QString cacheDirectory = settings.value( "cache/directory" ).toString(); + QString cacheDirectory = settings.value( QStringLiteral( "cache/directory" ) ).toString(); if ( cacheDirectory.isEmpty() ) cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache"; - qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong(); + qint64 cacheSize = settings.value( QStringLiteral( "cache/size" ), 50 * 1024 * 1024 ).toULongLong(); newcache->setCacheDirectory( cacheDirectory ); newcache->setMaximumCacheSize( cacheSize ); QgsDebugMsg( QString( "cacheDirectory: %1" ).arg( newcache->cacheDirectory() ) ); diff --git a/src/core/qgsnetworkreplyparser.cpp b/src/core/qgsnetworkreplyparser.cpp index 2f76cc86f79e..d08359c3b28b 100644 --- a/src/core/qgsnetworkreplyparser.cpp +++ b/src/core/qgsnetworkreplyparser.cpp @@ -77,7 +77,7 @@ QgsNetworkReplyParser::QgsNetworkReplyParser( QNetworkReply *reply ) { QgsDebugMsg( QString( "No more boundaries, rest size = %1" ).arg( data.size() - from - 1 ) ); // It may be end, last boundary is followed by '--' - if ( data.size() - from - 1 == 2 && QString( data.mid( from, 2 ) ) == "--" ) // end + if ( data.size() - from - 1 == 2 && QString( data.mid( from, 2 ) ) == QLatin1String( "--" ) ) // end { break; } @@ -122,7 +122,7 @@ QgsNetworkReplyParser::QgsNetworkReplyParser( QNetworkReply *reply ) Q_FOREACH ( const QString& row, headerRows ) { QgsDebugMsg( "row = " + row ); - QStringList kv = row.split( ": " ); + QStringList kv = row.split( QStringLiteral( ": " ) ); headersMap.insert( kv.value( 0 ).toLatin1(), kv.value( 1 ).toLatin1() ); } mHeaders.append( headersMap ); @@ -145,5 +145,5 @@ bool QgsNetworkReplyParser::isMultipart( QNetworkReply *reply ) // Multipart content type examples: // multipart/mixed; boundary=wcs // multipart/mixed; boundary="wcs"\n - return contentType.startsWith( "multipart/", Qt::CaseInsensitive ); + return contentType.startsWith( QLatin1String( "multipart/" ), Qt::CaseInsensitive ); } diff --git a/src/core/qgsobjectcustomproperties.cpp b/src/core/qgsobjectcustomproperties.cpp index f438b4f94a0c..0ac3a3b61240 100644 --- a/src/core/qgsobjectcustomproperties.cpp +++ b/src/core/qgsobjectcustomproperties.cpp @@ -48,7 +48,7 @@ void QgsObjectCustomProperties::remove( const QString& key ) void QgsObjectCustomProperties::readXml( const QDomNode& parentNode, const QString& keyStartsWith ) { - QDomNode propsNode = parentNode.namedItem( "customproperties" ); + QDomNode propsNode = parentNode.namedItem( QStringLiteral( "customproperties" ) ); if ( propsNode.isNull() ) // no properties stored... return; @@ -81,25 +81,25 @@ void QgsObjectCustomProperties::readXml( const QDomNode& parentNode, const QStri for ( int i = 0; i < nodes.size(); i++ ) { QDomNode propNode = nodes.at( i ); - if ( propNode.isNull() || propNode.nodeName() != "property" ) + if ( propNode.isNull() || propNode.nodeName() != QLatin1String( "property" ) ) continue; QDomElement propElement = propNode.toElement(); - QString key = propElement.attribute( "key" ); + QString key = propElement.attribute( QStringLiteral( "key" ) ); if ( key.isEmpty() || key.startsWith( keyStartsWith ) ) { - if ( propElement.hasAttribute( "value" ) ) + if ( propElement.hasAttribute( QStringLiteral( "value" ) ) ) { - QString value = propElement.attribute( "value" ); + QString value = propElement.attribute( QStringLiteral( "value" ) ); mMap[key] = QVariant( value ); } else { QStringList list; - for ( QDomElement itemElement = propElement.firstChildElement( "value" ); + for ( QDomElement itemElement = propElement.firstChildElement( QStringLiteral( "value" ) ); !itemElement.isNull(); - itemElement = itemElement.nextSiblingElement( "value" ) ) + itemElement = itemElement.nextSiblingElement( QStringLiteral( "value" ) ) ) { list << itemElement.text(); } @@ -114,27 +114,27 @@ void QgsObjectCustomProperties::readXml( const QDomNode& parentNode, const QStri void QgsObjectCustomProperties::writeXml( QDomNode& parentNode, QDomDocument& doc ) const { //remove already existing tags - QDomNodeList propertyList = parentNode.toElement().elementsByTagName( "customproperties" ); + QDomNodeList propertyList = parentNode.toElement().elementsByTagName( QStringLiteral( "customproperties" ) ); for ( int i = 0; i < propertyList.size(); ++i ) { parentNode.removeChild( propertyList.at( i ) ); } - QDomElement propsElement = doc.createElement( "customproperties" ); + QDomElement propsElement = doc.createElement( QStringLiteral( "customproperties" ) ); for ( QMap::const_iterator it = mMap.constBegin(); it != mMap.constEnd(); ++it ) { - QDomElement propElement = doc.createElement( "property" ); - propElement.setAttribute( "key", it.key() ); + QDomElement propElement = doc.createElement( QStringLiteral( "property" ) ); + propElement.setAttribute( QStringLiteral( "key" ), it.key() ); if ( it.value().canConvert() ) { - propElement.setAttribute( "value", it.value().toString() ); + propElement.setAttribute( QStringLiteral( "value" ), it.value().toString() ); } else if ( it.value().canConvert() ) { Q_FOREACH ( const QString& value, it.value().toStringList() ) { - QDomElement itemElement = doc.createElement( "value" ); + QDomElement itemElement = doc.createElement( QStringLiteral( "value" ) ); itemElement.appendChild( doc.createTextNode( value ) ); propElement.appendChild( itemElement ); } diff --git a/src/core/qgsofflineediting.cpp b/src/core/qgsofflineediting.cpp index aed1683e558b..6bd50c33b0da 100644 --- a/src/core/qgsofflineediting.cpp +++ b/src/core/qgsofflineediting.cpp @@ -185,7 +185,7 @@ bool QgsOfflineEditing::convertToOfflineProject( const QString& offlineDataPath, { projectTitle = QFileInfo( QgsProject::instance()->fileName() ).fileName(); } - projectTitle += " (offline)"; + projectTitle += QLatin1String( " (offline)" ); QgsProject::instance()->setTitle( projectTitle ); QgsProject::instance()->writeEntry( PROJECT_ENTRY_SCOPE_OFFLINE, PROJECT_ENTRY_KEY_OFFLINE_DB_PATH, QgsProject::instance()->writePath( dbPath ) ); @@ -241,7 +241,7 @@ void QgsOfflineEditing::synchronize() if ( remoteLayer->isValid() ) { // Rebuild WFS cache to get feature id<->GML fid mapping - if ( remoteLayer->dataProvider()->name().contains( "WFS", Qt::CaseInsensitive ) ) + if ( remoteLayer->dataProvider()->name().contains( QLatin1String( "WFS" ), Qt::CaseInsensitive ) ) { QgsFeatureIterator fit = remoteLayer->getFeatures(); QgsFeature f; @@ -261,7 +261,7 @@ void QgsOfflineEditing::synchronize() // apply layer edit log QString qgisLayerId = layer->id(); - QString sql = QString( "SELECT \"id\" FROM 'log_layer_ids' WHERE \"qgis_id\" = '%1'" ).arg( qgisLayerId ); + QString sql = QStringLiteral( "SELECT \"id\" FROM 'log_layer_ids' WHERE \"qgis_id\" = '%1'" ).arg( qgisLayerId ); int layerId = sqlQueryInt( db, sql, -1 ); if ( layerId != -1 ) { @@ -288,24 +288,24 @@ void QgsOfflineEditing::synchronize() updateFidLookup( remoteLayer, db, layerId ); // clear edit log for this layer - sql = QString( "DELETE FROM 'log_added_attrs' WHERE \"layer_id\" = %1" ).arg( layerId ); + sql = QStringLiteral( "DELETE FROM 'log_added_attrs' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); - sql = QString( "DELETE FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); + sql = QStringLiteral( "DELETE FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); - sql = QString( "DELETE FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId ); + sql = QStringLiteral( "DELETE FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); - sql = QString( "DELETE FROM 'log_feature_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); + sql = QStringLiteral( "DELETE FROM 'log_feature_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); - sql = QString( "DELETE FROM 'log_geometry_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); + sql = QStringLiteral( "DELETE FROM 'log_geometry_updates' WHERE \"layer_id\" = %1" ).arg( layerId ); sqlExec( db, sql ); // reset commitNo - QString sql = QString( "UPDATE 'log_indices' SET 'last_index' = 0 WHERE \"name\" = 'commit_no'" ); + QString sql = QStringLiteral( "UPDATE 'log_indices' SET 'last_index' = 0 WHERE \"name\" = 'commit_no'" ); sqlExec( db, sql ); } else { - showWarning( remoteLayer->commitErrors().join( "\n" ) ); + showWarning( remoteLayer->commitErrors().join( QStringLiteral( "\n" ) ) ); } } else @@ -441,42 +441,42 @@ bool QgsOfflineEditing::createSpatialiteDB( const QString& offlineDbPath ) void QgsOfflineEditing::createLoggingTables( sqlite3* db ) { // indices - QString sql = "CREATE TABLE 'log_indices' ('name' TEXT, 'last_index' INTEGER)"; + QString sql = QStringLiteral( "CREATE TABLE 'log_indices' ('name' TEXT, 'last_index' INTEGER)" ); sqlExec( db, sql ); - sql = "INSERT INTO 'log_indices' VALUES ('commit_no', 0)"; + sql = QStringLiteral( "INSERT INTO 'log_indices' VALUES ('commit_no', 0)" ); sqlExec( db, sql ); - sql = "INSERT INTO 'log_indices' VALUES ('layer_id', 0)"; + sql = QStringLiteral( "INSERT INTO 'log_indices' VALUES ('layer_id', 0)" ); sqlExec( db, sql ); // layername <-> layer id - sql = "CREATE TABLE 'log_layer_ids' ('id' INTEGER, 'qgis_id' TEXT)"; + sql = QStringLiteral( "CREATE TABLE 'log_layer_ids' ('id' INTEGER, 'qgis_id' TEXT)" ); sqlExec( db, sql ); // offline fid <-> remote fid - sql = "CREATE TABLE 'log_fids' ('layer_id' INTEGER, 'offline_fid' INTEGER, 'remote_fid' INTEGER)"; + sql = QStringLiteral( "CREATE TABLE 'log_fids' ('layer_id' INTEGER, 'offline_fid' INTEGER, 'remote_fid' INTEGER)" ); sqlExec( db, sql ); // added attributes - sql = "CREATE TABLE 'log_added_attrs' ('layer_id' INTEGER, 'commit_no' INTEGER, "; - sql += "'name' TEXT, 'type' INTEGER, 'length' INTEGER, 'precision' INTEGER, 'comment' TEXT)"; + sql = QStringLiteral( "CREATE TABLE 'log_added_attrs' ('layer_id' INTEGER, 'commit_no' INTEGER, " ); + sql += QLatin1String( "'name' TEXT, 'type' INTEGER, 'length' INTEGER, 'precision' INTEGER, 'comment' TEXT)" ); sqlExec( db, sql ); // added features - sql = "CREATE TABLE 'log_added_features' ('layer_id' INTEGER, 'fid' INTEGER)"; + sql = QStringLiteral( "CREATE TABLE 'log_added_features' ('layer_id' INTEGER, 'fid' INTEGER)" ); sqlExec( db, sql ); // removed features - sql = "CREATE TABLE 'log_removed_features' ('layer_id' INTEGER, 'fid' INTEGER)"; + sql = QStringLiteral( "CREATE TABLE 'log_removed_features' ('layer_id' INTEGER, 'fid' INTEGER)" ); sqlExec( db, sql ); // feature updates - sql = "CREATE TABLE 'log_feature_updates' ('layer_id' INTEGER, 'commit_no' INTEGER, 'fid' INTEGER, 'attr' INTEGER, 'value' TEXT)"; + sql = QStringLiteral( "CREATE TABLE 'log_feature_updates' ('layer_id' INTEGER, 'commit_no' INTEGER, 'fid' INTEGER, 'attr' INTEGER, 'value' TEXT)" ); sqlExec( db, sql ); // geometry updates - sql = "CREATE TABLE 'log_geometry_updates' ('layer_id' INTEGER, 'commit_no' INTEGER, 'fid' INTEGER, 'geom_wkt' TEXT)"; + sql = QStringLiteral( "CREATE TABLE 'log_geometry_updates' ('layer_id' INTEGER, 'commit_no' INTEGER, 'fid' INTEGER, 'geom_wkt' TEXT)" ); sqlExec( db, sql ); /* TODO: other logging tables @@ -493,30 +493,30 @@ QgsVectorLayer* QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlit QgsDebugMsgLevel( QString( "Creating offline table %1 ..." ).arg( tableName ), 4 ); // create table - QString sql = QString( "CREATE TABLE '%1' (" ).arg( tableName ); - QString delim = ""; + QString sql = QStringLiteral( "CREATE TABLE '%1' (" ).arg( tableName ); + QString delim = QLatin1String( "" ); Q_FOREACH ( const QgsField& field, layer->dataProvider()->fields() ) { - QString dataType = ""; + QString dataType = QLatin1String( "" ); QVariant::Type type = field.type(); if ( type == QVariant::Int || type == QVariant::LongLong ) { - dataType = "INTEGER"; + dataType = QStringLiteral( "INTEGER" ); } else if ( type == QVariant::Double ) { - dataType = "REAL"; + dataType = QStringLiteral( "REAL" ); } else if ( type == QVariant::String ) { - dataType = "TEXT"; + dataType = QStringLiteral( "TEXT" ); } else { showWarning( tr( "%1: Unknown data type %2. Not using type affinity for the field." ).arg( field.name(), QVariant::typeToName( type ) ) ); } - sql += delim + QString( "'%1' %2" ).arg( field.name(), dataType ); + sql += delim + QStringLiteral( "'%1' %2" ).arg( field.name(), dataType ); delim = ','; } sql += ')'; @@ -526,38 +526,38 @@ QgsVectorLayer* QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlit // add geometry column if ( layer->hasGeometryType() ) { - QString geomType = ""; + QString geomType = QLatin1String( "" ); switch ( layer->wkbType() ) { case QgsWkbTypes::Point: - geomType = "POINT"; + geomType = QStringLiteral( "POINT" ); break; case QgsWkbTypes::MultiPoint: - geomType = "MULTIPOINT"; + geomType = QStringLiteral( "MULTIPOINT" ); break; case QgsWkbTypes::LineString: - geomType = "LINESTRING"; + geomType = QStringLiteral( "LINESTRING" ); break; case QgsWkbTypes::MultiLineString: - geomType = "MULTILINESTRING"; + geomType = QStringLiteral( "MULTILINESTRING" ); break; case QgsWkbTypes::Polygon: - geomType = "POLYGON"; + geomType = QStringLiteral( "POLYGON" ); break; case QgsWkbTypes::MultiPolygon: - geomType = "MULTIPOLYGON"; + geomType = QStringLiteral( "MULTIPOLYGON" ); break; default: showWarning( tr( "QGIS wkbType %1 not supported" ).arg( layer->wkbType() ) ); break; }; - QString sqlAddGeom = QString( "SELECT AddGeometryColumn('%1', 'Geometry', %2, '%3', 2)" ) + QString sqlAddGeom = QStringLiteral( "SELECT AddGeometryColumn('%1', 'Geometry', %2, '%3', 2)" ) .arg( tableName ) - .arg( layer->crs().authid().startsWith( "EPSG:", Qt::CaseInsensitive ) ? layer->crs().authid().mid( 5 ).toLong() : 0 ) + .arg( layer->crs().authid().startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) ? layer->crs().authid().mid( 5 ).toLong() : 0 ) .arg( geomType ); // create spatial index - QString sqlCreateIndex = QString( "SELECT CreateSpatialIndex('%1', 'Geometry')" ).arg( tableName ); + QString sqlCreateIndex = QStringLiteral( "SELECT CreateSpatialIndex('%1', 'Geometry')" ).arg( tableName ); if ( rc == SQLITE_OK ) { @@ -572,11 +572,11 @@ QgsVectorLayer* QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlit if ( rc == SQLITE_OK ) { // add new layer - QString connectionString = QString( "dbname='%1' table='%2'%3 sql=" ) + QString connectionString = QStringLiteral( "dbname='%1' table='%2'%3 sql=" ) .arg( offlineDbPath, tableName, layer->hasGeometryType() ? "(Geometry)" : "" ); QgsVectorLayer* newLayer = new QgsVectorLayer( connectionString, - layer->name() + " (offline)", "spatialite" ); + layer->name() + " (offline)", QStringLiteral( "spatialite" ) ); if ( newLayer->isValid() ) { // mark as offline layer @@ -679,7 +679,7 @@ QgsVectorLayer* QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlit } // NOTE: insert fids in this loop, as the db is locked during newLayer->nextFeature() - sqlExec( db, "BEGIN" ); + sqlExec( db, QStringLiteral( "BEGIN" ) ); int remoteCount = remoteFeatureIds.size(); for ( int i = 0; i < remoteCount; i++ ) { @@ -695,11 +695,11 @@ QgsVectorLayer* QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlit } emit progressUpdated( featureCount++ ); } - sqlExec( db, "COMMIT" ); + sqlExec( db, QStringLiteral( "COMMIT" ) ); } else { - showWarning( newLayer->commitErrors().join( "\n" ) ); + showWarning( newLayer->commitErrors().join( QStringLiteral( "\n" ) ) ); } } return newLayer; @@ -709,7 +709,7 @@ QgsVectorLayer* QgsOfflineEditing::copyVectorLayer( QgsVectorLayer* layer, sqlit void QgsOfflineEditing::applyAttributesAdded( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId, int commitNo ) { - QString sql = QString( "SELECT \"name\", \"type\", \"length\", \"precision\", \"comment\" FROM 'log_added_attrs' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2" ).arg( layerId ).arg( commitNo ); + QString sql = QStringLiteral( "SELECT \"name\", \"type\", \"length\", \"precision\", \"comment\" FROM 'log_added_attrs' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2" ).arg( layerId ).arg( commitNo ); QList fields = sqlQueryAttributesAdded( db, sql ); const QgsVectorDataProvider* provider = remoteLayer->dataProvider(); @@ -737,7 +737,7 @@ void QgsOfflineEditing::applyAttributesAdded( QgsVectorLayer* remoteLayer, sqlit } else { - showWarning( QString( "Could not add attribute '%1' of type %2" ).arg( field.name() ).arg( field.type() ) ); + showWarning( QStringLiteral( "Could not add attribute '%1' of type %2" ).arg( field.name() ).arg( field.type() ) ); } emit progressUpdated( i + 1 ); @@ -746,7 +746,7 @@ void QgsOfflineEditing::applyAttributesAdded( QgsVectorLayer* remoteLayer, sqlit void QgsOfflineEditing::applyFeaturesAdded( QgsVectorLayer* offlineLayer, QgsVectorLayer* remoteLayer, sqlite3* db, int layerId ) { - QString sql = QString( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); + QString sql = QStringLiteral( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); QList newFeatureIds = sqlQueryInts( db, sql ); QgsFields remoteFlds = remoteLayer->fields(); @@ -806,7 +806,7 @@ void QgsOfflineEditing::applyFeaturesAdded( QgsVectorLayer* offlineLayer, QgsVec void QgsOfflineEditing::applyFeaturesRemoved( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId ) { - QString sql = QString( "SELECT \"fid\" FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId ); + QString sql = QStringLiteral( "SELECT \"fid\" FROM 'log_removed_features' WHERE \"layer_id\" = %1" ).arg( layerId ); QgsFeatureIds values = sqlQueryFeaturesRemoved( db, sql ); emit progressModeSet( QgsOfflineEditing::RemoveFeatures, values.size() ); @@ -823,7 +823,7 @@ void QgsOfflineEditing::applyFeaturesRemoved( QgsVectorLayer* remoteLayer, sqlit void QgsOfflineEditing::applyAttributeValueChanges( QgsVectorLayer* offlineLayer, QgsVectorLayer* remoteLayer, sqlite3* db, int layerId, int commitNo ) { - QString sql = QString( "SELECT \"fid\", \"attr\", \"value\" FROM 'log_feature_updates' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2 " ).arg( layerId ).arg( commitNo ); + QString sql = QStringLiteral( "SELECT \"fid\", \"attr\", \"value\" FROM 'log_feature_updates' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2 " ).arg( layerId ).arg( commitNo ); AttributeValueChanges values = sqlQueryAttributeValueChanges( db, sql ); emit progressModeSet( QgsOfflineEditing::UpdateFeatures, values.size() ); @@ -842,7 +842,7 @@ void QgsOfflineEditing::applyAttributeValueChanges( QgsVectorLayer* offlineLayer void QgsOfflineEditing::applyGeometryChanges( QgsVectorLayer* remoteLayer, sqlite3* db, int layerId, int commitNo ) { - QString sql = QString( "SELECT \"fid\", \"geom_wkt\" FROM 'log_geometry_updates' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2" ).arg( layerId ).arg( commitNo ); + QString sql = QStringLiteral( "SELECT \"fid\", \"geom_wkt\" FROM 'log_geometry_updates' WHERE \"layer_id\" = %1 AND \"commit_no\" = %2" ).arg( layerId ).arg( commitNo ); GeometryChanges values = sqlQueryGeometryChanges( db, sql ); emit progressModeSet( QgsOfflineEditing::UpdateGeometries, values.size() ); @@ -883,7 +883,7 @@ void QgsOfflineEditing::updateFidLookup( QgsVectorLayer* remoteLayer, sqlite3* d // get local added fids // NOTE: fids are sorted - QString sql = QString( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); + QString sql = QStringLiteral( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); QList newOfflineFids = sqlQueryInts( db, sql ); if ( newRemoteFids.size() != newOfflineFids.size() ) @@ -894,12 +894,12 @@ void QgsOfflineEditing::updateFidLookup( QgsVectorLayer* remoteLayer, sqlite3* d { // add new fid lookups i = 0; - sqlExec( db, "BEGIN" ); + sqlExec( db, QStringLiteral( "BEGIN" ) ); for ( QMap::const_iterator it = newRemoteFids.begin(); it != newRemoteFids.end(); ++it ) { addFidLookup( db, layerId, newOfflineFids.at( i++ ), it.key() ); } - sqlExec( db, "COMMIT" ); + sqlExec( db, QStringLiteral( "COMMIT" ) ); } } @@ -965,21 +965,21 @@ sqlite3* QgsOfflineEditing::openLoggingDb() int QgsOfflineEditing::getOrCreateLayerId( sqlite3* db, const QString& qgisLayerId ) { - QString sql = QString( "SELECT \"id\" FROM 'log_layer_ids' WHERE \"qgis_id\" = '%1'" ).arg( qgisLayerId ); + QString sql = QStringLiteral( "SELECT \"id\" FROM 'log_layer_ids' WHERE \"qgis_id\" = '%1'" ).arg( qgisLayerId ); int layerId = sqlQueryInt( db, sql, -1 ); if ( layerId == -1 ) { // next layer id - sql = "SELECT \"last_index\" FROM 'log_indices' WHERE \"name\" = 'layer_id'"; + sql = QStringLiteral( "SELECT \"last_index\" FROM 'log_indices' WHERE \"name\" = 'layer_id'" ); int newLayerId = sqlQueryInt( db, sql, -1 ); // insert layer - sql = QString( "INSERT INTO 'log_layer_ids' VALUES (%1, '%2')" ).arg( newLayerId ).arg( qgisLayerId ); + sql = QStringLiteral( "INSERT INTO 'log_layer_ids' VALUES (%1, '%2')" ).arg( newLayerId ).arg( qgisLayerId ); sqlExec( db, sql ); // increase layer_id // TODO: use trigger for auto increment? - sql = QString( "UPDATE 'log_indices' SET 'last_index' = %1 WHERE \"name\" = 'layer_id'" ).arg( newLayerId + 1 ); + sql = QStringLiteral( "UPDATE 'log_indices' SET 'last_index' = %1 WHERE \"name\" = 'layer_id'" ).arg( newLayerId + 1 ); sqlExec( db, sql ); layerId = newLayerId; @@ -990,37 +990,37 @@ int QgsOfflineEditing::getOrCreateLayerId( sqlite3* db, const QString& qgisLayer int QgsOfflineEditing::getCommitNo( sqlite3* db ) { - QString sql = "SELECT \"last_index\" FROM 'log_indices' WHERE \"name\" = 'commit_no'"; + QString sql = QStringLiteral( "SELECT \"last_index\" FROM 'log_indices' WHERE \"name\" = 'commit_no'" ); return sqlQueryInt( db, sql, -1 ); } void QgsOfflineEditing::increaseCommitNo( sqlite3* db ) { - QString sql = QString( "UPDATE 'log_indices' SET 'last_index' = %1 WHERE \"name\" = 'commit_no'" ).arg( getCommitNo( db ) + 1 ); + QString sql = QStringLiteral( "UPDATE 'log_indices' SET 'last_index' = %1 WHERE \"name\" = 'commit_no'" ).arg( getCommitNo( db ) + 1 ); sqlExec( db, sql ); } void QgsOfflineEditing::addFidLookup( sqlite3* db, int layerId, QgsFeatureId offlineFid, QgsFeatureId remoteFid ) { - QString sql = QString( "INSERT INTO 'log_fids' VALUES ( %1, %2, %3 )" ).arg( layerId ).arg( offlineFid ).arg( remoteFid ); + QString sql = QStringLiteral( "INSERT INTO 'log_fids' VALUES ( %1, %2, %3 )" ).arg( layerId ).arg( offlineFid ).arg( remoteFid ); sqlExec( db, sql ); } QgsFeatureId QgsOfflineEditing::remoteFid( sqlite3* db, int layerId, QgsFeatureId offlineFid ) { - QString sql = QString( "SELECT \"remote_fid\" FROM 'log_fids' WHERE \"layer_id\" = %1 AND \"offline_fid\" = %2" ).arg( layerId ).arg( offlineFid ); + QString sql = QStringLiteral( "SELECT \"remote_fid\" FROM 'log_fids' WHERE \"layer_id\" = %1 AND \"offline_fid\" = %2" ).arg( layerId ).arg( offlineFid ); return sqlQueryInt( db, sql, -1 ); } QgsFeatureId QgsOfflineEditing::offlineFid( sqlite3* db, int layerId, QgsFeatureId remoteFid ) { - QString sql = QString( "SELECT \"offline_fid\" FROM 'log_fids' WHERE \"layer_id\" = %1 AND \"remote_fid\" = %2" ).arg( layerId ).arg( remoteFid ); + QString sql = QStringLiteral( "SELECT \"offline_fid\" FROM 'log_fids' WHERE \"layer_id\" = %1 AND \"remote_fid\" = %2" ).arg( layerId ).arg( remoteFid ); return sqlQueryInt( db, sql, -1 ); } bool QgsOfflineEditing::isAddedFeature( sqlite3* db, int layerId, QgsFeatureId fid ) { - QString sql = QString( "SELECT COUNT(\"fid\") FROM 'log_added_features' WHERE \"layer_id\" = %1 AND \"fid\" = %2" ).arg( layerId ).arg( fid ); + QString sql = QStringLiteral( "SELECT COUNT(\"fid\") FROM 'log_added_features' WHERE \"layer_id\" = %1 AND \"fid\" = %2" ).arg( layerId ).arg( fid ); return ( sqlQueryInt( db, sql, 0 ) > 0 ); } @@ -1094,7 +1094,7 @@ QList QgsOfflineEditing::sqlQueryAttributesAdded( sqlite3* db, const Q { QgsField field( QString( reinterpret_cast< const char* >( sqlite3_column_text( stmt, 0 ) ) ), static_cast< QVariant::Type >( sqlite3_column_int( stmt, 1 ) ), - "", // typeName + QLatin1String( "" ), // typeName sqlite3_column_int( stmt, 2 ), sqlite3_column_int( stmt, 3 ), QString( reinterpret_cast< const char* >( sqlite3_column_text( stmt, 4 ) ) ) ); @@ -1196,7 +1196,7 @@ void QgsOfflineEditing::committedAttributesAdded( const QString& qgisLayerId, co for ( QList::const_iterator it = addedAttributes.begin(); it != addedAttributes.end(); ++it ) { QgsField field = *it; - QString sql = QString( "INSERT INTO 'log_added_attrs' VALUES ( %1, %2, '%3', %4, %5, %6, '%7' )" ) + QString sql = QStringLiteral( "INSERT INTO 'log_added_attrs' VALUES ( %1, %2, '%3', %4, %5, %6, '%7' )" ) .arg( layerId ) .arg( commitNo ) .arg( field.name() ) @@ -1225,11 +1225,11 @@ void QgsOfflineEditing::committedFeaturesAdded( const QString& qgisLayerId, cons QgsDataSourceUri uri = QgsDataSourceUri( layer->source() ); // only store feature ids - QString sql = QString( "SELECT ROWID FROM '%1' ORDER BY ROWID DESC LIMIT %2" ).arg( uri.table() ).arg( addedFeatures.size() ); + QString sql = QStringLiteral( "SELECT ROWID FROM '%1' ORDER BY ROWID DESC LIMIT %2" ).arg( uri.table() ).arg( addedFeatures.size() ); QList newFeatureIds = sqlQueryInts( db, sql ); for ( int i = newFeatureIds.size() - 1; i >= 0; i-- ) { - QString sql = QString( "INSERT INTO 'log_added_features' VALUES ( %1, %2 )" ) + QString sql = QStringLiteral( "INSERT INTO 'log_added_features' VALUES ( %1, %2 )" ) .arg( layerId ) .arg( newFeatureIds.at( i ) ); sqlExec( db, sql ); @@ -1252,12 +1252,12 @@ void QgsOfflineEditing::committedFeaturesRemoved( const QString& qgisLayerId, co if ( isAddedFeature( db, layerId, *it ) ) { // remove from added features log - QString sql = QString( "DELETE FROM 'log_added_features' WHERE \"layer_id\" = %1 AND \"fid\" = %2" ).arg( layerId ).arg( *it ); + QString sql = QStringLiteral( "DELETE FROM 'log_added_features' WHERE \"layer_id\" = %1 AND \"fid\" = %2" ).arg( layerId ).arg( *it ); sqlExec( db, sql ); } else { - QString sql = QString( "INSERT INTO 'log_removed_features' VALUES ( %1, %2)" ) + QString sql = QStringLiteral( "INSERT INTO 'log_removed_features' VALUES ( %1, %2)" ) .arg( layerId ) .arg( *it ); sqlExec( db, sql ); @@ -1288,7 +1288,7 @@ void QgsOfflineEditing::committedAttributeValuesChanges( const QString& qgisLaye QgsAttributeMap attrMap = cit.value(); for ( QgsAttributeMap::const_iterator it = attrMap.begin(); it != attrMap.end(); ++it ) { - QString sql = QString( "INSERT INTO 'log_feature_updates' VALUES ( %1, %2, %3, %4, '%5' )" ) + QString sql = QStringLiteral( "INSERT INTO 'log_feature_updates' VALUES ( %1, %2, %3, %4, '%5' )" ) .arg( layerId ) .arg( commitNo ) .arg( fid ) @@ -1321,7 +1321,7 @@ void QgsOfflineEditing::committedGeometriesChanges( const QString& qgisLayerId, continue; } QgsGeometry geom = it.value(); - QString sql = QString( "INSERT INTO 'log_geometry_updates' VALUES ( %1, %2, %3, '%4' )" ) + QString sql = QStringLiteral( "INSERT INTO 'log_geometry_updates' VALUES ( %1, %2, %3, '%4' )" ) .arg( layerId ) .arg( commitNo ) .arg( fid ) diff --git a/src/core/qgsogcutils.cpp b/src/core/qgsogcutils.cpp index 255ea577b154..6918fc5b5b21 100644 --- a/src/core/qgsogcutils.cpp +++ b/src/core/qgsogcutils.cpp @@ -33,10 +33,10 @@ #endif -static const QString GML_NAMESPACE = "http://www.opengis.net/gml"; -static const QString GML32_NAMESPACE = "http://www.opengis.net/gml/3.2"; -static const QString OGC_NAMESPACE = "http://www.opengis.net/ogc"; -static const QString FES_NAMESPACE = "http://www.opengis.net/fes/2.0"; +static const QString GML_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml" ); +static const QString GML32_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml/3.2" ); +static const QString OGC_NAMESPACE = QStringLiteral( "http://www.opengis.net/ogc" ); +static const QString FES_NAMESPACE = QStringLiteral( "http://www.opengis.net/fes/2.0" ); QgsOgcUtilsExprToFilter::QgsOgcUtilsExprToFilter( QDomDocument& doc, QgsOgcUtils::GMLVersion gmlVersion, @@ -73,9 +73,9 @@ QgsGeometry QgsOgcUtils::geometryFromGML( const QDomNode& geometryNode ) QDomElement geometryTypeElement = geometryNode.toElement(); QString geomType = geometryTypeElement.tagName(); - if ( !( geomType == "Point" || geomType == "LineString" || geomType == "Polygon" || - geomType == "MultiPoint" || geomType == "MultiLineString" || geomType == "MultiPolygon" || - geomType == "Box" || geomType == "Envelope" ) ) + if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) || + geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) || + geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) ) { QDomNode geometryChild = geometryNode.firstChild(); if ( geometryChild.isNull() ) @@ -86,40 +86,40 @@ QgsGeometry QgsOgcUtils::geometryFromGML( const QDomNode& geometryNode ) geomType = geometryTypeElement.tagName(); } - if ( !( geomType == "Point" || geomType == "LineString" || geomType == "Polygon" || - geomType == "MultiPoint" || geomType == "MultiLineString" || geomType == "MultiPolygon" || - geomType == "Box" || geomType == "Envelope" ) ) + if ( !( geomType == QLatin1String( "Point" ) || geomType == QLatin1String( "LineString" ) || geomType == QLatin1String( "Polygon" ) || + geomType == QLatin1String( "MultiPoint" ) || geomType == QLatin1String( "MultiLineString" ) || geomType == QLatin1String( "MultiPolygon" ) || + geomType == QLatin1String( "Box" ) || geomType == QLatin1String( "Envelope" ) ) ) return QgsGeometry(); - if ( geomType == "Point" ) + if ( geomType == QLatin1String( "Point" ) ) { return geometryFromGMLPoint( geometryTypeElement ); } - else if ( geomType == "LineString" ) + else if ( geomType == QLatin1String( "LineString" ) ) { return geometryFromGMLLineString( geometryTypeElement ); } - else if ( geomType == "Polygon" ) + else if ( geomType == QLatin1String( "Polygon" ) ) { return geometryFromGMLPolygon( geometryTypeElement ); } - else if ( geomType == "MultiPoint" ) + else if ( geomType == QLatin1String( "MultiPoint" ) ) { return geometryFromGMLMultiPoint( geometryTypeElement ); } - else if ( geomType == "MultiLineString" ) + else if ( geomType == QLatin1String( "MultiLineString" ) ) { return geometryFromGMLMultiLineString( geometryTypeElement ); } - else if ( geomType == "MultiPolygon" ) + else if ( geomType == QLatin1String( "MultiPolygon" ) ) { return geometryFromGMLMultiPolygon( geometryTypeElement ); } - else if ( geomType == "Box" ) + else if ( geomType == QLatin1String( "Box" ) ) { return QgsGeometry::fromRect( rectangleFromGMLBox( geometryTypeElement ) ); } - else if ( geomType == "Envelope" ) + else if ( geomType == QLatin1String( "Envelope" ) ) { return QgsGeometry::fromRect( rectangleFromGMLEnvelope( geometryTypeElement ) ); } @@ -132,7 +132,7 @@ QgsGeometry QgsOgcUtils::geometryFromGML( const QDomNode& geometryNode ) QgsGeometry QgsOgcUtils::geometryFromGML( const QString& xmlString ) { // wrap the string into a root tag to have "gml" namespace (and also as a default namespace) - QString xml = QString( "%2" ).arg( GML_NAMESPACE, xmlString ); + QString xml = QStringLiteral( "%2" ).arg( GML_NAMESPACE, xmlString ); QDomDocument doc; if ( !doc.setContent( xml, true ) ) return QgsGeometry(); @@ -145,7 +145,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLPoint( const QDomElement& geometryElemen { QgsPolyline pointCoordinate; - QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordList.isEmpty() ) { QDomElement coordElement = coordList.at( 0 ).toElement(); @@ -156,7 +156,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLPoint( const QDomElement& geometryElemen } else { - QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "pos" ); + QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) ); if ( posList.size() < 1 ) { return QgsGeometry(); @@ -200,7 +200,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLLineString( const QDomElement& geometryE { QgsPolyline lineCoordinates; - QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + QDomNodeList coordList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordList.isEmpty() ) { QDomElement coordElement = coordList.at( 0 ).toElement(); @@ -211,7 +211,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLLineString( const QDomElement& geometryE } else { - QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "posList" ); + QDomNodeList posList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( posList.size() < 1 ) { return QgsGeometry(); @@ -264,7 +264,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement& geometryElem //read coordinates for outer boundary QgsPolyline exteriorPointList; - QDomNodeList outerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "outerBoundaryIs" ); + QDomNodeList outerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) ); if ( !outerBoundaryList.isEmpty() ) //outer ring is necessary { QDomElement coordinatesElement = outerBoundaryList.at( 0 ).firstChild().firstChild().toElement(); @@ -279,7 +279,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement& geometryElem ringCoordinates.push_back( exteriorPointList ); //read coordinates for inner boundary - QDomNodeList innerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "innerBoundaryIs" ); + QDomNodeList innerBoundaryList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) ); for ( int i = 0; i < innerBoundaryList.size(); ++i ) { QgsPolyline interiorPointList; @@ -298,7 +298,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement& geometryElem else { //read coordinates for exterior - QDomNodeList exteriorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "exterior" ); + QDomNodeList exteriorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) ); if ( exteriorList.size() < 1 ) //outer ring is necessary { return QgsGeometry(); @@ -315,7 +315,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLPolygon( const QDomElement& geometryElem ringCoordinates.push_back( exteriorPointList ); //read coordinates for inner boundary - QDomNodeList interiorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "interior" ); + QDomNodeList interiorList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) ); for ( int i = 0; i < interiorList.size(); ++i ) { QgsPolyline interiorPointList; @@ -388,7 +388,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPoint( const QDomElement& geometryE { QgsPolyline pointList; QgsPolyline currentPoint; - QDomNodeList pointMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "pointMember" ); + QDomNodeList pointMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pointMember" ) ); if ( pointMemberList.size() < 1 ) { return QgsGeometry(); @@ -400,13 +400,13 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPoint( const QDomElement& geometryE for ( int i = 0; i < pointMemberList.size(); ++i ) { // element - pointNodeList = pointMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, "Point" ); + pointNodeList = pointMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Point" ) ); if ( pointNodeList.size() < 1 ) { continue; } // element - coordinatesList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + coordinatesList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !coordinatesList.isEmpty() ) { currentPoint.clear(); @@ -424,7 +424,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPoint( const QDomElement& geometryE else { // element - posList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, "pos" ); + posList = pointNodeList.at( 0 ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "pos" ) ); if ( posList.size() < 1 ) { continue; @@ -498,18 +498,18 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement& geom QDomNodeList currentCoordList; QDomNodeList currentPosList; - QDomNodeList lineStringMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "lineStringMember" ); + QDomNodeList lineStringMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lineStringMember" ) ); if ( !lineStringMemberList.isEmpty() ) //geoserver { for ( int i = 0; i < lineStringMemberList.size(); ++i ) { - QDomNodeList lineStringNodeList = lineStringMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, "LineString" ); + QDomNodeList lineStringNodeList = lineStringMemberList.at( i ).toElement().elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) ); if ( lineStringNodeList.size() < 1 ) { return QgsGeometry(); } currentLineStringElement = lineStringNodeList.at( 0 ).toElement(); - currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !currentCoordList.isEmpty() ) { QgsPolyline currentPointList; @@ -521,7 +521,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement& geom } else { - currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, "posList" ); + currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { return QgsGeometry(); @@ -537,13 +537,13 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement& geom } else { - QDomNodeList lineStringList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "LineString" ); + QDomNodeList lineStringList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LineString" ) ); if ( !lineStringList.isEmpty() ) //mapserver { for ( int i = 0; i < lineStringList.size(); ++i ) { currentLineStringElement = lineStringList.at( i ).toElement(); - currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + currentCoordList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( !currentCoordList.isEmpty() ) { QgsPolyline currentPointList; @@ -556,7 +556,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiLineString( const QDomElement& geom } else { - currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, "posList" ); + currentPosList = currentLineStringElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { return QgsGeometry(); @@ -652,13 +652,13 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr QDomNodeList currentCoordinateList; QDomNodeList currentPosList; - QDomNodeList polygonMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, "polygonMember" ); + QDomNodeList polygonMemberList = geometryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "polygonMember" ) ); QgsPolygon currentPolygonList; for ( int i = 0; i < polygonMemberList.size(); ++i ) { currentPolygonList.resize( 0 ); // preserve capacity - don't use clear currentPolygonMemberElement = polygonMemberList.at( i ).toElement(); - polygonList = currentPolygonMemberElement.elementsByTagNameNS( GML_NAMESPACE, "Polygon" ); + polygonList = currentPolygonMemberElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "Polygon" ) ); if ( polygonList.size() < 1 ) { continue; @@ -666,19 +666,19 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr currentPolygonElement = polygonList.at( 0 ).toElement(); //find exterior ring - outerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, "outerBoundaryIs" ); + outerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "outerBoundaryIs" ) ); if ( !outerBoundaryList.isEmpty() ) { currentOuterBoundaryElement = outerBoundaryList.at( 0 ).toElement(); QgsPolyline ringCoordinates; - linearRingNodeList = currentOuterBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, "LinearRing" ); + linearRingNodeList = currentOuterBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); - currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( currentCoordinateList.size() < 1 ) { continue; @@ -690,18 +690,18 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr currentPolygonList.push_back( ringCoordinates ); //find interior rings - QDomNodeList innerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, "innerBoundaryIs" ); + QDomNodeList innerBoundaryList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "innerBoundaryIs" ) ); for ( int j = 0; j < innerBoundaryList.size(); ++j ) { QgsPolyline ringCoordinates; currentInnerBoundaryElement = innerBoundaryList.at( j ).toElement(); - linearRingNodeList = currentInnerBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, "LinearRing" ); + linearRingNodeList = currentInnerBoundaryElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); - currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, "coordinates" ); + currentCoordinateList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "coordinates" ) ); if ( currentCoordinateList.size() < 1 ) { continue; @@ -716,7 +716,7 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr else { //find exterior ring - exteriorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, "exterior" ); + exteriorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "exterior" ) ); if ( exteriorList.size() < 1 ) { continue; @@ -725,13 +725,13 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr currentExteriorElement = exteriorList.at( 0 ).toElement(); QgsPolyline ringPositions; - linearRingNodeList = currentExteriorElement.elementsByTagNameNS( GML_NAMESPACE, "LinearRing" ); + linearRingNodeList = currentExteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); - currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, "posList" ); + currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { continue; @@ -743,18 +743,18 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr currentPolygonList.push_back( ringPositions ); //find interior rings - QDomNodeList interiorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, "interior" ); + QDomNodeList interiorList = currentPolygonElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "interior" ) ); for ( int j = 0; j < interiorList.size(); ++j ) { QgsPolyline ringPositions; currentInteriorElement = interiorList.at( j ).toElement(); - linearRingNodeList = currentInteriorElement.elementsByTagNameNS( GML_NAMESPACE, "LinearRing" ); + linearRingNodeList = currentInteriorElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "LinearRing" ) ); if ( linearRingNodeList.size() < 1 ) { continue; } currentLinearRingElement = linearRingNodeList.at( 0 ).toElement(); - currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, "posList" ); + currentPosList = currentLinearRingElement.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "posList" ) ); if ( currentPosList.size() < 1 ) { continue; @@ -836,19 +836,19 @@ QgsGeometry QgsOgcUtils::geometryFromGMLMultiPolygon( const QDomElement& geometr bool QgsOgcUtils::readGMLCoordinates( QgsPolyline &coords, const QDomElement &elem ) { - QString coordSeparator = ","; - QString tupelSeparator = " "; + QString coordSeparator = QStringLiteral( "," ); + QString tupelSeparator = QStringLiteral( " " ); //"decimal" has to be "." coords.clear(); - if ( elem.hasAttribute( "cs" ) ) + if ( elem.hasAttribute( QStringLiteral( "cs" ) ) ) { - coordSeparator = elem.attribute( "cs" ); + coordSeparator = elem.attribute( QStringLiteral( "cs" ) ); } - if ( elem.hasAttribute( "ts" ) ) + if ( elem.hasAttribute( QStringLiteral( "ts" ) ) ) { - tupelSeparator = elem.attribute( "ts" ); + tupelSeparator = elem.attribute( QStringLiteral( "ts" ) ); } QStringList tupels = elem.text().split( tupelSeparator, QString::SkipEmptyParts ); @@ -884,19 +884,19 @@ QgsRectangle QgsOgcUtils::rectangleFromGMLBox( const QDomNode& boxNode ) QgsRectangle rect; QDomElement boxElem = boxNode.toElement(); - if ( boxElem.tagName() != "Box" ) + if ( boxElem.tagName() != QLatin1String( "Box" ) ) return rect; QDomElement bElem = boxElem.firstChild().toElement(); - QString coordSeparator = ","; - QString tupelSeparator = " "; - if ( bElem.hasAttribute( "cs" ) ) + QString coordSeparator = QStringLiteral( "," ); + QString tupelSeparator = QStringLiteral( " " ); + if ( bElem.hasAttribute( QStringLiteral( "cs" ) ) ) { - coordSeparator = bElem.attribute( "cs" ); + coordSeparator = bElem.attribute( QStringLiteral( "cs" ) ); } - if ( bElem.hasAttribute( "ts" ) ) + if ( bElem.hasAttribute( QStringLiteral( "ts" ) ) ) { - tupelSeparator = bElem.attribute( "ts" ); + tupelSeparator = bElem.attribute( QStringLiteral( "ts" ) ); } QString bString = bElem.text(); @@ -925,17 +925,17 @@ bool QgsOgcUtils::readGMLPositions( QgsPolyline &coords, const QDomElement &elem int posSize = pos.size(); int srsDimension = 2; - if ( elem.hasAttribute( "srsDimension" ) ) + if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { - srsDimension = elem.attribute( "srsDimension" ).toInt( &conversionSuccess ); + srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } - else if ( elem.hasAttribute( "dimension" ) ) + else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { - srsDimension = elem.attribute( "dimension" ).toInt( &conversionSuccess ); + srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; @@ -965,14 +965,14 @@ QgsRectangle QgsOgcUtils::rectangleFromGMLEnvelope( const QDomNode& envelopeNode QgsRectangle rect; QDomElement envelopeElem = envelopeNode.toElement(); - if ( envelopeElem.tagName() != "Envelope" ) + if ( envelopeElem.tagName() != QLatin1String( "Envelope" ) ) return rect; - QDomNodeList lowerCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, "lowerCorner" ); + QDomNodeList lowerCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "lowerCorner" ) ); if ( lowerCornerList.size() < 1 ) return rect; - QDomNodeList upperCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, "upperCorner" ); + QDomNodeList upperCornerList = envelopeElem.elementsByTagNameNS( GML_NAMESPACE, QStringLiteral( "upperCorner" ) ); if ( upperCornerList.size() < 1 ) return rect; @@ -980,17 +980,17 @@ QgsRectangle QgsOgcUtils::rectangleFromGMLEnvelope( const QDomNode& envelopeNode int srsDimension = 2; QDomElement elem = lowerCornerList.at( 0 ).toElement(); - if ( elem.hasAttribute( "srsDimension" ) ) + if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { - srsDimension = elem.attribute( "srsDimension" ).toInt( &conversionSuccess ); + srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } - else if ( elem.hasAttribute( "dimension" ) ) + else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { - srsDimension = elem.attribute( "dimension" ).toInt( &conversionSuccess ); + srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; @@ -1006,17 +1006,17 @@ QgsRectangle QgsOgcUtils::rectangleFromGMLEnvelope( const QDomNode& envelopeNode return rect; elem = upperCornerList.at( 0 ).toElement(); - if ( elem.hasAttribute( "srsDimension" ) ) + if ( elem.hasAttribute( QStringLiteral( "srsDimension" ) ) ) { - srsDimension = elem.attribute( "srsDimension" ).toInt( &conversionSuccess ); + srsDimension = elem.attribute( QStringLiteral( "srsDimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; } } - else if ( elem.hasAttribute( "dimension" ) ) + else if ( elem.hasAttribute( QStringLiteral( "dimension" ) ) ) { - srsDimension = elem.attribute( "dimension" ).toInt( &conversionSuccess ); + srsDimension = elem.attribute( QStringLiteral( "dimension" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { srsDimension = 2; @@ -1054,14 +1054,14 @@ QDomElement QgsOgcUtils::rectangleToGMLBox( QgsRectangle* box, QDomDocument& doc return QDomElement(); } - QDomElement boxElem = doc.createElement( "gml:Box" ); + QDomElement boxElem = doc.createElement( QStringLiteral( "gml:Box" ) ); if ( !srsName.isEmpty() ) { - boxElem.setAttribute( "srsName", srsName ); + boxElem.setAttribute( QStringLiteral( "srsName" ), srsName ); } - QDomElement coordElem = doc.createElement( "gml:coordinates" ); - coordElem.setAttribute( "cs", "," ); - coordElem.setAttribute( "ts", " " ); + QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); + coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) ); + coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) ); QString coordString; coordString += qgsDoubleToString( invertAxisOrientation ? box->yMinimum() : box->xMinimum(), precision ); @@ -1094,14 +1094,14 @@ QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle* env, QDomDocument return QDomElement(); } - QDomElement envElem = doc.createElement( "gml:Envelope" ); + QDomElement envElem = doc.createElement( QStringLiteral( "gml:Envelope" ) ); if ( !srsName.isEmpty() ) { - envElem.setAttribute( "srsName", srsName ); + envElem.setAttribute( QStringLiteral( "srsName" ), srsName ); } QString posList; - QDomElement lowerCornerElem = doc.createElement( "gml:lowerCorner" ); + QDomElement lowerCornerElem = doc.createElement( QStringLiteral( "gml:lowerCorner" ) ); posList = qgsDoubleToString( invertAxisOrientation ? env->yMinimum() : env->xMinimum(), precision ); posList += ' '; posList += qgsDoubleToString( invertAxisOrientation ? env->xMinimum() : env->yMinimum(), precision ); @@ -1109,7 +1109,7 @@ QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle* env, QDomDocument lowerCornerElem.appendChild( lowerCornerText ); envElem.appendChild( lowerCornerElem ); - QDomElement upperCornerElem = doc.createElement( "gml:upperCorner" ); + QDomElement upperCornerElem = doc.createElement( QStringLiteral( "gml:upperCorner" ) ); posList = qgsDoubleToString( invertAxisOrientation ? env->yMaximum() : env->xMaximum(), precision ); posList += ' '; posList += qgsDoubleToString( invertAxisOrientation ? env->xMaximum() : env->yMaximum(), precision ); @@ -1122,7 +1122,7 @@ QDomElement QgsOgcUtils::rectangleToGMLEnvelope( QgsRectangle* env, QDomDocument QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocument& doc, const QString& format, int precision ) { - return geometryToGML( geometry, doc, ( format == "GML2" ) ? GML_2_1_2 : GML_3_2_1, QString(), false, QString(), precision ); + return geometryToGML( geometry, doc, ( format == QLatin1String( "GML2" ) ) ? GML_2_1_2 : GML_3_2_1, QString(), false, QString(), precision ); } QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocument& doc, @@ -1136,9 +1136,9 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen return QDomElement(); // coordinate separator - QString cs = ","; + QString cs = QStringLiteral( "," ); // tupel separator - QString ts = " "; + QString ts = QStringLiteral( " " ); // coord element tagname QDomElement baseCoordElem; @@ -1164,20 +1164,20 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen case QgsWkbTypes::Point: case QgsWkbTypes::MultiPoint25D: case QgsWkbTypes::MultiPoint: - baseCoordElem = doc.createElement( "gml:pos" ); + baseCoordElem = doc.createElement( QStringLiteral( "gml:pos" ) ); break; default: - baseCoordElem = doc.createElement( "gml:posList" ); + baseCoordElem = doc.createElement( QStringLiteral( "gml:posList" ) ); break; } - baseCoordElem.setAttribute( "srsDimension", "2" ); + baseCoordElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) ); cs = ' '; } else { - baseCoordElem = doc.createElement( "gml:coordinates" ); - baseCoordElem.setAttribute( "cs", cs ); - baseCoordElem.setAttribute( "ts", ts ); + baseCoordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); + baseCoordElem.setAttribute( QStringLiteral( "cs" ), cs ); + baseCoordElem.setAttribute( QStringLiteral( "ts" ), ts ); } try @@ -1187,11 +1187,11 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen case QgsWkbTypes::Point25D: case QgsWkbTypes::Point: { - QDomElement pointElem = doc.createElement( "gml:Point" ); + QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - pointElem.setAttribute( "gml:id", gmlIdBase ); + pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) - pointElem.setAttribute( "srsName", srsName ); + pointElem.setAttribute( QStringLiteral( "srsName" ), srsName ); QDomElement coordElem = baseCoordElem.cloneNode().toElement(); double x, y; @@ -1212,21 +1212,21 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen FALLTHROUGH; case QgsWkbTypes::MultiPoint: { - QDomElement multiPointElem = doc.createElement( "gml:MultiPoint" ); + QDomElement multiPointElem = doc.createElement( QStringLiteral( "gml:MultiPoint" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - multiPointElem.setAttribute( "gml:id", gmlIdBase ); + multiPointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) - multiPointElem.setAttribute( "srsName", srsName ); + multiPointElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int nPoints; wkbPtr >> nPoints; for ( int idx = 0; idx < nPoints; ++idx ) { - QDomElement pointMemberElem = doc.createElement( "gml:pointMember" ); - QDomElement pointElem = doc.createElement( "gml:Point" ); + QDomElement pointMemberElem = doc.createElement( QStringLiteral( "gml:pointMember" ) ); + QDomElement pointElem = doc.createElement( QStringLiteral( "gml:Point" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - pointElem.setAttribute( "gml:id", gmlIdBase + QString( ".%1" ).arg( idx + 1 ) ); + pointElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( idx + 1 ) ); QDomElement coordElem = baseCoordElem.cloneNode().toElement(); wkbPtr.readHeader(); @@ -1256,11 +1256,11 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen FALLTHROUGH; case QgsWkbTypes::LineString: { - QDomElement lineStringElem = doc.createElement( "gml:LineString" ); + QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - lineStringElem.setAttribute( "gml:id", gmlIdBase ); + lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) - lineStringElem.setAttribute( "srsName", srsName ); + lineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName ); // get number of points in the line int nPoints; @@ -1298,21 +1298,21 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen FALLTHROUGH; case QgsWkbTypes::MultiLineString: { - QDomElement multiLineStringElem = doc.createElement( "gml:MultiLineString" ); + QDomElement multiLineStringElem = doc.createElement( QStringLiteral( "gml:MultiLineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - multiLineStringElem.setAttribute( "gml:id", gmlIdBase ); + multiLineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) - multiLineStringElem.setAttribute( "srsName", srsName ); + multiLineStringElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int nLines; wkbPtr >> nLines; for ( int jdx = 0; jdx < nLines; jdx++ ) { - QDomElement lineStringMemberElem = doc.createElement( "gml:lineStringMember" ); - QDomElement lineStringElem = doc.createElement( "gml:LineString" ); + QDomElement lineStringMemberElem = doc.createElement( QStringLiteral( "gml:lineStringMember" ) ); + QDomElement lineStringElem = doc.createElement( QStringLiteral( "gml:LineString" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - lineStringElem.setAttribute( "gml:id", gmlIdBase + QString( ".%1" ).arg( jdx + 1 ) ); + lineStringElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( jdx + 1 ) ); wkbPtr.readHeader(); @@ -1355,11 +1355,11 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen FALLTHROUGH; case QgsWkbTypes::Polygon: { - QDomElement polygonElem = doc.createElement( "gml:Polygon" ); + QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - polygonElem.setAttribute( "gml:id", gmlIdBase ); + polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) - polygonElem.setAttribute( "srsName", srsName ); + polygonElem.setAttribute( QStringLiteral( "srsName" ), srsName ); // get number of rings in the polygon int numRings; @@ -1378,7 +1378,7 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior"; } QDomElement boundaryElem = doc.createElement( boundaryName ); - QDomElement ringElem = doc.createElement( "gml:LinearRing" ); + QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) ); // get number of points in the ring int nPoints; wkbPtr >> nPoints; @@ -1420,21 +1420,21 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen FALLTHROUGH; case QgsWkbTypes::MultiPolygon: { - QDomElement multiPolygonElem = doc.createElement( "gml:MultiPolygon" ); + QDomElement multiPolygonElem = doc.createElement( QStringLiteral( "gml:MultiPolygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - multiPolygonElem.setAttribute( "gml:id", gmlIdBase ); + multiPolygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase ); if ( !srsName.isEmpty() ) - multiPolygonElem.setAttribute( "srsName", srsName ); + multiPolygonElem.setAttribute( QStringLiteral( "srsName" ), srsName ); int numPolygons; wkbPtr >> numPolygons; for ( int kdx = 0; kdx < numPolygons; kdx++ ) { - QDomElement polygonMemberElem = doc.createElement( "gml:polygonMember" ); - QDomElement polygonElem = doc.createElement( "gml:Polygon" ); + QDomElement polygonMemberElem = doc.createElement( QStringLiteral( "gml:polygonMember" ) ); + QDomElement polygonElem = doc.createElement( QStringLiteral( "gml:Polygon" ) ); if ( gmlVersion == GML_3_2_1 && !gmlIdBase.isEmpty() ) - polygonElem.setAttribute( "gml:id", gmlIdBase + QString( ".%1" ).arg( kdx + 1 ) ); + polygonElem.setAttribute( QStringLiteral( "gml:id" ), gmlIdBase + QStringLiteral( ".%1" ).arg( kdx + 1 ) ); wkbPtr.readHeader(); @@ -1449,7 +1449,7 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen boundaryName = ( gmlVersion == GML_2_1_2 ) ? "gml:innerBoundaryIs" : "gml:interior"; } QDomElement boundaryElem = doc.createElement( boundaryName ); - QDomElement ringElem = doc.createElement( "gml:LinearRing" ); + QDomElement ringElem = doc.createElement( QStringLiteral( "gml:LinearRing" ) ); int nPoints; wkbPtr >> nPoints; @@ -1500,14 +1500,14 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry *geometry, QDomDocument &doc, int precision ) { - return geometryToGML( geometry, doc, "GML2", precision ); + return geometryToGML( geometry, doc, QStringLiteral( "GML2" ), precision ); } QDomElement QgsOgcUtils::createGMLCoordinates( const QgsPolyline &points, QDomDocument &doc ) { - QDomElement coordElem = doc.createElement( "gml:coordinates" ); - coordElem.setAttribute( "cs", "," ); - coordElem.setAttribute( "ts", " " ); + QDomElement coordElem = doc.createElement( QStringLiteral( "gml:coordinates" ) ); + coordElem.setAttribute( QStringLiteral( "cs" ), QStringLiteral( "," ) ); + coordElem.setAttribute( QStringLiteral( "ts" ), QStringLiteral( " " ) ); QString coordString; QVector::const_iterator pointIt = points.constBegin(); @@ -1529,10 +1529,10 @@ QDomElement QgsOgcUtils::createGMLCoordinates( const QgsPolyline &points, QDomDo QDomElement QgsOgcUtils::createGMLPositions( const QgsPolyline &points, QDomDocument& doc ) { - QDomElement posElem = doc.createElement( "gml:pos" ); + QDomElement posElem = doc.createElement( QStringLiteral( "gml:pos" ) ); if ( points.size() > 1 ) - posElem = doc.createElement( "gml:posList" ); - posElem.setAttribute( "srsDimension", "2" ); + posElem = doc.createElement( QStringLiteral( "gml:posList" ) ); + posElem.setAttribute( QStringLiteral( "srsDimension" ), QStringLiteral( "2" ) ); QString coordString; QVector::const_iterator pointIt = points.constBegin(); @@ -1566,18 +1566,18 @@ QColor QgsOgcUtils::colorFromOgcFill( const QDomElement& fillElement ) QString cssName; QString elemText; QColor color; - QDomElement cssElem = fillElement.firstChildElement( "CssParameter" ); + QDomElement cssElem = fillElement.firstChildElement( QStringLiteral( "CssParameter" ) ); while ( !cssElem.isNull() ) { - cssName = cssElem.attribute( "name", "not_found" ); - if ( cssName != "not_found" ) + cssName = cssElem.attribute( QStringLiteral( "name" ), QStringLiteral( "not_found" ) ); + if ( cssName != QLatin1String( "not_found" ) ) { elemText = cssElem.text(); - if ( cssName == "fill" ) + if ( cssName == QLatin1String( "fill" ) ) { color.setNamedColor( elemText ); } - else if ( cssName == "fill-opacity" ) + else if ( cssName == QLatin1String( "fill-opacity" ) ) { bool ok; double opacity = elemText.toDouble( &ok ); @@ -1588,7 +1588,7 @@ QColor QgsOgcUtils::colorFromOgcFill( const QDomElement& fillElement ) } } - cssElem = cssElem.nextSiblingElement( "CssParameter" ); + cssElem = cssElem.nextSiblingElement( QStringLiteral( "CssParameter" ) ); } return color; @@ -1640,21 +1640,21 @@ static const QMap& binaryOperatorsTagNamesMap() if ( binOps.isEmpty() ) { // logical - binOps.insert( "Or", QgsExpression::boOr ); - binOps.insert( "And", QgsExpression::boAnd ); + binOps.insert( QStringLiteral( "Or" ), QgsExpression::boOr ); + binOps.insert( QStringLiteral( "And" ), QgsExpression::boAnd ); // comparison - binOps.insert( "PropertyIsEqualTo", QgsExpression::boEQ ); - binOps.insert( "PropertyIsNotEqualTo", QgsExpression::boNE ); - binOps.insert( "PropertyIsLessThanOrEqualTo", QgsExpression::boLE ); - binOps.insert( "PropertyIsGreaterThanOrEqualTo", QgsExpression::boGE ); - binOps.insert( "PropertyIsLessThan", QgsExpression::boLT ); - binOps.insert( "PropertyIsGreaterThan", QgsExpression::boGT ); - binOps.insert( "PropertyIsLike", QgsExpression::boLike ); + binOps.insert( QStringLiteral( "PropertyIsEqualTo" ), QgsExpression::boEQ ); + binOps.insert( QStringLiteral( "PropertyIsNotEqualTo" ), QgsExpression::boNE ); + binOps.insert( QStringLiteral( "PropertyIsLessThanOrEqualTo" ), QgsExpression::boLE ); + binOps.insert( QStringLiteral( "PropertyIsGreaterThanOrEqualTo" ), QgsExpression::boGE ); + binOps.insert( QStringLiteral( "PropertyIsLessThan" ), QgsExpression::boLT ); + binOps.insert( QStringLiteral( "PropertyIsGreaterThan" ), QgsExpression::boGT ); + binOps.insert( QStringLiteral( "PropertyIsLike" ), QgsExpression::boLike ); // arithmetics - binOps.insert( "Add", QgsExpression::boPlus ); - binOps.insert( "Sub", QgsExpression::boMinus ); - binOps.insert( "Mul", QgsExpression::boMul ); - binOps.insert( "Div", QgsExpression::boDiv ); + binOps.insert( QStringLiteral( "Add" ), QgsExpression::boPlus ); + binOps.insert( QStringLiteral( "Sub" ), QgsExpression::boMinus ); + binOps.insert( QStringLiteral( "Mul" ), QgsExpression::boMul ); + binOps.insert( QStringLiteral( "Div" ), QgsExpression::boDiv ); } return binOps; } @@ -1669,7 +1669,7 @@ static QString binaryOperatorToTagName( QgsExpression::BinaryOperator op ) { if ( op == QgsExpression::boILike ) { - return "PropertyIsLike"; + return QStringLiteral( "PropertyIsLike" ); } return binaryOperatorsTagNamesMap().key( op, QString() ); } @@ -1685,8 +1685,8 @@ static bool isSpatialOperator( const QString& tagName ) static QStringList spatialOps; if ( spatialOps.isEmpty() ) { - spatialOps << "BBOX" << "Intersects" << "Contains" << "Crosses" << "Equals" - << "Disjoint" << "Overlaps" << "Touches" << "Within"; + spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" ) + << QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" ); } return spatialOps.contains( tagName ); @@ -1713,27 +1713,27 @@ QgsExpression::Node* QgsOgcUtils::nodeFromOgcFilter( QDomElement &element, QStri // check for other OGC operators, convert them to expressions - if ( element.tagName() == "Not" ) + if ( element.tagName() == QLatin1String( "Not" ) ) { return nodeNotFromOgcFilter( element, errorMessage ); } - else if ( element.tagName() == "PropertyIsNull" ) + else if ( element.tagName() == QLatin1String( "PropertyIsNull" ) ) { return nodePropertyIsNullFromOgcFilter( element, errorMessage ); } - else if ( element.tagName() == "Literal" ) + else if ( element.tagName() == QLatin1String( "Literal" ) ) { return nodeLiteralFromOgcFilter( element, errorMessage ); } - else if ( element.tagName() == "Function" ) + else if ( element.tagName() == QLatin1String( "Function" ) ) { return nodeFunctionFromOgcFilter( element, errorMessage ); } - else if ( element.tagName() == "PropertyName" ) + else if ( element.tagName() == QLatin1String( "PropertyName" ) ) { return nodeColumnRefFromOgcFilter( element, errorMessage ); } - else if ( element.tagName() == "PropertyIsBetween" ) + else if ( element.tagName() == QLatin1String( "PropertyIsBetween" ) ) { return nodeIsBetweenFromOgcFilter( element, errorMessage ); } @@ -1757,7 +1757,7 @@ QgsExpression::NodeBinaryOperator* QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( return nullptr; } - if ( op == QgsExpression::boLike && element.hasAttribute( "matchCase" ) && element.attribute( "matchCase" ) == "false" ) + if ( op == QgsExpression::boLike && element.hasAttribute( QStringLiteral( "matchCase" ) ) && element.attribute( QStringLiteral( "matchCase" ) ) == QLatin1String( "false" ) ) { op = QgsExpression::boILike; } @@ -1785,55 +1785,55 @@ QgsExpression::NodeBinaryOperator* QgsOgcUtils::nodeBinaryOperatorFromOgcFilter( if ( op == QgsExpression::boLike || op == QgsExpression::boILike ) { QString wildCard; - if ( element.hasAttribute( "wildCard" ) ) + if ( element.hasAttribute( QStringLiteral( "wildCard" ) ) ) { - wildCard = element.attribute( "wildCard" ); + wildCard = element.attribute( QStringLiteral( "wildCard" ) ); } QString singleChar; - if ( element.hasAttribute( "singleChar" ) ) + if ( element.hasAttribute( QStringLiteral( "singleChar" ) ) ) { - singleChar = element.attribute( "singleChar" ); + singleChar = element.attribute( QStringLiteral( "singleChar" ) ); } - QString escape = "\\"; - if ( element.hasAttribute( "escape" ) ) + QString escape = QStringLiteral( "\\" ); + if ( element.hasAttribute( QStringLiteral( "escape" ) ) ) { - escape = element.attribute( "escape" ); + escape = element.attribute( QStringLiteral( "escape" ) ); } // replace QString oprValue = static_cast( opRight )->value().toString(); - if ( !wildCard.isEmpty() && wildCard != "%" ) + if ( !wildCard.isEmpty() && wildCard != QLatin1String( "%" ) ) { - oprValue.replace( '%', "\\%" ); + oprValue.replace( '%', QLatin1String( "\\%" ) ); if ( oprValue.startsWith( wildCard ) ) { - oprValue.replace( 0, 1, "%" ); + oprValue.replace( 0, 1, QStringLiteral( "%" ) ); } QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( wildCard ) + ")" ); int pos = 0; while (( pos = rx.indexIn( oprValue, pos ) ) != -1 ) { - oprValue.replace( pos + 1, 1, "%" ); + oprValue.replace( pos + 1, 1, QStringLiteral( "%" ) ); pos += 1; } oprValue.replace( escape + wildCard, wildCard ); } - if ( !singleChar.isEmpty() && singleChar != "_" ) + if ( !singleChar.isEmpty() && singleChar != QLatin1String( "_" ) ) { - oprValue.replace( '_', "\\_" ); + oprValue.replace( '_', QLatin1String( "\\_" ) ); if ( oprValue.startsWith( singleChar ) ) { - oprValue.replace( 0, 1, "_" ); + oprValue.replace( 0, 1, QStringLiteral( "_" ) ); } QRegExp rx( "[^" + QRegExp::escape( escape ) + "](" + QRegExp::escape( singleChar ) + ")" ); int pos = 0; while (( pos = rx.indexIn( oprValue, pos ) ) != -1 ) { - oprValue.replace( pos + 1, 1, "_" ); + oprValue.replace( pos + 1, 1, QStringLiteral( "_" ) ); pos += 1; } oprValue.replace( escape + singleChar, singleChar ); } - if ( !escape.isEmpty() && escape != "\\" ) + if ( !escape.isEmpty() && escape != QLatin1String( "\\" ) ) { oprValue.replace( escape + escape, escape ); } @@ -1869,7 +1869,7 @@ QgsExpression::NodeFunction* QgsOgcUtils::nodeSpatialOperatorFromOgcFilter( QDom QString gml2Str; while ( !childElem.isNull() && gml2Str.isEmpty() ) { - if ( childElem.tagName() != "PropertyName" ) + if ( childElem.tagName() != QLatin1String( "PropertyName" ) ) { QTextStream gml2Stream( &gml2Str ); childElem.save( gml2Stream, 0 ); @@ -1888,8 +1888,8 @@ QgsExpression::NodeFunction* QgsOgcUtils::nodeSpatialOperatorFromOgcFilter( QDom } QgsExpression::NodeList *opArgs = new QgsExpression::NodeList(); - opArgs->append( new QgsExpression::NodeFunction( QgsExpression::functionIndex( "$geometry" ), new QgsExpression::NodeList() ) ); - opArgs->append( new QgsExpression::NodeFunction( QgsExpression::functionIndex( "geomFromGML" ), gml2Args ) ); + opArgs->append( new QgsExpression::NodeFunction( QgsExpression::functionIndex( QStringLiteral( "$geometry" ) ), new QgsExpression::NodeList() ) ); + opArgs->append( new QgsExpression::NodeFunction( QgsExpression::functionIndex( QStringLiteral( "geomFromGML" ) ), gml2Args ) ); return new QgsExpression::NodeFunction( opIdx, opArgs ); } @@ -1897,7 +1897,7 @@ QgsExpression::NodeFunction* QgsOgcUtils::nodeSpatialOperatorFromOgcFilter( QDom QgsExpression::NodeUnaryOperator* QgsOgcUtils::nodeNotFromOgcFilter( QDomElement &element, QString &errorMessage ) { - if ( element.tagName() != "Not" ) + if ( element.tagName() != QLatin1String( "Not" ) ) return nullptr; QDomElement operandElem = element.firstChildElement(); @@ -1915,7 +1915,7 @@ QgsExpression::NodeUnaryOperator* QgsOgcUtils::nodeNotFromOgcFilter( QDomElement QgsExpression::NodeFunction* QgsOgcUtils::nodeFunctionFromOgcFilter( QDomElement &element, QString &errorMessage ) { - if ( element.isNull() || element.tagName() != "Function" ) + if ( element.isNull() || element.tagName() != QLatin1String( "Function" ) ) { errorMessage = QObject::tr( "ogc:Function expected, got %1" ).arg( element.tagName() ); return nullptr; @@ -1925,7 +1925,7 @@ QgsExpression::NodeFunction* QgsOgcUtils::nodeFunctionFromOgcFilter( QDomElement { QgsExpression::Function* funcDef = QgsExpression::Functions()[i]; - if ( element.attribute( "name" ) != funcDef->name() ) + if ( element.attribute( QStringLiteral( "name" ) ) != funcDef->name() ) continue; QgsExpression::NodeList *args = new QgsExpression::NodeList(); @@ -1954,7 +1954,7 @@ QgsExpression::NodeFunction* QgsOgcUtils::nodeFunctionFromOgcFilter( QDomElement QgsExpression::Node* QgsOgcUtils::nodeLiteralFromOgcFilter( QDomElement &element, QString &errorMessage ) { - if ( element.isNull() || element.tagName() != "Literal" ) + if ( element.isNull() || element.tagName() != QLatin1String( "Literal" ) ) { errorMessage = QObject::tr( "ogc:Literal expected, got %1" ).arg( element.tagName() ); return nullptr; @@ -2021,7 +2021,7 @@ QgsExpression::Node* QgsOgcUtils::nodeLiteralFromOgcFilter( QDomElement &element QgsExpression::NodeColumnRef* QgsOgcUtils::nodeColumnRefFromOgcFilter( QDomElement &element, QString &errorMessage ) { - if ( element.isNull() || element.tagName() != "PropertyName" ) + if ( element.isNull() || element.tagName() != QLatin1String( "PropertyName" ) ) { errorMessage = QObject::tr( "ogc:PropertyName expected, got %1" ).arg( element.tagName() ); return nullptr; @@ -2040,12 +2040,12 @@ QgsExpression::Node* QgsOgcUtils::nodeIsBetweenFromOgcFilter( QDomElement& eleme QDomElement operandElem = element.firstChildElement(); while ( !operandElem.isNull() ) { - if ( operandElem.tagName() == "LowerBoundary" ) + if ( operandElem.tagName() == QLatin1String( "LowerBoundary" ) ) { QDomElement lowerBoundElem = operandElem.firstChildElement(); lowerBound = nodeFromOgcFilter( lowerBoundElem, errorMessage ); } - else if ( operandElem.tagName() == "UpperBoundary" ) + else if ( operandElem.tagName() == QLatin1String( "UpperBoundary" ) ) { QDomElement upperBoundElem = operandElem.firstChildElement(); upperBound = nodeFromOgcFilter( upperBoundElem, errorMessage ); @@ -2089,7 +2089,7 @@ QgsExpression::Node* QgsOgcUtils::nodeIsBetweenFromOgcFilter( QDomElement& eleme QgsExpression::NodeBinaryOperator* QgsOgcUtils::nodePropertyIsNullFromOgcFilter( QDomElement& element, QString& errorMessage ) { // convert ogc:PropertyIsNull to IS operator with NULL right operand - if ( element.tagName() != "PropertyIsNull" ) + if ( element.tagName() != QLatin1String( "PropertyIsNull" ) ) { return nullptr; } @@ -2110,13 +2110,13 @@ QgsExpression::NodeBinaryOperator* QgsOgcUtils::nodePropertyIsNullFromOgcFilter( QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression& exp, QDomDocument& doc, QString* errorMessage ) { return expressionToOgcFilter( exp, doc, GML_2_1_2, FILTER_OGC_1_0, - "geometry", QString(), false, false, errorMessage ); + QStringLiteral( "geometry" ), QString(), false, false, errorMessage ); } QDomElement QgsOgcUtils::expressionToOgcExpression( const QgsExpression& exp, QDomDocument& doc, QString* errorMessage ) { return expressionToOgcExpression( exp, doc, GML_2_1_2, FILTER_OGC_1_0, - "geometry", QString(), false, false, errorMessage ); + QStringLiteral( "geometry" ), QString(), false, false, errorMessage ); } QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression& exp, @@ -2141,11 +2141,11 @@ QDomElement QgsOgcUtils::expressionToOgcFilter( const QgsExpression& exp, QDomElement filterElem = ( filterVersion == FILTER_FES_2_0 ) ? - doc.createElementNS( FES_NAMESPACE, "fes:Filter" ) : - doc.createElementNS( OGC_NAMESPACE, "ogc:Filter" ); + doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) : + doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) ); if ( utils.GMLNamespaceUsed() ) { - QDomAttr attr = doc.createAttribute( "xmlns:gml" ); + QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) ); if ( gmlVersion == GML_3_2_1 ) attr.setValue( GML32_NAMESPACE ); else @@ -2219,11 +2219,11 @@ QDomElement QgsOgcUtils::SQLStatementToOgcFilter( const QgsSQLStatement& stateme QDomElement filterElem = ( filterVersion == FILTER_FES_2_0 ) ? - doc.createElementNS( FES_NAMESPACE, "fes:Filter" ) : - doc.createElementNS( OGC_NAMESPACE, "ogc:Filter" ); + doc.createElementNS( FES_NAMESPACE, QStringLiteral( "fes:Filter" ) ) : + doc.createElementNS( OGC_NAMESPACE, QStringLiteral( "ogc:Filter" ) ); if ( utils.GMLNamespaceUsed() ) { - QDomAttr attr = doc.createAttribute( "xmlns:gml" ); + QDomAttr attr = doc.createAttribute( QStringLiteral( "xmlns:gml" ) ); if ( gmlVersion == GML_3_2_1 ) attr.setValue( GML32_NAMESPACE ); else @@ -2355,15 +2355,15 @@ QDomElement QgsOgcUtilsExprToFilter::expressionBinaryOperatorToOgcFilter( const if ( op == QgsExpression::boLike || op == QgsExpression::boILike ) { if ( op == QgsExpression::boILike ) - boElem.setAttribute( "matchCase", "false" ); + boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) ); // setup wildCards to - boElem.setAttribute( "wildCard", "%" ); - boElem.setAttribute( "singleChar", "_" ); + boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) ); + boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) - boElem.setAttribute( "escape", "\\" ); + boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) ); else - boElem.setAttribute( "escapeChar", "\\" ); + boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) ); } boElem.appendChild( leftElem ); @@ -2443,13 +2443,13 @@ static QMap binarySpatialOpsMap() static QMap binSpatialOps; if ( binSpatialOps.isEmpty() ) { - binSpatialOps.insert( "disjoint", "Disjoint" ); - binSpatialOps.insert( "intersects", "Intersects" ); - binSpatialOps.insert( "touches", "Touches" ); - binSpatialOps.insert( "crosses", "Crosses" ); - binSpatialOps.insert( "contains", "Contains" ); - binSpatialOps.insert( "overlaps", "Overlaps" ); - binSpatialOps.insert( "within", "Within" ); + binSpatialOps.insert( QStringLiteral( "disjoint" ), QStringLiteral( "Disjoint" ) ); + binSpatialOps.insert( QStringLiteral( "intersects" ), QStringLiteral( "Intersects" ) ); + binSpatialOps.insert( QStringLiteral( "touches" ), QStringLiteral( "Touches" ) ); + binSpatialOps.insert( QStringLiteral( "crosses" ), QStringLiteral( "Crosses" ) ); + binSpatialOps.insert( QStringLiteral( "contains" ), QStringLiteral( "Contains" ) ); + binSpatialOps.insert( QStringLiteral( "overlaps" ), QStringLiteral( "Overlaps" ) ); + binSpatialOps.insert( QStringLiteral( "within" ), QStringLiteral( "Within" ) ); } return binSpatialOps; } @@ -2471,7 +2471,7 @@ static bool isGeometryColumn( const QgsExpression::Node* node ) const QgsExpression::NodeFunction* fn = static_cast( node ); QgsExpression::Function* fd = QgsExpression::Functions()[fn->fnIndex()]; - return fd->name() == "$geometry"; + return fd->name() == QLatin1String( "$geometry" ); } static QgsGeometry geometryFromConstExpr( const QgsExpression::Node* node ) @@ -2483,7 +2483,7 @@ static QgsGeometry geometryFromConstExpr( const QgsExpression::Node* node ) { const QgsExpression::NodeFunction* fnNode = static_cast( node ); QgsExpression::Function* fnDef = QgsExpression::Functions()[fnNode->fnIndex()]; - if ( fnDef->name() == "geom_from_wkt" ) + if ( fnDef->name() == QLatin1String( "geom_from_wkt" ) ) { const QList& args = fnNode->args()->list(); if ( args[0]->nodeType() == QgsExpression::ntLiteral ) @@ -2501,7 +2501,7 @@ QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExp { QgsExpression::Function* fd = QgsExpression::Functions()[node->fnIndex()]; - if ( fd->name() == "intersects_bbox" ) + if ( fd->name() == QLatin1String( "intersects_bbox" ) ) { QList argNodes = node->args()->list(); Q_ASSERT( argNodes.count() == 2 ); // binary spatial ops must have two args @@ -2559,7 +2559,7 @@ QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExp const QgsExpression::NodeFunction* otherFn = static_cast( otherNode ); QgsExpression::Function* otherFnDef = QgsExpression::Functions()[otherFn->fnIndex()]; - if ( otherFnDef->name() == "geom_from_wkt" ) + if ( otherFnDef->name() == QLatin1String( "geom_from_wkt" ) ) { QgsExpression::Node* firstFnArg = otherFn->args()->list()[0]; if ( firstFnArg->nodeType() != QgsExpression::ntLiteral ) @@ -2570,10 +2570,10 @@ QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExp QString wkt = static_cast( firstFnArg )->value().toString(); QgsGeometry geom = QgsGeometry::fromWkt( wkt ); otherGeomElem = QgsOgcUtils::geometryToGML( &geom, mDoc, mGMLVersion, mSrsName, mInvertAxisOrientation, - QString( "qgis_id_geom_%1" ).arg( mGeomId ) ); + QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) ); mGeomId ++; } - else if ( otherFnDef->name() == "geom_from_gml" ) + else if ( otherFnDef->name() == QLatin1String( "geom_from_gml" ) ) { QgsExpression::Node* firstFnArg = otherFn->args()->list()[0]; if ( firstFnArg->nodeType() != QgsExpression::ntLiteral ) @@ -2617,7 +2617,7 @@ QDomElement QgsOgcUtilsExprToFilter::expressionFunctionToOgcFilter( const QgsExp // this is somehow wrong - we are just hoping that the other side supports the same functions as we do... QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" ); - funcElem.setAttribute( "name", fd->name() ); + funcElem.setAttribute( QStringLiteral( "name" ), fd->name() ); Q_FOREACH ( QgsExpression::Node* n, node->args()->list() ) { QDomElement childElem = expressionNodeToOgcFilter( n ); @@ -2763,25 +2763,25 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: QString opText; if ( op == QgsSQLStatement::boOr ) - opText = "Or"; + opText = QStringLiteral( "Or" ); else if ( op == QgsSQLStatement::boAnd ) - opText = "And"; + opText = QStringLiteral( "And" ); else if ( op == QgsSQLStatement::boEQ ) - opText = "PropertyIsEqualTo"; + opText = QStringLiteral( "PropertyIsEqualTo" ); else if ( op == QgsSQLStatement::boNE ) - opText = "PropertyIsNotEqualTo"; + opText = QStringLiteral( "PropertyIsNotEqualTo" ); else if ( op == QgsSQLStatement::boLE ) - opText = "PropertyIsLessThanOrEqualTo"; + opText = QStringLiteral( "PropertyIsLessThanOrEqualTo" ); else if ( op == QgsSQLStatement::boGE ) - opText = "PropertyIsGreaterThanOrEqualTo"; + opText = QStringLiteral( "PropertyIsGreaterThanOrEqualTo" ); else if ( op == QgsSQLStatement::boLT ) - opText = "PropertyIsLessThan"; + opText = QStringLiteral( "PropertyIsLessThan" ); else if ( op == QgsSQLStatement::boGT ) - opText = "PropertyIsGreaterThan"; + opText = QStringLiteral( "PropertyIsGreaterThan" ); else if ( op == QgsSQLStatement::boLike ) - opText = "PropertyIsLike"; + opText = QStringLiteral( "PropertyIsLike" ); else if ( op == QgsSQLStatement::boILike ) - opText = "PropertyIsLike"; + opText = QStringLiteral( "PropertyIsLike" ); if ( opText.isEmpty() ) { @@ -2795,15 +2795,15 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: if ( op == QgsSQLStatement::boLike || op == QgsSQLStatement::boILike ) { if ( op == QgsSQLStatement::boILike ) - boElem.setAttribute( "matchCase", "false" ); + boElem.setAttribute( QStringLiteral( "matchCase" ), QStringLiteral( "false" ) ); // setup wildCards to - boElem.setAttribute( "wildCard", "%" ); - boElem.setAttribute( "singleChar", "_" ); + boElem.setAttribute( QStringLiteral( "wildCard" ), QStringLiteral( "%" ) ); + boElem.setAttribute( QStringLiteral( "singleChar" ), QStringLiteral( "_" ) ); if ( mFilterVersion == QgsOgcUtils::FILTER_OGC_1_0 ) - boElem.setAttribute( "escape", "\\" ); + boElem.setAttribute( QStringLiteral( "escape" ), QStringLiteral( "\\" ) ); else - boElem.setAttribute( "escapeChar", "\\" ); + boElem.setAttribute( QStringLiteral( "escapeChar" ), QStringLiteral( "\\" ) ); } boElem.appendChild( leftElem ); @@ -2911,11 +2911,11 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: static QString mapBinarySpatialToOgc( const QString& name ) { QString nameCompare( name ); - if ( name.size() > 3 && name.midRef( 0, 3 ).compare( "ST_", Qt::CaseInsensitive ) == 0 ) + if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QStringLiteral( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); QStringList spatialOps; - spatialOps << "BBOX" << "Intersects" << "Contains" << "Crosses" << "Equals" - << "Disjoint" << "Overlaps" << "Touches" << "Within"; + spatialOps << QStringLiteral( "BBOX" ) << QStringLiteral( "Intersects" ) << QStringLiteral( "Contains" ) << QStringLiteral( "Crosses" ) << QStringLiteral( "Equals" ) + << QStringLiteral( "Disjoint" ) << QStringLiteral( "Overlaps" ) << QStringLiteral( "Touches" ) << QStringLiteral( "Within" ); Q_FOREACH ( QString op, spatialOps ) { if ( nameCompare.compare( op, Qt::CaseInsensitive ) == 0 ) @@ -2927,12 +2927,12 @@ static QString mapBinarySpatialToOgc( const QString& name ) static QString mapTernarySpatialToOgc( const QString& name ) { QString nameCompare( name ); - if ( name.size() > 3 && name.midRef( 0, 3 ).compare( "ST_", Qt::CaseInsensitive ) == 0 ) + if ( name.size() > 3 && name.midRef( 0, 3 ).compare( QStringLiteral( "ST_" ), Qt::CaseInsensitive ) == 0 ) nameCompare = name.mid( 3 ); - if ( nameCompare.compare( "DWithin", Qt::CaseInsensitive ) == 0 ) - return "DWithin"; - if ( nameCompare.compare( "Beyond", Qt::CaseInsensitive ) == 0 ) - return "Beyond"; + if ( nameCompare.compare( QLatin1String( "DWithin" ), Qt::CaseInsensitive ) == 0 ) + return QStringLiteral( "DWithin" ); + if ( nameCompare.compare( QLatin1String( "Beyond" ), Qt::CaseInsensitive ) == 0 ) + return QStringLiteral( "Beyond" ); return QString(); } @@ -2993,7 +2993,7 @@ bool QgsOgcUtilsSQLStatementToFilter::processSRSName( const QgsSQLStatement::Nod else { srsName = lit->value().toString(); - if ( srsName.startsWith( "EPSG:", Qt::CaseInsensitive ) ) + if ( srsName.startsWith( QLatin1String( "EPSG:" ), Qt::CaseInsensitive ) ) return true; } } @@ -3015,7 +3015,7 @@ bool QgsOgcUtilsSQLStatementToFilter::processSRSName( const QgsSQLStatement::Nod QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement::NodeFunction* node ) { // ST_GeometryFromText - if ( node->name().compare( "ST_GeometryFromText", Qt::CaseInsensitive ) == 0 ) + if ( node->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 ) { QList args = node->args()->list(); if ( args.size() != 1 && args.size() != 2 ) @@ -3041,7 +3041,7 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: QString wkt = static_cast( firstFnArg )->value().toString(); QgsGeometry geom = QgsGeometry::fromWkt( wkt ); QDomElement geomElem = QgsOgcUtils::geometryToGML( &geom, mDoc, mGMLVersion, srsName, axisInversion, - QString( "qgis_id_geom_%1" ).arg( mGeomId ) ); + QStringLiteral( "qgis_id_geom_%1" ).arg( mGeomId ) ); mGeomId ++; if ( geomElem.isNull() ) { @@ -3053,7 +3053,7 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: } // ST_MakeEnvelope - if ( node->name().compare( "ST_MakeEnvelope", Qt::CaseInsensitive ) == 0 ) + if ( node->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) { QList args = node->args()->list(); if ( args.size() != 4 && args.size() != 5 ) @@ -3110,7 +3110,7 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: } // ST_GeomFromGML - if ( node->name().compare( "ST_GeomFromGML", Qt::CaseInsensitive ) == 0 ) + if ( node->name().compare( QLatin1String( "ST_GeomFromGML" ), Qt::CaseInsensitive ) == 0 ) { QList args = node->args()->list(); if ( args.size() != 1 ) @@ -3153,8 +3153,8 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: for ( int i = 0; i < 2; i ++ ) { if ( args[i]->nodeType() == QgsSQLStatement::ntFunction && - ( static_cast( args[i] )->name().compare( "ST_GeometryFromText", Qt::CaseInsensitive ) == 0 || - static_cast( args[i] )->name().compare( "ST_MakeEnvelope", Qt::CaseInsensitive ) == 0 ) ) + ( static_cast( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 || + static_cast( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) ) { mCurrentSRSName = getGeometryColumnSRSName( args[1-i] ); break; @@ -3193,8 +3193,8 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: for ( int i = 0; i < 2; i ++ ) { if ( args[i]->nodeType() == QgsSQLStatement::ntFunction && - ( static_cast( args[i] )->name().compare( "ST_GeometryFromText", Qt::CaseInsensitive ) == 0 || - static_cast( args[i] )->name().compare( "ST_MakeEnvelope", Qt::CaseInsensitive ) == 0 ) ) + ( static_cast( args[i] )->name().compare( QLatin1String( "ST_GeometryFromText" ), Qt::CaseInsensitive ) == 0 || + static_cast( args[i] )->name().compare( QLatin1String( "ST_MakeEnvelope" ), Qt::CaseInsensitive ) == 0 ) ) { mCurrentSRSName = getGeometryColumnSRSName( args[1-i] ); break; @@ -3228,7 +3228,7 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: return QDomElement(); } QString distance; - QString unit( "m" ); + QString unit( QStringLiteral( "m" ) ); switch ( lit->value().type() ) { case QVariant::Int: @@ -3262,9 +3262,9 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: QDomElement distanceElem = mDoc.createElement( mFilterPrefix + ":Distance" ); if ( mFilterVersion == QgsOgcUtils::FILTER_FES_2_0 ) - distanceElem.setAttribute( "uom", unit ); + distanceElem.setAttribute( QStringLiteral( "uom" ), unit ); else - distanceElem.setAttribute( "unit", unit ); + distanceElem.setAttribute( QStringLiteral( "unit" ), unit ); distanceElem.appendChild( mDoc.createTextNode( distance ) ); funcElem.appendChild( distanceElem ); return funcElem; @@ -3272,7 +3272,7 @@ QDomElement QgsOgcUtilsSQLStatementToFilter::toOgcFilter( const QgsSQLStatement: // Other function QDomElement funcElem = mDoc.createElement( mFilterPrefix + ":Function" ); - funcElem.setAttribute( "name", node->name() ); + funcElem.setAttribute( QStringLiteral( "name" ), node->name() ); Q_FOREACH ( QgsSQLStatement::Node* n, node->args()->list() ) { QDomElement childElem = toOgcFilter( n ); diff --git a/src/core/qgsogrutils.cpp b/src/core/qgsogrutils.cpp index 3f1da65e0bef..9e5066044e95 100644 --- a/src/core/qgsogrutils.cpp +++ b/src/core/qgsogrutils.cpp @@ -241,7 +241,7 @@ QgsFeatureList QgsOgrUtils::stringToFeatureList( const QString& string, const Qg if ( string.isEmpty() ) return features; - QString randomFileName = QString( "/vsimem/%1" ).arg( QUuid::createUuid().toString() ); + QString randomFileName = QStringLiteral( "/vsimem/%1" ).arg( QUuid::createUuid().toString() ); // create memory file system object from string buffer QByteArray ba = string.toUtf8(); @@ -285,7 +285,7 @@ QgsFields QgsOgrUtils::stringToFields( const QString& string, QTextCodec* encodi if ( string.isEmpty() ) return fields; - QString randomFileName = QString( "/vsimem/%1" ).arg( QUuid::createUuid().toString() ); + QString randomFileName = QStringLiteral( "/vsimem/%1" ).arg( QUuid::createUuid().toString() ); // create memory file system object from buffer QByteArray ba = string.toUtf8(); diff --git a/src/core/qgsoptionalexpression.cpp b/src/core/qgsoptionalexpression.cpp index e93771c287bb..33812576897a 100644 --- a/src/core/qgsoptionalexpression.cpp +++ b/src/core/qgsoptionalexpression.cpp @@ -37,12 +37,12 @@ QgsOptionalExpression::QgsOptionalExpression( const QgsExpression& expression, b void QgsOptionalExpression::writeXml( QDomElement& element ) { QDomText exp = element.ownerDocument().createTextNode( data().expression() ); - element.setAttribute( "enabled", enabled() ); + element.setAttribute( QStringLiteral( "enabled" ), enabled() ); element.appendChild( exp ); } void QgsOptionalExpression::readXml( const QDomElement& element ) { - setEnabled( element.attribute( "enabled" ).toInt() ); + setEnabled( element.attribute( QStringLiteral( "enabled" ) ).toInt() ); setData( element.text() ); } diff --git a/src/core/qgsowsconnection.cpp b/src/core/qgsowsconnection.cpp index ad7ed8eff655..69be50addd0b 100644 --- a/src/core/qgsowsconnection.cpp +++ b/src/core/qgsowsconnection.cpp @@ -49,7 +49,7 @@ QgsOwsConnection::QgsOwsConnection( const QString & theService, const QString & QStringList connStringParts; mConnectionInfo = settings.value( key + "/url" ).toString(); - mUri.setParam( "url", settings.value( key + "/url" ).toString() ); + mUri.setParam( QStringLiteral( "url" ), settings.value( key + "/url" ).toString() ); // Check for credentials and prepend to the connection info QString username = settings.value( credentialsKey + "/username" ).toString(); @@ -57,14 +57,14 @@ QgsOwsConnection::QgsOwsConnection( const QString & theService, const QString & if ( !username.isEmpty() ) { // check for a password, if none prompt to get it - mUri.setParam( "username", username ); - mUri.setParam( "password", password ); + mUri.setParam( QStringLiteral( "username" ), username ); + mUri.setParam( QStringLiteral( "password" ), password ); } QString authcfg = settings.value( credentialsKey + "/authcfg" ).toString(); if ( !authcfg.isEmpty() ) { - mUri.setParam( "authcfg", authcfg ); + mUri.setParam( QStringLiteral( "authcfg" ), authcfg ); } mConnectionInfo.append( ",authcfg=" + authcfg ); @@ -74,19 +74,19 @@ QgsOwsConnection::QgsOwsConnection( const QString & theService, const QString & bool invertAxisOrientation = settings.value( key + "/invertAxisOrientation", false ).toBool(); if ( ignoreGetMap ) { - mUri.setParam( "IgnoreGetMapUrl", "1" ); + mUri.setParam( QStringLiteral( "IgnoreGetMapUrl" ), QStringLiteral( "1" ) ); } if ( ignoreGetFeatureInfo ) { - mUri.setParam( "IgnoreGetFeatureInfoUrl", "1" ); + mUri.setParam( QStringLiteral( "IgnoreGetFeatureInfoUrl" ), QStringLiteral( "1" ) ); } if ( ignoreAxisOrientation ) { - mUri.setParam( "IgnoreAxisOrientation", "1" ); + mUri.setParam( QStringLiteral( "IgnoreAxisOrientation" ), QStringLiteral( "1" ) ); } if ( invertAxisOrientation ) { - mUri.setParam( "InvertAxisOrientation", "1" ); + mUri.setParam( QStringLiteral( "InvertAxisOrientation" ), QStringLiteral( "1" ) ); } QgsDebugMsg( QString( "encoded uri: '%1'." ).arg( QString( mUri.encodedUri() ) ) ); diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index dbaa89e7a968..c453c7490331 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -108,11 +108,11 @@ QgsPalLayerSettings::QgsPalLayerSettings() useSubstitutions = false; // text formatting - wrapChar = ""; + wrapChar = QLatin1String( "" ); multilineAlign = MultiFollowPlacement; addDirectionSymbol = false; - leftDirectionSymbol = QString( "<" ); - rightDirectionSymbol = QString( ">" ); + leftDirectionSymbol = QStringLiteral( "<" ); + rightDirectionSymbol = QStringLiteral( ">" ); reverseDirectionSymbol = false; placeDirectionSymbol = SymbolLeftRight; formatNumbers = false; @@ -165,112 +165,112 @@ QgsPalLayerSettings::QgsPalLayerSettings() // NOTE: in QPair use -1 for second value (other values are for old-style layer properties migration) // text style - mDataDefinedNames.insert( Size, QPair( "Size", 0 ) ); - mDataDefinedNames.insert( Bold, QPair( "Bold", 1 ) ); - mDataDefinedNames.insert( Italic, QPair( "Italic", 2 ) ); - mDataDefinedNames.insert( Underline, QPair( "Underline", 3 ) ); - mDataDefinedNames.insert( Color, QPair( "Color", 4 ) ); - mDataDefinedNames.insert( Strikeout, QPair( "Strikeout", 5 ) ); - mDataDefinedNames.insert( Family, QPair( "Family", 6 ) ); - mDataDefinedNames.insert( FontStyle, QPair( "FontStyle", -1 ) ); - mDataDefinedNames.insert( FontSizeUnit, QPair( "FontSizeUnit", -1 ) ); - mDataDefinedNames.insert( FontTransp, QPair( "FontTransp", 18 ) ); - mDataDefinedNames.insert( FontCase, QPair( "FontCase", -1 ) ); - mDataDefinedNames.insert( FontLetterSpacing, QPair( "FontLetterSpacing", -1 ) ); - mDataDefinedNames.insert( FontWordSpacing, QPair( "FontWordSpacing", -1 ) ); - mDataDefinedNames.insert( FontBlendMode, QPair( "FontBlendMode", -1 ) ); + mDataDefinedNames.insert( Size, QPair( QStringLiteral( "Size" ), 0 ) ); + mDataDefinedNames.insert( Bold, QPair( QStringLiteral( "Bold" ), 1 ) ); + mDataDefinedNames.insert( Italic, QPair( QStringLiteral( "Italic" ), 2 ) ); + mDataDefinedNames.insert( Underline, QPair( QStringLiteral( "Underline" ), 3 ) ); + mDataDefinedNames.insert( Color, QPair( QStringLiteral( "Color" ), 4 ) ); + mDataDefinedNames.insert( Strikeout, QPair( QStringLiteral( "Strikeout" ), 5 ) ); + mDataDefinedNames.insert( Family, QPair( QStringLiteral( "Family" ), 6 ) ); + mDataDefinedNames.insert( FontStyle, QPair( QStringLiteral( "FontStyle" ), -1 ) ); + mDataDefinedNames.insert( FontSizeUnit, QPair( QStringLiteral( "FontSizeUnit" ), -1 ) ); + mDataDefinedNames.insert( FontTransp, QPair( QStringLiteral( "FontTransp" ), 18 ) ); + mDataDefinedNames.insert( FontCase, QPair( QStringLiteral( "FontCase" ), -1 ) ); + mDataDefinedNames.insert( FontLetterSpacing, QPair( QStringLiteral( "FontLetterSpacing" ), -1 ) ); + mDataDefinedNames.insert( FontWordSpacing, QPair( QStringLiteral( "FontWordSpacing" ), -1 ) ); + mDataDefinedNames.insert( FontBlendMode, QPair( QStringLiteral( "FontBlendMode" ), -1 ) ); // text formatting - mDataDefinedNames.insert( MultiLineWrapChar, QPair( "MultiLineWrapChar", -1 ) ); - mDataDefinedNames.insert( MultiLineHeight, QPair( "MultiLineHeight", -1 ) ); - mDataDefinedNames.insert( MultiLineAlignment, QPair( "MultiLineAlignment", -1 ) ); - mDataDefinedNames.insert( DirSymbDraw, QPair( "DirSymbDraw", -1 ) ); - mDataDefinedNames.insert( DirSymbLeft, QPair( "DirSymbLeft", -1 ) ); - mDataDefinedNames.insert( DirSymbRight, QPair( "DirSymbRight", -1 ) ); - mDataDefinedNames.insert( DirSymbPlacement, QPair( "DirSymbPlacement", -1 ) ); - mDataDefinedNames.insert( DirSymbReverse, QPair( "DirSymbReverse", -1 ) ); - mDataDefinedNames.insert( NumFormat, QPair( "NumFormat", -1 ) ); - mDataDefinedNames.insert( NumDecimals, QPair( "NumDecimals", -1 ) ); - mDataDefinedNames.insert( NumPlusSign, QPair( "NumPlusSign", -1 ) ); + mDataDefinedNames.insert( MultiLineWrapChar, QPair( QStringLiteral( "MultiLineWrapChar" ), -1 ) ); + mDataDefinedNames.insert( MultiLineHeight, QPair( QStringLiteral( "MultiLineHeight" ), -1 ) ); + mDataDefinedNames.insert( MultiLineAlignment, QPair( QStringLiteral( "MultiLineAlignment" ), -1 ) ); + mDataDefinedNames.insert( DirSymbDraw, QPair( QStringLiteral( "DirSymbDraw" ), -1 ) ); + mDataDefinedNames.insert( DirSymbLeft, QPair( QStringLiteral( "DirSymbLeft" ), -1 ) ); + mDataDefinedNames.insert( DirSymbRight, QPair( QStringLiteral( "DirSymbRight" ), -1 ) ); + mDataDefinedNames.insert( DirSymbPlacement, QPair( QStringLiteral( "DirSymbPlacement" ), -1 ) ); + mDataDefinedNames.insert( DirSymbReverse, QPair( QStringLiteral( "DirSymbReverse" ), -1 ) ); + mDataDefinedNames.insert( NumFormat, QPair( QStringLiteral( "NumFormat" ), -1 ) ); + mDataDefinedNames.insert( NumDecimals, QPair( QStringLiteral( "NumDecimals" ), -1 ) ); + mDataDefinedNames.insert( NumPlusSign, QPair( QStringLiteral( "NumPlusSign" ), -1 ) ); // text buffer - mDataDefinedNames.insert( BufferDraw, QPair( "BufferDraw", -1 ) ); - mDataDefinedNames.insert( BufferSize, QPair( "BufferSize", 7 ) ); - mDataDefinedNames.insert( BufferUnit, QPair( "BufferUnit", -1 ) ); - mDataDefinedNames.insert( BufferColor, QPair( "BufferColor", 8 ) ); - mDataDefinedNames.insert( BufferTransp, QPair( "BufferTransp", 19 ) ); - mDataDefinedNames.insert( BufferJoinStyle, QPair( "BufferJoinStyle", -1 ) ); - mDataDefinedNames.insert( BufferBlendMode, QPair( "BufferBlendMode", -1 ) ); + mDataDefinedNames.insert( BufferDraw, QPair( QStringLiteral( "BufferDraw" ), -1 ) ); + mDataDefinedNames.insert( BufferSize, QPair( QStringLiteral( "BufferSize" ), 7 ) ); + mDataDefinedNames.insert( BufferUnit, QPair( QStringLiteral( "BufferUnit" ), -1 ) ); + mDataDefinedNames.insert( BufferColor, QPair( QStringLiteral( "BufferColor" ), 8 ) ); + mDataDefinedNames.insert( BufferTransp, QPair( QStringLiteral( "BufferTransp" ), 19 ) ); + mDataDefinedNames.insert( BufferJoinStyle, QPair( QStringLiteral( "BufferJoinStyle" ), -1 ) ); + mDataDefinedNames.insert( BufferBlendMode, QPair( QStringLiteral( "BufferBlendMode" ), -1 ) ); // background - mDataDefinedNames.insert( ShapeDraw, QPair( "ShapeDraw", -1 ) ); - mDataDefinedNames.insert( ShapeKind, QPair( "ShapeKind", -1 ) ); - mDataDefinedNames.insert( ShapeSVGFile, QPair( "ShapeSVGFile", -1 ) ); - mDataDefinedNames.insert( ShapeSizeType, QPair( "ShapeSizeType", -1 ) ); - mDataDefinedNames.insert( ShapeSizeX, QPair( "ShapeSizeX", -1 ) ); - mDataDefinedNames.insert( ShapeSizeY, QPair( "ShapeSizeY", -1 ) ); - mDataDefinedNames.insert( ShapeSizeUnits, QPair( "ShapeSizeUnits", -1 ) ); - mDataDefinedNames.insert( ShapeRotationType, QPair( "ShapeRotationType", -1 ) ); - mDataDefinedNames.insert( ShapeRotation, QPair( "ShapeRotation", -1 ) ); - mDataDefinedNames.insert( ShapeOffset, QPair( "ShapeOffset", -1 ) ); - mDataDefinedNames.insert( ShapeOffsetUnits, QPair( "ShapeOffsetUnits", -1 ) ); - mDataDefinedNames.insert( ShapeRadii, QPair( "ShapeRadii", -1 ) ); - mDataDefinedNames.insert( ShapeRadiiUnits, QPair( "ShapeRadiiUnits", -1 ) ); - mDataDefinedNames.insert( ShapeTransparency, QPair( "ShapeTransparency", -1 ) ); - mDataDefinedNames.insert( ShapeBlendMode, QPair( "ShapeBlendMode", -1 ) ); - mDataDefinedNames.insert( ShapeFillColor, QPair( "ShapeFillColor", -1 ) ); - mDataDefinedNames.insert( ShapeBorderColor, QPair( "ShapeBorderColor", -1 ) ); - mDataDefinedNames.insert( ShapeBorderWidth, QPair( "ShapeBorderWidth", -1 ) ); - mDataDefinedNames.insert( ShapeBorderWidthUnits, QPair( "ShapeBorderWidthUnits", -1 ) ); - mDataDefinedNames.insert( ShapeJoinStyle, QPair( "ShapeJoinStyle", -1 ) ); + mDataDefinedNames.insert( ShapeDraw, QPair( QStringLiteral( "ShapeDraw" ), -1 ) ); + mDataDefinedNames.insert( ShapeKind, QPair( QStringLiteral( "ShapeKind" ), -1 ) ); + mDataDefinedNames.insert( ShapeSVGFile, QPair( QStringLiteral( "ShapeSVGFile" ), -1 ) ); + mDataDefinedNames.insert( ShapeSizeType, QPair( QStringLiteral( "ShapeSizeType" ), -1 ) ); + mDataDefinedNames.insert( ShapeSizeX, QPair( QStringLiteral( "ShapeSizeX" ), -1 ) ); + mDataDefinedNames.insert( ShapeSizeY, QPair( QStringLiteral( "ShapeSizeY" ), -1 ) ); + mDataDefinedNames.insert( ShapeSizeUnits, QPair( QStringLiteral( "ShapeSizeUnits" ), -1 ) ); + mDataDefinedNames.insert( ShapeRotationType, QPair( QStringLiteral( "ShapeRotationType" ), -1 ) ); + mDataDefinedNames.insert( ShapeRotation, QPair( QStringLiteral( "ShapeRotation" ), -1 ) ); + mDataDefinedNames.insert( ShapeOffset, QPair( QStringLiteral( "ShapeOffset" ), -1 ) ); + mDataDefinedNames.insert( ShapeOffsetUnits, QPair( QStringLiteral( "ShapeOffsetUnits" ), -1 ) ); + mDataDefinedNames.insert( ShapeRadii, QPair( QStringLiteral( "ShapeRadii" ), -1 ) ); + mDataDefinedNames.insert( ShapeRadiiUnits, QPair( QStringLiteral( "ShapeRadiiUnits" ), -1 ) ); + mDataDefinedNames.insert( ShapeTransparency, QPair( QStringLiteral( "ShapeTransparency" ), -1 ) ); + mDataDefinedNames.insert( ShapeBlendMode, QPair( QStringLiteral( "ShapeBlendMode" ), -1 ) ); + mDataDefinedNames.insert( ShapeFillColor, QPair( QStringLiteral( "ShapeFillColor" ), -1 ) ); + mDataDefinedNames.insert( ShapeBorderColor, QPair( QStringLiteral( "ShapeBorderColor" ), -1 ) ); + mDataDefinedNames.insert( ShapeBorderWidth, QPair( QStringLiteral( "ShapeBorderWidth" ), -1 ) ); + mDataDefinedNames.insert( ShapeBorderWidthUnits, QPair( QStringLiteral( "ShapeBorderWidthUnits" ), -1 ) ); + mDataDefinedNames.insert( ShapeJoinStyle, QPair( QStringLiteral( "ShapeJoinStyle" ), -1 ) ); // drop shadow - mDataDefinedNames.insert( ShadowDraw, QPair( "ShadowDraw", -1 ) ); - mDataDefinedNames.insert( ShadowUnder, QPair( "ShadowUnder", -1 ) ); - mDataDefinedNames.insert( ShadowOffsetAngle, QPair( "ShadowOffsetAngle", -1 ) ); - mDataDefinedNames.insert( ShadowOffsetDist, QPair( "ShadowOffsetDist", -1 ) ); - mDataDefinedNames.insert( ShadowOffsetUnits, QPair( "ShadowOffsetUnits", -1 ) ); - mDataDefinedNames.insert( ShadowRadius, QPair( "ShadowRadius", -1 ) ); - mDataDefinedNames.insert( ShadowRadiusUnits, QPair( "ShadowRadiusUnits", -1 ) ); - mDataDefinedNames.insert( ShadowTransparency, QPair( "ShadowTransparency", -1 ) ); - mDataDefinedNames.insert( ShadowScale, QPair( "ShadowScale", -1 ) ); - mDataDefinedNames.insert( ShadowColor, QPair( "ShadowColor", -1 ) ); - mDataDefinedNames.insert( ShadowBlendMode, QPair( "ShadowBlendMode", -1 ) ); + mDataDefinedNames.insert( ShadowDraw, QPair( QStringLiteral( "ShadowDraw" ), -1 ) ); + mDataDefinedNames.insert( ShadowUnder, QPair( QStringLiteral( "ShadowUnder" ), -1 ) ); + mDataDefinedNames.insert( ShadowOffsetAngle, QPair( QStringLiteral( "ShadowOffsetAngle" ), -1 ) ); + mDataDefinedNames.insert( ShadowOffsetDist, QPair( QStringLiteral( "ShadowOffsetDist" ), -1 ) ); + mDataDefinedNames.insert( ShadowOffsetUnits, QPair( QStringLiteral( "ShadowOffsetUnits" ), -1 ) ); + mDataDefinedNames.insert( ShadowRadius, QPair( QStringLiteral( "ShadowRadius" ), -1 ) ); + mDataDefinedNames.insert( ShadowRadiusUnits, QPair( QStringLiteral( "ShadowRadiusUnits" ), -1 ) ); + mDataDefinedNames.insert( ShadowTransparency, QPair( QStringLiteral( "ShadowTransparency" ), -1 ) ); + mDataDefinedNames.insert( ShadowScale, QPair( QStringLiteral( "ShadowScale" ), -1 ) ); + mDataDefinedNames.insert( ShadowColor, QPair( QStringLiteral( "ShadowColor" ), -1 ) ); + mDataDefinedNames.insert( ShadowBlendMode, QPair( QStringLiteral( "ShadowBlendMode" ), -1 ) ); // placement - mDataDefinedNames.insert( CentroidWhole, QPair( "CentroidWhole", -1 ) ); - mDataDefinedNames.insert( OffsetQuad, QPair( "OffsetQuad", -1 ) ); - mDataDefinedNames.insert( OffsetXY, QPair( "OffsetXY", -1 ) ); - mDataDefinedNames.insert( OffsetUnits, QPair( "OffsetUnits", -1 ) ); - mDataDefinedNames.insert( LabelDistance, QPair( "LabelDistance", 13 ) ); - mDataDefinedNames.insert( DistanceUnits, QPair( "DistanceUnits", -1 ) ); - mDataDefinedNames.insert( OffsetRotation, QPair( "OffsetRotation", -1 ) ); - mDataDefinedNames.insert( CurvedCharAngleInOut, QPair( "CurvedCharAngleInOut", -1 ) ); - mDataDefinedNames.insert( RepeatDistance, QPair( "RepeatDistance", -1 ) ); - mDataDefinedNames.insert( RepeatDistanceUnit, QPair( "RepeatDistanceUnit", -1 ) ); - mDataDefinedNames.insert( Priority, QPair( "Priority", -1 ) ); - mDataDefinedNames.insert( IsObstacle, QPair( "IsObstacle", -1 ) ); - mDataDefinedNames.insert( ObstacleFactor, QPair( "ObstacleFactor", -1 ) ); - mDataDefinedNames.insert( PredefinedPositionOrder, QPair( "PredefinedPositionOrder", -1 ) ); + mDataDefinedNames.insert( CentroidWhole, QPair( QStringLiteral( "CentroidWhole" ), -1 ) ); + mDataDefinedNames.insert( OffsetQuad, QPair( QStringLiteral( "OffsetQuad" ), -1 ) ); + mDataDefinedNames.insert( OffsetXY, QPair( QStringLiteral( "OffsetXY" ), -1 ) ); + mDataDefinedNames.insert( OffsetUnits, QPair( QStringLiteral( "OffsetUnits" ), -1 ) ); + mDataDefinedNames.insert( LabelDistance, QPair( QStringLiteral( "LabelDistance" ), 13 ) ); + mDataDefinedNames.insert( DistanceUnits, QPair( QStringLiteral( "DistanceUnits" ), -1 ) ); + mDataDefinedNames.insert( OffsetRotation, QPair( QStringLiteral( "OffsetRotation" ), -1 ) ); + mDataDefinedNames.insert( CurvedCharAngleInOut, QPair( QStringLiteral( "CurvedCharAngleInOut" ), -1 ) ); + mDataDefinedNames.insert( RepeatDistance, QPair( QStringLiteral( "RepeatDistance" ), -1 ) ); + mDataDefinedNames.insert( RepeatDistanceUnit, QPair( QStringLiteral( "RepeatDistanceUnit" ), -1 ) ); + mDataDefinedNames.insert( Priority, QPair( QStringLiteral( "Priority" ), -1 ) ); + mDataDefinedNames.insert( IsObstacle, QPair( QStringLiteral( "IsObstacle" ), -1 ) ); + mDataDefinedNames.insert( ObstacleFactor, QPair( QStringLiteral( "ObstacleFactor" ), -1 ) ); + mDataDefinedNames.insert( PredefinedPositionOrder, QPair( QStringLiteral( "PredefinedPositionOrder" ), -1 ) ); // (data defined only) - mDataDefinedNames.insert( PositionX, QPair( "PositionX", 9 ) ); - mDataDefinedNames.insert( PositionY, QPair( "PositionY", 10 ) ); - mDataDefinedNames.insert( Hali, QPair( "Hali", 11 ) ); - mDataDefinedNames.insert( Vali, QPair( "Vali", 12 ) ); - mDataDefinedNames.insert( Rotation, QPair( "Rotation", 14 ) ); + mDataDefinedNames.insert( PositionX, QPair( QStringLiteral( "PositionX" ), 9 ) ); + mDataDefinedNames.insert( PositionY, QPair( QStringLiteral( "PositionY" ), 10 ) ); + mDataDefinedNames.insert( Hali, QPair( QStringLiteral( "Hali" ), 11 ) ); + mDataDefinedNames.insert( Vali, QPair( QStringLiteral( "Vali" ), 12 ) ); + mDataDefinedNames.insert( Rotation, QPair( QStringLiteral( "Rotation" ), 14 ) ); //rendering - mDataDefinedNames.insert( ScaleVisibility, QPair( "ScaleVisibility", -1 ) ); - mDataDefinedNames.insert( MinScale, QPair( "MinScale", 16 ) ); - mDataDefinedNames.insert( MaxScale, QPair( "MaxScale", 17 ) ); - mDataDefinedNames.insert( FontLimitPixel, QPair( "FontLimitPixel", -1 ) ); - mDataDefinedNames.insert( FontMinPixel, QPair( "FontMinPixel", -1 ) ); - mDataDefinedNames.insert( FontMaxPixel, QPair( "FontMaxPixel", -1 ) ); - mDataDefinedNames.insert( ZIndex, QPair( "ZIndex", -1 ) ); + mDataDefinedNames.insert( ScaleVisibility, QPair( QStringLiteral( "ScaleVisibility" ), -1 ) ); + mDataDefinedNames.insert( MinScale, QPair( QStringLiteral( "MinScale" ), 16 ) ); + mDataDefinedNames.insert( MaxScale, QPair( QStringLiteral( "MaxScale" ), 17 ) ); + mDataDefinedNames.insert( FontLimitPixel, QPair( QStringLiteral( "FontLimitPixel" ), -1 ) ); + mDataDefinedNames.insert( FontMinPixel, QPair( QStringLiteral( "FontMinPixel" ), -1 ) ); + mDataDefinedNames.insert( FontMaxPixel, QPair( QStringLiteral( "FontMaxPixel" ), -1 ) ); + mDataDefinedNames.insert( ZIndex, QPair( QStringLiteral( "ZIndex" ), -1 ) ); // (data defined only) - mDataDefinedNames.insert( Show, QPair( "Show", 15 ) ); - mDataDefinedNames.insert( AlwaysShow, QPair( "AlwaysShow", 20 ) ); + mDataDefinedNames.insert( Show, QPair( QStringLiteral( "Show" ), 15 ) ); + mDataDefinedNames.insert( AlwaysShow, QPair( QStringLiteral( "AlwaysShow" ), 20 ) ); } @@ -406,18 +406,18 @@ QgsExpression* QgsPalLayerSettings::getLabelExpression() static QgsPalLayerSettings::SizeUnit _decodeUnits( const QString& str ) { - if ( str.compare( "Point", Qt::CaseInsensitive ) == 0 - || str.compare( "Points", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Points; - if ( str.compare( "MapUnit", Qt::CaseInsensitive ) == 0 - || str.compare( "MapUnits", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::MapUnits; - if ( str.compare( "Percent", Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Percent; + if ( str.compare( QLatin1String( "Point" ), Qt::CaseInsensitive ) == 0 + || str.compare( QLatin1String( "Points" ), Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Points; + if ( str.compare( QLatin1String( "MapUnit" ), Qt::CaseInsensitive ) == 0 + || str.compare( QLatin1String( "MapUnits" ), Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::MapUnits; + if ( str.compare( QLatin1String( "Percent" ), Qt::CaseInsensitive ) == 0 ) return QgsPalLayerSettings::Percent; return QgsPalLayerSettings::MM; // "MM" } static Qt::PenJoinStyle _decodePenJoinStyle( const QString& str ) { - if ( str.compare( "Miter", Qt::CaseInsensitive ) == 0 ) return Qt::MiterJoin; - if ( str.compare( "Round", Qt::CaseInsensitive ) == 0 ) return Qt::RoundJoin; + if ( str.compare( QLatin1String( "Miter" ), Qt::CaseInsensitive ) == 0 ) return Qt::MiterJoin; + if ( str.compare( QLatin1String( "Round" ), Qt::CaseInsensitive ) == 0 ) return Qt::RoundJoin; return Qt::BevelJoin; // "Bevel" } @@ -492,7 +492,7 @@ void QgsPalLayerSettings::writeDataDefinedPropertyMap( QgsVectorLayer* layer, QD values << field; if ( !values.isEmpty() ) { - propertyValue = QVariant( values.join( "~~" ) ); + propertyValue = QVariant( values.join( QStringLiteral( "~~" ) ) ); } } @@ -523,7 +523,7 @@ void QgsPalLayerSettings::writeDataDefinedPropertyMap( QgsVectorLayer* layer, QD if ( layer->customProperty( newPropertyName, QVariant() ).isValid() && i.value().second > -1 ) { // remove old-style field index-based property, if still present - layer->removeCustomProperty( QString( "labeling/dataDefinedProperty" ) + QString::number( i.value().second ) ); + layer->removeCustomProperty( QStringLiteral( "labeling/dataDefinedProperty" ) + QString::number( i.value().second ) ); } } } @@ -593,7 +593,7 @@ void QgsPalLayerSettings::readDataDefinedProperty( QgsVectorLayer* layer, if ( oldIndx == 16 || oldIndx == 17 ) // old minScale and maxScale enums { scaleVisibility = true; - layer->setCustomProperty( "labeling/scaleVisibility", true ); + layer->setCustomProperty( QStringLiteral( "labeling/scaleVisibility" ), true ); } } @@ -605,7 +605,7 @@ void QgsPalLayerSettings::readDataDefinedProperty( QgsVectorLayer* layer, { // TODO: update this when project settings for labeling are migrated to better XML layout QString newStyleString = updateDataDefinedString( ddString ); - QStringList ddv = newStyleString.split( "~~" ); + QStringList ddv = newStyleString.split( QStringLiteral( "~~" ) ); QgsDataDefined* dd = new QgsDataDefined( ddv.at( 0 ).toInt(), ddv.at( 1 ).toInt(), ddv.at( 2 ), ddv.at( 3 ) ); propertyMap.insert( p, dd ); @@ -619,7 +619,7 @@ void QgsPalLayerSettings::readDataDefinedProperty( QgsVectorLayer* layer, void QgsPalLayerSettings::readFromLayer( QgsVectorLayer* layer ) { - if ( layer->customProperty( "labeling" ).toString() != QLatin1String( "pal" ) ) + if ( layer->customProperty( QStringLiteral( "labeling" ) ).toString() != QLatin1String( "pal" ) ) { if ( layer->geometryType() == QgsWkbTypes::PointGeometry ) placement = OrderedPositionsAroundPoint; @@ -635,92 +635,92 @@ void QgsPalLayerSettings::readFromLayer( QgsVectorLayer* layer ) // NOTE: set defaults for newly added properties, for backwards compatibility enabled = layer->labelsEnabled(); - drawLabels = layer->customProperty( "labeling/drawLabels", true ).toBool(); + drawLabels = layer->customProperty( QStringLiteral( "labeling/drawLabels" ), true ).toBool(); mFormat.readFromLayer( layer ); // text style - fieldName = layer->customProperty( "labeling/fieldName" ).toString(); - isExpression = layer->customProperty( "labeling/isExpression" ).toBool(); - previewBkgrdColor = QColor( layer->customProperty( "labeling/previewBkgrdColor", QVariant( "#ffffff" ) ).toString() ); - QDomDocument doc( "substitutions" ); - doc.setContent( layer->customProperty( "labeling/substitutions" ).toString() ); - QDomElement replacementElem = doc.firstChildElement( "substitutions" ); + fieldName = layer->customProperty( QStringLiteral( "labeling/fieldName" ) ).toString(); + isExpression = layer->customProperty( QStringLiteral( "labeling/isExpression" ) ).toBool(); + previewBkgrdColor = QColor( layer->customProperty( QStringLiteral( "labeling/previewBkgrdColor" ), QVariant( "#ffffff" ) ).toString() ); + QDomDocument doc( QStringLiteral( "substitutions" ) ); + doc.setContent( layer->customProperty( QStringLiteral( "labeling/substitutions" ) ).toString() ); + QDomElement replacementElem = doc.firstChildElement( QStringLiteral( "substitutions" ) ); substitutions.readXml( replacementElem ); - useSubstitutions = layer->customProperty( "labeling/useSubstitutions" ).toBool(); + useSubstitutions = layer->customProperty( QStringLiteral( "labeling/useSubstitutions" ) ).toBool(); // text formatting - wrapChar = layer->customProperty( "labeling/wrapChar" ).toString(); - multilineAlign = static_cast< MultiLineAlign >( layer->customProperty( "labeling/multilineAlign", QVariant( MultiFollowPlacement ) ).toUInt() ); - addDirectionSymbol = layer->customProperty( "labeling/addDirectionSymbol" ).toBool(); - leftDirectionSymbol = layer->customProperty( "labeling/leftDirectionSymbol", QVariant( "<" ) ).toString(); - rightDirectionSymbol = layer->customProperty( "labeling/rightDirectionSymbol", QVariant( ">" ) ).toString(); - reverseDirectionSymbol = layer->customProperty( "labeling/reverseDirectionSymbol" ).toBool(); - placeDirectionSymbol = static_cast< DirectionSymbols >( layer->customProperty( "labeling/placeDirectionSymbol", QVariant( SymbolLeftRight ) ).toUInt() ); - formatNumbers = layer->customProperty( "labeling/formatNumbers" ).toBool(); - decimals = layer->customProperty( "labeling/decimals" ).toInt(); - plusSign = layer->customProperty( "labeling/plussign" ).toBool(); + wrapChar = layer->customProperty( QStringLiteral( "labeling/wrapChar" ) ).toString(); + multilineAlign = static_cast< MultiLineAlign >( layer->customProperty( QStringLiteral( "labeling/multilineAlign" ), QVariant( MultiFollowPlacement ) ).toUInt() ); + addDirectionSymbol = layer->customProperty( QStringLiteral( "labeling/addDirectionSymbol" ) ).toBool(); + leftDirectionSymbol = layer->customProperty( QStringLiteral( "labeling/leftDirectionSymbol" ), QVariant( "<" ) ).toString(); + rightDirectionSymbol = layer->customProperty( QStringLiteral( "labeling/rightDirectionSymbol" ), QVariant( ">" ) ).toString(); + reverseDirectionSymbol = layer->customProperty( QStringLiteral( "labeling/reverseDirectionSymbol" ) ).toBool(); + placeDirectionSymbol = static_cast< DirectionSymbols >( layer->customProperty( QStringLiteral( "labeling/placeDirectionSymbol" ), QVariant( SymbolLeftRight ) ).toUInt() ); + formatNumbers = layer->customProperty( QStringLiteral( "labeling/formatNumbers" ) ).toBool(); + decimals = layer->customProperty( QStringLiteral( "labeling/decimals" ) ).toInt(); + plusSign = layer->customProperty( QStringLiteral( "labeling/plussign" ) ).toBool(); // placement - placement = static_cast< Placement >( layer->customProperty( "labeling/placement" ).toInt() ); - placementFlags = layer->customProperty( "labeling/placementFlags" ).toUInt(); - centroidWhole = layer->customProperty( "labeling/centroidWhole", QVariant( false ) ).toBool(); - centroidInside = layer->customProperty( "labeling/centroidInside", QVariant( false ) ).toBool(); - predefinedPositionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( layer->customProperty( "labeling/predefinedPositionOrder" ).toString() ); + placement = static_cast< Placement >( layer->customProperty( QStringLiteral( "labeling/placement" ) ).toInt() ); + placementFlags = layer->customProperty( QStringLiteral( "labeling/placementFlags" ) ).toUInt(); + centroidWhole = layer->customProperty( QStringLiteral( "labeling/centroidWhole" ), QVariant( false ) ).toBool(); + centroidInside = layer->customProperty( QStringLiteral( "labeling/centroidInside" ), QVariant( false ) ).toBool(); + predefinedPositionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( layer->customProperty( QStringLiteral( "labeling/predefinedPositionOrder" ) ).toString() ); if ( predefinedPositionOrder.isEmpty() ) predefinedPositionOrder = DEFAULT_PLACEMENT_ORDER; - fitInPolygonOnly = layer->customProperty( "labeling/fitInPolygonOnly", QVariant( false ) ).toBool(); - dist = layer->customProperty( "labeling/dist" ).toDouble(); - distInMapUnits = layer->customProperty( "labeling/distInMapUnits" ).toBool(); - if ( layer->customProperty( "labeling/distMapUnitScale" ).toString().isEmpty() ) + fitInPolygonOnly = layer->customProperty( QStringLiteral( "labeling/fitInPolygonOnly" ), QVariant( false ) ).toBool(); + dist = layer->customProperty( QStringLiteral( "labeling/dist" ) ).toDouble(); + distInMapUnits = layer->customProperty( QStringLiteral( "labeling/distInMapUnits" ) ).toBool(); + if ( layer->customProperty( QStringLiteral( "labeling/distMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - distMapUnitScale.minScale = layer->customProperty( "labeling/distMapUnitMinScale", 0.0 ).toDouble(); - distMapUnitScale.maxScale = layer->customProperty( "labeling/distMapUnitMaxScale", 0.0 ).toDouble(); + distMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/distMapUnitMinScale" ), 0.0 ).toDouble(); + distMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/distMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - distMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/distMapUnitScale" ).toString() ); + distMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/distMapUnitScale" ) ).toString() ); } - offsetType = static_cast< OffsetType >( layer->customProperty( "labeling/offsetType", QVariant( FromPoint ) ).toUInt() ); - quadOffset = static_cast< QuadrantPosition >( layer->customProperty( "labeling/quadOffset", QVariant( QuadrantOver ) ).toUInt() ); - xOffset = layer->customProperty( "labeling/xOffset", QVariant( 0.0 ) ).toDouble(); - yOffset = layer->customProperty( "labeling/yOffset", QVariant( 0.0 ) ).toDouble(); - labelOffsetInMapUnits = layer->customProperty( "labeling/labelOffsetInMapUnits", QVariant( true ) ).toBool(); - if ( layer->customProperty( "labeling/labelOffsetMapUnitScale" ).toString().isEmpty() ) + offsetType = static_cast< OffsetType >( layer->customProperty( QStringLiteral( "labeling/offsetType" ), QVariant( FromPoint ) ).toUInt() ); + quadOffset = static_cast< QuadrantPosition >( layer->customProperty( QStringLiteral( "labeling/quadOffset" ), QVariant( QuadrantOver ) ).toUInt() ); + xOffset = layer->customProperty( QStringLiteral( "labeling/xOffset" ), QVariant( 0.0 ) ).toDouble(); + yOffset = layer->customProperty( QStringLiteral( "labeling/yOffset" ), QVariant( 0.0 ) ).toDouble(); + labelOffsetInMapUnits = layer->customProperty( QStringLiteral( "labeling/labelOffsetInMapUnits" ), QVariant( true ) ).toBool(); + if ( layer->customProperty( QStringLiteral( "labeling/labelOffsetMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - labelOffsetMapUnitScale.minScale = layer->customProperty( "labeling/labelOffsetMapUnitMinScale", 0.0 ).toDouble(); - labelOffsetMapUnitScale.maxScale = layer->customProperty( "labeling/labelOffsetMapUnitMaxScale", 0.0 ).toDouble(); + labelOffsetMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/labelOffsetMapUnitMinScale" ), 0.0 ).toDouble(); + labelOffsetMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/labelOffsetMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - labelOffsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/labelOffsetMapUnitScale" ).toString() ); + labelOffsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/labelOffsetMapUnitScale" ) ).toString() ); } - angleOffset = layer->customProperty( "labeling/angleOffset", QVariant( 0.0 ) ).toDouble(); - preserveRotation = layer->customProperty( "labeling/preserveRotation", QVariant( true ) ).toBool(); - maxCurvedCharAngleIn = layer->customProperty( "labeling/maxCurvedCharAngleIn", QVariant( 25.0 ) ).toDouble(); - maxCurvedCharAngleOut = layer->customProperty( "labeling/maxCurvedCharAngleOut", QVariant( -25.0 ) ).toDouble(); - priority = layer->customProperty( "labeling/priority" ).toInt(); - repeatDistance = layer->customProperty( "labeling/repeatDistance", 0.0 ).toDouble(); - repeatDistanceUnit = static_cast< SizeUnit >( layer->customProperty( "labeling/repeatDistanceUnit", QVariant( MM ) ).toUInt() ); - if ( layer->customProperty( "labeling/repeatDistanceMapUnitScale" ).toString().isEmpty() ) + angleOffset = layer->customProperty( QStringLiteral( "labeling/angleOffset" ), QVariant( 0.0 ) ).toDouble(); + preserveRotation = layer->customProperty( QStringLiteral( "labeling/preserveRotation" ), QVariant( true ) ).toBool(); + maxCurvedCharAngleIn = layer->customProperty( QStringLiteral( "labeling/maxCurvedCharAngleIn" ), QVariant( 25.0 ) ).toDouble(); + maxCurvedCharAngleOut = layer->customProperty( QStringLiteral( "labeling/maxCurvedCharAngleOut" ), QVariant( -25.0 ) ).toDouble(); + priority = layer->customProperty( QStringLiteral( "labeling/priority" ) ).toInt(); + repeatDistance = layer->customProperty( QStringLiteral( "labeling/repeatDistance" ), 0.0 ).toDouble(); + repeatDistanceUnit = static_cast< SizeUnit >( layer->customProperty( QStringLiteral( "labeling/repeatDistanceUnit" ), QVariant( MM ) ).toUInt() ); + if ( layer->customProperty( QStringLiteral( "labeling/repeatDistanceMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - repeatDistanceMapUnitScale.minScale = layer->customProperty( "labeling/repeatDistanceMapUnitMinScale", 0.0 ).toDouble(); - repeatDistanceMapUnitScale.maxScale = layer->customProperty( "labeling/repeatDistanceMapUnitMaxScale", 0.0 ).toDouble(); + repeatDistanceMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/repeatDistanceMapUnitMinScale" ), 0.0 ).toDouble(); + repeatDistanceMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/repeatDistanceMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - repeatDistanceMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/repeatDistanceMapUnitScale" ).toString() ); + repeatDistanceMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/repeatDistanceMapUnitScale" ) ).toString() ); } // rendering - int scalemn = layer->customProperty( "labeling/scaleMin", QVariant( 0 ) ).toInt(); - int scalemx = layer->customProperty( "labeling/scaleMax", QVariant( 0 ) ).toInt(); + int scalemn = layer->customProperty( QStringLiteral( "labeling/scaleMin" ), QVariant( 0 ) ).toInt(); + int scalemx = layer->customProperty( QStringLiteral( "labeling/scaleMax" ), QVariant( 0 ) ).toInt(); // fix for scale visibility limits being keyed off of just its values in the past (<2.0) - QVariant scalevis = layer->customProperty( "labeling/scaleVisibility", QVariant() ); + QVariant scalevis = layer->customProperty( QStringLiteral( "labeling/scaleVisibility" ), QVariant() ); if ( scalevis.isValid() ) { scaleVisibility = scalevis.toBool(); @@ -740,21 +740,21 @@ void QgsPalLayerSettings::readFromLayer( QgsVectorLayer* layer ) } - fontLimitPixelSize = layer->customProperty( "labeling/fontLimitPixelSize", QVariant( false ) ).toBool(); - fontMinPixelSize = layer->customProperty( "labeling/fontMinPixelSize", QVariant( 0 ) ).toInt(); - fontMaxPixelSize = layer->customProperty( "labeling/fontMaxPixelSize", QVariant( 10000 ) ).toInt(); - displayAll = layer->customProperty( "labeling/displayAll", QVariant( false ) ).toBool(); - upsidedownLabels = static_cast< UpsideDownLabels >( layer->customProperty( "labeling/upsidedownLabels", QVariant( Upright ) ).toUInt() ); + fontLimitPixelSize = layer->customProperty( QStringLiteral( "labeling/fontLimitPixelSize" ), QVariant( false ) ).toBool(); + fontMinPixelSize = layer->customProperty( QStringLiteral( "labeling/fontMinPixelSize" ), QVariant( 0 ) ).toInt(); + fontMaxPixelSize = layer->customProperty( QStringLiteral( "labeling/fontMaxPixelSize" ), QVariant( 10000 ) ).toInt(); + displayAll = layer->customProperty( QStringLiteral( "labeling/displayAll" ), QVariant( false ) ).toBool(); + upsidedownLabels = static_cast< UpsideDownLabels >( layer->customProperty( QStringLiteral( "labeling/upsidedownLabels" ), QVariant( Upright ) ).toUInt() ); - labelPerPart = layer->customProperty( "labeling/labelPerPart" ).toBool(); - mergeLines = layer->customProperty( "labeling/mergeLines" ).toBool(); - minFeatureSize = layer->customProperty( "labeling/minFeatureSize" ).toDouble(); - limitNumLabels = layer->customProperty( "labeling/limitNumLabels", QVariant( false ) ).toBool(); - maxNumLabels = layer->customProperty( "labeling/maxNumLabels", QVariant( 2000 ) ).toInt(); - obstacle = layer->customProperty( "labeling/obstacle", QVariant( true ) ).toBool(); - obstacleFactor = layer->customProperty( "labeling/obstacleFactor", QVariant( 1.0 ) ).toDouble(); - obstacleType = static_cast< ObstacleType >( layer->customProperty( "labeling/obstacleType", QVariant( PolygonInterior ) ).toUInt() ); - zIndex = layer->customProperty( "labeling/zIndex", QVariant( 0.0 ) ).toDouble(); + labelPerPart = layer->customProperty( QStringLiteral( "labeling/labelPerPart" ) ).toBool(); + mergeLines = layer->customProperty( QStringLiteral( "labeling/mergeLines" ) ).toBool(); + minFeatureSize = layer->customProperty( QStringLiteral( "labeling/minFeatureSize" ) ).toDouble(); + limitNumLabels = layer->customProperty( QStringLiteral( "labeling/limitNumLabels" ), QVariant( false ) ).toBool(); + maxNumLabels = layer->customProperty( QStringLiteral( "labeling/maxNumLabels" ), QVariant( 2000 ) ).toInt(); + obstacle = layer->customProperty( QStringLiteral( "labeling/obstacle" ), QVariant( true ) ).toBool(); + obstacleFactor = layer->customProperty( QStringLiteral( "labeling/obstacleFactor" ), QVariant( 1.0 ) ).toDouble(); + obstacleType = static_cast< ObstacleType >( layer->customProperty( QStringLiteral( "labeling/obstacleType" ), QVariant( PolygonInterior ) ).toUInt() ); + zIndex = layer->customProperty( QStringLiteral( "labeling/zIndex" ), QVariant( 0.0 ) ).toDouble(); readDataDefinedPropertyMap( layer, nullptr, dataDefinedProperties ); } @@ -762,82 +762,82 @@ void QgsPalLayerSettings::readFromLayer( QgsVectorLayer* layer ) void QgsPalLayerSettings::writeToLayer( QgsVectorLayer* layer ) { // this is a mark that labeling information is present - layer->setCustomProperty( "labeling", "pal" ); + layer->setCustomProperty( QStringLiteral( "labeling" ), "pal" ); - layer->setCustomProperty( "labeling/enabled", enabled ); - layer->setCustomProperty( "labeling/drawLabels", drawLabels ); + layer->setCustomProperty( QStringLiteral( "labeling/enabled" ), enabled ); + layer->setCustomProperty( QStringLiteral( "labeling/drawLabels" ), drawLabels ); mFormat.writeToLayer( layer ); // text style - layer->setCustomProperty( "labeling/fieldName", fieldName ); - layer->setCustomProperty( "labeling/isExpression", isExpression ); - layer->setCustomProperty( "labeling/previewBkgrdColor", previewBkgrdColor.name() ); - QDomDocument doc( "substitutions" ); - QDomElement replacementElem = doc.createElement( "substitutions" ); + layer->setCustomProperty( QStringLiteral( "labeling/fieldName" ), fieldName ); + layer->setCustomProperty( QStringLiteral( "labeling/isExpression" ), isExpression ); + layer->setCustomProperty( QStringLiteral( "labeling/previewBkgrdColor" ), previewBkgrdColor.name() ); + QDomDocument doc( QStringLiteral( "substitutions" ) ); + QDomElement replacementElem = doc.createElement( QStringLiteral( "substitutions" ) ); substitutions.writeXml( replacementElem, doc ); QString replacementProps; QTextStream stream( &replacementProps ); replacementElem.save( stream, -1 ); - layer->setCustomProperty( "labeling/substitutions", replacementProps ); - layer->setCustomProperty( "labeling/useSubstitutions", useSubstitutions ); + layer->setCustomProperty( QStringLiteral( "labeling/substitutions" ), replacementProps ); + layer->setCustomProperty( QStringLiteral( "labeling/useSubstitutions" ), useSubstitutions ); // text formatting - layer->setCustomProperty( "labeling/wrapChar", wrapChar ); - layer->setCustomProperty( "labeling/multilineAlign", static_cast< unsigned int >( multilineAlign ) ); - layer->setCustomProperty( "labeling/addDirectionSymbol", addDirectionSymbol ); - layer->setCustomProperty( "labeling/leftDirectionSymbol", leftDirectionSymbol ); - layer->setCustomProperty( "labeling/rightDirectionSymbol", rightDirectionSymbol ); - layer->setCustomProperty( "labeling/reverseDirectionSymbol", reverseDirectionSymbol ); - layer->setCustomProperty( "labeling/placeDirectionSymbol", static_cast< unsigned int >( placeDirectionSymbol ) ); - layer->setCustomProperty( "labeling/formatNumbers", formatNumbers ); - layer->setCustomProperty( "labeling/decimals", decimals ); - layer->setCustomProperty( "labeling/plussign", plusSign ); + layer->setCustomProperty( QStringLiteral( "labeling/wrapChar" ), wrapChar ); + layer->setCustomProperty( QStringLiteral( "labeling/multilineAlign" ), static_cast< unsigned int >( multilineAlign ) ); + layer->setCustomProperty( QStringLiteral( "labeling/addDirectionSymbol" ), addDirectionSymbol ); + layer->setCustomProperty( QStringLiteral( "labeling/leftDirectionSymbol" ), leftDirectionSymbol ); + layer->setCustomProperty( QStringLiteral( "labeling/rightDirectionSymbol" ), rightDirectionSymbol ); + layer->setCustomProperty( QStringLiteral( "labeling/reverseDirectionSymbol" ), reverseDirectionSymbol ); + layer->setCustomProperty( QStringLiteral( "labeling/placeDirectionSymbol" ), static_cast< unsigned int >( placeDirectionSymbol ) ); + layer->setCustomProperty( QStringLiteral( "labeling/formatNumbers" ), formatNumbers ); + layer->setCustomProperty( QStringLiteral( "labeling/decimals" ), decimals ); + layer->setCustomProperty( QStringLiteral( "labeling/plussign" ), plusSign ); // placement - layer->setCustomProperty( "labeling/placement", placement ); - layer->setCustomProperty( "labeling/placementFlags", static_cast< unsigned int >( placementFlags ) ); - layer->setCustomProperty( "labeling/centroidWhole", centroidWhole ); - layer->setCustomProperty( "labeling/centroidInside", centroidInside ); - layer->setCustomProperty( "labeling/predefinedPositionOrder", QgsLabelingUtils::encodePredefinedPositionOrder( predefinedPositionOrder ) ); - layer->setCustomProperty( "labeling/fitInPolygonOnly", fitInPolygonOnly ); - layer->setCustomProperty( "labeling/dist", dist ); - layer->setCustomProperty( "labeling/distInMapUnits", distInMapUnits ); - layer->setCustomProperty( "labeling/distMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( distMapUnitScale ) ); - layer->setCustomProperty( "labeling/offsetType", static_cast< unsigned int >( offsetType ) ); - layer->setCustomProperty( "labeling/quadOffset", static_cast< unsigned int >( quadOffset ) ); - layer->setCustomProperty( "labeling/xOffset", xOffset ); - layer->setCustomProperty( "labeling/yOffset", yOffset ); - layer->setCustomProperty( "labeling/labelOffsetInMapUnits", labelOffsetInMapUnits ); - layer->setCustomProperty( "labeling/labelOffsetMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( labelOffsetMapUnitScale ) ); - layer->setCustomProperty( "labeling/angleOffset", angleOffset ); - layer->setCustomProperty( "labeling/preserveRotation", preserveRotation ); - layer->setCustomProperty( "labeling/maxCurvedCharAngleIn", maxCurvedCharAngleIn ); - layer->setCustomProperty( "labeling/maxCurvedCharAngleOut", maxCurvedCharAngleOut ); - layer->setCustomProperty( "labeling/priority", priority ); - layer->setCustomProperty( "labeling/repeatDistance", repeatDistance ); - layer->setCustomProperty( "labeling/repeatDistanceUnit", repeatDistanceUnit ); - layer->setCustomProperty( "labeling/repeatDistanceMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( repeatDistanceMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/placement" ), placement ); + layer->setCustomProperty( QStringLiteral( "labeling/placementFlags" ), static_cast< unsigned int >( placementFlags ) ); + layer->setCustomProperty( QStringLiteral( "labeling/centroidWhole" ), centroidWhole ); + layer->setCustomProperty( QStringLiteral( "labeling/centroidInside" ), centroidInside ); + layer->setCustomProperty( QStringLiteral( "labeling/predefinedPositionOrder" ), QgsLabelingUtils::encodePredefinedPositionOrder( predefinedPositionOrder ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fitInPolygonOnly" ), fitInPolygonOnly ); + layer->setCustomProperty( QStringLiteral( "labeling/dist" ), dist ); + layer->setCustomProperty( QStringLiteral( "labeling/distInMapUnits" ), distInMapUnits ); + layer->setCustomProperty( QStringLiteral( "labeling/distMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( distMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/offsetType" ), static_cast< unsigned int >( offsetType ) ); + layer->setCustomProperty( QStringLiteral( "labeling/quadOffset" ), static_cast< unsigned int >( quadOffset ) ); + layer->setCustomProperty( QStringLiteral( "labeling/xOffset" ), xOffset ); + layer->setCustomProperty( QStringLiteral( "labeling/yOffset" ), yOffset ); + layer->setCustomProperty( QStringLiteral( "labeling/labelOffsetInMapUnits" ), labelOffsetInMapUnits ); + layer->setCustomProperty( QStringLiteral( "labeling/labelOffsetMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( labelOffsetMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/angleOffset" ), angleOffset ); + layer->setCustomProperty( QStringLiteral( "labeling/preserveRotation" ), preserveRotation ); + layer->setCustomProperty( QStringLiteral( "labeling/maxCurvedCharAngleIn" ), maxCurvedCharAngleIn ); + layer->setCustomProperty( QStringLiteral( "labeling/maxCurvedCharAngleOut" ), maxCurvedCharAngleOut ); + layer->setCustomProperty( QStringLiteral( "labeling/priority" ), priority ); + layer->setCustomProperty( QStringLiteral( "labeling/repeatDistance" ), repeatDistance ); + layer->setCustomProperty( QStringLiteral( "labeling/repeatDistanceUnit" ), repeatDistanceUnit ); + layer->setCustomProperty( QStringLiteral( "labeling/repeatDistanceMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( repeatDistanceMapUnitScale ) ); // rendering - layer->setCustomProperty( "labeling/scaleVisibility", scaleVisibility ); - layer->setCustomProperty( "labeling/scaleMin", scaleMin ); - layer->setCustomProperty( "labeling/scaleMax", scaleMax ); - layer->setCustomProperty( "labeling/fontLimitPixelSize", fontLimitPixelSize ); - layer->setCustomProperty( "labeling/fontMinPixelSize", fontMinPixelSize ); - layer->setCustomProperty( "labeling/fontMaxPixelSize", fontMaxPixelSize ); - layer->setCustomProperty( "labeling/displayAll", displayAll ); - layer->setCustomProperty( "labeling/upsidedownLabels", static_cast< unsigned int >( upsidedownLabels ) ); - - layer->setCustomProperty( "labeling/labelPerPart", labelPerPart ); - layer->setCustomProperty( "labeling/mergeLines", mergeLines ); - layer->setCustomProperty( "labeling/minFeatureSize", minFeatureSize ); - layer->setCustomProperty( "labeling/limitNumLabels", limitNumLabels ); - layer->setCustomProperty( "labeling/maxNumLabels", maxNumLabels ); - layer->setCustomProperty( "labeling/obstacle", obstacle ); - layer->setCustomProperty( "labeling/obstacleFactor", obstacleFactor ); - layer->setCustomProperty( "labeling/obstacleType", static_cast< unsigned int >( obstacleType ) ); - layer->setCustomProperty( "labeling/zIndex", zIndex ); + layer->setCustomProperty( QStringLiteral( "labeling/scaleVisibility" ), scaleVisibility ); + layer->setCustomProperty( QStringLiteral( "labeling/scaleMin" ), scaleMin ); + layer->setCustomProperty( QStringLiteral( "labeling/scaleMax" ), scaleMax ); + layer->setCustomProperty( QStringLiteral( "labeling/fontLimitPixelSize" ), fontLimitPixelSize ); + layer->setCustomProperty( QStringLiteral( "labeling/fontMinPixelSize" ), fontMinPixelSize ); + layer->setCustomProperty( QStringLiteral( "labeling/fontMaxPixelSize" ), fontMaxPixelSize ); + layer->setCustomProperty( QStringLiteral( "labeling/displayAll" ), displayAll ); + layer->setCustomProperty( QStringLiteral( "labeling/upsidedownLabels" ), static_cast< unsigned int >( upsidedownLabels ) ); + + layer->setCustomProperty( QStringLiteral( "labeling/labelPerPart" ), labelPerPart ); + layer->setCustomProperty( QStringLiteral( "labeling/mergeLines" ), mergeLines ); + layer->setCustomProperty( QStringLiteral( "labeling/minFeatureSize" ), minFeatureSize ); + layer->setCustomProperty( QStringLiteral( "labeling/limitNumLabels" ), limitNumLabels ); + layer->setCustomProperty( QStringLiteral( "labeling/maxNumLabels" ), maxNumLabels ); + layer->setCustomProperty( QStringLiteral( "labeling/obstacle" ), obstacle ); + layer->setCustomProperty( QStringLiteral( "labeling/obstacleFactor" ), obstacleFactor ); + layer->setCustomProperty( QStringLiteral( "labeling/obstacleType" ), static_cast< unsigned int >( obstacleType ) ); + layer->setCustomProperty( QStringLiteral( "labeling/zIndex" ), zIndex ); writeDataDefinedPropertyMap( layer, nullptr, dataDefinedProperties ); layer->emitStyleChanged(); @@ -849,106 +849,106 @@ void QgsPalLayerSettings::readXml( QDomElement& elem ) drawLabels = true; // text style - QDomElement textStyleElem = elem.firstChildElement( "text-style" ); - fieldName = textStyleElem.attribute( "fieldName" ); - isExpression = textStyleElem.attribute( "isExpression" ).toInt(); + QDomElement textStyleElem = elem.firstChildElement( QStringLiteral( "text-style" ) ); + fieldName = textStyleElem.attribute( QStringLiteral( "fieldName" ) ); + isExpression = textStyleElem.attribute( QStringLiteral( "isExpression" ) ).toInt(); mFormat.readXml( elem ); - previewBkgrdColor = QColor( textStyleElem.attribute( "previewBkgrdColor", "#ffffff" ) ); - substitutions.readXml( textStyleElem.firstChildElement( "substitutions" ) ); - useSubstitutions = textStyleElem.attribute( "useSubstitutions" ).toInt(); + previewBkgrdColor = QColor( textStyleElem.attribute( QStringLiteral( "previewBkgrdColor" ), QStringLiteral( "#ffffff" ) ) ); + substitutions.readXml( textStyleElem.firstChildElement( QStringLiteral( "substitutions" ) ) ); + useSubstitutions = textStyleElem.attribute( QStringLiteral( "useSubstitutions" ) ).toInt(); // text formatting - QDomElement textFormatElem = elem.firstChildElement( "text-format" ); - wrapChar = textFormatElem.attribute( "wrapChar" ); - multilineAlign = static_cast< MultiLineAlign >( textFormatElem.attribute( "multilineAlign", QString::number( MultiFollowPlacement ) ).toUInt() ); - addDirectionSymbol = textFormatElem.attribute( "addDirectionSymbol" ).toInt(); - leftDirectionSymbol = textFormatElem.attribute( "leftDirectionSymbol", "<" ); - rightDirectionSymbol = textFormatElem.attribute( "rightDirectionSymbol", ">" ); - reverseDirectionSymbol = textFormatElem.attribute( "reverseDirectionSymbol" ).toInt(); - placeDirectionSymbol = static_cast< DirectionSymbols >( textFormatElem.attribute( "placeDirectionSymbol", QString::number( SymbolLeftRight ) ).toUInt() ); - formatNumbers = textFormatElem.attribute( "formatNumbers" ).toInt(); - decimals = textFormatElem.attribute( "decimals" ).toInt(); - plusSign = textFormatElem.attribute( "plussign" ).toInt(); + QDomElement textFormatElem = elem.firstChildElement( QStringLiteral( "text-format" ) ); + wrapChar = textFormatElem.attribute( QStringLiteral( "wrapChar" ) ); + multilineAlign = static_cast< MultiLineAlign >( textFormatElem.attribute( QStringLiteral( "multilineAlign" ), QString::number( MultiFollowPlacement ) ).toUInt() ); + addDirectionSymbol = textFormatElem.attribute( QStringLiteral( "addDirectionSymbol" ) ).toInt(); + leftDirectionSymbol = textFormatElem.attribute( QStringLiteral( "leftDirectionSymbol" ), QStringLiteral( "<" ) ); + rightDirectionSymbol = textFormatElem.attribute( QStringLiteral( "rightDirectionSymbol" ), QStringLiteral( ">" ) ); + reverseDirectionSymbol = textFormatElem.attribute( QStringLiteral( "reverseDirectionSymbol" ) ).toInt(); + placeDirectionSymbol = static_cast< DirectionSymbols >( textFormatElem.attribute( QStringLiteral( "placeDirectionSymbol" ), QString::number( SymbolLeftRight ) ).toUInt() ); + formatNumbers = textFormatElem.attribute( QStringLiteral( "formatNumbers" ) ).toInt(); + decimals = textFormatElem.attribute( QStringLiteral( "decimals" ) ).toInt(); + plusSign = textFormatElem.attribute( QStringLiteral( "plussign" ) ).toInt(); // placement - QDomElement placementElem = elem.firstChildElement( "placement" ); - placement = static_cast< Placement >( placementElem.attribute( "placement" ).toInt() ); - placementFlags = placementElem.attribute( "placementFlags" ).toUInt(); - centroidWhole = placementElem.attribute( "centroidWhole", "0" ).toInt(); - centroidInside = placementElem.attribute( "centroidInside", "0" ).toInt(); - predefinedPositionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( placementElem.attribute( "predefinedPositionOrder" ) ); + QDomElement placementElem = elem.firstChildElement( QStringLiteral( "placement" ) ); + placement = static_cast< Placement >( placementElem.attribute( QStringLiteral( "placement" ) ).toInt() ); + placementFlags = placementElem.attribute( QStringLiteral( "placementFlags" ) ).toUInt(); + centroidWhole = placementElem.attribute( QStringLiteral( "centroidWhole" ), QStringLiteral( "0" ) ).toInt(); + centroidInside = placementElem.attribute( QStringLiteral( "centroidInside" ), QStringLiteral( "0" ) ).toInt(); + predefinedPositionOrder = QgsLabelingUtils::decodePredefinedPositionOrder( placementElem.attribute( QStringLiteral( "predefinedPositionOrder" ) ) ); if ( predefinedPositionOrder.isEmpty() ) predefinedPositionOrder = DEFAULT_PLACEMENT_ORDER; - fitInPolygonOnly = placementElem.attribute( "fitInPolygonOnly", "0" ).toInt(); - dist = placementElem.attribute( "dist" ).toDouble(); - distInMapUnits = placementElem.attribute( "distInMapUnits" ).toInt(); - if ( !placementElem.hasAttribute( "distMapUnitScale" ) ) + fitInPolygonOnly = placementElem.attribute( QStringLiteral( "fitInPolygonOnly" ), QStringLiteral( "0" ) ).toInt(); + dist = placementElem.attribute( QStringLiteral( "dist" ) ).toDouble(); + distInMapUnits = placementElem.attribute( QStringLiteral( "distInMapUnits" ) ).toInt(); + if ( !placementElem.hasAttribute( QStringLiteral( "distMapUnitScale" ) ) ) { //fallback to older property - distMapUnitScale.minScale = placementElem.attribute( "distMapUnitMinScale", "0" ).toDouble(); - distMapUnitScale.maxScale = placementElem.attribute( "distMapUnitMaxScale", "0" ).toDouble(); + distMapUnitScale.minScale = placementElem.attribute( QStringLiteral( "distMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + distMapUnitScale.maxScale = placementElem.attribute( QStringLiteral( "distMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - distMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( placementElem.attribute( "distMapUnitScale" ) ); + distMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( placementElem.attribute( QStringLiteral( "distMapUnitScale" ) ) ); } - offsetType = static_cast< OffsetType >( placementElem.attribute( "offsetType", QString::number( FromPoint ) ).toUInt() ); - quadOffset = static_cast< QuadrantPosition >( placementElem.attribute( "quadOffset", QString::number( QuadrantOver ) ).toUInt() ); - xOffset = placementElem.attribute( "xOffset", "0" ).toDouble(); - yOffset = placementElem.attribute( "yOffset", "0" ).toDouble(); - labelOffsetInMapUnits = placementElem.attribute( "labelOffsetInMapUnits", "1" ).toInt(); - if ( !placementElem.hasAttribute( "labelOffsetMapUnitScale" ) ) + offsetType = static_cast< OffsetType >( placementElem.attribute( QStringLiteral( "offsetType" ), QString::number( FromPoint ) ).toUInt() ); + quadOffset = static_cast< QuadrantPosition >( placementElem.attribute( QStringLiteral( "quadOffset" ), QString::number( QuadrantOver ) ).toUInt() ); + xOffset = placementElem.attribute( QStringLiteral( "xOffset" ), QStringLiteral( "0" ) ).toDouble(); + yOffset = placementElem.attribute( QStringLiteral( "yOffset" ), QStringLiteral( "0" ) ).toDouble(); + labelOffsetInMapUnits = placementElem.attribute( QStringLiteral( "labelOffsetInMapUnits" ), QStringLiteral( "1" ) ).toInt(); + if ( !placementElem.hasAttribute( QStringLiteral( "labelOffsetMapUnitScale" ) ) ) { //fallback to older property - labelOffsetMapUnitScale.minScale = placementElem.attribute( "labelOffsetMapUnitMinScale", "0" ).toDouble(); - labelOffsetMapUnitScale.maxScale = placementElem.attribute( "labelOffsetMapUnitMaxScale", "0" ).toDouble(); + labelOffsetMapUnitScale.minScale = placementElem.attribute( QStringLiteral( "labelOffsetMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + labelOffsetMapUnitScale.maxScale = placementElem.attribute( QStringLiteral( "labelOffsetMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - labelOffsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( placementElem.attribute( "labelOffsetMapUnitScale" ) ); + labelOffsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( placementElem.attribute( QStringLiteral( "labelOffsetMapUnitScale" ) ) ); } - angleOffset = placementElem.attribute( "angleOffset", "0" ).toDouble(); - preserveRotation = placementElem.attribute( "preserveRotation", "1" ).toInt(); - maxCurvedCharAngleIn = placementElem.attribute( "maxCurvedCharAngleIn", "25" ).toDouble(); - maxCurvedCharAngleOut = placementElem.attribute( "maxCurvedCharAngleOut", "-25" ).toDouble(); - priority = placementElem.attribute( "priority" ).toInt(); - repeatDistance = placementElem.attribute( "repeatDistance", "0" ).toDouble(); - repeatDistanceUnit = static_cast< SizeUnit >( placementElem.attribute( "repeatDistanceUnit", QString::number( MM ) ).toUInt() ); - if ( !placementElem.hasAttribute( "repeatDistanceMapUnitScale" ) ) + angleOffset = placementElem.attribute( QStringLiteral( "angleOffset" ), QStringLiteral( "0" ) ).toDouble(); + preserveRotation = placementElem.attribute( QStringLiteral( "preserveRotation" ), QStringLiteral( "1" ) ).toInt(); + maxCurvedCharAngleIn = placementElem.attribute( QStringLiteral( "maxCurvedCharAngleIn" ), QStringLiteral( "25" ) ).toDouble(); + maxCurvedCharAngleOut = placementElem.attribute( QStringLiteral( "maxCurvedCharAngleOut" ), QStringLiteral( "-25" ) ).toDouble(); + priority = placementElem.attribute( QStringLiteral( "priority" ) ).toInt(); + repeatDistance = placementElem.attribute( QStringLiteral( "repeatDistance" ), QStringLiteral( "0" ) ).toDouble(); + repeatDistanceUnit = static_cast< SizeUnit >( placementElem.attribute( QStringLiteral( "repeatDistanceUnit" ), QString::number( MM ) ).toUInt() ); + if ( !placementElem.hasAttribute( QStringLiteral( "repeatDistanceMapUnitScale" ) ) ) { //fallback to older property - repeatDistanceMapUnitScale.minScale = placementElem.attribute( "repeatDistanceMapUnitMinScale", "0" ).toDouble(); - repeatDistanceMapUnitScale.maxScale = placementElem.attribute( "repeatDistanceMapUnitMaxScale", "0" ).toDouble(); + repeatDistanceMapUnitScale.minScale = placementElem.attribute( QStringLiteral( "repeatDistanceMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + repeatDistanceMapUnitScale.maxScale = placementElem.attribute( QStringLiteral( "repeatDistanceMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - repeatDistanceMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( placementElem.attribute( "repeatDistanceMapUnitScale" ) ); + repeatDistanceMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( placementElem.attribute( QStringLiteral( "repeatDistanceMapUnitScale" ) ) ); } // rendering - QDomElement renderingElem = elem.firstChildElement( "rendering" ); - scaleMin = renderingElem.attribute( "scaleMin", "0" ).toInt(); - scaleMax = renderingElem.attribute( "scaleMax", "0" ).toInt(); - scaleVisibility = renderingElem.attribute( "scaleVisibility" ).toInt(); - - fontLimitPixelSize = renderingElem.attribute( "fontLimitPixelSize", "0" ).toInt(); - fontMinPixelSize = renderingElem.attribute( "fontMinPixelSize", "0" ).toInt(); - fontMaxPixelSize = renderingElem.attribute( "fontMaxPixelSize", "10000" ).toInt(); - displayAll = renderingElem.attribute( "displayAll", "0" ).toInt(); - upsidedownLabels = static_cast< UpsideDownLabels >( renderingElem.attribute( "upsidedownLabels", QString::number( Upright ) ).toUInt() ); - - labelPerPart = renderingElem.attribute( "labelPerPart" ).toInt(); - mergeLines = renderingElem.attribute( "mergeLines" ).toInt(); - minFeatureSize = renderingElem.attribute( "minFeatureSize" ).toDouble(); - limitNumLabels = renderingElem.attribute( "limitNumLabels", "0" ).toInt(); - maxNumLabels = renderingElem.attribute( "maxNumLabels", "2000" ).toInt(); - obstacle = renderingElem.attribute( "obstacle", "1" ).toInt(); - obstacleFactor = renderingElem.attribute( "obstacleFactor", "1" ).toDouble(); - obstacleType = static_cast< ObstacleType >( renderingElem.attribute( "obstacleType", QString::number( PolygonInterior ) ).toUInt() ); - zIndex = renderingElem.attribute( "zIndex", "0.0" ).toDouble(); - - QDomElement ddElem = elem.firstChildElement( "data-defined" ); + QDomElement renderingElem = elem.firstChildElement( QStringLiteral( "rendering" ) ); + scaleMin = renderingElem.attribute( QStringLiteral( "scaleMin" ), QStringLiteral( "0" ) ).toInt(); + scaleMax = renderingElem.attribute( QStringLiteral( "scaleMax" ), QStringLiteral( "0" ) ).toInt(); + scaleVisibility = renderingElem.attribute( QStringLiteral( "scaleVisibility" ) ).toInt(); + + fontLimitPixelSize = renderingElem.attribute( QStringLiteral( "fontLimitPixelSize" ), QStringLiteral( "0" ) ).toInt(); + fontMinPixelSize = renderingElem.attribute( QStringLiteral( "fontMinPixelSize" ), QStringLiteral( "0" ) ).toInt(); + fontMaxPixelSize = renderingElem.attribute( QStringLiteral( "fontMaxPixelSize" ), QStringLiteral( "10000" ) ).toInt(); + displayAll = renderingElem.attribute( QStringLiteral( "displayAll" ), QStringLiteral( "0" ) ).toInt(); + upsidedownLabels = static_cast< UpsideDownLabels >( renderingElem.attribute( QStringLiteral( "upsidedownLabels" ), QString::number( Upright ) ).toUInt() ); + + labelPerPart = renderingElem.attribute( QStringLiteral( "labelPerPart" ) ).toInt(); + mergeLines = renderingElem.attribute( QStringLiteral( "mergeLines" ) ).toInt(); + minFeatureSize = renderingElem.attribute( QStringLiteral( "minFeatureSize" ) ).toDouble(); + limitNumLabels = renderingElem.attribute( QStringLiteral( "limitNumLabels" ), QStringLiteral( "0" ) ).toInt(); + maxNumLabels = renderingElem.attribute( QStringLiteral( "maxNumLabels" ), QStringLiteral( "2000" ) ).toInt(); + obstacle = renderingElem.attribute( QStringLiteral( "obstacle" ), QStringLiteral( "1" ) ).toInt(); + obstacleFactor = renderingElem.attribute( QStringLiteral( "obstacleFactor" ), QStringLiteral( "1" ) ).toDouble(); + obstacleType = static_cast< ObstacleType >( renderingElem.attribute( QStringLiteral( "obstacleType" ), QString::number( PolygonInterior ) ).toUInt() ); + zIndex = renderingElem.attribute( QStringLiteral( "zIndex" ), QStringLiteral( "0.0" ) ).toDouble(); + + QDomElement ddElem = elem.firstChildElement( QStringLiteral( "data-defined" ) ); readDataDefinedPropertyMap( nullptr, &ddElem, dataDefinedProperties ); } @@ -961,78 +961,78 @@ QDomElement QgsPalLayerSettings::writeXml( QDomDocument& doc ) QDomElement textStyleElem = mFormat.writeXml( doc ); // text style - textStyleElem.setAttribute( "fieldName", fieldName ); - textStyleElem.setAttribute( "isExpression", isExpression ); - textStyleElem.setAttribute( "previewBkgrdColor", previewBkgrdColor.name() ); - QDomElement replacementElem = doc.createElement( "substitutions" ); + textStyleElem.setAttribute( QStringLiteral( "fieldName" ), fieldName ); + textStyleElem.setAttribute( QStringLiteral( "isExpression" ), isExpression ); + textStyleElem.setAttribute( QStringLiteral( "previewBkgrdColor" ), previewBkgrdColor.name() ); + QDomElement replacementElem = doc.createElement( QStringLiteral( "substitutions" ) ); substitutions.writeXml( replacementElem, doc ); textStyleElem.appendChild( replacementElem ); - textStyleElem.setAttribute( "useSubstitutions", useSubstitutions ); + textStyleElem.setAttribute( QStringLiteral( "useSubstitutions" ), useSubstitutions ); // text formatting - QDomElement textFormatElem = doc.createElement( "text-format" ); - textFormatElem.setAttribute( "wrapChar", wrapChar ); - textFormatElem.setAttribute( "multilineAlign", static_cast< unsigned int >( multilineAlign ) ); - textFormatElem.setAttribute( "addDirectionSymbol", addDirectionSymbol ); - textFormatElem.setAttribute( "leftDirectionSymbol", leftDirectionSymbol ); - textFormatElem.setAttribute( "rightDirectionSymbol", rightDirectionSymbol ); - textFormatElem.setAttribute( "reverseDirectionSymbol", reverseDirectionSymbol ); - textFormatElem.setAttribute( "placeDirectionSymbol", static_cast< unsigned int >( placeDirectionSymbol ) ); - textFormatElem.setAttribute( "formatNumbers", formatNumbers ); - textFormatElem.setAttribute( "decimals", decimals ); - textFormatElem.setAttribute( "plussign", plusSign ); + QDomElement textFormatElem = doc.createElement( QStringLiteral( "text-format" ) ); + textFormatElem.setAttribute( QStringLiteral( "wrapChar" ), wrapChar ); + textFormatElem.setAttribute( QStringLiteral( "multilineAlign" ), static_cast< unsigned int >( multilineAlign ) ); + textFormatElem.setAttribute( QStringLiteral( "addDirectionSymbol" ), addDirectionSymbol ); + textFormatElem.setAttribute( QStringLiteral( "leftDirectionSymbol" ), leftDirectionSymbol ); + textFormatElem.setAttribute( QStringLiteral( "rightDirectionSymbol" ), rightDirectionSymbol ); + textFormatElem.setAttribute( QStringLiteral( "reverseDirectionSymbol" ), reverseDirectionSymbol ); + textFormatElem.setAttribute( QStringLiteral( "placeDirectionSymbol" ), static_cast< unsigned int >( placeDirectionSymbol ) ); + textFormatElem.setAttribute( QStringLiteral( "formatNumbers" ), formatNumbers ); + textFormatElem.setAttribute( QStringLiteral( "decimals" ), decimals ); + textFormatElem.setAttribute( QStringLiteral( "plussign" ), plusSign ); // placement - QDomElement placementElem = doc.createElement( "placement" ); - placementElem.setAttribute( "placement", placement ); - placementElem.setAttribute( "placementFlags", static_cast< unsigned int >( placementFlags ) ); - placementElem.setAttribute( "centroidWhole", centroidWhole ); - placementElem.setAttribute( "centroidInside", centroidInside ); - placementElem.setAttribute( "predefinedPositionOrder", QgsLabelingUtils::encodePredefinedPositionOrder( predefinedPositionOrder ) ); - placementElem.setAttribute( "fitInPolygonOnly", fitInPolygonOnly ); - placementElem.setAttribute( "dist", dist ); - placementElem.setAttribute( "distInMapUnits", distInMapUnits ); - placementElem.setAttribute( "distMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( distMapUnitScale ) ); - placementElem.setAttribute( "offsetType", static_cast< unsigned int >( offsetType ) ); - placementElem.setAttribute( "quadOffset", static_cast< unsigned int >( quadOffset ) ); - placementElem.setAttribute( "xOffset", xOffset ); - placementElem.setAttribute( "yOffset", yOffset ); - placementElem.setAttribute( "labelOffsetInMapUnits", labelOffsetInMapUnits ); - placementElem.setAttribute( "labelOffsetMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( labelOffsetMapUnitScale ) ); - placementElem.setAttribute( "angleOffset", angleOffset ); - placementElem.setAttribute( "preserveRotation", preserveRotation ); - placementElem.setAttribute( "maxCurvedCharAngleIn", maxCurvedCharAngleIn ); - placementElem.setAttribute( "maxCurvedCharAngleOut", maxCurvedCharAngleOut ); - placementElem.setAttribute( "priority", priority ); - placementElem.setAttribute( "repeatDistance", repeatDistance ); - placementElem.setAttribute( "repeatDistanceUnit", repeatDistanceUnit ); - placementElem.setAttribute( "repeatDistanceMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( repeatDistanceMapUnitScale ) ); + QDomElement placementElem = doc.createElement( QStringLiteral( "placement" ) ); + placementElem.setAttribute( QStringLiteral( "placement" ), placement ); + placementElem.setAttribute( QStringLiteral( "placementFlags" ), static_cast< unsigned int >( placementFlags ) ); + placementElem.setAttribute( QStringLiteral( "centroidWhole" ), centroidWhole ); + placementElem.setAttribute( QStringLiteral( "centroidInside" ), centroidInside ); + placementElem.setAttribute( QStringLiteral( "predefinedPositionOrder" ), QgsLabelingUtils::encodePredefinedPositionOrder( predefinedPositionOrder ) ); + placementElem.setAttribute( QStringLiteral( "fitInPolygonOnly" ), fitInPolygonOnly ); + placementElem.setAttribute( QStringLiteral( "dist" ), dist ); + placementElem.setAttribute( QStringLiteral( "distInMapUnits" ), distInMapUnits ); + placementElem.setAttribute( QStringLiteral( "distMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( distMapUnitScale ) ); + placementElem.setAttribute( QStringLiteral( "offsetType" ), static_cast< unsigned int >( offsetType ) ); + placementElem.setAttribute( QStringLiteral( "quadOffset" ), static_cast< unsigned int >( quadOffset ) ); + placementElem.setAttribute( QStringLiteral( "xOffset" ), xOffset ); + placementElem.setAttribute( QStringLiteral( "yOffset" ), yOffset ); + placementElem.setAttribute( QStringLiteral( "labelOffsetInMapUnits" ), labelOffsetInMapUnits ); + placementElem.setAttribute( QStringLiteral( "labelOffsetMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( labelOffsetMapUnitScale ) ); + placementElem.setAttribute( QStringLiteral( "angleOffset" ), angleOffset ); + placementElem.setAttribute( QStringLiteral( "preserveRotation" ), preserveRotation ); + placementElem.setAttribute( QStringLiteral( "maxCurvedCharAngleIn" ), maxCurvedCharAngleIn ); + placementElem.setAttribute( QStringLiteral( "maxCurvedCharAngleOut" ), maxCurvedCharAngleOut ); + placementElem.setAttribute( QStringLiteral( "priority" ), priority ); + placementElem.setAttribute( QStringLiteral( "repeatDistance" ), repeatDistance ); + placementElem.setAttribute( QStringLiteral( "repeatDistanceUnit" ), repeatDistanceUnit ); + placementElem.setAttribute( QStringLiteral( "repeatDistanceMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( repeatDistanceMapUnitScale ) ); // rendering - QDomElement renderingElem = doc.createElement( "rendering" ); - renderingElem.setAttribute( "scaleVisibility", scaleVisibility ); - renderingElem.setAttribute( "scaleMin", scaleMin ); - renderingElem.setAttribute( "scaleMax", scaleMax ); - renderingElem.setAttribute( "fontLimitPixelSize", fontLimitPixelSize ); - renderingElem.setAttribute( "fontMinPixelSize", fontMinPixelSize ); - renderingElem.setAttribute( "fontMaxPixelSize", fontMaxPixelSize ); - renderingElem.setAttribute( "displayAll", displayAll ); - renderingElem.setAttribute( "upsidedownLabels", static_cast< unsigned int >( upsidedownLabels ) ); - - renderingElem.setAttribute( "labelPerPart", labelPerPart ); - renderingElem.setAttribute( "mergeLines", mergeLines ); - renderingElem.setAttribute( "minFeatureSize", minFeatureSize ); - renderingElem.setAttribute( "limitNumLabels", limitNumLabels ); - renderingElem.setAttribute( "maxNumLabels", maxNumLabels ); - renderingElem.setAttribute( "obstacle", obstacle ); - renderingElem.setAttribute( "obstacleFactor", obstacleFactor ); - renderingElem.setAttribute( "obstacleType", static_cast< unsigned int >( obstacleType ) ); - renderingElem.setAttribute( "zIndex", zIndex ); - - QDomElement ddElem = doc.createElement( "data-defined" ); + QDomElement renderingElem = doc.createElement( QStringLiteral( "rendering" ) ); + renderingElem.setAttribute( QStringLiteral( "scaleVisibility" ), scaleVisibility ); + renderingElem.setAttribute( QStringLiteral( "scaleMin" ), scaleMin ); + renderingElem.setAttribute( QStringLiteral( "scaleMax" ), scaleMax ); + renderingElem.setAttribute( QStringLiteral( "fontLimitPixelSize" ), fontLimitPixelSize ); + renderingElem.setAttribute( QStringLiteral( "fontMinPixelSize" ), fontMinPixelSize ); + renderingElem.setAttribute( QStringLiteral( "fontMaxPixelSize" ), fontMaxPixelSize ); + renderingElem.setAttribute( QStringLiteral( "displayAll" ), displayAll ); + renderingElem.setAttribute( QStringLiteral( "upsidedownLabels" ), static_cast< unsigned int >( upsidedownLabels ) ); + + renderingElem.setAttribute( QStringLiteral( "labelPerPart" ), labelPerPart ); + renderingElem.setAttribute( QStringLiteral( "mergeLines" ), mergeLines ); + renderingElem.setAttribute( QStringLiteral( "minFeatureSize" ), minFeatureSize ); + renderingElem.setAttribute( QStringLiteral( "limitNumLabels" ), limitNumLabels ); + renderingElem.setAttribute( QStringLiteral( "maxNumLabels" ), maxNumLabels ); + renderingElem.setAttribute( QStringLiteral( "obstacle" ), obstacle ); + renderingElem.setAttribute( QStringLiteral( "obstacleFactor" ), obstacleFactor ); + renderingElem.setAttribute( QStringLiteral( "obstacleType" ), static_cast< unsigned int >( obstacleType ) ); + renderingElem.setAttribute( QStringLiteral( "zIndex" ), zIndex ); + + QDomElement ddElem = doc.createElement( QStringLiteral( "data-defined" ) ); writeDataDefinedPropertyMap( nullptr, &ddElem, dataDefinedProperties ); - QDomElement elem = doc.createElement( "settings" ); + QDomElement elem = doc.createElement( QStringLiteral( "settings" ) ); elem.appendChild( textStyleElem ); elem.appendChild( textFormatElem ); elem.appendChild( placementElem ); @@ -1085,14 +1085,14 @@ QString QgsPalLayerSettings::updateDataDefinedString( const QString& value ) { // TODO: update or remove this when project settings for labeling are migrated to better XML layout QString newValue = value; - if ( !value.isEmpty() && !value.contains( "~~" ) ) + if ( !value.isEmpty() && !value.contains( QLatin1String( "~~" ) ) ) { QStringList values; - values << "1"; // all old-style values are active if not empty - values << "0"; - values << ""; + values << QStringLiteral( "1" ); // all old-style values are active if not empty + values << QStringLiteral( "0" ); + values << QLatin1String( "" ); values << value; // all old-style values are only field names - newValue = values.join( "~~" ); + newValue = values.join( QStringLiteral( "~~" ) ); } return newValue; @@ -1381,7 +1381,7 @@ void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString t if ( wrapchr.isEmpty() ) { - wrapchr = QLatin1String( "\n" ); // default to new line delimiter + wrapchr = QStringLiteral( "\n" ); // default to new line delimiter } //consider the space needed for the direction symbol @@ -1399,7 +1399,7 @@ void QgsPalLayerSettings::calculateLabelSize( const QFontMetricsF* fm, QString t } else { - text.prepend( dirSym + QLatin1String( "\n" ) ); // SymbolAbove or SymbolBelow + text.prepend( dirSym + QStringLiteral( "\n" ) ); // SymbolAbove or SymbolBelow } } @@ -1651,12 +1651,12 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont QgsDebugMsgLevel( QString( "Expression parser eval error:%1" ).arg( exp->evalErrorString() ), 4 ); return; } - labelText = result.isNull() ? "" : result.toString(); + labelText = result.isNull() ? QLatin1String( "" ) : result.toString(); } else { const QVariant &v = f.attribute( fieldIndex ); - labelText = v.isNull() ? "" : v.toString(); + labelText = v.isNull() ? QLatin1String( "" ) : v.toString(); } // apply text replacements @@ -1680,19 +1680,19 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont if ( !fcase.isEmpty() ) { - if ( fcase.compare( "NoChange", Qt::CaseInsensitive ) == 0 ) + if ( fcase.compare( QLatin1String( "NoChange" ), Qt::CaseInsensitive ) == 0 ) { capitalization = QgsStringUtils::MixedCase; } - else if ( fcase.compare( "Upper", Qt::CaseInsensitive ) == 0 ) + else if ( fcase.compare( QLatin1String( "Upper" ), Qt::CaseInsensitive ) == 0 ) { capitalization = QgsStringUtils::AllUppercase; } - else if ( fcase.compare( "Lower", Qt::CaseInsensitive ) == 0 ) + else if ( fcase.compare( QLatin1String( "Lower" ), Qt::CaseInsensitive ) == 0 ) { capitalization = QgsStringUtils::AllLowercase; } - else if ( fcase.compare( "Capitalize", Qt::CaseInsensitive ) == 0 ) + else if ( fcase.compare( QLatin1String( "Capitalize" ), Qt::CaseInsensitive ) == 0 ) { capitalization = QgsStringUtils::ForceFirstLetterToCapital; } @@ -1789,11 +1789,11 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont if ( !str.isEmpty() ) { - if ( str.compare( "Visible", Qt::CaseInsensitive ) == 0 ) + if ( str.compare( QLatin1String( "Visible" ), Qt::CaseInsensitive ) == 0 ) { wholeCentroid = false; } - else if ( str.compare( "Whole", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "Whole" ), Qt::CaseInsensitive ) == 0 ) { wholeCentroid = true; } @@ -2083,11 +2083,11 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont { QString haliString = exprVal.toString(); QgsDebugMsgLevel( QString( "exprVal Hali:%1" ).arg( haliString ), 4 ); - if ( haliString.compare( "Center", Qt::CaseInsensitive ) == 0 ) + if ( haliString.compare( QLatin1String( "Center" ), Qt::CaseInsensitive ) == 0 ) { xdiff -= labelX / 2.0; } - else if ( haliString.compare( "Right", Qt::CaseInsensitive ) == 0 ) + else if ( haliString.compare( QLatin1String( "Right" ), Qt::CaseInsensitive ) == 0 ) { xdiff -= labelX; } @@ -2099,16 +2099,16 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont QString valiString = exprVal.toString(); QgsDebugMsgLevel( QString( "exprVal Vali:%1" ).arg( valiString ), 4 ); - if ( valiString.compare( "Bottom", Qt::CaseInsensitive ) != 0 ) + if ( valiString.compare( QLatin1String( "Bottom" ), Qt::CaseInsensitive ) != 0 ) { - if ( valiString.compare( "Top", Qt::CaseInsensitive ) == 0 ) + if ( valiString.compare( QLatin1String( "Top" ), Qt::CaseInsensitive ) == 0 ) { ydiff -= labelY; } else { double descentRatio = labelFontMetrics->descent() / labelFontMetrics->height(); - if ( valiString.compare( "Base", Qt::CaseInsensitive ) == 0 ) + if ( valiString.compare( QLatin1String( "Base" ), Qt::CaseInsensitive ) == 0 ) { ydiff -= labelY * descentRatio; } @@ -2116,7 +2116,7 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont { double capHeightRatio = ( labelFontMetrics->boundingRect( 'H' ).height() + 1 + labelFontMetrics->descent() ) / labelFontMetrics->height(); ydiff -= labelY * capHeightRatio; - if ( valiString.compare( "Half", Qt::CaseInsensitive ) == 0 ) + if ( valiString.compare( QLatin1String( "Half" ), Qt::CaseInsensitive ) == 0 ) { ydiff += labelY * ( capHeightRatio - descentRatio ) / 2.0; } @@ -2412,7 +2412,7 @@ bool QgsPalLayerSettings::dataDefinedValEval( DataDefinedValueType valType, if ( dataDefinedEvaluate( p, exprVal, &context, originalValue ) ) { #ifdef QGISDEBUG - QString dbgStr = QString( "exprVal %1:" ).arg( mDataDefinedNames.value( p ).first ) + "%1"; // clazy:exclude=unused-non-trivial-variable + QString dbgStr = QStringLiteral( "exprVal %1:" ).arg( mDataDefinedNames.value( p ).first ) + "%1"; // clazy:exclude=unused-non-trivial-variable #endif switch ( valType ) @@ -2598,7 +2598,7 @@ void QgsPalLayerSettings::parseTextStyle( QFont& labelFont, // 2) Family + named style (bold or italic is ignored) // data defined font family? - QString ddFontFamily( "" ); + QString ddFontFamily( QLatin1String( "" ) ); if ( dataDefinedEvaluate( QgsPalLayerSettings::Family, exprVal, &context.expressionContext(), labelFont.family() ) ) { QString family = exprVal.toString().trimmed(); @@ -2616,7 +2616,7 @@ void QgsPalLayerSettings::parseTextStyle( QFont& labelFont, } // data defined named font style? - QString ddFontStyle( "" ); + QString ddFontStyle( QLatin1String( "" ) ); if ( dataDefinedEvaluate( QgsPalLayerSettings::FontStyle, exprVal, &context.expressionContext() ) ) { QString fontstyle = exprVal.toString().trimmed(); @@ -2656,7 +2656,7 @@ void QgsPalLayerSettings::parseTextStyle( QFont& labelFont, newFont.setItalic( ddItalic ); } else if ( !ddFontStyle.isEmpty() - && ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 ) + && ddFontStyle.compare( QLatin1String( "Ignore" ), Qt::CaseInsensitive ) != 0 ) { if ( !ddFontFamily.isEmpty() ) { @@ -2674,7 +2674,7 @@ void QgsPalLayerSettings::parseTextStyle( QFont& labelFont, } else if ( !ddFontFamily.isEmpty() ) { - if ( ddFontStyle.compare( "Ignore", Qt::CaseInsensitive ) != 0 ) + if ( ddFontStyle.compare( QLatin1String( "Ignore" ), Qt::CaseInsensitive ) != 0 ) { // just family is different, build font from database QFont styledfont = mFontDB.font( ddFontFamily, mFormat.namedStyle(), appFont.pointSize() ); @@ -2841,15 +2841,15 @@ void QgsPalLayerSettings::parseTextFormatting( QgsRenderContext &context ) // "Left" QgsPalLayerSettings::MultiLineAlign aligntype = QgsPalLayerSettings::MultiLeft; - if ( str.compare( "Center", Qt::CaseInsensitive ) == 0 ) + if ( str.compare( QLatin1String( "Center" ), Qt::CaseInsensitive ) == 0 ) { aligntype = QgsPalLayerSettings::MultiCenter; } - else if ( str.compare( "Right", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "Right" ), Qt::CaseInsensitive ) == 0 ) { aligntype = QgsPalLayerSettings::MultiRight; } - else if ( str.compare( "Follow", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "Follow" ), Qt::CaseInsensitive ) == 0 ) { aligntype = QgsPalLayerSettings::MultiFollowPlacement; } @@ -2883,11 +2883,11 @@ void QgsPalLayerSettings::parseTextFormatting( QgsRenderContext &context ) // "LeftRight" QgsPalLayerSettings::DirectionSymbols placetype = QgsPalLayerSettings::SymbolLeftRight; - if ( str.compare( "Above", Qt::CaseInsensitive ) == 0 ) + if ( str.compare( QLatin1String( "Above" ), Qt::CaseInsensitive ) == 0 ) { placetype = QgsPalLayerSettings::SymbolAbove; } - else if ( str.compare( "Below", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "Below" ), Qt::CaseInsensitive ) == 0 ) { placetype = QgsPalLayerSettings::SymbolBelow; } @@ -2948,19 +2948,19 @@ void QgsPalLayerSettings::parseShapeBackground( QgsRenderContext &context ) // "Rectangle" QgsTextBackgroundSettings::ShapeType shpkind = QgsTextBackgroundSettings::ShapeRectangle; - if ( skind.compare( "Square", Qt::CaseInsensitive ) == 0 ) + if ( skind.compare( QLatin1String( "Square" ), Qt::CaseInsensitive ) == 0 ) { shpkind = QgsTextBackgroundSettings::ShapeSquare; } - else if ( skind.compare( "Ellipse", Qt::CaseInsensitive ) == 0 ) + else if ( skind.compare( QLatin1String( "Ellipse" ), Qt::CaseInsensitive ) == 0 ) { shpkind = QgsTextBackgroundSettings::ShapeEllipse; } - else if ( skind.compare( "Circle", Qt::CaseInsensitive ) == 0 ) + else if ( skind.compare( QLatin1String( "Circle" ), Qt::CaseInsensitive ) == 0 ) { shpkind = QgsTextBackgroundSettings::ShapeCircle; } - else if ( skind.compare( "SVG", Qt::CaseInsensitive ) == 0 ) + else if ( skind.compare( QLatin1String( "SVG" ), Qt::CaseInsensitive ) == 0 ) { shpkind = QgsTextBackgroundSettings::ShapeSVG; } @@ -2993,7 +2993,7 @@ void QgsPalLayerSettings::parseShapeBackground( QgsRenderContext &context ) // "Buffer" QgsTextBackgroundSettings::SizeType sizType = QgsTextBackgroundSettings::SizeBuffer; - if ( stype.compare( "Fixed", Qt::CaseInsensitive ) == 0 ) + if ( stype.compare( QLatin1String( "Fixed" ), Qt::CaseInsensitive ) == 0 ) { sizType = QgsTextBackgroundSettings::SizeFixed; } @@ -3058,11 +3058,11 @@ void QgsPalLayerSettings::parseShapeBackground( QgsRenderContext &context ) // "Sync" QgsTextBackgroundSettings::RotationType rottype = QgsTextBackgroundSettings::RotationSync; - if ( rotstr.compare( "Offset", Qt::CaseInsensitive ) == 0 ) + if ( rotstr.compare( QLatin1String( "Offset" ), Qt::CaseInsensitive ) == 0 ) { rottype = QgsTextBackgroundSettings::RotationOffset; } - else if ( rotstr.compare( "Fixed", Qt::CaseInsensitive ) == 0 ) + else if ( rotstr.compare( QLatin1String( "Fixed" ), Qt::CaseInsensitive ) == 0 ) { rottype = QgsTextBackgroundSettings::RotationFixed; } @@ -3166,15 +3166,15 @@ void QgsPalLayerSettings::parseDropShadow( QgsRenderContext &context ) // "Lowest" QgsTextShadowSettings::ShadowPlacement shdwtype = QgsTextShadowSettings::ShadowLowest; - if ( str.compare( "Text", Qt::CaseInsensitive ) == 0 ) + if ( str.compare( QLatin1String( "Text" ), Qt::CaseInsensitive ) == 0 ) { shdwtype = QgsTextShadowSettings::ShadowText; } - else if ( str.compare( "Buffer", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "Buffer" ), Qt::CaseInsensitive ) == 0 ) { shdwtype = QgsTextShadowSettings::ShadowBuffer; } - else if ( str.compare( "Background", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "Background" ), Qt::CaseInsensitive ) == 0 ) { shdwtype = QgsTextShadowSettings::ShadowShape; } @@ -3235,9 +3235,9 @@ bool QgsPalLabeling::staticWillUseLayer( QgsVectorLayer* layer ) { // don't do QgsPalLayerSettings::readFromLayer( layer ) if not needed bool enabled = false; - if ( layer->customProperty( "labeling" ).toString() == "pal" ) + if ( layer->customProperty( QStringLiteral( "labeling" ) ).toString() == QLatin1String( "pal" ) ) enabled = layer->labelsEnabled() || layer->diagramsEnabled(); - else if ( layer->labeling()->type() == "rule-based" ) + else if ( layer->labeling()->type() == QLatin1String( "rule-based" ) ) return true; return enabled; @@ -3543,7 +3543,7 @@ void QgsPalLabeling::dataDefinedTextFormatting( QgsPalLayerSettings& tmpLyr, tmpLyr.wrapChar = ddValues.value( QgsPalLayerSettings::MultiLineWrapChar ).toString(); } - if ( !tmpLyr.wrapChar.isEmpty() || tmpLyr.getLabelExpression()->expression().contains( "wordwrap" ) ) + if ( !tmpLyr.wrapChar.isEmpty() || tmpLyr.getLabelExpression()->expression().contains( QLatin1String( "wordwrap" ) ) ) { if ( ddValues.contains( QgsPalLayerSettings::MultiLineHeight ) ) @@ -4070,14 +4070,14 @@ void QgsPalLabeling::saveEngineSettings() void QgsPalLabeling::clearEngineSettings() { - QgsProject::instance()->removeEntry( "PAL", "/SearchMethod" ); - QgsProject::instance()->removeEntry( "PAL", "/CandidatesPoint" ); - QgsProject::instance()->removeEntry( "PAL", "/CandidatesLine" ); - QgsProject::instance()->removeEntry( "PAL", "/CandidatesPolygon" ); - QgsProject::instance()->removeEntry( "PAL", "/ShowingCandidates" ); - QgsProject::instance()->removeEntry( "PAL", "/ShowingAllLabels" ); - QgsProject::instance()->removeEntry( "PAL", "/ShowingPartialsLabels" ); - QgsProject::instance()->removeEntry( "PAL", "/DrawOutlineLabels" ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/SearchMethod" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesPoint" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesLine" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/CandidatesPolygon" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingCandidates" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingAllLabels" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/ShowingPartialsLabels" ) ); + QgsProject::instance()->removeEntry( QStringLiteral( "PAL" ), QStringLiteral( "/DrawOutlineLabels" ) ); } QgsPalLabeling* QgsPalLabeling::clone() diff --git a/src/core/qgspallabeling.h b/src/core/qgspallabeling.h index f67685413d42..7230ce9475c8 100644 --- a/src/core/qgspallabeling.h +++ b/src/core/qgspallabeling.h @@ -95,8 +95,8 @@ class CORE_EXPORT QgsLabelPosition , labelRect( QgsRectangle() ) , width( 0 ) , height( 0 ) - , layerID( "" ) - , labelText( "" ) + , layerID( QLatin1String( "" ) ) + , labelText( QLatin1String( "" ) ) , labelFont( QFont() ) , upsideDown( false ) , isDiagram( false ) diff --git a/src/core/qgspoint.cpp b/src/core/qgspoint.cpp index 88915a402f78..7e4f813245c2 100644 --- a/src/core/qgspoint.cpp +++ b/src/core/qgspoint.cpp @@ -104,7 +104,7 @@ QgsVector QgsVector::normalized() const if ( len == 0.0 ) { - throw QgsException( "normalized vector of null vector undefined" ); + throw QgsException( QStringLiteral( "normalized vector of null vector undefined" ) ); } return *this / len; @@ -139,7 +139,7 @@ QString QgsPoint::toString( int thePrecision ) const { QString x = qIsFinite( m_x ) ? QString::number( m_x, 'f', thePrecision ) : QObject::tr( "infinite" ); QString y = qIsFinite( m_y ) ? QString::number( m_y, 'f', thePrecision ) : QObject::tr( "infinite" ); - return QString( "%1,%2" ).arg( x, y ); + return QStringLiteral( "%1,%2" ).arg( x, y ); } QString QgsPoint::toDegreesMinutesSeconds( int thePrecision, const bool useSuffix, const bool padded ) const @@ -238,12 +238,12 @@ QString QgsPoint::toDegreesMinutesSeconds( int thePrecision, const bool useSuffi myXHemisphere = QString(); } //pad minutes with leading digits if required - QString myMinutesX = padded ? QString( "%1" ).arg( myIntMinutesX, 2, 10, QChar( '0' ) ) : QString::number( myIntMinutesX ); - QString myMinutesY = padded ? QString( "%1" ).arg( myIntMinutesY, 2, 10, QChar( '0' ) ) : QString::number( myIntMinutesY ); + QString myMinutesX = padded ? QStringLiteral( "%1" ).arg( myIntMinutesX, 2, 10, QChar( '0' ) ) : QString::number( myIntMinutesX ); + QString myMinutesY = padded ? QStringLiteral( "%1" ).arg( myIntMinutesY, 2, 10, QChar( '0' ) ) : QString::number( myIntMinutesY ); //pad seconds with leading digits if required int digits = 2 + ( thePrecision == 0 ? 0 : 1 + thePrecision ); //1 for decimal place if required - QString myStrSecondsX = padded ? QString( "%1" ).arg( mySecondsX, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( mySecondsX, 'f', thePrecision ); - QString myStrSecondsY = padded ? QString( "%1" ).arg( mySecondsY, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( mySecondsY, 'f', thePrecision ); + QString myStrSecondsX = padded ? QStringLiteral( "%1" ).arg( mySecondsX, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( mySecondsX, 'f', thePrecision ); + QString myStrSecondsY = padded ? QStringLiteral( "%1" ).arg( mySecondsY, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( mySecondsY, 'f', thePrecision ); QString rep = myXSign + QString::number( myDegreesX ) + QChar( 176 ) + myMinutesX + QChar( 0x2032 ) + @@ -328,8 +328,8 @@ QString QgsPoint::toDegreesMinutes( int thePrecision, const bool useSuffix, cons //pad minutes with leading digits if required int digits = 2 + ( thePrecision == 0 ? 0 : 1 + thePrecision ); //1 for decimal place if required - QString myStrMinutesX = padded ? QString( "%1" ).arg( myFloatMinutesX, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( myFloatMinutesX, 'f', thePrecision ); - QString myStrMinutesY = padded ? QString( "%1" ).arg( myFloatMinutesY, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( myFloatMinutesY, 'f', thePrecision ); + QString myStrMinutesX = padded ? QStringLiteral( "%1" ).arg( myFloatMinutesX, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( myFloatMinutesX, 'f', thePrecision ); + QString myStrMinutesY = padded ? QStringLiteral( "%1" ).arg( myFloatMinutesY, digits, 'f', thePrecision, QChar( '0' ) ) : QString::number( myFloatMinutesY, 'f', thePrecision ); QString rep = myXSign + QString::number( myDegreesX ) + QChar( 176 ) + myStrMinutesX + QChar( 0x2032 ) + @@ -342,7 +342,7 @@ QString QgsPoint::toDegreesMinutes( int thePrecision, const bool useSuffix, cons QString QgsPoint::wellKnownText() const { - return QString( "POINT(%1 %2)" ).arg( qgsDoubleToString( m_x ), qgsDoubleToString( m_y ) ); + return QStringLiteral( "POINT(%1 %2)" ).arg( qgsDoubleToString( m_x ), qgsDoubleToString( m_y ) ); } double QgsPoint::sqrDist( double x, double y ) const diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 7b27b2debde4..53ca7b0f1ede 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -75,7 +75,7 @@ QStringList makeKeyTokens_( const QString& scope, const QString& key ) keyTokens += key.split( '/', QString::SkipEmptyParts ); // be sure to include the canonical root node - keyTokens.push_front( "properties" ); + keyTokens.push_front( QStringLiteral( "properties" ) ); //check validy of keys since an unvalid xml name will will be dropped upon saving the xml file. If not valid, we print a message to the console. for ( int i = 0; i < keyTokens.size(); ++i ) @@ -84,8 +84,8 @@ QStringList makeKeyTokens_( const QString& scope, const QString& key ) //invalid chars in XML are found at http://www.w3.org/TR/REC-xml/#NT-NameChar //note : it seems \x10000-\xEFFFF is valid, but it when added to the regexp, a lot of unwanted characters remain - QString nameCharRegexp = QString( "[^:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x2FF\\x370-\\x37D\\x37F-\\x1FFF\\x200C-\\x200D\\x2070-\\x218F\\x2C00-\\x2FEF\\x3001-\\xD7FF\\xF900-\\xFDCF\\xFDF0-\\xFFFD\\-\\.0-9\\xB7\\x0300-\\x036F\\x203F-\\x2040]" ); - QString nameStartCharRegexp = QString( "^[^:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x2FF\\x370-\\x37D\\x37F-\\x1FFF\\x200C-\\x200D\\x2070-\\x218F\\x2C00-\\x2FEF\\x3001-\\xD7FF\\xF900-\\xFDCF\\xFDF0-\\xFFFD]" ); + QString nameCharRegexp = QStringLiteral( "[^:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x2FF\\x370-\\x37D\\x37F-\\x1FFF\\x200C-\\x200D\\x2070-\\x218F\\x2C00-\\x2FEF\\x3001-\\xD7FF\\xF900-\\xFDCF\\xFDF0-\\xFFFD\\-\\.0-9\\xB7\\x0300-\\x036F\\x203F-\\x2040]" ); + QString nameStartCharRegexp = QStringLiteral( "^[^:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\x2FF\\x370-\\x37D\\x37F-\\x1FFF\\x200C-\\x200D\\x2070-\\x218F\\x2C00-\\x2FEF\\x3001-\\xD7FF\\xF900-\\xFDCF\\xFDF0-\\xFFFD]" ); if ( keyToken.contains( QRegExp( nameCharRegexp ) ) || keyToken.contains( QRegExp( nameStartCharRegexp ) ) ) { @@ -324,7 +324,7 @@ QgsProject::QgsProject( QObject* parent ) , mEvaluateDefaultValues( false ) , mDirty( false ) { - mProperties.setName( "properties" ); + mProperties.setName( QStringLiteral( "properties" ) ); clear(); // bind the layer tree to the map layer registry. @@ -411,7 +411,7 @@ QFileInfo QgsProject::fileInfo() const QgsCoordinateReferenceSystem QgsProject::crs() const { QgsCoordinateReferenceSystem projectCrs; - long currentCRS = readNumEntry( "SpatialRefSys", "/ProjectCRSID", -1 ); + long currentCRS = readNumEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectCRSID" ), -1 ); if ( currentCRS != -1 ) { projectCrs = QgsCoordinateReferenceSystem::fromSrsId( currentCRS ); @@ -421,20 +421,20 @@ QgsCoordinateReferenceSystem QgsProject::crs() const void QgsProject::setCrs( const QgsCoordinateReferenceSystem &crs ) { - writeEntry( "SpatialRefSys", "/ProjectCRSProj4String", crs.toProj4() ); - writeEntry( "SpatialRefSys", "/ProjectCRSID", static_cast< int >( crs.srsid() ) ); - writeEntry( "SpatialRefSys", "/ProjectCrs", crs.authid() ); + writeEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectCRSProj4String" ), crs.toProj4() ); + writeEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectCRSID" ), static_cast< int >( crs.srsid() ) ); + writeEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectCrs" ), crs.authid() ); setDirty( true ); } QString QgsProject::ellipsoid() const { - return readEntry( "Measure", "/Ellipsoid", GEO_NONE ); + return readEntry( QStringLiteral( "Measure" ), QStringLiteral( "/Ellipsoid" ), GEO_NONE ); } void QgsProject::setEllipsoid( const QString& ellipsoid ) { - writeEntry( "Measure", "/Ellipsoid", ellipsoid ); + writeEntry( QStringLiteral( "Measure" ), QStringLiteral( "/Ellipsoid" ), ellipsoid ); setDirty( true ); } @@ -459,14 +459,14 @@ void QgsProject::clear() // reset some default project properties // XXX THESE SHOULD BE MOVED TO STATUSBAR RELATED SOURCE - writeEntry( "PositionPrecision", "/Automatic", true ); - writeEntry( "PositionPrecision", "/DecimalPlaces", 2 ); - writeEntry( "Paths", "/Absolute", false ); + writeEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/Automatic" ), true ); + writeEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DecimalPlaces" ), 2 ); + writeEntry( QStringLiteral( "Paths" ), QStringLiteral( "/Absolute" ), false ); //copy default units to project QSettings s; - writeEntry( "Measurement", "/DistanceUnits", s.value( "/qgis/measure/displayunits" ).toString() ); - writeEntry( "Measurement", "/AreaUnits", s.value( "/qgis/measure/areaunits" ).toString() ); + writeEntry( QStringLiteral( "Measurement" ), QStringLiteral( "/DistanceUnits" ), s.value( QStringLiteral( "/qgis/measure/displayunits" ) ).toString() ); + writeEntry( QStringLiteral( "Measurement" ), QStringLiteral( "/AreaUnits" ), s.value( QStringLiteral( "/qgis/measure/areaunits" ) ).toString() ); setDirty( false ); } @@ -511,7 +511,7 @@ scope. "layers" is a list containing three string values. */ void _getProperties( const QDomDocument& doc, QgsPropertyKey& project_properties ) { - QDomNodeList properties = doc.elementsByTagName( "properties" ); + QDomNodeList properties = doc.elementsByTagName( QStringLiteral( "properties" ) ); if ( properties.count() > 1 ) { @@ -547,9 +547,9 @@ void _getProperties( const QDomDocument& doc, QgsPropertyKey& project_properties */ static void _getTitle( const QDomDocument& doc, QString& title ) { - QDomNodeList nl = doc.elementsByTagName( "title" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "title" ) ); - title = ""; // by default the title will be empty + title = QLatin1String( "" ); // by default the title will be empty if ( !nl.count() ) { @@ -581,7 +581,7 @@ static void _getTitle( const QDomDocument& doc, QString& title ) QgsProjectVersion getVersion( const QDomDocument& doc ) { - QDomNodeList nl = doc.elementsByTagName( "qgis" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "qgis" ) ); if ( !nl.count() ) { @@ -592,7 +592,7 @@ QgsProjectVersion getVersion( const QDomDocument& doc ) QDomNode qgisNode = nl.item( 0 ); // there should only be one, so zeroth element ok QDomElement qgisElement = qgisNode.toElement(); // qgis node should be element - QgsProjectVersion projectVersion( qgisElement.attribute( "version" ) ); + QgsProjectVersion projectVersion( qgisElement.attribute( QStringLiteral( "version" ) ) ); return projectVersion; } @@ -625,7 +625,7 @@ bool QgsProject::_getMapLayers( const QDomDocument& doc, QList& broken // Layer order is set by the restoring the legend settings from project file. // This is done on the 'readProject( ... )' signal - QDomNodeList nl = doc.elementsByTagName( "maplayer" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "maplayer" ) ); // process the map layer nodes @@ -658,13 +658,13 @@ bool QgsProject::_getMapLayers( const QDomDocument& doc, QList& broken { QDomElement element = node.toElement(); - QString name = node.namedItem( "layername" ).toElement().text(); + QString name = node.namedItem( QStringLiteral( "layername" ) ).toElement().text(); if ( !name.isNull() ) emit loadingLayer( tr( "Loading layer %1" ).arg( name ) ); - if ( element.attribute( "embedded" ) == "1" ) + if ( element.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { - createEmbeddedLayer( element.attribute( "id" ), readPath( element.attribute( "project" ) ), brokenNodes, vLayerList ); + createEmbeddedLayer( element.attribute( QStringLiteral( "id" ) ), readPath( element.attribute( QStringLiteral( "project" ) ) ), brokenNodes, vLayerList ); continue; } else @@ -701,21 +701,21 @@ bool QgsProject::_getMapLayers( const QDomDocument& doc, QList& broken bool QgsProject::addLayer( const QDomElement &layerElem, QList &brokenNodes, QList< QPair< QgsVectorLayer*, QDomElement > > &vectorLayerList ) { - QString type = layerElem.attribute( "type" ); + QString type = layerElem.attribute( QStringLiteral( "type" ) ); QgsDebugMsg( "Layer type is " + type ); QgsMapLayer *mapLayer = nullptr; - if ( type == "vector" ) + if ( type == QLatin1String( "vector" ) ) { mapLayer = new QgsVectorLayer; } - else if ( type == "raster" ) + else if ( type == QLatin1String( "raster" ) ) { mapLayer = new QgsRasterLayer; } - else if ( type == "plugin" ) + else if ( type == QLatin1String( "plugin" ) ) { - QString typeName = layerElem.attribute( "name" ); + QString typeName = layerElem.attribute( QStringLiteral( "name" ) ); mapLayer = QgsPluginLayerRegistry::instance()->createLayer( typeName ); } @@ -765,7 +765,7 @@ bool QgsProject::read() { clearError(); - QScopedPointer doc( new QDomDocument( "qgis" ) ); + QScopedPointer doc( new QDomDocument( QStringLiteral( "qgis" ) ) ); if ( !mFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { @@ -841,34 +841,34 @@ bool QgsProject::read() // now get project title _getTitle( *doc, mTitle ); - QDomNodeList nl = doc->elementsByTagName( "autotransaction" ); + QDomNodeList nl = doc->elementsByTagName( QStringLiteral( "autotransaction" ) ); if ( nl.count() ) { QDomElement transactionElement = nl.at( 0 ).toElement(); - if ( transactionElement.attribute( "active", "0" ).toInt() == 1 ) + if ( transactionElement.attribute( QStringLiteral( "active" ), QStringLiteral( "0" ) ).toInt() == 1 ) mAutoTransaction = true; } - nl = doc->elementsByTagName( "evaluateDefaultValues" ); + nl = doc->elementsByTagName( QStringLiteral( "evaluateDefaultValues" ) ); if ( nl.count() ) { QDomElement evaluateDefaultValuesElement = nl.at( 0 ).toElement(); - if ( evaluateDefaultValuesElement.attribute( "active", "0" ).toInt() == 1 ) + if ( evaluateDefaultValuesElement.attribute( QStringLiteral( "active" ), QStringLiteral( "0" ) ).toInt() == 1 ) mEvaluateDefaultValues = true; } // read the layer tree from project file - mRootGroup->setCustomProperty( "loading", 1 ); + mRootGroup->setCustomProperty( QStringLiteral( "loading" ), 1 ); - QDomElement layerTreeElem = doc->documentElement().firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = doc->documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) ); if ( !layerTreeElem.isNull() ) { mRootGroup->readChildrenFromXml( layerTreeElem ); } else { - QgsLayerTreeUtils::readOldLegend( mRootGroup, doc->documentElement().firstChildElement( "legend" ) ); + QgsLayerTreeUtils::readOldLegend( mRootGroup, doc->documentElement().firstChildElement( QStringLiteral( "legend" ) ) ); } QgsDebugMsg( "Loaded layer tree:\n " + mRootGroup->dump() ); @@ -902,7 +902,7 @@ bool QgsProject::read() // make sure the are just valid layers QgsLayerTreeUtils::removeInvalidLayers( mRootGroup ); - mRootGroup->removeCustomProperty( "loading" ); + mRootGroup->removeCustomProperty( QStringLiteral( "loading" ) ); mMapThemeCollection.reset( new QgsMapThemeCollection() ); emit mapThemeCollectionChanged(); @@ -919,8 +919,8 @@ bool QgsProject::read() emit snappingConfigChanged(); //add variables defined in project file - QStringList variableNames = readListEntry( "Variables", "/variableNames" ); - QStringList variableValues = readListEntry( "Variables", "/variableValues" ); + QStringList variableNames = readListEntry( QStringLiteral( "Variables" ), QStringLiteral( "/variableNames" ) ); + QStringList variableValues = readListEntry( QStringLiteral( "Variables" ), QStringLiteral( "/variableValues" ) ); mVariables.clear(); if ( variableNames.length() == variableValues.length() ) @@ -956,13 +956,13 @@ void QgsProject::loadEmbeddedNodes( QgsLayerTreeGroup *group ) if ( QgsLayerTree::isGroup( child ) ) { QgsLayerTreeGroup *childGroup = QgsLayerTree::toGroup( child ); - if ( childGroup->customProperty( "embedded" ).toInt() ) + if ( childGroup->customProperty( QStringLiteral( "embedded" ) ).toInt() ) { // make sure to convert the path from relative to absolute - QString projectPath = readPath( childGroup->customProperty( "embedded_project" ).toString() ); - childGroup->setCustomProperty( "embedded_project", projectPath ); + QString projectPath = readPath( childGroup->customProperty( QStringLiteral( "embedded_project" ) ).toString() ); + childGroup->setCustomProperty( QStringLiteral( "embedded_project" ), projectPath ); - QgsLayerTreeGroup *newGroup = createEmbeddedGroup( childGroup->name(), projectPath, childGroup->customProperty( "embedded-invisible-layers" ).toStringList() ); + QgsLayerTreeGroup *newGroup = createEmbeddedGroup( childGroup->name(), projectPath, childGroup->customProperty( QStringLiteral( "embedded-invisible-layers" ) ).toStringList() ); if ( newGroup ) { QList clonedChildren; @@ -980,11 +980,11 @@ void QgsProject::loadEmbeddedNodes( QgsLayerTreeGroup *group ) } else if ( QgsLayerTree::isLayer( child ) ) { - if ( child->customProperty( "embedded" ).toInt() ) + if ( child->customProperty( QStringLiteral( "embedded" ) ).toInt() ) { QList brokenNodes; QList< QPair< QgsVectorLayer*, QDomElement > > vectorLayerList; - createEmbeddedLayer( QgsLayerTree::toLayer( child )->layerId(), child->customProperty( "embedded_project" ).toString(), brokenNodes, vectorLayerList ); + createEmbeddedLayer( QgsLayerTree::toLayer( child )->layerId(), child->customProperty( QStringLiteral( "embedded_project" ) ).toString(), brokenNodes, vectorLayerList ); } } @@ -1012,8 +1012,8 @@ void QgsProject::setVariables( const QgsStringMap& variables ) variableValues << it.value(); } - writeEntry( "Variables", "/variableNames", variableNames ); - writeEntry( "Variables", "/variableValues", variableValues ); + writeEntry( QStringLiteral( "Variables" ), QStringLiteral( "/variableNames" ), variableNames ); + writeEntry( QStringLiteral( "Variables" ), QStringLiteral( "/variableValues" ), variableValues ); mVariables = variables; @@ -1022,12 +1022,12 @@ void QgsProject::setVariables( const QgsStringMap& variables ) QStringList QgsProject::avoidIntersectionsList() const { - return readListEntry( "Digitizing", "/AvoidIntersectionsList", QStringList() ); + return readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/AvoidIntersectionsList" ), QStringList() ); } void QgsProject::setAvoidIntersectionsList( const QStringList& avoidIntersectionsList ) { - writeEntry( "Digitizing", "/AvoidIntersectionsList", avoidIntersectionsList ); + writeEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/AvoidIntersectionsList" ), avoidIntersectionsList ); emit avoidIntersectionsListChanged(); } @@ -1170,26 +1170,26 @@ bool QgsProject::write() DomImplementation.setInvalidDataPolicy( QDomImplementation::DropInvalidChars ); QDomDocumentType documentType = - DomImplementation.createDocumentType( "qgis", "http://mrcc.com/qgis.dtd", - "SYSTEM" ); + DomImplementation.createDocumentType( QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), + QStringLiteral( "SYSTEM" ) ); QScopedPointer doc( new QDomDocument( documentType ) ); - QDomElement qgisNode = doc->createElement( "qgis" ); - qgisNode.setAttribute( "projectname", title() ); - qgisNode.setAttribute( "version", QString( "%1" ).arg( Qgis::QGIS_VERSION ) ); + QDomElement qgisNode = doc->createElement( QStringLiteral( "qgis" ) ); + qgisNode.setAttribute( QStringLiteral( "projectname" ), title() ); + qgisNode.setAttribute( QStringLiteral( "version" ), QStringLiteral( "%1" ).arg( Qgis::QGIS_VERSION ) ); doc->appendChild( qgisNode ); // title - QDomElement titleNode = doc->createElement( "title" ); + QDomElement titleNode = doc->createElement( QStringLiteral( "title" ) ); qgisNode.appendChild( titleNode ); - QDomElement transactionNode = doc->createElement( "autotransaction" ); - transactionNode.setAttribute( "active", mAutoTransaction ? "1" : "0" ); + QDomElement transactionNode = doc->createElement( QStringLiteral( "autotransaction" ) ); + transactionNode.setAttribute( QStringLiteral( "active" ), mAutoTransaction ? "1" : "0" ); qgisNode.appendChild( transactionNode ); - QDomElement evaluateDefaultValuesNode = doc->createElement( "evaluateDefaultValues" ); - evaluateDefaultValuesNode.setAttribute( "active", mEvaluateDefaultValues ? "1" : "0" ); + QDomElement evaluateDefaultValuesNode = doc->createElement( QStringLiteral( "evaluateDefaultValues" ) ); + evaluateDefaultValuesNode.setAttribute( QStringLiteral( "active" ), mEvaluateDefaultValues ? "1" : "0" ); qgisNode.appendChild( evaluateDefaultValuesNode ); QDomText titleText = doc->createTextNode( title() ); // XXX why have title TWICE? @@ -1212,7 +1212,7 @@ bool QgsProject::write() // Iterate over layers in zOrder // Call writeXml() on each - QDomElement projectLayersNode = doc->createElement( "projectlayers" ); + QDomElement projectLayersNode = doc->createElement( QStringLiteral( "projectlayers" ) ); QMap::ConstIterator li = layers.constBegin(); while ( li != layers.end() ) @@ -1225,7 +1225,7 @@ bool QgsProject::write() if ( emIt == mEmbeddedLayers.constEnd() ) { // general layer metadata - QDomElement maplayerElem = doc->createElement( "maplayer" ); + QDomElement maplayerElem = doc->createElement( QStringLiteral( "maplayer" ) ); ml->writeLayerXml( maplayerElem, *doc ); @@ -1239,10 +1239,10 @@ bool QgsProject::write() // only save embedded layer if not managed by a legend group if ( emIt.value().second ) { - QDomElement mapLayerElem = doc->createElement( "maplayer" ); - mapLayerElem.setAttribute( "embedded", 1 ); - mapLayerElem.setAttribute( "project", writePath( emIt.value().first ) ); - mapLayerElem.setAttribute( "id", ml->id() ); + QDomElement mapLayerElem = doc->createElement( QStringLiteral( "maplayer" ) ); + mapLayerElem.setAttribute( QStringLiteral( "embedded" ), 1 ); + mapLayerElem.setAttribute( QStringLiteral( "project" ), writePath( emIt.value().first ) ); + mapLayerElem.setAttribute( QStringLiteral( "id" ), ml->id() ); projectLayersNode.appendChild( mapLayerElem ); } } @@ -1261,7 +1261,7 @@ bool QgsProject::write() if ( !mProperties.isEmpty() ) // only worry about properties if we // actually have any properties { - mProperties.writeXml( "properties", qgisNode, *doc ); + mProperties.writeXml( QStringLiteral( "properties" ), qgisNode, *doc ); } mMapThemeCollection->writeXml( *doc ); @@ -1552,7 +1552,7 @@ void QgsProject::dumpProperties() const QString QgsProject::readPath( QString src ) const { - if ( readBoolEntry( "Paths", "/Absolute", false ) ) + if ( readBoolEntry( QStringLiteral( "Paths" ), QStringLiteral( "/Absolute" ), false ) ) { return src; } @@ -1563,14 +1563,14 @@ QString QgsProject::readPath( QString src ) const { // unfortunately qgsVsiPrefix returns prefix also for files like "/x/y/z.gz" // so we need to check if we really have the prefix - if ( src.startsWith( "/vsi", Qt::CaseInsensitive ) ) + if ( src.startsWith( QLatin1String( "/vsi" ), Qt::CaseInsensitive ) ) src.remove( 0, vsiPrefix.size() ); else vsiPrefix.clear(); } // relative path should always start with ./ or ../ - if ( !src.startsWith( "./" ) && !src.startsWith( "../" ) ) + if ( !src.startsWith( QLatin1String( "./" ) ) && !src.startsWith( QLatin1String( "../" ) ) ) { #if defined(Q_OS_WIN) if ( src.startsWith( "\\\\" ) || @@ -1639,11 +1639,11 @@ QString QgsProject::readPath( QString src ) const // append source path elements projElems << srcElems; - projElems.removeAll( "." ); + projElems.removeAll( QStringLiteral( "." ) ); // resolve .. int pos; - while (( pos = projElems.indexOf( ".." ) ) > 0 ) + while (( pos = projElems.indexOf( QStringLiteral( ".." ) ) ) > 0 ) { // remove preceding element and .. projElems.removeAt( pos - 1 ); @@ -1652,15 +1652,15 @@ QString QgsProject::readPath( QString src ) const #if !defined(Q_OS_WIN) // make path absolute - projElems.prepend( "" ); + projElems.prepend( QLatin1String( "" ) ); #endif - return vsiPrefix + projElems.join( "/" ); + return vsiPrefix + projElems.join( QStringLiteral( "/" ) ); } QString QgsProject::writePath( const QString& src, const QString& relativeBasePath ) const { - if ( readBoolEntry( "Paths", "/Absolute", false ) || src.isEmpty() ) + if ( readBoolEntry( QStringLiteral( "Paths" ), QStringLiteral( "/Absolute" ), false ) || src.isEmpty() ) { return src; } @@ -1714,8 +1714,8 @@ QString QgsProject::writePath( const QString& src, const QString& relativeBasePa // remove project file element projElems.removeLast(); - projElems.removeAll( "." ); - srcElems.removeAll( "." ); + projElems.removeAll( QStringLiteral( "." ) ); + srcElems.removeAll( QStringLiteral( "." ) ); // remove common part int n = 0; @@ -1739,17 +1739,17 @@ QString QgsProject::writePath( const QString& src, const QString& relativeBasePa // go up to the common directory for ( int i = 0; i < projElems.size(); i++ ) { - srcElems.insert( 0, ".." ); + srcElems.insert( 0, QStringLiteral( ".." ) ); } } else { // let it start with . nevertheless, // so relative path always start with either ./ or ../ - srcElems.insert( 0, "." ); + srcElems.insert( 0, QStringLiteral( "." ) ); } - return vsiPrefix + srcElems.join( "/" ); + return vsiPrefix + srcElems.join( QStringLiteral( "/" ) ); } void QgsProject::setError( const QString& errorMessage ) @@ -1816,32 +1816,32 @@ bool QgsProject::createEmbeddedLayer( const QString &layerId, const QString &pro // does project store pathes absolute or relative? bool useAbsolutePathes = true; - QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( "properties" ); + QDomElement propertiesElem = projectDocument.documentElement().firstChildElement( QStringLiteral( "properties" ) ); if ( !propertiesElem.isNull() ) { - QDomElement absElem = propertiesElem.firstChildElement( "Paths" ).firstChildElement( "Absolute" ); + QDomElement absElem = propertiesElem.firstChildElement( QStringLiteral( "Paths" ) ).firstChildElement( QStringLiteral( "Absolute" ) ); if ( !absElem.isNull() ) { - useAbsolutePathes = absElem.text().compare( "true", Qt::CaseInsensitive ) == 0; + useAbsolutePathes = absElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0; } } - QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( "projectlayers" ); + QDomElement projectLayersElem = projectDocument.documentElement().firstChildElement( QStringLiteral( "projectlayers" ) ); if ( projectLayersElem.isNull() ) { return false; } - QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( "maplayer" ); + QDomNodeList mapLayerNodes = projectLayersElem.elementsByTagName( QStringLiteral( "maplayer" ) ); for ( int i = 0; i < mapLayerNodes.size(); ++i ) { // get layer id QDomElement mapLayerElem = mapLayerNodes.at( i ).toElement(); - QString id = mapLayerElem.firstChildElement( "id" ).text(); + QString id = mapLayerElem.firstChildElement( QStringLiteral( "id" ) ).text(); if ( id == layerId ) { // layer can be embedded only once - if ( mapLayerElem.attribute( "embedded" ) == "1" ) + if ( mapLayerElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { return false; } @@ -1852,10 +1852,10 @@ bool QgsProject::createEmbeddedLayer( const QString &layerId, const QString &pro // see also QgsMapLayer::readLayerXML if ( !useAbsolutePathes ) { - QString provider( mapLayerElem.firstChildElement( "provider" ).text() ); - QDomElement dsElem( mapLayerElem.firstChildElement( "datasource" ) ); + QString provider( mapLayerElem.firstChildElement( QStringLiteral( "provider" ) ).text() ); + QDomElement dsElem( mapLayerElem.firstChildElement( QStringLiteral( "datasource" ) ) ); QString datasource( dsElem.text() ); - if ( provider == "spatialite" ) + if ( provider == QLatin1String( "spatialite" ) ) { QgsDataSourceUri uri( datasource ); QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + '/' + uri.database() ); @@ -1865,34 +1865,34 @@ bool QgsProject::createEmbeddedLayer( const QString &layerId, const QString &pro datasource = uri.uri(); } } - else if ( provider == "ogr" ) + else if ( provider == QLatin1String( "ogr" ) ) { QStringList theURIParts( datasource.split( '|' ) ); QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + '/' + theURIParts[0] ); if ( absoluteDs.exists() ) { theURIParts[0] = absoluteDs.absoluteFilePath(); - datasource = theURIParts.join( "|" ); + datasource = theURIParts.join( QStringLiteral( "|" ) ); } } - else if ( provider == "gpx" ) + else if ( provider == QLatin1String( "gpx" ) ) { QStringList theURIParts( datasource.split( '?' ) ); QFileInfo absoluteDs( QFileInfo( projectFilePath ).absolutePath() + '/' + theURIParts[0] ); if ( absoluteDs.exists() ) { theURIParts[0] = absoluteDs.absoluteFilePath(); - datasource = theURIParts.join( "?" ); + datasource = theURIParts.join( QStringLiteral( "?" ) ); } } - else if ( provider == "delimitedtext" ) + else if ( provider == QLatin1String( "delimitedtext" ) ) { QUrl urlSource( QUrl::fromEncoded( datasource.toLatin1() ) ); - if ( !datasource.startsWith( "file:" ) ) + if ( !datasource.startsWith( QLatin1String( "file:" ) ) ) { QUrl file( QUrl::fromLocalFile( datasource.left( datasource.indexOf( '?' ) ) ) ); - urlSource.setScheme( "file" ); + urlSource.setScheme( QStringLiteral( "file" ) ); urlSource.setPath( file.path() ); } @@ -1950,10 +1950,10 @@ QgsLayerTreeGroup *QgsProject::createEmbeddedGroup( const QString &groupName, co // store identify disabled layers of the embedded project QSet embeddedIdentifyDisabledLayers; - QDomElement disabledLayersElem = projectDocument.documentElement().firstChildElement( "properties" ).firstChildElement( "Identify" ).firstChildElement( "disabledLayers" ); + QDomElement disabledLayersElem = projectDocument.documentElement().firstChildElement( QStringLiteral( "properties" ) ).firstChildElement( QStringLiteral( "Identify" ) ).firstChildElement( QStringLiteral( "disabledLayers" ) ); if ( !disabledLayersElem.isNull() ) { - QDomNodeList valueList = disabledLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = disabledLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { embeddedIdentifyDisabledLayers.insert( valueList.at( i ).toElement().text() ); @@ -1962,18 +1962,18 @@ QgsLayerTreeGroup *QgsProject::createEmbeddedGroup( const QString &groupName, co QgsLayerTreeGroup *root = new QgsLayerTreeGroup; - QDomElement layerTreeElem = projectDocument.documentElement().firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = projectDocument.documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) ); if ( !layerTreeElem.isNull() ) { root->readChildrenFromXml( layerTreeElem ); } else { - QgsLayerTreeUtils::readOldLegend( root, projectDocument.documentElement().firstChildElement( "legend" ) ); + QgsLayerTreeUtils::readOldLegend( root, projectDocument.documentElement().firstChildElement( QStringLiteral( "legend" ) ) ); } QgsLayerTreeGroup *group = root->findGroup( groupName ); - if ( !group || group->customProperty( "embedded" ).toBool() ) + if ( !group || group->customProperty( QStringLiteral( "embedded" ) ).toBool() ) { // embedded groups cannot be embedded again delete root; @@ -1985,8 +1985,8 @@ QgsLayerTreeGroup *QgsProject::createEmbeddedGroup( const QString &groupName, co delete root; root = nullptr; - newGroup->setCustomProperty( "embedded", 1 ); - newGroup->setCustomProperty( "embedded_project", projectFilePath ); + newGroup->setCustomProperty( QStringLiteral( "embedded" ), 1 ); + newGroup->setCustomProperty( QStringLiteral( "embedded_project" ), projectFilePath ); // set "embedded" to all children + load embedded layers mLayerTreeRegistryBridge->setEnabled( false ); @@ -2020,7 +2020,7 @@ void QgsProject::initializeEmbeddedSubtree( const QString &projectFilePath, QgsL Q_FOREACH ( QgsLayerTreeNode *child, group->children() ) { // all nodes in the subtree will have "embedded" custom property set - child->setCustomProperty( "embedded", 1 ); + child->setCustomProperty( QStringLiteral( "embedded" ), 1 ); if ( QgsLayerTree::isGroup( child ) ) { @@ -2057,49 +2057,49 @@ void QgsProject::setEvaluateDefaultValues( bool evaluateDefaultValues ) void QgsProject::setTopologicalEditing( bool enabled ) { - QgsProject::instance()->writeEntry( "Digitizing", "/TopologicalEditing", ( enabled ? 1 : 0 ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/TopologicalEditing" ), ( enabled ? 1 : 0 ) ); emit topologicalEditingChanged(); } bool QgsProject::topologicalEditing() const { - return QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); + return QgsProject::instance()->readNumEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/TopologicalEditing" ), 0 ); } QgsUnitTypes::DistanceUnit QgsProject::distanceUnits() const { - QString distanceUnitString = QgsProject::instance()->readEntry( "Measurement", "/DistanceUnits", QString() ); + QString distanceUnitString = QgsProject::instance()->readEntry( QStringLiteral( "Measurement" ), QStringLiteral( "/DistanceUnits" ), QString() ); if ( !distanceUnitString.isEmpty() ) return QgsUnitTypes::decodeDistanceUnit( distanceUnitString ); //fallback to QGIS default measurement unit QSettings s; bool ok = false; - QgsUnitTypes::DistanceUnit type = QgsUnitTypes::decodeDistanceUnit( s.value( "/qgis/measure/displayunits" ).toString(), &ok ); + QgsUnitTypes::DistanceUnit type = QgsUnitTypes::decodeDistanceUnit( s.value( QStringLiteral( "/qgis/measure/displayunits" ) ).toString(), &ok ); return ok ? type : QgsUnitTypes::DistanceMeters; } void QgsProject::setDistanceUnits( QgsUnitTypes::DistanceUnit unit ) { - writeEntry( "Measurement", "/DistanceUnits", QgsUnitTypes::encodeUnit( unit ) ); + writeEntry( QStringLiteral( "Measurement" ), QStringLiteral( "/DistanceUnits" ), QgsUnitTypes::encodeUnit( unit ) ); } QgsUnitTypes::AreaUnit QgsProject::areaUnits() const { - QString areaUnitString = QgsProject::instance()->readEntry( "Measurement", "/AreaUnits", QString() ); + QString areaUnitString = QgsProject::instance()->readEntry( QStringLiteral( "Measurement" ), QStringLiteral( "/AreaUnits" ), QString() ); if ( !areaUnitString.isEmpty() ) return QgsUnitTypes::decodeAreaUnit( areaUnitString ); //fallback to QGIS default area unit QSettings s; bool ok = false; - QgsUnitTypes::AreaUnit type = QgsUnitTypes::decodeAreaUnit( s.value( "/qgis/measure/areaunits" ).toString(), &ok ); + QgsUnitTypes::AreaUnit type = QgsUnitTypes::decodeAreaUnit( s.value( QStringLiteral( "/qgis/measure/areaunits" ) ).toString(), &ok ); return ok ? type : QgsUnitTypes::AreaSquareMeters; } void QgsProject::setAreaUnits( QgsUnitTypes::AreaUnit unit ) { - writeEntry( "Measurement", "/AreaUnits", QgsUnitTypes::encodeUnit( unit ) ); + writeEntry( QStringLiteral( "Measurement" ), QStringLiteral( "/AreaUnits" ), QgsUnitTypes::encodeUnit( unit ) ); } QString QgsProject::homePath() const @@ -2151,14 +2151,14 @@ void QgsProject::setNonIdentifiableLayers( const QList& layers ) void QgsProject::setNonIdentifiableLayers( const QStringList& layerIds ) { - writeEntry( "Identify", "/disabledLayers", layerIds ); + writeEntry( QStringLiteral( "Identify" ), QStringLiteral( "/disabledLayers" ), layerIds ); emit nonIdentifiableLayersChanged( layerIds ); } QStringList QgsProject::nonIdentifiableLayers() const { - return QgsProject::instance()->readListEntry( "Identify", "/disabledLayers" ); + return QgsProject::instance()->readListEntry( QStringLiteral( "Identify" ), QStringLiteral( "/disabledLayers" ) ); } bool QgsProject::autoTransaction() const diff --git a/src/core/qgsprojectbadlayerhandler.cpp b/src/core/qgsprojectbadlayerhandler.cpp index f4f42abe76be..953487387c9e 100644 --- a/src/core/qgsprojectbadlayerhandler.cpp +++ b/src/core/qgsprojectbadlayerhandler.cpp @@ -21,10 +21,10 @@ void QgsProjectBadLayerHandler::handleBadLayers( const QList& layers ) { - QgsMessageLog::instance()->logMessage( QString( "%1 bad layers dismissed:" ).arg( layers.size() ) ); + QgsMessageLog::instance()->logMessage( QStringLiteral( "%1 bad layers dismissed:" ).arg( layers.size() ) ); Q_FOREACH ( const QDomNode& layer, layers ) { - QgsMessageLog::instance()->logMessage( QString( " * %1" ).arg( dataSource( layer ) ) ); + QgsMessageLog::instance()->logMessage( QStringLiteral( " * %1" ).arg( dataSource( layer ) ) ); } } @@ -34,7 +34,7 @@ QgsProjectBadLayerHandler::~QgsProjectBadLayerHandler() QgsProjectBadLayerHandler::DataType QgsProjectBadLayerHandler::dataType( const QDomNode& layerNode ) { - QString type = layerNode.toElement().attribute( "type" ); + QString type = layerNode.toElement().attribute( QStringLiteral( "type" ) ); if ( QString::null == type ) { @@ -63,7 +63,7 @@ QgsProjectBadLayerHandler::DataType QgsProjectBadLayerHandler::dataType( const Q QString QgsProjectBadLayerHandler::dataSource( const QDomNode& layerNode ) { - QDomNode dataSourceNode = layerNode.namedItem( "datasource" ); + QDomNode dataSourceNode = layerNode.namedItem( QStringLiteral( "datasource" ) ); if ( dataSourceNode.isNull() ) { @@ -87,11 +87,11 @@ QgsProjectBadLayerHandler::ProviderType QgsProjectBadLayerHandler::providerType( QgsDebugMsg( "datasource is " + ds ); - if ( ds.contains( "host=" ) ) + if ( ds.contains( QLatin1String( "host=" ) ) ) { return IS_URL; } - else if ( ds.contains( "dbname=" ) ) + else if ( ds.contains( QLatin1String( "dbname=" ) ) ) { return IS_DATABASE; } @@ -114,7 +114,7 @@ QgsProjectBadLayerHandler::ProviderType QgsProjectBadLayerHandler::providerType( void QgsProjectBadLayerHandler::setDataSource( QDomNode& layerNode, const QString& dataSource ) { - QDomNode dataSourceNode = layerNode.namedItem( "datasource" ); + QDomNode dataSourceNode = layerNode.namedItem( QStringLiteral( "datasource" ) ); QDomElement dataSourceElement = dataSourceNode.toElement(); QDomText dataSourceText = dataSourceElement.firstChild().toText(); diff --git a/src/core/qgsprojectfiletransform.cpp b/src/core/qgsprojectfiletransform.cpp index c7c25c32cd73..8551f724fc16 100644 --- a/src/core/qgsprojectfiletransform.cpp +++ b/src/core/qgsprojectfiletransform.cpp @@ -108,28 +108,28 @@ void QgsProjectFileTransform::transform081to090() QDomElement mapCanvas; // A null element. // there should only be one - QDomNode qgis = mDom.firstChildElement( "qgis" ); + QDomNode qgis = mDom.firstChildElement( QStringLiteral( "qgis" ) ); if ( ! qgis.isNull() ) { QgsDebugMsg( "Populating new mapcanvas" ); // Create a mapcanvas - mapCanvas = mDom.createElement( "mapcanvas" ); + mapCanvas = mDom.createElement( QStringLiteral( "mapcanvas" ) ); // Append mapcanvas to parent 'qgis'. qgis.appendChild( mapCanvas ); // Re-parent units - mapCanvas.appendChild( qgis.namedItem( "units" ) ); + mapCanvas.appendChild( qgis.namedItem( QStringLiteral( "units" ) ) ); // Re-parent extent - mapCanvas.appendChild( qgis.namedItem( "extent" ) ); + mapCanvas.appendChild( qgis.namedItem( QStringLiteral( "extent" ) ) ); // See if we can find if projection is on. - QDomElement properties = qgis.firstChildElement( "properties" ); - QDomElement spatial = properties.firstChildElement( "SpatialRefSys" ); - QDomElement hasCrsTransformEnabled = spatial.firstChildElement( "ProjectionsEnabled" ); + QDomElement properties = qgis.firstChildElement( QStringLiteral( "properties" ) ); + QDomElement spatial = properties.firstChildElement( QStringLiteral( "SpatialRefSys" ) ); + QDomElement hasCrsTransformEnabled = spatial.firstChildElement( QStringLiteral( "ProjectionsEnabled" ) ); // Type is 'int', and '1' if on. // Create an element - QDomElement projection = mDom.createElement( "projections" ); + QDomElement projection = mDom.createElement( QStringLiteral( "projections" ) ); QgsDebugMsg( QString( "Projection flag: " ) + hasCrsTransformEnabled.text() ); // Set flag from ProjectionsEnabled projection.appendChild( mDom.createTextNode( hasCrsTransformEnabled.text() ) ); @@ -141,17 +141,17 @@ void QgsProjectFileTransform::transform081to090() // Transforming coordinate-transforms // Create a list of all map layers - QDomNodeList mapLayers = mDom.elementsByTagName( "maplayer" ); + QDomNodeList mapLayers = mDom.elementsByTagName( QStringLiteral( "maplayer" ) ); bool doneDestination = false; for ( int i = 0; i < mapLayers.count(); i++ ) { QDomNode mapLayer = mapLayers.item( i ); // Find the coordinatetransform - QDomNode coordinateTransform = mapLayer.namedItem( "coordinatetransform" ); + QDomNode coordinateTransform = mapLayer.namedItem( QStringLiteral( "coordinatetransform" ) ); // Find the sourcesrs - QDomNode sourceCrs = coordinateTransform.namedItem( "sourcesrs" ); + QDomNode sourceCrs = coordinateTransform.namedItem( QStringLiteral( "sourcesrs" ) ); // Rename to srs - sourceCrs.toElement().setTagName( "srs" ); + sourceCrs.toElement().setTagName( QStringLiteral( "srs" ) ); // Re-parent to maplayer mapLayer.appendChild( sourceCrs ); // Re-move coordinatetransform @@ -159,7 +159,7 @@ void QgsProjectFileTransform::transform081to090() if ( ! doneDestination ) { // Use destination CRS from the last layer - QDomNode destinationCRS = coordinateTransform.namedItem( "destinationsrs" ); + QDomNode destinationCRS = coordinateTransform.namedItem( QStringLiteral( "destinationsrs" ) ); // Re-parent the destination CRS to the mapcanvas // If mapcanvas wasn't set, nothing will happen. mapCanvas.appendChild( destinationCRS ); @@ -173,29 +173,29 @@ void QgsProjectFileTransform::transform081to090() } // Set the flag 'visible' to match the status of 'checked' - QDomNodeList legendLayerFiles = mDom.elementsByTagName( "legendlayerfile" ); + QDomNodeList legendLayerFiles = mDom.elementsByTagName( QStringLiteral( "legendlayerfile" ) ); QgsDebugMsg( QString( "Legend layer file entries: " ) + QString::number( legendLayerFiles.count() ) ); for ( int i = 0; i < mapLayers.count(); i++ ) { // Get one maplayer element from list QDomElement mapLayer = mapLayers.item( i ).toElement(); // Find it's id. - QString id = mapLayer.firstChildElement( "id" ).text(); + QString id = mapLayer.firstChildElement( QStringLiteral( "id" ) ).text(); QgsDebugMsg( QString( "Handling layer " + id ) ); // Now, look it up in legend for ( int j = 0; j < legendLayerFiles.count(); j++ ) { QDomElement legendLayerFile = legendLayerFiles.item( j ).toElement(); - if ( id == legendLayerFile.attribute( "layerid" ) ) + if ( id == legendLayerFile.attribute( QStringLiteral( "layerid" ) ) ) { // Found a the legend layer that matches the maplayer QgsDebugMsg( "Found matching id" ); // Set visible flag from maplayer to legendlayer - legendLayerFile.setAttribute( "visible", mapLayer.attribute( "visible" ) ); + legendLayerFile.setAttribute( QStringLiteral( "visible" ), mapLayer.attribute( QStringLiteral( "visible" ) ) ); // Set overview flag from maplayer to legendlayer - legendLayerFile.setAttribute( "isInOverview", mapLayer.attribute( "showInOverviewFlag" ) ); + legendLayerFile.setAttribute( QStringLiteral( "isInOverview" ), mapLayer.attribute( QStringLiteral( "showInOverviewFlag" ) ) ); } } } @@ -209,7 +209,7 @@ void QgsProjectFileTransform::transform091to0100() if ( ! mDom.isNull() ) { // Insert transforms here! - QDomNodeList rasterPropertyList = mDom.elementsByTagName( "rasterproperties" ); + QDomNodeList rasterPropertyList = mDom.elementsByTagName( QStringLiteral( "rasterproperties" ) ); QgsDebugMsg( QString( "Raster properties file entries: " ) + QString::number( rasterPropertyList.count() ) ); for ( int i = 0; i < rasterPropertyList.count(); i++ ) { @@ -217,30 +217,30 @@ void QgsProjectFileTransform::transform091to0100() QDomNode rasterProperty = rasterPropertyList.item( i ); // rasterProperty.namedItem("").toElement().setTagName(""); - rasterProperty.namedItem( "stdDevsToPlotDouble" ).toElement().setTagName( "mStandardDeviations" ); + rasterProperty.namedItem( QStringLiteral( "stdDevsToPlotDouble" ) ).toElement().setTagName( QStringLiteral( "mStandardDeviations" ) ); - rasterProperty.namedItem( "invertHistogramFlag" ).toElement().setTagName( "mInvertPixelsFlag" ); - rasterProperty.namedItem( "showDebugOverLayFlag" ).toElement().setTagName( "mDebugOverLayFlag" ); + rasterProperty.namedItem( QStringLiteral( "invertHistogramFlag" ) ).toElement().setTagName( QStringLiteral( "mInvertPixelsFlag" ) ); + rasterProperty.namedItem( QStringLiteral( "showDebugOverLayFlag" ) ).toElement().setTagName( QStringLiteral( "mDebugOverLayFlag" ) ); - rasterProperty.namedItem( "redBandNameQString" ).toElement().setTagName( "mRedBandName" ); - rasterProperty.namedItem( "blueBandNameQString" ).toElement().setTagName( "mBlueBandName" ); - rasterProperty.namedItem( "greenBandNameQString" ).toElement().setTagName( "mGreenBandName" ); - rasterProperty.namedItem( "grayBandNameQString" ).toElement().setTagName( "mGrayBandName" ); + rasterProperty.namedItem( QStringLiteral( "redBandNameQString" ) ).toElement().setTagName( QStringLiteral( "mRedBandName" ) ); + rasterProperty.namedItem( QStringLiteral( "blueBandNameQString" ) ).toElement().setTagName( QStringLiteral( "mBlueBandName" ) ); + rasterProperty.namedItem( QStringLiteral( "greenBandNameQString" ) ).toElement().setTagName( QStringLiteral( "mGreenBandName" ) ); + rasterProperty.namedItem( QStringLiteral( "grayBandNameQString" ) ).toElement().setTagName( QStringLiteral( "mGrayBandName" ) ); } // Changing symbol size for hard: symbols - QDomNodeList symbolPropertyList = mDom.elementsByTagName( "symbol" ); + QDomNodeList symbolPropertyList = mDom.elementsByTagName( QStringLiteral( "symbol" ) ); for ( int i = 0; i < symbolPropertyList.count(); i++ ) { // Get the to check for 'hard:' for each QDomNode symbolProperty = symbolPropertyList.item( i ); - QDomElement pointSymbol = symbolProperty.firstChildElement( "pointsymbol" ); - if ( pointSymbol.text().startsWith( "hard:" ) ) + QDomElement pointSymbol = symbolProperty.firstChildElement( QStringLiteral( "pointsymbol" ) ); + if ( pointSymbol.text().startsWith( QLatin1String( "hard:" ) ) ) { // Get pointsize and line width - int lineWidth = symbolProperty.firstChildElement( "outlinewidth" ).text().toInt(); - int pointSize = symbolProperty.firstChildElement( "pointsize" ).text().toInt(); + int lineWidth = symbolProperty.firstChildElement( QStringLiteral( "outlinewidth" ) ).text().toInt(); + int pointSize = symbolProperty.firstChildElement( QStringLiteral( "pointsize" ) ).text().toInt(); // Just a precaution, checking for 0 if ( pointSize != 0 ) { @@ -249,7 +249,7 @@ void QgsProjectFileTransform::transform091to0100() // where '2r' is the old size. pointSize = pointSize + 2 + 2 * lineWidth; QgsDebugMsg( QString( "Setting point size to %1" ).arg( pointSize ) ); - QDomElement newPointSizeProperty = mDom.createElement( "pointsize" ); + QDomElement newPointSizeProperty = mDom.createElement( QStringLiteral( "pointsize" ) ); QDomText newPointSizeTxt = mDom.createTextNode( QString::number( pointSize ) ); newPointSizeProperty.appendChild( newPointSizeTxt ); symbolProperty.replaceChild( newPointSizeProperty, pointSymbol ); @@ -271,7 +271,7 @@ void QgsProjectFileTransform::transform0100to0110() int screenDpi = myPrinter.resolution(); double widthScaleFactor = 25.4 / screenDpi; - QDomNodeList outlineWidthList = mDom.elementsByTagName( "outlinewidth" ); + QDomNodeList outlineWidthList = mDom.elementsByTagName( QStringLiteral( "outlinewidth" ) ); for ( int i = 0; i < outlineWidthList.size(); ++i ) { //calculate new width @@ -287,7 +287,7 @@ void QgsProjectFileTransform::transform0100to0110() } //Change 'pointsize' in QgsSymbol - QDomNodeList pointSizeList = mDom.elementsByTagName( "pointsize" ); + QDomNodeList pointSizeList = mDom.elementsByTagName( QStringLiteral( "pointsize" ) ); for ( int i = 0; i < pointSizeList.size(); ++i ) { //calculate new size @@ -307,18 +307,18 @@ void QgsProjectFileTransform::transform0110to1000() { if ( ! mDom.isNull() ) { - QDomNodeList layerList = mDom.elementsByTagName( "maplayer" ); + QDomNodeList layerList = mDom.elementsByTagName( QStringLiteral( "maplayer" ) ); for ( int i = 0; i < layerList.size(); ++i ) { QDomElement layerElem = layerList.at( i ).toElement(); - QString typeString = layerElem.attribute( "type" ); - if ( typeString != "vector" ) + QString typeString = layerElem.attribute( QStringLiteral( "type" ) ); + if ( typeString != QLatin1String( "vector" ) ) { continue; } //datasource - QDomNode dataSourceNode = layerElem.namedItem( "datasource" ); + QDomNode dataSourceNode = layerElem.namedItem( QStringLiteral( "datasource" ) ); if ( dataSourceNode.isNull() ) { return; @@ -326,7 +326,7 @@ void QgsProjectFileTransform::transform0110to1000() QString dataSource = dataSourceNode.toElement().text(); //provider key - QDomNode providerNode = layerElem.namedItem( "provider" ); + QDomNode providerNode = layerElem.namedItem( QStringLiteral( "provider" ) ); if ( providerNode.isNull() ) { return; @@ -334,7 +334,7 @@ void QgsProjectFileTransform::transform0110to1000() QString providerKey = providerNode.toElement().text(); //create the layer to get the provider for int->fieldName conversion - QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, "", providerKey, false ); + QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, QLatin1String( "" ), providerKey, false ); if ( !theLayer->isValid() ) { delete theLayer; @@ -349,7 +349,7 @@ void QgsProjectFileTransform::transform0110to1000() QgsFields theFields = theProvider->fields(); //read classificationfield - QDomNodeList classificationFieldList = layerElem.elementsByTagName( "classificationfield" ); + QDomNodeList classificationFieldList = layerElem.elementsByTagName( QStringLiteral( "classificationfield" ) ); for ( int j = 0; j < classificationFieldList.size(); ++j ) { QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement(); @@ -372,32 +372,32 @@ void QgsProjectFileTransform::transform1100to1200() if ( mDom.isNull() ) return; - QDomNode qgis = mDom.firstChildElement( "qgis" ); + QDomNode qgis = mDom.firstChildElement( QStringLiteral( "qgis" ) ); if ( qgis.isNull() ) return; - QDomElement properties = qgis.firstChildElement( "properties" ); + QDomElement properties = qgis.firstChildElement( QStringLiteral( "properties" ) ); if ( properties.isNull() ) return; - QDomElement digitizing = properties.firstChildElement( "Digitizing" ); + QDomElement digitizing = properties.firstChildElement( QStringLiteral( "Digitizing" ) ); if ( digitizing.isNull() ) return; - QDomElement tolList = digitizing.firstChildElement( "LayerSnappingToleranceList" ); + QDomElement tolList = digitizing.firstChildElement( QStringLiteral( "LayerSnappingToleranceList" ) ); if ( tolList.isNull() ) return; - QDomElement tolUnitList = digitizing.firstChildElement( "LayerSnappingToleranceUnitList" ); + QDomElement tolUnitList = digitizing.firstChildElement( QStringLiteral( "LayerSnappingToleranceUnitList" ) ); if ( !tolUnitList.isNull() ) return; QStringList units; for ( int i = 0; i < tolList.childNodes().count(); i++ ) - units << "0"; + units << QStringLiteral( "0" ); QgsPropertyValue value( units ); - value.writeXml( "LayerSnappingToleranceUnitList", digitizing, mDom ); + value.writeXml( QStringLiteral( "LayerSnappingToleranceUnitList" ), digitizing, mDom ); } void QgsProjectFileTransform::transform1400to1500() @@ -408,7 +408,7 @@ void QgsProjectFileTransform::transform1400to1500() return; } //Add layer id to - QDomNodeList layerItemList = mDom.elementsByTagName( "LayerItem" ); + QDomNodeList layerItemList = mDom.elementsByTagName( QStringLiteral( "LayerItem" ) ); QDomElement currentLayerItemElem; QString currentLayerId; @@ -419,21 +419,21 @@ void QgsProjectFileTransform::transform1400to1500() { continue; } - currentLayerId = currentLayerItemElem.attribute( "layerId" ); + currentLayerId = currentLayerItemElem.attribute( QStringLiteral( "layerId" ) ); - QDomNodeList vectorClassificationList = currentLayerItemElem.elementsByTagName( "VectorClassificationItem" ); + QDomNodeList vectorClassificationList = currentLayerItemElem.elementsByTagName( QStringLiteral( "VectorClassificationItem" ) ); QDomElement currentClassificationElem; for ( int j = 0; j < vectorClassificationList.size(); ++j ) { currentClassificationElem = vectorClassificationList.at( j ).toElement(); if ( !currentClassificationElem.isNull() ) { - currentClassificationElem.setAttribute( "layerId", currentLayerId ); + currentClassificationElem.setAttribute( QStringLiteral( "layerId" ), currentLayerId ); } } //replace the text items with VectorClassification or RasterClassification items - QDomNodeList textItemList = currentLayerItemElem.elementsByTagName( "TextItem" ); + QDomNodeList textItemList = currentLayerItemElem.elementsByTagName( QStringLiteral( "TextItem" ) ); QDomElement currentTextItem; for ( int j = 0; j < textItemList.size(); ++j ) @@ -447,15 +447,15 @@ void QgsProjectFileTransform::transform1400to1500() QDomElement classificationElement; if ( !vectorClassificationList.isEmpty() ) //we guess it is a vector layer { - classificationElement = mDom.createElement( "VectorClassificationItem" ); + classificationElement = mDom.createElement( QStringLiteral( "VectorClassificationItem" ) ); } else { - classificationElement = mDom.createElement( "RasterClassificationItem" ); + classificationElement = mDom.createElement( QStringLiteral( "RasterClassificationItem" ) ); } - classificationElement.setAttribute( "layerId", currentLayerId ); - classificationElement.setAttribute( "text", currentTextItem.attribute( "text" ) ); + classificationElement.setAttribute( QStringLiteral( "layerId" ), currentLayerId ); + classificationElement.setAttribute( QStringLiteral( "text" ), currentTextItem.attribute( QStringLiteral( "text" ) ) ); currentLayerItemElem.replaceChild( classificationElement, currentTextItem ); } } @@ -468,13 +468,13 @@ void QgsProjectFileTransform::transform1800to1900() return; } - QDomNodeList layerItemList = mDom.elementsByTagName( "rasterproperties" ); + QDomNodeList layerItemList = mDom.elementsByTagName( QStringLiteral( "rasterproperties" ) ); for ( int i = 0; i < layerItemList.size(); ++i ) { QDomElement rasterPropertiesElem = layerItemList.at( i ).toElement(); QDomNode layerNode = rasterPropertiesElem.parentNode(); - QDomElement dataSourceElem = layerNode.firstChildElement( "datasource" ); - QDomElement layerNameElem = layerNode.firstChildElement( "layername" ); + QDomElement dataSourceElem = layerNode.firstChildElement( QStringLiteral( "datasource" ) ); + QDomElement layerNameElem = layerNode.firstChildElement( QStringLiteral( "layername" ) ); QgsRasterLayer rasterLayer; // TODO: We have to use more data from project file to read the layer it correctly, // OTOH, we should not read it until it was converted @@ -484,67 +484,67 @@ void QgsProjectFileTransform::transform1800to1900() //composer: replace mGridAnnotationPosition with mLeftGridAnnotationPosition & co. // and mGridAnnotationDirection with mLeftGridAnnotationDirection & co. - QDomNodeList composerMapList = mDom.elementsByTagName( "ComposerMap" ); + QDomNodeList composerMapList = mDom.elementsByTagName( QStringLiteral( "ComposerMap" ) ); for ( int i = 0; i < composerMapList.size(); ++i ) { - QDomNodeList gridList = composerMapList.at( i ).toElement().elementsByTagName( "Grid" ); + QDomNodeList gridList = composerMapList.at( i ).toElement().elementsByTagName( QStringLiteral( "Grid" ) ); for ( int j = 0; j < gridList.size(); ++j ) { - QDomNodeList annotationList = gridList.at( j ).toElement().elementsByTagName( "Annotation" ); + QDomNodeList annotationList = gridList.at( j ).toElement().elementsByTagName( QStringLiteral( "Annotation" ) ); for ( int k = 0; k < annotationList.size(); ++k ) { QDomElement annotationElem = annotationList.at( k ).toElement(); //position - if ( annotationElem.hasAttribute( "position" ) ) + if ( annotationElem.hasAttribute( QStringLiteral( "position" ) ) ) { - int pos = annotationElem.attribute( "position" ).toInt(); - annotationElem.setAttribute( "leftPosition", pos ); - annotationElem.setAttribute( "rightPosition", pos ); - annotationElem.setAttribute( "topPosition", pos ); - annotationElem.setAttribute( "bottomPosition", pos ); - annotationElem.removeAttribute( "position" ); + int pos = annotationElem.attribute( QStringLiteral( "position" ) ).toInt(); + annotationElem.setAttribute( QStringLiteral( "leftPosition" ), pos ); + annotationElem.setAttribute( QStringLiteral( "rightPosition" ), pos ); + annotationElem.setAttribute( QStringLiteral( "topPosition" ), pos ); + annotationElem.setAttribute( QStringLiteral( "bottomPosition" ), pos ); + annotationElem.removeAttribute( QStringLiteral( "position" ) ); } //direction - if ( annotationElem.hasAttribute( "direction" ) ) + if ( annotationElem.hasAttribute( QStringLiteral( "direction" ) ) ) { - int dir = annotationElem.attribute( "direction" ).toInt(); + int dir = annotationElem.attribute( QStringLiteral( "direction" ) ).toInt(); if ( dir == 2 ) { - annotationElem.setAttribute( "leftDirection", 0 ); - annotationElem.setAttribute( "rightDirection", 0 ); - annotationElem.setAttribute( "topDirection", 1 ); - annotationElem.setAttribute( "bottomDirection", 1 ); + annotationElem.setAttribute( QStringLiteral( "leftDirection" ), 0 ); + annotationElem.setAttribute( QStringLiteral( "rightDirection" ), 0 ); + annotationElem.setAttribute( QStringLiteral( "topDirection" ), 1 ); + annotationElem.setAttribute( QStringLiteral( "bottomDirection" ), 1 ); } else if ( dir == 3 ) { - annotationElem.setAttribute( "leftDirection", 1 ); - annotationElem.setAttribute( "rightDirection", 1 ); - annotationElem.setAttribute( "topDirection", 0 ); - annotationElem.setAttribute( "bottomDirection", 0 ); + annotationElem.setAttribute( QStringLiteral( "leftDirection" ), 1 ); + annotationElem.setAttribute( QStringLiteral( "rightDirection" ), 1 ); + annotationElem.setAttribute( QStringLiteral( "topDirection" ), 0 ); + annotationElem.setAttribute( QStringLiteral( "bottomDirection" ), 0 ); } else { - annotationElem.setAttribute( "leftDirection", dir ); - annotationElem.setAttribute( "rightDirection", dir ); - annotationElem.setAttribute( "topDirection", dir ); - annotationElem.setAttribute( "bottomDirection", dir ); + annotationElem.setAttribute( QStringLiteral( "leftDirection" ), dir ); + annotationElem.setAttribute( QStringLiteral( "rightDirection" ), dir ); + annotationElem.setAttribute( QStringLiteral( "topDirection" ), dir ); + annotationElem.setAttribute( QStringLiteral( "bottomDirection" ), dir ); } - annotationElem.removeAttribute( "direction" ); + annotationElem.removeAttribute( QStringLiteral( "direction" ) ); } } } } //Composer: move all items under Composition element - QDomNodeList composerList = mDom.elementsByTagName( "Composer" ); + QDomNodeList composerList = mDom.elementsByTagName( QStringLiteral( "Composer" ) ); for ( int i = 0; i < composerList.size(); ++i ) { QDomElement composerElem = composerList.at( i ).toElement(); //find = 0; --j ) { QDomElement childElem = composerChildren.at( j ).toElement(); - if ( childElem.tagName() == "Composition" ) + if ( childElem.tagName() == QLatin1String( "Composition" ) ) { continue; } @@ -574,22 +574,22 @@ void QgsProjectFileTransform::transform1800to1900() // SimpleFill symbol layer v2: avoid double transparency // replacing alpha value of symbol layer's color with 255 (the // transparency value is already stored as symbol transparency). - QDomNodeList rendererList = mDom.elementsByTagName( "renderer-v2" ); + QDomNodeList rendererList = mDom.elementsByTagName( QStringLiteral( "renderer-v2" ) ); for ( int i = 0; i < rendererList.size(); ++i ) { - QDomNodeList layerList = rendererList.at( i ).toElement().elementsByTagName( "layer" ); + QDomNodeList layerList = rendererList.at( i ).toElement().elementsByTagName( QStringLiteral( "layer" ) ); for ( int j = 0; j < layerList.size(); ++j ) { QDomElement layerElem = layerList.at( j ).toElement(); - if ( layerElem.attribute( "class" ) == "SimpleFill" ) + if ( layerElem.attribute( QStringLiteral( "class" ) ) == QLatin1String( "SimpleFill" ) ) { - QDomNodeList propList = layerElem.elementsByTagName( "prop" ); + QDomNodeList propList = layerElem.elementsByTagName( QStringLiteral( "prop" ) ); for ( int k = 0; k < propList.size(); ++k ) { QDomElement propElem = propList.at( k ).toElement(); - if ( propElem.attribute( "k" ) == "color" || propElem.attribute( "k" ) == "color_border" ) + if ( propElem.attribute( QStringLiteral( "k" ) ) == QLatin1String( "color" ) || propElem.attribute( QStringLiteral( "k" ) ) == QLatin1String( "color_border" ) ) { - propElem.setAttribute( "v", propElem.attribute( "v" ).section( ',', 0, 2 ) + ",255" ); + propElem.setAttribute( QStringLiteral( "v" ), propElem.attribute( QStringLiteral( "v" ) ).section( ',', 0, 2 ) + ",255" ); } } } @@ -602,11 +602,11 @@ void QgsProjectFileTransform::transform1800to1900() void QgsProjectFileTransform::transform2200to2300() { //composer: set placement for all picture items to middle, to mimic <=2.2 behaviour - QDomNodeList composerPictureList = mDom.elementsByTagName( "ComposerPicture" ); + QDomNodeList composerPictureList = mDom.elementsByTagName( QStringLiteral( "ComposerPicture" ) ); for ( int i = 0; i < composerPictureList.size(); ++i ) { QDomElement picture = composerPictureList.at( i ).toElement(); - picture.setAttribute( "anchorPoint", QString::number( 4 ) ); + picture.setAttribute( QStringLiteral( "anchorPoint" ), QString::number( 4 ) ); } } @@ -615,19 +615,19 @@ void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNo { //no data //TODO: We would need to set no data on all bands, but we don't know number of bands here - QDomNode noDataNode = rasterPropertiesElem.namedItem( "mNoDataValue" ); + QDomNode noDataNode = rasterPropertiesElem.namedItem( QStringLiteral( "mNoDataValue" ) ); QDomElement noDataElement = noDataNode.toElement(); if ( !noDataElement.text().isEmpty() ) { QgsDebugMsg( "mNoDataValue = " + noDataElement.text() ); - QDomElement noDataElem = doc.createElement( "noData" ); + QDomElement noDataElem = doc.createElement( QStringLiteral( "noData" ) ); - QDomElement noDataRangeList = doc.createElement( "noDataRangeList" ); - noDataRangeList.setAttribute( "bandNo", 1 ); + QDomElement noDataRangeList = doc.createElement( QStringLiteral( "noDataRangeList" ) ); + noDataRangeList.setAttribute( QStringLiteral( "bandNo" ), 1 ); - QDomElement noDataRange = doc.createElement( "noDataRange" ); - noDataRange.setAttribute( "min", noDataElement.text() ); - noDataRange.setAttribute( "max", noDataElement.text() ); + QDomElement noDataRange = doc.createElement( QStringLiteral( "noDataRange" ) ); + noDataRange.setAttribute( QStringLiteral( "min" ), noDataElement.text() ); + noDataRange.setAttribute( QStringLiteral( "max" ), noDataElement.text() ); noDataRangeList.appendChild( noDataRange ); noDataElem.appendChild( noDataRangeList ); @@ -635,82 +635,82 @@ void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNo parentNode.appendChild( noDataElem ); } - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); //convert general properties //invert color - rasterRendererElem.setAttribute( "invertColor", "0" ); - QDomElement invertColorElem = rasterPropertiesElem.firstChildElement( "mInvertColor" ); + rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "0" ) ); + QDomElement invertColorElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "mInvertColor" ) ); if ( !invertColorElem.isNull() ) { - if ( invertColorElem.text() == "true" ) + if ( invertColorElem.text() == QLatin1String( "true" ) ) { - rasterRendererElem.setAttribute( "invertColor", "1" ); + rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "1" ) ); } } //opacity - rasterRendererElem.setAttribute( "opacity", "1" ); - QDomElement transparencyElem = parentNode.firstChildElement( "transparencyLevelInt" ); + rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QStringLiteral( "1" ) ); + QDomElement transparencyElem = parentNode.firstChildElement( QStringLiteral( "transparencyLevelInt" ) ); if ( !transparencyElem.isNull() ) { double transparency = transparencyElem.text().toInt(); - rasterRendererElem.setAttribute( "opacity", QString::number( transparency / 255.0 ) ); + rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QString::number( transparency / 255.0 ) ); } //alphaBand was not saved until now (bug) - rasterRendererElem.setAttribute( "alphaBand", -1 ); + rasterRendererElem.setAttribute( QStringLiteral( "alphaBand" ), -1 ); //gray band is used for several renderers - int grayBand = rasterBandNumber( rasterPropertiesElem, "mGrayBandName", rlayer ); + int grayBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGrayBandName" ), rlayer ); //convert renderer specific properties - QString drawingStyle = rasterPropertiesElem.firstChildElement( "mDrawingStyle" ).text(); + QString drawingStyle = rasterPropertiesElem.firstChildElement( QStringLiteral( "mDrawingStyle" ) ).text(); // While PalettedColor should normaly contain only integer values, usually // color palette 0-255, it may happen (Tim, issue #7023) that it contains // colormap classification with double values and text labels // (which should normaly only appear in SingleBandPseudoColor drawingStyle) // => we have to check first the values and change drawingStyle if necessary - if ( drawingStyle == "PalettedColor" ) + if ( drawingStyle == QLatin1String( "PalettedColor" ) ) { - QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); - QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( "colorRampEntry" ); + QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) ); + QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) ); for ( int i = 0; i < colorRampEntryList.size(); ++i ) { QDomElement colorRampEntryElem = colorRampEntryList.at( i ).toElement(); - QString strValue = colorRampEntryElem.attribute( "value" ); + QString strValue = colorRampEntryElem.attribute( QStringLiteral( "value" ) ); double value = strValue.toDouble(); if ( value < 0 || value > 10000 || !qgsDoubleNear( value, static_cast< int >( value ) ) ) { QgsDebugMsg( QString( "forcing SingleBandPseudoColor value = %1" ).arg( value ) ); - drawingStyle = "SingleBandPseudoColor"; + drawingStyle = QStringLiteral( "SingleBandPseudoColor" ); break; } } } - if ( drawingStyle == "SingleBandGray" ) + if ( drawingStyle == QLatin1String( "SingleBandGray" ) ) { - rasterRendererElem.setAttribute( "type", "singlebandgray" ); - rasterRendererElem.setAttribute( "grayBand", grayBand ); + rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandgray" ) ); + rasterRendererElem.setAttribute( QStringLiteral( "grayBand" ), grayBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } - else if ( drawingStyle == "SingleBandPseudoColor" ) + else if ( drawingStyle == QLatin1String( "SingleBandPseudoColor" ) ) { - rasterRendererElem.setAttribute( "type", "singlebandpseudocolor" ); - rasterRendererElem.setAttribute( "band", grayBand ); - QDomElement newRasterShaderElem = doc.createElement( "rastershader" ); - QDomElement newColorRampShaderElem = doc.createElement( "colorrampshader" ); + rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandpseudocolor" ) ); + rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand ); + QDomElement newRasterShaderElem = doc.createElement( QStringLiteral( "rastershader" ) ); + QDomElement newColorRampShaderElem = doc.createElement( QStringLiteral( "colorrampshader" ) ); newRasterShaderElem.appendChild( newColorRampShaderElem ); rasterRendererElem.appendChild( newRasterShaderElem ); //switch depending on mColorShadingAlgorithm - QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( "mColorShadingAlgorithm" ).text(); - if ( colorShadingAlgorithm == "PseudoColorShader" || colorShadingAlgorithm == "FreakOutShader" ) + QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( QStringLiteral( "mColorShadingAlgorithm" ) ).text(); + if ( colorShadingAlgorithm == QLatin1String( "PseudoColorShader" ) || colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) ) { - newColorRampShaderElem.setAttribute( "colorRampType", "INTERPOLATED" ); + newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) ); //get minmax from rasterlayer QgsRasterBandStats rasterBandStats = rlayer->dataProvider()->bandStatistics( grayBand ); @@ -719,32 +719,32 @@ void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNo double breakSize = ( maxValue - minValue ) / 3; QStringList colorList; - if ( colorShadingAlgorithm == "FreakOutShader" ) + if ( colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) ) { - colorList << "#ff00ff" << "#00ffff" << "#ff0000" << "#00ff00"; + colorList << QStringLiteral( "#ff00ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ff0000" ) << QStringLiteral( "#00ff00" ); } else //pseudocolor { - colorList << "#0000ff" << "#00ffff" << "#ffff00" << "#ff0000"; + colorList << QStringLiteral( "#0000ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ffff00" ) << QStringLiteral( "#ff0000" ); } QStringList::const_iterator colorIt = colorList.constBegin(); double boundValue = minValue; for ( ; colorIt != colorList.constEnd(); ++colorIt ) { - QDomElement newItemElem = doc.createElement( "item" ); - newItemElem.setAttribute( "value", QString::number( boundValue ) ); - newItemElem.setAttribute( "label", QString::number( boundValue ) ); - newItemElem.setAttribute( "color", *colorIt ); + QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) ); + newItemElem.setAttribute( QStringLiteral( "value" ), QString::number( boundValue ) ); + newItemElem.setAttribute( QStringLiteral( "label" ), QString::number( boundValue ) ); + newItemElem.setAttribute( QStringLiteral( "color" ), *colorIt ); newColorRampShaderElem.appendChild( newItemElem ); boundValue += breakSize; } } - else if ( colorShadingAlgorithm == "ColorRampShader" ) + else if ( colorShadingAlgorithm == QLatin1String( "ColorRampShader" ) ) { - QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); - QString type = customColorRampElem.firstChildElement( "colorRampType" ).text(); - newColorRampShaderElem.setAttribute( "colorRampType", type ); - QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( "colorRampEntry" ); + QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) ); + QString type = customColorRampElem.firstChildElement( QStringLiteral( "colorRampType" ) ).text(); + newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), type ); + QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) ); QString value, label; QColor newColor; @@ -753,27 +753,27 @@ void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNo for ( int i = 0; i < colorNodeList.size(); ++i ) { currentItemElem = colorNodeList.at( i ).toElement(); - value = currentItemElem.attribute( "value" ); - label = currentItemElem.attribute( "label" ); - red = currentItemElem.attribute( "red" ).toInt(); - green = currentItemElem.attribute( "green" ).toInt(); - blue = currentItemElem.attribute( "blue" ).toInt(); + value = currentItemElem.attribute( QStringLiteral( "value" ) ); + label = currentItemElem.attribute( QStringLiteral( "label" ) ); + red = currentItemElem.attribute( QStringLiteral( "red" ) ).toInt(); + green = currentItemElem.attribute( QStringLiteral( "green" ) ).toInt(); + blue = currentItemElem.attribute( QStringLiteral( "blue" ) ).toInt(); newColor = QColor( red, green, blue ); - QDomElement newItemElem = doc.createElement( "item" ); - newItemElem.setAttribute( "value", value ); - newItemElem.setAttribute( "label", label ); - newItemElem.setAttribute( "color", newColor.name() ); + QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) ); + newItemElem.setAttribute( QStringLiteral( "value" ), value ); + newItemElem.setAttribute( QStringLiteral( "label" ), label ); + newItemElem.setAttribute( QStringLiteral( "color" ), newColor.name() ); newColorRampShaderElem.appendChild( newItemElem ); } } } - else if ( drawingStyle == "PalettedColor" ) + else if ( drawingStyle == QLatin1String( "PalettedColor" ) ) { - rasterRendererElem.setAttribute( "type", "paletted" ); - rasterRendererElem.setAttribute( "band", grayBand ); - QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( "customColorRamp" ); - QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( "colorRampEntry" ); - QDomElement newColorPaletteElem = doc.createElement( "colorPalette" ); + rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "paletted" ) ); + rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand ); + QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) ); + QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) ); + QDomElement newColorPaletteElem = doc.createElement( QStringLiteral( "colorPalette" ) ); int red = 0; int green = 0; @@ -783,33 +783,33 @@ void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNo for ( int i = 0; i < colorRampEntryList.size(); ++i ) { colorRampEntryElem = colorRampEntryList.at( i ).toElement(); - QDomElement newPaletteElem = doc.createElement( "paletteEntry" ); - value = static_cast< int >( colorRampEntryElem.attribute( "value" ).toDouble() ); - newPaletteElem.setAttribute( "value", value ); - red = colorRampEntryElem.attribute( "red" ).toInt(); - green = colorRampEntryElem.attribute( "green" ).toInt(); - blue = colorRampEntryElem.attribute( "blue" ).toInt(); - newPaletteElem.setAttribute( "color", QColor( red, green, blue ).name() ); - QString label = colorRampEntryElem.attribute( "label" ); + QDomElement newPaletteElem = doc.createElement( QStringLiteral( "paletteEntry" ) ); + value = static_cast< int >( colorRampEntryElem.attribute( QStringLiteral( "value" ) ).toDouble() ); + newPaletteElem.setAttribute( QStringLiteral( "value" ), value ); + red = colorRampEntryElem.attribute( QStringLiteral( "red" ) ).toInt(); + green = colorRampEntryElem.attribute( QStringLiteral( "green" ) ).toInt(); + blue = colorRampEntryElem.attribute( QStringLiteral( "blue" ) ).toInt(); + newPaletteElem.setAttribute( QStringLiteral( "color" ), QColor( red, green, blue ).name() ); + QString label = colorRampEntryElem.attribute( QStringLiteral( "label" ) ); if ( !label.isEmpty() ) { - newPaletteElem.setAttribute( "label", label ); + newPaletteElem.setAttribute( QStringLiteral( "label" ), label ); } newColorPaletteElem.appendChild( newPaletteElem ); } rasterRendererElem.appendChild( newColorPaletteElem ); } - else if ( drawingStyle == "MultiBandColor" ) + else if ( drawingStyle == QLatin1String( "MultiBandColor" ) ) { - rasterRendererElem.setAttribute( "type", "multibandcolor" ); + rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "multibandcolor" ) ); //red band, green band, blue band - int redBand = rasterBandNumber( rasterPropertiesElem, "mRedBandName", rlayer ); - int greenBand = rasterBandNumber( rasterPropertiesElem, "mGreenBandName", rlayer ); - int blueBand = rasterBandNumber( rasterPropertiesElem, "mBlueBandName", rlayer ); - rasterRendererElem.setAttribute( "redBand", redBand ); - rasterRendererElem.setAttribute( "greenBand", greenBand ); - rasterRendererElem.setAttribute( "blueBand", blueBand ); + int redBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mRedBandName" ), rlayer ); + int greenBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGreenBandName" ), rlayer ); + int blueBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mBlueBandName" ), rlayer ); + rasterRendererElem.setAttribute( QStringLiteral( "redBand" ), redBand ); + rasterRendererElem.setAttribute( QStringLiteral( "greenBand" ), greenBand ); + rasterRendererElem.setAttribute( QStringLiteral( "blueBand" ), blueBand ); transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem ); } @@ -856,13 +856,13 @@ void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, c double minimumValue = 0; double maximumValue = 0; - QDomElement contrastMinMaxElem = rasterproperties.firstChildElement( "contrastEnhancementMinMaxValues" ); + QDomElement contrastMinMaxElem = rasterproperties.firstChildElement( QStringLiteral( "contrastEnhancementMinMaxValues" ) ); if ( contrastMinMaxElem.isNull() ) { return; } - QDomElement contrastEnhancementAlgorithmElem = rasterproperties.firstChildElement( "mContrastEnhancementAlgorithm" ); + QDomElement contrastEnhancementAlgorithmElem = rasterproperties.firstChildElement( QStringLiteral( "mContrastEnhancementAlgorithm" ) ); if ( contrastEnhancementAlgorithmElem.isNull() ) { return; @@ -871,32 +871,32 @@ void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, c //convert enhancement name to enumeration int algorithmEnum = 0; QString algorithmString = contrastEnhancementAlgorithmElem.text(); - if ( algorithmString == "StretchToMinimumMaximum" ) + if ( algorithmString == QLatin1String( "StretchToMinimumMaximum" ) ) { algorithmEnum = 1; } - else if ( algorithmString == "StretchAndClipToMinimumMaximum" ) + else if ( algorithmString == QLatin1String( "StretchAndClipToMinimumMaximum" ) ) { algorithmEnum = 2; } - else if ( algorithmString == "ClipToMinimumMaximum" ) + else if ( algorithmString == QLatin1String( "ClipToMinimumMaximum" ) ) { algorithmEnum = 3; } - else if ( algorithmString == "UserDefinedEnhancement" ) + else if ( algorithmString == QLatin1String( "UserDefinedEnhancement" ) ) { algorithmEnum = 4; } - QDomNodeList minMaxEntryList = contrastMinMaxElem.elementsByTagName( "minMaxEntry" ); + QDomNodeList minMaxEntryList = contrastMinMaxElem.elementsByTagName( QStringLiteral( "minMaxEntry" ) ); QStringList enhancementNameList; if ( minMaxEntryList.size() == 1 ) { - enhancementNameList << "contrastEnhancement"; + enhancementNameList << QStringLiteral( "contrastEnhancement" ); } if ( minMaxEntryList.size() == 3 ) { - enhancementNameList << "redContrastEnhancement" << "greenContrastEnhancement" << "blueContrastEnhancement"; + enhancementNameList << QStringLiteral( "redContrastEnhancement" ) << QStringLiteral( "greenContrastEnhancement" ) << QStringLiteral( "blueContrastEnhancement" ); } if ( minMaxEntryList.size() > enhancementNameList.size() ) { @@ -907,14 +907,14 @@ void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, c for ( int i = 0; i < minMaxEntryList.size(); ++i ) { minMaxEntryElem = minMaxEntryList.at( i ).toElement(); - QDomElement minElem = minMaxEntryElem.firstChildElement( "min" ); + QDomElement minElem = minMaxEntryElem.firstChildElement( QStringLiteral( "min" ) ); if ( minElem.isNull() ) { return; } minimumValue = minElem.text().toDouble(); - QDomElement maxElem = minMaxEntryElem.firstChildElement( "max" ); + QDomElement maxElem = minMaxEntryElem.firstChildElement( QStringLiteral( "max" ) ); if ( maxElem.isNull() ) { return; @@ -922,16 +922,16 @@ void QgsProjectFileTransform::transformContrastEnhancement( QDomDocument& doc, c maximumValue = maxElem.text().toDouble(); QDomElement newContrastEnhancementElem = doc.createElement( enhancementNameList.at( i ) ); - QDomElement newMinValElem = doc.createElement( "minValue" ); + QDomElement newMinValElem = doc.createElement( QStringLiteral( "minValue" ) ); QDomText minText = doc.createTextNode( QString::number( minimumValue ) ); newMinValElem.appendChild( minText ); newContrastEnhancementElem.appendChild( newMinValElem ); - QDomElement newMaxValElem = doc.createElement( "maxValue" ); + QDomElement newMaxValElem = doc.createElement( QStringLiteral( "maxValue" ) ); QDomText maxText = doc.createTextNode( QString::number( maximumValue ) ); newMaxValElem.appendChild( maxText ); newContrastEnhancementElem.appendChild( newMaxValElem ); - QDomElement newAlgorithmElem = doc.createElement( "algorithm" ); + QDomElement newAlgorithmElem = doc.createElement( QStringLiteral( "algorithm" ) ); QDomText newAlgorithmText = doc.createTextNode( QString::number( algorithmEnum ) ); newAlgorithmElem.appendChild( newAlgorithmText ); newContrastEnhancementElem.appendChild( newAlgorithmElem ); diff --git a/src/core/qgsprojectproperty.cpp b/src/core/qgsprojectproperty.cpp index 165f81919103..8d30cc92a72f 100644 --- a/src/core/qgsprojectproperty.cpp +++ b/src/core/qgsprojectproperty.cpp @@ -60,7 +60,7 @@ bool QgsPropertyValue::readXml( QDomNode & keyNode ) QDomElement subkeyElement = keyNode.toElement(); // get the type so that we can properly parse the key value - QString typeString = subkeyElement.attribute( "type" ); + QString typeString = subkeyElement.attribute( QStringLiteral( "type" ) ); if ( QString::null == typeString ) { @@ -242,7 +242,7 @@ bool QgsPropertyValue::writeXml( QString const & nodeName, QDomElement valueElement = document.createElement( nodeName ); // remember the type so that we can rebuild it when the project is read in - valueElement.setAttribute( "type", value_.typeName() ); + valueElement.setAttribute( QStringLiteral( "type" ), value_.typeName() ); // we handle string lists differently from other types in that we @@ -257,7 +257,7 @@ bool QgsPropertyValue::writeXml( QString const & nodeName, i != sl.end(); ++i ) { - QDomElement stringListElement = document.createElement( "value" ); + QDomElement stringListElement = document.createElement( QStringLiteral( "value" ) ); QDomText valueText = document.createTextNode( *i ); stringListElement.appendChild( valueText ); @@ -370,7 +370,7 @@ bool QgsPropertyKey::readXml( QDomNode & keyNode ) // a subkey if ( subkeys.item( i ).hasAttributes() && // if we have attributes subkeys.item( i ).isElement() && // and we're an element - subkeys.item( i ).toElement().hasAttribute( "type" ) ) // and we have a "type" attribute + subkeys.item( i ).toElement().hasAttribute( QStringLiteral( "type" ) ) ) // and we have a "type" attribute { // then we're a key value delete mProperties.take( subkeys.item( i ).nodeName() ); mProperties.insert( subkeys.item( i ).nodeName(), new QgsPropertyValue ); diff --git a/src/core/qgsprojectproperty.h b/src/core/qgsprojectproperty.h index ba260029d870..507fb324f3a9 100644 --- a/src/core/qgsprojectproperty.h +++ b/src/core/qgsprojectproperty.h @@ -282,7 +282,7 @@ class CORE_EXPORT QgsPropertyKey : public QgsProperty /// reset the QgsProperty key to prestine state virtual void clear() { - mName = ""; + mName = QLatin1String( "" ); clearKeys(); } diff --git a/src/core/qgsprojectversion.cpp b/src/core/qgsprojectversion.cpp index d36aa66c7e12..75d5858690f4 100644 --- a/src/core/qgsprojectversion.cpp +++ b/src/core/qgsprojectversion.cpp @@ -93,10 +93,10 @@ QString QgsProjectVersion::text() { if ( mName.isEmpty() ) { - return QString( "%1.%2.%3" ).arg( mMajor ).arg( mMinor ).arg( mSub ); + return QStringLiteral( "%1.%2.%3" ).arg( mMajor ).arg( mMinor ).arg( mSub ); } else { - return QString( "%1.%2.%3-%4" ).arg( mMajor ).arg( mMinor ).arg( mSub ).arg( mName ); + return QStringLiteral( "%1.%2.%3-%4" ).arg( mMajor ).arg( mMinor ).arg( mSub ).arg( mName ); } } diff --git a/src/core/qgsprojectversion.h b/src/core/qgsprojectversion.h index 1e768a55c5e8..4ac064615e3a 100644 --- a/src/core/qgsprojectversion.h +++ b/src/core/qgsprojectversion.h @@ -38,7 +38,11 @@ class CORE_EXPORT QgsProjectVersion , mSub( 0 ) {} ~QgsProjectVersion() {} - QgsProjectVersion( int major, int minor, int sub, const QString& name = "" ); + + /** + * Constructor for QgsProjectVersion which accepts a major, minor and sub version number and a release name. + */ + QgsProjectVersion( int major, int minor, int sub, const QString& name = QLatin1String( "" ) ); QgsProjectVersion( const QString& string ); int majorVersion() { return mMajor;} int minorVersion() { return mMinor;} diff --git a/src/core/qgsproviderregistry.cpp b/src/core/qgsproviderregistry.cpp index 14da0e1256e4..5ab4457b156d 100644 --- a/src/core/qgsproviderregistry.cpp +++ b/src/core/qgsproviderregistry.cpp @@ -83,7 +83,7 @@ void QgsProviderRegistry::init() #elif defined(ANDROID) mLibraryDirectory.setNameFilters( QStringList( "*provider.so" ) ); #else - mLibraryDirectory.setNameFilters( QStringList( "*.so" ) ); + mLibraryDirectory.setNameFilters( QStringList( QStringLiteral( "*.so" ) ) ); #endif QgsDebugMsg( QString( "Checking %1 for provider plugins" ).arg( mLibraryDirectory.path() ) ); @@ -298,12 +298,12 @@ QString QgsProviderRegistry::pluginList( bool asHTML ) const QString list; if ( asHTML ) - list += "
                                                                                                                                                                                      "; + list += QLatin1String( "
                                                                                                                                                                                        " ); while ( it != mProviders.end() ) { if ( asHTML ) - list += "
                                                                                                                                                                                      1. "; + list += QLatin1String( "
                                                                                                                                                                                      2. " ); list += it->second->description(); @@ -316,7 +316,7 @@ QString QgsProviderRegistry::pluginList( bool asHTML ) const } if ( asHTML ) - list += "
                                                                                                                                                                                      "; + list += QLatin1String( "
                                                                                                                                                                                    " ); return list; } diff --git a/src/core/qgsrectangle.cpp b/src/core/qgsrectangle.cpp index 92e50de7dc60..f99abf270544 100644 --- a/src/core/qgsrectangle.cpp +++ b/src/core/qgsrectangle.cpp @@ -248,13 +248,13 @@ QString QgsRectangle::asWktCoordinates() const QString QgsRectangle::asWktPolygon() const { QString rep = - QString( "POLYGON((" ) + + QStringLiteral( "POLYGON((" ) + qgsDoubleToString( xmin ) + ' ' + qgsDoubleToString( ymin ) + ", " + qgsDoubleToString( xmax ) + ' ' + qgsDoubleToString( ymin ) + ", " + qgsDoubleToString( xmax ) + ' ' + qgsDoubleToString( ymax ) + ", " + qgsDoubleToString( xmin ) + ' ' + qgsDoubleToString( ymax ) + ", " + qgsDoubleToString( xmin ) + ' ' + qgsDoubleToString( ymin ) + - QString( "))" ); + QStringLiteral( "))" ); return rep; } @@ -290,9 +290,9 @@ QString QgsRectangle::toString( int thePrecision ) const { QString rep; if ( isEmpty() ) - rep = "Empty"; + rep = QStringLiteral( "Empty" ); else - rep = QString( "%1,%2 : %3,%4" ) + rep = QStringLiteral( "%1,%2 : %3,%4" ) .arg( xmin, 0, 'f', thePrecision ) .arg( ymin, 0, 'f', thePrecision ) .arg( xmax, 0, 'f', thePrecision ) diff --git a/src/core/qgsrelation.cpp b/src/core/qgsrelation.cpp index b2c67f8ee9ee..6cec7d79c78c 100644 --- a/src/core/qgsrelation.cpp +++ b/src/core/qgsrelation.cpp @@ -32,17 +32,17 @@ QgsRelation QgsRelation::createFromXml( const QDomNode &node ) { QDomElement elem = node.toElement(); - if ( elem.tagName() != "relation" ) + if ( elem.tagName() != QLatin1String( "relation" ) ) { QgsLogger::warning( QApplication::translate( "QgsRelation", "Cannot create relation. Unexpected tag '%1'" ).arg( elem.tagName() ) ); } QgsRelation relation; - QString referencingLayerId = elem.attribute( "referencingLayer" ); - QString referencedLayerId = elem.attribute( "referencedLayer" ); - QString id = elem.attribute( "id" ); - QString name = elem.attribute( "name" ); + QString referencingLayerId = elem.attribute( QStringLiteral( "referencingLayer" ) ); + QString referencedLayerId = elem.attribute( QStringLiteral( "referencedLayer" ) ); + QString id = elem.attribute( QStringLiteral( "id" ) ); + QString name = elem.attribute( QStringLiteral( "name" ) ); const QMap& mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); @@ -74,13 +74,13 @@ QgsRelation QgsRelation::createFromXml( const QDomNode &node ) relation.mRelationId = id; relation.mRelationName = name; - QDomNodeList references = elem.elementsByTagName( "fieldRef" ); + QDomNodeList references = elem.elementsByTagName( QStringLiteral( "fieldRef" ) ); for ( int i = 0; i < references.size(); ++i ) { QDomElement refEl = references.at( i ).toElement(); - QString referencingField = refEl.attribute( "referencingField" ); - QString referencedField = refEl.attribute( "referencedField" ); + QString referencingField = refEl.attribute( QStringLiteral( "referencingField" ) ); + QString referencedField = refEl.attribute( QStringLiteral( "referencedField" ) ); relation.addFieldPair( referencingField, referencedField ); } @@ -92,17 +92,17 @@ QgsRelation QgsRelation::createFromXml( const QDomNode &node ) void QgsRelation::writeXml( QDomNode &node, QDomDocument &doc ) const { - QDomElement elem = doc.createElement( "relation" ); - elem.setAttribute( "id", mRelationId ); - elem.setAttribute( "name", mRelationName ); - elem.setAttribute( "referencingLayer", mReferencingLayerId ); - elem.setAttribute( "referencedLayer", mReferencedLayerId ); + QDomElement elem = doc.createElement( QStringLiteral( "relation" ) ); + elem.setAttribute( QStringLiteral( "id" ), mRelationId ); + elem.setAttribute( QStringLiteral( "name" ), mRelationName ); + elem.setAttribute( QStringLiteral( "referencingLayer" ), mReferencingLayerId ); + elem.setAttribute( QStringLiteral( "referencedLayer" ), mReferencedLayerId ); Q_FOREACH ( const FieldPair& fields, mFieldPairs ) { - QDomElement referenceElem = doc.createElement( "fieldRef" ); - referenceElem.setAttribute( "referencingField", fields.first ); - referenceElem.setAttribute( "referencedField", fields.second ); + QDomElement referenceElem = doc.createElement( QStringLiteral( "fieldRef" ) ); + referenceElem.setAttribute( QStringLiteral( "referencingField" ), fields.first ); + referenceElem.setAttribute( QStringLiteral( "referencedField" ), fields.second ); elem.appendChild( referenceElem ); } @@ -175,21 +175,21 @@ QString QgsRelation::getRelatedFeaturesFilter( const QgsFeature& feature ) const if ( val.isNull() ) { - conditions << QString( "\"%1\" IS NULL" ).arg( fieldPair.referencingField() ); + conditions << QStringLiteral( "\"%1\" IS NULL" ).arg( fieldPair.referencingField() ); } else if ( referencingField.type() == QVariant::String ) { // Use quotes - conditions << QString( "\"%1\" = '%2'" ).arg( fieldPair.referencingField(), val.toString() ); + conditions << QStringLiteral( "\"%1\" = '%2'" ).arg( fieldPair.referencingField(), val.toString() ); } else { // No quotes - conditions << QString( "\"%1\" = %2" ).arg( fieldPair.referencingField(), val.toString() ); + conditions << QStringLiteral( "\"%1\" = %2" ).arg( fieldPair.referencingField(), val.toString() ); } } - return conditions.join( " AND " ); + return conditions.join( QStringLiteral( " AND " ) ); } QgsFeatureRequest QgsRelation::getReferencedFeatureRequest( const QgsAttributes& attributes ) const @@ -206,12 +206,12 @@ QgsFeatureRequest QgsRelation::getReferencedFeatureRequest( const QgsAttributes& if ( referencedField.type() == QVariant::String ) { // Use quotes - conditions << QString( "\"%1\" = '%2'" ).arg( fieldPair.referencedField(), attributes.at( referencingIdx ).toString() ); + conditions << QStringLiteral( "\"%1\" = '%2'" ).arg( fieldPair.referencedField(), attributes.at( referencingIdx ).toString() ); } else { // No quotes - conditions << QString( "\"%1\" = %2" ).arg( fieldPair.referencedField(), attributes.at( referencingIdx ).toString() ); + conditions << QStringLiteral( "\"%1\" = %2" ).arg( fieldPair.referencedField(), attributes.at( referencingIdx ).toString() ); } } @@ -219,7 +219,7 @@ QgsFeatureRequest QgsRelation::getReferencedFeatureRequest( const QgsAttributes& QgsDebugMsg( QString( "Filter conditions: '%1'" ).arg( conditions.join( " AND " ) ) ); - myRequest.setFilterExpression( conditions.join( " AND " ) ); + myRequest.setFilterExpression( conditions.join( QStringLiteral( " AND " ) ) ); return myRequest; } @@ -250,7 +250,7 @@ QString QgsRelation::id() const void QgsRelation::generateId() { - mRelationId = QString( "%1_%2_%3_%4" ) + mRelationId = QStringLiteral( "%1_%2_%3_%4" ) .arg( referencingLayerId(), mFieldPairs.at( 0 ).referencingField(), referencedLayerId(), diff --git a/src/core/qgsrelationmanager.cpp b/src/core/qgsrelationmanager.cpp index 48e3d132e1c7..437702197c2b 100644 --- a/src/core/qgsrelationmanager.cpp +++ b/src/core/qgsrelationmanager.cpp @@ -155,7 +155,7 @@ void QgsRelationManager::readProject( const QDomDocument & doc ) { mRelations.clear(); - QDomNodeList nodes = doc.elementsByTagName( "relations" ); + QDomNodeList nodes = doc.elementsByTagName( QStringLiteral( "relations" ) ); if ( nodes.count() ) { QDomNode node = nodes.item( 0 ); @@ -177,7 +177,7 @@ void QgsRelationManager::readProject( const QDomDocument & doc ) void QgsRelationManager::writeProject( QDomDocument & doc ) { - QDomNodeList nl = doc.elementsByTagName( "qgis" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "qgis" ) ); if ( !nl.count() ) { QgsDebugMsg( "Unable to find qgis element in project file" ); @@ -185,7 +185,7 @@ void QgsRelationManager::writeProject( QDomDocument & doc ) } QDomNode qgisNode = nl.item( 0 ); // there should only be one - QDomElement relationsNode = doc.createElement( "relations" ); + QDomElement relationsNode = doc.createElement( QStringLiteral( "relations" ) ); qgisNode.appendChild( relationsNode ); Q_FOREACH ( const QgsRelation& relation, mRelations ) diff --git a/src/core/qgsrenderchecker.cpp b/src/core/qgsrenderchecker.cpp index c682e73a7273..3d7be3b3779d 100644 --- a/src/core/qgsrenderchecker.cpp +++ b/src/core/qgsrenderchecker.cpp @@ -31,11 +31,11 @@ static int renderCounter = 0; QgsRenderChecker::QgsRenderChecker() - : mReport( "" ) + : mReport( QLatin1String( "" ) ) , mMatchTarget( 0 ) , mElapsedTime( 0 ) - , mRenderedImageFile( "" ) - , mExpectedImageFile( "" ) + , mRenderedImageFile( QLatin1String( "" ) ) + , mExpectedImageFile( QLatin1String( "" ) ) , mMismatchCount( 0 ) , mColorTolerance( 0 ) , mMaxSizeDifferenceX( 0 ) @@ -110,7 +110,7 @@ bool QgsRenderChecker::isKnownAnomaly( const QString& theDiffImageFile ) QString myControlImageDir = controlImagePath() + mControlName + '/'; QDir myDirectory = QDir( myControlImageDir ); QStringList myList; - QString myFilename = "*"; + QString myFilename = QStringLiteral( "*" ); myList = myDirectory.entryList( QStringList( myFilename ), QDir::Files | QDir::NoSymLinks ); //remove the control file from the list as the anomalies are @@ -125,30 +125,30 @@ bool QgsRenderChecker::isKnownAnomaly( const QString& theDiffImageFile ) QString myFile = myList.at( i ); mReport += "" "Checking if " + myFile + " is a known anomaly."; - mReport += ""; + mReport += QLatin1String( "" ); QString myAnomalyHash = imageToHash( controlImagePath() + mControlName + '/' + myFile ); - QString myHashMessage = QString( + QString myHashMessage = QStringLiteral( "Checking if anomaly %1 (hash %2)
                                                                                                                                                                                    " ) .arg( myFile, myAnomalyHash ); - myHashMessage += QString( "  matches %1 (hash %2)" ) + myHashMessage += QStringLiteral( "  matches %1 (hash %2)" ) .arg( theDiffImageFile, myImageHash ); //foo CDash - emitDashMessage( "Anomaly check", QgsDartMeasurement::Text, myHashMessage ); + emitDashMessage( QStringLiteral( "Anomaly check" ), QgsDartMeasurement::Text, myHashMessage ); mReport += "" + myHashMessage + ""; if ( myImageHash == myAnomalyHash ) { mReport += "" "Anomaly found! " + myFile; - mReport += ""; + mReport += QLatin1String( "" ); return true; } } mReport += "" "No anomaly found! "; - mReport += ""; + mReport += QLatin1String( "" ); return false; } @@ -235,7 +235,7 @@ bool QgsRenderChecker::runTest( const QString& theTestName, QgsRectangle r = mMapSettings.extent(); QTextStream stream( &wldFile ); - stream << QString( "%1\r\n0 \r\n0 \r\n%2\r\n%3\r\n%4\r\n" ) + stream << QStringLiteral( "%1\r\n0 \r\n0 \r\n%2\r\n%3\r\n%4\r\n" ) .arg( qgsDoubleToString( mMapSettings.mapUnitsPerPixel() ), qgsDoubleToString( -mMapSettings.mapUnitsPerPixel() ), qgsDoubleToString( r.xMinimum() + mMapSettings.mapUnitsPerPixel() / 2.0 ), @@ -300,7 +300,7 @@ bool QgsRenderChecker::compareImages( const QString& theTestName, //check for mask QString maskImagePath = mExpectedImageFile; maskImagePath.chop( 4 ); //remove .png extension - maskImagePath += "_mask.png"; + maskImagePath += QLatin1String( "_mask.png" ); QImage* maskImage = new QImage( maskImagePath ); bool hasMask = !maskImage->isNull(); if ( hasMask ) @@ -316,9 +316,9 @@ bool QgsRenderChecker::compareImages( const QString& theTestName, // // Set the report with the result // - mReport = QString( "\n" ).arg( TEST_DATA_DIR ); - mReport += ""; - mReport += "
                                                                                                                                                                                    "; + mReport = QStringLiteral( "\n" ).arg( TEST_DATA_DIR ); + mReport += QLatin1String( "" ); + mReport += QLatin1String( ""; + mReport += QLatin1String( "" ); mReport += myImagesString; delete maskImage; return false; } else { - mReport += ""; + mReport += QLatin1String( "" ); } } @@ -464,26 +464,26 @@ bool QgsRenderChecker::compareImages( const QString& theTestName, // // Send match result to report // - mReport += QString( "" ) + mReport += QStringLiteral( "" ) .arg( mMismatchCount ).arg( mMatchTarget ).arg( theMismatchCount ).arg( mColorTolerance ); // // And send it to CDash // - emitDashMessage( "Mismatch Count", QgsDartMeasurement::Integer, QString( "%1/%2" ).arg( mMismatchCount ).arg( mMatchTarget ) ); + emitDashMessage( QStringLiteral( "Mismatch Count" ), QgsDartMeasurement::Integer, QStringLiteral( "%1/%2" ).arg( mMismatchCount ).arg( mMatchTarget ) ); if ( mMismatchCount <= theMismatchCount ) { - mReport += ""; + mReport += QLatin1String( "" ); if ( mElapsedTimeTarget != 0 && mElapsedTimeTarget < mElapsedTime ) { //test failed because it took too long... qDebug( "Test failed because render step took too long" ); - mReport += ""; + mReport += QLatin1String( "" ); mReport += myImagesString; return false; } @@ -503,17 +503,17 @@ bool QgsRenderChecker::compareImages( const QString& theTestName, return true; } - mReport += ""; - emitDashMessage( "Image mismatch", QgsDartMeasurement::Text, "Difference image did not match any known anomaly or mask." + mReport += QLatin1String( "" ); + emitDashMessage( QStringLiteral( "Image mismatch" ), QgsDartMeasurement::Text, "Difference image did not match any known anomaly or mask." " If you feel the difference image should be considered an anomaly " "you can do something like this\n" "cp '" + myDiffImageFile + "' " + controlImagePath() + mControlName + "/\nIf it should be included in the mask run\n" "scripts/generate_test_mask_image.py '" + mExpectedImageFile + "' '" + mRenderedImageFile + "'\n" ); - mReport += ""; + mReport += QLatin1String( "" ); mReport += myImagesString; return false; } diff --git a/src/core/qgsrenderchecker.h b/src/core/qgsrenderchecker.h index 9e0abf7bacf3..1ec735be0298 100644 --- a/src/core/qgsrenderchecker.h +++ b/src/core/qgsrenderchecker.h @@ -124,7 +124,7 @@ class CORE_EXPORT QgsRenderChecker * @param theRenderedImageFile to optionally override the output filename * @note: make sure to call setExpectedImage and setRenderedImage first. */ - bool compareImages( const QString& theTestName, unsigned int theMismatchCount = 0, const QString& theRenderedImageFile = "" ); + bool compareImages( const QString& theTestName, unsigned int theMismatchCount = 0, const QString& theRenderedImageFile = QLatin1String( "" ) ); /** Get a list of all the anomalies. An anomaly is a rendered difference * file where there is some red pixel content (indicating a render check * mismatch), but where the output was still acceptible. If the render @@ -202,8 +202,8 @@ inline bool compareWkt( const QString& a, const QString& b, double tolerance = 0 QRegExp re( "-?\\d+(?:\\.\\d+)?(?:[eE]\\d+)?" ); QString a0( a ), b0( b ); - a0.replace( re, "#" ); - b0.replace( re, "#" ); + a0.replace( re, QStringLiteral( "#" ) ); + b0.replace( re, QStringLiteral( "#" ) ); QgsDebugMsg( QString( "a0:%1 b0:%2" ).arg( a0, b0 ) ); diff --git a/src/core/qgsrulebasedlabeling.cpp b/src/core/qgsrulebasedlabeling.cpp index 1846db12d88d..2b35d5b77941 100644 --- a/src/core/qgsrulebasedlabeling.cpp +++ b/src/core/qgsrulebasedlabeling.cpp @@ -93,7 +93,7 @@ void QgsRuleBasedLabeling::Rule::setSettings( QgsPalLayerSettings* settings ) void QgsRuleBasedLabeling::Rule::initFilter() { - if ( mElseRule || mFilterExp.compare( "ELSE", Qt::CaseInsensitive ) == 0 ) + if ( mElseRule || mFilterExp.compare( QLatin1String( "ELSE" ), Qt::CaseInsensitive ) == 0 ) { mElseRule = true; mFilter = nullptr; @@ -182,26 +182,26 @@ QgsRuleBasedLabeling::Rule*QgsRuleBasedLabeling::Rule::clone() const QgsRuleBasedLabeling::Rule*QgsRuleBasedLabeling::Rule::create( const QDomElement& ruleElem ) { QgsPalLayerSettings* settings = nullptr; - QDomElement settingsElem = ruleElem.firstChildElement( "settings" ); + QDomElement settingsElem = ruleElem.firstChildElement( QStringLiteral( "settings" ) ); if ( !settingsElem.isNull() ) { settings = new QgsPalLayerSettings; settings->readXml( settingsElem ); } - QString filterExp = ruleElem.attribute( "filter" ); - QString description = ruleElem.attribute( "description" ); - int scaleMinDenom = ruleElem.attribute( "scalemindenom", "0" ).toInt(); - int scaleMaxDenom = ruleElem.attribute( "scalemaxdenom", "0" ).toInt(); - QString ruleKey = ruleElem.attribute( "key" ); + QString filterExp = ruleElem.attribute( QStringLiteral( "filter" ) ); + QString description = ruleElem.attribute( QStringLiteral( "description" ) ); + int scaleMinDenom = ruleElem.attribute( QStringLiteral( "scalemindenom" ), QStringLiteral( "0" ) ).toInt(); + int scaleMaxDenom = ruleElem.attribute( QStringLiteral( "scalemaxdenom" ), QStringLiteral( "0" ) ).toInt(); + QString ruleKey = ruleElem.attribute( QStringLiteral( "key" ) ); Rule* rule = new Rule( settings, scaleMinDenom, scaleMaxDenom, filterExp, description ); if ( !ruleKey.isEmpty() ) rule->mRuleKey = ruleKey; - rule->setActive( ruleElem.attribute( "active", "1" ).toInt() ); + rule->setActive( ruleElem.attribute( QStringLiteral( "active" ), QStringLiteral( "1" ) ).toInt() ); - QDomElement childRuleElem = ruleElem.firstChildElement( "rule" ); + QDomElement childRuleElem = ruleElem.firstChildElement( QStringLiteral( "rule" ) ); while ( !childRuleElem.isNull() ) { Rule* childRule = create( childRuleElem ); @@ -213,7 +213,7 @@ QgsRuleBasedLabeling::Rule*QgsRuleBasedLabeling::Rule::create( const QDomElement { //QgsDebugMsg( "failed to init a child rule!" ); } - childRuleElem = childRuleElem.nextSiblingElement( "rule" ); + childRuleElem = childRuleElem.nextSiblingElement( QStringLiteral( "rule" ) ); } return rule; @@ -221,23 +221,23 @@ QgsRuleBasedLabeling::Rule*QgsRuleBasedLabeling::Rule::create( const QDomElement QDomElement QgsRuleBasedLabeling::Rule::save( QDomDocument& doc ) const { - QDomElement ruleElem = doc.createElement( "rule" ); + QDomElement ruleElem = doc.createElement( QStringLiteral( "rule" ) ); if ( mSettings ) { ruleElem.appendChild( mSettings->writeXml( doc ) ); } if ( !mFilterExp.isEmpty() ) - ruleElem.setAttribute( "filter", mFilterExp ); + ruleElem.setAttribute( QStringLiteral( "filter" ), mFilterExp ); if ( mScaleMinDenom != 0 ) - ruleElem.setAttribute( "scalemindenom", mScaleMinDenom ); + ruleElem.setAttribute( QStringLiteral( "scalemindenom" ), mScaleMinDenom ); if ( mScaleMaxDenom != 0 ) - ruleElem.setAttribute( "scalemaxdenom", mScaleMaxDenom ); + ruleElem.setAttribute( QStringLiteral( "scalemaxdenom" ), mScaleMaxDenom ); if ( !mDescription.isEmpty() ) - ruleElem.setAttribute( "description", mDescription ); + ruleElem.setAttribute( QStringLiteral( "description" ), mDescription ); if ( !mIsActive ) - ruleElem.setAttribute( "active", 0 ); - ruleElem.setAttribute( "key", mRuleKey ); + ruleElem.setAttribute( QStringLiteral( "active" ), 0 ); + ruleElem.setAttribute( QStringLiteral( "key" ), mRuleKey ); for ( RuleList::const_iterator it = mChildren.constBegin(); it != mChildren.constEnd(); ++it ) { @@ -389,7 +389,7 @@ QgsRuleBasedLabeling::~QgsRuleBasedLabeling() QgsRuleBasedLabeling*QgsRuleBasedLabeling::create( const QDomElement& element ) { - QDomElement rulesElem = element.firstChildElement( "rules" ); + QDomElement rulesElem = element.firstChildElement( QStringLiteral( "rules" ) ); Rule* root = Rule::create( rulesElem ); if ( !root ) @@ -401,16 +401,16 @@ QgsRuleBasedLabeling*QgsRuleBasedLabeling::create( const QDomElement& element ) QString QgsRuleBasedLabeling::type() const { - return "rule-based"; + return QStringLiteral( "rule-based" ); } QDomElement QgsRuleBasedLabeling::save( QDomDocument& doc ) const { - QDomElement elem = doc.createElement( "labeling" ); - elem.setAttribute( "type", "rule-based" ); + QDomElement elem = doc.createElement( QStringLiteral( "labeling" ) ); + elem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "rule-based" ) ); QDomElement rulesElem = mRootRule->save( doc ); - rulesElem.setTagName( "rules" ); // instead of just "rule" + rulesElem.setTagName( QStringLiteral( "rules" ) ); // instead of just "rule" elem.appendChild( rulesElem ); return elem; diff --git a/src/core/qgsruntimeprofiler.cpp b/src/core/qgsruntimeprofiler.cpp index d579bc806c70..87f5e6161126 100644 --- a/src/core/qgsruntimeprofiler.cpp +++ b/src/core/qgsruntimeprofiler.cpp @@ -52,7 +52,7 @@ void QgsRuntimeProfiler::end() name.prepend( mGroupPrefix ); double timing = mProfileTime.elapsed() / 1000.0; mProfileTimes.append( QPair( name, timing ) ); - QString message = QString( "PROFILE: %1 - %2" ).arg( name ).arg( timing ); + QString message = QStringLiteral( "PROFILE: %1 - %2" ).arg( name ).arg( timing ); QgsDebugMsg( message ); } diff --git a/src/core/qgsscaleexpression.cpp b/src/core/qgsscaleexpression.cpp index c0ff15a8ccad..c6caa8d9f8d5 100644 --- a/src/core/qgsscaleexpression.cpp +++ b/src/core/qgsscaleexpression.cpp @@ -139,12 +139,12 @@ QString QgsScaleExpression::createExpression( Type type, const QString & baseExp switch ( type ) { case Linear: - return QString( "coalesce(scale_linear(%1, %2, %3, %4, %5), %6)" ).arg( baseExpr, minValueString, maxValueString, minSizeString, maxSizeString, nullSizeString ); + return QStringLiteral( "coalesce(scale_linear(%1, %2, %3, %4, %5), %6)" ).arg( baseExpr, minValueString, maxValueString, minSizeString, maxSizeString, nullSizeString ); case Area: case Flannery: case Exponential: - return QString( "coalesce(scale_exp(%1, %2, %3, %4, %5, %6), %7)" ).arg( baseExpr, minValueString, maxValueString, minSizeString, maxSizeString, exponentString, nullSizeString ); + return QStringLiteral( "coalesce(scale_exp(%1, %2, %3, %4, %5, %6), %7)" ).arg( baseExpr, minValueString, maxValueString, minSizeString, maxSizeString, exponentString, nullSizeString ); case Unknown: break; diff --git a/src/core/qgsscaleutils.cpp b/src/core/qgsscaleutils.cpp index d29089e34ae5..34e18c961e1a 100644 --- a/src/core/qgsscaleutils.cpp +++ b/src/core/qgsscaleutils.cpp @@ -22,21 +22,21 @@ bool QgsScaleUtils::saveScaleList( const QString &fileName, const QStringList &scales, QString &errorMessage ) { QDomDocument doc; - QDomElement root = doc.createElement( "qgsScales" ); - root.setAttribute( "version", "1.0" ); + QDomElement root = doc.createElement( QStringLiteral( "qgsScales" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); for ( int i = 0; i < scales.count(); ++i ) { - QDomElement el = doc.createElement( "scale" ); - el.setAttribute( "value", scales.at( i ) ); + QDomElement el = doc.createElement( QStringLiteral( "scale" ) ); + el.setAttribute( QStringLiteral( "value" ), scales.at( i ) ); root.appendChild( el ); } QFile file( fileName ); if ( !file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) ) { - errorMessage = QString( "Cannot write file %1:\n%2." ).arg( fileName, file.errorString() ); + errorMessage = QStringLiteral( "Cannot write file %1:\n%2." ).arg( fileName, file.errorString() ); return false; } @@ -50,7 +50,7 @@ bool QgsScaleUtils::loadScaleList( const QString &fileName, QStringList &scales, QFile file( fileName ); if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { - errorMessage = QString( "Cannot read file %1:\n%2." ).arg( fileName, file.errorString() ); + errorMessage = QStringLiteral( "Cannot read file %1:\n%2." ).arg( fileName, file.errorString() ); return false; } @@ -61,7 +61,7 @@ bool QgsScaleUtils::loadScaleList( const QString &fileName, QStringList &scales, if ( !doc.setContent( &file, true, &errorStr, &errorLine, &errorColumn ) ) { - errorMessage = QString( "Parse error at line %1, column %2:\n%3" ) + errorMessage = QStringLiteral( "Parse error at line %1, column %2:\n%3" ) .arg( errorLine ) .arg( errorColumn ) .arg( errorStr ); @@ -69,16 +69,16 @@ bool QgsScaleUtils::loadScaleList( const QString &fileName, QStringList &scales, } QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsScales" ) + if ( root.tagName() != QLatin1String( "qgsScales" ) ) { - errorMessage = "The file is not an scales exchange file."; + errorMessage = QStringLiteral( "The file is not an scales exchange file." ); return false; } QDomElement child = root.firstChildElement(); while ( !child.isNull() ) { - scales.append( child.attribute( "value" ) ); + scales.append( child.attribute( QStringLiteral( "value" ) ) ); child = child.nextSiblingElement(); } diff --git a/src/core/qgssnappingconfig.cpp b/src/core/qgssnappingconfig.cpp index c09a4a52e455..cab7a900d60a 100644 --- a/src/core/qgssnappingconfig.cpp +++ b/src/core/qgssnappingconfig.cpp @@ -128,17 +128,17 @@ bool QgsSnappingConfig::operator==( const QgsSnappingConfig& other ) const void QgsSnappingConfig::reset() { // get defaults values. They are both used for standard and advanced configuration (per layer) - bool enabled = QSettings().value( "/qgis/digitizing/default_advanced_snap_enabled", true ).toBool(); - SnappingMode mode = ( SnappingMode )QSettings().value( "/qgis/digitizing/default_snap_mode", ( int )AllLayers ).toInt(); + bool enabled = QSettings().value( QStringLiteral( "/qgis/digitizing/default_advanced_snap_enabled" ), true ).toBool(); + SnappingMode mode = ( SnappingMode )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_mode" ), ( int )AllLayers ).toInt(); if ( mMode == 0 ) { // backward compatibility with QGIS 2.x // could be removed in 3.4+ mMode = AllLayers; } - SnappingType type = ( SnappingType )QSettings().value( "/qgis/digitizing/default_snap_type", ( int )Vertex ).toInt(); - double tolerance = QSettings().value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); - QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( "/qgis/digitizing/default_snapping_tolerance_unit", ( int )QgsTolerance::ProjectUnits ).toInt(); + SnappingType type = ( SnappingType )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_type" ), ( int )Vertex ).toInt(); + double tolerance = QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), 0 ).toDouble(); + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), ( int )QgsTolerance::ProjectUnits ).toInt(); // assign main (standard) config mEnabled = enabled; @@ -287,33 +287,33 @@ bool QgsSnappingConfig::operator!=( const QgsSnappingConfig& other ) const void QgsSnappingConfig::readProject( const QDomDocument& doc ) { - QDomElement snapSettingsElem = doc.firstChildElement( "qgis" ).firstChildElement( "snapping-settings" ); + QDomElement snapSettingsElem = doc.firstChildElement( QStringLiteral( "qgis" ) ).firstChildElement( QStringLiteral( "snapping-settings" ) ); if ( snapSettingsElem.isNull() ) { readLegacySettings(); return; } - if ( snapSettingsElem.hasAttribute( "enabled" ) ) - mEnabled = snapSettingsElem.attribute( "enabled" ) == "1"; + if ( snapSettingsElem.hasAttribute( QStringLiteral( "enabled" ) ) ) + mEnabled = snapSettingsElem.attribute( QStringLiteral( "enabled" ) ) == QLatin1String( "1" ); - if ( snapSettingsElem.hasAttribute( "mode" ) ) - mMode = ( SnappingMode )snapSettingsElem.attribute( "mode" ).toInt(); + if ( snapSettingsElem.hasAttribute( QStringLiteral( "mode" ) ) ) + mMode = ( SnappingMode )snapSettingsElem.attribute( QStringLiteral( "mode" ) ).toInt(); - if ( snapSettingsElem.hasAttribute( "type" ) ) - mType = ( SnappingType )snapSettingsElem.attribute( "type" ).toInt(); + if ( snapSettingsElem.hasAttribute( QStringLiteral( "type" ) ) ) + mType = ( SnappingType )snapSettingsElem.attribute( QStringLiteral( "type" ) ).toInt(); - if ( snapSettingsElem.hasAttribute( "tolerance" ) ) - mTolerance = snapSettingsElem.attribute( "tolerance" ).toDouble(); + if ( snapSettingsElem.hasAttribute( QStringLiteral( "tolerance" ) ) ) + mTolerance = snapSettingsElem.attribute( QStringLiteral( "tolerance" ) ).toDouble(); - if ( snapSettingsElem.hasAttribute( "unit" ) ) - mUnits = ( QgsTolerance::UnitType )snapSettingsElem.attribute( "unit" ).toInt(); + if ( snapSettingsElem.hasAttribute( QStringLiteral( "unit" ) ) ) + mUnits = ( QgsTolerance::UnitType )snapSettingsElem.attribute( QStringLiteral( "unit" ) ).toInt(); - if ( snapSettingsElem.hasAttribute( "intersection-snapping" ) ) - mIntersectionSnapping = snapSettingsElem.attribute( "intersection-snapping" ) == "1"; + if ( snapSettingsElem.hasAttribute( QStringLiteral( "intersection-snapping" ) ) ) + mIntersectionSnapping = snapSettingsElem.attribute( QStringLiteral( "intersection-snapping" ) ) == QLatin1String( "1" ); // do not clear the settings as they must be automatically synchronized with current layers - QDomNodeList nodes = snapSettingsElem.elementsByTagName( "individual-layer-settings" ); + QDomNodeList nodes = snapSettingsElem.elementsByTagName( QStringLiteral( "individual-layer-settings" ) ); if ( nodes.count() ) { QDomNode node = nodes.item( 0 ); @@ -322,17 +322,17 @@ void QgsSnappingConfig::readProject( const QDomDocument& doc ) for ( int i = 0; i < layerCount; ++i ) { QDomElement settingElement = settingNodes.at( i ).toElement(); - if ( settingElement.tagName() != "layer-setting" ) + if ( settingElement.tagName() != QLatin1String( "layer-setting" ) ) { QgsLogger::warning( QApplication::translate( "QgsProjectSnappingSettings", "Cannot read individual settings. Unexpected tag '%1'" ).arg( settingElement.tagName() ) ); continue; } - QString layerId = settingElement.attribute( "id" ); - bool enabled = settingElement.attribute( "enabled" ) == "1"; - SnappingType type = ( SnappingType )settingElement.attribute( "type" ).toInt(); - double tolerance = settingElement.attribute( "tolerance" ).toDouble(); - QgsTolerance::UnitType units = ( QgsTolerance::UnitType )settingElement.attribute( "units" ).toInt(); + QString layerId = settingElement.attribute( QStringLiteral( "id" ) ); + bool enabled = settingElement.attribute( QStringLiteral( "enabled" ) ) == QLatin1String( "1" ); + SnappingType type = ( SnappingType )settingElement.attribute( QStringLiteral( "type" ) ).toInt(); + double tolerance = settingElement.attribute( QStringLiteral( "tolerance" ) ).toDouble(); + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )settingElement.attribute( QStringLiteral( "units" ) ).toInt(); QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( layerId ); if ( !ml || ml->type() != QgsMapLayer::VectorLayer ) @@ -348,39 +348,39 @@ void QgsSnappingConfig::readProject( const QDomDocument& doc ) void QgsSnappingConfig::writeProject( QDomDocument& doc ) { - QDomElement snapSettingsElem = doc.createElement( "snapping-settings" ); - snapSettingsElem.setAttribute( "enabled", QString::number( mEnabled ) ); - snapSettingsElem.setAttribute( "mode", ( int )mMode ); - snapSettingsElem.setAttribute( "type", ( int )mType ); - snapSettingsElem.setAttribute( "tolerance", mTolerance ); - snapSettingsElem.setAttribute( "unit", ( int )mUnits ); - snapSettingsElem.setAttribute( "intersection-snapping", QString::number( mIntersectionSnapping ) ); + QDomElement snapSettingsElem = doc.createElement( QStringLiteral( "snapping-settings" ) ); + snapSettingsElem.setAttribute( QStringLiteral( "enabled" ), QString::number( mEnabled ) ); + snapSettingsElem.setAttribute( QStringLiteral( "mode" ), ( int )mMode ); + snapSettingsElem.setAttribute( QStringLiteral( "type" ), ( int )mType ); + snapSettingsElem.setAttribute( QStringLiteral( "tolerance" ), mTolerance ); + snapSettingsElem.setAttribute( QStringLiteral( "unit" ), ( int )mUnits ); + snapSettingsElem.setAttribute( QStringLiteral( "intersection-snapping" ), QString::number( mIntersectionSnapping ) ); - QDomElement ilsElement = doc.createElement( "individual-layer-settings" ); + QDomElement ilsElement = doc.createElement( QStringLiteral( "individual-layer-settings" ) ); Q_FOREACH ( QgsVectorLayer* vl, mIndividualLayerSettings.keys() ) { IndividualLayerSettings setting = mIndividualLayerSettings.value( vl ); - QDomElement layerElement = doc.createElement( "layer-setting" ); - layerElement.setAttribute( "id", vl->id() ); - layerElement.setAttribute( "enabled", QString::number( setting.enabled() ) ); - layerElement.setAttribute( "type", ( int )setting.type() ); - layerElement.setAttribute( "tolerance", setting.tolerance() ); - layerElement.setAttribute( "units", ( int )setting.units() ); + QDomElement layerElement = doc.createElement( QStringLiteral( "layer-setting" ) ); + layerElement.setAttribute( QStringLiteral( "id" ), vl->id() ); + layerElement.setAttribute( QStringLiteral( "enabled" ), QString::number( setting.enabled() ) ); + layerElement.setAttribute( QStringLiteral( "type" ), ( int )setting.type() ); + layerElement.setAttribute( QStringLiteral( "tolerance" ), setting.tolerance() ); + layerElement.setAttribute( QStringLiteral( "units" ), ( int )setting.units() ); ilsElement.appendChild( layerElement ); } snapSettingsElem.appendChild( ilsElement ); - doc.firstChildElement( "qgis" ).appendChild( snapSettingsElem ); + doc.firstChildElement( QStringLiteral( "qgis" ) ).appendChild( snapSettingsElem ); } bool QgsSnappingConfig::addLayers( const QList& layers ) { bool changed = false; - bool enabled = QSettings().value( "/qgis/digitizing/default_advanced_snap_enabled", true ).toBool(); - SnappingType type = ( SnappingType )QSettings().value( "/qgis/digitizing/default_snap_type", Vertex ).toInt(); - double tolerance = QSettings().value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); - QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( "/qgis/digitizing/default_snapping_tolerance_unit", QgsTolerance::ProjectUnits ).toInt(); + bool enabled = QSettings().value( QStringLiteral( "/qgis/digitizing/default_advanced_snap_enabled" ), true ).toBool(); + SnappingType type = ( SnappingType )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_type" ), Vertex ).toInt(); + double tolerance = QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), 0 ).toDouble(); + QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), QgsTolerance::ProjectUnits ).toInt(); Q_FOREACH ( QgsMapLayer* ml, layers ) { @@ -414,27 +414,27 @@ void QgsSnappingConfig::readLegacySettings() mMode = ActiveLayer; mIndividualLayerSettings.clear(); - QString snapMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode" ); + QString snapMode = QgsProject::instance()->readEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/SnappingMode" ) ); - QString snapType = QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType", QString( "off" ) ); - if ( snapType == "to segment" ) + QString snapType = QgsProject::instance()->readEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/DefaultSnapType" ), QStringLiteral( "off" ) ); + if ( snapType == QLatin1String( "to segment" ) ) mType = Segment; - else if ( snapType == "to vertex and segment" ) + else if ( snapType == QLatin1String( "to vertex and segment" ) ) mType = VertexAndSegment; - else if ( snapType == "to vertex" ) + else if ( snapType == QLatin1String( "to vertex" ) ) mType = Vertex; - mTolerance = QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance", 0 ); - mUnits = static_cast< QgsTolerance::UnitType >( QgsProject::instance()->readNumEntry( "Digitizing", "/DefaultSnapToleranceUnit", QgsTolerance::ProjectUnits ) ); + mTolerance = QgsProject::instance()->readDoubleEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/DefaultSnapTolerance" ), 0 ); + mUnits = static_cast< QgsTolerance::UnitType >( QgsProject::instance()->readNumEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/DefaultSnapToleranceUnit" ), QgsTolerance::ProjectUnits ) ); - mIntersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); + mIntersectionSnapping = QgsProject::instance()->readNumEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/IntersectionSnapping" ), 0 ); //read snapping settings from project bool snappingDefinedInProject, ok; - QStringList layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &snappingDefinedInProject ); - QStringList enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); - QStringList toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); - QStringList toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); - QStringList snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); + QStringList layerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingList" ), QStringList(), &snappingDefinedInProject ); + QStringList enabledList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingEnabledList" ), QStringList(), &ok ); + QStringList toleranceList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingToleranceList" ), QStringList(), &ok ); + QStringList toleranceUnitList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingToleranceUnitList" ), QStringList(), &ok ); + QStringList snapToList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnapToList" ), QStringList(), &ok ); // lists must have the same size, otherwise something is wrong if ( layerIdList.size() != enabledList.size() || @@ -447,9 +447,9 @@ void QgsSnappingConfig::readLegacySettings() return; // nothing defined in project - use current layer // Use snapping information from the project - if ( snapMode == "current_layer" ) + if ( snapMode == QLatin1String( "current_layer" ) ) mMode = ActiveLayer; - else if ( snapMode == "all_layers" ) + else if ( snapMode == QLatin1String( "all_layers" ) ) mMode = AllLayers; else // either "advanced" or empty (for background compatibility) mMode = AdvancedConfiguration; @@ -466,12 +466,12 @@ void QgsSnappingConfig::readLegacySettings() if ( !vlayer || !vlayer->hasGeometryType() ) continue; - SnappingType t( *snapIt == "to_vertex" ? Vertex : - ( *snapIt == "to_segment" ? Segment : + SnappingType t( *snapIt == QLatin1String( "to_vertex" ) ? Vertex : + ( *snapIt == QLatin1String( "to_segment" ) ? Segment : VertexAndSegment ) ); - mIndividualLayerSettings.insert( vlayer, IndividualLayerSettings( *enabledIt == "enabled", t, tolIt->toDouble(), static_cast( tolUnitIt->toInt() ) ) ); + mIndividualLayerSettings.insert( vlayer, IndividualLayerSettings( *enabledIt == QLatin1String( "enabled" ), t, tolIt->toDouble(), static_cast( tolUnitIt->toInt() ) ) ); } } diff --git a/src/core/qgssnappingutils.cpp b/src/core/qgssnappingutils.cpp index 86c0198479aa..c0a810fe165d 100644 --- a/src/core/qgssnappingutils.cpp +++ b/src/core/qgssnappingutils.cpp @@ -447,11 +447,11 @@ void QgsSnappingUtils::setCurrentLayer( QgsVectorLayer* layer ) QString QgsSnappingUtils::dump() { - QString msg = "--- SNAPPING UTILS DUMP ---\n"; + QString msg = QStringLiteral( "--- SNAPPING UTILS DUMP ---\n" ); if ( !mMapSettings.hasValidSettings() ) { - msg += "invalid map settings!"; + msg += QLatin1String( "invalid map settings!" ); return msg; } @@ -461,7 +461,7 @@ QString QgsSnappingUtils::dump() { if ( mSnappingConfig.mode() == QgsSnappingConfig::ActiveLayer && !mCurrentLayer ) { - msg += "no current layer!"; + msg += QLatin1String( "no current layer!" ); return msg; } @@ -491,36 +491,36 @@ QString QgsSnappingUtils::dump() { if ( QgsPointLocator* loc = locatorForLayer( layer.layer ) ) { - QString extentStr, cachedGeoms, limit( "no max area" ); + QString extentStr, cachedGeoms, limit( QStringLiteral( "no max area" ) ); if ( const QgsRectangle* r = loc->extent() ) { - extentStr = QString( " extent %1" ).arg( r->toString() ); + extentStr = QStringLiteral( " extent %1" ).arg( r->toString() ); } else - extentStr = "full extent"; + extentStr = QStringLiteral( "full extent" ); if ( loc->hasIndex() ) - cachedGeoms = QString( "%1 feats" ).arg( loc->cachedGeometryCount() ); + cachedGeoms = QStringLiteral( "%1 feats" ).arg( loc->cachedGeometryCount() ); else - cachedGeoms = "not initialized"; + cachedGeoms = QStringLiteral( "not initialized" ); if ( mStrategy == IndexHybrid ) { if ( mHybridMaxAreaPerLayer.contains( layer.layer->id() ) ) { double maxArea = mStrategy == IndexHybrid ? mHybridMaxAreaPerLayer[layer.layer->id()] : -1; if ( maxArea != -1 ) - limit = QString( "max area %1" ).arg( maxArea ); + limit = QStringLiteral( "max area %1" ).arg( maxArea ); } else - limit = "not evaluated"; + limit = QStringLiteral( "not evaluated" ); } - msg += QString( "index : YES | %1 | %2 | %3\n" ).arg( cachedGeoms, extentStr, limit ); + msg += QStringLiteral( "index : YES | %1 | %2 | %3\n" ).arg( cachedGeoms, extentStr, limit ); } else - msg += QString( "index : ???\n" ); // should not happen + msg += QStringLiteral( "index : ???\n" ); // should not happen } else - msg += "index : NO\n"; - msg += "-\n"; + msg += QLatin1String( "index : NO\n" ); + msg += QLatin1String( "-\n" ); } return msg; diff --git a/src/core/qgssqlexpressioncompiler.cpp b/src/core/qgssqlexpressioncompiler.cpp index fd1dfaac885f..6ebac5507f28 100644 --- a/src/core/qgssqlexpressioncompiler.cpp +++ b/src/core/qgssqlexpressioncompiler.cpp @@ -38,7 +38,7 @@ QgsSqlExpressionCompiler::Result QgsSqlExpressionCompiler::compile( const QgsExp QString QgsSqlExpressionCompiler::quotedIdentifier( const QString& identifier ) { QString quoted = identifier; - quoted.replace( '"', "\"\"" ); + quoted.replace( '"', QLatin1String( "\"\"" ) ); quoted = quoted.prepend( '\"' ).append( '\"' ); return quoted; } @@ -48,7 +48,7 @@ QString QgsSqlExpressionCompiler::quotedValue( const QVariant& value, bool& ok ) ok = true; if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( value.type() ) { @@ -63,9 +63,9 @@ QString QgsSqlExpressionCompiler::quotedValue( const QVariant& value, bool& ok ) default: case QVariant::String: QString v = value.toString(); - v.replace( '\'', "''" ); + v.replace( '\'', QLatin1String( "''" ) ); if ( v.contains( '\\' ) ) - return v.replace( '\\', "\\\\" ).prepend( "E'" ).append( '\'' ); + return v.replace( '\\', QLatin1String( "\\\\" ) ).prepend( "E'" ).append( '\'' ); else return v.prepend( '\'' ).append( '\'' ); } @@ -128,48 +128,48 @@ QgsSqlExpressionCompiler::Result QgsSqlExpressionCompiler::compileNode( const Qg partialCompilation = true; } - op = "="; + op = QStringLiteral( "=" ); break; case QgsExpression::boGE: - op = ">="; + op = QStringLiteral( ">=" ); break; case QgsExpression::boGT: - op = ">"; + op = QStringLiteral( ">" ); break; case QgsExpression::boLE: - op = "<="; + op = QStringLiteral( "<=" ); break; case QgsExpression::boLT: - op = "<"; + op = QStringLiteral( "<" ); break; case QgsExpression::boIs: - op = "IS"; + op = QStringLiteral( "IS" ); break; case QgsExpression::boIsNot: - op = "IS NOT"; + op = QStringLiteral( "IS NOT" ); failOnPartialNode = mFlags.testFlag( CaseInsensitiveStringMatch ); break; case QgsExpression::boLike: - op = "LIKE"; + op = QStringLiteral( "LIKE" ); partialCompilation = mFlags.testFlag( LikeIsCaseInsensitive ); break; case QgsExpression::boILike: if ( mFlags.testFlag( LikeIsCaseInsensitive ) ) - op = "LIKE"; + op = QStringLiteral( "LIKE" ); else - op = "ILIKE"; + op = QStringLiteral( "ILIKE" ); break; case QgsExpression::boNotLike: - op = "NOT LIKE"; + op = QStringLiteral( "NOT LIKE" ); partialCompilation = mFlags.testFlag( LikeIsCaseInsensitive ); failOnPartialNode = mFlags.testFlag( CaseInsensitiveStringMatch ); break; @@ -177,9 +177,9 @@ QgsSqlExpressionCompiler::Result QgsSqlExpressionCompiler::compileNode( const Qg case QgsExpression::boNotILike: failOnPartialNode = mFlags.testFlag( CaseInsensitiveStringMatch ); if ( mFlags.testFlag( LikeIsCaseInsensitive ) ) - op = "NOT LIKE"; + op = QStringLiteral( "NOT LIKE" ); else - op = "NOT ILIKE"; + op = QStringLiteral( "NOT ILIKE" ); break; case QgsExpression::boOr: @@ -189,7 +189,7 @@ QgsSqlExpressionCompiler::Result QgsSqlExpressionCompiler::compileNode( const Qg return Fail; } - op = "OR"; + op = QStringLiteral( "OR" ); break; case QgsExpression::boAnd: @@ -199,46 +199,46 @@ QgsSqlExpressionCompiler::Result QgsSqlExpressionCompiler::compileNode( const Qg return Fail; } - op = "AND"; + op = QStringLiteral( "AND" ); break; case QgsExpression::boNE: failOnPartialNode = mFlags.testFlag( CaseInsensitiveStringMatch ); - op = "<>"; + op = QStringLiteral( "<>" ); break; case QgsExpression::boMul: - op = "*"; + op = QStringLiteral( "*" ); break; case QgsExpression::boPlus: - op = "+"; + op = QStringLiteral( "+" ); break; case QgsExpression::boMinus: - op = "-"; + op = QStringLiteral( "-" ); break; case QgsExpression::boDiv: return Fail; // handle cast to real case QgsExpression::boMod: - op = "%"; + op = QStringLiteral( "%" ); break; case QgsExpression::boConcat: - op = "||"; + op = QStringLiteral( "||" ); break; case QgsExpression::boIntDiv: return Fail; // handle cast to int case QgsExpression::boPow: - op = "^"; + op = QStringLiteral( "^" ); break; case QgsExpression::boRegexp: - op = "~"; + op = QStringLiteral( "~" ); break; } @@ -319,7 +319,7 @@ QgsSqlExpressionCompiler::Result QgsSqlExpressionCompiler::compileNode( const Qg if ( rn != Complete && rn != Partial ) return rn; - result = QString( "%1 %2IN(%3)" ).arg( nd, n->isNotIn() ? "NOT " : "", list.join( "," ) ); + result = QStringLiteral( "%1 %2IN(%3)" ).arg( nd, n->isNotIn() ? "NOT " : "", list.join( QStringLiteral( "," ) ) ); return ( inResult == Partial || rn == Partial ) ? Partial : Complete; } diff --git a/src/core/qgssqliteexpressioncompiler.cpp b/src/core/qgssqliteexpressioncompiler.cpp index 0130d6d28642..e0f87d557873 100644 --- a/src/core/qgssqliteexpressioncompiler.cpp +++ b/src/core/qgssqliteexpressioncompiler.cpp @@ -51,7 +51,7 @@ QgsSqlExpressionCompiler::Result QgsSQLiteExpressionCompiler::compileNode( const QString QgsSQLiteExpressionCompiler::quotedIdentifier( const QString& identifier ) { QString id( identifier ); - id.replace( '\"', "\"\"" ); + id.replace( '\"', QLatin1String( "\"\"" ) ); return id.prepend( '\"' ).append( '\"' ); } @@ -60,7 +60,7 @@ QString QgsSQLiteExpressionCompiler::quotedValue( const QVariant& value, bool& o ok = true; if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( value.type() ) { @@ -80,7 +80,7 @@ QString QgsSQLiteExpressionCompiler::quotedValue( const QVariant& value, bool& o // """A string constant is formed by enclosing the string in single quotes ('). // A single quote within the string can be encoded by putting two single quotes // in a row - as in Pascal. C-style escapes using the backslash character are not supported because they are not standard SQL. """ - return v.replace( '\'', "''" ).prepend( '\'' ).append( '\'' ); + return v.replace( '\'', QLatin1String( "''" ) ).prepend( '\'' ).append( '\'' ); } } diff --git a/src/core/qgssqlstatement.cpp b/src/core/qgssqlstatement.cpp index a117983e257e..bfad00b357e5 100644 --- a/src/core/qgssqlstatement.cpp +++ b/src/core/qgssqlstatement.cpp @@ -68,7 +68,7 @@ QString QgsSQLStatement::dump() const QString QgsSQLStatement::quotedIdentifier( QString name ) { - return QString( "\"%1\"" ).arg( name.replace( '\"', "\"\"" ) ); + return QStringLiteral( "\"%1\"" ).arg( name.replace( '\"', QLatin1String( "\"\"" ) ) ); } QString QgsSQLStatement::quotedIdentifierIfNeeded( const QString& name ) @@ -100,18 +100,18 @@ QString QgsSQLStatement::stripQuotedIdentifier( QString text ) text = text.mid( 1, text.length() - 2 ); // make single "double quotes" from double "double quotes" - text.replace( "\"\"", "\"" ); + text.replace( QLatin1String( "\"\"" ), QLatin1String( "\"" ) ); } return text; } QString QgsSQLStatement::quotedString( QString text ) { - text.replace( '\'', "''" ); - text.replace( '\\', "\\\\" ); - text.replace( '\n', "\\n" ); - text.replace( '\t', "\\t" ); - return QString( "'%1'" ).arg( text ); + text.replace( '\'', QLatin1String( "''" ) ); + text.replace( '\\', QLatin1String( "\\\\" ) ); + text.replace( '\n', QLatin1String( "\\n" ) ); + text.replace( '\t', QLatin1String( "\\t" ) ); + return QStringLiteral( "'%1'" ).arg( text ); } QgsSQLStatement::QgsSQLStatement( const QString& expr ) @@ -236,7 +236,7 @@ bool QgsSQLStatement::doBasicValidationChecks( QString& errorMsgOut ) const if ( !v.tableNamesDeclared.contains( pair.first ) ) { if ( !errorMsgOut.isEmpty() ) - errorMsgOut += " "; + errorMsgOut += QLatin1String( " " ); errorMsgOut += QString( tr( "Table %1 is referenced by column %2, but not selected in FROM / JOIN." ) ).arg( pair.first, pair.second ); } } @@ -264,7 +264,7 @@ QString QgsSQLStatement::NodeList::dump() const bool first = true; Q_FOREACH ( Node* n, mList ) { - if ( !first ) msg += ", "; + if ( !first ) msg += QLatin1String( ", " ); else first = false; msg += n->dump(); } @@ -276,7 +276,7 @@ QString QgsSQLStatement::NodeList::dump() const QString QgsSQLStatement::NodeUnaryOperator::dump() const { - return QString( "%1 %2" ).arg( UnaryOperatorText[mOp], mOperand->dump() ); + return QStringLiteral( "%1 %2" ).arg( UnaryOperatorText[mOp], mOperand->dump() ); } QgsSQLStatement::Node*QgsSQLStatement::NodeUnaryOperator::clone() const @@ -384,13 +384,13 @@ QString QgsSQLStatement::NodeBinaryOperator::dump() const if ( leftAssociative() ) { fmt += lOp && ( lOp->precedence() < precedence() ) ? "(%1)" : "%1"; - fmt += " %2 "; + fmt += QLatin1String( " %2 " ); fmt += rOp && ( rOp->precedence() <= precedence() ) ? "(%3)" : "%3"; } else { fmt += lOp && ( lOp->precedence() <= precedence() ) ? "(%1)" : "%1"; - fmt += " %2 "; + fmt += QLatin1String( " %2 " ); fmt += rOp && ( rOp->precedence() < precedence() ) ? "(%3)" : "%3"; } @@ -406,7 +406,7 @@ QgsSQLStatement::Node* QgsSQLStatement::NodeBinaryOperator::clone() const QString QgsSQLStatement::NodeInOperator::dump() const { - return QString( "%1 %2IN (%3)" ).arg( mNode->dump(), mNotIn ? "NOT " : "", mList->dump() ); + return QStringLiteral( "%1 %2IN (%3)" ).arg( mNode->dump(), mNotIn ? "NOT " : "", mList->dump() ); } QgsSQLStatement::Node* QgsSQLStatement::NodeInOperator::clone() const @@ -418,7 +418,7 @@ QgsSQLStatement::Node* QgsSQLStatement::NodeInOperator::clone() const QString QgsSQLStatement::NodeBetweenOperator::dump() const { - return QString( "%1 %2BETWEEN %3 AND %4" ).arg( mNode->dump(), mNotBetween ? "NOT " : "", mMinVal->dump(), mMaxVal->dump() ); + return QStringLiteral( "%1 %2BETWEEN %3 AND %4" ).arg( mNode->dump(), mNotBetween ? "NOT " : "", mMinVal->dump(), mMaxVal->dump() ); } QgsSQLStatement::Node* QgsSQLStatement::NodeBetweenOperator::clone() const @@ -430,7 +430,7 @@ QgsSQLStatement::Node* QgsSQLStatement::NodeBetweenOperator::clone() const QString QgsSQLStatement::NodeFunction::dump() const { - return QString( "%1(%2)" ).arg( mName, mArgs ? mArgs->dump() : QString() ); // function + return QStringLiteral( "%1(%2)" ).arg( mName, mArgs ? mArgs->dump() : QString() ); // function } QgsSQLStatement::Node* QgsSQLStatement::NodeFunction::clone() const @@ -443,7 +443,7 @@ QgsSQLStatement::Node* QgsSQLStatement::NodeFunction::clone() const QString QgsSQLStatement::NodeLiteral::dump() const { if ( mValue.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( mValue.type() ) { @@ -473,7 +473,7 @@ QString QgsSQLStatement::NodeColumnRef::dump() const { QString ret; if ( mDistinct ) - ret += "DISTINCT "; + ret += QLatin1String( "DISTINCT " ); if ( !mTableName.isEmpty() ) { ret += quotedIdentifierIfNeeded( mTableName ); @@ -503,7 +503,7 @@ QString QgsSQLStatement::NodeSelectedColumn::dump() const ret += mColumnNode->dump(); if ( !mAlias.isEmpty() ) { - ret += " AS "; + ret += QLatin1String( " AS " ); ret += quotedIdentifierIfNeeded( mAlias ); } return ret; @@ -528,7 +528,7 @@ QString QgsSQLStatement::NodeTableDef::dump() const ret = quotedIdentifierIfNeeded( mName ); if ( !mAlias.isEmpty() ) { - ret += " AS "; + ret += QLatin1String( " AS " ); ret += quotedIdentifierIfNeeded( mAlias ); } return ret; @@ -548,23 +548,23 @@ QgsSQLStatement::Node* QgsSQLStatement::NodeTableDef::clone() const QString QgsSQLStatement::NodeSelect::dump() const { - QString ret = "SELECT "; + QString ret = QStringLiteral( "SELECT " ); if ( mDistinct ) - ret += "DISTINCT "; + ret += QLatin1String( "DISTINCT " ); bool bFirstColumn = true; Q_FOREACH ( QgsSQLStatement::NodeSelectedColumn* column, mColumns ) { if ( !bFirstColumn ) - ret += ", "; + ret += QLatin1String( ", " ); bFirstColumn = false; ret += column->dump(); } - ret += " FROM "; + ret += QLatin1String( " FROM " ); bool bFirstTable = true; Q_FOREACH ( QgsSQLStatement::NodeTableDef* table, mTableList ) { if ( !bFirstTable ) - ret += ", "; + ret += QLatin1String( ", " ); bFirstTable = false; ret += table->dump(); } @@ -575,17 +575,17 @@ QString QgsSQLStatement::NodeSelect::dump() const } if ( mWhere != nullptr ) { - ret += " WHERE "; + ret += QLatin1String( " WHERE " ); ret += mWhere->dump(); } if ( !mOrderBy.isEmpty() ) { - ret += " ORDER BY "; + ret += QLatin1String( " ORDER BY " ); bool bFirst = true; Q_FOREACH ( QgsSQLStatement::NodeColumnSorted* orderBy, mOrderBy ) { if ( !bFirst ) - ret += ", "; + ret += QLatin1String( ", " ); bFirst = false; ret += orderBy->dump(); } @@ -631,27 +631,27 @@ QString QgsSQLStatement::NodeJoin::dump() const if ( mType != jtDefault ) { ret += JoinTypeText[mType]; - ret += " "; + ret += QLatin1String( " " ); } - ret += "JOIN "; + ret += QLatin1String( "JOIN " ); ret += mTableDef->dump(); if ( mOnExpr != nullptr ) { - ret += " ON "; + ret += QLatin1String( " ON " ); ret += mOnExpr->dump(); } else { - ret += " USING ("; + ret += QLatin1String( " USING (" ); bool first = true; Q_FOREACH ( QString column, mUsingColumns ) { if ( !first ) - ret += ", "; + ret += QLatin1String( ", " ); first = false; ret += quotedIdentifierIfNeeded( column ); } - ret += ")"; + ret += QLatin1String( ")" ); } return ret; } @@ -676,7 +676,7 @@ QString QgsSQLStatement::NodeColumnSorted::dump() const QString ret; ret = mColumn->dump(); if ( !mAsc ) - ret += " DESC"; + ret += QLatin1String( " DESC" ); return ret; } @@ -694,9 +694,9 @@ QgsSQLStatement::NodeColumnSorted* QgsSQLStatement::NodeColumnSorted::cloneThis( QString QgsSQLStatement::NodeCast::dump() const { - QString ret( "CAST(" ); + QString ret( QStringLiteral( "CAST(" ) ); ret += mNode->dump(); - ret += " AS "; + ret += QLatin1String( " AS " ); ret += mType; ret += ')'; return ret; diff --git a/src/core/qgsstringutils.cpp b/src/core/qgsstringutils.cpp index d407d2e91569..7ab1dddebb4b 100644 --- a/src/core/qgsstringutils.cpp +++ b/src/core/qgsstringutils.cpp @@ -362,7 +362,7 @@ QString QgsStringUtils::insertLinks( const QString& string, bool *foundLinks ) { protoUrl.prepend( "http://" ); } - QString anchor = QString( "%2" ).arg( Qt::escape( protoUrl ), Qt::escape( url ) ); + QString anchor = QStringLiteral( "%2" ).arg( Qt::escape( protoUrl ), Qt::escape( url ) ); converted.replace( urlRegEx.pos( 1 ), url.length(), anchor ); offset = urlRegEx.pos( 1 ) + anchor.length(); } @@ -371,7 +371,7 @@ QString QgsStringUtils::insertLinks( const QString& string, bool *foundLinks ) { found = true; QString email = emailRegEx.cap( 1 ); - QString anchor = QString( "%1" ).arg( Qt::escape( email ), Qt::escape( email ) ); + QString anchor = QStringLiteral( "%1" ).arg( Qt::escape( email ), Qt::escape( email ) ); converted.replace( emailRegEx.pos( 1 ), email.length(), anchor ); offset = emailRegEx.pos( 1 ) + anchor.length(); } @@ -409,19 +409,19 @@ QString QgsStringReplacement::process( const QString& input ) const QgsStringMap QgsStringReplacement::properties() const { QgsStringMap map; - map.insert( "match", mMatch ); - map.insert( "replace", mReplacement ); - map.insert( "caseSensitive", mCaseSensitive ? "1" : "0" ); - map.insert( "wholeWord", mWholeWordOnly ? "1" : "0" ); + map.insert( QStringLiteral( "match" ), mMatch ); + map.insert( QStringLiteral( "replace" ), mReplacement ); + map.insert( QStringLiteral( "caseSensitive" ), mCaseSensitive ? "1" : "0" ); + map.insert( QStringLiteral( "wholeWord" ), mWholeWordOnly ? "1" : "0" ); return map; } QgsStringReplacement QgsStringReplacement::fromProperties( const QgsStringMap& properties ) { - return QgsStringReplacement( properties.value( "match" ), - properties.value( "replace" ), - properties.value( "caseSensitive", "0" ) == "1", - properties.value( "wholeWord", "0" ) == "1" ); + return QgsStringReplacement( properties.value( QStringLiteral( "match" ) ), + properties.value( QStringLiteral( "replace" ) ), + properties.value( QStringLiteral( "caseSensitive" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ), + properties.value( QStringLiteral( "wholeWord" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); } QString QgsStringReplacementCollection::process( const QString& input ) const @@ -439,7 +439,7 @@ void QgsStringReplacementCollection::writeXml( QDomElement& elem, QDomDocument& Q_FOREACH ( const QgsStringReplacement& r, mReplacements ) { QgsStringMap props = r.properties(); - QDomElement propEl = doc.createElement( "replacement" ); + QDomElement propEl = doc.createElement( QStringLiteral( "replacement" ) ); QgsStringMap::const_iterator it = props.constBegin(); for ( ; it != props.constEnd(); ++it ) { @@ -452,7 +452,7 @@ void QgsStringReplacementCollection::writeXml( QDomElement& elem, QDomDocument& void QgsStringReplacementCollection::readXml( const QDomElement& elem ) { mReplacements.clear(); - QDomNodeList nodelist = elem.elementsByTagName( "replacement" ); + QDomNodeList nodelist = elem.elementsByTagName( QStringLiteral( "replacement" ) ); for ( int i = 0;i < nodelist.count(); i++ ) { QDomElement replacementElem = nodelist.at( i ).toElement(); diff --git a/src/core/qgstextrenderer.cpp b/src/core/qgstextrenderer.cpp index 8aad733add7e..f668d734c570 100644 --- a/src/core/qgstextrenderer.cpp +++ b/src/core/qgstextrenderer.cpp @@ -168,10 +168,10 @@ void QgsTextBufferSettings::setBlendMode( QPainter::CompositionMode mode ) void QgsTextBufferSettings::readFromLayer( QgsVectorLayer* layer ) { // text buffer - double bufSize = layer->customProperty( "labeling/bufferSize", QVariant( 0.0 ) ).toDouble(); + double bufSize = layer->customProperty( QStringLiteral( "labeling/bufferSize" ), QVariant( 0.0 ) ).toDouble(); // fix for buffer being keyed off of just its size in the past (<2.0) - QVariant drawBuffer = layer->customProperty( "labeling/bufferDraw", QVariant() ); + QVariant drawBuffer = layer->customProperty( QStringLiteral( "labeling/bufferDraw" ), QVariant() ); if ( drawBuffer.isValid() ) { d->enabled = drawBuffer.toBool(); @@ -188,62 +188,62 @@ void QgsTextBufferSettings::readFromLayer( QgsVectorLayer* layer ) d->enabled = false; } - if ( layer->customProperty( "labeling/bufferSizeUnits" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/bufferSizeUnits" ) ).toString().isEmpty() ) { - bool bufferSizeInMapUnits = layer->customProperty( "labeling/bufferSizeInMapUnits" ).toBool(); + bool bufferSizeInMapUnits = layer->customProperty( QStringLiteral( "labeling/bufferSizeInMapUnits" ) ).toBool(); d->sizeUnit = bufferSizeInMapUnits ? QgsUnitTypes::RenderMapUnits : QgsUnitTypes::RenderMillimeters; } else { - d->sizeUnit = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/bufferSizeUnits" ).toString() ); + d->sizeUnit = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/bufferSizeUnits" ) ).toString() ); } - if ( layer->customProperty( "labeling/bufferSizeMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/bufferSizeMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->sizeMapUnitScale.minScale = layer->customProperty( "labeling/bufferSizeMapUnitMinScale", 0.0 ).toDouble(); - d->sizeMapUnitScale.maxScale = layer->customProperty( "labeling/bufferSizeMapUnitMaxScale", 0.0 ).toDouble(); + d->sizeMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/bufferSizeMapUnitMinScale" ), 0.0 ).toDouble(); + d->sizeMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/bufferSizeMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/bufferSizeMapUnitScale" ).toString() ); + d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/bufferSizeMapUnitScale" ) ).toString() ); } - d->color = _readColor( layer, "labeling/bufferColor", Qt::white, false ); - if ( layer->customProperty( "labeling/bufferOpacity" ).toString().isEmpty() ) + d->color = _readColor( layer, QStringLiteral( "labeling/bufferColor" ), Qt::white, false ); + if ( layer->customProperty( QStringLiteral( "labeling/bufferOpacity" ) ).toString().isEmpty() ) { - d->opacity = ( 1 - layer->customProperty( "labeling/bufferTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( QStringLiteral( "labeling/bufferTransp" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( layer->customProperty( "labeling/bufferOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( QStringLiteral( "labeling/bufferOpacity" ) ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/bufferBlendMode", QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); - d->joinStyle = static_cast< Qt::PenJoinStyle >( layer->customProperty( "labeling/bufferJoinStyle", QVariant( Qt::RoundJoin ) ).toUInt() ); + static_cast< QgsPainting::BlendMode >( layer->customProperty( QStringLiteral( "labeling/bufferBlendMode" ), QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); + d->joinStyle = static_cast< Qt::PenJoinStyle >( layer->customProperty( QStringLiteral( "labeling/bufferJoinStyle" ), QVariant( Qt::RoundJoin ) ).toUInt() ); - d->fillBufferInterior = !layer->customProperty( "labeling/bufferNoFill", QVariant( false ) ).toBool(); + d->fillBufferInterior = !layer->customProperty( QStringLiteral( "labeling/bufferNoFill" ), QVariant( false ) ).toBool(); } void QgsTextBufferSettings::writeToLayer( QgsVectorLayer* layer ) const { - layer->setCustomProperty( "labeling/bufferDraw", d->enabled ); - layer->setCustomProperty( "labeling/bufferSize", d->size ); - layer->setCustomProperty( "labeling/bufferSizeUnits", QgsUnitTypes::encodeUnit( d->sizeUnit ) ); - layer->setCustomProperty( "labeling/bufferSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); - _writeColor( layer, "labeling/bufferColor", d->color ); - layer->setCustomProperty( "labeling/bufferNoFill", !d->fillBufferInterior ); - layer->setCustomProperty( "labeling/bufferOpacity", d->opacity ); - layer->setCustomProperty( "labeling/bufferJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); - layer->setCustomProperty( "labeling/bufferBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferDraw" ), d->enabled ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferSize" ), d->size ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferSizeUnits" ), QgsUnitTypes::encodeUnit( d->sizeUnit ) ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); + _writeColor( layer, QStringLiteral( "labeling/bufferColor" ), d->color ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferNoFill" ), !d->fillBufferInterior ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferOpacity" ), d->opacity ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferJoinStyle" ), static_cast< unsigned int >( d->joinStyle ) ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferBlendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); } void QgsTextBufferSettings::readXml( const QDomElement& elem ) { - QDomElement textBufferElem = elem.firstChildElement( "text-buffer" ); - double bufSize = textBufferElem.attribute( "bufferSize", "0" ).toDouble(); + QDomElement textBufferElem = elem.firstChildElement( QStringLiteral( "text-buffer" ) ); + double bufSize = textBufferElem.attribute( QStringLiteral( "bufferSize" ), QStringLiteral( "0" ) ).toDouble(); // fix for buffer being keyed off of just its size in the past (<2.0) - QVariant drawBuffer = textBufferElem.attribute( "bufferDraw" ); + QVariant drawBuffer = textBufferElem.attribute( QStringLiteral( "bufferDraw" ) ); if ( drawBuffer.isValid() ) { d->enabled = drawBuffer.toBool(); @@ -260,56 +260,56 @@ void QgsTextBufferSettings::readXml( const QDomElement& elem ) d->enabled = false; } - if ( !textBufferElem.hasAttribute( "bufferSizeUnits" ) ) + if ( !textBufferElem.hasAttribute( QStringLiteral( "bufferSizeUnits" ) ) ) { - bool bufferSizeInMapUnits = textBufferElem.attribute( "bufferSizeInMapUnits" ).toInt(); + bool bufferSizeInMapUnits = textBufferElem.attribute( QStringLiteral( "bufferSizeInMapUnits" ) ).toInt(); d->sizeUnit = bufferSizeInMapUnits ? QgsUnitTypes::RenderMapUnits : QgsUnitTypes::RenderMillimeters; } else { - d->sizeUnit = QgsUnitTypes::decodeRenderUnit( textBufferElem.attribute( "bufferSizeUnits" ) ); + d->sizeUnit = QgsUnitTypes::decodeRenderUnit( textBufferElem.attribute( QStringLiteral( "bufferSizeUnits" ) ) ); } - if ( !textBufferElem.hasAttribute( "bufferSizeMapUnitScale" ) ) + if ( !textBufferElem.hasAttribute( QStringLiteral( "bufferSizeMapUnitScale" ) ) ) { //fallback to older property - d->sizeMapUnitScale.minScale = textBufferElem.attribute( "bufferSizeMapUnitMinScale", "0" ).toDouble(); - d->sizeMapUnitScale.maxScale = textBufferElem.attribute( "bufferSizeMapUnitMaxScale", "0" ).toDouble(); + d->sizeMapUnitScale.minScale = textBufferElem.attribute( QStringLiteral( "bufferSizeMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->sizeMapUnitScale.maxScale = textBufferElem.attribute( QStringLiteral( "bufferSizeMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( textBufferElem.attribute( "bufferSizeMapUnitScale" ) ); + d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( textBufferElem.attribute( QStringLiteral( "bufferSizeMapUnitScale" ) ) ); } - d->color = QgsSymbolLayerUtils::decodeColor( textBufferElem.attribute( "bufferColor", QgsSymbolLayerUtils::encodeColor( Qt::white ) ) ); + d->color = QgsSymbolLayerUtils::decodeColor( textBufferElem.attribute( QStringLiteral( "bufferColor" ), QgsSymbolLayerUtils::encodeColor( Qt::white ) ) ); - if ( !textBufferElem.hasAttribute( "bufferOpacity" ) ) + if ( !textBufferElem.hasAttribute( QStringLiteral( "bufferOpacity" ) ) ) { - d->opacity = ( 1 - textBufferElem.attribute( "bufferTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - textBufferElem.attribute( QStringLiteral( "bufferTransp" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( textBufferElem.attribute( "bufferOpacity" ).toDouble() ); + d->opacity = ( textBufferElem.attribute( QStringLiteral( "bufferOpacity" ) ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( textBufferElem.attribute( "bufferBlendMode", QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); - d->joinStyle = static_cast< Qt::PenJoinStyle >( textBufferElem.attribute( "bufferJoinStyle", QString::number( Qt::RoundJoin ) ).toUInt() ); - d->fillBufferInterior = !textBufferElem.attribute( "bufferNoFill", "0" ).toInt(); + static_cast< QgsPainting::BlendMode >( textBufferElem.attribute( QStringLiteral( "bufferBlendMode" ), QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); + d->joinStyle = static_cast< Qt::PenJoinStyle >( textBufferElem.attribute( QStringLiteral( "bufferJoinStyle" ), QString::number( Qt::RoundJoin ) ).toUInt() ); + d->fillBufferInterior = !textBufferElem.attribute( QStringLiteral( "bufferNoFill" ), QStringLiteral( "0" ) ).toInt(); } QDomElement QgsTextBufferSettings::writeXml( QDomDocument& doc ) const { // text buffer - QDomElement textBufferElem = doc.createElement( "text-buffer" ); - textBufferElem.setAttribute( "bufferDraw", d->enabled ); - textBufferElem.setAttribute( "bufferSize", d->size ); - textBufferElem.setAttribute( "bufferSizeUnits", QgsUnitTypes::encodeUnit( d->sizeUnit ) ); - textBufferElem.setAttribute( "bufferSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); - textBufferElem.setAttribute( "bufferColor", QgsSymbolLayerUtils::encodeColor( d->color ) ); - textBufferElem.setAttribute( "bufferNoFill", !d->fillBufferInterior ); - textBufferElem.setAttribute( "bufferOpacity", d->opacity ); - textBufferElem.setAttribute( "bufferJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); - textBufferElem.setAttribute( "bufferBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); + QDomElement textBufferElem = doc.createElement( QStringLiteral( "text-buffer" ) ); + textBufferElem.setAttribute( QStringLiteral( "bufferDraw" ), d->enabled ); + textBufferElem.setAttribute( QStringLiteral( "bufferSize" ), d->size ); + textBufferElem.setAttribute( QStringLiteral( "bufferSizeUnits" ), QgsUnitTypes::encodeUnit( d->sizeUnit ) ); + textBufferElem.setAttribute( QStringLiteral( "bufferSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); + textBufferElem.setAttribute( QStringLiteral( "bufferColor" ), QgsSymbolLayerUtils::encodeColor( d->color ) ); + textBufferElem.setAttribute( QStringLiteral( "bufferNoFill" ), !d->fillBufferInterior ); + textBufferElem.setAttribute( QStringLiteral( "bufferOpacity" ), d->opacity ); + textBufferElem.setAttribute( QStringLiteral( "bufferJoinStyle" ), static_cast< unsigned int >( d->joinStyle ) ); + textBufferElem.setAttribute( QStringLiteral( "bufferBlendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); return textBufferElem; } @@ -572,293 +572,293 @@ void QgsTextBackgroundSettings::setJoinStyle( Qt::PenJoinStyle style ) void QgsTextBackgroundSettings::readFromLayer( QgsVectorLayer* layer ) { - d->enabled = layer->customProperty( "labeling/shapeDraw", QVariant( false ) ).toBool(); - d->type = static_cast< ShapeType >( layer->customProperty( "labeling/shapeType", QVariant( ShapeRectangle ) ).toUInt() ); - d->svgFile = layer->customProperty( "labeling/shapeSVGFile", QVariant( "" ) ).toString(); - d->sizeType = static_cast< SizeType >( layer->customProperty( "labeling/shapeSizeType", QVariant( SizeBuffer ) ).toUInt() ); - d->size = QSizeF( layer->customProperty( "labeling/shapeSizeX", QVariant( 0.0 ) ).toDouble(), - layer->customProperty( "labeling/shapeSizeY", QVariant( 0.0 ) ).toDouble() ); + d->enabled = layer->customProperty( QStringLiteral( "labeling/shapeDraw" ), QVariant( false ) ).toBool(); + d->type = static_cast< ShapeType >( layer->customProperty( QStringLiteral( "labeling/shapeType" ), QVariant( ShapeRectangle ) ).toUInt() ); + d->svgFile = layer->customProperty( QStringLiteral( "labeling/shapeSVGFile" ), QVariant( "" ) ).toString(); + d->sizeType = static_cast< SizeType >( layer->customProperty( QStringLiteral( "labeling/shapeSizeType" ), QVariant( SizeBuffer ) ).toUInt() ); + d->size = QSizeF( layer->customProperty( QStringLiteral( "labeling/shapeSizeX" ), QVariant( 0.0 ) ).toDouble(), + layer->customProperty( QStringLiteral( "labeling/shapeSizeY" ), QVariant( 0.0 ) ).toDouble() ); - if ( layer->customProperty( "labeling/shapeSizeUnit" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeSizeUnit" ) ).toString().isEmpty() ) { - d->sizeUnits = layer->customProperty( "labeling/shapeSizeUnits", 0 ).toUInt() == 0 ? + d->sizeUnits = layer->customProperty( QStringLiteral( "labeling/shapeSizeUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->sizeUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/shapeSizeUnit" ).toString() ); + d->sizeUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/shapeSizeUnit" ) ).toString() ); } - if ( layer->customProperty( "labeling/shapeSizeMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeSizeMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->sizeMapUnitScale.minScale = layer->customProperty( "labeling/shapeSizeMapUnitMinScale", 0.0 ).toDouble(); - d->sizeMapUnitScale.maxScale = layer->customProperty( "labeling/shapeSizeMapUnitMaxScale", 0.0 ).toDouble(); + d->sizeMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/shapeSizeMapUnitMinScale" ), 0.0 ).toDouble(); + d->sizeMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/shapeSizeMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/shapeSizeMapUnitScale" ).toString() ); + d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/shapeSizeMapUnitScale" ) ).toString() ); } - d->rotationType = static_cast< RotationType >( layer->customProperty( "labeling/shapeRotationType", QVariant( RotationSync ) ).toUInt() ); - d->rotation = layer->customProperty( "labeling/shapeRotation", QVariant( 0.0 ) ).toDouble(); - d->offset = QPointF( layer->customProperty( "labeling/shapeOffsetX", QVariant( 0.0 ) ).toDouble(), - layer->customProperty( "labeling/shapeOffsetY", QVariant( 0.0 ) ).toDouble() ); + d->rotationType = static_cast< RotationType >( layer->customProperty( QStringLiteral( "labeling/shapeRotationType" ), QVariant( RotationSync ) ).toUInt() ); + d->rotation = layer->customProperty( QStringLiteral( "labeling/shapeRotation" ), QVariant( 0.0 ) ).toDouble(); + d->offset = QPointF( layer->customProperty( QStringLiteral( "labeling/shapeOffsetX" ), QVariant( 0.0 ) ).toDouble(), + layer->customProperty( QStringLiteral( "labeling/shapeOffsetY" ), QVariant( 0.0 ) ).toDouble() ); - if ( layer->customProperty( "labeling/shapeOffsetUnit" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeOffsetUnit" ) ).toString().isEmpty() ) { - d->offsetUnits = layer->customProperty( "labeling/shapeOffsetUnits", 0 ).toUInt() == 0 ? + d->offsetUnits = layer->customProperty( QStringLiteral( "labeling/shapeOffsetUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->offsetUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/shapeOffsetUnit" ).toString() ); + d->offsetUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/shapeOffsetUnit" ) ).toString() ); } - if ( layer->customProperty( "labeling/shapeOffsetMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeOffsetMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->offsetMapUnitScale.minScale = layer->customProperty( "labeling/shapeOffsetMapUnitMinScale", 0.0 ).toDouble(); - d->offsetMapUnitScale.maxScale = layer->customProperty( "labeling/shapeOffsetMapUnitMaxScale", 0.0 ).toDouble(); + d->offsetMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/shapeOffsetMapUnitMinScale" ), 0.0 ).toDouble(); + d->offsetMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/shapeOffsetMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/shapeOffsetMapUnitScale" ).toString() ); + d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/shapeOffsetMapUnitScale" ) ).toString() ); } - d->radii = QSizeF( layer->customProperty( "labeling/shapeRadiiX", QVariant( 0.0 ) ).toDouble(), - layer->customProperty( "labeling/shapeRadiiY", QVariant( 0.0 ) ).toDouble() ); + d->radii = QSizeF( layer->customProperty( QStringLiteral( "labeling/shapeRadiiX" ), QVariant( 0.0 ) ).toDouble(), + layer->customProperty( QStringLiteral( "labeling/shapeRadiiY" ), QVariant( 0.0 ) ).toDouble() ); - if ( layer->customProperty( "labeling/shapeRadiiUnit" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeRadiiUnit" ) ).toString().isEmpty() ) { - d->radiiUnits = layer->customProperty( "labeling/shapeRadiiUnits", 0 ).toUInt() == 0 ? + d->radiiUnits = layer->customProperty( QStringLiteral( "labeling/shapeRadiiUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->radiiUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/shapeRadiiUnit" ).toString() ); + d->radiiUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/shapeRadiiUnit" ) ).toString() ); } - if ( layer->customProperty( "labeling/shapeRadiiMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeRadiiMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->radiiMapUnitScale.minScale = layer->customProperty( "labeling/shapeRadiiMapUnitMinScale", 0.0 ).toDouble(); - d->radiiMapUnitScale.maxScale = layer->customProperty( "labeling/shapeRadiiMapUnitMaxScale", 0.0 ).toDouble(); + d->radiiMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/shapeRadiiMapUnitMinScale" ), 0.0 ).toDouble(); + d->radiiMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/shapeRadiiMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->radiiMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/shapeRadiiMapUnitScale" ).toString() ); + d->radiiMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/shapeRadiiMapUnitScale" ) ).toString() ); } - d->fillColor = _readColor( layer, "labeling/shapeFillColor", Qt::white, true ); - d->borderColor = _readColor( layer, "labeling/shapeBorderColor", Qt::darkGray, true ); - d->borderWidth = layer->customProperty( "labeling/shapeBorderWidth", QVariant( .0 ) ).toDouble(); - if ( layer->customProperty( "labeling/shapeBorderWidthUnit" ).toString().isEmpty() ) + d->fillColor = _readColor( layer, QStringLiteral( "labeling/shapeFillColor" ), Qt::white, true ); + d->borderColor = _readColor( layer, QStringLiteral( "labeling/shapeBorderColor" ), Qt::darkGray, true ); + d->borderWidth = layer->customProperty( QStringLiteral( "labeling/shapeBorderWidth" ), QVariant( .0 ) ).toDouble(); + if ( layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthUnit" ) ).toString().isEmpty() ) { - d->borderWidthUnits = layer->customProperty( "labeling/shapeBorderWidthUnits", 0 ).toUInt() == 0 ? + d->borderWidthUnits = layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->borderWidthUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/shapeBorderWidthUnit" ).toString() ); + d->borderWidthUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthUnit" ) ).toString() ); } - if ( layer->customProperty( "labeling/shapeBorderWidthMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->borderWidthMapUnitScale.minScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMinScale", 0.0 ).toDouble(); - d->borderWidthMapUnitScale.maxScale = layer->customProperty( "labeling/shapeBorderWidthMapUnitMaxScale", 0.0 ).toDouble(); + d->borderWidthMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthMapUnitMinScale" ), 0.0 ).toDouble(); + d->borderWidthMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->borderWidthMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/shapeBorderWidthMapUnitScale" ).toString() ); + d->borderWidthMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/shapeBorderWidthMapUnitScale" ) ).toString() ); } - d->joinStyle = static_cast< Qt::PenJoinStyle >( layer->customProperty( "labeling/shapeJoinStyle", QVariant( Qt::BevelJoin ) ).toUInt() ); + d->joinStyle = static_cast< Qt::PenJoinStyle >( layer->customProperty( QStringLiteral( "labeling/shapeJoinStyle" ), QVariant( Qt::BevelJoin ) ).toUInt() ); - if ( layer->customProperty( "labeling/shapeOpacity" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shapeOpacity" ) ).toString().isEmpty() ) { - d->opacity = ( 1 - layer->customProperty( "labeling/shapeTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( QStringLiteral( "labeling/shapeTransparency" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( layer->customProperty( "labeling/shapeOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( QStringLiteral( "labeling/shapeOpacity" ) ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/shapeBlendMode", QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); + static_cast< QgsPainting::BlendMode >( layer->customProperty( QStringLiteral( "labeling/shapeBlendMode" ), QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); } void QgsTextBackgroundSettings::writeToLayer( QgsVectorLayer* layer ) const { - layer->setCustomProperty( "labeling/shapeDraw", d->enabled ); - layer->setCustomProperty( "labeling/shapeType", static_cast< unsigned int >( d->type ) ); - layer->setCustomProperty( "labeling/shapeSVGFile", d->svgFile ); - layer->setCustomProperty( "labeling/shapeSizeType", static_cast< unsigned int >( d->sizeType ) ); - layer->setCustomProperty( "labeling/shapeSizeX", d->size.width() ); - layer->setCustomProperty( "labeling/shapeSizeY", d->size.height() ); - layer->setCustomProperty( "labeling/shapeSizeUnit", QgsUnitTypes::encodeUnit( d->sizeUnits ) ); - layer->setCustomProperty( "labeling/shapeSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); - layer->setCustomProperty( "labeling/shapeRotationType", static_cast< unsigned int >( d->rotationType ) ); - layer->setCustomProperty( "labeling/shapeRotation", d->rotation ); - layer->setCustomProperty( "labeling/shapeOffsetX", d->offset.x() ); - layer->setCustomProperty( "labeling/shapeOffsetY", d->offset.y() ); - layer->setCustomProperty( "labeling/shapeOffsetUnit", QgsUnitTypes::encodeUnit( d->offsetUnits ) ); - layer->setCustomProperty( "labeling/shapeOffsetMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); - layer->setCustomProperty( "labeling/shapeRadiiX", d->radii.width() ); - layer->setCustomProperty( "labeling/shapeRadiiY", d->radii.height() ); - layer->setCustomProperty( "labeling/shapeRadiiUnit", QgsUnitTypes::encodeUnit( d->radiiUnits ) ); - layer->setCustomProperty( "labeling/shapeRadiiMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->radiiMapUnitScale ) ); - _writeColor( layer, "labeling/shapeFillColor", d->fillColor, true ); - _writeColor( layer, "labeling/shapeBorderColor", d->borderColor, true ); - layer->setCustomProperty( "labeling/shapeBorderWidth", d->borderWidth ); - layer->setCustomProperty( "labeling/shapeBorderWidthUnit", QgsUnitTypes::encodeUnit( d->borderWidthUnits ) ); - layer->setCustomProperty( "labeling/shapeBorderWidthMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->borderWidthMapUnitScale ) ); - layer->setCustomProperty( "labeling/shapeJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); - layer->setCustomProperty( "labeling/shapeOpacity", d->opacity ); - layer->setCustomProperty( "labeling/shapeBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeDraw" ), d->enabled ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeType" ), static_cast< unsigned int >( d->type ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeSVGFile" ), d->svgFile ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeSizeType" ), static_cast< unsigned int >( d->sizeType ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeSizeX" ), d->size.width() ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeSizeY" ), d->size.height() ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeSizeUnit" ), QgsUnitTypes::encodeUnit( d->sizeUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeRotationType" ), static_cast< unsigned int >( d->rotationType ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeRotation" ), d->rotation ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeOffsetX" ), d->offset.x() ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeOffsetY" ), d->offset.y() ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeOffsetUnit" ), QgsUnitTypes::encodeUnit( d->offsetUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeOffsetMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeRadiiX" ), d->radii.width() ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeRadiiY" ), d->radii.height() ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeRadiiUnit" ), QgsUnitTypes::encodeUnit( d->radiiUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeRadiiMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->radiiMapUnitScale ) ); + _writeColor( layer, QStringLiteral( "labeling/shapeFillColor" ), d->fillColor, true ); + _writeColor( layer, QStringLiteral( "labeling/shapeBorderColor" ), d->borderColor, true ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeBorderWidth" ), d->borderWidth ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeBorderWidthUnit" ), QgsUnitTypes::encodeUnit( d->borderWidthUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeBorderWidthMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->borderWidthMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeJoinStyle" ), static_cast< unsigned int >( d->joinStyle ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeOpacity" ), d->opacity ); + layer->setCustomProperty( QStringLiteral( "labeling/shapeBlendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); } void QgsTextBackgroundSettings::readXml( const QDomElement& elem ) { - QDomElement backgroundElem = elem.firstChildElement( "background" ); - d->enabled = backgroundElem.attribute( "shapeDraw", "0" ).toInt(); - d->type = static_cast< ShapeType >( backgroundElem.attribute( "shapeType", QString::number( ShapeRectangle ) ).toUInt() ); - d->svgFile = backgroundElem.attribute( "shapeSVGFile" ); - d->sizeType = static_cast< SizeType >( backgroundElem.attribute( "shapeSizeType", QString::number( SizeBuffer ) ).toUInt() ); - d->size = QSizeF( backgroundElem.attribute( "shapeSizeX", "0" ).toDouble(), - backgroundElem.attribute( "shapeSizeY", "0" ).toDouble() ); + QDomElement backgroundElem = elem.firstChildElement( QStringLiteral( "background" ) ); + d->enabled = backgroundElem.attribute( QStringLiteral( "shapeDraw" ), QStringLiteral( "0" ) ).toInt(); + d->type = static_cast< ShapeType >( backgroundElem.attribute( QStringLiteral( "shapeType" ), QString::number( ShapeRectangle ) ).toUInt() ); + d->svgFile = backgroundElem.attribute( QStringLiteral( "shapeSVGFile" ) ); + d->sizeType = static_cast< SizeType >( backgroundElem.attribute( QStringLiteral( "shapeSizeType" ), QString::number( SizeBuffer ) ).toUInt() ); + d->size = QSizeF( backgroundElem.attribute( QStringLiteral( "shapeSizeX" ), QStringLiteral( "0" ) ).toDouble(), + backgroundElem.attribute( QStringLiteral( "shapeSizeY" ), QStringLiteral( "0" ) ).toDouble() ); - if ( !backgroundElem.hasAttribute( "shapeSizeUnit" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeSizeUnit" ) ) ) { - d->sizeUnits = backgroundElem.attribute( "shapeSizeUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters + d->sizeUnits = backgroundElem.attribute( QStringLiteral( "shapeSizeUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->sizeUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( "shapeSizeUnit" ) ); + d->sizeUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( QStringLiteral( "shapeSizeUnit" ) ) ); } - if ( !backgroundElem.hasAttribute( "shapeSizeMapUnitScale" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeSizeMapUnitScale" ) ) ) { //fallback to older property - d->sizeMapUnitScale.minScale = backgroundElem.attribute( "shapeSizeMapUnitMinScale", "0" ).toDouble(); - d->sizeMapUnitScale.maxScale = backgroundElem.attribute( "shapeSizeMapUnitMaxScale", "0" ).toDouble(); + d->sizeMapUnitScale.minScale = backgroundElem.attribute( QStringLiteral( "shapeSizeMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->sizeMapUnitScale.maxScale = backgroundElem.attribute( QStringLiteral( "shapeSizeMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( "shapeSizeMapUnitScale" ) ); + d->sizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( QStringLiteral( "shapeSizeMapUnitScale" ) ) ); } - d->rotationType = static_cast< RotationType >( backgroundElem.attribute( "shapeRotationType", QString::number( RotationSync ) ).toUInt() ); - d->rotation = backgroundElem.attribute( "shapeRotation", "0" ).toDouble(); - d->offset = QPointF( backgroundElem.attribute( "shapeOffsetX", "0" ).toDouble(), - backgroundElem.attribute( "shapeOffsetY", "0" ).toDouble() ); + d->rotationType = static_cast< RotationType >( backgroundElem.attribute( QStringLiteral( "shapeRotationType" ), QString::number( RotationSync ) ).toUInt() ); + d->rotation = backgroundElem.attribute( QStringLiteral( "shapeRotation" ), QStringLiteral( "0" ) ).toDouble(); + d->offset = QPointF( backgroundElem.attribute( QStringLiteral( "shapeOffsetX" ), QStringLiteral( "0" ) ).toDouble(), + backgroundElem.attribute( QStringLiteral( "shapeOffsetY" ), QStringLiteral( "0" ) ).toDouble() ); - if ( !backgroundElem.hasAttribute( "shapeOffsetUnit" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeOffsetUnit" ) ) ) { - d->offsetUnits = backgroundElem.attribute( "shapeOffsetUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters + d->offsetUnits = backgroundElem.attribute( QStringLiteral( "shapeOffsetUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->offsetUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( "shapeOffsetUnit" ) ); + d->offsetUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( QStringLiteral( "shapeOffsetUnit" ) ) ); } - if ( !backgroundElem.hasAttribute( "shapeOffsetMapUnitScale" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeOffsetMapUnitScale" ) ) ) { //fallback to older property - d->offsetMapUnitScale.minScale = backgroundElem.attribute( "shapeOffsetMapUnitMinScale", "0" ).toDouble(); - d->offsetMapUnitScale.maxScale = backgroundElem.attribute( "shapeOffsetMapUnitMaxScale", "0" ).toDouble(); + d->offsetMapUnitScale.minScale = backgroundElem.attribute( QStringLiteral( "shapeOffsetMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->offsetMapUnitScale.maxScale = backgroundElem.attribute( QStringLiteral( "shapeOffsetMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( "shapeOffsetMapUnitScale" ) ); + d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( QStringLiteral( "shapeOffsetMapUnitScale" ) ) ); } - d->radii = QSizeF( backgroundElem.attribute( "shapeRadiiX", "0" ).toDouble(), - backgroundElem.attribute( "shapeRadiiY", "0" ).toDouble() ); + d->radii = QSizeF( backgroundElem.attribute( QStringLiteral( "shapeRadiiX" ), QStringLiteral( "0" ) ).toDouble(), + backgroundElem.attribute( QStringLiteral( "shapeRadiiY" ), QStringLiteral( "0" ) ).toDouble() ); - if ( !backgroundElem.hasAttribute( "shapeRadiiUnit" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeRadiiUnit" ) ) ) { - d->radiiUnits = backgroundElem.attribute( "shapeRadiiUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters + d->radiiUnits = backgroundElem.attribute( QStringLiteral( "shapeRadiiUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->radiiUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( "shapeRadiiUnit" ) ); + d->radiiUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( QStringLiteral( "shapeRadiiUnit" ) ) ); } - if ( !backgroundElem.hasAttribute( "shapeRadiiMapUnitScale" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeRadiiMapUnitScale" ) ) ) { //fallback to older property - d->radiiMapUnitScale.minScale = backgroundElem.attribute( "shapeRadiiMapUnitMinScale", "0" ).toDouble(); - d->radiiMapUnitScale.maxScale = backgroundElem.attribute( "shapeRadiiMapUnitMaxScale", "0" ).toDouble(); + d->radiiMapUnitScale.minScale = backgroundElem.attribute( QStringLiteral( "shapeRadiiMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->radiiMapUnitScale.maxScale = backgroundElem.attribute( QStringLiteral( "shapeRadiiMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->radiiMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( "shapeRadiiMapUnitScale" ) ); + d->radiiMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( QStringLiteral( "shapeRadiiMapUnitScale" ) ) ); } - d->fillColor = QgsSymbolLayerUtils::decodeColor( backgroundElem.attribute( "shapeFillColor", QgsSymbolLayerUtils::encodeColor( Qt::white ) ) ); - d->borderColor = QgsSymbolLayerUtils::decodeColor( backgroundElem.attribute( "shapeBorderColor", QgsSymbolLayerUtils::encodeColor( Qt::darkGray ) ) ); - d->borderWidth = backgroundElem.attribute( "shapeBorderWidth", "0" ).toDouble(); + d->fillColor = QgsSymbolLayerUtils::decodeColor( backgroundElem.attribute( QStringLiteral( "shapeFillColor" ), QgsSymbolLayerUtils::encodeColor( Qt::white ) ) ); + d->borderColor = QgsSymbolLayerUtils::decodeColor( backgroundElem.attribute( QStringLiteral( "shapeBorderColor" ), QgsSymbolLayerUtils::encodeColor( Qt::darkGray ) ) ); + d->borderWidth = backgroundElem.attribute( QStringLiteral( "shapeBorderWidth" ), QStringLiteral( "0" ) ).toDouble(); - if ( !backgroundElem.hasAttribute( "shapeBorderWidthUnit" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeBorderWidthUnit" ) ) ) { - d->borderWidthUnits = backgroundElem.attribute( "shapeBorderWidthUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters + d->borderWidthUnits = backgroundElem.attribute( QStringLiteral( "shapeBorderWidthUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->borderWidthUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( "shapeBorderWidthUnit" ) ); + d->borderWidthUnits = QgsUnitTypes::decodeRenderUnit( backgroundElem.attribute( QStringLiteral( "shapeBorderWidthUnit" ) ) ); } - if ( !backgroundElem.hasAttribute( "shapeBorderWidthMapUnitScale" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeBorderWidthMapUnitScale" ) ) ) { //fallback to older property - d->borderWidthMapUnitScale.minScale = backgroundElem.attribute( "shapeBorderWidthMapUnitMinScale", "0" ).toDouble(); - d->borderWidthMapUnitScale.maxScale = backgroundElem.attribute( "shapeBorderWidthMapUnitMaxScale", "0" ).toDouble(); + d->borderWidthMapUnitScale.minScale = backgroundElem.attribute( QStringLiteral( "shapeBorderWidthMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->borderWidthMapUnitScale.maxScale = backgroundElem.attribute( QStringLiteral( "shapeBorderWidthMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->borderWidthMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( "shapeBorderWidthMapUnitScale" ) ); + d->borderWidthMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( backgroundElem.attribute( QStringLiteral( "shapeBorderWidthMapUnitScale" ) ) ); } - d->joinStyle = static_cast< Qt::PenJoinStyle >( backgroundElem.attribute( "shapeJoinStyle", QString::number( Qt::BevelJoin ) ).toUInt() ); + d->joinStyle = static_cast< Qt::PenJoinStyle >( backgroundElem.attribute( QStringLiteral( "shapeJoinStyle" ), QString::number( Qt::BevelJoin ) ).toUInt() ); - if ( !backgroundElem.hasAttribute( "shapeOpacity" ) ) + if ( !backgroundElem.hasAttribute( QStringLiteral( "shapeOpacity" ) ) ) { - d->opacity = ( 1 - backgroundElem.attribute( "shapeTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - backgroundElem.attribute( QStringLiteral( "shapeTransparency" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( backgroundElem.attribute( "shapeOpacity" ).toDouble() ); + d->opacity = ( backgroundElem.attribute( QStringLiteral( "shapeOpacity" ) ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( backgroundElem.attribute( "shapeBlendMode", QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); + static_cast< QgsPainting::BlendMode >( backgroundElem.attribute( QStringLiteral( "shapeBlendMode" ), QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); } QDomElement QgsTextBackgroundSettings::writeXml( QDomDocument& doc ) const { - QDomElement backgroundElem = doc.createElement( "background" ); - backgroundElem.setAttribute( "shapeDraw", d->enabled ); - backgroundElem.setAttribute( "shapeType", static_cast< unsigned int >( d->type ) ); - backgroundElem.setAttribute( "shapeSVGFile", d->svgFile ); - backgroundElem.setAttribute( "shapeSizeType", static_cast< unsigned int >( d->sizeType ) ); - backgroundElem.setAttribute( "shapeSizeX", d->size.width() ); - backgroundElem.setAttribute( "shapeSizeY", d->size.height() ); - backgroundElem.setAttribute( "shapeSizeUnit", QgsUnitTypes::encodeUnit( d->sizeUnits ) ); - backgroundElem.setAttribute( "shapeSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); - backgroundElem.setAttribute( "shapeRotationType", static_cast< unsigned int >( d->rotationType ) ); - backgroundElem.setAttribute( "shapeRotation", d->rotation ); - backgroundElem.setAttribute( "shapeOffsetX", d->offset.x() ); - backgroundElem.setAttribute( "shapeOffsetY", d->offset.y() ); - backgroundElem.setAttribute( "shapeOffsetUnit", QgsUnitTypes::encodeUnit( d->offsetUnits ) ); - backgroundElem.setAttribute( "shapeOffsetMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); - backgroundElem.setAttribute( "shapeRadiiX", d->radii.width() ); - backgroundElem.setAttribute( "shapeRadiiY", d->radii.height() ); - backgroundElem.setAttribute( "shapeRadiiUnit", QgsUnitTypes::encodeUnit( d->radiiUnits ) ); - backgroundElem.setAttribute( "shapeRadiiMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->radiiMapUnitScale ) ); - backgroundElem.setAttribute( "shapeFillColor", QgsSymbolLayerUtils::encodeColor( d->fillColor ) ); - backgroundElem.setAttribute( "shapeBorderColor", QgsSymbolLayerUtils::encodeColor( d->borderColor ) ); - backgroundElem.setAttribute( "shapeBorderWidth", d->borderWidth ); - backgroundElem.setAttribute( "shapeBorderWidthUnit", QgsUnitTypes::encodeUnit( d->borderWidthUnits ) ); - backgroundElem.setAttribute( "shapeBorderWidthMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->borderWidthMapUnitScale ) ); - backgroundElem.setAttribute( "shapeJoinStyle", static_cast< unsigned int >( d->joinStyle ) ); - backgroundElem.setAttribute( "shapeOpacity", d->opacity ); - backgroundElem.setAttribute( "shapeBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); + QDomElement backgroundElem = doc.createElement( QStringLiteral( "background" ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeDraw" ), d->enabled ); + backgroundElem.setAttribute( QStringLiteral( "shapeType" ), static_cast< unsigned int >( d->type ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeSVGFile" ), d->svgFile ); + backgroundElem.setAttribute( QStringLiteral( "shapeSizeType" ), static_cast< unsigned int >( d->sizeType ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeSizeX" ), d->size.width() ); + backgroundElem.setAttribute( QStringLiteral( "shapeSizeY" ), d->size.height() ); + backgroundElem.setAttribute( QStringLiteral( "shapeSizeUnit" ), QgsUnitTypes::encodeUnit( d->sizeUnits ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->sizeMapUnitScale ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeRotationType" ), static_cast< unsigned int >( d->rotationType ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeRotation" ), d->rotation ); + backgroundElem.setAttribute( QStringLiteral( "shapeOffsetX" ), d->offset.x() ); + backgroundElem.setAttribute( QStringLiteral( "shapeOffsetY" ), d->offset.y() ); + backgroundElem.setAttribute( QStringLiteral( "shapeOffsetUnit" ), QgsUnitTypes::encodeUnit( d->offsetUnits ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeOffsetMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeRadiiX" ), d->radii.width() ); + backgroundElem.setAttribute( QStringLiteral( "shapeRadiiY" ), d->radii.height() ); + backgroundElem.setAttribute( QStringLiteral( "shapeRadiiUnit" ), QgsUnitTypes::encodeUnit( d->radiiUnits ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeRadiiMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->radiiMapUnitScale ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeFillColor" ), QgsSymbolLayerUtils::encodeColor( d->fillColor ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeBorderColor" ), QgsSymbolLayerUtils::encodeColor( d->borderColor ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeBorderWidth" ), d->borderWidth ); + backgroundElem.setAttribute( QStringLiteral( "shapeBorderWidthUnit" ), QgsUnitTypes::encodeUnit( d->borderWidthUnits ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeBorderWidthMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->borderWidthMapUnitScale ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeJoinStyle" ), static_cast< unsigned int >( d->joinStyle ) ); + backgroundElem.setAttribute( QStringLiteral( "shapeOpacity" ), d->opacity ); + backgroundElem.setAttribute( QStringLiteral( "shapeBlendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); return backgroundElem; } @@ -1041,171 +1041,171 @@ void QgsTextShadowSettings::setBlendMode( QPainter::CompositionMode mode ) void QgsTextShadowSettings::readFromLayer( QgsVectorLayer* layer ) { - d->enabled = layer->customProperty( "labeling/shadowDraw", QVariant( false ) ).toBool(); - d->shadowUnder = static_cast< ShadowPlacement >( layer->customProperty( "labeling/shadowUnder", QVariant( ShadowLowest ) ).toUInt() );//ShadowLowest; - d->offsetAngle = layer->customProperty( "labeling/shadowOffsetAngle", QVariant( 135 ) ).toInt(); - d->offsetDist = layer->customProperty( "labeling/shadowOffsetDist", QVariant( 1.0 ) ).toDouble(); + d->enabled = layer->customProperty( QStringLiteral( "labeling/shadowDraw" ), QVariant( false ) ).toBool(); + d->shadowUnder = static_cast< ShadowPlacement >( layer->customProperty( QStringLiteral( "labeling/shadowUnder" ), QVariant( ShadowLowest ) ).toUInt() );//ShadowLowest; + d->offsetAngle = layer->customProperty( QStringLiteral( "labeling/shadowOffsetAngle" ), QVariant( 135 ) ).toInt(); + d->offsetDist = layer->customProperty( QStringLiteral( "labeling/shadowOffsetDist" ), QVariant( 1.0 ) ).toDouble(); - if ( layer->customProperty( "labeling/shadowOffsetUnit" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shadowOffsetUnit" ) ).toString().isEmpty() ) { - d->offsetUnits = layer->customProperty( "labeling/shadowOffsetUnits", 0 ).toUInt() == 0 ? + d->offsetUnits = layer->customProperty( QStringLiteral( "labeling/shadowOffsetUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->offsetUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/shadowOffsetUnit" ).toString() ); + d->offsetUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/shadowOffsetUnit" ) ).toString() ); } - if ( layer->customProperty( "labeling/shadowOffsetMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shadowOffsetMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->offsetMapUnitScale.minScale = layer->customProperty( "labeling/shadowOffsetMapUnitMinScale", 0.0 ).toDouble(); - d->offsetMapUnitScale.maxScale = layer->customProperty( "labeling/shadowOffsetMapUnitMaxScale", 0.0 ).toDouble(); + d->offsetMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/shadowOffsetMapUnitMinScale" ), 0.0 ).toDouble(); + d->offsetMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/shadowOffsetMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/shadowOffsetMapUnitScale" ).toString() ); + d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/shadowOffsetMapUnitScale" ) ).toString() ); } - d->offsetGlobal = layer->customProperty( "labeling/shadowOffsetGlobal", QVariant( true ) ).toBool(); - d->radius = layer->customProperty( "labeling/shadowRadius", QVariant( 1.5 ) ).toDouble(); + d->offsetGlobal = layer->customProperty( QStringLiteral( "labeling/shadowOffsetGlobal" ), QVariant( true ) ).toBool(); + d->radius = layer->customProperty( QStringLiteral( "labeling/shadowRadius" ), QVariant( 1.5 ) ).toDouble(); - if ( layer->customProperty( "labeling/shadowRadiusUnit" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shadowRadiusUnit" ) ).toString().isEmpty() ) { - d->radiusUnits = layer->customProperty( "labeling/shadowRadiusUnits", 0 ).toUInt() == 0 ? + d->radiusUnits = layer->customProperty( QStringLiteral( "labeling/shadowRadiusUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->radiusUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/shadowRadiusUnit" ).toString() ); + d->radiusUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/shadowRadiusUnit" ) ).toString() ); } - if ( layer->customProperty( "labeling/shadowRadiusMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shadowRadiusMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->radiusMapUnitScale.minScale = layer->customProperty( "labeling/shadowRadiusMapUnitMinScale", 0.0 ).toDouble(); - d->radiusMapUnitScale.maxScale = layer->customProperty( "labeling/shadowRadiusMapUnitMaxScale", 0.0 ).toDouble(); + d->radiusMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/shadowRadiusMapUnitMinScale" ), 0.0 ).toDouble(); + d->radiusMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/shadowRadiusMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->radiusMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/shadowRadiusMapUnitScale" ).toString() ); + d->radiusMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/shadowRadiusMapUnitScale" ) ).toString() ); } - d->radiusAlphaOnly = layer->customProperty( "labeling/shadowRadiusAlphaOnly", QVariant( false ) ).toBool(); + d->radiusAlphaOnly = layer->customProperty( QStringLiteral( "labeling/shadowRadiusAlphaOnly" ), QVariant( false ) ).toBool(); - if ( layer->customProperty( "labeling/shadowOpacity" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/shadowOpacity" ) ).toString().isEmpty() ) { - d->opacity = ( 1 - layer->customProperty( "labeling/shadowTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( QStringLiteral( "labeling/shadowTransparency" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( layer->customProperty( "labeling/shadowOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( QStringLiteral( "labeling/shadowOpacity" ) ).toDouble() ); } - d->scale = layer->customProperty( "labeling/shadowScale", QVariant( 100 ) ).toInt(); - d->color = _readColor( layer, "labeling/shadowColor", Qt::black, false ); + d->scale = layer->customProperty( QStringLiteral( "labeling/shadowScale" ), QVariant( 100 ) ).toInt(); + d->color = _readColor( layer, QStringLiteral( "labeling/shadowColor" ), Qt::black, false ); d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/shadowBlendMode", QVariant( QgsPainting::BlendMultiply ) ).toUInt() ) ); + static_cast< QgsPainting::BlendMode >( layer->customProperty( QStringLiteral( "labeling/shadowBlendMode" ), QVariant( QgsPainting::BlendMultiply ) ).toUInt() ) ); } void QgsTextShadowSettings::writeToLayer( QgsVectorLayer* layer ) const { - layer->setCustomProperty( "labeling/shadowDraw", d->enabled ); - layer->setCustomProperty( "labeling/shadowUnder", static_cast< unsigned int >( d->shadowUnder ) ); - layer->setCustomProperty( "labeling/shadowOffsetAngle", d->offsetAngle ); - layer->setCustomProperty( "labeling/shadowOffsetDist", d->offsetDist ); - layer->setCustomProperty( "labeling/shadowOffsetUnit", QgsUnitTypes::encodeUnit( d->offsetUnits ) ); - layer->setCustomProperty( "labeling/shadowOffsetMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); - layer->setCustomProperty( "labeling/shadowOffsetGlobal", d->offsetGlobal ); - layer->setCustomProperty( "labeling/shadowRadius", d->radius ); - layer->setCustomProperty( "labeling/shadowRadiusUnit", QgsUnitTypes::encodeUnit( d->radiusUnits ) ); - layer->setCustomProperty( "labeling/shadowRadiusMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->radiusMapUnitScale ) ); - layer->setCustomProperty( "labeling/shadowRadiusAlphaOnly", d->radiusAlphaOnly ); - layer->setCustomProperty( "labeling/shadowOpacity", d->opacity ); - layer->setCustomProperty( "labeling/shadowScale", d->scale ); - _writeColor( layer, "labeling/shadowColor", d->color, false ); - layer->setCustomProperty( "labeling/shadowBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowDraw" ), d->enabled ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowUnder" ), static_cast< unsigned int >( d->shadowUnder ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowOffsetAngle" ), d->offsetAngle ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowOffsetDist" ), d->offsetDist ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowOffsetUnit" ), QgsUnitTypes::encodeUnit( d->offsetUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowOffsetMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowOffsetGlobal" ), d->offsetGlobal ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowRadius" ), d->radius ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowRadiusUnit" ), QgsUnitTypes::encodeUnit( d->radiusUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowRadiusMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->radiusMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowRadiusAlphaOnly" ), d->radiusAlphaOnly ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowOpacity" ), d->opacity ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowScale" ), d->scale ); + _writeColor( layer, QStringLiteral( "labeling/shadowColor" ), d->color, false ); + layer->setCustomProperty( QStringLiteral( "labeling/shadowBlendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); } void QgsTextShadowSettings::readXml( const QDomElement& elem ) { - QDomElement shadowElem = elem.firstChildElement( "shadow" ); - d->enabled = shadowElem.attribute( "shadowDraw", "0" ).toInt(); - d->shadowUnder = static_cast< ShadowPlacement >( shadowElem.attribute( "shadowUnder", QString::number( ShadowLowest ) ).toUInt() );//ShadowLowest ; - d->offsetAngle = shadowElem.attribute( "shadowOffsetAngle", "135" ).toInt(); - d->offsetDist = shadowElem.attribute( "shadowOffsetDist", "1" ).toDouble(); + QDomElement shadowElem = elem.firstChildElement( QStringLiteral( "shadow" ) ); + d->enabled = shadowElem.attribute( QStringLiteral( "shadowDraw" ), QStringLiteral( "0" ) ).toInt(); + d->shadowUnder = static_cast< ShadowPlacement >( shadowElem.attribute( QStringLiteral( "shadowUnder" ), QString::number( ShadowLowest ) ).toUInt() );//ShadowLowest ; + d->offsetAngle = shadowElem.attribute( QStringLiteral( "shadowOffsetAngle" ), QStringLiteral( "135" ) ).toInt(); + d->offsetDist = shadowElem.attribute( QStringLiteral( "shadowOffsetDist" ), QStringLiteral( "1" ) ).toDouble(); - if ( !shadowElem.hasAttribute( "shadowOffsetUnit" ) ) + if ( !shadowElem.hasAttribute( QStringLiteral( "shadowOffsetUnit" ) ) ) { - d->offsetUnits = shadowElem.attribute( "shadowOffsetUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters + d->offsetUnits = shadowElem.attribute( QStringLiteral( "shadowOffsetUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->offsetUnits = QgsUnitTypes::decodeRenderUnit( shadowElem.attribute( "shadowOffsetUnit" ) ); + d->offsetUnits = QgsUnitTypes::decodeRenderUnit( shadowElem.attribute( QStringLiteral( "shadowOffsetUnit" ) ) ); } - if ( !shadowElem.hasAttribute( "shadowOffsetMapUnitScale" ) ) + if ( !shadowElem.hasAttribute( QStringLiteral( "shadowOffsetMapUnitScale" ) ) ) { //fallback to older property - d->offsetMapUnitScale.minScale = shadowElem.attribute( "shadowOffsetMapUnitMinScale", "0" ).toDouble(); - d->offsetMapUnitScale.maxScale = shadowElem.attribute( "shadowOffsetMapUnitMaxScale", "0" ).toDouble(); + d->offsetMapUnitScale.minScale = shadowElem.attribute( QStringLiteral( "shadowOffsetMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->offsetMapUnitScale.maxScale = shadowElem.attribute( QStringLiteral( "shadowOffsetMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( shadowElem.attribute( "shadowOffsetMapUnitScale" ) ); + d->offsetMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( shadowElem.attribute( QStringLiteral( "shadowOffsetMapUnitScale" ) ) ); } - d->offsetGlobal = shadowElem.attribute( "shadowOffsetGlobal", "1" ).toInt(); - d->radius = shadowElem.attribute( "shadowRadius", "1.5" ).toDouble(); + d->offsetGlobal = shadowElem.attribute( QStringLiteral( "shadowOffsetGlobal" ), QStringLiteral( "1" ) ).toInt(); + d->radius = shadowElem.attribute( QStringLiteral( "shadowRadius" ), QStringLiteral( "1.5" ) ).toDouble(); - if ( !shadowElem.hasAttribute( "shadowRadiusUnit" ) ) + if ( !shadowElem.hasAttribute( QStringLiteral( "shadowRadiusUnit" ) ) ) { - d->radiusUnits = shadowElem.attribute( "shadowRadiusUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters + d->radiusUnits = shadowElem.attribute( QStringLiteral( "shadowRadiusUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderMillimeters : QgsUnitTypes::RenderMapUnits; } else { - d->radiusUnits = QgsUnitTypes::decodeRenderUnit( shadowElem.attribute( "shadowRadiusUnit" ) ); + d->radiusUnits = QgsUnitTypes::decodeRenderUnit( shadowElem.attribute( QStringLiteral( "shadowRadiusUnit" ) ) ); } - if ( !shadowElem.hasAttribute( "shadowRadiusMapUnitScale" ) ) + if ( !shadowElem.hasAttribute( QStringLiteral( "shadowRadiusMapUnitScale" ) ) ) { //fallback to older property - d->radiusMapUnitScale.minScale = shadowElem.attribute( "shadowRadiusMapUnitMinScale", "0" ).toDouble(); - d->radiusMapUnitScale.maxScale = shadowElem.attribute( "shadowRadiusMapUnitMaxScale", "0" ).toDouble(); + d->radiusMapUnitScale.minScale = shadowElem.attribute( QStringLiteral( "shadowRadiusMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->radiusMapUnitScale.maxScale = shadowElem.attribute( QStringLiteral( "shadowRadiusMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->radiusMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( shadowElem.attribute( "shadowRadiusMapUnitScale" ) ); + d->radiusMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( shadowElem.attribute( QStringLiteral( "shadowRadiusMapUnitScale" ) ) ); } - d->radiusAlphaOnly = shadowElem.attribute( "shadowRadiusAlphaOnly", "0" ).toInt(); + d->radiusAlphaOnly = shadowElem.attribute( QStringLiteral( "shadowRadiusAlphaOnly" ), QStringLiteral( "0" ) ).toInt(); - if ( !shadowElem.hasAttribute( "shadowOpacity" ) ) + if ( !shadowElem.hasAttribute( QStringLiteral( "shadowOpacity" ) ) ) { - d->opacity = ( 1 - shadowElem.attribute( "shadowTransparency" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - shadowElem.attribute( QStringLiteral( "shadowTransparency" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( shadowElem.attribute( "shadowOpacity" ).toDouble() ); + d->opacity = ( shadowElem.attribute( QStringLiteral( "shadowOpacity" ) ).toDouble() ); } - d->scale = shadowElem.attribute( "shadowScale", "100" ).toInt(); - d->color = QgsSymbolLayerUtils::decodeColor( shadowElem.attribute( "shadowColor", QgsSymbolLayerUtils::encodeColor( Qt::black ) ) ); + d->scale = shadowElem.attribute( QStringLiteral( "shadowScale" ), QStringLiteral( "100" ) ).toInt(); + d->color = QgsSymbolLayerUtils::decodeColor( shadowElem.attribute( QStringLiteral( "shadowColor" ), QgsSymbolLayerUtils::encodeColor( Qt::black ) ) ); d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( shadowElem.attribute( "shadowBlendMode", QString::number( QgsPainting::BlendMultiply ) ).toUInt() ) ); + static_cast< QgsPainting::BlendMode >( shadowElem.attribute( QStringLiteral( "shadowBlendMode" ), QString::number( QgsPainting::BlendMultiply ) ).toUInt() ) ); } QDomElement QgsTextShadowSettings::writeXml( QDomDocument& doc ) const { - QDomElement shadowElem = doc.createElement( "shadow" ); - shadowElem.setAttribute( "shadowDraw", d->enabled ); - shadowElem.setAttribute( "shadowUnder", static_cast< unsigned int >( d->shadowUnder ) ); - shadowElem.setAttribute( "shadowOffsetAngle", d->offsetAngle ); - shadowElem.setAttribute( "shadowOffsetDist", d->offsetDist ); - shadowElem.setAttribute( "shadowOffsetUnit", QgsUnitTypes::encodeUnit( d->offsetUnits ) ); - shadowElem.setAttribute( "shadowOffsetMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); - shadowElem.setAttribute( "shadowOffsetGlobal", d->offsetGlobal ); - shadowElem.setAttribute( "shadowRadius", d->radius ); - shadowElem.setAttribute( "shadowRadiusUnit", QgsUnitTypes::encodeUnit( d->radiusUnits ) ); - shadowElem.setAttribute( "shadowRadiusMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->radiusMapUnitScale ) ); - shadowElem.setAttribute( "shadowRadiusAlphaOnly", d->radiusAlphaOnly ); - shadowElem.setAttribute( "shadowOpacity", d->opacity ); - shadowElem.setAttribute( "shadowScale", d->scale ); - shadowElem.setAttribute( "shadowColor", QgsSymbolLayerUtils::encodeColor( d->color ) ); - shadowElem.setAttribute( "shadowBlendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); + QDomElement shadowElem = doc.createElement( QStringLiteral( "shadow" ) ); + shadowElem.setAttribute( QStringLiteral( "shadowDraw" ), d->enabled ); + shadowElem.setAttribute( QStringLiteral( "shadowUnder" ), static_cast< unsigned int >( d->shadowUnder ) ); + shadowElem.setAttribute( QStringLiteral( "shadowOffsetAngle" ), d->offsetAngle ); + shadowElem.setAttribute( QStringLiteral( "shadowOffsetDist" ), d->offsetDist ); + shadowElem.setAttribute( QStringLiteral( "shadowOffsetUnit" ), QgsUnitTypes::encodeUnit( d->offsetUnits ) ); + shadowElem.setAttribute( QStringLiteral( "shadowOffsetMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->offsetMapUnitScale ) ); + shadowElem.setAttribute( QStringLiteral( "shadowOffsetGlobal" ), d->offsetGlobal ); + shadowElem.setAttribute( QStringLiteral( "shadowRadius" ), d->radius ); + shadowElem.setAttribute( QStringLiteral( "shadowRadiusUnit" ), QgsUnitTypes::encodeUnit( d->radiusUnits ) ); + shadowElem.setAttribute( QStringLiteral( "shadowRadiusMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->radiusMapUnitScale ) ); + shadowElem.setAttribute( QStringLiteral( "shadowRadiusAlphaOnly" ), d->radiusAlphaOnly ); + shadowElem.setAttribute( QStringLiteral( "shadowOpacity" ), d->opacity ); + shadowElem.setAttribute( QStringLiteral( "shadowScale" ), d->scale ); + shadowElem.setAttribute( QStringLiteral( "shadowColor" ), QgsSymbolLayerUtils::encodeColor( d->color ) ); + shadowElem.setAttribute( QStringLiteral( "shadowBlendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); return shadowElem; } @@ -1353,7 +1353,7 @@ void QgsTextFormat::setLineHeight( double height ) void QgsTextFormat::readFromLayer( QgsVectorLayer* layer ) { QFont appFont = QApplication::font(); - mTextFontFamily = layer->customProperty( "labeling/fontFamily", QVariant( appFont.family() ) ).toString(); + mTextFontFamily = layer->customProperty( QStringLiteral( "labeling/fontFamily" ), QVariant( appFont.family() ) ).toString(); QString fontFamily = mTextFontFamily; if ( mTextFontFamily != appFont.family() && !QgsFontUtils::fontFamilyMatchOnSystem( mTextFontFamily ) ) { @@ -1371,59 +1371,59 @@ void QgsTextFormat::readFromLayer( QgsVectorLayer* layer ) mTextFontFound = true; } - if ( !layer->customProperty( "labeling/fontSize" ).isValid() ) + if ( !layer->customProperty( QStringLiteral( "labeling/fontSize" ) ).isValid() ) { d->fontSize = appFont.pointSizeF(); } else { - d->fontSize = layer->customProperty( "labeling/fontSize" ).toDouble(); + d->fontSize = layer->customProperty( QStringLiteral( "labeling/fontSize" ) ).toDouble(); } - if ( layer->customProperty( "labeling/fontSizeUnit" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/fontSizeUnit" ) ).toString().isEmpty() ) { - d->fontSizeUnits = layer->customProperty( "labeling/fontSizeInMapUnits", 0 ).toUInt() == 0 ? + d->fontSizeUnits = layer->customProperty( QStringLiteral( "labeling/fontSizeInMapUnits" ), 0 ).toUInt() == 0 ? QgsUnitTypes::RenderPoints : QgsUnitTypes::RenderMapUnits; } else { bool ok = false; - d->fontSizeUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( "labeling/fontSizeUnit" ).toString(), &ok ); + d->fontSizeUnits = QgsUnitTypes::decodeRenderUnit( layer->customProperty( QStringLiteral( "labeling/fontSizeUnit" ) ).toString(), &ok ); if ( !ok ) d->fontSizeUnits = QgsUnitTypes::RenderPoints; } - if ( layer->customProperty( "labeling/fontSizeMapUnitScale" ).toString().isEmpty() ) + if ( layer->customProperty( QStringLiteral( "labeling/fontSizeMapUnitScale" ) ).toString().isEmpty() ) { //fallback to older property - d->fontSizeMapUnitScale.minScale = layer->customProperty( "labeling/fontSizeMapUnitMinScale", 0.0 ).toDouble(); - d->fontSizeMapUnitScale.maxScale = layer->customProperty( "labeling/fontSizeMapUnitMaxScale", 0.0 ).toDouble(); + d->fontSizeMapUnitScale.minScale = layer->customProperty( QStringLiteral( "labeling/fontSizeMapUnitMinScale" ), 0.0 ).toDouble(); + d->fontSizeMapUnitScale.maxScale = layer->customProperty( QStringLiteral( "labeling/fontSizeMapUnitMaxScale" ), 0.0 ).toDouble(); } else { - d->fontSizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( "labeling/fontSizeMapUnitScale" ).toString() ); + d->fontSizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( layer->customProperty( QStringLiteral( "labeling/fontSizeMapUnitScale" ) ).toString() ); } - int fontWeight = layer->customProperty( "labeling/fontWeight" ).toInt(); - bool fontItalic = layer->customProperty( "labeling/fontItalic" ).toBool(); + int fontWeight = layer->customProperty( QStringLiteral( "labeling/fontWeight" ) ).toInt(); + bool fontItalic = layer->customProperty( QStringLiteral( "labeling/fontItalic" ) ).toBool(); d->textFont = QFont( fontFamily, d->fontSize, fontWeight, fontItalic ); - d->textNamedStyle = QgsFontUtils::translateNamedStyle( layer->customProperty( "labeling/namedStyle", QVariant( "" ) ).toString() ); + d->textNamedStyle = QgsFontUtils::translateNamedStyle( layer->customProperty( QStringLiteral( "labeling/namedStyle" ), QVariant( "" ) ).toString() ); QgsFontUtils::updateFontViaStyle( d->textFont, d->textNamedStyle ); // must come after textFont.setPointSizeF() - d->textFont.setCapitalization( static_cast< QFont::Capitalization >( layer->customProperty( "labeling/fontCapitals", QVariant( 0 ) ).toUInt() ) ); - d->textFont.setUnderline( layer->customProperty( "labeling/fontUnderline" ).toBool() ); - d->textFont.setStrikeOut( layer->customProperty( "labeling/fontStrikeout" ).toBool() ); - d->textFont.setLetterSpacing( QFont::AbsoluteSpacing, layer->customProperty( "labeling/fontLetterSpacing", QVariant( 0.0 ) ).toDouble() ); - d->textFont.setWordSpacing( layer->customProperty( "labeling/fontWordSpacing", QVariant( 0.0 ) ).toDouble() ); - d->textColor = _readColor( layer, "labeling/textColor", Qt::black, false ); - if ( layer->customProperty( "labeling/textOpacity" ).toString().isEmpty() ) + d->textFont.setCapitalization( static_cast< QFont::Capitalization >( layer->customProperty( QStringLiteral( "labeling/fontCapitals" ), QVariant( 0 ) ).toUInt() ) ); + d->textFont.setUnderline( layer->customProperty( QStringLiteral( "labeling/fontUnderline" ) ).toBool() ); + d->textFont.setStrikeOut( layer->customProperty( QStringLiteral( "labeling/fontStrikeout" ) ).toBool() ); + d->textFont.setLetterSpacing( QFont::AbsoluteSpacing, layer->customProperty( QStringLiteral( "labeling/fontLetterSpacing" ), QVariant( 0.0 ) ).toDouble() ); + d->textFont.setWordSpacing( layer->customProperty( QStringLiteral( "labeling/fontWordSpacing" ), QVariant( 0.0 ) ).toDouble() ); + d->textColor = _readColor( layer, QStringLiteral( "labeling/textColor" ), Qt::black, false ); + if ( layer->customProperty( QStringLiteral( "labeling/textOpacity" ) ).toString().isEmpty() ) { - d->opacity = ( 1 - layer->customProperty( "labeling/textTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - layer->customProperty( QStringLiteral( "labeling/textTransp" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( layer->customProperty( "labeling/textOpacity" ).toDouble() ); + d->opacity = ( layer->customProperty( QStringLiteral( "labeling/textOpacity" ) ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( layer->customProperty( "labeling/blendMode", QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); - d->multilineHeight = layer->customProperty( "labeling/multilineHeight", QVariant( 1.0 ) ).toDouble(); + static_cast< QgsPainting::BlendMode >( layer->customProperty( QStringLiteral( "labeling/blendMode" ), QVariant( QgsPainting::BlendNormal ) ).toUInt() ) ); + d->multilineHeight = layer->customProperty( QStringLiteral( "labeling/multilineHeight" ), QVariant( 1.0 ) ).toDouble(); mBufferSettings.readFromLayer( layer ); mShadowSettings.readFromLayer( layer ); @@ -1432,23 +1432,23 @@ void QgsTextFormat::readFromLayer( QgsVectorLayer* layer ) void QgsTextFormat::writeToLayer( QgsVectorLayer* layer ) const { - layer->setCustomProperty( "labeling/fontFamily", d->textFont.family() ); - layer->setCustomProperty( "labeling/namedStyle", QgsFontUtils::untranslateNamedStyle( d->textNamedStyle ) ); - layer->setCustomProperty( "labeling/fontSize", d->fontSize ); - layer->setCustomProperty( "labeling/fontSizeUnit", QgsUnitTypes::encodeUnit( d->fontSizeUnits ) ); - layer->setCustomProperty( "labeling/fontSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->fontSizeMapUnitScale ) ); - layer->setCustomProperty( "labeling/fontWeight", d->textFont.weight() ); - layer->setCustomProperty( "labeling/fontItalic", d->textFont.italic() ); - layer->setCustomProperty( "labeling/fontStrikeout", d->textFont.strikeOut() ); - layer->setCustomProperty( "labeling/fontUnderline", d->textFont.underline() ); - _writeColor( layer, "labeling/textColor", d->textColor ); - layer->setCustomProperty( "labeling/textOpacity", d->opacity ); - layer->setCustomProperty( "labeling/fontCapitals", static_cast< unsigned int >( d->textFont.capitalization() ) ); - layer->setCustomProperty( "labeling/fontLetterSpacing", d->textFont.letterSpacing() ); - layer->setCustomProperty( "labeling/fontWordSpacing", d->textFont.wordSpacing() ); - layer->setCustomProperty( "labeling/textOpacity", d->opacity ); - layer->setCustomProperty( "labeling/blendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); - layer->setCustomProperty( "labeling/multilineHeight", d->multilineHeight ); + layer->setCustomProperty( QStringLiteral( "labeling/fontFamily" ), d->textFont.family() ); + layer->setCustomProperty( QStringLiteral( "labeling/namedStyle" ), QgsFontUtils::untranslateNamedStyle( d->textNamedStyle ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontSize" ), d->fontSize ); + layer->setCustomProperty( QStringLiteral( "labeling/fontSizeUnit" ), QgsUnitTypes::encodeUnit( d->fontSizeUnits ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->fontSizeMapUnitScale ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontWeight" ), d->textFont.weight() ); + layer->setCustomProperty( QStringLiteral( "labeling/fontItalic" ), d->textFont.italic() ); + layer->setCustomProperty( QStringLiteral( "labeling/fontStrikeout" ), d->textFont.strikeOut() ); + layer->setCustomProperty( QStringLiteral( "labeling/fontUnderline" ), d->textFont.underline() ); + _writeColor( layer, QStringLiteral( "labeling/textColor" ), d->textColor ); + layer->setCustomProperty( QStringLiteral( "labeling/textOpacity" ), d->opacity ); + layer->setCustomProperty( QStringLiteral( "labeling/fontCapitals" ), static_cast< unsigned int >( d->textFont.capitalization() ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontLetterSpacing" ), d->textFont.letterSpacing() ); + layer->setCustomProperty( QStringLiteral( "labeling/fontWordSpacing" ), d->textFont.wordSpacing() ); + layer->setCustomProperty( QStringLiteral( "labeling/textOpacity" ), d->opacity ); + layer->setCustomProperty( QStringLiteral( "labeling/blendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); + layer->setCustomProperty( QStringLiteral( "labeling/multilineHeight" ), d->multilineHeight ); mBufferSettings.writeToLayer( layer ); mShadowSettings.writeToLayer( layer ); @@ -1457,9 +1457,9 @@ void QgsTextFormat::writeToLayer( QgsVectorLayer* layer ) const void QgsTextFormat::readXml( const QDomElement& elem ) { - QDomElement textStyleElem = elem.firstChildElement( "text-style" ); + QDomElement textStyleElem = elem.firstChildElement( QStringLiteral( "text-style" ) ); QFont appFont = QApplication::font(); - mTextFontFamily = textStyleElem.attribute( "fontFamily", appFont.family() ); + mTextFontFamily = textStyleElem.attribute( QStringLiteral( "fontFamily" ), appFont.family() ); QString fontFamily = mTextFontFamily; if ( mTextFontFamily != appFont.family() && !QgsFontUtils::fontFamilyMatchOnSystem( mTextFontFamily ) ) { @@ -1477,69 +1477,69 @@ void QgsTextFormat::readXml( const QDomElement& elem ) mTextFontFound = true; } - if ( textStyleElem.hasAttribute( "fontSize" ) ) + if ( textStyleElem.hasAttribute( QStringLiteral( "fontSize" ) ) ) { - d->fontSize = textStyleElem.attribute( "fontSize" ).toDouble(); + d->fontSize = textStyleElem.attribute( QStringLiteral( "fontSize" ) ).toDouble(); } else { d->fontSize = appFont.pointSizeF(); } - if ( !textStyleElem.hasAttribute( "fontSizeUnit" ) ) + if ( !textStyleElem.hasAttribute( QStringLiteral( "fontSizeUnit" ) ) ) { - d->fontSizeUnits = textStyleElem.attribute( "fontSizeInMapUnits" ).toUInt() == 0 ? QgsUnitTypes::RenderPoints + d->fontSizeUnits = textStyleElem.attribute( QStringLiteral( "fontSizeInMapUnits" ) ).toUInt() == 0 ? QgsUnitTypes::RenderPoints : QgsUnitTypes::RenderMapUnits; } else { - d->fontSizeUnits = QgsUnitTypes::decodeRenderUnit( textStyleElem.attribute( "fontSizeUnit" ) ); + d->fontSizeUnits = QgsUnitTypes::decodeRenderUnit( textStyleElem.attribute( QStringLiteral( "fontSizeUnit" ) ) ); } - if ( !textStyleElem.hasAttribute( "fontSizeMapUnitScale" ) ) + if ( !textStyleElem.hasAttribute( QStringLiteral( "fontSizeMapUnitScale" ) ) ) { //fallback to older property - d->fontSizeMapUnitScale.minScale = textStyleElem.attribute( "fontSizeMapUnitMinScale", "0" ).toDouble(); - d->fontSizeMapUnitScale.maxScale = textStyleElem.attribute( "fontSizeMapUnitMaxScale", "0" ).toDouble(); + d->fontSizeMapUnitScale.minScale = textStyleElem.attribute( QStringLiteral( "fontSizeMapUnitMinScale" ), QStringLiteral( "0" ) ).toDouble(); + d->fontSizeMapUnitScale.maxScale = textStyleElem.attribute( QStringLiteral( "fontSizeMapUnitMaxScale" ), QStringLiteral( "0" ) ).toDouble(); } else { - d->fontSizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( textStyleElem.attribute( "fontSizeMapUnitScale" ) ); + d->fontSizeMapUnitScale = QgsSymbolLayerUtils::decodeMapUnitScale( textStyleElem.attribute( QStringLiteral( "fontSizeMapUnitScale" ) ) ); } - int fontWeight = textStyleElem.attribute( "fontWeight" ).toInt(); - bool fontItalic = textStyleElem.attribute( "fontItalic" ).toInt(); + int fontWeight = textStyleElem.attribute( QStringLiteral( "fontWeight" ) ).toInt(); + bool fontItalic = textStyleElem.attribute( QStringLiteral( "fontItalic" ) ).toInt(); d->textFont = QFont( fontFamily, d->fontSize, fontWeight, fontItalic ); d->textFont.setPointSizeF( d->fontSize ); //double precision needed because of map units - d->textNamedStyle = QgsFontUtils::translateNamedStyle( textStyleElem.attribute( "namedStyle" ) ); + d->textNamedStyle = QgsFontUtils::translateNamedStyle( textStyleElem.attribute( QStringLiteral( "namedStyle" ) ) ); QgsFontUtils::updateFontViaStyle( d->textFont, d->textNamedStyle ); // must come after textFont.setPointSizeF() - d->textFont.setCapitalization( static_cast< QFont::Capitalization >( textStyleElem.attribute( "fontCapitals", "0" ).toUInt() ) ); - d->textFont.setUnderline( textStyleElem.attribute( "fontUnderline" ).toInt() ); - d->textFont.setStrikeOut( textStyleElem.attribute( "fontStrikeout" ).toInt() ); - d->textFont.setLetterSpacing( QFont::AbsoluteSpacing, textStyleElem.attribute( "fontLetterSpacing", "0" ).toDouble() ); - d->textFont.setWordSpacing( textStyleElem.attribute( "fontWordSpacing", "0" ).toDouble() ); - d->textColor = QgsSymbolLayerUtils::decodeColor( textStyleElem.attribute( "textColor", QgsSymbolLayerUtils::encodeColor( Qt::black ) ) ); - if ( !textStyleElem.hasAttribute( "textOpacity" ) ) + d->textFont.setCapitalization( static_cast< QFont::Capitalization >( textStyleElem.attribute( QStringLiteral( "fontCapitals" ), QStringLiteral( "0" ) ).toUInt() ) ); + d->textFont.setUnderline( textStyleElem.attribute( QStringLiteral( "fontUnderline" ) ).toInt() ); + d->textFont.setStrikeOut( textStyleElem.attribute( QStringLiteral( "fontStrikeout" ) ).toInt() ); + d->textFont.setLetterSpacing( QFont::AbsoluteSpacing, textStyleElem.attribute( QStringLiteral( "fontLetterSpacing" ), QStringLiteral( "0" ) ).toDouble() ); + d->textFont.setWordSpacing( textStyleElem.attribute( QStringLiteral( "fontWordSpacing" ), QStringLiteral( "0" ) ).toDouble() ); + d->textColor = QgsSymbolLayerUtils::decodeColor( textStyleElem.attribute( QStringLiteral( "textColor" ), QgsSymbolLayerUtils::encodeColor( Qt::black ) ) ); + if ( !textStyleElem.hasAttribute( QStringLiteral( "textOpacity" ) ) ) { - d->opacity = ( 1 - textStyleElem.attribute( "textTransp" ).toInt() / 100.0 ); //0 -100 + d->opacity = ( 1 - textStyleElem.attribute( QStringLiteral( "textTransp" ) ).toInt() / 100.0 ); //0 -100 } else { - d->opacity = ( textStyleElem.attribute( "textOpacity" ).toDouble() ); + d->opacity = ( textStyleElem.attribute( QStringLiteral( "textOpacity" ) ).toDouble() ); } d->blendMode = QgsPainting::getCompositionMode( - static_cast< QgsPainting::BlendMode >( textStyleElem.attribute( "blendMode", QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); + static_cast< QgsPainting::BlendMode >( textStyleElem.attribute( QStringLiteral( "blendMode" ), QString::number( QgsPainting::BlendNormal ) ).toUInt() ) ); - if ( !textStyleElem.hasAttribute( "multilineHeight" ) ) + if ( !textStyleElem.hasAttribute( QStringLiteral( "multilineHeight" ) ) ) { - QDomElement textFormatElem = elem.firstChildElement( "text-format" ); - d->multilineHeight = textFormatElem.attribute( "multilineHeight", "1" ).toDouble(); + QDomElement textFormatElem = elem.firstChildElement( QStringLiteral( "text-format" ) ); + d->multilineHeight = textFormatElem.attribute( QStringLiteral( "multilineHeight" ), QStringLiteral( "1" ) ).toDouble(); } else { - d->multilineHeight = textStyleElem.attribute( "multilineHeight", "1" ).toDouble(); + d->multilineHeight = textStyleElem.attribute( QStringLiteral( "multilineHeight" ), QStringLiteral( "1" ) ).toDouble(); } - if ( textStyleElem.firstChildElement( "text-buffer" ).isNull() ) + if ( textStyleElem.firstChildElement( QStringLiteral( "text-buffer" ) ).isNull() ) { mBufferSettings.readXml( elem ); } @@ -1547,7 +1547,7 @@ void QgsTextFormat::readXml( const QDomElement& elem ) { mBufferSettings.readXml( textStyleElem ); } - if ( textStyleElem.firstChildElement( "shadow" ).isNull() ) + if ( textStyleElem.firstChildElement( QStringLiteral( "shadow" ) ).isNull() ) { mShadowSettings.readXml( elem ); } @@ -1555,7 +1555,7 @@ void QgsTextFormat::readXml( const QDomElement& elem ) { mShadowSettings.readXml( textStyleElem ); } - if ( textStyleElem.firstChildElement( "background" ).isNull() ) + if ( textStyleElem.firstChildElement( QStringLiteral( "background" ) ).isNull() ) { mBackgroundSettings.readXml( elem ); } @@ -1568,23 +1568,23 @@ void QgsTextFormat::readXml( const QDomElement& elem ) QDomElement QgsTextFormat::writeXml( QDomDocument& doc ) const { // text style - QDomElement textStyleElem = doc.createElement( "text-style" ); - textStyleElem.setAttribute( "fontFamily", d->textFont.family() ); - textStyleElem.setAttribute( "namedStyle", QgsFontUtils::untranslateNamedStyle( d->textNamedStyle ) ); - textStyleElem.setAttribute( "fontSize", d->fontSize ); - textStyleElem.setAttribute( "fontSizeUnit", QgsUnitTypes::encodeUnit( d->fontSizeUnits ) ); - textStyleElem.setAttribute( "fontSizeMapUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( d->fontSizeMapUnitScale ) ); - textStyleElem.setAttribute( "fontWeight", d->textFont.weight() ); - textStyleElem.setAttribute( "fontItalic", d->textFont.italic() ); - textStyleElem.setAttribute( "fontStrikeout", d->textFont.strikeOut() ); - textStyleElem.setAttribute( "fontUnderline", d->textFont.underline() ); - textStyleElem.setAttribute( "textColor", QgsSymbolLayerUtils::encodeColor( d->textColor ) ); - textStyleElem.setAttribute( "fontCapitals", static_cast< unsigned int >( d->textFont.capitalization() ) ); - textStyleElem.setAttribute( "fontLetterSpacing", d->textFont.letterSpacing() ); - textStyleElem.setAttribute( "fontWordSpacing", d->textFont.wordSpacing() ); - textStyleElem.setAttribute( "textOpacity", d->opacity ); - textStyleElem.setAttribute( "blendMode", QgsPainting::getBlendModeEnum( d->blendMode ) ); - textStyleElem.setAttribute( "multilineHeight", d->multilineHeight ); + QDomElement textStyleElem = doc.createElement( QStringLiteral( "text-style" ) ); + textStyleElem.setAttribute( QStringLiteral( "fontFamily" ), d->textFont.family() ); + textStyleElem.setAttribute( QStringLiteral( "namedStyle" ), QgsFontUtils::untranslateNamedStyle( d->textNamedStyle ) ); + textStyleElem.setAttribute( QStringLiteral( "fontSize" ), d->fontSize ); + textStyleElem.setAttribute( QStringLiteral( "fontSizeUnit" ), QgsUnitTypes::encodeUnit( d->fontSizeUnits ) ); + textStyleElem.setAttribute( QStringLiteral( "fontSizeMapUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( d->fontSizeMapUnitScale ) ); + textStyleElem.setAttribute( QStringLiteral( "fontWeight" ), d->textFont.weight() ); + textStyleElem.setAttribute( QStringLiteral( "fontItalic" ), d->textFont.italic() ); + textStyleElem.setAttribute( QStringLiteral( "fontStrikeout" ), d->textFont.strikeOut() ); + textStyleElem.setAttribute( QStringLiteral( "fontUnderline" ), d->textFont.underline() ); + textStyleElem.setAttribute( QStringLiteral( "textColor" ), QgsSymbolLayerUtils::encodeColor( d->textColor ) ); + textStyleElem.setAttribute( QStringLiteral( "fontCapitals" ), static_cast< unsigned int >( d->textFont.capitalization() ) ); + textStyleElem.setAttribute( QStringLiteral( "fontLetterSpacing" ), d->textFont.letterSpacing() ); + textStyleElem.setAttribute( QStringLiteral( "fontWordSpacing" ), d->textFont.wordSpacing() ); + textStyleElem.setAttribute( QStringLiteral( "textOpacity" ), d->opacity ); + textStyleElem.setAttribute( QStringLiteral( "blendMode" ), QgsPainting::getBlendModeEnum( d->blendMode ) ); + textStyleElem.setAttribute( QStringLiteral( "multilineHeight" ), d->multilineHeight ); textStyleElem.appendChild( mBufferSettings.writeXml( doc ) ); textStyleElem.appendChild( mBackgroundSettings.writeXml( doc ) ); @@ -2042,10 +2042,10 @@ void QgsTextRenderer::drawBackground( QgsRenderContext& context, QgsTextRenderer return; QgsStringMap map; // for SVG symbology marker - map["name"] = QgsSymbolLayerUtils::symbolNameToPath( background.svgFile().trimmed() ); - map["size"] = QString::number( sizeOut ); - map["size_unit"] = QgsUnitTypes::encodeUnit( QgsUnitTypes::RenderPixels ); - map["angle"] = QString::number( 0.0 ); // angle is handled by this local painter + map[QStringLiteral( "name" )] = QgsSymbolLayerUtils::symbolNameToPath( background.svgFile().trimmed() ); + map[QStringLiteral( "size" )] = QString::number( sizeOut ); + map[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( QgsUnitTypes::RenderPixels ); + map[QStringLiteral( "angle" )] = QString::number( 0.0 ); // angle is handled by this local painter // offset is handled by this local painter // TODO: see why the marker renderer doesn't seem to translate offset *after* applying rotation @@ -2053,19 +2053,19 @@ void QgsTextRenderer::drawBackground( QgsRenderContext& context, QgsTextRenderer //map["offset_unit"] = QgsUnitTypes::encodeUnit( // tmpLyr.shapeOffsetUnits == QgsPalLayerSettings::MapUnits ? QgsUnitTypes::MapUnit : QgsUnitTypes::MM ); - map["fill"] = background.fillColor().name(); - map["outline"] = background.borderColor().name(); - map["outline-width"] = QString::number( background.borderWidth() ); - map["outline_width_unit"] = QgsUnitTypes::encodeUnit( background.borderWidthUnit() ); + map[QStringLiteral( "fill" )] = background.fillColor().name(); + map[QStringLiteral( "outline" )] = background.borderColor().name(); + map[QStringLiteral( "outline-width" )] = QString::number( background.borderWidth() ); + map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( background.borderWidthUnit() ); if ( format.shadow().enabled() && format.shadow().shadowPlacement() == QgsTextShadowSettings::ShadowShape ) { QgsTextShadowSettings shadow = format.shadow(); // configure SVG shadow specs QgsStringMap shdwmap( map ); - shdwmap["fill"] = shadow.color().name(); - shdwmap["outline"] = shadow.color().name(); - shdwmap["size"] = QString::number( sizeOut * context.rasterScaleFactor() ); + shdwmap[QStringLiteral( "fill" )] = shadow.color().name(); + shdwmap[QStringLiteral( "outline" )] = shadow.color().name(); + shdwmap[QStringLiteral( "size" )] = QString::number( sizeOut * context.rasterScaleFactor() ); // store SVG's drawing in QPicture for drop shadow call QPicture svgPict; diff --git a/src/core/qgstolerance.cpp b/src/core/qgstolerance.cpp index 0be9fe687150..52c607af09ba 100644 --- a/src/core/qgstolerance.cpp +++ b/src/core/qgstolerance.cpp @@ -71,8 +71,8 @@ double QgsTolerance::toleranceInMapUnits( double tolerance, QgsMapLayer *layer, double QgsTolerance::vertexSearchRadius( const QgsMapSettings& mapSettings ) { QSettings settings; - double tolerance = settings.value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble(); - UnitType units = static_cast< QgsTolerance::UnitType >( settings.value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt() ); + double tolerance = settings.value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit" ), 10 ).toDouble(); + UnitType units = static_cast< QgsTolerance::UnitType >( settings.value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit_unit" ), QgsTolerance::Pixels ).toInt() ); if ( units == LayerUnits ) units = ProjectUnits; return toleranceInProjectUnits( tolerance, nullptr, mapSettings, units ); @@ -81,16 +81,16 @@ double QgsTolerance::vertexSearchRadius( const QgsMapSettings& mapSettings ) double QgsTolerance::vertexSearchRadius( QgsMapLayer *layer, const QgsMapSettings &mapSettings ) { QSettings settings; - double tolerance = settings.value( "/qgis/digitizing/search_radius_vertex_edit", 10 ).toDouble(); - UnitType units = static_cast< QgsTolerance::UnitType >( settings.value( "/qgis/digitizing/search_radius_vertex_edit_unit", QgsTolerance::Pixels ).toInt() ); + double tolerance = settings.value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit" ), 10 ).toDouble(); + UnitType units = static_cast< QgsTolerance::UnitType >( settings.value( QStringLiteral( "/qgis/digitizing/search_radius_vertex_edit_unit" ), QgsTolerance::Pixels ).toInt() ); return toleranceInMapUnits( tolerance, layer, mapSettings, units ); } double QgsTolerance::defaultTolerance( QgsMapLayer *layer, const QgsMapSettings& mapSettings ) { QSettings settings; - double tolerance = settings.value( "/qgis/digitizing/default_snapping_tolerance", 0 ).toDouble(); - UnitType units = static_cast< QgsTolerance::UnitType >( settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", ProjectUnits ).toInt() ); + double tolerance = settings.value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), 0 ).toDouble(); + UnitType units = static_cast< QgsTolerance::UnitType >( settings.value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), ProjectUnits ).toInt() ); return toleranceInMapUnits( tolerance, layer, mapSettings, units ); } diff --git a/src/core/qgsunittypes.cpp b/src/core/qgsunittypes.cpp index ba9ff5912324..dbcc9b3e9f82 100644 --- a/src/core/qgsunittypes.cpp +++ b/src/core/qgsunittypes.cpp @@ -73,28 +73,28 @@ QString QgsUnitTypes::encodeUnit( DistanceUnit unit ) switch ( unit ) { case DistanceMeters: - return "meters"; + return QStringLiteral( "meters" ); case DistanceKilometers: - return "km"; + return QStringLiteral( "km" ); case DistanceFeet: - return "feet"; + return QStringLiteral( "feet" ); case DistanceYards: - return "yd"; + return QStringLiteral( "yd" ); case DistanceMiles: - return "mi"; + return QStringLiteral( "mi" ); case DistanceDegrees: - return "degrees"; + return QStringLiteral( "degrees" ); case DistanceUnknownUnit: - return ""; + return QStringLiteral( "" ); case DistanceNauticalMiles: - return "nautical miles"; + return QStringLiteral( "nautical miles" ); } return QString(); } @@ -400,25 +400,25 @@ QString QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaUnit unit ) switch ( unit ) { case AreaSquareMeters: - return "m2"; + return QStringLiteral( "m2" ); case AreaSquareKilometers: - return "km2"; + return QStringLiteral( "km2" ); case AreaSquareFeet: - return "ft2"; + return QStringLiteral( "ft2" ); case AreaSquareYards: - return "y2"; + return QStringLiteral( "y2" ); case AreaSquareMiles: - return "mi2"; + return QStringLiteral( "mi2" ); case AreaHectares: - return "ha"; + return QStringLiteral( "ha" ); case AreaAcres: - return "ac"; + return QStringLiteral( "ac" ); case AreaSquareNauticalMiles: - return "nm2"; + return QStringLiteral( "nm2" ); case AreaSquareDegrees: - return "deg2"; + return QStringLiteral( "deg2" ); case AreaUnknownUnit: - return ""; + return QStringLiteral( "" ); } return QString(); } @@ -833,19 +833,19 @@ QString QgsUnitTypes::encodeUnit( QgsUnitTypes::AngleUnit unit ) switch ( unit ) { case AngleDegrees: - return "degrees"; + return QStringLiteral( "degrees" ); case AngleRadians: - return "radians"; + return QStringLiteral( "radians" ); case AngleGon: - return "gon"; + return QStringLiteral( "gon" ); case AngleMinutesOfArc: - return "moa"; + return QStringLiteral( "moa" ); case AngleSecondsOfArc: - return "soa"; + return QStringLiteral( "soa" ); case AngleTurn: - return "tr"; + return QStringLiteral( "tr" ); case AngleUnknownUnit: - return ""; + return QStringLiteral( "" ); } return QString(); } @@ -1064,7 +1064,7 @@ QString QgsUnitTypes::formatAngle( double angle, int decimals, QgsUnitTypes::Ang break; } - return QString( "%L1%2" ).arg( angle, 0, 'f', decimals ).arg( unitLabel ); + return QStringLiteral( "%L1%2" ).arg( angle, 0, 'f', decimals ).arg( unitLabel ); } QString QgsUnitTypes::encodeUnit( RenderUnit unit ) @@ -1072,17 +1072,17 @@ QString QgsUnitTypes::encodeUnit( RenderUnit unit ) switch ( unit ) { case RenderMillimeters: - return "MM"; + return QStringLiteral( "MM" ); case RenderMapUnits: - return "MapUnit"; + return QStringLiteral( "MapUnit" ); case RenderPixels: - return "Pixel"; + return QStringLiteral( "Pixel" ); case RenderPercentage: - return "Percentage"; + return QStringLiteral( "Percentage" ); case RenderPoints: - return "Point"; + return QStringLiteral( "Point" ); default: - return "MM"; + return QStringLiteral( "MM" ); } } @@ -1097,17 +1097,17 @@ QgsUnitTypes::RenderUnit QgsUnitTypes::decodeRenderUnit( const QString& string, return RenderMillimeters; if ( normalized == encodeUnit( RenderMapUnits ).toLower() ) return RenderMapUnits; - if ( normalized == "mapunits" ) + if ( normalized == QLatin1String( "mapunits" ) ) return RenderMapUnits; if ( normalized == encodeUnit( RenderPixels ).toLower() ) return RenderPixels; if ( normalized == encodeUnit( RenderPercentage ).toLower() ) return RenderPercentage; - if ( normalized == "percent" ) + if ( normalized == QLatin1String( "percent" ) ) return RenderPercentage; if ( normalized == encodeUnit( RenderPoints ).toLower() ) return RenderPoints; - if ( normalized == "points" ) + if ( normalized == QLatin1String( "points" ) ) return RenderPoints; if ( ok ) diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index da4c0484b5e4..7387e828f85c 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -38,7 +38,7 @@ QgsVectorDataProvider::QgsVectorDataProvider( const QString& uri ) , mCacheMinMaxDirty( true ) { QSettings settings; - setEncoding( settings.value( "/UI/encoding", "System" ).toString() ); + setEncoding( settings.value( QStringLiteral( "/UI/encoding" ), "System" ).toString() ); } @@ -48,7 +48,7 @@ QgsVectorDataProvider::~QgsVectorDataProvider() QString QgsVectorDataProvider::storageType() const { - return "Generic vector file"; + return QStringLiteral( "Generic vector file" ); } QString QgsVectorDataProvider::dataComment() const @@ -133,7 +133,7 @@ void QgsVectorDataProvider::setEncoding( const QString& e ) { mEncoding = QTextCodec::codecForName( e.toLocal8Bit().constData() ); - if ( !mEncoding && e != "System" ) + if ( !mEncoding && e != QLatin1String( "System" ) ) { QgsMessageLog::logMessage( tr( "Codec %1 not found. Falling back to system locale" ).arg( e ) ); mEncoding = QTextCodec::codecForName( "System" ); @@ -152,7 +152,7 @@ QString QgsVectorDataProvider::encoding() const return mEncoding->name(); } - return ""; + return QLatin1String( "" ); } QString QgsVectorDataProvider::capabilitiesString() const @@ -252,7 +252,7 @@ QString QgsVectorDataProvider::capabilitiesString() const QgsDebugMsg( "Supports circular geometry types (circularstring, compoundcurve, curvepolygon)" ); } - return abilitiesList.join( ", " ); + return abilitiesList.join( QStringLiteral( ", " ) ); } diff --git a/src/core/qgsvectorfilewriter.cpp b/src/core/qgsvectorfilewriter.cpp index 6d64b22723ab..d177a479b82e 100644 --- a/src/core/qgsvectorfilewriter.cpp +++ b/src/core/qgsvectorfilewriter.cpp @@ -153,24 +153,24 @@ void QgsVectorFileWriter::init( QString vectorFileName, return; } - if ( driverName == "MapInfo MIF" ) + if ( driverName == QLatin1String( "MapInfo MIF" ) ) { - mOgrDriverName = "MapInfo File"; + mOgrDriverName = QStringLiteral( "MapInfo File" ); } - else if ( driverName == "SpatiaLite" ) + else if ( driverName == QLatin1String( "SpatiaLite" ) ) { - mOgrDriverName = "SQLite"; - if ( !datasourceOptions.contains( "SPATIALITE=YES" ) ) + mOgrDriverName = QStringLiteral( "SQLite" ); + if ( !datasourceOptions.contains( QStringLiteral( "SPATIALITE=YES" ) ) ) { - datasourceOptions.append( "SPATIALITE=YES" ); + datasourceOptions.append( QStringLiteral( "SPATIALITE=YES" ) ); } } - else if ( driverName == "DBF file" ) + else if ( driverName == QLatin1String( "DBF file" ) ) { - mOgrDriverName = "ESRI Shapefile"; - if ( !layerOptions.contains( "SHPT=NULL" ) ) + mOgrDriverName = QStringLiteral( "ESRI Shapefile" ); + if ( !layerOptions.contains( QStringLiteral( "SHPT=NULL" ) ) ) { - layerOptions.append( "SHPT=NULL" ); + layerOptions.append( QStringLiteral( "SHPT=NULL" ) ); } srs = QgsCoordinateReferenceSystem(); } @@ -197,20 +197,20 @@ void QgsVectorFileWriter::init( QString vectorFileName, MetaData metadata; bool metadataFound = driverMetadata( driverName, metadata ); - if ( mOgrDriverName == "ESRI Shapefile" ) + if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) ) { - if ( layerOptions.join( "" ).toUpper().indexOf( "ENCODING=" ) == -1 ) + if ( layerOptions.join( QLatin1String( "" ) ).toUpper().indexOf( QLatin1String( "ENCODING=" ) ) == -1 ) { layerOptions.append( "ENCODING=" + convertCodecNameForEncodingOption( fileEncoding ) ); } - if ( driverName == "ESRI Shapefile" && !vectorFileName.endsWith( ".shp", Qt::CaseInsensitive ) ) + if ( driverName == QLatin1String( "ESRI Shapefile" ) && !vectorFileName.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) { - vectorFileName += ".shp"; + vectorFileName += QLatin1String( ".shp" ); } - else if ( driverName == "DBF file" && !vectorFileName.endsWith( ".dbf", Qt::CaseInsensitive ) ) + else if ( driverName == QLatin1String( "DBF file" ) && !vectorFileName.endsWith( QLatin1String( ".dbf" ), Qt::CaseInsensitive ) ) { - vectorFileName += ".dbf"; + vectorFileName += QLatin1String( ".dbf" ); } #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM < 1700 @@ -256,7 +256,7 @@ void QgsVectorFileWriter::init( QString vectorFileName, if ( action == CreateOrOverwriteFile ) { - if ( vectorFileName.endsWith( ".gdb", Qt::CaseInsensitive ) ) + if ( vectorFileName.endsWith( QLatin1String( ".gdb" ), Qt::CaseInsensitive ) ) { QDir dir( vectorFileName ); if ( dir.exists() ) @@ -360,7 +360,7 @@ void QgsVectorFileWriter::init( QString vectorFileName, QgsDebugMsg( "error finding QTextCodec for " + fileEncoding ); QSettings settings; - QString enc = settings.value( "/UI/encoding", "System" ).toString(); + QString enc = settings.value( QStringLiteral( "/UI/encoding" ), "System" ).toString(); mCodec = QTextCodec::codecForName( enc.toLocal8Bit().constData() ); if ( !mCodec ) { @@ -382,7 +382,7 @@ void QgsVectorFileWriter::init( QString vectorFileName, OGRwkbGeometryType wkbType = ogrTypeFromWkbType( geometryType ); // Remove FEATURE_DATASET layer option (used for ESRI File GDB driver) if its value is not set - int optIndex = layerOptions.indexOf( "FEATURE_DATASET=" ); + int optIndex = layerOptions.indexOf( QStringLiteral( "FEATURE_DATASET=" ) ); if ( optIndex != -1 ) { layerOptions.removeAt( optIndex ); @@ -415,16 +415,16 @@ void QgsVectorFileWriter::init( QString vectorFileName, } QSettings settings; - if ( !settings.value( "/qgis/ignoreShapeEncoding", true ).toBool() ) + if ( !settings.value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ) { CPLSetConfigOption( "SHAPE_ENCODING", nullptr ); } if ( srs.isValid() ) { - if ( mOgrDriverName == "ESRI Shapefile" ) + if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) ) { - QString layerName = vectorFileName.left( vectorFileName.indexOf( ".shp", Qt::CaseInsensitive ) ); + QString layerName = vectorFileName.left( vectorFileName.indexOf( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ); QFile prjFile( layerName + ".qpj" ); if ( prjFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { @@ -535,7 +535,7 @@ void QgsVectorFileWriter::init( QString vectorFileName, break; case QVariant::Time: - if ( mOgrDriverName == "ESRI Shapefile" ) + if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) ) { ogrType = OFTString; ogrWidth = 12; // %02d:%02d:%06.3f @@ -547,7 +547,7 @@ void QgsVectorFileWriter::init( QString vectorFileName, break; case QVariant::DateTime: - if ( mOgrDriverName == "ESRI Shapefile" ) + if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) ) { ogrType = OFTString; ogrWidth = 24; // "%04d/%02d/%02d %02d:%02d:%06.3f" @@ -566,12 +566,12 @@ void QgsVectorFileWriter::init( QString vectorFileName, return; } - if ( mOgrDriverName == "SQLite" && name.compare( "ogc_fid", Qt::CaseInsensitive ) == 0 ) + if ( mOgrDriverName == QLatin1String( "SQLite" ) && name.compare( QLatin1String( "ogc_fid" ), Qt::CaseInsensitive ) == 0 ) { int i; for ( i = 0; i < 10; i++ ) { - name = QString( "ogc_fid%1" ).arg( i ); + name = QStringLiteral( "ogc_fid%1" ).arg( i ); int j; for ( j = 0; j < fields.size() && name.compare( fields.at( j ).name(), Qt::CaseInsensitive ) != 0; j++ ) @@ -700,12 +700,12 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "AVCE00", + driverMetadata.insert( QStringLiteral( "AVCE00" ), MetaData( - "Arc/Info ASCII Coverage", + QStringLiteral( "Arc/Info ASCII Coverage" ), QObject::tr( "Arc/Info ASCII Coverage" ), - "*.e00", - "e00", + QStringLiteral( "*.e00" ), + QStringLiteral( "e00" ), datasetOptions, layerOptions ) @@ -715,18 +715,18 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "LINEFORMAT", new SetOption( + datasetOptions.insert( QStringLiteral( "LINEFORMAT" ), new SetOption( QObject::tr( "New BNA files are created by the " "systems default line termination conventions. " "This may be overridden here." ), QStringList() - << "CRLF" - << "LF", - "", // Default value + << QStringLiteral( "CRLF" ) + << QStringLiteral( "LF" ), + QLatin1String( "" ), // Default value true // Allow None ) ); - datasetOptions.insert( "MULTILINE", new BoolOption( + datasetOptions.insert( QStringLiteral( "MULTILINE" ), new BoolOption( QObject::tr( "By default, BNA files are created in multi-line format. " "For each record, the first line contains the identifiers and the " "type/number of coordinates to follow. Each following line contains " @@ -734,19 +734,19 @@ QMap QgsVectorFileWriter::initMetaData() true // Default value ) ); - datasetOptions.insert( "NB_IDS", new SetOption( + datasetOptions.insert( QStringLiteral( "NB_IDS" ), new SetOption( QObject::tr( "BNA records may contain from 2 to 4 identifiers per record. " "Some software packages only support a precise number of identifiers. " "You can override the default value (2) by a precise value" ), QStringList() - << "2" - << "3" - << "4" - << "NB_SOURCE_FIELDS", - "2" // Default value + << QStringLiteral( "2" ) + << QStringLiteral( "3" ) + << QStringLiteral( "4" ) + << QStringLiteral( "NB_SOURCE_FIELDS" ), + QStringLiteral( "2" ) // Default value ) ); - datasetOptions.insert( "ELLIPSES_AS_ELLIPSES", new BoolOption( + datasetOptions.insert( QStringLiteral( "ELLIPSES_AS_ELLIPSES" ), new BoolOption( QObject::tr( "The BNA writer will try to recognize ellipses and circles when writing a polygon. " "This will only work if the feature has previously been read from a BNA file. " "As some software packages do not support ellipses/circles in BNA data file, " @@ -755,22 +755,22 @@ QMap QgsVectorFileWriter::initMetaData() true // Default value ) ); - datasetOptions.insert( "NB_PAIRS_PER_LINE", new IntOption( + datasetOptions.insert( QStringLiteral( "NB_PAIRS_PER_LINE" ), new IntOption( QObject::tr( "Limit the number of coordinate pairs per line in multiline format." ), 2 // Default value ) ); - datasetOptions.insert( "COORDINATE_PRECISION", new IntOption( + datasetOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new IntOption( QObject::tr( "Set the number of decimal for coordinates. Default value is 10." ), 10 // Default value ) ); - driverMetadata.insert( "BNA", + driverMetadata.insert( QStringLiteral( "BNA" ), MetaData( - "Atlas BNA", + QStringLiteral( "Atlas BNA" ), QObject::tr( "Atlas BNA" ), - "*.bna", - "bna", + QStringLiteral( "*.bna" ), + QStringLiteral( "bna" ), datasetOptions, layerOptions ) @@ -780,59 +780,59 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "LINEFORMAT", new SetOption( + layerOptions.insert( QStringLiteral( "LINEFORMAT" ), new SetOption( QObject::tr( "By default when creating new .csv files they " "are created with the line termination conventions " "of the local platform (CR/LF on Win32 or LF on all other systems). " "This may be overridden through the use of the LINEFORMAT option." ), QStringList() - << "CRLF" - << "LF", - "", // Default value + << QStringLiteral( "CRLF" ) + << QStringLiteral( "LF" ), + QLatin1String( "" ), // Default value true // Allow None ) ); - layerOptions.insert( "GEOMETRY", new SetOption( + layerOptions.insert( QStringLiteral( "GEOMETRY" ), new SetOption( QObject::tr( "By default, the geometry of a feature written to a .csv file is discarded. " "It is possible to export the geometry in its WKT representation by " "specifying GEOMETRY=AS_WKT. It is also possible to export point geometries " "into their X,Y,Z components by specifying GEOMETRY=AS_XYZ, GEOMETRY=AS_XY " "or GEOMETRY=AS_YX." ), QStringList() - << "AS_WKT" - << "AS_XYZ" - << "AS_XY" - << "AS_YX", - "AS_XY", // Default value + << QStringLiteral( "AS_WKT" ) + << QStringLiteral( "AS_XYZ" ) + << QStringLiteral( "AS_XY" ) + << QStringLiteral( "AS_YX" ), + QStringLiteral( "AS_XY" ), // Default value true // Allow None ) ); - layerOptions.insert( "CREATE_CSVT", new BoolOption( + layerOptions.insert( QStringLiteral( "CREATE_CSVT" ), new BoolOption( QObject::tr( "Create the associated .csvt file to describe the type of each " "column of the layer and its optional width and precision." ), false // Default value ) ); - layerOptions.insert( "SEPARATOR", new SetOption( + layerOptions.insert( QStringLiteral( "SEPARATOR" ), new SetOption( QObject::tr( "Field separator character." ), QStringList() - << "COMMA" - << "SEMICOLON" - << "TAB", - "COMMA" // Default value + << QStringLiteral( "COMMA" ) + << QStringLiteral( "SEMICOLON" ) + << QStringLiteral( "TAB" ), + QStringLiteral( "COMMA" ) // Default value ) ); - layerOptions.insert( "WRITE_BOM", new BoolOption( + layerOptions.insert( QStringLiteral( "WRITE_BOM" ), new BoolOption( QObject::tr( "Write a UTF-8 Byte Order Mark (BOM) at the start of the file." ), false // Default value ) ); - driverMetadata.insert( "CSV", + driverMetadata.insert( QStringLiteral( "CSV" ), MetaData( - "Comma Separated Value [CSV]", + QStringLiteral( "Comma Separated Value [CSV]" ), QObject::tr( "Comma Separated Value [CSV]" ), - "*.csv", - "csv", + QStringLiteral( "*.csv" ), + QStringLiteral( "csv" ), datasetOptions, layerOptions ) @@ -842,22 +842,22 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "SHPT", new SetOption( + layerOptions.insert( QStringLiteral( "SHPT" ), new SetOption( QObject::tr( "Override the type of shapefile created. " "Can be one of NULL for a simple .dbf file with no .shp file, POINT, " "ARC, POLYGON or MULTIPOINT for 2D, or POINTZ, ARCZ, POLYGONZ or " "MULTIPOINTZ for 3D. Shapefiles with measure values are not supported, " "nor are MULTIPATCH files." ), QStringList() - << "NULL" - << "POINT" - << "ARC" - << "POLYGON" - << "MULTIPOINT" - << "POINTZ" - << "ARCZ" - << "POLYGONZ" - << "MULTIPOINTZ", + << QStringLiteral( "NULL" ) + << QStringLiteral( "POINT" ) + << QStringLiteral( "ARC" ) + << QStringLiteral( "POLYGON" ) + << QStringLiteral( "MULTIPOINT" ) + << QStringLiteral( "POINTZ" ) + << QStringLiteral( "ARCZ" ) + << QStringLiteral( "POLYGONZ" ) + << QStringLiteral( "MULTIPOINTZ" ), QString(), // Default value true // Allow None ) ); @@ -875,17 +875,17 @@ QMap QgsVectorFileWriter::initMetaData() ) ); #endif - layerOptions.insert( "RESIZE", new BoolOption( + layerOptions.insert( QStringLiteral( "RESIZE" ), new BoolOption( QObject::tr( "Set to YES to resize fields to their optimal size." ), false // Default value ) ); - driverMetadata.insert( "ESRI", + driverMetadata.insert( QStringLiteral( "ESRI" ), MetaData( - "ESRI Shapefile", + QStringLiteral( "ESRI Shapefile" ), QObject::tr( "ESRI Shapefile" ), - "*.shp", - "shp", + QStringLiteral( "*.shp" ), + QStringLiteral( "shp" ), datasetOptions, layerOptions ) @@ -895,12 +895,12 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "DBF File", + driverMetadata.insert( QStringLiteral( "DBF File" ), MetaData( - "DBF File", + QStringLiteral( "DBF File" ), QObject::tr( "DBF File" ), - "*.dbf", - "dbf", + QStringLiteral( "*.dbf" ), + QStringLiteral( "dbf" ), datasetOptions, layerOptions ) @@ -910,12 +910,12 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "FMEObjects Gateway", + driverMetadata.insert( QStringLiteral( "FMEObjects Gateway" ), MetaData( - "FMEObjects Gateway", + QStringLiteral( "FMEObjects Gateway" ), QObject::tr( "FMEObjects Gateway" ), - "*.fdd", - "fdd", + QStringLiteral( "*.fdd" ), + QStringLiteral( "fdd" ), datasetOptions, layerOptions ) @@ -925,27 +925,27 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "WRITE_BBOX", new BoolOption( + layerOptions.insert( QStringLiteral( "WRITE_BBOX" ), new BoolOption( QObject::tr( "Set to YES to write a bbox property with the bounding box " "of the geometries at the feature and feature collection level." ), false // Default value ) ); - layerOptions.insert( "COORDINATE_PRECISION", new IntOption( + layerOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new IntOption( QObject::tr( "Maximum number of figures after decimal separator to write in coordinates. " "Default to 15. Truncation will occur to remove trailing zeros." ), 15 // Default value ) ); - driverMetadata.insert( "GeoJSON", + driverMetadata.insert( QStringLiteral( "GeoJSON" ), MetaData( - "GeoJSON", + QStringLiteral( "GeoJSON" ), QObject::tr( "GeoJSON" ), - "*.geojson", - "geojson", + QStringLiteral( "*.geojson" ), + QStringLiteral( "geojson" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -953,27 +953,27 @@ QMap QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "FORMAT", new SetOption( + datasetOptions.insert( QStringLiteral( "FORMAT" ), new SetOption( QObject::tr( "whether the document must be in RSS 2.0 or Atom 1.0 format. " "Default value : RSS" ), QStringList() - << "RSS" - << "ATOM", - "RSS" // Default value + << QStringLiteral( "RSS" ) + << QStringLiteral( "ATOM" ), + QStringLiteral( "RSS" ) // Default value ) ); - datasetOptions.insert( "GEOM_DIALECT", new SetOption( + datasetOptions.insert( QStringLiteral( "GEOM_DIALECT" ), new SetOption( QObject::tr( "The encoding of location information. Default value : SIMPLE. " "W3C_GEO only supports point geometries. " "SIMPLE or W3C_GEO only support geometries in geographic WGS84 coordinates." ), QStringList() - << "SIMPLE" - << "GML" - << "W3C_GEO", - "SIMPLE" // Default value + << QStringLiteral( "SIMPLE" ) + << QStringLiteral( "GML" ) + << QStringLiteral( "W3C_GEO" ), + QStringLiteral( "SIMPLE" ) // Default value ) ); - datasetOptions.insert( "USE_EXTENSIONS", new BoolOption( + datasetOptions.insert( QStringLiteral( "USE_EXTENSIONS" ), new BoolOption( QObject::tr( "If defined to YES, extension fields will be written. " "If the field name not found in the base schema matches " "the foo_bar pattern, foo will be considered as the namespace " @@ -982,65 +982,65 @@ QMap QgsVectorFileWriter::initMetaData() true // Default value ) ); - datasetOptions.insert( "WRITE_HEADER_AND_FOOTER", new BoolOption( + datasetOptions.insert( QStringLiteral( "WRITE_HEADER_AND_FOOTER" ), new BoolOption( QObject::tr( "If defined to NO, only or elements will be written. " "The user will have to provide the appropriate header and footer of the document." ), true // Default value ) ); - datasetOptions.insert( "HEADER", new StringOption( + datasetOptions.insert( QStringLiteral( "HEADER" ), new StringOption( QObject::tr( "XML content that will be put between the element and the " "first element for a RSS document, or between the xml tag and " "the first element for an Atom document. " ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "TITLE", new StringOption( + datasetOptions.insert( QStringLiteral( "TITLE" ), new StringOption( QObject::tr( "Value put inside the element in the header. " "If not provided, a dummy value will be used as that element is compulsory." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "DESCRIPTION", new StringOption( + datasetOptions.insert( QStringLiteral( "DESCRIPTION" ), new StringOption( QObject::tr( "Value put inside the <description> element in the header. " "If not provided, a dummy value will be used as that element is compulsory." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "LINK", new StringOption( + datasetOptions.insert( QStringLiteral( "LINK" ), new StringOption( QObject::tr( "Value put inside the <link> element in the header. " "If not provided, a dummy value will be used as that element is compulsory." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "UPDATED", new StringOption( + datasetOptions.insert( QStringLiteral( "UPDATED" ), new StringOption( QObject::tr( "Value put inside the <updated> element in the header. " "Should be formatted as a XML datetime. " "If not provided, a dummy value will be used as that element is compulsory." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "AUTHOR_NAME", new StringOption( + datasetOptions.insert( QStringLiteral( "AUTHOR_NAME" ), new StringOption( QObject::tr( "Value put inside the <author><name> element in the header. " "If not provided, a dummy value will be used as that element is compulsory." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "ID", new StringOption( + datasetOptions.insert( QStringLiteral( "ID" ), new StringOption( QObject::tr( "Value put inside the <id> element in the header. " "If not provided, a dummy value will be used as that element is compulsory." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - driverMetadata.insert( "GeoRSS", + driverMetadata.insert( QStringLiteral( "GeoRSS" ), MetaData( - "GeoRSS", + QStringLiteral( "GeoRSS" ), QObject::tr( "GeoRSS" ), - "*.xml", - "xml", + QStringLiteral( "*.xml" ), + QStringLiteral( "xml" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1048,55 +1048,55 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "XSISCHEMAURI", new StringOption( + datasetOptions.insert( QStringLiteral( "XSISCHEMAURI" ), new StringOption( QObject::tr( "If provided, this URI will be inserted as the schema location. " "Note that the schema file isn't actually accessed by OGR, so it " "is up to the user to ensure it will match the schema of the OGR " "produced GML data file." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "XSISCHEMA", new SetOption( + datasetOptions.insert( QStringLiteral( "XSISCHEMA" ), new SetOption( QObject::tr( "This writes a GML application schema file to a corresponding " ".xsd file (with the same basename). If INTERNAL is used the " "schema is written within the GML file, but this is experimental " "and almost certainly not valid XML. " "OFF disables schema generation (and is implicit if XSISCHEMAURI is used)." ), QStringList() - << "EXTERNAL" - << "INTERNAL" - << "OFF", - "EXTERNAL" // Default value + << QStringLiteral( "EXTERNAL" ) + << QStringLiteral( "INTERNAL" ) + << QStringLiteral( "OFF" ), + QStringLiteral( "EXTERNAL" ) // Default value ) ); - datasetOptions.insert( "PREFIX", new StringOption( + datasetOptions.insert( QStringLiteral( "PREFIX" ), new StringOption( QObject::tr( "This is the prefix for the application target namespace." ), - "ogr" // Default value + QStringLiteral( "ogr" ) // Default value ) ); - datasetOptions.insert( "STRIP_PREFIX", new BoolOption( + datasetOptions.insert( QStringLiteral( "STRIP_PREFIX" ), new BoolOption( QObject::tr( "Can be set to TRUE to avoid writing the prefix of the " "application target namespace in the GML file." ), false // Default value ) ); - datasetOptions.insert( "TARGET_NAMESPACE", new StringOption( + datasetOptions.insert( QStringLiteral( "TARGET_NAMESPACE" ), new StringOption( QObject::tr( "Defaults to 'http://ogr.maptools.org/'. " "This is the application target namespace." ), - "http://ogr.maptools.org/" // Default value + QStringLiteral( "http://ogr.maptools.org/" ) // Default value ) ); - datasetOptions.insert( "FORMAT", new SetOption( + datasetOptions.insert( QStringLiteral( "FORMAT" ), new SetOption( QObject::tr( "If not specified, GML2 will be used." ), QStringList() - << "GML3" - << "GML3Deegree" - << "GML3.2", - "", // Default value + << QStringLiteral( "GML3" ) + << QStringLiteral( "GML3Deegree" ) + << QStringLiteral( "GML3.2" ), + QLatin1String( "" ), // Default value true // Allow None ) ); - datasetOptions.insert( "GML3_LONGSRS", new BoolOption( + datasetOptions.insert( QStringLiteral( "GML3_LONGSRS" ), new BoolOption( QObject::tr( "only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. " "If YES, SRS with EPSG authority will be written with the " "'urn:ogc:def:crs:EPSG::' prefix. In the case, if the SRS is a " @@ -1108,29 +1108,29 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() true // Default value ) ); - datasetOptions.insert( "WRITE_FEATURE_BOUNDED_BY", new BoolOption( + datasetOptions.insert( QStringLiteral( "WRITE_FEATURE_BOUNDED_BY" ), new BoolOption( QObject::tr( "only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. " "If set to NO, the <gml:boundedBy> element will not be written for " "each feature." ), true // Default value ) ); - datasetOptions.insert( "SPACE_INDENTATION", new BoolOption( + datasetOptions.insert( QStringLiteral( "SPACE_INDENTATION" ), new BoolOption( QObject::tr( "Default to YES. If YES, the output will be indented with spaces " "for more readability, but at the expense of file size." ), true // Default value ) ); - driverMetadata.insert( "GML", + driverMetadata.insert( QStringLiteral( "GML" ), MetaData( - "Geography Markup Language [GML]", + QStringLiteral( "Geography Markup Language [GML]" ), QObject::tr( "Geography Markup Language [GML]" ), - "*.gml", - "gml", + QStringLiteral( "*.gml" ), + QStringLiteral( "gml" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1138,24 +1138,24 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "IDENTIFIER", new StringOption( + layerOptions.insert( QStringLiteral( "IDENTIFIER" ), new StringOption( QObject::tr( "Human-readable identifier (e.g. short name) for the layer content" ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - layerOptions.insert( "DESCRIPTION", new StringOption( + layerOptions.insert( QStringLiteral( "DESCRIPTION" ), new StringOption( QObject::tr( "Human-readable description for the layer content" ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - layerOptions.insert( "FID", new StringOption( + layerOptions.insert( QStringLiteral( "FID" ), new StringOption( QObject::tr( "Name for the feature identifier column" ), - "fid" // Default value + QStringLiteral( "fid" ) // Default value ) ); - layerOptions.insert( "GEOMETRY_NAME", new StringOption( + layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new StringOption( QObject::tr( "Name for the geometry column" ), - "geometry" // Default value + QStringLiteral( "geometry" ) // Default value ) ); #if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,0) @@ -1165,15 +1165,15 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() ) ); #endif - driverMetadata.insert( "GPKG", + driverMetadata.insert( QStringLiteral( "GPKG" ), MetaData( - "GeoPackage", + QStringLiteral( "GeoPackage" ), QObject::tr( "GeoPackage" ), - "*.gpkg", - "gpkg", + QStringLiteral( "*.gpkg" ), + QStringLiteral( "gpkg" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1181,12 +1181,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "GMT", + driverMetadata.insert( QStringLiteral( "GMT" ), MetaData( - "Generic Mapping Tools [GMT]", + QStringLiteral( "Generic Mapping Tools [GMT]" ), QObject::tr( "Generic Mapping Tools [GMT]" ), - "*.gmt", - "gmt", + QStringLiteral( "*.gmt" ), + QStringLiteral( "gmt" ), datasetOptions, layerOptions ) @@ -1196,7 +1196,7 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "FORCE_GPX_TRACK", new BoolOption( + layerOptions.insert( QStringLiteral( "FORCE_GPX_TRACK" ), new BoolOption( QObject::tr( "By default when writing a layer whose features are of " "type wkbLineString, the GPX driver chooses to write " "them as routes. If FORCE_GPX_TRACK=YES is specified, " @@ -1204,7 +1204,7 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() false // Default value ) ); - layerOptions.insert( "FORCE_GPX_ROUTE", new BoolOption( + layerOptions.insert( QStringLiteral( "FORCE_GPX_ROUTE" ), new BoolOption( QObject::tr( "By default when writing a layer whose features are of " "type wkbMultiLineString, the GPX driver chooses to write " "them as tracks. If FORCE_GPX_ROUTE=YES is specified, " @@ -1213,46 +1213,46 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() false // Default value ) ); - datasetOptions.insert( "GPX_USE_EXTENSIONS", new BoolOption( + datasetOptions.insert( QStringLiteral( "GPX_USE_EXTENSIONS" ), new BoolOption( QObject::tr( "If GPX_USE_EXTENSIONS=YES is specified, " "extra fields will be written inside the <extensions> tag." ), true // Default value ) ); - datasetOptions.insert( "GPX_EXTENSIONS_NS", new StringOption( + datasetOptions.insert( QStringLiteral( "GPX_EXTENSIONS_NS" ), new StringOption( QObject::tr( "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS_URL " "is set. The namespace value used for extension tags. By default, 'ogr'." ), - "ogr" // Default value + QStringLiteral( "ogr" ) // Default value ) ); - datasetOptions.insert( "GPX_EXTENSIONS_NS_URL", new StringOption( + datasetOptions.insert( QStringLiteral( "GPX_EXTENSIONS_NS_URL" ), new StringOption( QObject::tr( "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS " "is set. The namespace URI. By default, 'http://osgeo.org/gdal'." ), - "http://osgeo.org/gdal" // Default value + QStringLiteral( "http://osgeo.org/gdal" ) // Default value ) ); - datasetOptions.insert( "LINEFORMAT", new SetOption( + datasetOptions.insert( QStringLiteral( "LINEFORMAT" ), new SetOption( QObject::tr( "By default files are created with the line termination " "conventions of the local platform (CR/LF on win32 or LF " "on all other systems). This may be overridden through use " "of the LINEFORMAT layer creation option which may have a value " "of CRLF (DOS format) or LF (Unix format)." ), QStringList() - << "CRLF" - << "LF", - "", // Default value + << QStringLiteral( "CRLF" ) + << QStringLiteral( "LF" ), + QLatin1String( "" ), // Default value true // Allow None ) ); - driverMetadata.insert( "GPX", + driverMetadata.insert( QStringLiteral( "GPX" ), MetaData( - "GPS eXchange Format [GPX]", + QStringLiteral( "GPS eXchange Format [GPX]" ), QObject::tr( "GPS eXchange Format [GPX]" ), - "*.gpx", - "gpx", + QStringLiteral( "*.gpx" ), + QStringLiteral( "gpx" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1260,12 +1260,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "Interlis 1", + driverMetadata.insert( QStringLiteral( "Interlis 1" ), MetaData( - "INTERLIS 1", + QStringLiteral( "INTERLIS 1" ), QObject::tr( "INTERLIS 1" ), - "*.itf *.xml *.ili", - "ili", + QStringLiteral( "*.itf *.xml *.ili" ), + QStringLiteral( "ili" ), datasetOptions, layerOptions ) @@ -1275,12 +1275,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "Interlis 2", + driverMetadata.insert( QStringLiteral( "Interlis 2" ), MetaData( - "INTERLIS 2", + QStringLiteral( "INTERLIS 2" ), QObject::tr( "INTERLIS 2" ), - "*.itf *.xml *.ili", - "ili", + QStringLiteral( "*.itf *.xml *.ili" ), + QStringLiteral( "ili" ), datasetOptions, layerOptions ) @@ -1290,35 +1290,35 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "NameField", new StringOption( + datasetOptions.insert( QStringLiteral( "NameField" ), new StringOption( QObject::tr( "Allows you to specify the field to use for the KML <name> element. " ), - "Name" // Default value + QStringLiteral( "Name" ) // Default value ) ); - datasetOptions.insert( "DescriptionField", new StringOption( + datasetOptions.insert( QStringLiteral( "DescriptionField" ), new StringOption( QObject::tr( "Allows you to specify the field to use for the KML <description> element." ), - "Description" // Default value + QStringLiteral( "Description" ) // Default value ) ); - datasetOptions.insert( "AltitudeMode", new SetOption( + datasetOptions.insert( QStringLiteral( "AltitudeMode" ), new SetOption( QObject::tr( "Allows you to specify the AltitudeMode to use for KML geometries. " "This will only affect 3D geometries and must be one of the valid KML options." ), QStringList() - << "clampToGround" - << "relativeToGround" - << "absolute", - "clampToGround" // Default value + << QStringLiteral( "clampToGround" ) + << QStringLiteral( "relativeToGround" ) + << QStringLiteral( "absolute" ), + QStringLiteral( "clampToGround" ) // Default value ) ); - driverMetadata.insert( "KML", + driverMetadata.insert( QStringLiteral( "KML" ), MetaData( - "Keyhole Markup Language [KML]", + QStringLiteral( "Keyhole Markup Language [KML]" ), QObject::tr( "Keyhole Markup Language [KML]" ), - "*.kml", - "kml", + QStringLiteral( "*.kml" ), + QStringLiteral( "kml" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1326,34 +1326,34 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "SPATIAL_INDEX_MODE", new SetOption( + layerOptions.insert( QStringLiteral( "SPATIAL_INDEX_MODE" ), new SetOption( QObject::tr( "Use this to turn on 'quick spatial index mode'. " "In this mode writing files can be about 5 times faster, " "but spatial queries can be up to 30 times slower." ), QStringList() - << "QUICK", - "", // Default value + << QStringLiteral( "QUICK" ), + QLatin1String( "" ), // Default value true // Allow None ) ); - driverMetadata.insert( "MapInfo File", + driverMetadata.insert( QStringLiteral( "MapInfo File" ), MetaData( - "Mapinfo", + QStringLiteral( "Mapinfo" ), QObject::tr( "Mapinfo TAB" ), - "*.tab", - "tab", + QStringLiteral( "*.tab" ), + QStringLiteral( "tab" ), datasetOptions, layerOptions ) ); // QGIS internal alias for MIF files - driverMetadata.insert( "MapInfo MIF", + driverMetadata.insert( QStringLiteral( "MapInfo MIF" ), MetaData( - "Mapinfo", + QStringLiteral( "Mapinfo" ), QObject::tr( "Mapinfo MIF" ), - "*.mif", - "mif", + QStringLiteral( "*.mif" ), + QStringLiteral( "mif" ), datasetOptions, layerOptions ) @@ -1363,64 +1363,64 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "3D", new BoolOption( + datasetOptions.insert( QStringLiteral( "3D" ), new BoolOption( QObject::tr( "Determine whether 2D (seed_2d.dgn) or 3D (seed_3d.dgn) " "seed file should be used. This option is ignored if the SEED option is provided." ), false // Default value ) ); - datasetOptions.insert( "SEED", new StringOption( + datasetOptions.insert( QStringLiteral( "SEED" ), new StringOption( QObject::tr( "Override the seed file to use." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "COPY_WHOLE_SEED_FILE", new BoolOption( + datasetOptions.insert( QStringLiteral( "COPY_WHOLE_SEED_FILE" ), new BoolOption( QObject::tr( "Indicate whether the whole seed file should be copied. " "If not, only the first three elements will be copied." ), false // Default value ) ); - datasetOptions.insert( "COPY_SEED_FILE_COLOR_TABLEE", new BoolOption( + datasetOptions.insert( QStringLiteral( "COPY_SEED_FILE_COLOR_TABLEE" ), new BoolOption( QObject::tr( "Indicates whether the color table should be copied from the seed file." ), false // Default value ) ); - datasetOptions.insert( "MASTER_UNIT_NAME", new StringOption( + datasetOptions.insert( QStringLiteral( "MASTER_UNIT_NAME" ), new StringOption( QObject::tr( "Override the master unit name from the seed file with " "the provided one or two character unit name." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "SUB_UNIT_NAME", new StringOption( + datasetOptions.insert( QStringLiteral( "SUB_UNIT_NAME" ), new StringOption( QObject::tr( "Override the sub unit name from the seed file with the provided " "one or two character unit name." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - datasetOptions.insert( "SUB_UNITS_PER_MASTER_UNIT", new IntOption( + datasetOptions.insert( QStringLiteral( "SUB_UNITS_PER_MASTER_UNIT" ), new IntOption( QObject::tr( "Override the number of subunits per master unit. " "By default the seed file value is used." ), 0 // Default value ) ); - datasetOptions.insert( "UOR_PER_SUB_UNIT", new IntOption( + datasetOptions.insert( QStringLiteral( "UOR_PER_SUB_UNIT" ), new IntOption( QObject::tr( "Override the number of UORs (Units of Resolution) " "per sub unit. By default the seed file value is used." ), 0 // Default value ) ); - datasetOptions.insert( "ORIGIN", new StringOption( + datasetOptions.insert( QStringLiteral( "ORIGIN" ), new StringOption( QObject::tr( "ORIGIN=x,y,z: Override the origin of the design plane. " "By default the origin from the seed file is used." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - driverMetadata.insert( "DGN", + driverMetadata.insert( QStringLiteral( "DGN" ), MetaData( - "Microstation DGN", + QStringLiteral( "Microstation DGN" ), QObject::tr( "Microstation DGN" ), - "*.dgn", - "dgn", + QStringLiteral( "*.dgn" ), + QStringLiteral( "dgn" ), datasetOptions, layerOptions ) @@ -1430,15 +1430,15 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "UPDATES", new SetOption( + datasetOptions.insert( QStringLiteral( "UPDATES" ), new SetOption( QObject::tr( "Should update files be incorporated into the base data on the fly. " ), QStringList() - << "APPLY" - << "IGNORE", - "APPLY" // Default value + << QStringLiteral( "APPLY" ) + << QStringLiteral( "IGNORE" ), + QStringLiteral( "APPLY" ) // Default value ) ); - datasetOptions.insert( "SPLIT_MULTIPOINT", new BoolOption( + datasetOptions.insert( QStringLiteral( "SPLIT_MULTIPOINT" ), new BoolOption( QObject::tr( "Should multipoint soundings be split into many single point sounding features. " "Multipoint geometries are not well handled by many formats, " "so it can be convenient to split single sounding features with many points " @@ -1446,40 +1446,40 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() false // Default value ) ); - datasetOptions.insert( "ADD_SOUNDG_DEPTH", new BoolOption( + datasetOptions.insert( QStringLiteral( "ADD_SOUNDG_DEPTH" ), new BoolOption( QObject::tr( "Should a DEPTH attribute be added on SOUNDG features and assign the depth " "of the sounding. This should only be enabled with SPLIT_MULTIPOINT is " "also enabled." ), false // Default value ) ); - datasetOptions.insert( "RETURN_PRIMITIVES", new BoolOption( + datasetOptions.insert( QStringLiteral( "RETURN_PRIMITIVES" ), new BoolOption( QObject::tr( "Should all the low level geometry primitives be returned as special " "IsolatedNode, ConnectedNode, Edge and Face layers." ), true // Default value ) ); - datasetOptions.insert( "PRESERVE_EMPTY_NUMBERS", new BoolOption( + datasetOptions.insert( QStringLiteral( "PRESERVE_EMPTY_NUMBERS" ), new BoolOption( QObject::tr( "If enabled, numeric attributes assigned an empty string as a value will " "be preserved as a special numeric value. This option should not generally " "be needed, but may be useful when translated S-57 to S-57 losslessly." ), false // Default value ) ); - datasetOptions.insert( "LNAM_REFS", new BoolOption( + datasetOptions.insert( QStringLiteral( "LNAM_REFS" ), new BoolOption( QObject::tr( "Should LNAM and LNAM_REFS fields be attached to features capturing " "the feature to feature relationships in the FFPT group of the S-57 file." ), true // Default value ) ); - datasetOptions.insert( "RETURN_LINKAGES", new BoolOption( + datasetOptions.insert( QStringLiteral( "RETURN_LINKAGES" ), new BoolOption( QObject::tr( "Should additional attributes relating features to their underlying " "geometric primitives be attached. These are the values of the FSPT group, " "and are primarily needed when doing S-57 to S-57 translations." ), true // Default value ) ); - datasetOptions.insert( "RECODE_BY_DSSI", new BoolOption( + datasetOptions.insert( QStringLiteral( "RECODE_BY_DSSI" ), new BoolOption( QObject::tr( "Should attribute values be recoded to UTF-8 from the character encoding " "specified in the S57 DSSI record." ), false // Default value @@ -1487,12 +1487,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() // set OGR_S57_OPTIONS = "RETURN_PRIMITIVES=ON,RETURN_LINKAGES=ON,LNAM_REFS=ON" - driverMetadata.insert( "S57", + driverMetadata.insert( QStringLiteral( "S57" ), MetaData( - "S-57 Base file", + QStringLiteral( "S-57 Base file" ), QObject::tr( "S-57 Base file" ), - "*.000", - "000", + QStringLiteral( "*.000" ), + QStringLiteral( "000" ), datasetOptions, layerOptions ) @@ -1502,12 +1502,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - driverMetadata.insert( "SDTS", + driverMetadata.insert( QStringLiteral( "SDTS" ), MetaData( - "Spatial Data Transfer Standard [SDTS]", + QStringLiteral( "Spatial Data Transfer Standard [SDTS]" ), QObject::tr( "Spatial Data Transfer Standard [SDTS]" ), - "*catd.ddf", - "ddf", + QStringLiteral( "*catd.ddf" ), + QStringLiteral( "ddf" ), datasetOptions, layerOptions ) @@ -1517,7 +1517,7 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "METADATA", new BoolOption( + datasetOptions.insert( QStringLiteral( "METADATA" ), new BoolOption( QObject::tr( "Can be used to avoid creating the geometry_columns and spatial_ref_sys " "tables in a new database. By default these metadata tables are created " "when a new database is created." ), @@ -1525,45 +1525,45 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() ) ); // Will handle the spatialite alias - datasetOptions.insert( "SPATIALITE", new HiddenOption( - "NO" + datasetOptions.insert( QStringLiteral( "SPATIALITE" ), new HiddenOption( + QStringLiteral( "NO" ) ) ); - datasetOptions.insert( "INIT_WITH_EPSG", new HiddenOption( - "NO" + datasetOptions.insert( QStringLiteral( "INIT_WITH_EPSG" ), new HiddenOption( + QStringLiteral( "NO" ) ) ); - layerOptions.insert( "FORMAT", new SetOption( + layerOptions.insert( QStringLiteral( "FORMAT" ), new SetOption( QObject::tr( "Controls the format used for the geometry column. Defaults to WKB." "This is generally more space and processing efficient, but harder " "to inspect or use in simple applications than WKT (Well Known Text)." ), QStringList() - << "WKB" - << "WKT", - "WKB" // Default value + << QStringLiteral( "WKB" ) + << QStringLiteral( "WKT" ), + QStringLiteral( "WKB" ) // Default value ) ); - layerOptions.insert( "LAUNDER", new BoolOption( + layerOptions.insert( QStringLiteral( "LAUNDER" ), new BoolOption( QObject::tr( "Controls whether layer and field names will be laundered for easier use " "in SQLite. Laundered names will be converted to lower case and some special " "characters(' - #) will be changed to underscores." ), true // Default value ) ); - layerOptions.insert( "SPATIAL_INDEX", new HiddenOption( - "NO" + layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new HiddenOption( + QStringLiteral( "NO" ) ) ); - layerOptions.insert( "COMPRESS_GEOM", new HiddenOption( - "NO" + layerOptions.insert( QStringLiteral( "COMPRESS_GEOM" ), new HiddenOption( + QStringLiteral( "NO" ) ) ); - layerOptions.insert( "SRID", new HiddenOption( - "" + layerOptions.insert( QStringLiteral( "SRID" ), new HiddenOption( + QLatin1String( "" ) ) ); - layerOptions.insert( "COMPRESS_COLUMNS", new StringOption( + layerOptions.insert( QStringLiteral( "COMPRESS_COLUMNS" ), new StringOption( QObject::tr( "column_name1[,column_name2, ...] A list of (String) columns that " "must be compressed with ZLib DEFLATE algorithm. This might be beneficial " "for databases that have big string blobs. However, use with care, since " @@ -1573,18 +1573,18 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() "done transparently. However, such columns cannot be (easily) queried with " "an attribute filter or WHERE clause. Note: in table definition, such columns " "have the 'VARCHAR_deflate' declaration type." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - driverMetadata.insert( "SQLite", + driverMetadata.insert( QStringLiteral( "SQLite" ), MetaData( - "SQLite", + QStringLiteral( "SQLite" ), QObject::tr( "SQLite" ), - "*.sqlite", - "sqlite", + QStringLiteral( "*.sqlite" ), + QStringLiteral( "sqlite" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1592,49 +1592,49 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "METADATA", new BoolOption( + datasetOptions.insert( QStringLiteral( "METADATA" ), new BoolOption( QObject::tr( "Can be used to avoid creating the geometry_columns and spatial_ref_sys " "tables in a new database. By default these metadata tables are created " "when a new database is created." ), true // Default value ) ); - datasetOptions.insert( "SPATIALITE", new HiddenOption( - "YES" + datasetOptions.insert( QStringLiteral( "SPATIALITE" ), new HiddenOption( + QStringLiteral( "YES" ) ) ); - datasetOptions.insert( "INIT_WITH_EPSG", new BoolOption( + datasetOptions.insert( QStringLiteral( "INIT_WITH_EPSG" ), new BoolOption( QObject::tr( "Insert the content of the EPSG CSV files into the spatial_ref_sys table. " "Set to NO for regular SQLite databases." ), true // Default value ) ); - layerOptions.insert( "FORMAT", new HiddenOption( - "SPATIALITE" + layerOptions.insert( QStringLiteral( "FORMAT" ), new HiddenOption( + QStringLiteral( "SPATIALITE" ) ) ); - layerOptions.insert( "LAUNDER", new BoolOption( + layerOptions.insert( QStringLiteral( "LAUNDER" ), new BoolOption( QObject::tr( "Controls whether layer and field names will be laundered for easier use " "in SQLite. Laundered names will be converted to lower case and some special " "characters(' - #) will be changed to underscores." ), true // Default value ) ); - layerOptions.insert( "SPATIAL_INDEX", new BoolOption( + layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new BoolOption( QObject::tr( "If the database is of the SpatiaLite flavour, and if OGR is linked " "against libspatialite, this option can be used to control if a spatial " "index must be created." ), true // Default value ) ); - layerOptions.insert( "COMPRESS_GEOM", new BoolOption( + layerOptions.insert( QStringLiteral( "COMPRESS_GEOM" ), new BoolOption( QObject::tr( "If the format of the geometry BLOB is of the SpatiaLite flavour, " "this option can be used to control if the compressed format for " "geometries (LINESTRINGs, POLYGONs) must be used" ), false // Default value ) ); - layerOptions.insert( "SRID", new StringOption( + layerOptions.insert( QStringLiteral( "SRID" ), new StringOption( QObject::tr( "Used to force the SRID number of the SRS associated with the layer. " "When this option isn't specified and that a SRS is associated with the " "layer, a search is made in the spatial_ref_sys to find a match for the " @@ -1642,10 +1642,10 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() "the spatial_ref_sys table. When the SRID option is specified, this " "search (and the eventual insertion of a new entry) will not be done: " "the specified SRID is used as such." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - layerOptions.insert( "COMPRESS_COLUMNS", new StringOption( + layerOptions.insert( QStringLiteral( "COMPRESS_COLUMNS" ), new StringOption( QObject::tr( "column_name1[,column_name2, ...] A list of (String) columns that " "must be compressed with ZLib DEFLATE algorithm. This might be beneficial " "for databases that have big string blobs. However, use with care, since " @@ -1655,18 +1655,18 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() "done transparently. However, such columns cannot be (easily) queried with " "an attribute filter or WHERE clause. Note: in table definition, such columns " "have the 'VARCHAR_deflate' declaration type." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - driverMetadata.insert( "SpatiaLite", + driverMetadata.insert( QStringLiteral( "SpatiaLite" ), MetaData( - "SpatiaLite", + QStringLiteral( "SpatiaLite" ), QObject::tr( "SpatiaLite" ), - "*.sqlite", - "sqlite", + QStringLiteral( "*.sqlite" ), + QStringLiteral( "sqlite" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); // AutoCAD DXF @@ -1685,12 +1685,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() ) ); #endif - driverMetadata.insert( "DXF", + driverMetadata.insert( QStringLiteral( "DXF" ), MetaData( - "AutoCAD DXF", + QStringLiteral( "AutoCAD DXF" ), QObject::tr( "AutoCAD DXF" ), - "*.dxf", - "dxf", + QStringLiteral( "*.dxf" ), + QStringLiteral( "dxf" ), datasetOptions, layerOptions ) @@ -1700,13 +1700,13 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - datasetOptions.insert( "EXTENSION", new SetOption( + datasetOptions.insert( QStringLiteral( "EXTENSION" ), new SetOption( QObject::tr( "Indicates the GeoConcept export file extension. " "TXT was used by earlier releases of GeoConcept. GXT is currently used." ), QStringList() - << "GXT" - << "TXT", - "GXT" // Default value + << QStringLiteral( "GXT" ) + << QStringLiteral( "TXT" ), + QStringLiteral( "GXT" ) // Default value ) ); #if 0 @@ -1718,12 +1718,12 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() ) ); #endif - driverMetadata.insert( "Geoconcept", + driverMetadata.insert( QStringLiteral( "Geoconcept" ), MetaData( - "Geoconcept", + QStringLiteral( "Geoconcept" ), QObject::tr( "Geoconcept" ), - "*.gxt *.txt", - "gxt", + QStringLiteral( "*.gxt *.txt" ), + QStringLiteral( "gxt" ), datasetOptions, layerOptions ) @@ -1733,31 +1733,31 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "FEATURE_DATASET", new StringOption( + layerOptions.insert( QStringLiteral( "FEATURE_DATASET" ), new StringOption( QObject::tr( "When this option is set, the new layer will be created inside the named " "FeatureDataset folder. If the folder does not already exist, it will be created." ), - "" // Default value + QLatin1String( "" ) // Default value ) ); - layerOptions.insert( "GEOMETRY_NAME", new StringOption( + layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new StringOption( QObject::tr( "Set name of geometry column in new layer. Defaults to 'SHAPE'." ), - "SHAPE" // Default value + QStringLiteral( "SHAPE" ) // Default value ) ); - layerOptions.insert( "OID_NAME", new StringOption( + layerOptions.insert( QStringLiteral( "OID_NAME" ), new StringOption( QObject::tr( "Name of the OID column to create. Defaults to 'OBJECTID'." ), - "OBJECTID" // Default value + QStringLiteral( "OBJECTID" ) // Default value ) ); - driverMetadata.insert( "FileGDB", + driverMetadata.insert( QStringLiteral( "FileGDB" ), MetaData( - "ESRI FileGDB", + QStringLiteral( "ESRI FileGDB" ), QObject::tr( "ESRI FileGDB" ), - "*.gdb", - "gdb", + QStringLiteral( "*.gdb" ), + QStringLiteral( "gdb" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1765,25 +1765,25 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "OGR_XLSX_FIELD_TYPES", new SetOption( + layerOptions.insert( QStringLiteral( "OGR_XLSX_FIELD_TYPES" ), new SetOption( QObject::tr( "By default, the driver will try to detect the data type of fields. If set " "to STRING, all fields will be of String type." ), QStringList() - << "AUTO" - << "STRING", - "AUTO", // Default value + << QStringLiteral( "AUTO" ) + << QStringLiteral( "STRING" ), + QStringLiteral( "AUTO" ), // Default value false // Allow None ) ); - driverMetadata.insert( "XLSX", + driverMetadata.insert( QStringLiteral( "XLSX" ), MetaData( - "MS Office Open XML spreadsheet", + QStringLiteral( "MS Office Open XML spreadsheet" ), QObject::tr( "MS Office Open XML spreadsheet" ), - "*.xlsx", - "xlsx", + QStringLiteral( "*.xlsx" ), + QStringLiteral( "xlsx" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -1791,25 +1791,25 @@ QMap<QString, QgsVectorFileWriter::MetaData> QgsVectorFileWriter::initMetaData() datasetOptions.clear(); layerOptions.clear(); - layerOptions.insert( "OGR_ODS_FIELD_TYPES", new SetOption( + layerOptions.insert( QStringLiteral( "OGR_ODS_FIELD_TYPES" ), new SetOption( QObject::tr( "By default, the driver will try to detect the data type of fields. If set " "to STRING, all fields will be of String type." ), QStringList() - << "AUTO" - << "STRING", - "AUTO", // Default value + << QStringLiteral( "AUTO" ) + << QStringLiteral( "STRING" ), + QStringLiteral( "AUTO" ), // Default value false // Allow None ) ); - driverMetadata.insert( "ODS", + driverMetadata.insert( QStringLiteral( "ODS" ), MetaData( - "Open Document Spreadsheet", + QStringLiteral( "Open Document Spreadsheet" ), QObject::tr( "Open Document Spreadsheet" ), - "*.ods", - "ods", + QStringLiteral( "*.ods" ), + QStringLiteral( "ods" ), datasetOptions, layerOptions, - "UTF-8" + QStringLiteral( "UTF-8" ) ) ); @@ -2015,9 +2015,9 @@ OGRFeatureH QgsVectorFileWriter::createFeature( const QgsFeature& feature ) 0, 0, 0, 0 ); break; case QVariant::DateTime: - if ( mOgrDriverName == "ESRI Shapefile" ) + if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) ) { - OGR_F_SetFieldString( poFeature, ogrField, mCodec->fromUnicode( attrValue.toDateTime().toString( "yyyy/MM/dd hh:mm:ss.zzz" ) ).constData() ); + OGR_F_SetFieldString( poFeature, ogrField, mCodec->fromUnicode( attrValue.toDateTime().toString( QStringLiteral( "yyyy/MM/dd hh:mm:ss.zzz" ) ) ).constData() ); } else { @@ -2032,7 +2032,7 @@ OGRFeatureH QgsVectorFileWriter::createFeature( const QgsFeature& feature ) } break; case QVariant::Time: - if ( mOgrDriverName == "ESRI Shapefile" ) + if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) ) { OGR_F_SetFieldString( poFeature, ogrField, mCodec->fromUnicode( attrValue.toString() ).constData() ); } @@ -2274,7 +2274,7 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe } QgsVectorFileWriter::SaveVectorOptions::SaveVectorOptions() - : driverName( "ESRI Shapefile" ) + : driverName( QStringLiteral( "ESRI Shapefile" ) ) , layerName( QString() ) , actionOnExistingFile( CreateOrOverwriteFile ) , fileEncoding( QString() ) @@ -2343,7 +2343,7 @@ QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer* layer, Q_FOREACH ( int idx, layer->attributeList() ) { QgsField fld = layer->fields().at( idx ); - if ( layer->providerType() == "oracle" && fld.typeName().contains( "SDO_GEOMETRY" ) ) + if ( layer->providerType() == QLatin1String( "oracle" ) && fld.typeName().contains( QLatin1String( "SDO_GEOMETRY" ) ) ) continue; attributes.append( idx ); } @@ -2358,7 +2358,7 @@ QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer* layer, } } - if ( layer->providerType() == "ogr" && layer->dataProvider() ) + if ( layer->providerType() == QLatin1String( "ogr" ) && layer->dataProvider() ) { QStringList theURIParts = layer->dataProvider()->dataSourceUri().split( '|' ); QString srcFileName = theURIParts[0]; @@ -2371,7 +2371,7 @@ QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer* layer, } // Shapefiles might contain multi types although wkbType() only reports singles - if ( layer->storageType() == "ESRI Shapefile" && !QgsWkbTypes::isMultiType( destWkbType ) ) + if ( layer->storageType() == QLatin1String( "ESRI Shapefile" ) && !QgsWkbTypes::isMultiType( destWkbType ) ) { QgsFeatureRequest req; if ( options.onlySelectedFeatures ) @@ -2391,7 +2391,7 @@ QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer* layer, } } } - else if ( layer->providerType() == "spatialite" ) + else if ( layer->providerType() == QLatin1String( "spatialite" ) ) { for ( int i = 0; i < fields.size(); i++ ) { @@ -2656,18 +2656,18 @@ QMap<QString, QString> QgsVectorFileWriter::ogrDriverList() if ( OGR_Dr_TestCapability( drv, "CreateDataSource" ) != 0 ) { // Add separate format for Mapinfo MIF (MITAB is OGR default) - if ( drvName == "MapInfo File" ) + if ( drvName == QLatin1String( "MapInfo File" ) ) { - writableDrivers << "MapInfo MIF"; + writableDrivers << QStringLiteral( "MapInfo MIF" ); } - else if ( drvName == "SQLite" ) + else if ( drvName == QLatin1String( "SQLite" ) ) { // Unfortunately it seems that there is no simple way to detect if // OGR SQLite driver is compiled with SpatiaLite support. // We have HAVE_SPATIALITE in QGIS, but that may differ from OGR // http://lists.osgeo.org/pipermail/gdal-dev/2012-November/034580.html // -> test if creation failes - QString option = "SPATIALITE=YES"; + QString option = QStringLiteral( "SPATIALITE=YES" ); char *options[2] = { CPLStrdup( option.toLocal8Bit().constData() ), nullptr }; OGRSFDriverH poDriver; QgsApplication::registerOgrDrivers(); @@ -2677,16 +2677,16 @@ QMap<QString, QString> QgsVectorFileWriter::ogrDriverList() OGRDataSourceH ds = OGR_Dr_CreateDataSource( poDriver, TO8F( QString( "/vsimem/spatialitetest.sqlite" ) ), options ); if ( ds ) { - writableDrivers << "SpatiaLite"; + writableDrivers << QStringLiteral( "SpatiaLite" ); OGR_Dr_DeleteDataSource( poDriver, TO8F( QString( "/vsimem/spatialitetest.sqlite" ) ) ); OGR_DS_Destroy( ds ); } } CPLFree( options[0] ); } - else if ( drvName == "ESRI Shapefile" ) + else if ( drvName == QLatin1String( "ESRI Shapefile" ) ) { - writableDrivers << "DBF file"; + writableDrivers << QStringLiteral( "DBF file" ); } writableDrivers << drvName; } @@ -2713,7 +2713,7 @@ QString QgsVectorFileWriter::fileFilterString() for ( ; it != driverFormatMap.constEnd(); ++it ) { if ( !filterString.isEmpty() ) - filterString += ";;"; + filterString += QLatin1String( ";;" ); filterString += it.key(); } @@ -2724,15 +2724,15 @@ QString QgsVectorFileWriter::filterForDriver( const QString& driverName ) { MetaData metadata; if ( !driverMetadata( driverName, metadata ) || metadata.trLongName.isEmpty() || metadata.glob.isEmpty() ) - return ""; + return QLatin1String( "" ); return metadata.trLongName + " [OGR] (" + metadata.glob.toLower() + ' ' + metadata.glob.toUpper() + ')'; } QString QgsVectorFileWriter::convertCodecNameForEncodingOption( const QString &codecName ) { - if ( codecName == "System" ) - return QString( "LDID/0" ); + if ( codecName == QLatin1String( "System" ) ) + return QStringLiteral( "LDID/0" ); QRegExp re = QRegExp( QString( "(CP|windows-|ISO[ -])(.+)" ), Qt::CaseInsensitive ); if ( re.exactMatch( codecName ) ) @@ -3039,7 +3039,7 @@ QStringList QgsVectorFileWriter::concatenateOptions( const QMap<QString, QgsVect QgsVectorFileWriter::IntOption *opt = dynamic_cast<QgsVectorFileWriter::IntOption*>( option ); if ( opt ) { - list.append( QString( "%1=%2" ).arg( it.key() ).arg( opt->defaultValue ) ); + list.append( QStringLiteral( "%1=%2" ).arg( it.key() ).arg( opt->defaultValue ) ); } break; } @@ -3049,7 +3049,7 @@ QStringList QgsVectorFileWriter::concatenateOptions( const QMap<QString, QgsVect QgsVectorFileWriter::SetOption *opt = dynamic_cast<QgsVectorFileWriter::SetOption*>( option ); if ( opt && !opt->defaultValue.isEmpty() ) { - list.append( QString( "%1=%2" ).arg( it.key(), opt->defaultValue ) ); + list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->defaultValue ) ); } break; } @@ -3059,7 +3059,7 @@ QStringList QgsVectorFileWriter::concatenateOptions( const QMap<QString, QgsVect QgsVectorFileWriter::StringOption *opt = dynamic_cast<QgsVectorFileWriter::StringOption*>( option ); if ( opt ) { - list.append( QString( "%1=%2" ).arg( it.key(), opt->defaultValue ) ); + list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->defaultValue ) ); } break; } @@ -3068,7 +3068,7 @@ QStringList QgsVectorFileWriter::concatenateOptions( const QMap<QString, QgsVect QgsVectorFileWriter::HiddenOption *opt = dynamic_cast<QgsVectorFileWriter::HiddenOption*>( option ); if ( opt ) { - list.append( QString( "%1=%2" ).arg( it.key(), opt->mValue ) ); + list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->mValue ) ); } break; } @@ -3090,7 +3090,7 @@ QgsVectorFileWriter::EditionCapabilities QgsVectorFileWriter::editionCapabilitie // Shapefile driver returns True for a "foo.shp" dataset name, // creating "bar.shp" new layer, but this would be a bit confusing // for the user, so pretent that it does not support that - if ( !( drvName == "ESRI Shapefile" && QFile::exists( datasetName ) ) ) + if ( !( drvName == QLatin1String( "ESRI Shapefile" ) && QFile::exists( datasetName ) ) ) caps |= CanAddNewLayer; } if ( OGR_DS_TestCapability( hDS, ODsCDeleteLayer ) ) diff --git a/src/core/qgsvectorfilewriter.h b/src/core/qgsvectorfilewriter.h index 21f045970fa6..034cc8c4beed 100644 --- a/src/core/qgsvectorfilewriter.h +++ b/src/core/qgsvectorfilewriter.h @@ -110,7 +110,7 @@ class CORE_EXPORT QgsVectorFileWriter { public: BoolOption( const QString& docString, bool defaultValue ) - : SetOption( docString, QStringList() << "YES" << "NO", defaultValue ? "YES" : "NO" ) + : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" ) {} }; @@ -120,7 +120,7 @@ class CORE_EXPORT QgsVectorFileWriter { public: explicit HiddenOption( const QString& value ) - : Option( "", Hidden ) + : Option( QLatin1String( "" ), Hidden ) , mValue( value ) {} @@ -264,7 +264,7 @@ class CORE_EXPORT QgsVectorFileWriter const QString& fileName, const QString& fileEncoding, const QgsCoordinateReferenceSystem& destCRS = QgsCoordinateReferenceSystem(), - const QString& driverName = "ESRI Shapefile", + const QString& driverName = QStringLiteral( "ESRI Shapefile" ), bool onlySelected = false, QString *errorMessage = nullptr, const QStringList &datasourceOptions = QStringList(), @@ -309,7 +309,7 @@ class CORE_EXPORT QgsVectorFileWriter const QString& fileName, const QString& fileEncoding, const QgsCoordinateTransform& ct, - const QString& driverName = "ESRI Shapefile", + const QString& driverName = QStringLiteral( "ESRI Shapefile" ), bool onlySelected = false, QString *errorMessage = nullptr, const QStringList &datasourceOptions = QStringList(), @@ -414,7 +414,7 @@ class CORE_EXPORT QgsVectorFileWriter const QgsFields& fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem& srs = QgsCoordinateReferenceSystem(), - const QString& driverName = "ESRI Shapefile", + const QString& driverName = QStringLiteral( "ESRI Shapefile" ), const QStringList &datasourceOptions = QStringList(), const QStringList &layerOptions = QStringList(), QString *newFilename = nullptr, diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index e9f36394db5d..f1b78711caed 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -161,11 +161,11 @@ QgsVectorLayer::QgsVectorLayer( const QString& vectorLayerPath, // Default simplify drawing settings QSettings settings; - mSimplifyMethod.setSimplifyHints( static_cast< QgsVectorSimplifyMethod::SimplifyHints >( settings.value( "/qgis/simplifyDrawingHints", static_cast< int>( mSimplifyMethod.simplifyHints() ) ).toInt() ) ); - mSimplifyMethod.setSimplifyAlgorithm( static_cast< QgsVectorSimplifyMethod::SimplifyAlgorithm >( settings.value( "/qgis/simplifyAlgorithm", static_cast< int>( mSimplifyMethod.simplifyAlgorithm() ) ).toInt() ) ); - mSimplifyMethod.setThreshold( settings.value( "/qgis/simplifyDrawingTol", mSimplifyMethod.threshold() ).toFloat() ); - mSimplifyMethod.setForceLocalOptimization( settings.value( "/qgis/simplifyLocal", mSimplifyMethod.forceLocalOptimization() ).toBool() ); - mSimplifyMethod.setMaximumScale( settings.value( "/qgis/simplifyMaxScale", mSimplifyMethod.maximumScale() ).toFloat() ); + mSimplifyMethod.setSimplifyHints( static_cast< QgsVectorSimplifyMethod::SimplifyHints >( settings.value( QStringLiteral( "/qgis/simplifyDrawingHints" ), static_cast< int>( mSimplifyMethod.simplifyHints() ) ).toInt() ) ); + mSimplifyMethod.setSimplifyAlgorithm( static_cast< QgsVectorSimplifyMethod::SimplifyAlgorithm >( settings.value( QStringLiteral( "/qgis/simplifyAlgorithm" ), static_cast< int>( mSimplifyMethod.simplifyAlgorithm() ) ).toInt() ) ); + mSimplifyMethod.setThreshold( settings.value( QStringLiteral( "/qgis/simplifyDrawingTol" ), mSimplifyMethod.threshold() ).toFloat() ); + mSimplifyMethod.setForceLocalOptimization( settings.value( QStringLiteral( "/qgis/simplifyLocal" ), mSimplifyMethod.forceLocalOptimization() ).toBool() ); + mSimplifyMethod.setMaximumScale( settings.value( QStringLiteral( "/qgis/simplifyMaxScale" ), mSimplifyMethod.maximumScale() ).toFloat() ); } // QgsVectorLayer ctor @@ -602,8 +602,8 @@ bool QgsVectorLayer::labelsEnabled() const // for simple labeling the mode can be "no labels" - so we need to check // in properties whether we are really enabled or not - if ( mLabeling->type() == "simple" ) - return customProperty( "labeling/enabled", QVariant( false ) ).toBool(); + if ( mLabeling->type() == QLatin1String( "simple" ) ) + return customProperty( QStringLiteral( "labeling/enabled" ), QVariant( false ) ).toBool(); // for other labeling implementations we always assume that labeling is enabled return true; @@ -705,7 +705,7 @@ bool QgsVectorLayer::countSymbolFeatures( bool showProgress ) QWidget* mainWindow = nullptr; Q_FOREACH ( QWidget* widget, qApp->topLevelWidgets() ) { - if ( widget->objectName() == "QgisApp" ) + if ( widget->objectName() == QLatin1String( "QgisApp" ) ) { mainWindow = widget; break; @@ -1366,11 +1366,11 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) QgsDebugMsg( QString( "Datasource in QgsVectorLayer::readXml: " ) + mDataSource.toLocal8Bit().data() ); //process provider key - QDomNode pkeyNode = layer_node.namedItem( "provider" ); + QDomNode pkeyNode = layer_node.namedItem( QStringLiteral( "provider" ) ); if ( pkeyNode.isNull() ) { - mProviderKey = ""; + mProviderKey = QLatin1String( "" ); } else { @@ -1384,13 +1384,13 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) // if the provider string isn't empty, then we successfully // got the stored provider } - else if ( mDataSource.contains( "dbname=" ) ) + else if ( mDataSource.contains( QLatin1String( "dbname=" ) ) ) { - mProviderKey = "postgres"; + mProviderKey = QStringLiteral( "postgres" ); } else { - mProviderKey = "ogr"; + mProviderKey = QStringLiteral( "ogr" ); } if ( !setDataProvider( mProviderKey ) ) @@ -1399,13 +1399,13 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) } QDomElement mapLayerNode = layer_node.toElement(); - if ( mapLayerNode.attribute( "readOnly", "0" ).toInt() == 1 ) + if ( mapLayerNode.attribute( QStringLiteral( "readOnly" ), QStringLiteral( "0" ) ).toInt() == 1 ) mReadOnly = true; QDomElement pkeyElem = pkeyNode.toElement(); if ( !pkeyElem.isNull() ) { - QString encodingString = pkeyElem.attribute( "encoding" ); + QString encodingString = pkeyElem.attribute( QStringLiteral( "encoding" ) ); if ( !encodingString.isEmpty() ) { mDataProvider->setEncoding( encodingString ); @@ -1433,16 +1433,16 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) // default expressions mDefaultExpressionMap.clear(); - QDomNode defaultsNode = layer_node.namedItem( "defaults" ); + QDomNode defaultsNode = layer_node.namedItem( QStringLiteral( "defaults" ) ); if ( !defaultsNode.isNull() ) { - QDomNodeList defaultNodeList = defaultsNode.toElement().elementsByTagName( "default" ); + QDomNodeList defaultNodeList = defaultsNode.toElement().elementsByTagName( QStringLiteral( "default" ) ); for ( int i = 0; i < defaultNodeList.size(); ++i ) { QDomElement defaultElem = defaultNodeList.at( i ).toElement(); - QString field = defaultElem.attribute( "field", QString() ); - QString expression = defaultElem.attribute( "expression", QString() ); + QString field = defaultElem.attribute( QStringLiteral( "field" ), QString() ); + QString expression = defaultElem.attribute( QStringLiteral( "expression" ), QString() ); if ( field.isEmpty() || expression.isEmpty() ) continue; @@ -1451,13 +1451,13 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) } updateFields(); - QDomNode depsNode = layer_node.namedItem( "dataDependencies" ); + QDomNode depsNode = layer_node.namedItem( QStringLiteral( "dataDependencies" ) ); QDomNodeList depsNodes = depsNode.childNodes(); QSet<QgsMapLayerDependency> sources; for ( int i = 0; i < depsNodes.count(); i++ ) { QDomNode node = depsNodes.at( i ); - QString source = depsNodes.at( i ).toElement().attribute( "id" ); + QString source = depsNodes.at( i ).toElement().attribute( QStringLiteral( "id" ) ); sources << QgsMapLayerDependency( source ); } setDependencies( sources ); @@ -1547,7 +1547,7 @@ bool QgsVectorLayer::setDataProvider( QString const & provider ) mExpressionFieldBuffer = new QgsExpressionFieldBuffer(); updateFields(); - if ( mProviderKey == "postgres" ) + if ( mProviderKey == QLatin1String( "postgres" ) ) { QgsDebugMsg( "Beautifying layer name " + name() ); @@ -1578,16 +1578,16 @@ bool QgsVectorLayer::setDataProvider( QString const & provider ) // deal with unnecessary schema qualification to make v.in.ogr happy mDataSource = mDataProvider->dataSourceUri(); } - else if ( mProviderKey == "osm" ) + else if ( mProviderKey == QLatin1String( "osm" ) ) { // make sure that the "observer" has been removed from URI to avoid crashes mDataSource = mDataProvider->dataSourceUri(); } - else if ( provider == "ogr" ) + else if ( provider == QLatin1String( "ogr" ) ) { // make sure that the /vsigzip or /vsizip is added to uri, if applicable mDataSource = mDataProvider->dataSourceUri(); - if ( mDataSource.right( 10 ) == "|layerid=0" ) + if ( mDataSource.right( 10 ) == QLatin1String( "|layerid=0" ) ) mDataSource.chop( 10 ); } @@ -1614,16 +1614,16 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, return false; } - mapLayerNode.setAttribute( "type", "vector" ); + mapLayerNode.setAttribute( QStringLiteral( "type" ), QStringLiteral( "vector" ) ); // set the geometry type - mapLayerNode.setAttribute( "geometry", QgsWkbTypes::geometryDisplayString( geometryType() ) ); + mapLayerNode.setAttribute( QStringLiteral( "geometry" ), QgsWkbTypes::geometryDisplayString( geometryType() ) ); // add provider node if ( mDataProvider ) { - QDomElement provider = document.createElement( "provider" ); - provider.setAttribute( "encoding", mDataProvider->encoding() ); + QDomElement provider = document.createElement( QStringLiteral( "provider" ) ); + provider.setAttribute( QStringLiteral( "encoding" ), mDataProvider->encoding() ); QDomText providerText = document.createTextNode( providerType() ); provider.appendChild( providerText ); layer_node.appendChild( provider ); @@ -1633,36 +1633,36 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, mJoinBuffer->writeXml( layer_node, document ); // dependencies - QDomElement dependenciesElement = document.createElement( "layerDependencies" ); + QDomElement dependenciesElement = document.createElement( QStringLiteral( "layerDependencies" ) ); Q_FOREACH ( const QgsMapLayerDependency& dep, dependencies() ) { if ( dep.type() != QgsMapLayerDependency::PresenceDependency ) continue; - QDomElement depElem = document.createElement( "layer" ); - depElem.setAttribute( "id", dep.layerId() ); + QDomElement depElem = document.createElement( QStringLiteral( "layer" ) ); + depElem.setAttribute( QStringLiteral( "id" ), dep.layerId() ); dependenciesElement.appendChild( depElem ); } layer_node.appendChild( dependenciesElement ); //default expressions - QDomElement defaultsElem = document.createElement( "defaults" ); + QDomElement defaultsElem = document.createElement( QStringLiteral( "defaults" ) ); Q_FOREACH ( const QgsField& field, mFields ) { - QDomElement defaultElem = document.createElement( "default" ); - defaultElem.setAttribute( "field", field.name() ); - defaultElem.setAttribute( "expression", field.defaultValueExpression() ); + QDomElement defaultElem = document.createElement( QStringLiteral( "default" ) ); + defaultElem.setAttribute( QStringLiteral( "field" ), field.name() ); + defaultElem.setAttribute( QStringLiteral( "expression" ), field.defaultValueExpression() ); defaultsElem.appendChild( defaultElem ); } layer_node.appendChild( defaultsElem ); // change dependencies - QDomElement dataDependenciesElement = document.createElement( "dataDependencies" ); + QDomElement dataDependenciesElement = document.createElement( QStringLiteral( "dataDependencies" ) ); Q_FOREACH ( const QgsMapLayerDependency& dep, dependencies() ) { if ( dep.type() != QgsMapLayerDependency::DataDependency ) continue; - QDomElement depElem = document.createElement( "layer" ); - depElem.setAttribute( "id", dep.layerId() ); + QDomElement depElem = document.createElement( QStringLiteral( "layer" ) ); + depElem.setAttribute( QStringLiteral( "id" ), dep.layerId() ); dataDependenciesElement.appendChild( depElem ); } layer_node.appendChild( dataDependenciesElement ); @@ -1688,10 +1688,10 @@ bool QgsVectorLayer::readSymbology( const QDomNode& node, QString& errorMessage readStyle( node, errorMessage ); - mDisplayExpression = node.namedItem( "previewExpression" ).toElement().text(); - mMapTipTemplate = node.namedItem( "mapTip" ).toElement().text(); + mDisplayExpression = node.namedItem( QStringLiteral( "previewExpression" ) ).toElement().text(); + mMapTipTemplate = node.namedItem( QStringLiteral( "mapTip" ) ).toElement().text(); - QString displayField = node.namedItem( "displayfield" ).toElement().text(); + QString displayField = node.namedItem( QStringLiteral( "displayfield" ) ).toElement().text(); // Try to migrate pre QGIS 3.0 display field property if ( mFields.lookupField( displayField ) < 0 ) @@ -1709,7 +1709,7 @@ bool QgsVectorLayer::readSymbology( const QDomNode& node, QString& errorMessage // process the attribute actions mActions->readXml( node ); - QDomNode annotationFormNode = node.namedItem( "annotationform" ); + QDomNode annotationFormNode = node.namedItem( QStringLiteral( "annotationform" ) ); if ( !annotationFormNode.isNull() ) { QDomElement e = annotationFormNode.toElement(); @@ -1717,40 +1717,40 @@ bool QgsVectorLayer::readSymbology( const QDomNode& node, QString& errorMessage } mAttributeAliasMap.clear(); - QDomNode aliasesNode = node.namedItem( "aliases" ); + QDomNode aliasesNode = node.namedItem( QStringLiteral( "aliases" ) ); if ( !aliasesNode.isNull() ) { QDomElement aliasElem; - QDomNodeList aliasNodeList = aliasesNode.toElement().elementsByTagName( "alias" ); + QDomNodeList aliasNodeList = aliasesNode.toElement().elementsByTagName( QStringLiteral( "alias" ) ); for ( int i = 0; i < aliasNodeList.size(); ++i ) { aliasElem = aliasNodeList.at( i ).toElement(); QString field; - if ( aliasElem.hasAttribute( "field" ) ) + if ( aliasElem.hasAttribute( QStringLiteral( "field" ) ) ) { - field = aliasElem.attribute( "field" ); + field = aliasElem.attribute( QStringLiteral( "field" ) ); } else { - int index = aliasElem.attribute( "index" ).toInt(); + int index = aliasElem.attribute( QStringLiteral( "index" ) ).toInt(); if ( index >= 0 && index < fields().count() ) field = fields().at( index ).name(); } - mAttributeAliasMap.insert( field, aliasElem.attribute( "name" ) ); + mAttributeAliasMap.insert( field, aliasElem.attribute( QStringLiteral( "name" ) ) ); } } updateFields(); //Attributes excluded from WMS and WFS mExcludeAttributesWMS.clear(); - QDomNode excludeWMSNode = node.namedItem( "excludeAttributesWMS" ); + QDomNode excludeWMSNode = node.namedItem( QStringLiteral( "excludeAttributesWMS" ) ); if ( !excludeWMSNode.isNull() ) { - QDomNodeList attributeNodeList = excludeWMSNode.toElement().elementsByTagName( "attribute" ); + QDomNodeList attributeNodeList = excludeWMSNode.toElement().elementsByTagName( QStringLiteral( "attribute" ) ); for ( int i = 0; i < attributeNodeList.size(); ++i ) { mExcludeAttributesWMS.insert( attributeNodeList.at( i ).toElement().text() ); @@ -1758,10 +1758,10 @@ bool QgsVectorLayer::readSymbology( const QDomNode& node, QString& errorMessage } mExcludeAttributesWFS.clear(); - QDomNode excludeWFSNode = node.namedItem( "excludeAttributesWFS" ); + QDomNode excludeWFSNode = node.namedItem( QStringLiteral( "excludeAttributesWFS" ) ); if ( !excludeWFSNode.isNull() ) { - QDomNodeList attributeNodeList = excludeWFSNode.toElement().elementsByTagName( "attribute" ); + QDomNodeList attributeNodeList = excludeWFSNode.toElement().elementsByTagName( QStringLiteral( "attribute" ) ); for ( int i = 0; i < attributeNodeList.size(); ++i ) { mExcludeAttributesWFS.insert( attributeNodeList.at( i ).toElement().text() ); @@ -1774,7 +1774,7 @@ bool QgsVectorLayer::readSymbology( const QDomNode& node, QString& errorMessage mConditionalStyles->readXml( node ); - readCustomProperties( node, "variable" ); + readCustomProperties( node, QStringLiteral( "variable" ) ); return true; } @@ -1815,7 +1815,7 @@ bool QgsVectorLayer::readStyle( const QDomNode &node, QString &errorMessage ) setRenderer( QgsFeatureRenderer::defaultRenderer( geometryType() ) ); } - QDomElement labelingElement = node.firstChildElement( "labeling" ); + QDomElement labelingElement = node.firstChildElement( QStringLiteral( "labeling" ) ); if ( !labelingElement.isNull() ) { QgsAbstractVectorLayerLabeling* l = QgsAbstractVectorLayerLabeling::create( labelingElement ); @@ -1823,7 +1823,7 @@ bool QgsVectorLayer::readStyle( const QDomNode &node, QString &errorMessage ) } // get and set the blend mode if it exists - QDomNode blendModeNode = node.namedItem( "blendMode" ); + QDomNode blendModeNode = node.namedItem( QStringLiteral( "blendMode" ) ); if ( !blendModeNode.isNull() ) { QDomElement e = blendModeNode.toElement(); @@ -1831,7 +1831,7 @@ bool QgsVectorLayer::readStyle( const QDomNode &node, QString &errorMessage ) } // get and set the feature blend mode if it exists - QDomNode featureBlendModeNode = node.namedItem( "featureBlendMode" ); + QDomNode featureBlendModeNode = node.namedItem( QStringLiteral( "featureBlendMode" ) ); if ( !featureBlendModeNode.isNull() ) { QDomElement e = featureBlendModeNode.toElement(); @@ -1839,7 +1839,7 @@ bool QgsVectorLayer::readStyle( const QDomNode &node, QString &errorMessage ) } // get and set the layer transparency if it exists - QDomNode layerTransparencyNode = node.namedItem( "layerTransparency" ); + QDomNode layerTransparencyNode = node.namedItem( QStringLiteral( "layerTransparency" ) ); if ( !layerTransparencyNode.isNull() ) { QDomElement e = layerTransparencyNode.toElement(); @@ -1849,25 +1849,25 @@ bool QgsVectorLayer::readStyle( const QDomNode &node, QString &errorMessage ) QDomElement e = node.toElement(); // get the simplification drawing settings - mSimplifyMethod.setSimplifyHints( static_cast< QgsVectorSimplifyMethod::SimplifyHints >( e.attribute( "simplifyDrawingHints", "1" ).toInt() ) ); - mSimplifyMethod.setSimplifyAlgorithm( static_cast< QgsVectorSimplifyMethod::SimplifyAlgorithm >( e.attribute( "simplifyAlgorithm", "0" ).toInt() ) ); - mSimplifyMethod.setThreshold( e.attribute( "simplifyDrawingTol", "1" ).toFloat() ); - mSimplifyMethod.setForceLocalOptimization( e.attribute( "simplifyLocal", "1" ).toInt() ); - mSimplifyMethod.setMaximumScale( e.attribute( "simplifyMaxScale", "1" ).toFloat() ); + mSimplifyMethod.setSimplifyHints( static_cast< QgsVectorSimplifyMethod::SimplifyHints >( e.attribute( QStringLiteral( "simplifyDrawingHints" ), QStringLiteral( "1" ) ).toInt() ) ); + mSimplifyMethod.setSimplifyAlgorithm( static_cast< QgsVectorSimplifyMethod::SimplifyAlgorithm >( e.attribute( QStringLiteral( "simplifyAlgorithm" ), QStringLiteral( "0" ) ).toInt() ) ); + mSimplifyMethod.setThreshold( e.attribute( QStringLiteral( "simplifyDrawingTol" ), QStringLiteral( "1" ) ).toFloat() ); + mSimplifyMethod.setForceLocalOptimization( e.attribute( QStringLiteral( "simplifyLocal" ), QStringLiteral( "1" ) ).toInt() ); + mSimplifyMethod.setMaximumScale( e.attribute( QStringLiteral( "simplifyMaxScale" ), QStringLiteral( "1" ) ).toFloat() ); //also restore custom properties (for labeling-ng) - readCustomProperties( node, "labeling" ); + readCustomProperties( node, QStringLiteral( "labeling" ) ); //diagram renderer and diagram layer settings delete mDiagramRenderer; mDiagramRenderer = nullptr; - QDomElement singleCatDiagramElem = node.firstChildElement( "SingleCategoryDiagramRenderer" ); + QDomElement singleCatDiagramElem = node.firstChildElement( QStringLiteral( "SingleCategoryDiagramRenderer" ) ); if ( !singleCatDiagramElem.isNull() ) { mDiagramRenderer = new QgsSingleCategoryDiagramRenderer(); mDiagramRenderer->readXml( singleCatDiagramElem, this ); } - QDomElement linearDiagramElem = node.firstChildElement( "LinearlyInterpolatedDiagramRenderer" ); + QDomElement linearDiagramElem = node.firstChildElement( QStringLiteral( "LinearlyInterpolatedDiagramRenderer" ) ); if ( !linearDiagramElem.isNull() ) { mDiagramRenderer = new QgsLinearlyInterpolatedDiagramRenderer(); @@ -1876,7 +1876,7 @@ bool QgsVectorLayer::readStyle( const QDomNode &node, QString &errorMessage ) if ( mDiagramRenderer ) { - QDomElement diagramSettingsElem = node.firstChildElement( "DiagramLayerSettings" ); + QDomElement diagramSettingsElem = node.firstChildElement( QStringLiteral( "DiagramLayerSettings" ) ); if ( !diagramSettingsElem.isNull() ) { delete mDiagramLayerSettings; @@ -1899,29 +1899,29 @@ bool QgsVectorLayer::writeSymbology( QDomNode& node, QDomDocument& doc, QString& // still other editing settings are written here, // although they are not part of symbology either - QDomElement afField = doc.createElement( "annotationform" ); + QDomElement afField = doc.createElement( QStringLiteral( "annotationform" ) ); QDomText afText = doc.createTextNode( QgsProject::instance()->writePath( mAnnotationForm ) ); afField.appendChild( afText ); node.appendChild( afField ); //attribute aliases - QDomElement aliasElem = doc.createElement( "aliases" ); + QDomElement aliasElem = doc.createElement( QStringLiteral( "aliases" ) ); Q_FOREACH ( const QgsField& field, mFields ) { - QDomElement aliasEntryElem = doc.createElement( "alias" ); - aliasEntryElem.setAttribute( "field", field.name() ); - aliasEntryElem.setAttribute( "index", mFields.indexFromName( field.name() ) ); - aliasEntryElem.setAttribute( "name", field.alias() ); + QDomElement aliasEntryElem = doc.createElement( QStringLiteral( "alias" ) ); + aliasEntryElem.setAttribute( QStringLiteral( "field" ), field.name() ); + aliasEntryElem.setAttribute( QStringLiteral( "index" ), mFields.indexFromName( field.name() ) ); + aliasEntryElem.setAttribute( QStringLiteral( "name" ), field.alias() ); aliasElem.appendChild( aliasEntryElem ); } node.appendChild( aliasElem ); //exclude attributes WMS - QDomElement excludeWMSElem = doc.createElement( "excludeAttributesWMS" ); + QDomElement excludeWMSElem = doc.createElement( QStringLiteral( "excludeAttributesWMS" ) ); QSet<QString>::const_iterator attWMSIt = mExcludeAttributesWMS.constBegin(); for ( ; attWMSIt != mExcludeAttributesWMS.constEnd(); ++attWMSIt ) { - QDomElement attrElem = doc.createElement( "attribute" ); + QDomElement attrElem = doc.createElement( QStringLiteral( "attribute" ) ); QDomText attrText = doc.createTextNode( *attWMSIt ); attrElem.appendChild( attrText ); excludeWMSElem.appendChild( attrElem ); @@ -1929,11 +1929,11 @@ bool QgsVectorLayer::writeSymbology( QDomNode& node, QDomDocument& doc, QString& node.appendChild( excludeWMSElem ); //exclude attributes WFS - QDomElement excludeWFSElem = doc.createElement( "excludeAttributesWFS" ); + QDomElement excludeWFSElem = doc.createElement( QStringLiteral( "excludeAttributesWFS" ) ); QSet<QString>::const_iterator attWFSIt = mExcludeAttributesWFS.constBegin(); for ( ; attWFSIt != mExcludeAttributesWFS.constEnd(); ++attWFSIt ) { - QDomElement attrElem = doc.createElement( "attribute" ); + QDomElement attrElem = doc.createElement( QStringLiteral( "attribute" ) ); QDomText attrText = doc.createTextNode( *attWFSIt ); attrElem.appendChild( attrText ); excludeWFSElem.appendChild( attrElem ); @@ -1950,16 +1950,16 @@ bool QgsVectorLayer::writeSymbology( QDomNode& node, QDomDocument& doc, QString& mExpressionFieldBuffer->writeXml( node, doc ); // save readonly state - node.toElement().setAttribute( "readOnly", mReadOnly ); + node.toElement().setAttribute( QStringLiteral( "readOnly" ), mReadOnly ); // save preview expression - QDomElement prevExpElem = doc.createElement( "previewExpression" ); + QDomElement prevExpElem = doc.createElement( QStringLiteral( "previewExpression" ) ); QDomText prevExpText = doc.createTextNode( mDisplayExpression ); prevExpElem.appendChild( prevExpText ); node.appendChild( prevExpElem ); // save map tip - QDomElement mapTipElem = doc.createElement( "mapTip" ); + QDomElement mapTipElem = doc.createElement( QStringLiteral( "mapTip" ) ); QDomText mapTipText = doc.createTextNode( mMapTipTemplate ); mapTipElem.appendChild( mapTipText ); node.toElement().appendChild( mapTipElem ); @@ -1988,29 +1988,29 @@ bool QgsVectorLayer::writeStyle( QDomNode &node, QDomDocument &doc, QString &err } // save the simplification drawing settings - mapLayerNode.setAttribute( "simplifyDrawingHints", QString::number( mSimplifyMethod.simplifyHints() ) ); - mapLayerNode.setAttribute( "simplifyAlgorithm", QString::number( mSimplifyMethod.simplifyAlgorithm() ) ); - mapLayerNode.setAttribute( "simplifyDrawingTol", QString::number( mSimplifyMethod.threshold() ) ); - mapLayerNode.setAttribute( "simplifyLocal", mSimplifyMethod.forceLocalOptimization() ? 1 : 0 ); - mapLayerNode.setAttribute( "simplifyMaxScale", QString::number( mSimplifyMethod.maximumScale() ) ); + mapLayerNode.setAttribute( QStringLiteral( "simplifyDrawingHints" ), QString::number( mSimplifyMethod.simplifyHints() ) ); + mapLayerNode.setAttribute( QStringLiteral( "simplifyAlgorithm" ), QString::number( mSimplifyMethod.simplifyAlgorithm() ) ); + mapLayerNode.setAttribute( QStringLiteral( "simplifyDrawingTol" ), QString::number( mSimplifyMethod.threshold() ) ); + mapLayerNode.setAttribute( QStringLiteral( "simplifyLocal" ), mSimplifyMethod.forceLocalOptimization() ? 1 : 0 ); + mapLayerNode.setAttribute( QStringLiteral( "simplifyMaxScale" ), QString::number( mSimplifyMethod.maximumScale() ) ); //save customproperties (for labeling ng) writeCustomProperties( node, doc ); // add the blend mode field - QDomElement blendModeElem = doc.createElement( "blendMode" ); + QDomElement blendModeElem = doc.createElement( QStringLiteral( "blendMode" ) ); QDomText blendModeText = doc.createTextNode( QString::number( QgsPainting::getBlendModeEnum( blendMode() ) ) ); blendModeElem.appendChild( blendModeText ); node.appendChild( blendModeElem ); // add the feature blend mode field - QDomElement featureBlendModeElem = doc.createElement( "featureBlendMode" ); + QDomElement featureBlendModeElem = doc.createElement( QStringLiteral( "featureBlendMode" ) ); QDomText featureBlendModeText = doc.createTextNode( QString::number( QgsPainting::getBlendModeEnum( featureBlendMode() ) ) ); featureBlendModeElem.appendChild( featureBlendModeText ); node.appendChild( featureBlendModeElem ); // add the layer transparency - QDomElement layerTransparencyElem = doc.createElement( "layerTransparency" ); + QDomElement layerTransparencyElem = doc.createElement( QStringLiteral( "layerTransparency" ) ); QDomText layerTransparencyText = doc.createTextNode( QString::number( layerTransparency() ) ); layerTransparencyElem.appendChild( layerTransparencyText ); node.appendChild( layerTransparencyElem ); @@ -2028,10 +2028,10 @@ bool QgsVectorLayer::writeStyle( QDomNode &node, QDomDocument &doc, QString &err bool QgsVectorLayer::readSld( const QDomNode& node, QString& errorMessage ) { // get the Name element - QDomElement nameElem = node.firstChildElement( "Name" ); + QDomElement nameElem = node.firstChildElement( QStringLiteral( "Name" ) ); if ( nameElem.isNull() ) { - errorMessage = "Warning: Name element not found within NamedLayer while it's required."; + errorMessage = QStringLiteral( "Warning: Name element not found within NamedLayer while it's required." ); } if ( hasGeometryType() ) @@ -2058,7 +2058,7 @@ bool QgsVectorLayer::writeSld( QDomNode& node, QDomDocument& doc, QString& error Q_UNUSED( errorMessage ); // store the Name element - QDomElement nameNode = doc.createElement( "se:Name" ); + QDomElement nameNode = doc.createElement( QStringLiteral( "se:Name" ) ); nameNode.appendChild( doc.createTextNode( name() ) ); node.appendChild( nameNode ); @@ -2325,7 +2325,7 @@ bool QgsVectorLayer::commitChanges() } else { - QgsMessageLog::logMessage( tr( "Commit errors:\n %1" ).arg( mCommitErrors.join( "\n " ) ) ); + QgsMessageLog::logMessage( tr( "Commit errors:\n %1" ).arg( mCommitErrors.join( QStringLiteral( "\n " ) ) ) ); } if ( mCache ) @@ -2676,17 +2676,17 @@ QString QgsVectorLayer::displayExpression() const // We assume that the user has organized the data with the // more "interesting" field names first. As such, name should // be selected before oldname, othername, etc. - if ( fldName.indexOf( "name", 0, Qt::CaseInsensitive ) > -1 ) + if ( fldName.indexOf( QLatin1String( "name" ), 0, Qt::CaseInsensitive ) > -1 ) { idxName = fldName; break; } - if ( fldName.indexOf( "descrip", 0, Qt::CaseInsensitive ) > -1 ) + if ( fldName.indexOf( QLatin1String( "descrip" ), 0, Qt::CaseInsensitive ) > -1 ) { idxName = fldName; break; } - if ( fldName.indexOf( "id", 0, Qt::CaseInsensitive ) > -1 ) + if ( fldName.indexOf( QLatin1String( "id" ), 0, Qt::CaseInsensitive ) > -1 ) { idxName = fldName; break; @@ -3443,14 +3443,14 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) if ( element.isNull() ) return; - QDomElement userStyleElem = element.firstChildElement( "UserStyle" ); + QDomElement userStyleElem = element.firstChildElement( QStringLiteral( "UserStyle" ) ); if ( userStyleElem.isNull() ) { QgsDebugMsg( "Info: UserStyle element not found." ); return; } - QDomElement featureTypeStyleElem = userStyleElem.firstChildElement( "FeatureTypeStyle" ); + QDomElement featureTypeStyleElem = userStyleElem.firstChildElement( QStringLiteral( "FeatureTypeStyle" ) ); if ( featureTypeStyleElem.isNull() ) { QgsDebugMsg( "Info: FeatureTypeStyle element not found." ); @@ -3458,7 +3458,7 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) } // use last rule - QDomElement ruleElem = featureTypeStyleElem.lastChildElement( "Rule" ); + QDomElement ruleElem = featureTypeStyleElem.lastChildElement( QStringLiteral( "Rule" ) ); if ( ruleElem.isNull() ) { QgsDebugMsg( "Info: Rule element not found." ); @@ -3466,7 +3466,7 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) } // use last text symbolizer - QDomElement textSymbolizerElem = ruleElem.lastChildElement( "TextSymbolizer" ); + QDomElement textSymbolizerElem = ruleElem.lastChildElement( QStringLiteral( "TextSymbolizer" ) ); if ( textSymbolizerElem.isNull() ) { QgsDebugMsg( "Info: TextSymbolizer element not found." ); @@ -3474,45 +3474,45 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) } // Label - setCustomProperty( "labeling/enabled", false ); - QDomElement labelElem = textSymbolizerElem.firstChildElement( "Label" ); + setCustomProperty( QStringLiteral( "labeling/enabled" ), false ); + QDomElement labelElem = textSymbolizerElem.firstChildElement( QStringLiteral( "Label" ) ); if ( !labelElem.isNull() ) { - QDomElement propertyNameElem = labelElem.firstChildElement( "PropertyName" ); + QDomElement propertyNameElem = labelElem.firstChildElement( QStringLiteral( "PropertyName" ) ); if ( !propertyNameElem.isNull() ) { // enable labeling - setCustomProperty( "labeling", "pal" ); - setCustomProperty( "labeling/enabled", true ); + setCustomProperty( QStringLiteral( "labeling" ), "pal" ); + setCustomProperty( QStringLiteral( "labeling/enabled" ), true ); // set labeling defaults - setCustomProperty( "labeling/fontFamily", "Sans-Serif" ); - setCustomProperty( "labeling/fontItalic", false ); - setCustomProperty( "labeling/fontSize", 10 ); - setCustomProperty( "labeling/fontSizeInMapUnits", false ); - setCustomProperty( "labeling/fontBold", false ); - setCustomProperty( "labeling/fontUnderline", false ); - setCustomProperty( "labeling/textColorR", 0 ); - setCustomProperty( "labeling/textColorG", 0 ); - setCustomProperty( "labeling/textColorB", 0 ); - setCustomProperty( "labeling/textTransp", 0 ); - setCustomProperty( "labeling/bufferDraw", false ); - setCustomProperty( "labeling/bufferSize", 1 ); - setCustomProperty( "labeling/bufferSizeInMapUnits", false ); - setCustomProperty( "labeling/bufferColorR", 255 ); - setCustomProperty( "labeling/bufferColorG", 255 ); - setCustomProperty( "labeling/bufferColorB", 255 ); - setCustomProperty( "labeling/bufferTransp", 0 ); - setCustomProperty( "labeling/placement", QgsPalLayerSettings::AroundPoint ); - setCustomProperty( "labeling/xOffset", 0 ); - setCustomProperty( "labeling/yOffset", 0 ); - setCustomProperty( "labeling/labelOffsetInMapUnits", false ); - setCustomProperty( "labeling/angleOffset", 0 ); + setCustomProperty( QStringLiteral( "labeling/fontFamily" ), "Sans-Serif" ); + setCustomProperty( QStringLiteral( "labeling/fontItalic" ), false ); + setCustomProperty( QStringLiteral( "labeling/fontSize" ), 10 ); + setCustomProperty( QStringLiteral( "labeling/fontSizeInMapUnits" ), false ); + setCustomProperty( QStringLiteral( "labeling/fontBold" ), false ); + setCustomProperty( QStringLiteral( "labeling/fontUnderline" ), false ); + setCustomProperty( QStringLiteral( "labeling/textColorR" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/textColorG" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/textColorB" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/textTransp" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/bufferDraw" ), false ); + setCustomProperty( QStringLiteral( "labeling/bufferSize" ), 1 ); + setCustomProperty( QStringLiteral( "labeling/bufferSizeInMapUnits" ), false ); + setCustomProperty( QStringLiteral( "labeling/bufferColorR" ), 255 ); + setCustomProperty( QStringLiteral( "labeling/bufferColorG" ), 255 ); + setCustomProperty( QStringLiteral( "labeling/bufferColorB" ), 255 ); + setCustomProperty( QStringLiteral( "labeling/bufferTransp" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/placement" ), QgsPalLayerSettings::AroundPoint ); + setCustomProperty( QStringLiteral( "labeling/xOffset" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/yOffset" ), 0 ); + setCustomProperty( QStringLiteral( "labeling/labelOffsetInMapUnits" ), false ); + setCustomProperty( QStringLiteral( "labeling/angleOffset" ), 0 ); // label attribute QString labelAttribute = propertyNameElem.text(); - setCustomProperty( "labeling/fieldName", labelAttribute ); - setCustomProperty( "labeling/isExpression", false ); + setCustomProperty( QStringLiteral( "labeling/fieldName" ), labelAttribute ); + setCustomProperty( QStringLiteral( "labeling/isExpression" ), false ); int fieldIndex = mFields.lookupField( labelAttribute ); if ( fieldIndex == -1 ) @@ -3521,7 +3521,7 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) QgsExpression exp( labelAttribute ); if ( !exp.hasEvalError() ) { - setCustomProperty( "labeling/isExpression", true ); + setCustomProperty( QStringLiteral( "labeling/isExpression" ), true ); } else { @@ -3542,130 +3542,130 @@ void QgsVectorLayer::readSldLabeling( const QDomNode& node ) } // Font - QDomElement fontElem = textSymbolizerElem.firstChildElement( "Font" ); + QDomElement fontElem = textSymbolizerElem.firstChildElement( QStringLiteral( "Font" ) ); if ( !fontElem.isNull() ) { QString cssName; QString elemText; - QDomElement cssElem = fontElem.firstChildElement( "CssParameter" ); + QDomElement cssElem = fontElem.firstChildElement( QStringLiteral( "CssParameter" ) ); while ( !cssElem.isNull() ) { - cssName = cssElem.attribute( "name", "not_found" ); - if ( cssName != "not_found" ) + cssName = cssElem.attribute( QStringLiteral( "name" ), QStringLiteral( "not_found" ) ); + if ( cssName != QLatin1String( "not_found" ) ) { elemText = cssElem.text(); - if ( cssName == "font-family" ) + if ( cssName == QLatin1String( "font-family" ) ) { - setCustomProperty( "labeling/fontFamily", elemText ); + setCustomProperty( QStringLiteral( "labeling/fontFamily" ), elemText ); } - else if ( cssName == "font-style" ) + else if ( cssName == QLatin1String( "font-style" ) ) { - setCustomProperty( "labeling/fontItalic", ( elemText == "italic" ) || ( elemText == "Italic" ) ); + setCustomProperty( QStringLiteral( "labeling/fontItalic" ), ( elemText == QLatin1String( "italic" ) ) || ( elemText == QLatin1String( "Italic" ) ) ); } - else if ( cssName == "font-size" ) + else if ( cssName == QLatin1String( "font-size" ) ) { bool ok; int fontSize = elemText.toInt( &ok ); if ( ok ) { - setCustomProperty( "labeling/fontSize", fontSize ); + setCustomProperty( QStringLiteral( "labeling/fontSize" ), fontSize ); } } - else if ( cssName == "font-weight" ) + else if ( cssName == QLatin1String( "font-weight" ) ) { - setCustomProperty( "labeling/fontBold", ( elemText == "bold" ) || ( elemText == "Bold" ) ); + setCustomProperty( QStringLiteral( "labeling/fontBold" ), ( elemText == QLatin1String( "bold" ) ) || ( elemText == QLatin1String( "Bold" ) ) ); } - else if ( cssName == "font-underline" ) + else if ( cssName == QLatin1String( "font-underline" ) ) { - setCustomProperty( "labeling/fontUnderline", ( elemText == "underline" ) || ( elemText == "Underline" ) ); + setCustomProperty( QStringLiteral( "labeling/fontUnderline" ), ( elemText == QLatin1String( "underline" ) ) || ( elemText == QLatin1String( "Underline" ) ) ); } } - cssElem = cssElem.nextSiblingElement( "CssParameter" ); + cssElem = cssElem.nextSiblingElement( QStringLiteral( "CssParameter" ) ); } } // Fill - QColor textColor = QgsOgcUtils::colorFromOgcFill( textSymbolizerElem.firstChildElement( "Fill" ) ); + QColor textColor = QgsOgcUtils::colorFromOgcFill( textSymbolizerElem.firstChildElement( QStringLiteral( "Fill" ) ) ); if ( textColor.isValid() ) { - setCustomProperty( "labeling/textColorR", textColor.red() ); - setCustomProperty( "labeling/textColorG", textColor.green() ); - setCustomProperty( "labeling/textColorB", textColor.blue() ); - setCustomProperty( "labeling/textTransp", 100 - static_cast< int >( 100 * textColor.alphaF() ) ); + setCustomProperty( QStringLiteral( "labeling/textColorR" ), textColor.red() ); + setCustomProperty( QStringLiteral( "labeling/textColorG" ), textColor.green() ); + setCustomProperty( QStringLiteral( "labeling/textColorB" ), textColor.blue() ); + setCustomProperty( QStringLiteral( "labeling/textTransp" ), 100 - static_cast< int >( 100 * textColor.alphaF() ) ); } // Halo - QDomElement haloElem = textSymbolizerElem.firstChildElement( "Halo" ); + QDomElement haloElem = textSymbolizerElem.firstChildElement( QStringLiteral( "Halo" ) ); if ( !haloElem.isNull() ) { - setCustomProperty( "labeling/bufferDraw", true ); - setCustomProperty( "labeling/bufferSize", 1 ); + setCustomProperty( QStringLiteral( "labeling/bufferDraw" ), true ); + setCustomProperty( QStringLiteral( "labeling/bufferSize" ), 1 ); - QDomElement radiusElem = haloElem.firstChildElement( "Radius" ); + QDomElement radiusElem = haloElem.firstChildElement( QStringLiteral( "Radius" ) ); if ( !radiusElem.isNull() ) { bool ok; double bufferSize = radiusElem.text().toDouble( &ok ); if ( ok ) { - setCustomProperty( "labeling/bufferSize", bufferSize ); + setCustomProperty( QStringLiteral( "labeling/bufferSize" ), bufferSize ); } } - QColor bufferColor = QgsOgcUtils::colorFromOgcFill( haloElem.firstChildElement( "Fill" ) ); + QColor bufferColor = QgsOgcUtils::colorFromOgcFill( haloElem.firstChildElement( QStringLiteral( "Fill" ) ) ); if ( bufferColor.isValid() ) { - setCustomProperty( "labeling/bufferColorR", bufferColor.red() ); - setCustomProperty( "labeling/bufferColorG", bufferColor.green() ); - setCustomProperty( "labeling/bufferColorB", bufferColor.blue() ); - setCustomProperty( "labeling/bufferTransp", 100 - static_cast< int >( 100 * bufferColor.alphaF() ) ); + setCustomProperty( QStringLiteral( "labeling/bufferColorR" ), bufferColor.red() ); + setCustomProperty( QStringLiteral( "labeling/bufferColorG" ), bufferColor.green() ); + setCustomProperty( QStringLiteral( "labeling/bufferColorB" ), bufferColor.blue() ); + setCustomProperty( QStringLiteral( "labeling/bufferTransp" ), 100 - static_cast< int >( 100 * bufferColor.alphaF() ) ); } } // LabelPlacement - QDomElement labelPlacementElem = textSymbolizerElem.firstChildElement( "LabelPlacement" ); + QDomElement labelPlacementElem = textSymbolizerElem.firstChildElement( QStringLiteral( "LabelPlacement" ) ); if ( !labelPlacementElem.isNull() ) { // PointPlacement - QDomElement pointPlacementElem = labelPlacementElem.firstChildElement( "PointPlacement" ); + QDomElement pointPlacementElem = labelPlacementElem.firstChildElement( QStringLiteral( "PointPlacement" ) ); if ( !pointPlacementElem.isNull() ) { - setCustomProperty( "labeling/placement", QgsPalLayerSettings::OverPoint ); + setCustomProperty( QStringLiteral( "labeling/placement" ), QgsPalLayerSettings::OverPoint ); - QDomElement displacementElem = pointPlacementElem.firstChildElement( "Displacement" ); + QDomElement displacementElem = pointPlacementElem.firstChildElement( QStringLiteral( "Displacement" ) ); if ( !displacementElem.isNull() ) { - QDomElement displacementXElem = displacementElem.firstChildElement( "DisplacementX" ); + QDomElement displacementXElem = displacementElem.firstChildElement( QStringLiteral( "DisplacementX" ) ); if ( !displacementXElem.isNull() ) { bool ok; double xOffset = displacementXElem.text().toDouble( &ok ); if ( ok ) { - setCustomProperty( "labeling/xOffset", xOffset ); + setCustomProperty( QStringLiteral( "labeling/xOffset" ), xOffset ); } } - QDomElement displacementYElem = displacementElem.firstChildElement( "DisplacementY" ); + QDomElement displacementYElem = displacementElem.firstChildElement( QStringLiteral( "DisplacementY" ) ); if ( !displacementYElem.isNull() ) { bool ok; double yOffset = displacementYElem.text().toDouble( &ok ); if ( ok ) { - setCustomProperty( "labeling/yOffset", yOffset ); + setCustomProperty( QStringLiteral( "labeling/yOffset" ), yOffset ); } } } - QDomElement rotationElem = pointPlacementElem.firstChildElement( "Rotation" ); + QDomElement rotationElem = pointPlacementElem.firstChildElement( QStringLiteral( "Rotation" ) ); if ( !rotationElem.isNull() ) { bool ok; double rotation = rotationElem.text().toDouble( &ok ); if ( ok ) { - setCustomProperty( "labeling/angleOffset", rotation ); + setCustomProperty( QStringLiteral( "labeling/angleOffset" ), rotation ); } } } @@ -3738,43 +3738,43 @@ void QgsVectorLayer::setDiagramLayerSettings( const QgsDiagramLayerSettings& s ) QString QgsVectorLayer::metadata() const { - QString myMetadata = "<html><body>"; + QString myMetadata = QStringLiteral( "<html><body>" ); //------------- - myMetadata += "<p class=\"subheaderglossy\">"; + myMetadata += QLatin1String( "<p class=\"subheaderglossy\">" ); myMetadata += tr( "General" ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); // data comment if ( !( dataComment().isEmpty() ) ) { myMetadata += "<p class=\"glossy\">" + tr( "Layer comment" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += dataComment(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); } //storage type myMetadata += "<p class=\"glossy\">" + tr( "Storage type of this layer" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += storageType(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); if ( dataProvider() ) { //provider description myMetadata += "<p class=\"glossy\">" + tr( "Description of this provider" ) + "</p>\n"; - myMetadata += "<p>"; - myMetadata += dataProvider()->description().replace( '\n', "<br>" ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "<p>" ); + myMetadata += dataProvider()->description().replace( '\n', QLatin1String( "<br>" ) ); + myMetadata += QLatin1String( "</p>\n" ); } // data source myMetadata += "<p class=\"glossy\">" + tr( "Source for this layer" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += publicSource(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //geom type @@ -3789,43 +3789,43 @@ QString QgsVectorLayer::metadata() const QString typeString( QgsWkbTypes::geometryDisplayString( geometryType() ) ); myMetadata += "<p class=\"glossy\">" + tr( "Geometry type of the features in this layer" ) + "</p>\n"; - myMetadata += QString( "<p>%1</p>\n" ).arg( typeString ); + myMetadata += QStringLiteral( "<p>%1</p>\n" ).arg( typeString ); } QgsAttributeList pkAttrList = pkAttributeList(); if ( !pkAttrList.isEmpty() ) { myMetadata += "<p class=\"glossy\">" + tr( "Primary key attributes" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); Q_FOREACH ( int idx, pkAttrList ) { myMetadata += fields().at( idx ).name() + ' '; } - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); } //feature count myMetadata += "<p class=\"glossy\">" + tr( "The number of features in this layer" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += QString::number( featureCount() ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //capabilities myMetadata += "<p class=\"glossy\">" + tr( "Capabilities of this layer" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += capabilitiesString(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //------------- QgsRectangle myExtent = extent(); - myMetadata += "<p class=\"subheaderglossy\">"; + myMetadata += QLatin1String( "<p class=\"subheaderglossy\">" ); myMetadata += tr( "Extents" ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //extents in layer cs TODO...maybe make a little nested table to improve layout... myMetadata += "<p class=\"glossy\">" + tr( "In layer spatial reference system units" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); // Try to be a bit clever over what number format we use for the // extents. Some people don't like it using scientific notation when the // numbers get large, but for small numbers this is the more practical @@ -3842,35 +3842,35 @@ QString QgsVectorLayer::metadata() const double changeoverValue = 99999; // The 'largest' 5 digit number if ( qAbs( myExtent.xMinimum() ) > changeoverValue ) { - xMin = QString( "%1" ).arg( myExtent.xMinimum(), 0, 'f', 2 ); + xMin = QStringLiteral( "%1" ).arg( myExtent.xMinimum(), 0, 'f', 2 ); } else { - xMin = QString( "%1" ).arg( myExtent.xMinimum() ); + xMin = QStringLiteral( "%1" ).arg( myExtent.xMinimum() ); } if ( qAbs( myExtent.yMinimum() ) > changeoverValue ) { - yMin = QString( "%1" ).arg( myExtent.yMinimum(), 0, 'f', 2 ); + yMin = QStringLiteral( "%1" ).arg( myExtent.yMinimum(), 0, 'f', 2 ); } else { - yMin = QString( "%1" ).arg( myExtent.yMinimum() ); + yMin = QStringLiteral( "%1" ).arg( myExtent.yMinimum() ); } if ( qAbs( myExtent.xMaximum() ) > changeoverValue ) { - xMax = QString( "%1" ).arg( myExtent.xMaximum(), 0, 'f', 2 ); + xMax = QStringLiteral( "%1" ).arg( myExtent.xMaximum(), 0, 'f', 2 ); } else { - xMax = QString( "%1" ).arg( myExtent.xMaximum() ); + xMax = QStringLiteral( "%1" ).arg( myExtent.xMaximum() ); } if ( qAbs( myExtent.yMaximum() ) > changeoverValue ) { - yMax = QString( "%1" ).arg( myExtent.yMaximum(), 0, 'f', 2 ); + yMax = QStringLiteral( "%1" ).arg( myExtent.yMaximum(), 0, 'f', 2 ); } else { - yMax = QString( "%1" ).arg( myExtent.yMaximum() ); + yMax = QStringLiteral( "%1" ).arg( myExtent.yMaximum() ); } myMetadata += tr( "xMin,yMin %1,%2 : xMax,yMax %3,%4" ) @@ -3881,7 +3881,7 @@ QString QgsVectorLayer::metadata() const myMetadata += tr( "unknown extent" ); } - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //extents in project cs @@ -3904,9 +3904,9 @@ QString QgsVectorLayer::metadata() const // Display layer spatial ref system // myMetadata += "<p class=\"glossy\">" + tr( "Layer Spatial Reference System" ) + "</p>\n"; - myMetadata += "<p>"; - myMetadata += crs().toProj4().replace( '"', " \"" ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "<p>" ); + myMetadata += crs().toProj4().replace( '"', QLatin1String( " \"" ) ); + myMetadata += QLatin1String( "</p>\n" ); // // Display project (output) spatial ref system @@ -3926,9 +3926,9 @@ QString QgsVectorLayer::metadata() const QgsDebugMsg( cse.what() ); myMetadata += "<p class=\"glossy\">" + tr( "In project spatial reference system units" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "(Invalid transformation of layer extents)" ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); } @@ -3984,7 +3984,7 @@ QString QgsVectorLayer::metadata() const myMetadata += "</table>"; //end of nested table #endif - myMetadata += "</body></html>"; + myMetadata += QLatin1String( "</body></html>" ); return myMetadata; } @@ -4033,7 +4033,7 @@ int QgsVectorLayer::listStylesInDatabase( QStringList &ids, QStringList &names, if ( !listStylesExternalMethod ) { delete myLib; - msgError = QObject::tr( "Provider %1 has no %2 method" ).arg( mProviderKey, "listStyles" ); + msgError = QObject::tr( "Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral( "listStyles" ) ); return -1; } @@ -4054,7 +4054,7 @@ QString QgsVectorLayer::getStyleFromDatabase( const QString& styleId, QString &m if ( !getStyleByIdMethod ) { delete myLib; - msgError = QObject::tr( "Provider %1 has no %2 method" ).arg( mProviderKey, "getStyleById" ); + msgError = QObject::tr( "Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral( "getStyleById" ) ); return QObject::tr( "" ); } @@ -4079,7 +4079,7 @@ void QgsVectorLayer::saveStyleToDatabase( const QString& name, const QString& de if ( !saveStyleExternalMethod ) { delete myLib; - msgError = QObject::tr( "Provider %1 has no %2 method" ).arg( mProviderKey, "saveStyle" ); + msgError = QObject::tr( "Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral( "saveStyle" ) ); return; } @@ -4125,7 +4125,7 @@ QString QgsVectorLayer::loadNamedStyle( const QString &theURI, bool &theResultFl qml = loadStyleExternalMethod( mDataSource, errorMsg ); if ( !qml.isEmpty() ) { - QDomDocument myDocument( "qgis" ); + QDomDocument myDocument( QStringLiteral( "qgis" ) ); myDocument.setContent( qml ); theResultFlag = importNamedStyle( myDocument, errorMsg ); return QObject::tr( "Loaded from Provider" ); diff --git a/src/core/qgsvectorlayereditbuffer.cpp b/src/core/qgsvectorlayereditbuffer.cpp index c424545af714..72c9fb8072a1 100644 --- a/src/core/qgsvectorlayereditbuffer.cpp +++ b/src/core/qgsvectorlayereditbuffer.cpp @@ -438,14 +438,14 @@ bool QgsVectorLayerEditBuffer::commitChanges( QStringList& commitErrors ) << tr( "ERROR: field with index %1 is not the same!" ).arg( i ) << tr( "Provider: %1" ).arg( L->providerType() ) << tr( "Storage: %1" ).arg( L->storageType() ) - << QString( "%1: name=%2 type=%3 typeName=%4 len=%5 precision=%6" ) + << QStringLiteral( "%1: name=%2 type=%3 typeName=%4 len=%5 precision=%6" ) .arg( tr( "expected field" ), oldField.name(), QVariant::typeToName( oldField.type() ), oldField.typeName() ) .arg( oldField.length() ) .arg( oldField.precision() ) - << QString( "%1: name=%2 type=%3 typeName=%4 len=%5 precision=%6" ) + << QStringLiteral( "%1: name=%2 type=%3 typeName=%4 len=%5 precision=%6" ) .arg( tr( "retrieved field" ), newField.name(), QVariant::typeToName( newField.type() ), @@ -619,7 +619,7 @@ bool QgsVectorLayerEditBuffer::commitChanges( QStringList& commitErrors ) commitErrors << tr( "\n Provider errors:" ); Q_FOREACH ( QString e, provider->errors() ) { - commitErrors << " " + e.replace( '\n', "\n " ); + commitErrors << " " + e.replace( '\n', QLatin1String( "\n " ) ); } provider->clearErrors(); } diff --git a/src/core/qgsvectorlayerfeatureiterator.cpp b/src/core/qgsvectorlayerfeatureiterator.cpp index 5014532951f5..b16c84e0a4f3 100644 --- a/src/core/qgsvectorlayerfeatureiterator.cpp +++ b/src/core/qgsvectorlayerfeatureiterator.cpp @@ -793,11 +793,11 @@ void QgsVectorLayerFeatureIterator::FetchJoinInfo::addJoinedAttributesDirect( Qg else joinFieldName = joinInfo->joinFieldName; - subsetString.append( QString( "\"%1\"" ).arg( joinFieldName ) ); + subsetString.append( QStringLiteral( "\"%1\"" ).arg( joinFieldName ) ); if ( joinValue.isNull() ) { - subsetString += " IS NULL"; + subsetString += QLatin1String( " IS NULL" ); } else { @@ -811,7 +811,7 @@ void QgsVectorLayerFeatureIterator::FetchJoinInfo::addJoinedAttributesDirect( Qg default: case QVariant::String: - v.replace( '\'', "''" ); + v.replace( '\'', QLatin1String( "''" ) ); v.prepend( '\'' ).append( '\'' ); break; } diff --git a/src/core/qgsvectorlayerimport.cpp b/src/core/qgsvectorlayerimport.cpp index 0f6f0376a5db..8e536dc64d04 100644 --- a/src/core/qgsvectorlayerimport.cpp +++ b/src/core/qgsvectorlayerimport.cpp @@ -76,7 +76,7 @@ QgsVectorLayerImport::QgsVectorLayerImport( const QString &uri, { delete myLib; mError = ErrProviderUnsupportedFeature; - mErrorMessage = QObject::tr( "Provider %1 has no %2 method" ).arg( providerKey, "createEmptyLayer" ); + mErrorMessage = QObject::tr( "Provider %1 has no %2 method" ).arg( providerKey, QStringLiteral( "createEmptyLayer" ) ); return; } @@ -180,7 +180,7 @@ bool QgsVectorLayerImport::flushBuffer() mErrorMessage = QObject::tr( "Creation error for features from #%1 to #%2. Provider errors was: \n%3" ) .arg( mFeatureBuffer.first().id() ) .arg( mFeatureBuffer.last().id() ) - .arg( errors.join( "\n" ) ); + .arg( errors.join( QStringLiteral( "\n" ) ) ); mError = ErrFeatureWriteFailed; mErrorCount += mFeatureBuffer.count(); @@ -241,15 +241,15 @@ QgsVectorLayerImport::importLayer( QgsVectorLayer* layer, bool forceSinglePartGeom = false; if ( options ) { - overwrite = options->take( "overwrite" ).toBool(); - forceSinglePartGeom = options->take( "forceSinglePartGeometryType" ).toBool(); + overwrite = options->take( QStringLiteral( "overwrite" ) ).toBool(); + forceSinglePartGeom = options->take( QStringLiteral( "forceSinglePartGeometryType" ) ).toBool(); } QgsFields fields = skipAttributeCreation ? QgsFields() : layer->fields(); QgsWkbTypes::Type wkbType = layer->wkbType(); // Special handling for Shapefiles - if ( layer->providerType() == "ogr" && layer->storageType() == "ESRI Shapefile" ) + if ( layer->providerType() == QLatin1String( "ogr" ) && layer->storageType() == QLatin1String( "ESRI Shapefile" ) ) { // convert field names to lowercase for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) diff --git a/src/core/qgsvectorlayerjoinbuffer.cpp b/src/core/qgsvectorlayerjoinbuffer.cpp index aa3ca05b5ded..e9b734493e88 100644 --- a/src/core/qgsvectorlayerjoinbuffer.cpp +++ b/src/core/qgsvectorlayerjoinbuffer.cpp @@ -282,33 +282,33 @@ void QgsVectorLayerJoinBuffer::createJoinCaches() void QgsVectorLayerJoinBuffer::writeXml( QDomNode& layer_node, QDomDocument& document ) const { - QDomElement vectorJoinsElem = document.createElement( "vectorjoins" ); + QDomElement vectorJoinsElem = document.createElement( QStringLiteral( "vectorjoins" ) ); layer_node.appendChild( vectorJoinsElem ); QList< QgsVectorJoinInfo >::const_iterator joinIt = mVectorJoins.constBegin(); for ( ; joinIt != mVectorJoins.constEnd(); ++joinIt ) { - QDomElement joinElem = document.createElement( "join" ); + QDomElement joinElem = document.createElement( QStringLiteral( "join" ) ); if ( joinIt->targetFieldName.isEmpty() ) - joinElem.setAttribute( "targetField", joinIt->targetFieldIndex ); //for compatibility with 1.x + joinElem.setAttribute( QStringLiteral( "targetField" ), joinIt->targetFieldIndex ); //for compatibility with 1.x else - joinElem.setAttribute( "targetFieldName", joinIt->targetFieldName ); + joinElem.setAttribute( QStringLiteral( "targetFieldName" ), joinIt->targetFieldName ); - joinElem.setAttribute( "joinLayerId", joinIt->joinLayerId ); + joinElem.setAttribute( QStringLiteral( "joinLayerId" ), joinIt->joinLayerId ); if ( joinIt->joinFieldName.isEmpty() ) - joinElem.setAttribute( "joinField", joinIt->joinFieldIndex ); //for compatibility with 1.x + joinElem.setAttribute( QStringLiteral( "joinField" ), joinIt->joinFieldIndex ); //for compatibility with 1.x else - joinElem.setAttribute( "joinFieldName", joinIt->joinFieldName ); + joinElem.setAttribute( QStringLiteral( "joinFieldName" ), joinIt->joinFieldName ); - joinElem.setAttribute( "memoryCache", joinIt->memoryCache ); + joinElem.setAttribute( QStringLiteral( "memoryCache" ), joinIt->memoryCache ); if ( joinIt->joinFieldNamesSubset() ) { - QDomElement subsetElem = document.createElement( "joinFieldsSubset" ); + QDomElement subsetElem = document.createElement( QStringLiteral( "joinFieldsSubset" ) ); Q_FOREACH ( const QString& fieldName, *joinIt->joinFieldNamesSubset() ) { - QDomElement fieldElem = document.createElement( "field" ); - fieldElem.setAttribute( "name", fieldName ); + QDomElement fieldElem = document.createElement( QStringLiteral( "field" ) ); + fieldElem.setAttribute( QStringLiteral( "name" ), fieldName ); subsetElem.appendChild( fieldElem ); } @@ -317,8 +317,8 @@ void QgsVectorLayerJoinBuffer::writeXml( QDomNode& layer_node, QDomDocument& doc if ( !joinIt->prefix.isNull() ) { - joinElem.setAttribute( "customPrefix", joinIt->prefix ); - joinElem.setAttribute( "hasCustomPrefix", 1 ); + joinElem.setAttribute( QStringLiteral( "customPrefix" ), joinIt->prefix ); + joinElem.setAttribute( QStringLiteral( "hasCustomPrefix" ), 1 ); } vectorJoinsElem.appendChild( joinElem ); @@ -328,36 +328,36 @@ void QgsVectorLayerJoinBuffer::writeXml( QDomNode& layer_node, QDomDocument& doc void QgsVectorLayerJoinBuffer::readXml( const QDomNode& layer_node ) { mVectorJoins.clear(); - QDomElement vectorJoinsElem = layer_node.firstChildElement( "vectorjoins" ); + QDomElement vectorJoinsElem = layer_node.firstChildElement( QStringLiteral( "vectorjoins" ) ); if ( !vectorJoinsElem.isNull() ) { - QDomNodeList joinList = vectorJoinsElem.elementsByTagName( "join" ); + QDomNodeList joinList = vectorJoinsElem.elementsByTagName( QStringLiteral( "join" ) ); for ( int i = 0; i < joinList.size(); ++i ) { QDomElement infoElem = joinList.at( i ).toElement(); QgsVectorJoinInfo info; - info.joinFieldName = infoElem.attribute( "joinFieldName" ); - info.joinLayerId = infoElem.attribute( "joinLayerId" ); - info.targetFieldName = infoElem.attribute( "targetFieldName" ); - info.memoryCache = infoElem.attribute( "memoryCache" ).toInt(); + info.joinFieldName = infoElem.attribute( QStringLiteral( "joinFieldName" ) ); + info.joinLayerId = infoElem.attribute( QStringLiteral( "joinLayerId" ) ); + info.targetFieldName = infoElem.attribute( QStringLiteral( "targetFieldName" ) ); + info.memoryCache = infoElem.attribute( QStringLiteral( "memoryCache" ) ).toInt(); info.cacheDirty = true; - info.joinFieldIndex = infoElem.attribute( "joinField" ).toInt(); //for compatibility with 1.x - info.targetFieldIndex = infoElem.attribute( "targetField" ).toInt(); //for compatibility with 1.x + info.joinFieldIndex = infoElem.attribute( QStringLiteral( "joinField" ) ).toInt(); //for compatibility with 1.x + info.targetFieldIndex = infoElem.attribute( QStringLiteral( "targetField" ) ).toInt(); //for compatibility with 1.x - QDomElement subsetElem = infoElem.firstChildElement( "joinFieldsSubset" ); + QDomElement subsetElem = infoElem.firstChildElement( QStringLiteral( "joinFieldsSubset" ) ); if ( !subsetElem.isNull() ) { QStringList* fieldNames = new QStringList; - QDomNodeList fieldNodes = infoElem.elementsByTagName( "field" ); + QDomNodeList fieldNodes = infoElem.elementsByTagName( QStringLiteral( "field" ) ); fieldNames->reserve( fieldNodes.count() ); for ( int i = 0; i < fieldNodes.count(); ++i ) - *fieldNames << fieldNodes.at( i ).toElement().attribute( "name" ); + *fieldNames << fieldNodes.at( i ).toElement().attribute( QStringLiteral( "name" ) ); info.setJoinFieldNamesSubset( fieldNames ); } - if ( infoElem.attribute( "hasCustomPrefix" ).toInt() ) - info.prefix = infoElem.attribute( "customPrefix" ); + if ( infoElem.attribute( QStringLiteral( "hasCustomPrefix" ) ).toInt() ) + info.prefix = infoElem.attribute( QStringLiteral( "customPrefix" ) ); else info.prefix = QString::null; diff --git a/src/core/qgsvectorlayerlabeling.cpp b/src/core/qgsvectorlayerlabeling.cpp index cb78abc7e51b..7664137c7ec2 100644 --- a/src/core/qgsvectorlayerlabeling.cpp +++ b/src/core/qgsvectorlayerlabeling.cpp @@ -25,7 +25,7 @@ QgsAbstractVectorLayerLabeling::~QgsAbstractVectorLayerLabeling() QgsAbstractVectorLayerLabeling* QgsAbstractVectorLayerLabeling::create( const QDomElement& element ) { - if ( element.attribute( "type" ) == "rule-based" ) + if ( element.attribute( QStringLiteral( "type" ) ) == QLatin1String( "rule-based" ) ) { return QgsRuleBasedLabeling::create( element ); } @@ -38,7 +38,7 @@ QgsAbstractVectorLayerLabeling* QgsAbstractVectorLayerLabeling::create( const QD QgsVectorLayerLabelProvider* QgsVectorLayerSimpleLabeling::provider( QgsVectorLayer* layer ) const { - if ( layer->customProperty( "labeling" ).toString() == QLatin1String( "pal" ) && layer->labelsEnabled() ) + if ( layer->customProperty( QStringLiteral( "labeling" ) ).toString() == QLatin1String( "pal" ) && layer->labelsEnabled() ) return new QgsVectorLayerLabelProvider( layer, QString(), false ); return nullptr; @@ -46,14 +46,14 @@ QgsVectorLayerLabelProvider* QgsVectorLayerSimpleLabeling::provider( QgsVectorLa QString QgsVectorLayerSimpleLabeling::type() const { - return "simple"; + return QStringLiteral( "simple" ); } QDomElement QgsVectorLayerSimpleLabeling::save( QDomDocument& doc ) const { // all configuration is kept in layer custom properties (for compatibility) - QDomElement elem = doc.createElement( "labeling" ); - elem.setAttribute( "type", "simple" ); + QDomElement elem = doc.createElement( QStringLiteral( "labeling" ) ); + elem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "simple" ) ); return elem; } diff --git a/src/core/qgsvectorlayerlabelprovider.cpp b/src/core/qgsvectorlayerlabelprovider.cpp index 0bf77029d78c..98d1494c6a83 100644 --- a/src/core/qgsvectorlayerlabelprovider.cpp +++ b/src/core/qgsvectorlayerlabelprovider.cpp @@ -599,12 +599,12 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition* label, Q if ( tmpLyr.placeDirectionSymbol == QgsPalLayerSettings::SymbolAbove ) { prependSymb = true; - symb = symb + QLatin1String( "\n" ); + symb = symb + QStringLiteral( "\n" ); } else if ( tmpLyr.placeDirectionSymbol == QgsPalLayerSettings::SymbolBelow ) { prependSymb = false; - symb = QLatin1String( "\n" ) + symb; + symb = QStringLiteral( "\n" ) + symb; } if ( prependSymb ) diff --git a/src/core/qgsvectorlayerrenderer.cpp b/src/core/qgsvectorlayerrenderer.cpp index 9aec1cf58cba..fa36b2307c2f 100644 --- a/src/core/qgsvectorlayerrenderer.cpp +++ b/src/core/qgsvectorlayerrenderer.cpp @@ -71,14 +71,14 @@ QgsVectorLayerRenderer::QgsVectorLayerRenderer( QgsVectorLayer* layer, QgsRender mSimplifyGeometry = layer->simplifyDrawingCanbeApplied( mContext, QgsVectorSimplifyMethod::GeometrySimplification ); QSettings settings; - mVertexMarkerOnlyForSelection = settings.value( "/qgis/digitizing/marker_only_for_selected", false ).toBool(); + mVertexMarkerOnlyForSelection = settings.value( QStringLiteral( "/qgis/digitizing/marker_only_for_selected" ), false ).toBool(); - QString markerTypeString = settings.value( "/qgis/digitizing/marker_style", "Cross" ).toString(); - if ( markerTypeString == "Cross" ) + QString markerTypeString = settings.value( QStringLiteral( "/qgis/digitizing/marker_style" ), "Cross" ).toString(); + if ( markerTypeString == QLatin1String( "Cross" ) ) { mVertexMarkerStyle = QgsVectorLayer::Cross; } - else if ( markerTypeString == "SemiTransparentCircle" ) + else if ( markerTypeString == QLatin1String( "SemiTransparentCircle" ) ) { mVertexMarkerStyle = QgsVectorLayer::SemiTransparentCircle; } @@ -87,7 +87,7 @@ QgsVectorLayerRenderer::QgsVectorLayerRenderer( QgsVectorLayer* layer, QgsRender mVertexMarkerStyle = QgsVectorLayer::NoMarker; } - mVertexMarkerSize = settings.value( "/qgis/digitizing/marker_size", 3 ).toInt(); + mVertexMarkerSize = settings.value( QStringLiteral( "/qgis/digitizing/marker_size" ), 3 ).toInt(); if ( !mRenderer ) return; @@ -165,7 +165,7 @@ bool QgsVectorLayerRenderer::render() { featureFilterProvider->filterFeatures( mLayer, featureRequest ); } - if ( !rendererFilter.isEmpty() && rendererFilter != "TRUE" ) + if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) ) { featureRequest.combineFilterExpression( rendererFilter ); } diff --git a/src/core/qgsvirtuallayerdefinition.cpp b/src/core/qgsvirtuallayerdefinition.cpp index 7f178d2d5e40..d7213c993e5a 100644 --- a/src/core/qgsvirtuallayerdefinition.cpp +++ b/src/core/qgsvirtuallayerdefinition.cpp @@ -36,7 +36,7 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) def.setFilePath( url.toLocalFile() ); // regexp for column name - const QString columnNameRx( "[a-zA-Z_\x80-\xFF][a-zA-Z0-9_\x80-\xFF]*" ); + const QString columnNameRx( QStringLiteral( "[a-zA-Z_\x80-\xFF][a-zA-Z0-9_\x80-\xFF]*" ) ); QgsFields fields; @@ -46,7 +46,7 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) { QString key = items.at( i ).first; QString value = items.at( i ).second; - if ( key == "layer_ref" ) + if ( key == QLatin1String( "layer_ref" ) ) { layerIdx++; // layer id, with optional layer_name @@ -55,7 +55,7 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) if ( pos == -1 ) { layerId = value; - vlayerName = QString( "vtab%1" ).arg( layerIdx ); + vlayerName = QStringLiteral( "vtab%1" ).arg( layerIdx ); } else { @@ -65,14 +65,14 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) // add the layer to the list def.addSource( vlayerName, layerId ); } - else if ( key == "layer" ) + else if ( key == QLatin1String( "layer" ) ) { layerIdx++; // syntax: layer=provider:url_encoded_source_URI(:name(:encoding)?)? int pos = value.indexOf( ':' ); if ( pos != -1 ) { - QString providerKey, source, vlayerName, encoding = "UTF-8"; + QString providerKey, source, vlayerName, encoding = QStringLiteral( "UTF-8" ); providerKey = value.left( pos ); int pos2 = value.indexOf( ':', pos + 1 ); @@ -95,13 +95,13 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) else { source = QUrl::fromPercentEncoding( value.mid( pos + 1 ).toUtf8() ); - vlayerName = QString( "vtab%1" ).arg( layerIdx ); + vlayerName = QStringLiteral( "vtab%1" ).arg( layerIdx ); } def.addSource( vlayerName, source, providerKey, encoding ); } } - else if ( key == "geometry" ) + else if ( key == QLatin1String( "geometry" ) ) { // geometry field definition, optional // geometry_column(:wkb_type:srid)? @@ -123,20 +123,20 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) } } } - else if ( key == "nogeometry" ) + else if ( key == QLatin1String( "nogeometry" ) ) { def.setGeometryWkbType( QgsWkbTypes::NoGeometry ); } - else if ( key == "uid" ) + else if ( key == QLatin1String( "uid" ) ) { def.setUid( value ); } - else if ( key == "query" ) + else if ( key == QLatin1String( "query" ) ) { // url encoded query def.setQuery( QUrl::fromPercentEncoding( value.toUtf8() ) ); } - else if ( key == "field" ) + else if ( key == QLatin1String( "field" ) ) { // field_name:type (int, real, text) QRegExp reField( "(" + columnNameRx + "):(int|real|text)" ); @@ -145,15 +145,15 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinition::fromUrl( const QUrl& url ) { QString fieldName( reField.cap( 1 ) ); QString fieldType( reField.cap( 2 ) ); - if ( fieldType == "int" ) + if ( fieldType == QLatin1String( "int" ) ) { fields.append( QgsField( fieldName, QVariant::Int, fieldType ) ); } - else if ( fieldType == "real" ) + else if ( fieldType == QLatin1String( "real" ) ) { fields.append( QgsField( fieldName, QVariant::Double, fieldType ) ); } - if ( fieldType == "text" ) + if ( fieldType == QLatin1String( "text" ) ) { fields.append( QgsField( fieldName, QVariant::String, fieldType ) ); } @@ -174,9 +174,9 @@ QUrl QgsVirtualLayerDefinition::toUrl() const Q_FOREACH ( const QgsVirtualLayerDefinition::SourceLayer& l, sourceLayers() ) { if ( l.isReferenced() ) - url.addQueryItem( "layer_ref", QString( "%1:%2" ).arg( l.reference(), l.name() ) ); + url.addQueryItem( QStringLiteral( "layer_ref" ), QStringLiteral( "%1:%2" ).arg( l.reference(), l.name() ) ); else - url.addEncodedQueryItem( "layer", QString( "%1:%4:%2:%3" ) // the order is important, since the 4th argument may contain '%2' as well + url.addEncodedQueryItem( "layer", QStringLiteral( "%1:%4:%2:%3" ) // the order is important, since the 4th argument may contain '%2' as well .arg( l.provider(), QString( QUrl::toPercentEncoding( l.name() ) ), l.encoding(), @@ -185,30 +185,30 @@ QUrl QgsVirtualLayerDefinition::toUrl() const if ( !query().isEmpty() ) { - url.addQueryItem( "query", query() ); + url.addQueryItem( QStringLiteral( "query" ), query() ); } if ( !uid().isEmpty() ) - url.addQueryItem( "uid", uid() ); + url.addQueryItem( QStringLiteral( "uid" ), uid() ); if ( geometryWkbType() == QgsWkbTypes::NoGeometry ) - url.addQueryItem( "nogeometry", "" ); + url.addQueryItem( QStringLiteral( "nogeometry" ), QLatin1String( "" ) ); else if ( !geometryField().isEmpty() ) { if ( hasDefinedGeometry() ) - url.addQueryItem( "geometry", QString( "%1:%2:%3" ).arg( geometryField() ). arg( geometryWkbType() ).arg( geometrySrid() ).toUtf8() ); + url.addQueryItem( QStringLiteral( "geometry" ), QStringLiteral( "%1:%2:%3" ).arg( geometryField() ). arg( geometryWkbType() ).arg( geometrySrid() ).toUtf8() ); else - url.addQueryItem( "geometry", geometryField() ); + url.addQueryItem( QStringLiteral( "geometry" ), geometryField() ); } Q_FOREACH ( const QgsField& f, fields() ) { if ( f.type() == QVariant::Int ) - url.addQueryItem( "field", f.name() + ":int" ); + url.addQueryItem( QStringLiteral( "field" ), f.name() + ":int" ); else if ( f.type() == QVariant::Double ) - url.addQueryItem( "field", f.name() + ":real" ); + url.addQueryItem( QStringLiteral( "field" ), f.name() + ":real" ); else if ( f.type() == QVariant::String ) - url.addQueryItem( "field", f.name() + ":text" ); + url.addQueryItem( QStringLiteral( "field" ), f.name() + ":text" ); } return url; diff --git a/src/core/qgsvirtuallayerdefinition.h b/src/core/qgsvirtuallayerdefinition.h index af04f5f05df0..e9a4a2eb5653 100644 --- a/src/core/qgsvirtuallayerdefinition.h +++ b/src/core/qgsvirtuallayerdefinition.h @@ -76,7 +76,7 @@ class CORE_EXPORT QgsVirtualLayerDefinition }; //! Constructor with an optional file path - QgsVirtualLayerDefinition( const QString& filePath = "" ); + QgsVirtualLayerDefinition( const QString& filePath = QStringLiteral( "" ) ); //! Constructor to build a definition from a QUrl //! The path part of the URL is extracted as well as the following optional keys: @@ -102,7 +102,7 @@ class CORE_EXPORT QgsVirtualLayerDefinition void addSource( const QString& name, const QString& ref ); //! Add a layer with a source, a provider and an encoding - void addSource( const QString& name, const QString& source, const QString& provider, const QString& encoding = "" ); + void addSource( const QString& name, const QString& source, const QString& provider, const QString& encoding = QStringLiteral( "" ) ); //! List of source layers typedef QList<SourceLayer> SourceLayers; diff --git a/src/core/qgsvirtuallayerdefinitionutils.cpp b/src/core/qgsvirtuallayerdefinitionutils.cpp index 6a559fdfc7f0..5d1d8f12abee 100644 --- a/src/core/qgsvirtuallayerdefinitionutils.cpp +++ b/src/core/qgsvirtuallayerdefinitionutils.cpp @@ -38,9 +38,9 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinitionUtils::fromJoinedLayer( QgsVe else { // find an uid name - QString uid = "uid"; + QString uid = QStringLiteral( "uid" ); while ( fields.lookupField( uid ) != -1 ) - uid += "_"; // add "_" each time this name already exists + uid += QLatin1String( "_" ); // add "_" each time this name already exists // add a column columns << "t.rowid AS " + uid; @@ -55,13 +55,13 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinitionUtils::fromJoinedLayer( QgsVe int joinIdx = 0; Q_FOREACH ( const QgsVectorJoinInfo& join, layer->vectorJoins() ) { - QString joinName = QString( "j%1" ).arg( ++joinIdx ); + QString joinName = QStringLiteral( "j%1" ).arg( ++joinIdx ); QgsVectorLayer* joinedLayer = static_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( join.joinLayerId ) ); if ( !joinedLayer ) continue; QString prefix = join.prefix.isEmpty() ? joinedLayer->name() + "_" : join.prefix; - leftJoins << QString( "LEFT JOIN %1 AS %2 ON t.\"%5\"=%2.\"%3\"" ).arg( join.joinLayerId, joinName, join.joinFieldName, join.targetFieldName ); + leftJoins << QStringLiteral( "LEFT JOIN %1 AS %2 ON t.\"%5\"=%2.\"%3\"" ).arg( join.joinLayerId, joinName, join.joinFieldName, join.targetFieldName ); if ( join.joinFieldNamesSubset() ) { Q_FOREACH ( const QString& f, *join.joinFieldNamesSubset() ) @@ -80,7 +80,7 @@ QgsVirtualLayerDefinition QgsVirtualLayerDefinitionUtils::fromJoinedLayer( QgsVe } } - QString query = "SELECT " + columns.join( ", " ) + " FROM " + layer->id() + " AS t " + leftJoins.join( " " ); + QString query = "SELECT " + columns.join( QStringLiteral( ", " ) ) + " FROM " + layer->id() + " AS t " + leftJoins.join( QStringLiteral( " " ) ); def.setQuery( query ); return def; diff --git a/src/core/qgsxmlutils.cpp b/src/core/qgsxmlutils.cpp index 70f7f455fe84..1b00a7e8cadb 100644 --- a/src/core/qgsxmlutils.cpp +++ b/src/core/qgsxmlutils.cpp @@ -37,10 +37,10 @@ QgsRectangle QgsXmlUtils::readRectangle( const QDomElement& element ) { QgsRectangle aoi; - QDomNode xminNode = element.namedItem( "xmin" ); - QDomNode yminNode = element.namedItem( "ymin" ); - QDomNode xmaxNode = element.namedItem( "xmax" ); - QDomNode ymaxNode = element.namedItem( "ymax" ); + QDomNode xminNode = element.namedItem( QStringLiteral( "xmin" ) ); + QDomNode yminNode = element.namedItem( QStringLiteral( "ymin" ) ); + QDomNode xmaxNode = element.namedItem( QStringLiteral( "xmax" ) ); + QDomNode ymaxNode = element.namedItem( QStringLiteral( "ymax" ) ); QDomElement exElement = xminNode.toElement(); double xmin = exElement.text().toDouble(); @@ -68,19 +68,19 @@ QDomElement QgsXmlUtils::writeMapUnits( QgsUnitTypes::DistanceUnit units, QDomDo QString unitsString = QgsUnitTypes::encodeUnit( units ); // maintain compatibility with old projects if ( units == QgsUnitTypes::DistanceUnknownUnit ) - unitsString = "unknown"; + unitsString = QStringLiteral( "unknown" ); - QDomElement unitsNode = doc.createElement( "units" ); + QDomElement unitsNode = doc.createElement( QStringLiteral( "units" ) ); unitsNode.appendChild( doc.createTextNode( unitsString ) ); return unitsNode; } QDomElement QgsXmlUtils::writeRectangle( const QgsRectangle& rect, QDomDocument& doc ) { - QDomElement xMin = doc.createElement( "xmin" ); - QDomElement yMin = doc.createElement( "ymin" ); - QDomElement xMax = doc.createElement( "xmax" ); - QDomElement yMax = doc.createElement( "ymax" ); + QDomElement xMin = doc.createElement( QStringLiteral( "xmin" ) ); + QDomElement yMin = doc.createElement( QStringLiteral( "ymin" ) ); + QDomElement xMax = doc.createElement( QStringLiteral( "xmax" ) ); + QDomElement yMax = doc.createElement( QStringLiteral( "ymax" ) ); QDomText xMinText = doc.createTextNode( qgsDoubleToString( rect.xMinimum() ) ); QDomText yMinText = doc.createTextNode( qgsDoubleToString( rect.yMinimum() ) ); @@ -92,7 +92,7 @@ QDomElement QgsXmlUtils::writeRectangle( const QgsRectangle& rect, QDomDocument& xMax.appendChild( xMaxText ); yMax.appendChild( yMaxText ); - QDomElement extentNode = doc.createElement( "extent" ); + QDomElement extentNode = doc.createElement( QStringLiteral( "extent" ) ); extentNode.appendChild( xMin ); extentNode.appendChild( yMin ); extentNode.appendChild( xMax ); diff --git a/src/core/raster/qgsbilinearrasterresampler.h b/src/core/raster/qgsbilinearrasterresampler.h index 49f4ebcd5c31..7fbb8f130765 100644 --- a/src/core/raster/qgsbilinearrasterresampler.h +++ b/src/core/raster/qgsbilinearrasterresampler.h @@ -31,7 +31,7 @@ class CORE_EXPORT QgsBilinearRasterResampler: public QgsRasterResampler ~QgsBilinearRasterResampler(); void resample( const QImage& srcImage, QImage& dstImage ) override; - QString type() const override { return "bilinear"; } + QString type() const override { return QStringLiteral( "bilinear" ); } QgsBilinearRasterResampler * clone() const override; }; diff --git a/src/core/raster/qgsbrightnesscontrastfilter.cpp b/src/core/raster/qgsbrightnesscontrastfilter.cpp index d09557d938d9..b01e33bf45f2 100644 --- a/src/core/raster/qgsbrightnesscontrastfilter.cpp +++ b/src/core/raster/qgsbrightnesscontrastfilter.cpp @@ -203,10 +203,10 @@ void QgsBrightnessContrastFilter::writeXml( QDomDocument& doc, QDomElement& pare return; } - QDomElement filterElem = doc.createElement( "brightnesscontrast" ); + QDomElement filterElem = doc.createElement( QStringLiteral( "brightnesscontrast" ) ); - filterElem.setAttribute( "brightness", QString::number( mBrightness ) ); - filterElem.setAttribute( "contrast", QString::number( mContrast ) ); + filterElem.setAttribute( QStringLiteral( "brightness" ), QString::number( mBrightness ) ); + filterElem.setAttribute( QStringLiteral( "contrast" ), QString::number( mContrast ) ); parentElem.appendChild( filterElem ); } @@ -217,6 +217,6 @@ void QgsBrightnessContrastFilter::readXml( const QDomElement& filterElem ) return; } - mBrightness = filterElem.attribute( "brightness", "0" ).toInt(); - mContrast = filterElem.attribute( "contrast", "0" ).toInt(); + mBrightness = filterElem.attribute( QStringLiteral( "brightness" ), QStringLiteral( "0" ) ).toInt(); + mContrast = filterElem.attribute( QStringLiteral( "contrast" ), QStringLiteral( "0" ) ).toInt(); } diff --git a/src/core/raster/qgscolorrampshader.cpp b/src/core/raster/qgscolorrampshader.cpp index bbf996e98f48..be9fb2c6c6f8 100644 --- a/src/core/raster/qgscolorrampshader.cpp +++ b/src/core/raster/qgscolorrampshader.cpp @@ -44,13 +44,13 @@ QString QgsColorRampShader::colorRampTypeAsQString() switch ( mColorRampType ) { case INTERPOLATED: - return QString( "INTERPOLATED" ); + return QStringLiteral( "INTERPOLATED" ); case DISCRETE: - return QString( "DISCRETE" ); + return QStringLiteral( "DISCRETE" ); case EXACT: - return QString( "EXACT" ); + return QStringLiteral( "EXACT" ); } - return QString( "Unknown" ); + return QStringLiteral( "Unknown" ); } void QgsColorRampShader::setColorRampItemList( const QList<QgsColorRampShader::ColorRampItem>& theList ) @@ -68,11 +68,11 @@ void QgsColorRampShader::setColorRampType( QgsColorRampShader::ColorRamp_TYPE th void QgsColorRampShader::setColorRampType( const QString& theType ) { - if ( theType == "INTERPOLATED" ) + if ( theType == QLatin1String( "INTERPOLATED" ) ) { mColorRampType = INTERPOLATED; } - else if ( theType == "DISCRETE" ) + else if ( theType == QLatin1String( "DISCRETE" ) ) { mColorRampType = DISCRETE; } diff --git a/src/core/raster/qgscontrastenhancement.cpp b/src/core/raster/qgscontrastenhancement.cpp index bc2cfcccc5e2..387b0b01a7f6 100644 --- a/src/core/raster/qgscontrastenhancement.cpp +++ b/src/core/raster/qgscontrastenhancement.cpp @@ -361,19 +361,19 @@ void QgsContrastEnhancement::setMinimumValue( double theValue, bool generateTabl void QgsContrastEnhancement::writeXml( QDomDocument& doc, QDomElement& parentElem ) const { //minimum value - QDomElement minElem = doc.createElement( "minValue" ); + QDomElement minElem = doc.createElement( QStringLiteral( "minValue" ) ); QDomText minText = doc.createTextNode( QgsRasterBlock::printValue( mMinimumValue ) ); minElem.appendChild( minText ); parentElem.appendChild( minElem ); //maximum value - QDomElement maxElem = doc.createElement( "maxValue" ); + QDomElement maxElem = doc.createElement( QStringLiteral( "maxValue" ) ); QDomText maxText = doc.createTextNode( QgsRasterBlock::printValue( mMaximumValue ) ); maxElem.appendChild( maxText ); parentElem.appendChild( maxElem ); //algorithm - QDomElement algorithmElem = doc.createElement( "algorithm" ); + QDomElement algorithmElem = doc.createElement( QStringLiteral( "algorithm" ) ); QDomText algorithmText = doc.createTextNode( contrastEnhancementAlgorithmString( mContrastEnhancementAlgorithm ) ); algorithmElem.appendChild( algorithmText ); parentElem.appendChild( algorithmElem ); @@ -381,39 +381,39 @@ void QgsContrastEnhancement::writeXml( QDomDocument& doc, QDomElement& parentEle void QgsContrastEnhancement::readXml( const QDomElement& elem ) { - QDomElement minValueElem = elem.firstChildElement( "minValue" ); + QDomElement minValueElem = elem.firstChildElement( QStringLiteral( "minValue" ) ); if ( !minValueElem.isNull() ) { mMinimumValue = minValueElem.text().toDouble(); } - QDomElement maxValueElem = elem.firstChildElement( "maxValue" ); + QDomElement maxValueElem = elem.firstChildElement( QStringLiteral( "maxValue" ) ); if ( !maxValueElem.isNull() ) { mMaximumValue = maxValueElem.text().toDouble(); } - QDomElement algorithmElem = elem.firstChildElement( "algorithm" ); + QDomElement algorithmElem = elem.firstChildElement( QStringLiteral( "algorithm" ) ); if ( !algorithmElem.isNull() ) { QString algorithmString = algorithmElem.text(); ContrastEnhancementAlgorithm algorithm = NoEnhancement; // old version ( < 19 Apr 2013) was using enum directly -> for backward compatibility - if ( algorithmString == "0" ) + if ( algorithmString == QLatin1String( "0" ) ) { algorithm = NoEnhancement; } - else if ( algorithmString == "1" ) + else if ( algorithmString == QLatin1String( "1" ) ) { algorithm = StretchToMinimumMaximum; } - else if ( algorithmString == "2" ) + else if ( algorithmString == QLatin1String( "2" ) ) { algorithm = StretchAndClipToMinimumMaximum; } - else if ( algorithmString == "3" ) + else if ( algorithmString == QLatin1String( "3" ) ) { algorithm = ClipToMinimumMaximum; } - else if ( algorithmString == "4" ) + else if ( algorithmString == QLatin1String( "4" ) ) { algorithm = UserDefinedEnhancement; } @@ -431,34 +431,34 @@ QString QgsContrastEnhancement::contrastEnhancementAlgorithmString( ContrastEnha switch ( algorithm ) { case NoEnhancement: - return "NoEnhancement"; + return QStringLiteral( "NoEnhancement" ); case StretchToMinimumMaximum: - return "StretchToMinimumMaximum"; + return QStringLiteral( "StretchToMinimumMaximum" ); case StretchAndClipToMinimumMaximum: - return "StretchAndClipToMinimumMaximum"; + return QStringLiteral( "StretchAndClipToMinimumMaximum" ); case ClipToMinimumMaximum: - return "ClipToMinimumMaximum"; + return QStringLiteral( "ClipToMinimumMaximum" ); case UserDefinedEnhancement: - return "UserDefinedEnhancement"; + return QStringLiteral( "UserDefinedEnhancement" ); } - return "NoEnhancement"; + return QStringLiteral( "NoEnhancement" ); } QgsContrastEnhancement::ContrastEnhancementAlgorithm QgsContrastEnhancement::contrastEnhancementAlgorithmFromString( const QString& contrastEnhancementString ) { - if ( contrastEnhancementString == "StretchToMinimumMaximum" ) + if ( contrastEnhancementString == QLatin1String( "StretchToMinimumMaximum" ) ) { return StretchToMinimumMaximum; } - else if ( contrastEnhancementString == "StretchAndClipToMinimumMaximum" ) + else if ( contrastEnhancementString == QLatin1String( "StretchAndClipToMinimumMaximum" ) ) { return StretchAndClipToMinimumMaximum; } - else if ( contrastEnhancementString == "ClipToMinimumMaximum" ) + else if ( contrastEnhancementString == QLatin1String( "ClipToMinimumMaximum" ) ) { return ClipToMinimumMaximum; } - else if ( contrastEnhancementString == "UserDefinedEnhancement" ) + else if ( contrastEnhancementString == QLatin1String( "UserDefinedEnhancement" ) ) { return UserDefinedEnhancement; } diff --git a/src/core/raster/qgscubicrasterresampler.h b/src/core/raster/qgscubicrasterresampler.h index c37e2a49f232..8b9e1bacda72 100644 --- a/src/core/raster/qgscubicrasterresampler.h +++ b/src/core/raster/qgscubicrasterresampler.h @@ -31,7 +31,7 @@ class CORE_EXPORT QgsCubicRasterResampler: public QgsRasterResampler ~QgsCubicRasterResampler(); QgsCubicRasterResampler * clone() const override; void resample( const QImage& srcImage, QImage& dstImage ) override; - QString type() const override { return "cubic"; } + QString type() const override { return QStringLiteral( "cubic" ); } private: static void xDerivativeMatrix( int nCols, int nRows, double* matrix, const int* colorMatrix ); diff --git a/src/core/raster/qgshillshaderenderer.cpp b/src/core/raster/qgshillshaderenderer.cpp index 7aaeeb39d81f..da9462f41136 100644 --- a/src/core/raster/qgshillshaderenderer.cpp +++ b/src/core/raster/qgshillshaderenderer.cpp @@ -25,7 +25,7 @@ QgsHillshadeRenderer::QgsHillshadeRenderer( QgsRasterInterface *input, int band, double lightAzimuth, double lightAngle ): - QgsRasterRenderer( input, "hillshade" ) + QgsRasterRenderer( input, QStringLiteral( "hillshade" ) ) , mBand( band ) , mZFactor( 1 ) , mLightAngle( lightAngle ) @@ -52,11 +52,11 @@ QgsRasterRenderer *QgsHillshadeRenderer::create( const QDomElement &elem, QgsRas return nullptr; } - int band = elem.attribute( "band", "0" ).toInt(); - double azimuth = elem.attribute( "azimuth", "315" ).toDouble(); - double angle = elem.attribute( "angle", "45" ).toDouble(); - double zFactor = elem.attribute( "zfactor", "1" ).toDouble(); - bool multiDirectional = elem.attribute( "multidirection", "0" ).toInt(); + int band = elem.attribute( QStringLiteral( "band" ), QStringLiteral( "0" ) ).toInt(); + double azimuth = elem.attribute( QStringLiteral( "azimuth" ), QStringLiteral( "315" ) ).toDouble(); + double angle = elem.attribute( QStringLiteral( "angle" ), QStringLiteral( "45" ) ).toDouble(); + double zFactor = elem.attribute( QStringLiteral( "zfactor" ), QStringLiteral( "1" ) ).toDouble(); + bool multiDirectional = elem.attribute( QStringLiteral( "multidirection" ), QStringLiteral( "0" ) ).toInt(); QgsHillshadeRenderer* r = new QgsHillshadeRenderer( input, band, azimuth , angle ); r->readXml( elem ); @@ -72,14 +72,14 @@ void QgsHillshadeRenderer::writeXml( QDomDocument &doc, QDomElement &parentElem return; } - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); _writeXml( doc, rasterRendererElem ); - rasterRendererElem.setAttribute( "band", mBand ); - rasterRendererElem.setAttribute( "azimuth", QString::number( mLightAzimuth ) ); - rasterRendererElem.setAttribute( "angle", QString::number( mLightAngle ) ); - rasterRendererElem.setAttribute( "zfactor", QString::number( mZFactor ) ); - rasterRendererElem.setAttribute( "multidirection", QString::number( mMultiDirectional ) ); + rasterRendererElem.setAttribute( QStringLiteral( "band" ), mBand ); + rasterRendererElem.setAttribute( QStringLiteral( "azimuth" ), QString::number( mLightAzimuth ) ); + rasterRendererElem.setAttribute( QStringLiteral( "angle" ), QString::number( mLightAngle ) ); + rasterRendererElem.setAttribute( QStringLiteral( "zfactor" ), QString::number( mZFactor ) ); + rasterRendererElem.setAttribute( QStringLiteral( "multidirection" ), QString::number( mMultiDirectional ) ); parentElem.appendChild( rasterRendererElem ); } diff --git a/src/core/raster/qgshuesaturationfilter.cpp b/src/core/raster/qgshuesaturationfilter.cpp index 300c1496c762..4d7f0f0d4eec 100644 --- a/src/core/raster/qgshuesaturationfilter.cpp +++ b/src/core/raster/qgshuesaturationfilter.cpp @@ -350,15 +350,15 @@ void QgsHueSaturationFilter::writeXml( QDomDocument& doc, QDomElement& parentEle return; } - QDomElement filterElem = doc.createElement( "huesaturation" ); + QDomElement filterElem = doc.createElement( QStringLiteral( "huesaturation" ) ); - filterElem.setAttribute( "saturation", QString::number( mSaturation ) ); - filterElem.setAttribute( "grayscaleMode", QString::number( mGrayscaleMode ) ); - filterElem.setAttribute( "colorizeOn", QString::number( mColorizeOn ) ); - filterElem.setAttribute( "colorizeRed", QString::number( mColorizeColor.red() ) ); - filterElem.setAttribute( "colorizeGreen", QString::number( mColorizeColor.green() ) ); - filterElem.setAttribute( "colorizeBlue", QString::number( mColorizeColor.blue() ) ); - filterElem.setAttribute( "colorizeStrength", QString::number( mColorizeStrength ) ); + filterElem.setAttribute( QStringLiteral( "saturation" ), QString::number( mSaturation ) ); + filterElem.setAttribute( QStringLiteral( "grayscaleMode" ), QString::number( mGrayscaleMode ) ); + filterElem.setAttribute( QStringLiteral( "colorizeOn" ), QString::number( mColorizeOn ) ); + filterElem.setAttribute( QStringLiteral( "colorizeRed" ), QString::number( mColorizeColor.red() ) ); + filterElem.setAttribute( QStringLiteral( "colorizeGreen" ), QString::number( mColorizeColor.green() ) ); + filterElem.setAttribute( QStringLiteral( "colorizeBlue" ), QString::number( mColorizeColor.blue() ) ); + filterElem.setAttribute( QStringLiteral( "colorizeStrength" ), QString::number( mColorizeStrength ) ); parentElem.appendChild( filterElem ); } @@ -370,14 +370,14 @@ void QgsHueSaturationFilter::readXml( const QDomElement& filterElem ) return; } - setSaturation( filterElem.attribute( "saturation", "0" ).toInt() ); - mGrayscaleMode = ( QgsHueSaturationFilter::GrayscaleMode )filterElem.attribute( "grayscaleMode", "0" ).toInt(); + setSaturation( filterElem.attribute( QStringLiteral( "saturation" ), QStringLiteral( "0" ) ).toInt() ); + mGrayscaleMode = ( QgsHueSaturationFilter::GrayscaleMode )filterElem.attribute( QStringLiteral( "grayscaleMode" ), QStringLiteral( "0" ) ).toInt(); - mColorizeOn = ( bool )filterElem.attribute( "colorizeOn", "0" ).toInt(); - int mColorizeRed = filterElem.attribute( "colorizeRed", "255" ).toInt(); - int mColorizeGreen = filterElem.attribute( "colorizeGreen", "128" ).toInt(); - int mColorizeBlue = filterElem.attribute( "colorizeBlue", "128" ).toInt(); + mColorizeOn = ( bool )filterElem.attribute( QStringLiteral( "colorizeOn" ), QStringLiteral( "0" ) ).toInt(); + int mColorizeRed = filterElem.attribute( QStringLiteral( "colorizeRed" ), QStringLiteral( "255" ) ).toInt(); + int mColorizeGreen = filterElem.attribute( QStringLiteral( "colorizeGreen" ), QStringLiteral( "128" ) ).toInt(); + int mColorizeBlue = filterElem.attribute( QStringLiteral( "colorizeBlue" ), QStringLiteral( "128" ) ).toInt(); setColorizeColor( QColor::fromRgb( mColorizeRed, mColorizeGreen, mColorizeBlue ) ); - mColorizeStrength = filterElem.attribute( "colorizeStrength", "100" ).toInt(); + mColorizeStrength = filterElem.attribute( QStringLiteral( "colorizeStrength" ), QStringLiteral( "100" ) ).toInt(); } diff --git a/src/core/raster/qgsmultibandcolorrenderer.cpp b/src/core/raster/qgsmultibandcolorrenderer.cpp index 8a39f600117b..e16f123d17b3 100644 --- a/src/core/raster/qgsmultibandcolorrenderer.cpp +++ b/src/core/raster/qgsmultibandcolorrenderer.cpp @@ -28,7 +28,7 @@ QgsMultiBandColorRenderer::QgsMultiBandColorRenderer( QgsRasterInterface* input, QgsContrastEnhancement* redEnhancement, QgsContrastEnhancement* greenEnhancement, QgsContrastEnhancement* blueEnhancement ) - : QgsRasterRenderer( input, "multibandcolor" ) + : QgsRasterRenderer( input, QStringLiteral( "multibandcolor" ) ) , mRedBand( redBand ) , mGreenBand( greenBand ) , mBlueBand( blueBand ) @@ -92,13 +92,13 @@ QgsRasterRenderer* QgsMultiBandColorRenderer::create( const QDomElement& elem, Q } //red band, green band, blue band - int redBand = elem.attribute( "redBand", "-1" ).toInt(); - int greenBand = elem.attribute( "greenBand", "-1" ).toInt(); - int blueBand = elem.attribute( "blueBand", "-1" ).toInt(); + int redBand = elem.attribute( QStringLiteral( "redBand" ), QStringLiteral( "-1" ) ).toInt(); + int greenBand = elem.attribute( QStringLiteral( "greenBand" ), QStringLiteral( "-1" ) ).toInt(); + int blueBand = elem.attribute( QStringLiteral( "blueBand" ), QStringLiteral( "-1" ) ).toInt(); //contrast enhancements QgsContrastEnhancement* redContrastEnhancement = nullptr; - QDomElement redContrastElem = elem.firstChildElement( "redContrastEnhancement" ); + QDomElement redContrastElem = elem.firstChildElement( QStringLiteral( "redContrastEnhancement" ) ); if ( !redContrastElem.isNull() ) { redContrastEnhancement = new QgsContrastEnhancement(( Qgis::DataType )( @@ -107,7 +107,7 @@ QgsRasterRenderer* QgsMultiBandColorRenderer::create( const QDomElement& elem, Q } QgsContrastEnhancement* greenContrastEnhancement = nullptr; - QDomElement greenContrastElem = elem.firstChildElement( "greenContrastEnhancement" ); + QDomElement greenContrastElem = elem.firstChildElement( QStringLiteral( "greenContrastEnhancement" ) ); if ( !greenContrastElem.isNull() ) { greenContrastEnhancement = new QgsContrastEnhancement(( Qgis::DataType )( @@ -116,7 +116,7 @@ QgsRasterRenderer* QgsMultiBandColorRenderer::create( const QDomElement& elem, Q } QgsContrastEnhancement* blueContrastEnhancement = nullptr; - QDomElement blueContrastElem = elem.firstChildElement( "blueContrastEnhancement" ); + QDomElement blueContrastElem = elem.firstChildElement( QStringLiteral( "blueContrastEnhancement" ) ); if ( !blueContrastElem.isNull() ) { blueContrastEnhancement = new QgsContrastEnhancement(( Qgis::DataType )( @@ -333,28 +333,28 @@ void QgsMultiBandColorRenderer::writeXml( QDomDocument& doc, QDomElement& parent return; } - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); _writeXml( doc, rasterRendererElem ); - rasterRendererElem.setAttribute( "redBand", mRedBand ); - rasterRendererElem.setAttribute( "greenBand", mGreenBand ); - rasterRendererElem.setAttribute( "blueBand", mBlueBand ); + rasterRendererElem.setAttribute( QStringLiteral( "redBand" ), mRedBand ); + rasterRendererElem.setAttribute( QStringLiteral( "greenBand" ), mGreenBand ); + rasterRendererElem.setAttribute( QStringLiteral( "blueBand" ), mBlueBand ); //contrast enhancement if ( mRedContrastEnhancement ) { - QDomElement redContrastElem = doc.createElement( "redContrastEnhancement" ); + QDomElement redContrastElem = doc.createElement( QStringLiteral( "redContrastEnhancement" ) ); mRedContrastEnhancement->writeXml( doc, redContrastElem ); rasterRendererElem.appendChild( redContrastElem ); } if ( mGreenContrastEnhancement ) { - QDomElement greenContrastElem = doc.createElement( "greenContrastEnhancement" ); + QDomElement greenContrastElem = doc.createElement( QStringLiteral( "greenContrastEnhancement" ) ); mGreenContrastEnhancement->writeXml( doc, greenContrastElem ); rasterRendererElem.appendChild( greenContrastElem ); } if ( mBlueContrastEnhancement ) { - QDomElement blueContrastElem = doc.createElement( "blueContrastEnhancement" ); + QDomElement blueContrastElem = doc.createElement( QStringLiteral( "blueContrastEnhancement" ) ); mBlueContrastEnhancement->writeXml( doc, blueContrastElem ); rasterRendererElem.appendChild( blueContrastElem ); } diff --git a/src/core/raster/qgspalettedrasterrenderer.cpp b/src/core/raster/qgspalettedrasterrenderer.cpp index 9b6e18677d18..24a0f4fe532a 100644 --- a/src/core/raster/qgspalettedrasterrenderer.cpp +++ b/src/core/raster/qgspalettedrasterrenderer.cpp @@ -26,7 +26,7 @@ QgsPalettedRasterRenderer::QgsPalettedRasterRenderer( QgsRasterInterface* input, int bandNumber, QColor* colorArray, int nColors, const QVector<QString>& labels ): - QgsRasterRenderer( input, "paletted" ), mBand( bandNumber ), mNColors( nColors ), mLabels( labels ) + QgsRasterRenderer( input, QStringLiteral( "paletted" ) ), mBand( bandNumber ), mNColors( nColors ), mLabels( labels ) { mColors = new QRgb[nColors]; for ( int i = 0; i < nColors; ++i ) @@ -37,7 +37,7 @@ QgsPalettedRasterRenderer::QgsPalettedRasterRenderer( QgsRasterInterface* input, } QgsPalettedRasterRenderer::QgsPalettedRasterRenderer( QgsRasterInterface* input, int bandNumber, QRgb* colorArray, int nColors, const QVector<QString>& labels ): - QgsRasterRenderer( input, "paletted" ), mBand( bandNumber ), mColors( colorArray ), mNColors( nColors ), mLabels( labels ) + QgsRasterRenderer( input, QStringLiteral( "paletted" ) ), mBand( bandNumber ), mColors( colorArray ), mNColors( nColors ), mLabels( labels ) { } @@ -62,15 +62,15 @@ QgsRasterRenderer* QgsPalettedRasterRenderer::create( const QDomElement& elem, Q return nullptr; } - int bandNumber = elem.attribute( "band", "-1" ).toInt(); + int bandNumber = elem.attribute( QStringLiteral( "band" ), QStringLiteral( "-1" ) ).toInt(); int nColors = 0; QRgb* colors = nullptr; QVector<QString> labels; - QDomElement paletteElem = elem.firstChildElement( "colorPalette" ); + QDomElement paletteElem = elem.firstChildElement( QStringLiteral( "colorPalette" ) ); if ( !paletteElem.isNull() ) { - QDomNodeList paletteEntries = paletteElem.elementsByTagName( "paletteEntry" ); + QDomNodeList paletteEntries = paletteElem.elementsByTagName( QStringLiteral( "paletteEntry" ) ); QDomElement entryElem; int value; @@ -81,7 +81,7 @@ QgsRasterRenderer* QgsPalettedRasterRenderer::create( const QDomElement& elem, Q { entryElem = paletteEntries.at( i ).toElement(); // Could be written as doubles (with .0000) in old project files - value = ( int )entryElem.attribute( "value", "0" ).toDouble(); + value = ( int )entryElem.attribute( QStringLiteral( "value" ), QStringLiteral( "0" ) ).toDouble(); if ( value >= nColors && value <= 10000 ) nColors = value + 1; } QgsDebugMsgLevel( QString( "nColors = %1" ).arg( nColors ), 4 ); @@ -91,12 +91,12 @@ QgsRasterRenderer* QgsPalettedRasterRenderer::create( const QDomElement& elem, Q for ( int i = 0; i < nColors; ++i ) { entryElem = paletteEntries.at( i ).toElement(); - value = ( int )entryElem.attribute( "value", "0" ).toDouble(); + value = ( int )entryElem.attribute( QStringLiteral( "value" ), QStringLiteral( "0" ) ).toDouble(); QgsDebugMsgLevel( entryElem.attribute( "color", "#000000" ), 4 ); if ( value >= 0 && value < nColors ) { - colors[value] = QColor( entryElem.attribute( "color", "#000000" ) ).rgba(); - QString label = entryElem.attribute( "label" ); + colors[value] = QColor( entryElem.attribute( QStringLiteral( "color" ), QStringLiteral( "#000000" ) ) ).rgba(); + QString label = entryElem.attribute( QStringLiteral( "label" ) ); if ( !label.isEmpty() ) { if ( value >= labels.size() ) labels.resize( value + 1 ); @@ -247,19 +247,19 @@ void QgsPalettedRasterRenderer::writeXml( QDomDocument& doc, QDomElement& parent return; } - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); _writeXml( doc, rasterRendererElem ); - rasterRendererElem.setAttribute( "band", mBand ); - QDomElement colorPaletteElem = doc.createElement( "colorPalette" ); + rasterRendererElem.setAttribute( QStringLiteral( "band" ), mBand ); + QDomElement colorPaletteElem = doc.createElement( QStringLiteral( "colorPalette" ) ); for ( int i = 0; i < mNColors; ++i ) { - QDomElement colorElem = doc.createElement( "paletteEntry" ); - colorElem.setAttribute( "value", i ); - colorElem.setAttribute( "color", QColor( mColors[i] ).name() ); + QDomElement colorElem = doc.createElement( QStringLiteral( "paletteEntry" ) ); + colorElem.setAttribute( QStringLiteral( "value" ), i ); + colorElem.setAttribute( QStringLiteral( "color" ), QColor( mColors[i] ).name() ); if ( !label( i ).isEmpty() ) { - colorElem.setAttribute( "label", label( i ) ); + colorElem.setAttribute( QStringLiteral( "label" ), label( i ) ); } colorPaletteElem.appendChild( colorElem ); } diff --git a/src/core/raster/qgsraster.cpp b/src/core/raster/qgsraster.cpp index cc62d5a84c4f..32eb1b94051b 100644 --- a/src/core/raster/qgsraster.cpp +++ b/src/core/raster/qgsraster.cpp @@ -24,28 +24,28 @@ QString QgsRaster::contrastEnhancementLimitsAsString( ContrastEnhancementLimits switch ( theLimits ) { case QgsRaster::ContrastEnhancementMinMax: - return "MinMax"; + return QStringLiteral( "MinMax" ); case QgsRaster::ContrastEnhancementStdDev: - return "StdDev"; + return QStringLiteral( "StdDev" ); case QgsRaster::ContrastEnhancementCumulativeCut: - return "CumulativeCut"; + return QStringLiteral( "CumulativeCut" ); default: break; } - return "None"; + return QStringLiteral( "None" ); } QgsRaster::ContrastEnhancementLimits QgsRaster::contrastEnhancementLimitsFromString( const QString& theLimits ) { - if ( theLimits == "MinMax" ) + if ( theLimits == QLatin1String( "MinMax" ) ) { return ContrastEnhancementMinMax; } - else if ( theLimits == "StdDev" ) + else if ( theLimits == QLatin1String( "StdDev" ) ) { return ContrastEnhancementStdDev; } - else if ( theLimits == "CumulativeCut" ) + else if ( theLimits == QLatin1String( "CumulativeCut" ) ) { return ContrastEnhancementCumulativeCut; } diff --git a/src/core/raster/qgsrasterblock.cpp b/src/core/raster/qgsrasterblock.cpp index 22a9954b20ba..99e2649ab46f 100644 --- a/src/core/raster/qgsrasterblock.cpp +++ b/src/core/raster/qgsrasterblock.cpp @@ -933,7 +933,7 @@ bool QgsRasterBlock::createNoDataBitmap() QString QgsRasterBlock::toString() const { - return QString( "dataType = %1 width = %2 height = %3" ) + return QStringLiteral( "dataType = %1 width = %2 height = %3" ) .arg( mDataType ).arg( mWidth ).arg( mHeight ); } diff --git a/src/core/raster/qgsrasterchecker.cpp b/src/core/raster/qgsrasterchecker.cpp index 9574a7b5a440..91267730fa34 100644 --- a/src/core/raster/qgsrasterchecker.cpp +++ b/src/core/raster/qgsrasterchecker.cpp @@ -29,26 +29,26 @@ #include <QBuffer> QgsRasterChecker::QgsRasterChecker() - : mReport( "" ) + : mReport( QLatin1String( "" ) ) { - mTabStyle = "border-spacing: 0px; border-width: 1px 1px 0 0; border-style: solid;"; - mCellStyle = "border-width: 0 0 1px 1px; border-style: solid; font-size: smaller; text-align: center;"; - mOkStyle = "background: #00ff00;"; - mErrStyle = "background: #ff0000;"; - mErrMsgStyle = "color: #ff0000;"; + mTabStyle = QStringLiteral( "border-spacing: 0px; border-width: 1px 1px 0 0; border-style: solid;" ); + mCellStyle = QStringLiteral( "border-width: 0 0 1px 1px; border-style: solid; font-size: smaller; text-align: center;" ); + mOkStyle = QStringLiteral( "background: #00ff00;" ); + mErrStyle = QStringLiteral( "background: #ff0000;" ); + mErrMsgStyle = QStringLiteral( "color: #ff0000;" ); } bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifiedUri, const QString& theExpectedKey, QString theExpectedUri ) { bool ok = true; - mReport += "\n\n"; + mReport += QLatin1String( "\n\n" ); //QgsRasterDataProvider* verifiedProvider = QgsRasterLayer::loadProvider( theVerifiedKey, theVerifiedUri ); QgsRasterDataProvider* verifiedProvider = dynamic_cast< QgsRasterDataProvider* >( QgsProviderRegistry::instance()->provider( theVerifiedKey, theVerifiedUri ) ); if ( !verifiedProvider || !verifiedProvider->isValid() ) { - error( QString( "Cannot load provider %1 with URI: %2" ).arg( theVerifiedKey, theVerifiedUri ), mReport ); + error( QStringLiteral( "Cannot load provider %1 with URI: %2" ).arg( theVerifiedKey, theVerifiedUri ), mReport ); ok = false; } @@ -56,51 +56,51 @@ bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifi QgsRasterDataProvider* expectedProvider = dynamic_cast< QgsRasterDataProvider* >( QgsProviderRegistry::instance()->provider( theExpectedKey, theExpectedUri ) ); if ( !expectedProvider || !expectedProvider->isValid() ) { - error( QString( "Cannot load provider %1 with URI: %2" ).arg( theExpectedKey, theExpectedUri ), mReport ); + error( QStringLiteral( "Cannot load provider %1 with URI: %2" ).arg( theExpectedKey, theExpectedUri ), mReport ); ok = false; } if ( !ok ) return false; - mReport += QString( "Verified URI: %1<br>" ).arg( theVerifiedUri.replace( '&', "&" ) ); - mReport += QString( "Expected URI: %1<br>" ).arg( theExpectedUri.replace( '&', "&" ) ); + mReport += QStringLiteral( "Verified URI: %1<br>" ).arg( theVerifiedUri.replace( '&', QLatin1String( "&" ) ) ); + mReport += QStringLiteral( "Expected URI: %1<br>" ).arg( theExpectedUri.replace( '&', QLatin1String( "&" ) ) ); - mReport += "<br>"; - mReport += QString( "<table style='%1'>\n" ).arg( mTabStyle ); + mReport += QLatin1String( "<br>" ); + mReport += QStringLiteral( "<table style='%1'>\n" ).arg( mTabStyle ); mReport += compareHead(); - compare( "Band count", verifiedProvider->bandCount(), expectedProvider->bandCount(), mReport, ok ); + compare( QStringLiteral( "Band count" ), verifiedProvider->bandCount(), expectedProvider->bandCount(), mReport, ok ); - compare( "Width", verifiedProvider->xSize(), expectedProvider->xSize(), mReport, ok ); - compare( "Height", verifiedProvider->ySize(), expectedProvider->ySize(), mReport, ok ); + compare( QStringLiteral( "Width" ), verifiedProvider->xSize(), expectedProvider->xSize(), mReport, ok ); + compare( QStringLiteral( "Height" ), verifiedProvider->ySize(), expectedProvider->ySize(), mReport, ok ); - compareRow( "Extent", verifiedProvider->extent().toString(), expectedProvider->extent().toString(), mReport, verifiedProvider->extent() == expectedProvider->extent() ); + compareRow( QStringLiteral( "Extent" ), verifiedProvider->extent().toString(), expectedProvider->extent().toString(), mReport, verifiedProvider->extent() == expectedProvider->extent() ); if ( verifiedProvider->extent() != expectedProvider->extent() ) ok = false; - mReport += "</table>\n"; + mReport += QLatin1String( "</table>\n" ); if ( !ok ) return false; bool allOk = true; for ( int band = 1; band <= expectedProvider->bandCount(); band++ ) { - mReport += QString( "<h3>Band %1</h3>\n" ).arg( band ); - mReport += QString( "<table style='%1'>\n" ).arg( mTabStyle ); + mReport += QStringLiteral( "<h3>Band %1</h3>\n" ).arg( band ); + mReport += QStringLiteral( "<table style='%1'>\n" ).arg( mTabStyle ); mReport += compareHead(); // Data types may differ (?) bool typesOk = true; - compare( "Source data type", verifiedProvider->sourceDataType( band ), expectedProvider->sourceDataType( band ), mReport, typesOk ); - compare( "Data type", verifiedProvider->dataType( band ), expectedProvider->dataType( band ), mReport, typesOk ); + compare( QStringLiteral( "Source data type" ), verifiedProvider->sourceDataType( band ), expectedProvider->sourceDataType( band ), mReport, typesOk ); + compare( QStringLiteral( "Data type" ), verifiedProvider->dataType( band ), expectedProvider->dataType( band ), mReport, typesOk ); // Check nodata bool noDataOk = true; - compare( "No data (NULL) value existence flag", verifiedProvider->sourceHasNoDataValue( band ), expectedProvider->sourceHasNoDataValue( band ), mReport, noDataOk ); + compare( QStringLiteral( "No data (NULL) value existence flag" ), verifiedProvider->sourceHasNoDataValue( band ), expectedProvider->sourceHasNoDataValue( band ), mReport, noDataOk ); if ( verifiedProvider->sourceHasNoDataValue( band ) && expectedProvider->sourceHasNoDataValue( band ) ) { - compare( "No data (NULL) value", verifiedProvider->sourceNoDataValue( band ), expectedProvider->sourceNoDataValue( band ), mReport, noDataOk ); + compare( QStringLiteral( "No data (NULL) value" ), verifiedProvider->sourceNoDataValue( band ), expectedProvider->sourceNoDataValue( band ), mReport, noDataOk ); } bool statsOk = true; @@ -110,22 +110,22 @@ bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifi // Min/max may 'slightly' differ, for big numbers however, the difference may // be quite big, for example for Float32 with max -3.332e+38, the difference is 1.47338e+24 double tol = tolerance( expectedStats.minimumValue ); - compare( "Minimum value", verifiedStats.minimumValue, expectedStats.minimumValue, mReport, statsOk, tol ); + compare( QStringLiteral( "Minimum value" ), verifiedStats.minimumValue, expectedStats.minimumValue, mReport, statsOk, tol ); tol = tolerance( expectedStats.maximumValue ); - compare( "Maximum value", verifiedStats.maximumValue, expectedStats.maximumValue, mReport, statsOk, tol ); + compare( QStringLiteral( "Maximum value" ), verifiedStats.maximumValue, expectedStats.maximumValue, mReport, statsOk, tol ); // TODO: enable once fixed (WCS excludes nulls but GDAL does not) //compare( "Cells count", verifiedStats.elementCount, expectedStats.elementCount, mReport, statsOk ); tol = tolerance( expectedStats.mean ); - compare( "Mean", verifiedStats.mean, expectedStats.mean, mReport, statsOk, tol ); + compare( QStringLiteral( "Mean" ), verifiedStats.mean, expectedStats.mean, mReport, statsOk, tol ); // stdDev usually differ significantly tol = tolerance( expectedStats.stdDev, 1 ); - compare( "Standard deviation", verifiedStats.stdDev, expectedStats.stdDev, mReport, statsOk, tol ); + compare( QStringLiteral( "Standard deviation" ), verifiedStats.stdDev, expectedStats.stdDev, mReport, statsOk, tol ); - mReport += "</table>"; - mReport += "<br>"; + mReport += QLatin1String( "</table>" ); + mReport += QLatin1String( "<br>" ); if ( !statsOk || !typesOk || !noDataOk ) { @@ -133,13 +133,13 @@ bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifi // create values table anyway so that values are available } - mReport += "<table><tr>"; - mReport += "<td>Data comparison</td>"; - mReport += QString( "<td style='%1 %2 border: 1px solid'>correct value</td>" ).arg( mCellStyle, mOkStyle ); - mReport += "<td></td>"; - mReport += QString( "<td style='%1 %2 border: 1px solid'>wrong value<br>expected value</td></tr>" ).arg( mCellStyle, mErrStyle ); - mReport += "</tr></table>"; - mReport += "<br>"; + mReport += QLatin1String( "<table><tr>" ); + mReport += QLatin1String( "<td>Data comparison</td>" ); + mReport += QStringLiteral( "<td style='%1 %2 border: 1px solid'>correct value</td>" ).arg( mCellStyle, mOkStyle ); + mReport += QLatin1String( "<td></td>" ); + mReport += QStringLiteral( "<td style='%1 %2 border: 1px solid'>wrong value<br>expected value</td></tr>" ).arg( mCellStyle, mErrStyle ); + mReport += QLatin1String( "</tr></table>" ); + mReport += QLatin1String( "<br>" ); int width = expectedProvider->xSize(); int height = expectedProvider->ySize(); @@ -150,15 +150,15 @@ bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifi !verifiedBlock || !verifiedBlock->isValid() ) { allOk = false; - mReport += "cannot read raster block"; + mReport += QLatin1String( "cannot read raster block" ); continue; } // compare data values - QString htmlTable = QString( "<table style='%1'>" ).arg( mTabStyle ); + QString htmlTable = QStringLiteral( "<table style='%1'>" ).arg( mTabStyle ); for ( int row = 0; row < height; row ++ ) { - htmlTable += "<tr>"; + htmlTable += QLatin1String( "<tr>" ); for ( int col = 0; col < width; col ++ ) { bool cellOk = true; @@ -168,19 +168,19 @@ bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifi QString valStr; if ( compare( verifiedVal, expectedVal, 0 ) ) { - valStr = QString( "%1" ).arg( verifiedVal ); + valStr = QStringLiteral( "%1" ).arg( verifiedVal ); } else { cellOk = false; allOk = false; - valStr = QString( "%1<br>%2" ).arg( verifiedVal ).arg( expectedVal ); + valStr = QStringLiteral( "%1<br>%2" ).arg( verifiedVal ).arg( expectedVal ); } - htmlTable += QString( "<td style='%1 %2'>%3</td>" ).arg( mCellStyle, cellOk ? mOkStyle : mErrStyle, valStr ); + htmlTable += QStringLiteral( "<td style='%1 %2'>%3</td>" ).arg( mCellStyle, cellOk ? mOkStyle : mErrStyle, valStr ); } - htmlTable += "</tr>"; + htmlTable += QLatin1String( "</tr>" ); } - htmlTable += "</table>"; + htmlTable += QLatin1String( "</table>" ); mReport += htmlTable; @@ -194,9 +194,9 @@ bool QgsRasterChecker::runTest( const QString& theVerifiedKey, QString theVerifi void QgsRasterChecker::error( const QString& theMessage, QString &theReport ) { - theReport += QString( "<font style='%1'>Error: " ).arg( mErrMsgStyle ); + theReport += QStringLiteral( "<font style='%1'>Error: " ).arg( mErrMsgStyle ); theReport += theMessage; - theReport += "</font>"; + theReport += QLatin1String( "</font>" ); } double QgsRasterChecker::tolerance( double val, int places ) @@ -209,7 +209,7 @@ double QgsRasterChecker::tolerance( double val, int places ) QString QgsRasterChecker::compareHead() { QString html; - html += QString( "<tr><th style='%1'>Param name</th><th style='%1'>Verified value</th><th style='%1'>Expected value</th><th style='%1'>Difference</th><th style='%1'>Tolerance</th></tr>" ).arg( mCellStyle ); + html += QStringLiteral( "<tr><th style='%1'>Param name</th><th style='%1'>Verified value</th><th style='%1'>Expected value</th><th style='%1'>Difference</th><th style='%1'>Tolerance</th></tr>" ).arg( mCellStyle ); return html; } @@ -235,9 +235,9 @@ void QgsRasterChecker::compare( const QString& theParamName, double verifiedVal, void QgsRasterChecker::compareRow( const QString& theParamName, const QString& verifiedVal, const QString& expectedVal, QString &theReport, bool theOk, const QString& theDifference, const QString& theTolerance ) { - theReport += "<tr>\n"; - theReport += QString( "<td style='%1'>%2</td><td style='%1 %3'>%4</td><td style='%1'>%5</td>\n" ).arg( mCellStyle, theParamName, theOk ? mOkStyle : mErrStyle, verifiedVal, expectedVal ); - theReport += QString( "<td style='%1'>%2</td>\n" ).arg( mCellStyle, theDifference ); - theReport += QString( "<td style='%1'>%2</td>\n" ).arg( mCellStyle, theTolerance ); - theReport += "</tr>"; + theReport += QLatin1String( "<tr>\n" ); + theReport += QStringLiteral( "<td style='%1'>%2</td><td style='%1 %3'>%4</td><td style='%1'>%5</td>\n" ).arg( mCellStyle, theParamName, theOk ? mOkStyle : mErrStyle, verifiedVal, expectedVal ); + theReport += QStringLiteral( "<td style='%1'>%2</td>\n" ).arg( mCellStyle, theDifference ); + theReport += QStringLiteral( "<td style='%1'>%2</td>\n" ).arg( mCellStyle, theTolerance ); + theReport += QLatin1String( "</tr>" ); } diff --git a/src/core/raster/qgsrasterchecker.h b/src/core/raster/qgsrasterchecker.h index 2582311d73e0..8f31e7440af3 100644 --- a/src/core/raster/qgsrasterchecker.h +++ b/src/core/raster/qgsrasterchecker.h @@ -61,7 +61,7 @@ class CORE_EXPORT QgsRasterChecker bool compare( double verifiedVal, double expectedVal, double theTolerance ); void compare( const QString& theParamName, int verifiedVal, int expectedVal, QString &theReport, bool &theOk ); void compare( const QString& theParamName, double verifiedVal, double expectedVal, QString &theReport, bool &theOk, double theTolerance = 0 ); - void compareRow( const QString& theParamName, const QString& verifiedVal, const QString& expectedVal, QString &theReport, bool theOk, const QString& theDifference = "", const QString& theTolerance = "" ); + void compareRow( const QString& theParamName, const QString& verifiedVal, const QString& expectedVal, QString &theReport, bool theOk, const QString& theDifference = QStringLiteral( "" ), const QString& theTolerance = QStringLiteral( "" ) ); double tolerance( double val, int places = 6 ); }; // class QgsRasterChecker diff --git a/src/core/raster/qgsrasterdataprovider.cpp b/src/core/raster/qgsrasterdataprovider.cpp index 60cdd1031be9..4b45b31d70ce 100644 --- a/src/core/raster/qgsrasterdataprovider.cpp +++ b/src/core/raster/qgsrasterdataprovider.cpp @@ -255,7 +255,7 @@ QString QgsRasterDataProvider::makeTableCell( QString const & value ) // convenience function for building metadata() HTML table cells QString QgsRasterDataProvider::makeTableCells( QStringList const & values ) { - QString s( "<tr>" ); + QString s( QStringLiteral( "<tr>" ) ); for ( QStringList::const_iterator i = values.begin(); i != values.end(); @@ -264,7 +264,7 @@ QString QgsRasterDataProvider::makeTableCells( QStringList const & values ) s += QgsRasterDataProvider::makeTableCell( *i ); } - s += "</tr>"; + s += QLatin1String( "</tr>" ); return s; } // makeTableCell_ @@ -343,7 +343,7 @@ QgsRasterIdentifyResult QgsRasterDataProvider::identify( const QgsPoint & thePoi QString QgsRasterDataProvider::lastErrorFormat() { - return "text/plain"; + return QStringLiteral( "text/plain" ); } typedef QList<QPair<QString, QString> > *pyramidResamplingMethods_t(); @@ -451,15 +451,15 @@ QString QgsRasterDataProvider::identifyFormatName( QgsRaster::IdentifyFormat for switch ( format ) { case QgsRaster::IdentifyFormatValue: - return "Value"; + return QStringLiteral( "Value" ); case QgsRaster::IdentifyFormatText: - return "Text"; + return QStringLiteral( "Text" ); case QgsRaster::IdentifyFormatHtml: - return "Html"; + return QStringLiteral( "Html" ); case QgsRaster::IdentifyFormatFeature: - return "Feature"; + return QStringLiteral( "Feature" ); default: - return "Undefined"; + return QStringLiteral( "Undefined" ); } } @@ -476,16 +476,16 @@ QString QgsRasterDataProvider::identifyFormatLabel( QgsRaster::IdentifyFormat fo case QgsRaster::IdentifyFormatFeature: return tr( "Feature" ); default: - return "Undefined"; + return QStringLiteral( "Undefined" ); } } QgsRaster::IdentifyFormat QgsRasterDataProvider::identifyFormatFromName( const QString& formatName ) { - if ( formatName == "Value" ) return QgsRaster::IdentifyFormatValue; - if ( formatName == "Text" ) return QgsRaster::IdentifyFormatText; - if ( formatName == "Html" ) return QgsRaster::IdentifyFormatHtml; - if ( formatName == "Feature" ) return QgsRaster::IdentifyFormatFeature; + if ( formatName == QLatin1String( "Value" ) ) return QgsRaster::IdentifyFormatValue; + if ( formatName == QLatin1String( "Text" ) ) return QgsRaster::IdentifyFormatText; + if ( formatName == QLatin1String( "Html" ) ) return QgsRaster::IdentifyFormatHtml; + if ( formatName == QLatin1String( "Feature" ) ) return QgsRaster::IdentifyFormatFeature; return QgsRaster::IdentifyFormatUndefined; } diff --git a/src/core/raster/qgsrasterdataprovider.h b/src/core/raster/qgsrasterdataprovider.h index 35cd0c194195..ab562332e171 100644 --- a/src/core/raster/qgsrasterdataprovider.h +++ b/src/core/raster/qgsrasterdataprovider.h @@ -125,58 +125,58 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast switch ( colorInterpretation ) { case QgsRaster::UndefinedColorInterpretation: - return "Undefined"; + return QStringLiteral( "Undefined" ); case QgsRaster::GrayIndex: - return "Gray"; + return QStringLiteral( "Gray" ); case QgsRaster::PaletteIndex: - return "Palette"; + return QStringLiteral( "Palette" ); case QgsRaster::RedBand: - return "Red"; + return QStringLiteral( "Red" ); case QgsRaster::GreenBand: - return "Green"; + return QStringLiteral( "Green" ); case QgsRaster::BlueBand: - return "Blue"; + return QStringLiteral( "Blue" ); case QgsRaster::AlphaBand: - return "Alpha"; + return QStringLiteral( "Alpha" ); case QgsRaster::HueBand: - return "Hue"; + return QStringLiteral( "Hue" ); case QgsRaster::SaturationBand: - return "Saturation"; + return QStringLiteral( "Saturation" ); case QgsRaster::LightnessBand: - return "Lightness"; + return QStringLiteral( "Lightness" ); case QgsRaster::CyanBand: - return "Cyan"; + return QStringLiteral( "Cyan" ); case QgsRaster::MagentaBand: - return "Magenta"; + return QStringLiteral( "Magenta" ); case QgsRaster::YellowBand: - return "Yellow"; + return QStringLiteral( "Yellow" ); case QgsRaster::BlackBand: - return "Black"; + return QStringLiteral( "Black" ); case QgsRaster::YCbCr_YBand: - return "YCbCr_Y"; + return QStringLiteral( "YCbCr_Y" ); case QgsRaster::YCbCr_CbBand: - return "YCbCr_Cb"; + return QStringLiteral( "YCbCr_Cb" ); case QgsRaster::YCbCr_CrBand: - return "YCbCr_Cr"; + return QStringLiteral( "YCbCr_Cr" ); default: - return "Unknown"; + return QStringLiteral( "Unknown" ); } } /** Reload data (data could change) */ @@ -268,7 +268,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast /** \brief Create pyramid overviews */ virtual QString buildPyramids( const QList<QgsRasterPyramid> & thePyramidList, - const QString & theResamplingMethod = "NEAREST", + const QString & theResamplingMethod = QStringLiteral( "NEAREST" ), QgsRaster::RasterPyramidsFormat theFormat = QgsRaster::PyramidsGTiff, const QStringList & theConfigOptions = QStringList() ) { @@ -276,7 +276,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast Q_UNUSED( theResamplingMethod ); Q_UNUSED( theFormat ); Q_UNUSED( theConfigOptions ); - return "FAILED_NOT_SUPPORTED"; + return QStringLiteral( "FAILED_NOT_SUPPORTED" ); } /** \brief Accessor for ths raster layers pyramid list. diff --git a/src/core/raster/qgsrasterfilewriter.cpp b/src/core/raster/qgsrasterfilewriter.cpp index 4b09674c006e..00a3bec09343 100644 --- a/src/core/raster/qgsrasterfilewriter.cpp +++ b/src/core/raster/qgsrasterfilewriter.cpp @@ -32,8 +32,8 @@ QgsRasterFileWriter::QgsRasterFileWriter( const QString& outputUrl ) : mMode( Raw ) , mOutputUrl( outputUrl ) - , mOutputProviderKey( "gdal" ) - , mOutputFormat( "GTiff" ) + , mOutputProviderKey( QStringLiteral( "gdal" ) ) + , mOutputFormat( QStringLiteral( "GTiff" ) ) , mTiledMode( false ) , mMaxTileWidth( 500 ) , mMaxTileHeight( 500 ) @@ -48,8 +48,8 @@ QgsRasterFileWriter::QgsRasterFileWriter( const QString& outputUrl ) QgsRasterFileWriter::QgsRasterFileWriter() : mMode( Raw ) - , mOutputProviderKey( "gdal" ) - , mOutputFormat( "GTiff" ) + , mOutputProviderKey( QStringLiteral( "gdal" ) ) + , mOutputFormat( QStringLiteral( "GTiff" ) ) , mTiledMode( false ) , mMaxTileWidth( 500 ) , mMaxTileHeight( 500 ) @@ -642,44 +642,44 @@ void QgsRasterFileWriter::addToVRT( const QString& filename, int band, int xSize { QDomElement bandElem = mVRTBands.value( band - 1 ); - QDomElement simpleSourceElem = mVRTDocument.createElement( "SimpleSource" ); + QDomElement simpleSourceElem = mVRTDocument.createElement( QStringLiteral( "SimpleSource" ) ); //SourceFilename - QDomElement sourceFilenameElem = mVRTDocument.createElement( "SourceFilename" ); - sourceFilenameElem.setAttribute( "relativeToVRT", "1" ); + QDomElement sourceFilenameElem = mVRTDocument.createElement( QStringLiteral( "SourceFilename" ) ); + sourceFilenameElem.setAttribute( QStringLiteral( "relativeToVRT" ), QStringLiteral( "1" ) ); QDomText sourceFilenameText = mVRTDocument.createTextNode( filename ); sourceFilenameElem.appendChild( sourceFilenameText ); simpleSourceElem.appendChild( sourceFilenameElem ); //SourceBand - QDomElement sourceBandElem = mVRTDocument.createElement( "SourceBand" ); + QDomElement sourceBandElem = mVRTDocument.createElement( QStringLiteral( "SourceBand" ) ); QDomText sourceBandText = mVRTDocument.createTextNode( QString::number( band ) ); sourceBandElem.appendChild( sourceBandText ); simpleSourceElem.appendChild( sourceBandElem ); //SourceProperties - QDomElement sourcePropertiesElem = mVRTDocument.createElement( "SourceProperties" ); - sourcePropertiesElem.setAttribute( "RasterXSize", xSize ); - sourcePropertiesElem.setAttribute( "RasterYSize", ySize ); - sourcePropertiesElem.setAttribute( "BlockXSize", xSize ); - sourcePropertiesElem.setAttribute( "BlockYSize", ySize ); - sourcePropertiesElem.setAttribute( "DataType", "Byte" ); + QDomElement sourcePropertiesElem = mVRTDocument.createElement( QStringLiteral( "SourceProperties" ) ); + sourcePropertiesElem.setAttribute( QStringLiteral( "RasterXSize" ), xSize ); + sourcePropertiesElem.setAttribute( QStringLiteral( "RasterYSize" ), ySize ); + sourcePropertiesElem.setAttribute( QStringLiteral( "BlockXSize" ), xSize ); + sourcePropertiesElem.setAttribute( QStringLiteral( "BlockYSize" ), ySize ); + sourcePropertiesElem.setAttribute( QStringLiteral( "DataType" ), QStringLiteral( "Byte" ) ); simpleSourceElem.appendChild( sourcePropertiesElem ); //SrcRect - QDomElement srcRectElem = mVRTDocument.createElement( "SrcRect" ); - srcRectElem.setAttribute( "xOff", "0" ); - srcRectElem.setAttribute( "yOff", "0" ); - srcRectElem.setAttribute( "xSize", xSize ); - srcRectElem.setAttribute( "ySize", ySize ); + QDomElement srcRectElem = mVRTDocument.createElement( QStringLiteral( "SrcRect" ) ); + srcRectElem.setAttribute( QStringLiteral( "xOff" ), QStringLiteral( "0" ) ); + srcRectElem.setAttribute( QStringLiteral( "yOff" ), QStringLiteral( "0" ) ); + srcRectElem.setAttribute( QStringLiteral( "xSize" ), xSize ); + srcRectElem.setAttribute( QStringLiteral( "ySize" ), ySize ); simpleSourceElem.appendChild( srcRectElem ); //DstRect - QDomElement dstRectElem = mVRTDocument.createElement( "DstRect" ); - dstRectElem.setAttribute( "xOff", xOffset ); - dstRectElem.setAttribute( "yOff", yOffset ); - dstRectElem.setAttribute( "xSize", xSize ); - dstRectElem.setAttribute( "ySize", ySize ); + QDomElement dstRectElem = mVRTDocument.createElement( QStringLiteral( "DstRect" ) ); + dstRectElem.setAttribute( QStringLiteral( "xOff" ), xOffset ); + dstRectElem.setAttribute( QStringLiteral( "yOff" ), yOffset ); + dstRectElem.setAttribute( QStringLiteral( "xSize" ), xSize ); + dstRectElem.setAttribute( QStringLiteral( "ySize" ), ySize ); simpleSourceElem.appendChild( dstRectElem ); bandElem.appendChild( simpleSourceElem ); @@ -749,28 +749,28 @@ void QgsRasterFileWriter::buildPyramids( const QString& filename ) if ( !res.isNull() ) { QString title, message; - if ( res == "ERROR_WRITE_ACCESS" ) + if ( res == QLatin1String( "ERROR_WRITE_ACCESS" ) ) { title = QObject::tr( "Building pyramids failed - write access denied" ); message = QObject::tr( "Write access denied. Adjust the file permissions and try again." ); } - else if ( res == "ERROR_WRITE_FORMAT" ) + else if ( res == QLatin1String( "ERROR_WRITE_FORMAT" ) ) { title = QObject::tr( "Building pyramids failed." ); message = QObject::tr( "The file was not writable. Some formats do not " "support pyramid overviews. Consult the GDAL documentation if in doubt." ); } - else if ( res == "FAILED_NOT_SUPPORTED" ) + else if ( res == QLatin1String( "FAILED_NOT_SUPPORTED" ) ) { title = QObject::tr( "Building pyramids failed." ); message = QObject::tr( "Building pyramid overviews is not supported on this type of raster." ); } - else if ( res == "ERROR_JPEG_COMPRESSION" ) + else if ( res == QLatin1String( "ERROR_JPEG_COMPRESSION" ) ) { title = QObject::tr( "Building pyramids failed." ); message = QObject::tr( "Building internal pyramid overviews is not supported on raster layers with JPEG compression and your current libtiff library." ); } - else if ( res == "ERROR_VIRTUAL" ) + else if ( res == QLatin1String( "ERROR_VIRTUAL" ) ) { title = QObject::tr( "Building pyramids failed." ); message = QObject::tr( "Building pyramid overviews is not supported on this type of raster." ); @@ -804,15 +804,15 @@ int QgsRasterFileWriter::pyramidsProgress( double dfComplete, const char *pszMes void QgsRasterFileWriter::createVRT( int xSize, int ySize, const QgsCoordinateReferenceSystem& crs, double* geoTransform, Qgis::DataType type, const QList<bool>& destHasNoDataValueList, const QList<double>& destNoDataValueList ) { mVRTDocument.clear(); - QDomElement VRTDatasetElem = mVRTDocument.createElement( "VRTDataset" ); + QDomElement VRTDatasetElem = mVRTDocument.createElement( QStringLiteral( "VRTDataset" ) ); //xsize / ysize - VRTDatasetElem.setAttribute( "rasterXSize", xSize ); - VRTDatasetElem.setAttribute( "rasterYSize", ySize ); + VRTDatasetElem.setAttribute( QStringLiteral( "rasterXSize" ), xSize ); + VRTDatasetElem.setAttribute( QStringLiteral( "rasterYSize" ), ySize ); mVRTDocument.appendChild( VRTDatasetElem ); //CRS - QDomElement SRSElem = mVRTDocument.createElement( "SRS" ); + QDomElement SRSElem = mVRTDocument.createElement( QStringLiteral( "SRS" ) ); QDomText crsText = mVRTDocument.createTextNode( crs.toWkt() ); SRSElem.appendChild( crsText ); VRTDatasetElem.appendChild( SRSElem ); @@ -820,7 +820,7 @@ void QgsRasterFileWriter::createVRT( int xSize, int ySize, const QgsCoordinateRe //geotransform if ( geoTransform ) { - QDomElement geoTransformElem = mVRTDocument.createElement( "GeoTransform" ); + QDomElement geoTransformElem = mVRTDocument.createElement( QStringLiteral( "GeoTransform" ) ); QString geoTransformString = QString::number( geoTransform[0] ) + ", " + QString::number( geoTransform[1] ) + ", " + QString::number( geoTransform[2] ) + ", " + QString::number( geoTransform[3] ) + ", " + QString::number( geoTransform[4] ) + ", " + QString::number( geoTransform[5] ); QDomText geoTransformText = mVRTDocument.createTextNode( geoTransformString ); @@ -839,32 +839,32 @@ void QgsRasterFileWriter::createVRT( int xSize, int ySize, const QgsCoordinateRe } QStringList colorInterp; - colorInterp << "Red" << "Green" << "Blue" << "Alpha"; + colorInterp << QStringLiteral( "Red" ) << QStringLiteral( "Green" ) << QStringLiteral( "Blue" ) << QStringLiteral( "Alpha" ); QMap<Qgis::DataType, QString> dataTypes; - dataTypes.insert( Qgis::Byte, "Byte" ); - dataTypes.insert( Qgis::UInt16, "UInt16" ); - dataTypes.insert( Qgis::Int16, "Int16" ); - dataTypes.insert( Qgis::UInt32, "Int32" ); - dataTypes.insert( Qgis::Float32, "Float32" ); - dataTypes.insert( Qgis::Float64, "Float64" ); - dataTypes.insert( Qgis::CInt16, "CInt16" ); - dataTypes.insert( Qgis::CInt32, "CInt32" ); - dataTypes.insert( Qgis::CFloat32, "CFloat32" ); - dataTypes.insert( Qgis::CFloat64, "CFloat64" ); + dataTypes.insert( Qgis::Byte, QStringLiteral( "Byte" ) ); + dataTypes.insert( Qgis::UInt16, QStringLiteral( "UInt16" ) ); + dataTypes.insert( Qgis::Int16, QStringLiteral( "Int16" ) ); + dataTypes.insert( Qgis::UInt32, QStringLiteral( "Int32" ) ); + dataTypes.insert( Qgis::Float32, QStringLiteral( "Float32" ) ); + dataTypes.insert( Qgis::Float64, QStringLiteral( "Float64" ) ); + dataTypes.insert( Qgis::CInt16, QStringLiteral( "CInt16" ) ); + dataTypes.insert( Qgis::CInt32, QStringLiteral( "CInt32" ) ); + dataTypes.insert( Qgis::CFloat32, QStringLiteral( "CFloat32" ) ); + dataTypes.insert( Qgis::CFloat64, QStringLiteral( "CFloat64" ) ); for ( int i = 1; i <= nBands; i++ ) { - QDomElement VRTBand = mVRTDocument.createElement( "VRTRasterBand" ); + QDomElement VRTBand = mVRTDocument.createElement( QStringLiteral( "VRTRasterBand" ) ); - VRTBand.setAttribute( "band", QString::number( i ) ); + VRTBand.setAttribute( QStringLiteral( "band" ), QString::number( i ) ); QString dataType = dataTypes.value( type ); - VRTBand.setAttribute( "dataType", dataType ); + VRTBand.setAttribute( QStringLiteral( "dataType" ), dataType ); if ( mMode == Image ) { - VRTBand.setAttribute( "dataType", "Byte" ); - QDomElement colorInterpElement = mVRTDocument.createElement( "ColorInterp" ); + VRTBand.setAttribute( QStringLiteral( "dataType" ), QStringLiteral( "Byte" ) ); + QDomElement colorInterpElement = mVRTDocument.createElement( QStringLiteral( "ColorInterp" ) ); QDomText interpText = mVRTDocument.createTextNode( colorInterp.value( i - 1 ) ); colorInterpElement.appendChild( interpText ); VRTBand.appendChild( colorInterpElement ); @@ -872,7 +872,7 @@ void QgsRasterFileWriter::createVRT( int xSize, int ySize, const QgsCoordinateRe if ( !destHasNoDataValueList.isEmpty() && destHasNoDataValueList.value( i - 1 ) ) { - VRTBand.setAttribute( "NoDataValue", QString::number( destNoDataValueList.value( i - 1 ) ) ); + VRTBand.setAttribute( QStringLiteral( "NoDataValue" ), QString::number( destNoDataValueList.value( i - 1 ) ) ); } mVRTBands.append( VRTBand ); @@ -974,11 +974,11 @@ QString QgsRasterFileWriter::partFileName( int fileIndex ) { // .tif for now QFileInfo outputInfo( mOutputUrl ); - return QString( "%1.%2.tif" ).arg( outputInfo.fileName() ).arg( fileIndex ); + return QStringLiteral( "%1.%2.tif" ).arg( outputInfo.fileName() ).arg( fileIndex ); } QString QgsRasterFileWriter::vrtFileName() { QFileInfo outputInfo( mOutputUrl ); - return QString( "%1.vrt" ).arg( outputInfo.fileName() ); + return QStringLiteral( "%1.vrt" ).arg( outputInfo.fileName() ); } diff --git a/src/core/raster/qgsrasterinterface.cpp b/src/core/raster/qgsrasterinterface.cpp index 67fa016143e1..7be4f39955d3 100644 --- a/src/core/raster/qgsrasterinterface.cpp +++ b/src/core/raster/qgsrasterinterface.cpp @@ -602,5 +602,5 @@ QString QgsRasterInterface::capabilitiesString() const QgsDebugMsgLevel( "Capability: " + abilitiesList.join( ", " ), 4 ); - return abilitiesList.join( ", " ); + return abilitiesList.join( QStringLiteral( ", " ) ); } diff --git a/src/core/raster/qgsrasterinterface.h b/src/core/raster/qgsrasterinterface.h index d1f598ba78cd..f87161533c9d 100644 --- a/src/core/raster/qgsrasterinterface.h +++ b/src/core/raster/qgsrasterinterface.h @@ -139,7 +139,7 @@ class CORE_EXPORT QgsRasterInterface /** \brief helper function to create zero padded band names */ virtual QString generateBandName( int theBandNumber ) const { - return tr( "Band" ) + QString( " %1" ) .arg( theBandNumber, 1 + static_cast< int >( log10( static_cast< double >( bandCount() ) ) ), 10, QChar( '0' ) ); + return tr( "Band" ) + QStringLiteral( " %1" ) .arg( theBandNumber, 1 + static_cast< int >( log10( static_cast< double >( bandCount() ) ) ), 10, QChar( '0' ) ); } /** Read block of data using given extent and size. diff --git a/src/core/raster/qgsrasterlayer.cpp b/src/core/raster/qgsrasterlayer.cpp index ef506a0efb5b..4260760814fa 100644 --- a/src/core/raster/qgsrasterlayer.cpp +++ b/src/core/raster/qgsrasterlayer.cpp @@ -85,7 +85,7 @@ const double QgsRasterLayer::SAMPLE_SIZE = 250000; QgsRasterLayer::QgsRasterLayer() : QgsMapLayer( RasterLayer ) - , QSTRING_NOT_SET( "Not Set" ) + , QSTRING_NOT_SET( QStringLiteral( "Not Set" ) ) , TRSTRING_NOT_SET( tr( "Not Set" ) ) , mDataProvider( nullptr ) { @@ -98,7 +98,7 @@ QgsRasterLayer::QgsRasterLayer( const QString& baseName, bool loadDefaultStyleFlag ) : QgsMapLayer( RasterLayer, baseName, path ) - , QSTRING_NOT_SET( "Not Set" ) + , QSTRING_NOT_SET( QStringLiteral( "Not Set" ) ) , TRSTRING_NOT_SET( tr( "Not Set" ) ) , mDataProvider( nullptr ) { @@ -106,7 +106,7 @@ QgsRasterLayer::QgsRasterLayer( // TODO, call constructor with provider key init(); - setDataProvider( "gdal" ); + setDataProvider( QStringLiteral( "gdal" ) ); if ( !mValid ) return; bool defaultLoadedFlag = false; @@ -131,7 +131,7 @@ QgsRasterLayer::QgsRasterLayer( const QString & uri, bool loadDefaultStyleFlag ) : QgsMapLayer( RasterLayer, baseName, uri ) // Constant that signals property not used. - , QSTRING_NOT_SET( "Not Set" ) + , QSTRING_NOT_SET( QStringLiteral( "Not Set" ) ) , TRSTRING_NOT_SET( tr( "Not Set" ) ) , mDataProvider( nullptr ) , mProviderKey( providerKey ) @@ -311,18 +311,18 @@ QString QgsRasterLayer::metadata() const QgsRasterDataProvider* provider = const_cast< QgsRasterDataProvider* >( mDataProvider ); QString myMetadata; myMetadata += "<p class=\"glossy\">" + tr( "Driver" ) + "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += mDataProvider->description(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); // Insert provider-specific (e.g. WMS-specific) metadata // crashing myMetadata += mDataProvider->metadata(); - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "No Data Value" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); // TODO: all bands if ( mDataProvider->sourceHasNoDataValue( 1 ) ) { @@ -332,13 +332,13 @@ QString QgsRasterLayer::metadata() const { myMetadata += '*' + tr( "NoDataValue not set" ) + '*'; } - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); - myMetadata += "</p>\n"; - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Data Type" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); //just use the first band switch ( mDataProvider->sourceDataType( 1 ) ) { @@ -378,26 +378,26 @@ QString QgsRasterLayer::metadata() const default: myMetadata += tr( "Could not determine raster data type." ); } - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Pyramid overviews" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Layer Spatial Reference System" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += crs().toProj4(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Layer Extent (layer original source projection)" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += mDataProvider->extent().toString(); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); // output coordinate system // TODO: this is not related to layer, to be removed? [MD] @@ -418,31 +418,31 @@ QString QgsRasterLayer::metadata() const { QgsDebugMsgLevel( "Raster properties : checking if band " + QString::number( myIteratorInt ) + " has stats? ", 4 ); //band name - myMetadata += "<p class=\"glossy\">\n"; + myMetadata += QLatin1String( "<p class=\"glossy\">\n" ); myMetadata += tr( "Band" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += bandName( myIteratorInt ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //band number - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Band No" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myIteratorInt ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //check if full stats for this layer have already been collected if ( !provider->hasStatistics( myIteratorInt ) ) //not collected { QgsDebugMsgLevel( ".....no", 4 ); - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "No Stats" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += tr( "No stats collected yet" ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); } else // collected - show full detail { @@ -450,68 +450,68 @@ QString QgsRasterLayer::metadata() const QgsRasterBandStats myRasterBandStats = provider->bandStatistics( myIteratorInt ); //Min Val - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Min Val" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.minimumValue, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); // Max Val - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Max Val" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.maximumValue, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); // Range - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Range" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.range, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); // Mean - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Mean" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.mean, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //sum of squares - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Sum of squares" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.sumOfSquares, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //standard deviation - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Standard Deviation" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.stdDev, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //sum of all cells - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Sum of all cells" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.sum, 'f', 10 ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //number of cells - myMetadata += "<p>"; + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "Cell Count" ); - myMetadata += "</p>\n"; - myMetadata += "<p>\n"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>\n" ); myMetadata += QString::number( myRasterBandStats.elementCount ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); } } @@ -660,7 +660,7 @@ void QgsRasterLayer::setDataProvider( QString const & provider ) return; } - if ( provider == "gdal" ) + if ( provider == QLatin1String( "gdal" ) ) { // make sure that the /vsigzip or /vsizip is added to uri, if applicable mDataSource = mDataProvider->dataSourceUri(); @@ -811,7 +811,7 @@ void QgsRasterLayer::setDataProvider( QString const & provider ) { identifyFormat = QgsRaster::IdentifyFormatValue; } - setCustomProperty( "identify/format", QgsRasterDataProvider::identifyFormatName( identifyFormat ) ); + setCustomProperty( QStringLiteral( "identify/format" ), QgsRasterDataProvider::identifyFormatName( identifyFormat ) ); // Store timestamp // TODO move to provider @@ -855,13 +855,13 @@ void QgsRasterLayer::setContrastEnhancement( QgsContrastEnhancement::ContrastEnh QgsSingleBandGrayRenderer* myGrayRenderer = nullptr; QgsMultiBandColorRenderer* myMultiBandRenderer = nullptr; QString rendererType = mPipe.renderer()->type(); - if ( rendererType == "singlebandgray" ) + if ( rendererType == QLatin1String( "singlebandgray" ) ) { myGrayRenderer = dynamic_cast<QgsSingleBandGrayRenderer*>( mPipe.renderer() ); if ( !myGrayRenderer ) return; myBands << myGrayRenderer->grayBand(); } - else if ( rendererType == "multibandcolor" ) + else if ( rendererType == QLatin1String( "multibandcolor" ) ) { myMultiBandRenderer = dynamic_cast<QgsMultiBandColorRenderer*>( mPipe.renderer() ); if ( !myMultiBandRenderer ) return; @@ -895,8 +895,8 @@ void QgsRasterLayer::setContrastEnhancement( QgsContrastEnhancement::ContrastEnh else if ( theLimits == QgsRaster::ContrastEnhancementCumulativeCut ) { QSettings mySettings; - double myLower = mySettings.value( "/Raster/cumulativeCutLower", QString::number( CUMULATIVE_CUT_LOWER ) ).toDouble(); - double myUpper = mySettings.value( "/Raster/cumulativeCutUpper", QString::number( CUMULATIVE_CUT_UPPER ) ).toDouble(); + double myLower = mySettings.value( QStringLiteral( "/Raster/cumulativeCutLower" ), QString::number( CUMULATIVE_CUT_LOWER ) ).toDouble(); + double myUpper = mySettings.value( QStringLiteral( "/Raster/cumulativeCutUpper" ), QString::number( CUMULATIVE_CUT_UPPER ) ).toDouble(); QgsDebugMsgLevel( QString( "myLower = %1 myUpper = %2" ).arg( myLower ).arg( myUpper ), 4 ); mDataProvider->cumulativeCut( myBand, myLower, myUpper, myMin, myMax, theExtent, theSampleSize ); } @@ -912,11 +912,11 @@ void QgsRasterLayer::setContrastEnhancement( QgsContrastEnhancement::ContrastEnh } } - if ( rendererType == "singlebandgray" ) + if ( rendererType == QLatin1String( "singlebandgray" ) ) { if ( myEnhancements.first() ) myGrayRenderer->setContrastEnhancement( myEnhancements.takeFirst() ); } - else if ( rendererType == "multibandcolor" ) + else if ( rendererType == QLatin1String( "multibandcolor" ) ) { if ( myEnhancements.first() ) myMultiBandRenderer->setRedContrastEnhancement( myEnhancements.takeFirst() ); if ( myEnhancements.first() ) myMultiBandRenderer->setGreenContrastEnhancement( myEnhancements.takeFirst() ); @@ -942,20 +942,20 @@ void QgsRasterLayer::setDefaultContrastEnhancement() // TODO: we should not test renderer class here, move it somehow to renderers if ( dynamic_cast<QgsSingleBandGrayRenderer*>( renderer() ) ) { - myKey = "singleBand"; - myDefault = "StretchToMinimumMaximum"; + myKey = QStringLiteral( "singleBand" ); + myDefault = QStringLiteral( "StretchToMinimumMaximum" ); } else if ( dynamic_cast<QgsMultiBandColorRenderer*>( renderer() ) ) { if ( QgsRasterBlock::typeSize( dataProvider()->sourceDataType( 1 ) ) == 1 ) { - myKey = "multiBandSingleByte"; - myDefault = "NoEnhancement"; + myKey = QStringLiteral( "multiBandSingleByte" ); + myDefault = QStringLiteral( "NoEnhancement" ); } else { - myKey = "multiBandMultiByte"; - myDefault = "StretchToMinimumMaximum"; + myKey = QStringLiteral( "multiBandMultiByte" ); + myDefault = QStringLiteral( "StretchToMinimumMaximum" ); } } @@ -975,7 +975,7 @@ void QgsRasterLayer::setDefaultContrastEnhancement() return; } - QString myLimitsString = mySettings.value( "/Raster/defaultContrastEnhancementLimits", "CumulativeCut" ).toString(); + QString myLimitsString = mySettings.value( QStringLiteral( "/Raster/defaultContrastEnhancementLimits" ), "CumulativeCut" ).toString(); QgsRaster::ContrastEnhancementLimits myLimits = QgsRaster::contrastEnhancementLimitsFromString( myLimitsString ); setContrastEnhancement( myAlgorithm, myLimits ); @@ -1117,32 +1117,32 @@ bool QgsRasterLayer::readSymbology( const QDomNode& layer_node, QString& errorMe // already many project files in use so we support 1.9 backward compatibility // even it was never officialy released -> use pipe element if present, otherwise // use layer node - QDomNode pipeNode = layer_node.firstChildElement( "pipe" ); + QDomNode pipeNode = layer_node.firstChildElement( QStringLiteral( "pipe" ) ); if ( pipeNode.isNull() ) // old project { pipeNode = layer_node; } //rasterlayerproperties element there -> old format (1.8 and early 1.9) - if ( !layer_node.firstChildElement( "rasterproperties" ).isNull() ) + if ( !layer_node.firstChildElement( QStringLiteral( "rasterproperties" ) ).isNull() ) { //copy node because layer_node is const QDomNode layerNodeCopy = layer_node.cloneNode(); QDomDocument doc = layerNodeCopy.ownerDocument(); - QDomElement rasterPropertiesElem = layerNodeCopy.firstChildElement( "rasterproperties" ); + QDomElement rasterPropertiesElem = layerNodeCopy.firstChildElement( QStringLiteral( "rasterproperties" ) ); QgsProjectFileTransform::convertRasterProperties( doc, layerNodeCopy, rasterPropertiesElem, this ); - rasterRendererElem = layerNodeCopy.firstChildElement( "rasterrenderer" ); + rasterRendererElem = layerNodeCopy.firstChildElement( QStringLiteral( "rasterrenderer" ) ); QgsDebugMsgLevel( doc.toString(), 4 ); } else { - rasterRendererElem = pipeNode.firstChildElement( "rasterrenderer" ); + rasterRendererElem = pipeNode.firstChildElement( QStringLiteral( "rasterrenderer" ) ); } if ( !rasterRendererElem.isNull() ) { - QString rendererType = rasterRendererElem.attribute( "type" ); + QString rendererType = rasterRendererElem.attribute( QStringLiteral( "type" ) ); QgsRasterRendererRegistryEntry rendererEntry; if ( QgsRasterRendererRegistry::instance()->rendererData( rendererType, rendererEntry ) ) { @@ -1156,7 +1156,7 @@ bool QgsRasterLayer::readSymbology( const QDomNode& layer_node, QString& errorMe mPipe.set( brightnessFilter ); //brightness coefficient - QDomElement brightnessElem = pipeNode.firstChildElement( "brightnesscontrast" ); + QDomElement brightnessElem = pipeNode.firstChildElement( QStringLiteral( "brightnesscontrast" ) ); if ( !brightnessElem.isNull() ) { brightnessFilter->readXml( brightnessElem ); @@ -1167,7 +1167,7 @@ bool QgsRasterLayer::readSymbology( const QDomNode& layer_node, QString& errorMe mPipe.set( hueSaturationFilter ); //saturation coefficient - QDomElement hueSaturationElem = pipeNode.firstChildElement( "huesaturation" ); + QDomElement hueSaturationElem = pipeNode.firstChildElement( QStringLiteral( "huesaturation" ) ); if ( !hueSaturationElem.isNull() ) { hueSaturationFilter->readXml( hueSaturationElem ); @@ -1178,14 +1178,14 @@ bool QgsRasterLayer::readSymbology( const QDomNode& layer_node, QString& errorMe mPipe.set( resampleFilter ); //max oversampling - QDomElement resampleElem = pipeNode.firstChildElement( "rasterresampler" ); + QDomElement resampleElem = pipeNode.firstChildElement( QStringLiteral( "rasterresampler" ) ); if ( !resampleElem.isNull() ) { resampleFilter->readXml( resampleElem ); } // get and set the blend mode if it exists - QDomNode blendModeNode = layer_node.namedItem( "blendMode" ); + QDomNode blendModeNode = layer_node.namedItem( QStringLiteral( "blendMode" ) ); if ( !blendModeNode.isNull() ) { QDomElement e = blendModeNode.toElement(); @@ -1214,11 +1214,11 @@ bool QgsRasterLayer::readXml( const QDomNode& layer_node ) //! @note Make sure to read the file first so stats etc are initialized properly! //process provider key - QDomNode pkeyNode = layer_node.namedItem( "provider" ); + QDomNode pkeyNode = layer_node.namedItem( QStringLiteral( "provider" ) ); if ( pkeyNode.isNull() ) { - mProviderKey = "gdal"; + mProviderKey = QStringLiteral( "gdal" ); } else { @@ -1226,7 +1226,7 @@ bool QgsRasterLayer::readXml( const QDomNode& layer_node ) mProviderKey = pkeyElt.text(); if ( mProviderKey.isEmpty() ) { - mProviderKey = "gdal"; + mProviderKey = QStringLiteral( "gdal" ); } } @@ -1236,38 +1236,38 @@ bool QgsRasterLayer::readXml( const QDomNode& layer_node ) // Collect provider-specific information - QDomNode rpNode = layer_node.namedItem( "rasterproperties" ); + QDomNode rpNode = layer_node.namedItem( QStringLiteral( "rasterproperties" ) ); - if ( mProviderKey == "wms" ) + if ( mProviderKey == QLatin1String( "wms" ) ) { // >>> BACKWARD COMPATIBILITY < 1.9 // The old WMS URI format does not contain all the information, we add them here. - if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) ) + if ( !mDataSource.contains( QLatin1String( "crs=" ) ) && !mDataSource.contains( QLatin1String( "format=" ) ) ) { QgsDebugMsgLevel( "Old WMS URI format detected -> adding params", 4 ); QgsDataSourceUri uri; uri.setEncodedUri( mDataSource ); - QDomElement layerElement = rpNode.firstChildElement( "wmsSublayer" ); + QDomElement layerElement = rpNode.firstChildElement( QStringLiteral( "wmsSublayer" ) ); while ( !layerElement.isNull() ) { // TODO: sublayer visibility - post-0.8 release timeframe // collect name for the sublayer - uri.setParam( "layers", layerElement.namedItem( "name" ).toElement().text() ); + uri.setParam( QStringLiteral( "layers" ), layerElement.namedItem( QStringLiteral( "name" ) ).toElement().text() ); // collect style for the sublayer - uri.setParam( "styles", layerElement.namedItem( "style" ).toElement().text() ); + uri.setParam( QStringLiteral( "styles" ), layerElement.namedItem( QStringLiteral( "style" ) ).toElement().text() ); - layerElement = layerElement.nextSiblingElement( "wmsSublayer" ); + layerElement = layerElement.nextSiblingElement( QStringLiteral( "wmsSublayer" ) ); } // Collect format - QDomNode formatNode = rpNode.namedItem( "wmsFormat" ); - uri.setParam( "format", rpNode.namedItem( "wmsFormat" ).toElement().text() ); + QDomNode formatNode = rpNode.namedItem( QStringLiteral( "wmsFormat" ) ); + uri.setParam( QStringLiteral( "format" ), rpNode.namedItem( QStringLiteral( "wmsFormat" ) ).toElement().text() ); // WMS CRS URL param should not be mixed with that assigned to the layer. // In the old WMS URI version there was no CRS and layer crs().authid() was used. - uri.setParam( "crs", crs().authid() ); + uri.setParam( QStringLiteral( "crs" ), crs().authid() ); mDataSource = uri.encodedUri(); } // <<< BACKWARD COMPATIBILITY < 1.9 @@ -1280,7 +1280,7 @@ bool QgsRasterLayer::readXml( const QDomNode& layer_node ) bool res = readSymbology( layer_node, theError ); // old wms settings we need to correct - if ( res && mProviderKey == "wms" && ( !renderer() || renderer()->type() != "singlebandcolordata" ) ) + if ( res && mProviderKey == QLatin1String( "wms" ) && ( !renderer() || renderer()->type() != QLatin1String( "singlebandcolordata" ) ) ) { setRendererForDrawingStyle( QgsRaster::SingleBandColorDataStyle ); } @@ -1308,29 +1308,29 @@ bool QgsRasterLayer::readXml( const QDomNode& layer_node ) #endif // Load user no data value - QDomElement noDataElement = layer_node.firstChildElement( "noData" ); + QDomElement noDataElement = layer_node.firstChildElement( QStringLiteral( "noData" ) ); - QDomNodeList noDataBandList = noDataElement.elementsByTagName( "noDataList" ); + QDomNodeList noDataBandList = noDataElement.elementsByTagName( QStringLiteral( "noDataList" ) ); for ( int i = 0; i < noDataBandList.size(); ++i ) { QDomElement bandElement = noDataBandList.at( i ).toElement(); bool ok; - int bandNo = bandElement.attribute( "bandNo" ).toInt( &ok ); + int bandNo = bandElement.attribute( QStringLiteral( "bandNo" ) ).toInt( &ok ); QgsDebugMsgLevel( QString( "bandNo = %1" ).arg( bandNo ), 4 ); if ( ok && ( bandNo > 0 ) && ( bandNo <= mDataProvider->bandCount() ) ) { - mDataProvider->setUseSourceNoDataValue( bandNo, bandElement.attribute( "useSrcNoData" ).toInt() ); + mDataProvider->setUseSourceNoDataValue( bandNo, bandElement.attribute( QStringLiteral( "useSrcNoData" ) ).toInt() ); QgsRasterRangeList myNoDataRangeList; - QDomNodeList rangeList = bandElement.elementsByTagName( "noDataRange" ); + QDomNodeList rangeList = bandElement.elementsByTagName( QStringLiteral( "noDataRange" ) ); myNoDataRangeList.reserve( rangeList.size() ); for ( int j = 0; j < rangeList.size(); ++j ) { QDomElement rangeElement = rangeList.at( j ).toElement(); - QgsRasterRange myNoDataRange( rangeElement.attribute( "min" ).toDouble(), - rangeElement.attribute( "max" ).toDouble() ); + QgsRasterRange myNoDataRange( rangeElement.attribute( QStringLiteral( "min" ) ).toDouble(), + rangeElement.attribute( QStringLiteral( "max" ) ).toDouble() ); QgsDebugMsgLevel( QString( "min = %1 %2" ).arg( rangeElement.attribute( "min" ) ).arg( myNoDataRange.min() ), 4 ); myNoDataRangeList << myNoDataRange; } @@ -1356,7 +1356,7 @@ bool QgsRasterLayer::writeSymbology( QDomNode & layer_node, QDomDocument & docum // Store pipe members (except provider) into pipe element, in future, it will be // possible to add custom filters into the pipe - QDomElement pipeElement = document.createElement( "pipe" ); + QDomElement pipeElement = document.createElement( QStringLiteral( "pipe" ) ); for ( int i = 1; i < mPipe.size(); i++ ) { @@ -1368,7 +1368,7 @@ bool QgsRasterLayer::writeSymbology( QDomNode & layer_node, QDomDocument & docum layer_node.appendChild( pipeElement ); // add blend mode node - QDomElement blendModeElement = document.createElement( "blendMode" ); + QDomElement blendModeElement = document.createElement( QStringLiteral( "blendMode" ) ); QDomText blendModeText = document.createTextNode( QString::number( QgsPainting::getBlendModeEnum( blendMode() ) ) ); blendModeElement.appendChild( blendModeText ); layer_node.appendChild( blendModeElement ); @@ -1399,30 +1399,30 @@ bool QgsRasterLayer::writeXml( QDomNode & layer_node, return false; } - mapLayerNode.setAttribute( "type", "raster" ); + mapLayerNode.setAttribute( QStringLiteral( "type" ), QStringLiteral( "raster" ) ); // add provider node - QDomElement provider = document.createElement( "provider" ); + QDomElement provider = document.createElement( QStringLiteral( "provider" ) ); QDomText providerText = document.createTextNode( mProviderKey ); provider.appendChild( providerText ); layer_node.appendChild( provider ); // User no data - QDomElement noData = document.createElement( "noData" ); + QDomElement noData = document.createElement( QStringLiteral( "noData" ) ); for ( int bandNo = 1; bandNo <= mDataProvider->bandCount(); bandNo++ ) { - QDomElement noDataRangeList = document.createElement( "noDataList" ); - noDataRangeList.setAttribute( "bandNo", bandNo ); - noDataRangeList.setAttribute( "useSrcNoData", mDataProvider->useSourceNoDataValue( bandNo ) ); + QDomElement noDataRangeList = document.createElement( QStringLiteral( "noDataList" ) ); + noDataRangeList.setAttribute( QStringLiteral( "bandNo" ), bandNo ); + noDataRangeList.setAttribute( QStringLiteral( "useSrcNoData" ), mDataProvider->useSourceNoDataValue( bandNo ) ); Q_FOREACH ( QgsRasterRange range, mDataProvider->userNoDataValues( bandNo ) ) { - QDomElement noDataRange = document.createElement( "noDataRange" ); + QDomElement noDataRange = document.createElement( QStringLiteral( "noDataRange" ) ); - noDataRange.setAttribute( "min", QgsRasterBlock::printValue( range.min() ) ); - noDataRange.setAttribute( "max", QgsRasterBlock::printValue( range.max() ) ); + noDataRange.setAttribute( QStringLiteral( "min" ), QgsRasterBlock::printValue( range.min() ) ); + noDataRange.setAttribute( QStringLiteral( "max" ), QgsRasterBlock::printValue( range.max() ) ); noDataRangeList.appendChild( noDataRange ); } diff --git a/src/core/raster/qgsrasterprojector.cpp b/src/core/raster/qgsrasterprojector.cpp index 508eb5fac874..10cdad91677b 100644 --- a/src/core/raster/qgsrasterprojector.cpp +++ b/src/core/raster/qgsrasterprojector.cpp @@ -292,7 +292,7 @@ QString ProjectorData::cpToString() for ( int j = 0; j < mCPCols; j++ ) { if ( j > 0 ) - myString += " "; + myString += QLatin1String( " " ); QgsPoint myPoint = mCPMatrix[i][j]; if ( mCPLegalMatrix[i][j] ) { @@ -300,7 +300,7 @@ QString ProjectorData::cpToString() } else { - myString += "(-,-)"; + myString += QLatin1String( "(-,-)" ); } } } @@ -742,7 +742,7 @@ QString QgsRasterProjector::precisionLabel( Precision precision ) case Exact: return tr( "Exact" ); } - return "Unknown"; + return QStringLiteral( "Unknown" ); } QgsRasterBlock * QgsRasterProjector::block( int bandNo, QgsRectangle const & extent, int width, int height, QgsRasterBlockFeedback* feedback ) diff --git a/src/core/raster/qgsrasterrenderer.cpp b/src/core/raster/qgsrasterrenderer.cpp index 31fa0c17bda0..251b1a533652 100644 --- a/src/core/raster/qgsrasterrenderer.cpp +++ b/src/core/raster/qgsrasterrenderer.cpp @@ -104,9 +104,9 @@ void QgsRasterRenderer::_writeXml( QDomDocument& doc, QDomElement& rasterRendere return; } - rasterRendererElem.setAttribute( "type", mType ); - rasterRendererElem.setAttribute( "opacity", QString::number( mOpacity ) ); - rasterRendererElem.setAttribute( "alphaBand", mAlphaBand ); + rasterRendererElem.setAttribute( QStringLiteral( "type" ), mType ); + rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QString::number( mOpacity ) ); + rasterRendererElem.setAttribute( QStringLiteral( "alphaBand" ), mAlphaBand ); if ( mRasterTransparency ) { @@ -121,11 +121,11 @@ void QgsRasterRenderer::readXml( const QDomElement& rendererElem ) return; } - mType = rendererElem.attribute( "type" ); - mOpacity = rendererElem.attribute( "opacity", "1.0" ).toDouble(); - mAlphaBand = rendererElem.attribute( "alphaBand", "-1" ).toInt(); + mType = rendererElem.attribute( QStringLiteral( "type" ) ); + mOpacity = rendererElem.attribute( QStringLiteral( "opacity" ), QStringLiteral( "1.0" ) ).toDouble(); + mAlphaBand = rendererElem.attribute( QStringLiteral( "alphaBand" ), QStringLiteral( "-1" ) ).toInt(); - QDomElement rasterTransparencyElem = rendererElem.firstChildElement( "rasterTransparency" ); + QDomElement rasterTransparencyElem = rendererElem.firstChildElement( QStringLiteral( "rasterTransparency" ) ); if ( !rasterTransparencyElem.isNull() ) { delete mRasterTransparency; @@ -148,43 +148,43 @@ QString QgsRasterRenderer::minMaxOriginName( int theOrigin ) { if ( theOrigin == MinMaxUnknown ) { - return "Unknown"; + return QStringLiteral( "Unknown" ); } else if ( theOrigin == MinMaxUser ) { - return "User"; + return QStringLiteral( "User" ); } QString name; if ( theOrigin & MinMaxMinMax ) { - name += "MinMax"; + name += QLatin1String( "MinMax" ); } else if ( theOrigin & MinMaxCumulativeCut ) { - name += "CumulativeCut"; + name += QLatin1String( "CumulativeCut" ); } else if ( theOrigin & MinMaxStdDev ) { - name += "StdDev"; + name += QLatin1String( "StdDev" ); } if ( theOrigin & MinMaxFullExtent ) { - name += "FullExtent"; + name += QLatin1String( "FullExtent" ); } else if ( theOrigin & MinMaxSubExtent ) { - name += "SubExtent"; + name += QLatin1String( "SubExtent" ); } if ( theOrigin & MinMaxEstimated ) { - name += "Estimated"; + name += QLatin1String( "Estimated" ); } else if ( theOrigin & MinMaxExact ) { - name += "Exact"; + name += QLatin1String( "Exact" ); } return name; } @@ -246,44 +246,44 @@ QString QgsRasterRenderer::minMaxOriginLabel( int theOrigin ) int QgsRasterRenderer::minMaxOriginFromName( const QString& theName ) { - if ( theName.contains( "Unknown" ) ) + if ( theName.contains( QLatin1String( "Unknown" ) ) ) { return MinMaxUnknown; } - else if ( theName.contains( "User" ) ) + else if ( theName.contains( QLatin1String( "User" ) ) ) { return MinMaxUser; } int origin = 0; - if ( theName.contains( "MinMax" ) ) + if ( theName.contains( QLatin1String( "MinMax" ) ) ) { origin |= MinMaxMinMax; } - else if ( theName.contains( "CumulativeCut" ) ) + else if ( theName.contains( QLatin1String( "CumulativeCut" ) ) ) { origin |= MinMaxCumulativeCut; } - else if ( theName.contains( "StdDev" ) ) + else if ( theName.contains( QLatin1String( "StdDev" ) ) ) { origin |= MinMaxStdDev; } - if ( theName.contains( "FullExtent" ) ) + if ( theName.contains( QLatin1String( "FullExtent" ) ) ) { origin |= MinMaxFullExtent; } - else if ( theName.contains( "SubExtent" ) ) + else if ( theName.contains( QLatin1String( "SubExtent" ) ) ) { origin |= MinMaxSubExtent; } - if ( theName.contains( "Estimated" ) ) + if ( theName.contains( QLatin1String( "Estimated" ) ) ) { origin |= MinMaxEstimated; } - else if ( theName.contains( "Exact" ) ) + else if ( theName.contains( QLatin1String( "Exact" ) ) ) { origin |= MinMaxExact; } diff --git a/src/core/raster/qgsrasterrenderer.h b/src/core/raster/qgsrasterrenderer.h index d6ef8b9c8bb5..bc1ae595b563 100644 --- a/src/core/raster/qgsrasterrenderer.h +++ b/src/core/raster/qgsrasterrenderer.h @@ -55,7 +55,11 @@ class CORE_EXPORT QgsRasterRenderer : public QgsRasterInterface static const QRgb NODATA_COLOR; - QgsRasterRenderer( QgsRasterInterface* input = nullptr, const QString& type = "" ); + /** + * Constructor for QgsRasterRenderer. + */ + QgsRasterRenderer( QgsRasterInterface* input = nullptr, const QString& type = QLatin1String( "" ) ); + virtual ~QgsRasterRenderer(); QgsRasterRenderer * clone() const override = 0; diff --git a/src/core/raster/qgsrasterrendererregistry.cpp b/src/core/raster/qgsrasterrendererregistry.cpp index 74ac67a79f34..e5cf48719ee4 100644 --- a/src/core/raster/qgsrasterrendererregistry.cpp +++ b/src/core/raster/qgsrasterrendererregistry.cpp @@ -58,16 +58,16 @@ QgsRasterRendererRegistry* QgsRasterRendererRegistry::instance() QgsRasterRendererRegistry::QgsRasterRendererRegistry() { // insert items in a particular order, which is returned in renderersList() - insert( QgsRasterRendererRegistryEntry( "multibandcolor", QObject::tr( "Multiband color" ), + insert( QgsRasterRendererRegistryEntry( QStringLiteral( "multibandcolor" ), QObject::tr( "Multiband color" ), QgsMultiBandColorRenderer::create, nullptr ) ); - insert( QgsRasterRendererRegistryEntry( "paletted", QObject::tr( "Paletted" ), QgsPalettedRasterRenderer::create, nullptr ) ); - insert( QgsRasterRendererRegistryEntry( "singlebandgray", QObject::tr( "Singleband gray" ), + insert( QgsRasterRendererRegistryEntry( QStringLiteral( "paletted" ), QObject::tr( "Paletted" ), QgsPalettedRasterRenderer::create, nullptr ) ); + insert( QgsRasterRendererRegistryEntry( QStringLiteral( "singlebandgray" ), QObject::tr( "Singleband gray" ), QgsSingleBandGrayRenderer::create, nullptr ) ); - insert( QgsRasterRendererRegistryEntry( "singlebandpseudocolor", QObject::tr( "Singleband pseudocolor" ), + insert( QgsRasterRendererRegistryEntry( QStringLiteral( "singlebandpseudocolor" ), QObject::tr( "Singleband pseudocolor" ), QgsSingleBandPseudoColorRenderer::create, nullptr ) ); - insert( QgsRasterRendererRegistryEntry( "singlebandcolordata", QObject::tr( "Singleband color data" ), + insert( QgsRasterRendererRegistryEntry( QStringLiteral( "singlebandcolordata" ), QObject::tr( "Singleband color data" ), QgsSingleBandColorDataRenderer::create, nullptr ) ); - insert( QgsRasterRendererRegistryEntry( "hillshade", QObject::tr( "Hillshade" ), + insert( QgsRasterRendererRegistryEntry( QStringLiteral( "hillshade" ), QObject::tr( "Hillshade" ), QgsHillshadeRenderer::create, nullptr ) ); } @@ -191,17 +191,17 @@ QgsRasterRenderer* QgsRasterRendererRegistry::defaultRendererForDrawingStyle( Qg { QSettings s; - int redBand = s.value( "/Raster/defaultRedBand", 1 ).toInt(); + int redBand = s.value( QStringLiteral( "/Raster/defaultRedBand" ), 1 ).toInt(); if ( redBand < 0 || redBand > provider->bandCount() ) { redBand = -1; } - int greenBand = s.value( "/Raster/defaultGreenBand", 2 ).toInt(); + int greenBand = s.value( QStringLiteral( "/Raster/defaultGreenBand" ), 2 ).toInt(); if ( greenBand < 0 || greenBand > provider->bandCount() ) { greenBand = -1; } - int blueBand = s.value( "/Raster/defaultBlueBand", 3 ).toInt(); + int blueBand = s.value( QStringLiteral( "/Raster/defaultBlueBand" ), 3 ).toInt(); if ( blueBand < 0 || blueBand > provider->bandCount() ) { blueBand = -1; @@ -246,11 +246,11 @@ bool QgsRasterRendererRegistry::minMaxValuesForBand( int band, QgsRasterDataProv maxValue = 0; QSettings s; - if ( s.value( "/Raster/useStandardDeviation", false ).toBool() ) + if ( s.value( QStringLiteral( "/Raster/useStandardDeviation" ), false ).toBool() ) { QgsRasterBandStats stats = provider->bandStatistics( band, QgsRasterBandStats::Mean | QgsRasterBandStats::StdDev ); - double stdDevFactor = s.value( "/Raster/defaultStandardDeviation", 2.0 ).toDouble(); + double stdDevFactor = s.value( QStringLiteral( "/Raster/defaultStandardDeviation" ), 2.0 ).toDouble(); double diff = stdDevFactor * stats.stdDev; minValue = stats.mean - diff; maxValue = stats.mean + diff; diff --git a/src/core/raster/qgsrasterresamplefilter.cpp b/src/core/raster/qgsrasterresamplefilter.cpp index ad50896c0e02..a2f5340510d2 100644 --- a/src/core/raster/qgsrasterresamplefilter.cpp +++ b/src/core/raster/qgsrasterresamplefilter.cpp @@ -230,16 +230,16 @@ void QgsRasterResampleFilter::writeXml( QDomDocument& doc, QDomElement& parentEl return; } - QDomElement rasterRendererElem = doc.createElement( "rasterresampler" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterresampler" ) ); - rasterRendererElem.setAttribute( "maxOversampling", QString::number( mMaxOversampling ) ); + rasterRendererElem.setAttribute( QStringLiteral( "maxOversampling" ), QString::number( mMaxOversampling ) ); if ( mZoomedInResampler ) { - rasterRendererElem.setAttribute( "zoomedInResampler", mZoomedInResampler->type() ); + rasterRendererElem.setAttribute( QStringLiteral( "zoomedInResampler" ), mZoomedInResampler->type() ); } if ( mZoomedOutResampler ) { - rasterRendererElem.setAttribute( "zoomedOutResampler", mZoomedOutResampler->type() ); + rasterRendererElem.setAttribute( QStringLiteral( "zoomedOutResampler" ), mZoomedOutResampler->type() ); } parentElem.appendChild( rasterRendererElem ); } @@ -251,20 +251,20 @@ void QgsRasterResampleFilter::readXml( const QDomElement& filterElem ) return; } - mMaxOversampling = filterElem.attribute( "maxOversampling", "2.0" ).toDouble(); + mMaxOversampling = filterElem.attribute( QStringLiteral( "maxOversampling" ), QStringLiteral( "2.0" ) ).toDouble(); - QString zoomedInResamplerType = filterElem.attribute( "zoomedInResampler" ); - if ( zoomedInResamplerType == "bilinear" ) + QString zoomedInResamplerType = filterElem.attribute( QStringLiteral( "zoomedInResampler" ) ); + if ( zoomedInResamplerType == QLatin1String( "bilinear" ) ) { mZoomedInResampler = new QgsBilinearRasterResampler(); } - else if ( zoomedInResamplerType == "cubic" ) + else if ( zoomedInResamplerType == QLatin1String( "cubic" ) ) { mZoomedInResampler = new QgsCubicRasterResampler(); } - QString zoomedOutResamplerType = filterElem.attribute( "zoomedOutResampler" ); - if ( zoomedOutResamplerType == "bilinear" ) + QString zoomedOutResamplerType = filterElem.attribute( QStringLiteral( "zoomedOutResampler" ) ); + if ( zoomedOutResamplerType == QLatin1String( "bilinear" ) ) { mZoomedOutResampler = new QgsBilinearRasterResampler(); } diff --git a/src/core/raster/qgsrastershader.cpp b/src/core/raster/qgsrastershader.cpp index 47005cbdbcf2..79b8b7853208 100644 --- a/src/core/raster/qgsrastershader.cpp +++ b/src/core/raster/qgsrastershader.cpp @@ -138,23 +138,23 @@ void QgsRasterShader::writeXml( QDomDocument& doc, QDomElement& parent ) const return; } - QDomElement rasterShaderElem = doc.createElement( "rastershader" ); + QDomElement rasterShaderElem = doc.createElement( QStringLiteral( "rastershader" ) ); QgsColorRampShader* colorRampShader = dynamic_cast<QgsColorRampShader*>( mRasterShaderFunction ); if ( colorRampShader ) { - QDomElement colorRampShaderElem = doc.createElement( "colorrampshader" ); - colorRampShaderElem.setAttribute( "colorRampType", colorRampShader->colorRampTypeAsQString() ); - colorRampShaderElem.setAttribute( "clip", colorRampShader->clip() ); + QDomElement colorRampShaderElem = doc.createElement( QStringLiteral( "colorrampshader" ) ); + colorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), colorRampShader->colorRampTypeAsQString() ); + colorRampShaderElem.setAttribute( QStringLiteral( "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", QgsRasterBlock::printValue( itemIt->value ) ); - itemElem.setAttribute( "color", itemIt->color.name() ); - itemElem.setAttribute( "alpha", itemIt->color.alpha() ); + QDomElement itemElem = doc.createElement( QStringLiteral( "item" ) ); + itemElem.setAttribute( QStringLiteral( "label" ), itemIt->label ); + itemElem.setAttribute( QStringLiteral( "value" ), QgsRasterBlock::printValue( itemIt->value ) ); + itemElem.setAttribute( QStringLiteral( "color" ), itemIt->color.name() ); + itemElem.setAttribute( QStringLiteral( "alpha" ), itemIt->color.alpha() ); colorRampShaderElem.appendChild( itemElem ); } rasterShaderElem.appendChild( colorRampShaderElem ); @@ -165,12 +165,12 @@ void QgsRasterShader::writeXml( QDomDocument& doc, QDomElement& parent ) const void QgsRasterShader::readXml( const QDomElement& elem ) { //only colorrampshader - QDomElement colorRampShaderElem = elem.firstChildElement( "colorrampshader" ); + QDomElement colorRampShaderElem = elem.firstChildElement( QStringLiteral( "colorrampshader" ) ); if ( !colorRampShaderElem.isNull() ) { QgsColorRampShader* colorRampShader = new QgsColorRampShader(); - colorRampShader->setColorRampType( colorRampShaderElem.attribute( "colorRampType", "INTERPOLATED" ) ); - colorRampShader->setClip( colorRampShaderElem.attribute( "clip", "0" ) == "1" ); + colorRampShader->setColorRampType( colorRampShaderElem.attribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) ) ); + colorRampShader->setClip( colorRampShaderElem.attribute( QStringLiteral( "clip" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); QList<QgsColorRampShader::ColorRampItem> itemList; QDomElement itemElem; @@ -178,15 +178,15 @@ void QgsRasterShader::readXml( const QDomElement& elem ) double itemValue; QColor itemColor; - QDomNodeList itemNodeList = colorRampShaderElem.elementsByTagName( "item" ); + QDomNodeList itemNodeList = colorRampShaderElem.elementsByTagName( QStringLiteral( "item" ) ); itemList.reserve( itemNodeList.size() ); for ( int i = 0; i < itemNodeList.size(); ++i ) { itemElem = itemNodeList.at( i ).toElement(); - itemValue = itemElem.attribute( "value" ).toDouble(); - itemLabel = itemElem.attribute( "label" ); - itemColor.setNamedColor( itemElem.attribute( "color" ) ); - itemColor.setAlpha( itemElem.attribute( "alpha", "255" ).toInt() ); + itemValue = itemElem.attribute( QStringLiteral( "value" ) ).toDouble(); + itemLabel = itemElem.attribute( QStringLiteral( "label" ) ); + itemColor.setNamedColor( itemElem.attribute( QStringLiteral( "color" ) ) ); + itemColor.setAlpha( itemElem.attribute( QStringLiteral( "alpha" ), QStringLiteral( "255" ) ).toInt() ); itemList.push_back( QgsColorRampShader::ColorRampItem( itemValue, itemColor, itemLabel ) ); } diff --git a/src/core/raster/qgsrastertransparency.cpp b/src/core/raster/qgsrastertransparency.cpp index c599cf00fa0f..8142cf1c4512 100644 --- a/src/core/raster/qgsrastertransparency.cpp +++ b/src/core/raster/qgsrastertransparency.cpp @@ -184,17 +184,17 @@ bool QgsRasterTransparency::isEmpty() const void QgsRasterTransparency::writeXml( QDomDocument& doc, QDomElement& parentElem ) const { - QDomElement rasterTransparencyElem = doc.createElement( "rasterTransparency" ); + QDomElement rasterTransparencyElem = doc.createElement( QStringLiteral( "rasterTransparency" ) ); if ( !mTransparentSingleValuePixelList.isEmpty() ) { - QDomElement singleValuePixelListElement = doc.createElement( "singleValuePixelList" ); + QDomElement singleValuePixelListElement = doc.createElement( QStringLiteral( "singleValuePixelList" ) ); QList<QgsRasterTransparency::TransparentSingleValuePixel>::const_iterator it = mTransparentSingleValuePixelList.constBegin(); for ( ; it != mTransparentSingleValuePixelList.constEnd(); ++it ) { - QDomElement pixelListElement = doc.createElement( "pixelListEntry" ); - pixelListElement.setAttribute( "min", QgsRasterBlock::printValue( it->min ) ); - pixelListElement.setAttribute( "max", QgsRasterBlock::printValue( it->max ) ); - pixelListElement.setAttribute( "percentTransparent", QString::number( it->percentTransparent ) ); + QDomElement pixelListElement = doc.createElement( QStringLiteral( "pixelListEntry" ) ); + pixelListElement.setAttribute( QStringLiteral( "min" ), QgsRasterBlock::printValue( it->min ) ); + pixelListElement.setAttribute( QStringLiteral( "max" ), QgsRasterBlock::printValue( it->max ) ); + pixelListElement.setAttribute( QStringLiteral( "percentTransparent" ), QString::number( it->percentTransparent ) ); singleValuePixelListElement.appendChild( pixelListElement ); } rasterTransparencyElem.appendChild( singleValuePixelListElement ); @@ -202,15 +202,15 @@ void QgsRasterTransparency::writeXml( QDomDocument& doc, QDomElement& parentElem } if ( !mTransparentThreeValuePixelList.isEmpty() ) { - QDomElement threeValuePixelListElement = doc.createElement( "threeValuePixelList" ); + QDomElement threeValuePixelListElement = doc.createElement( QStringLiteral( "threeValuePixelList" ) ); QList<QgsRasterTransparency::TransparentThreeValuePixel>::const_iterator it = mTransparentThreeValuePixelList.constBegin(); for ( ; it != mTransparentThreeValuePixelList.constEnd(); ++it ) { - QDomElement pixelListElement = doc.createElement( "pixelListEntry" ); - pixelListElement.setAttribute( "red", QgsRasterBlock::printValue( it->red ) ); - pixelListElement.setAttribute( "green", QgsRasterBlock::printValue( it->green ) ); - pixelListElement.setAttribute( "blue", QgsRasterBlock::printValue( it->blue ) ); - pixelListElement.setAttribute( "percentTransparent", QString::number( it->percentTransparent ) ); + QDomElement pixelListElement = doc.createElement( QStringLiteral( "pixelListEntry" ) ); + pixelListElement.setAttribute( QStringLiteral( "red" ), QgsRasterBlock::printValue( it->red ) ); + pixelListElement.setAttribute( QStringLiteral( "green" ), QgsRasterBlock::printValue( it->green ) ); + pixelListElement.setAttribute( QStringLiteral( "blue" ), QgsRasterBlock::printValue( it->blue ) ); + pixelListElement.setAttribute( QStringLiteral( "percentTransparent" ), QString::number( it->percentTransparent ) ); threeValuePixelListElement.appendChild( pixelListElement ); } rasterTransparencyElem.appendChild( threeValuePixelListElement ); @@ -229,40 +229,40 @@ void QgsRasterTransparency::readXml( const QDomElement& elem ) mTransparentThreeValuePixelList.clear(); QDomElement currentEntryElem; - QDomElement singlePixelListElem = elem.firstChildElement( "singleValuePixelList" ); + QDomElement singlePixelListElem = elem.firstChildElement( QStringLiteral( "singleValuePixelList" ) ); if ( !singlePixelListElem.isNull() ) { - QDomNodeList entryList = singlePixelListElem.elementsByTagName( "pixelListEntry" ); + QDomNodeList entryList = singlePixelListElem.elementsByTagName( QStringLiteral( "pixelListEntry" ) ); TransparentSingleValuePixel sp; for ( int i = 0; i < entryList.size(); ++i ) { currentEntryElem = entryList.at( i ).toElement(); - sp.percentTransparent = currentEntryElem.attribute( "percentTransparent" ).toDouble(); + sp.percentTransparent = currentEntryElem.attribute( QStringLiteral( "percentTransparent" ) ).toDouble(); // Backward compoatibility < 1.9 : pixelValue (before ranges) - if ( currentEntryElem.hasAttribute( "pixelValue" ) ) + if ( currentEntryElem.hasAttribute( QStringLiteral( "pixelValue" ) ) ) { - sp.min = sp.max = currentEntryElem.attribute( "pixelValue" ).toDouble(); + sp.min = sp.max = currentEntryElem.attribute( QStringLiteral( "pixelValue" ) ).toDouble(); } else { - sp.min = currentEntryElem.attribute( "min" ).toDouble(); - sp.max = currentEntryElem.attribute( "max" ).toDouble(); + sp.min = currentEntryElem.attribute( QStringLiteral( "min" ) ).toDouble(); + sp.max = currentEntryElem.attribute( QStringLiteral( "max" ) ).toDouble(); } mTransparentSingleValuePixelList.append( sp ); } } - QDomElement threeValuePixelListElem = elem.firstChildElement( "threeValuePixelList" ); + QDomElement threeValuePixelListElem = elem.firstChildElement( QStringLiteral( "threeValuePixelList" ) ); if ( !threeValuePixelListElem.isNull() ) { - QDomNodeList entryList = threeValuePixelListElem.elementsByTagName( "pixelListEntry" ); + QDomNodeList entryList = threeValuePixelListElem.elementsByTagName( QStringLiteral( "pixelListEntry" ) ); TransparentThreeValuePixel tp; for ( int i = 0; i < entryList.size(); ++i ) { currentEntryElem = entryList.at( i ).toElement(); - tp.red = currentEntryElem.attribute( "red" ).toDouble(); - tp.green = currentEntryElem.attribute( "green" ).toDouble(); - tp.blue = currentEntryElem.attribute( "blue" ).toDouble(); - tp.percentTransparent = currentEntryElem.attribute( "percentTransparent" ).toDouble(); + tp.red = currentEntryElem.attribute( QStringLiteral( "red" ) ).toDouble(); + tp.green = currentEntryElem.attribute( QStringLiteral( "green" ) ).toDouble(); + tp.blue = currentEntryElem.attribute( QStringLiteral( "blue" ) ).toDouble(); + tp.percentTransparent = currentEntryElem.attribute( QStringLiteral( "percentTransparent" ) ).toDouble(); mTransparentThreeValuePixelList.append( tp ); } } diff --git a/src/core/raster/qgssinglebandcolordatarenderer.cpp b/src/core/raster/qgssinglebandcolordatarenderer.cpp index 3a50e1cd055c..7b422cd41c33 100644 --- a/src/core/raster/qgssinglebandcolordatarenderer.cpp +++ b/src/core/raster/qgssinglebandcolordatarenderer.cpp @@ -23,7 +23,7 @@ #include <QImage> QgsSingleBandColorDataRenderer::QgsSingleBandColorDataRenderer( QgsRasterInterface* input, int band ): - QgsRasterRenderer( input, "singlebandcolordata" ), mBand( band ) + QgsRasterRenderer( input, QStringLiteral( "singlebandcolordata" ) ), mBand( band ) { } @@ -46,7 +46,7 @@ QgsRasterRenderer* QgsSingleBandColorDataRenderer::create( const QDomElement& el return nullptr; } - int band = elem.attribute( "band", "-1" ).toInt(); + int band = elem.attribute( QStringLiteral( "band" ), QStringLiteral( "-1" ) ).toInt(); QgsRasterRenderer* r = new QgsSingleBandColorDataRenderer( input, band ); r->readXml( elem ); return r; @@ -105,9 +105,9 @@ void QgsSingleBandColorDataRenderer::writeXml( QDomDocument& doc, QDomElement& p if ( parentElem.isNull() ) return; - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); _writeXml( doc, rasterRendererElem ); - rasterRendererElem.setAttribute( "band", mBand ); + rasterRendererElem.setAttribute( QStringLiteral( "band" ), mBand ); parentElem.appendChild( rasterRendererElem ); } diff --git a/src/core/raster/qgssinglebandgrayrenderer.cpp b/src/core/raster/qgssinglebandgrayrenderer.cpp index 6f17bb9e0eda..cf7008806859 100644 --- a/src/core/raster/qgssinglebandgrayrenderer.cpp +++ b/src/core/raster/qgssinglebandgrayrenderer.cpp @@ -24,7 +24,7 @@ #include <QColor> QgsSingleBandGrayRenderer::QgsSingleBandGrayRenderer( QgsRasterInterface* input, int grayBand ): - QgsRasterRenderer( input, "singlebandgray" ), mGrayBand( grayBand ), mGradient( BlackToWhite ), mContrastEnhancement( nullptr ) + QgsRasterRenderer( input, QStringLiteral( "singlebandgray" ) ), mGrayBand( grayBand ), mGradient( BlackToWhite ), mContrastEnhancement( nullptr ) { } @@ -53,16 +53,16 @@ QgsRasterRenderer* QgsSingleBandGrayRenderer::create( const QDomElement& elem, Q return nullptr; } - int grayBand = elem.attribute( "grayBand", "-1" ).toInt(); + int grayBand = elem.attribute( QStringLiteral( "grayBand" ), QStringLiteral( "-1" ) ).toInt(); QgsSingleBandGrayRenderer* r = new QgsSingleBandGrayRenderer( input, grayBand ); r->readXml( elem ); - if ( elem.attribute( "gradient" ) == "WhiteToBlack" ) + if ( elem.attribute( QStringLiteral( "gradient" ) ) == QLatin1String( "WhiteToBlack" ) ) { r->setGradient( WhiteToBlack ); // BlackToWhite is default } - QDomElement contrastEnhancementElem = elem.firstChildElement( "contrastEnhancement" ); + QDomElement contrastEnhancementElem = elem.firstChildElement( QStringLiteral( "contrastEnhancement" ) ); if ( !contrastEnhancementElem.isNull() ) { QgsContrastEnhancement* ce = new QgsContrastEnhancement(( Qgis::DataType )( @@ -184,25 +184,25 @@ void QgsSingleBandGrayRenderer::writeXml( QDomDocument& doc, QDomElement& parent return; } - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); _writeXml( doc, rasterRendererElem ); - rasterRendererElem.setAttribute( "grayBand", mGrayBand ); + rasterRendererElem.setAttribute( QStringLiteral( "grayBand" ), mGrayBand ); QString gradient; if ( mGradient == BlackToWhite ) { - gradient = "BlackToWhite"; + gradient = QStringLiteral( "BlackToWhite" ); } else { - gradient = "WhiteToBlack"; + gradient = QStringLiteral( "WhiteToBlack" ); } - rasterRendererElem.setAttribute( "gradient", gradient ); + rasterRendererElem.setAttribute( QStringLiteral( "gradient" ), gradient ); if ( mContrastEnhancement ) { - QDomElement contrastElem = doc.createElement( "contrastEnhancement" ); + QDomElement contrastElem = doc.createElement( QStringLiteral( "contrastEnhancement" ) ); mContrastEnhancement->writeXml( doc, contrastElem ); rasterRendererElem.appendChild( contrastElem ); } diff --git a/src/core/raster/qgssinglebandpseudocolorrenderer.cpp b/src/core/raster/qgssinglebandpseudocolorrenderer.cpp index 1b5bd43679dd..bcf4f0807763 100644 --- a/src/core/raster/qgssinglebandpseudocolorrenderer.cpp +++ b/src/core/raster/qgssinglebandpseudocolorrenderer.cpp @@ -25,7 +25,7 @@ #include <QImage> QgsSingleBandPseudoColorRenderer::QgsSingleBandPseudoColorRenderer( QgsRasterInterface* input, int band, QgsRasterShader* shader ): - QgsRasterRenderer( input, "singlebandpseudocolor" ) + QgsRasterRenderer( input, QStringLiteral( "singlebandpseudocolor" ) ) , mShader( shader ) , mBand( band ) , mClassificationMin( std::numeric_limits<double>::quiet_NaN() ) @@ -88,9 +88,9 @@ QgsRasterRenderer* QgsSingleBandPseudoColorRenderer::create( const QDomElement& return nullptr; } - int band = elem.attribute( "band", "-1" ).toInt(); + int band = elem.attribute( QStringLiteral( "band" ), QStringLiteral( "-1" ) ).toInt(); QgsRasterShader* shader = nullptr; - QDomElement rasterShaderElem = elem.firstChildElement( "rastershader" ); + QDomElement rasterShaderElem = elem.firstChildElement( QStringLiteral( "rastershader" ) ); if ( !rasterShaderElem.isNull() ) { shader = new QgsRasterShader(); @@ -101,9 +101,9 @@ QgsRasterRenderer* QgsSingleBandPseudoColorRenderer::create( const QDomElement& r->readXml( elem ); // TODO: add _readXML in superclass? - r->setClassificationMin( elem.attribute( "classificationMin", "NaN" ).toDouble() ); - r->setClassificationMax( elem.attribute( "classificationMax", "NaN" ).toDouble() ); - r->setClassificationMinMaxOrigin( QgsRasterRenderer::minMaxOriginFromName( elem.attribute( "classificationMinMaxOrigin", "Unknown" ) ) ); + r->setClassificationMin( elem.attribute( QStringLiteral( "classificationMin" ), QStringLiteral( "NaN" ) ).toDouble() ); + r->setClassificationMax( elem.attribute( QStringLiteral( "classificationMax" ), QStringLiteral( "NaN" ) ).toDouble() ); + r->setClassificationMinMaxOrigin( QgsRasterRenderer::minMaxOriginFromName( elem.attribute( QStringLiteral( "classificationMinMaxOrigin" ), QStringLiteral( "Unknown" ) ) ) ); return r; } @@ -215,16 +215,16 @@ void QgsSingleBandPseudoColorRenderer::writeXml( QDomDocument& doc, QDomElement& return; } - QDomElement rasterRendererElem = doc.createElement( "rasterrenderer" ); + QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) ); _writeXml( doc, rasterRendererElem ); - rasterRendererElem.setAttribute( "band", mBand ); + rasterRendererElem.setAttribute( QStringLiteral( "band" ), mBand ); if ( mShader ) { mShader->writeXml( doc, rasterRendererElem ); //todo: include color ramp items directly in this renderer } - rasterRendererElem.setAttribute( "classificationMin", QgsRasterBlock::printValue( mClassificationMin ) ); - rasterRendererElem.setAttribute( "classificationMax", QgsRasterBlock::printValue( mClassificationMax ) ); - rasterRendererElem.setAttribute( "classificationMinMaxOrigin", QgsRasterRenderer::minMaxOriginName( mClassificationMinMaxOrigin ) ); + rasterRendererElem.setAttribute( QStringLiteral( "classificationMin" ), QgsRasterBlock::printValue( mClassificationMin ) ); + rasterRendererElem.setAttribute( QStringLiteral( "classificationMax" ), QgsRasterBlock::printValue( mClassificationMax ) ); + rasterRendererElem.setAttribute( QStringLiteral( "classificationMinMaxOrigin" ), QgsRasterRenderer::minMaxOriginName( mClassificationMinMaxOrigin ) ); parentElem.appendChild( rasterRendererElem ); } diff --git a/src/core/symbology-ng/qgs25drenderer.cpp b/src/core/symbology-ng/qgs25drenderer.cpp index 5fc3ea2b11bc..5098c8fb8cc4 100644 --- a/src/core/symbology-ng/qgs25drenderer.cpp +++ b/src/core/symbology-ng/qgs25drenderer.cpp @@ -60,7 +60,7 @@ ")" Qgs25DRenderer::Qgs25DRenderer() - : QgsFeatureRenderer( "25dRenderer" ) + : QgsFeatureRenderer( QStringLiteral( "25dRenderer" ) ) { mSymbol.reset( new QgsFillSymbol() ); @@ -69,13 +69,13 @@ Qgs25DRenderer::Qgs25DRenderer() QgsSymbolLayer* floor = QgsSimpleFillSymbolLayer::create(); QgsStringMap wallProperties; - wallProperties.insert( "geometryModifier", WALL_EXPRESSION ); - wallProperties.insert( "symbolType", "Fill" ); + wallProperties.insert( QStringLiteral( "geometryModifier" ), WALL_EXPRESSION ); + wallProperties.insert( QStringLiteral( "symbolType" ), QStringLiteral( "Fill" ) ); QgsSymbolLayer* walls = QgsGeometryGeneratorSymbolLayer::create( wallProperties ); QgsStringMap roofProperties; - roofProperties.insert( "geometryModifier", ROOF_EXPRESSION ); - roofProperties.insert( "symbolType", "Fill" ); + roofProperties.insert( QStringLiteral( "geometryModifier" ), ROOF_EXPRESSION ); + roofProperties.insert( QStringLiteral( "symbolType" ), QStringLiteral( "Fill" ) ); QgsSymbolLayer* roof = QgsGeometryGeneratorSymbolLayer::create( roofProperties ); floor->setLocked( true ); @@ -96,7 +96,7 @@ Qgs25DRenderer::Qgs25DRenderer() setRoofColor( QColor( "#b1a97c" ) ); setWallColor( QColor( "#777777" ) ); - wallLayer()->setDataDefinedProperty( "color", new QgsDataDefined( QString( WALL_SHADING_EXPRESSION ) ) ); + wallLayer()->setDataDefinedProperty( QStringLiteral( "color" ), new QgsDataDefined( QString( WALL_SHADING_EXPRESSION ) ) ); setShadowSpread( 4 ); setShadowColor( QColor( "#111111" ) ); @@ -114,9 +114,9 @@ QDomElement Qgs25DRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "25dRenderer" ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "25dRenderer" ) ); - QDomElement symbolElem = QgsSymbolLayerUtils::saveSymbol( "symbol", mSymbol.data(), doc ); + QDomElement symbolElem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "symbol" ), mSymbol.data(), doc ); rendererElem.appendChild( symbolElem ); @@ -127,7 +127,7 @@ QgsFeatureRenderer* Qgs25DRenderer::create( QDomElement& element ) { Qgs25DRenderer* renderer = new Qgs25DRenderer(); - QDomNodeList symbols = element.elementsByTagName( "symbol" ); + QDomNodeList symbols = element.elementsByTagName( QStringLiteral( "symbol" ) ); if ( symbols.size() ) { renderer->mSymbol.reset( QgsSymbolLayerUtils::loadSymbol( symbols.at( 0 ).toElement() ) ); @@ -232,12 +232,12 @@ void Qgs25DRenderer::setWallColor( const QColor& wallColor ) void Qgs25DRenderer::setWallShadingEnabled( bool enabled ) { - wallLayer()->getDataDefinedProperty( "color" )->setActive( enabled ); + wallLayer()->getDataDefinedProperty( QStringLiteral( "color" ) )->setActive( enabled ); } bool Qgs25DRenderer::wallShadingEnabled() { - return wallLayer()->getDataDefinedProperty( "color" )->isActive(); + return wallLayer()->getDataDefinedProperty( QStringLiteral( "color" ) )->isActive(); } QColor Qgs25DRenderer::roofColor() const @@ -253,7 +253,7 @@ void Qgs25DRenderer::setRoofColor( const QColor& roofColor ) Qgs25DRenderer* Qgs25DRenderer::convertFromRenderer( QgsFeatureRenderer* renderer ) { - if ( renderer->type() == "25dRenderer" ) + if ( renderer->type() == QLatin1String( "25dRenderer" ) ) { return static_cast<Qgs25DRenderer*>( renderer->clone() ); } diff --git a/src/core/symbology-ng/qgsarrowsymbollayer.cpp b/src/core/symbology-ng/qgsarrowsymbollayer.cpp index eaae0d157048..e91f7fae2b2d 100644 --- a/src/core/symbology-ng/qgsarrowsymbollayer.cpp +++ b/src/core/symbology-ng/qgsarrowsymbollayer.cpp @@ -59,62 +59,62 @@ QgsSymbolLayer* QgsArrowSymbolLayer::create( const QgsStringMap& props ) { QgsArrowSymbolLayer* l = new QgsArrowSymbolLayer(); - if ( props.contains( "arrow_width" ) ) - l->setArrowWidth( props["arrow_width"].toDouble() ); + if ( props.contains( QStringLiteral( "arrow_width" ) ) ) + l->setArrowWidth( props[QStringLiteral( "arrow_width" )].toDouble() ); - if ( props.contains( "arrow_width_unit" ) ) - l->setArrowWidthUnit( QgsUnitTypes::decodeRenderUnit( props["arrow_width_unit"] ) ); + if ( props.contains( QStringLiteral( "arrow_width_unit" ) ) ) + l->setArrowWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "arrow_width_unit" )] ) ); - if ( props.contains( "arrow_width_unit_scale" ) ) - l->setArrowWidthUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["arrow_width_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "arrow_width_unit_scale" ) ) ) + l->setArrowWidthUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "arrow_width_unit_scale" )] ) ); - if ( props.contains( "arrow_start_width" ) ) - l->setArrowStartWidth( props["arrow_start_width"].toDouble() ); + if ( props.contains( QStringLiteral( "arrow_start_width" ) ) ) + l->setArrowStartWidth( props[QStringLiteral( "arrow_start_width" )].toDouble() ); - if ( props.contains( "arrow_start_width_unit" ) ) - l->setArrowStartWidthUnit( QgsUnitTypes::decodeRenderUnit( props["arrow_start_width_unit"] ) ); + if ( props.contains( QStringLiteral( "arrow_start_width_unit" ) ) ) + l->setArrowStartWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "arrow_start_width_unit" )] ) ); - if ( props.contains( "arrow_start_width_unit_scale" ) ) - l->setArrowStartWidthUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["arrow_start_width_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "arrow_start_width_unit_scale" ) ) ) + l->setArrowStartWidthUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "arrow_start_width_unit_scale" )] ) ); - if ( props.contains( "is_curved" ) ) - l->setIsCurved( props["is_curved"].toInt() == 1 ); + if ( props.contains( QStringLiteral( "is_curved" ) ) ) + l->setIsCurved( props[QStringLiteral( "is_curved" )].toInt() == 1 ); - if ( props.contains( "is_repeated" ) ) - l->setIsRepeated( props["is_repeated"].toInt() == 1 ); + if ( props.contains( QStringLiteral( "is_repeated" ) ) ) + l->setIsRepeated( props[QStringLiteral( "is_repeated" )].toInt() == 1 ); - if ( props.contains( "head_length" ) ) - l->setHeadLength( props["head_length"].toDouble() ); + if ( props.contains( QStringLiteral( "head_length" ) ) ) + l->setHeadLength( props[QStringLiteral( "head_length" )].toDouble() ); - if ( props.contains( "head_length_unit" ) ) - l->setHeadLengthUnit( QgsUnitTypes::decodeRenderUnit( props["head_length_unit"] ) ); + if ( props.contains( QStringLiteral( "head_length_unit" ) ) ) + l->setHeadLengthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "head_length_unit" )] ) ); - if ( props.contains( "head_length_unit_scale" ) ) - l->setHeadLengthUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["head_length_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "head_length_unit_scale" ) ) ) + l->setHeadLengthUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "head_length_unit_scale" )] ) ); - if ( props.contains( "head_thickness" ) ) - l->setHeadThickness( props["head_thickness"].toDouble() ); + if ( props.contains( QStringLiteral( "head_thickness" ) ) ) + l->setHeadThickness( props[QStringLiteral( "head_thickness" )].toDouble() ); - if ( props.contains( "head_thickness_unit" ) ) - l->setHeadThicknessUnit( QgsUnitTypes::decodeRenderUnit( props["head_thickness_unit"] ) ); + if ( props.contains( QStringLiteral( "head_thickness_unit" ) ) ) + l->setHeadThicknessUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "head_thickness_unit" )] ) ); - if ( props.contains( "head_thickness_unit_scale" ) ) - l->setHeadThicknessUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["head_thickness_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "head_thickness_unit_scale" ) ) ) + l->setHeadThicknessUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "head_thickness_unit_scale" )] ) ); - if ( props.contains( "head_type" ) ) - l->setHeadType( static_cast<HeadType>( props["head_type"].toInt() ) ); + if ( props.contains( QStringLiteral( "head_type" ) ) ) + l->setHeadType( static_cast<HeadType>( props[QStringLiteral( "head_type" )].toInt() ) ); - if ( props.contains( "arrow_type" ) ) - l->setArrowType( static_cast<ArrowType>( props["arrow_type"].toInt() ) ); + if ( props.contains( QStringLiteral( "arrow_type" ) ) ) + l->setArrowType( static_cast<ArrowType>( props[QStringLiteral( "arrow_type" )].toInt() ) ); - if ( props.contains( "offset" ) ) - l->setOffset( props["offset"].toDouble() ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + l->setOffset( props[QStringLiteral( "offset" )].toDouble() ); - if ( props.contains( "offset_unit" ) ) - l->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + l->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); - if ( props.contains( "offset_unit_scale" ) ) - l->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "offset_unit_scale" ) ) ) + l->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_unit_scale" )] ) ); l->restoreDataDefinedProperties( props ); @@ -134,38 +134,38 @@ QgsArrowSymbolLayer* QgsArrowSymbolLayer::clone() const QString QgsArrowSymbolLayer::layerType() const { - return "ArrowLine"; + return QStringLiteral( "ArrowLine" ); } QgsStringMap QgsArrowSymbolLayer::properties() const { QgsStringMap map; - map["arrow_width"] = QString::number( arrowWidth() ); - map["arrow_width_unit"] = QgsUnitTypes::encodeUnit( arrowWidthUnit() ); - map["arrow_width_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( arrowWidthUnitScale() ); + map[QStringLiteral( "arrow_width" )] = QString::number( arrowWidth() ); + map[QStringLiteral( "arrow_width_unit" )] = QgsUnitTypes::encodeUnit( arrowWidthUnit() ); + map[QStringLiteral( "arrow_width_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( arrowWidthUnitScale() ); - map["arrow_start_width"] = QString::number( arrowStartWidth() ); - map["arrow_start_width_unit"] = QgsUnitTypes::encodeUnit( arrowStartWidthUnit() ); - map["arrow_start_width_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( arrowStartWidthUnitScale() ); + map[QStringLiteral( "arrow_start_width" )] = QString::number( arrowStartWidth() ); + map[QStringLiteral( "arrow_start_width_unit" )] = QgsUnitTypes::encodeUnit( arrowStartWidthUnit() ); + map[QStringLiteral( "arrow_start_width_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( arrowStartWidthUnitScale() ); - map["is_curved"] = QString::number( isCurved() ? 1 : 0 ); - map["is_repeated"] = QString::number( isRepeated() ? 1 : 0 ); + map[QStringLiteral( "is_curved" )] = QString::number( isCurved() ? 1 : 0 ); + map[QStringLiteral( "is_repeated" )] = QString::number( isRepeated() ? 1 : 0 ); - map["head_length"] = QString::number( headLength() ); - map["head_length_unit"] = QgsUnitTypes::encodeUnit( headLengthUnit() ); - map["head_length_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( headLengthUnitScale() ); + map[QStringLiteral( "head_length" )] = QString::number( headLength() ); + map[QStringLiteral( "head_length_unit" )] = QgsUnitTypes::encodeUnit( headLengthUnit() ); + map[QStringLiteral( "head_length_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( headLengthUnitScale() ); - map["head_thickness"] = QString::number( headThickness() ); - map["head_thickness_unit"] = QgsUnitTypes::encodeUnit( headThicknessUnit() ); - map["head_thickness_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( headThicknessUnitScale() ); + map[QStringLiteral( "head_thickness" )] = QString::number( headThickness() ); + map[QStringLiteral( "head_thickness_unit" )] = QgsUnitTypes::encodeUnit( headThicknessUnit() ); + map[QStringLiteral( "head_thickness_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( headThicknessUnitScale() ); - map["head_type"] = QString::number( headType() ); - map["arrow_type"] = QString::number( arrowType() ); + map[QStringLiteral( "head_type" )] = QString::number( headType() ); + map[QStringLiteral( "arrow_type" )] = QString::number( arrowType() ); - map["offset"] = QString::number( offset() ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( offsetUnit() ); - map["offset_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( offsetMapUnitScale() ); + map[QStringLiteral( "offset" )] = QString::number( offset() ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( offsetUnit() ); + map[QStringLiteral( "offset_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( offsetMapUnitScale() ); saveDataDefinedProperties( map ); return map; @@ -614,37 +614,37 @@ void QgsArrowSymbolLayer::_resolveDataDefined( QgsSymbolRenderContext& context ) return; // shortcut if case there is no data defined properties at all bool ok; - if ( hasDataDefinedProperty( "arrow_width" ) ) + if ( hasDataDefinedProperty( QStringLiteral( "arrow_width" ) ) ) { context.setOriginalValueVariable( arrowWidth() ); - double w = evaluateDataDefinedProperty( "arrow_width", context, QVariant(), &ok ).toDouble(); + double w = evaluateDataDefinedProperty( QStringLiteral( "arrow_width" ), context, QVariant(), &ok ).toDouble(); if ( ok ) { mScaledArrowWidth = QgsSymbolLayerUtils::convertToPainterUnits( context.renderContext(), w, arrowWidthUnit(), arrowWidthUnitScale() ); } } - if ( hasDataDefinedProperty( "arrow_start_width" ) ) + if ( hasDataDefinedProperty( QStringLiteral( "arrow_start_width" ) ) ) { context.setOriginalValueVariable( arrowStartWidth() ); - double w = evaluateDataDefinedProperty( "arrow_start_width", context, QVariant(), &ok ).toDouble(); + double w = evaluateDataDefinedProperty( QStringLiteral( "arrow_start_width" ), context, QVariant(), &ok ).toDouble(); if ( ok ) { mScaledArrowStartWidth = QgsSymbolLayerUtils::convertToPainterUnits( context.renderContext(), w, arrowStartWidthUnit(), arrowStartWidthUnitScale() ); } } - if ( hasDataDefinedProperty( "head_length" ) ) + if ( hasDataDefinedProperty( QStringLiteral( "head_length" ) ) ) { context.setOriginalValueVariable( headLength() ); - double w = evaluateDataDefinedProperty( "head_length", context, QVariant(), &ok ).toDouble(); + double w = evaluateDataDefinedProperty( QStringLiteral( "head_length" ), context, QVariant(), &ok ).toDouble(); if ( ok ) { mScaledHeadLength = QgsSymbolLayerUtils::convertToPainterUnits( context.renderContext(), w, headLengthUnit(), headLengthUnitScale() ); } } - if ( hasDataDefinedProperty( "head_thickness" ) ) + if ( hasDataDefinedProperty( QStringLiteral( "head_thickness" ) ) ) { context.setOriginalValueVariable( headThickness() ); - double w = evaluateDataDefinedProperty( "head_thickness", context, QVariant(), &ok ).toDouble(); + double w = evaluateDataDefinedProperty( QStringLiteral( "head_thickness" ), context, QVariant(), &ok ).toDouble(); if ( ok ) { mScaledHeadThickness = QgsSymbolLayerUtils::convertToPainterUnits( context.renderContext(), w, headThicknessUnit(), headThicknessUnitScale() ); @@ -660,20 +660,20 @@ void QgsArrowSymbolLayer::_resolveDataDefined( QgsSymbolRenderContext& context ) } } - if ( hasDataDefinedProperty( "head_type" ) ) + if ( hasDataDefinedProperty( QStringLiteral( "head_type" ) ) ) { context.setOriginalValueVariable( headType() ); - int h = evaluateDataDefinedProperty( "head_type", context, QVariant(), &ok ).toInt(); + int h = evaluateDataDefinedProperty( QStringLiteral( "head_type" ), context, QVariant(), &ok ).toInt(); if ( ok ) { mComputedHeadType = static_cast<HeadType>( h ); } } - if ( hasDataDefinedProperty( "arrow_type" ) ) + if ( hasDataDefinedProperty( QStringLiteral( "arrow_type" ) ) ) { context.setOriginalValueVariable( arrowType() ); - int h = evaluateDataDefinedProperty( "arrow_type", context, QVariant(), &ok ).toInt(); + int h = evaluateDataDefinedProperty( QStringLiteral( "arrow_type" ), context, QVariant(), &ok ).toInt(); if ( ok ) { mComputedArrowType = static_cast<ArrowType>( h ); diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp index 6c3cd44c8632..e1cbb6df89ba 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.cpp @@ -111,34 +111,34 @@ void QgsRendererCategory::setRenderState( bool render ) QString QgsRendererCategory::dump() const { - return QString( "%1::%2::%3:%4\n" ).arg( mValue.toString(), mLabel, mSymbol->dump() ).arg( mRender ); + return QStringLiteral( "%1::%2::%3:%4\n" ).arg( mValue.toString(), mLabel, mSymbol->dump() ).arg( mRender ); } void QgsRendererCategory::toSld( QDomDocument &doc, QDomElement &element, QgsStringMap props ) const { - if ( !mSymbol.data() || props.value( "attribute", "" ).isEmpty() ) + if ( !mSymbol.data() || props.value( QStringLiteral( "attribute" ), QLatin1String( "" ) ).isEmpty() ) return; - QString attrName = props[ "attribute" ]; + QString attrName = props[ QStringLiteral( "attribute" )]; - QDomElement ruleElem = doc.createElement( "se:Rule" ); + QDomElement ruleElem = doc.createElement( QStringLiteral( "se:Rule" ) ); element.appendChild( ruleElem ); - QDomElement nameElem = doc.createElement( "se:Name" ); + QDomElement nameElem = doc.createElement( QStringLiteral( "se:Name" ) ); nameElem.appendChild( doc.createTextNode( mLabel ) ); ruleElem.appendChild( nameElem ); - QDomElement descrElem = doc.createElement( "se:Description" ); - QDomElement titleElem = doc.createElement( "se:Title" ); - QString descrStr = QString( "%1 is '%2'" ).arg( attrName, mValue.toString() ); + QDomElement descrElem = doc.createElement( QStringLiteral( "se:Description" ) ); + QDomElement titleElem = doc.createElement( QStringLiteral( "se:Title" ) ); + QString descrStr = QStringLiteral( "%1 is '%2'" ).arg( attrName, mValue.toString() ); titleElem.appendChild( doc.createTextNode( !mLabel.isEmpty() ? mLabel : descrStr ) ); descrElem.appendChild( titleElem ); ruleElem.appendChild( descrElem ); // create the ogc:Filter for the range - QString filterFunc = QString( "%1 = '%2'" ) - .arg( attrName.replace( '\"', "\"\"" ), - mValue.toString().replace( '\'', "''" ) ); + QString filterFunc = QStringLiteral( "%1 = '%2'" ) + .arg( attrName.replace( '\"', QLatin1String( "\"\"" ) ), + mValue.toString().replace( '\'', QLatin1String( "''" ) ) ); QgsSymbolLayerUtils::createFunctionElement( doc, ruleElem, filterFunc ); // add the mix/max scale denoms if we got any from the callers @@ -150,7 +150,7 @@ void QgsRendererCategory::toSld( QDomDocument &doc, QDomElement &element, QgsStr /////////////////// QgsCategorizedSymbolRenderer::QgsCategorizedSymbolRenderer( const QString& attrName, const QgsCategoryList& categories ) - : QgsFeatureRenderer( "categorizedSymbol" ) + : QgsFeatureRenderer( QStringLiteral( "categorizedSymbol" ) ) , mAttrName( attrName ) , mInvertedColorRamp( false ) , mAttrNum( -1 ) @@ -196,7 +196,7 @@ QgsSymbol*QgsCategorizedSymbolRenderer::skipRender() QgsSymbol* QgsCategorizedSymbolRenderer::symbolForValue( const QVariant& value ) { // TODO: special case for int, double - QHash<QString, QgsSymbol*>::const_iterator it = mSymbolHash.constFind( value.isNull() ? "" : value.toString() ); + QHash<QString, QgsSymbol*>::const_iterator it = mSymbolHash.constFind( value.isNull() ? QLatin1String( "" ) : value.toString() ); if ( it == mSymbolHash.constEnd() ) { if ( mSymbolHash.isEmpty() ) @@ -458,7 +458,7 @@ QSet<QString> QgsCategorizedSymbolRenderer::usedAttributes() const QString QgsCategorizedSymbolRenderer::dump() const { - QString s = QString( "CATEGORIZED: idx %1\n" ).arg( mAttrName ); + QString s = QStringLiteral( "CATEGORIZED: idx %1\n" ).arg( mAttrName ); for ( int i = 0; i < mCategories.count(); i++ ) s += mCategories[i].dump(); return s; @@ -483,7 +483,7 @@ QgsCategorizedSymbolRenderer* QgsCategorizedSymbolRenderer::clone() const void QgsCategorizedSymbolRenderer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap &props ) const { QgsStringMap newProps = props; - newProps[ "attribute" ] = mAttrName; + newProps[ QStringLiteral( "attribute" )] = mAttrName; // create a Rule for each range for ( QgsCategoryList::const_iterator it = mCategories.constBegin(); it != mCategories.constEnd(); ++it ) @@ -544,7 +544,7 @@ QString QgsCategorizedSymbolRenderer::filter( const QgsFields& fields ) } } - QString attr = isExpression ? mAttrName : QString( "\"%1\"" ).arg( mAttrName ); + QString attr = isExpression ? mAttrName : QStringLiteral( "\"%1\"" ).arg( mAttrName ); if ( allActive && hasDefault ) { @@ -552,15 +552,15 @@ QString QgsCategorizedSymbolRenderer::filter( const QgsFields& fields ) } else if ( noneActive ) { - return "FALSE"; + return QStringLiteral( "FALSE" ); } else if ( defaultActive ) { - return QString( "(%1) NOT IN (%2) OR (%1) IS NULL" ).arg( attr, inactiveValues ); + return QStringLiteral( "(%1) NOT IN (%2) OR (%1) IS NULL" ).arg( attr, inactiveValues ); } else { - return QString( "(%1) IN (%2)" ).arg( attr, activeValues ); + return QStringLiteral( "(%1) IN (%2)" ).arg( attr, activeValues ); } } @@ -578,11 +578,11 @@ QgsSymbolList QgsCategorizedSymbolRenderer::symbols( QgsRenderContext &context ) QgsFeatureRenderer* QgsCategorizedSymbolRenderer::create( QDomElement& element ) { - QDomElement symbolsElem = element.firstChildElement( "symbols" ); + QDomElement symbolsElem = element.firstChildElement( QStringLiteral( "symbols" ) ); if ( symbolsElem.isNull() ) return nullptr; - QDomElement catsElem = element.firstChildElement( "categories" ); + QDomElement catsElem = element.firstChildElement( QStringLiteral( "categories" ) ); if ( catsElem.isNull() ) return nullptr; @@ -592,12 +592,12 @@ QgsFeatureRenderer* QgsCategorizedSymbolRenderer::create( QDomElement& element ) QDomElement catElem = catsElem.firstChildElement(); while ( !catElem.isNull() ) { - if ( catElem.tagName() == "category" ) + if ( catElem.tagName() == QLatin1String( "category" ) ) { - QVariant value = QVariant( catElem.attribute( "value" ) ); - QString symbolName = catElem.attribute( "symbol" ); - QString label = catElem.attribute( "label" ); - bool render = catElem.attribute( "render" ) != "false"; + QVariant value = QVariant( catElem.attribute( QStringLiteral( "value" ) ) ); + QString symbolName = catElem.attribute( QStringLiteral( "symbol" ) ); + QString label = catElem.attribute( QStringLiteral( "label" ) ); + bool render = catElem.attribute( QStringLiteral( "render" ) ) != QLatin1String( "false" ); if ( symbolMap.contains( symbolName ) ) { QgsSymbol* symbol = symbolMap.take( symbolName ); @@ -607,7 +607,7 @@ QgsFeatureRenderer* QgsCategorizedSymbolRenderer::create( QDomElement& element ) catElem = catElem.nextSiblingElement(); } - QString attrName = element.attribute( "attr" ); + QString attrName = element.attribute( QStringLiteral( "attr" ) ); QgsCategorizedSymbolRenderer* r = new QgsCategorizedSymbolRenderer( attrName, cats ); @@ -615,54 +615,54 @@ QgsFeatureRenderer* QgsCategorizedSymbolRenderer::create( QDomElement& element ) QgsSymbolLayerUtils::clearSymbolMap( symbolMap ); // try to load source symbol (optional) - QDomElement sourceSymbolElem = element.firstChildElement( "source-symbol" ); + QDomElement sourceSymbolElem = element.firstChildElement( QStringLiteral( "source-symbol" ) ); if ( !sourceSymbolElem.isNull() ) { QgsSymbolMap sourceSymbolMap = QgsSymbolLayerUtils::loadSymbols( sourceSymbolElem ); - if ( sourceSymbolMap.contains( "0" ) ) + if ( sourceSymbolMap.contains( QStringLiteral( "0" ) ) ) { - r->setSourceSymbol( sourceSymbolMap.take( "0" ) ); + r->setSourceSymbol( sourceSymbolMap.take( QStringLiteral( "0" ) ) ); } QgsSymbolLayerUtils::clearSymbolMap( sourceSymbolMap ); } // try to load color ramp (optional) - QDomElement sourceColorRampElem = element.firstChildElement( "colorramp" ); - if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( "name" ) == "[source]" ) + QDomElement sourceColorRampElem = element.firstChildElement( QStringLiteral( "colorramp" ) ); + if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( QStringLiteral( "name" ) ) == QLatin1String( "[source]" ) ) { r->setSourceColorRamp( QgsSymbolLayerUtils::loadColorRamp( sourceColorRampElem ) ); - QDomElement invertedColorRampElem = element.firstChildElement( "invertedcolorramp" ); + QDomElement invertedColorRampElem = element.firstChildElement( QStringLiteral( "invertedcolorramp" ) ); if ( !invertedColorRampElem.isNull() ) - r->setInvertedColorRamp( invertedColorRampElem.attribute( "value" ) == "1" ); + r->setInvertedColorRamp( invertedColorRampElem.attribute( QStringLiteral( "value" ) ) == QLatin1String( "1" ) ); } - QDomElement rotationElem = element.firstChildElement( "rotation" ); - if ( !rotationElem.isNull() && !rotationElem.attribute( "field" ).isEmpty() ) + QDomElement rotationElem = element.firstChildElement( QStringLiteral( "rotation" ) ); + if ( !rotationElem.isNull() && !rotationElem.attribute( QStringLiteral( "field" ) ).isEmpty() ) { Q_FOREACH ( const QgsRendererCategory& cat, r->mCategories ) { - convertSymbolRotation( cat.symbol(), rotationElem.attribute( "field" ) ); + convertSymbolRotation( cat.symbol(), rotationElem.attribute( QStringLiteral( "field" ) ) ); } if ( r->mSourceSymbol.data() ) { - convertSymbolRotation( r->mSourceSymbol.data(), rotationElem.attribute( "field" ) ); + convertSymbolRotation( r->mSourceSymbol.data(), rotationElem.attribute( QStringLiteral( "field" ) ) ); } } - QDomElement sizeScaleElem = element.firstChildElement( "sizescale" ); - if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( "field" ).isEmpty() ) + QDomElement sizeScaleElem = element.firstChildElement( QStringLiteral( "sizescale" ) ); + if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( QStringLiteral( "field" ) ).isEmpty() ) { Q_FOREACH ( const QgsRendererCategory& cat, r->mCategories ) { convertSymbolSizeScale( cat.symbol(), - QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ), - sizeScaleElem.attribute( "field" ) ); + QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( QStringLiteral( "scalemethod" ) ) ), + sizeScaleElem.attribute( QStringLiteral( "field" ) ) ); } if ( r->mSourceSymbol.data() && r->mSourceSymbol->type() == QgsSymbol::Marker ) { convertSymbolSizeScale( r->mSourceSymbol.data(), - QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ), - sizeScaleElem.attribute( "field" ) ); + QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( QStringLiteral( "scalemethod" ) ) ), + sizeScaleElem.attribute( QStringLiteral( "field" ) ) ); } } @@ -673,17 +673,17 @@ QgsFeatureRenderer* QgsCategorizedSymbolRenderer::create( QDomElement& element ) QDomElement QgsCategorizedSymbolRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "categorizedSymbol" ); - rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); - rendererElem.setAttribute( "attr", mAttrName ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "categorizedSymbol" ) ); + rendererElem.setAttribute( QStringLiteral( "symbollevels" ), ( mUsingSymbolLevels ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "attr" ), mAttrName ); // categories if ( !mCategories.isEmpty() ) { int i = 0; QgsSymbolMap symbols; - QDomElement catsElem = doc.createElement( "categories" ); + QDomElement catsElem = doc.createElement( QStringLiteral( "categories" ) ); QgsCategoryList::const_iterator it = mCategories.constBegin(); for ( ; it != mCategories.constEnd(); ++it ) { @@ -691,18 +691,18 @@ QDomElement QgsCategorizedSymbolRenderer::save( QDomDocument& doc ) QString symbolName = QString::number( i ); symbols.insert( symbolName, cat.symbol() ); - QDomElement catElem = doc.createElement( "category" ); - catElem.setAttribute( "value", cat.value().toString() ); - catElem.setAttribute( "symbol", symbolName ); - catElem.setAttribute( "label", cat.label() ); - catElem.setAttribute( "render", cat.renderState() ? "true" : "false" ); + QDomElement catElem = doc.createElement( QStringLiteral( "category" ) ); + catElem.setAttribute( QStringLiteral( "value" ), cat.value().toString() ); + catElem.setAttribute( QStringLiteral( "symbol" ), symbolName ); + catElem.setAttribute( QStringLiteral( "label" ), cat.label() ); + catElem.setAttribute( QStringLiteral( "render" ), cat.renderState() ? "true" : "false" ); catsElem.appendChild( catElem ); i++; } rendererElem.appendChild( catsElem ); // save symbols - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, "symbols", doc ); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, QStringLiteral( "symbols" ), doc ); rendererElem.appendChild( symbolsElem ); } @@ -711,25 +711,25 @@ QDomElement QgsCategorizedSymbolRenderer::save( QDomDocument& doc ) if ( mSourceSymbol.data() ) { QgsSymbolMap sourceSymbols; - sourceSymbols.insert( "0", mSourceSymbol.data() ); - QDomElement sourceSymbolElem = QgsSymbolLayerUtils::saveSymbols( sourceSymbols, "source-symbol", doc ); + sourceSymbols.insert( QStringLiteral( "0" ), mSourceSymbol.data() ); + QDomElement sourceSymbolElem = QgsSymbolLayerUtils::saveSymbols( sourceSymbols, QStringLiteral( "source-symbol" ), doc ); rendererElem.appendChild( sourceSymbolElem ); } // save source color ramp if ( mSourceColorRamp.data() ) { - QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( "[source]", mSourceColorRamp.data(), doc ); + QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( QStringLiteral( "[source]" ), mSourceColorRamp.data(), doc ); rendererElem.appendChild( colorRampElem ); - QDomElement invertedElem = doc.createElement( "invertedcolorramp" ); - invertedElem.setAttribute( "value", mInvertedColorRamp ); + QDomElement invertedElem = doc.createElement( QStringLiteral( "invertedcolorramp" ) ); + invertedElem.setAttribute( QStringLiteral( "value" ), mInvertedColorRamp ); rendererElem.appendChild( invertedElem ); } - QDomElement rotationElem = doc.createElement( "rotation" ); + QDomElement rotationElem = doc.createElement( QStringLiteral( "rotation" ) ); rendererElem.appendChild( rotationElem ); - QDomElement sizeScaleElem = doc.createElement( "sizescale" ); + QDomElement sizeScaleElem = doc.createElement( QStringLiteral( "sizescale" ) ); rendererElem.appendChild( sizeScaleElem ); if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) @@ -737,11 +737,11 @@ QDomElement QgsCategorizedSymbolRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -804,11 +804,11 @@ QgsLegendSymbolListV2 QgsCategorizedSymbolRenderer::legendSymbolItemsV2() const QgsScaleExpression exp( ddSize.expressionString() ); if ( exp.type() != QgsScaleExpression::Unknown ) { - QgsLegendSymbolItem title( nullptr, exp.baseExpression(), "" ); + QgsLegendSymbolItem title( nullptr, exp.baseExpression(), QLatin1String( "" ) ); lst << title; Q_FOREACH ( double v, QgsSymbolLayerUtils::prettyBreaks( exp.minValue(), exp.maxValue(), 4 ) ) { - QgsLegendSymbolItem si( mSourceSymbol.data(), QString::number( v ), "" ); + QgsLegendSymbolItem si( mSourceSymbol.data(), QString::number( v ), QLatin1String( "" ) ); QgsMarkerSymbol * s = static_cast<QgsMarkerSymbol *>( si.symbol() ); s->setDataDefinedSize( QgsDataDefined() ); s->setSize( exp.size( v ) ); @@ -937,17 +937,17 @@ void QgsCategorizedSymbolRenderer::checkLegendSymbolItem( const QString& key, bo QgsCategorizedSymbolRenderer* QgsCategorizedSymbolRenderer::convertFromRenderer( const QgsFeatureRenderer *renderer ) { QgsCategorizedSymbolRenderer* r = nullptr; - if ( renderer->type() == "categorizedSymbol" ) + if ( renderer->type() == QLatin1String( "categorizedSymbol" ) ) { r = dynamic_cast<QgsCategorizedSymbolRenderer*>( renderer->clone() ); } - else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) + else if ( renderer->type() == QLatin1String( "pointDisplacement" ) || renderer->type() == QLatin1String( "pointCluster" ) ) { const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast<const QgsPointDistanceRenderer*>( renderer ); if ( pointDistanceRenderer ) r = convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } - else if ( renderer->type() == "invertedPolygonRenderer" ) + else if ( renderer->type() == QLatin1String( "invertedPolygonRenderer" ) ) { const QgsInvertedPolygonRenderer* invertedPolygonRenderer = dynamic_cast<const QgsInvertedPolygonRenderer*>( renderer ); if ( invertedPolygonRenderer ) @@ -959,7 +959,7 @@ QgsCategorizedSymbolRenderer* QgsCategorizedSymbolRenderer::convertFromRenderer( if ( !r ) { - r = new QgsCategorizedSymbolRenderer( "", QgsCategoryList() ); + r = new QgsCategorizedSymbolRenderer( QLatin1String( "" ), QgsCategoryList() ); QgsRenderContext context; QgsSymbolList symbols = const_cast<QgsFeatureRenderer *>( renderer )->symbols( context ); if ( !symbols.isEmpty() ) diff --git a/src/core/symbology-ng/qgscptcityarchive.cpp b/src/core/symbology-ng/qgscptcityarchive.cpp index ecb187eccb34..4d90e47dcf43 100644 --- a/src/core/symbology-ng/qgscptcityarchive.cpp +++ b/src/core/symbology-ng/qgscptcityarchive.cpp @@ -54,7 +54,7 @@ QgsCptCityArchive::QgsCptCityArchive( const QString& archiveName, const QString& QgsCptCityDirectoryItem* dirItem = nullptr; Q_FOREACH ( const QString& path, QDir( mBaseDir ).entryList( QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name ) ) { - if ( path == "selections" ) + if ( path == QLatin1String( "selections" ) ) continue; QgsDebugMsg( "path= " + path ); dirItem = new QgsCptCityDirectoryItem( nullptr, QFileInfo( path ).baseName(), path ); @@ -127,10 +127,10 @@ QString QgsCptCityArchive::defaultBaseDir() QSettings settings; // use CptCity/baseDir setting if set, default is user dir - baseDir = settings.value( "CptCity/baseDir", + baseDir = settings.value( QStringLiteral( "CptCity/baseDir" ), QgsApplication::pkgDataPath() + "/resources" ).toString(); // sub-dir defaults to cpt-city - archiveName = settings.value( "CptCity/archiveName", DEFAULT_CPTCITY_ARCHIVE ).toString(); + archiveName = settings.value( QStringLiteral( "CptCity/archiveName" ), DEFAULT_CPTCITY_ARCHIVE ).toString(); return baseDir + '/' + archiveName; } @@ -140,7 +140,7 @@ QString QgsCptCityArchive::findFileName( const QString & target, const QString & { // QgsDebugMsg( "target= " + target + " startDir= " + startDir + " baseDir= " + baseDir ); - if ( startDir == "" || ! startDir.startsWith( baseDir ) ) + if ( startDir == QLatin1String( "" ) || ! startDir.startsWith( baseDir ) ) return QString(); QDir dir = QDir( startDir ); @@ -159,13 +159,13 @@ QString QgsCptCityArchive::findFileName( const QString & target, const QString & QString QgsCptCityArchive::copyingFileName( const QString& path ) const { - return QgsCptCityArchive::findFileName( "COPYING.xml", + return QgsCptCityArchive::findFileName( QStringLiteral( "COPYING.xml" ), baseDir() + '/' + path, baseDir() ); } QString QgsCptCityArchive::descFileName( const QString& path ) const { - return QgsCptCityArchive::findFileName( "DESC.xml", + return QgsCptCityArchive::findFileName( QStringLiteral( "DESC.xml" ), baseDir() + '/' + path, baseDir() ); } @@ -193,7 +193,7 @@ QgsStringMap QgsCptCityArchive::copyingInfo( const QString& fileName ) } // parse the document - QDomDocument doc( "license" ); + QDomDocument doc( QStringLiteral( "license" ) ); if ( !doc.setContent( &f ) ) { f.close(); @@ -204,14 +204,14 @@ QgsStringMap QgsCptCityArchive::copyingInfo( const QString& fileName ) // get root element QDomElement docElem = doc.documentElement(); - if ( docElem.tagName() != "copying" ) + if ( docElem.tagName() != QLatin1String( "copying" ) ) { QgsDebugMsg( "Incorrect root tag: " + docElem.tagName() ); return copyingMap; } // load author information - QDomElement authorsElement = docElem.firstChildElement( "authors" ); + QDomElement authorsElement = docElem.firstChildElement( QStringLiteral( "authors" ) ); if ( authorsElement.isNull() ) { QgsDebugMsg( "authors tag missing" ); @@ -222,47 +222,47 @@ QgsStringMap QgsCptCityArchive::copyingInfo( const QString& fileName ) QStringList authors; while ( ! e.isNull() ) { - if ( e.tagName() == "author" ) + if ( e.tagName() == QLatin1String( "author" ) ) { - if ( ! e.firstChildElement( "name" ).isNull() ) - authors << e.firstChildElement( "name" ).text().simplified(); + if ( ! e.firstChildElement( QStringLiteral( "name" ) ).isNull() ) + authors << e.firstChildElement( QStringLiteral( "name" ) ).text().simplified(); // org??? } e = e.nextSiblingElement(); } - copyingMap[ "authors" ] = authors.join( ", " ); + copyingMap[ QStringLiteral( "authors" )] = authors.join( QStringLiteral( ", " ) ); } // load license information - QDomElement licenseElement = docElem.firstChildElement( "license" ); + QDomElement licenseElement = docElem.firstChildElement( QStringLiteral( "license" ) ); if ( licenseElement.isNull() ) { QgsDebugMsg( "license tag missing" ); } else { - QDomElement e = licenseElement.firstChildElement( "informal" ); + QDomElement e = licenseElement.firstChildElement( QStringLiteral( "informal" ) ); if ( ! e.isNull() ) - copyingMap[ "license/informal" ] = e.text().simplified(); - e = licenseElement.firstChildElement( "year" ); + copyingMap[ QStringLiteral( "license/informal" )] = e.text().simplified(); + e = licenseElement.firstChildElement( QStringLiteral( "year" ) ); if ( ! e.isNull() ) - copyingMap[ "license/year" ] = e.text().simplified(); - e = licenseElement.firstChildElement( "text" ); - if ( ! e.isNull() && e.attribute( "href" ) != QString() ) - copyingMap[ "license/url" ] = e.attribute( "href" ); + copyingMap[ QStringLiteral( "license/year" )] = e.text().simplified(); + e = licenseElement.firstChildElement( QStringLiteral( "text" ) ); + if ( ! e.isNull() && e.attribute( QStringLiteral( "href" ) ) != QString() ) + copyingMap[ QStringLiteral( "license/url" )] = e.attribute( QStringLiteral( "href" ) ); } // load src information - QDomElement element = docElem.firstChildElement( "src" ); + QDomElement element = docElem.firstChildElement( QStringLiteral( "src" ) ); if ( element.isNull() ) { QgsDebugMsg( "src tag missing" ); } else { - QDomElement e = element.firstChildElement( "link" ); - if ( ! e.isNull() && e.attribute( "href" ) != QString() ) - copyingMap[ "src/link" ] = e.attribute( "href" ); + QDomElement e = element.firstChildElement( QStringLiteral( "link" ) ); + if ( ! e.isNull() && e.attribute( QStringLiteral( "href" ) ) != QString() ) + copyingMap[ QStringLiteral( "src/link" )] = e.attribute( QStringLiteral( "href" ) ); } // save copyingMap for further access @@ -285,7 +285,7 @@ QgsStringMap QgsCptCityArchive::description( const QString& fileName ) // parse the document QString errMsg; - QDomDocument doc( "description" ); + QDomDocument doc( QStringLiteral( "description" ) ); if ( !doc.setContent( &f, &errMsg ) ) { f.close(); @@ -296,25 +296,25 @@ QgsStringMap QgsCptCityArchive::description( const QString& fileName ) // read description QDomElement docElem = doc.documentElement(); - if ( docElem.tagName() != "description" ) + if ( docElem.tagName() != QLatin1String( "description" ) ) { QgsDebugMsg( "Incorrect root tag: " + docElem.tagName() ); return descMap; } // should we make sure the <dir> tag is ok? - QDomElement e = docElem.firstChildElement( "name" ); + QDomElement e = docElem.firstChildElement( QStringLiteral( "name" ) ); if ( e.isNull() ) { QgsDebugMsg( "name tag missing" ); } - descMap[ "name" ] = e.text().simplified(); - e = docElem.firstChildElement( "full" ); + descMap[ QStringLiteral( "name" )] = e.text().simplified(); + e = docElem.firstChildElement( QStringLiteral( "full" ) ); if ( e.isNull() ) { QgsDebugMsg( "full tag missing" ); } - descMap[ "full" ] = e.text().simplified(); + descMap[ QStringLiteral( "full" )] = e.text().simplified(); return descMap; } @@ -332,7 +332,7 @@ QMap< double, QPair<QColor, QColor> >QgsCptCityArchive::gradientColorMap( const } // parse the document - QDomDocument doc( "gradient" ); + QDomDocument doc( QStringLiteral( "gradient" ) ); if ( !doc.setContent( &f ) ) { f.close(); @@ -343,17 +343,17 @@ QMap< double, QPair<QColor, QColor> >QgsCptCityArchive::gradientColorMap( const QDomElement docElem = doc.documentElement(); - if ( docElem.tagName() != "svg" ) + if ( docElem.tagName() != QLatin1String( "svg" ) ) { QgsDebugMsg( "Incorrect root tag: " + docElem.tagName() ); return colorMap; } // load color ramp from first linearGradient node - QDomElement rampsElement = docElem.firstChildElement( "linearGradient" ); + QDomElement rampsElement = docElem.firstChildElement( QStringLiteral( "linearGradient" ) ); if ( rampsElement.isNull() ) { - QDomNodeList nodeList = docElem.elementsByTagName( "linearGradient" ); + QDomNodeList nodeList = docElem.elementsByTagName( QStringLiteral( "linearGradient" ) ); if ( ! nodeList.isEmpty() ) rampsElement = nodeList.at( 0 ).toElement(); } @@ -368,13 +368,13 @@ QMap< double, QPair<QColor, QColor> >QgsCptCityArchive::gradientColorMap( const while ( !e.isNull() ) { - if ( e.tagName() == "stop" ) + if ( e.tagName() == QLatin1String( "stop" ) ) { //todo integrate this into symbollayerutils, keep here for now... double offset; - QString offsetStr = e.attribute( "offset" ); // offset="50.00%" | offset="0.5" - QString colorStr = e.attribute( "stop-color", "" ); // stop-color="rgb(222,235,247)" - QString opacityStr = e.attribute( "stop-opacity", "1.0" ); // stop-opacity="1.0000" + QString offsetStr = e.attribute( QStringLiteral( "offset" ) ); // offset="50.00%" | offset="0.5" + QString colorStr = e.attribute( QStringLiteral( "stop-color" ), QLatin1String( "" ) ); // stop-color="rgb(222,235,247)" + QString opacityStr = e.attribute( QStringLiteral( "stop-opacity" ), QStringLiteral( "1.0" ) ); // stop-opacity="1.0000" if ( offsetStr.endsWith( '%' ) ) offset = offsetStr.remove( offsetStr.size() - 1, 1 ).toDouble() / 100.0; else @@ -416,7 +416,7 @@ bool QgsCptCityArchive::isEmpty() QgsCptCityArchive* QgsCptCityArchive::defaultArchive() { QSettings settings; - mDefaultArchiveName = settings.value( "CptCity/archiveName", DEFAULT_CPTCITY_ARCHIVE ).toString(); + mDefaultArchiveName = settings.value( QStringLiteral( "CptCity/archiveName" ), DEFAULT_CPTCITY_ARCHIVE ).toString(); if ( QgsCptCityArchive::mArchiveRegistry.contains( mDefaultArchiveName ) ) return QgsCptCityArchive::mArchiveRegistry.value( mDefaultArchiveName ); else @@ -436,10 +436,10 @@ void QgsCptCityArchive::initDefaultArchive() { QSettings settings; // use CptCity/baseDir setting if set, default is user dir - QString baseDir = settings.value( "CptCity/baseDir", + QString baseDir = settings.value( QStringLiteral( "CptCity/baseDir" ), QgsApplication::pkgDataPath() + "/resources" ).toString(); // sub-dir defaults to - QString defArchiveName = settings.value( "CptCity/archiveName", DEFAULT_CPTCITY_ARCHIVE ).toString(); + QString defArchiveName = settings.value( QStringLiteral( "CptCity/archiveName" ), DEFAULT_CPTCITY_ARCHIVE ).toString(); if ( ! mArchiveRegistry.contains( defArchiveName ) ) initArchive( defArchiveName, baseDir + '/' + defArchiveName ); @@ -452,10 +452,10 @@ void QgsCptCityArchive::initArchives( bool loadAll ) QSettings settings; // use CptCity/baseDir setting if set, default is user dir - baseDir = settings.value( "CptCity/baseDir", + baseDir = settings.value( QStringLiteral( "CptCity/baseDir" ), QgsApplication::pkgDataPath() + "/resources" ).toString(); // sub-dir defaults to - defArchiveName = settings.value( "CptCity/archiveName", DEFAULT_CPTCITY_ARCHIVE ).toString(); + defArchiveName = settings.value( QStringLiteral( "CptCity/archiveName" ), DEFAULT_CPTCITY_ARCHIVE ).toString(); QgsDebugMsg( "baseDir= " + baseDir + " defArchiveName= " + defArchiveName ); if ( loadAll ) @@ -784,7 +784,7 @@ void QgsCptCityColorRampItem::init() } else { - mInfo = ""; + mInfo = QLatin1String( "" ); } } @@ -830,7 +830,7 @@ QIcon QgsCptCityColorRampItem::icon( QSize size ) QPixmap blankPixmap( size ); blankPixmap.fill( Qt::white ); icon = QIcon( blankPixmap ); - mInfo = ""; + mInfo = QLatin1String( "" ); } mIcons.append( icon ); @@ -914,12 +914,12 @@ QgsCptCityDirectoryItem::QgsCptCityDirectoryItem( QgsCptCityDataItem* parent, } // parse DESC.xml to get mInfo - mInfo = ""; + mInfo = QLatin1String( "" ); QString fileName = QgsCptCityArchive::defaultBaseDir() + '/' + mPath + '/' + "DESC.xml"; QgsStringMap descMap = QgsCptCityArchive::description( fileName ); - if ( descMap.contains( "name" ) ) - mInfo = descMap.value( "name" ); + if ( descMap.contains( QStringLiteral( "name" ) ) ) + mInfo = descMap.value( QStringLiteral( "name" ) ); // populate(); } @@ -974,7 +974,7 @@ QMap< QString, QStringList > QgsCptCityDirectoryItem::rampsMap() bool prevAdd, curAdd; QDir dir( QgsCptCityArchive::defaultBaseDir() + '/' + mPath ); - schemeNamesAll = dir.entryList( QStringList( "*.svg" ), QDir::Files, QDir::Name ); + schemeNamesAll = dir.entryList( QStringList( QStringLiteral( "*.svg" ) ), QDir::Files, QDir::Name ); // TODO detect if there are duplicate names with different variant counts, combine in 1 for ( int i = 0; i < schemeNamesAll.count(); i++ ) @@ -985,7 +985,7 @@ QMap< QString, QStringList > QgsCptCityDirectoryItem::rampsMap() // QgsDebugMsg("============="); // QgsDebugMsg("scheme = "+schemeName); curName = schemeName; - curVariant = ""; + curVariant = QLatin1String( "" ); // find if name ends with 1-3 digit number // TODO need to detect if ends with b/c also @@ -1007,20 +1007,20 @@ QMap< QString, QStringList > QgsCptCityDirectoryItem::rampsMap() } curSep = curName.right( 1 ); - if ( curSep == "-" || curSep == "_" ) + if ( curSep == QLatin1String( "-" ) || curSep == QLatin1String( "_" ) ) { curName.chop( 1 ); curVariant = curSep + curVariant; } - if ( prevName == "" ) + if ( prevName == QLatin1String( "" ) ) prevName = curName; // add element, unless it is empty, or a variant of last element prevAdd = false; curAdd = false; - if ( curName == "" ) - curName = "__empty__"; + if ( curName == QLatin1String( "" ) ) + curName = QStringLiteral( "__empty__" ); // if current is a variant of last, don't add previous and append current variant if ( curName == prevName ) { @@ -1031,7 +1031,7 @@ QMap< QString, QStringList > QgsCptCityDirectoryItem::rampsMap() } else { - if ( prevName != "" ) + if ( prevName != QLatin1String( "" ) ) { prevAdd = true; } @@ -1072,7 +1072,7 @@ QMap< QString, QStringList > QgsCptCityDirectoryItem::rampsMap() } if ( curAdd ) { - if ( curVariant != "" ) + if ( curVariant != QLatin1String( "" ) ) curName += curVariant; schemeNames << curName; mRampsMap[ mPath + '/' + curName ] = QStringList(); @@ -1081,7 +1081,7 @@ QMap< QString, QStringList > QgsCptCityDirectoryItem::rampsMap() if ( prevAdd || curAdd ) { prevName = curName; - if ( curVariant != "" ) + if ( curVariant != QLatin1String( "" ) ) listVariant << curVariant; } @@ -1235,7 +1235,7 @@ void QgsCptCitySelectionItem::parseXml() // parse the document QString errMsg; - QDomDocument doc( "selection" ); + QDomDocument doc( QStringLiteral( "selection" ) ); if ( !doc.setContent( &f, &errMsg ) ) { f.close(); @@ -1246,38 +1246,38 @@ void QgsCptCitySelectionItem::parseXml() // read description QDomElement docElem = doc.documentElement(); - if ( docElem.tagName() != "selection" ) + if ( docElem.tagName() != QLatin1String( "selection" ) ) { QgsDebugMsg( "Incorrect root tag: " + docElem.tagName() ); return; } - QDomElement e = docElem.firstChildElement( "name" ); + QDomElement e = docElem.firstChildElement( QStringLiteral( "name" ) ); if ( ! e.isNull() && ! e.text().isNull() ) mName = e.text(); - mInfo = docElem.firstChildElement( "synopsis" ).text().simplified(); + mInfo = docElem.firstChildElement( QStringLiteral( "synopsis" ) ).text().simplified(); // get archives - QDomElement collectsElem = docElem.firstChildElement( "seealsocollects" ); - e = collectsElem.firstChildElement( "collect" ); + QDomElement collectsElem = docElem.firstChildElement( QStringLiteral( "seealsocollects" ) ); + e = collectsElem.firstChildElement( QStringLiteral( "collect" ) ); while ( ! e.isNull() ) { - if ( ! e.attribute( "dir" ).isNull() ) + if ( ! e.attribute( QStringLiteral( "dir" ) ).isNull() ) { // TODO parse description and use that, instead of default archive name - mSelectionsList << e.attribute( "dir" ) + '/'; + mSelectionsList << e.attribute( QStringLiteral( "dir" ) ) + '/'; } e = e.nextSiblingElement(); } // get individual gradients - QDomElement gradientsElem = docElem.firstChildElement( "gradients" ); - e = gradientsElem.firstChildElement( "gradient" ); + QDomElement gradientsElem = docElem.firstChildElement( QStringLiteral( "gradients" ) ); + e = gradientsElem.firstChildElement( QStringLiteral( "gradient" ) ); while ( ! e.isNull() ) { - if ( ! e.attribute( "dir" ).isNull() ) + if ( ! e.attribute( QStringLiteral( "dir" ) ).isNull() ) { // QgsDebugMsg( "add " + e.attribute( "dir" ) + '/' + e.attribute( "file" ) + " to " + selname ); // TODO parse description and save elsewhere - mSelectionsList << e.attribute( "dir" ) + '/' + e.attribute( "file" ); + mSelectionsList << e.attribute( QStringLiteral( "dir" ) ) + '/' + e.attribute( QStringLiteral( "file" ) ); } e = e.nextSiblingElement(); } diff --git a/src/core/symbology-ng/qgsellipsesymbollayer.cpp b/src/core/symbology-ng/qgsellipsesymbollayer.cpp index 66fb783ddb0c..4df2da95726f 100644 --- a/src/core/symbology-ng/qgsellipsesymbollayer.cpp +++ b/src/core/symbology-ng/qgsellipsesymbollayer.cpp @@ -29,7 +29,7 @@ QgsEllipseSymbolLayer::QgsEllipseSymbolLayer() : QgsMarkerSymbolLayer() - , mSymbolName( "circle" ) + , mSymbolName( QStringLiteral( "circle" ) ) , mSymbolWidth( 4 ) , mSymbolWidthUnit( QgsUnitTypes::RenderMillimeters ) , mSymbolHeight( 3 ) @@ -58,151 +58,151 @@ QgsEllipseSymbolLayer::~QgsEllipseSymbolLayer() QgsSymbolLayer* QgsEllipseSymbolLayer::create( const QgsStringMap& properties ) { QgsEllipseSymbolLayer* layer = new QgsEllipseSymbolLayer(); - if ( properties.contains( "symbol_name" ) ) + if ( properties.contains( QStringLiteral( "symbol_name" ) ) ) { - layer->setSymbolName( properties[ "symbol_name" ] ); + layer->setSymbolName( properties[ QStringLiteral( "symbol_name" )] ); } - if ( properties.contains( "symbol_width" ) ) + if ( properties.contains( QStringLiteral( "symbol_width" ) ) ) { - layer->setSymbolWidth( properties["symbol_width"].toDouble() ); + layer->setSymbolWidth( properties[QStringLiteral( "symbol_width" )].toDouble() ); } - if ( properties.contains( "symbol_width_unit" ) ) + if ( properties.contains( QStringLiteral( "symbol_width_unit" ) ) ) { - layer->setSymbolWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["symbol_width_unit"] ) ); + layer->setSymbolWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "symbol_width_unit" )] ) ); } - if ( properties.contains( "symbol_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "symbol_width_map_unit_scale" ) ) ) { - layer->setSymbolWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["symbol_width_map_unit_scale"] ) ); + layer->setSymbolWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "symbol_width_map_unit_scale" )] ) ); } - if ( properties.contains( "symbol_height" ) ) + if ( properties.contains( QStringLiteral( "symbol_height" ) ) ) { - layer->setSymbolHeight( properties["symbol_height"].toDouble() ); + layer->setSymbolHeight( properties[QStringLiteral( "symbol_height" )].toDouble() ); } - if ( properties.contains( "symbol_height_unit" ) ) + if ( properties.contains( QStringLiteral( "symbol_height_unit" ) ) ) { - layer->setSymbolHeightUnit( QgsUnitTypes::decodeRenderUnit( properties["symbol_height_unit"] ) ); + layer->setSymbolHeightUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "symbol_height_unit" )] ) ); } - if ( properties.contains( "symbol_height_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "symbol_height_map_unit_scale" ) ) ) { - layer->setSymbolHeightMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["symbol_height_map_unit_scale"] ) ); + layer->setSymbolHeightMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "symbol_height_map_unit_scale" )] ) ); } - if ( properties.contains( "angle" ) ) + if ( properties.contains( QStringLiteral( "angle" ) ) ) { - layer->setAngle( properties["angle"].toDouble() ); + layer->setAngle( properties[QStringLiteral( "angle" )].toDouble() ); } - if ( properties.contains( "outline_style" ) ) + if ( properties.contains( QStringLiteral( "outline_style" ) ) ) { - layer->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( properties["outline_style"] ) ); + layer->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( properties[QStringLiteral( "outline_style" )] ) ); } - else if ( properties.contains( "line_style" ) ) + else if ( properties.contains( QStringLiteral( "line_style" ) ) ) { - layer->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( properties["line_style"] ) ); + layer->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( properties[QStringLiteral( "line_style" )] ) ); } - if ( properties.contains( "joinstyle" ) ) + if ( properties.contains( QStringLiteral( "joinstyle" ) ) ) { - layer->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( properties["joinstyle"] ) ); + layer->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( properties[QStringLiteral( "joinstyle" )] ) ); } - if ( properties.contains( "outline_width" ) ) + if ( properties.contains( QStringLiteral( "outline_width" ) ) ) { - layer->setOutlineWidth( properties["outline_width"].toDouble() ); + layer->setOutlineWidth( properties[QStringLiteral( "outline_width" )].toDouble() ); } - else if ( properties.contains( "line_width" ) ) + else if ( properties.contains( QStringLiteral( "line_width" ) ) ) { - layer->setOutlineWidth( properties["line_width"].toDouble() ); + layer->setOutlineWidth( properties[QStringLiteral( "line_width" )].toDouble() ); } - if ( properties.contains( "outline_width_unit" ) ) + if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) ) { - layer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["outline_width_unit"] ) ); + layer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )] ) ); } - else if ( properties.contains( "line_width_unit" ) ) + else if ( properties.contains( QStringLiteral( "line_width_unit" ) ) ) { - layer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["line_width_unit"] ) ); + layer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "line_width_unit" )] ) ); } - if ( properties.contains( "outline_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) { - layer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["outline_width_map_unit_scale"] ) ); + layer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )] ) ); } - if ( properties.contains( "fill_color" ) ) + if ( properties.contains( QStringLiteral( "fill_color" ) ) ) { //pre 2.5 projects used "fill_color" - layer->setFillColor( QgsSymbolLayerUtils::decodeColor( properties["fill_color"] ) ); + layer->setFillColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "fill_color" )] ) ); } - else if ( properties.contains( "color" ) ) + else if ( properties.contains( QStringLiteral( "color" ) ) ) { - layer->setFillColor( QgsSymbolLayerUtils::decodeColor( properties["color"] ) ); + layer->setFillColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "color" )] ) ); } - if ( properties.contains( "outline_color" ) ) + if ( properties.contains( QStringLiteral( "outline_color" ) ) ) { - layer->setOutlineColor( QgsSymbolLayerUtils::decodeColor( properties["outline_color"] ) ); + layer->setOutlineColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "outline_color" )] ) ); } - else if ( properties.contains( "line_color" ) ) + else if ( properties.contains( QStringLiteral( "line_color" ) ) ) { - layer->setOutlineColor( QgsSymbolLayerUtils::decodeColor( properties["line_color"] ) ); + layer->setOutlineColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "line_color" )] ) ); } - if ( properties.contains( "size" ) ) + if ( properties.contains( QStringLiteral( "size" ) ) ) { - layer->setSize( properties["size"].toDouble() ); + layer->setSize( properties[QStringLiteral( "size" )].toDouble() ); } - if ( properties.contains( "size_unit" ) ) + if ( properties.contains( QStringLiteral( "size_unit" ) ) ) { - layer->setSizeUnit( QgsUnitTypes::decodeRenderUnit( properties["size_unit"] ) ); + layer->setSizeUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "size_unit" )] ) ); } - if ( properties.contains( "size_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "size_map_unit_scale" ) ) ) { - layer->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["size_map_unit_scale"] ) ); + layer->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "size_map_unit_scale" )] ) ); } - if ( properties.contains( "offset" ) ) + if ( properties.contains( QStringLiteral( "offset" ) ) ) { - layer->setOffset( QgsSymbolLayerUtils::decodePoint( properties["offset"] ) ); + layer->setOffset( QgsSymbolLayerUtils::decodePoint( properties[QStringLiteral( "offset" )] ) ); } - if ( properties.contains( "offset_unit" ) ) + if ( properties.contains( QStringLiteral( "offset_unit" ) ) ) { - layer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties["offset_unit"] ) ); + layer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_unit" )] ) ); } - if ( properties.contains( "offset_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) { - layer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["offset_map_unit_scale"] ) ); + layer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_map_unit_scale" )] ) ); } - if ( properties.contains( "horizontal_anchor_point" ) ) + if ( properties.contains( QStringLiteral( "horizontal_anchor_point" ) ) ) { - layer->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( properties[ "horizontal_anchor_point" ].toInt() ) ); + layer->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( properties[ QStringLiteral( "horizontal_anchor_point" )].toInt() ) ); } - if ( properties.contains( "vertical_anchor_point" ) ) + if ( properties.contains( QStringLiteral( "vertical_anchor_point" ) ) ) { - layer->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( properties[ "vertical_anchor_point" ].toInt() ) ); + layer->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( properties[ QStringLiteral( "vertical_anchor_point" )].toInt() ) ); } //data defined properties layer->restoreDataDefinedProperties( properties ); //compatibility with old project file format - if ( !properties["width_field"].isEmpty() ) + if ( !properties[QStringLiteral( "width_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_WIDTH, new QgsDataDefined( properties["width_field"] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_WIDTH, new QgsDataDefined( properties[QStringLiteral( "width_field" )] ) ); } - if ( !properties["height_field"].isEmpty() ) + if ( !properties[QStringLiteral( "height_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_HEIGHT, new QgsDataDefined( properties["height_field"] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_HEIGHT, new QgsDataDefined( properties[QStringLiteral( "height_field" )] ) ); } - if ( !properties["rotation_field"].isEmpty() ) + if ( !properties[QStringLiteral( "rotation_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_ROTATION, new QgsDataDefined( properties["rotation_field"] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_ROTATION, new QgsDataDefined( properties[QStringLiteral( "rotation_field" )] ) ); } - if ( !properties["outline_width_field"].isEmpty() ) + if ( !properties[QStringLiteral( "outline_width_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_OUTLINE_WIDTH, new QgsDataDefined( properties[ "outline_width_field" ] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_OUTLINE_WIDTH, new QgsDataDefined( properties[ QStringLiteral( "outline_width_field" )] ) ); } - if ( !properties["fill_color_field"].isEmpty() ) + if ( !properties[QStringLiteral( "fill_color_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_FILL_COLOR, new QgsDataDefined( properties["fill_color_field"] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_FILL_COLOR, new QgsDataDefined( properties[QStringLiteral( "fill_color_field" )] ) ); } - if ( !properties["outline_color_field"].isEmpty() ) + if ( !properties[QStringLiteral( "outline_color_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_OUTLINE_COLOR, new QgsDataDefined( properties["outline_color_field"] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_OUTLINE_COLOR, new QgsDataDefined( properties[QStringLiteral( "outline_color_field" )] ) ); } - if ( !properties["symbol_name_field"].isEmpty() ) + if ( !properties[QStringLiteral( "symbol_name_field" )].isEmpty() ) { - layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_SYMBOL_NAME, new QgsDataDefined( properties["symbol_name_field"] ) ); + layer->setDataDefinedProperty( QgsSymbolLayer::EXPR_SYMBOL_NAME, new QgsDataDefined( properties[QStringLiteral( "symbol_name_field" )] ) ); } return layer; @@ -338,7 +338,7 @@ void QgsEllipseSymbolLayer::calculateOffsetAndRotation( QgsSymbolRenderContext& QString QgsEllipseSymbolLayer::layerType() const { - return "EllipseMarker"; + return QStringLiteral( "EllipseMarker" ); } void QgsEllipseSymbolLayer::startRender( QgsSymbolRenderContext& context ) @@ -391,13 +391,13 @@ QgsEllipseSymbolLayer* QgsEllipseSymbolLayer::clone() const void QgsEllipseSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { - QDomElement symbolizerElem = doc.createElement( "se:PointSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PointSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); writeSldMarker( doc, symbolizerElem, props ); } @@ -405,7 +405,7 @@ void QgsEllipseSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, cons void QgsEllipseSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { // <Graphic> - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); element.appendChild( graphicElem ); double outlineWidth = QgsSymbolLayerUtils::rescaleUom( mOutlineWidth, mOutlineWidthUnit, props ); @@ -415,7 +415,7 @@ void QgsEllipseSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &elem // <Rotation> QgsDataDefined* ddRotation = getDataDefinedProperty( QgsSymbolLayer::EXPR_ROTATION ); - QString angleFunc = props.value( "angle", "" ); + QString angleFunc = props.value( QStringLiteral( "angle" ), QLatin1String( "" ) ); if ( angleFunc.isEmpty() ) // symbol has no angle set { if ( ddRotation && ddRotation->isActive() ) @@ -429,7 +429,7 @@ void QgsEllipseSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &elem { // the symbol has an angle and the symbol layer have a rotation // property set - angleFunc = QString( "%1 + %2" ).arg( angleFunc, ddRotation->useExpression() ? ddRotation->expressionString() : ddRotation->field() ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( angleFunc, ddRotation->useExpression() ? ddRotation->expressionString() : ddRotation->field() ); } else if ( !qgsDoubleNear( mAngle, 0.0 ) ) { @@ -439,7 +439,7 @@ void QgsEllipseSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &elem if ( !ok ) { // its a string (probably a property name or a function) - angleFunc = QString( "%1 + %2" ).arg( angleFunc ).arg( mAngle ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( angleFunc ).arg( mAngle ); } else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) ) { @@ -455,7 +455,7 @@ void QgsEllipseSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &elem // store w/h factor in a <VendorOption> double widthHeightFactor = mSymbolWidth / mSymbolHeight; - QDomElement factorElem = QgsSymbolLayerUtils::createVendorOptionElement( doc, "widthHeightFactor", QString::number( widthHeightFactor ) ); + QDomElement factorElem = QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "widthHeightFactor" ), QString::number( widthHeightFactor ) ); graphicElem.appendChild( factorElem ); } @@ -463,11 +463,11 @@ QgsSymbolLayer* QgsEllipseSymbolLayer::createFromSld( QDomElement &element ) { QgsDebugMsg( "Entered." ); - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return nullptr; - QString name = "circle"; + QString name = QStringLiteral( "circle" ); QColor fillColor, borderColor; double borderWidth, size; double widthHeightFactor = 1.0; @@ -476,7 +476,7 @@ QgsSymbolLayer* QgsEllipseSymbolLayer::createFromSld( QDomElement &element ) QgsStringMap vendorOptions = QgsSymbolLayerUtils::getVendorOptionList( graphicElem ); for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it ) { - if ( it.key() == "widthHeightFactor" ) + if ( it.key() == QLatin1String( "widthHeightFactor" ) ) { bool ok; double v = it.value().toDouble( &ok ); @@ -513,29 +513,29 @@ QgsSymbolLayer* QgsEllipseSymbolLayer::createFromSld( QDomElement &element ) QgsStringMap QgsEllipseSymbolLayer::properties() const { QgsStringMap map; - map["symbol_name"] = mSymbolName; - map["symbol_width"] = QString::number( mSymbolWidth ); - map["symbol_width_unit"] = QgsUnitTypes::encodeUnit( mSymbolWidthUnit ); - map["symbol_width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSymbolWidthMapUnitScale ); - map["symbol_height"] = QString::number( mSymbolHeight ); - map["symbol_height_unit"] = QgsUnitTypes::encodeUnit( mSymbolHeightUnit ); - map["symbol_height_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSymbolHeightMapUnitScale ); - map["angle"] = QString::number( mAngle ); - map["outline_style"] = QgsSymbolLayerUtils::encodePenStyle( mOutlineStyle ); - map["outline_width"] = QString::number( mOutlineWidth ); - map["outline_width_unit"] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); - map["outline_width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); - map["joinstyle"] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); - map["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["outline_color"] = QgsSymbolLayerUtils::encodeColor( mOutlineColor ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["size"] = QString::number( mSize ); - map["size_unit"] = QgsUnitTypes::encodeUnit( mSizeUnit ); - map["size_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); - map["horizontal_anchor_point"] = QString::number( mHorizontalAnchorPoint ); - map["vertical_anchor_point"] = QString::number( mVerticalAnchorPoint ); + map[QStringLiteral( "symbol_name" )] = mSymbolName; + map[QStringLiteral( "symbol_width" )] = QString::number( mSymbolWidth ); + map[QStringLiteral( "symbol_width_unit" )] = QgsUnitTypes::encodeUnit( mSymbolWidthUnit ); + map[QStringLiteral( "symbol_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSymbolWidthMapUnitScale ); + map[QStringLiteral( "symbol_height" )] = QString::number( mSymbolHeight ); + map[QStringLiteral( "symbol_height_unit" )] = QgsUnitTypes::encodeUnit( mSymbolHeightUnit ); + map[QStringLiteral( "symbol_height_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSymbolHeightMapUnitScale ); + map[QStringLiteral( "angle" )] = QString::number( mAngle ); + map[QStringLiteral( "outline_style" )] = QgsSymbolLayerUtils::encodePenStyle( mOutlineStyle ); + map[QStringLiteral( "outline_width" )] = QString::number( mOutlineWidth ); + map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); + map[QStringLiteral( "outline_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); + map[QStringLiteral( "joinstyle" )] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "outline_color" )] = QgsSymbolLayerUtils::encodeColor( mOutlineColor ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "size" )] = QString::number( mSize ); + map[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit ); + map[QStringLiteral( "size_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); + map[QStringLiteral( "horizontal_anchor_point" )] = QString::number( mHorizontalAnchorPoint ); + map[QStringLiteral( "vertical_anchor_point" )] = QString::number( mVerticalAnchorPoint ); saveDataDefinedProperties( map ); return map; } @@ -583,20 +583,20 @@ void QgsEllipseSymbolLayer::preparePath( const QString& symbolName, QgsSymbolRen QSizeF size = calculateSize( context, scaledWidth, scaledHeight ); - if ( symbolName == "circle" ) + if ( symbolName == QLatin1String( "circle" ) ) { mPainterPath.addEllipse( QRectF( -size.width() / 2.0, -size.height() / 2.0, size.width(), size.height() ) ); } - else if ( symbolName == "semi_circle" ) + else if ( symbolName == QLatin1String( "semi_circle" ) ) { mPainterPath.arcTo( -size.width() / 2.0, -size.height() / 2.0, size.width(), size.height(), 0, 180 ); mPainterPath.lineTo( 0, 0 ); } - else if ( symbolName == "rectangle" ) + else if ( symbolName == QLatin1String( "rectangle" ) ) { mPainterPath.addRect( QRectF( -size.width() / 2.0, -size.height() / 2.0, size.width(), size.height() ) ); } - else if ( symbolName == "diamond" ) + else if ( symbolName == QLatin1String( "diamond" ) ) { mPainterPath.moveTo( -size.width() / 2.0, 0 ); mPainterPath.lineTo( 0, size.height() / 2.0 ); @@ -604,28 +604,28 @@ void QgsEllipseSymbolLayer::preparePath( const QString& symbolName, QgsSymbolRen mPainterPath.lineTo( 0, -size.height() / 2.0 ); mPainterPath.lineTo( -size.width() / 2.0, 0 ); } - else if ( symbolName == "cross" ) + else if ( symbolName == QLatin1String( "cross" ) ) { mPainterPath.moveTo( 0, -size.height() / 2.0 ); mPainterPath.lineTo( 0, size.height() / 2.0 ); mPainterPath.moveTo( -size.width() / 2.0, 0 ); mPainterPath.lineTo( size.width() / 2.0, 0 ); } - else if ( symbolName == "triangle" ) + else if ( symbolName == QLatin1String( "triangle" ) ) { mPainterPath.moveTo( 0, -size.height() / 2.0 ); mPainterPath.lineTo( -size.width() / 2.0, size.height() / 2.0 ); mPainterPath.lineTo( size.width() / 2.0, size.height() / 2.0 ); mPainterPath.lineTo( 0, -size.height() / 2.0 ); } - else if ( symbolName == "left_half_triangle" ) + else if ( symbolName == QLatin1String( "left_half_triangle" ) ) { mPainterPath.moveTo( 0, size.height() / 2.0 ); mPainterPath.lineTo( size.width() / 2.0, size.height() / 2.0 ); mPainterPath.lineTo( 0, -size.height() / 2.0 ); mPainterPath.lineTo( 0, size.height() / 2.0 ); } - else if ( symbolName == "right_half_triangle" ) + else if ( symbolName == QLatin1String( "right_half_triangle" ) ) { mPainterPath.moveTo( -size.width() / 2.0, size.height() / 2.0 ); mPainterPath.lineTo( 0, size.height() / 2.0 ); @@ -705,7 +705,7 @@ QRectF QgsEllipseSymbolLayer::bounds( QPointF point, QgsSymbolRenderContext& con { context.setOriginalValueVariable( QgsSymbolLayerUtils::encodePenStyle( mOutlineStyle ) ); QString outlineStyle = evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_OUTLINE_STYLE, context, QVariant(), &ok ).toString(); - if ( ok && outlineStyle == "no" ) + if ( ok && outlineStyle == QLatin1String( "no" ) ) { penWidth = 0.0; } @@ -825,7 +825,7 @@ bool QgsEllipseSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFact double halfWidth = symbolWidth / 2.0; double halfHeight = symbolHeight / 2.0; - if ( symbolName == "circle" ) + if ( symbolName == QLatin1String( "circle" ) ) { if ( qgsDoubleNear( halfWidth, halfHeight ) ) { @@ -848,12 +848,12 @@ bool QgsEllipseSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFact line << line.at( 0 ); if ( mBrush.style() != Qt::NoBrush ) - e.writePolygon( QgsRingSequence() << line, layerName, "SOLID", fc ); + e.writePolygon( QgsRingSequence() << line, layerName, QStringLiteral( "SOLID" ), fc ); if ( mPen.style() != Qt::NoPen ) - e.writePolyline( line, layerName, "CONTINUOUS", oc, outlineWidth ); + e.writePolyline( line, layerName, QStringLiteral( "CONTINUOUS" ), oc, outlineWidth ); } } - else if ( symbolName == "rectangle" ) + else if ( symbolName == QLatin1String( "rectangle" ) ) { QgsPointSequence p; p << QgsPointV2( t.map( QPointF( -halfWidth, -halfHeight ) ) ) @@ -863,24 +863,24 @@ bool QgsEllipseSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFact p << p[0]; if ( mBrush.style() != Qt::NoBrush ) - e.writePolygon( QgsRingSequence() << p, layerName, "SOLID", fc ); + e.writePolygon( QgsRingSequence() << p, layerName, QStringLiteral( "SOLID" ), fc ); if ( mPen.style() != Qt::NoPen ) - e.writePolyline( p, layerName, "CONTINUOUS", oc, outlineWidth ); + e.writePolyline( p, layerName, QStringLiteral( "CONTINUOUS" ), oc, outlineWidth ); return true; } - else if ( symbolName == "cross" && mPen.style() != Qt::NoPen ) + else if ( symbolName == QLatin1String( "cross" ) && mPen.style() != Qt::NoPen ) { e.writePolyline( QgsPointSequence() << QgsPointV2( t.map( QPointF( -halfWidth, 0 ) ) ) << QgsPointV2( t.map( QPointF( halfWidth, 0 ) ) ), - layerName, "CONTINUOUS", oc, outlineWidth ); + layerName, QStringLiteral( "CONTINUOUS" ), oc, outlineWidth ); e.writePolyline( QgsPointSequence() << QgsPointV2( t.map( QPointF( 0, halfHeight ) ) ) << QgsPointV2( t.map( QPointF( 0, -halfHeight ) ) ), - layerName, "CONTINUOUS", oc, outlineWidth ); + layerName, QStringLiteral( "CONTINUOUS" ), oc, outlineWidth ); return true; } - else if ( symbolName == "triangle" ) + else if ( symbolName == QLatin1String( "triangle" ) ) { QgsPointSequence p; p << QgsPointV2( t.map( QPointF( -halfWidth, -halfHeight ) ) ) @@ -888,9 +888,9 @@ bool QgsEllipseSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFact << QgsPointV2( t.map( QPointF( 0, halfHeight ) ) ); p << p[0]; if ( mBrush.style() != Qt::NoBrush ) - e.writePolygon( QgsRingSequence() << p, layerName, "SOLID", fc ); + e.writePolygon( QgsRingSequence() << p, layerName, QStringLiteral( "SOLID" ), fc ); if ( mPen.style() != Qt::NoPen ) - e.writePolyline( p, layerName, "CONTINUOUS", oc, outlineWidth ); + e.writePolyline( p, layerName, QStringLiteral( "CONTINUOUS" ), oc, outlineWidth ); return true; } diff --git a/src/core/symbology-ng/qgsfillsymbollayer.cpp b/src/core/symbology-ng/qgsfillsymbollayer.cpp index 0baa7acb0c8c..c23ecc085495 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.cpp +++ b/src/core/symbology-ng/qgsfillsymbollayer.cpp @@ -147,76 +147,76 @@ QgsSymbolLayer* QgsSimpleFillSymbolLayer::create( const QgsStringMap& props ) Qt::PenJoinStyle penJoinStyle = DEFAULT_SIMPLEFILL_JOINSTYLE; QPointF offset; - if ( props.contains( "color" ) ) - color = QgsSymbolLayerUtils::decodeColor( props["color"] ); - if ( props.contains( "style" ) ) - style = QgsSymbolLayerUtils::decodeBrushStyle( props["style"] ); - if ( props.contains( "color_border" ) ) + if ( props.contains( QStringLiteral( "color" ) ) ) + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ); + if ( props.contains( QStringLiteral( "style" ) ) ) + style = QgsSymbolLayerUtils::decodeBrushStyle( props[QStringLiteral( "style" )] ); + if ( props.contains( QStringLiteral( "color_border" ) ) ) { //pre 2.5 projects used "color_border" - borderColor = QgsSymbolLayerUtils::decodeColor( props["color_border"] ); + borderColor = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color_border" )] ); } - else if ( props.contains( "outline_color" ) ) + else if ( props.contains( QStringLiteral( "outline_color" ) ) ) { - borderColor = QgsSymbolLayerUtils::decodeColor( props["outline_color"] ); + borderColor = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "outline_color" )] ); } - else if ( props.contains( "line_color" ) ) + else if ( props.contains( QStringLiteral( "line_color" ) ) ) { - borderColor = QgsSymbolLayerUtils::decodeColor( props["line_color"] ); + borderColor = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "line_color" )] ); } - if ( props.contains( "style_border" ) ) + if ( props.contains( QStringLiteral( "style_border" ) ) ) { //pre 2.5 projects used "style_border" - borderStyle = QgsSymbolLayerUtils::decodePenStyle( props["style_border"] ); + borderStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "style_border" )] ); } - else if ( props.contains( "outline_style" ) ) + else if ( props.contains( QStringLiteral( "outline_style" ) ) ) { - borderStyle = QgsSymbolLayerUtils::decodePenStyle( props["outline_style"] ); + borderStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "outline_style" )] ); } - else if ( props.contains( "line_style" ) ) + else if ( props.contains( QStringLiteral( "line_style" ) ) ) { - borderStyle = QgsSymbolLayerUtils::decodePenStyle( props["line_style"] ); + borderStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "line_style" )] ); } - if ( props.contains( "width_border" ) ) + if ( props.contains( QStringLiteral( "width_border" ) ) ) { //pre 2.5 projects used "width_border" - borderWidth = props["width_border"].toDouble(); + borderWidth = props[QStringLiteral( "width_border" )].toDouble(); } - else if ( props.contains( "outline_width" ) ) + else if ( props.contains( QStringLiteral( "outline_width" ) ) ) { - borderWidth = props["outline_width"].toDouble(); + borderWidth = props[QStringLiteral( "outline_width" )].toDouble(); } - else if ( props.contains( "line_width" ) ) + else if ( props.contains( QStringLiteral( "line_width" ) ) ) { - borderWidth = props["line_width"].toDouble(); + borderWidth = props[QStringLiteral( "line_width" )].toDouble(); } - if ( props.contains( "offset" ) ) - offset = QgsSymbolLayerUtils::decodePoint( props["offset"] ); - if ( props.contains( "joinstyle" ) ) - penJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( props["joinstyle"] ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + offset = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ); + if ( props.contains( QStringLiteral( "joinstyle" ) ) ) + penJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( props[QStringLiteral( "joinstyle" )] ); QgsSimpleFillSymbolLayer* sl = new QgsSimpleFillSymbolLayer( color, style, borderColor, borderStyle, borderWidth, penJoinStyle ); sl->setOffset( offset ); - if ( props.contains( "border_width_unit" ) ) + if ( props.contains( QStringLiteral( "border_width_unit" ) ) ) { - sl->setBorderWidthUnit( QgsUnitTypes::decodeRenderUnit( props["border_width_unit"] ) ); + sl->setBorderWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "border_width_unit" )] ) ); } - else if ( props.contains( "outline_width_unit" ) ) + else if ( props.contains( QStringLiteral( "outline_width_unit" ) ) ) { - sl->setBorderWidthUnit( QgsUnitTypes::decodeRenderUnit( props["outline_width_unit"] ) ); + sl->setBorderWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "outline_width_unit" )] ) ); } - else if ( props.contains( "line_width_unit" ) ) + else if ( props.contains( QStringLiteral( "line_width_unit" ) ) ) { - sl->setBorderWidthUnit( QgsUnitTypes::decodeRenderUnit( props["line_width_unit"] ) ); + sl->setBorderWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "line_width_unit" )] ) ); } - if ( props.contains( "offset_unit" ) ) - sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); - if ( props.contains( "border_width_map_unit_scale" ) ) - sl->setBorderWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["border_width_map_unit_scale"] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "border_width_map_unit_scale" ) ) ) + sl->setBorderWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "border_width_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); sl->restoreDataDefinedProperties( props ); @@ -226,7 +226,7 @@ QgsSymbolLayer* QgsSimpleFillSymbolLayer::create( const QgsStringMap& props ) QString QgsSimpleFillSymbolLayer::layerType() const { - return "SimpleFill"; + return QStringLiteral( "SimpleFill" ); } void QgsSimpleFillSymbolLayer::startRender( QgsSymbolRenderContext& context ) @@ -297,17 +297,17 @@ void QgsSimpleFillSymbolLayer::renderPolygon( const QPolygonF& points, QList<QPo QgsStringMap QgsSimpleFillSymbolLayer::properties() const { QgsStringMap map; - map["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["style"] = QgsSymbolLayerUtils::encodeBrushStyle( mBrushStyle ); - map["outline_color"] = QgsSymbolLayerUtils::encodeColor( mBorderColor ); - map["outline_style"] = QgsSymbolLayerUtils::encodePenStyle( mBorderStyle ); - map["outline_width"] = QString::number( mBorderWidth ); - map["outline_width_unit"] = QgsUnitTypes::encodeUnit( mBorderWidthUnit ); - map["border_width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mBorderWidthMapUnitScale ); - map["joinstyle"] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "style" )] = QgsSymbolLayerUtils::encodeBrushStyle( mBrushStyle ); + map[QStringLiteral( "outline_color" )] = QgsSymbolLayerUtils::encodeColor( mBorderColor ); + map[QStringLiteral( "outline_style" )] = QgsSymbolLayerUtils::encodePenStyle( mBorderStyle ); + map[QStringLiteral( "outline_width" )] = QString::number( mBorderWidth ); + map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( mBorderWidthUnit ); + map[QStringLiteral( "border_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mBorderWidthMapUnitScale ); + map[QStringLiteral( "joinstyle" )] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); saveDataDefinedProperties( map ); return map; } @@ -330,18 +330,18 @@ void QgsSimpleFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c if ( mBrushStyle == Qt::NoBrush && mBorderStyle == Qt::NoPen ) return; - QDomElement symbolizerElem = doc.createElement( "se:PolygonSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); if ( mBrushStyle != Qt::NoBrush ) { // <Fill> - QDomElement fillElem = doc.createElement( "se:Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) ); symbolizerElem.appendChild( fillElem ); QgsSymbolLayerUtils::fillToSld( doc, fillElem, mBrushStyle, mColor ); } @@ -349,7 +349,7 @@ void QgsSimpleFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c if ( mBorderStyle != Qt::NoPen ) { // <Stroke> - QDomElement strokeElem = doc.createElement( "se:Stroke" ); + QDomElement strokeElem = doc.createElement( QStringLiteral( "se:Stroke" ) ); symbolizerElem.appendChild( strokeElem ); double borderWidth = QgsSymbolLayerUtils::rescaleUom( mBorderWidth, mBorderWidthUnit, props ); QgsSymbolLayerUtils::lineToSld( doc, strokeElem, mBorderStyle, borderWidth, borderWidth, &mPenJoinStyle ); @@ -380,10 +380,10 @@ QgsSymbolLayer* QgsSimpleFillSymbolLayer::createFromSld( QDomElement &element ) Qt::PenStyle borderStyle; double borderWidth; - QDomElement fillElem = element.firstChildElement( "Fill" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); QgsSymbolLayerUtils::fillFromSld( fillElem, fillStyle, color ); - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); QgsSymbolLayerUtils::lineFromSld( strokeElem, borderStyle, borderColor, borderWidth ); QPointF offset; @@ -501,41 +501,41 @@ QgsSymbolLayer* QgsGradientFillSymbolLayer::create( const QgsStringMap& props ) QPointF offset; //update gradient properties from props - if ( props.contains( "type" ) ) - type = static_cast< GradientType >( props["type"].toInt() ); - if ( props.contains( "coordinate_mode" ) ) - coordinateMode = static_cast< GradientCoordinateMode >( props["coordinate_mode"].toInt() ); - if ( props.contains( "spread" ) ) - gradientSpread = static_cast< GradientSpread >( props["spread"].toInt() ); - if ( props.contains( "color_type" ) ) - colorType = static_cast< GradientColorType >( props["color_type"].toInt() ); - if ( props.contains( "gradient_color" ) ) + if ( props.contains( QStringLiteral( "type" ) ) ) + type = static_cast< GradientType >( props[QStringLiteral( "type" )].toInt() ); + if ( props.contains( QStringLiteral( "coordinate_mode" ) ) ) + coordinateMode = static_cast< GradientCoordinateMode >( props[QStringLiteral( "coordinate_mode" )].toInt() ); + if ( props.contains( QStringLiteral( "spread" ) ) ) + gradientSpread = static_cast< GradientSpread >( props[QStringLiteral( "spread" )].toInt() ); + if ( props.contains( QStringLiteral( "color_type" ) ) ) + colorType = static_cast< GradientColorType >( props[QStringLiteral( "color_type" )].toInt() ); + if ( props.contains( QStringLiteral( "gradient_color" ) ) ) { //pre 2.5 projects used "gradient_color" - color = QgsSymbolLayerUtils::decodeColor( props["gradient_color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "gradient_color" )] ); } - else if ( props.contains( "color" ) ) + else if ( props.contains( QStringLiteral( "color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( props["color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ); } - if ( props.contains( "gradient_color2" ) ) + if ( props.contains( QStringLiteral( "gradient_color2" ) ) ) { - color2 = QgsSymbolLayerUtils::decodeColor( props["gradient_color2"] ); + color2 = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "gradient_color2" )] ); } - if ( props.contains( "reference_point1" ) ) - referencePoint1 = QgsSymbolLayerUtils::decodePoint( props["reference_point1"] ); - if ( props.contains( "reference_point1_iscentroid" ) ) - refPoint1IsCentroid = props["reference_point1_iscentroid"].toInt(); - if ( props.contains( "reference_point2" ) ) - referencePoint2 = QgsSymbolLayerUtils::decodePoint( props["reference_point2"] ); - if ( props.contains( "reference_point2_iscentroid" ) ) - refPoint2IsCentroid = props["reference_point2_iscentroid"].toInt(); - if ( props.contains( "angle" ) ) - angle = props["angle"].toDouble(); + if ( props.contains( QStringLiteral( "reference_point1" ) ) ) + referencePoint1 = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "reference_point1" )] ); + if ( props.contains( QStringLiteral( "reference_point1_iscentroid" ) ) ) + refPoint1IsCentroid = props[QStringLiteral( "reference_point1_iscentroid" )].toInt(); + if ( props.contains( QStringLiteral( "reference_point2" ) ) ) + referencePoint2 = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "reference_point2" )] ); + if ( props.contains( QStringLiteral( "reference_point2_iscentroid" ) ) ) + refPoint2IsCentroid = props[QStringLiteral( "reference_point2_iscentroid" )].toInt(); + if ( props.contains( QStringLiteral( "angle" ) ) ) + angle = props[QStringLiteral( "angle" )].toDouble(); - if ( props.contains( "offset" ) ) - offset = QgsSymbolLayerUtils::decodePoint( props["offset"] ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + offset = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ); //attempt to create color ramp from props QgsColorRamp* gradientRamp = QgsGradientColorRamp::create( props ); @@ -543,10 +543,10 @@ QgsSymbolLayer* QgsGradientFillSymbolLayer::create( const QgsStringMap& props ) //create a new gradient fill layer with desired properties QgsGradientFillSymbolLayer* sl = new QgsGradientFillSymbolLayer( color, color2, colorType, type, coordinateMode, gradientSpread ); sl->setOffset( offset ); - if ( props.contains( "offset_unit" ) ) - sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); sl->setReferencePoint1( referencePoint1 ); sl->setReferencePoint1IsCentroid( refPoint1IsCentroid ); sl->setReferencePoint2( referencePoint2 ); @@ -568,7 +568,7 @@ void QgsGradientFillSymbolLayer::setColorRamp( QgsColorRamp* ramp ) QString QgsGradientFillSymbolLayer::layerType() const { - return "GradientFill"; + return QStringLiteral( "GradientFill" ); } void QgsGradientFillSymbolLayer::applyDataDefinedSymbology( QgsSymbolRenderContext& context, const QPolygonF& points ) @@ -815,7 +815,7 @@ void QgsGradientFillSymbolLayer::applyGradient( const QgsSymbolRenderContext &co } //add stops to gradient - if ( gradientColorType == QgsGradientFillSymbolLayer::ColorRamp && gradientRamp && gradientRamp->type() == "gradient" ) + if ( gradientColorType == QgsGradientFillSymbolLayer::ColorRamp && gradientRamp && gradientRamp->type() == QLatin1String( "gradient" ) ) { //color ramp gradient QgsGradientColorRamp* gradRamp = static_cast<QgsGradientColorRamp*>( gradientRamp ); @@ -876,20 +876,20 @@ void QgsGradientFillSymbolLayer::renderPolygon( const QPolygonF& points, QList<Q QgsStringMap QgsGradientFillSymbolLayer::properties() const { QgsStringMap map; - map["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["gradient_color2"] = QgsSymbolLayerUtils::encodeColor( mColor2 ); - map["color_type"] = QString::number( mGradientColorType ); - map["type"] = QString::number( mGradientType ); - map["coordinate_mode"] = QString::number( mCoordinateMode ); - map["spread"] = QString::number( mGradientSpread ); - map["reference_point1"] = QgsSymbolLayerUtils::encodePoint( mReferencePoint1 ); - map["reference_point1_iscentroid"] = QString::number( mReferencePoint1IsCentroid ); - map["reference_point2"] = QgsSymbolLayerUtils::encodePoint( mReferencePoint2 ); - map["reference_point2_iscentroid"] = QString::number( mReferencePoint2IsCentroid ); - map["angle"] = QString::number( mAngle ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "gradient_color2" )] = QgsSymbolLayerUtils::encodeColor( mColor2 ); + map[QStringLiteral( "color_type" )] = QString::number( mGradientColorType ); + map[QStringLiteral( "type" )] = QString::number( mGradientType ); + map[QStringLiteral( "coordinate_mode" )] = QString::number( mCoordinateMode ); + map[QStringLiteral( "spread" )] = QString::number( mGradientSpread ); + map[QStringLiteral( "reference_point1" )] = QgsSymbolLayerUtils::encodePoint( mReferencePoint1 ); + map[QStringLiteral( "reference_point1_iscentroid" )] = QString::number( mReferencePoint1IsCentroid ); + map[QStringLiteral( "reference_point2" )] = QgsSymbolLayerUtils::encodePoint( mReferencePoint2 ); + map[QStringLiteral( "reference_point2_iscentroid" )] = QString::number( mReferencePoint2IsCentroid ); + map[QStringLiteral( "angle" )] = QString::number( mAngle ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); saveDataDefinedProperties( map ); if ( mGradientRamp ) { @@ -976,44 +976,44 @@ QgsSymbolLayer* QgsShapeburstFillSymbolLayer::create( const QgsStringMap& props QPointF offset; //update fill properties from props - if ( props.contains( "color_type" ) ) + if ( props.contains( QStringLiteral( "color_type" ) ) ) { - colorType = static_cast< ShapeburstColorType >( props["color_type"].toInt() ); + colorType = static_cast< ShapeburstColorType >( props[QStringLiteral( "color_type" )].toInt() ); } - if ( props.contains( "shapeburst_color" ) ) + if ( props.contains( QStringLiteral( "shapeburst_color" ) ) ) { //pre 2.5 projects used "shapeburst_color" - color = QgsSymbolLayerUtils::decodeColor( props["shapeburst_color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "shapeburst_color" )] ); } - else if ( props.contains( "color" ) ) + else if ( props.contains( QStringLiteral( "color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( props["color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ); } - if ( props.contains( "shapeburst_color2" ) ) + if ( props.contains( QStringLiteral( "shapeburst_color2" ) ) ) { //pre 2.5 projects used "shapeburst_color2" - color2 = QgsSymbolLayerUtils::decodeColor( props["shapeburst_color2"] ); + color2 = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "shapeburst_color2" )] ); } - else if ( props.contains( "gradient_color2" ) ) + else if ( props.contains( QStringLiteral( "gradient_color2" ) ) ) { - color2 = QgsSymbolLayerUtils::decodeColor( props["gradient_color2"] ); + color2 = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "gradient_color2" )] ); } - if ( props.contains( "blur_radius" ) ) + if ( props.contains( QStringLiteral( "blur_radius" ) ) ) { - blurRadius = props["blur_radius"].toInt(); + blurRadius = props[QStringLiteral( "blur_radius" )].toInt(); } - if ( props.contains( "use_whole_shape" ) ) + if ( props.contains( QStringLiteral( "use_whole_shape" ) ) ) { - useWholeShape = props["use_whole_shape"].toInt(); + useWholeShape = props[QStringLiteral( "use_whole_shape" )].toInt(); } - if ( props.contains( "max_distance" ) ) + if ( props.contains( QStringLiteral( "max_distance" ) ) ) { - maxDistance = props["max_distance"].toDouble(); + maxDistance = props[QStringLiteral( "max_distance" )].toDouble(); } - if ( props.contains( "offset" ) ) + if ( props.contains( QStringLiteral( "offset" ) ) ) { - offset = QgsSymbolLayerUtils::decodePoint( props["offset"] ); + offset = QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ); } //attempt to create color ramp from props @@ -1022,25 +1022,25 @@ QgsSymbolLayer* QgsShapeburstFillSymbolLayer::create( const QgsStringMap& props //create a new shapeburst fill layer with desired properties QgsShapeburstFillSymbolLayer* sl = new QgsShapeburstFillSymbolLayer( color, color2, colorType, blurRadius, useWholeShape, maxDistance ); sl->setOffset( offset ); - if ( props.contains( "offset_unit" ) ) + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) { - sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); + sl->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); } - if ( props.contains( "distance_unit" ) ) + if ( props.contains( QStringLiteral( "distance_unit" ) ) ) { - sl->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( props["distance_unit"] ) ); + sl->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "distance_unit" )] ) ); } - if ( props.contains( "offset_map_unit_scale" ) ) + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) { - sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); + sl->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); } - if ( props.contains( "distance_map_unit_scale" ) ) + if ( props.contains( QStringLiteral( "distance_map_unit_scale" ) ) ) { - sl->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["distance_map_unit_scale"] ) ); + sl->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "distance_map_unit_scale" )] ) ); } - if ( props.contains( "ignore_rings" ) ) + if ( props.contains( QStringLiteral( "ignore_rings" ) ) ) { - sl->setIgnoreRings( props["ignore_rings"].toInt() ); + sl->setIgnoreRings( props[QStringLiteral( "ignore_rings" )].toInt() ); } if ( gradientRamp ) { @@ -1054,7 +1054,7 @@ QgsSymbolLayer* QgsShapeburstFillSymbolLayer::create( const QgsStringMap& props QString QgsShapeburstFillSymbolLayer::layerType() const { - return "ShapeburstFill"; + return QStringLiteral( "ShapeburstFill" ); } void QgsShapeburstFillSymbolLayer::setColorRamp( QgsColorRamp* ramp ) @@ -1475,18 +1475,18 @@ void QgsShapeburstFillSymbolLayer::dtArrayToQImage( double * array, QImage *im, QgsStringMap QgsShapeburstFillSymbolLayer::properties() const { QgsStringMap map; - map["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["gradient_color2"] = QgsSymbolLayerUtils::encodeColor( mColor2 ); - map["color_type"] = QString::number( mColorType ); - map["blur_radius"] = QString::number( mBlurRadius ); - map["use_whole_shape"] = QString::number( mUseWholeShape ); - map["max_distance"] = QString::number( mMaxDistance ); - map["distance_unit"] = QgsUnitTypes::encodeUnit( mDistanceUnit ); - map["distance_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ); - map["ignore_rings"] = QString::number( mIgnoreRings ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "gradient_color2" )] = QgsSymbolLayerUtils::encodeColor( mColor2 ); + map[QStringLiteral( "color_type" )] = QString::number( mColorType ); + map[QStringLiteral( "blur_radius" )] = QString::number( mBlurRadius ); + map[QStringLiteral( "use_whole_shape" )] = QString::number( mUseWholeShape ); + map[QStringLiteral( "max_distance" )] = QString::number( mMaxDistance ); + map[QStringLiteral( "distance_unit" )] = QgsUnitTypes::encodeUnit( mDistanceUnit ); + map[QStringLiteral( "distance_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ); + map[QStringLiteral( "ignore_rings" )] = QString::number( mIgnoreRings ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); saveDataDefinedProperties( map ); @@ -1822,19 +1822,19 @@ QgsSymbolLayer* QgsSVGFillSymbolLayer::create( const QgsStringMap& properties ) QString svgFilePath; double angle = 0.0; - if ( properties.contains( "width" ) ) + if ( properties.contains( QStringLiteral( "width" ) ) ) { - width = properties["width"].toDouble(); + width = properties[QStringLiteral( "width" )].toDouble(); } - if ( properties.contains( "svgFile" ) ) + if ( properties.contains( QStringLiteral( "svgFile" ) ) ) { - QString svgName = properties["svgFile"]; + QString svgName = properties[QStringLiteral( "svgFile" )]; QString savePath = QgsSymbolLayerUtils::symbolNameToPath( svgName ); svgFilePath = ( savePath.isEmpty() ? svgName : savePath ); } - if ( properties.contains( "angle" ) ) + if ( properties.contains( QStringLiteral( "angle" ) ) ) { - angle = properties["angle"].toDouble(); + angle = properties[QStringLiteral( "angle" )].toDouble(); } QgsSVGFillSymbolLayer* symbolLayer = nullptr; @@ -1844,74 +1844,74 @@ QgsSymbolLayer* QgsSVGFillSymbolLayer::create( const QgsStringMap& properties ) } else { - if ( properties.contains( "data" ) ) + if ( properties.contains( QStringLiteral( "data" ) ) ) { - data = QByteArray::fromHex( properties["data"].toLocal8Bit() ); + data = QByteArray::fromHex( properties[QStringLiteral( "data" )].toLocal8Bit() ); } symbolLayer = new QgsSVGFillSymbolLayer( data, width, angle ); } //svg parameters - if ( properties.contains( "svgFillColor" ) ) + if ( properties.contains( QStringLiteral( "svgFillColor" ) ) ) { //pre 2.5 projects used "svgFillColor" - symbolLayer->setSvgFillColor( QgsSymbolLayerUtils::decodeColor( properties["svgFillColor"] ) ); + symbolLayer->setSvgFillColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "svgFillColor" )] ) ); } - else if ( properties.contains( "color" ) ) + else if ( properties.contains( QStringLiteral( "color" ) ) ) { - symbolLayer->setSvgFillColor( QgsSymbolLayerUtils::decodeColor( properties["color"] ) ); + symbolLayer->setSvgFillColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "color" )] ) ); } - if ( properties.contains( "svgOutlineColor" ) ) + if ( properties.contains( QStringLiteral( "svgOutlineColor" ) ) ) { //pre 2.5 projects used "svgOutlineColor" - symbolLayer->setSvgOutlineColor( QgsSymbolLayerUtils::decodeColor( properties["svgOutlineColor"] ) ); + symbolLayer->setSvgOutlineColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "svgOutlineColor" )] ) ); } - else if ( properties.contains( "outline_color" ) ) + else if ( properties.contains( QStringLiteral( "outline_color" ) ) ) { - symbolLayer->setSvgOutlineColor( QgsSymbolLayerUtils::decodeColor( properties["outline_color"] ) ); + symbolLayer->setSvgOutlineColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "outline_color" )] ) ); } - else if ( properties.contains( "line_color" ) ) + else if ( properties.contains( QStringLiteral( "line_color" ) ) ) { - symbolLayer->setSvgOutlineColor( QgsSymbolLayerUtils::decodeColor( properties["line_color"] ) ); + symbolLayer->setSvgOutlineColor( QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "line_color" )] ) ); } - if ( properties.contains( "svgOutlineWidth" ) ) + if ( properties.contains( QStringLiteral( "svgOutlineWidth" ) ) ) { //pre 2.5 projects used "svgOutlineWidth" - symbolLayer->setSvgOutlineWidth( properties["svgOutlineWidth"].toDouble() ); + symbolLayer->setSvgOutlineWidth( properties[QStringLiteral( "svgOutlineWidth" )].toDouble() ); } - else if ( properties.contains( "outline_width" ) ) + else if ( properties.contains( QStringLiteral( "outline_width" ) ) ) { - symbolLayer->setSvgOutlineWidth( properties["outline_width"].toDouble() ); + symbolLayer->setSvgOutlineWidth( properties[QStringLiteral( "outline_width" )].toDouble() ); } - else if ( properties.contains( "line_width" ) ) + else if ( properties.contains( QStringLiteral( "line_width" ) ) ) { - symbolLayer->setSvgOutlineWidth( properties["line_width"].toDouble() ); + symbolLayer->setSvgOutlineWidth( properties[QStringLiteral( "line_width" )].toDouble() ); } //units - if ( properties.contains( "pattern_width_unit" ) ) + if ( properties.contains( QStringLiteral( "pattern_width_unit" ) ) ) { - symbolLayer->setPatternWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["pattern_width_unit"] ) ); + symbolLayer->setPatternWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "pattern_width_unit" )] ) ); } - if ( properties.contains( "pattern_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "pattern_width_map_unit_scale" ) ) ) { - symbolLayer->setPatternWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["pattern_width_map_unit_scale"] ) ); + symbolLayer->setPatternWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "pattern_width_map_unit_scale" )] ) ); } - if ( properties.contains( "svg_outline_width_unit" ) ) + if ( properties.contains( QStringLiteral( "svg_outline_width_unit" ) ) ) { - symbolLayer->setSvgOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["svg_outline_width_unit"] ) ); + symbolLayer->setSvgOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "svg_outline_width_unit" )] ) ); } - if ( properties.contains( "svg_outline_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "svg_outline_width_map_unit_scale" ) ) ) { - symbolLayer->setSvgOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["svg_outline_width_map_unit_scale"] ) ); + symbolLayer->setSvgOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "svg_outline_width_map_unit_scale" )] ) ); } - if ( properties.contains( "outline_width_unit" ) ) + if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) ) { - symbolLayer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["outline_width_unit"] ) ); + symbolLayer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )] ) ); } - if ( properties.contains( "outline_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) { - symbolLayer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["outline_width_map_unit_scale"] ) ); + symbolLayer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )] ) ); } symbolLayer->restoreDataDefinedProperties( properties ); @@ -1921,7 +1921,7 @@ QgsSymbolLayer* QgsSVGFillSymbolLayer::create( const QgsStringMap& properties ) QString QgsSVGFillSymbolLayer::layerType() const { - return "SVGFill"; + return QStringLiteral( "SVGFill" ); } void QgsSVGFillSymbolLayer::applyPattern( QBrush& brush, const QString& svgFilePath, double patternWidth, QgsUnitTypes::RenderUnit patternWidthUnit, @@ -2005,28 +2005,28 @@ QgsStringMap QgsSVGFillSymbolLayer::properties() const QgsStringMap map; if ( !mSvgFilePath.isEmpty() ) { - map.insert( "svgFile", QgsSymbolLayerUtils::symbolPathToName( mSvgFilePath ) ); + map.insert( QStringLiteral( "svgFile" ), QgsSymbolLayerUtils::symbolPathToName( mSvgFilePath ) ); } else { - map.insert( "data", QString( mSvgData.toHex() ) ); + map.insert( QStringLiteral( "data" ), QString( mSvgData.toHex() ) ); } - map.insert( "width", QString::number( mPatternWidth ) ); - map.insert( "angle", QString::number( mAngle ) ); + map.insert( QStringLiteral( "width" ), QString::number( mPatternWidth ) ); + map.insert( QStringLiteral( "angle" ), QString::number( mAngle ) ); //svg parameters - map.insert( "color", QgsSymbolLayerUtils::encodeColor( mColor ) ); - map.insert( "outline_color", QgsSymbolLayerUtils::encodeColor( mSvgOutlineColor ) ); - map.insert( "outline_width", QString::number( mSvgOutlineWidth ) ); + map.insert( QStringLiteral( "color" ), QgsSymbolLayerUtils::encodeColor( mColor ) ); + map.insert( QStringLiteral( "outline_color" ), QgsSymbolLayerUtils::encodeColor( mSvgOutlineColor ) ); + map.insert( QStringLiteral( "outline_width" ), QString::number( mSvgOutlineWidth ) ); //units - map.insert( "pattern_width_unit", QgsUnitTypes::encodeUnit( mPatternWidthUnit ) ); - map.insert( "pattern_width_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mPatternWidthMapUnitScale ) ); - map.insert( "svg_outline_width_unit", QgsUnitTypes::encodeUnit( mSvgOutlineWidthUnit ) ); - map.insert( "svg_outline_width_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mSvgOutlineWidthMapUnitScale ) ); - map.insert( "outline_width_unit", QgsUnitTypes::encodeUnit( mOutlineWidthUnit ) ); - map.insert( "outline_width_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ) ); + map.insert( QStringLiteral( "pattern_width_unit" ), QgsUnitTypes::encodeUnit( mPatternWidthUnit ) ); + map.insert( QStringLiteral( "pattern_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mPatternWidthMapUnitScale ) ); + map.insert( QStringLiteral( "svg_outline_width_unit" ), QgsUnitTypes::encodeUnit( mSvgOutlineWidthUnit ) ); + map.insert( QStringLiteral( "svg_outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mSvgOutlineWidthMapUnitScale ) ); + map.insert( QStringLiteral( "outline_width_unit" ), QgsUnitTypes::encodeUnit( mOutlineWidthUnit ) ); + map.insert( QStringLiteral( "outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ) ); saveDataDefinedProperties( map ); return map; @@ -2065,32 +2065,32 @@ QgsSVGFillSymbolLayer* QgsSVGFillSymbolLayer::clone() const void QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { - QDomElement symbolizerElem = doc.createElement( "se:PolygonSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); - QDomElement fillElem = doc.createElement( "se:Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) ); symbolizerElem.appendChild( fillElem ); - QDomElement graphicFillElem = doc.createElement( "se:GraphicFill" ); + QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) ); fillElem.appendChild( graphicFillElem ); - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); graphicFillElem.appendChild( graphicElem ); if ( !mSvgFilePath.isEmpty() ) { double partternWidth = QgsSymbolLayerUtils::rescaleUom( mPatternWidth, mPatternWidthUnit, props ); - QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, mSvgFilePath, "image/svg+xml", mColor, partternWidth ); + QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, mSvgFilePath, QStringLiteral( "image/svg+xml" ), mColor, partternWidth ); } else { // TODO: create svg from data // <se:InlineContent> - symbolizerElem.appendChild( doc.createComment( "SVG from data not implemented yet" ) ); + symbolizerElem.appendChild( doc.createComment( QStringLiteral( "SVG from data not implemented yet" ) ) ); } if ( mSvgOutlineColor.isValid() || mSvgOutlineWidth >= 0 ) @@ -2102,10 +2102,10 @@ void QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, cons // <Rotation> QString angleFunc; bool ok; - double angle = props.value( "angle", "0" ).toDouble( &ok ); + double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok ); if ( !ok ) { - angleFunc = QString( "%1 + %2" ).arg( props.value( "angle", "0" ) ).arg( mAngle ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ) ).arg( mAngle ); } else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) ) { @@ -2131,22 +2131,22 @@ QgsSymbolLayer* QgsSVGFillSymbolLayer::createFromSld( QDomElement &element ) Qt::PenStyle penStyle; double size, borderWidth; - QDomElement fillElem = element.firstChildElement( "Fill" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); if ( fillElem.isNull() ) return nullptr; - QDomElement graphicFillElem = fillElem.firstChildElement( "GraphicFill" ); + QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) ); if ( graphicFillElem.isNull() ) return nullptr; - QDomElement graphicElem = graphicFillElem.firstChildElement( "Graphic" ); + QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return nullptr; if ( !QgsSymbolLayerUtils::externalGraphicFromSld( graphicElem, path, mimeType, fillColor, size ) ) return nullptr; - if ( mimeType != "image/svg+xml" ) + if ( mimeType != QLatin1String( "image/svg+xml" ) ) return nullptr; QgsSymbolLayerUtils::lineFromSld( graphicElem, penStyle, borderColor, borderWidth ); @@ -2167,7 +2167,7 @@ QgsSymbolLayer* QgsSVGFillSymbolLayer::createFromSld( QDomElement &element ) sl->setSvgOutlineWidth( borderWidth ); // try to get the outline - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( !strokeElem.isNull() ) { QgsSymbolLayer *l = QgsSymbolLayerUtils::createLineLayerFromSld( strokeElem ); @@ -2426,94 +2426,94 @@ QgsSymbolLayer* QgsLinePatternFillSymbolLayer::create( const QgsStringMap& prope QColor color( Qt::black ); double offset = 0.0; - if ( properties.contains( "lineangle" ) ) + if ( properties.contains( QStringLiteral( "lineangle" ) ) ) { //pre 2.5 projects used "lineangle" - lineAngle = properties["lineangle"].toDouble(); + lineAngle = properties[QStringLiteral( "lineangle" )].toDouble(); } - else if ( properties.contains( "angle" ) ) + else if ( properties.contains( QStringLiteral( "angle" ) ) ) { - lineAngle = properties["angle"].toDouble(); + lineAngle = properties[QStringLiteral( "angle" )].toDouble(); } patternLayer->setLineAngle( lineAngle ); - if ( properties.contains( "distance" ) ) + if ( properties.contains( QStringLiteral( "distance" ) ) ) { - distance = properties["distance"].toDouble(); + distance = properties[QStringLiteral( "distance" )].toDouble(); } patternLayer->setDistance( distance ); - if ( properties.contains( "linewidth" ) ) + if ( properties.contains( QStringLiteral( "linewidth" ) ) ) { //pre 2.5 projects used "linewidth" - lineWidth = properties["linewidth"].toDouble(); + lineWidth = properties[QStringLiteral( "linewidth" )].toDouble(); } - else if ( properties.contains( "outline_width" ) ) + else if ( properties.contains( QStringLiteral( "outline_width" ) ) ) { - lineWidth = properties["outline_width"].toDouble(); + lineWidth = properties[QStringLiteral( "outline_width" )].toDouble(); } - else if ( properties.contains( "line_width" ) ) + else if ( properties.contains( QStringLiteral( "line_width" ) ) ) { - lineWidth = properties["line_width"].toDouble(); + lineWidth = properties[QStringLiteral( "line_width" )].toDouble(); } patternLayer->setLineWidth( lineWidth ); - if ( properties.contains( "color" ) ) + if ( properties.contains( QStringLiteral( "color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( properties["color"] ); + color = QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "color" )] ); } - else if ( properties.contains( "outline_color" ) ) + else if ( properties.contains( QStringLiteral( "outline_color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( properties["outline_color"] ); + color = QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "outline_color" )] ); } - else if ( properties.contains( "line_color" ) ) + else if ( properties.contains( QStringLiteral( "line_color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( properties["line_color"] ); + color = QgsSymbolLayerUtils::decodeColor( properties[QStringLiteral( "line_color" )] ); } patternLayer->setColor( color ); - if ( properties.contains( "offset" ) ) + if ( properties.contains( QStringLiteral( "offset" ) ) ) { - offset = properties["offset"].toDouble(); + offset = properties[QStringLiteral( "offset" )].toDouble(); } patternLayer->setOffset( offset ); - if ( properties.contains( "distance_unit" ) ) + if ( properties.contains( QStringLiteral( "distance_unit" ) ) ) { - patternLayer->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( properties["distance_unit"] ) ); + patternLayer->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_unit" )] ) ); } - if ( properties.contains( "distance_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "distance_map_unit_scale" ) ) ) { - patternLayer->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["distance_map_unit_scale"] ) ); + patternLayer->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_map_unit_scale" )] ) ); } - if ( properties.contains( "line_width_unit" ) ) + if ( properties.contains( QStringLiteral( "line_width_unit" ) ) ) { - patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["line_width_unit"] ) ); + patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "line_width_unit" )] ) ); } - else if ( properties.contains( "outline_width_unit" ) ) + else if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) ) { - patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["outline_width_unit"] ) ); + patternLayer->setLineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )] ) ); } - if ( properties.contains( "line_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "line_width_map_unit_scale" ) ) ) { - patternLayer->setLineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["line_width_map_unit_scale"] ) ); + patternLayer->setLineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "line_width_map_unit_scale" )] ) ); } - if ( properties.contains( "offset_unit" ) ) + if ( properties.contains( QStringLiteral( "offset_unit" ) ) ) { - patternLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties["offset_unit"] ) ); + patternLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_unit" )] ) ); } - if ( properties.contains( "offset_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) { - patternLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["offset_map_unit_scale"] ) ); + patternLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_map_unit_scale" )] ) ); } - if ( properties.contains( "outline_width_unit" ) ) + if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) ) { - patternLayer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["outline_width_unit"] ) ); + patternLayer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )] ) ); } - if ( properties.contains( "outline_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) { - patternLayer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["outline_width_map_unit_scale"] ) ); + patternLayer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )] ) ); } patternLayer->restoreDataDefinedProperties( properties ); @@ -2523,7 +2523,7 @@ QgsSymbolLayer* QgsLinePatternFillSymbolLayer::create( const QgsStringMap& prope QString QgsLinePatternFillSymbolLayer::layerType() const { - return "LinePatternFill"; + return QStringLiteral( "LinePatternFill" ); } void QgsLinePatternFillSymbolLayer::applyPattern( const QgsSymbolRenderContext& context, QBrush& brush, double lineAngle, double distance, @@ -2833,19 +2833,19 @@ void QgsLinePatternFillSymbolLayer::stopRender( QgsSymbolRenderContext & ) QgsStringMap QgsLinePatternFillSymbolLayer::properties() const { QgsStringMap map; - map.insert( "angle", QString::number( mLineAngle ) ); - map.insert( "distance", QString::number( mDistance ) ); - map.insert( "line_width", QString::number( mLineWidth ) ); - map.insert( "color", QgsSymbolLayerUtils::encodeColor( mColor ) ); - map.insert( "offset", QString::number( mOffset ) ); - map.insert( "distance_unit", QgsUnitTypes::encodeUnit( mDistanceUnit ) ); - map.insert( "line_width_unit", QgsUnitTypes::encodeUnit( mLineWidthUnit ) ); - map.insert( "offset_unit", QgsUnitTypes::encodeUnit( mOffsetUnit ) ); - map.insert( "distance_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ) ); - map.insert( "line_width_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mLineWidthMapUnitScale ) ); - map.insert( "offset_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ) ); - map.insert( "outline_width_unit", QgsUnitTypes::encodeUnit( mOutlineWidthUnit ) ); - map.insert( "outline_width_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ) ); + map.insert( QStringLiteral( "angle" ), QString::number( mLineAngle ) ); + map.insert( QStringLiteral( "distance" ), QString::number( mDistance ) ); + map.insert( QStringLiteral( "line_width" ), QString::number( mLineWidth ) ); + map.insert( QStringLiteral( "color" ), QgsSymbolLayerUtils::encodeColor( mColor ) ); + map.insert( QStringLiteral( "offset" ), QString::number( mOffset ) ); + map.insert( QStringLiteral( "distance_unit" ), QgsUnitTypes::encodeUnit( mDistanceUnit ) ); + map.insert( QStringLiteral( "line_width_unit" ), QgsUnitTypes::encodeUnit( mLineWidthUnit ) ); + map.insert( QStringLiteral( "offset_unit" ), QgsUnitTypes::encodeUnit( mOffsetUnit ) ); + map.insert( QStringLiteral( "distance_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ) ); + map.insert( QStringLiteral( "line_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mLineWidthMapUnitScale ) ); + map.insert( QStringLiteral( "offset_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ) ); + map.insert( QStringLiteral( "outline_width_unit" ), QgsUnitTypes::encodeUnit( mOutlineWidthUnit ) ); + map.insert( QStringLiteral( "outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ) ); saveDataDefinedProperties( map ); return map; } @@ -2863,21 +2863,21 @@ QgsLinePatternFillSymbolLayer* QgsLinePatternFillSymbolLayer::clone() const void QgsLinePatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { - QDomElement symbolizerElem = doc.createElement( "se:PolygonSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); - QDomElement fillElem = doc.createElement( "se:Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) ); symbolizerElem.appendChild( fillElem ); - QDomElement graphicFillElem = doc.createElement( "se:GraphicFill" ); + QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) ); fillElem.appendChild( graphicFillElem ); - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); graphicFillElem.appendChild( graphicElem ); //line properties must be inside the graphic definition @@ -2885,15 +2885,15 @@ void QgsLinePatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &eleme double lineWidth = mFillLineSymbol ? mFillLineSymbol->width() : 0.0; lineWidth = QgsSymbolLayerUtils::rescaleUom( lineWidth, mLineWidthUnit, props ); double distance = QgsSymbolLayerUtils::rescaleUom( mDistance, mDistanceUnit, props ); - QgsSymbolLayerUtils::wellKnownMarkerToSld( doc, graphicElem, "horline", QColor(), lineColor, Qt::SolidLine, lineWidth, distance ); + QgsSymbolLayerUtils::wellKnownMarkerToSld( doc, graphicElem, QStringLiteral( "horline" ), QColor(), lineColor, Qt::SolidLine, lineWidth, distance ); // <Rotation> QString angleFunc; bool ok; - double angle = props.value( "angle", "0" ).toDouble( &ok ); + double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok ); if ( !ok ) { - angleFunc = QString( "%1 + %2" ).arg( props.value( "angle", "0" ) ).arg( mLineAngle ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ) ).arg( mLineAngle ); } else if ( !qgsDoubleNear( angle + mLineAngle, 0.0 ) ) { @@ -2911,13 +2911,13 @@ QString QgsLinePatternFillSymbolLayer::ogrFeatureStyleWidth( double widthScaleFa { QString featureStyle; featureStyle.append( "Brush(" ); - featureStyle.append( QString( "fc:%1" ).arg( mColor.name() ) ); - featureStyle.append( QString( ",bc:%1" ).arg( "#00000000" ) ); //transparent background + featureStyle.append( QStringLiteral( "fc:%1" ).arg( mColor.name() ) ); + featureStyle.append( QStringLiteral( ",bc:%1" ).arg( QStringLiteral( "#00000000" ) ) ); //transparent background featureStyle.append( ",id:\"ogr-brush-2\"" ); - featureStyle.append( QString( ",a:%1" ).arg( mLineAngle ) ); - featureStyle.append( QString( ",s:%1" ).arg( mLineWidth * widthScaleFactor ) ); + featureStyle.append( QStringLiteral( ",a:%1" ).arg( mLineAngle ) ); + featureStyle.append( QStringLiteral( ",s:%1" ).arg( mLineWidth * widthScaleFactor ) ); featureStyle.append( ",dx:0mm" ); - featureStyle.append( QString( ",dy:%1mm" ).arg( mDistance * widthScaleFactor ) ); + featureStyle.append( QStringLiteral( ",dy:%1mm" ).arg( mDistance * widthScaleFactor ) ); featureStyle.append( ')' ); return featureStyle; } @@ -2970,22 +2970,22 @@ QgsSymbolLayer* QgsLinePatternFillSymbolLayer::createFromSld( QDomElement &eleme double size, lineWidth; Qt::PenStyle lineStyle; - QDomElement fillElem = element.firstChildElement( "Fill" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); if ( fillElem.isNull() ) return nullptr; - QDomElement graphicFillElem = fillElem.firstChildElement( "GraphicFill" ); + QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) ); if ( graphicFillElem.isNull() ) return nullptr; - QDomElement graphicElem = graphicFillElem.firstChildElement( "Graphic" ); + QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return nullptr; if ( !QgsSymbolLayerUtils::wellKnownMarkerFromSld( graphicElem, name, fillColor, lineColor, lineStyle, lineWidth, size ) ) return nullptr; - if ( name != "horline" ) + if ( name != QLatin1String( "horline" ) ) return nullptr; double angle = 0.0; @@ -3013,7 +3013,7 @@ QgsSymbolLayer* QgsLinePatternFillSymbolLayer::createFromSld( QDomElement &eleme sl->setDistance( size ); // try to get the outline - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( !strokeElem.isNull() ) { QgsSymbolLayer *l = QgsSymbolLayerUtils::createLineLayerFromSld( strokeElem ); @@ -3104,62 +3104,62 @@ QgsMapUnitScale QgsPointPatternFillSymbolLayer::mapUnitScale() const QgsSymbolLayer* QgsPointPatternFillSymbolLayer::create( const QgsStringMap& properties ) { QgsPointPatternFillSymbolLayer* layer = new QgsPointPatternFillSymbolLayer(); - if ( properties.contains( "distance_x" ) ) + if ( properties.contains( QStringLiteral( "distance_x" ) ) ) { - layer->setDistanceX( properties["distance_x"].toDouble() ); + layer->setDistanceX( properties[QStringLiteral( "distance_x" )].toDouble() ); } - if ( properties.contains( "distance_y" ) ) + if ( properties.contains( QStringLiteral( "distance_y" ) ) ) { - layer->setDistanceY( properties["distance_y"].toDouble() ); + layer->setDistanceY( properties[QStringLiteral( "distance_y" )].toDouble() ); } - if ( properties.contains( "displacement_x" ) ) + if ( properties.contains( QStringLiteral( "displacement_x" ) ) ) { - layer->setDisplacementX( properties["displacement_x"].toDouble() ); + layer->setDisplacementX( properties[QStringLiteral( "displacement_x" )].toDouble() ); } - if ( properties.contains( "displacement_y" ) ) + if ( properties.contains( QStringLiteral( "displacement_y" ) ) ) { - layer->setDisplacementY( properties["displacement_y"].toDouble() ); + layer->setDisplacementY( properties[QStringLiteral( "displacement_y" )].toDouble() ); } - if ( properties.contains( "distance_x_unit" ) ) + if ( properties.contains( QStringLiteral( "distance_x_unit" ) ) ) { - layer->setDistanceXUnit( QgsUnitTypes::decodeRenderUnit( properties["distance_x_unit"] ) ); + layer->setDistanceXUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_x_unit" )] ) ); } - if ( properties.contains( "distance_x_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "distance_x_map_unit_scale" ) ) ) { - layer->setDistanceXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["distance_x_map_unit_scale"] ) ); + layer->setDistanceXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_x_map_unit_scale" )] ) ); } - if ( properties.contains( "distance_y_unit" ) ) + if ( properties.contains( QStringLiteral( "distance_y_unit" ) ) ) { - layer->setDistanceYUnit( QgsUnitTypes::decodeRenderUnit( properties["distance_y_unit"] ) ); + layer->setDistanceYUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_y_unit" )] ) ); } - if ( properties.contains( "distance_y_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "distance_y_map_unit_scale" ) ) ) { - layer->setDistanceYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["distance_y_map_unit_scale"] ) ); + layer->setDistanceYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_y_map_unit_scale" )] ) ); } - if ( properties.contains( "displacement_x_unit" ) ) + if ( properties.contains( QStringLiteral( "displacement_x_unit" ) ) ) { - layer->setDisplacementXUnit( QgsUnitTypes::decodeRenderUnit( properties["displacement_x_unit"] ) ); + layer->setDisplacementXUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "displacement_x_unit" )] ) ); } - if ( properties.contains( "displacement_x_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "displacement_x_map_unit_scale" ) ) ) { - layer->setDisplacementXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["displacement_x_map_unit_scale"] ) ); + layer->setDisplacementXMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "displacement_x_map_unit_scale" )] ) ); } - if ( properties.contains( "displacement_y_unit" ) ) + if ( properties.contains( QStringLiteral( "displacement_y_unit" ) ) ) { - layer->setDisplacementYUnit( QgsUnitTypes::decodeRenderUnit( properties["displacement_y_unit"] ) ); + layer->setDisplacementYUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "displacement_y_unit" )] ) ); } - if ( properties.contains( "displacement_y_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "displacement_y_map_unit_scale" ) ) ) { - layer->setDisplacementYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["displacement_y_map_unit_scale"] ) ); + layer->setDisplacementYMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "displacement_y_map_unit_scale" )] ) ); } - if ( properties.contains( "outline_width_unit" ) ) + if ( properties.contains( QStringLiteral( "outline_width_unit" ) ) ) { - layer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["outline_width_unit"] ) ); + layer->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "outline_width_unit" )] ) ); } - if ( properties.contains( "outline_width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) { - layer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["outline_width_map_unit_scale"] ) ); + layer->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "outline_width_map_unit_scale" )] ) ); } layer->restoreDataDefinedProperties( properties ); @@ -3169,7 +3169,7 @@ QgsSymbolLayer* QgsPointPatternFillSymbolLayer::create( const QgsStringMap& prop QString QgsPointPatternFillSymbolLayer::layerType() const { - return "PointPatternFill"; + return QStringLiteral( "PointPatternFill" ); } void QgsPointPatternFillSymbolLayer::applyPattern( const QgsSymbolRenderContext& context, QBrush& brush, double distanceX, double distanceY, @@ -3261,20 +3261,20 @@ void QgsPointPatternFillSymbolLayer::stopRender( QgsSymbolRenderContext& context QgsStringMap QgsPointPatternFillSymbolLayer::properties() const { QgsStringMap map; - map.insert( "distance_x", QString::number( mDistanceX ) ); - map.insert( "distance_y", QString::number( mDistanceY ) ); - map.insert( "displacement_x", QString::number( mDisplacementX ) ); - map.insert( "displacement_y", QString::number( mDisplacementY ) ); - map.insert( "distance_x_unit", QgsUnitTypes::encodeUnit( mDistanceXUnit ) ); - map.insert( "distance_y_unit", QgsUnitTypes::encodeUnit( mDistanceYUnit ) ); - map.insert( "displacement_x_unit", QgsUnitTypes::encodeUnit( mDisplacementXUnit ) ); - map.insert( "displacement_y_unit", QgsUnitTypes::encodeUnit( mDisplacementYUnit ) ); - map.insert( "distance_x_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceXMapUnitScale ) ); - map.insert( "distance_y_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceYMapUnitScale ) ); - map.insert( "displacement_x_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementXMapUnitScale ) ); - map.insert( "displacement_y_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementYMapUnitScale ) ); - map.insert( "outline_width_unit", QgsUnitTypes::encodeUnit( mOutlineWidthUnit ) ); - map.insert( "outline_width_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ) ); + map.insert( QStringLiteral( "distance_x" ), QString::number( mDistanceX ) ); + map.insert( QStringLiteral( "distance_y" ), QString::number( mDistanceY ) ); + map.insert( QStringLiteral( "displacement_x" ), QString::number( mDisplacementX ) ); + map.insert( QStringLiteral( "displacement_y" ), QString::number( mDisplacementY ) ); + map.insert( QStringLiteral( "distance_x_unit" ), QgsUnitTypes::encodeUnit( mDistanceXUnit ) ); + map.insert( QStringLiteral( "distance_y_unit" ), QgsUnitTypes::encodeUnit( mDistanceYUnit ) ); + map.insert( QStringLiteral( "displacement_x_unit" ), QgsUnitTypes::encodeUnit( mDisplacementXUnit ) ); + map.insert( QStringLiteral( "displacement_y_unit" ), QgsUnitTypes::encodeUnit( mDisplacementYUnit ) ); + map.insert( QStringLiteral( "distance_x_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceXMapUnitScale ) ); + map.insert( QStringLiteral( "distance_y_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceYMapUnitScale ) ); + map.insert( QStringLiteral( "displacement_x_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementXMapUnitScale ) ); + map.insert( QStringLiteral( "displacement_y_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mDisplacementYMapUnitScale ) ); + map.insert( QStringLiteral( "outline_width_unit" ), QgsUnitTypes::encodeUnit( mOutlineWidthUnit ) ); + map.insert( QStringLiteral( "outline_width_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ) ); saveDataDefinedProperties( map ); return map; } @@ -3294,32 +3294,32 @@ void QgsPointPatternFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &elem { for ( int i = 0; i < mMarkerSymbol->symbolLayerCount(); i++ ) { - QDomElement symbolizerElem = doc.createElement( "se:PolygonSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PolygonSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); - QDomElement fillElem = doc.createElement( "se:Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) ); symbolizerElem.appendChild( fillElem ); - QDomElement graphicFillElem = doc.createElement( "se:GraphicFill" ); + QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) ); fillElem.appendChild( graphicFillElem ); // store distanceX, distanceY, displacementX, displacementY in a <VendorOption> double dx = QgsSymbolLayerUtils::rescaleUom( mDistanceX, mDistanceXUnit, props ); double dy = QgsSymbolLayerUtils::rescaleUom( mDistanceY, mDistanceYUnit, props ); QString dist = QgsSymbolLayerUtils::encodePoint( QPointF( dx, dy ) ); - QDomElement distanceElem = QgsSymbolLayerUtils::createVendorOptionElement( doc, "distance", dist ); + QDomElement distanceElem = QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "distance" ), dist ); symbolizerElem.appendChild( distanceElem ); QgsSymbolLayer *layer = mMarkerSymbol->symbolLayer( i ); QgsMarkerSymbolLayer *markerLayer = static_cast<QgsMarkerSymbolLayer *>( layer ); if ( !markerLayer ) { - QString errorMsg = QString( "MarkerSymbolLayerV2 expected, %1 found. Skip it." ).arg( layer->layerType() ); + QString errorMsg = QStringLiteral( "MarkerSymbolLayerV2 expected, %1 found. Skip it." ).arg( layer->layerType() ); graphicFillElem.appendChild( doc.createComment( errorMsg ) ); } else @@ -3436,10 +3436,10 @@ QgsSymbolLayer* QgsCentroidFillSymbolLayer::create( const QgsStringMap& properti { QgsCentroidFillSymbolLayer* sl = new QgsCentroidFillSymbolLayer(); - if ( properties.contains( "point_on_surface" ) ) - sl->setPointOnSurface( properties["point_on_surface"].toInt() != 0 ); - if ( properties.contains( "point_on_all_parts" ) ) - sl->setPointOnAllParts( properties["point_on_all_parts"].toInt() != 0 ); + if ( properties.contains( QStringLiteral( "point_on_surface" ) ) ) + sl->setPointOnSurface( properties[QStringLiteral( "point_on_surface" )].toInt() != 0 ); + if ( properties.contains( QStringLiteral( "point_on_all_parts" ) ) ) + sl->setPointOnAllParts( properties[QStringLiteral( "point_on_all_parts" )].toInt() != 0 ); sl->restoreDataDefinedProperties( properties ); @@ -3448,7 +3448,7 @@ QgsSymbolLayer* QgsCentroidFillSymbolLayer::create( const QgsStringMap& properti QString QgsCentroidFillSymbolLayer::layerType() const { - return "CentroidFill"; + return QStringLiteral( "CentroidFill" ); } void QgsCentroidFillSymbolLayer::setColor( const QColor& color ) @@ -3523,8 +3523,8 @@ void QgsCentroidFillSymbolLayer::renderPolygon( const QPolygonF& points, QList<Q QgsStringMap QgsCentroidFillSymbolLayer::properties() const { QgsStringMap map; - map["point_on_surface"] = QString::number( mPointOnSurface ); - map["point_on_all_parts"] = QString::number( mPointOnAllParts ); + map[QStringLiteral( "point_on_surface" )] = QString::number( mPointOnSurface ); + map[QStringLiteral( "point_on_all_parts" )] = QString::number( mPointOnAllParts ); saveDataDefinedProperties( map ); return map; } @@ -3660,29 +3660,29 @@ QgsSymbolLayer *QgsRasterFillSymbolLayer::create( const QgsStringMap &properties double width = 0.0; QString imagePath; - if ( properties.contains( "imageFile" ) ) + if ( properties.contains( QStringLiteral( "imageFile" ) ) ) { - imagePath = properties["imageFile"]; + imagePath = properties[QStringLiteral( "imageFile" )]; } - if ( properties.contains( "coordinate_mode" ) ) + if ( properties.contains( QStringLiteral( "coordinate_mode" ) ) ) { - mode = static_cast< FillCoordinateMode >( properties["coordinate_mode"].toInt() ); + mode = static_cast< FillCoordinateMode >( properties[QStringLiteral( "coordinate_mode" )].toInt() ); } - if ( properties.contains( "alpha" ) ) + if ( properties.contains( QStringLiteral( "alpha" ) ) ) { - alpha = properties["alpha"].toDouble(); + alpha = properties[QStringLiteral( "alpha" )].toDouble(); } - if ( properties.contains( "offset" ) ) + if ( properties.contains( QStringLiteral( "offset" ) ) ) { - offset = QgsSymbolLayerUtils::decodePoint( properties["offset"] ); + offset = QgsSymbolLayerUtils::decodePoint( properties[QStringLiteral( "offset" )] ); } - if ( properties.contains( "angle" ) ) + if ( properties.contains( QStringLiteral( "angle" ) ) ) { - angle = properties["angle"].toDouble(); + angle = properties[QStringLiteral( "angle" )].toDouble(); } - if ( properties.contains( "width" ) ) + if ( properties.contains( QStringLiteral( "width" ) ) ) { - width = properties["width"].toDouble(); + width = properties[QStringLiteral( "width" )].toDouble(); } QgsRasterFillSymbolLayer* symbolLayer = new QgsRasterFillSymbolLayer( imagePath ); symbolLayer->setCoordinateMode( mode ); @@ -3690,21 +3690,21 @@ QgsSymbolLayer *QgsRasterFillSymbolLayer::create( const QgsStringMap &properties symbolLayer->setOffset( offset ); symbolLayer->setAngle( angle ); symbolLayer->setWidth( width ); - if ( properties.contains( "offset_unit" ) ) + if ( properties.contains( QStringLiteral( "offset_unit" ) ) ) { - symbolLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties["offset_unit"] ) ); + symbolLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_unit" )] ) ); } - if ( properties.contains( "offset_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) { - symbolLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["offset_map_unit_scale"] ) ); + symbolLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_map_unit_scale" )] ) ); } - if ( properties.contains( "width_unit" ) ) + if ( properties.contains( QStringLiteral( "width_unit" ) ) ) { - symbolLayer->setWidthUnit( QgsUnitTypes::decodeRenderUnit( properties["width_unit"] ) ); + symbolLayer->setWidthUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "width_unit" )] ) ); } - if ( properties.contains( "width_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "width_map_unit_scale" ) ) ) { - symbolLayer->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["width_map_unit_scale"] ) ); + symbolLayer->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "width_map_unit_scale" )] ) ); } symbolLayer->restoreDataDefinedProperties( properties ); @@ -3720,7 +3720,7 @@ bool QgsRasterFillSymbolLayer::setSubSymbol( QgsSymbol *symbol ) QString QgsRasterFillSymbolLayer::layerType() const { - return "RasterFill"; + return QStringLiteral( "RasterFill" ); } void QgsRasterFillSymbolLayer::renderPolygon( const QPolygonF &points, QList<QPolygonF> *rings, QgsSymbolRenderContext &context ) @@ -3765,16 +3765,16 @@ void QgsRasterFillSymbolLayer::stopRender( QgsSymbolRenderContext &context ) QgsStringMap QgsRasterFillSymbolLayer::properties() const { QgsStringMap map; - map["imageFile"] = mImageFilePath; - map["coordinate_mode"] = QString::number( mCoordinateMode ); - map["alpha"] = QString::number( mAlpha ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["angle"] = QString::number( mAngle ); - map["width"] = QString::number( mWidth ); - map["width_unit"] = QgsUnitTypes::encodeUnit( mWidthUnit ); - map["width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale ); + map[QStringLiteral( "imageFile" )] = mImageFilePath; + map[QStringLiteral( "coordinate_mode" )] = QString::number( mCoordinateMode ); + map[QStringLiteral( "alpha" )] = QString::number( mAlpha ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "angle" )] = QString::number( mAngle ); + map[QStringLiteral( "width" )] = QString::number( mWidth ); + map[QStringLiteral( "width_unit" )] = QgsUnitTypes::encodeUnit( mWidthUnit ); + map[QStringLiteral( "width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale ); saveDataDefinedProperties( map ); return map; diff --git a/src/core/symbology-ng/qgsfillsymbollayer.h b/src/core/symbology-ng/qgsfillsymbollayer.h index 837a32af3486..640c3a20bd23 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.h +++ b/src/core/symbology-ng/qgsfillsymbollayer.h @@ -817,7 +817,11 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer class CORE_EXPORT QgsSVGFillSymbolLayer: public QgsImageFillSymbolLayer { public: - QgsSVGFillSymbolLayer( const QString& svgFilePath = "", double width = 20, double rotation = 0.0 ); + + /** + * Constructor for QgsSVGFillSymbolLayer which accepts the path to an SVG file. + */ + QgsSVGFillSymbolLayer( const QString& svgFilePath = QLatin1String( "" ), double width = 20, double rotation = 0.0 ); QgsSVGFillSymbolLayer( const QByteArray& svgData, double width = 20, double rotation = 0.0 ); ~QgsSVGFillSymbolLayer(); diff --git a/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp b/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp index c58be9ee0149..deb14624252b 100644 --- a/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp +++ b/src/core/symbology-ng/qgsgeometrygeneratorsymbollayer.cpp @@ -25,18 +25,18 @@ QgsGeometryGeneratorSymbolLayer::~QgsGeometryGeneratorSymbolLayer() QgsSymbolLayer* QgsGeometryGeneratorSymbolLayer::create( const QgsStringMap& properties ) { - QString expression = properties.value( "geometryModifier" ); + QString expression = properties.value( QStringLiteral( "geometryModifier" ) ); if ( expression.isEmpty() ) { - expression = "$geometry"; + expression = QStringLiteral( "$geometry" ); } QgsGeometryGeneratorSymbolLayer* symbolLayer = new QgsGeometryGeneratorSymbolLayer( expression ); - if ( properties.value( "SymbolType" ) == "Marker" ) + if ( properties.value( QStringLiteral( "SymbolType" ) ) == QLatin1String( "Marker" ) ) { symbolLayer->setSubSymbol( QgsMarkerSymbol::createSimple( properties ) ); } - else if ( properties.value( "SymbolType" ) == "Line" ) + else if ( properties.value( QStringLiteral( "SymbolType" ) ) == QLatin1String( "Line" ) ) { symbolLayer->setSubSymbol( QgsLineSymbol::createSimple( properties ) ); } @@ -63,7 +63,7 @@ QgsGeometryGeneratorSymbolLayer::QgsGeometryGeneratorSymbolLayer( const QString& QString QgsGeometryGeneratorSymbolLayer::layerType() const { - return "GeometryGenerator"; + return QStringLiteral( "GeometryGenerator" ); } void QgsGeometryGeneratorSymbolLayer::setSymbolType( QgsSymbol::SymbolType symbolType ) @@ -127,17 +127,17 @@ QgsSymbolLayer* QgsGeometryGeneratorSymbolLayer::clone() const QgsStringMap QgsGeometryGeneratorSymbolLayer::properties() const { QgsStringMap props; - props.insert( "geometryModifier" , mExpression->expression() ); + props.insert( QStringLiteral( "geometryModifier" ) , mExpression->expression() ); switch ( mSymbolType ) { case QgsSymbol::Marker: - props.insert( "SymbolType", "Marker" ); + props.insert( QStringLiteral( "SymbolType" ), QStringLiteral( "Marker" ) ); break; case QgsSymbol::Line: - props.insert( "SymbolType", "Line" ); + props.insert( QStringLiteral( "SymbolType" ), QStringLiteral( "Line" ) ); break; default: - props.insert( "SymbolType", "Fill" ); + props.insert( QStringLiteral( "SymbolType" ), QStringLiteral( "Fill" ) ); break; } saveDataDefinedProperties( props ); diff --git a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp index 3d5d0236bf9a..33e9b023d22e 100644 --- a/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgsgraduatedsymbolrenderer.cpp @@ -139,33 +139,33 @@ void QgsRendererRange::setRenderState( bool render ) QString QgsRendererRange::dump() const { - return QString( "%1 - %2::%3::%4\n" ).arg( mLowerValue ).arg( mUpperValue ).arg( mLabel, mSymbol.data() ? mSymbol->dump() : "(no symbol)" ); + return QStringLiteral( "%1 - %2::%3::%4\n" ).arg( mLowerValue ).arg( mUpperValue ).arg( mLabel, mSymbol.data() ? mSymbol->dump() : QStringLiteral( "(no symbol)" ) ); } void QgsRendererRange::toSld( QDomDocument &doc, QDomElement &element, QgsStringMap props, bool firstRange ) const { - if ( !mSymbol.data() || props.value( "attribute", "" ).isEmpty() ) + if ( !mSymbol.data() || props.value( QStringLiteral( "attribute" ), QLatin1String( "" ) ).isEmpty() ) return; - QString attrName = props[ "attribute" ]; + QString attrName = props[ QStringLiteral( "attribute" )]; - QDomElement ruleElem = doc.createElement( "se:Rule" ); + QDomElement ruleElem = doc.createElement( QStringLiteral( "se:Rule" ) ); element.appendChild( ruleElem ); - QDomElement nameElem = doc.createElement( "se:Name" ); + QDomElement nameElem = doc.createElement( QStringLiteral( "se:Name" ) ); nameElem.appendChild( doc.createTextNode( mLabel ) ); ruleElem.appendChild( nameElem ); - QDomElement descrElem = doc.createElement( "se:Description" ); - QDomElement titleElem = doc.createElement( "se:Title" ); - QString descrStr = QString( "range: %1 - %2" ).arg( qgsDoubleToString( mLowerValue ), qgsDoubleToString( mUpperValue ) ); + QDomElement descrElem = doc.createElement( QStringLiteral( "se:Description" ) ); + QDomElement titleElem = doc.createElement( QStringLiteral( "se:Title" ) ); + QString descrStr = QStringLiteral( "range: %1 - %2" ).arg( qgsDoubleToString( mLowerValue ), qgsDoubleToString( mUpperValue ) ); titleElem.appendChild( doc.createTextNode( !mLabel.isEmpty() ? mLabel : descrStr ) ); descrElem.appendChild( titleElem ); ruleElem.appendChild( descrElem ); // create the ogc:Filter for the range - QString filterFunc = QString( "%1 %2 %3 AND %1 <= %4" ) - .arg( attrName.replace( '\"', "\"\"" ), + QString filterFunc = QStringLiteral( "%1 %2 %3 AND %1 <= %4" ) + .arg( attrName.replace( '\"', QLatin1String( "\"\"" ) ), firstRange ? ">=" : ">", qgsDoubleToString( mLowerValue ), qgsDoubleToString( mUpperValue ) ); @@ -180,11 +180,11 @@ int QgsRendererRangeLabelFormat::MaxPrecision = 15; int QgsRendererRangeLabelFormat::MinPrecision = -6; QgsRendererRangeLabelFormat::QgsRendererRangeLabelFormat() - : mFormat( " %1 - %2 " ) + : mFormat( QStringLiteral( " %1 - %2 " ) ) , mPrecision( 4 ) , mTrimTrailingZeroes( false ) , mNumberScale( 1.0 ) - , mNumberSuffix( "" ) + , mNumberSuffix( QLatin1String( "" ) ) , mReTrailingZeroes( "[.,]?0*$" ) , mReNegativeZero( "^\\-0(?:[.,]0*)?$" ) { @@ -219,7 +219,7 @@ void QgsRendererRangeLabelFormat::setPrecision( int precision ) precision = qBound( MinPrecision, precision, MaxPrecision ); mPrecision = precision; mNumberScale = 1.0; - mNumberSuffix = ""; + mNumberSuffix = QLatin1String( "" ); while ( precision < 0 ) { precision++; @@ -247,9 +247,9 @@ QString QgsRendererRangeLabelFormat::formatNumber( double value ) const else { QString valueStr = QString::number( value * mNumberScale, 'f', 0 ); - if ( valueStr == "-0" ) + if ( valueStr == QLatin1String( "-0" ) ) valueStr = '0'; - if ( valueStr != "0" ) + if ( valueStr != QLatin1String( "0" ) ) valueStr = valueStr + mNumberSuffix; return valueStr; } @@ -261,31 +261,31 @@ QString QgsRendererRangeLabelFormat::labelForRange( double lower, double upper ) QString upperStr = formatNumber( upper ); QString legend( mFormat ); - return legend.replace( "%1", lowerStr ).replace( "%2", upperStr ); + return legend.replace( QLatin1String( "%1" ), lowerStr ).replace( QLatin1String( "%2" ), upperStr ); } void QgsRendererRangeLabelFormat::setFromDomElement( QDomElement &element ) { - mFormat = element.attribute( "format", - element.attribute( "prefix", " " ) + "%1" + - element.attribute( "separator", " - " ) + "%2" + - element.attribute( "suffix", " " ) + mFormat = element.attribute( QStringLiteral( "format" ), + element.attribute( QStringLiteral( "prefix" ), QStringLiteral( " " ) ) + "%1" + + element.attribute( QStringLiteral( "separator" ), QStringLiteral( " - " ) ) + "%2" + + element.attribute( QStringLiteral( "suffix" ), QStringLiteral( " " ) ) ); - setPrecision( element.attribute( "decimalplaces", "4" ).toInt() ); - mTrimTrailingZeroes = element.attribute( "trimtrailingzeroes", "false" ) == "true"; + setPrecision( element.attribute( QStringLiteral( "decimalplaces" ), QStringLiteral( "4" ) ).toInt() ); + mTrimTrailingZeroes = element.attribute( QStringLiteral( "trimtrailingzeroes" ), QStringLiteral( "false" ) ) == QLatin1String( "true" ); } void QgsRendererRangeLabelFormat::saveToDomElement( QDomElement &element ) { - element.setAttribute( "format", mFormat ); - element.setAttribute( "decimalplaces", mPrecision ); - element.setAttribute( "trimtrailingzeroes", mTrimTrailingZeroes ? "true" : "false" ); + element.setAttribute( QStringLiteral( "format" ), mFormat ); + element.setAttribute( QStringLiteral( "decimalplaces" ), mPrecision ); + element.setAttribute( QStringLiteral( "trimtrailingzeroes" ), mTrimTrailingZeroes ? "true" : "false" ); } /////////// QgsGraduatedSymbolRenderer::QgsGraduatedSymbolRenderer( const QString& attrName, const QgsRangeList& ranges ) - : QgsFeatureRenderer( "graduatedSymbol" ) + : QgsFeatureRenderer( QStringLiteral( "graduatedSymbol" ) ) , mAttrName( attrName ) , mMode( Custom ) , mInvertedColorRamp( false ) @@ -486,7 +486,7 @@ bool QgsGraduatedSymbolRenderer::updateRangeRenderState( int rangeIndex, bool va QString QgsGraduatedSymbolRenderer::dump() const { - QString s = QString( "GRADUATED: attr %1\n" ).arg( mAttrName ); + QString s = QStringLiteral( "GRADUATED: attr %1\n" ).arg( mAttrName ); for ( int i = 0; i < mRanges.count(); i++ ) s += mRanges[i].dump(); return s; @@ -513,8 +513,8 @@ QgsGraduatedSymbolRenderer* QgsGraduatedSymbolRenderer::clone() const void QgsGraduatedSymbolRenderer::toSld( QDomDocument& doc, QDomElement &element, const QgsStringMap &props ) const { QgsStringMap newProps = props; - newProps[ "attribute" ] = mAttrName; - newProps[ "method" ] = graduatedMethodStr( mGraduatedMethod ); + newProps[ QStringLiteral( "attribute" )] = mAttrName; + newProps[ QStringLiteral( "method" )] = graduatedMethodStr( mGraduatedMethod ); // create a Rule for each range bool first = true; @@ -921,11 +921,11 @@ void QgsGraduatedSymbolRenderer::updateClasses( QgsVectorLayer* vlayer, Mode mod QgsFeatureRenderer* QgsGraduatedSymbolRenderer::create( QDomElement& element ) { - QDomElement symbolsElem = element.firstChildElement( "symbols" ); + QDomElement symbolsElem = element.firstChildElement( QStringLiteral( "symbols" ) ); if ( symbolsElem.isNull() ) return nullptr; - QDomElement rangesElem = element.firstChildElement( "ranges" ); + QDomElement rangesElem = element.firstChildElement( QStringLiteral( "ranges" ) ); if ( rangesElem.isNull() ) return nullptr; @@ -935,13 +935,13 @@ QgsFeatureRenderer* QgsGraduatedSymbolRenderer::create( QDomElement& element ) QDomElement rangeElem = rangesElem.firstChildElement(); while ( !rangeElem.isNull() ) { - if ( rangeElem.tagName() == "range" ) + if ( rangeElem.tagName() == QLatin1String( "range" ) ) { - double lowerValue = rangeElem.attribute( "lower" ).toDouble(); - double upperValue = rangeElem.attribute( "upper" ).toDouble(); - QString symbolName = rangeElem.attribute( "symbol" ); - QString label = rangeElem.attribute( "label" ); - bool render = rangeElem.attribute( "render", "true" ) != "false"; + double lowerValue = rangeElem.attribute( QStringLiteral( "lower" ) ).toDouble(); + double upperValue = rangeElem.attribute( QStringLiteral( "upper" ) ).toDouble(); + QString symbolName = rangeElem.attribute( QStringLiteral( "symbol" ) ); + QString label = rangeElem.attribute( QStringLiteral( "label" ) ); + bool render = rangeElem.attribute( QStringLiteral( "render" ), QStringLiteral( "true" ) ) != QLatin1String( "false" ); if ( symbolMap.contains( symbolName ) ) { QgsSymbol* symbol = symbolMap.take( symbolName ); @@ -951,11 +951,11 @@ QgsFeatureRenderer* QgsGraduatedSymbolRenderer::create( QDomElement& element ) rangeElem = rangeElem.nextSiblingElement(); } - QString attrName = element.attribute( "attr" ); + QString attrName = element.attribute( QStringLiteral( "attr" ) ); QgsGraduatedSymbolRenderer* r = new QgsGraduatedSymbolRenderer( attrName, ranges ); - QString attrMethod = element.attribute( "graduatedMethod" ); + QString attrMethod = element.attribute( QStringLiteral( "graduatedMethod" ) ); if ( !attrMethod.isEmpty() ) { if ( attrMethod == graduatedMethodStr( GraduatedColor ) ) @@ -969,75 +969,75 @@ QgsFeatureRenderer* QgsGraduatedSymbolRenderer::create( QDomElement& element ) QgsSymbolLayerUtils::clearSymbolMap( symbolMap ); // try to load source symbol (optional) - QDomElement sourceSymbolElem = element.firstChildElement( "source-symbol" ); + QDomElement sourceSymbolElem = element.firstChildElement( QStringLiteral( "source-symbol" ) ); if ( !sourceSymbolElem.isNull() ) { QgsSymbolMap sourceSymbolMap = QgsSymbolLayerUtils::loadSymbols( sourceSymbolElem ); - if ( sourceSymbolMap.contains( "0" ) ) + if ( sourceSymbolMap.contains( QStringLiteral( "0" ) ) ) { - r->setSourceSymbol( sourceSymbolMap.take( "0" ) ); + r->setSourceSymbol( sourceSymbolMap.take( QStringLiteral( "0" ) ) ); } QgsSymbolLayerUtils::clearSymbolMap( sourceSymbolMap ); } // try to load color ramp (optional) - QDomElement sourceColorRampElem = element.firstChildElement( "colorramp" ); - if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( "name" ) == "[source]" ) + QDomElement sourceColorRampElem = element.firstChildElement( QStringLiteral( "colorramp" ) ); + if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( QStringLiteral( "name" ) ) == QLatin1String( "[source]" ) ) { r->setSourceColorRamp( QgsSymbolLayerUtils::loadColorRamp( sourceColorRampElem ) ); - QDomElement invertedColorRampElem = element.firstChildElement( "invertedcolorramp" ); + QDomElement invertedColorRampElem = element.firstChildElement( QStringLiteral( "invertedcolorramp" ) ); if ( !invertedColorRampElem.isNull() ) - r->setInvertedColorRamp( invertedColorRampElem.attribute( "value" ) == "1" ); + r->setInvertedColorRamp( invertedColorRampElem.attribute( QStringLiteral( "value" ) ) == QLatin1String( "1" ) ); } // try to load mode - QDomElement modeElem = element.firstChildElement( "mode" ); + QDomElement modeElem = element.firstChildElement( QStringLiteral( "mode" ) ); if ( !modeElem.isNull() ) { - QString modeString = modeElem.attribute( "name" ); - if ( modeString == "equal" ) + QString modeString = modeElem.attribute( QStringLiteral( "name" ) ); + if ( modeString == QLatin1String( "equal" ) ) r->setMode( EqualInterval ); - else if ( modeString == "quantile" ) + else if ( modeString == QLatin1String( "quantile" ) ) r->setMode( Quantile ); - else if ( modeString == "jenks" ) + else if ( modeString == QLatin1String( "jenks" ) ) r->setMode( Jenks ); - else if ( modeString == "stddev" ) + else if ( modeString == QLatin1String( "stddev" ) ) r->setMode( StdDev ); - else if ( modeString == "pretty" ) + else if ( modeString == QLatin1String( "pretty" ) ) r->setMode( Pretty ); } - QDomElement rotationElem = element.firstChildElement( "rotation" ); - if ( !rotationElem.isNull() && !rotationElem.attribute( "field" ).isEmpty() ) + QDomElement rotationElem = element.firstChildElement( QStringLiteral( "rotation" ) ); + if ( !rotationElem.isNull() && !rotationElem.attribute( QStringLiteral( "field" ) ).isEmpty() ) { Q_FOREACH ( const QgsRendererRange& range, r->mRanges ) { - convertSymbolRotation( range.symbol(), rotationElem.attribute( "field" ) ); + convertSymbolRotation( range.symbol(), rotationElem.attribute( QStringLiteral( "field" ) ) ); } if ( r->mSourceSymbol.data() ) { - convertSymbolRotation( r->mSourceSymbol.data(), rotationElem.attribute( "field" ) ); + convertSymbolRotation( r->mSourceSymbol.data(), rotationElem.attribute( QStringLiteral( "field" ) ) ); } } - QDomElement sizeScaleElem = element.firstChildElement( "sizescale" ); - if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( "field" ).isEmpty() ) + QDomElement sizeScaleElem = element.firstChildElement( QStringLiteral( "sizescale" ) ); + if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( QStringLiteral( "field" ) ).isEmpty() ) { Q_FOREACH ( const QgsRendererRange& range, r->mRanges ) { convertSymbolSizeScale( range.symbol(), - QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ), - sizeScaleElem.attribute( "field" ) ); + QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( QStringLiteral( "scalemethod" ) ) ), + sizeScaleElem.attribute( QStringLiteral( "field" ) ) ); } if ( r->mSourceSymbol.data() && r->mSourceSymbol->type() == QgsSymbol::Marker ) { convertSymbolSizeScale( r->mSourceSymbol.data(), - QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ), - sizeScaleElem.attribute( "field" ) ); + QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( QStringLiteral( "scalemethod" ) ) ), + sizeScaleElem.attribute( QStringLiteral( "field" ) ) ); } } - QDomElement labelFormatElem = element.firstChildElement( "labelformat" ); + QDomElement labelFormatElem = element.firstChildElement( QStringLiteral( "labelformat" ) ); if ( ! labelFormatElem.isNull() ) { QgsRendererRangeLabelFormat labelFormat; @@ -1051,16 +1051,16 @@ QgsFeatureRenderer* QgsGraduatedSymbolRenderer::create( QDomElement& element ) QDomElement QgsGraduatedSymbolRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "graduatedSymbol" ); - rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); - rendererElem.setAttribute( "attr", mAttrName ); - rendererElem.setAttribute( "graduatedMethod", graduatedMethodStr( mGraduatedMethod ) ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "graduatedSymbol" ) ); + rendererElem.setAttribute( QStringLiteral( "symbollevels" ), ( mUsingSymbolLevels ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "attr" ), mAttrName ); + rendererElem.setAttribute( QStringLiteral( "graduatedMethod" ), graduatedMethodStr( mGraduatedMethod ) ); // ranges int i = 0; QgsSymbolMap symbols; - QDomElement rangesElem = doc.createElement( "ranges" ); + QDomElement rangesElem = doc.createElement( QStringLiteral( "ranges" ) ); QgsRangeList::const_iterator it = mRanges.constBegin(); for ( ; it != mRanges.constEnd(); ++it ) { @@ -1068,12 +1068,12 @@ QDomElement QgsGraduatedSymbolRenderer::save( QDomDocument& doc ) QString symbolName = QString::number( i ); symbols.insert( symbolName, range.symbol() ); - QDomElement rangeElem = doc.createElement( "range" ); - rangeElem.setAttribute( "lower", QString::number( range.lowerValue(), 'f', 15 ) ); - rangeElem.setAttribute( "upper", QString::number( range.upperValue(), 'f', 15 ) ); - rangeElem.setAttribute( "symbol", symbolName ); - rangeElem.setAttribute( "label", range.label() ); - rangeElem.setAttribute( "render", range.renderState() ? "true" : "false" ); + QDomElement rangeElem = doc.createElement( QStringLiteral( "range" ) ); + rangeElem.setAttribute( QStringLiteral( "lower" ), QString::number( range.lowerValue(), 'f', 15 ) ); + rangeElem.setAttribute( QStringLiteral( "upper" ), QString::number( range.upperValue(), 'f', 15 ) ); + rangeElem.setAttribute( QStringLiteral( "symbol" ), symbolName ); + rangeElem.setAttribute( QStringLiteral( "label" ), range.label() ); + rangeElem.setAttribute( QStringLiteral( "render" ), range.renderState() ? "true" : "false" ); rangesElem.appendChild( rangeElem ); i++; } @@ -1081,54 +1081,54 @@ QDomElement QgsGraduatedSymbolRenderer::save( QDomDocument& doc ) rendererElem.appendChild( rangesElem ); // save symbols - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, "symbols", doc ); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, QStringLiteral( "symbols" ), doc ); rendererElem.appendChild( symbolsElem ); // save source symbol if ( mSourceSymbol.data() ) { QgsSymbolMap sourceSymbols; - sourceSymbols.insert( "0", mSourceSymbol.data() ); - QDomElement sourceSymbolElem = QgsSymbolLayerUtils::saveSymbols( sourceSymbols, "source-symbol", doc ); + sourceSymbols.insert( QStringLiteral( "0" ), mSourceSymbol.data() ); + QDomElement sourceSymbolElem = QgsSymbolLayerUtils::saveSymbols( sourceSymbols, QStringLiteral( "source-symbol" ), doc ); rendererElem.appendChild( sourceSymbolElem ); } // save source color ramp if ( mSourceColorRamp.data() ) { - QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( "[source]", mSourceColorRamp.data(), doc ); + QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( QStringLiteral( "[source]" ), mSourceColorRamp.data(), doc ); rendererElem.appendChild( colorRampElem ); - QDomElement invertedElem = doc.createElement( "invertedcolorramp" ); - invertedElem.setAttribute( "value", mInvertedColorRamp ); + QDomElement invertedElem = doc.createElement( QStringLiteral( "invertedcolorramp" ) ); + invertedElem.setAttribute( QStringLiteral( "value" ), mInvertedColorRamp ); rendererElem.appendChild( invertedElem ); } // save mode QString modeString; if ( mMode == EqualInterval ) - modeString = "equal"; + modeString = QStringLiteral( "equal" ); else if ( mMode == Quantile ) - modeString = "quantile"; + modeString = QStringLiteral( "quantile" ); else if ( mMode == Jenks ) - modeString = "jenks"; + modeString = QStringLiteral( "jenks" ); else if ( mMode == StdDev ) - modeString = "stddev"; + modeString = QStringLiteral( "stddev" ); else if ( mMode == Pretty ) - modeString = "pretty"; + modeString = QStringLiteral( "pretty" ); if ( !modeString.isEmpty() ) { - QDomElement modeElem = doc.createElement( "mode" ); - modeElem.setAttribute( "name", modeString ); + QDomElement modeElem = doc.createElement( QStringLiteral( "mode" ) ); + modeElem.setAttribute( QStringLiteral( "name" ), modeString ); rendererElem.appendChild( modeElem ); } - QDomElement rotationElem = doc.createElement( "rotation" ); + QDomElement rotationElem = doc.createElement( QStringLiteral( "rotation" ) ); rendererElem.appendChild( rotationElem ); - QDomElement sizeScaleElem = doc.createElement( "sizescale" ); + QDomElement sizeScaleElem = doc.createElement( QStringLiteral( "sizescale" ) ); rendererElem.appendChild( sizeScaleElem ); - QDomElement labelFormatElem = doc.createElement( "labelformat" ); + QDomElement labelFormatElem = doc.createElement( QStringLiteral( "labelformat" ) ); mLabelFormat.saveToDomElement( labelFormatElem ); rendererElem.appendChild( labelFormatElem ); @@ -1137,11 +1137,11 @@ QDomElement QgsGraduatedSymbolRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -1189,11 +1189,11 @@ QgsLegendSymbolListV2 QgsGraduatedSymbolRenderer::legendSymbolItemsV2() const QgsScaleExpression exp( ddSize.expressionString() ); if ( exp.type() != QgsScaleExpression::Unknown ) { - QgsLegendSymbolItem title( nullptr, exp.baseExpression(), "" ); + QgsLegendSymbolItem title( nullptr, exp.baseExpression(), QLatin1String( "" ) ); list << title; Q_FOREACH ( double v, QgsSymbolLayerUtils::prettyBreaks( exp.minValue(), exp.maxValue(), 4 ) ) { - QgsLegendSymbolItem si( mSourceSymbol.data(), QString::number( v ), "" ); + QgsLegendSymbolItem si( mSourceSymbol.data(), QString::number( v ), QLatin1String( "" ) ); QgsMarkerSymbol * s = static_cast<QgsMarkerSymbol *>( si.symbol() ); s->setDataDefinedSize( QgsDataDefined() ); s->setSize( exp.size( v ) ); @@ -1400,7 +1400,7 @@ void QgsGraduatedSymbolRenderer::setLegendSymbolItem( const QString& key, QgsSym void QgsGraduatedSymbolRenderer::addClass( QgsSymbol* symbol ) { QgsSymbol* newSymbol = symbol->clone(); - QString label = "0.0 - 0.0"; + QString label = QStringLiteral( "0.0 - 0.0" ); mRanges.insert( 0, QgsRendererRange( 0.0, 0.0, newSymbol, label ) ); } @@ -1611,17 +1611,17 @@ void QgsGraduatedSymbolRenderer::sortByLabel( Qt::SortOrder order ) QgsGraduatedSymbolRenderer* QgsGraduatedSymbolRenderer::convertFromRenderer( const QgsFeatureRenderer *renderer ) { QgsGraduatedSymbolRenderer* r = nullptr; - if ( renderer->type() == "graduatedSymbol" ) + if ( renderer->type() == QLatin1String( "graduatedSymbol" ) ) { r = dynamic_cast<QgsGraduatedSymbolRenderer*>( renderer->clone() ); } - else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) + else if ( renderer->type() == QLatin1String( "pointDisplacement" ) || renderer->type() == QLatin1String( "pointCluster" ) ) { const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast<const QgsPointDistanceRenderer*>( renderer ); if ( pointDistanceRenderer ) r = convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } - else if ( renderer->type() == "invertedPolygonRenderer" ) + else if ( renderer->type() == QLatin1String( "invertedPolygonRenderer" ) ) { const QgsInvertedPolygonRenderer* invertedPolygonRenderer = dynamic_cast<const QgsInvertedPolygonRenderer*>( renderer ); if ( invertedPolygonRenderer ) @@ -1633,7 +1633,7 @@ QgsGraduatedSymbolRenderer* QgsGraduatedSymbolRenderer::convertFromRenderer( con if ( !r ) { - r = new QgsGraduatedSymbolRenderer( "", QgsRangeList() ); + r = new QgsGraduatedSymbolRenderer( QLatin1String( "" ), QgsRangeList() ); QgsRenderContext context; QgsSymbolList symbols = const_cast<QgsFeatureRenderer *>( renderer )->symbols( context ); if ( !symbols.isEmpty() ) diff --git a/src/core/symbology-ng/qgsheatmaprenderer.cpp b/src/core/symbology-ng/qgsheatmaprenderer.cpp index 34ba0532ef4a..664deb4e13ca 100644 --- a/src/core/symbology-ng/qgsheatmaprenderer.cpp +++ b/src/core/symbology-ng/qgsheatmaprenderer.cpp @@ -32,7 +32,7 @@ #include <QDomElement> QgsHeatmapRenderer::QgsHeatmapRenderer() - : QgsFeatureRenderer( "heatmapRenderer" ) + : QgsFeatureRenderer( QStringLiteral( "heatmapRenderer" ) ) , mCalculatedMaxValue( 0 ) , mRadius( 10 ) , mRadiusPixels( 0 ) @@ -276,7 +276,7 @@ void QgsHeatmapRenderer::renderImage( QgsRenderContext& context ) QString QgsHeatmapRenderer::dump() const { - return "[HEATMAP]"; + return QStringLiteral( "[HEATMAP]" ); } QgsHeatmapRenderer* QgsHeatmapRenderer::clone() const @@ -325,50 +325,50 @@ void QgsHeatmapRenderer::modifyRequestExtent( QgsRectangle &extent, QgsRenderCon QgsFeatureRenderer* QgsHeatmapRenderer::create( QDomElement& element ) { QgsHeatmapRenderer* r = new QgsHeatmapRenderer(); - r->setRadius( element.attribute( "radius", "50.0" ).toFloat() ); - r->setRadiusUnit( static_cast< QgsUnitTypes::RenderUnit >( element.attribute( "radius_unit", "0" ).toInt() ) ); - r->setRadiusMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( "radius_map_unit_scale", QString() ) ) ); - r->setMaximumValue( element.attribute( "max_value", "0.0" ).toFloat() ); - r->setRenderQuality( element.attribute( "quality", "0" ).toInt() ); - r->setWeightExpression( element.attribute( "weight_expression" ) ); - - QDomElement sourceColorRampElem = element.firstChildElement( "colorramp" ); - if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( "name" ) == "[source]" ) + r->setRadius( element.attribute( QStringLiteral( "radius" ), QStringLiteral( "50.0" ) ).toFloat() ); + r->setRadiusUnit( static_cast< QgsUnitTypes::RenderUnit >( element.attribute( QStringLiteral( "radius_unit" ), QStringLiteral( "0" ) ).toInt() ) ); + r->setRadiusMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( QStringLiteral( "radius_map_unit_scale" ), QString() ) ) ); + r->setMaximumValue( element.attribute( QStringLiteral( "max_value" ), QStringLiteral( "0.0" ) ).toFloat() ); + r->setRenderQuality( element.attribute( QStringLiteral( "quality" ), QStringLiteral( "0" ) ).toInt() ); + r->setWeightExpression( element.attribute( QStringLiteral( "weight_expression" ) ) ); + + QDomElement sourceColorRampElem = element.firstChildElement( QStringLiteral( "colorramp" ) ); + if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( QStringLiteral( "name" ) ) == QLatin1String( "[source]" ) ) { r->setColorRamp( QgsSymbolLayerUtils::loadColorRamp( sourceColorRampElem ) ); } - r->setInvertRamp( element.attribute( "invert_ramp", "0" ).toInt() ); + r->setInvertRamp( element.attribute( QStringLiteral( "invert_ramp" ), QStringLiteral( "0" ) ).toInt() ); return r; } QDomElement QgsHeatmapRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "heatmapRenderer" ); - rendererElem.setAttribute( "radius", QString::number( mRadius ) ); - rendererElem.setAttribute( "radius_unit", QString::number( mRadiusUnit ) ); - rendererElem.setAttribute( "radius_map_unit_scale", QgsSymbolLayerUtils::encodeMapUnitScale( mRadiusMapUnitScale ) ); - rendererElem.setAttribute( "max_value", QString::number( mExplicitMax ) ); - rendererElem.setAttribute( "quality", QString::number( mRenderQuality ) ); - rendererElem.setAttribute( "weight_expression", mWeightExpressionString ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "heatmapRenderer" ) ); + rendererElem.setAttribute( QStringLiteral( "radius" ), QString::number( mRadius ) ); + rendererElem.setAttribute( QStringLiteral( "radius_unit" ), QString::number( mRadiusUnit ) ); + rendererElem.setAttribute( QStringLiteral( "radius_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mRadiusMapUnitScale ) ); + rendererElem.setAttribute( QStringLiteral( "max_value" ), QString::number( mExplicitMax ) ); + rendererElem.setAttribute( QStringLiteral( "quality" ), QString::number( mRenderQuality ) ); + rendererElem.setAttribute( QStringLiteral( "weight_expression" ), mWeightExpressionString ); if ( mGradientRamp ) { - QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( "[source]", mGradientRamp, doc ); + QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( QStringLiteral( "[source]" ), mGradientRamp, doc ); rendererElem.appendChild( colorRampElem ); } - rendererElem.setAttribute( "invert_ramp", QString::number( mInvertRamp ) ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "invert_ramp" ), QString::number( mInvertRamp ) ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) mPaintEffect->saveProperties( doc, rendererElem ); if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -403,7 +403,7 @@ QSet<QString> QgsHeatmapRenderer::usedAttributes() const QgsHeatmapRenderer* QgsHeatmapRenderer::convertFromRenderer( const QgsFeatureRenderer *renderer ) { - if ( renderer->type() == "heatmapRenderer" ) + if ( renderer->type() == QLatin1String( "heatmapRenderer" ) ) { return dynamic_cast<QgsHeatmapRenderer*>( renderer->clone() ); } diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp b/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp index 8bf2e09b0638..db3323c5fc22 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.cpp @@ -30,7 +30,7 @@ #include <QDomElement> QgsInvertedPolygonRenderer::QgsInvertedPolygonRenderer( QgsFeatureRenderer* subRenderer ) - : QgsFeatureRenderer( "invertedPolygonRenderer" ) + : QgsFeatureRenderer( QStringLiteral( "invertedPolygonRenderer" ) ) , mPreprocessingEnabled( false ) { if ( subRenderer ) @@ -356,7 +356,7 @@ QString QgsInvertedPolygonRenderer::dump() const { if ( !mSubRenderer ) { - return "INVERTED: NULL"; + return QStringLiteral( "INVERTED: NULL" ); } return "INVERTED [" + mSubRenderer->dump() + ']'; } @@ -381,22 +381,22 @@ QgsFeatureRenderer* QgsInvertedPolygonRenderer::create( QDomElement& element ) { QgsInvertedPolygonRenderer* r = new QgsInvertedPolygonRenderer(); //look for an embedded renderer <renderer-v2> - QDomElement embeddedRendererElem = element.firstChildElement( "renderer-v2" ); + QDomElement embeddedRendererElem = element.firstChildElement( QStringLiteral( "renderer-v2" ) ); if ( !embeddedRendererElem.isNull() ) { QgsFeatureRenderer* renderer = QgsFeatureRenderer::load( embeddedRendererElem ); r->setEmbeddedRenderer( renderer ); } - r->setPreprocessingEnabled( element.attribute( "preprocessing", "0" ).toInt() == 1 ); + r->setPreprocessingEnabled( element.attribute( QStringLiteral( "preprocessing" ), QStringLiteral( "0" ) ).toInt() == 1 ); return r; } QDomElement QgsInvertedPolygonRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "invertedPolygonRenderer" ); - rendererElem.setAttribute( "preprocessing", preprocessingEnabled() ? "1" : "0" ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "invertedPolygonRenderer" ) ); + rendererElem.setAttribute( QStringLiteral( "preprocessing" ), preprocessingEnabled() ? "1" : "0" ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); if ( mSubRenderer ) { @@ -409,11 +409,11 @@ QDomElement QgsInvertedPolygonRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -506,15 +506,15 @@ bool QgsInvertedPolygonRenderer::willRenderFeature( QgsFeature& feat, QgsRenderC QgsInvertedPolygonRenderer* QgsInvertedPolygonRenderer::convertFromRenderer( const QgsFeatureRenderer *renderer ) { - if ( renderer->type() == "invertedPolygonRenderer" ) + if ( renderer->type() == QLatin1String( "invertedPolygonRenderer" ) ) { return dynamic_cast<QgsInvertedPolygonRenderer*>( renderer->clone() ); } - if ( renderer->type() == "singleSymbol" || - renderer->type() == "categorizedSymbol" || - renderer->type() == "graduatedSymbol" || - renderer->type() == "RuleRenderer" ) + if ( renderer->type() == QLatin1String( "singleSymbol" ) || + renderer->type() == QLatin1String( "categorizedSymbol" ) || + renderer->type() == QLatin1String( "graduatedSymbol" ) || + renderer->type() == QLatin1String( "RuleRenderer" ) ) { return new QgsInvertedPolygonRenderer( renderer->clone() ); } diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h index a7e510acff2e..c83f78a70c80 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h @@ -94,7 +94,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer /** Proxy that will call this method on the embedded renderer. * @note not available in python bindings */ - virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; + virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) override; /** Proxy that will call this method on the embedded renderer. */ virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgslinesymbollayer.cpp b/src/core/symbology-ng/qgslinesymbollayer.cpp index 2633544e31cd..dcba6bdf5c36 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.cpp +++ b/src/core/symbology-ng/qgslinesymbollayer.cpp @@ -87,92 +87,92 @@ QgsSymbolLayer* QgsSimpleLineSymbolLayer::create( const QgsStringMap& props ) double width = DEFAULT_SIMPLELINE_WIDTH; Qt::PenStyle penStyle = DEFAULT_SIMPLELINE_PENSTYLE; - if ( props.contains( "line_color" ) ) + if ( props.contains( QStringLiteral( "line_color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( props["line_color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "line_color" )] ); } - else if ( props.contains( "outline_color" ) ) + else if ( props.contains( QStringLiteral( "outline_color" ) ) ) { - color = QgsSymbolLayerUtils::decodeColor( props["outline_color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "outline_color" )] ); } - else if ( props.contains( "color" ) ) + else if ( props.contains( QStringLiteral( "color" ) ) ) { //pre 2.5 projects used "color" - color = QgsSymbolLayerUtils::decodeColor( props["color"] ); + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ); } - if ( props.contains( "line_width" ) ) + if ( props.contains( QStringLiteral( "line_width" ) ) ) { - width = props["line_width"].toDouble(); + width = props[QStringLiteral( "line_width" )].toDouble(); } - else if ( props.contains( "outline_width" ) ) + else if ( props.contains( QStringLiteral( "outline_width" ) ) ) { - width = props["outline_width"].toDouble(); + width = props[QStringLiteral( "outline_width" )].toDouble(); } - else if ( props.contains( "width" ) ) + else if ( props.contains( QStringLiteral( "width" ) ) ) { //pre 2.5 projects used "width" - width = props["width"].toDouble(); + width = props[QStringLiteral( "width" )].toDouble(); } - if ( props.contains( "line_style" ) ) + if ( props.contains( QStringLiteral( "line_style" ) ) ) { - penStyle = QgsSymbolLayerUtils::decodePenStyle( props["line_style"] ); + penStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "line_style" )] ); } - else if ( props.contains( "outline_style" ) ) + else if ( props.contains( QStringLiteral( "outline_style" ) ) ) { - penStyle = QgsSymbolLayerUtils::decodePenStyle( props["outline_style"] ); + penStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "outline_style" )] ); } - else if ( props.contains( "penstyle" ) ) + else if ( props.contains( QStringLiteral( "penstyle" ) ) ) { - penStyle = QgsSymbolLayerUtils::decodePenStyle( props["penstyle"] ); + penStyle = QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "penstyle" )] ); } QgsSimpleLineSymbolLayer* l = new QgsSimpleLineSymbolLayer( color, width, penStyle ); - if ( props.contains( "line_width_unit" ) ) + if ( props.contains( QStringLiteral( "line_width_unit" ) ) ) { - l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props["line_width_unit"] ) ); + l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "line_width_unit" )] ) ); } - else if ( props.contains( "outline_width_unit" ) ) + else if ( props.contains( QStringLiteral( "outline_width_unit" ) ) ) { - l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props["outline_width_unit"] ) ); + l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "outline_width_unit" )] ) ); } - else if ( props.contains( "width_unit" ) ) + else if ( props.contains( QStringLiteral( "width_unit" ) ) ) { //pre 2.5 projects used "width_unit" - l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props["width_unit"] ) ); + l->setWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "width_unit" )] ) ); } - if ( props.contains( "width_map_unit_scale" ) ) - l->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["width_map_unit_scale"] ) ); - if ( props.contains( "offset" ) ) - l->setOffset( props["offset"].toDouble() ); - if ( props.contains( "offset_unit" ) ) - l->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - l->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); - if ( props.contains( "joinstyle" ) ) - l->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( props["joinstyle"] ) ); - if ( props.contains( "capstyle" ) ) - l->setPenCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( props["capstyle"] ) ); + if ( props.contains( QStringLiteral( "width_map_unit_scale" ) ) ) + l->setWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "width_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + l->setOffset( props[QStringLiteral( "offset" )].toDouble() ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + l->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + l->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "joinstyle" ) ) ) + l->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( props[QStringLiteral( "joinstyle" )] ) ); + if ( props.contains( QStringLiteral( "capstyle" ) ) ) + l->setPenCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( props[QStringLiteral( "capstyle" )] ) ); - if ( props.contains( "use_custom_dash" ) ) + if ( props.contains( QStringLiteral( "use_custom_dash" ) ) ) { - l->setUseCustomDashPattern( props["use_custom_dash"].toInt() ); + l->setUseCustomDashPattern( props[QStringLiteral( "use_custom_dash" )].toInt() ); } - if ( props.contains( "customdash" ) ) + if ( props.contains( QStringLiteral( "customdash" ) ) ) { - l->setCustomDashVector( QgsSymbolLayerUtils::decodeRealVector( props["customdash"] ) ); + l->setCustomDashVector( QgsSymbolLayerUtils::decodeRealVector( props[QStringLiteral( "customdash" )] ) ); } - if ( props.contains( "customdash_unit" ) ) + if ( props.contains( QStringLiteral( "customdash_unit" ) ) ) { - l->setCustomDashPatternUnit( QgsUnitTypes::decodeRenderUnit( props["customdash_unit"] ) ); + l->setCustomDashPatternUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "customdash_unit" )] ) ); } - if ( props.contains( "customdash_map_unit_scale" ) ) + if ( props.contains( QStringLiteral( "customdash_map_unit_scale" ) ) ) { - l->setCustomDashPatternMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["customdash_map_unit_scale"] ) ); + l->setCustomDashPatternMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "customdash_map_unit_scale" )] ) ); } - if ( props.contains( "draw_inside_polygon" ) ) + if ( props.contains( QStringLiteral( "draw_inside_polygon" ) ) ) { - l->setDrawInsidePolygon( props["draw_inside_polygon"].toInt() ); + l->setDrawInsidePolygon( props[QStringLiteral( "draw_inside_polygon" )].toInt() ); } l->restoreDataDefinedProperties( props ); @@ -183,7 +183,7 @@ QgsSymbolLayer* QgsSimpleLineSymbolLayer::create( const QgsStringMap& props ) QString QgsSimpleLineSymbolLayer::layerType() const { - return "SimpleLine"; + return QStringLiteral( "SimpleLine" ); } void QgsSimpleLineSymbolLayer::startRender( QgsSymbolRenderContext& context ) @@ -344,21 +344,21 @@ void QgsSimpleLineSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbo QgsStringMap QgsSimpleLineSymbolLayer::properties() const { QgsStringMap map; - map["line_color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["line_width"] = QString::number( mWidth ); - map["line_width_unit"] = QgsUnitTypes::encodeUnit( mWidthUnit ); - map["width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale ); - map["line_style"] = QgsSymbolLayerUtils::encodePenStyle( mPenStyle ); - map["joinstyle"] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); - map["capstyle"] = QgsSymbolLayerUtils::encodePenCapStyle( mPenCapStyle ); - map["offset"] = QString::number( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["use_custom_dash"] = ( mUseCustomDashPattern ? "1" : "0" ); - map["customdash"] = QgsSymbolLayerUtils::encodeRealVector( mCustomDashVector ); - map["customdash_unit"] = QgsUnitTypes::encodeUnit( mCustomDashPatternUnit ); - map["customdash_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mCustomDashPatternMapUnitScale ); - map["draw_inside_polygon"] = ( mDrawInsidePolygon ? "1" : "0" ); + map[QStringLiteral( "line_color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "line_width" )] = QString::number( mWidth ); + map[QStringLiteral( "line_width_unit" )] = QgsUnitTypes::encodeUnit( mWidthUnit ); + map[QStringLiteral( "width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mWidthMapUnitScale ); + map[QStringLiteral( "line_style" )] = QgsSymbolLayerUtils::encodePenStyle( mPenStyle ); + map[QStringLiteral( "joinstyle" )] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); + map[QStringLiteral( "capstyle" )] = QgsSymbolLayerUtils::encodePenCapStyle( mPenCapStyle ); + map[QStringLiteral( "offset" )] = QString::number( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "use_custom_dash" )] = ( mUseCustomDashPattern ? "1" : "0" ); + map[QStringLiteral( "customdash" )] = QgsSymbolLayerUtils::encodeRealVector( mCustomDashVector ); + map[QStringLiteral( "customdash_unit" )] = QgsUnitTypes::encodeUnit( mCustomDashPatternUnit ); + map[QStringLiteral( "customdash_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mCustomDashPatternMapUnitScale ); + map[QStringLiteral( "draw_inside_polygon" )] = ( mDrawInsidePolygon ? "1" : "0" ); saveDataDefinedProperties( map ); return map; } @@ -388,16 +388,16 @@ void QgsSimpleLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c if ( mPenStyle == Qt::NoPen ) return; - QDomElement symbolizerElem = doc.createElement( "se:LineSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:LineSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); // <Stroke> - QDomElement strokeElem = doc.createElement( "se:Stroke" ); + QDomElement strokeElem = doc.createElement( QStringLiteral( "se:Stroke" ) ); symbolizerElem.appendChild( strokeElem ); Qt::PenStyle penStyle = mUseCustomDashPattern ? Qt::CustomDashLine : mPenStyle; @@ -409,7 +409,7 @@ void QgsSimpleLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c // <se:PerpendicularOffset> if ( !qgsDoubleNear( mOffset, 0.0 ) ) { - QDomElement perpOffsetElem = doc.createElement( "se:PerpendicularOffset" ); + QDomElement perpOffsetElem = doc.createElement( QStringLiteral( "se:PerpendicularOffset" ) ); double offset = QgsSymbolLayerUtils::rescaleUom( mOffset, mOffsetUnit, props ); perpOffsetElem.appendChild( doc.createTextNode( qgsDoubleToString( offset ) ) ); symbolizerElem.appendChild( perpOffsetElem ); @@ -435,7 +435,7 @@ QgsSymbolLayer* QgsSimpleLineSymbolLayer::createFromSld( QDomElement &element ) { QgsDebugMsg( "Entered." ); - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( strokeElem.isNull() ) return nullptr; @@ -453,7 +453,7 @@ QgsSymbolLayer* QgsSimpleLineSymbolLayer::createFromSld( QDomElement &element ) return nullptr; double offset = 0.0; - QDomElement perpOffsetElem = element.firstChildElement( "PerpendicularOffset" ); + QDomElement perpOffsetElem = element.firstChildElement( QStringLiteral( "PerpendicularOffset" ) ); if ( !perpOffsetElem.isNull() ) { bool ok; @@ -724,57 +724,57 @@ QgsSymbolLayer* QgsMarkerLineSymbolLayer::create( const QgsStringMap& props ) double interval = DEFAULT_MARKERLINE_INTERVAL; - if ( props.contains( "interval" ) ) - interval = props["interval"].toDouble(); - if ( props.contains( "rotate" ) ) - rotate = ( props["rotate"] == "1" ); + if ( props.contains( QStringLiteral( "interval" ) ) ) + interval = props[QStringLiteral( "interval" )].toDouble(); + if ( props.contains( QStringLiteral( "rotate" ) ) ) + rotate = ( props[QStringLiteral( "rotate" )] == QLatin1String( "1" ) ); QgsMarkerLineSymbolLayer* x = new QgsMarkerLineSymbolLayer( rotate, interval ); - if ( props.contains( "offset" ) ) + if ( props.contains( QStringLiteral( "offset" ) ) ) { - x->setOffset( props["offset"].toDouble() ); + x->setOffset( props[QStringLiteral( "offset" )].toDouble() ); } - if ( props.contains( "offset_unit" ) ) + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) { - x->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); + x->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); } - if ( props.contains( "interval_unit" ) ) + if ( props.contains( QStringLiteral( "interval_unit" ) ) ) { - x->setIntervalUnit( QgsUnitTypes::decodeRenderUnit( props["interval_unit"] ) ); + x->setIntervalUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "interval_unit" )] ) ); } - if ( props.contains( "offset_along_line" ) ) + if ( props.contains( QStringLiteral( "offset_along_line" ) ) ) { - x->setOffsetAlongLine( props["offset_along_line"].toDouble() ); + x->setOffsetAlongLine( props[QStringLiteral( "offset_along_line" )].toDouble() ); } - if ( props.contains( "offset_along_line_unit" ) ) + if ( props.contains( QStringLiteral( "offset_along_line_unit" ) ) ) { - x->setOffsetAlongLineUnit( QgsUnitTypes::decodeRenderUnit( props["offset_along_line_unit"] ) ); + x->setOffsetAlongLineUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_along_line_unit" )] ) ); } if ( props.contains(( "offset_along_line_map_unit_scale" ) ) ) { - x->setOffsetAlongLineMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_along_line_map_unit_scale"] ) ); + x->setOffsetAlongLineMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_along_line_map_unit_scale" )] ) ); } - if ( props.contains( "offset_map_unit_scale" ) ) + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) { - x->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); + x->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); } - if ( props.contains( "interval_map_unit_scale" ) ) + if ( props.contains( QStringLiteral( "interval_map_unit_scale" ) ) ) { - x->setIntervalMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["interval_map_unit_scale"] ) ); + x->setIntervalMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "interval_map_unit_scale" )] ) ); } - if ( props.contains( "placement" ) ) + if ( props.contains( QStringLiteral( "placement" ) ) ) { - if ( props["placement"] == "vertex" ) + if ( props[QStringLiteral( "placement" )] == QLatin1String( "vertex" ) ) x->setPlacement( Vertex ); - else if ( props["placement"] == "lastvertex" ) + else if ( props[QStringLiteral( "placement" )] == QLatin1String( "lastvertex" ) ) x->setPlacement( LastVertex ); - else if ( props["placement"] == "firstvertex" ) + else if ( props[QStringLiteral( "placement" )] == QLatin1String( "firstvertex" ) ) x->setPlacement( FirstVertex ); - else if ( props["placement"] == "centralpoint" ) + else if ( props[QStringLiteral( "placement" )] == QLatin1String( "centralpoint" ) ) x->setPlacement( CentralPoint ); - else if ( props["placement"] == "curvepoint" ) + else if ( props[QStringLiteral( "placement" )] == QLatin1String( "curvepoint" ) ) x->setPlacement( CurvePoint ); else x->setPlacement( Interval ); @@ -787,7 +787,7 @@ QgsSymbolLayer* QgsMarkerLineSymbolLayer::create( const QgsStringMap& props ) QString QgsMarkerLineSymbolLayer::layerType() const { - return "MarkerLine"; + return QStringLiteral( "MarkerLine" ); } void QgsMarkerLineSymbolLayer::setColor( const QColor& color ) @@ -837,23 +837,23 @@ void QgsMarkerLineSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbo QString placementString = evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_PLACEMENT, context, QVariant(), &ok ).toString(); if ( ok ) { - if ( placementString.compare( "vertex", Qt::CaseInsensitive ) == 0 ) + if ( placementString.compare( QLatin1String( "vertex" ), Qt::CaseInsensitive ) == 0 ) { placement = Vertex; } - else if ( placementString.compare( "lastvertex", Qt::CaseInsensitive ) == 0 ) + else if ( placementString.compare( QLatin1String( "lastvertex" ), Qt::CaseInsensitive ) == 0 ) { placement = LastVertex; } - else if ( placementString.compare( "firstvertex", Qt::CaseInsensitive ) == 0 ) + else if ( placementString.compare( QLatin1String( "firstvertex" ), Qt::CaseInsensitive ) == 0 ) { placement = FirstVertex; } - else if ( placementString.compare( "centerpoint", Qt::CaseInsensitive ) == 0 ) + else if ( placementString.compare( QLatin1String( "centerpoint" ), Qt::CaseInsensitive ) == 0 ) { placement = CentralPoint; } - else if ( placementString.compare( "curvepoint", Qt::CaseInsensitive ) == 0 ) + else if ( placementString.compare( QLatin1String( "curvepoint" ), Qt::CaseInsensitive ) == 0 ) { placement = CurvePoint; } @@ -1320,28 +1320,28 @@ void QgsMarkerLineSymbolLayer::renderPolylineCentral( const QPolygonF& points, Q QgsStringMap QgsMarkerLineSymbolLayer::properties() const { QgsStringMap map; - map["rotate"] = ( mRotateMarker ? "1" : "0" ); - map["interval"] = QString::number( mInterval ); - map["offset"] = QString::number( mOffset ); - map["offset_along_line"] = QString::number( mOffsetAlongLine ); - map["offset_along_line_unit"] = QgsUnitTypes::encodeUnit( mOffsetAlongLineUnit ); - map["offset_along_line_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetAlongLineMapUnitScale ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["interval_unit"] = QgsUnitTypes::encodeUnit( mIntervalUnit ); - map["interval_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mIntervalMapUnitScale ); + map[QStringLiteral( "rotate" )] = ( mRotateMarker ? "1" : "0" ); + map[QStringLiteral( "interval" )] = QString::number( mInterval ); + map[QStringLiteral( "offset" )] = QString::number( mOffset ); + map[QStringLiteral( "offset_along_line" )] = QString::number( mOffsetAlongLine ); + map[QStringLiteral( "offset_along_line_unit" )] = QgsUnitTypes::encodeUnit( mOffsetAlongLineUnit ); + map[QStringLiteral( "offset_along_line_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetAlongLineMapUnitScale ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "interval_unit" )] = QgsUnitTypes::encodeUnit( mIntervalUnit ); + map[QStringLiteral( "interval_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mIntervalMapUnitScale ); if ( mPlacement == Vertex ) - map["placement"] = "vertex"; + map[QStringLiteral( "placement" )] = QStringLiteral( "vertex" ); else if ( mPlacement == LastVertex ) - map["placement"] = "lastvertex"; + map[QStringLiteral( "placement" )] = QStringLiteral( "lastvertex" ); else if ( mPlacement == FirstVertex ) - map["placement"] = "firstvertex"; + map[QStringLiteral( "placement" )] = QStringLiteral( "firstvertex" ); else if ( mPlacement == CentralPoint ) - map["placement"] = "centralpoint"; + map[QStringLiteral( "placement" )] = QStringLiteral( "centralpoint" ); else if ( mPlacement == CurvePoint ) - map["placement"] = "curvepoint"; + map[QStringLiteral( "placement" )] = QStringLiteral( "curvepoint" ); else - map["placement"] = "interval"; + map[QStringLiteral( "placement" )] = QStringLiteral( "interval" ); saveDataDefinedProperties( map ); return map; @@ -1388,29 +1388,29 @@ void QgsMarkerLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c { for ( int i = 0; i < mMarker->symbolLayerCount(); i++ ) { - QDomElement symbolizerElem = doc.createElement( "se:LineSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:LineSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); QString gap; switch ( mPlacement ) { case FirstVertex: - symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, "placement", "firstPoint" ) ); + symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "placement" ), QStringLiteral( "firstPoint" ) ) ); break; case LastVertex: - symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, "placement", "lastPoint" ) ); + symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "placement" ), QStringLiteral( "lastPoint" ) ) ); break; case CentralPoint: - symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, "placement", "centralPoint" ) ); + symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "placement" ), QStringLiteral( "centralPoint" ) ) ); break; case Vertex: // no way to get line/polygon's vertices, use a VendorOption - symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, "placement", "points" ) ); + symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "placement" ), QStringLiteral( "points" ) ) ); break; default: double interval = QgsSymbolLayerUtils::rescaleUom( mInterval, mIntervalUnit, props ); @@ -1422,22 +1422,22 @@ void QgsMarkerLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c { // markers in LineSymbolizer must be drawn following the line orientation, // use a VendorOption when no marker rotation - symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, "rotateMarker", "0" ) ); + symbolizerElem.appendChild( QgsSymbolLayerUtils::createVendorOptionElement( doc, QStringLiteral( "rotateMarker" ), QStringLiteral( "0" ) ) ); } // <Stroke> - QDomElement strokeElem = doc.createElement( "se:Stroke" ); + QDomElement strokeElem = doc.createElement( QStringLiteral( "se:Stroke" ) ); symbolizerElem.appendChild( strokeElem ); // <GraphicStroke> - QDomElement graphicStrokeElem = doc.createElement( "se:GraphicStroke" ); + QDomElement graphicStrokeElem = doc.createElement( QStringLiteral( "se:GraphicStroke" ) ); strokeElem.appendChild( graphicStrokeElem ); QgsSymbolLayer *layer = mMarker->symbolLayer( i ); QgsMarkerSymbolLayer *markerLayer = static_cast<QgsMarkerSymbolLayer *>( layer ); if ( !markerLayer ) { - graphicStrokeElem.appendChild( doc.createComment( QString( "MarkerSymbolLayerV2 expected, %1 found. Skip it." ).arg( layer->layerType() ) ) ); + graphicStrokeElem.appendChild( doc.createComment( QStringLiteral( "MarkerSymbolLayerV2 expected, %1 found. Skip it." ).arg( layer->layerType() ) ) ); } else { @@ -1446,14 +1446,14 @@ void QgsMarkerLineSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, c if ( !gap.isEmpty() ) { - QDomElement gapElem = doc.createElement( "se:Gap" ); + QDomElement gapElem = doc.createElement( QStringLiteral( "se:Gap" ) ); QgsSymbolLayerUtils::createExpressionElement( doc, gapElem, gap ); graphicStrokeElem.appendChild( gapElem ); } if ( !qgsDoubleNear( mOffset, 0.0 ) ) { - QDomElement perpOffsetElem = doc.createElement( "se:PerpendicularOffset" ); + QDomElement perpOffsetElem = doc.createElement( QStringLiteral( "se:PerpendicularOffset" ) ); double offset = QgsSymbolLayerUtils::rescaleUom( mOffset, mOffsetUnit, props ); perpOffsetElem.appendChild( doc.createTextNode( qgsDoubleToString( offset ) ) ); symbolizerElem.appendChild( perpOffsetElem ); @@ -1465,11 +1465,11 @@ QgsSymbolLayer* QgsMarkerLineSymbolLayer::createFromSld( QDomElement &element ) { QgsDebugMsg( "Entered." ); - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( strokeElem.isNull() ) return nullptr; - QDomElement graphicStrokeElem = strokeElem.firstChildElement( "GraphicStroke" ); + QDomElement graphicStrokeElem = strokeElem.firstChildElement( QStringLiteral( "GraphicStroke" ) ); if ( graphicStrokeElem.isNull() ) return nullptr; @@ -1480,16 +1480,16 @@ QgsSymbolLayer* QgsMarkerLineSymbolLayer::createFromSld( QDomElement &element ) QgsStringMap vendorOptions = QgsSymbolLayerUtils::getVendorOptionList( element ); for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it ) { - if ( it.key() == "placement" ) + if ( it.key() == QLatin1String( "placement" ) ) { - if ( it.value() == "points" ) placement = Vertex; - else if ( it.value() == "firstPoint" ) placement = FirstVertex; - else if ( it.value() == "lastPoint" ) placement = LastVertex; - else if ( it.value() == "centralPoint" ) placement = CentralPoint; + if ( it.value() == QLatin1String( "points" ) ) placement = Vertex; + else if ( it.value() == QLatin1String( "firstPoint" ) ) placement = FirstVertex; + else if ( it.value() == QLatin1String( "lastPoint" ) ) placement = LastVertex; + else if ( it.value() == QLatin1String( "centralPoint" ) ) placement = CentralPoint; } - else if ( it.value() == "rotateMarker" ) + else if ( it.value() == QLatin1String( "rotateMarker" ) ) { - rotateMarker = it.value() == "0"; + rotateMarker = it.value() == QLatin1String( "0" ); } } @@ -1507,7 +1507,7 @@ QgsSymbolLayer* QgsMarkerLineSymbolLayer::createFromSld( QDomElement &element ) return nullptr; double interval = 0.0; - QDomElement gapElem = graphicStrokeElem.firstChildElement( "Gap" ); + QDomElement gapElem = graphicStrokeElem.firstChildElement( QStringLiteral( "Gap" ) ); if ( !gapElem.isNull() ) { bool ok; @@ -1517,7 +1517,7 @@ QgsSymbolLayer* QgsMarkerLineSymbolLayer::createFromSld( QDomElement &element ) } double offset = 0.0; - QDomElement perpOffsetElem = graphicStrokeElem.firstChildElement( "PerpendicularOffset" ); + QDomElement perpOffsetElem = graphicStrokeElem.firstChildElement( QStringLiteral( "PerpendicularOffset" ) ); if ( !perpOffsetElem.isNull() ) { bool ok; diff --git a/src/core/symbology-ng/qgsmarkersymbollayer.cpp b/src/core/symbology-ng/qgsmarkersymbollayer.cpp index 3ac207234881..fff7ff1b5f78 100644 --- a/src/core/symbology-ng/qgsmarkersymbollayer.cpp +++ b/src/core/symbology-ng/qgsmarkersymbollayer.cpp @@ -278,51 +278,51 @@ QgsSimpleMarkerSymbolLayerBase::Shape QgsSimpleMarkerSymbolLayerBase::decodeShap *ok = true; QString cleaned = name.toLower().trimmed(); - if ( cleaned == "square" || cleaned == "rectangle" ) + if ( cleaned == QLatin1String( "square" ) || cleaned == QLatin1String( "rectangle" ) ) return Square; - else if ( cleaned == "diamond" ) + else if ( cleaned == QLatin1String( "diamond" ) ) return Diamond; - else if ( cleaned == "pentagon" ) + else if ( cleaned == QLatin1String( "pentagon" ) ) return Pentagon; - else if ( cleaned == "hexagon" ) + else if ( cleaned == QLatin1String( "hexagon" ) ) return Hexagon; - else if ( cleaned == "triangle" ) + else if ( cleaned == QLatin1String( "triangle" ) ) return Triangle; - else if ( cleaned == "equilateral_triangle" ) + else if ( cleaned == QLatin1String( "equilateral_triangle" ) ) return EquilateralTriangle; - else if ( cleaned == "star" || cleaned == "regular_star" ) + else if ( cleaned == QLatin1String( "star" ) || cleaned == QLatin1String( "regular_star" ) ) return Star; - else if ( cleaned == "arrow" ) + else if ( cleaned == QLatin1String( "arrow" ) ) return Arrow; - else if ( cleaned == "circle" ) + else if ( cleaned == QLatin1String( "circle" ) ) return Circle; - else if ( cleaned == "cross" ) + else if ( cleaned == QLatin1String( "cross" ) ) return Cross; - else if ( cleaned == "cross_fill" ) + else if ( cleaned == QLatin1String( "cross_fill" ) ) return CrossFill; - else if ( cleaned == "cross2" || cleaned == "x" ) + else if ( cleaned == QLatin1String( "cross2" ) || cleaned == QLatin1String( "x" ) ) return Cross2; - else if ( cleaned == "line" ) + else if ( cleaned == QLatin1String( "line" ) ) return Line; - else if ( cleaned == "arrowhead" ) + else if ( cleaned == QLatin1String( "arrowhead" ) ) return ArrowHead; - else if ( cleaned == "filled_arrowhead" ) + else if ( cleaned == QLatin1String( "filled_arrowhead" ) ) return ArrowHeadFilled; - else if ( cleaned == "semi_circle" ) + else if ( cleaned == QLatin1String( "semi_circle" ) ) return SemiCircle; - else if ( cleaned == "third_circle" ) + else if ( cleaned == QLatin1String( "third_circle" ) ) return ThirdCircle; - else if ( cleaned == "quarter_circle" ) + else if ( cleaned == QLatin1String( "quarter_circle" ) ) return QuarterCircle; - else if ( cleaned == "quarter_square" ) + else if ( cleaned == QLatin1String( "quarter_square" ) ) return QuarterSquare; - else if ( cleaned == "half_square" ) + else if ( cleaned == QLatin1String( "half_square" ) ) return HalfSquare; - else if ( cleaned == "diagonal_half_square" ) + else if ( cleaned == QLatin1String( "diagonal_half_square" ) ) return DiagonalHalfSquare; - else if ( cleaned == "right_half_triangle" ) + else if ( cleaned == QLatin1String( "right_half_triangle" ) ) return RightHalfTriangle; - else if ( cleaned == "left_half_triangle" ) + else if ( cleaned == QLatin1String( "left_half_triangle" ) ) return LeftHalfTriangle; if ( ok ) @@ -335,51 +335,51 @@ QString QgsSimpleMarkerSymbolLayerBase::encodeShape( QgsSimpleMarkerSymbolLayerB switch ( shape ) { case Square: - return "square"; + return QStringLiteral( "square" ); case QuarterSquare: - return "quarter_square"; + return QStringLiteral( "quarter_square" ); case HalfSquare: - return "half_square"; + return QStringLiteral( "half_square" ); case DiagonalHalfSquare: - return "diagonal_half_square"; + return QStringLiteral( "diagonal_half_square" ); case Diamond: - return "diamond"; + return QStringLiteral( "diamond" ); case Pentagon: - return "pentagon"; + return QStringLiteral( "pentagon" ); case Hexagon: - return "hexagon"; + return QStringLiteral( "hexagon" ); case Triangle: - return "triangle"; + return QStringLiteral( "triangle" ); case EquilateralTriangle: - return "equilateral_triangle"; + return QStringLiteral( "equilateral_triangle" ); case LeftHalfTriangle: - return "left_half_triangle"; + return QStringLiteral( "left_half_triangle" ); case RightHalfTriangle: - return "right_half_triangle"; + return QStringLiteral( "right_half_triangle" ); case Star: - return "star"; + return QStringLiteral( "star" ); case Arrow: - return "arrow"; + return QStringLiteral( "arrow" ); case ArrowHeadFilled: - return "filled_arrowhead"; + return QStringLiteral( "filled_arrowhead" ); case CrossFill: - return "cross_fill"; + return QStringLiteral( "cross_fill" ); case Circle: - return "circle"; + return QStringLiteral( "circle" ); case Cross: - return "cross"; + return QStringLiteral( "cross" ); case Cross2: - return "cross2"; + return QStringLiteral( "cross2" ); case Line: - return "line"; + return QStringLiteral( "line" ); case ArrowHead: - return "arrowhead"; + return QStringLiteral( "arrowhead" ); case SemiCircle: - return "semi_circle"; + return QStringLiteral( "semi_circle" ); case ThirdCircle: - return "third_circle"; + return QStringLiteral( "third_circle" ); case QuarterCircle: - return "quarter_circle"; + return QStringLiteral( "quarter_circle" ); } return QString(); } @@ -702,84 +702,84 @@ QgsSymbolLayer* QgsSimpleMarkerSymbolLayer::create( const QgsStringMap& props ) double angle = DEFAULT_SIMPLEMARKER_ANGLE; QgsSymbol::ScaleMethod scaleMethod = DEFAULT_SCALE_METHOD; - if ( props.contains( "name" ) ) + if ( props.contains( QStringLiteral( "name" ) ) ) { - shape = decodeShape( props["name"] ); + shape = decodeShape( props[QStringLiteral( "name" )] ); } - if ( props.contains( "color" ) ) - color = QgsSymbolLayerUtils::decodeColor( props["color"] ); - if ( props.contains( "color_border" ) ) + if ( props.contains( QStringLiteral( "color" ) ) ) + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ); + if ( props.contains( QStringLiteral( "color_border" ) ) ) { //pre 2.5 projects use "color_border" - borderColor = QgsSymbolLayerUtils::decodeColor( props["color_border"] ); + borderColor = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color_border" )] ); } - else if ( props.contains( "outline_color" ) ) + else if ( props.contains( QStringLiteral( "outline_color" ) ) ) { - borderColor = QgsSymbolLayerUtils::decodeColor( props["outline_color"] ); + borderColor = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "outline_color" )] ); } - else if ( props.contains( "line_color" ) ) + else if ( props.contains( QStringLiteral( "line_color" ) ) ) { - borderColor = QgsSymbolLayerUtils::decodeColor( props["line_color"] ); + borderColor = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "line_color" )] ); } - if ( props.contains( "joinstyle" ) ) + if ( props.contains( QStringLiteral( "joinstyle" ) ) ) { - penJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( props["joinstyle"] ); + penJoinStyle = QgsSymbolLayerUtils::decodePenJoinStyle( props[QStringLiteral( "joinstyle" )] ); } - if ( props.contains( "size" ) ) - size = props["size"].toDouble(); - if ( props.contains( "angle" ) ) - angle = props["angle"].toDouble(); - if ( props.contains( "scale_method" ) ) - scaleMethod = QgsSymbolLayerUtils::decodeScaleMethod( props["scale_method"] ); + if ( props.contains( QStringLiteral( "size" ) ) ) + size = props[QStringLiteral( "size" )].toDouble(); + if ( props.contains( QStringLiteral( "angle" ) ) ) + angle = props[QStringLiteral( "angle" )].toDouble(); + if ( props.contains( QStringLiteral( "scale_method" ) ) ) + scaleMethod = QgsSymbolLayerUtils::decodeScaleMethod( props[QStringLiteral( "scale_method" )] ); QgsSimpleMarkerSymbolLayer* m = new QgsSimpleMarkerSymbolLayer( shape, size, angle, scaleMethod, color, borderColor, penJoinStyle ); - if ( props.contains( "offset" ) ) - m->setOffset( QgsSymbolLayerUtils::decodePoint( props["offset"] ) ); - if ( props.contains( "offset_unit" ) ) - m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); - if ( props.contains( "size_unit" ) ) - m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props["size_unit"] ) ); - if ( props.contains( "size_map_unit_scale" ) ) - m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["size_map_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + m->setOffset( QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "size_unit" ) ) ) + m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "size_unit" )] ) ); + if ( props.contains( QStringLiteral( "size_map_unit_scale" ) ) ) + m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "size_map_unit_scale" )] ) ); - if ( props.contains( "outline_style" ) ) + if ( props.contains( QStringLiteral( "outline_style" ) ) ) { - m->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( props["outline_style"] ) ); + m->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "outline_style" )] ) ); } - else if ( props.contains( "line_style" ) ) + else if ( props.contains( QStringLiteral( "line_style" ) ) ) { - m->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( props["line_style"] ) ); + m->setOutlineStyle( QgsSymbolLayerUtils::decodePenStyle( props[QStringLiteral( "line_style" )] ) ); } - if ( props.contains( "outline_width" ) ) + if ( props.contains( QStringLiteral( "outline_width" ) ) ) { - m->setOutlineWidth( props["outline_width"].toDouble() ); + m->setOutlineWidth( props[QStringLiteral( "outline_width" )].toDouble() ); } - else if ( props.contains( "line_width" ) ) + else if ( props.contains( QStringLiteral( "line_width" ) ) ) { - m->setOutlineWidth( props["line_width"].toDouble() ); + m->setOutlineWidth( props[QStringLiteral( "line_width" )].toDouble() ); } - if ( props.contains( "outline_width_unit" ) ) + if ( props.contains( QStringLiteral( "outline_width_unit" ) ) ) { - m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props["outline_width_unit"] ) ); + m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "outline_width_unit" )] ) ); } - if ( props.contains( "line_width_unit" ) ) + if ( props.contains( QStringLiteral( "line_width_unit" ) ) ) { - m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props["line_width_unit"] ) ); + m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "line_width_unit" )] ) ); } - if ( props.contains( "outline_width_map_unit_scale" ) ) + if ( props.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) { - m->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["outline_width_map_unit_scale"] ) ); + m->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "outline_width_map_unit_scale" )] ) ); } - if ( props.contains( "horizontal_anchor_point" ) ) + if ( props.contains( QStringLiteral( "horizontal_anchor_point" ) ) ) { - m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ "horizontal_anchor_point" ].toInt() ) ); + m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ QStringLiteral( "horizontal_anchor_point" )].toInt() ) ); } - if ( props.contains( "vertical_anchor_point" ) ) + if ( props.contains( QStringLiteral( "vertical_anchor_point" ) ) ) { - m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ "vertical_anchor_point" ].toInt() ) ); + m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ QStringLiteral( "vertical_anchor_point" )].toInt() ) ); } m->restoreDataDefinedProperties( props ); @@ -790,7 +790,7 @@ QgsSymbolLayer* QgsSimpleMarkerSymbolLayer::create( const QgsStringMap& props ) QString QgsSimpleMarkerSymbolLayer::layerType() const { - return "SimpleMarker"; + return QStringLiteral( "SimpleMarker" ); } void QgsSimpleMarkerSymbolLayer::startRender( QgsSymbolRenderContext& context ) @@ -1040,24 +1040,24 @@ void QgsSimpleMarkerSymbolLayer::renderPoint( QPointF point, QgsSymbolRenderCont QgsStringMap QgsSimpleMarkerSymbolLayer::properties() const { QgsStringMap map; - map["name"] = encodeShape( mShape ); - map["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["outline_color"] = QgsSymbolLayerUtils::encodeColor( mBorderColor ); - map["size"] = QString::number( mSize ); - map["size_unit"] = QgsUnitTypes::encodeUnit( mSizeUnit ); - map["size_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); - map["angle"] = QString::number( mAngle ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["scale_method"] = QgsSymbolLayerUtils::encodeScaleMethod( mScaleMethod ); - map["outline_style"] = QgsSymbolLayerUtils::encodePenStyle( mOutlineStyle ); - map["outline_width"] = QString::number( mOutlineWidth ); - map["outline_width_unit"] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); - map["outline_width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); - map["joinstyle"] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); - map["horizontal_anchor_point"] = QString::number( mHorizontalAnchorPoint ); - map["vertical_anchor_point"] = QString::number( mVerticalAnchorPoint ); + map[QStringLiteral( "name" )] = encodeShape( mShape ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "outline_color" )] = QgsSymbolLayerUtils::encodeColor( mBorderColor ); + map[QStringLiteral( "size" )] = QString::number( mSize ); + map[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit ); + map[QStringLiteral( "size_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); + map[QStringLiteral( "angle" )] = QString::number( mAngle ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "scale_method" )] = QgsSymbolLayerUtils::encodeScaleMethod( mScaleMethod ); + map[QStringLiteral( "outline_style" )] = QgsSymbolLayerUtils::encodePenStyle( mOutlineStyle ); + map[QStringLiteral( "outline_width" )] = QString::number( mOutlineWidth ); + map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); + map[QStringLiteral( "outline_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); + map[QStringLiteral( "joinstyle" )] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); + map[QStringLiteral( "horizontal_anchor_point" )] = QString::number( mHorizontalAnchorPoint ); + map[QStringLiteral( "vertical_anchor_point" )] = QString::number( mVerticalAnchorPoint ); //data define properties @@ -1087,7 +1087,7 @@ QgsSimpleMarkerSymbolLayer* QgsSimpleMarkerSymbolLayer::clone() const void QgsSimpleMarkerSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { // <Graphic> - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); element.appendChild( graphicElem ); double outlineWidth = QgsSymbolLayerUtils::rescaleUom( mOutlineWidth, mOutlineWidthUnit, props ); @@ -1097,10 +1097,10 @@ void QgsSimpleMarkerSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement // <Rotation> QString angleFunc; bool ok; - double angle = props.value( "angle", "0" ).toDouble( &ok ); + double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok ); if ( !ok ) { - angleFunc = QString( "%1 + %2" ).arg( props.value( "angle", "0" ) ).arg( mAngle ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ) ).arg( mAngle ); } else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) ) { @@ -1179,11 +1179,11 @@ QgsSymbolLayer* QgsSimpleMarkerSymbolLayer::createFromSld( QDomElement &element { QgsDebugMsg( "Entered." ); - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return nullptr; - QString name = "square"; + QString name = QStringLiteral( "square" ); QColor color, borderColor; double borderWidth, size; Qt::PenStyle borderStyle; @@ -1354,16 +1354,16 @@ bool QgsSimpleMarkerSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScal p << p[0]; if ( mBrush.style() != Qt::NoBrush ) - e.writePolygon( QgsRingSequence() << p, layerName, "SOLID", bc ); + e.writePolygon( QgsRingSequence() << p, layerName, QStringLiteral( "SOLID" ), bc ); if ( mPen.style() != Qt::NoPen ) - e.writePolyline( p, layerName, "CONTINUOUS", pc, outlineWidth ); + e.writePolyline( p, layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); } else if ( shape == Circle ) { if ( mBrush.style() != Qt::NoBrush ) e.writeFilledCircle( layerName, bc, QgsPointV2( shift ), halfSize ); if ( mPen.style() != Qt::NoPen ) - e.writeCircle( layerName, pc, QgsPointV2( shift ), halfSize, "CONTINUOUS", outlineWidth ); + e.writeCircle( layerName, pc, QgsPointV2( shift ), halfSize, QStringLiteral( "CONTINUOUS" ), outlineWidth ); } else if ( shape == Line ) { @@ -1371,7 +1371,7 @@ bool QgsSimpleMarkerSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScal QPointF pt2 = t.map( QPointF( 0, halfSize ) ); if ( mPen.style() != Qt::NoPen ) - e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, "CONTINUOUS", pc, outlineWidth ); + e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); } else if ( shape == Cross ) { @@ -1382,8 +1382,8 @@ bool QgsSimpleMarkerSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScal QPointF pt3 = t.map( QPointF( 0, -halfSize ) ); QPointF pt4 = t.map( QPointF( 0, halfSize ) ); - e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, "CONTINUOUS", pc, outlineWidth ); - e.writeLine( QgsPointV2( pt3 ), QgsPointV2( pt4 ), layerName, "CONTINUOUS", pc, outlineWidth ); + e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); + e.writeLine( QgsPointV2( pt3 ), QgsPointV2( pt4 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); } } else if ( shape == Cross2 ) @@ -1395,8 +1395,8 @@ bool QgsSimpleMarkerSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScal QPointF pt3 = t.map( QPointF( halfSize, -halfSize ) ); QPointF pt4 = t.map( QPointF( -halfSize, halfSize ) ); - e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, "CONTINUOUS", pc, outlineWidth ); - e.writeLine( QgsPointV2( pt3 ), QgsPointV2( pt4 ), layerName, "CONTINUOUS", pc, outlineWidth ); + e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); + e.writeLine( QgsPointV2( pt3 ), QgsPointV2( pt4 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); } } else if ( shape == ArrowHead ) @@ -1407,8 +1407,8 @@ bool QgsSimpleMarkerSymbolLayer::writeDxf( QgsDxfExport& e, double mmMapUnitScal QPointF pt2 = t.map( QPointF( 0, 0 ) ); QPointF pt3 = t.map( QPointF( -halfSize, -halfSize ) ); - e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, "CONTINUOUS", pc, outlineWidth ); - e.writeLine( QgsPointV2( pt3 ), QgsPointV2( pt2 ), layerName, "CONTINUOUS", pc, outlineWidth ); + e.writeLine( QgsPointV2( pt1 ), QgsPointV2( pt2 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); + e.writeLine( QgsPointV2( pt3 ), QgsPointV2( pt2 ), layerName, QStringLiteral( "CONTINUOUS" ), pc, outlineWidth ); } } else @@ -1472,7 +1472,7 @@ QRectF QgsSimpleMarkerSymbolLayer::bounds( QPointF point, QgsSymbolRenderContext { context.setOriginalValueVariable( QgsSymbolLayerUtils::encodePenStyle( mOutlineStyle ) ); QString outlineStyle = evaluateDataDefinedProperty( QgsSymbolLayer::EXPR_OUTLINE_STYLE, context, QVariant(), &ok ).toString(); - if ( ok && outlineStyle == "no" ) + if ( ok && outlineStyle == QLatin1String( "no" ) ) { penWidth = 0.0; } @@ -1531,33 +1531,33 @@ QgsSymbolLayer *QgsFilledMarkerSymbolLayer::create( const QgsStringMap &props ) double angle = DEFAULT_SIMPLEMARKER_ANGLE; QgsSymbol::ScaleMethod scaleMethod = DEFAULT_SCALE_METHOD; - if ( props.contains( "name" ) ) - name = props["name"]; - if ( props.contains( "size" ) ) - size = props["size"].toDouble(); - if ( props.contains( "angle" ) ) - angle = props["angle"].toDouble(); - if ( props.contains( "scale_method" ) ) - scaleMethod = QgsSymbolLayerUtils::decodeScaleMethod( props["scale_method"] ); + if ( props.contains( QStringLiteral( "name" ) ) ) + name = props[QStringLiteral( "name" )]; + if ( props.contains( QStringLiteral( "size" ) ) ) + size = props[QStringLiteral( "size" )].toDouble(); + if ( props.contains( QStringLiteral( "angle" ) ) ) + angle = props[QStringLiteral( "angle" )].toDouble(); + if ( props.contains( QStringLiteral( "scale_method" ) ) ) + scaleMethod = QgsSymbolLayerUtils::decodeScaleMethod( props[QStringLiteral( "scale_method" )] ); QgsFilledMarkerSymbolLayer* m = new QgsFilledMarkerSymbolLayer( decodeShape( name ), size, angle, scaleMethod ); - if ( props.contains( "offset" ) ) - m->setOffset( QgsSymbolLayerUtils::decodePoint( props["offset"] ) ); - if ( props.contains( "offset_unit" ) ) - m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); - if ( props.contains( "size_unit" ) ) - m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props["size_unit"] ) ); - if ( props.contains( "size_map_unit_scale" ) ) - m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["size_map_unit_scale"] ) ); - if ( props.contains( "horizontal_anchor_point" ) ) + if ( props.contains( QStringLiteral( "offset" ) ) ) + m->setOffset( QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "size_unit" ) ) ) + m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "size_unit" )] ) ); + if ( props.contains( QStringLiteral( "size_map_unit_scale" ) ) ) + m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "size_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "horizontal_anchor_point" ) ) ) { - m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ "horizontal_anchor_point" ].toInt() ) ); + m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ QStringLiteral( "horizontal_anchor_point" )].toInt() ) ); } - if ( props.contains( "vertical_anchor_point" ) ) + if ( props.contains( QStringLiteral( "vertical_anchor_point" ) ) ) { - m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ "vertical_anchor_point" ].toInt() ) ); + m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ QStringLiteral( "vertical_anchor_point" )].toInt() ) ); } m->setSubSymbol( QgsFillSymbol::createSimple( props ) ); @@ -1569,7 +1569,7 @@ QgsSymbolLayer *QgsFilledMarkerSymbolLayer::create( const QgsStringMap &props ) QString QgsFilledMarkerSymbolLayer::layerType() const { - return "FilledMarker"; + return QStringLiteral( "FilledMarker" ); } void QgsFilledMarkerSymbolLayer::startRender( QgsSymbolRenderContext &context ) @@ -1593,21 +1593,21 @@ void QgsFilledMarkerSymbolLayer::stopRender( QgsSymbolRenderContext& context ) QgsStringMap QgsFilledMarkerSymbolLayer::properties() const { QgsStringMap map; - map["name"] = encodeShape( mShape ); - map["size"] = QString::number( mSize ); - map["size_unit"] = QgsUnitTypes::encodeUnit( mSizeUnit ); - map["size_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); - map["angle"] = QString::number( mAngle ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["scale_method"] = QgsSymbolLayerUtils::encodeScaleMethod( mScaleMethod ); - map["horizontal_anchor_point"] = QString::number( mHorizontalAnchorPoint ); - map["vertical_anchor_point"] = QString::number( mVerticalAnchorPoint ); + map[QStringLiteral( "name" )] = encodeShape( mShape ); + map[QStringLiteral( "size" )] = QString::number( mSize ); + map[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit ); + map[QStringLiteral( "size_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); + map[QStringLiteral( "angle" )] = QString::number( mAngle ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "scale_method" )] = QgsSymbolLayerUtils::encodeScaleMethod( mScaleMethod ); + map[QStringLiteral( "horizontal_anchor_point" )] = QString::number( mHorizontalAnchorPoint ); + map[QStringLiteral( "vertical_anchor_point" )] = QString::number( mVerticalAnchorPoint ); if ( mFill.data() ) { - map["color"] = QgsSymbolLayerUtils::encodeColor( mFill->color() ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mFill->color() ); } //data define properties @@ -1730,20 +1730,20 @@ QgsSymbolLayer* QgsSvgMarkerSymbolLayer::create( const QgsStringMap& props ) double angle = DEFAULT_SVGMARKER_ANGLE; QgsSymbol::ScaleMethod scaleMethod = DEFAULT_SCALE_METHOD; - if ( props.contains( "name" ) ) - name = props["name"]; - if ( props.contains( "size" ) ) - size = props["size"].toDouble(); - if ( props.contains( "angle" ) ) - angle = props["angle"].toDouble(); - if ( props.contains( "scale_method" ) ) - scaleMethod = QgsSymbolLayerUtils::decodeScaleMethod( props["scale_method"] ); + if ( props.contains( QStringLiteral( "name" ) ) ) + name = props[QStringLiteral( "name" )]; + if ( props.contains( QStringLiteral( "size" ) ) ) + size = props[QStringLiteral( "size" )].toDouble(); + if ( props.contains( QStringLiteral( "angle" ) ) ) + angle = props[QStringLiteral( "angle" )].toDouble(); + if ( props.contains( QStringLiteral( "scale_method" ) ) ) + scaleMethod = QgsSymbolLayerUtils::decodeScaleMethod( props[QStringLiteral( "scale_method" )] ); QgsSvgMarkerSymbolLayer* m = new QgsSvgMarkerSymbolLayer( name, size, angle, scaleMethod ); //we only check the svg default parameters if necessary, since it could be expensive - if ( !props.contains( "fill" ) && !props.contains( "color" ) && !props.contains( "outline" ) && - !props.contains( "outline_color" ) && !props.contains( "outline-width" ) && !props.contains( "outline_width" ) ) + if ( !props.contains( QStringLiteral( "fill" ) ) && !props.contains( QStringLiteral( "color" ) ) && !props.contains( QStringLiteral( "outline" ) ) && + !props.contains( QStringLiteral( "outline_color" ) ) && !props.contains( QStringLiteral( "outline-width" ) ) && !props.contains( QStringLiteral( "outline_width" ) ) ) { QColor fillColor, outlineColor; double fillOpacity = 1.0; @@ -1782,71 +1782,71 @@ QgsSymbolLayer* QgsSvgMarkerSymbolLayer::create( const QgsStringMap& props ) } } - if ( props.contains( "size_unit" ) ) - m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props["size_unit"] ) ); - if ( props.contains( "size_map_unit_scale" ) ) - m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["size_map_unit_scale"] ) ); - if ( props.contains( "offset" ) ) - m->setOffset( QgsSymbolLayerUtils::decodePoint( props["offset"] ) ); - if ( props.contains( "offset_unit" ) ) - m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit"] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale"] ) ); - if ( props.contains( "fill" ) ) + if ( props.contains( QStringLiteral( "size_unit" ) ) ) + m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "size_unit" )] ) ); + if ( props.contains( QStringLiteral( "size_map_unit_scale" ) ) ) + m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "size_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + m->setOffset( QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "fill" ) ) ) { //pre 2.5 projects used "fill" - m->setFillColor( QgsSymbolLayerUtils::decodeColor( props["fill"] ) ); + m->setFillColor( QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "fill" )] ) ); } - else if ( props.contains( "color" ) ) + else if ( props.contains( QStringLiteral( "color" ) ) ) { - m->setFillColor( QgsSymbolLayerUtils::decodeColor( props["color"] ) ); + m->setFillColor( QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ) ); } - if ( props.contains( "outline" ) ) + if ( props.contains( QStringLiteral( "outline" ) ) ) { //pre 2.5 projects used "outline" - m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props["outline"] ) ); + m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "outline" )] ) ); } - else if ( props.contains( "outline_color" ) ) + else if ( props.contains( QStringLiteral( "outline_color" ) ) ) { - m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props["outline_color"] ) ); + m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "outline_color" )] ) ); } - else if ( props.contains( "line_color" ) ) + else if ( props.contains( QStringLiteral( "line_color" ) ) ) { - m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props["line_color"] ) ); + m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "line_color" )] ) ); } - if ( props.contains( "outline-width" ) ) + if ( props.contains( QStringLiteral( "outline-width" ) ) ) { //pre 2.5 projects used "outline-width" - m->setOutlineWidth( props["outline-width"].toDouble() ); + m->setOutlineWidth( props[QStringLiteral( "outline-width" )].toDouble() ); } - else if ( props.contains( "outline_width" ) ) + else if ( props.contains( QStringLiteral( "outline_width" ) ) ) { - m->setOutlineWidth( props["outline_width"].toDouble() ); + m->setOutlineWidth( props[QStringLiteral( "outline_width" )].toDouble() ); } - else if ( props.contains( "line_width" ) ) + else if ( props.contains( QStringLiteral( "line_width" ) ) ) { - m->setOutlineWidth( props["line_width"].toDouble() ); + m->setOutlineWidth( props[QStringLiteral( "line_width" )].toDouble() ); } - if ( props.contains( "outline_width_unit" ) ) + if ( props.contains( QStringLiteral( "outline_width_unit" ) ) ) { - m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props["outline_width_unit"] ) ); + m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "outline_width_unit" )] ) ); } - else if ( props.contains( "line_width_unit" ) ) + else if ( props.contains( QStringLiteral( "line_width_unit" ) ) ) { - m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props["line_width_unit"] ) ); + m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "line_width_unit" )] ) ); } - if ( props.contains( "outline_width_map_unit_scale" ) ) - m->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["outline_width_map_unit_scale"] ) ); + if ( props.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) + m->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "outline_width_map_unit_scale" )] ) ); - if ( props.contains( "horizontal_anchor_point" ) ) + if ( props.contains( QStringLiteral( "horizontal_anchor_point" ) ) ) { - m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ "horizontal_anchor_point" ].toInt() ) ); + m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ QStringLiteral( "horizontal_anchor_point" )].toInt() ) ); } - if ( props.contains( "vertical_anchor_point" ) ) + if ( props.contains( QStringLiteral( "vertical_anchor_point" ) ) ) { - m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ "vertical_anchor_point" ].toInt() ) ); + m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ QStringLiteral( "vertical_anchor_point" )].toInt() ) ); } m->restoreDataDefinedProperties( props ); @@ -1901,7 +1901,7 @@ void QgsSvgMarkerSymbolLayer::setPath( const QString& path ) QString QgsSvgMarkerSymbolLayer::layerType() const { - return "SvgMarker"; + return QStringLiteral( "SvgMarker" ); } void QgsSvgMarkerSymbolLayer::startRender( QgsSymbolRenderContext& context ) @@ -2116,22 +2116,22 @@ void QgsSvgMarkerSymbolLayer::calculateOffsetAndRotation( QgsSymbolRenderContext QgsStringMap QgsSvgMarkerSymbolLayer::properties() const { QgsStringMap map; - map["name"] = QgsSymbolLayerUtils::symbolPathToName( mPath ); - map["size"] = QString::number( mSize ); - map["size_unit"] = QgsUnitTypes::encodeUnit( mSizeUnit ); - map["size_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); - map["angle"] = QString::number( mAngle ); - map["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - map["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - map["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - map["scale_method"] = QgsSymbolLayerUtils::encodeScaleMethod( mScaleMethod ); - map["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - map["outline_color"] = QgsSymbolLayerUtils::encodeColor( mOutlineColor ); - map["outline_width"] = QString::number( mOutlineWidth ); - map["outline_width_unit"] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); - map["outline_width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); - map["horizontal_anchor_point"] = QString::number( mHorizontalAnchorPoint ); - map["vertical_anchor_point"] = QString::number( mVerticalAnchorPoint ); + map[QStringLiteral( "name" )] = QgsSymbolLayerUtils::symbolPathToName( mPath ); + map[QStringLiteral( "size" )] = QString::number( mSize ); + map[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit ); + map[QStringLiteral( "size_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); + map[QStringLiteral( "angle" )] = QString::number( mAngle ); + map[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + map[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + map[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + map[QStringLiteral( "scale_method" )] = QgsSymbolLayerUtils::encodeScaleMethod( mScaleMethod ); + map[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + map[QStringLiteral( "outline_color" )] = QgsSymbolLayerUtils::encodeColor( mOutlineColor ); + map[QStringLiteral( "outline_width" )] = QString::number( mOutlineWidth ); + map[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); + map[QStringLiteral( "outline_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); + map[QStringLiteral( "horizontal_anchor_point" )] = QString::number( mHorizontalAnchorPoint ); + map[QStringLiteral( "vertical_anchor_point" )] = QString::number( mVerticalAnchorPoint ); saveDataDefinedProperties( map ); return map; @@ -2191,19 +2191,19 @@ QgsMapUnitScale QgsSvgMarkerSymbolLayer::mapUnitScale() const void QgsSvgMarkerSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { // <Graphic> - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); element.appendChild( graphicElem ); double size = QgsSymbolLayerUtils::rescaleUom( mSize, mSizeUnit, props ); - QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, mPath, "image/svg+xml", mColor, size ); + QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, mPath, QStringLiteral( "image/svg+xml" ), mColor, size ); // <Rotation> QString angleFunc; bool ok; - double angle = props.value( "angle", "0" ).toDouble( &ok ); + double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok ); if ( !ok ) { - angleFunc = QString( "%1 + %2" ).arg( props.value( "angle", "0" ) ).arg( mAngle ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ) ).arg( mAngle ); } else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) ) { @@ -2221,7 +2221,7 @@ QgsSymbolLayer* QgsSvgMarkerSymbolLayer::createFromSld( QDomElement &element ) { QgsDebugMsg( "Entered." ); - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return nullptr; @@ -2232,7 +2232,7 @@ QgsSymbolLayer* QgsSvgMarkerSymbolLayer::createFromSld( QDomElement &element ) if ( !QgsSymbolLayerUtils::externalGraphicFromSld( graphicElem, path, mimeType, fillColor, size ) ) return nullptr; - if ( mimeType != "image/svg+xml" ) + if ( mimeType != QLatin1String( "image/svg+xml" ) ) return nullptr; double angle = 0.0; @@ -2504,43 +2504,43 @@ QgsSymbolLayer* QgsFontMarkerSymbolLayer::create( const QgsStringMap& props ) QColor color = DEFAULT_FONTMARKER_COLOR; double angle = DEFAULT_FONTMARKER_ANGLE; - if ( props.contains( "font" ) ) - fontFamily = props["font"]; - if ( props.contains( "chr" ) && props["chr"].length() > 0 ) - chr = props["chr"].at( 0 ); - if ( props.contains( "size" ) ) - pointSize = props["size"].toDouble(); - if ( props.contains( "color" ) ) - color = QgsSymbolLayerUtils::decodeColor( props["color"] ); - if ( props.contains( "angle" ) ) - angle = props["angle"].toDouble(); + if ( props.contains( QStringLiteral( "font" ) ) ) + fontFamily = props[QStringLiteral( "font" )]; + if ( props.contains( QStringLiteral( "chr" ) ) && props[QStringLiteral( "chr" )].length() > 0 ) + chr = props[QStringLiteral( "chr" )].at( 0 ); + if ( props.contains( QStringLiteral( "size" ) ) ) + pointSize = props[QStringLiteral( "size" )].toDouble(); + if ( props.contains( QStringLiteral( "color" ) ) ) + color = QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "color" )] ); + if ( props.contains( QStringLiteral( "angle" ) ) ) + angle = props[QStringLiteral( "angle" )].toDouble(); QgsFontMarkerSymbolLayer* m = new QgsFontMarkerSymbolLayer( fontFamily, chr, pointSize, color, angle ); - if ( props.contains( "outline_color" ) ) - m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props["outline_color"] ) ); - if ( props.contains( "outline_width" ) ) - m->setOutlineWidth( props["outline_width"].toDouble() ); - if ( props.contains( "offset" ) ) - m->setOffset( QgsSymbolLayerUtils::decodePoint( props["offset"] ) ); - if ( props.contains( "offset_unit" ) ) - m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props["offset_unit" ] ) ); - if ( props.contains( "offset_map_unit_scale" ) ) - m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["offset_map_unit_scale" ] ) ); - if ( props.contains( "size_unit" ) ) - m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props["size_unit"] ) ); - if ( props.contains( "size_map_unit_scale" ) ) - m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["size_map_unit_scale"] ) ); - if ( props.contains( "outline_width_unit" ) ) - m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props["outline_width_unit"] ) ); - if ( props.contains( "outline_width_map_unit_scale" ) ) - m->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props["outline_width_map_unit_scale"] ) ); - if ( props.contains( "joinstyle" ) ) - m->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( props["joinstyle"] ) ); - if ( props.contains( "horizontal_anchor_point" ) ) - m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ "horizontal_anchor_point" ].toInt() ) ); - if ( props.contains( "vertical_anchor_point" ) ) - m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ "vertical_anchor_point" ].toInt() ) ); + if ( props.contains( QStringLiteral( "outline_color" ) ) ) + m->setOutlineColor( QgsSymbolLayerUtils::decodeColor( props[QStringLiteral( "outline_color" )] ) ); + if ( props.contains( QStringLiteral( "outline_width" ) ) ) + m->setOutlineWidth( props[QStringLiteral( "outline_width" )].toDouble() ); + if ( props.contains( QStringLiteral( "offset" ) ) ) + m->setOffset( QgsSymbolLayerUtils::decodePoint( props[QStringLiteral( "offset" )] ) ); + if ( props.contains( QStringLiteral( "offset_unit" ) ) ) + m->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "offset_unit" )] ) ); + if ( props.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) + m->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "offset_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "size_unit" ) ) ) + m->setSizeUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "size_unit" )] ) ); + if ( props.contains( QStringLiteral( "size_map_unit_scale" ) ) ) + m->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "size_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "outline_width_unit" ) ) ) + m->setOutlineWidthUnit( QgsUnitTypes::decodeRenderUnit( props[QStringLiteral( "outline_width_unit" )] ) ); + if ( props.contains( QStringLiteral( "outline_width_map_unit_scale" ) ) ) + m->setOutlineWidthMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( props[QStringLiteral( "outline_width_map_unit_scale" )] ) ); + if ( props.contains( QStringLiteral( "joinstyle" ) ) ) + m->setPenJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( props[QStringLiteral( "joinstyle" )] ) ); + if ( props.contains( QStringLiteral( "horizontal_anchor_point" ) ) ) + m->setHorizontalAnchorPoint( QgsMarkerSymbolLayer::HorizontalAnchorPoint( props[ QStringLiteral( "horizontal_anchor_point" )].toInt() ) ); + if ( props.contains( QStringLiteral( "vertical_anchor_point" ) ) ) + m->setVerticalAnchorPoint( QgsMarkerSymbolLayer::VerticalAnchorPoint( props[ QStringLiteral( "vertical_anchor_point" )].toInt() ) ); m->restoreDataDefinedProperties( props ); @@ -2549,7 +2549,7 @@ QgsSymbolLayer* QgsFontMarkerSymbolLayer::create( const QgsStringMap& props ) QString QgsFontMarkerSymbolLayer::layerType() const { - return "FontMarker"; + return QStringLiteral( "FontMarker" ); } void QgsFontMarkerSymbolLayer::startRender( QgsSymbolRenderContext& context ) @@ -2764,23 +2764,23 @@ void QgsFontMarkerSymbolLayer::renderPoint( QPointF point, QgsSymbolRenderContex QgsStringMap QgsFontMarkerSymbolLayer::properties() const { QgsStringMap props; - props["font"] = mFontFamily; - props["chr"] = mChr; - props["size"] = QString::number( mSize ); - props["size_unit"] = QgsUnitTypes::encodeUnit( mSizeUnit ); - props["size_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); - props["color"] = QgsSymbolLayerUtils::encodeColor( mColor ); - props["outline_color"] = QgsSymbolLayerUtils::encodeColor( mOutlineColor ); - props["outline_width"] = QString::number( mOutlineWidth ); - props["outline_width_unit"] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); - props["outline_width_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); - props["joinstyle"] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); - props["angle"] = QString::number( mAngle ); - props["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - props["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - props["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); - props["horizontal_anchor_point"] = QString::number( mHorizontalAnchorPoint ); - props["vertical_anchor_point"] = QString::number( mVerticalAnchorPoint ); + props[QStringLiteral( "font" )] = mFontFamily; + props[QStringLiteral( "chr" )] = mChr; + props[QStringLiteral( "size" )] = QString::number( mSize ); + props[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit ); + props[QStringLiteral( "size_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); + props[QStringLiteral( "color" )] = QgsSymbolLayerUtils::encodeColor( mColor ); + props[QStringLiteral( "outline_color" )] = QgsSymbolLayerUtils::encodeColor( mOutlineColor ); + props[QStringLiteral( "outline_width" )] = QString::number( mOutlineWidth ); + props[QStringLiteral( "outline_width_unit" )] = QgsUnitTypes::encodeUnit( mOutlineWidthUnit ); + props[QStringLiteral( "outline_width_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOutlineWidthMapUnitScale ); + props[QStringLiteral( "joinstyle" )] = QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ); + props[QStringLiteral( "angle" )] = QString::number( mAngle ); + props[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + props[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + props[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + props[QStringLiteral( "horizontal_anchor_point" )] = QString::number( mHorizontalAnchorPoint ); + props[QStringLiteral( "vertical_anchor_point" )] = QString::number( mVerticalAnchorPoint ); //data define properties saveDataDefinedProperties( props ); @@ -2811,21 +2811,21 @@ QgsFontMarkerSymbolLayer* QgsFontMarkerSymbolLayer::clone() const void QgsFontMarkerSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { // <Graphic> - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); element.appendChild( graphicElem ); - QString fontPath = QString( "ttf://%1" ).arg( mFontFamily ); + QString fontPath = QStringLiteral( "ttf://%1" ).arg( mFontFamily ); int markIndex = mChr.unicode(); double size = QgsSymbolLayerUtils::rescaleUom( mSize, mSizeUnit, props ); - QgsSymbolLayerUtils::externalMarkerToSld( doc, graphicElem, fontPath, "ttf", &markIndex, mColor, size ); + QgsSymbolLayerUtils::externalMarkerToSld( doc, graphicElem, fontPath, QStringLiteral( "ttf" ), &markIndex, mColor, size ); // <Rotation> QString angleFunc; bool ok; - double angle = props.value( "angle", "0" ).toDouble( &ok ); + double angle = props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ).toDouble( &ok ); if ( !ok ) { - angleFunc = QString( "%1 + %2" ).arg( props.value( "angle", "0" ) ).arg( mAngle ); + angleFunc = QStringLiteral( "%1 + %2" ).arg( props.value( QStringLiteral( "angle" ), QStringLiteral( "0" ) ) ).arg( mAngle ); } else if ( !qgsDoubleNear( angle + mAngle, 0.0 ) ) { @@ -2879,7 +2879,7 @@ QgsSymbolLayer* QgsFontMarkerSymbolLayer::createFromSld( QDomElement &element ) { QgsDebugMsg( "Entered." ); - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return nullptr; @@ -2891,7 +2891,7 @@ QgsSymbolLayer* QgsFontMarkerSymbolLayer::createFromSld( QDomElement &element ) if ( !QgsSymbolLayerUtils::externalMarkerFromSld( graphicElem, name, format, chr, color, size ) ) return nullptr; - if ( !name.startsWith( "ttf://" ) || format != "ttf" ) + if ( !name.startsWith( QLatin1String( "ttf://" ) ) || format != QLatin1String( "ttf" ) ) return nullptr; QString fontFamily = name.mid( 6 ); diff --git a/src/core/symbology-ng/qgsnullsymbolrenderer.cpp b/src/core/symbology-ng/qgsnullsymbolrenderer.cpp index 5dabae674490..15a1496dd3f4 100644 --- a/src/core/symbology-ng/qgsnullsymbolrenderer.cpp +++ b/src/core/symbology-ng/qgsnullsymbolrenderer.cpp @@ -21,7 +21,7 @@ #include <QDomElement> QgsNullSymbolRenderer::QgsNullSymbolRenderer() - : QgsFeatureRenderer( "nullSymbol" ) + : QgsFeatureRenderer( QStringLiteral( "nullSymbol" ) ) { } @@ -91,7 +91,7 @@ QSet<QString> QgsNullSymbolRenderer::usedAttributes() const QString QgsNullSymbolRenderer::dump() const { - return QString( "NULL" ); + return QStringLiteral( "NULL" ); } QgsFeatureRenderer* QgsNullSymbolRenderer::clone() const @@ -115,7 +115,7 @@ QgsFeatureRenderer* QgsNullSymbolRenderer::create( QDomElement& element ) QDomElement QgsNullSymbolRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "nullSymbol" ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "nullSymbol" ) ); return rendererElem; } diff --git a/src/core/symbology-ng/qgspointclusterrenderer.cpp b/src/core/symbology-ng/qgspointclusterrenderer.cpp index d0a7f01b03ba..235674c1e17d 100644 --- a/src/core/symbology-ng/qgspointclusterrenderer.cpp +++ b/src/core/symbology-ng/qgspointclusterrenderer.cpp @@ -29,7 +29,7 @@ #endif QgsPointClusterRenderer::QgsPointClusterRenderer() - : QgsPointDistanceRenderer( "pointCluster" ) + : QgsPointDistanceRenderer( QStringLiteral( "pointCluster" ) ) { mClusterSymbol.reset( new QgsMarkerSymbol() ); mClusterSymbol->setSize( 4 ); @@ -40,7 +40,7 @@ QgsPointClusterRenderer::QgsPointClusterRenderer() fm->setColor( QColor( 255, 255, 255 ) ); fm->setSize( 3.2 ); fm->setOffset( QPointF( 0, -0.4 ) ); - fm->setDataDefinedProperty( "char", new QgsDataDefined( true, true, "@cluster_size" ) ); + fm->setDataDefinedProperty( QStringLiteral( "char" ), new QgsDataDefined( true, true, QStringLiteral( "@cluster_size" ) ) ); mClusterSymbol->insertSymbolLayer( 1, fm ); } @@ -98,19 +98,19 @@ void QgsPointClusterRenderer::stopRender( QgsRenderContext& context ) QgsFeatureRenderer* QgsPointClusterRenderer::create( QDomElement& symbologyElem ) { QgsPointClusterRenderer* r = new QgsPointClusterRenderer(); - r->setTolerance( symbologyElem.attribute( "tolerance", "0.00001" ).toDouble() ); - r->setToleranceUnit( QgsUnitTypes::decodeRenderUnit( symbologyElem.attribute( "toleranceUnit", "MapUnit" ) ) ); - r->setToleranceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( symbologyElem.attribute( "toleranceUnitScale" ) ) ); + r->setTolerance( symbologyElem.attribute( QStringLiteral( "tolerance" ), QStringLiteral( "0.00001" ) ).toDouble() ); + r->setToleranceUnit( QgsUnitTypes::decodeRenderUnit( symbologyElem.attribute( QStringLiteral( "toleranceUnit" ), QStringLiteral( "MapUnit" ) ) ) ); + r->setToleranceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( symbologyElem.attribute( QStringLiteral( "toleranceUnitScale" ) ) ) ); //look for an embedded renderer <renderer-v2> - QDomElement embeddedRendererElem = symbologyElem.firstChildElement( "renderer-v2" ); + QDomElement embeddedRendererElem = symbologyElem.firstChildElement( QStringLiteral( "renderer-v2" ) ); if ( !embeddedRendererElem.isNull() ) { r->setEmbeddedRenderer( QgsFeatureRenderer::load( embeddedRendererElem ) ); } //center symbol - QDomElement centerSymbolElem = symbologyElem.firstChildElement( "symbol" ); + QDomElement centerSymbolElem = symbologyElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !centerSymbolElem.isNull() ) { r->setClusterSymbol( QgsSymbolLayerUtils::loadSymbol<QgsMarkerSymbol>( centerSymbolElem ) ); @@ -126,11 +126,11 @@ QgsMarkerSymbol* QgsPointClusterRenderer::clusterSymbol() QDomElement QgsPointClusterRenderer::save( QDomDocument& doc ) { QDomElement rendererElement = doc.createElement( RENDERER_TAG_NAME ); - rendererElement.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); - rendererElement.setAttribute( "type", "pointCluster" ); - rendererElement.setAttribute( "tolerance", QString::number( mTolerance ) ); - rendererElement.setAttribute( "toleranceUnit", QgsUnitTypes::encodeUnit( mToleranceUnit ) ); - rendererElement.setAttribute( "toleranceUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( mToleranceMapUnitScale ) ); + rendererElement.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); + rendererElement.setAttribute( QStringLiteral( "type" ), QStringLiteral( "pointCluster" ) ); + rendererElement.setAttribute( QStringLiteral( "tolerance" ), QString::number( mTolerance ) ); + rendererElement.setAttribute( QStringLiteral( "toleranceUnit" ), QgsUnitTypes::encodeUnit( mToleranceUnit ) ); + rendererElement.setAttribute( QStringLiteral( "toleranceUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mToleranceMapUnitScale ) ); if ( mRenderer ) { @@ -139,7 +139,7 @@ QDomElement QgsPointClusterRenderer::save( QDomDocument& doc ) } if ( mClusterSymbol ) { - QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( "centerSymbol", mClusterSymbol.data(), doc ); + QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "centerSymbol" ), mClusterSymbol.data(), doc ); rendererElement.appendChild( centerSymbolElem ); } @@ -148,11 +148,11 @@ QDomElement QgsPointClusterRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElement.appendChild( orderBy ); } - rendererElement.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElement.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElement; } @@ -172,20 +172,20 @@ void QgsPointClusterRenderer::setClusterSymbol( QgsMarkerSymbol* symbol ) QgsPointClusterRenderer* QgsPointClusterRenderer::convertFromRenderer( const QgsFeatureRenderer* renderer ) { - if ( renderer->type() == "pointCluster" ) + if ( renderer->type() == QLatin1String( "pointCluster" ) ) { return dynamic_cast<QgsPointClusterRenderer*>( renderer->clone() ); } - else if ( renderer->type() == "singleSymbol" || - renderer->type() == "categorizedSymbol" || - renderer->type() == "graduatedSymbol" || - renderer->type() == "RuleRenderer" ) + else if ( renderer->type() == QLatin1String( "singleSymbol" ) || + renderer->type() == QLatin1String( "categorizedSymbol" ) || + renderer->type() == QLatin1String( "graduatedSymbol" ) || + renderer->type() == QLatin1String( "RuleRenderer" ) ) { QgsPointClusterRenderer* pointRenderer = new QgsPointClusterRenderer(); pointRenderer->setEmbeddedRenderer( renderer->clone() ); return pointRenderer; } - else if ( renderer->type() == "pointDisplacement" ) + else if ( renderer->type() == QLatin1String( "pointDisplacement" ) ) { QgsPointClusterRenderer* pointRenderer = new QgsPointClusterRenderer(); const QgsPointDisplacementRenderer* displacementRenderer = static_cast< const QgsPointDisplacementRenderer* >( renderer ); diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp index b189cf5db829..cc4e2da5d89a 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.cpp +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.cpp @@ -30,7 +30,7 @@ #endif QgsPointDisplacementRenderer::QgsPointDisplacementRenderer( const QString& labelAttributeName ) - : QgsPointDistanceRenderer( "pointDisplacement", labelAttributeName ) + : QgsPointDistanceRenderer( QStringLiteral( "pointDisplacement" ), labelAttributeName ) , mPlacement( Ring ) , mCircleWidth( 0.4 ) , mCircleColor( QColor( 125, 125, 125 ) ) @@ -135,32 +135,32 @@ void QgsPointDisplacementRenderer::stopRender( QgsRenderContext& context ) QgsFeatureRenderer* QgsPointDisplacementRenderer::create( QDomElement& symbologyElem ) { QgsPointDisplacementRenderer* r = new QgsPointDisplacementRenderer(); - r->setLabelAttributeName( symbologyElem.attribute( "labelAttributeName" ) ); + r->setLabelAttributeName( symbologyElem.attribute( QStringLiteral( "labelAttributeName" ) ) ); QFont labelFont; - if ( !QgsFontUtils::setFromXmlChildNode( labelFont, symbologyElem, "labelFontProperties" ) ) + if ( !QgsFontUtils::setFromXmlChildNode( labelFont, symbologyElem, QStringLiteral( "labelFontProperties" ) ) ) { - labelFont.fromString( symbologyElem.attribute( "labelFont", "" ) ); + labelFont.fromString( symbologyElem.attribute( QStringLiteral( "labelFont" ), QLatin1String( "" ) ) ); } r->setLabelFont( labelFont ); - r->setPlacement( static_cast< Placement >( symbologyElem.attribute( "placement", "0" ).toInt() ) ); - r->setCircleWidth( symbologyElem.attribute( "circleWidth", "0.4" ).toDouble() ); - r->setCircleColor( QgsSymbolLayerUtils::decodeColor( symbologyElem.attribute( "circleColor", "" ) ) ); - r->setLabelColor( QgsSymbolLayerUtils::decodeColor( symbologyElem.attribute( "labelColor", "" ) ) ); - r->setCircleRadiusAddition( symbologyElem.attribute( "circleRadiusAddition", "0.0" ).toDouble() ); - r->setMaxLabelScaleDenominator( symbologyElem.attribute( "maxLabelScaleDenominator", "-1" ).toDouble() ); - r->setTolerance( symbologyElem.attribute( "tolerance", "0.00001" ).toDouble() ); - r->setToleranceUnit( QgsUnitTypes::decodeRenderUnit( symbologyElem.attribute( "toleranceUnit", "MapUnit" ) ) ); - r->setToleranceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( symbologyElem.attribute( "toleranceUnitScale" ) ) ); + r->setPlacement( static_cast< Placement >( symbologyElem.attribute( QStringLiteral( "placement" ), QStringLiteral( "0" ) ).toInt() ) ); + r->setCircleWidth( symbologyElem.attribute( QStringLiteral( "circleWidth" ), QStringLiteral( "0.4" ) ).toDouble() ); + r->setCircleColor( QgsSymbolLayerUtils::decodeColor( symbologyElem.attribute( QStringLiteral( "circleColor" ), QLatin1String( "" ) ) ) ); + r->setLabelColor( QgsSymbolLayerUtils::decodeColor( symbologyElem.attribute( QStringLiteral( "labelColor" ), QLatin1String( "" ) ) ) ); + r->setCircleRadiusAddition( symbologyElem.attribute( QStringLiteral( "circleRadiusAddition" ), QStringLiteral( "0.0" ) ).toDouble() ); + r->setMaxLabelScaleDenominator( symbologyElem.attribute( QStringLiteral( "maxLabelScaleDenominator" ), QStringLiteral( "-1" ) ).toDouble() ); + r->setTolerance( symbologyElem.attribute( QStringLiteral( "tolerance" ), QStringLiteral( "0.00001" ) ).toDouble() ); + r->setToleranceUnit( QgsUnitTypes::decodeRenderUnit( symbologyElem.attribute( QStringLiteral( "toleranceUnit" ), QStringLiteral( "MapUnit" ) ) ) ); + r->setToleranceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( symbologyElem.attribute( QStringLiteral( "toleranceUnitScale" ) ) ) ); //look for an embedded renderer <renderer-v2> - QDomElement embeddedRendererElem = symbologyElem.firstChildElement( "renderer-v2" ); + QDomElement embeddedRendererElem = symbologyElem.firstChildElement( QStringLiteral( "renderer-v2" ) ); if ( !embeddedRendererElem.isNull() ) { r->setEmbeddedRenderer( QgsFeatureRenderer::load( embeddedRendererElem ) ); } //center symbol - QDomElement centerSymbolElem = symbologyElem.firstChildElement( "symbol" ); + QDomElement centerSymbolElem = symbologyElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !centerSymbolElem.isNull() ) { r->setCenterSymbol( QgsSymbolLayerUtils::loadSymbol<QgsMarkerSymbol>( centerSymbolElem ) ); @@ -176,19 +176,19 @@ QgsMarkerSymbol* QgsPointDisplacementRenderer::centerSymbol() QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) { QDomElement rendererElement = doc.createElement( RENDERER_TAG_NAME ); - rendererElement.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); - rendererElement.setAttribute( "type", "pointDisplacement" ); - rendererElement.setAttribute( "labelAttributeName", mLabelAttributeName ); - rendererElement.appendChild( QgsFontUtils::toXmlElement( mLabelFont, doc, "labelFontProperties" ) ); - rendererElement.setAttribute( "circleWidth", QString::number( mCircleWidth ) ); - rendererElement.setAttribute( "circleColor", QgsSymbolLayerUtils::encodeColor( mCircleColor ) ); - rendererElement.setAttribute( "labelColor", QgsSymbolLayerUtils::encodeColor( mLabelColor ) ); - rendererElement.setAttribute( "circleRadiusAddition", QString::number( mCircleRadiusAddition ) ); - rendererElement.setAttribute( "placement", static_cast< int >( mPlacement ) ); - rendererElement.setAttribute( "maxLabelScaleDenominator", QString::number( mMaxLabelScaleDenominator ) ); - rendererElement.setAttribute( "tolerance", QString::number( mTolerance ) ); - rendererElement.setAttribute( "toleranceUnit", QgsUnitTypes::encodeUnit( mToleranceUnit ) ); - rendererElement.setAttribute( "toleranceUnitScale", QgsSymbolLayerUtils::encodeMapUnitScale( mToleranceMapUnitScale ) ); + rendererElement.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); + rendererElement.setAttribute( QStringLiteral( "type" ), QStringLiteral( "pointDisplacement" ) ); + rendererElement.setAttribute( QStringLiteral( "labelAttributeName" ), mLabelAttributeName ); + rendererElement.appendChild( QgsFontUtils::toXmlElement( mLabelFont, doc, QStringLiteral( "labelFontProperties" ) ) ); + rendererElement.setAttribute( QStringLiteral( "circleWidth" ), QString::number( mCircleWidth ) ); + rendererElement.setAttribute( QStringLiteral( "circleColor" ), QgsSymbolLayerUtils::encodeColor( mCircleColor ) ); + rendererElement.setAttribute( QStringLiteral( "labelColor" ), QgsSymbolLayerUtils::encodeColor( mLabelColor ) ); + rendererElement.setAttribute( QStringLiteral( "circleRadiusAddition" ), QString::number( mCircleRadiusAddition ) ); + rendererElement.setAttribute( QStringLiteral( "placement" ), static_cast< int >( mPlacement ) ); + rendererElement.setAttribute( QStringLiteral( "maxLabelScaleDenominator" ), QString::number( mMaxLabelScaleDenominator ) ); + rendererElement.setAttribute( QStringLiteral( "tolerance" ), QString::number( mTolerance ) ); + rendererElement.setAttribute( QStringLiteral( "toleranceUnit" ), QgsUnitTypes::encodeUnit( mToleranceUnit ) ); + rendererElement.setAttribute( QStringLiteral( "toleranceUnitScale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mToleranceMapUnitScale ) ); if ( mRenderer ) { @@ -197,7 +197,7 @@ QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) } if ( mCenterSymbol ) { - QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( "centerSymbol", mCenterSymbol.data(), doc ); + QDomElement centerSymbolElem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "centerSymbol" ), mCenterSymbol.data(), doc ); rendererElement.appendChild( centerSymbolElem ); } @@ -206,11 +206,11 @@ QDomElement QgsPointDisplacementRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElement.appendChild( orderBy ); } - rendererElement.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElement.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElement; } @@ -337,20 +337,20 @@ void QgsPointDisplacementRenderer::drawSymbols( const ClusteredGroup& group, Qgs QgsPointDisplacementRenderer* QgsPointDisplacementRenderer::convertFromRenderer( const QgsFeatureRenderer* renderer ) { - if ( renderer->type() == "pointDisplacement" ) + if ( renderer->type() == QLatin1String( "pointDisplacement" ) ) { return dynamic_cast<QgsPointDisplacementRenderer*>( renderer->clone() ); } - else if ( renderer->type() == "singleSymbol" || - renderer->type() == "categorizedSymbol" || - renderer->type() == "graduatedSymbol" || - renderer->type() == "RuleRenderer" ) + else if ( renderer->type() == QLatin1String( "singleSymbol" ) || + renderer->type() == QLatin1String( "categorizedSymbol" ) || + renderer->type() == QLatin1String( "graduatedSymbol" ) || + renderer->type() == QLatin1String( "RuleRenderer" ) ) { QgsPointDisplacementRenderer* pointRenderer = new QgsPointDisplacementRenderer(); pointRenderer->setEmbeddedRenderer( renderer->clone() ); return pointRenderer; } - else if ( renderer->type() == "pointCluster" ) + else if ( renderer->type() == QLatin1String( "pointCluster" ) ) { QgsPointDisplacementRenderer* pointRenderer = new QgsPointDisplacementRenderer(); const QgsPointClusterRenderer* clusterRenderer = static_cast< const QgsPointClusterRenderer* >( renderer ); diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index 21f34ae67d3f..10e27dd06ab8 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -87,7 +87,7 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ) override; - QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; + QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) override; void setEmbeddedRenderer( QgsFeatureRenderer* r ) override; const QgsFeatureRenderer* embeddedRenderer() const override; void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) override; diff --git a/src/core/symbology-ng/qgsrenderer.cpp b/src/core/symbology-ng/qgsrenderer.cpp index bae700e784bb..8cf792dffbc9 100644 --- a/src/core/symbology-ng/qgsrenderer.cpp +++ b/src/core/symbology-ng/qgsrenderer.cpp @@ -112,7 +112,7 @@ void QgsFeatureRenderer::renderFeatureWithSymbol( QgsFeature& feature, QgsSymbol QString QgsFeatureRenderer::dump() const { - return "UNKNOWN RENDERER\n"; + return QStringLiteral( "UNKNOWN RENDERER\n" ); } QgsFeatureRenderer* QgsFeatureRenderer::load( QDomElement& element ) @@ -123,7 +123,7 @@ QgsFeatureRenderer* QgsFeatureRenderer::load( QDomElement& element ) return nullptr; // load renderer - QString rendererType = element.attribute( "type" ); + QString rendererType = element.attribute( QStringLiteral( "type" ) ); QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( rendererType ); if ( !m ) @@ -132,20 +132,20 @@ QgsFeatureRenderer* QgsFeatureRenderer::load( QDomElement& element ) QgsFeatureRenderer* r = m->createRenderer( element ); if ( r ) { - r->setUsingSymbolLevels( element.attribute( "symbollevels", "0" ).toInt() ); - r->setForceRasterRender( element.attribute( "forceraster", "0" ).toInt() ); + r->setUsingSymbolLevels( element.attribute( QStringLiteral( "symbollevels" ), QStringLiteral( "0" ) ).toInt() ); + r->setForceRasterRender( element.attribute( QStringLiteral( "forceraster" ), QStringLiteral( "0" ) ).toInt() ); //restore layer effect - QDomElement effectElem = element.firstChildElement( "effect" ); + QDomElement effectElem = element.firstChildElement( QStringLiteral( "effect" ) ); if ( !effectElem.isNull() ) { r->setPaintEffect( QgsPaintEffectRegistry::instance()->createEffect( effectElem ) ); } // restore order by - QDomElement orderByElem = element.firstChildElement( "orderby" ); + QDomElement orderByElem = element.firstChildElement( QStringLiteral( "orderby" ) ); r->mOrderBy.load( orderByElem ); - r->setOrderByEnabled( element.attribute( "enableorderby", "0" ).toInt() ); + r->setOrderByEnabled( element.attribute( QStringLiteral( "enableorderby" ), QStringLiteral( "0" ) ).toInt() ); } return r; } @@ -154,18 +154,18 @@ QDomElement QgsFeatureRenderer::save( QDomDocument& doc ) { // create empty renderer element QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) mPaintEffect->saveProperties( doc, rendererElem ); if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -176,19 +176,19 @@ QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTyp return nullptr; // get the UserStyle element - QDomElement userStyleElem = element.firstChildElement( "UserStyle" ); + QDomElement userStyleElem = element.firstChildElement( QStringLiteral( "UserStyle" ) ); if ( userStyleElem.isNull() ) { // UserStyle element not found, nothing will be rendered - errorMessage = "Info: UserStyle element not found."; + errorMessage = QStringLiteral( "Info: UserStyle element not found." ); return nullptr; } // get the FeatureTypeStyle element - QDomElement featTypeStyleElem = userStyleElem.firstChildElement( "FeatureTypeStyle" ); + QDomElement featTypeStyleElem = userStyleElem.firstChildElement( QStringLiteral( "FeatureTypeStyle" ) ); if ( featTypeStyleElem.isNull() ) { - errorMessage = "Info: FeatureTypeStyle element not found."; + errorMessage = QStringLiteral( "Info: FeatureTypeStyle element not found." ); return nullptr; } @@ -198,7 +198,7 @@ QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTyp bool needRuleRenderer = false; int ruleCount = 0; - QDomElement ruleElem = featTypeStyleElem.firstChildElement( "Rule" ); + QDomElement ruleElem = featTypeStyleElem.firstChildElement( QStringLiteral( "Rule" ) ); while ( !ruleElem.isNull() ) { ruleCount++; @@ -215,9 +215,9 @@ QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTyp while ( !ruleChildElem.isNull() ) { // rule has filter or min/max scale denominator, use the RuleRenderer - if ( ruleChildElem.localName() == "Filter" || - ruleChildElem.localName() == "MinScaleDenominator" || - ruleChildElem.localName() == "MaxScaleDenominator" ) + if ( ruleChildElem.localName() == QLatin1String( "Filter" ) || + ruleChildElem.localName() == QLatin1String( "MinScaleDenominator" ) || + ruleChildElem.localName() == QLatin1String( "MaxScaleDenominator" ) ) { QgsDebugMsg( "Filter or Min/MaxScaleDenominator element found: need a RuleRenderer" ); needRuleRenderer = true; @@ -232,17 +232,17 @@ QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTyp break; } - ruleElem = ruleElem.nextSiblingElement( "Rule" ); + ruleElem = ruleElem.nextSiblingElement( QStringLiteral( "Rule" ) ); } QString rendererType; if ( needRuleRenderer ) { - rendererType = "RuleRenderer"; + rendererType = QStringLiteral( "RuleRenderer" ); } else { - rendererType = "singleSymbol"; + rendererType = QStringLiteral( "singleSymbol" ); } QgsDebugMsg( QString( "Instantiating a '%1' renderer..." ).arg( rendererType ) ); @@ -250,7 +250,7 @@ QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTyp QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( rendererType ); if ( !m ) { - errorMessage = QString( "Error: Unable to get metadata for '%1' renderer." ).arg( rendererType ); + errorMessage = QStringLiteral( "Error: Unable to get metadata for '%1' renderer." ).arg( rendererType ); return nullptr; } @@ -260,13 +260,13 @@ QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTyp QDomElement QgsFeatureRenderer::writeSld( QDomDocument& doc, const QString& styleName, const QgsStringMap& props ) const { - QDomElement userStyleElem = doc.createElement( "UserStyle" ); + QDomElement userStyleElem = doc.createElement( QStringLiteral( "UserStyle" ) ); - QDomElement nameElem = doc.createElement( "se:Name" ); + QDomElement nameElem = doc.createElement( QStringLiteral( "se:Name" ) ); nameElem.appendChild( doc.createTextNode( styleName ) ); userStyleElem.appendChild( nameElem ); - QDomElement featureTypeStyleElem = doc.createElement( "se:FeatureTypeStyle" ); + QDomElement featureTypeStyleElem = doc.createElement( QStringLiteral( "se:FeatureTypeStyle" ) ); toSld( doc, featureTypeStyleElem, props ); userStyleElem.appendChild( featureTypeStyleElem ); diff --git a/src/core/symbology-ng/qgsrenderer.h b/src/core/symbology-ng/qgsrenderer.h index 4d4e7d70cb3a..5299f8eafd7d 100644 --- a/src/core/symbology-ng/qgsrenderer.h +++ b/src/core/symbology-ng/qgsrenderer.h @@ -242,7 +242,7 @@ class CORE_EXPORT QgsFeatureRenderer //! used from subclasses to create SLD Rule elements following SLD v1.1 specs virtual void toSld( QDomDocument& doc, QDomElement &element, const QgsStringMap& props = QgsStringMap() ) const { - element.appendChild( doc.createComment( QString( "FeatureRendererV2 %1 not implemented yet" ).arg( type() ) ) ); + element.appendChild( doc.createComment( QStringLiteral( "FeatureRendererV2 %1 not implemented yet" ).arg( type() ) ) ); ( void ) props; // warning avoidance } @@ -270,7 +270,7 @@ class CORE_EXPORT QgsFeatureRenderer //! return a list of item text / symbol //! @note not available in python bindings - virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ); + virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ); //! Return a list of symbology items for the legend. Better choice than legendSymbolItems(). //! Default fallback implementation just uses legendSymbolItems() implementation diff --git a/src/core/symbology-ng/qgsrendererregistry.cpp b/src/core/symbology-ng/qgsrendererregistry.cpp index b7245729fb7d..659f7f6eeccc 100644 --- a/src/core/symbology-ng/qgsrendererregistry.cpp +++ b/src/core/symbology-ng/qgsrendererregistry.cpp @@ -30,50 +30,50 @@ QgsRendererRegistry::QgsRendererRegistry() { // add default renderers - addRenderer( new QgsRendererMetadata( "nullSymbol", + addRenderer( new QgsRendererMetadata( QStringLiteral( "nullSymbol" ), QObject::tr( "No symbols" ), QgsNullSymbolRenderer::create ) ); - addRenderer( new QgsRendererMetadata( "singleSymbol", + addRenderer( new QgsRendererMetadata( QStringLiteral( "singleSymbol" ), QObject::tr( "Single symbol" ), QgsSingleSymbolRenderer::create, QgsSingleSymbolRenderer::createFromSld ) ); - addRenderer( new QgsRendererMetadata( "categorizedSymbol", + addRenderer( new QgsRendererMetadata( QStringLiteral( "categorizedSymbol" ), QObject::tr( "Categorized" ), QgsCategorizedSymbolRenderer::create ) ); - addRenderer( new QgsRendererMetadata( "graduatedSymbol", + addRenderer( new QgsRendererMetadata( QStringLiteral( "graduatedSymbol" ), QObject::tr( "Graduated" ), QgsGraduatedSymbolRenderer::create ) ); - addRenderer( new QgsRendererMetadata( "RuleRenderer", + addRenderer( new QgsRendererMetadata( QStringLiteral( "RuleRenderer" ), QObject::tr( "Rule-based" ), QgsRuleBasedRenderer::create, QgsRuleBasedRenderer::createFromSld ) ); - addRenderer( new QgsRendererMetadata( "pointDisplacement", + addRenderer( new QgsRendererMetadata( QStringLiteral( "pointDisplacement" ), QObject::tr( "Point displacement" ), QgsPointDisplacementRenderer::create, QIcon(), nullptr, QgsRendererAbstractMetadata::PointLayer ) ); - addRenderer( new QgsRendererMetadata( "pointCluster", + addRenderer( new QgsRendererMetadata( QStringLiteral( "pointCluster" ), QObject::tr( "Point cluster" ), QgsPointClusterRenderer::create, QIcon(), nullptr, QgsRendererAbstractMetadata::PointLayer ) ); - addRenderer( new QgsRendererMetadata( "invertedPolygonRenderer", + addRenderer( new QgsRendererMetadata( QStringLiteral( "invertedPolygonRenderer" ), QObject::tr( "Inverted polygons" ), QgsInvertedPolygonRenderer::create, QIcon(), nullptr, QgsRendererAbstractMetadata::PolygonLayer ) ); - addRenderer( new QgsRendererMetadata( "heatmapRenderer", + addRenderer( new QgsRendererMetadata( QStringLiteral( "heatmapRenderer" ), QObject::tr( "Heatmap" ), QgsHeatmapRenderer::create, QIcon(), @@ -81,7 +81,7 @@ QgsRendererRegistry::QgsRendererRegistry() QgsRendererAbstractMetadata::PointLayer ) ); - addRenderer( new QgsRendererMetadata( "25dRenderer", + addRenderer( new QgsRendererMetadata( QStringLiteral( "25dRenderer" ), QObject::tr( "2.5 D" ), Qgs25DRenderer::create, QIcon(), diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.cpp b/src/core/symbology-ng/qgsrulebasedrenderer.cpp index 9cddfdb5199f..b2f2ac319a4a 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.cpp +++ b/src/core/symbology-ng/qgsrulebasedrenderer.cpp @@ -48,7 +48,7 @@ QgsRuleBasedRenderer::Rule::Rule( QgsSymbol* symbol, int scaleMinDenom, int scal , mFilter( nullptr ) { if ( mElseRule ) - mFilterExp = "ELSE"; + mFilterExp = QStringLiteral( "ELSE" ); mRuleKey = QUuid::createUuid().toString(); initFilter(); @@ -64,7 +64,7 @@ QgsRuleBasedRenderer::Rule::~Rule() void QgsRuleBasedRenderer::Rule::initFilter() { - if ( mFilterExp.trimmed().compare( "ELSE", Qt::CaseInsensitive ) == 0 ) + if ( mFilterExp.trimmed().compare( QLatin1String( "ELSE" ), Qt::CaseInsensitive ) == 0 ) { mElseRule = true; delete mFilter; @@ -155,7 +155,7 @@ void QgsRuleBasedRenderer::Rule::updateElseRules() void QgsRuleBasedRenderer::Rule::setIsElse( bool iselse ) { - mFilterExp = "ELSE"; + mFilterExp = QStringLiteral( "ELSE" ); mElseRule = iselse; delete mFilter; mFilter = nullptr; @@ -166,8 +166,8 @@ QString QgsRuleBasedRenderer::Rule::dump( int indent ) const { QString off; off.fill( QChar( ' ' ), indent ); - QString symbolDump = ( mSymbol ? mSymbol->dump() : QString( "[]" ) ); - QString msg = off + QString( "RULE %1 - scale [%2,%3] - filter %4 - symbol %5\n" ) + QString symbolDump = ( mSymbol ? mSymbol->dump() : QStringLiteral( "[]" ) ); + QString msg = off + QStringLiteral( "RULE %1 - scale [%2,%3] - filter %4 - symbol %5\n" ) .arg( mLabel ).arg( mScaleMinDenom ).arg( mScaleMaxDenom ) .arg( mFilterExp, symbolDump ); @@ -176,7 +176,7 @@ QString QgsRuleBasedRenderer::Rule::dump( int indent ) const { lst.append( rule->dump( indent + 2 ) ); } - msg += lst.join( "\n" ); + msg += lst.join( QStringLiteral( "\n" ) ); return msg; } @@ -305,27 +305,27 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::clone() const QDomElement QgsRuleBasedRenderer::Rule::save( QDomDocument& doc, QgsSymbolMap& symbolMap ) const { - QDomElement ruleElem = doc.createElement( "rule" ); + QDomElement ruleElem = doc.createElement( QStringLiteral( "rule" ) ); if ( mSymbol ) { int symbolIndex = symbolMap.size(); symbolMap[QString::number( symbolIndex )] = mSymbol; - ruleElem.setAttribute( "symbol", symbolIndex ); + ruleElem.setAttribute( QStringLiteral( "symbol" ), symbolIndex ); } if ( !mFilterExp.isEmpty() ) - ruleElem.setAttribute( "filter", mFilterExp ); + ruleElem.setAttribute( QStringLiteral( "filter" ), mFilterExp ); if ( mScaleMinDenom != 0 ) - ruleElem.setAttribute( "scalemindenom", mScaleMinDenom ); + ruleElem.setAttribute( QStringLiteral( "scalemindenom" ), mScaleMinDenom ); if ( mScaleMaxDenom != 0 ) - ruleElem.setAttribute( "scalemaxdenom", mScaleMaxDenom ); + ruleElem.setAttribute( QStringLiteral( "scalemaxdenom" ), mScaleMaxDenom ); if ( !mLabel.isEmpty() ) - ruleElem.setAttribute( "label", mLabel ); + ruleElem.setAttribute( QStringLiteral( "label" ), mLabel ); if ( !mDescription.isEmpty() ) - ruleElem.setAttribute( "description", mDescription ); + ruleElem.setAttribute( QStringLiteral( "description" ), mDescription ); if ( !mIsActive ) - ruleElem.setAttribute( "checkstate", 0 ); - ruleElem.setAttribute( "key", mRuleKey ); + ruleElem.setAttribute( QStringLiteral( "checkstate" ), 0 ); + ruleElem.setAttribute( QStringLiteral( "key" ), mRuleKey ); Q_FOREACH ( Rule* rule, mChildren ) { @@ -343,45 +343,45 @@ void QgsRuleBasedRenderer::Rule::toSld( QDomDocument& doc, QDomElement &element, if ( !mFilterExp.isEmpty() ) { - if ( !props.value( "filter", "" ).isEmpty() ) - props[ "filter" ] += " AND "; - props[ "filter" ] += mFilterExp; + if ( !props.value( QStringLiteral( "filter" ), QLatin1String( "" ) ).isEmpty() ) + props[ QStringLiteral( "filter" )] += QLatin1String( " AND " ); + props[ QStringLiteral( "filter" )] += mFilterExp; } QgsSymbolLayerUtils::mergeScaleDependencies( mScaleMinDenom, mScaleMaxDenom, props ); if ( mSymbol ) { - QDomElement ruleElem = doc.createElement( "se:Rule" ); + QDomElement ruleElem = doc.createElement( QStringLiteral( "se:Rule" ) ); element.appendChild( ruleElem ); //XXX: <se:Name> is the rule identifier, but our the Rule objects // have no properties could be used as identifier. Use the label. - QDomElement nameElem = doc.createElement( "se:Name" ); + QDomElement nameElem = doc.createElement( QStringLiteral( "se:Name" ) ); nameElem.appendChild( doc.createTextNode( mLabel ) ); ruleElem.appendChild( nameElem ); if ( !mLabel.isEmpty() || !mDescription.isEmpty() ) { - QDomElement descrElem = doc.createElement( "se:Description" ); + QDomElement descrElem = doc.createElement( QStringLiteral( "se:Description" ) ); if ( !mLabel.isEmpty() ) { - QDomElement titleElem = doc.createElement( "se:Title" ); + QDomElement titleElem = doc.createElement( QStringLiteral( "se:Title" ) ); titleElem.appendChild( doc.createTextNode( mLabel ) ); descrElem.appendChild( titleElem ); } if ( !mDescription.isEmpty() ) { - QDomElement abstractElem = doc.createElement( "se:Abstract" ); + QDomElement abstractElem = doc.createElement( QStringLiteral( "se:Abstract" ) ); abstractElem.appendChild( doc.createTextNode( mDescription ) ); descrElem.appendChild( abstractElem ); } ruleElem.appendChild( descrElem ); } - if ( !props.value( "filter", "" ).isEmpty() ) + if ( !props.value( QStringLiteral( "filter" ), QLatin1String( "" ) ).isEmpty() ) { - QgsSymbolLayerUtils::createFunctionElement( doc, ruleElem, props.value( "filter", "" ) ); + QgsSymbolLayerUtils::createFunctionElement( doc, ruleElem, props.value( QStringLiteral( "filter" ), QLatin1String( "" ) ) ); } QgsSymbolLayerUtils::applyScaleDependency( doc, ruleElem, props ); @@ -433,10 +433,10 @@ bool QgsRuleBasedRenderer::Rule::startRender( QgsRenderContext& context, const Q // If there are subfilters present (and it's not a single empty one), group them and join them with OR if ( subfilters.length() > 1 || !subfilters.value( 0 ).isEmpty() ) { - if ( subfilters.contains( "TRUE" ) ) - sf = "TRUE"; + if ( subfilters.contains( QStringLiteral( "TRUE" ) ) ) + sf = QStringLiteral( "TRUE" ); else - sf = subfilters.join( ") OR (" ).prepend( '(' ).append( ')' ); + sf = subfilters.join( QStringLiteral( ") OR (" ) ).prepend( '(' ).append( ')' ); } // Now join the subfilters with their parent (this) based on if @@ -447,18 +447,18 @@ bool QgsRuleBasedRenderer::Rule::startRender( QgsRenderContext& context, const Q if ( !mFilter ) { if ( mSymbol || sf.isEmpty() ) - filter = "TRUE"; + filter = QStringLiteral( "TRUE" ); else filter = sf; } else if ( mSymbol ) filter = mFilterExp; else if ( !mFilterExp.trimmed().isEmpty() && !sf.isEmpty() ) - filter = QString( "(%1) AND (%2)" ).arg( mFilterExp, sf ); + filter = QStringLiteral( "(%1) AND (%2)" ).arg( mFilterExp, sf ); else if ( !mFilterExp.trimmed().isEmpty() ) filter = mFilterExp; else if ( sf.isEmpty() ) - filter = "TRUE"; + filter = QStringLiteral( "TRUE" ); else filter = sf; @@ -636,7 +636,7 @@ void QgsRuleBasedRenderer::Rule::stopRender( QgsRenderContext& context ) QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::create( QDomElement& ruleElem, QgsSymbolMap& symbolMap ) { - QString symbolIdx = ruleElem.attribute( "symbol" ); + QString symbolIdx = ruleElem.attribute( QStringLiteral( "symbol" ) ); QgsSymbol* symbol = nullptr; if ( !symbolIdx.isEmpty() ) { @@ -650,20 +650,20 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::create( QDomElement& rul } } - QString filterExp = ruleElem.attribute( "filter" ); - QString label = ruleElem.attribute( "label" ); - QString description = ruleElem.attribute( "description" ); - int scaleMinDenom = ruleElem.attribute( "scalemindenom", "0" ).toInt(); - int scaleMaxDenom = ruleElem.attribute( "scalemaxdenom", "0" ).toInt(); - QString ruleKey = ruleElem.attribute( "key" ); + QString filterExp = ruleElem.attribute( QStringLiteral( "filter" ) ); + QString label = ruleElem.attribute( QStringLiteral( "label" ) ); + QString description = ruleElem.attribute( QStringLiteral( "description" ) ); + int scaleMinDenom = ruleElem.attribute( QStringLiteral( "scalemindenom" ), QStringLiteral( "0" ) ).toInt(); + int scaleMaxDenom = ruleElem.attribute( QStringLiteral( "scalemaxdenom" ), QStringLiteral( "0" ) ).toInt(); + QString ruleKey = ruleElem.attribute( QStringLiteral( "key" ) ); Rule* rule = new Rule( symbol, scaleMinDenom, scaleMaxDenom, filterExp, label, description ); if ( !ruleKey.isEmpty() ) rule->mRuleKey = ruleKey; - rule->setActive( ruleElem.attribute( "checkstate", "1" ).toInt() ); + rule->setActive( ruleElem.attribute( QStringLiteral( "checkstate" ), QStringLiteral( "1" ) ).toInt() ); - QDomElement childRuleElem = ruleElem.firstChildElement( "rule" ); + QDomElement childRuleElem = ruleElem.firstChildElement( QStringLiteral( "rule" ) ); while ( !childRuleElem.isNull() ) { Rule* childRule = create( childRuleElem, symbolMap ); @@ -675,7 +675,7 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::create( QDomElement& rul { QgsDebugMsg( "failed to init a child rule!" ); } - childRuleElem = childRuleElem.nextSiblingElement( "rule" ); + childRuleElem = childRuleElem.nextSiblingElement( QStringLiteral( "rule" ) ); } return rule; @@ -683,7 +683,7 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::create( QDomElement& rul QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::createFromSld( QDomElement& ruleElem, QgsWkbTypes::GeometryType geomType ) { - if ( ruleElem.localName() != "Rule" ) + if ( ruleElem.localName() != QLatin1String( "Rule" ) ) { QgsDebugMsg( QString( "invalid element: Rule element expected, %1 found!" ).arg( ruleElem.tagName() ) ); return nullptr; @@ -697,39 +697,39 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::createFromSld( QDomEleme QDomElement childElem = ruleElem.firstChildElement(); while ( !childElem.isNull() ) { - if ( childElem.localName() == "Name" ) + if ( childElem.localName() == QLatin1String( "Name" ) ) { // <se:Name> tag contains the rule identifier, // so prefer title tag for the label property value if ( label.isEmpty() ) label = childElem.firstChild().nodeValue(); } - else if ( childElem.localName() == "Description" ) + else if ( childElem.localName() == QLatin1String( "Description" ) ) { // <se:Description> can contains a title and an abstract - QDomElement titleElem = childElem.firstChildElement( "Title" ); + QDomElement titleElem = childElem.firstChildElement( QStringLiteral( "Title" ) ); if ( !titleElem.isNull() ) { label = titleElem.firstChild().nodeValue(); } - QDomElement abstractElem = childElem.firstChildElement( "Abstract" ); + QDomElement abstractElem = childElem.firstChildElement( QStringLiteral( "Abstract" ) ); if ( !abstractElem.isNull() ) { description = abstractElem.firstChild().nodeValue(); } } - else if ( childElem.localName() == "Abstract" ) + else if ( childElem.localName() == QLatin1String( "Abstract" ) ) { // <sld:Abstract> (v1.0) description = childElem.firstChild().nodeValue(); } - else if ( childElem.localName() == "Title" ) + else if ( childElem.localName() == QLatin1String( "Title" ) ) { // <sld:Title> (v1.0) label = childElem.firstChild().nodeValue(); } - else if ( childElem.localName() == "Filter" ) + else if ( childElem.localName() == QLatin1String( "Filter" ) ) { QgsExpression *filter = QgsOgcUtils::expressionFromOgcFilter( childElem ); if ( filter ) @@ -745,21 +745,21 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::createFromSld( QDomEleme delete filter; } } - else if ( childElem.localName() == "MinScaleDenominator" ) + else if ( childElem.localName() == QLatin1String( "MinScaleDenominator" ) ) { bool ok; int v = childElem.firstChild().nodeValue().toInt( &ok ); if ( ok ) scaleMinDenom = v; } - else if ( childElem.localName() == "MaxScaleDenominator" ) + else if ( childElem.localName() == QLatin1String( "MaxScaleDenominator" ) ) { bool ok; int v = childElem.firstChild().nodeValue().toInt( &ok ); if ( ok ) scaleMaxDenom = v; } - else if ( childElem.localName().endsWith( "Symbolizer" ) ) + else if ( childElem.localName().endsWith( QLatin1String( "Symbolizer" ) ) ) { // create symbol layers for this symbolizer QgsSymbolLayerUtils::createSymbolLayerListFromSld( childElem, geomType, layers ); @@ -800,13 +800,13 @@ QgsRuleBasedRenderer::Rule* QgsRuleBasedRenderer::Rule::createFromSld( QDomEleme ///////////////////// QgsRuleBasedRenderer::QgsRuleBasedRenderer( QgsRuleBasedRenderer::Rule* root ) - : QgsFeatureRenderer( "RuleRenderer" ) + : QgsFeatureRenderer( QStringLiteral( "RuleRenderer" ) ) , mRootRule( root ) { } QgsRuleBasedRenderer::QgsRuleBasedRenderer( QgsSymbol* defaultSymbol ) - : QgsFeatureRenderer( "RuleRenderer" ) + : QgsFeatureRenderer( QStringLiteral( "RuleRenderer" ) ) { mRootRule = new Rule( nullptr ); // root has no symbol, no filter etc - just a container mRootRule->appendChild( new Rule( defaultSymbol ) ); @@ -954,17 +954,17 @@ QgsSymbolList QgsRuleBasedRenderer::symbols( QgsRenderContext& context ) QDomElement QgsRuleBasedRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "RuleRenderer" ); - rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "RuleRenderer" ) ); + rendererElem.setAttribute( QStringLiteral( "symbollevels" ), ( mUsingSymbolLevels ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); QgsSymbolMap symbols; QDomElement rulesElem = mRootRule->save( doc, symbols ); - rulesElem.setTagName( "rules" ); // instead of just "rule" + rulesElem.setTagName( QStringLiteral( "rules" ) ); // instead of just "rule" rendererElem.appendChild( rulesElem ); - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, "symbols", doc ); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, QStringLiteral( "symbols" ), doc ); rendererElem.appendChild( symbolsElem ); if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) @@ -972,11 +972,11 @@ QDomElement QgsRuleBasedRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -1035,13 +1035,13 @@ QgsLegendSymbolListV2 QgsRuleBasedRenderer::legendSymbolItemsV2() const QgsFeatureRenderer* QgsRuleBasedRenderer::create( QDomElement& element ) { // load symbols - QDomElement symbolsElem = element.firstChildElement( "symbols" ); + QDomElement symbolsElem = element.firstChildElement( QStringLiteral( "symbols" ) ); if ( symbolsElem.isNull() ) return nullptr; QgsSymbolMap symbolMap = QgsSymbolLayerUtils::loadSymbols( symbolsElem ); - QDomElement rulesElem = element.firstChildElement( "rules" ); + QDomElement rulesElem = element.firstChildElement( QStringLiteral( "rules" ) ); Rule* root = Rule::create( rulesElem, symbolMap ); if ( !root ) @@ -1060,7 +1060,7 @@ QgsFeatureRenderer* QgsRuleBasedRenderer::createFromSld( QDomElement& element, Q // retrieve child rules Rule* root = nullptr; - QDomElement ruleElem = element.firstChildElement( "Rule" ); + QDomElement ruleElem = element.firstChildElement( QStringLiteral( "Rule" ) ); while ( !ruleElem.isNull() ) { Rule *child = Rule::createFromSld( ruleElem, geomType ); @@ -1073,7 +1073,7 @@ QgsFeatureRenderer* QgsRuleBasedRenderer::createFromSld( QDomElement& element, Q root->appendChild( child ); } - ruleElem = ruleElem.nextSiblingElement( "Rule" ); + ruleElem = ruleElem.nextSiblingElement( QStringLiteral( "Rule" ) ); } if ( !root ) @@ -1113,7 +1113,7 @@ void QgsRuleBasedRenderer::refineRuleCategories( QgsRuleBasedRenderer::Rule* ini value = QString::number( cat.value().toDouble(), 'f', 4 ); else value = QgsExpression::quotedString( cat.value().toString() ); - QString filter = QString( "%1 = %2" ).arg( attr, value ); + QString filter = QStringLiteral( "%1 = %2" ).arg( attr, value ); QString label = filter; initialRule->appendChild( new Rule( cat.symbol()->clone(), 0, 0, filter, label ) ); } @@ -1133,7 +1133,7 @@ void QgsRuleBasedRenderer::refineRuleRanges( QgsRuleBasedRenderer::Rule* initial else if ( !testExpr.isField() ) { //otherwise wrap expression in brackets - attr = QString( "(%1)" ).arg( attr ); + attr = QStringLiteral( "(%1)" ).arg( attr ); } bool firstRange = true; @@ -1141,7 +1141,7 @@ void QgsRuleBasedRenderer::refineRuleRanges( QgsRuleBasedRenderer::Rule* initial { // due to the loss of precision in double->string conversion we may miss out values at the limit of the range // TODO: have a possibility to construct expressions directly as a parse tree to avoid loss of precision - QString filter = QString( "%1 %2 %3 AND %1 <= %4" ).arg( attr, firstRange ? ">=" : ">", + QString filter = QStringLiteral( "%1 %2 %3 AND %1 <= %4" ).arg( attr, firstRange ? ">=" : ">", QString::number( rng.lowerValue(), 'f', 4 ), QString::number( rng.upperValue(), 'f', 4 ) ); firstRange = false; @@ -1162,16 +1162,16 @@ void QgsRuleBasedRenderer::refineRuleScales( QgsRuleBasedRenderer::Rule* initial continue; // jump over the first scales out of the interval if ( maxDenom != 0 && maxDenom <= scale ) break; // ignore the latter scales out of the interval - initialRule->appendChild( new Rule( symbol->clone(), oldScale, scale, QString(), QString( "%1 - %2" ).arg( oldScale ).arg( scale ) ) ); + initialRule->appendChild( new Rule( symbol->clone(), oldScale, scale, QString(), QStringLiteral( "%1 - %2" ).arg( oldScale ).arg( scale ) ) ); oldScale = scale; } // last rule - initialRule->appendChild( new Rule( symbol->clone(), oldScale, maxDenom, QString(), QString( "%1 - %2" ).arg( oldScale ).arg( maxDenom ) ) ); + initialRule->appendChild( new Rule( symbol->clone(), oldScale, maxDenom, QString(), QStringLiteral( "%1 - %2" ).arg( oldScale ).arg( maxDenom ) ) ); } QString QgsRuleBasedRenderer::dump() const { - QString msg( "Rule-based renderer:\n" ); + QString msg( QStringLiteral( "Rule-based renderer:\n" ) ); msg += mRootRule->dump(); return msg; } @@ -1199,11 +1199,11 @@ QSet< QString > QgsRuleBasedRenderer::legendKeysForFeature( QgsFeature& feature, QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatureRenderer* renderer ) { QgsRuleBasedRenderer* r = nullptr; - if ( renderer->type() == "RuleRenderer" ) + if ( renderer->type() == QLatin1String( "RuleRenderer" ) ) { r = dynamic_cast<QgsRuleBasedRenderer*>( renderer->clone() ); } - else if ( renderer->type() == "singleSymbol" ) + else if ( renderer->type() == QLatin1String( "singleSymbol" ) ) { const QgsSingleSymbolRenderer* singleSymbolRenderer = dynamic_cast<const QgsSingleSymbolRenderer*>( renderer ); if ( !singleSymbolRenderer ) @@ -1212,7 +1212,7 @@ QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatur QgsSymbol* origSymbol = singleSymbolRenderer->symbol()->clone(); r = new QgsRuleBasedRenderer( origSymbol ); } - else if ( renderer->type() == "categorizedSymbol" ) + else if ( renderer->type() == QLatin1String( "categorizedSymbol" ) ) { const QgsCategorizedSymbolRenderer* categorizedRenderer = dynamic_cast<const QgsCategorizedSymbolRenderer*>( renderer ); if ( !categorizedRenderer ) @@ -1252,13 +1252,13 @@ QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatur } //An empty category is equivalent to the ELSE keyword - if ( value == "''" ) + if ( value == QLatin1String( "''" ) ) { - expression = "ELSE"; + expression = QStringLiteral( "ELSE" ); } else { - expression = QString( "%1 = %2" ).arg( attr, value ); + expression = QStringLiteral( "%1 = %2" ).arg( attr, value ); } rule->setFilterExpression( expression ); @@ -1274,7 +1274,7 @@ QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatur r = new QgsRuleBasedRenderer( rootrule ); } - else if ( renderer->type() == "graduatedSymbol" ) + else if ( renderer->type() == QLatin1String( "graduatedSymbol" ) ) { const QgsGraduatedSymbolRenderer* graduatedRenderer = dynamic_cast<const QgsGraduatedSymbolRenderer*>( renderer ); if ( !graduatedRenderer ) @@ -1292,7 +1292,7 @@ QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatur else if ( !testExpr.isField() ) { //otherwise wrap expression in brackets - attr = QString( "(%1)" ).arg( attr ); + attr = QStringLiteral( "(%1)" ).arg( attr ); } QgsRuleBasedRenderer::Rule* rootrule = new QgsRuleBasedRenderer::Rule( nullptr ); @@ -1328,13 +1328,13 @@ QgsRuleBasedRenderer* QgsRuleBasedRenderer::convertFromRenderer( const QgsFeatur r = new QgsRuleBasedRenderer( rootrule ); } - else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) + else if ( renderer->type() == QLatin1String( "pointDisplacement" ) || renderer->type() == QLatin1String( "pointCluster" ) ) { const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast<const QgsPointDistanceRenderer*>( renderer ); if ( pointDistanceRenderer ) return convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } - else if ( renderer->type() == "invertedPolygonRenderer" ) + else if ( renderer->type() == QLatin1String( "invertedPolygonRenderer" ) ) { const QgsInvertedPolygonRenderer* invertedPolygonRenderer = dynamic_cast<const QgsInvertedPolygonRenderer*>( renderer ); if ( invertedPolygonRenderer ) @@ -1361,12 +1361,12 @@ void QgsRuleBasedRenderer::convertToDataDefinedSymbology( QgsSymbol* symbol, con QgsMarkerSymbolLayer* msl = static_cast<QgsMarkerSymbolLayer*>( symbol->symbolLayer( j ) ); if ( ! sizeScaleField.isEmpty() ) { - sizeExpression = QString( "%1*(%2)" ).arg( msl->size() ).arg( sizeScaleField ); - msl->setDataDefinedProperty( "size", new QgsDataDefined( sizeExpression ) ); + sizeExpression = QStringLiteral( "%1*(%2)" ).arg( msl->size() ).arg( sizeScaleField ); + msl->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( sizeExpression ) ); } if ( ! rotationField.isEmpty() ) { - msl->setDataDefinedProperty( "angle", new QgsDataDefined( true, false, QString(), rotationField ) ); + msl->setDataDefinedProperty( QStringLiteral( "angle" ), new QgsDataDefined( true, false, QString(), rotationField ) ); } } break; @@ -1375,20 +1375,20 @@ void QgsRuleBasedRenderer::convertToDataDefinedSymbology( QgsSymbol* symbol, con { for ( int j = 0; j < symbol->symbolLayerCount();++j ) { - if ( symbol->symbolLayer( j )->layerType() == "SimpleLine" ) + if ( symbol->symbolLayer( j )->layerType() == QLatin1String( "SimpleLine" ) ) { QgsLineSymbolLayer* lsl = static_cast<QgsLineSymbolLayer*>( symbol->symbolLayer( j ) ); - sizeExpression = QString( "%1*(%2)" ).arg( lsl->width() ).arg( sizeScaleField ); - lsl->setDataDefinedProperty( "width", new QgsDataDefined( sizeExpression ) ); + sizeExpression = QStringLiteral( "%1*(%2)" ).arg( lsl->width() ).arg( sizeScaleField ); + lsl->setDataDefinedProperty( QStringLiteral( "width" ), new QgsDataDefined( sizeExpression ) ); } - if ( symbol->symbolLayer( j )->layerType() == "MarkerLine" ) + if ( symbol->symbolLayer( j )->layerType() == QLatin1String( "MarkerLine" ) ) { QgsSymbol* marker = symbol->symbolLayer( j )->subSymbol(); for ( int k = 0; k < marker->symbolLayerCount();++k ) { QgsMarkerSymbolLayer* msl = static_cast<QgsMarkerSymbolLayer*>( marker->symbolLayer( k ) ); - sizeExpression = QString( "%1*(%2)" ).arg( msl->size() ).arg( sizeScaleField ); - msl->setDataDefinedProperty( "size", new QgsDataDefined( sizeExpression ) ); + sizeExpression = QStringLiteral( "%1*(%2)" ).arg( msl->size() ).arg( sizeScaleField ); + msl->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( sizeExpression ) ); } } } diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.h b/src/core/symbology-ng/qgsrulebasedrenderer.h index e7e299939abf..f62b7cde9280 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.h +++ b/src/core/symbology-ng/qgsrulebasedrenderer.h @@ -145,7 +145,7 @@ class CORE_EXPORT QgsRuleBasedRenderer : public QgsFeatureRenderer QgsSymbolList symbols( const QgsRenderContext& context = QgsRenderContext() ) const; //! @note not available in python bindings - QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) const; + QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) const; //! @note added in 2.6 QgsLegendSymbolListV2 legendSymbolItemsV2( int currentLevel = -1 ) const; @@ -440,7 +440,7 @@ class CORE_EXPORT QgsRuleBasedRenderer : public QgsFeatureRenderer virtual void checkLegendSymbolItem( const QString& key, bool state = true ) override; virtual void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) override; - virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; + virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) override; virtual QgsLegendSymbolListV2 legendSymbolItemsV2() const override; virtual QString dump() const override; virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgssinglesymbolrenderer.cpp b/src/core/symbology-ng/qgssinglesymbolrenderer.cpp index a697c27418ef..9c3783511189 100644 --- a/src/core/symbology-ng/qgssinglesymbolrenderer.cpp +++ b/src/core/symbology-ng/qgssinglesymbolrenderer.cpp @@ -34,7 +34,7 @@ #include <QDomElement> QgsSingleSymbolRenderer::QgsSingleSymbolRenderer( QgsSymbol* symbol ) - : QgsFeatureRenderer( "singleSymbol" ) + : QgsFeatureRenderer( QStringLiteral( "singleSymbol" ) ) , mSymbol( symbol ) { Q_ASSERT( symbol ); @@ -93,7 +93,7 @@ void QgsSingleSymbolRenderer::setSymbol( QgsSymbol* s ) QString QgsSingleSymbolRenderer::dump() const { - return mSymbol.data() ? QString( "SINGLE: %1" ).arg( mSymbol->dump() ) : ""; + return mSymbol.data() ? QStringLiteral( "SINGLE: %1" ).arg( mSymbol->dump() ) : QLatin1String( "" ); } QgsSingleSymbolRenderer* QgsSingleSymbolRenderer::clone() const @@ -108,11 +108,11 @@ void QgsSingleSymbolRenderer::toSld( QDomDocument& doc, QDomElement &element, co { QgsStringMap newProps = props; - QDomElement ruleElem = doc.createElement( "se:Rule" ); + QDomElement ruleElem = doc.createElement( QStringLiteral( "se:Rule" ) ); element.appendChild( ruleElem ); - QDomElement nameElem = doc.createElement( "se:Name" ); - nameElem.appendChild( doc.createTextNode( "Single symbol" ) ); + QDomElement nameElem = doc.createElement( QStringLiteral( "se:Name" ) ); + nameElem.appendChild( doc.createTextNode( QStringLiteral( "Single symbol" ) ) ); ruleElem.appendChild( nameElem ); QgsSymbolLayerUtils::applyScaleDependency( doc, ruleElem, newProps ); @@ -131,32 +131,32 @@ QgsSymbolList QgsSingleSymbolRenderer::symbols( QgsRenderContext &context ) QgsFeatureRenderer* QgsSingleSymbolRenderer::create( QDomElement& element ) { - QDomElement symbolsElem = element.firstChildElement( "symbols" ); + QDomElement symbolsElem = element.firstChildElement( QStringLiteral( "symbols" ) ); if ( symbolsElem.isNull() ) return nullptr; QgsSymbolMap symbolMap = QgsSymbolLayerUtils::loadSymbols( symbolsElem ); - if ( !symbolMap.contains( "0" ) ) + if ( !symbolMap.contains( QStringLiteral( "0" ) ) ) return nullptr; - QgsSingleSymbolRenderer* r = new QgsSingleSymbolRenderer( symbolMap.take( "0" ) ); + QgsSingleSymbolRenderer* r = new QgsSingleSymbolRenderer( symbolMap.take( QStringLiteral( "0" ) ) ); // delete symbols if there are any more QgsSymbolLayerUtils::clearSymbolMap( symbolMap ); - QDomElement rotationElem = element.firstChildElement( "rotation" ); - if ( !rotationElem.isNull() && !rotationElem.attribute( "field" ).isEmpty() ) + QDomElement rotationElem = element.firstChildElement( QStringLiteral( "rotation" ) ); + if ( !rotationElem.isNull() && !rotationElem.attribute( QStringLiteral( "field" ) ).isEmpty() ) { - convertSymbolRotation( r->mSymbol.data(), rotationElem.attribute( "field" ) ); + convertSymbolRotation( r->mSymbol.data(), rotationElem.attribute( QStringLiteral( "field" ) ) ); } - QDomElement sizeScaleElem = element.firstChildElement( "sizescale" ); - if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( "field" ).isEmpty() ) + QDomElement sizeScaleElem = element.firstChildElement( QStringLiteral( "sizescale" ) ); + if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( QStringLiteral( "field" ) ).isEmpty() ) { convertSymbolSizeScale( r->mSymbol.data(), - QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( "scalemethod" ) ), - sizeScaleElem.attribute( "field" ) ); + QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( QStringLiteral( "scalemethod" ) ) ), + sizeScaleElem.attribute( QStringLiteral( "field" ) ) ); } // TODO: symbol levels @@ -168,7 +168,7 @@ QgsFeatureRenderer* QgsSingleSymbolRenderer::createFromSld( QDomElement& element // XXX this renderer can handle only one Rule! // get the first Rule element - QDomElement ruleElem = element.firstChildElement( "Rule" ); + QDomElement ruleElem = element.firstChildElement( QStringLiteral( "Rule" ) ); if ( ruleElem.isNull() ) { QgsDebugMsg( "no Rule elements found!" ); @@ -182,39 +182,39 @@ QgsFeatureRenderer* QgsSingleSymbolRenderer::createFromSld( QDomElement& element QDomElement childElem = ruleElem.firstChildElement(); while ( !childElem.isNull() ) { - if ( childElem.localName() == "Name" ) + if ( childElem.localName() == QLatin1String( "Name" ) ) { // <se:Name> tag contains the rule identifier, // so prefer title tag for the label property value if ( label.isEmpty() ) label = childElem.firstChild().nodeValue(); } - else if ( childElem.localName() == "Description" ) + else if ( childElem.localName() == QLatin1String( "Description" ) ) { // <se:Description> can contains a title and an abstract - QDomElement titleElem = childElem.firstChildElement( "Title" ); + QDomElement titleElem = childElem.firstChildElement( QStringLiteral( "Title" ) ); if ( !titleElem.isNull() ) { label = titleElem.firstChild().nodeValue(); } - QDomElement abstractElem = childElem.firstChildElement( "Abstract" ); + QDomElement abstractElem = childElem.firstChildElement( QStringLiteral( "Abstract" ) ); if ( !abstractElem.isNull() ) { description = abstractElem.firstChild().nodeValue(); } } - else if ( childElem.localName() == "Abstract" ) + else if ( childElem.localName() == QLatin1String( "Abstract" ) ) { // <sld:Abstract> (v1.0) description = childElem.firstChild().nodeValue(); } - else if ( childElem.localName() == "Title" ) + else if ( childElem.localName() == QLatin1String( "Title" ) ) { // <sld:Title> (v1.0) label = childElem.firstChild().nodeValue(); } - else if ( childElem.localName().endsWith( "Symbolizer" ) ) + else if ( childElem.localName().endsWith( QLatin1String( "Symbolizer" ) ) ) { // create symbol layers for this symbolizer QgsSymbolLayerUtils::createSymbolLayerListFromSld( childElem, geomType, layers ); @@ -254,19 +254,19 @@ QgsFeatureRenderer* QgsSingleSymbolRenderer::createFromSld( QDomElement& element QDomElement QgsSingleSymbolRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "singleSymbol" ); - rendererElem.setAttribute( "symbollevels", ( mUsingSymbolLevels ? "1" : "0" ) ); - rendererElem.setAttribute( "forceraster", ( mForceRaster ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singleSymbol" ) ); + rendererElem.setAttribute( QStringLiteral( "symbollevels" ), ( mUsingSymbolLevels ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? "1" : "0" ) ); QgsSymbolMap symbols; - symbols["0"] = mSymbol.data(); - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, "symbols", doc ); + symbols[QStringLiteral( "0" )] = mSymbol.data(); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, QStringLiteral( "symbols" ), doc ); rendererElem.appendChild( symbolsElem ); - QDomElement rotationElem = doc.createElement( "rotation" ); + QDomElement rotationElem = doc.createElement( QStringLiteral( "rotation" ) ); rendererElem.appendChild( rotationElem ); - QDomElement sizeScaleElem = doc.createElement( "sizescale" ); + QDomElement sizeScaleElem = doc.createElement( QStringLiteral( "sizescale" ) ); rendererElem.appendChild( sizeScaleElem ); if ( mPaintEffect && !QgsPaintEffectRegistry::isDefaultStack( mPaintEffect ) ) @@ -274,11 +274,11 @@ QDomElement QgsSingleSymbolRenderer::save( QDomDocument& doc ) if ( !mOrderBy.isEmpty() ) { - QDomElement orderBy = doc.createElement( "orderby" ); + QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) ); mOrderBy.save( orderBy ); rendererElem.appendChild( orderBy ); } - rendererElem.setAttribute( "enableorderby", ( mOrderByEnabled ? "1" : "0" ) ); + rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? "1" : "0" ) ); return rendererElem; } @@ -350,17 +350,17 @@ void QgsSingleSymbolRenderer::setLegendSymbolItem( const QString& key, QgsSymbol QgsSingleSymbolRenderer* QgsSingleSymbolRenderer::convertFromRenderer( const QgsFeatureRenderer *renderer ) { QgsSingleSymbolRenderer* r = nullptr; - if ( renderer->type() == "singleSymbol" ) + if ( renderer->type() == QLatin1String( "singleSymbol" ) ) { r = dynamic_cast<QgsSingleSymbolRenderer*>( renderer->clone() ); } - else if ( renderer->type() == "pointDisplacement" || renderer->type() == "pointCluster" ) + else if ( renderer->type() == QLatin1String( "pointDisplacement" ) || renderer->type() == QLatin1String( "pointCluster" ) ) { const QgsPointDistanceRenderer* pointDistanceRenderer = dynamic_cast<const QgsPointDistanceRenderer*>( renderer ); if ( pointDistanceRenderer ) r = convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ); } - else if ( renderer->type() == "invertedPolygonRenderer" ) + else if ( renderer->type() == QLatin1String( "invertedPolygonRenderer" ) ) { const QgsInvertedPolygonRenderer* invertedPolygonRenderer = dynamic_cast<const QgsInvertedPolygonRenderer*>( renderer ); if ( invertedPolygonRenderer ) diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index 834739d92c57..4410974001dc 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -105,7 +105,7 @@ bool QgsStyle::addSymbol( const QString& name, QgsSymbol* symbol, bool update ) bool QgsStyle::saveSymbol( const QString& name, QgsSymbol* symbol, int groupid, const QStringList& tags ) { // TODO add support for groups - QDomDocument doc( "dummy" ); + QDomDocument doc( QStringLiteral( "dummy" ) ); QDomElement symEl = QgsSymbolLayerUtils::saveSymbol( name, symbol, doc ); if ( symEl.isNull() ) { @@ -210,7 +210,7 @@ bool QgsStyle::addColorRamp( const QString& name, QgsColorRamp* colorRamp, bool bool QgsStyle::saveColorRamp( const QString& name, QgsColorRamp* ramp, int groupid, const QStringList& tags ) { // insert it into the database - QDomDocument doc( "dummy" ); + QDomDocument doc( QStringLiteral( "dummy" ) ); QDomElement rampEl = QgsSymbolLayerUtils::saveColorRamp( name, ramp, doc ); if ( rampEl.isNull() ) { @@ -295,7 +295,7 @@ bool QgsStyle::load( const QString& filename ) // Open the sqlite database if ( !openDB( filename ) ) { - mErrorString = "Unable to open database file specified"; + mErrorString = QStringLiteral( "Unable to open database file specified" ); QgsDebugMsg( mErrorString ); return false; } @@ -502,7 +502,7 @@ QgsSymbolGroupMap QgsStyle::childGroupNames( const QString& parent ) sqlite3_stmt *ppStmt; // decide the query to be run based on parent group - if ( parent == "" || parent == QString() ) + if ( parent == QLatin1String( "" ) || parent == QString() ) { query = sqlite3_mprintf( "SELECT * FROM symgroup WHERE parent=0" ); } @@ -699,7 +699,7 @@ void QgsStyle::rename( StyleEntity type, int id, const QString& newName ) return; } if ( !runEmptyQuery( query ) ) - mErrorString = "Could not rename!"; + mErrorString = QStringLiteral( "Could not rename!" ); } char* QgsStyle::getGroupRemoveQuery( int id ) @@ -830,7 +830,7 @@ QStringList QgsStyle::findSymbols( StyleEntity type, const QString& qword ) sqlite3_finalize( ppStmt ); - QString dummy = tagids.join( ", " ); + QString dummy = tagids.join( QStringLiteral( ", " ) ); if ( type == SymbolEntity ) { @@ -853,7 +853,7 @@ QStringList QgsStyle::findSymbols( StyleEntity type, const QString& qword ) sqlite3_finalize( ppStmt ); - dummy = symbolids.join( ", " ); + dummy = symbolids.join( QStringLiteral( ", " ) ); query = sqlite3_mprintf( "SELECT name FROM %q WHERE id IN (%q)", item.toUtf8().constData(), dummy.toUtf8().constData() ); nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL ); @@ -1054,52 +1054,52 @@ QString QgsStyle::getName( const QString& table, int id ) const int QgsStyle::symbolId( const QString& name ) { - return getId( "symbol", name ); + return getId( QStringLiteral( "symbol" ), name ); } int QgsStyle::colorrampId( const QString& name ) { - return getId( "colorramp", name ); + return getId( QStringLiteral( "colorramp" ), name ); } int QgsStyle::groupId( const QString& name ) { - return getId( "symgroup", name ); + return getId( QStringLiteral( "symgroup" ), name ); } QString QgsStyle::groupName( int groupId ) const { - return getName( "symgroup", groupId ); + return getName( QStringLiteral( "symgroup" ), groupId ); } int QgsStyle::tagId( const QString& name ) { - return getId( "tag", name ); + return getId( QStringLiteral( "tag" ), name ); } int QgsStyle::smartgroupId( const QString& name ) { - return getId( "smartgroup", name ); + return getId( QStringLiteral( "smartgroup" ), name ); } int QgsStyle::addSmartgroup( const QString& name, const QString& op, const QgsSmartConditionMap& conditions ) { - QDomDocument doc( "dummy" ); - QDomElement smartEl = doc.createElement( "smartgroup" ); - smartEl.setAttribute( "name", name ); - smartEl.setAttribute( "operator", op ); + QDomDocument doc( QStringLiteral( "dummy" ) ); + QDomElement smartEl = doc.createElement( QStringLiteral( "smartgroup" ) ); + smartEl.setAttribute( QStringLiteral( "name" ), name ); + smartEl.setAttribute( QStringLiteral( "operator" ), op ); QStringList constraints; - constraints << "tag" << "group" << "name" << "!tag" << "!group" << "!name"; + constraints << QStringLiteral( "tag" ) << QStringLiteral( "group" ) << QStringLiteral( "name" ) << QStringLiteral( "!tag" ) << QStringLiteral( "!group" ) << QStringLiteral( "!name" ); Q_FOREACH ( const QString &constraint, constraints ) { QStringList parameters = conditions.values( constraint ); Q_FOREACH ( const QString ¶m, parameters ) { - QDomElement condEl = doc.createElement( "condition" ); - condEl.setAttribute( "constraint", constraint ); - condEl.setAttribute( "param", param ); + QDomElement condEl = doc.createElement( QStringLiteral( "condition" ) ); + condEl.setAttribute( QStringLiteral( "constraint" ), constraint ); + condEl.setAttribute( QStringLiteral( "param" ), param ); smartEl.appendChild( condEl ); } } @@ -1195,29 +1195,29 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) QgsDebugMsg( QString( "Cannot open smartgroup id: %1" ).arg( id ) ); } QDomElement smartEl = doc.documentElement(); - QString op = smartEl.attribute( "operator" ); + QString op = smartEl.attribute( QStringLiteral( "operator" ) ); QDomNodeList conditionNodes = smartEl.childNodes(); bool firstSet = true; for ( int i = 0; i < conditionNodes.count(); i++ ) { QDomElement condEl = conditionNodes.at( i ).toElement(); - QString constraint = condEl.attribute( "constraint" ); - QString param = condEl.attribute( "param" ); + QString constraint = condEl.attribute( QStringLiteral( "constraint" ) ); + QString param = condEl.attribute( QStringLiteral( "param" ) ); QStringList resultNames; // perform suitable action for the given constraint - if ( constraint == "tag" ) + if ( constraint == QLatin1String( "tag" ) ) { resultNames = symbolsWithTag( type, tagId( param ) ); } - else if ( constraint == "group" ) + else if ( constraint == QLatin1String( "group" ) ) { // XXX Validating group id might be a good idea here resultNames = symbolsOfGroup( type, groupId( param ) ); } - else if ( constraint == "name" ) + else if ( constraint == QLatin1String( "name" ) ) { if ( type == SymbolEntity ) { @@ -1228,7 +1228,7 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) resultNames = colorRampNames().filter( param, Qt::CaseInsensitive ); } } - else if ( constraint == "!tag" ) + else if ( constraint == QLatin1String( "!tag" ) ) { resultNames = type == SymbolEntity ? symbolNames() : colorRampNames(); QStringList unwanted = symbolsWithTag( type, tagId( param ) ); @@ -1237,7 +1237,7 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) resultNames.removeAll( name ); } } - else if ( constraint == "!group" ) + else if ( constraint == QLatin1String( "!group" ) ) { resultNames = type == SymbolEntity ? symbolNames() : colorRampNames(); QStringList unwanted = symbolsOfGroup( type, groupId( param ) ); @@ -1246,7 +1246,7 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) resultNames.removeAll( name ); } } - else if ( constraint == "!name" ) + else if ( constraint == QLatin1String( "!name" ) ) { QStringList all = type == SymbolEntity ? symbolNames() : colorRampNames(); Q_FOREACH ( const QString &str, all ) @@ -1264,11 +1264,11 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) } else { - if ( op == "OR" ) + if ( op == QLatin1String( "OR" ) ) { symbols << resultNames; } - else if ( op == "AND" ) + else if ( op == QLatin1String( "AND" ) ) { QStringList dummy = symbols; symbols.clear(); @@ -1316,8 +1316,8 @@ QgsSmartConditionMap QgsStyle::smartgroup( int id ) for ( int i = 0; i < conditionNodes.count(); i++ ) { QDomElement condEl = conditionNodes.at( i ).toElement(); - QString constraint = condEl.attribute( "constraint" ); - QString param = condEl.attribute( "param" ); + QString constraint = condEl.attribute( QStringLiteral( "constraint" ) ); + QString param = condEl.attribute( QStringLiteral( "param" ) ); condition.insert( constraint, param ); } @@ -1351,7 +1351,7 @@ QString QgsStyle::smartgroupOperator( int id ) QgsDebugMsg( QString( "Cannot open smartgroup id: %1" ).arg( id ) ); } QDomElement smartEl = doc.documentElement(); - op = smartEl.attribute( "operator" ); + op = smartEl.attribute( QStringLiteral( "operator" ) ); } sqlite3_finalize( ppStmt ); @@ -1367,14 +1367,14 @@ bool QgsStyle::exportXml( const QString& filename ) return false; } - QDomDocument doc( "qgis_style" ); - QDomElement root = doc.createElement( "qgis_style" ); - root.setAttribute( "version", STYLE_CURRENT_VERSION ); + QDomDocument doc( QStringLiteral( "qgis_style" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgis_style" ) ); + root.setAttribute( QStringLiteral( "version" ), STYLE_CURRENT_VERSION ); doc.appendChild( root ); // TODO work on the groups and tags - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( mSymbols, "symbols", doc ); - QDomElement rampsElem = doc.createElement( "colorramps" ); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( mSymbols, QStringLiteral( "symbols" ), doc ); + QDomElement rampsElem = doc.createElement( QStringLiteral( "colorramps" ) ); // save color ramps for ( QMap<QString, QgsColorRamp*>::const_iterator itr = mColorRamps.constBegin(); itr != mColorRamps.constEnd(); ++itr ) @@ -1406,18 +1406,18 @@ bool QgsStyle::exportXml( const QString& filename ) bool QgsStyle::importXml( const QString& filename ) { mErrorString = QString(); - QDomDocument doc( "style" ); + QDomDocument doc( QStringLiteral( "style" ) ); QFile f( filename ); if ( !f.open( QFile::ReadOnly ) ) { - mErrorString = "Unable to open the specified file"; + mErrorString = QStringLiteral( "Unable to open the specified file" ); QgsDebugMsg( "Error opening the style XML file." ); return false; } if ( !doc.setContent( &f ) ) { - mErrorString = QString( "Unable to understand the style file: %1" ).arg( filename ); + mErrorString = QStringLiteral( "Unable to understand the style file: %1" ).arg( filename ); QgsDebugMsg( "XML Parsing error" ); f.close(); return false; @@ -1425,14 +1425,14 @@ bool QgsStyle::importXml( const QString& filename ) f.close(); QDomElement docEl = doc.documentElement(); - if ( docEl.tagName() != "qgis_style" ) + if ( docEl.tagName() != QLatin1String( "qgis_style" ) ) { mErrorString = "Incorrect root tag in style: " + docEl.tagName(); return false; } - QString version = docEl.attribute( "version" ); - if ( version != STYLE_CURRENT_VERSION && version != "0" ) + QString version = docEl.attribute( QStringLiteral( "version" ) ); + if ( version != STYLE_CURRENT_VERSION && version != QLatin1String( "0" ) ) { mErrorString = "Unknown style file version: " + version; return false; @@ -1440,7 +1440,7 @@ bool QgsStyle::importXml( const QString& filename ) QgsSymbolMap symbols; - QDomElement symbolsElement = docEl.firstChildElement( "symbols" ); + QDomElement symbolsElement = docEl.firstChildElement( QStringLiteral( "symbols" ) ); QDomElement e = symbolsElement.firstChildElement(); if ( version == STYLE_CURRENT_VERSION ) @@ -1448,12 +1448,12 @@ bool QgsStyle::importXml( const QString& filename ) // For the new style, load symbols individualy while ( !e.isNull() ) { - if ( e.tagName() == "symbol" ) + if ( e.tagName() == QLatin1String( "symbol" ) ) { QgsSymbol* symbol = QgsSymbolLayerUtils::loadSymbol( e ); if ( symbol ) { - symbols.insert( e.attribute( "name" ), symbol ); + symbols.insert( e.attribute( QStringLiteral( "name" ) ), symbol ); } } else @@ -1476,16 +1476,16 @@ bool QgsStyle::importXml( const QString& filename ) } // load color ramps - QDomElement rampsElement = docEl.firstChildElement( "colorramps" ); + QDomElement rampsElement = docEl.firstChildElement( QStringLiteral( "colorramps" ) ); e = rampsElement.firstChildElement(); while ( !e.isNull() ) { - if ( e.tagName() == "colorramp" ) + if ( e.tagName() == QLatin1String( "colorramp" ) ) { QgsColorRamp* ramp = QgsSymbolLayerUtils::loadColorRamp( e ); if ( ramp ) { - addColorRamp( e.attribute( "name" ), ramp ); + addColorRamp( e.attribute( QStringLiteral( "name" ) ), ramp ); } } else @@ -1501,7 +1501,7 @@ bool QgsStyle::importXml( const QString& filename ) bool QgsStyle::updateSymbol( StyleEntity type, const QString& name ) { - QDomDocument doc( "dummy" ); + QDomDocument doc( QStringLiteral( "dummy" ) ); QDomElement symEl; QByteArray xmlArray; QTextStream stream( &xmlArray ); diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index 6c0edcf32629..4593e1ed84a8 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -131,7 +131,7 @@ class CORE_EXPORT QgsStyle : public QObject QStringList tags() const; //! return a map of groupid and names for the given parent group - QgsSymbolGroupMap childGroupNames( const QString& parent = "" ); + QgsSymbolGroupMap childGroupNames( const QString& parent = QStringLiteral( "" ) ); //! remove all contents of the style void clear(); diff --git a/src/core/symbology-ng/qgssvgcache.cpp b/src/core/symbology-ng/qgssvgcache.cpp index f35b0c086f2d..ab36f84630fe 100644 --- a/src/core/symbology-ng/qgssvgcache.cpp +++ b/src/core/symbology-ng/qgssvgcache.cpp @@ -106,7 +106,7 @@ QgsSvgCache::QgsSvgCache( QObject *parent ) , mLeastRecentEntry( nullptr ) , mMostRecentEntry( nullptr ) { - mMissingSvg = QString( "<svg width='10' height='10'><text x='5' y='10' font-size='10' text-anchor='middle'>?</text></svg>" ).toLatin1(); + mMissingSvg = QStringLiteral( "<svg width='10' height='10'><text x='5' y='10' font-size='10' text-anchor='middle'>?</text></svg>" ).toLatin1(); } QgsSvgCache::~QgsSvgCache() @@ -328,23 +328,23 @@ double QgsSvgCache::calcSizeScaleFactor( QgsSvgCacheEntry* entry, const QDomElem //find svg viewbox attribute //first check if docElem is svg element - if ( docElem.tagName() == "svg" && docElem.hasAttribute( "viewBox" ) ) + if ( docElem.tagName() == QLatin1String( "svg" ) && docElem.hasAttribute( QStringLiteral( "viewBox" ) ) ) { - viewBox = docElem.attribute( "viewBox", QString() ); + viewBox = docElem.attribute( QStringLiteral( "viewBox" ), QString() ); } - else if ( docElem.tagName() == "svg" && docElem.hasAttribute( "viewbox" ) ) + else if ( docElem.tagName() == QLatin1String( "svg" ) && docElem.hasAttribute( QStringLiteral( "viewbox" ) ) ) { - viewBox = docElem.attribute( "viewbox", QString() ); + viewBox = docElem.attribute( QStringLiteral( "viewbox" ), QString() ); } else { - QDomElement svgElem = docElem.firstChildElement( "svg" ) ; + QDomElement svgElem = docElem.firstChildElement( QStringLiteral( "svg" ) ) ; if ( !svgElem.isNull() ) { - if ( svgElem.hasAttribute( "viewBox" ) ) - viewBox = svgElem.attribute( "viewBox", QString() ); - else if ( svgElem.hasAttribute( "viewbox" ) ) - viewBox = svgElem.attribute( "viewbox", QString() ); + if ( svgElem.hasAttribute( QStringLiteral( "viewBox" ) ) ) + viewBox = svgElem.attribute( QStringLiteral( "viewBox" ), QString() ); + else if ( svgElem.hasAttribute( QStringLiteral( "viewbox" ) ) ) + viewBox = svgElem.attribute( QStringLiteral( "viewbox" ), QString() ); } } @@ -389,7 +389,7 @@ QByteArray QgsSvgCache::getImageData( const QString &path ) const } // maybe it's a url... - if ( !path.contains( "://" ) ) // otherwise short, relative SVG paths might be considered URLs + if ( !path.contains( QLatin1String( "://" ) ) ) // otherwise short, relative SVG paths might be considered URLs { return mMissingSvg; } @@ -401,7 +401,7 @@ QByteArray QgsSvgCache::getImageData( const QString &path ) const } // check whether it's a url pointing to a local file - if ( svgUrl.scheme().compare( "file", Qt::CaseInsensitive ) == 0 ) + if ( svgUrl.scheme().compare( QLatin1String( "file" ), Qt::CaseInsensitive ) == 0 ) { svgFile.setFileName( svgUrl.toLocalFile() ); if ( svgFile.exists() ) @@ -474,7 +474,7 @@ QByteArray QgsSvgCache::getImageData( const QString &path ) const QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString(); QgsDebugMsg( "contentType: " + contentType ); - if ( !contentType.startsWith( "image/svg+xml", Qt::CaseInsensitive ) ) + if ( !contentType.startsWith( QLatin1String( "image/svg+xml" ), Qt::CaseInsensitive ) ) { reply->deleteLater(); return mMissingSvg; @@ -632,7 +632,7 @@ void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, cons { QDomAttr attribute = attributes.item( i ).toAttr(); //e.g. style="fill:param(fill);param(stroke)" - if ( attribute.name().compare( "style", Qt::CaseInsensitive ) == 0 ) + if ( attribute.name().compare( QLatin1String( "style" ), Qt::CaseInsensitive ) == 0 ) { //entries separated by ';' QString newAttributeString; @@ -648,23 +648,23 @@ void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, cons } QString key = keyValueSplit.at( 0 ); QString value = keyValueSplit.at( 1 ); - if ( value.startsWith( "param(fill)" ) ) + if ( value.startsWith( QLatin1String( "param(fill)" ) ) ) { value = fill.name(); } - else if ( value.startsWith( "param(fill-opacity)" ) ) + else if ( value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { value = fill.alphaF(); } - else if ( value.startsWith( "param(outline)" ) ) + else if ( value.startsWith( QLatin1String( "param(outline)" ) ) ) { value = outline.name(); } - else if ( value.startsWith( "param(outline-opacity)" ) ) + else if ( value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { value = outline.alphaF(); } - else if ( value.startsWith( "param(outline-width)" ) ) + else if ( value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { value = QString::number( outlineWidth ); } @@ -680,23 +680,23 @@ void QgsSvgCache::replaceElemParams( QDomElement& elem, const QColor& fill, cons else { QString value = attribute.value(); - if ( value.startsWith( "param(fill)" ) ) + if ( value.startsWith( QLatin1String( "param(fill)" ) ) ) { elem.setAttribute( attribute.name(), fill.name() ); } - else if ( value.startsWith( "param(fill-opacity)" ) ) + else if ( value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { elem.setAttribute( attribute.name(), fill.alphaF() ); } - else if ( value.startsWith( "param(outline)" ) ) + else if ( value.startsWith( QLatin1String( "param(outline)" ) ) ) { elem.setAttribute( attribute.name(), outline.name() ); } - else if ( value.startsWith( "param(outline-opacity)" ) ) + else if ( value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { elem.setAttribute( attribute.name(), outline.alphaF() ); } - else if ( value.startsWith( "param(outline-width)" ) ) + else if ( value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { elem.setAttribute( attribute.name(), QString::number( outlineWidth ) ); } @@ -737,7 +737,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara for ( int i = 0; i < nAttributes; ++i ) { QDomAttr attribute = attributes.item( i ).toAttr(); - if ( attribute.name().compare( "style", Qt::CaseInsensitive ) == 0 ) + if ( attribute.name().compare( QLatin1String( "style" ), Qt::CaseInsensitive ) == 0 ) { //entries separated by ';' QStringList entryList = attribute.value().split( ';' ); @@ -751,7 +751,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara } QString value = keyValueSplit.at( 1 ); valueSplit = value.split( ' ' ); - if ( !hasFillParam && value.startsWith( "param(fill)" ) ) + if ( !hasFillParam && value.startsWith( QLatin1String( "param(fill)" ) ) ) { hasFillParam = true; if ( valueSplit.size() > 1 ) @@ -760,7 +760,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara hasDefaultFill = true; } } - else if ( !hasFillOpacityParam && value.startsWith( "param(fill-opacity)" ) ) + else if ( !hasFillOpacityParam && value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { hasFillOpacityParam = true; if ( valueSplit.size() > 1 ) @@ -774,7 +774,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara } } } - else if ( !hasOutlineParam && value.startsWith( "param(outline)" ) ) + else if ( !hasOutlineParam && value.startsWith( QLatin1String( "param(outline)" ) ) ) { hasOutlineParam = true; if ( valueSplit.size() > 1 ) @@ -783,7 +783,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara hasDefaultOutline = true; } } - else if ( !hasOutlineWidthParam && value.startsWith( "param(outline-width)" ) ) + else if ( !hasOutlineWidthParam && value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { hasOutlineWidthParam = true; if ( valueSplit.size() > 1 ) @@ -792,7 +792,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara hasDefaultOutlineWidth = true; } } - else if ( !hasOutlineOpacityParam && value.startsWith( "param(outline-opacity)" ) ) + else if ( !hasOutlineOpacityParam && value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { hasOutlineOpacityParam = true; if ( valueSplit.size() > 1 ) @@ -812,7 +812,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara { QString value = attribute.value(); valueSplit = value.split( ' ' ); - if ( !hasFillParam && value.startsWith( "param(fill)" ) ) + if ( !hasFillParam && value.startsWith( QLatin1String( "param(fill)" ) ) ) { hasFillParam = true; if ( valueSplit.size() > 1 ) @@ -821,7 +821,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara hasDefaultFill = true; } } - else if ( !hasFillOpacityParam && value.startsWith( "param(fill-opacity)" ) ) + else if ( !hasFillOpacityParam && value.startsWith( QLatin1String( "param(fill-opacity)" ) ) ) { hasFillOpacityParam = true; if ( valueSplit.size() > 1 ) @@ -835,7 +835,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara } } } - else if ( !hasOutlineParam && value.startsWith( "param(outline)" ) ) + else if ( !hasOutlineParam && value.startsWith( QLatin1String( "param(outline)" ) ) ) { hasOutlineParam = true; if ( valueSplit.size() > 1 ) @@ -844,7 +844,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara hasDefaultOutline = true; } } - else if ( !hasOutlineWidthParam && value.startsWith( "param(outline-width)" ) ) + else if ( !hasOutlineWidthParam && value.startsWith( QLatin1String( "param(outline-width)" ) ) ) { hasOutlineWidthParam = true; if ( valueSplit.size() > 1 ) @@ -853,7 +853,7 @@ void QgsSvgCache::containsElemParams( const QDomElement& elem, bool& hasFillPara hasDefaultOutlineWidth = true; } } - else if ( !hasOutlineOpacityParam && value.startsWith( "param(outline-opacity)" ) ) + else if ( !hasOutlineOpacityParam && value.startsWith( QLatin1String( "param(outline-opacity)" ) ) ) { hasOutlineOpacityParam = true; if ( valueSplit.size() > 1 ) @@ -953,7 +953,7 @@ void QgsSvgCache::takeEntryFromList( QgsSvgCacheEntry* entry ) void QgsSvgCache::downloadProgress( qint64 bytesReceived, qint64 bytesTotal ) { - QString msg = tr( "%1 of %2 bytes of svg image downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QString( "unknown number of" ) : QString::number( bytesTotal ) ); + QString msg = tr( "%1 of %2 bytes of svg image downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QStringLiteral( "unknown number of" ) : QString::number( bytesTotal ) ); QgsDebugMsg( msg ); emit statusChanged( msg ); } diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index bfde6421f6ce..f5ecd8a24738 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -75,9 +75,9 @@ QgsDataDefined* scaleWholeSymbol( double scaleFactorX, double scaleFactorY, cons QgsDataDefined* scaledDD = new QgsDataDefined( dd ); QString exprString = dd.useExpression() ? dd.expressionString() : dd.field(); scaledDD->setExpressionString( - ( !qgsDoubleNear( scaleFactorX, 0.0 ) ? "tostring(" + QString::number( scaleFactorX ) + "*(" + exprString + "))" : "'0'" ) + + ( !qgsDoubleNear( scaleFactorX, 0.0 ) ? "tostring(" + QString::number( scaleFactorX ) + "*(" + exprString + "))" : QStringLiteral( "'0'" ) ) + "|| ',' || " + - ( !qgsDoubleNear( scaleFactorY, 0.0 ) ? "tostring(" + QString::number( scaleFactorY ) + "*(" + exprString + "))" : "'0'" ) ); + ( !qgsDoubleNear( scaleFactorY, 0.0 ) ? "tostring(" + QString::number( scaleFactorY ) + "*(" + exprString + "))" : QStringLiteral( "'0'" ) ) ); scaledDD->setUseExpression( true ); return scaledDD; } @@ -272,19 +272,19 @@ QgsSymbol* QgsSymbol::defaultSymbol( QgsWkbTypes::GeometryType geomType ) switch ( geomType ) { case QgsWkbTypes::PointGeometry : - defaultSymbol = QgsProject::instance()->readEntry( "DefaultStyles", "/Marker", "" ); + defaultSymbol = QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Marker" ), QLatin1String( "" ) ); break; case QgsWkbTypes::LineGeometry : - defaultSymbol = QgsProject::instance()->readEntry( "DefaultStyles", "/Line", "" ); + defaultSymbol = QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Line" ), QLatin1String( "" ) ); break; case QgsWkbTypes::PolygonGeometry : - defaultSymbol = QgsProject::instance()->readEntry( "DefaultStyles", "/Fill", "" ); + defaultSymbol = QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/Fill" ), QLatin1String( "" ) ); break; default: - defaultSymbol = ""; + defaultSymbol = QLatin1String( "" ); break; } - if ( defaultSymbol != "" ) + if ( defaultSymbol != QLatin1String( "" ) ) s = QgsStyle::defaultStyle()->symbol( defaultSymbol ); // if no default found for this type, get global default (as previously) @@ -308,11 +308,11 @@ QgsSymbol* QgsSymbol::defaultSymbol( QgsWkbTypes::GeometryType geomType ) } // set alpha transparency - s->setAlpha( QgsProject::instance()->readDoubleEntry( "DefaultStyles", "/AlphaInt", 255 ) / 255.0 ); + s->setAlpha( QgsProject::instance()->readDoubleEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/AlphaInt" ), 255 ) / 255.0 ); // set random color, it project prefs allow - if ( defaultSymbol == "" || - QgsProject::instance()->readBoolEntry( "DefaultStyles", "/RandomColors", true ) ) + if ( defaultSymbol == QLatin1String( "" ) || + QgsProject::instance()->readBoolEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/RandomColors" ), true ) ) { s->setColor( QColor::fromHsv( qrand() % 360, 64 + qrand() % 192, 128 + qrand() % 128 ) ); } @@ -478,7 +478,7 @@ void QgsSymbol::drawPreviewIcon( QPainter* painter, QSize size, QgsRenderContext void QgsSymbol::exportImage( const QString& path, const QString& format, QSize size ) { - if ( format.toLower() == "svg" ) + if ( format.toLower() == QLatin1String( "svg" ) ) { QSvgGenerator generator; generator.setFileName( path ); @@ -560,18 +560,18 @@ QString QgsSymbol::dump() const switch ( type() ) { case QgsSymbol::Marker: - t = "MARKER"; + t = QStringLiteral( "MARKER" ); break; case QgsSymbol::Line: - t = "LINE"; + t = QStringLiteral( "LINE" ); break; case QgsSymbol::Fill: - t = "FILL"; + t = QStringLiteral( "FILL" ); break; default: Q_ASSERT( 0 && "unknown symbol type" ); } - QString s = QString( "%1 SYMBOL (%2 layers) color %3" ).arg( t ).arg( mLayers.count() ).arg( QgsSymbolLayerUtils::encodeColor( color() ) ); + QString s = QStringLiteral( "%1 SYMBOL (%2 layers) color %3" ).arg( t ).arg( mLayers.count() ).arg( QgsSymbolLayerUtils::encodeColor( color() ) ); for ( QgsSymbolLayerList::const_iterator it = mLayers.begin(); it != mLayers.end(); ++it ) { @@ -582,10 +582,10 @@ QString QgsSymbol::dump() const void QgsSymbol::toSld( QDomDocument &doc, QDomElement &element, QgsStringMap props ) const { - props[ "alpha" ] = QString::number( alpha() ); + props[ QStringLiteral( "alpha" )] = QString::number( alpha() ); double scaleFactor = 1.0; - props[ "uom" ] = QgsSymbolLayerUtils::encodeSldUom( outputUnit(), &scaleFactor ); - props[ "uomScale" ] = ( !qgsDoubleNear( scaleFactor, 1.0 ) ? qgsDoubleToString( scaleFactor ) : "" ); + props[ QStringLiteral( "uom" )] = QgsSymbolLayerUtils::encodeSldUom( outputUnit(), &scaleFactor ); + props[ QStringLiteral( "uomScale" )] = ( !qgsDoubleNear( scaleFactor, 1.0 ) ? qgsDoubleToString( scaleFactor ) : QLatin1String( "" ) ); for ( QgsSymbolLayerList::const_iterator it = mLayers.begin(); it != mLayers.end(); ++it ) { @@ -1130,18 +1130,18 @@ void QgsMarkerSymbol::setDataDefinedAngle( const QgsDataDefined& dd ) const QgsMarkerSymbolLayer* markerLayer = static_cast<const QgsMarkerSymbolLayer*>( layer ); if ( dd.hasDefaultValues() ) { - layer->removeDataDefinedProperty( "angle" ); + layer->removeDataDefinedProperty( QStringLiteral( "angle" ) ); } else { if ( qgsDoubleNear( markerLayer->angle(), symbolRotation ) ) { - layer->setDataDefinedProperty( "angle", new QgsDataDefined( dd ) ); + layer->setDataDefinedProperty( QStringLiteral( "angle" ), new QgsDataDefined( dd ) ); } else { QgsDataDefined* rotatedDD = rotateWholeSymbol( markerLayer->angle() - symbolRotation, dd ); - layer->setDataDefinedProperty( "angle", rotatedDD ); + layer->setDataDefinedProperty( QStringLiteral( "angle" ), rotatedDD ); } } } @@ -1158,9 +1158,9 @@ QgsDataDefined QgsMarkerSymbol::dataDefinedAngle() const if ( layer->type() != QgsSymbol::Marker ) continue; const QgsMarkerSymbolLayer* markerLayer = static_cast<const QgsMarkerSymbolLayer*>( layer ); - if ( qgsDoubleNear( markerLayer->angle(), symbolRotation ) && markerLayer->getDataDefinedProperty( "angle" ) ) + if ( qgsDoubleNear( markerLayer->angle(), symbolRotation ) && markerLayer->getDataDefinedProperty( QStringLiteral( "angle" ) ) ) { - symbolDD = markerLayer->getDataDefinedProperty( "angle" ); + symbolDD = markerLayer->getDataDefinedProperty( QStringLiteral( "angle" ) ); break; } } @@ -1174,7 +1174,7 @@ QgsDataDefined QgsMarkerSymbol::dataDefinedAngle() const if ( layer->type() != QgsSymbol::Marker ) continue; const QgsMarkerSymbolLayer* markerLayer = static_cast<const QgsMarkerSymbolLayer*>( layer ); - QgsDataDefined* layerAngleDD = markerLayer->getDataDefinedProperty( "angle" ); + QgsDataDefined* layerAngleDD = markerLayer->getDataDefinedProperty( QStringLiteral( "angle" ) ); if ( qgsDoubleNear( markerLayer->angle(), symbolRotation ) ) { @@ -1304,23 +1304,23 @@ void QgsMarkerSymbol::setDataDefinedSize( const QgsDataDefined &dd ) if ( dd.hasDefaultValues() ) { - markerLayer->removeDataDefinedProperty( "size" ); - markerLayer->removeDataDefinedProperty( "offset" ); + markerLayer->removeDataDefinedProperty( QStringLiteral( "size" ) ); + markerLayer->removeDataDefinedProperty( QStringLiteral( "offset" ) ); } else { if ( qgsDoubleNear( symbolSize, 0.0 ) || qgsDoubleNear( markerLayer->size(), symbolSize ) ) { - markerLayer->setDataDefinedProperty( "size", new QgsDataDefined( dd ) ); + markerLayer->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( dd ) ); } else { - markerLayer->setDataDefinedProperty( "size", scaleWholeSymbol( markerLayer->size() / symbolSize, dd ) ); + markerLayer->setDataDefinedProperty( QStringLiteral( "size" ), scaleWholeSymbol( markerLayer->size() / symbolSize, dd ) ); } if ( !qgsDoubleNear( markerLayer->offset().x(), 0.0 ) || !qgsDoubleNear( markerLayer->offset().y(), 0.0 ) ) { - markerLayer->setDataDefinedProperty( "offset", scaleWholeSymbol( + markerLayer->setDataDefinedProperty( QStringLiteral( "offset" ), scaleWholeSymbol( markerLayer->offset().x() / symbolSize, markerLayer->offset().y() / symbolSize, dd ) ); } @@ -1340,9 +1340,9 @@ QgsDataDefined QgsMarkerSymbol::dataDefinedSize() const if ( layer->type() != QgsSymbol::Marker ) continue; const QgsMarkerSymbolLayer* markerLayer = static_cast<const QgsMarkerSymbolLayer*>( layer ); - if ( qgsDoubleNear( markerLayer->size(), symbolSize ) && markerLayer->getDataDefinedProperty( "size" ) ) + if ( qgsDoubleNear( markerLayer->size(), symbolSize ) && markerLayer->getDataDefinedProperty( QStringLiteral( "size" ) ) ) { - symbolDD = markerLayer->getDataDefinedProperty( "size" ); + symbolDD = markerLayer->getDataDefinedProperty( QStringLiteral( "size" ) ); break; } } @@ -1357,8 +1357,8 @@ QgsDataDefined QgsMarkerSymbol::dataDefinedSize() const continue; const QgsMarkerSymbolLayer* markerLayer = static_cast<const QgsMarkerSymbolLayer*>( layer ); - QgsDataDefined* layerSizeDD = markerLayer->getDataDefinedProperty( "size" ); - QgsDataDefined* layerOffsetDD = markerLayer->getDataDefinedProperty( "offset" ); + QgsDataDefined* layerSizeDD = markerLayer->getDataDefinedProperty( QStringLiteral( "size" ) ); + QgsDataDefined* layerOffsetDD = markerLayer->getDataDefinedProperty( QStringLiteral( "offset" ) ); if ( qgsDoubleNear( markerLayer->size(), symbolSize ) ) { @@ -1572,23 +1572,23 @@ void QgsLineSymbol::setDataDefinedWidth( const QgsDataDefined& dd ) { if ( dd.hasDefaultValues() ) { - lineLayer->removeDataDefinedProperty( "width" ); - lineLayer->removeDataDefinedProperty( "offset" ); + lineLayer->removeDataDefinedProperty( QStringLiteral( "width" ) ); + lineLayer->removeDataDefinedProperty( QStringLiteral( "offset" ) ); } else { if ( qgsDoubleNear( symbolWidth, 0.0 ) || qgsDoubleNear( lineLayer->width(), symbolWidth ) ) { - lineLayer->setDataDefinedProperty( "width", new QgsDataDefined( dd ) ); + lineLayer->setDataDefinedProperty( QStringLiteral( "width" ), new QgsDataDefined( dd ) ); } else { - lineLayer->setDataDefinedProperty( "width", scaleWholeSymbol( lineLayer->width() / symbolWidth, dd ) ); + lineLayer->setDataDefinedProperty( QStringLiteral( "width" ), scaleWholeSymbol( lineLayer->width() / symbolWidth, dd ) ); } if ( !qgsDoubleNear( lineLayer->offset(), 0.0 ) ) { - lineLayer->setDataDefinedProperty( "offset", scaleWholeSymbol( lineLayer->offset() / symbolWidth, dd ) ); + lineLayer->setDataDefinedProperty( QStringLiteral( "offset" ), scaleWholeSymbol( lineLayer->offset() / symbolWidth, dd ) ); } } } @@ -1605,9 +1605,9 @@ QgsDataDefined QgsLineSymbol::dataDefinedWidth() const for ( QgsSymbolLayerList::const_iterator it = mLayers.begin(); it != mLayers.end(); ++it ) { const QgsLineSymbolLayer* layer = dynamic_cast<const QgsLineSymbolLayer*>( *it ); - if ( layer && qgsDoubleNear( layer->width(), symbolWidth ) && layer->getDataDefinedProperty( "width" ) ) + if ( layer && qgsDoubleNear( layer->width(), symbolWidth ) && layer->getDataDefinedProperty( QStringLiteral( "width" ) ) ) { - symbolDD = layer->getDataDefinedProperty( "width" ); + symbolDD = layer->getDataDefinedProperty( QStringLiteral( "width" ) ); break; } } @@ -1622,8 +1622,8 @@ QgsDataDefined QgsLineSymbol::dataDefinedWidth() const continue; const QgsLineSymbolLayer* lineLayer = static_cast<const QgsLineSymbolLayer*>( layer ); - QgsDataDefined* layerWidthDD = lineLayer->getDataDefinedProperty( "width" ); - QgsDataDefined* layerOffsetDD = lineLayer->getDataDefinedProperty( "offset" ); + QgsDataDefined* layerWidthDD = lineLayer->getDataDefinedProperty( QStringLiteral( "width" ) ); + QgsDataDefined* layerOffsetDD = lineLayer->getDataDefinedProperty( QStringLiteral( "offset" ) ); if ( qgsDoubleNear( lineLayer->width(), symbolWidth ) ) { diff --git a/src/core/symbology-ng/qgssymbollayer.cpp b/src/core/symbology-ng/qgssymbollayer.cpp index 9e9ed17efc79..fcf04070c372 100644 --- a/src/core/symbology-ng/qgssymbollayer.cpp +++ b/src/core/symbology-ng/qgssymbollayer.cpp @@ -31,65 +31,65 @@ #include <QPointF> #include <QPolygonF> -const QString QgsSymbolLayer::EXPR_SIZE( "size" ); -const QString QgsSymbolLayer::EXPR_ANGLE( "angle" ); -const QString QgsSymbolLayer::EXPR_NAME( "name" ); -const QString QgsSymbolLayer::EXPR_COLOR( "color" ); -const QString QgsSymbolLayer::EXPR_COLOR_BORDER( "color_border" ); -const QString QgsSymbolLayer::EXPR_OUTLINE_WIDTH( "outline_width" ); -const QString QgsSymbolLayer::EXPR_OUTLINE_STYLE( "outline_style" ); -const QString QgsSymbolLayer::EXPR_FILL( "fill" ); -const QString QgsSymbolLayer::EXPR_OUTLINE( "outline" ); -const QString QgsSymbolLayer::EXPR_OFFSET( "offset" ); -const QString QgsSymbolLayer::EXPR_CHAR( "char" ); -const QString QgsSymbolLayer::EXPR_FILL_COLOR( "fill_color" ); -const QString QgsSymbolLayer::EXPR_OUTLINE_COLOR( "outline_color" ); -const QString QgsSymbolLayer::EXPR_WIDTH( "width" ); -const QString QgsSymbolLayer::EXPR_HEIGHT( "height" ); -const QString QgsSymbolLayer::EXPR_SYMBOL_NAME( "symbol_name" ); -const QString QgsSymbolLayer::EXPR_ROTATION( "rotation" ); -const QString QgsSymbolLayer::EXPR_FILL_STYLE( "fill_style" ); -const QString QgsSymbolLayer::EXPR_WIDTH_BORDER( "width_border" ); -const QString QgsSymbolLayer::EXPR_BORDER_STYLE( "border_style" ); -const QString QgsSymbolLayer::EXPR_JOIN_STYLE( "join_style" ); -const QString QgsSymbolLayer::EXPR_BORDER_COLOR( "border_color" ); -const QString QgsSymbolLayer::EXPR_COLOR2( "color2" ); -const QString QgsSymbolLayer::EXPR_LINEANGLE( "lineangle" ); -const QString QgsSymbolLayer::EXPR_GRADIENT_TYPE( "gradient_type" ); -const QString QgsSymbolLayer::EXPR_COORDINATE_MODE( "coordinate_mode" ); -const QString QgsSymbolLayer::EXPR_SPREAD( "spread" ); -const QString QgsSymbolLayer::EXPR_REFERENCE1_X( "reference1_x" ); -const QString QgsSymbolLayer::EXPR_REFERENCE1_Y( "reference1_y" ); -const QString QgsSymbolLayer::EXPR_REFERENCE2_X( "reference2_x" ); -const QString QgsSymbolLayer::EXPR_REFERENCE2_Y( "reference2_y" ); -const QString QgsSymbolLayer::EXPR_REFERENCE1_ISCENTROID( "reference1_iscentroid" ); -const QString QgsSymbolLayer::EXPR_REFERENCE2_ISCENTROID( "reference2_iscentroid" ); -const QString QgsSymbolLayer::EXPR_BLUR_RADIUS( "blur_radius" ); -const QString QgsSymbolLayer::EXPR_DISTANCE( "distance" ); -const QString QgsSymbolLayer::EXPR_USE_WHOLE_SHAPE( "use_whole_shape" ); -const QString QgsSymbolLayer::EXPR_MAX_DISTANCE( "max_distance" ); -const QString QgsSymbolLayer::EXPR_IGNORE_RINGS( "ignore_rings" ); -const QString QgsSymbolLayer::EXPR_SVG_FILE( "svgFile" ); -const QString QgsSymbolLayer::EXPR_SVG_FILL_COLOR( "svgFillColor" ); -const QString QgsSymbolLayer::EXPR_SVG_OUTLINE_COLOR( "svgOutlineColor" ); -const QString QgsSymbolLayer::EXPR_SVG_OUTLINE_WIDTH( "svgOutlineWidth" ); -const QString QgsSymbolLayer::EXPR_LINEWIDTH( "linewidth" ); -const QString QgsSymbolLayer::EXPR_DISTANCE_X( "distance_x" ); -const QString QgsSymbolLayer::EXPR_DISTANCE_Y( "distance_y" ); -const QString QgsSymbolLayer::EXPR_DISPLACEMENT_X( "displacement_x" ); -const QString QgsSymbolLayer::EXPR_DISPLACEMENT_Y( "displacement_y" ); -const QString QgsSymbolLayer::EXPR_FILE( "file" ); -const QString QgsSymbolLayer::EXPR_ALPHA( "alpha" ); -const QString QgsSymbolLayer::EXPR_CUSTOMDASH( "customdash" ); -const QString QgsSymbolLayer::EXPR_LINE_STYLE( "line_style" ); -const QString QgsSymbolLayer::EXPR_JOINSTYLE( "joinstyle" ); -const QString QgsSymbolLayer::EXPR_CAPSTYLE( "capstyle" ); -const QString QgsSymbolLayer::EXPR_PLACEMENT( "placement" ); -const QString QgsSymbolLayer::EXPR_INTERVAL( "interval" ); -const QString QgsSymbolLayer::EXPR_OFFSET_ALONG_LINE( "offset_along_line" ); -const QString QgsSymbolLayer::EXPR_HORIZONTAL_ANCHOR_POINT( "horizontal_anchor_point" ); -const QString QgsSymbolLayer::EXPR_VERTICAL_ANCHOR_POINT( "vertical_anchor_point" ); -const QString QgsSymbolLayer::EXPR_LAYER_ENABLED( "enabled" ); +const QString QgsSymbolLayer::EXPR_SIZE( QStringLiteral( "size" ) ); +const QString QgsSymbolLayer::EXPR_ANGLE( QStringLiteral( "angle" ) ); +const QString QgsSymbolLayer::EXPR_NAME( QStringLiteral( "name" ) ); +const QString QgsSymbolLayer::EXPR_COLOR( QStringLiteral( "color" ) ); +const QString QgsSymbolLayer::EXPR_COLOR_BORDER( QStringLiteral( "color_border" ) ); +const QString QgsSymbolLayer::EXPR_OUTLINE_WIDTH( QStringLiteral( "outline_width" ) ); +const QString QgsSymbolLayer::EXPR_OUTLINE_STYLE( QStringLiteral( "outline_style" ) ); +const QString QgsSymbolLayer::EXPR_FILL( QStringLiteral( "fill" ) ); +const QString QgsSymbolLayer::EXPR_OUTLINE( QStringLiteral( "outline" ) ); +const QString QgsSymbolLayer::EXPR_OFFSET( QStringLiteral( "offset" ) ); +const QString QgsSymbolLayer::EXPR_CHAR( QStringLiteral( "char" ) ); +const QString QgsSymbolLayer::EXPR_FILL_COLOR( QStringLiteral( "fill_color" ) ); +const QString QgsSymbolLayer::EXPR_OUTLINE_COLOR( QStringLiteral( "outline_color" ) ); +const QString QgsSymbolLayer::EXPR_WIDTH( QStringLiteral( "width" ) ); +const QString QgsSymbolLayer::EXPR_HEIGHT( QStringLiteral( "height" ) ); +const QString QgsSymbolLayer::EXPR_SYMBOL_NAME( QStringLiteral( "symbol_name" ) ); +const QString QgsSymbolLayer::EXPR_ROTATION( QStringLiteral( "rotation" ) ); +const QString QgsSymbolLayer::EXPR_FILL_STYLE( QStringLiteral( "fill_style" ) ); +const QString QgsSymbolLayer::EXPR_WIDTH_BORDER( QStringLiteral( "width_border" ) ); +const QString QgsSymbolLayer::EXPR_BORDER_STYLE( QStringLiteral( "border_style" ) ); +const QString QgsSymbolLayer::EXPR_JOIN_STYLE( QStringLiteral( "join_style" ) ); +const QString QgsSymbolLayer::EXPR_BORDER_COLOR( QStringLiteral( "border_color" ) ); +const QString QgsSymbolLayer::EXPR_COLOR2( QStringLiteral( "color2" ) ); +const QString QgsSymbolLayer::EXPR_LINEANGLE( QStringLiteral( "lineangle" ) ); +const QString QgsSymbolLayer::EXPR_GRADIENT_TYPE( QStringLiteral( "gradient_type" ) ); +const QString QgsSymbolLayer::EXPR_COORDINATE_MODE( QStringLiteral( "coordinate_mode" ) ); +const QString QgsSymbolLayer::EXPR_SPREAD( QStringLiteral( "spread" ) ); +const QString QgsSymbolLayer::EXPR_REFERENCE1_X( QStringLiteral( "reference1_x" ) ); +const QString QgsSymbolLayer::EXPR_REFERENCE1_Y( QStringLiteral( "reference1_y" ) ); +const QString QgsSymbolLayer::EXPR_REFERENCE2_X( QStringLiteral( "reference2_x" ) ); +const QString QgsSymbolLayer::EXPR_REFERENCE2_Y( QStringLiteral( "reference2_y" ) ); +const QString QgsSymbolLayer::EXPR_REFERENCE1_ISCENTROID( QStringLiteral( "reference1_iscentroid" ) ); +const QString QgsSymbolLayer::EXPR_REFERENCE2_ISCENTROID( QStringLiteral( "reference2_iscentroid" ) ); +const QString QgsSymbolLayer::EXPR_BLUR_RADIUS( QStringLiteral( "blur_radius" ) ); +const QString QgsSymbolLayer::EXPR_DISTANCE( QStringLiteral( "distance" ) ); +const QString QgsSymbolLayer::EXPR_USE_WHOLE_SHAPE( QStringLiteral( "use_whole_shape" ) ); +const QString QgsSymbolLayer::EXPR_MAX_DISTANCE( QStringLiteral( "max_distance" ) ); +const QString QgsSymbolLayer::EXPR_IGNORE_RINGS( QStringLiteral( "ignore_rings" ) ); +const QString QgsSymbolLayer::EXPR_SVG_FILE( QStringLiteral( "svgFile" ) ); +const QString QgsSymbolLayer::EXPR_SVG_FILL_COLOR( QStringLiteral( "svgFillColor" ) ); +const QString QgsSymbolLayer::EXPR_SVG_OUTLINE_COLOR( QStringLiteral( "svgOutlineColor" ) ); +const QString QgsSymbolLayer::EXPR_SVG_OUTLINE_WIDTH( QStringLiteral( "svgOutlineWidth" ) ); +const QString QgsSymbolLayer::EXPR_LINEWIDTH( QStringLiteral( "linewidth" ) ); +const QString QgsSymbolLayer::EXPR_DISTANCE_X( QStringLiteral( "distance_x" ) ); +const QString QgsSymbolLayer::EXPR_DISTANCE_Y( QStringLiteral( "distance_y" ) ); +const QString QgsSymbolLayer::EXPR_DISPLACEMENT_X( QStringLiteral( "displacement_x" ) ); +const QString QgsSymbolLayer::EXPR_DISPLACEMENT_Y( QStringLiteral( "displacement_y" ) ); +const QString QgsSymbolLayer::EXPR_FILE( QStringLiteral( "file" ) ); +const QString QgsSymbolLayer::EXPR_ALPHA( QStringLiteral( "alpha" ) ); +const QString QgsSymbolLayer::EXPR_CUSTOMDASH( QStringLiteral( "customdash" ) ); +const QString QgsSymbolLayer::EXPR_LINE_STYLE( QStringLiteral( "line_style" ) ); +const QString QgsSymbolLayer::EXPR_JOINSTYLE( QStringLiteral( "joinstyle" ) ); +const QString QgsSymbolLayer::EXPR_CAPSTYLE( QStringLiteral( "capstyle" ) ); +const QString QgsSymbolLayer::EXPR_PLACEMENT( QStringLiteral( "placement" ) ); +const QString QgsSymbolLayer::EXPR_INTERVAL( QStringLiteral( "interval" ) ); +const QString QgsSymbolLayer::EXPR_OFFSET_ALONG_LINE( QStringLiteral( "offset_along_line" ) ); +const QString QgsSymbolLayer::EXPR_HORIZONTAL_ANCHOR_POINT( QStringLiteral( "horizontal_anchor_point" ) ); +const QString QgsSymbolLayer::EXPR_VERTICAL_ANCHOR_POINT( QStringLiteral( "vertical_anchor_point" ) ); +const QString QgsSymbolLayer::EXPR_LAYER_ENABLED( QStringLiteral( "enabled" ) ); QgsDataDefined *QgsSymbolLayer::getDataDefinedProperty( const QString &property ) const { @@ -336,7 +336,7 @@ void QgsSymbolLayer::restoreDataDefinedProperties( const QgsStringMap &stringMap QgsStringMap::const_iterator propIt = stringMap.constBegin(); for ( ; propIt != stringMap.constEnd(); ++propIt ) { - if ( propIt.key().endsWith( "_dd_expression" ) ) + if ( propIt.key().endsWith( QLatin1String( "_dd_expression" ) ) ) { //found a data defined property @@ -347,7 +347,7 @@ void QgsSymbolLayer::restoreDataDefinedProperties( const QgsStringMap &stringMap if ( dd ) setDataDefinedProperty( propertyName, dd ); } - else if ( propIt.key().endsWith( "_expression" ) ) + else if ( propIt.key().endsWith( QLatin1String( "_expression" ) ) ) { //old style data defined property, upgrade @@ -501,11 +501,11 @@ QPointF QgsMarkerSymbolLayer::_rotatedOffset( QPointF offset, double angle ) QgsMarkerSymbolLayer::HorizontalAnchorPoint QgsMarkerSymbolLayer::decodeHorizontalAnchorPoint( const QString& str ) { - if ( str.compare( "left", Qt::CaseInsensitive ) == 0 ) + if ( str.compare( QLatin1String( "left" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Left; } - else if ( str.compare( "right", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "right" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Right; } @@ -517,11 +517,11 @@ QgsMarkerSymbolLayer::HorizontalAnchorPoint QgsMarkerSymbolLayer::decodeHorizont QgsMarkerSymbolLayer::VerticalAnchorPoint QgsMarkerSymbolLayer::decodeVerticalAnchorPoint( const QString& str ) { - if ( str.compare( "top", Qt::CaseInsensitive ) == 0 ) + if ( str.compare( QLatin1String( "top" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Top; } - else if ( str.compare( "bottom", Qt::CaseInsensitive ) == 0 ) + else if ( str.compare( QLatin1String( "bottom" ), Qt::CaseInsensitive ) == 0 ) { return QgsMarkerSymbolLayer::Bottom; } @@ -668,13 +668,13 @@ void QgsFillSymbolLayer::_renderPolygon( QPainter* p, const QPolygonF& points, c void QgsMarkerSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const { - QDomElement symbolizerElem = doc.createElement( "se:PointSymbolizer" ); - if ( !props.value( "uom", "" ).isEmpty() ) - symbolizerElem.setAttribute( "uom", props.value( "uom", "" ) ); + QDomElement symbolizerElem = doc.createElement( QStringLiteral( "se:PointSymbolizer" ) ); + if ( !props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ).isEmpty() ) + symbolizerElem.setAttribute( QStringLiteral( "uom" ), props.value( QStringLiteral( "uom" ), QLatin1String( "" ) ) ); element.appendChild( symbolizerElem ); // <Geometry> - QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( "geom", "" ) ); + QgsSymbolLayerUtils::createGeometryElement( doc, symbolizerElem, props.value( QStringLiteral( "geom" ), QLatin1String( "" ) ) ); writeSldMarker( doc, symbolizerElem, props ); } diff --git a/src/core/symbology-ng/qgssymbollayer.h b/src/core/symbology-ng/qgssymbollayer.h index 3b9610847868..963d3f8393c4 100644 --- a/src/core/symbology-ng/qgssymbollayer.h +++ b/src/core/symbology-ng/qgssymbollayer.h @@ -109,7 +109,7 @@ class CORE_EXPORT QgsSymbolLayer virtual QgsSymbolLayer* clone() const = 0; virtual void toSld( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const - { Q_UNUSED( props ); element.appendChild( doc.createComment( QString( "SymbolLayerV2 %1 not implemented yet" ).arg( layerType() ) ) ); } + { Q_UNUSED( props ); element.appendChild( doc.createComment( QStringLiteral( "SymbolLayerV2 %1 not implemented yet" ).arg( layerType() ) ) ); } virtual QString ogrFeatureStyle( double mmScaleFactor, double mapUnitScaleFactor ) const { Q_UNUSED( mmScaleFactor ); Q_UNUSED( mapUnitScaleFactor ); return QString(); } @@ -593,7 +593,7 @@ class CORE_EXPORT QgsMarkerSymbolLayer : public QgsSymbolLayer * @param props symbol layer definition (see properties()) */ virtual void writeSldMarker( QDomDocument &doc, QDomElement &element, const QgsStringMap& props ) const - { Q_UNUSED( props ); element.appendChild( doc.createComment( QString( "QgsMarkerSymbolLayer %1 not implemented yet" ).arg( layerType() ) ) ); } + { Q_UNUSED( props ); element.appendChild( doc.createComment( QStringLiteral( "QgsMarkerSymbolLayer %1 not implemented yet" ).arg( layerType() ) ) ); } void setOutputUnit( QgsUnitTypes::RenderUnit unit ) override; QgsUnitTypes::RenderUnit outputUnit() const override; diff --git a/src/core/symbology-ng/qgssymbollayerregistry.cpp b/src/core/symbology-ng/qgssymbollayerregistry.cpp index 2704130075ee..b49862c62c7e 100644 --- a/src/core/symbology-ng/qgssymbollayerregistry.cpp +++ b/src/core/symbology-ng/qgssymbollayerregistry.cpp @@ -26,43 +26,43 @@ QgsSymbolLayerRegistry::QgsSymbolLayerRegistry() { // init registry with known symbol layers - addSymbolLayerType( new QgsSymbolLayerMetadata( "SimpleLine", QObject::tr( "Simple line" ), QgsSymbol::Line, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "SimpleLine" ), QObject::tr( "Simple line" ), QgsSymbol::Line, QgsSimpleLineSymbolLayer::create, QgsSimpleLineSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "MarkerLine", QObject::tr( "Marker line" ), QgsSymbol::Line, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "MarkerLine" ), QObject::tr( "Marker line" ), QgsSymbol::Line, QgsMarkerLineSymbolLayer::create, QgsMarkerLineSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "ArrowLine", QObject::tr( "Arrow" ), QgsSymbol::Line, QgsArrowSymbolLayer::create ) ); + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "ArrowLine" ), QObject::tr( "Arrow" ), QgsSymbol::Line, QgsArrowSymbolLayer::create ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "SimpleMarker", QObject::tr( "Simple marker" ), QgsSymbol::Marker, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "SimpleMarker" ), QObject::tr( "Simple marker" ), QgsSymbol::Marker, QgsSimpleMarkerSymbolLayer::create, QgsSimpleMarkerSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "FilledMarker", QObject::tr( "Filled marker" ), QgsSymbol::Marker, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "FilledMarker" ), QObject::tr( "Filled marker" ), QgsSymbol::Marker, QgsFilledMarkerSymbolLayer::create ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "SvgMarker", QObject::tr( "SVG marker" ), QgsSymbol::Marker, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "SvgMarker" ), QObject::tr( "SVG marker" ), QgsSymbol::Marker, QgsSvgMarkerSymbolLayer::create, QgsSvgMarkerSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "FontMarker", QObject::tr( "Font marker" ), QgsSymbol::Marker, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "FontMarker" ), QObject::tr( "Font marker" ), QgsSymbol::Marker, QgsFontMarkerSymbolLayer::create, QgsFontMarkerSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "EllipseMarker", QObject::tr( "Ellipse marker" ), QgsSymbol::Marker, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "EllipseMarker" ), QObject::tr( "Ellipse marker" ), QgsSymbol::Marker, QgsEllipseSymbolLayer::create, QgsEllipseSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "VectorField", QObject::tr( "Vector field marker" ), QgsSymbol::Marker, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "VectorField" ), QObject::tr( "Vector field marker" ), QgsSymbol::Marker, QgsVectorFieldSymbolLayer::create ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "SimpleFill", QObject::tr( "Simple fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "SimpleFill" ), QObject::tr( "Simple fill" ), QgsSymbol::Fill, QgsSimpleFillSymbolLayer::create, QgsSimpleFillSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "GradientFill", QObject::tr( "Gradient fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "GradientFill" ), QObject::tr( "Gradient fill" ), QgsSymbol::Fill, QgsGradientFillSymbolLayer::create ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "ShapeburstFill", QObject::tr( "Shapeburst fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "ShapeburstFill" ), QObject::tr( "Shapeburst fill" ), QgsSymbol::Fill, QgsShapeburstFillSymbolLayer::create ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "RasterFill", QObject::tr( "Raster image fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "RasterFill" ), QObject::tr( "Raster image fill" ), QgsSymbol::Fill, QgsRasterFillSymbolLayer::create ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "SVGFill", QObject::tr( "SVG fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "SVGFill" ), QObject::tr( "SVG fill" ), QgsSymbol::Fill, QgsSVGFillSymbolLayer::create, QgsSVGFillSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "CentroidFill", QObject::tr( "Centroid fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "CentroidFill" ), QObject::tr( "Centroid fill" ), QgsSymbol::Fill, QgsCentroidFillSymbolLayer::create, QgsCentroidFillSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "LinePatternFill", QObject::tr( "Line pattern fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "LinePatternFill" ), QObject::tr( "Line pattern fill" ), QgsSymbol::Fill, QgsLinePatternFillSymbolLayer::create, QgsLinePatternFillSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "PointPatternFill", QObject::tr( "Point pattern fill" ), QgsSymbol::Fill, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "PointPatternFill" ), QObject::tr( "Point pattern fill" ), QgsSymbol::Fill, QgsPointPatternFillSymbolLayer::create, QgsPointPatternFillSymbolLayer::createFromSld ) ); - addSymbolLayerType( new QgsSymbolLayerMetadata( "GeometryGenerator", QObject::tr( "Geometry generator" ), QgsSymbol::Hybrid, + addSymbolLayerType( new QgsSymbolLayerMetadata( QStringLiteral( "GeometryGenerator" ), QObject::tr( "Geometry generator" ), QgsSymbol::Hybrid, QgsGeometryGeneratorSymbolLayer::create ) ); } diff --git a/src/core/symbology-ng/qgssymbollayerutils.cpp b/src/core/symbology-ng/qgssymbollayerutils.cpp index b7d378c71178..af7fde79dce0 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.cpp +++ b/src/core/symbology-ng/qgssymbollayerutils.cpp @@ -44,7 +44,7 @@ QString QgsSymbolLayerUtils::encodeColor( const QColor& color ) { - return QString( "%1,%2,%3,%4" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ).arg( color.alpha() ); + return QStringLiteral( "%1,%2,%3,%4" ).arg( color.red() ).arg( color.green() ).arg( color.blue() ).arg( color.alpha() ); } QColor QgsSymbolLayerUtils::decodeColor( const QString& str ) @@ -87,33 +87,33 @@ QString QgsSymbolLayerUtils::encodeSldFontStyle( QFont::Style style ) switch ( style ) { case QFont::StyleNormal: - return "normal"; + return QStringLiteral( "normal" ); case QFont::StyleItalic: - return "italic"; + return QStringLiteral( "italic" ); case QFont::StyleOblique: - return "oblique"; + return QStringLiteral( "oblique" ); default: - return ""; + return QLatin1String( "" ); } } QFont::Style QgsSymbolLayerUtils::decodeSldFontStyle( const QString& str ) { - if ( str == "normal" ) return QFont::StyleNormal; - if ( str == "italic" ) return QFont::StyleItalic; - if ( str == "oblique" ) return QFont::StyleOblique; + if ( str == QLatin1String( "normal" ) ) return QFont::StyleNormal; + if ( str == QLatin1String( "italic" ) ) return QFont::StyleItalic; + if ( str == QLatin1String( "oblique" ) ) return QFont::StyleOblique; return QFont::StyleNormal; } QString QgsSymbolLayerUtils::encodeSldFontWeight( int weight ) { - if ( weight == 50 ) return "normal"; - if ( weight == 75 ) return "bold"; + if ( weight == 50 ) return QStringLiteral( "normal" ); + if ( weight == 75 ) return QStringLiteral( "bold" ); // QFont::Weight is between 0 and 99 // CSS font-weight is between 100 and 900 - if ( weight < 0 ) return "100"; - if ( weight > 99 ) return "900"; + if ( weight < 0 ) return QStringLiteral( "100" ); + if ( weight > 99 ) return QStringLiteral( "900" ); return QString::number( weight * 800 / 99 + 100 ); } @@ -136,30 +136,30 @@ QString QgsSymbolLayerUtils::encodePenStyle( Qt::PenStyle style ) switch ( style ) { case Qt::NoPen: - return "no"; + return QStringLiteral( "no" ); case Qt::SolidLine: - return "solid"; + return QStringLiteral( "solid" ); case Qt::DashLine: - return "dash"; + return QStringLiteral( "dash" ); case Qt::DotLine: - return "dot"; + return QStringLiteral( "dot" ); case Qt::DashDotLine: - return "dash dot"; + return QStringLiteral( "dash dot" ); case Qt::DashDotDotLine: - return "dash dot dot"; + return QStringLiteral( "dash dot dot" ); default: - return "???"; + return QStringLiteral( "???" ); } } Qt::PenStyle QgsSymbolLayerUtils::decodePenStyle( const QString& str ) { - if ( str == "no" ) return Qt::NoPen; - if ( str == "solid" ) return Qt::SolidLine; - if ( str == "dash" ) return Qt::DashLine; - if ( str == "dot" ) return Qt::DotLine; - if ( str == "dash dot" ) return Qt::DashDotLine; - if ( str == "dash dot dot" ) return Qt::DashDotDotLine; + if ( str == QLatin1String( "no" ) ) return Qt::NoPen; + if ( str == QLatin1String( "solid" ) ) return Qt::SolidLine; + if ( str == QLatin1String( "dash" ) ) return Qt::DashLine; + if ( str == QLatin1String( "dot" ) ) return Qt::DotLine; + if ( str == QLatin1String( "dash dot" ) ) return Qt::DashDotLine; + if ( str == QLatin1String( "dash dot dot" ) ) return Qt::DashDotDotLine; return Qt::SolidLine; } @@ -168,21 +168,21 @@ QString QgsSymbolLayerUtils::encodePenJoinStyle( Qt::PenJoinStyle style ) switch ( style ) { case Qt::BevelJoin: - return "bevel"; + return QStringLiteral( "bevel" ); case Qt::MiterJoin: - return "miter"; + return QStringLiteral( "miter" ); case Qt::RoundJoin: - return "round"; + return QStringLiteral( "round" ); default: - return "???"; + return QStringLiteral( "???" ); } } Qt::PenJoinStyle QgsSymbolLayerUtils::decodePenJoinStyle( const QString& str ) { - if ( str == "bevel" ) return Qt::BevelJoin; - if ( str == "miter" ) return Qt::MiterJoin; - if ( str == "round" ) return Qt::RoundJoin; + if ( str == QLatin1String( "bevel" ) ) return Qt::BevelJoin; + if ( str == QLatin1String( "miter" ) ) return Qt::MiterJoin; + if ( str == QLatin1String( "round" ) ) return Qt::RoundJoin; return Qt::BevelJoin; } @@ -191,21 +191,21 @@ QString QgsSymbolLayerUtils::encodeSldLineJoinStyle( Qt::PenJoinStyle style ) switch ( style ) { case Qt::BevelJoin: - return "bevel"; + return QStringLiteral( "bevel" ); case Qt::MiterJoin: - return "mitre"; + return QStringLiteral( "mitre" ); case Qt::RoundJoin: - return "round"; + return QStringLiteral( "round" ); default: - return ""; + return QLatin1String( "" ); } } Qt::PenJoinStyle QgsSymbolLayerUtils::decodeSldLineJoinStyle( const QString& str ) { - if ( str == "bevel" ) return Qt::BevelJoin; - if ( str == "mitre" ) return Qt::MiterJoin; - if ( str == "round" ) return Qt::RoundJoin; + if ( str == QLatin1String( "bevel" ) ) return Qt::BevelJoin; + if ( str == QLatin1String( "mitre" ) ) return Qt::MiterJoin; + if ( str == QLatin1String( "round" ) ) return Qt::RoundJoin; return Qt::BevelJoin; } @@ -214,21 +214,21 @@ QString QgsSymbolLayerUtils::encodePenCapStyle( Qt::PenCapStyle style ) switch ( style ) { case Qt::SquareCap: - return "square"; + return QStringLiteral( "square" ); case Qt::FlatCap: - return "flat"; + return QStringLiteral( "flat" ); case Qt::RoundCap: - return "round"; + return QStringLiteral( "round" ); default: - return "???"; + return QStringLiteral( "???" ); } } Qt::PenCapStyle QgsSymbolLayerUtils::decodePenCapStyle( const QString& str ) { - if ( str == "square" ) return Qt::SquareCap; - if ( str == "flat" ) return Qt::FlatCap; - if ( str == "round" ) return Qt::RoundCap; + if ( str == QLatin1String( "square" ) ) return Qt::SquareCap; + if ( str == QLatin1String( "flat" ) ) return Qt::FlatCap; + if ( str == QLatin1String( "round" ) ) return Qt::RoundCap; return Qt::SquareCap; } @@ -237,21 +237,21 @@ QString QgsSymbolLayerUtils::encodeSldLineCapStyle( Qt::PenCapStyle style ) switch ( style ) { case Qt::SquareCap: - return "square"; + return QStringLiteral( "square" ); case Qt::FlatCap: - return "butt"; + return QStringLiteral( "butt" ); case Qt::RoundCap: - return "round"; + return QStringLiteral( "round" ); default: - return ""; + return QLatin1String( "" ); } } Qt::PenCapStyle QgsSymbolLayerUtils::decodeSldLineCapStyle( const QString& str ) { - if ( str == "square" ) return Qt::SquareCap; - if ( str == "butt" ) return Qt::FlatCap; - if ( str == "round" ) return Qt::RoundCap; + if ( str == QLatin1String( "square" ) ) return Qt::SquareCap; + if ( str == QLatin1String( "butt" ) ) return Qt::FlatCap; + if ( str == QLatin1String( "round" ) ) return Qt::RoundCap; return Qt::SquareCap; } @@ -260,57 +260,57 @@ QString QgsSymbolLayerUtils::encodeBrushStyle( Qt::BrushStyle style ) switch ( style ) { case Qt::SolidPattern : - return "solid"; + return QStringLiteral( "solid" ); case Qt::HorPattern : - return "horizontal"; + return QStringLiteral( "horizontal" ); case Qt::VerPattern : - return "vertical"; + return QStringLiteral( "vertical" ); case Qt::CrossPattern : - return "cross"; + return QStringLiteral( "cross" ); case Qt::BDiagPattern : - return "b_diagonal"; + return QStringLiteral( "b_diagonal" ); case Qt::FDiagPattern : - return "f_diagonal"; + return QStringLiteral( "f_diagonal" ); case Qt::DiagCrossPattern : - return "diagonal_x"; + return QStringLiteral( "diagonal_x" ); case Qt::Dense1Pattern : - return "dense1"; + return QStringLiteral( "dense1" ); case Qt::Dense2Pattern : - return "dense2"; + return QStringLiteral( "dense2" ); case Qt::Dense3Pattern : - return "dense3"; + return QStringLiteral( "dense3" ); case Qt::Dense4Pattern : - return "dense4"; + return QStringLiteral( "dense4" ); case Qt::Dense5Pattern : - return "dense5"; + return QStringLiteral( "dense5" ); case Qt::Dense6Pattern : - return "dense6"; + return QStringLiteral( "dense6" ); case Qt::Dense7Pattern : - return "dense7"; + return QStringLiteral( "dense7" ); case Qt::NoBrush : - return "no"; + return QStringLiteral( "no" ); default: - return "???"; + return QStringLiteral( "???" ); } } Qt::BrushStyle QgsSymbolLayerUtils::decodeBrushStyle( const QString& str ) { - if ( str == "solid" ) return Qt::SolidPattern; - if ( str == "horizontal" ) return Qt::HorPattern; - if ( str == "vertical" ) return Qt::VerPattern; - if ( str == "cross" ) return Qt::CrossPattern; - if ( str == "b_diagonal" ) return Qt::BDiagPattern; - if ( str == "f_diagonal" ) return Qt::FDiagPattern; - if ( str == "diagonal_x" ) return Qt::DiagCrossPattern; - if ( str == "dense1" ) return Qt::Dense1Pattern; - if ( str == "dense2" ) return Qt::Dense2Pattern; - if ( str == "dense3" ) return Qt::Dense3Pattern; - if ( str == "dense4" ) return Qt::Dense4Pattern; - if ( str == "dense5" ) return Qt::Dense5Pattern; - if ( str == "dense6" ) return Qt::Dense6Pattern; - if ( str == "dense7" ) return Qt::Dense7Pattern; - if ( str == "no" ) return Qt::NoBrush; + if ( str == QLatin1String( "solid" ) ) return Qt::SolidPattern; + if ( str == QLatin1String( "horizontal" ) ) return Qt::HorPattern; + if ( str == QLatin1String( "vertical" ) ) return Qt::VerPattern; + if ( str == QLatin1String( "cross" ) ) return Qt::CrossPattern; + if ( str == QLatin1String( "b_diagonal" ) ) return Qt::BDiagPattern; + if ( str == QLatin1String( "f_diagonal" ) ) return Qt::FDiagPattern; + if ( str == QLatin1String( "diagonal_x" ) ) return Qt::DiagCrossPattern; + if ( str == QLatin1String( "dense1" ) ) return Qt::Dense1Pattern; + if ( str == QLatin1String( "dense2" ) ) return Qt::Dense2Pattern; + if ( str == QLatin1String( "dense3" ) ) return Qt::Dense3Pattern; + if ( str == QLatin1String( "dense4" ) ) return Qt::Dense4Pattern; + if ( str == QLatin1String( "dense5" ) ) return Qt::Dense5Pattern; + if ( str == QLatin1String( "dense6" ) ) return Qt::Dense6Pattern; + if ( str == QLatin1String( "dense7" ) ) return Qt::Dense7Pattern; + if ( str == QLatin1String( "no" ) ) return Qt::NoBrush; return Qt::SolidPattern; } @@ -319,22 +319,22 @@ QString QgsSymbolLayerUtils::encodeSldBrushStyle( Qt::BrushStyle style ) switch ( style ) { case Qt::CrossPattern: - return "cross"; + return QStringLiteral( "cross" ); case Qt::DiagCrossPattern: - return "x"; + return QStringLiteral( "x" ); /* The following names are taken from the presentation "GeoServer * Cartographic Rendering" by Andrea Aime at the FOSS4G 2010. * (see http://2010.foss4g.org/presentations/3588.pdf) */ case Qt::HorPattern: - return "horline"; + return QStringLiteral( "horline" ); case Qt::VerPattern: - return "line"; + return QStringLiteral( "line" ); case Qt::BDiagPattern: - return "slash"; + return QStringLiteral( "slash" ); case Qt::FDiagPattern: - return "backslash"; + return QStringLiteral( "backslash" ); /* define the other names following the same pattern used above */ case Qt::Dense1Pattern: @@ -344,7 +344,7 @@ QString QgsSymbolLayerUtils::encodeSldBrushStyle( Qt::BrushStyle style ) case Qt::Dense5Pattern: case Qt::Dense6Pattern: case Qt::Dense7Pattern: - return QString( "brush://%1" ).arg( encodeBrushStyle( style ) ); + return QStringLiteral( "brush://%1" ).arg( encodeBrushStyle( style ) ); default: return QString(); @@ -353,14 +353,14 @@ QString QgsSymbolLayerUtils::encodeSldBrushStyle( Qt::BrushStyle style ) Qt::BrushStyle QgsSymbolLayerUtils::decodeSldBrushStyle( const QString& str ) { - if ( str == "horline" ) return Qt::HorPattern; - if ( str == "line" ) return Qt::VerPattern; - if ( str == "cross" ) return Qt::CrossPattern; - if ( str == "slash" ) return Qt::BDiagPattern; - if ( str == "backshash" ) return Qt::FDiagPattern; - if ( str == "x" ) return Qt::DiagCrossPattern; + if ( str == QLatin1String( "horline" ) ) return Qt::HorPattern; + if ( str == QLatin1String( "line" ) ) return Qt::VerPattern; + if ( str == QLatin1String( "cross" ) ) return Qt::CrossPattern; + if ( str == QLatin1String( "slash" ) ) return Qt::BDiagPattern; + if ( str == QLatin1String( "backshash" ) ) return Qt::FDiagPattern; + if ( str == QLatin1String( "x" ) ) return Qt::DiagCrossPattern; - if ( str.startsWith( "brush://" ) ) + if ( str.startsWith( QLatin1String( "brush://" ) ) ) return decodeBrushStyle( str.mid( 8 ) ); return Qt::NoBrush; @@ -368,7 +368,7 @@ Qt::BrushStyle QgsSymbolLayerUtils::decodeSldBrushStyle( const QString& str ) QString QgsSymbolLayerUtils::encodePoint( QPointF point ) { - return QString( "%1,%2" ).arg( qgsDoubleToString( point.x() ), qgsDoubleToString( point.y() ) ); + return QStringLiteral( "%1,%2" ).arg( qgsDoubleToString( point.x() ), qgsDoubleToString( point.y() ) ); } QPointF QgsSymbolLayerUtils::decodePoint( const QString& str ) @@ -381,7 +381,7 @@ QPointF QgsSymbolLayerUtils::decodePoint( const QString& str ) QString QgsSymbolLayerUtils::encodeSize( QSizeF size ) { - return QString( "%1,%2" ).arg( qgsDoubleToString( size.width() ), qgsDoubleToString( size.height() ) ); + return QStringLiteral( "%1,%2" ).arg( qgsDoubleToString( size.width() ), qgsDoubleToString( size.height() ) ); } QSizeF QgsSymbolLayerUtils::decodeSize( const QString& string ) @@ -394,7 +394,7 @@ QSizeF QgsSymbolLayerUtils::decodeSize( const QString& string ) QString QgsSymbolLayerUtils::encodeMapUnitScale( const QgsMapUnitScale& mapUnitScale ) { - return QString( "%1,%2,%3,%4,%5,%6" ).arg( qgsDoubleToString( mapUnitScale.minScale ), + return QStringLiteral( "%1,%2,%3,%4,%5,%6" ).arg( qgsDoubleToString( mapUnitScale.minScale ), qgsDoubleToString( mapUnitScale.maxScale ) ) .arg( mapUnitScale.minSizeMMEnabled ? 1 : 0 ) .arg( mapUnitScale.minSizeMM ) @@ -429,7 +429,7 @@ QString QgsSymbolLayerUtils::encodeSldUom( QgsUnitTypes::RenderUnit unit, double case QgsUnitTypes::RenderMapUnits: if ( scaleFactor ) *scaleFactor = 0.001; // from millimeters to meters - return "http://www.opengeospatial.org/se/units/metre"; + return QStringLiteral( "http://www.opengeospatial.org/se/units/metre" ); case QgsUnitTypes::RenderMillimeters: default: @@ -445,13 +445,13 @@ QString QgsSymbolLayerUtils::encodeSldUom( QgsUnitTypes::RenderUnit unit, double QgsUnitTypes::RenderUnit QgsSymbolLayerUtils::decodeSldUom( const QString& str, double *scaleFactor ) { - if ( str == "http://www.opengeospatial.org/se/units/metre" ) + if ( str == QLatin1String( "http://www.opengeospatial.org/se/units/metre" ) ) { if ( scaleFactor ) *scaleFactor = 1000.0; // from meters to millimeters return QgsUnitTypes::RenderMapUnits; } - else if ( str == "http://www.opengeospatial.org/se/units/foot" ) + else if ( str == QLatin1String( "http://www.opengeospatial.org/se/units/foot" ) ) { if ( scaleFactor ) *scaleFactor = 304.8; // from feet to meters @@ -530,10 +530,10 @@ QString QgsSymbolLayerUtils::encodeScaleMethod( QgsSymbol::ScaleMethod scaleMeth switch ( scaleMethod ) { case QgsSymbol::ScaleDiameter: - encodedValue = "diameter"; + encodedValue = QStringLiteral( "diameter" ); break; case QgsSymbol::ScaleArea: - encodedValue = "area"; + encodedValue = QStringLiteral( "area" ); break; } return encodedValue; @@ -543,7 +543,7 @@ QgsSymbol::ScaleMethod QgsSymbolLayerUtils::decodeScaleMethod( const QString& st { QgsSymbol::ScaleMethod scaleMethod; - if ( str == "diameter" ) + if ( str == QLatin1String( "diameter" ) ) { scaleMethod = QgsSymbol::ScaleDiameter; } @@ -557,18 +557,18 @@ QgsSymbol::ScaleMethod QgsSymbolLayerUtils::decodeScaleMethod( const QString& st QPainter::CompositionMode QgsSymbolLayerUtils::decodeBlendMode( const QString &s ) { - if ( s.compare( "Lighten", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Lighten; - if ( s.compare( "Screen", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Screen; - if ( s.compare( "Dodge", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_ColorDodge; - if ( s.compare( "Addition", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Plus; - if ( s.compare( "Darken", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Darken; - if ( s.compare( "Multiply", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Multiply; - if ( s.compare( "Burn", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_ColorBurn; - if ( s.compare( "Overlay", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Overlay; - if ( s.compare( "SoftLight", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_SoftLight; - if ( s.compare( "HardLight", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_HardLight; - if ( s.compare( "Difference", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Difference; - if ( s.compare( "Subtract", Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Exclusion; + if ( s.compare( QLatin1String( "Lighten" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Lighten; + if ( s.compare( QLatin1String( "Screen" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Screen; + if ( s.compare( QLatin1String( "Dodge" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_ColorDodge; + if ( s.compare( QLatin1String( "Addition" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Plus; + if ( s.compare( QLatin1String( "Darken" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Darken; + if ( s.compare( QLatin1String( "Multiply" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Multiply; + if ( s.compare( QLatin1String( "Burn" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_ColorBurn; + if ( s.compare( QLatin1String( "Overlay" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Overlay; + if ( s.compare( QLatin1String( "SoftLight" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_SoftLight; + if ( s.compare( QLatin1String( "HardLight" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_HardLight; + if ( s.compare( QLatin1String( "Difference" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Difference; + if ( s.compare( QLatin1String( "Subtract" ), Qt::CaseInsensitive ) == 0 ) return QPainter::CompositionMode_Exclusion; return QPainter::CompositionMode_SourceOver; // "Normal" } @@ -797,7 +797,7 @@ QgsSymbol* QgsSymbolLayerUtils::loadSymbol( const QDomElement &element ) QDomElement e = layerNode.toElement(); if ( !e.isNull() ) { - if ( e.tagName() != "layer" ) + if ( e.tagName() != QLatin1String( "layer" ) ) { QgsDebugMsg( "unknown tag " + e.tagName() ); } @@ -808,7 +808,7 @@ QgsSymbol* QgsSymbolLayerUtils::loadSymbol( const QDomElement &element ) if ( layer ) { // Dealing with sub-symbols nested into a layer - QDomElement s = e.firstChildElement( "symbol" ); + QDomElement s = e.firstChildElement( QStringLiteral( "symbol" ) ); if ( !s.isNull() ) { QgsSymbol* subSymbol = loadSymbol( s ); @@ -831,14 +831,14 @@ QgsSymbol* QgsSymbolLayerUtils::loadSymbol( const QDomElement &element ) return nullptr; } - QString symbolType = element.attribute( "type" ); + QString symbolType = element.attribute( QStringLiteral( "type" ) ); QgsSymbol* symbol = nullptr; - if ( symbolType == "line" ) + if ( symbolType == QLatin1String( "line" ) ) symbol = new QgsLineSymbol( layers ); - else if ( symbolType == "fill" ) + else if ( symbolType == QLatin1String( "fill" ) ) symbol = new QgsFillSymbol( layers ); - else if ( symbolType == "marker" ) + else if ( symbolType == QLatin1String( "marker" ) ) symbol = new QgsMarkerSymbol( layers ); else { @@ -846,29 +846,29 @@ QgsSymbol* QgsSymbolLayerUtils::loadSymbol( const QDomElement &element ) return nullptr; } - if ( element.hasAttribute( "outputUnit" ) ) + if ( element.hasAttribute( QStringLiteral( "outputUnit" ) ) ) { - symbol->setOutputUnit( QgsUnitTypes::decodeRenderUnit( element.attribute( "outputUnit" ) ) ); + symbol->setOutputUnit( QgsUnitTypes::decodeRenderUnit( element.attribute( QStringLiteral( "outputUnit" ) ) ) ); } if ( element.hasAttribute(( "mapUnitScale" ) ) ) { QgsMapUnitScale mapUnitScale; - mapUnitScale.minScale = element.attribute( "mapUnitMinScale", "0.0" ).toDouble(); - mapUnitScale.maxScale = element.attribute( "mapUnitMaxScale", "0.0" ).toDouble(); + mapUnitScale.minScale = element.attribute( QStringLiteral( "mapUnitMinScale" ), QStringLiteral( "0.0" ) ).toDouble(); + mapUnitScale.maxScale = element.attribute( QStringLiteral( "mapUnitMaxScale" ), QStringLiteral( "0.0" ) ).toDouble(); symbol->setMapUnitScale( mapUnitScale ); } - symbol->setAlpha( element.attribute( "alpha", "1.0" ).toDouble() ); - symbol->setClipFeaturesToExtent( element.attribute( "clip_to_extent", "1" ).toInt() ); + symbol->setAlpha( element.attribute( QStringLiteral( "alpha" ), QStringLiteral( "1.0" ) ).toDouble() ); + symbol->setClipFeaturesToExtent( element.attribute( QStringLiteral( "clip_to_extent" ), QStringLiteral( "1" ) ).toInt() ); return symbol; } QgsSymbolLayer* QgsSymbolLayerUtils::loadSymbolLayer( QDomElement& element ) { - QString layerClass = element.attribute( "class" ); - bool locked = element.attribute( "locked" ).toInt(); - bool enabled = element.attribute( "enabled", "1" ).toInt(); - int pass = element.attribute( "pass" ).toInt(); + QString layerClass = element.attribute( QStringLiteral( "class" ) ); + bool locked = element.attribute( QStringLiteral( "locked" ) ).toInt(); + bool enabled = element.attribute( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); + int pass = element.attribute( QStringLiteral( "pass" ) ).toInt(); // parse properties QgsStringMap props = parseProperties( element ); @@ -882,7 +882,7 @@ QgsSymbolLayer* QgsSymbolLayerUtils::loadSymbolLayer( QDomElement& element ) layer->setEnabled( enabled ); //restore layer effect - QDomElement effectElem = element.firstChildElement( "effect" ); + QDomElement effectElem = element.firstChildElement( QStringLiteral( "effect" ) ); if ( !effectElem.isNull() ) { layer->setPaintEffect( QgsPaintEffectRegistry::instance()->createEffect( effectElem ) ); @@ -901,42 +901,42 @@ static QString _nameForSymbolType( QgsSymbol::SymbolType type ) switch ( type ) { case QgsSymbol::Line: - return "line"; + return QStringLiteral( "line" ); case QgsSymbol::Marker: - return "marker"; + return QStringLiteral( "marker" ); case QgsSymbol::Fill: - return "fill"; + return QStringLiteral( "fill" ); default: - return ""; + return QLatin1String( "" ); } } QDomElement QgsSymbolLayerUtils::saveSymbol( const QString& name, QgsSymbol* symbol, QDomDocument& doc ) { Q_ASSERT( symbol ); - QDomElement symEl = doc.createElement( "symbol" ); - symEl.setAttribute( "type", _nameForSymbolType( symbol->type() ) ); - symEl.setAttribute( "name", name ); - symEl.setAttribute( "alpha", QString::number( symbol->alpha() ) ); - symEl.setAttribute( "clip_to_extent", symbol->clipFeaturesToExtent() ? "1" : "0" ); + QDomElement symEl = doc.createElement( QStringLiteral( "symbol" ) ); + symEl.setAttribute( QStringLiteral( "type" ), _nameForSymbolType( symbol->type() ) ); + symEl.setAttribute( QStringLiteral( "name" ), name ); + symEl.setAttribute( QStringLiteral( "alpha" ), QString::number( symbol->alpha() ) ); + symEl.setAttribute( QStringLiteral( "clip_to_extent" ), symbol->clipFeaturesToExtent() ? "1" : "0" ); //QgsDebugMsg( "num layers " + QString::number( symbol->symbolLayerCount() ) ); for ( int i = 0; i < symbol->symbolLayerCount(); i++ ) { QgsSymbolLayer* layer = symbol->symbolLayer( i ); - QDomElement layerEl = doc.createElement( "layer" ); - layerEl.setAttribute( "class", layer->layerType() ); - layerEl.setAttribute( "enabled", layer->enabled() ); - layerEl.setAttribute( "locked", layer->isLocked() ); - layerEl.setAttribute( "pass", layer->renderingPass() ); + QDomElement layerEl = doc.createElement( QStringLiteral( "layer" ) ); + layerEl.setAttribute( QStringLiteral( "class" ), layer->layerType() ); + layerEl.setAttribute( QStringLiteral( "enabled" ), layer->enabled() ); + layerEl.setAttribute( QStringLiteral( "locked" ), layer->isLocked() ); + layerEl.setAttribute( QStringLiteral( "pass" ), layer->renderingPass() ); saveProperties( layer->properties(), doc, layerEl ); if ( !QgsPaintEffectRegistry::isDefaultStack( layer->paintEffect() ) ) layer->paintEffect()->saveProperties( doc, layerEl ); if ( layer->subSymbol() ) { - QString subname = QString( "@%1@%2" ).arg( name ).arg( i ); + QString subname = QStringLiteral( "@%1@%2" ).arg( name ).arg( i ); QDomElement subEl = saveSymbol( subname, layer->subSymbol(), doc ); layerEl.appendChild( subEl ); } @@ -948,8 +948,8 @@ QDomElement QgsSymbolLayerUtils::saveSymbol( const QString& name, QgsSymbol* sym QString QgsSymbolLayerUtils::symbolProperties( QgsSymbol* symbol ) { - QDomDocument doc( "qgis-symbol-definition" ); - QDomElement symbolElem = saveSymbol( "symbol", symbol, doc ); + QDomDocument doc( QStringLiteral( "qgis-symbol-definition" ) ); + QDomElement symbolElem = saveSymbol( QStringLiteral( "symbol" ), symbol, doc ); QString props; QTextStream stream( &props ); symbolElem.save( stream, -1 ); @@ -969,10 +969,10 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, QString symbolizerName = element.localName(); - if ( symbolizerName == "PointSymbolizer" ) + if ( symbolizerName == QLatin1String( "PointSymbolizer" ) ) { // first check for Graphic element, nothing will be rendered if not found - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) { QgsDebugMsg( "Graphic element not found in PointSymbolizer" ); @@ -983,7 +983,7 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, { case QgsWkbTypes::PolygonGeometry: // polygon layer and point symbolizer: draw poligon centroid - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "CentroidFill", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "CentroidFill" ), element ); if ( l ) layers.append( l ); @@ -999,7 +999,7 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, case QgsWkbTypes::LineGeometry: // line layer and point symbolizer: draw central point - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "SimpleMarker", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "SimpleMarker" ), element ); if ( l ) layers.append( l ); @@ -1011,10 +1011,10 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, } } - if ( symbolizerName == "LineSymbolizer" ) + if ( symbolizerName == QLatin1String( "LineSymbolizer" ) ) { // check for Stroke element, nothing will be rendered if not found - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( strokeElem.isNull() ) { QgsDebugMsg( "Stroke element not found in LineSymbolizer" ); @@ -1035,7 +1035,7 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, case QgsWkbTypes::PointGeometry: // point layer and line symbolizer: draw a little line marker - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "MarkerLine", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "MarkerLine" ), element ); if ( l ) layers.append( l ); @@ -1047,11 +1047,11 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, } } - if ( symbolizerName == "PolygonSymbolizer" ) + if ( symbolizerName == QLatin1String( "PolygonSymbolizer" ) ) { // get Fill and Stroke elements, nothing will be rendered if both are missing - QDomElement fillElem = element.firstChildElement( "Fill" ); - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( fillElem.isNull() && strokeElem.isNull() ) { QgsDebugMsg( "neither Fill nor Stroke element not found in PolygonSymbolizer" ); @@ -1072,7 +1072,7 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, // SVGFill and SimpleFill symbolLayerV2 supports outline internally, // so don't go forward to create a different symbolLayerV2 for outline - if ( l->layerType() == "SimpleFill" || l->layerType() == "SVGFill" ) + if ( l->layerType() == QLatin1String( "SimpleFill" ) || l->layerType() == QLatin1String( "SVGFill" ) ) break; } @@ -1108,7 +1108,7 @@ bool QgsSymbolLayerUtils::createSymbolLayerListFromSld( QDomElement& element, QgsSymbolLayer* QgsSymbolLayerUtils::createFillLayerFromSld( QDomElement &element ) { - QDomElement fillElem = element.firstChildElement( "Fill" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); if ( fillElem.isNull() ) { QgsDebugMsg( "Fill element not found" ); @@ -1118,20 +1118,20 @@ QgsSymbolLayer* QgsSymbolLayerUtils::createFillLayerFromSld( QDomElement &elemen QgsSymbolLayer *l = nullptr; if ( needLinePatternFill( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "LinePatternFill", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "LinePatternFill" ), element ); else if ( needPointPatternFill( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "PointPatternFill", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "PointPatternFill" ), element ); else if ( needSvgFill( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "SVGFill", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "SVGFill" ), element ); else - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "SimpleFill", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "SimpleFill" ), element ); return l; } QgsSymbolLayer* QgsSymbolLayerUtils::createLineLayerFromSld( QDomElement &element ) { - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( strokeElem.isNull() ) { QgsDebugMsg( "Stroke element not found" ); @@ -1141,16 +1141,16 @@ QgsSymbolLayer* QgsSymbolLayerUtils::createLineLayerFromSld( QDomElement &elemen QgsSymbolLayer *l = nullptr; if ( needMarkerLine( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "MarkerLine", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "MarkerLine" ), element ); else - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "SimpleLine", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "SimpleLine" ), element ); return l; } QgsSymbolLayer* QgsSymbolLayerUtils::createMarkerLayerFromSld( QDomElement &element ) { - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) { QgsDebugMsg( "Graphic element not found" ); @@ -1160,42 +1160,42 @@ QgsSymbolLayer* QgsSymbolLayerUtils::createMarkerLayerFromSld( QDomElement &elem QgsSymbolLayer *l = nullptr; if ( needFontMarker( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "FontMarker", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "FontMarker" ), element ); else if ( needSvgMarker( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "SvgMarker", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "SvgMarker" ), element ); else if ( needEllipseMarker( element ) ) - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "EllipseMarker", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "EllipseMarker" ), element ); else - l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( "SimpleMarker", element ); + l = QgsSymbolLayerRegistry::instance()->createSymbolLayerFromSld( QStringLiteral( "SimpleMarker" ), element ); return l; } bool QgsSymbolLayerUtils::hasExternalGraphic( QDomElement &element ) { - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return false; - QDomElement externalGraphicElem = graphicElem.firstChildElement( "ExternalGraphic" ); + QDomElement externalGraphicElem = graphicElem.firstChildElement( QStringLiteral( "ExternalGraphic" ) ); if ( externalGraphicElem.isNull() ) return false; // check for format - QDomElement formatElem = externalGraphicElem.firstChildElement( "Format" ); + QDomElement formatElem = externalGraphicElem.firstChildElement( QStringLiteral( "Format" ) ); if ( formatElem.isNull() ) return false; QString format = formatElem.firstChild().nodeValue(); - if ( format != "image/svg+xml" ) + if ( format != QLatin1String( "image/svg+xml" ) ) { QgsDebugMsg( "unsupported External Graphic format found: " + format ); return false; } // check for a valid content - QDomElement onlineResourceElem = externalGraphicElem.firstChildElement( "OnlineResource" ); - QDomElement inlineContentElem = externalGraphicElem.firstChildElement( "InlineContent" ); + QDomElement onlineResourceElem = externalGraphicElem.firstChildElement( QStringLiteral( "OnlineResource" ) ); + QDomElement inlineContentElem = externalGraphicElem.firstChildElement( QStringLiteral( "InlineContent" ) ); if ( !onlineResourceElem.isNull() ) { return true; @@ -1214,15 +1214,15 @@ bool QgsSymbolLayerUtils::hasExternalGraphic( QDomElement &element ) bool QgsSymbolLayerUtils::hasWellKnownMark( QDomElement &element ) { - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return false; - QDomElement markElem = graphicElem.firstChildElement( "Mark" ); + QDomElement markElem = graphicElem.firstChildElement( QStringLiteral( "Mark" ) ); if ( markElem.isNull() ) return false; - QDomElement wellKnownNameElem = markElem.firstChildElement( "WellKnownName" ); + QDomElement wellKnownNameElem = markElem.firstChildElement( QStringLiteral( "WellKnownName" ) ); if ( wellKnownNameElem.isNull() ) return false; @@ -1232,33 +1232,33 @@ bool QgsSymbolLayerUtils::hasWellKnownMark( QDomElement &element ) bool QgsSymbolLayerUtils::needFontMarker( QDomElement &element ) { - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return false; - QDomElement markElem = graphicElem.firstChildElement( "Mark" ); + QDomElement markElem = graphicElem.firstChildElement( QStringLiteral( "Mark" ) ); if ( markElem.isNull() ) return false; // check for format - QDomElement formatElem = markElem.firstChildElement( "Format" ); + QDomElement formatElem = markElem.firstChildElement( QStringLiteral( "Format" ) ); if ( formatElem.isNull() ) return false; QString format = formatElem.firstChild().nodeValue(); - if ( format != "ttf" ) + if ( format != QLatin1String( "ttf" ) ) { QgsDebugMsg( "unsupported Graphic Mark format found: " + format ); return false; } // check for a valid content - QDomElement onlineResourceElem = markElem.firstChildElement( "OnlineResource" ); - QDomElement inlineContentElem = markElem.firstChildElement( "InlineContent" ); + QDomElement onlineResourceElem = markElem.firstChildElement( QStringLiteral( "OnlineResource" ) ); + QDomElement inlineContentElem = markElem.firstChildElement( QStringLiteral( "InlineContent" ) ); if ( !onlineResourceElem.isNull() ) { // mark with ttf format has a markIndex element - QDomElement markIndexElem = markElem.firstChildElement( "MarkIndex" ); + QDomElement markIndexElem = markElem.firstChildElement( QStringLiteral( "MarkIndex" ) ); if ( !markIndexElem.isNull() ) return true; } @@ -1277,14 +1277,14 @@ bool QgsSymbolLayerUtils::needSvgMarker( QDomElement &element ) bool QgsSymbolLayerUtils::needEllipseMarker( QDomElement &element ) { - QDomElement graphicElem = element.firstChildElement( "Graphic" ); + QDomElement graphicElem = element.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return false; QgsStringMap vendorOptions = QgsSymbolLayerUtils::getVendorOptionList( graphicElem ); for ( QgsStringMap::iterator it = vendorOptions.begin(); it != vendorOptions.end(); ++it ) { - if ( it.key() == "widthHeightFactor" ) + if ( it.key() == QLatin1String( "widthHeightFactor" ) ) { return true; } @@ -1295,11 +1295,11 @@ bool QgsSymbolLayerUtils::needEllipseMarker( QDomElement &element ) bool QgsSymbolLayerUtils::needMarkerLine( QDomElement &element ) { - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); if ( strokeElem.isNull() ) return false; - QDomElement graphicStrokeElem = strokeElem.firstChildElement( "GraphicStroke" ); + QDomElement graphicStrokeElem = strokeElem.firstChildElement( QStringLiteral( "GraphicStroke" ) ); if ( graphicStrokeElem.isNull() ) return false; @@ -1308,15 +1308,15 @@ bool QgsSymbolLayerUtils::needMarkerLine( QDomElement &element ) bool QgsSymbolLayerUtils::needLinePatternFill( QDomElement &element ) { - QDomElement fillElem = element.firstChildElement( "Fill" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); if ( fillElem.isNull() ) return false; - QDomElement graphicFillElem = fillElem.firstChildElement( "GraphicFill" ); + QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) ); if ( graphicFillElem.isNull() ) return false; - QDomElement graphicElem = graphicFillElem.firstChildElement( "Graphic" ); + QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return false; @@ -1329,7 +1329,7 @@ bool QgsSymbolLayerUtils::needLinePatternFill( QDomElement &element ) if ( !wellKnownMarkerFromSld( graphicElem, name, fillColor, borderColor, borderStyle, borderWidth, size ) ) return false; - if ( name != "horline" ) + if ( name != QLatin1String( "horline" ) ) return false; QString angleFunc; @@ -1352,11 +1352,11 @@ bool QgsSymbolLayerUtils::needPointPatternFill( QDomElement &element ) bool QgsSymbolLayerUtils::needSvgFill( QDomElement &element ) { - QDomElement fillElem = element.firstChildElement( "Fill" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); if ( fillElem.isNull() ) return false; - QDomElement graphicFillElem = fillElem.firstChildElement( "GraphicFill" ); + QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) ); if ( graphicFillElem.isNull() ) return false; @@ -1377,8 +1377,8 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el QgsSymbolLayerList layers; // retrieve both Fill and Stroke elements - QDomElement fillElem = element.firstChildElement( "Fill" ); - QDomElement strokeElem = element.firstChildElement( "Stroke" ); + QDomElement fillElem = element.firstChildElement( QStringLiteral( "Fill" ) ); + QDomElement strokeElem = element.firstChildElement( QStringLiteral( "Stroke" ) ); // first symbol layer { @@ -1406,13 +1406,13 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el if ( validFill || validBorder ) { QgsStringMap map; - map["name"] = "square"; - map["color"] = encodeColor( validFill ? fillColor : Qt::transparent ); - map["color_border"] = encodeColor( validBorder ? borderColor : Qt::transparent ); - map["size"] = QString::number( 6 ); - map["angle"] = QString::number( 0 ); - map["offset"] = encodePoint( QPointF( 0, 0 ) ); - layers.append( QgsSymbolLayerRegistry::instance()->createSymbolLayer( "SimpleMarker", map ) ); + map[QStringLiteral( "name" )] = QStringLiteral( "square" ); + map[QStringLiteral( "color" )] = encodeColor( validFill ? fillColor : Qt::transparent ); + map[QStringLiteral( "color_border" )] = encodeColor( validBorder ? borderColor : Qt::transparent ); + map[QStringLiteral( "size" )] = QString::number( 6 ); + map[QStringLiteral( "angle" )] = QString::number( 0 ); + map[QStringLiteral( "offset" )] = encodePoint( QPointF( 0, 0 ) ); + layers.append( QgsSymbolLayerRegistry::instance()->createSymbolLayer( QStringLiteral( "SimpleMarker" ), map ) ); } } @@ -1428,11 +1428,11 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el QPointF anchor, offset; // Fill element can contain a GraphicFill element - QDomElement graphicFillElem = fillElem.firstChildElement( "GraphicFill" ); + QDomElement graphicFillElem = fillElem.firstChildElement( QStringLiteral( "GraphicFill" ) ); if ( !graphicFillElem.isNull() ) { // GraphicFill element must contain a Graphic element - QDomElement graphicElem = graphicFillElem.firstChildElement( "Graphic" ); + QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) ); if ( !graphicElem.isNull() ) { // Graphic element can contains some ExternalGraphic and Mark element @@ -1442,10 +1442,10 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el QDomElement graphicChildElem = graphicElem.firstChildElement(); while ( !graphicChildElem.isNull() ) { - if ( graphicChildElem.localName() == "Mark" ) + if ( graphicChildElem.localName() == QLatin1String( "Mark" ) ) { // check for a well known name - QDomElement wellKnownNameElem = graphicChildElem.firstChildElement( "WellKnownName" ); + QDomElement wellKnownNameElem = graphicChildElem.firstChildElement( QStringLiteral( "WellKnownName" ) ); if ( !wellKnownNameElem.isNull() ) { name = wellKnownNameElem.firstChild().nodeValue(); @@ -1454,10 +1454,10 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el } } - if ( graphicChildElem.localName() == "ExternalGraphic" || graphicChildElem.localName() == "Mark" ) + if ( graphicChildElem.localName() == QLatin1String( "ExternalGraphic" ) || graphicChildElem.localName() == QLatin1String( "Mark" ) ) { // check for external graphic format - QDomElement formatElem = graphicChildElem.firstChildElement( "Format" ); + QDomElement formatElem = graphicChildElem.firstChildElement( QStringLiteral( "Format" ) ); if ( formatElem.isNull() ) continue; @@ -1465,30 +1465,30 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el // TODO: remove this check when more formats will be supported // only SVG external graphics are supported in this moment - if ( graphicChildElem.localName() == "ExternalGraphic" && format != "image/svg+xml" ) + if ( graphicChildElem.localName() == QLatin1String( "ExternalGraphic" ) && format != QLatin1String( "image/svg+xml" ) ) continue; // TODO: remove this check when more formats will be supported // only ttf marks are supported in this moment - if ( graphicChildElem.localName() == "Mark" && format != "ttf" ) + if ( graphicChildElem.localName() == QLatin1String( "Mark" ) && format != QLatin1String( "ttf" ) ) continue; // check for a valid content - QDomElement onlineResourceElem = graphicChildElem.firstChildElement( "OnlineResource" ); - QDomElement inlineContentElem = graphicChildElem.firstChildElement( "InlineContent" ); + QDomElement onlineResourceElem = graphicChildElem.firstChildElement( QStringLiteral( "OnlineResource" ) ); + QDomElement inlineContentElem = graphicChildElem.firstChildElement( QStringLiteral( "InlineContent" ) ); if ( !onlineResourceElem.isNull() ) { - name = onlineResourceElem.attributeNS( "http://www.w3.org/1999/xlink", "href" ); + name = onlineResourceElem.attributeNS( QStringLiteral( "http://www.w3.org/1999/xlink" ), QStringLiteral( "href" ) ); - if ( graphicChildElem.localName() == "Mark" && format == "ttf" ) + if ( graphicChildElem.localName() == QLatin1String( "Mark" ) && format == QLatin1String( "ttf" ) ) { // mark with ttf format may have a name like ttf://fontFamily - if ( name.startsWith( "ttf://" ) ) + if ( name.startsWith( QLatin1String( "ttf://" ) ) ) name = name.mid( 6 ); // mark with ttf format has a markIndex element - QDomElement markIndexElem = graphicChildElem.firstChildElement( "MarkIndex" ); + QDomElement markIndexElem = graphicChildElem.firstChildElement( QStringLiteral( "MarkIndex" ) ); if ( markIndexElem.isNull() ) continue; @@ -1514,16 +1514,16 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el // if Mark element is present but it doesn't contains neither // WellKnownName nor OnlineResource nor InlineContent, // use the default mark (square) - if ( graphicChildElem.localName() == "Mark" ) + if ( graphicChildElem.localName() == QLatin1String( "Mark" ) ) { - name = "square"; + name = QStringLiteral( "square" ); found = true; break; } } // if found a valid Mark, check for its Fill and Stroke element - if ( found && graphicChildElem.localName() == "Mark" ) + if ( found && graphicChildElem.localName() == QLatin1String( "Mark" ) ) { // XXX: recursive definition!?! couldn't be dangerous??? // to avoid recursion we handle only simple fill and simple stroke @@ -1532,7 +1532,7 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el // Fill element can contain some SvgParameter elements Qt::BrushStyle markFillStyle; - QDomElement markFillElem = graphicChildElem.firstChildElement( "Fill" ); + QDomElement markFillElem = graphicChildElem.firstChildElement( QStringLiteral( "Fill" ) ); if ( fillFromSld( markFillElem, markFillStyle, fillColor ) ) validFill = true; @@ -1542,7 +1542,7 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el double borderWidth = 1.0, dashOffset = 0.0; QVector<qreal> customDashPattern; - QDomElement markStrokeElem = graphicChildElem.firstChildElement( "Stroke" ); + QDomElement markStrokeElem = graphicChildElem.firstChildElement( QStringLiteral( "Stroke" ) ); if ( lineFromSld( markStrokeElem, borderStyle, borderColor, borderWidth, nullptr, nullptr, &customDashPattern, &dashOffset ) ) validBorder = true; @@ -1551,11 +1551,11 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el if ( found ) { // check for Opacity, Size, Rotation, AnchorPoint, Displacement - QDomElement opacityElem = graphicElem.firstChildElement( "Opacity" ); + QDomElement opacityElem = graphicElem.firstChildElement( QStringLiteral( "Opacity" ) ); if ( !opacityElem.isNull() ) fillColor.setAlpha( decodeSldAlpha( opacityElem.firstChild().nodeValue() ) ); - QDomElement sizeElem = graphicElem.firstChildElement( "Size" ); + QDomElement sizeElem = graphicElem.firstChildElement( QStringLiteral( "Size" ) ); if ( !sizeElem.isNull() ) { bool ok; @@ -1580,34 +1580,34 @@ bool QgsSymbolLayerUtils::convertPolygonSymbolizerToPointMarker( QDomElement &el if ( validFill || validBorder ) { - if ( format == "image/svg+xml" ) + if ( format == QLatin1String( "image/svg+xml" ) ) { QgsStringMap map; - map["name"] = name; - map["fill"] = fillColor.name(); - map["outline"] = borderColor.name(); - map["outline-width"] = QString::number( borderWidth ); + map[QStringLiteral( "name" )] = name; + map[QStringLiteral( "fill" )] = fillColor.name(); + map[QStringLiteral( "outline" )] = borderColor.name(); + map[QStringLiteral( "outline-width" )] = QString::number( borderWidth ); if ( !qgsDoubleNear( size, 0.0 ) ) - map["size"] = QString::number( size ); + map[QStringLiteral( "size" )] = QString::number( size ); if ( !qgsDoubleNear( angle, 0.0 ) ) - map["angle"] = QString::number( angle ); + map[QStringLiteral( "angle" )] = QString::number( angle ); if ( !offset.isNull() ) - map["offset"] = encodePoint( offset ); - layers.append( QgsSymbolLayerRegistry::instance()->createSymbolLayer( "SvgMarker", map ) ); + map[QStringLiteral( "offset" )] = encodePoint( offset ); + layers.append( QgsSymbolLayerRegistry::instance()->createSymbolLayer( QStringLiteral( "SvgMarker" ), map ) ); } - else if ( format == "ttf" ) + else if ( format == QLatin1String( "ttf" ) ) { QgsStringMap map; - map["font"] = name; - map["chr"] = markIndex; - map["color"] = encodeColor( validFill ? fillColor : Qt::transparent ); + map[QStringLiteral( "font" )] = name; + map[QStringLiteral( "chr" )] = markIndex; + map[QStringLiteral( "color" )] = encodeColor( validFill ? fillColor : Qt::transparent ); if ( size > 0 ) - map["size"] = QString::number( size ); + map[QStringLiteral( "size" )] = QString::number( size ); if ( !qgsDoubleNear( angle, 0.0 ) ) - map["angle"] = QString::number( angle ); + map[QStringLiteral( "angle" )] = QString::number( angle ); if ( !offset.isNull() ) - map["offset"] = encodePoint( offset ); - layers.append( QgsSymbolLayerRegistry::instance()->createSymbolLayer( "FontMarker", map ) ); + map[QStringLiteral( "offset" )] = encodePoint( offset ); + layers.append( QgsSymbolLayerRegistry::instance()->createSymbolLayer( QStringLiteral( "FontMarker" ), map ) ); } } } @@ -1631,9 +1631,9 @@ void QgsSymbolLayerUtils::fillToSld( QDomDocument &doc, QDomElement &element, Qt case Qt::SolidPattern: if ( color.isValid() ) { - element.appendChild( createSvgParameterElement( doc, "fill", color.name() ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "fill" ), color.name() ) ); if ( color.alpha() < 255 ) - element.appendChild( createSvgParameterElement( doc, "fill-opacity", encodeSldAlpha( color.alpha() ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "fill-opacity" ), encodeSldAlpha( color.alpha() ) ) ); } return; @@ -1654,18 +1654,18 @@ void QgsSymbolLayerUtils::fillToSld( QDomDocument &doc, QDomElement &element, Qt break; default: - element.appendChild( doc.createComment( QString( "Qt::BrushStyle '%1'' not supported yet" ).arg( brushStyle ) ) ); + element.appendChild( doc.createComment( QStringLiteral( "Qt::BrushStyle '%1'' not supported yet" ).arg( brushStyle ) ) ); return; } - QDomElement graphicFillElem = doc.createElement( "se:GraphicFill" ); + QDomElement graphicFillElem = doc.createElement( QStringLiteral( "se:GraphicFill" ) ); element.appendChild( graphicFillElem ); - QDomElement graphicElem = doc.createElement( "se:Graphic" ); + QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); graphicFillElem.appendChild( graphicElem ); - QColor fillColor = patternName.startsWith( "brush://" ) ? color : QColor(); - QColor borderColor = !patternName.startsWith( "brush://" ) ? color : QColor(); + QColor fillColor = patternName.startsWith( QLatin1String( "brush://" ) ) ? color : QColor(); + QColor borderColor = !patternName.startsWith( QLatin1String( "brush://" ) ) ? color : QColor(); /* Use WellKnownName tag to handle QT brush styles. */ wellKnownMarkerToSld( doc, graphicElem, patternName, fillColor, borderColor, Qt::SolidLine, -1, -1 ); @@ -1685,7 +1685,7 @@ bool QgsSymbolLayerUtils::fillFromSld( QDomElement &element, Qt::BrushStyle &bru return true; } - QDomElement graphicFillElem = element.firstChildElement( "GraphicFill" ); + QDomElement graphicFillElem = element.firstChildElement( QStringLiteral( "GraphicFill" ) ); // if no GraphicFill element is found, it's a solid fill if ( graphicFillElem.isNull() ) { @@ -1694,19 +1694,19 @@ bool QgsSymbolLayerUtils::fillFromSld( QDomElement &element, Qt::BrushStyle &bru { QgsDebugMsg( QString( "found SvgParameter %1: %2" ).arg( it.key(), it.value() ) ); - if ( it.key() == "fill" ) + if ( it.key() == QLatin1String( "fill" ) ) color = QColor( it.value() ); - else if ( it.key() == "fill-opacity" ) + else if ( it.key() == QLatin1String( "fill-opacity" ) ) color.setAlpha( decodeSldAlpha( it.value() ) ); } } else // wellKnown marker { - QDomElement graphicElem = graphicFillElem.firstChildElement( "Graphic" ); + QDomElement graphicElem = graphicFillElem.firstChildElement( QStringLiteral( "Graphic" ) ); if ( graphicElem.isNull() ) return false; // Graphic is required within GraphicFill - QString patternName = "square"; + QString patternName = QStringLiteral( "square" ); QColor fillColor, borderColor; double borderWidth, size; Qt::PenStyle borderStyle; @@ -1717,7 +1717,7 @@ bool QgsSymbolLayerUtils::fillFromSld( QDomElement &element, Qt::BrushStyle &bru if ( brushStyle == Qt::NoBrush ) return false; // unable to decode brush style - QColor c = patternName.startsWith( "brush://" ) ? fillColor : borderColor; + QColor c = patternName.startsWith( QLatin1String( "brush://" ) ) ? fillColor : borderColor; if ( c.isValid() ) color = c; } @@ -1735,7 +1735,7 @@ void QgsSymbolLayerUtils::lineToSld( QDomDocument &doc, QDomElement &element, if ( penStyle == Qt::CustomDashLine && !customDashPattern ) { - element.appendChild( doc.createComment( "WARNING: Custom dash pattern required but not provided. Using default dash pattern." ) ); + element.appendChild( doc.createComment( QStringLiteral( "WARNING: Custom dash pattern required but not provided. Using default dash pattern." ) ) ); penStyle = Qt::DashLine; } @@ -1776,28 +1776,28 @@ void QgsSymbolLayerUtils::lineToSld( QDomDocument &doc, QDomElement &element, break; default: - element.appendChild( doc.createComment( QString( "Qt::BrushStyle '%1'' not supported yet" ).arg( penStyle ) ) ); + element.appendChild( doc.createComment( QStringLiteral( "Qt::BrushStyle '%1'' not supported yet" ).arg( penStyle ) ) ); return; } if ( color.isValid() ) { - element.appendChild( createSvgParameterElement( doc, "stroke", color.name() ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke" ), color.name() ) ); if ( color.alpha() < 255 ) - element.appendChild( createSvgParameterElement( doc, "stroke-opacity", encodeSldAlpha( color.alpha() ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke-opacity" ), encodeSldAlpha( color.alpha() ) ) ); } if ( width > 0 ) - element.appendChild( createSvgParameterElement( doc, "stroke-width", qgsDoubleToString( width ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke-width" ), qgsDoubleToString( width ) ) ); if ( penJoinStyle ) - element.appendChild( createSvgParameterElement( doc, "stroke-linejoin", encodeSldLineJoinStyle( *penJoinStyle ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke-linejoin" ), encodeSldLineJoinStyle( *penJoinStyle ) ) ); if ( penCapStyle ) - element.appendChild( createSvgParameterElement( doc, "stroke-linecap", encodeSldLineCapStyle( *penCapStyle ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke-linecap" ), encodeSldLineCapStyle( *penCapStyle ) ) ); if ( !pattern->isEmpty() ) { - element.appendChild( createSvgParameterElement( doc, "stroke-dasharray", encodeSldRealVector( *pattern ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke-dasharray" ), encodeSldRealVector( *pattern ) ) ); if ( !qgsDoubleNear( dashOffset, 0.0 ) ) - element.appendChild( createSvgParameterElement( doc, "stroke-dashoffset", qgsDoubleToString( dashOffset ) ) ); + element.appendChild( createSvgParameterElement( doc, QStringLiteral( "stroke-dashoffset" ), qgsDoubleToString( dashOffset ) ) ); } } @@ -1833,30 +1833,30 @@ bool QgsSymbolLayerUtils::lineFromSld( QDomElement &element, { QgsDebugMsg( QString( "found SvgParameter %1: %2" ).arg( it.key(), it.value() ) ); - if ( it.key() == "stroke" ) + if ( it.key() == QLatin1String( "stroke" ) ) { color = QColor( it.value() ); } - else if ( it.key() == "stroke-opacity" ) + else if ( it.key() == QLatin1String( "stroke-opacity" ) ) { color.setAlpha( decodeSldAlpha( it.value() ) ); } - else if ( it.key() == "stroke-width" ) + else if ( it.key() == QLatin1String( "stroke-width" ) ) { bool ok; double w = it.value().toDouble( &ok ); if ( ok ) width = w; } - else if ( it.key() == "stroke-linejoin" && penJoinStyle ) + else if ( it.key() == QLatin1String( "stroke-linejoin" ) && penJoinStyle ) { *penJoinStyle = decodeSldLineJoinStyle( it.value() ); } - else if ( it.key() == "stroke-linecap" && penCapStyle ) + else if ( it.key() == QLatin1String( "stroke-linecap" ) && penCapStyle ) { *penCapStyle = decodeSldLineCapStyle( it.value() ); } - else if ( it.key() == "stroke-dasharray" ) + else if ( it.key() == QLatin1String( "stroke-dasharray" ) ) { QVector<qreal> dashPattern = decodeSldRealVector( it.value() ); if ( !dashPattern.isEmpty() ) @@ -1921,7 +1921,7 @@ bool QgsSymbolLayerUtils::lineFromSld( QDomElement &element, } } } - else if ( it.key() == "stroke-dashoffset" && dashOffset ) + else if ( it.key() == QLatin1String( "stroke-dashoffset" ) && dashOffset ) { bool ok; double d = it.value().toDouble( &ok ); @@ -1937,7 +1937,7 @@ void QgsSymbolLayerUtils::externalGraphicToSld( QDomDocument &doc, QDomElement & const QString& path, const QString& mime, const QColor& color, double size ) { - QDomElement externalGraphicElem = doc.createElement( "se:ExternalGraphic" ); + QDomElement externalGraphicElem = doc.createElement( QStringLiteral( "se:ExternalGraphic" ) ); element.appendChild( externalGraphicElem ); createOnlineResourceElement( doc, externalGraphicElem, path, mime ); @@ -1947,7 +1947,7 @@ void QgsSymbolLayerUtils::externalGraphicToSld( QDomDocument &doc, QDomElement & if ( size >= 0 ) { - QDomElement sizeElem = doc.createElement( "se:Size" ); + QDomElement sizeElem = doc.createElement( QStringLiteral( "se:Size" ) ); sizeElem.appendChild( doc.createTextNode( qgsDoubleToString( size ) ) ); element.appendChild( sizeElem ); } @@ -1960,13 +1960,13 @@ bool QgsSymbolLayerUtils::externalGraphicFromSld( QDomElement &element, QgsDebugMsg( "Entered." ); Q_UNUSED( color ); - QDomElement externalGraphicElem = element.firstChildElement( "ExternalGraphic" ); + QDomElement externalGraphicElem = element.firstChildElement( QStringLiteral( "ExternalGraphic" ) ); if ( externalGraphicElem.isNull() ) return false; onlineResourceFromSldElement( externalGraphicElem, path, mime ); - QDomElement sizeElem = element.firstChildElement( "Size" ); + QDomElement sizeElem = element.firstChildElement( QStringLiteral( "Size" ) ); if ( !sizeElem.isNull() ) { bool ok; @@ -1982,27 +1982,27 @@ void QgsSymbolLayerUtils::externalMarkerToSld( QDomDocument &doc, QDomElement &e const QString& path, const QString& format, int *markIndex, const QColor& color, double size ) { - QDomElement markElem = doc.createElement( "se:Mark" ); + QDomElement markElem = doc.createElement( QStringLiteral( "se:Mark" ) ); element.appendChild( markElem ); createOnlineResourceElement( doc, markElem, path, format ); if ( markIndex ) { - QDomElement markIndexElem = doc.createElement( "se:MarkIndex" ); + QDomElement markIndexElem = doc.createElement( QStringLiteral( "se:MarkIndex" ) ); markIndexElem.appendChild( doc.createTextNode( QString::number( *markIndex ) ) ); markElem.appendChild( markIndexElem ); } // <Fill> - QDomElement fillElem = doc.createElement( "se:Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) ); fillToSld( doc, fillElem, Qt::SolidPattern, color ); markElem.appendChild( fillElem ); // <Size> if ( !qgsDoubleNear( size, 0.0 ) && size > 0 ) { - QDomElement sizeElem = doc.createElement( "se:Size" ); + QDomElement sizeElem = doc.createElement( QStringLiteral( "se:Size" ) ); sizeElem.appendChild( doc.createTextNode( qgsDoubleToString( size ) ) ); element.appendChild( sizeElem ); } @@ -2018,13 +2018,13 @@ bool QgsSymbolLayerUtils::externalMarkerFromSld( QDomElement &element, markIndex = -1; size = -1; - QDomElement markElem = element.firstChildElement( "Mark" ); + QDomElement markElem = element.firstChildElement( QStringLiteral( "Mark" ) ); if ( markElem.isNull() ) return false; onlineResourceFromSldElement( markElem, path, format ); - QDomElement markIndexElem = markElem.firstChildElement( "MarkIndex" ); + QDomElement markIndexElem = markElem.firstChildElement( QStringLiteral( "MarkIndex" ) ); if ( !markIndexElem.isNull() ) { bool ok; @@ -2034,13 +2034,13 @@ bool QgsSymbolLayerUtils::externalMarkerFromSld( QDomElement &element, } // <Fill> - QDomElement fillElem = markElem.firstChildElement( "Fill" ); + QDomElement fillElem = markElem.firstChildElement( QStringLiteral( "Fill" ) ); Qt::BrushStyle b = Qt::SolidPattern; fillFromSld( fillElem, b, color ); // ignore brush style, solid expected // <Size> - QDomElement sizeElem = element.firstChildElement( "Size" ); + QDomElement sizeElem = element.firstChildElement( QStringLiteral( "Size" ) ); if ( !sizeElem.isNull() ) { bool ok; @@ -2056,17 +2056,17 @@ void QgsSymbolLayerUtils::wellKnownMarkerToSld( QDomDocument &doc, QDomElement & const QString& name, const QColor& color, const QColor& borderColor, Qt::PenStyle borderStyle, double borderWidth, double size ) { - QDomElement markElem = doc.createElement( "se:Mark" ); + QDomElement markElem = doc.createElement( QStringLiteral( "se:Mark" ) ); element.appendChild( markElem ); - QDomElement wellKnownNameElem = doc.createElement( "se:WellKnownName" ); + QDomElement wellKnownNameElem = doc.createElement( QStringLiteral( "se:WellKnownName" ) ); wellKnownNameElem.appendChild( doc.createTextNode( name ) ); markElem.appendChild( wellKnownNameElem ); // <Fill> if ( color.isValid() ) { - QDomElement fillElem = doc.createElement( "se:Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "se:Fill" ) ); fillToSld( doc, fillElem, Qt::SolidPattern, color ); markElem.appendChild( fillElem ); } @@ -2074,7 +2074,7 @@ void QgsSymbolLayerUtils::wellKnownMarkerToSld( QDomDocument &doc, QDomElement & // <Stroke> if ( borderColor.isValid() ) { - QDomElement strokeElem = doc.createElement( "se:Stroke" ); + QDomElement strokeElem = doc.createElement( QStringLiteral( "se:Stroke" ) ); lineToSld( doc, strokeElem, borderStyle, borderColor, borderWidth ); markElem.appendChild( strokeElem ); } @@ -2082,7 +2082,7 @@ void QgsSymbolLayerUtils::wellKnownMarkerToSld( QDomDocument &doc, QDomElement & // <Size> if ( !qgsDoubleNear( size, 0.0 ) && size > 0 ) { - QDomElement sizeElem = doc.createElement( "se:Size" ); + QDomElement sizeElem = doc.createElement( QStringLiteral( "se:Size" ) ); sizeElem.appendChild( doc.createTextNode( qgsDoubleToString( size ) ) ); element.appendChild( sizeElem ); } @@ -2094,17 +2094,17 @@ bool QgsSymbolLayerUtils::wellKnownMarkerFromSld( QDomElement &element, { QgsDebugMsg( "Entered." ); - name = "square"; + name = QStringLiteral( "square" ); color = QColor(); borderColor = QColor( "#000000" ); borderWidth = 1; size = 6; - QDomElement markElem = element.firstChildElement( "Mark" ); + QDomElement markElem = element.firstChildElement( QStringLiteral( "Mark" ) ); if ( markElem.isNull() ) return false; - QDomElement wellKnownNameElem = markElem.firstChildElement( "WellKnownName" ); + QDomElement wellKnownNameElem = markElem.firstChildElement( QStringLiteral( "WellKnownName" ) ); if ( !wellKnownNameElem.isNull() ) { name = wellKnownNameElem.firstChild().nodeValue(); @@ -2112,18 +2112,18 @@ bool QgsSymbolLayerUtils::wellKnownMarkerFromSld( QDomElement &element, } // <Fill> - QDomElement fillElem = markElem.firstChildElement( "Fill" ); + QDomElement fillElem = markElem.firstChildElement( QStringLiteral( "Fill" ) ); Qt::BrushStyle b = Qt::SolidPattern; fillFromSld( fillElem, b, color ); // ignore brush style, solid expected // <Stroke> - QDomElement strokeElem = markElem.firstChildElement( "Stroke" ); + QDomElement strokeElem = markElem.firstChildElement( QStringLiteral( "Stroke" ) ); lineFromSld( strokeElem, borderStyle, borderColor, borderWidth ); // ignore border style, solid expected // <Size> - QDomElement sizeElem = element.firstChildElement( "Size" ); + QDomElement sizeElem = element.firstChildElement( QStringLiteral( "Size" ) ); if ( !sizeElem.isNull() ) { bool ok; @@ -2139,7 +2139,7 @@ void QgsSymbolLayerUtils::createRotationElement( QDomDocument &doc, QDomElement { if ( !rotationFunc.isEmpty() ) { - QDomElement rotationElem = doc.createElement( "se:Rotation" ); + QDomElement rotationElem = doc.createElement( QStringLiteral( "se:Rotation" ) ); createExpressionElement( doc, rotationElem, rotationFunc ); element.appendChild( rotationElem ); } @@ -2147,7 +2147,7 @@ void QgsSymbolLayerUtils::createRotationElement( QDomDocument &doc, QDomElement bool QgsSymbolLayerUtils::rotationFromSldElement( QDomElement &element, QString &rotationFunc ) { - QDomElement rotationElem = element.firstChildElement( "Rotation" ); + QDomElement rotationElem = element.firstChildElement( QStringLiteral( "Rotation" ) ); if ( !rotationElem.isNull() ) { return functionFromSldElement( rotationElem, rotationFunc ); @@ -2160,7 +2160,7 @@ void QgsSymbolLayerUtils::createOpacityElement( QDomDocument &doc, QDomElement & { if ( !alphaFunc.isEmpty() ) { - QDomElement opacityElem = doc.createElement( "se:Opacity" ); + QDomElement opacityElem = doc.createElement( QStringLiteral( "se:Opacity" ) ); createExpressionElement( doc, opacityElem, alphaFunc ); element.appendChild( opacityElem ); } @@ -2168,7 +2168,7 @@ void QgsSymbolLayerUtils::createOpacityElement( QDomDocument &doc, QDomElement & bool QgsSymbolLayerUtils::opacityFromSldElement( QDomElement &element, QString &alphaFunc ) { - QDomElement opacityElem = element.firstChildElement( "Opacity" ); + QDomElement opacityElem = element.firstChildElement( QStringLiteral( "Opacity" ) ); if ( !opacityElem.isNull() ) { return functionFromSldElement( opacityElem, alphaFunc ); @@ -2181,13 +2181,13 @@ void QgsSymbolLayerUtils::createDisplacementElement( QDomDocument &doc, QDomElem if ( offset.isNull() ) return; - QDomElement displacementElem = doc.createElement( "se:Displacement" ); + QDomElement displacementElem = doc.createElement( QStringLiteral( "se:Displacement" ) ); element.appendChild( displacementElem ); - QDomElement dispXElem = doc.createElement( "se:DisplacementX" ); + QDomElement dispXElem = doc.createElement( QStringLiteral( "se:DisplacementX" ) ); dispXElem.appendChild( doc.createTextNode( qgsDoubleToString( offset.x() ) ) ); - QDomElement dispYElem = doc.createElement( "se:DisplacementY" ); + QDomElement dispYElem = doc.createElement( QStringLiteral( "se:DisplacementY" ) ); dispYElem.appendChild( doc.createTextNode( qgsDoubleToString( offset.y() ) ) ); displacementElem.appendChild( dispXElem ); @@ -2198,11 +2198,11 @@ bool QgsSymbolLayerUtils::displacementFromSldElement( QDomElement &element, QPoi { offset = QPointF( 0, 0 ); - QDomElement displacementElem = element.firstChildElement( "Displacement" ); + QDomElement displacementElem = element.firstChildElement( QStringLiteral( "Displacement" ) ); if ( displacementElem.isNull() ) return true; - QDomElement dispXElem = displacementElem.firstChildElement( "DisplacementX" ); + QDomElement dispXElem = displacementElem.firstChildElement( QStringLiteral( "DisplacementX" ) ); if ( !dispXElem.isNull() ) { bool ok; @@ -2211,7 +2211,7 @@ bool QgsSymbolLayerUtils::displacementFromSldElement( QDomElement &element, QPoi offset.setX( offsetX ); } - QDomElement dispYElem = displacementElem.firstChildElement( "DisplacementY" ); + QDomElement dispYElem = displacementElem.firstChildElement( QStringLiteral( "DisplacementY" ) ); if ( !dispYElem.isNull() ) { bool ok; @@ -2227,24 +2227,24 @@ void QgsSymbolLayerUtils::labelTextToSld( QDomDocument &doc, QDomElement &elemen const QString& label, const QFont& font, const QColor& color, double size ) { - QDomElement labelElem = doc.createElement( "se:Label" ); + QDomElement labelElem = doc.createElement( QStringLiteral( "se:Label" ) ); labelElem.appendChild( doc.createTextNode( label ) ); element.appendChild( labelElem ); - QDomElement fontElem = doc.createElement( "se:Font" ); + QDomElement fontElem = doc.createElement( QStringLiteral( "se:Font" ) ); element.appendChild( fontElem ); - fontElem.appendChild( createSvgParameterElement( doc, "font-family", font.family() ) ); + fontElem.appendChild( createSvgParameterElement( doc, QStringLiteral( "font-family" ), font.family() ) ); #if 0 fontElem.appendChild( createSldParameterElement( doc, "font-style", encodeSldFontStyle( font.style() ) ) ); fontElem.appendChild( createSldParameterElement( doc, "font-weight", encodeSldFontWeight( font.weight() ) ) ); #endif - fontElem.appendChild( createSvgParameterElement( doc, "font-size", QString::number( size ) ) ); + fontElem.appendChild( createSvgParameterElement( doc, QStringLiteral( "font-size" ), QString::number( size ) ) ); // <Fill> if ( color.isValid() ) { - QDomElement fillElem = doc.createElement( "Fill" ); + QDomElement fillElem = doc.createElement( QStringLiteral( "Fill" ) ); fillToSld( doc, fillElem, Qt::SolidPattern, color ); element.appendChild( fillElem ); } @@ -2339,7 +2339,7 @@ void QgsSymbolLayerUtils::createGeometryElement( QDomDocument &doc, QDomElement if ( geomFunc.isEmpty() ) return; - QDomElement geometryElem = doc.createElement( "Geometry" ); + QDomElement geometryElem = doc.createElement( QStringLiteral( "Geometry" ) ); element.appendChild( geometryElem ); /* About using a function withing the Geometry tag. @@ -2370,7 +2370,7 @@ void QgsSymbolLayerUtils::createGeometryElement( QDomDocument &doc, QDomElement bool QgsSymbolLayerUtils::geometryFromSldElement( QDomElement &element, QString &geomFunc ) { - QDomElement geometryElem = element.firstChildElement( "Geometry" ); + QDomElement geometryElem = element.firstChildElement( QStringLiteral( "Geometry" ) ); if ( geometryElem.isNull() ) return true; @@ -2411,9 +2411,9 @@ bool QgsSymbolLayerUtils::createFunctionElement( QDomDocument &doc, QDomElement bool QgsSymbolLayerUtils::functionFromSldElement( QDomElement &element, QString &function ) { QDomElement elem = element; - if ( element.tagName() != "Filter" ) + if ( element.tagName() != QLatin1String( "Filter" ) ) { - QDomNodeList filterNodes = element.elementsByTagName( "Filter" ); + QDomNodeList filterNodes = element.elementsByTagName( QStringLiteral( "Filter" ) ); if ( !filterNodes.isEmpty() ) { elem = filterNodes.at( 0 ).toElement(); @@ -2449,12 +2449,12 @@ void QgsSymbolLayerUtils::createOnlineResourceElement( QDomDocument &doc, QDomEl { // get resource url or relative path QString url = symbolPathToName( path ); - QDomElement onlineResourceElem = doc.createElement( "se:OnlineResource" ); - onlineResourceElem.setAttribute( "xlink:type", "simple" ); - onlineResourceElem.setAttribute( "xlink:href", url ); + QDomElement onlineResourceElem = doc.createElement( QStringLiteral( "se:OnlineResource" ) ); + onlineResourceElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + onlineResourceElem.setAttribute( QStringLiteral( "xlink:href" ), url ); element.appendChild( onlineResourceElem ); - QDomElement formatElem = doc.createElement( "se:Format" ); + QDomElement formatElem = doc.createElement( QStringLiteral( "se:Format" ) ); formatElem.appendChild( doc.createTextNode( format ) ); element.appendChild( formatElem ); } @@ -2463,13 +2463,13 @@ bool QgsSymbolLayerUtils::onlineResourceFromSldElement( QDomElement &element, QS { QgsDebugMsg( "Entered." ); - QDomElement onlineResourceElem = element.firstChildElement( "OnlineResource" ); + QDomElement onlineResourceElem = element.firstChildElement( QStringLiteral( "OnlineResource" ) ); if ( onlineResourceElem.isNull() ) return false; - path = onlineResourceElem.attributeNS( "http://www.w3.org/1999/xlink", "href" ); + path = onlineResourceElem.attributeNS( QStringLiteral( "http://www.w3.org/1999/xlink" ), QStringLiteral( "href" ) ); - QDomElement formatElem = element.firstChildElement( "Format" ); + QDomElement formatElem = element.firstChildElement( QStringLiteral( "Format" ) ); if ( formatElem.isNull() ) return false; // OnlineResource requires a Format sibling element @@ -2480,8 +2480,8 @@ bool QgsSymbolLayerUtils::onlineResourceFromSldElement( QDomElement &element, QS QDomElement QgsSymbolLayerUtils::createSvgParameterElement( QDomDocument &doc, const QString& name, const QString& value ) { - QDomElement nodeElem = doc.createElement( "se:SvgParameter" ); - nodeElem.setAttribute( "name", name ); + QDomElement nodeElem = doc.createElement( QStringLiteral( "se:SvgParameter" ) ); + nodeElem.setAttribute( QStringLiteral( "name" ), name ); nodeElem.appendChild( doc.createTextNode( value ) ); return nodeElem; } @@ -2493,9 +2493,9 @@ QgsStringMap QgsSymbolLayerUtils::getSvgParameterList( QDomElement &element ) QDomElement paramElem = element.firstChildElement(); while ( !paramElem.isNull() ) { - if ( paramElem.localName() == "SvgParameter" || paramElem.localName() == "CssParameter" ) + if ( paramElem.localName() == QLatin1String( "SvgParameter" ) || paramElem.localName() == QLatin1String( "CssParameter" ) ) { - QString name = paramElem.attribute( "name" ); + QString name = paramElem.attribute( QStringLiteral( "name" ) ); QString value = paramElem.firstChild().nodeValue(); if ( !name.isEmpty() && !value.isEmpty() ) @@ -2510,8 +2510,8 @@ QgsStringMap QgsSymbolLayerUtils::getSvgParameterList( QDomElement &element ) QDomElement QgsSymbolLayerUtils::createVendorOptionElement( QDomDocument &doc, const QString& name, const QString& value ) { - QDomElement nodeElem = doc.createElement( "VendorOption" ); - nodeElem.setAttribute( "name", name ); + QDomElement nodeElem = doc.createElement( QStringLiteral( "VendorOption" ) ); + nodeElem.setAttribute( QStringLiteral( "name" ), name ); nodeElem.appendChild( doc.createTextNode( value ) ); return nodeElem; } @@ -2520,16 +2520,16 @@ QgsStringMap QgsSymbolLayerUtils::getVendorOptionList( QDomElement &element ) { QgsStringMap params; - QDomElement paramElem = element.firstChildElement( "VendorOption" ); + QDomElement paramElem = element.firstChildElement( QStringLiteral( "VendorOption" ) ); while ( !paramElem.isNull() ) { - QString name = paramElem.attribute( "name" ); + QString name = paramElem.attribute( QStringLiteral( "name" ) ); QString value = paramElem.firstChild().nodeValue(); if ( !name.isEmpty() && !value.isEmpty() ) params[ name ] = value; - paramElem = paramElem.nextSiblingElement( "VendorOption" ); + paramElem = paramElem.nextSiblingElement( QStringLiteral( "VendorOption" ) ); } return params; @@ -2542,14 +2542,14 @@ QgsStringMap QgsSymbolLayerUtils::parseProperties( QDomElement& element ) QDomElement e = element.firstChildElement(); while ( !e.isNull() ) { - if ( e.tagName() != "prop" ) + if ( e.tagName() != QLatin1String( "prop" ) ) { QgsDebugMsg( "unknown tag " + e.tagName() ); } else { - QString propKey = e.attribute( "k" ); - QString propValue = e.attribute( "v" ); + QString propKey = e.attribute( QStringLiteral( "k" ) ); + QString propValue = e.attribute( QStringLiteral( "v" ) ); props[propKey] = propValue; } e = e.nextSiblingElement(); @@ -2562,9 +2562,9 @@ void QgsSymbolLayerUtils::saveProperties( QgsStringMap props, QDomDocument& doc, { for ( QgsStringMap::iterator it = props.begin(); it != props.end(); ++it ) { - QDomElement propEl = doc.createElement( "prop" ); - propEl.setAttribute( "k", it.key() ); - propEl.setAttribute( "v", it.value() ); + QDomElement propEl = doc.createElement( QStringLiteral( "prop" ) ); + propEl.setAttribute( QStringLiteral( "k" ), it.key() ); + propEl.setAttribute( QStringLiteral( "v" ), it.value() ); element.appendChild( propEl ); } } @@ -2578,11 +2578,11 @@ QgsSymbolMap QgsSymbolLayerUtils::loadSymbols( QDomElement& element ) while ( !e.isNull() ) { - if ( e.tagName() == "symbol" ) + if ( e.tagName() == QLatin1String( "symbol" ) ) { QgsSymbol* symbol = QgsSymbolLayerUtils::loadSymbol( e ); if ( symbol ) - symbols.insert( e.attribute( "name" ), symbol ); + symbols.insert( e.attribute( QStringLiteral( "name" ) ), symbol ); } else { @@ -2670,20 +2670,20 @@ void QgsSymbolLayerUtils::clearSymbolMap( QgsSymbolMap& symbols ) QgsColorRamp* QgsSymbolLayerUtils::loadColorRamp( QDomElement& element ) { - QString rampType = element.attribute( "type" ); + QString rampType = element.attribute( QStringLiteral( "type" ) ); // parse properties QgsStringMap props = QgsSymbolLayerUtils::parseProperties( element ); - if ( rampType == "gradient" ) + if ( rampType == QLatin1String( "gradient" ) ) return QgsGradientColorRamp::create( props ); - else if ( rampType == "random" ) + else if ( rampType == QLatin1String( "random" ) ) return QgsLimitedRandomColorRamp::create( props ); - else if ( rampType == "colorbrewer" ) + else if ( rampType == QLatin1String( "colorbrewer" ) ) return QgsColorBrewerColorRamp::create( props ); - else if ( rampType == "cpt-city" ) + else if ( rampType == QLatin1String( "cpt-city" ) ) return QgsCptCityColorRamp::create( props ); - else if ( rampType == "preset" ) + else if ( rampType == QLatin1String( "preset" ) ) return QgsPresetSchemeColorRamp::create( props ); else { @@ -2695,9 +2695,9 @@ QgsColorRamp* QgsSymbolLayerUtils::loadColorRamp( QDomElement& element ) QDomElement QgsSymbolLayerUtils::saveColorRamp( const QString& name, QgsColorRamp* ramp, QDomDocument& doc ) { - QDomElement rampEl = doc.createElement( "colorramp" ); - rampEl.setAttribute( "type", ramp->type() ); - rampEl.setAttribute( "name", name ); + QDomElement rampEl = doc.createElement( QStringLiteral( "colorramp" ) ); + rampEl.setAttribute( QStringLiteral( "type" ), ramp->type() ); + rampEl.setAttribute( QStringLiteral( "name" ), name ); QgsSymbolLayerUtils::saveProperties( ramp->properties(), doc, rampEl ); return rampEl; @@ -2819,15 +2819,15 @@ QgsNamedColorList QgsSymbolLayerUtils::colorListFromMimeData( const QMimeData *d QgsNamedColorList mimeColors; //prefer xml format - if ( data->hasFormat( "text/xml" ) ) + if ( data->hasFormat( QStringLiteral( "text/xml" ) ) ) { //get XML doc - QByteArray encodedData = data->data( "text/xml" ); + QByteArray encodedData = data->data( QStringLiteral( "text/xml" ) ); QDomDocument xmlDoc; xmlDoc.setContent( encodedData ); QDomElement dragDataElem = xmlDoc.documentElement(); - if ( dragDataElem.tagName() == "ColorSchemeModelDragData" ) + if ( dragDataElem.tagName() == QLatin1String( "ColorSchemeModelDragData" ) ) { QDomNodeList nodeList = dragDataElem.childNodes(); int nChildNodes = nodeList.size(); @@ -2842,22 +2842,22 @@ QgsNamedColorList QgsSymbolLayerUtils::colorListFromMimeData( const QMimeData *d } QPair< QColor, QString> namedColor; - namedColor.first = QgsSymbolLayerUtils::decodeColor( currentElem.attribute( "color", "255,255,255,255" ) ); - namedColor.second = currentElem.attribute( "label", "" ); + namedColor.first = QgsSymbolLayerUtils::decodeColor( currentElem.attribute( QStringLiteral( "color" ), QStringLiteral( "255,255,255,255" ) ) ); + namedColor.second = currentElem.attribute( QStringLiteral( "label" ), QLatin1String( "" ) ); mimeColors << namedColor; } } } - if ( mimeColors.length() == 0 && data->hasFormat( "application/x-colorobject-list" ) ) + if ( mimeColors.length() == 0 && data->hasFormat( QStringLiteral( "application/x-colorobject-list" ) ) ) { //get XML doc - QByteArray encodedData = data->data( "application/x-colorobject-list" ); + QByteArray encodedData = data->data( QStringLiteral( "application/x-colorobject-list" ) ); QDomDocument xmlDoc; xmlDoc.setContent( encodedData ); - QDomNodeList colorsNodes = xmlDoc.elementsByTagName( QString( "colors" ) ); + QDomNodeList colorsNodes = xmlDoc.elementsByTagName( QStringLiteral( "colors" ) ); if ( colorsNodes.length() > 0 ) { QDomElement colorsElem = colorsNodes.at( 0 ).toElement(); @@ -2874,8 +2874,8 @@ QgsNamedColorList QgsSymbolLayerUtils::colorListFromMimeData( const QMimeData *d continue; } - QDomNodeList colorNodes = currentElem.elementsByTagName( QString( "color" ) ); - QDomNodeList nameNodes = currentElem.elementsByTagName( QString( "name" ) ); + QDomNodeList colorNodes = currentElem.elementsByTagName( QStringLiteral( "color" ) ); + QDomNodeList nameNodes = currentElem.elementsByTagName( QStringLiteral( "name" ) ); if ( colorNodes.length() > 0 ) { @@ -2932,18 +2932,18 @@ QMimeData* QgsSymbolLayerUtils::colorListToMimeData( const QgsNamedColorList& co //native format QMimeData* mimeData = new QMimeData(); QDomDocument xmlDoc; - QDomElement xmlRootElement = xmlDoc.createElement( "ColorSchemeModelDragData" ); + QDomElement xmlRootElement = xmlDoc.createElement( QStringLiteral( "ColorSchemeModelDragData" ) ); xmlDoc.appendChild( xmlRootElement ); QgsNamedColorList::const_iterator colorIt = colorList.constBegin(); for ( ; colorIt != colorList.constEnd(); ++colorIt ) { - QDomElement namedColor = xmlDoc.createElement( "NamedColor" ); - namedColor.setAttribute( "color", QgsSymbolLayerUtils::encodeColor(( *colorIt ).first ) ); - namedColor.setAttribute( "label", ( *colorIt ).second ); + QDomElement namedColor = xmlDoc.createElement( QStringLiteral( "NamedColor" ) ); + namedColor.setAttribute( QStringLiteral( "color" ), QgsSymbolLayerUtils::encodeColor(( *colorIt ).first ) ); + namedColor.setAttribute( QStringLiteral( "label" ), ( *colorIt ).second ); xmlRootElement.appendChild( namedColor ); } - mimeData->setData( "text/xml", xmlDoc.toByteArray() ); + mimeData->setData( QStringLiteral( "text/xml" ), xmlDoc.toByteArray() ); if ( !allFormats ) { @@ -2957,7 +2957,7 @@ QMimeData* QgsSymbolLayerUtils::colorListToMimeData( const QgsNamedColorList& co { colorListString << ( *colorIt ).first.name(); } - mimeData->setText( colorListString.join( "\n" ) ); + mimeData->setText( colorListString.join( QStringLiteral( "\n" ) ) ); //set mime color data to first color if ( colorList.length() > 0 ) @@ -2995,7 +2995,7 @@ bool QgsSymbolLayerUtils::saveColorsToGpl( QFile &file, const QString& paletteNa { continue; } - stream << QString( "%1 %2 %3" ).arg( color.red(), 3 ).arg( color.green(), 3 ).arg( color.blue(), 3 ); + stream << QStringLiteral( "%1 %2 %3" ).arg( color.red(), 3 ).arg( color.green(), 3 ).arg( color.blue(), 3 ); stream << "\t" << (( *colorIt ).second.isEmpty() ? color.name() : ( *colorIt ).second ) << endl; } file.close(); @@ -3016,18 +3016,18 @@ QgsNamedColorList QgsSymbolLayerUtils::importColorsFromGpl( QFile &file, bool &o QTextStream in( &file ); QString line = in.readLine(); - if ( !line.startsWith( "GIMP Palette" ) ) + if ( !line.startsWith( QLatin1String( "GIMP Palette" ) ) ) { ok = false; return importedColors; } //find name line - while ( !in.atEnd() && !line.startsWith( "Name:" ) && !line.startsWith( '#' ) ) + while ( !in.atEnd() && !line.startsWith( QLatin1String( "Name:" ) ) && !line.startsWith( '#' ) ) { line = in.readLine(); } - if ( line.startsWith( "Name:" ) ) + if ( line.startsWith( QLatin1String( "Name:" ) ) ) { QRegExp nameRx( "Name:\\s*(\\S.*)$" ); if ( nameRx.indexIn( line ) != -1 ) @@ -3113,7 +3113,7 @@ QColor QgsSymbolLayerUtils::parseColorWithAlpha( const QString& colorStr, bool & if ( hexColorIndex > -1 ) { QString hexColor = hexColorAlphaRx.cap( 1 ); - parsedColor.setNamedColor( QString( "#" ) + hexColor ); + parsedColor.setNamedColor( QStringLiteral( "#" ) + hexColor ); bool alphaOk; int alphaHex = hexColorAlphaRx.cap( 2 ).toInt( &alphaOk, 16 ); @@ -3132,7 +3132,7 @@ QColor QgsSymbolLayerUtils::parseColorWithAlpha( const QString& colorStr, bool & if ( hexColorRx2.indexIn( colorStr ) != -1 ) { //add "#" and parse - parsedColor.setNamedColor( QString( "#" ) + colorStr ); + parsedColor.setNamedColor( QStringLiteral( "#" ) + colorStr ); if ( parsedColor.isValid() ) { containsAlpha = false; @@ -3616,12 +3616,12 @@ QString QgsSymbolLayerUtils::symbolNameToPath( QString name ) return QFileInfo( name ).canonicalFilePath(); // or it might be an url... - if ( name.contains( "://" ) ) + if ( name.contains( QLatin1String( "://" ) ) ) { QUrl url( name ); if ( url.isValid() && !url.scheme().isEmpty() ) { - if ( url.scheme().compare( "file", Qt::CaseInsensitive ) == 0 ) + if ( url.scheme().compare( QLatin1String( "file" ), Qt::CaseInsensitive ) == 0 ) { // it's a url to a local file name = url.toLocalFile(); @@ -3976,10 +3976,10 @@ double QgsSymbolLayerUtils::rescaleUom( double size, QgsUnitTypes::RenderUnit un bool roundToUnit = false; if ( unit == QgsUnitTypes::RenderUnknownUnit ) { - if ( props.contains( "uomScale" ) ) + if ( props.contains( QStringLiteral( "uomScale" ) ) ) { bool ok; - scale = props.value( "uomScale" ).toDouble( &ok ); + scale = props.value( QStringLiteral( "uomScale" ) ).toDouble( &ok ); if ( !ok ) { return size; @@ -3988,7 +3988,7 @@ double QgsSymbolLayerUtils::rescaleUom( double size, QgsUnitTypes::RenderUnit un } else { - if ( props.value( "uom" ) == "http://www.opengeospatial.org/se/units/metre" ) + if ( props.value( QStringLiteral( "uom" ) ) == QLatin1String( "http://www.opengeospatial.org/se/units/metre" ) ) { switch ( unit ) { @@ -4049,17 +4049,17 @@ QVector<qreal> QgsSymbolLayerUtils::rescaleUom( const QVector<qreal>& array, Qgs void QgsSymbolLayerUtils::applyScaleDependency( QDomDocument& doc, QDomElement& ruleElem, QgsStringMap& props ) { - if ( !props.value( "scaleMinDenom", "" ).isEmpty() ) + if ( !props.value( QStringLiteral( "scaleMinDenom" ), QLatin1String( "" ) ).isEmpty() ) { - QDomElement scaleMinDenomElem = doc.createElement( "se:MinScaleDenominator" ); - scaleMinDenomElem.appendChild( doc.createTextNode( props.value( "scaleMinDenom", "" ) ) ); + QDomElement scaleMinDenomElem = doc.createElement( QStringLiteral( "se:MinScaleDenominator" ) ); + scaleMinDenomElem.appendChild( doc.createTextNode( props.value( QStringLiteral( "scaleMinDenom" ), QLatin1String( "" ) ) ) ); ruleElem.appendChild( scaleMinDenomElem ); } - if ( !props.value( "scaleMaxDenom", "" ).isEmpty() ) + if ( !props.value( QStringLiteral( "scaleMaxDenom" ), QLatin1String( "" ) ).isEmpty() ) { - QDomElement scaleMaxDenomElem = doc.createElement( "se:MaxScaleDenominator" ); - scaleMaxDenomElem.appendChild( doc.createTextNode( props.value( "scaleMaxDenom", "" ) ) ); + QDomElement scaleMaxDenomElem = doc.createElement( QStringLiteral( "se:MaxScaleDenominator" ) ); + scaleMaxDenomElem.appendChild( doc.createTextNode( props.value( QStringLiteral( "scaleMaxDenom" ), QLatin1String( "" ) ) ) ); ruleElem.appendChild( scaleMaxDenomElem ); } } @@ -4069,20 +4069,20 @@ void QgsSymbolLayerUtils::mergeScaleDependencies( int mScaleMinDenom, int mScale if ( mScaleMinDenom != 0 ) { bool ok; - int parentScaleMinDenom = props.value( "scaleMinDenom", "0" ).toInt( &ok ); + int parentScaleMinDenom = props.value( QStringLiteral( "scaleMinDenom" ), QStringLiteral( "0" ) ).toInt( &ok ); if ( !ok || parentScaleMinDenom <= 0 ) - props[ "scaleMinDenom" ] = QString::number( mScaleMinDenom ); + props[ QStringLiteral( "scaleMinDenom" )] = QString::number( mScaleMinDenom ); else - props[ "scaleMinDenom" ] = QString::number( qMax( parentScaleMinDenom, mScaleMinDenom ) ); + props[ QStringLiteral( "scaleMinDenom" )] = QString::number( qMax( parentScaleMinDenom, mScaleMinDenom ) ); } if ( mScaleMaxDenom != 0 ) { bool ok; - int parentScaleMaxDenom = props.value( "scaleMaxDenom", "0" ).toInt( &ok ); + int parentScaleMaxDenom = props.value( QStringLiteral( "scaleMaxDenom" ), QStringLiteral( "0" ) ).toInt( &ok ); if ( !ok || parentScaleMaxDenom <= 0 ) - props[ "scaleMaxDenom" ] = QString::number( mScaleMaxDenom ); + props[ QStringLiteral( "scaleMaxDenom" )] = QString::number( mScaleMaxDenom ); else - props[ "scaleMaxDenom" ] = QString::number( qMin( parentScaleMaxDenom, mScaleMaxDenom ) ); + props[ QStringLiteral( "scaleMaxDenom" )] = QString::number( qMin( parentScaleMaxDenom, mScaleMaxDenom ) ); } } diff --git a/src/core/symbology-ng/qgssymbologyconversion.cpp b/src/core/symbology-ng/qgssymbologyconversion.cpp index 8e248cbae09c..6d0cb494c88a 100644 --- a/src/core/symbology-ng/qgssymbologyconversion.cpp +++ b/src/core/symbology-ng/qgssymbologyconversion.cpp @@ -37,11 +37,11 @@ static QgsOldSymbolMeta readSymbolMeta( const QDomNode& synode ) { QgsOldSymbolMeta meta; - QDomNode lvalnode = synode.namedItem( "lowervalue" ); + QDomNode lvalnode = synode.namedItem( QStringLiteral( "lowervalue" ) ); if ( ! lvalnode.isNull() ) { QDomElement lvalelement = lvalnode.toElement(); - if ( lvalelement.attribute( "null" ).toInt() == 1 ) + if ( lvalelement.attribute( QStringLiteral( "null" ) ).toInt() == 1 ) { meta.lowerValue = QString::null; } @@ -51,14 +51,14 @@ static QgsOldSymbolMeta readSymbolMeta( const QDomNode& synode ) } } - QDomNode uvalnode = synode.namedItem( "uppervalue" ); + QDomNode uvalnode = synode.namedItem( QStringLiteral( "uppervalue" ) ); if ( ! uvalnode.isNull() ) { QDomElement uvalelement = uvalnode.toElement(); meta.upperValue = uvalelement.text(); } - QDomNode labelnode = synode.namedItem( "label" ); + QDomNode labelnode = synode.namedItem( QStringLiteral( "label" ) ); if ( ! labelnode.isNull() ) { QDomElement labelelement = labelnode.toElement(); @@ -73,15 +73,15 @@ static QColor readSymbolColor( const QDomNode& synode, bool fillColor ) { QDomNode cnode = synode.namedItem( fillColor ? "fillcolor" : "outlinecolor" ); QDomElement celement = cnode.toElement(); - int red = celement.attribute( "red" ).toInt(); - int green = celement.attribute( "green" ).toInt(); - int blue = celement.attribute( "blue" ).toInt(); + int red = celement.attribute( QStringLiteral( "red" ) ).toInt(); + int green = celement.attribute( QStringLiteral( "green" ) ).toInt(); + int blue = celement.attribute( QStringLiteral( "blue" ) ).toInt(); return QColor( red, green, blue ); } static double readOutlineWidth( const QDomNode& synode ) { - QDomNode outlwnode = synode.namedItem( "outlinewidth" ); + QDomNode outlwnode = synode.namedItem( QStringLiteral( "outlinewidth" ) ); QDomElement outlwelement = outlwnode.toElement(); return outlwelement.text().toDouble(); } @@ -89,32 +89,32 @@ static double readOutlineWidth( const QDomNode& synode ) static Qt::PenStyle readOutlineStyle( const QDomNode& synode ) { - QDomNode outlstnode = synode.namedItem( "outlinestyle" ); + QDomNode outlstnode = synode.namedItem( QStringLiteral( "outlinestyle" ) ); QDomElement outlstelement = outlstnode.toElement(); return QgsSymbologyConversion::qString2PenStyle( outlstelement.text() ); } static Qt::BrushStyle readBrushStyle( const QDomNode& synode ) { - QDomNode fillpnode = synode.namedItem( "fillpattern" ); + QDomNode fillpnode = synode.namedItem( QStringLiteral( "fillpattern" ) ); QDomElement fillpelement = fillpnode.toElement(); return QgsSymbologyConversion::qString2BrushStyle( fillpelement.text() ); } static QString readMarkerSymbolName( const QDomNode& synode ) { - QDomNode psymbnode = synode.namedItem( "pointsymbol" ); + QDomNode psymbnode = synode.namedItem( QStringLiteral( "pointsymbol" ) ); if ( ! psymbnode.isNull() ) { QDomElement psymbelement = psymbnode.toElement(); return psymbelement.text(); } - return QString( "hard:circle" ); + return QStringLiteral( "hard:circle" ); } static float readMarkerSymbolSize( const QDomNode& synode ) { - QDomNode psizenode = synode.namedItem( "pointsize" ); + QDomNode psizenode = synode.namedItem( QStringLiteral( "pointsize" ) ); if ( ! psizenode.isNull() ) { QDomElement psizeelement = psizenode.toElement(); @@ -135,7 +135,7 @@ static QgsSymbol* readOldSymbol( const QDomNode& synode, QgsWkbTypes::GeometryTy double size = readMarkerSymbolSize( synode ); double angle = 0; // rotation only from classification field QString symbolName = readMarkerSymbolName( synode ); - if ( symbolName.startsWith( "hard:" ) ) + if ( symbolName.startsWith( QLatin1String( "hard:" ) ) ) { // simple symbol marker QColor color = readSymbolColor( synode, true ); @@ -191,7 +191,7 @@ static QgsSymbol* readOldSymbol( const QDomNode& synode, QgsWkbTypes::GeometryTy static QgsFeatureRenderer* readOldSingleSymbolRenderer( const QDomNode& rnode, QgsWkbTypes::GeometryType geomType ) { - QDomNode synode = rnode.namedItem( "symbol" ); + QDomNode synode = rnode.namedItem( QStringLiteral( "symbol" ) ); if ( synode.isNull() ) return nullptr; @@ -203,17 +203,17 @@ static QgsFeatureRenderer* readOldSingleSymbolRenderer( const QDomNode& rnode, Q static QgsFeatureRenderer* readOldGraduatedSymbolRenderer( const QDomNode& rnode, QgsWkbTypes::GeometryType geomType ) { - QDomNode modeNode = rnode.namedItem( "mode" ); + QDomNode modeNode = rnode.namedItem( QStringLiteral( "mode" ) ); QString modeValue = modeNode.toElement().text(); - QDomNode classnode = rnode.namedItem( "classificationfield" ); + QDomNode classnode = rnode.namedItem( QStringLiteral( "classificationfield" ) ); QString classificationField = classnode.toElement().text(); QgsGraduatedSymbolRenderer::Mode m = QgsGraduatedSymbolRenderer::Custom; - if ( modeValue == "Empty" ) + if ( modeValue == QLatin1String( "Empty" ) ) { m = QgsGraduatedSymbolRenderer::Custom; } - else if ( modeValue == "Quantile" ) + else if ( modeValue == QLatin1String( "Quantile" ) ) { m = QgsGraduatedSymbolRenderer::Quantile; } @@ -224,7 +224,7 @@ static QgsFeatureRenderer* readOldGraduatedSymbolRenderer( const QDomNode& rnode // load ranges and symbols QgsRangeList ranges; - QDomNode symbolnode = rnode.namedItem( "symbol" ); + QDomNode symbolnode = rnode.namedItem( QStringLiteral( "symbol" ) ); while ( !symbolnode.isNull() ) { QgsSymbol* symbol = readOldSymbol( symbolnode, geomType ); @@ -235,7 +235,7 @@ static QgsFeatureRenderer* readOldGraduatedSymbolRenderer( const QDomNode& rnode double upperValue = meta.upperValue.toDouble(); QString label = meta.label; if ( label.isEmpty() ) - label = QString( "%1 - %2" ).arg( lowerValue, -1, 'f', 3 ).arg( upperValue, -1, 'f', 3 ); + label = QStringLiteral( "%1 - %2" ).arg( lowerValue, -1, 'f', 3 ).arg( upperValue, -1, 'f', 3 ); ranges.append( QgsRendererRange( lowerValue, upperValue, symbol, label ) ); } @@ -252,12 +252,12 @@ static QgsFeatureRenderer* readOldGraduatedSymbolRenderer( const QDomNode& rnode static QgsFeatureRenderer* readOldUniqueValueRenderer( const QDomNode& rnode, QgsWkbTypes::GeometryType geomType ) { - QDomNode classnode = rnode.namedItem( "classificationfield" ); + QDomNode classnode = rnode.namedItem( QStringLiteral( "classificationfield" ) ); QString classificationField = classnode.toElement().text(); // read categories and symbols QgsCategoryList cats; - QDomNode symbolnode = rnode.namedItem( "symbol" ); + QDomNode symbolnode = rnode.namedItem( QStringLiteral( "symbol" ) ); while ( !symbolnode.isNull() ) { QgsSymbol* symbol = readOldSymbol( symbolnode, geomType ); @@ -284,10 +284,10 @@ static QgsFeatureRenderer* readOldUniqueValueRenderer( const QDomNode& rnode, Qg QgsFeatureRenderer* QgsSymbologyConversion::readOldRenderer( const QDomNode& layerNode, QgsWkbTypes::GeometryType geomType ) { - QDomNode singlenode = layerNode.namedItem( "singlesymbol" ); - QDomNode graduatednode = layerNode.namedItem( "graduatedsymbol" ); - QDomNode continuousnode = layerNode.namedItem( "continuoussymbol" ); - QDomNode uniquevaluenode = layerNode.namedItem( "uniquevalue" ); + QDomNode singlenode = layerNode.namedItem( QStringLiteral( "singlesymbol" ) ); + QDomNode graduatednode = layerNode.namedItem( QStringLiteral( "graduatedsymbol" ) ); + QDomNode continuousnode = layerNode.namedItem( QStringLiteral( "continuoussymbol" ) ); + QDomNode uniquevaluenode = layerNode.namedItem( QStringLiteral( "uniquevalue" ) ); if ( !singlenode.isNull() ) { @@ -356,31 +356,31 @@ QString QgsSymbologyConversion::penStyle2QString( Qt::PenStyle penstyle ) { if ( penstyle == Qt::NoPen ) { - return "NoPen"; + return QStringLiteral( "NoPen" ); } else if ( penstyle == Qt::SolidLine ) { - return "SolidLine"; + return QStringLiteral( "SolidLine" ); } else if ( penstyle == Qt::DashLine ) { - return "DashLine"; + return QStringLiteral( "DashLine" ); } else if ( penstyle == Qt::DotLine ) { - return "DotLine"; + return QStringLiteral( "DotLine" ); } else if ( penstyle == Qt::DashDotLine ) { - return "DashDotLine"; + return QStringLiteral( "DashDotLine" ); } else if ( penstyle == Qt::DashDotDotLine ) { - return "DashDotDotLine"; + return QStringLiteral( "DashDotDotLine" ); } else if ( penstyle == Qt::MPenStyle ) { - return "MPenStyle"; + return QStringLiteral( "MPenStyle" ); } else //return a null string { @@ -390,31 +390,31 @@ QString QgsSymbologyConversion::penStyle2QString( Qt::PenStyle penstyle ) Qt::PenStyle QgsSymbologyConversion::qString2PenStyle( const QString& penString ) { - if ( penString == "NoPen" ) + if ( penString == QLatin1String( "NoPen" ) ) { return Qt::NoPen; } - else if ( penString == "SolidLine" ) + else if ( penString == QLatin1String( "SolidLine" ) ) { return Qt::SolidLine; } - else if ( penString == "DashLine" ) + else if ( penString == QLatin1String( "DashLine" ) ) { return Qt::DashLine; } - else if ( penString == "DotLine" ) + else if ( penString == QLatin1String( "DotLine" ) ) { return Qt::DotLine; } - else if ( penString == "DashDotLine" ) + else if ( penString == QLatin1String( "DashDotLine" ) ) { return Qt::DashDotLine; } - else if ( penString == "DashDotDotLine" ) + else if ( penString == QLatin1String( "DashDotDotLine" ) ) { return Qt::DashDotDotLine; } - else if ( penString == "MPenStyle" ) + else if ( penString == QLatin1String( "MPenStyle" ) ) { return Qt::MPenStyle; } @@ -428,138 +428,138 @@ QString QgsSymbologyConversion::brushStyle2QString( Qt::BrushStyle brushstyle ) { if ( brushstyle == Qt::NoBrush ) { - return "NoBrush"; + return QStringLiteral( "NoBrush" ); } else if ( brushstyle == Qt::SolidPattern ) { - return "SolidPattern"; + return QStringLiteral( "SolidPattern" ); } else if ( brushstyle == Qt::Dense1Pattern ) { - return "Dense1Pattern"; + return QStringLiteral( "Dense1Pattern" ); } else if ( brushstyle == Qt::Dense2Pattern ) { - return "Dense2Pattern"; + return QStringLiteral( "Dense2Pattern" ); } else if ( brushstyle == Qt::Dense3Pattern ) { - return "Dense3Pattern"; + return QStringLiteral( "Dense3Pattern" ); } else if ( brushstyle == Qt::Dense4Pattern ) { - return "Dense4Pattern"; + return QStringLiteral( "Dense4Pattern" ); } else if ( brushstyle == Qt::Dense5Pattern ) { - return "Dense5Pattern"; + return QStringLiteral( "Dense5Pattern" ); } else if ( brushstyle == Qt::Dense6Pattern ) { - return "Dense6Pattern"; + return QStringLiteral( "Dense6Pattern" ); } else if ( brushstyle == Qt::Dense7Pattern ) { - return "Dense7Pattern"; + return QStringLiteral( "Dense7Pattern" ); } else if ( brushstyle == Qt::HorPattern ) { - return "HorPattern"; + return QStringLiteral( "HorPattern" ); } else if ( brushstyle == Qt::VerPattern ) { - return "VerPattern"; + return QStringLiteral( "VerPattern" ); } else if ( brushstyle == Qt::CrossPattern ) { - return "CrossPattern"; + return QStringLiteral( "CrossPattern" ); } else if ( brushstyle == Qt::BDiagPattern ) { - return "BDiagPattern"; + return QStringLiteral( "BDiagPattern" ); } else if ( brushstyle == Qt::FDiagPattern ) { - return "FDiagPattern"; + return QStringLiteral( "FDiagPattern" ); } else if ( brushstyle == Qt::DiagCrossPattern ) { - return "DiagCrossPattern"; + return QStringLiteral( "DiagCrossPattern" ); } else if ( brushstyle == Qt::TexturePattern ) { - return "TexturePattern"; + return QStringLiteral( "TexturePattern" ); } else //return a null string { QgsDebugMsg( "no matching pattern found" ); - return " "; + return QStringLiteral( " " ); } } Qt::BrushStyle QgsSymbologyConversion::qString2BrushStyle( const QString& brushString ) { - if ( brushString == "NoBrush" ) + if ( brushString == QLatin1String( "NoBrush" ) ) { return Qt::NoBrush; } - else if ( brushString == "SolidPattern" ) + else if ( brushString == QLatin1String( "SolidPattern" ) ) { return Qt::SolidPattern; } - else if ( brushString == "Dense1Pattern" ) + else if ( brushString == QLatin1String( "Dense1Pattern" ) ) { return Qt::Dense1Pattern; } - else if ( brushString == "Dense2Pattern" ) + else if ( brushString == QLatin1String( "Dense2Pattern" ) ) { return Qt::Dense2Pattern; } - else if ( brushString == "Dense3Pattern" ) + else if ( brushString == QLatin1String( "Dense3Pattern" ) ) { return Qt::Dense3Pattern; } - else if ( brushString == "Dense4Pattern" ) + else if ( brushString == QLatin1String( "Dense4Pattern" ) ) { return Qt::Dense4Pattern; } - else if ( brushString == "Dense5Pattern" ) + else if ( brushString == QLatin1String( "Dense5Pattern" ) ) { return Qt::Dense5Pattern; } - else if ( brushString == "Dense6Pattern" ) + else if ( brushString == QLatin1String( "Dense6Pattern" ) ) { return Qt::Dense6Pattern; } - else if ( brushString == "Dense7Pattern" ) + else if ( brushString == QLatin1String( "Dense7Pattern" ) ) { return Qt::Dense7Pattern; } - else if ( brushString == "HorPattern" ) + else if ( brushString == QLatin1String( "HorPattern" ) ) { return Qt::HorPattern; } - else if ( brushString == "VerPattern" ) + else if ( brushString == QLatin1String( "VerPattern" ) ) { return Qt::VerPattern; } - else if ( brushString == "CrossPattern" ) + else if ( brushString == QLatin1String( "CrossPattern" ) ) { return Qt::CrossPattern; } - else if ( brushString == "BDiagPattern" ) + else if ( brushString == QLatin1String( "BDiagPattern" ) ) { return Qt::BDiagPattern; } - else if ( brushString == "FDiagPattern" ) + else if ( brushString == QLatin1String( "FDiagPattern" ) ) { return Qt::FDiagPattern; } - else if ( brushString == "DiagCrossPattern" ) + else if ( brushString == QLatin1String( "DiagCrossPattern" ) ) { return Qt::DiagCrossPattern; } - else if ( brushString == "TexturePattern" ) + else if ( brushString == QLatin1String( "TexturePattern" ) ) { return Qt::TexturePattern; } diff --git a/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp b/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp index 2db2b6806987..b3601aff2737 100644 --- a/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp +++ b/src/core/symbology-ng/qgsvectorfieldsymbollayer.cpp @@ -20,8 +20,8 @@ #include "qgsunittypes.h" QgsVectorFieldSymbolLayer::QgsVectorFieldSymbolLayer() - : mXAttribute( "" ) - , mYAttribute( "" ) + : mXAttribute( QLatin1String( "" ) ) + , mYAttribute( QLatin1String( "" ) ) , mDistanceUnit( QgsUnitTypes::RenderMillimeters ) , mScale( 1.0 ) , mVectorFieldType( Cartesian ) @@ -72,61 +72,61 @@ QgsMapUnitScale QgsVectorFieldSymbolLayer::mapUnitScale() const QgsSymbolLayer* QgsVectorFieldSymbolLayer::create( const QgsStringMap& properties ) { QgsVectorFieldSymbolLayer* symbolLayer = new QgsVectorFieldSymbolLayer(); - if ( properties.contains( "x_attribute" ) ) + if ( properties.contains( QStringLiteral( "x_attribute" ) ) ) { - symbolLayer->setXAttribute( properties["x_attribute"] ); + symbolLayer->setXAttribute( properties[QStringLiteral( "x_attribute" )] ); } - if ( properties.contains( "y_attribute" ) ) + if ( properties.contains( QStringLiteral( "y_attribute" ) ) ) { - symbolLayer->setYAttribute( properties["y_attribute"] ); + symbolLayer->setYAttribute( properties[QStringLiteral( "y_attribute" )] ); } - if ( properties.contains( "distance_unit" ) ) + if ( properties.contains( QStringLiteral( "distance_unit" ) ) ) { - symbolLayer->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( properties["distance_unit"] ) ); + symbolLayer->setDistanceUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "distance_unit" )] ) ); } - if ( properties.contains( "distance_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "distance_map_unit_scale" ) ) ) { - symbolLayer->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["distance_map_unit_scale"] ) ); + symbolLayer->setDistanceMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "distance_map_unit_scale" )] ) ); } - if ( properties.contains( "scale" ) ) + if ( properties.contains( QStringLiteral( "scale" ) ) ) { - symbolLayer->setScale( properties["scale"].toDouble() ); + symbolLayer->setScale( properties[QStringLiteral( "scale" )].toDouble() ); } - if ( properties.contains( "vector_field_type" ) ) + if ( properties.contains( QStringLiteral( "vector_field_type" ) ) ) { - symbolLayer->setVectorFieldType( static_cast< VectorFieldType >( properties["vector_field_type"].toInt() ) ); + symbolLayer->setVectorFieldType( static_cast< VectorFieldType >( properties[QStringLiteral( "vector_field_type" )].toInt() ) ); } - if ( properties.contains( "angle_orientation" ) ) + if ( properties.contains( QStringLiteral( "angle_orientation" ) ) ) { - symbolLayer->setAngleOrientation( static_cast< AngleOrientation >( properties["angle_orientation"].toInt() ) ); + symbolLayer->setAngleOrientation( static_cast< AngleOrientation >( properties[QStringLiteral( "angle_orientation" )].toInt() ) ); } - if ( properties.contains( "angle_units" ) ) + if ( properties.contains( QStringLiteral( "angle_units" ) ) ) { - symbolLayer->setAngleUnits( static_cast< AngleUnits >( properties["angle_units"].toInt() ) ); + symbolLayer->setAngleUnits( static_cast< AngleUnits >( properties[QStringLiteral( "angle_units" )].toInt() ) ); } - if ( properties.contains( "size" ) ) + if ( properties.contains( QStringLiteral( "size" ) ) ) { - symbolLayer->setSize( properties["size"].toDouble() ); + symbolLayer->setSize( properties[QStringLiteral( "size" )].toDouble() ); } - if ( properties.contains( "size_unit" ) ) + if ( properties.contains( QStringLiteral( "size_unit" ) ) ) { - symbolLayer->setSizeUnit( QgsUnitTypes::decodeRenderUnit( properties["size_unit"] ) ); + symbolLayer->setSizeUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "size_unit" )] ) ); } - if ( properties.contains( "size_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "size_map_unit_scale" ) ) ) { - symbolLayer->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["size_map_unit_scale"] ) ); + symbolLayer->setSizeMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "size_map_unit_scale" )] ) ); } - if ( properties.contains( "offset" ) ) + if ( properties.contains( QStringLiteral( "offset" ) ) ) { - symbolLayer->setOffset( QgsSymbolLayerUtils::decodePoint( properties["offset"] ) ); + symbolLayer->setOffset( QgsSymbolLayerUtils::decodePoint( properties[QStringLiteral( "offset" )] ) ); } - if ( properties.contains( "offset_unit" ) ) + if ( properties.contains( QStringLiteral( "offset_unit" ) ) ) { - symbolLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties["offset_unit"] ) ); + symbolLayer->setOffsetUnit( QgsUnitTypes::decodeRenderUnit( properties[QStringLiteral( "offset_unit" )] ) ); } - if ( properties.contains( "offset_map_unit_scale" ) ) + if ( properties.contains( QStringLiteral( "offset_map_unit_scale" ) ) ) { - symbolLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties["offset_map_unit_scale"] ) ); + symbolLayer->setOffsetMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( properties[QStringLiteral( "offset_map_unit_scale" )] ) ); } return symbolLayer; } @@ -244,26 +244,26 @@ QgsVectorFieldSymbolLayer* QgsVectorFieldSymbolLayer::clone() const QgsStringMap QgsVectorFieldSymbolLayer::properties() const { QgsStringMap properties; - properties["x_attribute"] = mXAttribute; - properties["y_attribute"] = mYAttribute; - properties["distance_unit"] = QgsUnitTypes::encodeUnit( mDistanceUnit ); - properties["distance_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ); - properties["scale"] = QString::number( mScale ); - properties["vector_field_type"] = QString::number( mVectorFieldType ); - properties["angle_orientation"] = QString::number( mAngleOrientation ); - properties["angle_units"] = QString::number( mAngleUnits ); - properties["size"] = QString::number( mSize ); - properties["size_unit"] = QgsUnitTypes::encodeUnit( mSizeUnit ); - properties["size_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); - properties["offset"] = QgsSymbolLayerUtils::encodePoint( mOffset ); - properties["offset_unit"] = QgsUnitTypes::encodeUnit( mOffsetUnit ); - properties["offset_map_unit_scale"] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); + properties[QStringLiteral( "x_attribute" )] = mXAttribute; + properties[QStringLiteral( "y_attribute" )] = mYAttribute; + properties[QStringLiteral( "distance_unit" )] = QgsUnitTypes::encodeUnit( mDistanceUnit ); + properties[QStringLiteral( "distance_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mDistanceMapUnitScale ); + properties[QStringLiteral( "scale" )] = QString::number( mScale ); + properties[QStringLiteral( "vector_field_type" )] = QString::number( mVectorFieldType ); + properties[QStringLiteral( "angle_orientation" )] = QString::number( mAngleOrientation ); + properties[QStringLiteral( "angle_units" )] = QString::number( mAngleUnits ); + properties[QStringLiteral( "size" )] = QString::number( mSize ); + properties[QStringLiteral( "size_unit" )] = QgsUnitTypes::encodeUnit( mSizeUnit ); + properties[QStringLiteral( "size_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mSizeMapUnitScale ); + properties[QStringLiteral( "offset" )] = QgsSymbolLayerUtils::encodePoint( mOffset ); + properties[QStringLiteral( "offset_unit" )] = QgsUnitTypes::encodeUnit( mOffsetUnit ); + properties[QStringLiteral( "offset_map_unit_scale" )] = QgsSymbolLayerUtils::encodeMapUnitScale( mOffsetMapUnitScale ); return properties; } void QgsVectorFieldSymbolLayer::toSld( QDomDocument& doc, QDomElement &element, const QgsStringMap& props ) const { - element.appendChild( doc.createComment( "VectorField not implemented yet..." ) ); + element.appendChild( doc.createComment( QStringLiteral( "VectorField not implemented yet..." ) ) ); mLineSymbol->toSld( doc, element, props ); } diff --git a/src/core/symbology-ng/qgsvectorfieldsymbollayer.h b/src/core/symbology-ng/qgsvectorfieldsymbollayer.h index 3b93a6ae7168..01aaaa848d1a 100644 --- a/src/core/symbology-ng/qgsvectorfieldsymbollayer.h +++ b/src/core/symbology-ng/qgsvectorfieldsymbollayer.h @@ -50,7 +50,7 @@ class CORE_EXPORT QgsVectorFieldSymbolLayer: public QgsMarkerSymbolLayer static QgsSymbolLayer* create( const QgsStringMap& properties = QgsStringMap() ); static QgsSymbolLayer* createFromSld( QDomElement &element ); - QString layerType() const override { return "VectorField"; } + QString layerType() const override { return QStringLiteral( "VectorField" ); } bool setSubSymbol( QgsSymbol* symbol ) override; QgsSymbol* subSymbol() override { return mLineSymbol; } diff --git a/src/gui/attributetable/qgsattributetablemodel.cpp b/src/gui/attributetable/qgsattributetablemodel.cpp index b6f8755b284c..147bde5cfbee 100644 --- a/src/gui/attributetable/qgsattributetablemodel.cpp +++ b/src/gui/attributetable/qgsattributetablemodel.cpp @@ -41,7 +41,7 @@ QgsAttributeTableModel::QgsAttributeTableModel( QgsVectorLayerCache *layerCache, : QAbstractTableModel( parent ) , mLayerCache( layerCache ) , mFieldCount( 0 ) - , mSortCacheExpression( "" ) + , mSortCacheExpression( QLatin1String( "" ) ) , mSortFieldIndex( -1 ) , mExtraColumns( 0 ) { @@ -252,7 +252,7 @@ void QgsAttributeTableModel::editCommandEnded() void QgsAttributeTableModel::attributeDeleted( int idx ) { if ( mSortCacheAttributes.contains( idx ) ) - prefetchSortData( "" ); + prefetchSortData( QLatin1String( "" ) ); } void QgsAttributeTableModel::layerDeleted() @@ -766,7 +766,7 @@ void QgsAttributeTableModel::prefetchColumnData( int column ) { if ( column == -1 || column >= mAttributes.count() ) { - prefetchSortData( "" ); + prefetchSortData( QLatin1String( "" ) ); } else { diff --git a/src/gui/attributetable/qgsattributetableview.cpp b/src/gui/attributetable/qgsattributetableview.cpp index 0c46070e3283..bc0bb8e5131f 100644 --- a/src/gui/attributetable/qgsattributetableview.cpp +++ b/src/gui/attributetable/qgsattributetableview.cpp @@ -45,7 +45,7 @@ QgsAttributeTableView::QgsAttributeTableView( QWidget *parent ) , mCtrlDragSelectionFlag( QItemSelectionModel::Select ) { QSettings settings; - restoreGeometry( settings.value( "/BetterAttributeTable/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/BetterAttributeTable/geometry" ) ).toByteArray() ); //verticalHeader()->setDefaultSectionSize( 20 ); horizontalHeader()->setHighlightSections( false ); @@ -184,7 +184,7 @@ QWidget* QgsAttributeTableView::createActionWidget( QgsFeatureId fid ) if ( !action.showInAttributeTable() ) continue; - QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : ""; + QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QLatin1String( "" ); QAction* act = new QAction( action.icon(), actionTitle, container ); act->setToolTip( action.name() ); act->setData( "user_action" ); @@ -252,7 +252,7 @@ void QgsAttributeTableView::closeEvent( QCloseEvent *e ) { Q_UNUSED( e ); QSettings settings; - settings.setValue( "/BetterAttributeTable/geometry", QVariant( saveGeometry() ) ); + settings.setValue( QStringLiteral( "/BetterAttributeTable/geometry" ), QVariant( saveGeometry() ) ); } void QgsAttributeTableView::mousePressEvent( QMouseEvent *event ) @@ -414,11 +414,11 @@ void QgsAttributeTableView::actionTriggered() QgsFeature f; mFilterModel->layerCache()->getFeatures( QgsFeatureRequest( fid ) ).nextFeature( f ); - if ( action->data().toString() == "user_action" ) + if ( action->data().toString() == QLatin1String( "user_action" ) ) { mFilterModel->layer()->actions()->doAction( action->property( "action_id" ).toInt(), f ); } - else if ( action->data().toString() == "map_layer_action" ) + else if ( action->data().toString() == QLatin1String( "map_layer_action" ) ) { QObject* object = action->property( "action" ).value<QObject *>(); QgsMapLayerAction* layerAction = qobject_cast<QgsMapLayerAction *>( object ); diff --git a/src/gui/attributetable/qgsdualview.cpp b/src/gui/attributetable/qgsdualview.cpp index 4bed2b419fed..c5e244230a18 100644 --- a/src/gui/attributetable/qgsdualview.cpp +++ b/src/gui/attributetable/qgsdualview.cpp @@ -60,7 +60,7 @@ QgsDualView::QgsDualView( QWidget* parent ) mActionPreviewColumnsMenu->setMenu( mPreviewColumnsMenu ); // Set preview icon - mActionExpressionPreview->setIcon( QgsApplication::getThemeIcon( "/mIconExpressionPreview.svg" ) ); + mActionExpressionPreview->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpressionPreview.svg" ) ) ); // Connect layer list preview signals connect( mActionExpressionPreview, SIGNAL( triggered() ), SLOT( previewExpressionBuilder() ) ); @@ -130,7 +130,7 @@ void QgsDualView::columnBoxInit() if ( displayExpression.isEmpty() ) { // ... there isn't really much to display - displayExpression = "'[Please define preview text]'"; + displayExpression = QStringLiteral( "'[Please define preview text]'" ); } mFeatureListPreviewButton->addAction( mActionExpressionPreview ); @@ -142,7 +142,7 @@ void QgsDualView::columnBoxInit() if ( fieldIndex == -1 ) continue; - if ( QgsEditorWidgetRegistry::instance()->findBest( mLayerCache->layer(), field.name() ).type() != "Hidden" ) + if ( QgsEditorWidgetRegistry::instance()->findBest( mLayerCache->layer(), field.name() ).type() != QLatin1String( "Hidden" ) ) { QIcon icon = mLayerCache->layer()->fields().iconForField( fieldIndex ); QString text = field.name(); @@ -172,7 +172,7 @@ void QgsDualView::columnBoxInit() mFeatureListPreviewButton->defaultAction()->trigger(); } - QAction* sortByPreviewExpression = new QAction( QgsApplication::getThemeIcon( "sort.svg" ), tr( "Sort by preview expression" ), this ); + QAction* sortByPreviewExpression = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "sort.svg" ) ), tr( "Sort by preview expression" ), this ); connect( sortByPreviewExpression, SIGNAL( triggered( bool ) ), this, SLOT( sortByPreviewExpression() ) ); mFeatureListPreviewButton->addAction( sortByPreviewExpression ); } @@ -202,7 +202,7 @@ void QgsDualView::initLayerCache( QgsVectorLayer* layer, bool cacheGeometry ) { // Initialize the cache QSettings settings; - int cacheSize = settings.value( "/qgis/attributeTableRowCache", "10000" ).toInt(); + int cacheSize = settings.value( QStringLiteral( "/qgis/attributeTableRowCache" ), "10000" ).toInt(); mLayerCache = new QgsVectorLayerCache( layer, cacheSize, this ); mLayerCache->setCacheGeometry( cacheGeometry ); if ( 0 == cacheSize || 0 == ( QgsVectorDataProvider::SelectAtId & mLayerCache->layer()->dataProvider()->capabilities() ) ) @@ -304,7 +304,7 @@ void QgsDualView::previewExpressionBuilder() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( mLayerCache->layer() ); - QgsExpressionBuilderDialog dlg( mLayerCache->layer(), mFeatureList->displayExpression(), this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayerCache->layer(), mFeatureList->displayExpression(), this, QStringLiteral( "generic" ), context ); dlg.setWindowTitle( tr( "Expression based preview" ) ); dlg.setExpressionText( mFeatureList->displayExpression() ); @@ -324,7 +324,7 @@ void QgsDualView::previewColumnChanged( QObject* action ) if ( previewAction ) { - if ( !mFeatureList->setDisplayExpression( QString( "COALESCE( \"%1\", '<NULL>' )" ).arg( previewAction->text() ) ) ) + if ( !mFeatureList->setDisplayExpression( QStringLiteral( "COALESCE( \"%1\", '<NULL>' )" ).arg( previewAction->text() ) ) ) { QMessageBox::warning( this, tr( "Could not set preview column" ), @@ -559,7 +559,7 @@ void QgsDualView::modifySort() expressionBuilder->setExpressionContext( context ); expressionBuilder->setLayer( layer ); expressionBuilder->loadFieldNames(); - expressionBuilder->loadRecent( "generic" ); + expressionBuilder->loadRecent( QStringLiteral( "generic" ) ); expressionBuilder->setExpressionText( sortExpression().isEmpty() ? layer->displayExpression() : sortExpression() ); sortingGroupBox->layout()->addWidget( expressionBuilder ); diff --git a/src/gui/attributetable/qgsfeaturelistmodel.cpp b/src/gui/attributetable/qgsfeaturelistmodel.cpp index 3a36f6ee1f66..e33c2c5a75c7 100644 --- a/src/gui/attributetable/qgsfeaturelistmodel.cpp +++ b/src/gui/attributetable/qgsfeaturelistmodel.cpp @@ -27,7 +27,7 @@ QgsFeatureListModel::QgsFeatureListModel( QgsAttributeTableFilterModel *sourceMo , mInjectNull( false ) { setSourceModel( sourceModel ); - mExpression = new QgsExpression( "" ); + mExpression = new QgsExpression( QLatin1String( "" ) ); } QgsFeatureListModel::~QgsFeatureListModel() @@ -73,7 +73,7 @@ QVariant QgsFeatureListModel::data( const QModelIndex &index, int role ) const { if ( role == Qt::DisplayRole ) { - return QSettings().value( "qgis/nullValue", "NULL" ).toString(); + return QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } else if ( role == QgsAttributeTableModel::FeatureIdRole ) { diff --git a/src/gui/attributetable/qgsfeaturelistviewdelegate.cpp b/src/gui/attributetable/qgsfeaturelistviewdelegate.cpp index 3db3585b0923..5c3799c93429 100644 --- a/src/gui/attributetable/qgsfeaturelistviewdelegate.cpp +++ b/src/gui/attributetable/qgsfeaturelistviewdelegate.cpp @@ -74,10 +74,10 @@ void QgsFeatureListViewDelegate::paint( QPainter *painter, const QStyleOptionVie { static QPixmap selectedIcon; if ( selectedIcon.isNull() ) - selectedIcon = QgsApplication::getThemePixmap( "/mIconSelected.svg" ); + selectedIcon = QgsApplication::getThemePixmap( QStringLiteral( "/mIconSelected.svg" ) ); static QPixmap deselectedIcon; if ( deselectedIcon.isNull() ) - deselectedIcon = QgsApplication::getThemePixmap( "/mIconDeselected.svg" ); + deselectedIcon = QgsApplication::getThemePixmap( QStringLiteral( "/mIconDeselected.svg" ) ); QString text = index.model()->data( index, Qt::EditRole ).toString(); QgsFeatureListModel::FeatureInfo featInfo = index.model()->data( index, Qt::UserRole ).value<QgsFeatureListModel::FeatureInfo>(); diff --git a/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp b/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp index 7370087b3c6d..81533fd7e856 100644 --- a/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp +++ b/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp @@ -78,10 +78,10 @@ void QgsFieldConditionalFormatWidget::setExpression() context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( mLayer ); - context.lastScope()->setVariable( "value", 0 ); - context.setHighlightedVariables( QStringList() << "value" ); + context.lastScope()->setVariable( QStringLiteral( "value" ), 0 ); + context.setHighlightedVariables( QStringList() << QStringLiteral( "value" ) ); - QgsExpressionBuilderDialog dlg( mLayer, mRuleEdit->text(), this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, mRuleEdit->text(), this, QStringLiteral( "generic" ), context ); dlg.setWindowTitle( tr( "Conditional style rule expression" ) ); if ( dlg.exec() ) @@ -214,7 +214,7 @@ void QgsFieldConditionalFormatWidget::reset() mRuleEdit->clear(); if ( fieldRadio->isChecked() ) { - mRuleEdit->setText( "@value " ); + mRuleEdit->setText( QStringLiteral( "@value " ) ); } btnBackgroundColor->setColor( QColor() ); btnTextColor->setColor( QColor() ); @@ -241,7 +241,7 @@ void QgsFieldConditionalFormatWidget::setPresets( const QList<QgsConditionalStyl { if ( style.isValid() ) { - QStandardItem* item = new QStandardItem( "abc - 123" ); + QStandardItem* item = new QStandardItem( QStringLiteral( "abc - 123" ) ); if ( style.backgroundColor().isValid() ) item->setBackground( style.backgroundColor() ); if ( style.textColor().isValid() ) diff --git a/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp b/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp index d87477769b23..057a0274cd90 100644 --- a/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp +++ b/src/gui/attributetable/qgsorganizetablecolumnsdialog.cpp @@ -61,7 +61,7 @@ QgsOrganizeTableColumnsDialog::QgsOrganizeTableColumnsDialog( const QgsVectorLay if ( columnConfig.type == QgsAttributeTableConfig::Action ) { item = new QListWidgetItem( tr( "[Action Widget]" ), mFieldsList ); - item->setIcon( QgsApplication::getThemeIcon( "/propertyicons/action.svg" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/action.svg" ) ) ); } else { @@ -71,15 +71,15 @@ QgsOrganizeTableColumnsDialog::QgsOrganizeTableColumnsDialog( const QgsVectorLay switch ( vl->fields().fieldOrigin( idx ) ) { case QgsFields::OriginExpression: - item->setIcon( QgsApplication::getThemeIcon( "/mIconExpression.svg" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); break; case QgsFields::OriginJoin: - item->setIcon( QgsApplication::getThemeIcon( "/propertyicons/join.png" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/join.png" ) ) ); break; default: - item->setIcon( QgsApplication::getThemeIcon( "/propertyicons/attributes.png" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/propertyicons/attributes.png" ) ) ); break; } } @@ -97,13 +97,13 @@ QgsOrganizeTableColumnsDialog::QgsOrganizeTableColumnsDialog( const QgsVectorLay QSettings settings; - restoreGeometry( settings.value( "/Windows/QgsOrganizeTableColumnsDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsOrganizeTableColumnsDialog/geometry" ) ).toByteArray() ); } QgsOrganizeTableColumnsDialog::~QgsOrganizeTableColumnsDialog() { QSettings settings; - settings.setValue( "/Windows/QgsOrganizeTableColumnsDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QgsOrganizeTableColumnsDialog/geometry" ), saveGeometry() ); } QgsAttributeTableConfig QgsOrganizeTableColumnsDialog::config() const diff --git a/src/gui/auth/qgsauthauthoritieseditor.cpp b/src/gui/auth/qgsauthauthoritieseditor.cpp index 978e302cabb2..692b5fccfda0 100644 --- a/src/gui/auth/qgsauthauthoritieseditor.cpp +++ b/src/gui/auth/qgsauthauthoritieseditor.cpp @@ -80,14 +80,14 @@ QgsAuthAuthoritiesEditor::QgsAuthAuthoritiesEditor( QWidget *parent ) connect( btnViewRefresh, SIGNAL( clicked() ), this, SLOT( refreshCaCertsView() ) ); - QVariant cafileval = QgsAuthManager::instance()->getAuthSetting( QString( "cafile" ) ); + QVariant cafileval = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "cafile" ) ); if ( !cafileval.isNull() ) { leCaFile->setText( cafileval.toString() ); } btnGroupByOrg->setChecked( false ); - QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QString( "casortby" ), QVariant( false ) ); + QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "casortby" ), QVariant( false ) ); if ( !sortbyval.isNull() ) btnGroupByOrg->setChecked( sortbyval.toBool() ); @@ -301,11 +301,11 @@ void QgsAuthAuthoritiesEditor::appendCertsToItem( const QList<QSslCertificate>& QTreeWidgetItem * item( new QTreeWidgetItem( parent, coltxts, ( int )catype ) ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificate.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificate.svg" ) ) ); if ( !cert.isValid() ) { item->setForeground( 2, redb ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } if ( trustedids.contains( id ) ) @@ -313,17 +313,17 @@ void QgsAuthAuthoritiesEditor::appendCertsToItem( const QList<QSslCertificate>& item->setForeground( 3, greenb ); if ( cert.isValid() ) { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateTrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateTrusted.svg" ) ) ); } } else if ( untrustedids.contains( id ) ) { item->setForeground( 3, redb ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } else if ( mDefaultTrustPolicy == QgsAuthCertUtils::Untrusted ) { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } item->setData( 0, Qt::UserRole, id ); @@ -339,10 +339,10 @@ void QgsAuthAuthoritiesEditor::updateCertTrustPolicyCache() void QgsAuthAuthoritiesEditor::populateUtilitiesMenu() { - mActionDefaultTrustPolicy = new QAction( "Change default trust policy", this ); + mActionDefaultTrustPolicy = new QAction( QStringLiteral( "Change default trust policy" ), this ); connect( mActionDefaultTrustPolicy, SIGNAL( triggered() ), this, SLOT( editDefaultTrustPolicy() ) ); - mActionShowTrustedCAs = new QAction( "Show trusted authorities/issuers", this ); + mActionShowTrustedCAs = new QAction( QStringLiteral( "Show trusted authorities/issuers" ), this ); connect( mActionShowTrustedCAs, SIGNAL( triggered() ), this, SLOT( showTrustedCertificateAuthorities() ) ); mUtilitiesMenu = new QMenu( this ); @@ -564,7 +564,7 @@ void QgsAuthAuthoritiesEditor::on_btnInfoCa_clicked() void QgsAuthAuthoritiesEditor::on_btnGroupByOrg_toggled( bool checked ) { - if ( !QgsAuthManager::instance()->storeAuthSetting( QString( "casortby" ), QVariant( checked ) ) ) + if ( !QgsAuthManager::instance()->storeAuthSetting( QStringLiteral( "casortby" ), QVariant( checked ) ) ) { authMessageOut( QObject::tr( "Could not store sort by preference" ), QObject::tr( "Authorities Manager" ), @@ -677,13 +677,13 @@ void QgsAuthAuthoritiesEditor::on_btnCaFile_clicked() const QString& fn = dlg->certFileToImport(); leCaFile->setText( fn ); - if ( !QgsAuthManager::instance()->storeAuthSetting( QString( "cafile" ), QVariant( fn ) ) ) + if ( !QgsAuthManager::instance()->storeAuthSetting( QStringLiteral( "cafile" ), QVariant( fn ) ) ) { authMessageOut( QObject::tr( "Could not store 'CA file path' in authentication database" ), QObject::tr( "Authorities Manager" ), QgsAuthManager::WARNING ); } - if ( !QgsAuthManager::instance()->storeAuthSetting( QString( "cafileallowinvalid" ), + if ( !QgsAuthManager::instance()->storeAuthSetting( QStringLiteral( "cafileallowinvalid" ), QVariant( dlg->allowInvalidCerts() ) ) ) { authMessageOut( QObject::tr( "Could not store 'CA file allow invalids' setting in authentication database" ), @@ -719,14 +719,14 @@ void QgsAuthAuthoritiesEditor::on_btnCaFile_clicked() void QgsAuthAuthoritiesEditor::on_btnCaFileClear_clicked() { - if ( !QgsAuthManager::instance()->removeAuthSetting( QString( "cafile" ) ) ) + if ( !QgsAuthManager::instance()->removeAuthSetting( QStringLiteral( "cafile" ) ) ) { authMessageOut( QObject::tr( "Could not remove 'CA file path' from authentication database" ), QObject::tr( "Authorities Manager" ), QgsAuthManager::WARNING ); return; } - if ( !QgsAuthManager::instance()->removeAuthSetting( QString( "cafileallowinvalid" ) ) ) + if ( !QgsAuthManager::instance()->removeAuthSetting( QStringLiteral( "cafileallowinvalid" ) ) ) { authMessageOut( QObject::tr( "Could not remove 'CA file allow invalids' setting from authentication database" ), QObject::tr( "Authorities Manager" ), @@ -792,5 +792,5 @@ QgsMessageBar * QgsAuthAuthoritiesEditor::messageBar() int QgsAuthAuthoritiesEditor::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } diff --git a/src/gui/auth/qgsauthcertificateinfo.cpp b/src/gui/auth/qgsauthcertificateinfo.cpp index c217464a741f..6809a238308c 100644 --- a/src/gui/auth/qgsauthcertificateinfo.cpp +++ b/src/gui/auth/qgsauthcertificateinfo.cpp @@ -148,7 +148,7 @@ bool QgsAuthCertInfo::populateQcaCertCollection() for ( int i = 0; i < certpairs.size(); ++i ) { QCA::ConvertResult res; - QCA::Certificate acert = QCA::Certificate::fromPEM( certpairs.at( i ).second.toPem(), &res, QString( "qca-ossl" ) ); + QCA::Certificate acert = QCA::Certificate::fromPEM( certpairs.at( i ).second.toPem(), &res, QStringLiteral( "qca-ossl" ) ); if ( res == QCA::ConvertGood && !acert.isNull() ) { mCaCerts.addCertificate( acert ); @@ -159,7 +159,7 @@ bool QgsAuthCertInfo::populateQcaCertCollection() Q_FOREACH ( const QSslCertificate& cert, mConnectionCAs ) { QCA::ConvertResult res; - QCA::Certificate acert = QCA::Certificate::fromPEM( cert.toPem(), &res, QString( "qca-ossl" ) ); + QCA::Certificate acert = QCA::Certificate::fromPEM( cert.toPem(), &res, QStringLiteral( "qca-ossl" ) ); if ( res == QCA::ConvertGood && !acert.isNull() ) { mCaCerts.addCertificate( acert ); @@ -178,7 +178,7 @@ bool QgsAuthCertInfo::populateQcaCertCollection() bool QgsAuthCertInfo::setQcaCertificate( const QSslCertificate& cert ) { QCA::ConvertResult res; - mCert = QCA::Certificate::fromPEM( cert.toPem(), &res, QString( "qca-ossl" ) ); + mCert = QCA::Certificate::fromPEM( cert.toPem(), &res, QStringLiteral( "qca-ossl" ) ); if ( res != QCA::ConvertGood || mCert.isNull() ) { setupError( tr( "Could not set QCA certificate" ) ); @@ -236,11 +236,11 @@ void QgsAuthCertInfo::setCertHierarchy() { QSslCertificate cert( it.previous() ); bool missingCA = cert.isNull(); - QString cert_source( "" ); + QString cert_source( QLatin1String( "" ) ); if ( missingCA && it.hasPrevious() ) { cert_source = QgsAuthCertUtils::resolvedCertName( it.peekPrevious(), true ); - cert_source += QString( " (%1)" ).arg( tr( "Missing CA" ) ); + cert_source += QStringLiteral( " (%1)" ).arg( tr( "Missing CA" ) ); } else { @@ -249,11 +249,11 @@ void QgsAuthCertInfo::setCertHierarchy() if ( mCaCertsCache.contains( sha ) ) { const QPair<QgsAuthCertUtils::CaCertSource, QSslCertificate >& certpair( mCaCertsCache.value( sha ) ); - cert_source += QString( " (%1)" ).arg( QgsAuthCertUtils::getCaSourceName( certpair.first, true ) ); + cert_source += QStringLiteral( " (%1)" ).arg( QgsAuthCertUtils::getCaSourceName( certpair.first, true ) ); } else if ( mConnectionCAs.contains( cert ) ) { - cert_source += QString( " (%1)" ) + cert_source += QStringLiteral( " (%1)" ) .arg( QgsAuthCertUtils::getCaSourceName( QgsAuthCertUtils::Connection, true ) ); } } @@ -407,7 +407,7 @@ void QgsAuthCertInfo::addFieldItem( QTreeWidgetItem *parent, const QString &fiel QTreeWidgetItem *item = new QTreeWidgetItem( parent, - QStringList() << field << ( wdgt == NoWidget ? value : "" ), + QStringList() << field << ( wdgt == NoWidget ? value : QLatin1String( "" ) ), ( int )DetailsField ); item->setTextAlignment( 0, Qt::AlignRight ); @@ -434,7 +434,7 @@ void QgsAuthCertInfo::addFieldItem( QTreeWidgetItem *parent, const QString &fiel le->setCursorPosition( 0 ); if ( color.isValid() ) { - le->setStyleSheet( QString( "QLineEdit { color: %1; }" ).arg( color.name() ) ); + le->setStyleSheet( QStringLiteral( "QLineEdit { color: %1; }" ).arg( color.name() ) ); } item->treeWidget()->setItemWidget( item, 1, le ); } @@ -447,7 +447,7 @@ void QgsAuthCertInfo::addFieldItem( QTreeWidgetItem *parent, const QString &fiel pte->moveCursor( QTextCursor::Start ); if ( color.isValid() ) { - pte->setStyleSheet( QString( "QPlainTextEdit { color: %1; }" ).arg( color.name() ) ); + pte->setStyleSheet( QStringLiteral( "QPlainTextEdit { color: %1; }" ).arg( color.name() ) ); } item->treeWidget()->setItemWidget( item, 1, pte ); } @@ -494,13 +494,13 @@ void QgsAuthCertInfo::populateInfoGeneralSection() } if (( isissuer || isca ) && isselfsigned ) { - certype = QString( "%1 %2" ) + certype = QStringLiteral( "%1 %2" ) .arg( tr( "Root" ), QgsAuthCertUtils::certificateUsageTypeString( QgsAuthCertUtils::CertAuthorityUsage ) ); } if ( isselfsigned ) { - certype.append( certype.isEmpty() ? selfsigned : QString( " (%1)" ).arg( selfsigned ) ); + certype.append( certype.isEmpty() ? selfsigned : QStringLiteral( " (%1)" ).arg( selfsigned ) ); } addFieldItem( mSecGeneral, tr( "Usage type" ), @@ -521,7 +521,7 @@ void QgsAuthCertInfo::populateInfoGeneralSection() QString alg( pubkey.algorithm() == QSsl::Rsa ? "RSA" : "DSA" ); int bitsize( pubkey.length() ); addFieldItem( mSecGeneral, tr( "Public key" ), - QString( "%1, %2 bits" ).arg( alg, bitsize == -1 ? QString( "?" ) : QString::number( bitsize ) ), + QStringLiteral( "%1, %2 bits" ).arg( alg, bitsize == -1 ? QStringLiteral( "?" ) : QString::number( bitsize ) ), LineEdit ); addFieldItem( mSecGeneral, tr( "Signature algorithm" ), QgsAuthCertUtils::qcaSignatureAlgorithm( mCurrentACert.signatureAlgorithm() ), @@ -604,7 +604,7 @@ void QgsAuthCertInfo::populateInfoDetailsSection() altslist << dns + dnss.join( '\n' + dns ); } addFieldItem( mGrpSubj, tr( "Alternate names" ), - altslist.join( "\n" ), + altslist.join( QStringLiteral( "\n" ) ), TextEdit ); // Issuer Info @@ -686,21 +686,21 @@ void QgsAuthCertInfo::populateInfoDetailsSection() if ( !crllocs.isEmpty() ) { addFieldItem( mGrpCert, tr( "CRL locations" ), - crllocs.join( "\n" ), + crllocs.join( QStringLiteral( "\n" ) ), TextEdit ); } QStringList issulocs( mCurrentACert.issuerLocations() ); if ( !issulocs.isEmpty() ) { addFieldItem( mGrpCert, tr( "Issuer locations" ), - issulocs.join( "\n" ), + issulocs.join( QStringLiteral( "\n" ) ), TextEdit ); } QStringList ocsplocs( mCurrentACert.ocspLocations() ); if ( !ocsplocs.isEmpty() ) { addFieldItem( mGrpCert, tr( "OCSP locations" ), - ocsplocs.join( "\n" ), + ocsplocs.join( QStringLiteral( "\n" ) ), TextEdit ); } @@ -710,10 +710,10 @@ void QgsAuthCertInfo::populateInfoDetailsSection() QString alg( pubqkey.algorithm() == QSsl::Rsa ? "RSA" : "DSA" ); int bitsize( pubqkey.length() ); addFieldItem( mGrpPkey, tr( "Algorithm" ), - bitsize == -1 ? QString( "Unknown (possibly Elliptic Curve)" ) : alg, + bitsize == -1 ? QStringLiteral( "Unknown (possibly Elliptic Curve)" ) : alg, LineEdit ); addFieldItem( mGrpPkey, tr( "Key size" ), - bitsize == -1 ? QString( "?" ) : QString::number( bitsize ), + bitsize == -1 ? QStringLiteral( "?" ) : QString::number( bitsize ), LineEdit ); if ( bitsize > 0 ) // ECC keys unsupported by Qt/QCA, so returned key size is 0 { @@ -773,7 +773,7 @@ void QgsAuthCertInfo::populateInfoDetailsSection() if ( !usage.isEmpty() ) { addFieldItem( mGrpPkey, tr( "Key usage" ), - usage.join( ", " ), + usage.join( QStringLiteral( ", " ) ), LineEdit ); } } @@ -783,7 +783,7 @@ void QgsAuthCertInfo::populateInfoDetailsSection() basicconst << tr( "Certificate Authority: %1" ).arg( mCurrentACert.isCA() ? tr( "Yes" ) : tr( "No" ) ) << tr( "Chain Path Limit: %1" ).arg( mCurrentACert.pathLimit() ); addFieldItem( mGrpExts, tr( "Basic constraints" ), - basicconst.join( "\n" ), + basicconst.join( QStringLiteral( "\n" ) ), TextEdit ); QStringList keyusage; @@ -803,13 +803,13 @@ void QgsAuthCertInfo::populateInfoDetailsSection() if ( !keyusage.isEmpty() ) { addFieldItem( mGrpExts, tr( "Key usage" ), - keyusage.join( "\n" ), + keyusage.join( QStringLiteral( "\n" ) ), TextEdit ); } if ( !extkeyusage.isEmpty() ) { addFieldItem( mGrpExts, tr( "Extended key usage" ), - extkeyusage.join( "\n" ), + extkeyusage.join( QStringLiteral( "\n" ) ), TextEdit ); } @@ -830,7 +830,7 @@ void QgsAuthCertInfo::populateInfoPemTextSection() QTreeWidgetItem *item = new QTreeWidgetItem( mSecPemText, - QStringList( "" ), + QStringList( QLatin1String( "" ) ), ( int )DetailsField ); item->setFirstColumnSpanned( true ); @@ -881,7 +881,7 @@ void QgsAuthCertInfo::decorateCertTreeItem( const QSslCertificate &cert, if ( cert.isNull() || trustpolicy == QgsAuthCertUtils::NoPolicy ) { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateMissing.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateMissing.svg" ) ) ); // missing CA, color gray and italicize QBrush b( item->foreground( 0 ) ); b.setColor( QColor::fromRgb( 90, 90, 90 ) ); @@ -894,23 +894,23 @@ void QgsAuthCertInfo::decorateCertTreeItem( const QSslCertificate &cert, if ( !cert.isValid() ) { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); return; } if ( trustpolicy == QgsAuthCertUtils::Trusted ) { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateTrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateTrusted.svg" ) ) ); } else if ( trustpolicy == QgsAuthCertUtils::Untrusted || ( trustpolicy == QgsAuthCertUtils::DefaultTrust && mDefaultTrustPolicy == QgsAuthCertUtils::Untrusted ) ) { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } else { - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificate.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificate.svg" ) ) ); } } diff --git a/src/gui/auth/qgsauthcerttrustpolicycombobox.cpp b/src/gui/auth/qgsauthcerttrustpolicycombobox.cpp index 97584b1c048a..5d0b3721205c 100644 --- a/src/gui/auth/qgsauthcerttrustpolicycombobox.cpp +++ b/src/gui/auth/qgsauthcerttrustpolicycombobox.cpp @@ -87,18 +87,18 @@ void QgsAuthCertTrustPolicyComboBox::setDefaultTrustPolicy( QgsAuthCertUtils::Ce void QgsAuthCertTrustPolicyComboBox::highlightCurrentIndex( int indx ) { QgsAuthCertUtils::CertTrustPolicy policy = ( QgsAuthCertUtils::CertTrustPolicy )itemData( indx ).toInt(); - QString ss( "" ); + QString ss( QLatin1String( "" ) ); // TODO: why are these widget state selectors backwards? switch ( policy ) { case QgsAuthCertUtils::Trusted: // ss = QgsAuthCertUtils::greenTextStyleSheet( "QLineEdit" ); - ss = QgsAuthGuiUtils::greenTextStyleSheet( "QComboBox:open" ) + "\nQComboBox:!open{}"; + ss = QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QComboBox:open" ) ) + "\nQComboBox:!open{}"; break; case QgsAuthCertUtils::Untrusted: // ss = QgsAuthCertUtils::redTextStyleSheet( "QLineEdit" ); - ss = QgsAuthGuiUtils::redTextStyleSheet( "QComboBox:open" ) + "\nQComboBox:!open{}"; + ss = QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QComboBox:open" ) ) + "\nQComboBox:!open{}"; break; case QgsAuthCertUtils::DefaultTrust: default: @@ -122,7 +122,7 @@ const QString QgsAuthCertTrustPolicyComboBox::defaultTrustText( QgsAuthCertUtils defaultpolicy = QgsAuthCertUtils::Trusted; } } - return QString( "%1 (%2)" ) + return QStringLiteral( "%1 (%2)" ) .arg( QgsAuthCertUtils::getCertTrustName( QgsAuthCertUtils::DefaultTrust ), QgsAuthCertUtils::getCertTrustName( defaultpolicy ) ); } diff --git a/src/gui/auth/qgsauthconfigedit.cpp b/src/gui/auth/qgsauthconfigedit.cpp index c28ed15d3df4..0fd667de7002 100644 --- a/src/gui/auth/qgsauthconfigedit.cpp +++ b/src/gui/auth/qgsauthconfigedit.cpp @@ -45,7 +45,7 @@ QgsAuthConfigEdit::QgsAuthConfigEdit( QWidget *parent , const QString& authcfg , mAuthNotifyLayout = new QVBoxLayout; this->setLayout( mAuthNotifyLayout ); - QString msg( disabled ? QgsAuthManager::instance()->disabledMessage() : "" ); + QString msg( disabled ? QgsAuthManager::instance()->disabledMessage() : QLatin1String( "" ) ); if ( !authcfg.isEmpty() ) { msg += "\n\n" + tr( "Authentication config id not loaded: %1" ).arg( authcfg ); diff --git a/src/gui/auth/qgsauthconfigeditor.cpp b/src/gui/auth/qgsauthconfigeditor.cpp index d12acf8de309..9cc105f57c18 100644 --- a/src/gui/auth/qgsauthconfigeditor.cpp +++ b/src/gui/auth/qgsauthconfigeditor.cpp @@ -97,12 +97,12 @@ QgsAuthConfigEditor::QgsAuthConfigEditor( QWidget *parent, bool showUtilities, b checkSelection(); // set up utility actions menu - mActionSetMasterPassword = new QAction( "Input master password", this ); - mActionClearCachedMasterPassword = new QAction( "Clear cached master password", this ); - mActionResetMasterPassword = new QAction( "Reset master password", this ); - mActionClearCachedAuthConfigs = new QAction( "Clear cached authentication configurations", this ); - mActionRemoveAuthConfigs = new QAction( "Remove all authentication configurations", this ); - mActionEraseAuthDatabase = new QAction( "Erase authentication database", this ); + mActionSetMasterPassword = new QAction( QStringLiteral( "Input master password" ), this ); + mActionClearCachedMasterPassword = new QAction( QStringLiteral( "Clear cached master password" ), this ); + mActionResetMasterPassword = new QAction( QStringLiteral( "Reset master password" ), this ); + mActionClearCachedAuthConfigs = new QAction( QStringLiteral( "Clear cached authentication configurations" ), this ); + mActionRemoveAuthConfigs = new QAction( QStringLiteral( "Remove all authentication configurations" ), this ); + mActionEraseAuthDatabase = new QAction( QStringLiteral( "Erase authentication database" ), this ); connect( mActionSetMasterPassword, SIGNAL( triggered() ), this, SLOT( setMasterPassword() ) ); connect( mActionClearCachedMasterPassword, SIGNAL( triggered() ), this, SLOT( clearCachedMasterPassword() ) ); @@ -287,7 +287,7 @@ QgsMessageBar * QgsAuthConfigEditor::messageBar() int QgsAuthConfigEditor::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } QString QgsAuthConfigEditor::selectedConfigId() diff --git a/src/gui/auth/qgsauthconfigidedit.cpp b/src/gui/auth/qgsauthconfigidedit.cpp index 028486da09a7..e89b9c9c64d6 100644 --- a/src/gui/auth/qgsauthconfigidedit.cpp +++ b/src/gui/auth/qgsauthconfigidedit.cpp @@ -94,9 +94,9 @@ void QgsAuthConfigIdEdit::clear() void QgsAuthConfigIdEdit::updateValidityStyle( bool valid ) { - QString ss( "QLineEdit{" ); - ss += valid ? "" : QString( "color: %1;" ).arg( QgsAuthGuiUtils::redColor().name() ); - ss += !btnLock->isChecked() ? "" : QString( "background-color: %1;" ).arg( QgsAuthGuiUtils::yellowColor().name() ); + QString ss( QStringLiteral( "QLineEdit{" ) ); + ss += valid ? QLatin1String( "" ) : QStringLiteral( "color: %1;" ).arg( QgsAuthGuiUtils::redColor().name() ); + ss += !btnLock->isChecked() ? QLatin1String( "" ) : QStringLiteral( "background-color: %1;" ).arg( QgsAuthGuiUtils::yellowColor().name() ); ss += '}'; leAuthCfg->setStyleSheet( ss ); diff --git a/src/gui/auth/qgsauthconfigselect.cpp b/src/gui/auth/qgsauthconfigselect.cpp index 9a59b2ee3914..734a88b8508e 100644 --- a/src/gui/auth/qgsauthconfigselect.cpp +++ b/src/gui/auth/qgsauthconfigselect.cpp @@ -49,7 +49,7 @@ QgsAuthConfigSelect::QgsAuthConfigSelect( QWidget *parent, const QString &datapr { setupUi( this ); - leConfigMsg->setStyleSheet( QString( "QLineEdit{background-color: %1}" ) + leConfigMsg->setStyleSheet( QStringLiteral( "QLineEdit{background-color: %1}" ) .arg( QgsAuthGuiUtils::yellowColor().name() ) ); clearConfig(); diff --git a/src/gui/auth/qgsautheditorwidgets.cpp b/src/gui/auth/qgsautheditorwidgets.cpp index dd83fbc03976..fc5cec5a9597 100644 --- a/src/gui/auth/qgsautheditorwidgets.cpp +++ b/src/gui/auth/qgsautheditorwidgets.cpp @@ -93,7 +93,7 @@ void QgsAuthMethodPlugins::populateTable() twi->setFlags( twi->flags() & ~Qt::ItemIsEditable ); tblAuthPlugins->setItem( i, 1, twi ); - twi = new QTableWidgetItem( authmethod->supportedDataProviders().join( ", " ) ); + twi = new QTableWidgetItem( authmethod->supportedDataProviders().join( QStringLiteral( ", " ) ) ); twi->setFlags( twi->flags() & ~Qt::ItemIsEditable ); tblAuthPlugins->setItem( i, 2, twi ); } @@ -153,12 +153,12 @@ void QgsAuthEditorWidgets::setupUtilitiesMenu() this, SLOT( authMessageOut( const QString&, const QString&, QgsAuthManager::MessageLevel ) ) ); // set up utility actions menu - mActionSetMasterPassword = new QAction( "Input master password", this ); - mActionClearCachedMasterPassword = new QAction( "Clear cached master password", this ); - mActionResetMasterPassword = new QAction( "Reset master password", this ); - mActionClearCachedAuthConfigs = new QAction( "Clear cached authentication configurations", this ); - mActionRemoveAuthConfigs = new QAction( "Remove all authentication configurations", this ); - mActionEraseAuthDatabase = new QAction( "Erase authentication database", this ); + mActionSetMasterPassword = new QAction( QStringLiteral( "Input master password" ), this ); + mActionClearCachedMasterPassword = new QAction( QStringLiteral( "Clear cached master password" ), this ); + mActionResetMasterPassword = new QAction( QStringLiteral( "Reset master password" ), this ); + mActionClearCachedAuthConfigs = new QAction( QStringLiteral( "Clear cached authentication configurations" ), this ); + mActionRemoveAuthConfigs = new QAction( QStringLiteral( "Remove all authentication configurations" ), this ); + mActionEraseAuthDatabase = new QAction( QStringLiteral( "Erase authentication database" ), this ); connect( mActionSetMasterPassword, SIGNAL( triggered() ), this, SLOT( setMasterPassword() ) ); connect( mActionClearCachedMasterPassword, SIGNAL( triggered() ), this, SLOT( clearCachedMasterPassword() ) ); @@ -224,5 +224,5 @@ QgsMessageBar *QgsAuthEditorWidgets::messageBar() int QgsAuthEditorWidgets::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } diff --git a/src/gui/auth/qgsauthguiutils.cpp b/src/gui/auth/qgsauthguiutils.cpp index f1924487d718..31fc61f23a54 100644 --- a/src/gui/auth/qgsauthguiutils.cpp +++ b/src/gui/auth/qgsauthguiutils.cpp @@ -49,17 +49,17 @@ QColor QgsAuthGuiUtils::yellowColor() QString QgsAuthGuiUtils::greenTextStyleSheet( const QString &selector ) { - return QString( "%1{color: %2;}" ).arg( selector, QgsAuthGuiUtils::greenColor().name() ); + return QStringLiteral( "%1{color: %2;}" ).arg( selector, QgsAuthGuiUtils::greenColor().name() ); } QString QgsAuthGuiUtils::orangeTextStyleSheet( const QString &selector ) { - return QString( "%1{color: %2;}" ).arg( selector, QgsAuthGuiUtils::orangeColor().name() ); + return QStringLiteral( "%1{color: %2;}" ).arg( selector, QgsAuthGuiUtils::orangeColor().name() ); } QString QgsAuthGuiUtils::redTextStyleSheet( const QString &selector ) { - return QString( "%1{color: %2;}" ).arg( selector, QgsAuthGuiUtils::redColor().name() ); + return QStringLiteral( "%1{color: %2;}" ).arg( selector, QgsAuthGuiUtils::redColor().name() ); } bool QgsAuthGuiUtils::isDisabled( QgsMessageBar *msgbar, int timeout ) @@ -239,24 +239,24 @@ void QgsAuthGuiUtils::fileFound( bool found, QWidget *widget ) { if ( !found ) { - widget->setStyleSheet( QgsAuthGuiUtils::redTextStyleSheet( "QLineEdit" ) ); + widget->setStyleSheet( QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QLineEdit" ) ) ); widget->setToolTip( QObject::tr( "File not found" ) ); } else { - widget->setStyleSheet( "" ); - widget->setToolTip( "" ); + widget->setStyleSheet( QLatin1String( "" ) ); + widget->setToolTip( QLatin1String( "" ) ); } } QString QgsAuthGuiUtils::getOpenFileName( QWidget *parent, const QString &title, const QString &extfilter ) { QSettings settings; - QString recentdir = settings.value( "UI/lastAuthOpenFileDir", QDir::homePath() ).toString(); + QString recentdir = settings.value( QStringLiteral( "UI/lastAuthOpenFileDir" ), QDir::homePath() ).toString(); QString f = QFileDialog::getOpenFileName( parent, title, recentdir, extfilter ); if ( !f.isEmpty() ) { - settings.setValue( "UI/lastAuthOpenFileDir", QFileInfo( f ).absoluteDir().path() ); + settings.setValue( QStringLiteral( "UI/lastAuthOpenFileDir" ), QFileInfo( f ).absoluteDir().path() ); } return f; } diff --git a/src/gui/auth/qgsauthguiutils.h b/src/gui/auth/qgsauthguiutils.h index 3ec09b6485d3..b06fd7caecde 100644 --- a/src/gui/auth/qgsauthguiutils.h +++ b/src/gui/auth/qgsauthguiutils.h @@ -44,13 +44,13 @@ class GUI_EXPORT QgsAuthGuiUtils static QColor yellowColor(); /** Green text stylesheet representing valid, trusted, etc. certificate */ - static QString greenTextStyleSheet( const QString& selector = "*" ); + static QString greenTextStyleSheet( const QString& selector = QStringLiteral( "*" ) ); /** Orange text stylesheet representing loaded component, but not stored in database */ - static QString orangeTextStyleSheet( const QString& selector = "*" ); + static QString orangeTextStyleSheet( const QString& selector = QStringLiteral( "*" ) ); /** Red text stylesheet representing invalid, untrusted, etc. certificate */ - static QString redTextStyleSheet( const QString& selector = "*" ); + static QString redTextStyleSheet( const QString& selector = QStringLiteral( "*" ) ); /** Verify the authentication system is active, else notify user */ diff --git a/src/gui/auth/qgsauthidentitieseditor.cpp b/src/gui/auth/qgsauthidentitieseditor.cpp index d56ea6273eff..ec65f3c481a2 100644 --- a/src/gui/auth/qgsauthidentitieseditor.cpp +++ b/src/gui/auth/qgsauthidentitieseditor.cpp @@ -66,7 +66,7 @@ QgsAuthIdentitiesEditor::QgsAuthIdentitiesEditor( QWidget *parent ) connect( btnViewRefresh, SIGNAL( clicked() ), this, SLOT( refreshIdentitiesView() ) ); btnGroupByOrg->setChecked( false ); - QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QString( "identitiessortby" ), QVariant( false ) ); + QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "identitiessortby" ), QVariant( false ) ); if ( !sortbyval.isNull() ) btnGroupByOrg->setChecked( sortbyval.toBool() ); @@ -208,11 +208,11 @@ void QgsAuthIdentitiesEditor::appendIdentitiesToItem( const QList<QSslCertificat QTreeWidgetItem * item( new QTreeWidgetItem( parent, coltxts, ( int )identype ) ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificate.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificate.svg" ) ) ); if ( !cert.isValid() ) { item->setForeground( 2, redb ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } item->setData( 0, Qt::UserRole, id ); @@ -374,7 +374,7 @@ void QgsAuthIdentitiesEditor::on_btnInfoIdentity_clicked() void QgsAuthIdentitiesEditor::on_btnGroupByOrg_toggled( bool checked ) { - if ( !QgsAuthManager::instance()->storeAuthSetting( QString( "identitiessortby" ), QVariant( checked ) ) ) + if ( !QgsAuthManager::instance()->storeAuthSetting( QStringLiteral( "identitiessortby" ), QVariant( checked ) ) ) { authMessageOut( QObject::tr( "Could not store sort by preference" ), QObject::tr( "Authentication Identities" ), @@ -406,5 +406,5 @@ QgsMessageBar * QgsAuthIdentitiesEditor::messageBar() int QgsAuthIdentitiesEditor::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } diff --git a/src/gui/auth/qgsauthimportcertdialog.cpp b/src/gui/auth/qgsauthimportcertdialog.cpp index 6386371fe8a3..4e1623033417 100644 --- a/src/gui/auth/qgsauthimportcertdialog.cpp +++ b/src/gui/auth/qgsauthimportcertdialog.cpp @@ -151,7 +151,7 @@ void QgsAuthImportCertDialog::validateCertificates() { mCerts.clear(); teValidation->clear(); - teValidation->setStyleSheet( "" ); + teValidation->setStyleSheet( QLatin1String( "" ) ); bool valid = false; QList<QSslCertificate> certs; @@ -208,8 +208,8 @@ void QgsAuthImportCertDialog::validateCertificates() if ( certssize > 0 ) { teValidation->setStyleSheet( - valid ? QgsAuthGuiUtils::greenTextStyleSheet( "QTextEdit" ) - : QgsAuthGuiUtils::redTextStyleSheet( "QTextEdit" ) ); + valid ? QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QTextEdit" ) ) + : QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QTextEdit" ) ) ); } QString msg = tr( "Certificates found: %1\n" @@ -245,7 +245,7 @@ void QgsAuthImportCertDialog::on_chkAllowInvalid_toggled( bool checked ) QString QgsAuthImportCertDialog::getOpenFileName( const QString &title, const QString &extfilter ) { QSettings settings; - QString recentdir = settings.value( "UI/lastAuthImportCertOpenFileDir", QDir::homePath() ).toString(); + QString recentdir = settings.value( QStringLiteral( "UI/lastAuthImportCertOpenFileDir" ), QDir::homePath() ).toString(); QString f = QFileDialog::getOpenFileName( this, title, recentdir, extfilter ); // return dialog focus on Mac @@ -254,7 +254,7 @@ QString QgsAuthImportCertDialog::getOpenFileName( const QString &title, const QS if ( !f.isEmpty() ) { - settings.setValue( "UI/lastAuthImportCertOpenFileDir", QFileInfo( f ).absoluteDir().path() ); + settings.setValue( QStringLiteral( "UI/lastAuthImportCertOpenFileDir" ), QFileInfo( f ).absoluteDir().path() ); } return f; } diff --git a/src/gui/auth/qgsauthimportidentitydialog.cpp b/src/gui/auth/qgsauthimportidentitydialog.cpp index ff433525cc82..d99fd7a4f378 100644 --- a/src/gui/auth/qgsauthimportidentitydialog.cpp +++ b/src/gui/auth/qgsauthimportidentitydialog.cpp @@ -162,7 +162,7 @@ bool QgsAuthImportIdentityDialog::validateBundle() void QgsAuthImportIdentityDialog::clearValidation() { teValidation->clear(); - teValidation->setStyleSheet( "" ); + teValidation->setStyleSheet( QLatin1String( "" ) ); } void QgsAuthImportIdentityDialog::writeValidation( const QString &msg, @@ -174,16 +174,16 @@ void QgsAuthImportIdentityDialog::writeValidation( const QString &msg, switch ( valid ) { case Valid: - ss = QgsAuthGuiUtils::greenTextStyleSheet( "QTextEdit" ); + ss = QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QTextEdit" ) ); txt = tr( "Valid: %1" ).arg( msg ); break; case Invalid: - ss = QgsAuthGuiUtils::redTextStyleSheet( "QTextEdit" ); + ss = QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QTextEdit" ) ); txt = tr( "Invalid: %1" ).arg( msg ); break; case Unknown: default: - ss = ""; + ss = QLatin1String( "" ); break; } teValidation->setStyleSheet( ss ); @@ -305,7 +305,7 @@ bool QgsAuthImportIdentityDialog::validatePkiPaths() //TODO: set enabled on cert info button, relative to cert validity // check for valid private key and that any supplied password works - bool keypem = keypath.endsWith( ".pem", Qt::CaseInsensitive ); + bool keypem = keypath.endsWith( QLatin1String( ".pem" ), Qt::CaseInsensitive ); QByteArray keydata( fileData_( keypath, keypem ) ); QSslKey clientkey; @@ -379,7 +379,7 @@ bool QgsAuthImportIdentityDialog::validatePkiPkcs12() } QCA::ConvertResult res; - QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QString( "qca-ossl" ) ) ); + QCA::KeyBundle bundle( QCA::KeyBundle::fromFile( bundlepath, passarray, &res, QStringLiteral( "qca-ossl" ) ) ); if ( res == QCA::ErrorFile ) { @@ -389,7 +389,7 @@ bool QgsAuthImportIdentityDialog::validatePkiPkcs12() else if ( res == QCA::ErrorPassphrase ) { writeValidation( tr( "Incorrect bundle password" ), Invalid ); - lePkiPkcs12KeyPass->setPlaceholderText( QString( "Required passphrase" ) ); + lePkiPkcs12KeyPass->setPlaceholderText( QStringLiteral( "Required passphrase" ) ); return false; } else if ( res == QCA::ErrorDecode ) @@ -466,20 +466,20 @@ void QgsAuthImportIdentityDialog::fileFound( bool found, QWidget *widget ) { if ( !found ) { - widget->setStyleSheet( QgsAuthGuiUtils::redTextStyleSheet( "QLineEdit" ) ); + widget->setStyleSheet( QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QLineEdit" ) ) ); widget->setToolTip( tr( "File not found" ) ); } else { - widget->setStyleSheet( "" ); - widget->setToolTip( "" ); + widget->setStyleSheet( QLatin1String( "" ) ); + widget->setToolTip( QLatin1String( "" ) ); } } QString QgsAuthImportIdentityDialog::getOpenFileName( const QString &title, const QString &extfilter ) { QSettings settings; - QString recentdir = settings.value( "UI/lastAuthImportBundleOpenFileDir", QDir::homePath() ).toString(); + QString recentdir = settings.value( QStringLiteral( "UI/lastAuthImportBundleOpenFileDir" ), QDir::homePath() ).toString(); QString f = QFileDialog::getOpenFileName( this, title, recentdir, extfilter ); // return dialog focus on Mac @@ -488,7 +488,7 @@ QString QgsAuthImportIdentityDialog::getOpenFileName( const QString &title, cons if ( !f.isEmpty() ) { - settings.setValue( "UI/lastAuthImportBundleOpenFileDir", QFileInfo( f ).absoluteDir().path() ); + settings.setValue( QStringLiteral( "UI/lastAuthImportBundleOpenFileDir" ), QFileInfo( f ).absoluteDir().path() ); } return f; } diff --git a/src/gui/auth/qgsauthmasterpassresetdialog.cpp b/src/gui/auth/qgsauthmasterpassresetdialog.cpp index ef38140b4b08..5c1330c35ac3 100644 --- a/src/gui/auth/qgsauthmasterpassresetdialog.cpp +++ b/src/gui/auth/qgsauthmasterpassresetdialog.cpp @@ -96,11 +96,11 @@ void QgsMasterPasswordResetDialog::on_chkPassShowNew_stateChanged( int state ) void QgsMasterPasswordResetDialog::validatePasswords() { - QString ss1 = mPassCurOk ? QgsAuthGuiUtils::greenTextStyleSheet( "QLineEdit" ) - : QgsAuthGuiUtils::redTextStyleSheet( "QLineEdit" ); + QString ss1 = mPassCurOk ? QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QLineEdit" ) ) + : QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QLineEdit" ) ); leMasterPassCurrent->setStyleSheet( ss1 ); - QString ss2 = mPassNewOk ? QgsAuthGuiUtils::greenTextStyleSheet( "QLineEdit" ) - : QgsAuthGuiUtils::redTextStyleSheet( "QLineEdit" ); + QString ss2 = mPassNewOk ? QgsAuthGuiUtils::greenTextStyleSheet( QStringLiteral( "QLineEdit" ) ) + : QgsAuthGuiUtils::redTextStyleSheet( QStringLiteral( "QLineEdit" ) ); leMasterPassNew->setStyleSheet( ss2 ); buttonBox->button( QDialogButtonBox::Ok )->setEnabled( mPassCurOk && mPassNewOk ); } diff --git a/src/gui/auth/qgsauthserverseditor.cpp b/src/gui/auth/qgsauthserverseditor.cpp index e91bef5b4b22..22971af85d52 100644 --- a/src/gui/auth/qgsauthserverseditor.cpp +++ b/src/gui/auth/qgsauthserverseditor.cpp @@ -64,7 +64,7 @@ QgsAuthServersEditor::QgsAuthServersEditor( QWidget *parent ) connect( btnViewRefresh, SIGNAL( clicked() ), this, SLOT( refreshSslConfigsView() ) ); btnGroupByOrg->setChecked( false ); - QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QString( "serverssortby" ), QVariant( false ) ); + QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "serverssortby" ), QVariant( false ) ); if ( !sortbyval.isNull() ) btnGroupByOrg->setChecked( sortbyval.toBool() ); @@ -209,11 +209,11 @@ void QgsAuthServersEditor::appendSslConfigsToItem( const QList<QgsAuthConfigSslS QTreeWidgetItem * item( new QTreeWidgetItem( parent, coltxts, ( int )conftype ) ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificate.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificate.svg" ) ) ); if ( !cert.isValid() ) { item->setForeground( 2, redb ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } item->setData( 0, Qt::UserRole, id ); @@ -389,7 +389,7 @@ void QgsAuthServersEditor::on_btnEditServer_clicked() void QgsAuthServersEditor::on_btnGroupByOrg_toggled( bool checked ) { - if ( !QgsAuthManager::instance()->storeAuthSetting( QString( "serverssortby" ), QVariant( checked ) ) ) + if ( !QgsAuthManager::instance()->storeAuthSetting( QStringLiteral( "serverssortby" ), QVariant( checked ) ) ) { authMessageOut( QObject::tr( "Could not store sort by preference" ), QObject::tr( "Authentication SSL Configs" ), @@ -421,5 +421,5 @@ QgsMessageBar * QgsAuthServersEditor::messageBar() int QgsAuthServersEditor::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } diff --git a/src/gui/auth/qgsauthsslconfigwidget.cpp b/src/gui/auth/qgsauthsslconfigwidget.cpp index b96faa693d25..84c45ad0ed67 100644 --- a/src/gui/auth/qgsauthsslconfigwidget.cpp +++ b/src/gui/auth/qgsauthsslconfigwidget.cpp @@ -76,7 +76,7 @@ QgsAuthSslConfigWidget::QgsAuthSslConfigWidget( QWidget *parent, setUpSslConfigTree(); lblLoadedConfig->setVisible( false ); - lblLoadedConfig->setText( "" ); + lblLoadedConfig->setText( QLatin1String( "" ) ); connect( leHost, SIGNAL( textChanged( QString ) ), this, SLOT( validateHostPortText( QString ) ) ); @@ -145,7 +145,7 @@ void QgsAuthSslConfigWidget::setUpSslConfigTree() mProtocolCmbBx->setCurrentIndex( 0 ); QTreeWidgetItem *protocolitem = new QTreeWidgetItem( mProtocolItem, - QStringList() << "", + QStringList() << QLatin1String( "" ), ( int )ConfigItem ); protocolitem->setFlags( protocolitem->flags() & ~Qt::ItemIsSelectable ); treeSslConfig->setItemWidget( protocolitem, 0, mProtocolCmbBx ); @@ -161,7 +161,7 @@ void QgsAuthSslConfigWidget::setUpSslConfigTree() mVerifyPeerCmbBx->setCurrentIndex( 0 ); QTreeWidgetItem *peerverifycmbxitem = new QTreeWidgetItem( mVerifyModeItem, - QStringList() << "", + QStringList() << QLatin1String( "" ), ( int )ConfigItem ); peerverifycmbxitem->setFlags( peerverifycmbxitem->flags() & ~Qt::ItemIsSelectable ); treeSslConfig->setItemWidget( peerverifycmbxitem, 0, mVerifyPeerCmbBx ); @@ -175,7 +175,7 @@ void QgsAuthSslConfigWidget::setUpSslConfigTree() mVerifyDepthSpnBx->setAlignment( Qt::AlignHCenter ); QTreeWidgetItem *peerverifyspnbxitem = new QTreeWidgetItem( mVerifyDepthItem, - QStringList() << "", + QStringList() << QLatin1String( "" ), ( int )ConfigItem ); peerverifyspnbxitem->setFlags( peerverifyspnbxitem->flags() & ~Qt::ItemIsSelectable ); treeSslConfig->setItemWidget( peerverifyspnbxitem, 0, mVerifyDepthSpnBx ); @@ -335,11 +335,11 @@ void QgsAuthSslConfigWidget::resetSslCertConfig() mCert.clear(); mConnectionCAs.clear(); leCommonName->clear(); - leCommonName->setStyleSheet( "" ); + leCommonName->setStyleSheet( QLatin1String( "" ) ); leHost->clear(); lblLoadedConfig->setVisible( false ); - lblLoadedConfig->setText( "" ); + lblLoadedConfig->setText( QLatin1String( "" ) ); resetSslProtocol(); resetSslIgnoreErrors(); resetSslPeerVerify(); @@ -547,10 +547,10 @@ bool QgsAuthSslConfigWidget::validateHostPort( const QString &txt ) // TODO: add QRegex checks against valid IP and domain.tld input // i.e., currently accepts unlikely (though maybe valid) host:port combo, like 'a:1' - QString urlbase( QString( "https://%1" ).arg( hostport ) ); + QString urlbase( QStringLiteral( "https://%1" ).arg( hostport ) ); QUrl url( urlbase ); return ( !url.host().isEmpty() && QString::number( url.port() ).size() > 0 - && QString( "https://%1:%2" ).arg( url.host() ).arg( url.port() ) == urlbase ); + && QStringLiteral( "https://%1:%2" ).arg( url.host() ).arg( url.port() ) == urlbase ); } void QgsAuthSslConfigWidget::validateHostPortText( const QString &txt ) diff --git a/src/gui/auth/qgsauthsslerrorsdialog.cpp b/src/gui/auth/qgsauthsslerrorsdialog.cpp index add35cdc9597..1d1e1c7d2a55 100644 --- a/src/gui/auth/qgsauthsslerrorsdialog.cpp +++ b/src/gui/auth/qgsauthsslerrorsdialog.cpp @@ -48,7 +48,7 @@ QgsAuthSslErrorsDialog::QgsAuthSslErrorsDialog( QNetworkReply *reply, } if ( mHostPort.isEmpty() ) { - mHostPort = QString( "%1:%2" ) + mHostPort = QStringLiteral( "%1:%2" ) .arg( reply->url().host() ) .arg( reply->url().port() != -1 ? reply->url().port() : 443 ) .trimmed(); @@ -59,7 +59,7 @@ QgsAuthSslErrorsDialog::QgsAuthSslErrorsDialog( QNetworkReply *reply, lblWarningIcon->setPixmap( style->standardIcon( QStyle::SP_MessageBoxWarning ).pixmap( 48, 48 ) ); lblWarningIcon->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); - lblErrorsText->setStyleSheet( "QLabel{ font-weight: bold; }" ); + lblErrorsText->setStyleSheet( QStringLiteral( "QLabel{ font-weight: bold; }" ) ); leUrl->setText( reply->request().url().toString() ); ignoreButton()->setDefault( false ); @@ -69,7 +69,7 @@ QgsAuthSslErrorsDialog::QgsAuthSslErrorsDialog( QNetworkReply *reply, { saveButton()->setEnabled( false ); - saveButton()->setText( QString( "%1 && %2" ).arg( saveButton()->text(), + saveButton()->setText( QStringLiteral( "%1 && %2" ).arg( saveButton()->text(), ignoreButton()->text() ) ); grpbxSslConfig->setChecked( false ); @@ -169,7 +169,7 @@ void QgsAuthSslErrorsDialog::on_buttonBox_clicked( QAbstractButton *button ) { case QDialogButtonBox::Ignore: QgsAuthManager::instance()->updateIgnoredSslErrorsCache( - QString( "%1:%2" ).arg( mDigest, mHostPort ), + QStringLiteral( "%1:%2" ).arg( mDigest, mHostPort ), mSslErrors ); accept(); break; @@ -191,11 +191,11 @@ void QgsAuthSslErrorsDialog::populateErrorsList() errs.reserve( mSslErrors.size() ); Q_FOREACH ( const QSslError &err, mSslErrors ) { - errs << QString( "* %1: %2" ) + errs << QStringLiteral( "* %1: %2" ) .arg( QgsAuthCertUtils::sslErrorEnumString( err.error() ), err.errorString() ); } - teSslErrors->setPlainText( errs.join( "\n" ) ); + teSslErrors->setPlainText( errs.join( QStringLiteral( "\n" ) ) ); } QPushButton *QgsAuthSslErrorsDialog::ignoreButton() diff --git a/src/gui/auth/qgsauthsslimportdialog.cpp b/src/gui/auth/qgsauthsslimportdialog.cpp index 636b5a7ca683..798b839f0014 100644 --- a/src/gui/auth/qgsauthsslimportdialog.cpp +++ b/src/gui/auth/qgsauthsslimportdialog.cpp @@ -154,7 +154,7 @@ void QgsAuthSslImportDialog::accept() void QgsAuthSslImportDialog::updateEnabledState() { - leServer->setStyleSheet( "" ); + leServer->setStyleSheet( QLatin1String( "" ) ); bool unconnected = !mSocket || mSocket->state() == QAbstractSocket::UnconnectedState; @@ -179,7 +179,7 @@ void QgsAuthSslImportDialog::secureConnect() return; } - leServer->setStyleSheet( "" ); + leServer->setStyleSheet( QLatin1String( "" ) ); clearStatusCertificateConfig(); if ( !mSocket ) @@ -248,11 +248,11 @@ void QgsAuthSslImportDialog::socketEncrypted() appendString( tr( "Socket ENCRYPTED" ) ); - appendString( QString( "%1: %2" ).arg( tr( "Protocol" ), - QgsAuthCertUtils::getSslProtocolName( mSocket->protocol() ) ) ); + appendString( QStringLiteral( "%1: %2" ).arg( tr( "Protocol" ), + QgsAuthCertUtils::getSslProtocolName( mSocket->protocol() ) ) ); QSslCipher ciph = mSocket->sessionCipher(); - QString cipher = QString( "%1: %2, %3 (%4/%5)" ) + QString cipher = QStringLiteral( "%1: %2, %3 (%4/%5)" ) .arg( tr( "Session cipher" ), ciph.authenticationMethod(), ciph.name() ) .arg( ciph.usedBits() ).arg( ciph.supportedBits() ); appendString( cipher ); @@ -260,7 +260,7 @@ void QgsAuthSslImportDialog::socketEncrypted() wdgtSslConfig->setEnabled( true ); - QString hostport( QString( "%1:%2" ).arg( mSocket->peerName() ).arg( mSocket->peerPort() ) ); + QString hostport( QStringLiteral( "%1:%2" ).arg( mSocket->peerName() ).arg( mSocket->peerPort() ) ); wdgtSslConfig->setSslCertificate( mSocket->peerCertificate(), hostport.trimmed() ); if ( !mSslErrors.isEmpty() ) { @@ -281,7 +281,7 @@ void QgsAuthSslImportDialog::socketError( QAbstractSocket::SocketError err ) Q_UNUSED( err ); if ( mSocket ) { - appendString( QString( "%1: %2" ).arg( tr( "Socket ERROR" ), mSocket->errorString() ) ); + appendString( QStringLiteral( "%1: %2" ).arg( tr( "Socket ERROR" ), mSocket->errorString() ) ); } } @@ -428,7 +428,7 @@ void QgsAuthSslImportDialog::loadCertFromFile() } wdgtSslConfig->setEnabled( true ); - wdgtSslConfig->setSslHost( "" ); + wdgtSslConfig->setSslHost( QLatin1String( "" ) ); wdgtSslConfig->setSslCertificate( cert ); if ( !mSslErrors.isEmpty() ) { @@ -459,7 +459,7 @@ QPushButton *QgsAuthSslImportDialog::closeButton() QString QgsAuthSslImportDialog::getOpenFileName( const QString &title, const QString &extfilter ) { QSettings settings; - QString recentdir = settings.value( "UI/lastAuthImportSslOpenFileDir", QDir::homePath() ).toString(); + QString recentdir = settings.value( QStringLiteral( "UI/lastAuthImportSslOpenFileDir" ), QDir::homePath() ).toString(); QString f = QFileDialog::getOpenFileName( this, title, recentdir, extfilter ); // return dialog focus on Mac @@ -468,7 +468,7 @@ QString QgsAuthSslImportDialog::getOpenFileName( const QString &title, const QSt if ( !f.isEmpty() ) { - settings.setValue( "UI/lastAuthImportSslOpenFileDir", QFileInfo( f ).absoluteDir().path() ); + settings.setValue( QStringLiteral( "UI/lastAuthImportSslOpenFileDir" ), QFileInfo( f ).absoluteDir().path() ); } return f; } diff --git a/src/gui/auth/qgsauthtrustedcasdialog.cpp b/src/gui/auth/qgsauthtrustedcasdialog.cpp index a73338909dfa..5ebaee0485c1 100644 --- a/src/gui/auth/qgsauthtrustedcasdialog.cpp +++ b/src/gui/auth/qgsauthtrustedcasdialog.cpp @@ -61,7 +61,7 @@ QgsAuthTrustedCAsDialog::QgsAuthTrustedCAsDialog( QWidget *parent, btnGroupByOrg->setChecked( false ); - QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QString( "trustedcasortby" ), QVariant( false ) ); + QVariant sortbyval = QgsAuthManager::instance()->getAuthSetting( QStringLiteral( "trustedcasortby" ), QVariant( false ) ); if ( !sortbyval.isNull() ) btnGroupByOrg->setChecked( sortbyval.toBool() ); @@ -201,11 +201,11 @@ void QgsAuthTrustedCAsDialog::appendCertsToItem( const QList<QSslCertificate>& c QTreeWidgetItem * item( new QTreeWidgetItem( parent, coltxts, ( int )catype ) ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificate.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificate.svg" ) ) ); if ( !cert.isValid() ) { item->setForeground( 2, redb ); - item->setIcon( 0, QgsApplication::getThemeIcon( "/mIconCertificateUntrusted.svg" ) ); + item->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mIconCertificateUntrusted.svg" ) ) ); } item->setData( 0, Qt::UserRole, id ); @@ -300,7 +300,7 @@ void QgsAuthTrustedCAsDialog::on_btnInfoCa_clicked() void QgsAuthTrustedCAsDialog::on_btnGroupByOrg_toggled( bool checked ) { - if ( !QgsAuthManager::instance()->storeAuthSetting( QString( "trustedcasortby" ), QVariant( checked ) ) ) + if ( !QgsAuthManager::instance()->storeAuthSetting( QStringLiteral( "trustedcasortby" ), QVariant( checked ) ) ) { authMessageOut( QObject::tr( "Could not store sort by preference" ), QObject::tr( "Trusted Authorities/Issuers" ), @@ -332,5 +332,5 @@ QgsMessageBar * QgsAuthTrustedCAsDialog::messageBar() int QgsAuthTrustedCAsDialog::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } diff --git a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp index 63a496f5c0ff..a52abda87b9f 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp @@ -85,7 +85,7 @@ QgsEditorWidgetAutoConf::QgsEditorWidgetAutoConf() QgsEditorWidgetSetup QgsEditorWidgetAutoConf::editorWidgetSetup( const QgsVectorLayer* vl, const QString& fieldName ) const { - QgsEditorWidgetSetup result( "TextEdit", QgsEditorWidgetConfig() ); + QgsEditorWidgetSetup result( QStringLiteral( "TextEdit" ), QgsEditorWidgetConfig() ); if ( vl->fields().indexFromName( fieldName ) >= 0 ) { diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index e5c86ece7c28..13bf85529a82 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -56,27 +56,27 @@ QgsEditorWidgetRegistry* QgsEditorWidgetRegistry::instance() void QgsEditorWidgetRegistry::initEditors( QgsMapCanvas *mapCanvas, QgsMessageBar *messageBar ) { QgsEditorWidgetRegistry *reg = instance(); - reg->registerWidget( "TextEdit", new QgsTextEditWidgetFactory( tr( "Text Edit" ) ) ); - reg->registerWidget( "Classification", new QgsClassificationWidgetWrapperFactory( tr( "Classification" ) ) ); - reg->registerWidget( "Range", new QgsRangeWidgetFactory( tr( "Range" ) ) ); - reg->registerWidget( "UniqueValues", new QgsUniqueValueWidgetFactory( tr( "Unique Values" ) ) ); - reg->registerWidget( "FileName", new QgsFileNameWidgetFactory( tr( "File Name" ) ) ); - reg->registerWidget( "ValueMap", new QgsValueMapWidgetFactory( tr( "Value Map" ) ) ); - reg->registerWidget( "Enumeration", new QgsEnumerationWidgetFactory( tr( "Enumeration" ) ) ); - reg->registerWidget( "Hidden", new QgsHiddenWidgetFactory( tr( "Hidden" ) ) ); - reg->registerWidget( "CheckBox", new QgsCheckboxWidgetFactory( tr( "Check Box" ) ) ); - reg->registerWidget( "ValueRelation", new QgsValueRelationWidgetFactory( tr( "Value Relation" ) ) ); - reg->registerWidget( "UuidGenerator", new QgsUuidWidgetFactory( tr( "Uuid Generator" ) ) ); - reg->registerWidget( "Photo", new QgsPhotoWidgetFactory( tr( "Photo" ) ) ); + reg->registerWidget( QStringLiteral( "TextEdit" ), new QgsTextEditWidgetFactory( tr( "Text Edit" ) ) ); + reg->registerWidget( QStringLiteral( "Classification" ), new QgsClassificationWidgetWrapperFactory( tr( "Classification" ) ) ); + reg->registerWidget( QStringLiteral( "Range" ), new QgsRangeWidgetFactory( tr( "Range" ) ) ); + reg->registerWidget( QStringLiteral( "UniqueValues" ), new QgsUniqueValueWidgetFactory( tr( "Unique Values" ) ) ); + reg->registerWidget( QStringLiteral( "FileName" ), new QgsFileNameWidgetFactory( tr( "File Name" ) ) ); + reg->registerWidget( QStringLiteral( "ValueMap" ), new QgsValueMapWidgetFactory( tr( "Value Map" ) ) ); + reg->registerWidget( QStringLiteral( "Enumeration" ), new QgsEnumerationWidgetFactory( tr( "Enumeration" ) ) ); + reg->registerWidget( QStringLiteral( "Hidden" ), new QgsHiddenWidgetFactory( tr( "Hidden" ) ) ); + reg->registerWidget( QStringLiteral( "CheckBox" ), new QgsCheckboxWidgetFactory( tr( "Check Box" ) ) ); + reg->registerWidget( QStringLiteral( "ValueRelation" ), new QgsValueRelationWidgetFactory( tr( "Value Relation" ) ) ); + reg->registerWidget( QStringLiteral( "UuidGenerator" ), new QgsUuidWidgetFactory( tr( "Uuid Generator" ) ) ); + reg->registerWidget( QStringLiteral( "Photo" ), new QgsPhotoWidgetFactory( tr( "Photo" ) ) ); #ifdef WITH_QTWEBKIT - reg->registerWidget( "WebView", new QgsWebViewWidgetFactory( tr( "Web View" ) ) ); + reg->registerWidget( QStringLiteral( "WebView" ), new QgsWebViewWidgetFactory( tr( "Web View" ) ) ); #endif - reg->registerWidget( "Color", new QgsColorWidgetFactory( tr( "Color" ) ) ); - reg->registerWidget( "RelationReference", new QgsRelationReferenceFactory( tr( "Relation Reference" ), mapCanvas, messageBar ) ); - reg->registerWidget( "DateTime", new QgsDateTimeEditFactory( tr( "Date/Time" ) ) ); - reg->registerWidget( "ExternalResource", new QgsExternalResourceWidgetFactory( tr( "External Resource" ) ) ); - reg->registerWidget( "KeyValue", new QgsKeyValueWidgetFactory( tr( "Key/Value" ) ) ); - reg->registerWidget( "List", new QgsListWidgetFactory( tr( "List" ) ) ); + reg->registerWidget( QStringLiteral( "Color" ), new QgsColorWidgetFactory( tr( "Color" ) ) ); + reg->registerWidget( QStringLiteral( "RelationReference" ), new QgsRelationReferenceFactory( tr( "Relation Reference" ), mapCanvas, messageBar ) ); + reg->registerWidget( QStringLiteral( "DateTime" ), new QgsDateTimeEditFactory( tr( "Date/Time" ) ) ); + reg->registerWidget( QStringLiteral( "ExternalResource" ), new QgsExternalResourceWidgetFactory( tr( "External Resource" ) ) ); + reg->registerWidget( QStringLiteral( "KeyValue" ), new QgsKeyValueWidgetFactory( tr( "Key/Value" ) ) ); + reg->registerWidget( QStringLiteral( "List" ), new QgsListWidgetFactory( tr( "List" ) ) ); } QgsEditorWidgetRegistry::QgsEditorWidgetRegistry() @@ -128,7 +128,7 @@ QgsEditorWidgetWrapper* QgsEditorWidgetRegistry::create( const QString& widgetId if ( !ww->valid() ) { delete ww; - QString wid = findSuitableWrapper( editor, "TextEdit" ); + QString wid = findSuitableWrapper( editor, QStringLiteral( "TextEdit" ) ); ww = mWidgetFactories[wid]->create( vl, fieldIdx, editor, parent ); ww->setConfig( config ); ww->setContext( context ); @@ -194,12 +194,12 @@ bool QgsEditorWidgetRegistry::registerWidget( const QString& widgetId, QgsEditor { if ( !widgetFactory ) { - QgsMessageLog::instance()->logMessage( "QgsEditorWidgetRegistry: Factory not valid." ); + QgsMessageLog::instance()->logMessage( QStringLiteral( "QgsEditorWidgetRegistry: Factory not valid." ) ); return false; } else if ( mWidgetFactories.contains( widgetId ) ) { - QgsMessageLog::instance()->logMessage( QString( "QgsEditorWidgetRegistry: Factory with id %1 already registered." ).arg( widgetId ) ); + QgsMessageLog::instance()->logMessage( QStringLiteral( "QgsEditorWidgetRegistry: Factory with id %1 already registered." ).arg( widgetId ) ); return false; } else @@ -233,7 +233,7 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle QgsVectorLayer* vectorLayer = qobject_cast<QgsVectorLayer*>( mapLayer ); Q_ASSERT( vectorLayer ); - QDomNodeList editTypeNodes = layerElem.namedItem( "edittypes" ).childNodes(); + QDomNodeList editTypeNodes = layerElem.namedItem( QStringLiteral( "edittypes" ) ).childNodes(); QgsEditFormConfig formConfig = vectorLayer->editFormConfig(); @@ -242,30 +242,30 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle QDomNode editTypeNode = editTypeNodes.at( i ); QDomElement editTypeElement = editTypeNode.toElement(); - QString name = editTypeElement.attribute( "name" ); + QString name = editTypeElement.attribute( QStringLiteral( "name" ) ); int idx = vectorLayer->fields().lookupField( name ); if ( idx == -1 ) continue; - QString ewv2Type = editTypeElement.attribute( "widgetv2type" ); + QString ewv2Type = editTypeElement.attribute( QStringLiteral( "widgetv2type" ) ); QgsEditorWidgetConfig cfg; if ( mWidgetFactories.contains( ewv2Type ) ) { formConfig.setWidgetType( name, ewv2Type ); - QDomElement ewv2CfgElem = editTypeElement.namedItem( "widgetv2config" ).toElement(); + QDomElement ewv2CfgElem = editTypeElement.namedItem( QStringLiteral( "widgetv2config" ) ).toElement(); if ( !ewv2CfgElem.isNull() ) { cfg = mWidgetFactories[ewv2Type]->readEditorConfig( ewv2CfgElem, vectorLayer, idx ); } - formConfig.setReadOnly( idx, ewv2CfgElem.attribute( "fieldEditable", "1" ) != "1" ); - formConfig.setLabelOnTop( idx, ewv2CfgElem.attribute( "labelOnTop", "0" ) == "1" ); - formConfig.setNotNull( idx, ewv2CfgElem.attribute( "notNull", "0" ) == "1" ); - formConfig.setConstraintExpression( idx, ewv2CfgElem.attribute( "constraint", QString() ) ); - formConfig.setContraintDescription( idx, ewv2CfgElem.attribute( "constraintDescription", QString() ) ); + formConfig.setReadOnly( idx, ewv2CfgElem.attribute( QStringLiteral( "fieldEditable" ), QStringLiteral( "1" ) ) != QLatin1String( "1" ) ); + formConfig.setLabelOnTop( idx, ewv2CfgElem.attribute( QStringLiteral( "labelOnTop" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); + formConfig.setNotNull( idx, ewv2CfgElem.attribute( QStringLiteral( "notNull" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); + formConfig.setConstraintExpression( idx, ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ) ); + formConfig.setContraintDescription( idx, ewv2CfgElem.attribute( QStringLiteral( "constraintDescription" ), QString() ) ); formConfig.setWidgetConfig( name, cfg ); } @@ -291,7 +291,7 @@ void QgsEditorWidgetRegistry::writeMapLayer( QgsMapLayer* mapLayer, QDomElement& return; } - QDomNode editTypesNode = doc.createElement( "edittypes" ); + QDomNode editTypesNode = doc.createElement( QStringLiteral( "edittypes" ) ); QgsFields fields = vectorLayer->fields(); for ( int idx = 0; idx < fields.count(); ++idx ) @@ -310,18 +310,18 @@ void QgsEditorWidgetRegistry::writeMapLayer( QgsMapLayer* mapLayer, QDomElement& } - QDomElement editTypeElement = doc.createElement( "edittype" ); - editTypeElement.setAttribute( "name", field.name() ); - editTypeElement.setAttribute( "widgetv2type", widgetType ); + QDomElement editTypeElement = doc.createElement( QStringLiteral( "edittype" ) ); + editTypeElement.setAttribute( QStringLiteral( "name" ), field.name() ); + editTypeElement.setAttribute( QStringLiteral( "widgetv2type" ), widgetType ); if ( mWidgetFactories.contains( widgetType ) ) { - QDomElement ewv2CfgElem = doc.createElement( "widgetv2config" ); - ewv2CfgElem.setAttribute( "fieldEditable", !vectorLayer->editFormConfig().readOnly( idx ) ); - ewv2CfgElem.setAttribute( "labelOnTop", vectorLayer->editFormConfig().labelOnTop( idx ) ); - ewv2CfgElem.setAttribute( "notNull", vectorLayer->editFormConfig().notNull( idx ) ); - ewv2CfgElem.setAttribute( "constraint", vectorLayer->editFormConfig().constraintExpression( idx ) ); - ewv2CfgElem.setAttribute( "constraintDescription", vectorLayer->editFormConfig().constraintDescription( idx ) ); + QDomElement ewv2CfgElem = doc.createElement( QStringLiteral( "widgetv2config" ) ); + ewv2CfgElem.setAttribute( QStringLiteral( "fieldEditable" ), !vectorLayer->editFormConfig().readOnly( idx ) ); + ewv2CfgElem.setAttribute( QStringLiteral( "labelOnTop" ), vectorLayer->editFormConfig().labelOnTop( idx ) ); + ewv2CfgElem.setAttribute( QStringLiteral( "notNull" ), vectorLayer->editFormConfig().notNull( idx ) ); + ewv2CfgElem.setAttribute( QStringLiteral( "constraint" ), vectorLayer->editFormConfig().constraintExpression( idx ) ); + ewv2CfgElem.setAttribute( QStringLiteral( "constraintDescription" ), vectorLayer->editFormConfig().constraintDescription( idx ) ); mWidgetFactories[widgetType]->writeConfig( vectorLayer->editFormConfig().widgetConfig( field.name() ), ewv2CfgElem, doc, vectorLayer, idx ); diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 4eb28e16ced2..5f725bb74fc5 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -102,7 +102,7 @@ void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid if ( constraintValid ) widget()->setStyleSheet( QString() ); else - widget()->setStyleSheet( "background-color: #dd7777;" ); + widget()->setStyleSheet( QStringLiteral( "background-color: #dd7777;" ) ); } void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) @@ -146,8 +146,8 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) } else { - description = "NotNull"; - expression = "NotNull"; + description = QStringLiteral( "NotNull" ); + expression = QStringLiteral( "NotNull" ); } mValidConstraint = mValidConstraint && !value.isNull(); diff --git a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp index fec5a7bf71bb..774dee5da60e 100644 --- a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.cpp @@ -103,6 +103,6 @@ void QgsSearchWidgetWrapper::setFeature( const QgsFeature& feature ) void QgsSearchWidgetWrapper::clearExpression() { - mExpression = QString( "TRUE" ); + mExpression = QStringLiteral( "TRUE" ); } diff --git a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h index 1b7b58b63757..42e5e7f1cca1 100644 --- a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h @@ -125,7 +125,7 @@ class GUI_EXPORT QgsSearchWidgetWrapper : public QgsWidgetWrapper * @note added in QGIS 2.16 */ // TODO QGIS 3.0 - make pure virtual - virtual QString createExpression( FilterFlags flags ) const { Q_UNUSED( flags ); return "TRUE"; } + virtual QString createExpression( FilterFlags flags ) const { Q_UNUSED( flags ); return QStringLiteral( "TRUE" ); } public slots: diff --git a/src/gui/editorwidgets/qgscheckboxconfigdlg.cpp b/src/gui/editorwidgets/qgscheckboxconfigdlg.cpp index 521065fbda53..26b25b09256c 100644 --- a/src/gui/editorwidgets/qgscheckboxconfigdlg.cpp +++ b/src/gui/editorwidgets/qgscheckboxconfigdlg.cpp @@ -28,14 +28,14 @@ QgsEditorWidgetConfig QgsCheckBoxConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "CheckedState", leCheckedState->text() ); - cfg.insert( "UncheckedState", leUncheckedState->text() ); + cfg.insert( QStringLiteral( "CheckedState" ), leCheckedState->text() ); + cfg.insert( QStringLiteral( "UncheckedState" ), leUncheckedState->text() ); return cfg; } void QgsCheckBoxConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - leCheckedState->setText( config.value( "CheckedState" ).toString() ); - leUncheckedState->setText( config.value( "UncheckedState" ).toString() ); + leCheckedState->setText( config.value( QStringLiteral( "CheckedState" ) ).toString() ); + leUncheckedState->setText( config.value( QStringLiteral( "UncheckedState" ) ).toString() ); } diff --git a/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp index 2ffa882f5279..9a2eeb0b16bf 100644 --- a/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgscheckboxsearchwidgetwrapper.cpp @@ -44,7 +44,7 @@ QVariant QgsCheckboxSearchWidgetWrapper::value() const QVariant v; if ( mCheckBox ) - v = mCheckBox->isChecked() ? config( "CheckedState" ) : config( "UncheckedState" ); + v = mCheckBox->isChecked() ? config( QStringLiteral( "CheckedState" ) ) : config( QStringLiteral( "UncheckedState" ) ); return v; } @@ -129,9 +129,9 @@ void QgsCheckboxSearchWidgetWrapper::setExpression( QString exp ) { QString fieldName = layer()->fields().at( mFieldIdx ).name(); - QString str = QString( "%1 = '%3'" ) + QString str = QStringLiteral( "%1 = '%3'" ) .arg( QgsExpression::quotedColumnRef( fieldName ), - exp.replace( '\'', "''" ) + exp.replace( '\'', QLatin1String( "''" ) ) ); mExpression = str; } diff --git a/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp b/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp index 9be31bfef551..4c28516fa147 100644 --- a/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp @@ -45,8 +45,8 @@ QgsEditorWidgetConfig QgsCheckboxWidgetFactory::readConfig( const QDomElement& c QgsEditorWidgetConfig cfg; - cfg.insert( "CheckedState", configElement.attribute( "CheckedState" ) ); - cfg.insert( "UncheckedState", configElement.attribute( "UncheckedState" ) ); + cfg.insert( QStringLiteral( "CheckedState" ), configElement.attribute( QStringLiteral( "CheckedState" ) ) ); + cfg.insert( QStringLiteral( "UncheckedState" ), configElement.attribute( QStringLiteral( "UncheckedState" ) ) ); return cfg; } @@ -57,8 +57,8 @@ void QgsCheckboxWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "CheckedState", config.value( "CheckedState", "1" ).toString() ); - configElement.setAttribute( "UncheckedState", config.value( "UncheckedState", "0" ).toString() ); + configElement.setAttribute( QStringLiteral( "CheckedState" ), config.value( QStringLiteral( "CheckedState" ), "1" ).toString() ); + configElement.setAttribute( QStringLiteral( "UncheckedState" ), config.value( QStringLiteral( "UncheckedState" ), "0" ).toString() ); } QHash<const char*, int> QgsCheckboxWidgetFactory::supportedWidgetTypes() diff --git a/src/gui/editorwidgets/qgscheckboxwidgetwrapper.cpp b/src/gui/editorwidgets/qgscheckboxwidgetwrapper.cpp index 322e18868b7a..a9ed4d7091bb 100644 --- a/src/gui/editorwidgets/qgscheckboxwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgscheckboxwidgetwrapper.cpp @@ -28,10 +28,10 @@ QVariant QgsCheckboxWidgetWrapper::value() const QVariant v; if ( mGroupBox ) - v = mGroupBox->isChecked() ? config( "CheckedState" ) : config( "UncheckedState" ); + v = mGroupBox->isChecked() ? config( QStringLiteral( "CheckedState" ) ) : config( QStringLiteral( "UncheckedState" ) ); if ( mCheckBox ) - v = mCheckBox->isChecked() ? config( "CheckedState" ) : config( "UncheckedState" ); + v = mCheckBox->isChecked() ? config( QStringLiteral( "CheckedState" ) ) : config( QStringLiteral( "UncheckedState" ) ); return v; @@ -68,7 +68,7 @@ bool QgsCheckboxWidgetWrapper::valid() const void QgsCheckboxWidgetWrapper::setValue( const QVariant& value ) { - bool state = ( value == config( "CheckedState" ) ); + bool state = ( value == config( QStringLiteral( "CheckedState" ) ) ); if ( mGroupBox ) { mGroupBox->setChecked( state ); diff --git a/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp b/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp index 1393160cd2d4..7b734edbba50 100644 --- a/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp @@ -50,7 +50,7 @@ QWidget* QgsColorWidgetWrapper::createWidget( QWidget* parent ) layout->setMargin( 0 ); layout->setContentsMargins( 0, 0, 0, 0 ); QgsColorButton* button = new QgsColorButton(); - button->setContext( QString( "editor" ) ); + button->setContext( QStringLiteral( "editor" ) ); layout->addWidget( button ); layout->addStretch(); container->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Minimum ); diff --git a/src/gui/editorwidgets/qgsdatetimeedit.cpp b/src/gui/editorwidgets/qgsdatetimeedit.cpp index 3d23252cdadc..264d4e2be6d7 100644 --- a/src/gui/editorwidgets/qgsdatetimeedit.cpp +++ b/src/gui/editorwidgets/qgsdatetimeedit.cpp @@ -31,18 +31,18 @@ QgsDateTimeEdit::QgsDateTimeEdit( QWidget *parent ) , mIsEmpty( false ) { mClearButton = new QToolButton( this ); - mClearButton->setIcon( QgsApplication::getThemeIcon( "/mIconClear.svg" ) ); + mClearButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconClear.svg" ) ) ); mClearButton->setCursor( Qt::ArrowCursor ); - mClearButton->setStyleSheet( "position: absolute; border: none; padding: 0px;" ); + mClearButton->setStyleSheet( QStringLiteral( "position: absolute; border: none; padding: 0px;" ) ); mClearButton->hide(); connect( mClearButton, SIGNAL( clicked() ), this, SLOT( clear() ) ); - mNullLabel = new QLineEdit( QSettings().value( "qgis/nullValue", "NULL" ).toString(), this ); + mNullLabel = new QLineEdit( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(), this ); mNullLabel->setReadOnly( true ); - mNullLabel->setStyleSheet( "position: absolute; border: none; font-style: italic; color: grey;" ); + mNullLabel->setStyleSheet( QStringLiteral( "position: absolute; border: none; font-style: italic; color: grey;" ) ); mNullLabel->hide(); - setStyleSheet( QString( ".QWidget, QLineEdit, QToolButton { padding-right: %1px; }" ).arg( mClearButton->sizeHint().width() + spinButtonWidth() + frameWidth() + 1 ) ); + setStyleSheet( QStringLiteral( ".QWidget, QLineEdit, QToolButton { padding-right: %1px; }" ).arg( mClearButton->sizeHint().width() + spinButtonWidth() + frameWidth() + 1 ) ); QSize msz = minimumSizeHint(); setMinimumSize( qMax( msz.width(), mClearButton->sizeHint().height() + frameWidth() * 2 + 2 ), diff --git a/src/gui/editorwidgets/qgsdatetimeeditconfig.cpp b/src/gui/editorwidgets/qgsdatetimeeditconfig.cpp index 492929ef8b59..996cfcd9fe35 100644 --- a/src/gui/editorwidgets/qgsdatetimeeditconfig.cpp +++ b/src/gui/editorwidgets/qgsdatetimeeditconfig.cpp @@ -111,10 +111,10 @@ QgsEditorWidgetConfig QgsDateTimeEditConfig::config() { QgsEditorWidgetConfig myConfig; - myConfig.insert( "field_format", mFieldFormatEdit->text() ); - myConfig.insert( "display_format", mDisplayFormatEdit->text() ); - myConfig.insert( "calendar_popup", mCalendarPopupCheckBox->isChecked() ); - myConfig.insert( "allow_null", mAllowNullCheckBox->isChecked() ); + myConfig.insert( QStringLiteral( "field_format" ), mFieldFormatEdit->text() ); + myConfig.insert( QStringLiteral( "display_format" ), mDisplayFormatEdit->text() ); + myConfig.insert( QStringLiteral( "calendar_popup" ), mCalendarPopupCheckBox->isChecked() ); + myConfig.insert( QStringLiteral( "allow_null" ), mAllowNullCheckBox->isChecked() ); return myConfig; } @@ -139,7 +139,7 @@ QString QgsDateTimeEditConfig::defaultFormat( const QVariant::Type type ) void QgsDateTimeEditConfig::setConfig( const QgsEditorWidgetConfig &config ) { const QgsField fieldDef = layer()->fields().at( field() ); - const QString fieldFormat = config.value( "field_format", defaultFormat( fieldDef.type() ) ).toString(); + const QString fieldFormat = config.value( QStringLiteral( "field_format" ), defaultFormat( fieldDef.type() ) ).toString(); mFieldFormatEdit->setText( fieldFormat ); if ( fieldFormat == QGSDATETIMEEDIT_DATEFORMAT ) @@ -151,7 +151,7 @@ void QgsDateTimeEditConfig::setConfig( const QgsEditorWidgetConfig &config ) else mFieldFormatComboBox->setCurrentIndex( 3 ); - QString displayFormat = config.value( "display_format", defaultFormat( fieldDef.type() ) ).toString(); + QString displayFormat = config.value( QStringLiteral( "display_format" ), defaultFormat( fieldDef.type() ) ).toString(); mDisplayFormatEdit->setText( displayFormat ); if ( displayFormat == mFieldFormatEdit->text() ) { @@ -162,6 +162,6 @@ void QgsDateTimeEditConfig::setConfig( const QgsEditorWidgetConfig &config ) mDisplayFormatComboBox->setCurrentIndex( 1 ); } - mCalendarPopupCheckBox->setChecked( config.value( "calendar_popup" , false ).toBool() ); - mAllowNullCheckBox->setChecked( config.value( "allow_null", true ).toBool() ); + mCalendarPopupCheckBox->setChecked( config.value( QStringLiteral( "calendar_popup" ) , false ).toBool() ); + mAllowNullCheckBox->setChecked( config.value( QStringLiteral( "allow_null" ), true ).toBool() ); } diff --git a/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp b/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp index 7cbabedb2b28..6c581c4d07b6 100644 --- a/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp +++ b/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp @@ -47,10 +47,10 @@ QgsEditorWidgetConfig QgsDateTimeEditFactory::readConfig( const QDomElement& con Q_UNUSED( fieldIdx ); QgsEditorWidgetConfig cfg; - cfg.insert( "field_format", configElement.attribute( "field_format" ) ); - cfg.insert( "display_format", configElement.attribute( "display_format" ) ); - cfg.insert( "calendar_popup", configElement.attribute( "calendar_popup" ) == "1" ); - cfg.insert( "allow_null", configElement.attribute( "allow_null" ) == "1" ); + cfg.insert( QStringLiteral( "field_format" ), configElement.attribute( QStringLiteral( "field_format" ) ) ); + cfg.insert( QStringLiteral( "display_format" ), configElement.attribute( QStringLiteral( "display_format" ) ) ); + cfg.insert( QStringLiteral( "calendar_popup" ), configElement.attribute( QStringLiteral( "calendar_popup" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "allow_null" ), configElement.attribute( QStringLiteral( "allow_null" ) ) == QLatin1String( "1" ) ); return cfg; } @@ -61,10 +61,10 @@ void QgsDateTimeEditFactory::writeConfig( const QgsEditorWidgetConfig& config, Q Q_UNUSED( layer ); Q_UNUSED( fieldIdx ); - configElement.setAttribute( "field_format", config["field_format"].toString() ); - configElement.setAttribute( "display_format", config["display_format"].toString() ); - configElement.setAttribute( "calendar_popup", config["calendar_popup"].toBool() ); - configElement.setAttribute( "allow_null", config["allow_null"].toBool() ); + configElement.setAttribute( QStringLiteral( "field_format" ), config[QStringLiteral( "field_format" )].toString() ); + configElement.setAttribute( QStringLiteral( "display_format" ), config[QStringLiteral( "display_format" )].toString() ); + configElement.setAttribute( QStringLiteral( "calendar_popup" ), config[QStringLiteral( "calendar_popup" )].toBool() ); + configElement.setAttribute( QStringLiteral( "allow_null" ), config[QStringLiteral( "allow_null" )].toBool() ); } QString QgsDateTimeEditFactory::representValue( QgsVectorLayer* vl, int fieldIdx, const QgsEditorWidgetConfig& config, const QVariant& cache, const QVariant& value ) const @@ -78,12 +78,12 @@ QString QgsDateTimeEditFactory::representValue( QgsVectorLayer* vl, int fieldIdx if ( value.isNull() ) { QSettings settings; - return settings.value( "qgis/nullValue", "NULL" ).toString(); + return settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } const QgsField field = vl->fields().at( fieldIdx ); - const QString displayFormat = config.value( "display_format", QgsDateTimeEditConfig::defaultFormat( field.type() ) ).toString(); - const QString fieldFormat = config.value( "field_format", QgsDateTimeEditConfig::defaultFormat( field.type() ) ).toString(); + const QString displayFormat = config.value( QStringLiteral( "display_format" ), QgsDateTimeEditConfig::defaultFormat( field.type() ) ).toString(); + const QString fieldFormat = config.value( QStringLiteral( "field_format" ), QgsDateTimeEditConfig::defaultFormat( field.type() ) ).toString(); QDateTime date = QDateTime::fromString( value.toString(), fieldFormat ); @@ -121,7 +121,7 @@ unsigned int QgsDateTimeEditFactory::fieldScore( const QgsVectorLayer* vl, int f const QgsField field = vl->fields().field( fieldIdx ); const QVariant::Type type = field.type(); const QgsEditorWidgetConfig config = vl->editFormConfig().widgetConfig( field.name() ); - if ( type == QVariant::DateTime || type == QVariant::Date || type == QVariant::Time || config.contains( "field_format" ) ) + if ( type == QVariant::DateTime || type == QVariant::Date || type == QVariant::Time || config.contains( QStringLiteral( "field_format" ) ) ) { return 20; } diff --git a/src/gui/editorwidgets/qgsdatetimeeditwrapper.cpp b/src/gui/editorwidgets/qgsdatetimeeditwrapper.cpp index 536bfaf4cd99..d7737ada3caf 100644 --- a/src/gui/editorwidgets/qgsdatetimeeditwrapper.cpp +++ b/src/gui/editorwidgets/qgsdatetimeeditwrapper.cpp @@ -59,14 +59,14 @@ void QgsDateTimeEditWrapper::initWidget( QWidget *editor ) if ( !mQDateTimeEdit ) { QgsDebugMsg( "Date/time edit widget could not be initialized because provided widget is not a QDateTimeEdit." ); - QgsMessageLog::logMessage( "Date/time edit widget could not be initialized because provided widget is not a QDateTimeEdit.", "UI forms", QgsMessageLog::WARNING ); + QgsMessageLog::logMessage( QStringLiteral( "Date/time edit widget could not be initialized because provided widget is not a QDateTimeEdit." ), QStringLiteral( "UI forms" ), QgsMessageLog::WARNING ); return; } - const QString displayFormat = config( "display_format", QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); + const QString displayFormat = config( QStringLiteral( "display_format" ), QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); mQDateTimeEdit->setDisplayFormat( displayFormat ); - const bool calendar = config( "calendar_popup", false ).toBool(); + const bool calendar = config( QStringLiteral( "calendar_popup" ), false ).toBool(); mQDateTimeEdit->setCalendarPopup( calendar ); if ( calendar && mQDateTimeEdit->calendarWidget() ) { @@ -76,7 +76,7 @@ void QgsDateTimeEditWrapper::initWidget( QWidget *editor ) mQDateTimeEdit->calendarWidget()->setDateTextFormat( QDate::currentDate(), todayFormat ); } - const bool allowNull = config( "allow_null", true ).toBool(); + const bool allowNull = config( QStringLiteral( "allow_null" ), true ).toBool(); if ( mQgsDateTimeEdit ) { mQgsDateTimeEdit->setAllowNull( allowNull ); @@ -85,7 +85,7 @@ void QgsDateTimeEditWrapper::initWidget( QWidget *editor ) { QgsMessageLog::instance()->logMessage( tr( "The usual date/time widget QDateTimeEdit cannot be configured to allow NULL values. " "For that the QGIS custom widget QgsDateTimeEdit needs to be used." ), - "field widgets" ); + QStringLiteral( "field widgets" ) ); } if ( mQgsDateTimeEdit ) @@ -111,7 +111,7 @@ void QgsDateTimeEditWrapper::showIndeterminateState() void QgsDateTimeEditWrapper::dateTimeChanged( const QDateTime& dateTime ) { - const QString fieldFormat = config( "field_format", QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); + const QString fieldFormat = config( QStringLiteral( "field_format" ), QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); emit valueChanged( dateTime.toString( fieldFormat ) ); } @@ -132,7 +132,7 @@ QVariant QgsDateTimeEditWrapper::value() const } } - const QString fieldFormat = config( "field_format", QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); + const QString fieldFormat = config( QStringLiteral( "field_format" ), QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); if ( mQgsDateTimeEdit ) { @@ -149,7 +149,7 @@ void QgsDateTimeEditWrapper::setValue( const QVariant &value ) if ( !mQDateTimeEdit ) return; - const QString fieldFormat = config( "field_format", QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); + const QString fieldFormat = config( QStringLiteral( "field_format" ), QgsDateTimeEditConfig::defaultFormat( field().type() ) ).toString(); const QDateTime date = field().type() == QVariant::DateTime ? value.toDateTime() : QDateTime::fromString( value.toString(), fieldFormat ); if ( mQgsDateTimeEdit ) diff --git a/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp index 1ad54ed818f7..b4e8e7a5fee1 100644 --- a/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsdatetimesearchwidgetwrapper.cpp @@ -46,7 +46,7 @@ QVariant QgsDateTimeSearchWidgetWrapper::value() const if ( ! mDateTimeEdit ) return QDateTime(); - const QString fieldFormat = config( "field_format", QgsDateTimeEditConfig::defaultFormat( layer()->fields().at( mFieldIdx ).type() ) ).toString(); + const QString fieldFormat = config( QStringLiteral( "field_format" ), QgsDateTimeEditConfig::defaultFormat( layer()->fields().at( mFieldIdx ).type() ) ).toString(); return mDateTimeEdit->dateTime().toString( fieldFormat ); } @@ -116,9 +116,9 @@ void QgsDateTimeSearchWidgetWrapper::setExpression( QString exp ) { QString fieldName = layer()->fields().at( mFieldIdx ).name(); - QString str = QString( "%1 = '%3'" ) + QString str = QStringLiteral( "%1 = '%3'" ) .arg( QgsExpression::quotedColumnRef( fieldName ), - exp.replace( '\'', "''" ) + exp.replace( '\'', QLatin1String( "''" ) ) ); mExpression = str; } @@ -152,10 +152,10 @@ void QgsDateTimeSearchWidgetWrapper::initWidget( QWidget* editor ) { mDateTimeEdit->setAllowNull( false ); - const QString displayFormat = config( "display_format", QgsDateTimeEditConfig::defaultFormat( layer()->fields().at( mFieldIdx ).type() ) ).toString(); + const QString displayFormat = config( QStringLiteral( "display_format" ), QgsDateTimeEditConfig::defaultFormat( layer()->fields().at( mFieldIdx ).type() ) ).toString(); mDateTimeEdit->setDisplayFormat( displayFormat ); - const bool calendar = config( "calendar_popup", false ).toBool(); + const bool calendar = config( QStringLiteral( "calendar_popup" ), false ).toBool(); mDateTimeEdit->setCalendarPopup( calendar ); if ( calendar && mDateTimeEdit->calendarWidget() ) { diff --git a/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp index 31970389d7b2..6920f89a3b3e 100644 --- a/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsdefaultsearchwidgetwrapper.cpp @@ -26,7 +26,7 @@ QgsDefaultSearchWidgetWrapper::QgsDefaultSearchWidgetWrapper( QgsVectorLayer* vl , mLineEdit( nullptr ) , mCheckbox( nullptr ) , mContainer( nullptr ) - , mCaseString( QString( "LIKE" ) ) + , mCaseString( QStringLiteral( "LIKE" ) ) { } @@ -39,11 +39,11 @@ void QgsDefaultSearchWidgetWrapper::setCaseString( int caseSensitiveCheckState ) { if ( caseSensitiveCheckState == Qt::Checked ) { - mCaseString = "LIKE"; + mCaseString = QStringLiteral( "LIKE" ); } else { - mCaseString = "ILIKE"; + mCaseString = QStringLiteral( "ILIKE" ); } // need to update also the line edit setExpression( mLineEdit->text() ); @@ -58,22 +58,22 @@ void QgsDefaultSearchWidgetWrapper::setExpression( QString exp ) bool numeric = ( fldType == QVariant::Int || fldType == QVariant::Double || fldType == QVariant::LongLong ); QSettings settings; - QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString(); + QString nullValue = settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); QString fieldName = layer()->fields().at( mFieldIdx ).name(); QString str; if ( exp == nullValue ) { - str = QString( "%1 IS NULL" ).arg( QgsExpression::quotedColumnRef( fieldName ) ); + str = QStringLiteral( "%1 IS NULL" ).arg( QgsExpression::quotedColumnRef( fieldName ) ); } else { - str = QString( "%1 %2 '%3'" ) + str = QStringLiteral( "%1 %2 '%3'" ) .arg( QgsExpression::quotedColumnRef( fieldName ), - numeric ? "=" : mCaseString, + numeric ? QStringLiteral( "=" ) : mCaseString, numeric ? - exp.replace( '\'', "''" ) + exp.replace( '\'', QLatin1String( "''" ) ) : - '%' + exp.replace( '\'', "''" ) + '%' ); // escape quotes + '%' + exp.replace( '\'', QLatin1String( "''" ) ) + '%' ); // escape quotes } mExpression = str; } @@ -211,9 +211,9 @@ QString QgsDefaultSearchWidgetWrapper::createExpression( QgsSearchWidgetWrapper: return fieldName + ( flags & EqualTo ? "=" : "<>" ) + QgsExpression::quotedString( mLineEdit->text() ); else - return QString( "lower(%1)" ).arg( fieldName ) + return QStringLiteral( "lower(%1)" ).arg( fieldName ) + ( flags & EqualTo ? "=" : "<>" ) + - QString( "lower(%1)" ).arg( QgsExpression::quotedString( mLineEdit->text() ) ); + QStringLiteral( "lower(%1)" ).arg( QgsExpression::quotedString( mLineEdit->text() ) ); } else if ( flags & Contains || flags & DoesNotContain ) { @@ -261,7 +261,7 @@ void QgsDefaultSearchWidgetWrapper::initWidget( QWidget* widget ) QVariant::Type fldType = layer()->fields().at( mFieldIdx ).type(); if ( fldType == QVariant::String ) { - mCheckbox = new QCheckBox( "Case sensitive" ); + mCheckbox = new QCheckBox( QStringLiteral( "Case sensitive" ) ); mContainer->layout()->addWidget( mCheckbox ); connect( mCheckbox, SIGNAL( stateChanged( int ) ), this, SLOT( setCaseString( int ) ) ); mCheckbox->setChecked( Qt::Unchecked ); @@ -271,7 +271,7 @@ void QgsDefaultSearchWidgetWrapper::initWidget( QWidget* widget ) connect( mLineEdit, SIGNAL( returnPressed() ), this, SLOT( filterChanged() ) ); connect( mLineEdit, SIGNAL( textEdited( QString ) ), this, SIGNAL( valueChanged() ) ); - mCaseString = "ILIKE"; + mCaseString = QStringLiteral( "ILIKE" ); } bool QgsDefaultSearchWidgetWrapper::valid() const diff --git a/src/gui/editorwidgets/qgsexternalresourceconfigdlg.cpp b/src/gui/editorwidgets/qgsexternalresourceconfigdlg.cpp index 1fa4eab24520..c53a7b311d07 100644 --- a/src/gui/editorwidgets/qgsexternalresourceconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsexternalresourceconfigdlg.cpp @@ -34,7 +34,7 @@ QgsExternalResourceConfigDlg::QgsExternalResourceConfigDlg( QgsVectorLayer* vl, QString defpath = QgsProject::instance()->fileName().isEmpty() ? QDir::homePath() : QgsProject::instance()->fileInfo().absolutePath(); - mRootPath->setPlaceholderText( QSettings().value( "/UI/lastExternalResourceWidgetDefaultPath", QDir::toNativeSeparators( QDir::cleanPath( defpath ) ) ).toString() ); + mRootPath->setPlaceholderText( QSettings().value( QStringLiteral( "/UI/lastExternalResourceWidgetDefaultPath" ), QDir::toNativeSeparators( QDir::cleanPath( defpath ) ) ).toString() ); // Add connection to button for choosing default path connect( mRootPathButton, SIGNAL( clicked() ), this, SLOT( chooseDefaultPath() ) ); @@ -82,7 +82,7 @@ void QgsExternalResourceConfigDlg::chooseDefaultPath() } else { - dir = QSettings().value( "/UI/lastExternalResourceWidgetDefaultPath", QDir::toNativeSeparators( QDir::cleanPath( QgsProject::instance()->fileInfo().absolutePath() ) ) ).toString(); + dir = QSettings().value( QStringLiteral( "/UI/lastExternalResourceWidgetDefaultPath" ), QDir::toNativeSeparators( QDir::cleanPath( QgsProject::instance()->fileInfo().absolutePath() ) ) ).toString(); } QString rootName = QFileDialog::getExistingDirectory( this, tr( "Select a directory" ), dir, QFileDialog::ShowDirsOnly ); @@ -126,44 +126,44 @@ QgsEditorWidgetConfig QgsExternalResourceConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "FileWidget", mFileWidgetGroupBox->isChecked() ); - cfg.insert( "FileWidgetButton", mFileWidgetButtonGroupBox->isChecked() ); - cfg.insert( "FileWidgetFilter", mFileWidgetFilterLineEdit->text() ); + cfg.insert( QStringLiteral( "FileWidget" ), mFileWidgetGroupBox->isChecked() ); + cfg.insert( QStringLiteral( "FileWidgetButton" ), mFileWidgetButtonGroupBox->isChecked() ); + cfg.insert( QStringLiteral( "FileWidgetFilter" ), mFileWidgetFilterLineEdit->text() ); if ( mUseLink->isChecked() ) { - cfg.insert( "UseLink", mUseLink->isChecked() ); + cfg.insert( QStringLiteral( "UseLink" ), mUseLink->isChecked() ); if ( mFullUrl->isChecked() ) - cfg.insert( "FullUrl", mFullUrl->isChecked() ); + cfg.insert( QStringLiteral( "FullUrl" ), mFullUrl->isChecked() ); } if ( !mRootPath->text().isEmpty() ) { - cfg.insert( "DefaultRoot", mRootPath->text() ); + cfg.insert( QStringLiteral( "DefaultRoot" ), mRootPath->text() ); } // Save Storage Mode - cfg.insert( "StorageMode", mStorageButtonGroup->checkedId() ); + cfg.insert( QStringLiteral( "StorageMode" ), mStorageButtonGroup->checkedId() ); // Save Relative Paths option if ( mRelativeGroupBox->isChecked() ) { - cfg.insert( "RelativeStorage", mRelativeButtonGroup->checkedId() ); + cfg.insert( QStringLiteral( "RelativeStorage" ), mRelativeButtonGroup->checkedId() ); } else { - cfg.insert( "RelativeStorage", ( int )QgsFileWidget::Absolute ); + cfg.insert( QStringLiteral( "RelativeStorage" ), ( int )QgsFileWidget::Absolute ); } if ( mDocumentViewerGroupBox->isChecked() ) { - cfg.insert( "DocumentViewer", mDocumentViewerContentComboBox->currentData().toInt() ); - cfg.insert( "DocumentViewerHeight", mDocumentViewerHeight->value() ); - cfg.insert( "DocumentViewerWidth", mDocumentViewerWidth->value() ); + cfg.insert( QStringLiteral( "DocumentViewer" ), mDocumentViewerContentComboBox->currentData().toInt() ); + cfg.insert( QStringLiteral( "DocumentViewerHeight" ), mDocumentViewerHeight->value() ); + cfg.insert( QStringLiteral( "DocumentViewerWidth" ), mDocumentViewerWidth->value() ); } else { - cfg.insert( "DocumentViewer", ( int )QgsExternalResourceWidget::NoContent ); + cfg.insert( QStringLiteral( "DocumentViewer" ), ( int )QgsExternalResourceWidget::NoContent ); } return cfg; @@ -172,35 +172,35 @@ QgsEditorWidgetConfig QgsExternalResourceConfigDlg::config() void QgsExternalResourceConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - if ( config.contains( "FileWidget" ) ) + if ( config.contains( QStringLiteral( "FileWidget" ) ) ) { - mFileWidgetGroupBox->setChecked( config.value( "FileWidget" ).toBool() ); + mFileWidgetGroupBox->setChecked( config.value( QStringLiteral( "FileWidget" ) ).toBool() ); } - if ( config.contains( "FileWidget" ) ) + if ( config.contains( QStringLiteral( "FileWidget" ) ) ) { - mFileWidgetButtonGroupBox->setChecked( config.value( "FileWidgetButton" ).toBool() ); + mFileWidgetButtonGroupBox->setChecked( config.value( QStringLiteral( "FileWidgetButton" ) ).toBool() ); } - if ( config.contains( "FileWidgetFilter" ) ) + if ( config.contains( QStringLiteral( "FileWidgetFilter" ) ) ) { - mFileWidgetFilterLineEdit->setText( config.value( "FileWidgetFilter" ).toString() ); + mFileWidgetFilterLineEdit->setText( config.value( QStringLiteral( "FileWidgetFilter" ) ).toString() ); } - if ( config.contains( "UseLink" ) ) + if ( config.contains( QStringLiteral( "UseLink" ) ) ) { - mUseLink->setChecked( config.value( "UseLink" ).toBool() ); - if ( config.contains( "FullUrl" ) ) + mUseLink->setChecked( config.value( QStringLiteral( "UseLink" ) ).toBool() ); + if ( config.contains( QStringLiteral( "FullUrl" ) ) ) mFullUrl->setChecked( true ); } - if ( config.contains( "DefaultRoot" ) ) + if ( config.contains( QStringLiteral( "DefaultRoot" ) ) ) { - mRootPath->setText( config.value( "DefaultRoot" ).toString() ); + mRootPath->setText( config.value( QStringLiteral( "DefaultRoot" ) ).toString() ); } // relative storage - if ( config.contains( "RelativeStorage" ) ) + if ( config.contains( QStringLiteral( "RelativeStorage" ) ) ) { - int relative = config.value( "RelativeStorage" ).toInt(); + int relative = config.value( QStringLiteral( "RelativeStorage" ) ).toInt(); if (( QgsFileWidget::RelativeStorage )relative == QgsFileWidget::Absolute ) { mRelativeGroupBox->setChecked( false ); @@ -213,29 +213,29 @@ void QgsExternalResourceConfigDlg::setConfig( const QgsEditorWidgetConfig& confi } // set storage mode - if ( config.contains( "StorageMode" ) ) + if ( config.contains( QStringLiteral( "StorageMode" ) ) ) { - int mode = config.value( "StorageMode" ).toInt(); + int mode = config.value( QStringLiteral( "StorageMode" ) ).toInt(); mStorageButtonGroup->button( mode )->setChecked( true ); } // Document viewer - if ( config.contains( "DocumentViewer" ) ) + if ( config.contains( QStringLiteral( "DocumentViewer" ) ) ) { - QgsExternalResourceWidget::DocumentViewerContent content = ( QgsExternalResourceWidget::DocumentViewerContent )config.value( "DocumentViewer" ).toInt(); + QgsExternalResourceWidget::DocumentViewerContent content = ( QgsExternalResourceWidget::DocumentViewerContent )config.value( QStringLiteral( "DocumentViewer" ) ).toInt(); mDocumentViewerGroupBox->setChecked( content != QgsExternalResourceWidget::NoContent ); int idx = mDocumentViewerContentComboBox->findData( content ); if ( idx >= 0 ) { mDocumentViewerContentComboBox->setCurrentIndex( idx ); } - if ( config.contains( "DocumentViewerHeight" ) ) + if ( config.contains( QStringLiteral( "DocumentViewerHeight" ) ) ) { - mDocumentViewerHeight->setValue( config.value( "DocumentViewerHeight" ).toInt() ); + mDocumentViewerHeight->setValue( config.value( QStringLiteral( "DocumentViewerHeight" ) ).toInt() ); } - if ( config.contains( "DocumentViewerWidth" ) ) + if ( config.contains( QStringLiteral( "DocumentViewerWidth" ) ) ) { - mDocumentViewerWidth->setValue( config.value( "DocumentViewerWidth" ).toInt() ); + mDocumentViewerWidth->setValue( config.value( QStringLiteral( "DocumentViewerWidth" ) ).toInt() ); } } } diff --git a/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp b/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp index e6de559ab497..3193578e915f 100644 --- a/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp @@ -40,36 +40,36 @@ void QgsExternalResourceWidgetFactory::writeConfig( const QgsEditorWidgetConfig& Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "FileWidget", config.value( "FileWidget", true ).toBool() ); - configElement.setAttribute( "FileWidgetButton", config.value( "FileWidgetButton", true ).toBool() ); + configElement.setAttribute( QStringLiteral( "FileWidget" ), config.value( QStringLiteral( "FileWidget" ), true ).toBool() ); + configElement.setAttribute( QStringLiteral( "FileWidgetButton" ), config.value( QStringLiteral( "FileWidgetButton" ), true ).toBool() ); // Non mandatory options are not saved into project file (to save some space). - if ( config.contains( "UseLink" ) ) - configElement.setAttribute( "UseLink", config.value( "UseLink" ).toBool() ); + if ( config.contains( QStringLiteral( "UseLink" ) ) ) + configElement.setAttribute( QStringLiteral( "UseLink" ), config.value( QStringLiteral( "UseLink" ) ).toBool() ); - if ( config.contains( "FullUrl" ) ) - configElement.setAttribute( "FullUrl", config.value( "FullUrl" ).toBool() ); + if ( config.contains( QStringLiteral( "FullUrl" ) ) ) + configElement.setAttribute( QStringLiteral( "FullUrl" ), config.value( QStringLiteral( "FullUrl" ) ).toBool() ); - if ( config.contains( "DefaultRoot" ) ) - configElement.setAttribute( "DefaultRoot", config.value( "DefaultRoot" ).toString() ); + if ( config.contains( QStringLiteral( "DefaultRoot" ) ) ) + configElement.setAttribute( QStringLiteral( "DefaultRoot" ), config.value( QStringLiteral( "DefaultRoot" ) ).toString() ); - if ( config.contains( "RelativeStorage" ) ) - configElement.setAttribute( "RelativeStorage" , config.value( "RelativeStorage" ).toString() ); + if ( config.contains( QStringLiteral( "RelativeStorage" ) ) ) + configElement.setAttribute( QStringLiteral( "RelativeStorage" ) , config.value( QStringLiteral( "RelativeStorage" ) ).toString() ); - if ( config.contains( "DocumentViewer" ) ) - configElement.setAttribute( "DocumentViewer", config.value( "DocumentViewer" ).toInt() ); + if ( config.contains( QStringLiteral( "DocumentViewer" ) ) ) + configElement.setAttribute( QStringLiteral( "DocumentViewer" ), config.value( QStringLiteral( "DocumentViewer" ) ).toInt() ); - if ( config.contains( "DocumentViewerWidth" ) ) - configElement.setAttribute( "DocumentViewerWidth", config.value( "DocumentViewerWidth" ).toInt() ); + if ( config.contains( QStringLiteral( "DocumentViewerWidth" ) ) ) + configElement.setAttribute( QStringLiteral( "DocumentViewerWidth" ), config.value( QStringLiteral( "DocumentViewerWidth" ) ).toInt() ); - if ( config.contains( "DocumentViewerHeight" ) ) - configElement.setAttribute( "DocumentViewerHeight", config.value( "DocumentViewerHeight" ).toInt() ); + if ( config.contains( QStringLiteral( "DocumentViewerHeight" ) ) ) + configElement.setAttribute( QStringLiteral( "DocumentViewerHeight" ), config.value( QStringLiteral( "DocumentViewerHeight" ) ).toInt() ); - if ( config.contains( "FileWidgetFilter" ) ) - configElement.setAttribute( "FileWidgetFilter", config.value( "FileWidgetFilter" ).toString() ); + if ( config.contains( QStringLiteral( "FileWidgetFilter" ) ) ) + configElement.setAttribute( QStringLiteral( "FileWidgetFilter" ), config.value( QStringLiteral( "FileWidgetFilter" ) ).toString() ); - configElement.setAttribute( "StorageMode", config.value( "StorageMode" ).toString() ); + configElement.setAttribute( QStringLiteral( "StorageMode" ), config.value( QStringLiteral( "StorageMode" ) ).toString() ); } QgsEditorWidgetConfig QgsExternalResourceWidgetFactory::readConfig( const QDomElement& configElement, QgsVectorLayer* layer, int fieldIdx ) @@ -79,42 +79,42 @@ QgsEditorWidgetConfig QgsExternalResourceWidgetFactory::readConfig( const QDomEl QgsEditorWidgetConfig cfg; - if ( configElement.hasAttribute( "FileWidgetButton" ) ) - cfg.insert( "FileWidgetButton", configElement.attribute( "FileWidgetButton" ) == "1" ); + if ( configElement.hasAttribute( QStringLiteral( "FileWidgetButton" ) ) ) + cfg.insert( QStringLiteral( "FileWidgetButton" ), configElement.attribute( QStringLiteral( "FileWidgetButton" ) ) == QLatin1String( "1" ) ); - if ( configElement.hasAttribute( "FileWidget" ) ) - cfg.insert( "FileWidget", configElement.attribute( "FileWidget" ) == "1" ); + if ( configElement.hasAttribute( QStringLiteral( "FileWidget" ) ) ) + cfg.insert( QStringLiteral( "FileWidget" ), configElement.attribute( QStringLiteral( "FileWidget" ) ) == QLatin1String( "1" ) ); - if ( configElement.hasAttribute( "UseLink" ) ) - cfg.insert( "UseLink", configElement.attribute( "UseLink" ) == "1" ); + if ( configElement.hasAttribute( QStringLiteral( "UseLink" ) ) ) + cfg.insert( QStringLiteral( "UseLink" ), configElement.attribute( QStringLiteral( "UseLink" ) ) == QLatin1String( "1" ) ); - if ( configElement.hasAttribute( "FullUrl" ) ) - cfg.insert( "FullUrl", configElement.attribute( "FullUrl" ) == "1" ); + if ( configElement.hasAttribute( QStringLiteral( "FullUrl" ) ) ) + cfg.insert( QStringLiteral( "FullUrl" ), configElement.attribute( QStringLiteral( "FullUrl" ) ) == QLatin1String( "1" ) ); - if ( configElement.hasAttribute( "DefaultRoot" ) ) - cfg.insert( "DefaultRoot", configElement.attribute( "DefaultRoot" ) ); + if ( configElement.hasAttribute( QStringLiteral( "DefaultRoot" ) ) ) + cfg.insert( QStringLiteral( "DefaultRoot" ), configElement.attribute( QStringLiteral( "DefaultRoot" ) ) ); - if ( configElement.hasAttribute( "RelativeStorage" ) ) + if ( configElement.hasAttribute( QStringLiteral( "RelativeStorage" ) ) ) { - if (( configElement.attribute( "RelativeStorage" ).toInt() == QgsFileWidget::RelativeDefaultPath && configElement.hasAttribute( "DefaultRoot" ) ) || - configElement.attribute( "RelativeStorage" ).toInt() == QgsFileWidget::RelativeProject ) - cfg.insert( "RelativeStorage" , configElement.attribute( "RelativeStorage" ).toInt() ); + if (( configElement.attribute( QStringLiteral( "RelativeStorage" ) ).toInt() == QgsFileWidget::RelativeDefaultPath && configElement.hasAttribute( QStringLiteral( "DefaultRoot" ) ) ) || + configElement.attribute( QStringLiteral( "RelativeStorage" ) ).toInt() == QgsFileWidget::RelativeProject ) + cfg.insert( QStringLiteral( "RelativeStorage" ) , configElement.attribute( QStringLiteral( "RelativeStorage" ) ).toInt() ); } - if ( configElement.hasAttribute( "DocumentViewer" ) ) - cfg.insert( "DocumentViewer", configElement.attribute( "DocumentViewer" ) ); + if ( configElement.hasAttribute( QStringLiteral( "DocumentViewer" ) ) ) + cfg.insert( QStringLiteral( "DocumentViewer" ), configElement.attribute( QStringLiteral( "DocumentViewer" ) ) ); - if ( configElement.hasAttribute( "DocumentViewerWidth" ) ) - cfg.insert( "DocumentViewerWidth", configElement.attribute( "DocumentViewerWidth" ) ); + if ( configElement.hasAttribute( QStringLiteral( "DocumentViewerWidth" ) ) ) + cfg.insert( QStringLiteral( "DocumentViewerWidth" ), configElement.attribute( QStringLiteral( "DocumentViewerWidth" ) ) ); - if ( configElement.hasAttribute( "DocumentViewerHeight" ) ) - cfg.insert( "DocumentViewerHeight", configElement.attribute( "DocumentViewerHeight" ) ); + if ( configElement.hasAttribute( QStringLiteral( "DocumentViewerHeight" ) ) ) + cfg.insert( QStringLiteral( "DocumentViewerHeight" ), configElement.attribute( QStringLiteral( "DocumentViewerHeight" ) ) ); - if ( configElement.hasAttribute( "FileWidgetFilter" ) ) - cfg.insert( "FileWidgetFilter", configElement.attribute( "FileWidgetFilter" ) ); + if ( configElement.hasAttribute( QStringLiteral( "FileWidgetFilter" ) ) ) + cfg.insert( QStringLiteral( "FileWidgetFilter" ), configElement.attribute( QStringLiteral( "FileWidgetFilter" ) ) ); - cfg.insert( "StorageMode", configElement.attribute( "StorageMode", "Files" ) ); + cfg.insert( QStringLiteral( "StorageMode" ), configElement.attribute( QStringLiteral( "StorageMode" ), QStringLiteral( "Files" ) ) ); return cfg; } diff --git a/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp b/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp index 37507ebd40b4..bd92f448a0f9 100644 --- a/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp @@ -41,7 +41,7 @@ QVariant QgsExternalResourceWidgetWrapper::value() const if ( mLineEdit ) { - if ( mLineEdit->text().isEmpty() || mLineEdit->text() == QSettings().value( "qgis/nullValue", "NULL" ).toString() ) + if ( mLineEdit->text().isEmpty() || mLineEdit->text() == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) { return QVariant( field().type() ); } @@ -93,7 +93,7 @@ void QgsExternalResourceWidgetWrapper::initWidget( QWidget* editor ) QgsFilterLineEdit* fle = qobject_cast<QgsFilterLineEdit*>( editor ); if ( fle ) { - fle->setNullValue( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + fle->setNullValue( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } } else @@ -102,41 +102,41 @@ void QgsExternalResourceWidgetWrapper::initWidget( QWidget* editor ) if ( mQgsWidget ) { mQgsWidget->fileWidget()->setStorageMode( QgsFileWidget::GetFile ); - if ( config().contains( "UseLink" ) ) + if ( config().contains( QStringLiteral( "UseLink" ) ) ) { - mQgsWidget->fileWidget()->setUseLink( config( "UseLink" ).toBool() ); + mQgsWidget->fileWidget()->setUseLink( config( QStringLiteral( "UseLink" ) ).toBool() ); } - if ( config().contains( "FullUrl" ) ) + if ( config().contains( QStringLiteral( "FullUrl" ) ) ) { - mQgsWidget->fileWidget()->setFullUrl( config( "FullUrl" ).toBool() ); + mQgsWidget->fileWidget()->setFullUrl( config( QStringLiteral( "FullUrl" ) ).toBool() ); } - if ( config().contains( "DefaultRoot" ) ) + if ( config().contains( QStringLiteral( "DefaultRoot" ) ) ) { - mQgsWidget->setDefaultRoot( config( "DefaultRoot" ).toString() ); + mQgsWidget->setDefaultRoot( config( QStringLiteral( "DefaultRoot" ) ).toString() ); } - if ( config().contains( "StorageMode" ) ) + if ( config().contains( QStringLiteral( "StorageMode" ) ) ) { - mQgsWidget->fileWidget()->setStorageMode(( QgsFileWidget::StorageMode )config( "StorageMode" ).toInt() ); + mQgsWidget->fileWidget()->setStorageMode(( QgsFileWidget::StorageMode )config( QStringLiteral( "StorageMode" ) ).toInt() ); } - if ( config().contains( "RelativeStorage" ) ) + if ( config().contains( QStringLiteral( "RelativeStorage" ) ) ) { - mQgsWidget->setRelativeStorage(( QgsFileWidget::RelativeStorage )config( "RelativeStorage" ).toInt() ); + mQgsWidget->setRelativeStorage(( QgsFileWidget::RelativeStorage )config( QStringLiteral( "RelativeStorage" ) ).toInt() ); } - if ( config().contains( "FileWidget" ) ) + if ( config().contains( QStringLiteral( "FileWidget" ) ) ) { - mQgsWidget->setFileWidgetVisible( config( "FileWidget" ).toBool() ); + mQgsWidget->setFileWidgetVisible( config( QStringLiteral( "FileWidget" ) ).toBool() ); } - if ( config().contains( "FileWidgetButton" ) ) + if ( config().contains( QStringLiteral( "FileWidgetButton" ) ) ) { - mQgsWidget->fileWidget()->setFileWidgetButtonVisible( config( "FileWidgetButton" ).toBool() ); + mQgsWidget->fileWidget()->setFileWidgetButtonVisible( config( QStringLiteral( "FileWidgetButton" ) ).toBool() ); } - if ( config().contains( "DocumentViewer" ) ) + if ( config().contains( QStringLiteral( "DocumentViewer" ) ) ) { - mQgsWidget->setDocumentViewerContent(( QgsExternalResourceWidget::DocumentViewerContent )config( "DocumentViewer" ).toInt() ); + mQgsWidget->setDocumentViewerContent(( QgsExternalResourceWidget::DocumentViewerContent )config( QStringLiteral( "DocumentViewer" ) ).toInt() ); } - if ( config().contains( "FileWidgetFilter" ) ) + if ( config().contains( QStringLiteral( "FileWidgetFilter" ) ) ) { - mQgsWidget->fileWidget()->setFilter( config( "FileWidgetFilter" ).toString() ); + mQgsWidget->fileWidget()->setFilter( config( QStringLiteral( "FileWidgetFilter" ) ).toString() ); } } @@ -151,7 +151,7 @@ void QgsExternalResourceWidgetWrapper::setValue( const QVariant& value ) { if ( value.isNull() ) { - mLineEdit->setText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mLineEdit->setText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } else { @@ -169,7 +169,7 @@ void QgsExternalResourceWidgetWrapper::setValue( const QVariant& value ) { if ( value.isNull() ) { - mQgsWidget->setDocumentPath( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mQgsWidget->setDocumentPath( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } else { @@ -195,6 +195,6 @@ void QgsExternalResourceWidgetWrapper::updateConstraintWidgetStatus( bool constr if ( constraintValid ) mLineEdit->setStyleSheet( QString() ); else - mLineEdit->setStyleSheet( "QgsFilterLineEdit { background-color: #dd7777; }" ); + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); } } diff --git a/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp b/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp index 4ffa43c42778..fd94432213ba 100644 --- a/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp @@ -36,7 +36,7 @@ QVariant QgsFileNameWidgetWrapper::value() const if ( mLineEdit ) { - if ( mLineEdit->text() == QSettings().value( "qgis/nullValue", "NULL" ).toString() ) + if ( mLineEdit->text() == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) value = QVariant( field().type() ); else value = mLineEdit->text(); @@ -103,7 +103,7 @@ void QgsFileNameWidgetWrapper::initWidget( QWidget* editor ) QgsFilterLineEdit* fle = qobject_cast<QgsFilterLineEdit*>( editor ); if ( fle ) { - fle->setNullValue( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + fle->setNullValue( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( valueChanged( QString ) ) ); @@ -115,7 +115,7 @@ void QgsFileNameWidgetWrapper::setValue( const QVariant& value ) if ( mLineEdit ) { if ( value.isNull() ) - mLineEdit->setText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mLineEdit->setText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); else mLineEdit->setText( value.toString() ); } @@ -160,7 +160,7 @@ void QgsFileNameWidgetWrapper::updateConstraintWidgetStatus( bool constraintVali mLineEdit->setStyleSheet( QString() ); else { - mLineEdit->setStyleSheet( "QgsFilterLineEdit { background-color: #dd7777; }" ); + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); } } } diff --git a/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp b/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp index 91dd023311af..b138130e408a 100644 --- a/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgskeyvaluewidgetfactory.cpp @@ -67,7 +67,7 @@ QString QgsKeyValueWidgetFactory::representValue( QgsVectorLayer* vl, int fieldI if ( value.isNull() ) { QSettings settings; - return settings.value( "qgis/nullValue", "NULL" ).toString(); + return settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } QString result; diff --git a/src/gui/editorwidgets/qgslistwidgetfactory.cpp b/src/gui/editorwidgets/qgslistwidgetfactory.cpp index d5a52883b636..87847de66dd8 100644 --- a/src/gui/editorwidgets/qgslistwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgslistwidgetfactory.cpp @@ -68,7 +68,7 @@ QString QgsListWidgetFactory::representValue( QgsVectorLayer* vl, int fieldIdx, if ( value.isNull() ) { QSettings settings; - return settings.value( "qgis/nullValue", "NULL" ).toString(); + return settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } QString result; diff --git a/src/gui/editorwidgets/qgsmultiedittoolbutton.cpp b/src/gui/editorwidgets/qgsmultiedittoolbutton.cpp index b201b9ab1726..b9aa301601c1 100644 --- a/src/gui/editorwidgets/qgsmultiedittoolbutton.cpp +++ b/src/gui/editorwidgets/qgsmultiedittoolbutton.cpp @@ -27,7 +27,7 @@ QgsMultiEditToolButton::QgsMultiEditToolButton( QWidget* parent ) // set default tool button icon properties setFixedSize( 22, 22 ); - setStyleSheet( QString( "QToolButton{ background: none; border: 1px solid rgba(0, 0, 0, 0%);} QToolButton:focus { border: 1px solid palette(highlight); }" ) ); + setStyleSheet( QStringLiteral( "QToolButton{ background: none; border: 1px solid rgba(0, 0, 0, 0%);} QToolButton:focus { border: 1px solid palette(highlight); }" ) ); setIconSize( QSize( 16, 16 ) ); setPopupMode( QToolButton::InstantPopup ); @@ -97,15 +97,15 @@ void QgsMultiEditToolButton::updateState() switch ( mState ) { case Default: - icon = QgsApplication::getThemeIcon( "/multieditSameValues.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/multieditSameValues.svg" ) ); tooltip = tr( "All features in selection have equal value for '%1'" ).arg( mField.name() ); break; case MixedValues: - icon = QgsApplication::getThemeIcon( "/multieditMixedValues.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/multieditMixedValues.svg" ) ); tooltip = tr( "Some features in selection have different values for '%1'" ).arg( mField.name() ); break; case Changed: - icon = QgsApplication::getThemeIcon( "/multieditChangedValues.svg" ); + icon = QgsApplication::getThemeIcon( QStringLiteral( "/multieditChangedValues.svg" ) ); tooltip = tr( "Values for '%1' have unsaved changes" ).arg( mField.name() ); break; } diff --git a/src/gui/editorwidgets/qgsphotoconfigdlg.cpp b/src/gui/editorwidgets/qgsphotoconfigdlg.cpp index 1899f790e378..812bfe6bf936 100644 --- a/src/gui/editorwidgets/qgsphotoconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsphotoconfigdlg.cpp @@ -27,14 +27,14 @@ QgsEditorWidgetConfig QgsPhotoConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "Height", sbWidgetHeight->value() ); - cfg.insert( "Width", sbWidgetWidth->value() ); + cfg.insert( QStringLiteral( "Height" ), sbWidgetHeight->value() ); + cfg.insert( QStringLiteral( "Width" ), sbWidgetWidth->value() ); return cfg; } void QgsPhotoConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - sbWidgetHeight->setValue( config.value( "Height", 0 ).toInt() ); - sbWidgetWidth->setValue( config.value( "Width", 0 ).toInt() ); + sbWidgetHeight->setValue( config.value( QStringLiteral( "Height" ), 0 ).toInt() ); + sbWidgetWidth->setValue( config.value( QStringLiteral( "Width" ), 0 ).toInt() ); } diff --git a/src/gui/editorwidgets/qgsphotowidgetfactory.cpp b/src/gui/editorwidgets/qgsphotowidgetfactory.cpp index b1357ef064ba..7fdb0840b8f3 100644 --- a/src/gui/editorwidgets/qgsphotowidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsphotowidgetfactory.cpp @@ -41,8 +41,8 @@ QgsEditorWidgetConfig QgsPhotoWidgetFactory::readConfig( const QDomElement& conf QgsEditorWidgetConfig cfg; - cfg.insert( "Height", configElement.attribute( "Height", 0 ).toInt() ); - cfg.insert( "Width", configElement.attribute( "Width", 0 ).toInt() ); + cfg.insert( QStringLiteral( "Height" ), configElement.attribute( QStringLiteral( "Height" ), 0 ).toInt() ); + cfg.insert( QStringLiteral( "Width" ), configElement.attribute( QStringLiteral( "Width" ), 0 ).toInt() ); return cfg; } @@ -53,6 +53,6 @@ void QgsPhotoWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, QD Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "Height", config.value( "Height", 0 ).toString() ); - configElement.setAttribute( "Width", config.value( "Width", 0 ).toString() ); + configElement.setAttribute( QStringLiteral( "Height" ), config.value( QStringLiteral( "Height" ), 0 ).toString() ); + configElement.setAttribute( QStringLiteral( "Width" ), config.value( QStringLiteral( "Width" ), 0 ).toString() ); } diff --git a/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp b/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp index cd009615c3a5..75232eb3322f 100644 --- a/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp @@ -84,7 +84,7 @@ void QgsPhotoWidgetWrapper::loadPixmap( const QString& fileName ) QPixmap pm( filePath ); if ( !pm.isNull() && mPhotoLabel ) { - QSize size( config( "Width" ).toInt(), config( "Height" ).toInt() ); + QSize size( config( QStringLiteral( "Width" ) ).toInt(), config( QStringLiteral( "Height" ) ).toInt() ); if ( size.width() == 0 && size.height() > 0 ) { size.setWidth( size.height() * pm.size().width() / pm.size().height() ); @@ -137,7 +137,7 @@ QVariant QgsPhotoWidgetWrapper::value() const if ( mLineEdit ) { - if ( mLineEdit->text() == QSettings().value( "qgis/nullValue", "NULL" ).toString() ) + if ( mLineEdit->text() == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) v = QVariant( QVariant::String ); else v = mLineEdit->text(); @@ -164,9 +164,9 @@ QWidget* QgsPhotoWidgetWrapper::createWidget( QWidget* parent ) QGridLayout* layout = new QGridLayout(); QgsFilterLineEdit* le = new QgsFilterLineEdit(); QgsPixmapLabel* label = new QgsPixmapLabel(); - label->setObjectName( "PhotoLabel" ); + label->setObjectName( QStringLiteral( "PhotoLabel" ) ); QPushButton* pb = new QPushButton( tr( "..." ) ); - pb->setObjectName( "FileChooserButton" ); + pb->setObjectName( QStringLiteral( "FileChooserButton" ) ); layout->addWidget( label, 0, 0, 1, 2 ); layout->addWidget( le, 1, 0 ); @@ -205,11 +205,11 @@ void QgsPhotoWidgetWrapper::initWidget( QWidget* editor ) mLineEdit = container->findChild<QLineEdit*>(); } - mButton = container->findChild<QPushButton*>( "FileChooserButton" ); + mButton = container->findChild<QPushButton*>( QStringLiteral( "FileChooserButton" ) ); if ( !mButton ) mButton = container->findChild<QPushButton*>(); - mPhotoLabel = container->findChild<QLabel*>( "PhotoLabel" ); + mPhotoLabel = container->findChild<QLabel*>( QStringLiteral( "PhotoLabel" ) ); if ( !mPhotoLabel ) mPhotoLabel = container->findChild<QLabel*>(); @@ -223,7 +223,7 @@ void QgsPhotoWidgetWrapper::initWidget( QWidget* editor ) QgsFilterLineEdit *fle = qobject_cast<QgsFilterLineEdit*>( mLineEdit ); if ( fle ) { - fle->setNullValue( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + fle->setNullValue( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( valueChanged( QString ) ) ); @@ -246,7 +246,7 @@ void QgsPhotoWidgetWrapper::setValue( const QVariant& value ) { if ( value.isNull() ) { - whileBlocking( mLineEdit )->setText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + whileBlocking( mLineEdit )->setText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); clearPicture(); } else @@ -275,7 +275,7 @@ void QgsPhotoWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) mLineEdit->setStyleSheet( QString() ); else { - mLineEdit->setStyleSheet( "QgsFilterLineEdit { background-color: #dd7777; }" ); + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); } } } diff --git a/src/gui/editorwidgets/qgsrangeconfigdlg.cpp b/src/gui/editorwidgets/qgsrangeconfigdlg.cpp index 10c640ae8c00..49c19f7a6a5e 100644 --- a/src/gui/editorwidgets/qgsrangeconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsrangeconfigdlg.cpp @@ -72,27 +72,27 @@ QgsEditorWidgetConfig QgsRangeConfigDlg::config() { case QVariant::Int: case QVariant::LongLong: - cfg.insert( "Min", minimumSpinBox->value() ); - cfg.insert( "Max", maximumSpinBox->value() ); - cfg.insert( "Step", stepSpinBox->value() ); + cfg.insert( QStringLiteral( "Min" ), minimumSpinBox->value() ); + cfg.insert( QStringLiteral( "Max" ), maximumSpinBox->value() ); + cfg.insert( QStringLiteral( "Step" ), stepSpinBox->value() ); break; case QVariant::Double: - cfg.insert( "Min", minimumDoubleSpinBox->value() ); - cfg.insert( "Max", maximumDoubleSpinBox->value() ); - cfg.insert( "Step", stepDoubleSpinBox->value() ); + cfg.insert( QStringLiteral( "Min" ), minimumDoubleSpinBox->value() ); + cfg.insert( QStringLiteral( "Max" ), maximumDoubleSpinBox->value() ); + cfg.insert( QStringLiteral( "Step" ), stepDoubleSpinBox->value() ); break; default: break; } - cfg.insert( "Style", rangeWidget->currentData().toString() ); - cfg.insert( "AllowNull", allowNullCheckBox->isChecked() ); + cfg.insert( QStringLiteral( "Style" ), rangeWidget->currentData().toString() ); + cfg.insert( QStringLiteral( "AllowNull" ), allowNullCheckBox->isChecked() ); - if ( suffixLineEdit->text() != "" ) + if ( suffixLineEdit->text() != QLatin1String( "" ) ) { - cfg.insert( "Suffix", suffixLineEdit->text() ); + cfg.insert( QStringLiteral( "Suffix" ), suffixLineEdit->text() ); } return cfg; @@ -100,23 +100,23 @@ QgsEditorWidgetConfig QgsRangeConfigDlg::config() void QgsRangeConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - minimumDoubleSpinBox->setValue( config.value( "Min", -std::numeric_limits<double>::max() ).toDouble() ); - maximumDoubleSpinBox->setValue( config.value( "Max", std::numeric_limits<double>::max() ).toDouble() ); - stepDoubleSpinBox->setValue( config.value( "Step", 1.0 ).toDouble() ); + minimumDoubleSpinBox->setValue( config.value( QStringLiteral( "Min" ), -std::numeric_limits<double>::max() ).toDouble() ); + maximumDoubleSpinBox->setValue( config.value( QStringLiteral( "Max" ), std::numeric_limits<double>::max() ).toDouble() ); + stepDoubleSpinBox->setValue( config.value( QStringLiteral( "Step" ), 1.0 ).toDouble() ); - minimumSpinBox->setValue( config.value( "Min", std::numeric_limits<int>::min() ).toInt() ); - maximumSpinBox->setValue( config.value( "Max", std::numeric_limits<int>::max() ).toInt() ); - stepSpinBox->setValue( config.value( "Step", 1 ).toInt() ); + minimumSpinBox->setValue( config.value( QStringLiteral( "Min" ), std::numeric_limits<int>::min() ).toInt() ); + maximumSpinBox->setValue( config.value( QStringLiteral( "Max" ), std::numeric_limits<int>::max() ).toInt() ); + stepSpinBox->setValue( config.value( QStringLiteral( "Step" ), 1 ).toInt() ); - rangeWidget->setCurrentIndex( rangeWidget->findData( config.value( "Style", "SpinBox" ) ) ); + rangeWidget->setCurrentIndex( rangeWidget->findData( config.value( QStringLiteral( "Style" ), "SpinBox" ) ) ); - suffixLineEdit->setText( config.value( "Suffix" ).toString() ); + suffixLineEdit->setText( config.value( QStringLiteral( "Suffix" ) ).toString() ); - allowNullCheckBox->setChecked( config.value( "AllowNull", true ).toBool() ); + allowNullCheckBox->setChecked( config.value( QStringLiteral( "AllowNull" ), true ).toBool() ); } void QgsRangeConfigDlg::rangeWidgetChanged( int index ) { QString style = rangeWidget->itemData( index ).toString(); - allowNullCheckBox->setEnabled( style == "SpinBox" ); + allowNullCheckBox->setEnabled( style == QLatin1String( "SpinBox" ) ); } diff --git a/src/gui/editorwidgets/qgsrangewidgetfactory.cpp b/src/gui/editorwidgets/qgsrangewidgetfactory.cpp index 31ccdecccb7e..dce3b3b471ce 100644 --- a/src/gui/editorwidgets/qgsrangewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsrangewidgetfactory.cpp @@ -40,15 +40,15 @@ QgsEditorWidgetConfig QgsRangeWidgetFactory::readConfig( const QDomElement& conf Q_UNUSED( fieldIdx ); QgsEditorWidgetConfig cfg; - cfg.insert( "Style", configElement.attribute( "Style" ) ); - cfg.insert( "Min", configElement.attribute( "Min" ) ); - cfg.insert( "Max", configElement.attribute( "Max" ) ); - cfg.insert( "Step", configElement.attribute( "Step" ) ); - cfg.insert( "AllowNull", configElement.attribute( "AllowNull" ) == "1" ); + cfg.insert( QStringLiteral( "Style" ), configElement.attribute( QStringLiteral( "Style" ) ) ); + cfg.insert( QStringLiteral( "Min" ), configElement.attribute( QStringLiteral( "Min" ) ) ); + cfg.insert( QStringLiteral( "Max" ), configElement.attribute( QStringLiteral( "Max" ) ) ); + cfg.insert( QStringLiteral( "Step" ), configElement.attribute( QStringLiteral( "Step" ) ) ); + cfg.insert( QStringLiteral( "AllowNull" ), configElement.attribute( QStringLiteral( "AllowNull" ) ) == QLatin1String( "1" ) ); - if ( configElement.hasAttribute( "Suffix" ) ) + if ( configElement.hasAttribute( QStringLiteral( "Suffix" ) ) ) { - cfg.insert( "Suffix", configElement.attribute( "Suffix" ) ); + cfg.insert( QStringLiteral( "Suffix" ), configElement.attribute( QStringLiteral( "Suffix" ) ) ); } return cfg; @@ -60,14 +60,14 @@ void QgsRangeWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, QD Q_UNUSED( layer ); Q_UNUSED( fieldIdx ); - configElement.setAttribute( "Style", config["Style"].toString() ); - configElement.setAttribute( "Min", config["Min"].toString() ); - configElement.setAttribute( "Max", config["Max"].toString() ); - configElement.setAttribute( "Step", config["Step"].toString() ); - configElement.setAttribute( "AllowNull", config["AllowNull"].toBool() ); - if ( config.contains( "Suffix" ) ) + configElement.setAttribute( QStringLiteral( "Style" ), config[QStringLiteral( "Style" )].toString() ); + configElement.setAttribute( QStringLiteral( "Min" ), config[QStringLiteral( "Min" )].toString() ); + configElement.setAttribute( QStringLiteral( "Max" ), config[QStringLiteral( "Max" )].toString() ); + configElement.setAttribute( QStringLiteral( "Step" ), config[QStringLiteral( "Step" )].toString() ); + configElement.setAttribute( QStringLiteral( "AllowNull" ), config[QStringLiteral( "AllowNull" )].toBool() ); + if ( config.contains( QStringLiteral( "Suffix" ) ) ) { - configElement.setAttribute( "Suffix", config["Suffix"].toString() ); + configElement.setAttribute( QStringLiteral( "Suffix" ), config[QStringLiteral( "Suffix" )].toString() ); } } diff --git a/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp b/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp index 2c35997d23c4..14f0112e66b2 100644 --- a/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp @@ -37,11 +37,11 @@ QWidget* QgsRangeWidgetWrapper::createWidget( QWidget* parent ) { QWidget* editor = nullptr; - if ( config( "Style" ).toString() == "Dial" ) + if ( config( QStringLiteral( "Style" ) ).toString() == QLatin1String( "Dial" ) ) { editor = new QgsDial( parent ); } - else if ( config( "Style" ).toString() == "Slider" ) + else if ( config( QStringLiteral( "Style" ) ).toString() == QLatin1String( "Slider" ) ) { editor = new QgsSlider( Qt::Horizontal, parent ); } @@ -85,11 +85,11 @@ void QgsRangeWidgetWrapper::initWidget( QWidget* editor ) mQgsDial = qobject_cast<QgsDial*>( editor ); mQgsSlider = qobject_cast<QgsSlider*>( editor ); - bool allowNull = config( "AllowNull", true ).toBool(); + bool allowNull = config( QStringLiteral( "AllowNull" ), true ).toBool(); - QVariant min( config( "Min" ) ); - QVariant max( config( "Max" ) ); - QVariant step( config( "Step" ) ); + QVariant min( config( QStringLiteral( "Min" ) ) ); + QVariant max( config( QStringLiteral( "Max" ) ) ); + QVariant step( config( QStringLiteral( "Step" ) ) ); if ( mDoubleSpinBox ) { @@ -116,13 +116,13 @@ void QgsRangeWidgetWrapper::initWidget( QWidget* editor ) minval -= stepval; } mDoubleSpinBox->setValue( minval ); - mDoubleSpinBox->setSpecialValueText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mDoubleSpinBox->setSpecialValueText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } mDoubleSpinBox->setMinimum( min.isValid() ? min.toDouble() : std::numeric_limits<double>::min() ); mDoubleSpinBox->setMaximum( max.isValid() ? max.toDouble() : std::numeric_limits<double>::max() ); mDoubleSpinBox->setSingleStep( step.isValid() ? step.toDouble() : 1.0 ); - if ( config( "Suffix" ).isValid() ) - mDoubleSpinBox->setSuffix( config( "Suffix" ).toString() ); + if ( config( QStringLiteral( "Suffix" ) ).isValid() ) + mDoubleSpinBox->setSuffix( config( QStringLiteral( "Suffix" ) ).toString() ); connect( mDoubleSpinBox, SIGNAL( valueChanged( double ) ), this, SLOT( valueChanged( double ) ) ); } @@ -137,11 +137,11 @@ void QgsRangeWidgetWrapper::initWidget( QWidget* editor ) int stepval = step.toInt(); minval -= stepval; mIntSpinBox->setValue( minval ); - mIntSpinBox->setSpecialValueText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mIntSpinBox->setSpecialValueText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } setupIntEditor( min, max, step, mIntSpinBox, this ); - if ( config( "Suffix" ).isValid() ) - mIntSpinBox->setSuffix( config( "Suffix" ).toString() ); + if ( config( QStringLiteral( "Suffix" ) ).isValid() ) + mIntSpinBox->setSuffix( config( QStringLiteral( "Suffix" ) ).toString() ); } else { @@ -175,7 +175,7 @@ QVariant QgsRangeWidgetWrapper::value() const if ( mDoubleSpinBox ) { value = mDoubleSpinBox->value(); - if ( value == mDoubleSpinBox->minimum() && config( "AllowNull" ).toBool() ) + if ( value == mDoubleSpinBox->minimum() && config( QStringLiteral( "AllowNull" ) ).toBool() ) { value = QVariant( field().type() ); } @@ -183,7 +183,7 @@ QVariant QgsRangeWidgetWrapper::value() const else if ( mIntSpinBox ) { value = mIntSpinBox->value(); - if ( value == mIntSpinBox->minimum() && config( "AllowNull" ).toBool() ) + if ( value == mIntSpinBox->minimum() && config( QStringLiteral( "AllowNull" ) ).toBool() ) { value = QVariant( field().type() ); } @@ -212,7 +212,7 @@ void QgsRangeWidgetWrapper::setValue( const QVariant& value ) { if ( mDoubleSpinBox ) { - if ( value.isNull() && config( "AllowNull" ).toBool() ) + if ( value.isNull() && config( QStringLiteral( "AllowNull" ) ).toBool() ) { mDoubleSpinBox->setValue( mDoubleSpinBox->minimum() ); } @@ -224,7 +224,7 @@ void QgsRangeWidgetWrapper::setValue( const QVariant& value ) if ( mIntSpinBox ) { - if ( value.isNull() && config( "AllowNull" ).toBool() ) + if ( value.isNull() && config( QStringLiteral( "AllowNull" ) ).toBool() ) { mIntSpinBox->setValue( mIntSpinBox->minimum() ); } diff --git a/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp b/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp index fea6ad17b5cc..676c8537f168 100644 --- a/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsrelationreferenceconfigdlg.cpp @@ -34,7 +34,7 @@ QgsRelationReferenceConfigDlg::QgsRelationReferenceConfigDlg( QgsVectorLayer* vl Q_FOREACH ( const QgsRelation& relation, vl->referencingRelations( fieldIdx ) ) { - mComboRelation->addItem( QString( "%1 (%2)" ).arg( relation.id(), relation.referencedLayerId() ), relation.id() ); + mComboRelation->addItem( QStringLiteral( "%1 (%2)" ).arg( relation.id(), relation.referencedLayerId() ), relation.id() ); if ( relation.referencedLayer() ) { mExpressionWidget->setField( relation.referencedLayer()->displayExpression() ); @@ -56,21 +56,21 @@ QgsRelationReferenceConfigDlg::QgsRelationReferenceConfigDlg( QgsVectorLayer* vl void QgsRelationReferenceConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - mCbxAllowNull->setChecked( config.value( "AllowNULL", false ).toBool() ); - mCbxOrderByValue->setChecked( config.value( "OrderByValue", false ).toBool() ); - mCbxShowForm->setChecked( config.value( "ShowForm", true ).toBool() ); + mCbxAllowNull->setChecked( config.value( QStringLiteral( "AllowNULL" ), false ).toBool() ); + mCbxOrderByValue->setChecked( config.value( QStringLiteral( "OrderByValue" ), false ).toBool() ); + mCbxShowForm->setChecked( config.value( QStringLiteral( "ShowForm" ), true ).toBool() ); - if ( config.contains( "Relation" ) ) + if ( config.contains( QStringLiteral( "Relation" ) ) ) { - mComboRelation->setCurrentIndex( mComboRelation->findData( config.value( "Relation" ).toString() ) ); + mComboRelation->setCurrentIndex( mComboRelation->findData( config.value( QStringLiteral( "Relation" ) ).toString() ) ); relationChanged( mComboRelation->currentIndex() ); } - mCbxMapIdentification->setChecked( config.value( "MapIdentification", false ).toBool() ); - mCbxAllowAddFeatures->setChecked( config.value( "AllowAddFeatures", false ).toBool() ); - mCbxReadOnly->setChecked( config.value( "ReadOnly", false ).toBool() ); + mCbxMapIdentification->setChecked( config.value( QStringLiteral( "MapIdentification" ), false ).toBool() ); + mCbxAllowAddFeatures->setChecked( config.value( QStringLiteral( "AllowAddFeatures" ), false ).toBool() ); + mCbxReadOnly->setChecked( config.value( QStringLiteral( "ReadOnly" ), false ).toBool() ); - if ( config.contains( "FilterFields" ) ) + if ( config.contains( QStringLiteral( "FilterFields" ) ) ) { mFilterGroupBox->setChecked( true ); Q_FOREACH ( const QString& fld, config.value( "FilterFields" ).toStringList() ) @@ -78,7 +78,7 @@ void QgsRelationReferenceConfigDlg::setConfig( const QgsEditorWidgetConfig& conf addFilterField( fld ); } - mCbxChainFilters->setChecked( config.value( "ChainFilters" ).toBool() ); + mCbxChainFilters->setChecked( config.value( QStringLiteral( "ChainFilters" ) ).toBool() ); } } @@ -118,13 +118,13 @@ void QgsRelationReferenceConfigDlg::on_mRemoveFilterButton_clicked() QgsEditorWidgetConfig QgsRelationReferenceConfigDlg::config() { QgsEditorWidgetConfig myConfig; - myConfig.insert( "AllowNULL", mCbxAllowNull->isChecked() ); - myConfig.insert( "OrderByValue", mCbxOrderByValue->isChecked() ); - myConfig.insert( "ShowForm", mCbxShowForm->isChecked() ); - myConfig.insert( "MapIdentification", mCbxMapIdentification->isEnabled() && mCbxMapIdentification->isChecked() ); - myConfig.insert( "ReadOnly", mCbxReadOnly->isChecked() ); - myConfig.insert( "Relation", mComboRelation->currentData() ); - myConfig.insert( "AllowAddFeatures", mCbxAllowAddFeatures->isChecked() ); + myConfig.insert( QStringLiteral( "AllowNULL" ), mCbxAllowNull->isChecked() ); + myConfig.insert( QStringLiteral( "OrderByValue" ), mCbxOrderByValue->isChecked() ); + myConfig.insert( QStringLiteral( "ShowForm" ), mCbxShowForm->isChecked() ); + myConfig.insert( QStringLiteral( "MapIdentification" ), mCbxMapIdentification->isEnabled() && mCbxMapIdentification->isChecked() ); + myConfig.insert( QStringLiteral( "ReadOnly" ), mCbxReadOnly->isChecked() ); + myConfig.insert( QStringLiteral( "Relation" ), mComboRelation->currentData() ); + myConfig.insert( QStringLiteral( "AllowAddFeatures" ), mCbxAllowAddFeatures->isChecked() ); if ( mFilterGroupBox->isChecked() ) { @@ -134,9 +134,9 @@ QgsEditorWidgetConfig QgsRelationReferenceConfigDlg::config() { filterFields << mFilterFieldsList->item( i )->data( Qt::UserRole ).toString(); } - myConfig.insert( "FilterFields", filterFields ); + myConfig.insert( QStringLiteral( "FilterFields" ), filterFields ); - myConfig.insert( "ChainFilters", mCbxChainFilters->isChecked() ); + myConfig.insert( QStringLiteral( "ChainFilters" ), mCbxChainFilters->isChecked() ); } if ( mReferencedLayer ) diff --git a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp index ba0f93da3936..33675756f90c 100644 --- a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp @@ -53,28 +53,28 @@ QgsEditorWidgetConfig QgsRelationReferenceFactory::readConfig( const QDomElement Q_UNUSED( fieldIdx ); QgsEditorWidgetConfig cfg; - cfg.insert( "AllowNULL", configElement.attribute( "AllowNULL" ) == "1" ); - cfg.insert( "OrderByValue", configElement.attribute( "OrderByValue" ) == "1" ); - cfg.insert( "ShowForm", configElement.attribute( "ShowForm" ) == "1" ); - cfg.insert( "Relation", configElement.attribute( "Relation" ) ); - cfg.insert( "MapIdentification", configElement.attribute( "MapIdentification" ) == "1" ); - cfg.insert( "ReadOnly", configElement.attribute( "ReadOnly" ) == "1" ); - cfg.insert( "AllowAddFeatures", configElement.attribute( "AllowAddFeatures" ) == "1" ); - - QDomNode filterNode = configElement.elementsByTagName( "FilterFields" ).at( 0 ); + cfg.insert( QStringLiteral( "AllowNULL" ), configElement.attribute( QStringLiteral( "AllowNULL" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "OrderByValue" ), configElement.attribute( QStringLiteral( "OrderByValue" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "ShowForm" ), configElement.attribute( QStringLiteral( "ShowForm" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "Relation" ), configElement.attribute( QStringLiteral( "Relation" ) ) ); + cfg.insert( QStringLiteral( "MapIdentification" ), configElement.attribute( QStringLiteral( "MapIdentification" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "ReadOnly" ), configElement.attribute( QStringLiteral( "ReadOnly" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "AllowAddFeatures" ), configElement.attribute( QStringLiteral( "AllowAddFeatures" ) ) == QLatin1String( "1" ) ); + + QDomNode filterNode = configElement.elementsByTagName( QStringLiteral( "FilterFields" ) ).at( 0 ); if ( !filterNode.isNull() ) { QStringList filterFields; - QDomNodeList fieldNodes = filterNode.toElement().elementsByTagName( "field" ); + QDomNodeList fieldNodes = filterNode.toElement().elementsByTagName( QStringLiteral( "field" ) ); filterFields.reserve( fieldNodes.size() ); for ( int i = 0; i < fieldNodes.size(); i++ ) { QDomElement fieldElement = fieldNodes.at( i ).toElement(); - filterFields << fieldElement.attribute( "name" ); + filterFields << fieldElement.attribute( QStringLiteral( "name" ) ); } - cfg.insert( "FilterFields", filterFields ); + cfg.insert( QStringLiteral( "FilterFields" ), filterFields ); - cfg.insert( "ChainFilters", filterNode.toElement().attribute( "ChainFilters" ) == "1" ); + cfg.insert( QStringLiteral( "ChainFilters" ), filterNode.toElement().attribute( QStringLiteral( "ChainFilters" ) ) == QLatin1String( "1" ) ); } return cfg; } @@ -85,27 +85,27 @@ void QgsRelationReferenceFactory::writeConfig( const QgsEditorWidgetConfig& conf Q_UNUSED( layer ); Q_UNUSED( fieldIdx ); - configElement.setAttribute( "AllowNULL", config["AllowNULL"].toBool() ); - configElement.setAttribute( "OrderByValue", config["OrderByValue"].toBool() ); - configElement.setAttribute( "ShowForm", config["ShowForm"].toBool() ); - configElement.setAttribute( "Relation", config["Relation"].toString() ); - configElement.setAttribute( "MapIdentification", config["MapIdentification"].toBool() ); - configElement.setAttribute( "ReadOnly", config["ReadOnly"].toBool() ); - configElement.setAttribute( "AllowAddFeatures", config["AllowAddFeatures"].toBool() ); + configElement.setAttribute( QStringLiteral( "AllowNULL" ), config[QStringLiteral( "AllowNULL" )].toBool() ); + configElement.setAttribute( QStringLiteral( "OrderByValue" ), config[QStringLiteral( "OrderByValue" )].toBool() ); + configElement.setAttribute( QStringLiteral( "ShowForm" ), config[QStringLiteral( "ShowForm" )].toBool() ); + configElement.setAttribute( QStringLiteral( "Relation" ), config[QStringLiteral( "Relation" )].toString() ); + configElement.setAttribute( QStringLiteral( "MapIdentification" ), config[QStringLiteral( "MapIdentification" )].toBool() ); + configElement.setAttribute( QStringLiteral( "ReadOnly" ), config[QStringLiteral( "ReadOnly" )].toBool() ); + configElement.setAttribute( QStringLiteral( "AllowAddFeatures" ), config[QStringLiteral( "AllowAddFeatures" )].toBool() ); - if ( config.contains( "FilterFields" ) ) + if ( config.contains( QStringLiteral( "FilterFields" ) ) ) { - QDomElement filterFields = doc.createElement( "FilterFields" ); + QDomElement filterFields = doc.createElement( QStringLiteral( "FilterFields" ) ); Q_FOREACH ( const QString& field, config["FilterFields"].toStringList() ) { - QDomElement fieldElem = doc.createElement( "field" ); - fieldElem.setAttribute( "name", field ); + QDomElement fieldElem = doc.createElement( QStringLiteral( "field" ) ); + fieldElem.setAttribute( QStringLiteral( "name" ), field ); filterFields.appendChild( fieldElem ); } configElement.appendChild( filterFields ); - filterFields.setAttribute( "ChainFilters", config["ChainFilters"].toBool() ); + filterFields.setAttribute( QStringLiteral( "ChainFilters" ), config[QStringLiteral( "ChainFilters" )].toBool() ); } } @@ -121,12 +121,12 @@ QString QgsRelationReferenceFactory::representValue( QgsVectorLayer* vl, int fie Q_UNUSED( cache ); // Some sanity checks - if ( !config.contains( "Relation" ) ) + if ( !config.contains( QStringLiteral( "Relation" ) ) ) { QgsDebugMsg( "Missing Relation in configuration" ); return value.toString(); } - QgsRelation relation = QgsProject::instance()->relationManager()->relation( config["Relation"].toString() ); + QgsRelation relation = QgsProject::instance()->relationManager()->relation( config[QStringLiteral( "Relation" )].toString() ); if ( !relation.isValid() ) { QgsDebugMsg( "Invalid relation" ); diff --git a/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp index 154ab28226a8..13990231e7a2 100644 --- a/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencesearchwidgetwrapper.cpp @@ -138,7 +138,7 @@ void QgsRelationReferenceSearchWidgetWrapper::onValueChanged( const QVariant& va else { QSettings settings; - setExpression( value.isNull() ? settings.value( "qgis/nullValue", "NULL" ).toString() : value.toString() ); + setExpression( value.isNull() ? settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() : value.toString() ); emit valueChanged(); } emit expressionChanged( mExpression ); @@ -147,19 +147,19 @@ void QgsRelationReferenceSearchWidgetWrapper::onValueChanged( const QVariant& va void QgsRelationReferenceSearchWidgetWrapper::setExpression( QString exp ) { QSettings settings; - QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString(); + QString nullValue = settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); QString fieldName = layer()->fields().at( mFieldIdx ).name(); QString str; if ( exp == nullValue ) { - str = QString( "%1 IS NULL" ).arg( QgsExpression::quotedColumnRef( fieldName ) ); + str = QStringLiteral( "%1 IS NULL" ).arg( QgsExpression::quotedColumnRef( fieldName ) ); } else { - str = QString( "%1 = '%3'" ) + str = QStringLiteral( "%1 = '%3'" ) .arg( QgsExpression::quotedColumnRef( fieldName ), - exp.replace( '\'', "''" ) + exp.replace( '\'', QLatin1String( "''" ) ) ); } mExpression = str; @@ -180,18 +180,18 @@ void QgsRelationReferenceSearchWidgetWrapper::initWidget( QWidget* editor ) mWidget->setEmbedForm( false ); mWidget->setReadOnlySelector( false ); - mWidget->setAllowMapIdentification( config( "MapIdentification", false ).toBool() ); - mWidget->setOrderByValue( config( "OrderByValue", false ).toBool() ); + mWidget->setAllowMapIdentification( config( QStringLiteral( "MapIdentification" ), false ).toBool() ); + mWidget->setOrderByValue( config( QStringLiteral( "OrderByValue" ), false ).toBool() ); mWidget->setAllowAddFeatures( false ); mWidget->setOpenFormButtonVisible( false ); - if ( config( "FilterFields", QVariant() ).isValid() ) + if ( config( QStringLiteral( "FilterFields" ), QVariant() ).isValid() ) { - mWidget->setFilterFields( config( "FilterFields" ).toStringList() ); - mWidget->setChainFilters( config( "ChainFilters" ).toBool() ); + mWidget->setFilterFields( config( QStringLiteral( "FilterFields" ) ).toStringList() ); + mWidget->setChainFilters( config( QStringLiteral( "ChainFilters" ) ).toBool() ); } - QgsRelation relation = QgsProject::instance()->relationManager()->relation( config( "Relation" ).toString() ); + QgsRelation relation = QgsProject::instance()->relationManager()->relation( config( QStringLiteral( "Relation" ) ).toString() ); mWidget->setRelation( relation, false ); mWidget->showIndeterminateState(); diff --git a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp index 73874d6a17bc..38ff106597a0 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp @@ -51,7 +51,7 @@ QgsRelationReferenceWidget::QgsRelationReferenceWidget( QWidget* parent ) , mHighlight( nullptr ) , mMapTool( nullptr ) , mMessageBarItem( nullptr ) - , mRelationName( "" ) + , mRelationName( QLatin1String( "" ) ) , mReferencedAttributeForm( nullptr ) , mReferencedLayer( nullptr ) , mReferencingLayer( nullptr ) @@ -103,21 +103,21 @@ QgsRelationReferenceWidget::QgsRelationReferenceWidget( QWidget* parent ) // open form button mOpenFormButton = new QToolButton(); - mOpenFormButton->setIcon( QgsApplication::getThemeIcon( "/mActionPropertyItem.svg" ) ); + mOpenFormButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPropertyItem.svg" ) ) ); mOpenFormButton->setText( tr( "Open related feature form" ) ); editLayout->addWidget( mOpenFormButton ); mAddEntryButton = new QToolButton(); - mAddEntryButton->setIcon( QgsApplication::getThemeIcon( "/mActionAdd.svg" ) ); + mAddEntryButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAdd.svg" ) ) ); mAddEntryButton->setText( tr( "Add new entry" ) ); editLayout->addWidget( mAddEntryButton ); // highlight button mHighlightFeatureButton = new QToolButton( this ); mHighlightFeatureButton->setPopupMode( QToolButton::MenuButtonPopup ); - mHighlightFeatureAction = new QAction( QgsApplication::getThemeIcon( "/mActionHighlightFeature.svg" ), tr( "Highlight feature" ), this ); - mScaleHighlightFeatureAction = new QAction( QgsApplication::getThemeIcon( "/mActionScaleHighlightFeature.svg" ), tr( "Scale and highlight feature" ), this ); - mPanHighlightFeatureAction = new QAction( QgsApplication::getThemeIcon( "/mActionPanHighlightFeature.svg" ), tr( "Pan and highlight feature" ), this ); + mHighlightFeatureAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionHighlightFeature.svg" ) ), tr( "Highlight feature" ), this ); + mScaleHighlightFeatureAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionScaleHighlightFeature.svg" ) ), tr( "Scale and highlight feature" ), this ); + mPanHighlightFeatureAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPanHighlightFeature.svg" ) ), tr( "Pan and highlight feature" ), this ); mHighlightFeatureButton->addAction( mHighlightFeatureAction ); mHighlightFeatureButton->addAction( mScaleHighlightFeatureAction ); mHighlightFeatureButton->addAction( mPanHighlightFeatureAction ); @@ -126,14 +126,14 @@ QgsRelationReferenceWidget::QgsRelationReferenceWidget( QWidget* parent ) // map identification button mMapIdentificationButton = new QToolButton( this ); - mMapIdentificationButton->setIcon( QgsApplication::getThemeIcon( "/mActionMapIdentification.svg" ) ); + mMapIdentificationButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMapIdentification.svg" ) ) ); mMapIdentificationButton->setText( tr( "Select on map" ) ); mMapIdentificationButton->setCheckable( true ); editLayout->addWidget( mMapIdentificationButton ); // remove foreign key button mRemoveFKButton = new QToolButton( this ); - mRemoveFKButton->setIcon( QgsApplication::getThemeIcon( "/mActionRemove.svg" ) ); + mRemoveFKButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemove.svg" ) ) ); mRemoveFKButton->setText( tr( "No selection" ) ); editLayout->addWidget( mRemoveFKButton ); @@ -152,7 +152,7 @@ QgsRelationReferenceWidget::QgsRelationReferenceWidget( QWidget* parent ) mInvalidLabel->setWordWrap( true ); QFont font = mInvalidLabel->font(); font.setItalic( true ); - mInvalidLabel->setStyleSheet( "QLabel { color: red; } " ); + mInvalidLabel->setStyleSheet( QStringLiteral( "QLabel { color: red; } " ) ); mInvalidLabel->setFont( font ); mTopLayout->addWidget( mInvalidLabel ); @@ -300,10 +300,10 @@ void QgsRelationReferenceWidget::setForeignKey( const QVariant& value ) void QgsRelationReferenceWidget::deleteForeignKey() { - QVariant nullValue = QSettings().value( "qgis/nullValue", "NULL" ); + QVariant nullValue = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ); if ( mReadOnlySelector ) { - QString nullText = ""; + QString nullText = QLatin1String( "" ); if ( mAllowNull ) { nullText = tr( "%1 (no selection)" ).arg( nullValue.toString() ); @@ -475,7 +475,7 @@ void QgsRelationReferenceWidget::init() mFilterComboBoxes << cb; mReferencedLayer->uniqueValues( idx, uniqueValues ); cb->addItem( mReferencedLayer->attributeDisplayName( idx ) ); - QVariant nullValue = QSettings().value( "qgis/nullValue", "NULL" ); + QVariant nullValue = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ); cb->addItem( nullValue.toString(), QVariant( mReferencedLayer->fields().at( idx ).type() ) ); qSort( uniqueValues.begin(), uniqueValues.end(), qgsVariantLessThan ); @@ -494,7 +494,7 @@ void QgsRelationReferenceWidget::init() if ( mChainFilters ) { - QVariant nullValue = QSettings().value( "qgis/nullValue", "NULL" ); + QVariant nullValue = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ); QgsFeature ft; QgsFeatureIterator fit = layerCache->getFeatures(); @@ -542,7 +542,7 @@ void QgsRelationReferenceWidget::init() mComboBox->setModel( mFeatureListModel ); - QVariant nullValue = QSettings().value( "qgis/nullValue", "NULL" ); + QVariant nullValue = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ); if ( mChainFilters && mFeature.isValid() ) { @@ -637,10 +637,10 @@ void QgsRelationReferenceWidget::highlightFeature( QgsFeature f, CanvasExtent ca deleteHighlight(); mHighlight = new QgsHighlight( mCanvas, f, mReferencedLayer ); QSettings settings; - QColor color = QColor( settings.value( "/Map/highlight/color", Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); - int alpha = settings.value( "/Map/highlight/colorAlpha", Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); - double buffer = settings.value( "/Map/highlight/buffer", Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); - double minWidth = settings.value( "/Map/highlight/minWidth", Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); + QColor color = QColor( settings.value( QStringLiteral( "/Map/highlight/color" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); + int alpha = settings.value( QStringLiteral( "/Map/highlight/colorAlpha" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); + double buffer = settings.value( QStringLiteral( "/Map/highlight/buffer" ), Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); + double minWidth = settings.value( QStringLiteral( "/Map/highlight/minWidth" ), Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); mHighlight->setColor( color ); // sets also fill with default alpha color.setAlpha( alpha ); @@ -787,7 +787,7 @@ void QgsRelationReferenceWidget::mapToolDeactivated() void QgsRelationReferenceWidget::filterChanged() { - QVariant nullValue = QSettings().value( "qgis/nullValue", "NULL" ); + QVariant nullValue = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ); QStringList filters; QgsAttributeList attrs; @@ -846,24 +846,24 @@ void QgsRelationReferenceWidget::filterChanged() if ( cb->currentText() == nullValue.toString() ) { - filters << QString( "\"%1\" IS NULL" ).arg( fieldName ); + filters << QStringLiteral( "\"%1\" IS NULL" ).arg( fieldName ); } else { if ( mReferencedLayer->fields().field( fieldName ).type() == QVariant::String ) { - filters << QString( "\"%1\" = '%2'" ).arg( fieldName, cb->currentText() ); + filters << QStringLiteral( "\"%1\" = '%2'" ).arg( fieldName, cb->currentText() ); } else { - filters << QString( "\"%1\" = %2" ).arg( fieldName, cb->currentText() ); + filters << QStringLiteral( "\"%1\" = %2" ).arg( fieldName, cb->currentText() ); } } attrs << mReferencedLayer->fields().lookupField( fieldName ); } } - QString filterExpression = filters.join( " AND " ); + QString filterExpression = filters.join( QStringLiteral( " AND " ) ); QgsFeatureIterator it( mMasterModel->layerCache()->getFeatures( QgsFeatureRequest().setFilterExpression( filterExpression ).setSubsetOfAttributes( attrs ) ) ); diff --git a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp index cd3decee481e..a0e0ee2d051d 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp @@ -46,23 +46,23 @@ void QgsRelationReferenceWidgetWrapper::initWidget( QWidget* editor ) mWidget->setEditorContext( context(), mCanvas, mMessageBar ); - bool showForm = config( "ShowForm", true ).toBool(); - bool mapIdent = config( "MapIdentification", false ).toBool(); - bool readOnlyWidget = config( "ReadOnly", false ).toBool(); - bool orderByValue = config( "OrderByValue", false ).toBool(); + bool showForm = config( QStringLiteral( "ShowForm" ), true ).toBool(); + bool mapIdent = config( QStringLiteral( "MapIdentification" ), false ).toBool(); + bool readOnlyWidget = config( QStringLiteral( "ReadOnly" ), false ).toBool(); + bool orderByValue = config( QStringLiteral( "OrderByValue" ), false ).toBool(); mWidget->setEmbedForm( showForm ); mWidget->setReadOnlySelector( readOnlyWidget ); mWidget->setAllowMapIdentification( mapIdent ); mWidget->setOrderByValue( orderByValue ); - if ( config( "FilterFields", QVariant() ).isValid() ) + if ( config( QStringLiteral( "FilterFields" ), QVariant() ).isValid() ) { - mWidget->setFilterFields( config( "FilterFields" ).toStringList() ); - mWidget->setChainFilters( config( "ChainFilters" ).toBool() ); + mWidget->setFilterFields( config( QStringLiteral( "FilterFields" ) ).toStringList() ); + mWidget->setChainFilters( config( QStringLiteral( "ChainFilters" ) ).toBool() ); } - mWidget->setAllowAddFeatures( config( "AllowAddFeatures", false ).toBool() ); + mWidget->setAllowAddFeatures( config( QStringLiteral( "AllowAddFeatures" ), false ).toBool() ); - QgsRelation relation = QgsProject::instance()->relationManager()->relation( config( "Relation" ).toString() ); + QgsRelation relation = QgsProject::instance()->relationManager()->relation( config( QStringLiteral( "Relation" ) ).toString() ); // If this widget is already embedded by the same relation, reduce functionality const QgsAttributeEditorContext* ctx = &context(); @@ -78,7 +78,7 @@ void QgsRelationReferenceWidgetWrapper::initWidget( QWidget* editor ) } while ( ctx ); - mWidget->setRelation( relation, config( "AllowNULL" ).toBool() ); + mWidget->setRelation( relation, config( QStringLiteral( "AllowNULL" ) ).toBool() ); connect( mWidget, SIGNAL( foreignKeyChanged( QVariant ) ), this, SLOT( foreignKeyChanged( QVariant ) ) ); } @@ -147,6 +147,6 @@ void QgsRelationReferenceWidgetWrapper::updateConstraintWidgetStatus( bool const if ( constraintValid ) mWidget->setStyleSheet( QString() ); else - mWidget->setStyleSheet( ".QComboBox { background-color: #dd7777; }" ); + mWidget->setStyleSheet( QStringLiteral( ".QComboBox { background-color: #dd7777; }" ) ); } } diff --git a/src/gui/editorwidgets/qgsrelationwidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationwidgetwrapper.cpp index eee149f691cf..e5db1c71df98 100644 --- a/src/gui/editorwidgets/qgsrelationwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationwidgetwrapper.cpp @@ -91,7 +91,7 @@ void QgsRelationWidgetWrapper::initWidget( QWidget* editor ) w->setEditorContext( myContext ); - QgsRelation nmrel = QgsProject::instance()->relationManager()->relation( config( "nm-rel" ).toString() ); + QgsRelation nmrel = QgsProject::instance()->relationManager()->relation( config( QStringLiteral( "nm-rel" ) ).toString() ); // If this widget is already embedded by the same relation, reduce functionality const QgsAttributeEditorContext* ctx = &context(); diff --git a/src/gui/editorwidgets/qgssearchwidgettoolbutton.cpp b/src/gui/editorwidgets/qgssearchwidgettoolbutton.cpp index 3f136b8e2ab5..babdd467d579 100644 --- a/src/gui/editorwidgets/qgssearchwidgettoolbutton.cpp +++ b/src/gui/editorwidgets/qgssearchwidgettoolbutton.cpp @@ -239,7 +239,7 @@ void QgsSearchWidgetToolButton::updateState() if ( active ) { - QString text = toolTips.join( ", " ); + QString text = toolTips.join( QStringLiteral( ", " ) ); setText( text ); setToolTip( text ); } diff --git a/src/gui/editorwidgets/qgstexteditconfigdlg.cpp b/src/gui/editorwidgets/qgstexteditconfigdlg.cpp index eae3d4892c77..0ce0a1635ef1 100644 --- a/src/gui/editorwidgets/qgstexteditconfigdlg.cpp +++ b/src/gui/editorwidgets/qgstexteditconfigdlg.cpp @@ -29,14 +29,14 @@ QgsEditorWidgetConfig QgsTextEditConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "IsMultiline", mIsMultiline->isChecked() ); - cfg.insert( "UseHtml", mUseHtml->isChecked() ); + cfg.insert( QStringLiteral( "IsMultiline" ), mIsMultiline->isChecked() ); + cfg.insert( QStringLiteral( "UseHtml" ), mUseHtml->isChecked() ); return cfg; } void QgsTextEditConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - mIsMultiline->setChecked( config.value( "IsMultiline" ).toBool() ); - mUseHtml->setChecked( config.value( "UseHtml" ).toBool() ); + mIsMultiline->setChecked( config.value( QStringLiteral( "IsMultiline" ) ).toBool() ); + mUseHtml->setChecked( config.value( QStringLiteral( "UseHtml" ) ).toBool() ); } diff --git a/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp b/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp index f0286f447d46..71b5a34f3343 100644 --- a/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp @@ -46,8 +46,8 @@ void QgsTextEditWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "IsMultiline", config.value( "IsMultiline", false ).toBool() ); - configElement.setAttribute( "UseHtml", config.value( "UseHtml", false ).toBool() ); + configElement.setAttribute( QStringLiteral( "IsMultiline" ), config.value( QStringLiteral( "IsMultiline" ), false ).toBool() ); + configElement.setAttribute( QStringLiteral( "UseHtml" ), config.value( QStringLiteral( "UseHtml" ), false ).toBool() ); } QgsEditorWidgetConfig QgsTextEditWidgetFactory::readConfig( const QDomElement& configElement, QgsVectorLayer* layer, int fieldIdx ) @@ -57,8 +57,8 @@ QgsEditorWidgetConfig QgsTextEditWidgetFactory::readConfig( const QDomElement& c QgsEditorWidgetConfig cfg; - cfg.insert( "IsMultiline", configElement.attribute( "IsMultiline", "0" ) == "1" ); - cfg.insert( "UseHtml", configElement.attribute( "UseHtml", "0" ) == "1" ); + cfg.insert( QStringLiteral( "IsMultiline" ), configElement.attribute( QStringLiteral( "IsMultiline" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); + cfg.insert( QStringLiteral( "UseHtml" ), configElement.attribute( QStringLiteral( "UseHtml" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); return cfg; } diff --git a/src/gui/editorwidgets/qgstexteditwrapper.cpp b/src/gui/editorwidgets/qgstexteditwrapper.cpp index 033da9bcee1c..c5d4d7d88938 100644 --- a/src/gui/editorwidgets/qgstexteditwrapper.cpp +++ b/src/gui/editorwidgets/qgstexteditwrapper.cpp @@ -35,7 +35,7 @@ QVariant QgsTextEditWrapper::value() const if ( mTextEdit ) { - if ( config( "UseHtml" ).toBool() ) + if ( config( QStringLiteral( "UseHtml" ) ).toBool() ) { v = mTextEdit->toHtml(); } @@ -56,7 +56,7 @@ QVariant QgsTextEditWrapper::value() const } if (( v.isEmpty() && ( field().type() == QVariant::Int || field().type() == QVariant::Double || field().type() == QVariant::LongLong || field().type() == QVariant::Date ) ) || - v == QSettings().value( "qgis/nullValue", "NULL" ).toString() ) + v == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) return QVariant( field().type() ); if ( !defaultValue().isNull() && v == defaultValue().toString() ) @@ -83,9 +83,9 @@ QVariant QgsTextEditWrapper::value() const QWidget* QgsTextEditWrapper::createWidget( QWidget* parent ) { - if ( config( "IsMultiline" ).toBool() ) + if ( config( QStringLiteral( "IsMultiline" ) ).toBool() ) { - if ( config( "UseHtml" ).toBool() ) + if ( config( QStringLiteral( "UseHtml" ) ).toBool() ) { return new QTextEdit( parent ); } @@ -119,7 +119,7 @@ void QgsTextEditWrapper::initWidget( QWidget* editor ) QVariant defVal = defaultValue(); if ( defVal.isNull() ) { - defVal = QSettings().value( "qgis/nullValue", "NULL" ); + defVal = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ); } QgsFilterLineEdit *fle = qobject_cast<QgsFilterLineEdit*>( mLineEdit ); @@ -162,7 +162,7 @@ void QgsTextEditWrapper::showIndeterminateState() mLineEdit->setPlaceholderText( QString() ); } - setWidgetValue( QString( "" ) ); + setWidgetValue( QLatin1String( "" ) ); if ( mTextEdit ) mTextEdit->blockSignals( false ); @@ -215,7 +215,7 @@ void QgsTextEditWrapper::setWidgetValue( const QVariant& val ) if ( val.isNull() ) { if ( !( field().type() == QVariant::Int || field().type() == QVariant::Double || field().type() == QVariant::LongLong || field().type() == QVariant::Date ) ) - v = QSettings().value( "qgis/nullValue", "NULL" ).toString(); + v = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } else v = val.toString(); @@ -224,7 +224,7 @@ void QgsTextEditWrapper::setWidgetValue( const QVariant& val ) { if ( val != value() ) { - if ( config( "UseHtml" ).toBool() ) + if ( config( QStringLiteral( "UseHtml" ) ).toBool() ) mTextEdit->setHtml( v ); else mTextEdit->setPlainText( v ); diff --git a/src/gui/editorwidgets/qgsuniquevaluesconfigdlg.cpp b/src/gui/editorwidgets/qgsuniquevaluesconfigdlg.cpp index f6e080f1ece7..37557d47ee46 100644 --- a/src/gui/editorwidgets/qgsuniquevaluesconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsuniquevaluesconfigdlg.cpp @@ -27,12 +27,12 @@ QgsEditorWidgetConfig QgsUniqueValuesConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "Editable", editableUniqueValues->isChecked() ); + cfg.insert( QStringLiteral( "Editable" ), editableUniqueValues->isChecked() ); return cfg; } void QgsUniqueValuesConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - editableUniqueValues->setChecked( config.value( "Editable", false ).toBool() ); + editableUniqueValues->setChecked( config.value( QStringLiteral( "Editable" ), false ).toBool() ); } diff --git a/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp b/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp index 7509f5664a34..5416d8111a66 100644 --- a/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp @@ -41,7 +41,7 @@ QgsEditorWidgetConfig QgsUniqueValueWidgetFactory::readConfig( const QDomElement QgsEditorWidgetConfig cfg; - cfg.insert( "Editable", configElement.attribute( "Editable", "0" ) == "1" ); + cfg.insert( QStringLiteral( "Editable" ), configElement.attribute( QStringLiteral( "Editable" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); return cfg; } @@ -51,5 +51,5 @@ void QgsUniqueValueWidgetFactory::writeConfig( const QgsEditorWidgetConfig& conf Q_UNUSED( doc ) Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "Editable", config.value( "Editable", false ).toBool() ); + configElement.setAttribute( QStringLiteral( "Editable" ), config.value( QStringLiteral( "Editable" ), false ).toBool() ); } diff --git a/src/gui/editorwidgets/qgsuniquevaluewidgetwrapper.cpp b/src/gui/editorwidgets/qgsuniquevaluewidgetwrapper.cpp index 56b3dcee90d9..f1e9a55f7c84 100644 --- a/src/gui/editorwidgets/qgsuniquevaluewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsuniquevaluewidgetwrapper.cpp @@ -37,7 +37,7 @@ QVariant QgsUniqueValuesWidgetWrapper::value() const if ( mLineEdit ) { - if ( mLineEdit->text() == QSettings().value( "qgis/nullValue", "NULL" ).toString() ) + if ( mLineEdit->text() == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) value = QVariant( field().type() ); else value = mLineEdit->text(); @@ -48,7 +48,7 @@ QVariant QgsUniqueValuesWidgetWrapper::value() const QWidget* QgsUniqueValuesWidgetWrapper::createWidget( QWidget* parent ) { - if ( config( "Editable" ).toBool() ) + if ( config( QStringLiteral( "Editable" ) ).toBool() ) return new QgsFilterLineEdit( parent ); else return new QComboBox( parent ); @@ -83,7 +83,7 @@ void QgsUniqueValuesWidgetWrapper::initWidget( QWidget* editor ) QgsFilterLineEdit* fle = qobject_cast<QgsFilterLineEdit*>( editor ); if ( fle && !( field().type() == QVariant::Int || field().type() == QVariant::Double || field().type() == QVariant::LongLong || field().type() == QVariant::Date ) ) { - fle->setNullValue( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + fle->setNullValue( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } QCompleter* c = new QCompleter( sValues ); @@ -127,7 +127,7 @@ void QgsUniqueValuesWidgetWrapper::setValue( const QVariant& value ) if ( mLineEdit ) { if ( value.isNull() ) - mLineEdit->setText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mLineEdit->setText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); else mLineEdit->setText( value.toString() ); } diff --git a/src/gui/editorwidgets/qgsvaluemapconfigdlg.cpp b/src/gui/editorwidgets/qgsvaluemapconfigdlg.cpp index 49774bf990d4..52957d217dec 100644 --- a/src/gui/editorwidgets/qgsvaluemapconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsvaluemapconfigdlg.cpp @@ -51,7 +51,7 @@ QgsEditorWidgetConfig QgsValueMapConfigDlg::config() continue; QString ks = ki->text(); - if (( ks == settings.value( "qgis/nullValue", "NULL" ).toString() ) && !( ki->flags() & Qt::ItemIsEditable ) ) + if (( ks == settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) && !( ki->flags() & Qt::ItemIsEditable ) ) ks = VALUEMAP_NULL_TEXT; if ( !vi || vi->text().isNull() ) @@ -132,7 +132,7 @@ void QgsValueMapConfigDlg::updateMap( const QMap<QString, QVariant> &map, bool i if ( insertNull ) { - setRow( row, VALUEMAP_NULL_TEXT, "<NULL>" ); + setRow( row, VALUEMAP_NULL_TEXT, QStringLiteral( "<NULL>" ) ); ++row; } @@ -151,11 +151,11 @@ void QgsValueMapConfigDlg::setRow( int row, const QString& value, const QString& QTableWidgetItem* valueCell; QTableWidgetItem* descriptionCell = new QTableWidgetItem( description ); tableWidget->insertRow( row ); - if ( value == QString( VALUEMAP_NULL_TEXT ) ) + if ( value == QStringLiteral( VALUEMAP_NULL_TEXT ) ) { QFont cellFont; cellFont.setItalic( true ); - valueCell = new QTableWidgetItem( settings.value( "qgis/nullValue", "NULL" ).toString() ); + valueCell = new QTableWidgetItem( settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); valueCell->setFont( cellFont ); valueCell->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled ); descriptionCell->setFont( cellFont ); @@ -170,7 +170,7 @@ void QgsValueMapConfigDlg::setRow( int row, const QString& value, const QString& void QgsValueMapConfigDlg::addNullButtonPushed() { - setRow( tableWidget->rowCount() - 1, VALUEMAP_NULL_TEXT, "<NULL>" ); + setRow( tableWidget->rowCount() - 1, VALUEMAP_NULL_TEXT, QStringLiteral( "<NULL>" ) ); } void QgsValueMapConfigDlg::loadFromLayerButtonPushed() @@ -242,8 +242,8 @@ void QgsValueMapConfigDlg::loadFromCSVButtonPushed() val = val.mid( 1, val.length() - 2 ); } - if ( key == settings.value( "qgis/nullValue", "NULL" ).toString() ) - key = QString( VALUEMAP_NULL_TEXT ); + if ( key == settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) + key = QStringLiteral( VALUEMAP_NULL_TEXT ); map[ key ] = val; } diff --git a/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp index e94aed1c5a96..03c5c58dbd05 100644 --- a/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluemapsearchwidgetwrapper.cpp @@ -146,7 +146,7 @@ void QgsValueMapSearchWidgetWrapper::initWidget( QWidget* editor ) while ( it != cfg.constEnd() ) { - if ( it.value() != QString( VALUEMAP_NULL_TEXT ) ) + if ( it.value() != QStringLiteral( VALUEMAP_NULL_TEXT ) ) mComboBox->addItem( it.key(), it.value() ); ++it; } @@ -159,9 +159,9 @@ void QgsValueMapSearchWidgetWrapper::setExpression( QString exp ) QString fieldName = layer()->fields().at( mFieldIdx ).name(); QString str; - str = QString( "%1 = '%2'" ) + str = QStringLiteral( "%1 = '%2'" ) .arg( QgsExpression::quotedColumnRef( fieldName ), - exp.replace( '\'', "''" ) ); + exp.replace( '\'', QLatin1String( "''" ) ) ); mExpression = str; } diff --git a/src/gui/editorwidgets/qgsvaluemapwidgetfactory.cpp b/src/gui/editorwidgets/qgsvaluemapwidgetfactory.cpp index ae726555753a..628fe67d350c 100644 --- a/src/gui/editorwidgets/qgsvaluemapwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsvaluemapwidgetfactory.cpp @@ -51,12 +51,12 @@ QgsEditorWidgetConfig QgsValueMapWidgetFactory::readConfig( const QDomElement& c QgsEditorWidgetConfig cfg; - QDomNodeList nodes = configElement.elementsByTagName( "value" ); + QDomNodeList nodes = configElement.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < nodes.size(); ++i ) { QDomElement elem = nodes.at( i ).toElement(); - cfg.insert( elem.attribute( "key" ), elem.attribute( "value" ) ); + cfg.insert( elem.attribute( QStringLiteral( "key" ) ), elem.attribute( QStringLiteral( "value" ) ) ); } return cfg; @@ -71,10 +71,10 @@ void QgsValueMapWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, while ( it != config.constEnd() ) { - QDomElement elem = doc.createElement( "value" ); + QDomElement elem = doc.createElement( QStringLiteral( "value" ) ); - elem.setAttribute( "key", it.key() ); - elem.setAttribute( "value", it.value().toString() ); + elem.setAttribute( QStringLiteral( "key" ), it.key() ); + elem.setAttribute( QStringLiteral( "value" ), it.value().toString() ); configElement.appendChild( elem ); @@ -88,11 +88,11 @@ QString QgsValueMapWidgetFactory::representValue( QgsVectorLayer* vl, int fieldI QString valueInternalText; if ( value.isNull() ) - valueInternalText = QString( VALUEMAP_NULL_TEXT ); + valueInternalText = QStringLiteral( VALUEMAP_NULL_TEXT ); else valueInternalText = value.toString(); - return config.key( valueInternalText, QVariant( QString( "(%1)" ).arg( vl->fields().at( fieldIdx ).displayString( value ) ) ).toString() ); + return config.key( valueInternalText, QVariant( QStringLiteral( "(%1)" ).arg( vl->fields().at( fieldIdx ).displayString( value ) ) ).toString() ); } QVariant QgsValueMapWidgetFactory::sortValue( QgsVectorLayer* vl, int fieldIdx, const QgsEditorWidgetConfig& config, const QVariant& cache, const QVariant& value ) const diff --git a/src/gui/editorwidgets/qgsvaluemapwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluemapwidgetwrapper.cpp index 8995e903a247..bfd0d07e798c 100644 --- a/src/gui/editorwidgets/qgsvaluemapwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluemapwidgetwrapper.cpp @@ -32,7 +32,7 @@ QVariant QgsValueMapWidgetWrapper::value() const if ( mComboBox ) v = mComboBox->currentData(); - if ( v == QString( VALUEMAP_NULL_TEXT ) ) + if ( v == QStringLiteral( VALUEMAP_NULL_TEXT ) ) v = QVariant( field().type() ); return v; @@ -78,7 +78,7 @@ void QgsValueMapWidgetWrapper::setValue( const QVariant& value ) { QString v; if ( value.isNull() ) - v = QString( VALUEMAP_NULL_TEXT ); + v = QStringLiteral( VALUEMAP_NULL_TEXT ); else v = value.toString(); diff --git a/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp b/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp index eb11d8f7a61e..7bbe41d0a32c 100644 --- a/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp @@ -41,29 +41,29 @@ QgsEditorWidgetConfig QgsValueRelationConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "Layer", mLayerName->currentLayer() ? mLayerName->currentLayer()->id() : QString() ); - cfg.insert( "Key", mKeyColumn->currentField() ); - cfg.insert( "Value", mValueColumn->currentField() ); - cfg.insert( "AllowMulti", mAllowMulti->isChecked() ); - cfg.insert( "AllowNull", mAllowNull->isChecked() ); - cfg.insert( "OrderByValue", mOrderByValue->isChecked() ); - cfg.insert( "FilterExpression", mFilterExpression->toPlainText() ); - cfg.insert( "UseCompleter", mUseCompleter->isChecked() ); + cfg.insert( QStringLiteral( "Layer" ), mLayerName->currentLayer() ? mLayerName->currentLayer()->id() : QString() ); + cfg.insert( QStringLiteral( "Key" ), mKeyColumn->currentField() ); + cfg.insert( QStringLiteral( "Value" ), mValueColumn->currentField() ); + cfg.insert( QStringLiteral( "AllowMulti" ), mAllowMulti->isChecked() ); + cfg.insert( QStringLiteral( "AllowNull" ), mAllowNull->isChecked() ); + cfg.insert( QStringLiteral( "OrderByValue" ), mOrderByValue->isChecked() ); + cfg.insert( QStringLiteral( "FilterExpression" ), mFilterExpression->toPlainText() ); + cfg.insert( QStringLiteral( "UseCompleter" ), mUseCompleter->isChecked() ); return cfg; } void QgsValueRelationConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - QgsVectorLayer* lyr = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( config.value( "Layer" ).toString() ) ); + QgsVectorLayer* lyr = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( config.value( QStringLiteral( "Layer" ) ).toString() ) ); mLayerName->setLayer( lyr ); - mKeyColumn->setField( config.value( "Key" ).toString() ); - mValueColumn->setField( config.value( "Value" ).toString() ); - mAllowMulti->setChecked( config.value( "AllowMulti" ).toBool() ); - mAllowNull->setChecked( config.value( "AllowNull" ).toBool() ); - mOrderByValue->setChecked( config.value( "OrderByValue" ).toBool() ); - mFilterExpression->setPlainText( config.value( "FilterExpression" ).toString() ); - mUseCompleter->setChecked( config.value( "UseCompleter" ).toBool() ); + mKeyColumn->setField( config.value( QStringLiteral( "Key" ) ).toString() ); + mValueColumn->setField( config.value( QStringLiteral( "Value" ) ).toString() ); + mAllowMulti->setChecked( config.value( QStringLiteral( "AllowMulti" ) ).toBool() ); + mAllowNull->setChecked( config.value( QStringLiteral( "AllowNull" ) ).toBool() ); + mOrderByValue->setChecked( config.value( QStringLiteral( "OrderByValue" ) ).toBool() ); + mFilterExpression->setPlainText( config.value( QStringLiteral( "FilterExpression" ) ).toString() ); + mUseCompleter->setChecked( config.value( QStringLiteral( "UseCompleter" ) ).toBool() ); } void QgsValueRelationConfigDlg::editExpression() @@ -77,7 +77,7 @@ void QgsValueRelationConfigDlg::editExpression() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( vl ); - QgsExpressionBuilderDialog dlg( vl, mFilterExpression->toPlainText(), this, "generic", context ); + QgsExpressionBuilderDialog dlg( vl, mFilterExpression->toPlainText(), this, QStringLiteral( "generic" ), context ); dlg.setWindowTitle( tr( "Edit filter expression" ) ); if ( dlg.exec() == QDialog::Accepted ) diff --git a/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp index ff012c8e4457..063b7dab6c23 100644 --- a/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationsearchwidgetwrapper.cpp @@ -72,7 +72,7 @@ QVariant QgsValueRelationSearchWidgetWrapper::value() const selection << item->data( Qt::UserRole ).toString(); } - v = selection.join( "," ).prepend( '{' ).append( '}' ); + v = selection.join( QStringLiteral( "," ) ).prepend( '{' ).append( '}' ); } if ( mLineEdit ) @@ -191,7 +191,7 @@ void QgsValueRelationSearchWidgetWrapper::onValueChanged() else { QSettings settings; - setExpression( vl.isNull() ? settings.value( "qgis/nullValue", "NULL" ).toString() : vl.toString() ); + setExpression( vl.isNull() ? settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() : vl.toString() ); emit valueChanged(); } emit expressionChanged( mExpression ); @@ -200,19 +200,19 @@ void QgsValueRelationSearchWidgetWrapper::onValueChanged() void QgsValueRelationSearchWidgetWrapper::setExpression( QString exp ) { QSettings settings; - QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString(); + QString nullValue = settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); QString fieldName = layer()->fields().at( mFieldIdx ).name(); QString str; if ( exp == nullValue ) { - str = QString( "%1 IS NULL" ).arg( QgsExpression::quotedColumnRef( fieldName ) ); + str = QStringLiteral( "%1 IS NULL" ).arg( QgsExpression::quotedColumnRef( fieldName ) ); } else { - str = QString( "%1 = '%3'" ) + str = QStringLiteral( "%1 = '%3'" ) .arg( QgsExpression::quotedColumnRef( fieldName ), - exp.replace( '\'', "''" ) + exp.replace( '\'', QLatin1String( "''" ) ) ); } mExpression = str; @@ -220,11 +220,11 @@ void QgsValueRelationSearchWidgetWrapper::setExpression( QString exp ) QWidget* QgsValueRelationSearchWidgetWrapper::createWidget( QWidget* parent ) { - if ( config( "AllowMulti" ).toBool() ) + if ( config( QStringLiteral( "AllowMulti" ) ).toBool() ) { return new QgsFilterLineEdit( parent ); } - else if ( config( "UseCompleter" ).toBool() ) + else if ( config( QStringLiteral( "UseCompleter" ) ).toBool() ) { return new QgsFilterLineEdit( parent ); } @@ -245,7 +245,7 @@ void QgsValueRelationSearchWidgetWrapper::initWidget( QWidget* editor ) if ( mComboBox ) { mComboBox->addItem( tr( "Please select" ), QVariant() ); // creates an invalid to allow selecting all features - if ( config( "AllowNull" ).toBool() ) + if ( config( QStringLiteral( "AllowNull" ) ).toBool() ) { mComboBox->addItem( tr( "(no selection)" ), QVariant( layer()->fields().at( mFieldIdx ).type() ) ); } diff --git a/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp b/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp index 63334daf866d..6df733d27827 100644 --- a/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp @@ -52,14 +52,14 @@ QgsEditorWidgetConfig QgsValueRelationWidgetFactory::readConfig( const QDomEleme QgsEditorWidgetConfig cfg; - cfg.insert( "Layer", configElement.attribute( "Layer" ) ); - cfg.insert( "Key", configElement.attribute( "Key" ) ); - cfg.insert( "Value", configElement.attribute( "Value" ) ); - cfg.insert( "FilterExpression", configElement.attribute( "FilterExpression" ) ); - cfg.insert( "OrderByValue", configElement.attribute( "OrderByValue" ) ); - cfg.insert( "AllowMulti", configElement.attribute( "AllowMulti" ) ); - cfg.insert( "AllowNull", configElement.attribute( "AllowNull" ) ); - cfg.insert( "UseCompleter", configElement.attribute( "UseCompleter" ) ); + cfg.insert( QStringLiteral( "Layer" ), configElement.attribute( QStringLiteral( "Layer" ) ) ); + cfg.insert( QStringLiteral( "Key" ), configElement.attribute( QStringLiteral( "Key" ) ) ); + cfg.insert( QStringLiteral( "Value" ), configElement.attribute( QStringLiteral( "Value" ) ) ); + cfg.insert( QStringLiteral( "FilterExpression" ), configElement.attribute( QStringLiteral( "FilterExpression" ) ) ); + cfg.insert( QStringLiteral( "OrderByValue" ), configElement.attribute( QStringLiteral( "OrderByValue" ) ) ); + cfg.insert( QStringLiteral( "AllowMulti" ), configElement.attribute( QStringLiteral( "AllowMulti" ) ) ); + cfg.insert( QStringLiteral( "AllowNull" ), configElement.attribute( QStringLiteral( "AllowNull" ) ) ); + cfg.insert( QStringLiteral( "UseCompleter" ), configElement.attribute( QStringLiteral( "UseCompleter" ) ) ); return cfg; } @@ -70,14 +70,14 @@ void QgsValueRelationWidgetFactory::writeConfig( const QgsEditorWidgetConfig& co Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "Layer", config.value( "Layer" ).toString() ); - configElement.setAttribute( "Key", config.value( "Key" ).toString() ); - configElement.setAttribute( "Value", config.value( "Value" ).toString() ); - configElement.setAttribute( "FilterExpression", config.value( "FilterExpression" ).toString() ); - configElement.setAttribute( "OrderByValue", config.value( "OrderByValue" ).toBool() ); - configElement.setAttribute( "AllowMulti", config.value( "AllowMulti" ).toBool() ); - configElement.setAttribute( "AllowNull", config.value( "AllowNull" ).toBool() ); - configElement.setAttribute( "UseCompleter", config.value( "UseCompleter" ).toBool() ); + configElement.setAttribute( QStringLiteral( "Layer" ), config.value( QStringLiteral( "Layer" ) ).toString() ); + configElement.setAttribute( QStringLiteral( "Key" ), config.value( QStringLiteral( "Key" ) ).toString() ); + configElement.setAttribute( QStringLiteral( "Value" ), config.value( QStringLiteral( "Value" ) ).toString() ); + configElement.setAttribute( QStringLiteral( "FilterExpression" ), config.value( QStringLiteral( "FilterExpression" ) ).toString() ); + configElement.setAttribute( QStringLiteral( "OrderByValue" ), config.value( QStringLiteral( "OrderByValue" ) ).toBool() ); + configElement.setAttribute( QStringLiteral( "AllowMulti" ), config.value( QStringLiteral( "AllowMulti" ) ).toBool() ); + configElement.setAttribute( QStringLiteral( "AllowNull" ), config.value( QStringLiteral( "AllowNull" ) ).toBool() ); + configElement.setAttribute( QStringLiteral( "UseCompleter" ), config.value( QStringLiteral( "UseCompleter" ) ).toBool() ); } QString QgsValueRelationWidgetFactory::representValue( QgsVectorLayer* vl, int fieldIdx, const QgsEditorWidgetConfig& config, const QVariant& cache, const QVariant& value ) const @@ -96,7 +96,7 @@ QString QgsValueRelationWidgetFactory::representValue( QgsVectorLayer* vl, int f vrCache = QgsValueRelationWidgetWrapper::createCache( config ); } - if ( config.value( "AllowMulti" ).toBool() ) + if ( config.value( QStringLiteral( "AllowMulti" ) ).toBool() ) { QStringList keyList = value.toString().remove( QChar( '{' ) ).remove( QChar( '}' ) ).split( ',' ); QStringList valueList; @@ -109,14 +109,14 @@ QString QgsValueRelationWidgetFactory::representValue( QgsVectorLayer* vl, int f } } - return valueList.join( ", " ).prepend( '{' ).append( '}' ); + return valueList.join( QStringLiteral( ", " ) ).prepend( '{' ).append( '}' ); } else { if ( value.isNull() ) { QSettings settings; - return settings.value( "qgis/nullValue", "NULL" ).toString(); + return settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } Q_FOREACH ( const QgsValueRelationWidgetWrapper::ValueRelationItem& item, vrCache ) @@ -128,7 +128,7 @@ QString QgsValueRelationWidgetFactory::representValue( QgsVectorLayer* vl, int f } } - return QString( "(%1)" ).arg( value.toString() ); + return QStringLiteral( "(%1)" ).arg( value.toString() ); } QVariant QgsValueRelationWidgetFactory::sortValue( QgsVectorLayer* vl, int fieldIdx, const QgsEditorWidgetConfig& config, const QVariant& cache, const QVariant& value ) const diff --git a/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp b/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp index d2f96a89b1fa..0844aaeac535 100644 --- a/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationwidgetwrapper.cpp @@ -71,7 +71,7 @@ QVariant QgsValueRelationWidgetWrapper::value() const selection << item->data( Qt::UserRole ).toString(); } - v = selection.join( "," ).prepend( '{' ).append( '}' ); + v = selection.join( QStringLiteral( "," ) ).prepend( '{' ).append( '}' ); } if ( mLineEdit ) @@ -91,11 +91,11 @@ QVariant QgsValueRelationWidgetWrapper::value() const QWidget* QgsValueRelationWidgetWrapper::createWidget( QWidget* parent ) { - if ( config( "AllowMulti" ).toBool() ) + if ( config( QStringLiteral( "AllowMulti" ) ).toBool() ) { return new QListWidget( parent ); } - else if ( config( "UseCompleter" ).toBool() ) + else if ( config( QStringLiteral( "UseCompleter" ) ).toBool() ) { return new QgsFilterLineEdit( parent ); } @@ -114,7 +114,7 @@ void QgsValueRelationWidgetWrapper::initWidget( QWidget* editor ) if ( mComboBox ) { - if ( config( "AllowNull" ).toBool() ) + if ( config( QStringLiteral( "AllowNull" ) ).toBool() ) { mComboBox->addItem( tr( "(no selection)" ), QVariant( field().type() ) ); } @@ -193,21 +193,21 @@ QgsValueRelationWidgetWrapper::ValueRelationCache QgsValueRelationWidgetWrapper: { ValueRelationCache cache; - QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( config.value( "Layer" ).toString() ) ); + QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( config.value( QStringLiteral( "Layer" ) ).toString() ) ); if ( !layer ) return cache; - int ki = layer->fields().lookupField( config.value( "Key" ).toString() ); - int vi = layer->fields().lookupField( config.value( "Value" ).toString() ); + int ki = layer->fields().lookupField( config.value( QStringLiteral( "Key" ) ).toString() ); + int vi = layer->fields().lookupField( config.value( QStringLiteral( "Value" ) ).toString() ); QgsFeatureRequest request; request.setFlags( QgsFeatureRequest::NoGeometry ); request.setSubsetOfAttributes( QgsAttributeList() << ki << vi ); - if ( !config.value( "FilterExpression" ).toString().isEmpty() ) + if ( !config.value( QStringLiteral( "FilterExpression" ) ).toString().isEmpty() ) { - request.setFilterExpression( config.value( "FilterExpression" ).toString() ); + request.setFilterExpression( config.value( QStringLiteral( "FilterExpression" ) ).toString() ); } QgsFeatureIterator fit = layer->getFeatures( request ); @@ -218,7 +218,7 @@ QgsValueRelationWidgetWrapper::ValueRelationCache QgsValueRelationWidgetWrapper: cache.append( ValueRelationItem( f.attribute( ki ), f.attribute( vi ).toString() ) ); } - if ( config.value( "OrderByValue" ).toBool() ) + if ( config.value( QStringLiteral( "OrderByValue" ) ).toBool() ) { qSort( cache.begin(), cache.end(), orderByValueLessThan ); } diff --git a/src/gui/editorwidgets/qgswebviewconfigdlg.cpp b/src/gui/editorwidgets/qgswebviewconfigdlg.cpp index c4ba7c10190d..ba2bffc14d2c 100644 --- a/src/gui/editorwidgets/qgswebviewconfigdlg.cpp +++ b/src/gui/editorwidgets/qgswebviewconfigdlg.cpp @@ -27,14 +27,14 @@ QgsEditorWidgetConfig QgsWebViewWidgetConfigDlg::config() { QgsEditorWidgetConfig cfg; - cfg.insert( "Height", sbWidgetHeight->value() ); - cfg.insert( "Width", sbWidgetWidth->value() ); + cfg.insert( QStringLiteral( "Height" ), sbWidgetHeight->value() ); + cfg.insert( QStringLiteral( "Width" ), sbWidgetWidth->value() ); return cfg; } void QgsWebViewWidgetConfigDlg::setConfig( const QgsEditorWidgetConfig& config ) { - sbWidgetHeight->setValue( config.value( "Height", 0 ).toInt() ); - sbWidgetWidth->setValue( config.value( "Width", 0 ).toInt() ); + sbWidgetHeight->setValue( config.value( QStringLiteral( "Height" ), 0 ).toInt() ); + sbWidgetWidth->setValue( config.value( QStringLiteral( "Width" ), 0 ).toInt() ); } diff --git a/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp b/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp index dfa4dc49fe36..899105a6592c 100644 --- a/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp @@ -41,8 +41,8 @@ QgsEditorWidgetConfig QgsWebViewWidgetFactory::readConfig( const QDomElement& co QgsEditorWidgetConfig cfg; - cfg.insert( "Height", configElement.attribute( "Height", 0 ).toInt() ); - cfg.insert( "Width", configElement.attribute( "Width", 0 ).toInt() ); + cfg.insert( QStringLiteral( "Height" ), configElement.attribute( QStringLiteral( "Height" ), 0 ).toInt() ); + cfg.insert( QStringLiteral( "Width" ), configElement.attribute( QStringLiteral( "Width" ), 0 ).toInt() ); return cfg; } @@ -53,6 +53,6 @@ void QgsWebViewWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( "Height", config.value( "Height", 0 ).toString() ); - configElement.setAttribute( "Width", config.value( "Width", 0 ).toString() ); + configElement.setAttribute( QStringLiteral( "Height" ), config.value( QStringLiteral( "Height" ), 0 ).toString() ); + configElement.setAttribute( QStringLiteral( "Width" ), config.value( QStringLiteral( "Width" ), 0 ).toString() ); } diff --git a/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp b/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp index aec4950023d5..837d618e98ea 100644 --- a/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp @@ -48,7 +48,7 @@ QVariant QgsWebViewWidgetWrapper::value() const if ( mLineEdit ) { - if ( mLineEdit->text() == QSettings().value( "qgis/nullValue", "NULL" ).toString() ) + if ( mLineEdit->text() == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ) v = QVariant( QVariant::String ); else v = mLineEdit->text(); @@ -74,9 +74,9 @@ QWidget* QgsWebViewWidgetWrapper::createWidget( QWidget* parent ) QGridLayout* layout = new QGridLayout(); QgsFilterLineEdit* le = new QgsFilterLineEdit(); QWebView* webView = new QWebView(); - webView->setObjectName( "EditorWebView" ); + webView->setObjectName( QStringLiteral( "EditorWebView" ) ); QPushButton* pb = new QPushButton( tr( "..." ) ); - pb->setObjectName( "FileChooserButton" ); + pb->setObjectName( QStringLiteral( "FileChooserButton" ) ); layout->addWidget( webView, 0, 0, 1, 2 ); layout->addWidget( le, 1, 0 ); @@ -101,7 +101,7 @@ void QgsWebViewWidgetWrapper::initWidget( QWidget* editor ) QgsFilterLineEdit* fle = qobject_cast<QgsFilterLineEdit*>( mLineEdit ); if ( fle ) { - fle->setNullValue( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + fle->setNullValue( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); } container = qobject_cast<QWidget*>( mLineEdit->parent() ); @@ -112,11 +112,11 @@ void QgsWebViewWidgetWrapper::initWidget( QWidget* editor ) mLineEdit = container->findChild<QLineEdit*>(); } - mButton = container->findChild<QPushButton*>( "FileChooserButton" ); + mButton = container->findChild<QPushButton*>( QStringLiteral( "FileChooserButton" ) ); if ( !mButton ) mButton = container->findChild<QPushButton*>(); - mWebView = container->findChild<QWebView*>( "EditorWebView" ); + mWebView = container->findChild<QWebView*>( QStringLiteral( "EditorWebView" ) ); if ( !mWebView ) mWebView = container->findChild<QWebView*>(); @@ -151,7 +151,7 @@ void QgsWebViewWidgetWrapper::setValue( const QVariant& value ) if ( mLineEdit ) { if ( value.isNull() ) - mLineEdit->setText( QSettings().value( "qgis/nullValue", "NULL" ).toString() ); + mLineEdit->setText( QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString() ); else mLineEdit->setText( value.toString() ); } @@ -198,7 +198,7 @@ void QgsWebViewWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid mLineEdit->setStyleSheet( QString() ); else { - mLineEdit->setStyleSheet( "QgsFilterLineEdit { background-color: #dd7777; }" ); + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); } } } diff --git a/src/gui/effects/qgseffectstackpropertieswidget.cpp b/src/gui/effects/qgseffectstackpropertieswidget.cpp index 161d0a119fd5..c5ccd6ee8347 100644 --- a/src/gui/effects/qgseffectstackpropertieswidget.cpp +++ b/src/gui/effects/qgseffectstackpropertieswidget.cpp @@ -406,7 +406,7 @@ QgsEffectStackCompactWidget::QgsEffectStackCompactWidget( QWidget *parent , QgsP layout->addWidget( mEnabledCheckBox ); mButton = new QToolButton( this ); - mButton->setIcon( QgsApplication::getThemeIcon( "mIconPaintEffects.svg" ) ); + mButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconPaintEffects.svg" ) ) ); mButton->setToolTip( tr( "Customise effects" ) ); layout->addWidget( mButton ); diff --git a/src/gui/effects/qgspainteffectpropertieswidget.cpp b/src/gui/effects/qgspainteffectpropertieswidget.cpp index f1863567369f..c73d9aaf9755 100644 --- a/src/gui/effects/qgspainteffectpropertieswidget.cpp +++ b/src/gui/effects/qgspainteffectpropertieswidget.cpp @@ -53,14 +53,14 @@ static void _initWidgetFunctions() if ( initialized ) return; - _initWidgetFunction( "blur", QgsBlurWidget::create ); - _initWidgetFunction( "dropShadow", QgsShadowEffectWidget::create ); - _initWidgetFunction( "innerShadow", QgsShadowEffectWidget::create ); - _initWidgetFunction( "drawSource", QgsDrawSourceWidget::create ); - _initWidgetFunction( "outerGlow", QgsGlowWidget::create ); - _initWidgetFunction( "innerGlow", QgsGlowWidget::create ); - _initWidgetFunction( "transform", QgsTransformWidget::create ); - _initWidgetFunction( "color", QgsColorEffectWidget::create ); + _initWidgetFunction( QStringLiteral( "blur" ), QgsBlurWidget::create ); + _initWidgetFunction( QStringLiteral( "dropShadow" ), QgsShadowEffectWidget::create ); + _initWidgetFunction( QStringLiteral( "innerShadow" ), QgsShadowEffectWidget::create ); + _initWidgetFunction( QStringLiteral( "drawSource" ), QgsDrawSourceWidget::create ); + _initWidgetFunction( QStringLiteral( "outerGlow" ), QgsGlowWidget::create ); + _initWidgetFunction( QStringLiteral( "innerGlow" ), QgsGlowWidget::create ); + _initWidgetFunction( QStringLiteral( "transform" ), QgsTransformWidget::create ); + _initWidgetFunction( QStringLiteral( "color" ), QgsColorEffectWidget::create ); initialized = true; } @@ -94,7 +94,7 @@ void QgsPaintEffectPropertiesWidget::populateEffectTypes() Q_FOREACH ( const QString& type, types ) { //don't show stack effect - if ( type == "effectStack" ) + if ( type == QLatin1String( "effectStack" ) ) continue; mEffectTypeCombo->addItem( registry->effectMetadata( type )->visibleName(), type ); diff --git a/src/gui/effects/qgspainteffectwidget.cpp b/src/gui/effects/qgspainteffectwidget.cpp index f4b8aaaa0c35..c613c411d0fb 100644 --- a/src/gui/effects/qgspainteffectwidget.cpp +++ b/src/gui/effects/qgspainteffectwidget.cpp @@ -40,7 +40,7 @@ QgsDrawSourceWidget::QgsDrawSourceWidget( QWidget *parent ) void QgsDrawSourceWidget::setPaintEffect( QgsPaintEffect *effect ) { - if ( !effect || effect->type() != "drawSource" ) + if ( !effect || effect->type() != QLatin1String( "drawSource" ) ) return; mEffect = static_cast<QgsDrawSourceEffect*>( effect ); @@ -132,7 +132,7 @@ QgsBlurWidget::QgsBlurWidget( QWidget *parent ) void QgsBlurWidget::setPaintEffect( QgsPaintEffect *effect ) { - if ( !effect || effect->type() != "blur" ) + if ( !effect || effect->type() != QLatin1String( "blur" ) ) return; mEffect = static_cast<QgsBlurEffect*>( effect ); @@ -252,7 +252,7 @@ QgsShadowEffectWidget::QgsShadowEffectWidget( QWidget *parent ) mShadowColorBtn->setAllowAlpha( false ); mShadowColorBtn->setColorDialogTitle( tr( "Select shadow color" ) ); - mShadowColorBtn->setContext( "symbology" ); + mShadowColorBtn->setContext( QStringLiteral( "symbology" ) ); mOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderMapUnits ); @@ -261,7 +261,7 @@ QgsShadowEffectWidget::QgsShadowEffectWidget( QWidget *parent ) void QgsShadowEffectWidget::setPaintEffect( QgsPaintEffect *effect ) { - if ( !effect || ( effect->type() != "dropShadow" && effect->type() != "innerShadow" ) ) + if ( !effect || ( effect->type() != QLatin1String( "dropShadow" ) && effect->type() != QLatin1String( "innerShadow" ) ) ) return; mEffect = static_cast<QgsShadowEffect*>( effect ); @@ -417,7 +417,7 @@ QgsGlowWidget::QgsGlowWidget( QWidget *parent ) mColorBtn->setAllowAlpha( false ); mColorBtn->setColorDialogTitle( tr( "Select glow color" ) ); - mColorBtn->setContext( "symbology" ); + mColorBtn->setContext( QStringLiteral( "symbology" ) ); mSpreadUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderMapUnits ); @@ -434,7 +434,7 @@ QgsGlowWidget::QgsGlowWidget( QWidget *parent ) void QgsGlowWidget::setPaintEffect( QgsPaintEffect *effect ) { - if ( !effect || ( effect->type() != "outerGlow" && effect->type() != "innerGlow" ) ) + if ( !effect || ( effect->type() != QLatin1String( "outerGlow" ) && effect->type() != QLatin1String( "innerGlow" ) ) ) return; mEffect = static_cast<QgsGlowEffect*>( effect ); @@ -626,7 +626,7 @@ QgsTransformWidget::QgsTransformWidget( QWidget *parent ) void QgsTransformWidget::setPaintEffect( QgsPaintEffect *effect ) { - if ( !effect || effect->type() != "transform" ) + if ( !effect || effect->type() != QLatin1String( "transform" ) ) return; mEffect = static_cast<QgsTransformEffect*>( effect ); @@ -804,7 +804,7 @@ QgsColorEffectWidget::QgsColorEffectWidget( QWidget *parent ) void QgsColorEffectWidget::setPaintEffect( QgsPaintEffect *effect ) { - if ( !effect || effect->type() != "color" ) + if ( !effect || effect->type() != QLatin1String( "color" ) ) return; mEffect = static_cast<QgsColorEffect*>( effect ); diff --git a/src/gui/layertree/qgscustomlayerorderwidget.cpp b/src/gui/layertree/qgscustomlayerorderwidget.cpp index 9a6b3db2282c..736a311d4869 100644 --- a/src/gui/layertree/qgscustomlayerorderwidget.cpp +++ b/src/gui/layertree/qgscustomlayerorderwidget.cpp @@ -163,7 +163,7 @@ Qt::DropActions CustomLayerOrderModel::supportedDropActions() const QStringList CustomLayerOrderModel::mimeTypes() const { QStringList types; - types << "application/qgis.layerorderdata"; + types << QStringLiteral( "application/qgis.layerorderdata" ); return types; } @@ -174,7 +174,7 @@ QMimeData*CustomLayerOrderModel::mimeData( const QModelIndexList& indexes ) cons lst << data( index, Qt::UserRole + 1 ).toString(); QMimeData* mimeData = new QMimeData(); - mimeData->setData( "application/qgis.layerorderdata", lst.join( "\n" ).toUtf8() ); + mimeData->setData( QStringLiteral( "application/qgis.layerorderdata" ), lst.join( QStringLiteral( "\n" ) ).toUtf8() ); return mimeData; } @@ -186,10 +186,10 @@ bool CustomLayerOrderModel::dropMimeData( const QMimeData* data, Qt::DropAction if ( action == Qt::IgnoreAction ) return true; - if ( !data->hasFormat( "application/qgis.layerorderdata" ) ) + if ( !data->hasFormat( QStringLiteral( "application/qgis.layerorderdata" ) ) ) return false; - QByteArray encodedData = data->data( "application/qgis.layerorderdata" ); + QByteArray encodedData = data->data( QStringLiteral( "application/qgis.layerorderdata" ) ); QStringList lst = QString::fromUtf8( encodedData ).split( '\n' ); if ( row < 0 ) diff --git a/src/gui/layertree/qgslayertreeembeddedconfigwidget.cpp b/src/gui/layertree/qgslayertreeembeddedconfigwidget.cpp index 32ca127d7b75..16f9bea11833 100644 --- a/src/gui/layertree/qgslayertreeembeddedconfigwidget.cpp +++ b/src/gui/layertree/qgslayertreeembeddedconfigwidget.cpp @@ -50,10 +50,10 @@ void QgsLayerTreeEmbeddedConfigWidget::setLayer( QgsMapLayer* layer ) mListAvailable->setModel( modelAvailable ); // populate used - int widgetsCount = layer->customProperty( "embeddedWidgets/count", 0 ).toInt(); + int widgetsCount = layer->customProperty( QStringLiteral( "embeddedWidgets/count" ), 0 ).toInt(); for ( int i = 0; i < widgetsCount; ++i ) { - QString providerId = layer->customProperty( QString( "embeddedWidgets/%1/id" ).arg( i ) ).toString(); + QString providerId = layer->customProperty( QStringLiteral( "embeddedWidgets/%1/id" ).arg( i ) ).toString(); if ( QgsLayerTreeEmbeddedWidgetProvider* provider = QgsLayerTreeEmbeddedWidgetRegistry::instance()->provider( providerId ) ) { QStandardItem* item = new QStandardItem( provider->name() ); @@ -99,18 +99,18 @@ void QgsLayerTreeEmbeddedConfigWidget::applyToLayer() return; // clear old properties - int widgetsCount = mLayer->customProperty( "embeddedWidgets/count", 0 ).toInt(); + int widgetsCount = mLayer->customProperty( QStringLiteral( "embeddedWidgets/count" ), 0 ).toInt(); for ( int i = 0; i < widgetsCount; ++i ) { - mLayer->removeCustomProperty( QString( "embeddedWidgets/%1/id" ).arg( i ) ); + mLayer->removeCustomProperty( QStringLiteral( "embeddedWidgets/%1/id" ).arg( i ) ); } // setup new properties int newCount = mListUsed->model()->rowCount(); - mLayer->setCustomProperty( "embeddedWidgets/count", newCount ); + mLayer->setCustomProperty( QStringLiteral( "embeddedWidgets/count" ), newCount ); for ( int i = 0; i < newCount; ++i ) { QString providerId = mListUsed->model()->data( mListUsed->model()->index( i, 0 ), Qt::UserRole + 1 ).toString(); - mLayer->setCustomProperty( QString( "embeddedWidgets/%1/id" ).arg( i ), providerId ); + mLayer->setCustomProperty( QStringLiteral( "embeddedWidgets/%1/id" ).arg( i ), providerId ); } } diff --git a/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.cpp b/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.cpp index cdd74689c9b1..00660d74ee2c 100644 --- a/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.cpp +++ b/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.cpp @@ -31,7 +31,7 @@ QgsLayerTreeTransparencyWidget::QgsLayerTreeTransparencyWidget( QgsMapLayer* lay : mLayer( layer ) { setAutoFillBackground( true ); // override the content from model - QLabel* l = new QLabel( "Transparency", this ); + QLabel* l = new QLabel( QStringLiteral( "Transparency" ), this ); mSlider = new QSlider( Qt::Horizontal, this ); mSlider->setRange( 0, 100 ); QHBoxLayout* lay = new QHBoxLayout(); @@ -102,7 +102,7 @@ void QgsLayerTreeTransparencyWidget::layerTrChanged() QString QgsLayerTreeTransparencyWidget::Provider::id() const { - return "transparency"; + return QStringLiteral( "transparency" ); } QString QgsLayerTreeTransparencyWidget::Provider::name() const diff --git a/src/gui/layertree/qgslayertreemapcanvasbridge.cpp b/src/gui/layertree/qgslayertreemapcanvasbridge.cpp index 81c2edbd229d..dbc3fa5a0652 100644 --- a/src/gui/layertree/qgslayertreemapcanvasbridge.cpp +++ b/src/gui/layertree/qgslayertreemapcanvasbridge.cpp @@ -124,7 +124,7 @@ void QgsLayerTreeMapCanvasBridge::setCanvasLayers() { QgsLayerTreeLayer* nodeLayer = mRoot->findLayer( layerId ); if ( nodeLayer ) - layers << QgsMapCanvasLayer( nodeLayer->layer(), nodeLayer->isVisible() == Qt::Checked, nodeLayer->customProperty( "overview", 0 ).toInt() ); + layers << QgsMapCanvasLayer( nodeLayer->layer(), nodeLayer->isVisible() == Qt::Checked, nodeLayer->customProperty( QStringLiteral( "overview" ), 0 ).toInt() ); } } else @@ -202,12 +202,12 @@ void QgsLayerTreeMapCanvasBridge::readProject( const QDomDocument& doc ) { mFirstCRS = QgsCoordinateReferenceSystem(); // invalidate on project load - QDomElement elem = doc.documentElement().firstChildElement( "layer-tree-canvas" ); + QDomElement elem = doc.documentElement().firstChildElement( QStringLiteral( "layer-tree-canvas" ) ); if ( elem.isNull() ) { bool oldEnabled; QStringList oldOrder; - if ( QgsLayerTreeUtils::readOldLegendLayerOrder( doc.documentElement().firstChildElement( "legend" ), oldEnabled, oldOrder ) ) + if ( QgsLayerTreeUtils::readOldLegendLayerOrder( doc.documentElement().firstChildElement( QStringLiteral( "legend" ) ), oldEnabled, oldOrder ) ) { setHasCustomLayerOrder( oldEnabled ); setCustomLayerOrder( oldOrder ); @@ -215,31 +215,31 @@ void QgsLayerTreeMapCanvasBridge::readProject( const QDomDocument& doc ) return; } - QDomElement customOrderElem = elem.firstChildElement( "custom-order" ); + QDomElement customOrderElem = elem.firstChildElement( QStringLiteral( "custom-order" ) ); if ( !customOrderElem.isNull() ) { QStringList order; - QDomElement itemElem = customOrderElem.firstChildElement( "item" ); + QDomElement itemElem = customOrderElem.firstChildElement( QStringLiteral( "item" ) ); while ( !itemElem.isNull() ) { order.append( itemElem.text() ); - itemElem = itemElem.nextSiblingElement( "item" ); + itemElem = itemElem.nextSiblingElement( QStringLiteral( "item" ) ); } - setHasCustomLayerOrder( customOrderElem.attribute( "enabled", QString() ).toInt() ); + setHasCustomLayerOrder( customOrderElem.attribute( QStringLiteral( "enabled" ), QString() ).toInt() ); setCustomLayerOrder( order ); } } void QgsLayerTreeMapCanvasBridge::writeProject( QDomDocument& doc ) { - QDomElement elem = doc.createElement( "layer-tree-canvas" ); - QDomElement customOrderElem = doc.createElement( "custom-order" ); - customOrderElem.setAttribute( "enabled", mHasCustomLayerOrder ? 1 : 0 ); + QDomElement elem = doc.createElement( QStringLiteral( "layer-tree-canvas" ) ); + QDomElement customOrderElem = doc.createElement( QStringLiteral( "custom-order" ) ); + customOrderElem.setAttribute( QStringLiteral( "enabled" ), mHasCustomLayerOrder ? 1 : 0 ); Q_FOREACH ( const QString& layerId, mCustomLayerOrder ) { - QDomElement itemElem = doc.createElement( "item" ); + QDomElement itemElem = doc.createElement( QStringLiteral( "item" ) ); itemElem.appendChild( doc.createTextNode( layerId ) ); customOrderElem.appendChild( itemElem ); } @@ -253,7 +253,7 @@ void QgsLayerTreeMapCanvasBridge::setCanvasLayers( QgsLayerTreeNode *node, QList if ( QgsLayerTree::isLayer( node ) ) { QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node ); - layers << QgsMapCanvasLayer( nodeLayer->layer(), nodeLayer->isVisible() == Qt::Checked, nodeLayer->customProperty( "overview", 0 ).toInt() ); + layers << QgsMapCanvasLayer( nodeLayer->layer(), nodeLayer->isVisible() == Qt::Checked, nodeLayer->customProperty( QStringLiteral( "overview" ), 0 ).toInt() ); } Q_FOREACH ( QgsLayerTreeNode* child, node->children() ) @@ -328,7 +328,7 @@ void QgsLayerTreeMapCanvasBridge::nodeVisibilityChanged() void QgsLayerTreeMapCanvasBridge::nodeCustomPropertyChanged( QgsLayerTreeNode* node, const QString& key ) { Q_UNUSED( node ); - if ( key == "overview" ) + if ( key == QLatin1String( "overview" ) ) deferredSetCanvasLayers(); } diff --git a/src/gui/layertree/qgslayertreeview.cpp b/src/gui/layertree/qgslayertreeview.cpp index 2297e89df1e0..2b3a32acadba 100644 --- a/src/gui/layertree/qgslayertreeview.cpp +++ b/src/gui/layertree/qgslayertreeview.cpp @@ -137,11 +137,11 @@ void QgsLayerTreeView::modelRowsInserted( const QModelIndex& index, int start, i QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( parentNode ); if ( QgsMapLayer* layer = nodeLayer->layer() ) { - int widgetsCount = layer->customProperty( "embeddedWidgets/count", 0 ).toInt(); + int widgetsCount = layer->customProperty( QStringLiteral( "embeddedWidgets/count" ), 0 ).toInt(); QList<QgsLayerTreeModelLegendNode*> legendNodes = layerTreeModel()->layerLegendNodes( nodeLayer ); for ( int i = 0; i < widgetsCount; ++i ) { - QString providerId = layer->customProperty( QString( "embeddedWidgets/%1/id" ).arg( i ) ).toString(); + QString providerId = layer->customProperty( QStringLiteral( "embeddedWidgets/%1/id" ).arg( i ) ).toString(); if ( QgsLayerTreeEmbeddedWidgetProvider* provider = QgsLayerTreeEmbeddedWidgetRegistry::instance()->provider( providerId ) ) { QModelIndex index = layerTreeModel()->legendNode2index( legendNodes[i] ); @@ -155,7 +155,7 @@ void QgsLayerTreeView::modelRowsInserted( const QModelIndex& index, int start, i if ( QgsLayerTree::isLayer( parentNode ) ) { // if ShowLegendAsTree flag is enabled in model, we may need to expand some legend nodes - QStringList expandedNodeKeys = parentNode->customProperty( "expandedLegendNodes" ).toStringList(); + QStringList expandedNodeKeys = parentNode->customProperty( QStringLiteral( "expandedLegendNodes" ) ).toStringList(); if ( expandedNodeKeys.isEmpty() ) return; @@ -193,18 +193,18 @@ void QgsLayerTreeView::updateExpandedStateToNode( const QModelIndex& index ) else if ( QgsLayerTreeModelLegendNode* node = layerTreeModel()->index2legendNode( index ) ) { QString ruleKey = node->data( QgsLayerTreeModelLegendNode::RuleKeyRole ).toString(); - QStringList lst = node->layerNode()->customProperty( "expandedLegendNodes" ).toStringList(); + QStringList lst = node->layerNode()->customProperty( QStringLiteral( "expandedLegendNodes" ) ).toStringList(); bool expanded = isExpanded( index ); bool isInList = lst.contains( ruleKey ); if ( expanded && !isInList ) { lst.append( ruleKey ); - node->layerNode()->setCustomProperty( "expandedLegendNodes", lst ); + node->layerNode()->setCustomProperty( QStringLiteral( "expandedLegendNodes" ), lst ); } else if ( !expanded && isInList ) { lst.removeAll( ruleKey ); - node->layerNode()->setCustomProperty( "expandedLegendNodes", lst ); + node->layerNode()->setCustomProperty( QStringLiteral( "expandedLegendNodes" ), lst ); } } } diff --git a/src/gui/layertree/qgslayertreeviewdefaultactions.cpp b/src/gui/layertree/qgslayertreeviewdefaultactions.cpp index b003ae17f6e7..9cd6004d1ec6 100644 --- a/src/gui/layertree/qgslayertreeviewdefaultactions.cpp +++ b/src/gui/layertree/qgslayertreeviewdefaultactions.cpp @@ -33,14 +33,14 @@ QgsLayerTreeViewDefaultActions::QgsLayerTreeViewDefaultActions( QgsLayerTreeView QAction* QgsLayerTreeViewDefaultActions::actionAddGroup( QObject* parent ) { - QAction* a = new QAction( QgsApplication::getThemeIcon( "/mActionAddGroup.svg" ), tr( "&Add Group" ), parent ); + QAction* a = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionAddGroup.svg" ) ), tr( "&Add Group" ), parent ); connect( a, SIGNAL( triggered() ), this, SLOT( addGroup() ) ); return a; } QAction* QgsLayerTreeViewDefaultActions::actionRemoveGroupOrLayer( QObject* parent ) { - QAction* a = new QAction( QgsApplication::getThemeIcon( "/mActionRemoveLayer.svg" ), tr( "&Remove" ), parent ); + QAction* a = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemoveLayer.svg" ) ), tr( "&Remove" ), parent ); connect( a, SIGNAL( triggered() ), this, SLOT( removeGroupOrLayer() ) ); return a; } @@ -54,7 +54,7 @@ QAction* QgsLayerTreeViewDefaultActions::actionShowInOverview( QObject* parent ) QAction* a = new QAction( tr( "&Show in Overview" ), parent ); connect( a, SIGNAL( triggered() ), this, SLOT( showInOverview() ) ); a->setCheckable( true ); - a->setChecked( node->customProperty( "overview", 0 ).toInt() ); + a->setChecked( node->customProperty( QStringLiteral( "overview" ), 0 ).toInt() ); return a; } @@ -74,13 +74,13 @@ QAction* QgsLayerTreeViewDefaultActions::actionShowFeatureCount( QObject* parent QAction* a = new QAction( tr( "Show Feature Count" ), parent ); connect( a, SIGNAL( triggered() ), this, SLOT( showFeatureCount() ) ); a->setCheckable( true ); - a->setChecked( node->customProperty( "showFeatureCount", 0 ).toInt() ); + a->setChecked( node->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() ); return a; } QAction* QgsLayerTreeViewDefaultActions::actionZoomToLayer( QgsMapCanvas* canvas, QObject* parent ) { - QAction* a = new QAction( QgsApplication::getThemeIcon( "/mActionZoomToLayer.svg" ), + QAction* a = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomToLayer.svg" ) ), tr( "&Zoom to Layer" ), parent ); a->setData( QVariant::fromValue( reinterpret_cast<void*>( canvas ) ) ); connect( a, SIGNAL( triggered() ), this, SLOT( zoomToLayer() ) ); @@ -89,7 +89,7 @@ QAction* QgsLayerTreeViewDefaultActions::actionZoomToLayer( QgsMapCanvas* canvas QAction* QgsLayerTreeViewDefaultActions::actionZoomToGroup( QgsMapCanvas* canvas, QObject* parent ) { - QAction* a = new QAction( QgsApplication::getThemeIcon( "/mActionZoomToLayer.svg" ), + QAction* a = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionZoomToLayer.svg" ) ), tr( "&Zoom to Group" ), parent ); a->setData( QVariant::fromValue( reinterpret_cast<void*>( canvas ) ) ); connect( a, SIGNAL( triggered() ), this, SLOT( zoomToGroup() ) ); @@ -152,9 +152,9 @@ void QgsLayerTreeViewDefaultActions::showInOverview() QgsLayerTreeNode* node = mView->currentNode(); if ( !node ) return; - int newValue = node->customProperty( "overview", 0 ).toInt(); + int newValue = node->customProperty( QStringLiteral( "overview" ), 0 ).toInt(); Q_FOREACH ( QgsLayerTreeLayer* l, mView->selectedLayerNodes() ) - l->setCustomProperty( "overview", newValue ? 0 : 1 ); + l->setCustomProperty( QStringLiteral( "overview" ), newValue ? 0 : 1 ); } void QgsLayerTreeViewDefaultActions::showFeatureCount() @@ -163,9 +163,9 @@ void QgsLayerTreeViewDefaultActions::showFeatureCount() if ( !QgsLayerTree::isLayer( node ) ) return; - int newValue = node->customProperty( "showFeatureCount", 0 ).toInt(); + int newValue = node->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt(); Q_FOREACH ( QgsLayerTreeLayer* l, mView->selectedLayerNodes() ) - l->setCustomProperty( "showFeatureCount", newValue ? 0 : 1 ); + l->setCustomProperty( QStringLiteral( "showFeatureCount" ), newValue ? 0 : 1 ); } diff --git a/src/gui/qgisgui.cpp b/src/gui/qgisgui.cpp index a6f3ede74249..51ff7b38c909 100644 --- a/src/gui/qgisgui.cpp +++ b/src/gui/qgisgui.cpp @@ -105,12 +105,12 @@ namespace QgisGui #endif QSettings settings; // where we keep last used filter in persistent state - QString lastUsedDir = settings.value( "/UI/lastSaveAsImageDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastSaveAsImageDir" ), QDir::homePath() ).toString(); // Prefer "png" format unless the user previously chose a different format - QString pngExtension = "png"; + QString pngExtension = QStringLiteral( "png" ); QString pngFilter = createFileFilter_( pngExtension ); - QString selectedFilter = settings.value( "/UI/lastSaveAsImageFilter", pngFilter ).toString(); + QString selectedFilter = settings.value( QStringLiteral( "/UI/lastSaveAsImageFilter" ), pngFilter ).toString(); QString initialPath; if ( defaultFilename.isNull() ) @@ -127,14 +127,14 @@ namespace QgisGui QString outputFileName; QString ext; #if defined(Q_OS_WIN) || defined(Q_OS_MAC) || defined(Q_OS_LINUX) - outputFileName = QFileDialog::getSaveFileName( theParent, theMessage, initialPath, QStringList( filterMap.keys() ).join( ";;" ), &selectedFilter ); + outputFileName = QFileDialog::getSaveFileName( theParent, theMessage, initialPath, QStringList( filterMap.keys() ).join( QStringLiteral( ";;" ) ), &selectedFilter ); if ( !outputFileName.isNull() ) { ext = filterMap.value( selectedFilter, QString::null ); if ( !ext.isNull() ) - settings.setValue( "/UI/lastSaveAsImageFilter", selectedFilter ); - settings.setValue( "/UI/lastSaveAsImageDir", QFileInfo( outputFileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/UI/lastSaveAsImageFilter" ), selectedFilter ); + settings.setValue( QStringLiteral( "/UI/lastSaveAsImageDir" ), QFileInfo( outputFileName ).absolutePath() ); } #else @@ -178,7 +178,7 @@ namespace QgisGui QString createFileFilter_( QString const &longName, QString const &glob ) { - return QString( "%1 (%2 %3)" ).arg( longName, glob.toLower(), glob.toUpper() ); + return QStringLiteral( "%1 (%2 %3)" ).arg( longName, glob.toLower(), glob.toUpper() ); } QString createFileFilter_( QString const &format ) diff --git a/src/gui/qgsadvanceddigitizingdockwidget.cpp b/src/gui/qgsadvanceddigitizingdockwidget.cpp index 7acdb5641424..218b7fc4c666 100644 --- a/src/gui/qgsadvanceddigitizingdockwidget.cpp +++ b/src/gui/qgsadvanceddigitizingdockwidget.cpp @@ -93,8 +93,8 @@ QgsAdvancedDigitizingDockWidget::QgsAdvancedDigitizingDockWidget( QgsMapCanvas* , mCurrentMapToolSupportsCad( false ) , mCadEnabled( false ) , mConstructionMode( false ) - , mSnappingMode(( QgsMapMouseEvent::SnappingMode ) QSettings().value( "/Cad/SnappingMode", QgsMapMouseEvent::SnapProjectConfig ).toInt() ) - , mCommonAngleConstraint( QSettings().value( "/Cad/CommonAngle", 90 ).toInt() ) + , mSnappingMode(( QgsMapMouseEvent::SnappingMode ) QSettings().value( QStringLiteral( "/Cad/SnappingMode" ), QgsMapMouseEvent::SnapProjectConfig ).toInt() ) + , mCommonAngleConstraint( QSettings().value( QStringLiteral( "/Cad/CommonAngle" ), 90 ).toInt() ) , mSnappedToVertex( false ) , mSessionActive( false ) , mErrorMessage( nullptr ) @@ -118,7 +118,7 @@ QgsAdvancedDigitizingDockWidget::QgsAdvancedDigitizingDockWidget( QgsMapCanvas* // this action is also used in the advanced digitizing tool bar mEnableAction = new QAction( this ); mEnableAction->setText( tr( "Enable advanced digitizing tools" ) ); - mEnableAction->setIcon( QgsApplication::getThemeIcon( "/cadtools/cad.svg" ) ); + mEnableAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/cadtools/cad.svg" ) ) ); mEnableAction->setCheckable( true ); mEnabledButton->addAction( mEnableAction ); mEnabledButton->setDefaultAction( mEnableAction ); @@ -164,9 +164,9 @@ QgsAdvancedDigitizingDockWidget::QgsAdvancedDigitizingDockWidget( QgsMapCanvas* mCommonAngleActions = QMap<QAction*, int>(); QList< QPair< int, QString > > commonAngles; commonAngles << QPair<int, QString>( 0, tr( "Do not snap to common angles" ) ); - commonAngles << QPair<int, QString>( 30, tr( "Snap to 30%1 angles" ).arg( QString::fromUtf8( "°" ) ) ); - commonAngles << QPair<int, QString>( 45, tr( "Snap to 45%1 angles" ).arg( QString::fromUtf8( "°" ) ) ); - commonAngles << QPair<int, QString>( 90, tr( "Snap to 90%1 angles" ).arg( QString::fromUtf8( "°" ) ) ); + commonAngles << QPair<int, QString>( 30, tr( "Snap to 30%1 angles" ).arg( QStringLiteral( "°" ) ) ); + commonAngles << QPair<int, QString>( 45, tr( "Snap to 45%1 angles" ).arg( QStringLiteral( "°" ) ) ); + commonAngles << QPair<int, QString>( 90, tr( "Snap to 90%1 angles" ).arg( QStringLiteral( "°" ) ) ); for ( QList< QPair< int, QString > >::const_iterator it = commonAngles.begin(); it != commonAngles.end(); ++it ) { QAction* action = new QAction( it->second, menu ); @@ -301,7 +301,7 @@ void QgsAdvancedDigitizingDockWidget::settingsButtonTriggered( QAction* action ) { isn.key()->setChecked( true ); mSnappingMode = isn.value(); - QSettings().setValue( "/Cad/SnappingMode", ( int )isn.value() ); + QSettings().setValue( QStringLiteral( "/Cad/SnappingMode" ), ( int )isn.value() ); return; } @@ -311,7 +311,7 @@ void QgsAdvancedDigitizingDockWidget::settingsButtonTriggered( QAction* action ) { ica.key()->setChecked( true ); mCommonAngleConstraint = ica.value(); - QSettings().setValue( "/Cad/CommonAngle", ica.value() ); + QSettings().setValue( QStringLiteral( "/Cad/CommonAngle" ), ica.value() ); return; } } diff --git a/src/gui/qgsannotationitem.cpp b/src/gui/qgsannotationitem.cpp index 637aa516b729..1e4c37df302f 100644 --- a/src/gui/qgsannotationitem.cpp +++ b/src/gui/qgsannotationitem.cpp @@ -261,7 +261,7 @@ void QgsAnnotationItem::drawSelectionBoxes( QPainter* p ) const } //no selection boxes for composer mode - if ( data( 1 ).toString() == "composer" ) + if ( data( 1 ).toString() == QLatin1String( "composer" ) ) { return; } @@ -412,28 +412,28 @@ void QgsAnnotationItem::_writeXml( QDomDocument& doc, QDomElement& itemElem ) co { return; } - QDomElement annotationElem = doc.createElement( "AnnotationItem" ); - annotationElem.setAttribute( "mapPositionFixed", mMapPositionFixed ); - annotationElem.setAttribute( "mapPosX", qgsDoubleToString( mMapPosition.x() ) ); - annotationElem.setAttribute( "mapPosY", qgsDoubleToString( mMapPosition.y() ) ); + QDomElement annotationElem = doc.createElement( QStringLiteral( "AnnotationItem" ) ); + annotationElem.setAttribute( QStringLiteral( "mapPositionFixed" ), mMapPositionFixed ); + annotationElem.setAttribute( QStringLiteral( "mapPosX" ), qgsDoubleToString( mMapPosition.x() ) ); + annotationElem.setAttribute( QStringLiteral( "mapPosY" ), qgsDoubleToString( mMapPosition.y() ) ); if ( mMapPositionCrs.isValid() ) mMapPositionCrs.writeXml( annotationElem, doc ); - annotationElem.setAttribute( "offsetX", qgsDoubleToString( mOffsetFromReferencePoint.x() ) ); - annotationElem.setAttribute( "offsetY", qgsDoubleToString( mOffsetFromReferencePoint.y() ) ); - annotationElem.setAttribute( "frameWidth", qgsDoubleToString( mFrameSize.width() ) ); - annotationElem.setAttribute( "frameHeight", qgsDoubleToString( mFrameSize.height() ) ); + annotationElem.setAttribute( QStringLiteral( "offsetX" ), qgsDoubleToString( mOffsetFromReferencePoint.x() ) ); + annotationElem.setAttribute( QStringLiteral( "offsetY" ), qgsDoubleToString( mOffsetFromReferencePoint.y() ) ); + annotationElem.setAttribute( QStringLiteral( "frameWidth" ), qgsDoubleToString( mFrameSize.width() ) ); + annotationElem.setAttribute( QStringLiteral( "frameHeight" ), qgsDoubleToString( mFrameSize.height() ) ); QPointF canvasPos = pos(); - annotationElem.setAttribute( "canvasPosX", qgsDoubleToString( canvasPos.x() ) ); - annotationElem.setAttribute( "canvasPosY", qgsDoubleToString( canvasPos.y() ) ); - annotationElem.setAttribute( "frameBorderWidth", qgsDoubleToString( mFrameBorderWidth ) ); - annotationElem.setAttribute( "frameColor", mFrameColor.name() ); - annotationElem.setAttribute( "frameColorAlpha", mFrameColor.alpha() ); - annotationElem.setAttribute( "frameBackgroundColor", mFrameBackgroundColor.name() ); - annotationElem.setAttribute( "frameBackgroundColorAlpha", mFrameBackgroundColor.alpha() ); - annotationElem.setAttribute( "visible", isVisible() ); + annotationElem.setAttribute( QStringLiteral( "canvasPosX" ), qgsDoubleToString( canvasPos.x() ) ); + annotationElem.setAttribute( QStringLiteral( "canvasPosY" ), qgsDoubleToString( canvasPos.y() ) ); + annotationElem.setAttribute( QStringLiteral( "frameBorderWidth" ), qgsDoubleToString( mFrameBorderWidth ) ); + annotationElem.setAttribute( QStringLiteral( "frameColor" ), mFrameColor.name() ); + annotationElem.setAttribute( QStringLiteral( "frameColorAlpha" ), mFrameColor.alpha() ); + annotationElem.setAttribute( QStringLiteral( "frameBackgroundColor" ), mFrameBackgroundColor.name() ); + annotationElem.setAttribute( QStringLiteral( "frameBackgroundColorAlpha" ), mFrameBackgroundColor.alpha() ); + annotationElem.setAttribute( QStringLiteral( "visible" ), isVisible() ); if ( mMarkerSymbol ) { - QDomElement symbolElem = QgsSymbolLayerUtils::saveSymbol( "marker symbol", mMarkerSymbol, doc ); + QDomElement symbolElem = QgsSymbolLayerUtils::saveSymbol( QStringLiteral( "marker symbol" ), mMarkerSymbol, doc ); if ( !symbolElem.isNull() ) { annotationElem.appendChild( symbolElem ); @@ -450,12 +450,12 @@ void QgsAnnotationItem::_readXml( const QDomDocument& doc, const QDomElement& an return; } QPointF pos; - pos.setX( annotationElem.attribute( "canvasPosX", "0" ).toDouble() ); - pos.setY( annotationElem.attribute( "canvasPosY", "0" ).toDouble() ); + pos.setX( annotationElem.attribute( QStringLiteral( "canvasPosX" ), QStringLiteral( "0" ) ).toDouble() ); + pos.setY( annotationElem.attribute( QStringLiteral( "canvasPosY" ), QStringLiteral( "0" ) ).toDouble() ); setPos( pos ); QgsPoint mapPos; - mapPos.setX( annotationElem.attribute( "mapPosX", "0" ).toDouble() ); - mapPos.setY( annotationElem.attribute( "mapPosY", "0" ).toDouble() ); + mapPos.setX( annotationElem.attribute( QStringLiteral( "mapPosX" ), QStringLiteral( "0" ) ).toDouble() ); + mapPos.setY( annotationElem.attribute( QStringLiteral( "mapPosY" ), QStringLiteral( "0" ) ).toDouble() ); mMapPosition = mapPos; if ( !mMapPositionCrs.readXml( annotationElem ) ) @@ -463,20 +463,20 @@ void QgsAnnotationItem::_readXml( const QDomDocument& doc, const QDomElement& an mMapPositionCrs = mMapCanvas->mapSettings().destinationCrs(); } - mFrameBorderWidth = annotationElem.attribute( "frameBorderWidth", "0.5" ).toDouble(); - mFrameColor.setNamedColor( annotationElem.attribute( "frameColor", "#000000" ) ); - mFrameColor.setAlpha( annotationElem.attribute( "frameColorAlpha", "255" ).toInt() ); - mFrameBackgroundColor.setNamedColor( annotationElem.attribute( "frameBackgroundColor" ) ); - mFrameBackgroundColor.setAlpha( annotationElem.attribute( "frameBackgroundColorAlpha", "255" ).toInt() ); - mFrameSize.setWidth( annotationElem.attribute( "frameWidth", "50" ).toDouble() ); - mFrameSize.setHeight( annotationElem.attribute( "frameHeight", "50" ).toDouble() ); - mOffsetFromReferencePoint.setX( annotationElem.attribute( "offsetX", "0" ).toDouble() ); - mOffsetFromReferencePoint.setY( annotationElem.attribute( "offsetY", "0" ).toDouble() ); - mMapPositionFixed = annotationElem.attribute( "mapPositionFixed", "1" ).toInt(); - setVisible( annotationElem.attribute( "visible", "1" ).toInt() ); + mFrameBorderWidth = annotationElem.attribute( QStringLiteral( "frameBorderWidth" ), QStringLiteral( "0.5" ) ).toDouble(); + mFrameColor.setNamedColor( annotationElem.attribute( QStringLiteral( "frameColor" ), QStringLiteral( "#000000" ) ) ); + mFrameColor.setAlpha( annotationElem.attribute( QStringLiteral( "frameColorAlpha" ), QStringLiteral( "255" ) ).toInt() ); + mFrameBackgroundColor.setNamedColor( annotationElem.attribute( QStringLiteral( "frameBackgroundColor" ) ) ); + mFrameBackgroundColor.setAlpha( annotationElem.attribute( QStringLiteral( "frameBackgroundColorAlpha" ), QStringLiteral( "255" ) ).toInt() ); + mFrameSize.setWidth( annotationElem.attribute( QStringLiteral( "frameWidth" ), QStringLiteral( "50" ) ).toDouble() ); + mFrameSize.setHeight( annotationElem.attribute( QStringLiteral( "frameHeight" ), QStringLiteral( "50" ) ).toDouble() ); + mOffsetFromReferencePoint.setX( annotationElem.attribute( QStringLiteral( "offsetX" ), QStringLiteral( "0" ) ).toDouble() ); + mOffsetFromReferencePoint.setY( annotationElem.attribute( QStringLiteral( "offsetY" ), QStringLiteral( "0" ) ).toDouble() ); + mMapPositionFixed = annotationElem.attribute( QStringLiteral( "mapPositionFixed" ), QStringLiteral( "1" ) ).toInt(); + setVisible( annotationElem.attribute( QStringLiteral( "visible" ), QStringLiteral( "1" ) ).toInt() ); //marker symbol - QDomElement symbolElem = annotationElem.firstChildElement( "symbol" ); + QDomElement symbolElem = annotationElem.firstChildElement( QStringLiteral( "symbol" ) ); if ( !symbolElem.isNull() ) { QgsMarkerSymbol* symbol = QgsSymbolLayerUtils::loadSymbol<QgsMarkerSymbol>( symbolElem ); diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 59ff500f8354..a6be3ed3f795 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -394,7 +394,7 @@ void QgsAttributeForm::resetMultiEdit( bool promptToSave ) void QgsAttributeForm::multiEditMessageClicked( const QString& link ) { clearMultiEditMessages(); - resetMultiEdit( link == "#apply" ); + resetMultiEdit( link == QLatin1String( "#apply" ) ); } void QgsAttributeForm::filterTriggered() @@ -629,7 +629,7 @@ QString QgsAttributeForm::createFilterExpression() const if ( filters.isEmpty() ) return QString(); - QString filter = filters.join( ") AND (" ).prepend( '(' ).append( ')' ); + QString filter = filters.join( QStringLiteral( ") AND (" ) ).prepend( '(' ).append( ')' ); return filter; } @@ -688,12 +688,12 @@ void QgsAttributeForm::onAttributeChanged( const QVariant& value ) if ( value.isNull() ) { // not good - buddy->setText( QString( "%1<font color=\"red\">❌</font>" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1<font color=\"red\">❌</font>" ).arg( text ) ); } else { // good - buddy->setText( QString( "%1<font color=\"green\">✔</font>" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1<font color=\"green\">✔</font>" ).arg( text ) ); } } } @@ -793,9 +793,9 @@ void QgsAttributeForm::displayInvalidConstraintMessage( const QStringList& f, int size = f.size() > max ? max : f.size(); QString descriptions; for ( int i = 0; i < size; i++ ) - descriptions += QString( "<li>%1: <i>%2</i></li>" ).arg( f[i], d[i] ); + descriptions += QStringLiteral( "<li>%1: <i>%2</i></li>" ).arg( f[i], d[i] ); - QString msg = QString( "<b>%1</b><ul>%2</ul>" ).arg( tr( "Invalid fields" ), descriptions ) ; + QString msg = QStringLiteral( "<b>%1</b><ul>%2</ul>" ).arg( tr( "Invalid fields" ), descriptions ) ; mInvalidConstraintMessage->setText( msg ); mTopMessageWidget->show(); @@ -914,12 +914,12 @@ void QgsAttributeForm::onConstraintStatusChanged( const QString& constraint, if ( !ok ) { // not good - buddy->setText( QString( "%1<font color=\"red\">*</font>" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1<font color=\"red\">*</font>" ).arg( text ) ); } else { // good - buddy->setText( QString( "%1<font color=\"green\">*</font>" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1<font color=\"green\">*</font>" ).arg( text ) ); } } } @@ -1058,7 +1058,7 @@ void QgsAttributeForm::init() mTopMessageWidget->hide(); mTopMessageWidget->setLayout( new QHBoxLayout() ); - QSvgWidget* warningIcon = new QSvgWidget( QgsApplication::iconPath( "/mIconWarning.svg" ) ); + QSvgWidget* warningIcon = new QSvgWidget( QgsApplication::iconPath( QStringLiteral( "/mIconWarning.svg" ) ) ); warningIcon->setFixedSize( 48, 48 ); mTopMessageWidget->layout()->addWidget( warningIcon ); mInvalidConstraintMessage = new QLabel( this ); @@ -1234,7 +1234,7 @@ void QgsAttributeForm::init() const QgsEditorWidgetSetup widgetSetup = QgsEditorWidgetRegistry::instance()->findBest( mLayer, field.name() ); - if ( widgetSetup.type() == "Hidden" ) + if ( widgetSetup.type() == QLatin1String( "Hidden" ) ) continue; bool labelOnTop = mLayer->editFormConfig().labelOnTop( idx ); @@ -1255,7 +1255,7 @@ void QgsAttributeForm::init() } else { - w = new QLabel( QString( "<p style=\"color: red; font-style: italic;\">Failed to create widget with type '%1'</p>" ).arg( widgetSetup.type() ) ); + w = new QLabel( QStringLiteral( "<p style=\"color: red; font-style: italic;\">Failed to create widget with type '%1'</p>" ).arg( widgetSetup.type() ) ); } @@ -1299,7 +1299,7 @@ void QgsAttributeForm::init() if ( !mButtonBox ) { mButtonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel ); - mButtonBox->setObjectName( "buttonBox" ); + mButtonBox->setObjectName( QStringLiteral( "buttonBox" ) ); layout->addWidget( mButtonBox, layout->rowCount(), 0, 1, layout->columnCount() ); } mButtonBox->setVisible( buttonBoxVisible ); @@ -1311,7 +1311,7 @@ void QgsAttributeForm::init() boxLayout->setMargin( 0 ); boxLayout->setContentsMargins( 0, 0, 0, 0 ); mSearchButtonBox->setLayout( boxLayout ); - mSearchButtonBox->setObjectName( "searchButtonBox" ); + mSearchButtonBox->setObjectName( QStringLiteral( "searchButtonBox" ) ); QPushButton* clearButton = new QPushButton( tr( "&Reset form" ), mSearchButtonBox ); connect( clearButton, SIGNAL( clicked( bool ) ), this, SLOT( resetSearch() ) ); @@ -1393,7 +1393,7 @@ void QgsAttributeForm::cleanPython() { if ( !mPyFormVarName.isNull() ) { - QString expr = QString( "if locals().has_key('%1'): del %1\n" ).arg( mPyFormVarName ); + QString expr = QStringLiteral( "if locals().has_key('%1'): del %1\n" ).arg( mPyFormVarName ); QgsPythonRunner::run( expr ); } } @@ -1428,12 +1428,12 @@ void QgsAttributeForm::initPython() } else // The file couldn't be opened { - QgsLogger::warning( QString( "The external python file path %1 could not be opened!" ).arg( initFilePath ) ); + QgsLogger::warning( QStringLiteral( "The external python file path %1 could not be opened!" ).arg( initFilePath ) ); } } else { - QgsLogger::warning( QString( "The external python file path is empty!" ) ); + QgsLogger::warning( QStringLiteral( "The external python file path is empty!" ) ); } break; @@ -1441,7 +1441,7 @@ void QgsAttributeForm::initPython() initCode = mLayer->editFormConfig().initCode(); if ( initCode.isEmpty() ) { - QgsLogger::warning( QString( "The python code provided in the dialog is empty!" ) ); + QgsLogger::warning( QStringLiteral( "The python code provided in the dialog is empty!" ) ); } break; @@ -1458,16 +1458,16 @@ void QgsAttributeForm::initPython() QgsPythonRunner::run( initCode ); } - QgsPythonRunner::run( "import inspect" ); + QgsPythonRunner::run( QStringLiteral( "import inspect" ) ); QString numArgs; // Check for eval result - if ( QgsPythonRunner::eval( QString( "len(inspect.getargspec(%1)[0])" ).arg( initFunction ), numArgs ) ) + if ( QgsPythonRunner::eval( QStringLiteral( "len(inspect.getargspec(%1)[0])" ).arg( initFunction ), numArgs ) ) { static int sFormId = 0; - mPyFormVarName = QString( "_qgis_featureform_%1_%2" ).arg( mFormNr ).arg( sFormId++ ); + mPyFormVarName = QStringLiteral( "_qgis_featureform_%1_%2" ).arg( mFormNr ).arg( sFormId++ ); - QString form = QString( "%1 = sip.wrapinstance( %2, qgis.gui.QgsAttributeForm )" ) + QString form = QStringLiteral( "%1 = sip.wrapinstance( %2, qgis.gui.QgsAttributeForm )" ) .arg( mPyFormVarName ) .arg(( unsigned long ) this ); @@ -1476,7 +1476,7 @@ void QgsAttributeForm::initPython() QgsDebugMsg( QString( "running featureForm init: %1" ).arg( mPyFormVarName ) ); // Legacy - if ( numArgs == "3" ) + if ( numArgs == QLatin1String( "3" ) ) { addInterface( new QgsAttributeFormLegacyInterface( initFunction, mPyFormVarName, this ) ); } @@ -1896,7 +1896,7 @@ void QgsAttributeForm::setMessageBar( QgsMessageBar* messageBar ) int QgsAttributeForm::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } void QgsAttributeForm::ContainerInformation::apply( QgsExpressionContext* expressionContext ) diff --git a/src/gui/qgsattributeformeditorwidget.cpp b/src/gui/qgsattributeformeditorwidget.cpp index e26550f5d400..fd27429f217f 100644 --- a/src/gui/qgsattributeformeditorwidget.cpp +++ b/src/gui/qgsattributeformeditorwidget.cpp @@ -199,14 +199,14 @@ QString QgsAttributeFormEditorWidget::currentFilterExpression() const // special case: Between search QString filter1 = mSearchWidgets.at( 0 )->createExpression( QgsSearchWidgetWrapper::GreaterThanOrEqualTo ); QString filter2 = mSearchWidgets.at( 1 )->createExpression( QgsSearchWidgetWrapper::LessThanOrEqualTo ); - return QString( "%1 AND %2" ).arg( filter1, filter2 ); + return QStringLiteral( "%1 AND %2" ).arg( filter1, filter2 ); } else if ( mSearchWidgetToolButton->activeFlags() & QgsSearchWidgetWrapper::IsNotBetween ) { // special case: Is Not Between search QString filter1 = mSearchWidgets.at( 0 )->createExpression( QgsSearchWidgetWrapper::LessThan ); QString filter2 = mSearchWidgets.at( 1 )->createExpression( QgsSearchWidgetWrapper::GreaterThan ); - return QString( "%1 OR %2" ).arg( filter1, filter2 ); + return QStringLiteral( "%1 OR %2" ).arg( filter1, filter2 ); } return mSearchWidgets.at( 0 )->createExpression( mSearchWidgetToolButton->activeFlags() ); diff --git a/src/gui/qgsattributeformlegacyinterface.cpp b/src/gui/qgsattributeformlegacyinterface.cpp index f946317e7305..a5b110767d08 100644 --- a/src/gui/qgsattributeformlegacyinterface.cpp +++ b/src/gui/qgsattributeformlegacyinterface.cpp @@ -28,10 +28,10 @@ QgsAttributeFormLegacyInterface::QgsAttributeFormLegacyInterface( const QString& , mPyFormVarName( pyFormName ) { static int sLayerCounter = 0; - mPyLayerVarName = QString( "_qgis_layer_%1_%2" ).arg( form->layer()->id() ).arg( sLayerCounter++ ); - mPyLayerVarName.replace( QRegExp( "[^a-zA-Z0-9_]" ), "_" ); // clean identifier + mPyLayerVarName = QStringLiteral( "_qgis_layer_%1_%2" ).arg( form->layer()->id() ).arg( sLayerCounter++ ); + mPyLayerVarName.replace( QRegExp( "[^a-zA-Z0-9_]" ), QStringLiteral( "_" ) ); // clean identifier - QString initLayer = QString( "%1 = sip.wrapinstance( %2, qgis.core.QgsVectorLayer )" ) + QString initLayer = QStringLiteral( "%1 = sip.wrapinstance( %2, qgis.core.QgsVectorLayer )" ) .arg( mPyLayerVarName ) .arg(( unsigned long ) form->layer() ); @@ -40,7 +40,7 @@ QgsAttributeFormLegacyInterface::QgsAttributeFormLegacyInterface( const QString& QgsAttributeFormLegacyInterface::~QgsAttributeFormLegacyInterface() { - QString delLayer = QString( "del %1" ).arg( mPyLayerVarName ); + QString delLayer = QStringLiteral( "del %1" ).arg( mPyLayerVarName ); QgsPythonRunner::run( delLayer ); } @@ -58,14 +58,14 @@ void QgsAttributeFormLegacyInterface::featureChanged() // Generate the unique ID of this feature. We used to use feature ID but some providers // return a ID that is an invalid python variable when we have new unsaved features. QDateTime dt = QDateTime::currentDateTime(); - QString pyFeatureVarName = QString( "_qgis_feature_%1" ).arg( dt.toString( "yyyyMMddhhmmsszzz" ) ); - QString initFeature = QString( "%1 = sip.wrapinstance( %2, qgis.core.QgsFeature )" ) + QString pyFeatureVarName = QStringLiteral( "_qgis_feature_%1" ).arg( dt.toString( QStringLiteral( "yyyyMMddhhmmsszzz" ) ) ); + QString initFeature = QStringLiteral( "%1 = sip.wrapinstance( %2, qgis.core.QgsFeature )" ) .arg( pyFeatureVarName ) .arg(( unsigned long ) & form()->feature() ); QgsPythonRunner::run( initFeature ); - QString expr = QString( "%1( %2, %3, %4)" ) + QString expr = QStringLiteral( "%1( %2, %3, %4)" ) .arg( mPyFunctionName, mPyFormVarName, mPyLayerVarName, @@ -73,6 +73,6 @@ void QgsAttributeFormLegacyInterface::featureChanged() QgsPythonRunner::run( expr ); - QString delFeature = QString( "del %1" ).arg( pyFeatureVarName ); + QString delFeature = QStringLiteral( "del %1" ).arg( pyFeatureVarName ); QgsPythonRunner::run( delFeature ); } diff --git a/src/gui/qgsblendmodecombobox.cpp b/src/gui/qgsblendmodecombobox.cpp index 8960f4be8e20..1f6f86c3320e 100644 --- a/src/gui/qgsblendmodecombobox.cpp +++ b/src/gui/qgsblendmodecombobox.cpp @@ -42,20 +42,20 @@ QgsBlendModeComboBox::~QgsBlendModeComboBox() QStringList QgsBlendModeComboBox::blendModesList() const { return QStringList() << tr( "Normal" ) - << "-" + << QStringLiteral( "-" ) << tr( "Lighten" ) << tr( "Screen" ) << tr( "Dodge" ) << tr( "Addition" ) - << "-" + << QStringLiteral( "-" ) << tr( "Darken" ) << tr( "Multiply" ) << tr( "Burn" ) - << "-" + << QStringLiteral( "-" ) << tr( "Overlay" ) << tr( "Soft light" ) << tr( "Hard light" ) - << "-" + << QStringLiteral( "-" ) << tr( "Difference" ) << tr( "Subtract" ); } @@ -79,7 +79,7 @@ void QgsBlendModeComboBox::updateModes() int blendModeIndex = 0; for ( ; blendModeIt != myBlendModesList.constEnd(); ++blendModeIt ) { - if ( *blendModeIt == "-" ) + if ( *blendModeIt == QLatin1String( "-" ) ) { // Add separator insertSeparator( index ); diff --git a/src/gui/qgsbrowsertreeview.cpp b/src/gui/qgsbrowsertreeview.cpp index dfdae0658eec..208b3eeee6fe 100644 --- a/src/gui/qgsbrowsertreeview.cpp +++ b/src/gui/qgsbrowsertreeview.cpp @@ -23,7 +23,7 @@ QgsBrowserTreeView::QgsBrowserTreeView( QWidget *parent ) : QTreeView( parent ) - , mSettingsSection( "browser" ) + , mSettingsSection( QStringLiteral( "browser" ) ) { } @@ -92,7 +92,7 @@ void QgsBrowserTreeView::restoreState() else { // expand root favourites item - QModelIndex index = QgsBrowserModel::findPath( model(), "favourites:" ); + QModelIndex index = QgsBrowserModel::findPath( model(), QStringLiteral( "favourites:" ) ); expand( index ); } } @@ -175,7 +175,7 @@ void QgsBrowserTreeView::rowsInserted( const QModelIndex & parentIndex, int star QModelIndex childIndex = model()->index( i, 0, parentIndex ); QString childPath = model()->data( childIndex, QgsBrowserModel::PathRole ).toString(); QString escapedChildPath = childPath; - escapedChildPath.replace( '|', "\\|" ); + escapedChildPath.replace( '|', QLatin1String( "\\|" ) ); QgsDebugMsgLevel( "childPath = " + childPath + " escapedChildPath = " + escapedChildPath, 2 ); if ( mExpandPaths.contains( childPath ) || mExpandPaths.indexOf( QRegExp( "^" + escapedChildPath + "/.*" ) ) != -1 ) diff --git a/src/gui/qgsbusyindicatordialog.h b/src/gui/qgsbusyindicatordialog.h index bf17c945116c..5765601f0fe4 100644 --- a/src/gui/qgsbusyindicatordialog.h +++ b/src/gui/qgsbusyindicatordialog.h @@ -38,7 +38,7 @@ class GUI_EXPORT QgsBusyIndicatorDialog : public QDialog * @param parent parent object (owner) * @param fl widget flags */ - QgsBusyIndicatorDialog( const QString& message = "", QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); + QgsBusyIndicatorDialog( const QString& message = QStringLiteral( "" ), QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); ~QgsBusyIndicatorDialog(); QString message() const { return mMessage; } diff --git a/src/gui/qgscharacterselectdialog.cpp b/src/gui/qgscharacterselectdialog.cpp index 1c4c2d97bb39..09aed07df261 100644 --- a/src/gui/qgscharacterselectdialog.cpp +++ b/src/gui/qgscharacterselectdialog.cpp @@ -34,7 +34,7 @@ QgsCharacterSelectorDialog::~QgsCharacterSelectorDialog() const QChar& QgsCharacterSelectorDialog::selectCharacter( bool* gotChar, const QFont& font, const QString& style ) { - mCharSelectLabelFont->setText( QString( "%1 %2" ).arg( font.family(), style ) ); + mCharSelectLabelFont->setText( QStringLiteral( "%1 %2" ).arg( font.family(), style ) ); mCharWidget->updateFont( font ); mCharWidget->updateStyle( style ); mCharWidget->updateSize( 22.0 ); diff --git a/src/gui/qgscodeeditor.cpp b/src/gui/qgscodeeditor.cpp index d533fdc39fe0..374319fe21bd 100644 --- a/src/gui/qgscodeeditor.cpp +++ b/src/gui/qgscodeeditor.cpp @@ -30,7 +30,7 @@ QgsCodeEditor::QgsCodeEditor( QWidget *parent, const QString& title, bool foldin { if ( !parent && mWidgetTitle.isEmpty() ) { - setWindowTitle( "Text Editor" ); + setWindowTitle( QStringLiteral( "Text Editor" ) ); } else { @@ -121,10 +121,10 @@ void QgsCodeEditor::setMarginVisible( bool margin ) mMargin = margin; if ( margin ) { - QFont marginFont( "Courier", 10 ); + QFont marginFont( QStringLiteral( "Courier" ), 10 ); setMarginLineNumbers( 1, true ); setMarginsFont( marginFont ); - setMarginWidth( 1, "00000" ); + setMarginWidth( 1, QStringLiteral( "00000" ) ); setMarginsForegroundColor( QColor( "#3E3EE3" ) ); setMarginsBackgroundColor( QColor( "#f9f9f9" ) ); } @@ -175,8 +175,8 @@ bool QgsCodeEditor::isFixedPitch( const QFont& font ) QFont QgsCodeEditor::getMonospaceFont() { QSettings settings; - QString loadFont = settings.value( "pythonConsole/fontfamilytextEditor", "Monospace" ).toString(); - int fontSize = settings.value( "pythonConsole/fontsizeEditor", 10 ).toInt(); + QString loadFont = settings.value( QStringLiteral( "pythonConsole/fontfamilytextEditor" ), "Monospace" ).toString(); + int fontSize = settings.value( QStringLiteral( "pythonConsole/fontsizeEditor" ), 10 ).toInt(); QFont font( loadFont ); font.setFixedPitch( true ); diff --git a/src/gui/qgscodeeditor.h b/src/gui/qgscodeeditor.h index 16ddbf346e25..c06e0e9ed0a8 100644 --- a/src/gui/qgscodeeditor.h +++ b/src/gui/qgscodeeditor.h @@ -43,7 +43,7 @@ class GUI_EXPORT QgsCodeEditor : public QsciScintilla * @param margin false: Enable margin for code editor * @note added in 2.6 */ - QgsCodeEditor( QWidget *parent = nullptr, const QString& title = "", bool folding = false, bool margin = false ); + QgsCodeEditor( QWidget *parent = nullptr, const QString& title = QLatin1String( "" ), bool folding = false, bool margin = false ); ~QgsCodeEditor(); /** Set the widget title diff --git a/src/gui/qgscodeeditorcss.cpp b/src/gui/qgscodeeditorcss.cpp index c0996027b010..0d5f4571f5ec 100644 --- a/src/gui/qgscodeeditorcss.cpp +++ b/src/gui/qgscodeeditorcss.cpp @@ -41,7 +41,7 @@ QgsCodeEditorCSS::~QgsCodeEditorCSS() void QgsCodeEditorCSS::setSciLexerCSS() { QsciLexerCSS* lexer = new QsciLexerCSS( this ); - lexer->setDefaultFont( QFont( "Sans", 10 ) ); + lexer->setDefaultFont( QFont( QStringLiteral( "Sans" ), 10 ) ); setLexer( lexer ); } diff --git a/src/gui/qgscodeeditorhtml.cpp b/src/gui/qgscodeeditorhtml.cpp index ec92b29e4d34..cdacebbba9ce 100644 --- a/src/gui/qgscodeeditorhtml.cpp +++ b/src/gui/qgscodeeditorhtml.cpp @@ -41,7 +41,7 @@ QgsCodeEditorHTML::~QgsCodeEditorHTML() void QgsCodeEditorHTML::setSciLexerHTML() { QsciLexerHTML* lexer = new QsciLexerHTML( this ); - lexer->setDefaultFont( QFont( "Sans", 10 ) ); + lexer->setDefaultFont( QFont( QStringLiteral( "Sans" ), 10 ) ); setLexer( lexer ); } diff --git a/src/gui/qgscodeeditorpython.cpp b/src/gui/qgscodeeditorpython.cpp index d13bf8892319..3e112b39b9d8 100644 --- a/src/gui/qgscodeeditorpython.cpp +++ b/src/gui/qgscodeeditorpython.cpp @@ -72,7 +72,7 @@ void QgsCodeEditorPython::setSciLexerPython() mPapFile = QgsApplication::pkgDataPath() + "/python/qsci_apis/pyqgis.pap"; apis->loadPrepared( mPapFile ); } - else if ( mAPISFilesList.length() == 1 && mAPISFilesList[0].right( 3 ) == "pap" ) + else if ( mAPISFilesList.length() == 1 && mAPISFilesList[0].right( 3 ) == QLatin1String( "pap" ) ) { if ( !QFileInfo::exists( mAPISFilesList[0] ) ) { diff --git a/src/gui/qgscollapsiblegroupbox.cpp b/src/gui/qgscollapsiblegroupbox.cpp index 3e2775165b0f..625884d64cbe 100644 --- a/src/gui/qgscollapsiblegroupbox.cpp +++ b/src/gui/qgscollapsiblegroupbox.cpp @@ -54,18 +54,18 @@ void QgsCollapsibleGroupBoxBasic::init() mShown = false; mParentScrollArea = nullptr; mSyncParent = nullptr; - mSyncGroup = ""; + mSyncGroup = QLatin1String( "" ); mAltDown = false; mShiftDown = false; mTitleClicked = false; // init icons - mCollapseIcon = QgsApplication::getThemeIcon( "/mIconCollapse.png" ); - mExpandIcon = QgsApplication::getThemeIcon( "/mIconExpand.png" ); + mCollapseIcon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconCollapse.png" ) ); + mExpandIcon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpand.png" ) ); // collapse button mCollapseButton = new QgsGroupBoxCollapseButton( this ); - mCollapseButton->setObjectName( "collapseButton" ); + mCollapseButton->setObjectName( QStringLiteral( "collapseButton" ) ); mCollapseButton->setAutoRaise( true ); mCollapseButton->setFixedSize( 16, 16 ); // TODO set size (as well as margins) depending on theme, in updateStyle() @@ -305,7 +305,7 @@ void QgsCollapsibleGroupBoxBasic::updateStyle() QSettings settings; // NOTE: QGIS-Style groupbox styled in app stylesheet - bool usingQgsStyle = settings.value( "qgis/stylesheet/groupBoxCustom", QVariant( false ) ).toBool(); + bool usingQgsStyle = settings.value( QStringLiteral( "qgis/stylesheet/groupBoxCustom" ), QVariant( false ) ).toBool(); QStyleOptionGroupBox box; initStyleOption( &box ); @@ -317,7 +317,7 @@ void QgsCollapsibleGroupBoxBasic::updateStyle() int marginLeft = 20; // title margin for disclosure triangle int marginRight = 5; // a little bit of space on the right, to match space on the left int offsetLeft = 0; // offset for oxygen theme - int offsetStyle = QApplication::style()->objectName().contains( "macintosh" ) ? ( usingQgsStyle ? 1 : 8 ) : 0; + int offsetStyle = QApplication::style()->objectName().contains( QLatin1String( "macintosh" ) ) ? ( usingQgsStyle ? 1 : 8 ) : 0; int topBuffer = ( usingQgsStyle ? 3 : 1 ) + offsetStyle; // space between top of title or triangle and widget above int offsetTop = topBuffer; int offsetTopTri = topBuffer; // offset for triangle @@ -334,7 +334,7 @@ void QgsCollapsibleGroupBoxBasic::updateStyle() // calculate offset if frame overlaps triangle (oxygen theme) // using an offset of 6 pixels from frame border - if ( QApplication::style()->objectName().toLower() == "oxygen" ) + if ( QApplication::style()->objectName().toLower() == QLatin1String( "oxygen" ) ) { QStyleOptionGroupBox box; initStyleOption( &box ); @@ -366,31 +366,31 @@ void QgsCollapsibleGroupBoxBasic::updateStyle() // customize style sheet for collapse/expand button and force left-aligned title QString ss; - if ( usingQgsStyle || QApplication::style()->objectName().contains( "macintosh" ) ) + if ( usingQgsStyle || QApplication::style()->objectName().contains( QLatin1String( "macintosh" ) ) ) { - ss += "QgsCollapsibleGroupBoxBasic, QgsCollapsibleGroupBox {"; - ss += QString( " margin-top: %1px;" ).arg( topBuffer + ( usingQgsStyle ? rectTitle.height() + 5 : rectFrame.top() ) ); + ss += QLatin1String( "QgsCollapsibleGroupBoxBasic, QgsCollapsibleGroupBox {" ); + ss += QStringLiteral( " margin-top: %1px;" ).arg( topBuffer + ( usingQgsStyle ? rectTitle.height() + 5 : rectFrame.top() ) ); ss += '}'; } - ss += "QgsCollapsibleGroupBoxBasic::title, QgsCollapsibleGroupBox::title {"; - ss += " subcontrol-origin: margin;"; - ss += " subcontrol-position: top left;"; - ss += QString( " margin-left: %1px;" ).arg( marginLeft ); - ss += QString( " margin-right: %1px;" ).arg( marginRight ); - ss += QString( " left: %1px;" ).arg( offsetLeft ); - ss += QString( " top: %1px;" ).arg( offsetTop ); - if ( QApplication::style()->objectName().contains( "macintosh" ) ) + ss += QLatin1String( "QgsCollapsibleGroupBoxBasic::title, QgsCollapsibleGroupBox::title {" ); + ss += QLatin1String( " subcontrol-origin: margin;" ); + ss += QLatin1String( " subcontrol-position: top left;" ); + ss += QStringLiteral( " margin-left: %1px;" ).arg( marginLeft ); + ss += QStringLiteral( " margin-right: %1px;" ).arg( marginRight ); + ss += QStringLiteral( " left: %1px;" ).arg( offsetLeft ); + ss += QStringLiteral( " top: %1px;" ).arg( offsetTop ); + if ( QApplication::style()->objectName().contains( QLatin1String( "macintosh" ) ) ) { - ss += " background-color: rgba(0,0,0,0)"; + ss += QLatin1String( " background-color: rgba(0,0,0,0)" ); } ss += '}'; setStyleSheet( ss ); // clear toolbutton default background and border and apply offset QString ssd; - ssd = QString( "QgsCollapsibleGroupBoxBasic > QToolButton#%1, QgsCollapsibleGroupBox > QToolButton#%1 {" ).arg( mCollapseButton->objectName() ); - ssd += " background-color: rgba(255, 255, 255, 0); border: none;"; - ssd += QString( "} QgsCollapsibleGroupBoxBasic > QToolButton#%1:focus, QgsCollapsibleGroupBox > QToolButton#%1:focus { border: 1px solid palette(highlight); }" ).arg( mCollapseButton->objectName() ); + ssd = QStringLiteral( "QgsCollapsibleGroupBoxBasic > QToolButton#%1, QgsCollapsibleGroupBox > QToolButton#%1 {" ).arg( mCollapseButton->objectName() ); + ssd += QLatin1String( " background-color: rgba(255, 255, 255, 0); border: none;" ); + ssd += QStringLiteral( "} QgsCollapsibleGroupBoxBasic > QToolButton#%1:focus, QgsCollapsibleGroupBox > QToolButton#%1:focus { border: 1px solid palette(highlight); }" ).arg( mCollapseButton->objectName() ); mCollapseButton->setStyleSheet( ssd ); if ( offsetLeft != 0 || offsetTopTri != 0 ) mCollapseButton->move( offsetLeft, offsetTopTri ); @@ -521,7 +521,7 @@ void QgsCollapsibleGroupBox::init() // NOTE: only turn on mSaveCheckedState for groupboxes NOT used // in multiple places or used as options for different parent objects mSaveCheckedState = false; - mSettingGroup = ""; // if not set, use window object name + mSettingGroup = QLatin1String( "" ); // if not set, use window object name } void QgsCollapsibleGroupBox::showEvent( QShowEvent * event ) diff --git a/src/gui/qgscolorbutton.cpp b/src/gui/qgscolorbutton.cpp index 0ff34b7b7b19..c1ef8c15e178 100644 --- a/src/gui/qgscolorbutton.cpp +++ b/src/gui/qgscolorbutton.cpp @@ -87,7 +87,7 @@ const QPixmap& QgsColorButton::transparentBackground() static QPixmap transpBkgrd; if ( transpBkgrd.isNull() ) - transpBkgrd = QgsApplication::getThemePixmap( "/transp-background_8x8.png" ); + transpBkgrd = QgsApplication::getThemePixmap( QStringLiteral( "/transp-background_8x8.png" ) ); return transpBkgrd; } @@ -108,7 +108,7 @@ void QgsColorButton::showColorDialog() QColor newColor; QSettings settings; - if ( mAcceptLiveUpdates && settings.value( "/qgis/live_color_dialogs", false ).toBool() ) + if ( mAcceptLiveUpdates && settings.value( QStringLiteral( "/qgis/live_color_dialogs" ), false ).toBool() ) { // live updating dialog - QgsColorDialog will automatically use native dialog if option is set newColor = QgsColorDialog::getLiveColor( @@ -118,7 +118,7 @@ void QgsColorButton::showColorDialog() else { // not using live updating dialog - first check if we need to use the limited native dialogs - bool useNative = settings.value( "/qgis/native_color_dialogs", false ).toBool(); + bool useNative = settings.value( QStringLiteral( "/qgis/native_color_dialogs" ), false ).toBool(); if ( useNative ) { // why would anyone want this? who knows.... maybe the limited nature of native dialogs helps ease the transition for MapInfo users? diff --git a/src/gui/qgscolorbutton.h b/src/gui/qgscolorbutton.h index c8488ba5b552..d69f29fdaaa2 100644 --- a/src/gui/qgscolorbutton.h +++ b/src/gui/qgscolorbutton.h @@ -62,7 +62,7 @@ class GUI_EXPORT QgsColorButton : public QToolButton * @param registry a color scheme registry for color swatch grids to show in the drop down menu. If not * specified, the button will use the global color scheme registry */ - QgsColorButton( QWidget *parent = nullptr, const QString& cdt = "", QgsColorSchemeRegistry* registry = nullptr ); + QgsColorButton( QWidget *parent = nullptr, const QString& cdt = QLatin1String( "" ), QgsColorSchemeRegistry* registry = nullptr ); virtual ~QgsColorButton(); diff --git a/src/gui/qgscolordialog.cpp b/src/gui/qgscolordialog.cpp index a1056f01a5b4..12c2f85cf355 100644 --- a/src/gui/qgscolordialog.cpp +++ b/src/gui/qgscolordialog.cpp @@ -38,7 +38,7 @@ QgsColorDialog::QgsColorDialog( QWidget *parent, Qt::WindowFlags fl, const QColo setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ColorDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ColorDialog/geometry" ) ).toByteArray() ); if ( mPreviousColor.isValid() ) { @@ -86,7 +86,7 @@ QColor QgsColorDialog::getLiveColor( const QColor &initialColor, QObject *update QSettings settings; //using native color dialogs? - bool useNative = settings.value( "/qgis/native_color_dialogs", false ).toBool(); + bool useNative = settings.value( QStringLiteral( "/qgis/native_color_dialogs" ), false ).toBool(); if ( useNative ) { QColorDialog* liveDialog = new QColorDialog( initialColor, parent ); @@ -130,7 +130,7 @@ QColor QgsColorDialog::getColor( const QColor &initialColor, QWidget *parent, co QSettings settings; //using native color dialogs? - bool useNative = settings.value( "/qgis/native_color_dialogs", false ).toBool(); + bool useNative = settings.value( QStringLiteral( "/qgis/native_color_dialogs" ), false ).toBool(); if ( useNative ) { return QColorDialog::getColor( initialColor, parent, dialogTitle, allowAlpha ? QColorDialog::ShowAlphaChannel : ( QColorDialog::ColorDialogOption )0 ); @@ -183,7 +183,7 @@ void QgsColorDialog::discardColor() void QgsColorDialog::saveSettings() { QSettings settings; - settings.setValue( "/Windows/ColorDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/geometry" ), saveGeometry() ); } void QgsColorDialog::setColor( const QColor &color ) diff --git a/src/gui/qgscolorschemelist.cpp b/src/gui/qgscolorschemelist.cpp index 94d3b68ebab1..5e8857e28e79 100644 --- a/src/gui/qgscolorschemelist.cpp +++ b/src/gui/qgscolorschemelist.cpp @@ -140,8 +140,8 @@ void QgsColorSchemeList::copyColors() void QgsColorSchemeList::showImportColorsDialog() { QSettings s; - QString lastDir = s.value( "/UI/lastGplPaletteDir", QDir::homePath() ).toString(); - QString filePath = QFileDialog::getOpenFileName( this, tr( "Select palette file" ), lastDir, "GPL (*.gpl);;All files (*.*)" ); + QString lastDir = s.value( QStringLiteral( "/UI/lastGplPaletteDir" ), QDir::homePath() ).toString(); + QString filePath = QFileDialog::getOpenFileName( this, tr( "Select palette file" ), lastDir, QStringLiteral( "GPL (*.gpl);;All files (*.*)" ) ); activateWindow(); if ( filePath.isEmpty() ) { @@ -156,7 +156,7 @@ void QgsColorSchemeList::showImportColorsDialog() return; } - s.setValue( "/UI/lastGplPaletteDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastGplPaletteDir" ), fileInfo.absolutePath() ); QFile file( filePath ); bool importOk = importColorsFromGpl( file ); if ( !importOk ) @@ -169,8 +169,8 @@ void QgsColorSchemeList::showImportColorsDialog() void QgsColorSchemeList::showExportColorsDialog() { QSettings s; - QString lastDir = s.value( "/UI/lastGplPaletteDir", QDir::homePath() ).toString(); - QString fileName = QFileDialog::getSaveFileName( this, tr( "Palette file" ), lastDir, "GPL (*.gpl)" ); + QString lastDir = s.value( QStringLiteral( "/UI/lastGplPaletteDir" ), QDir::homePath() ).toString(); + QString fileName = QFileDialog::getSaveFileName( this, tr( "Palette file" ), lastDir, QStringLiteral( "GPL (*.gpl)" ) ); activateWindow(); if ( fileName.isEmpty() ) { @@ -178,13 +178,13 @@ void QgsColorSchemeList::showExportColorsDialog() } // ensure filename contains extension - if ( !fileName.endsWith( ".gpl", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".gpl" ), Qt::CaseInsensitive ) ) { - fileName += ".gpl"; + fileName += QLatin1String( ".gpl" ); } QFileInfo fileInfo( fileName ); - s.setValue( "/UI/lastGplPaletteDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastGplPaletteDir" ), fileInfo.absolutePath() ); QFile file( fileName ); bool exportOk = exportColorsToGpl( file ); @@ -498,10 +498,10 @@ QStringList QgsColorSchemeModel::mimeTypes() const } QStringList types; - types << "text/xml"; - types << "text/plain"; - types << "application/x-color"; - types << "application/x-colorobject-list"; + types << QStringLiteral( "text/xml" ); + types << QStringLiteral( "text/plain" ); + types << QStringLiteral( "application/x-color" ); + types << QStringLiteral( "application/x-colorobject-list" ); return types; } @@ -739,7 +739,7 @@ const QPixmap& QgsColorSwatchDelegate::transparentBackground() const static QPixmap transpBkgrd; if ( transpBkgrd.isNull() ) - transpBkgrd = QgsApplication::getThemePixmap( "/transp-background_8x8.png" ); + transpBkgrd = QgsApplication::getThemePixmap( QStringLiteral( "/transp-background_8x8.png" ) ); return transpBkgrd; } diff --git a/src/gui/qgscolorswatchgrid.cpp b/src/gui/qgscolorswatchgrid.cpp index 58a0d6602b4a..cb48acec027c 100644 --- a/src/gui/qgscolorswatchgrid.cpp +++ b/src/gui/qgscolorswatchgrid.cpp @@ -330,7 +330,7 @@ const QPixmap& QgsColorSwatchGrid::transparentBackground() static QPixmap transpBkgrd; if ( transpBkgrd.isNull() ) - transpBkgrd = QgsApplication::getThemePixmap( "/transp-background_8x8.png" ); + transpBkgrd = QgsApplication::getThemePixmap( QStringLiteral( "/transp-background_8x8.png" ) ); return transpBkgrd; } diff --git a/src/gui/qgscolorwidgets.cpp b/src/gui/qgscolorwidgets.cpp index 28c28ad968be..439314f3f90a 100644 --- a/src/gui/qgscolorwidgets.cpp +++ b/src/gui/qgscolorwidgets.cpp @@ -180,7 +180,7 @@ const QPixmap &QgsColorWidget::transparentBackground() static QPixmap transpBkgrd; if ( transpBkgrd.isNull() ) - transpBkgrd = QgsApplication::getThemePixmap( "/transp-background_8x8.png" ); + transpBkgrd = QgsApplication::getThemePixmap( QStringLiteral( "/transp-background_8x8.png" ) ); return transpBkgrd; } @@ -1294,7 +1294,7 @@ QgsColorSliderWidget::QgsColorSliderWidget( QWidget *parent, const ColorComponen mSpinBox = new QSpinBox(); //set spinbox to a reasonable width - int largestCharWidth = mSpinBox->fontMetrics().width( "888%" ); + int largestCharWidth = mSpinBox->fontMetrics().width( QStringLiteral( "888%" ) ); mSpinBox->setMinimumWidth( largestCharWidth + 35 ); mSpinBox->setMinimum( 0 ); mSpinBox->setMaximum( convertRealToDisplay( componentRange() ) ); @@ -1426,15 +1426,15 @@ QgsColorTextWidget::QgsColorTextWidget( QWidget *parent ) hLayout->addWidget( mLineEdit ); mMenuButton = new QToolButton( mLineEdit ); - mMenuButton->setIcon( QgsApplication::getThemeIcon( "/mIconDropDownMenu.svg" ) ); + mMenuButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconDropDownMenu.svg" ) ) ); mMenuButton->setCursor( Qt::ArrowCursor ); mMenuButton->setFocusPolicy( Qt::NoFocus ); - mMenuButton->setStyleSheet( "QToolButton { border: none; padding: 0px; }" ); + mMenuButton->setStyleSheet( QStringLiteral( "QToolButton { border: none; padding: 0px; }" ) ); setLayout( hLayout ); int frameWidth = mLineEdit->style()->pixelMetric( QStyle::PM_DefaultFrameWidth ); - mLineEdit->setStyleSheet( QString( "QLineEdit { padding-right: %1px; } " ) + mLineEdit->setStyleSheet( QStringLiteral( "QLineEdit { padding-right: %1px; } " ) .arg( mMenuButton->sizeHint().width() + frameWidth + 1 ) ); connect( mLineEdit, SIGNAL( editingFinished() ), this, SLOT( textChanged() ) ); @@ -1442,7 +1442,7 @@ QgsColorTextWidget::QgsColorTextWidget( QWidget *parent ) //restore format setting QSettings settings; - mFormat = ( ColorTextFormat )settings.value( "/ColorWidgets/textWidgetFormat", 0 ).toInt(); + mFormat = ( ColorTextFormat )settings.value( QStringLiteral( "/ColorWidgets/textWidgetFormat" ), 0 ).toInt(); updateText(); } @@ -1475,7 +1475,7 @@ void QgsColorTextWidget::updateText() mLineEdit->setText( mCurrentColor.name() ); break; case HexRgbA: - mLineEdit->setText( mCurrentColor.name() + QString( "%1" ).arg( mCurrentColor.alpha(), 2, 16, QChar( '0' ) ) ); + mLineEdit->setText( mCurrentColor.name() + QStringLiteral( "%1" ).arg( mCurrentColor.alpha(), 2, 16, QChar( '0' ) ) ); break; case Rgb: mLineEdit->setText( QString( tr( "rgb( %1, %2, %3 )" ) ).arg( mCurrentColor.red() ).arg( mCurrentColor.green() ).arg( mCurrentColor.blue() ) ); @@ -1546,7 +1546,7 @@ void QgsColorTextWidget::showMenu() //save format setting QSettings settings; - settings.setValue( "/ColorWidgets/textWidgetFormat", ( int )mFormat ); + settings.setValue( QStringLiteral( "/ColorWidgets/textWidgetFormat" ), ( int )mFormat ); updateText(); } diff --git a/src/gui/qgscomposerruler.cpp b/src/gui/qgscomposerruler.cpp index c078a6462c89..f9be45d22f0b 100644 --- a/src/gui/qgscomposerruler.cpp +++ b/src/gui/qgscomposerruler.cpp @@ -43,7 +43,7 @@ QgsComposerRuler::QgsComposerRuler( QgsComposerRuler::Direction d ) //calculate ruler sizes and marker separations //minimum gap required between major ticks is 3 digits * 250%, based on appearance - mScaleMinPixelsWidth = mRulerFontMetrics->width( "000" ) * 2.5; + mScaleMinPixelsWidth = mRulerFontMetrics->width( QStringLiteral( "000" ) ) * 2.5; //minimum ruler height is twice the font height in pixels mRulerMinSize = mRulerFontMetrics->height() * 1.5; diff --git a/src/gui/qgscomposerview.cpp b/src/gui/qgscomposerview.cpp index 3ad8e803f910..9edb2daa8201 100644 --- a/src/gui/qgscomposerview.cpp +++ b/src/gui/qgscomposerview.cpp @@ -1465,7 +1465,7 @@ void QgsComposerView::copyItems( ClipboardMode mode ) QList<QgsComposerItem*>::iterator itemIt = composerItemList.begin(); QDomDocument doc; - QDomElement documentElement = doc.createElement( "ComposerItemClipboard" ); + QDomElement documentElement = doc.createElement( QStringLiteral( "ComposerItemClipboard" ) ); for ( ; itemIt != composerItemList.end(); ++itemIt ) { // copy each item in a group @@ -1491,19 +1491,19 @@ void QgsComposerView::copyItems( ClipboardMode mode ) if ( mode == ClipboardModeCopy ) { // remove all uuid attributes - QDomNodeList composerItemsNodes = doc.elementsByTagName( "ComposerItem" ); + QDomNodeList composerItemsNodes = doc.elementsByTagName( QStringLiteral( "ComposerItem" ) ); for ( int i = 0; i < composerItemsNodes.count(); ++i ) { QDomNode composerItemNode = composerItemsNodes.at( i ); if ( composerItemNode.isElement() ) { - composerItemNode.toElement().removeAttribute( "uuid" ); + composerItemNode.toElement().removeAttribute( QStringLiteral( "uuid" ) ); } } } QMimeData *mimeData = new QMimeData; - mimeData->setData( "text/xml", doc.toByteArray() ); + mimeData->setData( QStringLiteral( "text/xml" ), doc.toByteArray() ); QClipboard *clipboard = QApplication::clipboard(); clipboard->setMimeData( mimeData ); } @@ -1517,10 +1517,10 @@ void QgsComposerView::pasteItems( PasteMode mode ) QDomDocument doc; QClipboard *clipboard = QApplication::clipboard(); - if ( doc.setContent( clipboard->mimeData()->data( "text/xml" ) ) ) + if ( doc.setContent( clipboard->mimeData()->data( QStringLiteral( "text/xml" ) ) ) ) { QDomElement docElem = doc.documentElement(); - if ( docElem.tagName() == "ComposerItemClipboard" ) + if ( docElem.tagName() == QLatin1String( "ComposerItemClipboard" ) ) { if ( composition() ) { @@ -1974,14 +1974,14 @@ void QgsComposerView::wheelEvent( QWheelEvent* event ) { QSettings settings; //read zoom mode - QgsComposerItem::ZoomMode zoomMode = ( QgsComposerItem::ZoomMode )settings.value( "/qgis/wheel_action", 2 ).toInt(); + QgsComposerItem::ZoomMode zoomMode = ( QgsComposerItem::ZoomMode )settings.value( QStringLiteral( "/qgis/wheel_action" ), 2 ).toInt(); if ( zoomMode == QgsComposerItem::NoZoom ) { //do nothing return; } - double zoomFactor = settings.value( "/qgis/zoom_factor", 2.0 ).toDouble(); + double zoomFactor = settings.value( QStringLiteral( "/qgis/zoom_factor" ), 2.0 ).toDouble(); if ( event->modifiers() & Qt::ControlModifier ) { //holding ctrl while wheel zooming results in a finer zoom @@ -2007,7 +2007,7 @@ void QgsComposerView::wheelZoom( QWheelEvent * event ) { //get mouse wheel zoom behaviour settings QSettings mySettings; - double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble(); + double zoomFactor = mySettings.value( QStringLiteral( "/qgis/zoom_factor" ), 2 ).toDouble(); if ( event->modifiers() & Qt::ControlModifier ) { diff --git a/src/gui/qgscompoundcolorwidget.cpp b/src/gui/qgscompoundcolorwidget.cpp index 2e6965e68382..4e65ff7d0bf5 100644 --- a/src/gui/qgscompoundcolorwidget.cpp +++ b/src/gui/qgscompoundcolorwidget.cpp @@ -63,7 +63,7 @@ QgsCompoundColorWidget::QgsCompoundColorWidget( QWidget *parent, const QColor& c QList<QgsColorScheme *> schemeList = QgsColorSchemeRegistry::instance()->schemes( QgsColorScheme::ShowInColorDialog ); //choose a reasonable starting scheme - int activeScheme = settings.value( "/Windows/ColorDialog/activeScheme", 0 ).toInt(); + int activeScheme = settings.value( QStringLiteral( "/Windows/ColorDialog/activeScheme" ), 0 ).toInt(); activeScheme = activeScheme >= mSchemeComboBox->count() ? 0 : activeScheme; mSchemeList->setScheme( schemeList.at( activeScheme ) ); @@ -148,25 +148,25 @@ QgsCompoundColorWidget::QgsCompoundColorWidget( QWidget *parent, const QColor& c mSwatchButton16->setShowMenu( false ); mSwatchButton16->setBehaviour( QgsColorButton::SignalOnly ); //restore custom colors - mSwatchButton1->setColor( settings.value( "/Windows/ColorDialog/customColor1", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton2->setColor( settings.value( "/Windows/ColorDialog/customColor2", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton3->setColor( settings.value( "/Windows/ColorDialog/customColor3", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton4->setColor( settings.value( "/Windows/ColorDialog/customColor4", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton5->setColor( settings.value( "/Windows/ColorDialog/customColor5", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton6->setColor( settings.value( "/Windows/ColorDialog/customColor6", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton7->setColor( settings.value( "/Windows/ColorDialog/customColor7", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton8->setColor( settings.value( "/Windows/ColorDialog/customColor8", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton9->setColor( settings.value( "/Windows/ColorDialog/customColor9", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton10->setColor( settings.value( "/Windows/ColorDialog/customColor10", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton11->setColor( settings.value( "/Windows/ColorDialog/customColor11", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton12->setColor( settings.value( "/Windows/ColorDialog/customColor12", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton13->setColor( settings.value( "/Windows/ColorDialog/customColor13", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton14->setColor( settings.value( "/Windows/ColorDialog/customColor14", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton15->setColor( settings.value( "/Windows/ColorDialog/customColor15", QVariant( QColor() ) ).value<QColor>() ); - mSwatchButton16->setColor( settings.value( "/Windows/ColorDialog/customColor16", QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton1->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor1" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton2->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor2" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton3->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor3" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton4->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor4" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton5->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor5" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton6->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor6" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton7->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor7" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton8->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor8" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton9->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor9" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton10->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor10" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton11->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor11" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton12->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor12" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton13->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor13" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton14->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor14" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton15->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor15" ), QVariant( QColor() ) ).value<QColor>() ); + mSwatchButton16->setColor( settings.value( QStringLiteral( "/Windows/ColorDialog/customColor16" ), QVariant( QColor() ) ).value<QColor>() ); //restore sample radius - mSpinBoxRadius->setValue( settings.value( "/Windows/ColorDialog/sampleRadius", 1 ).toInt() ); + mSpinBoxRadius->setValue( settings.value( QStringLiteral( "/Windows/ColorDialog/sampleRadius" ), 1 ).toInt() ); mSamplePreview->setColor( QColor() ); if ( color.isValid() ) @@ -175,7 +175,7 @@ QgsCompoundColorWidget::QgsCompoundColorWidget( QWidget *parent, const QColor& c } //restore active component radio button - int activeRadio = settings.value( "/Windows/ColorDialog/activeComponent", 2 ).toInt(); + int activeRadio = settings.value( QStringLiteral( "/Windows/ColorDialog/activeComponent" ), 2 ).toInt(); switch ( activeRadio ) { case 0: @@ -197,7 +197,7 @@ QgsCompoundColorWidget::QgsCompoundColorWidget( QWidget *parent, const QColor& c mBlueRadio->setChecked( true ); break; } - int currentTab = settings.value( "/Windows/ColorDialog/activeTab", 0 ).toInt(); + int currentTab = settings.value( QStringLiteral( "/Windows/ColorDialog/activeTab" ), 0 ).toInt(); mTabWidget->setCurrentIndex( currentTab ); #ifdef Q_OS_MAC @@ -282,8 +282,8 @@ void QgsCompoundColorWidget::refreshSchemeComboBox() void QgsCompoundColorWidget::importPalette() { QSettings s; - QString lastDir = s.value( "/UI/lastGplPaletteDir", QDir::homePath() ).toString(); - QString filePath = QFileDialog::getOpenFileName( this, tr( "Select palette file" ), lastDir, "GPL (*.gpl);;All files (*.*)" ); + QString lastDir = s.value( QStringLiteral( "/UI/lastGplPaletteDir" ), QDir::homePath() ).toString(); + QString filePath = QFileDialog::getOpenFileName( this, tr( "Select palette file" ), lastDir, QStringLiteral( "GPL (*.gpl);;All files (*.*)" ) ); activateWindow(); if ( filePath.isEmpty() ) { @@ -298,7 +298,7 @@ void QgsCompoundColorWidget::importPalette() return; } - s.setValue( "/UI/lastGplPaletteDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastGplPaletteDir" ), fileInfo.absolutePath() ); QFile file( filePath ); QgsNamedColorList importedColors; @@ -384,7 +384,7 @@ void QgsCompoundColorWidget::newPalette() //generate file name for new palette QDir palettePath( gplFilePath() ); QRegExp badChars( "[,^@={}\\[\\]~!?:&*\"|#%<>$\"'();`' /\\\\]" ); - QString filename = name.simplified().toLower().replace( badChars, QLatin1String( "_" ) ); + QString filename = name.simplified().toLower().replace( badChars, QStringLiteral( "_" ) ); if ( filename.isEmpty() ) { filename = tr( "new_palette" ); @@ -394,7 +394,7 @@ void QgsCompoundColorWidget::newPalette() while ( destFileInfo.exists() ) { //try to generate a unique file name - destFileInfo = QFileInfo( palettePath.filePath( filename + QString( "%1.gpl" ).arg( fileNumber ) ) ); + destFileInfo = QFileInfo( palettePath.filePath( filename + QStringLiteral( "%1.gpl" ).arg( fileNumber ) ) ); fileNumber++; } @@ -567,34 +567,34 @@ void QgsCompoundColorWidget::saveSettings() activeRadio = 4; if ( mBlueRadio->isChecked() ) activeRadio = 5; - settings.setValue( "/Windows/ColorDialog/activeComponent", activeRadio ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/activeComponent" ), activeRadio ); //record current scheme - settings.setValue( "/Windows/ColorDialog/activeScheme", mSchemeComboBox->currentIndex() ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/activeScheme" ), mSchemeComboBox->currentIndex() ); //record current tab - settings.setValue( "/Windows/ColorDialog/activeTab", mTabWidget->currentIndex() ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/activeTab" ), mTabWidget->currentIndex() ); //record custom colors - settings.setValue( "/Windows/ColorDialog/customColor1", QVariant( mSwatchButton1->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor2", QVariant( mSwatchButton2->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor3", QVariant( mSwatchButton3->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor4", QVariant( mSwatchButton4->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor5", QVariant( mSwatchButton5->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor6", QVariant( mSwatchButton6->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor7", QVariant( mSwatchButton7->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor8", QVariant( mSwatchButton8->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor9", QVariant( mSwatchButton9->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor10", QVariant( mSwatchButton10->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor11", QVariant( mSwatchButton11->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor12", QVariant( mSwatchButton12->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor13", QVariant( mSwatchButton13->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor14", QVariant( mSwatchButton14->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor15", QVariant( mSwatchButton15->color() ) ); - settings.setValue( "/Windows/ColorDialog/customColor16", QVariant( mSwatchButton16->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor1" ), QVariant( mSwatchButton1->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor2" ), QVariant( mSwatchButton2->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor3" ), QVariant( mSwatchButton3->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor4" ), QVariant( mSwatchButton4->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor5" ), QVariant( mSwatchButton5->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor6" ), QVariant( mSwatchButton6->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor7" ), QVariant( mSwatchButton7->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor8" ), QVariant( mSwatchButton8->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor9" ), QVariant( mSwatchButton9->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor10" ), QVariant( mSwatchButton10->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor11" ), QVariant( mSwatchButton11->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor12" ), QVariant( mSwatchButton12->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor13" ), QVariant( mSwatchButton13->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor14" ), QVariant( mSwatchButton14->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor15" ), QVariant( mSwatchButton15->color() ) ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/customColor16" ), QVariant( mSwatchButton16->color() ) ); //sample radius - settings.setValue( "/Windows/ColorDialog/sampleRadius", mSpinBoxRadius->value() ); + settings.setValue( QStringLiteral( "/Windows/ColorDialog/sampleRadius" ), mSpinBoxRadius->value() ); } void QgsCompoundColorWidget::stopPicking( QPoint eventPos, const bool takeSample ) diff --git a/src/gui/qgsconfigureshortcutsdialog.cpp b/src/gui/qgsconfigureshortcutsdialog.cpp index 1590cd563600..c31a523de6db 100644 --- a/src/gui/qgsconfigureshortcutsdialog.cpp +++ b/src/gui/qgsconfigureshortcutsdialog.cpp @@ -66,7 +66,7 @@ QgsConfigureShortcutsDialog::~QgsConfigureShortcutsDialog() void QgsConfigureShortcutsDialog::saveState() { QSettings settings; - settings.setValue( "/Windows/ShortcutsDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ShortcutsDialog/geometry" ), saveGeometry() ); } /*! @@ -75,7 +75,7 @@ void QgsConfigureShortcutsDialog::saveState() void QgsConfigureShortcutsDialog::restoreState() { QSettings settings; - restoreGeometry( settings.value( "/Windows/ShortcutsDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ShortcutsDialog/geometry" ) ).toByteArray() ); } void QgsConfigureShortcutsDialog::populateActions() @@ -133,9 +133,9 @@ void QgsConfigureShortcutsDialog::saveShortcuts() return; // ensure the user never omitted the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } QFile file( fileName ); @@ -150,10 +150,10 @@ void QgsConfigureShortcutsDialog::saveShortcuts() QSettings settings; - QDomDocument doc( "shortcuts" ); - QDomElement root = doc.createElement( "qgsshortcuts" ); - root.setAttribute( "version", "1.0" ); - root.setAttribute( "locale", settings.value( "locale/userLocale", "en_US" ).toString() ); + QDomDocument doc( QStringLiteral( "shortcuts" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgsshortcuts" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); + root.setAttribute( QStringLiteral( "locale" ), settings.value( QStringLiteral( "locale/userLocale" ), "en_US" ).toString() ); doc.appendChild( root ); settings.beginGroup( mManager->settingsPath() ); @@ -167,9 +167,9 @@ void QgsConfigureShortcutsDialog::saveShortcuts() actionText = keys[ i ]; actionShortcut = settings.value( actionText, "" ).toString(); - QDomElement el = doc.createElement( "act" ); - el.setAttribute( "name", actionText ); - el.setAttribute( "shortcut", actionShortcut ); + QDomElement el = doc.createElement( QStringLiteral( "act" ) ); + el.setAttribute( QStringLiteral( "name" ), actionText ); + el.setAttribute( QStringLiteral( "shortcut" ), actionShortcut ); root.appendChild( el ); } @@ -213,7 +213,7 @@ void QgsConfigureShortcutsDialog::loadShortcuts() } QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsshortcuts" ) + if ( root.tagName() != QLatin1String( "qgsshortcuts" ) ) { QMessageBox::information( this, tr( "Loading shortcuts" ), tr( "The file is not an shortcuts exchange file." ) ); @@ -223,17 +223,17 @@ void QgsConfigureShortcutsDialog::loadShortcuts() QSettings settings; QString currentLocale; - bool localeOverrideFlag = settings.value( "locale/overrideFlag", false ).toBool(); + bool localeOverrideFlag = settings.value( QStringLiteral( "locale/overrideFlag" ), false ).toBool(); if ( localeOverrideFlag ) { - currentLocale = settings.value( "locale/userLocale", "en_US" ).toString(); + currentLocale = settings.value( QStringLiteral( "locale/userLocale" ), "en_US" ).toString(); } else // use QGIS locale { currentLocale = QLocale::system().name(); } - if ( root.attribute( "locale" ) != currentLocale ) + if ( root.attribute( QStringLiteral( "locale" ) ) != currentLocale ) { QMessageBox::information( this, tr( "Loading shortcuts" ), tr( "The file contains shortcuts created with different locale, so you can't use it." ) ); @@ -246,8 +246,8 @@ void QgsConfigureShortcutsDialog::loadShortcuts() QDomElement child = root.firstChildElement(); while ( !child.isNull() ) { - actionName = child.attribute( "name" ); - actionShortcut = child.attribute( "shortcut" ); + actionName = child.attribute( QStringLiteral( "name" ) ); + actionShortcut = child.attribute( QStringLiteral( "shortcut" ) ); mManager->setKeySequence( actionName, actionShortcut ); child = child.nextSiblingElement(); diff --git a/src/gui/qgscredentialdialog.cpp b/src/gui/qgscredentialdialog.cpp index 2a3b2d648cbf..63e71946ca88 100644 --- a/src/gui/qgscredentialdialog.cpp +++ b/src/gui/qgscredentialdialog.cpp @@ -24,9 +24,9 @@ #include <QSettings> #include <QThread> -static QString invalidStyle_( const QString& selector = "QLineEdit" ) +static QString invalidStyle_( const QString& selector = QStringLiteral( "QLineEdit" ) ) { - return QString( "%1{color: rgb(200, 0, 0);}" ).arg( selector ); + return QStringLiteral( "%1{color: rgb(200, 0, 0);}" ).arg( selector ); } QgsCredentialDialog::QgsCredentialDialog( QWidget *parent, Qt::WindowFlags fl ) @@ -228,11 +228,11 @@ void QgsCredentialDialog::on_chkMasterPassShow_stateChanged( int state ) void QgsCredentialDialog::on_leMasterPass_textChanged( const QString &pass ) { - leMasterPass->setStyleSheet( "" ); + leMasterPass->setStyleSheet( QLatin1String( "" ) ); bool passok = !pass.isEmpty(); // regardless of new or comparing existing, empty password disallowed if ( leMasterPassVerify->isVisible() ) { - leMasterPassVerify->setStyleSheet( "" ); + leMasterPassVerify->setStyleSheet( QLatin1String( "" ) ); passok = passok && ( leMasterPass->text() == leMasterPassVerify->text() ); } mOkButton->setEnabled( passok ); @@ -248,8 +248,8 @@ void QgsCredentialDialog::on_leMasterPassVerify_textChanged( const QString &pass { if ( leMasterPassVerify->isVisible() ) { - leMasterPass->setStyleSheet( "" ); - leMasterPassVerify->setStyleSheet( "" ); + leMasterPass->setStyleSheet( QLatin1String( "" ) ); + leMasterPassVerify->setStyleSheet( QLatin1String( "" ) ); // empty password disallowed bool passok = !pass.isEmpty() && ( leMasterPass->text() == leMasterPassVerify->text() ); diff --git a/src/gui/qgsdatadefinedbutton.cpp b/src/gui/qgsdatadefinedbutton.cpp index 051a0f716173..a391261f832e 100644 --- a/src/gui/qgsdatadefinedbutton.cpp +++ b/src/gui/qgsdatadefinedbutton.cpp @@ -39,19 +39,19 @@ QgsDataDefinedButton::QgsDataDefinedButton( QWidget* parent, // set up static icons if ( mIconDataDefine.isNull() ) { - mIconDataDefine = QgsApplication::getThemeIcon( "/mIconDataDefine.svg" ); - mIconDataDefineOn = QgsApplication::getThemeIcon( "/mIconDataDefineOn.svg" ); - mIconDataDefineError = QgsApplication::getThemeIcon( "/mIconDataDefineError.svg" ); - mIconDataDefineExpression = QgsApplication::getThemeIcon( "/mIconDataDefineExpression.svg" ); - mIconDataDefineExpressionOn = QgsApplication::getThemeIcon( "/mIconDataDefineExpressionOn.svg" ); - mIconDataDefineExpressionError = QgsApplication::getThemeIcon( "/mIconDataDefineExpressionError.svg" ); + mIconDataDefine = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDataDefine.svg" ) ); + mIconDataDefineOn = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDataDefineOn.svg" ) ); + mIconDataDefineError = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDataDefineError.svg" ) ); + mIconDataDefineExpression = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDataDefineExpression.svg" ) ); + mIconDataDefineExpressionOn = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDataDefineExpressionOn.svg" ) ); + mIconDataDefineExpressionError = QgsApplication::getThemeIcon( QStringLiteral( "/mIconDataDefineExpressionError.svg" ) ); } setFocusPolicy( Qt::StrongFocus ); // set default tool button icon properties setFixedSize( 30, 26 ); - setStyleSheet( QString( "QToolButton{ background: none; border: 1px solid rgba(0, 0, 0, 0%);} QToolButton:focus { border: 1px solid palette(highlight); }" ) ); + setStyleSheet( QStringLiteral( "QToolButton{ background: none; border: 1px solid rgba(0, 0, 0, 0%);} QToolButton:focus { border: 1px solid palette(highlight); }" ) ); setIconSize( QSize( 24, 24 ) ); setPopupMode( QToolButton::InstantPopup ); @@ -150,17 +150,17 @@ void QgsDataDefinedButton::init( const QgsVectorLayer* vl, // construct default property if none or incorrect passed in if ( !datadefined ) { - mProperty.insert( "active", "0" ); - mProperty.insert( "useexpr", "0" ); - mProperty.insert( "expression", QString() ); - mProperty.insert( "field", QString() ); + mProperty.insert( QStringLiteral( "active" ), QStringLiteral( "0" ) ); + mProperty.insert( QStringLiteral( "useexpr" ), QStringLiteral( "0" ) ); + mProperty.insert( QStringLiteral( "expression" ), QString() ); + mProperty.insert( QStringLiteral( "field" ), QString() ); } else { - mProperty.insert( "active", datadefined->isActive() ? "1" : "0" ); - mProperty.insert( "useexpr", datadefined->useExpression() ? "1" : "0" ); - mProperty.insert( "expression", datadefined->expressionString() ); - mProperty.insert( "field", datadefined->field() ); + mProperty.insert( QStringLiteral( "active" ), datadefined->isActive() ? "1" : "0" ); + mProperty.insert( QStringLiteral( "useexpr" ), datadefined->useExpression() ? "1" : "0" ); + mProperty.insert( QStringLiteral( "expression" ), datadefined->expressionString() ); + mProperty.insert( QStringLiteral( "field" ), datadefined->field() ); } mDataTypes = datatypes; @@ -191,7 +191,7 @@ void QgsDataDefinedButton::init( const QgsVectorLayer* vl, if ( !ts.isEmpty() ) { - mDataTypesString = ts.join( ", " ); + mDataTypesString = ts.join( QStringLiteral( ", " ) ); mActionDataTypes->setText( tr( "Field type: " ) + mDataTypesString ); } @@ -509,7 +509,7 @@ void QgsDataDefinedButton::showExpressionDialog() { QgsExpressionContext context = mExpressionContextGenerator ? mExpressionContextGenerator->createExpressionContext() : QgsExpressionContext(); - QgsExpressionBuilderDialog d( const_cast<QgsVectorLayer*>( mVectorLayer ), getExpression(), this, "generic", context ); + QgsExpressionBuilderDialog d( const_cast<QgsVectorLayer*>( mVectorLayer ), getExpression(), this, QStringLiteral( "generic" ), context ); if ( d.exec() == QDialog::Accepted ) { QString newExp = d.expressionText(); @@ -526,7 +526,7 @@ void QgsDataDefinedButton::showExpressionDialog() void QgsDataDefinedButton::updateGui() { QString oldDef = mCurrentDefinition; - QString newDef( "" ); + QString newDef( QLatin1String( "" ) ); bool hasExp = !getExpression().isEmpty(); bool hasField = !getField().isEmpty(); @@ -553,7 +553,7 @@ void QgsDataDefinedButton::updateGui() setActive( false ); icon = mIconDataDefineExpressionError; deftip = tr( "Parse error: %1" ).arg( exp.parserErrorString() ); - newDef = ""; + newDef = QLatin1String( "" ); } } else if ( !useExpression() && hasField ) @@ -566,7 +566,7 @@ void QgsDataDefinedButton::updateGui() setActive( false ); icon = mIconDataDefineError; deftip = tr( "'%1' field missing" ).arg( getField() ); - newDef = ""; + newDef = QLatin1String( "" ); } } @@ -599,10 +599,10 @@ void QgsDataDefinedButton::updateGui() mFullDescription += tr( "<b>Valid input types:</b><br>%1<br>" ).arg( mDataTypesString ); } - QString deftype( "" ); + QString deftype( QLatin1String( "" ) ); if ( deftip != tr( "undefined" ) ) { - deftype = QString( " (%1)" ).arg( useExpression() ? tr( "expression" ) : tr( "field" ) ); + deftype = QStringLiteral( " (%1)" ).arg( useExpression() ? tr( "expression" ) : tr( "field" ) ); } // truncate long expressions, or tool tip may be too wide for screen @@ -622,7 +622,7 @@ void QgsDataDefinedButton::setActive( bool active ) { if ( isActive() != active ) { - mProperty.insert( "active", active ? "1" : "0" ); + mProperty.insert( QStringLiteral( "active" ), active ? "1" : "0" ); emit dataDefinedActivated( active ); } } @@ -834,16 +834,16 @@ QString QgsDataDefinedButton::penJoinStyleDesc() QString QgsDataDefinedButton::blendModesDesc() { - return trString() + QLatin1String( "[<b>Normal</b>|<b>Lighten</b>|<b>Screen</b>|<b>Dodge</b>|<br>" - "<b>Addition</b>|<b>Darken</b>|<b>Multiply</b>|<b>Burn</b>|<b>Overlay</b>|<br>" - "<b>SoftLight</b>|<b>HardLight</b>|<b>Difference</b>|<b>Subtract</b>]" ); + return trString() + QStringLiteral( "[<b>Normal</b>|<b>Lighten</b>|<b>Screen</b>|<b>Dodge</b>|<br>" + "<b>Addition</b>|<b>Darken</b>|<b>Multiply</b>|<b>Burn</b>|<b>Overlay</b>|<br>" + "<b>SoftLight</b>|<b>HardLight</b>|<b>Difference</b>|<b>Subtract</b>]" ); } QString QgsDataDefinedButton::svgPathDesc() { - return trString() + QLatin1String( "[<b>filepath</b>] as<br>" - "<b>''</b>=empty|absolute|search-paths-relative|<br>" - "project-relative|URL" ); + return trString() + QStringLiteral( "[<b>filepath</b>] as<br>" + "<b>''</b>=empty|absolute|search-paths-relative|<br>" + "project-relative|URL" ); } QString QgsDataDefinedButton::filePathDesc() @@ -853,64 +853,64 @@ QString QgsDataDefinedButton::filePathDesc() QString QgsDataDefinedButton::paperSizeDesc() { - return trString() + QLatin1String( "[<b>A5</b>|<b>A4</b>|<b>A3</b>|<b>A2</b>|<b>A1</b>|<b>A0</b>" - "<b>B5</b>|<b>B4</b>|<b>B3</b>|<b>B2</b>|<b>B1</b>|<b>B0</b>" - "<b>Legal</b>|<b>Ansi A</b>|<b>Ansi B</b>|<b>Ansi C</b>|<b>Ansi D</b>|<b>Ansi E</b>" - "<b>Arch A</b>|<b>Arch B</b>|<b>Arch C</b>|<b>Arch D</b>|<b>Arch E</b>|<b>Arch E1</b>]" - ); + return trString() + QStringLiteral( "[<b>A5</b>|<b>A4</b>|<b>A3</b>|<b>A2</b>|<b>A1</b>|<b>A0</b>" + "<b>B5</b>|<b>B4</b>|<b>B3</b>|<b>B2</b>|<b>B1</b>|<b>B0</b>" + "<b>Legal</b>|<b>Ansi A</b>|<b>Ansi B</b>|<b>Ansi C</b>|<b>Ansi D</b>|<b>Ansi E</b>" + "<b>Arch A</b>|<b>Arch B</b>|<b>Arch C</b>|<b>Arch D</b>|<b>Arch E</b>|<b>Arch E1</b>]" + ); } QString QgsDataDefinedButton::paperOrientationDesc() { - return trString() + QLatin1String( "[<b>portrait</b>|<b>landscape</b>]" ); + return trString() + QStringLiteral( "[<b>portrait</b>|<b>landscape</b>]" ); } QString QgsDataDefinedButton::horizontalAnchorDesc() { - return trString() + QLatin1String( "[<b>left</b>|<b>center</b>|<b>right</b>]" ); + return trString() + QStringLiteral( "[<b>left</b>|<b>center</b>|<b>right</b>]" ); } QString QgsDataDefinedButton::verticalAnchorDesc() { - return trString() + QLatin1String( "[<b>top</b>|<b>center</b>|<b>bottom</b>]" ); + return trString() + QStringLiteral( "[<b>top</b>|<b>center</b>|<b>bottom</b>]" ); } QString QgsDataDefinedButton::gradientTypeDesc() { - return trString() + QLatin1String( "[<b>linear</b>|<b>radial</b>|<b>conical</b>]" ); + return trString() + QStringLiteral( "[<b>linear</b>|<b>radial</b>|<b>conical</b>]" ); } QString QgsDataDefinedButton::gradientCoordModeDesc() { - return trString() + QLatin1String( "[<b>feature</b>|<b>viewport</b>]" ); + return trString() + QStringLiteral( "[<b>feature</b>|<b>viewport</b>]" ); } QString QgsDataDefinedButton::gradientSpreadDesc() { - return trString() + QLatin1String( "[<b>pad</b>|<b>repeat</b>|<b>reflect</b>]" ); + return trString() + QStringLiteral( "[<b>pad</b>|<b>repeat</b>|<b>reflect</b>]" ); } QString QgsDataDefinedButton::lineStyleDesc() { - return trString() + QLatin1String( "[<b>no</b>|<b>solid</b>|<b>dash</b>|<b>dot</b>|<b>dash dot</b>|<b>dash dot dot</b>]" ); + return trString() + QStringLiteral( "[<b>no</b>|<b>solid</b>|<b>dash</b>|<b>dot</b>|<b>dash dot</b>|<b>dash dot dot</b>]" ); } QString QgsDataDefinedButton::capStyleDesc() { - return trString() + QLatin1String( "[<b>square</b>|<b>flat</b>|<b>round</b>]" ); + return trString() + QStringLiteral( "[<b>square</b>|<b>flat</b>|<b>round</b>]" ); } QString QgsDataDefinedButton::fillStyleDesc() { - return trString() + QLatin1String( "[<b>solid</b>|<b>horizontal</b>|<b>vertical</b>|<b>cross</b>|<b>b_diagonal</b>|<b>f_diagonal" - "</b>|<b>diagonal_x</b>|<b>dense1</b>|<b>dense2</b>|<b>dense3</b>|<b>dense4</b>|<b>dense5" - "</b>|<b>dense6</b>|<b>dense7</b>|<b>no]" ); + return trString() + QStringLiteral( "[<b>solid</b>|<b>horizontal</b>|<b>vertical</b>|<b>cross</b>|<b>b_diagonal</b>|<b>f_diagonal" + "</b>|<b>diagonal_x</b>|<b>dense1</b>|<b>dense2</b>|<b>dense3</b>|<b>dense4</b>|<b>dense5" + "</b>|<b>dense6</b>|<b>dense7</b>|<b>no]" ); } QString QgsDataDefinedButton::markerStyleDesc() { - return trString() + QLatin1String( "[<b>circle</b>|<b>rectangle</b>|<b>diamond</b>|<b>cross</b>|<b>triangle" - "</b>|<b>right_half_triangle</b>|<b>left_half_triangle</b>|<b>semi_circle</b>]" ); + return trString() + QStringLiteral( "[<b>circle</b>|<b>rectangle</b>|<b>diamond</b>|<b>cross</b>|<b>triangle" + "</b>|<b>right_half_triangle</b>|<b>left_half_triangle</b>|<b>semi_circle</b>]" ); } QString QgsDataDefinedButton::customDashDesc() diff --git a/src/gui/qgsdatadefinedbutton.h b/src/gui/qgsdatadefinedbutton.h index 50cd77615801..62a09f850800 100644 --- a/src/gui/qgsdatadefinedbutton.h +++ b/src/gui/qgsdatadefinedbutton.h @@ -141,22 +141,22 @@ class GUI_EXPORT QgsDataDefinedButton: public QToolButton /** * Whether the current data definition or expression is to be used */ - bool isActive() const { return mProperty.value( "active" ).toInt(); } + bool isActive() const { return mProperty.value( QStringLiteral( "active" ) ).toInt(); } /** * Whether the current expression is to be used instead of field mapping */ - bool useExpression() const { return mProperty.value( "useexpr" ).toInt(); } + bool useExpression() const { return mProperty.value( QStringLiteral( "useexpr" ) ).toInt(); } /** * The current defined expression */ - QString getExpression() const { return mProperty.value( "expression" ); } + QString getExpression() const { return mProperty.value( QStringLiteral( "expression" ) ); } /** * The current defined field */ - QString getField() const { return mProperty.value( "field" ); } + QString getField() const { return mProperty.value( QStringLiteral( "field" ) ); } /** * The current definition @@ -329,17 +329,17 @@ class GUI_EXPORT QgsDataDefinedButton: public QToolButton /** * Set whether the current expression is to be used instead of field mapping */ - void setUseExpression( bool use ) { mProperty.insert( "useexpr", use ? "1" : "0" ); } + void setUseExpression( bool use ) { mProperty.insert( QStringLiteral( "useexpr" ), use ? "1" : "0" ); } /** * Set the current defined expression */ - void setExpression( const QString& exp ) { mProperty.insert( "expression", exp ); } + void setExpression( const QString& exp ) { mProperty.insert( QStringLiteral( "expression" ), exp ); } /** * Set the current defined field */ - void setField( const QString& field ) { mProperty.insert( "field", field ); } + void setField( const QString& field ) { mProperty.insert( QStringLiteral( "field" ), field ); } private: void showDescriptionDialog(); diff --git a/src/gui/qgsdatumtransformdialog.cpp b/src/gui/qgsdatumtransformdialog.cpp index d9ac5e4e9808..15cadd47db7b 100644 --- a/src/gui/qgsdatumtransformdialog.cpp +++ b/src/gui/qgsdatumtransformdialog.cpp @@ -34,16 +34,16 @@ QgsDatumTransformDialog::QgsDatumTransformDialog( const QString& layerName, cons updateTitle(); QSettings settings; - restoreGeometry( settings.value( "/Windows/DatumTransformDialog/geometry" ).toByteArray() ); - mHideDeprecatedCheckBox->setChecked( settings.value( "/Windows/DatumTransformDialog/hideDeprecated", false ).toBool() ); - mRememberSelectionCheckBox->setChecked( settings.value( "/Windows/DatumTransformDialog/rememberSelection", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/DatumTransformDialog/geometry" ) ).toByteArray() ); + mHideDeprecatedCheckBox->setChecked( settings.value( QStringLiteral( "/Windows/DatumTransformDialog/hideDeprecated" ), false ).toBool() ); + mRememberSelectionCheckBox->setChecked( settings.value( QStringLiteral( "/Windows/DatumTransformDialog/rememberSelection" ), false ).toBool() ); - mLabelSrcDescription->setText( "" ); - mLabelDstDescription->setText( "" ); + mLabelSrcDescription->setText( QLatin1String( "" ) ); + mLabelDstDescription->setText( QLatin1String( "" ) ); for ( int i = 0; i < 2; i++ ) { - mDatumTransformTreeWidget->setColumnWidth( i, settings.value( QString( "/Windows/DatumTransformDialog/columnWidths/%1" ).arg( i ), mDatumTransformTreeWidget->columnWidth( i ) ).toInt() ); + mDatumTransformTreeWidget->setColumnWidth( i, settings.value( QStringLiteral( "/Windows/DatumTransformDialog/columnWidths/%1" ).arg( i ), mDatumTransformTreeWidget->columnWidth( i ) ).toInt() ); } load(); @@ -86,18 +86,18 @@ void QgsDatumTransformDialog::load() QString toolTipString; if ( gridShiftTransformation( item->text( i ) ) ) { - toolTipString.append( QString( "<p><b>NTv2</b></p>" ) ); + toolTipString.append( QStringLiteral( "<p><b>NTv2</b></p>" ) ); } if ( epsgNr > 0 ) - toolTipString.append( QString( "<p><b>EPSG Transformations Code:</b> %1</p>" ).arg( epsgNr ) ); + toolTipString.append( QStringLiteral( "<p><b>EPSG Transformations Code:</b> %1</p>" ).arg( epsgNr ) ); - toolTipString.append( QString( "<p><b>Source CRS:</b> %1</p><p><b>Destination CRS:</b> %2</p>" ).arg( srcGeoProj, destGeoProj ) ); + toolTipString.append( QStringLiteral( "<p><b>Source CRS:</b> %1</p><p><b>Destination CRS:</b> %2</p>" ).arg( srcGeoProj, destGeoProj ) ); if ( !remarks.isEmpty() ) - toolTipString.append( QString( "<p><b>Remarks:</b> %1</p>" ).arg( remarks ) ); + toolTipString.append( QStringLiteral( "<p><b>Remarks:</b> %1</p>" ).arg( remarks ) ); if ( !scope.isEmpty() ) - toolTipString.append( QString( "<p><b>Scope:</b> %1</p>" ).arg( scope ) ); + toolTipString.append( QStringLiteral( "<p><b>Scope:</b> %1</p>" ).arg( scope ) ); if ( preferred ) toolTipString.append( "<p><b>Preferred transformation</b></p>" ); if ( deprecated ) @@ -126,13 +126,13 @@ void QgsDatumTransformDialog::load() QgsDatumTransformDialog::~QgsDatumTransformDialog() { QSettings settings; - settings.setValue( "/Windows/DatumTransformDialog/geometry", saveGeometry() ); - settings.setValue( "/Windows/DatumTransformDialog/hideDeprecated", mHideDeprecatedCheckBox->isChecked() ); - settings.setValue( "/Windows/DatumTransformDialog/rememberSelection", mRememberSelectionCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/DatumTransformDialog/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/DatumTransformDialog/hideDeprecated" ), mHideDeprecatedCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/DatumTransformDialog/rememberSelection" ), mRememberSelectionCheckBox->isChecked() ); for ( int i = 0; i < 2; i++ ) { - settings.setValue( QString( "/Windows/DatumTransformDialog/columnWidths/%1" ).arg( i ), mDatumTransformTreeWidget->columnWidth( i ) ); + settings.setValue( QStringLiteral( "/Windows/DatumTransformDialog/columnWidths/%1" ).arg( i ), mDatumTransformTreeWidget->columnWidth( i ) ); } QApplication::restoreOverrideCursor(); @@ -168,7 +168,7 @@ bool QgsDatumTransformDialog::rememberSelection() const bool QgsDatumTransformDialog::gridShiftTransformation( const QString& itemText ) const { - return !itemText.isEmpty() && !itemText.contains( "towgs84", Qt::CaseInsensitive ); + return !itemText.isEmpty() && !itemText.contains( QLatin1String( "towgs84" ), Qt::CaseInsensitive ); } bool QgsDatumTransformDialog::testGridShiftFileAvailability( QTreeWidgetItem* item, int col ) const @@ -243,7 +243,7 @@ void QgsDatumTransformDialog::updateTitle() mLabelLayer->setText( mLayerName ); QgsCoordinateReferenceSystem crs; crs.createFromString( mSrcCRSauthId ); - mLabelSrcCrs->setText( QString( "%1 - %2" ).arg( mSrcCRSauthId, crs.isValid() ? crs.description() : tr( "unknown" ) ) ); + mLabelSrcCrs->setText( QStringLiteral( "%1 - %2" ).arg( mSrcCRSauthId, crs.isValid() ? crs.description() : tr( "unknown" ) ) ); crs.createFromString( mDestCRSauthId ); - mLabelDstCrs->setText( QString( "%1 - %2" ).arg( mDestCRSauthId, crs.isValid() ? crs.description() : tr( "unknown" ) ) ); + mLabelDstCrs->setText( QStringLiteral( "%1 - %2" ).arg( mDestCRSauthId, crs.isValid() ? crs.description() : tr( "unknown" ) ) ); } diff --git a/src/gui/qgsdetaileditemdelegate.cpp b/src/gui/qgsdetaileditemdelegate.cpp index 895fa92f6a01..456763a5f050 100644 --- a/src/gui/qgsdetaileditemdelegate.cpp +++ b/src/gui/qgsdetaileditemdelegate.cpp @@ -336,8 +336,8 @@ QStringList QgsDetailedItemDelegate::wordWrap( const QString& theString, //qDebug(myDebug.toLocal8Bit()); //iterate the string QStringList myList; - QString myCumulativeLine = ""; - QString myStringToPreviousSpace = ""; + QString myCumulativeLine = QLatin1String( "" ); + QString myStringToPreviousSpace = QLatin1String( "" ); int myPreviousSpacePos = 0; for ( int i = 0; i < theString.count(); ++i ) { @@ -355,8 +355,8 @@ QStringList QgsDetailedItemDelegate::wordWrap( const QString& theString, //forcing a break at current pos... myList << myStringToPreviousSpace.trimmed(); i = myPreviousSpacePos; - myStringToPreviousSpace = ""; - myCumulativeLine = ""; + myStringToPreviousSpace = QLatin1String( "" ); + myCumulativeLine = QLatin1String( "" ); } }//end of i loop //add whatever is left in the string to the list diff --git a/src/gui/qgsencodingfiledialog.cpp b/src/gui/qgsencodingfiledialog.cpp index b59978b0e347..04e42cc7de87 100644 --- a/src/gui/qgsencodingfiledialog.cpp +++ b/src/gui/qgsencodingfiledialog.cpp @@ -46,7 +46,7 @@ QgsEncodingFileDialog::QgsEncodingFileDialog( QWidget* parent, if ( encoding.isEmpty() ) { QSettings settings; - enc = settings.value( "/UI/encoding", "System" ).toString(); + enc = settings.value( QStringLiteral( "/UI/encoding" ), "System" ).toString(); } // The specified decoding is added if not existing alread, and then set current. @@ -84,7 +84,7 @@ QString QgsEncodingFileDialog::encoding() const void QgsEncodingFileDialog::saveUsedEncoding() { QSettings settings; - settings.setValue( "/UI/encoding", encoding() ); + settings.setValue( QStringLiteral( "/UI/encoding" ), encoding() ); QgsDebugMsg( QString( "Set encoding " + encoding() + " as default." ) ); } diff --git a/src/gui/qgserrordialog.cpp b/src/gui/qgserrordialog.cpp index b44954c769d6..b6bbcae2cd6a 100644 --- a/src/gui/qgserrordialog.cpp +++ b/src/gui/qgserrordialog.cpp @@ -29,7 +29,7 @@ QgsErrorDialog::QgsErrorDialog( const QgsError & theError, const QString & theTi setWindowTitle( title ); // QMessageBox has static standardIcon( Icon icon ), but it is marked as obsolete - QMessageBox messageBox( QMessageBox::Critical, "", "" ); + QMessageBox messageBox( QMessageBox::Critical, QLatin1String( "" ), QLatin1String( "" ) ); mIconLabel->setPixmap( messageBox.iconPixmap() ); mSummaryTextBrowser->setOpenExternalLinks( true ); mDetailTextBrowser->setOpenExternalLinks( true ); @@ -47,7 +47,7 @@ QgsErrorDialog::QgsErrorDialog( const QgsError & theError, const QString & theTi resize( width(), 150 ); QSettings settings; - Qt::CheckState state = ( Qt::CheckState ) settings.value( "/Error/dialog/detail", 0 ).toInt(); + Qt::CheckState state = ( Qt::CheckState ) settings.value( QStringLiteral( "/Error/dialog/detail" ), 0 ).toInt(); mDetailCheckBox->setCheckState( state ); if ( state == Qt::Checked ) on_mDetailPushButton_clicked(); } @@ -74,6 +74,6 @@ void QgsErrorDialog::on_mDetailPushButton_clicked() void QgsErrorDialog::on_mDetailCheckBox_stateChanged( int state ) { QSettings settings; - settings.setValue( "/Error/dialog/detail", state ); + settings.setValue( QStringLiteral( "/Error/dialog/detail" ), state ); } diff --git a/src/gui/qgsexpressionbuilderdialog.cpp b/src/gui/qgsexpressionbuilderdialog.cpp index 006735b15e5c..dc8e826b5c74 100644 --- a/src/gui/qgsexpressionbuilderdialog.cpp +++ b/src/gui/qgsexpressionbuilderdialog.cpp @@ -32,7 +32,7 @@ QgsExpressionBuilderDialog::QgsExpressionBuilderDialog( QgsVectorLayer* layer, c builder->loadRecent( mRecentKey ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ExpressionBuilderDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ExpressionBuilderDialog/geometry" ) ).toByteArray() ); } QgsExpressionBuilderWidget* QgsExpressionBuilderDialog::expressionBuilder() @@ -65,7 +65,7 @@ void QgsExpressionBuilderDialog::done( int r ) QDialog::done( r ); QSettings settings; - settings.setValue( "/Windows/ExpressionBuilderDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ExpressionBuilderDialog/geometry" ), saveGeometry() ); } void QgsExpressionBuilderDialog::accept() diff --git a/src/gui/qgsexpressionbuilderdialog.h b/src/gui/qgsexpressionbuilderdialog.h index 0e97b6d7469c..8b9c5cc84bd4 100644 --- a/src/gui/qgsexpressionbuilderdialog.h +++ b/src/gui/qgsexpressionbuilderdialog.h @@ -28,7 +28,11 @@ class GUI_EXPORT QgsExpressionBuilderDialog : public QDialog, private Ui::QgsExp Q_OBJECT public: - QgsExpressionBuilderDialog( QgsVectorLayer* layer, const QString& startText = QString(), QWidget* parent = nullptr, const QString& key = "generic", + + /** + * Constructor for QgsExpressionBuilderDialog. + */ + QgsExpressionBuilderDialog( QgsVectorLayer* layer, const QString& startText = QString(), QWidget* parent = nullptr, const QString& key = QStringLiteral( "generic" ), const QgsExpressionContext& context = QgsExpressionContext() ); /** The builder widget that is used by the dialog */ diff --git a/src/gui/qgsexpressionbuilderwidget.cpp b/src/gui/qgsexpressionbuilderwidget.cpp index cfbc54f62766..c23429c96854 100644 --- a/src/gui/qgsexpressionbuilderwidget.cpp +++ b/src/gui/qgsexpressionbuilderwidget.cpp @@ -80,9 +80,9 @@ QgsExpressionBuilderWidget::QgsExpressionBuilderWidget( QWidget *parent ) txtSearchEditValues->setPlaceholderText( tr( "Search" ) ); QSettings settings; - splitter->restoreState( settings.value( "/windows/QgsExpressionBuilderWidget/splitter" ).toByteArray() ); - editorSplit->restoreState( settings.value( "/windows/QgsExpressionBuilderWidget/editorsplitter" ).toByteArray() ); - functionsplit->restoreState( settings.value( "/windows/QgsExpressionBuilderWidget/functionsplitter" ).toByteArray() ); + splitter->restoreState( settings.value( QStringLiteral( "/windows/QgsExpressionBuilderWidget/splitter" ) ).toByteArray() ); + editorSplit->restoreState( settings.value( QStringLiteral( "/windows/QgsExpressionBuilderWidget/editorsplitter" ) ).toByteArray() ); + functionsplit->restoreState( settings.value( QStringLiteral( "/windows/QgsExpressionBuilderWidget/functionsplitter" ) ).toByteArray() ); txtExpressionString->setFoldingVisible( false ); @@ -90,7 +90,7 @@ QgsExpressionBuilderWidget::QgsExpressionBuilderWidget( QWidget *parent ) if ( QgsPythonRunner::isValid() ) { - QgsPythonRunner::eval( "qgis.user.expressionspath", mFunctionsPath ); + QgsPythonRunner::eval( QStringLiteral( "qgis.user.expressionspath" ), mFunctionsPath ); updateFunctionFileList( mFunctionsPath ); } else @@ -103,16 +103,16 @@ QgsExpressionBuilderWidget::QgsExpressionBuilderWidget( QWidget *parent ) QModelIndex firstItem = mProxyModel->index( 0, 0, QModelIndex() ); expressionTree->setCurrentIndex( firstItem ); - lblAutoSave->setText( "" ); + lblAutoSave->setText( QLatin1String( "" ) ); } QgsExpressionBuilderWidget::~QgsExpressionBuilderWidget() { QSettings settings; - settings.setValue( "/windows/QgsExpressionBuilderWidget/splitter", splitter->saveState() ); - settings.setValue( "/windows/QgsExpressionBuilderWidget/editorsplitter", editorSplit->saveState() ); - settings.setValue( "/windows/QgsExpressionBuilderWidget/functionsplitter", functionsplit->saveState() ); + settings.setValue( QStringLiteral( "/windows/QgsExpressionBuilderWidget/splitter" ), splitter->saveState() ); + settings.setValue( QStringLiteral( "/windows/QgsExpressionBuilderWidget/editorsplitter" ), editorSplit->saveState() ); + settings.setValue( QStringLiteral( "/windows/QgsExpressionBuilderWidget/functionsplitter" ), functionsplit->saveState() ); delete mModel; delete mProxyModel; @@ -132,7 +132,7 @@ void QgsExpressionBuilderWidget::setLayer( QgsVectorLayer *layer ) void QgsExpressionBuilderWidget::currentChanged( const QModelIndex &index, const QModelIndex & ) { - txtSearchEditValues->setText( QString( "" ) ); + txtSearchEditValues->setText( QLatin1String( "" ) ); // Get the item QModelIndex idx = mProxyModel->mapToSource( index ); @@ -184,7 +184,7 @@ void QgsExpressionBuilderWidget::saveFunctionFile( QString fileName ) myDir.mkpath( mFunctionsPath ); } - if ( !fileName.endsWith( ".py" ) ) + if ( !fileName.endsWith( QLatin1String( ".py" ) ) ) { fileName.append( ".py" ); } @@ -203,14 +203,14 @@ void QgsExpressionBuilderWidget::updateFunctionFileList( const QString& path ) { mFunctionsPath = path; QDir dir( path ); - dir.setNameFilters( QStringList() << "*.py" ); + dir.setNameFilters( QStringList() << QStringLiteral( "*.py" ) ); QStringList files = dir.entryList( QDir::Files ); cmbFileNames->clear(); Q_FOREACH ( const QString& name, files ) { QFileInfo info( mFunctionsPath + QDir::separator() + name ); - if ( info.baseName() == "__init__" ) continue; - QListWidgetItem* item = new QListWidgetItem( QgsApplication::getThemeIcon( "console/iconTabEditorConsole.png" ), info.baseName() ); + if ( info.baseName() == QLatin1String( "__init__" ) ) continue; + QListWidgetItem* item = new QListWidgetItem( QgsApplication::getThemeIcon( QStringLiteral( "console/iconTabEditorConsole.png" ) ), info.baseName() ); cmbFileNames->addItem( item ); } if ( !cmbFileNames->currentItem() ) @@ -224,7 +224,7 @@ void QgsExpressionBuilderWidget::newFunctionFile( const QString& fileName ) return; QString templatetxt; - QgsPythonRunner::eval( "qgis.user.expressions.template", templatetxt ); + QgsPythonRunner::eval( QStringLiteral( "qgis.user.expressions.template" ), templatetxt ); txtPython->setText( templatetxt ); cmbFileNames->insertItem( 0, fileName ); cmbFileNames->setCurrentRow( 0 ); @@ -236,7 +236,7 @@ void QgsExpressionBuilderWidget::on_btnNewFile_pressed() bool ok; QString text = QInputDialog::getText( this, tr( "Enter new file name" ), tr( "File name:" ), QLineEdit::Normal, - "", &ok ); + QLatin1String( "" ), &ok ); if ( ok && !text.isEmpty() ) { newFunctionFile( text ); @@ -256,7 +256,7 @@ void QgsExpressionBuilderWidget::on_cmbFileNames_currentItemChanged( QListWidget void QgsExpressionBuilderWidget::loadCodeFromFile( QString path ) { - if ( !path.endsWith( ".py" ) ) + if ( !path.endsWith( QLatin1String( ".py" ) ) ) path.append( ".py" ); txtPython->loadScript( path ); @@ -305,7 +305,7 @@ void QgsExpressionBuilderWidget::loadFieldNames( const QgsFields& fields ) { QString fieldName = fields.at( i ).name(); fieldNames << fieldName; - registerItem( "Fields and Values", fieldName, " \"" + fieldName + "\" ", "", QgsExpressionItem::Field, false, i ); + registerItem( QStringLiteral( "Fields and Values" ), fieldName, " \"" + fieldName + "\" ", QLatin1String( "" ), QgsExpressionItem::Field, false, i ); } // highlighter->addFields( fieldNames ); } @@ -342,11 +342,11 @@ void QgsExpressionBuilderWidget::fillFieldValues( const QString& fieldName, int { QString strValue; if ( value.isNull() ) - strValue = "NULL"; + strValue = QStringLiteral( "NULL" ); else if ( value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::LongLong ) strValue = value.toString(); else - strValue = '\'' + value.toString().replace( '\'', "''" ) + '\''; + strValue = '\'' + value.toString().replace( '\'', QLatin1String( "''" ) ) + '\''; strValues.append( strValue ); } mValuesModel->setStringList( strValues ); @@ -372,10 +372,10 @@ void QgsExpressionBuilderWidget::registerItem( const QString& group, else { // If the group doesn't exist yet we make it first. - QgsExpressionItem *newgroupNode = new QgsExpressionItem( QgsExpression::group( group ), "", QgsExpressionItem::Header ); + QgsExpressionItem *newgroupNode = new QgsExpressionItem( QgsExpression::group( group ), QLatin1String( "" ), QgsExpressionItem::Header ); newgroupNode->setData( group, Qt::UserRole ); //Recent group should always be last group - newgroupNode->setData( group.startsWith( "Recent (" ) ? 2 : 1, QgsExpressionItem::CustomSortRole ); + newgroupNode->setData( group.startsWith( QLatin1String( "Recent (" ) ) ? 2 : 1, QgsExpressionItem::CustomSortRole ); newgroupNode->appendRow( item ); newgroupNode->setBackground( QBrush( QColor( "#eee" ) ) ); mModel->appendRow( newgroupNode ); @@ -404,7 +404,7 @@ bool QgsExpressionBuilderWidget::isExpressionValid() void QgsExpressionBuilderWidget::saveToRecent( const QString& collection ) { QSettings settings; - QString location = QString( "/expressions/recent/%1" ).arg( collection ); + QString location = QStringLiteral( "/expressions/recent/%1" ).arg( collection ); QStringList expressions = settings.value( location ).toStringList(); expressions.removeAll( this->expressionText() ); @@ -430,7 +430,7 @@ void QgsExpressionBuilderWidget::loadRecent( const QString& collection ) } QSettings settings; - QString location = QString( "/expressions/recent/%1" ).arg( collection ); + QString location = QStringLiteral( "/expressions/recent/%1" ).arg( collection ); QStringList expressions = settings.value( location ).toStringList(); int i = 0; Q_FOREACH ( const QString& expression, expressions ) @@ -445,31 +445,31 @@ void QgsExpressionBuilderWidget::updateFunctionTree() mModel->clear(); mExpressionGroups.clear(); // TODO Can we move this stuff to QgsExpression, like the functions? - registerItem( "Operators", "+", " + " ); - registerItem( "Operators", "-", " - " ); - registerItem( "Operators", "*", " * " ); - registerItem( "Operators", "/", " / " ); - registerItem( "Operators", "%", " % " ); - registerItem( "Operators", "^", " ^ " ); - registerItem( "Operators", "=", " = " ); - registerItem( "Operators", ">", " > " ); - registerItem( "Operators", "<", " < " ); - registerItem( "Operators", "<>", " <> " ); - registerItem( "Operators", "<=", " <= " ); - registerItem( "Operators", ">=", " >= " ); - registerItem( "Operators", "||", " || " ); - registerItem( "Operators", "IN", " IN " ); - registerItem( "Operators", "LIKE", " LIKE " ); - registerItem( "Operators", "ILIKE", " ILIKE " ); - registerItem( "Operators", "IS", " IS " ); - registerItem( "Operators", "OR", " OR " ); - registerItem( "Operators", "AND", " AND " ); - registerItem( "Operators", "NOT", " NOT " ); - - QString casestring = "CASE WHEN condition THEN result END"; - registerItem( "Conditionals", "CASE", casestring ); - - registerItem( "Fields and Values", "NULL", "NULL" ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "+" ), QStringLiteral( " + " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "-" ), QStringLiteral( " - " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "*" ), QStringLiteral( " * " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "/" ), QStringLiteral( " / " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "%" ), QStringLiteral( " % " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "^" ), QStringLiteral( " ^ " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "=" ), QStringLiteral( " = " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( ">" ), QStringLiteral( " > " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "<" ), QStringLiteral( " < " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "<>" ), QStringLiteral( " <> " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "<=" ), QStringLiteral( " <= " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( ">=" ), QStringLiteral( " >= " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "||" ), QStringLiteral( " || " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "IN" ), QStringLiteral( " IN " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "LIKE" ), QStringLiteral( " LIKE " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "ILIKE" ), QStringLiteral( " ILIKE " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "IS" ), QStringLiteral( " IS " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "OR" ), QStringLiteral( " OR " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "AND" ), QStringLiteral( " AND " ) ); + registerItem( QStringLiteral( "Operators" ), QStringLiteral( "NOT" ), QStringLiteral( " NOT " ) ); + + QString casestring = QStringLiteral( "CASE WHEN condition THEN result END" ); + registerItem( QStringLiteral( "Conditionals" ), QStringLiteral( "CASE" ), casestring ); + + registerItem( QStringLiteral( "Fields and Values" ), QStringLiteral( "NULL" ), QStringLiteral( "NULL" ) ); // Load the functions from the QgsExpression class int count = QgsExpression::functionCount(); @@ -490,7 +490,7 @@ void QgsExpressionBuilderWidget::updateFunctionTree() if ( func->params() != 0 ) name += '('; else if ( !name.startsWith( '$' ) ) - name += "()"; + name += QLatin1String( "()" ); registerItemForAllGroups( func->groups(), func->name(), ' ' + name + ' ', func->helpText() ); } @@ -527,10 +527,10 @@ void QgsExpressionBuilderWidget::on_txtExpressionString_textChanged() // we don't show the user an error as it will be confusing. if ( text.isEmpty() ) { - lblPreview->setText( "" ); - lblPreview->setStyleSheet( "" ); - txtExpressionString->setToolTip( "" ); - lblPreview->setToolTip( "" ); + lblPreview->setText( QLatin1String( "" ) ); + lblPreview->setStyleSheet( QLatin1String( "" ) ); + txtExpressionString->setToolTip( QLatin1String( "" ) ); + lblPreview->setToolTip( QLatin1String( "" ) ); emit expressionParsed( false ); return; } @@ -558,7 +558,7 @@ void QgsExpressionBuilderWidget::on_txtExpressionString_textChanged() { // The feature is invalid because we don't have one but that doesn't mean user can't // build a expression string. They just get no preview. - lblPreview->setText( "" ); + lblPreview->setText( QLatin1String( "" ) ); } } else @@ -573,12 +573,12 @@ void QgsExpressionBuilderWidget::on_txtExpressionString_textChanged() if ( exp.hasParserError() || exp.hasEvalError() ) { - QString tooltip = QString( "<b>%1:</b><br>%2" ).arg( tr( "Parser Error" ), exp.parserErrorString() ); + QString tooltip = QStringLiteral( "<b>%1:</b><br>%2" ).arg( tr( "Parser Error" ), exp.parserErrorString() ); if ( exp.hasEvalError() ) - tooltip += QString( "<br><br><b>%1:</b><br>%2" ).arg( tr( "Eval Error" ), exp.evalErrorString() ); + tooltip += QStringLiteral( "<br><br><b>%1:</b><br>%2" ).arg( tr( "Eval Error" ), exp.evalErrorString() ); lblPreview->setText( tr( "Expression is invalid <a href=""more"">(more info)</a>" ) ); - lblPreview->setStyleSheet( "color: rgba(255, 6, 10, 255);" ); + lblPreview->setStyleSheet( QStringLiteral( "color: rgba(255, 6, 10, 255);" ) ); txtExpressionString->setToolTip( tooltip ); lblPreview->setToolTip( tooltip ); emit expressionParsed( false ); @@ -586,9 +586,9 @@ void QgsExpressionBuilderWidget::on_txtExpressionString_textChanged() } else { - lblPreview->setStyleSheet( "" ); - txtExpressionString->setToolTip( "" ); - lblPreview->setToolTip( "" ); + lblPreview->setStyleSheet( QLatin1String( "" ) ); + txtExpressionString->setToolTip( QLatin1String( "" ) ); + lblPreview->setToolTip( QLatin1String( "" ) ); emit expressionParsed( true ); } } @@ -598,7 +598,7 @@ void QgsExpressionBuilderWidget::loadExpressionContext() QStringList variableNames = mExpressionContext.filteredVariableNames(); Q_FOREACH ( const QString& variable, variableNames ) { - registerItem( "Variables", variable, " @" + variable + ' ', + registerItem( QStringLiteral( "Variables" ), variable, " @" + variable + ' ', QgsExpression::variableHelpText( variable, true, mExpressionContext.variable( variable ) ), QgsExpressionItem::ExpressionNode, mExpressionContext.isHighlightedVariable( variable ) ); @@ -727,7 +727,7 @@ void QgsExpressionBuilderWidget::loadAllValues() void QgsExpressionBuilderWidget::on_txtPython_textChanged() { - lblAutoSave->setText( "Saving..." ); + lblAutoSave->setText( QStringLiteral( "Saving..." ) ); if ( mAutoSave ) { autosave(); @@ -746,7 +746,7 @@ void QgsExpressionBuilderWidget::autosave() QString file = item->text(); saveFunctionFile( file ); - lblAutoSave->setText( "Saved" ); + lblAutoSave->setText( QStringLiteral( "Saved" ) ); QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(); lblAutoSave->setGraphicsEffect( effect ); QPropertyAnimation *anim = new QPropertyAnimation( effect, "opacity" ); @@ -778,7 +778,7 @@ QString QgsExpressionBuilderWidget::helpStylesheet() const QString QgsExpressionBuilderWidget::loadFunctionHelp( QgsExpressionItem* expressionItem ) { if ( !expressionItem ) - return ""; + return QLatin1String( "" ); QString helpContents = expressionItem->getHelpText(); @@ -788,7 +788,7 @@ QString QgsExpressionBuilderWidget::loadFunctionHelp( QgsExpressionItem* express QString name = expressionItem->data( Qt::UserRole ).toString(); if ( expressionItem->getItemType() == QgsExpressionItem::Field ) - helpContents = QgsExpression::helpText( "Field" ); + helpContents = QgsExpression::helpText( QStringLiteral( "Field" ) ); else helpContents = QgsExpression::helpText( name ); } diff --git a/src/gui/qgsexpressionbuilderwidget.h b/src/gui/qgsexpressionbuilderwidget.h index 453abb7d7917..aeea83817f03 100644 --- a/src/gui/qgsexpressionbuilderwidget.h +++ b/src/gui/qgsexpressionbuilderwidget.h @@ -183,7 +183,7 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp * @param sortOrder sort ranking for item */ void registerItem( const QString& group, const QString& label, const QString& expressionText, - const QString& helpText = "", + const QString& helpText = QLatin1String( "" ), QgsExpressionItem::ItemType type = QgsExpressionItem::ExpressionNode, bool highlightedItem = false, int sortOrder = 1 ); @@ -193,17 +193,17 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp * Adds the current expression to the given collection. * By default it is saved to the collection "generic". */ - void saveToRecent( const QString& collection = "generic" ); + void saveToRecent( const QString& collection = QStringLiteral( "generic" ) ); /** * Loads the recent expressions from the given collection. * By default it is loaded from the collection "generic". */ - void loadRecent( const QString& collection = "generic" ); + void loadRecent( const QString& collection = QStringLiteral( "generic" ) ); /** Create a new file in the function editor */ - void newFunctionFile( const QString& fileName = "scratch" ); + void newFunctionFile( const QString& fileName = QStringLiteral( "scratch" ) ); /** Save the current function editor text to the given file. */ @@ -291,7 +291,7 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp * @param sortOrder sort ranking for item */ void registerItemForAllGroups( const QStringList& groups, const QString& label, const QString& expressionText, - const QString& helpText = "", + const QString& helpText = QLatin1String( "" ), QgsExpressionItem::ItemType type = QgsExpressionItem::ExpressionNode, bool highlightedItem = false, int sortOrder = 1 ); diff --git a/src/gui/qgsexpressionhighlighter.cpp b/src/gui/qgsexpressionhighlighter.cpp index 6ecfe272120e..1a8ba09a91b8 100644 --- a/src/gui/qgsexpressionhighlighter.cpp +++ b/src/gui/qgsexpressionhighlighter.cpp @@ -23,8 +23,8 @@ QgsExpressionHighlighter::QgsExpressionHighlighter( QTextDocument *parent ) keywordFormat.setForeground( Qt::darkBlue ); keywordFormat.setFontWeight( QFont::Bold ); QStringList keywordPatterns; - keywordPatterns << "\\bCASE\\b" << "\\bWHEN\\b" << "\\bTHEN\\b" - << "\\bELSE\\b" << "\\bEND\\b"; + keywordPatterns << QStringLiteral( "\\bCASE\\b" ) << QStringLiteral( "\\bWHEN\\b" ) << QStringLiteral( "\\bTHEN\\b" ) + << QStringLiteral( "\\bELSE\\b" ) << QStringLiteral( "\\bEND\\b" ); Q_FOREACH ( const QString &pattern, keywordPatterns ) { diff --git a/src/gui/qgsexpressionlineedit.cpp b/src/gui/qgsexpressionlineedit.cpp index e54279027fb4..e6e53c0e0115 100644 --- a/src/gui/qgsexpressionlineedit.cpp +++ b/src/gui/qgsexpressionlineedit.cpp @@ -37,7 +37,7 @@ QgsExpressionLineEdit::QgsExpressionLineEdit( QWidget *parent ) { mButton = new QToolButton(); mButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); - mButton->setIcon( QgsApplication::getThemeIcon( "/mIconExpression.svg" ) ); + mButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); connect( mButton, SIGNAL( clicked() ), this, SLOT( editExpression() ) ); //sets up layout @@ -154,7 +154,7 @@ void QgsExpressionLineEdit::editExpression() QgsExpressionContext context = mExpressionContextGenerator ? mExpressionContextGenerator->createExpressionContext() : mExpressionContext; - QgsExpressionBuilderDialog dlg( mLayer, currentExpression, this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, currentExpression, this, QStringLiteral( "generic" ), context ); if ( !mDa.isNull() ) { dlg.setGeomCalculator( *mDa ); diff --git a/src/gui/qgsexpressionselectiondialog.cpp b/src/gui/qgsexpressionselectiondialog.cpp index c9395dc9f9fe..501f6fd37769 100644 --- a/src/gui/qgsexpressionselectiondialog.cpp +++ b/src/gui/qgsexpressionselectiondialog.cpp @@ -26,12 +26,12 @@ QgsExpressionSelectionDialog::QgsExpressionSelectionDialog( QgsVectorLayer* laye { setupUi( this ); - setWindowTitle( QString( "Select by expression - %1" ).arg( layer->name() ) ); + setWindowTitle( QStringLiteral( "Select by expression - %1" ).arg( layer->name() ) ); - mActionSelect->setIcon( QgsApplication::getThemeIcon( "/mIconExpressionSelect.svg" ) ); - mActionAddToSelection->setIcon( QgsApplication::getThemeIcon( "/mIconSelectAdd.svg" ) ); - mActionRemoveFromSelection->setIcon( QgsApplication::getThemeIcon( "/mIconSelectRemove.svg" ) ); - mActionSelectIntersect->setIcon( QgsApplication::getThemeIcon( "/mIconSelectIntersect.svg" ) ); + mActionSelect->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpressionSelect.svg" ) ) ); + mActionAddToSelection->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconSelectAdd.svg" ) ) ); + mActionRemoveFromSelection->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconSelectRemove.svg" ) ) ); + mActionSelectIntersect->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconSelectIntersect.svg" ) ) ); mButtonSelect->addAction( mActionSelect ); mButtonSelect->addAction( mActionAddToSelection ); @@ -42,7 +42,7 @@ QgsExpressionSelectionDialog::QgsExpressionSelectionDialog( QgsVectorLayer* laye mExpressionBuilder->setLayer( layer ); mExpressionBuilder->setExpressionText( startText ); mExpressionBuilder->loadFieldNames(); - mExpressionBuilder->loadRecent( "Selection" ); + mExpressionBuilder->loadRecent( QStringLiteral( "Selection" ) ); QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope() @@ -51,7 +51,7 @@ QgsExpressionSelectionDialog::QgsExpressionSelectionDialog( QgsVectorLayer* laye mExpressionBuilder->setExpressionContext( context ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ExpressionSelectionDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ExpressionSelectionDialog/geometry" ) ).toByteArray() ); } QgsExpressionBuilderWidget* QgsExpressionSelectionDialog::expressionBuilder() @@ -108,7 +108,7 @@ void QgsExpressionSelectionDialog::closeEvent( QCloseEvent *closeEvent ) QDialog::closeEvent( closeEvent ); QSettings settings; - settings.setValue( "/Windows/ExpressionSelectionDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ExpressionSelectionDialog/geometry" ), saveGeometry() ); } void QgsExpressionSelectionDialog::on_mPbnClose_clicked() @@ -124,5 +124,5 @@ void QgsExpressionSelectionDialog::done( int r ) void QgsExpressionSelectionDialog::saveRecent() { - mExpressionBuilder->saveToRecent( "Selection" ); + mExpressionBuilder->saveToRecent( QStringLiteral( "Selection" ) ); } diff --git a/src/gui/qgsexternalresourcewidget.cpp b/src/gui/qgsexternalresourcewidget.cpp index c901752f80e3..d5b131657f8f 100644 --- a/src/gui/qgsexternalresourcewidget.cpp +++ b/src/gui/qgsexternalresourcewidget.cpp @@ -218,7 +218,7 @@ void QgsExternalResourceWidget::loadDocument( const QString& path ) #ifdef WITH_QTWEBKIT if ( mDocumentViewerContent == Web ) { - mWebView->setUrl( QUrl( "about:blank" ) ); + mWebView->setUrl( QUrl( QStringLiteral( "about:blank" ) ) ); } #endif if ( mDocumentViewerContent == Image ) diff --git a/src/gui/qgsfieldcombobox.cpp b/src/gui/qgsfieldcombobox.cpp index 12cece89844c..14d21e355b6a 100644 --- a/src/gui/qgsfieldcombobox.cpp +++ b/src/gui/qgsfieldcombobox.cpp @@ -75,7 +75,7 @@ QString QgsFieldComboBox::currentField() const const QModelIndex proxyIndex = mFieldProxyModel->index( i, 0 ); if ( !proxyIndex.isValid() ) { - return ""; + return QLatin1String( "" ); } QString name = mFieldProxyModel->data( proxyIndex, QgsFieldModel::FieldNameRole ).toString(); diff --git a/src/gui/qgsfieldexpressionwidget.cpp b/src/gui/qgsfieldexpressionwidget.cpp index c4521af29df9..1984e2fae043 100644 --- a/src/gui/qgsfieldexpressionwidget.cpp +++ b/src/gui/qgsfieldexpressionwidget.cpp @@ -46,7 +46,7 @@ QgsFieldExpressionWidget::QgsFieldExpressionWidget( QWidget *parent ) mButton = new QToolButton( this ); mButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); - mButton->setIcon( QgsApplication::getThemeIcon( "/mIconExpression.svg" ) ); + mButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpression.svg" ) ) ); layout->addWidget( mCombo ); layout->addWidget( mButton ); @@ -217,7 +217,7 @@ void QgsFieldExpressionWidget::editExpression() QgsExpressionContext context = mExpressionContextGenerator ? mExpressionContextGenerator->createExpressionContext() : mExpressionContext; - QgsExpressionBuilderDialog dlg( vl, currentExpression, this, "generic", context ); + QgsExpressionBuilderDialog dlg( vl, currentExpression, this, QStringLiteral( "generic" ), context ); if ( !mDa.isNull() ) { dlg.setGeomCalculator( *mDa ); @@ -287,7 +287,7 @@ void QgsFieldExpressionWidget::currentFieldChanged() } else { - mCombo->setToolTip( "" ); + mCombo->setToolTip( QLatin1String( "" ) ); } emit fieldChanged( fieldName ); diff --git a/src/gui/qgsfieldvalidator.cpp b/src/gui/qgsfieldvalidator.cpp index 9814d3137999..8c4eea9da809 100644 --- a/src/gui/qgsfieldvalidator.cpp +++ b/src/gui/qgsfieldvalidator.cpp @@ -41,7 +41,7 @@ QgsFieldValidator::QgsFieldValidator( QObject *parent, const QgsField &field, co { if ( mField.length() > 0 ) { - QString re = QString( "-?\\d{0,%1}" ).arg( mField.length() ); + QString re = QStringLiteral( "-?\\d{0,%1}" ).arg( mField.length() ); mValidator = new QRegExpValidator( QRegExp( re ), parent ); } else @@ -55,17 +55,17 @@ QgsFieldValidator::QgsFieldValidator( QObject *parent, const QgsField &field, co { if ( mField.length() > 0 && mField.precision() > 0 ) { - QString re = QString( "-?\\d{0,%1}(\\.\\d{0,%2})?" ).arg( mField.length() - mField.precision() ).arg( mField.precision() ); + QString re = QStringLiteral( "-?\\d{0,%1}(\\.\\d{0,%2})?" ).arg( mField.length() - mField.precision() ).arg( mField.precision() ); mValidator = new QRegExpValidator( QRegExp( re ), parent ); } else if ( mField.length() > 0 && mField.precision() == 0 ) { - QString re = QString( "-?\\d{0,%1}" ).arg( mField.length() ); + QString re = QStringLiteral( "-?\\d{0,%1}" ).arg( mField.length() ); mValidator = new QRegExpValidator( QRegExp( re ), parent ); } else if ( mField.precision() > 0 ) { - QString re = QString( "-?\\d*(\\.\\d{0,%1})?" ).arg( mField.precision() ); + QString re = QStringLiteral( "-?\\d*(\\.\\d{0,%1})?" ).arg( mField.precision() ); mValidator = new QRegExpValidator( QRegExp( re ), parent ); } else @@ -84,7 +84,7 @@ QgsFieldValidator::QgsFieldValidator( QObject *parent, const QgsField &field, co } QSettings settings; - mNullValue = settings.value( "qgis/nullValue", "NULL" ).toString(); + mNullValue = settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } QgsFieldValidator::~QgsFieldValidator() @@ -158,6 +158,6 @@ void QgsFieldValidator::fixup( QString &s ) const else if ( mField.type() == QVariant::Date ) { // invalid dates will also translate to NULL - s = ""; + s = QLatin1String( "" ); } } diff --git a/src/gui/qgsfieldvalidator.h b/src/gui/qgsfieldvalidator.h index 82393a67cab9..a8c353e8072d 100644 --- a/src/gui/qgsfieldvalidator.h +++ b/src/gui/qgsfieldvalidator.h @@ -33,7 +33,12 @@ class GUI_EXPORT QgsFieldValidator : public QValidator Q_OBJECT public: - QgsFieldValidator( QObject *parent, const QgsField &field, const QString& defaultValue, const QString& dateFormat = "yyyy-MM-dd" ); + + /** + * Constructor for QgsFieldValidator. + */ + QgsFieldValidator( QObject *parent, const QgsField &field, const QString& defaultValue, const QString& dateFormat = QStringLiteral( "yyyy-MM-dd" ) ); + ~QgsFieldValidator(); virtual State validate( QString &, int & ) const override; diff --git a/src/gui/qgsfilewidget.cpp b/src/gui/qgsfilewidget.cpp index 8dbcfc19184f..ad22c4b97827 100644 --- a/src/gui/qgsfilewidget.cpp +++ b/src/gui/qgsfilewidget.cpp @@ -64,7 +64,7 @@ QgsFileWidget::QgsFileWidget( QWidget *parent ) layout->addWidget( mLineEdit, 1, 0 ); mFileWidgetButton = new QToolButton( this ); - mFileWidgetButton->setText( "..." ); + mFileWidgetButton->setText( QStringLiteral( "..." ) ); connect( mFileWidgetButton, SIGNAL( clicked() ), this, SLOT( openFileDialog() ) ); layout->addWidget( mFileWidgetButton, 0, 1, 2, 1 ); @@ -82,9 +82,9 @@ QString QgsFileWidget::filePath() void QgsFileWidget::setFilePath( QString path ) { - if ( path == QSettings().value( "qgis/nullValue", "NULL" ) ) + if ( path == QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ) ) { - path = ""; + path = QLatin1String( "" ); } //will trigger textEdited slot @@ -212,7 +212,7 @@ void QgsFileWidget::openFileDialog() { defPath = QDir::homePath(); } - oldPath = settings.value( "/UI/lastExternalResourceWidgetDefaultPath", defPath ).toString(); + oldPath = settings.value( QStringLiteral( "/UI/lastExternalResourceWidgetDefaultPath" ), defPath ).toString(); } // Handle Storage @@ -238,11 +238,11 @@ void QgsFileWidget::openFileDialog() if ( mStorageMode == GetFile ) { - settings.setValue( "/UI/lastFileNameWidgetDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/UI/lastFileNameWidgetDir" ), QFileInfo( fileName ).absolutePath() ); } else if ( mStorageMode == GetDirectory ) { - settings.setValue( "/UI/lastFileNameWidgetDir", fileName ); + settings.setValue( QStringLiteral( "/UI/lastFileNameWidgetDir" ), fileName ); } // Handle relative Path storage @@ -286,7 +286,7 @@ QString QgsFileWidget::toUrl( const QString& path ) const QString rep; if ( path.isEmpty() ) { - return QSettings().value( "qgis/nullValue", "NULL" ).toString(); + return QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); } QString urlStr = relativePath( path, false ); @@ -300,12 +300,12 @@ QString QgsFileWidget::toUrl( const QString& path ) const QString pathStr = url.toString(); if ( mFullUrl ) { - rep = QString( "<a href=\"%1\">%2</a>" ).arg( pathStr, path ); + rep = QStringLiteral( "<a href=\"%1\">%2</a>" ).arg( pathStr, path ); } else { QString fileName = QFileInfo( urlStr ).fileName(); - rep = QString( "<a href=\"%1\">%2</a>" ).arg( pathStr, fileName ); + rep = QStringLiteral( "<a href=\"%1\">%2</a>" ).arg( pathStr, fileName ); } return rep; diff --git a/src/gui/qgsfilterlineedit.cpp b/src/gui/qgsfilterlineedit.cpp index ee7540818171..ebe58ad40385 100644 --- a/src/gui/qgsfilterlineedit.cpp +++ b/src/gui/qgsfilterlineedit.cpp @@ -150,7 +150,7 @@ void QgsFilterLineEdit::onTextChanged( const QString &text ) { if ( isNull() ) { - setStyleSheet( QString( "QLineEdit { font: italic; color: gray; } %1" ).arg( mStyleSheet ) ); + setStyleSheet( QStringLiteral( "QLineEdit { font: italic; color: gray; } %1" ).arg( mStyleSheet ) ); emit valueChanged( QString::null ); } else diff --git a/src/gui/qgsformannotationitem.cpp b/src/gui/qgsformannotationitem.cpp index 70020f036890..936f2a8e9ae1 100644 --- a/src/gui/qgsformannotationitem.cpp +++ b/src/gui/qgsformannotationitem.cpp @@ -188,14 +188,14 @@ void QgsFormAnnotationItem::writeXml( QDomDocument& doc ) const return; } - QDomElement formAnnotationElem = doc.createElement( "FormAnnotationItem" ); + QDomElement formAnnotationElem = doc.createElement( QStringLiteral( "FormAnnotationItem" ) ); if ( mVectorLayer ) { - formAnnotationElem.setAttribute( "vectorLayer", mVectorLayer->id() ); + formAnnotationElem.setAttribute( QStringLiteral( "vectorLayer" ), mVectorLayer->id() ); } - formAnnotationElem.setAttribute( "hasFeature", mHasAssociatedFeature ); - formAnnotationElem.setAttribute( "feature", mFeature ); - formAnnotationElem.setAttribute( "designerForm", mDesignerForm ); + formAnnotationElem.setAttribute( QStringLiteral( "hasFeature" ), mHasAssociatedFeature ); + formAnnotationElem.setAttribute( QStringLiteral( "feature" ), mFeature ); + formAnnotationElem.setAttribute( QStringLiteral( "designerForm" ), mDesignerForm ); _writeXml( doc, formAnnotationElem ); documentElem.appendChild( formAnnotationElem ); } @@ -203,9 +203,9 @@ void QgsFormAnnotationItem::writeXml( QDomDocument& doc ) const void QgsFormAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& itemElem ) { mVectorLayer = nullptr; - if ( itemElem.hasAttribute( "vectorLayer" ) ) + if ( itemElem.hasAttribute( QStringLiteral( "vectorLayer" ) ) ) { - mVectorLayer = dynamic_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( itemElem.attribute( "vectorLayer", "" ) ) ); + mVectorLayer = dynamic_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( itemElem.attribute( QStringLiteral( "vectorLayer" ), QLatin1String( "" ) ) ) ); if ( mVectorLayer ) { QObject::connect( mVectorLayer, SIGNAL( layerModified() ), this, SLOT( setFeatureForMapPosition() ) ); @@ -213,10 +213,10 @@ void QgsFormAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& QObject::connect( mMapCanvas, SIGNAL( layersChanged() ), this, SLOT( updateVisibility() ) ); } } - mHasAssociatedFeature = itemElem.attribute( "hasFeature", "0" ).toInt(); - mFeature = itemElem.attribute( "feature", "0" ).toInt(); - mDesignerForm = itemElem.attribute( "designerForm", "" ); - QDomElement annotationElem = itemElem.firstChildElement( "AnnotationItem" ); + mHasAssociatedFeature = itemElem.attribute( QStringLiteral( "hasFeature" ), QStringLiteral( "0" ) ).toInt(); + mFeature = itemElem.attribute( QStringLiteral( "feature" ), QStringLiteral( "0" ) ).toInt(); + mDesignerForm = itemElem.attribute( QStringLiteral( "designerForm" ), QLatin1String( "" ) ); + QDomElement annotationElem = itemElem.firstChildElement( QStringLiteral( "AnnotationItem" ) ); if ( !annotationElem.isNull() ) { _readXml( doc, annotationElem ); diff --git a/src/gui/qgsgenericprojectionselector.cpp b/src/gui/qgsgenericprojectionselector.cpp index 1b74f78ee9c3..2ab1dc86862d 100644 --- a/src/gui/qgsgenericprojectionselector.cpp +++ b/src/gui/qgsgenericprojectionselector.cpp @@ -32,7 +32,7 @@ QgsGenericProjectionSelector::QgsGenericProjectionSelector( QWidget *parent, setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/ProjectionSelector/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/ProjectionSelector/geometry" ) ).toByteArray() ); //we will show this only when a message is set textEdit->hide(); @@ -48,7 +48,7 @@ void QgsGenericProjectionSelector::setMessage( QString theMessage ) if ( theMessage.isEmpty() ) { // Set up text edit pane - QString format( "<h1>%1</h1>%2 %3" ); + QString format( QStringLiteral( "<h1>%1</h1>%2 %3" ) ); QString header = tr( "Define this layer's coordinate reference system:" ); QString sentence1 = tr( "This layer appears to have no projection specification." ); QString sentence2 = tr( "By default, this layer will now have its projection set to that of the project, " @@ -65,7 +65,7 @@ void QgsGenericProjectionSelector::setMessage( QString theMessage ) QgsGenericProjectionSelector::~QgsGenericProjectionSelector() { QSettings settings; - settings.setValue( "/Windows/ProjectionSelector/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/ProjectionSelector/geometry" ), saveGeometry() ); } void QgsGenericProjectionSelector::setSelectedCrsName( const QString& theName ) diff --git a/src/gui/qgsgenericprojectionselector.h b/src/gui/qgsgenericprojectionselector.h index 2abc6d64c336..35ce08b561c4 100644 --- a/src/gui/qgsgenericprojectionselector.h +++ b/src/gui/qgsgenericprojectionselector.h @@ -61,7 +61,7 @@ class GUI_EXPORT QgsGenericProjectionSelector : public QDialog, private Ui::QgsG /** If no parameter is passed, the message will be a generic * 'define the CRS for this layer'. */ - void setMessage( QString theMessage = "" ); + void setMessage( QString theMessage = QStringLiteral( "" ) ); long selectedCrsId(); QString selectedAuthId(); diff --git a/src/gui/qgsgradientcolorrampdialog.cpp b/src/gui/qgsgradientcolorrampdialog.cpp index dbd3d8cc7451..8d4b0bd41a62 100644 --- a/src/gui/qgsgradientcolorrampdialog.cpp +++ b/src/gui/qgsgradientcolorrampdialog.cpp @@ -54,12 +54,12 @@ QgsGradientColorRampDialog::QgsGradientColorRampDialog( const QgsGradientColorRa mPositionSpinBox->setShowClearButton( false ); btnColor1->setAllowAlpha( true ); btnColor1->setColorDialogTitle( tr( "Select ramp color" ) ); - btnColor1->setContext( "symbology" ); + btnColor1->setContext( QStringLiteral( "symbology" ) ); btnColor1->setShowNoColor( true ); btnColor1->setNoColorString( tr( "Transparent" ) ); btnColor2->setAllowAlpha( true ); btnColor2->setColorDialogTitle( tr( "Select ramp color" ) ); - btnColor2->setContext( "symbology" ); + btnColor2->setContext( QStringLiteral( "symbology" ) ); btnColor2->setShowNoColor( true ); btnColor2->setNoColorString( tr( "Transparent" ) ); updateColorButtons(); @@ -86,7 +86,7 @@ QgsGradientColorRampDialog::QgsGradientColorRampDialog( const QgsGradientColorRa connect( mDeleteStopButton, SIGNAL( clicked() ), mStopEditor, SLOT( deleteSelectedStop() ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/GradientEditor/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/GradientEditor/geometry" ) ).toByteArray() ); // hide the ugly canvas frame mPlot->setFrameStyle( QFrame::NoFrame ); @@ -102,25 +102,25 @@ QgsGradientColorRampDialog::QgsGradientColorRampDialog( const QgsGradientColorRa mPlot->enableAxis( QwtPlot::yLeft, false ); mLightnessCurve = new QwtPlotCurve(); - mLightnessCurve->setTitle( "Lightness" ); + mLightnessCurve->setTitle( QStringLiteral( "Lightness" ) ); mLightnessCurve->setPen( QPen( QColor( 70, 150, 255 ), 0.0 ) ), mLightnessCurve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); mLightnessCurve->attach( mPlot ); mHueCurve = new QwtPlotCurve(); - mHueCurve->setTitle( "Hue" ); + mHueCurve->setTitle( QStringLiteral( "Hue" ) ); mHueCurve->setPen( QPen( QColor( 255, 215, 70 ), 0.0 ) ), mHueCurve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); mHueCurve->attach( mPlot ); mSaturationCurve = new QwtPlotCurve(); - mSaturationCurve->setTitle( "Saturation" ); + mSaturationCurve->setTitle( QStringLiteral( "Saturation" ) ); mSaturationCurve->setPen( QPen( QColor( 255, 70, 150 ), 0.0 ) ), mSaturationCurve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); mSaturationCurve->attach( mPlot ); mAlphaCurve = new QwtPlotCurve(); - mAlphaCurve->setTitle( "Alpha" ); + mAlphaCurve->setTitle( QStringLiteral( "Alpha" ) ); mAlphaCurve->setPen( QPen( QColor( 50, 50, 50 ), 0.0 ) ), mAlphaCurve->setRenderHint( QwtPlotItem::RenderAntialiased, true ); mAlphaCurve->attach( mPlot ); @@ -130,10 +130,10 @@ QgsGradientColorRampDialog::QgsGradientColorRampDialog( const QgsGradientColorRa connect( mPlotFilter, SIGNAL( mouseRelease( QPointF ) ), this, SLOT( plotMouseRelease( QPointF ) ) ); connect( mPlotFilter, SIGNAL( mouseMove( QPointF ) ), this, SLOT( plotMouseMove( QPointF ) ) ); - mPlotHueCheckbox->setChecked( settings.value( "/GradientEditor/plotHue", false ).toBool() ); - mPlotLightnessCheckbox->setChecked( settings.value( "/GradientEditor/plotLightness", true ).toBool() ); - mPlotSaturationCheckbox->setChecked( settings.value( "/GradientEditor/plotSaturation", false ).toBool() ); - mPlotAlphaCheckbox->setChecked( settings.value( "/GradientEditor/plotAlpha", false ).toBool() ); + mPlotHueCheckbox->setChecked( settings.value( QStringLiteral( "/GradientEditor/plotHue" ), false ).toBool() ); + mPlotLightnessCheckbox->setChecked( settings.value( QStringLiteral( "/GradientEditor/plotLightness" ), true ).toBool() ); + mPlotSaturationCheckbox->setChecked( settings.value( QStringLiteral( "/GradientEditor/plotSaturation" ), false ).toBool() ); + mPlotAlphaCheckbox->setChecked( settings.value( QStringLiteral( "/GradientEditor/plotAlpha" ), false ).toBool() ); mHueCurve->setVisible( mPlotHueCheckbox->isChecked() ); mLightnessCurve->setVisible( mPlotLightnessCheckbox->isChecked() ); @@ -147,11 +147,11 @@ QgsGradientColorRampDialog::QgsGradientColorRampDialog( const QgsGradientColorRa QgsGradientColorRampDialog::~QgsGradientColorRampDialog() { QSettings settings; - settings.setValue( "/Windows/GradientEditor/geometry", saveGeometry() ); - settings.setValue( "/GradientEditor/plotHue", mPlotHueCheckbox->isChecked() ); - settings.setValue( "/GradientEditor/plotLightness", mPlotLightnessCheckbox->isChecked() ); - settings.setValue( "/GradientEditor/plotSaturation", mPlotSaturationCheckbox->isChecked() ); - settings.setValue( "/GradientEditor/plotAlpha", mPlotAlphaCheckbox->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/GradientEditor/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/GradientEditor/plotHue" ), mPlotHueCheckbox->isChecked() ); + settings.setValue( QStringLiteral( "/GradientEditor/plotLightness" ), mPlotLightnessCheckbox->isChecked() ); + settings.setValue( QStringLiteral( "/GradientEditor/plotSaturation" ), mPlotSaturationCheckbox->isChecked() ); + settings.setValue( QStringLiteral( "/GradientEditor/plotAlpha" ), mPlotAlphaCheckbox->isChecked() ); } @@ -198,7 +198,7 @@ void QgsGradientColorRampDialog::on_btnInformation_pressed() for ( QgsStringMap::const_iterator it = rampInfo.constBegin(); it != rampInfo.constEnd(); ++it ) { - if ( it.key().startsWith( "cpt-city" ) ) + if ( it.key().startsWith( QLatin1String( "cpt-city" ) ) ) continue; tableInfo->setItem( i, 0, new QTableWidgetItem( it.key() ) ); tableInfo->setItem( i, 1, new QTableWidgetItem( it.value() ) ); @@ -215,15 +215,15 @@ void QgsGradientColorRampDialog::on_btnInformation_pressed() dlg->layout()->addSpacing( 5 ); // gradient file - QString gradientFile = mRamp.info().value( "cpt-city-gradient" ); + QString gradientFile = mRamp.info().value( QStringLiteral( "cpt-city-gradient" ) ); if ( ! gradientFile.isNull() ) { QString fileName = gradientFile; - fileName.replace( "<cpt-city>", QgsCptCityArchive::defaultBaseDir() ); + fileName.replace( QLatin1String( "<cpt-city>" ), QgsCptCityArchive::defaultBaseDir() ); if ( ! QFile::exists( fileName ) ) { fileName = gradientFile; - fileName.replace( "<cpt-city>", "http://soliton.vm.bytemark.co.uk/pub/cpt-city" ); + fileName.replace( QLatin1String( "<cpt-city>" ), QLatin1String( "http://soliton.vm.bytemark.co.uk/pub/cpt-city" ) ); } label = new QLabel( tr( "Gradient file : %1" ).arg( fileName ), dlg ); label->setTextInteractionFlags( Qt::TextBrowserInteraction ); @@ -232,15 +232,15 @@ void QgsGradientColorRampDialog::on_btnInformation_pressed() } // license file - QString licenseFile = mRamp.info().value( "cpt-city-license" ); + QString licenseFile = mRamp.info().value( QStringLiteral( "cpt-city-license" ) ); if ( !licenseFile.isNull() ) { QString fileName = licenseFile; - fileName.replace( "<cpt-city>", QgsCptCityArchive::defaultBaseDir() ); + fileName.replace( QLatin1String( "<cpt-city>" ), QgsCptCityArchive::defaultBaseDir() ); if ( ! QFile::exists( fileName ) ) { fileName = licenseFile; - fileName.replace( "<cpt-city>", "http://soliton.vm.bytemark.co.uk/pub/cpt-city" ); + fileName.replace( QLatin1String( "<cpt-city>" ), QLatin1String( "http://soliton.vm.bytemark.co.uk/pub/cpt-city" ) ); } label = new QLabel( tr( "License file : %1" ).arg( fileName ), dlg ); label->setTextInteractionFlags( Qt::TextBrowserInteraction ); diff --git a/src/gui/qgsgradientstopeditor.cpp b/src/gui/qgsgradientstopeditor.cpp index e01fe73fd635..2d2e4c7d84c4 100644 --- a/src/gui/qgsgradientstopeditor.cpp +++ b/src/gui/qgsgradientstopeditor.cpp @@ -381,7 +381,7 @@ const QPixmap& QgsGradientStopEditor::transparentBackground() static QPixmap transpBkgrd; if ( transpBkgrd.isNull() ) - transpBkgrd = QgsApplication::getThemePixmap( "/transp-background_8x8.png" ); + transpBkgrd = QgsApplication::getThemePixmap( QStringLiteral( "/transp-background_8x8.png" ) ); return transpBkgrd; } diff --git a/src/gui/qgshighlight.cpp b/src/gui/qgshighlight.cpp index 029fbc73e727..4be8d80ac68a 100644 --- a/src/gui/qgshighlight.cpp +++ b/src/gui/qgshighlight.cpp @@ -182,8 +182,8 @@ void QgsHighlight::setSymbol( QgsSymbol* symbol, const QgsRenderContext & contex { simpleFill->setBorderWidth( getSymbolWidth( context, simpleFill->borderWidth(), simpleFill->outputUnit() ) ); } - symbolLayer->removeDataDefinedProperty( "color" ); - symbolLayer->removeDataDefinedProperty( "color_border" ); + symbolLayer->removeDataDefinedProperty( QStringLiteral( "color" ) ); + symbolLayer->removeDataDefinedProperty( QStringLiteral( "color_border" ) ); } } } diff --git a/src/gui/qgshistogramwidget.cpp b/src/gui/qgshistogramwidget.cpp index b125b22a0a96..68314c8a9084 100644 --- a/src/gui/qgshistogramwidget.cpp +++ b/src/gui/qgshistogramwidget.cpp @@ -63,8 +63,8 @@ QgsHistogramWidget::QgsHistogramWidget( QWidget *parent, QgsVectorLayer* layer, #endif QSettings settings; - mMeanCheckBox->setChecked( settings.value( "/HistogramWidget/showMean", false ).toBool() ); - mStdevCheckBox->setChecked( settings.value( "/HistogramWidget/showStdev", false ).toBool() ); + mMeanCheckBox->setChecked( settings.value( QStringLiteral( "/HistogramWidget/showMean" ), false ).toBool() ); + mStdevCheckBox->setChecked( settings.value( QStringLiteral( "/HistogramWidget/showStdev" ), false ).toBool() ); connect( mBinsSpinBox, SIGNAL( valueChanged( int ) ), this, SLOT( refresh() ) ); connect( mMeanCheckBox, SIGNAL( toggled( bool ) ), this, SLOT( refresh() ) ); @@ -86,8 +86,8 @@ QgsHistogramWidget::QgsHistogramWidget( QWidget *parent, QgsVectorLayer* layer, QgsHistogramWidget::~QgsHistogramWidget() { QSettings settings; - settings.setValue( "/HistogramWidget/showMean", mMeanCheckBox->isChecked() ); - settings.setValue( "/HistogramWidget/showStdev", mStdevCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/HistogramWidget/showMean" ), mMeanCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/HistogramWidget/showStdev" ), mStdevCheckBox->isChecked() ); } static bool _rangesByLower( const QgsRendererRange& a, const QgsRendererRange& b ) diff --git a/src/gui/qgshtmlannotationitem.cpp b/src/gui/qgshtmlannotationitem.cpp index ae3e02004854..e66f18dd2d91 100644 --- a/src/gui/qgshtmlannotationitem.cpp +++ b/src/gui/qgshtmlannotationitem.cpp @@ -75,7 +75,7 @@ void QgsHtmlAnnotationItem::setHTMLPage( const QString& htmlFile ) mHtmlFile = htmlFile; if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { - mHtmlSource = ""; + mHtmlSource = QLatin1String( "" ); } else { @@ -117,7 +117,7 @@ void QgsHtmlAnnotationItem::paint( QPainter * painter, const QStyleOptionGraphic mWidgetContainer->setGeometry( QRectF( mOffsetFromReferencePoint.x() + mFrameBorderWidth / 2.0, mOffsetFromReferencePoint.y() + mFrameBorderWidth / 2.0, mFrameSize.width() - mFrameBorderWidth, mFrameSize.height() - mFrameBorderWidth ) ); - if ( data( 1 ).toString() == "composer" ) + if ( data( 1 ).toString() == QLatin1String( "composer" ) ) { mWidgetContainer->widget()->render( painter, mOffsetFromReferencePoint.toPoint() ); } @@ -149,14 +149,14 @@ void QgsHtmlAnnotationItem::writeXml( QDomDocument& doc ) const return; } - QDomElement formAnnotationElem = doc.createElement( "HtmlAnnotationItem" ); + QDomElement formAnnotationElem = doc.createElement( QStringLiteral( "HtmlAnnotationItem" ) ); if ( mVectorLayer ) { - formAnnotationElem.setAttribute( "vectorLayer", mVectorLayer->id() ); + formAnnotationElem.setAttribute( QStringLiteral( "vectorLayer" ), mVectorLayer->id() ); } - formAnnotationElem.setAttribute( "hasFeature", mHasAssociatedFeature ); - formAnnotationElem.setAttribute( "feature", mFeatureId ); - formAnnotationElem.setAttribute( "htmlfile", htmlPage() ); + formAnnotationElem.setAttribute( QStringLiteral( "hasFeature" ), mHasAssociatedFeature ); + formAnnotationElem.setAttribute( QStringLiteral( "feature" ), mFeatureId ); + formAnnotationElem.setAttribute( QStringLiteral( "htmlfile" ), htmlPage() ); _writeXml( doc, formAnnotationElem ); documentElem.appendChild( formAnnotationElem ); @@ -165,9 +165,9 @@ void QgsHtmlAnnotationItem::writeXml( QDomDocument& doc ) const void QgsHtmlAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& itemElem ) { mVectorLayer = nullptr; - if ( itemElem.hasAttribute( "vectorLayer" ) ) + if ( itemElem.hasAttribute( QStringLiteral( "vectorLayer" ) ) ) { - mVectorLayer = dynamic_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( itemElem.attribute( "vectorLayer", "" ) ) ); + mVectorLayer = dynamic_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( itemElem.attribute( QStringLiteral( "vectorLayer" ), QLatin1String( "" ) ) ) ); if ( mVectorLayer ) { QObject::connect( mVectorLayer, SIGNAL( layerModified() ), this, SLOT( setFeatureForMapPosition() ) ); @@ -175,10 +175,10 @@ void QgsHtmlAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& QObject::connect( mMapCanvas, SIGNAL( layersChanged() ), this, SLOT( updateVisibility() ) ); } } - mHasAssociatedFeature = itemElem.attribute( "hasFeature", "0" ).toInt(); - mFeatureId = itemElem.attribute( "feature", "0" ).toInt(); - mHtmlFile = itemElem.attribute( "htmlfile", "" ); - QDomElement annotationElem = itemElem.firstChildElement( "AnnotationItem" ); + mHasAssociatedFeature = itemElem.attribute( QStringLiteral( "hasFeature" ), QStringLiteral( "0" ) ).toInt(); + mFeatureId = itemElem.attribute( QStringLiteral( "feature" ), QStringLiteral( "0" ) ).toInt(); + mHtmlFile = itemElem.attribute( QStringLiteral( "htmlfile" ), QLatin1String( "" ) ); + QDomElement annotationElem = itemElem.firstChildElement( QStringLiteral( "AnnotationItem" ) ); if ( !annotationElem.isNull() ) { _readXml( doc, annotationElem ); @@ -246,8 +246,8 @@ void QgsHtmlAnnotationItem::updateVisibility() void QgsHtmlAnnotationItem::javascript() { QWebFrame *frame = mWebView->page()->mainFrame(); - frame->addToJavaScriptWindowObject( "canvas", mMapCanvas ); - frame->addToJavaScriptWindowObject( "layer", mVectorLayer ); + frame->addToJavaScriptWindowObject( QStringLiteral( "canvas" ), mMapCanvas ); + frame->addToJavaScriptWindowObject( QStringLiteral( "layer" ), mVectorLayer ); } diff --git a/src/gui/qgsidentifymenu.cpp b/src/gui/qgsidentifymenu.cpp index e5e4c2b69e36..0478ca81f416 100644 --- a/src/gui/qgsidentifymenu.cpp +++ b/src/gui/qgsidentifymenu.cpp @@ -131,7 +131,7 @@ QList<QgsMapToolIdentify::IdentifyResult> QgsIdentifyMenu::exec( const QList<Qgs if ( !singleLayer && mAllowMultipleReturn && idResults.count() > 1 ) { addSeparator(); - QAction* allAction = new QAction( QgsApplication::getThemeIcon( "/mActionIdentify.svg" ), tr( "%1 all (%2)" ).arg( mDefaultActionName ).arg( idResults.count() ), this ); + QAction* allAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionIdentify.svg" ) ), tr( "%1 all (%2)" ).arg( mDefaultActionName ).arg( idResults.count() ), this ); allAction->setData( QVariant::fromValue<ActionData>( ActionData( nullptr ) ) ); connect( allAction, SIGNAL( hovered() ), this, SLOT( handleMenuHover() ) ); addAction( allAction ); @@ -196,7 +196,7 @@ void QgsIdentifyMenu::addRasterLayer( QgsMapLayer* layer ) } // add layer action to the top menu - layerAction->setIcon( QgsApplication::getThemeIcon( "/mIconRasterLayer.svg" ) ); + layerAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconRasterLayer.svg" ) ) ); layerAction->setData( QVariant::fromValue<ActionData>( ActionData( layer ) ) ); connect( layerAction, SIGNAL( hovered() ), this, SLOT( handleMenuHover() ) ); addAction( layerAction ); @@ -278,8 +278,8 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT // case 1 QString featureTitle = results[0].mFeature.attribute( layer->displayField() ).toString(); if ( featureTitle.isEmpty() ) - featureTitle = QString( "%1" ).arg( results[0].mFeature.id() ); - layerAction = new QAction( QString( "%1 (%2)" ).arg( layer->name(), featureTitle ), this ); + featureTitle = QStringLiteral( "%1" ).arg( results[0].mFeature.id() ); + layerAction = new QAction( QStringLiteral( "%1 (%2)" ).arg( layer->name(), featureTitle ), this ); } else { @@ -300,8 +300,8 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT { QString featureTitle = results[0].mFeature.attribute( layer->displayField() ).toString(); if ( featureTitle.isEmpty() ) - featureTitle = QString( "%1" ).arg( results[0].mFeature.id() ); - layerMenu = new QMenu( QString( "%1 (%2)" ).arg( layer->name(), featureTitle ), this ); + featureTitle = QStringLiteral( "%1" ).arg( results[0].mFeature.id() ); + layerMenu = new QMenu( QStringLiteral( "%1 (%2)" ).arg( layer->name(), featureTitle ), this ); } layerAction = layerMenu->menuAction(); } @@ -314,13 +314,13 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT switch ( layer->geometryType() ) { case QgsWkbTypes::PointGeometry: - layerAction->setIcon( QgsApplication::getThemeIcon( "/mIconPointLayer.svg" ) ); + layerAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPointLayer.svg" ) ) ); break; case QgsWkbTypes::LineGeometry: - layerAction->setIcon( QgsApplication::getThemeIcon( "/mIconLineLayer.svg" ) ); + layerAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconLineLayer.svg" ) ) ); break; case QgsWkbTypes::PolygonGeometry: - layerAction->setIcon( QgsApplication::getThemeIcon( "/mIconPolygonLayer.svg" ) ); + layerAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPolygonLayer.svg" ) ) ); break; default: break; @@ -357,7 +357,7 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT // feature title QString featureTitle = result.mFeature.attribute( layer->displayField() ).toString(); if ( featureTitle.isEmpty() ) - featureTitle = QString( "%1" ).arg( result.mFeature.id() ); + featureTitle = QStringLiteral( "%1" ).arg( result.mFeature.id() ); if ( customFeatureActions.isEmpty() && ( !featureActionMenu || featureActionMenu->actions().isEmpty() ) ) { @@ -391,7 +391,7 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT continue; // add default identify action - QAction* identifyFeatureAction = new QAction( QgsApplication::getThemeIcon( "/mActionIdentify.svg" ), mDefaultActionName, featureMenu ); + QAction* identifyFeatureAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionIdentify.svg" ) ), mDefaultActionName, featureMenu ); connect( identifyFeatureAction, SIGNAL( hovered() ), this, SLOT( handleMenuHover() ) ); identifyFeatureAction->setData( QVariant::fromValue<ActionData>( ActionData( layer, result.mFeature.id() ) ) ); featureMenu->addAction( identifyFeatureAction ); @@ -423,7 +423,7 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT if ( mAllowMultipleReturn && results.count() > 1 ) { layerMenu->addSeparator(); - QAction* allAction = new QAction( QgsApplication::getThemeIcon( "/mActionIdentify.svg" ), tr( "%1 all (%2)" ).arg( mDefaultActionName ).arg( results.count() ), layerMenu ); + QAction* allAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionIdentify.svg" ) ), tr( "%1 all (%2)" ).arg( mDefaultActionName ).arg( results.count() ), layerMenu ); allAction->setData( QVariant::fromValue<ActionData>( ActionData( layer ) ) ); connect( allAction, SIGNAL( hovered() ), this, SLOT( handleMenuHover() ) ); layerMenu->addAction( allAction ); @@ -434,7 +434,7 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList<QgsMapT { QString title = mapLayerAction->text(); if ( mapLayerAction->targets().testFlag( QgsMapLayerAction::MultipleFeatures ) ) - title.append( QString( " (%1)" ).arg( results.count() ) ); + title.append( QStringLiteral( " (%1)" ).arg( results.count() ) ); QAction* action = new QAction( mapLayerAction->icon(), title, layerMenu ); action->setData( QVariant::fromValue<ActionData>( ActionData( layer, mapLayerAction ) ) ); connect( action, SIGNAL( hovered() ), this, SLOT( handleMenuHover() ) ); @@ -602,10 +602,10 @@ void QgsIdentifyMenu::handleMenuHover() QgsHighlight *hl = new QgsHighlight( mCanvas, result.mFeature.geometry(), vl ); QSettings settings; - QColor color = QColor( settings.value( "/Map/highlight/color", Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); - int alpha = settings.value( "/Map/highlight/colorAlpha", Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); - double buffer = settings.value( "/Map/highlight/buffer", Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); - double minWidth = settings.value( "/Map/highlight/minWidth", Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); + QColor color = QColor( settings.value( QStringLiteral( "/Map/highlight/color" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.name() ).toString() ); + int alpha = settings.value( QStringLiteral( "/Map/highlight/colorAlpha" ), Qgis::DEFAULT_HIGHLIGHT_COLOR.alpha() ).toInt(); + double buffer = settings.value( QStringLiteral( "/Map/highlight/buffer" ), Qgis::DEFAULT_HIGHLIGHT_BUFFER_MM ).toDouble(); + double minWidth = settings.value( QStringLiteral( "/Map/highlight/minWidth" ), Qgis::DEFAULT_HIGHLIGHT_MIN_WIDTH_MM ).toDouble(); hl->setColor( color ); // sets also fill with default alpha color.setAlpha( alpha ); hl->setFillColor( color ); // sets fill with alpha diff --git a/src/gui/qgskeyvaluewidget.cpp b/src/gui/qgskeyvaluewidget.cpp index c18de8dc29ed..e2a3b89c977b 100644 --- a/src/gui/qgskeyvaluewidget.cpp +++ b/src/gui/qgskeyvaluewidget.cpp @@ -123,7 +123,7 @@ bool QgsKeyValueModel::insertRows( int position, int rows, const QModelIndex & p beginInsertRows( QModelIndex(), position, position + rows - 1 ); for ( int i = 0; i < rows; ++i ) { - mLines.insert( position, Line( "", QVariant() ) ); + mLines.insert( position, Line( QLatin1String( "" ), QVariant() ) ); } endInsertRows(); return true; diff --git a/src/gui/qgslegendfilterbutton.cpp b/src/gui/qgslegendfilterbutton.cpp index ed946ca6773a..e33c495de715 100644 --- a/src/gui/qgslegendfilterbutton.cpp +++ b/src/gui/qgslegendfilterbutton.cpp @@ -38,7 +38,7 @@ QgsLegendFilterButton::QgsLegendFilterButton( QWidget* parent ) mMenu->addAction( mClearExpressionAction ); setCheckable( true ); - setIcon( QgsApplication::getThemeIcon( "/mIconExpressionFilter.svg" ) ); + setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpressionFilter.svg" ) ) ); setPopupMode( QToolButton::MenuButtonPopup ); setMenu( mMenu ); @@ -87,7 +87,7 @@ void QgsLegendFilterButton::onSetLegendFilterExpression() void QgsLegendFilterButton::onClearFilterExpression() { mClearExpressionAction->setEnabled( false ); - setExpressionText( "" ); + setExpressionText( QLatin1String( "" ) ); setChecked( false ); } diff --git a/src/gui/qgslonglongvalidator.h b/src/gui/qgslonglongvalidator.h index eea7652b41ec..057636594297 100644 --- a/src/gui/qgslonglongvalidator.h +++ b/src/gui/qgslonglongvalidator.h @@ -58,7 +58,7 @@ class GUI_EXPORT QgsLongLongValidator : public QValidator if ( t < 0 && input.startsWith( '+' ) ) return Invalid; - if ( input == "-" || input == "+" ) + if ( input == QLatin1String( "-" ) || input == QLatin1String( "+" ) ) return Intermediate; diff --git a/src/gui/qgsmanageconnectionsdialog.cpp b/src/gui/qgsmanageconnectionsdialog.cpp index 1406ef674fa1..7219b0b837c9 100644 --- a/src/gui/qgsmanageconnectionsdialog.cpp +++ b/src/gui/qgsmanageconnectionsdialog.cpp @@ -99,9 +99,9 @@ void QgsManageConnectionsDialog::doExportImport() } // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } mFileName = fileName; @@ -110,7 +110,7 @@ void QgsManageConnectionsDialog::doExportImport() switch ( mConnectionType ) { case WMS: - doc = saveOWSConnections( items, "WMS" ); + doc = saveOWSConnections( items, QStringLiteral( "WMS" ) ); break; case WFS: doc = saveWfsConnections( items ); @@ -122,7 +122,7 @@ void QgsManageConnectionsDialog::doExportImport() doc = saveMssqlConnections( items ); break; case WCS: - doc = saveOWSConnections( items, "WCS" ); + doc = saveOWSConnections( items, QStringLiteral( "WCS" ) ); break; case Oracle: doc = saveOracleConnections( items ); @@ -175,7 +175,7 @@ void QgsManageConnectionsDialog::doExportImport() switch ( mConnectionType ) { case WMS: - loadOWSConnections( doc, items, "WMS" ); + loadOWSConnections( doc, items, QStringLiteral( "WMS" ) ); break; case WFS: loadWfsConnections( doc, items ); @@ -187,7 +187,7 @@ void QgsManageConnectionsDialog::doExportImport() loadMssqlConnections( doc, items ); break; case WCS: - loadOWSConnections( doc, items, "WCS" ); + loadOWSConnections( doc, items, QStringLiteral( "WCS" ) ); break; case Oracle: loadOracleConnections( doc, items ); @@ -201,7 +201,7 @@ void QgsManageConnectionsDialog::doExportImport() accept(); } - mFileName = ""; + mFileName = QLatin1String( "" ); } bool QgsManageConnectionsDialog::populateConnections() @@ -213,25 +213,25 @@ bool QgsManageConnectionsDialog::populateConnections() switch ( mConnectionType ) { case WMS: - settings.beginGroup( "/Qgis/connections-wms" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wms" ) ); break; case WFS: - settings.beginGroup( "/Qgis/connections-wfs" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wfs" ) ); break; case WCS: - settings.beginGroup( "/Qgis/connections-wcs" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wcs" ) ); break; case PostGIS: - settings.beginGroup( "/PostgreSQL/connections" ); + settings.beginGroup( QStringLiteral( "/PostgreSQL/connections" ) ); break; case MSSQL: - settings.beginGroup( "/MSSQL/connections" ); + settings.beginGroup( QStringLiteral( "/MSSQL/connections" ) ); break; case Oracle: - settings.beginGroup( "/Oracle/connections" ); + settings.beginGroup( QStringLiteral( "/Oracle/connections" ) ); break; case DB2: - settings.beginGroup( "/DB2/connections" ); + settings.beginGroup( QStringLiteral( "/DB2/connections" ) ); break; } QStringList keys = settings.childGroups(); @@ -277,7 +277,7 @@ bool QgsManageConnectionsDialog::populateConnections() switch ( mConnectionType ) { case WMS: - if ( root.tagName() != "qgsWMSConnections" ) + if ( root.tagName() != QLatin1String( "qgsWMSConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an WMS connections exchange file." ) ); @@ -286,7 +286,7 @@ bool QgsManageConnectionsDialog::populateConnections() break; case WFS: - if ( root.tagName() != "qgsWFSConnections" ) + if ( root.tagName() != QLatin1String( "qgsWFSConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an WFS connections exchange file." ) ); @@ -295,7 +295,7 @@ bool QgsManageConnectionsDialog::populateConnections() break; case WCS: - if ( root.tagName() != "qgsWCSConnections" ) + if ( root.tagName() != QLatin1String( "qgsWCSConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an WCS connections exchange file." ) ); @@ -304,7 +304,7 @@ bool QgsManageConnectionsDialog::populateConnections() break; case PostGIS: - if ( root.tagName() != "qgsPgConnections" ) + if ( root.tagName() != QLatin1String( "qgsPgConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an PostGIS connections exchange file." ) ); @@ -313,7 +313,7 @@ bool QgsManageConnectionsDialog::populateConnections() break; case MSSQL: - if ( root.tagName() != "qgsMssqlConnections" ) + if ( root.tagName() != QLatin1String( "qgsMssqlConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an MSSQL connections exchange file." ) ); @@ -321,7 +321,7 @@ bool QgsManageConnectionsDialog::populateConnections() } break; case Oracle: - if ( root.tagName() != "qgsOracleConnections" ) + if ( root.tagName() != QLatin1String( "qgsOracleConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an Oracle connections exchange file." ) ); @@ -329,7 +329,7 @@ bool QgsManageConnectionsDialog::populateConnections() } break; case DB2: - if ( root.tagName() != "qgsDb2Connections" ) + if ( root.tagName() != QLatin1String( "qgsDb2Connections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an DB2 connections exchange file." ) ); @@ -342,7 +342,7 @@ bool QgsManageConnectionsDialog::populateConnections() while ( !child.isNull() ) { QListWidgetItem *item = new QListWidgetItem(); - item->setText( child.attribute( "name" ) ); + item->setText( child.attribute( QStringLiteral( "name" ) ) ); listConnections->addItem( item ); child = child.nextSiblingElement(); } @@ -352,9 +352,9 @@ bool QgsManageConnectionsDialog::populateConnections() QDomDocument QgsManageConnectionsDialog::saveOWSConnections( const QStringList &connections, const QString & service ) { - QDomDocument doc( "connections" ); + QDomDocument doc( QStringLiteral( "connections" ) ); QDomElement root = doc.createElement( "qgs" + service.toUpper() + "Connections" ); - root.setAttribute( "version", "1.0" ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); QSettings settings; @@ -363,23 +363,23 @@ QDomDocument QgsManageConnectionsDialog::saveOWSConnections( const QStringList & { path = "/Qgis/connections-" + service.toLower() + '/'; QDomElement el = doc.createElement( service.toLower() ); - el.setAttribute( "name", connections[ i ] ); - el.setAttribute( "url", settings.value( path + connections[ i ] + "/url", "" ).toString() ); + el.setAttribute( QStringLiteral( "name" ), connections[ i ] ); + el.setAttribute( QStringLiteral( "url" ), settings.value( path + connections[ i ] + "/url", "" ).toString() ); - if ( service == "WMS" ) + if ( service == QLatin1String( "WMS" ) ) { - el.setAttribute( "ignoreGetMapURI", settings.value( path + connections[i] + "/ignoreGetMapURI", false ).toBool() ? "true" : "false" ); - el.setAttribute( "ignoreGetFeatureInfoURI", settings.value( path + connections[i] + "/ignoreGetFeatureInfoURI", false ).toBool() ? "true" : "false" ); - el.setAttribute( "ignoreAxisOrientation", settings.value( path + connections[i] + "/ignoreAxisOrientation", false ).toBool() ? "true" : "false" ); - el.setAttribute( "invertAxisOrientation", settings.value( path + connections[i] + "/invertAxisOrientation", false ).toBool() ? "true" : "false" ); - el.setAttribute( "referer", settings.value( path + connections[ i ] + "/referer", "" ).toString() ); - el.setAttribute( "smoothPixmapTransform", settings.value( path + connections[i] + "/smoothPixmapTransform", false ).toBool() ? "true" : "false" ); - el.setAttribute( "dpiMode", settings.value( path + connections[i] + "/dpiMode", "7" ).toInt() ); + el.setAttribute( QStringLiteral( "ignoreGetMapURI" ), settings.value( path + connections[i] + "/ignoreGetMapURI", false ).toBool() ? "true" : "false" ); + el.setAttribute( QStringLiteral( "ignoreGetFeatureInfoURI" ), settings.value( path + connections[i] + "/ignoreGetFeatureInfoURI", false ).toBool() ? "true" : "false" ); + el.setAttribute( QStringLiteral( "ignoreAxisOrientation" ), settings.value( path + connections[i] + "/ignoreAxisOrientation", false ).toBool() ? "true" : "false" ); + el.setAttribute( QStringLiteral( "invertAxisOrientation" ), settings.value( path + connections[i] + "/invertAxisOrientation", false ).toBool() ? "true" : "false" ); + el.setAttribute( QStringLiteral( "referer" ), settings.value( path + connections[ i ] + "/referer", "" ).toString() ); + el.setAttribute( QStringLiteral( "smoothPixmapTransform" ), settings.value( path + connections[i] + "/smoothPixmapTransform", false ).toBool() ? "true" : "false" ); + el.setAttribute( QStringLiteral( "dpiMode" ), settings.value( path + connections[i] + "/dpiMode", "7" ).toInt() ); } path = "/Qgis/" + service.toUpper() + '/'; - el.setAttribute( "username", settings.value( path + connections[ i ] + "/username", "" ).toString() ); - el.setAttribute( "password", settings.value( path + connections[ i ] + "/password", "" ).toString() ); + el.setAttribute( QStringLiteral( "username" ), settings.value( path + connections[ i ] + "/username", "" ).toString() ); + el.setAttribute( QStringLiteral( "password" ), settings.value( path + connections[ i ] + "/password", "" ).toString() ); root.appendChild( el ); } @@ -388,25 +388,25 @@ QDomDocument QgsManageConnectionsDialog::saveOWSConnections( const QStringList & QDomDocument QgsManageConnectionsDialog::saveWfsConnections( const QStringList &connections ) { - QDomDocument doc( "connections" ); - QDomElement root = doc.createElement( "qgsWFSConnections" ); - root.setAttribute( "version", "1.0" ); + QDomDocument doc( QStringLiteral( "connections" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgsWFSConnections" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); QSettings settings; QString path; for ( int i = 0; i < connections.count(); ++i ) { - path = "/Qgis/connections-wfs/"; - QDomElement el = doc.createElement( "wfs" ); - el.setAttribute( "name", connections[ i ] ); - el.setAttribute( "url", settings.value( path + connections[ i ] + "/url", "" ).toString() ); + path = QStringLiteral( "/Qgis/connections-wfs/" ); + QDomElement el = doc.createElement( QStringLiteral( "wfs" ) ); + el.setAttribute( QStringLiteral( "name" ), connections[ i ] ); + el.setAttribute( QStringLiteral( "url" ), settings.value( path + connections[ i ] + "/url", "" ).toString() ); - el.setAttribute( "referer", settings.value( path + connections[ i ] + "/referer", "" ).toString() ); + el.setAttribute( QStringLiteral( "referer" ), settings.value( path + connections[ i ] + "/referer", "" ).toString() ); - path = "/Qgis/WFS/"; - el.setAttribute( "username", settings.value( path + connections[ i ] + "/username", "" ).toString() ); - el.setAttribute( "password", settings.value( path + connections[ i ] + "/password", "" ).toString() ); + path = QStringLiteral( "/Qgis/WFS/" ); + el.setAttribute( QStringLiteral( "username" ), settings.value( path + connections[ i ] + "/username", "" ).toString() ); + el.setAttribute( QStringLiteral( "password" ), settings.value( path + connections[ i ] + "/password", "" ).toString() ); root.appendChild( el ); } @@ -415,9 +415,9 @@ QDomDocument QgsManageConnectionsDialog::saveWfsConnections( const QStringList & QDomDocument QgsManageConnectionsDialog::savePgConnections( const QStringList &connections ) { - QDomDocument doc( "connections" ); - QDomElement root = doc.createElement( "qgsPgConnections" ); - root.setAttribute( "version", "1.0" ); + QDomDocument doc( QStringLiteral( "connections" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgsPgConnections" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); QSettings settings; @@ -425,27 +425,27 @@ QDomDocument QgsManageConnectionsDialog::savePgConnections( const QStringList &c for ( int i = 0; i < connections.count(); ++i ) { path = "/PostgreSQL/connections/" + connections[ i ]; - QDomElement el = doc.createElement( "postgis" ); - el.setAttribute( "name", connections[ i ] ); - el.setAttribute( "host", settings.value( path + "/host", "" ).toString() ); - el.setAttribute( "port", settings.value( path + "/port", "" ).toString() ); - el.setAttribute( "database", settings.value( path + "/database", "" ).toString() ); - el.setAttribute( "service", settings.value( path + "/service", "" ).toString() ); - el.setAttribute( "sslmode", settings.value( path + "/sslmode", "1" ).toString() ); - el.setAttribute( "estimatedMetadata", settings.value( path + "/estimatedMetadata", "0" ).toString() ); - - el.setAttribute( "saveUsername", settings.value( path + "/saveUsername", "false" ).toString() ); - - if ( settings.value( path + "/saveUsername", "false" ).toString() == "true" ) + QDomElement el = doc.createElement( QStringLiteral( "postgis" ) ); + el.setAttribute( QStringLiteral( "name" ), connections[ i ] ); + el.setAttribute( QStringLiteral( "host" ), settings.value( path + "/host", "" ).toString() ); + el.setAttribute( QStringLiteral( "port" ), settings.value( path + "/port", "" ).toString() ); + el.setAttribute( QStringLiteral( "database" ), settings.value( path + "/database", "" ).toString() ); + el.setAttribute( QStringLiteral( "service" ), settings.value( path + "/service", "" ).toString() ); + el.setAttribute( QStringLiteral( "sslmode" ), settings.value( path + "/sslmode", "1" ).toString() ); + el.setAttribute( QStringLiteral( "estimatedMetadata" ), settings.value( path + "/estimatedMetadata", "0" ).toString() ); + + el.setAttribute( QStringLiteral( "saveUsername" ), settings.value( path + "/saveUsername", "false" ).toString() ); + + if ( settings.value( path + "/saveUsername", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "username", settings.value( path + "/username", "" ).toString() ); + el.setAttribute( QStringLiteral( "username" ), settings.value( path + "/username", "" ).toString() ); } - el.setAttribute( "savePassword", settings.value( path + "/savePassword", "false" ).toString() ); + el.setAttribute( QStringLiteral( "savePassword" ), settings.value( path + "/savePassword", "false" ).toString() ); - if ( settings.value( path + "/savePassword", "false" ).toString() == "true" ) + if ( settings.value( path + "/savePassword", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "password", settings.value( path + "/password", "" ).toString() ); + el.setAttribute( QStringLiteral( "password" ), settings.value( path + "/password", "" ).toString() ); } root.appendChild( el ); @@ -456,9 +456,9 @@ QDomDocument QgsManageConnectionsDialog::savePgConnections( const QStringList &c QDomDocument QgsManageConnectionsDialog::saveMssqlConnections( const QStringList &connections ) { - QDomDocument doc( "connections" ); - QDomElement root = doc.createElement( "qgsMssqlConnections" ); - root.setAttribute( "version", "1.0" ); + QDomDocument doc( QStringLiteral( "connections" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgsMssqlConnections" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); QSettings settings; @@ -466,27 +466,27 @@ QDomDocument QgsManageConnectionsDialog::saveMssqlConnections( const QStringList for ( int i = 0; i < connections.count(); ++i ) { path = "/MSSQL/connections/" + connections[ i ]; - QDomElement el = doc.createElement( "mssql" ); - el.setAttribute( "name", connections[ i ] ); - el.setAttribute( "host", settings.value( path + "/host", "" ).toString() ); - el.setAttribute( "port", settings.value( path + "/port", "" ).toString() ); - el.setAttribute( "database", settings.value( path + "/database", "" ).toString() ); - el.setAttribute( "service", settings.value( path + "/service", "" ).toString() ); - el.setAttribute( "sslmode", settings.value( path + "/sslmode", "1" ).toString() ); - el.setAttribute( "estimatedMetadata", settings.value( path + "/estimatedMetadata", "0" ).toString() ); - - el.setAttribute( "saveUsername", settings.value( path + "/saveUsername", "false" ).toString() ); - - if ( settings.value( path + "/saveUsername", "false" ).toString() == "true" ) + QDomElement el = doc.createElement( QStringLiteral( "mssql" ) ); + el.setAttribute( QStringLiteral( "name" ), connections[ i ] ); + el.setAttribute( QStringLiteral( "host" ), settings.value( path + "/host", "" ).toString() ); + el.setAttribute( QStringLiteral( "port" ), settings.value( path + "/port", "" ).toString() ); + el.setAttribute( QStringLiteral( "database" ), settings.value( path + "/database", "" ).toString() ); + el.setAttribute( QStringLiteral( "service" ), settings.value( path + "/service", "" ).toString() ); + el.setAttribute( QStringLiteral( "sslmode" ), settings.value( path + "/sslmode", "1" ).toString() ); + el.setAttribute( QStringLiteral( "estimatedMetadata" ), settings.value( path + "/estimatedMetadata", "0" ).toString() ); + + el.setAttribute( QStringLiteral( "saveUsername" ), settings.value( path + "/saveUsername", "false" ).toString() ); + + if ( settings.value( path + "/saveUsername", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "username", settings.value( path + "/username", "" ).toString() ); + el.setAttribute( QStringLiteral( "username" ), settings.value( path + "/username", "" ).toString() ); } - el.setAttribute( "savePassword", settings.value( path + "/savePassword", "false" ).toString() ); + el.setAttribute( QStringLiteral( "savePassword" ), settings.value( path + "/savePassword", "false" ).toString() ); - if ( settings.value( path + "/savePassword", "false" ).toString() == "true" ) + if ( settings.value( path + "/savePassword", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "password", settings.value( path + "/password", "" ).toString() ); + el.setAttribute( QStringLiteral( "password" ), settings.value( path + "/password", "" ).toString() ); } root.appendChild( el ); @@ -497,9 +497,9 @@ QDomDocument QgsManageConnectionsDialog::saveMssqlConnections( const QStringList QDomDocument QgsManageConnectionsDialog::saveOracleConnections( const QStringList &connections ) { - QDomDocument doc( "connections" ); - QDomElement root = doc.createElement( "qgsOracleConnections" ); - root.setAttribute( "version", "1.0" ); + QDomDocument doc( QStringLiteral( "connections" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgsOracleConnections" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); QSettings settings; @@ -507,30 +507,30 @@ QDomDocument QgsManageConnectionsDialog::saveOracleConnections( const QStringLis for ( int i = 0; i < connections.count(); ++i ) { path = "/Oracle/connections/" + connections[ i ]; - QDomElement el = doc.createElement( "oracle" ); - el.setAttribute( "name", connections[ i ] ); - el.setAttribute( "host", settings.value( path + "/host", "" ).toString() ); - el.setAttribute( "port", settings.value( path + "/port", "" ).toString() ); - el.setAttribute( "database", settings.value( path + "/database", "" ).toString() ); - el.setAttribute( "dboptions", settings.value( path + "/dboptions", "" ).toString() ); - el.setAttribute( "dbworkspace", settings.value( path + "/dbworkspace", "" ).toString() ); - el.setAttribute( "estimatedMetadata", settings.value( path + "/estimatedMetadata", "0" ).toString() ); - el.setAttribute( "userTablesOnly", settings.value( path + "/userTablesOnly", "0" ).toString() ); - el.setAttribute( "geometryColumnsOnly", settings.value( path + "/geometryColumnsOnly", "0" ).toString() ); - el.setAttribute( "allowGeometrylessTables", settings.value( path + "/allowGeometrylessTables", "0" ).toString() ); - - el.setAttribute( "saveUsername", settings.value( path + "/saveUsername", "false" ).toString() ); - - if ( settings.value( path + "/saveUsername", "false" ).toString() == "true" ) + QDomElement el = doc.createElement( QStringLiteral( "oracle" ) ); + el.setAttribute( QStringLiteral( "name" ), connections[ i ] ); + el.setAttribute( QStringLiteral( "host" ), settings.value( path + "/host", "" ).toString() ); + el.setAttribute( QStringLiteral( "port" ), settings.value( path + "/port", "" ).toString() ); + el.setAttribute( QStringLiteral( "database" ), settings.value( path + "/database", "" ).toString() ); + el.setAttribute( QStringLiteral( "dboptions" ), settings.value( path + "/dboptions", "" ).toString() ); + el.setAttribute( QStringLiteral( "dbworkspace" ), settings.value( path + "/dbworkspace", "" ).toString() ); + el.setAttribute( QStringLiteral( "estimatedMetadata" ), settings.value( path + "/estimatedMetadata", "0" ).toString() ); + el.setAttribute( QStringLiteral( "userTablesOnly" ), settings.value( path + "/userTablesOnly", "0" ).toString() ); + el.setAttribute( QStringLiteral( "geometryColumnsOnly" ), settings.value( path + "/geometryColumnsOnly", "0" ).toString() ); + el.setAttribute( QStringLiteral( "allowGeometrylessTables" ), settings.value( path + "/allowGeometrylessTables", "0" ).toString() ); + + el.setAttribute( QStringLiteral( "saveUsername" ), settings.value( path + "/saveUsername", "false" ).toString() ); + + if ( settings.value( path + "/saveUsername", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "username", settings.value( path + "/username", "" ).toString() ); + el.setAttribute( QStringLiteral( "username" ), settings.value( path + "/username", "" ).toString() ); } - el.setAttribute( "savePassword", settings.value( path + "/savePassword", "false" ).toString() ); + el.setAttribute( QStringLiteral( "savePassword" ), settings.value( path + "/savePassword", "false" ).toString() ); - if ( settings.value( path + "/savePassword", "false" ).toString() == "true" ) + if ( settings.value( path + "/savePassword", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "password", settings.value( path + "/password", "" ).toString() ); + el.setAttribute( QStringLiteral( "password" ), settings.value( path + "/password", "" ).toString() ); } root.appendChild( el ); @@ -541,9 +541,9 @@ QDomDocument QgsManageConnectionsDialog::saveOracleConnections( const QStringLis QDomDocument QgsManageConnectionsDialog::saveDb2Connections( const QStringList &connections ) { - QDomDocument doc( "connections" ); - QDomElement root = doc.createElement( "qgsDb2Connections" ); - root.setAttribute( "version", "1.0" ); + QDomDocument doc( QStringLiteral( "connections" ) ); + QDomElement root = doc.createElement( QStringLiteral( "qgsDb2Connections" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( root ); QSettings settings; @@ -551,27 +551,27 @@ QDomDocument QgsManageConnectionsDialog::saveDb2Connections( const QStringList & for ( int i = 0; i < connections.count(); ++i ) { path = "/DB2/connections/" + connections[ i ]; - QDomElement el = doc.createElement( "db2" ); - el.setAttribute( "name", connections[ i ] ); - el.setAttribute( "host", settings.value( path + "/host", "" ).toString() ); - el.setAttribute( "port", settings.value( path + "/port", "" ).toString() ); - el.setAttribute( "database", settings.value( path + "/database", "" ).toString() ); - el.setAttribute( "service", settings.value( path + "/service", "" ).toString() ); - el.setAttribute( "sslmode", settings.value( path + "/sslmode", "1" ).toString() ); - el.setAttribute( "estimatedMetadata", settings.value( path + "/estimatedMetadata", "0" ).toString() ); - - el.setAttribute( "saveUsername", settings.value( path + "/saveUsername", "false" ).toString() ); - - if ( settings.value( path + "/saveUsername", "false" ).toString() == "true" ) + QDomElement el = doc.createElement( QStringLiteral( "db2" ) ); + el.setAttribute( QStringLiteral( "name" ), connections[ i ] ); + el.setAttribute( QStringLiteral( "host" ), settings.value( path + "/host", "" ).toString() ); + el.setAttribute( QStringLiteral( "port" ), settings.value( path + "/port", "" ).toString() ); + el.setAttribute( QStringLiteral( "database" ), settings.value( path + "/database", "" ).toString() ); + el.setAttribute( QStringLiteral( "service" ), settings.value( path + "/service", "" ).toString() ); + el.setAttribute( QStringLiteral( "sslmode" ), settings.value( path + "/sslmode", "1" ).toString() ); + el.setAttribute( QStringLiteral( "estimatedMetadata" ), settings.value( path + "/estimatedMetadata", "0" ).toString() ); + + el.setAttribute( QStringLiteral( "saveUsername" ), settings.value( path + "/saveUsername", "false" ).toString() ); + + if ( settings.value( path + "/saveUsername", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "username", settings.value( path + "/username", "" ).toString() ); + el.setAttribute( QStringLiteral( "username" ), settings.value( path + "/username", "" ).toString() ); } - el.setAttribute( "savePassword", settings.value( path + "/savePassword", "false" ).toString() ); + el.setAttribute( QStringLiteral( "savePassword" ), settings.value( path + "/savePassword", "false" ).toString() ); - if ( settings.value( path + "/savePassword", "false" ).toString() == "true" ) + if ( settings.value( path + "/savePassword", "false" ).toString() == QLatin1String( "true" ) ) { - el.setAttribute( "password", settings.value( path + "/password", "" ).toString() ); + el.setAttribute( QStringLiteral( "password" ), settings.value( path + "/password", "" ).toString() ); } root.appendChild( el ); @@ -601,7 +601,7 @@ void QgsManageConnectionsDialog::loadOWSConnections( const QDomDocument &doc, co while ( !child.isNull() ) { - connectionName = child.attribute( "name" ); + connectionName = child.attribute( QStringLiteral( "name" ) ); if ( !items.contains( connectionName ) ) { child = child.nextSiblingElement(); @@ -646,21 +646,21 @@ void QgsManageConnectionsDialog::loadOWSConnections( const QDomDocument &doc, co // no dups detected or overwrite is allowed settings.beginGroup( "/Qgis/connections-" + service.toLower() ); - settings.setValue( QString( '/' + connectionName + "/url" ), child.attribute( "url" ) ); - settings.setValue( QString( '/' + connectionName + "/ignoreGetMapURI" ), child.attribute( "ignoreGetMapURI" ) == "true" ); - settings.setValue( QString( '/' + connectionName + "/ignoreGetFeatureInfoURI" ), child.attribute( "ignoreGetFeatureInfoURI" ) == "true" ); - settings.setValue( QString( '/' + connectionName + "/ignoreAxisOrientation" ), child.attribute( "ignoreAxisOrientation" ) == "true" ); - settings.setValue( QString( '/' + connectionName + "/invertAxisOrientation" ), child.attribute( "invertAxisOrientation" ) == "true" ); - settings.setValue( QString( '/' + connectionName + "/referer" ), child.attribute( "referer" ) ); - settings.setValue( QString( '/' + connectionName + "/smoothPixmapTransform" ), child.attribute( "smoothPixmapTransform" ) == "true" ); - settings.setValue( QString( '/' + connectionName + "/dpiMode" ), child.attribute( "dpiMode", "7" ).toInt() ); + settings.setValue( QString( '/' + connectionName + "/url" ), child.attribute( QStringLiteral( "url" ) ) ); + settings.setValue( QString( '/' + connectionName + "/ignoreGetMapURI" ), child.attribute( QStringLiteral( "ignoreGetMapURI" ) ) == QLatin1String( "true" ) ); + settings.setValue( QString( '/' + connectionName + "/ignoreGetFeatureInfoURI" ), child.attribute( QStringLiteral( "ignoreGetFeatureInfoURI" ) ) == QLatin1String( "true" ) ); + settings.setValue( QString( '/' + connectionName + "/ignoreAxisOrientation" ), child.attribute( QStringLiteral( "ignoreAxisOrientation" ) ) == QLatin1String( "true" ) ); + settings.setValue( QString( '/' + connectionName + "/invertAxisOrientation" ), child.attribute( QStringLiteral( "invertAxisOrientation" ) ) == QLatin1String( "true" ) ); + settings.setValue( QString( '/' + connectionName + "/referer" ), child.attribute( QStringLiteral( "referer" ) ) ); + settings.setValue( QString( '/' + connectionName + "/smoothPixmapTransform" ), child.attribute( QStringLiteral( "smoothPixmapTransform" ) ) == QLatin1String( "true" ) ); + settings.setValue( QString( '/' + connectionName + "/dpiMode" ), child.attribute( QStringLiteral( "dpiMode" ), QStringLiteral( "7" ) ).toInt() ); settings.endGroup(); - if ( !child.attribute( "username" ).isEmpty() ) + if ( !child.attribute( QStringLiteral( "username" ) ).isEmpty() ) { settings.beginGroup( "/Qgis/" + service.toUpper() + '/' + connectionName ); - settings.setValue( "/username", child.attribute( "username" ) ); - settings.setValue( "/password", child.attribute( "password" ) ); + settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) ); + settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) ); settings.endGroup(); } child = child.nextSiblingElement(); @@ -670,7 +670,7 @@ void QgsManageConnectionsDialog::loadOWSConnections( const QDomDocument &doc, co void QgsManageConnectionsDialog::loadWfsConnections( const QDomDocument &doc, const QStringList &items ) { QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsWFSConnections" ) + if ( root.tagName() != QLatin1String( "qgsWFSConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), tr( "The file is not an WFS connections exchange file." ) ); @@ -679,7 +679,7 @@ void QgsManageConnectionsDialog::loadWfsConnections( const QDomDocument &doc, co QString connectionName; QSettings settings; - settings.beginGroup( "/Qgis/connections-wfs" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wfs" ) ); QStringList keys = settings.childGroups(); settings.endGroup(); QDomElement child = root.firstChildElement(); @@ -688,7 +688,7 @@ void QgsManageConnectionsDialog::loadWfsConnections( const QDomDocument &doc, co while ( !child.isNull() ) { - connectionName = child.attribute( "name" ); + connectionName = child.attribute( QStringLiteral( "name" ) ); if ( !items.contains( connectionName ) ) { child = child.nextSiblingElement(); @@ -732,15 +732,15 @@ void QgsManageConnectionsDialog::loadWfsConnections( const QDomDocument &doc, co } // no dups detected or overwrite is allowed - settings.beginGroup( "/Qgis/connections-wfs" ); - settings.setValue( QString( '/' + connectionName + "/url" ), child.attribute( "url" ) ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wfs" ) ); + settings.setValue( QString( '/' + connectionName + "/url" ), child.attribute( QStringLiteral( "url" ) ) ); settings.endGroup(); - if ( !child.attribute( "username" ).isEmpty() ) + if ( !child.attribute( QStringLiteral( "username" ) ).isEmpty() ) { settings.beginGroup( "/Qgis/WFS/" + connectionName ); - settings.setValue( "/username", child.attribute( "username" ) ); - settings.setValue( "/password", child.attribute( "password" ) ); + settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) ); + settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) ); settings.endGroup(); } child = child.nextSiblingElement(); @@ -751,7 +751,7 @@ void QgsManageConnectionsDialog::loadWfsConnections( const QDomDocument &doc, co void QgsManageConnectionsDialog::loadPgConnections( const QDomDocument &doc, const QStringList &items ) { QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsPgConnections" ) + if ( root.tagName() != QLatin1String( "qgsPgConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), @@ -761,7 +761,7 @@ void QgsManageConnectionsDialog::loadPgConnections( const QDomDocument &doc, con QString connectionName; QSettings settings; - settings.beginGroup( "/PostgreSQL/connections" ); + settings.beginGroup( QStringLiteral( "/PostgreSQL/connections" ) ); QStringList keys = settings.childGroups(); settings.endGroup(); QDomElement child = root.firstChildElement(); @@ -770,7 +770,7 @@ void QgsManageConnectionsDialog::loadPgConnections( const QDomDocument &doc, con while ( !child.isNull() ) { - connectionName = child.attribute( "name" ); + connectionName = child.attribute( QStringLiteral( "name" ) ); if ( !items.contains( connectionName ) ) { child = child.nextSiblingElement(); @@ -815,23 +815,23 @@ void QgsManageConnectionsDialog::loadPgConnections( const QDomDocument &doc, con //no dups detected or overwrite is allowed settings.beginGroup( "/PostgreSQL/connections/" + connectionName ); - settings.setValue( "/host", child.attribute( "host" ) ); - settings.setValue( "/port", child.attribute( "port" ) ); - settings.setValue( "/database", child.attribute( "database" ) ); - if ( child.hasAttribute( "service" ) ) + settings.setValue( QStringLiteral( "/host" ), child.attribute( QStringLiteral( "host" ) ) ); + settings.setValue( QStringLiteral( "/port" ), child.attribute( QStringLiteral( "port" ) ) ); + settings.setValue( QStringLiteral( "/database" ), child.attribute( QStringLiteral( "database" ) ) ); + if ( child.hasAttribute( QStringLiteral( "service" ) ) ) { - settings.setValue( "/service", child.attribute( "service" ) ); + settings.setValue( QStringLiteral( "/service" ), child.attribute( QStringLiteral( "service" ) ) ); } else { - settings.setValue( "/service", "" ); + settings.setValue( QStringLiteral( "/service" ), "" ); } - settings.setValue( "/sslmode", child.attribute( "sslmode" ) ); - settings.setValue( "/estimatedMetadata", child.attribute( "estimatedMetadata" ) ); - settings.setValue( "/saveUsername", child.attribute( "saveUsername" ) ); - settings.setValue( "/username", child.attribute( "username" ) ); - settings.setValue( "/savePassword", child.attribute( "savePassword" ) ); - settings.setValue( "/password", child.attribute( "password" ) ); + settings.setValue( QStringLiteral( "/sslmode" ), child.attribute( QStringLiteral( "sslmode" ) ) ); + settings.setValue( QStringLiteral( "/estimatedMetadata" ), child.attribute( QStringLiteral( "estimatedMetadata" ) ) ); + settings.setValue( QStringLiteral( "/saveUsername" ), child.attribute( QStringLiteral( "saveUsername" ) ) ); + settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) ); + settings.setValue( QStringLiteral( "/savePassword" ), child.attribute( QStringLiteral( "savePassword" ) ) ); + settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) ); settings.endGroup(); child = child.nextSiblingElement(); @@ -841,7 +841,7 @@ void QgsManageConnectionsDialog::loadPgConnections( const QDomDocument &doc, con void QgsManageConnectionsDialog::loadMssqlConnections( const QDomDocument &doc, const QStringList &items ) { QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsMssqlConnections" ) + if ( root.tagName() != QLatin1String( "qgsMssqlConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), @@ -851,7 +851,7 @@ void QgsManageConnectionsDialog::loadMssqlConnections( const QDomDocument &doc, QString connectionName; QSettings settings; - settings.beginGroup( "/MSSQL/connections" ); + settings.beginGroup( QStringLiteral( "/MSSQL/connections" ) ); QStringList keys = settings.childGroups(); settings.endGroup(); QDomElement child = root.firstChildElement(); @@ -860,7 +860,7 @@ void QgsManageConnectionsDialog::loadMssqlConnections( const QDomDocument &doc, while ( !child.isNull() ) { - connectionName = child.attribute( "name" ); + connectionName = child.attribute( QStringLiteral( "name" ) ); if ( !items.contains( connectionName ) ) { child = child.nextSiblingElement(); @@ -905,23 +905,23 @@ void QgsManageConnectionsDialog::loadMssqlConnections( const QDomDocument &doc, //no dups detected or overwrite is allowed settings.beginGroup( "/MSSQL/connections/" + connectionName ); - settings.setValue( "/host", child.attribute( "host" ) ); - settings.setValue( "/port", child.attribute( "port" ) ); - settings.setValue( "/database", child.attribute( "database" ) ); - if ( child.hasAttribute( "service" ) ) + settings.setValue( QStringLiteral( "/host" ), child.attribute( QStringLiteral( "host" ) ) ); + settings.setValue( QStringLiteral( "/port" ), child.attribute( QStringLiteral( "port" ) ) ); + settings.setValue( QStringLiteral( "/database" ), child.attribute( QStringLiteral( "database" ) ) ); + if ( child.hasAttribute( QStringLiteral( "service" ) ) ) { - settings.setValue( "/service", child.attribute( "service" ) ); + settings.setValue( QStringLiteral( "/service" ), child.attribute( QStringLiteral( "service" ) ) ); } else { - settings.setValue( "/service", "" ); + settings.setValue( QStringLiteral( "/service" ), "" ); } - settings.setValue( "/sslmode", child.attribute( "sslmode" ) ); - settings.setValue( "/estimatedMetadata", child.attribute( "estimatedMetadata" ) ); - settings.setValue( "/saveUsername", child.attribute( "saveUsername" ) ); - settings.setValue( "/username", child.attribute( "username" ) ); - settings.setValue( "/savePassword", child.attribute( "savePassword" ) ); - settings.setValue( "/password", child.attribute( "password" ) ); + settings.setValue( QStringLiteral( "/sslmode" ), child.attribute( QStringLiteral( "sslmode" ) ) ); + settings.setValue( QStringLiteral( "/estimatedMetadata" ), child.attribute( QStringLiteral( "estimatedMetadata" ) ) ); + settings.setValue( QStringLiteral( "/saveUsername" ), child.attribute( QStringLiteral( "saveUsername" ) ) ); + settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) ); + settings.setValue( QStringLiteral( "/savePassword" ), child.attribute( QStringLiteral( "savePassword" ) ) ); + settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) ); settings.endGroup(); child = child.nextSiblingElement(); @@ -931,7 +931,7 @@ void QgsManageConnectionsDialog::loadMssqlConnections( const QDomDocument &doc, void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, const QStringList &items ) { QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsOracleConnections" ) + if ( root.tagName() != QLatin1String( "qgsOracleConnections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), @@ -941,7 +941,7 @@ void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, QString connectionName; QSettings settings; - settings.beginGroup( "/Oracle/connections" ); + settings.beginGroup( QStringLiteral( "/Oracle/connections" ) ); QStringList keys = settings.childGroups(); settings.endGroup(); QDomElement child = root.firstChildElement(); @@ -950,7 +950,7 @@ void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, while ( !child.isNull() ) { - connectionName = child.attribute( "name" ); + connectionName = child.attribute( QStringLiteral( "name" ) ); if ( !items.contains( connectionName ) ) { child = child.nextSiblingElement(); @@ -995,19 +995,19 @@ void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, //no dups detected or overwrite is allowed settings.beginGroup( "/Oracle/connections/" + connectionName ); - settings.setValue( "/host", child.attribute( "host" ) ); - settings.setValue( "/port", child.attribute( "port" ) ); - settings.setValue( "/database", child.attribute( "database" ) ); - settings.setValue( "/dboptions", child.attribute( "dboptions" ) ); - settings.setValue( "/dbworkspace", child.attribute( "dbworkspace" ) ); - settings.setValue( "/estimatedMetadata", child.attribute( "estimatedMetadata" ) ); - settings.setValue( "/userTablesOnly", child.attribute( "userTablesOnly" ) ); - settings.setValue( "/geometryColumnsOnly", child.attribute( "geometryColumnsOnly" ) ); - settings.setValue( "/allowGeometrylessTables", child.attribute( "allowGeometrylessTables" ) ); - settings.setValue( "/saveUsername", child.attribute( "saveUsername" ) ); - settings.setValue( "/username", child.attribute( "username" ) ); - settings.setValue( "/savePassword", child.attribute( "savePassword" ) ); - settings.setValue( "/password", child.attribute( "password" ) ); + settings.setValue( QStringLiteral( "/host" ), child.attribute( QStringLiteral( "host" ) ) ); + settings.setValue( QStringLiteral( "/port" ), child.attribute( QStringLiteral( "port" ) ) ); + settings.setValue( QStringLiteral( "/database" ), child.attribute( QStringLiteral( "database" ) ) ); + settings.setValue( QStringLiteral( "/dboptions" ), child.attribute( QStringLiteral( "dboptions" ) ) ); + settings.setValue( QStringLiteral( "/dbworkspace" ), child.attribute( QStringLiteral( "dbworkspace" ) ) ); + settings.setValue( QStringLiteral( "/estimatedMetadata" ), child.attribute( QStringLiteral( "estimatedMetadata" ) ) ); + settings.setValue( QStringLiteral( "/userTablesOnly" ), child.attribute( QStringLiteral( "userTablesOnly" ) ) ); + settings.setValue( QStringLiteral( "/geometryColumnsOnly" ), child.attribute( QStringLiteral( "geometryColumnsOnly" ) ) ); + settings.setValue( QStringLiteral( "/allowGeometrylessTables" ), child.attribute( QStringLiteral( "allowGeometrylessTables" ) ) ); + settings.setValue( QStringLiteral( "/saveUsername" ), child.attribute( QStringLiteral( "saveUsername" ) ) ); + settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) ); + settings.setValue( QStringLiteral( "/savePassword" ), child.attribute( QStringLiteral( "savePassword" ) ) ); + settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) ); settings.endGroup(); child = child.nextSiblingElement(); @@ -1017,7 +1017,7 @@ void QgsManageConnectionsDialog::loadOracleConnections( const QDomDocument &doc, void QgsManageConnectionsDialog::loadDb2Connections( const QDomDocument &doc, const QStringList &items ) { QDomElement root = doc.documentElement(); - if ( root.tagName() != "qgsDb2Connections" ) + if ( root.tagName() != QLatin1String( "qgsDb2Connections" ) ) { QMessageBox::information( this, tr( "Loading connections" ), @@ -1027,7 +1027,7 @@ void QgsManageConnectionsDialog::loadDb2Connections( const QDomDocument &doc, co QString connectionName; QSettings settings; - settings.beginGroup( "/DB2/connections" ); + settings.beginGroup( QStringLiteral( "/DB2/connections" ) ); QStringList keys = settings.childGroups(); settings.endGroup(); QDomElement child = root.firstChildElement(); @@ -1036,7 +1036,7 @@ void QgsManageConnectionsDialog::loadDb2Connections( const QDomDocument &doc, co while ( !child.isNull() ) { - connectionName = child.attribute( "name" ); + connectionName = child.attribute( QStringLiteral( "name" ) ); if ( !items.contains( connectionName ) ) { child = child.nextSiblingElement(); @@ -1081,23 +1081,23 @@ void QgsManageConnectionsDialog::loadDb2Connections( const QDomDocument &doc, co //no dups detected or overwrite is allowed settings.beginGroup( "/DB2/connections/" + connectionName ); - settings.setValue( "/host", child.attribute( "host" ) ); - settings.setValue( "/port", child.attribute( "port" ) ); - settings.setValue( "/database", child.attribute( "database" ) ); - if ( child.hasAttribute( "service" ) ) + settings.setValue( QStringLiteral( "/host" ), child.attribute( QStringLiteral( "host" ) ) ); + settings.setValue( QStringLiteral( "/port" ), child.attribute( QStringLiteral( "port" ) ) ); + settings.setValue( QStringLiteral( "/database" ), child.attribute( QStringLiteral( "database" ) ) ); + if ( child.hasAttribute( QStringLiteral( "service" ) ) ) { - settings.setValue( "/service", child.attribute( "service" ) ); + settings.setValue( QStringLiteral( "/service" ), child.attribute( QStringLiteral( "service" ) ) ); } else { - settings.setValue( "/service", "" ); + settings.setValue( QStringLiteral( "/service" ), "" ); } - settings.setValue( "/sslmode", child.attribute( "sslmode" ) ); - settings.setValue( "/estimatedMetadata", child.attribute( "estimatedMetadata" ) ); - settings.setValue( "/saveUsername", child.attribute( "saveUsername" ) ); - settings.setValue( "/username", child.attribute( "username" ) ); - settings.setValue( "/savePassword", child.attribute( "savePassword" ) ); - settings.setValue( "/password", child.attribute( "password" ) ); + settings.setValue( QStringLiteral( "/sslmode" ), child.attribute( QStringLiteral( "sslmode" ) ) ); + settings.setValue( QStringLiteral( "/estimatedMetadata" ), child.attribute( QStringLiteral( "estimatedMetadata" ) ) ); + settings.setValue( QStringLiteral( "/saveUsername" ), child.attribute( QStringLiteral( "saveUsername" ) ) ); + settings.setValue( QStringLiteral( "/username" ), child.attribute( QStringLiteral( "username" ) ) ); + settings.setValue( QStringLiteral( "/savePassword" ), child.attribute( QStringLiteral( "savePassword" ) ) ); + settings.setValue( QStringLiteral( "/password" ), child.attribute( QStringLiteral( "password" ) ) ); settings.endGroup(); child = child.nextSiblingElement(); diff --git a/src/gui/qgsmanageconnectionsdialog.h b/src/gui/qgsmanageconnectionsdialog.h index 9f5bb4471145..c533d3c33e7f 100644 --- a/src/gui/qgsmanageconnectionsdialog.h +++ b/src/gui/qgsmanageconnectionsdialog.h @@ -47,10 +47,11 @@ class GUI_EXPORT QgsManageConnectionsDialog : public QDialog, private Ui::QgsMan Oracle, }; - // constructor - // mode argument must be 0 for export and 1 for import - // type argument must be 0 for WMS and 1 for PostGIS - QgsManageConnectionsDialog( QWidget *parent = nullptr, Mode mode = Export, Type type = WMS, const QString& fileName = "" ); + /** + * Constructor for QgsManageConnectionsDialog. The mode argument must be 0 for export and 1 for import. + * The type argument must be 0 for WMS and 1 for PostGIS. + */ + QgsManageConnectionsDialog( QWidget *parent = nullptr, Mode mode = Export, Type type = WMS, const QString& fileName = QStringLiteral( "" ) ); public slots: void doExportImport(); diff --git a/src/gui/qgsmapcanvas.cpp b/src/gui/qgsmapcanvas.cpp index 9c1a700254c4..ef3d67b7f42d 100644 --- a/src/gui/qgsmapcanvas.cpp +++ b/src/gui/qgsmapcanvas.cpp @@ -147,12 +147,12 @@ QgsMapCanvas::QgsMapCanvas( QWidget * parent ) //segmentation parameters QSettings settings; - double segmentationTolerance = settings.value( "/qgis/segmentationTolerance", "0.01745" ).toDouble(); - QgsAbstractGeometry::SegmentationToleranceType toleranceType = QgsAbstractGeometry::SegmentationToleranceType( settings.value( "/qgis/segmentationToleranceType", 0 ).toInt() ); + double segmentationTolerance = settings.value( QStringLiteral( "/qgis/segmentationTolerance" ), "0.01745" ).toDouble(); + QgsAbstractGeometry::SegmentationToleranceType toleranceType = QgsAbstractGeometry::SegmentationToleranceType( settings.value( QStringLiteral( "/qgis/segmentationToleranceType" ), 0 ).toInt() ); mSettings.setSegmentationTolerance( segmentationTolerance ); mSettings.setSegmentationToleranceType( toleranceType ); - mWheelZoomFactor = settings.value( "/qgis/zoom_factor", 2 ).toDouble(); + mWheelZoomFactor = settings.value( QStringLiteral( "/qgis/zoom_factor" ), 2 ).toDouble(); QSize s = viewport()->size(); mSettings.setOutputSize( s ); @@ -226,8 +226,8 @@ void QgsMapCanvas::setMagnificationFactor( double factor ) { // do not go higher or lower than min max magnification ratio QSettings settings; - double magnifierMin = settings.value( "/qgis/magnifier_factor_min", 0.1 ).toDouble(); - double magnifierMax = settings.value( "/qgis/magnifier_factor_max", 10 ).toDouble(); + double magnifierMin = settings.value( QStringLiteral( "/qgis/magnifier_factor_min" ), 0.1 ).toDouble(); + double magnifierMax = settings.value( QStringLiteral( "/qgis/magnifier_factor_max" ), 10 ).toDouble(); factor = qBound( magnifierMin, factor, magnifierMax ); // the magnifier widget is in integer percent @@ -642,7 +642,7 @@ void QgsMapCanvas::rendererJobFinished() emit renderComplete( &p ); QSettings settings; - if ( settings.value( "/Map/logCanvasRefreshEvent", false ).toBool() ) + if ( settings.value( QStringLiteral( "/Map/logCanvasRefreshEvent" ), false ).toBool() ) { QString logMsg = tr( "Canvas refresh: %1 ms" ).arg( mJob->renderingTime() ); QgsMessageLog::logMessage( logMsg, tr( "Rendering" ) ); @@ -660,7 +660,7 @@ void QgsMapCanvas::rendererJobFinished() p.setBrush( QColor( 0, 0, 0, 110 ) ); p.drawRect( r ); p.setPen( Qt::white ); - QString msg = QString( "%1 :: %2 ms" ).arg( mUseParallelRendering ? "PARALLEL" : "SEQUENTIAL" ).arg( mJob->renderingTime() ); + QString msg = QStringLiteral( "%1 :: %2 ms" ).arg( mUseParallelRendering ? "PARALLEL" : "SEQUENTIAL" ).arg( mJob->renderingTime() ); p.drawText( r, msg, QTextOption( Qt::AlignCenter ) ); } @@ -741,7 +741,7 @@ void QgsMapCanvas::saveAsImage( const QString& theFileName, QPixmap * theQPixmap { item = i.previous(); - if ( !item || item->data( 0 ).toString() != "AnnotationItem" ) + if ( !item || item->data( 0 ).toString() != QLatin1String( "AnnotationItem" ) ) { continue; } @@ -766,9 +766,9 @@ void QgsMapCanvas::saveAsImage( const QString& theFileName, QPixmap * theQPixmap //Pixel XDim myHeader += qgsDoubleToString( mapUnitsPerPixel() ) + "\r\n"; //Rotation on y axis - hard coded - myHeader += "0 \r\n"; + myHeader += QLatin1String( "0 \r\n" ); //Rotation on x axis - hard coded - myHeader += "0 \r\n"; + myHeader += QLatin1String( "0 \r\n" ); //Pixel YDim - almost always negative - see //http://en.wikipedia.org/wiki/World_file#cite_note-2 myHeader += '-' + qgsDoubleToString( mapUnitsPerPixel() ) + "\r\n"; @@ -1864,7 +1864,7 @@ void QgsMapCanvas::setSnappingUtils( QgsSnappingUtils* utils ) void QgsMapCanvas::readProject( const QDomDocument & doc ) { - QDomNodeList nodes = doc.elementsByTagName( "mapcanvas" ); + QDomNodeList nodes = doc.elementsByTagName( QStringLiteral( "mapcanvas" ) ); if ( nodes.count() ) { QDomNode node = nodes.item( 0 ); @@ -1891,7 +1891,7 @@ void QgsMapCanvas::writeProject( QDomDocument & doc ) { // create node "mapcanvas" and call mMapRenderer->writeXml() - QDomNodeList nl = doc.elementsByTagName( "qgis" ); + QDomNodeList nl = doc.elementsByTagName( QStringLiteral( "qgis" ) ); if ( !nl.count() ) { QgsDebugMsg( "Unable to find qgis element in project file" ); @@ -1899,7 +1899,7 @@ void QgsMapCanvas::writeProject( QDomDocument & doc ) } QDomNode qgisNode = nl.item( 0 ); // there should only be one, so zeroth element ok - QDomElement mapcanvasNode = doc.createElement( "mapcanvas" ); + QDomElement mapcanvasNode = doc.createElement( QStringLiteral( "mapcanvas" ) ); qgisNode.appendChild( mapcanvasNode ); mSettings.writeXml( mapcanvasNode, doc ); @@ -1928,7 +1928,7 @@ void QgsMapCanvas::getDatumTransformInfo( const QgsMapLayer* ml, const QString& QgsCoordinateReferenceSystem srcCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( srcAuthId ); QgsCoordinateReferenceSystem destCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( destAuthId ); - if ( !s.value( "/Projections/showDatumTransformDialog", false ).toBool() ) + if ( !s.value( QStringLiteral( "/Projections/showDatumTransformDialog" ), false ).toBool() ) { // just use the default transform mSettings.datumTransformStore().addEntry( ml->id(), srcAuthId, destAuthId, -1, -1 ); diff --git a/src/gui/qgsmapcanvas.h b/src/gui/qgsmapcanvas.h index 54ae4af82f09..996a9a6340bf 100644 --- a/src/gui/qgsmapcanvas.h +++ b/src/gui/qgsmapcanvas.h @@ -438,7 +438,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView void selectionChangedSlot(); //! Save the convtents of the map canvas to disk as an image - void saveAsImage( const QString& theFileName, QPixmap * QPixmap = nullptr, const QString& = "PNG" ); + void saveAsImage( const QString& theFileName, QPixmap * QPixmap = nullptr, const QString& = QStringLiteral( "PNG" ) ); //! This slot is connected to the visibility change of one or more layers void layerStateChange(); diff --git a/src/gui/qgsmapcanvassnapper.cpp b/src/gui/qgsmapcanvassnapper.cpp index 787614ee040f..9d8f3dde30f9 100644 --- a/src/gui/qgsmapcanvassnapper.cpp +++ b/src/gui/qgsmapcanvassnapper.cpp @@ -137,7 +137,7 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<Qg bool topologicalEditing = QgsProject::instance()->topologicalEditing(); //snapping on intersection on? - int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); + int intersectionSnapping = QgsProject::instance()->readNumEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/IntersectionSnapping" ), 0 ); if ( topologicalEditing == 0 ) { @@ -167,25 +167,25 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<Qg bool ok, snappingDefinedInProject; QSettings settings; - QString snappingMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode", "current_layer", &snappingDefinedInProject ); - QString defaultSnapToleranceUnit = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapToleranceUnit" ) : settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", "0" ).toString(); - QString defaultSnapType = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType" ) : settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); - QString defaultSnapTolerance = snappingDefinedInProject ? QString::number( QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance" ) ) : settings.value( "/qgis/digitizing/default_snapping_tolerance", "0" ).toString(); + QString snappingMode = QgsProject::instance()->readEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/SnappingMode" ), QStringLiteral( "current_layer" ), &snappingDefinedInProject ); + QString defaultSnapToleranceUnit = snappingDefinedInProject ? QgsProject::instance()->readEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/DefaultSnapToleranceUnit" ) ) : settings.value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), "0" ).toString(); + QString defaultSnapType = snappingDefinedInProject ? QgsProject::instance()->readEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/DefaultSnapType" ) ) : settings.value( QStringLiteral( "/qgis/digitizing/default_snap_mode" ), "off" ).toString(); + QString defaultSnapTolerance = snappingDefinedInProject ? QString::number( QgsProject::instance()->readDoubleEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/DefaultSnapTolerance" ) ) ) : settings.value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), "0" ).toString(); - if ( !snappingDefinedInProject && defaultSnapType == "off" ) + if ( !snappingDefinedInProject && defaultSnapType == QLatin1String( "off" ) ) { return 0; } - if ( snappingMode == "current_layer" || !snappingDefinedInProject ) + if ( snappingMode == QLatin1String( "current_layer" ) || !snappingDefinedInProject ) { layerIdList.append( currentVectorLayer->id() ); - enabledList.append( "enabled" ); + enabledList.append( QStringLiteral( "enabled" ) ); toleranceList.append( defaultSnapTolerance ); toleranceUnitList.append( defaultSnapToleranceUnit ); snapToList.append( defaultSnapType ); } - else if ( snappingMode == "all_layers" ) + else if ( snappingMode == QLatin1String( "all_layers" ) ) { QList<QgsMapLayer*> allLayers = mMapCanvas->layers(); QList<QgsMapLayer*>::const_iterator layerIt = allLayers.constBegin(); @@ -196,7 +196,7 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<Qg continue; } layerIdList.append(( *layerIt )->id() ); - enabledList.append( "enabled" ); + enabledList.append( QStringLiteral( "enabled" ) ); toleranceList.append( defaultSnapTolerance ); toleranceUnitList.append( defaultSnapToleranceUnit ); snapToList.append( defaultSnapType ); @@ -204,11 +204,11 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<Qg } else //advanced { - layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &ok ); - enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); - toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); - toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); - snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); + layerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingList" ), QStringList(), &ok ); + enabledList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingEnabledList" ), QStringList(), &ok ); + toleranceList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingToleranceList" ), QStringList(), &ok ); + toleranceUnitList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnappingToleranceUnitList" ), QStringList(), &ok ); + snapToList = QgsProject::instance()->readListEntry( QStringLiteral( "Digitizing" ), QStringLiteral( "/LayerSnapToList" ), QStringList(), &ok ); } if ( !( layerIdList.size() == enabledList.size() && @@ -233,7 +233,7 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<Qg QStringList::const_iterator enabledIt( enabledList.constBegin() ); for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt ) { - if ( *enabledIt != "enabled" ) + if ( *enabledIt != QLatin1String( "enabled" ) ) { // skip layer if snapping is not enabled continue; @@ -251,15 +251,15 @@ int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<Qg snapLayer.mUnitType = ( QgsTolerance::UnitType ) tolUnitIt->toInt(); // segment or vertex - if ( *snapIt == "to vertex" || *snapIt == "to_vertex" ) + if ( *snapIt == QLatin1String( "to vertex" ) || *snapIt == QLatin1String( "to_vertex" ) ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertex; } - else if ( *snapIt == "to segment" || *snapIt == "to_segment" ) + else if ( *snapIt == QLatin1String( "to segment" ) || *snapIt == QLatin1String( "to_segment" ) ) { snapLayer.mSnapTo = QgsSnapper::SnapToSegment; } - else if ( *snapIt == "to vertex and segment" || *snapIt == "to_vertex_and_segment" ) + else if ( *snapIt == QLatin1String( "to vertex and segment" ) || *snapIt == QLatin1String( "to_vertex_and_segment" ) ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment; } diff --git a/src/gui/qgsmapcanvastracer.cpp b/src/gui/qgsmapcanvastracer.cpp index e0473457c93c..ae632be52e5a 100644 --- a/src/gui/qgsmapcanvastracer.cpp +++ b/src/gui/qgsmapcanvastracer.cpp @@ -45,7 +45,7 @@ QgsMapCanvasTracer::QgsMapCanvasTracer( QgsMapCanvas* canvas, QgsMessageBar* mes // arbitrarily chosen limit that should allow for fairly fast initialization // of the underlying graph structure - setMaxFeatureCount( QSettings().value( "/qgis/digitizing/tracing_max_feature_count", 10000 ).toInt() ); + setMaxFeatureCount( QSettings().value( QStringLiteral( "/qgis/digitizing/tracing_max_feature_count" ), 10000 ).toInt() ); } QgsMapCanvasTracer::~QgsMapCanvasTracer() @@ -89,7 +89,7 @@ void QgsMapCanvasTracer::reportError( QgsTracer::PathError err, bool addingVerte return; mLastMessage = new QgsMessageBarItem( tr( "Tracing" ), message, QgsMessageBar::WARNING, - QSettings().value( "/qgis/messageTimeout", 5 ).toInt() ); + QSettings().value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt() ); mMessageBar->pushItem( mLastMessage ); } diff --git a/src/gui/qgsmaplayerstylemanagerwidget.cpp b/src/gui/qgsmaplayerstylemanagerwidget.cpp index 474b7ecce76f..8dd9c185b11a 100644 --- a/src/gui/qgsmaplayerstylemanagerwidget.cpp +++ b/src/gui/qgsmaplayerstylemanagerwidget.cpp @@ -43,13 +43,13 @@ QgsMapLayerStyleManagerWidget::QgsMapLayerStyleManagerWidget( QgsMapLayer* layer QToolBar* toolbar = new QToolBar( this ); QAction* addAction = toolbar->addAction( tr( "Add" ) ); - addAction->setIcon( QgsApplication::getThemeIcon( "symbologyAdd.svg" ) ); + addAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "symbologyAdd.svg" ) ) ); connect( addAction, SIGNAL( triggered() ), this, SLOT( addStyle() ) ); QAction* removeAction = toolbar->addAction( tr( "Remove Current" ) ); - removeAction->setIcon( QgsApplication::getThemeIcon( "symbologyRemove.svg" ) ); + removeAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "symbologyRemove.svg" ) ) ); connect( removeAction, SIGNAL( triggered() ), this, SLOT( removeStyle() ) ); QAction* loadFromFileAction = toolbar->addAction( tr( "Load Style" ) ); - loadFromFileAction->setIcon( QgsApplication::getThemeIcon( "/mActionFileOpen.svg" ) ); + loadFromFileAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileOpen.svg" ) ) ); connect( loadFromFileAction, SIGNAL( triggered() ), this, SLOT( loadStyle() ) ); QAction* saveAsDefaultAction = toolbar->addAction( tr( "Save as default" ) ); connect( saveAsDefaultAction, SIGNAL( triggered() ), this, SLOT( saveAsDefault() ) ); @@ -82,7 +82,7 @@ QgsMapLayerStyleManagerWidget::QgsMapLayerStyleManagerWidget( QgsMapLayer* layer QString stylename = name; if ( stylename.isEmpty() ) - stylename = "(default)"; + stylename = QStringLiteral( "(default)" ); QStandardItem* item = new QStandardItem( stylename ); mModel->appendRow( item ); @@ -98,8 +98,8 @@ void QgsMapLayerStyleManagerWidget::styleClicked( const QModelIndex &index ) return; QString name = index.data().toString(); - if ( name == "(default)" ) - name = ""; + if ( name == QLatin1String( "(default)" ) ) + name = QLatin1String( "" ); mLayer->styleManager()->setCurrentStyle( name ); } @@ -147,7 +147,7 @@ void QgsMapLayerStyleManagerWidget::addStyle() bool ok; QString text = QInputDialog::getText( nullptr, tr( "New style" ), tr( "Style name:" ), QLineEdit::Normal, - "new style", &ok ); + QStringLiteral( "new style" ), &ok ); if ( !ok || text.isEmpty() ) return; @@ -202,7 +202,7 @@ void QgsMapLayerStyleManagerWidget::saveAsDefault() case 0: return; case 2: - layer->saveStyleToDatabase( "", "", true, "", errorMsg ); + layer->saveStyleToDatabase( QLatin1String( "" ), QLatin1String( "" ), true, QLatin1String( "" ), errorMsg ); if ( errorMsg.isNull() ) { return; @@ -296,7 +296,7 @@ void QgsMapLayerStyleManagerWidget::saveStyle() void QgsMapLayerStyleManagerWidget::loadStyle() { QSettings myQSettings; // where we keep last used filter in persistent state - QString myLastUsedDir = myQSettings.value( "style/lastStyleDir", QDir::homePath() ).toString(); + QString myLastUsedDir = myQSettings.value( QStringLiteral( "style/lastStyleDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getOpenFileName( this, tr( "Load layer properties from style file" ), myLastUsedDir, tr( "QGIS Layer Style File" ) + " (*.qml);;" + tr( "SLD File" ) + " (*.sld)" ); @@ -308,7 +308,7 @@ void QgsMapLayerStyleManagerWidget::loadStyle() QString myMessage; bool defaultLoadedFlag = false; - if ( myFileName.endsWith( ".sld", Qt::CaseInsensitive ) ) + if ( myFileName.endsWith( QLatin1String( ".sld" ), Qt::CaseInsensitive ) ) { // load from SLD myMessage = mLayer->loadSldStyle( myFileName, defaultLoadedFlag ); @@ -330,6 +330,6 @@ void QgsMapLayerStyleManagerWidget::loadStyle() QFileInfo myFI( myFileName ); QString myPath = myFI.path(); - myQSettings.setValue( "style/lastStyleDir", myPath ); + myQSettings.setValue( QStringLiteral( "style/lastStyleDir" ), myPath ); } diff --git a/src/gui/qgsmapoverviewcanvas.cpp b/src/gui/qgsmapoverviewcanvas.cpp index 42f3b19e5220..99ff2dbc9582 100644 --- a/src/gui/qgsmapoverviewcanvas.cpp +++ b/src/gui/qgsmapoverviewcanvas.cpp @@ -37,7 +37,7 @@ QgsMapOverviewCanvas::QgsMapOverviewCanvas( QWidget * parent, QgsMapCanvas* mapC , mJob( nullptr ) { setAutoFillBackground( true ); - setObjectName( "theOverviewCanvas" ); + setObjectName( QStringLiteral( "theOverviewCanvas" ) ); mPanningWidget = new QgsPanningWidget( this ); mSettings.setFlag( QgsMapSettings::DrawLabeling, false ); @@ -282,7 +282,7 @@ QStringList QgsMapOverviewCanvas::layerSet() const QgsPanningWidget::QgsPanningWidget( QWidget* parent ) : QWidget( parent ) { - setObjectName( "panningWidget" ); + setObjectName( QStringLiteral( "panningWidget" ) ); setMinimumSize( 5, 5 ); setAttribute( Qt::WA_NoSystemBackground ); } diff --git a/src/gui/qgsmaptip.cpp b/src/gui/qgsmaptip.cpp index 250426999634..4cbca96ac690 100644 --- a/src/gui/qgsmaptip.cpp +++ b/src/gui/qgsmaptip.cpp @@ -149,7 +149,7 @@ void QgsMapTip::showMapTip( QgsMapLayer *pLayer, { // Get the content size QWebElement container = mWebView->page()->mainFrame()->findFirstElement( - "#QgsWebViewContainer" ); + QStringLiteral( "#QgsWebViewContainer" ) ); int width = container.geometry().width() + 5 + scrollbarWidth; int height = container.geometry().height() + 5 + scrollbarHeight; diff --git a/src/gui/qgsmaptool.cpp b/src/gui/qgsmaptool.cpp index 9c6bbff84ff0..b2b7308fefd0 100644 --- a/src/gui/qgsmaptool.cpp +++ b/src/gui/qgsmaptool.cpp @@ -192,7 +192,7 @@ QgsMapCanvas* QgsMapTool::canvas() double QgsMapTool::searchRadiusMM() { QSettings settings; - double radius = settings.value( "/Map/searchRadiusMM", Qgis::DEFAULT_SEARCH_RADIUS_MM ).toDouble(); + double radius = settings.value( QStringLiteral( "/Map/searchRadiusMM" ), Qgis::DEFAULT_SEARCH_RADIUS_MM ).toDouble(); if ( radius > 0 ) { diff --git a/src/gui/qgsmaptoolcapture.cpp b/src/gui/qgsmaptoolcapture.cpp index 652a3f9c1858..8e50aaba928a 100644 --- a/src/gui/qgsmaptoolcapture.cpp +++ b/src/gui/qgsmaptoolcapture.cpp @@ -103,7 +103,7 @@ void QgsMapToolCapture::validationFinished() QString msgFinished = tr( "Validation finished" ); if ( !mValidationWarnings.isEmpty() ) { - emit messageEmitted( mValidationWarnings.join( "\n" ).append( "\n" ).append( msgFinished ), QgsMessageBar::WARNING ); + emit messageEmitted( mValidationWarnings.join( QStringLiteral( "\n" ) ).append( "\n" ).append( msgFinished ), QgsMessageBar::WARNING ); } } @@ -619,7 +619,7 @@ void QgsMapToolCapture::closePolygon() void QgsMapToolCapture::validateGeometry() { QSettings settings; - if ( settings.value( "/qgis/digitizing/validate_geometries", 1 ).toInt() == 0 ) + if ( settings.value( QStringLiteral( "/qgis/digitizing/validate_geometries" ), 1 ).toInt() == 0 ) return; if ( mValidator ) @@ -691,7 +691,7 @@ void QgsMapToolCapture::addError( QgsGeometry::Error e ) } emit messageDiscarded(); - emit messageEmitted( mValidationWarnings.join( "\n" ), QgsMessageBar::WARNING ); + emit messageEmitted( mValidationWarnings.join( QStringLiteral( "\n" ) ), QgsMessageBar::WARNING ); } int QgsMapToolCapture::size() diff --git a/src/gui/qgsmaptooledit.cpp b/src/gui/qgsmaptooledit.cpp index 068e526c1f3b..d1a85ca5c3e6 100644 --- a/src/gui/qgsmaptooledit.cpp +++ b/src/gui/qgsmaptooledit.cpp @@ -38,15 +38,15 @@ QgsRubberBand* QgsMapToolEdit::createRubberBand( QgsWkbTypes::GeometryType geome { QSettings settings; QgsRubberBand* rb = new QgsRubberBand( mCanvas, geometryType ); - rb->setWidth( settings.value( "/qgis/digitizing/line_width", 1 ).toInt() ); + rb->setWidth( settings.value( QStringLiteral( "/qgis/digitizing/line_width" ), 1 ).toInt() ); QColor color( - settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(), - settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(), - settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt() ); - double myAlpha = settings.value( "/qgis/digitizing/line_color_alpha", 200 ).toInt() / 255.0; + settings.value( QStringLiteral( "/qgis/digitizing/line_color_red" ), 255 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_green" ), 0 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_blue" ), 0 ).toInt() ); + double myAlpha = settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), 200 ).toInt() / 255.0; if ( alternativeBand ) { - myAlpha = myAlpha * settings.value( "/qgis/digitizing/line_color_alpha_scale", 0.75 ).toDouble(); + myAlpha = myAlpha * settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha_scale" ), 0.75 ).toDouble(); rb->setLineStyle( Qt::DotLine ); } if ( geometryType == QgsWkbTypes::PolygonGeometry ) @@ -57,10 +57,10 @@ QgsRubberBand* QgsMapToolEdit::createRubberBand( QgsWkbTypes::GeometryType geome rb->setColor( color ); QColor fillColor( - settings.value( "/qgis/digitizing/fill_color_red", 255 ).toInt(), - settings.value( "/qgis/digitizing/fill_color_green", 0 ).toInt(), - settings.value( "/qgis/digitizing/fill_color_blue", 0 ).toInt() ); - myAlpha = settings.value( "/qgis/digitizing/fill_color_alpha", 30 ).toInt() / 255.0 ; + settings.value( QStringLiteral( "/qgis/digitizing/fill_color_red" ), 255 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/fill_color_green" ), 0 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/fill_color_blue" ), 0 ).toInt() ); + myAlpha = settings.value( QStringLiteral( "/qgis/digitizing/fill_color_alpha" ), 30 ).toInt() / 255.0 ; fillColor.setAlphaF( myAlpha ); rb->setFillColor( fillColor ); @@ -101,13 +101,13 @@ QgsGeometryRubberBand* QgsMapToolEdit::createGeometryRubberBand( QgsWkbTypes::Ge { QSettings settings; QgsGeometryRubberBand* rb = new QgsGeometryRubberBand( mCanvas, geometryType ); - QColor color( settings.value( "/qgis/digitizing/line_color_red", 255 ).toInt(), - settings.value( "/qgis/digitizing/line_color_green", 0 ).toInt(), - settings.value( "/qgis/digitizing/line_color_blue", 0 ).toInt() ); - double myAlpha = settings.value( "/qgis/digitizing/line_color_alpha", 200 ).toInt() / 255.0 ; + QColor color( settings.value( QStringLiteral( "/qgis/digitizing/line_color_red" ), 255 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_green" ), 0 ).toInt(), + settings.value( QStringLiteral( "/qgis/digitizing/line_color_blue" ), 0 ).toInt() ); + double myAlpha = settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha" ), 200 ).toInt() / 255.0 ; if ( alternativeBand ) { - myAlpha = myAlpha * settings.value( "/qgis/digitizing/line_color_alpha_scale", 0.75 ).toDouble(); + myAlpha = myAlpha * settings.value( QStringLiteral( "/qgis/digitizing/line_color_alpha_scale" ), 0.75 ).toDouble(); rb->setLineStyle( Qt::DotLine ); } color.setAlphaF( myAlpha ); diff --git a/src/gui/qgsmaptoolidentify.cpp b/src/gui/qgsmaptoolidentify.cpp index 0c2090c57b90..7a65771bf8ec 100644 --- a/src/gui/qgsmaptoolidentify.cpp +++ b/src/gui/qgsmaptoolidentify.cpp @@ -105,7 +105,7 @@ QList<QgsMapToolIdentify::IdentifyResult> QgsMapToolIdentify::identify( int x, i if ( mode == DefaultQgsSetting ) { QSettings settings; - mode = static_cast<IdentifyMode>( settings.value( "/Map/identifyMode", 0 ).toInt() ); + mode = static_cast<IdentifyMode>( settings.value( QStringLiteral( "/Map/identifyMode" ), 0 ).toInt() ); } if ( mode == LayerSelection ) @@ -132,7 +132,7 @@ QList<QgsMapToolIdentify::IdentifyResult> QgsMapToolIdentify::identify( int x, i { QApplication::setOverrideCursor( Qt::WaitCursor ); - QStringList noIdentifyLayerIdList = QgsProject::instance()->readListEntry( "Identify", "/disabledLayers" ); + QStringList noIdentifyLayerIdList = QgsProject::instance()->readListEntry( QStringLiteral( "Identify" ), QStringLiteral( "/disabledLayers" ) ); int layerCount; if ( layerList.isEmpty() ) @@ -300,18 +300,18 @@ void QgsMapToolIdentify::closestVertexAttributes( const QgsAbstractGeometry& geo QgsPointV2 closestPoint = geometry.vertexAt( vId ); QgsPoint closestPointMapCoords = mCanvas->mapSettings().layerToMapCoordinates( layer, QgsPoint( closestPoint.x(), closestPoint.y() ) ); - derivedAttributes.insert( "Closest vertex X", formatXCoordinate( closestPointMapCoords ) ); - derivedAttributes.insert( "Closest vertex Y", formatYCoordinate( closestPointMapCoords ) ); + derivedAttributes.insert( QStringLiteral( "Closest vertex X" ), formatXCoordinate( closestPointMapCoords ) ); + derivedAttributes.insert( QStringLiteral( "Closest vertex Y" ), formatYCoordinate( closestPointMapCoords ) ); if ( closestPoint.is3D() ) { str = QLocale::system().toString( closestPoint.z(), 'g', 10 ); - derivedAttributes.insert( "Closest vertex Z", str ); + derivedAttributes.insert( QStringLiteral( "Closest vertex Z" ), str ); } if ( closestPoint.isMeasure() ) { str = QLocale::system().toString( closestPoint.m(), 'g', 10 ); - derivedAttributes.insert( "Closest vertex M", str ); + derivedAttributes.insert( QStringLiteral( "Closest vertex M" ), str ); } if ( vId.type == QgsVertexId::CurveVertex ) @@ -323,7 +323,7 @@ void QgsMapToolIdentify::closestVertexAttributes( const QgsAbstractGeometry& geo ++vIdAfter.vertex; QgsGeometryUtils::circleCenterRadius( geometry.vertexAt( vIdBefore ), geometry.vertexAt( vId ), geometry.vertexAt( vIdAfter ), radius, centerX, centerY ); - derivedAttributes.insert( "Closest vertex radius", QLocale::system().toString( radius ) ); + derivedAttributes.insert( QStringLiteral( "Closest vertex radius" ), QLocale::system().toString( radius ) ); } } @@ -432,19 +432,19 @@ QMap< QString, QString > QgsMapToolIdentify::featureDerivedAttributes( QgsFeatur // Include the x and y coordinates of the point as a derived attribute QgsPoint pnt = mCanvas->mapSettings().layerToMapCoordinates( layer, feature->geometry().asPoint() ); QString str = formatXCoordinate( pnt ); - derivedAttributes.insert( "X", str ); + derivedAttributes.insert( QStringLiteral( "X" ), str ); str = formatYCoordinate( pnt ); - derivedAttributes.insert( "Y", str ); + derivedAttributes.insert( QStringLiteral( "Y" ), str ); if ( QgsWkbTypes::hasZ( wkbType ) ) { str = QLocale::system().toString( static_cast<const QgsPointV2*>( feature->geometry().geometry() )->z(), 'g', 10 ); - derivedAttributes.insert( "Z", str ); + derivedAttributes.insert( QStringLiteral( "Z" ), str ); } if ( QgsWkbTypes::hasM( wkbType ) ) { str = QLocale::system().toString( static_cast<const QgsPointV2*>( feature->geometry().geometry() )->m(), 'g', 10 ); - derivedAttributes.insert( "M", str ); + derivedAttributes.insert( QStringLiteral( "M" ), str ); } } @@ -483,7 +483,7 @@ bool QgsMapToolIdentify::identifyRasterLayer( QList<IdentifyResult> *results, Qg QMap< QString, QString > attributes, derivedAttributes; - QgsRaster::IdentifyFormat format = QgsRasterDataProvider::identifyFormatFromName( layer->customProperty( "identify/format" ).toString() ); + QgsRaster::IdentifyFormat format = QgsRasterDataProvider::identifyFormatFromName( layer->customProperty( QStringLiteral( "identify/format" ) ).toString() ); // check if the format is really supported otherwise use first supported format if ( !( QgsRasterDataProvider::identifyFormatToCapability( format ) & capabilities ) ) @@ -609,10 +609,10 @@ bool QgsMapToolIdentify::identifyRasterLayer( QList<IdentifyResult> *results, Qg // WMS sublayer and feature type, a sublayer may contain multiple feature types. // Sublayer name may be the same as layer name and feature type name // may be the same as sublayer. We try to avoid duplicities in label. - QString sublayer = featureStore.params().value( "sublayer" ).toString(); - QString featureType = featureStore.params().value( "featureType" ).toString(); + QString sublayer = featureStore.params().value( QStringLiteral( "sublayer" ) ).toString(); + QString featureType = featureStore.params().value( QStringLiteral( "featureType" ) ).toString(); // Strip UMN MapServer '_feature' - featureType.remove( "_feature" ); + featureType.remove( QStringLiteral( "_feature" ) ); QStringList labels; if ( sublayer.compare( layer->name(), Qt::CaseInsensitive ) != 0 ) { @@ -626,9 +626,9 @@ bool QgsMapToolIdentify::identifyRasterLayer( QList<IdentifyResult> *results, Qg QMap< QString, QString > derAttributes = derivedAttributes; derAttributes.unite( featureDerivedAttributes( &feature, layer ) ); - IdentifyResult identifyResult( qobject_cast<QgsMapLayer *>( layer ), labels.join( " / " ), featureStore.fields(), feature, derAttributes ); + IdentifyResult identifyResult( qobject_cast<QgsMapLayer *>( layer ), labels.join( QStringLiteral( " / " ) ), featureStore.fields(), feature, derAttributes ); - identifyResult.mParams.insert( "getFeatureInfoUrl", featureStore.params().value( "getFeatureInfoUrl" ) ); + identifyResult.mParams.insert( QStringLiteral( "getFeatureInfoUrl" ), featureStore.params().value( QStringLiteral( "getFeatureInfoUrl" ) ) ); results->append( identifyResult ); } } @@ -641,7 +641,7 @@ bool QgsMapToolIdentify::identifyRasterLayer( QList<IdentifyResult> *results, Qg { QString value = values.value( bandNo ).toString(); attributes.clear(); - attributes.insert( "", value ); + attributes.insert( QLatin1String( "" ), value ); QString label = layer->subLayers().value( bandNo ); results->append( IdentifyResult( qobject_cast<QgsMapLayer *>( layer ), label, attributes, derivedAttributes ) ); @@ -673,7 +673,7 @@ QgsUnitTypes::AreaUnit QgsMapToolIdentify::displayAreaUnits() const QString QgsMapToolIdentify::formatDistance( double distance ) const { QSettings settings; - bool baseUnit = settings.value( "/qgis/measure/keepbaseunit", true ).toBool(); + bool baseUnit = settings.value( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ).toBool(); return QgsDistanceArea::formatDistance( distance, 3, displayDistanceUnits(), baseUnit ); } @@ -681,7 +681,7 @@ QString QgsMapToolIdentify::formatDistance( double distance ) const QString QgsMapToolIdentify::formatArea( double area ) const { QSettings settings; - bool baseUnit = settings.value( "/qgis/measure/keepbaseunit", true ).toBool(); + bool baseUnit = settings.value( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ).toBool(); return QgsDistanceArea::formatArea( area, 3, displayAreaUnits(), baseUnit ); } diff --git a/src/gui/qgsmessagebar.cpp b/src/gui/qgsmessagebar.cpp index 23b8c529dc28..0fe3208ab73e 100644 --- a/src/gui/qgsmessagebar.cpp +++ b/src/gui/qgsmessagebar.cpp @@ -51,8 +51,8 @@ QgsMessageBar::QgsMessageBar( QWidget *parent ) " image: url(:/images/themes/default/%1) }" "QProgressBar::chunk { background-color: rgba(0, 0, 0, 30%); width: 5px; }" ); - mCountProgress->setStyleSheet( mCountStyleSheet.arg( "mIconTimerPause.png" ) ); - mCountProgress->setObjectName( "mCountdown" ); + mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.png" ) ) ); + mCountProgress->setObjectName( QStringLiteral( "mCountdown" ) ); mCountProgress->setFixedSize( 25, 14 ); mCountProgress->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); mCountProgress->setTextVisible( false ); @@ -61,26 +61,26 @@ QgsMessageBar::QgsMessageBar( QWidget *parent ) mLayout->addWidget( mCountProgress, 0, 0, 1, 1 ); mItemCount = new QLabel( this ); - mItemCount->setObjectName( "mItemCount" ); + mItemCount->setObjectName( QStringLiteral( "mItemCount" ) ); mItemCount->setToolTip( tr( "Remaining messages" ) ); mItemCount->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ); mLayout->addWidget( mItemCount, 0, 2, 1, 1 ); mCloseMenu = new QMenu( this ); - mCloseMenu->setObjectName( "mCloseMenu" ); + mCloseMenu->setObjectName( QStringLiteral( "mCloseMenu" ) ); mActionCloseAll = new QAction( tr( "Close all" ), this ); mCloseMenu->addAction( mActionCloseAll ); connect( mActionCloseAll, SIGNAL( triggered() ), this, SLOT( clearWidgets() ) ); mCloseBtn = new QToolButton( this ); - mCloseMenu->setObjectName( "mCloseMenu" ); + mCloseMenu->setObjectName( QStringLiteral( "mCloseMenu" ) ); mCloseBtn->setToolTip( tr( "Close" ) ); mCloseBtn->setMinimumWidth( 40 ); mCloseBtn->setStyleSheet( "QToolButton { background-color: rgba(0, 0, 0, 0); }" "QToolButton::menu-button { background-color: rgba(0, 0, 0, 0); }" ); mCloseBtn->setCursor( Qt::PointingHandCursor ); - mCloseBtn->setIcon( QgsApplication::getThemeIcon( "/mIconClose.svg" ) ); + mCloseBtn->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconClose.svg" ) ) ); mCloseBtn->setIconSize( QSize( 18, 18 ) ); mCloseBtn->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Maximum ); mCloseBtn->setMenu( mCloseMenu ); @@ -110,12 +110,12 @@ void QgsMessageBar::mousePressEvent( QMouseEvent * e ) if ( mCountdownTimer->isActive() ) { mCountdownTimer->stop(); - mCountProgress->setStyleSheet( mCountStyleSheet.arg( "mIconTimerContinue.png" ) ); + mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerContinue.png" ) ) ); } else { mCountdownTimer->start(); - mCountProgress->setStyleSheet( mCountStyleSheet.arg( "mIconTimerPause.png" ) ); + mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.png" ) ) ); } } } @@ -334,7 +334,7 @@ void QgsMessageBar::resetCountdown() if ( mCountdownTimer->isActive() ) mCountdownTimer->stop(); - mCountProgress->setStyleSheet( mCountStyleSheet.arg( "mIconTimerPause.png" ) ); + mCountProgress->setStyleSheet( mCountStyleSheet.arg( QStringLiteral( "mIconTimerPause.png" ) ) ); mCountProgress->setVisible( false ); } diff --git a/src/gui/qgsmessagebaritem.cpp b/src/gui/qgsmessagebaritem.cpp index 5e4dda8b01b1..77110cf3ea8c 100644 --- a/src/gui/qgsmessagebaritem.cpp +++ b/src/gui/qgsmessagebaritem.cpp @@ -25,7 +25,7 @@ QgsMessageBarItem::QgsMessageBarItem( const QString &text, QgsMessageBar::MessageLevel level, int duration, QWidget *parent ) : QWidget( parent ) - , mTitle( "" ) + , mTitle( QLatin1String( "" ) ) , mText( text ) , mLevel( level ) , mDuration( duration ) @@ -64,8 +64,8 @@ QgsMessageBarItem::QgsMessageBarItem( const QString &title, const QString &text, QgsMessageBarItem::QgsMessageBarItem( QWidget *widget, QgsMessageBar::MessageLevel level, int duration, QWidget *parent ) : QWidget( parent ) - , mTitle( "" ) - , mText( "" ) + , mTitle( QLatin1String( "" ) ) + , mText( QLatin1String( "" ) ) , mLevel( level ) , mDuration( duration ) , mWidget( widget ) @@ -102,17 +102,17 @@ void QgsMessageBarItem::writeContent() } else { - QString msgIcon( "/mIconInfo.png" ); + QString msgIcon( QStringLiteral( "/mIconInfo.png" ) ); switch ( mLevel ) { case QgsMessageBar::CRITICAL: - msgIcon = QString( "/mIconCritical.png" ); + msgIcon = QStringLiteral( "/mIconCritical.png" ); break; case QgsMessageBar::WARNING: - msgIcon = QString( "/mIconWarning.svg" ); + msgIcon = QStringLiteral( "/mIconWarning.svg" ); break; case QgsMessageBar::SUCCESS: - msgIcon = QString( "/mIconSuccess.png" ); + msgIcon = QStringLiteral( "/mIconSuccess.png" ); break; default: break; @@ -135,7 +135,7 @@ void QgsMessageBarItem::writeContent() if ( !mTextEdit ) { mTextEdit = new QTextEdit( this ); - mTextEdit->setObjectName( "textEdit" ); + mTextEdit->setObjectName( QStringLiteral( "textEdit" ) ); mTextEdit->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Maximum ); mTextEdit->setReadOnly( true ); mTextEdit->setFrameShape( QFrame::NoFrame ); @@ -152,9 +152,9 @@ void QgsMessageBarItem::writeContent() { // add ':' to end of title QString t = mTitle.trimmed(); - if ( !content.isEmpty() && !t.endsWith( ':' ) && !t.endsWith( ": " ) ) - t += ": "; - content.prepend( QLatin1String( "<b>" ) + t + " </b>" ); + if ( !content.isEmpty() && !t.endsWith( ':' ) && !t.endsWith( QLatin1String( ": " ) ) ) + t += QLatin1String( ": " ); + content.prepend( QStringLiteral( "<b>" ) + t + " </b>" ); } mTextEdit->setText( content ); } @@ -190,7 +190,7 @@ void QgsMessageBarItem::writeContent() mStyleSheet = "QgsMessageBar { background-color: #e7f5fe; border: 1px solid #b9cfe4; } " "QLabel,QTextEdit { color: #2554a1; } "; } - mStyleSheet += "QLabel#mItemCount { font-style: italic; }"; + mStyleSheet += QLatin1String( "QLabel#mItemCount { font-style: italic; }" ); } QgsMessageBarItem* QgsMessageBarItem::setText( const QString& text ) diff --git a/src/gui/qgsmessagelogviewer.cpp b/src/gui/qgsmessagelogviewer.cpp index 8f285bd374ef..2e598fd0265d 100644 --- a/src/gui/qgsmessagelogviewer.cpp +++ b/src/gui/qgsmessagelogviewer.cpp @@ -69,10 +69,10 @@ void QgsMessageLogViewer::logMessage( QString message, QString tag, QgsMessageLo tabWidget->setCurrentIndex( tabWidget->count() - 1 ); } - QString prefix = QString( "%1\t%2\t" ) + QString prefix = QStringLiteral( "%1\t%2\t" ) .arg( QDateTime::currentDateTime().toString( Qt::ISODate ) ) .arg( level ); - w->appendPlainText( message.prepend( prefix ).replace( '\n', "\n\t\t\t" ) ); + w->appendPlainText( message.prepend( prefix ).replace( '\n', QLatin1String( "\n\t\t\t" ) ) ); w->verticalScrollBar()->setValue( w->verticalScrollBar()->maximum() ); } diff --git a/src/gui/qgsmessageviewer.cpp b/src/gui/qgsmessageviewer.cpp index b96a7d6ed0c4..21f650f87c62 100644 --- a/src/gui/qgsmessageviewer.cpp +++ b/src/gui/qgsmessageviewer.cpp @@ -30,16 +30,16 @@ QgsMessageViewer::QgsMessageViewer( QWidget *parent, Qt::WindowFlags fl, bool de setCheckBoxVisible( false ); setCheckBoxState( Qt::Unchecked ); - mCheckBoxQSettingsLabel = ""; + mCheckBoxQSettingsLabel = QLatin1String( "" ); QSettings settings; - restoreGeometry( settings.value( "/Windows/MessageViewer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/MessageViewer/geometry" ) ).toByteArray() ); } QgsMessageViewer::~QgsMessageViewer() { QSettings settings; - settings.setValue( "/Windows/MessageViewer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/MessageViewer/geometry" ), saveGeometry() ); } void QgsMessageViewer::setMessageAsHtml( const QString &msg ) diff --git a/src/gui/qgsnewgeopackagelayerdialog.cpp b/src/gui/qgsnewgeopackagelayerdialog.cpp index cf1d6607a851..c14e1558f51f 100644 --- a/src/gui/qgsnewgeopackagelayerdialog.cpp +++ b/src/gui/qgsnewgeopackagelayerdialog.cpp @@ -60,10 +60,10 @@ QgsNewGeoPackageLayerDialog::QgsNewGeoPackageLayerDialog( QWidget *parent, Qt::W setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/NewGeoPackageLayer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/NewGeoPackageLayer/geometry" ) ).toByteArray() ); - mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.svg" ) ); - mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.svg" ) ); + mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); + mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); #ifdef SUPPORT_GEOMETRY_LESS mGeometryTypeBox->addItem( tr( "Non spatial" ), wkbNone ); @@ -104,7 +104,7 @@ QgsNewGeoPackageLayerDialog::QgsNewGeoPackageLayerDialog( QWidget *parent, Qt::W mOkButton->setEnabled( false ); // Set the SRID box to a default of WGS84 - QgsCoordinateReferenceSystem defaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString() ); + QgsCoordinateReferenceSystem defaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( QStringLiteral( "/Projections/layerDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString() ); defaultCrs.validate(); mCrsSelector->setCrs( defaultCrs ); @@ -139,15 +139,15 @@ QgsNewGeoPackageLayerDialog::QgsNewGeoPackageLayerDialog( QWidget *parent, Qt::W QgsNewGeoPackageLayerDialog::~QgsNewGeoPackageLayerDialog() { QSettings settings; - settings.setValue( "/Windows/NewGeoPackageLayer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/NewGeoPackageLayer/geometry" ), saveGeometry() ); } void QgsNewGeoPackageLayerDialog::on_mFieldTypeBox_currentIndexChanged( int ) { QString myType = mFieldTypeBox->itemData( mFieldTypeBox->currentIndex(), Qt::UserRole ).toString(); - mFieldLengthEdit->setEnabled( myType == "text" ); - if ( myType != "text" ) - mFieldLengthEdit->setText( "" ); + mFieldLengthEdit->setEnabled( myType == QLatin1String( "text" ) ); + if ( myType != QLatin1String( "text" ) ) + mFieldLengthEdit->setText( QLatin1String( "" ) ); } @@ -172,9 +172,9 @@ void QgsNewGeoPackageLayerDialog::on_mSelectDatabaseButton_clicked() if ( fileName.isEmpty() ) return; - if ( !fileName.endsWith( ".gpkg", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".gpkg" ), Qt::CaseInsensitive ) ) { - fileName += ".gpkg"; + fileName += QLatin1String( ".gpkg" ); } mDatabaseEdit->setText( fileName ); @@ -437,19 +437,19 @@ bool QgsNewGeoPackageLayerDialog::apply() QString fieldWidth(( *it )->text( 2 ) ); OGRFieldType ogrType( OFTString ); - if ( fieldType == "text" ) + if ( fieldType == QLatin1String( "text" ) ) ogrType = OFTString; - else if ( fieldType == "integer" ) + else if ( fieldType == QLatin1String( "integer" ) ) ogrType = OFTInteger; #ifdef SUPPORT_INTEGER64 else if ( fieldType == "integer64" ) ogrType = OFTInteger64; #endif - else if ( fieldType == "real" ) + else if ( fieldType == QLatin1String( "real" ) ) ogrType = OFTReal; - else if ( fieldType == "date" ) + else if ( fieldType == QLatin1String( "date" ) ) ogrType = OFTDate; - else if ( fieldType == "datetime" ) + else if ( fieldType == QLatin1String( "datetime" ) ) ogrType = OFTDateTime; int ogrWidth = fieldWidth.toInt(); @@ -489,9 +489,9 @@ bool QgsNewGeoPackageLayerDialog::apply() OGR_DS_Destroy( hDS ); - QString uri( QString( "%1|layername=%2" ).arg( mDatabaseEdit->text(), tableName ) ); + QString uri( QStringLiteral( "%1|layername=%2" ).arg( mDatabaseEdit->text(), tableName ) ); QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier ); - QgsVectorLayer *layer = new QgsVectorLayer( uri, userVisiblelayerName, "ogr" ); + QgsVectorLayer *layer = new QgsVectorLayer( uri, userVisiblelayerName, QStringLiteral( "ogr" ) ); if ( layer->isValid() ) { // register this layer with the central layers registry diff --git a/src/gui/qgsnewhttpconnection.cpp b/src/gui/qgsnewhttpconnection.cpp index f6bd383ed3c6..fb803055bd9a 100644 --- a/src/gui/qgsnewhttpconnection.cpp +++ b/src/gui/qgsnewhttpconnection.cpp @@ -101,11 +101,11 @@ QgsNewHttpConnection::QgsNewHttpConnection( QString version = settings.value( key + "/version" ).toString(); int versionIdx = 0; // AUTO - if ( version == "1.0.0" ) + if ( version == QLatin1String( "1.0.0" ) ) versionIdx = 1; - else if ( version == "1.1.0" ) + else if ( version == QLatin1String( "1.1.0" ) ) versionIdx = 2; - else if ( version == "2.0.0" ) + else if ( version == QLatin1String( "2.0.0" ) ) versionIdx = 3; cmbVersion->setCurrentIndex( versionIdx ); @@ -123,10 +123,10 @@ QgsNewHttpConnection::QgsNewHttpConnection( } } - if ( mBaseKey != "/Qgis/connections-wms/" ) + if ( mBaseKey != QLatin1String( "/Qgis/connections-wms/" ) ) { - if ( mBaseKey != "/Qgis/connections-wcs/" && - mBaseKey != "/Qgis/connections-wfs/" ) + if ( mBaseKey != QLatin1String( "/Qgis/connections-wcs/" ) && + mBaseKey != QLatin1String( "/Qgis/connections-wfs/" ) ) { cbxIgnoreAxisOrientation->setVisible( false ); cbxInvertAxisOrientation->setVisible( false ); @@ -134,12 +134,12 @@ QgsNewHttpConnection::QgsNewHttpConnection( mGroupBox->layout()->removeWidget( cbxInvertAxisOrientation ); } - if ( mBaseKey == "/Qgis/connections-wfs/" ) + if ( mBaseKey == QLatin1String( "/Qgis/connections-wfs/" ) ) { cbxIgnoreAxisOrientation->setText( tr( "Ignore axis orientation (WFS 1.1/WFS 2.0)" ) ); } - if ( mBaseKey == "/Qgis/connections-wcs/" ) + if ( mBaseKey == QLatin1String( "/Qgis/connections-wcs/" ) ) { cbxIgnoreGetMapURI->setText( tr( "Ignore GetCoverage URI reported in capabilities" ) ); cbxIgnoreAxisOrientation->setText( tr( "Ignore axis orientation" ) ); @@ -166,7 +166,7 @@ QgsNewHttpConnection::QgsNewHttpConnection( mGroupBox->layout()->removeWidget( lblReferer ); } - if ( mBaseKey != "/Qgis/connections-wfs/" ) + if ( mBaseKey != QLatin1String( "/Qgis/connections-wfs/" ) ) { cmbVersion->setVisible( false ); mGroupBox->layout()->removeWidget( cmbVersion ); @@ -242,13 +242,13 @@ void QgsNewHttpConnection::accept() params.insert( QString( it->first ).toUpper(), *it ); } - if ( params["SERVICE"].second.toUpper() == "WMS" || - params["SERVICE"].second.toUpper() == "WFS" || - params["SERVICE"].second.toUpper() == "WCS" ) + if ( params[QStringLiteral( "SERVICE" )].second.toUpper() == "WMS" || + params[QStringLiteral( "SERVICE" )].second.toUpper() == "WFS" || + params[QStringLiteral( "SERVICE" )].second.toUpper() == "WCS" ) { - url.removeEncodedQueryItem( params["SERVICE"].first ); - url.removeEncodedQueryItem( params["REQUEST"].first ); - url.removeEncodedQueryItem( params["FORMAT"].first ); + url.removeEncodedQueryItem( params[QStringLiteral( "SERVICE" )].first ); + url.removeEncodedQueryItem( params[QStringLiteral( "REQUEST" )].first ); + url.removeEncodedQueryItem( params[QStringLiteral( "FORMAT" )].first ); } if ( url.encodedPath().isEmpty() ) @@ -258,15 +258,15 @@ void QgsNewHttpConnection::accept() settings.setValue( key + "/url", url.toString() ); - if ( mBaseKey == "/Qgis/connections-wms/" || - mBaseKey == "/Qgis/connections-wcs/" || - mBaseKey == "/Qgis/connections-wfs/" ) + if ( mBaseKey == QLatin1String( "/Qgis/connections-wms/" ) || + mBaseKey == QLatin1String( "/Qgis/connections-wcs/" ) || + mBaseKey == QLatin1String( "/Qgis/connections-wfs/" ) ) { settings.setValue( key + "/ignoreAxisOrientation", cbxIgnoreAxisOrientation->isChecked() ); settings.setValue( key + "/invertAxisOrientation", cbxInvertAxisOrientation->isChecked() ); } - if ( mBaseKey == "/Qgis/connections-wms/" || mBaseKey == "/Qgis/connections-wcs/" ) + if ( mBaseKey == QLatin1String( "/Qgis/connections-wms/" ) || mBaseKey == QLatin1String( "/Qgis/connections-wcs/" ) ) { settings.setValue( key + "/ignoreGetMapURI", cbxIgnoreGetMapURI->isChecked() ); settings.setValue( key + "/smoothPixmapTransform", cbxSmoothPixmapTransform->isChecked() ); @@ -293,26 +293,26 @@ void QgsNewHttpConnection::accept() settings.setValue( key + "/dpiMode", dpiMode ); } - if ( mBaseKey == "/Qgis/connections-wms/" ) + if ( mBaseKey == QLatin1String( "/Qgis/connections-wms/" ) ) { settings.setValue( key + "/ignoreGetFeatureInfoURI", cbxIgnoreGetFeatureInfoURI->isChecked() ); } - if ( mBaseKey == "/Qgis/connections-wfs/" ) + if ( mBaseKey == QLatin1String( "/Qgis/connections-wfs/" ) ) { - QString version = "auto"; + QString version = QStringLiteral( "auto" ); switch ( cmbVersion->currentIndex() ) { case 0: - version = "auto"; + version = QStringLiteral( "auto" ); break; case 1: - version = "1.0.0"; + version = QStringLiteral( "1.0.0" ); break; case 2: - version = "1.1.0"; + version = QStringLiteral( "1.1.0" ); break; case 3: - version = "2.0.0"; + version = QStringLiteral( "2.0.0" ); break; } settings.setValue( key + "/version", version ); diff --git a/src/gui/qgsnewhttpconnection.h b/src/gui/qgsnewhttpconnection.h index 975c6706c855..c898961cf02d 100644 --- a/src/gui/qgsnewhttpconnection.h +++ b/src/gui/qgsnewhttpconnection.h @@ -32,7 +32,7 @@ class GUI_EXPORT QgsNewHttpConnection : public QDialog, private Ui::QgsNewHttpCo public: //! Constructor - QgsNewHttpConnection( QWidget *parent = nullptr, const QString& baseKey = "/Qgis/connections-wms/", const QString& connName = QString::null, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); + QgsNewHttpConnection( QWidget *parent = nullptr, const QString& baseKey = QStringLiteral( "/Qgis/connections-wms/" ), const QString& connName = QString::null, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); //! Destructor ~QgsNewHttpConnection(); public slots: diff --git a/src/gui/qgsnewmemorylayerdialog.cpp b/src/gui/qgsnewmemorylayerdialog.cpp index ce25d1ac88ea..e6af327cebcf 100644 --- a/src/gui/qgsnewmemorylayerdialog.cpp +++ b/src/gui/qgsnewmemorylayerdialog.cpp @@ -44,37 +44,37 @@ QgsVectorLayer *QgsNewMemoryLayerDialog::runAndCreateLayer( QWidget *parent ) switch ( geometrytype ) { case QgsWkbTypes::Point: - geomType = "point"; + geomType = QStringLiteral( "point" ); break; case QgsWkbTypes::LineString: - geomType = "linestring"; + geomType = QStringLiteral( "linestring" ); break; case QgsWkbTypes::Polygon: - geomType = "polygon"; + geomType = QStringLiteral( "polygon" ); break; case QgsWkbTypes::MultiPoint: - geomType = "multipoint"; + geomType = QStringLiteral( "multipoint" ); break; case QgsWkbTypes::MultiLineString: - geomType = "multilinestring"; + geomType = QStringLiteral( "multilinestring" ); break; case QgsWkbTypes::MultiPolygon: - geomType = "multipolygon"; + geomType = QStringLiteral( "multipolygon" ); break; case QgsWkbTypes::NoGeometry: - geomType = "none"; + geomType = QStringLiteral( "none" ); break; default: - geomType = "point"; + geomType = QStringLiteral( "point" ); } - QString layerProperties = QString( "%1?" ).arg( geomType ); + QString layerProperties = QStringLiteral( "%1?" ).arg( geomType ); if ( QgsWkbTypes::NoGeometry != geometrytype ) - layerProperties.append( QString( "crs=%1&" ).arg( dialog.crs().authid() ) ); - layerProperties.append( QString( "memoryid=%1" ).arg( QUuid::createUuid().toString() ) ); + layerProperties.append( QStringLiteral( "crs=%1&" ).arg( dialog.crs().authid() ) ); + layerProperties.append( QStringLiteral( "memoryid=%1" ).arg( QUuid::createUuid().toString() ) ); QString name = dialog.layerName().isEmpty() ? tr( "New scratch layer" ) : dialog.layerName(); - QgsVectorLayer* newLayer = new QgsVectorLayer( layerProperties, name, QString( "memory" ) ); + QgsVectorLayer* newLayer = new QgsVectorLayer( layerProperties, name, QStringLiteral( "memory" ) ); return newLayer; } @@ -84,11 +84,11 @@ QgsNewMemoryLayerDialog::QgsNewMemoryLayerDialog( QWidget *parent, Qt::WindowFla setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/NewMemoryLayer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/NewMemoryLayer/geometry" ) ).toByteArray() ); mPointRadioButton->setChecked( true ); - QgsCoordinateReferenceSystem defaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString() ); + QgsCoordinateReferenceSystem defaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( QStringLiteral( "/Projections/layerDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString() ); defaultCrs.validate(); mCrsSelector->setCrs( defaultCrs ); @@ -98,7 +98,7 @@ QgsNewMemoryLayerDialog::QgsNewMemoryLayerDialog( QWidget *parent, Qt::WindowFla QgsNewMemoryLayerDialog::~QgsNewMemoryLayerDialog() { QSettings settings; - settings.setValue( "/Windows/NewMemoryLayer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/NewMemoryLayer/geometry" ), saveGeometry() ); } QgsWkbTypes::Type QgsNewMemoryLayerDialog::selectedType() const diff --git a/src/gui/qgsnewnamedialog.cpp b/src/gui/qgsnewnamedialog.cpp index 3f732f8af560..d5e20536f349 100644 --- a/src/gui/qgsnewnamedialog.cpp +++ b/src/gui/qgsnewnamedialog.cpp @@ -59,11 +59,11 @@ QgsNewNameDialog::QgsNewNameDialog( const QString& source, const QString& initia QRegExpValidator *validator = new QRegExpValidator( regexp, this ); mLineEdit->setValidator( validator ); } - mLineEdit->setMinimumWidth( mLineEdit->fontMetrics().width( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) ); + mLineEdit->setMinimumWidth( mLineEdit->fontMetrics().width( QStringLiteral( "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) ) ); connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( nameChanged() ) ); layout()->addWidget( mLineEdit ); - mNamesLabel = new QLabel( " ", this ); + mNamesLabel = new QLabel( QStringLiteral( " " ), this ); mNamesLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); if ( !mExtensions.isEmpty() ) { @@ -71,7 +71,7 @@ QgsNewNameDialog::QgsNewNameDialog( const QString& source, const QString& initia layout()->addWidget( mNamesLabel ); } - mErrorLabel = new QLabel( " ", this ); + mErrorLabel = new QLabel( QStringLiteral( " " ), this ); mErrorLabel->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); mErrorLabel->setWordWrap( true ); layout()->addWidget( mErrorLabel ); @@ -117,7 +117,7 @@ void QgsNewNameDialog::nameChanged() { mNamesLabel->setText( namesString ); } - mErrorLabel->setText( " " ); // space to keep vertical space + mErrorLabel->setText( QStringLiteral( " " ) ); // space to keep vertical space QPushButton* okButton = buttonBox()->button( QDialogButtonBox::Ok ); okButton->setText( mOkString ); okButton->setEnabled( true ); @@ -134,7 +134,7 @@ void QgsNewNameDialog::nameChanged() QStringList newNames = fullNames( newName, mExtensions ); if ( !mExtensions.isEmpty() ) { - namesString += ' ' + newNames.join( ", " ); + namesString += ' ' + newNames.join( QStringLiteral( ", " ) ); mNamesLabel->setText( namesString ); } @@ -143,7 +143,7 @@ void QgsNewNameDialog::nameChanged() if ( !conflicts.isEmpty() ) { QString warning = !mConflictingNameWarning.isEmpty() ? mConflictingNameWarning - : tr( "%n Name(s) %1 exists", nullptr, conflicts.size() ).arg( conflicts.join( ", " ) ); + : tr( "%n Name(s) %1 exists", nullptr, conflicts.size() ).arg( conflicts.join( QStringLiteral( ", " ) ) ); mErrorLabel->setText( highlightText( warning ) ); if ( mOverwriteEnabled ) { diff --git a/src/gui/qgsnewvectorlayerdialog.cpp b/src/gui/qgsnewvectorlayerdialog.cpp index 20ca222ef3c0..18e6b38ff1d7 100644 --- a/src/gui/qgsnewvectorlayerdialog.cpp +++ b/src/gui/qgsnewvectorlayerdialog.cpp @@ -37,10 +37,10 @@ QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFla setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/NewVectorLayer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/NewVectorLayer/geometry" ) ).toByteArray() ); - mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.svg" ) ); - mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.svg" ) ); + mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); + mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); mTypeBox->addItem( tr( "Text data" ), "String" ); mTypeBox->addItem( tr( "Whole number" ), "Integer" ); mTypeBox->addItem( tr( "Decimal number" ), "Real" ); @@ -69,7 +69,7 @@ QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFla mFileEncoding->addItems( QgsVectorDataProvider::availableEncodings() ); // Use default encoding if none supplied - QString enc = QSettings().value( "/UI/encoding", "System" ).toString(); + QString enc = QSettings().value( QStringLiteral( "/UI/encoding" ), "System" ).toString(); // The specified decoding is added if not existing alread, and then set current. // This should select it. @@ -83,9 +83,9 @@ QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFla mOkButton = buttonBox->button( QDialogButtonBox::Ok ); - mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << "id" << "Integer" << "10" << "" ) ); + mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << QStringLiteral( "id" ) << QStringLiteral( "Integer" ) << QStringLiteral( "10" ) << QLatin1String( "" ) ) ); - QgsCoordinateReferenceSystem defaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( "/Projections/layerDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString() ); + QgsCoordinateReferenceSystem defaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( settings.value( QStringLiteral( "/Projections/layerDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString() ); defaultCrs.validate(); mCrsSelector->setCrs( defaultCrs ); @@ -99,7 +99,7 @@ QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFla QgsNewVectorLayerDialog::~QgsNewVectorLayerDialog() { QSettings settings; - settings.setValue( "/Windows/NewVectorLayer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/NewVectorLayer/geometry" ), saveGeometry() ); } void QgsNewVectorLayerDialog::on_mFileFormatComboBox_currentIndexChanged( int index ) @@ -118,21 +118,21 @@ void QgsNewVectorLayerDialog::on_mTypeBox_currentIndexChanged( int index ) { case 0: // Text data if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 255 ) - mWidth->setText( "80" ); + mWidth->setText( QStringLiteral( "80" ) ); mPrecision->setEnabled( false ); mWidth->setValidator( new QIntValidator( 1, 255, this ) ); break; case 1: // Whole number if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 10 ) - mWidth->setText( "10" ); + mWidth->setText( QStringLiteral( "10" ) ); mPrecision->setEnabled( false ); mWidth->setValidator( new QIntValidator( 1, 10, this ) ); break; case 2: // Decimal number if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 20 ) - mWidth->setText( "20" ); + mWidth->setText( QStringLiteral( "20" ) ); mPrecision->setEnabled( true ); mWidth->setValidator( new QIntValidator( 1, 20, this ) ); break; @@ -169,7 +169,7 @@ void QgsNewVectorLayerDialog::on_mAddAttributeButton_clicked() { QString myName = mNameEdit->text(); QString myWidth = mWidth->text(); - QString myPrecision = mPrecision->isEnabled() ? mPrecision->text() : ""; + QString myPrecision = mPrecision->isEnabled() ? mPrecision->text() : QLatin1String( "" ); //use userrole to avoid translated type string QString myType = mTypeBox->itemData( mTypeBox->currentIndex(), Qt::UserRole ).toString(); mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType << myWidth << myPrecision ) ); @@ -195,7 +195,7 @@ void QgsNewVectorLayerDialog::attributes( QList< QPair<QString, QString> >& at ) while ( *it ) { QTreeWidgetItem *item = *it; - QString type = QString( "%1;%2;%3" ).arg( item->text( 1 ), item->text( 2 ), item->text( 3 ) ); + QString type = QStringLiteral( "%1;%2;%3" ).arg( item->text( 1 ), item->text( 2 ), item->text( 3 ) ); at.push_back( qMakePair( item->text( 0 ), type ) ); QgsDebugMsg( QString( "appending %1//%2" ).arg( item->text( 0 ), type ) ); ++it; @@ -231,7 +231,7 @@ QString QgsNewVectorLayerDialog::runAndCreateLayer( QWidget* parent, QString* pE QgsNewVectorLayerDialog geomDialog( parent ); if ( geomDialog.exec() == QDialog::Rejected ) { - return ""; + return QLatin1String( "" ); } QgsWkbTypes::Type geometrytype = geomDialog.selectedType(); @@ -244,23 +244,23 @@ QString QgsNewVectorLayerDialog::runAndCreateLayer( QWidget* parent, QString* pE geomDialog.attributes( attributes ); QSettings settings; - QString lastUsedDir = settings.value( "/UI/lastVectorFileFilterDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString(); QString filterString = QgsVectorFileWriter::filterForDriver( fileformat ); QString fileName = QFileDialog::getSaveFileName( nullptr, tr( "Save layer as..." ), lastUsedDir, filterString ); if ( fileName.isNull() ) { - return ""; + return QLatin1String( "" ); } - if ( fileformat == "ESRI Shapefile" && !fileName.endsWith( ".shp", Qt::CaseInsensitive ) ) - fileName += ".shp"; + if ( fileformat == QLatin1String( "ESRI Shapefile" ) && !fileName.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) + fileName += QLatin1String( ".shp" ); - settings.setValue( "/UI/lastVectorFileFilterDir", QFileInfo( fileName ).absolutePath() ); - settings.setValue( "/UI/encoding", enc ); + settings.setValue( QStringLiteral( "/UI/lastVectorFileFilterDir" ), QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/UI/encoding" ), enc ); //try to create the new layer with OGRProvider instead of QgsVectorFileWriter QgsProviderRegistry * pReg = QgsProviderRegistry::instance(); - QString ogrlib = pReg->library( "ogr" ); + QString ogrlib = pReg->library( QStringLiteral( "ogr" ) ); // load the data provider QLibrary* myLib = new QLibrary( ogrlib ); bool loaded = myLib->load(); diff --git a/src/gui/qgsoptionsdialogbase.cpp b/src/gui/qgsoptionsdialogbase.cpp index fb9f8c0c3dc2..1435d9d6cab5 100644 --- a/src/gui/qgsoptionsdialogbase.cpp +++ b/src/gui/qgsoptionsdialogbase.cpp @@ -35,7 +35,7 @@ QgsOptionsDialogBase::QgsOptionsDialogBase( const QString& settingsKey, QWidget* , mOptStackedWidget( nullptr ) , mOptSplitter( nullptr ) , mOptButtonBox( nullptr ) - , mDialogTitle( "" ) + , mDialogTitle( QLatin1String( "" ) ) , mIconOnly( false ) , mSettings( settings ) , mDelSettings( false ) @@ -46,9 +46,9 @@ QgsOptionsDialogBase::~QgsOptionsDialogBase() { if ( mInit ) { - mSettings->setValue( QString( "/Windows/%1/geometry" ).arg( mOptsKey ), saveGeometry() ); - mSettings->setValue( QString( "/Windows/%1/splitState" ).arg( mOptsKey ), mOptSplitter->saveState() ); - mSettings->setValue( QString( "/Windows/%1/tab" ).arg( mOptsKey ), mOptStackedWidget->currentIndex() ); + mSettings->setValue( QStringLiteral( "/Windows/%1/geometry" ).arg( mOptsKey ), saveGeometry() ); + mSettings->setValue( QStringLiteral( "/Windows/%1/splitState" ).arg( mOptsKey ), mOptSplitter->saveState() ); + mSettings->setValue( QStringLiteral( "/Windows/%1/tab" ).arg( mOptsKey ), mOptStackedWidget->currentIndex() ); } if ( mDelSettings ) // local settings obj to delete @@ -86,19 +86,19 @@ void QgsOptionsDialogBase::initOptionsBase( bool restoreUi, const QString& title } // start with copy of qgsoptionsdialog_template.ui to ensure existence of these objects - mOptListWidget = findChild<QListWidget*>( "mOptionsListWidget" ); - QFrame* optionsFrame = findChild<QFrame*>( "mOptionsFrame" ); - mOptStackedWidget = findChild<QStackedWidget*>( "mOptionsStackedWidget" ); - mOptSplitter = findChild<QSplitter*>( "mOptionsSplitter" ); - mOptButtonBox = findChild<QDialogButtonBox*>( "buttonBox" ); - QFrame* buttonBoxFrame = findChild<QFrame*>( "mButtonBoxFrame" ); + mOptListWidget = findChild<QListWidget*>( QStringLiteral( "mOptionsListWidget" ) ); + QFrame* optionsFrame = findChild<QFrame*>( QStringLiteral( "mOptionsFrame" ) ); + mOptStackedWidget = findChild<QStackedWidget*>( QStringLiteral( "mOptionsStackedWidget" ) ); + mOptSplitter = findChild<QSplitter*>( QStringLiteral( "mOptionsSplitter" ) ); + mOptButtonBox = findChild<QDialogButtonBox*>( QStringLiteral( "buttonBox" ) ); + QFrame* buttonBoxFrame = findChild<QFrame*>( QStringLiteral( "mButtonBoxFrame" ) ); if ( !mOptListWidget || !mOptStackedWidget || !mOptSplitter || !optionsFrame ) { return; } - int size = mSettings->value( "/IconSize", 24 ).toInt(); + int size = mSettings->value( QStringLiteral( "/IconSize" ), 24 ).toInt(); // buffer size to match displayed icon size in toolbars, and expected geometry restore // newWidth (above) may need adjusted if you adjust iconBuffer here int iconBuffer = 4; @@ -163,13 +163,13 @@ void QgsOptionsDialogBase::restoreOptionsBaseUi( const QString& title ) // re-save original dialog title in case it was changed after dialog initialization mDialogTitle = windowTitle(); - restoreGeometry( mSettings->value( QString( "/Windows/%1/geometry" ).arg( mOptsKey ) ).toByteArray() ); + restoreGeometry( mSettings->value( QStringLiteral( "/Windows/%1/geometry" ).arg( mOptsKey ) ).toByteArray() ); // mOptListWidget width is fixed to take up less space in QtDesigner // revert it now unless the splitter's state hasn't been saved yet mOptListWidget->setMaximumWidth( - mSettings->value( QString( "/Windows/%1/splitState" ).arg( mOptsKey ) ).isNull() ? 150 : 16777215 ); - mOptSplitter->restoreState( mSettings->value( QString( "/Windows/%1/splitState" ).arg( mOptsKey ) ).toByteArray() ); - int curIndx = mSettings->value( QString( "/Windows/%1/tab" ).arg( mOptsKey ), 0 ).toInt(); + mSettings->value( QStringLiteral( "/Windows/%1/splitState" ).arg( mOptsKey ) ).isNull() ? 150 : 16777215 ); + mOptSplitter->restoreState( mSettings->value( QStringLiteral( "/Windows/%1/splitState" ).arg( mOptsKey ) ).toByteArray() ); + int curIndx = mSettings->value( QStringLiteral( "/Windows/%1/tab" ).arg( mOptsKey ), 0 ).toInt(); // if the last used tab is out of range or not enabled display the first enabled one if ( mOptStackedWidget->count() < ( curIndx + 1 ) @@ -224,7 +224,7 @@ void QgsOptionsDialogBase::updateWindowTitle() QListWidgetItem *curitem = mOptListWidget->currentItem(); if ( curitem ) { - setWindowTitle( QString( "%1 | %2" ).arg( mDialogTitle, curitem->text() ) ); + setWindowTitle( QStringLiteral( "%1 | %2" ).arg( mDialogTitle, curitem->text() ) ); } else { diff --git a/src/gui/qgsorderbydialog.cpp b/src/gui/qgsorderbydialog.cpp index b763ee7294c0..7c6b78cfaaf1 100644 --- a/src/gui/qgsorderbydialog.cpp +++ b/src/gui/qgsorderbydialog.cpp @@ -48,7 +48,7 @@ void QgsOrderByDialog::setOrderBy( const QgsFeatureRequest::OrderBy& orderBy ) } // Add an empty widget at the end - setRow( i, QgsFeatureRequest::OrderByClause( "" ) ); + setRow( i, QgsFeatureRequest::OrderByClause( QLatin1String( "" ) ) ); } QgsFeatureRequest::OrderBy QgsOrderByDialog::orderBy() @@ -103,7 +103,7 @@ void QgsOrderByDialog::onExpressionChanged( const QString& expression ) else if ( !expression.isEmpty() && row == mOrderByTableWidget->rowCount() - 1 ) { mOrderByTableWidget->insertRow( mOrderByTableWidget->rowCount() ); - setRow( row + 1, QgsFeatureRequest::OrderByClause( "" ) ); + setRow( row + 1, QgsFeatureRequest::OrderByClause( QLatin1String( "" ) ) ); } } diff --git a/src/gui/qgsowssourceselect.cpp b/src/gui/qgsowssourceselect.cpp index 952553e1a914..6880b936c8af 100644 --- a/src/gui/qgsowssourceselect.cpp +++ b/src/gui/qgsowssourceselect.cpp @@ -116,14 +116,14 @@ QgsOWSSourceSelect::QgsOWSSourceSelect( const QString& service, QWidget * parent QSettings settings; QgsDebugMsg( "restoring geometry" ); - restoreGeometry( settings.value( "/Windows/WMSSourceSelect/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/WMSSourceSelect/geometry" ) ).toByteArray() ); } QgsOWSSourceSelect::~QgsOWSSourceSelect() { QSettings settings; QgsDebugMsg( "saving geometry" ); - settings.setValue( "/Windows/WMSSourceSelect/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/WMSSourceSelect/geometry" ), saveGeometry() ); } void QgsOWSSourceSelect::clearFormats() @@ -162,14 +162,14 @@ void QgsOWSSourceSelect::populateFormats() // -> enabled all formats, GDAL may be able to open them QMap<QString, QString> formatsMap; - formatsMap.insert( "geotiff", "tiff" ); - formatsMap.insert( "gtiff", "tiff" ); - formatsMap.insert( "tiff", "tiff" ); - formatsMap.insert( "tif", "tiff" ); - formatsMap.insert( "gif", "gif" ); - formatsMap.insert( "jpeg", "jpeg" ); - formatsMap.insert( "jpg", "jpeg" ); - formatsMap.insert( "png", "png" ); + formatsMap.insert( QStringLiteral( "geotiff" ), QStringLiteral( "tiff" ) ); + formatsMap.insert( QStringLiteral( "gtiff" ), QStringLiteral( "tiff" ) ); + formatsMap.insert( QStringLiteral( "tiff" ), QStringLiteral( "tiff" ) ); + formatsMap.insert( QStringLiteral( "tif" ), QStringLiteral( "tiff" ) ); + formatsMap.insert( QStringLiteral( "gif" ), QStringLiteral( "gif" ) ); + formatsMap.insert( QStringLiteral( "jpeg" ), QStringLiteral( "jpeg" ) ); + formatsMap.insert( QStringLiteral( "jpg" ), QStringLiteral( "jpeg" ) ); + formatsMap.insert( QStringLiteral( "png" ), QStringLiteral( "png" ) ); int preferred = -1; QStringList layersFormats = selectedLayersFormats(); @@ -177,7 +177,7 @@ void QgsOWSSourceSelect::populateFormats() { QString format = layersFormats.value( i ); QgsDebugMsg( "server format = " + format ); - QString simpleFormat = format.toLower().remove( "image/" ).remove( QRegExp( "_.*" ) ); + QString simpleFormat = format.toLower().remove( QStringLiteral( "image/" ) ).remove( QRegExp( "_.*" ) ); QgsDebugMsg( "server simpleFormat = " + simpleFormat ); QString mimeFormat = "image/" + formatsMap.value( simpleFormat ); QgsDebugMsg( "server mimeFormat = " + mimeFormat ); @@ -192,7 +192,7 @@ void QgsOWSSourceSelect::populateFormats() label += " / " + mMimeLabelMap.value( mimeFormat ); } - if ( simpleFormat.contains( "tif" ) ) // prefer *tif* + if ( simpleFormat.contains( QLatin1String( "tif" ) ) ) // prefer *tif* { if ( preferred < 0 || simpleFormat.startsWith( 'g' ) ) // prefer geotiff { @@ -447,8 +447,8 @@ void QgsOWSSourceSelect::populateCrs() void QgsOWSSourceSelect::clearCrs() { mCRSLabel->setText( tr( "Coordinate Reference System" ) + ':' ); - mSelectedCRS = ""; - mSelectedCRSLabel->setText( "" ); + mSelectedCRS = QLatin1String( "" ); + mSelectedCRSLabel->setText( QLatin1String( "" ) ); mChangeCRSButton->setEnabled( false ); } @@ -557,7 +557,7 @@ void QgsOWSSourceSelect::showError( QString const &theTitle, QString const &theF QgsMessageViewer * mv = new QgsMessageViewer( this ); mv->setWindowTitle( theTitle ); - if ( theFormat == "text/html" ) + if ( theFormat == QLatin1String( "text/html" ) ) { mv->setMessageAsHtml( theError ); } @@ -592,8 +592,8 @@ QString QgsOWSSourceSelect::descriptionForAuthId( const QString& authId ) void QgsOWSSourceSelect::addDefaultServers() { QMap<QString, QString> exampleServers; - exampleServers["DM Solutions GMap"] = "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap"; - exampleServers["Lizardtech server"] = "http://wms.lizardtech.com/lizardtech/iserv/ows"; + exampleServers[QStringLiteral( "DM Solutions GMap" )] = QStringLiteral( "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap" ); + exampleServers[QStringLiteral( "Lizardtech server" )] = QStringLiteral( "http://wms.lizardtech.com/lizardtech/iserv/ows" ); // Nice to have the qgis users map, but I'm not sure of the URL at the moment. // exampleServers["Qgis users map"] = "http://qgis.org/wms.cgi"; @@ -621,11 +621,11 @@ void QgsOWSSourceSelect::addDefaultServers() void QgsOWSSourceSelect::addWmsListRow( const QDomElement& item, int row ) { - QDomElement title = item.firstChildElement( "title" ); + QDomElement title = item.firstChildElement( QStringLiteral( "title" ) ); addWmsListItem( title, row, 0 ); - QDomElement description = item.firstChildElement( "description" ); + QDomElement description = item.firstChildElement( QStringLiteral( "description" ) ); addWmsListItem( description, row, 1 ); - QDomElement link = item.firstChildElement( "link" ); + QDomElement link = item.firstChildElement( QStringLiteral( "link" ) ); addWmsListItem( link, row, 2 ); } @@ -653,7 +653,7 @@ void QgsOWSSourceSelect::on_mSearchButton_clicked() QSettings settings; // geopole.org (geopole.ch) 25.4.2012 : 503 Service Unavailable, archive: Recently added 20 Jul 2011 - QString mySearchUrl = settings.value( "/qgis/WMSSearchUrl", "http://geopole.org/wms/search?search=%1&type=rss" ).toString(); + QString mySearchUrl = settings.value( QStringLiteral( "/qgis/WMSSearchUrl" ), "http://geopole.org/wms/search?search=%1&type=rss" ).toString(); QUrl url( mySearchUrl.arg( mSearchTermLineEdit->text() ) ); QgsDebugMsg( url.toString() ); @@ -672,13 +672,13 @@ void QgsOWSSourceSelect::searchFinished() if ( r->error() == QNetworkReply::NoError ) { // parse results - QDomDocument doc( "RSS" ); + QDomDocument doc( QStringLiteral( "RSS" ) ); QByteArray res = r->readAll(); QString error; int line, column; if ( doc.setContent( res, &error, &line, &column ) ) { - QDomNodeList list = doc.elementsByTagName( "item" ); + QDomNodeList list = doc.elementsByTagName( QStringLiteral( "item" ) ); mSearchTableWidget->setRowCount( list.size() ); for ( int i = 0; i < list.size(); i++ ) { diff --git a/src/gui/qgspanelwidget.cpp b/src/gui/qgspanelwidget.cpp index 0ef06bf32a81..01bf929e9d1f 100644 --- a/src/gui/qgspanelwidget.cpp +++ b/src/gui/qgspanelwidget.cpp @@ -80,7 +80,7 @@ void QgsPanelWidget::openPanel( QgsPanelWidget* panel ) { // Show the dialog version if no one is connected QDialog* dlg = new QDialog(); - QString key = QString( "/UI/paneldialog/%1" ).arg( panel->panelTitle() ); + QString key = QStringLiteral( "/UI/paneldialog/%1" ).arg( panel->panelTitle() ); QSettings settings; dlg->restoreGeometry( settings.value( key ).toByteArray() ); dlg->setWindowTitle( panel->panelTitle() ); diff --git a/src/gui/qgspanelwidgetstack.cpp b/src/gui/qgspanelwidgetstack.cpp index 5a8e0195cf70..e7daac4f1078 100644 --- a/src/gui/qgspanelwidgetstack.cpp +++ b/src/gui/qgspanelwidgetstack.cpp @@ -152,7 +152,7 @@ void QgsPanelWidgetStack::updateBreadcrumb() QString breadcrumb; Q_FOREACH ( QString title, mTitles ) { - breadcrumb += QString( " %1 >" ).arg( title ); + breadcrumb += QStringLiteral( " %1 >" ).arg( title ); } // Remove the last breadcrumb.chop( 1 ); diff --git a/src/gui/qgsprojectbadlayerguihandler.cpp b/src/gui/qgsprojectbadlayerguihandler.cpp index c80611f05518..7bf2bd63abc7 100644 --- a/src/gui/qgsprojectbadlayerguihandler.cpp +++ b/src/gui/qgsprojectbadlayerguihandler.cpp @@ -123,13 +123,13 @@ bool QgsProjectBadLayerGuiHandler::findMissingFile( const QString& fileFilters, { case IS_VECTOR: { - memoryQualifier = "lastVectorFileFilter"; + memoryQualifier = QStringLiteral( "lastVectorFileFilter" ); break; } case IS_RASTER: { - memoryQualifier = "lastRasterFileFilter"; + memoryQualifier = QStringLiteral( "lastRasterFileFilter" ); break; } diff --git a/src/gui/qgsprojectionselectionwidget.cpp b/src/gui/qgsprojectionselectionwidget.cpp index e507b7872f01..3e28f0655ef9 100644 --- a/src/gui/qgsprojectionselectionwidget.cpp +++ b/src/gui/qgsprojectionselectionwidget.cpp @@ -36,7 +36,7 @@ QgsProjectionSelectionWidget::QgsProjectionSelectionWidget( QWidget *parent ) mCrsComboBox->addItem( tr( "invalid projection" ), QgsProjectionSelectionWidget::CurrentCrs ); mCrsComboBox->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Preferred ); - if ( QgsProject::instance()->readNumEntry( "SpatialRefSys", "/ProjectionsEnabled", 0 ) ) + if ( QgsProject::instance()->readNumEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectionsEnabled" ), 0 ) ) { //only show project CRS if OTF reprojection is enabled - otherwise the //CRS stored in the project can be misleading @@ -45,7 +45,7 @@ QgsProjectionSelectionWidget::QgsProjectionSelectionWidget( QWidget *parent ) } QSettings settings; - QString defCrsString = settings.value( "/Projections/projectDefaultCrs", GEO_EPSG_CRS_AUTHID ).toString(); + QString defCrsString = settings.value( QStringLiteral( "/Projections/projectDefaultCrs" ), GEO_EPSG_CRS_AUTHID ).toString(); mDefaultCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( defCrsString ); if ( mDefaultCrs.authid() != mProjectCrs.authid() ) { @@ -59,7 +59,7 @@ QgsProjectionSelectionWidget::QgsProjectionSelectionWidget( QWidget *parent ) layout->addWidget( mCrsComboBox ); mButton = new QToolButton( this ); - mButton->setIcon( QgsApplication::getThemeIcon( "mActionSetProjection.svg" ) ); + mButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mActionSetProjection.svg" ) ) ); mButton->setToolTip( tr( "Select CRS" ) ); layout->addWidget( mButton ); diff --git a/src/gui/qgsprojectionselector.cpp b/src/gui/qgsprojectionselector.cpp index c5dbdb800879..641fdcf4b533 100644 --- a/src/gui/qgsprojectionselector.cpp +++ b/src/gui/qgsprojectionselector.cpp @@ -90,7 +90,7 @@ QgsProjectionSelector::~QgsProjectionSelector() // Save to file *** Should be removed sometims in the future *** QSettings settings; - settings.setValue( "/UI/recentProjections", mRecentProjections ); + settings.setValue( QStringLiteral( "/UI/recentProjections" ), mRecentProjections ); // Convert to EPSG and proj4, and save those values also @@ -108,8 +108,8 @@ QgsProjectionSelector::~QgsProjectionSelector() projectionsProj4 << crs.toProj4(); projectionsAuthId << crs.authid(); } - settings.setValue( "/UI/recentProjectionsProj4", projectionsProj4 ); - settings.setValue( "/UI/recentProjectionsAuthId", projectionsAuthId ); + settings.setValue( QStringLiteral( "/UI/recentProjectionsProj4" ), projectionsProj4 ); + settings.setValue( QStringLiteral( "/UI/recentProjectionsAuthId" ), projectionsAuthId ); } void QgsProjectionSelector::resizeEvent( QResizeEvent * theEvent ) @@ -148,7 +148,7 @@ void QgsProjectionSelector::showEvent( QShowEvent * theEvent ) QString QgsProjectionSelector::ogcWmsCrsFilterAsSqlExpression( QSet<QString> * crsFilter ) { - QString sqlExpression = "1"; // it's "SQL" for "true" + QString sqlExpression = QStringLiteral( "1" ); // it's "SQL" for "true" QMap<QString, QStringList> authParts; if ( !crsFilter ) @@ -187,14 +187,14 @@ QString QgsProjectionSelector::ogcWmsCrsFilterAsSqlExpression( QSet<QString> * c if ( !authParts.isEmpty() ) { - QString prefix = " AND ("; + QString prefix = QStringLiteral( " AND (" ); Q_FOREACH ( const QString& auth_name, authParts.keys() ) { - sqlExpression += QString( "%1(upper(auth_name)='%2' AND upper(auth_id) IN ('%3'))" ) + sqlExpression += QStringLiteral( "%1(upper(auth_name)='%2' AND upper(auth_id) IN ('%3'))" ) .arg( prefix, auth_name, - authParts[auth_name].join( "','" ) ); - prefix = " OR "; + authParts[auth_name].join( QStringLiteral( "','" ) ) ); + prefix = QStringLiteral( " OR " ); } sqlExpression += ')'; } @@ -254,8 +254,8 @@ void QgsProjectionSelector::applySelection( int column, QString value ) // deselect the selected item to avoid confusing the user lstCoordinateSystems->clearSelection(); lstRecent->clearSelection(); - teProjection->setText( "" ); - teSelected->setText( "" ); + teProjection->setText( QLatin1String( "" ) ); + teSelected->setText( QLatin1String( "" ) ); } } @@ -293,7 +293,7 @@ QString QgsProjectionSelector::selectedProj4String() // Get the selected node QTreeWidgetItem *item = lstCoordinateSystems->currentItem(); if ( !item || item->text( QGIS_CRS_ID_COLUMN ).isEmpty() ) - return ""; + return QLatin1String( "" ); QString srsId = item->text( QGIS_CRS_ID_COLUMN ); @@ -323,13 +323,13 @@ QString QgsProjectionSelector::selectedProj4String() if ( rc ) { showDBMissingWarning( databaseFileName ); - return ""; + return QLatin1String( "" ); } // prepare the sql statement const char *tail; sqlite3_stmt *stmt; - QString sql = QString( "select parameters from tbl_srs where srs_id=%1" ).arg( srsId ); + QString sql = QStringLiteral( "select parameters from tbl_srs where srs_id=%1" ).arg( srsId ); QgsDebugMsg( "Selection sql: " + sql ); @@ -398,7 +398,7 @@ QString QgsProjectionSelector::getSelectedExpression( const QString& expression // prepare the sql statement const char *tail; sqlite3_stmt *stmt; - QString sql = QString( "select %1 from tbl_srs where srs_id=%2" ) + QString sql = QStringLiteral( "select %1 from tbl_srs where srs_id=%2" ) .arg( expression, lvi->text( QGIS_CRS_ID_COLUMN ) ); @@ -424,17 +424,17 @@ QString QgsProjectionSelector::getSelectedExpression( const QString& expression long QgsProjectionSelector::selectedPostgresSrId() { - return getSelectedExpression( "srid" ).toLong(); + return getSelectedExpression( QStringLiteral( "srid" ) ).toLong(); } QString QgsProjectionSelector::selectedAuthId() { - int srid = getSelectedExpression( "srs_id" ).toLong(); + int srid = getSelectedExpression( QStringLiteral( "srs_id" ) ).toLong(); if ( srid >= USER_CRS_START_ID ) - return QString( "USER:%1" ).arg( srid ); + return QStringLiteral( "USER:%1" ).arg( srid ); else - return getSelectedExpression( "upper(auth_name||':'||auth_id)" ); + return getSelectedExpression( QStringLiteral( "upper(auth_name||':'||auth_id)" ) ); } long QgsProjectionSelector::selectedCrsId() @@ -474,7 +474,7 @@ void QgsProjectionSelector::loadUserCrsList( QSet<QString> *crsFilter ) fontTemp.setItalic( true ); fontTemp.setBold( true ); mUserProjList->setFont( 0, fontTemp ); - mUserProjList->setIcon( 0, QgsApplication::getThemeIcon( "/user.png" ) ); + mUserProjList->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/user.png" ) ) ); //determine where the user proj database lives for this user. If none is found an empty //now only will be shown @@ -506,7 +506,7 @@ void QgsProjectionSelector::loadUserCrsList( QSet<QString> *crsFilter ) } // Set up the query to retrieve the projection information needed to populate the list - QString sql = QString( "select description, srs_id from vw_srs where %1" ).arg( sqlFilter ); + QString sql = QStringLiteral( "select description, srs_id from vw_srs where %1" ).arg( sqlFilter ); result = sqlite3_prepare( database, sql.toUtf8(), sql.toUtf8().length(), &stmt, &tail ); // XXX Need to free memory from the error msg if one is set @@ -522,7 +522,7 @@ void QgsProjectionSelector::loadUserCrsList( QSet<QString> *crsFilter ) // newItem->setText( EPSG_COLUMN, QString::fromUtf8(( char * )sqlite3_column_text( stmt, 2 ) ) ); // display the qgis srs_id (field 1) in the third column of the list view newItem->setText( QGIS_CRS_ID_COLUMN, QString::fromUtf8(( char * )sqlite3_column_text( stmt, 1 ) ) ); - newItem->setText( AUTHID_COLUMN, QString( "USER:%1" ).arg( QString::fromUtf8(( char * )sqlite3_column_text( stmt, 1 ) ).toInt() ) ); + newItem->setText( AUTHID_COLUMN, QStringLiteral( "USER:%1" ).arg( QString::fromUtf8(( char * )sqlite3_column_text( stmt, 1 ) ).toInt() ) ); } } // close the sqlite3 statement @@ -550,7 +550,7 @@ void QgsProjectionSelector::loadCrsList( QSet<QString> *crsFilter ) fontTemp.setItalic( true ); fontTemp.setBold( true ); mGeoList->setFont( 0, fontTemp ); - mGeoList->setIcon( 0, QgsApplication::getThemeIcon( "/geographic.png" ) ); + mGeoList->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/geographic.png" ) ) ); // Projected coordinate system node mProjList = new QTreeWidgetItem( lstCoordinateSystems, QStringList( tr( "Projected Coordinate Systems" ) ) ); @@ -559,7 +559,7 @@ void QgsProjectionSelector::loadCrsList( QSet<QString> *crsFilter ) fontTemp.setItalic( true ); fontTemp.setBold( true ); mProjList->setFont( 0, fontTemp ); - mProjList->setIcon( 0, QgsApplication::getThemeIcon( "/transformed.svg" ) ); + mProjList->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/transformed.svg" ) ) ); //bail out in case the projections db does not exist //this is necessary in case the pc is running linux with a @@ -588,7 +588,7 @@ void QgsProjectionSelector::loadCrsList( QSet<QString> *crsFilter ) // Set up the query to retrieve the projection information needed to populate the list //note I am giving the full field names for clarity here and in case someone //changes the underlying view TS - QString sql = QString( "select description, srs_id, upper(auth_name||':'||auth_id), is_geo, name, parameters, deprecated from vw_srs where %1 order by name,description" ) + QString sql = QStringLiteral( "select description, srs_id, upper(auth_name||':'||auth_id), is_geo, name, parameters, deprecated from vw_srs where %1 order by name,description" ) .arg( sqlFilter ); rc = sqlite3_prepare( database, sql.toUtf8(), sql.toUtf8().length(), &stmt, &tail ); @@ -598,7 +598,7 @@ void QgsProjectionSelector::loadCrsList( QSet<QString> *crsFilter ) QTreeWidgetItem *newItem; // Cache some stuff to speed up creating of the list of projected // spatial reference systems - QString previousSrsType( "" ); + QString previousSrsType( QLatin1String( "" ) ); QTreeWidgetItem* previousSrsTypeNode = nullptr; while ( sqlite3_step( stmt ) == SQLITE_ROW ) @@ -713,8 +713,8 @@ void QgsProjectionSelector::on_lstCoordinateSystems_currentItemChanged( QTreeWid { // Not an CRS - remove the highlight so the user doesn't get too confused current->setSelected( false ); - teProjection->setText( "" ); - teSelected->setText( "" ); + teProjection->setText( QLatin1String( "" ) ); + teSelected->setText( QLatin1String( "" ) ); lstRecent->clearSelection(); } } @@ -779,8 +779,8 @@ void QgsProjectionSelector::hideDeprecated( QTreeWidgetItem *item ) if ( item->isSelected() && item->isHidden() ) { item->setSelected( false ); - teProjection->setText( "" ); - teSelected->setText( "" ); + teProjection->setText( QLatin1String( "" ) ); + teSelected->setText( QLatin1String( "" ) ); } } @@ -797,7 +797,7 @@ void QgsProjectionSelector::on_cbxHideDeprecated_stateChanged() void QgsProjectionSelector::on_leSearch_textChanged( const QString & theFilterTxt ) { QString filterTxt = theFilterTxt; - filterTxt.replace( QRegExp( "\\s+" ), ".*" ); + filterTxt.replace( QRegExp( "\\s+" ), QStringLiteral( ".*" ) ); QRegExp re( filterTxt, Qt::CaseInsensitive ); // filter recent crs's @@ -954,7 +954,7 @@ QStringList QgsProjectionSelector::authorities() return QStringList(); } - QString theSql = "select distinct auth_name from tbl_srs"; + QString theSql = QStringLiteral( "select distinct auth_name from tbl_srs" ); result = sqlite3_prepare( database, theSql.toUtf8(), theSql.toUtf8().length(), &stmt, &tail ); QStringList authorities; @@ -986,10 +986,10 @@ QStringList QgsProjectionSelector::authorities() const QString QgsProjectionSelector::sqlSafeString( const QString& theSQL ) { QString retval = theSQL; - retval.replace( '\\', "\\\\" ); - retval.replace( '\"', "\\\"" ); - retval.replace( '\'', "\\'" ); - retval.replace( '%', "\\%" ); + retval.replace( '\\', QLatin1String( "\\\\" ) ); + retval.replace( '\"', QLatin1String( "\\\"" ) ); + retval.replace( '\'', QLatin1String( "\\'" ) ); + retval.replace( '%', QLatin1String( "\\%" ) ); return retval; } diff --git a/src/gui/qgsquerybuilder.cpp b/src/gui/qgsquerybuilder.cpp index b211face3510..384b4a3c2cdd 100644 --- a/src/gui/qgsquerybuilder.cpp +++ b/src/gui/qgsquerybuilder.cpp @@ -33,7 +33,7 @@ QgsQueryBuilder::QgsQueryBuilder( QgsVectorLayer *layer, setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/QueryBuilder/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QueryBuilder/geometry" ) ).toByteArray() ); QPushButton *pbn = new QPushButton( tr( "&Test" ) ); buttonBox->addButton( pbn, QDialogButtonBox::ActionRole ); @@ -58,7 +58,7 @@ QgsQueryBuilder::QgsQueryBuilder( QgsVectorLayer *layer, QgsQueryBuilder::~QgsQueryBuilder() { QSettings settings; - settings.setValue( "/Windows/QueryBuilder/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QueryBuilder/geometry" ), saveGeometry() ); } void QgsQueryBuilder::showEvent( QShowEvent *event ) @@ -120,7 +120,7 @@ void QgsQueryBuilder::fillValues( int idx, int limit ) mLayer->uniqueValues( idx, values, limit ); QSettings settings; - QString nullValue = settings.value( "qgis/nullValue", "NULL" ).toString(); + QString nullValue = settings.value( QStringLiteral( "qgis/nullValue" ), "NULL" ).toString(); QgsDebugMsg( QString( "nullValue: %1" ).arg( nullValue ) ); @@ -129,8 +129,8 @@ void QgsQueryBuilder::fillValues( int idx, int limit ) QString value; if ( values[i].isNull() ) value = nullValue; - else if ( values[i].type() == QVariant::Date && mLayer->providerType() == "ogr" && mLayer->storageType() == "ESRI Shapefile" ) - value = values[i].toDate().toString( "yyyy/MM/dd" ); + else if ( values[i].type() == QVariant::Date && mLayer->providerType() == QLatin1String( "ogr" ) && mLayer->storageType() == QLatin1String( "ESRI Shapefile" ) ) + value = values[i].toDate().toString( QStringLiteral( "yyyy/MM/dd" ) ); else value = values[i].toString(); @@ -149,7 +149,7 @@ void QgsQueryBuilder::on_btnSampleValues_clicked() QString prevSubsetString = mLayer->subsetString(); if ( mUseUnfilteredLayer->isChecked() && !prevSubsetString.isEmpty() ) { - mLayer->setSubsetString( "" ); + mLayer->setSubsetString( QLatin1String( "" ) ); } //delete connection mModelValues and lstValues @@ -176,7 +176,7 @@ void QgsQueryBuilder::on_btnGetAllValues_clicked() QString prevSubsetString = mLayer->subsetString(); if ( mUseUnfilteredLayer->isChecked() && !prevSubsetString.isEmpty() ) { - mLayer->setSubsetString( "" ); + mLayer->setSubsetString( QLatin1String( "" ) ); } //delete connection mModelValues and lstValues @@ -215,7 +215,7 @@ void QgsQueryBuilder::test() QMessageBox::warning( this, tr( "Query Failed" ), tr( "An error occurred when executing the query." ) - + tr( "\nThe data provider said:\n%1" ).arg( mLayer->dataProvider()->errors().join( "\n" ) ) ); + + tr( "\nThe data provider said:\n%1" ).arg( mLayer->dataProvider()->errors().join( QStringLiteral( "\n" ) ) ) ); mLayer->dataProvider()->clearErrors(); } else @@ -236,7 +236,7 @@ void QgsQueryBuilder::accept() QMessageBox::warning( this, tr( "Query Failed" ), tr( "An error occurred when executing the query." ) - + tr( "\nThe data provider said:\n%1" ).arg( mLayer->dataProvider()->errors().join( "\n" ) ) ); + + tr( "\nThe data provider said:\n%1" ).arg( mLayer->dataProvider()->errors().join( QStringLiteral( "\n" ) ) ) ); mLayer->dataProvider()->clearErrors(); } else @@ -260,43 +260,43 @@ void QgsQueryBuilder::reject() void QgsQueryBuilder::on_btnEqual_clicked() { - txtSQL->insertText( " = " ); + txtSQL->insertText( QStringLiteral( " = " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnLessThan_clicked() { - txtSQL->insertText( " < " ); + txtSQL->insertText( QStringLiteral( " < " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnGreaterThan_clicked() { - txtSQL->insertText( " > " ); + txtSQL->insertText( QStringLiteral( " > " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnPct_clicked() { - txtSQL->insertText( "%" ); + txtSQL->insertText( QStringLiteral( "%" ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnIn_clicked() { - txtSQL->insertText( " IN " ); + txtSQL->insertText( QStringLiteral( " IN " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnNotIn_clicked() { - txtSQL->insertText( " NOT IN " ); + txtSQL->insertText( QStringLiteral( " NOT IN " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnLike_clicked() { - txtSQL->insertText( " LIKE " ); + txtSQL->insertText( QStringLiteral( " LIKE " ) ); txtSQL->setFocus(); } @@ -333,63 +333,63 @@ void QgsQueryBuilder::on_lstValues_doubleClicked( const QModelIndex &index ) { QVariant value = mModelValues->data( index, Qt::UserRole + 1 ); if ( value.isNull() ) - txtSQL->insertText( "NULL" ); - else if ( value.type() == QVariant::Date && mLayer->providerType() == "ogr" && mLayer->storageType() == "ESRI Shapefile" ) - txtSQL->insertText( '\'' + value.toDate().toString( "yyyy/MM/dd" ) + '\'' ); + txtSQL->insertText( QStringLiteral( "NULL" ) ); + else if ( value.type() == QVariant::Date && mLayer->providerType() == QLatin1String( "ogr" ) && mLayer->storageType() == QLatin1String( "ESRI Shapefile" ) ) + txtSQL->insertText( '\'' + value.toDate().toString( QStringLiteral( "yyyy/MM/dd" ) ) + '\'' ); else if ( value.type() == QVariant::Int || value.type() == QVariant::Double || value.type() == QVariant::LongLong ) txtSQL->insertText( value.toString() ); else - txtSQL->insertText( '\'' + value.toString().replace( '\'', "''" ) + '\'' ); + txtSQL->insertText( '\'' + value.toString().replace( '\'', QLatin1String( "''" ) ) + '\'' ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnLessEqual_clicked() { - txtSQL->insertText( " <= " ); + txtSQL->insertText( QStringLiteral( " <= " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnGreaterEqual_clicked() { - txtSQL->insertText( " >= " ); + txtSQL->insertText( QStringLiteral( " >= " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnNotEqual_clicked() { - txtSQL->insertText( " != " ); + txtSQL->insertText( QStringLiteral( " != " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnAnd_clicked() { - txtSQL->insertText( " AND " ); + txtSQL->insertText( QStringLiteral( " AND " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnNot_clicked() { - txtSQL->insertText( " NOT " ); + txtSQL->insertText( QStringLiteral( " NOT " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::on_btnOr_clicked() { - txtSQL->insertText( " OR " ); + txtSQL->insertText( QStringLiteral( " OR " ) ); txtSQL->setFocus(); } void QgsQueryBuilder::clear() { txtSQL->clear(); - mLayer->setSubsetString( "" ); + mLayer->setSubsetString( QLatin1String( "" ) ); mUseUnfilteredLayer->setDisabled( true ); } void QgsQueryBuilder::on_btnILike_clicked() { - txtSQL->insertText( " ILIKE " ); + txtSQL->insertText( QStringLiteral( " ILIKE " ) ); txtSQL->setFocus(); } diff --git a/src/gui/qgsrasterformatsaveoptionswidget.cpp b/src/gui/qgsrasterformatsaveoptionswidget.cpp index 45f5100a5e7e..837718ac336f 100644 --- a/src/gui/qgsrasterformatsaveoptionswidget.cpp +++ b/src/gui/qgsrasterformatsaveoptionswidget.cpp @@ -32,8 +32,8 @@ QMap< QString, QStringList > QgsRasterFormatSaveOptionsWidget::mBuiltinProfiles; -static const QString PYRAMID_JPEG_YCBCR_COMPRESSION( "JPEG_QUALITY_OVERVIEW=75 COMPRESS_OVERVIEW=JPEG PHOTOMETRIC_OVERVIEW=YCBCR INTERLEAVE_OVERVIEW=PIXEL" ); -static const QString PYRAMID_JPEG_COMPRESSION( "JPEG_QUALITY_OVERVIEW=75 COMPRESS_OVERVIEW=JPEG INTERLEAVE_OVERVIEW=PIXEL" ); +static const QString PYRAMID_JPEG_YCBCR_COMPRESSION( QStringLiteral( "JPEG_QUALITY_OVERVIEW=75 COMPRESS_OVERVIEW=JPEG PHOTOMETRIC_OVERVIEW=YCBCR INTERLEAVE_OVERVIEW=PIXEL" ) ); +static const QString PYRAMID_JPEG_COMPRESSION( QStringLiteral( "JPEG_QUALITY_OVERVIEW=75 COMPRESS_OVERVIEW=JPEG INTERLEAVE_OVERVIEW=PIXEL" ) ); QgsRasterFormatSaveOptionsWidget::QgsRasterFormatSaveOptionsWidget( QWidget* parent, const QString& format, QgsRasterFormatSaveOptionsWidget::Type type, const QString& provider ) @@ -53,38 +53,38 @@ QgsRasterFormatSaveOptionsWidget::QgsRasterFormatSaveOptionsWidget( QWidget* par if ( mBuiltinProfiles.isEmpty() ) { // key=profileKey values=format,profileName,options - mBuiltinProfiles[ "z_adefault" ] = ( QStringList() << "" << tr( "Default" ) << "" ); + mBuiltinProfiles[ QStringLiteral( "z_adefault" )] = ( QStringList() << QLatin1String( "" ) << tr( "Default" ) << QLatin1String( "" ) ); // these GTiff profiles are based on Tim's benchmarks at // http://linfiniti.com/2011/05/gdal-efficiency-of-various-compression-algorithms/ // big: no compression | medium: reasonable size/speed tradeoff | small: smallest size - mBuiltinProfiles[ "z_gtiff_1big" ] = - ( QStringList() << "GTiff" << tr( "No compression" ) - << "COMPRESS=NONE BIGTIFF=IF_NEEDED" ); - mBuiltinProfiles[ "z_gtiff_2medium" ] = - ( QStringList() << "GTiff" << tr( "Low compression" ) - << "COMPRESS=PACKBITS" ); - mBuiltinProfiles[ "z_gtiff_3small" ] = - ( QStringList() << "GTiff" << tr( "High compression" ) - << "COMPRESS=DEFLATE PREDICTOR=2 ZLEVEL=9" ); - mBuiltinProfiles[ "z_gtiff_4jpeg" ] = - ( QStringList() << "GTiff" << tr( "JPEG compression" ) - << "COMPRESS=JPEG JPEG_QUALITY=75" ); + mBuiltinProfiles[ QStringLiteral( "z_gtiff_1big" )] = + ( QStringList() << QStringLiteral( "GTiff" ) << tr( "No compression" ) + << QStringLiteral( "COMPRESS=NONE BIGTIFF=IF_NEEDED" ) ); + mBuiltinProfiles[ QStringLiteral( "z_gtiff_2medium" )] = + ( QStringList() << QStringLiteral( "GTiff" ) << tr( "Low compression" ) + << QStringLiteral( "COMPRESS=PACKBITS" ) ); + mBuiltinProfiles[ QStringLiteral( "z_gtiff_3small" )] = + ( QStringList() << QStringLiteral( "GTiff" ) << tr( "High compression" ) + << QStringLiteral( "COMPRESS=DEFLATE PREDICTOR=2 ZLEVEL=9" ) ); + mBuiltinProfiles[ QStringLiteral( "z_gtiff_4jpeg" )] = + ( QStringList() << QStringLiteral( "GTiff" ) << tr( "JPEG compression" ) + << QStringLiteral( "COMPRESS=JPEG JPEG_QUALITY=75" ) ); // overview compression schemes for GTiff format, see // http://www.gdal.org/gdaladdo.html and http://www.gdal.org/frmt_gtiff.html // TODO - should we offer GDAL_TIFF_OVR_BLOCKSIZE option here or in QgsRasterPyramidsOptionsWidget ? - mBuiltinProfiles[ "z__pyramids_gtiff_1big" ] = - ( QStringList() << "_pyramids" << tr( "No compression" ) - << "COMPRESS_OVERVIEW=NONE BIGTIFF_OVERVIEW=IF_NEEDED" ); - mBuiltinProfiles[ "z__pyramids_gtiff_2medium" ] = - ( QStringList() << "_pyramids" << tr( "Low compression" ) - << "COMPRESS_OVERVIEW=PACKBITS" ); - mBuiltinProfiles[ "z__pyramids_gtiff_3small" ] = - ( QStringList() << "_pyramids" << tr( "High compression" ) - << "COMPRESS_OVERVIEW=DEFLATE PREDICTOR_OVERVIEW=2 ZLEVEL=9" ); // how to set zlevel? - mBuiltinProfiles[ "z__pyramids_gtiff_4jpeg" ] = - ( QStringList() << "_pyramids" << tr( "JPEG compression" ) + mBuiltinProfiles[ QStringLiteral( "z__pyramids_gtiff_1big" )] = + ( QStringList() << QStringLiteral( "_pyramids" ) << tr( "No compression" ) + << QStringLiteral( "COMPRESS_OVERVIEW=NONE BIGTIFF_OVERVIEW=IF_NEEDED" ) ); + mBuiltinProfiles[ QStringLiteral( "z__pyramids_gtiff_2medium" )] = + ( QStringList() << QStringLiteral( "_pyramids" ) << tr( "Low compression" ) + << QStringLiteral( "COMPRESS_OVERVIEW=PACKBITS" ) ); + mBuiltinProfiles[ QStringLiteral( "z__pyramids_gtiff_3small" )] = + ( QStringList() << QStringLiteral( "_pyramids" ) << tr( "High compression" ) + << QStringLiteral( "COMPRESS_OVERVIEW=DEFLATE PREDICTOR_OVERVIEW=2 ZLEVEL=9" ) ); // how to set zlevel? + mBuiltinProfiles[ QStringLiteral( "z__pyramids_gtiff_4jpeg" )] = + ( QStringList() << QStringLiteral( "_pyramids" ) << tr( "JPEG compression" ) << PYRAMID_JPEG_YCBCR_COMPRESSION ); } @@ -157,7 +157,7 @@ void QgsRasterFormatSaveOptionsWidget::setType( QgsRasterFormatSaveOptionsWidget QString QgsRasterFormatSaveOptionsWidget::pseudoFormat() const { - return mPyramids ? "_pyramids" : mFormat; + return mPyramids ? QStringLiteral( "_pyramids" ) : mFormat; } void QgsRasterFormatSaveOptionsWidget::updateProfiles() @@ -173,7 +173,7 @@ void QgsRasterFormatSaveOptionsWidget::updateProfiles() if ( ! profileKeys.contains( profileKey ) && !it.value().isEmpty() ) { // insert key if is for all formats or this format (GTiff) - if ( it.value()[0] == "" || it.value()[0] == format ) + if ( it.value()[0] == QLatin1String( "" ) || it.value()[0] == format ) { profileKeys.insert( 0, profileKey ); } @@ -262,7 +262,7 @@ void QgsRasterFormatSaveOptionsWidget::helpOptions() { QString message; - if ( mProvider == "gdal" && mFormat != "" && ! mPyramids ) + if ( mProvider == QLatin1String( "gdal" ) && mFormat != QLatin1String( "" ) && ! mPyramids ) { // get helpCreationOptionsFormat() function ptr for provider QLibrary *library = QgsProviderRegistry::instance()->providerLibrary( mProvider ); @@ -280,16 +280,16 @@ void QgsRasterFormatSaveOptionsWidget::helpOptions() } } else - message = QString( "cannot load provider library %1" ).arg( mProvider ); + message = QStringLiteral( "cannot load provider library %1" ).arg( mProvider ); if ( message.isEmpty() ) message = tr( "Cannot get create options for driver %1" ).arg( mFormat ); } - else if ( mProvider == "gdal" && mPyramids ) + else if ( mProvider == QLatin1String( "gdal" ) && mPyramids ) { message = tr( "For details on pyramids options please see the following pages" ); - message += "\n\nhttp://www.gdal.org/gdaladdo.html\n\nhttp://www.gdal.org/frmt_gtiff.html"; + message += QLatin1String( "\n\nhttp://www.gdal.org/gdaladdo.html\n\nhttp://www.gdal.org/frmt_gtiff.html" ); } else message = tr( "No help available" ); @@ -325,21 +325,21 @@ QString QgsRasterFormatSaveOptionsWidget::validateOptions( bool gui, bool report // this is taken from qgsbrowserdockwidget.cpp // TODO - integrate this into qgis core QSettings settings; - QString defaultProjectionOption = settings.value( "/Projections/defaultBehaviour", "prompt" ).toString(); - if ( settings.value( "/Projections/defaultBehaviour", "prompt" ).toString() == "prompt" ) + QString defaultProjectionOption = settings.value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString(); + if ( settings.value( QStringLiteral( "/Projections/defaultBehaviour" ), "prompt" ).toString() == QLatin1String( "prompt" ) ) { - settings.setValue( "/Projections/defaultBehaviour", "useProject" ); + settings.setValue( QStringLiteral( "/Projections/defaultBehaviour" ), "useProject" ); } tmpLayer = true; - rasterLayer = new QgsRasterLayer( mRasterFileName, QFileInfo( mRasterFileName ).baseName(), QString( "gdal" ) ); + rasterLayer = new QgsRasterLayer( mRasterFileName, QFileInfo( mRasterFileName ).baseName(), QStringLiteral( "gdal" ) ); // restore /Projections/defaultBehaviour - if ( defaultProjectionOption == "prompt" ) + if ( defaultProjectionOption == QLatin1String( "prompt" ) ) { - settings.setValue( "/Projections/defaultBehaviour", defaultProjectionOption ); + settings.setValue( QStringLiteral( "/Projections/defaultBehaviour" ), defaultProjectionOption ); } } - if ( mProvider == "gdal" && mPyramids ) + if ( mProvider == QLatin1String( "gdal" ) && mPyramids ) { if ( rasterLayer && rasterLayer->dataProvider() ) { @@ -351,7 +351,7 @@ QString QgsRasterFormatSaveOptionsWidget::validateOptions( bool gui, bool report message = tr( "cannot validate pyramid options" ); } } - else if ( !createOptions.isEmpty() && mProvider == "gdal" && mFormat != "" ) + else if ( !createOptions.isEmpty() && mProvider == QLatin1String( "gdal" ) && mFormat != QLatin1String( "" ) ) { if ( rasterLayer && rasterLayer->dataProvider() ) { @@ -376,12 +376,12 @@ QString QgsRasterFormatSaveOptionsWidget::validateOptions( bool gui, bool report } } else - message = QString( "cannot load provider library %1" ).arg( mProvider ); + message = QStringLiteral( "cannot load provider library %1" ).arg( mProvider ); } } else if ( ! createOptions.isEmpty() ) { - QMessageBox::information( this, "", tr( "Cannot validate creation options" ), QMessageBox::Close ); + QMessageBox::information( this, QLatin1String( "" ), tr( "Cannot validate creation options" ), QMessageBox::Close ); if ( tmpLayer ) delete rasterLayer; return QString(); @@ -392,11 +392,11 @@ QString QgsRasterFormatSaveOptionsWidget::validateOptions( bool gui, bool report if ( message.isNull() ) { if ( reportOK ) - QMessageBox::information( this, "", tr( "Valid" ), QMessageBox::Close ); + QMessageBox::information( this, QLatin1String( "" ), tr( "Valid" ), QMessageBox::Close ); } else { - QMessageBox::warning( this, "", tr( "Invalid %1:\n\n%2\n\nClick on help button to get valid creation options for this format." ).arg( mPyramids ? tr( "pyramid creation option" ) : tr( "creation option" ), message ), QMessageBox::Close ); + QMessageBox::warning( this, QLatin1String( "" ), tr( "Invalid %1:\n\n%2\n\nClick on help button to get valid creation options for this format." ).arg( mPyramids ? tr( "pyramid creation option" ) : tr( "creation option" ), message ), QMessageBox::Close ); } } @@ -433,11 +433,11 @@ void QgsRasterFormatSaveOptionsWidget::on_mOptionsLineEdit_editingFinished() void QgsRasterFormatSaveOptionsWidget::on_mProfileNewButton_clicked() { - QString profileName = QInputDialog::getText( this, "", tr( "Profile name:" ) ); + QString profileName = QInputDialog::getText( this, QLatin1String( "" ), tr( "Profile name:" ) ); if ( ! profileName.isEmpty() ) { profileName = profileName.trimmed(); - mOptionsMap[ profileName ] = ""; + mOptionsMap[ profileName ] = QLatin1String( "" ); mProfileComboBox->addItem( profileName, profileName ); mProfileComboBox->setCurrentIndex( mProfileComboBox->count() - 1 ); } @@ -463,7 +463,7 @@ void QgsRasterFormatSaveOptionsWidget::on_mProfileResetButton_clicked() } else { - mOptionsMap[ profileKey ] = ""; + mOptionsMap[ profileKey ] = QLatin1String( "" ); } mOptionsLineEdit->setText( mOptionsMap.value( currentProfileKey() ) ); mOptionsLineEdit->setCursorPosition( 0 ); @@ -500,7 +500,7 @@ void QgsRasterFormatSaveOptionsWidget::on_mOptionsDeleteButton_clicked() QString QgsRasterFormatSaveOptionsWidget::settingsKey( QString profileName ) const { - if ( profileName != "" ) + if ( profileName != QLatin1String( "" ) ) profileName = "/profile_" + profileName; else profileName = "/profile_default" + profileName; @@ -537,7 +537,7 @@ void QgsRasterFormatSaveOptionsWidget::setCreateOptions() while ( i != mOptionsMap.constEnd() ) { setCreateOptions( i.key(), i.value() ); - myProfiles += i.key() + QLatin1String( " " ); + myProfiles += i.key() + QStringLiteral( " " ); ++i; } mySettings.setValue( mProvider + "/driverOptions/" + pseudoFormat().toLower() + "/profiles", @@ -554,7 +554,7 @@ void QgsRasterFormatSaveOptionsWidget::setCreateOptions( const QString& profileN void QgsRasterFormatSaveOptionsWidget::setCreateOptions( const QString& profileName, const QStringList& list ) { - setCreateOptions( profileName, list.join( " " ) ); + setCreateOptions( profileName, list.join( QStringLiteral( " " ) ) ); } QStringList QgsRasterFormatSaveOptionsWidget::profiles() const @@ -590,7 +590,7 @@ void QgsRasterFormatSaveOptionsWidget::swapOptionsUI( int newIndex ) void QgsRasterFormatSaveOptionsWidget::updateControls() { - bool valid = mProvider == "gdal" && mFormat != ""; + bool valid = mProvider == QLatin1String( "gdal" ) && mFormat != QLatin1String( "" ); mOptionsValidateButton->setEnabled( valid ); mOptionsHelpButton->setEnabled( valid ); } @@ -609,7 +609,7 @@ bool QgsRasterFormatSaveOptionsWidget::eventFilter( QObject *obj, QEvent *event text = tr( "Use simple interface" ); else text = tr( "Use table interface" ); - if ( obj->objectName() == "mOptionsLineEdit" ) + if ( obj->objectName() == QLatin1String( "mOptionsLineEdit" ) ) { menu = mOptionsLineEdit->createStandardContextMenu(); menu->addSeparator(); diff --git a/src/gui/qgsrasterformatsaveoptionswidget.h b/src/gui/qgsrasterformatsaveoptionswidget.h index a86a903b5914..83a21b9ee89e 100644 --- a/src/gui/qgsrasterformatsaveoptionswidget.h +++ b/src/gui/qgsrasterformatsaveoptionswidget.h @@ -42,9 +42,12 @@ class GUI_EXPORT QgsRasterFormatSaveOptionsWidget: public QWidget, ProfileLineEdit // Profile + LineEdit }; - QgsRasterFormatSaveOptionsWidget( QWidget* parent = nullptr, const QString& format = "GTiff", + /** + * Constructor for QgsRasterFormatSaveOptionsWidget. + */ + QgsRasterFormatSaveOptionsWidget( QWidget* parent = nullptr, const QString& format = QStringLiteral( "GTiff" ), QgsRasterFormatSaveOptionsWidget::Type type = Default, - const QString& provider = "gdal" ); + const QString& provider = QStringLiteral( "gdal" ) ); ~QgsRasterFormatSaveOptionsWidget(); void setFormat( const QString& format ); diff --git a/src/gui/qgsrasterlayersaveasdialog.cpp b/src/gui/qgsrasterlayersaveasdialog.cpp index 82d22c121f7b..6d3ebb4d450f 100644 --- a/src/gui/qgsrasterlayersaveasdialog.cpp +++ b/src/gui/qgsrasterlayersaveasdialog.cpp @@ -42,10 +42,10 @@ QgsRasterLayerSaveAsDialog::QgsRasterLayerSaveAsDialog( QgsRasterLayer* rasterLa , mResolutionState( OriginalResolution ) { setupUi( this ); - mAddNoDataManuallyToolButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewAttribute.svg" ) ); - mLoadTransparentNoDataToolButton->setIcon( QgsApplication::getThemeIcon( "/mActionCopySelected.png" ) ); - mRemoveSelectedNoDataToolButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteAttribute.svg" ) ); - mRemoveAllNoDataToolButton->setIcon( QgsApplication::getThemeIcon( "/mActionRemove.svg" ) ); + mAddNoDataManuallyToolButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) ); + mLoadTransparentNoDataToolButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCopySelected.png" ) ) ); + mRemoveSelectedNoDataToolButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) ); + mRemoveAllNoDataToolButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRemove.svg" ) ) ); mNoDataTableWidget->setColumnCount( 2 ); mNoDataTableWidget->setHorizontalHeaderItem( 0, new QTableWidgetItem( tr( "From" ) ) ); @@ -59,7 +59,7 @@ QgsRasterLayerSaveAsDialog::QgsRasterLayerSaveAsDialog( QgsRasterLayer* rasterLa //only one hardcoded format at the moment QStringList myFormats; - myFormats << "GTiff"; + myFormats << QStringLiteral( "GTiff" ); Q_FOREACH ( const QString& myFormat, myFormats ) { mFormatComboBox->addItem( myFormat ); @@ -85,7 +85,7 @@ QgsRasterLayerSaveAsDialog::QgsRasterLayerSaveAsDialog( QgsRasterLayer* rasterLa // setup creation option widget mCreateOptionsWidget->setProvider( mDataProvider->name() ); - if ( mDataProvider->name() == "gdal" ) + if ( mDataProvider->name() == QLatin1String( "gdal" ) ) { mCreateOptionsWidget->setFormat( myFormats[0] ); } @@ -165,7 +165,7 @@ void QgsRasterLayerSaveAsDialog::on_mBrowseButton_clicked() QString fileName; QSettings settings; - QString dirName = mSaveAsLineEdit->text().isEmpty() ? settings.value( "/UI/lastRasterFileDir", QDir::homePath() ).toString() : mSaveAsLineEdit->text(); + QString dirName = mSaveAsLineEdit->text().isEmpty() ? settings.value( QStringLiteral( "/UI/lastRasterFileDir" ), QDir::homePath() ).toString() : mSaveAsLineEdit->text(); if ( mTileModeCheckBox->isChecked() ) { @@ -182,17 +182,17 @@ void QgsRasterLayerSaveAsDialog::on_mBrowseButton_clicked() QDir dir( fileName ); QString baseName = QFileInfo( fileName ).baseName(); QStringList filters; - filters << QString( "%1.*" ).arg( baseName ); + filters << QStringLiteral( "%1.*" ).arg( baseName ); QStringList files = dir.entryList( filters ); if ( files.isEmpty() ) break; if ( QMessageBox::warning( this, tr( "Warning" ), - tr( "The directory %1 contains files which will be overwritten: %2" ).arg( dir.absolutePath(), files.join( ", " ) ), + tr( "The directory %1 contains files which will be overwritten: %2" ).arg( dir.absolutePath(), files.join( QStringLiteral( ", " ) ) ), QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Ok ) break; - fileName = ""; + fileName = QLatin1String( "" ); } } else @@ -200,9 +200,9 @@ void QgsRasterLayerSaveAsDialog::on_mBrowseButton_clicked() fileName = QFileDialog::getSaveFileName( this, tr( "Select output file" ), dirName, tr( "GeoTIFF" ) + " (*.tif *.tiff *.TIF *.TIFF)" ); // ensure the user never omits the extension from the file name - if ( !fileName.isEmpty() && !fileName.endsWith( ".tif", Qt::CaseInsensitive ) && !fileName.endsWith( ".tiff", Qt::CaseInsensitive ) ) + if ( !fileName.isEmpty() && !fileName.endsWith( QLatin1String( ".tif" ), Qt::CaseInsensitive ) && !fileName.endsWith( QLatin1String( ".tiff" ), Qt::CaseInsensitive ) ) { - fileName += ".tif"; + fileName += QLatin1String( ".tif" ); } } @@ -227,7 +227,7 @@ void QgsRasterLayerSaveAsDialog::on_mSaveAsLineEdit_textChanged( const QString& void QgsRasterLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( const QString & text ) { //gdal-specific - if ( mDataProvider && mDataProvider->name() == "gdal" ) + if ( mDataProvider && mDataProvider->name() == QLatin1String( "gdal" ) ) { mCreateOptionsWidget->setFormat( text ); mCreateOptionsWidget->update(); @@ -670,7 +670,7 @@ void QgsRasterLayerSaveAsDialog::populatePyramidsLevels() { if ( ! mPyramidsUseExistingCheckBox->isChecked() || myRasterPyramidIterator->exists ) { - text += QString::number( myRasterPyramidIterator->xDim ) + QLatin1String( "x" ) + + text += QString::number( myRasterPyramidIterator->xDim ) + QStringLiteral( "x" ) + QString::number( myRasterPyramidIterator->yDim ) + ' '; } } diff --git a/src/gui/qgsrasterpyramidsoptionswidget.cpp b/src/gui/qgsrasterpyramidsoptionswidget.cpp index 89156a21c3fc..8415e3db3c4d 100644 --- a/src/gui/qgsrasterpyramidsoptionswidget.cpp +++ b/src/gui/qgsrasterpyramidsoptionswidget.cpp @@ -54,9 +54,9 @@ void QgsRasterPyramidsOptionsWidget::updateUi() // keep it in sync with qgsrasterlayerproperties.cpp tmpStr = mySettings.value( prefix + "format", "external" ).toString(); - if ( tmpStr == "internal" ) + if ( tmpStr == QLatin1String( "internal" ) ) cbxPyramidsFormat->setCurrentIndex( INTERNAL ); - else if ( tmpStr == "external_erdas" ) + else if ( tmpStr == QLatin1String( "external_erdas" ) ) cbxPyramidsFormat->setCurrentIndex( ERDAS ); else cbxPyramidsFormat->setCurrentIndex( GTIFF ); @@ -128,17 +128,17 @@ void QgsRasterPyramidsOptionsWidget::apply() // mySettings.setValue( prefix + "internal", cbxPyramidsInternal->isChecked() ); if ( cbxPyramidsFormat->currentIndex() == INTERNAL ) - tmpStr = "internal"; + tmpStr = QStringLiteral( "internal" ); else if ( cbxPyramidsFormat->currentIndex() == ERDAS ) - tmpStr = "external_erdas"; + tmpStr = QStringLiteral( "external_erdas" ); else - tmpStr = "external"; + tmpStr = QStringLiteral( "external" ); mySettings.setValue( prefix + "format", tmpStr ); mySettings.setValue( prefix + "resampling", resamplingMethod() ); mySettings.setValue( prefix + "overviewStr", lePyramidsLevels->text().trimmed() ); // overview list - tmpStr = ""; + tmpStr = QLatin1String( "" ); Q_FOREACH ( int i, mOverviewCheckBoxes.keys() ) { if ( mOverviewCheckBoxes[ i ]->isChecked() ) diff --git a/src/gui/qgsrasterpyramidsoptionswidget.h b/src/gui/qgsrasterpyramidsoptionswidget.h index c35a7a98f87b..7975cbd47761 100644 --- a/src/gui/qgsrasterpyramidsoptionswidget.h +++ b/src/gui/qgsrasterpyramidsoptionswidget.h @@ -32,7 +32,11 @@ class GUI_EXPORT QgsRasterPyramidsOptionsWidget: public QWidget, public: - QgsRasterPyramidsOptionsWidget( QWidget* parent = nullptr, const QString& provider = "gdal" ); + /** + * Constructor for QgsRasterPyramidsOptionsWidget. + */ + QgsRasterPyramidsOptionsWidget( QWidget* parent = nullptr, const QString& provider = QStringLiteral( "gdal" ) ); + ~QgsRasterPyramidsOptionsWidget(); QStringList configOptions() const { return mSaveOptionsWidget->options(); } diff --git a/src/gui/qgsrelationeditorwidget.cpp b/src/gui/qgsrelationeditorwidget.cpp index 6b7372748367..ad9e52a3112b 100644 --- a/src/gui/qgsrelationeditorwidget.cpp +++ b/src/gui/qgsrelationeditorwidget.cpp @@ -47,8 +47,8 @@ QgsRelationEditorWidget::QgsRelationEditorWidget( QWidget* parent ) buttonLayout->setContentsMargins( 0, 0, 0, 0 ); // toogle editing mToggleEditingButton = new QToolButton( this ); - mToggleEditingButton->setObjectName( "mToggleEditingButton" ); - mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( "/mActionToggleEditing.svg" ) ); + mToggleEditingButton->setObjectName( QStringLiteral( "mToggleEditingButton" ) ); + mToggleEditingButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionToggleEditing.svg" ) ) ); mToggleEditingButton->setText( tr( "Toggle editing" ) ); mToggleEditingButton->setEnabled( false ); mToggleEditingButton->setCheckable( true ); @@ -56,38 +56,38 @@ QgsRelationEditorWidget::QgsRelationEditorWidget( QWidget* parent ) buttonLayout->addWidget( mToggleEditingButton ); // save Edits mSaveEditsButton = new QToolButton( this ); - mSaveEditsButton->setIcon( QgsApplication::getThemeIcon( "/mActionSaveEdits.svg" ) ); + mSaveEditsButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSaveEdits.svg" ) ) ); mSaveEditsButton->setText( tr( "Save child layer edits" ) ); mSaveEditsButton->setToolTip( tr( "Save child layer edits" ) ); mSaveEditsButton->setEnabled( true ); buttonLayout->addWidget( mSaveEditsButton ); // add feature mAddFeatureButton = new QToolButton( this ); - mAddFeatureButton->setIcon( QgsApplication::getThemeIcon( "/mActionNewTableRow.svg" ) ); + mAddFeatureButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewTableRow.svg" ) ) ); mAddFeatureButton->setText( tr( "Add child feature" ) ); mAddFeatureButton->setToolTip( tr( "Add child feature" ) ); - mAddFeatureButton->setObjectName( "mAddFeatureButton" ); + mAddFeatureButton->setObjectName( QStringLiteral( "mAddFeatureButton" ) ); buttonLayout->addWidget( mAddFeatureButton ); // delete feature mDeleteFeatureButton = new QToolButton( this ); - mDeleteFeatureButton->setIcon( QgsApplication::getThemeIcon( "/mActionDeleteSelected.svg" ) ); + mDeleteFeatureButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteSelected.svg" ) ) ); mDeleteFeatureButton->setText( tr( "Delete child feature" ) ); mDeleteFeatureButton->setToolTip( tr( "Delete child feature" ) ); - mDeleteFeatureButton->setObjectName( "mDeleteFeatureButton" ); + mDeleteFeatureButton->setObjectName( QStringLiteral( "mDeleteFeatureButton" ) ); buttonLayout->addWidget( mDeleteFeatureButton ); // link feature mLinkFeatureButton = new QToolButton( this ); - mLinkFeatureButton->setIcon( QgsApplication::getThemeIcon( "/mActionLink.svg" ) ); + mLinkFeatureButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionLink.svg" ) ) ); mLinkFeatureButton->setText( tr( "Link existing features" ) ); mLinkFeatureButton->setToolTip( tr( "Link existing child features" ) ); - mLinkFeatureButton->setObjectName( "mLinkFeatureButton" ); + mLinkFeatureButton->setObjectName( QStringLiteral( "mLinkFeatureButton" ) ); buttonLayout->addWidget( mLinkFeatureButton ); // unlink feature mUnlinkFeatureButton = new QToolButton( this ); - mUnlinkFeatureButton->setIcon( QgsApplication::getThemeIcon( "/mActionUnlink.svg" ) ); + mUnlinkFeatureButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionUnlink.svg" ) ) ); mUnlinkFeatureButton->setText( tr( "Unlink feature" ) ); mUnlinkFeatureButton->setToolTip( tr( "Unlink child feature" ) ); - mUnlinkFeatureButton->setObjectName( "mUnlinkFeatureButton" ); + mUnlinkFeatureButton->setObjectName( QStringLiteral( "mUnlinkFeatureButton" ) ); buttonLayout->addWidget( mUnlinkFeatureButton ); // spacer buttonLayout->addItem( new QSpacerItem( 0, 0, QSizePolicy::Expanding ) ); @@ -95,7 +95,7 @@ QgsRelationEditorWidget::QgsRelationEditorWidget( QWidget* parent ) mFormViewButton = new QToolButton( this ); mFormViewButton->setText( tr( "Form view" ) ); mFormViewButton->setToolTip( tr( "Switch to form view" ) ); - mFormViewButton->setIcon( QgsApplication::getThemeIcon( "/mActionPropertyItem.svg" ) ); + mFormViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionPropertyItem.svg" ) ) ); mFormViewButton->setCheckable( true ); mFormViewButton->setChecked( mViewMode == QgsDualView::AttributeEditor ); buttonLayout->addWidget( mFormViewButton ); @@ -103,7 +103,7 @@ QgsRelationEditorWidget::QgsRelationEditorWidget( QWidget* parent ) mTableViewButton = new QToolButton( this ); mTableViewButton->setText( tr( "Table view" ) ); mTableViewButton->setToolTip( tr( "Switch to table view" ) ); - mTableViewButton->setIcon( QgsApplication::getThemeIcon( "/mActionOpenTable.svg" ) ); + mTableViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionOpenTable.svg" ) ) ); mTableViewButton->setCheckable( true ); mTableViewButton->setChecked( mViewMode == QgsDualView::AttributeTable ); buttonLayout->addWidget( mTableViewButton ); @@ -430,9 +430,9 @@ void QgsRelationEditorWidget::unlinkFeature() filters << '(' + mNmRelation.getRelatedFeaturesRequest( f ).filterExpression()->expression() + ')'; } - QString filter = QString( "(%1) AND (%2)" ).arg( + QString filter = QStringLiteral( "(%1) AND (%2)" ).arg( mRelation.getRelatedFeaturesRequest( mFeature ).filterExpression()->expression(), - filters.join( " OR " ) ); + filters.join( QStringLiteral( " OR " ) ) ); QgsFeatureIterator linkedIterator = mRelation.referencingLayer()->getFeatures( QgsFeatureRequest() .setSubsetOfAttributes( QgsAttributeList() ) @@ -536,7 +536,7 @@ void QgsRelationEditorWidget::updateUi() QgsFeatureRequest nmRequest; - nmRequest.setFilterExpression( filters.join( " OR " ) ); + nmRequest.setFilterExpression( filters.join( QStringLiteral( " OR " ) ) ); mDualView->init( mNmRelation.referencedLayer(), nullptr, nmRequest, mEditorContext ); } diff --git a/src/gui/qgsscalecombobox.cpp b/src/gui/qgsscalecombobox.cpp index dd35d03777a2..3f73211d7eff 100644 --- a/src/gui/qgsscalecombobox.cpp +++ b/src/gui/qgsscalecombobox.cpp @@ -51,7 +51,7 @@ void QgsScaleComboBox::updateScales( const QStringList &scales ) if ( scales.isEmpty() ) { QSettings settings; - QString myScales = settings.value( "Map/scales", PROJECT_SCALES ).toString(); + QString myScales = settings.value( QStringLiteral( "Map/scales" ), PROJECT_SCALES ).toString(); if ( !myScales.isEmpty() ) { myScalesList = myScales.split( ',' ); @@ -192,15 +192,15 @@ QString QgsScaleComboBox::toString( double scale ) { if ( scale == 0 ) { - return "0"; + return QStringLiteral( "0" ); } else if ( scale > 1 ) { - return QString( "%1:1" ).arg( QLocale::system().toString( qRound( scale ) ) ); + return QStringLiteral( "%1:1" ).arg( QLocale::system().toString( qRound( scale ) ) ); } else { - return QString( "1:%1" ).arg( QLocale::system().toString( qRound( 1.0 / scale ) ) ); + return QStringLiteral( "1:%1" ).arg( QLocale::system().toString( qRound( 1.0 / scale ) ) ); } } diff --git a/src/gui/qgsscalerangewidget.cpp b/src/gui/qgsscalerangewidget.cpp index 1a0f12caa997..f604fe747691 100644 --- a/src/gui/qgsscalerangewidget.cpp +++ b/src/gui/qgsscalerangewidget.cpp @@ -37,9 +37,9 @@ QgsScaleRangeWidget::QgsScaleRangeWidget( QWidget *parent ) "This limit is inclusive, that means the layer will be displayed on this scale." ) ); mMinimumScaleIconLabel = new QLabel( this ); - mMinimumScaleIconLabel->setPixmap( QgsApplication::getThemePixmap( "/mActionZoomOut.svg" ) ); + mMinimumScaleIconLabel->setPixmap( QgsApplication::getThemePixmap( QStringLiteral( "/mActionZoomOut.svg" ) ) ); mMaximumScaleIconLabel = new QLabel( this ); - mMaximumScaleIconLabel->setPixmap( QgsApplication::getThemePixmap( "/mActionZoomIn.svg" ) ); + mMaximumScaleIconLabel->setPixmap( QgsApplication::getThemePixmap( QStringLiteral( "/mActionZoomIn.svg" ) ) ); mMinimumScaleWidget = new QgsScaleWidget( this ); mMaximumScaleWidget = new QgsScaleWidget( this ); @@ -73,10 +73,10 @@ QgsScaleRangeWidget::~QgsScaleRangeWidget() void QgsScaleRangeWidget::reloadProjectScales() { - bool projectScales = QgsProject::instance()->readBoolEntry( "Scales", "/useProjectScales" ); + bool projectScales = QgsProject::instance()->readBoolEntry( QStringLiteral( "Scales" ), QStringLiteral( "/useProjectScales" ) ); if ( projectScales ) { - QStringList scalesList = QgsProject::instance()->readListEntry( "Scales", "/ScalesList" ); + QStringList scalesList = QgsProject::instance()->readListEntry( QStringLiteral( "Scales" ), QStringLiteral( "/ScalesList" ) ); mMinimumScaleWidget->updateScales( scalesList ); mMaximumScaleWidget->updateScales( scalesList ); } diff --git a/src/gui/qgsscalewidget.cpp b/src/gui/qgsscalewidget.cpp index d5962f19584d..267506887d91 100644 --- a/src/gui/qgsscalewidget.cpp +++ b/src/gui/qgsscalewidget.cpp @@ -33,7 +33,7 @@ QgsScaleWidget::QgsScaleWidget( QWidget *parent ) mCurrentScaleButton = new QToolButton( this ); mCurrentScaleButton->setToolTip( tr( "Set to current canvas scale" ) ); - mCurrentScaleButton->setIcon( QgsApplication::getThemeIcon( "/mActionMapIdentification.svg" ) ); + mCurrentScaleButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMapIdentification.svg" ) ) ); layout->addWidget( mCurrentScaleButton ); mCurrentScaleButton->hide(); diff --git a/src/gui/qgssearchquerybuilder.cpp b/src/gui/qgssearchquerybuilder.cpp index 7fca8aecb33a..905c58a2b94e 100644 --- a/src/gui/qgssearchquerybuilder.cpp +++ b/src/gui/qgssearchquerybuilder.cpp @@ -141,7 +141,7 @@ void QgsSearchQueryBuilder::getFieldValues( int limit ) if ( !numeric ) { // put string in single quotes and escape single quotes in the string - value = '\'' + value.replace( '\'', "''" ) + '\''; + value = '\'' + value.replace( '\'', QLatin1String( "''" ) ) + '\''; } // add item only if it's not there already @@ -269,37 +269,37 @@ void QgsSearchQueryBuilder::on_btnOk_clicked() void QgsSearchQueryBuilder::on_btnEqual_clicked() { - txtSQL->insertText( " = " ); + txtSQL->insertText( QStringLiteral( " = " ) ); } void QgsSearchQueryBuilder::on_btnLessThan_clicked() { - txtSQL->insertText( " < " ); + txtSQL->insertText( QStringLiteral( " < " ) ); } void QgsSearchQueryBuilder::on_btnGreaterThan_clicked() { - txtSQL->insertText( " > " ); + txtSQL->insertText( QStringLiteral( " > " ) ); } void QgsSearchQueryBuilder::on_btnPct_clicked() { - txtSQL->insertText( "%" ); + txtSQL->insertText( QStringLiteral( "%" ) ); } void QgsSearchQueryBuilder::on_btnIn_clicked() { - txtSQL->insertText( " IN " ); + txtSQL->insertText( QStringLiteral( " IN " ) ); } void QgsSearchQueryBuilder::on_btnNotIn_clicked() { - txtSQL->insertText( " NOT IN " ); + txtSQL->insertText( QStringLiteral( " NOT IN " ) ); } void QgsSearchQueryBuilder::on_btnLike_clicked() { - txtSQL->insertText( " LIKE " ); + txtSQL->insertText( QStringLiteral( " LIKE " ) ); } QString QgsSearchQueryBuilder::searchString() @@ -324,32 +324,32 @@ void QgsSearchQueryBuilder::on_lstValues_doubleClicked( const QModelIndex &index void QgsSearchQueryBuilder::on_btnLessEqual_clicked() { - txtSQL->insertText( " <= " ); + txtSQL->insertText( QStringLiteral( " <= " ) ); } void QgsSearchQueryBuilder::on_btnGreaterEqual_clicked() { - txtSQL->insertText( " >= " ); + txtSQL->insertText( QStringLiteral( " >= " ) ); } void QgsSearchQueryBuilder::on_btnNotEqual_clicked() { - txtSQL->insertText( " != " ); + txtSQL->insertText( QStringLiteral( " != " ) ); } void QgsSearchQueryBuilder::on_btnAnd_clicked() { - txtSQL->insertText( " AND " ); + txtSQL->insertText( QStringLiteral( " AND " ) ); } void QgsSearchQueryBuilder::on_btnNot_clicked() { - txtSQL->insertText( " NOT " ); + txtSQL->insertText( QStringLiteral( " NOT " ) ); } void QgsSearchQueryBuilder::on_btnOr_clicked() { - txtSQL->insertText( " OR " ); + txtSQL->insertText( QStringLiteral( " OR " ) ); } void QgsSearchQueryBuilder::on_btnClear_clicked() @@ -359,23 +359,23 @@ void QgsSearchQueryBuilder::on_btnClear_clicked() void QgsSearchQueryBuilder::on_btnILike_clicked() { - txtSQL->insertText( " ILIKE " ); + txtSQL->insertText( QStringLiteral( " ILIKE " ) ); } void QgsSearchQueryBuilder::saveQuery() { QSettings s; - QString lastQueryFileDir = s.value( "/UI/lastQueryFileDir", QDir::homePath() ).toString(); + QString lastQueryFileDir = s.value( QStringLiteral( "/UI/lastQueryFileDir" ), QDir::homePath() ).toString(); //save as qqt (QGIS query file) - QString saveFileName = QFileDialog::getSaveFileName( nullptr, tr( "Save query to file" ), lastQueryFileDir, "*.qqf" ); + QString saveFileName = QFileDialog::getSaveFileName( nullptr, tr( "Save query to file" ), lastQueryFileDir, QStringLiteral( "*.qqf" ) ); if ( saveFileName.isNull() ) { return; } - if ( !saveFileName.endsWith( ".qqf", Qt::CaseInsensitive ) ) + if ( !saveFileName.endsWith( QLatin1String( ".qqf" ), Qt::CaseInsensitive ) ) { - saveFileName += ".qqf"; + saveFileName += QLatin1String( ".qqf" ); } QFile saveFile( saveFileName ); @@ -386,7 +386,7 @@ void QgsSearchQueryBuilder::saveQuery() } QDomDocument xmlDoc; - QDomElement queryElem = xmlDoc.createElement( "Query" ); + QDomElement queryElem = xmlDoc.createElement( QStringLiteral( "Query" ) ); QDomText queryTextNode = xmlDoc.createTextNode( txtSQL->text() ); queryElem.appendChild( queryTextNode ); xmlDoc.appendChild( queryElem ); @@ -395,13 +395,13 @@ void QgsSearchQueryBuilder::saveQuery() xmlDoc.save( fileStream, 2 ); QFileInfo fi( saveFile ); - s.setValue( "/UI/lastQueryFileDir", fi.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastQueryFileDir" ), fi.absolutePath() ); } void QgsSearchQueryBuilder::loadQuery() { QSettings s; - QString lastQueryFileDir = s.value( "/UI/lastQueryFileDir", QDir::homePath() ).toString(); + QString lastQueryFileDir = s.value( QStringLiteral( "/UI/lastQueryFileDir" ), QDir::homePath() ).toString(); QString queryFileName = QFileDialog::getOpenFileName( nullptr, tr( "Load query from file" ), lastQueryFileDir, tr( "Query files" ) + " (*.qqf);;" + tr( "All files" ) + " (*)" ); if ( queryFileName.isNull() ) @@ -422,7 +422,7 @@ void QgsSearchQueryBuilder::loadQuery() return; } - QDomElement queryElem = queryDoc.firstChildElement( "Query" ); + QDomElement queryElem = queryDoc.firstChildElement( QStringLiteral( "Query" ) ); if ( queryElem.isNull() ) { QMessageBox::critical( nullptr, tr( "Error" ), tr( "File is not a valid query document" ) ); diff --git a/src/gui/qgsshortcutsmanager.cpp b/src/gui/qgsshortcutsmanager.cpp index aa63049f58a6..1ce06178be70 100644 --- a/src/gui/qgsshortcutsmanager.cpp +++ b/src/gui/qgsshortcutsmanager.cpp @@ -89,7 +89,7 @@ bool QgsShortcutsManager::registerAction( QAction* action, const QString& defaul #ifdef QGISDEBUG // if using a debug build, warn on duplicate actions if ( actionByName( action->text() ) || shortcutByName( action->text() ) ) - QgsLogger::warning( QString( "Duplicate shortcut registered: %1" ).arg( action->text() ) ); + QgsLogger::warning( QStringLiteral( "Duplicate shortcut registered: %1" ).arg( action->text() ) ); #endif mActions.insert( action, defaultSequence ); @@ -112,7 +112,7 @@ bool QgsShortcutsManager::registerShortcut( QShortcut* shortcut, const QString& #ifdef QGISDEBUG // if using a debug build, warn on duplicate actions if ( actionByName( shortcut->objectName() ) || shortcutByName( shortcut->objectName() ) ) - QgsLogger::warning( QString( "Duplicate shortcut registered: %1" ).arg( shortcut->objectName() ) ); + QgsLogger::warning( QStringLiteral( "Duplicate shortcut registered: %1" ).arg( shortcut->objectName() ) ); #endif mShortcuts.insert( shortcut, defaultSequence ); diff --git a/src/gui/qgsshortcutsmanager.h b/src/gui/qgsshortcutsmanager.h index 5998287b0055..83cdcf9e0a53 100644 --- a/src/gui/qgsshortcutsmanager.h +++ b/src/gui/qgsshortcutsmanager.h @@ -43,7 +43,7 @@ class GUI_EXPORT QgsShortcutsManager : public QObject * as the default value to store settings alongside built in QGIS shortcuts, but care must be * taken to not register actions which conflict with the built in QGIS actions. */ - QgsShortcutsManager( QObject *parent = nullptr, const QString& settingsRoot = "/shortcuts/" ); + QgsShortcutsManager( QObject *parent = nullptr, const QString& settingsRoot = QStringLiteral( "/shortcuts/" ) ); /** Automatically registers all QActions and QShortcuts which are children of the * passed object. diff --git a/src/gui/qgssourceselectdialog.cpp b/src/gui/qgssourceselectdialog.cpp index 8957678ed0ee..09b16433a79d 100644 --- a/src/gui/qgssourceselectdialog.cpp +++ b/src/gui/qgssourceselectdialog.cpp @@ -53,7 +53,7 @@ QgsSourceSelectDialog::QgsSourceSelectDialog( const QString& serviceName, Servic : QDialog( parent, fl ), mServiceName( serviceName ), mServiceType( serviceType ), mBuildQueryButton( 0 ), mImageEncodingGroup( 0 ) { setupUi( this ); - setWindowTitle( QString( "Add %1 Layer from a Server" ).arg( mServiceName ) ); + setWindowTitle( QStringLiteral( "Add %1 Layer from a Server" ).arg( mServiceName ) ); mAddButton = buttonBox->addButton( tr( "&Add" ), QDialogButtonBox::ActionRole ); mAddButton->setEnabled( false ); @@ -80,17 +80,17 @@ QgsSourceSelectDialog::QgsSourceSelectDialog( const QString& serviceName, Servic treeView->setItemDelegate( new QgsSourceSelectItemDelegate( treeView ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/SourceSelectDialog/geometry" ).toByteArray() ); - cbxUseTitleLayerName->setChecked( settings.value( "/Windows/SourceSelectDialog/UseTitleLayerName", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/SourceSelectDialog/geometry" ) ).toByteArray() ); + cbxUseTitleLayerName->setChecked( settings.value( QStringLiteral( "/Windows/SourceSelectDialog/UseTitleLayerName" ), false ).toBool() ); mModel = new QStandardItemModel(); - mModel->setHorizontalHeaderItem( 0, new QStandardItem( "Title" ) ); - mModel->setHorizontalHeaderItem( 1, new QStandardItem( "Name" ) ); - mModel->setHorizontalHeaderItem( 2, new QStandardItem( "Abstract" ) ); + mModel->setHorizontalHeaderItem( 0, new QStandardItem( QStringLiteral( "Title" ) ) ); + mModel->setHorizontalHeaderItem( 1, new QStandardItem( QStringLiteral( "Name" ) ) ); + mModel->setHorizontalHeaderItem( 2, new QStandardItem( QStringLiteral( "Abstract" ) ) ); if ( serviceType == FeatureService ) { - mModel->setHorizontalHeaderItem( 3, new QStandardItem( "Cache Feature" ) ); - mModel->setHorizontalHeaderItem( 4, new QStandardItem( "Filter" ) ); + mModel->setHorizontalHeaderItem( 3, new QStandardItem( QStringLiteral( "Cache Feature" ) ) ); + mModel->setHorizontalHeaderItem( 4, new QStandardItem( QStringLiteral( "Filter" ) ) ); gbImageEncoding->hide(); } else @@ -111,8 +111,8 @@ QgsSourceSelectDialog::QgsSourceSelectDialog( const QString& serviceName, Servic QgsSourceSelectDialog::~QgsSourceSelectDialog() { QSettings settings; - settings.setValue( "/Windows/SourceSelectDialog/geometry", saveGeometry() ); - settings.setValue( "/Windows/SourceSelectDialog/UseTitleLayerName", cbxUseTitleLayerName->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/SourceSelectDialog/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/SourceSelectDialog/UseTitleLayerName" ), cbxUseTitleLayerName->isChecked() ); delete mProjectionSelector; delete mModel; @@ -190,7 +190,7 @@ QString QgsSourceSelectDialog::getPreferredCrs( const QSet<QString>& crsSet ) co { if ( crsSet.size() < 1 ) { - return ""; + return QLatin1String( "" ); } //first: project CRS @@ -220,7 +220,7 @@ QString QgsSourceSelectDialog::getPreferredCrs( const QSet<QString>& crsSet ) co void QgsSourceSelectDialog::addEntryToServerList() { - QgsNewHttpConnection nc( 0, QString( "/Qgis/connections-%1/" ).arg( mServiceName.toLower() ) ); + QgsNewHttpConnection nc( 0, QStringLiteral( "/Qgis/connections-%1/" ).arg( mServiceName.toLower() ) ); nc.setWindowTitle( tr( "Create a new %1 connection" ).arg( mServiceName ) ); if ( nc.exec() ) @@ -232,7 +232,7 @@ void QgsSourceSelectDialog::addEntryToServerList() void QgsSourceSelectDialog::modifyEntryOfServerList() { - QgsNewHttpConnection nc( 0, QString( "/Qgis/connections-%1/" ).arg( mServiceName.toLower() ), cmbConnections->currentText() ); + QgsNewHttpConnection nc( 0, QStringLiteral( "/Qgis/connections-%1/" ).arg( mServiceName.toLower() ), cmbConnections->currentText() ); nc.setWindowTitle( tr( "Modify %1 connection" ).arg( mServiceName ) ); if ( nc.exec() ) @@ -345,7 +345,7 @@ void QgsSourceSelectDialog::addButtonClicked() QString layerTitle = mModel->item( row, 0 )->text(); //layer title/id QString layerName = mModel->item( row, 1 )->text(); //layer name bool cacheFeatures = mServiceType == FeatureService ? mModel->item( row, 3 )->checkState() == Qt::Checked : false; - QString filter = mServiceType == FeatureService ? mModel->item( row, 4 )->text() : ""; //optional filter specified by user + QString filter = mServiceType == FeatureService ? mModel->item( row, 4 )->text() : QLatin1String( "" ); //optional filter specified by user if ( cbxUseTitleLayerName->isChecked() && !layerTitle.isEmpty() ) { layerName = layerTitle; @@ -420,7 +420,7 @@ void QgsSourceSelectDialog::on_btnSave_clicked() void QgsSourceSelectDialog::on_btnLoad_clicked() { - QString fileName = QFileDialog::getOpenFileName( this, tr( "Load connections" ), ".", + QString fileName = QFileDialog::getOpenFileName( this, tr( "Load connections" ), QStringLiteral( "." ), tr( "XML files (*.xml *XML)" ) ); if ( fileName.isEmpty() ) { diff --git a/src/gui/qgssqlcomposerdialog.cpp b/src/gui/qgssqlcomposerdialog.cpp index 983ee97242df..ea189039f6b1 100644 --- a/src/gui/qgssqlcomposerdialog.cpp +++ b/src/gui/qgssqlcomposerdialog.cpp @@ -71,37 +71,37 @@ QgsSQLComposerDialog::QgsSQLComposerDialog( QWidget * parent, Qt::WindowFlags fl this, SLOT( buildSQLFromFields() ) ); QStringList baseList; - baseList << "SELECT"; - baseList << "FROM"; - baseList << "JOIN"; - baseList << "ON"; - baseList << "USING"; - baseList << "WHERE"; - baseList << "AND"; - baseList << "OR"; - baseList << "NOT"; - baseList << "IS"; - baseList << "NULL"; - baseList << "LIKE"; - baseList << "ORDER"; - baseList << "BY"; + baseList << QStringLiteral( "SELECT" ); + baseList << QStringLiteral( "FROM" ); + baseList << QStringLiteral( "JOIN" ); + baseList << QStringLiteral( "ON" ); + baseList << QStringLiteral( "USING" ); + baseList << QStringLiteral( "WHERE" ); + baseList << QStringLiteral( "AND" ); + baseList << QStringLiteral( "OR" ); + baseList << QStringLiteral( "NOT" ); + baseList << QStringLiteral( "IS" ); + baseList << QStringLiteral( "NULL" ); + baseList << QStringLiteral( "LIKE" ); + baseList << QStringLiteral( "ORDER" ); + baseList << QStringLiteral( "BY" ); addApis( baseList ); QStringList operatorsList; - operatorsList << "AND"; - operatorsList << "OR"; - operatorsList << "NOT"; - operatorsList << "="; - operatorsList << "<"; - operatorsList << "<="; - operatorsList << ">"; - operatorsList << ">="; - operatorsList << "<>"; - operatorsList << "IS"; - operatorsList << "IS NOT"; - operatorsList << "IN"; - operatorsList << "LIKE"; - operatorsList << "BETWEEN"; + operatorsList << QStringLiteral( "AND" ); + operatorsList << QStringLiteral( "OR" ); + operatorsList << QStringLiteral( "NOT" ); + operatorsList << QStringLiteral( "=" ); + operatorsList << QStringLiteral( "<" ); + operatorsList << QStringLiteral( "<=" ); + operatorsList << QStringLiteral( ">" ); + operatorsList << QStringLiteral( ">=" ); + operatorsList << QStringLiteral( "<>" ); + operatorsList << QStringLiteral( "IS" ); + operatorsList << QStringLiteral( "IS NOT" ); + operatorsList << QStringLiteral( "IN" ); + operatorsList << QStringLiteral( "LIKE" ); + operatorsList << QStringLiteral( "BETWEEN" ); addOperators( operatorsList ); mAggregatesCombo->hide(); @@ -115,8 +115,8 @@ QgsSQLComposerDialog::QgsSQLComposerDialog( QWidget * parent, Qt::WindowFlags fl mRemoveJoinButton->setEnabled( false ); mTableJoins->setRowCount( 0 ); - mTableJoins->setItem( 0, 0, new QTableWidgetItem( "" ) ); - mTableJoins->setItem( 0, 1, new QTableWidgetItem( "" ) ); + mTableJoins->setItem( 0, 0, new QTableWidgetItem( QLatin1String( "" ) ) ); + mTableJoins->setItem( 0, 1, new QTableWidgetItem( QLatin1String( "" ) ) ); } QgsSQLComposerDialog::~QgsSQLComposerDialog() @@ -231,11 +231,11 @@ void QgsSQLComposerDialog::buildSQLFromFields() if ( mAlreadyModifyingFields ) return; mAlreadyModifyingFields = true; - QString sql( "SELECT " ); + QString sql( QStringLiteral( "SELECT " ) ); if ( mDistinct ) - sql += "DISTINCT "; + sql += QLatin1String( "DISTINCT " ); sql += mColumnsEditor->toPlainText(); - sql += " FROM "; + sql += QLatin1String( " FROM " ); sql += mTablesEditor->text(); int rows = mTableJoins->rowCount(); @@ -246,21 +246,21 @@ void QgsSQLComposerDialog::buildSQLFromFields() if ( itemTable && !itemTable->text().isEmpty() && itemOn && !itemOn->text().isEmpty() ) { - sql += " JOIN "; + sql += QLatin1String( " JOIN " ); sql += itemTable->text(); - sql += " ON "; + sql += QLatin1String( " ON " ); sql += itemOn->text(); } } if ( !mWhereEditor->toPlainText().isEmpty() ) { - sql += " WHERE "; + sql += QLatin1String( " WHERE " ); sql += mWhereEditor->toPlainText(); } if ( !mOrderEditor->toPlainText().isEmpty() ) { - sql += " ORDER BY "; + sql += QLatin1String( " ORDER BY " ); sql += mOrderEditor->toPlainText(); } mQueryEdit->setText( sql ); @@ -284,7 +284,7 @@ void QgsSQLComposerDialog::splitSQLIntoFields() Q_FOREACH ( QgsSQLStatement::NodeSelectedColumn* column, columns ) { if ( !columnText.isEmpty() ) - columnText += ", "; + columnText += QLatin1String( ", " ); columnText += column->dump(); } @@ -293,7 +293,7 @@ void QgsSQLComposerDialog::splitSQLIntoFields() Q_FOREACH ( QgsSQLStatement::NodeTableDef* table, tables ) { if ( !tablesText.isEmpty() ) - tablesText += ", "; + tablesText += QLatin1String( ", " ); loadTableColumns( QgsSQLStatement::quotedIdentifierIfNeeded( table->name() ) ); tablesText += table->dump(); } @@ -308,7 +308,7 @@ void QgsSQLComposerDialog::splitSQLIntoFields() Q_FOREACH ( QgsSQLStatement::NodeColumnSorted* column, orderColumns ) { if ( !orderText.isEmpty() ) - orderText += ", "; + orderText += QLatin1String( ", " ); orderText += column->dump(); } @@ -329,11 +329,11 @@ void QgsSQLComposerDialog::splitSQLIntoFields() if ( join->onExpr() ) mTableJoins->setItem( iRow, 1 , new QTableWidgetItem( join->onExpr()->dump() ) ); else - mTableJoins->setItem( iRow, 1 , new QTableWidgetItem( "" ) ); + mTableJoins->setItem( iRow, 1 , new QTableWidgetItem( QLatin1String( "" ) ) ); iRow ++; } - mTableJoins->setItem( iRow, 0, new QTableWidgetItem( "" ) ); - mTableJoins->setItem( iRow, 1, new QTableWidgetItem( "" ) ); + mTableJoins->setItem( iRow, 0, new QTableWidgetItem( QLatin1String( "" ) ) ); + mTableJoins->setItem( iRow, 1, new QTableWidgetItem( QLatin1String( "" ) ) ); mAlreadyModifyingFields = false; } @@ -378,12 +378,12 @@ void QgsSQLComposerDialog::addColumnNames( const QStringList& list, const QStrin static QString sanitizeType( QString type ) { - if ( type.startsWith( "xs:" ) ) + if ( type.startsWith( QLatin1String( "xs:" ) ) ) return type.mid( 3 ); - if ( type.startsWith( "xsd:" ) ) + if ( type.startsWith( QLatin1String( "xsd:" ) ) ) return type.mid( 4 ); - if ( type == "gml:AbstractGeometryType" ) - return "geometry"; + if ( type == QLatin1String( "gml:AbstractGeometryType" ) ) + return QStringLiteral( "geometry" ); return type; } @@ -455,14 +455,14 @@ void QgsSQLComposerDialog::getFunctionList( const QList<Function>& list, { listApi << f.name; QString entryText( f.name ); - entryText += "("; + entryText += QLatin1String( "(" ); if ( !f.argumentList.isEmpty() ) { for ( int i = 0;i < f.argumentList.size();i++ ) { - if ( f.minArgs >= 0 && i >= f.minArgs ) entryText += "["; - if ( i > 0 ) entryText += ", "; - if ( f.argumentList[i].name == "number" && !f.argumentList[i].type.isEmpty() ) + if ( f.minArgs >= 0 && i >= f.minArgs ) entryText += QLatin1String( "[" ); + if ( i > 0 ) entryText += QLatin1String( ", " ); + if ( f.argumentList[i].name == QLatin1String( "number" ) && !f.argumentList[i].type.isEmpty() ) { entryText += sanitizeType( f.argumentList[i].type ); } @@ -473,16 +473,16 @@ void QgsSQLComposerDialog::getFunctionList( const QList<Function>& list, if ( !f.argumentList[i].type.isEmpty() && f.argumentList[i].name != sanitizedType ) { - entryText += ": "; + entryText += QLatin1String( ": " ); entryText += sanitizedType; } } - if ( f.minArgs >= 0 && i >= f.minArgs ) entryText += "]"; + if ( f.minArgs >= 0 && i >= f.minArgs ) entryText += QLatin1String( "]" ); } if ( entryText.size() > 60 ) { entryText = f.name ; - entryText += "("; + entryText += QLatin1String( "(" ); entryText += getFunctionAbbridgedParameters( f ); } } @@ -490,7 +490,7 @@ void QgsSQLComposerDialog::getFunctionList( const QList<Function>& list, { entryText += getFunctionAbbridgedParameters( f ); } - entryText += ")"; + entryText += QLatin1String( ")" ); if ( !f.returnType.isEmpty() ) entryText += ": " + sanitizeType( f.returnType ); listCombo << entryText; @@ -623,7 +623,7 @@ void QgsSQLComposerDialog::on_mColumnsCombo_currentIndexChanged( int ) mTableJoins->selectedItems().at( 0 )->column() == 1 ) { QString currentText( mTableJoins->selectedItems().at( 0 )->text() ); - if ( !currentText.isEmpty() && !currentText.contains( "=" ) ) + if ( !currentText.isEmpty() && !currentText.contains( QLatin1String( "=" ) ) ) mTableJoins->selectedItems().at( 0 )->setText( currentText + " = " + newText ); else mTableJoins->selectedItems().at( 0 )->setText( currentText + newText ); @@ -720,8 +720,8 @@ void QgsSQLComposerDialog::on_mAddJoinButton_clicked() mTableJoins->setItem( row, 0, mTableJoins->takeItem( row - 1, 0 ) ); mTableJoins->setItem( row, 1, mTableJoins->takeItem( row - 1, 1 ) ); } - mTableJoins->setItem(( insertRow == rowCount ) ? insertRow : insertRow + 1, 0, new QTableWidgetItem( "" ) ); - mTableJoins->setItem(( insertRow == rowCount ) ? insertRow : insertRow + 1, 1, new QTableWidgetItem( "" ) ); + mTableJoins->setItem(( insertRow == rowCount ) ? insertRow : insertRow + 1, 0, new QTableWidgetItem( QLatin1String( "" ) ) ); + mTableJoins->setItem(( insertRow == rowCount ) ? insertRow : insertRow + 1, 1, new QTableWidgetItem( QLatin1String( "" ) ) ); } void QgsSQLComposerDialog::on_mRemoveJoinButton_clicked() diff --git a/src/gui/qgssublayersdialog.cpp b/src/gui/qgssublayersdialog.cpp index 1fee56dfb51b..38cf07527a12 100644 --- a/src/gui/qgssublayersdialog.cpp +++ b/src/gui/qgssublayersdialog.cpp @@ -141,16 +141,16 @@ void QgsSublayersDialog::populateLayerTable( const QgsSublayersDialog::LayerDefi int QgsSublayersDialog::exec() { QSettings settings; - QString promptLayers = settings.value( "/qgis/promptForSublayers", 1 ).toString(); + QString promptLayers = settings.value( QStringLiteral( "/qgis/promptForSublayers" ), 1 ).toString(); // make sure three are sublayers to choose if ( layersTable->topLevelItemCount() == 0 ) return QDialog::Rejected; // check promptForSublayers settings - perhaps this should be in QgsDataSource instead? - if ( promptLayers == "no" ) + if ( promptLayers == QLatin1String( "no" ) ) return QDialog::Rejected; - else if ( promptLayers == "all" ) + else if ( promptLayers == QLatin1String( "all" ) ) { layersTable->selectAll(); return QDialog::Accepted; diff --git a/src/gui/qgssubstitutionlistwidget.cpp b/src/gui/qgssubstitutionlistwidget.cpp index 888b9025e0bf..44948291de36 100644 --- a/src/gui/qgssubstitutionlistwidget.cpp +++ b/src/gui/qgssubstitutionlistwidget.cpp @@ -94,14 +94,14 @@ void QgsSubstitutionListWidget::on_mButtonExport_clicked() } // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } QDomDocument doc; - QDomElement root = doc.createElement( "substitutions" ); - root.setAttribute( "version", "1.0" ); + QDomElement root = doc.createElement( QStringLiteral( "substitutions" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); QgsStringReplacementCollection collection = substitutions(); collection.writeXml( root, doc ); doc.appendChild( root ); @@ -157,7 +157,7 @@ void QgsSubstitutionListWidget::on_mButtonImport_clicked() } QDomElement root = doc.documentElement(); - if ( root.tagName() != "substitutions" ) + if ( root.tagName() != QLatin1String( "substitutions" ) ) { QMessageBox::warning( nullptr, tr( "Import substitutions" ), tr( "The selected file is not a substitution list." ), diff --git a/src/gui/qgssvgannotationitem.cpp b/src/gui/qgssvgannotationitem.cpp index 060ae8245d7c..19a51b12eae0 100644 --- a/src/gui/qgssvgannotationitem.cpp +++ b/src/gui/qgssvgannotationitem.cpp @@ -39,17 +39,17 @@ void QgsSvgAnnotationItem::writeXml( QDomDocument& doc ) const return; } - QDomElement svgAnnotationElem = doc.createElement( "SVGAnnotationItem" ); - svgAnnotationElem.setAttribute( "file", QgsProject::instance()->writePath( mFilePath ) ); + QDomElement svgAnnotationElem = doc.createElement( QStringLiteral( "SVGAnnotationItem" ) ); + svgAnnotationElem.setAttribute( QStringLiteral( "file" ), QgsProject::instance()->writePath( mFilePath ) ); _writeXml( doc, svgAnnotationElem ); documentElem.appendChild( svgAnnotationElem ); } void QgsSvgAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& itemElem ) { - QString filePath = QgsProject::instance()->readPath( itemElem.attribute( "file" ) ); + QString filePath = QgsProject::instance()->readPath( itemElem.attribute( QStringLiteral( "file" ) ) ); setFilePath( filePath ); - QDomElement annotationElem = itemElem.firstChildElement( "AnnotationItem" ); + QDomElement annotationElem = itemElem.firstChildElement( QStringLiteral( "AnnotationItem" ) ); if ( !annotationElem.isNull() ) { _readXml( doc, annotationElem ); diff --git a/src/gui/qgstextannotationitem.cpp b/src/gui/qgstextannotationitem.cpp index 4226807ee609..d65915ac9906 100644 --- a/src/gui/qgstextannotationitem.cpp +++ b/src/gui/qgstextannotationitem.cpp @@ -88,10 +88,10 @@ void QgsTextAnnotationItem::writeXml( QDomDocument& doc ) const { return; } - QDomElement annotationElem = doc.createElement( "TextAnnotationItem" ); + QDomElement annotationElem = doc.createElement( QStringLiteral( "TextAnnotationItem" ) ); if ( mDocument ) { - annotationElem.setAttribute( "document", mDocument->toHtml() ); + annotationElem.setAttribute( QStringLiteral( "document" ), mDocument->toHtml() ); } _writeXml( doc, annotationElem ); documentElem.appendChild( annotationElem ); @@ -101,8 +101,8 @@ void QgsTextAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& { delete mDocument; mDocument = new QTextDocument; - mDocument->setHtml( itemElem.attribute( "document", QObject::tr( "" ) ) ); - QDomElement annotationElem = itemElem.firstChildElement( "AnnotationItem" ); + mDocument->setHtml( itemElem.attribute( QStringLiteral( "document" ), QObject::tr( "" ) ) ); + QDomElement annotationElem = itemElem.firstChildElement( QStringLiteral( "AnnotationItem" ) ); if ( !annotationElem.isNull() ) { _readXml( doc, annotationElem ); diff --git a/src/gui/qgstextformatwidget.cpp b/src/gui/qgstextformatwidget.cpp index d0166c976274..9b567c27346f 100644 --- a/src/gui/qgstextformatwidget.cpp +++ b/src/gui/qgstextformatwidget.cpp @@ -132,20 +132,20 @@ void QgsTextFormatWidget::initWidget() // color buttons mPreviewBackgroundBtn->setColorDialogTitle( tr( "Select fill color" ) ); - mPreviewBackgroundBtn->setContext( "labelling" ); + mPreviewBackgroundBtn->setContext( QStringLiteral( "labelling" ) ); mPreviewBackgroundBtn->setColor( QColor( 255, 255, 255 ) ); btnTextColor->setColorDialogTitle( tr( "Select text color" ) ); - btnTextColor->setContext( "labelling" ); + btnTextColor->setContext( QStringLiteral( "labelling" ) ); btnTextColor->setDefaultColor( Qt::black ); btnBufferColor->setColorDialogTitle( tr( "Select buffer color" ) ); - btnBufferColor->setContext( "labelling" ); + btnBufferColor->setContext( QStringLiteral( "labelling" ) ); btnBufferColor->setDefaultColor( Qt::white ); mShapeBorderColorBtn->setColorDialogTitle( tr( "Select border color" ) ); - mShapeBorderColorBtn->setContext( "labelling" ); + mShapeBorderColorBtn->setContext( QStringLiteral( "labelling" ) ); mShapeFillColorBtn->setColorDialogTitle( tr( "Select fill color" ) ); - mShapeFillColorBtn->setContext( "labelling" ); + mShapeFillColorBtn->setContext( QStringLiteral( "labelling" ) ); mShadowColorBtn->setColorDialogTitle( tr( "Select shadow color" ) ); - mShadowColorBtn->setContext( "labelling" ); + mShadowColorBtn->setContext( QStringLiteral( "labelling" ) ); mShadowColorBtn->setDefaultColor( Qt::black ); // set up quadrant offset button group @@ -215,7 +215,7 @@ void QgsTextFormatWidget::initWidget() // maintains state across different dialogs Q_FOREACH ( QgsCollapsibleGroupBox *grpbox, findChildren<QgsCollapsibleGroupBox*>() ) { - grpbox->setSettingGroup( QString( "mAdvLabelingDlg" ) ); + grpbox->setSettingGroup( QStringLiteral( "mAdvLabelingDlg" ) ); } connect( groupBox_mPreview, @@ -232,7 +232,7 @@ void QgsTextFormatWidget::initWidget() QSizePolicy policy( mLabelingOptionsListFrame->sizePolicy() ); policy.setHorizontalStretch( 0 ); mLabelingOptionsListFrame->setSizePolicy( policy ); - if ( !settings.contains( QString( "/Windows/Labeling/OptionsSplitState" ) ) ) + if ( !settings.contains( QStringLiteral( "/Windows/Labeling/OptionsSplitState" ) ) ) { // set left list widget width on intial showing QList<int> splitsizes; @@ -244,10 +244,10 @@ void QgsTextFormatWidget::initWidget() connect( mLabelStackedWidget, SIGNAL( currentChanged( int ) ), this, SLOT( optionsStackedWidget_CurrentChanged( int ) ) ); // restore dialog, splitters and current tab - mFontPreviewSplitter->restoreState( settings.value( QString( "/Windows/Labeling/FontPreviewSplitState" ) ).toByteArray() ); - mLabelingOptionsSplitter->restoreState( settings.value( QString( "/Windows/Labeling/OptionsSplitState" ) ).toByteArray() ); + mFontPreviewSplitter->restoreState( settings.value( QStringLiteral( "/Windows/Labeling/FontPreviewSplitState" ) ).toByteArray() ); + mLabelingOptionsSplitter->restoreState( settings.value( QStringLiteral( "/Windows/Labeling/OptionsSplitState" ) ).toByteArray() ); - mLabelingOptionsListWidget->setCurrentRow( settings.value( QString( "/Windows/Labeling/Tab" ), 0 ).toInt() ); + mLabelingOptionsListWidget->setCurrentRow( settings.value( QStringLiteral( "/Windows/Labeling/Tab" ), 0 ).toInt() ); setDockMode( false ); @@ -581,7 +581,7 @@ void QgsTextFormatWidget::connectValueChanged( const QList<QWidget *>& widgets, } else { - QgsLogger::warning( QString( "Could not create connection for widget %1" ).arg( widget->objectName() ) ); + QgsLogger::warning( QStringLiteral( "Could not create connection for widget %1" ).arg( widget->objectName() ) ); } } } @@ -626,7 +626,7 @@ void QgsTextFormatWidget::updateWidgetForFormat( const QgsTextFormat& format ) QString txtPrepend = tr( "Chosen font" ); if ( !format.resolvedFontFamily().isEmpty() ) { - txtPrepend = QString( "'%1'" ).arg( format.resolvedFontFamily() ); + txtPrepend = QStringLiteral( "'%1'" ).arg( format.resolvedFontFamily() ); } mFontMissingLabel->setText( missingTxt.arg( txtPrepend ) ); @@ -697,9 +697,9 @@ void QgsTextFormatWidget::updateWidgetForFormat( const QgsTextFormat& format ) QgsTextFormatWidget::~QgsTextFormatWidget() { QSettings settings; - settings.setValue( QString( "/Windows/Labeling/FontPreviewSplitState" ), mFontPreviewSplitter->saveState() ); - settings.setValue( QString( "/Windows/Labeling/OptionsSplitState" ), mLabelingOptionsSplitter->saveState() ); - settings.setValue( QString( "/Windows/Labeling/Tab" ), mLabelingOptionsListWidget->currentRow() ); + settings.setValue( QStringLiteral( "/Windows/Labeling/FontPreviewSplitState" ), mFontPreviewSplitter->saveState() ); + settings.setValue( QStringLiteral( "/Windows/Labeling/OptionsSplitState" ), mLabelingOptionsSplitter->saveState() ); + settings.setValue( QStringLiteral( "/Windows/Labeling/Tab" ), mLabelingOptionsListWidget->currentRow() ); } QgsTextFormat QgsTextFormatWidget::format() const @@ -869,7 +869,7 @@ void QgsTextFormatWidget::scrollPreview() void QgsTextFormatWidget::setPreviewBackground( const QColor& color ) { - scrollArea_mPreview->widget()->setStyleSheet( QString( "background: rgb(%1, %2, %3);" ).arg( QString::number( color.red() ), + scrollArea_mPreview->widget()->setStyleSheet( QStringLiteral( "background: rgb(%1, %2, %3);" ).arg( QString::number( color.red() ), QString::number( color.green() ), QString::number( color.blue() ) ) ); } @@ -1116,7 +1116,7 @@ void QgsTextFormatWidget::on_mShapeTypeCmbBx_currentIndexChanged( int index ) mShapeSizeYLabel->setVisible( !isSVG ); mShapeSizeYSpnBx->setVisible( !isSVG ); mShapeSizeYDDBtn->setVisible( !isSVG ); - mShapeSizeXLabel->setText( tr( "Size%1" ).arg( !isSVG ? tr( " X" ) : "" ) ); + mShapeSizeXLabel->setText( tr( "Size%1" ).arg( !isSVG ? tr( " X" ) : QLatin1String( "" ) ) ); // SVG parameter setting doesn't support color's alpha component yet mShapeFillColorBtn->setAllowAlpha( !isSVG ); @@ -1273,7 +1273,7 @@ void QgsTextFormatWidget::on_mPreviewTextEdit_textChanged( const QString & text void QgsTextFormatWidget::on_mPreviewTextBtn_clicked() { - mPreviewTextEdit->setText( QString( "Lorem Ipsum" ) ); + mPreviewTextEdit->setText( QStringLiteral( "Lorem Ipsum" ) ); updatePreview(); } @@ -1397,7 +1397,7 @@ QgsTextFormatDialog::QgsTextFormatDialog( const QgsTextFormat& format, QgsMapCan setLayout( layout ); QSettings settings; - restoreGeometry( settings.value( "/Windows/TextFormatDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/TextFormatDialog/geometry" ) ).toByteArray() ); connect( buttonBox->button( QDialogButtonBox::Ok ), SIGNAL( clicked() ), this, SLOT( accept() ) ); connect( buttonBox->button( QDialogButtonBox::Cancel ), SIGNAL( clicked() ), this, SLOT( reject() ) ); @@ -1406,7 +1406,7 @@ QgsTextFormatDialog::QgsTextFormatDialog( const QgsTextFormat& format, QgsMapCan QgsTextFormatDialog::~QgsTextFormatDialog() { QSettings settings; - settings.setValue( "/Windows/TextFormatDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/TextFormatDialog/geometry" ), saveGeometry() ); } QgsTextFormat QgsTextFormatDialog::format() const diff --git a/src/gui/qgsvariableeditorwidget.cpp b/src/gui/qgsvariableeditorwidget.cpp index 33438a4551dd..38f721ee17c3 100644 --- a/src/gui/qgsvariableeditorwidget.cpp +++ b/src/gui/qgsvariableeditorwidget.cpp @@ -50,11 +50,11 @@ QgsVariableEditorWidget::QgsVariableEditorWidget( QWidget *parent ) QSpacerItem* horizontalSpacer = new QSpacerItem( 40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ); horizontalLayout->addItem( horizontalSpacer ); mAddButton = new QPushButton(); - mAddButton->setIcon( QgsApplication::getThemeIcon( "/symbologyAdd.svg" ) ); + mAddButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/symbologyAdd.svg" ) ) ); mAddButton->setEnabled( false ); horizontalLayout->addWidget( mAddButton ); mRemoveButton = new QPushButton(); - mRemoveButton->setIcon( QgsApplication::getThemeIcon( "/symbologyRemove.svg" ) ); + mRemoveButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/symbologyRemove.svg" ) ) ); mRemoveButton->setEnabled( false ); horizontalLayout->addWidget( mRemoveButton ); verticalLayout->addLayout( horizontalLayout ); @@ -167,9 +167,9 @@ void QgsVariableEditorWidget::on_mAddButton_clicked() return; QgsExpressionContextScope* scope = mContext->scope( mEditableScopeIndex ); - scope->setVariable( "new_variable", QVariant() ); + scope->setVariable( QStringLiteral( "new_variable" ), QVariant() ); mTreeWidget->refreshTree(); - QTreeWidgetItem* item = mTreeWidget->itemFromVariable( scope, "new_variable" ); + QTreeWidgetItem* item = mTreeWidget->itemFromVariable( scope, QStringLiteral( "new_variable" ) ); QModelIndex index = mTreeWidget->itemToIndex( item ); mTreeWidget->selectionModel()->select( index, QItemSelectionModel::ClearAndSelect ); mTreeWidget->editItem( item, 0 ); @@ -258,10 +258,10 @@ QgsVariableEditorTree::QgsVariableEditorTree( QWidget *parent ) { QPixmap pix( 14, 14 ); pix.fill( Qt::transparent ); - mExpandIcon.addPixmap( QgsApplication::getThemeIcon( "/mIconExpandSmall.svg" ).pixmap( 14, 14 ), QIcon::Normal, QIcon::Off ); - mExpandIcon.addPixmap( QgsApplication::getThemeIcon( "/mIconExpandSmall.svg" ).pixmap( 14, 14 ), QIcon::Selected, QIcon::Off ); - mExpandIcon.addPixmap( QgsApplication::getThemeIcon( "/mIconCollapseSmall.svg" ).pixmap( 14, 14 ), QIcon::Normal, QIcon::On ); - mExpandIcon.addPixmap( QgsApplication::getThemeIcon( "/mIconCollapseSmall.svg" ).pixmap( 14, 14 ), QIcon::Selected, QIcon::On ); + mExpandIcon.addPixmap( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpandSmall.svg" ) ).pixmap( 14, 14 ), QIcon::Normal, QIcon::Off ); + mExpandIcon.addPixmap( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpandSmall.svg" ) ).pixmap( 14, 14 ), QIcon::Selected, QIcon::Off ); + mExpandIcon.addPixmap( QgsApplication::getThemeIcon( QStringLiteral( "/mIconCollapseSmall.svg" ) ).pixmap( 14, 14 ), QIcon::Normal, QIcon::On ); + mExpandIcon.addPixmap( QgsApplication::getThemeIcon( QStringLiteral( "/mIconCollapseSmall.svg" ) ).pixmap( 14, 14 ), QIcon::Selected, QIcon::On ); } setIconSize( QSize( 18, 18 ) ); diff --git a/src/gui/raster/qgsrasterhistogramwidget.cpp b/src/gui/raster/qgsrasterhistogramwidget.cpp index 0e7d42b32d37..17b9ab12f90c 100644 --- a/src/gui/raster/qgsrasterhistogramwidget.cpp +++ b/src/gui/raster/qgsrasterhistogramwidget.cpp @@ -62,10 +62,10 @@ QgsRasterHistogramWidget::QgsRasterHistogramWidget( QgsRasterLayer* lyr, QWidget { setupUi( this ); - mSaveAsImageButton->setIcon( QgsApplication::getThemeIcon( "/mActionFileSave.svg" ) ); + mSaveAsImageButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFileSave.svg" ) ) ); mRendererWidget = nullptr; - mRendererName = "singlebandgray"; + mRendererName = QStringLiteral( "singlebandgray" ); mHistoMin = 0; mHistoMax = 0; @@ -76,11 +76,11 @@ QgsRasterHistogramWidget::QgsRasterHistogramWidget( QgsRasterLayer* lyr, QWidget mHistoMarkerMax = nullptr; QSettings settings; - mHistoShowMarkers = settings.value( "/Raster/histogram/showMarkers", false ).toBool(); + mHistoShowMarkers = settings.value( QStringLiteral( "/Raster/histogram/showMarkers" ), false ).toBool(); // mHistoLoadApplyAll = settings.value( "/Raster/histogram/loadApplyAll", false ).toBool(); - mHistoZoomToMinMax = settings.value( "/Raster/histogram/zoomToMinMax", false ).toBool(); - mHistoUpdateStyleToMinMax = settings.value( "/Raster/histogram/updateStyleToMinMax", true ).toBool(); - mHistoDrawLines = settings.value( "/Raster/histogram/drawLines", true ).toBool(); + mHistoZoomToMinMax = settings.value( QStringLiteral( "/Raster/histogram/zoomToMinMax" ), false ).toBool(); + mHistoUpdateStyleToMinMax = settings.value( QStringLiteral( "/Raster/histogram/updateStyleToMinMax" ), true ).toBool(); + mHistoDrawLines = settings.value( QStringLiteral( "/Raster/histogram/drawLines" ), true ).toBool(); // mHistoShowBands = (HistoShowBands) settings.value( "/Raster/histogram/showBands", (int) ShowAll ).toInt(); mHistoShowBands = ShowAll; @@ -177,7 +177,7 @@ QgsRasterHistogramWidget::QgsRasterHistogramWidget( QgsRasterLayer* lyr, QWidget action->setSeparator( true ); menu->addAction( action ); // should we plot as histogram instead of line plot? (int data only) - action = new QAction( "", group ); + action = new QAction( QLatin1String( "" ), group ); action->setData( QVariant( "Draw lines" ) ); if ( isInt ) { @@ -384,7 +384,7 @@ void QgsRasterHistogramWidget::refreshHistogram() // assign colors to each band, depending on the current RGB/gray band selection // grayscale QList< int > mySelectedBands = rendererSelectedBands(); - if ( mRendererName == "singlebandgray" ) + if ( mRendererName == QLatin1String( "singlebandgray" ) ) { int myGrayBand = mySelectedBands[0]; for ( int i = 1; i <= myBandCountInt; i++ ) @@ -410,7 +410,7 @@ void QgsRasterHistogramWidget::refreshHistogram() } } // RGB - else if ( mRendererName == "multibandcolor" ) + else if ( mRendererName == QLatin1String( "multibandcolor" ) ) { int myRedBand = mySelectedBands[0]; int myGreenBand = mySelectedBands[1]; @@ -675,7 +675,7 @@ void QgsRasterHistogramWidget::refreshHistogram() disconnect( mRasterLayer, SIGNAL( progressUpdate( int ) ), mHistogramProgress, SLOT( setValue( int ) ) ); stackedWidget2->setCurrentIndex( 0 ); // icon from http://findicons.com/icon/169577/14_zoom?id=171427 - mpPlot->canvas()->setCursor( QCursor( QgsApplication::getThemePixmap( "/mIconZoom.svg" ) ) ); + mpPlot->canvas()->setCursor( QCursor( QgsApplication::getThemePixmap( QStringLiteral( "/mIconZoom.svg" ) ) ) ); // on_cboHistoBand_currentIndexChanged( -1 ); QApplication::restoreOverrideCursor(); } @@ -687,7 +687,7 @@ void QgsRasterHistogramWidget::on_mSaveAsImageButton_clicked() QPair< QString, QString> myFileNameAndFilter = QgisGui::getSaveAsImageName( this, tr( "Choose a file name to save the map image as" ) ); QFileInfo myInfo( myFileNameAndFilter.first ); - if ( myInfo.baseName() != "" ) + if ( myInfo.baseName() != QLatin1String( "" ) ) { histoSaveAsImage( myFileNameAndFilter.first ); } @@ -784,61 +784,61 @@ void QgsRasterHistogramWidget::histoActionTriggered( QAction* action ) void QgsRasterHistogramWidget::histoAction( const QString &actionName, bool actionFlag ) { - if ( actionName == "" ) + if ( actionName == QLatin1String( "" ) ) return; // this approach is a bit of a hack, but this way we don't have to define slots for each action QgsDebugMsg( QString( "band = %1 action = %2" ).arg( cboHistoBand->currentIndex() + 1 ).arg( actionName ) ); // checkeable actions - if ( actionName == "Show markers" ) + if ( actionName == QLatin1String( "Show markers" ) ) { mHistoShowMarkers = actionFlag; QSettings settings; - settings.setValue( "/Raster/histogram/showMarkers", mHistoShowMarkers ); + settings.setValue( QStringLiteral( "/Raster/histogram/showMarkers" ), mHistoShowMarkers ); updateHistoMarkers(); return; } - else if ( actionName == "Zoom min_max" ) + else if ( actionName == QLatin1String( "Zoom min_max" ) ) { mHistoZoomToMinMax = actionFlag; QSettings settings; - settings.setValue( "/Raster/histogram/zoomToMinMax", mHistoZoomToMinMax ); + settings.setValue( QStringLiteral( "/Raster/histogram/zoomToMinMax" ), mHistoZoomToMinMax ); return; } - else if ( actionName == "Update min_max" ) + else if ( actionName == QLatin1String( "Update min_max" ) ) { mHistoUpdateStyleToMinMax = actionFlag; QSettings settings; - settings.setValue( "/Raster/histogram/updateStyleToMinMax", mHistoUpdateStyleToMinMax ); + settings.setValue( QStringLiteral( "/Raster/histogram/updateStyleToMinMax" ), mHistoUpdateStyleToMinMax ); return; } - else if ( actionName == "Show all" ) + else if ( actionName == QLatin1String( "Show all" ) ) { mHistoShowBands = ShowAll; // settings.setValue( "/Raster/histogram/showBands", (int)mHistoShowBands ); refreshHistogram(); return; } - else if ( actionName == "Show selected" ) + else if ( actionName == QLatin1String( "Show selected" ) ) { mHistoShowBands = ShowSelected; // settings.setValue( "/Raster/histogram/showBands", (int)mHistoShowBands ); refreshHistogram(); return; } - else if ( actionName == "Show RGB" ) + else if ( actionName == QLatin1String( "Show RGB" ) ) { mHistoShowBands = ShowRGB; // settings.setValue( "/Raster/histogram/showBands", (int)mHistoShowBands ); refreshHistogram(); return; } - else if ( actionName == "Draw lines" ) + else if ( actionName == QLatin1String( "Draw lines" ) ) { mHistoDrawLines = actionFlag; QSettings settings; - settings.setValue( "/Raster/histogram/drawLines", mHistoDrawLines ); + settings.setValue( QStringLiteral( "/Raster/histogram/drawLines" ), mHistoDrawLines ); on_btnHistoCompute_clicked(); // refresh return; } @@ -852,7 +852,7 @@ void QgsRasterHistogramWidget::histoAction( const QString &actionName, bool acti #endif // Load actions // TODO - separate calculations from rendererwidget so we can do them without - else if ( actionName.left( 5 ) == "Load " && mRendererWidget ) + else if ( actionName.left( 5 ) == QLatin1String( "Load " ) && mRendererWidget ) { QVector<int> myBands; bool ok = false; @@ -917,7 +917,7 @@ void QgsRasterHistogramWidget::histoAction( const QString &actionName, bool acti // apply current item cboHistoBand->setCurrentIndex( theBandNo - 1 ); - if ( !ok || actionName == "Load reset" ) + if ( !ok || actionName == QLatin1String( "Load reset" ) ) { leHistoMin->clear(); leHistoMax->clear(); @@ -943,7 +943,7 @@ void QgsRasterHistogramWidget::histoAction( const QString &actionName, bool acti leHistoMax->blockSignals( false ); updateHistoMarkers(); } - else if ( actionName == "Compute histogram" ) + else if ( actionName == QLatin1String( "Compute histogram" ) ) { on_btnHistoCompute_clicked(); } @@ -1052,7 +1052,7 @@ void QgsRasterHistogramWidget::on_btnHistoMax_toggled() // this is sensitive and may not always be correct, needs more testing QString findClosestTickVal( double target, const QwtScaleDiv * scale, int div = 100 ) { - if ( !scale ) return ""; + if ( !scale ) return QLatin1String( "" ); QList< double > minorTicks = scale->ticks( QwtScaleDiv::MinorTick ); QList< double > majorTicks = scale->ticks( QwtScaleDiv::MajorTick ); @@ -1139,9 +1139,9 @@ void QgsRasterHistogramWidget::updateHistoMarkers() double maxVal = mHistoMax; QString minStr = leHistoMin->text(); QString maxStr = leHistoMax->text(); - if ( minStr != "" ) + if ( minStr != QLatin1String( "" ) ) minVal = minStr.toDouble(); - if ( maxStr != "" ) + if ( maxStr != QLatin1String( "" ) ) maxVal = maxStr.toDouble(); QPen linePen = QPen( mHistoColors.at( theBandNo ) ); @@ -1188,11 +1188,11 @@ QList< int > QgsRasterHistogramWidget::rendererSelectedBands() return mySelectedBands; } - if ( mRendererName == "singlebandgray" ) + if ( mRendererName == QLatin1String( "singlebandgray" ) ) { mySelectedBands << mRendererWidget->selectedBand(); } - else if ( mRendererName == "multibandcolor" ) + else if ( mRendererName == QLatin1String( "multibandcolor" ) ) { for ( int i = 0; i <= 2; i++ ) { @@ -1210,7 +1210,7 @@ QPair< QString, QString > QgsRasterHistogramWidget::rendererMinMax( int theBandN if ( ! mRendererWidget ) return myMinMax; - if ( mRendererName == "singlebandgray" ) + if ( mRendererName == QLatin1String( "singlebandgray" ) ) { if ( theBandNo == mRendererWidget->selectedBand() ) { @@ -1218,7 +1218,7 @@ QPair< QString, QString > QgsRasterHistogramWidget::rendererMinMax( int theBandN myMinMax.second = mRendererWidget->max(); } } - else if ( mRendererName == "multibandcolor" ) + else if ( mRendererName == QLatin1String( "multibandcolor" ) ) { for ( int i = 0; i <= 2; i++ ) { diff --git a/src/gui/raster/qgsrasterminmaxwidget.cpp b/src/gui/raster/qgsrasterminmaxwidget.cpp index 2537a8c1eaf6..6433e4aca2c3 100644 --- a/src/gui/raster/qgsrasterminmaxwidget.cpp +++ b/src/gui/raster/qgsrasterminmaxwidget.cpp @@ -36,18 +36,18 @@ QgsRasterMinMaxWidget::QgsRasterMinMaxWidget( QgsRasterLayer* theLayer, QWidget // set contrast enhancement setting to default // ideally we should set it actual method last used to get min/max, but there is no way to know currently - QString contrastEnchacementLimits = mySettings.value( "/Raster/defaultContrastEnhancementLimits", "CumulativeCut" ).toString(); - if ( contrastEnchacementLimits == "MinMax" ) + QString contrastEnchacementLimits = mySettings.value( QStringLiteral( "/Raster/defaultContrastEnhancementLimits" ), "CumulativeCut" ).toString(); + if ( contrastEnchacementLimits == QLatin1String( "MinMax" ) ) mMinMaxRadioButton->setChecked( true ); - else if ( contrastEnchacementLimits == "StdDev" ) + else if ( contrastEnchacementLimits == QLatin1String( "StdDev" ) ) mStdDevRadioButton->setChecked( true ); - double myLower = 100.0 * mySettings.value( "/Raster/cumulativeCutLower", QString::number( QgsRasterLayer::CUMULATIVE_CUT_LOWER ) ).toDouble(); - double myUpper = 100.0 * mySettings.value( "/Raster/cumulativeCutUpper", QString::number( QgsRasterLayer::CUMULATIVE_CUT_UPPER ) ).toDouble(); + double myLower = 100.0 * mySettings.value( QStringLiteral( "/Raster/cumulativeCutLower" ), QString::number( QgsRasterLayer::CUMULATIVE_CUT_LOWER ) ).toDouble(); + double myUpper = 100.0 * mySettings.value( QStringLiteral( "/Raster/cumulativeCutUpper" ), QString::number( QgsRasterLayer::CUMULATIVE_CUT_UPPER ) ).toDouble(); mCumulativeCutLowerDoubleSpinBox->setValue( myLower ); mCumulativeCutUpperDoubleSpinBox->setValue( myUpper ); - mStdDevSpinBox->setValue( mySettings.value( "/Raster/defaultStandardDeviation", 2.0 ).toDouble() ); + mStdDevSpinBox->setValue( mySettings.value( QStringLiteral( "/Raster/defaultStandardDeviation" ), 2.0 ).toDouble() ); } QgsRasterMinMaxWidget::~QgsRasterMinMaxWidget() diff --git a/src/gui/raster/qgsrasterrendererwidget.cpp b/src/gui/raster/qgsrasterrendererwidget.cpp index 1e5793e97b6a..61f8969ac319 100644 --- a/src/gui/raster/qgsrasterrendererwidget.cpp +++ b/src/gui/raster/qgsrasterrendererwidget.cpp @@ -47,9 +47,9 @@ QString QgsRasterRendererWidget::displayBandName( int band ) const name = provider->generateBandName( band ); QString colorInterp = provider->colorInterpretationName( band ); - if ( colorInterp != "Undefined" ) + if ( colorInterp != QLatin1String( "Undefined" ) ) { - name.append( QString( " (%1)" ).arg( colorInterp ) ); + name.append( QStringLiteral( " (%1)" ).arg( colorInterp ) ); } return name; } diff --git a/src/gui/raster/qgsrastertransparencywidget.cpp b/src/gui/raster/qgsrastertransparencywidget.cpp index 3a92370729af..1df1eafff4a8 100644 --- a/src/gui/raster/qgsrastertransparencywidget.cpp +++ b/src/gui/raster/qgsrastertransparencywidget.cpp @@ -87,9 +87,9 @@ void QgsRasterTransparencyWidget::syncToLayer() bandName = provider->generateBandName( i ); QString colorInterp = provider->colorInterpretationName( i ); - if ( colorInterp != "Undefined" ) + if ( colorInterp != QLatin1String( "Undefined" ) ) { - bandName.append( QString( " (%1)" ).arg( colorInterp ) ); + bandName.append( QStringLiteral( " (%1)" ).arg( colorInterp ) ); } cboxTransparencyBand->addItem( bandName, i ); } @@ -237,11 +237,11 @@ void QgsRasterTransparencyWidget::on_pbnDefaultValues_clicked() void QgsRasterTransparencyWidget::on_pbnExportTransparentPixelValues_clicked() { QSettings myQSettings; - QString myLastDir = myQSettings.value( "lastRasterFileFilterDir", QDir::homePath() ).toString(); + QString myLastDir = myQSettings.value( QStringLiteral( "lastRasterFileFilterDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getSaveFileName( this, tr( "Save file" ), myLastDir, tr( "Textfile" ) + " (*.txt)" ); if ( !myFileName.isEmpty() ) { - if ( !myFileName.endsWith( ".txt", Qt::CaseInsensitive ) ) + if ( !myFileName.endsWith( QLatin1String( ".txt" ), Qt::CaseInsensitive ) ) { myFileName = myFileName + ".txt"; } @@ -287,7 +287,7 @@ void QgsRasterTransparencyWidget::on_pbnImportTransparentPixelValues_clicked() bool myImportError = false; QString myBadLines; QSettings myQSettings; - QString myLastDir = myQSettings.value( "lastRasterFileFilterDir", QDir::homePath() ).toString(); + QString myLastDir = myQSettings.value( QStringLiteral( "lastRasterFileFilterDir" ), QDir::homePath() ).toString(); QString myFileName = QFileDialog::getOpenFileName( this, tr( "Open file" ), myLastDir, tr( "Textfile" ) + " (*.txt)" ); QFile myInputFile( myFileName ); if ( myInputFile.open( QFile::ReadOnly ) ) diff --git a/src/gui/raster/qgsrendererrasterpropertieswidget.cpp b/src/gui/raster/qgsrendererrasterpropertieswidget.cpp index 0af84f433fcf..3d8ae246f85b 100644 --- a/src/gui/raster/qgsrendererrasterpropertieswidget.cpp +++ b/src/gui/raster/qgsrendererrasterpropertieswidget.cpp @@ -37,11 +37,11 @@ static void _initRendererWidgetFunctions() if ( initialized ) return; - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "paletted", QgsPalettedRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "multibandcolor", QgsMultiBandColorRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "singlebandpseudocolor", QgsSingleBandPseudoColorRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "singlebandgray", QgsSingleBandGrayRendererWidget::create ); - QgsRasterRendererRegistry::instance()->insertWidgetFunction( "hillshade", QgsHillshadeRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "paletted" ), QgsPalettedRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "multibandcolor" ), QgsMultiBandColorRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "singlebandpseudocolor" ), QgsSingleBandPseudoColorRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "singlebandgray" ), QgsSingleBandGrayRendererWidget::create ); + QgsRasterRendererRegistry::instance()->insertWidgetFunction( QStringLiteral( "hillshade" ), QgsHillshadeRendererWidget::create ); initialized = true; } @@ -195,8 +195,8 @@ void QgsRendererRasterPropertiesWidget::syncToLayer( QgsRasterLayer* layer ) { if ( QgsRasterRendererRegistry::instance()->rendererData( name, entry ) ) { - if (( mRasterLayer->rasterType() != QgsRasterLayer::ColorLayer && entry.name != "singlebandcolordata" ) || - ( mRasterLayer->rasterType() == QgsRasterLayer::ColorLayer && entry.name == "singlebandcolordata" ) ) + if (( mRasterLayer->rasterType() != QgsRasterLayer::ColorLayer && entry.name != QLatin1String( "singlebandcolordata" ) ) || + ( mRasterLayer->rasterType() == QgsRasterLayer::ColorLayer && entry.name == QLatin1String( "singlebandcolordata" ) ) ) { cboRenderers->addItem( entry.icon(), entry.visibleName, entry.name ); } @@ -219,7 +219,7 @@ void QgsRendererRasterPropertiesWidget::syncToLayer( QgsRasterLayer* layer ) } btnColorizeColor->setColorDialogTitle( tr( "Select color" ) ); - btnColorizeColor->setContext( "symbology" ); + btnColorizeColor->setContext( QStringLiteral( "symbology" ) ); // Hue and saturation color control const QgsHueSaturationFilter* hueSaturationFilter = mRasterLayer->hueSaturationFilter(); @@ -249,11 +249,11 @@ void QgsRendererRasterPropertiesWidget::syncToLayer( QgsRasterLayer* layer ) const QgsRasterResampler* zoomedInResampler = resampleFilter->zoomedInResampler(); if ( zoomedInResampler ) { - if ( zoomedInResampler->type() == "bilinear" ) + if ( zoomedInResampler->type() == QLatin1String( "bilinear" ) ) { mZoomedInResamplingComboBox->setCurrentIndex( 1 ); } - else if ( zoomedInResampler->type() == "cubic" ) + else if ( zoomedInResampler->type() == QLatin1String( "cubic" ) ) { mZoomedInResamplingComboBox->setCurrentIndex( 2 ); } @@ -266,7 +266,7 @@ void QgsRendererRasterPropertiesWidget::syncToLayer( QgsRasterLayer* layer ) const QgsRasterResampler* zoomedOutResampler = resampleFilter->zoomedOutResampler(); if ( zoomedOutResampler ) { - if ( zoomedOutResampler->type() == "bilinear" ) //bilinear resampler does averaging when zooming out + if ( zoomedOutResampler->type() == QLatin1String( "bilinear" ) ) //bilinear resampler does averaging when zooming out { mZoomedOutResamplingComboBox->setCurrentIndex( 1 ); } diff --git a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp index dac7fb27bca5..437711a42c09 100644 --- a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp +++ b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp @@ -44,7 +44,7 @@ QgsSingleBandPseudoColorRendererWidget::QgsSingleBandPseudoColorRendererWidget( mColormapTreeWidget->setColumnWidth( ColorColumn, 50 ); - QString defaultPalette = settings.value( "/Raster/defaultPalette", "Spectral" ).toString(); + QString defaultPalette = settings.value( QStringLiteral( "/Raster/defaultPalette" ), "Spectral" ).toString(); mColorRampComboBox->populate( QgsStyle::defaultStyle() ); @@ -286,7 +286,7 @@ void QgsSingleBandPseudoColorRendererWidget::setUnitFromLabels() void QgsSingleBandPseudoColorRendererWidget::on_mAddEntryButton_clicked() { QgsTreeWidgetItemObject* newItem = new QgsTreeWidgetItemObject( mColormapTreeWidget ); - newItem->setText( ValueColumn, "0" ); + newItem->setText( ValueColumn, QStringLiteral( "0" ) ); newItem->setBackground( ColorColumn, QBrush( QColor( Qt::magenta ) ) ); newItem->setText( LabelColumn, QString() ); newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable ); @@ -522,7 +522,7 @@ void QgsSingleBandPseudoColorRendererWidget::on_mColorRampComboBox_currentIndexC { Q_UNUSED( index ); QSettings settings; - settings.setValue( "/Raster/defaultPalette", mColorRampComboBox->currentText() ); + settings.setValue( QStringLiteral( "/Raster/defaultPalette" ), mColorRampComboBox->currentText() ); QScopedPointer< QgsColorRamp > ramp( mColorRampComboBox->currentColorRamp() ); if ( !ramp ) @@ -582,7 +582,7 @@ void QgsSingleBandPseudoColorRendererWidget::on_mLoadFromFileButton_clicked() bool importError = false; QString badLines; QSettings settings; - QString lastDir = settings.value( "lastColorMapDir", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "lastColorMapDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, tr( "Open file" ), lastDir, tr( "Textfile (*.txt)" ) ); QFile inputFile( fileName ); if ( inputFile.open( QFile::ReadOnly ) ) @@ -604,16 +604,16 @@ void QgsSingleBandPseudoColorRendererWidget::on_mLoadFromFileButton_clicked() { if ( !inputLine.simplified().startsWith( '#' ) ) { - if ( inputLine.contains( "INTERPOLATION", Qt::CaseInsensitive ) ) + if ( inputLine.contains( QLatin1String( "INTERPOLATION" ), Qt::CaseInsensitive ) ) { inputStringComponents = inputLine.split( ':' ); if ( inputStringComponents.size() == 2 ) { - if ( inputStringComponents[1].trimmed().toUpper().compare( "INTERPOLATED", Qt::CaseInsensitive ) == 0 ) + if ( inputStringComponents[1].trimmed().toUpper().compare( QLatin1String( "INTERPOLATED" ), Qt::CaseInsensitive ) == 0 ) { mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findData( QgsColorRampShader::INTERPOLATED ) ); } - else if ( inputStringComponents[1].trimmed().toUpper().compare( "DISCRETE", Qt::CaseInsensitive ) == 0 ) + else if ( inputStringComponents[1].trimmed().toUpper().compare( QLatin1String( "DISCRETE" ), Qt::CaseInsensitive ) == 0 ) { mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findData( QgsColorRampShader::DISCRETE ) ); } @@ -652,7 +652,7 @@ void QgsSingleBandPseudoColorRendererWidget::on_mLoadFromFileButton_clicked() populateColormapTreeWidget( colorRampItems ); QFileInfo fileInfo( fileName ); - settings.setValue( "lastColorMapDir", fileInfo.absoluteDir().absolutePath() ); + settings.setValue( QStringLiteral( "lastColorMapDir" ), fileInfo.absoluteDir().absolutePath() ); if ( importError ) { @@ -669,11 +669,11 @@ void QgsSingleBandPseudoColorRendererWidget::on_mLoadFromFileButton_clicked() void QgsSingleBandPseudoColorRendererWidget::on_mExportToFileButton_clicked() { QSettings settings; - QString lastDir = settings.value( "lastColorMapDir", QDir::homePath() ).toString(); + QString lastDir = settings.value( QStringLiteral( "lastColorMapDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getSaveFileName( this, tr( "Save file" ), lastDir, tr( "Textfile (*.txt)" ) ); if ( !fileName.isEmpty() ) { - if ( !fileName.endsWith( ".txt", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".txt" ), Qt::CaseInsensitive ) ) { fileName = fileName + ".txt"; } @@ -724,7 +724,7 @@ void QgsSingleBandPseudoColorRendererWidget::on_mExportToFileButton_clicked() outputFile.close(); QFileInfo fileInfo( fileName ); - settings.setValue( "lastColorMapDir", fileInfo.absoluteDir().absolutePath() ); + settings.setValue( QStringLiteral( "lastColorMapDir" ), fileInfo.absoluteDir().absolutePath() ); } else { @@ -743,7 +743,7 @@ void QgsSingleBandPseudoColorRendererWidget::on_mColormapTreeWidget_itemDoubleCl if ( column == ColorColumn ) { item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable ); - QColor newColor = QgsColorDialog::getColor( item->background( column ).color(), this, "Change color", true ); + QColor newColor = QgsColorDialog::getColor( item->background( column ).color(), this, QStringLiteral( "Change color" ), true ); if ( newColor.isValid() ) { item->setBackground( ColorColumn, QBrush( newColor ) ); diff --git a/src/gui/symbology-ng/qgs25drendererwidget.cpp b/src/gui/symbology-ng/qgs25drendererwidget.cpp index defbe8217402..1033944655f0 100644 --- a/src/gui/symbology-ng/qgs25drendererwidget.cpp +++ b/src/gui/symbology-ng/qgs25drendererwidget.cpp @@ -41,13 +41,13 @@ Qgs25DRendererWidget::Qgs25DRendererWidget( QgsVectorLayer* layer, QgsStyle* sty mWallColorButton->setColorDialogTitle( tr( "Select wall color" ) ); mWallColorButton->setAllowAlpha( true ); - mWallColorButton->setContext( "symbology" ); + mWallColorButton->setContext( QStringLiteral( "symbology" ) ); mRoofColorButton->setColorDialogTitle( tr( "Select roof color" ) ); mRoofColorButton->setAllowAlpha( true ); - mRoofColorButton->setContext( "symbology" ); + mRoofColorButton->setContext( QStringLiteral( "symbology" ) ); mShadowColorButton->setColorDialogTitle( tr( "Select shadow color" ) ); mShadowColorButton->setAllowAlpha( true ); - mShadowColorButton->setContext( "symbology" ); + mShadowColorButton->setContext( QStringLiteral( "symbology" ) ); if ( renderer ) { @@ -57,11 +57,11 @@ Qgs25DRendererWidget::Qgs25DRendererWidget( QgsVectorLayer* layer, QgsStyle* sty mHeightWidget->setLayer( layer ); QgsExpressionContextScope* scope = QgsExpressionContextUtils::layerScope( mLayer ); - QVariant height = scope->variable( "qgis_25d_height" ); - QVariant angle = scope->variable( "qgis_25d_angle" ); + QVariant height = scope->variable( QStringLiteral( "qgis_25d_height" ) ); + QVariant angle = scope->variable( QStringLiteral( "qgis_25d_angle" ) ); delete scope; - mHeightWidget->setField( height.isNull() ? "10" : height.toString() ); + mHeightWidget->setField( height.isNull() ? QStringLiteral( "10" ) : height.toString() ); mAngleWidget->setValue( angle.isNull() ? 70 : angle.toDouble() ); mWallColorButton->setColor( mRenderer->wallColor() ); mRoofColorButton->setColor( mRenderer->roofColor() ); @@ -100,8 +100,8 @@ void Qgs25DRendererWidget::apply() { if ( mHeightWidget ) { - QgsExpressionContextUtils::setLayerVariable( mLayer, "qgis_25d_height", mHeightWidget->currentText() ); - QgsExpressionContextUtils::setLayerVariable( mLayer, "qgis_25d_angle", mAngleWidget->value() ); + QgsExpressionContextUtils::setLayerVariable( mLayer, QStringLiteral( "qgis_25d_height" ), mHeightWidget->currentText() ); + QgsExpressionContextUtils::setLayerVariable( mLayer, QStringLiteral( "qgis_25d_angle" ), mAngleWidget->value() ); emit layerVariablesChanged(); } diff --git a/src/gui/symbology-ng/qgsarrowsymbollayerwidget.cpp b/src/gui/symbology-ng/qgsarrowsymbollayerwidget.cpp index e1021a0dac5a..cffe504cc2dc 100644 --- a/src/gui/symbology-ng/qgsarrowsymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgsarrowsymbollayerwidget.cpp @@ -34,7 +34,7 @@ QgsArrowSymbolLayerWidget::QgsArrowSymbolLayerWidget( const QgsVectorLayer* vl, void QgsArrowSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( !layer || layer->layerType() != "ArrowLine" ) + if ( !layer || layer->layerType() != QLatin1String( "ArrowLine" ) ) { return; } @@ -66,13 +66,13 @@ void QgsArrowSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) mCurvedArrowChck->setChecked( mLayer->isCurved() ); mRepeatArrowChck->setChecked( mLayer->isRepeated() ); - registerDataDefinedButton( mArrowWidthDDBtn, "arrow_width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mArrowStartWidthDDBtn, "arrow_start_width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mHeadWidthDDBtn, "head_length", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mHeadHeightDDBtn, "head_thickness", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mHeadTypeDDBtn, "head_type", QgsDataDefinedButton::Int, QgsDataDefinedButton::intDesc() ); - registerDataDefinedButton( mArrowTypeDDBtn, "arrow_type", QgsDataDefinedButton::Int, QgsDataDefinedButton::intDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::String, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mArrowWidthDDBtn, QStringLiteral( "arrow_width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mArrowStartWidthDDBtn, QStringLiteral( "arrow_start_width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mHeadWidthDDBtn, QStringLiteral( "head_length" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mHeadHeightDDBtn, QStringLiteral( "head_thickness" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mHeadTypeDDBtn, QStringLiteral( "head_type" ), QgsDataDefinedButton::Int, QgsDataDefinedButton::intDesc() ); + registerDataDefinedButton( mArrowTypeDDBtn, QStringLiteral( "arrow_type" ), QgsDataDefinedButton::Int, QgsDataDefinedButton::intDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::String, QgsDataDefinedButton::doubleDesc() ); } diff --git a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp index f506486a50e6..0f007091f23d 100644 --- a/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgscategorizedsymbolrendererwidget.cpp @@ -47,7 +47,7 @@ QgsCategorizedSymbolRendererModel::QgsCategorizedSymbolRendererModel( QObject * parent ) : QAbstractItemModel( parent ) , mRenderer( nullptr ) - , mMimeFormat( "application/x-qgscategorizedsymbolrendererv2model" ) + , mMimeFormat( QStringLiteral( "application/x-qgscategorizedsymbolrendererv2model" ) ) { } @@ -399,7 +399,7 @@ QgsCategorizedSymbolRendererWidget::QgsCategorizedSymbolRendererWidget( QgsVecto } if ( !mRenderer ) { - mRenderer = new QgsCategorizedSymbolRenderer( "", QgsCategoryList() ); + mRenderer = new QgsCategorizedSymbolRenderer( QLatin1String( "" ), QgsCategoryList() ); } QString attrName = mRenderer->classAttribute(); @@ -419,8 +419,8 @@ QgsCategorizedSymbolRendererWidget::QgsCategorizedSymbolRendererWidget( QgsVecto } // set project default color ramp - QString defaultColorRamp = QgsProject::instance()->readEntry( "DefaultStyles", "/ColorRamp", "" ); - if ( defaultColorRamp != "" ) + QString defaultColorRamp = QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/ColorRamp" ), QLatin1String( "" ) ); + if ( defaultColorRamp != QLatin1String( "" ) ) { int index = cboCategorizedColorRamp->findText( defaultColorRamp, Qt::MatchCaseSensitive ); if ( index >= 0 ) @@ -934,7 +934,7 @@ int QgsCategorizedSymbolRendererWidget::matchToSymbols( QgsStyle* style ) void QgsCategorizedSymbolRendererWidget::matchToSymbolsFromXml() { QSettings settings; - QString openFileDir = settings.value( "UI/lastMatchToSymbolsDir", QDir::homePath() ).toString(); + QString openFileDir = settings.value( QStringLiteral( "UI/lastMatchToSymbolsDir" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getOpenFileName( this, tr( "Match to symbols from file" ), openFileDir, tr( "XML files (*.xml *XML)" ) ); @@ -944,7 +944,7 @@ void QgsCategorizedSymbolRendererWidget::matchToSymbolsFromXml() } QFileInfo openFileInfo( fileName ); - settings.setValue( "UI/lastMatchToSymbolsDir", openFileInfo.absolutePath() ); + settings.setValue( QStringLiteral( "UI/lastMatchToSymbolsDir" ), openFileInfo.absolutePath() ); QgsStyle importedStyle; if ( !importedStyle.importXml( fileName ) ) diff --git a/src/gui/symbology-ng/qgscolorrampcombobox.cpp b/src/gui/symbology-ng/qgscolorrampcombobox.cpp index af79978c3ca5..e4f4a93ab620 100644 --- a/src/gui/symbology-ng/qgscolorrampcombobox.cpp +++ b/src/gui/symbology-ng/qgscolorrampcombobox.cpp @@ -54,7 +54,7 @@ void QgsColorRampComboBox::populate( QgsStyle* style ) { QScopedPointer< QgsColorRamp > ramp( style->colorRamp( *it ) ); - if ( !mShowGradientOnly || ramp->type() == "gradient" ) + if ( !mShowGradientOnly || ramp->type() == QLatin1String( "gradient" ) ) { QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.data(), rampIconSize ); @@ -76,7 +76,7 @@ QgsColorRamp* QgsColorRampComboBox::currentColorRamp() const { return new QgsRandomColorRamp(); } - else if ( rampName == "[source]" && mSourceColorRamp ) + else if ( rampName == QLatin1String( "[source]" ) && mSourceColorRamp ) return mSourceColorRamp->clone(); else return mStyle->colorRamp( rampName ); @@ -94,10 +94,10 @@ void QgsColorRampComboBox::setSourceColorRamp( QgsColorRamp* sourceRamp ) mSourceColorRamp = sourceRamp->clone(); QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( mSourceColorRamp, rampIconSize ); - if ( itemText( 0 ) == "[source]" ) + if ( itemText( 0 ) == QLatin1String( "[source]" ) ) setItemIcon( 0, icon ); else - insertItem( 0, icon, "[source]" ); + insertItem( 0, icon, QStringLiteral( "[source]" ) ); setCurrentIndex( 0 ); } @@ -114,7 +114,7 @@ void QgsColorRampComboBox::colorRampChanged( int index ) } else { - rampName = QgsStyleManagerDialog::addColorRampStatic( this, mStyle, "Gradient" ); + rampName = QgsStyleManagerDialog::addColorRampStatic( this, mStyle, QStringLiteral( "Gradient" ) ); } if ( rampName.isEmpty() ) return; @@ -143,7 +143,7 @@ void QgsColorRampComboBox::editSourceRamp() if ( !currentRamp ) return; - if ( currentRamp->type() == "gradient" ) + if ( currentRamp->type() == QLatin1String( "gradient" ) ) { QgsGradientColorRamp* gradRamp = static_cast<QgsGradientColorRamp*>( currentRamp.data() ); QgsGradientColorRampDialog dlg( *gradRamp, this ); @@ -153,7 +153,7 @@ void QgsColorRampComboBox::editSourceRamp() emit sourceRampEdited(); } } - else if ( currentRamp->type() == "random" ) + else if ( currentRamp->type() == QLatin1String( "random" ) ) { QgsLimitedRandomColorRamp* randRamp = static_cast<QgsLimitedRandomColorRamp*>( currentRamp.data() ); if ( panelMode ) @@ -173,7 +173,7 @@ void QgsColorRampComboBox::editSourceRamp() } } } - else if ( currentRamp->type() == "preset" ) + else if ( currentRamp->type() == QLatin1String( "preset" ) ) { QgsPresetSchemeColorRamp* presetRamp = static_cast<QgsPresetSchemeColorRamp*>( currentRamp.data() ); if ( panelMode ) @@ -193,7 +193,7 @@ void QgsColorRampComboBox::editSourceRamp() } } } - else if ( currentRamp->type() == "colorbrewer" ) + else if ( currentRamp->type() == QLatin1String( "colorbrewer" ) ) { QgsColorBrewerColorRamp* brewerRamp = static_cast<QgsColorBrewerColorRamp*>( currentRamp.data() ); if ( panelMode ) @@ -213,7 +213,7 @@ void QgsColorRampComboBox::editSourceRamp() } } } - else if ( currentRamp->type() == "cpt-city" ) + else if ( currentRamp->type() == QLatin1String( "cpt-city" ) ) { QgsCptCityColorRamp* cptCityRamp = static_cast<QgsCptCityColorRamp*>( currentRamp.data() ); QgsCptCityColorRampDialog dlg( *cptCityRamp, this ); diff --git a/src/gui/symbology-ng/qgscptcitycolorrampdialog.cpp b/src/gui/symbology-ng/qgscptcitycolorrampdialog.cpp index 7e0883398493..d0b22fbe4745 100644 --- a/src/gui/symbology-ng/qgscptcitycolorrampdialog.cpp +++ b/src/gui/symbology-ng/qgscptcitycolorrampdialog.cpp @@ -46,9 +46,9 @@ QgsCptCityColorRampDialog::QgsCptCityColorRampDialog( const QgsCptCityColorRamp& buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); QSettings settings; - restoreGeometry( settings.value( "/Windows/CptCityColorRampV2Dialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/CptCityColorRampV2Dialog/geometry" ) ).toByteArray() ); mSplitter->setSizes( QList<int>() << 250 << 550 ); - mSplitter->restoreState( settings.value( "/Windows/CptCityColorRampV2Dialog/splitter" ).toByteArray() ); + mSplitter->restoreState( settings.value( QStringLiteral( "/Windows/CptCityColorRampV2Dialog/splitter" ) ).toByteArray() ); mModel = mAuthorsModel = mSelectionsModel = nullptr; //mListModel = 0; mTreeFilter = nullptr; @@ -74,8 +74,8 @@ QgsCptCityColorRampDialog::QgsCptCityColorRampDialog( const QgsCptCityColorRamp& "and unzip it to your QGIS settings directory [%1] .\n\n" "This file can be found at [%2]\nand current file is [%3]" ).arg( QgsApplication::qgisSettingsDirPath(), - "http://soliton.vm.bytemark.co.uk/pub/cpt-city/pkg/", - "http://soliton.vm.bytemark.co.uk/pub/cpt-city/pkg/cpt-city-svg-2.07.zip" ); + QStringLiteral( "http://soliton.vm.bytemark.co.uk/pub/cpt-city/pkg/" ), + QStringLiteral( "http://soliton.vm.bytemark.co.uk/pub/cpt-city/pkg/cpt-city-svg-2.07.zip" ) ); edit->setText( helpText ); mStackedWidget->addWidget( edit ); mStackedWidget->setCurrentIndex( 1 ); @@ -226,26 +226,26 @@ void QgsCptCityColorRampDialog::updateTreeView( QgsCptCityDataItem *item, bool r { if ( resetRamp ) { - mRamp.setName( "", "" ); + mRamp.setName( QLatin1String( "" ), QLatin1String( "" ) ); QgsDebugMsg( QString( "variant= %1 - %2 variants" ).arg( mRamp.variantName() ).arg( mRamp.variantList().count() ) ); - lblSchemeName->setText( "" ); + lblSchemeName->setText( QLatin1String( "" ) ); populateVariants(); } updateListWidget( item ); lblSchemePath->setText( item->path() ); - lblCollectionInfo->setText( QString( "%1 (%2)" ).arg( item->info() ).arg( item->leafCount() ) ); + lblCollectionInfo->setText( QStringLiteral( "%1 (%2)" ).arg( item->info() ).arg( item->leafCount() ) ); updateCopyingInfo( mArchive->copyingInfo( mArchive->copyingFileName( item->path() ) ) ); } else if ( item->type() == QgsCptCityDataItem::Selection ) { - lblSchemePath->setText( "" ); + lblSchemePath->setText( QLatin1String( "" ) ); clearCopyingInfo(); updateListWidget( item ); - lblCollectionInfo->setText( QString( "%1 (%2)" ).arg( item->info() ).arg( item->leafCount() ) ); + lblCollectionInfo->setText( QStringLiteral( "%1 (%2)" ).arg( item->info() ).arg( item->leafCount() ) ); } else if ( item->type() == QgsCptCityDataItem::AllRamps ) { - lblSchemePath->setText( "" ); + lblSchemePath->setText( QLatin1String( "" ) ); clearCopyingInfo(); updateListWidget( item ); lblCollectionInfo->setText( tr( "All Ramps (%1)" ).arg( item->leafCount() ) ); @@ -277,7 +277,7 @@ void QgsCptCityColorRampDialog::on_mListWidget_itemSelectionChanged() { if ( mListWidget->selectedItems().isEmpty() ) { - mRamp.setName( "", "" ); + mRamp.setName( QLatin1String( "" ), QLatin1String( "" ) ); } } @@ -361,14 +361,14 @@ void QgsCptCityColorRampDialog::on_pbtnLicenseDetails_pressed() } } textEdit->insertPlainText( title + "\n\n" ); - textEdit->insertPlainText( "===================" ); - textEdit->insertPlainText( " copying " ); - textEdit->insertPlainText( "===================\n" ); + textEdit->insertPlainText( QStringLiteral( "===================" ) ); + textEdit->insertPlainText( QStringLiteral( " copying " ) ); + textEdit->insertPlainText( QStringLiteral( "===================\n" ) ); textEdit->insertPlainText( copyText ); - textEdit->insertPlainText( "\n" ); - textEdit->insertPlainText( "==================" ); - textEdit->insertPlainText( " description " ); - textEdit->insertPlainText( "==================\n" ); + textEdit->insertPlainText( QStringLiteral( "\n" ) ); + textEdit->insertPlainText( QStringLiteral( "==================" ) ); + textEdit->insertPlainText( QStringLiteral( " description " ) ); + textEdit->insertPlainText( QStringLiteral( "==================\n" ) ); textEdit->insertPlainText( descText ); textEdit->moveCursor( QTextCursor::Start ); @@ -380,11 +380,11 @@ void QgsCptCityColorRampDialog::updatePreview( bool clear ) { QSize size = lblPreview->size(); - if ( clear || mRamp.schemeName() == "" ) + if ( clear || mRamp.schemeName() == QLatin1String( "" ) ) { - lblSchemeName->setText( "" ); - lblSchemePath->setText( "" ); - lblLicensePreview->setText( "" ); + lblSchemeName->setText( QLatin1String( "" ) ); + lblSchemePath->setText( QLatin1String( "" ) ); + lblLicensePreview->setText( QLatin1String( "" ) ); QPixmap blankPixmap( size ); blankPixmap.fill( Qt::transparent ); lblPreview->setPixmap( blankPixmap ); @@ -412,27 +412,27 @@ void QgsCptCityColorRampDialog::clearCopyingInfo() void QgsCptCityColorRampDialog::updateCopyingInfo( const QMap< QString, QString >& copyingMap ) { - QString authorStr = copyingMap.value( "authors" ); + QString authorStr = copyingMap.value( QStringLiteral( "authors" ) ); if ( authorStr.length() > 80 ) - authorStr.replace( authorStr.indexOf( ' ', 80 ), 1, "\n" ); + authorStr.replace( authorStr.indexOf( ' ', 80 ), 1, QStringLiteral( "\n" ) ); lblAuthorName->setText( authorStr ); - QString licenseStr = copyingMap.value( "license/informal" ); - if ( copyingMap.contains( "license/year" ) ) - licenseStr += " (" + copyingMap.value( "license/year" ) + ')'; + QString licenseStr = copyingMap.value( QStringLiteral( "license/informal" ) ); + if ( copyingMap.contains( QStringLiteral( "license/year" ) ) ) + licenseStr += " (" + copyingMap.value( QStringLiteral( "license/year" ) ) + ')'; if ( licenseStr.length() > 80 ) - licenseStr.replace( licenseStr.indexOf( ' ', 80 ), 1, "\n" ); - if ( copyingMap.contains( "license/url" ) ) - licenseStr += "\n[ " + copyingMap.value( "license/url" ) + " ]"; + licenseStr.replace( licenseStr.indexOf( ' ', 80 ), 1, QStringLiteral( "\n" ) ); + if ( copyingMap.contains( QStringLiteral( "license/url" ) ) ) + licenseStr += "\n[ " + copyingMap.value( QStringLiteral( "license/url" ) ) + " ]"; else licenseStr += '\n'; lblLicenseName->setText( licenseStr ); - licenseStr.replace( '\n', " " ); + licenseStr.replace( '\n', QLatin1String( " " ) ); lblLicensePreview->setText( licenseStr ); lblLicensePreview->setCursorPosition( 0 ); - if ( copyingMap.contains( "src/link" ) ) - lblSrcLink->setText( copyingMap.value( "src/link" ) ); + if ( copyingMap.contains( QStringLiteral( "src/link" ) ) ) + lblSrcLink->setText( copyingMap.value( QStringLiteral( "src/link" ) ) ); else - lblSrcLink->setText( "" ); + lblSrcLink->setText( QLatin1String( "" ) ); } void QgsCptCityColorRampDialog::on_cboVariantName_currentIndexChanged( int index ) @@ -449,8 +449,8 @@ void QgsCptCityColorRampDialog::onFinished() { // save settings QSettings settings; - settings.setValue( "/Windows/CptCityColorRampV2Dialog/geometry", saveGeometry() ); - settings.setValue( "/Windows/CptCityColorRampV2Dialog/splitter", mSplitter->saveState() ); + settings.setValue( QStringLiteral( "/Windows/CptCityColorRampV2Dialog/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/CptCityColorRampV2Dialog/splitter" ), mSplitter->saveState() ); } void QgsCptCityColorRampDialog::on_buttonBox_helpRequested() @@ -469,7 +469,7 @@ void QgsCptCityColorRampDialog::updateUi() { // look for item, if not found in selections archive, look for in authors QgsDebugMsg( "looking for ramp " + mRamp.schemeName() ); - if ( mRamp.schemeName() != "" ) + if ( mRamp.schemeName() != QLatin1String( "" ) ) { bool found = updateRamp(); if ( ! found ) @@ -576,7 +576,7 @@ bool QgsCptCityColorRampDialog::updateRamp() updatePreview( true ); QgsDebugMsg( "schemeName= " + mRamp.schemeName() ); - if ( mRamp.schemeName() == "" ) + if ( mRamp.schemeName() == QLatin1String( "" ) ) { showAll(); return false; @@ -634,7 +634,7 @@ bool QgsCptCityColorRampDialog::updateRamp() void QgsCptCityColorRampDialog::showAll() { - QModelIndex modelIndex = mModel->findPath( "" ); + QModelIndex modelIndex = mModel->findPath( QLatin1String( "" ) ); if ( modelIndex != QModelIndex() ) { QModelIndex selIndex = mTreeFilter->mapFromSource( modelIndex ); diff --git a/src/gui/symbology-ng/qgsdashspacedialog.cpp b/src/gui/symbology-ng/qgsdashspacedialog.cpp index b518297d17aa..4fd3acb025cf 100644 --- a/src/gui/symbology-ng/qgsdashspacedialog.cpp +++ b/src/gui/symbology-ng/qgsdashspacedialog.cpp @@ -60,8 +60,8 @@ void QgsDashSpaceDialog::on_mAddButton_clicked() //add new (default) item QTreeWidgetItem* entry = new QTreeWidgetItem(); entry->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled ); - entry->setText( 0, "5" ); - entry->setText( 1, "2" ); + entry->setText( 0, QStringLiteral( "5" ) ); + entry->setText( 1, QStringLiteral( "2" ) ); mDashSpaceTreeWidget->addTopLevelItem( entry ); } diff --git a/src/gui/symbology-ng/qgsellipsesymbollayerwidget.cpp b/src/gui/symbology-ng/qgsellipsesymbollayerwidget.cpp index d8029d6d8f81..2dee9c7676d8 100644 --- a/src/gui/symbology-ng/qgsellipsesymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgsellipsesymbollayerwidget.cpp @@ -31,12 +31,12 @@ QgsEllipseSymbolLayerWidget::QgsEllipseSymbolLayerWidget( const QgsVectorLayer* btnChangeColorFill->setAllowAlpha( true ); btnChangeColorFill->setColorDialogTitle( tr( "Select fill color" ) ); - btnChangeColorFill->setContext( "symbology" ); + btnChangeColorFill->setContext( QStringLiteral( "symbology" ) ); btnChangeColorFill->setShowNoColor( true ); btnChangeColorFill->setNoColorString( tr( "Transparent fill" ) ); btnChangeColorBorder->setAllowAlpha( true ); btnChangeColorBorder->setColorDialogTitle( tr( "Select border color" ) ); - btnChangeColorBorder->setContext( "symbology" ); + btnChangeColorBorder->setContext( QStringLiteral( "symbology" ) ); btnChangeColorBorder->setShowNoColor( true ); btnChangeColorBorder->setNoColorString( tr( "Transparent border" ) ); @@ -45,7 +45,7 @@ QgsEllipseSymbolLayerWidget::QgsEllipseSymbolLayerWidget( const QgsVectorLayer* mRotationSpinBox->setClearValue( 0.0 ); QStringList names; - names << "circle" << "rectangle" << "diamond" << "cross" << "triangle" << "right_half_triangle" << "left_half_triangle" << "semi_circle"; + names << QStringLiteral( "circle" ) << QStringLiteral( "rectangle" ) << QStringLiteral( "diamond" ) << QStringLiteral( "cross" ) << QStringLiteral( "triangle" ) << QStringLiteral( "right_half_triangle" ) << QStringLiteral( "left_half_triangle" ) << QStringLiteral( "semi_circle" ); QSize iconSize = mShapeListWidget->iconSize(); Q_FOREACH ( const QString& name, names ) @@ -57,7 +57,7 @@ QgsEllipseSymbolLayerWidget::QgsEllipseSymbolLayerWidget( const QgsVectorLayer* lyr->setSymbolWidth( 4 ); lyr->setSymbolHeight( 2 ); QIcon icon = QgsSymbolLayerUtils::symbolLayerPreviewIcon( lyr, QgsUnitTypes::RenderMillimeters, iconSize ); - QListWidgetItem* item = new QListWidgetItem( icon, "", mShapeListWidget ); + QListWidgetItem* item = new QListWidgetItem( icon, QLatin1String( "" ), mShapeListWidget ); item->setToolTip( name ); item->setData( Qt::UserRole, name ); delete lyr; @@ -70,7 +70,7 @@ QgsEllipseSymbolLayerWidget::QgsEllipseSymbolLayerWidget( const QgsVectorLayer* void QgsEllipseSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( !layer || layer->layerType() != "EllipseMarker" ) + if ( !layer || layer->layerType() != QLatin1String( "EllipseMarker" ) ) { return; } @@ -108,18 +108,18 @@ void QgsEllipseSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) cboJoinStyle->setPenJoinStyle( mLayer->penJoinStyle() ); blockComboSignals( false ); - registerDataDefinedButton( mSymbolWidthDDBtn, "width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mSymbolHeightDDBtn, "height", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mRotationDDBtn, "rotation", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mOutlineWidthDDBtn, "outline_width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mFillColorDDBtn, "fill_color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBorderColorDDBtn, "outline_color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mOutlineStyleDDBtn, "outline_style", QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); - registerDataDefinedButton( mJoinStyleDDBtn, "join_style", QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); - registerDataDefinedButton( mShapeDDBtn, "symbol_name", QgsDataDefinedButton::String, QgsDataDefinedButton::markerStyleDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); - registerDataDefinedButton( mHorizontalAnchorDDBtn, "horizontal_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); - registerDataDefinedButton( mVerticalAnchorDDBtn, "vertical_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); + registerDataDefinedButton( mSymbolWidthDDBtn, QStringLiteral( "width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mSymbolHeightDDBtn, QStringLiteral( "height" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mRotationDDBtn, QStringLiteral( "rotation" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mOutlineWidthDDBtn, QStringLiteral( "outline_width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mFillColorDDBtn, QStringLiteral( "fill_color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBorderColorDDBtn, QStringLiteral( "outline_color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mOutlineStyleDDBtn, QStringLiteral( "outline_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); + registerDataDefinedButton( mJoinStyleDDBtn, QStringLiteral( "join_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); + registerDataDefinedButton( mShapeDDBtn, QStringLiteral( "symbol_name" ), QgsDataDefinedButton::String, QgsDataDefinedButton::markerStyleDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); + registerDataDefinedButton( mHorizontalAnchorDDBtn, QStringLiteral( "horizontal_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); + registerDataDefinedButton( mVerticalAnchorDDBtn, QStringLiteral( "vertical_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); } diff --git a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp index a1de567c6fc7..4ee3926bd356 100644 --- a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.cpp @@ -45,7 +45,7 @@ QgsGraduatedSymbolRendererModel::QgsGraduatedSymbolRendererModel( QObject * parent ) : QAbstractItemModel( parent ) , mRenderer( nullptr ) - , mMimeFormat( "application/x-qgsgraduatedsymbolrendererv2model" ) + , mMimeFormat( QStringLiteral( "application/x-qgsgraduatedsymbolrendererv2model" ) ) { } @@ -433,7 +433,7 @@ QgsGraduatedSymbolRendererWidget::QgsGraduatedSymbolRendererWidget( QgsVectorLay } if ( !mRenderer ) { - mRenderer = new QgsGraduatedSymbolRenderer( "", QgsRangeList() ); + mRenderer = new QgsGraduatedSymbolRenderer( QLatin1String( "" ), QgsRangeList() ); } // setup user interface @@ -452,8 +452,8 @@ QgsGraduatedSymbolRendererWidget::QgsGraduatedSymbolRendererWidget( QgsVectorLay spinPrecision->setMaximum( QgsRendererRangeLabelFormat::MaxPrecision ); // set project default color ramp - QString defaultColorRamp = QgsProject::instance()->readEntry( "DefaultStyles", "/ColorRamp", "" ); - if ( defaultColorRamp != "" ) + QString defaultColorRamp = QgsProject::instance()->readEntry( QStringLiteral( "DefaultStyles" ), QStringLiteral( "/ColorRamp" ), QLatin1String( "" ) ); + if ( defaultColorRamp != QLatin1String( "" ) ) { int index = cboGraduatedColorRamp->findText( defaultColorRamp, Qt::MatchCaseSensitive ); if ( index >= 0 ) @@ -466,16 +466,16 @@ QgsGraduatedSymbolRendererWidget::QgsGraduatedSymbolRendererWidget( QgsVectorLay mGraduatedSymbol = QgsSymbol::defaultSymbol( mLayer->geometryType() ); methodComboBox->blockSignals( true ); - methodComboBox->addItem( "Color" ); + methodComboBox->addItem( QStringLiteral( "Color" ) ); if ( mGraduatedSymbol->type() == QgsSymbol::Marker ) { - methodComboBox->addItem( "Size" ); + methodComboBox->addItem( QStringLiteral( "Size" ) ); minSizeSpinBox->setValue( 1 ); maxSizeSpinBox->setValue( 8 ); } else if ( mGraduatedSymbol->type() == QgsSymbol::Line ) { - methodComboBox->addItem( "Size" ); + methodComboBox->addItem( QStringLiteral( "Size" ) ); minSizeSpinBox->setValue( .1 ); maxSizeSpinBox->setValue( 2 ); } diff --git a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp index c60b9c3feb67..f2afc1eea4e9 100644 --- a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.cpp @@ -74,7 +74,7 @@ QgsInvertedPolygonRendererWidget::QgsInvertedPolygonRendererWidget( QgsVectorLay mRendererComboBox->blockSignals( true ); for ( ; it != rendererList.constEnd(); ++it, ++idx ) { - if ( *it != "invertedPolygonRenderer" ) //< an inverted renderer cannot contain another inverted renderer + if ( *it != QLatin1String( "invertedPolygonRenderer" ) ) //< an inverted renderer cannot contain another inverted renderer { QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( *it ); mRendererComboBox->addItem( m->icon(), m->visibleName(), /* data */ *it ); diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp index 2b45bdcbf317..2174d2779b2f 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp @@ -63,27 +63,27 @@ static void _initWidgetFunctions() if ( initialized ) return; - _initWidgetFunction( "SimpleLine", QgsSimpleLineSymbolLayerWidget::create ); - _initWidgetFunction( "MarkerLine", QgsMarkerLineSymbolLayerWidget::create ); - _initWidgetFunction( "ArrowLine", QgsArrowSymbolLayerWidget::create ); - - _initWidgetFunction( "SimpleMarker", QgsSimpleMarkerSymbolLayerWidget::create ); - _initWidgetFunction( "FilledMarker", QgsFilledMarkerSymbolLayerWidget::create ); - _initWidgetFunction( "SvgMarker", QgsSvgMarkerSymbolLayerWidget::create ); - _initWidgetFunction( "FontMarker", QgsFontMarkerSymbolLayerWidget::create ); - _initWidgetFunction( "EllipseMarker", QgsEllipseSymbolLayerWidget::create ); - _initWidgetFunction( "VectorField", QgsVectorFieldSymbolLayerWidget::create ); - - _initWidgetFunction( "SimpleFill", QgsSimpleFillSymbolLayerWidget::create ); - _initWidgetFunction( "GradientFill", QgsGradientFillSymbolLayerWidget::create ); - _initWidgetFunction( "ShapeburstFill", QgsShapeburstFillSymbolLayerWidget::create ); - _initWidgetFunction( "RasterFill", QgsRasterFillSymbolLayerWidget::create ); - _initWidgetFunction( "SVGFill", QgsSVGFillSymbolLayerWidget::create ); - _initWidgetFunction( "CentroidFill", QgsCentroidFillSymbolLayerWidget::create ); - _initWidgetFunction( "LinePatternFill", QgsLinePatternFillSymbolLayerWidget::create ); - _initWidgetFunction( "PointPatternFill", QgsPointPatternFillSymbolLayerWidget::create ); - - _initWidgetFunction( "GeometryGenerator", QgsGeometryGeneratorSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "SimpleLine" ), QgsSimpleLineSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "MarkerLine" ), QgsMarkerLineSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "ArrowLine" ), QgsArrowSymbolLayerWidget::create ); + + _initWidgetFunction( QStringLiteral( "SimpleMarker" ), QgsSimpleMarkerSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "FilledMarker" ), QgsFilledMarkerSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "SvgMarker" ), QgsSvgMarkerSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "FontMarker" ), QgsFontMarkerSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "EllipseMarker" ), QgsEllipseSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "VectorField" ), QgsVectorFieldSymbolLayerWidget::create ); + + _initWidgetFunction( QStringLiteral( "SimpleFill" ), QgsSimpleFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "GradientFill" ), QgsGradientFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "ShapeburstFill" ), QgsShapeburstFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "RasterFill" ), QgsRasterFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "SVGFill" ), QgsSVGFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "CentroidFill" ), QgsCentroidFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "LinePatternFill" ), QgsLinePatternFillSymbolLayerWidget::create ); + _initWidgetFunction( QStringLiteral( "PointPatternFill" ), QgsPointPatternFillSymbolLayerWidget::create ); + + _initWidgetFunction( QStringLiteral( "GeometryGenerator" ), QgsGeometryGeneratorSymbolLayerWidget::create ); initialized = true; } diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp index ca90de09828b..155d9f2b2be1 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp @@ -66,7 +66,7 @@ QgsPointClusterRendererWidget::QgsPointClusterRendererWidget( QgsVectorLayer* la QStringList::const_iterator it = rendererList.constBegin(); for ( ; it != rendererList.constEnd(); ++it ) { - if ( *it != "pointDisplacement" && *it != "pointCluster" && *it != "heatmapRenderer" ) + if ( *it != QLatin1String( "pointDisplacement" ) && *it != QLatin1String( "pointCluster" ) && *it != QLatin1String( "heatmapRenderer" ) ) { QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( *it ); mRendererComboBox->addItem( m->icon(), m->visibleName(), *it ); diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index d73d619906d4..6be2724573c9 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -90,7 +90,7 @@ QgsPointDisplacementRendererWidget::QgsPointDisplacementRendererWidget( QgsVecto QStringList::const_iterator it = rendererList.constBegin(); for ( ; it != rendererList.constEnd(); ++it ) { - if ( *it != "pointDisplacement" && *it != "pointCluster" && *it != "heatmapRenderer" ) + if ( *it != QLatin1String( "pointDisplacement" ) && *it != QLatin1String( "pointCluster" ) && *it != QLatin1String( "heatmapRenderer" ) ) { QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( *it ); mRendererComboBox->addItem( m->icon(), m->visibleName(), *it ); @@ -98,11 +98,11 @@ QgsPointDisplacementRendererWidget::QgsPointDisplacementRendererWidget( QgsVecto } mCircleColorButton->setColorDialogTitle( tr( "Select color" ) ); - mCircleColorButton->setContext( "symbology" ); + mCircleColorButton->setContext( QStringLiteral( "symbology" ) ); mCircleColorButton->setAllowAlpha( true ); mCircleColorButton->setShowNoColor( true ); mCircleColorButton->setNoColorString( tr( "No outline" ) ); - mLabelColorButton->setContext( "symbology" ); + mLabelColorButton->setContext( QStringLiteral( "symbology" ) ); mLabelColorButton->setColorDialogTitle( tr( "Select color" ) ); mLabelColorButton->setAllowAlpha( true ); @@ -171,7 +171,7 @@ void QgsPointDisplacementRendererWidget::on_mLabelFieldComboBox_currentIndexChan { if ( text == tr( "None" ) ) { - mRenderer->setLabelAttributeName( "" ); + mRenderer->setLabelAttributeName( QLatin1String( "" ) ); } else { @@ -311,7 +311,7 @@ void QgsPointDisplacementRendererWidget::on_mScaleDependentLabelsCheckBox_stateC { if ( state == Qt::Unchecked ) { - mMaxScaleDenominatorEdit->setText( "-1" ); + mMaxScaleDenominatorEdit->setText( QStringLiteral( "-1" ) ); mMaxScaleDenominatorEdit->setEnabled( false ); } else diff --git a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp index 435fa69ada6a..faa2936d0e7c 100644 --- a/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp +++ b/src/gui/symbology-ng/qgsrendererpropertiesdialog.cpp @@ -69,16 +69,16 @@ static void _initRendererWidgetFunctions() if ( initialized ) return; - _initRenderer( "singleSymbol", QgsSingleSymbolRendererWidget::create, "rendererSingleSymbol.svg" ); - _initRenderer( "categorizedSymbol", QgsCategorizedSymbolRendererWidget::create, "rendererCategorizedSymbol.svg" ); - _initRenderer( "graduatedSymbol", QgsGraduatedSymbolRendererWidget::create, "rendererGraduatedSymbol.svg" ); - _initRenderer( "RuleRenderer", QgsRuleBasedRendererWidget::create, "rendererRuleBasedSymbol.svg" ); - _initRenderer( "pointDisplacement", QgsPointDisplacementRendererWidget::create, "rendererPointDisplacementSymbol.svg" ); - _initRenderer( "pointCluster", QgsPointClusterRendererWidget::create, "rendererPointClusterSymbol.svg" ); - _initRenderer( "invertedPolygonRenderer", QgsInvertedPolygonRendererWidget::create, "rendererInvertedSymbol.svg" ); - _initRenderer( "heatmapRenderer", QgsHeatmapRendererWidget::create, "rendererHeatmapSymbol.svg" ); - _initRenderer( "25dRenderer", Qgs25DRendererWidget::create, "renderer25dSymbol.svg" ); - _initRenderer( "nullSymbol", QgsNullSymbolRendererWidget::create, "rendererNullSymbol.svg" ); + _initRenderer( QStringLiteral( "singleSymbol" ), QgsSingleSymbolRendererWidget::create, QStringLiteral( "rendererSingleSymbol.svg" ) ); + _initRenderer( QStringLiteral( "categorizedSymbol" ), QgsCategorizedSymbolRendererWidget::create, QStringLiteral( "rendererCategorizedSymbol.svg" ) ); + _initRenderer( QStringLiteral( "graduatedSymbol" ), QgsGraduatedSymbolRendererWidget::create, QStringLiteral( "rendererGraduatedSymbol.svg" ) ); + _initRenderer( QStringLiteral( "RuleRenderer" ), QgsRuleBasedRendererWidget::create, QStringLiteral( "rendererRuleBasedSymbol.svg" ) ); + _initRenderer( QStringLiteral( "pointDisplacement" ), QgsPointDisplacementRendererWidget::create, QStringLiteral( "rendererPointDisplacementSymbol.svg" ) ); + _initRenderer( QStringLiteral( "pointCluster" ), QgsPointClusterRendererWidget::create, QStringLiteral( "rendererPointClusterSymbol.svg" ) ); + _initRenderer( QStringLiteral( "invertedPolygonRenderer" ), QgsInvertedPolygonRendererWidget::create, QStringLiteral( "rendererInvertedSymbol.svg" ) ); + _initRenderer( QStringLiteral( "heatmapRenderer" ), QgsHeatmapRendererWidget::create, QStringLiteral( "rendererHeatmapSymbol.svg" ) ); + _initRenderer( QStringLiteral( "25dRenderer" ), Qgs25DRendererWidget::create, QStringLiteral( "renderer25dSymbol.svg" ) ); + _initRenderer( QStringLiteral( "nullSymbol" ), QgsNullSymbolRendererWidget::create, QStringLiteral( "rendererNullSymbol.svg" ) ); initialized = true; } @@ -91,7 +91,7 @@ QgsRendererPropertiesDialog::QgsRendererPropertiesDialog( QgsVectorLayer* layer, , mMapCanvas( nullptr ) { setupUi( this ); - mLayerRenderingGroupBox->setSettingGroup( "layerRenderingGroupBox" ); + mLayerRenderingGroupBox->setSettingGroup( QStringLiteral( "layerRenderingGroupBox" ) ); // can be embedded in vector layer properties if ( embedded ) @@ -318,7 +318,7 @@ void QgsRendererPropertiesDialog::openPanel( QgsPanelWidget *panel ) QgsDebugMsg( "DIALOG MODE" ); // Show the dialog version if no one is connected QDialog* dlg = new QDialog(); - QString key = QString( "/UI/paneldialog/%1" ).arg( panel->panelTitle() ); + QString key = QStringLiteral( "/UI/paneldialog/%1" ).arg( panel->panelTitle() ); QSettings settings; dlg->restoreGeometry( settings.value( key ).toByteArray() ); dlg->setWindowTitle( panel->panelTitle() ); diff --git a/src/gui/symbology-ng/qgsrendererwidget.cpp b/src/gui/symbology-ng/qgsrendererwidget.cpp index 95288e1cbb25..bd276826de31 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrendererwidget.cpp @@ -79,7 +79,7 @@ void QgsRendererWidget::changeSymbolColor() if ( !firstSymbol ) return; - QColor color = QgsColorDialog::getColor( firstSymbol->color(), this, "Change Symbol Color", true ); + QColor color = QgsColorDialog::getColor( firstSymbol->color(), this, QStringLiteral( "Change Symbol Color" ), true ); if ( color.isValid() ) { Q_FOREACH ( QgsSymbol* symbol, symbolList ) diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp index 23afabfedd9e..a46b36dabf2b 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp @@ -416,7 +416,7 @@ void QgsRuleBasedRendererWidget::saveSectionWidth( int section, int oldSize, int void QgsRuleBasedRendererWidget::restoreSectionWidths() { QSettings settings; - QString path = "/Windows/RuleBasedTree/sectionWidth/"; + QString path = QStringLiteral( "/Windows/RuleBasedTree/sectionWidth/" ); QHeaderView* head = viewRules->header(); head->resizeSection( 0, settings.value( path + QString::number( 0 ), 150 ).toInt() ); head->resizeSection( 1, settings.value( path + QString::number( 1 ), 150 ).toInt() ); @@ -693,13 +693,13 @@ QgsRendererRulePropsDialog::QgsRendererRulePropsDialog( QgsRuleBasedRenderer::Ru connect( buttonBox, SIGNAL( rejected() ), this, SLOT( reject() ) ); QSettings settings; - restoreGeometry( settings.value( "/Windows/QgsRendererRulePropsDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsRendererRulePropsDialog/geometry" ) ).toByteArray() ); } QgsRendererRulePropsDialog::~QgsRendererRulePropsDialog() { QSettings settings; - settings.setValue( "/Windows/QgsRendererRulePropsDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QgsRendererRulePropsDialog/geometry" ), saveGeometry() ); } void QgsRendererRulePropsDialog::testFilter() @@ -741,7 +741,7 @@ void QgsRendererRulePropsWidget::buildExpression() context.appendScope( new QgsExpressionContextScope( scope ) ); } - QgsExpressionBuilderDialog dlg( mLayer, editFilter->text(), this, "generic", context ); + QgsExpressionBuilderDialog dlg( mLayer, editFilter->text(), this, QStringLiteral( "generic" ), context ); if ( dlg.exec() ) editFilter->setText( dlg.expressionText() ); @@ -833,7 +833,7 @@ static QString _formatScale( int denom ) { if ( denom != 0 ) { - QString txt = QString( "1:%L1" ).arg( denom ); + QString txt = QStringLiteral( "1:%L1" ).arg( denom ); return txt; } else @@ -905,13 +905,13 @@ QVariant QgsRuleBasedRendererModel::data( const QModelIndex &index, int role ) c { if ( mFeatureCountMap[rule].duplicateCount > 0 ) { - QString tip = "<p style='margin:0px;'><ul>"; + QString tip = QStringLiteral( "<p style='margin:0px;'><ul>" ); Q_FOREACH ( QgsRuleBasedRenderer::Rule* duplicateRule, mFeatureCountMap[rule].duplicateCountMap.keys() ) { - QString label = duplicateRule->label().replace( '&', "&" ).replace( '>', ">" ).replace( '<', "<" ); + QString label = duplicateRule->label().replace( '&', QLatin1String( "&" ) ).replace( '>', QLatin1String( ">" ) ).replace( '<', QLatin1String( "<" ) ); tip += tr( "<li><nobr>%1 features also in rule %2</nobr></li>" ).arg( mFeatureCountMap[rule].duplicateCountMap[duplicateRule] ).arg( label ); } - tip += "</ul>"; + tip += QLatin1String( "</ul>" ); return tip; } else @@ -1082,7 +1082,7 @@ Qt::DropActions QgsRuleBasedRendererModel::supportedDropActions() const QStringList QgsRuleBasedRendererModel::mimeTypes() const { QStringList types; - types << "application/vnd.text.list"; + types << QStringLiteral( "application/vnd.text.list" ); return types; } @@ -1105,11 +1105,11 @@ QMimeData *QgsRuleBasedRendererModel::mimeData( const QModelIndexList &indexes ) QDomDocument doc; QgsSymbolMap symbols; - QDomElement rootElem = doc.createElement( "rule_mime" ); - rootElem.setAttribute( "type", "renderer" ); // for determining whether rules are from renderer or labeling + QDomElement rootElem = doc.createElement( QStringLiteral( "rule_mime" ) ); + rootElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "renderer" ) ); // for determining whether rules are from renderer or labeling QDomElement rulesElem = rule->save( doc, symbols ); rootElem.appendChild( rulesElem ); - QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, "symbols", doc ); + QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, QStringLiteral( "symbols" ), doc ); rootElem.appendChild( symbolsElem ); doc.appendChild( rootElem ); @@ -1118,7 +1118,7 @@ QMimeData *QgsRuleBasedRendererModel::mimeData( const QModelIndexList &indexes ) stream << doc.toString( -1 ); } - mimeData->setData( "application/vnd.text.list", encodedData ); + mimeData->setData( QStringLiteral( "application/vnd.text.list" ), encodedData ); return mimeData; } @@ -1127,15 +1127,15 @@ QMimeData *QgsRuleBasedRendererModel::mimeData( const QModelIndexList &indexes ) void _labeling2rendererRules( QDomElement& ruleElem ) { // labeling rules recognize only "description" - if ( ruleElem.hasAttribute( "description" ) ) - ruleElem.setAttribute( "label", ruleElem.attribute( "description" ) ); + if ( ruleElem.hasAttribute( QStringLiteral( "description" ) ) ) + ruleElem.setAttribute( QStringLiteral( "label" ), ruleElem.attribute( QStringLiteral( "description" ) ) ); // run recursively - QDomElement childRuleElem = ruleElem.firstChildElement( "rule" ); + QDomElement childRuleElem = ruleElem.firstChildElement( QStringLiteral( "rule" ) ); while ( !childRuleElem.isNull() ) { _labeling2rendererRules( childRuleElem ); - childRuleElem = childRuleElem.nextSiblingElement( "rule" ); + childRuleElem = childRuleElem.nextSiblingElement( QStringLiteral( "rule" ) ); } } @@ -1148,13 +1148,13 @@ bool QgsRuleBasedRendererModel::dropMimeData( const QMimeData *data, if ( action == Qt::IgnoreAction ) return true; - if ( !data->hasFormat( "application/vnd.text.list" ) ) + if ( !data->hasFormat( QStringLiteral( "application/vnd.text.list" ) ) ) return false; if ( parent.column() > 0 ) return false; - QByteArray encodedData = data->data( "application/vnd.text.list" ); + QByteArray encodedData = data->data( QStringLiteral( "application/vnd.text.list" ) ); QDataStream stream( &encodedData, QIODevice::ReadOnly ); int rows = 0; @@ -1173,16 +1173,16 @@ bool QgsRuleBasedRendererModel::dropMimeData( const QMimeData *data, if ( !doc.setContent( text ) ) continue; QDomElement rootElem = doc.documentElement(); - if ( rootElem.tagName() != "rule_mime" ) + if ( rootElem.tagName() != QLatin1String( "rule_mime" ) ) continue; - if ( rootElem.attribute( "type" ) == "labeling" ) - rootElem.appendChild( doc.createElement( "symbols" ) ); - QDomElement symbolsElem = rootElem.firstChildElement( "symbols" ); + if ( rootElem.attribute( QStringLiteral( "type" ) ) == QLatin1String( "labeling" ) ) + rootElem.appendChild( doc.createElement( QStringLiteral( "symbols" ) ) ); + QDomElement symbolsElem = rootElem.firstChildElement( QStringLiteral( "symbols" ) ); if ( symbolsElem.isNull() ) continue; QgsSymbolMap symbolMap = QgsSymbolLayerUtils::loadSymbols( symbolsElem ); - QDomElement ruleElem = rootElem.firstChildElement( "rule" ); - if ( rootElem.attribute( "type" ) == "labeling" ) + QDomElement ruleElem = rootElem.firstChildElement( QStringLiteral( "rule" ) ); + if ( rootElem.attribute( QStringLiteral( "type" ) ) == QLatin1String( "labeling" ) ) _labeling2rendererRules( ruleElem ); QgsRuleBasedRenderer::Rule* rule = QgsRuleBasedRenderer::Rule::create( ruleElem, symbolMap ); diff --git a/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp b/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp index 5c80c0a17f5f..7f60c0d5ac48 100644 --- a/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp +++ b/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp @@ -159,7 +159,7 @@ QString QgsSmartGroupEditorDialog::conditionOperator() void QgsSmartGroupEditorDialog::setConditionMap( const QgsSmartConditionMap& map ) { QStringList constraints; - constraints << "tag" << "group" << "name" << "!tag" << "!group" << "!name"; + constraints << QStringLiteral( "tag" ) << QStringLiteral( "group" ) << QStringLiteral( "name" ) << QStringLiteral( "!tag" ) << QStringLiteral( "!group" ) << QStringLiteral( "!name" ); // clear any defaults Q_FOREACH ( int id, mConditionMap.keys() ) diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp index 17ba4755630a..eb2792cc30fc 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp @@ -57,7 +57,7 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget mTempStyle = new QgsStyle(); // TODO validate - mFileName = ""; + mFileName = QLatin1String( "" ); mProgressDlg = nullptr; mGroupSelectionDlg = nullptr; mTempFile = nullptr; @@ -74,13 +74,13 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget connect( importTypeCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( importTypeChanged( int ) ) ); QStringList groups = mQgisStyle->groupNames(); - groupCombo->addItem( "imported", QVariant( "new" ) ); + groupCombo->addItem( QStringLiteral( "imported" ), QVariant( "new" ) ); Q_FOREACH ( const QString& gName, groups ) { groupCombo->addItem( gName ); } - btnBrowse->setText( "Browse" ); + btnBrowse->setText( QStringLiteral( "Browse" ) ); connect( btnBrowse, SIGNAL( clicked() ), this, SLOT( browse() ) ); label->setText( tr( "Select symbols to import" ) ); @@ -135,9 +135,9 @@ void QgsStyleExportImportDialog::doExportImport() } // ensure the user never ommited the extension from the file name - if ( !fileName.endsWith( ".xml", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) ) { - fileName += ".xml"; + fileName += QLatin1String( ".xml" ); } mFileName = fileName; @@ -161,7 +161,7 @@ void QgsStyleExportImportDialog::doExportImport() accept(); } - mFileName = ""; + mFileName = QLatin1String( "" ); mTempStyle->clear(); } @@ -449,21 +449,21 @@ void QgsStyleExportImportDialog::importTypeChanged( int index ) { QString type = importTypeCombo->itemData( index ).toString(); - locationLineEdit->setText( "" ); + locationLineEdit->setText( QLatin1String( "" ) ); - if ( type == "file" ) + if ( type == QLatin1String( "file" ) ) { locationLineEdit->setEnabled( true ); - btnBrowse->setText( "Browse" ); + btnBrowse->setText( QStringLiteral( "Browse" ) ); } - else if ( type == "official" ) + else if ( type == QLatin1String( "official" ) ) { - btnBrowse->setText( "Fetch Symbols" ); + btnBrowse->setText( QStringLiteral( "Fetch Symbols" ) ); locationLineEdit->setEnabled( false ); } else { - btnBrowse->setText( "Fetch Symbols" ); + btnBrowse->setText( QStringLiteral( "Fetch Symbols" ) ); locationLineEdit->setEnabled( true ); } } @@ -472,7 +472,7 @@ void QgsStyleExportImportDialog::browse() { QString type = importTypeCombo->currentData().toString(); - if ( type == "file" ) + if ( type == QLatin1String( "file" ) ) { mFileName = QFileDialog::getOpenFileName( this, tr( "Load styles" ), QDir::homePath(), tr( "XML files (*.xml *XML)" ) ); @@ -481,12 +481,12 @@ void QgsStyleExportImportDialog::browse() return; } QFileInfo pathInfo( mFileName ); - QString groupName = pathInfo.fileName().remove( ".xml" ); + QString groupName = pathInfo.fileName().remove( QStringLiteral( ".xml" ) ); groupCombo->setItemText( 0, groupName ); locationLineEdit->setText( mFileName ); populateStyles( mTempStyle ); } - else if ( type == "official" ) + else if ( type == QLatin1String( "official" ) ) { // TODO set URL // downloadStyleXML( QUrl( "http://...." ) ); @@ -539,7 +539,7 @@ void QgsStyleExportImportDialog::httpFinished() if ( mNetReply->error() ) { mTempFile->remove(); - mFileName = ""; + mFileName = QLatin1String( "" ); mProgressDlg->hide(); QMessageBox::information( this, tr( "HTTP Error!" ), tr( "Download failed: %1." ).arg( mNetReply->errorString() ) ); @@ -568,7 +568,7 @@ void QgsStyleExportImportDialog::downloadCanceled() { mNetReply->abort(); mTempFile->remove(); - mFileName = ""; + mFileName = QLatin1String( "" ); } void QgsStyleExportImportDialog::selectionChanged( const QItemSelection & selected, const QItemSelection & deselected ) diff --git a/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp b/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp index 94cff794d41d..2b8a95d2281c 100644 --- a/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp +++ b/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp @@ -37,7 +37,7 @@ QgsStyleGroupSelectionDialog::QgsStyleGroupSelectionDialog( QgsStyle *style, QWi setBold( allSymbols ); model->appendRow( allSymbols ); - QStandardItem *group = new QStandardItem( "" ); //require empty name to get first order groups + QStandardItem *group = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups group->setData( "groupsheader", Qt::UserRole + 2 ); group->setEditable( false ); group->setFlags( group->flags() & ~Qt::ItemIsSelectable ); @@ -100,46 +100,46 @@ void QgsStyleGroupSelectionDialog::groupTreeSelectionChanged( const QItemSelecti Q_FOREACH ( index, deselectedItems ) { - if ( index.data( Qt::UserRole + 2 ).toString() == "groupsheader" ) + if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "groupsheader" ) ) { // Ignore: it's the group header } - else if ( index.data( Qt::UserRole + 2 ).toString() == "all" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "all" ) ) { emit allDeselected(); } - else if ( index.data( Qt::UserRole + 2 ).toString() == "smartgroupsheader" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "smartgroupsheader" ) ) { // Ignore: it's the smartgroups header } - else if ( index.data( Qt::UserRole + 2 ).toString() == "smartgroup" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "smartgroup" ) ) { emit smartgroupDeselected( index.data().toString() ); } - else if ( index.data( Qt::UserRole + 2 ).toString() == "group" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "group" ) ) { // It's a group emit groupDeselected( index.data().toString() ); } } Q_FOREACH ( index, selectedItems ) { - if ( index.data( Qt::UserRole + 2 ).toString() == "groupsheader" ) + if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "groupsheader" ) ) { // Ignore: it's the group header } - else if ( index.data( Qt::UserRole + 2 ).toString() == "all" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "all" ) ) { emit allSelected(); } - else if ( index.data( Qt::UserRole + 2 ).toString() == "smartgroupsheader" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "smartgroupsheader" ) ) { // Ignore: it's the smartgroups header } - else if ( index.data( Qt::UserRole + 2 ).toString() == "smartgroup" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "smartgroup" ) ) { emit smartgroupSelected( index.data().toString() ); } - else if ( index.data( Qt::UserRole + 2 ).toString() == "group" ) + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "group" ) ) { // It's a group emit groupSelected( index.data().toString() ); } diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp index 87b7ebf9112b..f9ad62764a55 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp @@ -53,9 +53,9 @@ QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle* style, QWidget* parent ) QSettings settings; - restoreGeometry( settings.value( "/Windows/StyleV2Manager/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/StyleV2Manager/geometry" ) ).toByteArray() ); mSplitter->setSizes( QList<int>() << 170 << 540 ); - mSplitter->restoreState( settings.value( "/Windows/StyleV2Manager/splitter" ).toByteArray() ); + mSplitter->restoreState( settings.value( QStringLiteral( "/Windows/StyleV2Manager/splitter" ) ).toByteArray() ); tabItemType->setDocumentMode( true ); searchBox->setPlaceholderText( tr( "Type here to filter symbols..." ) ); @@ -178,8 +178,8 @@ void QgsStyleManagerDialog::onFinished() } QSettings settings; - settings.setValue( "/Windows/StyleV2Manager/geometry", saveGeometry() ); - settings.setValue( "/Windows/StyleV2Manager/splitter", mSplitter->saveState() ); + settings.setValue( QStringLiteral( "/Windows/StyleV2Manager/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/StyleV2Manager/splitter" ), mSplitter->saveState() ); } void QgsStyleManagerDialog::populateTypes() @@ -497,7 +497,7 @@ QString QgsStyleManagerDialog::addColorRampStatic( QWidget* parent, QgsStyle* st } else if ( rampType == tr( "cpt-city" ) ) { - QgsCptCityColorRampDialog dlg( QgsCptCityColorRamp( "", "" ), parent ); + QgsCptCityColorRampDialog dlg( QgsCptCityColorRamp( QLatin1String( "" ), QLatin1String( "" ) ), parent ); if ( !dlg.exec() ) { return QString(); @@ -635,7 +635,7 @@ bool QgsStyleManagerDialog::editColorRamp() QScopedPointer< QgsColorRamp > ramp( mStyle->colorRamp( name ) ); - if ( ramp->type() == "gradient" ) + if ( ramp->type() == QLatin1String( "gradient" ) ) { QgsGradientColorRamp* gradRamp = static_cast<QgsGradientColorRamp*>( ramp.data() ); QgsGradientColorRampDialog dlg( *gradRamp, this ); @@ -645,7 +645,7 @@ bool QgsStyleManagerDialog::editColorRamp() } ramp.reset( dlg.ramp().clone() ); } - else if ( ramp->type() == "random" ) + else if ( ramp->type() == QLatin1String( "random" ) ) { QgsLimitedRandomColorRamp* randRamp = static_cast<QgsLimitedRandomColorRamp*>( ramp.data() ); QgsLimitedRandomColorRampDialog dlg( *randRamp, this ); @@ -655,7 +655,7 @@ bool QgsStyleManagerDialog::editColorRamp() } ramp.reset( dlg.ramp().clone() ); } - else if ( ramp->type() == "colorbrewer" ) + else if ( ramp->type() == QLatin1String( "colorbrewer" ) ) { QgsColorBrewerColorRamp* brewerRamp = static_cast<QgsColorBrewerColorRamp*>( ramp.data() ); QgsColorBrewerColorRampDialog dlg( *brewerRamp, this ); @@ -665,7 +665,7 @@ bool QgsStyleManagerDialog::editColorRamp() } ramp.reset( dlg.ramp().clone() ); } - else if ( ramp->type() == "preset" ) + else if ( ramp->type() == QLatin1String( "preset" ) ) { QgsPresetSchemeColorRamp* presetRamp = static_cast<QgsPresetSchemeColorRamp*>( ramp.data() ); QgsPresetColorRampDialog dlg( *presetRamp, this ); @@ -675,7 +675,7 @@ bool QgsStyleManagerDialog::editColorRamp() } ramp.reset( dlg.ramp().clone() ); } - else if ( ramp->type() == "cpt-city" ) + else if ( ramp->type() == QLatin1String( "cpt-city" ) ) { QgsCptCityColorRamp* cptCityRamp = static_cast<QgsCptCityColorRamp*>( ramp.data() ); QgsCptCityColorRampDialog dlg( *cptCityRamp, this ); @@ -800,7 +800,7 @@ void QgsStyleManagerDialog::exportItemsPNG() QDir::home().absolutePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); - exportSelectedItemsImages( dir, "png", QSize( 32, 32 ) ); + exportSelectedItemsImages( dir, QStringLiteral( "png" ), QSize( 32, 32 ) ); } void QgsStyleManagerDialog::exportItemsSVG() @@ -809,7 +809,7 @@ void QgsStyleManagerDialog::exportItemsSVG() QDir::home().absolutePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks ); - exportSelectedItemsImages( dir, "svg", QSize( 32, 32 ) ); + exportSelectedItemsImages( dir, QStringLiteral( "svg" ), QSize( 32, 32 ) ); } @@ -860,7 +860,7 @@ void QgsStyleManagerDialog::populateGroups() setBold( allSymbols ); model->appendRow( allSymbols ); - QStandardItem *group = new QStandardItem( "" ); //require empty name to get first order groups + QStandardItem *group = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups group->setData( "groups" ); group->setEditable( false ); buildGroupTree( group ); @@ -922,10 +922,10 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) } QString category = index.data( Qt::UserRole + 1 ).toString(); - if ( category == "all" || category == "groups" || category == "smartgroups" ) + if ( category == QLatin1String( "all" ) || category == QLatin1String( "groups" ) || category == QLatin1String( "smartgroups" ) ) { enableGroupInputs( false ); - if ( category == "groups" || category == "smartgroups" ) + if ( category == QLatin1String( "groups" ) || category == QLatin1String( "smartgroups" ) ) { btnAddGroup->setEnabled( true ); actnAddGroup->setEnabled( true ); @@ -978,9 +978,9 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) actnGroupSymbols->setVisible( false ); actnFinishGrouping->setVisible( false ); - if ( index.parent().isValid() && ( index.data().toString() != "Ungrouped" ) ) + if ( index.parent().isValid() && ( index.data().toString() != QLatin1String( "Ungrouped" ) ) ) { - if ( index.parent().data( Qt::UserRole + 1 ).toString() == "smartgroups" ) + if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) { actnEditSmartGroup->setVisible( !mGrouppingMode ); } @@ -1005,7 +1005,7 @@ void QgsStyleManagerDialog::addGroup() // Violation 1: Creating sub-groups of system defined groups QString parentData = parentIndex.data( Qt::UserRole + 1 ).toString(); - if ( parentData == "all" || ( parentIndex.data() == "Ungrouped" && parentData == "0" ) ) + if ( parentData == QLatin1String( "all" ) || ( parentIndex.data() == "Ungrouped" && parentData == QLatin1String( "0" ) ) ) { int err = QMessageBox::critical( this, tr( "Invalid Selection" ), tr( "The parent group you have selected is not user editable.\n" @@ -1015,7 +1015,7 @@ void QgsStyleManagerDialog::addGroup() } // Violation 2: Creating a nested tag - if ( parentIndex.parent().data( Qt::UserRole + 1 ).toString() == "smartgroups" ) + if ( parentIndex.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) { int err = QMessageBox::critical( this, tr( "Operation Not Allowed" ), tr( "Creation of nested smart groups are not allowed\n" @@ -1028,7 +1028,7 @@ void QgsStyleManagerDialog::addGroup() bool isGroup = true; int id; - if ( parentData == "smartgroups" ) + if ( parentData == QLatin1String( "smartgroups" ) ) { // create a smart group @@ -1046,7 +1046,7 @@ void QgsStyleManagerDialog::addGroup() // create a simple child-group to the selected itemName = QString( tr( "New Group" ) ); - int parentid = ( parentData == "groups" ) ? 0 : parentData.toInt(); // parentid is 0 for top-level groups + int parentid = ( parentData == QLatin1String( "groups" ) ) ? 0 : parentData.toInt(); // parentid is 0 for top-level groups id = mStyle->addGroup( itemName, parentid ); if ( !id ) { @@ -1076,7 +1076,7 @@ void QgsStyleManagerDialog::removeGroup() // Violation: removing system groups QString data = index.data( Qt::UserRole + 1 ).toString(); - if ( data == "all" || data == "groups" || data == "smartgroups" || index.data() == "Ungrouped" ) + if ( data == QLatin1String( "all" ) || data == QLatin1String( "groups" ) || data == QLatin1String( "smartgroups" ) || index.data() == "Ungrouped" ) { int err = QMessageBox::critical( this, tr( "Invalid selection" ), tr( "Cannot delete system defined categories.\n" @@ -1086,7 +1086,7 @@ void QgsStyleManagerDialog::removeGroup() } QStandardItem *parentItem = model->itemFromIndex( index.parent() ); - if ( parentItem->data( Qt::UserRole + 1 ).toString() == "smartgroups" ) + if ( parentItem->data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) { mStyle->remove( QgsStyle::SmartgroupEntity, index.data( Qt::UserRole + 1 ).toInt() ); } @@ -1302,7 +1302,7 @@ void QgsStyleManagerDialog::symbolSelected( const QModelIndex& index ) QStandardItem *item = static_cast<QStandardItemModel*>( listItems->model() )->itemFromIndex( index ); QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; mTagList = mStyle->tagsOfSymbol( type, item->data().toString() ); - tagsLineEdit->setText( mTagList.join( "," ) ); + tagsLineEdit->setText( mTagList.join( QStringLiteral( "," ) ) ); } actnEditItem->setEnabled( index.isValid() && !mGrouppingMode ); diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.cpp b/src/gui/symbology-ng/qgssvgselectorwidget.cpp index bcf384f42960..b5af97e82c75 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.cpp +++ b/src/gui/symbology-ng/qgssvgselectorwidget.cpp @@ -380,23 +380,23 @@ QgsSvgSelectorWidget::QgsSvgSelectorWidget( QWidget* parent ) this, SLOT( populateIcons( const QModelIndex& ) ) ); QSettings settings; - bool useRelativePath = ( QgsProject::instance()->readBoolEntry( "Paths", "/Absolute", false ) - || settings.value( "/Windows/SvgSelectorWidget/RelativePath" ).toBool() ); + bool useRelativePath = ( QgsProject::instance()->readBoolEntry( QStringLiteral( "Paths" ), QStringLiteral( "/Absolute" ), false ) + || settings.value( QStringLiteral( "/Windows/SvgSelectorWidget/RelativePath" ) ).toBool() ); mRelativePathChkBx->setChecked( useRelativePath ); } QgsSvgSelectorWidget::~QgsSvgSelectorWidget() { QSettings settings; - settings.setValue( "/Windows/SvgSelectorWidget/RelativePath", mRelativePathChkBx->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/SvgSelectorWidget/RelativePath" ), mRelativePathChkBx->isChecked() ); } void QgsSvgSelectorWidget::setSvgPath( const QString& svgPath ) { - QString updatedPath( "" ); + QString updatedPath( QLatin1String( "" ) ); // skip possible urls, excepting those that may locally resolve - if ( !svgPath.contains( "://" ) || ( svgPath.contains( "file://", Qt::CaseInsensitive ) ) ) + if ( !svgPath.contains( QLatin1String( "://" ) ) || ( svgPath.contains( QLatin1String( "file://" ), Qt::CaseInsensitive ) ) ) { QString resolvedPath = QgsSymbolLayerUtils::symbolNameToPath( svgPath.trimmed() ); if ( !resolvedPath.isNull() ) @@ -471,7 +471,7 @@ void QgsSvgSelectorWidget::populateIcons( const QModelIndex& idx ) void QgsSvgSelectorWidget::on_mFilePushButton_clicked() { QSettings settings; - QString openDir = settings.value( "/UI/lastSVGMarkerDir", QDir::homePath() ).toString(); + QString openDir = settings.value( QStringLiteral( "/UI/lastSVGMarkerDir" ), QDir::homePath() ).toString(); QString lineEditText = mFileLineEdit->text(); if ( !lineEditText.isEmpty() ) @@ -497,7 +497,7 @@ void QgsSvgSelectorWidget::on_mFilePushButton_clicked() updateLineEditFeedback( false ); return; } - settings.setValue( "/UI/lastSVGMarkerDir", fi.absolutePath() ); + settings.setValue( QStringLiteral( "/UI/lastSVGMarkerDir" ), fi.absolutePath() ); mFileLineEdit->setText( file ); updateCurrentSvgPath( file ); } @@ -562,12 +562,12 @@ QgsSvgSelectorDialog::QgsSvgSelectorDialog( QWidget *parent, Qt::WindowFlags fl, setLayout( mLayout ); QSettings settings; - restoreGeometry( settings.value( "/Windows/SvgSelectorDialog/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/SvgSelectorDialog/geometry" ) ).toByteArray() ); } QgsSvgSelectorDialog::~QgsSvgSelectorDialog() { QSettings settings; - settings.setValue( "/Windows/SvgSelectorDialog/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/SvgSelectorDialog/geometry" ), saveGeometry() ); } diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.cpp b/src/gui/symbology-ng/qgssymbollayerwidget.cpp index 988d2750c33f..2f6e9a55683d 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgssymbollayerwidget.cpp @@ -160,7 +160,7 @@ QgsSimpleLineSymbolLayerWidget::QgsSimpleLineSymbolLayerWidget( const QgsVectorL btnChangeColor->setAllowAlpha( true ); btnChangeColor->setColorDialogTitle( tr( "Select line color" ) ); - btnChangeColor->setContext( "symbology" ); + btnChangeColor->setContext( QStringLiteral( "symbology" ) ); spinOffset->setClearValue( 0.0 ); @@ -201,7 +201,7 @@ void QgsSimpleLineSymbolLayerWidget::updateAssistantSymbol() mAssistantPreviewSymbol->deleteSymbolLayer( i ); } mAssistantPreviewSymbol->appendSymbolLayer( mLayer->clone() ); - QgsDataDefined* ddWidth = mLayer->getDataDefinedProperty( "width" ); + QgsDataDefined* ddWidth = mLayer->getDataDefinedProperty( QStringLiteral( "width" ) ); if ( ddWidth ) mAssistantPreviewSymbol->setDataDefinedWidth( *ddWidth ); } @@ -209,7 +209,7 @@ void QgsSimpleLineSymbolLayerWidget::updateAssistantSymbol() void QgsSimpleLineSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( !layer || layer->layerType() != "SimpleLine" ) + if ( !layer || layer->layerType() != QLatin1String( "SimpleLine" ) ) return; // layer type is correct, we can do the cast @@ -267,13 +267,13 @@ void QgsSimpleLineSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) updatePatternIcon(); - registerDataDefinedButton( mColorDDBtn, "color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mPenWidthDDBtn, "width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mDashPatternDDBtn, "customdash", QgsDataDefinedButton::String, QgsDataDefinedButton::customDashDesc() ); - registerDataDefinedButton( mPenStyleDDBtn, "line_style", QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); - registerDataDefinedButton( mJoinStyleDDBtn, "joinstyle", QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); - registerDataDefinedButton( mCapStyleDDBtn, "capstyle", QgsDataDefinedButton::String, QgsDataDefinedButton::capStyleDesc() ); + registerDataDefinedButton( mColorDDBtn, QStringLiteral( "color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mPenWidthDDBtn, QStringLiteral( "width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mDashPatternDDBtn, QStringLiteral( "customdash" ), QgsDataDefinedButton::String, QgsDataDefinedButton::customDashDesc() ); + registerDataDefinedButton( mPenStyleDDBtn, QStringLiteral( "line_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); + registerDataDefinedButton( mJoinStyleDDBtn, QStringLiteral( "joinstyle" ), QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); + registerDataDefinedButton( mCapStyleDDBtn, QStringLiteral( "capstyle" ), QgsDataDefinedButton::String, QgsDataDefinedButton::capStyleDesc() ); updateAssistantSymbol(); } @@ -405,12 +405,12 @@ QgsSimpleMarkerSymbolLayerWidget::QgsSimpleMarkerSymbolLayerWidget( const QgsVec btnChangeColorFill->setAllowAlpha( true ); btnChangeColorFill->setColorDialogTitle( tr( "Select fill color" ) ); - btnChangeColorFill->setContext( "symbology" ); + btnChangeColorFill->setContext( QStringLiteral( "symbology" ) ); btnChangeColorFill->setShowNoColor( true ); btnChangeColorFill->setNoColorString( tr( "Transparent fill" ) ); btnChangeColorBorder->setAllowAlpha( true ); btnChangeColorBorder->setColorDialogTitle( tr( "Select border color" ) ); - btnChangeColorBorder->setContext( "symbology" ); + btnChangeColorBorder->setContext( QStringLiteral( "symbology" ) ); btnChangeColorBorder->setShowNoColor( true ); btnChangeColorBorder->setNoColorString( tr( "Transparent border" ) ); @@ -455,7 +455,7 @@ QgsSimpleMarkerSymbolLayerWidget::~QgsSimpleMarkerSymbolLayerWidget() void QgsSimpleMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "SimpleMarker" ) + if ( layer->layerType() != QLatin1String( "SimpleMarker" ) ) return; // layer type is correct, we can do the cast @@ -523,22 +523,22 @@ void QgsSimpleMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) mHorizontalAnchorComboBox->blockSignals( false ); mVerticalAnchorComboBox->blockSignals( false ); - registerDataDefinedButton( mNameDDBtn, "name", QgsDataDefinedButton::String, tr( "string " ) + QLatin1String( "[<b>square</b>|<b>rectangle</b>|<b>diamond</b>|" + registerDataDefinedButton( mNameDDBtn, QStringLiteral( "name" ), QgsDataDefinedButton::String, tr( "string " ) + QStringLiteral( "[<b>square</b>|<b>rectangle</b>|<b>diamond</b>|" "<b>pentagon</b>|<b>hexagon</b>|<b>triangle</b>|<b>equilateral_triangle</b>|" "<b>star</b>|<b>arrow</b>|<b>filled_arrowhead</b>|" "<b>circle</b>|<b>cross</b>|<b>cross_fill</b>|<b>x</b>|" "<b>line</b>|<b>arrowhead</b>|<b>cross2</b>|<b>semi_circle</b>|<b>third_circle</b>|<b>quarter_circle</b>|" "<b>quarter_square</b>|<b>half_square</b>|<b>diagonal_half_square</b>|<b>right_half_triangle</b>|<b>left_half_triangle</b>]" ) ); - registerDataDefinedButton( mFillColorDDBtn, "color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBorderColorDDBtn, "color_border", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mOutlineWidthDDBtn, "outline_width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mOutlineStyleDDBtn, "outline_style", QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); - registerDataDefinedButton( mJoinStyleDDBtn, "join_style", QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); - registerDataDefinedButton( mSizeDDBtn, "size", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mAngleDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); - registerDataDefinedButton( mHorizontalAnchorDDBtn, "horizontal_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); - registerDataDefinedButton( mVerticalAnchorDDBtn, "vertical_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); + registerDataDefinedButton( mFillColorDDBtn, QStringLiteral( "color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBorderColorDDBtn, QStringLiteral( "color_border" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mOutlineWidthDDBtn, QStringLiteral( "outline_width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mOutlineStyleDDBtn, QStringLiteral( "outline_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); + registerDataDefinedButton( mJoinStyleDDBtn, QStringLiteral( "join_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); + registerDataDefinedButton( mSizeDDBtn, QStringLiteral( "size" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mAngleDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); + registerDataDefinedButton( mHorizontalAnchorDDBtn, QStringLiteral( "horizontal_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); + registerDataDefinedButton( mVerticalAnchorDDBtn, QStringLiteral( "vertical_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); updateAssistantSymbol(); } @@ -666,7 +666,7 @@ void QgsSimpleMarkerSymbolLayerWidget::updateAssistantSymbol() mAssistantPreviewSymbol->deleteSymbolLayer( i ); } mAssistantPreviewSymbol->appendSymbolLayer( mLayer->clone() ); - QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( "size" ); + QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( QStringLiteral( "size" ) ); if ( ddSize ) mAssistantPreviewSymbol->setDataDefinedSize( *ddSize ); } @@ -685,12 +685,12 @@ QgsSimpleFillSymbolLayerWidget::QgsSimpleFillSymbolLayerWidget( const QgsVectorL btnChangeColor->setAllowAlpha( true ); btnChangeColor->setColorDialogTitle( tr( "Select fill color" ) ); - btnChangeColor->setContext( "symbology" ); + btnChangeColor->setContext( QStringLiteral( "symbology" ) ); btnChangeColor->setShowNoColor( true ); btnChangeColor->setNoColorString( tr( "Transparent fill" ) ); btnChangeBorderColor->setAllowAlpha( true ); btnChangeBorderColor->setColorDialogTitle( tr( "Select border color" ) ); - btnChangeBorderColor->setContext( "symbology" ); + btnChangeBorderColor->setContext( QStringLiteral( "symbology" ) ); btnChangeBorderColor->setShowNoColor( true ); btnChangeBorderColor->setNoColorString( tr( "Transparent border" ) ); @@ -709,7 +709,7 @@ QgsSimpleFillSymbolLayerWidget::QgsSimpleFillSymbolLayerWidget( const QgsVectorL void QgsSimpleFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "SimpleFill" ) + if ( layer->layerType() != QLatin1String( "SimpleFill" ) ) return; // layer type is correct, we can do the cast @@ -750,12 +750,12 @@ void QgsSimpleFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) mOffsetUnitWidget->setMapUnitScale( mLayer->offsetMapUnitScale() ); mOffsetUnitWidget->blockSignals( false ); - registerDataDefinedButton( mFillColorDDBtn, "color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBorderColorDDBtn, "color_border", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBorderWidthDDBtn, "width_border", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mFillStyleDDBtn, "fill_style", QgsDataDefinedButton::String, QgsDataDefinedButton::fillStyleDesc() ); - registerDataDefinedButton( mBorderStyleDDBtn, "border_style", QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); - registerDataDefinedButton( mJoinStyleDDBtn, "join_style", QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); + registerDataDefinedButton( mFillColorDDBtn, QStringLiteral( "color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBorderColorDDBtn, QStringLiteral( "color_border" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBorderWidthDDBtn, QStringLiteral( "width_border" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mFillStyleDDBtn, QStringLiteral( "fill_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::fillStyleDesc() ); + registerDataDefinedButton( mBorderStyleDDBtn, QStringLiteral( "border_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::lineStyleDesc() ); + registerDataDefinedButton( mJoinStyleDDBtn, QStringLiteral( "join_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); } @@ -873,7 +873,7 @@ QgsFilledMarkerSymbolLayerWidget::~QgsFilledMarkerSymbolLayerWidget() void QgsFilledMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "FilledMarker" ) + if ( layer->layerType() != QLatin1String( "FilledMarker" ) ) return; // layer type is correct, we can do the cast @@ -907,17 +907,17 @@ void QgsFilledMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) whileBlocking( mHorizontalAnchorComboBox )->setCurrentIndex( mLayer->horizontalAnchorPoint() ); whileBlocking( mVerticalAnchorComboBox )->setCurrentIndex( mLayer->verticalAnchorPoint() ); - registerDataDefinedButton( mNameDDBtn, "name", QgsDataDefinedButton::String, tr( "string " ) + QLatin1String( "[<b>square</b>|<b>rectangle</b>|<b>diamond</b>|" + registerDataDefinedButton( mNameDDBtn, QStringLiteral( "name" ), QgsDataDefinedButton::String, tr( "string " ) + QStringLiteral( "[<b>square</b>|<b>rectangle</b>|<b>diamond</b>|" "<b>pentagon</b>|<b>hexagon</b>|<b>triangle</b>|<b>equilateral_triangle</b>|" "<b>star</b>|<b>arrow</b>|<b>filled_arrowhead</b>|" "<b>circle</b>|<b>cross</b>|<b>cross_fill</b>|<b>x</b>|" "<b>line</b>|<b>arrowhead</b>|<b>cross2</b>|<b>semi_circle</b>|<b>third_circle</b>|<b>quarter_circle</b>|" "<b>quarter_square</b>|<b>half_square</b>|<b>diagonal_half_square</b>|<b>right_half_triangle</b>|<b>left_half_triangle</b>]" ) ); - registerDataDefinedButton( mSizeDDBtn, "size", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mAngleDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); - registerDataDefinedButton( mHorizontalAnchorDDBtn, "horizontal_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); - registerDataDefinedButton( mVerticalAnchorDDBtn, "vertical_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); + registerDataDefinedButton( mSizeDDBtn, QStringLiteral( "size" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mAngleDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); + registerDataDefinedButton( mHorizontalAnchorDDBtn, QStringLiteral( "horizontal_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); + registerDataDefinedButton( mVerticalAnchorDDBtn, QStringLiteral( "vertical_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); updateAssistantSymbol(); } @@ -996,7 +996,7 @@ void QgsFilledMarkerSymbolLayerWidget::updateAssistantSymbol() mAssistantPreviewSymbol->deleteSymbolLayer( i ); } mAssistantPreviewSymbol->appendSymbolLayer( mLayer->clone() ); - QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( "size" ); + QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( QStringLiteral( "size" ) ); if ( ddSize ) mAssistantPreviewSymbol->setDataDefinedSize( *ddSize ); } @@ -1017,12 +1017,12 @@ QgsGradientFillSymbolLayerWidget::QgsGradientFillSymbolLayerWidget( const QgsVec btnChangeColor->setAllowAlpha( true ); btnChangeColor->setColorDialogTitle( tr( "Select gradient color" ) ); - btnChangeColor->setContext( "symbology" ); + btnChangeColor->setContext( QStringLiteral( "symbology" ) ); btnChangeColor->setShowNoColor( true ); btnChangeColor->setNoColorString( tr( "Transparent" ) ); btnChangeColor2->setAllowAlpha( true ); btnChangeColor2->setColorDialogTitle( tr( "Select gradient color" ) ); - btnChangeColor2->setContext( "symbology" ); + btnChangeColor2->setContext( QStringLiteral( "symbology" ) ); btnChangeColor2->setShowNoColor( true ); btnChangeColor2->setNoColorString( tr( "Transparent" ) ); @@ -1050,7 +1050,7 @@ QgsGradientFillSymbolLayerWidget::QgsGradientFillSymbolLayerWidget( const QgsVec void QgsGradientFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "GradientFill" ) + if ( layer->layerType() != QLatin1String( "GradientFill" ) ) return; // layer type is correct, we can do the cast @@ -1173,18 +1173,18 @@ void QgsGradientFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) mOffsetUnitWidget->setMapUnitScale( mLayer->offsetMapUnitScale() ); mOffsetUnitWidget->blockSignals( false ); - registerDataDefinedButton( mStartColorDDBtn, "color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mEndColorDDBtn, "color2", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mAngleDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mGradientTypeDDBtn, "gradient_type", QgsDataDefinedButton::String, QgsDataDefinedButton::gradientTypeDesc() ); - registerDataDefinedButton( mCoordinateModeDDBtn, "coordinate_mode", QgsDataDefinedButton::String, QgsDataDefinedButton::gradientCoordModeDesc() ); - registerDataDefinedButton( mSpreadDDBtn, "spread", QgsDataDefinedButton::Double, QgsDataDefinedButton::gradientSpreadDesc() ); - registerDataDefinedButton( mRefPoint1XDDBtn, "reference1_x", QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); - registerDataDefinedButton( mRefPoint1YDDBtn, "reference1_y", QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); - registerDataDefinedButton( mRefPoint1CentroidDDBtn, "reference1_iscentroid", QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); - registerDataDefinedButton( mRefPoint2XDDBtn, "reference2_x", QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); - registerDataDefinedButton( mRefPoint2YDDBtn, "reference2_y", QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); - registerDataDefinedButton( mRefPoint2CentroidDDBtn, "reference2_iscentroid", QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); + registerDataDefinedButton( mStartColorDDBtn, QStringLiteral( "color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mEndColorDDBtn, QStringLiteral( "color2" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mAngleDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mGradientTypeDDBtn, QStringLiteral( "gradient_type" ), QgsDataDefinedButton::String, QgsDataDefinedButton::gradientTypeDesc() ); + registerDataDefinedButton( mCoordinateModeDDBtn, QStringLiteral( "coordinate_mode" ), QgsDataDefinedButton::String, QgsDataDefinedButton::gradientCoordModeDesc() ); + registerDataDefinedButton( mSpreadDDBtn, QStringLiteral( "spread" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::gradientSpreadDesc() ); + registerDataDefinedButton( mRefPoint1XDDBtn, QStringLiteral( "reference1_x" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); + registerDataDefinedButton( mRefPoint1YDDBtn, QStringLiteral( "reference1_y" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); + registerDataDefinedButton( mRefPoint1CentroidDDBtn, QStringLiteral( "reference1_iscentroid" ), QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); + registerDataDefinedButton( mRefPoint2XDDBtn, QStringLiteral( "reference2_x" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); + registerDataDefinedButton( mRefPoint2YDDBtn, QStringLiteral( "reference2_y" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); + registerDataDefinedButton( mRefPoint2CentroidDDBtn, QStringLiteral( "reference2_iscentroid" ), QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); } QgsSymbolLayer* QgsGradientFillSymbolLayerWidget::symbolLayer() @@ -1352,12 +1352,12 @@ QgsShapeburstFillSymbolLayerWidget::QgsShapeburstFillSymbolLayerWidget( const Qg group2->addButton( mRadioUseWholeShape ); btnChangeColor->setAllowAlpha( true ); btnChangeColor->setColorDialogTitle( tr( "Select gradient color" ) ); - btnChangeColor->setContext( "symbology" ); + btnChangeColor->setContext( QStringLiteral( "symbology" ) ); btnChangeColor->setShowNoColor( true ); btnChangeColor->setNoColorString( tr( "Transparent" ) ); btnChangeColor2->setAllowAlpha( true ); btnChangeColor2->setColorDialogTitle( tr( "Select gradient color" ) ); - btnChangeColor2->setContext( "symbology" ); + btnChangeColor2->setContext( QStringLiteral( "symbology" ) ); btnChangeColor2->setShowNoColor( true ); btnChangeColor2->setNoColorString( tr( "Transparent" ) ); @@ -1382,7 +1382,7 @@ QgsShapeburstFillSymbolLayerWidget::QgsShapeburstFillSymbolLayerWidget( const Qg void QgsShapeburstFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "ShapeburstFill" ) + if ( layer->layerType() != QLatin1String( "ShapeburstFill" ) ) return; // layer type is correct, we can do the cast @@ -1464,12 +1464,12 @@ void QgsShapeburstFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) mOffsetUnitWidget->setMapUnitScale( mLayer->offsetMapUnitScale() ); mOffsetUnitWidget->blockSignals( false ); - registerDataDefinedButton( mStartColorDDBtn, "color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mEndColorDDBtn, "color2", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBlurRadiusDDBtn, "blur_radius", QgsDataDefinedButton::Int, tr( "Integer between 0 and 18" ) ); - registerDataDefinedButton( mShadeWholeShapeDDBtn, "use_whole_shape", QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); - registerDataDefinedButton( mShadeDistanceDDBtn, "max_distance", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mIgnoreRingsDDBtn, "ignore_rings", QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); + registerDataDefinedButton( mStartColorDDBtn, QStringLiteral( "color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mEndColorDDBtn, QStringLiteral( "color2" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBlurRadiusDDBtn, QStringLiteral( "blur_radius" ), QgsDataDefinedButton::Int, tr( "Integer between 0 and 18" ) ); + registerDataDefinedButton( mShadeWholeShapeDDBtn, QStringLiteral( "use_whole_shape" ), QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); + registerDataDefinedButton( mShadeDistanceDDBtn, QStringLiteral( "max_distance" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mIgnoreRingsDDBtn, QStringLiteral( "ignore_rings" ), QgsDataDefinedButton::Int, QgsDataDefinedButton::boolDesc() ); } QgsSymbolLayer* QgsShapeburstFillSymbolLayerWidget::symbolLayer() @@ -1616,7 +1616,7 @@ QgsMarkerLineSymbolLayerWidget::QgsMarkerLineSymbolLayerWidget( const QgsVectorL void QgsMarkerLineSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "MarkerLine" ) + if ( layer->layerType() != QLatin1String( "MarkerLine" ) ) return; // layer type is correct, we can do the cast @@ -1664,10 +1664,10 @@ void QgsMarkerLineSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) setPlacement(); // update gui - registerDataDefinedButton( mIntervalDDBtn, "interval", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mLineOffsetDDBtn, "offset", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mPlacementDDBtn, "placement", QgsDataDefinedButton::String, tr( "string " ) + QLatin1String( "[<b>vertex</b>|<b>lastvertex</b>|<b>firstvertex</b>|<b>centerpoint</b>]" ) ); - registerDataDefinedButton( mOffsetAlongLineDDBtn, "offset_along_line", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mIntervalDDBtn, QStringLiteral( "interval" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mLineOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mPlacementDDBtn, QStringLiteral( "placement" ), QgsDataDefinedButton::String, tr( "string " ) + QStringLiteral( "[<b>vertex</b>|<b>lastvertex</b>|<b>firstvertex</b>|<b>centerpoint</b>]" ) ); + registerDataDefinedButton( mOffsetAlongLineDDBtn, QStringLiteral( "offset_along_line" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); } QgsSymbolLayer* QgsMarkerLineSymbolLayerWidget::symbolLayer() @@ -1766,10 +1766,10 @@ QgsSvgMarkerSymbolLayerWidget::QgsSvgMarkerSymbolLayerWidget( const QgsVectorLay viewGroups->setHeaderHidden( true ); mChangeColorButton->setAllowAlpha( true ); mChangeColorButton->setColorDialogTitle( tr( "Select fill color" ) ); - mChangeColorButton->setContext( "symbology" ); + mChangeColorButton->setContext( QStringLiteral( "symbology" ) ); mChangeBorderColorButton->setAllowAlpha( true ); mChangeBorderColorButton->setColorDialogTitle( tr( "Select border color" ) ); - mChangeBorderColorButton->setContext( "symbology" ); + mChangeBorderColorButton->setContext( QStringLiteral( "symbology" ) ); spinOffsetX->setClearValue( 0.0 ); spinOffsetY->setClearValue( 0.0 ); @@ -1896,7 +1896,7 @@ void QgsSvgMarkerSymbolLayerWidget::updateAssistantSymbol() mAssistantPreviewSymbol->deleteSymbolLayer( i ); } mAssistantPreviewSymbol->appendSymbolLayer( mLayer->clone() ); - QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( "size" ); + QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( QStringLiteral( "size" ) ); if ( ddSize ) mAssistantPreviewSymbol->setDataDefinedSize( *ddSize ); } @@ -1909,7 +1909,7 @@ void QgsSvgMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) return; } - if ( layer->layerType() != "SvgMarker" ) + if ( layer->layerType() != QLatin1String( "SvgMarker" ) ) return; // layer type is correct, we can do the cast @@ -1969,15 +1969,15 @@ void QgsSvgMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) setGuiForSvg( mLayer ); - registerDataDefinedButton( mSizeDDBtn, "size", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mBorderWidthDDBtn, "outline_width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mAngleDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); - registerDataDefinedButton( mFilenameDDBtn, "name", QgsDataDefinedButton::String, QgsDataDefinedButton::filePathDesc() ); - registerDataDefinedButton( mFillColorDDBtn, "fill", QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); - registerDataDefinedButton( mBorderColorDDBtn, "outline", QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); - registerDataDefinedButton( mHorizontalAnchorDDBtn, "horizontal_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); - registerDataDefinedButton( mVerticalAnchorDDBtn, "vertical_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); + registerDataDefinedButton( mSizeDDBtn, QStringLiteral( "size" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mBorderWidthDDBtn, QStringLiteral( "outline_width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mAngleDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); + registerDataDefinedButton( mFilenameDDBtn, QStringLiteral( "name" ), QgsDataDefinedButton::String, QgsDataDefinedButton::filePathDesc() ); + registerDataDefinedButton( mFillColorDDBtn, QStringLiteral( "fill" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); + registerDataDefinedButton( mBorderColorDDBtn, QStringLiteral( "outline" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); + registerDataDefinedButton( mHorizontalAnchorDDBtn, QStringLiteral( "horizontal_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); + registerDataDefinedButton( mVerticalAnchorDDBtn, QStringLiteral( "vertical_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); updateAssistantSymbol(); } @@ -2020,7 +2020,7 @@ void QgsSvgMarkerSymbolLayerWidget::on_mFileToolButton_clicked() QSettings s; QString file = QFileDialog::getOpenFileName( nullptr, tr( "Select SVG file" ), - s.value( "/UI/lastSVGMarkerDir", QDir::homePath() ).toString(), + s.value( QStringLiteral( "/UI/lastSVGMarkerDir" ), QDir::homePath() ).toString(), tr( "SVG files" ) + " (*.svg)" ); QFileInfo fi( file ); if ( file.isEmpty() || !fi.exists() ) @@ -2029,7 +2029,7 @@ void QgsSvgMarkerSymbolLayerWidget::on_mFileToolButton_clicked() } mFileLineEdit->setText( file ); mLayer->setPath( file ); - s.setValue( "/UI/lastSVGMarkerDir", fi.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastSVGMarkerDir" ), fi.absolutePath() ); setGuiForSvg( mLayer ); emit changed(); } @@ -2155,9 +2155,9 @@ QgsSVGFillSymbolLayerWidget::QgsSVGFillSymbolLayerWidget( const QgsVectorLayer* insertIcons(); mChangeColorButton->setColorDialogTitle( tr( "Select fill color" ) ); - mChangeColorButton->setContext( "symbology" ); + mChangeColorButton->setContext( QStringLiteral( "symbology" ) ); mChangeBorderColorButton->setColorDialogTitle( tr( "Select border color" ) ); - mChangeBorderColorButton->setContext( "symbology" ); + mChangeBorderColorButton->setContext( QStringLiteral( "symbology" ) ); connect( mSvgListView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( setFile( const QModelIndex& ) ) ); connect( mSvgTreeView->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( populateIcons( const QModelIndex& ) ) ); @@ -2170,7 +2170,7 @@ void QgsSVGFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) return; } - if ( layer->layerType() != "SVGFill" ) + if ( layer->layerType() != QLatin1String( "SVGFill" ) ) { return; } @@ -2206,12 +2206,12 @@ void QgsSVGFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) } updateParamGui( false ); - registerDataDefinedButton( mTextureWidthDDBtn, "width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mSVGDDBtn, "svgFile", QgsDataDefinedButton::String, QgsDataDefinedButton::svgPathDesc() ); - registerDataDefinedButton( mRotationDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mFilColorDDBtn, "svgFillColor", QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); - registerDataDefinedButton( mBorderColorDDBtn, "svgOutlineColor", QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); - registerDataDefinedButton( mBorderWidthDDBtn, "svgOutlineWidth", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mTextureWidthDDBtn, QStringLiteral( "width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mSVGDDBtn, QStringLiteral( "svgFile" ), QgsDataDefinedButton::String, QgsDataDefinedButton::svgPathDesc() ); + registerDataDefinedButton( mRotationDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mFilColorDDBtn, QStringLiteral( "svgFillColor" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); + registerDataDefinedButton( mBorderColorDDBtn, QStringLiteral( "svgOutlineColor" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorNoAlphaDesc() ); + registerDataDefinedButton( mBorderWidthDDBtn, QStringLiteral( "svgOutlineWidth" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); } QgsSymbolLayer* QgsSVGFillSymbolLayerWidget::symbolLayer() @@ -2441,7 +2441,7 @@ QgsLinePatternFillSymbolLayerWidget::QgsLinePatternFillSymbolLayerWidget( const void QgsLinePatternFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "LinePatternFill" ) + if ( layer->layerType() != QLatin1String( "LinePatternFill" ) ) { return; } @@ -2471,8 +2471,8 @@ void QgsLinePatternFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer mOffsetUnitWidget->blockSignals( false ); } - registerDataDefinedButton( mAngleDDBtn, "lineangle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mDistanceDDBtn, "distance", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mAngleDDBtn, QStringLiteral( "lineangle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mDistanceDDBtn, QStringLiteral( "distance" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); } QgsSymbolLayer* QgsLinePatternFillSymbolLayerWidget::symbolLayer() @@ -2542,7 +2542,7 @@ QgsPointPatternFillSymbolLayerWidget::QgsPointPatternFillSymbolLayerWidget( cons void QgsPointPatternFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( !layer || layer->layerType() != "PointPatternFill" ) + if ( !layer || layer->layerType() != QLatin1String( "PointPatternFill" ) ) { return; } @@ -2578,10 +2578,10 @@ void QgsPointPatternFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer mVerticalDisplacementUnitWidget->setMapUnitScale( mLayer->displacementYMapUnitScale() ); mVerticalDisplacementUnitWidget->blockSignals( false ); - registerDataDefinedButton( mHorizontalDistanceDDBtn, "distance_x", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mVerticalDistanceDDBtn, "distance_y", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mHorizontalDisplacementDDBtn, "displacement_x", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); - registerDataDefinedButton( mVerticalDisplacementDDBtn, "displacement_y", QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mHorizontalDistanceDDBtn, QStringLiteral( "distance_x" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mVerticalDistanceDDBtn, QStringLiteral( "distance_y" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mHorizontalDisplacementDDBtn, QStringLiteral( "displacement_x" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); + registerDataDefinedButton( mVerticalDisplacementDDBtn, QStringLiteral( "displacement_y" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doubleDesc() ); } QgsSymbolLayer* QgsPointPatternFillSymbolLayerWidget::symbolLayer() @@ -2681,10 +2681,10 @@ QgsFontMarkerSymbolLayerWidget::QgsFontMarkerSymbolLayerWidget( const QgsVectorL btnColor->setAllowAlpha( true ); btnColor->setColorDialogTitle( tr( "Select symbol fill color" ) ); - btnColor->setContext( "symbology" ); + btnColor->setContext( QStringLiteral( "symbology" ) ); btnBorderColor->setAllowAlpha( true ); btnBorderColor->setColorDialogTitle( tr( "Select symbol outline color" ) ); - btnBorderColor->setContext( "symbology" ); + btnBorderColor->setContext( QStringLiteral( "symbology" ) ); spinOffsetX->setClearValue( 0.0 ); spinOffsetY->setClearValue( 0.0 ); @@ -2715,7 +2715,7 @@ QgsFontMarkerSymbolLayerWidget::~QgsFontMarkerSymbolLayerWidget() void QgsFontMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "FontMarker" ) + if ( layer->layerType() != QLatin1String( "FontMarker" ) ) return; // layer type is correct, we can do the cast @@ -2760,16 +2760,16 @@ void QgsFontMarkerSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) whileBlocking( mHorizontalAnchorComboBox )->setCurrentIndex( mLayer->horizontalAnchorPoint() ); whileBlocking( mVerticalAnchorComboBox )->setCurrentIndex( mLayer->verticalAnchorPoint() ); - registerDataDefinedButton( mSizeDDBtn, "size", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mRotationDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mColorDDBtn, "color", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBorderColorDDBtn, "color_border", QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); - registerDataDefinedButton( mBorderWidthDDBtn, "outline_width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); - registerDataDefinedButton( mJoinStyleDDBtn, "join_style", QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); - registerDataDefinedButton( mOffsetDDBtn, "offset", QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); - registerDataDefinedButton( mHorizontalAnchorDDBtn, "horizontal_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); - registerDataDefinedButton( mVerticalAnchorDDBtn, "vertical_anchor_point", QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); - registerDataDefinedButton( mCharDDBtn, "char", QgsDataDefinedButton::String, QgsDataDefinedButton::charDesc() ); + registerDataDefinedButton( mSizeDDBtn, QStringLiteral( "size" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mRotationDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mColorDDBtn, QStringLiteral( "color" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBorderColorDDBtn, QStringLiteral( "color_border" ), QgsDataDefinedButton::String, QgsDataDefinedButton::colorAlphaDesc() ); + registerDataDefinedButton( mBorderWidthDDBtn, QStringLiteral( "outline_width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mJoinStyleDDBtn, QStringLiteral( "join_style" ), QgsDataDefinedButton::String, QgsDataDefinedButton::penJoinStyleDesc() ); + registerDataDefinedButton( mOffsetDDBtn, QStringLiteral( "offset" ), QgsDataDefinedButton::String, QgsDataDefinedButton::doubleXYDesc() ); + registerDataDefinedButton( mHorizontalAnchorDDBtn, QStringLiteral( "horizontal_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::horizontalAnchorDesc() ); + registerDataDefinedButton( mVerticalAnchorDDBtn, QStringLiteral( "vertical_anchor_point" ), QgsDataDefinedButton::String, QgsDataDefinedButton::verticalAnchorDesc() ); + registerDataDefinedButton( mCharDDBtn, QStringLiteral( "char" ), QgsDataDefinedButton::String, QgsDataDefinedButton::charDesc() ); updateAssistantSymbol(); } @@ -2893,7 +2893,7 @@ void QgsFontMarkerSymbolLayerWidget::updateAssistantSymbol() mAssistantPreviewSymbol->deleteSymbolLayer( i ); } mAssistantPreviewSymbol->appendSymbolLayer( mLayer->clone() ); - QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( "size" ); + QgsDataDefined* ddSize = mLayer->getDataDefinedProperty( QStringLiteral( "size" ) ); if ( ddSize ) mAssistantPreviewSymbol->setDataDefinedSize( *ddSize ); } @@ -2911,7 +2911,7 @@ QgsCentroidFillSymbolLayerWidget::QgsCentroidFillSymbolLayerWidget( const QgsVec void QgsCentroidFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "CentroidFill" ) + if ( layer->layerType() != QLatin1String( "CentroidFill" ) ) return; // layer type is correct, we can do the cast @@ -2965,7 +2965,7 @@ void QgsRasterFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer *layer ) return; } - if ( layer->layerType() != "RasterFill" ) + if ( layer->layerType() != QLatin1String( "RasterFill" ) ) { return; } @@ -3022,10 +3022,10 @@ void QgsRasterFillSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer *layer ) mWidthUnitWidget->blockSignals( false ); updatePreviewImage(); - registerDataDefinedButton( mFilenameDDBtn, "file", QgsDataDefinedButton::String, QgsDataDefinedButton::filePathDesc() ); - registerDataDefinedButton( mOpacityDDBtn, "alpha", QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); - registerDataDefinedButton( mRotationDDBtn, "angle", QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); - registerDataDefinedButton( mWidthDDBtn, "width", QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); + registerDataDefinedButton( mFilenameDDBtn, QStringLiteral( "file" ), QgsDataDefinedButton::String, QgsDataDefinedButton::filePathDesc() ); + registerDataDefinedButton( mOpacityDDBtn, QStringLiteral( "alpha" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double0to1Desc() ); + registerDataDefinedButton( mRotationDDBtn, QStringLiteral( "angle" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::double180RotDesc() ); + registerDataDefinedButton( mWidthDDBtn, QStringLiteral( "width" ), QgsDataDefinedButton::Double, QgsDataDefinedButton::doublePosDesc() ); } QgsSymbolLayer *QgsRasterFillSymbolLayerWidget::symbolLayer() @@ -3046,7 +3046,7 @@ void QgsRasterFillSymbolLayerWidget::on_mBrowseToolButton_clicked() if ( openDir.isEmpty() ) { - openDir = s.value( "/UI/lastRasterFillImageDir", QDir::homePath() ).toString(); + openDir = s.value( QStringLiteral( "/UI/lastRasterFillImageDir" ), QDir::homePath() ).toString(); } //show file dialog @@ -3057,11 +3057,11 @@ void QgsRasterFillSymbolLayerWidget::on_mBrowseToolButton_clicked() QFileInfo fileInfo( filePath ); if ( !fileInfo.exists() || !fileInfo.isReadable() ) { - QMessageBox::critical( nullptr, "Invalid file", "Error, file does not exist or is not readable" ); + QMessageBox::critical( nullptr, QStringLiteral( "Invalid file" ), QStringLiteral( "Error, file does not exist or is not readable" ) ); return; } - s.setValue( "/UI/lastRasterFillImageDir", fileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/UI/lastRasterFillImageDir" ), fileInfo.absolutePath() ); mImageLineEdit->setText( filePath ); on_mImageLineEdit_editingFinished(); } @@ -3224,9 +3224,9 @@ QgsGeometryGeneratorSymbolLayerWidget::QgsGeometryGeneratorSymbolLayerWidget( co modificationExpressionSelector->setMultiLine( true ); modificationExpressionSelector->setLayer( const_cast<QgsVectorLayer*>( vl ) ); modificationExpressionSelector->registerExpressionContextGenerator( this ); - cbxGeometryType->addItem( QgsApplication::getThemeIcon( "/mIconPolygonLayer.svg" ), tr( "Polygon / MultiPolygon" ), QgsSymbol::Fill ); - cbxGeometryType->addItem( QgsApplication::getThemeIcon( "/mIconLineLayer.svg" ), tr( "LineString / MultiLineString" ), QgsSymbol::Line ); - cbxGeometryType->addItem( QgsApplication::getThemeIcon( "/mIconPointLayer.svg" ), tr( "Point / MultiPoint" ), QgsSymbol::Marker ); + cbxGeometryType->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPolygonLayer.svg" ) ), tr( "Polygon / MultiPolygon" ), QgsSymbol::Fill ); + cbxGeometryType->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconLineLayer.svg" ) ), tr( "LineString / MultiLineString" ), QgsSymbol::Line ); + cbxGeometryType->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPointLayer.svg" ) ), tr( "Point / MultiPoint" ), QgsSymbol::Marker ); connect( modificationExpressionSelector, SIGNAL( expressionChanged( QString ) ), this, SLOT( updateExpression( QString ) ) ); connect( cbxGeometryType, SIGNAL( currentIndexChanged( int ) ), this, SLOT( updateSymbolType() ) ); } diff --git a/src/gui/symbology-ng/qgssymbollevelsdialog.cpp b/src/gui/symbology-ng/qgssymbollevelsdialog.cpp index 70deef91cc5c..3d47f7b5934f 100644 --- a/src/gui/symbology-ng/qgssymbollevelsdialog.cpp +++ b/src/gui/symbology-ng/qgssymbollevelsdialog.cpp @@ -35,7 +35,7 @@ QgsSymbolLevelsDialog::QgsSymbolLevelsDialog( const QgsLegendSymbolList& list, b setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/symbolLevelsDlg/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/symbolLevelsDlg/geometry" ) ).toByteArray() ); tableLevels->setItemDelegate( new SpinBoxDelegate( this ) ); @@ -88,7 +88,7 @@ QgsSymbolLevelsDialog::QgsSymbolLevelsDialog( const QgsLegendSymbolList& list, b QgsSymbolLevelsDialog::~QgsSymbolLevelsDialog() { QSettings settings; - settings.setValue( "/Windows/symbolLevelsDlg/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/symbolLevelsDlg/geometry" ), saveGeometry() ); } void QgsSymbolLevelsDialog::populateTable() diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.cpp b/src/gui/symbology-ng/qgssymbolselectordialog.cpp index a727846b15ab..05dd9ceb9ea1 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.cpp +++ b/src/gui/symbology-ng/qgssymbolselectordialog.cpp @@ -236,10 +236,10 @@ QgsSymbolSelectorWidget::QgsSymbolSelectorWidget( QgsSymbol* symbol, QgsStyle* s btnAddLayer->setIcon( QIcon( QgsApplication::iconPath( "symbologyAdd.svg" ) ) ); btnRemoveLayer->setIcon( QIcon( QgsApplication::iconPath( "symbologyRemove.svg" ) ) ); QIcon iconLock; - iconLock.addFile( QgsApplication::iconPath( "locked.svg" ), QSize(), QIcon::Normal, QIcon::On ); - iconLock.addFile( QgsApplication::iconPath( "locked.svg" ), QSize(), QIcon::Active, QIcon::On ); - iconLock.addFile( QgsApplication::iconPath( "unlocked.svg" ), QSize(), QIcon::Normal, QIcon::Off ); - iconLock.addFile( QgsApplication::iconPath( "unlocked.svg" ), QSize(), QIcon::Active, QIcon::Off ); + iconLock.addFile( QgsApplication::iconPath( QStringLiteral( "locked.svg" ) ), QSize(), QIcon::Normal, QIcon::On ); + iconLock.addFile( QgsApplication::iconPath( QStringLiteral( "locked.svg" ) ), QSize(), QIcon::Active, QIcon::On ); + iconLock.addFile( QgsApplication::iconPath( QStringLiteral( "unlocked.svg" ) ), QSize(), QIcon::Normal, QIcon::Off ); + iconLock.addFile( QgsApplication::iconPath( QStringLiteral( "unlocked.svg" ) ), QSize(), QIcon::Active, QIcon::Off ); btnLock->setIcon( iconLock ); btnDuplicate->setIcon( QIcon( QgsApplication::iconPath( "mActionDuplicateLayer.svg" ) ) ); btnUp->setIcon( QIcon( QgsApplication::iconPath( "symbologyUp.svg" ) ) ); @@ -692,7 +692,7 @@ QgsSymbolSelectorDialog::QgsSymbolSelectorDialog( QgsSymbol *symbol, QgsStyle *s layout()->addWidget( mButtonBox ); QSettings settings; - restoreGeometry( settings.value( "/Windows/SymbolSelectorWidget/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/SymbolSelectorWidget/geometry" ) ).toByteArray() ); // can be embedded in renderer properties dialog if ( embedded ) @@ -706,7 +706,7 @@ QgsSymbolSelectorDialog::QgsSymbolSelectorDialog( QgsSymbol *symbol, QgsStyle *s QgsSymbolSelectorDialog::~QgsSymbolSelectorDialog() { QSettings settings; - settings.setValue( "/Windows/SymbolSelectorWidget/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/SymbolSelectorWidget/geometry" ), saveGeometry() ); } QMenu *QgsSymbolSelectorDialog::advancedMenu() diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index 389fe874f430..235aa8e7ab51 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -70,7 +70,7 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, connect( mClipFeaturesAction, SIGNAL( toggled( bool ) ), this, SLOT( clipFeaturesToggled( bool ) ) ); // populate the groups - groupsCombo->addItem( "" ); + groupsCombo->addItem( QLatin1String( "" ) ); populateGroups(); QStringList groups = style->smartgroupNames(); Q_FOREACH ( const QString& group, groups ) @@ -85,7 +85,7 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, connect( mStyle, SIGNAL( symbolSaved( QString, QgsSymbol* ) ), this, SLOT( symbolAddedToStyle( QString, QgsSymbol* ) ) ); connect( openStyleManagerButton, SIGNAL( pressed() ), this, SLOT( openStyleManager() ) ); - lblSymbolName->setText( "" ); + lblSymbolName->setText( QLatin1String( "" ) ); populateSymbolView(); if ( mSymbol ) @@ -117,7 +117,7 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, btnColor->setAcceptLiveUpdates( false ); btnColor->setAllowAlpha( true ); btnColor->setColorDialogTitle( tr( "Select color" ) ); - btnColor->setContext( "symbology" ); + btnColor->setContext( QStringLiteral( "symbology" ) ); connect( btnSaveSymbol, SIGNAL( clicked() ), this, SLOT( saveSymbol() ) ); } @@ -567,7 +567,7 @@ void QgsSymbolsListWidget::on_groupsCombo_currentIndexChanged( int index ) else { int groupid; - if ( groupsCombo->itemData( index ).toString() == "smart" ) + if ( groupsCombo->itemData( index ).toString() == QLatin1String( "smart" ) ) { groupid = mStyle->smartgroupId( text ); symbols = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, groupid ); diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.h b/src/gui/symbology-ng/qgssymbolslistwidget.h index dd8809364014..e12cc8e66c43 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.h +++ b/src/gui/symbology-ng/qgssymbolslistwidget.h @@ -100,7 +100,7 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW /** Displays alpha value as transparency in mTransparencyLabel*/ void displayTransparency( double alpha ); /** Recursive function to create the group tree in the widget */ - void populateGroups( const QString& parent = "", const QString& prepend = "" ); + void populateGroups( const QString& parent = QLatin1String( "" ), const QString& prepend = QLatin1String( "" ) ); QgsSymbolWidgetContext mContext; diff --git a/src/gui/symbology-ng/qgsvectorfieldsymbollayerwidget.cpp b/src/gui/symbology-ng/qgsvectorfieldsymbollayerwidget.cpp index 0f7b592247d2..323de98a04c5 100644 --- a/src/gui/symbology-ng/qgsvectorfieldsymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgsvectorfieldsymbollayerwidget.cpp @@ -24,8 +24,8 @@ QgsVectorFieldSymbolLayerWidget::QgsVectorFieldSymbolLayerWidget( const QgsVecto if ( vectorLayer() ) { - mXAttributeComboBox->addItem( "" ); - mYAttributeComboBox->addItem( "" ); + mXAttributeComboBox->addItem( QLatin1String( "" ) ); + mYAttributeComboBox->addItem( QLatin1String( "" ) ); int i = 0; Q_FOREACH ( const QgsField& f, vectorLayer()->fields() ) { @@ -43,7 +43,7 @@ QgsVectorFieldSymbolLayerWidget::~QgsVectorFieldSymbolLayerWidget() void QgsVectorFieldSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer* layer ) { - if ( layer->layerType() != "VectorField" ) + if ( layer->layerType() != QLatin1String( "VectorField" ) ) { return; } @@ -162,7 +162,7 @@ void QgsVectorFieldSymbolLayerWidget::on_mHeightRadioButton_toggled( bool checke if ( mLayer && checked ) { mLayer->setVectorFieldType( QgsVectorFieldSymbolLayer::Height ); - mXAttributeLabel->setText( "" ); + mXAttributeLabel->setText( QLatin1String( "" ) ); mXAttributeComboBox->setEnabled( false ); mYAttributeLabel->setText( tr( "Height attribute" ) ); emit changed(); diff --git a/src/helpviewer/main.cpp b/src/helpviewer/main.cpp index 6988c92bff0c..b5c5a41b9ac1 100644 --- a/src/helpviewer/main.cpp +++ b/src/helpviewer/main.cpp @@ -31,11 +31,11 @@ int main( int argc, char ** argv ) QgsApplication a( argc, argv, true ); // Set up the QSettings environment must be done after qapp is created - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS3" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS3" ) ); - QString myTranslationCode = ""; + QString myTranslationCode = QLatin1String( "" ); if ( argc == 2 ) { @@ -60,9 +60,9 @@ int main( int argc, char ** argv ) myTranslationCode = QLocale::system().name(); QSettings settings; - if ( settings.value( "locale/overrideFlag", false ).toBool() ) + if ( settings.value( QStringLiteral( "locale/overrideFlag" ), false ).toBool() ) { - myTranslationCode = settings.value( "locale/userLocale", "en_US" ).toString(); + myTranslationCode = settings.value( QStringLiteral( "locale/userLocale" ), "en_US" ).toString(); } } QgsDebugMsg( QString( "Setting translation to %1/qgis_%2" ).arg( i18nPath, myTranslationCode ) ); @@ -70,7 +70,7 @@ int main( int argc, char ** argv ) /* Translation file for QGIS. */ QTranslator qgistor( nullptr ); - if ( qgistor.load( QString( "qgis_" ) + myTranslationCode, i18nPath ) ) + if ( qgistor.load( QStringLiteral( "qgis_" ) + myTranslationCode, i18nPath ) ) { a.installTranslator( &qgistor ); } @@ -81,7 +81,7 @@ int main( int argc, char ** argv ) * These items must be translated identically in both qt_ and qgis_ files. */ QTranslator qttor( nullptr ); - if ( qttor.load( QString( "qt_" ) + myTranslationCode, QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) + if ( qttor.load( QStringLiteral( "qt_" ) + myTranslationCode, QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ) ) { a.installTranslator( &qttor ); } diff --git a/src/helpviewer/qgshelpviewer.cpp b/src/helpviewer/qgshelpviewer.cpp index cc4057c2d6c5..044b3261d550 100644 --- a/src/helpviewer/qgshelpviewer.cpp +++ b/src/helpviewer/qgshelpviewer.cpp @@ -112,11 +112,11 @@ void QgsHelpViewer::resizeEvent( QResizeEvent *event ) void QgsHelpViewer::restorePosition() { QSettings settings; - restoreGeometry( settings.value( "/HelpViewer/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/HelpViewer/geometry" ) ).toByteArray() ); } void QgsHelpViewer::saveWindowLocation() { QSettings settings; - settings.setValue( "/HelpViewer/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/HelpViewer/geometry" ), saveGeometry() ); } diff --git a/src/plugins/coordinate_capture/coordinatecapture.cpp b/src/plugins/coordinate_capture/coordinatecapture.cpp index 5980ecf3fdff..1c1fcdd5e63b 100644 --- a/src/plugins/coordinate_capture/coordinatecapture.cpp +++ b/src/plugins/coordinate_capture/coordinatecapture.cpp @@ -51,7 +51,7 @@ static const QString sName = QObject::tr( "Coordinate Capture" ); static const QString sDescription = QObject::tr( "Capture mouse coordinates in different CRS" ); static const QString sCategory = QObject::tr( "Vector" ); static const QString sPluginVersion = QObject::tr( "Version 0.1" ); -static const QString sPluginIcon = ":/coordinate_capture/coordinate_capture.png"; +static const QString sPluginIcon = QStringLiteral( ":/coordinate_capture/coordinate_capture.png" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; ////////////////////////////////////////////////////////////////////// @@ -101,13 +101,13 @@ void CoordinateCapture::initGui() //create the dock widget mpDockWidget = new QgsDockWidget( tr( "Coordinate Capture" ), mQGisIface->mainWindow() ); - mpDockWidget->setObjectName( "CoordinateCapture" ); + mpDockWidget->setObjectName( QStringLiteral( "CoordinateCapture" ) ); mpDockWidget->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); mQGisIface->addDockWidget( Qt::LeftDockWidgetArea, mpDockWidget ); // Create the action for tool mQActionPointer = new QAction( QIcon(), tr( "Coordinate Capture" ), this ); - mQActionPointer->setObjectName( "mQActionPointer" ); + mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); mQActionPointer->setCheckable( true ); mQActionPointer->setChecked( mpDockWidget->isVisible() ); // Set the what's this text @@ -161,7 +161,7 @@ void CoordinateCapture::initGui() connect( mpCaptureButton, SIGNAL( clicked() ), this, SLOT( run() ) ); // Set the icons - setCurrentTheme( "" ); + setCurrentTheme( QLatin1String( "" ) ); mypLayout->addWidget( mypUserCrsToolButton, 0, 0 ); mypLayout->addWidget( mpUserCrsEdit, 0, 1 ); @@ -289,7 +289,7 @@ void CoordinateCapture::setCurrentTheme( const QString& theThemeName ) mpTrackMouseButton->setIcon( QIcon( getIconPath( "tracking.svg" ) ) ); mpCaptureButton->setIcon( QIcon( getIconPath( "coordinate_capture.png" ) ) ); mypUserCrsToolButton->setIcon( QIcon( getIconPath( "geographic.png" ) ) ); - mypCRSLabel->setPixmap( QPixmap( getIconPath( "transformed.svg" ) ) ); + mypCRSLabel->setPixmap( QPixmap( getIconPath( QStringLiteral( "transformed.svg" ) ) ) ); } } @@ -313,7 +313,7 @@ QString CoordinateCapture::getIconPath( const QString& theName ) } else { - return ""; + return QLatin1String( "" ); } } diff --git a/src/plugins/dxf2shp_converter/builder.cpp b/src/plugins/dxf2shp_converter/builder.cpp index da7f0f28a6e2..611bfa0becc2 100644 --- a/src/plugins/dxf2shp_converter/builder.cpp +++ b/src/plugins/dxf2shp_converter/builder.cpp @@ -411,7 +411,7 @@ void Builder::print_shpObjects() SHPHandle hSHP; - if ( fname.endsWith( ".shp", Qt::CaseInsensitive ) ) + if ( fname.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) { QString fn( fname.mid( fname.length() - 4 ) ); diff --git a/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp b/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp index 492bf1ca2566..cc69f8cd2381 100644 --- a/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp +++ b/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp @@ -38,7 +38,7 @@ static const QString sDescription = QObject::tr( "Converts from dxf to shp file static const QString sCategory = QObject::tr( "Vector" ); static const QString sPluginVersion = QObject::tr( "Version 0.1" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/dxf2shp_converter.png"; +static const QString sPluginIcon = QStringLiteral( ":/dxf2shp_converter.png" ); ////////////////////////////////////////////////////////////////////// // @@ -70,11 +70,11 @@ void dxf2shpConverter::initGui() { // Create the action for tool delete mQActionPointer; - mQActionPointer = new QAction( QIcon(), "Dxf2Shp Converter", this ); - mQActionPointer->setObjectName( "mQActionPointer" ); + mQActionPointer = new QAction( QIcon(), QStringLiteral( "Dxf2Shp Converter" ), this ); + mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); // Set the icon - setCurrentTheme( "" ); + setCurrentTheme( QLatin1String( "" ) ); // Set the what's this text mQActionPointer->setWhatsThis( tr( "Converts DXF files in Shapefile format" ) ); @@ -124,7 +124,7 @@ void dxf2shpConverter::unload() void dxf2shpConverter::addMyLayer( const QString& myfname, const QString& mytitle ) { - mQGisIface->addVectorLayer( myfname, mytitle, "ogr" ); + mQGisIface->addVectorLayer( myfname, mytitle, QStringLiteral( "ogr" ) ); } //! Set icons to the current theme @@ -133,7 +133,7 @@ void dxf2shpConverter::setCurrentTheme( const QString& theThemeName ) Q_UNUSED( theThemeName ); QString myCurThemePath = QgsApplication::activeThemePath() + "/plugins/dxf2shp_converter.png"; QString myDefThemePath = QgsApplication::defaultThemePath() + "/plugins/dxf2shp_converter.png"; - QString myQrcPath = ":/dxf2shp_converter.png"; + QString myQrcPath = QStringLiteral( ":/dxf2shp_converter.png" ); if ( mQActionPointer ) { if ( QFile::exists( myCurThemePath ) ) diff --git a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp b/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp index 4c276e5e541d..988b974ceabf 100644 --- a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp +++ b/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp @@ -37,7 +37,7 @@ dxf2shpConverterGui::dxf2shpConverterGui( QWidget *parent, Qt::WindowFlags fl ): dxf2shpConverterGui::~dxf2shpConverterGui() { QSettings settings; - settings.setValue( "/Plugin-DXF/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Plugin-DXF/geometry" ), saveGeometry() ); } void dxf2shpConverterGui::on_buttonBox_accepted() @@ -87,16 +87,16 @@ void dxf2shpConverterGui::on_buttonBox_accepted() parser->print_shpObjects(); - emit createLayer( parser->outputShp(), "Data layer" ); + emit createLayer( parser->outputShp(), QStringLiteral( "Data layer" ) ); if ( convertTextCheck->isChecked() && parser->textObjectsSize() > 0 ) { - emit createLayer( parser->outputTShp(), "Text layer" ); + emit createLayer( parser->outputTShp(), QStringLiteral( "Text layer" ) ); } if ( convertInsertCheck->isChecked() && parser->insertObjectsSize() > 0 ) { - emit createLayer( parser->outputIShp(), "Insert layer" ); + emit createLayer( parser->outputIShp(), QStringLiteral( "Insert layer" ) ); } delete parser; @@ -125,7 +125,7 @@ void dxf2shpConverterGui::on_buttonBox_helpRequested() "CNR, Milan Unit (Information Technology), Construction Technologies Institute.\n" "For support send a mail to scala@itc.cnr.it\n" ); - QMessageBox::information( this, "Help", s ); + QMessageBox::information( this, QStringLiteral( "Help" ), s ); } void dxf2shpConverterGui::on_btnBrowseForFile_clicked() @@ -143,13 +143,13 @@ void dxf2shpConverterGui::getInputFileName() QSettings settings; QString s = QFileDialog::getOpenFileName( this, tr( "Choose a DXF file to open" ), - settings.value( "/Plugin-DXF/text_path", QDir::homePath() ).toString(), + settings.value( QStringLiteral( "/Plugin-DXF/text_path" ), QDir::homePath() ).toString(), tr( "DXF files" ) + " (*.dxf)" ); if ( !s.isEmpty() ) { name->setText( s ); - settings.setValue( "/Plugin-DXF/text_path", QFileInfo( s ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-DXF/text_path" ), QFileInfo( s ).absolutePath() ); } } @@ -158,22 +158,22 @@ void dxf2shpConverterGui::getOutputDir() QSettings settings; QString s = QFileDialog::getSaveFileName( this, tr( "Choose a file name to save to" ), - settings.value( "/UI/lastShapefileDir", QDir::homePath() ).toString(), + settings.value( QStringLiteral( "/UI/lastShapefileDir" ), QDir::homePath() ).toString(), tr( "Shapefile" ) + " (*.shp)" ); if ( !s.isEmpty() ) { - if ( !s.endsWith( ".shp", Qt::CaseInsensitive ) ) + if ( !s.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) { - s += ".shp"; + s += QLatin1String( ".shp" ); } dirout->setText( s ); - settings.setValue( "/UI/lastShapefileDir", QFileInfo( s ).absolutePath() ); + settings.setValue( QStringLiteral( "/UI/lastShapefileDir" ), QFileInfo( s ).absolutePath() ); } } void dxf2shpConverterGui::restoreState() { QSettings settings; - restoreGeometry( settings.value( "/Plugin-DXF/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Plugin-DXF/geometry" ) ).toByteArray() ); } diff --git a/src/plugins/evis/databaseconnection/evisdatabaseconnection.cpp b/src/plugins/evis/databaseconnection/evisdatabaseconnection.cpp index cc544d8f777a..f2a2b60d1049 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaseconnection.cpp +++ b/src/plugins/evis/databaseconnection/evisdatabaseconnection.cpp @@ -60,56 +60,56 @@ bool eVisDatabaseConnection::connect() } //Add the correct database to the list of database connections, Reuse a connection if the connection exists in the list already. - if ( MSACCESS == databaseType() && !mDatabase.contains( "odbc" ) ) + if ( MSACCESS == databaseType() && !mDatabase.contains( QStringLiteral( "odbc" ) ) ) { - mDatabase = QSqlDatabase::addDatabase( "QODBC", "odbc" ); + mDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QODBC" ), QStringLiteral( "odbc" ) ); } else if ( MSACCESS == databaseType() ) { - mDatabase = QSqlDatabase::database( "odbc" ); + mDatabase = QSqlDatabase::database( QStringLiteral( "odbc" ) ); } - else if ( QMYSQL == databaseType() && !mDatabase.contains( "mysql" ) ) + else if ( QMYSQL == databaseType() && !mDatabase.contains( QStringLiteral( "mysql" ) ) ) { - mDatabase = QSqlDatabase::addDatabase( "QMYSQL", "mysql" ); + mDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QMYSQL" ), QStringLiteral( "mysql" ) ); } else if ( QMYSQL == databaseType() ) { - mDatabase = QSqlDatabase::database( "mysql" ); + mDatabase = QSqlDatabase::database( QStringLiteral( "mysql" ) ); } - else if ( QODBC == databaseType() && !mDatabase.contains( "odbc" ) ) + else if ( QODBC == databaseType() && !mDatabase.contains( QStringLiteral( "odbc" ) ) ) { - mDatabase = QSqlDatabase::addDatabase( "QODBC", "odbc" ); + mDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QODBC" ), QStringLiteral( "odbc" ) ); } else if ( QODBC == databaseType() ) { - mDatabase = QSqlDatabase::database( "odbc" ); + mDatabase = QSqlDatabase::database( QStringLiteral( "odbc" ) ); } - else if ( QPSQL == databaseType() && !mDatabase.contains( "postgres" ) ) + else if ( QPSQL == databaseType() && !mDatabase.contains( QStringLiteral( "postgres" ) ) ) { - mDatabase = QSqlDatabase::addDatabase( "QPSQL", "postgres" ); + mDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QPSQL" ), QStringLiteral( "postgres" ) ); } else if ( QPSQL == databaseType() ) { - mDatabase = QSqlDatabase::database( "postgres" ); + mDatabase = QSqlDatabase::database( QStringLiteral( "postgres" ) ); } - else if ( QSQLITE == databaseType() && !mDatabase.contains( "sqlite" ) ) + else if ( QSQLITE == databaseType() && !mDatabase.contains( QStringLiteral( "sqlite" ) ) ) { - mDatabase = QSqlDatabase::addDatabase( "QSQLITE", "sqlite" ); + mDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QSQLITE" ), QStringLiteral( "sqlite" ) ); } else if ( QSQLITE == databaseType() ) { - mDatabase = QSqlDatabase::database( "sqlite" ); + mDatabase = QSqlDatabase::database( QStringLiteral( "sqlite" ) ); } else { - setLastError( "No matching DATABASE_TYPE found" ); + setLastError( QStringLiteral( "No matching DATABASE_TYPE found" ) ); return false; } //Do a little extra validation of connection information if ( mHostName.isEmpty() && ( QMYSQL == databaseType() || QPSQL == databaseType() ) ) { - setLastError( "Host name was empty" ); + setLastError( QStringLiteral( "Host name was empty" ) ); return false; } else if ( !mHostName.isEmpty() ) @@ -124,7 +124,7 @@ bool eVisDatabaseConnection::connect() if ( mDatabaseName.isEmpty() ) { - setLastError( "Database name was empty" ); + setLastError( QStringLiteral( "Database name was empty" ) ); return false; } else if ( MSACCESS == databaseType() ) @@ -181,7 +181,7 @@ QSqlQuery* eVisDatabaseConnection::query( const QString& sqlStatement ) } } - setLastError( "Database connection was not open." ); + setLastError( QStringLiteral( "Database connection was not open." ) ); return nullptr; } @@ -214,6 +214,6 @@ QStringList eVisDatabaseConnection::tables() return mDatabase.tables(); } - setLastError( "Database connection was not open." ); + setLastError( QStringLiteral( "Database connection was not open." ) ); return QStringList(); } diff --git a/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.cpp b/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.cpp index 8f87d4ac0e86..b407ec7e4d16 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.cpp +++ b/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.cpp @@ -52,7 +52,7 @@ eVisDatabaseConnectionGui::eVisDatabaseConnectionGui( QList<QTemporaryFile*>* th setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/eVis/db-geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/eVis/db-geometry" ) ).toByteArray() ); mTempOutputFileList = theTemoraryFileList; @@ -68,10 +68,10 @@ eVisDatabaseConnectionGui::eVisDatabaseConnectionGui( QList<QTemporaryFile*>* th #ifdef Q_OS_WIN cboxDatabaseType->insertItem( 0, "MSAccess" ); #endif - cboxDatabaseType->insertItem( 0, "MYSQL" ); - cboxDatabaseType->insertItem( 0, "ODBC" ); - cboxDatabaseType->insertItem( 0, "PostGreSQL" ); - cboxDatabaseType->insertItem( 0, "SQLITE" ); + cboxDatabaseType->insertItem( 0, QStringLiteral( "MYSQL" ) ); + cboxDatabaseType->insertItem( 0, QStringLiteral( "ODBC" ) ); + cboxDatabaseType->insertItem( 0, QStringLiteral( "PostGreSQL" ) ); + cboxDatabaseType->insertItem( 0, QStringLiteral( "SQLITE" ) ); cboxDatabaseType->insertItem( 0, tr( "Undefined" ) ); cboxDatabaseType->setCurrentIndex( 0 ); cboxPredefinedQueryList->insertItem( 0, tr( "No predefined queries loaded" ) ); @@ -90,7 +90,7 @@ eVisDatabaseConnectionGui::eVisDatabaseConnectionGui( QList<QTemporaryFile*>* th eVisDatabaseConnectionGui::~eVisDatabaseConnectionGui() { QSettings settings; - settings.setValue( "/eVis/db-geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/eVis/db-geometry" ), saveGeometry() ); } /* @@ -114,11 +114,11 @@ void eVisDatabaseConnectionGui::drawNewVectorLayer( const QString& layerName, co //the last file in the list is always the newest mTempOutputFileList->last()->open(); QUrl url = QUrl::fromLocalFile( mTempOutputFileList->last()->fileName() ); - url.addQueryItem( "delimiter", "\t" ); - url.addQueryItem( "delimiterType", "regexp" ); - url.addQueryItem( "xField", xCoordinate ); - url.addQueryItem( "yField", yCoordinate ); - emit drawVectorLayer( QString::fromAscii( url.toEncoded() ), layerName, "delimitedtext" ); + url.addQueryItem( QStringLiteral( "delimiter" ), QStringLiteral( "\t" ) ); + url.addQueryItem( QStringLiteral( "delimiterType" ), QStringLiteral( "regexp" ) ); + url.addQueryItem( QStringLiteral( "xField" ), xCoordinate ); + url.addQueryItem( QStringLiteral( "yField" ), yCoordinate ); + emit drawVectorLayer( QString::fromAscii( url.toEncoded() ), layerName, QStringLiteral( "delimitedtext" ) ); mTempOutputFileList->last()->close(); } } @@ -156,64 +156,64 @@ void eVisDatabaseConnectionGui::on_buttonBox_accepted() void eVisDatabaseConnectionGui::on_cboxDatabaseType_currentIndexChanged( int currentIndex ) { Q_UNUSED( currentIndex ); - if ( cboxDatabaseType->currentText() == "MYSQL" ) + if ( cboxDatabaseType->currentText() == QLatin1String( "MYSQL" ) ) { lblDatabaseHost->setEnabled( true ); leDatabaseHost->setEnabled( true ); lblDatabasePort->setEnabled( true ); - leDatabasePort->setText( "3306" ); + leDatabasePort->setText( QStringLiteral( "3306" ) ); leDatabasePort->setEnabled( true ); pbtnOpenFile->setEnabled( false ); lblDatabaseUsername->setEnabled( true ); leDatabaseUsername->setEnabled( true ); lblDatabasePassword->setEnabled( true ); leDatabasePassword->setEnabled( true ); - leDatabaseName->setText( "" ); + leDatabaseName->setText( QLatin1String( "" ) ); } - else if ( cboxDatabaseType->currentText() == "PostGreSQL" ) + else if ( cboxDatabaseType->currentText() == QLatin1String( "PostGreSQL" ) ) { lblDatabaseHost->setEnabled( true ); leDatabaseHost->setEnabled( true ); lblDatabasePort->setEnabled( true ); - leDatabasePort->setText( "5432" ); + leDatabasePort->setText( QStringLiteral( "5432" ) ); leDatabasePort->setEnabled( true ); pbtnOpenFile->setEnabled( false ); lblDatabaseUsername->setEnabled( true ); leDatabaseUsername->setEnabled( true ); lblDatabasePassword->setEnabled( true ); leDatabasePassword->setEnabled( true ); - leDatabaseName->setText( "" ); + leDatabaseName->setText( QLatin1String( "" ) ); } - else if ( cboxDatabaseType->currentText() == "SQLITE" || cboxDatabaseType->currentText() == "MSAccess" ) + else if ( cboxDatabaseType->currentText() == QLatin1String( "SQLITE" ) || cboxDatabaseType->currentText() == QLatin1String( "MSAccess" ) ) { lblDatabaseHost->setEnabled( false ); - leDatabaseHost->setText( "" ); + leDatabaseHost->setText( QLatin1String( "" ) ); leDatabaseHost->setEnabled( false ); lblDatabasePort->setEnabled( false ); - leDatabasePort->setText( "" ); + leDatabasePort->setText( QLatin1String( "" ) ); leDatabasePort->setEnabled( false ); pbtnOpenFile->setEnabled( true ); lblDatabaseUsername->setEnabled( false ); - leDatabaseUsername->setText( "" ); + leDatabaseUsername->setText( QLatin1String( "" ) ); leDatabaseUsername->setEnabled( false ); lblDatabasePassword->setEnabled( false ); - leDatabasePassword->setText( "" ); + leDatabasePassword->setText( QLatin1String( "" ) ); leDatabasePassword->setEnabled( false ); - leDatabaseName->setText( "" ); + leDatabaseName->setText( QLatin1String( "" ) ); } else { lblDatabaseHost->setEnabled( true ); leDatabaseHost->setEnabled( true ); lblDatabasePort->setEnabled( false ); - leDatabasePort->setText( "" ); + leDatabasePort->setText( QLatin1String( "" ) ); leDatabasePort->setEnabled( false ); pbtnOpenFile->setEnabled( false ); lblDatabaseUsername->setEnabled( true ); leDatabaseUsername->setEnabled( true ); lblDatabasePassword->setEnabled( true ); leDatabasePassword->setEnabled( true ); - leDatabaseName->setText( "" ); + leDatabaseName->setText( QLatin1String( "" ) ); } } @@ -232,7 +232,7 @@ void eVisDatabaseConnectionGui::on_pbtnConnect_clicked() errors = true; } - if ( !errors && ( cboxDatabaseType->currentText() == "MYSQL" || cboxDatabaseType->currentText() == "PostGreSQL" ) ) + if ( !errors && ( cboxDatabaseType->currentText() == QLatin1String( "MYSQL" ) || cboxDatabaseType->currentText() == QLatin1String( "PostGreSQL" ) ) ) { if ( leDatabaseHost->text().isEmpty() ) { @@ -251,19 +251,19 @@ void eVisDatabaseConnectionGui::on_pbtnConnect_clicked() if ( !errors ) { eVisDatabaseConnection::DATABASE_TYPE myDatabaseType; - if ( cboxDatabaseType->currentText() == "MSAccess" ) + if ( cboxDatabaseType->currentText() == QLatin1String( "MSAccess" ) ) { myDatabaseType = eVisDatabaseConnection::MSACCESS; } - else if ( cboxDatabaseType->currentText() == "MYSQL" ) + else if ( cboxDatabaseType->currentText() == QLatin1String( "MYSQL" ) ) { myDatabaseType = eVisDatabaseConnection::QMYSQL; } - else if ( cboxDatabaseType->currentText() == "ODBC" ) + else if ( cboxDatabaseType->currentText() == QLatin1String( "ODBC" ) ) { myDatabaseType = eVisDatabaseConnection::QODBC; } - else if ( cboxDatabaseType->currentText() == "PostGreSQL" ) + else if ( cboxDatabaseType->currentText() == QLatin1String( "PostGreSQL" ) ) { myDatabaseType = eVisDatabaseConnection::QPSQL; } @@ -313,8 +313,8 @@ void eVisDatabaseConnectionGui::on_pbtnLoadPredefinedQueries_clicked() //There probably needs to be some more error checking, but works for now. //Select the XML file to parse - QString myFilename = QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), "XML ( *.xml )" ); - if ( myFilename != "" ) + QString myFilename = QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), QStringLiteral( "XML ( *.xml )" ) ); + if ( myFilename != QLatin1String( "" ) ) { //Display the name of the file being parsed lblPredefinedQueryFilename->setText( myFilename ); @@ -342,7 +342,7 @@ void eVisDatabaseConnectionGui::on_pbtnLoadPredefinedQueries_clicked() QDomNode myNode = myXmlDoc.documentElement().firstChild(); while ( !myNode.isNull() ) { - if ( myNode.toElement().tagName() == "query" ) + if ( myNode.toElement().tagName() == QLatin1String( "query" ) ) { bool insert = false; eVisQueryDefinition myQueryDefinition; @@ -350,50 +350,50 @@ void eVisDatabaseConnectionGui::on_pbtnLoadPredefinedQueries_clicked() while ( !myChildNodes.isNull() ) { QDomNode myDataNode = myChildNodes.toElement().firstChild(); - QString myDataNodeContent = ""; + QString myDataNodeContent = QLatin1String( "" ); if ( !myDataNode.isNull() ) { myDataNodeContent = myDataNode.toText().data(); } - if ( myChildNodes.toElement().tagName() == "shortdescription" ) + if ( myChildNodes.toElement().tagName() == QLatin1String( "shortdescription" ) ) { - if ( myDataNodeContent != "" ) + if ( myDataNodeContent != QLatin1String( "" ) ) { myQueryDefinition.setShortDescription( myDataNodeContent ); myQueryCount++; insert = true; } } - else if ( myChildNodes.toElement().tagName() == "description" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "description" ) ) { myQueryDefinition.setDescription( myDataNodeContent ); } - else if ( myChildNodes.toElement().tagName() == "databasetype" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "databasetype" ) ) { myQueryDefinition.setDatabaseType( myDataNodeContent ); } - else if ( myChildNodes.toElement().tagName() == "databasehost" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "databasehost" ) ) { myQueryDefinition.setDatabaseHost( myDataNodeContent ); } - else if ( myChildNodes.toElement().tagName() == "databaseport" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "databaseport" ) ) { myQueryDefinition.setDatabasePort( myDataNodeContent.toInt() ); } - else if ( myChildNodes.toElement().tagName() == "databasename" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "databasename" ) ) { myQueryDefinition.setDatabaseName( myDataNodeContent ); } - else if ( myChildNodes.toElement().tagName() == "databaseusername" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "databaseusername" ) ) { myQueryDefinition.setDatabaseUsername( myDataNodeContent ); } - else if ( myChildNodes.toElement().tagName() == "databasepassword" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "databasepassword" ) ) { myQueryDefinition.setDatabasePassword( myDataNodeContent ); } - else if ( myChildNodes.toElement().tagName() == "sqlstatement" ) + else if ( myChildNodes.toElement().tagName() == QLatin1String( "sqlstatement" ) ) { myQueryDefinition.setSqlStatement( myDataNodeContent ); } @@ -439,7 +439,7 @@ void eVisDatabaseConnectionGui::on_cboxPredefinedQueryList_currentIndexChanged( teditQueryDescription->setText( myQueryDefinition.description() ); cboxDatabaseType->setCurrentIndex( cboxDatabaseType->findText( myQueryDefinition.databaseType() ) ); leDatabaseHost->setText( myQueryDefinition.databaseHost() ); - leDatabasePort->setText( QString( "%1" ).arg( myQueryDefinition.databasePort() ) ); + leDatabasePort->setText( QStringLiteral( "%1" ).arg( myQueryDefinition.databasePort() ) ); leDatabaseName->setText( myQueryDefinition.databaseName() ); leDatabaseUsername->setText( myQueryDefinition.databaseUsername() ); leDatabasePassword->setText( myQueryDefinition.databasePassword() ); @@ -452,10 +452,10 @@ void eVisDatabaseConnectionGui::on_cboxPredefinedQueryList_currentIndexChanged( */ void eVisDatabaseConnectionGui::on_pbtnOpenFile_clicked() { - if ( cboxDatabaseType->currentText() == "MSAccess" ) - leDatabaseName->setText( QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), "MSAccess ( *.mdb )" ) ); + if ( cboxDatabaseType->currentText() == QLatin1String( "MSAccess" ) ) + leDatabaseName->setText( QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), QStringLiteral( "MSAccess ( *.mdb )" ) ) ); else - leDatabaseName->setText( QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), "Sqlite ( *.db )" ) ); + leDatabaseName->setText( QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), QStringLiteral( "Sqlite ( *.db )" ) ) ); } /** diff --git a/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp b/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp index ef1ed1f6322c..a4b50582d051 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp +++ b/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp @@ -88,7 +88,7 @@ void eVisDatabaseLayerFieldSelectionGui::on_buttonBox_accepted() close(); //reset the layer name line edit - leLayerName->setText( "" ); + leLayerName->setText( QLatin1String( "" ) ); } /** @@ -97,5 +97,5 @@ void eVisDatabaseLayerFieldSelectionGui::on_buttonBox_accepted() void eVisDatabaseLayerFieldSelectionGui::on_buttonBox_rejected() { close(); - leLayerName->setText( "" ); + leLayerName->setText( QLatin1String( "" ) ); } diff --git a/src/plugins/evis/databaseconnection/evisquerydefinition.cpp b/src/plugins/evis/databaseconnection/evisquerydefinition.cpp index fd6ad0f997ea..500c16f41ea2 100644 --- a/src/plugins/evis/databaseconnection/evisquerydefinition.cpp +++ b/src/plugins/evis/databaseconnection/evisquerydefinition.cpp @@ -31,13 +31,13 @@ */ eVisQueryDefinition::eVisQueryDefinition() { - mDatabaseType = ""; - mDatabaseHost = ""; + mDatabaseType = QLatin1String( "" ); + mDatabaseHost = QLatin1String( "" ); mDatabasePort = -1; - mDatabaseName = ""; - mDatabaseUsername = ""; - mDatabasePassword = ""; - mSqlStatement = ""; + mDatabaseName = QLatin1String( "" ); + mDatabaseUsername = QLatin1String( "" ); + mDatabasePassword = QLatin1String( "" ); + mSqlStatement = QLatin1String( "" ); mAutoConnect = false; } diff --git a/src/plugins/evis/databaseconnection/evisquerydefinition.h b/src/plugins/evis/databaseconnection/evisquerydefinition.h index 6e60a83b0f55..6b13cd1f5a7e 100644 --- a/src/plugins/evis/databaseconnection/evisquerydefinition.h +++ b/src/plugins/evis/databaseconnection/evisquerydefinition.h @@ -105,7 +105,7 @@ class eVisQueryDefinition /** \brief Mutator for auto connection flag */ void setAutoConnect( const QString& autoconnect ) { - if ( autoconnect.startsWith( "true", Qt::CaseInsensitive ) ) + if ( autoconnect.startsWith( QLatin1String( "true" ), Qt::CaseInsensitive ) ) { mAutoConnect = true; } diff --git a/src/plugins/evis/eventbrowser/evisconfiguration.cpp b/src/plugins/evis/eventbrowser/evisconfiguration.cpp index 4790821392c6..e3c99fc07d07 100644 --- a/src/plugins/evis/eventbrowser/evisconfiguration.cpp +++ b/src/plugins/evis/eventbrowser/evisconfiguration.cpp @@ -33,21 +33,21 @@ eVisConfiguration::eVisConfiguration() { QSettings myQSettings; - setApplyPathRulesToDocs( myQSettings.value( "/eVis/applypathrulestodocs", false ).toBool() ); + setApplyPathRulesToDocs( myQSettings.value( QStringLiteral( "/eVis/applypathrulestodocs" ), false ).toBool() ); - setEventImagePathField( myQSettings.value( "/eVis/eventimagepathfield", "" ).toString() ); - setEventImagePathRelative( myQSettings.value( "/eVis/eventimagepathrelative", false ).toBool() ); + setEventImagePathField( myQSettings.value( QStringLiteral( "/eVis/eventimagepathfield" ), "" ).toString() ); + setEventImagePathRelative( myQSettings.value( QStringLiteral( "/eVis/eventimagepathrelative" ), false ).toBool() ); - setDisplayCompassBearing( myQSettings.value( "/eVis/displaycompassbearing", false ).toBool() ); - setCompassBearingField( myQSettings.value( "/eVis/compassbearingfield", "" ).toString() ); + setDisplayCompassBearing( myQSettings.value( QStringLiteral( "/eVis/displaycompassbearing" ), false ).toBool() ); + setCompassBearingField( myQSettings.value( QStringLiteral( "/eVis/compassbearingfield" ), "" ).toString() ); - setManualCompassOffset( myQSettings.value( "/eVis/manualcompassoffset", false ).toBool() ); - setCompassOffset( myQSettings.value( "/eVis/compassoffset", "0.0" ).toDouble() ); - setAttributeCompassOffset( myQSettings.value( "/eVis/attributecompassoffset", false ).toBool() ); - setCompassOffsetField( myQSettings.value( "/eVis/compassoffsetfield", "" ).toString() ); + setManualCompassOffset( myQSettings.value( QStringLiteral( "/eVis/manualcompassoffset" ), false ).toBool() ); + setCompassOffset( myQSettings.value( QStringLiteral( "/eVis/compassoffset" ), "0.0" ).toDouble() ); + setAttributeCompassOffset( myQSettings.value( QStringLiteral( "/eVis/attributecompassoffset" ), false ).toBool() ); + setCompassOffsetField( myQSettings.value( QStringLiteral( "/eVis/compassoffsetfield" ), "" ).toString() ); - setBasePath( myQSettings.value( "/eVis/basepath", QDir::homePath() ).toString() ); - mUseOnlyFilename = myQSettings.value( "/eVis/useonlyfilename", false ).toBool(); + setBasePath( myQSettings.value( QStringLiteral( "/eVis/basepath" ), QDir::homePath() ).toString() ); + mUseOnlyFilename = myQSettings.value( QStringLiteral( "/eVis/useonlyfilename" ), false ).toBool(); } QString eVisConfiguration::basePath() diff --git a/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp b/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp index 5b0e9f19cc0b..3c2464515b07 100644 --- a/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp +++ b/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.cpp @@ -56,7 +56,7 @@ eVisGenericEventBrowserGui::eVisGenericEventBrowserGui( QWidget* parent, QgisInt setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/eVis/browser-geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/eVis/browser-geometry" ) ).toByteArray() ); mCurrentFeatureIndex = 0; mInterface = interface; @@ -114,7 +114,7 @@ eVisGenericEventBrowserGui::eVisGenericEventBrowserGui( QWidget* parent, QgsMapC eVisGenericEventBrowserGui::~eVisGenericEventBrowserGui() { QSettings settings; - settings.setValue( "/eVis/browser-geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/eVis/browser-geometry" ), saveGeometry() ); //Clean up, disconnect the highlighting routine and refesh the canvase to clear highlighting symbol if ( mCanvas ) @@ -141,8 +141,8 @@ bool eVisGenericEventBrowserGui::initBrowser() connect( treeEventData, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ), this, SLOT( launchExternalApplication( QTreeWidgetItem *, int ) ) ); - mHighlightSymbol.load( ":/evis/eVisHighlightSymbol.png" ); - mPointerSymbol.load( ":/evis/eVisPointerSymbol.png" ); + mHighlightSymbol.load( QStringLiteral( ":/evis/eVisHighlightSymbol.png" ) ); + mPointerSymbol.load( QStringLiteral( ":/evis/eVisPointerSymbol.png" ) ); mCompassOffset = 0.0; //Flag to let us know if the browser fully loaded @@ -320,15 +320,15 @@ bool eVisGenericEventBrowserGui::initBrowser() //Load file associations into Configure External Applications tab gui items QSettings myQSettings; - myQSettings.beginWriteArray( "/eVis/filetypeassociations" ); + myQSettings.beginWriteArray( QStringLiteral( "/eVis/filetypeassociations" ) ); int myTotalAssociations = myQSettings.childGroups().count(); int myIterator = 0; while ( myIterator < myTotalAssociations ) { myQSettings.setArrayIndex( myIterator ); tableFileTypeAssociations->insertRow( tableFileTypeAssociations->rowCount() ); - tableFileTypeAssociations->setItem( myIterator, 0, new QTableWidgetItem( myQSettings.value( "extension", "" ).toString() ) ); - tableFileTypeAssociations->setItem( myIterator, 1, new QTableWidgetItem( myQSettings.value( "application", "" ).toString() ) ); + tableFileTypeAssociations->setItem( myIterator, 0, new QTableWidgetItem( myQSettings.value( QStringLiteral( "extension" ), "" ).toString() ) ); + tableFileTypeAssociations->setItem( myIterator, 1, new QTableWidgetItem( myQSettings.value( QStringLiteral( "application" ), "" ).toString() ) ); myIterator++; } myQSettings.endArray(); @@ -428,41 +428,41 @@ void eVisGenericEventBrowserGui::accept() if ( chkboxSaveEventImagePathData->isChecked() ) { - myQSettings.setValue( "/eVis/eventimagepathfield", cboxEventImagePathField->currentText() ); - myQSettings.setValue( "/eVis/eventimagepathrelative", chkboxEventImagePathRelative->isChecked() ); + myQSettings.setValue( QStringLiteral( "/eVis/eventimagepathfield" ), cboxEventImagePathField->currentText() ); + myQSettings.setValue( QStringLiteral( "/eVis/eventimagepathrelative" ), chkboxEventImagePathRelative->isChecked() ); } if ( chkboxSaveCompassBearingData->isChecked() ) { - myQSettings.setValue( "/eVis/compassbearingfield", cboxCompassBearingField->currentText() ); - myQSettings.setValue( "/eVis/displaycompassbearing", chkboxDisplayCompassBearing->isChecked() ); + myQSettings.setValue( QStringLiteral( "/eVis/compassbearingfield" ), cboxCompassBearingField->currentText() ); + myQSettings.setValue( QStringLiteral( "/eVis/displaycompassbearing" ), chkboxDisplayCompassBearing->isChecked() ); } if ( chkboxSaveCompassOffsetData->isChecked() ) { - myQSettings.setValue( "/eVis/manualcompassoffset", rbtnManualCompassOffset->isChecked() ); - myQSettings.setValue( "/eVis/compassoffset", dsboxCompassOffset->value() ); - myQSettings.setValue( "/eVis/attributecompassoffset", rbtnAttributeCompassOffset->isChecked() ); - myQSettings.setValue( "/eVis/compassoffsetfield", cboxCompassOffsetField->currentText() ); + myQSettings.setValue( QStringLiteral( "/eVis/manualcompassoffset" ), rbtnManualCompassOffset->isChecked() ); + myQSettings.setValue( QStringLiteral( "/eVis/compassoffset" ), dsboxCompassOffset->value() ); + myQSettings.setValue( QStringLiteral( "/eVis/attributecompassoffset" ), rbtnAttributeCompassOffset->isChecked() ); + myQSettings.setValue( QStringLiteral( "/eVis/compassoffsetfield" ), cboxCompassOffsetField->currentText() ); } if ( chkboxSaveBasePathData->isChecked() ) { - myQSettings.setValue( "/eVis/basepath", leBasePath->text() ); + myQSettings.setValue( QStringLiteral( "/eVis/basepath" ), leBasePath->text() ); } if ( chkboxSaveUseOnlyFilenameData->isChecked() ) { - myQSettings.setValue( "/eVis/useonlyfilename", chkboxUseOnlyFilename->isChecked() ); + myQSettings.setValue( QStringLiteral( "/eVis/useonlyfilename" ), chkboxUseOnlyFilename->isChecked() ); } if ( chkboxSaveApplyPathRulesToDocs->isChecked() ) { - myQSettings.setValue( "/eVis/applypathrulestodocs", chkboxApplyPathRulesToDocs->isChecked() ); + myQSettings.setValue( QStringLiteral( "/eVis/applypathrulestodocs" ), chkboxApplyPathRulesToDocs->isChecked() ); } - myQSettings.remove( "/eVis/filetypeassociations" ); - myQSettings.beginWriteArray( "/eVis/filetypeassociations" ); + myQSettings.remove( QStringLiteral( "/eVis/filetypeassociations" ) ); + myQSettings.beginWriteArray( QStringLiteral( "/eVis/filetypeassociations" ) ); int myIterator = 0; int myIndex = 0; while ( myIterator < tableFileTypeAssociations->rowCount() ) @@ -470,8 +470,8 @@ void eVisGenericEventBrowserGui::accept() myQSettings.setArrayIndex( myIndex ); if ( tableFileTypeAssociations->item( myIterator, 0 ) && tableFileTypeAssociations->item( myIterator, 1 ) ) { - myQSettings.setValue( "extension", tableFileTypeAssociations->item( myIterator, 0 )->text() ); - myQSettings.setValue( "application", tableFileTypeAssociations->item( myIterator, 1 )->text() ); + myQSettings.setValue( QStringLiteral( "extension" ), tableFileTypeAssociations->item( myIterator, 0 )->text() ); + myQSettings.setValue( QStringLiteral( "application" ), tableFileTypeAssociations->item( myIterator, 1 )->text() ); myIndex++; } myIterator++; @@ -522,7 +522,7 @@ void eVisGenericEventBrowserGui::displayImage() //This if statement is a bit of a hack, have to track down where the 0 is comming from on initalization if ( "0" != mEventImagePath && 0 == displayArea->currentIndex() ) { - if ( mEventImagePath.startsWith( "http://", Qt::CaseInsensitive ) ) + if ( mEventImagePath.startsWith( QLatin1String( "http://" ), Qt::CaseInsensitive ) ) { imageDisplayArea->displayUrlImage( mEventImagePath ); } @@ -665,7 +665,7 @@ void eVisGenericEventBrowserGui::restoreDefaultOptions() rbtnManualCompassOffset->setChecked( true ); dsboxCompassOffset->setValue( 0.0 ); - leBasePath->setText( "" ); + leBasePath->setText( QLatin1String( "" ) ); chkboxUseOnlyFilename->setChecked( false ); chkboxSaveEventImagePathData->setChecked( false ); @@ -701,14 +701,14 @@ void eVisGenericEventBrowserGui::setBasePathToDataSource() #ifdef Q_OS_WIN mySourceUri.replace( "\\\\", "\\" ); #else - if ( mySourceUri.startsWith( "http://", Qt::CaseInsensitive ) ) + if ( mySourceUri.startsWith( QLatin1String( "http://" ), Qt::CaseInsensitive ) ) { - mySourceUri.replace( "//", "/" ); - mySourceUri.replace( "http:/", "http://", Qt::CaseInsensitive ); + mySourceUri.replace( QLatin1String( "//" ), QLatin1String( "/" ) ); + mySourceUri.replace( QLatin1String( "http:/" ), QLatin1String( "http://" ), Qt::CaseInsensitive ); } else { - mySourceUri.replace( "//", "/" ); + mySourceUri.replace( QLatin1String( "//" ), QLatin1String( "/" ) ); } #endif @@ -1049,7 +1049,7 @@ void eVisGenericEventBrowserGui::on_pbtnResetApplyPathRulesToDocs_clicked() void eVisGenericEventBrowserGui::on_pbtnResetBasePathData_clicked() { - leBasePath->setText( "" ); + leBasePath->setText( QLatin1String( "" ) ); if ( chkboxEventImagePathRelative->isChecked() ) { setBasePathToDataSource(); diff --git a/src/plugins/evis/evis.cpp b/src/plugins/evis/evis.cpp index 8dbe555b6943..c36b3f5cc9d3 100644 --- a/src/plugins/evis/evis.cpp +++ b/src/plugins/evis/evis.cpp @@ -78,7 +78,7 @@ static const QString sDescription = QObject::tr( "An event visualization tool - static const QString sCategory = QObject::tr( "Database" ); static const QString sPluginVersion = QObject::tr( "Version 1.1.0" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sIcon = ":/evis/eVisEventBrowser.png"; +static const QString sIcon = QStringLiteral( ":/evis/eVisEventBrowser.png" ); @@ -104,11 +104,11 @@ void eVis::initGui() // Create the action for tool mDatabaseConnectionActionPointer = new QAction( QIcon( ":/evis/eVisDatabaseConnection.png" ), tr( "eVis Database Connection" ), this ); - mDatabaseConnectionActionPointer->setObjectName( "mDatabaseConnectionActionPointer" ); + mDatabaseConnectionActionPointer->setObjectName( QStringLiteral( "mDatabaseConnectionActionPointer" ) ); mEventIdToolActionPointer = new QAction( QIcon( ":/evis/eVisEventIdTool.png" ), tr( "eVis Event Id Tool" ), this ); - mEventIdToolActionPointer->setObjectName( "mEventIdToolActionPointer" ); + mEventIdToolActionPointer->setObjectName( QStringLiteral( "mEventIdToolActionPointer" ) ); mEventBrowserActionPointer = new QAction( QIcon( ":/evis/eVisEventBrowser.png" ), tr( "eVis Event Browser" ), this ); - mEventBrowserActionPointer->setObjectName( "mEventBrowserActionPointer" ); + mEventBrowserActionPointer->setObjectName( QStringLiteral( "mEventBrowserActionPointer" ) ); // Set the what's this text mDatabaseConnectionActionPointer->setWhatsThis( tr( "Create layer from a database query" ) ); @@ -126,9 +126,9 @@ void eVis::initGui() mQGisIface->addDatabaseToolBarIcon( mEventIdToolActionPointer ); mQGisIface->addDatabaseToolBarIcon( mEventBrowserActionPointer ); - mQGisIface->addPluginToDatabaseMenu( "&eVis", mDatabaseConnectionActionPointer ); - mQGisIface->addPluginToDatabaseMenu( "&eVis", mEventIdToolActionPointer ); - mQGisIface->addPluginToDatabaseMenu( "&eVis", mEventBrowserActionPointer ); + mQGisIface->addPluginToDatabaseMenu( QStringLiteral( "&eVis" ), mDatabaseConnectionActionPointer ); + mQGisIface->addPluginToDatabaseMenu( QStringLiteral( "&eVis" ), mEventIdToolActionPointer ); + mQGisIface->addPluginToDatabaseMenu( QStringLiteral( "&eVis" ), mEventBrowserActionPointer ); mEventIdToolActionPointer->setCheckable( true ); } @@ -170,15 +170,15 @@ void eVis::launchEventBrowser() void eVis::unload() { // remove the GUI - mQGisIface->removePluginDatabaseMenu( "&eVis", mDatabaseConnectionActionPointer ); + mQGisIface->removePluginDatabaseMenu( QStringLiteral( "&eVis" ), mDatabaseConnectionActionPointer ); mQGisIface->removeDatabaseToolBarIcon( mDatabaseConnectionActionPointer ); delete mDatabaseConnectionActionPointer; - mQGisIface->removePluginDatabaseMenu( "&eVis", mEventIdToolActionPointer ); + mQGisIface->removePluginDatabaseMenu( QStringLiteral( "&eVis" ), mEventIdToolActionPointer ); mQGisIface->removeDatabaseToolBarIcon( mEventIdToolActionPointer ); delete mEventIdToolActionPointer; - mQGisIface->removePluginDatabaseMenu( "&eVis", mEventBrowserActionPointer ); + mQGisIface->removePluginDatabaseMenu( QStringLiteral( "&eVis" ), mEventBrowserActionPointer ); mQGisIface->removeDatabaseToolBarIcon( mEventBrowserActionPointer ); delete mEventBrowserActionPointer; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryanglecheck.h b/src/plugins/geometry_checker/checks/qgsgeometryanglecheck.h index 3625a779a238..2a51c82c4e54 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryanglecheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryanglecheck.h @@ -31,7 +31,7 @@ class QgsGeometryAngleCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Minimal angle" ); } - QString errorName() const override { return "QgsGeometryAngleCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryAngleCheck" ); } private: enum ResolutionMethod { DeleteNode, NoChange }; double mMinAngle; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryareacheck.h b/src/plugins/geometry_checker/checks/qgsgeometryareacheck.h index cfde2fb77d4e..67f010f6c986 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryareacheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryareacheck.h @@ -33,7 +33,7 @@ class QgsGeometryAreaCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Minimal area" ); } - QString errorName() const override { return "QgsGeometryAreaCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryAreaCheck" ); } private: enum ResolutionMethod { MergeLongestEdge, MergeLargestArea, MergeIdenticalAttribute, Delete, NoChange }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrycontainedcheck.h b/src/plugins/geometry_checker/checks/qgsgeometrycontainedcheck.h index 360a1c2f75bb..5449ad1a07b7 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrycontainedcheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrycontainedcheck.h @@ -54,7 +54,7 @@ class QgsGeometryContainedCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Within" ); } - QString errorName() const override { return "QgsGeometryContainedCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryContainedCheck" ); } private: enum ResolutionMethod { Delete, NoChange }; }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrydegeneratepolygoncheck.h b/src/plugins/geometry_checker/checks/qgsgeometrydegeneratepolygoncheck.h index d7594bd420e0..f5290e471d86 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrydegeneratepolygoncheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrydegeneratepolygoncheck.h @@ -29,7 +29,7 @@ class QgsGeometryDegeneratePolygonCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Polygon with less than three nodes" ); } - QString errorName() const override { return "QgsGeometryDegeneratePolygonCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryDegeneratePolygonCheck" ); } private: enum ResolutionMethod { DeleteRing, NoChange }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryduplicatecheck.h b/src/plugins/geometry_checker/checks/qgsgeometryduplicatecheck.h index a8b1f05a64af..bf16e77fba61 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryduplicatecheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryduplicatecheck.h @@ -48,7 +48,7 @@ class QgsGeometryDuplicateCheckError : public QgsGeometryCheckError { str.append( QString::number( id ) ); } - return str.join( ", " ); + return str.join( QStringLiteral( ", " ) ); } }; @@ -63,7 +63,7 @@ class QgsGeometryDuplicateCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Duplicate" ); } - QString errorName() const override { return "QgsGeometryDuplicateCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryDuplicateCheck" ); } private: enum ResolutionMethod { NoChange, RemoveDuplicates }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryduplicatenodescheck.h b/src/plugins/geometry_checker/checks/qgsgeometryduplicatenodescheck.h index 10ef7003a2b6..bb83997c4cd2 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryduplicatenodescheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryduplicatenodescheck.h @@ -29,7 +29,7 @@ class QgsGeometryDuplicateNodesCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Duplicate node" ); } - QString errorName() const override { return "QgsGeometryDuplicateNodesCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryDuplicateNodesCheck" ); } private: enum ResolutionMethod { RemoveDuplicates, NoChange }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrygapcheck.h b/src/plugins/geometry_checker/checks/qgsgeometrygapcheck.h index 50cbb10a6ee8..fd103d35637d 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrygapcheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrygapcheck.h @@ -93,7 +93,7 @@ class QgsGeometryGapCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Gap" ); } - QString errorName() const override { return "QgsGeometryGapCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryGapCheck" ); } private: enum ResolutionMethod { MergeLongestEdge, NoChange }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryholecheck.h b/src/plugins/geometry_checker/checks/qgsgeometryholecheck.h index 45e487394511..e151a586d6c4 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryholecheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryholecheck.h @@ -29,7 +29,7 @@ class QgsGeometryHoleCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Polygon with hole" ); } - QString errorName() const override { return "QgsGeometryHoleCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryHoleCheck" ); } private: enum ResolutionMethod { RemoveHoles, NoChange }; }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrymultipartcheck.h b/src/plugins/geometry_checker/checks/qgsgeometrymultipartcheck.h index cacf9ead1201..8282bb113c07 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrymultipartcheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrymultipartcheck.h @@ -29,7 +29,7 @@ class QgsGeometryMultipartCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Multipart object with only one feature" ); } - QString errorName() const override { return "QgsGeometryMultipartCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryMultipartCheck" ); } private: enum ResolutionMethod { ConvertToSingle, RemoveObject, NoChange }; }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryoverlapcheck.h b/src/plugins/geometry_checker/checks/qgsgeometryoverlapcheck.h index 1d76d1773c7f..018d230c525d 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryoverlapcheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryoverlapcheck.h @@ -66,7 +66,7 @@ class QgsGeometryOverlapCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Overlap" ); } - QString errorName() const override { return "QgsGeometryOverlapCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryOverlapCheck" ); } private: enum ResolutionMethod { Subtract, NoChange }; double mThreshold; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrysegmentlengthcheck.h b/src/plugins/geometry_checker/checks/qgsgeometrysegmentlengthcheck.h index 93bb5d5b5247..392e948fce35 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrysegmentlengthcheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrysegmentlengthcheck.h @@ -31,7 +31,7 @@ class QgsGeometrySegmentLengthCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Minimal segment length" ); } - QString errorName() const override { return "QgsGeometrySegmentLengthCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometrySegmentLengthCheck" ); } private: enum ResolutionMethod { NoChange }; double mMinLength; diff --git a/src/plugins/geometry_checker/checks/qgsgeometryselfintersectioncheck.h b/src/plugins/geometry_checker/checks/qgsgeometryselfintersectioncheck.h index c488c1b325b1..945aab4a25e4 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometryselfintersectioncheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometryselfintersectioncheck.h @@ -56,7 +56,7 @@ class QgsGeometrySelfIntersectionCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Self intersection" ); } - QString errorName() const override { return "QgsGeometrySelfIntersectionCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometrySelfIntersectionCheck" ); } private: enum ResolutionMethod { ToMultiObject, ToSingleObjects, NoChange }; }; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrysliverpolygoncheck.h b/src/plugins/geometry_checker/checks/qgsgeometrysliverpolygoncheck.h index 60e43e2460c4..df75ff4006d6 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrysliverpolygoncheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrysliverpolygoncheck.h @@ -27,7 +27,7 @@ class QgsGeometrySliverPolygonCheck : public QgsGeometryAreaCheck QgsGeometrySliverPolygonCheck( QgsFeaturePool* featurePool, double threshold, double maxArea = 0. ) : QgsGeometryAreaCheck( featurePool, threshold ), mMaxArea( maxArea ) {} QString errorDescription() const override { return tr( "Sliver polygon" ); } - QString errorName() const override { return "QgsGeometrySliverPolygonCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometrySliverPolygonCheck" ); } private: double mMaxArea; diff --git a/src/plugins/geometry_checker/checks/qgsgeometrytypecheck.h b/src/plugins/geometry_checker/checks/qgsgeometrytypecheck.h index 6c62edcecf4e..e7d978b02f02 100644 --- a/src/plugins/geometry_checker/checks/qgsgeometrytypecheck.h +++ b/src/plugins/geometry_checker/checks/qgsgeometrytypecheck.h @@ -36,7 +36,7 @@ class QgsGeometryTypeCheckError : public QgsGeometryCheckError mTypeName == static_cast<QgsGeometryTypeCheckError*>( other )->mTypeName; } - virtual QString description() const override { return QString( "%1 (%2)" ).arg( mCheck->errorDescription(), mTypeName ); } + virtual QString description() const override { return QStringLiteral( "%1 (%2)" ).arg( mCheck->errorDescription(), mTypeName ); } private: QString mTypeName; @@ -55,7 +55,7 @@ class QgsGeometryTypeCheck : public QgsGeometryCheck void fixError( QgsGeometryCheckError* error, int method, int mergeAttributeIndex, Changes& changes ) const override; const QStringList& getResolutionMethods() const override; QString errorDescription() const override { return tr( "Geometry type" ); } - QString errorName() const override { return "QgsGeometryTypeCheck"; } + QString errorName() const override { return QStringLiteral( "QgsGeometryTypeCheck" ); } private: enum ResolutionMethod { Convert, Delete, NoChange }; int mAllowedTypes; diff --git a/src/plugins/geometry_checker/qgsgeometrycheckerplugin.h b/src/plugins/geometry_checker/qgsgeometrycheckerplugin.h index 8551765c536d..807da08ff32d 100644 --- a/src/plugins/geometry_checker/qgsgeometrycheckerplugin.h +++ b/src/plugins/geometry_checker/qgsgeometrycheckerplugin.h @@ -46,6 +46,6 @@ static const QString sDescription = QApplication::translate( "QgsGeometryChecker static const QString sCategory = QApplication::translate( "QgsGeometryCheckerPlugin", "Vector" ); static const QString sPluginVersion = QApplication::translate( "QgsGeometryCheckerPlugin", "Version 0.1" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/geometrychecker/icons/geometrychecker.png"; +static const QString sPluginIcon = QStringLiteral( ":/geometrychecker/icons/geometrychecker.png" ); #endif // QGS_GEOMETRY_CHECKER_PLUGIN_H diff --git a/src/plugins/geometry_checker/qgsgeometrycheckfactory.cpp b/src/plugins/geometry_checker/qgsgeometrycheckfactory.cpp index 57a59597b777..29ef2dd9e4a7 100644 --- a/src/plugins/geometry_checker/qgsgeometrycheckfactory.cpp +++ b/src/plugins/geometry_checker/qgsgeometrycheckfactory.cpp @@ -33,7 +33,7 @@ #include "utils/qgsfeaturepool.h" -QString QgsGeometryCheckFactory::sSettingsGroup = "/geometry_checker/previous_values/"; +QString QgsGeometryCheckFactory::sSettingsGroup = QStringLiteral( "/geometry_checker/previous_values/" ); template<> void QgsGeometryCheckFactoryT<QgsGeometryAngleCheck>::restorePrevious( Ui::QgsGeometryCheckerSetupTab& ui ) const diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckerdialog.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckerdialog.cpp index c7623f8f431d..ada9ec1026b7 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckerdialog.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckerdialog.cpp @@ -30,7 +30,7 @@ QgsGeometryCheckerDialog::QgsGeometryCheckerDialog( QgisInterface *iface, QWidge setWindowTitle( tr( "Check Geometries" ) ); QSettings s; - restoreGeometry( s.value( "/Plugin-GeometryChecker/Window/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/Plugin-GeometryChecker/Window/geometry" ) ).toByteArray() ); mTabWidget = new QTabWidget(); mButtonBox = new QDialogButtonBox( QDialogButtonBox::Close, Qt::Horizontal ); @@ -51,7 +51,7 @@ QgsGeometryCheckerDialog::QgsGeometryCheckerDialog( QgisInterface *iface, QWidge QgsGeometryCheckerDialog::~QgsGeometryCheckerDialog() { QSettings s; - s.setValue( "/Plugin-GeometryChecker/Window/geometry", saveGeometry() ); + s.setValue( QStringLiteral( "/Plugin-GeometryChecker/Window/geometry" ), saveGeometry() ); } void QgsGeometryCheckerDialog::onCheckerStarted( QgsGeometryChecker *checker, QgsFeaturePool *featurePool ) diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckerfixsummarydialog.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckerfixsummarydialog.cpp index bc31db7f4a1e..f01fb7f8c426 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckerfixsummarydialog.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckerfixsummarydialog.cpp @@ -53,7 +53,7 @@ QgsGeometryCheckerFixSummaryDialog::QgsGeometryCheckerFixSummaryDialog( QgisInte setupTable( ui.tableWidgetNotFixed ); setupTable( ui.tableWidgetObsoleteErrors ); - ui.plainTextEditMessages->setPlainText( messages.join( "\n" ) ); + ui.plainTextEditMessages->setPlainText( messages.join( QStringLiteral( "\n" ) ) ); ui.groupBoxFixedErrors->setVisible( !stats.fixedErrors.isEmpty() ); ui.groupBoxNewErrors->setVisible( !stats.newErrors.isEmpty() ); @@ -65,7 +65,7 @@ QgsGeometryCheckerFixSummaryDialog::QgsGeometryCheckerFixSummaryDialog( QgisInte void QgsGeometryCheckerFixSummaryDialog::addError( QTableWidget* table, QgsGeometryCheckError* error ) { int prec = 7 - std::floor( qMax( 0., std::log10( qMax( error->location().x(), error->location().y() ) ) ) ); - QString posStr = QString( "%1, %2" ).arg( error->location().x(), 0, 'f', prec ).arg( error->location().y(), 0, 'f', prec ); + QString posStr = QStringLiteral( "%1, %2" ).arg( error->location().x(), 0, 'f', prec ).arg( error->location().y(), 0, 'f', prec ); double layerToMap = mIface->mapCanvas()->mapSettings().layerToMapUnits( mLayer ); QVariant value; if ( error->valueType() == QgsGeometryCheckError::ValueLength ) diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp index 8b6f22568db7..c1b1b3ad6613 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp @@ -35,7 +35,7 @@ #include "qgsvectordataprovider.h" #include "qgsvectorfilewriter.h" -QString QgsGeometryCheckerResultTab::sSettingsGroup = "/geometry_checker/default_fix_methods/"; +QString QgsGeometryCheckerResultTab::sSettingsGroup = QStringLiteral( "/geometry_checker/default_fix_methods/" ); QgsGeometryCheckerResultTab::QgsGeometryCheckerResultTab( QgisInterface* iface, QgsGeometryChecker* checker, QgsFeaturePool *featurePool, QTabWidget* tabWidget, QWidget* parent ) : QWidget( parent ) @@ -98,7 +98,7 @@ void QgsGeometryCheckerResultTab::finalize() QDialog dialog; dialog.setLayout( new QVBoxLayout() ); dialog.layout()->addWidget( new QLabel( tr( "The following checks reported errors:" ) ) ); - dialog.layout()->addWidget( new QPlainTextEdit( mChecker->getMessages().join( "\n" ) ) ); + dialog.layout()->addWidget( new QPlainTextEdit( mChecker->getMessages().join( QStringLiteral( "\n" ) ) ) ); QDialogButtonBox* bbox = new QDialogButtonBox( QDialogButtonBox::Close, Qt::Horizontal ); dialog.layout()->addWidget( bbox ); connect( bbox, SIGNAL( accepted() ), &dialog, SLOT( accept() ) ); @@ -116,7 +116,7 @@ void QgsGeometryCheckerResultTab::addError( QgsGeometryCheckError *error ) int row = ui.tableWidgetErrors->rowCount(); int prec = 7 - std::floor( qMax( 0., std::log10( qMax( error->location().x(), error->location().y() ) ) ) ); - QString posStr = QString( "%1, %2" ).arg( error->location().x(), 0, 'f', prec ).arg( error->location().y(), 0, 'f', prec ); + QString posStr = QStringLiteral( "%1, %2" ).arg( error->location().x(), 0, 'f', prec ).arg( error->location().y(), 0, 'f', prec ); double layerToMap = mIface->mapCanvas()->mapSettings().layerToMapUnits( mFeaturePool->getLayer() ); QVariant value; if ( error->valueType() == QgsGeometryCheckError::ValueLength ) @@ -140,7 +140,7 @@ void QgsGeometryCheckerResultTab::addError( QgsGeometryCheckError *error ) QTableWidgetItem* valueItem = new QTableWidgetItem(); valueItem->setData( Qt::EditRole, value ); ui.tableWidgetErrors->setItem( row, 3, valueItem ); - ui.tableWidgetErrors->setItem( row, 4, new QTableWidgetItem( "" ) ); + ui.tableWidgetErrors->setItem( row, 4, new QTableWidgetItem( QLatin1String( "" ) ) ); ui.tableWidgetErrors->item( row, 0 )->setData( Qt::UserRole, QVariant::fromValue( error ) ); ++mErrorCount; ui.labelErrorCount->setText( tr( "Total errors: %1, fixed errors: %2" ).arg( mErrorCount ).arg( mFixedCount ) ); @@ -164,7 +164,7 @@ void QgsGeometryCheckerResultTab::updateError( QgsGeometryCheckError *error, boo int row = mErrorMap.value( error ).row(); int prec = 7 - std::floor( qMax( 0., std::log10( qMax( error->location().x(), error->location().y() ) ) ) ); - QString posStr = QString( "%1, %2" ).arg( error->location().x(), 0, 'f', prec ).arg( error->location().y(), 0, 'f', prec ); + QString posStr = QStringLiteral( "%1, %2" ).arg( error->location().x(), 0, 'f', prec ).arg( error->location().y(), 0, 'f', prec ); double layerToMap = mIface->mapCanvas()->mapSettings().layerToMapUnits( mFeaturePool->getLayer() ); QVariant value; if ( error->valueType() == QgsGeometryCheckError::ValueLength ) @@ -237,10 +237,10 @@ void QgsGeometryCheckerResultTab::exportErrors() bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString& file ) { QList< QPair<QString, QString> > attributes; - attributes.append( qMakePair( QString( "FeatureID" ), QString( "String;10;" ) ) ); - attributes.append( qMakePair( QString( "ErrorDesc" ), QString( "String;80;" ) ) ); + attributes.append( qMakePair( QStringLiteral( "FeatureID" ), QStringLiteral( "String;10;" ) ) ); + attributes.append( qMakePair( QStringLiteral( "ErrorDesc" ), QStringLiteral( "String;80;" ) ) ); - QLibrary ogrLib( QgsProviderRegistry::instance()->library( "ogr" ) ); + QLibrary ogrLib( QgsProviderRegistry::instance()->library( QStringLiteral( "ogr" ) ) ); if ( !ogrLib.load() ) { return false; @@ -251,19 +251,19 @@ bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString& file ) { return false; } - if ( !createEmptyDataSource( file, "ESRI Shapefile", mFeaturePool->getLayer()->dataProvider()->encoding(), QgsWkbTypes::Point, attributes, mFeaturePool->getLayer()->crs() ) ) + if ( !createEmptyDataSource( file, QStringLiteral( "ESRI Shapefile" ), mFeaturePool->getLayer()->dataProvider()->encoding(), QgsWkbTypes::Point, attributes, mFeaturePool->getLayer()->crs() ) ) { return false; } - QgsVectorLayer* layer = new QgsVectorLayer( file, QFileInfo( file ).baseName(), "ogr" ); + QgsVectorLayer* layer = new QgsVectorLayer( file, QFileInfo( file ).baseName(), QStringLiteral( "ogr" ) ); if ( !layer->isValid() ) { delete layer; return false; } - int fieldFeatureId = layer->fields().lookupField( "FeatureID" ); - int fieldErrDesc = layer->fields().lookupField( "ErrorDesc" ); + int fieldFeatureId = layer->fields().lookupField( QStringLiteral( "FeatureID" ) ); + int fieldErrDesc = layer->fields().lookupField( QStringLiteral( "ErrorDesc" ) ); for ( int row = 0, nRows = ui.tableWidgetErrors->rowCount(); row < nRows; ++row ) { QgsGeometryCheckError* error = ui.tableWidgetErrors->item( row, 0 )->data( Qt::UserRole ).value<QgsGeometryCheckError*>(); @@ -434,14 +434,14 @@ void QgsGeometryCheckerResultTab::openAttributeTable() QStringList expr; Q_FOREACH ( int id, ids ) { - expr.append( QString( "$id = %1 " ).arg( id ) ); + expr.append( QStringLiteral( "$id = %1 " ).arg( id ) ); } if ( mAttribTableDialog ) { disconnect( mAttribTableDialog, SIGNAL( destroyed() ), this, SLOT( clearAttribTableDialog() ) ); mAttribTableDialog->close(); } - mAttribTableDialog = mIface->showAttributeTable( mFeaturePool->getLayer(), expr.join( " or " ) ); + mAttribTableDialog = mIface->showAttributeTable( mFeaturePool->getLayer(), expr.join( QStringLiteral( " or " ) ) ); connect( mAttribTableDialog, SIGNAL( destroyed() ), this, SLOT( clearAttribTableDialog() ) ); } diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp index f45d74f4ac30..fbcab8b1a2c0 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp @@ -130,12 +130,12 @@ void QgsGeometryCheckerSetupTab::validateInput() void QgsGeometryCheckerSetupTab::selectOutputFile() { - QString filterString = QgsVectorFileWriter::filterForDriver( "ESRI Shapefile" ); + QString filterString = QgsVectorFileWriter::filterForDriver( QStringLiteral( "ESRI Shapefile" ) ); QMap<QString, QString> filterFormatMap = QgsVectorFileWriter::supportedFiltersAndFormats(); Q_FOREACH ( const QString& filter, filterFormatMap.keys() ) { QString driverName = filterFormatMap.value( filter ); - if ( driverName != "ESRI Shapefile" ) // Default entry, first in list (see above) + if ( driverName != QLatin1String( "ESRI Shapefile" ) ) // Default entry, first in list (see above) { filterString += ";;" + filter; } @@ -158,9 +158,9 @@ void QgsGeometryCheckerSetupTab::selectOutputFile() QgsVectorFileWriter::MetaData mdata; if ( QgsVectorFileWriter::driverMetadata( mOutputDriverName, mdata ) ) { - if ( !filename.endsWith( QString( ".%1" ).arg( mdata.ext ), Qt::CaseInsensitive ) ) + if ( !filename.endsWith( QStringLiteral( ".%1" ).arg( mdata.ext ), Qt::CaseInsensitive ) ) { - filename += QString( ".%1" ).arg( mdata.ext ); + filename += QStringLiteral( ".%1" ).arg( mdata.ext ); } } ui.lineEditOutput->setText( filename ); @@ -226,7 +226,7 @@ void QgsGeometryCheckerSetupTab::runChecks() unsetCursor(); return; } - QgsVectorLayer* newlayer = new QgsVectorLayer( filename, QFileInfo( filename ).completeBaseName(), "ogr" ); + QgsVectorLayer* newlayer = new QgsVectorLayer( filename, QFileInfo( filename ).completeBaseName(), QStringLiteral( "ogr" ) ); if ( selectedOnly ) { @@ -260,12 +260,12 @@ void QgsGeometryCheckerSetupTab::runChecks() { QString outputFileName = ui.lineEditOutput->text(); QFile( outputFileName ).remove(); - if ( mOutputDriverName == "ESRI Shapefile" ) + if ( mOutputDriverName == QLatin1String( "ESRI Shapefile" ) ) { - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "dbf" ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "prj" ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "qpj" ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "shx" ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "dbf" ) ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "prj" ) ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "qpj" ) ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "shx" ) ) ).remove(); } } return; diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckfixdialog.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckfixdialog.cpp index aaa20a632c5d..6f53646cd637 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckfixdialog.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckfixdialog.cpp @@ -87,7 +87,7 @@ void QgsGeometryCheckerFixDialog::setupNextError() mFixBtn->setVisible( true ); mFixBtn->setFocus(); mSkipBtn->setVisible( true ); - mStatusLabel->setText( "" ); + mStatusLabel->setText( QLatin1String( "" ) ); mResolutionsBox->setEnabled( true ); QgsGeometryCheckError* error = mErrors.at( 0 ); diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp b/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp index e6f7e2b6d9cd..f9a364e21e1d 100644 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp +++ b/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp @@ -144,12 +144,12 @@ void QgsGeometrySnapperDialog::validateInput() void QgsGeometrySnapperDialog::selectOutputFile() { - QString filterString = QgsVectorFileWriter::filterForDriver( "ESRI Shapefile" ); + QString filterString = QgsVectorFileWriter::filterForDriver( QStringLiteral( "ESRI Shapefile" ) ); QMap<QString, QString> filterFormatMap = QgsVectorFileWriter::supportedFiltersAndFormats(); Q_FOREACH ( const QString& filter, filterFormatMap.keys() ) { QString driverName = filterFormatMap.value( filter ); - if ( driverName != "ESRI Shapefile" ) // Default entry, first in list (see above) + if ( driverName != QLatin1String( "ESRI Shapefile" ) ) // Default entry, first in list (see above) { filterString += ";;" + filter; } @@ -172,9 +172,9 @@ void QgsGeometrySnapperDialog::selectOutputFile() QgsVectorFileWriter::MetaData mdata; if ( QgsVectorFileWriter::driverMetadata( mOutputDriverName, mdata ) ) { - if ( !filename.endsWith( QString( ".%1" ).arg( mdata.ext ), Qt::CaseInsensitive ) ) + if ( !filename.endsWith( QStringLiteral( ".%1" ).arg( mdata.ext ), Qt::CaseInsensitive ) ) { - filename += QString( ".%1" ).arg( mdata.ext ); + filename += QStringLiteral( ".%1" ).arg( mdata.ext ); } } lineEditOutput->setText( filename ); @@ -228,7 +228,7 @@ void QgsGeometrySnapperDialog::run() QMessageBox::critical( this, tr( "Layer Creation Failed" ), tr( "Failed to create the output layer: %1" ).arg( errMsg ) ); return; } - QgsVectorLayer* newlayer = new QgsVectorLayer( filename, QFileInfo( filename ).completeBaseName(), "ogr" ); + QgsVectorLayer* newlayer = new QgsVectorLayer( filename, QFileInfo( filename ).completeBaseName(), QStringLiteral( "ogr" ) ); if ( selectedOnly ) { @@ -261,12 +261,12 @@ void QgsGeometrySnapperDialog::run() { QString outputFileName = lineEditOutput->text(); QFile( outputFileName ).remove(); - if ( mOutputDriverName == "ESRI Shapefile" ) + if ( mOutputDriverName == QLatin1String( "ESRI Shapefile" ) ) { - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "dbf" ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "prj" ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "qpj" ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), "shx" ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "dbf" ) ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "prj" ) ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "qpj" ) ) ).remove(); + QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "shx" ) ) ).remove(); } return; } @@ -313,7 +313,7 @@ void QgsGeometrySnapperDialog::run() /** Show errors **/ if ( !snapper.getErrors().isEmpty() ) { - QMessageBox::warning( this, tr( "Errors occurred" ), tr( "<p>The following errors occurred:</p><ul><li>%1</li></ul>" ).arg( snapper.getErrors().join( "</li><li>" ) ) ); + QMessageBox::warning( this, tr( "Errors occurred" ), tr( "<p>The following errors occurred:</p><ul><li>%1</li></ul>" ).arg( snapper.getErrors().join( QStringLiteral( "</li><li>" ) ) ) ); } hide() ; } diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h b/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h index de1fe9a1f488..611747ee0648 100644 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h +++ b/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h @@ -28,7 +28,7 @@ static const QString sDescription = QApplication::translate( "QgsGeometrySnapper static const QString sCategory = QApplication::translate( "QgsGeometrySnapperPlugin", "Vector" ); static const QString sPluginVersion = QApplication::translate( "QgsGeometrySnapperPlugin", "Version 0.1" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/geometrysnapper/icons/geometrysnapper.png"; +static const QString sPluginIcon = QStringLiteral( ":/geometrysnapper/icons/geometrysnapper.png" ); class QgsGeometrySnapperPlugin : public QObject, public QgisPlugin diff --git a/src/plugins/georeferencer/qgsgcpcanvasitem.cpp b/src/plugins/georeferencer/qgsgcpcanvasitem.cpp index e2a04f56e070..28e46c85b902 100644 --- a/src/plugins/georeferencer/qgsgcpcanvasitem.cpp +++ b/src/plugins/georeferencer/qgsgcpcanvasitem.cpp @@ -61,13 +61,13 @@ void QgsGCPCanvasItem::paint( QPainter* p ) p->drawEllipse( -2, -2, 5, 5 ); QSettings s; - bool showIDs = s.value( "/Plugin-GeoReferencer/Config/ShowId" ).toBool(); - bool showCoords = s.value( "/Plugin-GeoReferencer/Config/ShowCoords" ).toBool(); + bool showIDs = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowId" ) ).toBool(); + bool showCoords = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowCoords" ) ).toBool(); QString msg; if ( showIDs && showCoords ) { - msg = QString( "%1\nX %2\nY %3" ).arg( QString::number( id ), QString::number( worldCoords.x(), 'f' ), QString::number( worldCoords.y(), 'f' ) ); + msg = QStringLiteral( "%1\nX %2\nY %3" ).arg( QString::number( id ), QString::number( worldCoords.x(), 'f' ), QString::number( worldCoords.y(), 'f' ) ); } else if ( showIDs ) { @@ -75,13 +75,13 @@ void QgsGCPCanvasItem::paint( QPainter* p ) } else if ( showCoords ) { - msg = QString( "X %1\nY %2" ).arg( QString::number( worldCoords.x(), 'f' ), QString::number( worldCoords.y(), 'f' ) ); + msg = QStringLiteral( "X %1\nY %2" ).arg( QString::number( worldCoords.x(), 'f' ), QString::number( worldCoords.y(), 'f' ) ); } if ( !msg.isEmpty() ) { p->setBrush( mLabelBrush ); - QFont textFont( "helvetica" ); + QFont textFont( QStringLiteral( "helvetica" ) ); textFont.setPixelSize( fontSizePainterUnits( 12, context ) ); p->setFont( textFont ); QRectF textBounds = p->boundingRect( 3 * context.scaleFactor(), 3 * context.scaleFactor(), 5 * context.scaleFactor(), 5 * context.scaleFactor(), Qt::AlignLeft, msg ); diff --git a/src/plugins/georeferencer/qgsgcplistmodel.cpp b/src/plugins/georeferencer/qgsgcplistmodel.cpp index 29572c121168..6cf1bc639229 100644 --- a/src/plugins/georeferencer/qgsgcplistmodel.cpp +++ b/src/plugins/georeferencer/qgsgcplistmodel.cpp @@ -95,7 +95,7 @@ void QgsGCPListModel::updateModel() } - if ( s.value( "/Plugin-GeoReferencer/Config/ResidualUnits" ) == "mapUnits" && mapUnitsPossible ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ResidualUnits" ) ) == "mapUnits" && mapUnitsPossible ) { unitType = tr( "map units" ); } @@ -183,9 +183,9 @@ void QgsGCPListModel::updateModel() } else { - setItem( i, j++, new QgsStandardItem( "n/a" ) ); - setItem( i, j++, new QgsStandardItem( "n/a" ) ); - setItem( i, j++, new QgsStandardItem( "n/a" ) ); + setItem( i, j++, new QgsStandardItem( QStringLiteral( "n/a" ) ) ); + setItem( i, j++, new QgsStandardItem( QStringLiteral( "n/a" ) ) ); + setItem( i, j++, new QgsStandardItem( QStringLiteral( "n/a" ) ) ); } } } diff --git a/src/plugins/georeferencer/qgsgeorefconfigdialog.cpp b/src/plugins/georeferencer/qgsgeorefconfigdialog.cpp index ab1eb3372aa9..2f4bc95289a5 100644 --- a/src/plugins/georeferencer/qgsgeorefconfigdialog.cpp +++ b/src/plugins/georeferencer/qgsgeorefconfigdialog.cpp @@ -25,7 +25,7 @@ QgsGeorefConfigDialog::QgsGeorefConfigDialog( QWidget *parent ) setupUi( this ); QSettings s; - restoreGeometry( s.value( "/Plugin-GeoReferencer/ConfigWindow/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/Plugin-GeoReferencer/ConfigWindow/geometry" ) ).toByteArray() ); mPaperSizeComboBox->addItem( tr( "A5 (148x210 mm)" ), QSizeF( 148, 210 ) ); mPaperSizeComboBox->addItem( tr( "A4 (210x297 mm)" ), QSizeF( 210, 297 ) ); @@ -59,7 +59,7 @@ QgsGeorefConfigDialog::QgsGeorefConfigDialog( QWidget *parent ) QgsGeorefConfigDialog::~QgsGeorefConfigDialog() { QSettings settings; - settings.setValue( "/Plugin-GeoReferencer/ConfigWindow/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/ConfigWindow/geometry" ), saveGeometry() ); } void QgsGeorefConfigDialog::changeEvent( QEvent *e ) @@ -89,7 +89,7 @@ void QgsGeorefConfigDialog::on_buttonBox_rejected() void QgsGeorefConfigDialog::readSettings() { QSettings s; - if ( s.value( "/Plugin-GeoReferencer/Config/ShowId" ).toBool() ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowId" ) ).toBool() ) { mShowIDsCheckBox->setChecked( true ); } @@ -98,7 +98,7 @@ void QgsGeorefConfigDialog::readSettings() mShowIDsCheckBox->setChecked( false ); } - if ( s.value( "/Plugin-GeoReferencer/Config/ShowCoords" ).toBool() ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowCoords" ) ).toBool() ) { mShowCoordsCheckBox->setChecked( true ); } @@ -107,7 +107,7 @@ void QgsGeorefConfigDialog::readSettings() mShowCoordsCheckBox->setChecked( false ); } - if ( s.value( "/Plugin-GeoReferencer/Config/ShowDocked" ).toBool() ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowDocked" ) ).toBool() ) { mShowDockedCheckBox->setChecked( true ); } @@ -116,7 +116,7 @@ void QgsGeorefConfigDialog::readSettings() mShowDockedCheckBox->setChecked( false ); } - if ( s.value( "/Plugin-GeoReferencer/Config/ResidualUnits" ).toString() == "mapUnits" ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ResidualUnits" ) ).toString() == QLatin1String( "mapUnits" ) ) { mMapUnitsButton->setChecked( true ); } @@ -125,11 +125,11 @@ void QgsGeorefConfigDialog::readSettings() mPixelsButton->setChecked( true ); } - mLeftMarginSpinBox->setValue( s.value( "/Plugin-GeoReferencer/Config/LeftMarginPDF", "2.0" ).toDouble() ); - mRightMarginSpinBox->setValue( s.value( "/Plugin-GeoReferencer/Config/RightMarginPDF", "2.0" ).toDouble() ); + mLeftMarginSpinBox->setValue( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/LeftMarginPDF" ), "2.0" ).toDouble() ); + mRightMarginSpinBox->setValue( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/RightMarginPDF" ), "2.0" ).toDouble() ); - double currentWidth = s.value( "/Plugin-GeoReferencer/Config/WidthPDFMap", "297" ).toDouble(); - double currentHeight = s.value( "/Plugin-GeoReferencer/Config/HeightPDFMap", "420" ).toDouble(); + double currentWidth = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/WidthPDFMap" ), "297" ).toDouble(); + double currentHeight = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/HeightPDFMap" ), "420" ).toDouble(); int paperIndex = 2; //default to A3 for ( int i = 0; i < mPaperSizeComboBox->count(); ++i ) @@ -148,22 +148,22 @@ void QgsGeorefConfigDialog::readSettings() void QgsGeorefConfigDialog::writeSettings() { QSettings s; - s.setValue( "/Plugin-GeoReferencer/Config/ShowId", mShowIDsCheckBox->isChecked() ); - s.setValue( "/Plugin-GeoReferencer/Config/ShowCoords", mShowCoordsCheckBox->isChecked() ); - s.setValue( "/Plugin-GeoReferencer/Config/ShowDocked", mShowDockedCheckBox->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowId" ), mShowIDsCheckBox->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowCoords" ), mShowCoordsCheckBox->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowDocked" ), mShowDockedCheckBox->isChecked() ); if ( mPixelsButton->isChecked() ) { - s.setValue( "/Plugin-GeoReferencer/Config/ResidualUnits", "pixels" ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/ResidualUnits" ), "pixels" ); } else { - s.setValue( "/Plugin-GeoReferencer/Config/ResidualUnits", "mapUnits" ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/ResidualUnits" ), "mapUnits" ); } - s.setValue( "/Plugin-GeoReferencer/Config/LeftMarginPDF", mLeftMarginSpinBox->value() ); - s.setValue( "/Plugin-GeoReferencer/Config/RightMarginPDF", mRightMarginSpinBox->value() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/LeftMarginPDF" ), mLeftMarginSpinBox->value() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/RightMarginPDF" ), mRightMarginSpinBox->value() ); - s.setValue( "/Plugin-GeoReferencer/Config/WidthPDFMap", mPaperSizeComboBox->currentData().toSizeF().width() ); - s.setValue( "/Plugin-GeoReferencer/Config/HeightPDFMap", mPaperSizeComboBox->currentData().toSizeF().height() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/WidthPDFMap" ), mPaperSizeComboBox->currentData().toSizeF().width() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/Config/HeightPDFMap" ), mPaperSizeComboBox->currentData().toSizeF().height() ); } diff --git a/src/plugins/georeferencer/qgsgeorefplugin.cpp b/src/plugins/georeferencer/qgsgeorefplugin.cpp index dfcc72e6b322..292729bc933e 100644 --- a/src/plugins/georeferencer/qgsgeorefplugin.cpp +++ b/src/plugins/georeferencer/qgsgeorefplugin.cpp @@ -64,7 +64,7 @@ static const QString sDescription = QObject::tr( "Georeferencing rasters using G static const QString sCategory = QObject::tr( "Raster" ); static const QString sPluginVersion = QObject::tr( "Version 3.1.9" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/icons/default/mGeorefRun.png"; +static const QString sPluginIcon = QStringLiteral( ":/icons/default/mGeorefRun.png" ); ////////////////////////////////////////////////////////////////////// // @@ -99,12 +99,12 @@ void QgsGeorefPlugin::initGui() // Create the action for tool mActionRunGeoref = new QAction( QIcon(), tr( "&Georeferencer..." ), this ); - mActionRunGeoref->setObjectName( "mActionRunGeoref" ); + mActionRunGeoref->setObjectName( QStringLiteral( "mActionRunGeoref" ) ); // Connect the action to the run connect( mActionRunGeoref, SIGNAL( triggered() ), this, SLOT( run() ) ); - setCurrentTheme( "" ); + setCurrentTheme( QLatin1String( "" ) ); // this is called when the icon theme is changed connect( mQGisIface, SIGNAL( currentThemeChanged( QString ) ), this, SLOT( setCurrentTheme( QString ) ) ); @@ -139,7 +139,7 @@ void QgsGeorefPlugin::unload() void QgsGeorefPlugin::setCurrentTheme( const QString& ) { if ( mActionRunGeoref ) - mActionRunGeoref->setIcon( getThemeIcon( "/mGeorefRun.png" ) ); + mActionRunGeoref->setIcon( getThemeIcon( QStringLiteral( "/mGeorefRun.png" ) ) ); } QIcon QgsGeorefPlugin::getThemeIcon( const QString &theName ) diff --git a/src/plugins/georeferencer/qgsgeorefplugingui.cpp b/src/plugins/georeferencer/qgsgeorefplugingui.cpp index 7a9c55136118..0a0435bd101c 100644 --- a/src/plugins/georeferencer/qgsgeorefplugingui.cpp +++ b/src/plugins/georeferencer/qgsgeorefplugingui.cpp @@ -71,7 +71,7 @@ QgsGeorefDockWidget::QgsGeorefDockWidget( const QString & title, QWidget * parent, Qt::WindowFlags flags ) : QgsDockWidget( title, parent, flags ) { - setObjectName( "GeorefDockWidget" ); // set object name so the position can be saved + setObjectName( QStringLiteral( "GeorefDockWidget" ) ); // set object name so the position can be saved } QgsGeorefPluginGui::QgsGeorefPluginGui( QgisInterface* theQgisInterface, QWidget* parent, Qt::WindowFlags fl ) @@ -91,7 +91,7 @@ QgsGeorefPluginGui::QgsGeorefPluginGui( QgisInterface* theQgisInterface, QWidget setupUi( this ); QSettings s; - restoreGeometry( s.value( "/Plugin-GeoReferencer/Window/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/Plugin-GeoReferencer/Window/geometry" ) ).toByteArray() ); QWidget *centralWidget = this->centralWidget(); mCentralLayout = new QGridLayout( centralWidget ); @@ -121,7 +121,7 @@ QgsGeorefPluginGui::QgsGeorefPluginGui( QgisInterface* theQgisInterface, QWidget connect( mIface, SIGNAL( currentThemeChanged( QString ) ), this, SLOT( updateIconTheme( QString ) ) ); - if ( s.value( "/Plugin-GeoReferencer/Config/ShowDocked" ).toBool() ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowDocked" ) ).toBool() ) { dockThisWindow( true ); } @@ -151,7 +151,7 @@ void QgsGeorefPluginGui::dockThisWindow( bool dock ) QgsGeorefPluginGui::~QgsGeorefPluginGui() { QSettings settings; - settings.setValue( "/Plugin-GeoReferencer/Window/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/Window/geometry" ), saveGeometry() ); clearGCPData(); @@ -179,7 +179,7 @@ void QgsGeorefPluginGui::closeEvent( QCloseEvent *e ) writeSettings(); clearGCPData(); removeOldLayer(); - mRasterFileName = ""; + mRasterFileName = QLatin1String( "" ); e->accept(); return; case QgsGeorefPluginGui::GCPSILENTSAVE: @@ -187,13 +187,13 @@ void QgsGeorefPluginGui::closeEvent( QCloseEvent *e ) saveGCPs(); clearGCPData(); removeOldLayer(); - mRasterFileName = ""; + mRasterFileName = QLatin1String( "" ); return; case QgsGeorefPluginGui::GCPDISCARD: writeSettings(); clearGCPData(); removeOldLayer(); - mRasterFileName = ""; + mRasterFileName = QLatin1String( "" ); e->accept(); return; case QgsGeorefPluginGui::GCPCANCEL: @@ -242,18 +242,18 @@ void QgsGeorefPluginGui::openRaster() } QSettings s; - QString dir = s.value( "/Plugin-GeoReferencer/rasterdirectory" ).toString(); + QString dir = s.value( QStringLiteral( "/Plugin-GeoReferencer/rasterdirectory" ) ).toString(); if ( dir.isEmpty() ) dir = '.'; QString otherFiles = tr( "All other files (*)" ); - QString lastUsedFilter = s.value( "/Plugin-GeoReferencer/lastusedfilter", otherFiles ).toString(); + QString lastUsedFilter = s.value( QStringLiteral( "/Plugin-GeoReferencer/lastusedfilter" ), otherFiles ).toString(); QString filters = QgsProviderRegistry::instance()->fileRasterFilters(); filters.prepend( otherFiles + ";;" ); filters.chop( otherFiles.size() + 2 ); mRasterFileName = QFileDialog::getOpenFileName( this, tr( "Open raster" ), dir, filters, &lastUsedFilter ); - mModifiedRasterFileName = ""; + mModifiedRasterFileName = QLatin1String( "" ); if ( mRasterFileName.isEmpty() ) return; @@ -271,8 +271,8 @@ void QgsGeorefPluginGui::openRaster() } QFileInfo fileInfo( mRasterFileName ); - s.setValue( "/Plugin-GeoReferencer/rasterdirectory", fileInfo.path() ); - s.setValue( "/Plugin-GeoReferencer/lastusedfilter", lastUsedFilter ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/rasterdirectory" ), fileInfo.path() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastusedfilter" ), lastUsedFilter ); mGeorefTransform.selectTransformParametrisation( mTransformParam ); mGeorefTransform.setRasterChangeCoords( mRasterFileName ); @@ -597,7 +597,7 @@ void QgsGeorefPluginGui::showCoordDialog( const QgsPoint &pixelCoords ) void QgsGeorefPluginGui::loadGCPsDialog() { - QString selectedFile = mRasterFileName.isEmpty() ? "" : mRasterFileName + ".points"; + QString selectedFile = mRasterFileName.isEmpty() ? QLatin1String( "" ) : mRasterFileName + ".points"; mGCPpointsFileName = QFileDialog::getOpenFileName( this, tr( "Load GCP points" ), selectedFile, tr( "GCP file" ) + " (*.points)" ); if ( mGCPpointsFileName.isEmpty() ) @@ -621,7 +621,7 @@ void QgsGeorefPluginGui::saveGCPsDialog() return; } - QString selectedFile = mRasterFileName.isEmpty() ? "" : mRasterFileName + ".points"; + QString selectedFile = mRasterFileName.isEmpty() ? QLatin1String( "" ) : mRasterFileName + ".points"; mGCPpointsFileName = QFileDialog::getSaveFileName( this, tr( "Save GCP points" ), selectedFile, tr( "GCP file" ) + " (*.points)" ); @@ -629,8 +629,8 @@ void QgsGeorefPluginGui::saveGCPsDialog() if ( mGCPpointsFileName.isEmpty() ) return; - if ( mGCPpointsFileName.right( 7 ) != ".points" ) - mGCPpointsFileName += ".points"; + if ( mGCPpointsFileName.right( 7 ) != QLatin1String( ".points" ) ) + mGCPpointsFileName += QLatin1String( ".points" ); saveGCPs(); } @@ -657,7 +657,7 @@ void QgsGeorefPluginGui::showGeorefConfigDialog() mIface->mapCanvas()->refresh(); QSettings s; //update dock state - bool dock = s.value( "/Plugin-GeoReferencer/Config/ShowDocked" ).toBool(); + bool dock = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ShowDocked" ) ).toBool(); if ( dock && !mDock ) { dockThisWindow( true ); @@ -796,7 +796,7 @@ void QgsGeorefPluginGui::updateMouseCoordinatePrecision() // function needs to be called every time one of the above happens. // Get the display precision from the project s - bool automatic = QgsProject::instance()->readBoolEntry( "PositionPrecision", "/Automatic" ); + bool automatic = QgsProject::instance()->readBoolEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/Automatic" ) ); int dp = 0; if ( automatic ) @@ -809,7 +809,7 @@ void QgsGeorefPluginGui::updateMouseCoordinatePrecision() dp = static_cast<int>( ceil( -1.0 * log10( mCanvas->mapUnitsPerPixel() ) ) ); } else - dp = QgsProject::instance()->readNumEntry( "PositionPrecision", "/DecimalPlaces" ); + dp = QgsProject::instance()->readNumEntry( QStringLiteral( "PositionPrecision" ), QStringLiteral( "/DecimalPlaces" ) ); // Keep dp sensible if ( dp < 0 ) @@ -847,72 +847,72 @@ void QgsGeorefPluginGui::createActions() // File actions connect( mActionReset, SIGNAL( triggered() ), this, SLOT( reset() ) ); - mActionOpenRaster->setIcon( getThemeIcon( "/mActionAddRasterLayer.svg" ) ); + mActionOpenRaster->setIcon( getThemeIcon( QStringLiteral( "/mActionAddRasterLayer.svg" ) ) ); connect( mActionOpenRaster, SIGNAL( triggered() ), this, SLOT( openRaster() ) ); - mActionStartGeoref->setIcon( getThemeIcon( "/mActionStartGeoref.png" ) ); + mActionStartGeoref->setIcon( getThemeIcon( QStringLiteral( "/mActionStartGeoref.png" ) ) ); connect( mActionStartGeoref, SIGNAL( triggered() ), this, SLOT( doGeoreference() ) ); - mActionGDALScript->setIcon( getThemeIcon( "/mActionGDALScript.png" ) ); + mActionGDALScript->setIcon( getThemeIcon( QStringLiteral( "/mActionGDALScript.png" ) ) ); connect( mActionGDALScript, SIGNAL( triggered() ), this, SLOT( generateGDALScript() ) ); - mActionLoadGCPpoints->setIcon( getThemeIcon( "/mActionLoadGCPpoints.png" ) ); + mActionLoadGCPpoints->setIcon( getThemeIcon( QStringLiteral( "/mActionLoadGCPpoints.png" ) ) ); connect( mActionLoadGCPpoints, SIGNAL( triggered() ), this, SLOT( loadGCPsDialog() ) ); - mActionSaveGCPpoints->setIcon( getThemeIcon( "/mActionSaveGCPpointsAs.png" ) ); + mActionSaveGCPpoints->setIcon( getThemeIcon( QStringLiteral( "/mActionSaveGCPpointsAs.png" ) ) ); connect( mActionSaveGCPpoints, SIGNAL( triggered() ), this, SLOT( saveGCPsDialog() ) ); - mActionTransformSettings->setIcon( getThemeIcon( "/mActionTransformSettings.png" ) ); + mActionTransformSettings->setIcon( getThemeIcon( QStringLiteral( "/mActionTransformSettings.png" ) ) ); connect( mActionTransformSettings, SIGNAL( triggered() ), this, SLOT( getTransformSettings() ) ); // Edit actions - mActionAddPoint->setIcon( getThemeIcon( "/mActionAddGCPPoint.png" ) ); + mActionAddPoint->setIcon( getThemeIcon( QStringLiteral( "/mActionAddGCPPoint.png" ) ) ); connect( mActionAddPoint, SIGNAL( triggered() ), this, SLOT( setAddPointTool() ) ); - mActionDeletePoint->setIcon( getThemeIcon( "/mActionDeleteGCPPoint.png" ) ); + mActionDeletePoint->setIcon( getThemeIcon( QStringLiteral( "/mActionDeleteGCPPoint.png" ) ) ); connect( mActionDeletePoint, SIGNAL( triggered() ), this, SLOT( setDeletePointTool() ) ); - mActionMoveGCPPoint->setIcon( getThemeIcon( "/mActionMoveGCPPoint.png" ) ); + mActionMoveGCPPoint->setIcon( getThemeIcon( QStringLiteral( "/mActionMoveGCPPoint.png" ) ) ); connect( mActionMoveGCPPoint, SIGNAL( triggered() ), this, SLOT( setMovePointTool() ) ); // View actions - mActionPan->setIcon( getThemeIcon( "/mActionPan.svg" ) ); + mActionPan->setIcon( getThemeIcon( QStringLiteral( "/mActionPan.svg" ) ) ); connect( mActionPan, SIGNAL( triggered() ), this, SLOT( setPanTool() ) ); - mActionZoomIn->setIcon( getThemeIcon( "/mActionZoomIn.svg" ) ); + mActionZoomIn->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomIn.svg" ) ) ); connect( mActionZoomIn, SIGNAL( triggered() ), this, SLOT( setZoomInTool() ) ); - mActionZoomOut->setIcon( getThemeIcon( "/mActionZoomOut.svg" ) ); + mActionZoomOut->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomOut.svg" ) ) ); connect( mActionZoomOut, SIGNAL( triggered() ), this, SLOT( setZoomOutTool() ) ); - mActionZoomToLayer->setIcon( getThemeIcon( "/mActionZoomToLayer.svg" ) ); + mActionZoomToLayer->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomToLayer.svg" ) ) ); connect( mActionZoomToLayer, SIGNAL( triggered() ), this, SLOT( zoomToLayerTool() ) ); - mActionZoomLast->setIcon( getThemeIcon( "/mActionZoomLast.svg" ) ); + mActionZoomLast->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomLast.svg" ) ) ); connect( mActionZoomLast, SIGNAL( triggered() ), this, SLOT( zoomToLast() ) ); - mActionZoomNext->setIcon( getThemeIcon( "/mActionZoomNext.svg" ) ); + mActionZoomNext->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomNext.svg" ) ) ); connect( mActionZoomNext, SIGNAL( triggered() ), this, SLOT( zoomToNext() ) ); - mActionLinkGeorefToQGis->setIcon( getThemeIcon( "/mActionLinkGeorefToQGis.png" ) ); + mActionLinkGeorefToQGis->setIcon( getThemeIcon( QStringLiteral( "/mActionLinkGeorefToQGis.png" ) ) ); connect( mActionLinkGeorefToQGis, SIGNAL( triggered( bool ) ), this, SLOT( linkGeorefToQGis( bool ) ) ); - mActionLinkQGisToGeoref->setIcon( getThemeIcon( "/mActionLinkQGisToGeoref.png" ) ); + mActionLinkQGisToGeoref->setIcon( getThemeIcon( QStringLiteral( "/mActionLinkQGisToGeoref.png" ) ) ); connect( mActionLinkQGisToGeoref, SIGNAL( triggered( bool ) ), this, SLOT( linkQGisToGeoref( bool ) ) ); // Settings actions - mActionRasterProperties->setIcon( getThemeIcon( "/mActionRasterProperties.png" ) ); + mActionRasterProperties->setIcon( getThemeIcon( QStringLiteral( "/mActionRasterProperties.png" ) ) ); connect( mActionRasterProperties, SIGNAL( triggered() ), this, SLOT( showRasterPropertiesDialog() ) ); - mActionGeorefConfig->setIcon( getThemeIcon( "/mActionGeorefConfig.png" ) ); + mActionGeorefConfig->setIcon( getThemeIcon( QStringLiteral( "/mActionGeorefConfig.png" ) ) ); connect( mActionGeorefConfig, SIGNAL( triggered() ), this, SLOT( showGeorefConfigDialog() ) ); // Histogram stretch - mActionLocalHistogramStretch->setIcon( getThemeIcon( "/mActionLocalHistogramStretch.svg" ) ); + mActionLocalHistogramStretch->setIcon( getThemeIcon( QStringLiteral( "/mActionLocalHistogramStretch.svg" ) ) ); connect( mActionLocalHistogramStretch, SIGNAL( triggered() ), this, SLOT( localHistogramStretch() ) ); mActionLocalHistogramStretch->setEnabled( false ); - mActionFullHistogramStretch->setIcon( getThemeIcon( "/mActionFullHistogramStretch.svg" ) ); + mActionFullHistogramStretch->setIcon( getThemeIcon( QStringLiteral( "/mActionFullHistogramStretch.svg" ) ) ); connect( mActionFullHistogramStretch, SIGNAL( triggered() ), this, SLOT( fullHistogramStretch() ) ); mActionFullHistogramStretch->setEnabled( false ); @@ -920,7 +920,7 @@ void QgsGeorefPluginGui::createActions() mActionHelp = new QAction( tr( "Help" ), this ); connect( mActionHelp, SIGNAL( triggered() ), this, SLOT( contextHelp() ) ); - mActionQuit->setIcon( getThemeIcon( "/mActionQuit.png" ) ); + mActionQuit->setIcon( getThemeIcon( QStringLiteral( "/mActionQuit.png" ) ) ); mActionQuit->setShortcuts( QList<QKeySequence>() << QKeySequence( Qt::CTRL + Qt::Key_Q ) << QKeySequence( Qt::Key_Escape ) ); connect( mActionQuit, SIGNAL( triggered() ), this, SLOT( close() ) ); @@ -948,7 +948,7 @@ void QgsGeorefPluginGui::createMapCanvas() { // set up the canvas mCanvas = new QgsMapCanvas( this->centralWidget() ); - mCanvas->setObjectName( "georefCanvas" ); + mCanvas->setObjectName( QStringLiteral( "georefCanvas" ) ); mCanvas->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); mCanvas->setCanvasColor( Qt::white ); mCanvas->setMinimumWidth( 400 ); @@ -994,7 +994,7 @@ void QgsGeorefPluginGui::createMapCanvas() this, SLOT( releasePoint( const QPoint & ) ) ); QSettings s; - double zoomFactor = s.value( "/qgis/zoom_factor", 2 ).toDouble(); + double zoomFactor = s.value( QStringLiteral( "/qgis/zoom_factor" ), 2 ).toDouble(); mCanvas->setWheelFactor( zoomFactor ); mExtentsChangedRecursionGuard = false; @@ -1015,18 +1015,18 @@ void QgsGeorefPluginGui::createMenus() QDialogButtonBox::ButtonLayout( style()->styleHint( QStyle::SH_DialogButtonLayout, nullptr, this ) ); mPanelMenu = new QMenu( tr( "Panels" ) ); - mPanelMenu->setObjectName( "mPanelMenu" ); + mPanelMenu->setObjectName( QStringLiteral( "mPanelMenu" ) ); mPanelMenu->addAction( dockWidgetGCPpoints->toggleViewAction() ); // mPanelMenu->addAction(dockWidgetLogView->toggleViewAction()); mToolbarMenu = new QMenu( tr( "Toolbars" ) ); - mToolbarMenu->setObjectName( "mToolbarMenu" ); + mToolbarMenu->setObjectName( QStringLiteral( "mToolbarMenu" ) ); mToolbarMenu->addAction( toolBarFile->toggleViewAction() ); mToolbarMenu->addAction( toolBarEdit->toggleViewAction() ); mToolbarMenu->addAction( toolBarView->toggleViewAction() ); QSettings s; - int size = s.value( "/IconSize", 32 ).toInt(); + int size = s.value( QStringLiteral( "/IconSize" ), 32 ).toInt(); toolBarFile->setIconSize( QSize( size, size ) ); toolBarEdit->setIconSize( QSize( size, size ) ); toolBarView->setIconSize( QSize( size, size ) ); @@ -1070,7 +1070,7 @@ void QgsGeorefPluginGui::createDockWidgets() QLabel* QgsGeorefPluginGui::createBaseLabelStatus() { - QFont myFont( "Arial", 9 ); + QFont myFont( QStringLiteral( "Arial" ), 9 ); QLabel* label = new QLabel( statusBar() ); label->setFont( myFont ); label->setMinimumWidth( 10 ); @@ -1095,7 +1095,7 @@ void QgsGeorefPluginGui::createStatusBar() statusBar()->addPermanentWidget( mCoordsLabel, 0 ); mEPSG = createBaseLabelStatus(); - mEPSG->setText( "EPSG:" ); + mEPSG->setText( QStringLiteral( "EPSG:" ) ); statusBar()->addPermanentWidget( mEPSG, 0 ); } @@ -1130,39 +1130,39 @@ void QgsGeorefPluginGui::updateIconTheme( const QString& theme ) { Q_UNUSED( theme ); // File actions - mActionOpenRaster->setIcon( getThemeIcon( "/mActionAddRasterLayer.svg" ) ); - mActionStartGeoref->setIcon( getThemeIcon( "/mActionStartGeoref.png" ) ); - mActionGDALScript->setIcon( getThemeIcon( "/mActionGDALScript.png" ) ); - mActionLoadGCPpoints->setIcon( getThemeIcon( "/mActionLoadGCPpoints.png" ) ); - mActionSaveGCPpoints->setIcon( getThemeIcon( "/mActionSaveGCPpointsAs.png" ) ); - mActionTransformSettings->setIcon( getThemeIcon( "/mActionTransformSettings.png" ) ); + mActionOpenRaster->setIcon( getThemeIcon( QStringLiteral( "/mActionAddRasterLayer.svg" ) ) ); + mActionStartGeoref->setIcon( getThemeIcon( QStringLiteral( "/mActionStartGeoref.png" ) ) ); + mActionGDALScript->setIcon( getThemeIcon( QStringLiteral( "/mActionGDALScript.png" ) ) ); + mActionLoadGCPpoints->setIcon( getThemeIcon( QStringLiteral( "/mActionLoadGCPpoints.png" ) ) ); + mActionSaveGCPpoints->setIcon( getThemeIcon( QStringLiteral( "/mActionSaveGCPpointsAs.png" ) ) ); + mActionTransformSettings->setIcon( getThemeIcon( QStringLiteral( "/mActionTransformSettings.png" ) ) ); // Edit actions - mActionAddPoint->setIcon( getThemeIcon( "/mActionAddGCPPoint.png" ) ); - mActionDeletePoint->setIcon( getThemeIcon( "/mActionDeleteGCPPoint.png" ) ); - mActionMoveGCPPoint->setIcon( getThemeIcon( "/mActionMoveGCPPoint.png" ) ); + mActionAddPoint->setIcon( getThemeIcon( QStringLiteral( "/mActionAddGCPPoint.png" ) ) ); + mActionDeletePoint->setIcon( getThemeIcon( QStringLiteral( "/mActionDeleteGCPPoint.png" ) ) ); + mActionMoveGCPPoint->setIcon( getThemeIcon( QStringLiteral( "/mActionMoveGCPPoint.png" ) ) ); // View actions - mActionPan->setIcon( getThemeIcon( "/mActionPan.svg" ) ); - mActionZoomIn->setIcon( getThemeIcon( "/mActionZoomIn.svg" ) ); - mActionZoomOut->setIcon( getThemeIcon( "/mActionZoomOut.svg" ) ); - mActionZoomToLayer->setIcon( getThemeIcon( "/mActionZoomToLayer.svg" ) ); - mActionZoomLast->setIcon( getThemeIcon( "/mActionZoomLast.svg" ) ); - mActionZoomNext->setIcon( getThemeIcon( "/mActionZoomNext.svg" ) ); - mActionLinkGeorefToQGis->setIcon( getThemeIcon( "/mActionLinkGeorefToQGis.png" ) ); - mActionLinkQGisToGeoref->setIcon( getThemeIcon( "/mActionLinkQGisToGeoref.png" ) ); + mActionPan->setIcon( getThemeIcon( QStringLiteral( "/mActionPan.svg" ) ) ); + mActionZoomIn->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomIn.svg" ) ) ); + mActionZoomOut->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomOut.svg" ) ) ); + mActionZoomToLayer->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomToLayer.svg" ) ) ); + mActionZoomLast->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomLast.svg" ) ) ); + mActionZoomNext->setIcon( getThemeIcon( QStringLiteral( "/mActionZoomNext.svg" ) ) ); + mActionLinkGeorefToQGis->setIcon( getThemeIcon( QStringLiteral( "/mActionLinkGeorefToQGis.png" ) ) ); + mActionLinkQGisToGeoref->setIcon( getThemeIcon( QStringLiteral( "/mActionLinkQGisToGeoref.png" ) ) ); // Settings actions - mActionRasterProperties->setIcon( getThemeIcon( "/mActionRasterProperties.png" ) ); - mActionGeorefConfig->setIcon( getThemeIcon( "/mActionGeorefConfig.png" ) ); + mActionRasterProperties->setIcon( getThemeIcon( QStringLiteral( "/mActionRasterProperties.png" ) ) ); + mActionGeorefConfig->setIcon( getThemeIcon( QStringLiteral( "/mActionGeorefConfig.png" ) ) ); - mActionQuit->setIcon( getThemeIcon( "/mActionQuit.png" ) ); + mActionQuit->setIcon( getThemeIcon( QStringLiteral( "/mActionQuit.png" ) ) ); } // Mapcanvas Plugin void QgsGeorefPluginGui::addRaster( const QString& file ) { - mLayer = new QgsRasterLayer( file, "Raster" ); + mLayer = new QgsRasterLayer( file, QStringLiteral( "Raster" ) ); // so layer is not added to legend QgsMapLayerRegistry::instance()->addMapLayers( @@ -1197,30 +1197,30 @@ void QgsGeorefPluginGui::readSettings() { QSettings s; QRect georefRect = QApplication::desktop()->screenGeometry( mIface->mainWindow() ); - resize( s.value( "/Plugin-GeoReferencer/size", QSize( georefRect.width() / 2 + georefRect.width() / 5, + resize( s.value( QStringLiteral( "/Plugin-GeoReferencer/size" ), QSize( georefRect.width() / 2 + georefRect.width() / 5, mIface->mainWindow()->height() ) ).toSize() ); - move( s.value( "/Plugin-GeoReferencer/pos", QPoint( parentWidget()->width() / 2 - width() / 2, 0 ) ).toPoint() ); - restoreState( s.value( "/Plugin-GeoReferencer/uistate" ).toByteArray() ); + move( s.value( QStringLiteral( "/Plugin-GeoReferencer/pos" ), QPoint( parentWidget()->width() / 2 - width() / 2, 0 ) ).toPoint() ); + restoreState( s.value( QStringLiteral( "/Plugin-GeoReferencer/uistate" ) ).toByteArray() ); // warp options - mResamplingMethod = ( QgsImageWarper::ResamplingMethod )s.value( "/Plugin-GeoReferencer/resamplingmethod", + mResamplingMethod = ( QgsImageWarper::ResamplingMethod )s.value( QStringLiteral( "/Plugin-GeoReferencer/resamplingmethod" ), QgsImageWarper::NearestNeighbour ).toInt(); - mCompressionMethod = s.value( "/Plugin-GeoReferencer/compressionmethod", "NONE" ).toString(); - mUseZeroForTrans = s.value( "/Plugin-GeoReferencer/usezerofortrans", false ).toBool(); + mCompressionMethod = s.value( QStringLiteral( "/Plugin-GeoReferencer/compressionmethod" ), "NONE" ).toString(); + mUseZeroForTrans = s.value( QStringLiteral( "/Plugin-GeoReferencer/usezerofortrans" ), false ).toBool(); } void QgsGeorefPluginGui::writeSettings() { QSettings s; - s.setValue( "/Plugin-GeoReferencer/pos", pos() ); - s.setValue( "/Plugin-GeoReferencer/size", size() ); - s.setValue( "/Plugin-GeoReferencer/uistate", saveState() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/pos" ), pos() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/size" ), size() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/uistate" ), saveState() ); // warp options - s.setValue( "/Plugin-GeoReferencer/transformparam", mTransformParam ); - s.setValue( "/Plugin-GeoReferencer/resamplingmethod", mResamplingMethod ); - s.setValue( "/Plugin-GeoReferencer/compressionmethod", mCompressionMethod ); - s.setValue( "/Plugin-GeoReferencer/usezerofortrans", mUseZeroForTrans ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/transformparam" ), mTransformParam ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/resamplingmethod" ), mResamplingMethod ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/compressionmethod" ), mCompressionMethod ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/usezerofortrans" ), mUseZeroForTrans ); } // GCP points @@ -1286,7 +1286,7 @@ void QgsGeorefPluginGui::saveGCPs() points << "mapX,mapY,pixelX,pixelY,enable" << endl; Q_FOREACH ( QgsGeorefDataPoint *pt, mPoints ) { - points << QString( "%1,%2,%3,%4,%5" ) + points << QStringLiteral( "%1,%2,%3,%4,%5" ) .arg( qgsDoubleToString( pt->mapCoords().x() ), qgsDoubleToString( pt->mapCoords().y() ), qgsDoubleToString( pt->pixelCoords().x() ), @@ -1515,8 +1515,8 @@ bool QgsGeorefPluginGui::writePDFMapFile( const QString& fileName, const QgsGeor printer.setOutputFileName( fileName ); QSettings s; - double paperWidth = s.value( "/Plugin-GeoReferencer/Config/WidthPDFMap", "297" ).toDouble(); - double paperHeight = s.value( "/Plugin-GeoReferencer/Config/HeightPDFMap", "420" ).toDouble(); + double paperWidth = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/WidthPDFMap" ), "297" ).toDouble(); + double paperHeight = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/HeightPDFMap" ), "420" ).toDouble(); //create composition QgsComposition* composition = new QgsComposition( mCanvas->mapSettings() ); @@ -1548,7 +1548,7 @@ bool QgsGeorefPluginGui::writePDFMapFile( const QString& fileName, const QgsGeor printer.setColorMode( QPrinter::Color ); QString residualUnits; - if ( s.value( "/Plugin-GeoReferencer/Config/ResidualUnits" ) == "mapUnits" && mGeorefTransform.providesAccurateInverseTransformation() ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ResidualUnits" ) ) == "mapUnits" && mGeorefTransform.providesAccurateInverseTransformation() ) { residualUnits = tr( "map units" ); } @@ -1602,8 +1602,8 @@ bool QgsGeorefPluginGui::writePDFReportFile( const QString& fileName, const QgsG tableContentFont.setPointSize( 9 ); QSettings s; - double leftMargin = s.value( "/Plugin-GeoReferencer/Config/LeftMarginPDF", "2.0" ).toDouble(); - double rightMargin = s.value( "/Plugin-GeoReferencer/Config/RightMarginPDF", "2.0" ).toDouble(); + double leftMargin = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/LeftMarginPDF" ), "2.0" ).toDouble(); + double rightMargin = s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/RightMarginPDF" ), "2.0" ).toDouble(); double contentWidth = 210 - ( leftMargin + rightMargin ); //title @@ -1653,7 +1653,7 @@ bool QgsGeorefPluginGui::writePDFReportFile( const QString& fileName, const QgsG bool wldTransform = transform.getOriginScaleRotation( origin, scaleX, scaleY, rotation ); QString residualUnits; - if ( s.value( "/Plugin-GeoReferencer/Config/ResidualUnits" ) == "mapUnits" && mGeorefTransform.providesAccurateInverseTransformation() ) + if ( s.value( QStringLiteral( "/Plugin-GeoReferencer/Config/ResidualUnits" ) ) == "mapUnits" && mGeorefTransform.providesAccurateInverseTransformation() ) { residualUnits = tr( "map units" ); } @@ -1665,7 +1665,7 @@ bool QgsGeorefPluginGui::writePDFReportFile( const QString& fileName, const QgsG QGraphicsRectItem* previousItem = composerMap; if ( wldTransform ) { - QString parameterTitle = tr( "Transformation parameters" ) + QLatin1String( " (" ) + convertTransformEnumToString( transform.transformParametrisation() ) + QLatin1String( ")" ); + QString parameterTitle = tr( "Transformation parameters" ) + QStringLiteral( " (" ) + convertTransformEnumToString( transform.transformParametrisation() ) + QStringLiteral( ")" ); parameterLabel = new QgsComposerLabel( composition ); parameterLabel->setFont( titleFont ); parameterLabel->setText( parameterTitle ); @@ -1822,11 +1822,11 @@ void QgsGeorefPluginGui::updateTransformParamLabel() // Gdal script void QgsGeorefPluginGui::showGDALScript( const QStringList& commands ) { - QString script = commands.join( "\n" ) + '\n'; + QString script = commands.join( QStringLiteral( "\n" ) ) + '\n'; // create window to show gdal script QDialogButtonBox *bbxGdalScript = new QDialogButtonBox( QDialogButtonBox::Cancel, Qt::Horizontal, this ); - QPushButton *pbnCopyInClipBoard = new QPushButton( getThemeIcon( "/mActionEditPaste.svg" ), + QPushButton *pbnCopyInClipBoard = new QPushButton( getThemeIcon( QStringLiteral( "/mActionEditPaste.svg" ) ), tr( "Copy to Clipboard" ), bbxGdalScript ); bbxGdalScript->addButton( pbnCopyInClipBoard, QDialogButtonBox::AcceptRole ); @@ -1855,52 +1855,52 @@ void QgsGeorefPluginGui::showGDALScript( const QStringList& commands ) QString QgsGeorefPluginGui::generateGDALtranslateCommand( bool generateTFW ) { QStringList gdalCommand; - gdalCommand << "gdal_translate" << "-of GTiff"; + gdalCommand << QStringLiteral( "gdal_translate" ) << QStringLiteral( "-of GTiff" ); if ( generateTFW ) { // say gdal generate associated ESRI world file - gdalCommand << "-co TFW=YES"; + gdalCommand << QStringLiteral( "-co TFW=YES" ); } Q_FOREACH ( QgsGeorefDataPoint *pt, mPoints ) { - gdalCommand << QString( "-gcp %1 %2 %3 %4" ).arg( pt->pixelCoords().x() ).arg( -pt->pixelCoords().y() ) + gdalCommand << QStringLiteral( "-gcp %1 %2 %3 %4" ).arg( pt->pixelCoords().x() ).arg( -pt->pixelCoords().y() ) .arg( pt->mapCoords().x() ).arg( pt->mapCoords().y() ); } QFileInfo rasterFileInfo( mRasterFileName ); mTranslatedRasterFileName = QDir::tempPath() + '/' + rasterFileInfo.fileName(); - gdalCommand << QString( "\"%1\"" ).arg( mRasterFileName ) << QString( "\"%1\"" ).arg( mTranslatedRasterFileName ); + gdalCommand << QStringLiteral( "\"%1\"" ).arg( mRasterFileName ) << QStringLiteral( "\"%1\"" ).arg( mTranslatedRasterFileName ); - return gdalCommand.join( " " ); + return gdalCommand.join( QStringLiteral( " " ) ); } QString QgsGeorefPluginGui::generateGDALwarpCommand( const QString& resampling, const QString& compress, bool useZeroForTrans, int order, double targetResX, double targetResY ) { QStringList gdalCommand; - gdalCommand << "gdalwarp" << "-r" << resampling; + gdalCommand << QStringLiteral( "gdalwarp" ) << QStringLiteral( "-r" ) << resampling; if ( order > 0 && order <= 3 ) { // Let gdalwarp use polynomial warp with the given degree - gdalCommand << "-order" << QString::number( order ); + gdalCommand << QStringLiteral( "-order" ) << QString::number( order ); } else { // Otherwise, use thin plate spline interpolation - gdalCommand << "-tps"; + gdalCommand << QStringLiteral( "-tps" ); } gdalCommand << "-co COMPRESS=" + compress << ( useZeroForTrans ? "-dstalpha" : "" ); if ( targetResX != 0.0 && targetResY != 0.0 ) { - gdalCommand << "-tr" << QString::number( targetResX, 'f' ) << QString::number( targetResY, 'f' ); + gdalCommand << QStringLiteral( "-tr" ) << QString::number( targetResX, 'f' ) << QString::number( targetResY, 'f' ); } - gdalCommand << QString( "\"%1\"" ).arg( mTranslatedRasterFileName ) << QString( "\"%1\"" ).arg( mModifiedRasterFileName ); + gdalCommand << QStringLiteral( "\"%1\"" ).arg( mTranslatedRasterFileName ) << QStringLiteral( "\"%1\"" ).arg( mModifiedRasterFileName ); - return gdalCommand.join( " " ); + return gdalCommand.join( QStringLiteral( " " ) ); } // Log @@ -2053,17 +2053,17 @@ QString QgsGeorefPluginGui::convertResamplingEnumToString( QgsImageWarper::Resam switch ( resampling ) { case QgsImageWarper::NearestNeighbour: - return "near"; + return QStringLiteral( "near" ); case QgsImageWarper::Bilinear: - return "bilinear"; + return QStringLiteral( "bilinear" ); case QgsImageWarper::Cubic: - return "cubic"; + return QStringLiteral( "cubic" ); case QgsImageWarper::CubicSpline: - return "cubicspline"; + return QStringLiteral( "cubicspline" ); case QgsImageWarper::Lanczos: - return "lanczos"; + return QStringLiteral( "lanczos" ); } - return ""; + return QLatin1String( "" ); } int QgsGeorefPluginGui::polynomialOrder( QgsGeorefTransform::TransformParametrisation transform ) @@ -2086,7 +2086,7 @@ int QgsGeorefPluginGui::polynomialOrder( QgsGeorefTransform::TransformParametris QString QgsGeorefPluginGui::guessWorldFileName( const QString &rasterFileName ) { - QString worldFileName = ""; + QString worldFileName = QLatin1String( "" ); int point = rasterFileName.lastIndexOf( '.' ); if ( point != -1 && point != rasterFileName.length() - 1 ) worldFileName = rasterFileName.left( point + 1 ) + "wld"; @@ -2109,7 +2109,7 @@ QIcon QgsGeorefPluginGui::getThemeIcon( const QString &theName ) else { QSettings settings; - QString themePath = ":/icons/" + settings.value( "/Themes" ).toString() + theName; + QString themePath = ":/icons/" + settings.value( QStringLiteral( "/Themes" ) ).toString() + theName; if ( QFile::exists( themePath ) ) { return QIcon( themePath ); @@ -2197,5 +2197,5 @@ void QgsGeorefPluginGui::clearGCPData() int QgsGeorefPluginGui::messageTimeout() { QSettings settings; - return settings.value( "/qgis/messageTimeout", 5 ).toInt(); + return settings.value( QStringLiteral( "/qgis/messageTimeout" ), 5 ).toInt(); } diff --git a/src/plugins/georeferencer/qgsgeorefvalidators.cpp b/src/plugins/georeferencer/qgsgeorefvalidators.cpp index 3cba8a33d1de..2cf49eba44da 100644 --- a/src/plugins/georeferencer/qgsgeorefvalidators.cpp +++ b/src/plugins/georeferencer/qgsgeorefvalidators.cpp @@ -45,16 +45,16 @@ QValidator::State QgsDMSAndDDValidator::validate( QString &input, int &pos ) con if ( !input.contains( ' ' ) ) { - rx.setPattern( "-?\\d*(\\.|,)(\\d+)?" ); + rx.setPattern( QStringLiteral( "-?\\d*(\\.|,)(\\d+)?" ) ); if ( rx.exactMatch( input ) ) return Acceptable; } else { - rx.setPattern( "-?\\d{1,3}\\s(\\d{1,2}(\\s(\\d{1,2}((\\.|,)(\\d{1,3})?)?)?)?)?" ); + rx.setPattern( QStringLiteral( "-?\\d{1,3}\\s(\\d{1,2}(\\s(\\d{1,2}((\\.|,)(\\d{1,3})?)?)?)?)?" ) ); if ( rx.exactMatch( input ) ) { - rx.setPattern( "-?\\d{1,3}\\s60" ); + rx.setPattern( QStringLiteral( "-?\\d{1,3}\\s60" ) ); if ( rx.exactMatch( input ) ) { int in = input.leftRef( input.indexOf( ' ' ) ).toInt(); @@ -65,7 +65,7 @@ QValidator::State QgsDMSAndDDValidator::validate( QString &input, int &pos ) con return Acceptable; } - rx.setPattern( "-?\\d{1,3}\\s\\d{1,2}\\s60" ); + rx.setPattern( QStringLiteral( "-?\\d{1,3}\\s\\d{1,2}\\s60" ) ); if ( rx.exactMatch( input ) ) { int min = input.split( ' ' ).at( 1 ).toInt() + 1; diff --git a/src/plugins/georeferencer/qgsmapcoordsdialog.cpp b/src/plugins/georeferencer/qgsmapcoordsdialog.cpp index fff848f90334..a7a216adfbd4 100644 --- a/src/plugins/georeferencer/qgsmapcoordsdialog.cpp +++ b/src/plugins/georeferencer/qgsmapcoordsdialog.cpp @@ -29,7 +29,7 @@ QgsMapCoordsDialog::QgsMapCoordsDialog( QgsMapCanvas* qgisCanvas, const QgsPoint setupUi( this ); QSettings s; - restoreGeometry( s.value( "/Plugin-GeoReferencer/MapCoordsWindow/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/Plugin-GeoReferencer/MapCoordsWindow/geometry" ) ).toByteArray() ); setAttribute( Qt::WA_DeleteOnClose ); @@ -61,7 +61,7 @@ QgsMapCoordsDialog::~QgsMapCoordsDialog() delete mToolEmitPoint; QSettings settings; - settings.setValue( "/Plugin-GeoReferencer/MapCoordsWindow/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/MapCoordsWindow/geometry" ), saveGeometry() ); } void QgsMapCoordsDialog::updateOK() diff --git a/src/plugins/georeferencer/qgsresidualplotitem.cpp b/src/plugins/georeferencer/qgsresidualplotitem.cpp index 8c33b9727f48..3581d48f2e05 100644 --- a/src/plugins/georeferencer/qgsresidualplotitem.cpp +++ b/src/plugins/georeferencer/qgsresidualplotitem.cpp @@ -135,11 +135,11 @@ void QgsResidualPlotItem::paint( QPainter* painter, const QStyleOptionGraphicsIt scaleBarFont.setPointSize( 9 ); if ( mConvertScaleToMapUnits ) { - QgsComposerUtils::drawText( painter, QPointF( 5, rect().height() - 4 + QgsComposerUtils::fontAscentMM( scaleBarFont ) ), QString( "%1 map units" ).arg( scaleBarWidthUnits ), QFont() ); + QgsComposerUtils::drawText( painter, QPointF( 5, rect().height() - 4 + QgsComposerUtils::fontAscentMM( scaleBarFont ) ), QStringLiteral( "%1 map units" ).arg( scaleBarWidthUnits ), QFont() ); } else { - QgsComposerUtils::drawText( painter, QPointF( 5, rect().height() - 4 + QgsComposerUtils::fontAscentMM( scaleBarFont ) ), QString( "%1 pixels" ).arg( scaleBarWidthUnits ), QFont() ); + QgsComposerUtils::drawText( painter, QPointF( 5, rect().height() - 4 + QgsComposerUtils::fontAscentMM( scaleBarFont ) ), QStringLiteral( "%1 pixels" ).arg( scaleBarWidthUnits ), QFont() ); } drawFrame( painter ); diff --git a/src/plugins/georeferencer/qgstransformsettingsdialog.cpp b/src/plugins/georeferencer/qgstransformsettingsdialog.cpp index 1d15b998655a..a9b53a5c139c 100644 --- a/src/plugins/georeferencer/qgstransformsettingsdialog.cpp +++ b/src/plugins/georeferencer/qgstransformsettingsdialog.cpp @@ -35,7 +35,7 @@ QgsTransformSettingsDialog::QgsTransformSettingsDialog( const QString &raster, c setupUi( this ); QSettings s; - restoreGeometry( s.value( "/Plugin-GeoReferencer/TransformSettingsWindow/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/Plugin-GeoReferencer/TransformSettingsWindow/geometry" ) ).toByteArray() ); cmbTransformType->addItem( tr( "Linear" ), ( int )QgsGeorefTransform::Linear ); cmbTransformType->addItem( tr( "Helmert" ), ( int )QgsGeorefTransform::Helmert ); @@ -48,10 +48,10 @@ QgsTransformSettingsDialog::QgsTransformSettingsDialog( const QString &raster, c leOutputRaster->setText( output ); // Populate CompressionComboBox - mListCompression.append( "None" ); - mListCompression.append( "LZW" ); - mListCompression.append( "PACKBITS" ); - mListCompression.append( "DEFLATE" ); + mListCompression.append( QStringLiteral( "None" ) ); + mListCompression.append( QStringLiteral( "LZW" ) ); + mListCompression.append( QStringLiteral( "PACKBITS" ) ); + mListCompression.append( QStringLiteral( "DEFLATE" ) ); QStringList listCompressionTr; Q_FOREACH ( const QString& item, mListCompression ) { @@ -59,33 +59,33 @@ QgsTransformSettingsDialog::QgsTransformSettingsDialog( const QString &raster, c } cmbCompressionComboBox->addItems( listCompressionTr ); - cmbTransformType->setCurrentIndex( s.value( "/Plugin-GeoReferencer/lasttransformation", -1 ).toInt() ); - cmbResampling->setCurrentIndex( s.value( "/Plugin-GeoReferencer/lastresampling", 0 ).toInt() ); - cmbCompressionComboBox->setCurrentIndex( s.value( "/Plugin-GeoReferencer/lastcompression", 0 ).toInt() ); + cmbTransformType->setCurrentIndex( s.value( QStringLiteral( "/Plugin-GeoReferencer/lasttransformation" ), -1 ).toInt() ); + cmbResampling->setCurrentIndex( s.value( QStringLiteral( "/Plugin-GeoReferencer/lastresampling" ), 0 ).toInt() ); + cmbCompressionComboBox->setCurrentIndex( s.value( QStringLiteral( "/Plugin-GeoReferencer/lastcompression" ), 0 ).toInt() ); - QString targetCRSString = s.value( "/Plugin-GeoReferencer/targetsrs" ).toString(); + QString targetCRSString = s.value( QStringLiteral( "/Plugin-GeoReferencer/targetsrs" ) ).toString(); QgsCoordinateReferenceSystem targetCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( targetCRSString ); mCrsSelector->setCrs( targetCRS ); - mWorldFileCheckBox->setChecked( s.value( "/Plugin-Georeferencer/word_file_checkbox", false ).toBool() ); + mWorldFileCheckBox->setChecked( s.value( QStringLiteral( "/Plugin-Georeferencer/word_file_checkbox" ), false ).toBool() ); - cbxUserResolution->setChecked( s.value( "/Plugin-Georeferencer/user_specified_resolution", false ).toBool() ); + cbxUserResolution->setChecked( s.value( QStringLiteral( "/Plugin-Georeferencer/user_specified_resolution" ), false ).toBool() ); bool ok; - dsbHorizRes->setValue( s.value( "/Plugin-GeoReferencer/user_specified_resx", 1.0 ).toDouble( &ok ) ); + dsbHorizRes->setValue( s.value( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resx" ), 1.0 ).toDouble( &ok ) ); if ( !ok ) dsbHorizRes->setValue( 1.0 ); - dsbVerticalRes->setValue( s.value( "/Plugin-GeoReferencer/user_specified_resy", -1.0 ).toDouble( &ok ) ); + dsbVerticalRes->setValue( s.value( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resy" ), -1.0 ).toDouble( &ok ) ); if ( !ok ) dsbHorizRes->setValue( -1.0 ); - cbxZeroAsTrans->setChecked( s.value( "/Plugin-GeoReferencer/zeroastrans", false ).toBool() ); - cbxLoadInQgisWhenDone->setChecked( s.value( "/Plugin-GeoReferencer/loadinqgis", false ).toBool() ); + cbxZeroAsTrans->setChecked( s.value( QStringLiteral( "/Plugin-GeoReferencer/zeroastrans" ), false ).toBool() ); + cbxLoadInQgisWhenDone->setChecked( s.value( QStringLiteral( "/Plugin-GeoReferencer/loadinqgis" ), false ).toBool() ); } QgsTransformSettingsDialog::~QgsTransformSettingsDialog() { QSettings settings; - settings.setValue( "/Plugin-GeoReferencer/TransformSettingsWindow/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/TransformSettingsWindow/geometry" ), saveGeometry() ); } void QgsTransformSettingsDialog::getTransformSettings( QgsGeorefTransform::TransformParametrisation &tp, @@ -103,7 +103,7 @@ void QgsTransformSettingsDialog::getTransformSettings( QgsGeorefTransform::Trans comprMethod = mListCompression.at( cmbCompressionComboBox->currentIndex() ).toUpper(); if ( mWorldFileCheckBox->isChecked() ) { - raster = ""; + raster = QLatin1String( "" ); } else { @@ -126,17 +126,17 @@ void QgsTransformSettingsDialog::getTransformSettings( QgsGeorefTransform::Trans void QgsTransformSettingsDialog::resetSettings() { QSettings s; - s.setValue( "/Plugin-GeoReferencer/lasttransformation", -1 ); - s.setValue( "/Plugin-GeoReferencer/lastresampling", 0 ); - s.setValue( "/Plugin-GeoReferencer/lastcompression", 0 ); - s.setValue( "/Plugin-GeoReferencer/targetsrs", QString() ); - s.setValue( "/Plugin-GeoReferencer/zeroastrans", false ); - s.setValue( "/Plugin-GeoReferencer/loadinqgis", false ); - s.setValue( "/Plugin-GeoReferencer/user_specified_resolution", false ); - s.setValue( "/Plugin-GeoReferencer/user_specified_resx", 1.0 ); - s.setValue( "/Plugin-GeoReferencer/user_specified_resy", -1.0 ); - s.setValue( "/Plugin-GeoReferencer/word_file_checkbox", false ); - s.setValue( "/Plugin-GeoReferencer/lastPDFReportDir", QDir::homePath() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lasttransformation" ), -1 ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastresampling" ), 0 ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastcompression" ), 0 ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/targetsrs" ), QString() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/zeroastrans" ), false ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/loadinqgis" ), false ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resolution" ), false ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resx" ), 1.0 ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resy" ), -1.0 ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/word_file_checkbox" ), false ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), QDir::homePath() ); } void QgsTransformSettingsDialog::changeEvent( QEvent *e ) @@ -178,21 +178,21 @@ void QgsTransformSettingsDialog::accept() } QSettings s; - s.setValue( "/Plugin-GeoReferencer/lasttransformation", cmbTransformType->currentIndex() ); - s.setValue( "/Plugin-GeoReferencer/lastresampling", cmbResampling->currentIndex() ); - s.setValue( "/Plugin-GeoReferencer/lastcompression", cmbCompressionComboBox->currentIndex() ); - s.setValue( "/Plugin-GeoReferencer/targetsrs", mCrsSelector->crs().authid() ); - s.setValue( "/Plugin-GeoReferencer/zeroastrans", cbxZeroAsTrans->isChecked() ); - s.setValue( "/Plugin-GeoReferencer/loadinqgis", cbxLoadInQgisWhenDone->isChecked() ); - s.setValue( "/Plugin-GeoReferencer/user_specified_resolution", cbxUserResolution->isChecked() ); - s.setValue( "/Plugin-GeoReferencer/user_specified_resx", dsbHorizRes->value() ); - s.setValue( "/Plugin-GeoReferencer/user_specified_resy", dsbVerticalRes->value() ); - s.setValue( "/Plugin-GeoReferencer/word_file_checkbox", mWorldFileCheckBox->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lasttransformation" ), cmbTransformType->currentIndex() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastresampling" ), cmbResampling->currentIndex() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastcompression" ), cmbCompressionComboBox->currentIndex() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/targetsrs" ), mCrsSelector->crs().authid() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/zeroastrans" ), cbxZeroAsTrans->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/loadinqgis" ), cbxLoadInQgisWhenDone->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resolution" ), cbxUserResolution->isChecked() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resx" ), dsbHorizRes->value() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resy" ), dsbVerticalRes->value() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/word_file_checkbox" ), mWorldFileCheckBox->isChecked() ); QString pdfReportFileName = mReportFileLineEdit->text(); if ( !pdfReportFileName.isEmpty() ) { QFileInfo fi( pdfReportFileName ); - s.setValue( "/Plugin-GeoReferencer/lastPDFReportDir", fi.absolutePath() ); + s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), fi.absolutePath() ); } QDialog::accept(); } @@ -206,7 +206,7 @@ void QgsTransformSettingsDialog::on_tbnOutputRaster_clicked() } QString rasterFileName = QFileDialog::getSaveFileName( this, tr( "Destination Raster" ), - selectedFile, "GeoTIFF (*.tif *.tiff *.TIF *.TIFF)" ); + selectedFile, QStringLiteral( "GeoTIFF (*.tif *.tiff *.TIF *.TIFF)" ) ); if ( rasterFileName.isEmpty() ) return; @@ -217,12 +217,12 @@ void QgsTransformSettingsDialog::on_tbnOutputRaster_clicked() void QgsTransformSettingsDialog::on_tbnMapFile_clicked() { QSettings s; - QString myLastUsedDir = s.value( "/Plugin-GeoReferencer/lastPDFReportDir", QDir::homePath() ).toString(); + QString myLastUsedDir = s.value( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), QDir::homePath() ).toString(); QString initialFile = !mMapFileLineEdit->text().isEmpty() ? mMapFileLineEdit->text() : myLastUsedDir; QString outputFileName = QFileDialog::getSaveFileName( this, tr( "Save Map File as" ), initialFile, tr( "PDF Format" ) + " (*.pdf *PDF)" ); if ( !outputFileName.isNull() ) { - if ( !outputFileName.endsWith( ".pdf", Qt::CaseInsensitive ) ) + if ( !outputFileName.endsWith( QLatin1String( ".pdf" ), Qt::CaseInsensitive ) ) { outputFileName.append( ".pdf" ); } @@ -233,12 +233,12 @@ void QgsTransformSettingsDialog::on_tbnMapFile_clicked() void QgsTransformSettingsDialog::on_tbnReportFile_clicked() { QSettings s; - QString myLastUsedDir = s.value( "/Plugin-GeoReferencer/lastPDFReportDir", QDir::homePath() ).toString(); + QString myLastUsedDir = s.value( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), QDir::homePath() ).toString(); QString initialFile = !mReportFileLineEdit->text().isEmpty() ? mReportFileLineEdit->text() : myLastUsedDir; QString outputFileName = QFileDialog::getSaveFileName( this, tr( "Save Report File as" ), initialFile, tr( "PDF Format" ) + " (*.pdf *PDF)" ); if ( !outputFileName.isNull() ) { - if ( !outputFileName.endsWith( ".pdf", Qt::CaseInsensitive ) ) + if ( !outputFileName.endsWith( QLatin1String( ".pdf" ), Qt::CaseInsensitive ) ) { outputFileName.append( ".pdf" ); } @@ -291,7 +291,7 @@ QString QgsTransformSettingsDialog::generateModifiedRasterFileName( const QStrin modifiedFileName.insert( pos, tr( "_modified", "Georeferencer:QgsOpenRasterDialog.cpp - used to modify a user given file name" ) ); pos = modifiedFileName.size() - modifiedFileInfo.suffix().size(); - modifiedFileName.replace( pos, modifiedFileName.size(), "tif" ); + modifiedFileName.replace( pos, modifiedFileName.size(), QStringLiteral( "tif" ) ); return modifiedFileName; } @@ -311,7 +311,7 @@ QIcon QgsTransformSettingsDialog::getThemeIcon( const QString &theName ) else { QSettings settings; - QString themePath = ":/icons/" + settings.value( "/Themes" ).toString() + theName; + QString themePath = ":/icons/" + settings.value( QStringLiteral( "/Themes" ) ).toString() + theName; if ( QFile::exists( themePath ) ) { return QIcon( themePath ); diff --git a/src/plugins/gps_importer/qgsbabelformat.cpp b/src/plugins/gps_importer/qgsbabelformat.cpp index cfb17e133ca8..f86960b45847 100644 --- a/src/plugins/gps_importer/qgsbabelformat.cpp +++ b/src/plugins/gps_importer/qgsbabelformat.cpp @@ -115,13 +115,13 @@ QStringList QgsSimpleBabelFormat::importCommand( const QString& babel, { QStringList args; args - << QString( "\"%1\"" ).arg( babel ) + << QStringLiteral( "\"%1\"" ).arg( babel ) << featuretype - << "-i" + << QStringLiteral( "-i" ) << mFormat - << "-o" << "gpx" - << QString( "\"%1\"" ).arg( input ) - << QString( "\"%1\"" ).arg( output ); + << QStringLiteral( "-o" ) << QStringLiteral( "gpx" ) + << QStringLiteral( "\"%1\"" ).arg( input ) + << QStringLiteral( "\"%1\"" ).arg( output ); return args; } @@ -157,14 +157,14 @@ QStringList QgsBabelCommand::importCommand( const QString& babel, QStringList::const_iterator iter; for ( iter = mImportCmd.begin(); iter != mImportCmd.end(); ++iter ) { - if ( *iter == "%babel" ) + if ( *iter == QLatin1String( "%babel" ) ) copy.append( babel ); - else if ( *iter == "%type" ) + else if ( *iter == QLatin1String( "%type" ) ) copy.append( featuretype ); - else if ( *iter == "%in" ) - copy.append( QString( "\"%1\"" ).arg( input ) ); - else if ( *iter == "%out" ) - copy.append( QString( "\"%1\"" ).arg( output ) ); + else if ( *iter == QLatin1String( "%in" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( input ) ); + else if ( *iter == QLatin1String( "%out" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( output ) ); else copy.append( *iter ); } @@ -181,14 +181,14 @@ QStringList QgsBabelCommand::exportCommand( const QString& babel, QStringList::const_iterator iter; for ( iter = mExportCmd.begin(); iter != mExportCmd.end(); ++iter ) { - if ( *iter == "%babel" ) + if ( *iter == QLatin1String( "%babel" ) ) copy.append( babel ); - else if ( *iter == "%type" ) + else if ( *iter == QLatin1String( "%type" ) ) copy.append( featuretype ); - else if ( *iter == "%in" ) - copy.append( QString( "\"%1\"" ).arg( input ) ); - else if ( *iter == "%out" ) - copy.append( QString( "\"%1\"" ).arg( output ) ); + else if ( *iter == QLatin1String( "%in" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( input ) ); + else if ( *iter == QLatin1String( "%out" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( output ) ); else copy.append( *iter ); } diff --git a/src/plugins/gps_importer/qgsbabelformat.h b/src/plugins/gps_importer/qgsbabelformat.h index 70df06926bd6..986fdf8cc3d3 100644 --- a/src/plugins/gps_importer/qgsbabelformat.h +++ b/src/plugins/gps_importer/qgsbabelformat.h @@ -26,7 +26,7 @@ class QString; class QgsBabelFormat { public: - explicit QgsBabelFormat( const QString& name = "" ); + explicit QgsBabelFormat( const QString& name = QStringLiteral( "" ) ); virtual ~QgsBabelFormat() { } const QString& name() const; diff --git a/src/plugins/gps_importer/qgsgpsdevice.cpp b/src/plugins/gps_importer/qgsgpsdevice.cpp index d2d3e2b5be76..476a5f6a1469 100644 --- a/src/plugins/gps_importer/qgsgpsdevice.cpp +++ b/src/plugins/gps_importer/qgsgpsdevice.cpp @@ -42,25 +42,25 @@ QStringList QgsGPSDevice::importCommand( const QString& babel, const QString& out ) const { const QStringList* original; - if ( type == "-w" ) + if ( type == QLatin1String( "-w" ) ) original = &mWptDlCmd; - else if ( type == "-r" ) + else if ( type == QLatin1String( "-r" ) ) original = &mRteDlCmd; - else if ( type == "-t" ) + else if ( type == QLatin1String( "-t" ) ) original = &mTrkDlCmd; else throw "Bad error!"; QStringList copy; QStringList::const_iterator iter; for ( iter = original->begin(); iter != original->end(); ++iter ) { - if ( *iter == "%babel" ) + if ( *iter == QLatin1String( "%babel" ) ) copy.append( babel ); - else if ( *iter == "%type" ) + else if ( *iter == QLatin1String( "%type" ) ) copy.append( type ); - else if ( *iter == "%in" ) - copy.append( QString( "\"%1\"" ).arg( in ) ); - else if ( *iter == "%out" ) - copy.append( QString( "\"%1\"" ).arg( out ) ); + else if ( *iter == QLatin1String( "%in" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( in ) ); + else if ( *iter == QLatin1String( "%out" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( out ) ); else copy.append( *iter ); } @@ -74,25 +74,25 @@ QStringList QgsGPSDevice::exportCommand( const QString& babel, const QString& out ) const { const QStringList* original; - if ( type == "-w" ) + if ( type == QLatin1String( "-w" ) ) original = &mWptUlCmd; - else if ( type == "-r" ) + else if ( type == QLatin1String( "-r" ) ) original = &mRteUlCmd; - else if ( type == "-t" ) + else if ( type == QLatin1String( "-t" ) ) original = &mTrkUlCmd; else throw "Bad error!"; QStringList copy; QStringList::const_iterator iter; for ( iter = original->begin(); iter != original->end(); ++iter ) { - if ( *iter == "%babel" ) + if ( *iter == QLatin1String( "%babel" ) ) copy.append( babel ); - else if ( *iter == "%type" ) + else if ( *iter == QLatin1String( "%type" ) ) copy.append( type ); - else if ( *iter == "%in" ) - copy.append( QString( "\"%1\"" ).arg( in ) ); - else if ( *iter == "%out" ) - copy.append( QString( "\"%1\"" ).arg( out ) ); + else if ( *iter == QLatin1String( "%in" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( in ) ); + else if ( *iter == QLatin1String( "%out" ) ) + copy.append( QStringLiteral( "\"%1\"" ).arg( out ) ); else copy.append( *iter ); } diff --git a/src/plugins/gps_importer/qgsgpsdevicedialog.cpp b/src/plugins/gps_importer/qgsgpsdevicedialog.cpp index 7a6630cf0194..a989805a9630 100644 --- a/src/plugins/gps_importer/qgsgpsdevicedialog.cpp +++ b/src/plugins/gps_importer/qgsgpsdevicedialog.cpp @@ -93,10 +93,10 @@ void QgsGPSDeviceDialog::on_pbnUpdateDevice_clicked() void QgsGPSDeviceDialog::slotUpdateDeviceList( const QString& selection ) { QString selected; - if ( selection == "" ) + if ( selection == QLatin1String( "" ) ) { QListWidgetItem* item = lbDeviceList->currentItem(); - selected = ( item ? item->text() : "" ); + selected = ( item ? item->text() : QLatin1String( "" ) ); } else { @@ -137,17 +137,17 @@ void QgsGPSDeviceDialog::slotSelectionChanged( QListWidgetItem *current ) leDeviceName->setText( devName ); QgsGPSDevice* device = mDevices[devName]; leWptDown->setText( device-> - importCommand( "%babel", "-w", "%in", "%out" ).join( " " ) ); + importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leWptUp->setText( device-> - exportCommand( "%babel", "-w", "%in", "%out" ).join( " " ) ); + exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leRteDown->setText( device-> - importCommand( "%babel", "-r", "%in", "%out" ).join( " " ) ); + importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leRteUp->setText( device-> - exportCommand( "%babel", "-r", "%in", "%out" ).join( " " ) ); + exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leTrkDown->setText( device-> - importCommand( "%babel", "-t", "%in", "%out" ).join( " " ) ); + importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); leTrkUp->setText( device-> - exportCommand( "%babel", "-t", "%in", "%out" ).join( " " ) ); + exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ) ); } } @@ -156,25 +156,25 @@ void QgsGPSDeviceDialog::writeDeviceSettings() { QStringList deviceNames; QSettings settings; - QString devPath = "/Plugin-GPS/devices/%1"; - settings.remove( "/Plugin-GPS/devices" ); + QString devPath = QStringLiteral( "/Plugin-GPS/devices/%1" ); + settings.remove( QStringLiteral( "/Plugin-GPS/devices" ) ); std::map<QString, QgsGPSDevice*>::const_iterator iter; for ( iter = mDevices.begin(); iter != mDevices.end(); ++iter ) { deviceNames.append( iter->first ); QString wptDownload = - iter->second->importCommand( "%babel", "-w", "%in", "%out" ).join( " " ); + iter->second->importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString wptUpload = - iter->second->exportCommand( "%babel", "-w", "%in", "%out" ).join( " " ); + iter->second->exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-w" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString rteDownload = - iter->second->importCommand( "%babel", "-r", "%in", "%out" ).join( " " ); + iter->second->importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString rteUpload = - iter->second->exportCommand( "%babel", "-r", "%in", "%out" ).join( " " ); + iter->second->exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-r" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString trkDownload = - iter->second->importCommand( "%babel", "-t", "%in", "%out" ).join( " " ); + iter->second->importCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); QString trkUpload = - iter->second->exportCommand( "%babel", "-t", "%in", "%out" ).join( " " ); + iter->second->exportCommand( QStringLiteral( "%babel" ), QStringLiteral( "-t" ), QStringLiteral( "%in" ), QStringLiteral( "%out" ) ).join( QStringLiteral( " " ) ); settings.setValue( devPath.arg( iter->first ) + "/wptdownload", wptDownload ); settings.setValue( devPath.arg( iter->first ) + "/wptupload", wptUpload ); @@ -185,7 +185,7 @@ void QgsGPSDeviceDialog::writeDeviceSettings() trkDownload ); settings.setValue( devPath.arg( iter->first ) + "/trkupload", trkUpload ); } - settings.setValue( "/Plugin-GPS/devicelist", deviceNames ); + settings.setValue( QStringLiteral( "/Plugin-GPS/devicelist" ), deviceNames ); } void QgsGPSDeviceDialog::on_pbnClose_clicked() diff --git a/src/plugins/gps_importer/qgsgpsdevicedialog.h b/src/plugins/gps_importer/qgsgpsdevicedialog.h index cc793eda4d02..11d78bd6eaed 100644 --- a/src/plugins/gps_importer/qgsgpsdevicedialog.h +++ b/src/plugins/gps_importer/qgsgpsdevicedialog.h @@ -29,7 +29,7 @@ class QgsGPSDeviceDialog : public QDialog, private Ui::QgsGPSDeviceDialogBase void on_pbnDeleteDevice_clicked(); void on_pbnUpdateDevice_clicked(); void on_pbnClose_clicked(); - void slotUpdateDeviceList( const QString& selection = "" ); + void slotUpdateDeviceList( const QString& selection = QLatin1String( "" ) ); void slotSelectionChanged( QListWidgetItem *current ); signals: diff --git a/src/plugins/gps_importer/qgsgpsplugin.cpp b/src/plugins/gps_importer/qgsgpsplugin.cpp index 9e736a2ce029..34f4c278d09b 100644 --- a/src/plugins/gps_importer/qgsgpsplugin.cpp +++ b/src/plugins/gps_importer/qgsgpsplugin.cpp @@ -53,7 +53,7 @@ static const QString description_ = QObject::tr( "Tools for loading and importin static const QString category_ = QObject::tr( "Vector" ); static const QString version_ = QObject::tr( "Version 0.1" ); static const QgisPlugin::PLUGINTYPE type_ = QgisPlugin::UI; -static const QString icon_ = ":/gps_importer.svg"; +static const QString icon_ = QStringLiteral( ":/gps_importer.svg" ); /** @@ -92,10 +92,10 @@ void QgsGPSPlugin::initGui() // add an action to the toolbar mQActionPointer = new QAction( QIcon(), tr( "&GPS Tools" ), this ); - mQActionPointer->setObjectName( "mQActionPointer" ); + mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); mCreateGPXAction = new QAction( QIcon(), tr( "&Create new GPX layer" ), this ); - mCreateGPXAction->setObjectName( "mCreateGPXAction" ); - setCurrentTheme( "" ); + mCreateGPXAction->setObjectName( QStringLiteral( "mCreateGPXAction" ) ); + setCurrentTheme( QLatin1String( "" ) ); mQActionPointer->setWhatsThis( tr( "Creates a new GPX layer and displays it on the map canvas" ) ); mCreateGPXAction->setWhatsThis( tr( "Creates a new GPX layer and displays it on the map canvas" ) ); @@ -131,7 +131,7 @@ void QgsGPSPlugin::run() if ( iter.value()->type() == QgsMapLayer::VectorLayer ) { QgsVectorLayer* vLayer = qobject_cast<QgsVectorLayer *>( iter.value() ); - if ( vLayer->providerType() == "gpx" ) + if ( vLayer->providerType() == QLatin1String( "gpx" ) ) gpxLayers.push_back( vLayer ); } } @@ -167,7 +167,7 @@ void QgsGPSPlugin::run() void QgsGPSPlugin::createGPX() { QSettings settings; - QString dir = settings.value( "/Plugin-GPS/gpxdirectory", QDir::homePath() ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QDir::homePath() ).toString(); QString fileName = QFileDialog::getSaveFileName( mQGisInterface->mainWindow(), tr( "Save new GPX file as..." ), @@ -175,9 +175,9 @@ void QgsGPSPlugin::createGPX() tr( "GPS eXchange file" ) + " (*.gpx)" ); if ( !fileName.isEmpty() ) { - if ( !fileName.endsWith( ".gpx", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".gpx" ), Qt::CaseInsensitive ) ) { - fileName += ".gpx"; + fileName += QLatin1String( ".gpx" ); } QFileInfo fileInfo( fileName ); std::ofstream ofs( fileName.toUtf8() ); @@ -189,16 +189,16 @@ void QgsGPSPlugin::createGPX() "directory." ) ); return; } - settings.setValue( "/Plugin-GPS/gpxdirectory", fileInfo.absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), fileInfo.absolutePath() ); ofs << "<gpx></gpx>" << std::endl; emit drawVectorLayer( fileName + "?type=track", - fileInfo.baseName() + ", tracks", "gpx" ); + fileInfo.baseName() + ", tracks", QStringLiteral( "gpx" ) ); emit drawVectorLayer( fileName + "?type=route", - fileInfo.baseName() + ", routes", "gpx" ); + fileInfo.baseName() + ", routes", QStringLiteral( "gpx" ) ); emit drawVectorLayer( fileName + "?type=waypoint", - fileInfo.baseName() + ", waypoints", "gpx" ); + fileInfo.baseName() + ", waypoints", QStringLiteral( "gpx" ) ); } } @@ -238,13 +238,13 @@ void QgsGPSPlugin::loadGPXFile( const QString& fileName, bool loadWaypoints, boo // add the requested layers if ( loadTracks ) emit drawVectorLayer( fileName + "?type=track", - fileInfo.baseName() + ", tracks", "gpx" ); + fileInfo.baseName() + ", tracks", QStringLiteral( "gpx" ) ); if ( loadRoutes ) emit drawVectorLayer( fileName + "?type=route", - fileInfo.baseName() + ", routes", "gpx" ); + fileInfo.baseName() + ", routes", QStringLiteral( "gpx" ) ); if ( loadWaypoints ) emit drawVectorLayer( fileName + "?type=waypoint", - fileInfo.baseName() + ", waypoints", "gpx" ); + fileInfo.baseName() + ", waypoints", QStringLiteral( "gpx" ) ); emit closeGui(); } @@ -257,11 +257,11 @@ void QgsGPSPlugin::importGPSFile( const QString& inputFileName, QgsBabelFormat* // what features does the user want to import? QString typeArg; if ( importWaypoints ) - typeArg = "-w"; + typeArg = QStringLiteral( "-w" ); else if ( importRoutes ) - typeArg = "-r"; + typeArg = QStringLiteral( "-r" ); else if ( importTracks ) - typeArg = "-t"; + typeArg = QStringLiteral( "-t" ); // try to start the gpsbabel process QStringList babelArgs = @@ -271,7 +271,7 @@ void QgsGPSPlugin::importGPSFile( const QString& inputFileName, QgsBabelFormat* QgsDebugMsg( QString( "Import command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; - babelProcess.start( babelArgs.join( " " ) ); + babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), @@ -305,13 +305,13 @@ void QgsGPSPlugin::importGPSFile( const QString& inputFileName, QgsBabelFormat* // add the layer if ( importTracks ) emit drawVectorLayer( outputFileName + "?type=track", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); if ( importRoutes ) emit drawVectorLayer( outputFileName + "?type=route", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); if ( importWaypoints ) emit drawVectorLayer( outputFileName + "?type=waypoint", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); emit closeGui(); } @@ -327,16 +327,16 @@ void QgsGPSPlugin::convertGPSFile( const QString& inputFileName, switch ( convertType ) { case 0: - convertStrings << "-x" << "transform,wpt=rte,del"; + convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,wpt=rte,del" ); break; case 1: - convertStrings << "-x" << "transform,rte=wpt,del"; + convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,rte=wpt,del" ); break; case 2: - convertStrings << "-x" << "transform,trk=wpt,del"; + convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,trk=wpt,del" ); break; case 3: - convertStrings << "-x" << "transform,wpt=trk,del"; + convertStrings << QStringLiteral( "-x" ) << QStringLiteral( "transform,wpt=trk,del" ); break; default: QgsDebugMsg( "Illegal conversion index!" ); @@ -345,12 +345,12 @@ void QgsGPSPlugin::convertGPSFile( const QString& inputFileName, // try to start the gpsbabel process QStringList babelArgs; - babelArgs << mBabelPath << "-i" << "gpx" << "-f" << QString( "\"%1\"" ).arg( inputFileName ) - << convertStrings << "-o" << "gpx" << "-F" << QString( "\"%1\"" ).arg( outputFileName ); + babelArgs << mBabelPath << QStringLiteral( "-i" ) << QStringLiteral( "gpx" ) << QStringLiteral( "-f" ) << QStringLiteral( "\"%1\"" ).arg( inputFileName ) + << convertStrings << QStringLiteral( "-o" ) << QStringLiteral( "gpx" ) << QStringLiteral( "-F" ) << QStringLiteral( "\"%1\"" ).arg( outputFileName ); QgsDebugMsg( QString( "Conversion command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; - babelProcess.start( babelArgs.join( " " ) ); + babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), @@ -385,15 +385,15 @@ void QgsGPSPlugin::convertGPSFile( const QString& inputFileName, case 0: case 3: emit drawVectorLayer( outputFileName + "?type=waypoint", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); break; case 1: emit drawVectorLayer( outputFileName + "?type=route", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); break; case 2: emit drawVectorLayer( outputFileName + "?type=track", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); break; default: QgsDebugMsg( "Illegal conversion index!" ); @@ -412,18 +412,18 @@ void QgsGPSPlugin::downloadFromGPS( const QString& device, const QString& port, QString typeArg, features; if ( downloadWaypoints ) { - typeArg = "-w"; - features = "waypoints"; + typeArg = QStringLiteral( "-w" ); + features = QStringLiteral( "waypoints" ); } else if ( downloadRoutes ) { - typeArg = "-r"; - features = "routes"; + typeArg = QStringLiteral( "-r" ); + features = QStringLiteral( "routes" ); } else if ( downloadTracks ) { - typeArg = "-t"; - features = "tracks"; + typeArg = QStringLiteral( "-t" ); + features = QStringLiteral( "tracks" ); } // try to start the gpsbabel process @@ -441,7 +441,7 @@ void QgsGPSPlugin::downloadFromGPS( const QString& device, const QString& port, QgsDebugMsg( QString( "Download command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; - babelProcess.start( babelArgs.join( " " ) ); + babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), @@ -472,18 +472,18 @@ void QgsGPSPlugin::downloadFromGPS( const QString& device, const QString& port, // add the layer if ( downloadWaypoints ) emit drawVectorLayer( outputFileName + "?type=waypoint", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); if ( downloadRoutes ) emit drawVectorLayer( outputFileName + "?type=route", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); if ( downloadTracks ) emit drawVectorLayer( outputFileName + "?type=track", - layerName, "gpx" ); + layerName, QStringLiteral( "gpx" ) ); // everything was OK, remember the device and port for next time QSettings settings; - settings.setValue( "/Plugin-GPS/lastdldevice", device ); - settings.setValue( "/Plugin-GPS/lastdlport", port ); + settings.setValue( QStringLiteral( "/Plugin-GPS/lastdldevice" ), device ); + settings.setValue( QStringLiteral( "/Plugin-GPS/lastdlport" ), port ); emit closeGui(); } @@ -495,20 +495,20 @@ void QgsGPSPlugin::uploadToGPS( QgsVectorLayer* gpxLayer, const QString& device, // what kind of data does the user want to upload? QString typeArg, features; - if ( source.right( 8 ) == "waypoint" ) + if ( source.right( 8 ) == QLatin1String( "waypoint" ) ) { - typeArg = "-w"; - features = "waypoints"; + typeArg = QStringLiteral( "-w" ); + features = QStringLiteral( "waypoints" ); } - else if ( source.right( 5 ) == "route" ) + else if ( source.right( 5 ) == QLatin1String( "route" ) ) { - typeArg = "-r"; - features = "routes"; + typeArg = QStringLiteral( "-r" ); + features = QStringLiteral( "routes" ); } - else if ( source.right( 5 ) == "track" ) + else if ( source.right( 5 ) == QLatin1String( "track" ) ) { - typeArg = "-t"; - features = "tracks"; + typeArg = QStringLiteral( "-t" ); + features = QStringLiteral( "tracks" ); } else { @@ -531,7 +531,7 @@ void QgsGPSPlugin::uploadToGPS( QgsVectorLayer* gpxLayer, const QString& device, QgsDebugMsg( QString( "Upload command: " ) + babelArgs.join( "|" ) ); QProcess babelProcess; - babelProcess.start( babelArgs.join( " " ) ); + babelProcess.start( babelArgs.join( QStringLiteral( " " ) ) ); if ( !babelProcess.waitForStarted() ) { QMessageBox::warning( nullptr, tr( "Could not start process" ), @@ -561,8 +561,8 @@ void QgsGPSPlugin::uploadToGPS( QgsVectorLayer* gpxLayer, const QString& device, // everything was OK, remember this device for next time QSettings settings; - settings.setValue( "/Plugin-GPS/lastuldevice", device ); - settings.setValue( "/Plugin-GPS/lastulport", port ); + settings.setValue( QStringLiteral( "/Plugin-GPS/lastuldevice" ), device ); + settings.setValue( QStringLiteral( "/Plugin-GPS/lastulport" ), port ); emit closeGui(); } @@ -571,80 +571,80 @@ void QgsGPSPlugin::setupBabel() { // where is gpsbabel? QSettings settings; - mBabelPath = settings.value( "/Plugin-GPS/gpsbabelpath", QString() ).toString(); + mBabelPath = settings.value( QStringLiteral( "/Plugin-GPS/gpsbabelpath" ), QString() ).toString(); if ( mBabelPath.isEmpty() ) - mBabelPath = "gpsbabel"; + mBabelPath = QStringLiteral( "gpsbabel" ); // the importable formats - mImporters["Shapefile"] = - new QgsSimpleBabelFormat( "shape", true, true, true ); - mImporters["Geocaching.com .loc"] = - new QgsSimpleBabelFormat( "geo", true, false, false ); - mImporters["Magellan Mapsend"] = - new QgsSimpleBabelFormat( "mapsend", true, true, true ); - mImporters["Garmin PCX5"] = - new QgsSimpleBabelFormat( "pcx", true, false, true ); - mImporters["Garmin Mapsource"] = - new QgsSimpleBabelFormat( "mapsource", true, true, true ); - mImporters["GPSUtil"] = - new QgsSimpleBabelFormat( "gpsutil", true, false, false ); - mImporters["PocketStreets 2002/2003 Pushpin"] = - new QgsSimpleBabelFormat( "psp", true, false, false ); - mImporters["CoPilot Flight Planner"] = - new QgsSimpleBabelFormat( "copilot", true, false, false ); - mImporters["Magellan Navigator Companion"] = - new QgsSimpleBabelFormat( "magnav", true, false, false ); - mImporters["Holux"] = - new QgsSimpleBabelFormat( "holux", true, false, false ); - mImporters["Topo by National Geographic"] = - new QgsSimpleBabelFormat( "tpg", true, false, false ); - mImporters["TopoMapPro"] = - new QgsSimpleBabelFormat( "tmpro", true, false, false ); - mImporters["GeocachingDB"] = - new QgsSimpleBabelFormat( "gcdb", true, false, false ); - mImporters["Tiger"] = - new QgsSimpleBabelFormat( "tiger", true, false, false ); - mImporters["EasyGPS Binary Format"] = - new QgsSimpleBabelFormat( "easygps", true, false, false ); - mImporters["Delorme Routes"] = - new QgsSimpleBabelFormat( "saroute", false, false, true ); - mImporters["Navicache"] = - new QgsSimpleBabelFormat( "navicache", true, false, false ); - mImporters["PSITrex"] = - new QgsSimpleBabelFormat( "psitrex", true, true, true ); - mImporters["Delorme GPS Log"] = - new QgsSimpleBabelFormat( "gpl", false, false, true ); - mImporters["OziExplorer"] = - new QgsSimpleBabelFormat( "ozi", true, false, false ); - mImporters["NMEA Sentences"] = - new QgsSimpleBabelFormat( "nmea", true, false, true ); - mImporters["Delorme Street Atlas 2004 Plus"] = - new QgsSimpleBabelFormat( "saplus", true, false, false ); - mImporters["Microsoft Streets and Trips"] = - new QgsSimpleBabelFormat( "s_and_t", true, false, false ); - mImporters["NIMA/GNIS Geographic Names"] = - new QgsSimpleBabelFormat( "nima", true, false, false ); - mImporters["Maptech"] = - new QgsSimpleBabelFormat( "mxf", true, false, false ); - mImporters["Mapopolis.com Mapconverter Application"] = - new QgsSimpleBabelFormat( "mapconverter", true, false, false ); - mImporters["GPSman"] = - new QgsSimpleBabelFormat( "gpsman", true, false, false ); - mImporters["GPSDrive"] = - new QgsSimpleBabelFormat( "gpsdrive", true, false, false ); - mImporters["Fugawi"] = - new QgsSimpleBabelFormat( "fugawi", true, false, false ); - mImporters["DNA"] = - new QgsSimpleBabelFormat( "dna", true, false, false ); + mImporters[QStringLiteral( "Shapefile" )] = + new QgsSimpleBabelFormat( QStringLiteral( "shape" ), true, true, true ); + mImporters[QStringLiteral( "Geocaching.com .loc" )] = + new QgsSimpleBabelFormat( QStringLiteral( "geo" ), true, false, false ); + mImporters[QStringLiteral( "Magellan Mapsend" )] = + new QgsSimpleBabelFormat( QStringLiteral( "mapsend" ), true, true, true ); + mImporters[QStringLiteral( "Garmin PCX5" )] = + new QgsSimpleBabelFormat( QStringLiteral( "pcx" ), true, false, true ); + mImporters[QStringLiteral( "Garmin Mapsource" )] = + new QgsSimpleBabelFormat( QStringLiteral( "mapsource" ), true, true, true ); + mImporters[QStringLiteral( "GPSUtil" )] = + new QgsSimpleBabelFormat( QStringLiteral( "gpsutil" ), true, false, false ); + mImporters[QStringLiteral( "PocketStreets 2002/2003 Pushpin" )] = + new QgsSimpleBabelFormat( QStringLiteral( "psp" ), true, false, false ); + mImporters[QStringLiteral( "CoPilot Flight Planner" )] = + new QgsSimpleBabelFormat( QStringLiteral( "copilot" ), true, false, false ); + mImporters[QStringLiteral( "Magellan Navigator Companion" )] = + new QgsSimpleBabelFormat( QStringLiteral( "magnav" ), true, false, false ); + mImporters[QStringLiteral( "Holux" )] = + new QgsSimpleBabelFormat( QStringLiteral( "holux" ), true, false, false ); + mImporters[QStringLiteral( "Topo by National Geographic" )] = + new QgsSimpleBabelFormat( QStringLiteral( "tpg" ), true, false, false ); + mImporters[QStringLiteral( "TopoMapPro" )] = + new QgsSimpleBabelFormat( QStringLiteral( "tmpro" ), true, false, false ); + mImporters[QStringLiteral( "GeocachingDB" )] = + new QgsSimpleBabelFormat( QStringLiteral( "gcdb" ), true, false, false ); + mImporters[QStringLiteral( "Tiger" )] = + new QgsSimpleBabelFormat( QStringLiteral( "tiger" ), true, false, false ); + mImporters[QStringLiteral( "EasyGPS Binary Format" )] = + new QgsSimpleBabelFormat( QStringLiteral( "easygps" ), true, false, false ); + mImporters[QStringLiteral( "Delorme Routes" )] = + new QgsSimpleBabelFormat( QStringLiteral( "saroute" ), false, false, true ); + mImporters[QStringLiteral( "Navicache" )] = + new QgsSimpleBabelFormat( QStringLiteral( "navicache" ), true, false, false ); + mImporters[QStringLiteral( "PSITrex" )] = + new QgsSimpleBabelFormat( QStringLiteral( "psitrex" ), true, true, true ); + mImporters[QStringLiteral( "Delorme GPS Log" )] = + new QgsSimpleBabelFormat( QStringLiteral( "gpl" ), false, false, true ); + mImporters[QStringLiteral( "OziExplorer" )] = + new QgsSimpleBabelFormat( QStringLiteral( "ozi" ), true, false, false ); + mImporters[QStringLiteral( "NMEA Sentences" )] = + new QgsSimpleBabelFormat( QStringLiteral( "nmea" ), true, false, true ); + mImporters[QStringLiteral( "Delorme Street Atlas 2004 Plus" )] = + new QgsSimpleBabelFormat( QStringLiteral( "saplus" ), true, false, false ); + mImporters[QStringLiteral( "Microsoft Streets and Trips" )] = + new QgsSimpleBabelFormat( QStringLiteral( "s_and_t" ), true, false, false ); + mImporters[QStringLiteral( "NIMA/GNIS Geographic Names" )] = + new QgsSimpleBabelFormat( QStringLiteral( "nima" ), true, false, false ); + mImporters[QStringLiteral( "Maptech" )] = + new QgsSimpleBabelFormat( QStringLiteral( "mxf" ), true, false, false ); + mImporters[QStringLiteral( "Mapopolis.com Mapconverter Application" )] = + new QgsSimpleBabelFormat( QStringLiteral( "mapconverter" ), true, false, false ); + mImporters[QStringLiteral( "GPSman" )] = + new QgsSimpleBabelFormat( QStringLiteral( "gpsman" ), true, false, false ); + mImporters[QStringLiteral( "GPSDrive" )] = + new QgsSimpleBabelFormat( QStringLiteral( "gpsdrive" ), true, false, false ); + mImporters[QStringLiteral( "Fugawi" )] = + new QgsSimpleBabelFormat( QStringLiteral( "fugawi" ), true, false, false ); + mImporters[QStringLiteral( "DNA" )] = + new QgsSimpleBabelFormat( QStringLiteral( "dna" ), true, false, false ); // and the GPS devices - mDevices["Garmin serial"] = - new QgsGPSDevice( "%babel -w -i garmin -o gpx %in %out", - "%babel -w -i gpx -o garmin %in %out", - "%babel -r -i garmin -o gpx %in %out", - "%babel -r -i gpx -o garmin %in %out", - "%babel -t -i garmin -o gpx %in %out", - "%babel -t -i gpx -o garmin %in %out" ); - QStringList deviceNames = settings.value( "/Plugin-GPS/devicelist" ). + mDevices[QStringLiteral( "Garmin serial" )] = + new QgsGPSDevice( QStringLiteral( "%babel -w -i garmin -o gpx %in %out" ), + QStringLiteral( "%babel -w -i gpx -o garmin %in %out" ), + QStringLiteral( "%babel -r -i garmin -o gpx %in %out" ), + QStringLiteral( "%babel -r -i gpx -o garmin %in %out" ), + QStringLiteral( "%babel -t -i garmin -o gpx %in %out" ), + QStringLiteral( "%babel -t -i gpx -o garmin %in %out" ) ); + QStringList deviceNames = settings.value( QStringLiteral( "/Plugin-GPS/devicelist" ) ). toStringList(); QStringList::const_iterator iter; @@ -652,22 +652,22 @@ void QgsGPSPlugin::setupBabel() for ( iter = deviceNames.begin(); iter != deviceNames.end(); ++iter ) { QString wptDownload = settings. - value( QString( "/Plugin-GPS/devices/%1/wptdownload" ). + value( QStringLiteral( "/Plugin-GPS/devices/%1/wptdownload" ). arg( *iter ), "" ).toString(); QString wptUpload = settings. - value( QString( "/Plugin-GPS/devices/%1/wptupload" ).arg( *iter ), "" ). + value( QStringLiteral( "/Plugin-GPS/devices/%1/wptupload" ).arg( *iter ), "" ). toString(); QString rteDownload = settings. - value( QString( "/Plugin-GPS/devices/%1/rtedownload" ).arg( *iter ), "" ). + value( QStringLiteral( "/Plugin-GPS/devices/%1/rtedownload" ).arg( *iter ), "" ). toString(); QString rteUpload = settings. - value( QString( "/Plugin-GPS/devices/%1/rteupload" ).arg( *iter ), "" ). + value( QStringLiteral( "/Plugin-GPS/devices/%1/rteupload" ).arg( *iter ), "" ). toString(); QString trkDownload = settings. - value( QString( "/Plugin-GPS/devices/%1/trkdownload" ).arg( *iter ), "" ). + value( QStringLiteral( "/Plugin-GPS/devices/%1/trkdownload" ).arg( *iter ), "" ). toString(); QString trkUpload = settings. - value( QString( "/Plugin-GPS/devices/%1/trkupload" ).arg( *iter ), "" ). + value( QStringLiteral( "/Plugin-GPS/devices/%1/trkupload" ).arg( *iter ), "" ). toString(); mDevices[*iter] = new QgsGPSDevice( wptDownload, wptUpload, rteDownload, rteUpload, @@ -681,7 +681,7 @@ void QgsGPSPlugin::setCurrentTheme( const QString& theThemeName ) Q_UNUSED( theThemeName ); QString myCurThemePath = QgsApplication::activeThemePath() + "/plugins/gps_importer/"; QString myDefThemePath = QgsApplication::defaultThemePath() + "/plugins/gps_importer/"; - QString myQrcPath = ":/"; + QString myQrcPath = QStringLiteral( ":/" ); if ( mQActionPointer ) { if ( QFile::exists( myCurThemePath ) ) diff --git a/src/plugins/gps_importer/qgsgpsplugingui.cpp b/src/plugins/gps_importer/qgsgpsplugingui.cpp index c99f91fe385d..40fcaa6f7f01 100644 --- a/src/plugins/gps_importer/qgsgpsplugingui.cpp +++ b/src/plugins/gps_importer/qgsgpsplugingui.cpp @@ -75,14 +75,14 @@ QgsGPSPluginGui::QgsGPSPluginGui( const BabelMap& importers, this, SLOT( enableRelevantControls() ) ); // drag and drop filter - leGPXFile->setSuffixFilter( "gpx" ); + leGPXFile->setSuffixFilter( QStringLiteral( "gpx" ) ); } QgsGPSPluginGui::~QgsGPSPluginGui() { QSettings settings; - settings.setValue( "/Plugin-GPS/geometry", saveGeometry() ); - settings.setValue( "/Plugin-GPS/lastTab", tabWidget->currentIndex() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/lastTab" ), tabWidget->currentIndex() ); } void QgsGPSPluginGui::on_buttonBox_accepted() @@ -116,9 +116,9 @@ void QgsGPSPluginGui::on_buttonBox_accepted() int featureType = cmbDLFeatureType->currentIndex(); QString fileName = leDLOutput->text(); - if ( !fileName.endsWith( ".gpx", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".gpx" ), Qt::CaseInsensitive ) ) { - fileName += ".gpx"; + fileName += QLatin1String( ".gpx" ); } emit downloadFromGPS( cmbDLDevice->currentText(), @@ -158,7 +158,7 @@ void QgsGPSPluginGui::on_buttonBox_accepted() void QgsGPSPluginGui::on_pbnDLOutput_clicked() { QSettings settings; - QString dir = settings.value( "/Plugin-GPS/gpxdirectory", QDir::homePath() ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QDir::homePath() ).toString(); QString myFileNameQString = QFileDialog::getSaveFileName( this, tr( "Choose a file name to save under" ), @@ -166,12 +166,12 @@ void QgsGPSPluginGui::on_pbnDLOutput_clicked() tr( "GPS eXchange format" ) + " (*.gpx)" ); if ( !myFileNameQString.isEmpty() ) { - if ( !myFileNameQString.endsWith( ".gpx", Qt::CaseInsensitive ) ) + if ( !myFileNameQString.endsWith( QLatin1String( ".gpx" ), Qt::CaseInsensitive ) ) { - myFileNameQString += ".gpx"; + myFileNameQString += QLatin1String( ".gpx" ); } leDLOutput->setText( myFileNameQString ); - settings.setValue( "/Plugin-GPS/gpxdirectory", QFileInfo( myFileNameQString ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QFileInfo( myFileNameQString ).absolutePath() ); } } @@ -180,7 +180,7 @@ void QgsGPSPluginGui::enableRelevantControls() // load GPX if ( tabWidget->currentIndex() == 0 ) { - if (( leGPXFile->text() == "" ) ) + if (( leGPXFile->text() == QLatin1String( "" ) ) ) { pbnOK->setEnabled( false ); cbGPXWaypoints->setEnabled( false ); @@ -205,8 +205,8 @@ void QgsGPSPluginGui::enableRelevantControls() // import other file else if ( tabWidget->currentIndex() == 1 ) { - if (( leIMPInput->text() == "" ) || ( leIMPOutput->text() == "" ) || - ( leIMPLayer->text() == "" ) ) + if (( leIMPInput->text() == QLatin1String( "" ) ) || ( leIMPOutput->text() == QLatin1String( "" ) ) || + ( leIMPLayer->text() == QLatin1String( "" ) ) ) pbnOK->setEnabled( false ); else pbnOK->setEnabled( true ); @@ -215,8 +215,8 @@ void QgsGPSPluginGui::enableRelevantControls() // download from device else if ( tabWidget->currentIndex() == 2 ) { - if ( cmbDLDevice->currentText() == "" || leDLBasename->text() == "" || - leDLOutput->text() == "" ) + if ( cmbDLDevice->currentText() == QLatin1String( "" ) || leDLBasename->text() == QLatin1String( "" ) || + leDLOutput->text() == QLatin1String( "" ) ) pbnOK->setEnabled( false ); else pbnOK->setEnabled( true ); @@ -225,7 +225,7 @@ void QgsGPSPluginGui::enableRelevantControls() // upload to device else if ( tabWidget->currentIndex() == 3 ) { - if ( cmbULDevice->currentText() == "" || cmbULLayer->currentText() == "" ) + if ( cmbULDevice->currentText() == QLatin1String( "" ) || cmbULLayer->currentText() == QLatin1String( "" ) ) pbnOK->setEnabled( false ); else pbnOK->setEnabled( true ); @@ -234,8 +234,8 @@ void QgsGPSPluginGui::enableRelevantControls() // convert between waypoint/routes else if ( tabWidget->currentIndex() == 4 ) { - if (( leCONVInput->text() == "" ) || ( leCONVOutput->text() == "" ) || - ( leCONVLayer->text() == "" ) ) + if (( leCONVInput->text() == QLatin1String( "" ) ) || ( leCONVOutput->text() == QLatin1String( "" ) ) || + ( leCONVLayer->text() == QLatin1String( "" ) ) ) pbnOK->setEnabled( false ); else pbnOK->setEnabled( true ); @@ -249,9 +249,9 @@ void QgsGPSPluginGui::on_buttonBox_rejected() void QgsGPSPluginGui::on_pbnGPXSelectFile_clicked() { - QgsLogger::debug( " GPS File Importer::pbnGPXSelectFile_clicked() " ); + QgsLogger::debug( QStringLiteral( " GPS File Importer::pbnGPXSelectFile_clicked() " ) ); QSettings settings; - QString dir = settings.value( "/Plugin-GPS/gpxdirectory", QDir::homePath() ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QDir::homePath() ).toString(); QString myFileNameQString = QFileDialog::getOpenFileName( this, tr( "Select GPX file" ), @@ -260,16 +260,16 @@ void QgsGPSPluginGui::on_pbnGPXSelectFile_clicked() if ( !myFileNameQString.isEmpty() ) { leGPXFile->setText( myFileNameQString ); - settings.setValue( "/Plugin-GPS/gpxdirectory", QFileInfo( myFileNameQString ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QFileInfo( myFileNameQString ).absolutePath() ); } } void QgsGPSPluginGui::on_pbnIMPInput_clicked() { QSettings settings; - QString dir = settings.value( "/Plugin-GPS/importdirectory", QDir::homePath() ).toString(); - QString tf = mBabelFilter.split( ";;" ).first(); - QString myFileType = settings.value( "/Plugin-GPS/lastImportFilter", tf ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/importdirectory" ), QDir::homePath() ).toString(); + QString tf = mBabelFilter.split( QStringLiteral( ";;" ) ).first(); + QString myFileType = settings.value( QStringLiteral( "/Plugin-GPS/lastImportFilter" ), tf ).toString(); QString myFileName = QFileDialog::getOpenFileName( this, tr( "Select file and format to import" ), @@ -279,8 +279,8 @@ void QgsGPSPluginGui::on_pbnIMPInput_clicked() if ( !myFileName.isEmpty() ) { // save directory and file type - settings.setValue( "/Plugin-GPS/importdirectory", QFileInfo( myFileName ).absolutePath() ); - settings.setValue( "/Plugin-GPS/lastImportFilter", myFileType ); + settings.setValue( QStringLiteral( "/Plugin-GPS/importdirectory" ), QFileInfo( myFileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/lastImportFilter" ), myFileType ); mImpFormat = myFileType.left( myFileType.length() - 6 ); std::map<QString, QgsBabelFormat*>::const_iterator iter; @@ -308,7 +308,7 @@ void QgsGPSPluginGui::on_pbnIMPInput_clicked() void QgsGPSPluginGui::on_pbnIMPOutput_clicked() { QSettings settings; - QString dir = settings.value( "/Plugin-GPS/gpxdirectory", QDir::homePath() ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QDir::homePath() ).toString(); QString myFileNameQString = QFileDialog::getSaveFileName( this, tr( "Choose a file name to save under" ), @@ -316,12 +316,12 @@ void QgsGPSPluginGui::on_pbnIMPOutput_clicked() tr( "GPS eXchange format" ) + " (*.gpx)" ); if ( !myFileNameQString.isEmpty() ) { - if ( !myFileNameQString.endsWith( ".gpx", Qt::CaseInsensitive ) ) + if ( !myFileNameQString.endsWith( QLatin1String( ".gpx" ), Qt::CaseInsensitive ) ) { - myFileNameQString += ".gpx"; + myFileNameQString += QLatin1String( ".gpx" ); } leIMPOutput->setText( myFileNameQString ); - settings.setValue( "/Plugin-GPS/gpxdirectory", QFileInfo( myFileNameQString ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QFileInfo( myFileNameQString ).absolutePath() ); } } @@ -332,7 +332,7 @@ void QgsGPSPluginGui::on_pbnRefresh_clicked() void QgsGPSPluginGui::populatePortComboBoxes() { - QList< QPair<QString, QString> > devs = QgsGPSDetector::availablePorts() << QPair<QString, QString>( "usb:", "usb:" ); + QList< QPair<QString, QString> > devs = QgsGPSDetector::availablePorts() << QPair<QString, QString>( QStringLiteral( "usb:" ), QStringLiteral( "usb:" ) ); cmbDLPort->clear(); cmbULPort->clear(); @@ -344,8 +344,8 @@ void QgsGPSPluginGui::populatePortComboBoxes() // remember the last ports used QSettings settings; - QString lastDLPort = settings.value( "/Plugin-GPS/lastdlport", "" ).toString(); - QString lastULPort = settings.value( "/Plugin-GPS/lastulport", "" ).toString(); + QString lastDLPort = settings.value( QStringLiteral( "/Plugin-GPS/lastdlport" ), "" ).toString(); + QString lastULPort = settings.value( QStringLiteral( "/Plugin-GPS/lastulport" ), "" ).toString(); int idx = cmbDLPort->findData( lastDLPort ); cmbDLPort->setCurrentIndex( idx < 0 ? 0 : idx ); @@ -369,12 +369,12 @@ void QgsGPSPluginGui::populateULLayerComboBox() void QgsGPSPluginGui::populateIMPBabelFormats() { - mBabelFilter = ""; + mBabelFilter = QLatin1String( "" ); cmbULDevice->clear(); cmbDLDevice->clear(); QSettings settings; - QString lastDLDevice = settings.value( "/Plugin-GPS/lastdldevice", "" ).toString(); - QString lastULDevice = settings.value( "/Plugin-GPS/lastuldevice", "" ).toString(); + QString lastDLDevice = settings.value( QStringLiteral( "/Plugin-GPS/lastdldevice" ), "" ).toString(); + QString lastULDevice = settings.value( QStringLiteral( "/Plugin-GPS/lastuldevice" ), "" ).toString(); BabelMap::const_iterator iter; for ( iter = mImporters.begin(); iter != mImporters.end(); ++iter ) mBabelFilter.append( iter->first ).append( " (*.*);;" ); @@ -399,7 +399,7 @@ void QgsGPSPluginGui::populateIMPBabelFormats() void QgsGPSPluginGui::on_pbnCONVInput_clicked() { QSettings settings; - QString dir = settings.value( "/Plugin-GPS/gpxdirectory", QDir::homePath() ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QDir::homePath() ).toString(); QString myFileNameQString = QFileDialog::getOpenFileName( this, tr( "Select GPX file" ), @@ -408,14 +408,14 @@ void QgsGPSPluginGui::on_pbnCONVInput_clicked() if ( !myFileNameQString.isEmpty() ) { leCONVInput->setText( myFileNameQString ); - settings.setValue( "/Plugin-GPS/gpxdirectory", QFileInfo( myFileNameQString ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QFileInfo( myFileNameQString ).absolutePath() ); } } void QgsGPSPluginGui::on_pbnCONVOutput_clicked() { QSettings settings; - QString dir = settings.value( "/Plugin-GPS/gpxdirectory", QDir::homePath() ).toString(); + QString dir = settings.value( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QDir::homePath() ).toString(); QString myFileNameQString = QFileDialog::getSaveFileName( this, tr( "Choose a file name to save under" ), @@ -423,12 +423,12 @@ void QgsGPSPluginGui::on_pbnCONVOutput_clicked() tr( "GPS eXchange format" ) + " (*.gpx)" ); if ( !myFileNameQString.isEmpty() ) { - if ( !myFileNameQString.endsWith( ".gpx", Qt::CaseInsensitive ) ) + if ( !myFileNameQString.endsWith( QLatin1String( ".gpx" ), Qt::CaseInsensitive ) ) { - myFileNameQString += ".gpx"; + myFileNameQString += QLatin1String( ".gpx" ); } leCONVOutput->setText( myFileNameQString ); - settings.setValue( "/Plugin-GPS/gpxdirectory", QFileInfo( myFileNameQString ).absolutePath() ); + settings.setValue( QStringLiteral( "/Plugin-GPS/gpxdirectory" ), QFileInfo( myFileNameQString ).absolutePath() ); } } @@ -447,6 +447,6 @@ void QgsGPSPluginGui::devicesUpdated() void QgsGPSPluginGui::restoreState() { QSettings settings; - restoreGeometry( settings.value( "/Plugin-GPS/geometry" ).toByteArray() ); - tabWidget->setCurrentIndex( settings.value( "/Plugin-GPS/lastTab", 4 ).toInt() ); + restoreGeometry( settings.value( QStringLiteral( "/Plugin-GPS/geometry" ) ).toByteArray() ); + tabWidget->setCurrentIndex( settings.value( QStringLiteral( "/Plugin-GPS/lastTab" ), 4 ).toInt() ); } diff --git a/src/plugins/grass/qgsgrasseditrenderer.cpp b/src/plugins/grass/qgsgrasseditrenderer.cpp index dc7cc139402d..96e845f41238 100644 --- a/src/plugins/grass/qgsgrasseditrenderer.cpp +++ b/src/plugins/grass/qgsgrasseditrenderer.cpp @@ -31,7 +31,7 @@ #include "qgsgrassprovider.h" QgsGrassEditRenderer::QgsGrassEditRenderer() - : QgsFeatureRenderer( "grassEdit" ) + : QgsFeatureRenderer( QStringLiteral( "grassEdit" ) ) , mLineRenderer( 0 ) , mMarkerRenderer( 0 ) { @@ -45,11 +45,11 @@ QgsGrassEditRenderer::QgsGrassEditRenderer() QHash<int, QString> labels; //labels.insert( QgsGrassVectorMap::TopoUndefined, "Unknown type" ); - labels.insert( QgsGrassVectorMap::TopoLine, "Line" ); - labels.insert( QgsGrassVectorMap::TopoBoundaryError, "Boundary (topological error on both sides)" ); - labels.insert( QgsGrassVectorMap::TopoBoundaryErrorLeft, "Boundary (topological error on the left side)" ); - labels.insert( QgsGrassVectorMap::TopoBoundaryErrorRight, "Boundary (topological error on the right side)" ); - labels.insert( QgsGrassVectorMap::TopoBoundaryOk, "Boundary (correct)" ); + labels.insert( QgsGrassVectorMap::TopoLine, QStringLiteral( "Line" ) ); + labels.insert( QgsGrassVectorMap::TopoBoundaryError, QStringLiteral( "Boundary (topological error on both sides)" ) ); + labels.insert( QgsGrassVectorMap::TopoBoundaryErrorLeft, QStringLiteral( "Boundary (topological error on the left side)" ) ); + labels.insert( QgsGrassVectorMap::TopoBoundaryErrorRight, QStringLiteral( "Boundary (topological error on the right side)" ) ); + labels.insert( QgsGrassVectorMap::TopoBoundaryOk, QStringLiteral( "Boundary (correct)" ) ); QgsCategoryList categoryList; @@ -76,7 +76,7 @@ QgsGrassEditRenderer::QgsGrassEditRenderer() } delete firstVertexMarkerLine; delete lastVertexMarkerLine; - mLineRenderer = new QgsCategorizedSymbolRenderer( "topo_symbol", categoryList ); + mLineRenderer = new QgsCategorizedSymbolRenderer( QStringLiteral( "topo_symbol" ), categoryList ); colors.clear(); labels.clear(); @@ -86,10 +86,10 @@ QgsGrassEditRenderer::QgsGrassEditRenderer() colors.insert( QgsGrassVectorMap::TopoCentroidOut, QColor( 255, 0, 0 ) ); colors.insert( QgsGrassVectorMap::TopoCentroidDupl, QColor( 255, 0, 255 ) ); - labels.insert( QgsGrassVectorMap::TopoPoint, "Point" ); - labels.insert( QgsGrassVectorMap::TopoCentroidIn, "Centroid in area" ); - labels.insert( QgsGrassVectorMap::TopoCentroidOut, "Centroid outside area" ); - labels.insert( QgsGrassVectorMap::TopoCentroidDupl, "Duplicate centroid" ); + labels.insert( QgsGrassVectorMap::TopoPoint, QStringLiteral( "Point" ) ); + labels.insert( QgsGrassVectorMap::TopoCentroidIn, QStringLiteral( "Centroid in area" ) ); + labels.insert( QgsGrassVectorMap::TopoCentroidOut, QStringLiteral( "Centroid outside area" ) ); + labels.insert( QgsGrassVectorMap::TopoCentroidDupl, QStringLiteral( "Duplicate centroid" ) ); categoryList.clear(); @@ -100,7 +100,7 @@ QgsGrassEditRenderer::QgsGrassEditRenderer() categoryList << QgsRendererCategory( QVariant( value ), symbol, labels.value( value ) ); } - mMarkerRenderer = new QgsCategorizedSymbolRenderer( "topo_symbol", categoryList ); + mMarkerRenderer = new QgsCategorizedSymbolRenderer( QStringLiteral( "topo_symbol" ), categoryList ); } QgsGrassEditRenderer::~QgsGrassEditRenderer() @@ -122,7 +122,7 @@ void QgsGrassEditRenderer::setMarkerRenderer( QgsFeatureRenderer *renderer ) QgsSymbol* QgsGrassEditRenderer::symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) { - int symbolCode = feature.attribute( "topo_symbol" ).toInt(); + int symbolCode = feature.attribute( QStringLiteral( "topo_symbol" ) ).toInt(); QgsDebugMsgLevel( QString( "fid = %1 symbolCode = %2" ).arg( feature.id() ).arg( symbolCode ), 3 ); QgsSymbol* symbol = 0; @@ -199,19 +199,19 @@ QgsSymbolList QgsGrassEditRenderer::symbols( QgsRenderContext& context ) QString QgsGrassEditRenderer::dump() const { - return "GRASS edit renderer"; + return QStringLiteral( "GRASS edit renderer" ); } QDomElement QgsGrassEditRenderer::save( QDomDocument& doc ) { QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME ); - rendererElem.setAttribute( "type", "grassEdit" ); + rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "grassEdit" ) ); - QDomElement lineElem = doc.createElement( "line" ); + QDomElement lineElem = doc.createElement( QStringLiteral( "line" ) ); rendererElem.appendChild( lineElem ); lineElem.appendChild( mLineRenderer->save( doc ) ); - QDomElement pointElem = doc.createElement( "marker" ); + QDomElement pointElem = doc.createElement( QStringLiteral( "marker" ) ); rendererElem.appendChild( pointElem ); pointElem.appendChild( mMarkerRenderer->save( doc ) ); @@ -229,7 +229,7 @@ QgsFeatureRenderer* QgsGrassEditRenderer::create( QDomElement& element ) QDomElement elem = childElem.firstChildElement(); if ( !elem.isNull() ) { - QString rendererType = elem.attribute( "type" ); + QString rendererType = elem.attribute( QStringLiteral( "type" ) ); QgsDebugMsg( "childElem.tagName() = " + childElem.tagName() + " rendererType = " + rendererType ); QgsRendererAbstractMetadata* meta = QgsRendererRegistry::instance()->rendererMetadata( rendererType ); if ( meta ) @@ -238,11 +238,11 @@ QgsFeatureRenderer* QgsGrassEditRenderer::create( QDomElement& element ) if ( subRenderer ) { QgsDebugMsg( "renderer created : " + renderer->type() ); - if ( childElem.tagName() == "line" ) + if ( childElem.tagName() == QLatin1String( "line" ) ) { renderer->setLineRenderer( subRenderer ); } - else if ( childElem.tagName() == "marker" ) + else if ( childElem.tagName() == QLatin1String( "marker" ) ) { renderer->setMarkerRenderer( subRenderer ); } diff --git a/src/plugins/grass/qgsgrassmapcalc.cpp b/src/plugins/grass/qgsgrassmapcalc.cpp index 785ada0ef968..13c420fe0edc 100644 --- a/src/plugins/grass/qgsgrassmapcalc.cpp +++ b/src/plugins/grass/qgsgrassmapcalc.cpp @@ -79,42 +79,42 @@ QgsGrassMapcalc::QgsGrassMapcalc( QActionGroup *ag = new QActionGroup( this ); QToolBar *tb = addToolBar( tr( "Mapcalc tools" ) ); - mActionAddMap = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_add_map.png" ), + mActionAddMap = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_add_map.png" ) ), tr( "Add map" ), this ); mActionAddMap->setCheckable( true ); ag->addAction( mActionAddMap ); tb->addAction( mActionAddMap ); connect( mActionAddMap, SIGNAL( triggered() ), this, SLOT( addMap() ) ); - mActionAddConstant = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_add_constant.png" ), + mActionAddConstant = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_add_constant.png" ) ), tr( "Add constant value" ), this ); mActionAddConstant->setCheckable( true ); ag->addAction( mActionAddConstant ); tb->addAction( mActionAddConstant ); connect( mActionAddConstant, SIGNAL( triggered() ), this, SLOT( addConstant() ) ); - mActionAddFunction = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_add_function.png" ), + mActionAddFunction = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_add_function.png" ) ), tr( "Add operator or function" ), this ); mActionAddFunction->setCheckable( true ); ag->addAction( mActionAddFunction ); tb->addAction( mActionAddFunction ); connect( mActionAddFunction, SIGNAL( triggered() ), this, SLOT( addFunction() ) ); - mActionAddConnection = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_add_connection.png" ), + mActionAddConnection = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_add_connection.png" ) ), tr( "Add connection" ), this ); mActionAddConnection->setCheckable( true ); ag->addAction( mActionAddConnection ); tb->addAction( mActionAddConnection ); connect( mActionAddConnection, SIGNAL( triggered() ), this, SLOT( addConnection() ) ); - mActionSelectItem = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_select.png" ), + mActionSelectItem = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_select.png" ) ), tr( "Select item" ), this ); mActionSelectItem->setCheckable( true ); ag->addAction( mActionSelectItem ); tb->addAction( mActionSelectItem ); connect( mActionSelectItem, SIGNAL( triggered() ), this, SLOT( selectItem() ) ); - mActionDeleteItem = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_delete.png" ), + mActionDeleteItem = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_delete.png" ) ), tr( "Delete selected item" ), this ); mActionDeleteItem->setCheckable( true ); mActionDeleteItem->setEnabled( false ); @@ -124,18 +124,18 @@ QgsGrassMapcalc::QgsGrassMapcalc( mActionAddMap->setChecked( true ); - mActionLoad = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_open.png" ), + mActionLoad = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_open.png" ) ), tr( "Open" ), this ); tb->addAction( mActionLoad ); connect( mActionLoad, SIGNAL( triggered() ), this, SLOT( load() ) ); - mActionSave = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_save.png" ), + mActionSave = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_save.png" ) ), tr( "Save" ), this ); tb->addAction( mActionSave ); connect( mActionSave, SIGNAL( triggered() ), this, SLOT( save() ) ); mActionSave->setEnabled( false ); - mActionSaveAs = new QAction( QgsGrassPlugin::getThemeIcon( "mapcalc_save_as.png" ), + mActionSaveAs = new QAction( QgsGrassPlugin::getThemeIcon( QStringLiteral( "mapcalc_save_as.png" ) ), tr( "Save as" ), this ); tb->addAction( mActionSaveAs ); connect( mActionSaveAs, SIGNAL( triggered() ), this, SLOT( saveAs() ) ); @@ -154,61 +154,61 @@ QgsGrassMapcalc::QgsGrassMapcalc( /* Create functions */ int t = QgsGrassMapcalcFunction::Operator; // Arithmetical - mFunctions.push_back( QgsGrassMapcalcFunction( t, "+", 2, tr( "Addition" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "-", 2, tr( "Subtraction" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "*", 2, tr( "Multiplication" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "/", 2, tr( "Division" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "%", 2, tr( "Modulus" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "^", 2, tr( "Exponentiation" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "+" ), 2, tr( "Addition" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "-" ), 2, tr( "Subtraction" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "*" ), 2, tr( "Multiplication" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "/" ), 2, tr( "Division" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "%" ), 2, tr( "Modulus" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "^" ), 2, tr( "Exponentiation" ) ) ); // Logical - mFunctions.push_back( QgsGrassMapcalcFunction( t, "==", 2, tr( "Equal" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "!=", 2, tr( "Not equal" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, ">", 2, tr( "Greater than" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, ">=", 2, tr( "Greater than or equal" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "<", 2, tr( "Less than" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "<=", 2, tr( "Less than or equal" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "&&", 2, tr( "And" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "||", 2, tr( "Or" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "==" ), 2, tr( "Equal" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "!=" ), 2, tr( "Not equal" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( ">" ), 2, tr( "Greater than" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( ">=" ), 2, tr( "Greater than or equal" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "<" ), 2, tr( "Less than" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "<=" ), 2, tr( "Less than or equal" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "&&" ), 2, tr( "And" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "||" ), 2, tr( "Or" ) ) ); t = QgsGrassMapcalcFunction::Function; - mFunctions.push_back( QgsGrassMapcalcFunction( t, "abs", 1, tr( "Absolute value of x" ), "abs(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "atan", 1, tr( "Inverse tangent of x (result is in degrees)" ), "atan(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "atan", 2, tr( "Inverse tangent of y/x (result is in degrees)" ), "atan(x,y)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "col", 0, tr( "Current column of moving window (starts with 1)" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "cos", 1, tr( "Cosine of x (x is in degrees)" ), "cos(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "double", 1, tr( "Convert x to double-precision floating point" ), "double(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "ewres", 0, tr( "Current east-west resolution" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "exp", 1, tr( "Exponential function of x" ), "exp(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "exp", 2, tr( "x to the power y" ), "exp(x,y)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "float", 1, tr( "Convert x to single-precision floating point" ), "float(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "if", 1, tr( "Decision: 1 if x not zero, 0 otherwise" ), "if(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "if", 2, tr( "Decision: a if x not zero, 0 otherwise" ), "if(x,a)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "if", 3, tr( "Decision: a if x not zero, b otherwise" ), "if(x,a,b)", "if,then,else", false ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "if", 4, tr( "Decision: a if x > 0, b if x is zero, c if x < 0" ), "if(x,a,b,c)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "int", 1, tr( "Convert x to integer [ truncates ]" ), "int(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "isnull", 1, tr( "Check if x = NULL" ), "isnull(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "log", 1, tr( "Natural log of x" ), "log(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "log", 2, tr( "Log of x base b" ), "log(x,b)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "max", 2, tr( "Largest value" ), "max(a,b)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "max", 3, tr( "Largest value" ), "max(a,b,c)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "median", 2, tr( "Median value" ), "median(a,b)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "median", 3, tr( "Median value" ), "median(a,b,c)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "min", 2, tr( "Smallest value" ), "min(a,b)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "min", 3, tr( "Smallest value" ), "min(a,b,c)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "mode", 2, tr( "Mode value" ), "mode(a,b)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "mode", 3, tr( "Mode value" ), "mode(a,b,c)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "not", 1, tr( "1 if x is zero, 0 otherwise" ), "not(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "nsres", 0, tr( "Current north-south resolution" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "null", 0, tr( "NULL value" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "rand", 2, tr( "Random value between a and b" ), "rand(a,b)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "round", 1, tr( "Round x to nearest integer" ), "round(x)" ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "row", 0, tr( "Current row of moving window (Starts with 1)" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "sin", 1, tr( "Sine of x (x is in degrees)", "sin(x)" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "sqrt", 1, tr( "Square root of x", "sqrt(x)" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "tan", 1, tr( "Tangent of x (x is in degrees)", "tan(x)" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "x", 0, tr( "Current x-coordinate of moving window" ) ) ); - mFunctions.push_back( QgsGrassMapcalcFunction( t, "y", 0, tr( "Current y-coordinate of moving window" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "abs" ), 1, tr( "Absolute value of x" ), QStringLiteral( "abs(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "atan" ), 1, tr( "Inverse tangent of x (result is in degrees)" ), QStringLiteral( "atan(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "atan" ), 2, tr( "Inverse tangent of y/x (result is in degrees)" ), QStringLiteral( "atan(x,y)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "col" ), 0, tr( "Current column of moving window (starts with 1)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "cos" ), 1, tr( "Cosine of x (x is in degrees)" ), QStringLiteral( "cos(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "double" ), 1, tr( "Convert x to double-precision floating point" ), QStringLiteral( "double(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "ewres" ), 0, tr( "Current east-west resolution" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "exp" ), 1, tr( "Exponential function of x" ), QStringLiteral( "exp(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "exp" ), 2, tr( "x to the power y" ), QStringLiteral( "exp(x,y)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "float" ), 1, tr( "Convert x to single-precision floating point" ), QStringLiteral( "float(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "if" ), 1, tr( "Decision: 1 if x not zero, 0 otherwise" ), QStringLiteral( "if(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "if" ), 2, tr( "Decision: a if x not zero, 0 otherwise" ), QStringLiteral( "if(x,a)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "if" ), 3, tr( "Decision: a if x not zero, b otherwise" ), QStringLiteral( "if(x,a,b)" ), QStringLiteral( "if,then,else" ), false ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "if" ), 4, tr( "Decision: a if x > 0, b if x is zero, c if x < 0" ), QStringLiteral( "if(x,a,b,c)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "int" ), 1, tr( "Convert x to integer [ truncates ]" ), QStringLiteral( "int(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "isnull" ), 1, tr( "Check if x = NULL" ), QStringLiteral( "isnull(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "log" ), 1, tr( "Natural log of x" ), QStringLiteral( "log(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "log" ), 2, tr( "Log of x base b" ), QStringLiteral( "log(x,b)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "max" ), 2, tr( "Largest value" ), QStringLiteral( "max(a,b)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "max" ), 3, tr( "Largest value" ), QStringLiteral( "max(a,b,c)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "median" ), 2, tr( "Median value" ), QStringLiteral( "median(a,b)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "median" ), 3, tr( "Median value" ), QStringLiteral( "median(a,b,c)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "min" ), 2, tr( "Smallest value" ), QStringLiteral( "min(a,b)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "min" ), 3, tr( "Smallest value" ), QStringLiteral( "min(a,b,c)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "mode" ), 2, tr( "Mode value" ), QStringLiteral( "mode(a,b)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "mode" ), 3, tr( "Mode value" ), QStringLiteral( "mode(a,b,c)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "not" ), 1, tr( "1 if x is zero, 0 otherwise" ), QStringLiteral( "not(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "nsres" ), 0, tr( "Current north-south resolution" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "null" ), 0, tr( "NULL value" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "rand" ), 2, tr( "Random value between a and b" ), QStringLiteral( "rand(a,b)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "round" ), 1, tr( "Round x to nearest integer" ), QStringLiteral( "round(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "row" ), 0, tr( "Current row of moving window (Starts with 1)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "sin" ), 1, tr( "Sine of x (x is in degrees)", "sin(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "sqrt" ), 1, tr( "Square root of x", "sqrt(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "tan" ), 1, tr( "Tangent of x (x is in degrees)", "tan(x)" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "x" ), 0, tr( "Current x-coordinate of moving window" ) ) ); + mFunctions.push_back( QgsGrassMapcalcFunction( t, QStringLiteral( "y" ), 0, tr( "Current y-coordinate of moving window" ) ) ); for ( unsigned int i = 0; i < mFunctions.size(); i++ ) { @@ -445,7 +445,7 @@ void QgsGrassMapcalc::mouseReleaseEvent( QMouseEvent* e ) QStringList QgsGrassMapcalc::arguments() { - QString cmd = ""; + QString cmd = QLatin1String( "" ); // Attention with quotes and spaces! //cmd.append("\""); @@ -512,7 +512,7 @@ QStringList QgsGrassMapcalc::checkRegion() struct Cell_head window; - QStringList mm = obj->value().split( "@" ); + QStringList mm = obj->value().split( QStringLiteral( "@" ) ); if ( mm.size() < 1 ) continue; @@ -571,7 +571,7 @@ bool QgsGrassMapcalc::inputRegion( struct Cell_head *window, QgsCoordinateRefere struct Cell_head mapWindow; - QStringList mm = obj->value().split( "@" ); + QStringList mm = obj->value().split( QStringLiteral( "@" ) ); if ( mm.size() < 1 ) continue; @@ -656,7 +656,7 @@ void QgsGrassMapcalc::setOption() { case QgsGrassMapcalcObject::Map : { - QStringList mapMapset = mObject->value().split( "@" ); + QStringList mapMapset = mObject->value().split( QStringLiteral( "@" ) ); if ( !mMapComboBox->setCurrent( mapMapset.value( 0 ), mapMapset.value( 1 ) ) ) { mMapComboBox->setEditText( mObject->value() ); @@ -990,7 +990,7 @@ void QgsGrassMapcalc::saveAs() { QDir d( ms ); - if ( !d.mkdir( "mapcalc" ) ) + if ( !d.mkdir( QStringLiteral( "mapcalc" ) ) ) { QMessageBox::warning( 0, tr( "Warning" ), tr( "Cannot create 'mapcalc' directory in current mapset." ) ); return; @@ -1078,30 +1078,30 @@ void QgsGrassMapcalc::save() QString type; if ( obj->type() == QgsGrassMapcalcObject::Map ) { - type = "map"; + type = QStringLiteral( "map" ); } else if ( obj->type() == QgsGrassMapcalcObject::Constant ) { - type = "constant"; + type = QStringLiteral( "constant" ); } else if ( obj->type() == QgsGrassMapcalcObject::Function ) { if ( obj->function().type() == QgsGrassMapcalcFunction::Operator ) - type = "operator"; + type = QStringLiteral( "operator" ); else - type = "function"; + type = QStringLiteral( "function" ); } else if ( obj->type() == QgsGrassMapcalcObject::Output ) { - type = "output"; + type = QStringLiteral( "output" ); } QString val = obj->value(); if ( obj->type() == QgsGrassMapcalcObject::Function ) { - val.replace( "&", "&" ); - val.replace( "<", "<" ); - val.replace( ">", ">" ); + val.replace( QLatin1String( "&" ), QLatin1String( "&" ) ); + val.replace( QLatin1String( "<" ), QLatin1String( "<" ) ); + val.replace( QLatin1String( ">" ), QLatin1String( ">" ) ); } stream << " <object id=\"" + QString::number( obj->id() ) @@ -1188,7 +1188,7 @@ void QgsGrassMapcalc::load() return; } - QDomDocument doc( "mapcalc" ); + QDomDocument doc( QStringLiteral( "mapcalc" ) ); QString err; int line, column; int parsed = doc.setContent( &file, &err, &line, &column ); @@ -1205,15 +1205,15 @@ void QgsGrassMapcalc::load() QDomElement docElem = doc.documentElement(); // Set canvas - QDomNodeList canvasNodes = docElem.elementsByTagName( "canvas" ); + QDomNodeList canvasNodes = docElem.elementsByTagName( QStringLiteral( "canvas" ) ); QDomElement canvasElement = canvasNodes.item( 0 ).toElement(); - int width = canvasElement.attribute( "width", "300" ).toInt(); - int height = canvasElement.attribute( "height", "200" ).toInt(); + int width = canvasElement.attribute( QStringLiteral( "width" ), QStringLiteral( "300" ) ).toInt(); + int height = canvasElement.attribute( QStringLiteral( "height" ), QStringLiteral( "200" ) ).toInt(); resizeCanvas( width, height ); // Add objects std::vector<QgsGrassMapcalcObject *> objects; - QDomNodeList objectNodes = docElem.elementsByTagName( "object" ); + QDomNodeList objectNodes = docElem.elementsByTagName( QStringLiteral( "object" ) ); QgsDebugMsg( QString( "objectNodes.count() = %1" ).arg( objectNodes.count() ) ); for ( int n = 0; n < objectNodes.count(); n++ ) { @@ -1223,11 +1223,11 @@ void QgsGrassMapcalc::load() continue; QgsDebugMsg( QString( "id = %1" ).arg( e.attribute( "id", "?" ).toLocal8Bit().constData() ) ); - unsigned int id = e.attribute( "id", "0" ).toInt(); - int x = e.attribute( "x", "0" ).toInt(); - int y = e.attribute( "y", "0" ).toInt(); - QString typeName = e.attribute( "type", "constant" ); - QString value = e.attribute( "value", "???" ); + unsigned int id = e.attribute( QStringLiteral( "id" ), QStringLiteral( "0" ) ).toInt(); + int x = e.attribute( QStringLiteral( "x" ), QStringLiteral( "0" ) ).toInt(); + int y = e.attribute( QStringLiteral( "y" ), QStringLiteral( "0" ) ).toInt(); + QString typeName = e.attribute( QStringLiteral( "type" ), QStringLiteral( "constant" ) ); + QString value = e.attribute( QStringLiteral( "value" ), QStringLiteral( "???" ) ); if ( id >= mNextId ) mNextId = id + 1; @@ -1238,15 +1238,15 @@ void QgsGrassMapcalc::load() int type = -1; - if ( typeName == "map" ) + if ( typeName == QLatin1String( "map" ) ) type = QgsGrassMapcalcObject::Map; - else if ( typeName == "constant" ) + else if ( typeName == QLatin1String( "constant" ) ) type = QgsGrassMapcalcObject::Constant; - else if ( typeName == "operator" ) + else if ( typeName == QLatin1String( "operator" ) ) type = QgsGrassMapcalcObject::Function; - else if ( typeName == "function" ) + else if ( typeName == QLatin1String( "function" ) ) type = QgsGrassMapcalcObject::Function; - else if ( typeName == "output" ) + else if ( typeName == QLatin1String( "output" ) ) type = QgsGrassMapcalcObject::Output; if ( type == -1 ) @@ -1265,7 +1265,7 @@ void QgsGrassMapcalc::load() { case QgsGrassMapcalcObject::Map: { - QString label = QApplication::translate( "grasslabel", e.attribute( "label", "???" ).toUtf8() ); + QString label = QApplication::translate( "grasslabel", e.attribute( QStringLiteral( "label" ), QStringLiteral( "???" ) ).toUtf8() ); obj->setValue( value, label ); break; } @@ -1276,7 +1276,7 @@ void QgsGrassMapcalc::load() break; case QgsGrassMapcalcObject::Function : - int inputCount = e.attribute( "inputCount", "1" ).toInt(); + int inputCount = e.attribute( QStringLiteral( "inputCount" ), QStringLiteral( "1" ) ).toInt(); // Find function int fn = -1; for ( unsigned int i = 0; i < mFunctions.size(); i++ ) @@ -1299,7 +1299,7 @@ void QgsGrassMapcalc::load() } // Add connectors - QDomNodeList connectorNodes = docElem.elementsByTagName( "connector" ); + QDomNodeList connectorNodes = docElem.elementsByTagName( QStringLiteral( "connector" ) ); for ( int n = 0; n < connectorNodes.count(); n++ ) { QDomNode node = connectorNodes.item( n ); @@ -1308,7 +1308,7 @@ void QgsGrassMapcalc::load() continue; QgsDebugMsg( QString( "id = %1" ).arg( e.attribute( "id", "?" ).toLocal8Bit().constData() ) ); - unsigned int id = e.attribute( "id", "0" ).toInt(); + unsigned int id = e.attribute( QStringLiteral( "id" ), QStringLiteral( "0" ) ).toInt(); if ( id >= mNextId ) mNextId = id + 1; @@ -1318,7 +1318,7 @@ void QgsGrassMapcalc::load() mCanvasScene->addItem( con ); con->show(); - QDomNodeList endNodes = e.elementsByTagName( "end" ); + QDomNodeList endNodes = e.elementsByTagName( QStringLiteral( "end" ) ); QgsDebugMsg( QString( "endNodes.count = %1" ).arg( endNodes.count() ) ); for ( int n2 = 0; n2 < endNodes.count() && n2 < 2; n2++ ) { @@ -1327,27 +1327,27 @@ void QgsGrassMapcalc::load() if ( e2.isNull() ) continue; - int x = e2.attribute( "x", "0" ).toInt(); - int y = e2.attribute( "y", "0" ).toInt(); + int x = e2.attribute( QStringLiteral( "x" ), QStringLiteral( "0" ) ).toInt(); + int y = e2.attribute( QStringLiteral( "y" ), QStringLiteral( "0" ) ).toInt(); con->setPoint( n2, QPoint( x, y ) ); QgsDebugMsg( QString( "x = %1 y = %2" ).arg( x ).arg( y ) ); - int objId = e2.attribute( "object", "-1" ).toInt(); + int objId = e2.attribute( QStringLiteral( "object" ), QStringLiteral( "-1" ) ).toInt(); QgsDebugMsg( QString( "objId = %1" ).arg( objId ) ); if ( objId < 0 ) continue; // not connected if ( static_cast<uint>( objId ) < objects.size() && objects[objId] ) { - QString socketTypeName = e2.attribute( "socketType", "out" ); + QString socketTypeName = e2.attribute( QStringLiteral( "socketType" ), QStringLiteral( "out" ) ); int socketType; - if ( socketTypeName == "in" ) + if ( socketTypeName == QLatin1String( "in" ) ) socketType = QgsGrassMapcalcObject::In; else socketType = QgsGrassMapcalcObject::Out; - int socket = e2.attribute( "socket", "0" ).toInt(); + int socket = e2.attribute( QStringLiteral( "socket" ), QStringLiteral( "0" ) ).toInt(); QgsDebugMsg( QString( "end = %1 objId = %2 socketType = %3 socket = %4" ).arg( n2 ).arg( objId ).arg( socketType ).arg( socket ) ); @@ -1772,7 +1772,7 @@ QString QgsGrassMapcalcObject::expression() //return mInputConnectors[0]->expression(); return "(" + mInputConnectors[0]->expression() + ")"; else - return "null()"; + return QStringLiteral( "null()" ); } // Functions and operators @@ -1994,7 +1994,7 @@ QString QgsGrassMapcalcConnector::expression() return mSocketObjects[i]->expression(); } - return "null()"; + return QStringLiteral( "null()" ); } QgsGrassMapcalcObject *QgsGrassMapcalcConnector::object( int end ) @@ -2018,7 +2018,7 @@ QgsGrassMapcalcFunction::QgsGrassMapcalcFunction( int type, QString name, if ( !labels.isEmpty() ) { - mInputLabels = labels.split( ",", QString::SkipEmptyParts ); + mInputLabels = labels.split( QStringLiteral( "," ), QString::SkipEmptyParts ); } } diff --git a/src/plugins/grass/qgsgrassmapcalc.h b/src/plugins/grass/qgsgrassmapcalc.h index 898b3a2431f1..9967edc7c6e7 100644 --- a/src/plugins/grass/qgsgrassmapcalc.h +++ b/src/plugins/grass/qgsgrassmapcalc.h @@ -217,8 +217,8 @@ class QgsGrassMapcalcFunction QgsGrassMapcalcFunction(); QgsGrassMapcalcFunction( int type, QString name, int count = 2, - QString description = "", QString label = "", - QString labels = "", bool drawLabel = true ); + QString description = QStringLiteral( "" ), QString label = QStringLiteral( "" ), + QString labels = QStringLiteral( "" ), bool drawLabel = true ); ~QgsGrassMapcalcFunction(); QString name() { return mName; } @@ -329,7 +329,7 @@ class QgsGrassMapcalcObject: public QGraphicsRectItem, public QgsGrassMapcalcIte ~QgsGrassMapcalcObject(); // Set map name, constant value or function/operator - void setValue( QString val, QString lab = "" ); + void setValue( QString val, QString lab = QStringLiteral( "" ) ); // Set function void setFunction( QgsGrassMapcalcFunction f ); diff --git a/src/plugins/grass/qgsgrassmodule.cpp b/src/plugins/grass/qgsgrassmodule.cpp index 36f1e792cd62..6c6794b4ccda 100644 --- a/src/plugins/grass/qgsgrassmodule.cpp +++ b/src/plugins/grass/qgsgrassmodule.cpp @@ -69,17 +69,17 @@ QProcessEnvironment QgsGrassModule::processEnvironment( bool direct ) QProcessEnvironment environment = QProcessEnvironment::systemEnvironment(); QStringList paths = QgsGrass::grassModulesPaths(); - paths += environment.value( "PATH" ).split( QgsGrass::pathSeparator() ); - environment.insert( "PATH", paths.join( QgsGrass::pathSeparator() ) ); - environment.insert( "PYTHONPATH", QgsGrass::getPythonPath() ); + paths += environment.value( QStringLiteral( "PATH" ) ).split( QgsGrass::pathSeparator() ); + environment.insert( QStringLiteral( "PATH" ), paths.join( QgsGrass::pathSeparator() ) ); + environment.insert( QStringLiteral( "PYTHONPATH" ), QgsGrass::getPythonPath() ); if ( direct ) { // Set path to GRASS gis fake library QgsGrassModule::setDirectLibraryPath( environment ); - environment.insert( "QGIS_PREFIX_PATH", QgsApplication::prefixPath() ); + environment.insert( QStringLiteral( "QGIS_PREFIX_PATH" ), QgsApplication::prefixPath() ); // Window to avoid crash in G__gisinit - environment.insert( "GRASS_REGION", "west:0;south:0;east:1;north:1;cols:1;rows:1;proj:0;zone:0" ); + environment.insert( QStringLiteral( "GRASS_REGION" ), QStringLiteral( "west:0;south:0;east:1;north:1;cols:1;rows:1;proj:0;zone:0" ) ); } return environment; } @@ -97,7 +97,7 @@ QgsGrassModule::QgsGrassModule( QgsGrassTools *tools, QString moduleName, QgisIn setupUi( this ); // use fixed width font because module's output may be formated - mOutputTextBrowser->setStyleSheet( "font-family: Monospace; font-size: 9pt;" ); + mOutputTextBrowser->setStyleSheet( QStringLiteral( "font-family: Monospace; font-size: 9pt;" ) ); lblModuleName->setText( tr( "Module: %1" ).arg( moduleName ) ); mTools = tools; mIface = iface; @@ -120,7 +120,7 @@ QgsGrassModule::QgsGrassModule( QgsGrassTools *tools, QString moduleName, QgisIn mErrors.append( tr( "Cannot open module file (%1)" ).arg( mpath ) ); return; } - QDomDocument qDoc( "qgisgrassmodule" ); + QDomDocument qDoc( QStringLiteral( "qgisgrassmodule" ) ); QString err; int line, column; if ( !qDoc.setContent( &qFile, &err, &line, &column ) ) @@ -136,8 +136,8 @@ QgsGrassModule::QgsGrassModule( QgsGrassTools *tools, QString moduleName, QgisIn QDomElement qDocElem = qDoc.documentElement(); // Read GRASS module description - QString xName = qDocElem.attribute( "module" ); - QString xDocName = qDocElem.attribute( "manual" ); + QString xName = qDocElem.attribute( QStringLiteral( "module" ) ); + QString xDocName = qDocElem.attribute( QStringLiteral( "manual" ) ); if ( xDocName.isEmpty() ) { xDocName = xName; @@ -161,7 +161,7 @@ QgsGrassModule::QgsGrassModule( QgsGrassTools *tools, QString moduleName, QgisIn QVBoxLayout *layout = new QVBoxLayout( mTabWidget->widget( 0 ) ); layout->setContentsMargins( 0, 0, 0, 0 ); - if ( xName == "r.mapcalc" ) + if ( xName == QLatin1String( "r.mapcalc" ) ) { mOptions = new QgsGrassMapcalc( mTools, this, mIface, mTabWidget->widget( 0 ) ); @@ -198,7 +198,7 @@ QgsGrassModule::QgsGrassModule( QgsGrassTools *tools, QString moduleName, QgisIn else { mManualTextBrowser->clear(); - mManualTextBrowser->textCursor().insertImage( ":/grass/error.png" ); + mManualTextBrowser->textCursor().insertImage( QStringLiteral( ":/grass/error.png" ) ); mManualTextBrowser->insertPlainText( tr( "Cannot find man page %1" ).arg( manPath ) ); mManualTextBrowser->insertPlainText( tr( "Please ensure you have the GRASS documentation installed." ) ); } @@ -230,7 +230,7 @@ QgsGrassModule::Description QgsGrassModule::description( QString path ) { return Description( tr( "Not available, cannot open description (%1)" ).arg( path ) ); } - QDomDocument qDoc( "qgisgrassmodule" ); + QDomDocument qDoc( QStringLiteral( "qgisgrassmodule" ) ); QString err; int line, column; if ( !qDoc.setContent( &qFile, &err, &line, &column ) ) @@ -245,8 +245,8 @@ QgsGrassModule::Description QgsGrassModule::description( QString path ) qFile.close(); QDomElement qDocElem = qDoc.documentElement(); - QString label = QApplication::translate( "grasslabel", qDocElem.attribute( "label" ).trimmed().toUtf8() ); - bool direct = qDocElem.attribute( "direct" ) == "1"; + QString label = QApplication::translate( "grasslabel", qDocElem.attribute( QStringLiteral( "label" ) ).trimmed().toUtf8() ); + bool direct = qDocElem.attribute( QStringLiteral( "direct" ) ) == QLatin1String( "1" ); return Description( label, direct ); } @@ -498,7 +498,7 @@ void QgsGrassModule::run() if ( outsideRegion.size() > 0 ) { QMessageBox questionBox( QMessageBox::Question, tr( "Warning" ), - tr( "Input %1 outside current region!" ).arg( outsideRegion.join( "," ) ), + tr( "Input %1 outside current region!" ).arg( outsideRegion.join( QStringLiteral( "," ) ) ), QMessageBox::Ok | QMessageBox::Cancel ); QPushButton *resetButton = nullptr; if ( QgsGrass::versionMajor() > 6 || ( QgsGrass::versionMajor() == 6 && QgsGrass::versionMinor() >= 1 ) ) @@ -530,8 +530,8 @@ void QgsGrassModule::run() QStringList outputExists = mOptions->checkOutput(); if ( outputExists.size() > 0 ) { - QMessageBox::StandardButton ret = QMessageBox::question( 0, "Warning", - tr( "Output %1 exists! Overwrite?" ).arg( outputExists.join( "," ) ), + QMessageBox::StandardButton ret = QMessageBox::question( 0, QStringLiteral( "Warning" ), + tr( "Output %1 exists! Overwrite?" ).arg( outputExists.join( QStringLiteral( "," ) ) ), QMessageBox::Ok | QMessageBox::Cancel ); if ( ret == QMessageBox::Cancel ) @@ -544,7 +544,7 @@ void QgsGrassModule::run() arguments.append( "--o" ); } #else - arguments.append( "--o" ); + arguments.append( QStringLiteral( "--o" ) ); #endif } } @@ -592,7 +592,7 @@ void QgsGrassModule::run() mOutputTextBrowser->clear(); QProcessEnvironment environment = processEnvironment( mDirect ); - environment.insert( "GRASS_HTML_BROWSER", QgsGrassUtils::htmlBrowserPath() ); + environment.insert( QStringLiteral( "GRASS_HTML_BROWSER" ), QgsGrassUtils::htmlBrowserPath() ); // Warning: it is not useful to write requested region to WIND file and // reset then to original beacuse it is reset before @@ -603,7 +603,7 @@ void QgsGrassModule::run() { QString reg = QgsGrass::regionString( &tempWindow ); QgsDebugMsg( "reg: " + reg ); - environment.insert( "GRASS_REGION", reg ); + environment.insert( QStringLiteral( "GRASS_REGION" ), reg ); } if ( mDirect ) @@ -615,30 +615,30 @@ void QgsGrassModule::run() #elif defined(Q_OS_MAC) variables << "DYLD_LIBRARY_PATH"; #else - variables << "LD_LIBRARY_PATH"; + variables << QStringLiteral( "LD_LIBRARY_PATH" ); #endif - environment.insert( "QGIS_PREFIX_PATH", QgsApplication::prefixPath() ); + environment.insert( QStringLiteral( "QGIS_PREFIX_PATH" ), QgsApplication::prefixPath() ); if ( crs.isValid() ) // it should always be valid { - environment.insert( "QGIS_GRASS_CRS", crs.toProj4() ); + environment.insert( QStringLiteral( "QGIS_GRASS_CRS" ), crs.toProj4() ); } // Suppress debug output - environment.insert( "QGIS_DEBUG", "-1" ); + environment.insert( QStringLiteral( "QGIS_DEBUG" ), QStringLiteral( "-1" ) ); // Print some important variables - variables << "QGIS_PREFIX_PATH" << "QGIS_GRASS_CRS" << "GRASS_REGION"; + variables << QStringLiteral( "QGIS_PREFIX_PATH" ) << QStringLiteral( "QGIS_GRASS_CRS" ) << QStringLiteral( "GRASS_REGION" ); Q_FOREACH ( const QString& v, variables ) { mOutputTextBrowser->append( v + "=" + environment.value( v ) + "<BR>" ); } } - QString commandHtml = mXName + " " + argumentsHtml.join( " " ); + QString commandHtml = mXName + " " + argumentsHtml.join( QStringLiteral( " " ) ); QgsDebugMsg( "command: " + commandHtml ); - commandHtml.replace( "&", "&" ); - commandHtml.replace( "<", "<" ); - commandHtml.replace( ">", ">" ); + commandHtml.replace( QLatin1String( "&" ), QLatin1String( "&" ) ); + commandHtml.replace( QLatin1String( "<" ), QLatin1String( "<" ) ); + commandHtml.replace( QLatin1String( ">" ), QLatin1String( ">" ) ); mOutputTextBrowser->append( "<B>" + commandHtml + "</B>" ); // I was not able to get scripts working on Windows @@ -777,7 +777,7 @@ void QgsGrassModule::readStdout() while ( mProcess.canReadLine() ) { QByteArray ba = mProcess.readLine(); - line = QString::fromLocal8Bit( ba ).replace( '\n', "" ); + line = QString::fromLocal8Bit( ba ).replace( '\n', QLatin1String( "" ) ); // GRASS_INFO_PERCENT is catched here only because of bugs in GRASS, // normaly it should be printed to stderr @@ -803,7 +803,7 @@ void QgsGrassModule::readStderr() while ( mProcess.canReadLine() ) { QByteArray ba = mProcess.readLine(); - line = QString::fromLocal8Bit( ba ).replace( '\n', "" ); + line = QString::fromLocal8Bit( ba ).replace( '\n', QLatin1String( "" ) ); QString text, html; int percent; @@ -895,7 +895,7 @@ void QgsGrassModule::viewOutput() QString name = QgsGrassUtils::vectorLayerName( map, layers[j], 1 ); - mIface->addVectorLayer( uri, name, "grass" ); + mIface->addVectorLayer( uri, name, QStringLiteral( "grass" ) ); } } } @@ -907,7 +907,7 @@ void QgsGrassModule::viewOutput() if ( mDirect ) { QString baseName = QFileInfo( map ).baseName(); - mIface->addRasterLayer( map, baseName, "gdal" ); + mIface->addRasterLayer( map, baseName, QStringLiteral( "gdal" ) ); } else { @@ -916,7 +916,7 @@ void QgsGrassModule::viewOutput() + QgsGrass::getDefaultMapset() + "/cellhd/" + map; - mIface->addRasterLayer( uri, map, "grassraster" ); + mIface->addRasterLayer( uri, map, QStringLiteral( "grassraster" ) ); } } } @@ -947,7 +947,7 @@ QString QgsGrassModule::libraryPathVariable() #elif defined(Q_OS_MAC) return "DYLD_LIBRARY_PATH"; #else - return "LD_LIBRARY_PATH"; + return QStringLiteral( "LD_LIBRARY_PATH" ); #endif } @@ -960,7 +960,7 @@ void QgsGrassModule::setDirectLibraryPath( QProcessEnvironment & environment ) #elif defined(Q_OS_MAC) separator = ":"; #else - separator = ":"; + separator = QStringLiteral( ":" ); #endif QString lp = environment.value( pathVariable ); lp = QgsApplication::pluginPath() + separator + lp; diff --git a/src/plugins/grass/qgsgrassmoduleinput.cpp b/src/plugins/grass/qgsgrassmoduleinput.cpp index 9b9c31d74773..de0642c88369 100644 --- a/src/plugins/grass/qgsgrassmoduleinput.cpp +++ b/src/plugins/grass/qgsgrassmoduleinput.cpp @@ -126,11 +126,11 @@ void QgsGrassModuleInputModel::onDirectoryChanged( const QString & path ) { QgsDebugMsg( "cellhd/vector = " + path ); mapset = parentDir.dirName(); - if ( path.endsWith( "cellhd" ) ) + if ( path.endsWith( QLatin1String( "cellhd" ) ) ) { types << QgsGrassObject::Raster; } - else if ( path.endsWith( "vector" ) ) + else if ( path.endsWith( QLatin1String( "vector" ) ) ) { types << QgsGrassObject::Vector; } @@ -149,7 +149,7 @@ void QgsGrassModuleInputModel::onFileChanged( const QString & path ) { QgsDebugMsg( "path = " + path ); // when tgis/sqlite.db is changed, this gets called twice, probably the file changes more times when it is modified - if ( path.endsWith( "/tgis/sqlite.db" ) ) + if ( path.endsWith( QLatin1String( "/tgis/sqlite.db" ) ) ) { QDir dir = QFileInfo( path ).dir(); dir.cdUp(); @@ -216,12 +216,12 @@ void QgsGrassModuleInputModel::refreshMapset( QStandardItem *mapsetItem, const Q } Q_FOREACH ( QgsGrassObject::Type type, types ) { - QgsGrassObject mapsetObject( QgsGrass::getDefaultGisdbase(), QgsGrass::getDefaultLocation(), mapset, "", QgsGrassObject::Mapset ); + QgsGrassObject mapsetObject( QgsGrass::getDefaultGisdbase(), QgsGrass::getDefaultLocation(), mapset, QLatin1String( "" ), QgsGrassObject::Mapset ); QStringList maps = QgsGrass::grassObjects( mapsetObject, type ); QStringList mapNames; Q_FOREACH ( const QString& map, maps ) { - if ( map.startsWith( "qgis_import_tmp_" ) ) + if ( map.startsWith( QLatin1String( "qgis_import_tmp_" ) ) ) { continue; } @@ -827,19 +827,19 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, adjustTitle(); // Check if this parameter is required - mRequired = gnode.toElement().attribute( "required" ) == "yes"; + mRequired = gnode.toElement().attribute( QStringLiteral( "required" ) ) == QLatin1String( "yes" ); - QDomNode promptNode = gnode.namedItem( "gisprompt" ); + QDomNode promptNode = gnode.namedItem( QStringLiteral( "gisprompt" ) ); QDomElement promptElem = promptNode.toElement(); - QString element = promptElem.attribute( "element" ); + QString element = promptElem.attribute( QStringLiteral( "element" ) ); QDomNode typeNode; - if ( element == "vector" ) + if ( element == QLatin1String( "vector" ) ) { mType = QgsGrassObject::Vector; // Read type mask if "typeoption" is defined - QString opt = qdesc.attribute( "typeoption" ); + QString opt = qdesc.attribute( QStringLiteral( "typeoption" ) ); if ( ! opt.isNull() ) { typeNode = nodeByKey( gdesc, opt ); @@ -852,7 +852,7 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, { mGeometryTypeOption = opt; - QDomNode valuesNode = typeNode.namedItem( "values" ); + QDomNode valuesNode = typeNode.namedItem( QStringLiteral( "values" ) ); if ( valuesNode.isNull() ) { mErrors << tr( "Cannot find values for typeoption %1" ).arg( opt ); @@ -866,9 +866,9 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, while ( !valueNode.isNull() ) { QDomElement valueElem = valueNode.toElement(); - if ( !valueElem.isNull() && valueElem.tagName() == "value" ) + if ( !valueElem.isNull() && valueElem.tagName() == QLatin1String( "value" ) ) { - QDomNode n = valueNode.namedItem( "name" ); + QDomNode n = valueNode.namedItem( QStringLiteral( "name" ) ); if ( !n.isNull() ) { QDomElement e = n.toElement(); @@ -884,7 +884,7 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, } // Read type mask defined in configuration - opt = qdesc.attribute( "typemask" ); + opt = qdesc.attribute( QStringLiteral( "typemask" ) ); if ( ! opt.isNull() ) { int mask = 0; @@ -899,7 +899,7 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, } // Read "layeroption" if defined - opt = qdesc.attribute( "layeroption" ); + opt = qdesc.attribute( QStringLiteral( "layeroption" ) ); if ( ! opt.isNull() ) { @@ -916,25 +916,25 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, } // Read "mapid" - mMapId = qdesc.attribute( "mapid" ); + mMapId = qdesc.attribute( QStringLiteral( "mapid" ) ); } - else if ( element == "cell" ) + else if ( element == QLatin1String( "cell" ) ) { mType = QgsGrassObject::Raster; } - else if ( element == "strds" ) + else if ( element == QLatin1String( "strds" ) ) { mType = QgsGrassObject::Strds; } - else if ( element == "stvds" ) + else if ( element == QLatin1String( "stvds" ) ) { mType = QgsGrassObject::Stvds; } - else if ( element == "str3ds" ) + else if ( element == QLatin1String( "str3ds" ) ) { mType = QgsGrassObject::Str3ds; } - else if ( element == "stds" ) + else if ( element == QLatin1String( "stds" ) ) { mType = QgsGrassObject::Stds; } @@ -943,7 +943,7 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, mErrors << tr( "GRASS element %1 not supported" ).arg( element ); } - if ( qdesc.attribute( "update" ) == "yes" ) + if ( qdesc.attribute( QStringLiteral( "update" ) ) == QLatin1String( "yes" ) ) { mUpdate = true; } @@ -963,11 +963,11 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, mapLayout->addWidget( mComboBox ); // Region button - QString region = qdesc.attribute( "region" ); + QString region = qdesc.attribute( QStringLiteral( "region" ) ); // TODO: implement region for multiple - if ( mType == QgsGrassObject::Raster && region != "no" && !mDirect && !multiple() ) + if ( mType == QgsGrassObject::Raster && region != QLatin1String( "no" ) && !mDirect && !multiple() ) { - mRegionButton = new QPushButton( QgsGrassPlugin::getThemeIcon( "grass_set_region.png" ), "" ); + mRegionButton = new QPushButton( QgsGrassPlugin::getThemeIcon( QStringLiteral( "grass_set_region.png" ) ), QLatin1String( "" ) ); mRegionButton->setToolTip( tr( "Use region of this map" ) ); mRegionButton->setCheckable( true ); @@ -1036,7 +1036,7 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, mUsesRegion = false; if ( region.length() > 0 ) { - if ( region == "yes" ) + if ( region == QLatin1String( "yes" ) ) mUsesRegion = true; } else @@ -1045,7 +1045,7 @@ QgsGrassModuleInput::QgsGrassModuleInput( QgsGrassModule *module, mUsesRegion = true; } QgsDebugMsg( QString( "mUsesRegion = %1" ).arg( mUsesRegion ) ); - onChanged( "" ); + onChanged( QLatin1String( "" ) ); } QgsGrassModuleInput::~QgsGrassModuleInput() @@ -1069,7 +1069,7 @@ QStringList QgsGrassModuleInput::options() { maps << mSelectedModel->item( i )->text(); } - list << mKey + "=" + maps.join( "," ); + list << mKey + "=" + maps.join( QStringLiteral( "," ) ); } else { @@ -1092,7 +1092,7 @@ QStringList QgsGrassModuleInput::options() if ( !mGeometryTypeOption.isEmpty() ) { - list << mGeometryTypeOption + "=" + currentGeometryTypeNames().join( "," ); + list << mGeometryTypeOption + "=" + currentGeometryTypeNames().join( QStringLiteral( "," ) ); } } @@ -1113,7 +1113,7 @@ QgsFields QgsGrassModuleInput::currentFields() QgsGrassObject QgsGrassModuleInput::currentGrassObject() { - QgsGrassObject grassObject( QgsGrass::getDefaultGisdbase(), QgsGrass::getDefaultLocation(), "", "", mType ); + QgsGrassObject grassObject( QgsGrass::getDefaultGisdbase(), QgsGrass::getDefaultLocation(), QLatin1String( "" ), QLatin1String( "" ), mType ); grassObject.setFullName( mComboBox->currentText() ); return grassObject; } @@ -1158,8 +1158,8 @@ QStringList QgsGrassModuleInput::currentLayerCodes() { Q_FOREACH ( QString type, currentGeometryTypeNames() ) { - type.replace( "area", "polygon" ); - list << QString( "%1_%2" ).arg( currentLayer()->number() ).arg( type ); + type.replace( QLatin1String( "area" ), QLatin1String( "polygon" ) ); + list << QStringLiteral( "%1_%2" ).arg( currentLayer()->number() ).arg( type ); } } QgsDebugMsg( "list = " + list.join( "," ) ); diff --git a/src/plugins/grass/qgsgrassmoduleinput.h b/src/plugins/grass/qgsgrassmoduleinput.h index fd8a53117731..d5989a062ef6 100644 --- a/src/plugins/grass/qgsgrassmoduleinput.h +++ b/src/plugins/grass/qgsgrassmoduleinput.h @@ -87,7 +87,7 @@ class QgsGrassModuleInputModel : public QStandardItemModel void watch( const QString & path ); QString mLocationPath; // mapset watched dirs - QStringList watchedDirs() { QStringList l; l << "cellhd" << "vector" << "tgis"; return l; } + QStringList watchedDirs() { QStringList l; l << QStringLiteral( "cellhd" ) << QStringLiteral( "vector" ) << QStringLiteral( "tgis" ); return l; } // names of QStringList locationDirNames(); QFileSystemWatcher *mWatcher; diff --git a/src/plugins/grass/qgsgrassmoduleoptions.cpp b/src/plugins/grass/qgsgrassmoduleoptions.cpp index 53ef34fc78da..38929d4b295f 100644 --- a/src/plugins/grass/qgsgrassmoduleoptions.cpp +++ b/src/plugins/grass/qgsgrassmoduleoptions.cpp @@ -159,7 +159,7 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( { // Check GRASS version QStringList errors; - if ( !QgsGrassModuleOption::checkVersion( confDomElement.attribute( "version_min" ), confDomElement.attribute( "version_max" ), errors ) ) + if ( !QgsGrassModuleOption::checkVersion( confDomElement.attribute( QStringLiteral( "version_min" ) ), confDomElement.attribute( QStringLiteral( "version_max" ) ), errors ) ) { mErrors << errors; // checkVersion returns falso also if parsing fails confDomNode = confDomNode.nextSibling(); @@ -169,7 +169,7 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( QString optionType = confDomElement.tagName(); QgsDebugMsg( "optionType = " + optionType ); - if ( confDomElement.attribute( "advanced", "no" ) == "yes" ) + if ( confDomElement.attribute( QStringLiteral( "advanced" ), QStringLiteral( "no" ) ) == QLatin1String( "yes" ) ) { layout = mypAdvancedLayout; } @@ -178,7 +178,7 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( layout = mypSimpleLayout; } - QString key = confDomElement.attribute( "key" ); + QString key = confDomElement.attribute( QStringLiteral( "key" ) ); QgsDebugMsg( "key = " + key ); QDomNode gnode = QgsGrassModuleParam::nodeByKey( descDocElem, key ); @@ -189,23 +189,23 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( continue; } - if ( optionType == "option" ) + if ( optionType == QLatin1String( "option" ) ) { bool created = false; // Check option type and create appropriate control - QDomNode promptNode = gnode.namedItem( "gisprompt" ); + QDomNode promptNode = gnode.namedItem( QStringLiteral( "gisprompt" ) ); QDomElement promptElem = promptNode.toElement(); if ( !promptElem.isNull() ) { - QString element = promptElem.attribute( "element" ); - QString age = promptElem.attribute( "age" ); + QString element = promptElem.attribute( QStringLiteral( "element" ) ); + QString age = promptElem.attribute( QStringLiteral( "age" ) ); //QgsDebugMsg("element = " + element + " age = " + age); - if ( age == "old" && ( element == "vector" || element == "cell" || - element == "strds" || element == "stvds" || - element == "str3ds" || element == "stds" ) - && confDomElement.attribute( "widget" ) != "text" ) + if ( age == QLatin1String( "old" ) && ( element == QLatin1String( "vector" ) || element == QLatin1String( "cell" ) || + element == QLatin1String( "strds" ) || element == QLatin1String( "stvds" ) || + element == QLatin1String( "str3ds" ) || element == QLatin1String( "stds" ) ) + && confDomElement.attribute( QStringLiteral( "widget" ) ) != QLatin1String( "text" ) ) { QgsGrassModuleInput *mi = new QgsGrassModuleInput( mModule, this, key, confDomElement, descDocElem, gnode, mDirect, this ); @@ -224,14 +224,14 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( layout->addWidget( so ); mParams.append( so ); - if ( promptElem.attribute( "prompt" ) == "dbcolumn" ) + if ( promptElem.attribute( QStringLiteral( "prompt" ) ) == QLatin1String( "dbcolumn" ) ) { // Give only warning if the option is not hidden if ( !so->hidden() ) { // G_OPT_DB_COLUMN may be also used for new columns (v.in.db) so we check also if there is at least one input vector // but a vector input may also exist (v.random). - QList<QDomNode> vectorNodes = QgsGrassModuleParam::nodesByType( descDocElem, G_OPT_V_INPUT, "old" ); + QList<QDomNode> vectorNodes = QgsGrassModuleParam::nodesByType( descDocElem, G_OPT_V_INPUT, QStringLiteral( "old" ) ); QgsDebugMsg( QString( "vectorNodes.size() = %1" ).arg( vectorNodes.size() ) ); if ( !vectorNodes.isEmpty() ) { @@ -241,7 +241,7 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( } } } - else if ( optionType == "ogr" ) + else if ( optionType == QLatin1String( "ogr" ) ) { QgsGrassModuleGdalInput *mi = new QgsGrassModuleGdalInput( mModule, QgsGrassModuleGdalInput::Ogr, key, confDomElement, @@ -249,7 +249,7 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( layout->addWidget( mi ); mParams.append( mi ); } - else if ( optionType == "gdal" ) + else if ( optionType == QLatin1String( "gdal" ) ) { QgsGrassModuleGdalInput *mi = new QgsGrassModuleGdalInput( mModule, QgsGrassModuleGdalInput::Gdal, key, confDomElement, @@ -257,9 +257,9 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( layout->addWidget( mi ); mParams.append( mi ); } - else if ( optionType == "field" ) + else if ( optionType == QLatin1String( "field" ) ) { - if ( confDomElement.hasAttribute( "layer" ) ) + if ( confDomElement.hasAttribute( QStringLiteral( "layer" ) ) ) { QgsGrassModuleVectorField *mi = new QgsGrassModuleVectorField( mModule, this, key, confDomElement, @@ -276,7 +276,7 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( mParams.append( mi ); } } - else if ( optionType == "selection" ) + else if ( optionType == QLatin1String( "selection" ) ) { QgsGrassModuleSelection *mi = new QgsGrassModuleSelection( mModule, this, key, confDomElement, @@ -284,14 +284,14 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( layout->addWidget( mi ); mParams.append( mi ); } - else if ( optionType == "file" ) + else if ( optionType == QLatin1String( "file" ) ) { QgsGrassModuleFile *mi = new QgsGrassModuleFile( mModule, key, confDomElement, descDocElem, gnode, mDirect, this ); layout->addWidget( mi ); mParams.append( mi ); } - else if ( optionType == "flag" ) + else if ( optionType == QLatin1String( "flag" ) ) { QgsGrassModuleFlag *flag = new QgsGrassModuleFlag( mModule, key, confDomElement, descDocElem, gnode, mDirect, this ); @@ -325,9 +325,9 @@ QgsGrassModuleStandardOptions::QgsGrassModuleStandardOptions( QString optionType = confDomElement.tagName(); QgsDebugMsg( "optionType = " + optionType ); - if ( optionType == "flag" ) + if ( optionType == QLatin1String( "flag" ) ) { - QString name = confDomElement.attribute( "name" ).trimmed(); + QString name = confDomElement.attribute( QStringLiteral( "name" ) ).trimmed(); QgsDebugMsg( "name = " + name ); mFlagNames.append( name ); } @@ -484,7 +484,7 @@ QList<QgsGrassProvider *> QgsGrassModuleStandardOptions::grassProviders() if ( layer->type() == QgsMapLayer::VectorLayer ) { QgsVectorLayer *vector = qobject_cast<QgsVectorLayer*>( layer ); - if ( vector && vector->providerType() == "grass" ) + if ( vector && vector->providerType() == QLatin1String( "grass" ) ) { QgsGrassProvider *provider = qobject_cast<QgsGrassProvider *>( vector->dataProvider() ); if ( provider ) @@ -505,7 +505,7 @@ QList<QgsGrassRasterProvider *> QgsGrassModuleStandardOptions::grassRasterProvid if ( layer->type() == QgsMapLayer::RasterLayer ) { QgsRasterLayer *raster = qobject_cast<QgsRasterLayer*>( layer ); - if ( raster && raster->providerType() == "grassraster" ) + if ( raster && raster->providerType() == QLatin1String( "grassraster" ) ) { QgsGrassRasterProvider *provider = qobject_cast<QgsGrassRasterProvider *>( raster->dataProvider() ); if ( provider ) @@ -866,7 +866,7 @@ bool QgsGrassModuleStandardOptions::getCurrentMapRegion( QgsGrassModuleInput* in return false; } - QStringList mm = input->currentMap().split( "@" ); + QStringList mm = input->currentMap().split( QStringLiteral( "@" ) ); QString map = mm.value( 0 ); QString mapset = QgsGrass::getDefaultMapset(); if ( mm.size() > 1 ) @@ -891,7 +891,7 @@ QgsGrassModuleStandardOptions::~QgsGrassModuleStandardOptions() QDomDocument QgsGrassModuleStandardOptions::readInterfaceDescription( const QString & xname, QStringList & errors ) { - QDomDocument gDoc( "task" ); + QDomDocument gDoc( QStringLiteral( "task" ) ); // Attention!: sh.exe (MSYS) sets $0 in scripts to file name // without full path. Strange because when run from msys.bat @@ -908,7 +908,7 @@ QDomDocument QgsGrassModuleStandardOptions::readInterfaceDescription( const QStr QString cmd = arguments.takeFirst(); - arguments.append( "--interface-description" ); + arguments.append( QStringLiteral( "--interface-description" ) ); QProcess process( this ); @@ -923,16 +923,16 @@ QDomDocument QgsGrassModuleStandardOptions::readInterfaceDescription( const QStr || !process.waitForReadyRead() || !process.waitForFinished() || ( process.exitCode() != 0 && process.exitCode() != 255 && - ( !cmd.endsWith( ".py" ) || process.exitCode() != 1 ) ) ) + ( !cmd.endsWith( QLatin1String( ".py" ) ) || process.exitCode() != 1 ) ) ) { QString pathVariable = QgsGrassModule::libraryPathVariable(); QgsDebugMsg( "process.exitCode() = " + QString::number( process.exitCode() ) ); QString msg = tr( "Cannot start module %1" ).arg( mXName ) + "<br><br>" + pathVariable + "=" + environment.value( pathVariable ) - + "<br><br>PATH=" + environment.value( "PATH" ) - + "<br><br>PYTHONPATH=" + environment.value( "PYTHONPATH" ) - + "<br><br>" + tr( "command" ) + QString( ": %1 %2<br>%3<br>%4" ) - .arg( cmd, arguments.join( " " ), + + "<br><br>PATH=" + environment.value( QStringLiteral( "PATH" ) ) + + "<br><br>PYTHONPATH=" + environment.value( QStringLiteral( "PYTHONPATH" ) ) + + "<br><br>" + tr( "command" ) + QStringLiteral( ": %1 %2<br>%3<br>%4" ) + .arg( cmd, arguments.join( QStringLiteral( " " ) ), process.readAllStandardOutput().constData(), process.readAllStandardError().constData() ); QgsDebugMsg( msg ); diff --git a/src/plugins/grass/qgsgrassmoduleparam.cpp b/src/plugins/grass/qgsgrassmoduleparam.cpp index 428efb03156c..5c74c741c635 100644 --- a/src/plugins/grass/qgsgrassmoduleparam.cpp +++ b/src/plugins/grass/qgsgrassmoduleparam.cpp @@ -59,13 +59,13 @@ QgsGrassModuleParam::QgsGrassModuleParam( QgsGrassModule *module, QString key, Q_UNUSED( gdesc ); //mAnswer = qdesc.attribute("answer", ""); - if ( !qdesc.attribute( "answer" ).isNull() ) + if ( !qdesc.attribute( QStringLiteral( "answer" ) ).isNull() ) { - mAnswer = qdesc.attribute( "answer" ).trimmed(); + mAnswer = qdesc.attribute( QStringLiteral( "answer" ) ).trimmed(); } else { - QDomNode n = gnode.namedItem( "default" ); + QDomNode n = gnode.namedItem( QStringLiteral( "default" ) ); if ( !n.isNull() ) { QDomElement e = n.toElement(); @@ -73,26 +73,26 @@ QgsGrassModuleParam::QgsGrassModuleParam( QgsGrassModule *module, QString key, } } - if ( qdesc.attribute( "hidden" ) == "yes" ) + if ( qdesc.attribute( QStringLiteral( "hidden" ) ) == QLatin1String( "yes" ) ) { mHidden = true; } QString label, description; - if ( !qdesc.attribute( "label" ).isEmpty() ) + if ( !qdesc.attribute( QStringLiteral( "label" ) ).isEmpty() ) { - label = QApplication::translate( "grasslabel", qdesc.attribute( "label" ).trimmed().toUtf8() ); + label = QApplication::translate( "grasslabel", qdesc.attribute( QStringLiteral( "label" ) ).trimmed().toUtf8() ); } if ( label.isEmpty() ) { - QDomNode n = gnode.namedItem( "label" ); + QDomNode n = gnode.namedItem( QStringLiteral( "label" ) ); if ( !n.isNull() ) { QDomElement e = n.toElement(); label = module->translate( e.text() ); } } - QDomNode n = gnode.namedItem( "description" ); + QDomNode n = gnode.namedItem( QStringLiteral( "description" ) ); if ( !n.isNull() ) { QDomElement e = n.toElement(); @@ -109,11 +109,11 @@ QgsGrassModuleParam::QgsGrassModuleParam( QgsGrassModule *module, QString key, mTitle = description; } - mRequired = gnode.toElement().attribute( "required" ) == "yes"; + mRequired = gnode.toElement().attribute( QStringLiteral( "required" ) ) == QLatin1String( "yes" ); - mMultiple = gnode.toElement().attribute( "multiple" ) == "yes"; + mMultiple = gnode.toElement().attribute( QStringLiteral( "multiple" ) ) == QLatin1String( "yes" ); - mId = qdesc.attribute( "id" ); + mId = qdesc.attribute( QStringLiteral( "id" ) ); } QgsGrassModuleParam::~QgsGrassModuleParam() {} @@ -130,7 +130,7 @@ QStringList QgsGrassModuleParam::options() QString QgsGrassModuleParam::getDescPrompt( QDomElement descDomElement, const QString & name ) { - QDomNode gispromptNode = descDomElement.namedItem( "gisprompt" ); + QDomNode gispromptNode = descDomElement.namedItem( QStringLiteral( "gisprompt" ) ); if ( !gispromptNode.isNull() ) { @@ -154,9 +154,9 @@ QDomNode QgsGrassModuleParam::nodeByKey( QDomElement descDomElement, QString key if ( !e.isNull() ) { - if ( e.tagName() == "parameter" || e.tagName() == "flag" ) + if ( e.tagName() == QLatin1String( "parameter" ) || e.tagName() == QLatin1String( "flag" ) ) { - if ( e.attribute( "name" ) == key ) + if ( e.attribute( QStringLiteral( "name" ) ) == key ) { return n; } @@ -181,21 +181,21 @@ QList<QDomNode> QgsGrassModuleParam::nodesByType( QDomElement descDomElement, ST typeMap.insert( "dbname", G_OPT_DATABASE ); typeMap.insert( "dbcolumn", G_OPT_COLUMN ); #else - typeMap.insert( "dbtable", G_OPT_DB_TABLE ); - typeMap.insert( "dbdriver", G_OPT_DB_DRIVER ); - typeMap.insert( "dbname", G_OPT_DB_DATABASE ); - typeMap.insert( "dbcolumn", G_OPT_DB_COLUMN ); + typeMap.insert( QStringLiteral( "dbtable" ), G_OPT_DB_TABLE ); + typeMap.insert( QStringLiteral( "dbdriver" ), G_OPT_DB_DRIVER ); + typeMap.insert( QStringLiteral( "dbname" ), G_OPT_DB_DATABASE ); + typeMap.insert( QStringLiteral( "dbcolumn" ), G_OPT_DB_COLUMN ); #endif - typeMap.insert( "vector", G_OPT_V_INPUT ); + typeMap.insert( QStringLiteral( "vector" ), G_OPT_V_INPUT ); QDomNode n = descDomElement.firstChild(); while ( !n.isNull() ) { - QString prompt = getDescPrompt( n.toElement(), "prompt" ); + QString prompt = getDescPrompt( n.toElement(), QStringLiteral( "prompt" ) ); if ( typeMap.value( prompt ) == optionType ) { - if ( age.isEmpty() || getDescPrompt( n.toElement(), "age" ) == age ) + if ( age.isEmpty() || getDescPrompt( n.toElement(), QStringLiteral( "age" ) ) == age ) { nodes << n; } @@ -265,11 +265,11 @@ void QgsGrassModuleMultiParam::showAddRemoveButtons() mLayout->insertLayout( -1, mButtonsLayout ); // TODO: how to keep both buttons on the top? - QPushButton *addButton = new QPushButton( "+", this ); + QPushButton *addButton = new QPushButton( QStringLiteral( "+" ), this ); connect( addButton, SIGNAL( clicked() ), this, SLOT( addRow() ) ); mButtonsLayout->addWidget( addButton, 0, Qt::AlignTop ); - QPushButton *removeButton = new QPushButton( "-", this ); + QPushButton *removeButton = new QPushButton( QStringLiteral( "-" ), this ); connect( removeButton, SIGNAL( clicked() ), this, SLOT( removeRow() ) ); mButtonsLayout->addWidget( removeButton, 0, Qt::AlignTop ); @@ -302,23 +302,23 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, } // Is it output? - QDomNode promptNode = gnode.namedItem( "gisprompt" ); + QDomNode promptNode = gnode.namedItem( QStringLiteral( "gisprompt" ) ); if ( !promptNode.isNull() ) { QDomElement promptElem = promptNode.toElement(); - QString element = promptElem.attribute( "element" ); - QString age = promptElem.attribute( "age" ); + QString element = promptElem.attribute( QStringLiteral( "element" ) ); + QString age = promptElem.attribute( QStringLiteral( "age" ) ); - if ( age == "new" ) + if ( age == QLatin1String( "new" ) ) { mOutputElement = element; mIsOutput = true; - if ( element == "vector" ) + if ( element == QLatin1String( "vector" ) ) { mOutputType = Vector; } - else if ( element == "cell" ) + else if ( element == QLatin1String( "cell" ) ) { mOutputType = Raster; } @@ -334,7 +334,7 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, // outputType qgm attribute allows forcing an output type // Predefined values ? - QDomNode valuesNode = gnode.namedItem( "values" ); + QDomNode valuesNode = gnode.namedItem( QStringLiteral( "values" ) ); QDomElement valuesElem = valuesNode.toElement(); // null if valuesNode is null if ( !valuesNode.isNull() && valuesNode.childNodes().count() > 1 ) @@ -344,7 +344,7 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, // TODO: add add/removeRow support for ComboBox? // one or many? - if ( gelem.attribute( "multiple" ) == "yes" ) + if ( gelem.attribute( QStringLiteral( "multiple" ) ) == QLatin1String( "yes" ) ) { mControlType = CheckBoxes; } @@ -356,7 +356,7 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, } // List of values to be excluded - QStringList exclude = qdesc.attribute( "exclude" ).split( ',', QString::SkipEmptyParts ); + QStringList exclude = qdesc.attribute( QStringLiteral( "exclude" ) ).split( ',', QString::SkipEmptyParts ); QDomNode valueNode = valuesElem.firstChild(); @@ -364,10 +364,10 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, { QDomElement valueElem = valueNode.toElement(); - if ( !valueElem.isNull() && valueElem.tagName() == "value" ) + if ( !valueElem.isNull() && valueElem.tagName() == QLatin1String( "value" ) ) { - QDomNode n = valueNode.namedItem( "name" ); + QDomNode n = valueNode.namedItem( QStringLiteral( "name" ) ); if ( !n.isNull() ) { QDomElement e = n.toElement(); @@ -375,7 +375,7 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, if ( exclude.contains( val ) == 0 ) { - n = valueNode.namedItem( "description" ); + n = valueNode.namedItem( QStringLiteral( "description" ) ); QString desc; if ( !n.isNull() ) { @@ -419,18 +419,18 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, // Output option may have missing gisprompt if output may be both vector and raster according to other options (e.g. v.kernel) // outputType qgm attribute allow forcing an output type QgsDebugMsg( "outputType = " + qdesc.attribute( "outputType" ) ); - if ( qdesc.hasAttribute( "outputType" ) ) + if ( qdesc.hasAttribute( QStringLiteral( "outputType" ) ) ) { - QString outputType = qdesc.attribute( "outputType" ); + QString outputType = qdesc.attribute( QStringLiteral( "outputType" ) ); mIsOutput = true; - if ( outputType == "vector" ) + if ( outputType == QLatin1String( "vector" ) ) { - mOutputElement = "vector"; + mOutputElement = QStringLiteral( "vector" ); mOutputType = Vector; } - else if ( outputType == "raster" ) + else if ( outputType == QLatin1String( "raster" ) ) { - mOutputElement = "cell"; + mOutputElement = QStringLiteral( "cell" ); mOutputType = Raster; } else @@ -439,11 +439,11 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, } } - if ( gelem.attribute( "type" ) == "integer" ) + if ( gelem.attribute( QStringLiteral( "type" ) ) == QLatin1String( "integer" ) ) { mValueType = Integer; } - else if ( gelem.attribute( "type" ) == "float" ) + else if ( gelem.attribute( QStringLiteral( "type" ) ) == QLatin1String( "float" ) ) { mValueType = Double; } @@ -453,12 +453,12 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, { QDomNode valueNode = valuesElem.firstChild(); - QDomNode n = valueNode.namedItem( "name" ); + QDomNode n = valueNode.namedItem( QStringLiteral( "name" ) ); if ( !n.isNull() ) { QDomElement e = n.toElement(); QString val = e.text().trimmed(); - minMax = val.split( "-" ); + minMax = val.split( QStringLiteral( "-" ) ); if ( minMax.size() == 2 ) { mHaveLimits = true; @@ -468,7 +468,7 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, } } - QDomNode keydescNode = gnode.namedItem( "keydesc" ); + QDomNode keydescNode = gnode.namedItem( QStringLiteral( "keydesc" ) ); if ( !keydescNode.isNull() ) { // fixed number of line edits @@ -492,7 +492,7 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, else { addRow(); - if ( gelem.attribute( "multiple" ) == "yes" ) + if ( gelem.attribute( QStringLiteral( "multiple" ) ) == QLatin1String( "yes" ) ) { showAddRemoveButtons(); } @@ -501,10 +501,10 @@ QgsGrassModuleOption::QgsGrassModuleOption( QgsGrassModule *module, QString key, } mUsesRegion = false; - QString region = qdesc.attribute( "region" ); + QString region = qdesc.attribute( QStringLiteral( "region" ) ); if ( region.length() > 0 ) { - if ( region == "yes" ) + if ( region == QLatin1String( "yes" ) ) mUsesRegion = true; } else @@ -555,11 +555,11 @@ void QgsGrassModuleOption::addRow() QRegExp rx; if ( mOutputType == Vector ) { - rx.setPattern( "[A-Za-z_][A-Za-z0-9_]+" ); + rx.setPattern( QStringLiteral( "[A-Za-z_][A-Za-z0-9_]+" ) ); } else { - rx.setPattern( "[A-Za-z0-9_.]+" ); + rx.setPattern( QStringLiteral( "[A-Za-z0-9_.]+" ) ); } mValidator = new QRegExpValidator( rx, this ); @@ -598,16 +598,16 @@ void QgsGrassModuleOption::browse( bool checked ) Q_UNUSED( checked ); QSettings settings; - QString lastDir = settings.value( "/GRASS/lastDirectOutputDir", "" ).toString(); + QString lastDir = settings.value( QStringLiteral( "/GRASS/lastDirectOutputDir" ), "" ).toString(); QString fileName = QFileDialog::getSaveFileName( this, tr( "Output file" ), lastDir, tr( "GeoTIFF" ) + " (*.tif)" ); if ( !fileName.isEmpty() ) { - if ( !fileName.endsWith( ".tif", Qt::CaseInsensitive ) && !fileName.endsWith( ".tiff", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".tif" ), Qt::CaseInsensitive ) && !fileName.endsWith( QLatin1String( ".tiff" ), Qt::CaseInsensitive ) ) { fileName = fileName + ".tif"; } mLineEdits.at( 0 )->setText( fileName ); - settings.setValue( "/GRASS/lastDirectOutputDir", QFileInfo( fileName ).absolutePath() ); + settings.setValue( QStringLiteral( "/GRASS/lastDirectOutputDir" ), QFileInfo( fileName ).absolutePath() ); } } @@ -676,7 +676,7 @@ QString QgsGrassModuleOption::value() values.append( mValues[i] ); } } - value = values.join( "," ); + value = values.join( QStringLiteral( "," ) ); } return value; } @@ -777,13 +777,13 @@ QgsGrassModuleOption::~QgsGrassModuleOption() QgsGrassModuleFlag::QgsGrassModuleFlag( QgsGrassModule *module, QString key, QDomElement &qdesc, QDomElement &gdesc, QDomNode &gnode, bool direct, QWidget * parent ) - : QgsGrassModuleCheckBox( "", parent ), QgsGrassModuleParam( module, key, qdesc, gdesc, gnode, direct ) + : QgsGrassModuleCheckBox( QLatin1String( "" ), parent ), QgsGrassModuleParam( module, key, qdesc, gdesc, gnode, direct ) { if ( mHidden ) hide(); - if ( mAnswer == "on" ) + if ( mAnswer == QLatin1String( "on" ) ) setChecked( true ); else setChecked( false ); @@ -813,8 +813,8 @@ QgsGrassModuleGdalInput::QgsGrassModuleGdalInput( QDomElement &gdesc, QDomNode &gnode, bool direct, QWidget * parent ) : QgsGrassModuleGroupBoxItem( module, key, qdesc, gdesc, gnode, direct, parent ) , mType( type ) - , mOgrLayerOption( "" ) - , mOgrWhereOption( "" ) + , mOgrLayerOption( QLatin1String( "" ) ) + , mOgrWhereOption( QLatin1String( "" ) ) { if ( mTitle.isEmpty() ) { @@ -823,10 +823,10 @@ QgsGrassModuleGdalInput::QgsGrassModuleGdalInput( adjustTitle(); // Check if this parameter is required - mRequired = gnode.toElement().attribute( "required" ) == "yes"; + mRequired = gnode.toElement().attribute( QStringLiteral( "required" ) ) == QLatin1String( "yes" ); // Read "layeroption" is defined - QString opt = qdesc.attribute( "layeroption" ); + QString opt = qdesc.attribute( QStringLiteral( "layeroption" ) ); if ( ! opt.isNull() ) { @@ -843,7 +843,7 @@ QgsGrassModuleGdalInput::QgsGrassModuleGdalInput( } // Read "whereoption" if defined - opt = qdesc.attribute( "whereoption" ); + opt = qdesc.attribute( QStringLiteral( "whereoption" ) ); if ( !opt.isNull() ) { QDomNode optNode = nodeByKey( gdesc, opt ); @@ -907,7 +907,7 @@ void QgsGrassModuleGdalInput::updateQgisLayers() { QgsVectorLayer *vector = qobject_cast<QgsVectorLayer *>( layer ); if ( !vector || - ( vector->providerType() != "ogr" && vector->providerType() != "postgres" ) + ( vector->providerType() != QLatin1String( "ogr" ) && vector->providerType() != QLatin1String( "postgres" ) ) ) continue; @@ -916,7 +916,7 @@ void QgsGrassModuleGdalInput::updateQgisLayers() QString uri; QString ogrLayer; QString ogrWhere; - if ( vector->providerType() == "postgres" ) + if ( vector->providerType() == QLatin1String( "postgres" ) ) { // Construct OGR DSN QgsDataSourceUri dsUri( provider->dataSourceUri() ); @@ -932,44 +932,44 @@ void QgsGrassModuleGdalInput::updateQgisLayers() ogrLayer += dsUri.table(); ogrWhere = dsUri.sql(); } - else if ( vector->providerType() == "ogr" ) + else if ( vector->providerType() == QLatin1String( "ogr" ) ) { - QStringList items = provider->dataSourceUri().split( "|" ); + QStringList items = provider->dataSourceUri().split( QStringLiteral( "|" ) ); if ( items.size() > 1 ) { uri = items[0]; - ogrLayer = ""; - ogrWhere = ""; + ogrLayer = QLatin1String( "" ); + ogrWhere = QLatin1String( "" ); for ( int i = 1; i < items.size(); i++ ) { - QStringList args = items[i].split( "=" ); + QStringList args = items[i].split( QStringLiteral( "=" ) ); if ( args.size() != 2 ) continue; - if ( args[0] == "layername" && args[0] == "layerid" ) + if ( args[0] == QLatin1String( "layername" ) && args[0] == QLatin1String( "layerid" ) ) { ogrLayer = args[1]; } - else if ( args[0] == "subset" ) + else if ( args[0] == QLatin1String( "subset" ) ) { ogrWhere = args[1]; } } - if ( uri.endsWith( ".shp", Qt::CaseInsensitive ) ) + if ( uri.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) { - ogrLayer = ""; + ogrLayer = QLatin1String( "" ); } } else { uri = items[0]; - ogrLayer = ""; - ogrWhere = ""; + ogrLayer = QLatin1String( "" ); + ogrWhere = QLatin1String( "" ); } } @@ -991,8 +991,8 @@ void QgsGrassModuleGdalInput::updateQgisLayers() if ( layer->name() == current ) mLayerComboBox->setItemText( mLayerComboBox->currentIndex(), current ); mUri.push_back( uri ); - mOgrLayers.push_back( "" ); - mOgrWheres.push_back( "" ); + mOgrLayers.push_back( QLatin1String( "" ) ); + mOgrWheres.push_back( QLatin1String( "" ) ); } } } @@ -1011,7 +1011,7 @@ QStringList QgsGrassModuleGdalInput::options() { QString uri = mUri[current]; - if ( uri.startsWith( "PG:" ) && uri.contains( "password=" ) && !mLayerPassword->text().isEmpty() ) + if ( uri.startsWith( QLatin1String( "PG:" ) ) && uri.contains( QLatin1String( "password=" ) ) && !mLayerPassword->text().isEmpty() ) { uri += " password=" + mLayerPassword->text(); } @@ -1073,7 +1073,7 @@ QString QgsGrassModuleGdalInput::ready() void QgsGrassModuleGdalInput::changed( int i ) { - mLayerPassword->setEnabled( i < mUri.size() && mUri.value( i ).startsWith( "PG:" ) && !mUri.value( i ).contains( "password=" ) ); + mLayerPassword->setEnabled( i < mUri.size() && mUri.value( i ).startsWith( QLatin1String( "PG:" ) ) && !mUri.value( i ).contains( QLatin1String( "password=" ) ) ); } QgsGrassModuleGdalInput::~QgsGrassModuleGdalInput() @@ -1114,12 +1114,12 @@ QgsGrassModuleVectorField::QgsGrassModuleVectorField( } adjustTitle(); - QDomNode promptNode = gnode.namedItem( "gisprompt" ); + QDomNode promptNode = gnode.namedItem( QStringLiteral( "gisprompt" ) ); QDomElement gelem = gnode.toElement(); - mType = qdesc.attribute( "type" ); + mType = qdesc.attribute( QStringLiteral( "type" ) ); - mLayerKey = qdesc.attribute( "layer" ); + mLayerKey = qdesc.attribute( QStringLiteral( "layer" ) ); if ( mLayerKey.isNull() || mLayerKey.length() == 0 ) { mErrors << tr( "'layer' attribute in field tag with key= %1 is missing." ).arg( mKey ); @@ -1136,7 +1136,7 @@ QgsGrassModuleVectorField::QgsGrassModuleVectorField( } addRow(); - if ( gelem.attribute( "multiple" ) == "yes" ) + if ( gelem.attribute( QStringLiteral( "multiple" ) ) == QLatin1String( "yes" ) ) { showAddRemoveButtons(); } @@ -1210,7 +1210,7 @@ QStringList QgsGrassModuleVectorField::options() if ( !valueList.isEmpty() ) { - QString opt = mKey + "=" + valueList.join( "," ); + QString opt = mKey + "=" + valueList.join( QStringLiteral( "," ) ); list << opt; } @@ -1238,12 +1238,12 @@ QgsGrassModuleSelection::QgsGrassModuleSelection( } adjustTitle(); - QDomNode promptNode = gnode.namedItem( "gisprompt" ); + QDomNode promptNode = gnode.namedItem( QStringLiteral( "gisprompt" ) ); QDomElement promptElem = promptNode.toElement(); - mLayerId = qdesc.attribute( "layerid" ); + mLayerId = qdesc.attribute( QStringLiteral( "layerid" ) ); - mType = qdesc.attribute( "type" ); + mType = qdesc.attribute( QStringLiteral( "type" ) ); QgsGrassModuleParam *item = mModuleStandardOptions->item( mLayerId ); // TODO check type @@ -1283,11 +1283,11 @@ void QgsGrassModuleSelection::onLayerChanged() Q_FOREACH ( QgsMapLayer *layer, QgsMapLayerRegistry::instance()->mapLayers().values() ) { QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer ); - if ( vectorLayer && vectorLayer->providerType() == "grass" ) + if ( vectorLayer && vectorLayer->providerType() == QLatin1String( "grass" ) ) { QString uri = vectorLayer->dataProvider()->dataSourceUri(); QgsDebugMsg( "uri = " + uri ); - QString layerCode = uri.split( "/" ).last(); + QString layerCode = uri.split( QStringLiteral( "/" ) ).last(); if ( mLayerInput->currentLayerCodes().contains( layerCode ) ) { // Qt::UserRole+1 may be also uri (AddLayer) but hardly matching layer id @@ -1376,7 +1376,7 @@ void QgsGrassModuleSelection::onModeChanged() QString name = mModeComboBox->itemData( index, Qt::UserRole + 2 ).toString(); QgsDebugMsg( "uri = " + uri ); - QgsVectorLayer *layer = new QgsVectorLayer( uri, name, "grass" ); + QgsVectorLayer *layer = new QgsVectorLayer( uri, name, QStringLiteral( "grass" ) ); QgsMapLayerRegistry::instance()->addMapLayer( layer ); onLayerChanged(); // update with added layer } @@ -1426,14 +1426,14 @@ void QgsGrassModuleSelection::onLayerSelectionChanged() } else if ( range ) // close range and next cat { - list += QString( "-%1,%2" ).arg( last ).arg( cat ); + list += QStringLiteral( "-%1,%2" ).arg( last ).arg( cat ); range = false; } else // next cat { if ( !list.isEmpty() ) { - list += ","; + list += QLatin1String( "," ); } list += QString::number( cat ); } @@ -1441,7 +1441,7 @@ void QgsGrassModuleSelection::onLayerSelectionChanged() } if ( range ) { - list += QString( "-%1" ).arg( last ); + list += QStringLiteral( "-%1" ).arg( last ); } mLineEdit->setText( list ); @@ -1479,27 +1479,27 @@ QgsGrassModuleFile::QgsGrassModuleFile( } adjustTitle(); - if ( qdesc.attribute( "type" ).toLower() == "new" ) + if ( qdesc.attribute( QStringLiteral( "type" ) ).toLower() == QLatin1String( "new" ) ) { mType = New; } - if ( qdesc.attribute( "type" ).toLower() == "multiple" ) + if ( qdesc.attribute( QStringLiteral( "type" ) ).toLower() == QLatin1String( "multiple" ) ) { mType = Multiple; } - if ( qdesc.attribute( "type" ).toLower() == "directory" ) + if ( qdesc.attribute( QStringLiteral( "type" ) ).toLower() == QLatin1String( "directory" ) ) { mType = Directory; } - mFilters = qdesc.attribute( "filters" ); + mFilters = qdesc.attribute( QStringLiteral( "filters" ) ); - mFileOption = qdesc.attribute( "fileoption" ); + mFileOption = qdesc.attribute( QStringLiteral( "fileoption" ) ); QHBoxLayout *l = new QHBoxLayout( this ); mLineEdit = new QLineEdit(); - mBrowseButton = new QPushButton( "..." ); + mBrowseButton = new QPushButton( QStringLiteral( "..." ) ); l->addWidget( mLineEdit ); l->addWidget( mBrowseButton ); @@ -1537,7 +1537,7 @@ void QgsGrassModuleFile::browse() if ( mType == Multiple ) { - QString path = mLineEdit->text().split( "," ).first(); + QString path = mLineEdit->text().split( QStringLiteral( "," ) ).first(); if ( path.isEmpty() ) path = lastDir; else @@ -1549,7 +1549,7 @@ void QgsGrassModuleFile::browse() lastDir = QFileInfo( files[0] ).absolutePath(); - mLineEdit->setText( files.join( "," ) ); + mLineEdit->setText( files.join( QStringLiteral( "," ) ) ); } else { diff --git a/src/plugins/grass/qgsgrassnewmapset.cpp b/src/plugins/grass/qgsgrassnewmapset.cpp index 05a58d7c3113..79867a5be147 100644 --- a/src/plugins/grass/qgsgrassnewmapset.cpp +++ b/src/plugins/grass/qgsgrassnewmapset.cpp @@ -78,7 +78,7 @@ QgsGrassNewMapset::QgsGrassNewMapset( QgisInterface *iface, mPreviousPage = -1; mRegionModified = false; - QString mapPath = ":/images/grass/world.png"; + QString mapPath = QStringLiteral( ":/images/grass/world.png" ); QgsDebugMsg( QString( "mapPath = %1" ).arg( mapPath ) ); //mPixmap = QPixmap( *(mRegionMap->pixmap()) ); @@ -96,7 +96,7 @@ QgsGrassNewMapset::QgsGrassNewMapset( QgisInterface *iface, // DATABASE QSettings settings; - QString gisdbase = settings.value( "/GRASS/lastGisdbase" ).toString(); + QString gisdbase = settings.value( QStringLiteral( "/GRASS/lastGisdbase" ) ).toString(); if ( gisdbase.isEmpty() ) { gisdbase = QDir::homePath() + QDir::separator() + "grassdata"; @@ -117,16 +117,16 @@ QgsGrassNewMapset::QgsGrassNewMapset( QgisInterface *iface, mMapsetsListView->header()->setResizeMode( QHeaderView::ResizeToContents ); // FINISH - mOpenNewMapsetCheckBox->setChecked( settings.value( "/GRASS/newMapsetWizard/openMapset", true ).toBool() ); + mOpenNewMapsetCheckBox->setChecked( settings.value( QStringLiteral( "/GRASS/newMapsetWizard/openMapset" ), true ).toBool() ); connect( this, SIGNAL( currentIdChanged( int ) ), SLOT( pageSelected( int ) ) ); - restoreGeometry( settings.value( "/Windows/QgsGrassNewMapset/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsGrassNewMapset/geometry" ) ).toByteArray() ); } QgsGrassNewMapset::~QgsGrassNewMapset() { QSettings settings; - settings.setValue( "/Windows/QgsGrassNewMapset/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/QgsGrassNewMapset/geometry" ), saveGeometry() ); mRunning = false; } /*************************** DATABASE *******************************/ @@ -146,7 +146,7 @@ void QgsGrassNewMapset::databaseChanged() { QSettings settings; - settings.setValue( "/GRASS/lastGisdbase", mDatabaseLineEdit->text() ); + settings.setValue( QStringLiteral( "/GRASS/lastGisdbase" ), mDatabaseLineEdit->text() ); button( QWizard::NextButton )->setEnabled( false ); setError( mDatabaseErrorLabel ); @@ -172,7 +172,7 @@ void QgsGrassNewMapset::databaseChanged() QDir dir( gisdbase() ); for ( unsigned int i = 0; i < dir.count(); i++ ) { - if ( dir[i] == "." || dir[i] == ".." ) + if ( dir[i] == QLatin1String( "." ) || dir[i] == QLatin1String( ".." ) ) continue; QString windName = gisdbase() + "/" + dir[i] + "/PERMANENT/DEFAULT_WIND"; @@ -222,7 +222,7 @@ void QgsGrassNewMapset::setLocations() mLocationComboBox->clear(); QSettings settings; - QString lastLocation = settings.value( "/GRASS/lastLocation" ).toString(); + QString lastLocation = settings.value( QStringLiteral( "/GRASS/lastLocation" ) ).toString(); if ( gisdbaseExists() ) { @@ -234,7 +234,7 @@ void QgsGrassNewMapset::setLocations() int sel = -1; for ( unsigned int i = 0; i < gisdbaseDir.count(); i++ ) { - if ( gisdbaseDir[i] == "." || gisdbaseDir[i] == ".." ) + if ( gisdbaseDir[i] == QLatin1String( "." ) || gisdbaseDir[i] == QLatin1String( ".." ) ) continue; QString windName = mDatabaseLineEdit->text() + "/" + gisdbaseDir[i] + "/PERMANENT/DEFAULT_WIND"; @@ -600,24 +600,24 @@ void QgsGrassNewMapset::setGrassRegionDefaults() } else if ( mCellHead.proj == PROJECTION_XY ) { - mNorthLineEdit->setText( "1000" ); - mSouthLineEdit->setText( "0" ); - mEastLineEdit->setText( "1000" ); - mWestLineEdit->setText( "0" ); + mNorthLineEdit->setText( QStringLiteral( "1000" ) ); + mSouthLineEdit->setText( QStringLiteral( "0" ) ); + mEastLineEdit->setText( QStringLiteral( "1000" ) ); + mWestLineEdit->setText( QStringLiteral( "0" ) ); } else if ( mCellHead.proj == PROJECTION_LL ) { - mNorthLineEdit->setText( "90" ); - mSouthLineEdit->setText( "-90" ); - mEastLineEdit->setText( "180" ); - mWestLineEdit->setText( "-180" ); + mNorthLineEdit->setText( QStringLiteral( "90" ) ); + mSouthLineEdit->setText( QStringLiteral( "-90" ) ); + mEastLineEdit->setText( QStringLiteral( "180" ) ); + mWestLineEdit->setText( QStringLiteral( "-180" ) ); } else { - mNorthLineEdit->setText( "100000" ); - mSouthLineEdit->setText( "-100000" ); - mEastLineEdit->setText( "100000" ); - mWestLineEdit->setText( "-100000" ); + mNorthLineEdit->setText( QStringLiteral( "100000" ) ); + mSouthLineEdit->setText( QStringLiteral( "-100000" ) ); + mEastLineEdit->setText( QStringLiteral( "100000" ) ); + mWestLineEdit->setText( QStringLiteral( "-100000" ) ); } mRegionModified = false; } @@ -711,7 +711,7 @@ void QgsGrassNewMapset::loadRegions() return; } - QDomDocument doc( "gml:FeatureCollection" ); + QDomDocument doc( QStringLiteral( "gml:FeatureCollection" ) ); QString err; int line, column; @@ -726,7 +726,7 @@ void QgsGrassNewMapset::loadRegions() } QDomElement docElem = doc.documentElement(); - QDomNodeList nodes = docElem.elementsByTagName( "gml:featureMember" ); + QDomNodeList nodes = docElem.elementsByTagName( QStringLiteral( "gml:featureMember" ) ); for ( int i = 0; i < nodes.count(); i++ ) { @@ -738,7 +738,7 @@ void QgsGrassNewMapset::loadRegions() } QDomElement elem = node.toElement(); - QDomNodeList nameNodes = elem.elementsByTagName( "gml:name" ); + QDomNodeList nameNodes = elem.elementsByTagName( QStringLiteral( "gml:name" ) ); if ( nameNodes.count() == 0 ) continue; if ( nameNodes.item( 0 ).isNull() ) @@ -748,14 +748,14 @@ void QgsGrassNewMapset::loadRegions() if ( nameElem.text().isNull() ) continue; - QDomNodeList envNodes = elem.elementsByTagName( "gml:Envelope" ); + QDomNodeList envNodes = elem.elementsByTagName( QStringLiteral( "gml:Envelope" ) ); if ( envNodes.count() == 0 ) continue; if ( envNodes.item( 0 ).isNull() ) continue; QDomElement envElem = envNodes.item( 0 ).toElement(); - QDomNodeList coorNodes = envElem.elementsByTagName( "gml:coordinates" ); + QDomNodeList coorNodes = envElem.elementsByTagName( QStringLiteral( "gml:coordinates" ) ); if ( coorNodes.count() == 0 ) continue; if ( coorNodes.item( 0 ).isNull() ) @@ -764,15 +764,15 @@ void QgsGrassNewMapset::loadRegions() if ( coorElem.text().isNull() ) continue; - QStringList coor = coorElem.text().split( " ", QString::SkipEmptyParts ); + QStringList coor = coorElem.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); if ( coor.size() != 2 ) { QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) ); continue; } - QStringList ll = coor[0].split( ",", QString::SkipEmptyParts ); - QStringList ur = coor[1].split( ",", QString::SkipEmptyParts ); + QStringList ll = coor[0].split( QStringLiteral( "," ), QString::SkipEmptyParts ); + QStringList ur = coor[1].split( QStringLiteral( "," ), QString::SkipEmptyParts ); if ( ll.size() != 2 || ur.size() != 2 ) { QgsDebugMsg( QString( "Cannot parse coordinates: %1" ).arg( coorElem.text() ) ); @@ -1130,7 +1130,7 @@ void QgsGrassNewMapset::setMapsets() // Add all subdirs containing WIND for ( unsigned int i = 0; i < d.count(); i++ ) { - if ( d[i] == "." || d[i] == ".." ) + if ( d[i] == QLatin1String( "." ) || d[i] == QLatin1String( ".." ) ) continue; QString mapsetPath = locationPath + "/" + d[i]; @@ -1182,7 +1182,7 @@ void QgsGrassNewMapset::on_mOpenNewMapsetCheckBox_stateChanged( int state ) { Q_UNUSED( state ); QSettings settings; - settings.setValue( "/GRASS/newMapsetWizard/openMapset", mOpenNewMapsetCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/GRASS/newMapsetWizard/openMapset" ), mOpenNewMapsetCheckBox->isChecked() ); } void QgsGrassNewMapset::setFinishPage() @@ -1255,7 +1255,7 @@ void QgsGrassNewMapset::createMapset() setLocations(); mSelectLocationRadioButton->setChecked( true ); mLocationComboBox->setItemText( mLocationComboBox->currentIndex(), location ); - mLocationLineEdit->setText( "" ); + mLocationLineEdit->setText( QLatin1String( "" ) ); locationRadioSwitched(); // calls also checkLocation() } else @@ -1266,7 +1266,7 @@ void QgsGrassNewMapset::createMapset() // Create mapset QString mapset = mMapsetLineEdit->text(); - if ( mapset != "PERMANENT" ) + if ( mapset != QLatin1String( "PERMANENT" ) ) { QString error; QgsGrass::createMapset( gisdbase(), location, mapset, error ); @@ -1323,7 +1323,7 @@ void QgsGrassNewMapset::setError( QLabel *line, const QString &err ) } else { - line->setText( "" ); + line->setText( QLatin1String( "" ) ); line->hide(); } } diff --git a/src/plugins/grass/qgsgrassplugin.cpp b/src/plugins/grass/qgsgrassplugin.cpp index 200e83364eb9..65aa9024d808 100644 --- a/src/plugins/grass/qgsgrassplugin.cpp +++ b/src/plugins/grass/qgsgrassplugin.cpp @@ -61,7 +61,7 @@ static const QString pluginName = QObject::tr( "GRASS %1" ).arg( GRASS_VERSION_M static const QString pluginDescription = QObject::tr( "GRASS %1 (Geographic Resources Analysis Support System)" ).arg( GRASS_VERSION_MAJOR ); static const QString pluginCategory = QObject::tr( "Plugins" ); static const QString pluginVersion = QObject::tr( "Version 2.0" ); -static const QString pluginIcon = ":/images/themes/default/grass/grass_tools.png"; +static const QString pluginIcon = QStringLiteral( ":/images/themes/default/grass/grass_tools.png" ); /** * Constructor for the plugin. The plugin is passed a pointer to the main app @@ -153,23 +153,23 @@ void QgsGrassPlugin::initGui() // Create the action for tool (the icons are set later by calling setCurrentTheme) mOpenMapsetAction = new QAction( QIcon(), tr( "Open Mapset" ), this ); - mOpenMapsetAction->setObjectName( "mOpenMapsetAction" ); + mOpenMapsetAction->setObjectName( QStringLiteral( "mOpenMapsetAction" ) ); mNewMapsetAction = new QAction( QIcon(), tr( "New Mapset" ), this ); - mNewMapsetAction->setObjectName( "mNewMapsetAction" ); + mNewMapsetAction->setObjectName( QStringLiteral( "mNewMapsetAction" ) ); mCloseMapsetAction = new QAction( QIcon(), tr( "Close Mapset" ), this ); - mCloseMapsetAction->setObjectName( "mCloseMapsetAction" ); + mCloseMapsetAction->setObjectName( QStringLiteral( "mCloseMapsetAction" ) ); mOpenToolsAction = new QAction( QIcon(), tr( "Open GRASS Tools" ), this ); - mOpenToolsAction->setObjectName( "mAddPolygonActionmOpenToolsAction" ); + mOpenToolsAction->setObjectName( QStringLiteral( "mAddPolygonActionmOpenToolsAction" ) ); mOpenToolsAction->setWhatsThis( tr( "Open GRASS tools" ) ); mRegionAction = new QAction( QIcon(), tr( "Display Current Grass Region" ), this ); - mRegionAction->setObjectName( "mRegionAction" ); + mRegionAction->setObjectName( QStringLiteral( "mRegionAction" ) ); mRegionAction->setWhatsThis( tr( "Displays the current GRASS region as a rectangle on the map canvas" ) ); mRegionAction->setCheckable( true ); mOptionsAction = new QAction( QIcon(), tr( "GRASS Options" ), this ); - mOptionsAction->setObjectName( "mOptionsAction" ); + mOptionsAction->setObjectName( QStringLiteral( "mOptionsAction" ) ); // Connect the actions connect( mOpenMapsetAction, SIGNAL( triggered() ), this, SLOT( openMapset() ) ); @@ -190,7 +190,7 @@ void QgsGrassPlugin::initGui() // Add the toolbar to the main window mToolBarPointer = qGisInterface->addToolBar( tr( "GRASS" ) ); - mToolBarPointer->setObjectName( "GRASS" ); + mToolBarPointer->setObjectName( QStringLiteral( "GRASS" ) ); // Add to the toolbar #if 0 @@ -203,24 +203,24 @@ void QgsGrassPlugin::initGui() mToolBarPointer->addAction( mRegionAction ); // Editing - mAddPointAction = new QAction( QgsApplication::getThemeIcon( "/mActionCapturePoint.svg" ), tr( "Add Point" ), this ); - mAddPointAction->setObjectName( "mAddPointAction" ); + mAddPointAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePoint.svg" ) ), tr( "Add Point" ), this ); + mAddPointAction->setObjectName( QStringLiteral( "mAddPointAction" ) ); mAddPointAction->setCheckable( true ); - mAddLineAction = new QAction( QgsApplication::getThemeIcon( "/mActionCaptureLine.svg" ), tr( "Add Line" ), this ); - mAddLineAction->setObjectName( "mAddLineAction" ); + mAddLineAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCaptureLine.svg" ) ), tr( "Add Line" ), this ); + mAddLineAction->setObjectName( QStringLiteral( "mAddLineAction" ) ); mAddLineAction->setCheckable( true ); - mAddBoundaryAction = new QAction( getThemeIcon( "mActionCaptureBoundary.png" ), tr( "Add Boundary" ), this ); - mAddBoundaryAction->setObjectName( "mAddBoundaryAction" ); + mAddBoundaryAction = new QAction( getThemeIcon( QStringLiteral( "mActionCaptureBoundary.png" ) ), tr( "Add Boundary" ), this ); + mAddBoundaryAction->setObjectName( QStringLiteral( "mAddBoundaryAction" ) ); mAddBoundaryAction->setCheckable( true ); - mAddCentroidAction = new QAction( getThemeIcon( "mActionCaptureCentroid.png" ), tr( "Add Centroid" ), this ); - mAddCentroidAction->setObjectName( "mAddCentroidAction" ); + mAddCentroidAction = new QAction( getThemeIcon( QStringLiteral( "mActionCaptureCentroid.png" ) ), tr( "Add Centroid" ), this ); + mAddCentroidAction->setObjectName( QStringLiteral( "mAddCentroidAction" ) ); mAddCentroidAction->setCheckable( true ); - mAddAreaAction = new QAction( QgsApplication::getThemeIcon( "/mActionCapturePolygon.svg" ), tr( "Add Closed Boundary" ), this ); - mAddAreaAction->setObjectName( "mAddAreaAction" ); + mAddAreaAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePolygon.svg" ) ), tr( "Add Closed Boundary" ), this ); + mAddAreaAction->setObjectName( QStringLiteral( "mAddAreaAction" ) ); mAddAreaAction->setCheckable( true ); connect( mAddPointAction, SIGNAL( triggered() ), SLOT( addFeature() ) ); @@ -264,7 +264,7 @@ void QgsGrassPlugin::initGui() connect( qgis, SIGNAL( newProject() ), this, SLOT( newProject() ) ); // Set icons to current theme - setCurrentTheme( "" ); + setCurrentTheme( QLatin1String( "" ) ); // Connect theme change signal connect( qGisInterface, SIGNAL( currentThemeChanged( QString ) ), this, SLOT( setCurrentTheme( QString ) ) ); @@ -290,9 +290,9 @@ void QgsGrassPlugin::initGui() qGisInterface->addDockWidget( Qt::RightDockWidgetArea, mTools ); // add edit renderer immediately so that if project was saved during editing, the layer can be loaded - if ( !QgsRendererRegistry::instance()->renderersList().contains( "grassEdit" ) ) + if ( !QgsRendererRegistry::instance()->renderersList().contains( QStringLiteral( "grassEdit" ) ) ) { - QgsRendererRegistry::instance()->addRenderer( new QgsRendererMetadata( "grassEdit", + QgsRendererRegistry::instance()->addRenderer( new QgsRendererMetadata( QStringLiteral( "grassEdit" ), QObject::tr( "GRASS edit" ), QgsGrassEditRenderer::create, QIcon( QgsApplication::defaultThemePath() + "rendererGrassSymbol.svg" ), @@ -402,7 +402,7 @@ void QgsGrassPlugin::onEditingStarted() // Because the edit style may be stored to project: // - do not translate because it may be loaded in QGIS running with different language // - do not change the name until really necessary because it could not be found in project - QString editStyleName = "GRASS Edit"; // should not be translated + QString editStyleName = QStringLiteral( "GRASS Edit" ); // should not be translated if ( vectorLayer->styleManager()->styles().contains( editStyleName ) ) { @@ -437,7 +437,7 @@ void QgsGrassPlugin::onEditingStopped() if ( vectorLayer ) { QString style = mOldStyles.value( vectorLayer ); - if ( vectorLayer->styleManager()->currentStyle() == "GRASS Edit" ) // not changed by user + if ( vectorLayer->styleManager()->currentStyle() == QLatin1String( "GRASS Edit" ) ) // not changed by user { QgsDebugMsg( "reset style to " + style ); vectorLayer->styleManager()->setCurrentStyle( style ); @@ -464,7 +464,7 @@ void QgsGrassPlugin::onFieldsChanged() } QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer ); - if ( vectorLayer && vectorLayer->providerType() == "grass" && vectorLayer->dataProvider() ) + if ( vectorLayer && vectorLayer->providerType() == QLatin1String( "grass" ) && vectorLayer->dataProvider() ) { if ( vectorLayer->dataProvider()->dataSourceUri().startsWith( uri ) ) { @@ -553,7 +553,7 @@ void QgsGrassPlugin::mapsetChanged() mCloseMapsetAction->setEnabled( true ); QSettings settings; - bool on = settings.value( "/GRASS/region/on", true ).toBool(); + bool on = settings.value( QStringLiteral( "/GRASS/region/on" ), true ).toBool(); mRegionAction->setChecked( on ); switchRegion( on ); @@ -592,8 +592,8 @@ void QgsGrassPlugin::newVector() QString name; QgsGrassElementDialog dialog( qGisInterface->mainWindow() ); - name = dialog.getItem( "vector", tr( "New vector name" ), - tr( "New vector name" ), "", "", &ok ); + name = dialog.getItem( QStringLiteral( "vector" ), tr( "New vector name" ), + tr( "New vector name" ), QLatin1String( "" ), QLatin1String( "" ), &ok ); if ( !ok ) return; @@ -633,7 +633,7 @@ void QgsGrassPlugin::newVector() + QgsGrass::getDefaultMapset() + "/" + name + "/0_point"; - QgsVectorLayer* layer = new QgsVectorLayer( uri, name, "grass" ); + QgsVectorLayer* layer = new QgsVectorLayer( uri, name, QStringLiteral( "grass" ) ); if ( !layer ) { @@ -648,7 +648,7 @@ void QgsGrassPlugin::newVector() void QgsGrassPlugin::onNewLayer( QString uri, QString name ) { QgsDebugMsg( "uri = " + uri + " name = " + name ); - QgsVectorLayer* vectorLayer = qGisInterface->addVectorLayer( uri, name, "grass" ); + QgsVectorLayer* vectorLayer = qGisInterface->addVectorLayer( uri, name, QStringLiteral( "grass" ) ); if ( vectorLayer ) { vectorLayer->startEditing(); @@ -702,7 +702,7 @@ void QgsGrassPlugin::switchRegion( bool on ) { QSettings settings; - settings.setValue( "/GRASS/region/on", on ); + settings.setValue( QStringLiteral( "/GRASS/region/on" ), on ); if ( on ) { @@ -761,12 +761,12 @@ void QgsGrassPlugin::projectRead() bool ok; QString gisdbase = QgsProject::instance()->readPath( QgsProject::instance()->readEntry( - "GRASS", "/WorkingGisdbase", "", &ok ).trimmed() + QStringLiteral( "GRASS" ), QStringLiteral( "/WorkingGisdbase" ), QLatin1String( "" ), &ok ).trimmed() ); QString location = QgsProject::instance()->readEntry( - "GRASS", "/WorkingLocation", "", &ok ).trimmed(); + QStringLiteral( "GRASS" ), QStringLiteral( "/WorkingLocation" ), QLatin1String( "" ), &ok ).trimmed(); QString mapset = QgsProject::instance()->readEntry( - "GRASS", "/WorkingMapset", "", &ok ).trimmed(); + QStringLiteral( "GRASS" ), QStringLiteral( "/WorkingMapset" ), QLatin1String( "" ), &ok ).trimmed(); if ( gisdbase.isEmpty() || location.isEmpty() || mapset.isEmpty() ) { @@ -839,7 +839,7 @@ void QgsGrassPlugin::unload() } QgsVectorLayer *vectorLayer = qobject_cast<QgsVectorLayer *>( layer ); - if ( vectorLayer && vectorLayer->providerType() == "grass" ) + if ( vectorLayer && vectorLayer->providerType() == QLatin1String( "grass" ) ) { disconnect( vectorLayer, SIGNAL( editingStarted() ), this, SLOT( onEditingStarted() ) ); disconnect( vectorLayer, SIGNAL( editingStopped() ), this, SLOT( onEditingStopped() ) ); @@ -886,12 +886,12 @@ void QgsGrassPlugin::setCurrentTheme( QString theThemeName ) Q_UNUSED( theThemeName ); if ( mToolBarPointer ) { - mOpenMapsetAction->setIcon( getThemeIcon( "grass_open_mapset.png" ) ); - mNewMapsetAction->setIcon( getThemeIcon( "grass_new_mapset.png" ) ); - mCloseMapsetAction->setIcon( getThemeIcon( "grass_close_mapset.png" ) ); - mOpenToolsAction->setIcon( getThemeIcon( "grass_tools.png" ) ); - mRegionAction->setIcon( getThemeIcon( "grass_region.png" ) ); - mOptionsAction->setIcon( QgsApplication::getThemeIcon( "propertyicons/general.svg" ) ); + mOpenMapsetAction->setIcon( getThemeIcon( QStringLiteral( "grass_open_mapset.png" ) ) ); + mNewMapsetAction->setIcon( getThemeIcon( QStringLiteral( "grass_new_mapset.png" ) ) ); + mCloseMapsetAction->setIcon( getThemeIcon( QStringLiteral( "grass_close_mapset.png" ) ) ); + mOpenToolsAction->setIcon( getThemeIcon( QStringLiteral( "grass_tools.png" ) ) ); + mRegionAction->setIcon( getThemeIcon( QStringLiteral( "grass_region.png" ) ) ); + mOptionsAction->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "propertyicons/general.svg" ) ) ); } } diff --git a/src/plugins/grass/qgsgrassselect.cpp b/src/plugins/grass/qgsgrassselect.cpp index e4b1d335863c..0324367a4451 100644 --- a/src/plugins/grass/qgsgrassselect.cpp +++ b/src/plugins/grass/qgsgrassselect.cpp @@ -56,14 +56,14 @@ QgsGrassSelect::QgsGrassSelect( QWidget *parent, int type ) else { QSettings settings; - lastGisdbase = settings.value( "/GRASS/lastGisdbase" ).toString(); + lastGisdbase = settings.value( QStringLiteral( "/GRASS/lastGisdbase" ) ).toString(); //check we got something from qsettings otherwise default to users home dir if ( lastGisdbase.isEmpty() ) { QDir home = QDir::home(); lastGisdbase = QString( home.path() ); } - lastMapset = settings.value( "/GRASS/lastMapset" ).toString(); + lastMapset = settings.value( QStringLiteral( "/GRASS/lastMapset" ) ).toString(); } first = false; } @@ -131,7 +131,7 @@ void QgsGrassSelect::setLocations() // Add all subdirs containing PERMANENT/DEFAULT_WIND for ( unsigned int i = 0; i < d.count(); i++ ) { - if ( d[i] == "." || d[i] == ".." ) + if ( d[i] == QLatin1String( "." ) || d[i] == QLatin1String( ".." ) ) continue; QString ldpath = egisdbase->text() + "/" + d[i]; @@ -287,7 +287,7 @@ void QgsGrassSelect::setMaps() for ( unsigned int j = 0; j < md.count(); j++ ) { - if ( md[j] == "." || md[j] == ".." ) + if ( md[j] == QLatin1String( "." ) || md[j] == QLatin1String( ".." ) ) continue; QString m = QString( md[j] + " (GROUP)" ); @@ -425,7 +425,7 @@ void QgsGrassSelect::accept() //write to qgsettings as gisdbase seems to be valid QSettings settings; - settings.setValue( "/GRASS/lastGisdbase", lastGisdbase ); + settings.setValue( QStringLiteral( "/GRASS/lastGisdbase" ), lastGisdbase ); location = elocation->currentText(); lastLocation = location; @@ -433,7 +433,7 @@ void QgsGrassSelect::accept() mapset = emapset->currentText(); lastMapset = mapset; - settings.setValue( "/GRASS/lastMapset", lastMapset ); + settings.setValue( QStringLiteral( "/GRASS/lastMapset" ), lastMapset ); map = emap->currentText().trimmed(); @@ -459,9 +459,9 @@ void QgsGrassSelect::accept() else if ( type == QgsGrassSelect::RASTER ) { lastRasterMap = map; - if ( map.indexOf( " (GROUP)" ) != -1 ) + if ( map.indexOf( QLatin1String( " (GROUP)" ) ) != -1 ) { - map.remove( " (GROUP)" ); + map.remove( QStringLiteral( " (GROUP)" ) ); selectedType = QgsGrassSelect::GROUP; } else diff --git a/src/plugins/grass/qgsgrassshell.cpp b/src/plugins/grass/qgsgrassshell.cpp index 33b5c1467be6..189ac0c54e92 100644 --- a/src/plugins/grass/qgsgrassshell.cpp +++ b/src/plugins/grass/qgsgrassshell.cpp @@ -71,7 +71,7 @@ QgsGrassShell::QgsGrassShell( QgsGrassTools *tools, QTabWidget *parent, const ch // QTermWidget does set default font family Monospace, size 10 via QWidget::setFont() // but QWidget::setFont() does not guarantee to really change the font (see doc) // setStyleSheet() works (it is applied to QTermWidget children TerminalDisplay) - mTerminal->setStyleSheet( "font-family: Monospace; font-size: 10pt;" ); + mTerminal->setStyleSheet( QStringLiteral( "font-family: Monospace; font-size: 10pt;" ) ); } QgsGrassShell::~QgsGrassShell() @@ -97,8 +97,8 @@ void QgsGrassShell::closeShell() void QgsGrassShell::initTerminal( QTermWidget *terminal ) { - QStringList env( "" ); - QStringList args( "" ); + QStringList env( QLatin1String( "" ) ); + QStringList args( QLatin1String( "" ) ); // GRASS Init.sh should not be started here, it is either run when GRASS is started if QGIS is run from GRASS shell or everything (set environment variables and lock mapset) is done in QgsGrass::openMapset //QString shellProgram = QString( "%1/etc/Init.sh" ).arg( ::getenv( "GISBASE" ) ); @@ -111,13 +111,13 @@ void QgsGrassShell::initTerminal( QTermWidget *terminal ) env << "PATH=" + path; env << "PYTHONPATH=" + QgsGrass::getPythonPath(); - env << "TERM=vt100"; - env << "GISRC_MODE_MEMORY"; + env << QStringLiteral( "TERM=vt100" ); + env << QStringLiteral( "GISRC_MODE_MEMORY" ); // TODO: we should check if these environment variable were set by user before QGIS was started env << "GRASS_HTML_BROWSER=" + QgsGrassUtils::htmlBrowserPath() ; - env << "GRASS_WISH=wish"; - env << "GRASS_TCLSH=tclsh"; - env << "GRASS_PYTHON=python"; + env << QStringLiteral( "GRASS_WISH=wish" ); + env << QStringLiteral( "GRASS_TCLSH=tclsh" ); + env << QStringLiteral( "GRASS_PYTHON=python" ); //args << "-text"; //args << QString( "%1/%2/%3" ).arg( QgsGrass::getDefaultGisdbase() ).arg( QgsGrass::getDefaultLocation() ).arg( QgsGrass::getDefaultMapset() ); diff --git a/src/plugins/grass/qgsgrasstools.cpp b/src/plugins/grass/qgsgrasstools.cpp index 5bb840f9238d..a26dd3ba1ed6 100644 --- a/src/plugins/grass/qgsgrasstools.cpp +++ b/src/plugins/grass/qgsgrasstools.cpp @@ -157,7 +157,7 @@ QgsGrassTools::QgsGrassTools( QgisInterface *iface, QWidget * parent, const char Q_UNUSED( name ); QgsDebugMsg( "QgsGrassTools()" ); setupUi( this ); - QPushButton * closeMapsetButton = new QPushButton( QgsApplication::getThemeIcon( "mActionFileExit.png" ), tr( "Close mapset" ), this ); + QPushButton * closeMapsetButton = new QPushButton( QgsApplication::getThemeIcon( QStringLiteral( "mActionFileExit.png" ) ), tr( "Close mapset" ), this ); mTabWidget->setCornerWidget( closeMapsetButton ); connect( closeMapsetButton, SIGNAL( clicked() ), SLOT( closeMapset() ) ); @@ -269,7 +269,7 @@ void QgsGrassTools::runModule( QString name, bool direct ) #endif QWidget *m; - if ( name == "shell" ) + if ( name == QLatin1String( "shell" ) ) { #ifdef Q_OS_WIN QgsGrass::putEnv( "GRASS_HTML_BROWSER", QgsGrassUtils::htmlBrowserPath() ); @@ -309,7 +309,7 @@ void QgsGrassTools::runModule( QString name, bool direct ) QApplication::restoreOverrideCursor(); if ( !gmod->errors().isEmpty() ) { - QgsGrass::warning( gmod->errors().join( "\n" ) ); + QgsGrass::warning( gmod->errors().join( QStringLiteral( "\n" ) ) ); } m = qobject_cast<QWidget *>( gmod ); } @@ -330,7 +330,7 @@ void QgsGrassTools::runModule( QString name, bool direct ) QIcon is; is.addPixmap( pixmap ); - mTabWidget->addTab( m, is, "" ); + mTabWidget->addTab( m, is, QLatin1String( "" ) ); } else { @@ -380,7 +380,7 @@ bool QgsGrassTools::loadConfig( QString filePath, QStandardItemModel *treeModel, return false; } - QDomDocument doc( "qgisgrass" ); + QDomDocument doc( QStringLiteral( "qgisgrass" ) ); QString err; int line, column; if ( !doc.setContent( &file, &err, &line, &column ) ) @@ -394,7 +394,7 @@ bool QgsGrassTools::loadConfig( QString filePath, QStandardItemModel *treeModel, } QDomElement docElem = doc.documentElement(); - QDomNodeList modulesNodes = docElem.elementsByTagName( "modules" ); + QDomNodeList modulesNodes = docElem.elementsByTagName( QStringLiteral( "modules" ) ); if ( modulesNodes.count() == 0 ) { @@ -451,7 +451,7 @@ void QgsGrassTools::addModules( QStandardItem *parent, QDomElement &element, QSt { // QgsDebugMsg(QString("tag = %1").arg(e.tagName())); - if ( e.tagName() != "section" && e.tagName() != "grass" ) + if ( e.tagName() != QLatin1String( "section" ) && e.tagName() != QLatin1String( "grass" ) ) { QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) ); continue; @@ -459,26 +459,26 @@ void QgsGrassTools::addModules( QStandardItem *parent, QDomElement &element, QSt // Check GRASS version QStringList errors; - if ( !QgsGrassModuleOption::checkVersion( e.attribute( "version_min" ), e.attribute( "version_max" ), errors ) ) + if ( !QgsGrassModuleOption::checkVersion( e.attribute( QStringLiteral( "version_min" ) ), e.attribute( QStringLiteral( "version_max" ) ), errors ) ) { // TODO: show somehow errors only in debug mode, but without reloading tree if ( !errors.isEmpty() ) { - QString label = e.attribute( "label" ) + e.attribute( "name" ); // one should be non empty - label += "\n ERROR:\t" + errors.join( "\n\t" ); + QString label = e.attribute( QStringLiteral( "label" ) ) + e.attribute( QStringLiteral( "name" ) ); // one should be non empty + label += "\n ERROR:\t" + errors.join( QStringLiteral( "\n\t" ) ); QStandardItem *item = new QStandardItem( label ); item->setData( label, Qt::UserRole + Label ); item->setData( label, Qt::UserRole + Search ); - item->setData( QgsApplication::getThemeIcon( "mIconWarning.svg" ), Qt::DecorationRole ); + item->setData( QgsApplication::getThemeIcon( QStringLiteral( "mIconWarning.svg" ) ), Qt::DecorationRole ); appendItem( treeModel, parent, item ); } n = n.nextSibling(); continue; } - if ( e.tagName() == "section" ) + if ( e.tagName() == QLatin1String( "section" ) ) { - QString label = QApplication::translate( "grasslabel", e.attribute( "label" ).toUtf8() ); + QString label = QApplication::translate( "grasslabel", e.attribute( QStringLiteral( "label" ) ).toUtf8() ); QgsDebugMsg( QString( "label = %1" ).arg( label ) ); QStandardItem *item = new QStandardItem( label ); item->setData( label, Qt::UserRole + Label ); // original label, for debug @@ -487,9 +487,9 @@ void QgsGrassTools::addModules( QStandardItem *parent, QDomElement &element, QSt addModules( item, e, treeModel, modulesListModel, direct ); appendItem( treeModel, parent, item ); } - else if ( e.tagName() == "grass" ) + else if ( e.tagName() == QLatin1String( "grass" ) ) { // GRASS module - QString name = e.attribute( "name" ); + QString name = e.attribute( QStringLiteral( "name" ) ); QgsDebugMsgLevel( QString( "name = %1" ).arg( name ), 1 ); //QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name; @@ -620,14 +620,14 @@ void QgsGrassTools::closeEvent( QCloseEvent *e ) void QgsGrassTools::restorePosition() { QSettings settings; - restoreGeometry( settings.value( "/GRASS/windows/tools/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/GRASS/windows/tools/geometry" ) ).toByteArray() ); show(); } void QgsGrassTools::saveWindowLocation() { QSettings settings; - settings.setValue( "/GRASS/windows/tools/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/GRASS/windows/tools/geometry" ), saveGeometry() ); } void QgsGrassTools::emitRegionChanged() @@ -739,7 +739,7 @@ int QgsGrassTools::debug( QStandardItem *item ) if ( errors > 0 ) { label += " ( " + tr( "%1 errors" ).arg( errors ) + " )"; - item->setIcon( QgsApplication::getThemeIcon( "mIconWarning.svg" ) ); + item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconWarning.svg" ) ) ); } else { @@ -750,7 +750,7 @@ int QgsGrassTools::debug( QStandardItem *item ) } else // module { - if ( name == "shell" ) + if ( name == QLatin1String( "shell" ) ) { return 0; } @@ -759,7 +759,7 @@ int QgsGrassTools::debug( QStandardItem *item ) Q_FOREACH ( QString error, module->errors() ) { // each error may have multiple rows and may be html formated (<br>) - label += "\n ERROR:\t" + error.replace( "<br>", "\n" ).replace( "\n", "\n\t" ); + label += "\n ERROR:\t" + error.replace( QLatin1String( "<br>" ), QLatin1String( "\n" ) ).replace( QLatin1String( "\n" ), QLatin1String( "\n\t" ) ); } item->setText( label ); int nErrors = module->errors().size(); @@ -780,12 +780,12 @@ void QgsGrassTools::on_mViewModeButton_clicked() { mListView->hide(); mTreeView->show(); - mViewModeButton->setIcon( QgsApplication::getThemeIcon( "mIconListView.png" ) ); + mViewModeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconListView.png" ) ) ); } else { mTreeView->hide(); mListView->show(); - mViewModeButton->setIcon( QgsApplication::getThemeIcon( "mIconTreeView.png" ) ); + mViewModeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconTreeView.png" ) ) ); } } diff --git a/src/plugins/grass/qgsgrassutils.cpp b/src/plugins/grass/qgsgrassutils.cpp index 1f1d8e4f0cb6..0de87b7f951e 100644 --- a/src/plugins/grass/qgsgrassutils.cpp +++ b/src/plugins/grass/qgsgrassutils.cpp @@ -60,7 +60,7 @@ void QgsGrassUtils::addVectorLayers( QgisInterface *iface, QgsDebugMsg( QString( "uri = %1" ).arg( uri.toLocal8Bit().constData() ) ); QgsDebugMsg( QString( "name = %1" ).arg( name.toLocal8Bit().constData() ) ); - iface->addVectorLayer( uri, name, "grass" ); + iface->addVectorLayer( uri, name, QStringLiteral( "grass" ) ); } } @@ -113,20 +113,20 @@ QString QgsGrassElementDialog::getItem( QString element, mLineEdit = new QLineEdit( text ); QRegExp rx; - if ( element == "vector" ) + if ( element == QLatin1String( "vector" ) ) { - rx.setPattern( "[A-Za-z_][A-Za-z0-9_]+" ); + rx.setPattern( QStringLiteral( "[A-Za-z_][A-Za-z0-9_]+" ) ); } else { - rx.setPattern( "[A-Za-z0-9_.]+" ); + rx.setPattern( QStringLiteral( "[A-Za-z0-9_.]+" ) ); } QRegExpValidator *val = new QRegExpValidator( rx, this ); mLineEdit->setValidator( val ); layout->addWidget( mLineEdit ); - mErrorLabel = new QLabel( "X" ); + mErrorLabel = new QLabel( QStringLiteral( "X" ) ); layout->addWidget( mErrorLabel ); // Intention: keep fixed size - but it does not help mErrorLabel->adjustSize(); @@ -160,7 +160,7 @@ void QgsGrassElementDialog::textChanged() QString text = mLineEdit->text().trimmed(); - mErrorLabel->setText( " " ); + mErrorLabel->setText( QStringLiteral( " " ) ); mOkButton->setText( tr( "Ok" ) ); mOkButton->setEnabled( true ); diff --git a/src/plugins/grass/qtermwidget/ColorScheme.cpp b/src/plugins/grass/qtermwidget/ColorScheme.cpp index 200b9916a5b0..9b6c74c1f2f8 100644 --- a/src/plugins/grass/qtermwidget/ColorScheme.cpp +++ b/src/plugins/grass/qtermwidget/ColorScheme.cpp @@ -272,10 +272,10 @@ qreal ColorScheme::opacity() const { return _opacity; } void ColorScheme::read(const QString & fileName) { QSettings s(fileName, QSettings::IniFormat); - s.beginGroup("General"); + s.beginGroup(QStringLiteral("General")); - _description = s.value("Description", QObject::tr("Un-named Color Scheme")).toString(); - _opacity = s.value("Opacity",qreal(1.0)).toDouble(); + _description = s.value(QStringLiteral("Description"), QObject::tr("Un-named Color Scheme")).toString(); + _opacity = s.value(QStringLiteral("Opacity"),qreal(1.0)).toDouble(); s.endGroup(); for (int i=0 ; i < TABLE_COLORS ; i++) @@ -333,7 +333,7 @@ void ColorScheme::readColorEntry(QSettings * s , int index) ColorEntry entry; - QStringList rgbList = s->value("Color", QStringList()).toStringList(); + QStringList rgbList = s->value(QStringLiteral("Color"), QStringList()).toStringList(); if (rgbList.count() != 3) { Q_ASSERT(0); @@ -344,20 +344,20 @@ void ColorScheme::readColorEntry(QSettings * s , int index) b = rgbList[2].toInt(); entry.color = QColor(r, g, b); - entry.transparent = s->value("Transparent",false).toBool(); + entry.transparent = s->value(QStringLiteral("Transparent"),false).toBool(); // Deprecated key from KDE 4.0 which set 'Bold' to true to force // a color to be bold or false to use the current format // // TODO - Add a new tri-state key which allows for bold, normal or // current format - if (s->contains("Bold")) - entry.fontWeight = s->value("Bold",false).toBool() ? ColorEntry::Bold : + if (s->contains(QStringLiteral("Bold"))) + entry.fontWeight = s->value(QStringLiteral("Bold"),false).toBool() ? ColorEntry::Bold : ColorEntry::UseCurrentFormat; - quint16 hue = s->value("MaxRandomHue",0).toInt(); - quint8 value = s->value("MaxRandomValue",0).toInt(); - quint8 saturation = s->value("MaxRandomSaturation",0).toInt(); + quint16 hue = s->value(QStringLiteral("MaxRandomHue"),0).toInt(); + quint8 value = s->value(QStringLiteral("MaxRandomValue"),0).toInt(); + quint8 saturation = s->value(QStringLiteral("MaxRandomSaturation"),0).toInt(); setColorTableEntry( index , entry ); @@ -500,7 +500,7 @@ bool KDE3ColorSchemeReader::readColorLine(const QString& line,ColorScheme* schem if (list.count() != 7) return false; - if (list.first() != "color") + if (list.first() != QLatin1String("color")) return false; int index = list[1].toInt(); @@ -689,7 +689,7 @@ QList<QString> ColorSchemeManager::listKDE3ColorSchemes() QString dname(get_color_schemes_dir()); QDir dir(dname); QStringList filters; - filters << "*.schema"; + filters << QStringLiteral("*.schema"); dir.setNameFilters(filters); QStringList list = dir.entryList(filters); QStringList ret; @@ -706,7 +706,7 @@ QList<QString> ColorSchemeManager::listColorSchemes() QString dname(get_color_schemes_dir()); QDir dir(dname); QStringList filters; - filters << "*.colorscheme"; + filters << QStringLiteral("*.colorscheme"); dir.setNameFilters(filters); QStringList list = dir.entryList(filters); QStringList ret; diff --git a/src/plugins/grass/qtermwidget/Filter.cpp b/src/plugins/grass/qtermwidget/Filter.cpp index fd41a3b6dd14..8b7d22e4441f 100644 --- a/src/plugins/grass/qtermwidget/Filter.cpp +++ b/src/plugins/grass/qtermwidget/Filter.cpp @@ -364,7 +364,7 @@ void RegExpFilter::process() // ignore any regular expressions which match an empty string. // otherwise the while loop below will run indefinitely - static const QString emptyString(""); + static const QString emptyString(QLatin1String("")); if ( _searchText.exactMatch(emptyString) ) return; @@ -449,19 +449,19 @@ void UrlFilter::HotSpot::activate(const QString& actionName) const UrlType kind = urlType(); - if ( actionName == "copy-action" ) + if ( actionName == QLatin1String("copy-action") ) { QApplication::clipboard()->setText(url); return; } - if ( actionName.isEmpty() || actionName == "open-action" ) + if ( actionName.isEmpty() || actionName == QLatin1String("open-action") ) { if ( kind == StandardUrl ) { // if the URL path does not include the protocol ( eg. "www.kde.org" ) then // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) - if (!url.contains("://")) + if (!url.contains(QLatin1String("://"))) { url.prepend("http://"); } @@ -542,8 +542,8 @@ QList<QAction*> UrlFilter::HotSpot::actions() // object names are set here so that the hotspot performs the // correct action when activated() is called with the triggered // action passed as a parameter. - openAction->setObjectName( QLatin1String("open-action" )); - copyAction->setObjectName( QLatin1String("copy-action" )); + openAction->setObjectName( QStringLiteral("open-action" )); + copyAction->setObjectName( QStringLiteral("copy-action" )); QObject::connect( openAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); QObject::connect( copyAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); diff --git a/src/plugins/grass/qtermwidget/KeyboardTranslator.cpp b/src/plugins/grass/qtermwidget/KeyboardTranslator.cpp index 66e1a4e1f6f2..f104711d489a 100644 --- a/src/plugins/grass/qtermwidget/KeyboardTranslator.cpp +++ b/src/plugins/grass/qtermwidget/KeyboardTranslator.cpp @@ -68,7 +68,7 @@ void KeyboardTranslatorManager::findTranslators() { QDir dir(get_kb_layout_dir()); QStringList filters; - filters << "*.keytab"; + filters << QStringLiteral("*.keytab"); dir.setNameFilters(filters); QStringList list = dir.entryList(filters); list = dir.entryList(filters); @@ -158,13 +158,13 @@ const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator() { // Try to find the default.keytab file if it exists, otherwise // fall back to the hard-coded one - const KeyboardTranslator* translator = findTranslator("default"); + const KeyboardTranslator* translator = findTranslator(QStringLiteral("default")); if (!translator) { QBuffer textBuffer; textBuffer.setData(defaultTranslatorText); textBuffer.open(QIODevice::ReadOnly); - translator = loadTranslator(&textBuffer,"fallback"); + translator = loadTranslator(&textBuffer,QStringLiteral("fallback")); } return translator; } @@ -309,17 +309,17 @@ void KeyboardTranslatorReader::readNext() bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) { - if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) + if ( text.compare(QLatin1String("erase"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::EraseCommand; - else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrollpageup"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageUpCommand; - else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrollpagedown"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageDownCommand; - else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrolllineup"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineUpCommand; - else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrolllinedown"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineDownCommand; - else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrolllock"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLockCommand; else return false; @@ -404,15 +404,15 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) { - if ( item == "shift" ) + if ( item == QLatin1String("shift") ) modifier = Qt::ShiftModifier; - else if ( item == "ctrl" || item == "control" ) + else if ( item == QLatin1String("ctrl") || item == QLatin1String("control") ) modifier = Qt::ControlModifier; - else if ( item == "alt" ) + else if ( item == QLatin1String("alt") ) modifier = Qt::AltModifier; - else if ( item == "meta" ) + else if ( item == QLatin1String("meta") ) modifier = Qt::MetaModifier; - else if ( item == "keypad" ) + else if ( item == QLatin1String("keypad") ) modifier = Qt::KeypadModifier; else return false; @@ -421,17 +421,17 @@ bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::Keyboar } bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) { - if ( item == "appcukeys" || item == "appcursorkeys" ) + if ( item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys") ) flag = KeyboardTranslator::CursorKeysState; - else if ( item == "ansi" ) + else if ( item == QLatin1String("ansi") ) flag = KeyboardTranslator::AnsiState; - else if ( item == "newline" ) + else if ( item == QLatin1String("newline") ) flag = KeyboardTranslator::NewLineState; - else if ( item == "appscreen" ) + else if ( item == QLatin1String("appscreen") ) flag = KeyboardTranslator::AlternateScreenState; - else if ( item == "anymod" || item == "anymodifier" ) + else if ( item == QLatin1String("anymod") || item == QLatin1String("anymodifier") ) flag = KeyboardTranslator::AnyModifierState; - else if ( item == "appkeypad" ) + else if ( item == QLatin1String("appkeypad") ) flag = KeyboardTranslator::ApplicationKeypadState; else return false; @@ -451,9 +451,9 @@ bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode } } // additional cases implemented for backwards compatibility with KDE 3 - else if ( item == "prior" ) + else if ( item == QLatin1String("prior") ) keyCode = Qt::Key_PageUp; - else if ( item == "next" ) + else if ( item == QLatin1String("next") ) keyCode = Qt::Key_PageDown; else return false; @@ -472,7 +472,7 @@ bool KeyboardTranslatorReader::hasNextEntry() KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , const QString& result ) { - QString entryString("keyboard \"temporary\"\nkey "); + QString entryString(QStringLiteral("keyboard \"temporary\"\nkey ")); entryString.append(condition); entryString.append(" : "); @@ -736,15 +736,15 @@ void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) c item += '-'; if ( modifier == Qt::ShiftModifier ) - item += "Shift"; + item += QLatin1String("Shift"); else if ( modifier == Qt::ControlModifier ) - item += "Ctrl"; + item += QLatin1String("Ctrl"); else if ( modifier == Qt::AltModifier ) - item += "Alt"; + item += QLatin1String("Alt"); else if ( modifier == Qt::MetaModifier ) - item += "Meta"; + item += QLatin1String("Meta"); else if ( modifier == Qt::KeypadModifier ) - item += "KeyPad"; + item += QLatin1String("KeyPad"); } void KeyboardTranslator::Entry::insertState( QString& item , int state ) const { @@ -757,34 +757,34 @@ void KeyboardTranslator::Entry::insertState( QString& item , int state ) const item += '-' ; if ( state == KeyboardTranslator::AlternateScreenState ) - item += "AppScreen"; + item += QLatin1String("AppScreen"); else if ( state == KeyboardTranslator::NewLineState ) - item += "NewLine"; + item += QLatin1String("NewLine"); else if ( state == KeyboardTranslator::AnsiState ) - item += "Ansi"; + item += QLatin1String("Ansi"); else if ( state == KeyboardTranslator::CursorKeysState ) - item += "AppCursorKeys"; + item += QLatin1String("AppCursorKeys"); else if ( state == KeyboardTranslator::AnyModifierState ) - item += "AnyModifier"; + item += QLatin1String("AnyModifier"); else if ( state == KeyboardTranslator::ApplicationKeypadState ) - item += "AppKeypad"; + item += QLatin1String("AppKeypad"); } QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { if ( !_text.isEmpty() ) return escapedText(expandWildCards,modifiers); else if ( _command == EraseCommand ) - return "Erase"; + return QStringLiteral("Erase"); else if ( _command == ScrollPageUpCommand ) - return "ScrollPageUp"; + return QStringLiteral("ScrollPageUp"); else if ( _command == ScrollPageDownCommand ) - return "ScrollPageDown"; + return QStringLiteral("ScrollPageDown"); else if ( _command == ScrollLineUpCommand ) - return "ScrollLineUp"; + return QStringLiteral("ScrollLineUp"); else if ( _command == ScrollLineDownCommand ) - return "ScrollLineDown"; + return QStringLiteral("ScrollLineDown"); else if ( _command == ScrollLockCommand ) - return "ScrollLock"; + return QStringLiteral("ScrollLock"); return QString(); } diff --git a/src/plugins/grass/qtermwidget/Pty.cpp b/src/plugins/grass/qtermwidget/Pty.cpp index bec018ed81c6..87d8bc12d740 100644 --- a/src/plugins/grass/qtermwidget/Pty.cpp +++ b/src/plugins/grass/qtermwidget/Pty.cpp @@ -172,7 +172,7 @@ int Pty::start(const QString& program, addEnvironmentVariables(environment); - setEnv("WINDOWID", QString::number(winid)); + setEnv(QStringLiteral("WINDOWID"), QString::number(winid)); // unless the LANGUAGE environment variable has been set explicitly // set it to a null string @@ -185,7 +185,7 @@ int Pty::start(const QString& program, // does not have a translation for // // BR:149300 - setEnv("LANGUAGE",QString(),false /* do not overwrite existing value if any */); + setEnv(QStringLiteral("LANGUAGE"),QString(),false /* do not overwrite existing value if any */); setUseUtmp(addToUtmp); diff --git a/src/plugins/grass/qtermwidget/Session.cpp b/src/plugins/grass/qtermwidget/Session.cpp index c28ea48602c0..3c237cd8bbed 100644 --- a/src/plugins/grass/qtermwidget/Session.cpp +++ b/src/plugins/grass/qtermwidget/Session.cpp @@ -296,7 +296,7 @@ void Session::run() // here we expect full path. If there is no fullpath let's expect it's // a custom shell (eg. python, etc.) available in the PATH. - if (exec.startsWith("/")) + if (exec.startsWith(QLatin1String("/"))) { QFile excheck(exec); if ( exec.isEmpty() || !excheck.exists() ) { @@ -305,13 +305,13 @@ void Session::run() excheck.setFileName(exec); if ( exec.isEmpty() || !excheck.exists() ) { - exec = "/bin/sh"; + exec = QStringLiteral("/bin/sh"); } } // _arguments sometimes contain ("") so isEmpty() // or count() does not work as expected... - QString argsTmp(_arguments.join(" ").trimmed()); + QString argsTmp(_arguments.join(QStringLiteral(" ")).trimmed()); QStringList arguments; arguments << exec; if (argsTmp.length()) diff --git a/src/plugins/grass/qtermwidget/TerminalCharacterDecoder.cpp b/src/plugins/grass/qtermwidget/TerminalCharacterDecoder.cpp index b267b37cc358..dd62785d0e40 100644 --- a/src/plugins/grass/qtermwidget/TerminalCharacterDecoder.cpp +++ b/src/plugins/grass/qtermwidget/TerminalCharacterDecoder.cpp @@ -124,7 +124,7 @@ void HTMLDecoder::begin(QTextStream* output) QString text; //open monospace span - openSpan(text,"font-family:monospace"); + openSpan(text,QStringLiteral("font-family:monospace")); *output << text; } @@ -188,11 +188,11 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP //colours - a colour table must have been defined first if ( _colorTable ) { - style.append( QString("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) ); + style.append( QStringLiteral("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) ); if (!characters[i].isTransparent(_colorTable)) { - style.append( QString("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) ); + style.append( QStringLiteral("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) ); } } @@ -237,7 +237,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP } void HTMLDecoder::openSpan(QString& text , const QString& style) { - text.append( QString("<span style=\"%1\">").arg(style) ); + text.append( QStringLiteral("<span style=\"%1\">").arg(style) ); } void HTMLDecoder::closeSpan(QString& text) diff --git a/src/plugins/grass/qtermwidget/TerminalDisplay.cpp b/src/plugins/grass/qtermwidget/TerminalDisplay.cpp index 3d932d95333a..b6834ae62511 100644 --- a/src/plugins/grass/qtermwidget/TerminalDisplay.cpp +++ b/src/plugins/grass/qtermwidget/TerminalDisplay.cpp @@ -318,7 +318,7 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) ,_preserveLineBreaks(false) ,_columnSelectionMode(false) ,_scrollbarLocation(NoScrollBar) -,_wordCharacters(":@-./_~") +,_wordCharacters(QStringLiteral(":@-./_~")) ,_bellMode(SystemBeepBell) ,_blinking(false) ,_hasBlinker(false) @@ -1148,18 +1148,18 @@ void TerminalDisplay::showResizeNotification() } if (!_resizeWidget) { - _resizeWidget = new QLabel("Size: XXX x XXX", this); - _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width("Size: XXX x XXX")); + _resizeWidget = new QLabel(QStringLiteral("Size: XXX x XXX"), this); + _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(QStringLiteral("Size: XXX x XXX"))); _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); _resizeWidget->setAlignment(Qt::AlignCenter); - _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)"); + _resizeWidget->setStyleSheet(QStringLiteral("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)")); _resizeTimer = new QTimer(this); _resizeTimer->setSingleShot(true); connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide())); } - QString sizeStr = QString("Size: %1 x %2").arg(_columns).arg(_lines); + QString sizeStr = QStringLiteral("Size: %1 x %2").arg(_columns).arg(_lines); _resizeWidget->setText(sizeStr); _resizeWidget->move((width()-_resizeWidget->width())/2, (height()-_resizeWidget->height())/2+20); @@ -1799,7 +1799,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); if (spot && spot->type() == Filter::HotSpot::Link) - spot->activate("open-action"); + spot->activate(QStringLiteral("open-action")); } } else if ( ev->button() == Qt::MidButton ) @@ -2945,7 +2945,7 @@ QSize TerminalDisplay::sizeHint() const void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) { - if (event->mimeData()->hasFormat("text/plain")) + if (event->mimeData()->hasFormat(QStringLiteral("text/plain"))) event->acceptProposedAction(); if (event->mimeData()->urls().count()) event->acceptProposedAction(); diff --git a/src/plugins/grass/qtermwidget/kprocess.cpp b/src/plugins/grass/qtermwidget/kprocess.cpp index 73264a611f94..204701c8b96f 100644 --- a/src/plugins/grass/qtermwidget/kprocess.cpp +++ b/src/plugins/grass/qtermwidget/kprocess.cpp @@ -165,7 +165,7 @@ void KProcess::setNextOpenMode(QIODevice::OpenMode mode) void KProcess::clearEnvironment() { - setEnvironment(QStringList() << QString::fromLatin1(DUMMYENV)); + setEnvironment(QStringList() << QStringLiteral(DUMMYENV)); } void KProcess::setEnv(const QString &name, const QString &value, bool overwrite) @@ -173,7 +173,7 @@ void KProcess::setEnv(const QString &name, const QString &value, bool overwrite) QStringList env = environment(); if (env.isEmpty()) { env = systemEnvironment(); - env.removeAll(QString::fromLatin1(DUMMYENV)); + env.removeAll(QStringLiteral(DUMMYENV)); } QString fname(name); fname.append(QLatin1Char('=')); @@ -194,7 +194,7 @@ void KProcess::unsetEnv(const QString &name) QStringList env = environment(); if (env.isEmpty()) { env = systemEnvironment(); - env.removeAll(QString::fromLatin1(DUMMYENV)); + env.removeAll(QStringLiteral(DUMMYENV)); } QString fname(name); fname.append(QLatin1Char('=')); @@ -202,7 +202,7 @@ void KProcess::unsetEnv(const QString &name) if ((*it).startsWith(fname)) { env.erase(it); if (env.isEmpty()) - env.append(QString::fromLatin1(DUMMYENV)); + env.append(QStringLiteral(DUMMYENV)); setEnvironment(env); return; } diff --git a/src/plugins/grass/qtermwidget/kptydevice.cpp b/src/plugins/grass/qtermwidget/kptydevice.cpp index 37ecce8c9c5e..0445947bf52c 100644 --- a/src/plugins/grass/qtermwidget/kptydevice.cpp +++ b/src/plugins/grass/qtermwidget/kptydevice.cpp @@ -130,7 +130,7 @@ bool KPtyDevicePrivate::_k_canRead() } if (readBytes < 0) { readBuffer.unreserve(available); - q->setErrorString("Error reading from PTY"); + q->setErrorString(QStringLiteral("Error reading from PTY")); return false; } readBuffer.unreserve(available - readBytes); // *should* be a no-op @@ -164,7 +164,7 @@ bool KPtyDevicePrivate::_k_canWrite() write(q->masterFd(), writeBuffer.readPointer(), writeBuffer.readSize())); if (wroteBytes < 0) { - q->setErrorString("Error writing to PTY"); + q->setErrorString(QStringLiteral("Error writing to PTY")); return false; } writeBuffer.free(wroteBytes); @@ -249,7 +249,7 @@ bool KPtyDevicePrivate::doWait(int msecs, bool reading) break; return false; case 0: - q->setErrorString("PTY operation timed out"); + q->setErrorString(QStringLiteral("PTY operation timed out")); return false; default: if (FD_ISSET(q->masterFd(), &rfds)) { @@ -305,7 +305,7 @@ bool KPtyDevice::open(OpenMode mode) return true; if (!KPty::open()) { - setErrorString("Error opening PTY"); + setErrorString(QStringLiteral("Error opening PTY")); return false; } @@ -319,7 +319,7 @@ bool KPtyDevice::open(int fd, OpenMode mode) Q_D(KPtyDevice); if (!KPty::open(fd)) { - setErrorString("Error opening PTY"); + setErrorString(QStringLiteral("Error opening PTY")); return false; } diff --git a/src/plugins/grass/qtermwidget/qtermwidget.cpp b/src/plugins/grass/qtermwidget/qtermwidget.cpp index 9245a16a3118..8fbbf58881b2 100644 --- a/src/plugins/grass/qtermwidget/qtermwidget.cpp +++ b/src/plugins/grass/qtermwidget/qtermwidget.cpp @@ -64,7 +64,7 @@ Session *TermWidgetImpl::createSession(QWidget* parent) { Session *session = new Session(parent); - session->setTitle(Session::NameRole, "QTermWidget"); + session->setTitle(Session::NameRole, QStringLiteral("QTermWidget")); /* Thats a freaking bad idea!!!! * /bin/bash is not there on every system @@ -79,7 +79,7 @@ Session *TermWidgetImpl::createSession(QWidget* parent) - QStringList args(""); + QStringList args(QLatin1String("")); session->setArguments(args); session->setAutoClose(true); @@ -90,7 +90,7 @@ Session *TermWidgetImpl::createSession(QWidget* parent) session->setDarkBackground(true); - session->setKeyBindings(""); + session->setKeyBindings(QLatin1String("")); return session; } @@ -289,7 +289,7 @@ void QTermWidget::init(int startnow) // m_impl->m_terminalDisplay->setSize(80, 40); QFont font = QApplication::font(); - font.setFamily("Monospace"); + font.setFamily(QStringLiteral("Monospace")); font.setPointSize(10); font.setStyleHint(QFont::TypeWriter); setTerminalFont(font); @@ -355,7 +355,7 @@ QString QTermWidget::workingDirectory() // Christian Surlykke: On linux we could look at /proc/<pid>/cwd which should be a link to current // working directory (<pid>: process id of the shell). I don't know about BSD. // Maybe we could just offer it when running linux, for a start. - QDir d(QString("/proc/%1/cwd").arg(getShellPID())); + QDir d(QStringLiteral("/proc/%1/cwd").arg(getShellPID())); if (!d.exists()) { qDebug() << "Cannot find" << d.dirName(); diff --git a/src/plugins/grass/qtermwidget/tools.cpp b/src/plugins/grass/qtermwidget/tools.cpp index 487495d4d403..5dd8bc88efb7 100644 --- a/src/plugins/grass/qtermwidget/tools.cpp +++ b/src/plugins/grass/qtermwidget/tools.cpp @@ -16,7 +16,7 @@ QString get_kb_layout_dir() #else // qDebug() << __FILE__ << __FUNCTION__; - QString rval = ""; + QString rval = QLatin1String(""); QString k(KB_LAYOUT_DIR); QDir d(k); @@ -54,7 +54,7 @@ QString get_color_schemes_dir() #else // qDebug() << __FILE__ << __FUNCTION__; - QString rval = ""; + QString rval = QLatin1String(""); QString k(COLORSCHEMES_DIR); QDir d(k); diff --git a/src/plugins/heatmap/heatmap.cpp b/src/plugins/heatmap/heatmap.cpp index ab97545ccc95..9f7898f48e05 100644 --- a/src/plugins/heatmap/heatmap.cpp +++ b/src/plugins/heatmap/heatmap.cpp @@ -60,7 +60,7 @@ static const QString sDescription = QObject::tr( "Creates a Heatmap raster for t static const QString sCategory = QObject::tr( "Raster" ); static const QString sPluginVersion = QObject::tr( "Version 0.2" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/heatmap/heatmap.png"; +static const QString sPluginIcon = QStringLiteral( ":/heatmap/heatmap.png" ); /** * Constructor for the plugin. The plugin is passed a pointer @@ -90,7 +90,7 @@ void Heatmap::initGui() // Create the action for tool mQActionPointer = new QAction( QIcon( ":/heatmap/heatmap.png" ), tr( "Heatmap..." ), this ); - mQActionPointer->setObjectName( "mQActionPointer" ); + mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); // Set the what's this text mQActionPointer->setWhatsThis( tr( "Creates a heatmap raster for the input point vector." ) ); // Connect the action to the run diff --git a/src/plugins/heatmap/heatmapgui.cpp b/src/plugins/heatmap/heatmapgui.cpp index fb53d0852d40..99a5e55e1b70 100644 --- a/src/plugins/heatmap/heatmapgui.cpp +++ b/src/plugins/heatmap/heatmapgui.cpp @@ -58,7 +58,7 @@ HeatmapGui::HeatmapGui( QWidget* parent, Qt::WindowFlags fl, QMap<QString, QVari mHeatmapSessionSettings = temporarySettings; // Adding point layers to the inputLayerCombo - QString lastUsedLayer = mHeatmapSessionSettings->value( QString( "lastInputLayer" ) ).toString(); + QString lastUsedLayer = mHeatmapSessionSettings->value( QStringLiteral( "lastInputLayer" ) ).toString(); bool usingLastInputLayer = false; mInputLayerCombo->setFilters( QgsMapLayerProxyModel::PointLayer ); @@ -87,7 +87,7 @@ HeatmapGui::HeatmapGui( QWidget* parent, Qt::WindowFlags fl, QMap<QString, QVari char **driverMetadata = GDALGetMetadata( nthDriver, nullptr ); // Only formats which allow creation of Float32 data types are valid if ( CSLFetchBoolean( driverMetadata, GDAL_DCAP_CREATE, false ) && - QString( GDALGetMetadataItem( nthDriver, GDAL_DMD_CREATIONDATATYPES, nullptr ) ).contains( "Float32" ) ) + QString( GDALGetMetadataItem( nthDriver, GDAL_DMD_CREATIONDATATYPES, nullptr ) ).contains( QLatin1String( "Float32" ) ) ) { ++myIndex; QString myLongName = GDALGetMetadataItem( nthDriver, GDAL_DMD_LONGNAME, nullptr ); @@ -95,7 +95,7 @@ HeatmapGui::HeatmapGui( QWidget* parent, Qt::WindowFlags fl, QMap<QString, QVari mFormatCombo->addItem( myLongName, QVariant( GDALGetDescription( nthDriver ) ) ); // Add the drivers and their extensions to a map for filename correction mExtensionMap.insert( GDALGetDescription( nthDriver ), GDALGetMetadataItem( nthDriver, GDAL_DMD_EXTENSION, nullptr ) ); - if ( myLongName == "GeoTIFF" ) + if ( myLongName == QLatin1String( "GeoTIFF" ) ) { myTiffIndex = myIndex; } @@ -103,14 +103,14 @@ HeatmapGui::HeatmapGui( QWidget* parent, Qt::WindowFlags fl, QMap<QString, QVari } //Restore choice of output format from last run QSettings s; - int defaultFormatIndex = s.value( "/Heatmap/lastFormat", myTiffIndex ).toInt(); + int defaultFormatIndex = s.value( QStringLiteral( "/Heatmap/lastFormat" ), myTiffIndex ).toInt(); mFormatCombo->setCurrentIndex( defaultFormatIndex ); restoreSettings( usingLastInputLayer ); updateBBox(); updateSize(); - mAddToCanvas->setChecked( s.value( "/Heatmap/addToCanvas", true ).toBool() ); + mAddToCanvas->setChecked( s.value( QStringLiteral( "/Heatmap/addToCanvas" ), true ).toBool() ); blockAllSignals( false ); @@ -154,7 +154,7 @@ void HeatmapGui::restoreSettings( bool usingLastInputLayer ) if ( usingLastInputLayer ) { // Advanced checkbox - if ( mHeatmapSessionSettings->value( QString( "advancedEnabled" ) ).toBool() ) + if ( mHeatmapSessionSettings->value( QStringLiteral( "advancedEnabled" ) ).toBool() ) { mAdvancedGroupBox->setChecked( true ); } @@ -163,26 +163,26 @@ void HeatmapGui::restoreSettings( bool usingLastInputLayer ) mWeightFieldCombo->setLayer( mInputLayerCombo->currentLayer() ); // Radius controls - mBufferSizeLineEdit->setText( mHeatmapSessionSettings->value( QString( "lastRadius" ) ).toString() ); - mBufferUnitCombo->setCurrentIndex( mHeatmapSessionSettings->value( QString( "lastRadiusUnit" ) ).toInt() ); + mBufferSizeLineEdit->setText( mHeatmapSessionSettings->value( QStringLiteral( "lastRadius" ) ).toString() ); + mBufferUnitCombo->setCurrentIndex( mHeatmapSessionSettings->value( QStringLiteral( "lastRadiusUnit" ) ).toInt() ); // Raster size controls - mRows = mHeatmapSessionSettings->value( QString( "lastRows" ) ).toInt(); + mRows = mHeatmapSessionSettings->value( QStringLiteral( "lastRows" ) ).toInt(); mRowsSpinBox->setValue( mRows ); // Data defined radius controls - if ( mHeatmapSessionSettings->value( QString( "useRadius" ) ).toBool() ) + if ( mHeatmapSessionSettings->value( QStringLiteral( "useRadius" ) ).toBool() ) { mRadiusFieldCheckBox->setChecked( true ); - mRadiusFieldUnitCombo->setCurrentIndex( mHeatmapSessionSettings->value( QString( "radiusFieldUnit" ) ).toInt() ); - mRadiusFieldCombo->setField( mHeatmapSessionSettings->value( QString( "radiusField" ) ).toString() ); + mRadiusFieldUnitCombo->setCurrentIndex( mHeatmapSessionSettings->value( QStringLiteral( "radiusFieldUnit" ) ).toInt() ); + mRadiusFieldCombo->setField( mHeatmapSessionSettings->value( QStringLiteral( "radiusField" ) ).toString() ); } // Data defined weight controls - if ( mHeatmapSessionSettings->value( QString( "useWeight" ) ).toBool() ) + if ( mHeatmapSessionSettings->value( QStringLiteral( "useWeight" ) ).toBool() ) { mWeightFieldCheckBox->setChecked( true ); - mWeightFieldCombo->setField( mHeatmapSessionSettings->value( QString( "weightField" ) ).toString() ); + mWeightFieldCombo->setField( mHeatmapSessionSettings->value( QStringLiteral( "weightField" ) ).toString() ); } } else @@ -192,16 +192,16 @@ void HeatmapGui::restoreSettings( bool usingLastInputLayer ) } // Kernel setting - not layer specific - if ( mHeatmapSessionSettings->value( QString( "lastKernel" ) ).toInt() ) + if ( mHeatmapSessionSettings->value( QStringLiteral( "lastKernel" ) ).toInt() ) { mKernelShapeCombo->setCurrentIndex( mKernelShapeCombo->findData( - ( Heatmap::KernelShape )( mHeatmapSessionSettings->value( QString( "lastKernel" ) ).toInt() ) ) ); - mDecayLineEdit->setText( mHeatmapSessionSettings->value( QString( "decayRatio" ) ).toString() ); + ( Heatmap::KernelShape )( mHeatmapSessionSettings->value( QStringLiteral( "lastKernel" ) ).toInt() ) ) ); + mDecayLineEdit->setText( mHeatmapSessionSettings->value( QStringLiteral( "decayRatio" ) ).toString() ); mDecayLineEdit->setEnabled( mAdvancedGroupBox->isChecked() && ( Heatmap::KernelShape )( mKernelShapeCombo->currentData().toInt() ) == Heatmap::Triangular ); } mOutputValuesComboBox->setCurrentIndex( mOutputValuesComboBox->findData( - ( Heatmap::OutputValues )( mHeatmapSessionSettings->value( QString( "lastOutputValues" ), "0" ).toInt() ) ) ); + ( Heatmap::OutputValues )( mHeatmapSessionSettings->value( QStringLiteral( "lastOutputValues" ), "0" ).toInt() ) ) ); } @@ -209,23 +209,23 @@ void HeatmapGui::saveSettings() { // Save persistent settings QSettings s; - s.setValue( "/Heatmap/lastFormat", QVariant( mFormatCombo->currentIndex() ) ); - s.setValue( "/Heatmap/addToCanvas", mAddToCanvas->isChecked() ); + s.setValue( QStringLiteral( "/Heatmap/lastFormat" ), QVariant( mFormatCombo->currentIndex() ) ); + s.setValue( QStringLiteral( "/Heatmap/addToCanvas" ), mAddToCanvas->isChecked() ); // Store temporary settings, which only apply to this session - mHeatmapSessionSettings->insert( QString( "lastInputLayer" ), QVariant( mInputLayerCombo->currentLayer()->id() ) ); - mHeatmapSessionSettings->insert( QString( "lastRadius" ), QVariant( mBufferSizeLineEdit->text().toDouble() ) ); - mHeatmapSessionSettings->insert( QString( "lastRadiusUnit" ), QVariant( mBufferUnitCombo->currentIndex() ) ); - mHeatmapSessionSettings->insert( QString( "advancedEnabled" ), QVariant( mAdvancedGroupBox->isChecked() ) ); - mHeatmapSessionSettings->insert( QString( "lastRows" ), QVariant( mRowsSpinBox->value() ) ); - mHeatmapSessionSettings->insert( QString( "lastKernel" ), QVariant( mKernelShapeCombo->currentData().toInt() ) ); - mHeatmapSessionSettings->insert( QString( "useRadius" ), QVariant( mRadiusFieldCheckBox->isChecked() ) ); - mHeatmapSessionSettings->insert( QString( "radiusField" ), QVariant( mRadiusFieldCombo->currentField() ) ); - mHeatmapSessionSettings->insert( QString( "radiusFieldUnit" ), QVariant( mRadiusFieldUnitCombo->currentIndex() ) ); - mHeatmapSessionSettings->insert( QString( "useWeight" ), QVariant( mWeightFieldCheckBox->isChecked() ) ); - mHeatmapSessionSettings->insert( QString( "weightField" ), QVariant( mWeightFieldCombo->currentField() ) ); - mHeatmapSessionSettings->insert( QString( "decayRatio" ), QVariant( mDecayLineEdit->text() ) ); - mHeatmapSessionSettings->insert( QString( "lastOutputValues" ), QVariant( mOutputValuesComboBox->currentData().toInt() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "lastInputLayer" ), QVariant( mInputLayerCombo->currentLayer()->id() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "lastRadius" ), QVariant( mBufferSizeLineEdit->text().toDouble() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "lastRadiusUnit" ), QVariant( mBufferUnitCombo->currentIndex() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "advancedEnabled" ), QVariant( mAdvancedGroupBox->isChecked() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "lastRows" ), QVariant( mRowsSpinBox->value() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "lastKernel" ), QVariant( mKernelShapeCombo->currentData().toInt() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "useRadius" ), QVariant( mRadiusFieldCheckBox->isChecked() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "radiusField" ), QVariant( mRadiusFieldCombo->currentField() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "radiusFieldUnit" ), QVariant( mRadiusFieldUnitCombo->currentIndex() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "useWeight" ), QVariant( mWeightFieldCheckBox->isChecked() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "weightField" ), QVariant( mWeightFieldCombo->currentField() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "decayRatio" ), QVariant( mDecayLineEdit->text() ) ); + mHeatmapSessionSettings->insert( QStringLiteral( "lastOutputValues" ), QVariant( mOutputValuesComboBox->currentData().toInt() ) ); } void HeatmapGui::on_mButtonBox_rejected() @@ -241,7 +241,7 @@ void HeatmapGui::on_mButtonBox_helpRequested() void HeatmapGui::on_mBrowseButton_clicked() { QSettings s; - QString lastDir = s.value( "/Heatmap/lastOutputDir", QDir::homePath() ).toString(); + QString lastDir = s.value( QStringLiteral( "/Heatmap/lastOutputDir" ), QDir::homePath() ).toString(); QString outputFilename = QFileDialog::getSaveFileName( nullptr, tr( "Save Heatmap as:" ), lastDir ); if ( !outputFilename.isEmpty() ) @@ -251,7 +251,7 @@ void HeatmapGui::on_mBrowseButton_clicked() QDir outputDir = outputFileInfo.absoluteDir(); if ( outputDir.exists() ) { - s.setValue( "/Heatmap/lastOutputDir", outputFileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/Heatmap/lastOutputDir" ), outputFileInfo.absolutePath() ); } } diff --git a/src/plugins/interpolation/qgsinterpolationdialog.cpp b/src/plugins/interpolation/qgsinterpolationdialog.cpp index 339f79b16781..ade19e780a79 100644 --- a/src/plugins/interpolation/qgsinterpolationdialog.cpp +++ b/src/plugins/interpolation/qgsinterpolationdialog.cpp @@ -37,7 +37,7 @@ QgsInterpolationDialog::QgsInterpolationDialog( QWidget* parent, QgisInterface* setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Interpolation/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Interpolation/geometry" ) ).toByteArray() ); //enter available layers into the combo box QMap<QString, QgsMapLayer*> mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); @@ -59,7 +59,7 @@ QgsInterpolationDialog::QgsInterpolationDialog( QWidget* parent, QgisInterface* //only inverse distance weighting available for now mInterpolationMethodComboBox->insertItem( 0, tr( "Triangular interpolation (TIN)" ) ); mInterpolationMethodComboBox->insertItem( 1, tr( "Inverse Distance Weighting (IDW)" ) ); - mInterpolationMethodComboBox->setCurrentIndex( settings.value( "/Interpolation/lastMethod", 0 ).toInt() ); + mInterpolationMethodComboBox->setCurrentIndex( settings.value( QStringLiteral( "/Interpolation/lastMethod" ), 0 ).toInt() ); enableOrDisableOkButton(); } @@ -67,8 +67,8 @@ QgsInterpolationDialog::QgsInterpolationDialog( QWidget* parent, QgisInterface* QgsInterpolationDialog::~QgsInterpolationDialog() { QSettings settings; - settings.setValue( "/Interpolation/geometry", saveGeometry() ); - settings.setValue( "/Interpolation/lastMethod", mInterpolationMethodComboBox->currentIndex() ); + settings.setValue( QStringLiteral( "/Interpolation/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Interpolation/lastMethod" ), mInterpolationMethodComboBox->currentIndex() ); } void QgsInterpolationDialog::enableOrDisableOkButton() @@ -151,7 +151,7 @@ void QgsInterpolationDialog::on_buttonBox_accepted() currentLayerData.vectorLayer = theVectorLayer; QString interpolationAttString = mLayersTreeWidget->topLevelItem( i )->text( 1 ); - if ( interpolationAttString == "Z_COORD" ) + if ( interpolationAttString == QLatin1String( "Z_COORD" ) ) { currentLayerData.zCoordInterpolation = true; currentLayerData.interpolationAttribute = -1; @@ -264,7 +264,7 @@ void QgsInterpolationDialog::on_mAddPushButton_clicked() QString interpolationAttribute; if ( mUseZCoordCheckBox->checkState() == Qt::Checked ) { - interpolationAttribute = "Z_COORD"; + interpolationAttribute = QStringLiteral( "Z_COORD" ); } else { @@ -304,7 +304,7 @@ void QgsInterpolationDialog::on_mOutputFileButton_clicked() { //get last output file dir QSettings s; - QString lastOutputDir = s.value( "/Interpolation/lastOutputDir", QDir::homePath() ).toString(); + QString lastOutputDir = s.value( QStringLiteral( "/Interpolation/lastOutputDir" ), QDir::homePath() ).toString(); QString rasterFileName = QFileDialog::getSaveFileName( nullptr, tr( "Save interpolated raster as..." ), lastOutputDir ); if ( !rasterFileName.isEmpty() ) @@ -314,7 +314,7 @@ void QgsInterpolationDialog::on_mOutputFileButton_clicked() QDir fileDir = rasterFileInfo.absoluteDir(); if ( fileDir.exists() ) { - s.setValue( "/Interpolation/lastOutputDir", rasterFileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/Interpolation/lastOutputDir" ), rasterFileInfo.absolutePath() ); } } enableOrDisableOkButton(); @@ -322,7 +322,7 @@ void QgsInterpolationDialog::on_mOutputFileButton_clicked() void QgsInterpolationDialog::on_mOutputFileLineEdit_textChanged() { - if ( mOutputFileLineEdit->text().endsWith( ".asc" ) ) + if ( mOutputFileLineEdit->text().endsWith( QLatin1String( ".asc" ) ) ) { enableOrDisableOkButton(); } diff --git a/src/plugins/interpolation/qgsinterpolationplugin.cpp b/src/plugins/interpolation/qgsinterpolationplugin.cpp index 162c0af16dfd..ac6d4c203a47 100644 --- a/src/plugins/interpolation/qgsinterpolationplugin.cpp +++ b/src/plugins/interpolation/qgsinterpolationplugin.cpp @@ -26,7 +26,7 @@ static const QString name_ = QObject::tr( "Interpolation plugin" ); static const QString description_ = QObject::tr( "A plugin for interpolation based on vertices of a vector layer" ); static const QString category_ = QObject::tr( "Raster" ); static const QString version_ = QObject::tr( "Version 0.001" ); -static const QString icon_ = ":/raster-interpolate.png"; +static const QString icon_ = QStringLiteral( ":/raster-interpolate.png" ); QgsInterpolationPlugin::QgsInterpolationPlugin( QgisInterface* iface ): mIface( iface ), mInterpolationAction( nullptr ) { @@ -43,7 +43,7 @@ void QgsInterpolationPlugin::initGui() if ( mIface ) { mInterpolationAction = new QAction( QIcon( ":/raster-interpolate.png" ), tr( "&Interpolation" ), nullptr ); - mInterpolationAction->setObjectName( "mInterpolationAction" ); + mInterpolationAction->setObjectName( QStringLiteral( "mInterpolationAction" ) ); QObject::connect( mInterpolationAction, SIGNAL( triggered() ), this, SLOT( showInterpolationDialog() ) ); mIface->addRasterToolBarIcon( mInterpolationAction ); mIface->addPluginToRasterMenu( tr( "&Interpolation" ), mInterpolationAction ); diff --git a/src/plugins/interpolation/qgstininterpolatordialog.cpp b/src/plugins/interpolation/qgstininterpolatordialog.cpp index 46adea81601d..6eaed717075b 100644 --- a/src/plugins/interpolation/qgstininterpolatordialog.cpp +++ b/src/plugins/interpolation/qgstininterpolatordialog.cpp @@ -82,8 +82,8 @@ void QgsTINInterpolatorDialog::on_mTriangulationFileButton_clicked() { QSettings s; //read last triangulation directory - QString lastTriangulationDir = s.value( "/Interpolation/lastTriangulationDir", QDir::homePath() ).toString(); - QString filename = QFileDialog::getSaveFileName( nullptr, tr( "Save triangulation to file" ), lastTriangulationDir, "*shp" ); + QString lastTriangulationDir = s.value( QStringLiteral( "/Interpolation/lastTriangulationDir" ), QDir::homePath() ).toString(); + QString filename = QFileDialog::getSaveFileName( nullptr, tr( "Save triangulation to file" ), lastTriangulationDir, QStringLiteral( "*shp" ) ); if ( !filename.isEmpty() ) { mTriangulationFileEdit->setText( filename ); @@ -93,7 +93,7 @@ void QgsTINInterpolatorDialog::on_mTriangulationFileButton_clicked() QDir fileDir = triangulationFileInfo.absoluteDir(); if ( fileDir.exists() ) { - s.setValue( "/Interpolation/lastTriangulationDir", triangulationFileInfo.absolutePath() ); + s.setValue( QStringLiteral( "/Interpolation/lastTriangulationDir" ), triangulationFileInfo.absolutePath() ); } } } diff --git a/src/plugins/offline_editing/offline_editing_plugin.cpp b/src/plugins/offline_editing/offline_editing_plugin.cpp index 4ce62bbec0be..1a58fe96e5c4 100644 --- a/src/plugins/offline_editing/offline_editing_plugin.cpp +++ b/src/plugins/offline_editing/offline_editing_plugin.cpp @@ -34,7 +34,7 @@ static const QString sDescription = QObject::tr( "Allow offline editing and sync static const QString sCategory = QObject::tr( "Database" ); static const QString sPluginVersion = QObject::tr( "Version 0.1" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/offline_editing/offline_editing_copy.png"; +static const QString sPluginIcon = QStringLiteral( ":/offline_editing/offline_editing_copy.png" ); QgsOfflineEditingPlugin::QgsOfflineEditingPlugin( QgisInterface* theQgisInterface ) : QgisPlugin( sName, sDescription, sCategory, sPluginVersion, sPluginType ) @@ -57,7 +57,7 @@ void QgsOfflineEditingPlugin::initGui() // Create the action for tool mActionConvertProject = new QAction( QIcon( ":/offline_editing/offline_editing_copy.png" ), tr( "Convert to offline project" ), this ); - mActionConvertProject->setObjectName( "mActionConvertProject" ); + mActionConvertProject->setObjectName( QStringLiteral( "mActionConvertProject" ) ); // Set the what's this text mActionConvertProject->setWhatsThis( tr( "Create offline copies of selected layers and save as offline project" ) ); // Connect the action to the run @@ -68,7 +68,7 @@ void QgsOfflineEditingPlugin::initGui() mActionConvertProject->setEnabled( false ); mActionSynchronize = new QAction( QIcon( ":/offline_editing/offline_editing_sync.png" ), tr( "Synchronize" ), this ); - mActionSynchronize->setObjectName( "mActionSynchronize" ); + mActionSynchronize->setObjectName( QStringLiteral( "mActionSynchronize" ) ); mActionSynchronize->setWhatsThis( tr( "Synchronize offline project with remote layers" ) ); connect( mActionSynchronize, SIGNAL( triggered() ), this, SLOT( synchronize() ) ); mQGisIface->addDatabaseToolBarIcon( mActionSynchronize ); @@ -167,7 +167,7 @@ void QgsOfflineEditingPlugin::setLayerProgress( int layer, int numLayers ) void QgsOfflineEditingPlugin::setProgressMode( QgsOfflineEditing::ProgressMode mode, int maximum ) { - QString format = ""; + QString format = QLatin1String( "" ); switch ( mode ) { case QgsOfflineEditing::CopyFeatures: diff --git a/src/plugins/offline_editing/offline_editing_plugin_gui.cpp b/src/plugins/offline_editing/offline_editing_plugin_gui.cpp index fae44b93223b..ff2e9a7b07e2 100644 --- a/src/plugins/offline_editing/offline_editing_plugin_gui.cpp +++ b/src/plugins/offline_editing/offline_editing_plugin_gui.cpp @@ -74,7 +74,7 @@ QgsOfflineEditingPluginGui::QgsOfflineEditingPluginGui( QWidget* parent, Qt::Win restoreState(); - mOfflineDbFile = "offline.sqlite"; + mOfflineDbFile = QStringLiteral( "offline.sqlite" ); mOfflineDataPathLineEdit->setText( QDir( mOfflineDataPath ).absoluteFilePath( mOfflineDbFile ) ); QgsLayerTreeGroup* rootNode = QgsLayerTree::toGroup( QgsProject::instance()->layerTreeRoot()->clone() ); @@ -88,8 +88,8 @@ QgsOfflineEditingPluginGui::QgsOfflineEditingPluginGui( QWidget* parent, Qt::Win QgsOfflineEditingPluginGui::~QgsOfflineEditingPluginGui() { QSettings settings; - settings.setValue( "Plugin-OfflineEditing/geometry", saveGeometry() ); - settings.setValue( "Plugin-OfflineEditing/offline_data_path", mOfflineDataPath ); + settings.setValue( QStringLiteral( "Plugin-OfflineEditing/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "Plugin-OfflineEditing/offline_data_path" ), mOfflineDataPath ); } QString QgsOfflineEditingPluginGui::offlineDataPath() @@ -122,9 +122,9 @@ void QgsOfflineEditingPluginGui::on_mBrowseButton_clicked() if ( !fileName.isEmpty() ) { - if ( !fileName.endsWith( ".sqlite", Qt::CaseInsensitive ) ) + if ( !fileName.endsWith( QLatin1String( ".sqlite" ), Qt::CaseInsensitive ) ) { - fileName += ".sqlite"; + fileName += QLatin1String( ".sqlite" ); } mOfflineDbFile = QFileInfo( fileName ).fileName(); mOfflineDataPath = QFileInfo( fileName ).absolutePath(); @@ -174,8 +174,8 @@ void QgsOfflineEditingPluginGui::on_buttonBox_helpRequested() void QgsOfflineEditingPluginGui::restoreState() { QSettings settings; - mOfflineDataPath = settings.value( "Plugin-OfflineEditing/offline_data_path", QDir::homePath() ).toString(); - restoreGeometry( settings.value( "Plugin-OfflineEditing/geometry" ).toByteArray() ); + mOfflineDataPath = settings.value( QStringLiteral( "Plugin-OfflineEditing/offline_data_path" ), QDir::homePath() ).toString(); + restoreGeometry( settings.value( QStringLiteral( "Plugin-OfflineEditing/geometry" ) ).toByteArray() ); } void QgsOfflineEditingPluginGui::selectAll() diff --git a/src/plugins/oracle_raster/qgsoracle_plugin.cpp b/src/plugins/oracle_raster/qgsoracle_plugin.cpp index ad6a0fd79e44..05dff2b304ae 100644 --- a/src/plugins/oracle_raster/qgsoracle_plugin.cpp +++ b/src/plugins/oracle_raster/qgsoracle_plugin.cpp @@ -23,7 +23,7 @@ static const QString sDescription = QObject::tr( "Access Oracle Spatial GeoRaste static const QString sCategory = QObject::tr( "Layers" ); static const QString sPluginVersion = QObject::tr( "Version 0.1" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/oracleplugin/oracleraster.svg"; +static const QString sPluginIcon = QStringLiteral( ":/oracleplugin/oracleraster.svg" ); ////////////////////////////////////////////////////////////////////// // @@ -56,7 +56,7 @@ void QgsOraclePlugin::initGui() { // Create the action for tool mQActionPointer = new QAction( QIcon( ":/oracleplugin/oracleraster.svg" ), tr( "Add Oracle GeoRaster Layer..." ), this ); - mQActionPointer->setObjectName( "mQActionPointer" ); + mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); // Set the what's this text mQActionPointer->setWhatsThis( tr( "Add a Oracle Spatial GeoRaster..." ) ); // Connect the action to the run diff --git a/src/plugins/oracle_raster/qgsoracleconnect_ui.cpp b/src/plugins/oracle_raster/qgsoracleconnect_ui.cpp index 1686bc0a7588..e4ae2a8e6763 100644 --- a/src/plugins/oracle_raster/qgsoracleconnect_ui.cpp +++ b/src/plugins/oracle_raster/qgsoracleconnect_ui.cpp @@ -37,7 +37,7 @@ QgsOracleConnect::QgsOracleConnect( QWidget* parent, txtDatabase->setText( settings.value( key + "/database" ).toString() ); txtUsername->setText( settings.value( key + "/username" ).toString() ); - if ( settings.value( key + "/savepass" ).toString() == "true" ) + if ( settings.value( key + "/savepass" ).toString() == QLatin1String( "true" ) ) { txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); @@ -68,7 +68,7 @@ void QgsOracleConnect::saveConnection() { QSettings settings; - QString baseKey = "/Oracle/connections/"; + QString baseKey = QStringLiteral( "/Oracle/connections/" ); settings.setValue( baseKey + "selected", txtName->text() ); baseKey += txtName->text(); diff --git a/src/plugins/oracle_raster/qgsselectgeoraster_ui.cpp b/src/plugins/oracle_raster/qgsselectgeoraster_ui.cpp index 6563527f5804..1c6e941385f7 100644 --- a/src/plugins/oracle_raster/qgsselectgeoraster_ui.cpp +++ b/src/plugins/oracle_raster/qgsselectgeoraster_ui.cpp @@ -50,9 +50,9 @@ QgsOracleSelectGeoraster::QgsOracleSelectGeoraster( QWidget* parent, */ QSettings settings; - QString selected = settings.value( "/Oracle/connections/selected" ).toString(); + QString selected = settings.value( QStringLiteral( "/Oracle/connections/selected" ) ).toString(); - restoreGeometry( settings.value( "/Oracle/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Oracle/geometry" ) ).toByteArray() ); cmbConnections->setCurrentIndex( cmbConnections->findText( selected ) ); if ( selected == cmbConnections->currentText() ) @@ -64,14 +64,14 @@ QgsOracleSelectGeoraster::QgsOracleSelectGeoraster( QWidget* parent, QgsOracleSelectGeoraster::~QgsOracleSelectGeoraster() { QSettings settings; - settings.setValue( "/Oracle/geometry", saveGeometry() ); - settings.setValue( "/Oracle/connections/selected", cmbConnections->currentText() ); + settings.setValue( QStringLiteral( "/Oracle/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Oracle/connections/selected" ), cmbConnections->currentText() ); } void QgsOracleSelectGeoraster::populateConnectionList() { QSettings settings; - settings.beginGroup( "/Oracle/connections" ); + settings.beginGroup( QStringLiteral( "/Oracle/connections" ) ); QStringList keys = settings.childGroups(); QStringList::Iterator it = keys.begin(); @@ -108,7 +108,7 @@ void QgsOracleSelectGeoraster::populateConnectionList() void QgsOracleSelectGeoraster::on_btnNew_clicked() { - QgsOracleConnect *oc = new QgsOracleConnect( this, "New Connection" ); + QgsOracleConnect *oc = new QgsOracleConnect( this, QStringLiteral( "New Connection" ) ); if ( oc->exec() ) { populateConnectionList(); @@ -144,7 +144,7 @@ void QgsOracleSelectGeoraster::on_btnDelete_clicked() settings.remove( key ); cmbConnections->removeItem( cmbConnections->currentIndex() ); setConnectionListPosition(); - lineEdit->setText( "" ); + lineEdit->setText( QLatin1String( "" ) ); listWidget->clear(); } } @@ -161,7 +161,7 @@ void QgsOracleSelectGeoraster::connectToServer() QString database = settings.value( key + "/database" ).toString(); QString subdtset = settings.value( key + "/subdtset" ).toString(); bool makeConnection = true; - if ( savepass == "false" ) + if ( savepass == QLatin1String( "false" ) ) { makeConnection = false; ( void )QInputDialog::getText( this, @@ -173,7 +173,7 @@ void QgsOracleSelectGeoraster::connectToServer() } if ( makeConnection ) { - settings.setValue( "/Oracle/connections/selected", + settings.setValue( QStringLiteral( "/Oracle/connections/selected" ), cmbConnections->currentText() ); showSelection( subdtset ); lineEdit->setText( subdtset ); @@ -247,34 +247,34 @@ void QgsOracleSelectGeoraster::showSelection( const QString & line ) QStringList fields = identification.split( ',' ); QString count = QString::number( nSubDatasets / 2 ); - QString plural = "s"; + QString plural = QStringLiteral( "s" ); - if ( count == "1" ) + if ( count == QLatin1String( "1" ) ) { - plural = ""; + plural = QLatin1String( "" ); } if ( fields.size() < 4 ) { - labelStatus->setText( QString( "%1 GeoRaster table%2" ) + labelStatus->setText( QStringLiteral( "%1 GeoRaster table%2" ) .arg( count, plural ) ); checkBox->setEnabled( false ); } else if ( fields.size() == 4 ) { - labelStatus->setText( QString( "%1 GeoRaster column%2 on table %3" ) + labelStatus->setText( QStringLiteral( "%1 GeoRaster column%2 on table %3" ) .arg( count, plural, fields[3] ) ); checkBox->setEnabled( false ); } else if ( fields.size() == 5 ) { - labelStatus->setText( QString( "%1 GeoRaster object%2 on table %3 column %4" ) + labelStatus->setText( QStringLiteral( "%1 GeoRaster object%2 on table %3 column %4" ) .arg( count, plural, fields[3], fields[4] ) ); checkBox->setEnabled( true ); } else { - labelStatus->setText( QString( "%1 GeoRaster object%2 on table %3 column %4 where %5" ) + labelStatus->setText( QStringLiteral( "%1 GeoRaster object%2 on table %3 column %4 where %5" ) .arg( count, plural, fields[3], fields[4], fields[5] ) ); checkBox->setEnabled( true ); } @@ -314,7 +314,7 @@ void QgsOracleSelectGeoraster::setConnectionListPosition() { // If possible, set the item currently displayed database QSettings settings; - QString toSelect = settings.value( "/Oracle/connections/selected" ).toString(); + QString toSelect = settings.value( QStringLiteral( "/Oracle/connections/selected" ) ).toString(); cmbConnections->setCurrentIndex( cmbConnections->findText( toSelect ) ); // If we couldn't find the stored item, but there are some, diff --git a/src/plugins/qgisplugin.h b/src/plugins/qgisplugin.h index 15eedbfe2db6..4222260e45af 100644 --- a/src/plugins/qgisplugin.h +++ b/src/plugins/qgisplugin.h @@ -76,10 +76,10 @@ class QgisPlugin /** * Constructor for QgisPlugin */ - QgisPlugin( QString const & name = "", - QString const & description = "", - QString const & category = "", - QString const & version = "", + QgisPlugin( QString const & name = QLatin1String( "" ), + QString const & description = QLatin1String( "" ), + QString const & category = QLatin1String( "" ), + QString const & version = QLatin1String( "" ), PLUGINTYPE type = MAPLAYER ) : mName( name ) , mDescription( description ) diff --git a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.cpp b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.cpp index 7d92399afbee..eccdc650bc42 100644 --- a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.cpp +++ b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.cpp @@ -31,7 +31,7 @@ QgsRasterTerrainAnalysisDialog::QgsRasterTerrainAnalysisDialog( DisplayMode mode setupUi( this ); QSettings s; - restoreGeometry( s.value( "/RasterTerrainAnalysis/geometry" ).toByteArray() ); + restoreGeometry( s.value( QStringLiteral( "/RasterTerrainAnalysis/geometry" ) ).toByteArray() ); if ( mode == HillshadeInput ) { @@ -50,7 +50,7 @@ QgsRasterTerrainAnalysisDialog::QgsRasterTerrainAnalysisDialog( DisplayMode mode } adjustSize(); - mZFactorLineEdit->setText( s.value( "/RasterTerrainAnalysis/zfactor", "1.0" ).toString() ); + mZFactorLineEdit->setText( s.value( QStringLiteral( "/RasterTerrainAnalysis/zfactor" ), "1.0" ).toString() ); mZFactorLineEdit->setValidator( new QDoubleValidator( this ) ); //insert available raster layers @@ -91,7 +91,7 @@ QgsRasterTerrainAnalysisDialog::QgsRasterTerrainAnalysisDialog( DisplayMode mode } //and set last used driver in combo box - QString lastUsedDriver = s.value( "/RasterTerrainAnalysis/lastOutputFormat", "GeoTIFF" ).toString(); + QString lastUsedDriver = s.value( QStringLiteral( "/RasterTerrainAnalysis/lastOutputFormat" ), "GeoTIFF" ).toString(); int lastDriverIndex = mOutputFormatComboBox->findText( lastUsedDriver ); if ( lastDriverIndex != -1 ) { @@ -127,7 +127,7 @@ QString QgsRasterTerrainAnalysisDialog::inputFile() const QgsMapLayer* inputLayer = QgsMapLayerRegistry::instance()->mapLayer( mElevationLayerComboBox->currentData().toString() ); if ( !inputLayer ) { - return ""; + return QLatin1String( "" ); } QString inputFilePath = inputLayer->source(); @@ -166,7 +166,7 @@ QString QgsRasterTerrainAnalysisDialog::outputFormat() const int index = mOutputFormatComboBox->currentIndex(); if ( index == -1 ) { - return ""; + return QLatin1String( "" ); } return mOutputFormatComboBox->itemData( index ).toString(); } @@ -232,19 +232,19 @@ void QgsRasterTerrainAnalysisDialog::on_mExportColorsButton_clicked() } QDomDocument doc; - QDomElement reliefColorsElem = doc.createElement( "ReliefColors" ); + QDomElement reliefColorsElem = doc.createElement( QStringLiteral( "ReliefColors" ) ); doc.appendChild( reliefColorsElem ); QList< QgsRelief::ReliefColor > rColors = reliefColors(); QList< QgsRelief::ReliefColor >::const_iterator rColorsIt = rColors.constBegin(); for ( ; rColorsIt != rColors.constEnd(); ++rColorsIt ) { - QDomElement classElem = doc.createElement( "ReliefColor" ); - classElem.setAttribute( "MinElevation", QString::number( rColorsIt->minElevation ) ); - classElem.setAttribute( "MaxElevation", QString::number( rColorsIt->maxElevation ) ); - classElem.setAttribute( "red", QString::number( rColorsIt->color.red() ) ); - classElem.setAttribute( "green", QString::number( rColorsIt->color.green() ) ); - classElem.setAttribute( "blue", QString::number( rColorsIt->color.blue() ) ); + QDomElement classElem = doc.createElement( QStringLiteral( "ReliefColor" ) ); + classElem.setAttribute( QStringLiteral( "MinElevation" ), QString::number( rColorsIt->minElevation ) ); + classElem.setAttribute( QStringLiteral( "MaxElevation" ), QString::number( rColorsIt->maxElevation ) ); + classElem.setAttribute( QStringLiteral( "red" ), QString::number( rColorsIt->color.red() ) ); + classElem.setAttribute( QStringLiteral( "green" ), QString::number( rColorsIt->color.green() ) ); + classElem.setAttribute( QStringLiteral( "blue" ), QString::number( rColorsIt->color.blue() ) ); reliefColorsElem.appendChild( classElem ); } @@ -281,15 +281,15 @@ void QgsRasterTerrainAnalysisDialog::on_mImportColorsButton_clicked() mReliefClassTreeWidget->clear(); - QDomNodeList reliefColorList = doc.elementsByTagName( "ReliefColor" ); + QDomNodeList reliefColorList = doc.elementsByTagName( QStringLiteral( "ReliefColor" ) ); for ( int i = 0; i < reliefColorList.size(); ++i ) { QDomElement reliefColorElem = reliefColorList.at( i ).toElement(); QTreeWidgetItem* newItem = new QTreeWidgetItem(); - newItem->setText( 0, reliefColorElem.attribute( "MinElevation" ) ); - newItem->setText( 1, reliefColorElem.attribute( "MaxElevation" ) ); - newItem->setBackground( 2, QBrush( QColor( reliefColorElem.attribute( "red" ).toInt(), reliefColorElem.attribute( "green" ).toInt(), - reliefColorElem.attribute( "blue" ).toInt() ) ) ); + newItem->setText( 0, reliefColorElem.attribute( QStringLiteral( "MinElevation" ) ) ); + newItem->setText( 1, reliefColorElem.attribute( QStringLiteral( "MaxElevation" ) ) ); + newItem->setBackground( 2, QBrush( QColor( reliefColorElem.attribute( QStringLiteral( "red" ) ).toInt(), reliefColorElem.attribute( QStringLiteral( "green" ) ).toInt(), + reliefColorElem.attribute( QStringLiteral( "blue" ) ).toInt() ) ) ); mReliefClassTreeWidget->addTopLevelItem( newItem ); } } @@ -297,7 +297,7 @@ void QgsRasterTerrainAnalysisDialog::on_mImportColorsButton_clicked() void QgsRasterTerrainAnalysisDialog::on_mOutputLayerToolButton_clicked() { QSettings s; - QString lastDir = s.value( "/RasterTerrainAnalysis/lastOutputDir", QDir::homePath() ).toString(); + QString lastDir = s.value( QStringLiteral( "/RasterTerrainAnalysis/lastOutputDir" ), QDir::homePath() ).toString(); QString saveFileName = QFileDialog::getSaveFileName( nullptr, tr( "Enter result file" ), lastDir ); if ( !saveFileName.isNull() ) { @@ -319,8 +319,8 @@ void QgsRasterTerrainAnalysisDialog::on_mAddClassButton_clicked() { //add class which can be edited by the user later QTreeWidgetItem* newItem = new QTreeWidgetItem(); - newItem->setText( 0, "0.00" ); - newItem->setText( 1, "0.00" ); + newItem->setText( 0, QStringLiteral( "0.00" ) ); + newItem->setText( 1, QStringLiteral( "0.00" ) ); newItem->setBackground( 2, QBrush( QColor( 127, 127, 127 ) ) ); mReliefClassTreeWidget->addTopLevelItem( newItem ); } @@ -408,14 +408,14 @@ void QgsRasterTerrainAnalysisDialog::on_mButtonBox_accepted() { // save last output format QSettings s; - s.setValue( "/RasterTerrainAnalysis/lastOutputFormat", QVariant( mOutputFormatComboBox->currentText() ) ); + s.setValue( QStringLiteral( "/RasterTerrainAnalysis/lastOutputFormat" ), QVariant( mOutputFormatComboBox->currentText() ) ); // save last output directory - s.setValue( "/RasterTerrainAnalysis/lastOutputDir", QFileInfo( mOutputLayerLineEdit->text() ).absolutePath() ); + s.setValue( QStringLiteral( "/RasterTerrainAnalysis/lastOutputDir" ), QFileInfo( mOutputLayerLineEdit->text() ).absolutePath() ); // save z-factor - s.setValue( "/RasterTerrainAnalysis/zfactor", mZFactorLineEdit->text() ); + s.setValue( QStringLiteral( "/RasterTerrainAnalysis/zfactor" ), mZFactorLineEdit->text() ); // save geometry and position - s.setValue( "/RasterTerrainAnalysis/geometry", saveGeometry() ); + s.setValue( QStringLiteral( "/RasterTerrainAnalysis/geometry" ), saveGeometry() ); } diff --git a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.cpp b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.cpp index 572ef3f6961d..323eee942bef 100644 --- a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.cpp +++ b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.cpp @@ -37,7 +37,7 @@ static const QString name_ = QObject::tr( "Raster Terrain Analysis plugin" ); static const QString description_ = QObject::tr( "A plugin for raster based terrain analysis" ); static const QString version_ = QObject::tr( "Version 0.1" ); -static const QString icon_ = ":/raster/dem.png"; +static const QString icon_ = QStringLiteral( ":/raster/dem.png" ); static const QString category_ = QObject::tr( "Raster" ); QgsRasterTerrainAnalysisPlugin::QgsRasterTerrainAnalysisPlugin( QgisInterface* iface ): mIface( iface ), mTerrainAnalysisMenu( nullptr ) @@ -88,19 +88,19 @@ void QgsRasterTerrainAnalysisPlugin::initGui() } mTerrainAnalysisMenu = new QMenu( tr( "Terrain Analysis" ), rasterMenu ); - mTerrainAnalysisMenu->setObjectName( "mTerrainAnalysisMenu" ); + mTerrainAnalysisMenu->setObjectName( QStringLiteral( "mTerrainAnalysisMenu" ) ); mTerrainAnalysisMenu->setIcon( QIcon( ":/raster/dem.png" ) ); QAction *slopeAction = mTerrainAnalysisMenu->addAction( tr( "Slope" ), this, SLOT( slope() ) ); - slopeAction->setObjectName( "slopeAction" ); + slopeAction->setObjectName( QStringLiteral( "slopeAction" ) ); QAction *aspectAction = mTerrainAnalysisMenu->addAction( tr( "Aspect..." ), this, SLOT( aspect() ) ); - aspectAction->setObjectName( "aspectAction" ); + aspectAction->setObjectName( QStringLiteral( "aspectAction" ) ); QAction *hilshadeAction = mTerrainAnalysisMenu->addAction( tr( "Hillshade..." ), this, SLOT( hillshade() ) ); - hilshadeAction->setObjectName( "hilshadeAction" ); + hilshadeAction->setObjectName( QStringLiteral( "hilshadeAction" ) ); QAction *reliefAction = mTerrainAnalysisMenu->addAction( tr( "Relief..." ), this, SLOT( relief() ) ); - reliefAction->setObjectName( "reliefAction" ); + reliefAction->setObjectName( QStringLiteral( "reliefAction" ) ); QAction *ruggednesIndex = mTerrainAnalysisMenu->addAction( tr( "Ruggedness Index..." ), this, SLOT( ruggedness() ) ); - ruggednesIndex->setObjectName( "ruggednesIndex" ); + ruggednesIndex->setObjectName( QStringLiteral( "ruggednesIndex" ) ); rasterMenu->addMenu( mTerrainAnalysisMenu ); diff --git a/src/plugins/roadgraph/exportdlg.cpp b/src/plugins/roadgraph/exportdlg.cpp index 51391ae03ac7..257c9404d9e8 100644 --- a/src/plugins/roadgraph/exportdlg.cpp +++ b/src/plugins/roadgraph/exportdlg.cpp @@ -74,18 +74,18 @@ QgsVectorLayer* RgExportDlg::mapLayer() const QgsVectorLayer* myLayer = nullptr; QString layerId = mcbLayers->currentData().toString(); - if ( layerId == "-1" ) + if ( layerId == QLatin1String( "-1" ) ) { // create a temporary layer - myLayer = new QgsVectorLayer( QString( "LineString?crs=epsg:4326&memoryid=%1" ).arg( QUuid::createUuid().toString() ), "shortest path", "memory" ); + myLayer = new QgsVectorLayer( QStringLiteral( "LineString?crs=epsg:4326&memoryid=%1" ).arg( QUuid::createUuid().toString() ), QStringLiteral( "shortest path" ), QStringLiteral( "memory" ) ); QgsVectorDataProvider *prov = myLayer->dataProvider(); if ( !prov ) return nullptr; QList<QgsField> attrList; - attrList.append( QgsField( "length", QVariant::Double, "", 20, 8 ) ); - attrList.append( QgsField( "time", QVariant::Double, "", 20, 8 ) ); + attrList.append( QgsField( QStringLiteral( "length" ), QVariant::Double, QLatin1String( "" ), 20, 8 ) ); + attrList.append( QgsField( QStringLiteral( "time" ), QVariant::Double, QLatin1String( "" ), 20, 8 ) ); prov->addAttributes( attrList ); myLayer->updateFields(); QList<QgsMapLayer *> myList; diff --git a/src/plugins/roadgraph/linevectorlayersettings.cpp b/src/plugins/roadgraph/linevectorlayersettings.cpp index fa6150c6e923..a4abd996be84 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.cpp +++ b/src/plugins/roadgraph/linevectorlayersettings.cpp @@ -58,17 +58,17 @@ bool RgLineVectorLayerSettings::test() void RgLineVectorLayerSettings::read( const QgsProject *project ) { - int dd = project->readNumEntry( "roadgraphplugin", "/defaultDirection" ); - mDirection = project->readEntry( "roadgraphplugin", "/directionField" ); + int dd = project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ); + mDirection = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/directionField" ) ); mFirstPointToLastPointDirectionVal = - project->readEntry( "roadgraphplugin", "/FirstPointToLastPointDirectionVal" ); + project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/FirstPointToLastPointDirectionVal" ) ); mLastPointToFirstPointDirectionVal = - project->readEntry( "roadgraphplugin", "/LastPointToFirstPointDirectionVal" ); - mBothDirectionVal = project->readEntry( "roadgraphplugin", "/BothDirectionVal" ); - mSpeed = project->readEntry( "roadgraphplugin", "/speedField" ); - mDefaultSpeed = project->readDoubleEntry( "roadgraphplugin", "/defaultSpeed" ); - mLayerName = project->readEntry( "roadgraphplugin", "/layer" ); - mSpeedUnitName = project->readEntry( "roadgraphplugin", "/speedUnitName" ); + project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/LastPointToFirstPointDirectionVal" ) ); + mBothDirectionVal = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/BothDirectionVal" ) ); + mSpeed = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedField" ) ); + mDefaultSpeed = project->readDoubleEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultSpeed" ) ); + mLayerName = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/layer" ) ); + mSpeedUnitName = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedUnitName" ) ); if ( dd == 1 ) { @@ -87,17 +87,17 @@ void RgLineVectorLayerSettings::read( const QgsProject *project ) void RgLineVectorLayerSettings::write( QgsProject *project ) { - project->writeEntry( "roadgraphplugin", "/defaultDirection", mDefaultDirection ); - project->writeEntry( "roadgraphplugin", "/directionField", mDirection ); - project->writeEntry( "roadgraphplugin", "/FirstPointToLastPointDirectionVal", + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ), mDefaultDirection ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/directionField" ), mDirection ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/FirstPointToLastPointDirectionVal" ), mFirstPointToLastPointDirectionVal ); - project->writeEntry( "roadgraphplugin", "/LastPointToFirstPointDirectionVal", + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/LastPointToFirstPointDirectionVal" ), mLastPointToFirstPointDirectionVal ); - project->writeEntry( "roadgraphplugin", "/BothDirectionVal", mBothDirectionVal ); - project->writeEntry( "roadgraphplugin", "/speedField", mSpeed ); - project->writeEntry( "roadgraphplugin", "/defaultSpeed", mDefaultSpeed ); - project->writeEntry( "roadgraphplugin", "/layer", mLayerName ); - project->writeEntry( "roadgraphplugin", "/speedUnitName", mSpeedUnitName ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/BothDirectionVal" ), mBothDirectionVal ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedField" ), mSpeed ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultSpeed" ), mDefaultSpeed ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/layer" ), mLayerName ); + project->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedUnitName" ), mSpeedUnitName ); } // RgLineVectorLayerSettings::write( QgsProject *project ) QWidget* RgLineVectorLayerSettings::getGui( QWidget *parent ) @@ -135,10 +135,10 @@ void RgLineVectorLayerSettings::setFromGui( QWidget *myGui ) if ( w->mcbUnitOfSpeed->currentIndex() == 0 ) { - mSpeedUnitName = "m/s"; + mSpeedUnitName = QStringLiteral( "m/s" ); } else if ( w->mcbUnitOfSpeed->currentIndex() == 1 ) { - mSpeedUnitName = "km/h"; + mSpeedUnitName = QStringLiteral( "km/h" ); } } diff --git a/src/plugins/roadgraph/linevectorlayerwidget.cpp b/src/plugins/roadgraph/linevectorlayerwidget.cpp index 20f02710bbc8..47903e6fecfb 100644 --- a/src/plugins/roadgraph/linevectorlayerwidget.cpp +++ b/src/plugins/roadgraph/linevectorlayerwidget.cpp @@ -153,9 +153,9 @@ RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget( RgLineVectorLa mcbDirectionDefault->setCurrentIndex( 2 ); break; } - if ( s->mSpeedUnitName == "km/h" ) + if ( s->mSpeedUnitName == QLatin1String( "km/h" ) ) mcbUnitOfSpeed->setCurrentIndex( 1 ); - else if ( s->mSpeedUnitName == "m/s" ) + else if ( s->mSpeedUnitName == QLatin1String( "m/s" ) ) mcbUnitOfSpeed->setCurrentIndex( 0 ); } diff --git a/src/plugins/roadgraph/roadgraphplugin.cpp b/src/plugins/roadgraph/roadgraphplugin.cpp index 585d81309a2f..6183eb536aab 100644 --- a/src/plugins/roadgraph/roadgraphplugin.cpp +++ b/src/plugins/roadgraph/roadgraphplugin.cpp @@ -59,7 +59,7 @@ static const QString sName = QObject::tr( "Road graph plugin" ); static const QString sDescription = QObject::tr( "Solves the shortest path problem by tracing along line layers." ); static const QString sCategory = QObject::tr( "Vector" ); static const QString sPluginVersion = QObject::tr( "Version 0.1" ); -static const QString sPluginIcon = ":/roadgraph/road-fast.png"; +static const QString sPluginIcon = QStringLiteral( ":/roadgraph/road-fast.png" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; ////////////////////////////////////////////////////////////////////// @@ -80,8 +80,8 @@ RoadGraphPlugin::RoadGraphPlugin( QgisInterface * theQgisInterface ) , mQShortestPathDock( nullptr ) { mSettings = new RgLineVectorLayerSettings(); - mTimeUnitName = "h"; - mDistanceUnitName = "km"; + mTimeUnitName = QStringLiteral( "h" ); + mDistanceUnitName = QStringLiteral( "km" ); mTopologyToleranceFactor = 0.0; } @@ -102,7 +102,7 @@ void RoadGraphPlugin::initGui() // Create the action for tool mQSettingsAction = new QAction( QIcon( ":/roadgraph/road.png" ), tr( "Settings..." ), this ); - mQSettingsAction->setObjectName( "mQSettingsAction" ); + mQSettingsAction->setObjectName( QStringLiteral( "mQSettingsAction" ) ); // Set the what's this text mQSettingsAction->setWhatsThis( tr( "Road graph plugin settings" ) ); @@ -174,19 +174,19 @@ void RoadGraphPlugin::property() mTopologyToleranceFactor = dlg.topologyTolerance(); mSettings->write( QgsProject::instance() ); - QgsProject::instance()->writeEntry( "roadgraphplugin", "/pluginTimeUnit", mTimeUnitName ); - QgsProject::instance()->writeEntry( "roadgraphplugin", "/pluginDistanceUnit", mDistanceUnitName ); - QgsProject::instance()->writeEntry( "roadgraphplugin", "/topologyToleranceFactor", mTopologyToleranceFactor ); + QgsProject::instance()->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/pluginTimeUnit" ), mTimeUnitName ); + QgsProject::instance()->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/pluginDistanceUnit" ), mDistanceUnitName ); + QgsProject::instance()->writeEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/topologyToleranceFactor" ), mTopologyToleranceFactor ); setGuiElementsToDefault(); } void RoadGraphPlugin::projectRead() { mSettings->read( QgsProject::instance() ); - mTimeUnitName = QgsProject::instance()->readEntry( "roadgraphplugin", "/pluginTimeUnit", "h" ); - mDistanceUnitName = QgsProject::instance()->readEntry( "roadgraphplugin", "/pluginDistanceUnit", "km" ); + mTimeUnitName = QgsProject::instance()->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/pluginTimeUnit" ), QStringLiteral( "h" ) ); + mDistanceUnitName = QgsProject::instance()->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/pluginDistanceUnit" ), QStringLiteral( "km" ) ); mTopologyToleranceFactor = - QgsProject::instance()->readDoubleEntry( "roadgraphplugin", "/topologyToleranceFactor", 0.0 ); + QgsProject::instance()->readDoubleEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/topologyToleranceFactor" ), 0.0 ); setGuiElementsToDefault(); } diff --git a/src/plugins/roadgraph/shortestpathwidget.cpp b/src/plugins/roadgraph/shortestpathwidget.cpp index 7672d02c3964..1ab7529860fb 100644 --- a/src/plugins/roadgraph/shortestpathwidget.cpp +++ b/src/plugins/roadgraph/shortestpathwidget.cpp @@ -58,7 +58,7 @@ RgShortestPathWidget::RgShortestPathWidget( QWidget* theParent, RoadGraphPlugin , mPlugin( thePlugin ) { setWindowTitle( tr( "Shortest path" ) ); - setObjectName( "ShortestPathDock" ); + setObjectName( QStringLiteral( "ShortestPathDock" ) ); setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); QWidget *myWidget = new QWidget( this ); @@ -192,7 +192,7 @@ void RgShortestPathWidget::onSelectFrontPoint() void RgShortestPathWidget::setFrontPoint( const QgsPoint& pt ) { mPlugin->iface()->mapCanvas()->unsetMapTool( mFrontPointMapTool ); - mFrontPointLineEdit->setText( QString( "(%1, %2)" ).arg( QString::number( pt.x(), 'f' ), + mFrontPointLineEdit->setText( QStringLiteral( "(%1, %2)" ).arg( QString::number( pt.x(), 'f' ), QString::number( pt.y(), 'f' ) ) ); mFrontPoint = pt; @@ -216,7 +216,7 @@ void RgShortestPathWidget::setBackPoint( const QgsPoint& pt ) mPlugin->iface()->mapCanvas()->unsetMapTool( mBackPointMapTool ); mBackPoint = pt; - mBackPointLineEdit->setText( QString( "(%1, %2)" ).arg( QString::number( pt.x(), 'f' ), + mBackPointLineEdit->setText( QStringLiteral( "(%1, %2)" ).arg( QString::number( pt.x(), 'f' ), QString::number( pt.y(), 'f' ) ) ); double mupp = mPlugin->iface()->mapCanvas()->getCoordinateTransform()->mapUnitsPerPixel() * 2; diff --git a/src/plugins/roadgraph/units.cpp b/src/plugins/roadgraph/units.cpp index 11168afd2b96..5787607d770b 100644 --- a/src/plugins/roadgraph/units.cpp +++ b/src/plugins/roadgraph/units.cpp @@ -40,20 +40,20 @@ double Unit::multipler() const } Unit Unit::byName( const QString& name ) { - if ( name == "h" ) + if ( name == QLatin1String( "h" ) ) return Unit( name, 60*60 ); - else if ( name == "km" ) + else if ( name == QLatin1String( "km" ) ) return Unit( name, 1000 ); - else if ( name == "s" ) + else if ( name == QLatin1String( "s" ) ) return Unit( name, 1 ); - else if ( name == "m" ) + else if ( name == QLatin1String( "m" ) ) return Unit( name, 1 ); return Unit(); } SpeedUnit::SpeedUnit() - : mTimeUnit( "", 1 ) - , mDistanceUnit( "", 1 ) + : mTimeUnit( QLatin1String( "" ), 1 ) + , mDistanceUnit( QLatin1String( "" ), 1 ) { } @@ -68,15 +68,15 @@ QString SpeedUnit::name() const { if ( mDistanceUnit.name().isNull() || mTimeUnit.name().isNull() ) return QString(); - return mDistanceUnit.name() + QLatin1String( "/" ) + mTimeUnit.name(); + return mDistanceUnit.name() + QStringLiteral( "/" ) + mTimeUnit.name(); } SpeedUnit SpeedUnit::byName( const QString& name ) { - if ( name == "km/h" ) - return SpeedUnit( Unit::byName( "km" ), Unit::byName( "h" ) ); - else if ( name == "m/s" ) - return SpeedUnit( Unit::byName( "m" ), Unit::byName( "s" ) ); + if ( name == QLatin1String( "km/h" ) ) + return SpeedUnit( Unit::byName( QStringLiteral( "km" ) ), Unit::byName( QStringLiteral( "h" ) ) ); + else if ( name == QLatin1String( "m/s" ) ) + return SpeedUnit( Unit::byName( QStringLiteral( "m" ) ), Unit::byName( QStringLiteral( "s" ) ) ); return SpeedUnit(); } diff --git a/src/plugins/spatialquery/qgsspatialquerydialog.cpp b/src/plugins/spatialquery/qgsspatialquerydialog.cpp index 44d4e611dcd7..12a4ed61ef69 100644 --- a/src/plugins/spatialquery/qgsspatialquerydialog.cpp +++ b/src/plugins/spatialquery/qgsspatialquerydialog.cpp @@ -37,7 +37,7 @@ QgsSpatialQueryDialog::QgsSpatialQueryDialog( QWidget* parent, QgisInterface* if setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "SpatialQuery/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "SpatialQuery/geometry" ) ).toByteArray() ); mLayerReference = mLayerTarget = nullptr; mIface = iface; @@ -50,7 +50,7 @@ QgsSpatialQueryDialog::QgsSpatialQueryDialog( QWidget* parent, QgisInterface* if QgsSpatialQueryDialog::~QgsSpatialQueryDialog() { QSettings settings; - settings.setValue( "SpatialQuery/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "SpatialQuery/geometry" ), saveGeometry() ); disconnectAll(); delete mRubberSelectId; @@ -205,24 +205,24 @@ void QgsSpatialQueryDialog::showResultQuery( QDateTime *datetimeStart, QDateTime teStatus->append( msg ); msg = tr( "Begin at %L1" ).arg( datetimeStart->toString() ); teStatus->append( msg ); - teStatus->append( "" ); - msg = QString( "%1" ).arg( getDescriptionLayerShow( true ) ); + teStatus->append( QLatin1String( "" ) ); + msg = QStringLiteral( "%1" ).arg( getDescriptionLayerShow( true ) ); teStatus->append( msg ); msg = tr( "< %1 >" ).arg( cbOperation->currentText() ); teStatus->append( msg ); - msg = QString( "%1" ).arg( getDescriptionLayerShow( false ) ); + msg = QStringLiteral( "%1" ).arg( getDescriptionLayerShow( false ) ); teStatus->append( msg ); msg = tr( "Total of features = %1" ).arg( mFeatureResult.size() ); teStatus->append( msg ); - teStatus->append( "" ); + teStatus->append( QLatin1String( "" ) ); teStatus->append( tr( "Total of invalid features:" ) ); teStatus->append( getDescriptionInvalidFeaturesShow( true ) ); teStatus->append( getDescriptionInvalidFeaturesShow( false ) ); - teStatus->append( "" ); + teStatus->append( QLatin1String( "" ) ); double timeProcess = ( double )datetimeStart->secsTo( *datetimeEnd ) / 60.0; msg = tr( "Finish at %L1 (processing time %L2 minutes)" ).arg( datetimeEnd->toString() ).arg( timeProcess, 0, 'f', 2 ); teStatus->append( msg ); - teStatus->append( "" ); + teStatus->append( QLatin1String( "" ) ); ckbLogProcessing->setChecked( false ); QVariant item = QVariant::fromValue(( int )itemsResult ); @@ -264,8 +264,8 @@ QString QgsSpatialQueryDialog::getSubsetFIDs( const QgsFeatureIds *fids, const Q { lstFID.append( FID_TO_STRING( item.next() ) ); } - QString qFormat( "%1 in (%2)" ); - QString qReturn = qFormat.arg( fieldFID, lstFID.join( "," ) ); + QString qFormat( QStringLiteral( "%1 in (%2)" ) ); + QString qReturn = qFormat.arg( fieldFID, lstFID.join( QStringLiteral( "," ) ) ); lstFID.clear(); return qReturn; } // QString QgsSpatialQueryDialog::getSubsetFIDs( const QgsFeatureIds *fids, QString fieldFID ) @@ -274,13 +274,13 @@ QgsSpatialQueryDialog::TypeVerifyCreateSubset QgsSpatialQueryDialog::verifyCreat { QString providerType = mLayerTarget->providerType().toUpper(); // OGR - if ( providerType == "OGR" ) + if ( providerType == QLatin1String( "OGR" ) ) { - fieldFID = QString( "FID" ); + fieldFID = QStringLiteral( "FID" ); return verifyOk; } // Database Postgis and Spatialite - if ( providerType == "POSTGRES" || providerType == "SPATIALITE" ) + if ( providerType == QLatin1String( "POSTGRES" ) || providerType == QLatin1String( "SPATIALITE" ) ) { fieldFID = mLayerTarget->dataProvider()->fields().at( 0 ).name(); msg = tr( "Using the field \"%1\" for subset" ).arg( fieldFID ); @@ -322,7 +322,7 @@ QString QgsSpatialQueryDialog::getDescriptionLayerShow( bool isTarget ) ? tr( "%1 of %2" ).arg( lyr->selectedFeatureCount() ).arg( lyr->featureCount() ) : tr( "all = %1" ).arg( lyr->featureCount() ); - return QString( "%1 (%2)" ).arg( lyr->name(), sDescFeatures ); + return QStringLiteral( "%1 (%2)" ).arg( lyr->name(), sDescFeatures ); } // QString QgsSpatialQueryDialog::getDescriptionLayerShow(bool isTarget) QString QgsSpatialQueryDialog::getDescriptionInvalidFeaturesShow( bool isTarget ) @@ -347,7 +347,7 @@ QString QgsSpatialQueryDialog::getDescriptionInvalidFeaturesShow( bool isTarget ? tr( "%1 of %2(selected features)" ).arg( totalInvalid ).arg( lyr->selectedFeatureCount() ) : tr( "%1 of %2" ).arg( totalInvalid ).arg( lyr->featureCount() ); - return QString( "%1: %2" ).arg( lyr->name(), sDescFeatures ); + return QStringLiteral( "%1: %2" ).arg( lyr->name(), sDescFeatures ); } // QString QgsSpatialQueryDialog::getDescriptionInvalidFeatures(bool isTarget) void QgsSpatialQueryDialog::connectAll() @@ -408,15 +408,15 @@ QIcon QgsSpatialQueryDialog::getIconTypeGeometry( QgsWkbTypes::GeometryType geom QString theName; if ( geomType == QgsWkbTypes::PointGeometry ) { - theName = "/mIconPointLayer.svg"; + theName = QStringLiteral( "/mIconPointLayer.svg" ); } else if ( geomType == QgsWkbTypes::LineGeometry ) { - theName = "/mIconLineLayer.svg"; + theName = QStringLiteral( "/mIconLineLayer.svg" ); } else // Polygon { - theName = "/mIconPolygonLayer.svg"; + theName = QStringLiteral( "/mIconPolygonLayer.svg" ); } // Copy from qgisapp.cpp QString myPreferredPath = QgsApplication::activeThemePath() + QDir::separator() + theName; @@ -823,7 +823,7 @@ void QgsSpatialQueryDialog::on_pbCreateLayerItems_clicked() } QString subset = getSubsetFIDs( fids, fieldFID ); - QString name = QString( "%1 < %2 > %3" ).arg( mLayerTarget->name(), cbOperation->currentText(), mLayerReference->name() ); + QString name = QStringLiteral( "%1 < %2 > %3" ).arg( mLayerTarget->name(), cbOperation->currentText(), mLayerReference->name() ); if ( ! addLayerSubset( name, subset ) ) { msg = tr( "The query from \"%1\" using \"%2\" in field not possible." ).arg( mLayerTarget->name(), fieldFID ); @@ -849,7 +849,7 @@ void QgsSpatialQueryDialog::on_pbCreateLayerSelected_clicked() } QString subset = getSubsetFIDs( fids, fieldFID ); - QString name = QString( "%1 selected" ).arg( mLayerTarget->name() ); + QString name = QStringLiteral( "%1 selected" ).arg( mLayerTarget->name() ); if ( ! addLayerSubset( name, subset ) ) { msg = tr( "The query from \"%1\" using \"%2\" in field not possible." ).arg( mLayerTarget->name(), fieldFID ); diff --git a/src/plugins/spatialquery/qgsspatialqueryplugin.cpp b/src/plugins/spatialquery/qgsspatialqueryplugin.cpp index 33ca2f925094..878687f0ff3e 100644 --- a/src/plugins/spatialquery/qgsspatialqueryplugin.cpp +++ b/src/plugins/spatialquery/qgsspatialqueryplugin.cpp @@ -45,7 +45,7 @@ static const QString description_ = QObject::tr( "A plugin that makes spatial qu static const QString category_ = QObject::tr( "Vector" ); static const QString version_ = QObject::tr( "Version 0.1" ); static const QgisPlugin::PLUGINTYPE type_ = QgisPlugin::UI; -static const QString icon_ = ":/icons/spatialquery.png"; +static const QString icon_ = QStringLiteral( ":/icons/spatialquery.png" ); /** * Constructor for the plugin. The plugin is passed a pointer to the main app @@ -74,12 +74,12 @@ void QgsSpatialQueryPlugin::initGui() // Create the action for tool mSpatialQueryAction = new QAction( QIcon(), tr( "&Spatial Query" ), this ); - mSpatialQueryAction->setObjectName( "mSpatialQueryAction" ); + mSpatialQueryAction->setObjectName( QStringLiteral( "mSpatialQueryAction" ) ); // Connect the action to the spatialQuery slot connect( mSpatialQueryAction, SIGNAL( triggered() ), this, SLOT( run() ) ); - setCurrentTheme( "" ); + setCurrentTheme( QLatin1String( "" ) ); // this is called when the icon theme is changed connect( mIface, SIGNAL( currentThemeChanged( QString ) ), this, SLOT( setCurrentTheme( QString ) ) ); @@ -136,7 +136,7 @@ void QgsSpatialQueryPlugin::run() void QgsSpatialQueryPlugin::setCurrentTheme( const QString& ) { if ( mSpatialQueryAction ) - mSpatialQueryAction->setIcon( getThemeIcon( "/spatialquery.png" ) ); + mSpatialQueryAction->setIcon( getThemeIcon( QStringLiteral( "/spatialquery.png" ) ) ); } QIcon QgsSpatialQueryPlugin::getThemeIcon( const QString &theName ) diff --git a/src/plugins/topology/dockModel.cpp b/src/plugins/topology/dockModel.cpp index 6c3b01d0fe7d..a89cc6cccfb8 100644 --- a/src/plugins/topology/dockModel.cpp +++ b/src/plugins/topology/dockModel.cpp @@ -81,7 +81,7 @@ QVariant DockModel::data( const QModelIndex &index, int role ) const break; case 1: if ( !mErrorlist[row]->featurePairs().first().layer ) - val = QString( "Unknown" ); + val = QStringLiteral( "Unknown" ); else val = mErrorlist[row]->featurePairs().first().layer->name(); break; diff --git a/src/plugins/topology/rulesDialog.cpp b/src/plugins/topology/rulesDialog.cpp index 4ee459b17c1a..eef862e302b2 100644 --- a/src/plugins/topology/rulesDialog.cpp +++ b/src/plugins/topology/rulesDialog.cpp @@ -72,7 +72,7 @@ rulesDialog::~rulesDialog() void rulesDialog::setHorizontalHeaderItems() { QStringList labels; - labels << tr( "Test" ) << tr( "Layer #1" ) << tr( "Layer #2" ) << tr( "Tolerance" ) << "" << ""; + labels << tr( "Test" ) << tr( "Layer #1" ) << tr( "Layer #2" ) << tr( "Tolerance" ) << QLatin1String( "" ) << QLatin1String( "" ); mRulesTable->setHorizontalHeaderLabels( labels ); } @@ -83,12 +83,12 @@ void rulesDialog::readTest( int index, QgsMapLayerRegistry* layerRegistry ) QString layer2Id; QString tolerance; QgsProject* project = QgsProject::instance(); - QString postfix = QString( "%1" ).arg( index ); + QString postfix = QStringLiteral( "%1" ).arg( index ); - testName = project->readEntry( "Topol", "/testname_" + postfix, "" ); - tolerance = project->readEntry( "Topol", "/tolerance_" + postfix, "" ); - layer1Id = project->readEntry( "Topol", "/layer1_" + postfix, "" ); - layer2Id = project->readEntry( "Topol", "/layer2_" + postfix, "" ); + testName = project->readEntry( QStringLiteral( "Topol" ), "/testname_" + postfix, QLatin1String( "" ) ); + tolerance = project->readEntry( QStringLiteral( "Topol" ), "/tolerance_" + postfix, QLatin1String( "" ) ); + layer1Id = project->readEntry( QStringLiteral( "Topol" ), "/layer1_" + postfix, QLatin1String( "" ) ); + layer2Id = project->readEntry( QStringLiteral( "Topol" ), "/layer2_" + postfix, QLatin1String( "" ) ); QgsVectorLayer* l1; if ( !( QgsVectorLayer* )layerRegistry->mapLayers().contains( layer1Id ) ) @@ -113,7 +113,7 @@ void rulesDialog::readTest( int index, QgsMapLayerRegistry* layerRegistry ) } } else - layer2Name = "No layer"; + layer2Name = QStringLiteral( "No layer" ); int row = index; mRulesTable->insertRow( row ); @@ -150,7 +150,7 @@ void rulesDialog::projectRead() { clearRules(); QgsMapLayerRegistry* layerRegistry = QgsMapLayerRegistry::instance(); - int testCount = QgsProject::instance()->readNumEntry( "Topol", "/testCount" ); + int testCount = QgsProject::instance()->readNumEntry( QStringLiteral( "Topol" ), QStringLiteral( "/testCount" ) ); mRulesTable->clearContents(); for ( int i = 0; i < testCount; ++i ) @@ -256,7 +256,7 @@ void rulesDialog::addRule() mRulesTable->setItem( row, 2, newItem ); if ( mTestConfMap[test].useTolerance ) - newItem = new QTableWidgetItem( QString( "%1" ).arg( mToleranceBox->value() ) ); + newItem = new QTableWidgetItem( QStringLiteral( "%1" ).arg( mToleranceBox->value() ) ); else newItem = new QTableWidgetItem( tr( "No tolerance" ) ); @@ -279,14 +279,14 @@ void rulesDialog::addRule() mRulesTable->setItem( row, 5, newItem ); // save state to the project file..... - QString postfix = QString( "%1" ).arg( row ); + QString postfix = QStringLiteral( "%1" ).arg( row ); QgsProject* project = QgsProject::instance(); - project->writeEntry( "Topol", "/testCount", row + 1 ); - project->writeEntry( "Topol", "/testname_" + postfix, test ); - project->writeEntry( "Topol", "/tolerance_" + postfix, QString( "%1" ).arg( mToleranceBox->value() ) ); - project->writeEntry( "Topol", "/layer1_" + postfix, layer1ID ); - project->writeEntry( "Topol", "/layer2_" + postfix, layer2ID ); + project->writeEntry( QStringLiteral( "Topol" ), QStringLiteral( "/testCount" ), row + 1 ); + project->writeEntry( QStringLiteral( "Topol" ), "/testname_" + postfix, test ); + project->writeEntry( QStringLiteral( "Topol" ), "/tolerance_" + postfix, QStringLiteral( "%1" ).arg( mToleranceBox->value() ) ); + project->writeEntry( QStringLiteral( "Topol" ), "/layer1_" + postfix, layer1ID ); + project->writeEntry( QStringLiteral( "Topol" ), "/layer2_" + postfix, layer2ID ); // reset controls to default mRuleBox->setCurrentIndex( 0 ); diff --git a/src/plugins/topology/topol.cpp b/src/plugins/topology/topol.cpp index f4e8878990cd..cfb84201f6d9 100644 --- a/src/plugins/topology/topol.cpp +++ b/src/plugins/topology/topol.cpp @@ -35,7 +35,7 @@ static const QString sDescription = QObject::tr( "A Plugin for finding topologic static const QString sCategory = QObject::tr( "Vector" ); static const QString sPluginVersion = QObject::tr( "Version 0.1" ); static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = ":/topology/mActionTopologyChecker.svg"; +static const QString sPluginIcon = QStringLiteral( ":/topology/mActionTopologyChecker.svg" ); ////////////////////////////////////////////////////////////////////// // @@ -69,7 +69,7 @@ void Topol::initGui() delete mQActionPointer; mQActionPointer = new QAction( QIcon( sPluginIcon ), sName, this ); - mQActionPointer->setObjectName( "mQActionPointer" ); + mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); //mQActionPointer = new QAction( QIcon(), tr( "Topology Checker" ), this ); mQActionPointer->setCheckable( true ); diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp b/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp index c5606c060384..8b4baddf188d 100644 --- a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp +++ b/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp @@ -86,7 +86,7 @@ QgsZonalStatisticsDialog::QgsZonalStatisticsDialog( QgisInterface* iface ): QDia varietyItem->setData( Qt::UserRole, QgsZonalStatistics::Variety ); mStatsListWidget->addItem( varietyItem ); QSettings settings; - restoreGeometry( settings.value( "Plugin-ZonalStatistics/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "Plugin-ZonalStatistics/geometry" ) ).toByteArray() ); insertAvailableLayers(); mColumnPrefixLineEdit->setText( proposeAttributePrefix() ); @@ -97,13 +97,13 @@ QgsZonalStatisticsDialog::QgsZonalStatisticsDialog(): QDialog( nullptr ), mIface setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "Plugin-ZonalStatistics/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "Plugin-ZonalStatistics/geometry" ) ).toByteArray() ); } QgsZonalStatisticsDialog::~QgsZonalStatisticsDialog() { QSettings settings; - settings.setValue( "Plugin-ZonalStatistics/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "Plugin-ZonalStatistics/geometry" ), saveGeometry() ); } void QgsZonalStatisticsDialog::insertAvailableLayers() @@ -119,7 +119,7 @@ void QgsZonalStatisticsDialog::insertAvailableLayers() if ( rl ) { QgsRasterDataProvider* rp = rl->dataProvider(); - if ( rp && rp->name() == "gdal" ) + if ( rp && rp->name() == QLatin1String( "gdal" ) ) { mRasterLayerComboBox->addItem( rl->name(), QVariant( rl->id() ) ); } @@ -195,10 +195,10 @@ QString QgsZonalStatisticsDialog::proposeAttributePrefix() const { if ( !polygonLayer() ) { - return ""; + return QLatin1String( "" ); } - QString proposedPrefix = ""; + QString proposedPrefix = QLatin1String( "" ); while ( !prefixIsValid( proposedPrefix ) ) { proposedPrefix.prepend( '_' ); diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp b/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp index 2995eb94ae40..fe4f5d3c16b3 100644 --- a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp +++ b/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp @@ -27,7 +27,7 @@ static const QString name_ = QObject::tr( "Zonal statistics plugin" ); static const QString description_ = QObject::tr( "A plugin to calculate count, sum, mean of rasters for each polygon of a vector layer" ); static const QString category_ = QObject::tr( "Raster" ); static const QString version_ = QObject::tr( "Version 0.1" ); -static const QString pluginIcon_ = ":/zonal_statistics/raster-stats.png"; +static const QString pluginIcon_ = QStringLiteral( ":/zonal_statistics/raster-stats.png" ); QgsZonalStatisticsPlugin::QgsZonalStatisticsPlugin( QgisInterface* iface ) : mIface( iface ) @@ -44,7 +44,7 @@ void QgsZonalStatisticsPlugin::initGui() delete mAction; mAction = new QAction( QIcon( ":/zonal_statistics/raster-stats.png" ), tr( "&Zonal statistics" ), nullptr ); - mAction->setObjectName( "ZonalStatistics" ); + mAction->setObjectName( QStringLiteral( "ZonalStatistics" ) ); QObject::connect( mAction, SIGNAL( triggered() ), this, SLOT( run() ) ); mIface->addRasterToolBarIcon( mAction ); mIface->addPluginToRasterMenu( tr( "&Zonal statistics" ), mAction ); diff --git a/src/providers/arcgisrest/qgsafsdataitems.cpp b/src/providers/arcgisrest/qgsafsdataitems.cpp index d06bca1449d6..8d73ac6c7734 100644 --- a/src/providers/arcgisrest/qgsafsdataitems.cpp +++ b/src/providers/arcgisrest/qgsafsdataitems.cpp @@ -29,7 +29,7 @@ QgsAfsRootItem::QgsAfsRootItem( QgsDataItem* parent, const QString &name, const : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconAfs.svg"; + mIconName = QStringLiteral( "mIconAfs.svg" ); populate(); } @@ -39,9 +39,9 @@ QVector<QgsDataItem*> QgsAfsRootItem::createChildren() Q_FOREACH ( const QString& connName, QgsOwsConnection::connectionList( "ArcGisFeatureServer" ) ) { - QgsOwsConnection connection( "ArcGisFeatureServer", connName ); + QgsOwsConnection connection( QStringLiteral( "ArcGisFeatureServer" ), connName ); QString path = "afs:/" + connName; - connections.append( new QgsAfsConnectionItem( this, connName, path, connection.uri().param( "url" ) ) ); + connections.append( new QgsAfsConnectionItem( this, connName, path, connection.uri().param( QStringLiteral( "url" ) ) ) ); } return connections; } @@ -67,7 +67,7 @@ void QgsAfsRootItem::connectionsChanged() void QgsAfsRootItem::newConnection() { - QgsNewHttpConnection nc( 0, "/Qgis/connections-afs/" ); + QgsNewHttpConnection nc( 0, QStringLiteral( "/Qgis/connections-afs/" ) ); nc.setWindowTitle( tr( "Create a new AFS connection" ) ); if ( nc.exec() ) @@ -82,7 +82,7 @@ QgsAfsConnectionItem::QgsAfsConnectionItem( QgsDataItem* parent, const QString & : QgsDataCollectionItem( parent, name, path ) , mUrl( url ) { - mIconName = "mIconAfs.svg"; + mIconName = QStringLiteral( "mIconAfs.svg" ); } QVector<QgsDataItem*> QgsAfsConnectionItem::createChildren() @@ -94,13 +94,13 @@ QVector<QgsDataItem*> QgsAfsConnectionItem::createChildren() { return layers; } - QString authid = QgsArcGisRestUtils::parseSpatialReference( serviceData["spatialReference"].toMap() ).authid(); + QString authid = QgsArcGisRestUtils::parseSpatialReference( serviceData[QStringLiteral( "spatialReference" )].toMap() ).authid(); foreach ( const QVariant& layerInfo, serviceData["layers"].toList() ) { QVariantMap layerInfoMap = layerInfo.toMap(); - QString id = layerInfoMap["id"].toString(); - QgsAfsLayerItem* layer = new QgsAfsLayerItem( this, mName, mUrl + "/" + id, layerInfoMap["name"].toString(), authid ); + QString id = layerInfoMap[QStringLiteral( "id" )].toString(); + QgsAfsLayerItem* layer = new QgsAfsLayerItem( this, mName, mUrl + "/" + id, layerInfoMap[QStringLiteral( "name" )].toString(), authid ); layers.append( layer ); } @@ -130,7 +130,7 @@ QList<QAction*> QgsAfsConnectionItem::actions() void QgsAfsConnectionItem::editConnection() { - QgsNewHttpConnection nc( 0, "/Qgis/connections-afs/", mName ); + QgsNewHttpConnection nc( 0, QStringLiteral( "/Qgis/connections-afs/" ), mName ); nc.setWindowTitle( tr( "Modify AFS connection" ) ); if ( nc.exec() ) @@ -141,16 +141,16 @@ void QgsAfsConnectionItem::editConnection() void QgsAfsConnectionItem::deleteConnection() { - QgsOwsConnection::deleteConnection( "ArcGisFeatureServer", mName ); + QgsOwsConnection::deleteConnection( QStringLiteral( "ArcGisFeatureServer" ), mName ); mParent->refresh(); } /////////////////////////////////////////////////////////////////////////////// QgsAfsLayerItem::QgsAfsLayerItem( QgsDataItem* parent, const QString &name, const QString &url, const QString &title, const QString& authid ) - : QgsLayerItem( parent, title, parent->path() + "/" + name, QString(), QgsLayerItem::Vector, "arcgisfeatureserver" ) + : QgsLayerItem( parent, title, parent->path() + "/" + name, QString(), QgsLayerItem::Vector, QStringLiteral( "arcgisfeatureserver" ) ) { - mUri = QString( "crs='%1' url='%2'" ).arg( authid, url ); + mUri = QStringLiteral( "crs='%1' url='%2'" ).arg( authid, url ); setState( Populated ); - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); } diff --git a/src/providers/arcgisrest/qgsafsprovider.cpp b/src/providers/arcgisrest/qgsafsprovider.cpp index 9c7a7818a29e..1b67e6d3a9c1 100644 --- a/src/providers/arcgisrest/qgsafsprovider.cpp +++ b/src/providers/arcgisrest/qgsafsprovider.cpp @@ -38,22 +38,22 @@ QgsAfsProvider::QgsAfsProvider( const QString& uri ) mDataSource = QgsDataSourceUri( uri ); // Set CRS - mSourceCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mDataSource.param( "crs" ) ); + mSourceCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mDataSource.param( QStringLiteral( "crs" ) ) ); // Get layer info QString errorTitle, errorMessage; - QVariantMap layerData = QgsArcGisRestUtils::getLayerInfo( mDataSource.param( "url" ), errorTitle, errorMessage ); + QVariantMap layerData = QgsArcGisRestUtils::getLayerInfo( mDataSource.param( QStringLiteral( "url" ) ), errorTitle, errorMessage ); if ( layerData.isEmpty() ) { pushError( errorTitle + ": " + errorMessage ); - appendError( QgsErrorMessage( tr( "getLayerInfo failed" ), "AFSProvider" ) ); + appendError( QgsErrorMessage( tr( "getLayerInfo failed" ), QStringLiteral( "AFSProvider" ) ) ); return; } - mLayerName = layerData["name"].toString(); - mLayerDescription = layerData["description"].toString(); + mLayerName = layerData[QStringLiteral( "name" )].toString(); + mLayerDescription = layerData[QStringLiteral( "description" )].toString(); // Set extent - QStringList coords = mDataSource.param( "bbox" ).split( "," ); + QStringList coords = mDataSource.param( QStringLiteral( "bbox" ) ).split( QStringLiteral( "," ) ); if ( coords.size() == 4 ) { bool xminOk = false, yminOk = false, xmaxOk = false, ymaxOk = false; @@ -66,21 +66,21 @@ QgsAfsProvider::QgsAfsProvider( const QString& uri ) } if ( mExtent.isEmpty() ) { - QVariantMap layerExtentMap = layerData["extent"].toMap(); + QVariantMap layerExtentMap = layerData[QStringLiteral( "extent" )].toMap(); bool xminOk = false, yminOk = false, xmaxOk = false, ymaxOk = false; - mExtent.setXMinimum( layerExtentMap["xmin"].toDouble( &xminOk ) ); - mExtent.setYMinimum( layerExtentMap["ymin"].toDouble( &yminOk ) ); - mExtent.setXMaximum( layerExtentMap["xmax"].toDouble( &xmaxOk ) ); - mExtent.setYMaximum( layerExtentMap["ymax"].toDouble( &ymaxOk ) ); + mExtent.setXMinimum( layerExtentMap[QStringLiteral( "xmin" )].toDouble( &xminOk ) ); + mExtent.setYMinimum( layerExtentMap[QStringLiteral( "ymin" )].toDouble( &yminOk ) ); + mExtent.setXMaximum( layerExtentMap[QStringLiteral( "xmax" )].toDouble( &xmaxOk ) ); + mExtent.setYMaximum( layerExtentMap[QStringLiteral( "ymax" )].toDouble( &ymaxOk ) ); if ( !xminOk || !yminOk || !xmaxOk || !ymaxOk ) { - appendError( QgsErrorMessage( tr( "Could not retrieve layer extent" ), "AFSProvider" ) ); + appendError( QgsErrorMessage( tr( "Could not retrieve layer extent" ), QStringLiteral( "AFSProvider" ) ) ); return; } - QgsCoordinateReferenceSystem extentCrs = QgsArcGisRestUtils::parseSpatialReference( layerExtentMap["spatialReference"].toMap() ); + QgsCoordinateReferenceSystem extentCrs = QgsArcGisRestUtils::parseSpatialReference( layerExtentMap[QStringLiteral( "spatialReference" )].toMap() ); if ( !extentCrs.isValid() ) { - appendError( QgsErrorMessage( tr( "Could not parse spatial reference" ), "AFSProvider" ) ); + appendError( QgsErrorMessage( tr( "Could not parse spatial reference" ), QStringLiteral( "AFSProvider" ) ) ); return; } mExtent = QgsCoordinateTransform( extentCrs, mSourceCRS ).transformBoundingBox( mExtent ); @@ -90,24 +90,24 @@ QgsAfsProvider::QgsAfsProvider( const QString& uri ) foreach ( const QVariant& fieldData, layerData["fields"].toList() ) { QVariantMap fieldDataMap = fieldData.toMap(); - QString fieldName = fieldDataMap["name"].toString(); - QVariant::Type type = QgsArcGisRestUtils::mapEsriFieldType( fieldDataMap["type"].toString() ); - if ( fieldName == "geometry" || type == QVariant::Invalid ) + QString fieldName = fieldDataMap[QStringLiteral( "name" )].toString(); + QVariant::Type type = QgsArcGisRestUtils::mapEsriFieldType( fieldDataMap[QStringLiteral( "type" )].toString() ); + if ( fieldName == QLatin1String( "geometry" ) || type == QVariant::Invalid ) { QgsDebugMsg( QString( "Skipping unsupported (or possibly geometry) field" ).arg( fieldName ) ); continue; } - QgsField field( fieldName, type, fieldDataMap["type"].toString(), fieldDataMap["length"].toInt() ); + QgsField field( fieldName, type, fieldDataMap[QStringLiteral( "type" )].toString(), fieldDataMap[QStringLiteral( "length" )].toInt() ); mFields.append( field ); } // Determine geometry type - bool hasM = layerData["hasM"].toBool(); - bool hasZ = layerData["hasZ"].toBool(); - mGeometryType = QgsArcGisRestUtils::mapEsriGeometryType( layerData["geometryType"].toString() ); + bool hasM = layerData[QStringLiteral( "hasM" )].toBool(); + bool hasZ = layerData[QStringLiteral( "hasZ" )].toBool(); + mGeometryType = QgsArcGisRestUtils::mapEsriGeometryType( layerData[QStringLiteral( "geometryType" )].toString() ); if ( mGeometryType == QgsWkbTypes::Unknown ) { - appendError( QgsErrorMessage( tr( "Failed to determine geometry type" ), "AFSProvider" ) ); + appendError( QgsErrorMessage( tr( "Failed to determine geometry type" ), QStringLiteral( "AFSProvider" ) ) ); return; } mGeometryType = QgsWkbTypes::zmType( mGeometryType, hasZ, hasM ); @@ -115,18 +115,18 @@ QgsAfsProvider::QgsAfsProvider( const QString& uri ) // Read OBJECTIDs of all features: these may not be a continuous sequence, // and we need to store these to iterate through the features. This query // also returns the name of the ObjectID field. - QVariantMap objectIdData = QgsArcGisRestUtils::getObjectIds( mDataSource.param( "url" ), errorTitle, errorMessage ); + QVariantMap objectIdData = QgsArcGisRestUtils::getObjectIds( mDataSource.param( QStringLiteral( "url" ) ), errorTitle, errorMessage ); if ( objectIdData.isEmpty() ) { - appendError( QgsErrorMessage( tr( "getObjectIds failed: %1 - %2" ).arg( errorTitle, errorMessage ), "AFSProvider" ) ); + appendError( QgsErrorMessage( tr( "getObjectIds failed: %1 - %2" ).arg( errorTitle, errorMessage ), QStringLiteral( "AFSProvider" ) ) ); return; } - if ( !objectIdData["objectIdFieldName"].isValid() || !objectIdData["objectIds"].isValid() ) + if ( !objectIdData[QStringLiteral( "objectIdFieldName" )].isValid() || !objectIdData[QStringLiteral( "objectIds" )].isValid() ) { - appendError( QgsErrorMessage( tr( "Failed to determine objectIdFieldName and/or objectIds" ), "AFSProvider" ) ); + appendError( QgsErrorMessage( tr( "Failed to determine objectIdFieldName and/or objectIds" ), QStringLiteral( "AFSProvider" ) ) ); return; } - mObjectIdFieldName = objectIdData["objectIdFieldName"].toString(); + mObjectIdFieldName = objectIdData[QStringLiteral( "objectIdFieldName" )].toString(); for ( int idx = 0, nIdx = mFields.count(); idx < nIdx; ++idx ) { if ( mFields.at( idx ).name() == mObjectIdFieldName ) @@ -194,7 +194,7 @@ bool QgsAfsProvider::getFeature( QgsFeatureId id, QgsFeature &f, bool fetchGeome // Query QString errorTitle, errorMessage; QVariantMap queryData = QgsArcGisRestUtils::getObjects( - mDataSource.param( "url" ), objectIds, mDataSource.param( "crs" ), fetchGeometry, + mDataSource.param( QStringLiteral( "url" ) ), objectIds, mDataSource.param( QStringLiteral( "crs" ) ), fetchGeometry, fetchAttribNames, QgsWkbTypes::hasM( mGeometryType ), QgsWkbTypes::hasZ( mGeometryType ), filterRect, errorTitle, errorMessage ); if ( queryData.isEmpty() ) @@ -204,7 +204,7 @@ bool QgsAfsProvider::getFeature( QgsFeatureId id, QgsFeature &f, bool fetchGeome return false; } - QVariantList featuresData = queryData["features"].toList(); + QVariantList featuresData = queryData[QStringLiteral( "features" )].toList(); if ( featuresData.isEmpty() ) { QgsDebugMsg( "Query returned no features" ); @@ -221,7 +221,7 @@ bool QgsAfsProvider::getFeature( QgsFeatureId id, QgsFeature &f, bool fetchGeome // Set attributes if ( !fetchAttribIdx.isEmpty() ) { - QVariantMap attributesData = featureData["attributes"].toMap(); + QVariantMap attributesData = featureData[QStringLiteral( "attributes" )].toMap(); feature.setFields( mFields ); QgsAttributes attributes( mFields.size() ); foreach ( int idx, fetchAttribIdx ) @@ -234,8 +234,8 @@ bool QgsAfsProvider::getFeature( QgsFeatureId id, QgsFeature &f, bool fetchGeome // Set geometry if ( fetchGeometry ) { - QVariantMap geometryData = featureData["geometry"].toMap(); - QgsAbstractGeometry* geometry = QgsArcGisRestUtils::parseEsriGeoJSON( geometryData, queryData["geometryType"].toString(), + QVariantMap geometryData = featureData[QStringLiteral( "geometry" )].toMap(); + QgsAbstractGeometry* geometry = QgsArcGisRestUtils::parseEsriGeoJSON( geometryData, queryData[QStringLiteral( "geometryType" )].toString(), QgsWkbTypes::hasM( mGeometryType ), QgsWkbTypes::hasZ( mGeometryType ) ); // Above might return 0, which is ok since in theory empty geometries are allowed feature.setGeometry( QgsGeometry( geometry ) ); diff --git a/src/providers/arcgisrest/qgsafsprovider.h b/src/providers/arcgisrest/qgsafsprovider.h index 44d28fff7421..a807897026b0 100644 --- a/src/providers/arcgisrest/qgsafsprovider.h +++ b/src/providers/arcgisrest/qgsafsprovider.h @@ -40,7 +40,7 @@ class QgsAfsProvider : public QgsVectorDataProvider /* Inherited from QgsVectorDataProvider */ QgsAbstractFeatureSource* featureSource() const override; - QString storageType() const override { return "ESRI ArcGIS Feature Server"; } + QString storageType() const override { return QStringLiteral( "ESRI ArcGIS Feature Server" ); } QgsFeatureIterator getFeatures( const QgsFeatureRequest& request = QgsFeatureRequest() ) const override; QgsWkbTypes::Type wkbType() const override { return static_cast<QgsWkbTypes::Type>( mGeometryType ); } long featureCount() const override { return mObjectIds.size(); } diff --git a/src/providers/arcgisrest/qgsafsproviderextern.cpp b/src/providers/arcgisrest/qgsafsproviderextern.cpp index 6be15dd6b877..865c191d3d98 100644 --- a/src/providers/arcgisrest/qgsafsproviderextern.cpp +++ b/src/providers/arcgisrest/qgsafsproviderextern.cpp @@ -21,8 +21,8 @@ #include "qgsafssourceselect.h" #include "qgsowsconnection.h" -const QString AFS_KEY = "arcgisfeatureserver"; -const QString AFS_DESCRIPTION = "ArcGIS Feature Server data provider"; +const QString AFS_KEY = QStringLiteral( "arcgisfeatureserver" ); +const QString AFS_DESCRIPTION = QStringLiteral( "ArcGIS Feature Server data provider" ); QGISEXTERN QgsAfsProvider * classFactory( const QString *uri ) @@ -59,17 +59,17 @@ QGISEXTERN QgsDataItem *dataItem( QString thePath, QgsDataItem *parentItem ) { if ( thePath.isEmpty() ) { - return new QgsAfsRootItem( parentItem, "ArcGisFeatureServer", "arcgisfeatureserver:" ); + return new QgsAfsRootItem( parentItem, QStringLiteral( "ArcGisFeatureServer" ), QStringLiteral( "arcgisfeatureserver:" ) ); } // path schema: afs:/connection name (used by OWS) - if ( thePath.startsWith( "afs:/" ) ) + if ( thePath.startsWith( QLatin1String( "afs:/" ) ) ) { QString connectionName = thePath.split( '/' ).last(); - if ( QgsOwsConnection::connectionList( "ArcGisFeatureServer" ).contains( connectionName ) ) + if ( QgsOwsConnection::connectionList( QStringLiteral( "ArcGisFeatureServer" ) ).contains( connectionName ) ) { - QgsOwsConnection connection( "ArcGisFeatureServer", connectionName ); - return new QgsAfsConnectionItem( parentItem, "ArcGisFeatureServer", thePath, connection.uri().param( "url" ) ); + QgsOwsConnection connection( QStringLiteral( "ArcGisFeatureServer" ), connectionName ); + return new QgsAfsConnectionItem( parentItem, QStringLiteral( "ArcGisFeatureServer" ), thePath, connection.uri().param( QStringLiteral( "url" ) ) ); } } diff --git a/src/providers/arcgisrest/qgsafssourceselect.cpp b/src/providers/arcgisrest/qgsafssourceselect.cpp index 49cbde18a825..a256fcd9f224 100644 --- a/src/providers/arcgisrest/qgsafssourceselect.cpp +++ b/src/providers/arcgisrest/qgsafssourceselect.cpp @@ -27,7 +27,7 @@ QgsAfsSourceSelect::QgsAfsSourceSelect( QWidget* parent, Qt::WindowFlags fl, bool embeddedMode ) - : QgsSourceSelectDialog( "ArcGisFeatureServer", QgsSourceSelectDialog::FeatureService, parent, fl ) + : QgsSourceSelectDialog( QStringLiteral( "ArcGisFeatureServer" ), QgsSourceSelectDialog::FeatureService, parent, fl ) { if ( embeddedMode ) { @@ -38,7 +38,7 @@ QgsAfsSourceSelect::QgsAfsSourceSelect( QWidget* parent, Qt::WindowFlags fl, boo bool QgsAfsSourceSelect::connectToService( const QgsOwsConnection &connection ) { QString errorTitle, errorMessage; - QVariantMap serviceInfoMap = QgsArcGisRestUtils::getServiceInfo( connection.uri().param( "url" ), errorTitle, errorMessage ); + QVariantMap serviceInfoMap = QgsArcGisRestUtils::getServiceInfo( connection.uri().param( QStringLiteral( "url" ) ), errorTitle, errorMessage ); if ( serviceInfoMap.isEmpty() ) { QMessageBox::warning( this, tr( "Error" ), tr( "Failed to retrieve service capabilities:\n%1: %2" ).arg( errorTitle, errorMessage ) ); @@ -49,41 +49,41 @@ bool QgsAfsSourceSelect::connectToService( const QgsOwsConnection &connection ) foreach ( const QVariant& layerInfo, serviceInfoMap["layers"].toList() ) { QVariantMap layerInfoMap = layerInfo.toMap(); - if ( !layerInfoMap["id"].isValid() ) + if ( !layerInfoMap[QStringLiteral( "id" )].isValid() ) { continue; } // Get layer info - QVariantMap layerData = QgsArcGisRestUtils::getLayerInfo( connection.uri().param( "url" ) + "/" + layerInfoMap["id"].toString(), errorTitle, errorMessage ); + QVariantMap layerData = QgsArcGisRestUtils::getLayerInfo( connection.uri().param( QStringLiteral( "url" ) ) + "/" + layerInfoMap[QStringLiteral( "id" )].toString(), errorTitle, errorMessage ); if ( layerData.isEmpty() ) { - layerErrors.append( tr( "Layer %1: %2 - %3" ).arg( layerInfoMap["id"].toString(), errorTitle, errorMessage ) ); + layerErrors.append( tr( "Layer %1: %2 - %3" ).arg( layerInfoMap[QStringLiteral( "id" )].toString(), errorTitle, errorMessage ) ); continue; } // insert the typenames, titles and abstracts into the tree view - QStandardItem* idItem = new QStandardItem( layerData["id"].toString() ); - QStandardItem* nameItem = new QStandardItem( layerData["name"].toString() ); - QStandardItem* abstractItem = new QStandardItem( layerData["description"].toString() ); - abstractItem->setToolTip( layerData["description"].toString() ); + QStandardItem* idItem = new QStandardItem( layerData[QStringLiteral( "id" )].toString() ); + QStandardItem* nameItem = new QStandardItem( layerData[QStringLiteral( "name" )].toString() ); + QStandardItem* abstractItem = new QStandardItem( layerData[QStringLiteral( "description" )].toString() ); + abstractItem->setToolTip( layerData[QStringLiteral( "description" )].toString() ); QStandardItem* cachedItem = new QStandardItem(); QStandardItem* filterItem = new QStandardItem(); cachedItem->setCheckable( true ); cachedItem->setCheckState( Qt::Checked ); - QgsCoordinateReferenceSystem crs = QgsArcGisRestUtils::parseSpatialReference( serviceInfoMap["spatialReference"].toMap() ); + QgsCoordinateReferenceSystem crs = QgsArcGisRestUtils::parseSpatialReference( serviceInfoMap[QStringLiteral( "spatialReference" )].toMap() ); if ( !crs.isValid() ) { // If not spatial reference, just use WGS84 - crs.createFromString( "EPSG:4326" ); + crs.createFromString( QStringLiteral( "EPSG:4326" ) ); } - mAvailableCRS[layerData["name"].toString()] = QList<QString>() << crs.authid(); + mAvailableCRS[layerData[QStringLiteral( "name" )].toString()] = QList<QString>() << crs.authid(); mModel->appendRow( QList<QStandardItem*>() << idItem << nameItem << abstractItem << cachedItem << filterItem ); } if ( !layerErrors.isEmpty() ) { - QMessageBox::warning( this, tr( "Error" ), tr( "Failed to query some layers:\n%1" ).arg( layerErrors.join( "\n" ) ) ); + QMessageBox::warning( this, tr( "Error" ), tr( "Failed to query some layers:\n%1" ).arg( layerErrors.join( QStringLiteral( "\n" ) ) ) ); } return true; } @@ -99,9 +99,9 @@ void QgsAfsSourceSelect::buildQuery( const QgsOwsConnection &connection, const Q // Query available fields QgsDataSourceUri ds = connection.uri(); - QString url = ds.param( "url" ) + "/" + id; - ds.removeParam( "url" ); - ds.setParam( "url", url ); + QString url = ds.param( QStringLiteral( "url" ) ) + "/" + id; + ds.removeParam( QStringLiteral( "url" ) ); + ds.setParam( QStringLiteral( "url" ), url ); QgsAfsProvider provider( ds.uri() ); if ( !provider.isValid() ) { @@ -129,14 +129,14 @@ QString QgsAfsSourceSelect::getLayerURI( const QgsOwsConnection& connection, const QgsRectangle& bBox ) const { QgsDataSourceUri ds = connection.uri(); - QString url = ds.param( "url" ) + "/" + layerTitle; - ds.removeParam( "url" ); - ds.setParam( "url", url ); - ds.setParam( "filter", filter ); - ds.setParam( "crs", crs ); + QString url = ds.param( QStringLiteral( "url" ) ) + "/" + layerTitle; + ds.removeParam( QStringLiteral( "url" ) ); + ds.setParam( QStringLiteral( "url" ), url ); + ds.setParam( QStringLiteral( "filter" ), filter ); + ds.setParam( QStringLiteral( "crs" ), crs ); if ( !bBox.isEmpty() ) { - ds.setParam( "bbox", QString( "%1,%2,%3,%4" ).arg( bBox.xMinimum() ).arg( bBox.yMinimum() ).arg( bBox.xMaximum() ).arg( bBox.yMaximum() ) ); + ds.setParam( QStringLiteral( "bbox" ), QStringLiteral( "%1,%2,%3,%4" ).arg( bBox.xMinimum() ).arg( bBox.yMinimum() ).arg( bBox.xMaximum() ).arg( bBox.yMaximum() ) ); } return ds.uri(); } diff --git a/src/providers/arcgisrest/qgsamsdataitems.cpp b/src/providers/arcgisrest/qgsamsdataitems.cpp index 324ee3755ae6..c8ca16963c11 100644 --- a/src/providers/arcgisrest/qgsamsdataitems.cpp +++ b/src/providers/arcgisrest/qgsamsdataitems.cpp @@ -25,7 +25,7 @@ QgsAmsRootItem::QgsAmsRootItem( QgsDataItem* parent, QString name, QString path : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconAms.svg"; + mIconName = QStringLiteral( "mIconAms.svg" ); populate(); } @@ -35,9 +35,9 @@ QVector<QgsDataItem*> QgsAmsRootItem::createChildren() Q_FOREACH ( const QString& connName, QgsOwsConnection::connectionList( "ArcGisMapServer" ) ) { - QgsOwsConnection connection( "ArcGisMapServer", connName ); + QgsOwsConnection connection( QStringLiteral( "ArcGisMapServer" ), connName ); QString path = "ams:/" + connName; - connections.append( new QgsAmsConnectionItem( this, connName, path, connection.uri().param( "url" ) ) ); + connections.append( new QgsAmsConnectionItem( this, connName, path, connection.uri().param( QStringLiteral( "url" ) ) ) ); } return connections; } @@ -79,7 +79,7 @@ QgsAmsConnectionItem::QgsAmsConnectionItem( QgsDataItem* parent, QString name, Q : QgsDataCollectionItem( parent, name, path ) , mUrl( url ) { - mIconName = "mIconAms.png"; + mIconName = QStringLiteral( "mIconAms.png" ); } QVector<QgsDataItem*> QgsAmsConnectionItem::createChildren() @@ -92,8 +92,8 @@ QVector<QgsDataItem*> QgsAmsConnectionItem::createChildren() return layers; } - QString authid = QgsArcGisRestUtils::parseSpatialReference( serviceData["spatialReference"].toMap() ).authid(); - QString format = "jpg"; + QString authid = QgsArcGisRestUtils::parseSpatialReference( serviceData[QStringLiteral( "spatialReference" )].toMap() ).authid(); + QString format = QStringLiteral( "jpg" ); bool found = false; QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats(); foreach ( const QString& encoding, serviceData["supportedImageFormatTypes"].toString().split( "," ) ) @@ -114,8 +114,8 @@ QVector<QgsDataItem*> QgsAmsConnectionItem::createChildren() foreach ( const QVariant& layerInfo, serviceData["layers"].toList() ) { QVariantMap layerInfoMap = layerInfo.toMap(); - QString id = layerInfoMap["id"].toString(); - QgsAmsLayerItem* layer = new QgsAmsLayerItem( this, mName, mUrl, id, layerInfoMap["name"].toString(), authid, format ); + QString id = layerInfoMap[QStringLiteral( "id" )].toString(); + QgsAmsLayerItem* layer = new QgsAmsLayerItem( this, mName, mUrl, id, layerInfoMap[QStringLiteral( "name" )].toString(), authid, format ); layers.append( layer ); } @@ -145,7 +145,7 @@ QList<QAction*> QgsAmsConnectionItem::actions() void QgsAmsConnectionItem::editConnection() { - QgsNewHttpConnection nc( 0, "/Qgis/connections-afs/", mName ); + QgsNewHttpConnection nc( 0, QStringLiteral( "/Qgis/connections-afs/" ), mName ); nc.setWindowTitle( tr( "Modify AMS connection" ) ); if ( nc.exec() ) @@ -156,16 +156,16 @@ void QgsAmsConnectionItem::editConnection() void QgsAmsConnectionItem::deleteConnection() { - QgsOwsConnection::deleteConnection( "ArcGisMapServer", mName ); + QgsOwsConnection::deleteConnection( QStringLiteral( "ArcGisMapServer" ), mName ); mParent->refresh(); } /////////////////////////////////////////////////////////////////////////////// QgsAmsLayerItem::QgsAmsLayerItem( QgsDataItem* parent, const QString& name, const QString &url, const QString& id, const QString& title, const QString& authid, const QString& format ) - : QgsLayerItem( parent, title, parent->path() + "/" + name, QString(), QgsLayerItem::Raster, "arcgismapserver" ) + : QgsLayerItem( parent, title, parent->path() + "/" + name, QString(), QgsLayerItem::Raster, QStringLiteral( "arcgismapserver" ) ) { - mUri = QString( "crs='%1' format='%2' layer='%3' url='%4'" ).arg( authid, format, id, url ); + mUri = QStringLiteral( "crs='%1' format='%2' layer='%3' url='%4'" ).arg( authid, format, id, url ); setState( Populated ); - mIconName = "mIconAms.svg"; + mIconName = QStringLiteral( "mIconAms.svg" ); } diff --git a/src/providers/arcgisrest/qgsamsprovider.cpp b/src/providers/arcgisrest/qgsamsprovider.cpp index f3f9dfec1712..043aecda871f 100644 --- a/src/providers/arcgisrest/qgsamsprovider.cpp +++ b/src/providers/arcgisrest/qgsamsprovider.cpp @@ -45,8 +45,8 @@ void QgsAmsLegendFetcher::start() // http://resources.arcgis.com/en/help/rest/apiref/mslegend.html // http://sampleserver5.arcgisonline.com/arcgis/rest/services/CommunityAddressing/MapServer/legend?f=pjson QgsDataSourceUri dataSource( mProvider->dataSourceUri() ); - QUrl queryUrl( dataSource.param( "url" ) + "/legend" ); - queryUrl.addQueryItem( "f", "json" ); + QUrl queryUrl( dataSource.param( QStringLiteral( "url" ) ) + "/legend" ); + queryUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) ); mQuery->start( queryUrl, &mQueryReply ); } @@ -62,7 +62,7 @@ void QgsAmsLegendFetcher::handleFinished() QJsonDocument doc = QJsonDocument::fromJson( mQueryReply, &err ); if ( doc.isNull() ) { - emit error( QString( "Parsing error:" ).arg( err.errorString() ) ); + emit error( QStringLiteral( "Parsing error:" ).arg( err.errorString() ) ); } QVariantMap queryResults = doc.object().toVariantMap(); QgsDataSourceUri dataSource( mProvider->dataSourceUri() ); @@ -70,19 +70,19 @@ void QgsAmsLegendFetcher::handleFinished() foreach ( const QVariant& result, queryResults["layers"].toList() ) { QVariantMap queryResultMap = result.toMap(); - QString layerId = queryResultMap["layerId"].toString(); - if ( layerId != dataSource.param( "layer" ) && !mProvider->subLayers().contains( layerId ) ) + QString layerId = queryResultMap[QStringLiteral( "layerId" )].toString(); + if ( layerId != dataSource.param( QStringLiteral( "layer" ) ) && !mProvider->subLayers().contains( layerId ) ) { continue; } - QVariantList legendSymbols = queryResultMap["legend"].toList(); + QVariantList legendSymbols = queryResultMap[QStringLiteral( "legend" )].toList(); foreach ( const QVariant& legendEntry, legendSymbols ) { QVariantMap legendEntryMap = legendEntry.toMap(); - QString label = legendEntryMap["label"].toString(); + QString label = legendEntryMap[QStringLiteral( "label" )].toString(); if ( label.isEmpty() && legendSymbols.size() == 1 ) - label = queryResultMap["layerName"].toString(); - QByteArray imageData = QByteArray::fromBase64( legendEntryMap["imageData"].toByteArray() ); + label = queryResultMap[QStringLiteral( "layerName" )].toString(); + QByteArray imageData = QByteArray::fromBase64( legendEntryMap[QStringLiteral( "imageData" )].toByteArray() ); legendEntries.append( qMakePair( label, QImage::fromData( imageData ) ) ); } } @@ -126,23 +126,23 @@ QgsAmsProvider::QgsAmsProvider( const QString & uri ) mLegendFetcher = new QgsAmsLegendFetcher( this ); QgsDataSourceUri dataSource( dataSourceUri() ); - mServiceInfo = QgsArcGisRestUtils::getServiceInfo( dataSource.param( "url" ), mErrorTitle, mError ); - mLayerInfo = QgsArcGisRestUtils::getLayerInfo( dataSource.param( "url" ) + "/" + dataSource.param( "layer" ), mErrorTitle, mError ); - - QVariantMap extentData = mLayerInfo["extent"].toMap(); - mExtent.setXMinimum( extentData["xmin"].toDouble() ); - mExtent.setYMinimum( extentData["ymin"].toDouble() ); - mExtent.setXMaximum( extentData["xmax"].toDouble() ); - mExtent.setYMaximum( extentData["ymax"].toDouble() ); - mCrs = QgsArcGisRestUtils::parseSpatialReference( extentData["spatialReference"].toMap() ); + mServiceInfo = QgsArcGisRestUtils::getServiceInfo( dataSource.param( QStringLiteral( "url" ) ), mErrorTitle, mError ); + mLayerInfo = QgsArcGisRestUtils::getLayerInfo( dataSource.param( QStringLiteral( "url" ) ) + "/" + dataSource.param( QStringLiteral( "layer" ) ), mErrorTitle, mError ); + + QVariantMap extentData = mLayerInfo[QStringLiteral( "extent" )].toMap(); + mExtent.setXMinimum( extentData[QStringLiteral( "xmin" )].toDouble() ); + mExtent.setYMinimum( extentData[QStringLiteral( "ymin" )].toDouble() ); + mExtent.setXMaximum( extentData[QStringLiteral( "xmax" )].toDouble() ); + mExtent.setYMaximum( extentData[QStringLiteral( "ymax" )].toDouble() ); + mCrs = QgsArcGisRestUtils::parseSpatialReference( extentData[QStringLiteral( "spatialReference" )].toMap() ); if ( !mCrs.isValid() ) { - appendError( QgsErrorMessage( tr( "Could not parse spatial reference" ), "AMSProvider" ) ); + appendError( QgsErrorMessage( tr( "Could not parse spatial reference" ), QStringLiteral( "AMSProvider" ) ) ); return; } foreach ( const QVariant& sublayer, mLayerInfo["subLayers"].toList() ) { - mSubLayers.append( sublayer.toMap()["id"].toString() ); + mSubLayers.append( sublayer.toMap()[QStringLiteral( "id" )].toString() ); mSubLayerVisibilities.append( true ); } @@ -212,24 +212,24 @@ QgsRasterInterface * QgsAmsProvider::clone() const static inline QString dumpVariantMap( const QVariantMap& variantMap, const QString& title = QString() ) { - QString result = "<table>"; + QString result = QStringLiteral( "<table>" ); if ( !title.isEmpty() ) { - result += QString( "<tr><td class=\"glossy\" colspan=\"2\">%1</td></tr>" ).arg( title ); + result += QStringLiteral( "<tr><td class=\"glossy\" colspan=\"2\">%1</td></tr>" ).arg( title ); } foreach ( const QString& key, variantMap.keys() ) { QVariantMap childMap = variantMap[key].toMap(); if ( childMap.isEmpty() ) { - result += QString( "<tr><td>%1</td><td>%2</td></tr>" ).arg( key, variantMap[key].toString() ); + result += QStringLiteral( "<tr><td>%1</td><td>%2</td></tr>" ).arg( key, variantMap[key].toString() ); } else { - result += QString( "<tr><td>%1</td><td>%2</td></tr>" ).arg( key, dumpVariantMap( childMap ) ); + result += QStringLiteral( "<tr><td>%1</td><td>%2</td></tr>" ).arg( key, dumpVariantMap( childMap ) ); } } - result += "</table>"; + result += QLatin1String( "</table>" ); return result; } @@ -247,7 +247,7 @@ QImage* QgsAmsProvider::draw( const QgsRectangle & viewExtent, int pixelWidth, i QgsDataSourceUri dataSource( dataSourceUri() ); // Use of tiles currently only implemented if service CRS is meter based - if ( mServiceInfo["singleFusedMapCache"].toBool() && mCrs.mapUnits() == QgsUnitTypes::DistanceMeters ) + if ( mServiceInfo[QStringLiteral( "singleFusedMapCache" )].toBool() && mCrs.mapUnits() == QgsUnitTypes::DistanceMeters ) { // Compute ideal resolution // - Measure distance in meters along lower and upper edge of bounding box @@ -256,15 +256,15 @@ QImage* QgsAmsProvider::draw( const QgsRectangle & viewExtent, int pixelWidth, i double targetRes = width / ( pixelWidth ); // Tiles available, assemble image from tiles - QVariantMap tileInfo = mServiceInfo["tileInfo"].toMap(); - int tileWidth = tileInfo["cols"].toInt(); - int tileHeight = tileInfo["rows"].toInt(); - QVariantMap origin = tileInfo["origin"].toMap(); - double ox = origin["x"].toDouble(); - double oy = origin["y"].toDouble(); + QVariantMap tileInfo = mServiceInfo[QStringLiteral( "tileInfo" )].toMap(); + int tileWidth = tileInfo[QStringLiteral( "cols" )].toInt(); + int tileHeight = tileInfo[QStringLiteral( "rows" )].toInt(); + QVariantMap origin = tileInfo[QStringLiteral( "origin" )].toMap(); + double ox = origin[QStringLiteral( "x" )].toDouble(); + double oy = origin[QStringLiteral( "y" )].toDouble(); // Search matching resolution (tile resolution <= targetRes) - QList<QVariant> lodEntries = tileInfo["lods"].toList(); + QList<QVariant> lodEntries = tileInfo[QStringLiteral( "lods" )].toList(); if ( lodEntries.isEmpty() ) { mCachedImage = QImage(); @@ -272,13 +272,13 @@ QImage* QgsAmsProvider::draw( const QgsRectangle & viewExtent, int pixelWidth, i return &mCachedImage; } int level = 0; - double resolution = lodEntries.front().toMap()["resolution"].toDouble(); + double resolution = lodEntries.front().toMap()[QStringLiteral( "resolution" )].toDouble(); foreach ( const QVariant& lodEntry, lodEntries ) { QVariantMap lodEntryMap = lodEntry.toMap(); - level = lodEntryMap["level"].toInt(); - resolution = lodEntryMap["resolution"].toDouble(); - if ( lodEntryMap["resolution"].toDouble() <= 1.5*targetRes ) + level = lodEntryMap[QStringLiteral( "level" )].toInt(); + resolution = lodEntryMap[QStringLiteral( "resolution" )].toDouble(); + if ( lodEntryMap[QStringLiteral( "resolution" )].toDouble() <= 1.5*targetRes ) { break; } @@ -302,7 +302,7 @@ QImage* QgsAmsProvider::draw( const QgsRectangle & viewExtent, int pixelWidth, i { for ( int ix = ixStart; ix <= ixEnd; ++ix ) { - queries[( iy - iyStart ) * ixCount + ( ix - ixStart )] = QUrl( dataSource.param( "url" ) + QString( "/tile/%1/%2/%3" ).arg( level ).arg( iy ).arg( ix ) ); + queries[( iy - iyStart ) * ixCount + ( ix - ixStart )] = QUrl( dataSource.param( QStringLiteral( "url" ) ) + QStringLiteral( "/tile/%1/%2/%3" ).arg( level ).arg( iy ).arg( ix ) ); } } QgsArcGisAsyncParallelQuery query; @@ -322,22 +322,22 @@ QImage* QgsAmsProvider::draw( const QgsRectangle & viewExtent, int pixelWidth, i { for ( int ix = ixStart; ix <= ixEnd; ++ix ) { - QImage image = QImage::fromData( results[( iy - iyStart ) * ixCount + ( ix - ixStart )], tileInfo["format"].toByteArray() ); + QImage image = QImage::fromData( results[( iy - iyStart ) * ixCount + ( ix - ixStart )], tileInfo[QStringLiteral( "format" )].toByteArray() ); painter.drawImage( QPointF( ix * tileWidth - imX, iy * tileHeight - imY ), image ); } } } else { - QUrl requestUrl( dataSource.param( "url" ) + "/export" ); - requestUrl.addQueryItem( "bbox", QString( "%1,%2,%3,%4" ).arg( viewExtent.xMinimum(), 0, 'f', -1 ).arg( viewExtent.yMinimum(), 0, 'f', -1 ).arg( viewExtent.xMaximum(), 0, 'f', -1 ).arg( viewExtent.yMaximum(), 0, 'f', -1 ) ); - requestUrl.addQueryItem( "size", QString( "%1,%2" ).arg( pixelWidth ).arg( pixelHeight ) ); - requestUrl.addQueryItem( "format", dataSource.param( "format" ) ); - requestUrl.addQueryItem( "layers", QString( "show:%1" ).arg( dataSource.param( "layer" ) ) ); - requestUrl.addQueryItem( "transparent", "true" ); - requestUrl.addQueryItem( "f", "image" ); + QUrl requestUrl( dataSource.param( QStringLiteral( "url" ) ) + "/export" ); + requestUrl.addQueryItem( QStringLiteral( "bbox" ), QStringLiteral( "%1,%2,%3,%4" ).arg( viewExtent.xMinimum(), 0, 'f', -1 ).arg( viewExtent.yMinimum(), 0, 'f', -1 ).arg( viewExtent.xMaximum(), 0, 'f', -1 ).arg( viewExtent.yMaximum(), 0, 'f', -1 ) ); + requestUrl.addQueryItem( QStringLiteral( "size" ), QStringLiteral( "%1,%2" ).arg( pixelWidth ).arg( pixelHeight ) ); + requestUrl.addQueryItem( QStringLiteral( "format" ), dataSource.param( QStringLiteral( "format" ) ) ); + requestUrl.addQueryItem( QStringLiteral( "layers" ), QStringLiteral( "show:%1" ).arg( dataSource.param( QStringLiteral( "layer" ) ) ) ); + requestUrl.addQueryItem( QStringLiteral( "transparent" ), QStringLiteral( "true" ) ); + requestUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "image" ) ); QByteArray reply = QgsArcGisRestUtils::queryService( requestUrl, mErrorTitle, mError ); - mCachedImage = QImage::fromData( reply, dataSource.param( "format" ).toLatin1() ); + mCachedImage = QImage::fromData( reply, dataSource.param( QStringLiteral( "format" ) ).toLatin1() ); if ( mCachedImage.format() != QImage::Format_ARGB32 ) { mCachedImage = mCachedImage.convertToFormat( QImage::Format_ARGB32 ); @@ -378,16 +378,16 @@ QgsRasterIdentifyResult QgsAmsProvider::identify( const QgsPoint & thePoint, Qgs { // http://resources.arcgis.com/en/help/rest/apiref/identify.html QgsDataSourceUri dataSource( dataSourceUri() ); - QUrl queryUrl( dataSource.param( "url" ) + "/identify" ); - queryUrl.addQueryItem( "f", "json" ); - queryUrl.addQueryItem( "geometryType", "esriGeometryPoint" ); - queryUrl.addQueryItem( "geometry", QString( "{x: %1, y: %2}" ).arg( thePoint.x(), 0, 'f' ).arg( thePoint.y(), 0, 'f' ) ); + QUrl queryUrl( dataSource.param( QStringLiteral( "url" ) ) + "/identify" ); + queryUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) ); + queryUrl.addQueryItem( QStringLiteral( "geometryType" ), QStringLiteral( "esriGeometryPoint" ) ); + queryUrl.addQueryItem( QStringLiteral( "geometry" ), QStringLiteral( "{x: %1, y: %2}" ).arg( thePoint.x(), 0, 'f' ).arg( thePoint.y(), 0, 'f' ) ); // queryUrl.addQueryItem( "sr", mCrs.postgisSrid() ); - queryUrl.addQueryItem( "layers", QString( "all:%1" ).arg( dataSource.param( "layer" ) ) ); - queryUrl.addQueryItem( "imageDisplay", QString( "%1,%2,%3" ).arg( theWidth ).arg( theHeight ).arg( theDpi ) ); - queryUrl.addQueryItem( "mapExtent", QString( "%1,%2,%3,%4" ).arg( theExtent.xMinimum(), 0, 'f' ).arg( theExtent.yMinimum(), 0, 'f' ).arg( theExtent.xMaximum(), 0, 'f' ).arg( theExtent.yMaximum(), 0, 'f' ) ); - queryUrl.addQueryItem( "tolerance", "10" ); - QVariantList queryResults = QgsArcGisRestUtils::queryServiceJSON( queryUrl, mErrorTitle, mError ).value( "results" ).toList(); + queryUrl.addQueryItem( QStringLiteral( "layers" ), QStringLiteral( "all:%1" ).arg( dataSource.param( QStringLiteral( "layer" ) ) ) ); + queryUrl.addQueryItem( QStringLiteral( "imageDisplay" ), QStringLiteral( "%1,%2,%3" ).arg( theWidth ).arg( theHeight ).arg( theDpi ) ); + queryUrl.addQueryItem( QStringLiteral( "mapExtent" ), QStringLiteral( "%1,%2,%3,%4" ).arg( theExtent.xMinimum(), 0, 'f' ).arg( theExtent.yMinimum(), 0, 'f' ).arg( theExtent.xMaximum(), 0, 'f' ).arg( theExtent.yMaximum(), 0, 'f' ) ); + queryUrl.addQueryItem( QStringLiteral( "tolerance" ), QStringLiteral( "10" ) ); + QVariantList queryResults = QgsArcGisRestUtils::queryServiceJSON( queryUrl, mErrorTitle, mError ).value( QStringLiteral( "results" ) ).toList(); QMap<int, QVariant> entries; @@ -396,11 +396,11 @@ QgsRasterIdentifyResult QgsAmsProvider::identify( const QgsPoint & thePoint, Qgs foreach ( const QVariant& result, queryResults ) { QVariantMap resultMap = result.toMap(); - QVariantMap attributesMap = resultMap["attributes"].toMap(); + QVariantMap attributesMap = resultMap[QStringLiteral( "attributes" )].toMap(); QString valueStr; foreach ( const QString& attribute, attributesMap.keys() ) { - valueStr += QString( "%1 = %2\n" ).arg( attribute, attributesMap[attribute].toString() ); + valueStr += QStringLiteral( "%1 = %2\n" ).arg( attribute, attributesMap[attribute].toString() ); } entries.insert( entries.size(), valueStr ); } @@ -412,23 +412,23 @@ QgsRasterIdentifyResult QgsAmsProvider::identify( const QgsPoint & thePoint, Qgs QVariantMap resultMap = result.toMap(); QgsFields fields; - QVariantMap attributesMap = resultMap["attributes"].toMap(); + QVariantMap attributesMap = resultMap[QStringLiteral( "attributes" )].toMap(); QgsAttributes featureAttributes; foreach ( const QString& attribute, attributesMap.keys() ) { - fields.append( QgsField( attribute, QVariant::String, "string" ) ); + fields.append( QgsField( attribute, QVariant::String, QStringLiteral( "string" ) ) ); featureAttributes.append( attributesMap[attribute].toString() ); } QgsCoordinateReferenceSystem crs; - QgsAbstractGeometry* geometry = QgsArcGisRestUtils::parseEsriGeoJSON( resultMap["geometry"].toMap(), resultMap["geometryType"].toString(), false, false, &crs ); + QgsAbstractGeometry* geometry = QgsArcGisRestUtils::parseEsriGeoJSON( resultMap[QStringLiteral( "geometry" )].toMap(), resultMap[QStringLiteral( "geometryType" )].toString(), false, false, &crs ); QgsFeature feature( fields ); feature.setGeometry( QgsGeometry( geometry ) ); feature.setAttributes( featureAttributes ); feature.setValid( true ); QgsFeatureStore store( fields, crs ); QMap<QString, QVariant> params; - params["sublayer"] = resultMap["layerName"].toString(); - params["featureType"] = attributesMap[resultMap["displayFieldName"].toString()].toString(); + params[QStringLiteral( "sublayer" )] = resultMap[QStringLiteral( "layerName" )].toString(); + params[QStringLiteral( "featureType" )] = attributesMap[resultMap[QStringLiteral( "displayFieldName" )].toString()].toString(); store.setParams( params ); store.features().append( feature ); entries.insert( entries.size(), qVariantFromValue( QList<QgsFeatureStore>() << store ) ); diff --git a/src/providers/arcgisrest/qgsamsprovider.h b/src/providers/arcgisrest/qgsamsprovider.h index 44d9077d0cdc..171b12f9ca2b 100644 --- a/src/providers/arcgisrest/qgsamsprovider.h +++ b/src/providers/arcgisrest/qgsamsprovider.h @@ -58,8 +58,8 @@ class QgsAmsProvider : public QgsRasterDataProvider /* Inherited from QgsDataProvider */ bool isValid() const override { return mValid; } - QString name() const override { return "mapserver"; } - QString description() const override { return "ArcGIS MapServer data provider"; } + QString name() const override { return QStringLiteral( "mapserver" ); } + QString description() const override { return QStringLiteral( "ArcGIS MapServer data provider" ); } QgsCoordinateReferenceSystem crs() const override { return mCrs; } uint subLayerCount() const override { return mSubLayers.size(); } QStringList subLayers() const override { return mSubLayers; } diff --git a/src/providers/arcgisrest/qgsamsproviderextern.cpp b/src/providers/arcgisrest/qgsamsproviderextern.cpp index 3e54576cc1de..e4ac7af8bf77 100644 --- a/src/providers/arcgisrest/qgsamsproviderextern.cpp +++ b/src/providers/arcgisrest/qgsamsproviderextern.cpp @@ -21,8 +21,8 @@ #include "qgsamssourceselect.h" #include "qgsowsconnection.h" -const QString AMS_KEY = "arcgismapserver"; -const QString AMS_DESCRIPTION = "ArcGIS Map Server data provider"; +const QString AMS_KEY = QStringLiteral( "arcgismapserver" ); +const QString AMS_DESCRIPTION = QStringLiteral( "ArcGIS Map Server data provider" ); QGISEXTERN QgsAmsProvider * classFactory( const QString *uri ) @@ -59,17 +59,17 @@ QGISEXTERN QgsDataItem *dataItem( QString thePath, QgsDataItem *parentItem ) { if ( thePath.isEmpty() ) { - return new QgsAmsRootItem( parentItem, "ArcGisMapServer", "arcgismapserver:" ); + return new QgsAmsRootItem( parentItem, QStringLiteral( "ArcGisMapServer" ), QStringLiteral( "arcgismapserver:" ) ); } // path schema: ams:/connection name (used by OWS) - if ( thePath.startsWith( "ams:/" ) ) + if ( thePath.startsWith( QLatin1String( "ams:/" ) ) ) { QString connectionName = thePath.split( '/' ).last(); - if ( QgsOwsConnection::connectionList( "ArcGisMapServer" ).contains( connectionName ) ) + if ( QgsOwsConnection::connectionList( QStringLiteral( "ArcGisMapServer" ) ).contains( connectionName ) ) { - QgsOwsConnection connection( "ArcGisMapServer", connectionName ); - return new QgsAmsConnectionItem( parentItem, "ArcGisMapServer", thePath, connection.uri().param( "url" ) ); + QgsOwsConnection connection( QStringLiteral( "ArcGisMapServer" ), connectionName ); + return new QgsAmsConnectionItem( parentItem, QStringLiteral( "ArcGisMapServer" ), thePath, connection.uri().param( QStringLiteral( "url" ) ) ); } } diff --git a/src/providers/arcgisrest/qgsamssourceselect.cpp b/src/providers/arcgisrest/qgsamssourceselect.cpp index bdaa7c751697..b1dd77e24cb8 100644 --- a/src/providers/arcgisrest/qgsamssourceselect.cpp +++ b/src/providers/arcgisrest/qgsamssourceselect.cpp @@ -26,7 +26,7 @@ QgsAmsSourceSelect::QgsAmsSourceSelect( QWidget* parent, Qt::WindowFlags fl, bool embeddedMode ) - : QgsSourceSelectDialog( "ArcGisMapServer", QgsSourceSelectDialog::MapService, parent, fl ) + : QgsSourceSelectDialog( QStringLiteral( "ArcGisMapServer" ), QgsSourceSelectDialog::MapService, parent, fl ) { if ( embeddedMode ) { @@ -37,50 +37,50 @@ QgsAmsSourceSelect::QgsAmsSourceSelect( QWidget* parent, Qt::WindowFlags fl, boo bool QgsAmsSourceSelect::connectToService( const QgsOwsConnection &connection ) { QString errorTitle, errorMessage; - QVariantMap serviceInfoMap = QgsArcGisRestUtils::getServiceInfo( connection.uri().param( "url" ), errorTitle, errorMessage ); + QVariantMap serviceInfoMap = QgsArcGisRestUtils::getServiceInfo( connection.uri().param( QStringLiteral( "url" ) ), errorTitle, errorMessage ); if ( serviceInfoMap.isEmpty() ) { QMessageBox::warning( this, tr( "Error" ), tr( "Failed to retrieve service capabilities:\n%1: %2" ).arg( errorTitle, errorMessage ) ); return false; } - populateImageEncodings( serviceInfoMap["supportedImageFormatTypes"].toString().split( "," ) ); + populateImageEncodings( serviceInfoMap[QStringLiteral( "supportedImageFormatTypes" )].toString().split( QStringLiteral( "," ) ) ); QStringList layerErrors; foreach ( const QVariant& layerInfo, serviceInfoMap["layers"].toList() ) { QVariantMap layerInfoMap = layerInfo.toMap(); - if ( !layerInfoMap["id"].isValid() ) + if ( !layerInfoMap[QStringLiteral( "id" )].isValid() ) { continue; } // Get layer info - QVariantMap layerData = QgsArcGisRestUtils::getLayerInfo( connection.uri().param( "url" ) + "/" + layerInfoMap["id"].toString(), errorTitle, errorMessage ); + QVariantMap layerData = QgsArcGisRestUtils::getLayerInfo( connection.uri().param( QStringLiteral( "url" ) ) + "/" + layerInfoMap[QStringLiteral( "id" )].toString(), errorTitle, errorMessage ); if ( layerData.isEmpty() ) { - layerErrors.append( QString( "Layer %1: %2 - %3" ).arg( layerInfoMap["id"].toString(), errorTitle, errorMessage ) ); + layerErrors.append( QStringLiteral( "Layer %1: %2 - %3" ).arg( layerInfoMap[QStringLiteral( "id" )].toString(), errorTitle, errorMessage ) ); continue; } // insert the typenames, titles and abstracts into the tree view - QStandardItem* idItem = new QStandardItem( layerData["id"].toString() ); - QStandardItem* nameItem = new QStandardItem( layerData["name"].toString() ); - QStandardItem* abstractItem = new QStandardItem( layerData["description"].toString() ); - abstractItem->setToolTip( layerData["description"].toString() ); + QStandardItem* idItem = new QStandardItem( layerData[QStringLiteral( "id" )].toString() ); + QStandardItem* nameItem = new QStandardItem( layerData[QStringLiteral( "name" )].toString() ); + QStandardItem* abstractItem = new QStandardItem( layerData[QStringLiteral( "description" )].toString() ); + abstractItem->setToolTip( layerData[QStringLiteral( "description" )].toString() ); - QgsCoordinateReferenceSystem crs = QgsArcGisRestUtils::parseSpatialReference( serviceInfoMap["spatialReference"].toMap() ); + QgsCoordinateReferenceSystem crs = QgsArcGisRestUtils::parseSpatialReference( serviceInfoMap[QStringLiteral( "spatialReference" )].toMap() ); if ( !crs.isValid() ) { - layerErrors.append( tr( "Layer %1: unable to parse spatial reference" ).arg( layerInfoMap["id"].toString() ) ); + layerErrors.append( tr( "Layer %1: unable to parse spatial reference" ).arg( layerInfoMap[QStringLiteral( "id" )].toString() ) ); continue; } - mAvailableCRS[layerData["name"].toString()] = QList<QString>() << crs.authid(); + mAvailableCRS[layerData[QStringLiteral( "name" )].toString()] = QList<QString>() << crs.authid(); mModel->appendRow( QList<QStandardItem*>() << idItem << nameItem << abstractItem ); } if ( !layerErrors.isEmpty() ) { - QMessageBox::warning( this, tr( "Error" ), tr( "Failed to query some layers:\n%1" ).arg( layerErrors.join( "\n" ) ) ); + QMessageBox::warning( this, tr( "Error" ), tr( "Failed to query some layers:\n%1" ).arg( layerErrors.join( QStringLiteral( "\n" ) ) ) ); } return true; } @@ -92,8 +92,8 @@ QString QgsAmsSourceSelect::getLayerURI( const QgsOwsConnection& connection, const QgsRectangle& /*bBox*/ ) const { QgsDataSourceUri ds = connection.uri(); - ds.setParam( "layer", layerTitle ); - ds.setParam( "crs", crs ); - ds.setParam( "format", getSelectedImageEncoding() ); + ds.setParam( QStringLiteral( "layer" ), layerTitle ); + ds.setParam( QStringLiteral( "crs" ), crs ); + ds.setParam( QStringLiteral( "format" ), getSelectedImageEncoding() ); return ds.uri(); } diff --git a/src/providers/arcgisrest/qgsarcgisrestutils.cpp b/src/providers/arcgisrest/qgsarcgisrestutils.cpp index ea0def10c4a3..f7d22a9e0833 100644 --- a/src/providers/arcgisrest/qgsarcgisrestutils.cpp +++ b/src/providers/arcgisrest/qgsarcgisrestutils.cpp @@ -38,31 +38,31 @@ QVariant::Type QgsArcGisRestUtils::mapEsriFieldType( const QString &esriFieldType ) { - if ( esriFieldType == "esriFieldTypeInteger" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeInteger" ) ) return QVariant::LongLong; - if ( esriFieldType == "esriFieldTypeSmallInteger" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeSmallInteger" ) ) return QVariant::Int; - if ( esriFieldType == "esriFieldTypeDouble" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeDouble" ) ) return QVariant::Double; - if ( esriFieldType == "esriFieldTypeSingle" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeSingle" ) ) return QVariant::Double; - if ( esriFieldType == "esriFieldTypeString" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeString" ) ) return QVariant::String; - if ( esriFieldType == "esriFieldTypeDate" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeDate" ) ) return QVariant::Date; - if ( esriFieldType == "esriFieldTypeGeometry" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeGeometry" ) ) return QVariant::Invalid; // Geometry column should not appear as field - if ( esriFieldType == "esriFieldTypeOID" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeOID" ) ) return QVariant::LongLong; - if ( esriFieldType == "esriFieldTypeBlob" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeBlob" ) ) return QVariant::ByteArray; - if ( esriFieldType == "esriFieldTypeGlobalID" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeGlobalID" ) ) return QVariant::String; - if ( esriFieldType == "esriFieldTypeRaster" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeRaster" ) ) return QVariant::ByteArray; - if ( esriFieldType == "esriFieldTypeGUID" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeGUID" ) ) return QVariant::String; - if ( esriFieldType == "esriFieldTypeXML" ) + if ( esriFieldType == QLatin1String( "esriFieldTypeXML" ) ) return QVariant::String; return QVariant::Invalid; } @@ -70,17 +70,17 @@ QVariant::Type QgsArcGisRestUtils::mapEsriFieldType( const QString &esriFieldTyp QgsWkbTypes::Type QgsArcGisRestUtils::mapEsriGeometryType( const QString& esriGeometryType ) { // http://resources.arcgis.com/en/help/arcobjects-cpp/componenthelp/index.html#//000w0000001p000000 - if ( esriGeometryType == "esriGeometryNull" ) + if ( esriGeometryType == QLatin1String( "esriGeometryNull" ) ) return QgsWkbTypes::Unknown; - else if ( esriGeometryType == "esriGeometryPoint" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryPoint" ) ) return QgsWkbTypes::Point; - else if ( esriGeometryType == "esriGeometryMultipoint" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryMultipoint" ) ) return QgsWkbTypes::MultiPoint; - else if ( esriGeometryType == "esriGeometryPolyline" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryPolyline" ) ) return QgsWkbTypes::MultiCurve; - else if ( esriGeometryType == "esriGeometryPolygon" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryPolygon" ) ) return QgsWkbTypes::Polygon; - else if ( esriGeometryType == "esriGeometryEnvelope" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryEnvelope" ) ) return QgsWkbTypes::Polygon; // Unsupported (either by qgis, or format unspecified by the specification) // esriGeometryCircularArc @@ -117,7 +117,7 @@ static QgsPointV2* parsePoint( const QVariantList& coordList, QgsWkbTypes::Type static QgsCircularString* parseCircularString( const QVariantMap& curveData, QgsWkbTypes::Type pointType, const QgsPointV2& startPoint ) { - QVariantList coordsList = curveData["c"].toList(); + QVariantList coordsList = curveData[QStringLiteral( "c" )].toList(); if ( coordsList.isEmpty() ) return nullptr; QList<QgsPointV2> points; @@ -185,19 +185,19 @@ static QgsAbstractGeometry* parseEsriGeometryPoint( const QVariantMap& geometryD { // {"x" : <x>, "y" : <y>, "z" : <z>, "m" : <m>} bool xok = false, yok = false; - double x = geometryData["x"].toDouble( &xok ); - double y = geometryData["y"].toDouble( &yok ); + double x = geometryData[QStringLiteral( "x" )].toDouble( &xok ); + double y = geometryData[QStringLiteral( "y" )].toDouble( &yok ); if ( !xok || !yok ) return nullptr; - double z = geometryData["z"].toDouble(); - double m = geometryData["m"].toDouble(); + double z = geometryData[QStringLiteral( "z" )].toDouble(); + double m = geometryData[QStringLiteral( "m" )].toDouble(); return new QgsPointV2( pointType, x, y, z, m ); } static QgsAbstractGeometry* parseEsriGeometryMultiPoint( const QVariantMap& geometryData, QgsWkbTypes::Type pointType ) { // {"points" : [[ <x1>, <y1>, <z1>, <m1> ] , [ <x2>, <y2>, <z2>, <m2> ], ... ]} - QVariantList coordsList = geometryData["points"].toList(); + QVariantList coordsList = geometryData[QStringLiteral( "points" )].toList(); if ( coordsList.isEmpty() ) return nullptr; @@ -220,10 +220,10 @@ static QgsAbstractGeometry* parseEsriGeometryPolyline( const QVariantMap& geomet { // {"curvePaths": [[[0,0], {"c": [[3,3],[1,4]]} ]]} QVariantList pathsList; - if ( geometryData["paths"].isValid() ) - pathsList = geometryData["paths"].toList(); - else if ( geometryData["curvePaths"].isValid() ) - pathsList = geometryData["curvePaths"].toList(); + if ( geometryData[QStringLiteral( "paths" )].isValid() ) + pathsList = geometryData[QStringLiteral( "paths" )].toList(); + else if ( geometryData[QStringLiteral( "curvePaths" )].isValid() ) + pathsList = geometryData[QStringLiteral( "curvePaths" )].toList(); if ( pathsList.isEmpty() ) return nullptr; QgsMultiCurve* multiCurve = new QgsMultiCurve(); @@ -244,10 +244,10 @@ static QgsAbstractGeometry* parseEsriGeometryPolygon( const QVariantMap& geometr { // {"curveRings": [[[0,0], {"c": [[3,3],[1,4]]} ]]} QVariantList ringsList; - if ( geometryData["rings"].isValid() ) - ringsList = geometryData["rings"].toList(); - else if ( geometryData["ringPaths"].isValid() ) - ringsList = geometryData["ringPaths"].toList(); + if ( geometryData[QStringLiteral( "rings" )].isValid() ) + ringsList = geometryData[QStringLiteral( "rings" )].toList(); + else if ( geometryData[QStringLiteral( "ringPaths" )].isValid() ) + ringsList = geometryData[QStringLiteral( "ringPaths" )].toList(); if ( ringsList.isEmpty() ) return nullptr; QgsCurvePolygon* polygon = new QgsCurvePolygon(); @@ -275,10 +275,10 @@ static QgsAbstractGeometry* parseEsriEnvelope( const QVariantMap& geometryData ) { // {"xmin" : -109.55, "ymin" : 25.76, "xmax" : -86.39, "ymax" : 49.94} bool xminOk = false, yminOk = false, xmaxOk = false, ymaxOk = false; - double xmin = geometryData["xmin"].toDouble( &xminOk ); - double ymin = geometryData["ymin"].toDouble( &yminOk ); - double xmax = geometryData["xmax"].toDouble( &xmaxOk ); - double ymax = geometryData["ymax"].toDouble( &ymaxOk ); + double xmin = geometryData[QStringLiteral( "xmin" )].toDouble( &xminOk ); + double ymin = geometryData[QStringLiteral( "ymin" )].toDouble( &yminOk ); + double xmax = geometryData[QStringLiteral( "xmax" )].toDouble( &xmaxOk ); + double ymax = geometryData[QStringLiteral( "ymax" )].toDouble( &ymaxOk ); if ( !xminOk || !yminOk || !xmaxOk || !ymaxOk ) return nullptr; QgsLineString* ext = new QgsLineString(); @@ -297,21 +297,21 @@ QgsAbstractGeometry* QgsArcGisRestUtils::parseEsriGeoJSON( const QVariantMap& ge QgsWkbTypes::Type pointType = QgsWkbTypes::zmType( QgsWkbTypes::Point, readZ, readM ); if ( crs ) { - *crs = parseSpatialReference( geometryData["spatialReference"].toMap() ); + *crs = parseSpatialReference( geometryData[QStringLiteral( "spatialReference" )].toMap() ); } // http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Geometry_Objects/02r3000000n1000000/ - if ( esriGeometryType == "esriGeometryNull" ) + if ( esriGeometryType == QLatin1String( "esriGeometryNull" ) ) return nullptr; - else if ( esriGeometryType == "esriGeometryPoint" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryPoint" ) ) return parseEsriGeometryPoint( geometryData, pointType ); - else if ( esriGeometryType == "esriGeometryMultipoint" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryMultipoint" ) ) return parseEsriGeometryMultiPoint( geometryData, pointType ); - else if ( esriGeometryType == "esriGeometryPolyline" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryPolyline" ) ) return parseEsriGeometryPolyline( geometryData, pointType ); - else if ( esriGeometryType == "esriGeometryPolygon" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryPolygon" ) ) return parseEsriGeometryPolygon( geometryData, pointType ); - else if ( esriGeometryType == "esriGeometryEnvelope" ) + else if ( esriGeometryType == QLatin1String( "esriGeometryEnvelope" ) ) return parseEsriEnvelope( geometryData ); // Unsupported (either by qgis, or format unspecified by the specification) // esriGeometryCircularArc @@ -333,17 +333,17 @@ QgsAbstractGeometry* QgsArcGisRestUtils::parseEsriGeoJSON( const QVariantMap& ge QgsCoordinateReferenceSystem QgsArcGisRestUtils::parseSpatialReference( const QVariantMap &spatialReferenceMap ) { - QString spatialReference = spatialReferenceMap["latestWkid"].toString(); + QString spatialReference = spatialReferenceMap[QStringLiteral( "latestWkid" )].toString(); if ( spatialReference.isEmpty() ) - spatialReference = spatialReferenceMap["wkid"].toString(); + spatialReference = spatialReferenceMap[QStringLiteral( "wkid" )].toString(); if ( spatialReference.isEmpty() ) - spatialReference = spatialReferenceMap["wkt"].toString(); + spatialReference = spatialReferenceMap[QStringLiteral( "wkt" )].toString(); else - spatialReference = QString( "EPSG:%1" ).arg( spatialReference ); + spatialReference = QStringLiteral( "EPSG:%1" ).arg( spatialReference ); QgsCoordinateReferenceSystem crs; crs.createFromString( spatialReference ); - if ( crs.authid().startsWith( "USER:" ) ) - crs.createFromString( "EPSG:4326" ); // If we can't recognize the SRS, fall back to WGS84 + if ( crs.authid().startsWith( QLatin1String( "USER:" ) ) ) + crs.createFromString( QStringLiteral( "EPSG:4326" ) ); // If we can't recognize the SRS, fall back to WGS84 return crs; } @@ -352,7 +352,7 @@ QVariantMap QgsArcGisRestUtils::getServiceInfo( const QString& baseurl, QString& { // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer?f=json QUrl queryUrl( baseurl ); - queryUrl.addQueryItem( "f", "json" ); + queryUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) ); return queryServiceJSON( queryUrl, errorTitle, errorText ); } @@ -360,7 +360,7 @@ QVariantMap QgsArcGisRestUtils::getLayerInfo( const QString& layerurl, QString& { // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/1?f=json QUrl queryUrl( layerurl ); - queryUrl.addQueryItem( "f", "json" ); + queryUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) ); return queryServiceJSON( queryUrl, errorTitle, errorText ); } @@ -368,9 +368,9 @@ QVariantMap QgsArcGisRestUtils::getObjectIds( const QString& layerurl, QString& { // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/1/query?where=objectid%3Dobjectid&returnIdsOnly=true&f=json QUrl queryUrl( layerurl + "/query" ); - queryUrl.addQueryItem( "f", "json" ); - queryUrl.addQueryItem( "where", "objectid=objectid" ); - queryUrl.addQueryItem( "returnIdsOnly", "true" ); + queryUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) ); + queryUrl.addQueryItem( QStringLiteral( "where" ), QStringLiteral( "objectid=objectid" ) ); + queryUrl.addQueryItem( QStringLiteral( "returnIdsOnly" ), QStringLiteral( "true" ) ); return queryServiceJSON( queryUrl, errorTitle, errorText ); } @@ -386,31 +386,31 @@ QVariantMap QgsArcGisRestUtils::getObjects( const QString& layerurl, const QList ids.append( QString::number( id ) ); } QUrl queryUrl( layerurl + "/query" ); - queryUrl.addQueryItem( "f", "json" ); - queryUrl.addQueryItem( "objectIds", ids.join( "," ) ); - QString wkid = crs.indexOf( ":" ) >= 0 ? crs.split( ":" )[1] : ""; - queryUrl.addQueryItem( "inSR", wkid ); - queryUrl.addQueryItem( "outSR", wkid ); - QString outFields = fetchAttributes.join( "," ); + queryUrl.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) ); + queryUrl.addQueryItem( QStringLiteral( "objectIds" ), ids.join( QStringLiteral( "," ) ) ); + QString wkid = crs.indexOf( QLatin1String( ":" ) ) >= 0 ? crs.split( QStringLiteral( ":" ) )[1] : QLatin1String( "" ); + queryUrl.addQueryItem( QStringLiteral( "inSR" ), wkid ); + queryUrl.addQueryItem( QStringLiteral( "outSR" ), wkid ); + QString outFields = fetchAttributes.join( QStringLiteral( "," ) ); if ( fetchGeometry ) { - queryUrl.addQueryItem( "returnGeometry", "true" ); - queryUrl.addQueryItem( "outFields", outFields ); + queryUrl.addQueryItem( QStringLiteral( "returnGeometry" ), QStringLiteral( "true" ) ); + queryUrl.addQueryItem( QStringLiteral( "outFields" ), outFields ); } else { - queryUrl.addQueryItem( "returnGeometry", "false" ); - queryUrl.addQueryItem( "outFields", outFields ); + queryUrl.addQueryItem( QStringLiteral( "returnGeometry" ), QStringLiteral( "false" ) ); + queryUrl.addQueryItem( QStringLiteral( "outFields" ), outFields ); } - queryUrl.addQueryItem( "returnM", fetchM ? "true" : "false" ); - queryUrl.addQueryItem( "returnZ", fetchZ ? "true" : "false" ); + queryUrl.addQueryItem( QStringLiteral( "returnM" ), fetchM ? "true" : "false" ); + queryUrl.addQueryItem( QStringLiteral( "returnZ" ), fetchZ ? "true" : "false" ); if ( !filterRect.isEmpty() ) { - queryUrl.addQueryItem( "geometry", QString( "%1,%2,%3,%4" ) + queryUrl.addQueryItem( QStringLiteral( "geometry" ), QStringLiteral( "%1,%2,%3,%4" ) .arg( filterRect.xMinimum(), 0, 'f', -1 ).arg( filterRect.yMinimum(), 0, 'f', -1 ) .arg( filterRect.xMaximum(), 0, 'f', -1 ).arg( filterRect.yMaximum(), 0, 'f', -1 ) ); - queryUrl.addQueryItem( "geometryType", "esriGeometryEnvelope" ); - queryUrl.addQueryItem( "spatialRel", "esriSpatialRelEnvelopeIntersects" ); + queryUrl.addQueryItem( QStringLiteral( "geometryType" ), QStringLiteral( "esriGeometryEnvelope" ) ); + queryUrl.addQueryItem( QStringLiteral( "spatialRel" ), QStringLiteral( "esriSpatialRelEnvelopeIntersects" ) ); } return queryServiceJSON( queryUrl, errorTitle, errorText ); } @@ -437,7 +437,7 @@ QByteArray QgsArcGisRestUtils::queryService( const QUrl& url, QString& errorTitl if ( reply->error() != QNetworkReply::NoError ) { QgsDebugMsg( QString( "Network error: %1" ).arg( reply->errorString() ) ); - errorTitle = "Network error"; + errorTitle = QStringLiteral( "Network error" ); errorText = reply->errorString(); return QByteArray(); } @@ -469,7 +469,7 @@ QVariantMap QgsArcGisRestUtils::queryServiceJSON( const QUrl &url, QString &erro QJsonDocument doc = QJsonDocument::fromJson( reply, &err ); if ( doc.isNull() ) { - errorTitle = "Parsing error"; + errorTitle = QStringLiteral( "Parsing error" ); errorText = err.errorString(); QgsDebugMsg( QString( "Parsing error: %1" ).arg( err.errorString() ) ); return QVariantMap(); @@ -512,7 +512,7 @@ void QgsArcGisAsyncQuery::handleReply() if ( mReply->error() != QNetworkReply::NoError ) { QgsDebugMsg( QString( "Network error: %1" ).arg( mReply->errorString() ) ); - emit failed( "Network error", mReply->errorString() ); + emit failed( QStringLiteral( "Network error" ), mReply->errorString() ); return; } diff --git a/src/providers/db2/qgsdb2dataitems.cpp b/src/providers/db2/qgsdb2dataitems.cpp index 078b2356c23d..bdbc584879d6 100644 --- a/src/providers/db2/qgsdb2dataitems.cpp +++ b/src/providers/db2/qgsdb2dataitems.cpp @@ -31,12 +31,12 @@ //#include <QtSql/QSqlError> #include <QProgressDialog> -static const QString PROVIDER_KEY = "DB2"; +static const QString PROVIDER_KEY = QStringLiteral( "DB2" ); QgsDb2ConnectionItem::QgsDb2ConnectionItem( QgsDataItem *parent, const QString name, const QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); populate(); } @@ -61,7 +61,7 @@ bool QgsDb2ConnectionItem::ConnInfoFromParameters( if ( driver.isEmpty() || host.isEmpty() || database.isEmpty() || port.isEmpty() ) { QgsDebugMsg( "Host, port, driver or database missing" ); - errorMsg = "Host, port, driver or database missing"; + errorMsg = QStringLiteral( "Host, port, driver or database missing" ); return false; } connInfo = "driver='" + driver + "' " @@ -74,7 +74,7 @@ bool QgsDb2ConnectionItem::ConnInfoFromParameters( if ( database.isEmpty() ) { QgsDebugMsg( "Database must be specified" ); - errorMsg = "Database must be specified"; + errorMsg = QStringLiteral( "Database must be specified" ); return false; } connInfo = "service='" + service + "' " @@ -333,7 +333,7 @@ bool QgsDb2ConnectionItem::handleDrop( const QMimeData* data, const QString& toS QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data ); Q_FOREACH ( const QgsMimeDataUtils::Uri& u, lst ) { - if ( u.layerType != "vector" ) + if ( u.layerType != QLatin1String( "vector" ) ) { importResults.append( tr( "%1: Not a vector layer!" ).arg( u.name ) ); hasError = true; // only vectors can be imported @@ -349,7 +349,7 @@ bool QgsDb2ConnectionItem::handleDrop( const QMimeData* data, const QString& toS QString tableName; if ( !toSchema.isEmpty() ) { - tableName = QString( "%1.%2" ).arg( toSchema, u.name ); + tableName = QStringLiteral( "%1.%2" ).arg( toSchema, u.name ); } else { @@ -358,11 +358,11 @@ bool QgsDb2ConnectionItem::handleDrop( const QMimeData* data, const QString& toS QString uri = connInfo() + " table=" + tableName; if ( srcLayer->geometryType() != QgsWkbTypes::NullGeometry ) - uri += " (geom)"; + uri += QLatin1String( " (geom)" ); QgsVectorLayerImport::ImportError err; QString importError; - err = QgsVectorLayerImport::importLayer( srcLayer, uri, "DB2", srcLayer->crs(), false, &importError, false, nullptr, progress ); + err = QgsVectorLayerImport::importLayer( srcLayer, uri, QStringLiteral( "DB2" ), srcLayer->crs(), false, &importError, false, nullptr, progress ); if ( err == QgsVectorLayerImport::NoError ) { importResults.append( tr( "%1: OK!" ).arg( u.name ) ); @@ -377,7 +377,7 @@ bool QgsDb2ConnectionItem::handleDrop( const QMimeData* data, const QString& toS } else { - QString errMsg = QString( "%1: %2" ).arg( u.name, importError ); + QString errMsg = QStringLiteral( "%1: %2" ).arg( u.name, importError ); QgsDebugMsg( "import failed: " + errMsg ); importResults.append( errMsg ); hasError = true; @@ -403,7 +403,7 @@ bool QgsDb2ConnectionItem::handleDrop( const QMimeData* data, const QString& toS } else if ( hasError ) { - QMessageBox::warning( nullptr, tr( "Import to DB2 database" ), tr( "Failed to import some layers!\n\n" ) + importResults.join( "\n" ) ); + QMessageBox::warning( nullptr, tr( "Import to DB2 database" ), tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ) ); } else { @@ -421,7 +421,7 @@ bool QgsDb2ConnectionItem::handleDrop( const QMimeData* data, const QString& toS QgsDb2RootItem::QgsDb2RootItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconDb2.svg"; + mIconName = QStringLiteral( "mIconDb2.svg" ); populate(); } @@ -433,7 +433,7 @@ QVector<QgsDataItem*> QgsDb2RootItem::createChildren() { QVector<QgsDataItem*> connections; QSettings settings; - settings.beginGroup( "/DB2/connections" ); + settings.beginGroup( QStringLiteral( "/DB2/connections" ) ); Q_FOREACH ( const QString& connName, settings.childGroups() ) { connections << new QgsDb2ConnectionItem( this, connName, mPath + "/" + connName ); @@ -503,7 +503,7 @@ QString QgsDb2LayerItem::createUri() uri.setDataSource( mLayerProperty.schemaName, mLayerProperty.tableName, mLayerProperty.geometryColName, mLayerProperty.sql, mLayerProperty.pkColumnName ); uri.setSrid( mLayerProperty.srid ); uri.setWkbType( QgsDb2TableModel::wkbTypeFromDb2( mLayerProperty.type ) ); - uri.setParam( "extents", mLayerProperty.extents ); + uri.setParam( QStringLiteral( "extents" ), mLayerProperty.extents ); QString uriString = uri.uri( false ); QgsDebugMsg( "Layer URI: " + uriString ); return uriString; @@ -512,7 +512,7 @@ QString QgsDb2LayerItem::createUri() QgsDb2SchemaItem::QgsDb2SchemaItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconDbSchema.png"; + mIconName = QStringLiteral( "mIconDbSchema.png" ); } QVector<QgsDataItem*> QgsDb2SchemaItem::createChildren() @@ -585,7 +585,7 @@ QgsDb2LayerItem* QgsDb2SchemaItem::addLayer( QgsDb2LayerProperty layerProperty, layerType = QgsLayerItem::Polygon; break; default: - if ( layerProperty.type == "NONE" && layerProperty.geometryColName.isEmpty() ) + if ( layerProperty.type == QLatin1String( "NONE" ) && layerProperty.geometryColName.isEmpty() ) { layerType = QgsLayerItem::TableLayer; tip = tr( "as geometryless table" ); diff --git a/src/providers/db2/qgsdb2expressioncompiler.cpp b/src/providers/db2/qgsdb2expressioncompiler.cpp index baa057b1ade0..0bd00656d545 100644 --- a/src/providers/db2/qgsdb2expressioncompiler.cpp +++ b/src/providers/db2/qgsdb2expressioncompiler.cpp @@ -28,26 +28,26 @@ QgsDb2ExpressionCompiler::QgsDb2ExpressionCompiler( QgsDb2FeatureSource* source QString nodeType( const QgsExpression::Node* node ) { - QString opString = "?"; - if ( node->nodeType() == QgsExpression::ntUnaryOperator ) opString = "ntUnaryOperator"; - if ( node->nodeType() == QgsExpression::ntBinaryOperator ) opString = "ntBinaryOperator"; - if ( node->nodeType() == QgsExpression::ntInOperator ) opString = "ntInOperator"; - if ( node->nodeType() == QgsExpression::ntFunction ) opString = "ntFunction"; - if ( node->nodeType() == QgsExpression::ntLiteral ) opString = "ntLiteral"; - if ( node->nodeType() == QgsExpression::ntColumnRef ) opString = "ntColumnRef"; - if ( node->nodeType() == QgsExpression::ntCondition ) opString = "ntCondition"; - QString result = QString( "%1 - " ).arg( node->nodeType() ) + opString; + QString opString = QStringLiteral( "?" ); + if ( node->nodeType() == QgsExpression::ntUnaryOperator ) opString = QStringLiteral( "ntUnaryOperator" ); + if ( node->nodeType() == QgsExpression::ntBinaryOperator ) opString = QStringLiteral( "ntBinaryOperator" ); + if ( node->nodeType() == QgsExpression::ntInOperator ) opString = QStringLiteral( "ntInOperator" ); + if ( node->nodeType() == QgsExpression::ntFunction ) opString = QStringLiteral( "ntFunction" ); + if ( node->nodeType() == QgsExpression::ntLiteral ) opString = QStringLiteral( "ntLiteral" ); + if ( node->nodeType() == QgsExpression::ntColumnRef ) opString = QStringLiteral( "ntColumnRef" ); + if ( node->nodeType() == QgsExpression::ntCondition ) opString = QStringLiteral( "ntCondition" ); + QString result = QStringLiteral( "%1 - " ).arg( node->nodeType() ) + opString; return result; } QString resultType( QgsSqlExpressionCompiler::Result result ) { - if ( result == QgsSqlExpressionCompiler::None ) return "None"; - if ( result == QgsSqlExpressionCompiler::Complete ) return "Complete"; - if ( result == QgsSqlExpressionCompiler::Partial ) return "Partial"; - if ( result == QgsSqlExpressionCompiler::Fail ) return "Fail"; - return "Other result"; + if ( result == QgsSqlExpressionCompiler::None ) return QStringLiteral( "None" ); + if ( result == QgsSqlExpressionCompiler::Complete ) return QStringLiteral( "Complete" ); + if ( result == QgsSqlExpressionCompiler::Partial ) return QStringLiteral( "Partial" ); + if ( result == QgsSqlExpressionCompiler::Fail ) return QStringLiteral( "Fail" ); + return QStringLiteral( "Other result" ); } @@ -113,7 +113,7 @@ QgsSqlExpressionCompiler::Result QgsDb2ExpressionCompiler::compileNode( const Qg rr = compileNode( n->operand(), result ); if ( "NULL" == result.toUpper() ) { - result = ""; + result = QLatin1String( "" ); return Fail; } @@ -147,13 +147,13 @@ QgsSqlExpressionCompiler::Result QgsDb2ExpressionCompiler::compileNode( const Qg switch ( bin->op() ) { case QgsExpression::boMod: - result = QString( "MOD(%1,%2)" ).arg( left, right ); + result = QStringLiteral( "MOD(%1,%2)" ).arg( left, right ); compileResult = ( lr == Partial || rr == Partial ) ? Partial : Complete; QgsDebugMsg( QString( "MOD compile status: %1" ).arg( compileResult ) + "; " + result ); return compileResult; case QgsExpression::boPow: - result = QString( "power(%1,%2)" ).arg( left, right ); + result = QStringLiteral( "power(%1,%2)" ).arg( left, right ); compileResult = ( lr == Partial || rr == Partial ) ? Partial : Complete; QgsDebugMsg( QString( "POWER compile status: %1" ).arg( compileResult ) + "; " + result ); return compileResult; @@ -162,7 +162,7 @@ QgsSqlExpressionCompiler::Result QgsDb2ExpressionCompiler::compileNode( const Qg return Fail; //not supported, regexp syntax is too different to Qt case QgsExpression::boConcat: - result = QString( "%1 || %2" ).arg( left, right ); + result = QStringLiteral( "%1 || %2" ).arg( left, right ); compileResult = ( lr == Partial || rr == Partial ) ? Partial : Complete; QgsDebugMsg( QString( "CONCAT compile status: %1" ).arg( compileResult ) + "; " + result ); return compileResult; diff --git a/src/providers/db2/qgsdb2featureiterator.cpp b/src/providers/db2/qgsdb2featureiterator.cpp index 33805f7e920b..394e841f192d 100644 --- a/src/providers/db2/qgsdb2featureiterator.cpp +++ b/src/providers/db2/qgsdb2featureiterator.cpp @@ -63,17 +63,17 @@ QgsDb2FeatureIterator::~QgsDb2FeatureIterator() void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) { bool limitAtProvider = ( mRequest.limit() >= 0 ); - QString delim = ""; + QString delim = QLatin1String( "" ); // build sql statement - mStatement = QString( "SELECT " ); + mStatement = QStringLiteral( "SELECT " ); if ( !mSource->mFidColName.isEmpty() ) { mStatement += mSource->mFidColName; mFidCol = mSource->mFields.indexFromName( mSource->mFidColName ); mAttributesToFetch.append( mFidCol ); - delim = ","; + delim = QStringLiteral( "," ); } bool subsetOfAttributes = mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes; @@ -94,7 +94,7 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) if ( mSource->mFidColName == fieldname ) continue; mStatement += delim + fieldname; - delim = ","; + delim = QStringLiteral( "," ); mAttributesToFetch.append( i ); QgsDebugMsg( QString( "i: %1; name: %2" ).arg( i ).arg( fieldname ) ); } @@ -110,7 +110,7 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) mAttributesToFetch.append( 2 ); // dummy - won't store geometry as an attribute } - mStatement += QString( " FROM %1.%2" ).arg( mSource->mSchemaName, mSource->mTableName ); + mStatement += QStringLiteral( " FROM %1.%2" ).arg( mSource->mSchemaName, mSource->mTableName ); bool filterAdded = false; // set spatial filter @@ -120,14 +120,14 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) { QString rectangleWkt = request.filterRect().asWktPolygon(); QgsDebugMsg( "filter polygon: " + rectangleWkt ); - mStatement += QString( " WHERE DB2GSE.ST_Intersects(%1, DB2GSE.ST_POLYGON('%2', %3)) = 1" ).arg( + mStatement += QStringLiteral( " WHERE DB2GSE.ST_Intersects(%1, DB2GSE.ST_POLYGON('%2', %3)) = 1" ).arg( mSource->mGeometryColName, rectangleWkt, QString::number( mSource->mSRId ) ); } else { - mStatement += QString( " WHERE DB2GSE.ENVELOPESINTERSECT(%1, %2, %3, %4, %5, %6) = 1" ).arg( + mStatement += QStringLiteral( " WHERE DB2GSE.ENVELOPESINTERSECT(%1, %2, %3, %4, %5, %6) = 1" ).arg( mSource->mGeometryColName, qgsDoubleToString( request.filterRect().xMinimum() ), qgsDoubleToString( request.filterRect().yMinimum() ), @@ -141,12 +141,12 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) // set fid filter if ( request.filterType() == QgsFeatureRequest::FilterFid && !mSource->mFidColName.isEmpty() ) { - QString fidfilter = QString( " %1 = %2" ).arg( mSource->mFidColName, QString::number( request.filterFid() ) ); + QString fidfilter = QStringLiteral( " %1 = %2" ).arg( mSource->mFidColName, QString::number( request.filterFid() ) ); // set attribute filter if ( !filterAdded ) - mStatement += " WHERE "; + mStatement += QLatin1String( " WHERE " ); else - mStatement += " AND "; + mStatement += QLatin1String( " AND " ); mStatement += fidfilter; filterAdded = true; @@ -155,7 +155,7 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) && !mRequest.filterFids().isEmpty() ) { QString delim; - QString inClause = QString( "%1 IN (" ).arg( mSource->mFidColName ); + QString inClause = QStringLiteral( "%1 IN (" ).arg( mSource->mFidColName ); Q_FOREACH ( QgsFeatureId featureId, mRequest.filterFids() ) { inClause += delim + FID_TO_STRING( featureId ); @@ -164,9 +164,9 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) inClause.append( ')' ); if ( !filterAdded ) - mStatement += " WHERE "; + mStatement += QLatin1String( " WHERE " ); else - mStatement += " AND "; + mStatement += QLatin1String( " AND " ); mStatement += inClause; filterAdded = true; @@ -185,7 +185,7 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) if ( request.filterType() == QgsFeatureRequest::FilterExpression ) { QgsDebugMsg( QString( "compileExpressions: %1" ).arg( QSettings().value( "/qgis/compileExpressions", true ).toString() ) ); - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { QgsDb2ExpressionCompiler compiler = QgsDb2ExpressionCompiler( mSource ); QgsDebugMsg( "expression dump: " + request.filterExpression()->dump() ); @@ -218,7 +218,7 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) QStringList orderByParts; mOrderByCompiled = true; QgsDebugMsg( QString( "compileExpressions: %1" ).arg( QSettings().value( "/qgis/compileExpressions", true ).toString() ) ); - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() && limitAtProvider ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() && limitAtProvider ) { Q_FOREACH ( const QgsFeatureRequest::OrderByClause& clause, request.orderBy() ) { @@ -261,13 +261,13 @@ void QgsDb2FeatureIterator::BuildStatement( const QgsFeatureRequest& request ) if ( !orderByParts.isEmpty() ) { - mOrderByClause = QString( " ORDER BY %1" ).arg( orderByParts.join( "," ) ); + mOrderByClause = QStringLiteral( " ORDER BY %1" ).arg( orderByParts.join( QStringLiteral( "," ) ) ); mStatement += mOrderByClause; } if ( limitAtProvider && request.limit() > 0 ) { - mStatement += QString( " FETCH FIRST %1 ROWS ONLY" ).arg( mRequest.limit() ); + mStatement += QStringLiteral( " FETCH FIRST %1 ROWS ONLY" ).arg( mRequest.limit() ); } QgsDebugMsg( mStatement ); diff --git a/src/providers/db2/qgsdb2geometrycolumns.cpp b/src/providers/db2/qgsdb2geometrycolumns.cpp index 5576ca2dff5c..84ae03c9c92d 100644 --- a/src/providers/db2/qgsdb2geometrycolumns.cpp +++ b/src/providers/db2/qgsdb2geometrycolumns.cpp @@ -52,7 +52,7 @@ int QgsDb2GeometryColumns::open( const QString &schemaName, const QString &table if ( !schemaName.isEmpty() && !tableName.isEmpty() ) { - QString whereClause = QString( " WHERE TABLE_SCHEMA = '%1' AND TABLE_NAME = '%2'" ) + QString whereClause = QStringLiteral( " WHERE TABLE_SCHEMA = '%1' AND TABLE_NAME = '%2'" ) .arg( schemaName, tableName ); queryExtents += whereClause; queryNoExtents += whereClause; @@ -111,15 +111,15 @@ bool QgsDb2GeometryColumns::populateLayerProperty( QgsDb2LayerProperty &layer ) layer.type = mQuery.value( 3 ).toString(); if ( mQuery.value( 4 ).isNull() ) { - layer.srid = QString( "" ); - layer.srsName = QString( "" ); + layer.srid = QLatin1String( "" ); + layer.srsName = QLatin1String( "" ); } else { layer.srid = mQuery.value( 4 ).toString(); layer.srsName = mQuery.value( 5 ).toString(); } - layer.extents = QString( "0 0 0 0" ); // no extents + layer.extents = QStringLiteral( "0 0 0 0" ); // no extents if ( ENV_LUW == mEnvironment ) { if ( !mQuery.value( 6 ).isNull() ) // Don't get values if null @@ -142,7 +142,7 @@ bool QgsDb2GeometryColumns::populateLayerProperty( QgsDb2LayerProperty &layer ) // to set the FID column. // We can only use the primary key if it only has one column and // the type is Integer or BigInt. - QString table = QString( "%1.%2" ).arg( layer.schemaName, layer.tableName ); + QString table = QStringLiteral( "%1.%2" ).arg( layer.schemaName, layer.tableName ); QSqlIndex pk = mDatabase.primaryIndex( table ); if ( pk.count() == 1 ) { diff --git a/src/providers/db2/qgsdb2newconnection.cpp b/src/providers/db2/qgsdb2newconnection.cpp index dc6341f26997..acef07d17c2a 100644 --- a/src/providers/db2/qgsdb2newconnection.cpp +++ b/src/providers/db2/qgsdb2newconnection.cpp @@ -38,7 +38,7 @@ QgsDb2NewConnection::QgsDb2NewConnection( QWidget *parent, const QString& connNa { setupUi( this ); - mAuthConfigSelect = new QgsAuthConfigSelect( this, "db2" ); + mAuthConfigSelect = new QgsAuthConfigSelect( this, QStringLiteral( "db2" ) ); tabAuthentication->insertTab( 1, mAuthConfigSelect, tr( "Configurations" ) ); if ( !connName.isEmpty() ) @@ -55,13 +55,13 @@ QgsDb2NewConnection::QgsDb2NewConnection( QWidget *parent, const QString& connNa txtDatabase->setText( settings.value( key + "/database" ).toString() ); - if ( settings.value( key + "/saveUsername" ).toString() == "true" ) + if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) ) { txtUsername->setText( settings.value( key + "/username" ).toString() ); chkStoreUsername->setChecked( true ); } - if ( settings.value( key + "/savePassword" ).toString() == "true" ) + if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) ) { txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); @@ -83,7 +83,7 @@ QgsDb2NewConnection::QgsDb2NewConnection( QWidget *parent, const QString& connNa void QgsDb2NewConnection::accept() { QSettings settings; - QString baseKey = "/DB2/connections/"; + QString baseKey = QStringLiteral( "/DB2/connections/" ); settings.setValue( baseKey + "selected", txtName->text() ); bool hasAuthConfigID = !mAuthConfigSelect->configId().isEmpty(); QgsDebugMsg( QString( "hasAuthConfigID: %1" ).arg( hasAuthConfigID ) ); @@ -122,8 +122,8 @@ void QgsDb2NewConnection::accept() settings.setValue( baseKey + "/port", txtPort->text() ); settings.setValue( baseKey + "/driver", txtDriver->text() ); settings.setValue( baseKey + "/database", txtDatabase->text() ); - settings.setValue( baseKey + "/username", chkStoreUsername->isChecked() && !hasAuthConfigID ? txtUsername->text() : "" ); - settings.setValue( baseKey + "/password", chkStorePassword->isChecked() && !hasAuthConfigID ? txtPassword->text() : "" ); + settings.setValue( baseKey + "/username", chkStoreUsername->isChecked() && !hasAuthConfigID ? txtUsername->text() : QLatin1String( "" ) ); + settings.setValue( baseKey + "/password", chkStorePassword->isChecked() && !hasAuthConfigID ? txtPassword->text() : QLatin1String( "" ) ); settings.setValue( baseKey + "/saveUsername", chkStoreUsername->isChecked() && !hasAuthConfigID ? "true" : "false" ); settings.setValue( baseKey + "/savePassword", chkStorePassword->isChecked() && !hasAuthConfigID ? "true" : "false" ); settings.setValue( baseKey + "/authcfg", mAuthConfigSelect->configId() ); @@ -183,7 +183,7 @@ bool QgsDb2NewConnection::testConnection() if ( errMsg.isEmpty() ) { QgsDebugMsg( "connection open succeeded " + connInfo ); - db2ConnectStatus -> setText( "DB2 connection open succeeded" ); + db2ConnectStatus -> setText( QStringLiteral( "DB2 connection open succeeded" ) ); return true; } else diff --git a/src/providers/db2/qgsdb2provider.cpp b/src/providers/db2/qgsdb2provider.cpp index 31dc48b80f06..03a89e1ed983 100644 --- a/src/providers/db2/qgsdb2provider.cpp +++ b/src/providers/db2/qgsdb2provider.cpp @@ -25,8 +25,8 @@ #include <qgslogger.h> #include "qgscredentials.h" -static const QString PROVIDER_KEY = "DB2"; -static const QString PROVIDER_DESCRIPTION = "DB2 Spatial Extender provider"; +static const QString PROVIDER_KEY = QStringLiteral( "DB2" ); +static const QString PROVIDER_DESCRIPTION = QStringLiteral( "DB2 Spatial Extender provider" ); int QgsDb2Provider::sConnectionId = 0; @@ -57,7 +57,7 @@ QgsDb2Provider::QgsDb2Provider( const QString& uri ) mFidColName = anUri.keyColumn().toUpper(); QgsDebugMsg( "mFidColName " + mFidColName ); - mExtents = anUri.param( "extents" ); + mExtents = anUri.param( QStringLiteral( "extents" ) ); QgsDebugMsg( "mExtents " + mExtents ); mUseEstimatedMetadata = anUri.useEstimatedMetadata(); @@ -112,27 +112,27 @@ QgsDb2Provider::QgsDb2Provider( const QString& uri ) //fill type names into sets setNativeTypes( QList< NativeType >() // integer types - << QgsVectorDataProvider::NativeType( tr( "8 Bytes integer" ), "bigint", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "4 Bytes integer" ), "integer", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "2 Bytes integer" ), "smallint", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 31, 0, 31 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 31, 0, 31 ) + << QgsVectorDataProvider::NativeType( tr( "8 Bytes integer" ), QStringLiteral( "bigint" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "4 Bytes integer" ), QStringLiteral( "integer" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "2 Bytes integer" ), QStringLiteral( "smallint" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 31, 0, 31 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 31, 0, 31 ) // floating point - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double", QVariant::Double ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double" ), QVariant::Double ) // date/time types - << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Time" ), "time", QVariant::Time, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), "datetime", QVariant::DateTime, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime, -1, -1, -1, -1 ) // string types - << QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), "char", QVariant::String, 1, 254 ) - << QgsVectorDataProvider::NativeType( tr( "Text, variable length (varchar)" ), "varchar", QVariant::String, 1, 32704 ) - << QgsVectorDataProvider::NativeType( tr( "Text, variable length large object (clob)" ), "clob", QVariant::String, 1, 2147483647 ) + << QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), QStringLiteral( "char" ), QVariant::String, 1, 254 ) + << QgsVectorDataProvider::NativeType( tr( "Text, variable length (varchar)" ), QStringLiteral( "varchar" ), QVariant::String, 1, 32704 ) + << QgsVectorDataProvider::NativeType( tr( "Text, variable length large object (clob)" ), QStringLiteral( "clob" ), QVariant::String, 1, 2147483647 ) //DBCLOB is for 1073741824 double-byte characters, data length should be the same as CLOB (2147483647)? - << QgsVectorDataProvider::NativeType( tr( "Text, variable length large object (dbclob)" ), "dbclob", QVariant::String, 1, 1073741824 ) + << QgsVectorDataProvider::NativeType( tr( "Text, variable length large object (dbclob)" ), QStringLiteral( "dbclob" ), QVariant::String, 1, 1073741824 ) ); } @@ -187,7 +187,7 @@ QSqlDatabase QgsDb2Provider::getDatabase( const QString &connInfo, QString &errM if ( !QSqlDatabase::contains( connectionName ) ) { QgsDebugMsg( "new connection. create new QODBC mapping" ); - db = QSqlDatabase::addDatabase( "QODBC3", connectionName ); + db = QSqlDatabase::addDatabase( QStringLiteral( "QODBC3" ), connectionName ); } else /* if existing database connection */ { @@ -210,7 +210,7 @@ QSqlDatabase QgsDb2Provider::getDatabase( const QString &connInfo, QString &errM password, errMsg ); if ( !ok ) { - errMsg = "Cancel clicked"; + errMsg = QStringLiteral( "Cancel clicked" ); QgsDebugMsg( errMsg ); QgsCredentials::instance()->unlock(); break; @@ -242,7 +242,7 @@ QSqlDatabase QgsDb2Provider::getDatabase( const QString &connInfo, QString &errM if ( db.open() ) { connected = true; - errMsg = ""; + errMsg = QLatin1String( "" ); } else { @@ -278,7 +278,7 @@ void QgsDb2Provider::loadFields() { mAttributeFields.clear(); //mDefaultValues.clear(); - QString table = QString( "%1.%2" ).arg( mSchemaName, mTableName ); + QString table = QStringLiteral( "%1.%2" ).arg( mSchemaName, mTableName ); // Use the Qt functionality to get the fields and their definitions. QSqlRecord r = mDatabase.record( table ); @@ -389,55 +389,55 @@ QVariant::Type QgsDb2Provider::decodeSqlType( int typeId ) // Return the DB2 type name for the type numeric value QString QgsDb2Provider::db2TypeName( int typeId ) { - QString typeName = ""; + QString typeName = QLatin1String( "" ); switch ( typeId ) { case -3: //VARBINARY - typeName = "VARBINARY"; // also for spatial types + typeName = QStringLiteral( "VARBINARY" ); // also for spatial types break; case 1: //CHAR - typeName = "CHAR"; + typeName = QStringLiteral( "CHAR" ); break; case 12: //VARCHAR - typeName = "VARCHAR"; + typeName = QStringLiteral( "VARCHAR" ); break; case 4: //INTEGER - typeName = "INTEGER"; + typeName = QStringLiteral( "INTEGER" ); break; case -5: //BIGINT - typeName = "BIGINT"; + typeName = QStringLiteral( "BIGINT" ); break; case 3: //NUMERIC and DECIMAL - typeName = "DECIMAL"; + typeName = QStringLiteral( "DECIMAL" ); break; case 7: //REAL - typeName = "REAL"; + typeName = QStringLiteral( "REAL" ); break; case 8: //DOUBLE - typeName = "DOUBLE"; + typeName = QStringLiteral( "DOUBLE" ); break; case 9: //DATE - typeName = "DATE"; + typeName = QStringLiteral( "DATE" ); break; case 10: //TIME - typeName = "TIME"; + typeName = QStringLiteral( "TIME" ); break; case 11: //TIMESTAMP - typeName = "TIMESTAMP"; + typeName = QStringLiteral( "TIMESTAMP" ); break; default: - typeName = "UNKNOWN"; + typeName = QStringLiteral( "UNKNOWN" ); } return typeName; @@ -477,7 +477,7 @@ long QgsDb2Provider::featureCount() const QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - QString sql = "SELECT COUNT(*) FROM %1.%2"; + QString sql = QStringLiteral( "SELECT COUNT(*) FROM %1.%2" ); QString statement = QString( sql ).arg( mSchemaName, mTableName ); QgsDebugMsg( statement ); if ( query.exec( statement ) && query.next() ) @@ -511,7 +511,7 @@ QgsCoordinateReferenceSystem QgsDb2Provider::crs() const // try to load crs from the database tables as a fallback QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - bool execOk = query.exec( QString( "SELECT DEFINITION FROM DB2GSE.ST_SPATIAL_REFERENCE_SYSTEMS WHERE SRS_ID = %1" ).arg( QString::number( mSRId ) ) ); + bool execOk = query.exec( QStringLiteral( "SELECT DEFINITION FROM DB2GSE.ST_SPATIAL_REFERENCE_SYSTEMS WHERE SRS_ID = %1" ).arg( QString::number( mSRId ) ) ); if ( execOk && query.isActive() ) { if ( query.next() ) @@ -534,9 +534,9 @@ void QgsDb2Provider::updateStatistics() const QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - statement = QString( "SELECT MIN(DB2GSE.ST_MINX(%1)), MIN(DB2GSE.ST_MINY(%1)), MAX(DB2GSE.ST_MAXX(%1)), MAX(DB2GSE.ST_MAXY(%1))" ).arg( mGeometryColName ); + statement = QStringLiteral( "SELECT MIN(DB2GSE.ST_MINX(%1)), MIN(DB2GSE.ST_MINY(%1)), MAX(DB2GSE.ST_MAXX(%1)), MAX(DB2GSE.ST_MAXY(%1))" ).arg( mGeometryColName ); - statement += QString( " FROM %1.%2" ).arg( mSchemaName, mTableName ); + statement += QStringLiteral( " FROM %1.%2" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { @@ -594,7 +594,7 @@ void QgsDb2Provider::updateStatistics() const if ( -1 == mSRId ) { query.clear(); - statement = QString( "SELECT DB2GSE.ST_SRID(%1) FROM %2.%3 FETCH FIRST ROW ONLY" ) + statement = QStringLiteral( "SELECT DB2GSE.ST_SRID(%1) FROM %2.%3 FETCH FIRST ROW ONLY" ) .arg( mGeometryColName, mSchemaName, mTableName ); QgsDebugMsg( statement ); @@ -641,13 +641,13 @@ bool QgsDb2Provider::setSubsetString( const QString& theSQL, bool ) QgsDebugMsg( theSQL ); mSqlWhereClause = theSQL.trimmed(); - QString sql = QString( "SELECT COUNT(*) FROM " ); + QString sql = QStringLiteral( "SELECT COUNT(*) FROM " ); - sql += QString( "%1.%2" ).arg( mSchemaName, mTableName ); + sql += QStringLiteral( "%1.%2" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " WHERE %1" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " WHERE %1" ).arg( mSqlWhereClause ); } if ( !openDatabase( mDatabase ) ) @@ -699,19 +699,19 @@ void QgsDb2Provider::db2WkbTypeAndDimension( QgsWkbTypes::Type wkbType, QString QgsWkbTypes::Type flatType = QgsWkbTypes::flatType( wkbType ); if ( flatType == QgsWkbTypes::Point ) - geometryType = "POINT"; + geometryType = QStringLiteral( "POINT" ); else if ( flatType == QgsWkbTypes::LineString ) - geometryType = "LINESTRING"; + geometryType = QStringLiteral( "LINESTRING" ); else if ( flatType == QgsWkbTypes::Polygon ) - geometryType = "POLYGON"; + geometryType = QStringLiteral( "POLYGON" ); else if ( flatType == QgsWkbTypes::MultiPoint ) - geometryType = "MULTIPOINT"; + geometryType = QStringLiteral( "MULTIPOINT" ); else if ( flatType == QgsWkbTypes::MultiLineString ) - geometryType = "MULTILINESTRING"; + geometryType = QStringLiteral( "MULTILINESTRING" ); else if ( flatType == QgsWkbTypes::MultiPolygon ) - geometryType = "MULTIPOLYGON"; + geometryType = QStringLiteral( "MULTIPOLYGON" ); else if ( flatType == QgsWkbTypes::Unknown ) - geometryType = "GEOMETRY"; + geometryType = QStringLiteral( "GEOMETRY" ); else dim = 0; } @@ -742,7 +742,7 @@ bool QgsDb2Provider::deleteFeatures( const QgsFeatureIds & id ) QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); QString statement; - statement = QString( "DELETE FROM %1.%2 WHERE %3 IN (%4)" ).arg( mSchemaName, + statement = QStringLiteral( "DELETE FROM %1.%2 WHERE %3 IN (%4)" ).arg( mSchemaName, mTableName, mFidColName, featureIds ); QgsDebugMsg( statement ); if ( !query.exec( statement ) ) @@ -776,7 +776,7 @@ bool QgsDb2Provider::changeAttributeValues( const QgsChangedAttributesMap &attr_ if ( attrs.isEmpty() ) continue; - QString statement = QString( "UPDATE %1.%2 SET " ).arg( mSchemaName, mTableName ); + QString statement = QStringLiteral( "UPDATE %1.%2 SET " ).arg( mSchemaName, mTableName ); bool first = true; if ( !mDatabase.isOpen() ) @@ -795,7 +795,7 @@ bool QgsDb2Provider::changeAttributeValues( const QgsChangedAttributesMap &attr_ { QgsField fld = mAttributeFields.at( it2.key() ); - if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) ) + if ( fld.typeName().endsWith( QLatin1String( " identity" ), Qt::CaseInsensitive ) ) continue; // skip identity field if ( fld.name().isEmpty() ) @@ -806,14 +806,14 @@ bool QgsDb2Provider::changeAttributeValues( const QgsChangedAttributesMap &attr_ else first = false; - statement += QString( "%1=?" ).arg( fld.name() ); + statement += QStringLiteral( "%1=?" ).arg( fld.name() ); } if ( first ) return true; // no fields have been changed // set attribute filter - statement += QString( " WHERE %1=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); + statement += QStringLiteral( " WHERE %1=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); // use prepared statement to prevent from sql injection if ( !query.prepare( statement ) ) @@ -912,7 +912,7 @@ bool QgsDb2Provider::addFeatures( QgsFeatureList & flist ) QgsFeature it = flist.at( 0 ); QString statement; QString values; - statement = QString( "INSERT INTO %1.%2 (" ).arg( mSchemaName, mTableName ); + statement = QStringLiteral( "INSERT INTO %1.%2 (" ).arg( mSchemaName, mTableName ); bool first = true; @@ -969,8 +969,8 @@ bool QgsDb2Provider::addFeatures( QgsFeatureList & flist ) else first = false; - statement += QString( "%1" ).arg( fld.name() ); - values += QString( "?" ); + statement += QStringLiteral( "%1" ).arg( fld.name() ); + values += QStringLiteral( "?" ); } // append geometry column name @@ -982,11 +982,11 @@ bool QgsDb2Provider::addFeatures( QgsFeatureList & flist ) values += ','; } - statement += QString( "%1" ).arg( mGeometryColName ); + statement += QStringLiteral( "%1" ).arg( mGeometryColName ); - values += QString( "db2gse.%1(CAST (%2 AS BLOB(2M)),%3)" ) + values += QStringLiteral( "db2gse.%1(CAST (%2 AS BLOB(2M)),%3)" ) .arg( mGeometryColType, - QString( "?" ), + QStringLiteral( "?" ), QString::number( mSRId ) ); } @@ -1141,7 +1141,7 @@ bool QgsDb2Provider::addFeatures( QgsFeatureList & flist ) .arg( commitStatus ).arg( writeCount ).arg( queryFid.value( 0 ).toLongLong() ) ); if ( !commitStatus ) { - pushError( "Commit of new features failed" ); + pushError( QStringLiteral( "Commit of new features failed" ) ); return false; } return true; @@ -1187,7 +1187,7 @@ bool QgsDb2Provider::changeGeometryValues( const QgsGeometryMap &geometry_map ) } QString statement; - statement = QString( "UPDATE %1.%2 SET %3 = " ) + statement = QStringLiteral( "UPDATE %1.%2 SET %3 = " ) .arg( mSchemaName, mTableName, mGeometryColName ); if ( !mDatabase.isOpen() ) @@ -1202,13 +1202,13 @@ bool QgsDb2Provider::changeGeometryValues( const QgsGeometryMap &geometry_map ) QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - statement += QString( "db2gse.%1(CAST (%2 AS BLOB(2M)),%3)" ) + statement += QStringLiteral( "db2gse.%1(CAST (%2 AS BLOB(2M)),%3)" ) .arg( mGeometryColType, - QString( "?" ), + QStringLiteral( "?" ), QString::number( mSRId ) ); // set attribute filter - statement += QString( " WHERE %1=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); + statement += QStringLiteral( " WHERE %1=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); QgsDebugMsg( statement ); if ( !query.prepare( statement ) ) { @@ -1269,7 +1269,7 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin if ( srid >= 0 ) { QSqlQuery query( db ); - QString statement = QString( "SELECT srs_name FROM db2gse.st_spatial_reference_systems where srs_id=%1" ) + QString statement = QStringLiteral( "SELECT srs_name FROM db2gse.st_spatial_reference_systems where srs_id=%1" ) .arg( srid ); QgsDebugMsg( statement ); @@ -1318,10 +1318,10 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin QgsWkbTypes::Type wkbTypeSingle; wkbTypeSingle = QgsWkbTypes::singleType( wkbType ); if ( wkbType != QgsWkbTypes::NoGeometry && geometryColumn.isEmpty() ) - geometryColumn = "GEOM"; + geometryColumn = QStringLiteral( "GEOM" ); if ( primaryKey.isEmpty() ) - primaryKey = "QGS_FID"; + primaryKey = QStringLiteral( "QGS_FID" ); // get the pk's name and type // if no pk name was passed, define the new pk field name @@ -1329,13 +1329,13 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin if ( primaryKey.isEmpty() ) { int index = 0; - QString pk = primaryKey = "QGS_FID"; + QString pk = primaryKey = QStringLiteral( "QGS_FID" ); for ( int i = 0; i < fieldCount; ++i ) { if ( fields.at( i ).name() == primaryKey ) { // it already exists, try again with a new name - primaryKey = QString( "%1_%2" ).arg( pk ).arg( index++ ); + primaryKey = QStringLiteral( "%1_%2" ).arg( pk ).arg( index++ ); i = 0; } } @@ -1389,7 +1389,7 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin // add fields to the layer if ( oldToNewAttrIdxMap ) oldToNewAttrIdxMap->clear(); - QString attr2Create = ""; + QString attr2Create = QLatin1String( "" ); if ( fields.size() > 0 ) { int offset = 0; @@ -1445,7 +1445,7 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin else { //geometryless table - sql = QString( // need to set specific geometry type + sql = QStringLiteral( // need to set specific geometry type "CREATE TABLE %1.%2(%3 INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS %4) " ) .arg( schemaName, tableName, @@ -1484,13 +1484,13 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin } if ( ENV_LUW == db2Environment ) { - sql = QString( "CALL DB2GSE.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?, ?)" ); + sql = QStringLiteral( "CALL DB2GSE.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?, ?)" ); outCode = 5; outMsg = 6; } else // z/OS doesn't support 'computeExtents' parameter and has different schema { - sql = QString( "CALL SYSPROC.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?)" ); + sql = QStringLiteral( "CALL SYSPROC.ST_Register_Spatial_Column(?, ?, ?, ?, ?, ?)" ); outCode = 4; outMsg = 5; } @@ -1544,41 +1544,41 @@ QgsVectorLayerImport::ImportError QgsDb2Provider::createEmptyLayer( const QStrin QString QgsDb2Provider::qgsFieldToDb2Field( const QgsField& field ) { - QString result = ""; + QString result = QLatin1String( "" ); switch ( field.type() ) { case QVariant::LongLong: - result = "BIGINT"; + result = QStringLiteral( "BIGINT" ); break; case QVariant::DateTime: - result = "TIMESTAMP"; + result = QStringLiteral( "TIMESTAMP" ); break; case QVariant::Date: - result = "DATE"; + result = QStringLiteral( "DATE" ); break; case QVariant::Time: - result = "TIME"; + result = QStringLiteral( "TIME" ); break; case QVariant::String: - result = QString( "VARCHAR(%1)" ).arg( field.length() ); + result = QStringLiteral( "VARCHAR(%1)" ).arg( field.length() ); break; case QVariant::Int: - result = "INTEGER"; + result = QStringLiteral( "INTEGER" ); break; case QVariant::Double: if ( field.length() <= 0 || field.precision() <= 0 ) { - result = "DOUBLE"; + result = QStringLiteral( "DOUBLE" ); } else { - result = QString( "DECIMAL(%1,%2)" ).arg( field.length(), field.precision() ); + result = QStringLiteral( "DECIMAL(%1,%2)" ).arg( field.length(), field.precision() ); } break; @@ -1593,39 +1593,39 @@ QString QgsDb2Provider::qgsFieldToDb2Field( const QgsField& field ) } bool QgsDb2Provider::convertField( QgsField &field ) { - QString fieldType = "VARCHAR"; //default to string + QString fieldType = QStringLiteral( "VARCHAR" ); //default to string int fieldSize = field.length(); int fieldPrec = field.precision(); switch ( field.type() ) { case QVariant::LongLong: - fieldType = "BIGINT"; + fieldType = QStringLiteral( "BIGINT" ); fieldSize = -1; fieldPrec = 0; break; case QVariant::DateTime: - fieldType = "TIMESTAMP"; + fieldType = QStringLiteral( "TIMESTAMP" ); fieldPrec = -1; break; case QVariant::Date: - fieldType = "DATE"; + fieldType = QStringLiteral( "DATE" ); fieldPrec = -1; break; case QVariant::Time: - fieldType = "TIME"; + fieldType = QStringLiteral( "TIME" ); fieldPrec = -1; break; case QVariant::String: - fieldType = "VARCHAR"; + fieldType = QStringLiteral( "VARCHAR" ); fieldPrec = -1; break; case QVariant::Int: - fieldType = "INTEGER"; + fieldType = QStringLiteral( "INTEGER" ); fieldSize = -1; fieldPrec = 0; break; @@ -1633,13 +1633,13 @@ bool QgsDb2Provider::convertField( QgsField &field ) case QVariant::Double: if ( fieldSize <= 0 || fieldPrec <= 0 ) { - fieldType = "DOUBLE"; + fieldType = QStringLiteral( "DOUBLE" ); fieldSize = -1; fieldPrec = -1; } else { - fieldType = "DECIMAL"; + fieldType = QStringLiteral( "DECIMAL" ); } break; @@ -1698,7 +1698,7 @@ QGISEXTERN QgsDataItem *dataItem( QString thePath, QgsDataItem *parentItem ) { Q_UNUSED( thePath ); QgsDebugMsg( "DB2: Browser Panel; data item detected." ); - return new QgsDb2RootItem( parentItem, PROVIDER_KEY, "DB2:" ); + return new QgsDb2RootItem( parentItem, PROVIDER_KEY, QStringLiteral( "DB2:" ) ); } diff --git a/src/providers/db2/qgsdb2sourceselect.cpp b/src/providers/db2/qgsdb2sourceselect.cpp index f70a9394c270..0296d376cd07 100644 --- a/src/providers/db2/qgsdb2sourceselect.cpp +++ b/src/providers/db2/qgsdb2sourceselect.cpp @@ -179,7 +179,7 @@ QgsDb2SourceSelect::QgsDb2SourceSelect( QWidget *parent, Qt::WindowFlags fl, boo connect( mTablesTreeView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( treeWidgetSelectionChanged( const QItemSelection&, const QItemSelection& ) ) ); QSettings settings; - mTablesTreeView->setSelectionMode( settings.value( "/qgis/addDb2DC", false ).toBool() ? + mTablesTreeView->setSelectionMode( settings.value( QStringLiteral( "/qgis/addDb2DC" ), false ).toBool() ? QAbstractItemView::ExtendedSelection : QAbstractItemView::MultiSelection ); @@ -188,12 +188,12 @@ QgsDb2SourceSelect::QgsDb2SourceSelect( QWidget *parent, Qt::WindowFlags fl, boo //in search does not seem to work mSearchColumnComboBox->setCurrentIndex( 2 ); - restoreGeometry( settings.value( "/Windows/Db2SourceSelect/geometry" ).toByteArray() ); - mHoldDialogOpen->setChecked( settings.value( "/Windows/Db2SourceSelect/HoldDialogOpen", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/Db2SourceSelect/geometry" ) ).toByteArray() ); + mHoldDialogOpen->setChecked( settings.value( QStringLiteral( "/Windows/Db2SourceSelect/HoldDialogOpen" ), false ).toBool() ); for ( int i = 0; i < mTableModel.columnCount(); i++ ) { - mTablesTreeView->setColumnWidth( i, settings.value( QString( "/Windows/Db2SourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ).toInt() ); + mTablesTreeView->setColumnWidth( i, settings.value( QStringLiteral( "/Windows/Db2SourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ).toInt() ); } //hide the search options by default @@ -261,7 +261,7 @@ void QgsDb2SourceSelect::on_btnSave_clicked() void QgsDb2SourceSelect::on_btnLoad_clicked() { - QString fileName = QFileDialog::getOpenFileName( this, tr( "Load connections" ), ".", + QString fileName = QFileDialog::getOpenFileName( this, tr( "Load connections" ), QStringLiteral( "." ), tr( "XML files (*.xml *XML)" ) ); if ( fileName.isEmpty() ) { @@ -292,7 +292,7 @@ void QgsDb2SourceSelect::on_cmbConnections_activated( int ) { // Remember which database was selected. QSettings settings; - settings.setValue( "/Db2/connections/selected", cmbConnections->currentText() ); + settings.setValue( QStringLiteral( "/Db2/connections/selected" ), cmbConnections->currentText() ); cbxAllowGeometrylessTables->blockSignals( true ); cbxAllowGeometrylessTables->setChecked( settings.value( "/Db2/connections/" + cmbConnections->currentText() + "/allowGeometrylessTables", false ).toBool() ); @@ -317,7 +317,7 @@ void QgsDb2SourceSelect::on_mTablesTreeView_clicked( const QModelIndex &index ) void QgsDb2SourceSelect::on_mTablesTreeView_doubleClicked( const QModelIndex &index ) { QSettings settings; - if ( settings.value( "/qgis/addDb2DC", false ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/addDb2DC" ), false ).toBool() ) { addTables(); } @@ -332,7 +332,7 @@ void QgsDb2SourceSelect::on_mSearchGroupBox_toggled( bool checked ) if ( mSearchTableEdit->text().isEmpty() ) return; - on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : "" ); + on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : QLatin1String( "" ) ); } void QgsDb2SourceSelect::on_mSearchTableEdit_textChanged( const QString & text ) @@ -403,19 +403,19 @@ QgsDb2SourceSelect::~QgsDb2SourceSelect() } QSettings settings; - settings.setValue( "/Windows/Db2SourceSelect/geometry", saveGeometry() ); - settings.setValue( "/Windows/Db2SourceSelect/HoldDialogOpen", mHoldDialogOpen->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/Db2SourceSelect/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/Db2SourceSelect/HoldDialogOpen" ), mHoldDialogOpen->isChecked() ); for ( int i = 0; i < mTableModel.columnCount(); i++ ) { - settings.setValue( QString( "/Windows/Db2SourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ); + settings.setValue( QStringLiteral( "/Windows/Db2SourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ); } } void QgsDb2SourceSelect::populateConnectionList() { QSettings settings; - settings.beginGroup( "/Db2/connections" ); + settings.beginGroup( QStringLiteral( "/Db2/connections" ) ); QStringList keys = settings.childGroups(); QStringList::Iterator it = keys.begin(); cmbConnections->clear(); @@ -457,7 +457,7 @@ void QgsDb2SourceSelect::addTables() } else { - emit addDatabaseLayers( mSelectedTables, "DB2" ); + emit addDatabaseLayers( mSelectedTables, QStringLiteral( "DB2" ) ); if ( !mHoldDialogOpen->isChecked() ) { accept(); @@ -593,7 +593,7 @@ void QgsDb2SourceSelect::setSql( const QModelIndex &index ) QModelIndex idx = mProxyModel.mapToSource( index ); QString tableName = mTableModel.itemFromIndex( idx.sibling( idx.row(), QgsDb2TableModel::dbtmTable ) )->text(); - QgsVectorLayer *vlayer = new QgsVectorLayer( mTableModel.layerURI( idx, mConnInfo, mUseEstimatedMetadata ), tableName, "DB2" ); + QgsVectorLayer *vlayer = new QgsVectorLayer( mTableModel.layerURI( idx, mConnInfo, mUseEstimatedMetadata ), tableName, QStringLiteral( "DB2" ) ); if ( !vlayer->isValid() ) { @@ -633,7 +633,7 @@ void QgsDb2SourceSelect::addSearchGeometryColumn( const QString& connectionName, QString QgsDb2SourceSelect::fullDescription( const QString& schema, const QString& table, const QString& column, const QString& type ) { - QString full_desc = ""; + QString full_desc = QLatin1String( "" ); if ( !schema.isEmpty() ) full_desc = schema + "."; full_desc += table + " (" + column + ") " + type; @@ -644,7 +644,7 @@ void QgsDb2SourceSelect::setConnectionListPosition() { // If possible, set the item currently displayed database QSettings settings; - QString toSelect = settings.value( "/Db2/connections/selected" ).toString(); + QString toSelect = settings.value( QStringLiteral( "/Db2/connections/selected" ) ).toString(); cmbConnections->setCurrentIndex( cmbConnections->findText( toSelect ) ); if ( cmbConnections->currentIndex() < 0 ) @@ -700,8 +700,8 @@ void QgsDb2GeomColumnTypeThread::run() if ( !mStopped ) { QString table; - table = QString( "%1[%2]" ) - .arg( layerProperty.schemaName.isEmpty() ? "" : QString( "[%1]." ).arg( layerProperty.schemaName ), + table = QStringLiteral( "%1[%2]" ) + .arg( layerProperty.schemaName.isEmpty() ? QLatin1String( "" ) : QStringLiteral( "[%1]." ).arg( layerProperty.schemaName ), layerProperty.tableName ); QString query = QString( "SELECT %3" @@ -713,7 +713,7 @@ void QgsDb2GeomColumnTypeThread::run() .arg( layerProperty.geometryColName, table, mUseEstimatedMetadata ? "TOP 1" : "", - layerProperty.sql.isEmpty() ? "" : QString( " AND %1" ).arg( layerProperty.sql ) ); + layerProperty.sql.isEmpty() ? QLatin1String( "" ) : QStringLiteral( " AND %1" ).arg( layerProperty.sql ) ); // issue the sql query QSqlDatabase db = QSqlDatabase::database( mConnectionName ); @@ -750,8 +750,8 @@ void QgsDb2GeomColumnTypeThread::run() srids << srid; } - type = types.join( "," ); - srid = srids.join( "," ); + type = types.join( QStringLiteral( "," ) ); + srid = srids.join( QStringLiteral( "," ) ); } layerProperty.type = type; @@ -759,8 +759,8 @@ void QgsDb2GeomColumnTypeThread::run() } else { - layerProperty.type = ""; - layerProperty.srid = ""; + layerProperty.type = QLatin1String( "" ); + layerProperty.srid = QLatin1String( "" ); } // Now tell the layer list dialog box... diff --git a/src/providers/db2/qgsdb2tablemodel.cpp b/src/providers/db2/qgsdb2tablemodel.cpp index e26a58c12709..c2f2421dfdd0 100644 --- a/src/providers/db2/qgsdb2tablemodel.cpp +++ b/src/providers/db2/qgsdb2tablemodel.cpp @@ -75,7 +75,7 @@ void QgsDb2TableModel::addTableEntry( const QgsDb2LayerProperty &layerProperty ) wkbType = QgsWkbTypes::NoGeometry; } - bool needToDetect = wkbType == QgsWkbTypes::Unknown && layerProperty.type != "GEOMETRYCOLLECTION"; + bool needToDetect = wkbType == QgsWkbTypes::Unknown && layerProperty.type != QLatin1String( "GEOMETRYCOLLECTION" ); QList<QStandardItem*> childItemList; @@ -94,11 +94,11 @@ void QgsDb2TableModel::addTableEntry( const QgsDb2LayerProperty &layerProperty ) QStandardItem *sridItem = new QStandardItem( layerProperty.srid ); sridItem->setEditable( false ); - QString pkText, pkCol = ""; + QString pkText, pkCol = QLatin1String( "" ); switch ( layerProperty.pkCols.size() ) { case 0: - pkText = ""; + pkText = QLatin1String( "" ); break; case 1: pkText = layerProperty.pkCols[0]; @@ -116,7 +116,7 @@ void QgsDb2TableModel::addTableEntry( const QgsDb2LayerProperty &layerProperty ) pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 ); pkItem->setData( pkCol, Qt::UserRole + 2 ); - QStandardItem *selItem = new QStandardItem( "" ); + QStandardItem *selItem = new QStandardItem( QLatin1String( "" ) ); selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable ); selItem->setCheckState( Qt::Checked ); selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) ); @@ -216,8 +216,8 @@ void QgsDb2TableModel::setSql( const QModelIndex &index, const QString &sql ) void QgsDb2TableModel::setGeometryTypesForTable( QgsDb2LayerProperty layerProperty ) { - QStringList typeList = layerProperty.type.split( ",", QString::SkipEmptyParts ); - QStringList sridList = layerProperty.srid.split( ",", QString::SkipEmptyParts ); + QStringList typeList = layerProperty.type.split( QStringLiteral( "," ), QString::SkipEmptyParts ); + QStringList sridList = layerProperty.srid.split( QStringLiteral( "," ), QString::SkipEmptyParts ); Q_ASSERT( typeList.size() == sridList.size() ); //find schema item and table item @@ -404,38 +404,38 @@ QgsWkbTypes::Type QgsDb2TableModel::wkbTypeFromDb2( QString type, int dim ) if ( dim == 3 ) { - if ( type == "ST_POINT" ) + if ( type == QLatin1String( "ST_POINT" ) ) return QgsWkbTypes::Point25D; - if ( type == "ST_LINESTRING" ) + if ( type == QLatin1String( "ST_LINESTRING" ) ) return QgsWkbTypes::LineString25D; - if ( type == "ST_POLYGON" ) + if ( type == QLatin1String( "ST_POLYGON" ) ) return QgsWkbTypes::Polygon25D; - if ( type == "ST_MULTIPOINT" ) + if ( type == QLatin1String( "ST_MULTIPOINT" ) ) return QgsWkbTypes::MultiPoint25D; - if ( type == "ST_MULTILINESTRING" ) + if ( type == QLatin1String( "ST_MULTILINESTRING" ) ) return QgsWkbTypes::MultiLineString25D; - if ( type == "ST_MULTIPOLYGON" ) + if ( type == QLatin1String( "ST_MULTIPOLYGON" ) ) return QgsWkbTypes::MultiPolygon25D; - if ( type == "NONE" ) + if ( type == QLatin1String( "NONE" ) ) return QgsWkbTypes::NoGeometry; else return QgsWkbTypes::Unknown; } else { - if ( type == "ST_POINT" ) + if ( type == QLatin1String( "ST_POINT" ) ) return QgsWkbTypes::Point; - if ( type == "ST_LINESTRING" ) + if ( type == QLatin1String( "ST_LINESTRING" ) ) return QgsWkbTypes::LineString; - if ( type == "ST_POLYGON" ) + if ( type == QLatin1String( "ST_POLYGON" ) ) return QgsWkbTypes::Polygon; - if ( type == "ST_MULTIPOINT" ) + if ( type == QLatin1String( "ST_MULTIPOINT" ) ) return QgsWkbTypes::MultiPoint; - if ( type == "ST_MULTILINESTRING" ) + if ( type == QLatin1String( "ST_MULTILINESTRING" ) ) return QgsWkbTypes::MultiLineString; - if ( type == "ST_MULTIPOLYGON" ) + if ( type == QLatin1String( "ST_MULTIPOLYGON" ) ) return QgsWkbTypes::MultiPolygon; - if ( type == "NONE" ) + if ( type == QLatin1String( "NONE" ) ) return QgsWkbTypes::NoGeometry; else return QgsWkbTypes::Unknown; diff --git a/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp b/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp index 0ebb0e23283c..ac6026533c0e 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp +++ b/src/providers/delimitedtext/qgsdelimitedtextfeatureiterator.cpp @@ -455,7 +455,7 @@ void QgsDelimitedTextFeatureIterator::fetchAttribute( QgsFeature& feature, int f } else { - dvalue = QString( value ).replace( mSource->mDecimalPoint, "." ).toDouble( &ok ); + dvalue = QString( value ).replace( mSource->mDecimalPoint, QLatin1String( "." ) ).toDouble( &ok ); } } if ( ok ) @@ -500,9 +500,9 @@ QgsDelimitedTextFeatureSource::QgsDelimitedTextFeatureSource( const QgsDelimited QUrl url = p->mFile->url(); // make sure watcher not created when using iterator (e.g. for rendering, see issue #15558) - if ( url.hasQueryItem( "watchFile" ) ) + if ( url.hasQueryItem( QStringLiteral( "watchFile" ) ) ) { - url.removeQueryItem( "watchFile" ); + url.removeQueryItem( QStringLiteral( "watchFile" ) ); } mFile = new QgsDelimitedTextFile(); diff --git a/src/providers/delimitedtext/qgsdelimitedtextfile.cpp b/src/providers/delimitedtext/qgsdelimitedtextfile.cpp index d66359f0a5a6..cd5838c1f129 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfile.cpp +++ b/src/providers/delimitedtext/qgsdelimitedtextfile.cpp @@ -32,7 +32,7 @@ QgsDelimitedTextFile::QgsDelimitedTextFile( const QString& url ) : mFileName( QString() ) - , mEncoding( "UTF-8" ) + , mEncoding( QStringLiteral( "UTF-8" ) ) , mFile( nullptr ) , mStream( nullptr ) , mUseWatcher( false ) @@ -51,7 +51,7 @@ QgsDelimitedTextFile::QgsDelimitedTextFile( const QString& url ) , mHoldCurrentRecord( false ) , mMaxRecordNumber( -1 ) , mMaxFieldCount( 0 ) - , mDefaultFieldName( "field_%1" ) + , mDefaultFieldName( QStringLiteral( "field_%1" ) ) // field_ is optional in following regexp to simplify QgsDelimitedTextFile::fieldNumber() , mDefaultFieldRegexp( "^(?:field_)?(\\d+)$", Qt::CaseInsensitive ) { @@ -152,81 +152,81 @@ bool QgsDelimitedTextFile::setFromUrl( const QUrl &url ) setFileName( url.toLocalFile() ); // Extract the encoding - if ( url.hasQueryItem( "encoding" ) ) + if ( url.hasQueryItem( QStringLiteral( "encoding" ) ) ) { - mEncoding = url.queryItemValue( "encoding" ); + mEncoding = url.queryItemValue( QStringLiteral( "encoding" ) ); } // - if ( url.hasQueryItem( "watchFile" ) ) + if ( url.hasQueryItem( QStringLiteral( "watchFile" ) ) ) { - mUseWatcher = url.queryItemValue( "watchFile" ).toUpper().startsWith( 'Y' ); + mUseWatcher = url.queryItemValue( QStringLiteral( "watchFile" ) ).toUpper().startsWith( 'Y' ); } // The default type is csv, to be consistent with the // previous implementation (except that quoting should be handled properly) - QString type( "csv" ); - QString delimiter( "," ); - QString quote = "\""; - QString escape = "\""; + QString type( QStringLiteral( "csv" ) ); + QString delimiter( QStringLiteral( "," ) ); + QString quote = QStringLiteral( "\"" ); + QString escape = QStringLiteral( "\"" ); mUseHeader = true; mSkipLines = 0; // Prefer simple "type" for delimiter type, but include delimiterType // as optional name for backwards compatibility - if ( url.hasQueryItem( "type" ) || url.hasQueryItem( "delimiterType" ) ) + if ( url.hasQueryItem( QStringLiteral( "type" ) ) || url.hasQueryItem( QStringLiteral( "delimiterType" ) ) ) { - if ( url.hasQueryItem( "type" ) ) - type = url.queryItemValue( "type" ); - else if ( url.hasQueryItem( "delimiterType" ) ) - type = url.queryItemValue( "delimiterType" ); + if ( url.hasQueryItem( QStringLiteral( "type" ) ) ) + type = url.queryItemValue( QStringLiteral( "type" ) ); + else if ( url.hasQueryItem( QStringLiteral( "delimiterType" ) ) ) + type = url.queryItemValue( QStringLiteral( "delimiterType" ) ); // Support for previous version of Qgs - plain chars had // quote characters ' or " - if ( type == "plain" ) + if ( type == QLatin1String( "plain" ) ) { - quote = "'\""; - escape = ""; + quote = QStringLiteral( "'\"" ); + escape = QLatin1String( "" ); } - else if ( type == "regexp " ) + else if ( type == QLatin1String( "regexp " ) ) { - delimiter = ""; - quote = ""; - escape = ""; + delimiter = QLatin1String( "" ); + quote = QLatin1String( "" ); + escape = QLatin1String( "" ); } } - if ( url.hasQueryItem( "delimiter" ) ) + if ( url.hasQueryItem( QStringLiteral( "delimiter" ) ) ) { - delimiter = url.queryItemValue( "delimiter" ); + delimiter = url.queryItemValue( QStringLiteral( "delimiter" ) ); } - if ( url.hasQueryItem( "quote" ) ) + if ( url.hasQueryItem( QStringLiteral( "quote" ) ) ) { - quote = url.queryItemValue( "quote" ); + quote = url.queryItemValue( QStringLiteral( "quote" ) ); } - if ( url.hasQueryItem( "escape" ) ) + if ( url.hasQueryItem( QStringLiteral( "escape" ) ) ) { - escape = url.queryItemValue( "escape" ); + escape = url.queryItemValue( QStringLiteral( "escape" ) ); } - if ( url.hasQueryItem( "skipLines" ) ) + if ( url.hasQueryItem( QStringLiteral( "skipLines" ) ) ) { - mSkipLines = url.queryItemValue( "skipLines" ).toInt(); + mSkipLines = url.queryItemValue( QStringLiteral( "skipLines" ) ).toInt(); } - if ( url.hasQueryItem( "useHeader" ) ) + if ( url.hasQueryItem( QStringLiteral( "useHeader" ) ) ) { - mUseHeader = ! url.queryItemValue( "useHeader" ).toUpper().startsWith( 'N' ); + mUseHeader = ! url.queryItemValue( QStringLiteral( "useHeader" ) ).toUpper().startsWith( 'N' ); } - if ( url.hasQueryItem( "skipEmptyFields" ) ) + if ( url.hasQueryItem( QStringLiteral( "skipEmptyFields" ) ) ) { - mDiscardEmptyFields = ! url.queryItemValue( "skipEmptyFields" ).toUpper().startsWith( 'N' ); + mDiscardEmptyFields = ! url.queryItemValue( QStringLiteral( "skipEmptyFields" ) ).toUpper().startsWith( 'N' ); } - if ( url.hasQueryItem( "trimFields" ) ) + if ( url.hasQueryItem( QStringLiteral( "trimFields" ) ) ) { - mTrimFields = ! url.queryItemValue( "trimFields" ).toUpper().startsWith( 'N' ); + mTrimFields = ! url.queryItemValue( QStringLiteral( "trimFields" ) ).toUpper().startsWith( 'N' ); } - if ( url.hasQueryItem( "maxFields" ) ) + if ( url.hasQueryItem( QStringLiteral( "maxFields" ) ) ) { - mMaxFields = url.queryItemValue( "maxFields" ).toInt(); + mMaxFields = url.queryItemValue( QStringLiteral( "maxFields" ) ).toInt(); } QgsDebugMsg( "Delimited text file is: " + mFileName ); @@ -242,15 +242,15 @@ bool QgsDelimitedTextFile::setFromUrl( const QUrl &url ) QgsDebugMsg( "Trim fields: " + QString( mTrimFields ? "Yes" : "No" ) ); // Support for previous version of plain characters - if ( type == "csv" || type == "plain" ) + if ( type == QLatin1String( "csv" ) || type == QLatin1String( "plain" ) ) { setTypeCSV( delimiter, quote, escape ); } - else if ( type == "whitespace" ) + else if ( type == QLatin1String( "whitespace" ) ) { setTypeWhitespace(); } - else if ( type == "regexp" ) + else if ( type == QLatin1String( "regexp" ) ) { setTypeRegexp( delimiter ); } @@ -264,46 +264,46 @@ bool QgsDelimitedTextFile::setFromUrl( const QUrl &url ) QUrl QgsDelimitedTextFile::url() { QUrl url = QUrl::fromLocalFile( mFileName ); - if ( mEncoding != "UTF-8" ) + if ( mEncoding != QLatin1String( "UTF-8" ) ) { - url.addQueryItem( "encoding", mEncoding ); + url.addQueryItem( QStringLiteral( "encoding" ), mEncoding ); } if ( mUseWatcher ) { - url.addQueryItem( "watchFile", "yes" ); + url.addQueryItem( QStringLiteral( "watchFile" ), QStringLiteral( "yes" ) ); } - url.addQueryItem( "type", type() ); + url.addQueryItem( QStringLiteral( "type" ), type() ); if ( mType == DelimTypeRegexp ) { - url.addQueryItem( "delimiter", mDelimRegexp.pattern() ); + url.addQueryItem( QStringLiteral( "delimiter" ), mDelimRegexp.pattern() ); } if ( mType == DelimTypeCSV ) { - if ( mDelimChars != "," ) url.addQueryItem( "delimiter", encodeChars( mDelimChars ) ); - if ( mQuoteChar != "\"" ) url.addQueryItem( "quote", encodeChars( mQuoteChar ) ); - if ( mEscapeChar != "\"" ) url.addQueryItem( "escape", encodeChars( mEscapeChar ) ); + if ( mDelimChars != QLatin1String( "," ) ) url.addQueryItem( QStringLiteral( "delimiter" ), encodeChars( mDelimChars ) ); + if ( mQuoteChar != QLatin1String( "\"" ) ) url.addQueryItem( QStringLiteral( "quote" ), encodeChars( mQuoteChar ) ); + if ( mEscapeChar != QLatin1String( "\"" ) ) url.addQueryItem( QStringLiteral( "escape" ), encodeChars( mEscapeChar ) ); } if ( mSkipLines > 0 ) { - url.addQueryItem( "skipLines", QString::number( mSkipLines ) ); + url.addQueryItem( QStringLiteral( "skipLines" ), QString::number( mSkipLines ) ); } if ( ! mUseHeader ) { - url.addQueryItem( "useHeader", "No" ); + url.addQueryItem( QStringLiteral( "useHeader" ), QStringLiteral( "No" ) ); } if ( mTrimFields ) { - url.addQueryItem( "trimFields", "Yes" ); + url.addQueryItem( QStringLiteral( "trimFields" ), QStringLiteral( "Yes" ) ); } if ( mDiscardEmptyFields && mType != DelimTypeWhitespace ) { - url.addQueryItem( "skipEmptyFields", "Yes" ); + url.addQueryItem( QStringLiteral( "skipEmptyFields" ), QStringLiteral( "Yes" ) ); } if ( mMaxFields > 0 ) { - url.addQueryItem( "maxFields", QString::number( mMaxFields ) ); + url.addQueryItem( QStringLiteral( "maxFields" ), QString::number( mMaxFields ) ); } return url; } @@ -328,15 +328,15 @@ void QgsDelimitedTextFile::setUseWatcher( bool useWatcher ) QString QgsDelimitedTextFile::type() { - if ( mType == DelimTypeWhitespace ) return QString( "whitespace" ); - if ( mType == DelimTypeCSV ) return QString( "csv" ); - if ( mType == DelimTypeRegexp ) return QString( "regexp" ); - return QString( "csv" ); + if ( mType == DelimTypeWhitespace ) return QStringLiteral( "whitespace" ); + if ( mType == DelimTypeCSV ) return QStringLiteral( "csv" ); + if ( mType == DelimTypeRegexp ) return QStringLiteral( "regexp" ); + return QStringLiteral( "csv" ); } void QgsDelimitedTextFile::setTypeWhitespace() { - setTypeRegexp( "\\s+" ); + setTypeRegexp( QStringLiteral( "\\s+" ) ); mDiscardEmptyFields = true; mType = DelimTypeWhitespace; } @@ -362,13 +362,13 @@ void QgsDelimitedTextFile::setTypeRegexp( const QString& regexp ) QString QgsDelimitedTextFile::decodeChars( QString chars ) { - chars = chars.replace( "\\t", "\t" ); + chars = chars.replace( QLatin1String( "\\t" ), QLatin1String( "\t" ) ); return chars; } QString QgsDelimitedTextFile::encodeChars( QString chars ) { - chars = chars.replace( '\t', "\\t" ); + chars = chars.replace( '\t', QLatin1String( "\\t" ) ); return chars; } diff --git a/src/providers/delimitedtext/qgsdelimitedtextfile.h b/src/providers/delimitedtext/qgsdelimitedtextfile.h index 670d825726ad..5706b579b0e3 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfile.h +++ b/src/providers/delimitedtext/qgsdelimitedtextfile.h @@ -147,7 +147,7 @@ class QgsDelimitedTextFile : public QObject * @param escape The escape character used to escape quote or delim * characters. */ - void setTypeCSV( const QString& delim = QString( "," ), const QString& quote = QString( "\"" ), const QString& escape = QString( "\"" ) ); + void setTypeCSV( const QString& delim = QStringLiteral( "," ), const QString& quote = QStringLiteral( "\"" ), const QString& escape = QStringLiteral( "\"" ) ); /** Set the number of header lines to skip * @param skiplines The maximum lines to skip diff --git a/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp b/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp index ed3714aeecb5..7a16be39aaef 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp +++ b/src/providers/delimitedtext/qgsdelimitedtextprovider.cpp @@ -45,8 +45,8 @@ #include "qgsdelimitedtextfeatureiterator.h" #include "qgsdelimitedtextfile.h" -static const QString TEXT_PROVIDER_KEY = "delimitedtext"; -static const QString TEXT_PROVIDER_DESCRIPTION = "Delimited text data provider"; +static const QString TEXT_PROVIDER_KEY = QStringLiteral( "delimitedtext" ); +static const QString TEXT_PROVIDER_DESCRIPTION = QStringLiteral( "Delimited text data provider" ); // If more than this fraction of records are not in a subset then use an index to // iterate over records rather than simple iterator and filter. @@ -68,7 +68,7 @@ QgsDelimitedTextProvider::QgsDelimitedTextProvider( const QString& uri ) , mWktFieldIndex( -1 ) , mWktHasPrefix( false ) , mXyDms( false ) - , mSubsetString( "" ) + , mSubsetString( QLatin1String( "" ) ) , mSubsetExpression( nullptr ) , mBuildSubsetIndex( true ) , mUseSubsetIndex( false ) @@ -84,10 +84,10 @@ QgsDelimitedTextProvider::QgsDelimitedTextProvider( const QString& uri ) // Add supported types to enable creating expression fields in field calculator setNativeTypes( QList< NativeType >() - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 0, 10 ) - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64 bit)" ), "int8", QVariant::LongLong ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double precision", QVariant::Double, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 10 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64 bit)" ), QStringLiteral( "int8" ), QVariant::LongLong ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 ) ); QgsDebugMsg( "Delimited text file uri is " + uri ); @@ -98,35 +98,35 @@ QgsDelimitedTextProvider::QgsDelimitedTextProvider( const QString& uri ) QString subset; - if ( url.hasQueryItem( "geomType" ) ) + if ( url.hasQueryItem( QStringLiteral( "geomType" ) ) ) { - QString gtype = url.queryItemValue( "geomType" ).toLower(); - if ( gtype == "point" ) mGeometryType = QgsWkbTypes::PointGeometry; - else if ( gtype == "line" ) mGeometryType = QgsWkbTypes::LineGeometry; - else if ( gtype == "polygon" ) mGeometryType = QgsWkbTypes::PolygonGeometry; - else if ( gtype == "none " ) mGeometryType = QgsWkbTypes::NullGeometry; + QString gtype = url.queryItemValue( QStringLiteral( "geomType" ) ).toLower(); + if ( gtype == QLatin1String( "point" ) ) mGeometryType = QgsWkbTypes::PointGeometry; + else if ( gtype == QLatin1String( "line" ) ) mGeometryType = QgsWkbTypes::LineGeometry; + else if ( gtype == QLatin1String( "polygon" ) ) mGeometryType = QgsWkbTypes::PolygonGeometry; + else if ( gtype == QLatin1String( "none " ) ) mGeometryType = QgsWkbTypes::NullGeometry; } if ( mGeometryType != QgsWkbTypes::NullGeometry ) { - if ( url.hasQueryItem( "wktField" ) ) + if ( url.hasQueryItem( QStringLiteral( "wktField" ) ) ) { - mWktFieldName = url.queryItemValue( "wktField" ); + mWktFieldName = url.queryItemValue( QStringLiteral( "wktField" ) ); mGeomRep = GeomAsWkt; QgsDebugMsg( "wktField is: " + mWktFieldName ); } - else if ( url.hasQueryItem( "xField" ) && url.hasQueryItem( "yField" ) ) + else if ( url.hasQueryItem( QStringLiteral( "xField" ) ) && url.hasQueryItem( QStringLiteral( "yField" ) ) ) { mGeomRep = GeomAsXy; mGeometryType = QgsWkbTypes::PointGeometry; - mXFieldName = url.queryItemValue( "xField" ); - mYFieldName = url.queryItemValue( "yField" ); + mXFieldName = url.queryItemValue( QStringLiteral( "xField" ) ); + mYFieldName = url.queryItemValue( QStringLiteral( "yField" ) ); QgsDebugMsg( "xField is: " + mXFieldName ); QgsDebugMsg( "yField is: " + mYFieldName ); - if ( url.hasQueryItem( "xyDms" ) ) + if ( url.hasQueryItem( QStringLiteral( "xyDms" ) ) ) { - mXyDms = ! url.queryItemValue( "xyDms" ).toLower().startsWith( 'n' ); + mXyDms = ! url.queryItemValue( QStringLiteral( "xyDms" ) ).toLower().startsWith( 'n' ); } } else @@ -135,30 +135,30 @@ QgsDelimitedTextProvider::QgsDelimitedTextProvider( const QString& uri ) } } - if ( url.hasQueryItem( "decimalPoint" ) ) - mDecimalPoint = url.queryItemValue( "decimalPoint" ); + if ( url.hasQueryItem( QStringLiteral( "decimalPoint" ) ) ) + mDecimalPoint = url.queryItemValue( QStringLiteral( "decimalPoint" ) ); - if ( url.hasQueryItem( "crs" ) ) - mCrs.createFromString( url.queryItemValue( "crs" ) ); + if ( url.hasQueryItem( QStringLiteral( "crs" ) ) ) + mCrs.createFromString( url.queryItemValue( QStringLiteral( "crs" ) ) ); - if ( url.hasQueryItem( "subsetIndex" ) ) + if ( url.hasQueryItem( QStringLiteral( "subsetIndex" ) ) ) { - mBuildSubsetIndex = ! url.queryItemValue( "subsetIndex" ).toLower().startsWith( 'n' ); + mBuildSubsetIndex = ! url.queryItemValue( QStringLiteral( "subsetIndex" ) ).toLower().startsWith( 'n' ); } - if ( url.hasQueryItem( "spatialIndex" ) ) + if ( url.hasQueryItem( QStringLiteral( "spatialIndex" ) ) ) { - mBuildSpatialIndex = ! url.queryItemValue( "spatialIndex" ).toLower().startsWith( 'n' ); + mBuildSpatialIndex = ! url.queryItemValue( QStringLiteral( "spatialIndex" ) ).toLower().startsWith( 'n' ); } - if ( url.hasQueryItem( "subset" ) ) + if ( url.hasQueryItem( QStringLiteral( "subset" ) ) ) { // We need to specify FullyDecoded so that %25 is decoded as % - subset = QUrlQuery( url ).queryItemValue( "subset" , QUrl::FullyDecoded ); + subset = QUrlQuery( url ).queryItemValue( QStringLiteral( "subset" ) , QUrl::FullyDecoded ); QgsDebugMsg( "subset is: " + subset ); } - if ( url.hasQueryItem( "quiet" ) ) mShowInvalidLines = false; + if ( url.hasQueryItem( QStringLiteral( "quiet" ) ) ) mShowInvalidLines = false; // Do an initial scan of the file to determine field names, types, // geometry type (for Wkt), extents, etc. Parameter value subset.isEmpty() @@ -307,7 +307,7 @@ bool QgsDelimitedTextProvider::createSpatialIndex() // rebuilt when theproject is reloaded, and rescan the file to populate the index mBuildSpatialIndex = true; - setUriParameter( "spatialIndex", "yes" ); + setUriParameter( QStringLiteral( "spatialIndex" ), QStringLiteral( "yes" ) ); rescanFile(); return true; } @@ -363,7 +363,7 @@ void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) mWktFieldIndex = mFile->fieldIndex( mWktFieldName ); if ( mWktFieldIndex < 0 ) { - messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( "Wkt", mWktFieldName ) ); + messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Wkt" ), mWktFieldName ) ); } } else if ( mGeomRep == GeomAsXy ) @@ -372,11 +372,11 @@ void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) mYFieldIndex = mFile->fieldIndex( mYFieldName ); if ( mXFieldIndex < 0 ) { - messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( "X", mWktFieldName ) ); + messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "X" ), mWktFieldName ) ); } if ( mYFieldIndex < 0 ) { - messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( "Y", mWktFieldName ) ); + messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Y" ), mWktFieldName ) ); } } if ( !messages.isEmpty() ) @@ -601,7 +601,7 @@ void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) { if ( ! mDecimalPoint.isEmpty() ) { - value.replace( mDecimalPoint, "." ); + value.replace( mDecimalPoint, QLatin1String( "." ) ); } value.toDouble( &couldBeDouble[i] ); } @@ -627,23 +627,23 @@ void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) // Add the field index lookup for the column attributeColumns.append( i ); QVariant::Type fieldType = QVariant::String; - QString typeName = "text"; + QString typeName = QStringLiteral( "text" ); if ( i < csvtTypes.size() ) { - if ( csvtTypes[i] == "integer" ) + if ( csvtTypes[i] == QLatin1String( "integer" ) ) { fieldType = QVariant::Int; - typeName = "integer"; + typeName = QStringLiteral( "integer" ); } - else if ( csvtTypes[i] == "long" || csvtTypes[i] == "longlong" || csvtTypes[i] == "int8" ) + else if ( csvtTypes[i] == QLatin1String( "long" ) || csvtTypes[i] == QLatin1String( "longlong" ) || csvtTypes[i] == QLatin1String( "int8" ) ) { fieldType = QVariant::LongLong; //QVariant doesn't support long - typeName = "longlong"; + typeName = QStringLiteral( "longlong" ); } - else if ( csvtTypes[i] == "real" || csvtTypes[i] == "double" ) + else if ( csvtTypes[i] == QLatin1String( "real" ) || csvtTypes[i] == QLatin1String( "double" ) ) { fieldType = QVariant::Double; - typeName = "double"; + typeName = QStringLiteral( "double" ); } } else if ( i < couldBeInt.size() ) @@ -651,17 +651,17 @@ void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) if ( couldBeInt[i] ) { fieldType = QVariant::Int; - typeName = "integer"; + typeName = QStringLiteral( "integer" ); } else if ( couldBeLongLong[i] ) { fieldType = QVariant::LongLong; - typeName = "longlong"; + typeName = QStringLiteral( "longlong" ); } else if ( couldBeDouble[i] ) { fieldType = QVariant::Double; - typeName = "double"; + typeName = QStringLiteral( "double" ); } } attributeFields.append( QgsField( fieldNames[i], fieldType, typeName ) ); @@ -735,7 +735,7 @@ void QgsDelimitedTextProvider::rescanFile() const mWktFieldIndex = mFile->fieldIndex( mWktFieldName ); if ( mWktFieldIndex < 0 ) { - messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( "Wkt", mWktFieldName ) ); + messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Wkt" ), mWktFieldName ) ); } } else if ( mGeomRep == GeomAsXy ) @@ -744,11 +744,11 @@ void QgsDelimitedTextProvider::rescanFile() const mYFieldIndex = mFile->fieldIndex( mYFieldName ); if ( mXFieldIndex < 0 ) { - messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( "X", mWktFieldName ) ); + messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "X" ), mWktFieldName ) ); } if ( mYFieldIndex < 0 ) { - messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( "Y", mWktFieldName ) ); + messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Y" ), mWktFieldName ) ); } } if ( !messages.isEmpty() ) @@ -826,7 +826,7 @@ QgsGeometry QgsDelimitedTextProvider::geomFromWkt( QString &sWkt, bool wktHasPre double QgsDelimitedTextProvider::dmsStringToDouble( const QString &sX, bool *xOk ) { - static QString negative( "swSW-" ); + static QString negative( QStringLiteral( "swSW-" ) ); QRegExp re( CrdDmsRegexp ); double x = 0.0; @@ -864,8 +864,8 @@ bool QgsDelimitedTextProvider::pointFromXY( QString &sX, QString &sY, QgsPoint & { if ( ! decimalPoint.isEmpty() ) { - sX.replace( decimalPoint, "." ); - sY.replace( decimalPoint, "." ); + sX.replace( decimalPoint, QLatin1String( "." ) ); + sY.replace( decimalPoint, QLatin1String( "." ) ); } bool xOk, yOk; @@ -893,7 +893,7 @@ bool QgsDelimitedTextProvider::pointFromXY( QString &sX, QString &sY, QgsPoint & QString QgsDelimitedTextProvider::storageType() const { - return "Delimited text file"; + return QStringLiteral( "Delimited text file" ); } QgsFeatureIterator QgsDelimitedTextProvider::getFeatures( const QgsFeatureRequest& request ) const @@ -936,7 +936,7 @@ void QgsDelimitedTextProvider::reportErrors( const QStringList& messages, bool s { if ( !mInvalidLines.isEmpty() || ! messages.isEmpty() ) { - QString tag( "DelimitedText" ); + QString tag( QStringLiteral( "DelimitedText" ) ); QgsMessageLog::logMessage( tr( "Errors in file %1" ).arg( mFile->fileName() ), tag ); Q_FOREACH ( const QString& message, messages ) { @@ -979,7 +979,7 @@ void QgsDelimitedTextProvider::reportErrors( const QStringList& messages, bool s bool QgsDelimitedTextProvider::setSubsetString( const QString& subset, bool updateFeatureCount ) { - QString nonNullSubset = subset.isNull() ? QString( "" ) : subset; + QString nonNullSubset = subset.isNull() ? QLatin1String( "" ) : subset; // If not changing string, then oll ok, nothing to do if ( nonNullSubset == mSubsetString ) @@ -1013,7 +1013,7 @@ bool QgsDelimitedTextProvider::setSubsetString( const QString& subset, bool upda valid = false; delete expression; expression = nullptr; - QString tag( "DelimitedText" ); + QString tag( QStringLiteral( "DelimitedText" ) ); QgsMessageLog::logMessage( tr( "Invalid subset string %1 for %2" ).arg( nonNullSubset, mFile->fileName() ), tag ); } } @@ -1057,7 +1057,7 @@ bool QgsDelimitedTextProvider::setSubsetString( const QString& subset, bool upda // Reset the subset index rescanFile(); // Encode the subset string into the data source URI. - setUriParameter( "subset", nonNullSubset ); + setUriParameter( QStringLiteral( "subset" ), nonNullSubset ); } } else diff --git a/src/providers/delimitedtext/qgsdelimitedtextsourceselect.cpp b/src/providers/delimitedtext/qgsdelimitedtextsourceselect.cpp index 39ef5e9fb88e..20bc2b0f9470 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextsourceselect.cpp +++ b/src/providers/delimitedtext/qgsdelimitedtextsourceselect.cpp @@ -38,8 +38,8 @@ QgsDelimitedTextSourceSelect::QgsDelimitedTextSourceSelect( QWidget * parent, Qt , mFile( new QgsDelimitedTextFile() ) , mExampleRowCount( 20 ) , mBadRowCount( 0 ) - , mPluginKey( "/Plugin-DelimitedText" ) - , mLastFileType( "" ) + , mPluginKey( QStringLiteral( "/Plugin-DelimitedText" ) ) + , mLastFileType( QLatin1String( "" ) ) { setupUi( this ); @@ -68,7 +68,7 @@ QgsDelimitedTextSourceSelect::QgsDelimitedTextSourceSelect( QWidget * parent, Qt cmbEncoding->clear(); cmbEncoding->addItems( QgsVectorDataProvider::availableEncodings() ); - cmbEncoding->setCurrentIndex( cmbEncoding->findText( "UTF-8" ) ); + cmbEncoding->setCurrentIndex( cmbEncoding->findText( QStringLiteral( "UTF-8" ) ) ); loadSettings(); updateFieldsAndEnable(); @@ -153,11 +153,11 @@ void QgsDelimitedTextSourceSelect::on_buttonBox_accepted() if ( cbxPointIsComma->isChecked() ) { - url.addQueryItem( "decimalPoint", "," ); + url.addQueryItem( QStringLiteral( "decimalPoint" ), QStringLiteral( "," ) ); } if ( cbxXyDms->isChecked() ) { - url.addQueryItem( "xyDms", "yes" ); + url.addQueryItem( QStringLiteral( "xyDms" ), QStringLiteral( "yes" ) ); } if ( geomTypeXY->isChecked() ) @@ -165,9 +165,9 @@ void QgsDelimitedTextSourceSelect::on_buttonBox_accepted() if ( !cmbXField->currentText().isEmpty() && !cmbYField->currentText().isEmpty() ) { QString field = cmbXField->currentText(); - url.addQueryItem( "xField", field ); + url.addQueryItem( QStringLiteral( "xField" ), field ); field = cmbYField->currentText(); - url.addQueryItem( "yField", field ); + url.addQueryItem( QStringLiteral( "yField" ), field ); } } else if ( geomTypeWKT->isChecked() ) @@ -175,21 +175,21 @@ void QgsDelimitedTextSourceSelect::on_buttonBox_accepted() if ( ! cmbWktField->currentText().isEmpty() ) { QString field = cmbWktField->currentText(); - url.addQueryItem( "wktField", field ); + url.addQueryItem( QStringLiteral( "wktField" ), field ); } if ( cmbGeometryType->currentIndex() > 0 ) { - url.addQueryItem( "geomType", cmbGeometryType->currentText() ); + url.addQueryItem( QStringLiteral( "geomType" ), cmbGeometryType->currentText() ); } } else { - url.addQueryItem( "geomType", "none" ); + url.addQueryItem( QStringLiteral( "geomType" ), QStringLiteral( "none" ) ); } - if ( ! geomTypeNone->isChecked() ) url.addQueryItem( "spatialIndex", cbxSpatialIndex->isChecked() ? "yes" : "no" ); - url.addQueryItem( "subsetIndex", cbxSubsetIndex->isChecked() ? "yes" : "no" ); - url.addQueryItem( "watchFile", cbxWatchFile->isChecked() ? "yes" : "no" ); + if ( ! geomTypeNone->isChecked() ) url.addQueryItem( QStringLiteral( "spatialIndex" ), cbxSpatialIndex->isChecked() ? "yes" : "no" ); + url.addQueryItem( QStringLiteral( "subsetIndex" ), cbxSubsetIndex->isChecked() ? "yes" : "no" ); + url.addQueryItem( QStringLiteral( "watchFile" ), cbxWatchFile->isChecked() ? "yes" : "no" ); // store the settings saveSettings(); @@ -197,7 +197,7 @@ void QgsDelimitedTextSourceSelect::on_buttonBox_accepted() // add the layer to the map - emit addVectorLayer( QString::fromAscii( url.toEncoded() ), txtLayerName->text(), "delimitedtext" ); + emit addVectorLayer( QString::fromAscii( url.toEncoded() ), txtLayerName->text(), QStringLiteral( "delimitedtext" ) ); accept(); } @@ -209,7 +209,7 @@ void QgsDelimitedTextSourceSelect::on_buttonBox_rejected() QString QgsDelimitedTextSourceSelect::selectedChars() { - QString chars = ""; + QString chars = QLatin1String( "" ); if ( cbxDelimComma->isChecked() ) chars.append( ',' ); if ( cbxDelimSpace->isChecked() ) @@ -248,15 +248,15 @@ void QgsDelimitedTextSourceSelect::loadSettings( const QString& subkey, bool loa // and how to use the delimiter QString delimiterType = settings.value( key + "/delimiterType", "" ).toString(); - if ( delimiterType == "chars" ) + if ( delimiterType == QLatin1String( "chars" ) ) { delimiterChars->setChecked( true ); } - else if ( delimiterType == "regexp" ) + else if ( delimiterType == QLatin1String( "regexp" ) ) { delimiterRegexp->setChecked( true ); } - else if ( delimiterType == "csv" ) + else if ( delimiterType == QLatin1String( "csv" ) ) { delimiterCSV->setChecked( true ); } @@ -285,8 +285,8 @@ void QgsDelimitedTextSourceSelect::loadSettings( const QString& subkey, bool loa if ( loadGeomSettings ) { QString geomColumnType = settings.value( key + "/geomColumnType", "xy" ).toString(); - if ( geomColumnType == "xy" ) geomTypeXY->setChecked( true ); - else if ( geomColumnType == "wkt" ) geomTypeWKT->setChecked( true ); + if ( geomColumnType == QLatin1String( "xy" ) ) geomTypeXY->setChecked( true ); + else if ( geomColumnType == QLatin1String( "wkt" ) ) geomTypeWKT->setChecked( true ); else geomTypeNone->setChecked( true ); cbxXyDms->setChecked( settings.value( key + "/xyDms", "false" ) == "true" ); swGeomType->setCurrentIndex( bgGeomType->checkedId() ); @@ -322,9 +322,9 @@ void QgsDelimitedTextSourceSelect::saveSettings( const QString& subkey, bool sav settings.setValue( key + "/watchFile", cbxWatchFile->isChecked() ? "true" : "false" ); if ( saveGeomSettings ) { - QString geomColumnType = "none"; - if ( geomTypeXY->isChecked() ) geomColumnType = "xy"; - if ( geomTypeWKT->isChecked() ) geomColumnType = "wkt"; + QString geomColumnType = QStringLiteral( "none" ); + if ( geomTypeXY->isChecked() ) geomColumnType = QStringLiteral( "xy" ); + if ( geomTypeWKT->isChecked() ) geomColumnType = QStringLiteral( "wkt" ); settings.setValue( key + "/geomColumnType", geomColumnType ); settings.setValue( key + "/xyDms", cbxXyDms->isChecked() ? "true" : "false" ); } @@ -443,7 +443,7 @@ void QgsDelimitedTextSourceSelect::updateFieldLists() for ( int i = 0; i < tblSample->columnCount(); i++ ) { - QString value = i < nv ? values[i] : ""; + QString value = i < nv ? values[i] : QLatin1String( "" ); if ( value.length() > MAX_SAMPLE_LENGTH ) value = value.mid( 0, MAX_SAMPLE_LENGTH ) + "..."; QTableWidgetItem *item = new QTableWidgetItem( value ); tblSample->setItem( counter - 1, i, item ); @@ -524,11 +524,11 @@ void QgsDelimitedTextSourceSelect::updateFieldLists() // Now try setting optional X,Y fields - will only reset the fields if // not already set. - trySetXYField( fieldList, isValidCoordinate, "longitude", "latitude" ); - trySetXYField( fieldList, isValidCoordinate, "lon", "lat" ); - trySetXYField( fieldList, isValidCoordinate, "east", "north" ); - trySetXYField( fieldList, isValidCoordinate, "x", "y" ); - trySetXYField( fieldList, isValidCoordinate, "e", "n" ); + trySetXYField( fieldList, isValidCoordinate, QStringLiteral( "longitude" ), QStringLiteral( "latitude" ) ); + trySetXYField( fieldList, isValidCoordinate, QStringLiteral( "lon" ), QStringLiteral( "lat" ) ); + trySetXYField( fieldList, isValidCoordinate, QStringLiteral( "east" ), QStringLiteral( "north" ) ); + trySetXYField( fieldList, isValidCoordinate, QStringLiteral( "x" ), QStringLiteral( "y" ) ); + trySetXYField( fieldList, isValidCoordinate, QStringLiteral( "e" ), QStringLiteral( "n" ) ); // And also a WKT field if there is one @@ -663,7 +663,7 @@ bool QgsDelimitedTextSourceSelect::validate() { // Check that input data is valid - provide a status message if not.. - QString message( "" ); + QString message( QLatin1String( "" ) ); bool enabled = false; if ( txtFilePath->text().trimmed().isEmpty() ) diff --git a/src/providers/gdal/qgsgdaldataitems.cpp b/src/providers/gdal/qgsgdaldataitems.cpp index aa881abedbb1..a6601e616ae7 100644 --- a/src/providers/gdal/qgsgdaldataitems.cpp +++ b/src/providers/gdal/qgsgdaldataitems.cpp @@ -26,7 +26,7 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString QgsGdalLayerItem::QgsGdalLayerItem( QgsDataItem* parent, QString name, QString path, QString uri, QStringList *theSublayers ) - : QgsLayerItem( parent, name, path, uri, QgsLayerItem::Raster, "gdal" ) + : QgsLayerItem( parent, name, path, uri, QgsLayerItem::Raster, QStringLiteral( "gdal" ) ) { mToolTip = uri; // save sublayers for subsequent access @@ -87,8 +87,8 @@ QVector<QgsDataItem*> QgsGdalLayerItem::createChildren() QString name = sublayers[i]; // if netcdf/hdf use all text after filename // for hdf4 it would be best to get description, because the subdataset_index is not very practical - if ( name.startsWith( "netcdf", Qt::CaseInsensitive ) || - name.startsWith( "hdf", Qt::CaseInsensitive ) ) + if ( name.startsWith( QLatin1String( "netcdf" ), Qt::CaseInsensitive ) || + name.startsWith( QLatin1String( "hdf" ), Qt::CaseInsensitive ) ) name = name.mid( name.indexOf( mPath ) + mPath.length() + 1 ); else { @@ -114,7 +114,7 @@ QVector<QgsDataItem*> QgsGdalLayerItem::createChildren() QString QgsGdalLayerItem::layerName() const { QFileInfo info( name() ); - if ( info.suffix() == "gz" ) + if ( info.suffix() == QLatin1String( "gz" ) ) return info.baseName(); else return info.completeBaseName(); @@ -141,23 +141,23 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) // zip settings + info QSettings settings; - QString scanZipSetting = settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString(); + QString scanZipSetting = settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString(); QString vsiPrefix = QgsZipItem::vsiPrefix( thePath ); - bool is_vsizip = ( vsiPrefix == "/vsizip/" ); - bool is_vsigzip = ( vsiPrefix == "/vsigzip/" ); - bool is_vsitar = ( vsiPrefix == "/vsitar/" ); + bool is_vsizip = ( vsiPrefix == QLatin1String( "/vsizip/" ) ); + bool is_vsigzip = ( vsiPrefix == QLatin1String( "/vsigzip/" ) ); + bool is_vsitar = ( vsiPrefix == QLatin1String( "/vsitar/" ) ); // should we check ext. only? // check if scanItemsInBrowser2 == extension or parent dir in scanItemsFastScanUris // TODO - do this in dir item, but this requires a way to inform which extensions are supported by provider // maybe a callback function or in the provider registry? bool scanExtSetting = false; - if (( settings.value( "/qgis/scanItemsInBrowser2", - "extension" ).toString() == "extension" ) || - ( parentItem && settings.value( "/qgis/scanItemsFastScanUris", + if (( settings.value( QStringLiteral( "/qgis/scanItemsInBrowser2" ), + "extension" ).toString() == QLatin1String( "extension" ) ) || + ( parentItem && settings.value( QStringLiteral( "/qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( parentItem->path() ) ) || (( is_vsizip || is_vsitar ) && parentItem && parentItem->parent() && - settings.value( "/qgis/scanItemsFastScanUris", + settings.value( QStringLiteral( "/qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( parentItem->parent()->path() ) ) ) { scanExtSetting = true; @@ -177,7 +177,7 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) + " suffix= " + suffix + " vsiPrefix= " + vsiPrefix, 3 ); // allow only normal files or VSIFILE items to continue - if ( !info.isFile() && vsiPrefix == "" ) + if ( !info.isFile() && vsiPrefix == QLatin1String( "" ) ) return nullptr; // get supported extensions @@ -197,14 +197,14 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) // skip *.aux.xml files (GDAL auxilary metadata files), // *.shp.xml files (ESRI metadata) and *.tif.xml files (TIFF metadata) // unless that extension is in the list (*.xml might be though) - if ( thePath.endsWith( ".aux.xml", Qt::CaseInsensitive ) && - !extensions.contains( "aux.xml" ) ) + if ( thePath.endsWith( QLatin1String( ".aux.xml" ), Qt::CaseInsensitive ) && + !extensions.contains( QStringLiteral( "aux.xml" ) ) ) return nullptr; - if ( thePath.endsWith( ".shp.xml", Qt::CaseInsensitive ) && - !extensions.contains( "shp.xml" ) ) + if ( thePath.endsWith( QLatin1String( ".shp.xml" ), Qt::CaseInsensitive ) && + !extensions.contains( QStringLiteral( "shp.xml" ) ) ) return nullptr; - if ( thePath.endsWith( ".tif.xml", Qt::CaseInsensitive ) && - !extensions.contains( "tif.xml" ) ) + if ( thePath.endsWith( QLatin1String( ".tif.xml" ), Qt::CaseInsensitive ) && + !extensions.contains( QStringLiteral( "tif.xml" ) ) ) return nullptr; // Filter files by extension @@ -225,7 +225,7 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) } // fix vsifile path and name - if ( vsiPrefix != "" ) + if ( vsiPrefix != QLatin1String( "" ) ) { // add vsiPrefix to path if needed if ( !thePath.startsWith( vsiPrefix ) ) @@ -245,10 +245,10 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) // scanExtSetting // or zipfile and scan zip == "Basic scan" if ( scanExtSetting || - (( is_vsizip || is_vsitar ) && scanZipSetting == "basic" ) ) + (( is_vsizip || is_vsitar ) && scanZipSetting == QLatin1String( "basic" ) ) ) { // if this is a VRT file make sure it is raster VRT to avoid duplicates - if ( suffix == "vrt" ) + if ( suffix == QLatin1String( "vrt" ) ) { // do not print errors, but write to debug CPLPushErrorHandler( CPLQuietErrorHandler ); diff --git a/src/providers/gdal/qgsgdalprovider.cpp b/src/providers/gdal/qgsgdalprovider.cpp index 056588d617fd..c5c83fbf58c6 100644 --- a/src/providers/gdal/qgsgdalprovider.cpp +++ b/src/providers/gdal/qgsgdalprovider.cpp @@ -55,8 +55,8 @@ #define ERRMSG(message) QGS_ERROR_MESSAGE(message,"GDAL provider") #define ERR(message) QgsError(message,"GDAL provider") -static QString PROVIDER_KEY = "gdal"; -static QString PROVIDER_DESCRIPTION = "GDAL provider"; +static QString PROVIDER_KEY = QStringLiteral( "gdal" ); +static QString PROVIDER_DESCRIPTION = QStringLiteral( "GDAL provider" ); struct QgsGdalProgress { @@ -155,7 +155,7 @@ QgsGdalProvider::QgsGdalProvider( const QString &uri, bool update ) // Try to open using VSIFileHandler (see qgsogrprovider.cpp) QString vsiPrefix = QgsZipItem::vsiPrefix( uri ); - if ( vsiPrefix != "" ) + if ( vsiPrefix != QLatin1String( "" ) ) { if ( !uri.startsWith( vsiPrefix ) ) setDataSourceUri( vsiPrefix + uri ); @@ -169,7 +169,7 @@ QgsGdalProvider::QgsGdalProvider( const QString &uri, bool update ) if ( !mGdalBaseDataset ) { - QString msg = QString( "Cannot open GDAL dataset %1:\n%2" ).arg( dataSourceUri(), QString::fromUtf8( CPLGetLastErrorMsg() ) ); + QString msg = QStringLiteral( "Cannot open GDAL dataset %1:\n%2" ).arg( dataSourceUri(), QString::fromUtf8( CPLGetLastErrorMsg() ) ); appendError( ERRMSG( msg ) ); return; } @@ -194,7 +194,7 @@ bool QgsGdalProvider::crsFromWkt( const char *wkt ) { if ( OSRAutoIdentifyEPSG( hCRS ) == OGRERR_NONE ) { - QString authid = QString( "%1:%2" ) + QString authid = QStringLiteral( "%1:%2" ) .arg( OSRGetAuthorityName( hCRS, nullptr ), OSRGetAuthorityCode( hCRS, nullptr ) ); QgsDebugMsg( "authid recognized as " + authid ); @@ -256,17 +256,17 @@ QString QgsGdalProvider::metadata() { QString myMetadata; myMetadata += QString( GDALGetDescription( GDALGetDatasetDriver( mGdalDataset ) ) ); - myMetadata += "<br>"; + myMetadata += QLatin1String( "<br>" ); myMetadata += QString( GDALGetMetadataItem( GDALGetDatasetDriver( mGdalDataset ), GDAL_DMD_LONGNAME, nullptr ) ); // my added code (MColetti) - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Dataset Description" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += FROM8( GDALGetDescription( mGdalDataset ) ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); char ** GDALmetadata = GDALGetMetadata( mGdalDataset, nullptr ); @@ -313,15 +313,15 @@ QString QgsGdalProvider::metadata() // end my added code - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Dimensions" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += tr( "X: %1 Y: %2 Bands: %3" ) .arg( GDALGetRasterXSize( mGdalDataset ) ) .arg( GDALGetRasterYSize( mGdalDataset ) ) .arg( GDALGetRasterCount( mGdalDataset ) ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); //just use the first band if ( GDALGetRasterCount( mGdalDataset ) > 0 ) @@ -350,23 +350,23 @@ QString QgsGdalProvider::metadata() } else { - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Origin" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += QString::number( mGeoTransform[0] ); myMetadata += ','; myMetadata += QString::number( mGeoTransform[3] ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); - myMetadata += "<p class=\"glossy\">"; + myMetadata += QLatin1String( "<p class=\"glossy\">" ); myMetadata += tr( "Pixel Size" ); - myMetadata += "</p>\n"; - myMetadata += "<p>"; + myMetadata += QLatin1String( "</p>\n" ); + myMetadata += QLatin1String( "<p>" ); myMetadata += QString::number( mGeoTransform[1] ); myMetadata += ','; myMetadata += QString::number( mGeoTransform[5] ); - myMetadata += "</p>\n"; + myMetadata += QLatin1String( "</p>\n" ); } return myMetadata; @@ -917,13 +917,13 @@ QString QgsGdalProvider::generateBandName( int theBandNumber ) const i != metadata.end(); ++i ) { QString val( *i ); - if ( !val.startsWith( "NETCDF_DIM_EXTRA" ) && !val.contains( "#units=" ) ) + if ( !val.startsWith( QLatin1String( "NETCDF_DIM_EXTRA" ) ) && !val.contains( QLatin1String( "#units=" ) ) ) continue; QStringList values = val.split( '=' ); val = values.at( 1 ); - if ( values.at( 0 ) == "NETCDF_DIM_EXTRA" ) + if ( values.at( 0 ) == QLatin1String( "NETCDF_DIM_EXTRA" ) ) { - dimExtraValues = val.replace( QString( "{" ), QString() ).replace( QString( "}" ), QString() ).split( ',' ); + dimExtraValues = val.replace( QStringLiteral( "{" ), QString() ).replace( QStringLiteral( "}" ), QString() ).split( ',' ); //http://qt-project.org/doc/qt-4.8/qregexp.html#capturedTexts } else @@ -944,7 +944,7 @@ QString QgsGdalProvider::generateBandName( int theBandNumber ) const i != metadata.end(); ++i ) { QString val( *i ); - if ( !val.startsWith( "NETCDF_DIM_" ) ) + if ( !val.startsWith( QLatin1String( "NETCDF_DIM_" ) ) ) continue; QStringList values = val.split( '=' ); for ( QStringList::const_iterator j = dimExtraValues.begin(); @@ -953,7 +953,7 @@ QString QgsGdalProvider::generateBandName( int theBandNumber ) const QString dim = ( *j ); if ( values.at( 0 ) != "NETCDF_DIM_" + dim ) continue; - if ( unitsMap.contains( dim ) && unitsMap[ dim ] != "" && unitsMap[ dim ] != "none" ) + if ( unitsMap.contains( dim ) && unitsMap[ dim ] != QLatin1String( "" ) && unitsMap[ dim ] != QLatin1String( "none" ) ) bandNameValues.append( dim + '=' + values.at( 1 ) + " (" + unitsMap[ dim ] + ')' ); else bandNameValues.append( dim + '=' + values.at( 1 ) ); @@ -962,7 +962,7 @@ QString QgsGdalProvider::generateBandName( int theBandNumber ) const } if ( !bandNameValues.isEmpty() ) - return tr( "Band" ) + QString( " %1 / %2" ) .arg( theBandNumber, 1 + ( int ) log10(( float ) bandCount() ), 10, QChar( '0' ) ).arg( bandNameValues.join( " / " ) ); + return tr( "Band" ) + QStringLiteral( " %1 / %2" ) .arg( theBandNumber, 1 + ( int ) log10(( float ) bandCount() ), 10, QChar( '0' ) ).arg( bandNameValues.join( QStringLiteral( " / " ) ) ); } } } @@ -1091,7 +1091,7 @@ int QgsGdalProvider::capabilities() const GDALDriverH myDriver = GDALGetDatasetDriver( mGdalDataset ); QString name = GDALGetDriverShortName( myDriver ); QgsDebugMsg( "driver short name = " + name ); - if ( name != "WMS" ) + if ( name != QLatin1String( "WMS" ) ) { capability |= QgsRasterDataProvider::Size; } @@ -1198,12 +1198,12 @@ bool QgsGdalProvider::isValid() const QString QgsGdalProvider::lastErrorTitle() { - return QString( "Not implemented" ); + return QStringLiteral( "Not implemented" ); } QString QgsGdalProvider::lastError() { - return QString( "Not implemented" ); + return QStringLiteral( "Not implemented" ); } QString QgsGdalProvider::name() const @@ -1234,7 +1234,7 @@ QStringList QgsGdalProvider::subLayers( GDALDatasetH dataset ) for ( int i = 0; metadata[i]; i++ ) { QString layer = QString::fromUtf8( metadata[i] ); - int pos = layer.indexOf( "_NAME=" ); + int pos = layer.indexOf( QLatin1String( "_NAME=" ) ); if ( pos >= 0 ) { subLayers << layer.mid( pos + 6 ); @@ -1536,8 +1536,8 @@ QString QgsGdalProvider::buildPyramids( const QList<QgsRasterPyramid> & theRaste if ( mGdalDataset != mGdalBaseDataset ) { - QgsLogger::warning( "Pyramid building not currently supported for 'warped virtual dataset'." ); - return "ERROR_VIRTUAL"; + QgsLogger::warning( QStringLiteral( "Pyramid building not currently supported for 'warped virtual dataset'." ) ); + return QStringLiteral( "ERROR_VIRTUAL" ); } // check if building internally @@ -1550,7 +1550,7 @@ QString QgsGdalProvider::buildPyramids( const QList<QgsRasterPyramid> & theRaste if ( !myQFile.isWritable() ) { - return "ERROR_WRITE_ACCESS"; + return QStringLiteral( "ERROR_WRITE_ACCESS" ); } // libtiff < 4.0 has a bug that prevents safe building of overviews on JPEG compressed files @@ -1563,7 +1563,7 @@ QString QgsGdalProvider::buildPyramids( const QList<QgsRasterPyramid> & theRaste QString myCompressionType = QString( GDALGetMetadataItem( mGdalDataset, "COMPRESSION", "IMAGE_STRUCTURE" ) ); if ( "JPEG" == myCompressionType ) { - return "ERROR_JPEG_COMPRESSION"; + return QStringLiteral( "ERROR_JPEG_COMPRESSION" ); } } @@ -1584,14 +1584,14 @@ QString QgsGdalProvider::buildPyramids( const QList<QgsRasterPyramid> & theRaste mGdalBaseDataset = gdalOpen( TO8F( dataSourceUri() ), GA_ReadOnly ); //Since we are not a virtual warped dataset, mGdalDataSet and mGdalBaseDataset are supposed to be the same mGdalDataset = mGdalBaseDataset; - return "ERROR_WRITE_FORMAT"; + return QStringLiteral( "ERROR_WRITE_FORMAT" ); } } } // are we using Erdas Imagine external overviews? QgsStringMap myConfigOptionsOld; - myConfigOptionsOld[ "USE_RRD" ] = CPLGetConfigOption( "USE_RRD", "NO" ); + myConfigOptionsOld[ QStringLiteral( "USE_RRD" )] = CPLGetConfigOption( "USE_RRD", "NO" ); if ( theFormat == QgsRaster::PyramidsErdas ) CPLSetConfigOption( "USE_RRD", "YES" ); else @@ -1697,7 +1697,7 @@ QString QgsGdalProvider::buildPyramids( const QList<QgsRasterPyramid> & theRaste } // TODO print exact error message - return "FAILED_NOT_SUPPORTED"; + return QStringLiteral( "FAILED_NOT_SUPPORTED" ); } else { @@ -1708,7 +1708,7 @@ QString QgsGdalProvider::buildPyramids( const QList<QgsRasterPyramid> & theRaste } catch ( CPLErr ) { - QgsLogger::warning( "Pyramid overview building failed!" ); + QgsLogger::warning( QStringLiteral( "Pyramid overview building failed!" ) ); } // restore former configOptions @@ -1988,8 +1988,8 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString char **myGdalDriverMetadata; // driver metadata strings - QString myGdalDriverLongName( "" ); // long name for the given driver - QString myGdalDriverExtension( "" ); // file name extension for given driver + QString myGdalDriverLongName( QLatin1String( "" ) ); // long name for the given driver + QString myGdalDriverExtension( QLatin1String( "" ) ); // file name extension for given driver QString myGdalDriverDescription; // QString wrapper of GDAL driver description QStringList metadataTokens; // essentially the metadata string delimited by '=' @@ -2012,7 +2012,7 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString // driver, which will be found in DMD_LONGNAME, which will have the // same form. - theFileFiltersString = ""; + theFileFiltersString = QLatin1String( "" ); QgsDebugMsg( QString( "GDAL driver count: %1" ).arg( GDALGetDriverCount() ) ); @@ -2043,7 +2043,7 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString myGdalDriverDescription = GDALGetDescription( myGdalDriver ); // QgsDebugMsg(QString("got driver string %1").arg(myGdalDriverDescription)); - myGdalDriverExtension = myGdalDriverLongName = ""; + myGdalDriverExtension = myGdalDriverLongName = QLatin1String( "" ); myGdalDriverMetadata = GDALGetMetadata( myGdalDriver, nullptr ); @@ -2085,33 +2085,33 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString if ( !( myGdalDriverExtension.isEmpty() || myGdalDriverLongName.isEmpty() ) ) { // XXX add check for SDTS; in that case we want (*CATD.DDF) - QString glob = "*." + myGdalDriverExtension.replace( '/', " *." ); + QString glob = "*." + myGdalDriverExtension.replace( '/', QLatin1String( " *." ) ); theExtensions << myGdalDriverExtension.remove( '/' ).remove( '*' ).remove( '.' ); // Add only the first JP2 driver found to the filter list (it's the one GDAL uses) - if ( myGdalDriverDescription == "JPEG2000" || - myGdalDriverDescription.startsWith( "JP2" ) ) // JP2ECW, JP2KAK, JP2MrSID + if ( myGdalDriverDescription == QLatin1String( "JPEG2000" ) || + myGdalDriverDescription.startsWith( QLatin1String( "JP2" ) ) ) // JP2ECW, JP2KAK, JP2MrSID { if ( jp2Driver ) break; // skip if already found a JP2 driver jp2Driver = myGdalDriver; // first JP2 driver found - glob += " *.j2k"; // add alternate extension - theExtensions << "j2k"; + glob += QLatin1String( " *.j2k" ); // add alternate extension + theExtensions << QStringLiteral( "j2k" ); } - else if ( myGdalDriverDescription == "GTiff" ) + else if ( myGdalDriverDescription == QLatin1String( "GTiff" ) ) { - glob += " *.tiff"; - theExtensions << "tiff"; + glob += QLatin1String( " *.tiff" ); + theExtensions << QStringLiteral( "tiff" ); } - else if ( myGdalDriverDescription == "JPEG" ) + else if ( myGdalDriverDescription == QLatin1String( "JPEG" ) ) { - glob += " *.jpeg"; - theExtensions << "jpeg"; + glob += QLatin1String( " *.jpeg" ); + theExtensions << QStringLiteral( "jpeg" ); } - else if ( myGdalDriverDescription == "VRT" ) + else if ( myGdalDriverDescription == QLatin1String( "VRT" ) ) { - glob += " *.ovr"; - theExtensions << "ovr"; + glob += QLatin1String( " *.ovr" ); + theExtensions << QStringLiteral( "ovr" ); } theFileFiltersString += createFileFilter_( myGdalDriverLongName, glob ); @@ -2139,41 +2139,41 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString // them appropriately // USGS DEMs use "*.dem" - if ( myGdalDriverDescription.startsWith( "USGSDEM" ) ) + if ( myGdalDriverDescription.startsWith( QLatin1String( "USGSDEM" ) ) ) { - theFileFiltersString += createFileFilter_( myGdalDriverLongName, "*.dem" ); - theExtensions << "dem"; + theFileFiltersString += createFileFilter_( myGdalDriverLongName, QStringLiteral( "*.dem" ) ); + theExtensions << QStringLiteral( "dem" ); } - else if ( myGdalDriverDescription.startsWith( "DTED" ) ) + else if ( myGdalDriverDescription.startsWith( QLatin1String( "DTED" ) ) ) { // DTED use "*.dt0, *.dt1, *.dt2" - QString glob = "*.dt0"; - glob += " *.dt1"; - glob += " *.dt2"; + QString glob = QStringLiteral( "*.dt0" ); + glob += QLatin1String( " *.dt1" ); + glob += QLatin1String( " *.dt2" ); theFileFiltersString += createFileFilter_( myGdalDriverLongName, glob ); - theExtensions << "dt0" << "dt1" << "dt2"; + theExtensions << QStringLiteral( "dt0" ) << QStringLiteral( "dt1" ) << QStringLiteral( "dt2" ); } - else if ( myGdalDriverDescription.startsWith( "MrSID" ) ) + else if ( myGdalDriverDescription.startsWith( QLatin1String( "MrSID" ) ) ) { // MrSID use "*.sid" - theFileFiltersString += createFileFilter_( myGdalDriverLongName, "*.sid" ); - theExtensions << "sid"; + theFileFiltersString += createFileFilter_( myGdalDriverLongName, QStringLiteral( "*.sid" ) ); + theExtensions << QStringLiteral( "sid" ); } - else if ( myGdalDriverDescription.startsWith( "EHdr" ) ) + else if ( myGdalDriverDescription.startsWith( QLatin1String( "EHdr" ) ) ) { - theFileFiltersString += createFileFilter_( myGdalDriverLongName, "*.bil" ); - theExtensions << "bil"; + theFileFiltersString += createFileFilter_( myGdalDriverLongName, QStringLiteral( "*.bil" ) ); + theExtensions << QStringLiteral( "bil" ); } - else if ( myGdalDriverDescription.startsWith( "AIG" ) ) + else if ( myGdalDriverDescription.startsWith( QLatin1String( "AIG" ) ) ) { - theFileFiltersString += createFileFilter_( myGdalDriverLongName, "hdr.adf" ); - theWildcards << "hdr.adf"; + theFileFiltersString += createFileFilter_( myGdalDriverLongName, QStringLiteral( "hdr.adf" ) ); + theWildcards << QStringLiteral( "hdr.adf" ); } - else if ( myGdalDriverDescription == "HDF4" ) + else if ( myGdalDriverDescription == QLatin1String( "HDF4" ) ) { // HDF4 extension missing in driver metadata - theFileFiltersString += createFileFilter_( myGdalDriverLongName, "*.hdf" ); - theExtensions << "hdf"; + theFileFiltersString += createFileFilter_( myGdalDriverLongName, QStringLiteral( "*.hdf" ) ); + theExtensions << QStringLiteral( "hdf" ); } else { @@ -2184,17 +2184,17 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString } // each loaded GDAL driver // sort file filters alphabetically - QStringList filters = theFileFiltersString.split( ";;", QString::SkipEmptyParts ); + QStringList filters = theFileFiltersString.split( QStringLiteral( ";;" ), QString::SkipEmptyParts ); filters.sort(); - theFileFiltersString = filters.join( ";;" ) + ";;"; + theFileFiltersString = filters.join( QStringLiteral( ";;" ) ) + ";;"; // VSIFileHandler (see qgsogrprovider.cpp) - second #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1600 QSettings settings; - if ( settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString() != "no" ) + if ( settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString() != QLatin1String( "no" ) ) { - theFileFiltersString.prepend( createFileFilter_( QObject::tr( "GDAL/OGR VSIFileHandler" ), "*.zip *.gz *.tar *.tar.gz *.tgz" ) ); - theExtensions << "zip" << "gz" << "tar" << "tar.gz" << "tgz"; + theFileFiltersString.prepend( createFileFilter_( QObject::tr( "GDAL/OGR VSIFileHandler" ), QStringLiteral( "*.zip *.gz *.tar *.tar.gz *.tgz" ) ) ); + theExtensions << QStringLiteral( "zip" ) << QStringLiteral( "gz" ) << QStringLiteral( "tar" ) << QStringLiteral( "tar.gz" ) << QStringLiteral( "tgz" ); } #endif @@ -2202,7 +2202,7 @@ void buildSupportedRasterFileFilterAndExtensions( QString & theFileFiltersString theFileFiltersString.prepend( QObject::tr( "All files" ) + " (*);;" ); // cleanup - if ( theFileFiltersString.endsWith( ";;" ) ) theFileFiltersString.chop( 2 ); + if ( theFileFiltersString.endsWith( QLatin1String( ";;" ) ) ) theFileFiltersString.chop( 2 ); QgsDebugMsg( "Raster filter list built: " + theFileFiltersString ); QgsDebugMsg( "Raster extension list built: " + theExtensions.join( " " ) ); @@ -2221,7 +2221,7 @@ QGISEXTERN bool isValidRasterFileName( QString const & theFileNameQString, QStri // Try to open using VSIFileHandler (see qgsogrprovider.cpp) // TODO suppress error messages and report in debug, like in OGR provider QString vsiPrefix = QgsZipItem::vsiPrefix( fileName ); - if ( vsiPrefix != "" ) + if ( vsiPrefix != QLatin1String( "" ) ) { if ( !fileName.startsWith( vsiPrefix ) ) fileName = vsiPrefix + fileName; @@ -2518,7 +2518,7 @@ void QgsGdalProvider::initBaseDataset() || GDALGetGCPCount( mGdalBaseDataset ) > 0 || GDALGetMetadata( mGdalBaseDataset, "RPC" ) ) { - QgsLogger::warning( "Creating Warped VRT." ); + QgsLogger::warning( QStringLiteral( "Creating Warped VRT." ) ); mGdalDataset = GDALAutoCreateWarpedVRT( mGdalBaseDataset, nullptr, nullptr, @@ -2526,7 +2526,7 @@ void QgsGdalProvider::initBaseDataset() if ( !mGdalDataset ) { - QgsLogger::warning( "Warped VRT Creation failed." ); + QgsLogger::warning( QStringLiteral( "Warped VRT Creation failed." ) ); mGdalDataset = mGdalBaseDataset; GDALReferenceDataset( mGdalDataset ); } @@ -2597,7 +2597,7 @@ void QgsGdalProvider::initBaseDataset() GDALGetMetadata( mGdalBaseDataset, "RPC" ) ) { // Warped VRT of RPC is in EPSG:4326 - mCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); + mCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); } else { @@ -2778,7 +2778,7 @@ QGISEXTERN QgsGdalProvider * create( GDALDriverH driver = GDALGetDriverByName( format.toLocal8Bit().data() ); if ( !driver ) { - QgsError error( "Cannot load GDAL driver " + format, "GDAL provider" ); + QgsError error( "Cannot load GDAL driver " + format, QStringLiteral( "GDAL provider" ) ); return new QgsGdalProvider( uri, error ); } @@ -2791,7 +2791,7 @@ QGISEXTERN QgsGdalProvider * create( CSLDestroy( papszOptions ); if ( !dataset ) { - QgsError error( QString( "Cannot create new dataset %1:\n%2" ).arg( uri, QString::fromUtf8( CPLGetLastErrorMsg() ) ), "GDAL provider" ); + QgsError error( QStringLiteral( "Cannot create new dataset %1:\n%2" ).arg( uri, QString::fromUtf8( CPLGetLastErrorMsg() ) ), QStringLiteral( "GDAL provider" ) ); QgsDebugMsg( error.summary() ); return new QgsGdalProvider( uri, error ); } @@ -2889,11 +2889,11 @@ QGISEXTERN QString helpCreationOptionsFormat( QString format ) { // first report details and help page char ** GDALmetadata = GDALGetMetadata( myGdalDriver, nullptr ); - message += "Format Details:\n"; - message += QString( " Extension: %1\n" ).arg( CSLFetchNameValue( GDALmetadata, GDAL_DMD_EXTENSION ) ); - message += QString( " Short Name: %1" ).arg( GDALGetDriverShortName( myGdalDriver ) ); - message += QString( " / Long Name: %1\n" ).arg( GDALGetDriverLongName( myGdalDriver ) ); - message += QString( " Help page: http://www.gdal.org/%1\n\n" ).arg( CSLFetchNameValue( GDALmetadata, GDAL_DMD_HELPTOPIC ) ); + message += QLatin1String( "Format Details:\n" ); + message += QStringLiteral( " Extension: %1\n" ).arg( CSLFetchNameValue( GDALmetadata, GDAL_DMD_EXTENSION ) ); + message += QStringLiteral( " Short Name: %1" ).arg( GDALGetDriverShortName( myGdalDriver ) ); + message += QStringLiteral( " / Long Name: %1\n" ).arg( GDALGetDriverLongName( myGdalDriver ) ); + message += QStringLiteral( " Help page: http://www.gdal.org/%1\n\n" ).arg( CSLFetchNameValue( GDALmetadata, GDAL_DMD_HELPTOPIC ) ); // next get creation options // need to serialize xml to get newlines, should we make the basic xml prettier? @@ -2917,7 +2917,7 @@ QGISEXTERN QString validateCreationOptionsFormat( const QStringList& createOptio { GDALDriverH myGdalDriver = GDALGetDriverByName( format.toLocal8Bit().constData() ); if ( ! myGdalDriver ) - return "invalid GDAL driver"; + return QStringLiteral( "invalid GDAL driver" ); char** papszOptions = papszFromStringList( createOptions ); // get error string? @@ -2925,7 +2925,7 @@ QGISEXTERN QString validateCreationOptionsFormat( const QStringList& createOptio CSLDestroy( papszOptions ); if ( !ok ) - return "Failed GDALValidateCreationOptions() test"; + return QStringLiteral( "Failed GDALValidateCreationOptions() test" ); return QString(); } @@ -2941,7 +2941,7 @@ QString QgsGdalProvider::validateCreationOptions( const QStringList& createOptio // next do specific validations, depending on format and dataset // only check certain destination formats QStringList formatsCheck; - formatsCheck << "gtiff"; + formatsCheck << QStringLiteral( "gtiff" ); if ( ! formatsCheck.contains( format.toLower() ) ) return QString(); @@ -2956,27 +2956,27 @@ QString QgsGdalProvider::validateCreationOptions( const QStringList& createOptio // gtiff files - validate PREDICTOR option // see gdal: frmts/gtiff/geotiff.cpp and libtiff: tif_predict.c) - if ( format.toLower() == "gtiff" && optionsMap.contains( "PREDICTOR" ) ) + if ( format.toLower() == QLatin1String( "gtiff" ) && optionsMap.contains( QStringLiteral( "PREDICTOR" ) ) ) { - QString value = optionsMap.value( "PREDICTOR" ); + QString value = optionsMap.value( QStringLiteral( "PREDICTOR" ) ); GDALDataType nDataType = ( !mGdalDataType.isEmpty() ) ? ( GDALDataType ) mGdalDataType.at( 0 ) : GDT_Unknown; int nBitsPerSample = nDataType != GDT_Unknown ? GDALGetDataTypeSize( nDataType ) : 0; QgsDebugMsg( QString( "PREDICTOR: %1 nbits: %2 type: %3" ).arg( value ).arg( nBitsPerSample ).arg(( GDALDataType ) mGdalDataType.at( 0 ) ) ); // PREDICTOR=2 only valid for 8/16/32 bits per sample // TODO check for NBITS option (see geotiff.cpp) - if ( value == "2" ) + if ( value == QLatin1String( "2" ) ) { if ( nBitsPerSample != 8 && nBitsPerSample != 16 && nBitsPerSample != 32 ) { - message = QString( "PREDICTOR=%1 only valid for 8/16/32 bits per sample (using %2)" ).arg( value ).arg( nBitsPerSample ); + message = QStringLiteral( "PREDICTOR=%1 only valid for 8/16/32 bits per sample (using %2)" ).arg( value ).arg( nBitsPerSample ); } } // PREDICTOR=3 only valid for float/double precision - else if ( value == "3" ) + else if ( value == QLatin1String( "3" ) ) { if ( nDataType != GDT_Float32 && nDataType != GDT_Float64 ) - message = "PREDICTOR=3 only valid for float/double precision"; + message = QStringLiteral( "PREDICTOR=3 only valid for float/double precision" ); } } @@ -2990,7 +2990,7 @@ QString QgsGdalProvider::validatePyramidsConfigOptions( QgsRaster::RasterPyramid if ( pyramidsFormat == QgsRaster::PyramidsErdas ) { if ( ! theConfigOptions.isEmpty() ) - return "Erdas Imagine format does not support config options"; + return QStringLiteral( "Erdas Imagine format does not support config options" ); else return QString(); } @@ -2998,18 +2998,18 @@ QString QgsGdalProvider::validatePyramidsConfigOptions( QgsRaster::RasterPyramid else if ( pyramidsFormat == QgsRaster::PyramidsInternal ) { QStringList supportedFormats; - supportedFormats << "gtiff" << "georaster" << "hfa" << "gpkg" << "rasterlite" << "nitf"; + supportedFormats << QStringLiteral( "gtiff" ) << QStringLiteral( "georaster" ) << QStringLiteral( "hfa" ) << QStringLiteral( "gpkg" ) << QStringLiteral( "rasterlite" ) << QStringLiteral( "nitf" ); if ( ! supportedFormats.contains( fileFormat.toLower() ) ) - return QString( "Internal pyramids format only supported for gtiff/georaster/gpkg/rasterlite/nitf files (using %1)" ).arg( fileFormat ); + return QStringLiteral( "Internal pyramids format only supported for gtiff/georaster/gpkg/rasterlite/nitf files (using %1)" ).arg( fileFormat ); } else { // for gtiff external pyramids, validate gtiff-specific values // PHOTOMETRIC_OVERVIEW=YCBCR requires a source raster with only 3 bands (RGB) - if ( theConfigOptions.contains( "PHOTOMETRIC_OVERVIEW=YCBCR" ) ) + if ( theConfigOptions.contains( QStringLiteral( "PHOTOMETRIC_OVERVIEW=YCBCR" ) ) ) { if ( GDALGetRasterCount( mGdalDataset ) != 3 ) - return "PHOTOMETRIC_OVERVIEW=YCBCR requires a source raster with only 3 bands (RGB)"; + return QStringLiteral( "PHOTOMETRIC_OVERVIEW=YCBCR requires a source raster with only 3 bands (RGB)" ); } } @@ -3037,16 +3037,16 @@ QGISEXTERN QList<QPair<QString, QString> > *pyramidResamplingMethods() if ( methods.isEmpty() ) { - methods.append( QPair<QString, QString>( "NEAREST", QObject::tr( "Nearest Neighbour" ) ) ); - methods.append( QPair<QString, QString>( "AVERAGE", QObject::tr( "Average" ) ) ); - methods.append( QPair<QString, QString>( "GAUSS", QObject::tr( "Gauss" ) ) ); - methods.append( QPair<QString, QString>( "CUBIC", QObject::tr( "Cubic" ) ) ); + methods.append( QPair<QString, QString>( QStringLiteral( "NEAREST" ), QObject::tr( "Nearest Neighbour" ) ) ); + methods.append( QPair<QString, QString>( QStringLiteral( "AVERAGE" ), QObject::tr( "Average" ) ) ); + methods.append( QPair<QString, QString>( QStringLiteral( "GAUSS" ), QObject::tr( "Gauss" ) ) ); + methods.append( QPair<QString, QString>( QStringLiteral( "CUBIC" ), QObject::tr( "Cubic" ) ) ); #if GDAL_VERSION_MAJOR >= 2 methods.append( QPair<QString, QString>( "CUBICSPLINE", QObject::tr( "Cubic Spline" ) ) ); methods.append( QPair<QString, QString>( "LANCZOS", QObject::tr( "Lanczos" ) ) ); #endif - methods.append( QPair<QString, QString>( "MODE", QObject::tr( "Mode" ) ) ); - methods.append( QPair<QString, QString>( "NONE", QObject::tr( "None" ) ) ); + methods.append( QPair<QString, QString>( QStringLiteral( "MODE" ), QObject::tr( "Mode" ) ) ); + methods.append( QPair<QString, QString>( QStringLiteral( "NONE" ), QObject::tr( "None" ) ) ); } return &methods; diff --git a/src/providers/gdal/qgsgdalprovider.h b/src/providers/gdal/qgsgdalprovider.h index 982bf04d19b9..3f566e2582cb 100644 --- a/src/providers/gdal/qgsgdalprovider.h +++ b/src/providers/gdal/qgsgdalprovider.h @@ -212,7 +212,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase bool theIncludeOutOfRange = false ) override; QString buildPyramids( const QList<QgsRasterPyramid> & theRasterPyramidList, - const QString & theResamplingMethod = "NEAREST", + const QString & theResamplingMethod = QStringLiteral( "NEAREST" ), QgsRaster::RasterPyramidsFormat theFormat = QgsRaster::PyramidsGTiff, const QStringList & theCreateOptions = QStringList() ) override; QList<QgsRasterPyramid> buildPyramidList( QList<int> overviewList = QList<int>() ) override; diff --git a/src/providers/gdal/qgsgdalproviderbase.cpp b/src/providers/gdal/qgsgdalproviderbase.cpp index b2136e4b438e..a1009a647109 100644 --- a/src/providers/gdal/qgsgdalproviderbase.cpp +++ b/src/providers/gdal/qgsgdalproviderbase.cpp @@ -219,7 +219,7 @@ void QgsGdalProviderBase::registerGdalDrivers() { GDALAllRegister(); QSettings mySettings; - QString myJoinedList = mySettings.value( "gdal/skipList", "" ).toString(); + QString myJoinedList = mySettings.value( QStringLiteral( "gdal/skipList" ), "" ).toString(); if ( !myJoinedList.isEmpty() ) { QStringList myList = myJoinedList.split( ' ' ); diff --git a/src/providers/gpx/gpsdata.cpp b/src/providers/gpx/gpsdata.cpp index eff1b7474d4c..ca0427fb123d 100644 --- a/src/providers/gpx/gpsdata.cpp +++ b/src/providers/gpx/gpsdata.cpp @@ -33,11 +33,11 @@ QString QgsGPSObject::xmlify( const QString& str ) { QString tmp = str; - tmp.replace( '&', "&" ); - tmp.replace( '<', "<" ); - tmp.replace( '>', ">" ); - tmp.replace( '\"', """ ); - tmp.replace( '\'', "'" ); + tmp.replace( '&', QLatin1String( "&" ) ); + tmp.replace( '<', QLatin1String( "<" ) ); + tmp.replace( '>', QLatin1String( ">" ) ); + tmp.replace( '\"', QLatin1String( """ ) ); + tmp.replace( '\'', QLatin1String( "'" ) ); return tmp; } @@ -494,7 +494,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) parseModes.top() == ParsingTrack ) { mString = &mObj->name; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -507,7 +507,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) parseModes.top() == ParsingTrack ) { mString = &mObj->cmt; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -520,7 +520,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) parseModes.top() == ParsingTrack ) { mString = &mObj->desc; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -533,7 +533,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) parseModes.top() == ParsingTrack ) { mString = &mObj->src; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -546,7 +546,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) parseModes.top() == ParsingTrack ) { mString = &mObj->url; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -559,7 +559,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) parseModes.top() == ParsingTrack ) { mString = &mObj->urlname; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -572,7 +572,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) if ( parseModes.top() == ParsingWaypoint ) { mDouble = &mWpt.ele; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingDouble ); } else @@ -583,7 +583,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) if ( parseModes.top() == ParsingWaypoint ) { mString = &mWpt.sym; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingString ); } else @@ -596,7 +596,7 @@ bool QgsGPXHandler::startElement( const XML_Char* qName, const XML_Char** attr ) if ( parseModes.top() == ParsingRoute ) { mInt = &mRte.number; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); parseModes.push( ParsingInt ); } else if ( parseModes.top() == ParsingTrack ) @@ -715,17 +715,17 @@ bool QgsGPXHandler::endElement( const std::string& qName ) else if ( parseModes.top() == ParsingDouble ) { *mDouble = QString( mCharBuffer ).toDouble(); - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); } else if ( parseModes.top() == ParsingInt ) { *mInt = QString( mCharBuffer ).toInt(); - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); } else if ( parseModes.top() == ParsingString ) { *mString = mCharBuffer; - mCharBuffer = ""; + mCharBuffer = QLatin1String( "" ); } parseModes.pop(); diff --git a/src/providers/gpx/gpsdata.h b/src/providers/gpx/gpsdata.h index b4681877a9a9..6c203659b99c 100644 --- a/src/providers/gpx/gpsdata.h +++ b/src/providers/gpx/gpsdata.h @@ -181,20 +181,20 @@ class QgsGPSData /** This function tries to add a new waypoint. An iterator to the new waypoint will be returned (it will be waypointsEnd() if the waypoint couldn't be added. */ - WaypointIterator addWaypoint( double lat, double lon, const QString& name = "", + WaypointIterator addWaypoint( double lat, double lon, const QString& name = QLatin1String( "" ), double ele = -std::numeric_limits<double>::max() ); WaypointIterator addWaypoint( const QgsWaypoint& wpt ); /** This function tries to add a new route. It returns an iterator to the new route. */ - RouteIterator addRoute( const QString& name = "" ); + RouteIterator addRoute( const QString& name = QLatin1String( "" ) ); RouteIterator addRoute( const QgsRoute& rte ); /** This function tries to add a new track. An iterator to the new track will be returned. */ - TrackIterator addTrack( const QString& name = "" ); + TrackIterator addTrack( const QString& name = QLatin1String( "" ) ); TrackIterator addTrack( const QgsTrack& trk ); diff --git a/src/providers/gpx/qgsgpxprovider.cpp b/src/providers/gpx/qgsgpxprovider.cpp index 1cffb9b8f3e5..417910b7d933 100644 --- a/src/providers/gpx/qgsgpxprovider.cpp +++ b/src/providers/gpx/qgsgpxprovider.cpp @@ -62,7 +62,7 @@ QgsGPXProvider::DataType QgsGPXProvider::attrUsed[] = const int QgsGPXProvider::attrCount = sizeof( QgsGPXProvider::attr ) / sizeof( const char* ); -const QString GPX_KEY = "gpx"; +const QString GPX_KEY = QStringLiteral( "gpx" ); const QString GPX_DESCRIPTION = QObject::tr( "GPS eXchange format provider" ); @@ -74,18 +74,18 @@ QgsGPXProvider::QgsGPXProvider( const QString& uri ) , mValid( false ) // assume that it won't work { // we always use UTF-8 - setEncoding( "utf8" ); + setEncoding( QStringLiteral( "utf8" ) ); // get the file name and the type parameter from the URI int fileNameEnd = uri.indexOf( '?' ); - if ( fileNameEnd == -1 || uri.mid( fileNameEnd + 1, 5 ) != "type=" ) + if ( fileNameEnd == -1 || uri.mid( fileNameEnd + 1, 5 ) != QLatin1String( "type=" ) ) { QgsLogger::warning( tr( "Bad URI - you need to specify the feature type." ) ); return; } QString typeStr = uri.mid( fileNameEnd + 6 ); - mFeatureType = ( typeStr == "waypoint" ? WaypointType : - ( typeStr == "route" ? RouteType : TrackType ) ); + mFeatureType = ( typeStr == QLatin1String( "waypoint" ) ? WaypointType : + ( typeStr == QLatin1String( "route" ) ? RouteType : TrackType ) ); // set up the attributes and the geometry type depending on the feature type for ( int i = 0; i < attrCount; ++i ) diff --git a/src/providers/grass/qgis.v.in.cpp b/src/providers/grass/qgis.v.in.cpp index 2ce7da34d9cb..8246e243309c 100644 --- a/src/providers/grass/qgis.v.in.cpp +++ b/src/providers/grass/qgis.v.in.cpp @@ -149,7 +149,7 @@ int main( int argc, char **argv ) // global finalName, tmpName are used by checkStream() finalName = QString( mapOption->answer ); QDateTime now = QDateTime::currentDateTime(); - tmpName = QString( "qgis_import_tmp_%1_%2" ).arg( mapOption->answer, now.toString( "yyyyMMddhhmmss" ) ); + tmpName = QStringLiteral( "qgis_import_tmp_%1_%2" ).arg( mapOption->answer, now.toString( QStringLiteral( "yyyyMMddhhmmss" ) ) ); qint32 typeQint32; stdinStream >> typeQint32; @@ -178,7 +178,7 @@ int main( int argc, char **argv ) QString key; while ( true ) { - key = "cat" + ( keyNum == 1 ? "" : QString::number( keyNum ) ); + key = "cat" + ( keyNum == 1 ? QLatin1String( "" ) : QString::number( keyNum ) ); if ( srcFields.indexFromName( key ) == -1 ) { break; diff --git a/src/providers/grass/qgsgrass.cpp b/src/providers/grass/qgsgrass.cpp index aceda83085ce..8903dff08dd9 100644 --- a/src/providers/grass/qgsgrass.cpp +++ b/src/providers/grass/qgsgrass.cpp @@ -177,28 +177,28 @@ QString QgsGrassObject::elementShort( Type type ) #if GRASS_VERSION_MAJOR < 7 return "rast"; #else - return "raster"; + return QStringLiteral( "raster" ); #endif else if ( type == Group ) - return "group"; + return QStringLiteral( "group" ); else if ( type == Vector ) #if GRASS_VERSION_MAJOR < 7 return "vect"; #else - return "vector"; + return QStringLiteral( "vector" ); #endif else if ( type == Region ) - return "region"; + return QStringLiteral( "region" ); else if ( type == Strds ) - return "strds"; + return QStringLiteral( "strds" ); else if ( type == Stvds ) - return "stvds"; + return QStringLiteral( "stvds" ); else if ( type == Str3ds ) - return "str3ds"; + return QStringLiteral( "str3ds" ); else if ( type == Stds ) - return "stds"; + return QStringLiteral( "stds" ); else - return ""; + return QLatin1String( "" ); } QString QgsGrassObject::elementName() const @@ -209,15 +209,15 @@ QString QgsGrassObject::elementName() const QString QgsGrassObject::elementName( Type type ) { if ( type == Raster ) - return "raster"; + return QStringLiteral( "raster" ); else if ( type == Group ) - return "group"; + return QStringLiteral( "group" ); else if ( type == Vector ) - return "vector"; + return QStringLiteral( "vector" ); else if ( type == Region ) - return "region"; + return QStringLiteral( "region" ); else - return ""; + return QLatin1String( "" ); } QString QgsGrassObject::dirName() const @@ -228,15 +228,15 @@ QString QgsGrassObject::dirName() const QString QgsGrassObject::dirName( Type type ) { if ( type == Raster ) - return "cellhd"; + return QStringLiteral( "cellhd" ); else if ( type == Group ) - return "group"; + return QStringLiteral( "group" ); else if ( type == Vector ) - return "vector"; + return QStringLiteral( "vector" ); else if ( type == Region ) - return "windows"; + return QStringLiteral( "windows" ); else - return ""; + return QLatin1String( "" ); } QString QgsGrassObject::toString() const @@ -263,11 +263,11 @@ QRegExp QgsGrassObject::newNameRegExp( Type type ) QRegExp rx; if ( type == QgsGrassObject::Vector ) { - rx.setPattern( "[A-Za-z_][A-Za-z0-9_]+" ); + rx.setPattern( QStringLiteral( "[A-Za-z_][A-Za-z0-9_]+" ) ); } else // location, raster, see G_legal_filename { - rx.setPattern( "[\\w_\\-][\\w_\\-.]+" ); + rx.setPattern( QStringLiteral( "[\\w_\\-][\\w_\\-.]+" ) ); } return rx; } @@ -288,7 +288,7 @@ QString QgsGrass::pathSeparator() #ifdef Q_OS_WIN return ";"; #else - return ":"; + return QStringLiteral( ":" ); #endif } @@ -405,7 +405,7 @@ bool QgsGrass::init( void ) { QgsDebugMsg( "Valid GRASS gisbase is: " + gisbase() ); // GISBASE environment variable must be set because is required by directly called GRASS functions - putEnv( "GISBASE", gisbase() ); + putEnv( QStringLiteral( "GISBASE" ), gisbase() ); // Create list of paths to GRASS modules // PATH environment variable is not used to search for modules (since 2.12) because it could @@ -456,7 +456,7 @@ bool QgsGrass::init( void ) QString pager; QStringList pagers; //pagers << "more" << "less" << "cat"; // se notes above - pagers << "cat"; + pagers << QStringLiteral( "cat" ); for ( int i = 0; i < pagers.size(); i++ ) { @@ -480,7 +480,7 @@ bool QgsGrass::init( void ) if ( pager.length() > 0 ) { - putEnv( "GRASS_PAGER", pager ); + putEnv( QStringLiteral( "GRASS_PAGER" ), pager ); } } initialized = 1; @@ -505,7 +505,7 @@ bool QgsGrass::isValidGrassBaseDir( const QString& gisbase ) { QgsDebugMsg( "isValidGrassBaseDir()" ); // GRASS currently doesn't handle paths with blanks - if ( gisbase.isEmpty() || gisbase.contains( " " ) ) + if ( gisbase.isEmpty() || gisbase.contains( QLatin1String( " " ) ) ) { return false; } @@ -565,7 +565,7 @@ QString QgsGrass::getDefaultLocation() QgsGrassObject QgsGrass::getDefaultLocationObject() { - return QgsGrassObject( defaultGisdbase, defaultLocation, "", "", QgsGrassObject::Location ); + return QgsGrassObject( defaultGisdbase, defaultLocation, QLatin1String( "" ), QLatin1String( "" ), QgsGrassObject::Location ); } QString QgsGrass::getDefaultLocationPath() @@ -584,7 +584,7 @@ QString QgsGrass::getDefaultMapset() QgsGrassObject QgsGrass::getDefaultMapsetObject() { - return QgsGrassObject( defaultGisdbase, defaultLocation, defaultMapset, "", QgsGrassObject::Mapset ); + return QgsGrassObject( defaultGisdbase, defaultLocation, defaultMapset, QLatin1String( "" ), QgsGrassObject::Mapset ); } QString QgsGrass::getDefaultMapsetPath() @@ -595,7 +595,7 @@ QString QgsGrass::getDefaultMapsetPath() void QgsGrass::setLocation( const QString& gisdbase, const QString& location ) { QgsDebugMsg( QString( "gisdbase = %1 location = %2" ).arg( gisdbase, location ) ); - setMapset( gisdbase, location, "PERMANENT" ); + setMapset( gisdbase, location, QStringLiteral( "PERMANENT" ) ); } void QgsGrass::setMapset( const QString& gisdbase, const QString& location, const QString& mapset ) @@ -665,7 +665,7 @@ void QgsGrass::addMapsetToSearchPath( const QString & mapset, QString& error ) #if GRASS_VERSION_MAJOR < 7 arguments << "addmapset=" + mapset; #else - arguments << "operation=add" << "mapset=" + mapset; + arguments << QStringLiteral( "operation=add" ) << "mapset=" + mapset; #endif try @@ -687,7 +687,7 @@ void QgsGrass::removeMapsetFromSearchPath( const QString & mapset, QString& erro #if GRASS_VERSION_MAJOR < 7 arguments << "removemapset=" + mapset; #else - arguments << "operation=remove" << "mapset=" + mapset; + arguments << QStringLiteral( "operation=remove" ) << "mapset=" + mapset; #endif try @@ -929,7 +929,7 @@ QString QgsGrass::openMapset( const QString& gisdbase, QString lockProgram( gisbase() + "/etc/lock" ); QStringList lockArguments; lockArguments << lock << QString::number( pid ); - QString lockCommand = lockProgram + " " + lockArguments.join( " " ); // for debug + QString lockCommand = lockProgram + " " + lockArguments.join( QStringLiteral( " " ) ); // for debug QgsDebugMsg( "lock command: " + lockCommand ); process.start( lockProgram, lockArguments ); @@ -939,7 +939,7 @@ QString QgsGrass::openMapset( const QString& gisdbase, } process.waitForFinished( 5000 ); - QString processResult = QString( "exitStatus=%1, exitCode=%2, errorCode=%3, error=%4 stdout=%5, stderr=%6" ) + QString processResult = QStringLiteral( "exitStatus=%1, exitCode=%2, errorCode=%3, error=%4 stdout=%5, stderr=%6" ) .arg( process.exitStatus() ).arg( process.exitCode() ) .arg( process.error() ).arg( process.errorString(), process.readAllStandardOutput().constData(), process.readAllStandardError().constData() ); @@ -1013,13 +1013,13 @@ QString QgsGrass::openMapset( const QString& gisdbase, while ( in.readLine( buf, 1000 ) != -1 ) { line = buf; - if ( line.contains( "GISDBASE:" ) || - line.contains( "LOCATION_NAME:" ) || - line.contains( "MAPSET:" ) ) + if ( line.contains( QLatin1String( "GISDBASE:" ) ) || + line.contains( QLatin1String( "LOCATION_NAME:" ) ) || + line.contains( QLatin1String( "MAPSET:" ) ) ) { continue; } - if ( line.contains( "GRASS_GUI:" ) ) + if ( line.contains( QLatin1String( "GRASS_GUI:" ) ) ) guiSet = true; stream << line; } @@ -1041,7 +1041,7 @@ QString QgsGrass::openMapset( const QString& gisdbase, // Set GISRC environment variable // Mapset must be set before Vect_close() /* _Correct_ putenv() implementation is not making copy! */ - putEnv( "GISRC", mGisrc ); + putEnv( QStringLiteral( "GISRC" ), mGisrc ); // Reinitialize GRASS G__setenv( "GISRC", mGisrc.toUtf8().data() ); @@ -1091,7 +1091,7 @@ QString QgsGrass::closeMapset() return QObject::tr( "Cannot remove mapset lock: %1" ).arg( mMapsetLock ); } #endif - mMapsetLock = ""; + mMapsetLock = QLatin1String( "" ); putenv(( char * ) "GISRC" ); @@ -1106,20 +1106,20 @@ QString QgsGrass::closeMapset() //G__setenv( "LOCATION_NAME", ( char * ) "" ); //G__setenv( "MAPSET", ( char * ) "" ); - defaultGisdbase = ""; - defaultLocation = ""; - defaultMapset = ""; + defaultGisdbase = QLatin1String( "" ); + defaultLocation = QLatin1String( "" ); + defaultMapset = QLatin1String( "" ); active = 0; // Delete temporary dir // To be sure that we don't delete '/' for example - if ( mTmp.left( 4 ) == "/tmp" ) + if ( mTmp.left( 4 ) == QLatin1String( "/tmp" ) ) { QDir dir( mTmp ); for ( unsigned int i = 0; i < dir.count(); i++ ) { - if ( dir[i] == "." || dir[i] == ".." ) + if ( dir[i] == QLatin1String( "." ) || dir[i] == QLatin1String( ".." ) ) continue; dir.remove( dir[i] ); @@ -1158,13 +1158,13 @@ void QgsGrass::saveMapset() { // Save working mapset in project file - QgsProject::instance()->writeEntry( "GRASS", "/WorkingGisdbase", + QgsProject::instance()->writeEntry( QStringLiteral( "GRASS" ), QStringLiteral( "/WorkingGisdbase" ), QgsProject::instance()->writePath( getDefaultGisdbase() ) ); - QgsProject::instance()->writeEntry( "GRASS", "/WorkingLocation", + QgsProject::instance()->writeEntry( QStringLiteral( "GRASS" ), QStringLiteral( "/WorkingLocation" ), getDefaultLocation() ); - QgsProject::instance()->writeEntry( "GRASS", "/WorkingMapset", + QgsProject::instance()->writeEntry( QStringLiteral( "GRASS" ), QStringLiteral( "/WorkingMapset" ), getDefaultMapset() ); } @@ -1393,7 +1393,7 @@ QStringList QgsGrass::vectorLayers( const QString& gisdbase, const QString& loca // TODO: add option in GUI to set listTopoLayers QSettings settings; - bool listTopoLayers = settings.value( "/GRASS/showTopoLayers", false ).toBool(); + bool listTopoLayers = settings.value( QStringLiteral( "/GRASS/showTopoLayers" ), false ).toBool(); if ( listTopoLayers ) { // add topology layers @@ -1405,11 +1405,11 @@ QStringList QgsGrass::vectorLayers( const QString& gisdbase, const QString& loca } if ( vector.typeCount( GV_LINES ) > 0 ) { - list.append( "topo_line" ); + list.append( QStringLiteral( "topo_line" ) ); } if ( vector.nodeCount() > 0 ) { - list.append( "topo_node" ); + list.append( QStringLiteral( "topo_node" ) ); } } @@ -1476,12 +1476,12 @@ QStringList QgsGrass::rasters( const QString& mapsetPath ) QStringList QgsGrass::groups( const QString& gisdbase, const QString& locationName, const QString& mapsetName ) { - return elements( gisdbase, locationName, mapsetName, "group" ); + return elements( gisdbase, locationName, mapsetName, QStringLiteral( "group" ) ); } QStringList QgsGrass::groups( const QString& mapsetPath ) { - return elements( mapsetPath, "group" ); + return elements( mapsetPath, QStringLiteral( "group" ) ); } QStringList QgsGrass::elements( const QString& gisdbase, const QString& locationName, @@ -1505,7 +1505,7 @@ QStringList QgsGrass::elements( const QString& mapsetPath, const QString& elem return list; QDir d = QDir( mapsetPath + "/" + element ); - if ( element == "vector" || element == "group" ) + if ( element == QLatin1String( "vector" ) || element == QLatin1String( "group" ) ) { d.setFilter( QDir::Dirs | QDir::NoDotAndDotDot ); } @@ -1537,7 +1537,7 @@ QStringList QgsGrass::grassObjects( const QgsGrassObject& mapsetObject, QgsGrass || type == QgsGrassObject::Str3ds || type == QgsGrassObject::Stds ) { #if GRASS_VERSION_MAJOR >= 7 - QString cmd = "t.list"; + QString cmd = QStringLiteral( "t.list" ); QStringList arguments; @@ -1552,7 +1552,7 @@ QStringList QgsGrass::grassObjects( const QgsGrassObject& mapsetObject, QgsGrass { if ( type == QgsGrassObject::Stds ) { - arguments << "type=strds,stvds,str3ds"; + arguments << QStringLiteral( "type=strds,stvds,str3ds" ); } else { @@ -1568,7 +1568,7 @@ QStringList QgsGrass::grassObjects( const QgsGrassObject& mapsetObject, QgsGrass fullName = fullName.trimmed(); if ( !fullName.isEmpty() ) { - QStringList nameMapset = fullName.split( "@" ); + QStringList nameMapset = fullName.split( QStringLiteral( "@" ) ); if ( nameMapset.value( 1 ) == mapsetObject.mapset() || nameMapset.value( 1 ).isEmpty() ) { list << nameMapset.value( 0 ); @@ -1978,11 +1978,11 @@ QString QgsGrass::findModule( QString module ) extensions << ".bat" << ".py" << ".exe"; #endif // and then try if it's a module without extension (standard on UNIX) - extensions << ""; + extensions << QLatin1String( "" ); QStringList paths; // Try first full path - paths << ""; + paths << QLatin1String( "" ); paths << QgsGrass::grassModulesPaths(); // Extensions first to prefer .bat over .exe on Windows @@ -2034,7 +2034,7 @@ QProcess *QgsGrass::startModule( const QString& gisdbase, const QString& locati throw QgsGrass::Exception( QObject::tr( "Cannot open GISRC file" ) ); } - QString error = tr( "Cannot start module" ) + "\n" + tr( "command: %1 %2" ).arg( module, arguments.join( " " ) ); + QString error = tr( "Cannot start module" ) + "\n" + tr( "command: %1 %2" ).arg( module, arguments.join( QStringLiteral( " " ) ) ); QTextStream out( &gisrcFile ); out << "GISDBASE: " << gisdbase << "\n"; @@ -2054,14 +2054,14 @@ QProcess *QgsGrass::startModule( const QString& gisdbase, const QString& locati QStringList paths = QgsGrass::grassModulesPaths(); // PYTHONPATH necessary for t.list.py // PATH necessary for g.parser called by t.list.py - paths += environment.value( "PATH" ).split( QgsGrass::pathSeparator() ); - environment.insert( "PATH", paths.join( QgsGrass::pathSeparator() ) ); - environment.insert( "PYTHONPATH", QgsGrass::getPythonPath() ); - environment.insert( "GISRC", gisrcFile.fileName() ); - environment.insert( "GRASS_MESSAGE_FORMAT", "gui" ); + paths += environment.value( QStringLiteral( "PATH" ) ).split( QgsGrass::pathSeparator() ); + environment.insert( QStringLiteral( "PATH" ), paths.join( QgsGrass::pathSeparator() ) ); + environment.insert( QStringLiteral( "PYTHONPATH" ), QgsGrass::getPythonPath() ); + environment.insert( QStringLiteral( "GISRC" ), gisrcFile.fileName() ); + environment.insert( QStringLiteral( "GRASS_MESSAGE_FORMAT" ), QStringLiteral( "gui" ) ); // Normaly modules must be run in a mapset owned by user, because each module calls G_gisinit() // which checks if G_mapset() is owned by user. The check is disabled by GRASS_SKIP_MAPSET_OWNER_CHECK. - environment.insert( "GRASS_SKIP_MAPSET_OWNER_CHECK", "1" ); + environment.insert( QStringLiteral( "GRASS_SKIP_MAPSET_OWNER_CHECK" ), QStringLiteral( "1" ) ); process->setProcessEnvironment( environment ); @@ -2092,7 +2092,7 @@ QByteArray QgsGrass::runModule( const QString& gisdbase, const QString& locatio throw QgsGrass::Exception( QObject::tr( "Cannot run module" ) + "\n" + QObject::tr( "command: %1 %2\nstdout: %3\nstderr: %4" ) - .arg( moduleName, arguments.join( " " ), + .arg( moduleName, arguments.join( QStringLiteral( " " ) ), process->readAllStandardOutput().constData(), process->readAllStandardError().constData() ) ); } @@ -2122,34 +2122,34 @@ QString QgsGrass::getInfo( const QString& info, const QString& gisdbase, switch ( type ) { case QgsGrassObject::Raster: - opt = "rast"; + opt = QStringLiteral( "rast" ); break; case QgsGrassObject::Vector: - opt = "vect"; + opt = QStringLiteral( "vect" ); break; default: QgsDebugMsg( QString( "unexpected type:%1" ).arg( type ) ); - return ""; + return QLatin1String( "" ); } arguments.append( opt + "=" + map + "@" + mapset ); } - if ( info == "query" ) + if ( info == QLatin1String( "query" ) ) { - arguments.append( QString( "coor=%1,%2" ).arg( x ).arg( y ) ); + arguments.append( QStringLiteral( "coor=%1,%2" ).arg( x ).arg( y ) ); } - if ( info == "stats" ) + if ( info == QLatin1String( "stats" ) ) { - arguments.append( QString( "north=%1" ).arg( extent.yMaximum() ) ); - arguments.append( QString( "south=%1" ).arg( extent.yMinimum() ) ); - arguments.append( QString( "east=%1" ).arg( extent.xMaximum() ) ); - arguments.append( QString( "west=%1" ).arg( extent.xMinimum() ) ); - arguments.append( QString( "rows=%1" ).arg( sampleRows ) ); - arguments.append( QString( "cols=%1" ).arg( sampleCols ) ); + arguments.append( QStringLiteral( "north=%1" ).arg( extent.yMaximum() ) ); + arguments.append( QStringLiteral( "south=%1" ).arg( extent.yMinimum() ) ); + arguments.append( QStringLiteral( "east=%1" ).arg( extent.xMaximum() ) ); + arguments.append( QStringLiteral( "west=%1" ).arg( extent.xMinimum() ) ); + arguments.append( QStringLiteral( "rows=%1" ).arg( sampleRows ) ); + arguments.append( QStringLiteral( "cols=%1" ).arg( sampleCols ) ); } //QByteArray data = runModule( gisdbase, location, mapset, cmd, arguments, timeOut ); // Run module with empty mapset so that it tries to find a mapset owned by user - QByteArray data = runModule( gisdbase, location, "", cmd, arguments, timeOut ); + QByteArray data = runModule( gisdbase, location, QLatin1String( "" ), cmd, arguments, timeOut ); QgsDebugMsg( data ); return QString( data ); } @@ -2161,7 +2161,7 @@ QgsCoordinateReferenceSystem QgsGrass::crs( const QString& gisdbase, const QStri QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem(); try { - QString wkt = getInfo( "proj", gisdbase, location ); + QString wkt = getInfo( QStringLiteral( "proj" ), gisdbase, location ); QgsDebugMsg( "wkt: " + wkt ); crs = QgsCoordinateReferenceSystem::fromWkt( wkt ); QgsDebugMsg( "crs.toWkt: " + crs.toWkt() ); @@ -2221,8 +2221,8 @@ QgsRectangle QgsGrass::extent( const QString& gisdbase, const QString& location, try { - QString str = getInfo( "window", gisdbase, location, mapset, map, type ); - QStringList list = str.split( "," ); + QString str = getInfo( QStringLiteral( "window" ), gisdbase, location, mapset, map, type ); + QStringList list = str.split( QStringLiteral( "," ) ); if ( list.size() != 4 ) { throw QgsGrass::Exception( "Cannot parse GRASS map extent: " + str ); @@ -2245,8 +2245,8 @@ void QgsGrass::size( const QString& gisdbase, const QString& location, const QSt *rows = 0; try { - QString str = getInfo( "size", gisdbase, location, mapset, map, QgsGrassObject::Raster ); - QStringList list = str.split( "," ); + QString str = getInfo( QStringLiteral( "size" ), gisdbase, location, mapset, map, QgsGrassObject::Raster ); + QStringList list = str.split( QStringLiteral( "," ) ); if ( list.size() != 2 ) { throw QgsGrass::Exception( "Cannot parse GRASS map size: " + str ); @@ -2278,7 +2278,7 @@ QHash<QString, QString> QgsGrass::info( const QString& gisdbase, const QString& { QString str = getInfo( info, gisdbase, location, mapset, map, type, 0, 0, extent, sampleRows, sampleCols, timeOut ); QgsDebugMsg( str ); - QStringList list = str.split( "\n" ); + QStringList list = str.split( QStringLiteral( "\n" ) ); for ( int i = 0; i < list.size(); i++ ) { QStringList keyVal = list[i].split( ':' ); @@ -2307,9 +2307,9 @@ QList<QgsGrass::Color> QgsGrass::colors( const QString& gisdbase, const QString& try { - QString str = getInfo( "colors", gisdbase, location, mapset, map, QgsGrassObject::Raster ); + QString str = getInfo( QStringLiteral( "colors" ), gisdbase, location, mapset, map, QgsGrassObject::Raster ); QgsDebugMsg( str ); - QStringList list = str.split( "\n" ); + QStringList list = str.split( QStringLiteral( "\n" ) ); for ( int i = 0; i < list.size(); i++ ) { QgsGrass::Color c; @@ -2338,8 +2338,8 @@ QMap<QString, QString> QgsGrass::query( const QString& gisdbase, const QString& // TODO: multiple values (more rows) try { - QString str = getInfo( "query", gisdbase, location, mapset, map, type, x, y ); - QStringList list = str.trimmed().split( ":" ); + QString str = getInfo( QStringLiteral( "query" ), gisdbase, location, mapset, map, type, x, y ); + QStringList list = str.trimmed().split( QStringLiteral( ":" ) ); if ( list.size() == 2 ) { result[list[0]] = list[1]; @@ -2405,7 +2405,7 @@ bool QgsGrass::deleteObject( const QgsGrassObject & object ) #if GRASS_VERSION_MAJOR < 7 arguments << object.elementShort() + "=" + object.name(); #else - arguments << "-f" << "type=" + object.elementShort() << "name=" + object.name(); + arguments << QStringLiteral( "-f" ) << "type=" + object.elementShort() << "name=" + object.name(); #endif try @@ -2460,13 +2460,13 @@ void QgsGrass::createTable( dbDriver *driver, const QString& tableName, const Qg { if ( !driver ) // should not happen { - throw QgsGrass::Exception( "driver is null" ); + throw QgsGrass::Exception( QStringLiteral( "driver is null" ) ); } QStringList fieldsStringList; Q_FOREACH ( const QgsField& field, fields ) { - QString name = field.name().toLower().replace( " ", "_" ); + QString name = field.name().toLower().replace( QLatin1String( " " ), QLatin1String( "_" ) ); if ( name.at( 0 ).isDigit() ) { name = "_" + name; @@ -2477,30 +2477,30 @@ void QgsGrass::createTable( dbDriver *driver, const QString& tableName, const Qg case QVariant::Int: case QVariant::LongLong: case QVariant::Bool: - typeName = "integer"; + typeName = QStringLiteral( "integer" ); break; case QVariant::Double: - typeName = "double precision"; + typeName = QStringLiteral( "double precision" ); break; // TODO: verify how is it with spatialite/dbf support for date, time, datetime, v.in.ogr is using all case QVariant::Date: - typeName = "date"; + typeName = QStringLiteral( "date" ); break; case QVariant::Time: - typeName = "time"; + typeName = QStringLiteral( "time" ); break; case QVariant::DateTime: - typeName = "datetime"; + typeName = QStringLiteral( "datetime" ); break; case QVariant::String: - typeName = QString( "varchar (%1)" ).arg( field.length() ); + typeName = QStringLiteral( "varchar (%1)" ).arg( field.length() ); break; default: - typeName = QString( "varchar (%1)" ).arg( field.length() > 0 ? field.length() : 255 ); + typeName = QStringLiteral( "varchar (%1)" ).arg( field.length() > 0 ? field.length() : 255 ); } fieldsStringList << name + " " + typeName; } - QString sql = QString( "create table %1 (%2);" ).arg( tableName, fieldsStringList.join( ", " ) ); + QString sql = QStringLiteral( "create table %1 (%2);" ).arg( tableName, fieldsStringList.join( QStringLiteral( ", " ) ) ); dbString dbstr; db_init_string( &dbstr ); @@ -2519,7 +2519,7 @@ void QgsGrass::insertRow( dbDriver *driver, const QString& tableName, { if ( !driver ) // should not happen { - throw QgsGrass::Exception( "driver is null" ); + throw QgsGrass::Exception( QStringLiteral( "driver is null" ) ); } QStringList valuesStringList; @@ -2553,7 +2553,7 @@ void QgsGrass::insertRow( dbDriver *driver, const QString& tableName, default: valueString = attribute.toString(); } - valueString.replace( "'", "''" ); + valueString.replace( QLatin1String( "'" ), QLatin1String( "''" ) ); if ( quote ) { @@ -2562,7 +2562,7 @@ void QgsGrass::insertRow( dbDriver *driver, const QString& tableName, valuesStringList << valueString; } - QString sql = QString( "insert into %1 values (%2);" ).arg( tableName, valuesStringList.join( ", " ) ); + QString sql = QStringLiteral( "insert into %1 values (%2);" ).arg( tableName, valuesStringList.join( QStringLiteral( ", " ) ) ); dbString dbstr; db_init_string( &dbstr ); @@ -2627,13 +2627,13 @@ QMap<int, QString> QgsGrass::vectorTypeMap() sMutex.lock(); if ( vectorTypes.isEmpty() ) { - vectorTypes.insert( GV_POINT, "point" ); - vectorTypes.insert( GV_CENTROID, "centroid" ); - vectorTypes.insert( GV_LINE, "line" ); - vectorTypes.insert( GV_BOUNDARY, "boundary" ); - vectorTypes.insert( GV_AREA, "area" ); - vectorTypes.insert( GV_FACE, "face" ); - vectorTypes.insert( GV_KERNEL, "kernel" ); + vectorTypes.insert( GV_POINT, QStringLiteral( "point" ) ); + vectorTypes.insert( GV_CENTROID, QStringLiteral( "centroid" ) ); + vectorTypes.insert( GV_LINE, QStringLiteral( "line" ) ); + vectorTypes.insert( GV_BOUNDARY, QStringLiteral( "boundary" ) ); + vectorTypes.insert( GV_AREA, QStringLiteral( "area" ) ); + vectorTypes.insert( GV_FACE, QStringLiteral( "face" ) ); + vectorTypes.insert( GV_KERNEL, QStringLiteral( "kernel" ) ); } sMutex.unlock(); } @@ -2676,14 +2676,14 @@ int QgsGrass::versionRelease() { #ifdef GRASS_VERSION_RELEASE #define QUOTE(x) #x - return QString( QUOTE( GRASS_VERSION_RELEASE ) ).toInt(); + return QStringLiteral( QUOTE( GRASS_VERSION_RELEASE ) ).toInt(); #else return QString( GRASS_VERSION_RELEASE ).toInt(); #endif } QString QgsGrass::versionString() { - return QString( GRASS_VERSION_STRING ); + return QStringLiteral( GRASS_VERSION_STRING ); } Qt::CaseSensitivity QgsGrass::caseSensitivity() @@ -2788,8 +2788,8 @@ QString QgsGrass::defaultGisbase() QString QgsGrass::gisbase() { QSettings settings; - bool customGisbase = settings.value( "/GRASS/gidbase/custom", false ).toBool(); - QString customGisdbaseDir = settings.value( "/GRASS/gidbase/customDir" ).toString(); + bool customGisbase = settings.value( QStringLiteral( "/GRASS/gidbase/custom" ), false ).toBool(); + QString customGisdbaseDir = settings.value( QStringLiteral( "/GRASS/gidbase/customDir" ) ).toString(); QString gisbase; if ( customGisbase && !customGisdbaseDir.isEmpty() ) @@ -2811,10 +2811,10 @@ void QgsGrass::setGisbase( bool custom, const QString &customDir ) QgsDebugMsg( QString( "custom = %1 customDir = %2" ).arg( custom ).arg( customDir ) ); QSettings settings; - bool previousCustom = settings.value( "/GRASS/gidbase/custom", false ).toBool(); - QString previousCustomDir = settings.value( "/GRASS/gidbase/customDir" ).toString(); - settings.setValue( "/GRASS/gidbase/custom", custom ); - settings.setValue( "/GRASS/gidbase/customDir", customDir ); + bool previousCustom = settings.value( QStringLiteral( "/GRASS/gidbase/custom" ), false ).toBool(); + QString previousCustomDir = settings.value( QStringLiteral( "/GRASS/gidbase/customDir" ) ).toString(); + settings.setValue( QStringLiteral( "/GRASS/gidbase/custom" ), custom ); + settings.setValue( QStringLiteral( "/GRASS/gidbase/customDir" ), customDir ); if ( custom != previousCustom || ( custom && customDir != previousCustomDir ) ) { @@ -2843,8 +2843,8 @@ QString QgsGrass::modulesConfigDefaultDirPath() QString QgsGrass::modulesConfigDirPath() { QSettings settings; - bool customModules = settings.value( "/GRASS/modules/config/custom", false ).toBool(); - QString customModulesDir = settings.value( "/GRASS/modules/config/customDir" ).toString(); + bool customModules = settings.value( QStringLiteral( "/GRASS/modules/config/custom" ), false ).toBool(); + QString customModulesDir = settings.value( QStringLiteral( "/GRASS/modules/config/customDir" ) ).toString(); if ( customModules && !customModulesDir.isEmpty() ) { @@ -2860,10 +2860,10 @@ void QgsGrass::setModulesConfig( bool custom, const QString &customDir ) { QSettings settings; - bool previousCustom = settings.value( "/GRASS/modules/config/custom", false ).toBool(); - QString previousCustomDir = settings.value( "/GRASS/modules/config/customDir" ).toString(); - settings.setValue( "/GRASS/modules/config/custom", custom ); - settings.setValue( "/GRASS/modules/config/customDir", customDir ); + bool previousCustom = settings.value( QStringLiteral( "/GRASS/modules/config/custom" ), false ).toBool(); + QString previousCustomDir = settings.value( QStringLiteral( "/GRASS/modules/config/customDir" ) ).toString(); + settings.setValue( QStringLiteral( "/GRASS/modules/config/custom" ), custom ); + settings.setValue( QStringLiteral( "/GRASS/modules/config/customDir" ), customDir ); if ( custom != previousCustom || ( custom && customDir != previousCustomDir ) ) { @@ -2875,30 +2875,30 @@ QPen QgsGrass::regionPen() { QSettings settings; QPen pen; - pen.setColor( QColor( settings.value( "/GRASS/region/color", "#ff0000" ).toString() ) ); - pen.setWidthF( settings.value( "/GRASS/region/width", 0 ).toFloat() ); + pen.setColor( QColor( settings.value( QStringLiteral( "/GRASS/region/color" ), "#ff0000" ).toString() ) ); + pen.setWidthF( settings.value( QStringLiteral( "/GRASS/region/width" ), 0 ).toFloat() ); return pen; } void QgsGrass::setRegionPen( const QPen & pen ) { QSettings settings; - settings.setValue( "/GRASS/region/color", pen.color().name() ); - settings.setValue( "/GRASS/region/width", pen.widthF() ); + settings.setValue( QStringLiteral( "/GRASS/region/color" ), pen.color().name() ); + settings.setValue( QStringLiteral( "/GRASS/region/width" ), pen.widthF() ); emit regionPenChanged(); } bool QgsGrass::modulesDebug() { QSettings settings; - return settings.value( "/GRASS/modules/debug", false ).toBool(); + return settings.value( QStringLiteral( "/GRASS/modules/debug" ), false ).toBool(); } void QgsGrass::setModulesDebug( bool debug ) { QSettings settings; bool previous = modulesDebug(); - settings.setValue( "/GRASS/modules/debug", debug ); + settings.setValue( QStringLiteral( "/GRASS/modules/debug" ), debug ); if ( previous != debug ) { emit modulesDebugChanged(); diff --git a/src/providers/grass/qgsgrass.h b/src/providers/grass/qgsgrass.h index 624ca8573843..ac4ce06e6697 100644 --- a/src/providers/grass/qgsgrass.h +++ b/src/providers/grass/qgsgrass.h @@ -438,7 +438,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject * @timeOut timeout */ static QString getInfo( const QString& info, const QString& gisdbase, - const QString& location, const QString& mapset = "PERMANENT", + const QString& location, const QString& mapset = QStringLiteral( "PERMANENT" ), const QString& map = QString::null, const QgsGrassObject::Type type = QgsGrassObject::None, double x = 0.0, double y = 0.0, const QgsRectangle& extent = QgsRectangle(), int sampleRows = 0, diff --git a/src/providers/grass/qgsgrassfeatureiterator.cpp b/src/providers/grass/qgsgrassfeatureiterator.cpp index 7f58a31d84b7..df1b7a544833 100644 --- a/src/providers/grass/qgsgrassfeatureiterator.cpp +++ b/src/providers/grass/qgsgrassfeatureiterator.cpp @@ -555,7 +555,7 @@ bool QgsGrassFeatureIterator::fetchFeature( QgsFeature& feature ) { int line = Vect_get_node_line( mSource->map(), lid, i ); QgsDebugMsg( "cancel" ); - if ( i > 0 ) lines += ","; + if ( i > 0 ) lines += QLatin1String( "," ); lines += QString::number( line ); } feature.setAttribute( 1, lines ); diff --git a/src/providers/grass/qgsgrassimport.cpp b/src/providers/grass/qgsgrassimport.cpp index 6c16f3ea96ba..4cbc3685e8de 100644 --- a/src/providers/grass/qgsgrassimport.cpp +++ b/src/providers/grass/qgsgrassimport.cpp @@ -44,7 +44,7 @@ QgsGrassImportIcon *QgsGrassImportIcon::instance() } QgsGrassImportIcon::QgsGrassImportIcon() - : QgsAnimatedIcon( QgsApplication::iconPath( "/mIconImport.gif" ) ) + : QgsAnimatedIcon( QgsApplication::iconPath( QStringLiteral( "/mIconImport.gif" ) ) ) { } @@ -102,7 +102,7 @@ void QgsGrassImportProgress::append( const QString & html ) QgsDebugMsg( "html = " + html ); if ( !mProgressHtml.isEmpty() ) { - mProgressHtml += "<br>"; + mProgressHtml += QLatin1String( "<br>" ); } mProgressHtml += html; emit progressChanged( html, mProgressHtml, mProgressMin, mProgressMax, mProgressValue ); @@ -113,13 +113,13 @@ void QgsGrassImportProgress::setRange( int min, int max ) mProgressMin = min; mProgressMax = max; mProgressValue = min; - emit progressChanged( "", mProgressHtml, mProgressMin, mProgressMax, mProgressValue ); + emit progressChanged( QLatin1String( "" ), mProgressHtml, mProgressMin, mProgressMax, mProgressValue ); } void QgsGrassImportProgress::setValue( int value ) { mProgressValue = value; - emit progressChanged( "", mProgressHtml, mProgressMin, mProgressMax, mProgressValue ); + emit progressChanged( QLatin1String( "" ), mProgressHtml, mProgressMin, mProgressMax, mProgressValue ); } //------------------------------ QgsGrassImport ------------------------------------ @@ -218,20 +218,20 @@ bool QgsGrassRasterImport::import() { if ( !mPipe ) { - setError( "Pipe is null." ); + setError( QStringLiteral( "Pipe is null." ) ); return false; } QgsRasterDataProvider * provider = mPipe->provider(); if ( !provider ) { - setError( "Pipe has no provider." ); + setError( QStringLiteral( "Pipe has no provider." ) ); return false; } if ( !provider->isValid() ) { - setError( "Provider is not valid." ); + setError( QStringLiteral( "Provider is not valid." ) ); return false; } @@ -239,7 +239,7 @@ bool QgsGrassRasterImport::import() struct Cell_head defaultWindow; if ( !QgsGrass::defaultRegion( mGrassObject.gisdbase(), mGrassObject.location(), &defaultWindow ) ) { - setError( "Cannot get default window" ); + setError( QStringLiteral( "Cannot get default window" ) ); return false; } @@ -303,7 +303,7 @@ bool QgsGrassRasterImport::import() if ( provider->bandCount() > 1 ) { // raster.<band> to keep in sync with r.in.gdal - name += QString( ".%1" ).arg( band ); + name += QStringLiteral( ".%1" ).arg( band ); } arguments.append( "output=" + name ); // get list of all output names QTemporaryFile gisrcFile; @@ -438,10 +438,10 @@ bool QgsGrassRasterImport::import() QString stdoutString = mProcess->readAllStandardOutput().constData(); QString stderrString = mProcess->readAllStandardError().constData(); - QString processResult = QString( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" ) + QString processResult = QStringLiteral( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" ) .arg( mProcess->exitStatus() ).arg( mProcess->exitCode() ) .arg( mProcess->error() ).arg( mProcess->errorString(), - stdoutString.replace( "\n", ", " ), stderrString.replace( "\n", ", " ) ); + stdoutString.replace( QLatin1String( "\n" ), QLatin1String( ", " ) ), stderrString.replace( QLatin1String( "\n" ), QLatin1String( ", " ) ) ); QgsDebugMsg( "processResult: " + processResult ); if ( mProcess->exitStatus() != QProcess::NormalExit ) @@ -474,9 +474,9 @@ bool QgsGrassRasterImport::import() QgsGrass::setMapset( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset() ); struct Ref ref; I_get_group_ref( name.toUtf8().data(), &ref ); - QString redName = name + QString( ".%1" ).arg( redBand ); - QString greenName = name + QString( ".%1" ).arg( greenBand ); - QString blueName = name + QString( ".%1" ).arg( blueBand ); + QString redName = name + QStringLiteral( ".%1" ).arg( redBand ); + QString greenName = name + QStringLiteral( ".%1" ).arg( greenBand ); + QString blueName = name + QStringLiteral( ".%1" ).arg( blueBand ); I_add_file_to_group_ref( redName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref ); I_add_file_to_group_ref( greenName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref ); I_add_file_to_group_ref( blueName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref ); @@ -494,7 +494,7 @@ QString QgsGrassRasterImport::srcDescription() const { if ( !mPipe || !mPipe->provider() ) { - return ""; + return QLatin1String( "" ); } return mPipe->provider()->dataSourceUri(); } @@ -508,7 +508,7 @@ QStringList QgsGrassRasterImport::extensions( QgsRasterDataProvider* provider ) list.reserve( bands ); for ( int band = 1; band <= bands; ++band ) { - list << QString( ".%1" ).arg( band ); + list << QStringLiteral( ".%1" ).arg( band ); } } return list; @@ -553,13 +553,13 @@ bool QgsGrassVectorImport::import() if ( !mProvider ) { - setError( "Provider is null." ); + setError( QStringLiteral( "Provider is null." ) ); return false; } if ( !mProvider->isValid() ) { - setError( "Provider is not valid." ); + setError( QStringLiteral( "Provider is not valid." ) ); return false; } @@ -716,10 +716,10 @@ bool QgsGrassVectorImport::import() QString stdoutString = mProcess->readAllStandardOutput().constData(); QString stderrString = mProcess->readAllStandardError().constData(); - QString processResult = QString( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" ) + QString processResult = QStringLiteral( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" ) .arg( mProcess->exitStatus() ).arg( mProcess->exitCode() ) .arg( mProcess->error() ).arg( mProcess->errorString(), - stdoutString.replace( "\n", ", " ), stderrString.replace( "\n", ", " ) ); + stdoutString.replace( QLatin1String( "\n" ), QLatin1String( ", " ) ), stderrString.replace( QLatin1String( "\n" ), QLatin1String( ", " ) ) ); QgsDebugMsg( "processResult: " + processResult ); if ( mProcess->exitStatus() != QProcess::NormalExit ) @@ -747,7 +747,7 @@ QString QgsGrassVectorImport::srcDescription() const { if ( !mProvider ) { - return ""; + return QLatin1String( "" ); } return mProvider->dataSourceUri(); } diff --git a/src/providers/grass/qgsgrassoptions.cpp b/src/providers/grass/qgsgrassoptions.cpp index f1db15981d7d..4ae479674ff5 100644 --- a/src/providers/grass/qgsgrassoptions.cpp +++ b/src/providers/grass/qgsgrassoptions.cpp @@ -29,10 +29,10 @@ extern "C" } QgsGrassOptions::QgsGrassOptions( QWidget *parent ) - : QgsOptionsDialogBase( "GrassOptions", parent ) + : QgsOptionsDialogBase( QStringLiteral( "GrassOptions" ), parent ) , QgsGrassOptionsBase() - , mImportSettingsPath( "/GRASS/browser/import" ) - , mModulesSettingsPath( "/GRASS/modules/config" ) + , mImportSettingsPath( QStringLiteral( "/GRASS/browser/import" ) ) + , mModulesSettingsPath( QStringLiteral( "/GRASS/modules/config" ) ) { setupUi( this ); initOptionsBase( false ); @@ -43,12 +43,12 @@ QgsGrassOptions::QgsGrassOptions( QWidget *parent ) QSettings settings; // General - QString version = QString( GRASS_VERSION_STRING ).remove( "@(#)" ).trimmed(); - QString revision = QString( GIS_H_VERSION ).remove( "$" ).trimmed(); + QString version = QStringLiteral( GRASS_VERSION_STRING ).remove( QStringLiteral( "@(#)" ) ).trimmed(); + QString revision = QStringLiteral( GIS_H_VERSION ).remove( QStringLiteral( "$" ) ).trimmed(); mGrassVersionLabel->setText( tr( "GRASS version" ) + " : " + version + " " + revision ); - bool customGisbase = settings.value( "/GRASS/gidbase/custom", false ).toBool(); - QString customGisbaseDir = settings.value( "/GRASS/gidbase/customDir" ).toString(); + bool customGisbase = settings.value( QStringLiteral( "/GRASS/gidbase/custom" ), false ).toBool(); + QString customGisbaseDir = settings.value( QStringLiteral( "/GRASS/gidbase/customDir" ) ).toString(); mGisbaseDefaultRadioButton->setText( tr( "Default" ) + " (" + QgsGrass::defaultGisbase() + ")" ); mGisbaseDefaultRadioButton->setChecked( !customGisbase ); mGisbaseCustomRadioButton->setChecked( customGisbase ); @@ -76,11 +76,11 @@ QgsGrassOptions::QgsGrassOptions( QWidget *parent ) mImportExternalCheckBox->setChecked( settings.value( mImportSettingsPath + "/external", true ).toBool() ); - mTopoLayersCheckBox->setChecked( settings.value( "/GRASS/showTopoLayers", false ).toBool() ); + mTopoLayersCheckBox->setChecked( settings.value( QStringLiteral( "/GRASS/showTopoLayers" ), false ).toBool() ); // Region QPen regionPen = QgsGrass::regionPen(); - mRegionColorButton->setContext( "gui" ); + mRegionColorButton->setContext( QStringLiteral( "gui" ) ); mRegionColorButton->setColorDialogTitle( tr( "Select color" ) ); mRegionColorButton->setColor( regionPen.color() ); mRegionWidthSpinBox->setValue( regionPen.width() ); @@ -162,7 +162,7 @@ void QgsGrassOptions::saveOptions() settings.setValue( mImportSettingsPath + "/external", mImportExternalCheckBox->isChecked() ); - settings.setValue( "/GRASS/showTopoLayers", mTopoLayersCheckBox->isChecked() ); + settings.setValue( QStringLiteral( "/GRASS/showTopoLayers" ), mTopoLayersCheckBox->isChecked() ); // Region QPen regionPen = QgsGrass::regionPen(); diff --git a/src/providers/grass/qgsgrassprovider.cpp b/src/providers/grass/qgsgrassprovider.cpp index f10ace7e4a84..ccb7b6fb7bef 100644 --- a/src/providers/grass/qgsgrassprovider.cpp +++ b/src/providers/grass/qgsgrassprovider.cpp @@ -104,7 +104,7 @@ typedef int Vect_delete_line_function_type( struct Map_info *, grass_off_t ); Vect_rewrite_line_function_type *Vect_rewrite_line_function_pointer = ( Vect_rewrite_line_function_type * )Vect_rewrite_line; Vect_delete_line_function_type *Vect_delete_line_function_pointer = ( Vect_delete_line_function_type * )Vect_delete_line; -static QString GRASS_KEY = "grass"; +static QString GRASS_KEY = QStringLiteral( "grass" ); int QgsGrassProvider::LAST_TYPE = -9999; int QgsGrassProvider::mEditedCount = 0; @@ -161,27 +161,27 @@ QgsGrassProvider::QgsGrassProvider( const QString& uri ) /* Parse Layer, supported layers <field>_point, <field>_line, <field>_area * Layer is opened even if it is empty (has no features) */ - if ( mLayerName.compare( "boundary" ) == 0 ) // currently not used + if ( mLayerName.compare( QLatin1String( "boundary" ) ) == 0 ) // currently not used { mLayerType = BOUNDARY; mGrassType = GV_BOUNDARY; } - else if ( mLayerName.compare( "centroid" ) == 0 ) // currently not used + else if ( mLayerName.compare( QLatin1String( "centroid" ) ) == 0 ) // currently not used { mLayerType = CENTROID; mGrassType = GV_CENTROID; } - else if ( mLayerName == "topo_point" ) + else if ( mLayerName == QLatin1String( "topo_point" ) ) { mLayerType = TOPO_POINT; mGrassType = GV_POINTS; } - else if ( mLayerName == "topo_line" ) + else if ( mLayerName == QLatin1String( "topo_line" ) ) { mLayerType = TOPO_LINE; mGrassType = GV_LINES; } - else if ( mLayerName == "topo_node" ) + else if ( mLayerName == QLatin1String( "topo_node" ) ) { mLayerType = TOPO_NODE; mGrassType = 0; @@ -262,12 +262,12 @@ QgsGrassProvider::QgsGrassProvider( const QString& uri ) // TODO: types according to database setNativeTypes( QList<NativeType>() - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "double precision", QVariant::Double, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 ) #if GRASS_VERSION_MAJOR < 7 << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length (varchar)" ), "varchar", QVariant::String, 1, 255, -1, -1 ) #else - << QgsVectorDataProvider::NativeType( tr( "Text" ), "text", QVariant::String ) + << QgsVectorDataProvider::NativeType( tr( "Text" ), QStringLiteral( "text" ), QVariant::String ) #endif // TODO: // << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, 8, 8 ); @@ -410,7 +410,7 @@ QgsAbstractFeatureSource* QgsGrassProvider::featureSource() const QString QgsGrassProvider::storageType() const { - return "GRASS (Geographic Resources Analysis and Support System) file"; + return QStringLiteral( "GRASS (Geographic Resources Analysis and Support System) file" ); } @@ -539,19 +539,19 @@ int QgsGrassProvider::grassLayerType( const QString& name ) } QString ts = name.right( name.length() - pos - 1 ); - if ( ts.compare( "point" ) == 0 ) + if ( ts.compare( QLatin1String( "point" ) ) == 0 ) { return GV_POINT; // ?! centroids may be points } - else if ( ts.compare( "line" ) == 0 ) + else if ( ts.compare( QLatin1String( "line" ) ) == 0 ) { return GV_LINES; } - else if ( ts.compare( "face" ) == 0 ) + else if ( ts.compare( QLatin1String( "face" ) ) == 0 ) { return GV_FACE; } - else if ( ts.compare( "polygon" ) == 0 ) + else if ( ts.compare( QLatin1String( "polygon" ) ) == 0 ) { return GV_AREA; } @@ -1064,24 +1064,24 @@ bool QgsGrassProvider::isTopoType( int layerType ) void QgsGrassProvider::setTopoFields() { - mTopoFields.append( QgsField( "id", QVariant::Int ) ); + mTopoFields.append( QgsField( QStringLiteral( "id" ), QVariant::Int ) ); if ( mLayerType == TOPO_POINT ) { - mTopoFields.append( QgsField( "type", QVariant::String ) ); - mTopoFields.append( QgsField( "node", QVariant::Int ) ); + mTopoFields.append( QgsField( QStringLiteral( "type" ), QVariant::String ) ); + mTopoFields.append( QgsField( QStringLiteral( "node" ), QVariant::Int ) ); } else if ( mLayerType == TOPO_LINE ) { - mTopoFields.append( QgsField( "type", QVariant::String ) ); - mTopoFields.append( QgsField( "node1", QVariant::Int ) ); - mTopoFields.append( QgsField( "node2", QVariant::Int ) ); - mTopoFields.append( QgsField( "left", QVariant::Int ) ); - mTopoFields.append( QgsField( "right", QVariant::Int ) ); + mTopoFields.append( QgsField( QStringLiteral( "type" ), QVariant::String ) ); + mTopoFields.append( QgsField( QStringLiteral( "node1" ), QVariant::Int ) ); + mTopoFields.append( QgsField( QStringLiteral( "node2" ), QVariant::Int ) ); + mTopoFields.append( QgsField( QStringLiteral( "left" ), QVariant::Int ) ); + mTopoFields.append( QgsField( QStringLiteral( "right" ), QVariant::Int ) ); } else if ( mLayerType == TOPO_NODE ) { - mTopoFields.append( QgsField( "lines", QVariant::String ) ); + mTopoFields.append( QgsField( QStringLiteral( "lines" ), QVariant::String ) ); } } diff --git a/src/providers/grass/qgsgrassprovidermodule.cpp b/src/providers/grass/qgsgrassprovidermodule.cpp index d3348807abe4..02589ed0735c 100644 --- a/src/providers/grass/qgsgrassprovidermodule.cpp +++ b/src/providers/grass/qgsgrassprovidermodule.cpp @@ -60,14 +60,14 @@ QList<QAction*> QgsGrassItemActions::actions() // TODO: check ownership if ( mGrassObject.type() == QgsGrassObject::Location ) { - QAction* newMapsetAction = new QAction( QgsApplication::getThemeIcon( "grass_new_mapset.png" ), tr( "New mapset" ), this ); + QAction* newMapsetAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "grass_new_mapset.png" ) ), tr( "New mapset" ), this ); connect( newMapsetAction, SIGNAL( triggered() ), SLOT( newMapset() ) ); list << newMapsetAction; } if ( mGrassObject.type() == QgsGrassObject::Mapset && isMapsetOwner ) { - QAction* openMapsetAction = new QAction( QgsApplication::getThemeIcon( "grass_open_mapset.png" ), tr( "Open mapset" ), this ); + QAction* openMapsetAction = new QAction( QgsApplication::getThemeIcon( QStringLiteral( "grass_open_mapset.png" ) ), tr( "Open mapset" ), this ); connect( openMapsetAction, SIGNAL( triggered() ), SLOT( openMapset() ) ); list << openMapsetAction; } @@ -128,7 +128,7 @@ void QgsGrassItemActions::newMapset() QgsDebugMsg( "existingNames = " + existingNames.join( "," ) ); QRegExp regExp = QgsGrassObject::newNameRegExp( QgsGrassObject::Mapset ); Qt::CaseSensitivity caseSensitivity = QgsGrass::caseSensitivity(); - QgsNewNameDialog dialog( "", "", QStringList(), existingNames, regExp, caseSensitivity ); + QgsNewNameDialog dialog( QLatin1String( "" ), QLatin1String( "" ), QStringList(), existingNames, regExp, caseSensitivity ); if ( dialog.exec() != QDialog::Accepted ) { @@ -240,7 +240,7 @@ QString QgsGrassItemActions::newVectorMap() QgsDebugMsg( "existingNames = " + existingNames.join( "," ) ); QRegExp regExp = QgsGrassObject::newNameRegExp( QgsGrassObject::Vector ); Qt::CaseSensitivity caseSensitivity = QgsGrass::caseSensitivity(); - QgsNewNameDialog dialog( "", "", QStringList(), existingNames, regExp, caseSensitivity ); + QgsNewNameDialog dialog( QLatin1String( "" ), QLatin1String( "" ), QStringList(), existingNames, regExp, caseSensitivity ); if ( dialog.exec() != QDialog::Accepted ) { @@ -259,7 +259,7 @@ QString QgsGrassItemActions::newVectorMap() if ( !error.isEmpty() ) { QgsGrass::warning( error ); - name = ""; + name = QLatin1String( "" ); } return name; } @@ -294,24 +294,24 @@ void QgsGrassItemActions::newLayer( const QString& type ) QgsDebugMsg( QString( "layerNumber = %1" ).arg( layerNumber ) ); - QString uri = mGrassObject.mapsetPath() + "/" + name + QString( "/%1_%2" ).arg( layerNumber ).arg( type ); + QString uri = mGrassObject.mapsetPath() + "/" + name + QStringLiteral( "/%1_%2" ).arg( layerNumber ).arg( type ); QgsDebugMsg( "uri = " + uri ); QgsGrass::instance()->emitNewLayer( uri, name ); } void QgsGrassItemActions::newPointLayer() { - newLayer( "point" ); + newLayer( QStringLiteral( "point" ) ); } void QgsGrassItemActions::newLineLayer() { - newLayer( "line" ); + newLayer( QStringLiteral( "line" ) ); } void QgsGrassItemActions::newPolygonLayer() { - newLayer( "polygon" ); + newLayer( QStringLiteral( "polygon" ) ); } //----------------------- QgsGrassObjectItemBase ------------------------------ @@ -324,7 +324,7 @@ QgsGrassObjectItemBase::QgsGrassObjectItemBase( const QgsGrassObject& grassObjec //----------------------- QgsGrassLocationItem ------------------------------ QgsGrassLocationItem::QgsGrassLocationItem( QgsDataItem* parent, QString dirPath, QString path ) - : QgsDirectoryItem( parent, "", dirPath, path ) + : QgsDirectoryItem( parent, QLatin1String( "" ), dirPath, path ) , QgsGrassObjectItemBase( QgsGrassObject() ) , mActions( 0 ) { @@ -335,10 +335,10 @@ QgsGrassLocationItem::QgsGrassLocationItem( QgsDataItem* parent, QString dirPath dir.cdUp(); QString gisdbase = dir.path(); - mGrassObject = QgsGrassObject( gisdbase, mName, "", "", QgsGrassObject::Location ); + mGrassObject = QgsGrassObject( gisdbase, mName, QLatin1String( "" ), QLatin1String( "" ), QgsGrassObject::Location ); mActions = new QgsGrassItemActions( mGrassObject, true, this ); - mIconName = "grass_location.png"; + mIconName = QStringLiteral( "grass_location.png" ); // set Directory type so that when sorted it gets into dirs (after the dir it represents) mType = QgsDataItem::Directory; @@ -369,7 +369,7 @@ QVector<QgsDataItem*>QgsGrassLocationItem::createChildren() QList<QgsGrassImport*> QgsGrassMapsetItem::mImports; QgsGrassMapsetItem::QgsGrassMapsetItem( QgsDataItem* parent, QString dirPath, QString path ) - : QgsDirectoryItem( parent, "", dirPath, path ) + : QgsDirectoryItem( parent, QLatin1String( "" ), dirPath, path ) , QgsGrassObjectItemBase( QgsGrassObject() ) , mActions( 0 ) , mMapsetFileSystemWatcher( 0 ) @@ -382,14 +382,14 @@ QgsGrassMapsetItem::QgsGrassMapsetItem( QgsDataItem* parent, QString dirPath, QS dir.cdUp(); QString gisdbase = dir.path(); - mGrassObject = QgsGrassObject( gisdbase, location, mName, "", QgsGrassObject::Mapset ); + mGrassObject = QgsGrassObject( gisdbase, location, mName, QLatin1String( "" ), QgsGrassObject::Mapset ); mActions = new QgsGrassItemActions( mGrassObject, true, this ); // emit data changed to possibly change icon connect( QgsGrass::instance(), SIGNAL( mapsetChanged() ), this, SLOT( emitDataChanged() ) ); connect( QgsGrass::instance(), SIGNAL( mapsetSearchPathChanged() ), this, SLOT( emitDataChanged() ) ); - mIconName = "grass_mapset.png"; + mIconName = QStringLiteral( "grass_mapset.png" ); } QIcon QgsGrassMapsetItem::icon() @@ -478,7 +478,7 @@ QVector<QgsDataItem*> QgsGrassMapsetItem::createChildren() // TODO: add some auto cleaning mechanism to remove temporary maps left after import fail // keep excluded tmp name in sync with qgis.v.in QgsDebugMsg( "name = " + name ); - if ( name.startsWith( "qgis_import_tmp_" ) ) + if ( name.startsWith( QLatin1String( "qgis_import_tmp_" ) ) ) { QgsDebugMsg( "skip tmp import vector " + name ); continue; @@ -556,14 +556,14 @@ QVector<QgsDataItem*> QgsGrassMapsetItem::createChildren() // somewhere not properly escaped (there was bug in QgsMimeDataUtils for example) QString uri = mDirPath + "/" + name + "/" + layerName; QgsLayerItem::LayerType layerType = QgsLayerItem::Vector; - QString typeName = layerName.split( "_" ).value( 1 ); - QString baseLayerName = layerName.split( "_" ).value( 0 ); + QString typeName = layerName.split( QStringLiteral( "_" ) ).value( 1 ); + QString baseLayerName = layerName.split( QStringLiteral( "_" ) ).value( 0 ); - if ( typeName == "point" || typeName == "node" ) + if ( typeName == QLatin1String( "point" ) || typeName == QLatin1String( "node" ) ) layerType = QgsLayerItem::Point; - else if ( typeName == "line" ) + else if ( typeName == QLatin1String( "line" ) ) layerType = QgsLayerItem::Line; - else if ( typeName == "polygon" ) + else if ( typeName == QLatin1String( "polygon" ) ) layerType = QgsLayerItem::Polygon; QString layerPath = mapPath + "/" + layerName; @@ -688,7 +688,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) Q_FOREACH ( const QgsMimeDataUtils::Uri& u, lst ) { - if ( u.layerType != "raster" && u.layerType != "vector" ) + if ( u.layerType != QLatin1String( "raster" ) && u.layerType != QLatin1String( "vector" ) ) { errors.append( tr( "%1 layer type not supported" ).arg( u.name ) ); continue; @@ -705,9 +705,9 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) // use g.copy for GRASS maps in the same location bool useCopy = false; - if ( u.layerType == "raster" ) + if ( u.layerType == QLatin1String( "raster" ) ) { - if ( u.providerKey == "grassraster" && srcObject.setFromUri( u.uri ) + if ( u.providerKey == QLatin1String( "grassraster" ) && srcObject.setFromUri( u.uri ) && srcObject.locationIdentical( mGrassObject ) ) { useCopy = true; @@ -720,9 +720,9 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) existingNames = existingRasters; regExp = QgsGrassObject::newNameRegExp( QgsGrassObject::Raster ); } - else if ( u.layerType == "vector" ) + else if ( u.layerType == QLatin1String( "vector" ) ) { - if ( u.providerKey == "grass" && srcObject.setFromUri( u.uri ) + if ( u.providerKey == QLatin1String( "grass" ) && srcObject.setFromUri( u.uri ) && srcObject.locationIdentical( mGrassObject ) ) { useCopy = true; @@ -754,7 +754,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) delete provider; continue; } - if ( u.layerType == "raster" ) + if ( u.layerType == QLatin1String( "raster" ) ) { extensions = QgsGrassRasterImport::extensions( rasterProvider ); } @@ -762,7 +762,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) } // TODO: add a method in QgsGrass to convert a name to GRASS valid name - QString destName = srcName.replace( " ", "_" ); + QString destName = srcName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); if ( QgsNewNameDialog::exists( destName, extensions, existingNames, caseSensitivity ) || !regExp.exactMatch( destName ) ) { @@ -785,7 +785,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) import = new QgsGrassCopy( srcObject, destObject ); } - else if ( u.layerType == "raster" ) + else if ( u.layerType == QLatin1String( "raster" ) ) { QgsRectangle newExtent = rasterProvider->extent(); int newXSize; @@ -820,10 +820,10 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) QgsDebugMsg( "providerCrs = " + providerCrs.toWkt() ); QgsDebugMsg( "mapsetCrs = " + mapsetCrs.toWkt() ); - bool settingsExternal = settings.value( "/GRASS/browser/import/external", true ).toBool(); + bool settingsExternal = settings.value( QStringLiteral( "/GRASS/browser/import/external" ), true ).toBool(); QgsGrassObject rasterObject( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset(), destName, QgsGrassObject::Raster ); if ( providerCrs.isValid() && mapsetCrs.isValid() && providerCrs == mapsetCrs - && rasterProvider->name() == "gdal" && settingsExternal ) + && rasterProvider->name() == QLatin1String( "gdal" ) && settingsExternal ) { import = new QgsGrassExternal( rasterProvider->dataSourceUri(), rasterObject ); delete rasterProvider; @@ -841,7 +841,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) projector->destExtentSize( rasterProvider->extent(), rasterProvider->xSize(), rasterProvider->ySize(), newExtent, newXSize, newYSize ); } - QgsRasterProjector::Precision precision = ( QgsRasterProjector::Precision ) settings.value( "/GRASS/browser/import/crsTransform", QgsRasterProjector::Approximate ).toInt(); + QgsRasterProjector::Precision precision = ( QgsRasterProjector::Precision ) settings.value( QStringLiteral( "/GRASS/browser/import/crsTransform" ), QgsRasterProjector::Approximate ).toInt(); projector->setPrecision( precision ); pipe->set( projector ); @@ -853,7 +853,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) import = new QgsGrassRasterImport( pipe, rasterObject, newExtent, newXSize, newYSize ); // takes pipe ownership } } - else if ( u.layerType == "vector" ) + else if ( u.layerType == QLatin1String( "vector" ) ) { QgsGrassObject vectorObject( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset(), destName, QgsGrassObject::Vector ); import = new QgsGrassVectorImport( vectorProvider, vectorObject ); // takes provider ownership @@ -885,11 +885,11 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) import->importInThread(); mImports.append( import ); - if ( u.layerType == "raster" ) + if ( u.layerType == QLatin1String( "raster" ) ) { existingRasters.append( import->names() ); } - else if ( u.layerType == "vector" ) + else if ( u.layerType == QLatin1String( "vector" ) ) { existingVectors.append( import->names() ); } @@ -899,7 +899,7 @@ bool QgsGrassMapsetItem::handleDrop( const QMimeData * data, Qt::DropAction ) if ( !errors.isEmpty() ) { QgsMessageOutput::showMessage( tr( "Import to GRASS mapset" ), - tr( "Failed to import some layers!\n\n" ) + errors.join( "\n" ), + tr( "Failed to import some layers!\n\n" ) + errors.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText ); } @@ -987,7 +987,7 @@ QgsGrassVectorItem::QgsGrassVectorItem( QgsDataItem* parent, QgsGrassObject gras if ( !mValid ) { setState( Populated ); - setIconName( "/mIconDelete.png" ); + setIconName( QStringLiteral( "/mIconDelete.png" ) ); } mActions = new QgsGrassItemActions( mGrassObject, mValid, this ); @@ -1043,7 +1043,7 @@ bool QgsGrassVectorItem::equal( const QgsDataItem *other ) QgsGrassVectorLayerItem::QgsGrassVectorLayerItem( QgsDataItem* parent, QgsGrassObject grassObject, QString layerName, QString path, QString uri, LayerType layerType, bool singleLayer ) - : QgsGrassObjectItem( parent, grassObject, layerName, path, uri, layerType, "grass" ) + : QgsGrassObjectItem( parent, grassObject, layerName, path, uri, layerType, QStringLiteral( "grass" ) ) , mSingleLayer( singleLayer ) { } @@ -1071,7 +1071,7 @@ bool QgsGrassVectorLayerItem::equal( const QgsDataItem *other ) QgsGrassRasterItem::QgsGrassRasterItem( QgsDataItem* parent, QgsGrassObject grassObject, QString path, QString uri, bool isExternal ) - : QgsGrassObjectItem( parent, grassObject, grassObject.name(), path, uri, QgsLayerItem::Raster, "grassraster" ) + : QgsGrassObjectItem( parent, grassObject, grassObject.name(), path, uri, QgsLayerItem::Raster, QStringLiteral( "grassraster" ) ) , mExternal( isExternal ) { } @@ -1084,7 +1084,7 @@ QIcon QgsGrassRasterItem::icon() { if ( linkIcon.isNull() ) { - linkIcon = QgsApplication::getThemeIcon( "/mIconRasterLink.svg" ); + linkIcon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconRasterLink.svg" ) ); } return linkIcon; } @@ -1101,7 +1101,7 @@ bool QgsGrassRasterItem::equal( const QgsDataItem *other ) QgsGrassGroupItem::QgsGrassGroupItem( QgsDataItem* parent, QgsGrassObject grassObject, QString path, QString uri ) - : QgsGrassObjectItem( parent, grassObject, grassObject.name(), path, uri, QgsLayerItem::Raster, "grassraster" ) + : QgsGrassObjectItem( parent, grassObject, grassObject.name(), path, uri, QgsLayerItem::Raster, QStringLiteral( "grassraster" ) ) { } @@ -1111,7 +1111,7 @@ QIcon QgsGrassGroupItem::icon() if ( linkIcon.isNull() ) { - linkIcon = QgsApplication::getThemeIcon( "/mIconRasterGroup.svg" ); + linkIcon = QgsApplication::getThemeIcon( QStringLiteral( "/mIconRasterGroup.svg" ) ); } return linkIcon; } @@ -1217,7 +1217,7 @@ QIcon QgsGrassImportItem::icon() { if ( mImport && mImport->isCanceled() ) { - setIconName( "/mIconDelete.png" ); + setIconName( QStringLiteral( "/mIconDelete.png" ) ); return QgsDataItem::icon(); } else @@ -1273,7 +1273,7 @@ QGISEXTERN QgsGrassProvider * classFactory( const QString *uri ) */ QGISEXTERN QString providerKey() { - return QString( "grass" ); + return QStringLiteral( "grass" ); } /** @@ -1281,7 +1281,7 @@ QGISEXTERN QString providerKey() */ QGISEXTERN QString description() { - return QString( "GRASS %1 vector provider" ).arg( GRASS_VERSION_MAJOR ); + return QStringLiteral( "GRASS %1 vector provider" ).arg( GRASS_VERSION_MAJOR ); } /** diff --git a/src/providers/grass/qgsgrassrasterprovider.cpp b/src/providers/grass/qgsgrassrasterprovider.cpp index 3a9302886199..c4eb3de5fffd 100644 --- a/src/providers/grass/qgsgrassrasterprovider.cpp +++ b/src/providers/grass/qgsgrassrasterprovider.cpp @@ -71,7 +71,7 @@ QgsGrassRasterProvider::QgsGrassRasterProvider( QString const & uri ) mMapName = fileInfo.fileName(); QDir dir = fileInfo.dir(); QString element = dir.dirName(); - if ( element != "cellhd" ) + if ( element != QLatin1String( "cellhd" ) ) { appendError( ERR( tr( "Groups not yet supported" ) ) ); return; @@ -106,10 +106,10 @@ QgsGrassRasterProvider::QgsGrassRasterProvider( QString const & uri ) error.clear(); mInfo = QgsGrass::info( mGisdbase, mLocation, mMapset, mMapName, QgsGrassObject::Raster, - "info", QgsRectangle(), 0, 0, 3000, error ); + QStringLiteral( "info" ), QgsRectangle(), 0, 0, 3000, error ); appendIfError( error ); - mGrassDataType = mInfo["TYPE"].toInt(); + mGrassDataType = mInfo[QStringLiteral( "TYPE" )].toInt(); QgsDebugMsg( "mGrassDataType = " + QString::number( mGrassDataType ) ); // TODO: avoid showing these strange numbers in GUI @@ -191,7 +191,7 @@ QImage* QgsGrassRasterProvider::draw( QgsRectangle const & viewExtent, int pixe QStringList arguments; arguments.append( "map=" + mMapName + "@" + mMapset ); - arguments.append(( QString( "window=%1,%2,%3,%4,%5,%6" ) + arguments.append(( QStringLiteral( "window=%1,%2,%3,%4,%5,%6" ) .arg( QgsRasterBlock::printValue( viewExtent.xMinimum() ), QgsRasterBlock::printValue( viewExtent.yMinimum() ), QgsRasterBlock::printValue( viewExtent.xMaximum() ), @@ -242,14 +242,14 @@ void QgsGrassRasterProvider::readBlock( int bandNo, int xBlock, int yBlock, void double yMinimum = yMaximum - cellHeight * mYBlockSize; QgsDebugMsg( "mYBlockSize = " + QString::number( mYBlockSize ) ); - arguments.append(( QString( "window=%1,%2,%3,%4,%5,%6" ) + arguments.append(( QStringLiteral( "window=%1,%2,%3,%4,%5,%6" ) .arg( QgsRasterBlock::printValue( ext.xMinimum() ), QgsRasterBlock::printValue( yMinimum ), QgsRasterBlock::printValue( ext.xMaximum() ), QgsRasterBlock::printValue( yMaximum ) ) .arg( mCols ).arg( mYBlockSize ) ) ); - arguments.append( "format=value" ); + arguments.append( QStringLiteral( "format=value" ) ); QString cmd = QgsApplication::libexecPath() + "grass/modules/qgis.d.rast"; QByteArray data; try @@ -292,13 +292,13 @@ void QgsGrassRasterProvider::readBlock( int bandNo, QgsRectangle const & viewEx QStringList arguments; arguments.append( "map=" + mMapName + "@" + mMapset ); - arguments.append(( QString( "window=%1,%2,%3,%4,%5,%6" ) + arguments.append(( QStringLiteral( "window=%1,%2,%3,%4,%5,%6" ) .arg( QgsRasterBlock::printValue( viewExtent.xMinimum() ), QgsRasterBlock::printValue( viewExtent.yMinimum() ), QgsRasterBlock::printValue( viewExtent.xMaximum() ), QgsRasterBlock::printValue( viewExtent.yMaximum() ) ) .arg( pixelWidth ).arg( pixelHeight ) ) ); - arguments.append( "format=value" ); + arguments.append( QStringLiteral( "format=value" ) ); QString cmd = QgsApplication::libexecPath() + "grass/modules/qgis.d.rast"; QByteArray data; try @@ -354,21 +354,21 @@ QgsRasterBandStats QgsGrassRasterProvider::bandStatistics( int theBandNo, int th QString error; QHash<QString, QString> info = QgsGrass::info( mGisdbase, mLocation, mMapset, mMapName, QgsGrassObject::Raster, - "stats", extent, sampleRows, sampleCols, timeout, error ); + QStringLiteral( "stats" ), extent, sampleRows, sampleCols, timeout, error ); if ( info.isEmpty() || !error.isEmpty() ) { return myRasterBandStats; } - myRasterBandStats.sum = info["SUM"].toDouble(); - myRasterBandStats.elementCount = info["COUNT"].toInt(); - myRasterBandStats.minimumValue = info["MIN"].toDouble(); - myRasterBandStats.maximumValue = info["MAX"].toDouble(); + myRasterBandStats.sum = info[QStringLiteral( "SUM" )].toDouble(); + myRasterBandStats.elementCount = info[QStringLiteral( "COUNT" )].toInt(); + myRasterBandStats.minimumValue = info[QStringLiteral( "MIN" )].toDouble(); + myRasterBandStats.maximumValue = info[QStringLiteral( "MAX" )].toDouble(); myRasterBandStats.range = myRasterBandStats.maximumValue - myRasterBandStats.minimumValue; - myRasterBandStats.sumOfSquares = info["SQSUM"].toDouble(); - myRasterBandStats.mean = info["MEAN"].toDouble(); - myRasterBandStats.stdDev = info["STDEV"].toDouble(); + myRasterBandStats.sumOfSquares = info[QStringLiteral( "SQSUM" )].toDouble(); + myRasterBandStats.mean = info[QStringLiteral( "MEAN" )].toDouble(); + myRasterBandStats.stdDev = info[QStringLiteral( "STDEV" )].toDouble(); QgsDebugMsg( QString( "min = %1" ).arg( myRasterBandStats.minimumValue ) ); QgsDebugMsg( QString( "max = %1" ).arg( myRasterBandStats.maximumValue ) ); @@ -608,12 +608,12 @@ QString QgsGrassRasterProvider::lastError() QString QgsGrassRasterProvider::name() const { - return QString( "grassraster" ); + return QStringLiteral( "grassraster" ); } QString QgsGrassRasterProvider::description() const { - return QString( "GRASS %1 raster provider" ).arg( GRASS_VERSION_MAJOR ); + return QStringLiteral( "GRASS %1 raster provider" ).arg( GRASS_VERSION_MAJOR ); } QDateTime QgsGrassRasterProvider::dataTimestamp() const @@ -621,7 +621,7 @@ QDateTime QgsGrassRasterProvider::dataTimestamp() const QDateTime time; QString mapset = mGisdbase + "/" + mLocation + "/" + mMapset; QStringList dirs; - dirs << "cell" << "colr"; + dirs << QStringLiteral( "cell" ) << QStringLiteral( "colr" ); Q_FOREACH ( const QString& dir, dirs ) { QString path = mapset + "/" + dir + "/" + mMapName; @@ -677,7 +677,7 @@ void QgsGrassRasterValue::start() QString module = QgsGrass::qgisGrassModulePath() + "/qgis.g.info"; QStringList arguments; - arguments.append( "info=query" ); + arguments.append( QStringLiteral( "info=query" ) ); arguments.append( "rast=" + mMapName + "@" + mMapset ); try { @@ -719,7 +719,7 @@ double QgsGrassRasterValue::value( double x, double y, bool *ok ) return value; } - QString coor = QString( "%1 %2\n" ).arg( QgsRasterBlock::printValue( x ), + QString coor = QStringLiteral( "%1 %2\n" ).arg( QgsRasterBlock::printValue( x ), QgsRasterBlock::printValue( y ) ); QgsDebugMsg( "coor : " + coor ); mProcess->write( coor.toLatin1() ); // how to flush, necessary? @@ -729,10 +729,10 @@ double QgsGrassRasterValue::value( double x, double y, bool *ok ) // TODO: use doubles instead of strings - QStringList list = str.trimmed().split( ":" ); + QStringList list = str.trimmed().split( QStringLiteral( ":" ) ); if ( list.size() == 2 ) { - if ( list[1] == "error" ) return value; + if ( list[1] == QLatin1String( "error" ) ) return value; value = list[1].toDouble( ok ); } return value; diff --git a/src/providers/grass/qgsgrassrasterprovidermodule.cpp b/src/providers/grass/qgsgrassrasterprovidermodule.cpp index 9bf25b467094..46deef41be7d 100644 --- a/src/providers/grass/qgsgrassrasterprovidermodule.cpp +++ b/src/providers/grass/qgsgrassrasterprovidermodule.cpp @@ -25,12 +25,12 @@ QGISEXTERN QgsGrassRasterProvider * classFactory( const QString *uri ) QGISEXTERN QString providerKey() { - return QString( "grassraster" ); + return QStringLiteral( "grassraster" ); } QGISEXTERN QString description() { - return QString( "GRASS %1 raster provider" ).arg( GRASS_VERSION_MAJOR ); + return QStringLiteral( "GRASS %1 raster provider" ).arg( GRASS_VERSION_MAJOR ); } QGISEXTERN bool isProvider() diff --git a/src/providers/grass/qgsgrassvector.cpp b/src/providers/grass/qgsgrassvector.cpp index 9400c29dd923..523e0f27f3a7 100644 --- a/src/providers/grass/qgsgrassvector.cpp +++ b/src/providers/grass/qgsgrassvector.cpp @@ -163,19 +163,19 @@ QgsFields QgsGrassVectorLayer::fields() switch ( ctype ) { case DB_C_TYPE_INT: - type = "int"; + type = QStringLiteral( "int" ); qtype = QVariant::Int; break; case DB_C_TYPE_DOUBLE: - type = "double"; + type = QStringLiteral( "double" ); qtype = QVariant::Double; break; case DB_C_TYPE_STRING: - type = "string"; + type = QStringLiteral( "string" ); qtype = QVariant::String; break; case DB_C_TYPE_DATETIME: - type = "datetime"; + type = QStringLiteral( "datetime" ); qtype = QVariant::String; break; } diff --git a/src/providers/grass/qgsgrassvectormap.cpp b/src/providers/grass/qgsgrassvectormap.cpp index 61969d6df02f..4a6e263b2459 100644 --- a/src/providers/grass/qgsgrassvectormap.cpp +++ b/src/providers/grass/qgsgrassvectormap.cpp @@ -159,7 +159,7 @@ bool QgsGrassVectorMap::openMap() } else if ( level == 1 ) { - QMessageBox::StandardButton ret = QMessageBox::question( 0, "Warning", + QMessageBox::StandardButton ret = QMessageBox::question( 0, QStringLiteral( "Warning" ), QObject::tr( "GRASS vector map %1 does not have topology. Build topology?" ).arg( mGrassObject.name() ), QMessageBox::Ok | QMessageBox::Cancel ); @@ -178,7 +178,7 @@ bool QgsGrassVectorMap::openMap() } G_CATCH( QgsGrass::Exception &e ) { - QgsGrass::warning( QString( "Cannot open GRASS vector: %1" ).arg( e.what() ) ); + QgsGrass::warning( QStringLiteral( "Cannot open GRASS vector: %1" ).arg( e.what() ) ); QgsGrass::unlock(); return false; } @@ -196,7 +196,7 @@ bool QgsGrassVectorMap::openMap() } G_CATCH( QgsGrass::Exception &e ) { - QgsGrass::warning( QString( "Cannot build topology: %1" ).arg( e.what() ) ); + QgsGrass::warning( QStringLiteral( "Cannot build topology: %1" ).arg( e.what() ) ); QgsGrass::unlock(); return false; } diff --git a/src/providers/grass/qgsgrassvectormap.h b/src/providers/grass/qgsgrassvectormap.h index e545e1eabe87..13115c4faea7 100644 --- a/src/providers/grass/qgsgrassvectormap.h +++ b/src/providers/grass/qgsgrassvectormap.h @@ -144,7 +144,7 @@ class GRASS_LIB_EXPORT QgsGrassVectorMap : public QObject * @param type geometry type */ TopoSymbol topoSymbol( int lid ); - static QString topoSymbolFieldName() { return "topo_symbol" ; } + static QString topoSymbolFieldName() { return QStringLiteral( "topo_symbol" ) ; } void printDebug(); diff --git a/src/providers/grass/qgsgrassvectormaplayer.cpp b/src/providers/grass/qgsgrassvectormaplayer.cpp index 21e178aabec9..66ab875af61f 100644 --- a/src/providers/grass/qgsgrassvectormaplayer.cpp +++ b/src/providers/grass/qgsgrassvectormaplayer.cpp @@ -162,19 +162,19 @@ void QgsGrassVectorMapLayer::load() switch ( ctype ) { case DB_C_TYPE_INT: - ctypeStr = "integer"; + ctypeStr = QStringLiteral( "integer" ); qtype = QVariant::Int; break; case DB_C_TYPE_DOUBLE: - ctypeStr = "double"; + ctypeStr = QStringLiteral( "double" ); qtype = QVariant::Double; break; case DB_C_TYPE_STRING: - ctypeStr = "string"; + ctypeStr = QStringLiteral( "string" ); qtype = QVariant::String; break; case DB_C_TYPE_DATETIME: - ctypeStr = "datetime"; + ctypeStr = QStringLiteral( "datetime" ); qtype = QVariant::String; break; } @@ -288,7 +288,7 @@ void QgsGrassVectorMapLayer::load() if ( mTableFields.size() == 0 ) { mKeyColumn = 0; - mTableFields.append( QgsField( "cat", QVariant::Int, "integer" ) ); + mTableFields.append( QgsField( QStringLiteral( "cat" ), QVariant::Int, QStringLiteral( "integer" ) ) ); QPair<double, double> minMax( 0, 0 ); if ( cidxFieldIndex() >= 0 ) @@ -390,7 +390,7 @@ QString QgsGrassVectorMapLayer::quotedValue( const QVariant& value ) { if ( value.isNull() ) { - return "NULL"; + return QStringLiteral( "NULL" ); } switch ( value.type() ) @@ -406,10 +406,10 @@ QString QgsGrassVectorMapLayer::quotedValue( const QVariant& value ) default: case QVariant::String: QString v = value.toString(); - v.replace( "'", "''" ); - if ( v.contains( "\\" ) ) + v.replace( QLatin1String( "'" ), QLatin1String( "''" ) ); + if ( v.contains( QLatin1String( "\\" ) ) ) { - v.replace( "\\", "\\\\" ); + v.replace( QLatin1String( "\\" ), QLatin1String( "\\\\" ) ); } return v.prepend( "'" ).append( "'" ); } @@ -427,7 +427,7 @@ dbDriver * QgsGrassVectorMapLayer::openDriver( QString &error ) else { QgsDebugMsg( "Field info found -> open database" ); - QString err = QString( "Cannot open database %1 by driver %2" ).arg( mFieldInfo->database, mFieldInfo->driver ); + QString err = QStringLiteral( "Cannot open database %1 by driver %2" ).arg( mFieldInfo->database, mFieldInfo->driver ); QgsGrass::lock(); G_TRY { @@ -462,7 +462,7 @@ dbDriver * QgsGrassVectorMapLayer::openDriver( QString &error ) void QgsGrassVectorMapLayer::addTopoField( QgsFields &fields ) { QString comment = tr( "Virtual topology symbol field" ); - QgsField topoField = QgsField( QgsGrassVectorMap::topoSymbolFieldName(), QVariant::Int, "integer", 0, 0, comment ); + QgsField topoField = QgsField( QgsGrassVectorMap::topoSymbolFieldName(), QVariant::Int, QStringLiteral( "integer" ), 0, 0, comment ); fields.append( topoField ); } @@ -602,7 +602,7 @@ void QgsGrassVectorMapLayer::createTable( const QgsFields &fields, QString &erro QgsDebugMsg( "Database opened -> create table" ); QgsFields catFields; - catFields.append( QgsField( mFieldInfo->key, QVariant::Int, "integer" ) ); + catFields.append( QgsField( mFieldInfo->key, QVariant::Int, QStringLiteral( "integer" ) ) ); Q_FOREACH ( const QgsField& field, fields ) { catFields.append( field ); @@ -632,7 +632,7 @@ void QgsGrassVectorMapLayer::createTable( const QgsFields &fields, QString &erro error = tr( "Cannot create link to the table." ); QgsDebugMsg( error ); // delete created table - QString query = QString( "DROP TABLE %1" ).arg( mFieldInfo->table ); + QString query = QStringLiteral( "DROP TABLE %1" ).arg( mFieldInfo->table ); QString dropError; executeSql( query, dropError ); if ( !dropError.isEmpty() ) @@ -683,14 +683,14 @@ void QgsGrassVectorMapLayer::addColumn( const QgsField &field, QString &error ) else // the table alread exists { QString type = field.typeName(); - if ( type == "varchar" ) + if ( type == QLatin1String( "varchar" ) ) { if ( field.length() > 0 ) { - type = QString( "%1(%2)" ).arg( type ).arg( field.length() ); + type = QStringLiteral( "%1(%2)" ).arg( type ).arg( field.length() ); } } - QString query = QString( "ALTER TABLE %1 ADD COLUMN %2 %3" ).arg( mFieldInfo->table, field.name(), type ); + QString query = QStringLiteral( "ALTER TABLE %1 ADD COLUMN %2 %3" ).arg( mFieldInfo->table, field.name(), type ); executeSql( query, error ); if ( error.isEmpty() ) @@ -708,7 +708,7 @@ void QgsGrassVectorMapLayer::addColumn( const QgsField &field, QString &error ) { QVariant value = mAttributes.value( cat ).value( index ); QString valueString = quotedValue( value ); - QString query = QString( "UPDATE %1 SET %2 = %3 WHERE %4 = %5" ) + QString query = QStringLiteral( "UPDATE %1 SET %2 = %3 WHERE %4 = %5" ) .arg( mFieldInfo->table, field.name(), valueString, keyColumnName() ).arg( cat ); QString err; executeSql( query, err ); @@ -718,7 +718,7 @@ void QgsGrassVectorMapLayer::addColumn( const QgsField &field, QString &error ) } if ( errors.size() > 5 ) { - error = tr( "Errors updating restored column, update interrupted" ) + " : " + errors.join( "; " ); + error = tr( "Errors updating restored column, update interrupted" ) + " : " + errors.join( QStringLiteral( "; " ) ); break; } } @@ -747,7 +747,7 @@ void QgsGrassVectorMapLayer::deleteColumn( const QgsField &field, QString &error } // SQLite does not support DROP COLUMN - if ( QString( mFieldInfo->driver ) == "sqlite" ) + if ( QString( mFieldInfo->driver ) == QLatin1String( "sqlite" ) ) { QStringList columns; Q_FOREACH ( const QgsField& f, mTableFields ) @@ -758,13 +758,13 @@ void QgsGrassVectorMapLayer::deleteColumn( const QgsField &field, QString &error } } QStringList queries; - queries << "BEGIN TRANSACTION"; - queries << QString( "CREATE TEMPORARY TABLE %1_tmp_drop_column AS SELECT %2 FROM %1" ).arg( mFieldInfo->table, columns.join( "," ) ); - queries << QString( "DROP TABLE %1" ).arg( mFieldInfo->table ); - queries << QString( "CREATE TABLE %1 AS SELECT * FROM %1_tmp_drop_column" ).arg( mFieldInfo->table ); - queries << QString( "DROP TABLE %1_tmp_drop_column" ).arg( mFieldInfo->table ); - queries << QString( "CREATE UNIQUE INDEX %1_%2 ON %1 (%2)" ).arg( mFieldInfo->table, mFieldInfo->key ); - queries << "COMMIT"; + queries << QStringLiteral( "BEGIN TRANSACTION" ); + queries << QStringLiteral( "CREATE TEMPORARY TABLE %1_tmp_drop_column AS SELECT %2 FROM %1" ).arg( mFieldInfo->table, columns.join( QStringLiteral( "," ) ) ); + queries << QStringLiteral( "DROP TABLE %1" ).arg( mFieldInfo->table ); + queries << QStringLiteral( "CREATE TABLE %1 AS SELECT * FROM %1_tmp_drop_column" ).arg( mFieldInfo->table ); + queries << QStringLiteral( "DROP TABLE %1_tmp_drop_column" ).arg( mFieldInfo->table ); + queries << QStringLiteral( "CREATE UNIQUE INDEX %1_%2 ON %1 (%2)" ).arg( mFieldInfo->table, mFieldInfo->key ); + queries << QStringLiteral( "COMMIT" ); // Execute one after another to get possible error Q_FOREACH ( const QString& query, queries ) { @@ -778,7 +778,7 @@ void QgsGrassVectorMapLayer::deleteColumn( const QgsField &field, QString &error } else { - QString query = QString( "ALTER TABLE %1 DROP COLUMN %2" ).arg( mFieldInfo->table, field.name() ); + QString query = QStringLiteral( "ALTER TABLE %1 DROP COLUMN %2" ).arg( mFieldInfo->table, field.name() ); QgsDebugMsg( "query = " + query ); executeSql( query, error ); } @@ -851,7 +851,7 @@ void QgsGrassVectorMapLayer::insertAttributes( int cat, const QgsFeature &featur int cacheIndex = mAttributeFields.indexFromName( name ); if ( cacheIndex < 0 ) // should not happen { - error = QString( "Field %1 not found in cached attributes" ).arg( name ); + error = QStringLiteral( "Field %1 not found in cached attributes" ).arg( name ); return; } else @@ -873,8 +873,8 @@ void QgsGrassVectorMapLayer::insertAttributes( int cat, const QgsFeature &featur } } - QString query = QString( "INSERT INTO %1 ( %2 ) VALUES ( %3 )" ).arg( mFieldInfo->table, - names.join( ", " ), values.join( "," ) ); + QString query = QStringLiteral( "INSERT INTO %1 ( %2 ) VALUES ( %3 )" ).arg( mFieldInfo->table, + names.join( QStringLiteral( ", " ) ), values.join( QStringLiteral( "," ) ) ); executeSql( query, error ); if ( error.isEmpty() ) { @@ -920,7 +920,7 @@ void QgsGrassVectorMapLayer::reinsertAttributes( int cat, QString &error ) } } - QString query = QString( "INSERT INTO %1 ( %2 ) VALUES ( %3 )" ).arg( mFieldInfo->table, names.join( ", " ), values.join( "," ) ); + QString query = QStringLiteral( "INSERT INTO %1 ( %2 ) VALUES ( %3 )" ).arg( mFieldInfo->table, names.join( QStringLiteral( ", " ) ), values.join( QStringLiteral( "," ) ) ); executeSql( query, error ); } else @@ -992,8 +992,8 @@ void QgsGrassVectorMapLayer::updateAttributes( int cat, QgsFeature &feature, QSt return; } - QString query = QString( "UPDATE %1 SET %2 WHERE %3 = %4" ).arg( mFieldInfo->table, - updates.join( ", " ), mFieldInfo->key ).arg( cat ); + QString query = QStringLiteral( "UPDATE %1 SET %2 WHERE %3 = %4" ).arg( mFieldInfo->table, + updates.join( QStringLiteral( ", " ) ), mFieldInfo->key ).arg( cat ); executeSql( query, error ); if ( error.isEmpty() ) @@ -1010,7 +1010,7 @@ void QgsGrassVectorMapLayer::deleteAttribute( int cat, QString &error ) { QgsDebugMsg( QString( "mField = %1 cat = %2" ).arg( mField ).arg( cat ) ); - QString query = QString( "DELETE FROM %1 WHERE %2 = %3" ).arg( mFieldInfo->table, mFieldInfo->key ).arg( cat ); + QString query = QStringLiteral( "DELETE FROM %1 WHERE %2 = %3" ).arg( mFieldInfo->table, mFieldInfo->key ).arg( cat ); executeSql( query, error ); } @@ -1094,7 +1094,7 @@ void QgsGrassVectorMapLayer::changeAttributeValue( int cat, const QgsField& fiel if ( exists ) { - query = QString( "UPDATE %1 SET %2 = %3 WHERE %4 = %5" ).arg( mFieldInfo->table, + query = QStringLiteral( "UPDATE %1 SET %2 = %3 WHERE %4 = %5" ).arg( mFieldInfo->table, field.name(), valueString, mFieldInfo->key ).arg( cat ); } else @@ -1105,8 +1105,8 @@ void QgsGrassVectorMapLayer::changeAttributeValue( int cat, const QgsField& fiel values << QString::number( cat ); names << field.name(); values << quotedValue( value ); - query = QString( "INSERT INTO %1 ( %2 ) VALUES ( %3 )" ).arg( mFieldInfo->table, - names.join( ", " ), values.join( "," ) ); + query = QStringLiteral( "INSERT INTO %1 ( %2 ) VALUES ( %3 )" ).arg( mFieldInfo->table, + names.join( QStringLiteral( ", " ) ), values.join( QStringLiteral( "," ) ) ); } QgsDebugMsg( QString( "query: %1" ).arg( query ) ); diff --git a/src/providers/memory/qgsmemoryprovider.cpp b/src/providers/memory/qgsmemoryprovider.cpp index 88c13aa9f28b..98b4be42adf3 100644 --- a/src/providers/memory/qgsmemoryprovider.cpp +++ b/src/providers/memory/qgsmemoryprovider.cpp @@ -27,8 +27,8 @@ #include <QRegExp> -static const QString TEXT_PROVIDER_KEY = "memory"; -static const QString TEXT_PROVIDER_DESCRIPTION = "Memory provider"; +static const QString TEXT_PROVIDER_KEY = QStringLiteral( "memory" ); +static const QString TEXT_PROVIDER_DESCRIPTION = QStringLiteral( "Memory provider" ); QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) : QgsVectorDataProvider( uri ) @@ -38,16 +38,16 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) // (ie, just 'point', 'line', 'polygon') QUrl url = QUrl::fromEncoded( uri.toUtf8() ); QString geometry; - if ( url.hasQueryItem( "geometry" ) ) + if ( url.hasQueryItem( QStringLiteral( "geometry" ) ) ) { - geometry = url.queryItemValue( "geometry" ); + geometry = url.queryItemValue( QStringLiteral( "geometry" ) ); } else { geometry = url.path(); } - if ( geometry.toLower() == "none" ) + if ( geometry.toLower() == QLatin1String( "none" ) ) { mWkbType = QgsWkbTypes::NoGeometry; } @@ -56,46 +56,46 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) mWkbType = QgsWkbTypes::parseType( geometry ); } - if ( url.hasQueryItem( "crs" ) ) + if ( url.hasQueryItem( QStringLiteral( "crs" ) ) ) { - QString crsDef = url.queryItemValue( "crs" ); + QString crsDef = url.queryItemValue( QStringLiteral( "crs" ) ); mCrs.createFromString( crsDef ); } mNextFeatureId = 1; setNativeTypes( QList< NativeType >() - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 0, 10 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 10 ) // Decimal number from OGR/Shapefile/dbf may come with length up to 32 and // precision up to length-2 = 30 (default, if width is not specified in dbf is length = 24 precision = 15) // We know that double (QVariant::Double) has only 15-16 significant numbers, // but setting that correct limits would disable the use of memory provider with // data from Shapefiles. In any case, the data are handled as doubles. // So the limits set here are not correct but enable use of data from Shapefiles. - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "double", QVariant::Double, 0, 32, 0, 30 ) - << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), "string", QVariant::String, 0, 255 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double" ), QVariant::Double, 0, 32, 0, 30 ) + << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), QStringLiteral( "string" ), QVariant::String, 0, 255 ) // date type - << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Time" ), "time", QVariant::Time, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), "datetime", QVariant::DateTime, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime, -1, -1, -1, -1 ) // integer types - << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), "int2", QVariant::Int, -1, -1, 0, 0 ) - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), "int4", QVariant::Int, -1, -1, 0, 0 ) - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), "int8", QVariant::LongLong, -1, -1, 0, 0 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 20, 0, 20 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 20, 0, 20 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), QStringLiteral( "int2" ), QVariant::Int, -1, -1, 0, 0 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), QStringLiteral( "int4" ), QVariant::Int, -1, -1, 0, 0 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), QStringLiteral( "int8" ), QVariant::LongLong, -1, -1, 0, 0 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 20, 0, 20 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 20, 0, 20 ) // floating point - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double precision", QVariant::Double, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 ) // string types - << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 ) ); - if ( url.hasQueryItem( "field" ) ) + if ( url.hasQueryItem( QStringLiteral( "field" ) ) ) { QList<QgsField> attributes; QRegExp reFieldDef( "\\:" @@ -104,13 +104,13 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) "(?:\\,(\\d+))?" // precision "\\))?(\\[\\])?" // array "$", Qt::CaseInsensitive ); - QStringList fields = url.allQueryItemValues( "field" ); + QStringList fields = url.allQueryItemValues( QStringLiteral( "field" ) ); for ( int i = 0; i < fields.size(); i++ ) { QString name = fields.at( i ); QVariant::Type type = QVariant::String; QVariant::Type subType = QVariant::Invalid; - QString typeName( "string" ); + QString typeName( QStringLiteral( "string" ) ); int length = 255; int precision = 0; @@ -119,65 +119,65 @@ QgsMemoryProvider::QgsMemoryProvider( const QString& uri ) { name = name.mid( 0, pos ); typeName = reFieldDef.cap( 1 ).toLower(); - if ( typeName == "int" || typeName == "integer" ) + if ( typeName == QLatin1String( "int" ) || typeName == QLatin1String( "integer" ) ) { type = QVariant::Int; - typeName = "integer"; + typeName = QStringLiteral( "integer" ); length = -1; } - else if ( typeName == "int8" || typeName == "long" ) + else if ( typeName == QLatin1String( "int8" ) || typeName == QLatin1String( "long" ) ) { type = QVariant::LongLong; - typeName = "int8"; + typeName = QStringLiteral( "int8" ); length = -1; } - else if ( typeName == "real" || typeName == "double" ) + else if ( typeName == QLatin1String( "real" ) || typeName == QLatin1String( "double" ) ) { type = QVariant::Double; - typeName = "double"; + typeName = QStringLiteral( "double" ); length = 20; precision = 5; } - else if ( typeName == "date" ) + else if ( typeName == QLatin1String( "date" ) ) { type = QVariant::Date; - typeName = "date"; + typeName = QStringLiteral( "date" ); length = -1; } - else if ( typeName == "time" ) + else if ( typeName == QLatin1String( "time" ) ) { type = QVariant::Time; - typeName = "time"; + typeName = QStringLiteral( "time" ); length = -1; } - else if ( typeName == "datetime" ) + else if ( typeName == QLatin1String( "datetime" ) ) { type = QVariant::DateTime; - typeName = "datetime"; + typeName = QStringLiteral( "datetime" ); length = -1; } - if ( reFieldDef.cap( 2 ) != "" ) + if ( reFieldDef.cap( 2 ) != QLatin1String( "" ) ) { length = reFieldDef.cap( 2 ).toInt(); } - if ( reFieldDef.cap( 3 ) != "" ) + if ( reFieldDef.cap( 3 ) != QLatin1String( "" ) ) { precision = reFieldDef.cap( 3 ).toInt(); } - if ( reFieldDef.cap( 4 ) != "" ) + if ( reFieldDef.cap( 4 ) != QLatin1String( "" ) ) { //array subType = type; type = ( subType == QVariant::String ? QVariant::StringList : QVariant::List ); } } - if ( name != "" ) - attributes.append( QgsField( name, type, typeName, length, precision, "", subType ) ); + if ( name != QLatin1String( "" ) ) + attributes.append( QgsField( name, type, typeName, length, precision, QLatin1String( "" ), subType ) ); } addAttributes( attributes ); } - if ( url.hasQueryItem( "index" ) && url.queryItemValue( "index" ) == "yes" ) + if ( url.hasQueryItem( QStringLiteral( "index" ) ) && url.queryItemValue( QStringLiteral( "index" ) ) == QLatin1String( "yes" ) ) { createSpatialIndex(); } @@ -198,15 +198,15 @@ QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const { Q_UNUSED( expandAuthConfig ) - QUrl uri( "memory" ); + QUrl uri( QStringLiteral( "memory" ) ); QString geometry = QgsWkbTypes::displayString( mWkbType ); - uri.addQueryItem( "geometry", geometry ); + uri.addQueryItem( QStringLiteral( "geometry" ), geometry ); if ( mCrs.isValid() ) { - QString crsDef( "" ); + QString crsDef( QLatin1String( "" ) ); QString authid = mCrs.authid(); - if ( authid.startsWith( "EPSG:" ) ) + if ( authid.startsWith( QLatin1String( "EPSG:" ) ) ) { crsDef = authid; } @@ -215,18 +215,18 @@ QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const int srid = mCrs.postgisSrid(); if ( srid ) { - crsDef = QString( "postgis:%1" ).arg( srid ); + crsDef = QStringLiteral( "postgis:%1" ).arg( srid ); } else { - crsDef = QString( "wkt:%1" ).arg( mCrs.toWkt() ); + crsDef = QStringLiteral( "wkt:%1" ).arg( mCrs.toWkt() ); } } - uri.addQueryItem( "crs", crsDef ); + uri.addQueryItem( QStringLiteral( "crs" ), crsDef ); } if ( mSpatialIndex ) { - uri.addQueryItem( "index", "yes" ); + uri.addQueryItem( QStringLiteral( "index" ), QStringLiteral( "yes" ) ); } QgsAttributeList attrs = const_cast<QgsMemoryProvider *>( this )->attributeIndexes(); @@ -234,8 +234,8 @@ QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const { QgsField field = mFields.at( attrs[i] ); QString fieldDef = field.name(); - fieldDef.append( QString( ":%2(%3,%4)" ).arg( field.typeName() ).arg( field.length() ).arg( field.precision() ) ); - uri.addQueryItem( "field", fieldDef ); + fieldDef.append( QStringLiteral( ":%2(%3,%4)" ).arg( field.typeName() ).arg( field.length() ).arg( field.precision() ) ); + uri.addQueryItem( QStringLiteral( "field" ), fieldDef ); } return QString( uri.toEncoded() ); @@ -244,7 +244,7 @@ QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const QString QgsMemoryProvider::storageType() const { - return "Memory storage"; + return QStringLiteral( "Memory storage" ); } QgsFeatureIterator QgsMemoryProvider::getFeatures( const QgsFeatureRequest& request ) const diff --git a/src/providers/mssql/qgsmssqldataitems.cpp b/src/providers/mssql/qgsmssqldataitems.cpp index 1b7f2729eeb4..422ecb3d1cf5 100644 --- a/src/providers/mssql/qgsmssqldataitems.cpp +++ b/src/providers/mssql/qgsmssqldataitems.cpp @@ -43,7 +43,7 @@ QgsMssqlConnectionItem::QgsMssqlConnectionItem( QgsDataItem* parent, QString nam , mColumnTypeThread( nullptr ) { mCapabilities |= Fast; - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); } QgsMssqlConnectionItem::~QgsMssqlConnectionItem() @@ -58,12 +58,12 @@ void QgsMssqlConnectionItem::readConnectionSettings() mService = settings.value( key + "/service" ).toString(); mHost = settings.value( key + "/host" ).toString(); mDatabase = settings.value( key + "/database" ).toString(); - if ( settings.value( key + "/saveUsername" ).toString() == "true" ) + if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) ) { mUsername = settings.value( key + "/username" ).toString(); } - if ( settings.value( key + "/savePassword" ).toString() == "true" ) + if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) ) { mPassword = settings.value( key + "/password" ).toString(); } @@ -76,7 +76,7 @@ void QgsMssqlConnectionItem::readConnectionSettings() if ( !mService.isEmpty() ) mConnInfo += " service='" + mService + '\''; if ( mUseEstimatedMetadata ) - mConnInfo += " estimatedmetadata=true"; + mConnInfo += QLatin1String( " estimatedmetadata=true" ); } void QgsMssqlConnectionItem::stop() @@ -137,19 +137,19 @@ QVector<QgsDataItem*> QgsMssqlConnectionItem::createChildren() QString connectionName = db.connectionName(); // build sql statement - QString query( "select " ); + QString query( QStringLiteral( "select " ) ); if ( mUseGeometryColumns ) { - query += "f_table_schema, f_table_name, f_geometry_column, srid, geometry_type from geometry_columns"; + query += QLatin1String( "f_table_schema, f_table_name, f_geometry_column, srid, geometry_type from geometry_columns" ); } else { - query += "sys.schemas.name, sys.objects.name, sys.columns.name, null, 'GEOMETRY' from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V')"; + query += QLatin1String( "sys.schemas.name, sys.objects.name, sys.columns.name, null, 'GEOMETRY' from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V')" ); } if ( mAllowGeometrylessTables ) { - query += " union all select sys.schemas.name, sys.objects.name, null, null, 'NONE' from sys.objects join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where not exists (select * from sys.columns sc1 join sys.types on sc1.system_type_id = sys.types.system_type_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and sys.objects.object_id = sc1.object_id) and (sys.objects.type = 'U' or sys.objects.type = 'V')"; + query += QLatin1String( " union all select sys.schemas.name, sys.objects.name, null, null, 'NONE' from sys.objects join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where not exists (select * from sys.columns sc1 join sys.types on sc1.system_type_id = sys.types.system_type_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and sys.objects.object_id = sc1.object_id) and (sys.objects.type = 'U' or sys.objects.type = 'V')" ); } // issue the sql query @@ -214,7 +214,7 @@ QVector<QgsDataItem*> QgsMssqlConnectionItem::createChildren() if ( !layer.geometryColName.isNull() ) { - if ( type == "GEOMETRY" || type.isNull() || srid.isEmpty() ) + if ( type == QLatin1String( "GEOMETRY" ) || type.isNull() || srid.isEmpty() ) { if ( !mColumnTypeThread ) { @@ -399,7 +399,7 @@ bool QgsMssqlConnectionItem::handleDrop( const QMimeData* data, const QString& t QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data ); Q_FOREACH ( const QgsMimeDataUtils::Uri& u, lst ) { - if ( u.layerType != "vector" ) + if ( u.layerType != QLatin1String( "vector" ) ) { importResults.append( tr( "%1: Not a vector layer!" ).arg( u.name ) ); hasError = true; // only vectors can be imported @@ -414,7 +414,7 @@ bool QgsMssqlConnectionItem::handleDrop( const QMimeData* data, const QString& t QString tableName; if ( !toSchema.isEmpty() ) { - tableName = QString( "\"%1\".\"%2\"" ).arg( toSchema, u.name ); + tableName = QStringLiteral( "\"%1\".\"%2\"" ).arg( toSchema, u.name ); } else { @@ -423,18 +423,18 @@ bool QgsMssqlConnectionItem::handleDrop( const QMimeData* data, const QString& t QString uri = connInfo() + " table=" + tableName; if ( srcLayer->geometryType() != QgsWkbTypes::NullGeometry ) - uri += " (geom)"; + uri += QLatin1String( " (geom)" ); QgsVectorLayerImport::ImportError err; QString importError; - err = QgsVectorLayerImport::importLayer( srcLayer, uri, "mssql", srcLayer->crs(), false, &importError, false, nullptr, progress ); + err = QgsVectorLayerImport::importLayer( srcLayer, uri, QStringLiteral( "mssql" ), srcLayer->crs(), false, &importError, false, nullptr, progress ); if ( err == QgsVectorLayerImport::NoError ) importResults.append( tr( "%1: OK!" ).arg( u.name ) ); else if ( err == QgsVectorLayerImport::ErrUserCancelled ) cancelled = true; else { - importResults.append( QString( "%1: %2" ).arg( u.name, importError ) ); + importResults.append( QStringLiteral( "%1: %2" ).arg( u.name, importError ) ); hasError = true; } } @@ -457,7 +457,7 @@ bool QgsMssqlConnectionItem::handleDrop( const QMimeData* data, const QString& t } else if ( hasError ) { - QMessageBox::warning( nullptr, tr( "Import to MSSQL database" ), tr( "Failed to import some layers!\n\n" ) + importResults.join( "\n" ) ); + QMessageBox::warning( nullptr, tr( "Import to MSSQL database" ), tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ) ); } else { @@ -475,7 +475,7 @@ bool QgsMssqlConnectionItem::handleDrop( const QMimeData* data, const QString& t // --------------------------------------------------------------------------- QgsMssqlLayerItem::QgsMssqlLayerItem( QgsDataItem* parent, QString name, QString path, QgsLayerItem::LayerType layerType, QgsMssqlLayerProperty layerProperty ) - : QgsLayerItem( parent, name, path, QString(), layerType, "mssql" ) + : QgsLayerItem( parent, name, path, QString(), layerType, QStringLiteral( "mssql" ) ) , mLayerProperty( layerProperty ) { mUri = createUri(); @@ -514,7 +514,7 @@ QString QgsMssqlLayerItem::createUri() QgsMssqlSchemaItem::QgsMssqlSchemaItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconDbSchema.png"; + mIconName = QStringLiteral( "mIconDbSchema.png" ); //not fertile, since children are created by QgsMssqlConnectionItem mCapabilities &= ~( Fertile ); } @@ -580,7 +580,7 @@ QgsMssqlLayerItem* QgsMssqlSchemaItem::addLayer( const QgsMssqlLayerProperty& la layerType = QgsLayerItem::Polygon; break; default: - if ( layerProperty.type == "NONE" && layerProperty.geometryColName.isEmpty() ) + if ( layerProperty.type == QLatin1String( "NONE" ) && layerProperty.geometryColName.isEmpty() ) { layerType = QgsLayerItem::TableLayer; tip = tr( "as geometryless table" ); @@ -605,7 +605,7 @@ QgsMssqlLayerItem* QgsMssqlSchemaItem::addLayer( const QgsMssqlLayerProperty& la QgsMssqlRootItem::QgsMssqlRootItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconMssql.svg"; + mIconName = QStringLiteral( "mIconMssql.svg" ); populate(); } @@ -617,7 +617,7 @@ QVector<QgsDataItem*> QgsMssqlRootItem::createChildren() { QVector<QgsDataItem*> connections; QSettings settings; - settings.beginGroup( "/MSSQL/connections" ); + settings.beginGroup( QStringLiteral( "/MSSQL/connections" ) ); Q_FOREACH ( const QString& connName, settings.childGroups() ) { connections << new QgsMssqlConnectionItem( this, connName, mPath + '/' + connName ); diff --git a/src/providers/mssql/qgsmssqlexpressioncompiler.cpp b/src/providers/mssql/qgsmssqlexpressioncompiler.cpp index be3a9229cb42..c926aaa6cb33 100644 --- a/src/providers/mssql/qgsmssqlexpressioncompiler.cpp +++ b/src/providers/mssql/qgsmssqlexpressioncompiler.cpp @@ -37,14 +37,14 @@ QgsSqlExpressionCompiler::Result QgsMssqlExpressionCompiler::compileNode( const switch ( bin->op() ) { case QgsExpression::boPow: - result = QString( "power(%1,%2)" ).arg( op1, op2 ); + result = QStringLiteral( "power(%1,%2)" ).arg( op1, op2 ); return result1 == Partial || result2 == Partial ? Partial : Complete; case QgsExpression::boRegexp: return Fail; //not supported, regexp syntax is too different to Qt case QgsExpression::boConcat: - result = QString( "%1 + %2" ).arg( op1, op2 ); + result = QStringLiteral( "%1 + %2" ).arg( op1, op2 ); return result1 == Partial || result2 == Partial ? Partial : Complete; default: diff --git a/src/providers/mssql/qgsmssqlfeatureiterator.cpp b/src/providers/mssql/qgsmssqlfeatureiterator.cpp index 616a2e1c7066..ded3c43ca635 100644 --- a/src/providers/mssql/qgsmssqlfeatureiterator.cpp +++ b/src/providers/mssql/qgsmssqlfeatureiterator.cpp @@ -71,7 +71,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) // build sql statement // note: 'SELECT ' is added later, to account for 'SELECT TOP...' type queries - mStatement += QString( "[%1]" ).arg( mSource->mFidColName ); + mStatement += QStringLiteral( "[%1]" ).arg( mSource->mFidColName ); mFidCol = mSource->mFields.indexFromName( mSource->mFidColName ); mAttributesToFetch.append( mFidCol ); @@ -93,7 +93,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) if ( mSource->mFidColName == fieldname ) continue; - mStatement += QString( ",[%1]" ).arg( fieldname ); + mStatement += QStringLiteral( ",[%1]" ).arg( fieldname ); mAttributesToFetch.append( i ); } @@ -104,10 +104,10 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) ) && mSource->isSpatial() ) { - mStatement += QString( ",[%1]" ).arg( mSource->mGeometryColName ); + mStatement += QStringLiteral( ",[%1]" ).arg( mSource->mGeometryColName ); } - mStatement += QString( "FROM [%1].[%2]" ).arg( mSource->mSchemaName, mSource->mTableName ); + mStatement += QStringLiteral( "FROM [%1].[%2]" ).arg( mSource->mSchemaName, mSource->mTableName ); bool filterAdded = false; // set spatial filter @@ -125,7 +125,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) << qgsDoubleToString( request.filterRect().xMinimum() ) << ' ' << qgsDoubleToString( request.filterRect().yMaximum() ) << ", " << qgsDoubleToString( request.filterRect().xMinimum() ) << ' ' << qgsDoubleToString( request.filterRect().yMinimum() ); - mStatement += QString( " where [%1].STIsValid() = 1 AND [%1].STIntersects([%2]::STGeomFromText('POLYGON((%3))',%4)) = 1" ).arg( + mStatement += QStringLiteral( " where [%1].STIsValid() = 1 AND [%1].STIntersects([%2]::STGeomFromText('POLYGON((%3))',%4)) = 1" ).arg( mSource->mGeometryColName, mSource->mGeometryColType, r, QString::number( mSource->mSRId ) ); filterAdded = true; } @@ -133,12 +133,12 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) // set fid filter if ( request.filterType() == QgsFeatureRequest::FilterFid && !mSource->mFidColName.isEmpty() ) { - QString fidfilter = QString( " [%1] = %2" ).arg( mSource->mFidColName, FID_TO_STRING( request.filterFid() ) ); + QString fidfilter = QStringLiteral( " [%1] = %2" ).arg( mSource->mFidColName, FID_TO_STRING( request.filterFid() ) ); // set attribute filter if ( !filterAdded ) - mStatement += " WHERE "; + mStatement += QLatin1String( " WHERE " ); else - mStatement += " AND "; + mStatement += QLatin1String( " AND " ); mStatement += fidfilter; filterAdded = true; @@ -147,7 +147,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) && !mRequest.filterFids().isEmpty() ) { QString delim; - QString inClause = QString( "%1 IN (" ).arg( mSource->mFidColName ); + QString inClause = QStringLiteral( "%1 IN (" ).arg( mSource->mFidColName ); Q_FOREACH ( QgsFeatureId featureId, mRequest.filterFids() ) { inClause += delim + FID_TO_STRING( featureId ); @@ -156,9 +156,9 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) inClause.append( ')' ); if ( !filterAdded ) - mStatement += " WHERE "; + mStatement += QLatin1String( " WHERE " ); else - mStatement += " AND "; + mStatement += QLatin1String( " AND " ); mStatement += inClause; filterAdded = true; @@ -178,7 +178,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) mCompileStatus = NoCompilation; if ( request.filterType() == QgsFeatureRequest::FilterExpression ) { - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { QgsMssqlExpressionCompiler compiler = QgsMssqlExpressionCompiler( mSource ); QgsSqlExpressionCompiler::Result result = compiler.compile( request.filterExpression() ); @@ -209,7 +209,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) QStringList orderByParts; mOrderByCompiled = true; - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { Q_FOREACH ( const QgsFeatureRequest::OrderByClause& clause, request.orderBy() ) { @@ -250,9 +250,9 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) if ( request.limit() >= 0 && limitAtProvider ) { - mStatement.prepend( QString( "SELECT TOP %1 " ).arg( mRequest.limit() ) ); + mStatement.prepend( QStringLiteral( "SELECT TOP %1 " ).arg( mRequest.limit() ) ); if ( !mFallbackStatement.isEmpty() ) - mFallbackStatement.prepend( QString( "SELECT TOP %1 " ).arg( mRequest.limit() ) ); + mFallbackStatement.prepend( QStringLiteral( "SELECT TOP %1 " ).arg( mRequest.limit() ) ); } else { @@ -263,7 +263,7 @@ void QgsMssqlFeatureIterator::BuildStatement( const QgsFeatureRequest& request ) if ( !orderByParts.isEmpty() ) { - mOrderByClause = QString( " ORDER BY %1" ).arg( orderByParts.join( "," ) ); + mOrderByClause = QStringLiteral( " ORDER BY %1" ).arg( orderByParts.join( QStringLiteral( "," ) ) ); } QgsDebugMsg( mStatement ); diff --git a/src/providers/mssql/qgsmssqlnewconnection.cpp b/src/providers/mssql/qgsmssqlnewconnection.cpp index a3ec18decb94..1b090d9d1765 100644 --- a/src/providers/mssql/qgsmssqlnewconnection.cpp +++ b/src/providers/mssql/qgsmssqlnewconnection.cpp @@ -49,14 +49,14 @@ QgsMssqlNewConnection::QgsMssqlNewConnection( QWidget *parent, const QString& co cb_allowGeometrylessTables->setChecked( settings.value( key + "/allowGeometrylessTables", true ).toBool() ); cb_useEstimatedMetadata->setChecked( settings.value( key + "/estimatedMetadata", false ).toBool() ); - if ( settings.value( key + "/saveUsername" ).toString() == "true" ) + if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) ) { txtUsername->setText( settings.value( key + "/username" ).toString() ); chkStoreUsername->setChecked( true ); cb_trustedConnection->setChecked( false ); } - if ( settings.value( key + "/savePassword" ).toString() == "true" ) + if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) ) { txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); @@ -70,7 +70,7 @@ QgsMssqlNewConnection::QgsMssqlNewConnection( QWidget *parent, const QString& co void QgsMssqlNewConnection::accept() { QSettings settings; - QString baseKey = "/MSSQL/connections/"; + QString baseKey = QStringLiteral( "/MSSQL/connections/" ); settings.setValue( baseKey + "selected", txtName->text() ); // warn if entry was renamed to an existing connection @@ -95,7 +95,7 @@ void QgsMssqlNewConnection::accept() baseKey += txtName->text(); QString database; QListWidgetItem* item = listDatabase->currentItem(); - if ( item && item->text() != "(from service)" ) + if ( item && item->text() != QLatin1String( "(from service)" ) ) { database = item->text(); } @@ -103,8 +103,8 @@ void QgsMssqlNewConnection::accept() settings.setValue( baseKey + "/service", txtService->text() ); settings.setValue( baseKey + "/host", txtHost->text() ); settings.setValue( baseKey + "/database", database ); - settings.setValue( baseKey + "/username", chkStoreUsername->isChecked() ? txtUsername->text() : "" ); - settings.setValue( baseKey + "/password", chkStorePassword->isChecked() ? txtPassword->text() : "" ); + settings.setValue( baseKey + "/username", chkStoreUsername->isChecked() ? txtUsername->text() : QLatin1String( "" ) ); + settings.setValue( baseKey + "/password", chkStorePassword->isChecked() ? txtPassword->text() : QLatin1String( "" ) ); settings.setValue( baseKey + "/saveUsername", chkStoreUsername->isChecked() ? "true" : "false" ); settings.setValue( baseKey + "/savePassword", chkStorePassword->isChecked() ? "true" : "false" ); settings.setValue( baseKey + "/geometryColumns", cb_geometryColumns->isChecked() ); @@ -129,9 +129,9 @@ void QgsMssqlNewConnection::on_cb_trustedConnection_clicked() if ( cb_trustedConnection->checkState() == Qt::Checked ) { txtUsername->setEnabled( false ); - txtUsername->setText( "" ); + txtUsername->setText( QLatin1String( "" ) ); txtPassword->setEnabled( false ); - txtPassword->setText( "" ); + txtPassword->setText( QLatin1String( "" ) ); } else { @@ -149,7 +149,7 @@ QgsMssqlNewConnection::~QgsMssqlNewConnection() bool QgsMssqlNewConnection::testConnection( const QString& testDatabase ) { - bar->pushMessage( "Testing connection", "....." ); + bar->pushMessage( QStringLiteral( "Testing connection" ), QStringLiteral( "....." ) ); // Gross but needed to show the last message. qApp->processEvents(); @@ -166,7 +166,7 @@ bool QgsMssqlNewConnection::testConnection( const QString& testDatabase ) { database = testDatabase; } - else if ( item && item->text() != "(from service)" ) + else if ( item && item->text() != QLatin1String( "(from service)" ) ) { database = item->text(); } @@ -200,13 +200,13 @@ bool QgsMssqlNewConnection::testConnection( const QString& testDatabase ) void QgsMssqlNewConnection::listDatabases() { - testConnection( "master" ); + testConnection( QStringLiteral( "master" ) ); listDatabase->clear(); - QString queryStr = "SELECT name FROM master..sysdatabases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')"; + QString queryStr = QStringLiteral( "SELECT name FROM master..sysdatabases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')" ); QSqlDatabase db = QgsMssqlProvider::GetDatabase( txtService->text().trimmed(), txtHost->text().trimmed(), - "master", + QStringLiteral( "master" ), txtUsername->text().trimmed(), txtPassword->text().trimmed() ); if ( db.open() ) @@ -217,7 +217,7 @@ void QgsMssqlNewConnection::listDatabases() if ( !txtService->text().isEmpty() ) { - listDatabase->addItem( "(from service)" ); + listDatabase->addItem( QStringLiteral( "(from service)" ) ); } if ( query.isActive() ) diff --git a/src/providers/mssql/qgsmssqlprovider.cpp b/src/providers/mssql/qgsmssqlprovider.cpp index 4e3f76ca1587..e5fc331968dd 100644 --- a/src/providers/mssql/qgsmssqlprovider.cpp +++ b/src/providers/mssql/qgsmssqlprovider.cpp @@ -49,8 +49,8 @@ #include "qgsmssqlfeatureiterator.h" -static const QString TEXT_PROVIDER_KEY = "mssql"; -static const QString TEXT_PROVIDER_DESCRIPTION = "MSSQL spatial data provider"; +static const QString TEXT_PROVIDER_KEY = QStringLiteral( "mssql" ); +static const QString TEXT_PROVIDER_DESCRIPTION = QStringLiteral( "MSSQL spatial data provider" ); int QgsMssqlProvider::sConnectionId = 0; QgsMssqlProvider::QgsMssqlProvider( const QString& uri ) @@ -100,7 +100,7 @@ QgsMssqlProvider::QgsMssqlProvider( const QString& uri ) if ( !anUri.schema().isEmpty() ) mSchemaName = anUri.schema(); else - mSchemaName = "dbo"; + mSchemaName = QStringLiteral( "dbo" ); if ( !anUri.table().isEmpty() ) { @@ -149,29 +149,29 @@ QgsMssqlProvider::QgsMssqlProvider( const QString& uri ) //fill type names into sets setNativeTypes( QList<NativeType>() // integer types - << QgsVectorDataProvider::NativeType( tr( "8 Bytes integer" ), "bigint", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "4 Bytes integer" ), "int", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "2 Bytes integer" ), "smallint", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "1 Bytes integer" ), "tinyint", QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 20, 0, 20 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 20, 0, 20 ) + << QgsVectorDataProvider::NativeType( tr( "8 Bytes integer" ), QStringLiteral( "bigint" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "4 Bytes integer" ), QStringLiteral( "int" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "2 Bytes integer" ), QStringLiteral( "smallint" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "1 Bytes integer" ), QStringLiteral( "tinyint" ), QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 20, 0, 20 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 20, 0, 20 ) // floating point - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "float", QVariant::Double ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "float" ), QVariant::Double ) // date/time types - << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Time" ), "time", QVariant::Time, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), "datetime", QVariant::DateTime, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime, -1, -1, -1, -1 ) // string types - << QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), "char", QVariant::String, 1, 255 ) - << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length (varchar)" ), "varchar", QVariant::String, 1, 255 ) - << QgsVectorDataProvider::NativeType( tr( "Text, fixed length unicode (nchar)" ), "nchar", QVariant::String, 1, 255 ) - << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length unicode (nvarchar)" ), "nvarchar", QVariant::String, 1, 255 ) - << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String ) - << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length unicode (ntext)" ), "text", QVariant::String ) + << QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), QStringLiteral( "char" ), QVariant::String, 1, 255 ) + << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length (varchar)" ), QStringLiteral( "varchar" ), QVariant::String, 1, 255 ) + << QgsVectorDataProvider::NativeType( tr( "Text, fixed length unicode (nchar)" ), QStringLiteral( "nchar" ), QVariant::String, 1, 255 ) + << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length unicode (nvarchar)" ), QStringLiteral( "nvarchar" ), QVariant::String, 1, 255 ) + << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String ) + << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length unicode (ntext)" ), QStringLiteral( "text" ), QVariant::String ) ); } @@ -228,21 +228,21 @@ QSqlDatabase QgsMssqlProvider::GetDatabase( const QString& service, const QStrin return db; } - connectionName += QString( "%1.%2" ).arg( database ).arg( sConnectionId++ ); + connectionName += QStringLiteral( "%1.%2" ).arg( database ).arg( sConnectionId++ ); } else connectionName = service; if ( !QSqlDatabase::contains( connectionName ) ) { - db = QSqlDatabase::addDatabase( "QODBC", connectionName ); - db.setConnectOptions( "SQL_ATTR_CONNECTION_POOLING=SQL_CP_ONE_PER_HENV" ); + db = QSqlDatabase::addDatabase( QStringLiteral( "QODBC" ), connectionName ); + db.setConnectOptions( QStringLiteral( "SQL_ATTR_CONNECTION_POOLING=SQL_CP_ONE_PER_HENV" ) ); } else db = QSqlDatabase::database( connectionName ); db.setHostName( host ); - QString connectionString = ""; + QString connectionString = QLatin1String( "" ); if ( !service.isEmpty() ) { // driver was specified explicitly @@ -253,7 +253,7 @@ QSqlDatabase QgsMssqlProvider::GetDatabase( const QString& service, const QStrin #ifdef Q_OS_WIN connectionString = "driver={SQL Server}"; #else - connectionString = "driver={FreeTDS};port=1433"; + connectionString = QStringLiteral( "driver={FreeTDS};port=1433" ); #endif } @@ -264,7 +264,7 @@ QSqlDatabase QgsMssqlProvider::GetDatabase( const QString& service, const QStrin connectionString += ";database=" + database; if ( password.isEmpty() ) - connectionString += ";trusted_connection=yes"; + connectionString += QLatin1String( ";trusted_connection=yes" ); else connectionString += ";uid=" + username + ";pwd=" + password; @@ -282,55 +282,55 @@ QSqlDatabase QgsMssqlProvider::GetDatabase( const QString& service, const QStrin QVariant::Type QgsMssqlProvider::DecodeSqlType( const QString& sqlTypeName ) { QVariant::Type type = QVariant::Invalid; - if ( sqlTypeName.startsWith( "decimal", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "numeric", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "real", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "float", Qt::CaseInsensitive ) ) + if ( sqlTypeName.startsWith( QLatin1String( "decimal" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "numeric" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "real" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "float" ), Qt::CaseInsensitive ) ) { type = QVariant::Double; } - else if ( sqlTypeName.startsWith( "char", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "nchar", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "varchar", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "nvarchar", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "text", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "ntext", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "uniqueidentifier", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "char" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "nchar" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "varchar" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "nvarchar" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "text" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "ntext" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "uniqueidentifier" ), Qt::CaseInsensitive ) ) { type = QVariant::String; } - else if ( sqlTypeName.startsWith( "smallint", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "int", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "bit", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "tinyint", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "smallint" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "int" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "bit" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "tinyint" ), Qt::CaseInsensitive ) ) { type = QVariant::Int; } - else if ( sqlTypeName.startsWith( "bigint", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "bigint" ), Qt::CaseInsensitive ) ) { type = QVariant::LongLong; } - else if ( sqlTypeName.startsWith( "binary", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "varbinary", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "image", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "binary" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "varbinary" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "image" ), Qt::CaseInsensitive ) ) { type = QVariant::ByteArray; } - else if ( sqlTypeName.startsWith( "datetime", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "smalldatetime", Qt::CaseInsensitive ) || - sqlTypeName.startsWith( "datetime2", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "datetime" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "smalldatetime" ), Qt::CaseInsensitive ) || + sqlTypeName.startsWith( QLatin1String( "datetime2" ), Qt::CaseInsensitive ) ) { type = QVariant::DateTime; } - else if ( sqlTypeName.startsWith( "date", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "date" ), Qt::CaseInsensitive ) ) { type = QVariant::Date; } - else if ( sqlTypeName.startsWith( "timestamp", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "timestamp" ), Qt::CaseInsensitive ) ) { type = QVariant::String; } - else if ( sqlTypeName.startsWith( "time", Qt::CaseInsensitive ) ) + else if ( sqlTypeName.startsWith( QLatin1String( "time" ), Qt::CaseInsensitive ) ) { type = QVariant::Time; } @@ -351,7 +351,7 @@ void QgsMssqlProvider::loadMetadata() QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - if ( !query.exec( QString( "select f_geometry_column, coord_dimension, srid, geometry_type from geometry_columns where f_table_schema = '%1' and f_table_name = '%2'" ).arg( mSchemaName, mTableName ) ) ) + if ( !query.exec( QStringLiteral( "select f_geometry_column, coord_dimension, srid, geometry_type from geometry_columns where f_table_schema = '%1' and f_table_name = '%2'" ).arg( mSchemaName, mTableName ) ) ) { QgsDebugMsg( query.lastError().text() ); } @@ -370,7 +370,7 @@ void QgsMssqlProvider::loadFields() // get field spec QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - if ( !query.exec( QString( "exec sp_columns @table_name = N'%1', @table_owner = '%2'" ).arg( mTableName, mSchemaName ) ) ) + if ( !query.exec( QStringLiteral( "exec sp_columns @table_name = N'%1', @table_owner = '%2'" ).arg( mTableName, mSchemaName ) ) ) { QgsDebugMsg( query.lastError().text( ) ); return; @@ -382,18 +382,18 @@ void QgsMssqlProvider::loadFields() while ( query.next() ) { QString sqlTypeName = query.value( 5 ).toString(); - if ( sqlTypeName == "geometry" || sqlTypeName == "geography" ) + if ( sqlTypeName == QLatin1String( "geometry" ) || sqlTypeName == QLatin1String( "geography" ) ) { mGeometryColName = query.value( 3 ).toString(); mGeometryColType = sqlTypeName; - mParser.IsGeography = sqlTypeName == "geography"; + mParser.IsGeography = sqlTypeName == QLatin1String( "geography" ); } else { QVariant::Type sqlType = DecodeSqlType( sqlTypeName ); - if ( sqlTypeName == "int identity" || sqlTypeName == "bigint identity" ) + if ( sqlTypeName == QLatin1String( "int identity" ) || sqlTypeName == QLatin1String( "bigint identity" ) ) mFidColName = query.value( 3 ).toString(); - else if ( sqlTypeName == "int" || sqlTypeName == "bigint" ) + else if ( sqlTypeName == QLatin1String( "int" ) || sqlTypeName == QLatin1String( "bigint" ) ) { pkCandidates << query.value( 3 ).toString(); } @@ -443,7 +443,7 @@ void QgsMssqlProvider::loadFields() { query.clear(); query.setForwardOnly( true ); - if ( !query.exec( QString( "exec sp_pkeys @table_name = N'%1', @table_owner = '%2' " ).arg( mTableName, mSchemaName ) ) ) + if ( !query.exec( QStringLiteral( "exec sp_pkeys @table_name = N'%1', @table_owner = '%2' " ).arg( mTableName, mSchemaName ) ) ) { QgsDebugMsg( query.lastError().text() ); } @@ -456,7 +456,7 @@ void QgsMssqlProvider::loadFields() { query.clear(); query.setForwardOnly( true ); - if ( !query.exec( QString( "select count(distinct [%1]), count([%1]) from [%2].[%3]" ) + if ( !query.exec( QStringLiteral( "select count(distinct [%1]), count([%1]) from [%2].[%3]" ) .arg( pk, mSchemaName, mTableName ) ) ) { QgsDebugMsg( query.lastError().text() ); @@ -467,7 +467,7 @@ void QgsMssqlProvider::loadFields() return; } } - QString error = QString( "No primary key could be found on table %1" ).arg( mTableName ); + QString error = QStringLiteral( "No primary key could be found on table %1" ).arg( mTableName ); QgsDebugMsg( error ); mValid = false; setLastError( error ); @@ -478,7 +478,7 @@ void QgsMssqlProvider::loadFields() QString QgsMssqlProvider::quotedValue( const QVariant& value ) { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( value.type() ) { @@ -493,9 +493,9 @@ QString QgsMssqlProvider::quotedValue( const QVariant& value ) default: case QVariant::String: QString v = value.toString(); - v.replace( '\'', "''" ); + v.replace( '\'', QLatin1String( "''" ) ); if ( v.contains( '\\' ) ) - return v.replace( '\\', "\\\\" ).prepend( "N'" ).append( '\'' ); + return v.replace( '\\', QLatin1String( "\\\\" ) ).prepend( "N'" ).append( '\'' ); else return v.prepend( '\'' ).append( '\'' ); } @@ -511,7 +511,7 @@ QVariant QgsMssqlProvider::defaultValue( int fieldId ) const QString QgsMssqlProvider::storageType() const { - return "MSSQL spatial database"; + return QStringLiteral( "MSSQL spatial database" ); } // Returns the minimum value of an attribute @@ -519,14 +519,14 @@ QVariant QgsMssqlProvider::minimumValue( int index ) const { // get the field name QgsField fld = mAttributeFields.at( index ); - QString sql = QString( "select min([%1]) from " ) + QString sql = QStringLiteral( "select min([%1]) from " ) .arg( fld.name() ); - sql += QString( "[%1].[%2]" ).arg( mSchemaName, mTableName ); + sql += QStringLiteral( "[%1].[%2]" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " where (%1)" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " where (%1)" ).arg( mSqlWhereClause ); } QSqlQuery query = QSqlQuery( mDatabase ); @@ -550,14 +550,14 @@ QVariant QgsMssqlProvider::maximumValue( int index ) const { // get the field name QgsField fld = mAttributeFields.at( index ); - QString sql = QString( "select max([%1]) from " ) + QString sql = QStringLiteral( "select max([%1]) from " ) .arg( fld.name() ); - sql += QString( "[%1].[%2]" ).arg( mSchemaName, mTableName ); + sql += QStringLiteral( "[%1].[%2]" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " where (%1)" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " where (%1)" ).arg( mSqlWhereClause ); } QSqlQuery query = QSqlQuery( mDatabase ); @@ -583,21 +583,21 @@ void QgsMssqlProvider::uniqueValues( int index, QList<QVariant> &uniqueValues, i // get the field name QgsField fld = mAttributeFields.at( index ); - QString sql = QString( "select distinct " ); + QString sql = QStringLiteral( "select distinct " ); if ( limit > 0 ) { - sql += QString( " top %1 " ).arg( limit ); + sql += QStringLiteral( " top %1 " ).arg( limit ); } - sql += QString( "[%1] from " ) + sql += QStringLiteral( "[%1] from " ) .arg( fld.name() ); - sql += QString( "[%1].[%2]" ).arg( mSchemaName, mTableName ); + sql += QStringLiteral( "[%1].[%2]" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " where (%1)" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " where (%1)" ).arg( mSqlWhereClause ); } QSqlQuery query = QSqlQuery( mDatabase ); @@ -660,23 +660,23 @@ void QgsMssqlProvider::UpdateStatistics( bool estimate ) const bool readAllGeography = false; if ( estimate ) { - if ( mGeometryColType == "geometry" ) - statement = QString( "select min([%1].MakeValid().STPointN(1).STX), min([%1].MakeValid().STPointN(1).STY), max([%1].MakeValid().STPointN(1).STX), max([%1].MakeValid().STPointN(1).STY)" ).arg( mGeometryColName ); + if ( mGeometryColType == QLatin1String( "geometry" ) ) + statement = QStringLiteral( "select min([%1].MakeValid().STPointN(1).STX), min([%1].MakeValid().STPointN(1).STY), max([%1].MakeValid().STPointN(1).STX), max([%1].MakeValid().STPointN(1).STY)" ).arg( mGeometryColName ); else - statement = QString( "select min([%1].MakeValid().STPointN(1).Long), min([%1].MakeValid().STPointN(1).Lat), max([%1].MakeValid().STPointN(1).Long), max([%1].MakeValid().STPointN(1).Lat)" ).arg( mGeometryColName ); + statement = QStringLiteral( "select min([%1].MakeValid().STPointN(1).Long), min([%1].MakeValid().STPointN(1).Lat), max([%1].MakeValid().STPointN(1).Long), max([%1].MakeValid().STPointN(1).Lat)" ).arg( mGeometryColName ); } else { - if ( mGeometryColType == "geometry" ) - statement = QString( "select min([%1].MakeValid().STEnvelope().STPointN(1).STX), min([%1].MakeValid().STEnvelope().STPointN(1).STY), max([%1].MakeValid().STEnvelope().STPointN(3).STX), max([%1].MakeValid().STEnvelope().STPointN(3).STY)" ).arg( mGeometryColName ); + if ( mGeometryColType == QLatin1String( "geometry" ) ) + statement = QStringLiteral( "select min([%1].MakeValid().STEnvelope().STPointN(1).STX), min([%1].MakeValid().STEnvelope().STPointN(1).STY), max([%1].MakeValid().STEnvelope().STPointN(3).STX), max([%1].MakeValid().STEnvelope().STPointN(3).STY)" ).arg( mGeometryColName ); else { - statement = QString( "select [%1]" ).arg( mGeometryColName ); + statement = QStringLiteral( "select [%1]" ).arg( mGeometryColName ); readAllGeography = true; } } - statement += QString( " from [%1].[%2]" ).arg( mSchemaName, mTableName ); + statement += QStringLiteral( " from [%1].[%2]" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { @@ -793,7 +793,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) { QString statement; QString values; - statement = QString( "INSERT INTO [%1].[%2] (" ).arg( mSchemaName, mTableName ); + statement = QStringLiteral( "INSERT INTO [%1].[%2] (" ).arg( mSchemaName, mTableName ); bool first = true; if ( !mDatabase.isOpen() ) @@ -809,7 +809,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) { QgsField fld = mAttributeFields.at( i ); - if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) ) + if ( fld.typeName().endsWith( QLatin1String( " identity" ), Qt::CaseInsensitive ) ) continue; // skip identity field if ( fld.name().isEmpty() ) @@ -826,8 +826,8 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) else first = false; - statement += QString( "[%1]" ).arg( fld.name() ); - values += QString( "?" ); + statement += QStringLiteral( "[%1]" ).arg( fld.name() ); + values += QStringLiteral( "?" ); } // append geometry column name @@ -839,24 +839,24 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) values += ','; } - statement += QString( "[%1]" ).arg( mGeometryColName ); - if ( mGeometryColType == "geometry" ) + statement += QStringLiteral( "[%1]" ).arg( mGeometryColName ); + if ( mGeometryColType == QLatin1String( "geometry" ) ) { if ( mUseWkb ) - values += QString( "geometry::STGeomFromWKB(%1,%2).MakeValid()" ).arg( - QString( "?" ), QString::number( mSRId ) ); + values += QStringLiteral( "geometry::STGeomFromWKB(%1,%2).MakeValid()" ).arg( + QStringLiteral( "?" ), QString::number( mSRId ) ); else - values += QString( "geometry::STGeomFromText(%1,%2).MakeValid()" ).arg( - QString( "?" ), QString::number( mSRId ) ); + values += QStringLiteral( "geometry::STGeomFromText(%1,%2).MakeValid()" ).arg( + QStringLiteral( "?" ), QString::number( mSRId ) ); } else { if ( mUseWkb ) - values += QString( "geography::STGeomFromWKB(%1,%2)" ).arg( - QString( "?" ), QString::number( mSRId ) ); + values += QStringLiteral( "geography::STGeomFromWKB(%1,%2)" ).arg( + QStringLiteral( "?" ), QString::number( mSRId ) ); else - values += QString( "geography::STGeomFromText(%1,%2)" ).arg( - QString( "?" ), QString::number( mSRId ) ); + values += QStringLiteral( "geography::STGeomFromText(%1,%2)" ).arg( + QStringLiteral( "?" ), QString::number( mSRId ) ); } } @@ -880,7 +880,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) { QgsField fld = mAttributeFields.at( i ); - if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) ) + if ( fld.typeName().endsWith( QLatin1String( " identity" ), Qt::CaseInsensitive ) ) continue; // skip identity field if ( fld.name().isEmpty() ) @@ -963,7 +963,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) } - statement = QString( "SELECT IDENT_CURRENT('%1.%2')" ).arg( mSchemaName, mTableName ); + statement = QStringLiteral( "SELECT IDENT_CURRENT('%1.%2')" ).arg( mSchemaName, mTableName ); if ( !query.exec( statement ) ) { @@ -1002,26 +1002,26 @@ bool QgsMssqlProvider::addAttributes( const QList<QgsField> &attributes ) for ( QList<QgsField>::const_iterator it = attributes.begin(); it != attributes.end(); ++it ) { QString type = it->typeName(); - if ( type == "char" || type == "varchar" ) + if ( type == QLatin1String( "char" ) || type == QLatin1String( "varchar" ) ) { if ( it->length() > 0 ) - type = QString( "%1(%2)" ).arg( type ).arg( it->length() ); + type = QStringLiteral( "%1(%2)" ).arg( type ).arg( it->length() ); } - else if ( type == "numeric" || type == "decimal" ) + else if ( type == QLatin1String( "numeric" ) || type == QLatin1String( "decimal" ) ) { if ( it->length() > 0 && it->precision() > 0 ) - type = QString( "%1(%2,%3)" ).arg( type ).arg( it->length() ).arg( it->precision() ); + type = QStringLiteral( "%1(%2,%3)" ).arg( type ).arg( it->length() ).arg( it->precision() ); } if ( statement.isEmpty() ) { - statement = QString( "ALTER TABLE [%1].[%2] ADD " ).arg( + statement = QStringLiteral( "ALTER TABLE [%1].[%2] ADD " ).arg( mSchemaName, mTableName ); } else statement += ','; - statement += QString( "[%1] %2" ).arg( it->name(), type ); + statement += QStringLiteral( "[%1] %2" ).arg( it->name(), type ); } if ( !mDatabase.isOpen() ) @@ -1048,12 +1048,12 @@ bool QgsMssqlProvider::deleteAttributes( const QgsAttributeIds &attributes ) { if ( statement.isEmpty() ) { - statement = QString( "ALTER TABLE [%1].[%2] DROP COLUMN " ).arg( mSchemaName, mTableName ); + statement = QStringLiteral( "ALTER TABLE [%1].[%2] DROP COLUMN " ).arg( mSchemaName, mTableName ); } else statement += ','; - statement += QString( "[%1]" ).arg( mAttributeFields.at( *it ).name() ); + statement += QStringLiteral( "[%1]" ).arg( mAttributeFields.at( *it ).name() ); } if ( !mDatabase.isOpen() ) @@ -1096,7 +1096,7 @@ bool QgsMssqlProvider::changeAttributeValues( const QgsChangedAttributesMap &att if ( attrs.isEmpty() ) continue; - QString statement = QString( "UPDATE [%1].[%2] SET " ).arg( mSchemaName, mTableName ); + QString statement = QStringLiteral( "UPDATE [%1].[%2] SET " ).arg( mSchemaName, mTableName ); bool first = true; if ( !mDatabase.isOpen() ) @@ -1110,7 +1110,7 @@ bool QgsMssqlProvider::changeAttributeValues( const QgsChangedAttributesMap &att { QgsField fld = mAttributeFields.at( it2.key() ); - if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) ) + if ( fld.typeName().endsWith( QLatin1String( " identity" ), Qt::CaseInsensitive ) ) continue; // skip identity field if ( fld.name().isEmpty() ) @@ -1121,14 +1121,14 @@ bool QgsMssqlProvider::changeAttributeValues( const QgsChangedAttributesMap &att else first = false; - statement += QString( "[%1]=?" ).arg( fld.name() ); + statement += QStringLiteral( "[%1]=?" ).arg( fld.name() ); } if ( first ) return true; // no fields have been changed // set attribute filter - statement += QString( " WHERE [%1]=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); + statement += QStringLiteral( " WHERE [%1]=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); // use prepared statement to prevent from sql injection if ( !query.prepare( statement ) ) @@ -1141,7 +1141,7 @@ bool QgsMssqlProvider::changeAttributeValues( const QgsChangedAttributesMap &att { QgsField fld = mAttributeFields.at( it2.key() ); - if ( fld.typeName().endsWith( " identity", Qt::CaseInsensitive ) ) + if ( fld.typeName().endsWith( QLatin1String( " identity" ), Qt::CaseInsensitive ) ) continue; // skip identity field if ( fld.name().isEmpty() ) @@ -1218,7 +1218,7 @@ bool QgsMssqlProvider::changeGeometryValues( const QgsGeometryMap &geometry_map continue; QString statement; - statement = QString( "UPDATE [%1].[%2] SET " ).arg( mSchemaName, mTableName ); + statement = QStringLiteral( "UPDATE [%1].[%2] SET " ).arg( mSchemaName, mTableName ); if ( !mDatabase.isOpen() ) { @@ -1227,27 +1227,27 @@ bool QgsMssqlProvider::changeGeometryValues( const QgsGeometryMap &geometry_map QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - if ( mGeometryColType == "geometry" ) + if ( mGeometryColType == QLatin1String( "geometry" ) ) { if ( mUseWkb ) - statement += QString( "[%1]=geometry::STGeomFromWKB(%2,%3).MakeValid()" ).arg( - mGeometryColName, QString( "?" ), QString::number( mSRId ) ); + statement += QStringLiteral( "[%1]=geometry::STGeomFromWKB(%2,%3).MakeValid()" ).arg( + mGeometryColName, QStringLiteral( "?" ), QString::number( mSRId ) ); else - statement += QString( "[%1]=geometry::STGeomFromText(%2,%3).MakeValid()" ).arg( - mGeometryColName, QString( "?" ), QString::number( mSRId ) ); + statement += QStringLiteral( "[%1]=geometry::STGeomFromText(%2,%3).MakeValid()" ).arg( + mGeometryColName, QStringLiteral( "?" ), QString::number( mSRId ) ); } else { if ( mUseWkb ) - statement += QString( "[%1]=geography::STGeomFromWKB(%2,%3)" ).arg( - mGeometryColName, QString( "?" ), QString::number( mSRId ) ); + statement += QStringLiteral( "[%1]=geography::STGeomFromWKB(%2,%3)" ).arg( + mGeometryColName, QStringLiteral( "?" ), QString::number( mSRId ) ); else - statement += QString( "[%1]=geography::STGeomFromText(%2,%3)" ).arg( - mGeometryColName, QString( "?" ), QString::number( mSRId ) ); + statement += QStringLiteral( "[%1]=geography::STGeomFromText(%2,%3)" ).arg( + mGeometryColName, QStringLiteral( "?" ), QString::number( mSRId ) ); } // set attribute filter - statement += QString( " WHERE [%1]=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); + statement += QStringLiteral( " WHERE [%1]=%2" ).arg( mFidColName, FID_TO_STRING( fid ) ); if ( !query.prepare( statement ) ) { @@ -1298,7 +1298,7 @@ bool QgsMssqlProvider::deleteFeatures( const QgsFeatureIds & id ) QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); QString statement; - statement = QString( "DELETE FROM [%1].[%2] WHERE [%3] IN (%4)" ).arg( mSchemaName, + statement = QStringLiteral( "DELETE FROM [%1].[%2] WHERE [%3] IN (%4)" ).arg( mSchemaName, mTableName, mFidColName, featureIds ); if ( !query.exec( statement ) ) @@ -1344,18 +1344,18 @@ bool QgsMssqlProvider::createSpatialIndex() QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); QString statement; - statement = QString( "CREATE SPATIAL INDEX [qgs_%1_sidx] ON [%2].[%3] ( [%4] )" ).arg( + statement = QStringLiteral( "CREATE SPATIAL INDEX [qgs_%1_sidx] ON [%2].[%3] ( [%4] )" ).arg( mGeometryColName, mSchemaName, mTableName, mGeometryColName ); - if ( mGeometryColType == "geometry" ) + if ( mGeometryColType == QLatin1String( "geometry" ) ) { - statement += QString( " USING GEOMETRY_GRID WITH (BOUNDING_BOX =(%1, %2, %3, %4))" ).arg( + statement += QStringLiteral( " USING GEOMETRY_GRID WITH (BOUNDING_BOX =(%1, %2, %3, %4))" ).arg( QString::number( mExtent.xMinimum() ), QString::number( mExtent.yMinimum() ), QString::number( mExtent.xMaximum() ), QString::number( mExtent.yMaximum() ) ); } else { - statement += " USING GEOGRAPHY_GRID"; + statement += QLatin1String( " USING GEOGRAPHY_GRID" ); } if ( !query.exec( statement ) ) @@ -1383,7 +1383,7 @@ bool QgsMssqlProvider::createAttributeIndex( int field ) return false; } - statement = QString( "CREATE NONCLUSTERED INDEX [qgs_%1_idx] ON [%2].[%3] ( [%4] )" ).arg( + statement = QStringLiteral( "CREATE NONCLUSTERED INDEX [qgs_%1_idx] ON [%2].[%3] ( [%4] )" ).arg( mGeometryColName, mSchemaName, mTableName, mAttributeFields.at( field ).name() ); if ( !query.exec( statement ) ) @@ -1406,7 +1406,7 @@ QgsCoordinateReferenceSystem QgsMssqlProvider::crs() const // try to load crs from the database tables as a fallback QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - bool execOk = query.exec( QString( "select srtext from spatial_ref_sys where srid = %1" ).arg( QString::number( mSRId ) ) ); + bool execOk = query.exec( QStringLiteral( "select srtext from spatial_ref_sys where srid = %1" ).arg( QString::number( mSRId ) ) ); if ( execOk && query.isActive() ) { if ( query.next() ) @@ -1421,7 +1421,7 @@ QgsCoordinateReferenceSystem QgsMssqlProvider::crs() const query.clear(); // Look in the system reference table for the data if we can't find it yet - execOk = query.exec( QString( "select well_known_text from sys.spatial_reference_systems where spatial_reference_id = %1" ).arg( QString::number( mSRId ) ) ); + execOk = query.exec( QStringLiteral( "select well_known_text from sys.spatial_reference_systems where spatial_reference_id = %1" ).arg( QString::number( mSRId ) ) ); if ( execOk && query.isActive() && query.next() ) { mCrs = QgsCoordinateReferenceSystem::fromWkt( query.value( 0 ).toString() ); @@ -1448,13 +1448,13 @@ bool QgsMssqlProvider::setSubsetString( const QString& theSQL, bool ) mSqlWhereClause = theSQL.trimmed(); - QString sql = QString( "select count(*) from " ); + QString sql = QStringLiteral( "select count(*) from " ); - sql += QString( "[%1].[%2]" ).arg( mSchemaName, mTableName ); + sql += QStringLiteral( "[%1].[%2]" ).arg( mSchemaName, mTableName ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " where %1" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " where %1" ).arg( mSqlWhereClause ); } QSqlQuery query = QSqlQuery( mDatabase ); @@ -1493,39 +1493,39 @@ QStringList QgsMssqlProvider::subLayers() const bool QgsMssqlProvider::convertField( QgsField &field ) { - QString fieldType = "nvarchar(max)"; //default to string + QString fieldType = QStringLiteral( "nvarchar(max)" ); //default to string int fieldSize = field.length(); int fieldPrec = field.precision(); switch ( field.type() ) { case QVariant::LongLong: - fieldType = "bigint"; + fieldType = QStringLiteral( "bigint" ); fieldSize = -1; fieldPrec = 0; break; case QVariant::DateTime: - fieldType = "datetime"; + fieldType = QStringLiteral( "datetime" ); fieldPrec = -1; break; case QVariant::Date: - fieldType = "date"; + fieldType = QStringLiteral( "date" ); fieldPrec = -1; break; case QVariant::Time: - fieldType = "time"; + fieldType = QStringLiteral( "time" ); fieldPrec = -1; break; case QVariant::String: - fieldType = "nvarchar(max)"; + fieldType = QStringLiteral( "nvarchar(max)" ); fieldPrec = -1; break; case QVariant::Int: - fieldType = "int"; + fieldType = QStringLiteral( "int" ); fieldSize = -1; fieldPrec = 0; break; @@ -1533,13 +1533,13 @@ bool QgsMssqlProvider::convertField( QgsField &field ) case QVariant::Double: if ( fieldSize <= 0 || fieldPrec <= 0 ) { - fieldType = "float"; + fieldType = QStringLiteral( "float" ); fieldSize = -1; fieldPrec = -1; } else { - fieldType = "decimal"; + fieldType = QStringLiteral( "decimal" ); } break; @@ -1561,19 +1561,19 @@ void QgsMssqlProvider::mssqlWkbTypeAndDimension( QgsWkbTypes::Type wkbType, QStr QgsWkbTypes::Type flatType = QgsWkbTypes::flatType( wkbType ); if ( flatType == QgsWkbTypes::Point ) - geometryType = "POINT"; + geometryType = QStringLiteral( "POINT" ); else if ( flatType == QgsWkbTypes::LineString ) - geometryType = "LINESTRING"; + geometryType = QStringLiteral( "LINESTRING" ); else if ( flatType == QgsWkbTypes::Polygon ) - geometryType = "POLYGON"; + geometryType = QStringLiteral( "POLYGON" ); else if ( flatType == QgsWkbTypes::MultiPoint ) - geometryType = "MULTIPOINT"; + geometryType = QStringLiteral( "MULTIPOINT" ); else if ( flatType == QgsWkbTypes::MultiLineString ) - geometryType = "MULTILINESTRING"; + geometryType = QStringLiteral( "MULTILINESTRING" ); else if ( flatType == QgsWkbTypes::MultiPolygon ) - geometryType = "MULTIPOLYGON"; + geometryType = QStringLiteral( "MULTIPOLYGON" ); else if ( flatType == QgsWkbTypes::Unknown ) - geometryType = "GEOMETRY"; + geometryType = QStringLiteral( "GEOMETRY" ); else dim = 0; } @@ -1582,34 +1582,34 @@ QgsWkbTypes::Type QgsMssqlProvider::getWkbType( const QString& geometryType, int { if ( dim == 3 ) { - if ( geometryType == "POINT" ) + if ( geometryType == QLatin1String( "POINT" ) ) return QgsWkbTypes::Point25D; - if ( geometryType == "LINESTRING" ) + if ( geometryType == QLatin1String( "LINESTRING" ) ) return QgsWkbTypes::LineString25D; - if ( geometryType == "POLYGON" ) + if ( geometryType == QLatin1String( "POLYGON" ) ) return QgsWkbTypes::Polygon25D; - if ( geometryType == "MULTIPOINT" ) + if ( geometryType == QLatin1String( "MULTIPOINT" ) ) return QgsWkbTypes::MultiPoint25D; - if ( geometryType == "MULTILINESTRING" ) + if ( geometryType == QLatin1String( "MULTILINESTRING" ) ) return QgsWkbTypes::MultiLineString25D; - if ( geometryType == "MULTIPOLYGON" ) + if ( geometryType == QLatin1String( "MULTIPOLYGON" ) ) return QgsWkbTypes::MultiPolygon25D; else return QgsWkbTypes::Unknown; } else { - if ( geometryType == "POINT" ) + if ( geometryType == QLatin1String( "POINT" ) ) return QgsWkbTypes::Point; - if ( geometryType == "LINESTRING" ) + if ( geometryType == QLatin1String( "LINESTRING" ) ) return QgsWkbTypes::LineString; - if ( geometryType == "POLYGON" ) + if ( geometryType == QLatin1String( "POLYGON" ) ) return QgsWkbTypes::Polygon; - if ( geometryType == "MULTIPOINT" ) + if ( geometryType == QLatin1String( "MULTIPOINT" ) ) return QgsWkbTypes::MultiPoint; - if ( geometryType == "MULTILINESTRING" ) + if ( geometryType == QLatin1String( "MULTILINESTRING" ) ) return QgsWkbTypes::MultiLineString; - if ( geometryType == "MULTIPOLYGON" ) + if ( geometryType == QLatin1String( "MULTIPOLYGON" ) ) return QgsWkbTypes::MultiPolygon; else return QgsWkbTypes::Unknown; @@ -1652,13 +1652,13 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr QString primaryKeyType; if ( schemaName.isEmpty() ) - schemaName = "dbo"; + schemaName = QStringLiteral( "dbo" ); if ( wkbType != QgsWkbTypes::NoGeometry && geometryColumn.isEmpty() ) - geometryColumn = "geom"; + geometryColumn = QStringLiteral( "geom" ); if ( primaryKey.isEmpty() ) - primaryKey = "qgs_fid"; + primaryKey = QStringLiteral( "qgs_fid" ); // get the pk's name and type @@ -1666,13 +1666,13 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr if ( primaryKey.isEmpty() ) { int index = 0; - QString pk = primaryKey = "qgs_fid"; + QString pk = primaryKey = QStringLiteral( "qgs_fid" ); for ( int i = 0, n = fields.size(); i < n; ++i ) { if ( fields.at( i ).name() == primaryKey ) { // it already exists, try again with a new name - primaryKey = QString( "%1_%2" ).arg( pk ).arg( index++ ); + primaryKey = QStringLiteral( "%1_%2" ).arg( pk ).arg( index++ ); i = 0; } } @@ -1696,7 +1696,7 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr // if the field doesn't not exist yet, create it as a serial field if ( primaryKeyType.isEmpty() ) - primaryKeyType = "serial"; + primaryKeyType = QStringLiteral( "serial" ); QString sql; QSqlQuery q = QSqlQuery( db ); @@ -1727,15 +1727,15 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr if ( srs.isValid() ) { srid = srs.srsid(); - QString auth_srid = "null"; - QString auth_name = "null"; + QString auth_srid = QStringLiteral( "null" ); + QString auth_name = QStringLiteral( "null" ); QStringList sl = srs.authid().split( ':' ); if ( sl.length() == 2 ) { auth_name = '\'' + sl[0] + '\''; auth_srid = sl[1]; } - sql = QString( "IF NOT EXISTS (SELECT * FROM spatial_ref_sys WHERE srid=%1) INSERT INTO spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) VALUES (%1, %2, %3, '%4', '%5')" ) + sql = QStringLiteral( "IF NOT EXISTS (SELECT * FROM spatial_ref_sys WHERE srid=%1) INSERT INTO spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text) VALUES (%1, %2, %3, '%4', '%5')" ) .arg( srs.srsid() ) .arg( auth_name, auth_srid, @@ -1757,7 +1757,7 @@ QgsVectorLayerImport::ImportError QgsMssqlProvider::createEmptyLayer( const QStr if ( overwrite ) { // remove the old table with the same name - sql = QString( "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[%1].[%2]') AND type in (N'U')) BEGIN DROP TABLE [%1].[%2] DELETE FROM geometry_columns where f_table_schema = '%1' and f_table_name = '%2' END;" ) + sql = QStringLiteral( "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[%1].[%2]') AND type in (N'U')) BEGIN DROP TABLE [%1].[%2] DELETE FROM geometry_columns where f_table_schema = '%1' and f_table_name = '%2' END;" ) .arg( schemaName, tableName ); if ( !q.exec( sql ) ) { @@ -1917,7 +1917,7 @@ QGISEXTERN int dataCapabilities() QGISEXTERN QgsDataItem *dataItem( QString thePath, QgsDataItem *parentItem ) { Q_UNUSED( thePath ); - return new QgsMssqlRootItem( parentItem, "MSSQL", "mssql:" ); + return new QgsMssqlRootItem( parentItem, QStringLiteral( "MSSQL" ), QStringLiteral( "mssql:" ) ); } QGISEXTERN QgsVectorLayerImport::ImportError createEmptyLayer( @@ -1952,7 +1952,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - if ( !query.exec( QString( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name= N'layer_styles'" ) ) ) + if ( !query.exec( QStringLiteral( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name= N'layer_styles'" ) ) ) { QString msg = query.lastError().text(); QgsDebugMsg( msg ); @@ -1989,8 +1989,8 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS QString uiFileValue; if ( !uiFileContent.isEmpty() ) { - uiFileColumn = ",ui"; - uiFileValue = QString( ",XMLPARSE(DOCUMENT %1)" ).arg( uiFileContent ); + uiFileColumn = QStringLiteral( ",ui" ); + uiFileValue = QStringLiteral( ",XMLPARSE(DOCUMENT %1)" ).arg( uiFileContent ); } QgsDebugMsg( "Ready to insert new style" ); // Note: in the construction of the INSERT and UPDATE strings the qmlStyle and sldStyle values @@ -2082,7 +2082,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS .arg( QgsMssqlProvider::quotedValue( dsUri.schema() ) ) .arg( QgsMssqlProvider::quotedValue( dsUri.table() ) ) .arg( QgsMssqlProvider::quotedValue( dsUri.geometryColumn() ) ); - sql = QString( "%1; %2;" ).arg( removeDefaultSql, sql ); + sql = QStringLiteral( "%1; %2;" ).arg( removeDefaultSql, sql ); } QgsDebugMsg( "Inserting styles" ); @@ -2159,7 +2159,7 @@ QGISEXTERN int listStyles( const QString &uri, QStringList &ids, QStringList &na query.setForwardOnly( true ); // check if layer_styles table already exist - if ( !query.exec( QString( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name= N'layer_styles'" ) ) ) + if ( !query.exec( QStringLiteral( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name= N'layer_styles'" ) ) ) { QString msg = query.lastError().text(); errCause = msg; @@ -2238,8 +2238,8 @@ QGISEXTERN QString getStyleById( const QString& uri, QString styleId, QString& e QSqlQuery query = QSqlQuery( mDatabase ); query.setForwardOnly( true ); - QString style = ""; - QString selectQmlQuery = QString( "SELECT styleQml FROM layer_styles WHERE id=%1" ).arg( QgsMssqlProvider::quotedValue( styleId ) ); + QString style = QLatin1String( "" ); + QString selectQmlQuery = QStringLiteral( "SELECT styleQml FROM layer_styles WHERE id=%1" ).arg( QgsMssqlProvider::quotedValue( styleId ) ); bool queryOk = query.exec( selectQmlQuery ); if ( !queryOk ) { diff --git a/src/providers/mssql/qgsmssqlsourceselect.cpp b/src/providers/mssql/qgsmssqlsourceselect.cpp index 77c3795a1295..6485d4034c7f 100644 --- a/src/providers/mssql/qgsmssqlsourceselect.cpp +++ b/src/providers/mssql/qgsmssqlsourceselect.cpp @@ -176,7 +176,7 @@ QgsMssqlSourceSelect::QgsMssqlSourceSelect( QWidget *parent, Qt::WindowFlags fl, connect( mTablesTreeView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( treeWidgetSelectionChanged( const QItemSelection&, const QItemSelection& ) ) ); QSettings settings; - mTablesTreeView->setSelectionMode( settings.value( "/qgis/addMSSQLDC", false ).toBool() ? + mTablesTreeView->setSelectionMode( settings.value( QStringLiteral( "/qgis/addMSSQLDC" ), false ).toBool() ? QAbstractItemView::ExtendedSelection : QAbstractItemView::MultiSelection ); @@ -185,12 +185,12 @@ QgsMssqlSourceSelect::QgsMssqlSourceSelect( QWidget *parent, Qt::WindowFlags fl, //in search does not seem to work mSearchColumnComboBox->setCurrentIndex( 2 ); - restoreGeometry( settings.value( "/Windows/MSSQLSourceSelect/geometry" ).toByteArray() ); - mHoldDialogOpen->setChecked( settings.value( "/Windows/MSSQLSourceSelect/HoldDialogOpen", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/MSSQLSourceSelect/geometry" ) ).toByteArray() ); + mHoldDialogOpen->setChecked( settings.value( QStringLiteral( "/Windows/MSSQLSourceSelect/HoldDialogOpen" ), false ).toBool() ); for ( int i = 0; i < mTableModel.columnCount(); i++ ) { - mTablesTreeView->setColumnWidth( i, settings.value( QString( "/Windows/MSSQLSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ).toInt() ); + mTablesTreeView->setColumnWidth( i, settings.value( QStringLiteral( "/Windows/MSSQLSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ).toInt() ); } //hide the search options by default @@ -287,7 +287,7 @@ void QgsMssqlSourceSelect::on_cmbConnections_activated( int ) { // Remember which database was selected. QSettings settings; - settings.setValue( "/MSSQL/connections/selected", cmbConnections->currentText() ); + settings.setValue( QStringLiteral( "/MSSQL/connections/selected" ), cmbConnections->currentText() ); cbxAllowGeometrylessTables->blockSignals( true ); cbxAllowGeometrylessTables->setChecked( settings.value( "/MSSQL/connections/" + cmbConnections->currentText() + "/allowGeometrylessTables", false ).toBool() ); @@ -312,7 +312,7 @@ void QgsMssqlSourceSelect::on_mTablesTreeView_clicked( const QModelIndex &index void QgsMssqlSourceSelect::on_mTablesTreeView_doubleClicked( const QModelIndex &index ) { QSettings settings; - if ( settings.value( "/qgis/addMSSQLDC", false ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/addMSSQLDC" ), false ).toBool() ) { addTables(); } @@ -327,7 +327,7 @@ void QgsMssqlSourceSelect::on_mSearchGroupBox_toggled( bool checked ) if ( mSearchTableEdit->text().isEmpty() ) return; - on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : "" ); + on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : QLatin1String( "" ) ); } void QgsMssqlSourceSelect::on_mSearchTableEdit_textChanged( const QString & text ) @@ -398,19 +398,19 @@ QgsMssqlSourceSelect::~QgsMssqlSourceSelect() } QSettings settings; - settings.setValue( "/Windows/MSSQLSourceSelect/geometry", saveGeometry() ); - settings.setValue( "/Windows/MSSQLSourceSelect/HoldDialogOpen", mHoldDialogOpen->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/MSSQLSourceSelect/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/MSSQLSourceSelect/HoldDialogOpen" ), mHoldDialogOpen->isChecked() ); for ( int i = 0; i < mTableModel.columnCount(); i++ ) { - settings.setValue( QString( "/Windows/MSSQLSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ); + settings.setValue( QStringLiteral( "/Windows/MSSQLSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ); } } void QgsMssqlSourceSelect::populateConnectionList() { QSettings settings; - settings.beginGroup( "/MSSQL/connections" ); + settings.beginGroup( QStringLiteral( "/MSSQL/connections" ) ); QStringList keys = settings.childGroups(); QStringList::Iterator it = keys.begin(); cmbConnections->clear(); @@ -452,7 +452,7 @@ void QgsMssqlSourceSelect::addTables() } else { - emit addDatabaseLayers( mSelectedTables, "mssql" ); + emit addDatabaseLayers( mSelectedTables, QStringLiteral( "mssql" ) ); if ( !mHoldDialogOpen->isChecked() ) { accept(); @@ -481,12 +481,12 @@ void QgsMssqlSourceSelect::on_btnConnect_clicked() QString database = settings.value( key + "/database" ).toString(); QString username; QString password; - if ( settings.value( key + "/saveUsername" ).toString() == "true" ) + if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) ) { username = settings.value( key + "/username" ).toString(); } - if ( settings.value( key + "/savePassword" ).toString() == "true" ) + if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) ) { password = settings.value( key + "/password" ).toString(); } @@ -526,12 +526,12 @@ void QgsMssqlSourceSelect::on_btnConnect_clicked() if ( useGeometryColumns ) { - QString testquery( "SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'geometry_columns'" ); + QString testquery( QStringLiteral( "SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'geometry_columns'" ) ); if ( !q.exec( testquery ) || !q.first() || q.value( 0 ).toInt() == 0 ) { QMessageBox::StandardButtons reply; - reply = QMessageBox::question( this, "Scan full database?", - "No geometry_columns table found. \nWould you like to search full database (might be slower)? ", + reply = QMessageBox::question( this, QStringLiteral( "Scan full database?" ), + QStringLiteral( "No geometry_columns table found. \nWould you like to search full database (might be slower)? " ), QMessageBox::Yes | QMessageBox::No ); if ( reply == QMessageBox::Yes ) @@ -545,19 +545,19 @@ void QgsMssqlSourceSelect::on_btnConnect_clicked() QApplication::setOverrideCursor( Qt::WaitCursor ); // build sql statement - QString query( "select " ); + QString query( QStringLiteral( "select " ) ); if ( useGeometryColumns ) { - query += "f_table_schema, f_table_name, f_geometry_column, srid, geometry_type from geometry_columns"; + query += QLatin1String( "f_table_schema, f_table_name, f_geometry_column, srid, geometry_type from geometry_columns" ); } else { - query += "sys.schemas.name, sys.objects.name, sys.columns.name, null, 'GEOMETRY' from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V')"; + query += QLatin1String( "sys.schemas.name, sys.objects.name, sys.columns.name, null, 'GEOMETRY' from sys.columns join sys.types on sys.columns.system_type_id = sys.types.system_type_id and sys.columns.user_type_id = sys.types.user_type_id join sys.objects on sys.objects.object_id = sys.columns.object_id join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and (sys.objects.type = 'U' or sys.objects.type = 'V')" ); } if ( allowGeometrylessTables ) { - query += " union all select sys.schemas.name, sys.objects.name, null, null, 'NONE' from sys.objects join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where not exists (select * from sys.columns sc1 join sys.types on sc1.system_type_id = sys.types.system_type_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and sys.objects.object_id = sc1.object_id) and (sys.objects.type = 'U' or sys.objects.type = 'V')"; + query += QLatin1String( " union all select sys.schemas.name, sys.objects.name, null, null, 'NONE' from sys.objects join sys.schemas on sys.objects.schema_id = sys.schemas.schema_id where not exists (select * from sys.columns sc1 join sys.types on sc1.system_type_id = sys.types.system_type_id where (sys.types.name = 'geometry' or sys.types.name = 'geography') and sys.objects.object_id = sc1.object_id) and (sys.objects.type = 'U' or sys.objects.type = 'V')" ); } // issue the sql query @@ -583,11 +583,11 @@ void QgsMssqlSourceSelect::on_btnConnect_clicked() if ( !layer.geometryColName.isNull() ) { - if ( type == "GEOMETRY" || type.isNull() || srid.isEmpty() ) + if ( type == QLatin1String( "GEOMETRY" ) || type.isNull() || srid.isEmpty() ) { addSearchGeometryColumn( connectionName, layer, estimateMetadata ); - type = ""; - srid = ""; + type = QLatin1String( "" ); + srid = QLatin1String( "" ); } } @@ -667,7 +667,7 @@ void QgsMssqlSourceSelect::setSql( const QModelIndex &index ) QModelIndex idx = mProxyModel.mapToSource( index ); QString tableName = mTableModel.itemFromIndex( idx.sibling( idx.row(), QgsMssqlTableModel::dbtmTable ) )->text(); - QgsVectorLayer *vlayer = new QgsVectorLayer( mTableModel.layerURI( idx, mConnInfo, mUseEstimatedMetadata ), tableName, "mssql" ); + QgsVectorLayer *vlayer = new QgsVectorLayer( mTableModel.layerURI( idx, mConnInfo, mUseEstimatedMetadata ), tableName, QStringLiteral( "mssql" ) ); if ( !vlayer->isValid() ) { @@ -707,7 +707,7 @@ void QgsMssqlSourceSelect::addSearchGeometryColumn( const QString& connectionNam QString QgsMssqlSourceSelect::fullDescription( const QString& schema, const QString& table, const QString& column, const QString& type ) { - QString full_desc = ""; + QString full_desc = QLatin1String( "" ); if ( !schema.isEmpty() ) full_desc = schema + '.'; full_desc += table + " (" + column + ") " + type; @@ -718,7 +718,7 @@ void QgsMssqlSourceSelect::setConnectionListPosition() { // If possible, set the item currently displayed database QSettings settings; - QString toSelect = settings.value( "/MSSQL/connections/selected" ).toString(); + QString toSelect = settings.value( QStringLiteral( "/MSSQL/connections/selected" ) ).toString(); cmbConnections->setCurrentIndex( cmbConnections->findText( toSelect ) ); if ( cmbConnections->currentIndex() < 0 ) @@ -773,8 +773,8 @@ void QgsMssqlGeomColumnTypeThread::run() if ( !mStopped ) { QString table; - table = QString( "%1[%2]" ) - .arg( layerProperty.schemaName.isEmpty() ? "" : QString( "[%1]." ).arg( layerProperty.schemaName ), + table = QStringLiteral( "%1[%2]" ) + .arg( layerProperty.schemaName.isEmpty() ? QLatin1String( "" ) : QStringLiteral( "[%1]." ).arg( layerProperty.schemaName ), layerProperty.tableName ); QString query = QString( "SELECT %3" @@ -786,7 +786,7 @@ void QgsMssqlGeomColumnTypeThread::run() .arg( layerProperty.geometryColName, table, mUseEstimatedMetadata ? "TOP 1" : "", - layerProperty.sql.isEmpty() ? "" : QString( " AND %1" ).arg( layerProperty.sql ) ); + layerProperty.sql.isEmpty() ? QLatin1String( "" ) : QStringLiteral( " AND %1" ).arg( layerProperty.sql ) ); // issue the sql query QSqlDatabase db = QSqlDatabase::database( mConnectionName ); @@ -823,8 +823,8 @@ void QgsMssqlGeomColumnTypeThread::run() srids << srid; } - type = types.join( "," ); - srid = srids.join( "," ); + type = types.join( QStringLiteral( "," ) ); + srid = srids.join( QStringLiteral( "," ) ); } layerProperty.type = type; @@ -832,8 +832,8 @@ void QgsMssqlGeomColumnTypeThread::run() } else { - layerProperty.type = ""; - layerProperty.srid = ""; + layerProperty.type = QLatin1String( "" ); + layerProperty.srid = QLatin1String( "" ); } // Now tell the layer list dialog box... diff --git a/src/providers/mssql/qgsmssqltablemodel.cpp b/src/providers/mssql/qgsmssqltablemodel.cpp index 083c759a15d7..0fd564e96cfd 100644 --- a/src/providers/mssql/qgsmssqltablemodel.cpp +++ b/src/providers/mssql/qgsmssqltablemodel.cpp @@ -75,7 +75,7 @@ void QgsMssqlTableModel::addTableEntry( const QgsMssqlLayerProperty &layerProper wkbType = QgsWkbTypes::NoGeometry; } - bool needToDetect = wkbType == QgsWkbTypes::Unknown && layerProperty.type != "GEOMETRYCOLLECTION"; + bool needToDetect = wkbType == QgsWkbTypes::Unknown && layerProperty.type != QLatin1String( "GEOMETRYCOLLECTION" ); QList<QStandardItem*> childItemList; @@ -94,11 +94,11 @@ void QgsMssqlTableModel::addTableEntry( const QgsMssqlLayerProperty &layerProper QStandardItem *sridItem = new QStandardItem( layerProperty.srid ); sridItem->setEditable( false ); - QString pkText, pkCol = ""; + QString pkText, pkCol = QLatin1String( "" ); switch ( layerProperty.pkCols.size() ) { case 0: - pkText = ""; + pkText = QLatin1String( "" ); break; case 1: pkText = layerProperty.pkCols[0]; @@ -116,7 +116,7 @@ void QgsMssqlTableModel::addTableEntry( const QgsMssqlLayerProperty &layerProper pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 ); pkItem->setData( pkCol, Qt::UserRole + 2 ); - QStandardItem *selItem = new QStandardItem( "" ); + QStandardItem *selItem = new QStandardItem( QLatin1String( "" ) ); selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable ); selItem->setCheckState( Qt::Checked ); selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) ); @@ -402,55 +402,55 @@ QgsWkbTypes::Type QgsMssqlTableModel::wkbTypeFromMssql( QString type ) { type = type.toUpper(); - if ( type == "POINT" ) + if ( type == QLatin1String( "POINT" ) ) { return QgsWkbTypes::Point; } - else if ( type == "POINTM" ) + else if ( type == QLatin1String( "POINTM" ) ) { return QgsWkbTypes::Point25D; } - else if ( type == "MULTIPOINT" ) + else if ( type == QLatin1String( "MULTIPOINT" ) ) { return QgsWkbTypes::MultiPoint; } - else if ( type == "MULTIPOINTM" ) + else if ( type == QLatin1String( "MULTIPOINTM" ) ) { return QgsWkbTypes::MultiPoint25D; } - else if ( type == "LINESTRING" ) + else if ( type == QLatin1String( "LINESTRING" ) ) { return QgsWkbTypes::LineString; } - else if ( type == "LINESTRINGM" ) + else if ( type == QLatin1String( "LINESTRINGM" ) ) { return QgsWkbTypes::LineString25D; } - else if ( type == "MULTILINESTRING" ) + else if ( type == QLatin1String( "MULTILINESTRING" ) ) { return QgsWkbTypes::MultiLineString; } - else if ( type == "MULTILINESTRINGM" ) + else if ( type == QLatin1String( "MULTILINESTRINGM" ) ) { return QgsWkbTypes::MultiLineString25D; } - else if ( type == "POLYGON" ) + else if ( type == QLatin1String( "POLYGON" ) ) { return QgsWkbTypes::Polygon; } - else if ( type == "POLYGONM" ) + else if ( type == QLatin1String( "POLYGONM" ) ) { return QgsWkbTypes::Polygon25D; } - else if ( type == "MULTIPOLYGON" ) + else if ( type == QLatin1String( "MULTIPOLYGON" ) ) { return QgsWkbTypes::MultiPolygon; } - else if ( type == "MULTIPOLYGONM" ) + else if ( type == QLatin1String( "MULTIPOLYGONM" ) ) { return QgsWkbTypes::MultiPolygon25D; } - else if ( type == "NONE" ) + else if ( type == QLatin1String( "NONE" ) ) { return QgsWkbTypes::NoGeometry; } diff --git a/src/providers/ogr/qgsogrconnpool.h b/src/providers/ogr/qgsogrconnpool.h index 8159a40a4e81..10035951c016 100644 --- a/src/providers/ogr/qgsogrconnpool.h +++ b/src/providers/ogr/qgsogrconnpool.h @@ -36,7 +36,7 @@ inline QString qgsConnectionPool_ConnectionToName( QgsOgrConn* c ) inline void qgsConnectionPool_ConnectionCreate( const QString& connInfo, QgsOgrConn*& c ) { c = new QgsOgrConn; - QString filePath = connInfo.left( connInfo.indexOf( "|" ) ); + QString filePath = connInfo.left( connInfo.indexOf( QLatin1String( "|" ) ) ); c->ds = OGROpen( filePath.toUtf8().constData(), false, nullptr ); c->path = connInfo; c->valid = true; diff --git a/src/providers/ogr/qgsogrdataitems.cpp b/src/providers/ogr/qgsogrdataitems.cpp index ebb5653a3389..8cd44ffa9e45 100644 --- a/src/providers/ogr/qgsogrdataitems.cpp +++ b/src/providers/ogr/qgsogrdataitems.cpp @@ -33,7 +33,7 @@ QGISEXTERN QStringList wildcards(); QgsOgrLayerItem::QgsOgrLayerItem( QgsDataItem* parent, QString name, QString path, QString uri, LayerType layerType ) - : QgsLayerItem( parent, name, path, uri, layerType, "ogr" ) + : QgsLayerItem( parent, name, path, uri, layerType, QStringLiteral( "ogr" ) ) { mToolTip = uri; setState( Populated ); // children are not expected @@ -47,7 +47,7 @@ QgsOgrLayerItem::QgsOgrLayerItem( QgsDataItem* parent, QString driverName = OGR_Dr_GetName( hDriver ); OGR_DS_Destroy( hDataSource ); - if ( driverName == "ESRI Shapefile" ) + if ( driverName == QLatin1String( "ESRI Shapefile" ) ) mCapabilities |= SetCrs; // It it is impossible to assign a crs to an existing layer @@ -65,7 +65,7 @@ bool QgsOgrLayerItem::setCrs( const QgsCoordinateReferenceSystem& crs ) if ( !( mCapabilities & SetCrs ) ) return false; - QString layerName = mPath.left( mPath.indexOf( ".shp", Qt::CaseInsensitive ) ); + QString layerName = mPath.left( mPath.indexOf( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ); QString wkt = crs.toWkt(); // save ordinary .prj file @@ -108,7 +108,7 @@ bool QgsOgrLayerItem::setCrs( const QgsCoordinateReferenceSystem& crs ) QString QgsOgrLayerItem::layerName() const { QFileInfo info( name() ); - if ( info.suffix() == "gz" ) + if ( info.suffix() == QLatin1String( "gz" ) ) return info.baseName(); else return info.completeBaseName(); @@ -222,23 +222,23 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) // zip settings + info QSettings settings; - QString scanZipSetting = settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString(); + QString scanZipSetting = settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString(); QString vsiPrefix = QgsZipItem::vsiPrefix( thePath ); - bool is_vsizip = ( vsiPrefix == "/vsizip/" ); - bool is_vsigzip = ( vsiPrefix == "/vsigzip/" ); - bool is_vsitar = ( vsiPrefix == "/vsitar/" ); + bool is_vsizip = ( vsiPrefix == QLatin1String( "/vsizip/" ) ); + bool is_vsigzip = ( vsiPrefix == QLatin1String( "/vsigzip/" ) ); + bool is_vsitar = ( vsiPrefix == QLatin1String( "/vsitar/" ) ); // should we check ext. only? // check if scanItemsInBrowser2 == extension or parent dir in scanItemsFastScanUris // TODO - do this in dir item, but this requires a way to inform which extensions are supported by provider // maybe a callback function or in the provider registry? bool scanExtSetting = false; - if (( settings.value( "/qgis/scanItemsInBrowser2", - "extension" ).toString() == "extension" ) || - ( parentItem && settings.value( "/qgis/scanItemsFastScanUris", + if (( settings.value( QStringLiteral( "/qgis/scanItemsInBrowser2" ), + "extension" ).toString() == QLatin1String( "extension" ) ) || + ( parentItem && settings.value( QStringLiteral( "/qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( parentItem->path() ) ) || (( is_vsizip || is_vsitar ) && parentItem && parentItem->parent() && - settings.value( "/qgis/scanItemsFastScanUris", + settings.value( QStringLiteral( "/qgis/scanItemsFastScanUris" ), QStringList() ).toStringList().contains( parentItem->parent()->path() ) ) ) { scanExtSetting = true; @@ -258,7 +258,7 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) + " suffix= " + suffix + " vsiPrefix= " + vsiPrefix, 3 ); // allow only normal files or VSIFILE items to continue - if ( !info.isFile() && vsiPrefix == "" ) + if ( !info.isFile() && vsiPrefix == QLatin1String( "" ) ) return nullptr; QStringList myExtensions = fileExtensions(); @@ -266,14 +266,14 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) // skip *.aux.xml files (GDAL auxilary metadata files), // *.shp.xml files (ESRI metadata) and *.tif.xml files (TIFF metadata) // unless that extension is in the list (*.xml might be though) - if ( thePath.endsWith( ".aux.xml", Qt::CaseInsensitive ) && - !myExtensions.contains( "aux.xml" ) ) + if ( thePath.endsWith( QLatin1String( ".aux.xml" ), Qt::CaseInsensitive ) && + !myExtensions.contains( QStringLiteral( "aux.xml" ) ) ) return nullptr; - if ( thePath.endsWith( ".shp.xml", Qt::CaseInsensitive ) && - !myExtensions.contains( "shp.xml" ) ) + if ( thePath.endsWith( QLatin1String( ".shp.xml" ), Qt::CaseInsensitive ) && + !myExtensions.contains( QStringLiteral( "shp.xml" ) ) ) return nullptr; - if ( thePath.endsWith( ".tif.xml", Qt::CaseInsensitive ) && - !myExtensions.contains( "tif.xml" ) ) + if ( thePath.endsWith( QLatin1String( ".tif.xml" ), Qt::CaseInsensitive ) && + !myExtensions.contains( QStringLiteral( "tif.xml" ) ) ) return nullptr; // We have to filter by extensions, otherwise e.g. all Shapefile files are displayed @@ -295,7 +295,7 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) } // .dbf should probably appear if .shp is not present - if ( suffix == "dbf" ) + if ( suffix == QLatin1String( "dbf" ) ) { QString pathShp = thePath.left( thePath.count() - 4 ) + ".shp"; if ( QFileInfo::exists( pathShp ) ) @@ -303,7 +303,7 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) } // fix vsifile path and name - if ( vsiPrefix != "" ) + if ( vsiPrefix != QLatin1String( "" ) ) { // add vsiPrefix to path if needed if ( !thePath.startsWith( vsiPrefix ) ) @@ -323,10 +323,10 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) // scanExtSetting // or zipfile and scan zip == "Basic scan" if ( scanExtSetting || - (( is_vsizip || is_vsitar ) && scanZipSetting == "basic" ) ) + (( is_vsizip || is_vsitar ) && scanZipSetting == QLatin1String( "basic" ) ) ) { // if this is a VRT file make sure it is vector VRT to avoid duplicates - if ( suffix == "vrt" ) + if ( suffix == QLatin1String( "vrt" ) ) { OGRSFDriverH hDriver = OGRGetDriverByName( "VRT" ); if ( hDriver ) diff --git a/src/providers/ogr/qgsogrexpressioncompiler.cpp b/src/providers/ogr/qgsogrexpressioncompiler.cpp index 9f736387a4c0..53189b2793e0 100644 --- a/src/providers/ogr/qgsogrexpressioncompiler.cpp +++ b/src/providers/ogr/qgsogrexpressioncompiler.cpp @@ -29,17 +29,17 @@ QgsSqlExpressionCompiler::Result QgsOgrExpressionCompiler::compile( const QgsExp //for certain driver types, OGR forwards SQL through to the underlying provider. In these cases //the syntax may differ from OGR SQL, so we don't support compilation for these drivers //see http://www.gdal.org/ogr_sql.html - if ( mSource->mDriverName == "MySQL" ) + if ( mSource->mDriverName == QLatin1String( "MySQL" ) ) return Fail; - else if ( mSource->mDriverName == "PostgreSQL" ) + else if ( mSource->mDriverName == QLatin1String( "PostgreSQL" ) ) return Fail; - else if ( mSource->mDriverName == "OCI" ) + else if ( mSource->mDriverName == QLatin1String( "OCI" ) ) return Fail; - else if ( mSource->mDriverName == "ODBC" ) + else if ( mSource->mDriverName == QLatin1String( "ODBC" ) ) return Fail; - else if ( mSource->mDriverName == "PGeo" ) + else if ( mSource->mDriverName == QLatin1String( "PGeo" ) ) return Fail; - else if ( mSource->mDriverName == "MSSQLSpatial" ) + else if ( mSource->mDriverName == QLatin1String( "MSSQLSpatial" ) ) return Fail; return QgsSqlExpressionCompiler::compile( exp ); diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index 646f4aff7957..0c97a4f48ee9 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -96,7 +96,7 @@ QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool // unless it's a VRT data source filtered by geometry as we don't know which // attributes make up the geometry and OGR won't fetch them to evaluate the // filter if we choose to ignore them (fixes #11223) - if (( mSource->mDriverName != "VRT" && mSource->mDriverName != "OGR_VRT" ) || mRequest.filterRect().isNull() ) + if (( mSource->mDriverName != QLatin1String( "VRT" ) && mSource->mDriverName != QLatin1String( "OGR_VRT" ) ) || mRequest.filterRect().isNull() ) { QgsOgrProviderUtils::setRelevantFields( ogrLayer, mSource->mFields.count(), mFetchGeometry, attrs, mSource->mFirstFieldIsFid ); } @@ -114,10 +114,10 @@ QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool } if ( request.filterType() == QgsFeatureRequest::FilterExpression - && QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + && QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { QgsSqlExpressionCompiler* compiler; - if ( source->mDriverName == "SQLite" || source->mDriverName == "GPKG" ) + if ( source->mDriverName == QLatin1String( "SQLite" ) || source->mDriverName == QLatin1String( "GPKG" ) ) { compiler = new QgsSQLiteExpressionCompiler( source->mFields ); } diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index ba354d1708af..84b82c9f6339 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -55,9 +55,9 @@ email : sherman at mrcc.com #include <sys/vfs.h> #endif -static const QString TEXT_PROVIDER_KEY = "ogr"; +static const QString TEXT_PROVIDER_KEY = QStringLiteral( "ogr" ); static const QString TEXT_PROVIDER_DESCRIPTION = - QString( "OGR data provider" ) + QStringLiteral( "OGR data provider" ) + " (compiled against GDAL/OGR library version " + GDAL_RELEASE_NAME + ", running against GDAL/OGR library version " @@ -151,7 +151,7 @@ bool QgsOgrProvider::convertField( QgsField &field, const QTextCodec &encoding ) void QgsOgrProvider::repack() { - if ( !mValid || ogrDriverName != "ESRI Shapefile" || !ogrOrigLayer ) + if ( !mValid || ogrDriverName != QLatin1String( "ESRI Shapefile" ) || !ogrOrigLayer ) return; QByteArray layerName = OGR_FD_GetName( OGR_L_GetLayerDefn( ogrOrigLayer ) ); @@ -166,7 +166,7 @@ void QgsOgrProvider::repack() pushError( tr( "OGR[%1] error %2: %3" ).arg( CPLGetLastErrorType() ).arg( CPLGetLastErrorNo() ).arg( CPLGetLastErrorMsg() ) ); } - if ( mFilePath.endsWith( ".shp", Qt::CaseInsensitive ) || mFilePath.endsWith( ".dbf", Qt::CaseInsensitive ) ) + if ( mFilePath.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) || mFilePath.endsWith( QLatin1String( ".dbf" ), Qt::CaseInsensitive ) ) { QString packedDbf( mFilePath.left( mFilePath.size() - 4 ) + "_packed.dbf" ); if ( QFile::exists( packedDbf ) ) @@ -222,22 +222,22 @@ QgsVectorLayerImport::ImportError QgsOgrProvider::createEmptyLayer( const QStrin const QMap<QString, QVariant> *options ) { QString encoding; - QString driverName = "ESRI Shapefile"; + QString driverName = QStringLiteral( "ESRI Shapefile" ); QStringList dsOptions, layerOptions; if ( options ) { - if ( options->contains( "fileEncoding" ) ) - encoding = options->value( "fileEncoding" ).toString(); + if ( options->contains( QStringLiteral( "fileEncoding" ) ) ) + encoding = options->value( QStringLiteral( "fileEncoding" ) ).toString(); - if ( options->contains( "driverName" ) ) - driverName = options->value( "driverName" ).toString(); + if ( options->contains( QStringLiteral( "driverName" ) ) ) + driverName = options->value( QStringLiteral( "driverName" ) ).toString(); - if ( options->contains( "datasourceOptions" ) ) - dsOptions << options->value( "datasourceOptions" ).toStringList(); + if ( options->contains( QStringLiteral( "datasourceOptions" ) ) ) + dsOptions << options->value( QStringLiteral( "datasourceOptions" ) ).toStringList(); - if ( options->contains( "layerOptions" ) ) - layerOptions << options->value( "layerOptions" ).toStringList(); + if ( options->contains( QStringLiteral( "layerOptions" ) ) ) + layerOptions << options->value( QStringLiteral( "layerOptions" ) ).toStringList(); } if ( oldToNewAttrIdxMap ) @@ -310,7 +310,7 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) QgsApplication::registerOgrDrivers(); QSettings settings; - CPLSetConfigOption( "SHAPE_ENCODING", settings.value( "/qgis/ignoreShapeEncoding", true ).toBool() ? "" : nullptr ); + CPLSetConfigOption( "SHAPE_ENCODING", settings.value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ? "" : nullptr ); // make connection to the data source @@ -344,7 +344,7 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) QString field = part.left( pos ); QString value = part.mid( pos + 1 ); - if ( field == "layerid" ) + if ( field == QLatin1String( "layerid" ) ) { bool ok; mLayerIndex = value.toInt( &ok ); @@ -357,18 +357,18 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) mIsSubLayer = true; } } - else if ( field == "layername" ) + else if ( field == QLatin1String( "layername" ) ) { mLayerName = value; mIsSubLayer = true; } - if ( field == "subset" ) + if ( field == QLatin1String( "subset" ) ) { mSubsetString = value; } - if ( field == "geometrytype" ) + if ( field == QLatin1String( "geometrytype" ) ) { mOgrGeometryTypeFilter = ogrWkbGeometryTypeFromName( value ); } @@ -378,22 +378,22 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) open( OpenModeInitial ); setNativeTypes( QList<NativeType>() - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "integer", QVariant::Int, 1, 10 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 1, 10 ) #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 << QgsVectorDataProvider::NativeType( tr( "Whole number (integer 64 bit)" ), "integer64", QVariant::LongLong, 1, 10 ) #endif - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "double", QVariant::Double, 1, 20, 0, 15 ) - << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), "string", QVariant::String, 1, 255 ) - << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, 8, 8 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double" ), QVariant::Double, 1, 20, 0, 15 ) + << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), QStringLiteral( "string" ), QVariant::String, 1, 255 ) + << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, 8, 8 ) ); // Some drivers do not support datetime type // Please help to fill this list - if ( ogrDriverName != "ESRI Shapefile" ) + if ( ogrDriverName != QLatin1String( "ESRI Shapefile" ) ) { setNativeTypes( QList<NativeType>() - << QgsVectorDataProvider::NativeType( tr( "Time" ), "time", QVariant::Time, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), "datetime", QVariant::DateTime ) + << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime ) ); } @@ -456,21 +456,21 @@ bool QgsOgrProvider::setSubsetString( const QString& theSQL, bool updateFeatureC QString uri = mFilePath; if ( !mLayerName.isNull() ) { - uri += QString( "|layername=%1" ).arg( mLayerName ); + uri += QStringLiteral( "|layername=%1" ).arg( mLayerName ); } else if ( mLayerIndex >= 0 ) { - uri += QString( "|layerid=%1" ).arg( mLayerIndex ); + uri += QStringLiteral( "|layerid=%1" ).arg( mLayerIndex ); } if ( !mSubsetString.isEmpty() ) { - uri += QString( "|subset=%1" ).arg( mSubsetString ); + uri += QStringLiteral( "|subset=%1" ).arg( mSubsetString ); } if ( mOgrGeometryTypeFilter != wkbUnknown ) { - uri += QString( "|geometrytype=%1" ).arg( ogrWkbGeometryTypeName( mOgrGeometryTypeFilter ) ); + uri += QStringLiteral( "|geometrytype=%1" ).arg( ogrWkbGeometryTypeName( mOgrGeometryTypeFilter ) ); } setDataSourceUri( uri ); @@ -521,28 +521,28 @@ QString QgsOgrProvider::ogrWkbGeometryTypeName( OGRwkbGeometryType type ) const switch (( long )type ) { case wkbUnknown: - geom = "Unknown"; + geom = QStringLiteral( "Unknown" ); break; case wkbPoint: - geom = "Point"; + geom = QStringLiteral( "Point" ); break; case wkbLineString: - geom = "LineString"; + geom = QStringLiteral( "LineString" ); break; case wkbPolygon: - geom = "Polygon"; + geom = QStringLiteral( "Polygon" ); break; case wkbMultiPoint: - geom = "MultiPoint"; + geom = QStringLiteral( "MultiPoint" ); break; case wkbMultiLineString: - geom = "MultiLineString"; + geom = QStringLiteral( "MultiLineString" ); break; case wkbMultiPolygon: - geom = "MultiPolygon"; + geom = QStringLiteral( "MultiPolygon" ); break; case wkbGeometryCollection: - geom = "GeometryCollection"; + geom = QStringLiteral( "GeometryCollection" ); break; #if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,0) case wkbCircularString: @@ -577,56 +577,56 @@ QString QgsOgrProvider::ogrWkbGeometryTypeName( OGRwkbGeometryType type ) const break; #endif case wkbNone: - geom = "None"; + geom = QStringLiteral( "None" ); break; case wkbUnknown | wkb25DBit: - geom = "Unknown25D"; + geom = QStringLiteral( "Unknown25D" ); break; case wkbPoint25D: - geom = "Point25D"; + geom = QStringLiteral( "Point25D" ); break; case wkbLineString25D: - geom = "LineString25D"; + geom = QStringLiteral( "LineString25D" ); break; case wkbPolygon25D: - geom = "Polygon25D"; + geom = QStringLiteral( "Polygon25D" ); break; case wkbMultiPoint25D: - geom = "MultiPoint25D"; + geom = QStringLiteral( "MultiPoint25D" ); break; case wkbMultiLineString25D: - geom = "MultiLineString25D"; + geom = QStringLiteral( "MultiLineString25D" ); break; case wkbMultiPolygon25D: - geom = "MultiPolygon25D"; + geom = QStringLiteral( "MultiPolygon25D" ); break; case wkbGeometryCollection25D: - geom = "GeometryCollection25D"; + geom = QStringLiteral( "GeometryCollection25D" ); break; default: // Do not use ':', as it will mess with the separator used by QgsSublayersDialog::populateLayers() - geom = QString( "Unknown WKB (%1)" ).arg( type ); + geom = QStringLiteral( "Unknown WKB (%1)" ).arg( type ); } return geom; } OGRwkbGeometryType QgsOgrProvider::ogrWkbGeometryTypeFromName( const QString& typeName ) const { - if ( typeName == "Point" ) return wkbPoint; - else if ( typeName == "LineString" ) return wkbLineString; - else if ( typeName == "Polygon" ) return wkbPolygon; - else if ( typeName == "MultiPoint" ) return wkbMultiPoint; - else if ( typeName == "MultiLineString" ) return wkbMultiLineString; - else if ( typeName == "MultiPolygon" ) return wkbMultiPolygon; - else if ( typeName == "GeometryCollection" ) return wkbGeometryCollection; - else if ( typeName == "None" ) return wkbNone; - else if ( typeName == "Point25D" ) return wkbPoint25D; - else if ( typeName == "LineString25D" ) return wkbLineString25D; - else if ( typeName == "Polygon25D" ) return wkbPolygon25D; - else if ( typeName == "MultiPoint25D" ) return wkbMultiPoint25D; - else if ( typeName == "MultiLineString25D" ) return wkbMultiLineString25D; - else if ( typeName == "MultiPolygon25D" ) return wkbMultiPolygon25D; - else if ( typeName == "GeometryCollection25D" ) return wkbGeometryCollection25D; + if ( typeName == QLatin1String( "Point" ) ) return wkbPoint; + else if ( typeName == QLatin1String( "LineString" ) ) return wkbLineString; + else if ( typeName == QLatin1String( "Polygon" ) ) return wkbPolygon; + else if ( typeName == QLatin1String( "MultiPoint" ) ) return wkbMultiPoint; + else if ( typeName == QLatin1String( "MultiLineString" ) ) return wkbMultiLineString; + else if ( typeName == QLatin1String( "MultiPolygon" ) ) return wkbMultiPolygon; + else if ( typeName == QLatin1String( "GeometryCollection" ) ) return wkbGeometryCollection; + else if ( typeName == QLatin1String( "None" ) ) return wkbNone; + else if ( typeName == QLatin1String( "Point25D" ) ) return wkbPoint25D; + else if ( typeName == QLatin1String( "LineString25D" ) ) return wkbLineString25D; + else if ( typeName == QLatin1String( "Polygon25D" ) ) return wkbPolygon25D; + else if ( typeName == QLatin1String( "MultiPoint25D" ) ) return wkbMultiPoint25D; + else if ( typeName == QLatin1String( "MultiLineString25D" ) ) return wkbMultiLineString25D; + else if ( typeName == QLatin1String( "MultiPolygon25D" ) ) return wkbMultiPolygon25D; + else if ( typeName == QLatin1String( "GeometryCollection25D" ) ) return wkbGeometryCollection25D; return wkbUnknown; } @@ -665,7 +665,7 @@ QStringList QgsOgrProvider::subLayers() const QString geom = ogrWkbGeometryTypeName( layerGeomType ); - mSubLayerList << QString( "%1:%2:%3:%4" ).arg( i ).arg( theLayerName, theLayerFeatureCount == -1 ? tr( "Unknown" ) : QString::number( theLayerFeatureCount ), geom ); + mSubLayerList << QStringLiteral( "%1:%2:%3:%4" ).arg( i ).arg( theLayerName, theLayerFeatureCount == -1 ? tr( "Unknown" ) : QString::number( theLayerFeatureCount ), geom ); } else { @@ -729,7 +729,7 @@ QStringList QgsOgrProvider::subLayers() const QString geom = ogrWkbGeometryTypeName(( bIs25D ) ? ( OGRwkbGeometryType )( countIt.key() | wkb25DBit ) : countIt.key() ); #endif - QString sl = QString( "%1:%2:%3:%4" ).arg( i ).arg( theLayerName ).arg( fCount.value( countIt.key() ) ).arg( geom ); + QString sl = QStringLiteral( "%1:%2:%3:%4" ).arg( i ).arg( theLayerName ).arg( fCount.value( countIt.key() ) ).arg( geom ); QgsDebugMsg( "sub layer: " + sl ); mSubLayerList << sl; } @@ -743,13 +743,13 @@ void QgsOgrProvider::setEncoding( const QString& e ) { #if defined(OLCStringsAsUTF8) QSettings settings; - if (( ogrDriverName == "ESRI Shapefile" && settings.value( "/qgis/ignoreShapeEncoding", true ).toBool() ) || !OGR_L_TestCapability( ogrLayer, OLCStringsAsUTF8 ) ) + if (( ogrDriverName == QLatin1String( "ESRI Shapefile" ) && settings.value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ) || !OGR_L_TestCapability( ogrLayer, OLCStringsAsUTF8 ) ) { QgsVectorDataProvider::setEncoding( e ); } else { - QgsVectorDataProvider::setEncoding( "UTF-8" ); + QgsVectorDataProvider::setEncoding( QStringLiteral( "UTF-8" ) ); } #else QgsVectorDataProvider::setEncoding( e ); @@ -830,7 +830,7 @@ void QgsOgrProvider::loadFields() QgsField( OGR_L_GetFIDColumn( ogrLayer ), QVariant::LongLong, - "Integer64" + QStringLiteral( "Integer64" ) ) ); } @@ -1305,7 +1305,7 @@ bool QgsOgrProvider::addAttributes( const QList<QgsField> &attributes ) if ( !doInitialActionsForEdition() ) return false; - if ( ogrDriverName == "MapInfo File" ) + if ( ogrDriverName == QLatin1String( "MapInfo File" ) ) { // adding attributes in mapinfo requires to be able to delete the .dat file // so drop any cached connections. @@ -1701,7 +1701,7 @@ bool QgsOgrProvider::createSpatialIndex() if ( !doInitialActionsForEdition() ) return false; - if ( ogrDriverName != "ESRI Shapefile" ) + if ( ogrDriverName != QLatin1String( "ESRI Shapefile" ) ) return false; QByteArray layerName = OGR_FD_GetName( OGR_L_GetLayerDefn( ogrOrigLayer ) ); @@ -1914,7 +1914,7 @@ void QgsOgrProvider::computeCapabilities() #endif // OGR doesn't handle shapefiles without attributes, ie. missing DBFs well, fixes #803 - if ( ogrDriverName == "ESRI Shapefile" ) + if ( ogrDriverName == QLatin1String( "ESRI Shapefile" ) ) { ability |= CreateSpatialIndex; ability |= CreateAttributeIndex; @@ -2028,38 +2028,38 @@ QString createFilters( const QString& type ) driverName = OGR_Dr_GetName( driver ); - if ( driverName.startsWith( "AVCBin" ) ) + if ( driverName.startsWith( QLatin1String( "AVCBin" ) ) ) { myDirectoryDrivers += QObject::tr( "Arc/Info Binary Coverage" ) + ",AVCBin;"; } - else if ( driverName.startsWith( "AVCE00" ) ) + else if ( driverName.startsWith( QLatin1String( "AVCE00" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Arc/Info ASCII Coverage" ), "*.e00" ); - myExtensions << "e00"; + myFileFilters += createFileFilter_( QObject::tr( "Arc/Info ASCII Coverage" ), QStringLiteral( "*.e00" ) ); + myExtensions << QStringLiteral( "e00" ); } - else if ( driverName.startsWith( "BNA" ) ) + else if ( driverName.startsWith( QLatin1String( "BNA" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Atlas BNA" ), "*.bna" ); - myExtensions << "bna"; + myFileFilters += createFileFilter_( QObject::tr( "Atlas BNA" ), QStringLiteral( "*.bna" ) ); + myExtensions << QStringLiteral( "bna" ); } - else if ( driverName.startsWith( "CSV" ) ) + else if ( driverName.startsWith( QLatin1String( "CSV" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Comma Separated Value" ), "*.csv" ); - myExtensions << "csv"; + myFileFilters += createFileFilter_( QObject::tr( "Comma Separated Value" ), QStringLiteral( "*.csv" ) ); + myExtensions << QStringLiteral( "csv" ); } else if ( driverName.startsWith( QObject::tr( "DODS" ) ) ) { - myProtocolDrivers += "DODS/OPeNDAP,DODS;"; + myProtocolDrivers += QLatin1String( "DODS/OPeNDAP,DODS;" ); } else if ( driverName.startsWith( QObject::tr( "CouchDB" ) ) ) { - myProtocolDrivers += "CouchDB;"; + myProtocolDrivers += QLatin1String( "CouchDB;" ); } - else if ( driverName.startsWith( "FileGDB" ) ) + else if ( driverName.startsWith( QLatin1String( "FileGDB" ) ) ) { myDirectoryDrivers += QObject::tr( "ESRI FileGDB" ) + ",FileGDB;"; } - else if ( driverName.startsWith( "PGeo" ) ) + else if ( driverName.startsWith( QLatin1String( "PGeo" ) ) ) { myDatabaseDrivers += QObject::tr( "ESRI Personal GeoDatabase" ) + ",PGeo;"; #ifdef Q_OS_WIN @@ -2067,268 +2067,268 @@ QString createFilters( const QString& type ) myExtensions << "mdb"; #endif } - else if ( driverName.startsWith( "SDE" ) ) + else if ( driverName.startsWith( QLatin1String( "SDE" ) ) ) { myDatabaseDrivers += QObject::tr( "ESRI ArcSDE" ) + ",SDE;"; } - else if ( driverName.startsWith( "ESRI" ) ) + else if ( driverName.startsWith( QLatin1String( "ESRI" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "ESRI Shapefiles" ), "*.shp" ); - myExtensions << "shp" << "dbf"; + myFileFilters += createFileFilter_( QObject::tr( "ESRI Shapefiles" ), QStringLiteral( "*.shp" ) ); + myExtensions << QStringLiteral( "shp" ) << QStringLiteral( "dbf" ); } else if ( driverName.startsWith( QObject::tr( "FMEObjects Gateway" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "FMEObjects Gateway" ), "*.fdd" ); - myExtensions << "fdd"; + myFileFilters += createFileFilter_( QObject::tr( "FMEObjects Gateway" ), QStringLiteral( "*.fdd" ) ); + myExtensions << QStringLiteral( "fdd" ); } - else if ( driverName.startsWith( "GeoJSON" ) ) + else if ( driverName.startsWith( QLatin1String( "GeoJSON" ) ) ) { - myProtocolDrivers += "GeoJSON,GeoJSON;"; - myFileFilters += createFileFilter_( QObject::tr( "GeoJSON" ), "*.geojson" ); - myExtensions << "geojson"; + myProtocolDrivers += QLatin1String( "GeoJSON,GeoJSON;" ); + myFileFilters += createFileFilter_( QObject::tr( "GeoJSON" ), QStringLiteral( "*.geojson" ) ); + myExtensions << QStringLiteral( "geojson" ); } - else if ( driverName.startsWith( "GeoRSS" ) ) + else if ( driverName.startsWith( QLatin1String( "GeoRSS" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "GeoRSS" ), "*.xml" ); - myExtensions << "xml"; + myFileFilters += createFileFilter_( QObject::tr( "GeoRSS" ), QStringLiteral( "*.xml" ) ); + myExtensions << QStringLiteral( "xml" ); } - else if ( driverName.startsWith( "GML" ) ) + else if ( driverName.startsWith( QLatin1String( "GML" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Geography Markup Language [GML]" ), "*.gml" ); - myExtensions << "gml"; + myFileFilters += createFileFilter_( QObject::tr( "Geography Markup Language [GML]" ), QStringLiteral( "*.gml" ) ); + myExtensions << QStringLiteral( "gml" ); } - else if ( driverName.startsWith( "GMT" ) ) + else if ( driverName.startsWith( QLatin1String( "GMT" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Generic Mapping Tools [GMT]" ), "*.gmt" ); - myExtensions << "gmt"; + myFileFilters += createFileFilter_( QObject::tr( "Generic Mapping Tools [GMT]" ), QStringLiteral( "*.gmt" ) ); + myExtensions << QStringLiteral( "gmt" ); } - else if ( driverName.startsWith( "GPX" ) ) + else if ( driverName.startsWith( QLatin1String( "GPX" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "GPS eXchange Format [GPX]" ), "*.gpx" ); - myExtensions << "gpx"; + myFileFilters += createFileFilter_( QObject::tr( "GPS eXchange Format [GPX]" ), QStringLiteral( "*.gpx" ) ); + myExtensions << QStringLiteral( "gpx" ); } - else if ( driverName.startsWith( "GPKG" ) ) + else if ( driverName.startsWith( QLatin1String( "GPKG" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "GeoPackage" ), "*.gpkg" ); - myExtensions << "gpkg"; + myFileFilters += createFileFilter_( QObject::tr( "GeoPackage" ), QStringLiteral( "*.gpkg" ) ); + myExtensions << QStringLiteral( "gpkg" ); } - else if ( driverName.startsWith( "GRASS" ) ) + else if ( driverName.startsWith( QLatin1String( "GRASS" ) ) ) { myDirectoryDrivers += QObject::tr( "Grass Vector" ) + ",GRASS;"; } - else if ( driverName.startsWith( "IDB" ) ) + else if ( driverName.startsWith( QLatin1String( "IDB" ) ) ) { myDatabaseDrivers += QObject::tr( "Informix DataBlade" ) + ",IDB;"; } - else if ( driverName.startsWith( "Interlis 1" ) ) + else if ( driverName.startsWith( QLatin1String( "Interlis 1" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "INTERLIS 1" ), "*.itf *.xml *.ili" ); - myExtensions << "itf" << "xml" << "ili"; + myFileFilters += createFileFilter_( QObject::tr( "INTERLIS 1" ), QStringLiteral( "*.itf *.xml *.ili" ) ); + myExtensions << QStringLiteral( "itf" ) << QStringLiteral( "xml" ) << QStringLiteral( "ili" ); } - else if ( driverName.startsWith( "Interlis 2" ) ) + else if ( driverName.startsWith( QLatin1String( "Interlis 2" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "INTERLIS 2" ), "*.itf *.xml *.ili" ); - myExtensions << "itf" << "xml" << "ili"; + myFileFilters += createFileFilter_( QObject::tr( "INTERLIS 2" ), QStringLiteral( "*.itf *.xml *.ili" ) ); + myExtensions << QStringLiteral( "itf" ) << QStringLiteral( "xml" ) << QStringLiteral( "ili" ); } - else if ( driverName.startsWith( "Ingres" ) ) + else if ( driverName.startsWith( QLatin1String( "Ingres" ) ) ) { myDatabaseDrivers += QObject::tr( "Ingres" ) + ",Ingres;"; } - else if ( driverName.startsWith( "KML" ) ) + else if ( driverName.startsWith( QLatin1String( "KML" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Keyhole Markup Language [KML]" ), "*.kml *.kmz" ); - myExtensions << "kml" << "kmz"; + myFileFilters += createFileFilter_( QObject::tr( "Keyhole Markup Language [KML]" ), QStringLiteral( "*.kml *.kmz" ) ); + myExtensions << QStringLiteral( "kml" ) << QStringLiteral( "kmz" ); } - else if ( driverName.startsWith( "MapInfo File" ) ) + else if ( driverName.startsWith( QLatin1String( "MapInfo File" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Mapinfo File" ), "*.mif *.tab" ); - myExtensions << "mif" << "tab"; + myFileFilters += createFileFilter_( QObject::tr( "Mapinfo File" ), QStringLiteral( "*.mif *.tab" ) ); + myExtensions << QStringLiteral( "mif" ) << QStringLiteral( "tab" ); } - else if ( driverName.startsWith( "DGN" ) ) + else if ( driverName.startsWith( QLatin1String( "DGN" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Microstation DGN" ), "*.dgn" ); - myExtensions << "dgn"; + myFileFilters += createFileFilter_( QObject::tr( "Microstation DGN" ), QStringLiteral( "*.dgn" ) ); + myExtensions << QStringLiteral( "dgn" ); } - else if ( driverName.startsWith( "MySQL" ) ) + else if ( driverName.startsWith( QLatin1String( "MySQL" ) ) ) { myDatabaseDrivers += QObject::tr( "MySQL" ) + ",MySQL;"; } - else if ( driverName.startsWith( "MSSQL" ) ) + else if ( driverName.startsWith( QLatin1String( "MSSQL" ) ) ) { myDatabaseDrivers += QObject::tr( "MSSQL" ) + ",MSSQL;"; } - else if ( driverName.startsWith( "OCI" ) ) + else if ( driverName.startsWith( QLatin1String( "OCI" ) ) ) { myDatabaseDrivers += QObject::tr( "Oracle Spatial" ) + ",OCI;"; } - else if ( driverName.startsWith( "ODBC" ) ) + else if ( driverName.startsWith( QLatin1String( "ODBC" ) ) ) { myDatabaseDrivers += QObject::tr( "ODBC" ) + ",ODBC;"; } - else if ( driverName.startsWith( "OGDI" ) ) + else if ( driverName.startsWith( QLatin1String( "OGDI" ) ) ) { myDatabaseDrivers += QObject::tr( "OGDI Vectors" ) + ",OGDI;"; } - else if ( driverName.startsWith( "OpenFileGDB" ) ) + else if ( driverName.startsWith( QLatin1String( "OpenFileGDB" ) ) ) { myDirectoryDrivers += QObject::tr( "OpenFileGDB" ) + ",OpenFileGDB;"; } - else if ( driverName.startsWith( "PostgreSQL" ) ) + else if ( driverName.startsWith( QLatin1String( "PostgreSQL" ) ) ) { myDatabaseDrivers += QObject::tr( "PostgreSQL" ) + ",PostgreSQL;"; } - else if ( driverName.startsWith( "S57" ) ) + else if ( driverName.startsWith( QLatin1String( "S57" ) ) ) { myFileFilters += createFileFilter_( QObject::tr( "S-57 Base file" ), - "*.000" ); - myExtensions << "000"; + QStringLiteral( "*.000" ) ); + myExtensions << QStringLiteral( "000" ); } - else if ( driverName.startsWith( "SDTS" ) ) + else if ( driverName.startsWith( QLatin1String( "SDTS" ) ) ) { myFileFilters += createFileFilter_( QObject::tr( "Spatial Data Transfer Standard [SDTS]" ), - "*catd.ddf" ); - myWildcards << "*catd.ddf"; + QStringLiteral( "*catd.ddf" ) ); + myWildcards << QStringLiteral( "*catd.ddf" ); } - else if ( driverName.startsWith( "SOSI" ) ) + else if ( driverName.startsWith( QLatin1String( "SOSI" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Systematic Organization of Spatial Information [SOSI]" ), "*.sos" ); - myExtensions << "sos"; + myFileFilters += createFileFilter_( QObject::tr( "Systematic Organization of Spatial Information [SOSI]" ), QStringLiteral( "*.sos" ) ); + myExtensions << QStringLiteral( "sos" ); } - else if ( driverName.startsWith( "SQLite" ) ) + else if ( driverName.startsWith( QLatin1String( "SQLite" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "SQLite/SpatiaLite" ), "*.sqlite *.db *.sqlite3 *.db3 *.s3db *.sl3" ); - myExtensions << "sqlite" << "db" << "sqlite3" << "db3" << "s3db" << "sl3"; + myFileFilters += createFileFilter_( QObject::tr( "SQLite/SpatiaLite" ), QStringLiteral( "*.sqlite *.db *.sqlite3 *.db3 *.s3db *.sl3" ) ); + myExtensions << QStringLiteral( "sqlite" ) << QStringLiteral( "db" ) << QStringLiteral( "sqlite3" ) << QStringLiteral( "db3" ) << QStringLiteral( "s3db" ) << QStringLiteral( "sl3" ); } - else if ( driverName.startsWith( "SXF" ) ) + else if ( driverName.startsWith( QLatin1String( "SXF" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Storage and eXchange Format" ), "*.sxf" ); - myExtensions << "sxf"; + myFileFilters += createFileFilter_( QObject::tr( "Storage and eXchange Format" ), QStringLiteral( "*.sxf" ) ); + myExtensions << QStringLiteral( "sxf" ); } - else if ( driverName.startsWith( "UK .NTF" ) ) + else if ( driverName.startsWith( QLatin1String( "UK .NTF" ) ) ) { myDirectoryDrivers += QObject::tr( "UK. NTF2" ) + ",UK. NTF;"; } - else if ( driverName.startsWith( "TIGER" ) ) + else if ( driverName.startsWith( QLatin1String( "TIGER" ) ) ) { myDirectoryDrivers += QObject::tr( "U.S. Census TIGER/Line" ) + ",TIGER;"; } - else if ( driverName.startsWith( "VRT" ) ) + else if ( driverName.startsWith( QLatin1String( "VRT" ) ) ) { myFileFilters += createFileFilter_( QObject::tr( "VRT - Virtual Datasource" ), - "*.vrt *.ovf" ); - myExtensions << "vrt" << "ovf"; + QStringLiteral( "*.vrt *.ovf" ) ); + myExtensions << QStringLiteral( "vrt" ) << QStringLiteral( "ovf" ); } - else if ( driverName.startsWith( "XPlane" ) ) + else if ( driverName.startsWith( QLatin1String( "XPlane" ) ) ) { myFileFilters += createFileFilter_( QObject::tr( "X-Plane/Flightgear" ), - "apt.dat nav.dat fix.dat awy.dat" ); - myWildcards << "apt.dat" << "nav.dat" << "fix.dat" << "awy.dat"; + QStringLiteral( "apt.dat nav.dat fix.dat awy.dat" ) ); + myWildcards << QStringLiteral( "apt.dat" ) << QStringLiteral( "nav.dat" ) << QStringLiteral( "fix.dat" ) << QStringLiteral( "awy.dat" ); } - else if ( driverName.startsWith( "Geoconcept" ) ) + else if ( driverName.startsWith( QLatin1String( "Geoconcept" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Geoconcept" ), "*.gxt *.txt" ); - myExtensions << "gxt" << "txt"; + myFileFilters += createFileFilter_( QObject::tr( "Geoconcept" ), QStringLiteral( "*.gxt *.txt" ) ); + myExtensions << QStringLiteral( "gxt" ) << QStringLiteral( "txt" ); } - else if ( driverName.startsWith( "DXF" ) ) + else if ( driverName.startsWith( QLatin1String( "DXF" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "AutoCAD DXF" ), "*.dxf" ); - myExtensions << "dxf"; + myFileFilters += createFileFilter_( QObject::tr( "AutoCAD DXF" ), QStringLiteral( "*.dxf" ) ); + myExtensions << QStringLiteral( "dxf" ); } - else if ( driverName.startsWith( "ODS" ) ) + else if ( driverName.startsWith( QLatin1String( "ODS" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Open Document Spreadsheet" ), "*.ods" ); - myExtensions << "ods"; + myFileFilters += createFileFilter_( QObject::tr( "Open Document Spreadsheet" ), QStringLiteral( "*.ods" ) ); + myExtensions << QStringLiteral( "ods" ); } - else if ( driverName.startsWith( "XLSX" ) ) + else if ( driverName.startsWith( QLatin1String( "XLSX" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "MS Office Open XML spreadsheet" ), "*.xlsx" ); - myExtensions << "xlsx"; + myFileFilters += createFileFilter_( QObject::tr( "MS Office Open XML spreadsheet" ), QStringLiteral( "*.xlsx" ) ); + myExtensions << QStringLiteral( "xlsx" ); } - else if ( driverName.endsWith( "XLS" ) ) + else if ( driverName.endsWith( QLatin1String( "XLS" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "MS Excel format" ), "*.xls" ); - myExtensions << "xls"; + myFileFilters += createFileFilter_( QObject::tr( "MS Excel format" ), QStringLiteral( "*.xls" ) ); + myExtensions << QStringLiteral( "xls" ); } - else if ( driverName.startsWith( "EDIGEO" ) ) + else if ( driverName.startsWith( QLatin1String( "EDIGEO" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "EDIGEO" ), "*.thf" ); - myExtensions << "thf"; + myFileFilters += createFileFilter_( QObject::tr( "EDIGEO" ), QStringLiteral( "*.thf" ) ); + myExtensions << QStringLiteral( "thf" ); } - else if ( driverName.startsWith( "NAS" ) ) + else if ( driverName.startsWith( QLatin1String( "NAS" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "NAS - ALKIS" ), "*.xml" ); - myExtensions << "xml"; + myFileFilters += createFileFilter_( QObject::tr( "NAS - ALKIS" ), QStringLiteral( "*.xml" ) ); + myExtensions << QStringLiteral( "xml" ); } - else if ( driverName.startsWith( "WAsP" ) ) + else if ( driverName.startsWith( QLatin1String( "WAsP" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "WAsP" ), "*.map" ); - myExtensions << "map"; + myFileFilters += createFileFilter_( QObject::tr( "WAsP" ), QStringLiteral( "*.map" ) ); + myExtensions << QStringLiteral( "map" ); } - else if ( driverName.startsWith( "PCIDSK" ) ) + else if ( driverName.startsWith( QLatin1String( "PCIDSK" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "PCI Geomatics Database File" ), "*.pix" ); - myExtensions << "pix"; + myFileFilters += createFileFilter_( QObject::tr( "PCI Geomatics Database File" ), QStringLiteral( "*.pix" ) ); + myExtensions << QStringLiteral( "pix" ); } - else if ( driverName.startsWith( "GPSTrackMaker" ) ) + else if ( driverName.startsWith( QLatin1String( "GPSTrackMaker" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "GPSTrackMaker" ), "*.gtm *.gtz" ); - myExtensions << "gtm" << "gtz"; + myFileFilters += createFileFilter_( QObject::tr( "GPSTrackMaker" ), QStringLiteral( "*.gtm *.gtz" ) ); + myExtensions << QStringLiteral( "gtm" ) << QStringLiteral( "gtz" ); } - else if ( driverName.startsWith( "VFK" ) ) + else if ( driverName.startsWith( QLatin1String( "VFK" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Czech Cadastral Exchange Data Format" ), "*.vfk" ); - myExtensions << "vfk"; + myFileFilters += createFileFilter_( QObject::tr( "Czech Cadastral Exchange Data Format" ), QStringLiteral( "*.vfk" ) ); + myExtensions << QStringLiteral( "vfk" ); } - else if ( driverName.startsWith( "OSM" ) ) + else if ( driverName.startsWith( QLatin1String( "OSM" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "OpenStreetMap" ), "*.osm *.pbf" ); - myExtensions << "osm" << "pbf"; + myFileFilters += createFileFilter_( QObject::tr( "OpenStreetMap" ), QStringLiteral( "*.osm *.pbf" ) ); + myExtensions << QStringLiteral( "osm" ) << QStringLiteral( "pbf" ); } - else if ( driverName.startsWith( "SUA" ) ) + else if ( driverName.startsWith( QLatin1String( "SUA" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Special Use Airspace Format" ), "*.sua" ); - myExtensions << "sua"; + myFileFilters += createFileFilter_( QObject::tr( "Special Use Airspace Format" ), QStringLiteral( "*.sua" ) ); + myExtensions << QStringLiteral( "sua" ); } - else if ( driverName.startsWith( "OpenAir" ) ) + else if ( driverName.startsWith( QLatin1String( "OpenAir" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "OpenAir Special Use Airspace Format" ), "*.txt" ); - myExtensions << "txt"; + myFileFilters += createFileFilter_( QObject::tr( "OpenAir Special Use Airspace Format" ), QStringLiteral( "*.txt" ) ); + myExtensions << QStringLiteral( "txt" ); } - else if ( driverName.startsWith( "PDS" ) ) + else if ( driverName.startsWith( QLatin1String( "PDS" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Planetary Data Systems TABLE" ), "*.xml" ); - myExtensions << "xml"; + myFileFilters += createFileFilter_( QObject::tr( "Planetary Data Systems TABLE" ), QStringLiteral( "*.xml" ) ); + myExtensions << QStringLiteral( "xml" ); } - else if ( driverName.startsWith( "HTF" ) ) + else if ( driverName.startsWith( QLatin1String( "HTF" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Hydrographic Transfer Format" ), "*.htf" ); - myExtensions << "htf"; + myFileFilters += createFileFilter_( QObject::tr( "Hydrographic Transfer Format" ), QStringLiteral( "*.htf" ) ); + myExtensions << QStringLiteral( "htf" ); } - else if ( driverName.startsWith( "SVG" ) ) + else if ( driverName.startsWith( QLatin1String( "SVG" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Scalable Vector Graphics" ), "*.svg" ); - myExtensions << "svg"; + myFileFilters += createFileFilter_( QObject::tr( "Scalable Vector Graphics" ), QStringLiteral( "*.svg" ) ); + myExtensions << QStringLiteral( "svg" ); } - else if ( driverName.startsWith( "ARCGEN" ) ) + else if ( driverName.startsWith( QLatin1String( "ARCGEN" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Arc/Info Generate" ), "*.gen" ); - myExtensions << "gen"; + myFileFilters += createFileFilter_( QObject::tr( "Arc/Info Generate" ), QStringLiteral( "*.gen" ) ); + myExtensions << QStringLiteral( "gen" ); } - else if ( driverName.startsWith( "PDF" ) ) + else if ( driverName.startsWith( QLatin1String( "PDF" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "Geospatial PDF" ), "*.pdf" ); - myExtensions << "pdf"; + myFileFilters += createFileFilter_( QObject::tr( "Geospatial PDF" ), QStringLiteral( "*.pdf" ) ); + myExtensions << QStringLiteral( "pdf" ); } - else if ( driverName.startsWith( "SEGY" ) ) + else if ( driverName.startsWith( QLatin1String( "SEGY" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "SEG-Y" ), "*.sgy *.segy" ); - myExtensions << "sgy" << "segy"; + myFileFilters += createFileFilter_( QObject::tr( "SEG-Y" ), QStringLiteral( "*.sgy *.segy" ) ); + myExtensions << QStringLiteral( "sgy" ) << QStringLiteral( "segy" ); } - else if ( driverName.startsWith( "SEGUKOOA" ) ) + else if ( driverName.startsWith( QLatin1String( "SEGUKOOA" ) ) ) { - myFileFilters += createFileFilter_( QObject::tr( "SEG-P1" ), "*.seg *.seg1 *.sp1" ); - myFileFilters += createFileFilter_( QObject::tr( "UKOOA P1/90" ), "*.uko *.ukooa" ); - myExtensions << "seg" << "seg1" << "sp1" << "uko" << "ukooa"; + myFileFilters += createFileFilter_( QObject::tr( "SEG-P1" ), QStringLiteral( "*.seg *.seg1 *.sp1" ) ); + myFileFilters += createFileFilter_( QObject::tr( "UKOOA P1/90" ), QStringLiteral( "*.uko *.ukooa" ) ); + myExtensions << QStringLiteral( "seg" ) << QStringLiteral( "seg1" ) << QStringLiteral( "sp1" ) << QStringLiteral( "uko" ) << QStringLiteral( "ukooa" ); } else { @@ -2341,9 +2341,9 @@ QString createFilters( const QString& type ) // sort file filters alphabetically QgsDebugMsg( "myFileFilters: " + myFileFilters ); - QStringList filters = myFileFilters.split( ";;", QString::SkipEmptyParts ); + QStringList filters = myFileFilters.split( QStringLiteral( ";;" ), QString::SkipEmptyParts ); filters.sort(); - myFileFilters = filters.join( ";;" ) + ";;"; + myFileFilters = filters.join( QStringLiteral( ";;" ) ) + ";;"; QgsDebugMsg( "myFileFilters: " + myFileFilters ); // VSIFileHandler (.zip and .gz files) - second @@ -2352,10 +2352,10 @@ QString createFilters( const QString& type ) // This does not work for some file types, see VSIFileHandler doc. #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1600 QSettings settings; - if ( settings.value( "/qgis/scanZipInBrowser2", "basic" ).toString() != "no" ) + if ( settings.value( QStringLiteral( "/qgis/scanZipInBrowser2" ), "basic" ).toString() != QLatin1String( "no" ) ) { - myFileFilters.prepend( createFileFilter_( QObject::tr( "GDAL/OGR VSIFileHandler" ), "*.zip *.gz *.tar *.tar.gz *.tgz" ) ); - myExtensions << "zip" << "gz" << "tar" << "tar.gz" << "tgz"; + myFileFilters.prepend( createFileFilter_( QObject::tr( "GDAL/OGR VSIFileHandler" ), QStringLiteral( "*.zip *.gz *.tar *.tar.gz *.tgz" ) ) ); + myExtensions << QStringLiteral( "zip" ) << QStringLiteral( "gz" ) << QStringLiteral( "tar" ) << QStringLiteral( "tar.gz" ) << QStringLiteral( "tgz" ); } #endif @@ -2364,90 +2364,90 @@ QString createFilters( const QString& type ) myFileFilters.prepend( QObject::tr( "All files" ) + " (*);;" ); // cleanup - if ( myFileFilters.endsWith( ";;" ) ) myFileFilters.chop( 2 ); + if ( myFileFilters.endsWith( QLatin1String( ";;" ) ) ) myFileFilters.chop( 2 ); QgsDebugMsg( "myFileFilters: " + myFileFilters ); } - if ( type == "file" ) + if ( type == QLatin1String( "file" ) ) { return myFileFilters; } - if ( type == "database" ) + if ( type == QLatin1String( "database" ) ) { return myDatabaseDrivers; } - if ( type == "protocol" ) + if ( type == QLatin1String( "protocol" ) ) { return myProtocolDrivers; } - if ( type == "directory" ) + if ( type == QLatin1String( "directory" ) ) { return myDirectoryDrivers; } - if ( type == "extensions" ) + if ( type == QLatin1String( "extensions" ) ) { - return myExtensions.join( "|" ); + return myExtensions.join( QStringLiteral( "|" ) ); } - if ( type == "wildcards" ) + if ( type == QLatin1String( "wildcards" ) ) { - return myWildcards.join( "|" ); + return myWildcards.join( QStringLiteral( "|" ) ); } else { - return ""; + return QLatin1String( "" ); } } QGISEXTERN QString fileVectorFilters() { - return createFilters( "file" ); + return createFilters( QStringLiteral( "file" ) ); } QString QgsOgrProvider::fileVectorFilters() const { - return createFilters( "file" ); + return createFilters( QStringLiteral( "file" ) ); } QGISEXTERN QString databaseDrivers() { - return createFilters( "database" ); + return createFilters( QStringLiteral( "database" ) ); } QString QgsOgrProvider::databaseDrivers() const { - return createFilters( "database" ); + return createFilters( QStringLiteral( "database" ) ); } QGISEXTERN QString protocolDrivers() { - return createFilters( "protocol" ); + return createFilters( QStringLiteral( "protocol" ) ); } QString QgsOgrProvider::protocolDrivers() const { - return createFilters( "protocol" ); + return createFilters( QStringLiteral( "protocol" ) ); } QGISEXTERN QString directoryDrivers() { - return createFilters( "directory" ); + return createFilters( QStringLiteral( "directory" ) ); } QString QgsOgrProvider::directoryDrivers() const { - return createFilters( "directory" ); + return createFilters( QStringLiteral( "directory" ) ); } QGISEXTERN QStringList fileExtensions() { - return createFilters( "extensions" ).split( '|' ); + return createFilters( QStringLiteral( "extensions" ) ).split( '|' ); } QGISEXTERN QStringList wildcards() { - return createFilters( "wildcards" ).split( '|' ); + return createFilters( QStringLiteral( "wildcards" ) ).split( '|' ); } @@ -2513,9 +2513,9 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, QString driverName = OGR_Dr_GetName( driver ); - if ( driverName == "ESRI Shapefile" ) + if ( driverName == QLatin1String( "ESRI Shapefile" ) ) { - if ( !uri.endsWith( ".shp", Qt::CaseInsensitive ) ) + if ( !uri.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) { QgsDebugMsg( QString( "uri %1 doesn't end with .shp" ).arg( uri ) ); return false; @@ -2600,7 +2600,7 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, } char **papszOptions = nullptr; - if ( driverName == "ESRI Shapefile" ) + if ( driverName == QLatin1String( "ESRI Shapefile" ) ) { papszOptions = CSLSetNameValue( papszOptions, "ENCODING", QgsVectorFileWriter::convertCodecNameForEncodingOption( encoding ).toLocal8Bit().data() ); // OGR Shapefile fails to create fields if given encoding is not supported by its side @@ -2613,7 +2613,7 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, CSLDestroy( papszOptions ); QSettings settings; - if ( !settings.value( "/qgis/ignoreShapeEncoding", true ).toBool() ) + if ( !settings.value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ) { CPLSetConfigOption( "SHAPE_ENCODING", nullptr ); } @@ -2647,7 +2647,7 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, width += 1; OGRFieldDefnH field; - if ( fields[0] == "Real" ) + if ( fields[0] == QLatin1String( "Real" ) ) { if ( width < 0 ) width = 32; @@ -2658,7 +2658,7 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, OGR_Fld_SetWidth( field, width ); OGR_Fld_SetPrecision( field, precision ); } - else if ( fields[0] == "Integer" ) + else if ( fields[0] == QLatin1String( "Integer" ) ) { if ( width < 0 || width > 10 ) width = 10; @@ -2667,7 +2667,7 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, // limit to 10. otherwise OGR sets it to 11 and recognizes as OFTDouble later OGR_Fld_SetWidth( field, width ); } - else if ( fields[0] == "String" ) + else if ( fields[0] == QLatin1String( "String" ) ) { if ( width < 0 || width > 255 ) width = 255; @@ -2675,15 +2675,15 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, field = OGR_Fld_Create( codec->fromUnicode( it->first ).constData(), OFTString ); OGR_Fld_SetWidth( field, width ); } - else if ( fields[0] == "Date" ) + else if ( fields[0] == QLatin1String( "Date" ) ) { field = OGR_Fld_Create( codec->fromUnicode( it->first ).constData(), OFTDate ); } - else if ( fields[0] == "Time" ) + else if ( fields[0] == QLatin1String( "Time" ) ) { field = OGR_Fld_Create( codec->fromUnicode( it->first ).constData(), OFTTime ); } - else if ( fields[0] == "DateTime" ) + else if ( fields[0] == QLatin1String( "DateTime" ) ) { field = OGR_Fld_Create( codec->fromUnicode( it->first ).constData(), OFTDateTime ); } @@ -2701,9 +2701,9 @@ QGISEXTERN bool createEmptyDataSource( const QString &uri, OGR_DS_Destroy( dataSource ); - if ( driverName == "ESRI Shapefile" ) + if ( driverName == QLatin1String( "ESRI Shapefile" ) ) { - QString layerName = uri.left( uri.indexOf( ".shp", Qt::CaseInsensitive ) ); + QString layerName = uri.left( uri.indexOf( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ); QFile prjFile( layerName + ".qpj" ); if ( prjFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { @@ -2739,9 +2739,9 @@ QgsCoordinateReferenceSystem QgsOgrProvider::crs() const { QString driverName = OGR_Dr_GetName( ogrDriver ); - if ( driverName == "ESRI Shapefile" ) + if ( driverName == QLatin1String( "ESRI Shapefile" ) ) { - QString layerName = mFilePath.left( mFilePath.indexOf( ".shp", Qt::CaseInsensitive ) ); + QString layerName = mFilePath.left( mFilePath.indexOf( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ); QFile prjFile( layerName + ".qpj" ); if ( prjFile.open( QIODevice::ReadOnly ) ) { @@ -2990,7 +2990,7 @@ void QgsOgrProviderUtils::OGRDestroyWrapper( OGRDataSourceH ogrDataSource ) OGRSFDriverH ogrDriver = OGR_DS_GetDriver( ogrDataSource ); QString ogrDriverName = OGR_Dr_GetName( ogrDriver ); QString datasetName( FROM8( OGR_DS_GetName( ogrDataSource ) ) ); - if ( ogrDriverName == "GPKG" && + if ( ogrDriverName == QLatin1String( "GPKG" ) && IsLocalFile( datasetName ) && !CPLGetConfigOption( "OGR_SQLITE_JOURNAL", NULL ) ) { @@ -3067,7 +3067,7 @@ void QgsOgrProviderUtils::OGRDestroyWrapper( OGRDataSourceH ogrDataSource ) QByteArray QgsOgrProviderUtils::quotedIdentifier( QByteArray field, const QString& ogrDriverName ) { - if ( ogrDriverName == "MySQL" ) + if ( ogrDriverName == QLatin1String( "MySQL" ) ) { field.replace( '\\', "\\\\" ); field.replace( '`', "``" ); @@ -3085,7 +3085,7 @@ QByteArray QgsOgrProviderUtils::quotedIdentifier( QByteArray field, const QStrin QString QgsOgrProviderUtils::quotedValue( const QVariant& value ) { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( value.type() ) { @@ -3101,9 +3101,9 @@ QString QgsOgrProviderUtils::quotedValue( const QVariant& value ) default: case QVariant::String: QString v = value.toString(); - v.replace( '\'', "''" ); + v.replace( '\'', QLatin1String( "''" ) ); if ( v.contains( '\\' ) ) - return v.replace( '\\', "\\\\" ).prepend( "E'" ).append( '\'' ); + return v.replace( '\\', QLatin1String( "\\\\" ) ).prepend( "E'" ).append( '\'' ); else return v.prepend( '\'' ).append( '\'' ); } @@ -3114,7 +3114,7 @@ bool QgsOgrProvider::syncToDisc() //for shapefiles, remove spatial index files and create a new index QgsOgrConnPool::instance()->unref( dataSourceUri() ); bool shapeIndex = false; - if ( ogrDriverName == "ESRI Shapefile" ) + if ( ogrDriverName == QLatin1String( "ESRI Shapefile" ) ) { QString sbnIndexFile; QFileInfo fi( mFilePath ); @@ -3210,7 +3210,7 @@ void QgsOgrProvider::recalculateFeatureCount() bool QgsOgrProvider::doesStrictFeatureTypeCheck() const { // FIXME probably other drivers too... - return ogrDriverName != "ESRI Shapefile" || ( mOGRGeomType == wkbPoint || mOGRGeomType == wkbPoint25D ); + return ogrDriverName != QLatin1String( "ESRI Shapefile" ) || ( mOGRGeomType == wkbPoint || mOGRGeomType == wkbPoint25D ); } OGRwkbGeometryType QgsOgrProvider::ogrWkbSingleFlatten( OGRwkbGeometryType type ) @@ -3246,7 +3246,7 @@ OGRLayerH QgsOgrProviderUtils::setSubsetString( OGRLayerH layer, OGRDataSourceH OGRSFDriverH ogrDriver = OGR_DS_GetDriver( ds ); QString ogrDriverName = OGR_Dr_GetName( ogrDriver ); - if ( ogrDriverName == "ODBC" ) //the odbc driver does not like schema names for subset + if ( ogrDriverName == QLatin1String( "ODBC" ) ) //the odbc driver does not like schema names for subset { QString layerNameString = encoding->toUnicode( layerName ); int dotIndex = layerNameString.indexOf( '.' ); @@ -3270,7 +3270,7 @@ void QgsOgrProvider::open( OpenMode mode ) // Try to open using VSIFileHandler // see http://trac.osgeo.org/gdal/wiki/UserDocs/ReadInZip QString vsiPrefix = QgsZipItem::vsiPrefix( dataSourceUri() ); - if ( vsiPrefix != "" ) + if ( vsiPrefix != QLatin1String( "" ) ) { // GDAL>=1.8.0 has write support for zip, but read and write operations // cannot be interleaved, so for now just use read-only. @@ -3290,7 +3290,7 @@ void QgsOgrProvider::open( OpenMode mode ) CPLSetConfigOption( "OGR_ORGANIZE_POLYGONS", "ONLY_CCW" ); // "SKIP" returns MULTIPOLYGONs for multiringed POLYGONs CPLSetConfigOption( "GPX_ELE_AS_25D", "YES" ); // use GPX elevation as z values - if ( mFilePath.startsWith( "MySQL:" ) && !mLayerName.isEmpty() && !mFilePath.endsWith( ",tables=" + mLayerName ) ) + if ( mFilePath.startsWith( QLatin1String( "MySQL:" ) ) && !mLayerName.isEmpty() && !mFilePath.endsWith( ",tables=" + mLayerName ) ) { mFilePath += ",tables=" + mLayerName; } @@ -3303,10 +3303,10 @@ void QgsOgrProvider::open( OpenMode mode ) // first try to open in update mode (unless specified otherwise) if ( !openReadOnly ) { - if ( QFileInfo( mFilePath ).suffix().compare( "gpkg", Qt::CaseInsensitive ) == 0 && + if ( QFileInfo( mFilePath ).suffix().compare( QLatin1String( "gpkg" ), Qt::CaseInsensitive ) == 0 && IsLocalFile( mFilePath ) && !CPLGetConfigOption( "OGR_SQLITE_JOURNAL", NULL ) && - QSettings().value( "/qgis/walForSqlite3", true ).toBool() ) + QSettings().value( QStringLiteral( "/qgis/walForSqlite3" ), true ).toBool() ) { // For GeoPackage, we force opening of the file in WAL (Write Ahead Log) // mode so as to avoid readers blocking writer(s), and vice-versa. @@ -3389,7 +3389,7 @@ void QgsOgrProvider::open( OpenMode mode ) // We limit to those drivers as re-opening is relatively cheap (other drivers // like GeoJSON might do full content ingestion for example) if ( mValid && mode == OpenModeInitial && mWriteAccess && - ( ogrDriverName == "ESRI Shapefile" || ogrDriverName == "MapInfo File" ) ) + ( ogrDriverName == QLatin1String( "ESRI Shapefile" ) || ogrDriverName == QLatin1String( "MapInfo File" ) ) ) { OGR_DS_Destroy( ogrDataSource ); ogrLayer = ogrOrigLayer = nullptr; @@ -3400,7 +3400,7 @@ void QgsOgrProvider::open( OpenMode mode ) // pre-existing holes in the DBF (see #15407), so if using a GDAL version // recent enough to have reliable packing, do a packing at the first edit // action. - if ( ogrDriverName == "ESRI Shapefile" && + if ( ogrDriverName == QLatin1String( "ESRI Shapefile" ) && atoi( GDALVersionInfo( "VERSION_NUM" ) ) >= GDAL_COMPUTE_VERSION( 2, 1, 2 ) ) { mShapefileMayBeCorrupted = true; diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index b60aa3e09b3d..dd5ca03829e8 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -68,7 +68,7 @@ class QgsOgrProvider : public QgsVectorDataProvider * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset */ - explicit QgsOgrProvider( QString const & uri = "" ); + explicit QgsOgrProvider( QString const & uri = QLatin1String( "" ) ); /** * Destructor diff --git a/src/providers/ows/qgsowsdataitems.cpp b/src/providers/ows/qgsowsdataitems.cpp index b3e670daf1ba..d283af10babd 100644 --- a/src/providers/ows/qgsowsdataitems.cpp +++ b/src/providers/ows/qgsowsdataitems.cpp @@ -28,7 +28,7 @@ QgsOWSConnectionItem::QgsOWSConnectionItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); } QgsOWSConnectionItem::~QgsOWSConnectionItem() @@ -93,7 +93,7 @@ QVector<QgsDataItem*> QgsOWSConnectionItem::createChildren() { item->removeChildItem( subItem ); subItem->setParent( this ); - replacePath( subItem, providerKey.toLower() + ":/", "ows:/" ); + replacePath( subItem, providerKey.toLower() + ":/", QStringLiteral( "ows:/" ) ); children.append( subItem ); } delete item; @@ -173,7 +173,7 @@ QgsOWSRootItem::QgsOWSRootItem( QgsDataItem* parent, QString name, QString path : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconOws.svg"; + mIconName = QStringLiteral( "mIconOws.svg" ); populate(); } @@ -259,7 +259,7 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) { if ( thePath.isEmpty() ) { - return new QgsOWSRootItem( parentItem, "OWS", "ows:" ); + return new QgsOWSRootItem( parentItem, QStringLiteral( "OWS" ), QStringLiteral( "ows:" ) ); } return nullptr; } diff --git a/src/providers/ows/qgsowsprovider.cpp b/src/providers/ows/qgsowsprovider.cpp index 0f0b5aae65d2..bbe4dace4262 100644 --- a/src/providers/ows/qgsowsprovider.cpp +++ b/src/providers/ows/qgsowsprovider.cpp @@ -21,8 +21,8 @@ #include <QString> -static QString PROVIDER_KEY = "ows"; -static QString PROVIDER_DESCRIPTION = "OWS meta provider"; +static QString PROVIDER_KEY = QStringLiteral( "ows" ); +static QString PROVIDER_DESCRIPTION = QStringLiteral( "OWS meta provider" ); QgsOwsProvider::QgsOwsProvider( const QString& uri ) : QgsDataProvider( uri ) diff --git a/src/providers/postgres/qgspgnewconnection.cpp b/src/providers/postgres/qgspgnewconnection.cpp index 005f7db706db..8bca623385b5 100644 --- a/src/providers/postgres/qgspgnewconnection.cpp +++ b/src/providers/postgres/qgspgnewconnection.cpp @@ -39,7 +39,7 @@ QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName cbxSSLmode->addItem( tr( "verify-ca" ), QgsDataSourceUri::SslVerifyCa ); cbxSSLmode->addItem( tr( "verify-full" ), QgsDataSourceUri::SslVerifyFull ); - mAuthConfigSelect = new QgsAuthConfigSelect( this, "postgres" ); + mAuthConfigSelect = new QgsAuthConfigSelect( this, QStringLiteral( "postgres" ) ); tabAuthentication->insertTab( 1, mAuthConfigSelect, tr( "Configurations" ) ); if ( !connName.isEmpty() ) @@ -54,7 +54,7 @@ QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName QString port = settings.value( key + "/port" ).toString(); if ( port.length() == 0 ) { - port = "5432"; + port = QStringLiteral( "5432" ); } txtPort->setText( port ); txtDatabase->setText( settings.value( key + "/database" ).toString() ); @@ -69,13 +69,13 @@ QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName cbxSSLmode->setCurrentIndex( cbxSSLmode->findData( settings.value( key + "/sslmode", QgsDataSourceUri::SslPrefer ).toInt() ) ); - if ( settings.value( key + "/saveUsername" ).toString() == "true" ) + if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) ) { txtUsername->setText( settings.value( key + "/username" ).toString() ); chkStoreUsername->setChecked( true ); } - if ( settings.value( key + "/savePassword" ).toString() == "true" ) + if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) ) { txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); @@ -87,7 +87,7 @@ QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName txtUsername->setText( settings.value( key + "/username" ).toString() ); chkStoreUsername->setChecked( !txtUsername->text().isEmpty() ); - if ( settings.value( key + "/save" ).toString() == "true" ) + if ( settings.value( key + "/save" ).toString() == QLatin1String( "true" ) ) txtPassword->setText( settings.value( key + "/password" ).toString() ); chkStorePassword->setChecked( true ); @@ -108,7 +108,7 @@ QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName void QgsPgNewConnection::accept() { QSettings settings; - QString baseKey = "/PostgreSQL/connections/"; + QString baseKey = QStringLiteral( "/PostgreSQL/connections/" ); settings.setValue( baseKey + "selected", txtName->text() ); bool hasAuthConfigID = !mAuthConfigSelect->configId().isEmpty(); @@ -145,8 +145,8 @@ void QgsPgNewConnection::accept() settings.setValue( baseKey + "/host", txtHost->text() ); settings.setValue( baseKey + "/port", txtPort->text() ); settings.setValue( baseKey + "/database", txtDatabase->text() ); - settings.setValue( baseKey + "/username", chkStoreUsername->isChecked() && !hasAuthConfigID ? txtUsername->text() : "" ); - settings.setValue( baseKey + "/password", chkStorePassword->isChecked() && !hasAuthConfigID ? txtPassword->text() : "" ); + settings.setValue( baseKey + "/username", chkStoreUsername->isChecked() && !hasAuthConfigID ? txtUsername->text() : QLatin1String( "" ) ); + settings.setValue( baseKey + "/password", chkStorePassword->isChecked() && !hasAuthConfigID ? txtPassword->text() : QLatin1String( "" ) ); settings.setValue( baseKey + "/authcfg", mAuthConfigSelect->configId() ); settings.setValue( baseKey + "/publicOnly", cb_publicSchemaOnly->isChecked() ); settings.setValue( baseKey + "/geometryColumnsOnly", cb_geometryColumnsOnly->isChecked() ); diff --git a/src/providers/postgres/qgspgsourceselect.cpp b/src/providers/postgres/qgspgsourceselect.cpp index 226d969adc6a..527a92aee7da 100644 --- a/src/providers/postgres/qgspgsourceselect.cpp +++ b/src/providers/postgres/qgspgsourceselect.cpp @@ -144,7 +144,7 @@ void QgsPgSourceSelectDelegate::setEditorData( QWidget *editor, const QModelInde bool ok; value.toInt( &ok ); if ( index.column() == QgsPgTableModel::dbtmSrid && !ok ) - value = ""; + value = QLatin1String( "" ); le->setText( value ); } @@ -174,7 +174,7 @@ void QgsPgSourceSelectDelegate::setModelData( QWidget *editor, QAbstractItemMode cols << item->text(); } - model->setData( index, cols.isEmpty() ? tr( "Select..." ) : cols.join( ", " ) ); + model->setData( index, cols.isEmpty() ? tr( "Select..." ) : cols.join( QStringLiteral( ", " ) ) ); model->setData( index, cols, Qt::UserRole + 2 ); } } @@ -255,7 +255,7 @@ QgsPgSourceSelect::QgsPgSourceSelect( QWidget *parent, Qt::WindowFlags fl, bool connect( mTablesTreeView->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( treeWidgetSelectionChanged( const QItemSelection&, const QItemSelection& ) ) ); QSettings settings; - mTablesTreeView->setSelectionMode( settings.value( "/qgis/addPostgisDC", false ).toBool() ? + mTablesTreeView->setSelectionMode( settings.value( QStringLiteral( "/qgis/addPostgisDC" ), false ).toBool() ? QAbstractItemView::ExtendedSelection : QAbstractItemView::MultiSelection ); @@ -263,12 +263,12 @@ QgsPgSourceSelect::QgsPgSourceSelect( QWidget *parent, Qt::WindowFlags fl, bool //in search does not seem to work mSearchColumnComboBox->setCurrentIndex( 2 ); - restoreGeometry( settings.value( "/Windows/PgSourceSelect/geometry" ).toByteArray() ); - mHoldDialogOpen->setChecked( settings.value( "/Windows/PgSourceSelect/HoldDialogOpen", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/PgSourceSelect/geometry" ) ).toByteArray() ); + mHoldDialogOpen->setChecked( settings.value( QStringLiteral( "/Windows/PgSourceSelect/HoldDialogOpen" ), false ).toBool() ); for ( int i = 0; i < mTableModel.columnCount(); i++ ) { - mTablesTreeView->setColumnWidth( i, settings.value( QString( "/Windows/PgSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ).toInt() ); + mTablesTreeView->setColumnWidth( i, settings.value( QStringLiteral( "/Windows/PgSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ).toInt() ); } //hide the search options by default @@ -370,7 +370,7 @@ void QgsPgSourceSelect::on_mTablesTreeView_clicked( const QModelIndex &index ) void QgsPgSourceSelect::on_mTablesTreeView_doubleClicked( const QModelIndex &index ) { QSettings settings; - if ( settings.value( "/qgis/addPostgisDC", false ).toBool() ) + if ( settings.value( QStringLiteral( "/qgis/addPostgisDC" ), false ).toBool() ) { addTables(); } @@ -385,7 +385,7 @@ void QgsPgSourceSelect::on_mSearchGroupBox_toggled( bool checked ) if ( mSearchTableEdit->text().isEmpty() ) return; - on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : "" ); + on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : QLatin1String( "" ) ); } void QgsPgSourceSelect::on_mSearchTableEdit_textChanged( const QString & text ) @@ -461,12 +461,12 @@ QgsPgSourceSelect::~QgsPgSourceSelect() } QSettings settings; - settings.setValue( "/Windows/PgSourceSelect/geometry", saveGeometry() ); - settings.setValue( "/Windows/PgSourceSelect/HoldDialogOpen", mHoldDialogOpen->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/PgSourceSelect/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/PgSourceSelect/HoldDialogOpen" ), mHoldDialogOpen->isChecked() ); for ( int i = 0; i < mTableModel.columnCount(); i++ ) { - settings.setValue( QString( "/Windows/PgSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ); + settings.setValue( QStringLiteral( "/Windows/PgSourceSelect/columnWidths/%1" ).arg( i ), mTablesTreeView->columnWidth( i ) ); } } @@ -508,7 +508,7 @@ void QgsPgSourceSelect::addTables() } else { - emit addDatabaseLayers( mSelectedTables, "postgres" ); + emit addDatabaseLayers( mSelectedTables, QStringLiteral( "postgres" ) ); if ( !mHoldDialogOpen->isChecked() ) { accept(); @@ -609,7 +609,7 @@ void QgsPgSourceSelect::setSql( const QModelIndex &index ) return; } - QgsVectorLayer *vlayer = new QgsVectorLayer( uri, tableName, "postgres" ); + QgsVectorLayer *vlayer = new QgsVectorLayer( uri, tableName, QStringLiteral( "postgres" ) ); if ( !vlayer->isValid() ) { delete vlayer; @@ -629,7 +629,7 @@ void QgsPgSourceSelect::setSql( const QModelIndex &index ) QString QgsPgSourceSelect::fullDescription( const QString& schema, const QString& table, const QString& column, const QString& type ) { - QString full_desc = ""; + QString full_desc = QLatin1String( "" ); if ( !schema.isEmpty() ) full_desc = QgsPostgresConn::quotedIdentifier( schema ) + '.'; full_desc += QgsPostgresConn::quotedIdentifier( table ) + " (" + column + ") " + type; diff --git a/src/providers/postgres/qgspgtablemodel.cpp b/src/providers/postgres/qgspgtablemodel.cpp index 96e84bd48acd..13d836a4f9d9 100644 --- a/src/providers/postgres/qgspgtablemodel.cpp +++ b/src/providers/postgres/qgspgtablemodel.cpp @@ -87,7 +87,7 @@ void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty& layerProper QStandardItem *tableItem = new QStandardItem( layerProperty.tableName ); QStandardItem *commentItem = new QStandardItem( layerProperty.tableComment ); QStandardItem *geomItem = new QStandardItem( layerProperty.geometryColName ); - QStandardItem *sridItem = new QStandardItem( wkbType != QgsWkbTypes::NoGeometry ? QString::number( srid ) : "" ); + QStandardItem *sridItem = new QStandardItem( wkbType != QgsWkbTypes::NoGeometry ? QString::number( srid ) : QLatin1String( "" ) ); sridItem->setEditable( wkbType != QgsWkbTypes::NoGeometry && srid == INT_MIN ); if ( sridItem->isEditable() ) { @@ -95,7 +95,7 @@ void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty& layerProper sridItem->setFlags( sridItem->flags() | Qt::ItemIsEditable ); } - QStandardItem *pkItem = new QStandardItem( "" ); + QStandardItem *pkItem = new QStandardItem( QLatin1String( "" ) ); if ( !layerProperty.pkCols.isEmpty() ) { pkItem->setText( tr( "Select..." ) ); @@ -107,7 +107,7 @@ void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty& layerProper pkItem->setData( layerProperty.pkCols, Qt::UserRole + 1 ); pkItem->setData( "", Qt::UserRole + 2 ); - QStandardItem *selItem = new QStandardItem( "" ); + QStandardItem *selItem = new QStandardItem( QLatin1String( "" ) ); selItem->setFlags( selItem->flags() | Qt::ItemIsUserCheckable ); selItem->setCheckState( Qt::Checked ); selItem->setToolTip( tr( "Disable 'Fast Access to Features at ID' capability to force keeping the attribute table in memory (e.g. in case of expensive views)." ) ); @@ -132,14 +132,14 @@ void QgsPgTableModel::addTableEntry( const QgsPostgresLayerProperty& layerProper if ( tip.isEmpty() ) { item->setFlags( item->flags() | Qt::ItemIsSelectable ); - item->setToolTip( "" ); + item->setToolTip( QLatin1String( "" ) ); } else { item->setFlags( item->flags() & ~Qt::ItemIsSelectable ); if ( item == schemaNameItem ) - item->setData( QgsApplication::getThemeIcon( "/mIconWarning.svg" ), Qt::DecorationRole ); + item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole ); if ( item == schemaNameItem || item == tableItem || item == geomItem ) { @@ -294,14 +294,14 @@ bool QgsPgTableModel::setData( const QModelIndex &idx, const QVariant &value, in } item->setFlags( item->flags() | Qt::ItemIsSelectable ); - item->setToolTip( "" ); + item->setToolTip( QLatin1String( "" ) ); } else { item->setFlags( item->flags() & ~Qt::ItemIsSelectable ); if ( i == dbtmSchema ) - item->setData( QgsApplication::getThemeIcon( "/mIconWarning.svg" ), Qt::DecorationRole ); + item->setData( QgsApplication::getThemeIcon( QStringLiteral( "/mIconWarning.svg" ) ), Qt::DecorationRole ); if ( i == dbtmSchema || i == dbtmTable || i == dbtmGeomCol ) { @@ -371,7 +371,7 @@ QString QgsPgTableModel::layerURI( const QModelIndex &index, const QString& conn cols << QgsPostgresConn::quotedIdentifier( col ); } - uri.setDataSource( schemaName, tableName, geomColumnName, sql, cols.join( "," ) ); + uri.setDataSource( schemaName, tableName, geomColumnName, sql, cols.join( QStringLiteral( "," ) ) ); uri.setUseEstimatedMetadata( useEstimatedMetadata ); uri.setWkbType( wkbType ); uri.setSrid( srid ); diff --git a/src/providers/postgres/qgspostgresconn.cpp b/src/providers/postgres/qgspostgresconn.cpp index 200478f70816..616daa1135a0 100644 --- a/src/providers/postgres/qgspostgresconn.cpp +++ b/src/providers/postgres/qgspostgresconn.cpp @@ -215,13 +215,13 @@ QgsPostgresConn::QgsPostgresConn( const QString& conninfo, bool readOnly, bool s // remove temporary cert/key/CA if they exist QgsDataSourceUri expandedUri( expandedConnectionInfo ); QStringList parameters; - parameters << "sslcert" << "sslkey" << "sslrootcert"; + parameters << QStringLiteral( "sslcert" ) << QStringLiteral( "sslkey" ) << QStringLiteral( "sslrootcert" ); Q_FOREACH ( const QString& param, parameters ) { if ( expandedUri.hasParam( param ) ) { QString fileName = expandedUri.param( param ); - fileName.remove( "'" ); + fileName.remove( QStringLiteral( "'" ) ); QFile::remove( fileName ); } } @@ -271,7 +271,7 @@ QgsPostgresConn::QgsPostgresConn( const QString& conninfo, bool readOnly, bool s //set client encoding to unicode because QString uses UTF-8 anyway QgsDebugMsg( "setting client encoding to UNICODE" ); - int errcode = PQsetClientEncoding( mConn, QString( "UNICODE" ).toLocal8Bit() ); + int errcode = PQsetClientEncoding( mConn, QStringLiteral( "UNICODE" ).toLocal8Bit() ); if ( errcode == 0 ) { QgsDebugMsg( "encoding successfully set" ); @@ -309,7 +309,7 @@ QgsPostgresConn::QgsPostgresConn( const QString& conninfo, bool readOnly, bool s if ( mPostgresqlVersion >= 90000 ) { - PQexecNR( "SET application_name='QGIS'" ); + PQexecNR( QStringLiteral( "SET application_name='QGIS'" ) ); } @@ -348,7 +348,7 @@ void QgsPostgresConn::addColumnInfo( QgsPostgresLayerProperty& layerProperty, co // TODO: optimize this query when pk candidates aren't needed // could use array_agg() and count() // array output would look like this: "{One,tWo}" - QString sql = QString( "SELECT attname, CASE WHEN typname = ANY(ARRAY['geometry','geography','topogeometry']) THEN 1 ELSE null END AS isSpatial FROM pg_attribute JOIN pg_type ON atttypid=pg_type.oid WHERE attrelid=regclass('%1.%2') AND attnum>0 ORDER BY attnum" ) + QString sql = QStringLiteral( "SELECT attname, CASE WHEN typname = ANY(ARRAY['geometry','geography','topogeometry']) THEN 1 ELSE null END AS isSpatial FROM pg_attribute JOIN pg_type ON atttypid=pg_type.oid WHERE attrelid=regclass('%1.%2') AND attnum>0 ORDER BY attnum" ) .arg( quotedIdentifier( schemaName ), quotedIdentifier( viewName ) ); //QgsDebugMsg( sql ); @@ -398,24 +398,24 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP if ( i == sctGeometry ) { - tableName = "l.f_table_name"; - schemaName = "l.f_table_schema"; - columnName = "l.f_geometry_column"; - typeName = "upper(l.type)"; - sridName = "l.srid"; - dimName = "l.coord_dimension"; - gtableName = "geometry_columns"; + tableName = QStringLiteral( "l.f_table_name" ); + schemaName = QStringLiteral( "l.f_table_schema" ); + columnName = QStringLiteral( "l.f_geometry_column" ); + typeName = QStringLiteral( "upper(l.type)" ); + sridName = QStringLiteral( "l.srid" ); + dimName = QStringLiteral( "l.coord_dimension" ); + gtableName = QStringLiteral( "geometry_columns" ); columnType = sctGeometry; } else if ( i == sctGeography ) { - tableName = "l.f_table_name"; - schemaName = "l.f_table_schema"; - columnName = "l.f_geography_column"; - typeName = "upper(l.type)"; - sridName = "l.srid"; - dimName = "2"; - gtableName = "geography_columns"; + tableName = QStringLiteral( "l.f_table_name" ); + schemaName = QStringLiteral( "l.f_table_schema" ); + columnName = QStringLiteral( "l.f_geography_column" ); + typeName = QStringLiteral( "upper(l.type)" ); + sridName = QStringLiteral( "l.srid" ); + dimName = QStringLiteral( "2" ); + gtableName = QStringLiteral( "geography_columns" ); columnType = sctGeography; } else if ( i == sctTopoGeometry ) @@ -423,18 +423,18 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP if ( !hasTopology() ) continue; - schemaName = "l.schema_name"; - tableName = "l.table_name"; - columnName = "l.feature_column"; + schemaName = QStringLiteral( "l.schema_name" ); + tableName = QStringLiteral( "l.table_name" ); + columnName = QStringLiteral( "l.feature_column" ); typeName = "CASE " "WHEN l.feature_type = 1 THEN 'MULTIPOINT' " "WHEN l.feature_type = 2 THEN 'MULTILINESTRING' " "WHEN l.feature_type = 3 THEN 'MULTIPOLYGON' " "WHEN l.feature_type = 4 THEN 'GEOMETRYCOLLECTION' " "END AS type"; - sridName = "(SELECT srid FROM topology.topology t WHERE l.topology_id=t.id)"; - dimName = "2"; - gtableName = "topology.layer"; + sridName = QStringLiteral( "(SELECT srid FROM topology.topology t WHERE l.topology_id=t.id)" ); + dimName = QStringLiteral( "2" ); + gtableName = QStringLiteral( "topology.layer" ); columnType = sctTopoGeometry; } else if ( i == sctPcPatch ) @@ -442,13 +442,13 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP if ( !hasPointcloud() ) continue; - tableName = "l.\"table\""; - schemaName = "l.\"schema\""; - columnName = "l.\"column\""; - typeName = "'POLYGON'"; - sridName = "l.srid"; - dimName = "2"; - gtableName = "pointcloud_columns"; + tableName = QStringLiteral( "l.\"table\"" ); + schemaName = QStringLiteral( "l.\"schema\"" ); + columnName = QStringLiteral( "l.\"column\"" ); + typeName = QStringLiteral( "'POLYGON'" ); + sridName = QStringLiteral( "l.srid" ); + dimName = QStringLiteral( "2" ); + gtableName = QStringLiteral( "pointcloud_columns" ); columnType = sctPcPatch; } else @@ -471,18 +471,18 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP .arg( tableName, schemaName, columnName, typeName, sridName, dimName, gtableName ); if ( searchPublicOnly ) - sql += " AND n.nspname='public'"; + sql += QLatin1String( " AND n.nspname='public'" ); if ( !schema.isEmpty() ) - sql += QString( " AND %1='%2'" ).arg( schemaName, schema ); + sql += QStringLiteral( " AND %1='%2'" ).arg( schemaName, schema ); - sql += QString( " ORDER BY n.nspname,c.relname,%1" ).arg( columnName ); + sql += QStringLiteral( " ORDER BY n.nspname,c.relname,%1" ).arg( columnName ); //QgsDebugMsg( "getting table info: " + sql ); result = PQexec( sql, i == 0 ); if ( result.PQresultStatus() != PGRES_TUPLES_OK ) { - PQexecNR( "COMMIT" ); + PQexecNR( QStringLiteral( "COMMIT" ) ); continue; } @@ -495,7 +495,7 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP QString ssrid = result.PQgetvalue( idx, 4 ); int dim = result.PQgetvalue( idx, 5 ).toInt(); QString relkind = result.PQgetvalue( idx, 6 ); - bool isView = relkind == "v" || relkind == "m"; + bool isView = relkind == QLatin1String( "v" ) || relkind == QLatin1String( "m" ); QString comment = result.PQgetvalue( idx, 7 ); int srid = ssrid.isEmpty() ? INT_MIN : ssrid.toInt(); @@ -520,12 +520,12 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP layerProperty.geometryColName = column; layerProperty.geometryColType = columnType; if ( dim == 3 && !type.endsWith( 'M' ) ) - type += "Z"; + type += QLatin1String( "Z" ); else if ( dim == 4 ) - type += "ZM"; + type += QLatin1String( "ZM" ); layerProperty.types = QList<QgsWkbTypes::Type>() << ( QgsPostgresConn::wkbTypeFromPostgis( type ) ); layerProperty.srids = QList<int>() << srid; - layerProperty.sql = ""; + layerProperty.sql = QLatin1String( "" ); layerProperty.relKind = relkind; layerProperty.isView = isView; layerProperty.tableComment = comment; @@ -573,27 +573,27 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP // user has select privilege if ( searchPublicOnly ) - sql += " AND n.nspname='public'"; + sql += QLatin1String( " AND n.nspname='public'" ); if ( !schema.isEmpty() ) - sql += QString( " AND n.nspname='%2'" ).arg( schema ); + sql += QStringLiteral( " AND n.nspname='%2'" ).arg( schema ); // skip columns of which we already derived information from the metadata tables if ( nColumns > 0 ) { if ( foundInTables & ( 1 << sctGeometry ) ) { - sql += " AND (n.nspname,c.relname,a.attname) NOT IN (SELECT f_table_schema,f_table_name,f_geometry_column FROM geometry_columns)"; + sql += QLatin1String( " AND (n.nspname,c.relname,a.attname) NOT IN (SELECT f_table_schema,f_table_name,f_geometry_column FROM geometry_columns)" ); } if ( foundInTables & ( 1 << sctGeography ) ) { - sql += " AND (n.nspname,c.relname,a.attname) NOT IN (SELECT f_table_schema,f_table_name,f_geography_column FROM geography_columns)"; + sql += QLatin1String( " AND (n.nspname,c.relname,a.attname) NOT IN (SELECT f_table_schema,f_table_name,f_geography_column FROM geography_columns)" ); } if ( foundInTables & ( 1 << sctPcPatch ) ) { - sql += " AND (n.nspname,c.relname,a.attname) NOT IN (SELECT \"schema\",\"table\",\"column\" FROM pointcloud_columns)"; + sql += QLatin1String( " AND (n.nspname,c.relname,a.attname) NOT IN (SELECT \"schema\",\"table\",\"column\" FROM pointcloud_columns)" ); } } @@ -606,7 +606,7 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP QgsMessageLog::logMessage( tr( "Database connection was successful, but the accessible tables could not be determined. The error message from the database was:\n%1\n" ) .arg( result.PQresultErrorMessage() ), tr( "PostGIS" ) ); - PQexecNR( "COMMIT" ); + PQexecNR( QStringLiteral( "COMMIT" ) ); return false; } @@ -621,7 +621,7 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP QString column = result.PQgetvalue( i, 2 ); // attname QString relkind = result.PQgetvalue( i, 3 ); // relation kind QString coltype = result.PQgetvalue( i, 4 ); // column type - bool isView = relkind == "v" || relkind == "m"; + bool isView = relkind == QLatin1String( "v" ) || relkind == QLatin1String( "m" ); QString comment = result.PQgetvalue( i, 5 ); // table comment //QgsDebugMsg( QString( "%1.%2.%3: %4" ).arg( schemaName ).arg( tableName ).arg( column ).arg( relkind ) ); @@ -634,19 +634,19 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP layerProperty.relKind = relkind; layerProperty.isView = isView; layerProperty.tableComment = comment; - if ( coltype == "geometry" ) + if ( coltype == QLatin1String( "geometry" ) ) { layerProperty.geometryColType = sctGeometry; } - else if ( coltype == "geography" ) + else if ( coltype == QLatin1String( "geography" ) ) { layerProperty.geometryColType = sctGeography; } - else if ( coltype == "topogeometry" ) + else if ( coltype == QLatin1String( "topogeometry" ) ) { layerProperty.geometryColType = sctTopoGeometry; } - else if ( coltype == "pcpatch" ) + else if ( coltype == QLatin1String( "pcpatch" ) ) { layerProperty.geometryColType = sctPcPatch; } @@ -662,7 +662,7 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP continue; } - layerProperty.sql = ""; + layerProperty.sql = QLatin1String( "" ); mLayersSupported << layerProperty; nColumns++; @@ -686,10 +686,10 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP // user has select privilege if ( searchPublicOnly ) - sql += " AND pg_namespace.nspname='public'"; + sql += QLatin1String( " AND pg_namespace.nspname='public'" ); if ( !schema.isEmpty() ) - sql += QString( " AND pg_namespace.nspname='%2'" ).arg( schema ); + sql += QStringLiteral( " AND pg_namespace.nspname='%2'" ).arg( schema ); //QgsDebugMsg( "sql: " + sql ); @@ -708,7 +708,7 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP QString table = result.PQgetvalue( i, 0 ); // relname QString schema = result.PQgetvalue( i, 1 ); // nspname QString relkind = result.PQgetvalue( i, 2 ); // relation kind - bool isView = relkind == "v" || relkind == "m"; + bool isView = relkind == QLatin1String( "v" ) || relkind == QLatin1String( "m" ); QString comment = result.PQgetvalue( i, 3 ); // table comment //QgsDebugMsg( QString( "%1.%2: %3" ).arg( schema ).arg( table ).arg( relkind ) ); @@ -738,7 +738,7 @@ bool QgsPostgresConn::getTableInfo( bool searchGeometryColumnsOnly, bool searchP continue; addColumnInfo( layerProperty, schema, table, isView ); - layerProperty.sql = ""; + layerProperty.sql = QLatin1String( "" ); mLayersSupported << layerProperty; nColumns++; @@ -774,12 +774,12 @@ bool QgsPostgresConn::getSchemas( QList<QgsPostgresSchemaProperty> &schemas ) schemas.clear(); QgsPostgresResult result; - QString sql = QString( "SELECT nspname, pg_get_userbyid(nspowner), pg_catalog.obj_description(oid) FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname != 'information_schema' ORDER BY nspname" ); + QString sql = QStringLiteral( "SELECT nspname, pg_get_userbyid(nspowner), pg_catalog.obj_description(oid) FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname != 'information_schema' ORDER BY nspname" ); result = PQexec( sql, true ); if ( result.PQresultStatus() != PGRES_TUPLES_OK ) { - PQexecNR( "COMMIT" ); + PQexecNR( QStringLiteral( "COMMIT" ) ); return false; } @@ -832,7 +832,7 @@ QString QgsPostgresConn::postgisVersion() mPostgresqlVersion = PQserverVersion( mConn ); - QgsPostgresResult result( PQexec( "SELECT postgis_version()", false ) ); + QgsPostgresResult result( PQexec( QStringLiteral( "SELECT postgis_version()" ), false ) ); if ( result.PQntuples() != 1 ) { QgsMessageLog::logMessage( tr( "No PostGIS support in the database." ), tr( "PostGIS" ) ); @@ -862,7 +862,7 @@ QString QgsPostgresConn::postgisVersion() // apparently postgis 1.5.2 doesn't report capabilities in postgis_version() anymore if ( mPostgisVersionMajor > 1 || ( mPostgisVersionMajor == 1 && mPostgisVersionMinor >= 5 ) ) { - result = PQexec( "SELECT postgis_geos_version(),postgis_proj_version()" ); + result = PQexec( QStringLiteral( "SELECT postgis_geos_version(),postgis_proj_version()" ) ); mGeosAvailable = result.PQntuples() == 1 && !result.PQgetisnull( 0, 0 ); mProjAvailable = result.PQntuples() == 1 && !result.PQgetisnull( 0, 1 ); QgsDebugMsg( QString( "geos:%1 proj:%2" ) @@ -878,20 +878,20 @@ QString QgsPostgresConn::postgisVersion() mProjAvailable = false; // parse out the capabilities and store them - QStringList geos = postgisParts.filter( "GEOS" ); + QStringList geos = postgisParts.filter( QStringLiteral( "GEOS" ) ); if ( geos.size() == 1 ) { - mGeosAvailable = ( geos[0].indexOf( "=1" ) > -1 ); + mGeosAvailable = ( geos[0].indexOf( QLatin1String( "=1" ) ) > -1 ); } - QStringList gist = postgisParts.filter( "STATS" ); + QStringList gist = postgisParts.filter( QStringLiteral( "STATS" ) ); if ( gist.size() == 1 ) { - mGistAvailable = ( gist[0].indexOf( "=1" ) > -1 ); + mGistAvailable = ( gist[0].indexOf( QLatin1String( "=1" ) ) > -1 ); } - QStringList proj = postgisParts.filter( "PROJ" ); + QStringList proj = postgisParts.filter( QStringLiteral( "PROJ" ) ); if ( proj.size() == 1 ) { - mProjAvailable = ( proj[0].indexOf( "=1" ) > -1 ); + mProjAvailable = ( proj[0].indexOf( QLatin1String( "=1" ) ) > -1 ); } } @@ -900,8 +900,8 @@ QString QgsPostgresConn::postgisVersion() mTopologyAvailable = false; if ( mPostgisVersionMajor > 1 ) { - QgsPostgresResult result( PQexec( "SELECT EXISTS ( SELECT c.oid FROM pg_class AS c JOIN pg_namespace AS n ON c.relnamespace=n.oid WHERE n.nspname='topology' AND c.relname='topology' )" ) ); - if ( result.PQntuples() >= 1 && result.PQgetvalue( 0, 0 ) == "t" ) + QgsPostgresResult result( PQexec( QStringLiteral( "SELECT EXISTS ( SELECT c.oid FROM pg_class AS c JOIN pg_namespace AS n ON c.relnamespace=n.oid WHERE n.nspname='topology' AND c.relname='topology' )" ) ) ); + if ( result.PQntuples() >= 1 && result.PQgetvalue( 0, 0 ) == QLatin1String( "t" ) ) { mTopologyAvailable = true; } @@ -912,7 +912,7 @@ QString QgsPostgresConn::postgisVersion() if ( mPostgresqlVersion >= 90000 ) { QgsDebugMsg( "Checking for pointcloud support" ); - result = PQexec( "SELECT oid FROM pg_catalog.pg_extension WHERE extname = 'pointcloud_postgis'", false ); + result = PQexec( QStringLiteral( "SELECT oid FROM pg_catalog.pg_extension WHERE extname = 'pointcloud_postgis'" ), false ); if ( result.PQntuples() == 1 ) { mPointcloudAvailable = true; @@ -926,16 +926,16 @@ QString QgsPostgresConn::postgisVersion() QString QgsPostgresConn::quotedIdentifier( const QString& ident ) { QString result = ident; - result.replace( '"', "\"\"" ); + result.replace( '"', QLatin1String( "\"\"" ) ); return result.prepend( '\"' ).append( '\"' ); } static QString quotedString( const QString& v ) { QString result = v; - result.replace( '\'', "''" ); + result.replace( '\'', QLatin1String( "''" ) ); if ( result.contains( '\\' ) ) - return result.replace( '\\', "\\\\" ).prepend( "E'" ).append( '\'' ); + return result.replace( '\\', QLatin1String( "\\\\" ) ).prepend( "E'" ).append( '\'' ); else return result.prepend( '\'' ).append( '\'' ); } @@ -943,7 +943,7 @@ static QString quotedString( const QString& v ) static QString doubleQuotedMapValue( const QString& v ) { QString result = v; - return "\"" + result.replace( '\\', "\\\\\\\\" ).replace( '\"', "\\\\\"" ).replace( '\'', "\\'" ) + "\""; + return "\"" + result.replace( '\\', QLatin1String( "\\\\\\\\" ) ).replace( '\"', QLatin1String( "\\\\\"" ) ).replace( '\'', QLatin1String( "\\'" ) ) + "\""; } static QString quotedMap( const QVariantMap& map ) @@ -953,7 +953,7 @@ static QString quotedMap( const QVariantMap& map ) { if ( !ret.isEmpty() ) { - ret += ","; + ret += QLatin1String( "," ); } ret.append( doubleQuotedMapValue( i.key() ) + "=>" + doubleQuotedMapValue( i.value().toString() ) ); @@ -968,7 +968,7 @@ static QString quotedList( const QVariantList& list ) { if ( !ret.isEmpty() ) { - ret += ","; + ret += QLatin1String( "," ); } ret.append( doubleQuotedMapValue( i->toString() ) ); } @@ -978,7 +978,7 @@ static QString quotedList( const QVariantList& list ) QString QgsPostgresConn::quotedValue( const QVariant& value ) { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); switch ( value.type() ) { @@ -1061,24 +1061,24 @@ bool QgsPostgresConn::openCursor( const QString& cursorName, const QString& sql { QgsDebugMsg( QString( "Starting read-only transaction: %1" ).arg( mPostgresqlVersion ) ); if ( mPostgresqlVersion >= 80000 ) - PQexecNR( "BEGIN READ ONLY" ); + PQexecNR( QStringLiteral( "BEGIN READ ONLY" ) ); else - PQexecNR( "BEGIN" ); + PQexecNR( QStringLiteral( "BEGIN" ) ); } QgsDebugMsgLevel( QString( "Binary cursor %1 for %2" ).arg( cursorName, sql ), 3 ); - return PQexecNR( QString( "DECLARE %1 BINARY CURSOR%2 FOR %3" ). - arg( cursorName, !mTransaction ? "" : QString( " WITH HOLD" ), sql ) ); + return PQexecNR( QStringLiteral( "DECLARE %1 BINARY CURSOR%2 FOR %3" ). + arg( cursorName, !mTransaction ? QLatin1String( "" ) : QStringLiteral( " WITH HOLD" ), sql ) ); } bool QgsPostgresConn::closeCursor( const QString& cursorName ) { - if ( !PQexecNR( QString( "CLOSE %1" ).arg( cursorName ) ) ) + if ( !PQexecNR( QStringLiteral( "CLOSE %1" ).arg( cursorName ) ) ) return false; if ( --mOpenCursors == 0 && !mTransaction ) { QgsDebugMsg( "Committing read-only transaction" ); - PQexecNR( "COMMIT" ); + PQexecNR( QStringLiteral( "COMMIT" ) ); } return true; @@ -1086,7 +1086,7 @@ bool QgsPostgresConn::closeCursor( const QString& cursorName ) QString QgsPostgresConn::uniqueCursorName() { - return QString( "qgis_%1" ).arg( ++mNextCursorId ); + return QStringLiteral( "qgis_%1" ).arg( ++mNextCursorId ); } bool QgsPostgresConn::PQexecNR( const QString& query, bool retry ) @@ -1113,7 +1113,7 @@ bool QgsPostgresConn::PQexecNR( const QString& query, bool retry ) if ( PQstatus() == CONNECTION_OK ) { - PQexecNR( "ROLLBACK" ); + PQexecNR( QStringLiteral( "ROLLBACK" ) ); } else if ( retry ) { @@ -1207,11 +1207,11 @@ bool QgsPostgresConn::begin() { if ( mTransaction ) { - return PQexecNR( "SAVEPOINT transaction_savepoint" ); + return PQexecNR( QStringLiteral( "SAVEPOINT transaction_savepoint" ) ); } else { - return PQexecNR( "BEGIN" ); + return PQexecNR( QStringLiteral( "BEGIN" ) ); } } @@ -1219,11 +1219,11 @@ bool QgsPostgresConn::commit() { if ( mTransaction ) { - return PQexecNR( "RELEASE SAVEPOINT transaction_savepoint" ); + return PQexecNR( QStringLiteral( "RELEASE SAVEPOINT transaction_savepoint" ) ); } else { - return PQexecNR( "COMMIT" ); + return PQexecNR( QStringLiteral( "COMMIT" ) ); } } @@ -1231,12 +1231,12 @@ bool QgsPostgresConn::rollback() { if ( mTransaction ) { - return PQexecNR( "ROLLBACK TO SAVEPOINT transaction_savepoint" ) - && PQexecNR( "RELEASE SAVEPOINT transaction_savepoint" ); + return PQexecNR( QStringLiteral( "ROLLBACK TO SAVEPOINT transaction_savepoint" ) ) + && PQexecNR( QStringLiteral( "RELEASE SAVEPOINT transaction_savepoint" ) ); } else { - return PQexecNR( "ROLLBACK" ); + return PQexecNR( QStringLiteral( "ROLLBACK" ) ); } } @@ -1252,7 +1252,7 @@ qint64 QgsPostgresConn::getBinaryInt( QgsPostgresResult &queryResult, int row, i QString buf; for ( size_t i = 0; i < s; i++ ) { - buf += QString( "%1 " ).arg( *( unsigned char * )( p + i ), 0, 16, QLatin1Char( ' ' ) ); + buf += QStringLiteral( "%1 " ).arg( *( unsigned char * )( p + i ), 0, 16, QLatin1Char( ' ' ) ); } QgsDebugMsg( QString( "int in hex:%1" ).arg( buf ) ); @@ -1328,28 +1328,28 @@ QString QgsPostgresConn::fieldExpression( const QgsField &fld, QString expr ) { const QString &type = fld.typeName(); expr = expr.arg( quotedIdentifier( fld.name() ) ); - if ( type == "money" ) + if ( type == QLatin1String( "money" ) ) { - return QString( "cash_out(%1)::text" ).arg( expr ); + return QStringLiteral( "cash_out(%1)::text" ).arg( expr ); } else if ( type.startsWith( '_' ) ) { //TODO: add native support for arrays - return QString( "array_out(%1)::text" ).arg( expr ); + return QStringLiteral( "array_out(%1)::text" ).arg( expr ); } - else if ( type == "bool" ) + else if ( type == QLatin1String( "bool" ) ) { - return QString( "boolout(%1)::text" ).arg( expr ); + return QStringLiteral( "boolout(%1)::text" ).arg( expr ); } - else if ( type == "geometry" ) + else if ( type == QLatin1String( "geometry" ) ) { - return QString( "%1(%2)" ) + return QStringLiteral( "%1(%2)" ) .arg( majorVersion() < 2 ? "asewkt" : "st_asewkt", expr ); } - else if ( type == "geography" ) + else if ( type == QLatin1String( "geography" ) ) { - return QString( "st_astext(%1)" ).arg( expr ); + return QStringLiteral( "st_astext(%1)" ).arg( expr ); } //TODO: add support for hstore else @@ -1365,17 +1365,17 @@ void QgsPostgresConn::deduceEndian() // version 7.4, binary cursors return data in XDR whereas previous versions // return data in the endian of the server - QgsPostgresResult res( PQexec( "select regclass('pg_class')::oid" ) ); + QgsPostgresResult res( PQexec( QStringLiteral( "select regclass('pg_class')::oid" ) ) ); QString oidValue = res.PQgetvalue( 0, 0 ); QgsDebugMsg( "Creating binary cursor" ); // get the same value using a binary cursor - openCursor( "oidcursor", "select regclass('pg_class')::oid" ); + openCursor( QStringLiteral( "oidcursor" ), QStringLiteral( "select regclass('pg_class')::oid" ) ); QgsDebugMsg( "Fetching a record and attempting to get check endian-ness" ); - res = PQexec( "fetch forward 1 from oidcursor" ); + res = PQexec( QStringLiteral( "fetch forward 1 from oidcursor" ) ); mSwapEndian = true; if ( res.PQntuples() > 0 ) @@ -1391,7 +1391,7 @@ void QgsPostgresConn::deduceEndian() mSwapEndian = false; } - closeCursor( "oidcursor" ); + closeCursor( QStringLiteral( "oidcursor" ) ); } void QgsPostgresConn::retrieveLayerTypes( QgsPostgresLayerProperty &layerProperty, bool useEstimatedMetadata ) @@ -1400,7 +1400,7 @@ void QgsPostgresConn::retrieveLayerTypes( QgsPostgresLayerProperty &layerPropert if ( !layerProperty.schemaName.isEmpty() ) { - table = QString( "%1.%2" ) + table = QStringLiteral( "%1.%2" ) .arg( quotedIdentifier( layerProperty.schemaName ), quotedIdentifier( layerProperty.tableName ) ); } @@ -1415,18 +1415,18 @@ void QgsPostgresConn::retrieveLayerTypes( QgsPostgresLayerProperty &layerPropert // our estimatation ignores that a where clause might restrict the feature type or srid if ( useEstimatedMetadata ) { - table = QString( "(SELECT %1 FROM %2%3 LIMIT %4) AS t" ) + table = QStringLiteral( "(SELECT %1 FROM %2%3 LIMIT %4) AS t" ) .arg( quotedIdentifier( layerProperty.geometryColName ), table, - layerProperty.sql.isEmpty() ? "" : QString( " WHERE %1" ).arg( layerProperty.sql ) ) + layerProperty.sql.isEmpty() ? QLatin1String( "" ) : QStringLiteral( " WHERE %1" ).arg( layerProperty.sql ) ) .arg( sGeomTypeSelectLimit ); } else if ( !layerProperty.sql.isEmpty() ) { - table += QString( " WHERE %1" ).arg( layerProperty.sql ); + table += QStringLiteral( " WHERE %1" ).arg( layerProperty.sql ); } - QString query = "SELECT DISTINCT "; + QString query = QStringLiteral( "SELECT DISTINCT " ); bool castToGeometry = layerProperty.geometryColType == sctGeography || layerProperty.geometryColType == sctPcPatch; @@ -1434,7 +1434,7 @@ void QgsPostgresConn::retrieveLayerTypes( QgsPostgresLayerProperty &layerPropert QgsWkbTypes::Type type = layerProperty.types.value( 0, QgsWkbTypes::Unknown ); if ( type == QgsWkbTypes::Unknown ) { - query += QString( "upper(geometrytype(%1%2))" ) + query += QStringLiteral( "upper(geometrytype(%1%2))" ) .arg( quotedIdentifier( layerProperty.geometryColName ), castToGeometry ? "::geometry" : "" ); } @@ -1448,7 +1448,7 @@ void QgsPostgresConn::retrieveLayerTypes( QgsPostgresLayerProperty &layerPropert int srid = layerProperty.srids.value( 0, INT_MIN ); if ( srid == INT_MIN ) { - query += QString( "%1(%2%3)" ) + query += QStringLiteral( "%1(%2%3)" ) .arg( majorVersion() < 2 ? "srid" : "st_srid", quotedIdentifier( layerProperty.geometryColName ), castToGeometry ? "::geometry" : "" ); @@ -1460,7 +1460,7 @@ void QgsPostgresConn::retrieveLayerTypes( QgsPostgresLayerProperty &layerPropert if ( !layerProperty.force2d ) { - query += QString( ",%1(%2%3)" ) + query += QStringLiteral( ",%1(%2%3)" ) .arg( majorVersion() < 2 ? "ndims" : "st_ndims", quotedIdentifier( layerProperty.geometryColName ), castToGeometry ? "::geometry" : "" ); @@ -1526,46 +1526,46 @@ void QgsPostgresConn::postgisWkbType( QgsWkbTypes::Type wkbType, QString& geomet dim = 3; FALLTHROUGH; case QgsWkbTypes::Point: - geometryType = "POINT"; + geometryType = QStringLiteral( "POINT" ); break; case QgsWkbTypes::LineString25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::LineString: - geometryType = "LINESTRING"; + geometryType = QStringLiteral( "LINESTRING" ); break; case QgsWkbTypes::Polygon25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::Polygon: - geometryType = "POLYGON"; + geometryType = QStringLiteral( "POLYGON" ); break; case QgsWkbTypes::MultiPoint25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::MultiPoint: - geometryType = "MULTIPOINT"; + geometryType = QStringLiteral( "MULTIPOINT" ); break; case QgsWkbTypes::MultiLineString25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::MultiLineString: - geometryType = "MULTILINESTRING"; + geometryType = QStringLiteral( "MULTILINESTRING" ); break; case QgsWkbTypes::MultiPolygon25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::MultiPolygon: - geometryType = "MULTIPOLYGON"; + geometryType = QStringLiteral( "MULTIPOLYGON" ); break; case QgsWkbTypes::Unknown: - geometryType = "GEOMETRY"; + geometryType = QStringLiteral( "GEOMETRY" ); break; case QgsWkbTypes::NoGeometry: @@ -1589,19 +1589,19 @@ QString QgsPostgresConn::postgisTypeFilter( QString geomCol, QgsWkbTypes::Type w { geomCol = quotedIdentifier( geomCol ); if ( castToGeometry ) - geomCol += "::geometry"; + geomCol += QLatin1String( "::geometry" ); QgsWkbTypes::GeometryType geomType = QgsWkbTypes::geometryType( wkbType ); switch ( geomType ) { case QgsWkbTypes::PointGeometry: - return QString( "upper(geometrytype(%1)) IN ('POINT','POINTZ','POINTM','POINTZM','MULTIPOINT','MULTIPOINTZ','MULTIPOINTM','MULTIPOINTZM')" ).arg( geomCol ); + return QStringLiteral( "upper(geometrytype(%1)) IN ('POINT','POINTZ','POINTM','POINTZM','MULTIPOINT','MULTIPOINTZ','MULTIPOINTM','MULTIPOINTZM')" ).arg( geomCol ); case QgsWkbTypes::LineGeometry: - return QString( "upper(geometrytype(%1)) IN ('LINESTRING','LINESTRINGZ','LINESTRINGM','LINESTRINGZM','CIRCULARSTRING','CIRCULARSTRINGZ','CIRCULARSTRINGM','CIRCULARSTRINGZM','COMPOUNDCURVE','COMPOUNDCURVEZ','COMPOUNDCURVEM','COMPOUNDCURVEZM','MULTILINESTRING','MULTILINESTRINGZ','MULTILINESTRINGM','MULTILINESTRINGZM','MULTICURVE','MULTICURVEZ','MULTICURVEM','MULTICURVEZM')" ).arg( geomCol ); + return QStringLiteral( "upper(geometrytype(%1)) IN ('LINESTRING','LINESTRINGZ','LINESTRINGM','LINESTRINGZM','CIRCULARSTRING','CIRCULARSTRINGZ','CIRCULARSTRINGM','CIRCULARSTRINGZM','COMPOUNDCURVE','COMPOUNDCURVEZ','COMPOUNDCURVEM','COMPOUNDCURVEZM','MULTILINESTRING','MULTILINESTRINGZ','MULTILINESTRINGM','MULTILINESTRINGZM','MULTICURVE','MULTICURVEZ','MULTICURVEM','MULTICURVEZM')" ).arg( geomCol ); case QgsWkbTypes::PolygonGeometry: - return QString( "upper(geometrytype(%1)) IN ('POLYGON','POLYGONZ','POLYGONM','POLYGONZM','CURVEPOLYGON','CURVEPOLYGONZ','CURVEPOLYGONM','CURVEPOLYGONZM','MULTIPOLYGON','MULTIPOLYGONZ','MULTIPOLYGONM','MULTIPOLYGONZM','MULTIPOLYGONM','MULTISURFACE','MULTISURFACEZ','MULTISURFACEM','MULTISURFACEZM','POLYHEDRALSURFACE','TIN')" ).arg( geomCol ); + return QStringLiteral( "upper(geometrytype(%1)) IN ('POLYGON','POLYGONZ','POLYGONM','POLYGONZM','CURVEPOLYGON','CURVEPOLYGONZ','CURVEPOLYGONM','CURVEPOLYGONZM','MULTIPOLYGON','MULTIPOLYGONZ','MULTIPOLYGONM','MULTIPOLYGONZM','MULTIPOLYGONM','MULTISURFACE','MULTISURFACEZ','MULTISURFACEM','MULTISURFACEZM','POLYHEDRALSURFACE','TIN')" ).arg( geomCol ); case QgsWkbTypes::NullGeometry: - return QString( "geometrytype(%1) IS NULL" ).arg( geomCol ); + return QStringLiteral( "geometrytype(%1) IS NULL" ).arg( geomCol ); default: //unknown geometry return QString::null; } @@ -1623,11 +1623,11 @@ QgsWkbTypes::Type QgsPostgresConn::wkbTypeFromPostgis( const QString& type ) // of Polygons and Triangles. // So, since QGIS does not natively support PS and TIN, but we would like to open them if possible, // we consider them as multipolygons. WKB will be converted by the feature iterator - if (( type == "POLYHEDRALSURFACE" ) || ( type == "TIN" ) ) + if (( type == QLatin1String( "POLYHEDRALSURFACE" ) ) || ( type == QLatin1String( "TIN" ) ) ) { return QgsWkbTypes::MultiPolygon; } - else if ( type == "TRIANGLE" ) + else if ( type == QLatin1String( "TRIANGLE" ) ) { return QgsWkbTypes::Polygon; } @@ -1696,20 +1696,20 @@ QgsWkbTypes::Type QgsPostgresConn::wkbTypeFromGeomType( QgsWkbTypes::GeometryTyp QStringList QgsPostgresConn::connectionList() { QSettings settings; - settings.beginGroup( "/PostgreSQL/connections" ); + settings.beginGroup( QStringLiteral( "/PostgreSQL/connections" ) ); return settings.childGroups(); } QString QgsPostgresConn::selectedConnection() { QSettings settings; - return settings.value( "/PostgreSQL/connections/selected" ).toString(); + return settings.value( QStringLiteral( "/PostgreSQL/connections/selected" ) ).toString(); } void QgsPostgresConn::setSelectedConnection( const QString& name ) { QSettings settings; - return settings.setValue( "/PostgreSQL/connections/selected", name ); + return settings.setValue( QStringLiteral( "/PostgreSQL/connections/selected" ), name ); } QgsDataSourceUri QgsPostgresConn::connUri( const QString& theConnName ) @@ -1725,7 +1725,7 @@ QgsDataSourceUri QgsPostgresConn::connUri( const QString& theConnName ) QString port = settings.value( key + "/port" ).toString(); if ( port.length() == 0 ) { - port = "5432"; + port = QStringLiteral( "5432" ); } QString database = settings.value( key + "/database" ).toString(); @@ -1734,12 +1734,12 @@ QgsDataSourceUri QgsPostgresConn::connUri( const QString& theConnName ) QString username; QString password; - if ( settings.value( key + "/saveUsername" ).toString() == "true" ) + if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) ) { username = settings.value( key + "/username" ).toString(); } - if ( settings.value( key + "/savePassword" ).toString() == "true" ) + if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) ) { password = settings.value( key + "/password" ).toString(); } @@ -1749,7 +1749,7 @@ QgsDataSourceUri QgsPostgresConn::connUri( const QString& theConnName ) { username = settings.value( key + "/username" ).toString(); - if ( settings.value( key + "/save" ).toString() == "true" ) + if ( settings.value( key + "/save" ).toString() == QLatin1String( "true" ) ) { password = settings.value( key + "/password" ).toString(); } diff --git a/src/providers/postgres/qgspostgresconn.h b/src/providers/postgres/qgspostgresconn.h index 4af1228d8e81..0b1b290bf6c6 100644 --- a/src/providers/postgres/qgspostgresconn.h +++ b/src/providers/postgres/qgspostgresconn.h @@ -134,13 +134,13 @@ struct QgsPostgresLayerProperty sridString += QString::number( srid ); } - return QString( "%1.%2.%3 type=%4 srid=%5 pkCols=%6 sql=%7 nSpCols=%8 force2d=%9" ) + return QStringLiteral( "%1.%2.%3 type=%4 srid=%5 pkCols=%6 sql=%7 nSpCols=%8 force2d=%9" ) .arg( schemaName, tableName, geometryColName, typeString, sridString, - pkCols.join( "|" ), + pkCols.join( QStringLiteral( "|" ) ), sql ) .arg( nSpCols ) .arg( force2d ? "yes" : "no" ); @@ -306,7 +306,7 @@ class QgsPostgresConn : public QObject qint64 getBinaryInt( QgsPostgresResult &queryResult, int row, int col ); - QString fieldExpression( const QgsField &fld, QString expr = "%1" ); + QString fieldExpression( const QgsField &fld, QString expr = QStringLiteral( "%1" ) ); QString connInfo() const { return mConnInfo; } diff --git a/src/providers/postgres/qgspostgresdataitems.cpp b/src/providers/postgres/qgspostgresdataitems.cpp index 7132a60de408..0a41dbf7af31 100644 --- a/src/providers/postgres/qgspostgresdataitems.cpp +++ b/src/providers/postgres/qgspostgresdataitems.cpp @@ -38,7 +38,7 @@ QGISEXTERN bool deleteSchema( const QString& schema, const QgsDataSourceUri& uri QgsPGConnectionItem::QgsPGConnectionItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); } QgsPGConnectionItem::~QgsPGConnectionItem() @@ -170,7 +170,7 @@ void QgsPGConnectionItem::createSchema() } //create the schema - QString sql = QString( "CREATE SCHEMA %1" ).arg( QgsPostgresConn::quotedIdentifier( schemaName ) ); + QString sql = QStringLiteral( "CREATE SCHEMA %1" ).arg( QgsPostgresConn::quotedIdentifier( schemaName ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) @@ -212,7 +212,7 @@ bool QgsPGConnectionItem::handleDrop( const QMimeData * data, QString toSchema ) QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data ); Q_FOREACH ( const QgsMimeDataUtils::Uri& u, lst ) { - if ( u.layerType != "vector" ) + if ( u.layerType != QLatin1String( "vector" ) ) { importResults.append( tr( "%1: Not a vector layer!" ).arg( u.name ) ); hasError = true; // only vectors can be imported @@ -224,7 +224,7 @@ bool QgsPGConnectionItem::handleDrop( const QMimeData * data, QString toSchema ) if ( srcLayer->isValid() ) { - uri.setDataSource( QString(), u.name, srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? "geom" : QString() ); + uri.setDataSource( QString(), u.name, srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? QStringLiteral( "geom" ) : QString() ); QgsDebugMsg( "URI " + uri.uri( false ) ); if ( !toSchema.isNull() ) @@ -234,14 +234,14 @@ bool QgsPGConnectionItem::handleDrop( const QMimeData * data, QString toSchema ) QgsVectorLayerImport::ImportError err; QString importError; - err = QgsVectorLayerImport::importLayer( srcLayer, uri.uri( false ), "postgres", srcLayer->crs(), false, &importError, false, nullptr, progress ); + err = QgsVectorLayerImport::importLayer( srcLayer, uri.uri( false ), QStringLiteral( "postgres" ), srcLayer->crs(), false, &importError, false, nullptr, progress ); if ( err == QgsVectorLayerImport::NoError ) importResults.append( tr( "%1: OK!" ).arg( u.name ) ); else if ( err == QgsVectorLayerImport::ErrUserCancelled ) cancelled = true; else { - importResults.append( QString( "%1: %2" ).arg( u.name, importError ) ); + importResults.append( QStringLiteral( "%1: %2" ).arg( u.name, importError ) ); hasError = true; } } @@ -267,7 +267,7 @@ bool QgsPGConnectionItem::handleDrop( const QMimeData * data, QString toSchema ) { QgsMessageOutput *output = QgsMessageOutput::createMessageOutput(); output->setTitle( tr( "Import to PostGIS database" ) ); - output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( "\n" ), QgsMessageOutput::MessageText ); + output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText ); output->showMessage(); } else @@ -281,7 +281,7 @@ bool QgsPGConnectionItem::handleDrop( const QMimeData * data, QString toSchema ) // --------------------------------------------------------------------------- QgsPGLayerItem::QgsPGLayerItem( QgsDataItem* parent, QString name, QString path, QgsLayerItem::LayerType layerType, QgsPostgresLayerProperty layerProperty ) - : QgsLayerItem( parent, name, path, QString(), layerType, "postgres" ) + : QgsLayerItem( parent, name, path, QString(), layerType, QStringLiteral( "postgres" ) ) , mLayerProperty( layerProperty ) { mUri = createUri(); @@ -375,12 +375,12 @@ void QgsPGLayerItem::renameLayer() QString sql; if ( mLayerProperty.isView ) { - sql = QString( "ALTER %1 VIEW %2 RENAME TO %3" ).arg( mLayerProperty.relKind == "m" ? QString( "MATERIALIZED" ) : QString(), + sql = QStringLiteral( "ALTER %1 VIEW %2 RENAME TO %3" ).arg( mLayerProperty.relKind == QLatin1String( "m" ) ? QStringLiteral( "MATERIALIZED" ) : QString(), oldName, newName ); } else { - sql = QString( "ALTER TABLE %1 RENAME TO %2" ).arg( oldName, newName ); + sql = QStringLiteral( "ALTER TABLE %1 RENAME TO %2" ).arg( oldName, newName ); } QgsPostgresResult result( conn->PQexec( sql ) ); @@ -421,7 +421,7 @@ void QgsPGLayerItem::truncateTable() } QString tableRef = schemaTableName + QgsPostgresConn::quotedIdentifier( tableName ); - QString sql = QString( "TRUNCATE TABLE %1" ).arg( tableRef ); + QString sql = QStringLiteral( "TRUNCATE TABLE %1" ).arg( tableRef ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) @@ -461,7 +461,7 @@ QgsPGSchemaItem::QgsPGSchemaItem( QgsDataItem* parent, QString connectionName, Q : QgsDataCollectionItem( parent, name, path ) , mConnectionName( connectionName ) { - mIconName = "mIconDbSchema.png"; + mIconName = QStringLiteral( "mIconDbSchema.png" ); } QgsPGSchemaItem::~QgsPGSchemaItem() @@ -560,7 +560,7 @@ void QgsPGSchemaItem::deleteSchema() return; } - QString sql = QString( "SELECT table_name FROM information_schema.tables WHERE table_schema='%1'" ).arg( mName ); + QString sql = QStringLiteral( "SELECT table_name FROM information_schema.tables WHERE table_schema='%1'" ).arg( mName ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() != PGRES_TUPLES_OK ) { @@ -582,10 +582,10 @@ void QgsPGSchemaItem::deleteSchema() int count = result.PQntuples(); if ( count > 0 ) { - QString objects = childObjects.join( "\n" ); + QString objects = childObjects.join( QStringLiteral( "\n" ) ); if ( count > maxListed ) { - objects += QString( "\n[%1 additional objects not listed]" ).arg( count - maxListed ); + objects += QStringLiteral( "\n[%1 additional objects not listed]" ).arg( count - maxListed ); } if ( QMessageBox::question( nullptr, QObject::tr( "Delete Schema" ), QObject::tr( "Schema '%1' contains objects:\n\n%2\n\nAre you sure you want to delete the schema and all these objects?" ).arg( mName, objects ), @@ -634,7 +634,7 @@ void QgsPGSchemaItem::renameSchema() } //rename the schema - QString sql = QString( "ALTER SCHEMA %1 RENAME TO %2" ) + QString sql = QStringLiteral( "ALTER SCHEMA %1 RENAME TO %2" ) .arg( schemaName, QgsPostgresConn::quotedIdentifier( dlg.name() ) ); QgsPostgresResult result( conn->PQexec( sql ) ); @@ -706,7 +706,7 @@ QgsPGRootItem::QgsPGRootItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconPostgis.svg"; + mIconName = QStringLiteral( "mIconPostgis.svg" ); populate(); } diff --git a/src/providers/postgres/qgspostgresfeatureiterator.cpp b/src/providers/postgres/qgspostgresfeatureiterator.cpp index 9ba1778b5c10..c51d0d03b617 100644 --- a/src/providers/postgres/qgspostgresfeatureiterator.cpp +++ b/src/providers/postgres/qgspostgresfeatureiterator.cpp @@ -100,7 +100,7 @@ QgsPostgresFeatureIterator::QgsPostgresFeatureIterator( QgsPostgresFeatureSource } mFilterRequiresGeometry = request.filterExpression()->needsGeometry(); - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { //IMPORTANT - this MUST be the last clause added! QgsPostgresExpressionCompiler compiler = QgsPostgresExpressionCompiler( source ); @@ -170,11 +170,11 @@ QgsPostgresFeatureIterator::QgsPostgresFeatureIterator( QgsPostgresFeatureSource if ( !mOrderByCompiled ) limitAtProvider = false; - bool success = declareCursor( whereClause, limitAtProvider ? mRequest.limit() : -1, false, orderByParts.join( "," ) ); + bool success = declareCursor( whereClause, limitAtProvider ? mRequest.limit() : -1, false, orderByParts.join( QStringLiteral( "," ) ) ); if ( !success && useFallbackWhereClause ) { //try with the fallback where clause, eg for cases when using compiled expression failed to prepare - success = declareCursor( fallbackWhereClause, -1, false, orderByParts.join( "," ) ); + success = declareCursor( fallbackWhereClause, -1, false, orderByParts.join( QStringLiteral( "," ) ) ); if ( success ) mExpressionCompiled = false; } @@ -224,7 +224,7 @@ bool QgsPostgresFeatureIterator::fetchFeature( QgsFeature& feature ) if ( mFeatureQueue.empty() && !mLastFetch ) { - QString fetch = QString( "FETCH FORWARD %1 FROM %2" ).arg( mFeatureQueueSize ).arg( mCursorName ); + QString fetch = QStringLiteral( "FETCH FORWARD %1 FROM %2" ).arg( mFeatureQueueSize ).arg( mCursorName ); QgsDebugMsgLevel( QString( "fetching %1 features." ).arg( mFeatureQueueSize ), 4 ); lock(); @@ -341,7 +341,7 @@ bool QgsPostgresFeatureIterator::rewind() // move cursor to first record lock(); - mConn->PQexecNR( QString( "move absolute 0 in %1" ).arg( mCursorName ) ); + mConn->PQexecNR( QStringLiteral( "move absolute 0 in %1" ).arg( mCursorName ) ); unlock(); mFeatureQueue.clear(); mFetched = 0; @@ -389,19 +389,19 @@ QString QgsPostgresFeatureIterator::whereClauseRect() if ( !rect.isFinite() ) { QgsMessageLog::logMessage( QObject::tr( "Infinite filter rectangle specified" ), QObject::tr( "PostGIS" ) ); - return "false"; + return QStringLiteral( "false" ); } QString qBox; if ( mConn->majorVersion() < 2 ) { - qBox = QString( "setsrid('BOX3D(%1)'::box3d,%2)" ) + qBox = QStringLiteral( "setsrid('BOX3D(%1)'::box3d,%2)" ) .arg( rect.asWktCoordinates(), mSource->mRequestedSrid.isEmpty() ? mSource->mDetectedSrid : mSource->mRequestedSrid ); } else { - qBox = QString( "st_makeenvelope(%1,%2,%3,%4,%5)" ) + qBox = QStringLiteral( "st_makeenvelope(%1,%2,%3,%4,%5)" ) .arg( qgsDoubleToString( rect.xMinimum() ), qgsDoubleToString( rect.yMinimum() ), qgsDoubleToString( rect.xMaximum() ), @@ -412,7 +412,7 @@ QString QgsPostgresFeatureIterator::whereClauseRect() bool castToGeometry = mSource->mSpatialColType == sctGeography || mSource->mSpatialColType == sctPcPatch; - QString whereClause = QString( "%1%2 && %3" ) + QString whereClause = QStringLiteral( "%1%2 && %3" ) .arg( QgsPostgresConn::quotedIdentifier( mSource->mGeometryColumn ), castToGeometry ? "::geometry" : "", qBox ); @@ -421,8 +421,8 @@ QString QgsPostgresFeatureIterator::whereClauseRect() { QString curveToLineFn; // in postgis < 1.5 the st_curvetoline function does not exist if ( mConn->majorVersion() >= 2 || ( mConn->majorVersion() == 1 && mConn->minorVersion() >= 5 ) ) - curveToLineFn = "st_curvetoline"; // st_ prefix is always used - whereClause += QString( " AND %1(%2(%3%4),%5)" ) + curveToLineFn = QStringLiteral( "st_curvetoline" ); // st_ prefix is always used + whereClause += QStringLiteral( " AND %1(%2(%3%4),%5)" ) .arg( mConn->majorVersion() < 2 ? "intersects" : "st_intersects", curveToLineFn, QgsPostgresConn::quotedIdentifier( mSource->mGeometryColumn ), @@ -432,7 +432,7 @@ QString QgsPostgresFeatureIterator::whereClauseRect() if ( !mSource->mRequestedSrid.isEmpty() && ( mSource->mRequestedSrid != mSource->mDetectedSrid || mSource->mRequestedSrid.toInt() == 0 ) ) { - whereClause += QString( " AND %1(%2%3)=%4" ) + whereClause += QStringLiteral( " AND %1(%2%3)=%4" ) .arg( mConn->majorVersion() < 2 ? "srid" : "st_srid", QgsPostgresConn::quotedIdentifier( mSource->mGeometryColumn ), castToGeometry ? "::geometry" : "", @@ -441,7 +441,7 @@ QString QgsPostgresFeatureIterator::whereClauseRect() if ( mSource->mRequestedGeomType != QgsWkbTypes::Unknown && mSource->mRequestedGeomType != mSource->mDetectedGeomType ) { - whereClause += QString( " AND %1" ).arg( QgsPostgresConn::postgisTypeFilter( mSource->mGeometryColumn, ( QgsWkbTypes::Type )mSource->mRequestedGeomType, castToGeometry ) ); + whereClause += QStringLiteral( " AND %1" ).arg( QgsPostgresConn::postgisTypeFilter( mSource->mGeometryColumn, ( QgsWkbTypes::Type )mSource->mRequestedGeomType, castToGeometry ) ); } return whereClause; @@ -461,7 +461,7 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long } #endif - QString query( "SELECT " ), delim( "" ); + QString query( QStringLiteral( "SELECT " ) ), delim( QLatin1String( "" ) ); if ( mFetchGeometry ) { @@ -469,11 +469,11 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long if ( mSource->mSpatialColType == sctGeography || mSource->mSpatialColType == sctPcPatch ) - geom += "::geometry"; + geom += QLatin1String( "::geometry" ); if ( mSource->mForce2d ) { - geom = QString( "%1(%2)" ) + geom = QStringLiteral( "%1(%2)" ) // Force_2D before 2.0 .arg( mConn->majorVersion() < 2 ? "force_2d" // ST_Force2D since 2.1.0 @@ -503,13 +503,13 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long // Optimize simplification for rendering if ( mConn->majorVersion() < 2 ) { - simplifyPostgisMethod = "snaptogrid"; + simplifyPostgisMethod = QStringLiteral( "snaptogrid" ); } else { // Default to st_snaptogrid - simplifyPostgisMethod = "st_snaptogrid"; + simplifyPostgisMethod = QStringLiteral( "st_snaptogrid" ); if (( mConn->majorVersion() == 2 && mConn->minorVersion() >= 2 ) || mConn->majorVersion() > 2 ) @@ -519,7 +519,7 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long // We should perhaps use it always for Linestrings, even if threshold > 1 ? if ( mRequest.simplifyMethod().threshold() <= 1.0 ) { - simplifyPostgisMethod = "st_removerepeatedpoints"; + simplifyPostgisMethod = QStringLiteral( "st_removerepeatedpoints" ); postSimplification = true; // Ask to apply a post-filtering simplification } } @@ -530,11 +530,11 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long // preserve topology if ( mConn->majorVersion() < 2 ) { - simplifyPostgisMethod = "simplifypreservetopology"; + simplifyPostgisMethod = QStringLiteral( "simplifypreservetopology" ); } else { - simplifyPostgisMethod = "st_simplifypreservetopology"; + simplifyPostgisMethod = QStringLiteral( "st_simplifypreservetopology" ); } } QgsDebugMsg( @@ -543,20 +543,20 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long .arg( simplifyPostgisMethod ) ); - geom = QString( "%1(%2,%3)" ) + geom = QStringLiteral( "%1(%2,%3)" ) .arg( simplifyPostgisMethod, geom ) .arg( mRequest.simplifyMethod().tolerance() * 0.8 ); //-> Default factor for the maximum displacement distance for simplification, similar as GeoServer does // Post-simplification if ( postSimplification ) { - geom = QString( "st_simplify( %1, %2, true )" ) + geom = QStringLiteral( "st_simplify( %1, %2, true )" ) .arg( geom ) .arg( mRequest.simplifyMethod().tolerance() * 0.7 ); //-> We use a smaller tolerance than pre-filtering to be on the safe side } } - geom = QString( "%1(%2,'%3')" ) + geom = QStringLiteral( "%1(%2,'%3')" ) .arg( mConn->majorVersion() < 2 ? "asbinary" : "st_asbinary", geom, QgsPostgresProvider::endianString() ); @@ -608,13 +608,13 @@ bool QgsPostgresFeatureIterator::declareCursor( const QString& whereClause, long query += " FROM " + mSource->mQuery; if ( !whereClause.isEmpty() ) - query += QString( " WHERE %1" ).arg( whereClause ); + query += QStringLiteral( " WHERE %1" ).arg( whereClause ); if ( limit >= 0 ) - query += QString( " LIMIT %1" ).arg( limit ); + query += QStringLiteral( " LIMIT %1" ).arg( limit ); if ( !orderBy.isEmpty() ) - query += QString( " ORDER BY %1 " ).arg( orderBy ); + query += QStringLiteral( " ORDER BY %1 " ).arg( orderBy ); lock(); if ( !mConn->openCursor( mCursorName, query ) ) @@ -805,7 +805,7 @@ QgsPostgresFeatureSource::QgsPostgresFeatureSource( const QgsPostgresProvider* p { mSqlWhereClause = p->filterWhereClause(); - if ( mSqlWhereClause.startsWith( " WHERE " ) ) + if ( mSqlWhereClause.startsWith( QLatin1String( " WHERE " ) ) ) mSqlWhereClause = mSqlWhereClause.mid( 7 ); if ( p->mTransaction ) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 350d5050fc9f..2cca87a975f2 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -38,9 +38,9 @@ #include "qgspostgrestransaction.h" #include "qgslogger.h" -const QString POSTGRES_KEY = "postgres"; -const QString POSTGRES_DESCRIPTION = "PostgreSQL/PostGIS data provider"; -static const QString EDITOR_WIDGET_STYLES_TABLE = "qgis_editor_widget_styles"; +const QString POSTGRES_KEY = QStringLiteral( "postgres" ); +const QString POSTGRES_DESCRIPTION = QStringLiteral( "PostgreSQL/PostGIS data provider" ); +static const QString EDITOR_WIDGET_STYLES_TABLE = QStringLiteral( "qgis_editor_widget_styles" ); inline qint64 PKINT2FID( qint32 x ) { @@ -113,7 +113,7 @@ QgsPostgresProvider::QgsPostgresProvider( QString const & uri ) { mIsQuery = true; mQuery = mTableName; - mTableName = ""; + mTableName = QLatin1String( "" ); } else { @@ -200,42 +200,42 @@ QgsPostgresProvider::QgsPostgresProvider( QString const & uri ) //fill type names into sets setNativeTypes( QList<NativeType>() // integer types - << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), "int2", QVariant::Int, -1, -1, 0, 0 ) - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), "int4", QVariant::Int, -1, -1, 0, 0 ) - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), "int8", QVariant::LongLong, -1, -1, 0, 0 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), "numeric", QVariant::Double, 1, 20, 0, 20 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), "decimal", QVariant::Double, 1, 20, 0, 20 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), QStringLiteral( "int2" ), QVariant::Int, -1, -1, 0, 0 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), QStringLiteral( "int4" ), QVariant::Int, -1, -1, 0, 0 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), QStringLiteral( "int8" ), QVariant::LongLong, -1, -1, 0, 0 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 20, 0, 20 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 20, 0, 20 ) // floating point - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), "real", QVariant::Double, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "double precision", QVariant::Double, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 ) // string types - << QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), "char", QVariant::String, 1, 255, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length (varchar)" ), "varchar", QVariant::String, 1, 255, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), "text", QVariant::String, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Text, fixed length (char)" ), QStringLiteral( "char" ), QVariant::String, 1, 255, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Text, limited variable length (varchar)" ), QStringLiteral( "varchar" ), QVariant::String, 1, 255, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 ) // date type - << QgsVectorDataProvider::NativeType( tr( "Date" ), "date", QVariant::Date, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Time" ), "time", QVariant::Time, -1, -1, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), "timestamp without time zone", QVariant::DateTime, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "timestamp without time zone" ), QVariant::DateTime, -1, -1, -1, -1 ) // complex types - << QgsVectorDataProvider::NativeType( tr( "Map" ), "hstore", QVariant::Map, -1, -1, -1, -1, QVariant::String ) - << QgsVectorDataProvider::NativeType( tr( "Array of number (integer - 32bit)" ), "int4[]", QVariant::List, -1, -1, -1, -1, QVariant::Int ) - << QgsVectorDataProvider::NativeType( tr( "Array of number (integer - 64bit)" ), "int8[]", QVariant::List, -1, -1, -1, -1, QVariant::LongLong ) - << QgsVectorDataProvider::NativeType( tr( "Array of number (double)" ), "double precision[]", QVariant::List, -1, -1, -1, -1, QVariant::Double ) - << QgsVectorDataProvider::NativeType( tr( "Array of text" ), "text[]", QVariant::StringList, -1, -1, -1, -1, QVariant::String ) + << QgsVectorDataProvider::NativeType( tr( "Map" ), QStringLiteral( "hstore" ), QVariant::Map, -1, -1, -1, -1, QVariant::String ) + << QgsVectorDataProvider::NativeType( tr( "Array of number (integer - 32bit)" ), QStringLiteral( "int4[]" ), QVariant::List, -1, -1, -1, -1, QVariant::Int ) + << QgsVectorDataProvider::NativeType( tr( "Array of number (integer - 64bit)" ), QStringLiteral( "int8[]" ), QVariant::List, -1, -1, -1, -1, QVariant::LongLong ) + << QgsVectorDataProvider::NativeType( tr( "Array of number (double)" ), QStringLiteral( "double precision[]" ), QVariant::List, -1, -1, -1, -1, QVariant::Double ) + << QgsVectorDataProvider::NativeType( tr( "Array of text" ), QStringLiteral( "text[]" ), QVariant::StringList, -1, -1, -1, -1, QVariant::String ) ); QString key; switch ( mPrimaryKeyType ) { case pktOid: - key = "oid"; + key = QStringLiteral( "oid" ); break; case pktTid: - key = "tid"; + key = QStringLiteral( "tid" ); break; case pktInt: case pktUint64: @@ -329,7 +329,7 @@ void QgsPostgresProvider::disconnectDb() QString QgsPostgresProvider::storageType() const { - return "PostgreSQL database with PostGIS extension"; + return QStringLiteral( "PostgreSQL database with PostGIS extension" ); } #if QT_VERSION >= 0x050000 && QT_VERSION < 0x050600 @@ -362,48 +362,48 @@ QString QgsPostgresProvider::pkParamWhereClause( int offset, const char *alias ) QString whereClause; QString aliased; - if ( alias ) aliased = QString( "%1." ).arg( alias ); + if ( alias ) aliased = QStringLiteral( "%1." ).arg( alias ); switch ( mPrimaryKeyType ) { case pktTid: - whereClause = QString( "%2ctid=$%1" ).arg( offset ).arg( aliased ); + whereClause = QStringLiteral( "%2ctid=$%1" ).arg( offset ).arg( aliased ); break; case pktOid: - whereClause = QString( "%2oid=$%1" ).arg( offset ).arg( aliased ); + whereClause = QStringLiteral( "%2oid=$%1" ).arg( offset ).arg( aliased ); break; case pktInt: case pktUint64: Q_ASSERT( mPrimaryKeyAttrs.size() == 1 ); - whereClause = QString( "%3%1=$%2" ).arg( quotedIdentifier( field( mPrimaryKeyAttrs[0] ).name() ) ).arg( offset ).arg( aliased ); + whereClause = QStringLiteral( "%3%1=$%2" ).arg( quotedIdentifier( field( mPrimaryKeyAttrs[0] ).name() ) ).arg( offset ).arg( aliased ); break; case pktFidMap: { - QString delim = ""; + QString delim = QLatin1String( "" ); for ( int i = 0; i < mPrimaryKeyAttrs.size(); i++ ) { int idx = mPrimaryKeyAttrs[i]; QgsField fld = field( idx ); - whereClause += delim + QString( "%3%1=$%2" ).arg( connectionRO()->fieldExpression( fld ) ).arg( offset++ ).arg( aliased ); - delim = " AND "; + whereClause += delim + QStringLiteral( "%3%1=$%2" ).arg( connectionRO()->fieldExpression( fld ) ).arg( offset++ ).arg( aliased ); + delim = QStringLiteral( " AND " ); } } break; case pktUnknown: Q_ASSERT( !"FAILURE: Primary key unknown" ); - whereClause = "NULL"; + whereClause = QStringLiteral( "NULL" ); break; } if ( !mSqlWhereClause.isEmpty() ) { if ( !whereClause.isEmpty() ) - whereClause += " AND "; + whereClause += QLatin1String( " AND " ); whereClause += '(' + mSqlWhereClause + ')'; } @@ -425,7 +425,7 @@ void QgsPostgresProvider::appendPkParams( QgsFeatureId featureId, QStringList &p break; case pktTid: - params << QString( "'(%1,%2)'" ).arg( FID_TO_NUMBER( featureId ) >> 16 ).arg( FID_TO_NUMBER( featureId ) & 0xffff ); + params << QStringLiteral( "'(%1,%2)'" ).arg( FID_TO_NUMBER( featureId ) >> 16 ).arg( FID_TO_NUMBER( featureId ) & 0xffff ); break; case pktFidMap: @@ -445,7 +445,7 @@ void QgsPostgresProvider::appendPkParams( QgsFeatureId featureId, QStringList &p else { QgsDebugMsg( QString( "FAILURE: Key value %1 for feature %2 not found." ).arg( mPrimaryKeyAttrs[i] ).arg( featureId ) ); - params << "NULL"; + params << QStringLiteral( "NULL" ); } } @@ -473,23 +473,23 @@ QString QgsPostgresUtils::whereClause( QgsFeatureId featureId, const QgsFields& switch ( pkType ) { case pktTid: - whereClause = QString( "ctid='(%1,%2)'" ) + whereClause = QStringLiteral( "ctid='(%1,%2)'" ) .arg( FID_TO_NUMBER( featureId ) >> 16 ) .arg( FID_TO_NUMBER( featureId ) & 0xffff ); break; case pktOid: - whereClause = QString( "oid=%1" ).arg( featureId ); + whereClause = QStringLiteral( "oid=%1" ).arg( featureId ); break; case pktInt: Q_ASSERT( pkAttrs.size() == 1 ); - whereClause = QString( "%1=%2" ).arg( QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ).arg( FID2PKINT( featureId ) ); + whereClause = QStringLiteral( "%1=%2" ).arg( QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ).arg( FID2PKINT( featureId ) ); break; case pktUint64: Q_ASSERT( pkAttrs.size() == 1 ); - whereClause = QString( "%1=%2" ).arg( QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ).arg( featureId ); + whereClause = QStringLiteral( "%1=%2" ).arg( QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ).arg( featureId ); break; case pktFidMap: @@ -499,7 +499,7 @@ QString QgsPostgresUtils::whereClause( QgsFeatureId featureId, const QgsFields& { Q_ASSERT( pkVals.size() == pkAttrs.size() ); - QString delim = ""; + QString delim = QLatin1String( "" ); for ( int i = 0; i < pkAttrs.size(); i++ ) { int idx = pkAttrs[i]; @@ -507,24 +507,24 @@ QString QgsPostgresUtils::whereClause( QgsFeatureId featureId, const QgsFields& whereClause += delim + conn->fieldExpression( fld ); if ( pkVals[i].isNull() ) - whereClause += " IS NULL"; + whereClause += QLatin1String( " IS NULL" ); else whereClause += '=' + QgsPostgresConn::quotedValue( pkVals[i].toString() ); - delim = " AND "; + delim = QStringLiteral( " AND " ); } } else { QgsDebugMsg( QString( "FAILURE: Key values for feature %1 not found." ).arg( featureId ) ); - whereClause = "NULL"; + whereClause = QStringLiteral( "NULL" ); } } break; case pktUnknown: Q_ASSERT( !"FAILURE: Primary key unknown" ); - whereClause = "NULL"; + whereClause = QStringLiteral( "NULL" ); break; } @@ -545,7 +545,7 @@ QString QgsPostgresUtils::whereClause( const QgsFeatureIds& featureIds, const Qg if ( !featureIds.isEmpty() ) { QString delim; - expr = QString( "%1 IN (" ).arg(( pkType == pktOid ? "oid" : QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ) ); + expr = QStringLiteral( "%1 IN (" ).arg(( pkType == pktOid ? QStringLiteral( "oid" ) : QgsPostgresConn::quotedIdentifier( fields.at( pkAttrs[0] ).name() ) ) ); Q_FOREACH ( const QgsFeatureId featureId, featureIds ) { @@ -567,7 +567,7 @@ QString QgsPostgresUtils::whereClause( const QgsFeatureIds& featureIds, const Qg { whereClauses << whereClause( featureId, fields, conn, pkType, pkAttrs, sharedData ); } - return whereClauses.isEmpty() ? "" : whereClauses.join( " OR " ).prepend( '(' ).append( ')' ); + return whereClauses.isEmpty() ? QLatin1String( "" ) : whereClauses.join( QStringLiteral( " OR " ) ).prepend( '(' ).append( ')' ); } } return QString(); //avoid warning @@ -580,34 +580,34 @@ QString QgsPostgresUtils::andWhereClauses( const QString& c1, const QString& c2 if ( c2.isEmpty() ) return c1; - return QString( "(%1) AND (%2)" ).arg( c1, c2 ); + return QStringLiteral( "(%1) AND (%2)" ).arg( c1, c2 ); } QString QgsPostgresProvider::filterWhereClause() const { QString where; - QString delim = " WHERE "; + QString delim = QStringLiteral( " WHERE " ); if ( !mSqlWhereClause.isEmpty() ) { where += delim + '(' + mSqlWhereClause + ')'; - delim = " AND "; + delim = QStringLiteral( " AND " ); } if ( !mRequestedSrid.isEmpty() && ( mRequestedSrid != mDetectedSrid || mRequestedSrid.toInt() == 0 ) ) { - where += delim + QString( "%1(%2%3)=%4" ) + where += delim + QStringLiteral( "%1(%2%3)=%4" ) .arg( connectionRO()->majorVersion() < 2 ? "srid" : "st_srid", quotedIdentifier( mGeometryColumn ), mSpatialColType == sctGeography ? "::geography" : "", mRequestedSrid ); - delim = " AND "; + delim = QStringLiteral( " AND " ); } if ( mRequestedGeomType != QgsWkbTypes::Unknown && mRequestedGeomType != mDetectedGeomType ) { where += delim + QgsPostgresConn::postgisTypeFilter( mGeometryColumn, ( QgsWkbTypes::Type )mRequestedGeomType, mSpatialColType == sctGeography ); - delim = " AND "; + delim = QStringLiteral( " AND " ); } return where; @@ -657,11 +657,11 @@ QString QgsPostgresProvider::endianString() switch ( QgsApplication::endian() ) { case QgsApplication::NDR: - return QString( "NDR" ); + return QStringLiteral( "NDR" ); case QgsApplication::XDR: - return QString( "XDR" ); + return QStringLiteral( "XDR" ); default : - return QString( "Unknown" ); + return QStringLiteral( "Unknown" ); } } @@ -681,12 +681,12 @@ bool QgsPostgresProvider::loadFields() QgsDebugMsg( QString( "Loading fields for table %1" ).arg( mTableName ) ); // Get the relation oid for use in later queries - QString sql = QString( "SELECT regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); + QString sql = QStringLiteral( "SELECT regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); QgsPostgresResult tresult( connectionRO()->PQexec( sql ) ); QString tableoid = tresult.PQgetvalue( 0, 0 ); // Get the table description - sql = QString( "SELECT description FROM pg_description WHERE objoid=%1 AND objsubid=0" ).arg( tableoid ); + sql = QStringLiteral( "SELECT description FROM pg_description WHERE objoid=%1 AND objsubid=0" ).arg( tableoid ); tresult = connectionRO()->PQexec( sql ); if ( tresult.PQntuples() > 0 ) mDataComment = tresult.PQgetvalue( 0, 0 ); @@ -694,12 +694,12 @@ bool QgsPostgresProvider::loadFields() // Populate the field vector for this layer. The field vector contains // field name, type, length, and precision (if numeric) - QString sql = QString( "SELECT * FROM %1 LIMIT 0" ).arg( mQuery ); + QString sql = QStringLiteral( "SELECT * FROM %1 LIMIT 0" ).arg( mQuery ); QgsPostgresResult result( connectionRO()->PQexec( sql ) ); // Collect type info - sql = "SELECT oid,typname,typtype,typelem,typlen FROM pg_type"; + sql = QStringLiteral( "SELECT oid,typname,typtype,typelem,typlen FROM pg_type" ); QgsPostgresResult typeResult( connectionRO()->PQexec( sql ) ); QMap<int, PGTypeInfo> typeMap; @@ -739,7 +739,7 @@ bool QgsPostgresProvider::loadFields() tableoidsList.append( QString::number( tableoid ) ); } - QString tableoidsFilter = '(' + tableoidsList.join( "," ) + ')'; + QString tableoidsFilter = '(' + tableoidsList.join( QStringLiteral( "," ) ) + ')'; // Collect formatted field types sql = "SELECT attrelid, attnum, pg_catalog.format_type(atttypid,atttypmod), pg_catalog.col_description(attrelid,attnum), pg_catalog.pg_get_expr(adbin,adrelid), atttypid" @@ -783,14 +783,14 @@ bool QgsPostgresProvider::loadFields() QString fieldTType = typeInfo.typeType; int fieldSize = typeInfo.typeLen; - bool isDomain = ( typeMap.value( atttypid ).typeType == "d" ); + bool isDomain = ( typeMap.value( atttypid ).typeType == QLatin1String( "d" ) ); QString formattedFieldType = fmtFieldTypeMap[tableoid][attnum]; QString originalFormattedFieldType = formattedFieldType; if ( isDomain ) { // get correct formatted field type for domain - sql = QString( "SELECT format_type(%1, %2)" ).arg( fldtyp ).arg( fldMod ); + sql = QStringLiteral( "SELECT format_type(%1, %2)" ).arg( fldtyp ).arg( fldMod ); QgsPostgresResult fmtFieldModResult( connectionRO()->PQexec( sql ) ); if ( fmtFieldModResult.PQntuples() > 0 ) { @@ -803,38 +803,38 @@ bool QgsPostgresProvider::loadFields() QVariant::Type fieldType; QVariant::Type fieldSubType = QVariant::Invalid; - if ( fieldTType == "b" ) + if ( fieldTType == QLatin1String( "b" ) ) { bool isArray = fieldTypeName.startsWith( '_' ); if ( isArray ) fieldTypeName = fieldTypeName.mid( 1 ); - if ( fieldTypeName == "int8" || fieldTypeName == "serial8" ) + if ( fieldTypeName == QLatin1String( "int8" ) || fieldTypeName == QLatin1String( "serial8" ) ) { fieldType = QVariant::LongLong; fieldSize = -1; fieldPrec = 0; } - else if ( fieldTypeName == "int2" || fieldTypeName == "int4" || - fieldTypeName == "oid" || fieldTypeName == "serial" ) + else if ( fieldTypeName == QLatin1String( "int2" ) || fieldTypeName == QLatin1String( "int4" ) || + fieldTypeName == QLatin1String( "oid" ) || fieldTypeName == QLatin1String( "serial" ) ) { fieldType = QVariant::Int; fieldSize = -1; fieldPrec = 0; } - else if ( fieldTypeName == "real" || fieldTypeName == "double precision" || - fieldTypeName == "float4" || fieldTypeName == "float8" ) + else if ( fieldTypeName == QLatin1String( "real" ) || fieldTypeName == QLatin1String( "double precision" ) || + fieldTypeName == QLatin1String( "float4" ) || fieldTypeName == QLatin1String( "float8" ) ) { fieldType = QVariant::Double; fieldSize = -1; fieldPrec = -1; } - else if ( fieldTypeName == "numeric" ) + else if ( fieldTypeName == QLatin1String( "numeric" ) ) { fieldType = QVariant::Double; - if ( formattedFieldType == "numeric" || formattedFieldType == "" ) + if ( formattedFieldType == QLatin1String( "numeric" ) || formattedFieldType == QLatin1String( "" ) ) { fieldSize = -1; fieldPrec = -1; @@ -847,7 +847,7 @@ bool QgsPostgresProvider::loadFields() fieldSize = re.cap( 1 ).toInt(); fieldPrec = re.cap( 2 ).toInt(); } - else if ( formattedFieldType != "numeric" ) + else if ( formattedFieldType != QLatin1String( "numeric" ) ) { QgsMessageLog::logMessage( tr( "unexpected formatted field type '%1' for field %2" ) .arg( formattedFieldType, @@ -858,7 +858,7 @@ bool QgsPostgresProvider::loadFields() } } } - else if ( fieldTypeName == "varchar" ) + else if ( fieldTypeName == QLatin1String( "varchar" ) ) { fieldType = QVariant::String; @@ -872,39 +872,39 @@ bool QgsPostgresProvider::loadFields() fieldSize = -1; } } - else if ( fieldTypeName == "date" ) + else if ( fieldTypeName == QLatin1String( "date" ) ) { fieldType = QVariant::Date; fieldSize = -1; } - else if ( fieldTypeName == "time" ) + else if ( fieldTypeName == QLatin1String( "time" ) ) { fieldType = QVariant::Time; fieldSize = -1; } - else if ( fieldTypeName == "timestamp" ) + else if ( fieldTypeName == QLatin1String( "timestamp" ) ) { fieldType = QVariant::DateTime; fieldSize = -1; } - else if ( fieldTypeName == "text" || - fieldTypeName == "bool" || - fieldTypeName == "geometry" || - fieldTypeName == "inet" || - fieldTypeName == "money" || - fieldTypeName == "ltree" || - fieldTypeName == "uuid" || - fieldTypeName == "xml" || - fieldTypeName.startsWith( "time" ) || - fieldTypeName.startsWith( "date" ) ) + else if ( fieldTypeName == QLatin1String( "text" ) || + fieldTypeName == QLatin1String( "bool" ) || + fieldTypeName == QLatin1String( "geometry" ) || + fieldTypeName == QLatin1String( "inet" ) || + fieldTypeName == QLatin1String( "money" ) || + fieldTypeName == QLatin1String( "ltree" ) || + fieldTypeName == QLatin1String( "uuid" ) || + fieldTypeName == QLatin1String( "xml" ) || + fieldTypeName.startsWith( QLatin1String( "time" ) ) || + fieldTypeName.startsWith( QLatin1String( "date" ) ) ) { fieldType = QVariant::String; fieldSize = -1; } - else if ( fieldTypeName == "bpchar" ) + else if ( fieldTypeName == QLatin1String( "bpchar" ) ) { // although postgres internally uses "bpchar", this is exposed to users as character in postgres - fieldTypeName = "character"; + fieldTypeName = QStringLiteral( "character" ); fieldType = QVariant::String; @@ -922,7 +922,7 @@ bool QgsPostgresProvider::loadFields() fieldPrec = -1; } } - else if ( fieldTypeName == "char" ) + else if ( fieldTypeName == QLatin1String( "char" ) ) { fieldType = QVariant::String; @@ -940,7 +940,7 @@ bool QgsPostgresProvider::loadFields() fieldPrec = -1; } } - else if ( fieldTypeName == "hstore" ) + else if ( fieldTypeName == QLatin1String( "hstore" ) ) { fieldType = QVariant::Map; fieldSubType = QVariant::String; @@ -960,7 +960,7 @@ bool QgsPostgresProvider::loadFields() fieldSize = -1; } } - else if ( fieldTType == "e" ) + else if ( fieldTType == QLatin1String( "e" ) ) { // enum fieldType = QVariant::String; @@ -1006,7 +1006,7 @@ void QgsPostgresProvider::setEditorWidgets() // type TEXT NOT NULL, config TEXT, // PRIMARY KEY(schema_name, table_name, field_name)); QgsField& field = mAttributeFields[i]; - const QString sql = QString( "SELECT type, config FROM %1 WHERE schema_name = %2 and table_name = %3 and field_name = %4 LIMIT 1" ). + const QString sql = QStringLiteral( "SELECT type, config FROM %1 WHERE schema_name = %2 and table_name = %3 and field_name = %4 LIMIT 1" ). arg( EDITOR_WIDGET_STYLES_TABLE, quotedValue( mSchemaName ), quotedValue( mTableName ), quotedValue( field.name() ) ); QgsPostgresResult result( connectionRO()->PQexec( sql ) ); for ( int i = 0; i < result.PQntuples(); ++i ) @@ -1041,7 +1041,7 @@ bool QgsPostgresProvider::hasSufficientPermsAndCapabilities() if ( !mIsQuery ) { // Check that we can read from the table (i.e., we have select permission). - QString sql = QString( "SELECT * FROM %1 LIMIT 1" ).arg( mQuery ); + QString sql = QStringLiteral( "SELECT * FROM %1 LIMIT 1" ).arg( mQuery ); QgsPostgresResult testAccess( connectionRO()->PQexec( sql ) ); if ( testAccess.PQresultStatus() != PGRES_TUPLES_OK ) { @@ -1056,8 +1056,8 @@ bool QgsPostgresProvider::hasSufficientPermsAndCapabilities() if ( connectionRO()->pgVersion() >= 90000 ) { - testAccess = connectionRO()->PQexec( "SELECT pg_is_in_recovery()" ); - if ( testAccess.PQresultStatus() != PGRES_TUPLES_OK || testAccess.PQgetvalue( 0, 0 ) == "t" ) + testAccess = connectionRO()->PQexec( QStringLiteral( "SELECT pg_is_in_recovery()" ) ); + if ( testAccess.PQresultStatus() != PGRES_TUPLES_OK || testAccess.PQgetvalue( 0, 0 ) == QLatin1String( "t" ) ) { QgsMessageLog::logMessage( tr( "PostgreSQL is still in recovery after a database crash\n(or you are connected to a (read-only) slave).\nWrite accesses will be denied." ), tr( "PostGIS" ) ); inRecovery = true; @@ -1083,8 +1083,8 @@ bool QgsPostgresProvider::hasSufficientPermsAndCapabilities() "current_schema()" ) .arg( quotedValue( mQuery ), mGeometryColumn.isNull() - ? QString( "'f'," ) - : QString( "has_column_privilege(%1,%2,'UPDATE')," ) + ? QStringLiteral( "'f'," ) + : QStringLiteral( "has_column_privilege(%1,%2,'UPDATE')," ) .arg( quotedValue( mQuery ), quotedValue( mGeometryColumn ) ) ); @@ -1112,25 +1112,25 @@ bool QgsPostgresProvider::hasSufficientPermsAndCapabilities() } - if ( testAccess.PQgetvalue( 0, 0 ) == "t" ) + if ( testAccess.PQgetvalue( 0, 0 ) == QLatin1String( "t" ) ) { // DELETE mEnabledCapabilities |= QgsVectorDataProvider::DeleteFeatures; } - if ( testAccess.PQgetvalue( 0, 1 ) == "t" ) + if ( testAccess.PQgetvalue( 0, 1 ) == QLatin1String( "t" ) ) { // UPDATE mEnabledCapabilities |= QgsVectorDataProvider::ChangeAttributeValues; } - if ( testAccess.PQgetvalue( 0, 2 ) == "t" ) + if ( testAccess.PQgetvalue( 0, 2 ) == QLatin1String( "t" ) ) { // UPDATE mEnabledCapabilities |= QgsVectorDataProvider::ChangeGeometries; } - if ( testAccess.PQgetvalue( 0, 3 ) == "t" ) + if ( testAccess.PQgetvalue( 0, 3 ) == QLatin1String( "t" ) ) { // INSERT mEnabledCapabilities |= QgsVectorDataProvider::AddFeatures; @@ -1168,19 +1168,19 @@ bool QgsPostgresProvider::hasSufficientPermsAndCapabilities() QRegExp regex; do { - alias = QString( "subQuery_%1" ).arg( QString::number( index++ ) ); - QString pattern = QString( "(\\\"?)%1\\1" ).arg( QRegExp::escape( alias ) ); + alias = QStringLiteral( "subQuery_%1" ).arg( QString::number( index++ ) ); + QString pattern = QStringLiteral( "(\\\"?)%1\\1" ).arg( QRegExp::escape( alias ) ); regex.setPattern( pattern ); regex.setCaseSensitivity( Qt::CaseInsensitive ); } while ( mQuery.contains( regex ) ); // convert the custom query into a subquery - mQuery = QString( "%1 AS %2" ) + mQuery = QStringLiteral( "%1 AS %2" ) .arg( mQuery, quotedIdentifier( alias ) ); - QString sql = QString( "SELECT * FROM %1 LIMIT 1" ).arg( mQuery ); + QString sql = QStringLiteral( "SELECT * FROM %1 LIMIT 1" ).arg( mQuery ); testAccess = connectionRO()->PQexec( sql ); if ( testAccess.PQresultStatus() != PGRES_TUPLES_OK ) @@ -1230,12 +1230,12 @@ bool QgsPostgresProvider::determinePrimaryKey() QString sql; if ( !mIsQuery ) { - sql = QString( "SELECT count(*) FROM pg_inherits WHERE inhparent=%1::regclass" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT count(*) FROM pg_inherits WHERE inhparent=%1::regclass" ).arg( quotedValue( mQuery ) ); QgsDebugMsg( QString( "Checking whether %1 is a parent table" ).arg( sql ) ); QgsPostgresResult res( connectionRO()->PQexec( sql ) ); bool isParentTable( res.PQntuples() == 0 || res.PQgetvalue( 0, 0 ).toInt() > 0 ); - sql = QString( "SELECT indexrelid FROM pg_index WHERE indrelid=%1::regclass AND (indisprimary OR indisunique) ORDER BY CASE WHEN indisprimary THEN 1 ELSE 2 END LIMIT 1" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT indexrelid FROM pg_index WHERE indrelid=%1::regclass AND (indisprimary OR indisunique) ORDER BY CASE WHEN indisprimary THEN 1 ELSE 2 END LIMIT 1" ).arg( quotedValue( mQuery ) ); QgsDebugMsg( QString( "Retrieving first primary or unique index: %1" ).arg( sql ) ); res = connectionRO()->PQexec( sql ); @@ -1253,18 +1253,18 @@ bool QgsPostgresProvider::determinePrimaryKey() // If the relation is a view try to find a suitable column to use as // the primary key. - sql = QString( "SELECT relkind FROM pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT relkind FROM pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); res = connectionRO()->PQexec( sql ); QString type = res.PQgetvalue( 0, 0 ); - if ( type == "r" ) // the relation is a table + if ( type == QLatin1String( "r" ) ) // the relation is a table { QgsDebugMsg( "Relation is a table. Checking to see if it has an oid column." ); mPrimaryKeyAttrs.clear(); // If there is an oid on the table, use that instead, - sql = QString( "SELECT attname FROM pg_attribute WHERE attname='oid' AND attrelid=regclass(%1)" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT attname FROM pg_attribute WHERE attname='oid' AND attrelid=regclass(%1)" ).arg( quotedValue( mQuery ) ); res = connectionRO()->PQexec( sql ); if ( res.PQntuples() == 1 ) @@ -1276,7 +1276,7 @@ bool QgsPostgresProvider::determinePrimaryKey() } else { - sql = QString( "SELECT attname FROM pg_attribute WHERE attname='ctid' AND attrelid=regclass(%1)" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT attname FROM pg_attribute WHERE attname='ctid' AND attrelid=regclass(%1)" ).arg( quotedValue( mQuery ) ); res = connectionRO()->PQexec( sql ); if ( res.PQntuples() == 1 ) @@ -1292,7 +1292,7 @@ bool QgsPostgresProvider::determinePrimaryKey() } } } - else if ( type == "v" || type == "m" ) // the relation is a view + else if ( type == QLatin1String( "v" ) || type == QLatin1String( "m" ) ) // the relation is a view { determinePrimaryKeyFromUriKeyColumn(); } @@ -1305,7 +1305,7 @@ bool QgsPostgresProvider::determinePrimaryKey() { // have a primary key or unique index QString indrelid = res.PQgetvalue( 0, 0 ); - sql = QString( "SELECT attname,attnotnull FROM pg_index,pg_attribute WHERE indexrelid=%1 AND indrelid=attrelid AND pg_attribute.attnum=any(pg_index.indkey)" ).arg( indrelid ); + sql = QStringLiteral( "SELECT attname,attnotnull FROM pg_index,pg_attribute WHERE indexrelid=%1 AND indrelid=attrelid AND pg_attribute.attnum=any(pg_index.indkey)" ).arg( indrelid ); QgsDebugMsg( "Retrieving key columns: " + sql ); res = connectionRO()->PQexec( sql ); @@ -1313,7 +1313,7 @@ bool QgsPostgresProvider::determinePrimaryKey() bool mightBeNull = false; QString primaryKey; - QString delim = ""; + QString delim = QLatin1String( "" ); mPrimaryKeyType = pktFidMap; // map by default, will downgrade if needed for ( int i = 0; i < res.PQntuples(); i++ ) @@ -1383,7 +1383,7 @@ QStringList QgsPostgresProvider::parseUriKey( const QString& key ) else { cols << col; - col = ""; + col = QLatin1String( "" ); if ( ++i == key.size() ) break; @@ -1392,7 +1392,7 @@ QStringList QgsPostgresProvider::parseUriKey( const QString& key ) i++; Q_ASSERT( key[i] == '"' ); i++; - col = ""; + col = QLatin1String( "" ); continue; } } @@ -1421,12 +1421,12 @@ void QgsPostgresProvider::determinePrimaryKeyFromUriKeyColumn() { QStringList cols = parseUriKey( primaryKey ); - primaryKey = ""; - QString del = ""; + primaryKey = QLatin1String( "" ); + QString del = QLatin1String( "" ); Q_FOREACH ( const QString& col, cols ) { primaryKey += del + quotedIdentifier( col ); - del = ","; + del = QStringLiteral( "," ); } Q_FOREACH ( const QString& col, cols ) @@ -1472,7 +1472,7 @@ void QgsPostgresProvider::determinePrimaryKeyFromUriKeyColumn() bool QgsPostgresProvider::uniqueData( const QString& quotedColNames ) { // Check to see if the given columns contain unique data - QString sql = QString( "SELECT count(distinct (%1))=count((%1)) FROM %2%3" ) + QString sql = QStringLiteral( "SELECT count(distinct (%1))=count((%1)) FROM %2%3" ) .arg( quotedColNames, mQuery, filterWhereClause() ); @@ -1495,16 +1495,16 @@ QVariant QgsPostgresProvider::minimumValue( int index ) const { // get the field name QgsField fld = field( index ); - QString sql = QString( "SELECT min(%1) AS %1 FROM %2" ) + QString sql = QStringLiteral( "SELECT min(%1) AS %1 FROM %2" ) .arg( quotedIdentifier( fld.name() ), mQuery ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " WHERE %1" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " WHERE %1" ).arg( mSqlWhereClause ); } - sql = QString( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); + sql = QStringLiteral( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); QgsPostgresResult rmin( connectionRO()->PQexec( sql ) ); return convertValue( fld.type(), fld.subType(), rmin.PQgetvalue( 0, 0 ) ); @@ -1524,23 +1524,23 @@ void QgsPostgresProvider::uniqueValues( int index, QList<QVariant> &uniqueValues { // get the field name QgsField fld = field( index ); - QString sql = QString( "SELECT DISTINCT %1 FROM %2" ) + QString sql = QStringLiteral( "SELECT DISTINCT %1 FROM %2" ) .arg( quotedIdentifier( fld.name() ), mQuery ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " WHERE %1" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " WHERE %1" ).arg( mSqlWhereClause ); } - sql += QString( " ORDER BY %1" ).arg( quotedIdentifier( fld.name() ) ); + sql += QStringLiteral( " ORDER BY %1" ).arg( quotedIdentifier( fld.name() ) ); if ( limit >= 0 ) { - sql += QString( " LIMIT %1" ).arg( limit ); + sql += QStringLiteral( " LIMIT %1" ).arg( limit ); } - sql = QString( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); + sql = QStringLiteral( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); QgsPostgresResult res( connectionRO()->PQexec( sql ) ); if ( res.PQresultStatus() == PGRES_TUPLES_OK ) @@ -1566,7 +1566,7 @@ void QgsPostgresProvider::enumValues( int index, QStringList& enumList ) const QString typeName = mAttributeFields.at( index ).typeName(); //is type an enum? - QString typeSql = QString( "SELECT typtype FROM pg_type WHERE typname=%1" ).arg( quotedValue( typeName ) ); + QString typeSql = QStringLiteral( "SELECT typtype FROM pg_type WHERE typname=%1" ).arg( quotedValue( typeName ) ); QgsPostgresResult typeRes( connectionRO()->PQexec( typeSql ) ); if ( typeRes.PQresultStatus() != PGRES_TUPLES_OK || typeRes.PQntuples() < 1 ) { @@ -1575,7 +1575,7 @@ void QgsPostgresProvider::enumValues( int index, QStringList& enumList ) const QString typtype = typeRes.PQgetvalue( 0, 0 ); - if ( typtype.compare( "e", Qt::CaseInsensitive ) == 0 ) + if ( typtype.compare( QLatin1String( "e" ), Qt::CaseInsensitive ) == 0 ) { //try to read enum_range of attribute if ( !parseEnumRange( enumList, fieldName ) ) @@ -1597,7 +1597,7 @@ bool QgsPostgresProvider::parseEnumRange( QStringList& enumValues, const QString { enumValues.clear(); - QString enumRangeSql = QString( "SELECT enumlabel FROM pg_catalog.pg_enum WHERE enumtypid=(SELECT atttypid::regclass FROM pg_attribute WHERE attrelid=%1::regclass AND attname=%2)" ) + QString enumRangeSql = QStringLiteral( "SELECT enumlabel FROM pg_catalog.pg_enum WHERE enumtypid=(SELECT atttypid::regclass FROM pg_attribute WHERE attrelid=%1::regclass AND attname=%2)" ) .arg( quotedValue( mQuery ), quotedValue( attributeName ) ); QgsPostgresResult enumRangeRes( connectionRO()->PQexec( enumRangeSql ) ); @@ -1617,12 +1617,12 @@ bool QgsPostgresProvider::parseDomainCheckConstraint( QStringList& enumValues, c enumValues.clear(); //is it a domain type with a check constraint? - QString domainSql = QString( "SELECT domain_name FROM information_schema.columns WHERE table_name=%1 AND column_name=%2" ).arg( quotedValue( mTableName ), quotedValue( attributeName ) ); + QString domainSql = QStringLiteral( "SELECT domain_name FROM information_schema.columns WHERE table_name=%1 AND column_name=%2" ).arg( quotedValue( mTableName ), quotedValue( attributeName ) ); QgsPostgresResult domainResult( connectionRO()->PQexec( domainSql ) ); if ( domainResult.PQresultStatus() == PGRES_TUPLES_OK && domainResult.PQntuples() > 0 ) { //a domain type - QString domainCheckDefinitionSql = QString( "SELECT consrc FROM pg_constraint WHERE conname=(SELECT constraint_name FROM information_schema.domain_constraints WHERE domain_name=%1)" ).arg( quotedValue( domainResult.PQgetvalue( 0, 0 ) ) ); + QString domainCheckDefinitionSql = QStringLiteral( "SELECT consrc FROM pg_constraint WHERE conname=(SELECT constraint_name FROM information_schema.domain_constraints WHERE domain_name=%1)" ).arg( quotedValue( domainResult.PQgetvalue( 0, 0 ) ) ); QgsPostgresResult domainCheckRes( connectionRO()->PQexec( domainCheckDefinitionSql ) ); if ( domainCheckRes.PQresultStatus() == PGRES_TUPLES_OK && domainCheckRes.PQntuples() > 0 ) { @@ -1633,7 +1633,7 @@ bool QgsPostgresProvider::parseDomainCheckConstraint( QStringList& enumValues, c //normally, postgresql creates that if the contstraint has been specified as 'VALUE in ('a', 'b', 'c', 'd') int anyPos = checkDefinition.indexOf( QRegExp( "VALUE\\s*=\\s*ANY\\s*\\(\\s*ARRAY\\s*\\[" ) ); - int arrayPosition = checkDefinition.lastIndexOf( "ARRAY[" ); + int arrayPosition = checkDefinition.lastIndexOf( QLatin1String( "ARRAY[" ) ); int closingBracketPos = checkDefinition.indexOf( ']', arrayPosition + 6 ); if ( anyPos == -1 || anyPos >= arrayPosition ) @@ -1670,16 +1670,16 @@ QVariant QgsPostgresProvider::maximumValue( int index ) const { // get the field name QgsField fld = field( index ); - QString sql = QString( "SELECT max(%1) AS %1 FROM %2" ) + QString sql = QStringLiteral( "SELECT max(%1) AS %1 FROM %2" ) .arg( quotedIdentifier( fld.name() ), mQuery ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " WHERE %1" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " WHERE %1" ).arg( mSqlWhereClause ); } - sql = QString( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); + sql = QStringLiteral( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); QgsPostgresResult rmax( connectionRO()->PQexec( sql ) ); @@ -1705,7 +1705,7 @@ QVariant QgsPostgresProvider::defaultValue( int fieldId ) const { QgsField fld = field( fieldId ); - QgsPostgresResult res( connectionRO()->PQexec( QString( "SELECT %1" ).arg( defVal.toString() ) ) ); + QgsPostgresResult res( connectionRO()->PQexec( QStringLiteral( "SELECT %1" ).arg( defVal.toString() ) ) ); if ( res.result() ) return convertValue( fld.type(), fld.subType(), res.PQgetvalue( 0, 0 ) ); @@ -1726,7 +1726,7 @@ QString QgsPostgresProvider::paramValue( const QString& fieldValue, const QStrin if ( fieldValue == defaultValue && !defaultValue.isNull() ) { - QgsPostgresResult result( connectionRO()->PQexec( QString( "SELECT %1" ).arg( defaultValue ) ) ); + QgsPostgresResult result( connectionRO()->PQexec( QStringLiteral( "SELECT %1" ).arg( defaultValue ) ) ); if ( result.PQresultStatus() != PGRES_TUPLES_OK ) throw PGException( result ); @@ -1796,7 +1796,7 @@ QString QgsPostgresProvider::geomParam( int offset ) const if ( mSpatialColType == sctTopoGeometry ) { - geometry += QString( "toTopoGeom(" ); + geometry += QStringLiteral( "toTopoGeom(" ); } if ( forceMulti ) @@ -1804,7 +1804,7 @@ QString QgsPostgresProvider::geomParam( int offset ) const geometry += connectionRO()->majorVersion() < 2 ? "multi(" : "st_multi("; } - geometry += QString( "%1($%2%3,%4)" ) + geometry += QStringLiteral( "%1($%2%3,%4)" ) .arg( connectionRO()->majorVersion() < 2 ? "geomfromwkb" : "st_geomfromwkb" ) .arg( offset ) .arg( connectionRO()->useWkbHex() ? "" : "::bytea", @@ -1817,7 +1817,7 @@ QString QgsPostgresProvider::geomParam( int offset ) const if ( mSpatialColType == sctTopoGeometry ) { - geometry += QString( ",%1,%2)" ) + geometry += QStringLiteral( ",%1,%2)" ) .arg( quotedValue( mTopoLayerInfo.topologyName ) ) .arg( mTopoLayerInfo.layerId ); } @@ -1847,9 +1847,9 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) conn->begin(); // Prepare the INSERT statement - QString insert = QString( "INSERT INTO %1(" ).arg( mQuery ); - QString values = ") VALUES ("; - QString delim = ""; + QString insert = QStringLiteral( "INSERT INTO %1(" ).arg( mQuery ); + QString values = QStringLiteral( ") VALUES (" ); + QString delim = QLatin1String( "" ); int offset = 1; QStringList defaultValues; @@ -1869,7 +1869,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) Q_FOREACH ( int idx, mPrimaryKeyAttrs ) { insert += delim + quotedIdentifier( field( idx ).name() ); - values += delim + QString( "$%1" ).arg( defaultValues.size() + offset ); + values += delim + QStringLiteral( "$%1" ).arg( defaultValues.size() + offset ); delim = ','; fieldId << idx; defaultValues << defaultValue( idx ).toString(); @@ -1924,16 +1924,16 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) values += delim + defVal; } } - else if ( fieldTypeName == "geometry" ) + else if ( fieldTypeName == QLatin1String( "geometry" ) ) { - values += QString( "%1%2(%3)" ) + values += QStringLiteral( "%1%2(%3)" ) .arg( delim, connectionRO()->majorVersion() < 2 ? "geomfromewkt" : "st_geomfromewkt", quotedValue( v.toString() ) ); } - else if ( fieldTypeName == "geography" ) + else if ( fieldTypeName == QLatin1String( "geography" ) ) { - values += QString( "%1st_geographyfromewkt(%2)" ) + values += QStringLiteral( "%1st_geographyfromewkt(%2)" ) .arg( delim, quotedValue( v.toString() ) ); } @@ -1946,22 +1946,22 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) else { // value is not unique => add parameter - if ( fieldTypeName == "geometry" ) + if ( fieldTypeName == QLatin1String( "geometry" ) ) { - values += QString( "%1%2($%3)" ) + values += QStringLiteral( "%1%2($%3)" ) .arg( delim, connectionRO()->majorVersion() < 2 ? "geomfromewkt" : "st_geomfromewkt" ) .arg( defaultValues.size() + offset ); } - else if ( fieldTypeName == "geography" ) + else if ( fieldTypeName == QLatin1String( "geography" ) ) { - values += QString( "%1st_geographyfromewkt($%2)" ) + values += QStringLiteral( "%1st_geographyfromewkt($%2)" ) .arg( delim ) .arg( defaultValues.size() + offset ); } else { - values += QString( "%1$%2" ) + values += QStringLiteral( "%1$%2" ) .arg( delim ) .arg( defaultValues.size() + offset ); } @@ -1976,7 +1976,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) if ( mPrimaryKeyType == pktFidMap || mPrimaryKeyType == pktInt || mPrimaryKeyType == pktUint64 ) { - insert += " RETURNING "; + insert += QLatin1String( " RETURNING " ); QString delim; Q_FOREACH ( int idx, mPrimaryKeyAttrs ) @@ -1987,7 +1987,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) } QgsDebugMsg( QString( "prepare addfeatures: %1" ).arg( insert ) ); - QgsPostgresResult stmt( conn->PQprepare( "addfeatures", insert, fieldId.size() + offset - 1, nullptr ) ); + QgsPostgresResult stmt( conn->PQprepare( QStringLiteral( "addfeatures" ), insert, fieldId.size() + offset - 1, nullptr ) ); if ( stmt.PQresultStatus() != PGRES_COMMAND_OK ) throw PGException( stmt ); @@ -2029,7 +2029,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) params << v; } - QgsPostgresResult result( conn->PQexecPrepared( "addfeatures", params ) ); + QgsPostgresResult result( conn->PQexecPrepared( QStringLiteral( "addfeatures" ), params ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { @@ -2080,7 +2080,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) } } - conn->PQexecNR( "DEALLOCATE addfeatures" ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE addfeatures" ) ); returnvalue &= conn->commit(); @@ -2090,7 +2090,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) { pushError( tr( "PostGIS error while adding features: %1" ).arg( e.errorMessage() ) ); conn->rollback(); - conn->PQexecNR( "DEALLOCATE addfeatures" ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE addfeatures" ) ); returnvalue = false; } @@ -2121,7 +2121,7 @@ bool QgsPostgresProvider::deleteFeatures( const QgsFeatureIds & id ) for ( QgsFeatureIds::const_iterator it = id.begin(); it != id.end(); ++it ) { - QString sql = QString( "DELETE FROM %1 WHERE %2" ) + QString sql = QStringLiteral( "DELETE FROM %1 WHERE %2" ) .arg( mQuery, whereClause( *it ) ); QgsDebugMsg( "delete sql: " + sql ); @@ -2180,22 +2180,22 @@ bool QgsPostgresProvider::addAttributes( const QList<QgsField> &attributes ) { conn->begin(); - QString delim = ""; - QString sql = QString( "ALTER TABLE %1 " ).arg( mQuery ); + QString delim = QLatin1String( "" ); + QString sql = QStringLiteral( "ALTER TABLE %1 " ).arg( mQuery ); for ( QList<QgsField>::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter ) { QString type = iter->typeName(); - if ( type == "char" || type == "varchar" ) + if ( type == QLatin1String( "char" ) || type == QLatin1String( "varchar" ) ) { if ( iter->length() > 0 ) - type = QString( "%1(%2)" ).arg( type ).arg( iter->length() ); + type = QStringLiteral( "%1(%2)" ).arg( type ).arg( iter->length() ); } - else if ( type == "numeric" || type == "decimal" ) + else if ( type == QLatin1String( "numeric" ) || type == QLatin1String( "decimal" ) ) { if ( iter->length() > 0 && iter->precision() >= 0 ) - type = QString( "%1(%2,%3)" ).arg( type ).arg( iter->length() ).arg( iter->precision() ); + type = QStringLiteral( "%1(%2,%3)" ).arg( type ).arg( iter->length() ).arg( iter->precision() ); } - sql.append( QString( "%1ADD COLUMN %2 %3" ).arg( delim, quotedIdentifier( iter->name() ), type ) ); + sql.append( QStringLiteral( "%1ADD COLUMN %2 %3" ).arg( delim, quotedIdentifier( iter->name() ), type ) ); delim = ','; } @@ -2208,7 +2208,7 @@ bool QgsPostgresProvider::addAttributes( const QList<QgsField> &attributes ) { if ( !iter->comment().isEmpty() ) { - sql = QString( "COMMENT ON COLUMN %1.%2 IS %3" ) + sql = QStringLiteral( "COMMENT ON COLUMN %1.%2 IS %3" ) .arg( mQuery, quotedIdentifier( iter->name() ), quotedValue( iter->comment() ) ); @@ -2260,7 +2260,7 @@ bool QgsPostgresProvider::deleteAttributes( const QgsAttributeIds& ids ) continue; QString column = mAttributeFields.at( index ).name(); - QString sql = QString( "ALTER TABLE %1 DROP COLUMN %2" ) + QString sql = QStringLiteral( "ALTER TABLE %1 DROP COLUMN %2" ) .arg( mQuery, quotedIdentifier( column ) ); @@ -2293,7 +2293,7 @@ bool QgsPostgresProvider::renameAttributes( const QgsFieldNameMap& renamedAttrib return false; - QString sql = "BEGIN;"; + QString sql = QStringLiteral( "BEGIN;" ); QgsFieldNameMap::const_iterator renameIt = renamedAttributes.constBegin(); bool returnvalue = true; @@ -2312,12 +2312,12 @@ bool QgsPostgresProvider::renameAttributes( const QgsFieldNameMap& renamedAttrib return false; } - sql += QString( "ALTER TABLE %1 RENAME COLUMN %2 TO %3;" ) + sql += QStringLiteral( "ALTER TABLE %1 RENAME COLUMN %2 TO %3;" ) .arg( mQuery, quotedIdentifier( mAttributeFields.at( fieldIndex ).name() ), quotedIdentifier( renameIt.value() ) ); } - sql += "COMMIT;"; + sql += QLatin1String( "COMMIT;" ); QgsPostgresConn* conn = connectionRW(); if ( !conn ) @@ -2380,7 +2380,7 @@ bool QgsPostgresProvider::changeAttributeValues( const QgsChangedAttributesMap & if ( attrs.isEmpty() ) continue; - QString sql = QString( "UPDATE %1 SET " ).arg( mQuery ); + QString sql = QStringLiteral( "UPDATE %1 SET " ).arg( mQuery ); bool pkChanged = false; @@ -2394,18 +2394,18 @@ bool QgsPostgresProvider::changeAttributeValues( const QgsChangedAttributesMap & pkChanged = pkChanged || mPrimaryKeyAttrs.contains( siter.key() ); - sql += delim + QString( "%1=" ).arg( quotedIdentifier( fld.name() ) ); + sql += delim + QStringLiteral( "%1=" ).arg( quotedIdentifier( fld.name() ) ); delim = ','; - if ( fld.typeName() == "geometry" ) + if ( fld.typeName() == QLatin1String( "geometry" ) ) { - sql += QString( "%1(%2)" ) + sql += QStringLiteral( "%1(%2)" ) .arg( connectionRO()->majorVersion() < 2 ? "geomfromewkt" : "st_geomfromewkt", quotedValue( siter->toString() ) ); } - else if ( fld.typeName() == "geography" ) + else if ( fld.typeName() == QLatin1String( "geography" ) ) { - sql += QString( "st_geographyfromewkt(%1)" ) + sql += QStringLiteral( "st_geographyfromewkt(%1)" ) .arg( quotedValue( siter->toString() ) ); } else @@ -2419,7 +2419,7 @@ bool QgsPostgresProvider::changeAttributeValues( const QgsChangedAttributesMap & } } - sql += QString( " WHERE %1" ).arg( whereClause( fid ) ); + sql += QStringLiteral( " WHERE %1" ).arg( whereClause( fid ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() != PGRES_COMMAND_OK && result.PQresultStatus() != PGRES_TUPLES_OK ) @@ -2473,9 +2473,9 @@ void QgsPostgresProvider::appendGeomParam( const QgsGeometry& geom, QStringList for ( size_t i = 0; i < wkbSize; ++i ) { if ( connectionRO()->useWkbHex() ) - param += QString( "%1" ).arg(( int ) buf[i], 2, 16, QChar( '0' ) ); + param += QStringLiteral( "%1" ).arg(( int ) buf[i], 2, 16, QChar( '0' ) ); else - param += QString( "\\%1" ).arg(( int ) buf[i], 3, 8, QChar( '0' ) ); + param += QStringLiteral( "\\%1" ).arg(( int ) buf[i], 3, 8, QChar( '0' ) ); } params << param; } @@ -2509,19 +2509,19 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m // Later, we'll replace the old TopoGeometry with the new one, // to avoid orphans and retain higher level in an eventual // hierarchical definition - update = QString( "SELECT id(%1) FROM %2 o WHERE %3" ) + update = QStringLiteral( "SELECT id(%1) FROM %2 o WHERE %3" ) .arg( geomParam( 1 ), mQuery, pkParamWhereClause( 2 ) ); - QString getid = QString( "SELECT id(%1) FROM %2 WHERE %3" ) + QString getid = QStringLiteral( "SELECT id(%1) FROM %2 WHERE %3" ) .arg( quotedIdentifier( mGeometryColumn ), mQuery, pkParamWhereClause( 1 ) ); QgsDebugMsg( "getting old topogeometry id: " + getid ); - result = connectionRO()->PQprepare( "getid", getid, 1, nullptr ); + result = connectionRO()->PQprepare( QStringLiteral( "getid" ), getid, 1, nullptr ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) { QgsDebugMsg( QString( "Exception thrown due to PQprepare of this query returning != PGRES_COMMAND_OK (%1 != expected %2): %3" ) @@ -2536,7 +2536,7 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m quotedIdentifier( mGeometryColumn ), pkParamWhereClause( 2 ) ); QgsDebugMsg( "TopoGeom swap: " + replace ); - result = conn->PQprepare( "replacetopogeom", replace, 2, nullptr ); + result = conn->PQprepare( QStringLiteral( "replacetopogeom" ), replace, 2, nullptr ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) { QgsDebugMsg( QString( "Exception thrown due to PQprepare of this query returning != PGRES_COMMAND_OK (%1 != expected %2): %3" ) @@ -2547,7 +2547,7 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m } else { - update = QString( "UPDATE %1 SET %2=%3 WHERE %4" ) + update = QStringLiteral( "UPDATE %1 SET %2=%3 WHERE %4" ) .arg( mQuery, quotedIdentifier( mGeometryColumn ), geomParam( 1 ), @@ -2556,7 +2556,7 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m QgsDebugMsg( "updating: " + update ); - result = conn->PQprepare( "updatefeatures", update, 2, nullptr ); + result = conn->PQprepare( QStringLiteral( "updatefeatures" ), update, 2, nullptr ); if ( result.PQresultStatus() != PGRES_COMMAND_OK && result.PQresultStatus() != PGRES_TUPLES_OK ) { QgsDebugMsg( QString( "Exception thrown due to PQprepare of this query returning != PGRES_COMMAND_OK (%1 != expected %2): %3" ) @@ -2578,7 +2578,7 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m { QStringList params; appendPkParams( iter.key(), params ); - result = connectionRO()->PQexecPrepared( "getid", params ); + result = connectionRO()->PQexecPrepared( QStringLiteral( "getid" ), params ); if ( result.PQresultStatus() != PGRES_TUPLES_OK ) { QgsDebugMsg( QString( "Exception thrown due to PQexecPrepared of 'getid' returning != PGRES_TUPLES_OK (%1 != expected %2)" ) @@ -2594,7 +2594,7 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m appendGeomParam( *iter, params ); appendPkParams( iter.key(), params ); - result = conn->PQexecPrepared( "updatefeatures", params ); + result = conn->PQexecPrepared( QStringLiteral( "updatefeatures" ), params ); if ( result.PQresultStatus() != PGRES_COMMAND_OK && result.PQresultStatus() != PGRES_TUPLES_OK ) throw PGException( result ); @@ -2636,11 +2636,11 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m } // for each feature - conn->PQexecNR( "DEALLOCATE updatefeatures" ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE updatefeatures" ) ); if ( mSpatialColType == sctTopoGeometry ) { - connectionRO()->PQexecNR( "DEALLOCATE getid" ); - conn->PQexecNR( "DEALLOCATE replacetopogeom" ); + connectionRO()->PQexecNR( QStringLiteral( "DEALLOCATE getid" ) ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE replacetopogeom" ) ); } returnvalue &= conn->commit(); @@ -2649,11 +2649,11 @@ bool QgsPostgresProvider::changeGeometryValues( const QgsGeometryMap &geometry_m { pushError( tr( "PostGIS error while changing geometry values: %1" ).arg( e.errorMessage() ) ); conn->rollback(); - conn->PQexecNR( "DEALLOCATE updatefeatures" ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE updatefeatures" ) ); if ( mSpatialColType == sctTopoGeometry ) { - connectionRO()->PQexecNR( "DEALLOCATE getid" ); - conn->PQexecNR( "DEALLOCATE replacetopogeom" ); + connectionRO()->PQexecNR( QStringLiteral( "DEALLOCATE getid" ) ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE replacetopogeom" ) ); } returnvalue = false; } @@ -2702,7 +2702,7 @@ bool QgsPostgresProvider::changeFeatures( const QgsChangedAttributesMap &attr_ma if ( attrs.isEmpty() && !geometry_map.contains( fid ) ) continue; - QString sql = QString( "UPDATE %1 SET " ).arg( mQuery ); + QString sql = QStringLiteral( "UPDATE %1 SET " ).arg( mQuery ); bool pkChanged = false; @@ -2716,18 +2716,18 @@ bool QgsPostgresProvider::changeFeatures( const QgsChangedAttributesMap &attr_ma pkChanged = pkChanged || mPrimaryKeyAttrs.contains( siter.key() ); - sql += delim + QString( "%1=" ).arg( quotedIdentifier( fld.name() ) ); + sql += delim + QStringLiteral( "%1=" ).arg( quotedIdentifier( fld.name() ) ); delim = ','; - if ( fld.typeName() == "geometry" ) + if ( fld.typeName() == QLatin1String( "geometry" ) ) { - sql += QString( "%1(%2)" ) + sql += QStringLiteral( "%1(%2)" ) .arg( connectionRO()->majorVersion() < 2 ? "geomfromewkt" : "st_geomfromewkt", quotedValue( siter->toString() ) ); } - else if ( fld.typeName() == "geography" ) + else if ( fld.typeName() == QLatin1String( "geography" ) ) { - sql += QString( "st_geographyfromewkt(%1)" ) + sql += QStringLiteral( "st_geographyfromewkt(%1)" ) .arg( quotedValue( siter->toString() ) ); } else @@ -2743,7 +2743,7 @@ bool QgsPostgresProvider::changeFeatures( const QgsChangedAttributesMap &attr_ma if ( !geometry_map.contains( fid ) ) { - sql += QString( " WHERE %1" ).arg( whereClause( fid ) ); + sql += QStringLiteral( " WHERE %1" ).arg( whereClause( fid ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() != PGRES_COMMAND_OK && result.PQresultStatus() != PGRES_TUPLES_OK ) @@ -2751,10 +2751,10 @@ bool QgsPostgresProvider::changeFeatures( const QgsChangedAttributesMap &attr_ma } else { - sql += QString( "%1%2=%3" ).arg( delim, quotedIdentifier( mGeometryColumn ), geomParam( 1 ) ); - sql += QString( " WHERE %1" ).arg( whereClause( fid ) ); + sql += QStringLiteral( "%1%2=%3" ).arg( delim, quotedIdentifier( mGeometryColumn ), geomParam( 1 ) ); + sql += QStringLiteral( " WHERE %1" ).arg( whereClause( fid ) ); - QgsPostgresResult result( conn->PQprepare( "updatefeature", sql, 1, nullptr ) ); + QgsPostgresResult result( conn->PQprepare( QStringLiteral( "updatefeature" ), sql, 1, nullptr ) ); if ( result.PQresultStatus() != PGRES_COMMAND_OK && result.PQresultStatus() != PGRES_TUPLES_OK ) { QgsDebugMsg( QString( "Exception thrown due to PQprepare of this query returning != PGRES_COMMAND_OK (%1 != expected %2): %3" ) @@ -2766,11 +2766,11 @@ bool QgsPostgresProvider::changeFeatures( const QgsChangedAttributesMap &attr_ma const QgsGeometry &geom = geometry_map[ fid ]; appendGeomParam( geom, params ); - result = conn->PQexecPrepared( "updatefeature", params ); + result = conn->PQexecPrepared( QStringLiteral( "updatefeature" ), params ); if ( result.PQresultStatus() != PGRES_COMMAND_OK && result.PQresultStatus() != PGRES_TUPLES_OK ) throw PGException( result ); - conn->PQexecNR( "DEALLOCATE updatefeature" ); + conn->PQexecNR( QStringLiteral( "DEALLOCATE updatefeature" ) ); } // update feature id map if key was changed @@ -2827,14 +2827,14 @@ bool QgsPostgresProvider::setSubsetString( const QString& theSQL, bool updateFea mSqlWhereClause = theSQL.trimmed(); - QString sql = QString( "SELECT * FROM %1" ).arg( mQuery ); + QString sql = QStringLiteral( "SELECT * FROM %1" ).arg( mQuery ); if ( !mSqlWhereClause.isEmpty() ) { - sql += QString( " WHERE %1" ).arg( mSqlWhereClause ); + sql += QStringLiteral( " WHERE %1" ).arg( mSqlWhereClause ); } - sql += " LIMIT 0"; + sql += QLatin1String( " LIMIT 0" ); QgsPostgresResult res( connectionRO()->PQexec( sql ) ); if ( res.PQresultStatus() != PGRES_TUPLES_OK ) @@ -2887,11 +2887,11 @@ long QgsPostgresProvider::featureCount() const // - but make huge dataset usable. if ( !mIsQuery && mUseEstimatedMetadata ) { - sql = QString( "SELECT reltuples::int FROM pg_catalog.pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT reltuples::int FROM pg_catalog.pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); } else { - sql = QString( "SELECT count(*) FROM %1%2" ).arg( mQuery, filterWhereClause() ); + sql = QStringLiteral( "SELECT count(*) FROM %1%2" ).arg( mQuery, filterWhereClause() ); } QgsPostgresResult result( connectionRO()->PQexec( sql ) ); @@ -2924,7 +2924,7 @@ QgsRectangle QgsPostgresProvider::extent() const if ( !mIsQuery && ( mUseEstimatedMetadata || mSqlWhereClause.isEmpty() ) ) { // do stats exists? - sql = QString( "SELECT count(*) FROM pg_stats WHERE schemaname=%1 AND tablename=%2 AND attname=%3" ) + sql = QStringLiteral( "SELECT count(*) FROM pg_stats WHERE schemaname=%1 AND tablename=%2 AND attname=%3" ) .arg( quotedValue( mSchemaName ), quotedValue( mTableName ), quotedValue( mGeometryColumn ) ); @@ -2933,13 +2933,13 @@ QgsRectangle QgsPostgresProvider::extent() const { if ( result.PQgetvalue( 0, 0 ).toInt() > 0 ) { - sql = QString( "SELECT reltuples::int FROM pg_catalog.pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); + sql = QStringLiteral( "SELECT reltuples::int FROM pg_catalog.pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) ); result = connectionRO()->PQexec( sql ); if ( result.PQresultStatus() == PGRES_TUPLES_OK && result.PQntuples() == 1 && result.PQgetvalue( 0, 0 ).toLong() > 0 ) { - sql = QString( "SELECT %1(%2,%3,%4)" ) + sql = QStringLiteral( "SELECT %1(%2,%3,%4)" ) .arg( connectionRO()->majorVersion() < 2 ? "estimated_extent" : ( connectionRO()->majorVersion() == 2 && connectionRO()->minorVersion() < 1 ? "st_estimated_extent" : "st_estimatedextent" ), quotedValue( mSchemaName ), @@ -2954,7 +2954,7 @@ QgsRectangle QgsPostgresProvider::extent() const // dateline extent() returns -180 to 180 (which appears right), but // estimated_extent() returns eastern bound of data (>-180) and // 180 degrees. - if ( !ext.startsWith( "-180 " ) && ext.contains( ",180 " ) ) + if ( !ext.startsWith( QLatin1String( "-180 " ) ) && ext.contains( QLatin1String( ",180 " ) ) ) { ext.clear(); } @@ -2975,7 +2975,7 @@ QgsRectangle QgsPostgresProvider::extent() const if ( ext.isEmpty() ) { - sql = QString( "SELECT %1(%2%3) FROM %4%5" ) + sql = QStringLiteral( "SELECT %1(%2%3) FROM %4%5" ) .arg( connectionRO()->majorVersion() < 2 ? "extent" : "st_extent", quotedIdentifier( mGeometryColumn ), mSpatialColType == sctPcPatch ? "::geometry" : "", @@ -2984,7 +2984,7 @@ QgsRectangle QgsPostgresProvider::extent() const result = connectionRO()->PQexec( sql ); if ( result.PQresultStatus() != PGRES_TUPLES_OK ) - connectionRO()->PQexecNR( "ROLLBACK" ); + connectionRO()->PQexecNR( QStringLiteral( "ROLLBACK" ) ); else if ( result.PQntuples() == 1 && !result.PQgetisnull( 0, 0 ) ) ext = result.PQgetvalue( 0, 0 ); } @@ -3039,7 +3039,7 @@ bool QgsPostgresProvider::getGeometryDetails() if ( mIsQuery ) { - sql = QString( "SELECT %1 FROM %2 LIMIT 0" ).arg( quotedIdentifier( mGeometryColumn ), mQuery ); + sql = QStringLiteral( "SELECT %1 FROM %2 LIMIT 0" ).arg( quotedIdentifier( mGeometryColumn ), mQuery ); QgsDebugMsg( QString( "Getting geometry column: %1" ).arg( sql ) ); @@ -3052,7 +3052,7 @@ bool QgsPostgresProvider::getGeometryDetails() result = connectionRO()->PQexec( sql ); if ( tableoid > 0 && PGRES_TUPLES_OK == result.PQresultStatus() ) { - sql = QString( "SELECT pg_namespace.nspname,pg_class.relname FROM pg_class,pg_namespace WHERE pg_class.relnamespace=pg_namespace.oid AND pg_class.oid=%1" ).arg( tableoid ); + sql = QStringLiteral( "SELECT pg_namespace.nspname,pg_class.relname FROM pg_class,pg_namespace WHERE pg_class.relnamespace=pg_namespace.oid AND pg_class.oid=%1" ).arg( tableoid ); result = connectionRO()->PQexec( sql ); if ( PGRES_TUPLES_OK == result.PQresultStatus() && 1 == result.PQntuples() ) @@ -3060,19 +3060,19 @@ bool QgsPostgresProvider::getGeometryDetails() schemaName = result.PQgetvalue( 0, 0 ); tableName = result.PQgetvalue( 0, 1 ); - sql = QString( "SELECT a.attname, t.typname FROM pg_attribute a, pg_type t WHERE a.attrelid=%1 AND a.attnum=%2 AND a.atttypid = t.oid" ).arg( tableoid ).arg( column ); + sql = QStringLiteral( "SELECT a.attname, t.typname FROM pg_attribute a, pg_type t WHERE a.attrelid=%1 AND a.attnum=%2 AND a.atttypid = t.oid" ).arg( tableoid ).arg( column ); result = connectionRO()->PQexec( sql ); if ( PGRES_TUPLES_OK == result.PQresultStatus() && 1 == result.PQntuples() ) { geomCol = result.PQgetvalue( 0, 0 ); geomColType = result.PQgetvalue( 0, 1 ); - if ( geomColType == "geometry" ) + if ( geomColType == QLatin1String( "geometry" ) ) mSpatialColType = sctGeometry; - else if ( geomColType == "geography" ) + else if ( geomColType == QLatin1String( "geography" ) ) mSpatialColType = sctGeography; - else if ( geomColType == "topogeometry" ) + else if ( geomColType == QLatin1String( "topogeometry" ) ) mSpatialColType = sctTopoGeometry; - else if ( geomColType == "pcpatch" ) + else if ( geomColType == QLatin1String( "pcpatch" ) ) mSpatialColType = sctPcPatch; else mSpatialColType = sctNone; @@ -3086,7 +3086,7 @@ bool QgsPostgresProvider::getGeometryDetails() } else { - schemaName = ""; + schemaName = QLatin1String( "" ); tableName = mQuery; } } @@ -3102,7 +3102,7 @@ bool QgsPostgresProvider::getGeometryDetails() if ( !schemaName.isEmpty() ) { // check geometry columns - sql = QString( "SELECT upper(type),srid,coord_dimension FROM geometry_columns WHERE f_table_name=%1 AND f_geometry_column=%2 AND f_table_schema=%3" ) + sql = QStringLiteral( "SELECT upper(type),srid,coord_dimension FROM geometry_columns WHERE f_table_name=%1 AND f_geometry_column=%2 AND f_table_schema=%3" ) .arg( quotedValue( tableName ), quotedValue( geomCol ), quotedValue( schemaName ) ); @@ -3115,23 +3115,23 @@ bool QgsPostgresProvider::getGeometryDetails() { detectedType = result.PQgetvalue( 0, 0 ); QString dim = result.PQgetvalue( 0, 2 ); - if ( dim == "3" && !detectedType.endsWith( 'M' ) ) - detectedType += "Z"; - else if ( dim == "4" ) - detectedType += "ZM"; + if ( dim == QLatin1String( "3" ) && !detectedType.endsWith( 'M' ) ) + detectedType += QLatin1String( "Z" ); + else if ( dim == QLatin1String( "4" ) ) + detectedType += QLatin1String( "ZM" ); detectedSrid = result.PQgetvalue( 0, 1 ); mSpatialColType = sctGeometry; } else { - connectionRO()->PQexecNR( "COMMIT" ); + connectionRO()->PQexecNR( QStringLiteral( "COMMIT" ) ); } if ( detectedType.isEmpty() ) { // check geography columns - sql = QString( "SELECT upper(type),srid FROM geography_columns WHERE f_table_name=%1 AND f_geography_column=%2 AND f_table_schema=%3" ) + sql = QStringLiteral( "SELECT upper(type),srid FROM geography_columns WHERE f_table_name=%1 AND f_geography_column=%2 AND f_table_schema=%3" ) .arg( quotedValue( tableName ), quotedValue( geomCol ), quotedValue( schemaName ) ); @@ -3148,7 +3148,7 @@ bool QgsPostgresProvider::getGeometryDetails() } else { - connectionRO()->PQexecNR( "COMMIT" ); + connectionRO()->PQexecNR( QStringLiteral( "COMMIT" ) ); } } @@ -3179,14 +3179,14 @@ bool QgsPostgresProvider::getGeometryDetails() } else { - connectionRO()->PQexecNR( "COMMIT" ); + connectionRO()->PQexecNR( QStringLiteral( "COMMIT" ) ); } } if ( detectedType.isEmpty() && connectionRO()->hasPointcloud() ) { // check pointcloud columns - sql = QString( "SELECT 'POLYGON',srid FROM pointcloud_columns WHERE \"table\"=%1 AND \"column\"=%2 AND \"schema\"=%3" ) + sql = QStringLiteral( "SELECT 'POLYGON',srid FROM pointcloud_columns WHERE \"table\"=%1 AND \"column\"=%2 AND \"schema\"=%3" ) .arg( quotedValue( tableName ), quotedValue( geomCol ), quotedValue( schemaName ) ); @@ -3203,7 +3203,7 @@ bool QgsPostgresProvider::getGeometryDetails() } else { - connectionRO()->PQexecNR( "COMMIT" ); + connectionRO()->PQexecNR( QStringLiteral( "COMMIT" ) ); } } @@ -3223,28 +3223,28 @@ bool QgsPostgresProvider::getGeometryDetails() if ( result.PQntuples() == 1 ) { geomColType = result.PQgetvalue( 0, 0 ); - if ( geomColType == "geometry" ) + if ( geomColType == QLatin1String( "geometry" ) ) mSpatialColType = sctGeometry; - else if ( geomColType == "geography" ) + else if ( geomColType == QLatin1String( "geography" ) ) mSpatialColType = sctGeography; - else if ( geomColType == "topogeometry" ) + else if ( geomColType == QLatin1String( "topogeometry" ) ) mSpatialColType = sctTopoGeometry; - else if ( geomColType == "pcpatch" ) + else if ( geomColType == QLatin1String( "pcpatch" ) ) mSpatialColType = sctPcPatch; } else { - connectionRO()->PQexecNR( "COMMIT" ); + connectionRO()->PQexecNR( QStringLiteral( "COMMIT" ) ); } } } else { - sql = QString( "SELECT %1 FROM %2 LIMIT 0" ).arg( quotedIdentifier( mGeometryColumn ), mQuery ); + sql = QStringLiteral( "SELECT %1 FROM %2 LIMIT 0" ).arg( quotedIdentifier( mGeometryColumn ), mQuery ); result = connectionRO()->PQexec( sql ); if ( PGRES_TUPLES_OK == result.PQresultStatus() ) { - sql = QString( "SELECT (SELECT t.typname FROM pg_type t WHERE oid = %1), upper(postgis_typmod_type(%2)), postgis_typmod_srid(%2)" ) + sql = QStringLiteral( "SELECT (SELECT t.typname FROM pg_type t WHERE oid = %1), upper(postgis_typmod_type(%2)), postgis_typmod_srid(%2)" ) .arg( QString::number( result.PQftype( 0 ) ), QString::number( result.PQfmod( 0 ) ) ); result = connectionRO()->PQexec( sql, false ); if ( result.PQntuples() == 1 ) @@ -3252,24 +3252,24 @@ bool QgsPostgresProvider::getGeometryDetails() geomColType = result.PQgetvalue( 0, 0 ); detectedType = result.PQgetvalue( 0, 1 ); detectedSrid = result.PQgetvalue( 0, 2 ); - if ( geomColType == "geometry" ) + if ( geomColType == QLatin1String( "geometry" ) ) mSpatialColType = sctGeometry; - else if ( geomColType == "geography" ) + else if ( geomColType == QLatin1String( "geography" ) ) mSpatialColType = sctGeography; - else if ( geomColType == "topogeometry" ) + else if ( geomColType == QLatin1String( "topogeometry" ) ) mSpatialColType = sctTopoGeometry; - else if ( geomColType == "pcpatch" ) + else if ( geomColType == QLatin1String( "pcpatch" ) ) mSpatialColType = sctPcPatch; else { - detectedType = mRequestedGeomType == QgsWkbTypes::Unknown ? "" : QgsPostgresConn::postgisWkbTypeName( mRequestedGeomType ); + detectedType = mRequestedGeomType == QgsWkbTypes::Unknown ? QLatin1String( "" ) : QgsPostgresConn::postgisWkbTypeName( mRequestedGeomType ); detectedSrid = mRequestedSrid; } } else { - connectionRO()->PQexecNR( "COMMIT" ); - detectedType = mRequestedGeomType == QgsWkbTypes::Unknown ? "" : QgsPostgresConn::postgisWkbTypeName( mRequestedGeomType ); + connectionRO()->PQexecNR( QStringLiteral( "COMMIT" ) ); + detectedType = mRequestedGeomType == QgsWkbTypes::Unknown ? QLatin1String( "" ) : QgsPostgresConn::postgisWkbTypeName( mRequestedGeomType ); } } else @@ -3284,7 +3284,7 @@ bool QgsPostgresProvider::getGeometryDetails() if ( mDetectedGeomType == QgsWkbTypes::Unknown ) { - mDetectedSrid = ""; + mDetectedSrid = QLatin1String( "" ); QgsPostgresLayerProperty layerProperty; if ( !mIsQuery ) @@ -3294,19 +3294,19 @@ bool QgsPostgresProvider::getGeometryDetails() } else { - layerProperty.schemaName = ""; + layerProperty.schemaName = QLatin1String( "" ); layerProperty.tableName = mQuery; } layerProperty.geometryColName = mGeometryColumn; layerProperty.geometryColType = mSpatialColType; layerProperty.force2d = false; - QString delim = ""; + QString delim = QLatin1String( "" ); if ( !mSqlWhereClause.isEmpty() ) { layerProperty.sql += delim + '(' + mSqlWhereClause + ')'; - delim = " AND "; + delim = QStringLiteral( " AND " ); } connectionRO()->retrieveLayerTypes( layerProperty, mUseEstimatedMetadata ); @@ -3365,9 +3365,9 @@ bool QgsPostgresProvider::getGeometryDetails() return false; // store whether the geometry includes measure value - if ( detectedType == "POINTM" || detectedType == "MULTIPOINTM" || - detectedType == "LINESTRINGM" || detectedType == "MULTILINESTRINGM" || - detectedType == "POLYGONM" || detectedType == "MULTIPOLYGONM" || + if ( detectedType == QLatin1String( "POINTM" ) || detectedType == QLatin1String( "MULTIPOINTM" ) || + detectedType == QLatin1String( "LINESTRINGM" ) || detectedType == QLatin1String( "MULTILINESTRINGM" ) || + detectedType == QLatin1String( "POLYGONM" ) || detectedType == QLatin1String( "MULTIPOLYGONM" ) || mForce2d ) { // explicitly disable adding new features and editing of geometries @@ -3384,11 +3384,11 @@ bool QgsPostgresProvider::getGeometryDetails() bool QgsPostgresProvider::convertField( QgsField &field, const QMap<QString, QVariant> *options ) { //determine field type to use for strings - QString stringFieldType = "varchar"; - if ( options && options->value( "dropStringConstraints", false ).toBool() ) + QString stringFieldType = QStringLiteral( "varchar" ); + if ( options && options->value( QStringLiteral( "dropStringConstraints" ), false ).toBool() ) { //drop string length constraints by using PostgreSQL text type for strings - stringFieldType = "text"; + stringFieldType = QStringLiteral( "text" ); } QString fieldType = stringFieldType; //default to string @@ -3397,16 +3397,16 @@ bool QgsPostgresProvider::convertField( QgsField &field, const QMap<QString, QVa switch ( field.type() ) { case QVariant::LongLong: - fieldType = "int8"; + fieldType = QStringLiteral( "int8" ); fieldPrec = 0; break; case QVariant::DateTime: - fieldType = "timestamp without time zone"; + fieldType = QStringLiteral( "timestamp without time zone" ); break; case QVariant::Time: - fieldType = "time"; + fieldType = QStringLiteral( "time" ); break; case QVariant::String: @@ -3415,28 +3415,28 @@ bool QgsPostgresProvider::convertField( QgsField &field, const QMap<QString, QVa break; case QVariant::Int: - fieldType = "int4"; + fieldType = QStringLiteral( "int4" ); fieldPrec = 0; break; case QVariant::Date: - fieldType = "date"; + fieldType = QStringLiteral( "date" ); fieldPrec = 0; break; case QVariant::Map: - fieldType = "hstore"; + fieldType = QStringLiteral( "hstore" ); fieldPrec = -1; break; case QVariant::StringList: - fieldType = "_text"; + fieldType = QStringLiteral( "_text" ); fieldPrec = -1; break; case QVariant::List: { - QgsField sub( "", field.subType(), "", fieldSize, fieldPrec ); + QgsField sub( QLatin1String( "" ), field.subType(), QLatin1String( "" ), fieldSize, fieldPrec ); if ( !convertField( sub, nullptr ) ) return false; fieldType = "_" + sub.typeName(); fieldPrec = -1; @@ -3446,12 +3446,12 @@ bool QgsPostgresProvider::convertField( QgsField &field, const QMap<QString, QVa case QVariant::Double: if ( fieldSize > 18 ) { - fieldType = "numeric"; + fieldType = QStringLiteral( "numeric" ); fieldSize = -1; } else { - fieldType = "float8"; + fieldType = QStringLiteral( "float8" ); } fieldPrec = -1; break; @@ -3489,7 +3489,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q QStringList pkList; QStringList pkType; - QString schemaTableName = ""; + QString schemaTableName = QLatin1String( "" ); if ( !schemaName.isEmpty() ) { schemaTableName += quotedIdentifier( schemaName ) + '.'; @@ -3516,13 +3516,13 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q if ( primaryKey.isEmpty() ) { int index = 0; - QString pk = primaryKey = "id"; + QString pk = primaryKey = QStringLiteral( "id" ); for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) { if ( fields.at( fldIdx ).name() == primaryKey ) { // it already exists, try again with a new name - primaryKey = QString( "%1_%2" ).arg( pk ).arg( index++ ); + primaryKey = QStringLiteral( "%1_%2" ).arg( pk ).arg( index++ ); fldIdx = -1; // it is incremented in the for loop, i.e. restarts at 0 } } @@ -3547,18 +3547,18 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q } } } - if ( type.isEmpty() ) type = "serial"; + if ( type.isEmpty() ) type = QStringLiteral( "serial" ); else { // if the pk field's type is one of the postgres integer types, // use the equivalent autoincremental type (serialN) - if ( primaryKeyType == "int2" || primaryKeyType == "int4" ) + if ( primaryKeyType == QLatin1String( "int2" ) || primaryKeyType == QLatin1String( "int4" ) ) { - primaryKeyType = "serial"; + primaryKeyType = QStringLiteral( "serial" ); } - else if ( primaryKeyType == "int8" ) + else if ( primaryKeyType == QLatin1String( "int8" ) ) { - primaryKeyType = "serial8"; + primaryKeyType = QStringLiteral( "serial8" ); } } pkType << type; @@ -3567,7 +3567,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q try { - conn->PQexecNR( "BEGIN" ); + conn->PQexecNR( QStringLiteral( "BEGIN" ) ); QString sql = QString( "SELECT 1" " FROM pg_class AS cls JOIN pg_namespace AS nsp" @@ -3597,14 +3597,14 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q throw PGException( result ); } - sql = QString( "CREATE TABLE %1(" ) .arg( schemaTableName ); + sql = QStringLiteral( "CREATE TABLE %1(" ) .arg( schemaTableName ); QString pk; for ( int i = 0; i < pkList.size(); ++i ) { QString col = pkList[i]; const QString& type = pkType[i]; - if ( options && options->value( "lowercaseFieldNames", false ).toBool() ) + if ( options && options->value( QStringLiteral( "lowercaseFieldNames" ), false ).toBool() ) { col = col.toLower(); } @@ -3615,14 +3615,14 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q if ( i ) { - pk += ","; - sql += ","; + pk += QLatin1String( "," ); + sql += QLatin1String( "," ); } pk += col; sql += col + " " + type; } - sql += QString( ", PRIMARY KEY (%1) )" ) .arg( pk ); + sql += QStringLiteral( ", PRIMARY KEY (%1) )" ) .arg( pk ); result = conn->PQexec( sql ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) @@ -3637,7 +3637,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q // create geometry column if ( !geometryType.isEmpty() ) { - sql = QString( "SELECT AddGeometryColumn(%1,%2,%3,%4,%5,%6)" ) + sql = QStringLiteral( "SELECT AddGeometryColumn(%1,%2,%3,%4,%5,%6)" ) .arg( quotedValue( schemaName ), quotedValue( tableName ), quotedValue( geometryColumn ) ) @@ -3654,7 +3654,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q geometryColumn.clear(); } - conn->PQexecNR( "COMMIT" ); + conn->PQexecNR( QStringLiteral( "COMMIT" ) ); } catch ( PGException &e ) { @@ -3663,7 +3663,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q .arg( schemaTableName, e.errorMessage() ); - conn->PQexecNR( "ROLLBACK" ); + conn->PQexecNR( QStringLiteral( "ROLLBACK" ) ); conn->unref(); return QgsVectorLayerImport::ErrCreateLayer; } @@ -3707,7 +3707,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q continue; } - if ( options && options->value( "lowercaseFieldNames", false ).toBool() ) + if ( options && options->value( QStringLiteral( "lowercaseFieldNames" ), false ).toBool() ) { //convert field name to lowercase fld.setName( fld.name().toLower() ); @@ -3717,7 +3717,7 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q for ( int i = 0; i < pkList.size(); ++i ) { QString col = pkList[i]; - if ( options && options->value( "lowercaseFieldNames", false ).toBool() ) + if ( options && options->value( QStringLiteral( "lowercaseFieldNames" ), false ).toBool() ) { //convert field name to lowercase (TODO: avoid doing this //over and over) @@ -3776,7 +3776,7 @@ QgsCoordinateReferenceSystem QgsPostgresProvider::crs() const srs.createFromSrid( srid ); if ( !srs.isValid() ) { - QgsPostgresResult result( connectionRO()->PQexec( QString( "SELECT proj4text FROM spatial_ref_sys WHERE srid=%1" ).arg( srid ) ) ); + QgsPostgresResult result( connectionRO()->PQexec( QStringLiteral( "SELECT proj4text FROM spatial_ref_sys WHERE srid=%1" ).arg( srid ) ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) srs = QgsCoordinateReferenceSystem::fromProj4( result.PQgetvalue( 0, 0 ) ); } @@ -3813,13 +3813,13 @@ QString QgsPostgresProvider::description() const { QgsPostgresResult result; - result = connectionRO()->PQexec( "SELECT version()" ); + result = connectionRO()->PQexec( QStringLiteral( "SELECT version()" ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { pgVersion = result.PQgetvalue( 0, 0 ); } - result = connectionRO()->PQexec( "SELECT postgis_version()" ); + result = connectionRO()->PQexec( QStringLiteral( "SELECT postgis_version()" ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { postgisVersion = result.PQgetvalue( 0, 0 ); @@ -3858,7 +3858,7 @@ static QString getNextString( const QString& txt, int& i, const QString& sep ) return QString::null; } i += sep.length(); - return stringRe.cap( 1 ).replace( "\\\"", "\"" ).replace( "\\\\", "\\" ); + return stringRe.cap( 1 ).replace( QLatin1String( "\\\"" ), QLatin1String( "\"" ) ).replace( QLatin1String( "\\\\" ), QLatin1String( "\\" ) ); } else { @@ -3879,8 +3879,8 @@ static QVariant parseHstore( const QString& txt ) int i = 0; while ( i < txt.length() ) { - QString key = getNextString( txt, i, "=>" ); - QString value = getNextString( txt, i, "," ); + QString key = getNextString( txt, i, QStringLiteral( "=>" ) ); + QString value = getNextString( txt, i, QStringLiteral( "," ) ); if ( key.isNull() || value.isNull() ) { QgsLogger::warning( "Error parsing hstore: " + txt ); @@ -3898,7 +3898,7 @@ static QVariant parseOtherArray( const QString& txt, QVariant::Type subType ) QVariantList result; while ( i < txt.length() ) { - const QString value = getNextString( txt, i, "," ); + const QString value = getNextString( txt, i, QStringLiteral( "," ) ); if ( value.isNull() ) { QgsLogger::warning( "Error parsing array: " + txt ); @@ -3915,7 +3915,7 @@ static QVariant parseStringArray( const QString& txt ) QStringList result; while ( i < txt.length() ) { - const QString value = getNextString( txt, i, "," ); + const QString value = getNextString( txt, i, QStringLiteral( "," ) ); if ( value.isNull() ) { QgsLogger::warning( "Error parsing array: " + txt ); @@ -4003,7 +4003,7 @@ QList<QgsRelation> QgsPostgresProvider::discoverRelations( const QgsVectorLayer* const QString refTable = sqlResult.PQgetvalue( row, 3 ); const QString refColumn = sqlResult.PQgetvalue( row, 4 ); const QString position = sqlResult.PQgetvalue( row, 5 ); - if ( position == "1" ) + if ( position == QLatin1String( "1" ) ) { // first reference field => try to find if we have layers for the referenced table const QList<QgsVectorLayer*> foundLayers = searchLayers( layers, mUri.connectionInfo( false ), refSchema, refTable ); Q_FOREACH ( const QgsVectorLayer* foundLayer, foundLayers ) @@ -4084,7 +4084,7 @@ QGISEXTERN int dataCapabilities() QGISEXTERN QgsDataItem *dataItem( QString thePath, QgsDataItem *parentItem ) { Q_UNUSED( thePath ); - return new QgsPGRootItem( parentItem, "PostGIS", "pg:" ); + return new QgsPGRootItem( parentItem, QStringLiteral( "PostGIS" ), QStringLiteral( "pg:" ) ); } // --------------------------------------------------------------------------- @@ -4151,7 +4151,7 @@ QGISEXTERN bool deleteLayer( const QString& uri, QString& errCause ) if ( !geometryCol.isEmpty() && count > 1 ) { // the table has more geometry columns, drop just the geometry column - sql = QString( "SELECT DropGeometryColumn(%1,%2,%3)" ) + sql = QStringLiteral( "SELECT DropGeometryColumn(%1,%2,%3)" ) .arg( QgsPostgresConn::quotedValue( schemaName ), QgsPostgresConn::quotedValue( tableName ), QgsPostgresConn::quotedValue( geometryCol ) ); @@ -4159,7 +4159,7 @@ QGISEXTERN bool deleteLayer( const QString& uri, QString& errCause ) else { // drop the table - sql = QString( "SELECT DropGeometryTable(%1,%2)" ) + sql = QStringLiteral( "SELECT DropGeometryTable(%1,%2)" ) .arg( QgsPostgresConn::quotedValue( schemaName ), QgsPostgresConn::quotedValue( tableName ) ); } @@ -4195,8 +4195,8 @@ QGISEXTERN bool deleteSchema( const QString& schema, const QgsDataSourceUri& uri } // drop the schema - QString sql = QString( "DROP SCHEMA %1 %2" ) - .arg( schemaName, cascade ? QString( "CASCADE" ) : QString() ); + QString sql = QStringLiteral( "DROP SCHEMA %1 %2" ) + .arg( schemaName, cascade ? QStringLiteral( "CASCADE" ) : QString() ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) @@ -4225,7 +4225,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS return false; } - if ( !tableExists( *conn, "layer_styles" ) ) + if ( !tableExists( *conn, QStringLiteral( "layer_styles" ) ) ) { QgsPostgresResult res( conn->PQexec( "CREATE TABLE layer_styles(" "id SERIAL PRIMARY KEY" @@ -4254,8 +4254,8 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS QString uiFileValue; if ( !uiFileContent.isEmpty() ) { - uiFileColumn = ",ui"; - uiFileValue = QString( ",XMLPARSE(DOCUMENT %1)" ).arg( QgsPostgresConn::quotedValue( uiFileContent ) ); + uiFileColumn = QStringLiteral( ",ui" ); + uiFileValue = QStringLiteral( ",XMLPARSE(DOCUMENT %1)" ).arg( QgsPostgresConn::quotedValue( uiFileContent ) ); } // Note: in the construction of the INSERT and UPDATE strings the qmlStyle and sldStyle values @@ -4344,7 +4344,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS .arg( QgsPostgresConn::quotedValue( dsUri.schema() ) ) .arg( QgsPostgresConn::quotedValue( dsUri.table() ) ) .arg( QgsPostgresConn::quotedValue( dsUri.geometryColumn() ) ); - sql = QString( "BEGIN; %1; %2; COMMIT;" ).arg( removeDefaultSql, sql ); + sql = QStringLiteral( "BEGIN; %1; %2; COMMIT;" ).arg( removeDefaultSql, sql ); } res = conn->PQexec( sql ); @@ -4367,12 +4367,12 @@ QGISEXTERN QString loadStyle( const QString& uri, QString& errCause ) if ( !conn ) { errCause = QObject::tr( "Connection to database failed" ); - return ""; + return QLatin1String( "" ); } - if ( !tableExists( *conn, "layer_styles" ) ) + if ( !tableExists( *conn, QStringLiteral( "layer_styles" ) ) ) { - return ""; + return QLatin1String( "" ); } QString selectQmlQuery = QString( "SELECT styleQML" @@ -4390,7 +4390,7 @@ QGISEXTERN QString loadStyle( const QString& uri, QString& errCause ) QgsPostgresResult result( conn->PQexec( selectQmlQuery ) ); - QString style = result.PQntuples() == 1 ? result.PQgetvalue( 0, 0 ) : ""; + QString style = result.PQntuples() == 1 ? result.PQgetvalue( 0, 0 ) : QLatin1String( "" ); conn->unref(); return style; @@ -4474,18 +4474,18 @@ QGISEXTERN QString getStyleById( const QString& uri, QString styleId, QString& e if ( !conn ) { errCause = QObject::tr( "Connection to database failed using username: %1" ).arg( dsUri.username() ); - return ""; + return QLatin1String( "" ); } QString style; - QString selectQmlQuery = QString( "SELECT styleQml FROM layer_styles WHERE id=%1" ).arg( QgsPostgresConn::quotedValue( styleId ) ); + QString selectQmlQuery = QStringLiteral( "SELECT styleQml FROM layer_styles WHERE id=%1" ).arg( QgsPostgresConn::quotedValue( styleId ) ); QgsPostgresResult result( conn->PQexec( selectQmlQuery ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { if ( result.PQntuples() == 1 ) style = result.PQgetvalue( 0, 0 ); else - errCause = QObject::tr( "Consistency error in table '%1'. Style id should be unique" ).arg( "layer_styles" ); + errCause = QObject::tr( "Consistency error in table '%1'. Style id should be unique" ).arg( QStringLiteral( "layer_styles" ) ); } else { diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index d1c46c808da1..d5d0ee07d9da 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -72,7 +72,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider * @param uri String containing the required parameters to connect to the database * and query the table. */ - explicit QgsPostgresProvider( QString const &uri = "" ); + explicit QgsPostgresProvider( QString const &uri = QLatin1String( "" ) ); //! Destructor virtual ~QgsPostgresProvider(); diff --git a/src/providers/postgres/qgspostgrestransaction.cpp b/src/providers/postgres/qgspostgrestransaction.cpp index 750cb7514467..560479349961 100644 --- a/src/providers/postgres/qgspostgrestransaction.cpp +++ b/src/providers/postgres/qgspostgrestransaction.cpp @@ -31,13 +31,13 @@ bool QgsPostgresTransaction::beginTransaction( QString &error, int statementTime { mConn = QgsPostgresConn::connectDb( mConnString, false /*readonly*/, false /*shared*/, true /*transaction*/ ); - return executeSql( QString( "SET statement_timeout = %1" ).arg( statementTimeout * 1000 ), error ) - && executeSql( "BEGIN TRANSACTION", error ); + return executeSql( QStringLiteral( "SET statement_timeout = %1" ).arg( statementTimeout * 1000 ), error ) + && executeSql( QStringLiteral( "BEGIN TRANSACTION" ), error ); } bool QgsPostgresTransaction::commitTransaction( QString &error ) { - if ( executeSql( "COMMIT TRANSACTION", error ) ) + if ( executeSql( QStringLiteral( "COMMIT TRANSACTION" ), error ) ) { mConn->unref(); mConn = nullptr; @@ -48,7 +48,7 @@ bool QgsPostgresTransaction::commitTransaction( QString &error ) bool QgsPostgresTransaction::rollbackTransaction( QString &error ) { - if ( executeSql( "ROLLBACK TRANSACTION", error ) ) + if ( executeSql( QStringLiteral( "ROLLBACK TRANSACTION" ), error ) ) { mConn->unref(); mConn = nullptr; @@ -70,7 +70,7 @@ bool QgsPostgresTransaction::executeSql( const QString &sql, QString &errorMsg ) mConn->unlock(); if ( r.PQresultStatus() != PGRES_COMMAND_OK ) { - errorMsg = QString( "Status %1 (%2)" ).arg( r.PQresultStatus() ).arg( r.PQresultErrorMessage() ); + errorMsg = QStringLiteral( "Status %1 (%2)" ).arg( r.PQresultStatus() ).arg( r.PQresultErrorMessage() ); QgsDebugMsg( errorMsg ); return false; } diff --git a/src/providers/spatialite/qgsspatialiteconnection.cpp b/src/providers/spatialite/qgsspatialiteconnection.cpp index 9bf918f1528f..b0db367f5f8b 100644 --- a/src/providers/spatialite/qgsspatialiteconnection.cpp +++ b/src/providers/spatialite/qgsspatialiteconnection.cpp @@ -28,7 +28,7 @@ QStringList QgsSpatiaLiteConnection::connectionList() { QSettings settings; - settings.beginGroup( "/SpatiaLite/connections" ); + settings.beginGroup( QStringLiteral( "/SpatiaLite/connections" ) ); return settings.childGroups(); } @@ -53,7 +53,7 @@ QgsSpatiaLiteConnection::QgsSpatiaLiteConnection( const QString& name ) // "name" can be either a saved connection or a path to database QSettings settings; - mPath = settings.value( QString( "/SpatiaLite/connections/%1/sqlitepath" ).arg( name ) ).toString(); + mPath = settings.value( QStringLiteral( "/SpatiaLite/connections/%1/sqlitepath" ).arg( name ) ).toString(); if ( mPath.isNull() ) mPath = name; // not found in settings - probably it's a path } @@ -179,7 +179,7 @@ int QgsSpatiaLiteConnection::checkHasMetadataTables( sqlite3* handle ) ret = sqlite3_get_table( handle, "PRAGMA table_info(geometry_columns)", &results, &rows, &columns, &errMsg ); if ( ret != SQLITE_OK ) { - mErrorMsg = tr( "table info on %1 failed" ).arg( "geometry_columns" ); + mErrorMsg = tr( "table info on %1 failed" ).arg( QStringLiteral( "geometry_columns" ) ); goto error; } if ( rows < 1 ) @@ -215,7 +215,7 @@ int QgsSpatiaLiteConnection::checkHasMetadataTables( sqlite3* handle ) ret = sqlite3_get_table( handle, "PRAGMA table_info(spatial_ref_sys)", &results, &rows, &columns, &errMsg ); if ( ret != SQLITE_OK ) { - mErrorMsg = tr( "table info on %1 failed" ).arg( "spatial_ref_sys" ); + mErrorMsg = tr( "table info on %1 failed" ).arg( QStringLiteral( "spatial_ref_sys" ) ); goto error; } if ( rows < 1 ) @@ -358,7 +358,7 @@ bool QgsSpatiaLiteConnection::getTableInfoAbstractInterface( sqlite3 * handle, b for ( i = 1; i <= rows; i++ ) { QString tableName = QString::fromUtf8( results[( i * columns ) + 0] ); - mTables.append( TableEntry( tableName, QString(), "qgis_table" ) ); + mTables.append( TableEntry( tableName, QString(), QStringLiteral( "qgis_table" ) ) ); } } sqlite3_free_table( results ); @@ -463,7 +463,7 @@ bool QgsSpatiaLiteConnection::getTableInfo( sqlite3 * handle, bool loadGeometryl for ( i = 1; i <= rows; i++ ) { QString tableName = QString::fromUtf8( results[( i * columns ) + 0] ); - mTables.append( TableEntry( tableName, QString(), "qgis_table" ) ); + mTables.append( TableEntry( tableName, QString(), QStringLiteral( "qgis_table" ) ) ); } sqlite3_free_table( results ); } @@ -484,9 +484,9 @@ bool QgsSpatiaLiteConnection::getTableInfo( sqlite3 * handle, bool loadGeometryl QString QgsSpatiaLiteConnection::quotedValue( QString value ) const { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); - value.replace( '\'', "''" ); + value.replace( '\'', QLatin1String( "''" ) ); return value.prepend( '\'' ).append( '\'' ); } @@ -500,7 +500,7 @@ bool QgsSpatiaLiteConnection::checkGeometryColumnsAuth( sqlite3 * handle ) bool exists = false; // checking the metadata tables - QString sql = QString( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'geometry_columns_auth'" ); + QString sql = QStringLiteral( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'geometry_columns_auth'" ); ret = sqlite3_get_table( handle, sql.toUtf8().constData(), &results, &rows, &columns, nullptr ); if ( ret != SQLITE_OK ) @@ -534,7 +534,7 @@ bool QgsSpatiaLiteConnection::checkViewsGeometryColumns( sqlite3 * handle ) bool exists = false; // checking the metadata tables - QString sql = QString( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'views_geometry_columns'" ); + QString sql = QStringLiteral( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'views_geometry_columns'" ); ret = sqlite3_get_table( handle, sql.toUtf8().constData(), &results, &rows, &columns, nullptr ); if ( ret != SQLITE_OK ) @@ -567,7 +567,7 @@ bool QgsSpatiaLiteConnection::checkVirtsGeometryColumns( sqlite3 * handle ) bool exists = false; // checking the metadata tables - QString sql = QString( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'virts_geometry_columns'" ); + QString sql = QStringLiteral( "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'virts_geometry_columns'" ); ret = sqlite3_get_table( handle, sql.toUtf8().constData(), &results, &rows, &columns, nullptr ); if ( ret != SQLITE_OK ) diff --git a/src/providers/spatialite/qgsspatialitedataitems.cpp b/src/providers/spatialite/qgsspatialitedataitems.cpp index 88b27977312c..4ba769d9f615 100644 --- a/src/providers/spatialite/qgsspatialitedataitems.cpp +++ b/src/providers/spatialite/qgsspatialitedataitems.cpp @@ -32,7 +32,7 @@ QGISEXTERN bool deleteLayer( const QString& dbPath, const QString& tableName, QString& errCause ); QgsSLLayerItem::QgsSLLayerItem( QgsDataItem* parent, QString name, QString path, QString uri, LayerType layerType ) - : QgsLayerItem( parent, name, path, uri, layerType, "spatialite" ) + : QgsLayerItem( parent, name, path, uri, layerType, QStringLiteral( "spatialite" ) ) { setState( Populated ); // no children are expected } @@ -84,19 +84,19 @@ QgsSLConnectionItem::~QgsSLConnectionItem() static QgsLayerItem::LayerType _layerTypeFromDb( QString dbType ) { - if ( dbType == "POINT" || dbType == "MULTIPOINT" ) + if ( dbType == QLatin1String( "POINT" ) || dbType == QLatin1String( "MULTIPOINT" ) ) { return QgsLayerItem::Point; } - else if ( dbType == "LINESTRING" || dbType == "MULTILINESTRING" ) + else if ( dbType == QLatin1String( "LINESTRING" ) || dbType == QLatin1String( "MULTILINESTRING" ) ) { return QgsLayerItem::Line; } - else if ( dbType == "POLYGON" || dbType == "MULTIPOLYGON" ) + else if ( dbType == QLatin1String( "POLYGON" ) || dbType == QLatin1String( "MULTIPOLYGON" ) ) { return QgsLayerItem::Polygon; } - else if ( dbType == "qgis_table" ) + else if ( dbType == QLatin1String( "qgis_table" ) ) { return QgsLayerItem::Table; } @@ -135,12 +135,12 @@ QVector<QgsDataItem*> QgsSLConnectionItem::createChildren() } QString msgDetails = connection.errorMessage(); if ( !msgDetails.isEmpty() ) - msg = QString( "%1 (%2)" ).arg( msg, msgDetails ); + msg = QStringLiteral( "%1 (%2)" ).arg( msg, msgDetails ); children.append( new QgsErrorItem( this, msg, mPath + "/error" ) ); return children; } - QString connectionInfo = QString( "dbname='%1'" ).arg( QString( connection.path() ).replace( '\'', "\\'" ) ); + QString connectionInfo = QStringLiteral( "dbname='%1'" ).arg( QString( connection.path() ).replace( '\'', QLatin1String( "\\'" ) ) ); QgsDataSourceUri uri( connectionInfo ); Q_FOREACH ( const QgsSpatiaLiteConnection::TableEntry& entry, connection.tables() ) @@ -217,7 +217,7 @@ bool QgsSLConnectionItem::handleDrop( const QMimeData * data, Qt::DropAction ) QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data ); Q_FOREACH ( const QgsMimeDataUtils::Uri& u, lst ) { - if ( u.layerType != "vector" ) + if ( u.layerType != QLatin1String( "vector" ) ) { importResults.append( tr( "%1: Not a vector layer!" ).arg( u.name ) ); hasError = true; // only vectors can be imported @@ -229,18 +229,18 @@ bool QgsSLConnectionItem::handleDrop( const QMimeData * data, Qt::DropAction ) if ( srcLayer->isValid() ) { - destUri.setDataSource( QString(), u.name, srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? "geom" : QString() ); + destUri.setDataSource( QString(), u.name, srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? QStringLiteral( "geom" ) : QString() ); QgsDebugMsg( "URI " + destUri.uri() ); QgsVectorLayerImport::ImportError err; QString importError; - err = QgsVectorLayerImport::importLayer( srcLayer, destUri.uri(), "spatialite", srcLayer->crs(), false, &importError, false, nullptr, progress ); + err = QgsVectorLayerImport::importLayer( srcLayer, destUri.uri(), QStringLiteral( "spatialite" ), srcLayer->crs(), false, &importError, false, nullptr, progress ); if ( err == QgsVectorLayerImport::NoError ) importResults.append( tr( "%1: OK!" ).arg( u.name ) ); else if ( err == QgsVectorLayerImport::ErrUserCancelled ) cancelled = true; else { - importResults.append( QString( "%1: %2" ).arg( u.name, importError ) ); + importResults.append( QStringLiteral( "%1: %2" ).arg( u.name, importError ) ); hasError = true; } } @@ -266,7 +266,7 @@ bool QgsSLConnectionItem::handleDrop( const QMimeData * data, Qt::DropAction ) { QgsMessageOutput *output = QgsMessageOutput::createMessageOutput(); output->setTitle( tr( "Import to SpatiaLite database" ) ); - output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( "\n" ), QgsMessageOutput::MessageText ); + output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText ); output->showMessage(); } else @@ -285,7 +285,7 @@ QgsSLRootItem::QgsSLRootItem( QgsDataItem* parent, QString name, QString path ) : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconSpatialite.svg"; + mIconName = QStringLiteral( "mIconSpatialite.svg" ); populate(); } @@ -344,7 +344,7 @@ QGISEXTERN bool createDb( const QString& dbPath, QString& errCause ); void QgsSLRootItem::createDatabase() { QSettings settings; - QString lastUsedDir = settings.value( "/UI/lastSpatiaLiteDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastSpatiaLiteDir" ), QDir::homePath() ).toString(); QString filename = QFileDialog::getSaveFileName( nullptr, tr( "New SpatiaLite Database File" ), lastUsedDir, @@ -382,5 +382,5 @@ QGISEXTERN int dataCapabilities() QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) { Q_UNUSED( thePath ); - return new QgsSLRootItem( parentItem, "SpatiaLite", "spatialite:" ); + return new QgsSLRootItem( parentItem, QStringLiteral( "SpatiaLite" ), QStringLiteral( "spatialite:" ) ); } diff --git a/src/providers/spatialite/qgsspatialitefeatureiterator.cpp b/src/providers/spatialite/qgsspatialitefeatureiterator.cpp index 2a48891ba16c..d90f9f286d16 100644 --- a/src/providers/spatialite/qgsspatialitefeatureiterator.cpp +++ b/src/providers/spatialite/qgsspatialitefeatureiterator.cpp @@ -99,7 +99,7 @@ QgsSpatiaLiteFeatureIterator::QgsSpatiaLiteFeatureIterator( QgsSpatiaLiteFeature mFetchGeometry = true; } - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { QgsSQLiteExpressionCompiler compiler = QgsSQLiteExpressionCompiler( source->mFields ); @@ -111,7 +111,7 @@ QgsSpatiaLiteFeatureIterator::QgsSpatiaLiteFeatureIterator( QgsSpatiaLiteFeature if ( !whereClause.isEmpty() ) { useFallbackWhereClause = true; - fallbackWhereClause = whereClauses.join( " AND " ); + fallbackWhereClause = whereClauses.join( QStringLiteral( " AND " ) ); whereClauses.append( whereClause ); //if only partial success when compiling expression, we need to double-check results using QGIS' expressions mExpressionCompiled = ( result == QgsSqlExpressionCompiler::Complete ); @@ -131,14 +131,14 @@ QgsSpatiaLiteFeatureIterator::QgsSpatiaLiteFeatureIterator( QgsSpatiaLiteFeature } - whereClause = whereClauses.join( " AND " ); + whereClause = whereClauses.join( QStringLiteral( " AND " ) ); // Setup the order by QStringList orderByParts; mOrderByCompiled = true; - if ( QSettings().value( "/qgis/compileExpressions", true ).toBool() ) + if ( QSettings().value( QStringLiteral( "/qgis/compileExpressions" ), true ).toBool() ) { Q_FOREACH ( const QgsFeatureRequest::OrderByClause& clause, request.orderBy() ) { @@ -150,9 +150,9 @@ QgsSpatiaLiteFeatureIterator::QgsSpatiaLiteFeatureIterator( QgsSpatiaLiteFeature part = compiler.result(); if ( clause.nullsFirst() ) - orderByParts << QString( "%1 IS NOT NULL" ).arg( part ); + orderByParts << QStringLiteral( "%1 IS NOT NULL" ).arg( part ); else - orderByParts << QString( "%1 IS NULL" ).arg( part ); + orderByParts << QStringLiteral( "%1 IS NULL" ).arg( part ); part += clause.ascending() ? " COLLATE NOCASE ASC" : " COLLATE NOCASE DESC"; orderByParts << part; @@ -177,12 +177,12 @@ QgsSpatiaLiteFeatureIterator::QgsSpatiaLiteFeatureIterator( QgsSpatiaLiteFeature limitAtProvider = false; // preparing the SQL statement - bool success = prepareStatement( whereClause, limitAtProvider ? mRequest.limit() : -1, orderByParts.join( "," ) ); + bool success = prepareStatement( whereClause, limitAtProvider ? mRequest.limit() : -1, orderByParts.join( QStringLiteral( "," ) ) ); if ( !success && useFallbackWhereClause ) { //try with the fallback where clause, eg for cases when using compiled expression failed to prepare mExpressionCompiled = false; - success = prepareStatement( fallbackWhereClause, -1, orderByParts.join( "," ) ); + success = prepareStatement( fallbackWhereClause, -1, orderByParts.join( QStringLiteral( "," ) ) ); } if ( !success ) @@ -286,7 +286,7 @@ bool QgsSpatiaLiteFeatureIterator::prepareStatement( const QString& whereClause, try { - QString sql = QString( "SELECT %1" ).arg( mHasPrimaryKey ? quotedPrimaryKey() : "0" ); + QString sql = QStringLiteral( "SELECT %1" ).arg( mHasPrimaryKey ? quotedPrimaryKey() : QStringLiteral( "0" ) ); int colIdx = 1; // column 0 is primary key if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) @@ -310,19 +310,19 @@ bool QgsSpatiaLiteFeatureIterator::prepareStatement( const QString& whereClause, if ( mFetchGeometry ) { - sql += QString( ", AsBinary(%1)" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ) ); + sql += QStringLiteral( ", AsBinary(%1)" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ) ); mGeomColIdx = colIdx; } - sql += QString( " FROM %1" ).arg( mSource->mQuery ); + sql += QStringLiteral( " FROM %1" ).arg( mSource->mQuery ); if ( !whereClause.isEmpty() ) - sql += QString( " WHERE %1" ).arg( whereClause ); + sql += QStringLiteral( " WHERE %1" ).arg( whereClause ); if ( !orderBy.isEmpty() ) - sql += QString( " ORDER BY %1" ).arg( orderBy ); + sql += QStringLiteral( " ORDER BY %1" ).arg( orderBy ); if ( limit >= 0 ) - sql += QString( " LIMIT %1" ).arg( limit ); + sql += QStringLiteral( " LIMIT %1" ).arg( limit ); if ( sqlite3_prepare_v2( mHandle->handle(), sql.toUtf8().constData(), -1, &sqliteStatement, nullptr ) != SQLITE_OK ) { @@ -342,20 +342,20 @@ bool QgsSpatiaLiteFeatureIterator::prepareStatement( const QString& whereClause, QString QgsSpatiaLiteFeatureIterator::quotedPrimaryKey() { - return mSource->mPrimaryKey.isEmpty() ? "ROWID" : QgsSpatiaLiteProvider::quotedIdentifier( mSource->mPrimaryKey ); + return mSource->mPrimaryKey.isEmpty() ? QStringLiteral( "ROWID" ) : QgsSpatiaLiteProvider::quotedIdentifier( mSource->mPrimaryKey ); } QString QgsSpatiaLiteFeatureIterator::whereClauseFid() { - return QString( "%1=%2" ).arg( quotedPrimaryKey() ).arg( mRequest.filterFid() ); + return QStringLiteral( "%1=%2" ).arg( quotedPrimaryKey() ).arg( mRequest.filterFid() ); } QString QgsSpatiaLiteFeatureIterator::whereClauseFids() { if ( mRequest.filterFids().isEmpty() ) - return ""; + return QLatin1String( "" ); - QString expr = QString( "%1 IN (" ).arg( quotedPrimaryKey() ), delim; + QString expr = QStringLiteral( "%1 IN (" ).arg( quotedPrimaryKey() ), delim; Q_FOREACH ( const QgsFeatureId featureId, mRequest.filterFids() ) { expr += delim + QString::number( featureId ); @@ -373,24 +373,24 @@ QString QgsSpatiaLiteFeatureIterator::whereClauseRect() if ( mRequest.flags() & QgsFeatureRequest::ExactIntersect ) { // we are requested to evaluate a true INTERSECT relationship - whereClause += QString( "Intersects(%1, BuildMbr(%2)) AND " ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ), mbr( rect ) ); + whereClause += QStringLiteral( "Intersects(%1, BuildMbr(%2)) AND " ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ), mbr( rect ) ); } if ( mSource->mVShapeBased ) { // handling a VirtualShape layer - whereClause += QString( "MbrIntersects(%1, BuildMbr(%2))" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ), mbr( rect ) ); + whereClause += QStringLiteral( "MbrIntersects(%1, BuildMbr(%2))" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ), mbr( rect ) ); } else if ( rect.isFinite() ) { if ( mSource->mSpatialIndexRTree ) { // using the RTree spatial index - QString mbrFilter = QString( "xmin <= %1 AND " ).arg( qgsDoubleToString( rect.xMaximum() ) ); - mbrFilter += QString( "xmax >= %1 AND " ).arg( qgsDoubleToString( rect.xMinimum() ) ); - mbrFilter += QString( "ymin <= %1 AND " ).arg( qgsDoubleToString( rect.yMaximum() ) ); - mbrFilter += QString( "ymax >= %1" ).arg( qgsDoubleToString( rect.yMinimum() ) ); - QString idxName = QString( "idx_%1_%2" ).arg( mSource->mIndexTable, mSource->mIndexGeometry ); - whereClause += QString( "%1 IN (SELECT pkid FROM %2 WHERE %3)" ) + QString mbrFilter = QStringLiteral( "xmin <= %1 AND " ).arg( qgsDoubleToString( rect.xMaximum() ) ); + mbrFilter += QStringLiteral( "xmax >= %1 AND " ).arg( qgsDoubleToString( rect.xMinimum() ) ); + mbrFilter += QStringLiteral( "ymin <= %1 AND " ).arg( qgsDoubleToString( rect.yMaximum() ) ); + mbrFilter += QStringLiteral( "ymax >= %1" ).arg( qgsDoubleToString( rect.yMinimum() ) ); + QString idxName = QStringLiteral( "idx_%1_%2" ).arg( mSource->mIndexTable, mSource->mIndexGeometry ); + whereClause += QStringLiteral( "%1 IN (SELECT pkid FROM %2 WHERE %3)" ) .arg( quotedPrimaryKey(), QgsSpatiaLiteProvider::quotedIdentifier( idxName ), mbrFilter ); @@ -398,8 +398,8 @@ QString QgsSpatiaLiteFeatureIterator::whereClauseRect() else if ( mSource->mSpatialIndexMbrCache ) { // using the MbrCache spatial index - QString idxName = QString( "cache_%1_%2" ).arg( mSource->mIndexTable, mSource->mIndexGeometry ); - whereClause += QString( "%1 IN (SELECT rowid FROM %2 WHERE mbr = FilterMbrIntersects(%3))" ) + QString idxName = QStringLiteral( "cache_%1_%2" ).arg( mSource->mIndexTable, mSource->mIndexGeometry ); + whereClause += QStringLiteral( "%1 IN (SELECT rowid FROM %2 WHERE mbr = FilterMbrIntersects(%3))" ) .arg( quotedPrimaryKey(), QgsSpatiaLiteProvider::quotedIdentifier( idxName ), mbr( rect ) ); @@ -407,7 +407,7 @@ QString QgsSpatiaLiteFeatureIterator::whereClauseRect() else { // using simple MBR filtering - whereClause += QString( "MbrIntersects(%1, BuildMbr(%2))" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ), mbr( rect ) ); + whereClause += QStringLiteral( "MbrIntersects(%1, BuildMbr(%2))" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mSource->mGeometryColumn ), mbr( rect ) ); } } else @@ -420,7 +420,7 @@ QString QgsSpatiaLiteFeatureIterator::whereClauseRect() QString QgsSpatiaLiteFeatureIterator::mbr( const QgsRectangle& rect ) { - return QString( "%1, %2, %3, %4" ) + return QStringLiteral( "%1, %2, %3, %4" ) .arg( qgsDoubleToString( rect.xMinimum() ), qgsDoubleToString( rect.yMinimum() ), qgsDoubleToString( rect.xMaximum() ), @@ -432,10 +432,10 @@ QString QgsSpatiaLiteFeatureIterator::fieldName( const QgsField& fld ) { QString fieldname = QgsSpatiaLiteProvider::quotedIdentifier( fld.name() ); const QString type = fld.typeName().toLower(); - if ( type.contains( "geometry" ) || type.contains( "point" ) || - type.contains( "line" ) || type.contains( "polygon" ) ) + if ( type.contains( QLatin1String( "geometry" ) ) || type.contains( QLatin1String( "point" ) ) || + type.contains( QLatin1String( "line" ) ) || type.contains( QLatin1String( "polygon" ) ) ) { - fieldname = QString( "AsText(%1)" ).arg( fieldname ); + fieldname = QStringLiteral( "AsText(%1)" ).arg( fieldname ); } return fieldname; } diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index ef7a49dd5d06..b8be23e70c1e 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -38,22 +38,22 @@ email : a.furieri@lqt.it #include <QDir> -const QString SPATIALITE_KEY = "spatialite"; -const QString SPATIALITE_DESCRIPTION = "SpatiaLite data provider"; -static const QString SPATIALITE_ARRAY_PREFIX = "json"; -static const QString SPATIALITE_ARRAY_SUFFIX = "list"; +const QString SPATIALITE_KEY = QStringLiteral( "spatialite" ); +const QString SPATIALITE_DESCRIPTION = QStringLiteral( "SpatiaLite data provider" ); +static const QString SPATIALITE_ARRAY_PREFIX = QStringLiteral( "json" ); +static const QString SPATIALITE_ARRAY_SUFFIX = QStringLiteral( "list" ); bool QgsSpatiaLiteProvider::convertField( QgsField &field ) { - QString fieldType = "TEXT"; //default to string + QString fieldType = QStringLiteral( "TEXT" ); //default to string int fieldSize = field.length(); int fieldPrec = field.precision(); switch ( field.type() ) { case QVariant::LongLong: - fieldType = "BIGINT"; + fieldType = QStringLiteral( "BIGINT" ); fieldSize = -1; fieldPrec = 0; break; @@ -62,12 +62,12 @@ bool QgsSpatiaLiteProvider::convertField( QgsField &field ) case QVariant::Date: case QVariant::Time: case QVariant::String: - fieldType = "TEXT"; + fieldType = QStringLiteral( "TEXT" ); fieldPrec = -1; break; case QVariant::Int: - fieldType = "INTEGER"; + fieldType = QStringLiteral( "INTEGER" ); fieldSize = -1; fieldPrec = 0; break; @@ -75,13 +75,13 @@ bool QgsSpatiaLiteProvider::convertField( QgsField &field ) case QVariant::Double: if ( fieldSize <= 0 || fieldPrec <= 0 ) { - fieldType = "REAL"; + fieldType = QStringLiteral( "REAL" ); fieldSize = -1; fieldPrec = -1; } else { - fieldType = "NUMERIC"; + fieldType = QStringLiteral( "NUMERIC" ); } break; @@ -159,13 +159,13 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, { // if no pk name was passed, define the new pk field name int index = 0; - QString pk = primaryKey = "pk"; + QString pk = primaryKey = QStringLiteral( "pk" ); for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) { if ( fields.at( fldIdx ).name() == primaryKey ) { // it already exists, try again with a new name - primaryKey = QString( "%1_%2" ).arg( pk ).arg( index++ ); + primaryKey = QStringLiteral( "%1_%2" ).arg( pk ).arg( index++ ); fldIdx = -1; // it is incremented in the for loop, i.e. restarts at 0 } } @@ -191,15 +191,15 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, // as it's autoincremental if ( primaryKeyType.isEmpty() ) { - primaryKeyType = "INTEGER"; + primaryKeyType = QStringLiteral( "INTEGER" ); } else { // if the pk field's type is bigint, use the autoincremental // integer type instead - if ( primaryKeyType == "BIGINT" ) + if ( primaryKeyType == QLatin1String( "BIGINT" ) ) { - primaryKeyType = "INTEGER"; + primaryKeyType = QStringLiteral( "INTEGER" ); } } @@ -214,14 +214,14 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, if ( overwrite ) { // delete the table if exists and the related entry in geometry_columns, then re-create it - sql = QString( "DROP TABLE IF EXISTS %1" ) + sql = QStringLiteral( "DROP TABLE IF EXISTS %1" ) .arg( quotedIdentifier( tableName ) ); ret = sqlite3_exec( sqliteHandle, sql.toUtf8().constData(), nullptr, nullptr, &errMsg ); if ( ret != SQLITE_OK ) throw SLException( errMsg ); - sql = QString( "DELETE FROM geometry_columns WHERE upper(f_table_name) = upper(%1)" ) + sql = QStringLiteral( "DELETE FROM geometry_columns WHERE upper(f_table_name) = upper(%1)" ) .arg( quotedValue( tableName ) ); ret = sqlite3_exec( sqliteHandle, sql.toUtf8().constData(), nullptr, nullptr, &errMsg ); @@ -229,7 +229,7 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, throw SLException( errMsg ); } - sql = QString( "CREATE TABLE %1 (%2 %3 PRIMARY KEY)" ) + sql = QStringLiteral( "CREATE TABLE %1 (%2 %3 PRIMARY KEY)" ) .arg( quotedIdentifier( tableName ), quotedIdentifier( primaryKey ), primaryKeyType ); @@ -248,46 +248,46 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, dim = 3; FALLTHROUGH; case QgsWkbTypes::Point: - geometryType = "POINT"; + geometryType = QStringLiteral( "POINT" ); break; case QgsWkbTypes::LineString25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::LineString: - geometryType = "LINESTRING"; + geometryType = QStringLiteral( "LINESTRING" ); break; case QgsWkbTypes::Polygon25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::Polygon: - geometryType = "POLYGON"; + geometryType = QStringLiteral( "POLYGON" ); break; case QgsWkbTypes::MultiPoint25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::MultiPoint: - geometryType = "MULTIPOINT"; + geometryType = QStringLiteral( "MULTIPOINT" ); break; case QgsWkbTypes::MultiLineString25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::MultiLineString: - geometryType = "MULTILINESTRING"; + geometryType = QStringLiteral( "MULTILINESTRING" ); break; case QgsWkbTypes::MultiPolygon25D: dim = 3; FALLTHROUGH; case QgsWkbTypes::MultiPolygon: - geometryType = "MULTIPOLYGON"; + geometryType = QStringLiteral( "MULTIPOLYGON" ); break; case QgsWkbTypes::Unknown: - geometryType = "GEOMETRY"; + geometryType = QStringLiteral( "GEOMETRY" ); break; case QgsWkbTypes::NoGeometry: @@ -299,7 +299,7 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, // create geometry column if ( !geometryType.isEmpty() ) { - sql = QString( "SELECT AddGeometryColumn(%1, %2, %3, %4, %5)" ) + sql = QStringLiteral( "SELECT AddGeometryColumn(%1, %2, %3, %4, %5)" ) .arg( QgsSpatiaLiteProvider::quotedValue( tableName ), QgsSpatiaLiteProvider::quotedValue( geometryColumn ) ) .arg( srid ) @@ -348,7 +348,7 @@ QgsSpatiaLiteProvider::createEmptyLayer( const QString& uri, } // use the provider to edit the table - dsUri.setDataSource( "", tableName, geometryColumn, QString(), primaryKey ); + dsUri.setDataSource( QLatin1String( "" ), tableName, geometryColumn, QString(), primaryKey ); QgsSpatiaLiteProvider *provider = new QgsSpatiaLiteProvider( dsUri.uri() ); if ( !provider->isValid() ) { @@ -467,7 +467,7 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ) mSqliteHandle = mHandle->handle(); if ( mSqliteHandle ) { - QStringList pragmaList = anUri.params( "pragma" ); + QStringList pragmaList = anUri.params( QStringLiteral( "pragma" ) ); Q_FOREACH ( const QString& pragma, pragmaList ) { char* errMsg = nullptr; @@ -597,7 +597,7 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ) if ( mTableBased && hasRowid() ) { - mPrimaryKey = "ROWID"; + mPrimaryKey = QStringLiteral( "ROWID" ); } // retrieve version information @@ -605,10 +605,10 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ) //fill type names into sets setNativeTypes( QList<NativeType>() - << QgsVectorDataProvider::NativeType( tr( "Binary object (BLOB)" ), "BLOB", QVariant::ByteArray ) - << QgsVectorDataProvider::NativeType( tr( "Text" ), "TEXT", QVariant::String ) - << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), "FLOAT", QVariant::Double ) - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), "INTEGER", QVariant::LongLong ) + << QgsVectorDataProvider::NativeType( tr( "Binary object (BLOB)" ), QStringLiteral( "BLOB" ), QVariant::ByteArray ) + << QgsVectorDataProvider::NativeType( tr( "Text" ), QStringLiteral( "TEXT" ), QVariant::String ) + << QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "FLOAT" ), QVariant::Double ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "INTEGER" ), QVariant::LongLong ) << QgsVectorDataProvider::NativeType( tr( "Array of text" ), SPATIALITE_ARRAY_PREFIX.toUpper() + "TEXT" + SPATIALITE_ARRAY_SUFFIX.toUpper(), QVariant::StringList, 0, 0, 0, 0, QVariant::String ) << QgsVectorDataProvider::NativeType( tr( "Array of decimal numbers (double)" ), SPATIALITE_ARRAY_PREFIX.toUpper() + "REAL" + SPATIALITE_ARRAY_SUFFIX.toUpper(), QVariant::List, 0, 0, 0, 0, QVariant::Double ) @@ -645,18 +645,18 @@ typedef QPair<QVariant::Type, QVariant::Type> TypeSubType; static TypeSubType getVariantType( const QString& type ) { // making some assumptions in order to guess a more realistic type - if ( type == "int" || - type == "integer" || - type == "integer64" || - type == "bigint" || - type == "smallint" || - type == "tinyint" || - type == "boolean" ) + if ( type == QLatin1String( "int" ) || + type == QLatin1String( "integer" ) || + type == QLatin1String( "integer64" ) || + type == QLatin1String( "bigint" ) || + type == QLatin1String( "smallint" ) || + type == QLatin1String( "tinyint" ) || + type == QLatin1String( "boolean" ) ) return TypeSubType( QVariant::LongLong, QVariant::Invalid ); - else if ( type == "real" || - type == "double" || - type == "double precision" || - type == "float" ) + else if ( type == QLatin1String( "real" ) || + type == QLatin1String( "double" ) || + type == QLatin1String( "double precision" ) || + type == QLatin1String( "float" ) ) return TypeSubType( QVariant::Double, QVariant::Invalid ); else if ( type.startsWith( SPATIALITE_ARRAY_PREFIX ) && type.endsWith( SPATIALITE_ARRAY_SUFFIX ) ) { @@ -711,12 +711,12 @@ void QgsSpatiaLiteProvider::loadFieldsAbstractInterface( gaiaVectorLayerPtr lyr fieldType = QVariant::Double; type = "DOUBLE"; } - mAttributeFields.append( QgsField( name, fieldType, type, 0, 0, "" ) ); + mAttributeFields.append( QgsField( name, fieldType, type, 0, 0, QLatin1String( "" ) ) ); } fld = fld->Next; } - QString sql = QString( "PRAGMA table_info(%1)" ).arg( quotedIdentifier( mTableName ) ); + QString sql = QStringLiteral( "PRAGMA table_info(%1)" ).arg( quotedIdentifier( mTableName ) ); char **results; int rows; @@ -781,7 +781,7 @@ QString QgsSpatiaLiteProvider::spatialiteVersion() char *errMsg = nullptr; QString sql; - sql = "SELECT spatialite_version()"; + sql = QStringLiteral( "SELECT spatialite_version()" ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8(), &results, &rows, &columns, &errMsg ); if ( ret != SQLITE_OK || rows != 1 ) { @@ -831,7 +831,7 @@ void QgsSpatiaLiteProvider::loadFields() mPrimaryKey.clear(); mPrimaryKeyAttrs.clear(); - sql = QString( "PRAGMA table_info(%1)" ).arg( quotedIdentifier( mTableName ) ); + sql = QStringLiteral( "PRAGMA table_info(%1)" ).arg( quotedIdentifier( mTableName ) ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); if ( ret != SQLITE_OK ) @@ -876,7 +876,7 @@ void QgsSpatiaLiteProvider::loadFields() } else { - sql = QString( "select * from %1 limit 1" ).arg( mQuery ); + sql = QStringLiteral( "select * from %1 limit 1" ).arg( mQuery ); if ( sqlite3_prepare_v2( mSqliteHandle, sql.toUtf8().constData(), -1, &stmt, nullptr ) != SQLITE_OK ) { @@ -902,7 +902,7 @@ void QgsSpatiaLiteProvider::loadFields() QString name = QString::fromUtf8( sqlite3_column_name( stmt, i ) ); QString type = QString::fromUtf8( sqlite3_column_decltype( stmt, i ) ).toLower(); if ( type.isEmpty() ) - type = "text"; + type = QStringLiteral( "text" ); if ( name == mPrimaryKey ) { @@ -980,7 +980,7 @@ bool QgsSpatiaLiteProvider::hasTriggers() char *errMsg = nullptr; QString sql; - sql = QString( "SELECT * FROM sqlite_master WHERE type='trigger' AND tbl_name=%1" ) + sql = QStringLiteral( "SELECT * FROM sqlite_master WHERE type='trigger' AND tbl_name=%1" ) .arg( quotedIdentifier( mTableName ) ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); @@ -990,11 +990,11 @@ bool QgsSpatiaLiteProvider::hasTriggers() bool QgsSpatiaLiteProvider::hasRowid() { - if ( mAttributeFields.lookupField( "ROWID" ) >= 0 ) + if ( mAttributeFields.lookupField( QStringLiteral( "ROWID" ) ) >= 0 ) return false; // table without rowid column - QString sql = QString( "SELECT rowid FROM %1 WHERE 0" ).arg( quotedIdentifier( mTableName ) ); + QString sql = QStringLiteral( "SELECT rowid FROM %1 WHERE 0" ).arg( quotedIdentifier( mTableName ) ); char *errMsg = nullptr; return sqlite3_exec( mSqliteHandle, sql.toUtf8(), nullptr, nullptr, &errMsg ) == SQLITE_OK; } @@ -1002,7 +1002,7 @@ bool QgsSpatiaLiteProvider::hasRowid() QString QgsSpatiaLiteProvider::storageType() const { - return "SQLite database with SpatiaLite extension"; + return QStringLiteral( "SQLite database with SpatiaLite extension" ); } QgsFeatureIterator QgsSpatiaLiteProvider::getFeatures( const QgsFeatureRequest& request ) const @@ -3364,7 +3364,7 @@ QgsCoordinateReferenceSystem QgsSpatiaLiteProvider::crs() const // familiar with the code (should also give a more descriptive name to the generated CRS) if ( srs.srsid() == 0 ) { - QString myName = QString( " * %1 (%2)" ) + QString myName = QStringLiteral( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), srs.toProj4() ); srs.saveAsUserCrs( myName ); @@ -3414,7 +3414,7 @@ QVariant QgsSpatiaLiteProvider::minimumValue( int index ) const // get the field name QgsField fld = field( index ); - sql = QString( "SELECT Min(%1) FROM %2" ).arg( quotedIdentifier( fld.name() ), mQuery ); + sql = QStringLiteral( "SELECT Min(%1) FROM %2" ).arg( quotedIdentifier( fld.name() ), mQuery ); if ( !mSubsetString.isEmpty() ) { @@ -3477,7 +3477,7 @@ QVariant QgsSpatiaLiteProvider::maximumValue( int index ) const // get the field name QgsField fld = field( index ); - sql = QString( "SELECT Max(%1) FROM %2" ).arg( quotedIdentifier( fld.name() ), mQuery ); + sql = QStringLiteral( "SELECT Max(%1) FROM %2" ).arg( quotedIdentifier( fld.name() ), mQuery ); if ( !mSubsetString.isEmpty() ) { @@ -3539,18 +3539,18 @@ void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueV } QgsField fld = mAttributeFields.at( index ); - sql = QString( "SELECT DISTINCT %1 FROM %2" ).arg( quotedIdentifier( fld.name() ), mQuery ); + sql = QStringLiteral( "SELECT DISTINCT %1 FROM %2" ).arg( quotedIdentifier( fld.name() ), mQuery ); if ( !mSubsetString.isEmpty() ) { sql += " WHERE ( " + mSubsetString + ')'; } - sql += QString( " ORDER BY %1" ).arg( quotedIdentifier( fld.name() ) ); + sql += QStringLiteral( " ORDER BY %1" ).arg( quotedIdentifier( fld.name() ) ); if ( limit >= 0 ) { - sql += QString( " LIMIT %1" ).arg( limit ); + sql += QStringLiteral( " LIMIT %1" ).arg( limit ); } // SQLite prepared statement @@ -3616,10 +3616,10 @@ QString QgsSpatiaLiteProvider::geomParam() const if ( forceMulti && hasMultiFunction ) { - geometry += "ST_Multi("; + geometry += QLatin1String( "ST_Multi(" ); } - geometry += QString( "GeomFromWKB(?, %2)" ).arg( mSrid ); + geometry += QStringLiteral( "GeomFromWKB(?, %2)" ).arg( mSrid ); if ( forceMulti && hasMultiFunction ) { @@ -3653,9 +3653,9 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist ) { toCommit = true; - sql = QString( "INSERT INTO %1(" ).arg( quotedIdentifier( mTableName ) ); - values = QString( ") VALUES (" ); - separator = ""; + sql = QStringLiteral( "INSERT INTO %1(" ).arg( quotedIdentifier( mTableName ) ); + values = QStringLiteral( ") VALUES (" ); + separator = QLatin1String( "" ); if ( !mGeometryColumn.isEmpty() ) { @@ -3836,7 +3836,7 @@ bool QgsSpatiaLiteProvider::deleteFeatures( const QgsFeatureIds &id ) } toCommit = true; - sql = QString( "DELETE FROM %1 WHERE %2=?" ).arg( quotedIdentifier( mTableName ), quotedIdentifier( mPrimaryKey ) ); + sql = QStringLiteral( "DELETE FROM %1 WHERE %2=?" ).arg( quotedIdentifier( mTableName ), quotedIdentifier( mPrimaryKey ) ); // SQLite prepared statement if ( sqlite3_prepare_v2( mSqliteHandle, sql.toUtf8().constData(), -1, &stmt, nullptr ) != SQLITE_OK ) @@ -3917,7 +3917,7 @@ bool QgsSpatiaLiteProvider::addAttributes( const QList<QgsField> &attributes ) for ( QList<QgsField>::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter ) { - sql = QString( "ALTER TABLE \"%1\" ADD COLUMN \"%2\" %3" ) + sql = QStringLiteral( "ALTER TABLE \"%1\" ADD COLUMN \"%2\" %3" ) .arg( mTableName, iter->name(), iter->typeName() ); @@ -3936,7 +3936,7 @@ bool QgsSpatiaLiteProvider::addAttributes( const QList<QgsField> &attributes ) goto abort; } #ifdef SPATIALITE_VERSION_GE_4_0_0 - sql = QString( "UPDATE geometry_columns_statistics set last_verified = 0 WHERE f_table_name=\"%1\" AND f_geometry_column=\"%2\";" ) + sql = QStringLiteral( "UPDATE geometry_columns_statistics set last_verified = 0 WHERE f_table_name=\"%1\" AND f_geometry_column=\"%2\";" ) .arg( mTableName, mGeometryColumn ); ret = sqlite3_exec( mSqliteHandle, sql.toUtf8().constData(), nullptr, nullptr, &errMsg ); @@ -3998,7 +3998,7 @@ bool QgsSpatiaLiteProvider::changeAttributeValues( const QgsChangedAttributesMap if ( attrs.isEmpty() ) continue; - QString sql = QString( "UPDATE %1 SET " ).arg( quotedIdentifier( mTableName ) ); + QString sql = QStringLiteral( "UPDATE %1 SET " ).arg( quotedIdentifier( mTableName ) ); bool first = true; // cycle through the changed attributes of the feature @@ -4020,22 +4020,22 @@ bool QgsSpatiaLiteProvider::changeAttributeValues( const QgsChangedAttributesMap if ( val.isNull() || !val.isValid() ) { // binding a NULL value - sql += QString( "%1=NULL" ).arg( quotedIdentifier( fld.name() ) ); + sql += QStringLiteral( "%1=NULL" ).arg( quotedIdentifier( fld.name() ) ); } else if ( type == QVariant::Int || type == QVariant::LongLong || type == QVariant::Double ) { // binding a NUMERIC value - sql += QString( "%1=%2" ).arg( quotedIdentifier( fld.name() ) , val.toString() ); + sql += QStringLiteral( "%1=%2" ).arg( quotedIdentifier( fld.name() ) , val.toString() ); } else if ( type == QVariant::StringList || type == QVariant::List ) { // binding an array value - sql += QString( "%1=%2" ).arg( quotedIdentifier( fld.name() ), quotedValue( QgsJSONUtils::encodeValue( val ) ) ); + sql += QStringLiteral( "%1=%2" ).arg( quotedIdentifier( fld.name() ), quotedValue( QgsJSONUtils::encodeValue( val ) ) ); } else { // binding a TEXT value - sql += QString( "%1=%2" ).arg( quotedIdentifier( fld.name() ), quotedValue( val.toString() ) ); + sql += QStringLiteral( "%1=%2" ).arg( quotedIdentifier( fld.name() ), quotedValue( val.toString() ) ); } } catch ( SLFieldNotFound ) @@ -4043,7 +4043,7 @@ bool QgsSpatiaLiteProvider::changeAttributeValues( const QgsChangedAttributesMap // Field was missing - shouldn't happen } } - sql += QString( " WHERE %1=%2" ).arg( quotedIdentifier( mPrimaryKey ) ).arg( fid ); + sql += QStringLiteral( " WHERE %1=%2" ).arg( quotedIdentifier( mPrimaryKey ) ).arg( fid ); ret = sqlite3_exec( mSqliteHandle, sql.toUtf8().constData(), nullptr, nullptr, &errMsg ); if ( ret != SQLITE_OK ) @@ -4094,7 +4094,7 @@ bool QgsSpatiaLiteProvider::changeGeometryValues( const QgsGeometryMap &geometry toCommit = true; sql = - QString( "UPDATE %1 SET %2=GeomFromWKB(?, %3) WHERE %4=?" ) + QStringLiteral( "UPDATE %1 SET %2=GeomFromWKB(?, %3) WHERE %4=?" ) .arg( quotedIdentifier( mTableName ), quotedIdentifier( mGeometryColumn ) ) .arg( mSrid ) @@ -4180,16 +4180,16 @@ void QgsSpatiaLiteProvider::closeDb() QString QgsSpatiaLiteProvider::quotedIdentifier( QString id ) { - id.replace( '\"', "\"\"" ); + id.replace( '\"', QLatin1String( "\"\"" ) ); return id.prepend( '\"' ).append( '\"' ); } QString QgsSpatiaLiteProvider::quotedValue( QString value ) { if ( value.isNull() ) - return "NULL"; + return QStringLiteral( "NULL" ); - value.replace( '\'', "''" ); + value.replace( '\'', QLatin1String( "''" ) ); return value.prepend( '\'' ).append( '\'' ); } @@ -4266,12 +4266,12 @@ bool QgsSpatiaLiteProvider::checkLayerType() if ( ret == SQLITE_OK && rows == 1 ) { QString type = QString( results[ columns + 0 ] ); - if ( type == "table" ) + if ( type == QLatin1String( "table" ) ) { mTableBased = true; mReadOnly = false; } - else if ( type == "view" ) + else if ( type == QLatin1String( "view" ) ) { mViewBased = true; mReadOnly = !hasTriggers(); @@ -4296,19 +4296,19 @@ bool QgsSpatiaLiteProvider::checkLayerType() QRegExp regex; do { - alias = QString( "subQuery_%1" ).arg( QString::number( index++ ) ); - QString pattern = QString( "(\\\"?)%1\\1" ).arg( QRegExp::escape( alias ) ); + alias = QStringLiteral( "subQuery_%1" ).arg( QString::number( index++ ) ); + QString pattern = QStringLiteral( "(\\\"?)%1\\1" ).arg( QRegExp::escape( alias ) ); regex.setPattern( pattern ); regex.setCaseSensitivity( Qt::CaseInsensitive ); } while ( mQuery.contains( regex ) ); // convert the custom query into a subquery - mQuery = QString( "%1 as %2" ) + mQuery = QStringLiteral( "%1 as %2" ) .arg( mQuery, quotedIdentifier( alias ) ); - sql = QString( "SELECT 0 FROM %1 LIMIT 1" ).arg( mQuery ); + sql = QStringLiteral( "SELECT 0 FROM %1 LIMIT 1" ).arg( mQuery ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); if ( ret == SQLITE_OK && rows == 1 ) { @@ -4340,7 +4340,7 @@ bool QgsSpatiaLiteProvider::checkLayerType() if ( errMsg && strcmp( errMsg, "no such table: geometry_columns_auth" ) == 0 ) { sqlite3_free( errMsg ); - sql = QString( "SELECT 0 FROM geometry_columns WHERE upper(f_table_name) = upper(%1) and upper(f_geometry_column) = upper(%2)" ) + sql = QStringLiteral( "SELECT 0 FROM geometry_columns WHERE upper(f_table_name) = upper(%1) and upper(f_geometry_column) = upper(%2)" ) .arg( quotedValue( mTableName ), quotedValue( mGeometryColumn ) ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); @@ -4579,27 +4579,27 @@ bool QgsSpatiaLiteProvider::getTableGeometryDetails() QString spatialIndex = results[( i * columns ) + 2]; QString dims = results[( i * columns ) + 3]; - if ( fType == "POINT" ) + if ( fType == QLatin1String( "POINT" ) ) { mGeomType = QgsWkbTypes::Point; } - else if ( fType == "MULTIPOINT" ) + else if ( fType == QLatin1String( "MULTIPOINT" ) ) { mGeomType = QgsWkbTypes::MultiPoint; } - else if ( fType == "LINESTRING" ) + else if ( fType == QLatin1String( "LINESTRING" ) ) { mGeomType = QgsWkbTypes::LineString; } - else if ( fType == "MULTILINESTRING" ) + else if ( fType == QLatin1String( "MULTILINESTRING" ) ) { mGeomType = QgsWkbTypes::MultiLineString; } - else if ( fType == "POLYGON" ) + else if ( fType == QLatin1String( "POLYGON" ) ) { mGeomType = QgsWkbTypes::Polygon; } - else if ( fType == "MULTIPOLYGON" ) + else if ( fType == QLatin1String( "MULTIPOLYGON" ) ) { mGeomType = QgsWkbTypes::MultiPolygon; } @@ -4612,19 +4612,19 @@ bool QgsSpatiaLiteProvider::getTableGeometryDetails() { mSpatialIndexMbrCache = true; } - if ( dims == "XY" || dims == "2" ) + if ( dims == QLatin1String( "XY" ) || dims == QLatin1String( "2" ) ) { nDims = GAIA_XY; } - else if ( dims == "XYZ" || dims == "3" ) + else if ( dims == QLatin1String( "XYZ" ) || dims == QLatin1String( "3" ) ) { nDims = GAIA_XY_Z; } - else if ( dims == "XYM" ) + else if ( dims == QLatin1String( "XYM" ) ) { nDims = GAIA_XY_M; } - else if ( dims == "XYZM" ) + else if ( dims == QLatin1String( "XYZM" ) ) { nDims = GAIA_XY_Z_M; } @@ -4678,27 +4678,27 @@ bool QgsSpatiaLiteProvider::getViewGeometryDetails() mIndexTable = results[( i * columns ) + 3]; mIndexGeometry = results[( i * columns ) + 4]; - if ( fType == "POINT" ) + if ( fType == QLatin1String( "POINT" ) ) { mGeomType = QgsWkbTypes::Point; } - else if ( fType == "MULTIPOINT" ) + else if ( fType == QLatin1String( "MULTIPOINT" ) ) { mGeomType = QgsWkbTypes::MultiPoint; } - else if ( fType == "LINESTRING" ) + else if ( fType == QLatin1String( "LINESTRING" ) ) { mGeomType = QgsWkbTypes::LineString; } - else if ( fType == "MULTILINESTRING" ) + else if ( fType == QLatin1String( "MULTILINESTRING" ) ) { mGeomType = QgsWkbTypes::MultiLineString; } - else if ( fType == "POLYGON" ) + else if ( fType == QLatin1String( "POLYGON" ) ) { mGeomType = QgsWkbTypes::Polygon; } - else if ( fType == "MULTIPOLYGON" ) + else if ( fType == QLatin1String( "MULTIPOLYGON" ) ) { mGeomType = QgsWkbTypes::MultiPolygon; } @@ -4756,27 +4756,27 @@ bool QgsSpatiaLiteProvider::getVShapeGeometryDetails() QString fType = results[( i * columns ) + 0]; QString xSrid = results[( i * columns ) + 1]; - if ( fType == "POINT" ) + if ( fType == QLatin1String( "POINT" ) ) { mGeomType = QgsWkbTypes::Point; } - else if ( fType == "MULTIPOINT" ) + else if ( fType == QLatin1String( "MULTIPOINT" ) ) { mGeomType = QgsWkbTypes::MultiPoint; } - else if ( fType == "LINESTRING" ) + else if ( fType == QLatin1String( "LINESTRING" ) ) { mGeomType = QgsWkbTypes::LineString; } - else if ( fType == "MULTILINESTRING" ) + else if ( fType == QLatin1String( "MULTILINESTRING" ) ) { mGeomType = QgsWkbTypes::MultiLineString; } - else if ( fType == "POLYGON" ) + else if ( fType == QLatin1String( "POLYGON" ) ) { mGeomType = QgsWkbTypes::Polygon; } - else if ( fType == "MULTIPOLYGON" ) + else if ( fType == QLatin1String( "MULTIPOLYGON" ) ) { mGeomType = QgsWkbTypes::MultiPolygon; } @@ -4810,12 +4810,12 @@ bool QgsSpatiaLiteProvider::getQueryGeometryDetails() int columns; char *errMsg = nullptr; - QString fType( "" ); - QString xSrid( "" ); + QString fType( QLatin1String( "" ) ); + QString xSrid( QLatin1String( "" ) ); // get stuff from the relevant column instead. This may (will?) // fail if there is no data in the relevant table. - QString sql = QString( "select srid(%1), geometrytype(%1) from %2" ) + QString sql = QStringLiteral( "select srid(%1), geometrytype(%1) from %2" ) .arg( quotedIdentifier( mGeometryColumn ), mQuery ); @@ -4825,7 +4825,7 @@ bool QgsSpatiaLiteProvider::getQueryGeometryDetails() sql += " WHERE " + mSubsetString; } - sql += " limit 1"; + sql += QLatin1String( " limit 1" ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); if ( ret != SQLITE_OK ) @@ -4844,7 +4844,7 @@ bool QgsSpatiaLiteProvider::getQueryGeometryDetails() if ( !xSrid.isEmpty() && !fType.isEmpty() ) { - if ( fType == "GEOMETRY" ) + if ( fType == QLatin1String( "GEOMETRY" ) ) { // check to see if there is a unique geometry type sql = QString( "select distinct " @@ -4875,27 +4875,27 @@ bool QgsSpatiaLiteProvider::getQueryGeometryDetails() sqlite3_free_table( results ); } - if ( fType == "POINT" ) + if ( fType == QLatin1String( "POINT" ) ) { mGeomType = QgsWkbTypes::Point; } - else if ( fType == "MULTIPOINT" ) + else if ( fType == QLatin1String( "MULTIPOINT" ) ) { mGeomType = QgsWkbTypes::MultiPoint; } - else if ( fType == "LINESTRING" ) + else if ( fType == QLatin1String( "LINESTRING" ) ) { mGeomType = QgsWkbTypes::LineString; } - else if ( fType == "MULTILINESTRING" ) + else if ( fType == QLatin1String( "MULTILINESTRING" ) ) { mGeomType = QgsWkbTypes::MultiLineString; } - else if ( fType == "POLYGON" ) + else if ( fType == QLatin1String( "POLYGON" ) ) { mGeomType = QgsWkbTypes::Polygon; } - else if ( fType == "MULTIPOLYGON" ) + else if ( fType == QLatin1String( "MULTIPOLYGON" ) ) { mGeomType = QgsWkbTypes::MultiPolygon; } @@ -4926,7 +4926,7 @@ bool QgsSpatiaLiteProvider::getSridDetails() int columns; char *errMsg = nullptr; - QString sql = QString( "SELECT auth_name||':'||auth_srid,proj4text FROM spatial_ref_sys WHERE srid=%1" ).arg( mSrid ); + QString sql = QStringLiteral( "SELECT auth_name||':'||auth_srid,proj4text FROM spatial_ref_sys WHERE srid=%1" ).arg( mSrid ); ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); if ( ret != SQLITE_OK ) @@ -4987,8 +4987,8 @@ bool QgsSpatiaLiteProvider::getTableSummary() int columns; char *errMsg = nullptr; - QString sql = QString( "SELECT Count(*)%1 FROM %2" ) - .arg( mGeometryColumn.isEmpty() ? "" : QString( ",Min(MbrMinX(%1)),Min(MbrMinY(%1)),Max(MbrMaxX(%1)),Max(MbrMaxY(%1))" ).arg( quotedIdentifier( mGeometryColumn ) ), + QString sql = QStringLiteral( "SELECT Count(*)%1 FROM %2" ) + .arg( mGeometryColumn.isEmpty() ? QLatin1String( "" ) : QStringLiteral( ",Min(MbrMinX(%1)),Min(MbrMinY(%1)),Max(MbrMaxX(%1)),Max(MbrMaxY(%1))" ).arg( quotedIdentifier( mGeometryColumn ) ), mQuery ); if ( !mSubsetString.isEmpty() ) @@ -5283,7 +5283,7 @@ QList<QgsVectorLayer*> QgsSpatiaLiteProvider::searchLayers( const QList<QgsVecto QList<QgsRelation> QgsSpatiaLiteProvider::discoverRelations( const QgsVectorLayer* self, const QList<QgsVectorLayer*>& layers ) const { QList<QgsRelation> output; - const QString sql = QString( "PRAGMA foreign_key_list(%1)" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mTableName ) ); + const QString sql = QStringLiteral( "PRAGMA foreign_key_list(%1)" ).arg( QgsSpatiaLiteProvider::quotedIdentifier( mTableName ) ); char **results; int rows; int columns; @@ -5299,7 +5299,7 @@ QList<QgsRelation> QgsSpatiaLiteProvider::discoverRelations( const QgsVectorLaye const QString refTable = QString::fromUtf8( results[row * columns + 2] ); const QString fkColumn = QString::fromUtf8( results[row * columns + 3] ); const QString refColumn = QString::fromUtf8( results[row * columns + 4] ); - if ( position == "0" ) + if ( position == QLatin1String( "0" ) ) { // first reference field => try to find if we have layers for the referenced table const QList<QgsVectorLayer*> foundLayers = searchLayers( layers, mSqlitePath, refTable ); Q_FOREACH ( const QgsVectorLayer* foundLayer, foundLayers ) @@ -5333,7 +5333,7 @@ QList<QgsRelation> QgsSpatiaLiteProvider::discoverRelations( const QgsVectorLaye } else { - QgsLogger::warning( QString( "SQLite error discovering relations: %1" ).arg( errMsg ) ); + QgsLogger::warning( QStringLiteral( "SQLite error discovering relations: %1" ).arg( errMsg ) ); sqlite3_free( errMsg ); } return output; @@ -5361,7 +5361,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS sqlite3 *sqliteHandle = handle->handle(); // check if layer_styles table already exist - QString countIfExist = QString( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='%1';" ).arg( "layer_styles" ); + QString countIfExist = QStringLiteral( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='%1';" ).arg( QStringLiteral( "layer_styles" ) ); char **results; int rows; @@ -5416,8 +5416,8 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS QString uiFileValue; if ( !uiFileContent.isEmpty() ) { - uiFileColumn = ",ui"; - uiFileValue = QString( ",%1" ).arg( QgsSpatiaLiteProvider::quotedValue( uiFileContent ) ); + uiFileColumn = QStringLiteral( ",ui" ); + uiFileValue = QStringLiteral( ",%1" ).arg( QgsSpatiaLiteProvider::quotedValue( uiFileContent ) ); } QString sql = QString( "INSERT INTO layer_styles(" @@ -5502,7 +5502,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS .arg( QgsSpatiaLiteProvider::quotedValue( dsUri.schema() ) ) .arg( QgsSpatiaLiteProvider::quotedValue( dsUri.table() ) ) .arg( QgsSpatiaLiteProvider::quotedValue( dsUri.geometryColumn() ) ); - sql = QString( "BEGIN; %1; %2; COMMIT;" ).arg( removeDefaultSql, sql ); + sql = QStringLiteral( "BEGIN; %1; %2; COMMIT;" ).arg( removeDefaultSql, sql ); } ret = sqlite3_exec( sqliteHandle, sql.toUtf8().constData(), nullptr, nullptr, &errMsg ); @@ -5534,7 +5534,7 @@ QGISEXTERN QString loadStyle( const QString& uri, QString& errCause ) { QgsDebugMsg( "Connection to database failed. Save style aborted." ); errCause = QObject::tr( "Connection to database failed" ); - return ""; + return QLatin1String( "" ); } sqlite3 *sqliteHandle = handle->handle(); @@ -5560,10 +5560,10 @@ QGISEXTERN QString loadStyle( const QString& uri, QString& errCause ) QgsSqliteHandle::closeDb( handle ); QgsMessageLog::logMessage( QObject::tr( "Error executing query: %1" ).arg( selectQmlQuery ) ); errCause = QObject::tr( "Error executing loading style. The query was logged" ); - return ""; + return QLatin1String( "" ); } - QString style = ( rows == 1 ) ? QString::fromUtf8( results[( rows * columns ) + 0 ] ) : ""; + QString style = ( rows == 1 ) ? QString::fromUtf8( results[( rows * columns ) + 0 ] ) : QLatin1String( "" ); sqlite3_free_table( results ); QgsSqliteHandle::closeDb( handle ); @@ -5589,7 +5589,7 @@ QGISEXTERN int listStyles( const QString &uri, QStringList &ids, QStringList &na sqlite3 *sqliteHandle = handle->handle(); // check if layer_styles table already exist - QString countIfExist = QString( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='%1';" ).arg( "layer_styles" ); + QString countIfExist = QStringLiteral( "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='%1';" ).arg( QStringLiteral( "layer_styles" ) ); char **results; int rows; @@ -5688,13 +5688,13 @@ QGISEXTERN QString getStyleById( const QString& uri, QString styleId, QString& e { QgsDebugMsg( "Connection to database failed. Save style aborted." ); errCause = QObject::tr( "Connection to database failed" ); - return ""; + return QLatin1String( "" ); } sqlite3 *sqliteHandle = handle->handle(); QString style; - QString selectQmlQuery = QString( "SELECT styleQml FROM layer_styles WHERE id=%1" ).arg( QgsSpatiaLiteProvider::quotedValue( styleId ) ); + QString selectQmlQuery = QStringLiteral( "SELECT styleQml FROM layer_styles WHERE id=%1" ).arg( QgsSpatiaLiteProvider::quotedValue( styleId ) ); char **results; int rows; int columns; @@ -5705,7 +5705,7 @@ QGISEXTERN QString getStyleById( const QString& uri, QString styleId, QString& e if ( 1 == rows ) style = QString::fromUtf8( results[( rows * columns ) + 0 ] ); else - errCause = QObject::tr( "Consistency error in table '%1'. Style id should be unique" ).arg( "layer_styles" ); + errCause = QObject::tr( "Consistency error in table '%1'. Style id should be unique" ).arg( QStringLiteral( "layer_styles" ) ); } else { diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 72b8725d611d..b59f01ced0fa 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -71,7 +71,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset */ - explicit QgsSpatiaLiteProvider( QString const &uri = "" ); + explicit QgsSpatiaLiteProvider( QString const &uri = QLatin1String( "" ) ); //! Destructor virtual ~ QgsSpatiaLiteProvider(); @@ -239,7 +239,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider QString errorMessage() const { - return errMsg ? QString::fromUtf8( errMsg ) : "unknown cause"; + return errMsg ? QString::fromUtf8( errMsg ) : QStringLiteral( "unknown cause" ); } private: diff --git a/src/providers/spatialite/qgsspatialitesourceselect.cpp b/src/providers/spatialite/qgsspatialitesourceselect.cpp index 6a93cfef9e7f..5f80ed6f51e8 100644 --- a/src/providers/spatialite/qgsspatialitesourceselect.cpp +++ b/src/providers/spatialite/qgsspatialitesourceselect.cpp @@ -45,8 +45,8 @@ QgsSpatiaLiteSourceSelect::QgsSpatiaLiteSourceSelect( QWidget * parent, Qt::Wind setupUi( this ); QSettings settings; - restoreGeometry( settings.value( "/Windows/SpatiaLiteSourceSelect/geometry" ).toByteArray() ); - mHoldDialogOpen->setChecked( settings.value( "/Windows/SpatiaLiteSourceSelect/HoldDialogOpen", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/SpatiaLiteSourceSelect/geometry" ) ).toByteArray() ); + mHoldDialogOpen->setChecked( settings.value( QStringLiteral( "/Windows/SpatiaLiteSourceSelect/HoldDialogOpen" ), false ).toBool() ); setWindowTitle( tr( "Add SpatiaLite Layer(s)" ) ); btnEdit->hide(); // hide the edit button @@ -117,8 +117,8 @@ QgsSpatiaLiteSourceSelect::QgsSpatiaLiteSourceSelect( QWidget * parent, Qt::Wind QgsSpatiaLiteSourceSelect::~QgsSpatiaLiteSourceSelect() { QSettings settings; - settings.setValue( "/Windows/SpatiaLiteSourceSelect/geometry", saveGeometry() ); - settings.setValue( "/Windows/SpatiaLiteSourceSelect/HoldDialogOpen", mHoldDialogOpen->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/SpatiaLiteSourceSelect/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/SpatiaLiteSourceSelect/HoldDialogOpen" ), mHoldDialogOpen->isChecked() ); } // Slot for performing action when the Add button is clicked @@ -189,7 +189,7 @@ void QgsSpatiaLiteSourceSelect::on_mSearchGroupBox_toggled( bool checked ) if ( mSearchTableEdit->text().isEmpty() ) return; - on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : "" ); + on_mSearchTableEdit_textChanged( checked ? mSearchTableEdit->text() : QLatin1String( "" ) ); } void QgsSpatiaLiteSourceSelect::on_mSearchTableEdit_textChanged( const QString & text ) @@ -270,7 +270,7 @@ bool QgsSpatiaLiteSourceSelect::newConnection( QWidget* parent ) { // Retrieve last used project dir from persistent settings QSettings settings; - QString lastUsedDir = settings.value( "/UI/lastSpatiaLiteDir", QDir::homePath() ).toString(); + QString lastUsedDir = settings.value( QStringLiteral( "/UI/lastSpatiaLiteDir" ), QDir::homePath() ).toString(); QString myFile = QFileDialog::getOpenFileName( parent, tr( "Choose a SpatiaLite/SQLite DB to open" ), @@ -283,7 +283,7 @@ bool QgsSpatiaLiteSourceSelect::newConnection( QWidget* parent ) QString myPath = myFI.path(); QString myName = myFI.fileName(); QString savedName = myFI.fileName(); - QString baseKey = "/SpatiaLite/connections/"; + QString baseKey = QStringLiteral( "/SpatiaLite/connections/" ); // TODO: keep the test //handle = openSpatiaLiteDb( myFI.canonicalFilePath() ); @@ -298,7 +298,7 @@ bool QgsSpatiaLiteSourceSelect::newConnection( QWidget* parent ) bool ok; savedName = QInputDialog::getText( nullptr , tr( "Cannot add connection '%1'" ).arg( myName ) , tr( "A connection with the same name already exists,\nplease provide a new name:" ), QLineEdit::Normal, - "", &ok ); + QLatin1String( "" ), &ok ); if ( !ok || savedName.isEmpty() ) { return false; @@ -306,7 +306,7 @@ bool QgsSpatiaLiteSourceSelect::newConnection( QWidget* parent ) } // Persist last used SpatiaLite dir - settings.setValue( "/UI/lastSpatiaLiteDir", myPath ); + settings.setValue( QStringLiteral( "/UI/lastSpatiaLiteDir" ), myPath ); // inserting this SQLite DB path settings.setValue( baseKey + "selected", savedName ); settings.setValue( baseKey + savedName + "/sqlitepath", myFI.canonicalFilePath() ); @@ -319,31 +319,31 @@ QString QgsSpatiaLiteSourceSelect::layerURI( const QModelIndex &index ) QString geomColumnName = mTableModel.itemFromIndex( index.sibling( index.row(), 2 ) )->text(); QString sql = mTableModel.itemFromIndex( index.sibling( index.row(), 3 ) )->text(); - if ( geomColumnName.contains( " AS " ) ) + if ( geomColumnName.contains( QLatin1String( " AS " ) ) ) { - int a = geomColumnName.indexOf( " AS " ); + int a = geomColumnName.indexOf( QLatin1String( " AS " ) ); QString typeName = geomColumnName.mid( a + 4 ); //only the type name geomColumnName = geomColumnName.left( a ); //only the geom column name QString geomFilter; - if ( typeName == "POINT" ) + if ( typeName == QLatin1String( "POINT" ) ) { - geomFilter = QString( "geometrytype(\"%1\") IN ('POINT','MULTIPOINT')" ).arg( geomColumnName ); + geomFilter = QStringLiteral( "geometrytype(\"%1\") IN ('POINT','MULTIPOINT')" ).arg( geomColumnName ); } - else if ( typeName == "LINESTRING" ) + else if ( typeName == QLatin1String( "LINESTRING" ) ) { - geomFilter = QString( "geometrytype(\"%1\") IN ('LINESTRING','MULTILINESTRING')" ).arg( geomColumnName ); + geomFilter = QStringLiteral( "geometrytype(\"%1\") IN ('LINESTRING','MULTILINESTRING')" ).arg( geomColumnName ); } - else if ( typeName == "POLYGON" ) + else if ( typeName == QLatin1String( "POLYGON" ) ) { - geomFilter = QString( "geometrytype(\"%1\") IN ('POLYGON','MULTIPOLYGON')" ).arg( geomColumnName ); + geomFilter = QStringLiteral( "geometrytype(\"%1\") IN ('POLYGON','MULTIPOLYGON')" ).arg( geomColumnName ); } if ( !geomFilter.isEmpty() && !sql.contains( geomFilter ) ) { if ( !sql.isEmpty() ) { - sql += " AND "; + sql += QLatin1String( " AND " ); } sql += geomFilter; @@ -351,7 +351,7 @@ QString QgsSpatiaLiteSourceSelect::layerURI( const QModelIndex &index ) } QgsDataSourceUri uri( connectionInfo() ); - uri.setDataSource( "", tableName, geomColumnName, sql, "" ); + uri.setDataSource( QLatin1String( "" ), tableName, geomColumnName, sql, QLatin1String( "" ) ); return uri.uri(); } @@ -416,7 +416,7 @@ void QgsSpatiaLiteSourceSelect::addTables() } else { - emit addDatabaseLayers( m_selectedTables, "spatialite" ); + emit addDatabaseLayers( m_selectedTables, QStringLiteral( "spatialite" ) ); if ( !mHoldDialogOpen->isChecked() ) { accept(); @@ -484,7 +484,7 @@ void QgsSpatiaLiteSourceSelect::on_btnConnect_clicked() QList<QgsSpatiaLiteConnection::TableEntry> tables = conn.tables(); Q_FOREACH ( const QgsSpatiaLiteConnection::TableEntry& table, tables ) { - mTableModel.addTableEntry( table.type, table.tableName, table.column, "" ); + mTableModel.addTableEntry( table.type, table.tableName, table.column, QLatin1String( "" ) ); } if ( cmbConnections->count() > 0 ) @@ -513,7 +513,7 @@ QStringList QgsSpatiaLiteSourceSelect::selectedTables() QString QgsSpatiaLiteSourceSelect::connectionInfo() { - return QString( "dbname='%1'" ).arg( QString( mSqlitePath ).replace( '\'', "\\'" ) ); + return QStringLiteral( "dbname='%1'" ).arg( QString( mSqlitePath ).replace( '\'', QLatin1String( "\\'" ) ) ); } void QgsSpatiaLiteSourceSelect::setSql( const QModelIndex &index ) @@ -521,7 +521,7 @@ void QgsSpatiaLiteSourceSelect::setSql( const QModelIndex &index ) QModelIndex idx = mProxyModel.mapToSource( index ); QString tableName = mTableModel.itemFromIndex( idx.sibling( idx.row(), 0 ) )->text(); - QgsVectorLayer *vlayer = new QgsVectorLayer( layerURI( idx ), tableName, "spatialite" ); + QgsVectorLayer *vlayer = new QgsVectorLayer( layerURI( idx ), tableName, QStringLiteral( "spatialite" ) ); if ( !vlayer->isValid() ) { @@ -542,7 +542,7 @@ void QgsSpatiaLiteSourceSelect::setSql( const QModelIndex &index ) QString QgsSpatiaLiteSourceSelect::fullDescription( const QString& table, const QString& column, const QString& type ) { - QString full_desc = ""; + QString full_desc = QLatin1String( "" ); full_desc += table + "\" (" + column + ") " + type; return full_desc; } @@ -551,14 +551,14 @@ void QgsSpatiaLiteSourceSelect::dbChanged() { // Remember which database was selected. QSettings settings; - settings.setValue( "/SpatiaLite/connections/selected", cmbConnections->currentText() ); + settings.setValue( QStringLiteral( "/SpatiaLite/connections/selected" ), cmbConnections->currentText() ); } void QgsSpatiaLiteSourceSelect::setConnectionListPosition() { QSettings settings; // If possible, set the item currently displayed database - QString toSelect = settings.value( "/SpatiaLite/connections/selected" ).toString(); + QString toSelect = settings.value( QStringLiteral( "/SpatiaLite/connections/selected" ) ).toString(); toSelect += '@' + settings.value( "/SpatiaLite/connections/" + toSelect + "/sqlitepath" ).toString(); diff --git a/src/providers/spatialite/qgsspatialitetablemodel.cpp b/src/providers/spatialite/qgsspatialitetablemodel.cpp index 4ae428b9eacf..2de269a1d573 100644 --- a/src/providers/spatialite/qgsspatialitetablemodel.cpp +++ b/src/providers/spatialite/qgsspatialitetablemodel.cpp @@ -150,7 +150,7 @@ void QgsSpatiaLiteTableModel::setGeometryTypesForTable( const QString & table, c QIcon myIcon = iconForType( wkbType ); itemFromIndex( currentTypeIndex )->setText( typeList.at( 0 ) ); //todo: add other rows itemFromIndex( currentTypeIndex )->setIcon( myIcon ); - if ( !geomColText.contains( " AS " ) ) + if ( !geomColText.contains( QLatin1String( " AS " ) ) ) { itemFromIndex( currentGeomColumnIndex )->setText( geomColText + " AS " + typeList.at( 0 ) ); } @@ -158,7 +158,7 @@ void QgsSpatiaLiteTableModel::setGeometryTypesForTable( const QString & table, c for ( int j = 1; j < typeList.size(); ++j ) { //todo: add correct type - addTableEntry( typeList.at( j ), table, geomColText + " AS " + typeList.at( j ), "" ); + addTableEntry( typeList.at( j ), table, geomColText + " AS " + typeList.at( j ), QLatin1String( "" ) ); } } } @@ -210,32 +210,32 @@ QString QgsSpatiaLiteTableModel::displayStringForType( QgsWkbTypes::Type type ) { return tr( "Multipolygon" ); } - return "Unknown"; + return QStringLiteral( "Unknown" ); } QgsWkbTypes::Type QgsSpatiaLiteTableModel::qgisTypeFromDbType( const QString & dbType ) const { - if ( dbType == "POINT" ) + if ( dbType == QLatin1String( "POINT" ) ) { return QgsWkbTypes::Point; } - else if ( dbType == "MULTIPOINT" ) + else if ( dbType == QLatin1String( "MULTIPOINT" ) ) { return QgsWkbTypes::MultiPoint; } - else if ( dbType == "LINESTRING" ) + else if ( dbType == QLatin1String( "LINESTRING" ) ) { return QgsWkbTypes::LineString; } - else if ( dbType == "MULTILINESTRING" ) + else if ( dbType == QLatin1String( "MULTILINESTRING" ) ) { return QgsWkbTypes::MultiLineString; } - else if ( dbType == "POLYGON" ) + else if ( dbType == QLatin1String( "POLYGON" ) ) { return QgsWkbTypes::Polygon; } - else if ( dbType == "MULTIPOLYGON" ) + else if ( dbType == QLatin1String( "MULTIPOLYGON" ) ) { return QgsWkbTypes::MultiPolygon; } diff --git a/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp b/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp index 2dbfdc178155..c2f675c96219 100644 --- a/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp +++ b/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp @@ -23,7 +23,7 @@ email : hugo dot mercier at oslandia dot com static QString quotedColumn( QString name ) { - return "\"" + name.replace( "\"", "\"\"" ) + "\""; + return "\"" + name.replace( QLatin1String( "\"" ), QLatin1String( "\"\"" ) ) + "\""; } QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerFeatureSource* source, bool ownSource, const QgsFeatureRequest& request ) @@ -47,16 +47,16 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF { bool do_exact = request.flags() & QgsFeatureRequest::ExactIntersect; QgsRectangle rect( request.filterRect() ); - QString mbr = QString( "%1,%2,%3,%4" ).arg( rect.xMinimum() ).arg( rect.yMinimum() ).arg( rect.xMaximum() ).arg( rect.yMaximum() ); + QString mbr = QStringLiteral( "%1,%2,%3,%4" ).arg( rect.xMinimum() ).arg( rect.yMinimum() ).arg( rect.xMaximum() ).arg( rect.yMaximum() ); wheres << quotedColumn( mDefinition.geometryField() ) + " is not null"; - wheres << QString( "%1Intersects(%2,BuildMbr(%3))" ) + wheres << QStringLiteral( "%1Intersects(%2,BuildMbr(%3))" ) .arg( do_exact ? "" : "Mbr", quotedColumn( mDefinition.geometryField() ), mbr ); } else if ( !mDefinition.uid().isNull() && request.filterType() == QgsFeatureRequest::FilterFid ) { - wheres << QString( "%1=%2" ) + wheres << QStringLiteral( "%1=%2" ) .arg( quotedColumn( mDefinition.uid() ) ) .arg( request.filterFid() ); } @@ -68,12 +68,12 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF { if ( !first ) { - values += ","; + values += QLatin1String( "," ); } first = false; values += QString::number( v ); } - values += ")"; + values += QLatin1String( ")" ); wheres << values; } @@ -111,11 +111,11 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF } else { - columns = "0"; + columns = QStringLiteral( "0" ); } Q_FOREACH ( int i, mAttributes ) { - columns += ","; + columns += QLatin1String( "," ); QString cname = mFields.at( i ).name().toLower(); columns += quotedColumn( cname ); } @@ -123,7 +123,7 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF // the last column is the geometry, if any if (( !( request.flags() & QgsFeatureRequest::NoGeometry ) || ( request.filterType() == QgsFeatureRequest::FilterExpression && request.filterExpression()->needsGeometry() ) ) - && !mDefinition.geometryField().isNull() && mDefinition.geometryField() != "*no*" ) + && !mDefinition.geometryField().isNull() && mDefinition.geometryField() != QLatin1String( "*no*" ) ) { columns += "," + quotedColumn( mDefinition.geometryField() ); } @@ -131,7 +131,7 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF mSqlQuery = "SELECT " + columns + " FROM " + tableName; if ( !wheres.isEmpty() ) { - mSqlQuery += " WHERE " + wheres.join( " AND " ); + mSqlQuery += " WHERE " + wheres.join( QStringLiteral( " AND " ) ); } mQuery.reset( new Sqlite::Query( mSqlite, mSqlQuery ) ); diff --git a/src/providers/virtual/qgsvirtuallayerprovider.cpp b/src/providers/virtual/qgsvirtuallayerprovider.cpp index 015e4b5f556e..6b1f0a02f3ab 100644 --- a/src/providers/virtual/qgsvirtuallayerprovider.cpp +++ b/src/providers/virtual/qgsvirtuallayerprovider.cpp @@ -36,14 +36,14 @@ extern "C" #include "qgsvirtuallayersqlitemodule.h" #include "qgsvirtuallayerqueryparser.h" -const QString VIRTUAL_LAYER_KEY = "virtual"; -const QString VIRTUAL_LAYER_DESCRIPTION = "Virtual layer data provider"; +const QString VIRTUAL_LAYER_KEY = QStringLiteral( "virtual" ); +const QString VIRTUAL_LAYER_DESCRIPTION = QStringLiteral( "Virtual layer data provider" ); -const QString VIRTUAL_LAYER_QUERY_VIEW = "_query"; +const QString VIRTUAL_LAYER_QUERY_VIEW = QStringLiteral( "_query" ); static QString quotedColumn( QString name ) { - return "\"" + name.replace( "\"", "\"\"" ) + "\""; + return "\"" + name.replace( QLatin1String( "\"" ), QLatin1String( "\"\"" ) ) + "\""; } #define PROVIDER_ERROR( msg ) do { mError = QgsError( msg, VIRTUAL_LAYER_KEY ); QgsDebugMsg( msg ); } while(0) @@ -149,7 +149,7 @@ bool QgsVirtualLayerProvider::openIt() } { - Sqlite::Query q( mSqlite.get(), "SELECT name FROM sqlite_master WHERE name='_meta'" ); + Sqlite::Query q( mSqlite.get(), QStringLiteral( "SELECT name FROM sqlite_master WHERE name='_meta'" ) ); if ( q.step() != SQLITE_ROW ) { PROVIDER_ERROR( "No metadata tables!" ); @@ -158,7 +158,7 @@ bool QgsVirtualLayerProvider::openIt() } // look for the correct version and the stored url { - Sqlite::Query q( mSqlite.get(), "SELECT version, url FROM _meta" ); + Sqlite::Query q( mSqlite.get(), QStringLiteral( "SELECT version, url FROM _meta" ) ); int version = 0; if ( q.step() == SQLITE_ROW ) { @@ -257,7 +257,7 @@ bool QgsVirtualLayerProvider::createIt() mPath = mDefinition.filePath(); // use a temporary file if needed if ( mPath.isEmpty() ) - path = ":memory:"; + path = QStringLiteral( ":memory:" ); else path = mPath; @@ -292,18 +292,18 @@ bool QgsVirtualLayerProvider::createIt() QString vname = mLayers.at( i ).name; if ( vlayer ) { - QString createStr = QString( "DROP TABLE IF EXISTS \"%1\"; CREATE VIRTUAL TABLE \"%1\" USING QgsVLayer(%2);" ).arg( vname, vlayer->id() ); + QString createStr = QStringLiteral( "DROP TABLE IF EXISTS \"%1\"; CREATE VIRTUAL TABLE \"%1\" USING QgsVLayer(%2);" ).arg( vname, vlayer->id() ); Sqlite::Query::exec( mSqlite.get(), createStr ); } else { QString provider = mLayers.at( i ).provider; // double each single quote - provider.replace( "'", "''" ); + provider.replace( QLatin1String( "'" ), QLatin1String( "''" ) ); QString source = mLayers.at( i ).source; - source.replace( "'", "''" ); + source.replace( QLatin1String( "'" ), QLatin1String( "''" ) ); QString encoding = mLayers.at( i ).encoding; - QString createStr = QString( "DROP TABLE IF EXISTS \"%1\"; CREATE VIRTUAL TABLE \"%1\" USING QgsVLayer('%2','%4',%3)" ) + QString createStr = QStringLiteral( "DROP TABLE IF EXISTS \"%1\"; CREATE VIRTUAL TABLE \"%1\" USING QgsVLayer('%2','%4',%3)" ) .arg( vname, provider, encoding, @@ -409,7 +409,7 @@ bool QgsVirtualLayerProvider::createIt() mTableName = VIRTUAL_LAYER_QUERY_VIEW; // create a view - QString viewStr = QString( "DROP VIEW IF EXISTS %1; CREATE VIEW %1 AS %2" ) + QString viewStr = QStringLiteral( "DROP VIEW IF EXISTS %1; CREATE VIEW %1 AS %2" ) .arg( VIRTUAL_LAYER_QUERY_VIEW, mDefinition.query() ); Sqlite::Query::exec( mSqlite.get(), viewStr ); @@ -428,7 +428,7 @@ bool QgsVirtualLayerProvider::createIt() } else if ( !noGeometry ) { - mDefinition.setGeometryField( "geometry" ); + mDefinition.setGeometryField( QStringLiteral( "geometry" ) ); mDefinition.setGeometryWkbType( c.wkbType() ); mDefinition.setGeometrySrid( c.srid() ); } @@ -438,7 +438,7 @@ bool QgsVirtualLayerProvider::createIt() // Save the definition back to the sqlite file { - Sqlite::Query q( mSqlite.get(), "UPDATE _meta SET url=?" ); + Sqlite::Query q( mSqlite.get(), QStringLiteral( "UPDATE _meta SET url=?" ) ); q.bind( mDefinition.toUrl().toString() ); q.step(); } @@ -454,14 +454,14 @@ void QgsVirtualLayerProvider::resetSqlite() { bool hasSpatialrefsys = false; { - Sqlite::Query q( mSqlite.get(), "SELECT name FROM sqlite_master WHERE name='spatial_ref_sys'" ); + Sqlite::Query q( mSqlite.get(), QStringLiteral( "SELECT name FROM sqlite_master WHERE name='spatial_ref_sys'" ) ); hasSpatialrefsys = q.step() == SQLITE_ROW; } - QString sql = "DROP TABLE IF EXISTS _meta;"; + QString sql = QStringLiteral( "DROP TABLE IF EXISTS _meta;" ); if ( !hasSpatialrefsys ) { - sql += "SELECT InitSpatialMetadata(1);"; + sql += QLatin1String( "SELECT InitSpatialMetadata(1);" ); } Sqlite::Query::exec( mSqlite.get(), sql ); } @@ -473,7 +473,7 @@ QgsAbstractFeatureSource* QgsVirtualLayerProvider::featureSource() const QString QgsVirtualLayerProvider::storageType() const { - return "No storage per se, view data from other data sources"; + return QStringLiteral( "No storage per se, view data from other data sources" ); } QgsCoordinateReferenceSystem QgsVirtualLayerProvider::crs() const @@ -527,9 +527,9 @@ QgsRectangle QgsVirtualLayerProvider::extent() const void QgsVirtualLayerProvider::updateStatistics() const { bool hasGeometry = mDefinition.geometryWkbType() != QgsWkbTypes::NoGeometry; - QString subset = mSubset.isEmpty() ? "" : " WHERE " + mSubset; - QString sql = QString( "SELECT Count(*)%1 FROM %2%3" ) - .arg( hasGeometry ? QString( ",Min(MbrMinX(%1)),Min(MbrMinY(%1)),Max(MbrMaxX(%1)),Max(MbrMaxY(%1))" ).arg( quotedColumn( mDefinition.geometryField() ) ) : "", + QString subset = mSubset.isEmpty() ? QLatin1String( "" ) : " WHERE " + mSubset; + QString sql = QStringLiteral( "SELECT Count(*)%1 FROM %2%3" ) + .arg( hasGeometry ? QStringLiteral( ",Min(MbrMinX(%1)),Min(MbrMinY(%1)),Max(MbrMaxX(%1)),Max(MbrMaxY(%1))" ).arg( quotedColumn( mDefinition.geometryField() ) ) : QLatin1String( "" ), mTableName, subset ); Sqlite::Query q( mSqlite.get(), sql ); diff --git a/src/providers/virtual/qgsvirtuallayerprovider.h b/src/providers/virtual/qgsvirtuallayerprovider.h index cbb23f090cca..812ef8f7c116 100644 --- a/src/providers/virtual/qgsvirtuallayerprovider.h +++ b/src/providers/virtual/qgsvirtuallayerprovider.h @@ -34,7 +34,7 @@ class QgsVirtualLayerProvider: public QgsVectorDataProvider * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset */ - explicit QgsVirtualLayerProvider( QString const &uri = "" ); + explicit QgsVirtualLayerProvider( QString const &uri = QLatin1String( "" ) ); /** Destructor */ virtual ~QgsVirtualLayerProvider(); @@ -92,11 +92,11 @@ class QgsVirtualLayerProvider: public QgsVectorDataProvider struct SourceLayer { SourceLayer(): layer( nullptr ) {} - SourceLayer( QgsVectorLayer *l, const QString& n = "" ) + SourceLayer( QgsVectorLayer *l, const QString& n = QLatin1String( "" ) ) : layer( l ) , name( n ) {} - SourceLayer( const QString& p, const QString& s, const QString& n, const QString& e = "UTF-8" ) + SourceLayer( const QString& p, const QString& s, const QString& n, const QString& e = QStringLiteral( "UTF-8" ) ) : layer( nullptr ) , name( n ) , source( s ) diff --git a/src/providers/virtual/qgsvirtuallayerqueryparser.cpp b/src/providers/virtual/qgsvirtuallayerqueryparser.cpp index 12d453e9c3e6..743d636d28d9 100644 --- a/src/providers/virtual/qgsvirtuallayerqueryparser.cpp +++ b/src/providers/virtual/qgsvirtuallayerqueryparser.cpp @@ -32,9 +32,9 @@ namespace QgsVirtualLayerQueryParser // open an empty in-memory sqlite database and execute the query // sqlite will return an error for each missing table // this way we know the list of tables referenced by the query - QgsScopedSqlite db( ":memory:", /*withExtension=*/ false ); + QgsScopedSqlite db( QStringLiteral( ":memory:" ), /*withExtension=*/ false ); - const QString noSuchError = "no such table: "; + const QString noSuchError = QStringLiteral( "no such table: " ); while ( true ) { @@ -47,7 +47,7 @@ namespace QgsVirtualLayerQueryParser tables << tableName; // create a dummy table to skip this error - QString createStr = QString( "CREATE TABLE \"%1\" (id int)" ).arg( tableName.replace( "\"", "\"\"" ) ); + QString createStr = QStringLiteral( "CREATE TABLE \"%1\" (id int)" ).arg( tableName.replace( QLatin1String( "\"" ), QLatin1String( "\"\"" ) ) ); ( void )sqlite3_exec( db.get(), createStr.toUtf8().constData(), nullptr, NULL, NULL ); } else @@ -74,11 +74,11 @@ namespace QgsVirtualLayerQueryParser QString type = rx.cap( 2 ); ColumnDef def; def.setName( column ); - if ( type == "int" ) + if ( type == QLatin1String( "int" ) ) def.setScalarType( QVariant::Int ); - else if ( type == "real" ) + else if ( type == QLatin1String( "real" ) ) def.setScalarType( QVariant::Double ); - else if ( type == "text" ) + else if ( type == QLatin1String( "text" ) ) def.setScalarType( QVariant::String ); else { @@ -103,13 +103,13 @@ namespace QgsVirtualLayerQueryParser // the type returned by PRAGMA table_info will be either // the type declared by one of the virtual tables // or null - if ( columnType == "int" ) + if ( columnType == QLatin1String( "int" ) ) d.setScalarType( QVariant::Int ); - else if ( columnType == "real" ) + else if ( columnType == QLatin1String( "real" ) ) d.setScalarType( QVariant::Double ); - else if ( columnType == "text" ) + else if ( columnType == QLatin1String( "text" ) ) d.setScalarType( QVariant::String ); - else if ( columnType.startsWith( "geometry" ) ) + else if ( columnType.startsWith( QLatin1String( "geometry" ) ) ) { // parse the geometry type and srid // geometry(type,srid) @@ -127,12 +127,12 @@ namespace QgsVirtualLayerQueryParser ColumnDef geometryDefinitionFromVirtualTable( sqlite3* db, const QString& tableName ) { ColumnDef d; - Sqlite::Query q( db, QString( "PRAGMA table_info(%1)" ).arg( tableName ) ); + Sqlite::Query q( db, QStringLiteral( "PRAGMA table_info(%1)" ).arg( tableName ) ); while ( q.step() == SQLITE_ROW ) { QString columnName = q.columnText( 1 ); QString columnType = q.columnText( 2 ); - if ( ! columnType.startsWith( "geometry" ) ) + if ( ! columnType.startsWith( QLatin1String( "geometry" ) ) ) continue; d.setName( columnName ); @@ -157,7 +157,7 @@ namespace QgsVirtualLayerQueryParser QVector<int> undefinedColumns; TableDef tableDef; { - Sqlite::Query q( db, "PRAGMA table_info(_tview)" ); + Sqlite::Query q( db, QStringLiteral( "PRAGMA table_info(_tview)" ) ); int columnNumber = 0; while ( q.step() == SQLITE_ROW ) { @@ -197,14 +197,14 @@ namespace QgsVirtualLayerQueryParser // get the first row to introspect types { - QString qs = "SELECT "; + QString qs = QStringLiteral( "SELECT " ); for ( int i = 0; i < undefinedColumns.size(); i++ ) { qs += "\"" + columns[undefinedColumns[i]] + "\""; if ( i != undefinedColumns.size() - 1 ) - qs += ", "; + qs += QLatin1String( ", " ); } - qs += " FROM _tview LIMIT 1"; + qs += QLatin1String( " FROM _tview LIMIT 1" ); qWarning() << qs; Sqlite::Query q( db, qs ); @@ -253,7 +253,7 @@ namespace QgsVirtualLayerQueryParser TableDef tableDefinitionFromVirtualTable( sqlite3* db, const QString& tableName ) { TableDef td; - Sqlite::Query q( db, QString( "PRAGMA table_info(%1)" ).arg( tableName ) ); + Sqlite::Query q( db, QStringLiteral( "PRAGMA table_info(%1)" ).arg( tableName ) ); while ( q.step() == SQLITE_ROW ) { ColumnDef d; diff --git a/src/providers/virtual/qgsvirtuallayersourceselect.cpp b/src/providers/virtual/qgsvirtuallayersourceselect.cpp index 7a511825a95b..27a7404fa652 100644 --- a/src/providers/virtual/qgsvirtuallayersourceselect.cpp +++ b/src/providers/virtual/qgsvirtuallayersourceselect.cpp @@ -54,19 +54,19 @@ QgsVirtualLayerSourceSelect::QgsVirtualLayerSourceSelect( QWidget* parent, Qt::W // we cannot know before trying to actually load a dataset // if the provider is raster or vector // so we manually exclude well-known raster providers - if ( pk != "gdal" && pk != "ows" && pk != "wcs" && pk != "wms" ) + if ( pk != QLatin1String( "gdal" ) && pk != QLatin1String( "ows" ) && pk != QLatin1String( "wcs" ) && pk != QLatin1String( "wms" ) ) { mProviderList << pk; } } - QgsLayerTreeView* treeView = parent->findChild<QgsLayerTreeView*>( "theLayerTreeView" ); + QgsLayerTreeView* treeView = parent->findChild<QgsLayerTreeView*>( QStringLiteral( "theLayerTreeView" ) ); if ( treeView ) { QgsLayerTreeModel* model = qobject_cast<QgsLayerTreeModel*>( treeView->model() ); Q_FOREACH ( QgsLayerTreeLayer* layer, model->rootGroup()->findLayers() ) { - if ( layer->layer()->type() == QgsMapLayer::VectorLayer && static_cast<QgsVectorLayer*>( layer->layer() )->providerType() == "virtual" ) + if ( layer->layer()->type() == QgsMapLayer::VectorLayer && static_cast<QgsVectorLayer*>( layer->layer() )->providerType() == QLatin1String( "virtual" ) ) { // store layer's id as user data mLayerNameCombo->addItem( layer->layer()->name(), layer->layer()->id() ); @@ -75,13 +75,13 @@ QgsVirtualLayerSourceSelect::QgsVirtualLayerSourceSelect( QWidget* parent, Qt::W } if ( mLayerNameCombo->count() == 0 ) - mLayerNameCombo->addItem( "virtual_layer" ); + mLayerNameCombo->addItem( QStringLiteral( "virtual_layer" ) ); // select the current layer, if any if ( treeView ) { QList<QgsMapLayer*> selected = treeView->selectedLayers(); - if ( selected.size() == 1 && selected[0]->type() == QgsMapLayer::VectorLayer && static_cast<QgsVectorLayer*>( selected[0] )->providerType() == "virtual" ) + if ( selected.size() == 1 && selected[0]->type() == QgsMapLayer::VectorLayer && static_cast<QgsVectorLayer*>( selected[0] )->providerType() == QLatin1String( "virtual" ) ) { mLayerNameCombo->setCurrentIndex( mLayerNameCombo->findData( selected[0]->id() ) ); } @@ -94,7 +94,7 @@ QgsVirtualLayerSourceSelect::QgsVirtualLayerSourceSelect( QWidget* parent, Qt::W QsciAPIs* apis = new QsciAPIs( mQueryEdit->lexer() ); Q_INIT_RESOURCE( sqlfunctionslist ); - QFile fFile( ":/sqlfunctions/list.txt" ); + QFile fFile( QStringLiteral( ":/sqlfunctions/list.txt" ) ); if ( fFile.open( QIODevice::ReadOnly ) ) { QTextStream in( &fFile ); @@ -229,7 +229,7 @@ void QgsVirtualLayerSourceSelect::onTestQuery() { QgsVirtualLayerDefinition def = getVirtualLayerDef(); - QScopedPointer<QgsVectorLayer> vl( new QgsVectorLayer( def.toString(), "test", "virtual" ) ); + QScopedPointer<QgsVectorLayer> vl( new QgsVectorLayer( def.toString(), QStringLiteral( "test" ), QStringLiteral( "virtual" ) ) ); if ( vl->isValid() ) { QMessageBox::information( nullptr, tr( "Virtual layer test" ), tr( "No error" ) ); @@ -253,7 +253,7 @@ void QgsVirtualLayerSourceSelect::onAddLayer() QComboBox* encodingCombo = new QComboBox(); encodingCombo->addItems( QgsVectorDataProvider::availableEncodings() ); - QString defaultEnc = QSettings().value( "/UI/encoding", "System" ).toString(); + QString defaultEnc = QSettings().value( QStringLiteral( "/UI/encoding" ), "System" ).toString(); encodingCombo->setCurrentIndex( encodingCombo->findText( defaultEnc ) ); mLayersTable->setCellWidget( mLayersTable->rowCount() - 1, 2, encodingCombo ); } @@ -303,7 +303,7 @@ void QgsVirtualLayerSourceSelect::onImportLayer() void QgsVirtualLayerSourceSelect::on_buttonBox_accepted() { - QString layerName = "virtual_layer"; + QString layerName = QStringLiteral( "virtual_layer" ); int idx = mLayerNameCombo->currentIndex(); if ( idx != -1 && !mLayerNameCombo->currentText().isEmpty() ) { @@ -320,12 +320,12 @@ void QgsVirtualLayerSourceSelect::on_buttonBox_accepted() int r = QMessageBox::warning( nullptr, tr( "Warning" ), tr( "A virtual layer of this name already exists, would you like to overwrite it?" ), QMessageBox::Yes | QMessageBox::No ); if ( r == QMessageBox::Yes ) { - emit replaceVectorLayer( id, def.toString(), layerName, "virtual" ); + emit replaceVectorLayer( id, def.toString(), layerName, QStringLiteral( "virtual" ) ); return; } } } - emit addVectorLayer( def.toString(), layerName, "virtual" ); + emit addVectorLayer( def.toString(), layerName, QStringLiteral( "virtual" ) ); } QGISEXTERN QgsVirtualLayerSourceSelect *selectWidget( QWidget *parent, Qt::WindowFlags fl ) diff --git a/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp b/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp index a84da327b1e6..067cf769ff45 100644 --- a/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp +++ b/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp @@ -39,7 +39,7 @@ QgsScopedSqlite::QgsScopedSqlite( const QString& path, bool withExtension ) if ( r ) { - QString err = QString( "%1 [%2]" ).arg( sqlite3_errmsg( db_ ), path ); + QString err = QStringLiteral( "%1 [%2]" ).arg( sqlite3_errmsg( db_ ), path ); QgsDebugMsg( err ); throw std::runtime_error( err.toLocal8Bit().constData() ); } @@ -96,7 +96,7 @@ namespace Sqlite int r = sqlite3_prepare_v2( db, ba.constData(), ba.size(), &stmt_, nullptr ); if ( r ) { - QString err = QString( "Query preparation error on %1: %2" ).arg( q ).arg( sqlite3_errmsg( db ) ); + QString err = QStringLiteral( "Query preparation error on %1: %2" ).arg( q ).arg( sqlite3_errmsg( db ) ); throw std::runtime_error( err.toLocal8Bit().constData() ); } } @@ -130,7 +130,7 @@ namespace Sqlite int r = sqlite3_exec( db, sql.toLocal8Bit().constData(), nullptr, nullptr, &errMsg ); if ( r ) { - QString err = QString( "Query execution error on %1: %2 - %3" ).arg( sql ).arg( r ).arg( errMsg ); + QString err = QStringLiteral( "Query execution error on %1: %2 - %3" ).arg( sql ).arg( r ).arg( errMsg ); throw std::runtime_error( err.toLocal8Bit().constData() ); } } diff --git a/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp b/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp index c8cca486532a..ee74d0a1bfa4 100644 --- a/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp +++ b/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp @@ -57,7 +57,7 @@ void initVirtualLayerMetadata( sqlite3* db ) char *errMsg; if ( create_meta ) { - r = sqlite3_exec( db, QString( "CREATE TABLE _meta (version INT, url TEXT); INSERT INTO _meta (version) VALUES(%1);" ).arg( VIRTUAL_LAYER_VERSION ).toLocal8Bit().constData(), nullptr, nullptr, &errMsg ); + r = sqlite3_exec( db, QStringLiteral( "CREATE TABLE _meta (version INT, url TEXT); INSERT INTO _meta (version) VALUES(%1);" ).arg( VIRTUAL_LAYER_VERSION ).toLocal8Bit().constData(), nullptr, nullptr, &errMsg ); if ( r ) { throw std::runtime_error( errMsg ); @@ -199,25 +199,25 @@ struct VTable QStringList sqlFields; // add a hidden field for rtree filtering - sqlFields << "_search_frame_ HIDDEN BLOB"; + sqlFields << QStringLiteral( "_search_frame_ HIDDEN BLOB" ); Q_FOREACH ( const QgsField& field, mFields ) { - QString typeName = "text"; + QString typeName = QStringLiteral( "text" ); switch ( field.type() ) { case QVariant::Int: case QVariant::UInt: case QVariant::Bool: case QVariant::LongLong: - typeName = "int"; + typeName = QStringLiteral( "int" ); break; case QVariant::Double: - typeName = "real"; + typeName = QStringLiteral( "real" ); break; case QVariant::String: default: - typeName = "text"; + typeName = QStringLiteral( "text" ); break; } sqlFields << field.name() + " " + typeName; @@ -230,7 +230,7 @@ struct VTable // the type of a column can be declared with two numeric arguments, usually for setting numeric precision // we are using them to set the geometry type and srid // these will be reused by the provider when it will introspect the query to detect types - sqlFields << QString( "geometry geometry(%1,%2)" ).arg( provider->wkbType() ).arg( provider->crs().postgisSrid() ); + sqlFields << QStringLiteral( "geometry geometry(%1,%2)" ).arg( provider->wkbType() ).arg( provider->crs().postgisSrid() ); } QgsAttributeList pkAttributeIndexes = provider->pkAttributeIndexes(); @@ -239,7 +239,7 @@ struct VTable mPkColumn = pkAttributeIndexes.at( 0 ) + 1; } - mCreationStr = "CREATE TABLE vtable (" + sqlFields.join( "," ) + ")"; + mCreationStr = "CREATE TABLE vtable (" + sqlFields.join( QStringLiteral( "," ) ) + ")"; mCrs = provider->crs().postgisSrid(); } @@ -336,7 +336,7 @@ int vtableCreateConnect( sqlite3* sql, void* aux, int argc, const char* const* a if ( argc < 4 ) { - QString err( "Missing arguments: layer_id | provider, source" ); + QString err( QStringLiteral( "Missing arguments: layer_id | provider, source" ) ); RETURN_CPPSTR_ERROR( err ); return SQLITE_ERROR; } @@ -359,7 +359,7 @@ int vtableCreateConnect( sqlite3* sql, void* aux, int argc, const char* const* a { if ( outErr ) { - QString err( "Cannot find layer " ); + QString err( QStringLiteral( "Cannot find layer " ) ); err += QString::fromUtf8( argv[3] ); RETURN_CPPSTR_ERROR( err ); } @@ -377,7 +377,7 @@ int vtableCreateConnect( sqlite3* sql, void* aux, int argc, const char* const* a // encoding = argv[5] QString provider = argv[3]; QString source = QString::fromUtf8( argv[4] ); - QString encoding = "UTF-8"; + QString encoding = QStringLiteral( "UTF-8" ); if ( argc == 6 ) { encoding = argv[5]; @@ -385,12 +385,12 @@ int vtableCreateConnect( sqlite3* sql, void* aux, int argc, const char* const* a if ( provider.size() >= 1 && provider[0] == '\'' ) { // trim and undouble single quotes - provider = provider.mid( 1, provider.size() - 2 ).replace( "''", "'" ); + provider = provider.mid( 1, provider.size() - 2 ).replace( QLatin1String( "''" ), QLatin1String( "'" ) ); } if ( source.size() >= 1 && source[0] == '\'' ) { // trim and undouble single quotes - source = source.mid( 1, source.size() - 2 ).replace( "''", "'" ); + source = source.mid( 1, source.size() - 2 ).replace( QLatin1String( "''" ), QLatin1String( "'" ) ); } try { @@ -514,23 +514,23 @@ int vtableBestIndex( sqlite3_vtab *pvtab, sqlite3_index_info* indexInfo ) switch ( indexInfo->aConstraint[i].op ) { case SQLITE_INDEX_CONSTRAINT_EQ: - expr += " = "; + expr += QLatin1String( " = " ); break; case SQLITE_INDEX_CONSTRAINT_GT: - expr += " > "; + expr += QLatin1String( " > " ); break; case SQLITE_INDEX_CONSTRAINT_LE: - expr += " <= "; + expr += QLatin1String( " <= " ); break; case SQLITE_INDEX_CONSTRAINT_LT: - expr += " < "; + expr += QLatin1String( " < " ); break; case SQLITE_INDEX_CONSTRAINT_GE: - expr += " >= "; + expr += QLatin1String( " >= " ); break; #ifdef SQLITE_INDEX_CONSTRAINT_LIKE case SQLITE_INDEX_CONSTRAINT_LIKE: - expr += " LIKE "; + expr += QLatin1String( " LIKE " ); break; #endif default: @@ -621,11 +621,11 @@ int vtableFilter( sqlite3_vtab_cursor * cursor, int idxNum, const char *idxStr, int n = sqlite3_value_bytes( argv[0] ); const char* t = reinterpret_cast<const char*>( sqlite3_value_text( argv[0] ) ); QString str = QString::fromUtf8( t, n ); - expr += "'" + str.replace( "'", "''" ) + "'"; + expr += "'" + str.replace( QLatin1String( "'" ), QLatin1String( "''" ) ) + "'"; break; } default: - expr = ""; + expr = QLatin1String( "" ); } if ( !expr.isEmpty() ) { @@ -779,7 +779,7 @@ void qgisFunctionWrapper( sqlite3_context* ctxt, int nArgs, sqlite3_value** args }; } - QgsExpression parentExpr( "" ); + QgsExpression parentExpr( QLatin1String( "" ) ); QVariant ret = foo->func( variants, &qgisFunctionExpressionContext, &parentExpr ); if ( parentExpr.hasEvalError() ) { @@ -845,9 +845,9 @@ void qgisFunctionWrapper( sqlite3_context* ctxt, int nArgs, sqlite3_value** args void registerQgisFunctions( sqlite3* db ) { QStringList excludedFunctions; - excludedFunctions << "min" << "max" << "coalesce" << "get_feature" << "getFeature" << "attribute"; + excludedFunctions << QStringLiteral( "min" ) << QStringLiteral( "max" ) << QStringLiteral( "coalesce" ) << QStringLiteral( "get_feature" ) << QStringLiteral( "getFeature" ) << QStringLiteral( "attribute" ); QStringList reservedFunctions; - reservedFunctions << "left" << "right" << "union"; + reservedFunctions << QStringLiteral( "left" ) << QStringLiteral( "right" ) << QStringLiteral( "union" ); // register QGIS expression functions Q_FOREACH ( QgsExpression::Function* foo, QgsExpression::Functions() ) { @@ -868,7 +868,7 @@ void registerQgisFunctions( sqlite3* db ) { if ( reservedFunctions.contains( name ) ) // reserved keyword name = "_" + name; - if ( name.startsWith( "$" ) ) + if ( name.startsWith( QLatin1String( "$" ) ) ) continue; // register the function and pass the pointer to the Function* as user data diff --git a/src/providers/wcs/qgswcscapabilities.cpp b/src/providers/wcs/qgswcscapabilities.cpp index 8312f11d2aa8..0c29a92dce19 100644 --- a/src/providers/wcs/qgswcscapabilities.cpp +++ b/src/providers/wcs/qgswcscapabilities.cpp @@ -78,7 +78,7 @@ void QgsWcsCapabilities::parseUri() { mCacheLoadControl = QNetworkRequest::PreferNetwork; - QString cache = mUri.param( "cache" ); + QString cache = mUri.param( QStringLiteral( "cache" ) ); QgsDebugMsg( "cache = " + cache ); if ( !cache.isEmpty() ) @@ -106,7 +106,7 @@ QString QgsWcsCapabilities::prepareUri( QString uri ) { uri.append( '?' ); } - else if ( uri.right( 1 ) != "?" && uri.right( 1 ) != "&" ) + else if ( uri.right( 1 ) != QLatin1String( "?" ) && uri.right( 1 ) != QLatin1String( "&" ) ) { uri.append( '&' ); } @@ -135,7 +135,7 @@ QString QgsWcsCapabilities::getCoverageUrl() const QString url = mCapabilities.getCoverageGetUrl; if ( url.isEmpty() ) { - url = mUri.param( "url" ); + url = mUri.param( QStringLiteral( "url" ) ); } return url; } @@ -143,7 +143,7 @@ QString QgsWcsCapabilities::getCoverageUrl() const bool QgsWcsCapabilities::sendRequest( QString const & url ) { QgsDebugMsg( "url = " + url ); - mError = ""; + mError = QLatin1String( "" ); QNetworkRequest request( url ); if ( !setAuthorization( request ) ) { @@ -177,7 +177,7 @@ bool QgsWcsCapabilities::sendRequest( QString const & url ) { if ( mError.isEmpty() ) { - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "empty capabilities document" ); } return false; @@ -186,7 +186,7 @@ bool QgsWcsCapabilities::sendRequest( QString const & url ) if ( mCapabilitiesResponse.startsWith( "<html>" ) || mCapabilitiesResponse.startsWith( "<HTML>" ) ) { - mErrorFormat = "text/html"; + mErrorFormat = QStringLiteral( "text/html" ); mError = mCapabilitiesResponse; return false; } @@ -202,17 +202,17 @@ void QgsWcsCapabilities::clear() QString QgsWcsCapabilities::getCapabilitiesUrl( const QString& version ) const { - QString url = prepareUri( mUri.param( "url" ) ) + "SERVICE=WCS&REQUEST=GetCapabilities"; + QString url = prepareUri( mUri.param( QStringLiteral( "url" ) ) ) + "SERVICE=WCS&REQUEST=GetCapabilities"; if ( !version.isEmpty() ) { // 1.0.0 - VERSION // 1.1.0 - AcceptVersions (not supported by UMN Mapserver 6.0.3 - defaults to latest 1.1 - if ( version.startsWith( "1.0" ) ) + if ( version.startsWith( QLatin1String( "1.0" ) ) ) { url += "&VERSION=" + version; } - else if ( version.startsWith( "1.1" ) ) + else if ( version.startsWith( QLatin1String( "1.1" ) ) ) { // Ignored by UMN Mapserver 6.0.3, see below url += "&AcceptVersions=" + version; @@ -232,7 +232,7 @@ bool QgsWcsCapabilities::retrieveServerCapabilities() QStringList versions; - QString preferredVersion = mUri.param( "version" ); + QString preferredVersion = mUri.param( QStringLiteral( "version" ) ); if ( !preferredVersion.isEmpty() ) { @@ -243,7 +243,7 @@ bool QgsWcsCapabilities::retrieveServerCapabilities() // We prefer 1.0 because 1.1 has many issues, each server implements it in defferent // way with various particularities // It may happen that server supports 1.1.0 but gives error for 1.1 - versions << "1.0.0" << "1.1.0,1.0.0"; + versions << QStringLiteral( "1.0.0" ) << QStringLiteral( "1.1.0,1.0.0" ); } Q_FOREACH ( const QString& v, versions ) @@ -290,13 +290,13 @@ bool QgsWcsCapabilities::retrieveServerCapabilities( const QString& preferredVer QString QgsWcsCapabilities::getDescribeCoverageUrl( QString const &identifier ) const { - QString url = prepareUri( mUri.param( "url" ) ) + "SERVICE=WCS&REQUEST=DescribeCoverage&VERSION=" + mVersion; + QString url = prepareUri( mUri.param( QStringLiteral( "url" ) ) ) + "SERVICE=WCS&REQUEST=DescribeCoverage&VERSION=" + mVersion; - if ( mVersion.startsWith( "1.0" ) ) + if ( mVersion.startsWith( QLatin1String( "1.0" ) ) ) { url += "&COVERAGE=" + identifier; } - else if ( mVersion.startsWith( "1.1" ) ) + else if ( mVersion.startsWith( QLatin1String( "1.1" ) ) ) { // in 1.1.0, 1.1.1, 1.1.2 the name of param is 'identifier' // but in KVP 'identifiers' @@ -328,11 +328,11 @@ bool QgsWcsCapabilities::describeCoverage( QString const &identifier, bool force QgsDebugMsg( "Converting to Dom." ); bool domOK = false; - if ( mVersion.startsWith( "1.0" ) ) + if ( mVersion.startsWith( QLatin1String( "1.0" ) ) ) { domOK = parseDescribeCoverageDom10( mCapabilitiesResponse, coverage ); } - else if ( mVersion.startsWith( "1.1" ) ) + else if ( mVersion.startsWith( QLatin1String( "1.1" ) ) ) { domOK = parseDescribeCoverageDom11( mCapabilitiesResponse, coverage ); } @@ -394,7 +394,7 @@ void QgsWcsCapabilities::capabilitiesReplyFinished() if ( mCapabilitiesResponse.isEmpty() ) { - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "empty of capabilities: %1" ).arg( mCapabilitiesReply->errorString() ); } } @@ -424,7 +424,7 @@ void QgsWcsCapabilities::capabilitiesReplyFinished() return; } - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Download of capabilities failed: %1" ).arg( mCapabilitiesReply->errorString() ); QgsMessageLog::logMessage( mError, tr( "WCS" ) ); mCapabilitiesResponse.clear(); @@ -438,7 +438,7 @@ void QgsWcsCapabilities::capabilitiesReplyFinished() void QgsWcsCapabilities::capabilitiesReplyProgress( qint64 bytesReceived, qint64 bytesTotal ) { - QString msg = tr( "%1 of %2 bytes of capabilities downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QString( "unknown number of" ) : QString::number( bytesTotal ) ); + QString msg = tr( "%1 of %2 bytes of capabilities downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QStringLiteral( "unknown number of" ) : QString::number( bytesTotal ) ); QgsDebugMsg( msg ); emit statusChanged( msg ); } @@ -470,22 +470,22 @@ bool QgsWcsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWcsCapa QString tagName = stripNS( docElem.tagName() ); if ( // We don't support 1.0, but try WCS_Capabilities tag to get version - tagName != "WCS_Capabilities" && // 1.0 - tagName != "Capabilities" // 1.1, tags seen: Capabilities, wcs:Capabilities + tagName != QLatin1String( "WCS_Capabilities" ) && // 1.0 + tagName != QLatin1String( "Capabilities" ) // 1.1, tags seen: Capabilities, wcs:Capabilities ) { - if ( tagName == "ExceptionReport" ) + if ( tagName == QLatin1String( "ExceptionReport" ) ) { mErrorTitle = tr( "Exception" ); - mErrorFormat = "text/plain"; - mError = tr( "Could not get WCS capabilities: %1" ).arg( domElementText( docElem, "Exception.ExceptionText" ) ); + mErrorFormat = QStringLiteral( "text/plain" ); + mError = tr( "Could not get WCS capabilities: %1" ).arg( domElementText( docElem, QStringLiteral( "Exception.ExceptionText" ) ) ); } else { mErrorTitle = tr( "Dom Exception" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Could not get WCS capabilities in the expected format (DTD): no %1 found.\nThis might be due to an incorrect WCS Server URL.\nTag:%3\nResponse was:\n%4" ) - .arg( "Capabilities", + .arg( QStringLiteral( "Capabilities" ), docElem.tagName(), QString( xml ) ); } @@ -495,13 +495,13 @@ bool QgsWcsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWcsCapa return false; } - capabilities.version = docElem.attribute( "version" ); + capabilities.version = docElem.attribute( QStringLiteral( "version" ) ); mVersion = capabilities.version; - if ( !mVersion.startsWith( "1.0" ) && !mVersion.startsWith( "1.1" ) ) + if ( !mVersion.startsWith( QLatin1String( "1.0" ) ) && !mVersion.startsWith( QLatin1String( "1.1" ) ) ) { mErrorTitle = tr( "Version not supported" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "WCS server version %1 is not supported by QGIS (supported versions: 1.0.0, 1.1.0, 1.1.2)" ) .arg( mVersion ); @@ -510,31 +510,31 @@ bool QgsWcsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWcsCapa return false; } - if ( mVersion.startsWith( "1.0" ) ) + if ( mVersion.startsWith( QLatin1String( "1.0" ) ) ) { - capabilities.title = domElementText( docElem, "Service.name" ); - capabilities.abstract = domElementText( docElem, "Service.description" ); + capabilities.title = domElementText( docElem, QStringLiteral( "Service.name" ) ); + capabilities.abstract = domElementText( docElem, QStringLiteral( "Service.description" ) ); // There is also "label" in 1.0 - capabilities.getCoverageGetUrl = domElement( docElem, "Capability.Request.GetCoverage.DCPType.HTTP.Get.OnlineResource" ).attribute( "xlink:href" ); + capabilities.getCoverageGetUrl = domElement( docElem, QStringLiteral( "Capability.Request.GetCoverage.DCPType.HTTP.Get.OnlineResource" ) ).attribute( QStringLiteral( "xlink:href" ) ); - parseContentMetadata( domElement( docElem, "ContentMetadata" ), capabilities.contents ); + parseContentMetadata( domElement( docElem, QStringLiteral( "ContentMetadata" ) ), capabilities.contents ); } - else if ( mVersion.startsWith( "1.1" ) ) + else if ( mVersion.startsWith( QLatin1String( "1.1" ) ) ) { - capabilities.title = domElementText( docElem, "ServiceIdentification.Title" ); - capabilities.abstract = domElementText( docElem, "ServiceIdentification.Abstract" ); + capabilities.title = domElementText( docElem, QStringLiteral( "ServiceIdentification.Title" ) ); + capabilities.abstract = domElementText( docElem, QStringLiteral( "ServiceIdentification.Abstract" ) ); - QList<QDomElement> operationElements = domElements( docElem, "OperationsMetadata.Operation" ); + QList<QDomElement> operationElements = domElements( docElem, QStringLiteral( "OperationsMetadata.Operation" ) ); Q_FOREACH ( const QDomElement& el, operationElements ) { - if ( el.attribute( "name" ) == "GetCoverage" ) + if ( el.attribute( QStringLiteral( "name" ) ) == QLatin1String( "GetCoverage" ) ) { - capabilities.getCoverageGetUrl = domElement( el, "DCP.HTTP.Get" ).attribute( "xlink:href" ); + capabilities.getCoverageGetUrl = domElement( el, QStringLiteral( "DCP.HTTP.Get" ) ).attribute( QStringLiteral( "xlink:href" ) ); } } - parseCoverageSummary( domElement( docElem, "Contents" ), capabilities.contents ); + parseCoverageSummary( domElement( docElem, QStringLiteral( "Contents" ) ), capabilities.contents ); } return true; @@ -593,7 +593,7 @@ QList<QDomElement> QgsWcsCapabilities::domElements( const QDomElement &element, } else { - list.append( domElements( el, names.join( "." ) ) ); + list.append( domElements( el, names.join( QStringLiteral( "." ) ) ) ); } } } @@ -626,7 +626,7 @@ QDomElement QgsWcsCapabilities::domElement( const QDomElement &element, const QS return el; } names.removeFirst(); - return domElement( el, names.join( "." ) ); + return domElement( el, names.join( QStringLiteral( "." ) ) ); } QString QgsWcsCapabilities::domElementText( const QDomElement &element, const QString & path ) @@ -695,7 +695,7 @@ void QgsWcsCapabilities::parseContentMetadata( QDomElement const & e, QgsWcsCove { QString tagName = stripNS( el.tagName() ); - if ( tagName == "CoverageOfferingBrief" ) + if ( tagName == QLatin1String( "CoverageOfferingBrief" ) ) { QgsWcsCoverageSummary subCoverageSummary; @@ -717,11 +717,11 @@ void QgsWcsCapabilities::parseCoverageOfferingBrief( QDomElement const & e, QgsW Q_UNUSED( parent ); coverageSummary.orderId = ++mCoverageCount; - coverageSummary.identifier = firstChildText( e, "name" ); - coverageSummary.title = firstChildText( e, "label" ); - coverageSummary.abstract = firstChildText( e, "description" ); + coverageSummary.identifier = firstChildText( e, QStringLiteral( "name" ) ); + coverageSummary.title = firstChildText( e, QStringLiteral( "label" ) ); + coverageSummary.abstract = firstChildText( e, QStringLiteral( "description" ) ); - QList<QDomElement> posElements = domElements( e, "lonLatEnvelope.pos" ); + QList<QDomElement> posElements = domElements( e, QStringLiteral( "lonLatEnvelope.pos" ) ); if ( posElements.size() != 2 ) { QgsDebugMsg( "Wrong number of pos elements" ); @@ -762,7 +762,7 @@ bool QgsWcsCapabilities::convertToDom( QByteArray const &xml ) if ( !contentSuccess ) { mErrorTitle = tr( "Dom Exception" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Could not get WCS capabilities: %1 at line %2 column %3\nThis is probably due to an incorrect WCS Server URL.\nResponse was:\n\n%4" ) .arg( errorMsg ) .arg( errorLine ) @@ -786,12 +786,12 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom10( QByteArray const &xml, QgsW QgsDebugMsg( "testing tagName " + docElem.tagName() ); QString tagName = stripNS( docElem.tagName() ); - if ( tagName != "CoverageDescription" ) + if ( tagName != QLatin1String( "CoverageDescription" ) ) { mErrorTitle = tr( "Dom Exception" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Could not get WCS capabilities in the expected format (DTD): no %1 found.\nThis might be due to an incorrect WCS Server URL.\nTag:%3\nResponse was:\n%4" ) - .arg( "CoverageDescription", + .arg( QStringLiteral( "CoverageDescription" ), docElem.tagName(), QString( xml ) ); @@ -800,42 +800,42 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom10( QByteArray const &xml, QgsW return false; } - QDomElement coverageOfferingElement = firstChild( docElem, "CoverageOffering" ); + QDomElement coverageOfferingElement = firstChild( docElem, QStringLiteral( "CoverageOffering" ) ); if ( coverageOfferingElement.isNull() ) return false; - QDomElement supportedCRSsElement = firstChild( coverageOfferingElement, "supportedCRSs" ); + QDomElement supportedCRSsElement = firstChild( coverageOfferingElement, QStringLiteral( "supportedCRSs" ) ); // requestResponseCRSs and requestCRSs + responseCRSs are alternatives - coverage->supportedCrs = domElementsTexts( coverageOfferingElement, "supportedCRSs.requestResponseCRSs" ); + coverage->supportedCrs = domElementsTexts( coverageOfferingElement, QStringLiteral( "supportedCRSs.requestResponseCRSs" ) ); // TODO: requestCRSs, responseCRSs - must be then implemented also in provider //QgsDebugMsg( "supportedCrs = " + coverage->supportedCrs.join( "," ) ); - coverage->nativeCrs = domElementText( coverageOfferingElement, "supportedCRSs.nativeCRSs" ); + coverage->nativeCrs = domElementText( coverageOfferingElement, QStringLiteral( "supportedCRSs.nativeCRSs" ) ); // may be GTiff, GeoTIFF, TIFF, GIF, .... - coverage->supportedFormat = domElementsTexts( coverageOfferingElement, "supportedFormats.formats" ); + coverage->supportedFormat = domElementsTexts( coverageOfferingElement, QStringLiteral( "supportedFormats.formats" ) ); QgsDebugMsg( "supportedFormat = " + coverage->supportedFormat.join( "," ) ); // spatialDomain and Grid/RectifiedGrid are optional according to specificationi. // If missing, we cannot get native resolution and size. - QDomElement gridElement = domElement( coverageOfferingElement, "domainSet.spatialDomain.RectifiedGrid" ); + QDomElement gridElement = domElement( coverageOfferingElement, QStringLiteral( "domainSet.spatialDomain.RectifiedGrid" ) ); if ( gridElement.isNull() ) { // Grid has also GridEnvelope from which we can get coverage size but it does not - gridElement = domElement( coverageOfferingElement, "domainSet.spatialDomain.Grid" ); + gridElement = domElement( coverageOfferingElement, QStringLiteral( "domainSet.spatialDomain.Grid" ) ); } // If supportedCRSs.nativeCRSs is not defined we try to get it from RectifiedGrid if ( coverage->nativeCrs.isEmpty() ) { - coverage->nativeCrs = gridElement.attribute( "srsName" ); + coverage->nativeCrs = gridElement.attribute( QStringLiteral( "srsName" ) ); } if ( !gridElement.isNull() ) { - QList<int> low = parseInts( domElementText( gridElement, "limits.GridEnvelope.low" ) ); - QList<int> high = parseInts( domElementText( gridElement, "limits.GridEnvelope.high" ) ); + QList<int> low = parseInts( domElementText( gridElement, QStringLiteral( "limits.GridEnvelope.low" ) ) ); + QList<int> high = parseInts( domElementText( gridElement, QStringLiteral( "limits.GridEnvelope.high" ) ) ); if ( low.size() == 2 && high.size() == 2 ) { // low/high are indexes in grid -> size is hight - low + 1 @@ -857,15 +857,15 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom10( QByteArray const &xml, QgsW // or recalc resolution from rotated grid to base CRS } - QList<QDomElement> envelopeElements = domElements( coverageOfferingElement, "domainSet.spatialDomain.Envelope" ); + QList<QDomElement> envelopeElements = domElements( coverageOfferingElement, QStringLiteral( "domainSet.spatialDomain.Envelope" ) ); QgsDebugMsg( QString( "%1 envelopeElements found" ).arg( envelopeElements.size() ) ); Q_FOREACH ( const QDomElement& el, envelopeElements ) { - QString srsName = el.attribute( "srsName" ); + QString srsName = el.attribute( QStringLiteral( "srsName" ) ); - QList<QDomElement> posElements = domElements( el, "pos" ); + QList<QDomElement> posElements = domElements( el, QStringLiteral( "pos" ) ); if ( posElements.size() != 2 ) { QgsDebugMsg( "Wrong number of pos elements" ); @@ -882,17 +882,17 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom10( QByteArray const &xml, QgsW } } - coverage->times = domElementsTexts( coverageOfferingElement, "domainSet.temporalDomain.timePosition" ); + coverage->times = domElementsTexts( coverageOfferingElement, QStringLiteral( "domainSet.temporalDomain.timePosition" ) ); - QList<QDomElement> timePeriodElements = domElements( coverageOfferingElement, "domainSet.temporalDomain.timePeriod" ); + QList<QDomElement> timePeriodElements = domElements( coverageOfferingElement, QStringLiteral( "domainSet.temporalDomain.timePeriod" ) ); QgsDebugMsg( QString( "%1 timePeriod found" ).arg( timePeriodElements.size() ) ); Q_FOREACH ( const QDomElement& el, timePeriodElements ) { - QString beginPosition = domElementText( el, "beginPosition" ); - QString endPosition = domElementText( el, "endPosition" ); - QString timeResolution = domElementText( el, "timeResolution" ); + QString beginPosition = domElementText( el, QStringLiteral( "beginPosition" ) ); + QString endPosition = domElementText( el, QStringLiteral( "endPosition" ) ); + QString timeResolution = domElementText( el, QStringLiteral( "timeResolution" ) ); // Format used in request QString time = beginPosition + '/' + endPosition; if ( !timeResolution.isEmpty() ) @@ -941,12 +941,12 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom11( QByteArray const &xml, QgsW QgsDebugMsg( "testing tagName " + docElem.tagName() ); QString tagName = stripNS( docElem.tagName() ); - if ( tagName != "CoverageDescriptions" ) + if ( tagName != QLatin1String( "CoverageDescriptions" ) ) { mErrorTitle = tr( "Dom Exception" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Could not get WCS capabilities in the expected format (DTD): no %1 found.\nThis might be due to an incorrect WCS Server URL.\nTag:%3\nResponse was:\n%4" ) - .arg( "CoverageDescriptions", + .arg( QStringLiteral( "CoverageDescriptions" ), docElem.tagName(), QString( xml ) ); @@ -959,19 +959,19 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom11( QByteArray const &xml, QgsW // but while at least one BoundingBox is mandatory, it does not have to be urn:ogc:def:crs:OGC::imageCRS // TODO: if BoundingBox with crs=urn:ogc:def:crs:OGC::imageCRS is not found, // we could calculate image size from GridCRS.GridOffsets (if available) - QList<QDomElement> boundingBoxElements = domElements( docElem, "CoverageDescription.Domain.SpatialDomain.BoundingBox" ); + QList<QDomElement> boundingBoxElements = domElements( docElem, QStringLiteral( "CoverageDescription.Domain.SpatialDomain.BoundingBox" ) ); QgsDebugMsg( QString( "%1 BoundingBox found" ).arg( boundingBoxElements.size() ) ); Q_FOREACH ( const QDomElement& el, boundingBoxElements ) { - QString authid = crsUrnToAuthId( el.attribute( "crs" ) ); - QList<double> low = parseDoubles( domElementText( el, "LowerCorner" ) ); - QList<double> high = parseDoubles( domElementText( el, "UpperCorner" ) ); + QString authid = crsUrnToAuthId( el.attribute( QStringLiteral( "crs" ) ) ); + QList<double> low = parseDoubles( domElementText( el, QStringLiteral( "LowerCorner" ) ) ); + QList<double> high = parseDoubles( domElementText( el, QStringLiteral( "UpperCorner" ) ) ); if ( low.size() != 2 && high.size() != 2 ) continue; - if ( el.attribute( "crs" ) == "urn:ogc:def:crs:OGC::imageCRS" ) + if ( el.attribute( QStringLiteral( "crs" ) ) == QLatin1String( "urn:ogc:def:crs:OGC::imageCRS" ) ) { coverage->width = ( int )( high[0] - low[0] + 1 ); coverage->height = ( int )( high[1] - low[1] + 1 ); @@ -997,11 +997,11 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom11( QByteArray const &xml, QgsW QgsDebugMsg( QString( "width = %1 height = %2" ).arg( coverage->width ).arg( coverage->height ) ); // Each georectified coverage should have GridCRS - QDomElement gridCRSElement = domElement( docElem, "CoverageDescription.Domain.SpatialDomain.GridCRS" ); + QDomElement gridCRSElement = domElement( docElem, QStringLiteral( "CoverageDescription.Domain.SpatialDomain.GridCRS" ) ); if ( !gridCRSElement.isNull() ) { - QString crsUrn = firstChildText( gridCRSElement, "GridBaseCRS" ); + QString crsUrn = firstChildText( gridCRSElement, QStringLiteral( "GridBaseCRS" ) ); coverage->nativeCrs = crsUrnToAuthId( crsUrn ); QgsDebugMsg( "nativeCrs = " + coverage->nativeCrs ); @@ -1009,17 +1009,17 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom11( QByteArray const &xml, QgsW // if urn:ogc:def:crs:OGC::imageCRS BoundingBox was not found } - coverage->times = domElementsTexts( docElem, "CoverageDescription.Domain.TemporalDomain.timePosition" ); + coverage->times = domElementsTexts( docElem, QStringLiteral( "CoverageDescription.Domain.TemporalDomain.timePosition" ) ); - QList<QDomElement> timePeriodElements = domElements( docElem, "CoverageDescription.Domain.TemporalDomain.timePeriod" ); + QList<QDomElement> timePeriodElements = domElements( docElem, QStringLiteral( "CoverageDescription.Domain.TemporalDomain.timePeriod" ) ); QgsDebugMsg( QString( "%1 timePeriod found" ).arg( timePeriodElements.size() ) ); Q_FOREACH ( const QDomElement& el, timePeriodElements ) { - QString beginPosition = domElementText( el, "beginTime" ); - QString endPosition = domElementText( el, "endTime" ); - QString timeResolution = domElementText( el, "timeResolution" ); + QString beginPosition = domElementText( el, QStringLiteral( "beginTime" ) ); + QString endPosition = domElementText( el, QStringLiteral( "endTime" ) ); + QString timeResolution = domElementText( el, QStringLiteral( "timeResolution" ) ); // Format used in request QString time = beginPosition + '/' + endPosition; if ( !timeResolution.isEmpty() ) @@ -1041,7 +1041,7 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom11( QByteArray const &xml, QgsW } } - QStringList formats = domElementsTexts( docElem, "CoverageDescription.SupportedFormat" ); + QStringList formats = domElementsTexts( docElem, QStringLiteral( "CoverageDescription.SupportedFormat" ) ); // There could be formats from GetCapabilities if ( !formats.isEmpty() ) { @@ -1049,7 +1049,7 @@ bool QgsWcsCapabilities::parseDescribeCoverageDom11( QByteArray const &xml, QgsW } - QStringList crss = domElementsTexts( docElem, "CoverageDescription.SupportedCRS" ); + QStringList crss = domElementsTexts( docElem, QStringLiteral( "CoverageDescription.SupportedCRS" ) ); QSet<QString> authids; // Set, in case one CRS is in more formats (URN, non URN) Q_FOREACH ( const QString& crs, crss ) { @@ -1070,9 +1070,9 @@ void QgsWcsCapabilities::parseCoverageSummary( QDomElement const & e, QgsWcsCove { coverageSummary.orderId = ++mCoverageCount; - coverageSummary.identifier = firstChildText( e, "Identifier" ); - coverageSummary.title = firstChildText( e, "Title" ); - coverageSummary.abstract = firstChildText( e, "Abstract" ); + coverageSummary.identifier = firstChildText( e, QStringLiteral( "Identifier" ) ); + coverageSummary.title = firstChildText( e, QStringLiteral( "Title" ) ); + coverageSummary.abstract = firstChildText( e, QStringLiteral( "Abstract" ) ); QDomNode n1 = e.firstChild(); while ( !n1.isNull() ) @@ -1083,21 +1083,21 @@ void QgsWcsCapabilities::parseCoverageSummary( QDomElement const & e, QgsWcsCove QString tagName = stripNS( el.tagName() ); QgsDebugMsg( tagName + " : " + el.text() ); - if ( tagName == "SupportedFormat" ) + if ( tagName == QLatin1String( "SupportedFormat" ) ) { // image/tiff, ... // Formats may be here (UMN Mapserver) or may not (GeoServer) coverageSummary.supportedFormat << el.text(); } - else if ( tagName == "SupportedCRS" ) + else if ( tagName == QLatin1String( "SupportedCRS" ) ) { // TODO: SupportedCRS may be URL referencing a document coverageSummary.supportedCrs << crsUrnToAuthId( el.text() ); } - else if ( tagName == "WGS84BoundingBox" ) + else if ( tagName == QLatin1String( "WGS84BoundingBox" ) ) { - QList<double> low = parseDoubles( domElementText( el, "LowerCorner" ) ); - QList<double> high = parseDoubles( domElementText( el, "UpperCorner" ) ); + QList<double> low = parseDoubles( domElementText( el, QStringLiteral( "LowerCorner" ) ) ); + QList<double> high = parseDoubles( domElementText( el, QStringLiteral( "UpperCorner" ) ) ); if ( low.size() == 2 && high.size() == 2 ) { @@ -1118,7 +1118,7 @@ void QgsWcsCapabilities::parseCoverageSummary( QDomElement const & e, QgsWcsCove { QString tagName = stripNS( el.tagName() ); - if ( tagName == "CoverageSummary" ) + if ( tagName == QLatin1String( "CoverageSummary" ) ) { QgsDebugMsg( " Nested coverage." ); @@ -1192,23 +1192,23 @@ QString QgsWcsCapabilities::lastErrorFormat() bool QgsWcsCapabilities::setAuthorization( QNetworkRequest &request ) const { - if ( mUri.hasParam( "authcfg" ) && !mUri.param( "authcfg" ).isEmpty() ) + if ( mUri.hasParam( QStringLiteral( "authcfg" ) ) && !mUri.param( QStringLiteral( "authcfg" ) ).isEmpty() ) { - return QgsAuthManager::instance()->updateNetworkRequest( request, mUri.param( "authcfg" ) ); + return QgsAuthManager::instance()->updateNetworkRequest( request, mUri.param( QStringLiteral( "authcfg" ) ) ); } - else if ( mUri.hasParam( "username" ) && mUri.hasParam( "password" ) ) + else if ( mUri.hasParam( QStringLiteral( "username" ) ) && mUri.hasParam( QStringLiteral( "password" ) ) ) { QgsDebugMsg( "setAuthorization " + mUri.param( "username" ) ); - request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( mUri.param( "username" ), mUri.param( "password" ) ).toLatin1().toBase64() ); + request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( mUri.param( QStringLiteral( "username" ) ), mUri.param( QStringLiteral( "password" ) ) ).toLatin1().toBase64() ); } return true; } bool QgsWcsCapabilities::setAuthorizationReply( QNetworkReply *reply ) const { - if ( mUri.hasParam( "authcfg" ) && !mUri.param( "authcfg" ).isEmpty() ) + if ( mUri.hasParam( QStringLiteral( "authcfg" ) ) && !mUri.param( QStringLiteral( "authcfg" ) ).isEmpty() ) { - return QgsAuthManager::instance()->updateNetworkReply( reply, mUri.param( "authcfg" ) ); + return QgsAuthManager::instance()->updateNetworkReply( reply, mUri.param( QStringLiteral( "authcfg" ) ) ); } return true; } diff --git a/src/providers/wcs/qgswcsdataitems.cpp b/src/providers/wcs/qgswcsdataitems.cpp index 073725b0e1e3..2226135a110d 100644 --- a/src/providers/wcs/qgswcsdataitems.cpp +++ b/src/providers/wcs/qgswcsdataitems.cpp @@ -28,7 +28,7 @@ QgsWCSConnectionItem::QgsWCSConnectionItem( QgsDataItem* parent, QString name, Q : QgsDataCollectionItem( parent, name, path ) , mUri( uri ) { - mIconName = "mIconWcs.svg"; + mIconName = QStringLiteral( "mIconWcs.svg" ); } QgsWCSConnectionItem::~QgsWCSConnectionItem() @@ -98,7 +98,7 @@ QList<QAction*> QgsWCSConnectionItem::actions() void QgsWCSConnectionItem::editConnection() { - QgsNewHttpConnection nc( nullptr, "/Qgis/connections-wcs/", mName ); + QgsNewHttpConnection nc( nullptr, QStringLiteral( "/Qgis/connections-wcs/" ), mName ); if ( nc.exec() ) { @@ -109,7 +109,7 @@ void QgsWCSConnectionItem::editConnection() void QgsWCSConnectionItem::deleteConnection() { - QgsOwsConnection::deleteConnection( "WCS", mName ); + QgsOwsConnection::deleteConnection( QStringLiteral( "WCS" ), mName ); // the parent should be updated mParent->refresh(); } @@ -118,7 +118,7 @@ void QgsWCSConnectionItem::deleteConnection() // --------------------------------------------------------------------------- QgsWCSLayerItem::QgsWCSLayerItem( QgsDataItem* parent, QString name, QString path, const QgsWcsCapabilitiesProperty& capabilitiesProperty, const QgsDataSourceUri &dataSourceUri, const QgsWcsCoverageSummary& coverageSummary ) - : QgsLayerItem( parent, name, path, QString(), QgsLayerItem::Raster, "wcs" ) + : QgsLayerItem( parent, name, path, QString(), QgsLayerItem::Raster, QStringLiteral( "wcs" ) ) , mCapabilities( capabilitiesProperty ) , mDataSourceUri( dataSourceUri ) , mCoverageSummary( coverageSummary ) @@ -138,7 +138,7 @@ QgsWCSLayerItem::QgsWCSLayerItem( QgsDataItem* parent, QString name, QString pat if ( mChildren.isEmpty() ) { - mIconName = "mIconWcs.svg"; + mIconName = QStringLiteral( "mIconWcs.svg" ); } setState( Populated ); } @@ -150,10 +150,10 @@ QgsWCSLayerItem::~QgsWCSLayerItem() QString QgsWCSLayerItem::createUri() { if ( mCoverageSummary.identifier.isEmpty() ) - return ""; // layer collection + return QLatin1String( "" ); // layer collection // Number of styles must match number of layers - mDataSourceUri.setParam( "identifier", mCoverageSummary.identifier ); + mDataSourceUri.setParam( QStringLiteral( "identifier" ), mCoverageSummary.identifier ); // TODO(?): with WCS 1.0 GetCapabilities does not contain CRS and formats, // to get them we would need to call QgsWcsCapabilities::describeCoverage @@ -167,9 +167,9 @@ QString QgsWCSLayerItem::createUri() //QStringList mimes = QgsGdalProvider::supportedMimes().keys(); QStringList mimes; // prefer tiff - if ( mimes.contains( "image/tiff" ) && mCoverageSummary.supportedFormat.contains( "image/tiff" ) ) + if ( mimes.contains( QStringLiteral( "image/tiff" ) ) && mCoverageSummary.supportedFormat.contains( QStringLiteral( "image/tiff" ) ) ) { - format = "image/tiff"; + format = QStringLiteral( "image/tiff" ); } else { @@ -184,7 +184,7 @@ QString QgsWCSLayerItem::createUri() } if ( !format.isEmpty() ) { - mDataSourceUri.setParam( "format", format ); + mDataSourceUri.setParam( QStringLiteral( "format" ), format ); } QString crs; @@ -207,7 +207,7 @@ QString QgsWCSLayerItem::createUri() } if ( !crs.isEmpty() ) { - mDataSourceUri.setParam( "crs", crs ); + mDataSourceUri.setParam( QStringLiteral( "crs" ), crs ); } return mDataSourceUri.encodedUri(); @@ -219,7 +219,7 @@ QgsWCSRootItem::QgsWCSRootItem( QgsDataItem* parent, QString name, QString path : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconWcs.svg"; + mIconName = QStringLiteral( "mIconWcs.svg" ); populate(); } @@ -232,7 +232,7 @@ QVector<QgsDataItem*>QgsWCSRootItem::createChildren() QVector<QgsDataItem*> connections; Q_FOREACH ( const QString& connName, QgsOwsConnection::connectionList( "WCS" ) ) { - QgsOwsConnection connection( "WCS", connName ); + QgsOwsConnection connection( QStringLiteral( "WCS" ), connName ); QgsDataItem * conn = new QgsWCSConnectionItem( this, connName, mPath + '/' + connName, connection.uri().encodedUri() ); connections.append( conn ); } @@ -265,7 +265,7 @@ void QgsWCSRootItem::connectionsChanged() void QgsWCSRootItem::newConnection() { - QgsNewHttpConnection nc( nullptr, "/Qgis/connections-wcs/" ); + QgsNewHttpConnection nc( nullptr, QStringLiteral( "/Qgis/connections-wcs/" ) ); if ( nc.exec() ) { @@ -290,17 +290,17 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) if ( thePath.isEmpty() ) { // Top level WCS - return new QgsWCSRootItem( parentItem, "WCS", "wcs:" ); + return new QgsWCSRootItem( parentItem, QStringLiteral( "WCS" ), QStringLiteral( "wcs:" ) ); } // path schema: wcs:/connection name (used by OWS) - if ( thePath.startsWith( "wcs:/" ) ) + if ( thePath.startsWith( QLatin1String( "wcs:/" ) ) ) { QString connectionName = thePath.split( '/' ).last(); - if ( QgsOwsConnection::connectionList( "WCS" ).contains( connectionName ) ) + if ( QgsOwsConnection::connectionList( QStringLiteral( "WCS" ) ).contains( connectionName ) ) { - QgsOwsConnection connection( "WCS", connectionName ); - return new QgsWCSConnectionItem( parentItem, "WCS", thePath, connection.uri().encodedUri() ); + QgsOwsConnection connection( QStringLiteral( "WCS" ), connectionName ); + return new QgsWCSConnectionItem( parentItem, QStringLiteral( "WCS" ), thePath, connection.uri().encodedUri() ); } } diff --git a/src/providers/wcs/qgswcsprovider.cpp b/src/providers/wcs/qgswcsprovider.cpp index c22fb399298a..bbb4044461e7 100644 --- a/src/providers/wcs/qgswcsprovider.cpp +++ b/src/providers/wcs/qgswcsprovider.cpp @@ -61,10 +61,10 @@ #define SRVERR(message) QGS_ERROR_MESSAGE(message,"WCS server") #define QGS_ERROR(message) QgsError(message,"WCS provider") -static QString WCS_KEY = "wcs"; -static QString WCS_DESCRIPTION = "OGC Web Coverage Service version 1.0/1.1 data provider"; +static QString WCS_KEY = QStringLiteral( "wcs" ); +static QString WCS_DESCRIPTION = QStringLiteral( "OGC Web Coverage Service version 1.0/1.1 data provider" ); -static QString DEFAULT_LATLON_CRS = "CRS:84"; +static QString DEFAULT_LATLON_CRS = QStringLiteral( "CRS:84" ); // TODO: colortable - use comon baseclass with gdal, mapserver does not support http://trac.osgeo.org/mapserver/ticket/1671 @@ -86,7 +86,7 @@ QgsWcsProvider::QgsWcsProvider( const QString& uri ) , mCachedViewWidth( 0 ) , mCachedViewHeight( 0 ) , mExtentDirty( true ) - , mGetFeatureInfoUrlBase( "" ) + , mGetFeatureInfoUrlBase( QLatin1String( "" ) ) , mErrors( 0 ) , mFixBox( false ) , mFixRotate( false ) @@ -95,7 +95,7 @@ QgsWcsProvider::QgsWcsProvider( const QString& uri ) QgsDebugMsg( "constructing with uri '" + mHttpUri + "'." ); mValid = false; - mCachedMemFilename = QString( "/vsimem/qgis/wcs/%0.dat" ).arg(( qlonglong )this ); + mCachedMemFilename = QStringLiteral( "/vsimem/qgis/wcs/%0.dat" ).arg(( qlonglong )this ); if ( !parseUri( uri ) ) return; @@ -107,9 +107,9 @@ QgsWcsProvider::QgsWcsProvider( const QString& uri ) QgsDataSourceUri capabilitiesUri; capabilitiesUri.setEncodedUri( uri ); // remove non relevant params - capabilitiesUri.removeParam( "identifier" ); - capabilitiesUri.removeParam( "crs" ); - capabilitiesUri.removeParam( "format" ); + capabilitiesUri.removeParam( QStringLiteral( "identifier" ) ); + capabilitiesUri.removeParam( QStringLiteral( "crs" ) ); + capabilitiesUri.removeParam( QStringLiteral( "format" ) ); // TODO: check if successful (add return to capabilities) mCapabilities.setUri( capabilitiesUri ); @@ -133,7 +133,7 @@ QgsWcsProvider::QgsWcsProvider( const QString& uri ) if ( mFormat.isEmpty() ) { // TIFF is known by GDAL - mFormat = mCoverageSummary.supportedFormat.filter( "tif", Qt::CaseInsensitive ).value( 0 ); + mFormat = mCoverageSummary.supportedFormat.filter( QStringLiteral( "tif" ), Qt::CaseInsensitive ).value( 0 ); } if ( mFormat.isEmpty() ) { @@ -155,9 +155,9 @@ QgsWcsProvider::QgsWcsProvider( const QString& uri ) { setCoverageCrs( mCoverageSummary.nativeCrs ); } - else if ( mCoverageSummary.supportedCrs.contains( "EPSG:4326", Qt::CaseInsensitive ) ) + else if ( mCoverageSummary.supportedCrs.contains( QStringLiteral( "EPSG:4326" ), Qt::CaseInsensitive ) ) { - setCoverageCrs( "EPSG:4326" ); + setCoverageCrs( QStringLiteral( "EPSG:4326" ) ); } else if ( !mCoverageSummary.supportedCrs.isEmpty() ) { @@ -388,38 +388,38 @@ bool QgsWcsProvider::parseUri( const QString& uriString ) mMaxWidth = 0; mMaxHeight = 0; - mHttpUri = uri.param( "url" ); + mHttpUri = uri.param( QStringLiteral( "url" ) ); mBaseUrl = prepareUri( mHttpUri ); QgsDebugMsg( "mBaseUrl = " + mBaseUrl ); - mIgnoreGetCoverageUrl = uri.hasParam( "IgnoreGetMapUrl" ); - mIgnoreAxisOrientation = uri.hasParam( "IgnoreAxisOrientation" ); // must be before parsing! - mInvertAxisOrientation = uri.hasParam( "InvertAxisOrientation" ); // must be before parsing! + mIgnoreGetCoverageUrl = uri.hasParam( QStringLiteral( "IgnoreGetMapUrl" ) ); + mIgnoreAxisOrientation = uri.hasParam( QStringLiteral( "IgnoreAxisOrientation" ) ); // must be before parsing! + mInvertAxisOrientation = uri.hasParam( QStringLiteral( "InvertAxisOrientation" ) ); // must be before parsing! - mAuth.mUserName = uri.param( "username" ); + mAuth.mUserName = uri.param( QStringLiteral( "username" ) ); QgsDebugMsg( "set username to " + mAuth.mUserName ); - mAuth.mPassword = uri.param( "password" ); + mAuth.mPassword = uri.param( QStringLiteral( "password" ) ); QgsDebugMsg( "set password to " + mAuth.mPassword ); - if ( uri.hasParam( "authcfg" ) ) + if ( uri.hasParam( QStringLiteral( "authcfg" ) ) ) { - mAuth.mAuthCfg = uri.param( "authcfg" ); + mAuth.mAuthCfg = uri.param( QStringLiteral( "authcfg" ) ); } QgsDebugMsg( "set authcfg to " + mAuth.mAuthCfg ); - mIdentifier = uri.param( "identifier" ); + mIdentifier = uri.param( QStringLiteral( "identifier" ) ); - mTime = uri.param( "time" ); + mTime = uri.param( QStringLiteral( "time" ) ); - setFormat( uri.param( "format" ) ); + setFormat( uri.param( QStringLiteral( "format" ) ) ); - if ( !uri.param( "crs" ).isEmpty() ) + if ( !uri.param( QStringLiteral( "crs" ) ).isEmpty() ) { - setCoverageCrs( uri.param( "crs" ) ); + setCoverageCrs( uri.param( QStringLiteral( "crs" ) ) ); } - QString cache = uri.param( "cache" ); + QString cache = uri.param( QStringLiteral( "cache" ) ); if ( !cache.isEmpty() ) { mCacheLoadControl = QgsNetworkAccessManager::cacheLoadControlFromName( cache ); @@ -435,7 +435,7 @@ QString QgsWcsProvider::prepareUri( QString uri ) const { uri.append( '?' ); } - else if ( uri.right( 1 ) != "?" && uri.right( 1 ) != "&" ) + else if ( uri.right( 1 ) != QLatin1String( "?" ) && uri.right( 1 ) != QLatin1String( "&" ) ) { uri.append( '&' ); } @@ -639,7 +639,7 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int // "The number of axes included, and the order of these axes, shall be as specified // by the referenced CRS." That means inverted for geographic. bool changeXY = false; - if ( !mIgnoreAxisOrientation && ( mCapabilities.version().startsWith( "1.1" ) ) ) + if ( !mIgnoreAxisOrientation && ( mCapabilities.version().startsWith( QLatin1String( "1.1" ) ) ) ) { //create CRS from string QgsCoordinateReferenceSystem theSrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs ); @@ -661,7 +661,7 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int // Mapserver and GDAL are using bbox defined by grid points, i.e. shrinked // by 1 pixel, but Geoserver and ArcGIS are using full bbox including // the space around edge grid points. - if ( mCapabilities.version().startsWith( "1.1" ) && !mFixBox ) + if ( mCapabilities.version().startsWith( QLatin1String( "1.1" ) ) && !mFixBox ) { // shrink the extent to border cells centers by half cell size extent = QgsRectangle( viewExtent.xMinimum() + xRes / 2., viewExtent.yMinimum() + yRes / 2., viewExtent.xMaximum() - xRes / 2., viewExtent.yMaximum() - yRes / 2. ); @@ -677,15 +677,15 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int QUrl url( mIgnoreGetCoverageUrl ? mBaseUrl : mCapabilities.getCoverageUrl() ); // Version 1.0.0, 1.1.0, 1.1.2 - setQueryItem( url, "SERVICE", "WCS" ); - setQueryItem( url, "VERSION", mCapabilities.version() ); - setQueryItem( url, "REQUEST", "GetCoverage" ); - setQueryItem( url, "FORMAT", mFormat ); + setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WCS" ) ); + setQueryItem( url, QStringLiteral( "VERSION" ), mCapabilities.version() ); + setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetCoverage" ) ); + setQueryItem( url, QStringLiteral( "FORMAT" ), mFormat ); // Version 1.0.0 - if ( mCapabilities.version().startsWith( "1.0" ) ) + if ( mCapabilities.version().startsWith( QLatin1String( "1.0" ) ) ) { - setQueryItem( url, "COVERAGE", mIdentifier ); + setQueryItem( url, QStringLiteral( "COVERAGE" ), mIdentifier ); if ( !mTime.isEmpty() ) { // It seems that Mmapserver (6.0.3) WCS 1.1 completely ignores @@ -694,28 +694,28 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int // TimeSequence param is not supported at all. If a coverage is defined // with timeposition in mapfile, the result of GetCoverage is empty // raster (all values 0). - setQueryItem( url, "TIME", mTime ); + setQueryItem( url, QStringLiteral( "TIME" ), mTime ); } - setQueryItem( url, "BBOX", bbox ); - setQueryItem( url, "CRS", crs ); // request BBOX CRS - setQueryItem( url, "RESPONSE_CRS", crs ); // response CRS - setQueryItem( url, "WIDTH", QString::number( pixelWidth ) ); - setQueryItem( url, "HEIGHT", QString::number( pixelHeight ) ); + setQueryItem( url, QStringLiteral( "BBOX" ), bbox ); + setQueryItem( url, QStringLiteral( "CRS" ), crs ); // request BBOX CRS + setQueryItem( url, QStringLiteral( "RESPONSE_CRS" ), crs ); // response CRS + setQueryItem( url, QStringLiteral( "WIDTH" ), QString::number( pixelWidth ) ); + setQueryItem( url, QStringLiteral( "HEIGHT" ), QString::number( pixelHeight ) ); } // Version 1.1.0, 1.1.2 - if ( mCapabilities.version().startsWith( "1.1" ) ) + if ( mCapabilities.version().startsWith( QLatin1String( "1.1" ) ) ) { - setQueryItem( url, "IDENTIFIER", mIdentifier ); - QString crsUrn = QString( "urn:ogc:def:crs:%1::%2" ).arg( crs.split( ':' ).value( 0 ), crs.split( ':' ).value( 1 ) ); + setQueryItem( url, QStringLiteral( "IDENTIFIER" ), mIdentifier ); + QString crsUrn = QStringLiteral( "urn:ogc:def:crs:%1::%2" ).arg( crs.split( ':' ).value( 0 ), crs.split( ':' ).value( 1 ) ); bbox += ',' + crsUrn; if ( !mTime.isEmpty() ) { - setQueryItem( url, "TIMESEQUENCE", mTime ); + setQueryItem( url, QStringLiteral( "TIMESEQUENCE" ), mTime ); } - setQueryItem( url, "BOUNDINGBOX", bbox ); + setQueryItem( url, QStringLiteral( "BOUNDINGBOX" ), bbox ); // Example: // GridBaseCRS=urn:ogc:def:crs:SG:6.6:32618 @@ -724,11 +724,11 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int // GridOrigin=0,0 // GridOffsets=0.0707,-0.0707,0.1414,0.1414& - setQueryItem( url, "GRIDBASECRS", crsUrn ); // response CRS + setQueryItem( url, QStringLiteral( "GRIDBASECRS" ), crsUrn ); // response CRS - setQueryItem( url, "GRIDCS", "urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS" ); + setQueryItem( url, QStringLiteral( "GRIDCS" ), QStringLiteral( "urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS" ) ); - setQueryItem( url, "GRIDTYPE", "urn:ogc:def:method:WCS:1.1:2dSimpleGrid" ); + setQueryItem( url, QStringLiteral( "GRIDTYPE" ), QStringLiteral( "urn:ogc:def:method:WCS:1.1:2dSimpleGrid" ) ); // GridOrigin is BBOX minx, maxy // Note: shifting origin to cell center (not realy necessary nor making sense) @@ -738,7 +738,7 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int QString gridOrigin = QString( changeXY ? "%2,%1" : "%1,%2" ) .arg( qgsDoubleToString( extent.xMinimum() ), qgsDoubleToString( extent.yMaximum() ) ); - setQueryItem( url, "GRIDORIGIN", gridOrigin ); + setQueryItem( url, QStringLiteral( "GRIDORIGIN" ), gridOrigin ); // GridOffsets WCS 1.1: // GridType urn:ogc:def:method:WCS:1.1:2dSimpleGrid : 2 values @@ -758,7 +758,7 @@ void QgsWcsProvider::getCache( int bandNo, QgsRectangle const & viewExtent, int //QString gridOffsets = QString( changeXY ? "%2,0,0,%1" : "%1,0,0,%2" ) .arg( qgsDoubleToString( xRes ), qgsDoubleToString( yOff ) ); - setQueryItem( url, "GRIDOFFSETS", gridOffsets ); + setQueryItem( url, QStringLiteral( "GRIDOFFSETS" ), gridOffsets ); } QgsDebugMsg( QString( "GetCoverage: %1" ).arg( url.toString() ) ); @@ -954,13 +954,13 @@ bool QgsWcsProvider::parseServiceExceptionReportDom( QByteArray const & xml, con //QString version = docElem.attribute("version"); QDomElement e; - if ( wcsVersion.startsWith( "1.0" ) ) + if ( wcsVersion.startsWith( QLatin1String( "1.0" ) ) ) { - e = QgsWcsCapabilities::domElement( docElem, "ServiceException" ); + e = QgsWcsCapabilities::domElement( docElem, QStringLiteral( "ServiceException" ) ); } else // 1.1 { - e = QgsWcsCapabilities::domElement( docElem, "Exception" ); + e = QgsWcsCapabilities::domElement( docElem, QStringLiteral( "Exception" ) ); } parseServiceException( e, wcsVersion, errorTitle, errorText ); @@ -981,39 +981,39 @@ void QgsWcsProvider::parseServiceException( QDomElement const & e, const QString // set up friendly descriptions for the service exception // 1.0 - exceptions["InvalidFormat"] = tr( "Request contains a format not offered by the server." ); - exceptions["CoverageNotDefined"] = tr( "Request is for a Coverage not offered by the service instance." ); - exceptions["CurrentUpdateSequence"] = tr( "Value of (optional) UpdateSequence parameter in GetCapabilities request is equal to current value of service metadata update sequence number." ); - exceptions["InvalidUpdateSequence"] = tr( "Value of (optional) UpdateSequence parameter in GetCapabilities request is greater than current value of service metadata update sequence number." ); + exceptions[QStringLiteral( "InvalidFormat" )] = tr( "Request contains a format not offered by the server." ); + exceptions[QStringLiteral( "CoverageNotDefined" )] = tr( "Request is for a Coverage not offered by the service instance." ); + exceptions[QStringLiteral( "CurrentUpdateSequence" )] = tr( "Value of (optional) UpdateSequence parameter in GetCapabilities request is equal to current value of service metadata update sequence number." ); + exceptions[QStringLiteral( "InvalidUpdateSequence" )] = tr( "Value of (optional) UpdateSequence parameter in GetCapabilities request is greater than current value of service metadata update sequence number." ); // 1.0, 1.1 - exceptions["MissingParameterValue"] = tr( "Request does not include a parameter value, and the server instance did not declare a default value for that dimension." ); - exceptions["InvalidParameterValue"] = tr( "Request contains an invalid parameter value." ); + exceptions[QStringLiteral( "MissingParameterValue" )] = tr( "Request does not include a parameter value, and the server instance did not declare a default value for that dimension." ); + exceptions[QStringLiteral( "InvalidParameterValue" )] = tr( "Request contains an invalid parameter value." ); // 1.1 - exceptions["NoApplicableCode"] = tr( "No other exceptionCode specified by this service and server applies to this exception." ); - exceptions["UnsupportedCombination"] = tr( "Operation request contains an output CRS that can not be used within the output format." ); - exceptions["NotEnoughStorage"] = tr( "Operation request specifies to \"store\" the result, but not enough storage is available to do this." ); + exceptions[QStringLiteral( "NoApplicableCode" )] = tr( "No other exceptionCode specified by this service and server applies to this exception." ); + exceptions[QStringLiteral( "UnsupportedCombination" )] = tr( "Operation request contains an output CRS that can not be used within the output format." ); + exceptions[QStringLiteral( "NotEnoughStorage" )] = tr( "Operation request specifies to \"store\" the result, but not enough storage is available to do this." ); QString seCode; QString seText; - if ( wcsVersion.startsWith( "1.0" ) ) + if ( wcsVersion.startsWith( QLatin1String( "1.0" ) ) ) { - seCode = e.attribute( "code" ); + seCode = e.attribute( QStringLiteral( "code" ) ); seText = e.text(); } else { QStringList codes; - seCode = e.attribute( "exceptionCode" ); + seCode = e.attribute( QStringLiteral( "exceptionCode" ) ); // UMN Mapserver (6.0.3) has messed/switched 'locator' and 'exceptionCode' if ( ! exceptions.contains( seCode ) ) { - seCode = e.attribute( "locator" ); + seCode = e.attribute( QStringLiteral( "locator" ) ); if ( ! exceptions.contains( seCode ) ) { - seCode = ""; + seCode = QLatin1String( "" ); } } - seText = QgsWcsCapabilities::firstChildText( e, "ExceptionText" ); + seText = QgsWcsCapabilities::firstChildText( e, QStringLiteral( "ExceptionText" ) ); } if ( seCode.isEmpty() ) @@ -1086,7 +1086,7 @@ bool QgsWcsProvider::calculateExtent() const // box to the user's selected CRS if ( !mCoordinateTransform.isValid() ) { - QgsCoordinateReferenceSystem qgisSrsSource = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); + QgsCoordinateReferenceSystem qgisSrsSource = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); QgsCoordinateReferenceSystem qgisSrsDest = QgsCoordinateReferenceSystem::fromOgcWmsCrs( mCoverageCrs ); //QgsDebugMsg( "qgisSrsSource: " + qgisSrsSource.toWkt() ); @@ -1198,16 +1198,16 @@ QString QgsWcsProvider::coverageMetadata( const QgsWcsCoverageSummary &coverage QString metadata; // Use a nested table - metadata += "<tr><td>"; - metadata += "<table width=\"100%\">"; + metadata += QLatin1String( "<tr><td>" ); + metadata += QLatin1String( "<table width=\"100%\">" ); // Table header - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Property" ); - metadata += "</th>"; - metadata += "<th class=\"glossy\">"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<th class=\"glossy\">" ); metadata += tr( "Value" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); metadata += htmlRow( tr( "Name (identifier)" ), coverage.identifier ); metadata += htmlRow( tr( "Title" ), coverage.title ); @@ -1248,21 +1248,21 @@ QString QgsWcsProvider::coverageMetadata( const QgsWcsCoverageSummary &coverage #endif // Close the nested table - metadata += "</table>"; - metadata += "</td></tr>"; + metadata += QLatin1String( "</table>" ); + metadata += QLatin1String( "</td></tr>" ); return metadata; } QString QgsWcsProvider::metadata() { - QString metadata = ""; + QString metadata = QLatin1String( "" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); - metadata += "</a> <a href=\"#coverages\">"; + metadata += QLatin1String( "</a> <a href=\"#coverages\">" ); metadata += tr( "Coverages" ); - metadata += "</a>"; + metadata += QLatin1String( "</a>" ); #if 0 // TODO @@ -1271,24 +1271,24 @@ QString QgsWcsProvider::metadata() metadata += "</a> "; #endif - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Server Properties section - metadata += "<tr><th class=\"glossy\"><a name=\"serverproperties\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"serverproperties\"></a>" ); metadata += tr( "Server Properties" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); // Use a nested table - metadata += "<tr><td>"; - metadata += "<table width=\"100%\">"; + metadata += QLatin1String( "<tr><td>" ); + metadata += QLatin1String( "<table width=\"100%\">" ); // Table header - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Property" ); - metadata += "</th>"; - metadata += "<th class=\"glossy\">"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<th class=\"glossy\">" ); metadata += tr( "Value" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); metadata += htmlRow(( "WCS Version" ), mCapabilities.version() ); metadata += htmlRow( tr( "Title" ), mCapabilities.capabilities().title ); @@ -1306,16 +1306,16 @@ QString QgsWcsProvider::metadata() metadata += htmlRow( tr( "Image Formats" ), mCapabilities.capability.request.getMap.format.join( "<br />" ) ); metadata += htmlRow( tr( "GetCapabilitiesUrl" ), mBaseUrl ); #endif - metadata += htmlRow( tr( "Get Coverage Url" ), mCapabilities.getCoverageUrl() + ( mIgnoreGetCoverageUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : "" ) ); + metadata += htmlRow( tr( "Get Coverage Url" ), mCapabilities.getCoverageUrl() + ( mIgnoreGetCoverageUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : QLatin1String( "" ) ) ); // Close the nested table - metadata += "</table>"; - metadata += "</td></tr>"; + metadata += QLatin1String( "</table>" ); + metadata += QLatin1String( "</td></tr>" ); // Coverage properties - metadata += "<tr><th class=\"glossy\"><a name=\"coverages\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"coverages\"></a>" ); metadata += tr( "Coverages" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); // Dialog takes too long to open if there are too many coverages (1000 for example) int count = 0; @@ -1325,7 +1325,7 @@ QString QgsWcsProvider::metadata() count++; if ( count >= 100 ) break; } - metadata += "</table>"; + metadata += QLatin1String( "</table>" ); if ( count < mCapabilities.coverages().size() ) { metadata += tr( "And %1 more coverages" ).arg( mCapabilities.coverages().size() - count ); @@ -1754,15 +1754,15 @@ void QgsWcsDownloadHandler::cacheReplyFinished() // Content type examples: text/xml // application/vnd.ogc.se_xml;charset=UTF-8 // application/xml - if ( contentType.startsWith( "text/", Qt::CaseInsensitive ) || - contentType.toLower() == "application/xml" || - contentType.startsWith( "application/vnd.ogc.se_xml", Qt::CaseInsensitive ) ) + if ( contentType.startsWith( QLatin1String( "text/" ), Qt::CaseInsensitive ) || + contentType.toLower() == QLatin1String( "application/xml" ) || + contentType.startsWith( QLatin1String( "application/vnd.ogc.se_xml" ), Qt::CaseInsensitive ) ) { QString errorTitle, errorText; QByteArray text = mCacheReply->readAll(); - if (( contentType.toLower() == "text/xml" || - contentType.toLower() == "application/xml" || - contentType.startsWith( "application/vnd.ogc.se_xml", Qt::CaseInsensitive ) ) + if (( contentType.toLower() == QLatin1String( "text/xml" ) || + contentType.toLower() == QLatin1String( "application/xml" ) || + contentType.startsWith( QLatin1String( "application/vnd.ogc.se_xml" ), Qt::CaseInsensitive ) ) && QgsWcsProvider::parseServiceExceptionReportDom( text, mWcsVersion, errorTitle, errorText ) ) { mCachedError.append( SRVERR( tr( "Map request error:<br>Title: %1<br>Error: %2<br>URL: <a href='%3'>%3</a>)" ) @@ -1815,7 +1815,7 @@ void QgsWcsDownloadHandler::cacheReplyFinished() QgsMessageLog::logMessage( tr( "More than 2 parts (%1) received" ).arg( parser.parts() ), tr( "WCS" ) ); } - QString transferEncoding = parser.rawHeader( 1, QString( "Content-Transfer-Encoding" ).toLatin1() ); + QString transferEncoding = parser.rawHeader( 1, QStringLiteral( "Content-Transfer-Encoding" ).toLatin1() ); QgsDebugMsg( "transferEncoding = " + transferEncoding ); // It may happen (GeoServer) that in part header is for example @@ -1845,11 +1845,11 @@ void QgsWcsDownloadHandler::cacheReplyFinished() return; } - if ( transferEncoding == "binary" ) + if ( transferEncoding == QLatin1String( "binary" ) ) { mCachedData = body; } - else if ( transferEncoding == "base64" ) + else if ( transferEncoding == QLatin1String( "base64" ) ) { mCachedData = QByteArray::fromBase64( body ); } diff --git a/src/providers/wcs/qgswcsprovider.h b/src/providers/wcs/qgswcsprovider.h index 07f3b5d38de4..3fb3e5580cce 100644 --- a/src/providers/wcs/qgswcsprovider.h +++ b/src/providers/wcs/qgswcsprovider.h @@ -67,7 +67,7 @@ struct QgsWcsAuthorization } else if ( !mUserName.isNull() || !mPassword.isNull() ) { - request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); + request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); } return true; } diff --git a/src/providers/wcs/qgswcssourceselect.cpp b/src/providers/wcs/qgswcssourceselect.cpp index d49b434cbe4a..c44fe5338d7e 100644 --- a/src/providers/wcs/qgswcssourceselect.cpp +++ b/src/providers/wcs/qgswcssourceselect.cpp @@ -28,7 +28,7 @@ #include <QWidget> QgsWCSSourceSelect::QgsWCSSourceSelect( QWidget * parent, Qt::WindowFlags fl, bool managerMode, bool embeddedMode ) - : QgsOWSSourceSelect( "WCS", parent, fl, managerMode, embeddedMode ) + : QgsOWSSourceSelect( QStringLiteral( "WCS" ), parent, fl, managerMode, embeddedMode ) { // Hide irrelevant widgets mWMSGroupBox->hide(); @@ -53,7 +53,7 @@ void QgsWCSSourceSelect::populateLayerList() QgsDataSourceUri uri = mUri; QString cache = QgsNetworkAccessManager::cacheLoadControlName( selectedCacheLoadControl() ); - uri.setParam( "cache", cache ); + uri.setParam( QStringLiteral( "cache" ), cache ); mCapabilities.setUri( uri ); @@ -119,7 +119,7 @@ void QgsWCSSourceSelect::addClicked() QString identifier = selectedIdentifier(); if ( identifier.isEmpty() ) { return; } - uri.setParam( "identifier", identifier ); + uri.setParam( QStringLiteral( "identifier" ), identifier ); // Set crs only if necessary (multiple offered), so that we can decide in the // provider if WCS 1.0 with RESPONSE_CRS has to be used. Not perfect, they can @@ -128,27 +128,27 @@ void QgsWCSSourceSelect::addClicked() // without that param user is asked for CRS //if ( selectedLayersCRSs().size() > 1 ) //{ - uri.setParam( "crs", selectedCrs() ); + uri.setParam( QStringLiteral( "crs" ), selectedCrs() ); //} QgsDebugMsg( "selectedFormat = " + selectedFormat() ); if ( !selectedFormat().isEmpty() ) { - uri.setParam( "format", selectedFormat() ); + uri.setParam( QStringLiteral( "format" ), selectedFormat() ); } QgsDebugMsg( "selectedTime = " + selectedTime() ); if ( !selectedTime().isEmpty() ) { - uri.setParam( "time", selectedTime() ); + uri.setParam( QStringLiteral( "time" ), selectedTime() ); } QString cache; QgsDebugMsg( QString( "selectedCacheLoadControl = %1" ).arg( selectedCacheLoadControl() ) ); cache = QgsNetworkAccessManager::cacheLoadControlName( selectedCacheLoadControl() ); - uri.setParam( "cache", cache ); + uri.setParam( QStringLiteral( "cache" ), cache ); - emit addRasterLayer( uri.encodedUri(), identifier, "wcs" ); + emit addRasterLayer( uri.encodedUri(), identifier, QStringLiteral( "wcs" ) ); } void QgsWCSSourceSelect::on_mLayersTreeWidget_itemSelectionChanged() @@ -198,7 +198,7 @@ QList<QgsWCSSourceSelect::SupportedFormat> QgsWCSSourceSelect::providerFormats() SupportedFormat format = { mime, mimes.value( mime ) }; // prefer tiff - if ( mime == "image/tiff" ) + if ( mime == QLatin1String( "image/tiff" ) ) { formats.prepend( format ); } diff --git a/src/providers/wfs/qgswfscapabilities.cpp b/src/providers/wfs/qgswfscapabilities.cpp index 50da4f219ad4..0726a0824dc9 100644 --- a/src/providers/wfs/qgswfscapabilities.cpp +++ b/src/providers/wfs/qgswfscapabilities.cpp @@ -38,14 +38,14 @@ QgsWfsCapabilities::~QgsWfsCapabilities() bool QgsWfsCapabilities::requestCapabilities( bool synchronous, bool forceRefresh ) { QUrl url( baseURL() ); - url.addQueryItem( "REQUEST", "GetCapabilities" ); + url.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetCapabilities" ) ); const QString& version = mUri.version(); if ( version == QgsWFSConstants::VERSION_AUTO ) // MapServer honours the order with the first value being the preferred one - url.addQueryItem( "ACCEPTVERSIONS", "2.0.0,1.1.0,1.0.0" ); + url.addQueryItem( QStringLiteral( "ACCEPTVERSIONS" ), QStringLiteral( "2.0.0,1.1.0,1.0.0" ) ); else - url.addQueryItem( "VERSION", version ); + url.addQueryItem( QStringLiteral( "VERSION" ), version ); if ( !sendGET( url, synchronous, forceRefresh ) ) { @@ -66,7 +66,7 @@ void QgsWfsCapabilities::Capabilities::clear() supportsHits = false; supportsPaging = false; supportsJoins = false; - version = ""; + version = QLatin1String( "" ); featureTypes.clear(); spatialPredicatesList.clear(); functionList.clear(); @@ -81,7 +81,7 @@ QString QgsWfsCapabilities::Capabilities::addPrefixIfNeeded( const QString& name if ( name.contains( ':' ) ) return name; if ( setAmbiguousUnprefixedTypename.contains( name ) ) - return ""; + return QLatin1String( "" ); return mapUnprefixedTypenameToPrefixedTypename[name]; } @@ -105,10 +105,10 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() QDomElement doc = capabilitiesDocument.documentElement(); // handle exceptions - if ( doc.tagName() == "ExceptionReport" ) + if ( doc.tagName() == QLatin1String( "ExceptionReport" ) ) { QDomNode ex = doc.firstChild(); - QString exc = ex.toElement().attribute( "exceptionCode", "Exception" ); + QString exc = ex.toElement().attribute( QStringLiteral( "exceptionCode" ), QStringLiteral( "Exception" ) ); QDomElement ext = ex.firstChild().toElement(); mErrorCode = QgsWfsRequest::ServerExceptionError; mErrorMessage = exc + ": " + ext.firstChild().nodeValue(); @@ -119,10 +119,10 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() mCaps.clear(); //test wfs version - mCaps.version = doc.attribute( "version" ); - if ( !mCaps.version.startsWith( "1.0" ) && - !mCaps.version.startsWith( "1.1" ) && - !mCaps.version.startsWith( "2.0" ) ) + mCaps.version = doc.attribute( QStringLiteral( "version" ) ); + if ( !mCaps.version.startsWith( QLatin1String( "1.0" ) ) && + !mCaps.version.startsWith( QLatin1String( "1.1" ) ) && + !mCaps.version.startsWith( QLatin1String( "2.0" ) ) ) { mErrorCode = WFSVersionNotSupported; mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version ); @@ -135,52 +135,52 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() // WFS 1.1 implementation too I think, but in the examples of the GetCapabilites // response of the WFS 1.1 standard (and in common implementations), this is // explictly advertized - if ( mCaps.version.startsWith( "2.0" ) ) + if ( mCaps.version.startsWith( QLatin1String( "2.0" ) ) ) mCaps.supportsHits = true; // Note: for conveniency, we do not use the elementsByTagNameNS() method as // the WFS and OWS namespaces URI are not the same in all versions // find <ows:OperationsMetadata> - QDomElement operationsMetadataElem = doc.firstChildElement( "OperationsMetadata" ); + QDomElement operationsMetadataElem = doc.firstChildElement( QStringLiteral( "OperationsMetadata" ) ); if ( !operationsMetadataElem.isNull() ) { - QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( "Constraint" ); + QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Constraint" ) ); for ( int i = 0; i < contraintList.size(); ++i ) { QDomElement contraint = contraintList.at( i ).toElement(); - if ( contraint.attribute( "name" ) == "DefaultMaxFeatures" /* WFS 1.1 */ ) + if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "DefaultMaxFeatures" ) /* WFS 1.1 */ ) { - QDomElement value = contraint.firstChildElement( "Value" ); + QDomElement value = contraint.firstChildElement( QStringLiteral( "Value" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } } - else if ( contraint.attribute( "name" ) == "CountDefault" /* WFS 2.0 (e.g. MapServer) */ ) + else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) /* WFS 2.0 (e.g. MapServer) */ ) { - QDomElement value = contraint.firstChildElement( "DefaultValue" ); + QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) ); } } - else if ( contraint.attribute( "name" ) == "ImplementsResultPaging" /* WFS 2.0 */ ) + else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsResultPaging" ) /* WFS 2.0 */ ) { - QDomElement value = contraint.firstChildElement( "DefaultValue" ); - if ( !value.isNull() && value.text() == "TRUE" ) + QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); + if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) ) { mCaps.supportsPaging = true; QgsDebugMsg( "Supports paging" ); } } - else if ( contraint.attribute( "name" ) == "ImplementsStandardJoins" || - contraint.attribute( "name" ) == "ImplementsSpatialJoins" /* WFS 2.0 */ ) + else if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsStandardJoins" ) || + contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "ImplementsSpatialJoins" ) /* WFS 2.0 */ ) { - QDomElement value = contraint.firstChildElement( "DefaultValue" ); - if ( !value.isNull() && value.text() == "TRUE" ) + QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); + if ( !value.isNull() && value.text() == QLatin1String( "TRUE" ) ) { mCaps.supportsJoins = true; QgsDebugMsg( "Supports joins" ); @@ -190,19 +190,19 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() // In WFS 2.0, max features can also be set in Operation.GetFeature (e.g. GeoServer) // and we are also interested by resultType=hits for WFS 1.1 - QDomNodeList operationList = operationsMetadataElem.elementsByTagName( "Operation" ); + QDomNodeList operationList = operationsMetadataElem.elementsByTagName( QStringLiteral( "Operation" ) ); for ( int i = 0; i < operationList.size(); ++i ) { QDomElement operation = operationList.at( i ).toElement(); - if ( operation.attribute( "name" ) == "GetFeature" ) + if ( operation.attribute( QStringLiteral( "name" ) ) == QLatin1String( "GetFeature" ) ) { - QDomNodeList operationContraintList = operation.elementsByTagName( "Constraint" ); + QDomNodeList operationContraintList = operation.elementsByTagName( QStringLiteral( "Constraint" ) ); for ( int j = 0; j < operationContraintList.size(); ++j ) { QDomElement contraint = operationContraintList.at( j ).toElement(); - if ( contraint.attribute( "name" ) == "CountDefault" ) + if ( contraint.attribute( QStringLiteral( "name" ) ) == QLatin1String( "CountDefault" ) ) { - QDomElement value = contraint.firstChildElement( "DefaultValue" ); + QDomElement value = contraint.firstChildElement( QStringLiteral( "DefaultValue" ) ); if ( !value.isNull() ) { mCaps.maxFeatures = value.text().toInt(); @@ -212,17 +212,17 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() } } - QDomNodeList parameterList = operation.elementsByTagName( "Parameter" ); + QDomNodeList parameterList = operation.elementsByTagName( QStringLiteral( "Parameter" ) ); for ( int j = 0; j < parameterList.size(); ++j ) { QDomElement parameter = parameterList.at( j ).toElement(); - if ( parameter.attribute( "name" ) == "resultType" ) + if ( parameter.attribute( QStringLiteral( "name" ) ) == QLatin1String( "resultType" ) ) { - QDomNodeList valueList = parameter.elementsByTagName( "Value" ); + QDomNodeList valueList = parameter.elementsByTagName( QStringLiteral( "Value" ) ); for ( int k = 0; k < valueList.size(); ++k ) { QDomElement value = valueList.at( k ).toElement(); - if ( value.text() == "hits" ) + if ( value.text() == QLatin1String( "hits" ) ) { mCaps.supportsHits = true; QgsDebugMsg( "Support hits" ); @@ -238,7 +238,7 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() } //go to <FeatureTypeList> - QDomElement featureTypeListElem = doc.firstChildElement( "FeatureTypeList" ); + QDomElement featureTypeListElem = doc.firstChildElement( QStringLiteral( "FeatureTypeList" ) ); if ( featureTypeListElem.isNull() ) { emit gotCapabilities(); @@ -247,70 +247,70 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() // Parse operations supported for all feature types bool insertCap, updateCap, deleteCap; - parseSupportedOperations( featureTypeListElem.firstChildElement( "Operations" ), + parseSupportedOperations( featureTypeListElem.firstChildElement( QStringLiteral( "Operations" ) ), insertCap, updateCap, deleteCap ); // get the <FeatureType> elements - QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( "FeatureType" ); + QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( QStringLiteral( "FeatureType" ) ); for ( int i = 0; i < featureTypeList.size(); ++i ) { FeatureType featureType; QDomElement featureTypeElem = featureTypeList.at( i ).toElement(); //Name - QDomNodeList nameList = featureTypeElem.elementsByTagName( "Name" ); + QDomNodeList nameList = featureTypeElem.elementsByTagName( QStringLiteral( "Name" ) ); if ( nameList.length() > 0 ) { featureType.name = nameList.at( 0 ).toElement().text(); } //Title - QDomNodeList titleList = featureTypeElem.elementsByTagName( "Title" ); + QDomNodeList titleList = featureTypeElem.elementsByTagName( QStringLiteral( "Title" ) ); if ( titleList.length() > 0 ) { featureType.title = titleList.at( 0 ).toElement().text(); } //Abstract - QDomNodeList abstractList = featureTypeElem.elementsByTagName( "Abstract" ); + QDomNodeList abstractList = featureTypeElem.elementsByTagName( QStringLiteral( "Abstract" ) ); if ( abstractList.length() > 0 ) { featureType.abstract = abstractList.at( 0 ).toElement().text(); } //DefaultSRS is always the first entry in the feature srs list - QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( "DefaultSRS" ); + QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultSRS" ) ); if ( defaultCRSList.length() == 0 ) // In WFS 2.0, this is spelled DefaultCRS... - defaultCRSList = featureTypeElem.elementsByTagName( "DefaultCRS" ); + defaultCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "DefaultCRS" ) ); if ( defaultCRSList.length() > 0 ) { QString srsname( defaultCRSList.at( 0 ).toElement().text() ); // Some servers like Geomedia advertize EPSG:XXXX even in WFS 1.1 or 2.0 - if ( srsname.startsWith( "EPSG:" ) ) + if ( srsname.startsWith( QLatin1String( "EPSG:" ) ) ) mCaps.useEPSGColumnFormat = true; featureType.crslist.append( NormalizeSRSName( srsname ) ); } //OtherSRS - QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( "OtherSRS" ); + QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherSRS" ) ); if ( otherCRSList.length() == 0 ) // In WFS 2.0, this is spelled OtherCRS... - otherCRSList = featureTypeElem.elementsByTagName( "OtherCRS" ); + otherCRSList = featureTypeElem.elementsByTagName( QStringLiteral( "OtherCRS" ) ); for ( int i = 0; i < otherCRSList.size(); ++i ) { featureType.crslist.append( NormalizeSRSName( otherCRSList.at( i ).toElement().text() ) ); } //Support <SRS> for compatibility with older versions - QDomNodeList srsList = featureTypeElem.elementsByTagName( "SRS" ); + QDomNodeList srsList = featureTypeElem.elementsByTagName( QStringLiteral( "SRS" ) ); for ( int i = 0; i < srsList.size(); ++i ) { featureType.crslist.append( NormalizeSRSName( srsList.at( i ).toElement().text() ) ); } // Get BBox WFS 1.0 way - QDomElement latLongBB = featureTypeElem.firstChildElement( "LatLongBoundingBox" ); + QDomElement latLongBB = featureTypeElem.firstChildElement( QStringLiteral( "LatLongBoundingBox" ) ); if ( latLongBB.hasAttributes() ) { // Despite the name LatLongBoundingBox, the coordinates are supposed to @@ -318,10 +318,10 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() // <!-- The LatLongBoundingBox element is used to indicate the edges of // an enclosing rectangle in the SRS of the associated feature type. featureType.bbox = QgsRectangle( - latLongBB.attribute( "minx" ).toDouble(), - latLongBB.attribute( "miny" ).toDouble(), - latLongBB.attribute( "maxx" ).toDouble(), - latLongBB.attribute( "maxy" ).toDouble() ); + latLongBB.attribute( QStringLiteral( "minx" ) ).toDouble(), + latLongBB.attribute( QStringLiteral( "miny" ) ).toDouble(), + latLongBB.attribute( QStringLiteral( "maxx" ) ).toDouble(), + latLongBB.attribute( QStringLiteral( "maxy" ) ).toDouble() ); featureType.bboxSRSIsWGS84 = false; // But some servers do not honour this and systematically reproject to WGS84 @@ -336,7 +336,7 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() { // If the CRS is projected then check that projecting the corner of the bbox, assumed to be in WGS84, // into the CRS, and then back to WGS84, works (check that we are in the validity area) - QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "CRS:84" ); + QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "CRS:84" ) ); QgsCoordinateTransform ct( crsWGS84, crs ); QgsPoint ptMin( featureType.bbox.xMinimum(), featureType.bbox.yMinimum() ); @@ -362,15 +362,15 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() else { // WFS 1.1 way - QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( "WGS84BoundingBox" ); + QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( QStringLiteral( "WGS84BoundingBox" ) ); if ( !WGS84BoundingBox.isNull() ) { - QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( "LowerCorner" ); - QDomElement upperCorner = WGS84BoundingBox.firstChildElement( "UpperCorner" ); + QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "LowerCorner" ) ); + QDomElement upperCorner = WGS84BoundingBox.firstChildElement( QStringLiteral( "UpperCorner" ) ); if ( !lowerCorner.isNull() && !upperCorner.isNull() ) { - QStringList lowerCornerList = lowerCorner.text().split( " ", QString::SkipEmptyParts ); - QStringList upperCornerList = upperCorner.text().split( " ", QString::SkipEmptyParts ); + QStringList lowerCornerList = lowerCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); + QStringList upperCornerList = upperCorner.text().split( QStringLiteral( " " ), QString::SkipEmptyParts ); if ( lowerCornerList.size() == 2 && upperCornerList.size() == 2 ) { featureType.bbox = QgsRectangle( @@ -385,7 +385,7 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() } // Parse Operations specific to the type name - parseSupportedOperations( featureTypeElem.firstChildElement( "Operations" ), + parseSupportedOperations( featureTypeElem.firstChildElement( QStringLiteral( "Operations" ) ), featureType.insertCap, featureType.updateCap, featureType.deleteCap ); @@ -415,29 +415,29 @@ void QgsWfsCapabilities::capabilitiesReplyFinished() } //go to <Filter_Capabilities> - QDomElement filterCapabilitiesElem = doc.firstChildElement( "Filter_Capabilities" ); + QDomElement filterCapabilitiesElem = doc.firstChildElement( QStringLiteral( "Filter_Capabilities" ) ); if ( !filterCapabilitiesElem.isNull() ) parseFilterCapabilities( filterCapabilitiesElem ); // Hard-coded functions - Function f_ST_GeometryFromText( "ST_GeometryFromText", 1, 2 ); - f_ST_GeometryFromText.returnType = "gml:AbstractGeometryType"; - f_ST_GeometryFromText.argumentList << Argument( "wkt", "xs:string" ); - f_ST_GeometryFromText.argumentList << Argument( "srsname", "xs:string" ); + Function f_ST_GeometryFromText( QStringLiteral( "ST_GeometryFromText" ), 1, 2 ); + f_ST_GeometryFromText.returnType = QStringLiteral( "gml:AbstractGeometryType" ); + f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "wkt" ), QStringLiteral( "xs:string" ) ); + f_ST_GeometryFromText.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_GeometryFromText; - Function f_ST_GeomFromGML( "ST_GeomFromGML", 1 ); - f_ST_GeomFromGML.returnType = "gml:AbstractGeometryType"; - f_ST_GeomFromGML.argumentList << Argument( "gml", "xs:string" ); + Function f_ST_GeomFromGML( QStringLiteral( "ST_GeomFromGML" ), 1 ); + f_ST_GeomFromGML.returnType = QStringLiteral( "gml:AbstractGeometryType" ); + f_ST_GeomFromGML.argumentList << Argument( QStringLiteral( "gml" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_GeomFromGML; - Function f_ST_MakeEnvelope( "ST_MakeEnvelope", 4, 5 ); - f_ST_MakeEnvelope.returnType = "gml:AbstractGeometryType"; - f_ST_MakeEnvelope.argumentList << Argument( "minx", "xs:double" ); - f_ST_MakeEnvelope.argumentList << Argument( "miny", "xs:double" ); - f_ST_MakeEnvelope.argumentList << Argument( "maxx", "xs:double" ); - f_ST_MakeEnvelope.argumentList << Argument( "maxy", "xs:double" ); - f_ST_MakeEnvelope.argumentList << Argument( "srsname", "xs:string" ); + Function f_ST_MakeEnvelope( QStringLiteral( "ST_MakeEnvelope" ), 4, 5 ); + f_ST_MakeEnvelope.returnType = QStringLiteral( "gml:AbstractGeometryType" ); + f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "minx" ), QStringLiteral( "xs:double" ) ); + f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "miny" ), QStringLiteral( "xs:double" ) ); + f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxx" ), QStringLiteral( "xs:double" ) ); + f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "maxy" ), QStringLiteral( "xs:double" ) ); + f_ST_MakeEnvelope.argumentList << Argument( QStringLiteral( "srsname" ), QStringLiteral( "xs:string" ) ); mCaps.functionList << f_ST_MakeEnvelope; emit gotCapabilities(); @@ -462,7 +462,7 @@ QString QgsWfsCapabilities::NormalizeSRSName( QString crsName ) int QgsWfsCapabilities::defaultExpirationInSec() { QSettings s; - return s.value( "/qgis/defaultCapabilitiesExpiry", "24" ).toInt() * 60 * 60; + return s.value( QStringLiteral( "/qgis/defaultCapabilitiesExpiry" ), "24" ).toInt() * 60 * 60; } void QgsWfsCapabilities::parseSupportedOperations( const QDomElement& operationsElem, @@ -475,7 +475,7 @@ void QgsWfsCapabilities::parseSupportedOperations( const QDomElement& operations deleteCap = false; // TODO: remove me when WFS-T 1.1 or 2.0 is done - if ( !mCaps.version.startsWith( "1.0" ) ) + if ( !mCaps.version.startsWith( QLatin1String( "1.0" ) ) ) return; if ( operationsElem.isNull() ) @@ -489,31 +489,31 @@ void QgsWfsCapabilities::parseSupportedOperations( const QDomElement& operations QDomElement elt = childList.at( i ).toElement(); QString elemName = elt.tagName(); /* WFS 1.0 */ - if ( elemName == "Insert" ) + if ( elemName == QLatin1String( "Insert" ) ) { insertCap = true; } - else if ( elemName == "Update" ) + else if ( elemName == QLatin1String( "Update" ) ) { updateCap = true; } - else if ( elemName == "Delete" ) + else if ( elemName == QLatin1String( "Delete" ) ) { deleteCap = true; } /* WFS 1.1 */ - else if ( elemName == "Operation" ) + else if ( elemName == QLatin1String( "Operation" ) ) { QString elemText = elt.text(); - if ( elemText == "Insert" ) + if ( elemText == QLatin1String( "Insert" ) ) { insertCap = true; } - else if ( elemText == "Update" ) + else if ( elemText == QLatin1String( "Update" ) ) { updateCap = true; } - else if ( elemText == "Delete" ) + else if ( elemText == QLatin1String( "Delete" ) ) { deleteCap = true; } @@ -525,25 +525,25 @@ static QgsWfsCapabilities::Function getSpatialPredicate( const QString& name ) { QgsWfsCapabilities::Function f; // WFS 1.0 advertize Intersect, but for conveniency we internally convert it to Intersects - if ( name == "Intersect" ) - f.name = "ST_Intersects"; + if ( name == QLatin1String( "Intersect" ) ) + f.name = QStringLiteral( "ST_Intersects" ); else - f.name = ( name == "BBOX" ) ? "BBOX" : "ST_" + name; - f.returnType = "xs:boolean"; - if ( name == "DWithin" || name == "Beyond" ) + f.name = ( name == QLatin1String( "BBOX" ) ) ? QStringLiteral( "BBOX" ) : "ST_" + name; + f.returnType = QStringLiteral( "xs:boolean" ); + if ( name == QLatin1String( "DWithin" ) || name == QLatin1String( "Beyond" ) ) { f.minArgs = 3; f.maxArgs = 3; - f.argumentList << QgsWfsCapabilities::Argument( "geometry", "gml:AbstractGeometryType" ); - f.argumentList << QgsWfsCapabilities::Argument( "geometry", "gml:AbstractGeometryType" ); - f.argumentList << QgsWfsCapabilities::Argument( "distance" ); + f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); + f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); + f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "distance" ) ); } else { f.minArgs = 2; f.maxArgs = 2; - f.argumentList << QgsWfsCapabilities::Argument( "geometry", "gml:AbstractGeometryType" ); - f.argumentList << QgsWfsCapabilities::Argument( "geometry", "gml:AbstractGeometryType" ); + f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); + f.argumentList << QgsWfsCapabilities::Argument( QStringLiteral( "geometry" ), QStringLiteral( "gml:AbstractGeometryType" ) ); } return f; } @@ -551,7 +551,7 @@ static QgsWfsCapabilities::Function getSpatialPredicate( const QString& name ) void QgsWfsCapabilities::parseFilterCapabilities( const QDomElement& filterCapabilitiesElem ) { // WFS 1.0 - QDomElement spatial_Operators = filterCapabilitiesElem.firstChildElement( "Spatial_Capabilities" ).firstChildElement( "Spatial_Operators" ); + QDomElement spatial_Operators = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Spatial_Capabilities" ) ).firstChildElement( QStringLiteral( "Spatial_Operators" ) ); QDomElement spatial_Operator = spatial_Operators.firstChildElement(); while ( !spatial_Operator.isNull() ) { @@ -564,30 +564,30 @@ void QgsWfsCapabilities::parseFilterCapabilities( const QDomElement& filterCapab } // WFS 1.1 and 2.0 - QDomElement spatialOperators = filterCapabilitiesElem.firstChildElement( "Spatial_Capabilities" ).firstChildElement( "SpatialOperators" ); - QDomElement spatialOperator = spatialOperators.firstChildElement( "SpatialOperator" ); + QDomElement spatialOperators = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Spatial_Capabilities" ) ).firstChildElement( QStringLiteral( "SpatialOperators" ) ); + QDomElement spatialOperator = spatialOperators.firstChildElement( QStringLiteral( "SpatialOperator" ) ); while ( !spatialOperator.isNull() ) { - QString name = spatialOperator.attribute( "name" ); + QString name = spatialOperator.attribute( QStringLiteral( "name" ) ); if ( !name.isEmpty() ) { mCaps.spatialPredicatesList << getSpatialPredicate( name ); } - spatialOperator = spatialOperator.nextSiblingElement( "SpatialOperator" ); + spatialOperator = spatialOperator.nextSiblingElement( QStringLiteral( "SpatialOperator" ) ); } // WFS 1.0 - QDomElement function_Names = filterCapabilitiesElem.firstChildElement( "Scalar_Capabilities" ) - .firstChildElement( "Arithmetic_Operators" ) - .firstChildElement( "Functions" ) - .firstChildElement( "Function_Names" ); - QDomElement function_NameElem = function_Names.firstChildElement( "Function_Name" ); + QDomElement function_Names = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Scalar_Capabilities" ) ) + .firstChildElement( QStringLiteral( "Arithmetic_Operators" ) ) + .firstChildElement( QStringLiteral( "Functions" ) ) + .firstChildElement( QStringLiteral( "Function_Names" ) ); + QDomElement function_NameElem = function_Names.firstChildElement( QStringLiteral( "Function_Name" ) ); while ( !function_NameElem.isNull() ) { Function f; f.name = function_NameElem.text(); bool ok; - int nArgs = function_NameElem.attribute( "nArgs" ).toInt( &ok ); + int nArgs = function_NameElem.attribute( QStringLiteral( "nArgs" ) ).toInt( &ok ); if ( ok ) { if ( nArgs >= 0 ) @@ -601,21 +601,21 @@ void QgsWfsCapabilities::parseFilterCapabilities( const QDomElement& filterCapab } } mCaps.functionList << f; - function_NameElem = function_NameElem.nextSiblingElement( "Function_Name" ); + function_NameElem = function_NameElem.nextSiblingElement( QStringLiteral( "Function_Name" ) ); } // WFS 1.1 - QDomElement functionNames = filterCapabilitiesElem.firstChildElement( "Scalar_Capabilities" ) - .firstChildElement( "ArithmeticOperators" ) - .firstChildElement( "Functions" ) - .firstChildElement( "FunctionNames" ); - QDomElement functionNameElem = functionNames.firstChildElement( "FunctionName" ); + QDomElement functionNames = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Scalar_Capabilities" ) ) + .firstChildElement( QStringLiteral( "ArithmeticOperators" ) ) + .firstChildElement( QStringLiteral( "Functions" ) ) + .firstChildElement( QStringLiteral( "FunctionNames" ) ); + QDomElement functionNameElem = functionNames.firstChildElement( QStringLiteral( "FunctionName" ) ); while ( !functionNameElem.isNull() ) { Function f; f.name = functionNameElem.text(); bool ok; - int nArgs = functionNameElem.attribute( "nArgs" ).toInt( &ok ); + int nArgs = functionNameElem.attribute( QStringLiteral( "nArgs" ) ).toInt( &ok ); if ( ok ) { if ( nArgs >= 0 ) @@ -629,35 +629,35 @@ void QgsWfsCapabilities::parseFilterCapabilities( const QDomElement& filterCapab } } mCaps.functionList << f; - functionNameElem = functionNameElem.nextSiblingElement( "FunctionName" ); + functionNameElem = functionNameElem.nextSiblingElement( QStringLiteral( "FunctionName" ) ); } - QDomElement functions = filterCapabilitiesElem.firstChildElement( "Functions" ); - QDomElement functionElem = functions.firstChildElement( "Function" ); + QDomElement functions = filterCapabilitiesElem.firstChildElement( QStringLiteral( "Functions" ) ); + QDomElement functionElem = functions.firstChildElement( QStringLiteral( "Function" ) ); while ( !functionElem.isNull() ) { - QString name = functionElem.attribute( "name" ); + QString name = functionElem.attribute( QStringLiteral( "name" ) ); if ( !name.isEmpty() ) { Function f; f.name = name; - QDomElement returnsElem = functionElem.firstChildElement( "Returns" ); + QDomElement returnsElem = functionElem.firstChildElement( QStringLiteral( "Returns" ) ); f.returnType = returnsElem.text(); - QDomElement argumentsElem = functionElem.firstChildElement( "Arguments" ); - QDomElement argumentElem = argumentsElem.firstChildElement( "Argument" ); + QDomElement argumentsElem = functionElem.firstChildElement( QStringLiteral( "Arguments" ) ); + QDomElement argumentElem = argumentsElem.firstChildElement( QStringLiteral( "Argument" ) ); while ( !argumentElem.isNull() ) { Argument arg; - arg.name = argumentElem.attribute( "name" ); - arg.type = argumentElem.firstChildElement( "Type" ).text(); + arg.name = argumentElem.attribute( QStringLiteral( "name" ) ); + arg.type = argumentElem.firstChildElement( QStringLiteral( "Type" ) ).text(); f.argumentList << arg; - argumentElem = argumentElem.nextSiblingElement( "Argument" ); + argumentElem = argumentElem.nextSiblingElement( QStringLiteral( "Argument" ) ); } f.minArgs = f.argumentList.count(); f.maxArgs = f.argumentList.count(); mCaps.functionList << f; } - functionElem = functionElem.nextSiblingElement( "Function" ); + functionElem = functionElem.nextSiblingElement( QStringLiteral( "Function" ) ); } } diff --git a/src/providers/wfs/qgswfsconnection.cpp b/src/providers/wfs/qgswfsconnection.cpp index 3adb32334077..842b7d776064 100644 --- a/src/providers/wfs/qgswfsconnection.cpp +++ b/src/providers/wfs/qgswfsconnection.cpp @@ -20,7 +20,7 @@ #include <QSettings> QgsWfsConnection::QgsWfsConnection( const QString & theConnName ) - : QgsOwsConnection( "WFS", theConnName ) + : QgsOwsConnection( QStringLiteral( "WFS" ), theConnName ) { const QString& key = QgsWFSConstants::CONNECTIONS_WFS + mConnName; @@ -43,20 +43,20 @@ QgsWfsConnection::QgsWfsConnection( const QString & theConnName ) QStringList QgsWfsConnection::connectionList() { - return QgsOwsConnection::connectionList( "WFS" ); + return QgsOwsConnection::connectionList( QStringLiteral( "WFS" ) ); } void QgsWfsConnection::deleteConnection( const QString & name ) { - QgsOwsConnection::deleteConnection( "WFS", name ); + QgsOwsConnection::deleteConnection( QStringLiteral( "WFS" ), name ); } QString QgsWfsConnection::selectedConnection() { - return QgsOwsConnection::selectedConnection( "WFS" ); + return QgsOwsConnection::selectedConnection( QStringLiteral( "WFS" ) ); } void QgsWfsConnection::setSelectedConnection( const QString & name ) { - QgsOwsConnection::setSelectedConnection( "WFS", name ); + QgsOwsConnection::setSelectedConnection( QStringLiteral( "WFS" ), name ); } diff --git a/src/providers/wfs/qgswfsconstants.cpp b/src/providers/wfs/qgswfsconstants.cpp index 87ff72f8fbc3..a44acf45726c 100644 --- a/src/providers/wfs/qgswfsconstants.cpp +++ b/src/providers/wfs/qgswfsconstants.cpp @@ -15,36 +15,36 @@ #include "qgswfsconstants.h" -const QString QgsWFSConstants::GML_NAMESPACE( "http://www.opengis.net/gml" ); -const QString QgsWFSConstants::OGC_NAMESPACE( "http://www.opengis.net/ogc" ); -const QString QgsWFSConstants::OWS_NAMESPACE( "http://www.opengis.net/ows" ); -const QString QgsWFSConstants::WFS_NAMESPACE( "http://www.opengis.net/wfs" ); -const QString QgsWFSConstants::XMLSCHEMA_NAMESPACE( "http://www.w3.org/2001/XMLSchema" ); +const QString QgsWFSConstants::GML_NAMESPACE( QStringLiteral( "http://www.opengis.net/gml" ) ); +const QString QgsWFSConstants::OGC_NAMESPACE( QStringLiteral( "http://www.opengis.net/ogc" ) ); +const QString QgsWFSConstants::OWS_NAMESPACE( QStringLiteral( "http://www.opengis.net/ows" ) ); +const QString QgsWFSConstants::WFS_NAMESPACE( QStringLiteral( "http://www.opengis.net/wfs" ) ); +const QString QgsWFSConstants::XMLSCHEMA_NAMESPACE( QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); -const QString QgsWFSConstants::URI_PARAM_URL( "url" ); -const QString QgsWFSConstants::URI_PARAM_USERNAME( "username" ); -const QString QgsWFSConstants::URI_PARAM_USER( "user" ); -const QString QgsWFSConstants::URI_PARAM_PASSWORD( "password" ); -const QString QgsWFSConstants::URI_PARAM_AUTHCFG( "authcfg" ); -const QString QgsWFSConstants::URI_PARAM_VERSION( "version" ); -const QString QgsWFSConstants::URI_PARAM_TYPENAME( "typename" ); -const QString QgsWFSConstants::URI_PARAM_SRSNAME( "srsname" ); -const QString QgsWFSConstants::URI_PARAM_BBOX( "bbox" ); -const QString QgsWFSConstants::URI_PARAM_FILTER( "filter" ); -const QString QgsWFSConstants::URI_PARAM_RESTRICT_TO_REQUEST_BBOX( "restrictToRequestBBOX" ); -const QString QgsWFSConstants::URI_PARAM_MAXNUMFEATURES( "maxNumFeatures" ); -const QString QgsWFSConstants::URI_PARAM_IGNOREAXISORIENTATION( "IgnoreAxisOrientation" ); -const QString QgsWFSConstants::URI_PARAM_INVERTAXISORIENTATION( "InvertAxisOrientation" ); -const QString QgsWFSConstants::URI_PARAM_VALIDATESQLFUNCTIONS( "validateSQLFunctions" ); -const QString QgsWFSConstants::URI_PARAM_HIDEDOWNLOADPROGRESSDIALOG( "hideDownloadProgressDialog" ); +const QString QgsWFSConstants::URI_PARAM_URL( QStringLiteral( "url" ) ); +const QString QgsWFSConstants::URI_PARAM_USERNAME( QStringLiteral( "username" ) ); +const QString QgsWFSConstants::URI_PARAM_USER( QStringLiteral( "user" ) ); +const QString QgsWFSConstants::URI_PARAM_PASSWORD( QStringLiteral( "password" ) ); +const QString QgsWFSConstants::URI_PARAM_AUTHCFG( QStringLiteral( "authcfg" ) ); +const QString QgsWFSConstants::URI_PARAM_VERSION( QStringLiteral( "version" ) ); +const QString QgsWFSConstants::URI_PARAM_TYPENAME( QStringLiteral( "typename" ) ); +const QString QgsWFSConstants::URI_PARAM_SRSNAME( QStringLiteral( "srsname" ) ); +const QString QgsWFSConstants::URI_PARAM_BBOX( QStringLiteral( "bbox" ) ); +const QString QgsWFSConstants::URI_PARAM_FILTER( QStringLiteral( "filter" ) ); +const QString QgsWFSConstants::URI_PARAM_RESTRICT_TO_REQUEST_BBOX( QStringLiteral( "restrictToRequestBBOX" ) ); +const QString QgsWFSConstants::URI_PARAM_MAXNUMFEATURES( QStringLiteral( "maxNumFeatures" ) ); +const QString QgsWFSConstants::URI_PARAM_IGNOREAXISORIENTATION( QStringLiteral( "IgnoreAxisOrientation" ) ); +const QString QgsWFSConstants::URI_PARAM_INVERTAXISORIENTATION( QStringLiteral( "InvertAxisOrientation" ) ); +const QString QgsWFSConstants::URI_PARAM_VALIDATESQLFUNCTIONS( QStringLiteral( "validateSQLFunctions" ) ); +const QString QgsWFSConstants::URI_PARAM_HIDEDOWNLOADPROGRESSDIALOG( QStringLiteral( "hideDownloadProgressDialog" ) ); -const QString QgsWFSConstants::VERSION_AUTO( "auto" ); +const QString QgsWFSConstants::VERSION_AUTO( QStringLiteral( "auto" ) ); -const QString QgsWFSConstants::CONNECTIONS_WFS( "/Qgis/connections-wfs/" ); -const QString QgsWFSConstants::SETTINGS_VERSION( "version" ); -const QString QgsWFSConstants::SETTINGS_MAXNUMFEATURES( "maxnumfeatures" ); +const QString QgsWFSConstants::CONNECTIONS_WFS( QStringLiteral( "/Qgis/connections-wfs/" ) ); +const QString QgsWFSConstants::SETTINGS_VERSION( QStringLiteral( "version" ) ); +const QString QgsWFSConstants::SETTINGS_MAXNUMFEATURES( QStringLiteral( "maxnumfeatures" ) ); -const QString QgsWFSConstants::FIELD_GEN_COUNTER( "__qgis_gen_counter" ); -const QString QgsWFSConstants::FIELD_GMLID( "__qgis_gmlid" ); -const QString QgsWFSConstants::FIELD_HEXWKB_GEOM( "__qgis_hexwkb_geom" ); -const QString QgsWFSConstants::FIELD_MD5( "__qgis_md5" ); +const QString QgsWFSConstants::FIELD_GEN_COUNTER( QStringLiteral( "__qgis_gen_counter" ) ); +const QString QgsWFSConstants::FIELD_GMLID( QStringLiteral( "__qgis_gmlid" ) ); +const QString QgsWFSConstants::FIELD_HEXWKB_GEOM( QStringLiteral( "__qgis_hexwkb_geom" ) ); +const QString QgsWFSConstants::FIELD_MD5( QStringLiteral( "__qgis_md5" ) ); diff --git a/src/providers/wfs/qgswfsdataitems.cpp b/src/providers/wfs/qgswfsdataitems.cpp index 7a9772467968..7ddbfa9e211f 100644 --- a/src/providers/wfs/qgswfsdataitems.cpp +++ b/src/providers/wfs/qgswfsdataitems.cpp @@ -28,13 +28,13 @@ QgsWfsLayerItem::QgsWfsLayerItem( QgsDataItem* parent, QString name, const QgsDataSourceUri& uri, QString featureType, QString title, QString crsString ) - : QgsLayerItem( parent, title, parent->path() + '/' + name, QString(), QgsLayerItem::Vector, "WFS" ) + : QgsLayerItem( parent, title, parent->path() + '/' + name, QString(), QgsLayerItem::Vector, QStringLiteral( "WFS" ) ) { QSettings settings; - bool useCurrentViewExtent = settings.value( "/Windows/WFSSourceSelect/FeatureCurrentViewExtent", true ).toBool(); + bool useCurrentViewExtent = settings.value( QStringLiteral( "/Windows/WFSSourceSelect/FeatureCurrentViewExtent" ), true ).toBool(); mUri = QgsWFSDataSourceURI::build( uri.uri(), featureType, crsString, QString(), useCurrentViewExtent ); setState( Populated ); - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); } QgsWfsLayerItem::~QgsWfsLayerItem() @@ -48,7 +48,7 @@ QgsWfsConnectionItem::QgsWfsConnectionItem( QgsDataItem* parent, QString name, Q , mUri( uri ) , mCapabilities( nullptr ) { - mIconName = "mIconWfs.svg"; + mIconName = QStringLiteral( "mIconWfs.svg" ); } QgsWfsConnectionItem::~QgsWfsConnectionItem() @@ -129,7 +129,7 @@ QgsWfsRootItem::QgsWfsRootItem( QgsDataItem* parent, QString name, QString path : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconWfs.svg"; + mIconName = QStringLiteral( "mIconWfs.svg" ); populate(); } @@ -202,17 +202,17 @@ QGISEXTERN QgsDataItem * dataItem( QString thePath, QgsDataItem* parentItem ) QgsDebugMsg( "thePath = " + thePath ); if ( thePath.isEmpty() ) { - return new QgsWfsRootItem( parentItem, "WFS", "wfs:" ); + return new QgsWfsRootItem( parentItem, QStringLiteral( "WFS" ), QStringLiteral( "wfs:" ) ); } // path schema: wfs:/connection name (used by OWS) - if ( thePath.startsWith( "wfs:/" ) ) + if ( thePath.startsWith( QLatin1String( "wfs:/" ) ) ) { QString connectionName = thePath.split( '/' ).last(); if ( QgsWfsConnection::connectionList().contains( connectionName ) ) { QgsWfsConnection connection( connectionName ); - return new QgsWfsConnectionItem( parentItem, "WFS", thePath, connection.uri().uri() ); + return new QgsWfsConnectionItem( parentItem, QStringLiteral( "WFS" ), thePath, connection.uri().uri() ); } } diff --git a/src/providers/wfs/qgswfsdatasourceuri.cpp b/src/providers/wfs/qgswfsdatasourceuri.cpp index a9b239e15a83..77cce780c992 100644 --- a/src/providers/wfs/qgswfsdatasourceuri.cpp +++ b/src/providers/wfs/qgswfsdatasourceuri.cpp @@ -56,13 +56,13 @@ QgsWFSDataSourceURI::QgsWFSDataSourceURI( const QString& uri ) } // Now remove all stuff that is not the core URL - url.removeQueryItem( "SERVICE" ); - url.removeQueryItem( "VERSION" ); - url.removeQueryItem( "TYPENAME" ); - url.removeQueryItem( "REQUEST" ); - url.removeQueryItem( "BBOX" ); - url.removeQueryItem( "SRSNAME" ); - url.removeQueryItem( "FILTER" ); + url.removeQueryItem( QStringLiteral( "SERVICE" ) ); + url.removeQueryItem( QStringLiteral( "VERSION" ) ); + url.removeQueryItem( QStringLiteral( "TYPENAME" ) ); + url.removeQueryItem( QStringLiteral( "REQUEST" ) ); + url.removeQueryItem( QStringLiteral( "BBOX" ) ); + url.removeQueryItem( QStringLiteral( "SRSNAME" ) ); + url.removeQueryItem( QStringLiteral( "FILTER" ) ); url.removeQueryItem( QgsWFSConstants::URI_PARAM_USERNAME ); url.removeQueryItem( QgsWFSConstants::URI_PARAM_PASSWORD ); url.removeQueryItem( QgsWFSConstants::URI_PARAM_AUTHCFG ); @@ -82,7 +82,7 @@ QgsWFSDataSourceURI::QgsWFSDataSourceURI( const QString& uri ) setFilter( filter ); if ( !bbox.isEmpty() ) - mURI.setParam( QgsWFSConstants::URI_PARAM_RESTRICT_TO_REQUEST_BBOX, "1" ); + mURI.setParam( QgsWFSConstants::URI_PARAM_RESTRICT_TO_REQUEST_BBOX, QStringLiteral( "1" ) ); } else { @@ -122,7 +122,7 @@ QUrl QgsWFSDataSourceURI::baseURL( bool bIncludeServiceWFS ) const QUrl url( mURI.param( QgsWFSConstants::URI_PARAM_URL ) ); if ( bIncludeServiceWFS ) { - url.addQueryItem( "SERVICE", "WFS" ); + url.addQueryItem( QStringLiteral( "SERVICE" ), QStringLiteral( "WFS" ) ); } return url; } @@ -208,7 +208,7 @@ bool QgsWFSDataSourceURI::isRestrictedToRequestBBOX() const return true; // accept previously used version with typo - if ( mURI.hasParam( "retrictToRequestBBOX" ) && mURI.param( "retrictToRequestBBOX" ).toInt() == 1 ) + if ( mURI.hasParam( QStringLiteral( "retrictToRequestBBOX" ) ) && mURI.param( QStringLiteral( "retrictToRequestBBOX" ) ).toInt() == 1 ) return true; return false; @@ -245,6 +245,6 @@ QString QgsWFSDataSourceURI::build( const QString& baseUri, uri.setSRSName( crsString ); uri.setSql( sql ); if ( restrictToCurrentViewExtent ) - uri.mURI.setParam( QgsWFSConstants::URI_PARAM_RESTRICT_TO_REQUEST_BBOX, "1" ); + uri.mURI.setParam( QgsWFSConstants::URI_PARAM_RESTRICT_TO_REQUEST_BBOX, QStringLiteral( "1" ) ); return uri.uri(); } diff --git a/src/providers/wfs/qgswfsdatasourceuri.h b/src/providers/wfs/qgswfsdatasourceuri.h index 497926246e2e..cd934eff8dbe 100644 --- a/src/providers/wfs/qgswfsdatasourceuri.h +++ b/src/providers/wfs/qgswfsdatasourceuri.h @@ -41,7 +41,7 @@ struct QgsWFSAuthorization } else if ( !mUserName.isNull() || !mPassword.isNull() ) // allow empty values { - request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); + request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); } return true; } diff --git a/src/providers/wfs/qgswfsdescribefeaturetype.cpp b/src/providers/wfs/qgswfsdescribefeaturetype.cpp index c69a4e17c405..bd7aba60b3e9 100644 --- a/src/providers/wfs/qgswfsdescribefeaturetype.cpp +++ b/src/providers/wfs/qgswfsdescribefeaturetype.cpp @@ -24,9 +24,9 @@ bool QgsWFSDescribeFeatureType::requestFeatureType( const QString& WFSVersion, const QString& typeName ) { QUrl url( baseURL() ); - url.addQueryItem( "REQUEST", "DescribeFeatureType" ); - url.addQueryItem( "VERSION", WFSVersion ); - url.addQueryItem( "TYPENAME", typeName ); + url.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "DescribeFeatureType" ) ); + url.addQueryItem( QStringLiteral( "VERSION" ), WFSVersion ); + url.addQueryItem( QStringLiteral( "TYPENAME" ), typeName ); return sendGET( url, true, false ); } diff --git a/src/providers/wfs/qgswfsfeatureiterator.cpp b/src/providers/wfs/qgswfsfeatureiterator.cpp index 589bb45324f7..b35387c6f8f9 100644 --- a/src/providers/wfs/qgswfsfeatureiterator.cpp +++ b/src/providers/wfs/qgswfsfeatureiterator.cpp @@ -56,7 +56,7 @@ void QgsWFSFeatureHitsAsyncRequest::hitsReplyFinished() if ( mErrorCode == NoError ) { QByteArray data = response(); - QgsGmlStreamingParser gmlParser( "", "", QgsFields() ); + QgsGmlStreamingParser gmlParser( QLatin1String( "" ), QLatin1String( "" ), QgsFields() ); QString errorMsg; if ( gmlParser.processData( data, true, errorMsg ) ) { @@ -179,18 +179,18 @@ void QgsWFSFeatureDownloader::createProgressDialog() QString QgsWFSFeatureDownloader::sanitizeFilter( QString filter ) { - filter = filter.replace( "<fes:ValueReference xmlns:fes=\"http://www.opengis.net/fes/2.0\">", "<fes:ValueReference>" ); + filter = filter.replace( QLatin1String( "<fes:ValueReference xmlns:fes=\"http://www.opengis.net/fes/2.0\">" ), QLatin1String( "<fes:ValueReference>" ) ); QString nsPrefix( QgsWFSUtils::nameSpacePrefix( mShared->mURI.typeName() ) ); if ( mRemoveNSPrefix && !nsPrefix.isEmpty() ) - filter = filter.replace( "<fes:ValueReference>" + nsPrefix + ":", "<fes:ValueReference>" ); + filter = filter.replace( "<fes:ValueReference>" + nsPrefix + ":", QLatin1String( "<fes:ValueReference>" ) ); return filter; } QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool forHits ) { QUrl getFeatureUrl( mShared->mURI.baseURL() ); - getFeatureUrl.addQueryItem( "REQUEST", "GetFeature" ); - getFeatureUrl.addQueryItem( "VERSION", mShared->mWFSVersion ); + getFeatureUrl.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetFeature" ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "VERSION" ), mShared->mWFSVersion ); QString typenames; if ( mShared->mLayerPropertiesList.isEmpty() ) @@ -202,17 +202,17 @@ QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool fo Q_FOREACH ( const QgsOgcUtils::LayerProperties layerProperties, mShared->mLayerPropertiesList ) { if ( !typenames.isEmpty() ) - typenames += ","; + typenames += QLatin1String( "," ); typenames += layerProperties.mName; } } - if ( mShared->mWFSVersion.startsWith( "2.0" ) ) - getFeatureUrl.addQueryItem( "TYPENAMES", typenames ); + if ( mShared->mWFSVersion.startsWith( QLatin1String( "2.0" ) ) ) + getFeatureUrl.addQueryItem( QStringLiteral( "TYPENAMES" ), typenames ); else - getFeatureUrl.addQueryItem( "TYPENAME", typenames ); + getFeatureUrl.addQueryItem( QStringLiteral( "TYPENAME" ), typenames ); if ( forHits ) { - getFeatureUrl.addQueryItem( "RESULTTYPE", "hits" ); + getFeatureUrl.addQueryItem( QStringLiteral( "RESULTTYPE" ), QStringLiteral( "hits" ) ); } else if ( maxFeatures > 0 ) { @@ -224,17 +224,17 @@ QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool fo // For example http://demo.opengeo.org/geoserver/wfs?SERVICE=WFS&REQUEST=GetFeature&VERSION=2.0.0&TYPENAMES=ne:ne_10m_admin_0_countries&STARTINDEX=0&COUNT=253 // doesn't include ne_10m_admin_0_countries.99, as expected since it is // at index 254. - getFeatureUrl.addQueryItem( "STARTINDEX", QString::number( startIndex ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "STARTINDEX" ), QString::number( startIndex ) ); } - if ( mShared->mWFSVersion.startsWith( "2.0" ) ) - getFeatureUrl.addQueryItem( "COUNT", QString::number( maxFeatures ) ); + if ( mShared->mWFSVersion.startsWith( QLatin1String( "2.0" ) ) ) + getFeatureUrl.addQueryItem( QStringLiteral( "COUNT" ), QString::number( maxFeatures ) ); else - getFeatureUrl.addQueryItem( "MAXFEATURES", QString::number( maxFeatures ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "MAXFEATURES" ), QString::number( maxFeatures ) ); } QString srsName( mShared->srsName() ); if ( !srsName.isEmpty() && !forHits ) { - getFeatureUrl.addQueryItem( "SRSNAME", srsName ); + getFeatureUrl.addQueryItem( QStringLiteral( "SRSNAME" ), srsName ); } // In case we must issue a BBOX and we have a filter, we must combine @@ -245,18 +245,18 @@ QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool fo double miny = mShared->mRect.yMinimum(); double maxx = mShared->mRect.xMaximum(); double maxy = mShared->mRect.yMaximum(); - QString filterBbox( QString( "intersects_bbox($geometry, geomFromWKT('LINESTRING(%1 %2,%3 %4)'))" ). + QString filterBbox( QStringLiteral( "intersects_bbox($geometry, geomFromWKT('LINESTRING(%1 %2,%3 %4)'))" ). arg( minx ).arg( miny ).arg( maxx ).arg( maxy ) ); QgsExpression bboxExp( filterBbox ); QgsOgcUtils::GMLVersion gmlVersion; QgsOgcUtils::FilterVersion filterVersion; bool honourAxisOrientation = false; - if ( mShared->mWFSVersion.startsWith( "1.0" ) ) + if ( mShared->mWFSVersion.startsWith( QLatin1String( "1.0" ) ) ) { gmlVersion = QgsOgcUtils::GML_2_1_2; filterVersion = QgsOgcUtils::FILTER_OGC_1_0; } - else if ( mShared->mWFSVersion.startsWith( "1.1" ) ) + else if ( mShared->mWFSVersion.startsWith( QLatin1String( "1.1" ) ) ) { honourAxisOrientation = !mShared->mURI.ignoreAxisOrientation(); gmlVersion = QgsOgcUtils::GML_3_1_0; @@ -289,12 +289,12 @@ QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool fo andElem.appendChild( filterNode ); doc.firstChildElement().appendChild( andElem ); - getFeatureUrl.addQueryItem( "FILTER", sanitizeFilter( doc.toString() ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "FILTER" ), sanitizeFilter( doc.toString() ) ); } else if ( !mShared->mRect.isNull() ) { bool invertAxis = false; - if ( !mShared->mWFSVersion.startsWith( "1.0" ) && !mShared->mURI.ignoreAxisOrientation() && + if ( !mShared->mWFSVersion.startsWith( QLatin1String( "1.0" ) ) && !mShared->mURI.ignoreAxisOrientation() && mShared->mSourceCRS.hasAxisInverted() ) { invertAxis = true; @@ -310,22 +310,22 @@ QUrl QgsWFSFeatureDownloader::buildURL( int startIndex, int maxFeatures, bool fo qgsDoubleToString( mShared->mRect.yMaximum() ) ) ); // Some servers like Geomedia need the srsname to be explictly appended // otherwise they are confused and do not interpret it properly - if ( !mShared->mWFSVersion.startsWith( "1.0" ) ) + if ( !mShared->mWFSVersion.startsWith( QLatin1String( "1.0" ) ) ) { // but it is illegal in WFS 1.0 and some servers definitely not like // it. See #15464 bbox += "," + mShared->srsName(); } - getFeatureUrl.addQueryItem( "BBOX", bbox ); + getFeatureUrl.addQueryItem( QStringLiteral( "BBOX" ), bbox ); } else if ( !mShared->mWFSFilter.isEmpty() ) { - getFeatureUrl.addQueryItem( "FILTER", sanitizeFilter( mShared->mWFSFilter ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "FILTER" ), sanitizeFilter( mShared->mWFSFilter ) ); } if ( !mShared->mSortBy.isEmpty() && !forHits ) { - getFeatureUrl.addQueryItem( "SORTBY", mShared->mSortBy ); + getFeatureUrl.addQueryItem( QStringLiteral( "SORTBY" ), mShared->mSortBy ); } return getFeatureUrl; @@ -379,7 +379,7 @@ void QgsWFSFeatureDownloader::run( bool serializeFeatures, int maxFeatures ) { Q_FOREACH ( QWidget* widget, qApp->topLevelWidgets() ) { - if ( widget->objectName() == "QgisApp" ) + if ( widget->objectName() == QLatin1String( "QgisApp" ) ) { mMainWindow = widget; break; @@ -402,7 +402,7 @@ void QgsWFSFeatureDownloader::run( bool serializeFeatures, int maxFeatures ) bool interrupted = false; bool truncatedResponse = false; QSettings s; - const int maxRetry = s.value( "/qgis/defaultTileMaxRetry", "3" ).toInt(); + const int maxRetry = s.value( QStringLiteral( "/qgis/defaultTileMaxRetry" ), "3" ).toInt(); int retryIter = 0; int lastValidTotalDownloadedFeatureCount = 0; int pagingIter = 1; @@ -417,9 +417,9 @@ void QgsWFSFeatureDownloader::run( bool serializeFeatures, int maxFeatures ) maxFeatures ? maxFeatures : mShared->mMaxFeatures, false ) ); // Small hack for testing purposes - if ( retryIter > 0 && url.toString().contains( "fake_qgis_http_endpoint" ) ) + if ( retryIter > 0 && url.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) ) { - url.addQueryItem( "RETRY", QString::number( retryIter ) ); + url.addQueryItem( QStringLiteral( "RETRY" ), QString::number( retryIter ) ); } sendGET( url, @@ -471,14 +471,14 @@ void QgsWFSFeatureDownloader::run( bool serializeFeatures, int maxFeatures ) // e.g. http://ows.region-bretagne.fr/geoserver/wfs?SERVICE=WFS&REQUEST=GetFeature&VERSION=2.0.0&TYPENAMES=rb:etudes&STARTINDEX=0&COUNT=1 // Disabling paging helps in those cases if ( mSupportsPaging && mTotalDownloadedFeatureCount == 0 && - parser->exceptionText().contains( "Cannot do natural order without a primary key" ) ) + parser->exceptionText().contains( QLatin1String( "Cannot do natural order without a primary key" ) ) ) { QgsDebugMsg( QString( "Got exception %1. Re-trying with paging disabled" ).arg( parser->exceptionText() ) ); mSupportsPaging = false; } // GeoServer doesn't like typenames prefixed by namespace prefix, despite // the examples in the WFS 2.0 spec showing that - else if ( !mRemoveNSPrefix && parser->exceptionText().contains( "more than one feature type" ) ) + else if ( !mRemoveNSPrefix && parser->exceptionText().contains( QLatin1String( "more than one feature type" ) ) ) { QgsDebugMsg( QString( "Got exception %1. Re-trying by removing namespace prefix" ).arg( parser->exceptionText() ) ); mRemoveNSPrefix = true; @@ -549,8 +549,8 @@ void QgsWFSFeatureDownloader::run( bool serializeFeatures, int maxFeatures ) // Heuristics to try to detect MapServer WFS 1.1 that honours EPSG axis order, but returns // EPSG:XXXX srsName and not EPSG urns if ( pagingIter == 1 && featureCountForThisResponse == 0 && - mShared->mWFSVersion.startsWith( "1.1" ) && - parser->srsName().startsWith( "EPSG:" ) && + mShared->mWFSVersion.startsWith( QLatin1String( "1.1" ) ) && + parser->srsName().startsWith( QLatin1String( "EPSG:" ) ) && !parser->layerExtent().isNull() && !mShared->mURI.ignoreAxisOrientation() && !mShared->mURI.invertAxisOrientation() ) @@ -906,7 +906,7 @@ void QgsWFSFeatureIterator::featureReceivedSynchronous( const QVector<QgsWFSFeat QString thisStr; thisStr.sprintf( "%p", this ); ++ mCounter; - mWriterFilename = QDir( QgsWFSUtils::acquireCacheDirectory() ).filePath( QString( "iterator_%1_%2.bin" ).arg( thisStr ).arg( mCounter ) ); + mWriterFilename = QDir( QgsWFSUtils::acquireCacheDirectory() ).filePath( QStringLiteral( "iterator_%1_%2.bin" ).arg( thisStr ).arg( mCounter ) ); QgsDebugMsg( QString( "Transferring feature iterator cache to %1" ).arg( mWriterFilename ) ); mWriterFile = new QFile( mWriterFilename ); if ( !mWriterFile->open( QIODevice::WriteOnly | QIODevice::Truncate ) ) diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index 2f79a5ecc6b9..fb371b40fdb2 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -48,8 +48,8 @@ #include <cfloat> -static const QString TEXT_PROVIDER_KEY = "WFS"; -static const QString TEXT_PROVIDER_DESCRIPTION = "WFS data provider"; +static const QString TEXT_PROVIDER_KEY = QStringLiteral( "WFS" ); +static const QString TEXT_PROVIDER_DESCRIPTION = QStringLiteral( "WFS data provider" ); QgsWFSProvider::QgsWFSProvider( const QString& uri, const QgsWfsCapabilities::Capabilities &caps ) : QgsVectorDataProvider( uri ) @@ -72,8 +72,8 @@ QgsWFSProvider::QgsWFSProvider( const QString& uri, const QgsWfsCapabilities::Ca QString srsname = mShared->mURI.SRSName(); if ( !srsname.isEmpty() ) { - if ( srsname == "EPSG:900913" ) - mShared->mSourceCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:3857" ); + if ( srsname == QLatin1String( "EPSG:900913" ) ) + mShared->mSourceCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:3857" ) ); else mShared->mSourceCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( srsname ); } @@ -280,26 +280,26 @@ bool QgsWFSProvider::processSQL( const QString& sqlString, QString& errorMsg, QS if ( sql.hasParserError() ) { QString parserErrorString( sql.parserErrorString() ); - QStringList parts( parserErrorString.split( "," ) ); - parserErrorString = ""; + QStringList parts( parserErrorString.split( QStringLiteral( "," ) ) ); + parserErrorString = QLatin1String( "" ); Q_FOREACH ( const QString& part, parts ) { QString newPart( part ); - if ( part == "syntax error" ) + if ( part == QLatin1String( "syntax error" ) ) newPart = tr( "Syntax error." ); - else if ( part == " unexpected $end" ) + else if ( part == QLatin1String( " unexpected $end" ) ) newPart = tr( "Missing content at end of string." ); - else if ( part.startsWith( " unexpected " ) ) - newPart = tr( "%1 is unexpected." ).arg( part.mid( QString( " unexpected " ).size() ) ); - else if ( part.startsWith( " expecting " ) ) - newPart = tr( "%1 is expected instead." ).arg( part.mid( QString( " expecting " ).size() ) ); + else if ( part.startsWith( QLatin1String( " unexpected " ) ) ) + newPart = tr( "%1 is unexpected." ).arg( part.mid( QStringLiteral( " unexpected " ).size() ) ); + else if ( part.startsWith( QLatin1String( " expecting " ) ) ) + newPart = tr( "%1 is expected instead." ).arg( part.mid( QStringLiteral( " expecting " ).size() ) ); if ( !parserErrorString.isEmpty() ) - parserErrorString += " "; + parserErrorString += QLatin1String( " " ); parserErrorString += newPart; } - parserErrorString.replace( " or ", tr( "%1 or %2" ).arg( "", "" ) ); - parserErrorString.replace( "COMMA", tr( "comma" ) ); - parserErrorString.replace( "IDENTIFIER", tr( "an identifier" ) ); + parserErrorString.replace( QLatin1String( " or " ), tr( "%1 or %2" ).arg( QLatin1String( "" ), QLatin1String( "" ) ) ); + parserErrorString.replace( QLatin1String( "COMMA" ), tr( "comma" ) ); + parserErrorString.replace( QLatin1String( "IDENTIFIER" ), tr( "an identifier" ) ); errorMsg = tr( "SQL query is invalid: %1" ).arg( parserErrorString ); return false; } @@ -413,7 +413,7 @@ bool QgsWFSProvider::processSQL( const QString& sqlString, QString& errorMsg, QS Q_FOREACH ( const QString& typeName, typenameList ) { if ( !concatenatedTypenames.isEmpty() ) - concatenatedTypenames += ","; + concatenatedTypenames += QLatin1String( "," ); concatenatedTypenames += typeName; } @@ -673,10 +673,10 @@ bool QgsWFSProvider::setSubsetString( const QString& theSQL, bool updateFeatureC mShared->mLayerPropertiesList.clear(); mShared->mMapFieldNameToSrcLayerNameFieldName.clear(); mShared->mDistinctSelect = false; - if ( theSQL.startsWith( "SELECT ", Qt::CaseInsensitive ) || - theSQL.startsWith( "SELECT\t", Qt::CaseInsensitive ) || - theSQL.startsWith( "SELECT\r", Qt::CaseInsensitive ) || - theSQL.startsWith( "SELECT\n", Qt::CaseInsensitive ) ) + if ( theSQL.startsWith( QLatin1String( "SELECT " ), Qt::CaseInsensitive ) || + theSQL.startsWith( QLatin1String( "SELECT\t" ), Qt::CaseInsensitive ) || + theSQL.startsWith( QLatin1String( "SELECT\r" ), Qt::CaseInsensitive ) || + theSQL.startsWith( QLatin1String( "SELECT\n" ), Qt::CaseInsensitive ) ) { QString errorMsg, warningMsg; if ( !processSQL( theSQL, errorMsg, warningMsg ) ) @@ -799,7 +799,7 @@ bool QgsWFSProvider::addFeatures( QgsFeatureList &flist ) for ( ; featureIt != flist.end(); ++featureIt ) { //Insert element - QDomElement insertElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Insert" ); + QDomElement insertElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Insert" ) ); transactionElem.appendChild( insertElem ); QDomElement featureElem = transactionDoc.createElementNS( mApplicationNamespace, tname ); @@ -832,7 +832,7 @@ bool QgsWFSProvider::addFeatures( QgsFeatureList &flist ) QDomElement gmlElem = QgsOgcUtils::geometryToGML( &the_geom, transactionDoc ); if ( !gmlElem.isNull() ) { - gmlElem.setAttribute( "srsName", crs().authid() ); + gmlElem.setAttribute( QStringLiteral( "srsName" ), crs().authid() ); geomElem.appendChild( gmlElem ); featureElem.appendChild( geomElem ); } @@ -903,9 +903,9 @@ bool QgsWFSProvider::deleteFeatures( const QgsFeatureIds &id ) QDomElement transactionElem = createTransactionElement( transactionDoc ); transactionDoc.appendChild( transactionElem ); //delete element - QDomElement deleteElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Delete" ); - deleteElem.setAttribute( "typeName", tname ); - QDomElement filterElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, "Filter" ); + QDomElement deleteElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Delete" ) ); + deleteElem.setAttribute( QStringLiteral( "typeName" ), tname ); + QDomElement filterElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "Filter" ) ); QgsFeatureIds::const_iterator idIt = id.constBegin(); @@ -918,8 +918,8 @@ bool QgsWFSProvider::deleteFeatures( const QgsFeatureIds &id ) QgsDebugMsg( QString( "Cannot identify feature of id %1" ).arg( *idIt ) ); continue; } - QDomElement featureIdElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, "FeatureId" ); - featureIdElem.setAttribute( "fid", gmlid ); + QDomElement featureIdElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "FeatureId" ) ); + featureIdElem.setAttribute( QStringLiteral( "fid" ), gmlid ); filterElem.appendChild( featureIdElem ); } @@ -968,25 +968,25 @@ bool QgsWFSProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) QgsDebugMsg( QString( "Cannot identify feature of id %1" ).arg( geomIt.key() ) ); continue; } - QDomElement updateElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Update" ); - updateElem.setAttribute( "typeName", tname ); + QDomElement updateElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Update" ) ); + updateElem.setAttribute( QStringLiteral( "typeName" ), tname ); //Property - QDomElement propertyElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Property" ); - QDomElement nameElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Name" ); + QDomElement propertyElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Property" ) ); + QDomElement nameElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Name" ) ); QDomText nameText = transactionDoc.createTextNode( mShared->mGeometryAttribute ); nameElem.appendChild( nameText ); propertyElem.appendChild( nameElem ); - QDomElement valueElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Value" ); + QDomElement valueElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Value" ) ); QDomElement gmlElem = QgsOgcUtils::geometryToGML( &geomIt.value(), transactionDoc ); - gmlElem.setAttribute( "srsName", crs().authid() ); + gmlElem.setAttribute( QStringLiteral( "srsName" ), crs().authid() ); valueElem.appendChild( gmlElem ); propertyElem.appendChild( valueElem ); updateElem.appendChild( propertyElem ); //filter - QDomElement filterElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, "Filter" ); - QDomElement featureIdElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, "FeatureId" ); - featureIdElem.setAttribute( "fid", gmlid ); + QDomElement filterElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "Filter" ) ); + QDomElement featureIdElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "FeatureId" ) ); + featureIdElem.setAttribute( QStringLiteral( "fid" ), gmlid ); filterElem.appendChild( featureIdElem ); updateElem.appendChild( filterElem ); @@ -1049,21 +1049,21 @@ bool QgsWFSProvider::changeAttributeValues( const QgsChangedAttributesMap &attr_ continue; } - QDomElement updateElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Update" ); - updateElem.setAttribute( "typeName", tname ); + QDomElement updateElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Update" ) ); + updateElem.setAttribute( QStringLiteral( "typeName" ), tname ); QgsAttributeMap::const_iterator attMapIt = attIt.value().constBegin(); for ( ; attMapIt != attIt.value().constEnd(); ++attMapIt ) { QString fieldName = mShared->mFields.at( attMapIt.key() ).name(); - QDomElement propertyElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Property" ); + QDomElement propertyElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Property" ) ); - QDomElement nameElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Name" ); + QDomElement nameElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Name" ) ); QDomText nameText = transactionDoc.createTextNode( fieldName ); nameElem.appendChild( nameText ); propertyElem.appendChild( nameElem ); - QDomElement valueElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Value" ); + QDomElement valueElem = transactionDoc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Value" ) ); QDomText valueText = transactionDoc.createTextNode( convertToXML( attMapIt.value() ) ); valueElem.appendChild( valueText ); propertyElem.appendChild( valueElem ); @@ -1072,9 +1072,9 @@ bool QgsWFSProvider::changeAttributeValues( const QgsChangedAttributesMap &attr_ } //Filter - QDomElement filterElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, "Filter" ); - QDomElement featureIdElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, "FeatureId" ); - featureIdElem.setAttribute( "fid", gmlid ); + QDomElement filterElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "Filter" ) ); + QDomElement featureIdElem = transactionDoc.createElementNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "FeatureId" ) ); + featureIdElem.setAttribute( QStringLiteral( "fid" ), gmlid ); filterElem.appendChild( featureIdElem ); updateElem.appendChild( filterElem ); @@ -1145,14 +1145,14 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, QString& errorMsg ) { //get the <schema> root element - QDomNodeList schemaNodeList = schemaDoc.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "schema" ); + QDomNodeList schemaNodeList = schemaDoc.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, QStringLiteral( "schema" ) ); if ( schemaNodeList.length() < 1 ) { errorMsg = tr( "Cannot find schema root element" ); return false; } QDomElement schemaElement = schemaNodeList.at( 0 ).toElement(); - mApplicationNamespace = schemaElement.attribute( "targetNamespace" ); + mApplicationNamespace = schemaElement.attribute( QStringLiteral( "targetNamespace" ) ); // Remove the namespace on the typename QString unprefixedTypename = prefixedTypename; @@ -1163,23 +1163,23 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, // Find the element whose name is the typename that interests us, and // collect the correspond type. - QDomElement elementElement = schemaElement.firstChildElement( "element" ); + QDomElement elementElement = schemaElement.firstChildElement( QStringLiteral( "element" ) ); QString elementTypeString; QDomElement complexTypeElement; while ( !elementElement.isNull() ) { - QString name = elementElement.attribute( "name" ); + QString name = elementElement.attribute( QStringLiteral( "name" ) ); if ( name == unprefixedTypename ) { - elementTypeString = elementElement.attribute( "type" ); + elementTypeString = elementElement.attribute( QStringLiteral( "type" ) ); if ( elementTypeString.isEmpty() ) { // e.g http://afnemers.ruimtelijkeplannen.nl/afnemers2012/services?SERVICE=WFS&REQUEST=DescribeFeatureType&VERSION=2.0.0&TYPENAME=app:Bouwvlak - complexTypeElement = elementElement.firstChildElement( "complexType" ); + complexTypeElement = elementElement.firstChildElement( QStringLiteral( "complexType" ) ); } break; } - elementElement = elementElement.nextSiblingElement( "element" ); + elementElement = elementElement.nextSiblingElement( QStringLiteral( "element" ) ); } if ( elementTypeString.isEmpty() && complexTypeElement.isNull() ) { @@ -1189,9 +1189,9 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, bool foundImport = false; while ( !iter.isNull() ) { - if ( iter.tagName() == "import" ) + if ( iter.tagName() == QLatin1String( "import" ) ) foundImport = true; - else if ( iter.tagName() != "include" ) + else if ( iter.tagName() != QLatin1String( "include" ) ) { onlyIncludeOrImport = false; break; @@ -1219,15 +1219,15 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, if ( complexTypeElement.isNull() ) { //the <complexType> element corresponding to the feature type - complexTypeElement = schemaElement.firstChildElement( "complexType" ); + complexTypeElement = schemaElement.firstChildElement( QStringLiteral( "complexType" ) ); while ( !complexTypeElement.isNull() ) { - QString name = complexTypeElement.attribute( "name" ); + QString name = complexTypeElement.attribute( QStringLiteral( "name" ) ); if ( name == elementTypeString ) { break; } - complexTypeElement = complexTypeElement.nextSiblingElement( "complexType" ); + complexTypeElement = complexTypeElement.nextSiblingElement( QStringLiteral( "complexType" ) ); } if ( complexTypeElement.isNull() ) { @@ -1237,7 +1237,7 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, } //we have the relevant <complexType> element. Now find out the geometry and the thematic attributes - QDomNodeList attributeNodeList = complexTypeElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, "element" ); + QDomNodeList attributeNodeList = complexTypeElement.elementsByTagNameNS( QgsWFSConstants::XMLSCHEMA_NAMESPACE, QStringLiteral( "element" ) ); if ( attributeNodeList.size() < 1 ) { errorMsg = tr( "Cannot find attribute elements" ); @@ -1251,7 +1251,7 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, QDomElement attributeElement = attributeNodeList.at( i ).toElement(); //attribute name - QString name = attributeElement.attribute( "name" ); + QString name = attributeElement.attribute( QStringLiteral( "name" ) ); // Some servers like http://ogi.state.ok.us/geoserver/wfs on layer ogi:doq_centroids // return attribute names padded with spaces. See http://hub.qgis.org/issues/3426 // I'm not completely sure how legal this @@ -1259,20 +1259,20 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, name = name.trimmed(); //attribute type - QString type = attributeElement.attribute( "type" ); + QString type = attributeElement.attribute( QStringLiteral( "type" ) ); if ( type.isEmpty() ) { - QDomElement extension = attributeElement.firstChildElement( "complexType" ). - firstChildElement( "simpleContent" ).firstChildElement( "extension" ); + QDomElement extension = attributeElement.firstChildElement( QStringLiteral( "complexType" ) ). + firstChildElement( QStringLiteral( "simpleContent" ) ).firstChildElement( QStringLiteral( "extension" ) ); if ( !extension.isNull() ) { - type = extension.attribute( "base" ); + type = extension.attribute( QStringLiteral( "base" ) ); } } QRegExp gmlPT( "gml:(.*)PropertyType" ); // gmgml: is Geomedia Web Server - if ( type == "gmgml:Polygon_Surface_MultiSurface_CompositeSurfacePropertyType" ) + if ( type == QLatin1String( "gmgml:Polygon_Surface_MultiSurface_CompositeSurfacePropertyType" ) ) { foundGeometryAttribute = true; geometryAttribute = name; @@ -1281,7 +1281,7 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, //is it a geometry attribute? //MH 090428: sometimes the <element> tags for geometry attributes have only attribute ref="gml:polygonProperty" and no name // the GeometryAssociationType has been seen in #11785 - else if ( type.indexOf( gmlPT ) == 0 || type == "gml:GeometryAssociationType" || name.isEmpty() ) + else if ( type.indexOf( gmlPT ) == 0 || type == QLatin1String( "gml:GeometryAssociationType" ) || name.isEmpty() ) { foundGeometryAttribute = true; geometryAttribute = name; @@ -1290,20 +1290,20 @@ bool QgsWFSProvider::readAttributesFromSchema( QDomDocument& schemaDoc, else //todo: distinguish between numerical and non-numerical types { QVariant::Type attributeType = QVariant::String; //string is default type - if ( type.contains( "double", Qt::CaseInsensitive ) || type.contains( "float", Qt::CaseInsensitive ) || type.contains( "decimal", Qt::CaseInsensitive ) ) + if ( type.contains( QLatin1String( "double" ), Qt::CaseInsensitive ) || type.contains( QLatin1String( "float" ), Qt::CaseInsensitive ) || type.contains( QLatin1String( "decimal" ), Qt::CaseInsensitive ) ) { attributeType = QVariant::Double; } - else if ( type.contains( "int", Qt::CaseInsensitive ) || - type.contains( "short", Qt::CaseInsensitive ) ) + else if ( type.contains( QLatin1String( "int" ), Qt::CaseInsensitive ) || + type.contains( QLatin1String( "short" ), Qt::CaseInsensitive ) ) { attributeType = QVariant::Int; } - else if ( type.contains( "long", Qt::CaseInsensitive ) ) + else if ( type.contains( QLatin1String( "long" ), Qt::CaseInsensitive ) ) { attributeType = QVariant::LongLong; } - else if ( type.contains( "dateTime", Qt::CaseInsensitive ) ) + else if ( type.contains( QLatin1String( "dateTime" ), Qt::CaseInsensitive ) ) { attributeType = QVariant::DateTime; } @@ -1346,20 +1346,20 @@ bool QgsWFSProvider::sendTransactionDocument( const QDomDocument& doc, QDomDocum QDomElement QgsWFSProvider::createTransactionElement( QDomDocument& doc ) const { - QDomElement transactionElem = doc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, "Transaction" ); - transactionElem.setAttribute( "version", "1.0.0" ); - transactionElem.setAttribute( "service", "WFS" ); - transactionElem.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + QDomElement transactionElem = doc.createElementNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Transaction" ) ); + transactionElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) ); + transactionElem.setAttribute( QStringLiteral( "service" ), QStringLiteral( "WFS" ) ); + transactionElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); QUrl describeFeatureTypeURL( mShared->mURI.baseURL() ); // For tests (since the URL contains part of random data, we need to replace it with a fixed content) - if ( mShared->mURI.baseURL().toString().contains( "fake_qgis_http_endpoint" ) ) - describeFeatureTypeURL = QUrl( "http://fake_qgis_http_endpoint" ); - describeFeatureTypeURL.addQueryItem( "REQUEST", "DescribeFeatureType" ); - describeFeatureTypeURL.addQueryItem( "VERSION", "1.0.0" ); - describeFeatureTypeURL.addQueryItem( "TYPENAME", mShared->mURI.typeName() ); + if ( mShared->mURI.baseURL().toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) ) + describeFeatureTypeURL = QUrl( QStringLiteral( "http://fake_qgis_http_endpoint" ) ); + describeFeatureTypeURL.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "DescribeFeatureType" ) ); + describeFeatureTypeURL.addQueryItem( QStringLiteral( "VERSION" ), QStringLiteral( "1.0.0" ) ); + describeFeatureTypeURL.addQueryItem( QStringLiteral( "TYPENAME" ), mShared->mURI.typeName() ); - transactionElem.setAttribute( "xsi:schemaLocation", mApplicationNamespace + ' ' + transactionElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), mApplicationNamespace + ' ' + describeFeatureTypeURL.toEncoded() ); QString namespacePrefix = QgsWFSUtils::nameSpacePrefix( mShared->mURI.typeName() ); @@ -1367,7 +1367,7 @@ QDomElement QgsWFSProvider::createTransactionElement( QDomDocument& doc ) const { transactionElem.setAttribute( "xmlns:" + namespacePrefix, mApplicationNamespace ); } - transactionElem.setAttribute( "xmlns:gml", QgsWFSConstants::GML_NAMESPACE ); + transactionElem.setAttribute( QStringLiteral( "xmlns:gml" ), QgsWFSConstants::GML_NAMESPACE ); return transactionElem; } @@ -1385,19 +1385,19 @@ bool QgsWFSProvider::transactionSuccess( const QDomDocument& serverResponse ) co return false; } - QDomNodeList transactionResultList = documentElem.elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, "TransactionResult" ); + QDomNodeList transactionResultList = documentElem.elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "TransactionResult" ) ); if ( transactionResultList.size() < 1 ) { return false; } - QDomNodeList statusList = transactionResultList.at( 0 ).toElement().elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, "Status" ); + QDomNodeList statusList = transactionResultList.at( 0 ).toElement().elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "Status" ) ); if ( statusList.size() < 1 ) { return false; } - if ( statusList.at( 0 ).firstChildElement().localName() == "SUCCESS" ) + if ( statusList.at( 0 ).firstChildElement().localName() == QLatin1String( "SUCCESS" ) ) { return true; } @@ -1421,13 +1421,13 @@ QStringList QgsWFSProvider::insertedFeatureIds( const QDomDocument& serverRespon return ids; } - QDomNodeList insertResultList = rootElem.elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, "InsertResult" ); + QDomNodeList insertResultList = rootElem.elementsByTagNameNS( QgsWFSConstants::WFS_NAMESPACE, QStringLiteral( "InsertResult" ) ); for ( int i = 0; i < insertResultList.size(); ++i ) { - QDomNodeList featureIdList = insertResultList.at( i ).toElement().elementsByTagNameNS( QgsWFSConstants::OGC_NAMESPACE, "FeatureId" ); + QDomNodeList featureIdList = insertResultList.at( i ).toElement().elementsByTagNameNS( QgsWFSConstants::OGC_NAMESPACE, QStringLiteral( "FeatureId" ) ); for ( int j = 0; j < featureIdList.size(); ++j ) { - QString fidString = featureIdList.at( j ).toElement().attribute( "fid" ); + QString fidString = featureIdList.at( j ).toElement().attribute( QStringLiteral( "fid" ) ); if ( !fidString.isEmpty() ) { ids << fidString; @@ -1466,7 +1466,7 @@ bool QgsWFSProvider::getCapabilities() if ( mShared->mMaxFeatures <= 0 && mShared->mCaps.supportsPaging ) { QSettings settings; - mShared->mMaxFeatures = settings.value( "wfs/max_feature_count_if_not_provided", "1000" ).toInt(); + mShared->mMaxFeatures = settings.value( QStringLiteral( "wfs/max_feature_count_if_not_provided" ), "1000" ).toInt(); mShared->mMaxFeaturesWasSetFromDefaultForPaging = true; QgsDebugMsg( QString( "Server declares paging but does not advertize max feature count and user did not specify it. Using %1" ).arg( mShared->mMaxFeatures ) ); } @@ -1487,7 +1487,7 @@ bool QgsWFSProvider::getCapabilities() { if ( mShared->mCaps.featureTypes[i].bboxSRSIsWGS84 ) { - QgsCoordinateReferenceSystem src = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "CRS:84" ); + QgsCoordinateReferenceSystem src = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "CRS:84" ) ); QgsCoordinateTransform ct( src, mShared->mSourceCRS ); QgsDebugMsg( "latlon ext:" + r.toString() ); @@ -1536,17 +1536,17 @@ QgsWkbTypes::Type QgsWFSProvider::geomTypeFromPropertyType( const QString& attNa QgsDebugMsg( QString( "DescribeFeatureType geometry attribute \"%1\" type is \"%2\"" ) .arg( attName, propType ) ); - if ( propType == "Point" ) + if ( propType == QLatin1String( "Point" ) ) return QgsWkbTypes::Point; - if ( propType == "LineString" || propType == "Curve" ) + if ( propType == QLatin1String( "LineString" ) || propType == QLatin1String( "Curve" ) ) return QgsWkbTypes::LineString; - if ( propType == "Polygon" || propType == "Surface" ) + if ( propType == QLatin1String( "Polygon" ) || propType == QLatin1String( "Surface" ) ) return QgsWkbTypes::Polygon; - if ( propType == "MultiPoint" ) + if ( propType == QLatin1String( "MultiPoint" ) ) return QgsWkbTypes::MultiPoint; - if ( propType == "MultiLineString" || propType == "MultiCurve" ) + if ( propType == QLatin1String( "MultiLineString" ) || propType == QLatin1String( "MultiCurve" ) ) return QgsWkbTypes::MultiLineString; - if ( propType == "MultiPolygon" || propType == "MultiSurface" ) + if ( propType == QLatin1String( "MultiPolygon" ) || propType == QLatin1String( "MultiSurface" ) ) return QgsWkbTypes::MultiPolygon; return QgsWkbTypes::Unknown; } @@ -1562,24 +1562,24 @@ void QgsWFSProvider::handleException( const QDomDocument& serverResponse ) return; } - if ( exceptionElem.tagName() == "ServiceExceptionReport" ) + if ( exceptionElem.tagName() == QLatin1String( "ServiceExceptionReport" ) ) { - pushError( tr( "WFS service exception:%1" ).arg( exceptionElem.firstChildElement( "ServiceException" ).text() ) ); + pushError( tr( "WFS service exception:%1" ).arg( exceptionElem.firstChildElement( QStringLiteral( "ServiceException" ) ).text() ) ); return; } - if ( exceptionElem.tagName() == "WFS_TransactionResponse" ) + if ( exceptionElem.tagName() == QLatin1String( "WFS_TransactionResponse" ) ) { - pushError( tr( "unsuccessful service response: %1" ).arg( exceptionElem.firstChildElement( "TransactionResult" ).firstChildElement( "Message" ).text() ) ); + pushError( tr( "unsuccessful service response: %1" ).arg( exceptionElem.firstChildElement( QStringLiteral( "TransactionResult" ) ).firstChildElement( QStringLiteral( "Message" ) ).text() ) ); return; } - if ( exceptionElem.tagName() == "ExceptionReport" ) + if ( exceptionElem.tagName() == QLatin1String( "ExceptionReport" ) ) { - QDomElement exception = exceptionElem.firstChildElement( "Exception" ); + QDomElement exception = exceptionElem.firstChildElement( QStringLiteral( "Exception" ) ); pushError( tr( "WFS exception report (code=%1 text=%2)" ) - .arg( exception.attribute( "exceptionCode", tr( "missing" ) ), - exception.firstChildElement( "ExceptionText" ).text() ) + .arg( exception.attribute( QStringLiteral( "exceptionCode" ), tr( "missing" ) ), + exception.firstChildElement( QStringLiteral( "ExceptionText" ) ).text() ) ); return; } diff --git a/src/providers/wfs/qgswfsrequest.cpp b/src/providers/wfs/qgswfsrequest.cpp index dbf38eb0a359..4ad748eb061a 100644 --- a/src/providers/wfs/qgswfsrequest.cpp +++ b/src/providers/wfs/qgswfsrequest.cpp @@ -61,14 +61,14 @@ bool QgsWfsRequest::sendGET( const QUrl& url, bool synchronous, bool forceRefres mResponse.clear(); QUrl modifiedUrl( url ); - if ( modifiedUrl.toString().contains( "fake_qgis_http_endpoint" ) ) + if ( modifiedUrl.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) ) { // Just for testing with local files instead of http:// ressources QString modifiedUrlString = modifiedUrl.toString(); // Qt5 does URL encoding from some reason (of the FILTER parameter for example) modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() ); QgsDebugMsg( QString( "Get %1" ).arg( modifiedUrlString ) ); - modifiedUrlString = modifiedUrlString.mid( QString( "http://" ).size() ); + modifiedUrlString = modifiedUrlString.mid( QStringLiteral( "http://" ).size() ); QString args = modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) ); if ( modifiedUrlString.size() > 256 ) { @@ -76,16 +76,16 @@ bool QgsWfsRequest::sendGET( const QUrl& url, bool synchronous, bool forceRefres } else { - args.replace( "?", "_" ); - args.replace( "&", "_" ); - args.replace( "<", "_" ); - args.replace( ">", "_" ); - args.replace( "'", "_" ); - args.replace( "\"", "_" ); - args.replace( " ", "_" ); - args.replace( ":", "_" ); - args.replace( "/", "_" ); - args.replace( "\n", "_" ); + args.replace( QLatin1String( "?" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( "&" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( "<" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( ">" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( "'" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( "\"" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( " " ), QLatin1String( "_" ) ); + args.replace( QLatin1String( ":" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( "/" ), QLatin1String( "_" ) ); + args.replace( QLatin1String( "\n" ), QLatin1String( "_" ) ); } #ifdef Q_OS_WIN // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c, @@ -152,7 +152,7 @@ bool QgsWfsRequest::sendPOST( const QUrl& url, const QString& contentTypeHeader, { // Hack for testing purposes QUrl modifiedUrl( url ); - modifiedUrl.addQueryItem( "POSTDATA", QString::fromUtf8( data ) ); + modifiedUrl.addQueryItem( QStringLiteral( "POSTDATA" ), QString::fromUtf8( data ) ); return sendGET( modifiedUrl, true, true, false ); } diff --git a/src/providers/wfs/qgswfsshareddata.cpp b/src/providers/wfs/qgswfsshareddata.cpp index da54b696b642..45200f1ea012 100644 --- a/src/providers/wfs/qgswfsshareddata.cpp +++ b/src/providers/wfs/qgswfsshareddata.cpp @@ -70,8 +70,8 @@ QString QgsWFSSharedData::srsName() const QString srsName; if ( !mSourceCRS.authid().isEmpty() ) { - if ( mWFSVersion.startsWith( "1.0" ) || - !mSourceCRS.authid().startsWith( "EPSG:" ) || + if ( mWFSVersion.startsWith( QLatin1String( "1.0" ) ) || + !mSourceCRS.authid().startsWith( QLatin1String( "EPSG:" ) ) || // For servers like Geomedia that advertize EPSG:XXXX in capabilities even in WFS 1.1 or 2.0 mCaps.useEPSGColumnFormat ) { @@ -80,7 +80,7 @@ QString QgsWFSSharedData::srsName() const else { QStringList list = mSourceCRS.authid().split( ':' ); - srsName = QString( "urn:ogc:def:crs:EPSG::%1" ).arg( list.last() ); + srsName = QStringLiteral( "urn:ogc:def:crs:EPSG::%1" ).arg( list.last() ); } } return srsName; @@ -95,12 +95,12 @@ bool QgsWFSSharedData::computeFilter( QString& errorMsg ) QgsOgcUtils::GMLVersion gmlVersion; QgsOgcUtils::FilterVersion filterVersion; bool honourAxisOrientation = false; - if ( mWFSVersion.startsWith( "1.0" ) ) + if ( mWFSVersion.startsWith( QLatin1String( "1.0" ) ) ) { gmlVersion = QgsOgcUtils::GML_2_1_2; filterVersion = QgsOgcUtils::FILTER_OGC_1_0; } - else if ( mWFSVersion.startsWith( "1.1" ) ) + else if ( mWFSVersion.startsWith( QLatin1String( "1.1" ) ) ) { honourAxisOrientation = !mURI.ignoreAxisOrientation(); gmlVersion = QgsOgcUtils::GML_3_1_0; @@ -128,14 +128,14 @@ bool QgsWFSSharedData::computeFilter( QString& errorMsg ) Q_FOREACH ( QgsSQLStatement::NodeColumnSorted* columnSorted, orderBy ) { if ( !mSortBy.isEmpty() ) - mSortBy += ","; + mSortBy += QLatin1String( "," ); mSortBy += columnSorted->column()->name(); if ( !columnSorted->ascending() ) { - if ( mWFSVersion.startsWith( "2.0" ) ) - mSortBy += " DESC"; + if ( mWFSVersion.startsWith( QLatin1String( "2.0" ) ) ) + mSortBy += QLatin1String( " DESC" ); else - mSortBy += " D"; + mSortBy += QLatin1String( " D" ); } } @@ -208,7 +208,7 @@ bool QgsWFSSharedData::computeFilter( QString& errorMsg ) static QString quotedIdentifier( QString id ) { - id.replace( '\"', "\"\"" ); + id.replace( '\"', QLatin1String( "\"\"" ) ); return id.prepend( '\"' ).append( '\"' ); } @@ -218,7 +218,7 @@ bool QgsWFSSharedData::createCache() static int tmpCounter = 0; ++tmpCounter; - mCacheDbname = QDir( QgsWFSUtils::acquireCacheDirectory() ).filePath( QString( "wfs_cache_%1.sqlite" ).arg( tmpCounter ) ); + mCacheDbname = QDir( QgsWFSUtils::acquireCacheDirectory() ).filePath( QStringLiteral( "wfs_cache_%1.sqlite" ).arg( tmpCounter ) ); QgsFields cacheFields; Q_FOREACH ( const QgsField& field, mFields ) @@ -234,29 +234,29 @@ bool QgsWFSSharedData::createCache() cacheFields.append( QgsField( field.name(), type, field.typeName() ) ); } // Add some field for our internal use - cacheFields.append( QgsField( QgsWFSConstants::FIELD_GEN_COUNTER, QVariant::Int, "int" ) ); - cacheFields.append( QgsField( QgsWFSConstants::FIELD_GMLID, QVariant::String, "string" ) ); - cacheFields.append( QgsField( QgsWFSConstants::FIELD_HEXWKB_GEOM, QVariant::String, "string" ) ); + cacheFields.append( QgsField( QgsWFSConstants::FIELD_GEN_COUNTER, QVariant::Int, QStringLiteral( "int" ) ) ); + cacheFields.append( QgsField( QgsWFSConstants::FIELD_GMLID, QVariant::String, QStringLiteral( "string" ) ) ); + cacheFields.append( QgsField( QgsWFSConstants::FIELD_HEXWKB_GEOM, QVariant::String, QStringLiteral( "string" ) ) ); if ( mDistinctSelect ) - cacheFields.append( QgsField( QgsWFSConstants::FIELD_MD5, QVariant::String, "string" ) ); + cacheFields.append( QgsField( QgsWFSConstants::FIELD_MD5, QVariant::String, QStringLiteral( "string" ) ) ); bool ogrWaySuccessful = false; - QString fidName( "__ogc_fid" ); - QString geometryFieldname( "__spatialite_geometry" ); + QString fidName( QStringLiteral( "__ogc_fid" ) ); + QString geometryFieldname( QStringLiteral( "__spatialite_geometry" ) ); #ifdef USE_OGR_FOR_DB_CREATION // Only GDAL >= 2.0 can use an alternate geometry or FID field name // but QgsVectorFileWriter will refuse anyway to create a ogc_fid, so we will // do it manually - bool useReservedNames = cacheFields.lookupField( "ogc_fid" ) >= 0; + bool useReservedNames = cacheFields.lookupField( QStringLiteral( "ogc_fid" ) ) >= 0; #if GDAL_VERSION_MAJOR < 2 - if ( cacheFields.lookupField( "geometry" ) >= 0 ) + if ( cacheFields.lookupField( QStringLiteral( "geometry" ) ) >= 0 ) useReservedNames = true; #endif if ( !useReservedNames ) { #if GDAL_VERSION_MAJOR < 2 - fidName = "ogc_fid"; - geometryFieldname = "GEOMETRY"; + fidName = QStringLiteral( "ogc_fid" ); + geometryFieldname = QStringLiteral( "GEOMETRY" ); #endif // Creating a spatialite database can be quite slow on some file systems // so we create a GDAL in-memory file, and then copy it on @@ -264,8 +264,8 @@ bool QgsWFSSharedData::createCache() QString vsimemFilename; QStringList datasourceOptions; QStringList layerOptions; - datasourceOptions.push_back( "INIT_WITH_EPSG=NO" ); - layerOptions.push_back( "LAUNDER=NO" ); // to get exact matches for field names, especially regarding case + datasourceOptions.push_back( QStringLiteral( "INIT_WITH_EPSG=NO" ) ); + layerOptions.push_back( QStringLiteral( "LAUNDER=NO" ) ); // to get exact matches for field names, especially regarding case #if GDAL_VERSION_MAJOR >= 2 layerOptions.push_back( "FID=__ogc_fid" ); layerOptions.push_back( "GEOMETRY_NAME=__spatialite_geometry" ); @@ -273,8 +273,8 @@ bool QgsWFSSharedData::createCache() vsimemFilename.sprintf( "/vsimem/qgis_wfs_cache_template_%p/features.sqlite", this ); mCacheTablename = CPLGetBasename( vsimemFilename.toStdString().c_str() ); VSIUnlink( vsimemFilename.toStdString().c_str() ); - QgsVectorFileWriter* writer = new QgsVectorFileWriter( vsimemFilename, "", - cacheFields, QgsWkbTypes::Polygon, QgsCoordinateReferenceSystem(), "SpatiaLite", datasourceOptions, layerOptions ); + QgsVectorFileWriter* writer = new QgsVectorFileWriter( vsimemFilename, QLatin1String( "" ), + cacheFields, QgsWkbTypes::Polygon, QgsCoordinateReferenceSystem(), QStringLiteral( "SpatiaLite" ), datasourceOptions, layerOptions ); if ( writer->hasError() == QgsVectorFileWriter::NoError ) { delete writer; @@ -321,7 +321,7 @@ bool QgsWFSSharedData::createCache() tempFile.open(); tempFile.setAutoRemove( false ); tempFile.close(); - QString spatialite_lib = QgsProviderRegistry::instance()->library( "spatialite" ); + QString spatialite_lib = QgsProviderRegistry::instance()->library( QStringLiteral( "spatialite" ) ); QLibrary* myLib = new QLibrary( spatialite_lib ); bool loaded = myLib->load(); bool created = false; @@ -381,20 +381,20 @@ bool QgsWFSSharedData::createCache() if ( !ogrWaySuccessful ) { - mCacheTablename = "features"; - sql = QString( "CREATE TABLE %1 (%2 INTEGER PRIMARY KEY" ).arg( mCacheTablename, fidName ); + mCacheTablename = QStringLiteral( "features" ); + sql = QStringLiteral( "CREATE TABLE %1 (%2 INTEGER PRIMARY KEY" ).arg( mCacheTablename, fidName ); Q_FOREACH ( const QgsField& field, cacheFields ) { - QString type( "VARCHAR" ); + QString type( QStringLiteral( "VARCHAR" ) ); if ( field.type() == QVariant::Int ) - type = "INTEGER"; + type = QStringLiteral( "INTEGER" ); else if ( field.type() == QVariant::LongLong ) - type = "BIGINT"; + type = QStringLiteral( "BIGINT" ); else if ( field.type() == QVariant::Double ) - type = "REAL"; - sql += QString( ", %1 %2" ).arg( quotedIdentifier( field.name() ), type ); + type = QStringLiteral( "REAL" ); + sql += QStringLiteral( ", %1 %2" ).arg( quotedIdentifier( field.name() ), type ); } - sql += ")"; + sql += QLatin1String( ")" ); rc = sqlite3_exec( db, sql.toUtf8(), nullptr, nullptr, nullptr ); if ( rc != SQLITE_OK ) { @@ -402,7 +402,7 @@ bool QgsWFSSharedData::createCache() ret = false; } - sql = QString( "SELECT AddGeometryColumn('%1','%2',0,'POLYGON',2)" ).arg( mCacheTablename, geometryFieldname ); + sql = QStringLiteral( "SELECT AddGeometryColumn('%1','%2',0,'POLYGON',2)" ).arg( mCacheTablename, geometryFieldname ); rc = sqlite3_exec( db, sql.toUtf8(), nullptr, nullptr, nullptr ); if ( rc != SQLITE_OK ) { @@ -410,7 +410,7 @@ bool QgsWFSSharedData::createCache() ret = false; } - sql = QString( "SELECT CreateSpatialIndex('%1','%2')" ).arg( mCacheTablename, geometryFieldname ); + sql = QStringLiteral( "SELECT CreateSpatialIndex('%1','%2')" ).arg( mCacheTablename, geometryFieldname ); rc = sqlite3_exec( db, sql.toUtf8(), nullptr, nullptr, nullptr ); if ( rc != SQLITE_OK ) { @@ -421,7 +421,7 @@ bool QgsWFSSharedData::createCache() // We need an index on the gmlid, since we will check for duplicates, particularly // useful in the case we do overlapping BBOX requests - sql = QString( "CREATE INDEX idx_%2 ON %1(%2)" ).arg( mCacheTablename, QgsWFSConstants::FIELD_GMLID ); + sql = QStringLiteral( "CREATE INDEX idx_%2 ON %1(%2)" ).arg( mCacheTablename, QgsWFSConstants::FIELD_GMLID ); rc = sqlite3_exec( db, sql.toUtf8(), nullptr, nullptr, nullptr ); if ( rc != SQLITE_OK ) { @@ -431,7 +431,7 @@ bool QgsWFSSharedData::createCache() if ( mDistinctSelect ) { - sql = QString( "CREATE INDEX idx_%2 ON %1(%2)" ).arg( mCacheTablename, QgsWFSConstants::FIELD_MD5 ); + sql = QStringLiteral( "CREATE INDEX idx_%2 ON %1(%2)" ).arg( mCacheTablename, QgsWFSConstants::FIELD_MD5 ); rc = sqlite3_exec( db, sql.toUtf8(), nullptr, nullptr, nullptr ); if ( rc != SQLITE_OK ) { @@ -458,13 +458,13 @@ bool QgsWFSSharedData::createCache() // regarding crashes, since this is a temporary DB QgsDataSourceUri dsURI; dsURI.setDatabase( mCacheDbname ); - dsURI.setDataSource( "", mCacheTablename, geometryFieldname, "", fidName ); + dsURI.setDataSource( QLatin1String( "" ), mCacheTablename, geometryFieldname, QLatin1String( "" ), fidName ); QStringList pragmas; - pragmas << "synchronous=OFF"; - pragmas << "journal_mode=WAL"; // WAL is needed to avoid reader to block writers - dsURI.setParam( "pragma", pragmas ); + pragmas << QStringLiteral( "synchronous=OFF" ); + pragmas << QStringLiteral( "journal_mode=WAL" ); // WAL is needed to avoid reader to block writers + dsURI.setParam( QStringLiteral( "pragma" ), pragmas ); mCacheDataProvider = ( QgsVectorDataProvider* )( QgsProviderRegistry::instance()->provider( - "spatialite", dsURI.uri() ) ); + QStringLiteral( "spatialite" ), dsURI.uri() ) ); if ( mCacheDataProvider && !mCacheDataProvider->isValid() ) { delete mCacheDataProvider; @@ -590,19 +590,19 @@ QSet<QString> QgsWFSSharedData::getExistingCachedGmlIds( const QVector<QgsWFSFea for ( int i = 0; i < featureList.size(); i ++ ) { if ( !first ) - expr += ","; + expr += QLatin1String( "," ); else { expr = QgsWFSConstants::FIELD_GMLID + " IN ("; first = false; } - expr += "'"; + expr += QLatin1String( "'" ); expr += featureList[i].second; - expr += "'"; + expr += QLatin1String( "'" ); if (( i > 0 && ( i % 1000 ) == 0 ) || i + 1 == featureList.size() ) { - expr += ")"; + expr += QLatin1String( ")" ); QgsFeatureRequest request; request.setFilterExpression( expr ); @@ -641,19 +641,19 @@ QSet<QString> QgsWFSSharedData::getExistingCachedMD5( const QVector<QgsWFSFeatur for ( int i = 0; i < featureList.size(); i ++ ) { if ( !first ) - expr += ","; + expr += QLatin1String( "," ); else { expr = QgsWFSConstants::FIELD_MD5 + " IN ("; first = false; } - expr += "'"; + expr += QLatin1String( "'" ); expr += QgsWFSUtils::getMD5( featureList[i].first ); - expr += "'"; + expr += QLatin1String( "'" ); if (( i > 0 && ( i % 1000 ) == 0 ) || i + 1 == featureList.size() ) { - expr += ")"; + expr += QLatin1String( ")" ); QgsFeatureRequest request; request.setFilterExpression( expr ); @@ -1067,7 +1067,7 @@ void QgsWFSSharedData::endOfDownload( bool success, int featureCount, msg += " " + tr( "Zoom in to fetch all data." ); else msg += " " + tr( "You may want to check the 'Only request features overlapping the view extent' option to be able to zoom in to fetch all data." ); - QgsMessageLog::logMessage( msg, "WFS" ); + QgsMessageLog::logMessage( msg, QStringLiteral( "WFS" ) ); } } @@ -1206,17 +1206,17 @@ int QgsWFSFeatureHitsRequest::getFeatureCount( const QString& WFSVersion, const QString& filter ) { QUrl getFeatureUrl( mUri.baseURL() ); - getFeatureUrl.addQueryItem( "REQUEST", "GetFeature" ); - getFeatureUrl.addQueryItem( "VERSION", WFSVersion ); - if ( WFSVersion.startsWith( "2.0" ) ) - getFeatureUrl.addQueryItem( "TYPENAMES", mUri.typeName() ); + getFeatureUrl.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetFeature" ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "VERSION" ), WFSVersion ); + if ( WFSVersion.startsWith( QLatin1String( "2.0" ) ) ) + getFeatureUrl.addQueryItem( QStringLiteral( "TYPENAMES" ), mUri.typeName() ); else - getFeatureUrl.addQueryItem( "TYPENAME", mUri.typeName() ); + getFeatureUrl.addQueryItem( QStringLiteral( "TYPENAME" ), mUri.typeName() ); if ( !filter.isEmpty() ) { - getFeatureUrl.addQueryItem( "FILTER", filter ); + getFeatureUrl.addQueryItem( QStringLiteral( "FILTER" ), filter ); } - getFeatureUrl.addQueryItem( "RESULTTYPE", "hits" ); + getFeatureUrl.addQueryItem( QStringLiteral( "RESULTTYPE" ), QStringLiteral( "hits" ) ); if ( !sendGET( getFeatureUrl, true ) ) return -1; @@ -1236,8 +1236,8 @@ int QgsWFSFeatureHitsRequest::getFeatureCount( const QString& WFSVersion, QDomElement doc = domDoc.documentElement(); QString numberOfFeatures = - ( WFSVersion.startsWith( "1.1" ) ) ? doc.attribute( "numberOfFeatures" ) : - /* 2.0 */ doc.attribute( "numberMatched" ) ; + ( WFSVersion.startsWith( QLatin1String( "1.1" ) ) ) ? doc.attribute( QStringLiteral( "numberOfFeatures" ) ) : + /* 2.0 */ doc.attribute( QStringLiteral( "numberMatched" ) ) ; if ( !numberOfFeatures.isEmpty() ) { bool isValid; @@ -1271,16 +1271,16 @@ QgsWFSSingleFeatureRequest::~QgsWFSSingleFeatureRequest() QgsRectangle QgsWFSSingleFeatureRequest::getExtent() { QUrl getFeatureUrl( mUri.baseURL() ); - getFeatureUrl.addQueryItem( "REQUEST", "GetFeature" ); - getFeatureUrl.addQueryItem( "VERSION", mShared->mWFSVersion ); - if ( mShared->mWFSVersion .startsWith( "2.0" ) ) - getFeatureUrl.addQueryItem( "TYPENAMES", mUri.typeName() ); + getFeatureUrl.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetFeature" ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "VERSION" ), mShared->mWFSVersion ); + if ( mShared->mWFSVersion .startsWith( QLatin1String( "2.0" ) ) ) + getFeatureUrl.addQueryItem( QStringLiteral( "TYPENAMES" ), mUri.typeName() ); else - getFeatureUrl.addQueryItem( "TYPENAME", mUri.typeName() ); - if ( mShared->mWFSVersion .startsWith( "2.0" ) ) - getFeatureUrl.addQueryItem( "COUNT", QString::number( 1 ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "TYPENAME" ), mUri.typeName() ); + if ( mShared->mWFSVersion .startsWith( QLatin1String( "2.0" ) ) ) + getFeatureUrl.addQueryItem( QStringLiteral( "COUNT" ), QString::number( 1 ) ); else - getFeatureUrl.addQueryItem( "MAXFEATURES", QString::number( 1 ) ); + getFeatureUrl.addQueryItem( QStringLiteral( "MAXFEATURES" ), QString::number( 1 ) ); if ( !sendGET( getFeatureUrl, true ) ) return -1; diff --git a/src/providers/wfs/qgswfssourceselect.cpp b/src/providers/wfs/qgswfssourceselect.cpp index 0fa4d9417070..dcabe5a0ed27 100644 --- a/src/providers/wfs/qgswfssourceselect.cpp +++ b/src/providers/wfs/qgswfssourceselect.cpp @@ -90,16 +90,16 @@ QgsWFSSourceSelect::QgsWFSSourceSelect( QWidget* parent, Qt::WindowFlags fl, boo QSettings settings; QgsDebugMsg( "restoring settings" ); - restoreGeometry( settings.value( "/Windows/WFSSourceSelect/geometry" ).toByteArray() ); - cbxUseTitleLayerName->setChecked( settings.value( "/Windows/WFSSourceSelect/UseTitleLayerName", false ).toBool() ); - cbxFeatureCurrentViewExtent->setChecked( settings.value( "/Windows/WFSSourceSelect/FeatureCurrentViewExtent", true ).toBool() ); - mHoldDialogOpen->setChecked( settings.value( "/Windows/WFSSourceSelect/HoldDialogOpen", false ).toBool() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/WFSSourceSelect/geometry" ) ).toByteArray() ); + cbxUseTitleLayerName->setChecked( settings.value( QStringLiteral( "/Windows/WFSSourceSelect/UseTitleLayerName" ), false ).toBool() ); + cbxFeatureCurrentViewExtent->setChecked( settings.value( QStringLiteral( "/Windows/WFSSourceSelect/FeatureCurrentViewExtent" ), true ).toBool() ); + mHoldDialogOpen->setChecked( settings.value( QStringLiteral( "/Windows/WFSSourceSelect/HoldDialogOpen" ), false ).toBool() ); mModel = new QStandardItemModel(); - mModel->setHorizontalHeaderItem( MODEL_IDX_TITLE, new QStandardItem( "Title" ) ); - mModel->setHorizontalHeaderItem( MODEL_IDX_NAME, new QStandardItem( "Name" ) ); - mModel->setHorizontalHeaderItem( MODEL_IDX_ABSTRACT, new QStandardItem( "Abstract" ) ); - mModel->setHorizontalHeaderItem( MODEL_IDX_SQL, new QStandardItem( "Sql" ) ); + mModel->setHorizontalHeaderItem( MODEL_IDX_TITLE, new QStandardItem( QStringLiteral( "Title" ) ) ); + mModel->setHorizontalHeaderItem( MODEL_IDX_NAME, new QStandardItem( QStringLiteral( "Name" ) ) ); + mModel->setHorizontalHeaderItem( MODEL_IDX_ABSTRACT, new QStandardItem( QStringLiteral( "Abstract" ) ) ); + mModel->setHorizontalHeaderItem( MODEL_IDX_SQL, new QStandardItem( QStringLiteral( "Sql" ) ) ); mModelProxy = new QSortFilterProxyModel( this ); mModelProxy->setSourceModel( mModel ); @@ -114,10 +114,10 @@ QgsWFSSourceSelect::~QgsWFSSourceSelect() { QSettings settings; QgsDebugMsg( "saving settings" ); - settings.setValue( "/Windows/WFSSourceSelect/geometry", saveGeometry() ); - settings.setValue( "/Windows/WFSSourceSelect/UseTitleLayerName", cbxUseTitleLayerName->isChecked() ); - settings.setValue( "/Windows/WFSSourceSelect/FeatureCurrentViewExtent", cbxFeatureCurrentViewExtent->isChecked() ); - settings.setValue( "/Windows/WFSSourceSelect/HoldDialogOpen", mHoldDialogOpen->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/WFSSourceSelect/geometry" ), saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/WFSSourceSelect/UseTitleLayerName" ), cbxUseTitleLayerName->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/WFSSourceSelect/FeatureCurrentViewExtent" ), cbxFeatureCurrentViewExtent->isChecked() ); + settings.setValue( QStringLiteral( "/Windows/WFSSourceSelect/HoldDialogOpen" ), mHoldDialogOpen->isChecked() ); delete mItemDelegate; delete mProjectionSelector; @@ -175,7 +175,7 @@ QString QgsWFSSourceSelect::getPreferredCrs( const QSet<QString>& crsSet ) const { if ( crsSet.size() < 1 ) { - return ""; + return QLatin1String( "" ); } //first: project CRS @@ -231,7 +231,7 @@ void QgsWFSSourceSelect::capabilitiesReplyFinished() QMessageBox* box = new QMessageBox( QMessageBox::Critical, title, mCapabilities->errorMessage(), QMessageBox::Ok, this ); box->setAttribute( Qt::WA_DeleteOnClose ); box->setModal( true ); - box->setObjectName( "WFSCapabilitiesErrorBox" ); + box->setObjectName( QStringLiteral( "WFSCapabilitiesErrorBox" ) ); if ( !property( "hideDialogs" ).toBool() ) box->open(); @@ -495,9 +495,9 @@ void QgsWFSTableSelectedCallback::tableSelected( const QString& name ) if ( !p.geometryAttribute().isEmpty() ) { QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( p.geometryAttribute() ) ); - fieldList << QgsSQLComposerDialog::PairNameType( fieldName, "geometry" ); + fieldList << QgsSQLComposerDialog::PairNameType( fieldName, QStringLiteral( "geometry" ) ); } - fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", "" ); + fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", QLatin1String( "" ) ); mDialog->addColumnNames( fieldList, name ); } @@ -521,7 +521,7 @@ void QgsWFSSourceSelect::buildQuery( const QModelIndex& index ) QMessageBox* box = new QMessageBox( QMessageBox::Critical, tr( "Server exception" ), tr( "DescribeFeatureType failed" ), QMessageBox::Ok, this ); box->setAttribute( Qt::WA_DeleteOnClose ); box->setModal( true ); - box->setObjectName( "WFSFeatureTypeErrorBox" ); + box->setObjectName( QStringLiteral( "WFSFeatureTypeErrorBox" ) ); if ( !property( "hideDialogs" ).toBool() ) box->open(); @@ -622,9 +622,9 @@ void QgsWFSSourceSelect::buildQuery( const QModelIndex& index ) if ( !p.geometryAttribute().isEmpty() ) { QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( p.geometryAttribute() ) ); - fieldList << QgsSQLComposerDialog::PairNameType( fieldName, "geometry" ); + fieldList << QgsSQLComposerDialog::PairNameType( fieldName, QStringLiteral( "geometry" ) ); } - fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", "" ); + fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", QLatin1String( "" ) ); d->addColumnNames( fieldList, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) ); diff --git a/src/providers/wfs/qgswfstransactionrequest.cpp b/src/providers/wfs/qgswfstransactionrequest.cpp index 571fcfabee95..5ed6a297c44a 100644 --- a/src/providers/wfs/qgswfstransactionrequest.cpp +++ b/src/providers/wfs/qgswfstransactionrequest.cpp @@ -27,7 +27,7 @@ bool QgsWFSTransactionRequest::send( const QDomDocument& doc, QDomDocument& serv QgsDebugMsg( doc.toString() ); - if ( sendPOST( url, "text/xml", doc.toByteArray( -1 ) ) ) + if ( sendPOST( url, QStringLiteral( "text/xml" ), doc.toByteArray( -1 ) ) ) { QString errorMsg; if ( !serverResponse.setContent( mResponse, true, &errorMsg ) ) diff --git a/src/providers/wfs/qgswfsutils.cpp b/src/providers/wfs/qgswfsutils.cpp index 5a9a6d2f4e34..728840823a81 100644 --- a/src/providers/wfs/qgswfsutils.cpp +++ b/src/providers/wfs/qgswfsutils.cpp @@ -37,25 +37,25 @@ int QgsWFSUtils::gmCounter = 0; QString QgsWFSUtils::getBaseCacheDirectory( bool createIfNotExisting ) { QSettings settings; - QString cacheDirectory = settings.value( "cache/directory" ).toString(); + QString cacheDirectory = settings.value( QStringLiteral( "cache/directory" ) ).toString(); if ( cacheDirectory.isEmpty() ) cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache"; if ( createIfNotExisting ) { QMutexLocker locker( &gmMutex ); - if ( !QDir( cacheDirectory ).exists( "wfsprovider" ) ) + if ( !QDir( cacheDirectory ).exists( QStringLiteral( "wfsprovider" ) ) ) { QgsDebugMsg( QString( "Creating main cache dir %1/wfsprovider" ).arg( cacheDirectory ) ); - QDir( cacheDirectory ).mkpath( "wfsprovider" ); + QDir( cacheDirectory ).mkpath( QStringLiteral( "wfsprovider" ) ); } } - return QDir( cacheDirectory ).filePath( "wfsprovider" ); + return QDir( cacheDirectory ).filePath( QStringLiteral( "wfsprovider" ) ); } QString QgsWFSUtils::getCacheDirectory( bool createIfNotExisting ) { QString baseDirectory( getBaseCacheDirectory( createIfNotExisting ) ); - QString processPath( QString( "pid_%1" ).arg( QCoreApplication::applicationPid() ) ); + QString processPath( QStringLiteral( "pid_%1" ).arg( QCoreApplication::applicationPid() ) ); if ( createIfNotExisting ) { QMutexLocker locker( &gmMutex ); @@ -180,7 +180,7 @@ QSharedMemory* QgsWFSUtils::createAndAttachSHM() // For debug purpose. To test in the case where shared memory mechanism doesn't work if ( !getenv( "QGIS_USE_SHARED_MEMORY_KEEP_ALIVE" ) ) { - sharedMemory = new QSharedMemory( QString( "qgis_wfs_pid_%1" ).arg( QCoreApplication::applicationPid() ) ); + sharedMemory = new QSharedMemory( QStringLiteral( "qgis_wfs_pid_%1" ).arg( QCoreApplication::applicationPid() ) ); if ( sharedMemory->create( sizeof( qint64 ) ) && sharedMemory->lock() && sharedMemory->unlock() ) { return sharedMemory; @@ -225,7 +225,7 @@ void QgsWFSUtils::init() QFileInfoList fileList( dir.entryInfoList( QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files ) ); Q_FOREACH ( const QFileInfo& info, fileList ) { - if ( info.isDir() && info.fileName().startsWith( "pid_" ) ) + if ( info.isDir() && info.fileName().startsWith( QLatin1String( "pid_" ) ) ) { QString pidStr( info.fileName().mid( 4 ) ); qint64 pid = pidStr.toLongLong(); @@ -237,7 +237,7 @@ void QgsWFSUtils::init() else if ( gmKeepAliveWorks ) { canDelete = true; - QSharedMemory otherSharedMemory( QString( "qgis_wfs_pid_%1" ).arg( pid ) ); + QSharedMemory otherSharedMemory( QStringLiteral( "qgis_wfs_pid_%1" ).arg( pid ) ); if ( otherSharedMemory.attach() ) { if ( otherSharedMemory.size() == sizeof( qint64 ) ) diff --git a/src/providers/wms/qgstilescalewidget.cpp b/src/providers/wms/qgstilescalewidget.cpp index dd7b170482d1..cf5255068ef3 100644 --- a/src/providers/wms/qgstilescalewidget.cpp +++ b/src/providers/wms/qgstilescalewidget.cpp @@ -47,7 +47,7 @@ void QgsTileScaleWidget::layerChanged( QgsMapLayer *layer ) mSlider->setDisabled( true ); QgsRasterLayer *rl = qobject_cast<QgsRasterLayer *>( layer ); - if ( !rl || rl->providerType() != "wms" || !rl->dataProvider() ) + if ( !rl || rl->providerType() != QLatin1String( "wms" ) || !rl->dataProvider() ) return; QVariant res = rl->dataProvider()->property( "resolutions" ); @@ -110,14 +110,14 @@ void QgsTileScaleWidget::on_mSlider_valueChanged( int value ) void QgsTileScaleWidget::showTileScale( QMainWindow *mainWindow ) { - QgsDockWidget *dock = mainWindow->findChild<QgsDockWidget *>( "theTileScaleDock" ); + QgsDockWidget *dock = mainWindow->findChild<QgsDockWidget *>( QStringLiteral( "theTileScaleDock" ) ); if ( dock ) { dock->setVisible( dock->isHidden() ); return; } - QgsMapCanvas *canvas = mainWindow->findChild<QgsMapCanvas *>( "theMapCanvas" ); + QgsMapCanvas *canvas = mainWindow->findChild<QgsMapCanvas *>( QStringLiteral( "theMapCanvas" ) ); QgsDebugMsg( QString( "canvas:%1 [%2]" ).arg(( ulong ) canvas, 0, 16 ).arg( canvas ? canvas->objectName() : "" ) ); if ( !canvas ) { @@ -126,9 +126,9 @@ void QgsTileScaleWidget::showTileScale( QMainWindow *mainWindow ) } QgsTileScaleWidget *tws = new QgsTileScaleWidget( canvas ); - tws->setObjectName( "theTileScaleWidget" ); + tws->setObjectName( QStringLiteral( "theTileScaleWidget" ) ); - QObject *legend = mainWindow->findChild<QObject*>( "theLayerTreeView" ); + QObject *legend = mainWindow->findChild<QObject*>( QStringLiteral( "theLayerTreeView" ) ); if ( legend ) { connect( legend, SIGNAL( currentLayerChanged( QgsMapLayer* ) ), @@ -141,12 +141,12 @@ void QgsTileScaleWidget::showTileScale( QMainWindow *mainWindow ) //create the dock widget dock = new QgsDockWidget( tr( "Tile Scale Panel" ), mainWindow ); - dock->setObjectName( "theTileScaleDock" ); + dock->setObjectName( QStringLiteral( "theTileScaleDock" ) ); dock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea ); mainWindow->addDockWidget( Qt::RightDockWidgetArea, dock ); // add to the Panel submenu - QMenu *panelMenu = mainWindow->findChild<QMenu *>( "mPanelMenu" ); + QMenu *panelMenu = mainWindow->findChild<QMenu *>( QStringLiteral( "mPanelMenu" ) ); if ( panelMenu ) { // add to the Panel submenu @@ -162,11 +162,11 @@ void QgsTileScaleWidget::showTileScale( QMainWindow *mainWindow ) connect( dock, SIGNAL( visibilityChanged( bool ) ), tws, SLOT( scaleEnabled( bool ) ) ); QSettings settings; - dock->setVisible( settings.value( "/UI/tileScaleEnabled", false ).toBool() ); + dock->setVisible( settings.value( QStringLiteral( "/UI/tileScaleEnabled" ), false ).toBool() ); } void QgsTileScaleWidget::scaleEnabled( bool enabled ) { QSettings settings; - settings.setValue( "/UI/tileScaleEnabled", enabled ); + settings.setValue( QStringLiteral( "/UI/tileScaleEnabled" ), enabled ); } diff --git a/src/providers/wms/qgswmscapabilities.cpp b/src/providers/wms/qgswmscapabilities.cpp index 65ff4da52a1f..6fc14a4b2e64 100644 --- a/src/providers/wms/qgswmscapabilities.cpp +++ b/src/providers/wms/qgswmscapabilities.cpp @@ -30,7 +30,7 @@ #include "qgscsexception.h" // %%% copied from qgswmsprovider.cpp -static QString DEFAULT_LATLON_CRS = "CRS:84"; +static QString DEFAULT_LATLON_CRS = QStringLiteral( "CRS:84" ); @@ -42,16 +42,16 @@ bool QgsWmsSettings::parseUri( const QString& uriString ) mXyz = false; // assume WMS / WMTS - if ( uri.param( "type" ) == "xyz" ) + if ( uri.param( QStringLiteral( "type" ) ) == QLatin1String( "xyz" ) ) { // for XYZ tiles most of the things do not apply mTiled = true; mXyz = true; mTileDimensionValues.clear(); - mTileMatrixSetId = "tms0"; + mTileMatrixSetId = QStringLiteral( "tms0" ); mMaxWidth = 0; mMaxHeight = 0; - mHttpUri = uri.param( "url" ); + mHttpUri = uri.param( QStringLiteral( "url" ) ); mBaseUrl = mHttpUri; mAuth.mUserName.clear(); mAuth.mPassword.clear(); @@ -61,12 +61,12 @@ bool QgsWmsSettings::parseUri( const QString& uriString ) mIgnoreGetFeatureInfoUrl = false; mSmoothPixmapTransform = true; mDpiMode = dpiNone; // does not matter what we set here - mActiveSubLayers = QStringList( "xyz" ); // just a placeholder to have one sub-layer - mActiveSubStyles = QStringList( "xyz" ); // just a placeholder to have one sub-style + mActiveSubLayers = QStringList( QStringLiteral( "xyz" ) ); // just a placeholder to have one sub-layer + mActiveSubStyles = QStringList( QStringLiteral( "xyz" ) ); // just a placeholder to have one sub-style mActiveSubLayerVisibility.clear(); mFeatureCount = 0; mImageMimeType.clear(); - mCrsId = "EPSG:3857"; + mCrsId = QStringLiteral( "EPSG:3857" ); mEnableContextualLegend = false; return true; } @@ -74,57 +74,57 @@ bool QgsWmsSettings::parseUri( const QString& uriString ) mTiled = false; mTileDimensionValues.clear(); - mHttpUri = uri.param( "url" ); + mHttpUri = uri.param( QStringLiteral( "url" ) ); mBaseUrl = QgsWmsProvider::prepareUri( mHttpUri ); // must set here, setImageCrs is using that QgsDebugMsg( "mBaseUrl = " + mBaseUrl ); - mIgnoreGetMapUrl = uri.hasParam( "IgnoreGetMapUrl" ); - mIgnoreGetFeatureInfoUrl = uri.hasParam( "IgnoreGetFeatureInfoUrl" ); - mParserSettings.ignoreAxisOrientation = uri.hasParam( "IgnoreAxisOrientation" ); // must be before parsing! - mParserSettings.invertAxisOrientation = uri.hasParam( "InvertAxisOrientation" ); // must be before parsing! - mSmoothPixmapTransform = uri.hasParam( "SmoothPixmapTransform" ); + mIgnoreGetMapUrl = uri.hasParam( QStringLiteral( "IgnoreGetMapUrl" ) ); + mIgnoreGetFeatureInfoUrl = uri.hasParam( QStringLiteral( "IgnoreGetFeatureInfoUrl" ) ); + mParserSettings.ignoreAxisOrientation = uri.hasParam( QStringLiteral( "IgnoreAxisOrientation" ) ); // must be before parsing! + mParserSettings.invertAxisOrientation = uri.hasParam( QStringLiteral( "InvertAxisOrientation" ) ); // must be before parsing! + mSmoothPixmapTransform = uri.hasParam( QStringLiteral( "SmoothPixmapTransform" ) ); - mDpiMode = uri.hasParam( "dpiMode" ) ? static_cast< QgsWmsDpiMode >( uri.param( "dpiMode" ).toInt() ) : dpiAll; + mDpiMode = uri.hasParam( QStringLiteral( "dpiMode" ) ) ? static_cast< QgsWmsDpiMode >( uri.param( QStringLiteral( "dpiMode" ) ).toInt() ) : dpiAll; - mAuth.mUserName = uri.param( "username" ); + mAuth.mUserName = uri.param( QStringLiteral( "username" ) ); QgsDebugMsg( "set username to " + mAuth.mUserName ); - mAuth.mPassword = uri.param( "password" ); + mAuth.mPassword = uri.param( QStringLiteral( "password" ) ); QgsDebugMsg( "set password to " + mAuth.mPassword ); - if ( uri.hasParam( "authcfg" ) ) + if ( uri.hasParam( QStringLiteral( "authcfg" ) ) ) { - mAuth.mAuthCfg = uri.param( "authcfg" ); + mAuth.mAuthCfg = uri.param( QStringLiteral( "authcfg" ) ); } QgsDebugMsg( "set authcfg to " + mAuth.mAuthCfg ); - mAuth.mReferer = uri.param( "referer" ); + mAuth.mReferer = uri.param( QStringLiteral( "referer" ) ); QgsDebugMsg( "set referer to " + mAuth.mReferer ); - mActiveSubLayers = uri.params( "layers" ); - mActiveSubStyles = uri.params( "styles" ); + mActiveSubLayers = uri.params( QStringLiteral( "layers" ) ); + mActiveSubStyles = uri.params( QStringLiteral( "styles" ) ); QgsDebugMsg( "Entering: layers:" + mActiveSubLayers.join( ", " ) + ", styles:" + mActiveSubStyles.join( ", " ) ); - mImageMimeType = uri.param( "format" ); + mImageMimeType = uri.param( QStringLiteral( "format" ) ); QgsDebugMsg( "Setting image encoding to " + mImageMimeType + '.' ); mMaxWidth = 0; mMaxHeight = 0; - if ( uri.hasParam( "maxWidth" ) && uri.hasParam( "maxHeight" ) ) + if ( uri.hasParam( QStringLiteral( "maxWidth" ) ) && uri.hasParam( QStringLiteral( "maxHeight" ) ) ) { - mMaxWidth = uri.param( "maxWidth" ).toInt(); - mMaxHeight = uri.param( "maxHeight" ).toInt(); + mMaxWidth = uri.param( QStringLiteral( "maxWidth" ) ).toInt(); + mMaxHeight = uri.param( QStringLiteral( "maxHeight" ) ).toInt(); } - if ( uri.hasParam( "tileMatrixSet" ) ) + if ( uri.hasParam( QStringLiteral( "tileMatrixSet" ) ) ) { mTiled = true; // tileMatrixSet may be empty if URI was converted from < 1.9 project file URI // in that case it means that the source is WMS-C - mTileMatrixSetId = uri.param( "tileMatrixSet" ); + mTileMatrixSetId = uri.param( QStringLiteral( "tileMatrixSet" ) ); } - if ( uri.hasParam( "tileDimensions" ) ) + if ( uri.hasParam( QStringLiteral( "tileDimensions" ) ) ) { mTiled = true; Q_FOREACH ( const QString& param, uri.param( "tileDimensions" ).split( ';' ) ) @@ -145,12 +145,12 @@ bool QgsWmsSettings::parseUri( const QString& uriString ) } } - mCrsId = uri.param( "crs" ); + mCrsId = uri.param( QStringLiteral( "crs" ) ); - mEnableContextualLegend = uri.param( "contextualWMSLegend" ).toInt(); + mEnableContextualLegend = uri.param( QStringLiteral( "contextualWMSLegend" ) ).toInt(); QgsDebugMsg( QString( "Contextual legend: %1" ).arg( mEnableContextualLegend ) ); - mFeatureCount = uri.param( "featureCount" ).toInt(); // default to 0 + mFeatureCount = uri.param( QStringLiteral( "featureCount" ) ).toInt(); // default to 0 return true; } @@ -175,7 +175,7 @@ bool QgsWmsCapabilities::parseResponse( const QByteArray& response, QgsWmsParser { if ( mError.isEmpty() ) { - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = QObject::tr( "empty capabilities document" ); } QgsDebugMsg( "response is empty" ); @@ -185,7 +185,7 @@ bool QgsWmsCapabilities::parseResponse( const QByteArray& response, QgsWmsParser if ( response.startsWith( "<html>" ) || response.startsWith( "<HTML>" ) ) { - mErrorFormat = "text/html"; + mErrorFormat = QStringLiteral( "text/html" ); mError = response; QgsDebugMsg( "starts with <html>" ); return false; @@ -219,19 +219,19 @@ bool QgsWmsCapabilities::parseResponse( const QByteArray& response, QgsWmsParser // 1.1.0, 1.3.0 - mime types, GML should use application/vnd.ogc.gml // but in UMN Mapserver it may be also OUTPUTFORMAT, e.g. OGRGML QgsRaster::IdentifyFormat format = QgsRaster::IdentifyFormatUndefined; - if ( f == "MIME" ) + if ( f == QLatin1String( "MIME" ) ) format = QgsRaster::IdentifyFormatText; // 1.0 - else if ( f == "text/plain" ) + else if ( f == QLatin1String( "text/plain" ) ) format = QgsRaster::IdentifyFormatText; - else if ( f == "text/html" ) + else if ( f == QLatin1String( "text/html" ) ) format = QgsRaster::IdentifyFormatHtml; - else if ( f.startsWith( "GML." ) ) + else if ( f.startsWith( QLatin1String( "GML." ) ) ) format = QgsRaster::IdentifyFormatFeature; // 1.0 - else if ( f == "application/vnd.ogc.gml" ) + else if ( f == QLatin1String( "application/vnd.ogc.gml" ) ) format = QgsRaster::IdentifyFormatFeature; - else if ( f == "application/json" ) + else if ( f == QLatin1String( "application/json" ) ) format = QgsRaster::IdentifyFormatFeature; - else if ( f.contains( "gml", Qt::CaseInsensitive ) ) + else if ( f.contains( QLatin1String( "gml" ), Qt::CaseInsensitive ) ) format = QgsRaster::IdentifyFormatFeature; mIdentifyFormats.insert( format, f ); @@ -266,7 +266,7 @@ bool QgsWmsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWmsCapa if ( !contentSuccess ) { mErrorCaption = QObject::tr( "Dom Exception" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = QObject::tr( "Could not get WMS capabilities: %1 at line %2 column %3\nThis is probably due to an incorrect WMS Server URL.\nResponse was:\n\n%4" ) .arg( errorMsg ) .arg( errorLine ) @@ -284,16 +284,16 @@ bool QgsWmsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWmsCapa QgsDebugMsg( "testing tagName " + docElem.tagName() ); if ( - docElem.tagName() != "WMS_Capabilities" && // (1.3 vintage) - docElem.tagName() != "WMT_MS_Capabilities" && // (1.1.1 vintage) - docElem.tagName() != "Capabilities" // WMTS + docElem.tagName() != QLatin1String( "WMS_Capabilities" ) && // (1.3 vintage) + docElem.tagName() != QLatin1String( "WMT_MS_Capabilities" ) && // (1.1.1 vintage) + docElem.tagName() != QLatin1String( "Capabilities" ) // WMTS ) { mErrorCaption = QObject::tr( "Dom Exception" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = QObject::tr( "Could not get WMS capabilities in the expected format (DTD): no %1 or %2 found.\nThis might be due to an incorrect WMS Server URL.\nTag:%3\nResponse was:\n%4" ) - .arg( "WMS_Capabilities", - "WMT_MS_Capabilities", + .arg( QStringLiteral( "WMS_Capabilities" ), + QStringLiteral( "WMT_MS_Capabilities" ), docElem.tagName(), QString( xml ) ); @@ -302,7 +302,7 @@ bool QgsWmsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWmsCapa return false; } - capabilitiesProperty.version = docElem.attribute( "version" ); + capabilitiesProperty.version = docElem.attribute( QStringLiteral( "version" ) ); // Start walking through XML. QDomNode n = docElem.firstChild(); @@ -314,17 +314,17 @@ bool QgsWmsCapabilities::parseCapabilitiesDom( QByteArray const &xml, QgsWmsCapa { QgsDebugMsg( e.tagName() ); // the node really is an element. - if ( e.tagName() == "Service" || e.tagName() == "ows:ServiceProvider" || e.tagName() == "ows:ServiceIdentification" ) + if ( e.tagName() == QLatin1String( "Service" ) || e.tagName() == QLatin1String( "ows:ServiceProvider" ) || e.tagName() == QLatin1String( "ows:ServiceIdentification" ) ) { QgsDebugMsg( " Service." ); parseService( e, capabilitiesProperty.service ); } - else if ( e.tagName() == "Capability" || e.tagName() == "ows:OperationsMetadata" ) + else if ( e.tagName() == QLatin1String( "Capability" ) || e.tagName() == QLatin1String( "ows:OperationsMetadata" ) ) { QgsDebugMsg( " Capability." ); parseCapability( e, capabilitiesProperty.capability ); } - else if ( e.tagName() == "Contents" ) + else if ( e.tagName() == QLatin1String( "Contents" ) ) { QgsDebugMsg( " Contents." ); parseWMTSContents( e ); @@ -350,48 +350,48 @@ void QgsWmsCapabilities::parseService( QDomElement const & e, QgsWmsServicePrope { // QgsDebugMsg( " " + e1.tagName() ); // the node really is an element. QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName.startsWith( "ows:" ) ) + if ( tagName.startsWith( QLatin1String( "ows:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Title" ) + if ( tagName == QLatin1String( "Title" ) ) { serviceProperty.title = e1.text(); } - else if ( tagName == "Abstract" ) + else if ( tagName == QLatin1String( "Abstract" ) ) { serviceProperty.abstract = e1.text(); } - else if ( tagName == "KeywordList" || tagName == "Keywords" ) + else if ( tagName == QLatin1String( "KeywordList" ) || tagName == QLatin1String( "Keywords" ) ) { parseKeywordList( e1, serviceProperty.keywordList ); } - else if ( tagName == "OnlineResource" ) + else if ( tagName == QLatin1String( "OnlineResource" ) ) { parseOnlineResource( e1, serviceProperty.onlineResource ); } - else if ( tagName == "ContactInformation" || tagName == "ServiceContact" ) + else if ( tagName == QLatin1String( "ContactInformation" ) || tagName == QLatin1String( "ServiceContact" ) ) { parseContactInformation( e1, serviceProperty.contactInformation ); } - else if ( tagName == "Fees" ) + else if ( tagName == QLatin1String( "Fees" ) ) { serviceProperty.fees = e1.text(); } - else if ( tagName == "AccessConstraints" ) + else if ( tagName == QLatin1String( "AccessConstraints" ) ) { serviceProperty.accessConstraints = e1.text(); } - else if ( tagName == "LayerLimit" ) + else if ( tagName == QLatin1String( "LayerLimit" ) ) { serviceProperty.layerLimit = e1.text().toUInt(); } - else if ( tagName == "MaxWidth" ) + else if ( tagName == QLatin1String( "MaxWidth" ) ) { serviceProperty.maxWidth = e1.text().toUInt(); } - else if ( tagName == "MaxHeight" ) + else if ( tagName == QLatin1String( "MaxHeight" ) ) { serviceProperty.maxHeight = e1.text().toUInt(); } @@ -406,7 +406,7 @@ void QgsWmsCapabilities::parseService( QDomElement const & e, QgsWmsServicePrope void QgsWmsCapabilities::parseOnlineResource( QDomElement const & e, QgsWmsOnlineResourceAttribute& onlineResourceAttribute ) { - onlineResourceAttribute.xlinkHref = QUrl::fromEncoded( e.attribute( "xlink:href" ).toUtf8() ).toString(); + onlineResourceAttribute.xlinkHref = QUrl::fromEncoded( e.attribute( QStringLiteral( "xlink:href" ) ).toUtf8() ).toString(); QgsDebugMsg( "exiting." ); } @@ -422,12 +422,12 @@ void QgsWmsCapabilities::parseKeywordList( QDomElement const & e, QStringList& if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName.startsWith( "ows:" ) ) + if ( tagName.startsWith( QLatin1String( "ows:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Keyword" ) + if ( tagName == QLatin1String( "Keyword" ) ) { QgsDebugMsg( " Keyword." ); keywordListProperty += e1.text(); @@ -449,54 +449,54 @@ void QgsWmsCapabilities::parseContactInformation( QDomElement const & e, QgsWmsC if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "ContactPersonPrimary" ) + if ( tagName == QLatin1String( "ContactPersonPrimary" ) ) { parseContactPersonPrimary( e1, contactInformationProperty.contactPersonPrimary ); } - else if ( tagName == "ContactPosition" || tagName == "ows:PositionName" ) + else if ( tagName == QLatin1String( "ContactPosition" ) || tagName == QLatin1String( "ows:PositionName" ) ) { contactInformationProperty.contactPosition = e1.text(); } - else if ( tagName == "ContactAddress" ) + else if ( tagName == QLatin1String( "ContactAddress" ) ) { parseContactAddress( e1, contactInformationProperty.contactAddress ); } - else if ( tagName == "ContactVoiceTelephone" ) + else if ( tagName == QLatin1String( "ContactVoiceTelephone" ) ) { contactInformationProperty.contactVoiceTelephone = e1.text(); } - else if ( tagName == "ContactFacsimileTelephone" ) + else if ( tagName == QLatin1String( "ContactFacsimileTelephone" ) ) { contactInformationProperty.contactFacsimileTelephone = e1.text(); } - else if ( tagName == "ContactElectronicMailAddress" ) + else if ( tagName == QLatin1String( "ContactElectronicMailAddress" ) ) { contactInformationProperty.contactElectronicMailAddress = e1.text(); } - else if ( tagName == "ows:IndividualName" ) + else if ( tagName == QLatin1String( "ows:IndividualName" ) ) { contactInformationProperty.contactPersonPrimary.contactPerson = e1.text(); } - else if ( tagName == "ows:ProviderName" ) + else if ( tagName == QLatin1String( "ows:ProviderName" ) ) { contactInformationProperty.contactPersonPrimary.contactOrganization = e1.text(); } - else if ( tagName == "ows:ContactInfo" ) + else if ( tagName == QLatin1String( "ows:ContactInfo" ) ) { - QDomNode n = n1.firstChildElement( "ows:Phone" ); - contactInformationProperty.contactVoiceTelephone = n.firstChildElement( "ows:Voice" ).toElement().text(); - contactInformationProperty.contactFacsimileTelephone = n.firstChildElement( "ows:Facsimile" ).toElement().text(); + QDomNode n = n1.firstChildElement( QStringLiteral( "ows:Phone" ) ); + contactInformationProperty.contactVoiceTelephone = n.firstChildElement( QStringLiteral( "ows:Voice" ) ).toElement().text(); + contactInformationProperty.contactFacsimileTelephone = n.firstChildElement( QStringLiteral( "ows:Facsimile" ) ).toElement().text(); - n = n1.firstChildElement( "ows:Address" ); - contactInformationProperty.contactElectronicMailAddress = n.firstChildElement( "ows:ElectronicMailAddress" ).toElement().text(); - contactInformationProperty.contactAddress.address = n.firstChildElement( "ows:DeliveryPoint" ).toElement().text(); - contactInformationProperty.contactAddress.city = n.firstChildElement( "ows:City" ).toElement().text(); - contactInformationProperty.contactAddress.stateOrProvince = n.firstChildElement( "ows:AdministrativeArea" ).toElement().text(); - contactInformationProperty.contactAddress.postCode = n.firstChildElement( "ows:PostalCode" ).toElement().text(); - contactInformationProperty.contactAddress.country = n.firstChildElement( "ows:Country" ).toElement().text(); + n = n1.firstChildElement( QStringLiteral( "ows:Address" ) ); + contactInformationProperty.contactElectronicMailAddress = n.firstChildElement( QStringLiteral( "ows:ElectronicMailAddress" ) ).toElement().text(); + contactInformationProperty.contactAddress.address = n.firstChildElement( QStringLiteral( "ows:DeliveryPoint" ) ).toElement().text(); + contactInformationProperty.contactAddress.city = n.firstChildElement( QStringLiteral( "ows:City" ) ).toElement().text(); + contactInformationProperty.contactAddress.stateOrProvince = n.firstChildElement( QStringLiteral( "ows:AdministrativeArea" ) ).toElement().text(); + contactInformationProperty.contactAddress.postCode = n.firstChildElement( QStringLiteral( "ows:PostalCode" ) ).toElement().text(); + contactInformationProperty.contactAddress.country = n.firstChildElement( QStringLiteral( "ows:Country" ) ).toElement().text(); } } n1 = n1.nextSibling(); @@ -515,14 +515,14 @@ void QgsWmsCapabilities::parseContactPersonPrimary( QDomElement const & e, QgsWm if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "ContactPerson" ) + if ( tagName == QLatin1String( "ContactPerson" ) ) { contactPersonPrimaryProperty.contactPerson = e1.text(); } - else if ( tagName == "ContactOrganization" ) + else if ( tagName == QLatin1String( "ContactOrganization" ) ) { contactPersonPrimaryProperty.contactOrganization = e1.text(); } @@ -544,30 +544,30 @@ void QgsWmsCapabilities::parseContactAddress( QDomElement const & e, QgsWmsConta if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "AddressType" ) + if ( tagName == QLatin1String( "AddressType" ) ) { contactAddressProperty.addressType = e1.text(); } - else if ( tagName == "Address" ) + else if ( tagName == QLatin1String( "Address" ) ) { contactAddressProperty.address = e1.text(); } - else if ( tagName == "City" ) + else if ( tagName == QLatin1String( "City" ) ) { contactAddressProperty.city = e1.text(); } - else if ( tagName == "StateOrProvince" ) + else if ( tagName == QLatin1String( "StateOrProvince" ) ) { contactAddressProperty.stateOrProvince = e1.text(); } - else if ( tagName == "PostCode" ) + else if ( tagName == QLatin1String( "PostCode" ) ) { contactAddressProperty.postCode = e1.text(); } - else if ( tagName == "Country" ) + else if ( tagName == QLatin1String( "Country" ) ) { contactAddressProperty.country = e1.text(); } @@ -589,22 +589,22 @@ void QgsWmsCapabilities::parseCapability( QDomElement const & e, QgsWmsCapabilit continue; QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); QgsDebugMsg( " " + e1.tagName() ); // the node really is an element. - if ( tagName == "Request" ) + if ( tagName == QLatin1String( "Request" ) ) { parseRequest( e1, capabilityProperty.request ); } - else if ( tagName == "Layer" ) + else if ( tagName == QLatin1String( "Layer" ) ) { QgsWmsLayerProperty layer; parseLayer( e1, layer ); capabilityProperty.layers.push_back( layer ); } - else if ( tagName == "VendorSpecificCapabilities" ) + else if ( tagName == QLatin1String( "VendorSpecificCapabilities" ) ) { for ( int i = 0; i < e1.childNodes().size(); i++ ) { @@ -612,23 +612,23 @@ void QgsWmsCapabilities::parseCapability( QDomElement const & e, QgsWmsCapabilit QDomElement e2 = n2.toElement(); QString tagName = e2.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "TileSet" ) + if ( tagName == QLatin1String( "TileSet" ) ) { parseTileSetProfile( e2 ); } } } - else if ( tagName == "ows:Operation" ) + else if ( tagName == QLatin1String( "ows:Operation" ) ) { - QString name = e1.attribute( "name" ); - QDomElement get = n1.firstChildElement( "ows:DCP" ) - .firstChildElement( "ows:HTTP" ) - .firstChildElement( "ows:Get" ); + QString name = e1.attribute( QStringLiteral( "name" ) ); + QDomElement get = n1.firstChildElement( QStringLiteral( "ows:DCP" ) ) + .firstChildElement( QStringLiteral( "ows:HTTP" ) ) + .firstChildElement( QStringLiteral( "ows:Get" ) ); - QString href = get.attribute( "xlink:href" ); + QString href = get.attribute( QStringLiteral( "xlink:href" ) ); QgsWmsDcpTypeProperty dcp; dcp.http.get.onlineResource.xlinkHref = href; @@ -638,15 +638,15 @@ void QgsWmsCapabilities::parseCapability( QDomElement const & e, QgsWmsCapabilit { QgsDebugMsg( QString( "http get missing from ows:Operation '%1'" ).arg( name ) ); } - else if ( name == "GetTile" ) + else if ( name == QLatin1String( "GetTile" ) ) { ot = &capabilityProperty.request.getTile; } - else if ( name == "GetFeatureInfo" ) + else if ( name == QLatin1String( "GetFeatureInfo" ) ) { ot = &capabilityProperty.request.getFeatureInfo; } - else if ( name == "GetLegendGraphic" || name == "sld:GetLegendGraphic" ) + else if ( name == QLatin1String( "GetLegendGraphic" ) || name == QLatin1String( "sld:GetLegendGraphic" ) ) { ot = &capabilityProperty.request.getLegendGraphic; } @@ -659,9 +659,9 @@ void QgsWmsCapabilities::parseCapability( QDomElement const & e, QgsWmsCapabilit { ot->dcpType << dcp; ot->allowedEncodings.clear(); - for ( QDomElement e2 = get.firstChildElement( "ows:Constraint" ).firstChildElement( "ows:AllowedValues" ).firstChildElement( "ows:Value" ); + for ( QDomElement e2 = get.firstChildElement( QStringLiteral( "ows:Constraint" ) ).firstChildElement( QStringLiteral( "ows:AllowedValues" ) ).firstChildElement( QStringLiteral( "ows:Value" ) ); !e2.isNull(); - e2 = e1.nextSiblingElement( "ows:Value" ) ) + e2 = e1.nextSiblingElement( QStringLiteral( "ows:Value" ) ) ) { ot->allowedEncodings << e2.text(); } @@ -683,22 +683,22 @@ void QgsWmsCapabilities::parseRequest( QDomElement const & e, QgsWmsRequestPrope if ( !e1.isNull() ) { QString operation = e1.tagName(); - if ( operation == "Operation" ) + if ( operation == QLatin1String( "Operation" ) ) { - operation = e1.attribute( "name" ); + operation = e1.attribute( QStringLiteral( "name" ) ); } - if ( operation == "GetMap" ) + if ( operation == QLatin1String( "GetMap" ) ) { QgsDebugMsg( " GetMap." ); parseOperationType( e1, requestProperty.getMap ); } - else if ( operation == "GetFeatureInfo" ) + else if ( operation == QLatin1String( "GetFeatureInfo" ) ) { QgsDebugMsg( " GetFeatureInfo." ); parseOperationType( e1, requestProperty.getFeatureInfo ); } - else if ( operation == "GetLegendGraphic" || operation == "sld:GetLegendGraphic" ) + else if ( operation == QLatin1String( "GetLegendGraphic" ) || operation == QLatin1String( "sld:GetLegendGraphic" ) ) { QgsDebugMsg( " GetLegendGraphic." ); parseOperationType( e1, requestProperty.getLegendGraphic ); @@ -715,8 +715,8 @@ void QgsWmsCapabilities::parseRequest( QDomElement const & e, QgsWmsRequestPrope void QgsWmsCapabilities::parseLegendUrl( QDomElement const & e, QgsWmsLegendUrlProperty& legendUrlProperty ) { - legendUrlProperty.width = e.attribute( "width" ).toUInt(); - legendUrlProperty.height = e.attribute( "height" ).toUInt(); + legendUrlProperty.width = e.attribute( QStringLiteral( "width" ) ).toUInt(); + legendUrlProperty.height = e.attribute( QStringLiteral( "height" ) ).toUInt(); QDomNode n1 = e.firstChild(); while ( !n1.isNull() ) @@ -725,14 +725,14 @@ void QgsWmsCapabilities::parseLegendUrl( QDomElement const & e, QgsWmsLegendUrlP if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Format" ) + if ( tagName == QLatin1String( "Format" ) ) { legendUrlProperty.format = e1.text(); } - else if ( tagName == "OnlineResource" ) + else if ( tagName == QLatin1String( "OnlineResource" ) ) { parseOnlineResource( e1, legendUrlProperty.onlineResource ); } @@ -757,12 +757,12 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& #endif layerProperty.orderId = ++mLayerCount; - layerProperty.queryable = e.attribute( "queryable" ).toUInt(); - layerProperty.cascaded = e.attribute( "cascaded" ).toUInt(); - layerProperty.opaque = e.attribute( "opaque" ).toUInt(); - layerProperty.noSubsets = e.attribute( "noSubsets" ).toUInt(); - layerProperty.fixedWidth = e.attribute( "fixedWidth" ).toUInt(); - layerProperty.fixedHeight = e.attribute( "fixedHeight" ).toUInt(); + layerProperty.queryable = e.attribute( QStringLiteral( "queryable" ) ).toUInt(); + layerProperty.cascaded = e.attribute( QStringLiteral( "cascaded" ) ).toUInt(); + layerProperty.opaque = e.attribute( QStringLiteral( "opaque" ) ).toUInt(); + layerProperty.noSubsets = e.attribute( QStringLiteral( "noSubsets" ) ).toUInt(); + layerProperty.fixedWidth = e.attribute( QStringLiteral( "fixedWidth" ) ).toUInt(); + layerProperty.fixedHeight = e.attribute( QStringLiteral( "fixedHeight" ) ).toUInt(); QDomNode n1 = e.firstChild(); while ( !n1.isNull() ) @@ -773,10 +773,10 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& //QgsDebugMsg( " " + e1.tagName() ); // the node really is an element. QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Layer" ) + if ( tagName == QLatin1String( "Layer" ) ) { //QgsDebugMsg( " Nested layer." ); @@ -794,23 +794,23 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& layerProperty.layer.push_back( subLayerProperty ); } - else if ( tagName == "Name" ) + else if ( tagName == QLatin1String( "Name" ) ) { layerProperty.name = e1.text(); } - else if ( tagName == "Title" ) + else if ( tagName == QLatin1String( "Title" ) ) { layerProperty.title = e1.text(); } - else if ( tagName == "Abstract" ) + else if ( tagName == QLatin1String( "Abstract" ) ) { layerProperty.abstract = e1.text(); } - else if ( tagName == "KeywordList" ) + else if ( tagName == QLatin1String( "KeywordList" ) ) { parseKeywordList( e1, layerProperty.keywordList ); } - else if ( tagName == "SRS" || tagName == "CRS" ) + else if ( tagName == QLatin1String( "SRS" ) || tagName == QLatin1String( "CRS" ) ) { // CRS can contain several definitions separated by whitespace // though this was deprecated in WMS 1.1.1 @@ -819,20 +819,20 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& layerProperty.crs.push_back( srs ); } } - else if ( tagName == "LatLonBoundingBox" ) // legacy from earlier versions of WMS + else if ( tagName == QLatin1String( "LatLonBoundingBox" ) ) // legacy from earlier versions of WMS { layerProperty.ex_GeographicBoundingBox = QgsRectangle( - e1.attribute( "minx" ).toDouble(), - e1.attribute( "miny" ).toDouble(), - e1.attribute( "maxx" ).toDouble(), - e1.attribute( "maxy" ).toDouble() + e1.attribute( QStringLiteral( "minx" ) ).toDouble(), + e1.attribute( QStringLiteral( "miny" ) ).toDouble(), + e1.attribute( QStringLiteral( "maxx" ) ).toDouble(), + e1.attribute( QStringLiteral( "maxy" ) ).toDouble() ); - if ( e1.hasAttribute( "SRS" ) && e1.attribute( "SRS" ) != DEFAULT_LATLON_CRS ) + if ( e1.hasAttribute( QStringLiteral( "SRS" ) ) && e1.attribute( QStringLiteral( "SRS" ) ) != DEFAULT_LATLON_CRS ) { try { - QgsCoordinateReferenceSystem src = QgsCoordinateReferenceSystem::fromOgcWmsCrs( e1.attribute( "SRS" ) ); + QgsCoordinateReferenceSystem src = QgsCoordinateReferenceSystem::fromOgcWmsCrs( e1.attribute( QStringLiteral( "SRS" ) ) ); QgsCoordinateReferenceSystem dst = QgsCoordinateReferenceSystem::fromOgcWmsCrs( DEFAULT_LATLON_CRS ); @@ -845,23 +845,23 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& } } } - else if ( tagName == "EX_GeographicBoundingBox" ) //for WMS 1.3 + else if ( tagName == QLatin1String( "EX_GeographicBoundingBox" ) ) //for WMS 1.3 { QDomElement wBoundLongitudeElem, eBoundLongitudeElem, sBoundLatitudeElem, nBoundLatitudeElem; - if ( e1.tagName() == "wms:EX_GeographicBoundingBox" ) + if ( e1.tagName() == QLatin1String( "wms:EX_GeographicBoundingBox" ) ) { - wBoundLongitudeElem = n1.namedItem( "wms:westBoundLongitude" ).toElement(); - eBoundLongitudeElem = n1.namedItem( "wms:eastBoundLongitude" ).toElement(); - sBoundLatitudeElem = n1.namedItem( "wms:southBoundLatitude" ).toElement(); - nBoundLatitudeElem = n1.namedItem( "wms:northBoundLatitude" ).toElement(); + wBoundLongitudeElem = n1.namedItem( QStringLiteral( "wms:westBoundLongitude" ) ).toElement(); + eBoundLongitudeElem = n1.namedItem( QStringLiteral( "wms:eastBoundLongitude" ) ).toElement(); + sBoundLatitudeElem = n1.namedItem( QStringLiteral( "wms:southBoundLatitude" ) ).toElement(); + nBoundLatitudeElem = n1.namedItem( QStringLiteral( "wms:northBoundLatitude" ) ).toElement(); } else { - wBoundLongitudeElem = n1.namedItem( "westBoundLongitude" ).toElement(); - eBoundLongitudeElem = n1.namedItem( "eastBoundLongitude" ).toElement(); - sBoundLatitudeElem = n1.namedItem( "southBoundLatitude" ).toElement(); - nBoundLatitudeElem = n1.namedItem( "northBoundLatitude" ).toElement(); + wBoundLongitudeElem = n1.namedItem( QStringLiteral( "westBoundLongitude" ) ).toElement(); + eBoundLongitudeElem = n1.namedItem( QStringLiteral( "eastBoundLongitude" ) ).toElement(); + sBoundLatitudeElem = n1.namedItem( QStringLiteral( "southBoundLatitude" ) ).toElement(); + nBoundLatitudeElem = n1.namedItem( QStringLiteral( "northBoundLatitude" ) ).toElement(); } double wBLong, eBLong, sBLat, nBLat; @@ -875,21 +875,21 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& layerProperty.ex_GeographicBoundingBox = QgsRectangle( wBLong, sBLat, eBLong, nBLat ); } } - else if ( tagName == "BoundingBox" ) + else if ( tagName == QLatin1String( "BoundingBox" ) ) { // TODO: overwrite inherited QgsWmsBoundingBoxProperty bbox; - bbox.box = QgsRectangle( e1.attribute( "minx" ).toDouble(), - e1.attribute( "miny" ).toDouble(), - e1.attribute( "maxx" ).toDouble(), - e1.attribute( "maxy" ).toDouble() + bbox.box = QgsRectangle( e1.attribute( QStringLiteral( "minx" ) ).toDouble(), + e1.attribute( QStringLiteral( "miny" ) ).toDouble(), + e1.attribute( QStringLiteral( "maxx" ) ).toDouble(), + e1.attribute( QStringLiteral( "maxy" ) ).toDouble() ); - if ( e1.hasAttribute( "CRS" ) || e1.hasAttribute( "SRS" ) ) + if ( e1.hasAttribute( QStringLiteral( "CRS" ) ) || e1.hasAttribute( QStringLiteral( "SRS" ) ) ) { - if ( e1.hasAttribute( "CRS" ) ) - bbox.crs = e1.attribute( "CRS" ); - else if ( e1.hasAttribute( "SRS" ) ) - bbox.crs = e1.attribute( "SRS" ); + if ( e1.hasAttribute( QStringLiteral( "CRS" ) ) ) + bbox.crs = e1.attribute( QStringLiteral( "CRS" ) ); + else if ( e1.hasAttribute( QStringLiteral( "SRS" ) ) ) + bbox.crs = e1.attribute( QStringLiteral( "SRS" ) ); if ( shouldInvertAxisOrientation( bbox.crs ) ) { @@ -905,35 +905,35 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& QgsDebugMsg( "CRS/SRS attribute not found in BoundingBox" ); } } - else if ( tagName == "Dimension" ) + else if ( tagName == QLatin1String( "Dimension" ) ) { // TODO } - else if ( tagName == "Attribution" ) + else if ( tagName == QLatin1String( "Attribution" ) ) { // TODO } - else if ( tagName == "AuthorityURL" ) + else if ( tagName == QLatin1String( "AuthorityURL" ) ) { // TODO } - else if ( tagName == "Identifier" ) + else if ( tagName == QLatin1String( "Identifier" ) ) { // TODO } - else if ( tagName == "MetadataURL" ) + else if ( tagName == QLatin1String( "MetadataURL" ) ) { // TODO } - else if ( tagName == "DataURL" ) + else if ( tagName == QLatin1String( "DataURL" ) ) { // TODO } - else if ( tagName == "FeatureListURL" ) + else if ( tagName == QLatin1String( "FeatureListURL" ) ) { // TODO } - else if ( tagName == "Style" ) + else if ( tagName == QLatin1String( "Style" ) ) { QgsWmsStyleProperty styleProperty; @@ -952,11 +952,11 @@ void QgsWmsCapabilities::parseLayer( QDomElement const & e, QgsWmsLayerProperty& } layerProperty.style.push_back( styleProperty ); } - else if ( tagName == "MinScaleDenominator" ) + else if ( tagName == QLatin1String( "MinScaleDenominator" ) ) { // TODO } - else if ( tagName == "MaxScaleDenominator" ) + else if ( tagName == QLatin1String( "MaxScaleDenominator" ) ) { // TODO } @@ -1008,31 +1008,31 @@ void QgsWmsCapabilities::parseStyle( QDomElement const & e, QgsWmsStyleProperty& if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Name" ) + if ( tagName == QLatin1String( "Name" ) ) { styleProperty.name = e1.text(); } - else if ( tagName == "Title" ) + else if ( tagName == QLatin1String( "Title" ) ) { styleProperty.title = e1.text(); } - else if ( tagName == "Abstract" ) + else if ( tagName == QLatin1String( "Abstract" ) ) { styleProperty.abstract = e1.text(); } - else if ( tagName == "LegendURL" ) + else if ( tagName == QLatin1String( "LegendURL" ) ) { styleProperty.legendUrl << QgsWmsLegendUrlProperty(); parseLegendUrl( e1, styleProperty.legendUrl.last() ); } - else if ( tagName == "StyleSheetURL" ) + else if ( tagName == QLatin1String( "StyleSheetURL" ) ) { // TODO } - else if ( tagName == "StyleURL" ) + else if ( tagName == QLatin1String( "StyleURL" ) ) { // TODO } @@ -1054,15 +1054,15 @@ void QgsWmsCapabilities::parseOperationType( QDomElement const & e, QgsWmsOperat if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Format" ) + if ( tagName == QLatin1String( "Format" ) ) { QgsDebugMsg( " Format." ); operationType.format += e1.text(); } - else if ( tagName == "DCPType" ) + else if ( tagName == QLatin1String( "DCPType" ) ) { QgsDebugMsg( " DCPType." ); QgsWmsDcpTypeProperty dcp; @@ -1086,7 +1086,7 @@ void QgsWmsCapabilities::parseDcpType( QDomElement const & e, QgsWmsDcpTypePrope QDomElement e1 = n1.toElement(); // try to convert the node to an element. if ( !e1.isNull() ) { - if ( e1.tagName() == "HTTP" ) + if ( e1.tagName() == QLatin1String( "HTTP" ) ) { QgsDebugMsg( " HTTP." ); parseHttp( e1, dcpType.http ); @@ -1108,15 +1108,15 @@ void QgsWmsCapabilities::parseHttp( QDomElement const & e, QgsWmsHttpProperty& h if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Get" ) + if ( tagName == QLatin1String( "Get" ) ) { QgsDebugMsg( " Get." ); parseGet( e1, httpProperty.get ); } - else if ( tagName == "Post" ) + else if ( tagName == QLatin1String( "Post" ) ) { QgsDebugMsg( " Post." ); parsePost( e1, httpProperty.post ); @@ -1138,10 +1138,10 @@ void QgsWmsCapabilities::parseGet( QDomElement const & e, QgsWmsGetProperty& get if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "OnlineResource" ) + if ( tagName == QLatin1String( "OnlineResource" ) ) { QgsDebugMsg( " OnlineResource." ); parseOnlineResource( e1, getProperty.onlineResource ); @@ -1163,10 +1163,10 @@ void QgsWmsCapabilities::parsePost( QDomElement const & e, QgsWmsPostProperty& p if ( !e1.isNull() ) { QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "OnlineResource" ) + if ( tagName == QLatin1String( "OnlineResource" ) ) { QgsDebugMsg( " OnlineResource." ); parseOnlineResource( e1, postProperty.onlineResource ); @@ -1197,50 +1197,50 @@ void QgsWmsCapabilities::parseTileSetProfile( QDomElement const &e ) QgsDebugMsg( " " + e1.tagName() ); // the node really is an element. QString tagName = e1.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "Layers" ) + if ( tagName == QLatin1String( "Layers" ) ) { layers << e1.text(); } - else if ( tagName == "Styles" ) + else if ( tagName == QLatin1String( "Styles" ) ) { styles << e1.text(); } - else if ( tagName == "Width" ) + else if ( tagName == QLatin1String( "Width" ) ) { m.tileWidth = e1.text().toInt(); } - else if ( tagName == "Height" ) + else if ( tagName == QLatin1String( "Height" ) ) { m.tileHeight = e1.text().toInt(); } - else if ( tagName == "SRS" ) + else if ( tagName == QLatin1String( "SRS" ) ) { ms.crs = e1.text(); } - else if ( tagName == "Format" ) + else if ( tagName == QLatin1String( "Format" ) ) { l.formats << e1.text(); } - else if ( tagName == "BoundingBox" ) + else if ( tagName == QLatin1String( "BoundingBox" ) ) { QgsWmsBoundingBoxProperty bb; bb.box = QgsRectangle( - e1.attribute( "minx" ).toDouble(), - e1.attribute( "miny" ).toDouble(), - e1.attribute( "maxx" ).toDouble(), - e1.attribute( "maxy" ).toDouble() + e1.attribute( QStringLiteral( "minx" ) ).toDouble(), + e1.attribute( QStringLiteral( "miny" ) ).toDouble(), + e1.attribute( QStringLiteral( "maxx" ) ).toDouble(), + e1.attribute( QStringLiteral( "maxy" ) ).toDouble() ); - if ( e1.hasAttribute( "SRS" ) ) - bb.crs = e1.attribute( "SRS" ); - else if ( e1.hasAttribute( "srs" ) ) - bb.crs = e1.attribute( "srs" ); - else if ( e1.hasAttribute( "CRS" ) ) - bb.crs = e1.attribute( "CRS" ); - else if ( e1.hasAttribute( "crs" ) ) - bb.crs = e1.attribute( "crs" ); + if ( e1.hasAttribute( QStringLiteral( "SRS" ) ) ) + bb.crs = e1.attribute( QStringLiteral( "SRS" ) ); + else if ( e1.hasAttribute( QStringLiteral( "srs" ) ) ) + bb.crs = e1.attribute( QStringLiteral( "srs" ) ); + else if ( e1.hasAttribute( QStringLiteral( "CRS" ) ) ) + bb.crs = e1.attribute( QStringLiteral( "CRS" ) ); + else if ( e1.hasAttribute( QStringLiteral( "crs" ) ) ) + bb.crs = e1.attribute( QStringLiteral( "crs" ) ); else { QgsDebugMsg( "crs of bounding box undefined" ); @@ -1255,7 +1255,7 @@ void QgsWmsCapabilities::parseTileSetProfile( QDomElement const &e ) l.boundingBoxes << bb; } } - else if ( tagName == "Resolutions" ) + else if ( tagName == QLatin1String( "Resolutions" ) ) { resolutions = e1.text().trimmed().split( ' ', QString::SkipEmptyParts ); } @@ -1267,11 +1267,11 @@ void QgsWmsCapabilities::parseTileSetProfile( QDomElement const &e ) n1 = n1.nextSibling(); } - ms.identifier = QString( "%1-wmsc-%2" ).arg( layers.join( "_" ) ).arg( mTileLayersSupported.size() ); + ms.identifier = QStringLiteral( "%1-wmsc-%2" ).arg( layers.join( QStringLiteral( "_" ) ) ).arg( mTileLayersSupported.size() ); - l.identifier = layers.join( "," ); + l.identifier = layers.join( QStringLiteral( "," ) ); QgsWmtsStyle s; - s.identifier = styles.join( "," ); + s.identifier = styles.join( QStringLiteral( "," ) ); l.styles.insert( s.identifier, s ); l.defaultStyle = s.identifier; @@ -1304,21 +1304,21 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) // mTileMatrixSets.clear(); - for ( QDomElement e0 = e.firstChildElement( "TileMatrixSet" ); + for ( QDomElement e0 = e.firstChildElement( QStringLiteral( "TileMatrixSet" ) ); !e0.isNull(); - e0 = e0.nextSiblingElement( "TileMatrixSet" ) ) + e0 = e0.nextSiblingElement( QStringLiteral( "TileMatrixSet" ) ) ) { QgsWmtsTileMatrixSet s; - s.identifier = e0.firstChildElement( "ows:Identifier" ).text(); - s.title = e0.firstChildElement( "ows:Title" ).text(); - s.abstract = e0.firstChildElement( "ows:Abstract" ).text(); + s.identifier = e0.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); + s.title = e0.firstChildElement( QStringLiteral( "ows:Title" ) ).text(); + s.abstract = e0.firstChildElement( QStringLiteral( "ows:Abstract" ) ).text(); parseKeywords( e0, s.keywords ); - QString supportedCRS = e0.firstChildElement( "ows:SupportedCRS" ).text(); + QString supportedCRS = e0.firstChildElement( QStringLiteral( "ows:SupportedCRS" ) ).text(); QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( supportedCRS ); - s.wkScaleSet = e0.firstChildElement( "WellKnownScaleSet" ).text(); + s.wkScaleSet = e0.firstChildElement( QStringLiteral( "WellKnownScaleSet" ) ).text(); double metersPerUnit = QgsUnitTypes::fromUnitToUnitFactor( crs.mapUnits(), QgsUnitTypes::DistanceMeters ); @@ -1336,20 +1336,20 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) .arg( invert ? "yes" : "no" ) ); - for ( QDomElement e1 = e0.firstChildElement( "TileMatrix" ); + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "TileMatrix" ) ); !e1.isNull(); - e1 = e1.nextSiblingElement( "TileMatrix" ) ) + e1 = e1.nextSiblingElement( QStringLiteral( "TileMatrix" ) ) ) { QgsWmtsTileMatrix m; - m.identifier = e1.firstChildElement( "ows:Identifier" ).text(); - m.title = e1.firstChildElement( "ows:Title" ).text(); - m.abstract = e1.firstChildElement( "ows:Abstract" ).text(); + m.identifier = e1.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); + m.title = e1.firstChildElement( QStringLiteral( "ows:Title" ) ).text(); + m.abstract = e1.firstChildElement( QStringLiteral( "ows:Abstract" ) ).text(); parseKeywords( e1, m.keywords ); - m.scaleDenom = e1.firstChildElement( "ScaleDenominator" ).text().toDouble(); + m.scaleDenom = e1.firstChildElement( QStringLiteral( "ScaleDenominator" ) ).text().toDouble(); - QStringList topLeft = e1.firstChildElement( "TopLeftCorner" ).text().split( ' ' ); + QStringList topLeft = e1.firstChildElement( QStringLiteral( "TopLeftCorner" ) ).text().split( ' ' ); if ( topLeft.size() == 2 ) { if ( invert ) @@ -1367,10 +1367,10 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) continue; } - m.tileWidth = e1.firstChildElement( "TileWidth" ).text().toInt(); - m.tileHeight = e1.firstChildElement( "TileHeight" ).text().toInt(); - m.matrixWidth = e1.firstChildElement( "MatrixWidth" ).text().toInt(); - m.matrixHeight = e1.firstChildElement( "MatrixHeight" ).text().toInt(); + m.tileWidth = e1.firstChildElement( QStringLiteral( "TileWidth" ) ).text().toInt(); + m.tileHeight = e1.firstChildElement( QStringLiteral( "TileHeight" ) ).text().toInt(); + m.matrixWidth = e1.firstChildElement( QStringLiteral( "MatrixWidth" ) ).text().toInt(); + m.matrixHeight = e1.firstChildElement( QStringLiteral( "MatrixHeight" ) ).text().toInt(); // the magic number below is "standardized rendering pixel size" defined // in WMTS (and WMS 1.3) standard, being 0.28 pixel @@ -1395,29 +1395,29 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) // mTileLayersSupported.clear(); - for ( QDomElement e0 = e.firstChildElement( "Layer" ); + for ( QDomElement e0 = e.firstChildElement( QStringLiteral( "Layer" ) ); !e0.isNull(); - e0 = e0.nextSiblingElement( "Layer" ) ) + e0 = e0.nextSiblingElement( QStringLiteral( "Layer" ) ) ) { #ifdef QGISDEBUG - QString id = e0.firstChildElement( "ows:Identifier" ).text(); // clazy:exclude=unused-non-trivial-variable + QString id = e0.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); // clazy:exclude=unused-non-trivial-variable QgsDebugMsg( QString( "Layer %1" ).arg( id ) ); #endif QgsWmtsTileLayer l; l.tileMode = WMTS; - l.identifier = e0.firstChildElement( "ows:Identifier" ).text(); - l.title = e0.firstChildElement( "ows:Title" ).text(); - l.abstract = e0.firstChildElement( "ows:Abstract" ).text(); + l.identifier = e0.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); + l.title = e0.firstChildElement( QStringLiteral( "ows:Title" ) ).text(); + l.abstract = e0.firstChildElement( QStringLiteral( "ows:Abstract" ) ).text(); parseKeywords( e0, l.keywords ); QgsWmsBoundingBoxProperty bb; - QDomElement bbox = e0.firstChildElement( "ows:WGS84BoundingBox" ); + QDomElement bbox = e0.firstChildElement( QStringLiteral( "ows:WGS84BoundingBox" ) ); if ( !bbox.isNull() ) { - QStringList ll = bbox.firstChildElement( "ows:LowerCorner" ).text().split( ' ' ); - QStringList ur = bbox.firstChildElement( "ows:UpperCorner" ).text().split( ' ' ); + QStringList ll = bbox.firstChildElement( QStringLiteral( "ows:LowerCorner" ) ).text().split( ' ' ); + QStringList ur = bbox.firstChildElement( QStringLiteral( "ows:UpperCorner" ) ).text().split( ' ' ); if ( ll.size() == 2 && ur.size() == 2 ) { @@ -1429,26 +1429,26 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) } } - for ( bbox = e0.firstChildElement( "ows:BoundingBox" ); + for ( bbox = e0.firstChildElement( QStringLiteral( "ows:BoundingBox" ) ); !bbox.isNull(); - bbox = bbox.nextSiblingElement( "ows:BoundingBox" ) ) + bbox = bbox.nextSiblingElement( QStringLiteral( "ows:BoundingBox" ) ) ) { - QStringList ll = bbox.firstChildElement( "ows:LowerCorner" ).text().split( ' ' ); - QStringList ur = bbox.firstChildElement( "ows:UpperCorner" ).text().split( ' ' ); + QStringList ll = bbox.firstChildElement( QStringLiteral( "ows:LowerCorner" ) ).text().split( ' ' ); + QStringList ur = bbox.firstChildElement( QStringLiteral( "ows:UpperCorner" ) ).text().split( ' ' ); if ( ll.size() == 2 && ur.size() == 2 ) { bb.box = QgsRectangle( QgsPoint( ll[0].toDouble(), ll[1].toDouble() ), QgsPoint( ur[0].toDouble(), ur[1].toDouble() ) ); - if ( bbox.hasAttribute( "SRS" ) ) - bb.crs = bbox.attribute( "SRS" ); - else if ( bbox.hasAttribute( "srs" ) ) - bb.crs = bbox.attribute( "srs" ); - else if ( bbox.hasAttribute( "CRS" ) ) - bb.crs = bbox.attribute( "CRS" ); - else if ( bbox.hasAttribute( "crs" ) ) - bb.crs = bbox.attribute( "crs" ); + if ( bbox.hasAttribute( QStringLiteral( "SRS" ) ) ) + bb.crs = bbox.attribute( QStringLiteral( "SRS" ) ); + else if ( bbox.hasAttribute( QStringLiteral( "srs" ) ) ) + bb.crs = bbox.attribute( QStringLiteral( "srs" ) ); + else if ( bbox.hasAttribute( QStringLiteral( "CRS" ) ) ) + bb.crs = bbox.attribute( QStringLiteral( "CRS" ) ); + else if ( bbox.hasAttribute( QStringLiteral( "crs" ) ) ) + bb.crs = bbox.attribute( QStringLiteral( "crs" ) ); else { QgsDebugMsg( "crs of bounding box undefined" ); @@ -1474,33 +1474,33 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) } } - for ( QDomElement e1 = e0.firstChildElement( "Style" ); + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "Style" ) ); !e1.isNull(); - e1 = e1.nextSiblingElement( "Style" ) ) + e1 = e1.nextSiblingElement( QStringLiteral( "Style" ) ) ) { QgsWmtsStyle s; - s.identifier = e1.firstChildElement( "ows:Identifier" ).text(); - s.title = e1.firstChildElement( "ows:Title" ).text(); - s.abstract = e1.firstChildElement( "ows:Abstract" ).text(); + s.identifier = e1.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); + s.title = e1.firstChildElement( QStringLiteral( "ows:Title" ) ).text(); + s.abstract = e1.firstChildElement( QStringLiteral( "ows:Abstract" ) ).text(); parseKeywords( e1, s.keywords ); - for ( QDomElement e2 = e1.firstChildElement( "ows:legendURL" ); + for ( QDomElement e2 = e1.firstChildElement( QStringLiteral( "ows:legendURL" ) ); !e2.isNull(); - e2 = e2.nextSiblingElement( "ows:legendURL" ) ) + e2 = e2.nextSiblingElement( QStringLiteral( "ows:legendURL" ) ) ) { QgsWmtsLegendURL u; - u.format = e2.firstChildElement( "format" ).text(); - u.minScale = e2.firstChildElement( "minScale" ).text().toDouble(); - u.maxScale = e2.firstChildElement( "maxScale" ).text().toDouble(); - u.href = e2.firstChildElement( "href" ).text(); - u.width = e2.firstChildElement( "width" ).text().toInt(); - u.height = e2.firstChildElement( "height" ).text().toInt(); + u.format = e2.firstChildElement( QStringLiteral( "format" ) ).text(); + u.minScale = e2.firstChildElement( QStringLiteral( "minScale" ) ).text().toDouble(); + u.maxScale = e2.firstChildElement( QStringLiteral( "maxScale" ) ).text().toDouble(); + u.href = e2.firstChildElement( QStringLiteral( "href" ) ).text(); + u.width = e2.firstChildElement( QStringLiteral( "width" ) ).text().toInt(); + u.height = e2.firstChildElement( QStringLiteral( "height" ) ).text().toInt(); s.legendURLs << u; } - s.isDefault = e1.attribute( "isDefault" ) == "true"; + s.isDefault = e1.attribute( QStringLiteral( "isDefault" ) ) == QLatin1String( "true" ); l.styles.insert( s.identifier, s ); @@ -1511,18 +1511,18 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) if ( l.styles.isEmpty() ) { QgsWmtsStyle s; - s.identifier = "default"; + s.identifier = QStringLiteral( "default" ); s.title = QObject::tr( "Generated default style" ); s.abstract = QObject::tr( "Style was missing in capabilities" ); l.styles.insert( s.identifier, s ); } - for ( QDomElement e1 = e0.firstChildElement( "Format" ); !e1.isNull(); e1 = e1.nextSiblingElement( "Format" ) ) + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "Format" ) ); !e1.isNull(); e1 = e1.nextSiblingElement( QStringLiteral( "Format" ) ) ) { l.formats << e1.text(); } - for ( QDomElement e1 = e0.firstChildElement( "InfoFormat" ); !e1.isNull(); e1 = e1.nextSiblingElement( "InfoFormat" ) ) + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "InfoFormat" ) ); !e1.isNull(); e1 = e1.nextSiblingElement( QStringLiteral( "InfoFormat" ) ) ) { QString format = e1.text(); @@ -1532,19 +1532,19 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) QgsDebugMsg( QString( "format=%1" ).arg( format ) ); - if ( format == "MIME" ) + if ( format == QLatin1String( "MIME" ) ) fmt = QgsRaster::IdentifyFormatText; // 1.0 - else if ( format == "text/plain" ) + else if ( format == QLatin1String( "text/plain" ) ) fmt = QgsRaster::IdentifyFormatText; - else if ( format == "text/html" ) + else if ( format == QLatin1String( "text/html" ) ) fmt = QgsRaster::IdentifyFormatHtml; - else if ( format.startsWith( "GML." ) ) + else if ( format.startsWith( QLatin1String( "GML." ) ) ) fmt = QgsRaster::IdentifyFormatFeature; // 1.0 - else if ( format == "application/vnd.ogc.gml" ) + else if ( format == QLatin1String( "application/vnd.ogc.gml" ) ) fmt = QgsRaster::IdentifyFormatFeature; - else if ( format.contains( "gml", Qt::CaseInsensitive ) ) + else if ( format.contains( QLatin1String( "gml" ), Qt::CaseInsensitive ) ) fmt = QgsRaster::IdentifyFormatFeature; - else if ( format == "application/json" ) + else if ( format == QLatin1String( "application/json" ) ) fmt = QgsRaster::IdentifyFormatFeature; else { @@ -1556,26 +1556,26 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) mIdentifyFormats.insert( fmt, format ); } - for ( QDomElement e1 = e0.firstChildElement( "Dimension" ); !e1.isNull(); e1 = e1.nextSiblingElement( "Dimension" ) ) + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "Dimension" ) ); !e1.isNull(); e1 = e1.nextSiblingElement( QStringLiteral( "Dimension" ) ) ) { QgsWmtsDimension d; - d.identifier = e1.firstChildElement( "ows:Identifier" ).text(); + d.identifier = e1.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); if ( d.identifier.isEmpty() ) continue; - d.title = e1.firstChildElement( "ows:Title" ).text(); - d.abstract = e1.firstChildElement( "ows:Abstract" ).text(); + d.title = e1.firstChildElement( QStringLiteral( "ows:Title" ) ).text(); + d.abstract = e1.firstChildElement( QStringLiteral( "ows:Abstract" ) ).text(); parseKeywords( e1, d.keywords ); - d.UOM = e1.firstChildElement( "UOM" ).text(); - d.unitSymbol = e1.firstChildElement( "unitSymbol" ).text(); - d.defaultValue = e1.firstChildElement( "Default" ).text(); - d.current = e1.firstChildElement( "current" ).text() == "true"; + d.UOM = e1.firstChildElement( QStringLiteral( "UOM" ) ).text(); + d.unitSymbol = e1.firstChildElement( QStringLiteral( "unitSymbol" ) ).text(); + d.defaultValue = e1.firstChildElement( QStringLiteral( "Default" ) ).text(); + d.current = e1.firstChildElement( QStringLiteral( "current" ) ).text() == QLatin1String( "true" ); - for ( QDomElement e2 = e1.firstChildElement( "Value" ); + for ( QDomElement e2 = e1.firstChildElement( QStringLiteral( "Value" ) ); !e2.isNull(); - e2 = e2.nextSiblingElement( "Value" ) ) + e2 = e2.nextSiblingElement( QStringLiteral( "Value" ) ) ) { d.values << e2.text(); } @@ -1583,11 +1583,11 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) l.dimensions.insert( d.identifier, d ); } - for ( QDomElement e1 = e0.firstChildElement( "TileMatrixSetLink" ); !e1.isNull(); e1 = e1.nextSiblingElement( "TileMatrixSetLink" ) ) + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "TileMatrixSetLink" ) ); !e1.isNull(); e1 = e1.nextSiblingElement( QStringLiteral( "TileMatrixSetLink" ) ) ) { QgsWmtsTileMatrixSetLink sl; - sl.tileMatrixSet = e1.firstChildElement( "TileMatrixSet" ).text(); + sl.tileMatrixSet = e1.firstChildElement( QStringLiteral( "TileMatrixSet" ) ).text(); if ( !mTileMatrixSets.contains( sl.tileMatrixSet ) ) { @@ -1597,13 +1597,13 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) const QgsWmtsTileMatrixSet &tms = mTileMatrixSets[ sl.tileMatrixSet ]; - for ( QDomElement e2 = e1.firstChildElement( "TileMatrixSetLimits" ); !e2.isNull(); e2 = e2.nextSiblingElement( "TileMatrixSetLimits" ) ) + for ( QDomElement e2 = e1.firstChildElement( QStringLiteral( "TileMatrixSetLimits" ) ); !e2.isNull(); e2 = e2.nextSiblingElement( QStringLiteral( "TileMatrixSetLimits" ) ) ) { - for ( QDomElement e3 = e2.firstChildElement( "TileMatrixLimits" ); !e3.isNull(); e3 = e3.nextSiblingElement( "TileMatrixLimits" ) ) + for ( QDomElement e3 = e2.firstChildElement( QStringLiteral( "TileMatrixLimits" ) ); !e3.isNull(); e3 = e3.nextSiblingElement( QStringLiteral( "TileMatrixLimits" ) ) ) { QgsWmtsTileMatrixLimits limit; - QString id = e3.firstChildElement( "TileMatrix" ).text(); + QString id = e3.firstChildElement( QStringLiteral( "TileMatrix" ) ).text(); bool isValid = false; int matrixWidth = -1, matrixHeight = -1; @@ -1620,10 +1620,10 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) if ( isValid ) { - limit.minTileRow = e3.firstChildElement( "MinTileRow" ).text().toInt(); - limit.maxTileRow = e3.firstChildElement( "MaxTileRow" ).text().toInt(); - limit.minTileCol = e3.firstChildElement( "MinTileCol" ).text().toInt(); - limit.maxTileCol = e3.firstChildElement( "MaxTileCol" ).text().toInt(); + limit.minTileRow = e3.firstChildElement( QStringLiteral( "MinTileRow" ) ).text().toInt(); + limit.maxTileRow = e3.firstChildElement( QStringLiteral( "MaxTileRow" ) ).text().toInt(); + limit.minTileCol = e3.firstChildElement( QStringLiteral( "MinTileCol" ) ).text().toInt(); + limit.maxTileCol = e3.firstChildElement( QStringLiteral( "MaxTileCol" ) ).text().toInt(); isValid = limit.minTileCol >= 0 && limit.minTileCol < matrixWidth && @@ -1656,11 +1656,11 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) l.setLinks.insert( sl.tileMatrixSet, sl ); } - for ( QDomElement e1 = e0.firstChildElement( "ResourceURL" ); !e1.isNull(); e1 = e1.nextSiblingElement( "ResourceURL" ) ) + for ( QDomElement e1 = e0.firstChildElement( QStringLiteral( "ResourceURL" ) ); !e1.isNull(); e1 = e1.nextSiblingElement( QStringLiteral( "ResourceURL" ) ) ) { - QString format = nodeAttribute( e1, "format" ); - QString resourceType = nodeAttribute( e1, "resourceType" ); - QString tmpl = nodeAttribute( e1, "template" ); + QString format = nodeAttribute( e1, QStringLiteral( "format" ) ); + QString resourceType = nodeAttribute( e1, QStringLiteral( "resourceType" ) ); + QString tmpl = nodeAttribute( e1, QStringLiteral( "template" ) ); if ( format.isEmpty() || resourceType.isEmpty() || tmpl.isEmpty() ) { @@ -1671,11 +1671,11 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) continue; } - if ( resourceType == "tile" ) + if ( resourceType == QLatin1String( "tile" ) ) { l.getTileURLs.insert( format, tmpl ); } - else if ( resourceType == "FeatureInfo" ) + else if ( resourceType == QLatin1String( "FeatureInfo" ) ) { l.getFeatureInfoURLs.insert( format, tmpl ); @@ -1683,19 +1683,19 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) QgsDebugMsg( QString( "format=%1" ).arg( format ) ); - if ( format == "MIME" ) + if ( format == QLatin1String( "MIME" ) ) fmt = QgsRaster::IdentifyFormatText; // 1.0 - else if ( format == "text/plain" ) + else if ( format == QLatin1String( "text/plain" ) ) fmt = QgsRaster::IdentifyFormatText; - else if ( format == "text/html" ) + else if ( format == QLatin1String( "text/html" ) ) fmt = QgsRaster::IdentifyFormatHtml; - else if ( format.startsWith( "GML." ) ) + else if ( format.startsWith( QLatin1String( "GML." ) ) ) fmt = QgsRaster::IdentifyFormatFeature; // 1.0 - else if ( format == "application/vnd.ogc.gml" ) + else if ( format == QLatin1String( "application/vnd.ogc.gml" ) ) fmt = QgsRaster::IdentifyFormatFeature; - else if ( format.contains( "gml", Qt::CaseInsensitive ) ) + else if ( format.contains( QLatin1String( "gml" ), Qt::CaseInsensitive ) ) fmt = QgsRaster::IdentifyFormatFeature; - else if ( format == "application/json" ) + else if ( format == QLatin1String( "application/json" ) ) fmt = QgsRaster::IdentifyFormatFeature; else { @@ -1723,9 +1723,9 @@ void QgsWmsCapabilities::parseWMTSContents( QDomElement const &e ) // themes // mTileThemes.clear(); - for ( QDomElement e0 = e.firstChildElement( "Themes" ).firstChildElement( "Theme" ); + for ( QDomElement e0 = e.firstChildElement( QStringLiteral( "Themes" ) ).firstChildElement( QStringLiteral( "Theme" ) ); !e0.isNull(); - e0 = e0.nextSiblingElement( "Theme" ) ) + e0 = e0.nextSiblingElement( QStringLiteral( "Theme" ) ) ) { mTileThemes << QgsWmtsTheme(); parseTheme( e0, mTileThemes.back() ); @@ -1756,9 +1756,9 @@ void QgsWmsCapabilities::parseKeywords( const QDomNode &e, QStringList &keywords { keywords.clear(); - for ( QDomElement e1 = e.firstChildElement( "ows:Keywords" ).firstChildElement( "ows:Keyword" ); + for ( QDomElement e1 = e.firstChildElement( QStringLiteral( "ows:Keywords" ) ).firstChildElement( QStringLiteral( "ows:Keyword" ) ); !e1.isNull(); - e1 = e1.nextSiblingElement( "ows:Keyword" ) ) + e1 = e1.nextSiblingElement( QStringLiteral( "ows:Keyword" ) ) ) { keywords << e1.text(); } @@ -1766,12 +1766,12 @@ void QgsWmsCapabilities::parseKeywords( const QDomNode &e, QStringList &keywords void QgsWmsCapabilities::parseTheme( const QDomElement &e, QgsWmtsTheme &t ) { - t.identifier = e.firstChildElement( "ows:Identifier" ).text(); - t.title = e.firstChildElement( "ows:Title" ).text(); - t.abstract = e.firstChildElement( "ows:Abstract" ).text(); + t.identifier = e.firstChildElement( QStringLiteral( "ows:Identifier" ) ).text(); + t.title = e.firstChildElement( QStringLiteral( "ows:Title" ) ).text(); + t.abstract = e.firstChildElement( QStringLiteral( "ows:Abstract" ) ).text(); parseKeywords( e, t.keywords ); - QDomElement sl = e.firstChildElement( "ows:Theme" ); + QDomElement sl = e.firstChildElement( QStringLiteral( "ows:Theme" ) ); if ( !sl.isNull() ) { t.subTheme = new QgsWmtsTheme; @@ -1783,9 +1783,9 @@ void QgsWmsCapabilities::parseTheme( const QDomElement &e, QgsWmtsTheme &t ) } t.layerRefs.clear(); - for ( QDomElement e1 = e.firstChildElement( "ows:LayerRef" ); + for ( QDomElement e1 = e.firstChildElement( QStringLiteral( "ows:LayerRef" ) ); !e1.isNull(); - e1 = e1.nextSiblingElement( "ows:LayerRef" ) ) + e1 = e1.nextSiblingElement( QStringLiteral( "ows:LayerRef" ) ) ) { t.layerRefs << e1.text(); } @@ -1856,7 +1856,7 @@ bool QgsWmsCapabilities::shouldInvertAxisOrientation( const QString& ogcCrs ) { //according to the WMS spec for 1.3, some CRS have inverted axis bool changeXY = false; - if ( !mParserSettings.ignoreAxisOrientation && ( mCapabilities.version == "1.3.0" || mCapabilities.version == "1.3" ) ) + if ( !mParserSettings.ignoreAxisOrientation && ( mCapabilities.version == QLatin1String( "1.3.0" ) || mCapabilities.version == QLatin1String( "1.3" ) ) ) { //have we already checked this crs? if ( mCrsInvertAxis.contains( ogcCrs ) ) @@ -1936,10 +1936,10 @@ bool QgsWmsCapabilitiesDownload::downloadCapabilities() QString url = mBaseUrl; QgsDebugMsg( "url = " + url ); - if ( !url.contains( "SERVICE=WMTS", Qt::CaseInsensitive ) && - !url.contains( "/WMTSCapabilities.xml", Qt::CaseInsensitive ) ) + if ( !url.contains( QLatin1String( "SERVICE=WMTS" ), Qt::CaseInsensitive ) && + !url.contains( QLatin1String( "/WMTSCapabilities.xml" ), Qt::CaseInsensitive ) ) { - url += "SERVICE=WMS&REQUEST=GetCapabilities"; + url += QLatin1String( "SERVICE=WMS&REQUEST=GetCapabilities" ); } mError.clear(); @@ -1985,7 +1985,7 @@ void QgsWmsCapabilitiesDownload::abort() void QgsWmsCapabilitiesDownload::capabilitiesReplyProgress( qint64 bytesReceived, qint64 bytesTotal ) { - QString msg = tr( "%1 of %2 bytes of capabilities downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QString( "unknown number of" ) : QString::number( bytesTotal ) ); + QString msg = tr( "%1 of %2 bytes of capabilities downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QStringLiteral( "unknown number of" ) : QString::number( bytesTotal ) ); QgsDebugMsg( msg ); emit statusChanged( msg ); } @@ -2066,7 +2066,7 @@ void QgsWmsCapabilitiesDownload::capabilitiesReplyFinished() if ( cmd.expirationDate().isNull() ) { QSettings s; - cmd.setExpirationDate( QDateTime::currentDateTime().addSecs( s.value( "/qgis/defaultCapabilitiesExpiry", "24" ).toInt() * 60 * 60 ) ); + cmd.setExpirationDate( QDateTime::currentDateTime().addSecs( s.value( QStringLiteral( "/qgis/defaultCapabilitiesExpiry" ), "24" ).toInt() * 60 * 60 ) ); } nam->cache()->updateMetaData( cmd ); diff --git a/src/providers/wms/qgswmscapabilities.h b/src/providers/wms/qgswmscapabilities.h index adcd16520cc9..00d6d36539a6 100644 --- a/src/providers/wms/qgswmscapabilities.h +++ b/src/providers/wms/qgswmscapabilities.h @@ -503,12 +503,12 @@ struct QgsWmsAuthorization } else if ( !mUserName.isNull() || !mPassword.isNull() ) { - request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); + request.setRawHeader( "Authorization", "Basic " + QStringLiteral( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); } if ( !mReferer.isNull() ) { - request.setRawHeader( "Referer", QString( "%1" ).arg( mReferer ).toLatin1() ); + request.setRawHeader( "Referer", QStringLiteral( "%1" ).arg( mReferer ).toLatin1() ); } return true; } diff --git a/src/providers/wms/qgswmsconnection.cpp b/src/providers/wms/qgswmsconnection.cpp index 7b6060a73f18..c46354223acf 100644 --- a/src/providers/wms/qgswmsconnection.cpp +++ b/src/providers/wms/qgswmsconnection.cpp @@ -48,27 +48,27 @@ QgsWMSConnection::QgsWMSConnection( const QString& theConnName ) QStringList connStringParts; - mUri.setParam( "url", settings.value( key + "/url" ).toString() ); + mUri.setParam( QStringLiteral( "url" ), settings.value( key + "/url" ).toString() ); // Check for credentials and prepend to the connection info QString username = settings.value( credentialsKey + "/username" ).toString(); QString password = settings.value( credentialsKey + "/password" ).toString(); if ( !username.isEmpty() ) { - mUri.setParam( "username", username ); - mUri.setParam( "password", password ); + mUri.setParam( QStringLiteral( "username" ), username ); + mUri.setParam( QStringLiteral( "password" ), password ); } QString authcfg = settings.value( credentialsKey + "/authcfg" ).toString(); if ( !authcfg.isEmpty() ) { - mUri.setParam( "authcfg", authcfg ); + mUri.setParam( QStringLiteral( "authcfg" ), authcfg ); } QString referer = settings.value( key + "/referer" ).toString(); if ( !referer.isEmpty() ) { - mUri.setParam( "referer", referer ); + mUri.setParam( QStringLiteral( "referer" ), referer ); } bool ignoreGetMap = settings.value( key + "/ignoreGetMapURI", false ).toBool(); @@ -80,32 +80,32 @@ QgsWMSConnection::QgsWMSConnection( const QString& theConnName ) if ( ignoreGetMap ) { - mUri.setParam( "IgnoreGetMapUrl", "1" ); + mUri.setParam( QStringLiteral( "IgnoreGetMapUrl" ), QStringLiteral( "1" ) ); } if ( ignoreGetFeatureInfo ) { - mUri.setParam( "IgnoreGetFeatureInfoUrl", "1" ); + mUri.setParam( QStringLiteral( "IgnoreGetFeatureInfoUrl" ), QStringLiteral( "1" ) ); } if ( ignoreAxisOrientation ) { - mUri.setParam( "IgnoreAxisOrientation", "1" ); + mUri.setParam( QStringLiteral( "IgnoreAxisOrientation" ), QStringLiteral( "1" ) ); } if ( invertAxisOrientation ) { - mUri.setParam( "InvertAxisOrientation", "1" ); + mUri.setParam( QStringLiteral( "InvertAxisOrientation" ), QStringLiteral( "1" ) ); } if ( smoothPixmapTransform ) { - mUri.setParam( "SmoothPixmapTransform", "1" ); + mUri.setParam( QStringLiteral( "SmoothPixmapTransform" ), QStringLiteral( "1" ) ); } if ( !dpiMode.isEmpty() ) { - mUri.setParam( "dpiMode", dpiMode ); + mUri.setParam( QStringLiteral( "dpiMode" ), dpiMode ); } QgsDebugMsg( QString( "encodedUri: '%1'." ).arg( QString( mUri.encodedUri() ) ) ); @@ -124,20 +124,20 @@ QgsDataSourceUri QgsWMSConnection::uri() QStringList QgsWMSConnection::connectionList() { QSettings settings; - settings.beginGroup( "/Qgis/connections-wms" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wms" ) ); return settings.childGroups(); } QString QgsWMSConnection::selectedConnection() { QSettings settings; - return settings.value( "/Qgis/connections-wms/selected" ).toString(); + return settings.value( QStringLiteral( "/Qgis/connections-wms/selected" ) ).toString(); } void QgsWMSConnection::setSelectedConnection( const QString& name ) { QSettings settings; - settings.setValue( "/Qgis/connections-wms/selected", name ); + settings.setValue( QStringLiteral( "/Qgis/connections-wms/selected" ), name ); } void QgsWMSConnection::deleteConnection( const QString& name ) diff --git a/src/providers/wms/qgswmsdataitems.cpp b/src/providers/wms/qgswmsdataitems.cpp index e28ac7a8859f..fe8af73ded02 100644 --- a/src/providers/wms/qgswmsdataitems.cpp +++ b/src/providers/wms/qgswmsdataitems.cpp @@ -33,7 +33,7 @@ QgsWMSConnectionItem::QgsWMSConnectionItem( QgsDataItem* parent, QString name, Q , mUri( uri ) , mCapabilitiesDownload( nullptr ) { - mIconName = "mIconConnect.png"; + mIconName = QStringLiteral( "mIconConnect.png" ); mCapabilitiesDownload = new QgsWmsCapabilitiesDownload( false ); } @@ -215,7 +215,7 @@ QList<QAction*> QgsWMSConnectionItem::actions() void QgsWMSConnectionItem::editConnection() { - QgsNewHttpConnection nc( nullptr, "/Qgis/connections-wms/", mName ); + QgsNewHttpConnection nc( nullptr, QStringLiteral( "/Qgis/connections-wms/" ), mName ); if ( nc.exec() ) { @@ -235,7 +235,7 @@ void QgsWMSConnectionItem::deleteConnection() // --------------------------------------------------------------------------- QgsWMSLayerItem::QgsWMSLayerItem( QgsDataItem* parent, QString name, QString path, const QgsWmsCapabilitiesProperty &capabilitiesProperty, const QgsDataSourceUri& dataSourceUri, const QgsWmsLayerProperty &layerProperty ) - : QgsLayerItem( parent, name, path, QString(), QgsLayerItem::Raster, "wms" ) + : QgsLayerItem( parent, name, path, QString(), QgsLayerItem::Raster, QStringLiteral( "wms" ) ) , mCapabilitiesProperty( capabilitiesProperty ) , mDataSourceUri( dataSourceUri ) , mLayerProperty( layerProperty ) @@ -257,7 +257,7 @@ QgsWMSLayerItem::QgsWMSLayerItem( QgsDataItem* parent, QString name, QString pat addChildItem( layer ); } - mIconName = "mIconWms.svg"; + mIconName = QStringLiteral( "mIconWms.svg" ); setState( Populated ); } @@ -269,12 +269,12 @@ QgsWMSLayerItem::~QgsWMSLayerItem() QString QgsWMSLayerItem::createUri() { if ( mLayerProperty.name.isEmpty() ) - return ""; // layer collection + return QLatin1String( "" ); // layer collection // Number of styles must match number of layers - mDataSourceUri.setParam( "layers", mLayerProperty.name ); - QString style = !mLayerProperty.style.isEmpty() ? mLayerProperty.style.at( 0 ).name : ""; - mDataSourceUri.setParam( "styles", style ); + mDataSourceUri.setParam( QStringLiteral( "layers" ), mLayerProperty.name ); + QString style = !mLayerProperty.style.isEmpty() ? mLayerProperty.style.at( 0 ).name : QLatin1String( "" ); + mDataSourceUri.setParam( QStringLiteral( "styles" ), style ); QString format; // get first supported by qt and server @@ -287,7 +287,7 @@ QString QgsWMSLayerItem::createUri() break; } } - mDataSourceUri.setParam( "format", format ); + mDataSourceUri.setParam( QStringLiteral( "format" ), format ); QString crs; // get first known if possible @@ -305,7 +305,7 @@ QString QgsWMSLayerItem::createUri() { crs = mLayerProperty.crs[0]; } - mDataSourceUri.setParam( "crs", crs ); + mDataSourceUri.setParam( QStringLiteral( "crs" ), crs ); //uri = rasterLayerPath + "|layers=" + layers.join( "," ) + "|styles=" + styles.join( "," ) + "|format=" + format + "|crs=" + crs; return mDataSourceUri.encodedUri(); @@ -323,7 +323,7 @@ QgsWMTSLayerItem::QgsWMTSLayerItem( QgsDataItem *parent, const QString &tileMatrixSet, const QString &crs, const QString &title ) - : QgsLayerItem( parent, name, path, QString(), QgsLayerItem::Raster, "wms" ) + : QgsLayerItem( parent, name, path, QString(), QgsLayerItem::Raster, QStringLiteral( "wms" ) ) , mDataSourceUri( uri ) , mId( id ) , mFormat( format ) @@ -345,11 +345,11 @@ QString QgsWMTSLayerItem::createUri() // TODO dimensions QgsDataSourceUri uri( mDataSourceUri ); - uri.setParam( "layers", mId ); - uri.setParam( "styles", mStyle ); - uri.setParam( "format", mFormat ); - uri.setParam( "crs", mCrs ); - uri.setParam( "tileMatrixSet", mTileMatrixSet ); + uri.setParam( QStringLiteral( "layers" ), mId ); + uri.setParam( QStringLiteral( "styles" ), mStyle ); + uri.setParam( QStringLiteral( "format" ), mFormat ); + uri.setParam( QStringLiteral( "crs" ), mCrs ); + uri.setParam( QStringLiteral( "tileMatrixSet" ), mTileMatrixSet ); return uri.encodedUri(); } @@ -358,7 +358,7 @@ QgsWMSRootItem::QgsWMSRootItem( QgsDataItem* parent, QString name, QString path : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconWms.svg"; + mIconName = QStringLiteral( "mIconWms.svg" ); populate(); } @@ -433,17 +433,17 @@ QgsDataItem* QgsWmsDataItemProvider::createDataItem( const QString& thePath, Qgs QgsDebugMsg( "thePath = " + thePath ); if ( thePath.isEmpty() ) { - return new QgsWMSRootItem( parentItem, "WMS", "wms:" ); + return new QgsWMSRootItem( parentItem, QStringLiteral( "WMS" ), QStringLiteral( "wms:" ) ); } // path schema: wms:/connection name (used by OWS) - if ( thePath.startsWith( "wms:/" ) ) + if ( thePath.startsWith( QLatin1String( "wms:/" ) ) ) { QString connectionName = thePath.split( '/' ).last(); if ( QgsWMSConnection::connectionList().contains( connectionName ) ) { QgsWMSConnection connection( connectionName ); - return new QgsWMSConnectionItem( parentItem, "WMS", thePath, connection.uri().encodedUri() ); + return new QgsWMSConnectionItem( parentItem, QStringLiteral( "WMS" ), thePath, connection.uri().encodedUri() ); } } @@ -464,7 +464,7 @@ QgsXyzTileRootItem::QgsXyzTileRootItem( QgsDataItem *parent, QString name, QStri : QgsDataCollectionItem( parent, name, path ) { mCapabilities |= Fast; - mIconName = "mIconWms.svg"; + mIconName = QStringLiteral( "mIconWms.svg" ); populate(); } @@ -512,7 +512,7 @@ void QgsXyzTileRootItem::newConnection() QgsXyzLayerItem::QgsXyzLayerItem( QgsDataItem *parent, QString name, QString path, const QString &encodedUri ) - : QgsLayerItem( parent, name, path, encodedUri, QgsLayerItem::Raster, "wms" ) + : QgsLayerItem( parent, name, path, encodedUri, QgsLayerItem::Raster, QStringLiteral( "wms" ) ) { setState( Populated ); } diff --git a/src/providers/wms/qgswmsdataitems.h b/src/providers/wms/qgswmsdataitems.h index d6dc4b8f7bbf..576365e6fca2 100644 --- a/src/providers/wms/qgswmsdataitems.h +++ b/src/providers/wms/qgswmsdataitems.h @@ -111,7 +111,7 @@ class QgsWMSRootItem : public QgsDataCollectionItem class QgsWmsDataItemProvider : public QgsDataItemProvider { public: - virtual QString name() override { return "WMS"; } + virtual QString name() override { return QStringLiteral( "WMS" ); } virtual int capabilities() override { return QgsDataProvider::Net; } @@ -152,14 +152,14 @@ class QgsXyzLayerItem : public QgsLayerItem class QgsXyzTileDataItemProvider : public QgsDataItemProvider { public: - virtual QString name() override { return "XYZ Tiles"; } + virtual QString name() override { return QStringLiteral( "XYZ Tiles" ); } virtual int capabilities() override { return QgsDataProvider::Net; } virtual QgsDataItem* createDataItem( const QString& path, QgsDataItem* parentItem ) override { if ( path.isEmpty() ) - return new QgsXyzTileRootItem( parentItem, "Tile Server (XYZ)", "xyz:" ); + return new QgsXyzTileRootItem( parentItem, QStringLiteral( "Tile Server (XYZ)" ), QStringLiteral( "xyz:" ) ); return nullptr; } }; diff --git a/src/providers/wms/qgswmsprovider.cpp b/src/providers/wms/qgswmsprovider.cpp index fbec63444ff1..8806a0e5067b 100644 --- a/src/providers/wms/qgswmsprovider.cpp +++ b/src/providers/wms/qgswmsprovider.cpp @@ -73,10 +73,10 @@ #define ERR(message) QGS_ERROR_MESSAGE(message,"WMS provider") #define QGS_ERROR(message) QgsError(message,"WMS provider") -static QString WMS_KEY = "wms"; -static QString WMS_DESCRIPTION = "OGC Web Map Service version 1.3 data provider"; +static QString WMS_KEY = QStringLiteral( "wms" ); +static QString WMS_DESCRIPTION = QStringLiteral( "OGC Web Map Service version 1.3 data provider" ); -static QString DEFAULT_LATLON_CRS = "CRS:84"; +static QString DEFAULT_LATLON_CRS = QStringLiteral( "CRS:84" ); QMap<QString, QgsWmsStatistics::Stat> QgsWmsStatistics::sData; @@ -110,7 +110,7 @@ QgsWmsProvider::QgsWmsProvider( QString const& uri, const QgsWmsCapabilities* ca { QgsDebugMsg( "constructing with uri '" + uri + "'." ); - mSupportedGetFeatureFormats = QStringList() << "text/html" << "text/plain" << "text/xml" << "application/vnd.ogc.gml" << "application/json"; + mSupportedGetFeatureFormats = QStringList() << QStringLiteral( "text/html" ) << QStringLiteral( "text/plain" ) << QStringLiteral( "text/xml" ) << QStringLiteral( "application/vnd.ogc.gml" ) << QStringLiteral( "application/json" ); mValid = false; @@ -175,16 +175,16 @@ QgsWmsProvider::QgsWmsProvider( QString const& uri, const QgsWmsCapabilities* ca QString QgsWmsProvider::prepareUri( QString uri ) { - if ( uri.contains( "SERVICE=WMTS" ) || uri.contains( "/WMTSCapabilities.xml" ) ) + if ( uri.contains( QLatin1String( "SERVICE=WMTS" ) ) || uri.contains( QLatin1String( "/WMTSCapabilities.xml" ) ) ) { return uri; } - if ( !uri.contains( "?" ) ) + if ( !uri.contains( QLatin1String( "?" ) ) ) { uri.append( '?' ); } - else if ( uri.right( 1 ) != "?" && uri.right( 1 ) != "&" ) + else if ( uri.right( 1 ) != QLatin1String( "?" ) && uri.right( 1 ) != QLatin1String( "&" ) ) { uri.append( '&' ); } @@ -224,7 +224,7 @@ QString QgsWmsProvider::getTileUrl() const { if ( mCaps.mCapabilities.capability.request.getTile.dcpType.isEmpty() || ( !mCaps.mCapabilities.capability.request.getTile.allowedEncodings.isEmpty() && - !mCaps.mCapabilities.capability.request.getTile.allowedEncodings.contains( "KVP" ) ) ) + !mCaps.mCapabilities.capability.request.getTile.allowedEncodings.contains( QStringLiteral( "KVP" ) ) ) ) { return QString::null; } @@ -236,7 +236,7 @@ QString QgsWmsProvider::getTileUrl() const static bool isValidLegend( const QgsWmsLegendUrlProperty &l ) { - return l.format.startsWith( "image/" ); + return l.format.startsWith( QLatin1String( "image/" ) ); } /** @@ -274,7 +274,7 @@ QString QgsWmsProvider::getLegendGraphicUrl() const if ( l.name == mSettings.mActiveSubLayers[0] ) { - if ( !mSettings.mActiveSubStyles[0].isEmpty() && mSettings.mActiveSubStyles[0] != "default" ) + if ( !mSettings.mActiveSubStyles[0].isEmpty() && mSettings.mActiveSubStyles[0] != QLatin1String( "default" ) ) { const QgsWmsStyleProperty *s = searchStyle( l.style, mSettings.mActiveSubStyles[0] ); if ( s ) @@ -291,7 +291,7 @@ QString QgsWmsProvider::getLegendGraphicUrl() const } else { - const QgsWmsStyleProperty *s = searchStyle( l.style, "default" ); + const QgsWmsStyleProperty *s = searchStyle( l.style, QStringLiteral( "default" ) ); if ( s ) url = pickLegend( *s ); } @@ -486,15 +486,15 @@ void QgsWmsProvider::setQueryItem( QUrl &url, const QString& item, const QString void QgsWmsProvider::setFormatQueryItem( QUrl &url ) { - url.removeQueryItem( "FORMAT" ); + url.removeQueryItem( QStringLiteral( "FORMAT" ) ); if ( mSettings.mImageMimeType.contains( '+' ) ) { QString format( mSettings.mImageMimeType ); - format.replace( '+', "%2b" ); + format.replace( '+', QLatin1String( "%2b" ) ); url.addEncodedQueryItem( "FORMAT", format.toUtf8() ); } else - setQueryItem( url, "FORMAT", mSettings.mImageMimeType ); + setQueryItem( url, QStringLiteral( "FORMAT" ), mSettings.mImageMimeType ); } QImage *QgsWmsProvider::draw( QgsRectangle const &viewExtent, int pixelWidth, int pixelHeight ) @@ -712,7 +712,7 @@ QImage *QgsWmsProvider::draw( QgsRectangle const & viewExtent, int pixelWidth, i QgsDebugMsg( QString( "tile number: %1x%2 = %3" ).arg( col1 - col0 + 1 ).arg( row1 - row0 + 1 ).arg( n ) ); if ( n > 256 ) { - emit statusChanged( QString( "current view would need %1 tiles. tile request per draw limited to 256." ).arg( n ) ); + emit statusChanged( QStringLiteral( "current view would need %1 tiles. tile request per draw limited to 256." ).arg( n ) ); return image; } #endif @@ -928,43 +928,43 @@ QUrl QgsWmsProvider::createRequestUrlWMS( const QgsRectangle& viewExtent, int pi ++it2; } - QString layers = visibleLayers.join( "," ); - layers = layers.isNull() ? "" : layers; - QString styles = visibleStyles.join( "," ); - styles = styles.isNull() ? "" : styles; + QString layers = visibleLayers.join( QStringLiteral( "," ) ); + layers = layers.isNull() ? QLatin1String( "" ) : layers; + QString styles = visibleStyles.join( QStringLiteral( "," ) ); + styles = styles.isNull() ? QLatin1String( "" ) : styles; QgsDebugMsg( "Visible layer list of " + layers + " and style list of " + styles ); QString bbox = toParamValue( viewExtent, changeXY ); QUrl url( mSettings.mIgnoreGetMapUrl ? mSettings.mBaseUrl : getMapUrl() ); - setQueryItem( url, "SERVICE", "WMS" ); - setQueryItem( url, "VERSION", mCaps.mCapabilities.version ); - setQueryItem( url, "REQUEST", "GetMap" ); - setQueryItem( url, "BBOX", bbox ); + setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); + setQueryItem( url, QStringLiteral( "VERSION" ), mCaps.mCapabilities.version ); + setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetMap" ) ); + setQueryItem( url, QStringLiteral( "BBOX" ), bbox ); setSRSQueryItem( url ); - setQueryItem( url, "WIDTH", QString::number( pixelWidth ) ); - setQueryItem( url, "HEIGHT", QString::number( pixelHeight ) ); - setQueryItem( url, "LAYERS", layers ); - setQueryItem( url, "STYLES", styles ); + setQueryItem( url, QStringLiteral( "WIDTH" ), QString::number( pixelWidth ) ); + setQueryItem( url, QStringLiteral( "HEIGHT" ), QString::number( pixelHeight ) ); + setQueryItem( url, QStringLiteral( "LAYERS" ), layers ); + setQueryItem( url, QStringLiteral( "STYLES" ), styles ); setFormatQueryItem( url ); if ( mDpi != -1 ) { if ( mSettings.mDpiMode & dpiQGIS ) - setQueryItem( url, "DPI", QString::number( mDpi ) ); + setQueryItem( url, QStringLiteral( "DPI" ), QString::number( mDpi ) ); if ( mSettings.mDpiMode & dpiUMN ) - setQueryItem( url, "MAP_RESOLUTION", QString::number( mDpi ) ); + setQueryItem( url, QStringLiteral( "MAP_RESOLUTION" ), QString::number( mDpi ) ); if ( mSettings.mDpiMode & dpiGeoServer ) - setQueryItem( url, "FORMAT_OPTIONS", QString( "dpi:%1" ).arg( mDpi ) ); + setQueryItem( url, QStringLiteral( "FORMAT_OPTIONS" ), QStringLiteral( "dpi:%1" ).arg( mDpi ) ); } //MH: jpeg does not support transparency and some servers complain if jpg and transparent=true - if ( mSettings.mImageMimeType == "image/x-jpegorpng" || - ( !mSettings.mImageMimeType.contains( "jpeg", Qt::CaseInsensitive ) && - !mSettings.mImageMimeType.contains( "jpg", Qt::CaseInsensitive ) ) ) + if ( mSettings.mImageMimeType == QLatin1String( "image/x-jpegorpng" ) || + ( !mSettings.mImageMimeType.contains( QLatin1String( "jpeg" ), Qt::CaseInsensitive ) && + !mSettings.mImageMimeType.contains( QLatin1String( "jpg" ), Qt::CaseInsensitive ) ) ) { - setQueryItem( url, "TRANSPARENT", "TRUE" ); // some servers giving error for 'true' (lowercase) + setQueryItem( url, QStringLiteral( "TRANSPARENT" ), QStringLiteral( "TRUE" ) ); // some servers giving error for 'true' (lowercase) } QgsDebugMsg( QString( "getmap: %1" ).arg( url.toString() ) ); @@ -978,37 +978,37 @@ void QgsWmsProvider::createTileRequestsWMSC( const QgsWmtsTileMatrix* tm, const // add WMS request QUrl url( mSettings.mIgnoreGetMapUrl ? mSettings.mBaseUrl : getMapUrl() ); - setQueryItem( url, "SERVICE", "WMS" ); - setQueryItem( url, "VERSION", mCaps.mCapabilities.version ); - setQueryItem( url, "REQUEST", "GetMap" ); - setQueryItem( url, "LAYERS", mSettings.mActiveSubLayers.join( "," ) ); - setQueryItem( url, "STYLES", mSettings.mActiveSubStyles.join( "," ) ); - setQueryItem( url, "WIDTH", QString::number( tm->tileWidth ) ); - setQueryItem( url, "HEIGHT", QString::number( tm->tileHeight ) ); + setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); + setQueryItem( url, QStringLiteral( "VERSION" ), mCaps.mCapabilities.version ); + setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetMap" ) ); + setQueryItem( url, QStringLiteral( "LAYERS" ), mSettings.mActiveSubLayers.join( QStringLiteral( "," ) ) ); + setQueryItem( url, QStringLiteral( "STYLES" ), mSettings.mActiveSubStyles.join( QStringLiteral( "," ) ) ); + setQueryItem( url, QStringLiteral( "WIDTH" ), QString::number( tm->tileWidth ) ); + setQueryItem( url, QStringLiteral( "HEIGHT" ), QString::number( tm->tileHeight ) ); setFormatQueryItem( url ); setSRSQueryItem( url ); if ( mSettings.mTiled ) { - setQueryItem( url, "TILED", "true" ); + setQueryItem( url, QStringLiteral( "TILED" ), QStringLiteral( "true" ) ); } if ( mDpi != -1 ) { if ( mSettings.mDpiMode & dpiQGIS ) - setQueryItem( url, "DPI", QString::number( mDpi ) ); + setQueryItem( url, QStringLiteral( "DPI" ), QString::number( mDpi ) ); if ( mSettings.mDpiMode & dpiUMN ) - setQueryItem( url, "MAP_RESOLUTION", QString::number( mDpi ) ); + setQueryItem( url, QStringLiteral( "MAP_RESOLUTION" ), QString::number( mDpi ) ); if ( mSettings.mDpiMode & dpiGeoServer ) - setQueryItem( url, "FORMAT_OPTIONS", QString( "dpi:%1" ).arg( mDpi ) ); + setQueryItem( url, QStringLiteral( "FORMAT_OPTIONS" ), QStringLiteral( "dpi:%1" ).arg( mDpi ) ); } - if ( mSettings.mImageMimeType == "image/x-jpegorpng" || - ( !mSettings.mImageMimeType.contains( "jpeg", Qt::CaseInsensitive ) && - !mSettings.mImageMimeType.contains( "jpg", Qt::CaseInsensitive ) ) ) + if ( mSettings.mImageMimeType == QLatin1String( "image/x-jpegorpng" ) || + ( !mSettings.mImageMimeType.contains( QLatin1String( "jpeg" ), Qt::CaseInsensitive ) && + !mSettings.mImageMimeType.contains( QLatin1String( "jpg" ), Qt::CaseInsensitive ) ) ) { - setQueryItem( url, "TRANSPARENT", "TRUE" ); // some servers giving error for 'true' (lowercase) + setQueryItem( url, QStringLiteral( "TRANSPARENT" ), QStringLiteral( "TRUE" ) ); // some servers giving error for 'true' (lowercase) } int i = 0; @@ -1038,29 +1038,29 @@ void QgsWmsProvider::createTileRequestsWMTS( const QgsWmtsTileMatrix* tm, const QUrl url( mSettings.mIgnoreGetMapUrl ? mSettings.mBaseUrl : getTileUrl() ); // compose static request arguments. - setQueryItem( url, "SERVICE", "WMTS" ); - setQueryItem( url, "REQUEST", "GetTile" ); - setQueryItem( url, "VERSION", mCaps.mCapabilities.version ); - setQueryItem( url, "LAYER", mSettings.mActiveSubLayers[0] ); - setQueryItem( url, "STYLE", mSettings.mActiveSubStyles[0] ); - setQueryItem( url, "FORMAT", mSettings.mImageMimeType ); - setQueryItem( url, "TILEMATRIXSET", mTileMatrixSet->identifier ); - setQueryItem( url, "TILEMATRIX", tm->identifier ); + setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WMTS" ) ); + setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetTile" ) ); + setQueryItem( url, QStringLiteral( "VERSION" ), mCaps.mCapabilities.version ); + setQueryItem( url, QStringLiteral( "LAYER" ), mSettings.mActiveSubLayers[0] ); + setQueryItem( url, QStringLiteral( "STYLE" ), mSettings.mActiveSubStyles[0] ); + setQueryItem( url, QStringLiteral( "FORMAT" ), mSettings.mImageMimeType ); + setQueryItem( url, QStringLiteral( "TILEMATRIXSET" ), mTileMatrixSet->identifier ); + setQueryItem( url, QStringLiteral( "TILEMATRIX" ), tm->identifier ); for ( QHash<QString, QString>::const_iterator it = mSettings.mTileDimensionValues.constBegin(); it != mSettings.mTileDimensionValues.constEnd(); ++it ) { setQueryItem( url, it.key(), it.value() ); } - url.removeQueryItem( "TILEROW" ); - url.removeQueryItem( "TILECOL" ); + url.removeQueryItem( QStringLiteral( "TILEROW" ) ); + url.removeQueryItem( QStringLiteral( "TILECOL" ) ); int i = 0; Q_FOREACH ( const TilePosition& tile, tiles ) { QString turl; turl += url.toString(); - turl += QString( "&TILEROW=%1&TILECOL=%2" ).arg( tile.row ).arg( tile.col ); + turl += QStringLiteral( "&TILEROW=%1&TILECOL=%2" ).arg( tile.row ).arg( tile.col ); QgsDebugMsg( QString( "tileRequest %1 %2/%3 (%4,%5): %6" ).arg( mTileReqNo ).arg( i ).arg( tiles.count() ).arg( tile.row ).arg( tile.col ).arg( turl ) ); requests << TileRequest( turl, tm->tileRect( tile.col, tile.row ), i ); @@ -1072,10 +1072,10 @@ void QgsWmsProvider::createTileRequestsWMTS( const QgsWmtsTileMatrix* tm, const // REST QString url = mTileLayer->getTileURLs[ mSettings.mImageMimeType ]; - url.replace( "{layer}", mSettings.mActiveSubLayers[0], Qt::CaseInsensitive ); - url.replace( "{style}", mSettings.mActiveSubStyles[0], Qt::CaseInsensitive ); - url.replace( "{tilematrixset}", mTileMatrixSet->identifier, Qt::CaseInsensitive ); - url.replace( "{tilematrix}", tm->identifier, Qt::CaseInsensitive ); + url.replace( QLatin1String( "{layer}" ), mSettings.mActiveSubLayers[0], Qt::CaseInsensitive ); + url.replace( QLatin1String( "{style}" ), mSettings.mActiveSubStyles[0], Qt::CaseInsensitive ); + url.replace( QLatin1String( "{tilematrixset}" ), mTileMatrixSet->identifier, Qt::CaseInsensitive ); + url.replace( QLatin1String( "{tilematrix}" ), tm->identifier, Qt::CaseInsensitive ); for ( QHash<QString, QString>::const_iterator it = mSettings.mTileDimensionValues.constBegin(); it != mSettings.mTileDimensionValues.constEnd(); ++it ) { @@ -1086,8 +1086,8 @@ void QgsWmsProvider::createTileRequestsWMTS( const QgsWmtsTileMatrix* tm, const Q_FOREACH ( const TilePosition& tile, tiles ) { QString turl( url ); - turl.replace( "{tilerow}", QString::number( tile.row ), Qt::CaseInsensitive ); - turl.replace( "{tilecol}", QString::number( tile.col ), Qt::CaseInsensitive ); + turl.replace( QLatin1String( "{tilerow}" ), QString::number( tile.row ), Qt::CaseInsensitive ); + turl.replace( QLatin1String( "{tilecol}" ), QString::number( tile.col ), Qt::CaseInsensitive ); QgsDebugMsgLevel( QString( "tileRequest %1 %2/%3 (%4,%5): %6" ).arg( mTileReqNo ).arg( i ).arg( tiles.count() ).arg( tile.row ).arg( tile.col ).arg( turl ), 2 ); requests << TileRequest( turl, tm->tileRect( tile.col, tile.row ), i ); @@ -1126,12 +1126,12 @@ void QgsWmsProvider::createTileRequestsXYZ( const QgsWmtsTileMatrix* tm, const Q ++i; QString turl( url ); - if ( turl.contains( "{q}" ) ) // used in Bing maps - turl.replace( "{q}", _tile2quadkey( tile.col, tile.row, z ) ); + if ( turl.contains( QLatin1String( "{q}" ) ) ) // used in Bing maps + turl.replace( QLatin1String( "{q}" ), _tile2quadkey( tile.col, tile.row, z ) ); - turl.replace( "{x}", QString::number( tile.col ), Qt::CaseInsensitive ); - turl.replace( "{y}", QString::number( tile.row ), Qt::CaseInsensitive ); - turl.replace( "{z}", QString::number( z ), Qt::CaseInsensitive ); + turl.replace( QLatin1String( "{x}" ), QString::number( tile.col ), Qt::CaseInsensitive ); + turl.replace( QLatin1String( "{y}" ), QString::number( tile.row ), Qt::CaseInsensitive ); + turl.replace( QLatin1String( "{z}" ), QString::number( z ), Qt::CaseInsensitive ); QgsDebugMsgLevel( QString( "tileRequest %1 %2/%3 (%4,%5): %6" ).arg( mTileReqNo ).arg( i ).arg( tiles.count() ).arg( tile.row ).arg( tile.col ).arg( turl ), 2 ); requests << TileRequest( turl, tm->tileRect( tile.col, tile.row ), i ); @@ -1148,7 +1148,7 @@ bool QgsWmsProvider::retrieveServerCapabilities( bool forceRefresh ) QgsWmsCapabilitiesDownload downloadCaps( mSettings.baseUrl(), mSettings.authorization(), forceRefresh ); if ( !downloadCaps.downloadCapabilities() ) { - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = downloadCaps.lastError(); return false; } @@ -1177,7 +1177,7 @@ void QgsWmsProvider::setupXyzCapabilities( const QString &uri ) QgsDataSourceUri parsedUri; parsedUri.setEncodedUri( uri ); - QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( "EPSG:4326" ), QgsCoordinateReferenceSystem( mSettings.mCrsId ) ); + QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ), QgsCoordinateReferenceSystem( mSettings.mCrsId ) ); // the whole world is projected to a square: // X going from 180 W to 180 E // Y going from ~85 N to ~85 S (=atan(sinh(pi)) ... to get a square) @@ -1193,21 +1193,21 @@ void QgsWmsProvider::setupXyzCapabilities( const QString &uri ) QgsWmtsTileLayer tl; tl.tileMode = XYZ; - tl.identifier = "xyz"; // as set in parseUri + tl.identifier = QStringLiteral( "xyz" ); // as set in parseUri tl.boundingBoxes << bbox; mCaps.mTileLayersSupported.append( tl ); QgsWmtsTileMatrixSet tms; - tms.identifier = "tms0"; // as set in parseUri + tms.identifier = QStringLiteral( "tms0" ); // as set in parseUri tms.crs = mSettings.mCrsId; mCaps.mTileMatrixSets[tms.identifier] = tms; int minZoom = 0; int maxZoom = 18; - if ( parsedUri.hasParam( "zmin" ) ) - minZoom = parsedUri.param( "zmin" ).toInt(); - if ( parsedUri.hasParam( "zmax" ) ) - maxZoom = parsedUri.param( "zmax" ).toInt(); + if ( parsedUri.hasParam( QStringLiteral( "zmin" ) ) ) + minZoom = parsedUri.param( QStringLiteral( "zmin" ) ).toInt(); + if ( parsedUri.hasParam( QStringLiteral( "zmax" ) ) ) + maxZoom = parsedUri.param( QStringLiteral( "zmax" ) ).toInt(); // zoom 0 is one tile for the whole world for ( int zoom = minZoom; zoom <= maxZoom; ++zoom ) @@ -1377,10 +1377,10 @@ bool QgsWmsProvider::parseServiceExceptionReportDom( QByteArray const & xml, QSt QgsDebugMsg( e.tagName() ); // the node really is an element. QString tagName = e.tagName(); - if ( tagName.startsWith( "wms:" ) ) + if ( tagName.startsWith( QLatin1String( "wms:" ) ) ) tagName = tagName.mid( 4 ); - if ( tagName == "ServiceException" ) + if ( tagName == QLatin1String( "ServiceException" ) ) { QgsDebugMsg( " ServiceException." ); parseServiceException( e, errorTitle, errorText ); @@ -1399,61 +1399,61 @@ bool QgsWmsProvider::parseServiceExceptionReportDom( QByteArray const & xml, QSt void QgsWmsProvider::parseServiceException( QDomElement const & e, QString& errorTitle, QString& errorText ) { - QString seCode = e.attribute( "code" ); + QString seCode = e.attribute( QStringLiteral( "code" ) ); QString seText = e.text(); errorTitle = tr( "Service Exception" ); // set up friendly descriptions for the service exception - if ( seCode == "InvalidFormat" ) + if ( seCode == QLatin1String( "InvalidFormat" ) ) { errorText = tr( "Request contains a format not offered by the server." ); } - else if ( seCode == "InvalidCRS" ) + else if ( seCode == QLatin1String( "InvalidCRS" ) ) { errorText = tr( "Request contains a CRS not offered by the server for one or more of the Layers in the request." ); } - else if ( seCode == "InvalidSRS" ) // legacy WMS < 1.3.0 + else if ( seCode == QLatin1String( "InvalidSRS" ) ) // legacy WMS < 1.3.0 { errorText = tr( "Request contains a SRS not offered by the server for one or more of the Layers in the request." ); } - else if ( seCode == "LayerNotDefined" ) + else if ( seCode == QLatin1String( "LayerNotDefined" ) ) { errorText = tr( "GetMap request is for a Layer not offered by the server, " "or GetFeatureInfo request is for a Layer not shown on the map." ); } - else if ( seCode == "StyleNotDefined" ) + else if ( seCode == QLatin1String( "StyleNotDefined" ) ) { errorText = tr( "Request is for a Layer in a Style not offered by the server." ); } - else if ( seCode == "LayerNotQueryable" ) + else if ( seCode == QLatin1String( "LayerNotQueryable" ) ) { errorText = tr( "GetFeatureInfo request is applied to a Layer which is not declared queryable." ); } - else if ( seCode == "InvalidPoint" ) + else if ( seCode == QLatin1String( "InvalidPoint" ) ) { errorText = tr( "GetFeatureInfo request contains invalid X or Y value." ); } - else if ( seCode == "CurrentUpdateSequence" ) + else if ( seCode == QLatin1String( "CurrentUpdateSequence" ) ) { errorText = tr( "Value of (optional) UpdateSequence parameter in GetCapabilities request is equal to " "current value of service metadata update sequence number." ); } - else if ( seCode == "InvalidUpdateSequence" ) + else if ( seCode == QLatin1String( "InvalidUpdateSequence" ) ) { errorText = tr( "Value of (optional) UpdateSequence parameter in GetCapabilities request is greater " "than current value of service metadata update sequence number." ); } - else if ( seCode == "MissingDimensionValue" ) + else if ( seCode == QLatin1String( "MissingDimensionValue" ) ) { errorText = tr( "Request does not include a sample dimension value, and the server did not declare a " "default value for that dimension." ); } - else if ( seCode == "InvalidDimensionValue" ) + else if ( seCode == QLatin1String( "InvalidDimensionValue" ) ) { errorText = tr( "Request contains an invalid sample dimension value." ); } - else if ( seCode == "OperationNotSupported" ) + else if ( seCode == QLatin1String( "OperationNotSupported" ) ) { errorText = tr( "Request is for an optional operation that is not supported by the server." ); } @@ -1660,116 +1660,116 @@ QString QgsWmsProvider::layerMetadata( QgsWmsLayerProperty &layer ) // Layer Properties section // Use a nested table - metadata += "<tr><td>"; - metadata += "<table width=\"100%\">"; + metadata += QLatin1String( "<tr><td>" ); + metadata += QLatin1String( "<table width=\"100%\">" ); // Table header - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Property" ); - metadata += "</th>"; - metadata += "<th class=\"glossy\">"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<th class=\"glossy\">" ); metadata += tr( "Value" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); // Name - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Name" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.name; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Visibility (as managed by this provider) - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Visibility" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mActiveSubLayerVisibility.find( layer.name ).value() ? tr( "Visible" ) : tr( "Hidden" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Title - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Title" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.title; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Abstract - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Abstract" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.abstract; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Queryability - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Can Identify" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.queryable ? tr( "Yes" ) : tr( "No" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Opacity - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Can be Transparent" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.opaque ? tr( "No" ) : tr( "Yes" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Subsetability - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Can Zoom In" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.noSubsets ? tr( "No" ) : tr( "Yes" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Server Cascade Count - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Cascade Count" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += QString::number( layer.cascaded ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Fixed Width - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Fixed Width" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += QString::number( layer.fixedWidth ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Fixed Height - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Fixed Height" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += QString::number( layer.fixedHeight ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Coordinate Reference Systems for ( int j = 0; j < qMin( layer.crs.size(), 10 ); j++ ) { - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Available in CRS" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += layer.crs[j]; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); } if ( layer.crs.size() > 10 ) { - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Available in CRS" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += tr( "(and %n more)", "crs", layer.crs.size() - 10 ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); } // Layer Styles @@ -1777,295 +1777,295 @@ QString QgsWmsProvider::layerMetadata( QgsWmsLayerProperty &layer ) { const QgsWmsStyleProperty &style = layer.style.at( j ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Available in style" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); // Nested table. - metadata += "<table width=\"100%\">"; + metadata += QLatin1String( "<table width=\"100%\">" ); // Layer Style Name - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Name" ); - metadata += "</th>"; - metadata += "<td>"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<td>" ); metadata += style.name; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Style Title - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Title" ); - metadata += "</th>"; - metadata += "<td>"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<td>" ); metadata += style.title; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Layer Style Abstract - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Abstract" ); - metadata += "</th>"; - metadata += "<td>"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<td>" ); metadata += style.abstract; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // LegendURLs if ( !style.legendUrl.isEmpty() ) { - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "LegendURLs" ); - metadata += "</th>"; - metadata += "<td><table>"; - metadata += "<tr><th>Format</th><th>URL</th></tr>"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<td><table>" ); + metadata += QLatin1String( "<tr><th>Format</th><th>URL</th></tr>" ); for ( int k = 0; k < style.legendUrl.size(); k++ ) { const QgsWmsLegendUrlProperty &l = style.legendUrl[k]; metadata += "<tr><td>" + l.format + "</td><td>" + l.onlineResource.xlinkHref + "</td></tr>"; } - metadata += "</table></td></tr>"; + metadata += QLatin1String( "</table></td></tr>" ); } // Close the nested table - metadata += "</table>"; - metadata += "</td></tr>"; + metadata += QLatin1String( "</table>" ); + metadata += QLatin1String( "</td></tr>" ); } // Close the nested table - metadata += "</table>"; - metadata += "</td></tr>"; + metadata += QLatin1String( "</table>" ); + metadata += QLatin1String( "</td></tr>" ); return metadata; } QString QgsWmsProvider::metadata() { - QString metadata = ""; + QString metadata = QLatin1String( "" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); if ( !mSettings.mTiled ) { - metadata += " <a href=\"#selectedlayers\">"; + metadata += QLatin1String( " <a href=\"#selectedlayers\">" ); metadata += tr( "Selected Layers" ); - metadata += "</a> <a href=\"#otherlayers\">"; + metadata += QLatin1String( "</a> <a href=\"#otherlayers\">" ); metadata += tr( "Other Layers" ); - metadata += "</a>"; + metadata += QLatin1String( "</a>" ); } else { - metadata += " <a href=\"#tilesetproperties\">"; + metadata += QLatin1String( " <a href=\"#tilesetproperties\">" ); metadata += tr( "Tile Layer Properties" ); - metadata += "</a> "; + metadata += QLatin1String( "</a> " ); - metadata += " <a href=\"#cachestats\">"; + metadata += QLatin1String( " <a href=\"#cachestats\">" ); metadata += tr( "Cache Stats" ); - metadata += "</a> "; + metadata += QLatin1String( "</a> " ); } - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Server Properties section - metadata += "<tr><th class=\"glossy\"><a name=\"serverproperties\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"serverproperties\"></a>" ); metadata += tr( "Server Properties" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); // Use a nested table - metadata += "<tr><td>"; - metadata += "<table width=\"100%\">"; + metadata += QLatin1String( "<tr><td>" ); + metadata += QLatin1String( "<table width=\"100%\">" ); // Table header - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Property" ); - metadata += "</th>"; - metadata += "<th class=\"glossy\">"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<th class=\"glossy\">" ); metadata += tr( "Value" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); // WMS Version - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "WMS Version" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mCaps.mCapabilities.version; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Service Title - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Title" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mCaps.mCapabilities.service.title; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Service Abstract - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Abstract" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mCaps.mCapabilities.service.abstract; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Service Keywords - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Keywords" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += mCaps.mCapabilities.service.keywordList.join( "<br />" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += mCaps.mCapabilities.service.keywordList.join( QStringLiteral( "<br />" ) ); + metadata += QLatin1String( "</td></tr>" ); // Service Online Resource - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Online Resource" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += '-'; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Service Contact Information - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Contact Person" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mCaps.mCapabilities.service.contactInformation.contactPersonPrimary.contactPerson; - metadata += "<br />"; + metadata += QLatin1String( "<br />" ); metadata += mCaps.mCapabilities.service.contactInformation.contactPosition; - metadata += "<br />"; + metadata += QLatin1String( "<br />" ); metadata += mCaps.mCapabilities.service.contactInformation.contactPersonPrimary.contactOrganization; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Service Fees - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Fees" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mCaps.mCapabilities.service.fees; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Service Access Constraints - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Access Constraints" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mCaps.mCapabilities.service.accessConstraints; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Base URL - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "GetCapabilitiesUrl" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += mSettings.mBaseUrl; - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "GetMapUrl" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += getMapUrl() + ( mSettings.mIgnoreGetMapUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : "" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += getMapUrl() + ( mSettings.mIgnoreGetMapUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : QLatin1String( "" ) ); + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "GetFeatureInfoUrl" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += getFeatureInfoUrl() + ( mSettings.mIgnoreGetFeatureInfoUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : "" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += getFeatureInfoUrl() + ( mSettings.mIgnoreGetFeatureInfoUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : QLatin1String( "" ) ); + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "GetLegendGraphic" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += getLegendGraphicUrl() + ( mSettings.mIgnoreGetMapUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : "" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += getLegendGraphicUrl() + ( mSettings.mIgnoreGetMapUrl ? tr( " <font color=\"red\">(advertised but ignored)</font>" ) : QLatin1String( "" ) ); + metadata += QLatin1String( "</td></tr>" ); if ( mSettings.mTiled ) { - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Tile Layer Count" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += QString::number( mCaps.mTileLayersSupported.size() ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "GetTileUrl" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += getTileUrl(); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); if ( mTileLayer ) { - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Tile templates" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); for ( QHash<QString, QString>::const_iterator it = mTileLayer->getTileURLs.constBegin(); it != mTileLayer->getTileURLs.constEnd(); ++it ) { - metadata += QString( "%1:%2<br>" ).arg( it.key(), it.value() ); + metadata += QStringLiteral( "%1:%2<br>" ).arg( it.key(), it.value() ); } - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "FeatureInfo templates" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); for ( QHash<QString, QString>::const_iterator it = mTileLayer->getFeatureInfoURLs.constBegin(); it != mTileLayer->getFeatureInfoURLs.constEnd(); ++it ) { - metadata += QString( "%1:%2<br>" ).arg( it.key(), it.value() ); + metadata += QStringLiteral( "%1:%2<br>" ).arg( it.key(), it.value() ); } - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); } // GetFeatureInfo Request Formats - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Identify Formats" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += mTileLayer->infoFormats.join( "<br />" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += mTileLayer->infoFormats.join( QStringLiteral( "<br />" ) ); + metadata += QLatin1String( "</td></tr>" ); } else { // GetMap Request Formats - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Image Formats" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += mCaps.mCapabilities.capability.request.getMap.format.join( "<br />" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += mCaps.mCapabilities.capability.request.getMap.format.join( QStringLiteral( "<br />" ) ); + metadata += QLatin1String( "</td></tr>" ); // GetFeatureInfo Request Formats - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Identify Formats" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += mCaps.mCapabilities.capability.request.getFeatureInfo.format.join( "<br />" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += mCaps.mCapabilities.capability.request.getFeatureInfo.format.join( QStringLiteral( "<br />" ) ); + metadata += QLatin1String( "</td></tr>" ); // Layer Count (as managed by this provider) - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Layer Count" ); - metadata += "</td>"; - metadata += "<td>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); metadata += QString::number( mCaps.mLayersSupported.size() ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); } // Close the nested table - metadata += "</table>"; - metadata += "</td></tr>"; + metadata += QLatin1String( "</table>" ); + metadata += QLatin1String( "</td></tr>" ); // Layer properties if ( !mSettings.mTiled ) { - metadata += "<tr><th class=\"glossy\"><a name=\"selectedlayers\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"selectedlayers\"></a>" ); metadata += tr( "Selected Layers" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); int n = 0; for ( int i = 0; i < mCaps.mLayersSupported.size(); i++ ) @@ -2080,9 +2080,9 @@ QString QgsWmsProvider::metadata() // Layer properties if ( n < mCaps.mLayersSupported.size() ) { - metadata += "<tr><th class=\"glossy\"><a name=\"otherlayers\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"otherlayers\"></a>" ); metadata += tr( "Other Layers" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); for ( int i = 0; i < mCaps.mLayersSupported.size(); i++ ) { @@ -2096,26 +2096,26 @@ QString QgsWmsProvider::metadata() else { // Tileset properties - metadata += "<tr><th class=\"glossy\"><a name=\"tilesetproperties\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"tilesetproperties\"></a>" ); metadata += tr( "Tileset Properties" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); // Iterate through tilesets - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); - metadata += "<table width=\"100%\">"; + metadata += QLatin1String( "<table width=\"100%\">" ); Q_FOREACH ( const QgsWmtsTileLayer &l, mCaps.mTileLayersSupported ) { - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Identifier" ); - metadata += "</th><th class=\"glossy\">"; + metadata += QLatin1String( "</th><th class=\"glossy\">" ); metadata += tr( "Tile mode" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += l.identifier; - metadata += "</td><td class=\"glossy\">"; + metadata += QLatin1String( "</td><td class=\"glossy\">" ); if ( l.tileMode == WMTS ) { @@ -2134,77 +2134,77 @@ QString QgsWmsProvider::metadata() metadata += tr( "Invalid tile mode" ); } - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); // Table header - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Property" ); - metadata += "</th>"; - metadata += "<th class=\"glossy\">"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<th class=\"glossy\">" ); metadata += tr( "Value" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); - metadata += "<tr><td class=\"glossy\">"; + metadata += QLatin1String( "<tr><td class=\"glossy\">" ); metadata += tr( "Selected" ); - metadata += "</td>"; - metadata += "<td class=\"glossy\">"; - metadata += l.identifier == mSettings.mActiveSubLayers.join( "," ) ? tr( "Yes" ) : tr( "No" ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td class=\"glossy\">" ); + metadata += l.identifier == mSettings.mActiveSubLayers.join( QStringLiteral( "," ) ) ? tr( "Yes" ) : tr( "No" ); + metadata += QLatin1String( "</td></tr>" ); if ( !l.styles.isEmpty() ) { - metadata += "<tr><td class=\"glossy\">"; + metadata += QLatin1String( "<tr><td class=\"glossy\">" ); metadata += tr( "Available Styles" ); - metadata += "</td>"; - metadata += "<td class=\"glossy\">"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td class=\"glossy\">" ); QStringList styles; Q_FOREACH ( const QgsWmtsStyle &style, l.styles ) { styles << style.identifier; } - metadata += styles.join( ", " ); - metadata += "</td></tr>"; + metadata += styles.join( QStringLiteral( ", " ) ); + metadata += QLatin1String( "</td></tr>" ); } - metadata += "<tr><td class=\"glossy\">"; + metadata += QLatin1String( "<tr><td class=\"glossy\">" ); metadata += tr( "CRS" ); - metadata += "</td>"; - metadata += "<td>"; - metadata += "<table><tr>"; - metadata += "<td class=\"glossy\">"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td>" ); + metadata += QLatin1String( "<table><tr>" ); + metadata += QLatin1String( "<td class=\"glossy\">" ); metadata += tr( "CRS" ); - metadata += "</td>"; - metadata += "<td class=\"glossy\">"; + metadata += QLatin1String( "</td>" ); + metadata += QLatin1String( "<td class=\"glossy\">" ); metadata += tr( "Bounding Box" ); - metadata += "</td>"; + metadata += QLatin1String( "</td>" ); for ( int i = 0; i < l.boundingBoxes.size(); i++ ) { - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += l.boundingBoxes[i].crs; - metadata += "</td><td>"; + metadata += QLatin1String( "</td><td>" ); metadata += l.boundingBoxes[i].box.toString(); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); } - metadata += "</table></td></tr>"; + metadata += QLatin1String( "</table></td></tr>" ); - metadata += "<tr><td class=\"glossy\">"; + metadata += QLatin1String( "<tr><td class=\"glossy\">" ); metadata += tr( "Available Tilesets" ); - metadata += "</td><td class=\"glossy\">"; + metadata += QLatin1String( "</td><td class=\"glossy\">" ); Q_FOREACH ( const QgsWmtsTileMatrixSetLink &setLink, l.setLinks ) { metadata += setLink.tileMatrixSet + "<br>"; } - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); } - metadata += "</table></td></tr>"; + metadata += QLatin1String( "</table></td></tr>" ); if ( mTileMatrixSet ) { // Iterate through tilesets - metadata += "<tr><td><table width=\"100%\">"; + metadata += QLatin1String( "<tr><td><table width=\"100%\">" ); metadata += QString( "<tr><th colspan=14 class=\"glossy\">%1 %2</th></tr>" "<tr>" @@ -2266,98 +2266,98 @@ QString QgsWmsProvider::metadata() // top if ( mLayerExtent.yMaximum() > r.yMaximum() ) { - metadata += QString( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) + metadata += QStringLiteral( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) .arg( tr( "%n missing row(s)", nullptr, ( int ) ceil(( mLayerExtent.yMaximum() - r.yMaximum() ) / th ) ), tr( "Layer's upper bound: %1" ).arg( mLayerExtent.yMaximum(), 0, 'f' ) ) .arg( r.yMaximum(), 0, 'f' ); } else { - metadata += QString( "<td>%1</td>" ).arg( r.yMaximum(), 0, 'f' ); + metadata += QStringLiteral( "<td>%1</td>" ).arg( r.yMaximum(), 0, 'f' ); } // left if ( mLayerExtent.xMinimum() < r.xMinimum() ) { - metadata += QString( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) + metadata += QStringLiteral( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) .arg( tr( "%n missing column(s)", nullptr, ( int ) ceil(( r.xMinimum() - mLayerExtent.xMinimum() ) / tw ) ), tr( "Layer's left bound: %1" ).arg( mLayerExtent.xMinimum(), 0, 'f' ) ) .arg( r.xMinimum(), 0, 'f' ); } else { - metadata += QString( "<td>%1</td>" ).arg( r.xMinimum(), 0, 'f' ); + metadata += QStringLiteral( "<td>%1</td>" ).arg( r.xMinimum(), 0, 'f' ); } // bottom if ( mLayerExtent.yMaximum() > r.yMaximum() ) { - metadata += QString( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) + metadata += QStringLiteral( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) .arg( tr( "%n missing row(s)", nullptr, ( int ) ceil(( mLayerExtent.yMaximum() - r.yMaximum() ) / th ) ), tr( "Layer's lower bound: %1" ).arg( mLayerExtent.yMaximum(), 0, 'f' ) ) .arg( r.yMaximum(), 0, 'f' ); } else { - metadata += QString( "<td>%1</td>" ).arg( r.yMaximum(), 0, 'f' ); + metadata += QStringLiteral( "<td>%1</td>" ).arg( r.yMaximum(), 0, 'f' ); } // right if ( mLayerExtent.xMaximum() > r.xMaximum() ) { - metadata += QString( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) + metadata += QStringLiteral( "<td title=\"%1<br>%2\"><font color=\"red\">%3</font></td>" ) .arg( tr( "%n missing column(s)", nullptr, ( int ) ceil(( mLayerExtent.xMaximum() - r.xMaximum() ) / tw ) ), tr( "Layer's right bound: %1" ).arg( mLayerExtent.xMaximum(), 0, 'f' ) ) .arg( r.xMaximum(), 0, 'f' ); } else { - metadata += QString( "<td>%1</td>" ).arg( r.xMaximum(), 0, 'f' ); + metadata += QStringLiteral( "<td>%1</td>" ).arg( r.xMaximum(), 0, 'f' ); } - metadata += "</tr>"; + metadata += QLatin1String( "</tr>" ); } - metadata += "</table></td></tr>"; + metadata += QLatin1String( "</table></td></tr>" ); } const QgsWmsStatistics::Stat& stat = QgsWmsStatistics::statForUri( dataSourceUri() ); - metadata += "<tr><th class=\"glossy\"><a name=\"cachestats\"></a>"; + metadata += QLatin1String( "<tr><th class=\"glossy\"><a name=\"cachestats\"></a>" ); metadata += tr( "Cache stats" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); - metadata += "<tr><td><table width=\"100%\">"; + metadata += QLatin1String( "<tr><td><table width=\"100%\">" ); - metadata += "<tr><th class=\"glossy\">"; + metadata += QLatin1String( "<tr><th class=\"glossy\">" ); metadata += tr( "Property" ); - metadata += "</th>"; - metadata += "<th class=\"glossy\">"; + metadata += QLatin1String( "</th>" ); + metadata += QLatin1String( "<th class=\"glossy\">" ); metadata += tr( "Value" ); - metadata += "</th></tr>"; + metadata += QLatin1String( "</th></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Hits" ); - metadata += "</td><td>"; + metadata += QLatin1String( "</td><td>" ); metadata += QString::number( stat.cacheHits ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Misses" ); - metadata += "</td><td>"; + metadata += QLatin1String( "</td><td>" ); metadata += QString::number( stat.cacheMisses ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); - metadata += "<tr><td>"; + metadata += QLatin1String( "<tr><td>" ); metadata += tr( "Errors" ); - metadata += "</td><td>"; + metadata += QLatin1String( "</td><td>" ); metadata += QString::number( stat.errors ); - metadata += "</td></tr>"; + metadata += QLatin1String( "</td></tr>" ); - metadata += "</table></td></tr>"; + metadata += QLatin1String( "</table></td></tr>" ); } - metadata += "</table>"; + metadata += QLatin1String( "</table>" ); QgsDebugMsg( "exiting with '" + metadata + "'." ); @@ -2475,10 +2475,10 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs bool changeXY = mCaps.shouldInvertAxisOrientation( mImageCrs ); // compose the URL query string for the WMS server. - QString crsKey = "SRS"; //SRS in 1.1.1 and CRS in 1.3.0 - if ( mCaps.mCapabilities.version == "1.3.0" || mCaps.mCapabilities.version == "1.3" ) + QString crsKey = QStringLiteral( "SRS" ); //SRS in 1.1.1 and CRS in 1.3.0 + if ( mCaps.mCapabilities.version == QLatin1String( "1.3.0" ) || mCaps.mCapabilities.version == QLatin1String( "1.3" ) ) { - crsKey = "CRS"; + crsKey = QStringLiteral( "CRS" ); } // Compose request to WMS server @@ -2522,33 +2522,33 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QgsDebugMsg( "Layer '" + *layers + "' is queryable." ); QUrl requestUrl( mSettings.mIgnoreGetFeatureInfoUrl ? mSettings.mBaseUrl : getFeatureInfoUrl() ); - setQueryItem( requestUrl, "SERVICE", "WMS" ); - setQueryItem( requestUrl, "VERSION", mCaps.mCapabilities.version ); - setQueryItem( requestUrl, "REQUEST", "GetFeatureInfo" ); - setQueryItem( requestUrl, "BBOX", bbox ); + setQueryItem( requestUrl, QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); + setQueryItem( requestUrl, QStringLiteral( "VERSION" ), mCaps.mCapabilities.version ); + setQueryItem( requestUrl, QStringLiteral( "REQUEST" ), QStringLiteral( "GetFeatureInfo" ) ); + setQueryItem( requestUrl, QStringLiteral( "BBOX" ), bbox ); setSRSQueryItem( requestUrl ); - setQueryItem( requestUrl, "WIDTH", QString::number( theWidth ) ); - setQueryItem( requestUrl, "HEIGHT", QString::number( theHeight ) ); - setQueryItem( requestUrl, "LAYERS", *layers ); - setQueryItem( requestUrl, "STYLES", *styles ); + setQueryItem( requestUrl, QStringLiteral( "WIDTH" ), QString::number( theWidth ) ); + setQueryItem( requestUrl, QStringLiteral( "HEIGHT" ), QString::number( theHeight ) ); + setQueryItem( requestUrl, QStringLiteral( "LAYERS" ), *layers ); + setQueryItem( requestUrl, QStringLiteral( "STYLES" ), *styles ); setFormatQueryItem( requestUrl ); - setQueryItem( requestUrl, "QUERY_LAYERS", *layers ); - setQueryItem( requestUrl, "INFO_FORMAT", format ); + setQueryItem( requestUrl, QStringLiteral( "QUERY_LAYERS" ), *layers ); + setQueryItem( requestUrl, QStringLiteral( "INFO_FORMAT" ), format ); - if ( mCaps.mCapabilities.version == "1.3.0" || mCaps.mCapabilities.version == "1.3" ) + if ( mCaps.mCapabilities.version == QLatin1String( "1.3.0" ) || mCaps.mCapabilities.version == QLatin1String( "1.3" ) ) { - setQueryItem( requestUrl, "I", QString::number( point.x() ) ); - setQueryItem( requestUrl, "J", QString::number( point.y() ) ); + setQueryItem( requestUrl, QStringLiteral( "I" ), QString::number( point.x() ) ); + setQueryItem( requestUrl, QStringLiteral( "J" ), QString::number( point.y() ) ); } else { - setQueryItem( requestUrl, "X", QString::number( point.x() ) ); - setQueryItem( requestUrl, "Y", QString::number( point.y() ) ); + setQueryItem( requestUrl, QStringLiteral( "X" ), QString::number( point.x() ) ); + setQueryItem( requestUrl, QStringLiteral( "Y" ), QString::number( point.y() ) ); } if ( mSettings.mFeatureCount > 0 ) { - setQueryItem( requestUrl, "FEATURE_COUNT", QString::number( mSettings.mFeatureCount ) ); + setQueryItem( requestUrl, QStringLiteral( "FEATURE_COUNT" ), QString::number( mSettings.mFeatureCount ) ); } layerList << *layers; @@ -2628,14 +2628,14 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs // REST QString url = mTileLayer->getFeatureInfoURLs[ format ]; - url.replace( "{layer}", mSettings.mActiveSubLayers[0], Qt::CaseInsensitive ); - url.replace( "{style}", mSettings.mActiveSubStyles[0], Qt::CaseInsensitive ); - url.replace( "{tilematrixset}", mTileMatrixSet->identifier, Qt::CaseInsensitive ); - url.replace( "{tilematrix}", tm->identifier, Qt::CaseInsensitive ); - url.replace( "{tilerow}", QString::number( row ), Qt::CaseInsensitive ); - url.replace( "{tilecol}", QString::number( col ), Qt::CaseInsensitive ); - url.replace( "{i}", QString::number( i ), Qt::CaseInsensitive ); - url.replace( "{j}", QString::number( j ), Qt::CaseInsensitive ); + url.replace( QLatin1String( "{layer}" ), mSettings.mActiveSubLayers[0], Qt::CaseInsensitive ); + url.replace( QLatin1String( "{style}" ), mSettings.mActiveSubStyles[0], Qt::CaseInsensitive ); + url.replace( QLatin1String( "{tilematrixset}" ), mTileMatrixSet->identifier, Qt::CaseInsensitive ); + url.replace( QLatin1String( "{tilematrix}" ), tm->identifier, Qt::CaseInsensitive ); + url.replace( QLatin1String( "{tilerow}" ), QString::number( row ), Qt::CaseInsensitive ); + url.replace( QLatin1String( "{tilecol}" ), QString::number( col ), Qt::CaseInsensitive ); + url.replace( QLatin1String( "{i}" ), QString::number( i ), Qt::CaseInsensitive ); + url.replace( QLatin1String( "{j}" ), QString::number( j ), Qt::CaseInsensitive ); for ( QHash<QString, QString>::const_iterator it = mSettings.mTileDimensionValues.constBegin(); it != mSettings.mTileDimensionValues.constEnd(); ++it ) { @@ -2651,24 +2651,24 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QUrl url( mSettings.mIgnoreGetFeatureInfoUrl ? mSettings.mBaseUrl : getFeatureInfoUrl() ); // compose static request arguments. - setQueryItem( url, "SERVICE", "WMTS" ); - setQueryItem( url, "REQUEST", "GetFeatureInfo" ); - setQueryItem( url, "VERSION", mCaps.mCapabilities.version ); - setQueryItem( url, "LAYER", mSettings.mActiveSubLayers[0] ); - setQueryItem( url, "STYLE", mSettings.mActiveSubStyles[0] ); - setQueryItem( url, "INFOFORMAT", format ); - setQueryItem( url, "TILEMATRIXSET", mTileMatrixSet->identifier ); - setQueryItem( url, "TILEMATRIX", tm->identifier ); + setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WMTS" ) ); + setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetFeatureInfo" ) ); + setQueryItem( url, QStringLiteral( "VERSION" ), mCaps.mCapabilities.version ); + setQueryItem( url, QStringLiteral( "LAYER" ), mSettings.mActiveSubLayers[0] ); + setQueryItem( url, QStringLiteral( "STYLE" ), mSettings.mActiveSubStyles[0] ); + setQueryItem( url, QStringLiteral( "INFOFORMAT" ), format ); + setQueryItem( url, QStringLiteral( "TILEMATRIXSET" ), mTileMatrixSet->identifier ); + setQueryItem( url, QStringLiteral( "TILEMATRIX" ), tm->identifier ); for ( QHash<QString, QString>::const_iterator it = mSettings.mTileDimensionValues.constBegin(); it != mSettings.mTileDimensionValues.constEnd(); ++it ) { setQueryItem( url, it.key(), it.value() ); } - setQueryItem( url, "TILEROW", QString::number( row ) ); - setQueryItem( url, "TILECOL", QString::number( col ) ); - setQueryItem( url, "I", qgsDoubleToString( i ) ); - setQueryItem( url, "J", qgsDoubleToString( j ) ); + setQueryItem( url, QStringLiteral( "TILEROW" ), QString::number( row ) ); + setQueryItem( url, QStringLiteral( "TILECOL" ), QString::number( col ) ); + setQueryItem( url, QStringLiteral( "I" ), qgsDoubleToString( i ) ); + setQueryItem( url, QStringLiteral( "J" ), qgsDoubleToString( j ) ); urls << url; layerList << mSettings.mActiveSubLayers[0]; @@ -2707,10 +2707,10 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs const QgsNetworkReplyParser::RawHeaderMap &headers = mIdentifyResultHeaders.value( 0 ); Q_FOREACH ( const QByteArray &v, headers.keys() ) { - if ( QString( v ).compare( "Content-Type", Qt::CaseInsensitive ) == 0 ) + if ( QString( v ).compare( QLatin1String( "Content-Type" ), Qt::CaseInsensitive ) == 0 ) { - isXml = QString( headers.value( v ) ).compare( "text/xml", Qt::CaseInsensitive ) == 0; - isGml = QString( headers.value( v ) ).compare( "ogr/gml", Qt::CaseInsensitive ) == 0; + isXml = QString( headers.value( v ) ).compare( QLatin1String( "text/xml" ), Qt::CaseInsensitive ) == 0; + isGml = QString( headers.value( v ) ).compare( QLatin1String( "ogr/gml" ), Qt::CaseInsensitive ) == 0; if ( isXml || isGml ) break; } @@ -2921,9 +2921,9 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs } QgsFeatureStore featureStore( fields, crs() ); QMap<QString, QVariant> params; - params.insert( "sublayer", layerList[count] ); - params.insert( "featureType", featureTypeName ); - params.insert( "getFeatureInfoUrl", requestUrl.toString() ); + params.insert( QStringLiteral( "sublayer" ), layerList[count] ); + params.insert( QStringLiteral( "featureType" ), featureTypeName ); + params.insert( QStringLiteral( "getFeatureInfoUrl" ), requestUrl.toString() ); featureStore.setParams( params ); Q_FOREACH ( QgsFeatureId id, features.keys() ) { @@ -2947,7 +2947,7 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs if ( xsdPart < 0 && !featureTypeNames.isEmpty() && featureStoreList.isEmpty() ) { QgsError err = QGS_ERROR( tr( "Cannot identify" ) ); - err.append( tr( "Result parsing failed. %1 feature types were guessed from gml (%2) but no features were parsed." ).arg( featureTypeNames.size() ).arg( featureTypeNames.join( "," ) ) ); + err.append( tr( "Result parsing failed. %1 feature types were guessed from gml (%2) but no features were parsed." ).arg( featureTypeNames.size() ).arg( featureTypeNames.join( QStringLiteral( "," ) ) ) ); QgsDebugMsg( "parsing GML error: " + err.message() ); return QgsRasterIdentifyResult( err ); } @@ -2959,8 +2959,8 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs json.prepend( '(' ).append( ')' ); QScriptEngine engine; - engine.evaluate( "function json_stringify(obj) { return JSON.stringify(obj); }" ); - QScriptValue json_stringify = engine.globalObject().property( "json_stringify" ); + engine.evaluate( QStringLiteral( "function json_stringify(obj) { return JSON.stringify(obj); }" ) ); + QScriptValue json_stringify = engine.globalObject().property( QStringLiteral( "json_stringify" ) ); Q_ASSERT( json_stringify.isFunction() ); QScriptValue result = engine.evaluate( json ); @@ -2973,19 +2973,19 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QgsDebugMsg( QString( "result:%1" ).arg( result.toString() ) ); if ( !result.isObject() ) - throw QString( "object expected" ); + throw QStringLiteral( "object expected" ); - if ( result.property( "type" ).toString() != "FeatureCollection" ) - throw QString( "type FeatureCollection expected: %1" ).arg( result.property( "type" ).toString() ); + if ( result.property( QStringLiteral( "type" ) ).toString() != QLatin1String( "FeatureCollection" ) ) + throw QStringLiteral( "type FeatureCollection expected: %1" ).arg( result.property( QStringLiteral( "type" ) ).toString() ); - if ( result.property( "crs" ).isValid() ) + if ( result.property( QStringLiteral( "crs" ) ).isValid() ) { - QString crsType = result.property( "crs" ).property( "type" ).toString(); + QString crsType = result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "type" ) ).toString(); QString crsText; - if ( crsType == "name" ) - crsText = result.property( "crs" ).property( "name" ).toString(); - else if ( crsType == "EPSG" ) - crsText = QString( "%1:%2" ).arg( crsType, result.property( "crs" ).property( "properties" ).property( "code" ).toString() ); + if ( crsType == QLatin1String( "name" ) ) + crsText = result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "name" ) ).toString(); + else if ( crsType == QLatin1String( "EPSG" ) ) + crsText = QStringLiteral( "%1:%2" ).arg( crsType, result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "properties" ) ).property( QStringLiteral( "code" ) ).toString() ); else { QgsDebugMsg( QString( "crs not supported:%1" ).arg( result.property( "crs" ).toString() ) ); @@ -2994,7 +2994,7 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QgsCoordinateReferenceSystem featuresCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crsText ); if ( !featuresCrs.isValid() ) - throw QString( "CRS %1 invalid" ).arg( crsText ); + throw QStringLiteral( "CRS %1 invalid" ).arg( crsText ); if ( featuresCrs.isValid() && featuresCrs != crs() ) { @@ -3002,16 +3002,16 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs } } - QScriptValue fc = result.property( "features" ); + QScriptValue fc = result.property( QStringLiteral( "features" ) ); if ( !fc.isArray() ) - throw QString( "FeatureCollection array expected" ); + throw QStringLiteral( "FeatureCollection array expected" ); QScriptValue f; for ( int i = 0; f = fc.property( i ), f.isValid(); i++ ) { QgsDebugMsg( QString( "feature %1" ).arg( i ) ); - QScriptValue props = f.property( "properties" ); + QScriptValue props = f.property( QStringLiteral( "properties" ) ); if ( !props.isObject() ) { QgsDebugMsg( "no properties found" ); @@ -3028,9 +3028,9 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QgsFeature feature( fields ); - if ( f.property( "geometry" ).isValid() ) + if ( f.property( QStringLiteral( "geometry" ) ).isValid() ) { - QScriptValue geom = json_stringify.call( QScriptValue(), QScriptValueList() << f.property( "geometry" ) ); + QScriptValue geom = json_stringify.call( QScriptValue(), QScriptValueList() << f.property( QStringLiteral( "geometry" ) ) ); if ( geom.isString() ) { OGRGeometryH ogrGeom = OGR_G_CreateGeometryFromJson( geom.toString().toUtf8() ); @@ -3066,9 +3066,9 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QgsFeatureStore featureStore( fields, crs() ); QMap<QString, QVariant> params; - params.insert( "sublayer", layerList[count] ); - params.insert( "featureType", QString( "%1_%2" ).arg( count ).arg( i ) ); - params.insert( "getFeatureInfoUrl", requestUrl.toString() ); + params.insert( QStringLiteral( "sublayer" ), layerList[count] ); + params.insert( QStringLiteral( "featureType" ), QStringLiteral( "%1_%2" ).arg( count ).arg( i ) ); + params.insert( QStringLiteral( "getFeatureInfoUrl" ), requestUrl.toString() ); featureStore.setParams( params ); feature.setValid( true ); @@ -3120,7 +3120,7 @@ void QgsWmsProvider::identifyReplyFinished() if ( !status.isNull() && status.toInt() >= 400 ) { QVariant phrase = mIdentifyReply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Map getfeatureinfo error %1: %2" ).arg( status.toInt() ).arg( phrase.toString() ); emit statusChanged( mError ); } @@ -3129,7 +3129,7 @@ void QgsWmsProvider::identifyReplyFinished() if ( !parser.isValid() ) { QgsDebugMsg( "Cannot parse reply" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Cannot parse getfeatureinfo: %1" ).arg( parser.error() ); emit statusChanged( mError ); } @@ -3144,7 +3144,7 @@ void QgsWmsProvider::identifyReplyFinished() else { //mIdentifyResult = tr( "ERROR: GetFeatureInfo failed" ); - mErrorFormat = "text/plain"; + mErrorFormat = QStringLiteral( "text/plain" ); mError = tr( "Map getfeatureinfo error: %1 [%2]" ).arg( mIdentifyReply->errorString(), mIdentifyReply->url().toString() ); emit statusChanged( mError ); QgsMessageLog::logMessage( mError, tr( "WMS" ) ); @@ -3298,48 +3298,48 @@ QUrl QgsWmsProvider::getLegendGraphicFullURL( double scale, const QgsRectangle& { qnames << url.queryItems().at( i ).first.toUpper(); } - if ( !qnames.contains( "SERVICE" ) ) - setQueryItem( url, "SERVICE", "WMS" ); - if ( !qnames.contains( "VERSION" ) ) - setQueryItem( url, "VERSION", mCaps.mCapabilities.version ); - if ( !qnames.contains( "SLD_VERSION" ) ) - setQueryItem( url, "SLD_VERSION", "1.1.0" ); // can not determine SLD_VERSION - if ( !qnames.contains( "REQUEST" ) ) - setQueryItem( url, "REQUEST", "GetLegendGraphic" ); - if ( !qnames.contains( "FORMAT" ) ) + if ( !qnames.contains( QStringLiteral( "SERVICE" ) ) ) + setQueryItem( url, QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); + if ( !qnames.contains( QStringLiteral( "VERSION" ) ) ) + setQueryItem( url, QStringLiteral( "VERSION" ), mCaps.mCapabilities.version ); + if ( !qnames.contains( QStringLiteral( "SLD_VERSION" ) ) ) + setQueryItem( url, QStringLiteral( "SLD_VERSION" ), QStringLiteral( "1.1.0" ) ); // can not determine SLD_VERSION + if ( !qnames.contains( QStringLiteral( "REQUEST" ) ) ) + setQueryItem( url, QStringLiteral( "REQUEST" ), QStringLiteral( "GetLegendGraphic" ) ); + if ( !qnames.contains( QStringLiteral( "FORMAT" ) ) ) setFormatQueryItem( url ); - if ( !qnames.contains( "LAYER" ) ) - setQueryItem( url, "LAYER", mSettings.mActiveSubLayers[0] ); - if ( !qnames.contains( "STYLE" ) ) - setQueryItem( url, "STYLE", mSettings.mActiveSubStyles[0] ); + if ( !qnames.contains( QStringLiteral( "LAYER" ) ) ) + setQueryItem( url, QStringLiteral( "LAYER" ), mSettings.mActiveSubLayers[0] ); + if ( !qnames.contains( QStringLiteral( "STYLE" ) ) ) + setQueryItem( url, QStringLiteral( "STYLE" ), mSettings.mActiveSubStyles[0] ); // by setting TRANSPARENT=true, even too big legend images will look good - if ( !qnames.contains( "TRANSPARENT" ) ) - setQueryItem( url, "TRANSPARENT", "true" ); + if ( !qnames.contains( QStringLiteral( "TRANSPARENT" ) ) ) + setQueryItem( url, QStringLiteral( "TRANSPARENT" ), QStringLiteral( "true" ) ); // add config parameter related to resolution QSettings s; - int defaultLegendGraphicResolution = s.value( "/qgis/defaultLegendGraphicResolution", 0 ).toInt(); + int defaultLegendGraphicResolution = s.value( QStringLiteral( "/qgis/defaultLegendGraphicResolution" ), 0 ).toInt(); QgsDebugMsg( QString( "defaultLegendGraphicResolution: %1" ).arg( defaultLegendGraphicResolution ) ); if ( defaultLegendGraphicResolution ) { if ( mSettings.mDpiMode & dpiQGIS ) - setQueryItem( url, "DPI", QString::number( defaultLegendGraphicResolution ) ); + setQueryItem( url, QStringLiteral( "DPI" ), QString::number( defaultLegendGraphicResolution ) ); if ( mSettings.mDpiMode & dpiUMN ) { - setQueryItem( url, "MAP_RESOLUTION", QString::number( defaultLegendGraphicResolution ) ); - setQueryItem( url, "SCALE", QString::number( scale, 'f' ) ); + setQueryItem( url, QStringLiteral( "MAP_RESOLUTION" ), QString::number( defaultLegendGraphicResolution ) ); + setQueryItem( url, QStringLiteral( "SCALE" ), QString::number( scale, 'f' ) ); } if ( mSettings.mDpiMode & dpiGeoServer ) { - setQueryItem( url, "FORMAT_OPTIONS", QString( "dpi:%1" ).arg( defaultLegendGraphicResolution ) ); - setQueryItem( url, "SCALE", QString::number( scale, 'f' ) ); + setQueryItem( url, QStringLiteral( "FORMAT_OPTIONS" ), QStringLiteral( "dpi:%1" ).arg( defaultLegendGraphicResolution ) ); + setQueryItem( url, QStringLiteral( "SCALE" ), QString::number( scale, 'f' ) ); } } if ( useContextualWMSLegend ) { bool changeXY = mCaps.shouldInvertAxisOrientation( mImageCrs ); - setQueryItem( url, "BBOX", toParamValue( visibleExtent, changeXY ) ); + setQueryItem( url, QStringLiteral( "BBOX" ), toParamValue( visibleExtent, changeXY ) ); setSRSQueryItem( url ); } @@ -3369,7 +3369,7 @@ QImage QgsWmsProvider::getLegendGraphic( double scale, bool forceRefresh, const if ( !forceRefresh ) return mGetLegendGraphicImage; - mError = ""; + mError = QLatin1String( "" ); QUrl url( getLegendGraphicFullURL( scale, mGetLegendGraphicExtent ) ); if ( !url.isValid() ) @@ -3478,7 +3478,7 @@ void QgsWmsProvider::getLegendGraphicReplyErrored( const QString& message ) void QgsWmsProvider::getLegendGraphicReplyProgress( qint64 bytesReceived, qint64 bytesTotal ) { - QString msg = tr( "%1 of %2 bytes of GetLegendGraphic downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QString( "unknown number of" ) : QString::number( bytesTotal ) ); + QString msg = tr( "%1 of %2 bytes of GetLegendGraphic downloaded." ).arg( bytesReceived ).arg( bytesTotal < 0 ? QStringLiteral( "unknown number of" ) : QString::number( bytesTotal ) ); QgsDebugMsg( msg ); emit statusChanged( msg ); } @@ -3601,8 +3601,8 @@ void QgsWmsImageDownloadHandler::cacheReplyFinished() QPainter p( mCachedImage ); p.drawImage( 0, 0, myLocalImage ); } - else if ( contentType.startsWith( "image/", Qt::CaseInsensitive ) || - contentType.compare( "application/octet-stream", Qt::CaseInsensitive ) == 0 ) + else if ( contentType.startsWith( QLatin1String( "image/" ), Qt::CaseInsensitive ) || + contentType.compare( QLatin1String( "application/octet-stream" ), Qt::CaseInsensitive ) == 0 ) { QgsMessageLog::logMessage( tr( "Returned image is flawed [Content-Type:%1; URL:%2]" ) .arg( contentType, mCacheReply->url().toString() ), tr( "WMS" ) ); @@ -3610,7 +3610,7 @@ void QgsWmsImageDownloadHandler::cacheReplyFinished() else { QString errorTitle, errorText; - if ( contentType.toLower() == "text/xml" && QgsWmsProvider::parseServiceExceptionReportDom( text, errorTitle, errorText ) ) + if ( contentType.toLower() == QLatin1String( "text/xml" ) && QgsWmsProvider::parseServiceExceptionReportDom( text, errorTitle, errorText ) ) { QgsMessageLog::logMessage( tr( "Map request error (Title:%1; Error:%2; URL: %3)" ) .arg( errorTitle, errorText, @@ -3776,7 +3776,7 @@ void QgsWmsTiledImageDownloadHandler::tileReplyFinished() if ( cmd.expirationDate().isNull() ) { QSettings s; - cmd.setExpirationDate( QDateTime::currentDateTime().addSecs( s.value( "/qgis/defaultTileExpiry", "24" ).toInt() * 60 * 60 ) ); + cmd.setExpirationDate( QDateTime::currentDateTime().addSecs( s.value( QStringLiteral( "/qgis/defaultTileExpiry" ), "24" ).toInt() * 60 * 60 ) ); } QgsNetworkAccessManager::instance()->cache()->updateMetaData( cmd ); @@ -3841,12 +3841,12 @@ void QgsWmsTiledImageDownloadHandler::tileReplyFinished() QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString(); QgsDebugMsg( "contentType: " + contentType ); - if ( !contentType.startsWith( "image/", Qt::CaseInsensitive ) && - contentType.compare( "application/octet-stream", Qt::CaseInsensitive ) != 0 ) + if ( !contentType.startsWith( QLatin1String( "image/" ), Qt::CaseInsensitive ) && + contentType.compare( QLatin1String( "application/octet-stream" ), Qt::CaseInsensitive ) != 0 ) { QByteArray text = reply->readAll(); QString errorTitle, errorText; - if ( contentType.toLower() == "text/xml" && QgsWmsProvider::parseServiceExceptionReportDom( text, errorTitle, errorText ) ) + if ( contentType.toLower() == QLatin1String( "text/xml" ) && QgsWmsProvider::parseServiceExceptionReportDom( text, errorTitle, errorText ) ) { QgsMessageLog::logMessage( tr( "Tile request error (Title:%1; Error:%2; URL: %3)" ) .arg( errorTitle, errorText, @@ -3993,7 +3993,7 @@ void QgsWmsTiledImageDownloadHandler::repeatTileRequest( QNetworkRequest const & retry++; QSettings s; - int maxRetry = s.value( "/qgis/defaultTileMaxRetry", "3" ).toInt(); + int maxRetry = s.value( QStringLiteral( "/qgis/defaultTileMaxRetry" ), "3" ).toInt(); if ( retry > maxRetry ) { if ( stat.errors < 100 ) @@ -4024,7 +4024,7 @@ void QgsWmsTiledImageDownloadHandler::repeatTileRequest( QNetworkRequest const & static QString formatDouble( double x ) { if ( x == 0.0 ) - return "0"; + return QStringLiteral( "0" ); const int numberOfDecimals = qMax( 0, 19 - static_cast<int>( ceil( log10( fabs( x ) ) ) ) ); return qgsDoubleToString( x, numberOfDecimals ); } @@ -4040,10 +4040,10 @@ QString QgsWmsProvider::toParamValue( const QgsRectangle& rect, bool changeXY ) void QgsWmsProvider::setSRSQueryItem( QUrl& url ) { - QString crsKey = "SRS"; //SRS in 1.1.1 and CRS in 1.3.0 - if ( mCaps.mCapabilities.version == "1.3.0" || mCaps.mCapabilities.version == "1.3" ) + QString crsKey = QStringLiteral( "SRS" ); //SRS in 1.1.1 and CRS in 1.3.0 + if ( mCaps.mCapabilities.version == QLatin1String( "1.3.0" ) || mCaps.mCapabilities.version == QLatin1String( "1.3" ) ) { - crsKey = "CRS"; + crsKey = QStringLiteral( "CRS" ); } setQueryItem( url, crsKey, mImageCrs ); } @@ -4160,7 +4160,7 @@ QgsWmsLegendDownloadHandler::finished() { QVariant phrase = mReply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ); QString msg( tr( "GetLegendGraphic request error" ) ); - msg += QString( " - " ); + msg += QStringLiteral( " - " ); msg += QString( tr( "Status: %1\nReason phrase: %2" ) ).arg( status.toInt() ).arg( phrase.toString() ); sendError( msg ); return; diff --git a/src/providers/wms/qgswmssourceselect.cpp b/src/providers/wms/qgswmssourceselect.cpp index fb43dc1c2f41..51db31871981 100644 --- a/src/providers/wms/qgswmssourceselect.cpp +++ b/src/providers/wms/qgswmssourceselect.cpp @@ -143,14 +143,14 @@ QgsWMSSourceSelect::QgsWMSSourceSelect( QWidget * parent, Qt::WindowFlags fl, bo QSettings settings; QgsDebugMsg( "restoring geometry" ); - restoreGeometry( settings.value( "/Windows/WMSSourceSelect/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/WMSSourceSelect/geometry" ) ).toByteArray() ); } QgsWMSSourceSelect::~QgsWMSSourceSelect() { QSettings settings; QgsDebugMsg( "saving geometry" ); - settings.setValue( "/Windows/WMSSourceSelect/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/WMSSourceSelect/geometry" ), saveGeometry() ); } @@ -176,7 +176,7 @@ void QgsWMSSourceSelect::on_btnNew_clicked() void QgsWMSSourceSelect::on_btnEdit_clicked() { - QgsNewHttpConnection *nc = new QgsNewHttpConnection( this, "/Qgis/connections-wms/", cmbConnections->currentText() ); + QgsNewHttpConnection *nc = new QgsNewHttpConnection( this, QStringLiteral( "/Qgis/connections-wms/" ), cmbConnections->currentText() ); if ( nc->exec() ) { @@ -487,8 +487,8 @@ void QgsWMSSourceSelect::addClicked() if ( mTileWidth->text().toInt() > 0 && mTileHeight->text().toInt() > 0 ) { - uri.setParam( "maxWidth", mTileWidth->text() ); - uri.setParam( "maxHeight", mTileHeight->text() ); + uri.setParam( QStringLiteral( "maxWidth" ), mTileWidth->text() ); + uri.setParam( QStringLiteral( "maxHeight" ), mTileHeight->text() ); } if ( lstTilesets->selectedItems().isEmpty() ) @@ -507,13 +507,13 @@ void QgsWMSSourceSelect::addClicked() crs = item->data( Qt::UserRole + 4 ).toString(); titles = QStringList( item->data( Qt::UserRole + 5 ).toString() ); - uri.setParam( "tileMatrixSet", item->data( Qt::UserRole + 3 ).toStringList() ); + uri.setParam( QStringLiteral( "tileMatrixSet" ), item->data( Qt::UserRole + 3 ).toStringList() ); const QgsWmtsTileLayer *layer = nullptr; Q_FOREACH ( const QgsWmtsTileLayer &l, mTileLayers ) { - if ( l.identifier == layers.join( "," ) ) + if ( l.identifier == layers.join( QStringLiteral( "," ) ) ) { layer = &l; break; @@ -548,26 +548,26 @@ void QgsWMSSourceSelect::addClicked() delete dlg; - uri.setParam( "tileDimensions", dimString ); + uri.setParam( QStringLiteral( "tileDimensions" ), dimString ); } } - uri.setParam( "layers", layers ); - uri.setParam( "styles", styles ); - uri.setParam( "format", format ); - uri.setParam( "crs", crs ); + uri.setParam( QStringLiteral( "layers" ), layers ); + uri.setParam( QStringLiteral( "styles" ), styles ); + uri.setParam( QStringLiteral( "format" ), format ); + uri.setParam( QStringLiteral( "crs" ), crs ); QgsDebugMsg( QString( "crs=%2 " ).arg( crs ) ); if ( mFeatureCount->text().toInt() > 0 ) { - uri.setParam( "featureCount", mFeatureCount->text() ); + uri.setParam( QStringLiteral( "featureCount" ), mFeatureCount->text() ); } - uri.setParam( "contextualWMSLegend", mContextualLegendCheckbox->isChecked() ? "1" : "0" ); + uri.setParam( QStringLiteral( "contextualWMSLegend" ), mContextualLegendCheckbox->isChecked() ? "1" : "0" ); emit addRasterLayer( uri.encodedUri(), - leLayerName->text().isEmpty() ? titles.join( "/" ) : leLayerName->text(), - "wms" ); + leLayerName->text().isEmpty() ? titles.join( QStringLiteral( "/" ) ) : leLayerName->text(), + QStringLiteral( "wms" ) ); } void QgsWMSSourceSelect::enableLayersForCrs( QTreeWidgetItem *item ) @@ -746,7 +746,7 @@ void QgsWMSSourceSelect::collectNamedLayers( QTreeWidgetItem *item, QStringList { // named layers layers << layerName; - styles << ""; + styles << QLatin1String( "" ); titles << titleName; if ( mCRSs.isEmpty() ) @@ -792,7 +792,7 @@ void QgsWMSSourceSelect::on_lstLayers_itemSelectionChanged() { // named layer: add using default style layers << layerName; - styles << ""; + styles << QLatin1String( "" ); titles << titleName; if ( mCRSs.isEmpty() ) mCRSs = item->data( 0, Qt::UserRole + 2 ).toStringList().toSet(); @@ -846,8 +846,8 @@ void QgsWMSSourceSelect::on_lstLayers_itemSelectionChanged() } else if ( layers.isEmpty() || mCRSs.isEmpty() ) { - mCRS = ""; - labelCoordRefSys->setText( "" ); + mCRS = QLatin1String( "" ); + labelCoordRefSys->setText( QLatin1String( "" ) ); } updateLayerOrderTab( layers, styles, titles ); @@ -963,13 +963,13 @@ void QgsWMSSourceSelect::updateButtons() { QStringList layers, styles, titles; collectSelectedLayers( layers, styles, titles ); - mLastLayerName = titles.join( "/" ); + mLastLayerName = titles.join( QStringLiteral( "/" ) ); leLayerName->setText( mLastLayerName ); } } else { - mLastLayerName = ""; + mLastLayerName = QLatin1String( "" ); leLayerName->setText( mLastLayerName ); } } @@ -999,7 +999,7 @@ QString QgsWMSSourceSelect::selectedImageEncoding() int id = mImageFormatGroup->checkedId(); if ( id < 0 ) { - return ""; + return QLatin1String( "" ); } else { @@ -1054,7 +1054,7 @@ void QgsWMSSourceSelect::showError( QgsWmsProvider * wms ) QgsMessageViewer * mv = new QgsMessageViewer( this ); mv->setWindowTitle( wms->lastErrorTitle() ); - if ( wms->lastErrorFormat() == "text/html" ) + if ( wms->lastErrorFormat() == QLatin1String( "text/html" ) ) { mv->setMessageAsHtml( wms->lastError() ); } @@ -1089,13 +1089,13 @@ QString QgsWMSSourceSelect::descriptionForAuthId( const QString& authId ) void QgsWMSSourceSelect::addDefaultServers() { QMap<QString, QString> exampleServers; - exampleServers["DM Solutions GMap"] = "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap"; - exampleServers["Lizardtech server"] = "http://wms.lizardtech.com/lizardtech/iserv/ows"; + exampleServers[QStringLiteral( "DM Solutions GMap" )] = QStringLiteral( "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap" ); + exampleServers[QStringLiteral( "Lizardtech server" )] = QStringLiteral( "http://wms.lizardtech.com/lizardtech/iserv/ows" ); // Nice to have the qgis users map, but I'm not sure of the URL at the moment. // exampleServers["Qgis users map"] = "http://qgis.org/wms.cgi"; QSettings settings; - settings.beginGroup( "/Qgis/connections-wms" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-wms" ) ); QMap<QString, QString>::const_iterator i = exampleServers.constBegin(); for ( ; i != exampleServers.constEnd(); ++i ) { @@ -1118,11 +1118,11 @@ void QgsWMSSourceSelect::addDefaultServers() void QgsWMSSourceSelect::addWMSListRow( const QDomElement& item, int row ) { - QDomElement title = item.firstChildElement( "title" ); + QDomElement title = item.firstChildElement( QStringLiteral( "title" ) ); addWMSListItem( title, row, 0 ); - QDomElement description = item.firstChildElement( "description" ); + QDomElement description = item.firstChildElement( QStringLiteral( "description" ) ); addWMSListItem( description, row, 1 ); - QDomElement link = item.firstChildElement( "link" ); + QDomElement link = item.firstChildElement( QStringLiteral( "link" ) ); addWMSListItem( link, row, 2 ); } @@ -1149,7 +1149,7 @@ void QgsWMSSourceSelect::on_btnSearch_clicked() QApplication::setOverrideCursor( Qt::WaitCursor ); QSettings settings; - QString mySearchUrl = settings.value( "/qgis/WMSSearchUrl", "http://geopole.org/wms/search?search=%1&type=rss" ).toString(); + QString mySearchUrl = settings.value( QStringLiteral( "/qgis/WMSSearchUrl" ), "http://geopole.org/wms/search?search=%1&type=rss" ).toString(); QUrl url( mySearchUrl.arg( leSearchTerm->text() ) ); QgsDebugMsg( url.toString() ); @@ -1168,13 +1168,13 @@ void QgsWMSSourceSelect::searchFinished() if ( r->error() == QNetworkReply::NoError ) { // parse results - QDomDocument doc( "RSS" ); + QDomDocument doc( QStringLiteral( "RSS" ) ); QByteArray res = r->readAll(); QString error; int line, column; if ( doc.setContent( res, &error, &line, &column ) ) { - QDomNodeList list = doc.elementsByTagName( "item" ); + QDomNodeList list = doc.elementsByTagName( QStringLiteral( "item" ) ); tableWidgetWMSList->setRowCount( list.size() ); for ( int i = 0; i < list.size(); i++ ) { @@ -1216,7 +1216,7 @@ void QgsWMSSourceSelect::on_btnAddWMS_clicked() QString wmsUrl = tableWidgetWMSList->item( selectedRow, 2 )->text(); QSettings settings; - if ( settings.contains( QString( "Qgis/connections-wms/%1/url" ).arg( wmsTitle ) ) ) + if ( settings.contains( QStringLiteral( "Qgis/connections-wms/%1/url" ).arg( wmsTitle ) ) ) { QString msg = tr( "The %1 connection already exists. Do you want to overwrite it?" ).arg( wmsTitle ); QMessageBox::StandardButton result = QMessageBox::information( this, tr( "Confirm Overwrite" ), msg, QMessageBox::Ok | QMessageBox::Cancel ); @@ -1227,7 +1227,7 @@ void QgsWMSSourceSelect::on_btnAddWMS_clicked() } // add selected WMS to config and mark as current - settings.setValue( QString( "Qgis/connections-wms/%1/url" ).arg( wmsTitle ), wmsUrl ); + settings.setValue( QStringLiteral( "Qgis/connections-wms/%1/url" ).arg( wmsTitle ), wmsUrl ); QgsWMSConnection::setSelectedConnection( wmsTitle ); populateConnectionList(); diff --git a/src/providers/wms/qgswmtsdimensions.cpp b/src/providers/wms/qgswmtsdimensions.cpp index bc6e61f24ff0..5faad281fbe8 100644 --- a/src/providers/wms/qgswmtsdimensions.cpp +++ b/src/providers/wms/qgswmtsdimensions.cpp @@ -49,14 +49,14 @@ QgsWmtsDimensions::QgsWmtsDimensions( const QgsWmtsTileLayer &layer, QWidget *pa QSettings settings; QgsDebugMsg( "restoring geometry" ); - restoreGeometry( settings.value( "/Windows/WMTSDimensions/geometry" ).toByteArray() ); + restoreGeometry( settings.value( QStringLiteral( "/Windows/WMTSDimensions/geometry" ) ).toByteArray() ); } QgsWmtsDimensions::~QgsWmtsDimensions() { QSettings settings; QgsDebugMsg( "saving geometry" ); - settings.setValue( "/Windows/WmtsDimensions/geometry", saveGeometry() ); + settings.setValue( QStringLiteral( "/Windows/WmtsDimensions/geometry" ), saveGeometry() ); } void QgsWmtsDimensions::selectedDimensions( QHash<QString, QString> &selected ) diff --git a/src/providers/wms/qgsxyzconnection.cpp b/src/providers/wms/qgsxyzconnection.cpp index 28a377343137..d5e1db42e68c 100644 --- a/src/providers/wms/qgsxyzconnection.cpp +++ b/src/providers/wms/qgsxyzconnection.cpp @@ -22,15 +22,15 @@ QString QgsXyzConnection::encodedUri() const { QgsDataSourceUri uri; - uri.setParam( "type", "xyz" ); - uri.setParam( "url", url ); + uri.setParam( QStringLiteral( "type" ), QStringLiteral( "xyz" ) ); + uri.setParam( QStringLiteral( "url" ), url ); return uri.encodedUri(); } QStringList QgsXyzConnectionUtils::connectionList() { QSettings settings; - settings.beginGroup( "/Qgis/connections-xyz" ); + settings.beginGroup( QStringLiteral( "/Qgis/connections-xyz" ) ); return settings.childGroups(); } @@ -41,7 +41,7 @@ QgsXyzConnection QgsXyzConnectionUtils::connection( const QString &name ) QgsXyzConnection conn; conn.name = name; - conn.url = settings.value( "url" ).toString(); + conn.url = settings.value( QStringLiteral( "url" ) ).toString(); return conn; } @@ -55,5 +55,5 @@ void QgsXyzConnectionUtils::addConnection( const QgsXyzConnection &conn ) { QSettings settings; settings.beginGroup( "/Qgis/connections-xyz/" + conn.name ); - settings.setValue( "url", conn.url ); + settings.setValue( QStringLiteral( "url" ), conn.url ); } diff --git a/src/python/qgspythonutilsimpl.cpp b/src/python/qgspythonutilsimpl.cpp index 1ddecb8580ad..8a2b2eec98a5 100644 --- a/src/python/qgspythonutilsimpl.cpp +++ b/src/python/qgspythonutilsimpl.cpp @@ -60,16 +60,16 @@ QgsPythonUtilsImpl::~QgsPythonUtilsImpl() bool QgsPythonUtilsImpl::checkSystemImports() { - runString( "import sys" ); // import sys module (for display / exception hooks) - runString( "import os" ); // import os module (for user paths) + runString( QStringLiteral( "import sys" ) ); // import sys module (for display / exception hooks) + runString( QStringLiteral( "import os" ) ); // import os module (for user paths) // support for PYTHONSTARTUP-like environment variable: PYQGIS_STARTUP // (unlike PYTHONHOME and PYTHONPATH, PYTHONSTARTUP is not supported for embedded interpreter by default) // this is different than user's 'startup.py' (below), since it is loaded just after Py_Initialize // it is very useful for cleaning sys.path, which may have undesireable paths, or for // isolating/loading the initial environ without requiring a virt env, e.g. homebrew or MacPorts installs on Mac - runString( "pyqgstart = os.getenv('PYQGIS_STARTUP')\n" ); - runString( "if pyqgstart is not None and os.path.exists(pyqgstart):\n with open(pyqgstart) as f:\n exec(f.read())\n" ); + runString( QStringLiteral( "pyqgstart = os.getenv('PYQGIS_STARTUP')\n" ) ); + runString( QStringLiteral( "if pyqgstart is not None and os.path.exists(pyqgstart):\n with open(pyqgstart) as f:\n exec(f.read())\n" ) ); #ifdef Q_OS_WIN runString( "oldhome=None" ); @@ -112,10 +112,10 @@ bool QgsPythonUtilsImpl::checkSystemImports() newpaths << '"' + pythonPath() + '"'; newpaths << homePythonPath(); newpaths << pluginpaths; - runString( "sys.path = [" + newpaths.join( "," ) + "] + sys.path" ); + runString( "sys.path = [" + newpaths.join( QStringLiteral( "," ) ) + "] + sys.path" ); // import SIP - if ( !runString( "import sip", + if ( !runString( QStringLiteral( "import sip" ), QObject::tr( "Couldn't load SIP module." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; @@ -123,10 +123,10 @@ bool QgsPythonUtilsImpl::checkSystemImports() // set PyQt4 api versions QStringList apiV2classes; - apiV2classes << "QDate" << "QDateTime" << "QString" << "QTextStream" << "QTime" << "QUrl" << "QVariant"; + apiV2classes << QStringLiteral( "QDate" ) << QStringLiteral( "QDateTime" ) << QStringLiteral( "QString" ) << QStringLiteral( "QTextStream" ) << QStringLiteral( "QTime" ) << QStringLiteral( "QUrl" ) << QStringLiteral( "QVariant" ); Q_FOREACH ( const QString& clsName, apiV2classes ) { - if ( !runString( QString( "sip.setapi('%1', 2)" ).arg( clsName ), + if ( !runString( QStringLiteral( "sip.setapi('%1', 2)" ).arg( clsName ), QObject::tr( "Couldn't set SIP API versions." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; @@ -141,7 +141,7 @@ bool QgsPythonUtilsImpl::checkSystemImports() } #else // import Qt bindings - if ( !runString( "from PyQt5 import QtCore, QtGui", + if ( !runString( QStringLiteral( "from PyQt5 import QtCore, QtGui" ), QObject::tr( "Couldn't load PyQt." ) + '\n' + QObject::tr( "Python support will be disabled." ) ) ) { return false; @@ -150,20 +150,20 @@ bool QgsPythonUtilsImpl::checkSystemImports() // import QGIS bindings QString error_msg = QObject::tr( "Couldn't load PyQGIS." ) + '\n' + QObject::tr( "Python support will be disabled." ); - if ( !runString( "from qgis.core import *", error_msg ) || !runString( "from qgis.gui import *", error_msg ) ) + if ( !runString( QStringLiteral( "from qgis.core import *" ), error_msg ) || !runString( QStringLiteral( "from qgis.gui import *" ), error_msg ) ) { return false; } // import QGIS utils error_msg = QObject::tr( "Couldn't load QGIS utils." ) + '\n' + QObject::tr( "Python support will be disabled." ); - if ( !runString( "import qgis.utils", error_msg ) ) + if ( !runString( QStringLiteral( "import qgis.utils" ), error_msg ) ) { return false; } // tell the utils script where to look for the plugins - runString( "qgis.utils.plugin_paths = [" + pluginpaths.join( "," ) + ']' ); + runString( "qgis.utils.plugin_paths = [" + pluginpaths.join( QStringLiteral( "," ) ) + ']' ); runString( "qgis.utils.sys_plugin_path = \"" + pluginsPath() + '\"' ); runString( "qgis.utils.home_plugin_path = " + homePluginsPath() ); @@ -201,7 +201,7 @@ bool QgsPythonUtilsImpl::checkQgisUser() { // import QGIS user QString error_msg = QObject::tr( "Couldn't load qgis.user." ) + '\n' + QObject::tr( "Python support will be disabled." ); - if ( !runString( "import qgis.user", error_msg ) ) + if ( !runString( QStringLiteral( "import qgis.user" ), error_msg ) ) { // Should we really bail because of this?! return false; @@ -241,7 +241,7 @@ void QgsPythonUtilsImpl::initServerPython( QgsServerInterface* interface ) // This is the main difference with initInterface() for desktop plugins // import QGIS Server bindings QString error_msg = QObject::tr( "Couldn't load PyQGIS Server." ) + '\n' + QObject::tr( "Python support will be disabled." ); - if ( !runString( "from qgis.server import *", error_msg ) ) + if ( !runString( QStringLiteral( "from qgis.server import *" ), error_msg ) ) { return; } @@ -256,7 +256,7 @@ bool QgsPythonUtilsImpl::startServerPlugin( QString packageName ) { QString output; evalString( "qgis.utils.startServerPlugin('" + packageName + "')", output ); - return ( output == "True" ); + return ( output == QLatin1String( "True" ) ); } #endif // End HAVE_SERVER_PYTHON_PLUGINS @@ -277,12 +277,12 @@ bool QgsPythonUtilsImpl::isEnabled() void QgsPythonUtilsImpl::installErrorHook() { - runString( "qgis.utils.installErrorHook()" ); + runString( QStringLiteral( "qgis.utils.installErrorHook()" ) ); } void QgsPythonUtilsImpl::uninstallErrorHook() { - runString( "qgis.utils.uninstallErrorHook()" ); + runString( QStringLiteral( "qgis.utils.uninstallErrorHook()" ) ); } @@ -322,14 +322,14 @@ bool QgsPythonUtilsImpl::runString( const QString& command, QString msgOnError, QString traceback = getTraceback(); QString path, version; - evalString( "str(sys.path)", path ); - evalString( "sys.version", version ); + evalString( QStringLiteral( "str(sys.path)" ), path ); + evalString( QStringLiteral( "sys.version" ), version ); QString str = "<font color=\"red\">" + msgOnError + "</font><br><pre>\n" + traceback + "\n</pre>" + QObject::tr( "Python version:" ) + "<br>" + version + "<br><br>" - + QObject::tr( "QGIS version:" ) + "<br>" + QString( "%1 '%2', %3" ).arg( Qgis::QGIS_VERSION, Qgis::QGIS_RELEASE_NAME, Qgis::QGIS_DEV_VERSION ) + "<br><br>" + + QObject::tr( "QGIS version:" ) + "<br>" + QStringLiteral( "%1 '%2', %3" ).arg( Qgis::QGIS_VERSION, Qgis::QGIS_RELEASE_NAME, Qgis::QGIS_DEV_VERSION ) + "<br><br>" + QObject::tr( "Python path:" ) + "<br>" + path; - str.replace( '\n', "<br>" ).replace( " ", "  " ); + str.replace( '\n', QLatin1String( "<br>" ) ).replace( QLatin1String( " " ), QLatin1String( "  " ) ); qDebug() << str; QgsMessageOutput* msg = QgsMessageOutput::createMessageOutput(); @@ -553,7 +553,7 @@ QString QgsPythonUtilsImpl::PyObjectToQString( PyObject* obj ) // some problem with conversion to unicode string QgsDebugMsg( "unable to convert PyObject to a QString!" ); - return "(qgis error)"; + return QStringLiteral( "(qgis error)" ); } @@ -595,13 +595,13 @@ QString QgsPythonUtilsImpl::pluginsPath() QString QgsPythonUtilsImpl::homePythonPath() { QString settingsDir = QgsApplication::qgisSettingsDirPath(); - if ( QDir::cleanPath( settingsDir ) == QDir::homePath() + QString( "/.qgis3" ) ) + if ( QDir::cleanPath( settingsDir ) == QDir::homePath() + QStringLiteral( "/.qgis3" ) ) { - return QString( "b\"%1/.qgis3/python\".decode('utf-8')" ).arg( QDir::homePath() ); + return QStringLiteral( "b\"%1/.qgis3/python\".decode('utf-8')" ).arg( QDir::homePath() ); } else { - return "b\"" + settingsDir.replace( '\\', "\\\\" ) + "python\".decode('utf-8')"; + return "b\"" + settingsDir.replace( '\\', QLatin1String( "\\\\" ) ) + "python\".decode('utf-8')"; } } @@ -630,10 +630,10 @@ QStringList QgsPythonUtilsImpl::extraPluginsPaths() QStringList QgsPythonUtilsImpl::pluginList() { - runString( "qgis.utils.updateAvailablePlugins()" ); + runString( QStringLiteral( "qgis.utils.updateAvailablePlugins()" ) ); QString output; - evalString( "'\\n'.join(qgis.utils.available_plugins)", output ); + evalString( QStringLiteral( "'\\n'.join(qgis.utils.available_plugins)" ), output ); return output.split( QChar( '\n' ), QString::SkipEmptyParts ); } @@ -650,40 +650,40 @@ bool QgsPythonUtilsImpl::loadPlugin( const QString& packageName ) { QString output; evalString( "qgis.utils.loadPlugin('" + packageName + "')", output ); - return ( output == "True" ); + return ( output == QLatin1String( "True" ) ); } bool QgsPythonUtilsImpl::startPlugin( const QString& packageName ) { QString output; evalString( "qgis.utils.startPlugin('" + packageName + "')", output ); - return ( output == "True" ); + return ( output == QLatin1String( "True" ) ); } bool QgsPythonUtilsImpl::canUninstallPlugin( const QString& packageName ) { QString output; evalString( "qgis.utils.canUninstallPlugin('" + packageName + "')", output ); - return ( output == "True" ); + return ( output == QLatin1String( "True" ) ); } bool QgsPythonUtilsImpl::unloadPlugin( const QString& packageName ) { QString output; evalString( "qgis.utils.unloadPlugin('" + packageName + "')", output ); - return ( output == "True" ); + return ( output == QLatin1String( "True" ) ); } bool QgsPythonUtilsImpl::isPluginLoaded( const QString& packageName ) { QString output; evalString( "qgis.utils.isPluginLoaded('" + packageName + "')", output ); - return ( output == "True" ); + return ( output == QLatin1String( "True" ) ); } QStringList QgsPythonUtilsImpl::listActivePlugins() { QString output; - evalString( "'\\n'.join(qgis.utils.active_plugins)", output ); + evalString( QStringLiteral( "'\\n'.join(qgis.utils.active_plugins)" ), output ); return output.split( QChar( '\n' ), QString::SkipEmptyParts ); } diff --git a/src/server/qgis_map_serv.cpp b/src/server/qgis_map_serv.cpp index 27146c77e13b..56f28e9e41db 100644 --- a/src/server/qgis_map_serv.cpp +++ b/src/server/qgis_map_serv.cpp @@ -37,7 +37,7 @@ int fcgi_accept() int main( int argc, char * argv[] ) { - QgsApplication app( argc, argv, getenv( "DISPLAY" ), QString(), "server" ); + QgsApplication app( argc, argv, getenv( "DISPLAY" ), QString(), QStringLiteral( "server" ) ); QgsServer server( false ); // Starts FCGI loop while ( fcgi_accept() >= 0 ) diff --git a/src/server/qgsaccesscontrol.cpp b/src/server/qgsaccesscontrol.cpp index c98182a1109c..8e13d9020a20 100644 --- a/src/server/qgsaccesscontrol.cpp +++ b/src/server/qgsaccesscontrol.cpp @@ -38,7 +38,7 @@ void QgsAccessControl::filterFeatures( const QgsVectorLayer* layer, QgsFeatureRe } if ( !expressions.isEmpty() ) { - featureRequest.setFilterExpression( QString( "((" ).append( expressions.join( ") AND (" ) ).append( "))" ) ); + featureRequest.setFilterExpression( QStringLiteral( "((" ).append( expressions.join( QStringLiteral( ") AND (" ) ) ).append( "))" ) ); } } @@ -61,7 +61,7 @@ QString QgsAccessControl::extraSubsetString( const QgsVectorLayer* layer ) const sqls.append( sql ); } } - return sqls.isEmpty() ? QString() : QString( "((" ).append( sqls.join( ") AND (" ) ).append( "))" ); + return sqls.isEmpty() ? QString() : QStringLiteral( "((" ).append( sqls.join( QStringLiteral( ") AND (" ) ) ).append( "))" ); } /** Return the layer read right */ diff --git a/src/server/qgsaccesscontrolfilter.cpp b/src/server/qgsaccesscontrolfilter.cpp index 43bdf11f7592..f75831a2a811 100644 --- a/src/server/qgsaccesscontrolfilter.cpp +++ b/src/server/qgsaccesscontrolfilter.cpp @@ -40,7 +40,7 @@ QgsAccessControlFilter::~QgsAccessControlFilter() /** Return an additional layer expression filter */ QString QgsAccessControlFilter::layerFilterExpression( const QgsVectorLayer* layer ) const { - QgsMessageLog::logMessage( "QgsAccessControlFilter plugin default layerFilterExpression called", "AccessControlFilter", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default layerFilterExpression called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); Q_UNUSED( layer ); return QString(); } @@ -48,7 +48,7 @@ QString QgsAccessControlFilter::layerFilterExpression( const QgsVectorLayer* lay /** Return an additional layer subset string (typically SQL) filter */ QString QgsAccessControlFilter::layerFilterSubsetString( const QgsVectorLayer* layer ) const { - QgsMessageLog::logMessage( "QgsAccessControlFilter plugin default layerFilterSQL called", "AccessControlFilter", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default layerFilterSQL called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); Q_UNUSED( layer ); return QString(); } @@ -56,7 +56,7 @@ QString QgsAccessControlFilter::layerFilterSubsetString( const QgsVectorLayer* l /** Return the layer permissions */ QgsAccessControlFilter::LayerPermissions QgsAccessControlFilter::layerPermissions( const QgsMapLayer* layer ) const { - QgsMessageLog::logMessage( "QgsAccessControlFilter plugin default layerPermissions called", "AccessControlFilter", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default layerPermissions called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); Q_UNUSED( layer ); LayerPermissions permissions = QgsAccessControlFilter::LayerPermissions(); permissions.canRead = permissions.canUpdate = permissions.canInsert = permissions.canDelete = true; @@ -67,14 +67,14 @@ QgsAccessControlFilter::LayerPermissions QgsAccessControlFilter::layerPermission QStringList QgsAccessControlFilter::authorizedLayerAttributes( const QgsVectorLayer* layer, const QStringList& attributes ) const { Q_UNUSED( layer ); - QgsMessageLog::logMessage( "QgsAccessControlFilter plugin default authorizedLayerAttributes called", "AccessControlFilter", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default authorizedLayerAttributes called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); return attributes; } /** Are we authorized to modify the feature */ bool QgsAccessControlFilter::allowToEdit( const QgsVectorLayer* layer, const QgsFeature& feature ) const { - QgsMessageLog::logMessage( "QgsAccessControlFilter plugin default allowToEdit called", "AccessControlFilter", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default allowToEdit called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); Q_UNUSED( layer ); Q_UNUSED( feature ); return true; diff --git a/src/server/qgsconfigcache.cpp b/src/server/qgsconfigcache.cpp index 54978e5b8944..b3915b672363 100644 --- a/src/server/qgsconfigcache.cpp +++ b/src/server/qgsconfigcache.cpp @@ -49,9 +49,9 @@ QgsConfigCache::~QgsConfigCache() QgsServerProjectParser* QgsConfigCache::serverConfiguration( const QString& filePath ) { QgsMessageLog::logMessage( - QString( "Open the project file '%1'." ) + QStringLiteral( "Open the project file '%1'." ) .arg( filePath ), - "Server", QgsMessageLog::INFO + QStringLiteral( "Server" ), QgsMessageLog::INFO ); QDomDocument* doc = xmlDocument( filePath ); @@ -70,13 +70,13 @@ QgsServerProjectParser* QgsConfigCache::serverConfiguration( const QString& file "\n========================================================================" "\n= WARNING: This project file was saved by a different version of QGIS. =" "\n========================================================================" - ), "Server", QgsMessageLog::WARNING + ), QStringLiteral( "Server" ), QgsMessageLog::WARNING ); } QgsMessageLog::logMessage( - QString( "QGIS server version %1, project version %2" ) + QStringLiteral( "QGIS server version %1, project version %2" ) .arg( thisVersion.text(), fileVersion.text() ), - "Server", QgsMessageLog::INFO + QStringLiteral( "Server" ), QgsMessageLog::INFO ); return new QgsServerProjectParser( doc, filePath ); } @@ -161,7 +161,7 @@ QgsWmsConfigParser *QgsConfigCache::wmsConfiguration( //sld or QGIS project file? //is it an sld document or a qgis project file? QDomElement documentElem = doc->documentElement(); - if ( documentElem.tagName() == "StyledLayerDescriptor" ) + if ( documentElem.tagName() == QLatin1String( "StyledLayerDescriptor" ) ) { p = new QgsSLDConfigParser( doc, parameterMap ); } @@ -189,13 +189,13 @@ QDomDocument* QgsConfigCache::xmlDocument( const QString& filePath ) QFile configFile( filePath ); if ( !configFile.exists() ) { - QgsMessageLog::logMessage( "Error, configuration file '" + filePath + "' does not exist", "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( "Error, configuration file '" + filePath + "' does not exist", QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); return nullptr; } if ( !configFile.open( QIODevice::ReadOnly ) ) { - QgsMessageLog::logMessage( "Error, cannot open configuration file '" + filePath + "'", "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( "Error, cannot open configuration file '" + filePath + "'", QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); return nullptr; } @@ -210,7 +210,7 @@ QDomDocument* QgsConfigCache::xmlDocument( const QString& filePath ) if ( !xmlDoc->setContent( &configFile, true, &errorMsg, &line, &column ) ) { QgsMessageLog::logMessage( "Error parsing file '" + filePath + - QString( "': parse error %1 at row %2, column %3" ).arg( errorMsg ).arg( line ).arg( column ), "Server", QgsMessageLog::CRITICAL ); + QStringLiteral( "': parse error %1 at row %2, column %3" ).arg( errorMsg ).arg( line ).arg( column ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); delete xmlDoc; return nullptr; } diff --git a/src/server/qgsconfigparserutils.cpp b/src/server/qgsconfigparserutils.cpp index fccf7fa2c9e8..12ea6d2b68d0 100644 --- a/src/server/qgsconfigparserutils.cpp +++ b/src/server/qgsconfigparserutils.cpp @@ -46,8 +46,8 @@ void QgsConfigParserUtils::appendCrsElementsToLayer( QDomElement& layerElement, } //insert the CRS elements after the title element to be in accordance with the WMS 1.3 specification - QDomElement titleElement = layerElement.firstChildElement( "Title" ); - QDomElement abstractElement = layerElement.firstChildElement( "Abstract" ); + QDomElement titleElement = layerElement.firstChildElement( QStringLiteral( "Title" ) ); + QDomElement abstractElement = layerElement.firstChildElement( QStringLiteral( "Abstract" ) ); QDomElement CRSPrecedingElement = abstractElement.isNull() ? titleElement : abstractElement; //last element before the CRS elements //In case the number of advertised CRS is constrained @@ -70,8 +70,8 @@ void QgsConfigParserUtils::appendCrsElementsToLayer( QDomElement& layerElement, void QgsConfigParserUtils::appendCrsElementToLayer( QDomElement& layerElement, const QDomElement& precedingElement, const QString& crsText, QDomDocument& doc ) { - QString version = doc.documentElement().attribute( "version" ); - QDomElement crsElement = doc.createElement( version == "1.1.1" ? "SRS" : "CRS" ); + QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); + QDomElement crsElement = doc.createElement( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS" ); QDomText crsTextNode = doc.createTextNode( crsText ); crsElement.appendChild( crsTextNode ); layerElement.insertAfter( crsElement, precedingElement ); @@ -87,7 +87,7 @@ void QgsConfigParserUtils::appendLayerBoundingBoxes( QDomElement& layerElem, QDo QgsCoordinateReferenceSystem wgs84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( GEO_EPSG_CRS_AUTHID ); - QString version = doc.documentElement().attribute( "version" ); + QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); //Ex_GeographicBoundingBox QDomElement ExGeoBBoxElement; @@ -106,30 +106,30 @@ void QgsConfigParserUtils::appendLayerBoundingBoxes( QDomElement& layerElem, QDo } } - if ( version == "1.1.1" ) // WMS Version 1.1.1 + if ( version == QLatin1String( "1.1.1" ) ) // WMS Version 1.1.1 { - ExGeoBBoxElement = doc.createElement( "LatLonBoundingBox" ); - ExGeoBBoxElement.setAttribute( "minx", QString::number( wgs84BoundingRect.xMinimum() ) ); - ExGeoBBoxElement.setAttribute( "maxx", QString::number( wgs84BoundingRect.xMaximum() ) ); - ExGeoBBoxElement.setAttribute( "miny", QString::number( wgs84BoundingRect.yMinimum() ) ); - ExGeoBBoxElement.setAttribute( "maxy", QString::number( wgs84BoundingRect.yMaximum() ) ); + ExGeoBBoxElement = doc.createElement( QStringLiteral( "LatLonBoundingBox" ) ); + ExGeoBBoxElement.setAttribute( QStringLiteral( "minx" ), QString::number( wgs84BoundingRect.xMinimum() ) ); + ExGeoBBoxElement.setAttribute( QStringLiteral( "maxx" ), QString::number( wgs84BoundingRect.xMaximum() ) ); + ExGeoBBoxElement.setAttribute( QStringLiteral( "miny" ), QString::number( wgs84BoundingRect.yMinimum() ) ); + ExGeoBBoxElement.setAttribute( QStringLiteral( "maxy" ), QString::number( wgs84BoundingRect.yMaximum() ) ); } else // WMS Version 1.3.0 { - ExGeoBBoxElement = doc.createElement( "EX_GeographicBoundingBox" ); - QDomElement wBoundLongitudeElement = doc.createElement( "westBoundLongitude" ); + ExGeoBBoxElement = doc.createElement( QStringLiteral( "EX_GeographicBoundingBox" ) ); + QDomElement wBoundLongitudeElement = doc.createElement( QStringLiteral( "westBoundLongitude" ) ); QDomText wBoundLongitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.xMinimum() ) ); wBoundLongitudeElement.appendChild( wBoundLongitudeText ); ExGeoBBoxElement.appendChild( wBoundLongitudeElement ); - QDomElement eBoundLongitudeElement = doc.createElement( "eastBoundLongitude" ); + QDomElement eBoundLongitudeElement = doc.createElement( QStringLiteral( "eastBoundLongitude" ) ); QDomText eBoundLongitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.xMaximum() ) ); eBoundLongitudeElement.appendChild( eBoundLongitudeText ); ExGeoBBoxElement.appendChild( eBoundLongitudeElement ); - QDomElement sBoundLatitudeElement = doc.createElement( "southBoundLatitude" ); + QDomElement sBoundLatitudeElement = doc.createElement( QStringLiteral( "southBoundLatitude" ) ); QDomText sBoundLatitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.yMinimum() ) ); sBoundLatitudeElement.appendChild( sBoundLatitudeText ); ExGeoBBoxElement.appendChild( sBoundLatitudeElement ); - QDomElement nBoundLatitudeElement = doc.createElement( "northBoundLatitude" ); + QDomElement nBoundLatitudeElement = doc.createElement( QStringLiteral( "northBoundLatitude" ) ); QDomText nBoundLatitudeText = doc.createTextNode( QString::number( wgs84BoundingRect.yMaximum() ) ); nBoundLatitudeElement.appendChild( nBoundLatitudeText ); ExGeoBBoxElement.appendChild( nBoundLatitudeElement ); @@ -157,7 +157,7 @@ void QgsConfigParserUtils::appendLayerBoundingBoxes( QDomElement& layerElem, QDo if ( !wgs84BoundingRect.isNull() ) //LatLonBoundingBox / Ex_GeographicBounding box is optional { - QDomElement lastCRSElem = layerElem.lastChildElement( version == "1.1.1" ? "SRS" : "CRS" ); + QDomElement lastCRSElem = layerElem.lastChildElement( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS" ); if ( !lastCRSElem.isNull() ) { layerElem.insertAfter( ExGeoBBoxElement, lastCRSElem ); @@ -195,7 +195,7 @@ void QgsConfigParserUtils::appendLayerBoundingBox( QDomElement& layerElem, QDomD return; } - QString version = doc.documentElement().attribute( "version" ); + QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crsText ); @@ -221,30 +221,30 @@ void QgsConfigParserUtils::appendLayerBoundingBox( QDomElement& layerElem, QDomD } //BoundingBox element - QDomElement bBoxElement = doc.createElement( "BoundingBox" ); + QDomElement bBoxElement = doc.createElement( QStringLiteral( "BoundingBox" ) ); if ( crs.isValid() ) { - bBoxElement.setAttribute( version == "1.1.1" ? "SRS" : "CRS", crs.authid() ); + bBoxElement.setAttribute( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS", crs.authid() ); } - if ( version != "1.1.1" && crs.hasAxisInverted() ) + if ( version != QLatin1String( "1.1.1" ) && crs.hasAxisInverted() ) { crsExtent.invert(); } - bBoxElement.setAttribute( "minx", QString::number( crsExtent.xMinimum() ) ); - bBoxElement.setAttribute( "miny", QString::number( crsExtent.yMinimum() ) ); - bBoxElement.setAttribute( "maxx", QString::number( crsExtent.xMaximum() ) ); - bBoxElement.setAttribute( "maxy", QString::number( crsExtent.yMaximum() ) ); + bBoxElement.setAttribute( QStringLiteral( "minx" ), QString::number( crsExtent.xMinimum() ) ); + bBoxElement.setAttribute( QStringLiteral( "miny" ), QString::number( crsExtent.yMinimum() ) ); + bBoxElement.setAttribute( QStringLiteral( "maxx" ), QString::number( crsExtent.xMaximum() ) ); + bBoxElement.setAttribute( QStringLiteral( "maxy" ), QString::number( crsExtent.yMaximum() ) ); - QDomElement lastBBoxElem = layerElem.lastChildElement( "BoundingBox" ); + QDomElement lastBBoxElem = layerElem.lastChildElement( QStringLiteral( "BoundingBox" ) ); if ( !lastBBoxElem.isNull() ) { layerElem.insertAfter( bBoxElement, lastBBoxElem ); } else { - lastBBoxElem = layerElem.lastChildElement( version == "1.1.1" ? "LatLonBoundingBox" : "EX_GeographicBoundingBox" ); + lastBBoxElem = layerElem.lastChildElement( version == QLatin1String( "1.1.1" ) ? "LatLonBoundingBox" : "EX_GeographicBoundingBox" ); if ( !lastBBoxElem.isNull() ) { layerElem.insertAfter( bBoxElement, lastBBoxElem ); @@ -273,7 +273,7 @@ QStringList QgsConfigParserUtils::createCrsListForLayer( QgsMapLayer* theMapLaye crsNumbers.push_back( theMapLayer->crs().authid() ); return crsNumbers; }; - QString mySql = "select upper(auth_name||':'||auth_id) from tbl_srs"; + QString mySql = QStringLiteral( "select upper(auth_name||':'||auth_id) from tbl_srs" ); myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.length(), &myPreparedStatement, &myTail ); if ( myResult == SQLITE_OK ) { @@ -290,7 +290,7 @@ QStringList QgsConfigParserUtils::createCrsListForLayer( QgsMapLayer* theMapLaye void QgsConfigParserUtils::fallbackServiceCapabilities( QDomElement& parentElement, QDomDocument& doc ) { Q_UNUSED( doc ); - QFile wmsService( "wms_metadata.xml" ); + QFile wmsService( QStringLiteral( "wms_metadata.xml" ) ); if ( wmsService.open( QIODevice::ReadOnly ) ) { QDomDocument externServiceDoc; diff --git a/src/server/qgshostedrdsbuilder.cpp b/src/server/qgshostedrdsbuilder.cpp index 8de34c7a3909..23b9c3a4cb8d 100644 --- a/src/server/qgshostedrdsbuilder.cpp +++ b/src/server/qgshostedrdsbuilder.cpp @@ -47,8 +47,8 @@ QgsMapLayer* QgsHostedRDSBuilder::createMapLayer( const QDomElement& elem, return nullptr; } - QString uri = elem.attribute( "uri", "not found" ); - if ( uri == "not found" ) + QString uri = elem.attribute( QStringLiteral( "uri" ), QStringLiteral( "not found" ) ); + if ( uri == QLatin1String( "not found" ) ) { QgsDebugMsg( "Uri not found" ); return nullptr; @@ -80,7 +80,7 @@ QgsMapLayer* QgsHostedRDSBuilder::createMapLayer( const QDomElement& elem, //projection if ( rl ) { - QString epsg = elem.attribute( "epsg" ); + QString epsg = elem.attribute( QStringLiteral( "epsg" ) ); if ( !epsg.isEmpty() ) { bool conversionOk; @@ -88,7 +88,7 @@ QgsMapLayer* QgsHostedRDSBuilder::createMapLayer( const QDomElement& elem, if ( conversionOk ) { //set spatial ref sys - QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( epsgnr ) ); + QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( epsgnr ) ); rl->setCrs( srs ); } } diff --git a/src/server/qgshostedvdsbuilder.cpp b/src/server/qgshostedvdsbuilder.cpp index 833ec92f11ca..0a75431500a2 100644 --- a/src/server/qgshostedvdsbuilder.cpp +++ b/src/server/qgshostedvdsbuilder.cpp @@ -44,10 +44,10 @@ QgsMapLayer* QgsHostedVDSBuilder::createMapLayer( const QDomElement& elem, return nullptr; } - QString providerType = elem.attribute( "providerType", "not found" ); - QString uri = elem.attribute( "uri", "not found" ); + QString providerType = elem.attribute( QStringLiteral( "providerType" ), QStringLiteral( "not found" ) ); + QString uri = elem.attribute( QStringLiteral( "uri" ), QStringLiteral( "not found" ) ); - if ( providerType == "not found" || uri == "not found" ) + if ( providerType == QLatin1String( "not found" ) || uri == QLatin1String( "not found" ) ) { QgsDebugMsg( "error, provider type not found" ); return nullptr; @@ -86,7 +86,7 @@ QgsMapLayer* QgsHostedVDSBuilder::createMapLayer( const QDomElement& elem, //projection if ( ml ) { - QString epsg = elem.attribute( "epsg" ); + QString epsg = elem.attribute( QStringLiteral( "epsg" ) ); if ( !epsg.isEmpty() ) { bool conversionOk; @@ -94,7 +94,7 @@ QgsMapLayer* QgsHostedVDSBuilder::createMapLayer( const QDomElement& elem, if ( conversionOk ) { //set spatial ref sys - QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( epsgnr ) ); + QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( epsgnr ) ); ml->setCrs( srs ); } } diff --git a/src/server/qgshttprequesthandler.cpp b/src/server/qgshttprequesthandler.cpp index b68d4b62f8d6..ab81f40f2402 100644 --- a/src/server/qgshttprequesthandler.cpp +++ b/src/server/qgshttprequesthandler.cpp @@ -51,7 +51,7 @@ QgsHttpRequestHandler::~QgsHttpRequestHandler() void QgsHttpRequestHandler::setHttpResponse( QByteArray *ba, const QString &format ) { - QgsMessageLog::logMessage( "Checking byte array is ok to set..." ); + QgsMessageLog::logMessage( QStringLiteral( "Checking byte array is ok to set..." ) ); if ( !ba ) { return; @@ -61,7 +61,7 @@ void QgsHttpRequestHandler::setHttpResponse( QByteArray *ba, const QString &form { return; } - QgsMessageLog::logMessage( "Byte array looks good, setting response..." ); + QgsMessageLog::logMessage( QStringLiteral( "Byte array looks good, setting response..." ) ); appendBody( *ba ); mInfoFormat = format; } @@ -80,17 +80,17 @@ void QgsHttpRequestHandler::setDefaultHeaders() { //format QString format = mInfoFormat; - if ( mInfoFormat.startsWith( "text/" ) || mInfoFormat.startsWith( "application/vnd.ogc.gml" ) ) + if ( mInfoFormat.startsWith( QLatin1String( "text/" ) ) || mInfoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml" ) ) ) { format.append( "; charset=utf-8" ); } - setHeader( "Content-Type", format ); + setHeader( QStringLiteral( "Content-Type" ), format ); //length int contentLength = mBody.size(); if ( contentLength > 0 ) // size is not known when streaming { - setHeader( "Content-Length", QString::number( contentLength ) ); + setHeader( QStringLiteral( "Content-Length" ), QString::number( contentLength ) ); } } @@ -182,7 +182,7 @@ void QgsHttpRequestHandler::sendBody() // Cannot use addToResponse because it uses printf size_t result = fwrite(( void* )mBody.data(), mBody.size(), 1, FCGI_stdout ); #ifdef QGISDEBUG - QgsMessageLog::logMessage( QString( "Sent %1 blocks of %2 bytes" ).arg( result ).arg( mBody.size() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Sent %1 blocks of %2 bytes" ).arg( result ).arg( mBody.size() ) ); #else Q_UNUSED( result ); #endif @@ -198,10 +198,10 @@ void QgsHttpRequestHandler::setPluginFilters( const QgsServerFiltersMap& pluginF void QgsHttpRequestHandler::sendResponse() { - QgsMessageLog::logMessage( QString( "Sending HTTP response" ) ); + QgsMessageLog::logMessage( QStringLiteral( "Sending HTTP response" ) ); if ( ! responseReady() ) { - QgsMessageLog::logMessage( QString( "Trying to send out an invalid response" ) ); + QgsMessageLog::logMessage( QStringLiteral( "Trying to send out an invalid response" ) ); return; } #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -231,21 +231,21 @@ QPair<QByteArray, QByteArray> QgsHttpRequestHandler::getResponse() QString QgsHttpRequestHandler::formatToMimeType( const QString& format ) const { - if ( format.compare( "png", Qt::CaseInsensitive ) == 0 ) + if ( format.compare( QLatin1String( "png" ), Qt::CaseInsensitive ) == 0 ) { - return "image/png"; + return QStringLiteral( "image/png" ); } - else if ( format.compare( "jpg", Qt::CaseInsensitive ) == 0 ) + else if ( format.compare( QLatin1String( "jpg" ), Qt::CaseInsensitive ) == 0 ) { - return "image/jpeg"; + return QStringLiteral( "image/jpeg" ); } - else if ( format.compare( "svg", Qt::CaseInsensitive ) == 0 ) + else if ( format.compare( QLatin1String( "svg" ), Qt::CaseInsensitive ) == 0 ) { - return "image/svg+xml"; + return QStringLiteral( "image/svg+xml" ); } - else if ( format.compare( "pdf", Qt::CaseInsensitive ) == 0 ) + else if ( format.compare( QLatin1String( "pdf" ), Qt::CaseInsensitive ) == 0 ) { - return "application/pdf"; + return QStringLiteral( "application/pdf" ); } return format; } @@ -253,17 +253,17 @@ QString QgsHttpRequestHandler::formatToMimeType( const QString& format ) const void QgsHttpRequestHandler::setGetMapResponse( const QString& service, QImage* img, int imageQuality = -1 ) { Q_UNUSED( service ); - QgsMessageLog::logMessage( "setting getmap response..." ); + QgsMessageLog::logMessage( QStringLiteral( "setting getmap response..." ) ); if ( img ) { - bool png16Bit = ( mFormatString.compare( "image/png; mode=16bit", Qt::CaseInsensitive ) == 0 ); - bool png8Bit = ( mFormatString.compare( "image/png; mode=8bit", Qt::CaseInsensitive ) == 0 ); - bool png1Bit = ( mFormatString.compare( "image/png; mode=1bit", Qt::CaseInsensitive ) == 0 ); - bool isBase64 = mFormatString.endsWith( ";base64", Qt::CaseInsensitive ); - if ( mFormat != "PNG" && mFormat != "JPG" && !png16Bit && !png8Bit && !png1Bit ) + bool png16Bit = ( mFormatString.compare( QLatin1String( "image/png; mode=16bit" ), Qt::CaseInsensitive ) == 0 ); + bool png8Bit = ( mFormatString.compare( QLatin1String( "image/png; mode=8bit" ), Qt::CaseInsensitive ) == 0 ); + bool png1Bit = ( mFormatString.compare( QLatin1String( "image/png; mode=1bit" ), Qt::CaseInsensitive ) == 0 ); + bool isBase64 = mFormatString.endsWith( QLatin1String( ";base64" ), Qt::CaseInsensitive ); + if ( mFormat != QLatin1String( "PNG" ) && mFormat != QLatin1String( "JPG" ) && !png16Bit && !png8Bit && !png1Bit ) { - QgsMessageLog::logMessage( "service exception - incorrect image format requested..." ); - setServiceException( QgsMapServiceException( "InvalidFormat", "Output format '" + mFormatString + "' is not supported in the GetMap request" ) ); + QgsMessageLog::logMessage( QStringLiteral( "service exception - incorrect image format requested..." ) ); + setServiceException( QgsMapServiceException( QStringLiteral( "InvalidFormat" ), "Output format '" + mFormatString + "' is not supported in the GetMap request" ) ); return; } @@ -274,7 +274,7 @@ void QgsHttpRequestHandler::setGetMapResponse( const QString& service, QImage* i // Do not use imageQuality for PNG images // For now, QImage expects quality to be a range 0-9 for PNG - if ( mFormat == "PNG" ) + if ( mFormat == QLatin1String( "PNG" ) ) { imageQuality = -1; } @@ -314,13 +314,13 @@ void QgsHttpRequestHandler::setGetMapResponse( const QString& service, QImage* i void QgsHttpRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc ) { QByteArray ba = doc.toByteArray(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } void QgsHttpRequestHandler::setXmlResponse( const QDomDocument& doc ) { QByteArray ba = doc.toByteArray(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } void QgsHttpRequestHandler::setXmlResponse( const QDomDocument& doc, const QString& mimeType ) @@ -334,21 +334,21 @@ void QgsHttpRequestHandler::setGetFeatureInfoResponse( const QDomDocument& infoD QByteArray ba; QgsMessageLog::logMessage( "Info format is:" + infoFormat ); - if ( infoFormat == "text/xml" || infoFormat.startsWith( "application/vnd.ogc.gml" ) ) + if ( infoFormat == QLatin1String( "text/xml" ) || infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml" ) ) ) { ba = infoDoc.toByteArray(); } - else if ( infoFormat == "text/plain" || infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/plain" ) || infoFormat == QLatin1String( "text/html" ) ) { //create string QString featureInfoString; - if ( infoFormat == "text/plain" ) + if ( infoFormat == QLatin1String( "text/plain" ) ) { featureInfoString.append( "GetFeatureInfo results\n" ); featureInfoString.append( "\n" ); } - else if ( infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/html" ) ) { featureInfoString.append( "<HEAD>\n" ); featureInfoString.append( "<TITLE> GetFeatureInfo results \n" ); @@ -357,42 +357,42 @@ void QgsHttpRequestHandler::setGetFeatureInfoResponse( const QDomDocument& infoD featureInfoString.append( "\n" ); } - QDomNodeList layerList = infoDoc.elementsByTagName( "Layer" ); + QDomNodeList layerList = infoDoc.elementsByTagName( QStringLiteral( "Layer" ) ); //layer loop for ( int i = 0; i < layerList.size(); ++i ) { QDomElement layerElem = layerList.at( i ).toElement(); - if ( infoFormat == "text/plain" ) + if ( infoFormat == QLatin1String( "text/plain" ) ) { - featureInfoString.append( "Layer '" + layerElem.attribute( "name" ) + "'\n" ); + featureInfoString.append( "Layer '" + layerElem.attribute( QStringLiteral( "name" ) ) + "'\n" ); } - else if ( infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/html" ) ) { featureInfoString.append( "
                                                                                                                                                                                    " ); mReport += QString( "
                                                                                                                                                                                    " "Test image and result image for %1
                                                                                                                                                                                    " "Expected size: %2 w x %3 h (%4 pixels)
                                                                                                                                                                                    " @@ -362,7 +362,7 @@ bool QgsRenderChecker::compareImages( const QString& theTestName, QString prefix; if ( !mControlPathPrefix.isNull() ) { - prefix = QString( " (prefix %1)" ).arg( mControlPathPrefix ); + prefix = QStringLiteral( " (prefix %1)" ).arg( mControlPathPrefix ); } // // To get the images into CDash @@ -384,18 +384,18 @@ bool QgsRenderChecker::compareImages( const QString& theTestName, if ( qAbs( myExpectedImage.width() - myResultImage.width() ) > mMaxSizeDifferenceX || qAbs( myExpectedImage.height() - myResultImage.height() ) > mMaxSizeDifferenceY ) { - mReport += "
                                                                                                                                                                                    "; + mReport += QLatin1String( "
                                                                                                                                                                                    " ); mReport += "Expected image and result image for " + theTestName + " are different dimensions - FAILING!"; - mReport += "
                                                                                                                                                                                    "; + mReport += QLatin1String( "
                                                                                                                                                                                    " ); mReport += "Expected image and result image for " + theTestName + " are different dimensions, but within tolerance"; - mReport += "
                                                                                                                                                                                    %1/%2 pixels mismatched (allowed threshold: %3, allowed color component tolerance: %4)
                                                                                                                                                                                    %1/%2 pixels mismatched (allowed threshold: %3, allowed color component tolerance: %4)
                                                                                                                                                                                    \n"; + mReport += QLatin1String( "
                                                                                                                                                                                    \n" ); mReport += "Test image and result image for " + theTestName + " are matched
                                                                                                                                                                                    "; - mReport += "
                                                                                                                                                                                    \n"; - mReport += "Test failed because render step took too long"; - mReport += "
                                                                                                                                                                                    \n" ); + mReport += QLatin1String( "Test failed because render step took too long" ); + mReport += QLatin1String( "
                                                                                                                                                                                    \n"; + mReport += QLatin1String( "
                                                                                                                                                                                    \n" ); mReport += "Test image and result image for " + theTestName + " are mismatched
                                                                                                                                                                                    "; - mReport += "
                                                                                                                                                                                    \n" ); - featureInfoString.append( "\n" ); + featureInfoString.append( "\n" ); featureInfoString.append( "
                                                                                                                                                                                    " ); } //feature loop (for vector layers) - QDomNodeList featureNodeList = layerElem.elementsByTagName( "Feature" ); + QDomNodeList featureNodeList = layerElem.elementsByTagName( QStringLiteral( "Feature" ) ); QDomElement currentFeatureElement; if ( featureNodeList.size() < 1 ) //raster layer? { - QDomNodeList attributeNodeList = layerElem.elementsByTagName( "Attribute" ); + QDomNodeList attributeNodeList = layerElem.elementsByTagName( QStringLiteral( "Attribute" ) ); for ( int j = 0; j < attributeNodeList.size(); ++j ) { QDomElement attributeElement = attributeNodeList.at( j ).toElement(); - if ( infoFormat == "text/plain" ) + if ( infoFormat == QLatin1String( "text/plain" ) ) { - featureInfoString.append( attributeElement.attribute( "name" ) + " = '" + - attributeElement.attribute( "value" ) + "'\n" ); + featureInfoString.append( attributeElement.attribute( QStringLiteral( "name" ) ) + " = '" + + attributeElement.attribute( QStringLiteral( "value" ) ) + "'\n" ); } - else if ( infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/html" ) ) { - featureInfoString.append( "\n" ); + featureInfoString.append( "\n" ); } } } @@ -401,48 +401,48 @@ void QgsHttpRequestHandler::setGetFeatureInfoResponse( const QDomDocument& infoD for ( int j = 0; j < featureNodeList.size(); ++j ) { QDomElement featureElement = featureNodeList.at( j ).toElement(); - if ( infoFormat == "text/plain" ) + if ( infoFormat == QLatin1String( "text/plain" ) ) { - featureInfoString.append( "Feature " + featureElement.attribute( "id" ) + "\n" ); + featureInfoString.append( "Feature " + featureElement.attribute( QStringLiteral( "id" ) ) + "\n" ); } - else if ( infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/html" ) ) { featureInfoString.append( "
                                                                                                                                                                                    Layer" + layerElem.attribute( "name" ) + "
                                                                                                                                                                                    Layer" + layerElem.attribute( QStringLiteral( "name" ) ) + "
                                                                                                                                                                                    " + attributeElement.attribute( "name" ) + "" + - attributeElement.attribute( "value" ) + "
                                                                                                                                                                                    " + attributeElement.attribute( QStringLiteral( "name" ) ) + "" + + attributeElement.attribute( QStringLiteral( "value" ) ) + "
                                                                                                                                                                                    \n" ); - featureInfoString.append( "\n" ); + featureInfoString.append( "\n" ); } //attribute loop - QDomNodeList attributeNodeList = featureElement.elementsByTagName( "Attribute" ); + QDomNodeList attributeNodeList = featureElement.elementsByTagName( QStringLiteral( "Attribute" ) ); for ( int k = 0; k < attributeNodeList.size(); ++k ) { QDomElement attributeElement = attributeNodeList.at( k ).toElement(); - if ( infoFormat == "text/plain" ) + if ( infoFormat == QLatin1String( "text/plain" ) ) { - featureInfoString.append( attributeElement.attribute( "name" ) + " = '" + - attributeElement.attribute( "value" ) + "'\n" ); + featureInfoString.append( attributeElement.attribute( QStringLiteral( "name" ) ) + " = '" + + attributeElement.attribute( QStringLiteral( "value" ) ) + "'\n" ); } - else if ( infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/html" ) ) { - featureInfoString.append( "\n" ); + featureInfoString.append( "\n" ); } } - if ( infoFormat == "text/html" ) + if ( infoFormat == QLatin1String( "text/html" ) ) { featureInfoString.append( "
                                                                                                                                                                                    Feature" + featureElement.attribute( "id" ) + "
                                                                                                                                                                                    Feature" + featureElement.attribute( QStringLiteral( "id" ) ) + "
                                                                                                                                                                                    " + attributeElement.attribute( "name" ) + "" + attributeElement.attribute( "value" ) + "
                                                                                                                                                                                    " + attributeElement.attribute( QStringLiteral( "name" ) ) + "" + attributeElement.attribute( QStringLiteral( "value" ) ) + "
                                                                                                                                                                                    \n
                                                                                                                                                                                    \n" ); } } } - if ( infoFormat == "text/plain" ) + if ( infoFormat == QLatin1String( "text/plain" ) ) { featureInfoString.append( "\n" ); } - else if ( infoFormat == "text/html" ) + else if ( infoFormat == QLatin1String( "text/html" ) ) { featureInfoString.append( "
                                                                                                                                                                                    \n

                                                                                                                                                                                    \n" ); } } - if ( infoFormat == "text/html" ) + if ( infoFormat == QLatin1String( "text/html" ) ) { featureInfoString.append( "\n" ); } @@ -450,7 +450,7 @@ void QgsHttpRequestHandler::setGetFeatureInfoResponse( const QDomDocument& infoD } else //unsupported format, set exception { - setServiceException( QgsMapServiceException( "InvalidFormat", "Feature info format '" + infoFormat + "' is not supported. Possibilities are 'text/plain', 'text/html' or 'text/xml'." ) ); + setServiceException( QgsMapServiceException( QStringLiteral( "InvalidFormat" ), "Feature info format '" + infoFormat + "' is not supported. Possibilities are 'text/plain', 'text/html' or 'text/xml'." ) ); return; } @@ -464,12 +464,12 @@ void QgsHttpRequestHandler::setServiceException( const QgsMapServiceException& e mException = new QgsMapServiceException( ex ); //create Exception DOM document QDomDocument exceptionDoc; - QDomElement serviceExceptionReportElem = exceptionDoc.createElement( "ServiceExceptionReport" ); - serviceExceptionReportElem.setAttribute( "version", "1.3.0" ); - serviceExceptionReportElem.setAttribute( "xmlns", "http://www.opengis.net/ogc" ); + QDomElement serviceExceptionReportElem = exceptionDoc.createElement( QStringLiteral( "ServiceExceptionReport" ) ); + serviceExceptionReportElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.3.0" ) ); + serviceExceptionReportElem.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.opengis.net/ogc" ) ); exceptionDoc.appendChild( serviceExceptionReportElem ); - QDomElement serviceExceptionElem = exceptionDoc.createElement( "ServiceException" ); - serviceExceptionElem.setAttribute( "code", ex.code() ); + QDomElement serviceExceptionElem = exceptionDoc.createElement( QStringLiteral( "ServiceException" ) ); + serviceExceptionElem.setAttribute( QStringLiteral( "code" ), ex.code() ); QDomText messageText = exceptionDoc.createTextNode( ex.message() ); serviceExceptionElem.appendChild( messageText ); serviceExceptionReportElem.appendChild( serviceExceptionElem ); @@ -479,12 +479,12 @@ void QgsHttpRequestHandler::setServiceException( const QgsMapServiceException& e // TODO: check for headersSent() clearHeaders(); clearBody(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } void QgsHttpRequestHandler::setGetPrintResponse( QByteArray* ba ) { - if ( mFormatString.endsWith( ";base64", Qt::CaseInsensitive ) ) + if ( mFormatString.endsWith( QLatin1String( ";base64" ), Qt::CaseInsensitive ) ) { *ba = ba->toBase64(); } @@ -505,10 +505,10 @@ bool QgsHttpRequestHandler::startGetFeatureResponse( QByteArray* ba, const QStri } QString format; - if ( infoFormat == "GeoJSON" ) - format = "text/plain"; + if ( infoFormat == QLatin1String( "GeoJSON" ) ) + format = QStringLiteral( "text/plain" ); else - format = "text/xml"; + format = QStringLiteral( "text/xml" ); setInfoFormat( format ); sendHeaders(); @@ -547,7 +547,7 @@ void QgsHttpRequestHandler::endGetFeatureResponse( QByteArray* ba ) void QgsHttpRequestHandler::setGetCoverageResponse( QByteArray* ba ) { - setHttpResponse( ba, "image/tiff" ); + setHttpResponse( ba, QStringLiteral( "image/tiff" ) ); } void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, QMap& parameters ) @@ -558,7 +558,7 @@ void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, //insert key and value into the map (parameters are separated by &) Q_FOREACH ( const QString& element, request.split( "&" ) ) { - int sepidx = element.indexOf( "=", 0, Qt::CaseSensitive ); + int sepidx = element.indexOf( QLatin1String( "=" ), 0, Qt::CaseSensitive ); if ( sepidx == -1 ) { continue; @@ -568,14 +568,14 @@ void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, key = QUrl::fromPercentEncoding( key.toUtf8() ); //replace encoded special characters and utf-8 encodings QString value = element.mid( sepidx + 1 ); - value.replace( "+", " " ); + value.replace( QLatin1String( "+" ), QLatin1String( " " ) ); value = QUrl::fromPercentEncoding( value.toUtf8() ); //replace encoded special characters and utf-8 encodings - if ( key.compare( "SLD_BODY", Qt::CaseInsensitive ) == 0 ) + if ( key.compare( QLatin1String( "SLD_BODY" ), Qt::CaseInsensitive ) == 0 ) { - key = "SLD"; + key = QStringLiteral( "SLD" ); } - else if ( key.compare( "SLD", Qt::CaseInsensitive ) == 0 ) + else if ( key.compare( QLatin1String( "SLD" ), Qt::CaseInsensitive ) == 0 ) { #if QT_VERSION < 0x050000 QByteArray fileContents; @@ -604,7 +604,7 @@ void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, } value = QUrl::fromPercentEncoding( fileContents ); #else - QgsMessageLog::logMessage( "http and ftp methods not supported with Qt5." ); + QgsMessageLog::logMessage( QStringLiteral( "http and ftp methods not supported with Qt5." ) ); continue; #endif @@ -614,36 +614,36 @@ void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, } //feature info format? - QString infoFormat = parameters.value( "INFO_FORMAT" ); + QString infoFormat = parameters.value( QStringLiteral( "INFO_FORMAT" ) ); if ( !infoFormat.isEmpty() ) { mFormat = infoFormat; } else //capabilities format or GetMap format { - mFormatString = parameters.value( "FORMAT" ); + mFormatString = parameters.value( QStringLiteral( "FORMAT" ) ); QString formatString = mFormatString; if ( !formatString.isEmpty() ) { - QgsMessageLog::logMessage( QString( "formatString is: %1" ).arg( formatString ) ); + QgsMessageLog::logMessage( QStringLiteral( "formatString is: %1" ).arg( formatString ) ); //remove the image/ in front of the format - if ( formatString.contains( "image/png", Qt::CaseInsensitive ) || formatString.compare( "png", Qt::CaseInsensitive ) == 0 ) + if ( formatString.contains( QLatin1String( "image/png" ), Qt::CaseInsensitive ) || formatString.compare( QLatin1String( "png" ), Qt::CaseInsensitive ) == 0 ) { - formatString = "PNG"; + formatString = QStringLiteral( "PNG" ); } - else if ( formatString.contains( "image/jpeg", Qt::CaseInsensitive ) || formatString.contains( "image/jpg", Qt::CaseInsensitive ) - || formatString.compare( "jpg", Qt::CaseInsensitive ) == 0 ) + else if ( formatString.contains( QLatin1String( "image/jpeg" ), Qt::CaseInsensitive ) || formatString.contains( QLatin1String( "image/jpg" ), Qt::CaseInsensitive ) + || formatString.compare( QLatin1String( "jpg" ), Qt::CaseInsensitive ) == 0 ) { - formatString = "JPG"; + formatString = QStringLiteral( "JPG" ); } - else if ( formatString.compare( "svg", Qt::CaseInsensitive ) == 0 ) + else if ( formatString.compare( QLatin1String( "svg" ), Qt::CaseInsensitive ) == 0 ) { - formatString = "SVG"; + formatString = QStringLiteral( "SVG" ); } - else if ( formatString.contains( "pdf", Qt::CaseInsensitive ) ) + else if ( formatString.contains( QLatin1String( "pdf" ), Qt::CaseInsensitive ) ) { - formatString = "PDF"; + formatString = QStringLiteral( "PDF" ); } mFormat = formatString; @@ -654,7 +654,7 @@ void QgsHttpRequestHandler::requestStringToParameterMap( const QString& request, QString QgsHttpRequestHandler::readPostBody() const { - QgsMessageLog::logMessage( "QgsHttpRequestHandler::readPostBody" ); + QgsMessageLog::logMessage( QStringLiteral( "QgsHttpRequestHandler::readPostBody" ) ); char* lengthString = nullptr; int length = 0; char* input = nullptr; @@ -683,13 +683,13 @@ QString QgsHttpRequestHandler::readPostBody() const } else { - QgsMessageLog::logMessage( "input is NULL " ); + QgsMessageLog::logMessage( QStringLiteral( "input is NULL " ) ); } delete [] input; } else { - QgsMessageLog::logMessage( "could not convert CONTENT_LENGTH to int" ); + QgsMessageLog::logMessage( QStringLiteral( "could not convert CONTENT_LENGTH to int" ) ); } } // Used by the tests diff --git a/src/server/qgsinterpolationlayerbuilder.cpp b/src/server/qgsinterpolationlayerbuilder.cpp index 0b61513d5385..ffcf182c05d6 100644 --- a/src/server/qgsinterpolationlayerbuilder.cpp +++ b/src/server/qgsinterpolationlayerbuilder.cpp @@ -56,7 +56,7 @@ QgsMapLayer* QgsInterpolationLayerBuilder::createMapLayer( const QDomElement &el return nullptr; } - QDomNodeList interpolationList = elem.elementsByTagName( "Interpolation" ); + QDomNodeList interpolationList = elem.elementsByTagName( QStringLiteral( "Interpolation" ) ); if ( interpolationList.size() < 1 ) { QgsDebugMsg( "No Interpolation element found" ); @@ -65,14 +65,14 @@ QgsMapLayer* QgsInterpolationLayerBuilder::createMapLayer( const QDomElement &el QDomElement interpolationElem = interpolationList.at( 0 ).toElement(); //create QgsInterpolator object from XML - QDomNodeList tinList = interpolationElem.elementsByTagName( "TINMethod" ); - QDomNodeList idwList = interpolationElem.elementsByTagName( "IDWMethod" ); + QDomNodeList tinList = interpolationElem.elementsByTagName( QStringLiteral( "TINMethod" ) ); + QDomNodeList idwList = interpolationElem.elementsByTagName( QStringLiteral( "IDWMethod" ) ); QgsInterpolator* theInterpolator = nullptr; QList layerDataList; QgsInterpolator::LayerData currentLayerData; currentLayerData.vectorLayer = mVectorLayer; - QDomNodeList propertyNameList = interpolationElem.elementsByTagName( "PropertyName" ); + QDomNodeList propertyNameList = interpolationElem.elementsByTagName( QStringLiteral( "PropertyName" ) ); if ( propertyNameList.size() < 1 ) { currentLayerData.zCoordInterpolation = true; @@ -114,7 +114,7 @@ QgsMapLayer* QgsInterpolationLayerBuilder::createMapLayer( const QDomElement &el //Resolution int nCols, nRows; - QDomNodeList resolutionNodeList = elem.elementsByTagName( "Resolution" ); + QDomNodeList resolutionNodeList = elem.elementsByTagName( QStringLiteral( "Resolution" ) ); if ( resolutionNodeList.size() < 1 ) { //use default values... @@ -124,8 +124,8 @@ QgsMapLayer* QgsInterpolationLayerBuilder::createMapLayer( const QDomElement &el else { QDomElement resolutionElem = resolutionNodeList.at( 0 ).toElement(); - nCols = resolutionElem.attribute( "ncols" ).toInt(); - nRows = resolutionElem.attribute( "nrows" ).toInt(); + nCols = resolutionElem.attribute( QStringLiteral( "ncols" ) ).toInt(); + nRows = resolutionElem.attribute( QStringLiteral( "nrows" ) ).toInt(); if ( nCols == 0 || nRows == 0 ) { QgsDebugMsg( "Reading of resolution failed" ); diff --git a/src/server/qgsmaprenderer.cpp b/src/server/qgsmaprenderer.cpp index 124c1d10f7eb..7f48c2f8b9d8 100644 --- a/src/server/qgsmaprenderer.cpp +++ b/src/server/qgsmaprenderer.cpp @@ -302,10 +302,10 @@ void QgsMapRenderer::render( QPainter* painter, double* forceWidthScale ) // set selection color QgsProject* prj = QgsProject::instance(); - int myRed = prj->readNumEntry( "Gui", "/SelectionColorRedPart", 255 ); - int myGreen = prj->readNumEntry( "Gui", "/SelectionColorGreenPart", 255 ); - int myBlue = prj->readNumEntry( "Gui", "/SelectionColorBluePart", 0 ); - int myAlpha = prj->readNumEntry( "Gui", "/SelectionColorAlphaPart", 255 ); + int myRed = prj->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorRedPart" ), 255 ); + int myGreen = prj->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorGreenPart" ), 255 ); + int myBlue = prj->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorBluePart" ), 0 ); + int myAlpha = prj->readNumEntry( QStringLiteral( "Gui" ), QStringLiteral( "/SelectionColorAlphaPart" ), 255 ); mRenderContext.setSelectionColor( QColor( myRed, myGreen, myBlue, myAlpha ) ); //calculate scale factor @@ -471,7 +471,7 @@ void QgsMapRenderer::render( QPainter* painter, double* forceWidthScale ) } mypFlattenedImage->fill( 0 ); QPainter * mypPainter = new QPainter( mypFlattenedImage ); - if ( mySettings.value( "/qgis/enable_anti_aliasing", true ).toBool() ) + if ( mySettings.value( QStringLiteral( "/qgis/enable_anti_aliasing" ), true ).toBool() ) { mypPainter->setRenderHint( QPainter::Antialiasing ); } @@ -816,7 +816,7 @@ QgsPoint QgsMapRenderer::layerToMapCoordinates( QgsMapLayer* theLayer, QgsPoint } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ) ); } } else @@ -840,7 +840,7 @@ QgsRectangle QgsMapRenderer::layerToMapCoordinates( QgsMapLayer* theLayer, QgsRe } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ) ); } } else @@ -862,7 +862,7 @@ QgsPoint QgsMapRenderer::mapToLayerCoordinates( QgsMapLayer* theLayer, QgsPoint } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ) ); } } else @@ -884,7 +884,7 @@ QgsRectangle QgsMapRenderer::mapToLayerCoordinates( QgsMapLayer* theLayer, QgsRe } catch ( QgsCsException &cse ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( cse.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( cse.what() ) ); } } return rect; @@ -981,25 +981,25 @@ bool QgsMapRenderer::readXml( QDomNode & theNode ) tmpSettings.readXml( theNode ); //load coordinate transform into mLayerCoordinateTransformInfo.clear(); - QDomElement layerCoordTransformInfoElem = theNode.firstChildElement( "layer_coordinate_transform_info" ); + QDomElement layerCoordTransformInfoElem = theNode.firstChildElement( QStringLiteral( "layer_coordinate_transform_info" ) ); if ( !layerCoordTransformInfoElem.isNull() ) { - QDomNodeList layerCoordinateTransformList = layerCoordTransformInfoElem.elementsByTagName( "layer_coordinate_transform" ); + QDomNodeList layerCoordinateTransformList = layerCoordTransformInfoElem.elementsByTagName( QStringLiteral( "layer_coordinate_transform" ) ); QDomElement layerCoordTransformElem; for ( int i = 0; i < layerCoordinateTransformList.size(); ++i ) { layerCoordTransformElem = layerCoordinateTransformList.at( i ).toElement(); - QString layerId = layerCoordTransformElem.attribute( "layerid" ); + QString layerId = layerCoordTransformElem.attribute( QStringLiteral( "layerid" ) ); if ( layerId.isEmpty() ) { continue; } QgsLayerCoordinateTransform lct; - lct.srcAuthId = layerCoordTransformElem.attribute( "srcAuthId" ); - lct.destAuthId = layerCoordTransformElem.attribute( "destAuthId" ); - lct.srcDatumTransform = layerCoordTransformElem.attribute( "srcDatumTransform", "-1" ).toInt(); - lct.destDatumTransform = layerCoordTransformElem.attribute( "destDatumTransform", "-1" ).toInt(); + lct.srcAuthId = layerCoordTransformElem.attribute( QStringLiteral( "srcAuthId" ) ); + lct.destAuthId = layerCoordTransformElem.attribute( QStringLiteral( "destAuthId" ) ); + lct.srcDatumTransform = layerCoordTransformElem.attribute( QStringLiteral( "srcDatumTransform" ), QStringLiteral( "-1" ) ).toInt(); + lct.destDatumTransform = layerCoordTransformElem.attribute( QStringLiteral( "destDatumTransform" ), QStringLiteral( "-1" ) ).toInt(); mLayerCoordinateTransformInfo.insert( layerId, lct ); } } @@ -1026,16 +1026,16 @@ bool QgsMapRenderer::writeXml( QDomNode & theNode, QDomDocument & theDoc ) tmpSettings.writeXml( theNode, theDoc ); // layer coordinate transform infos - QDomElement layerCoordTransformInfo = theDoc.createElement( "layer_coordinate_transform_info" ); + QDomElement layerCoordTransformInfo = theDoc.createElement( QStringLiteral( "layer_coordinate_transform_info" ) ); QHash< QString, QgsLayerCoordinateTransform >::const_iterator coordIt = mLayerCoordinateTransformInfo.constBegin(); for ( ; coordIt != mLayerCoordinateTransformInfo.constEnd(); ++coordIt ) { - QDomElement layerCoordTransformElem = theDoc.createElement( "layer_coordinate_transform" ); - layerCoordTransformElem.setAttribute( "layerid", coordIt.key() ); - layerCoordTransformElem.setAttribute( "srcAuthId", coordIt->srcAuthId ); - layerCoordTransformElem.setAttribute( "destAuthId", coordIt->destAuthId ); - layerCoordTransformElem.setAttribute( "srcDatumTransform", QString::number( coordIt->srcDatumTransform ) ); - layerCoordTransformElem.setAttribute( "destDatumTransform", QString::number( coordIt->destDatumTransform ) ); + QDomElement layerCoordTransformElem = theDoc.createElement( QStringLiteral( "layer_coordinate_transform" ) ); + layerCoordTransformElem.setAttribute( QStringLiteral( "layerid" ), coordIt.key() ); + layerCoordTransformElem.setAttribute( QStringLiteral( "srcAuthId" ), coordIt->srcAuthId ); + layerCoordTransformElem.setAttribute( QStringLiteral( "destAuthId" ), coordIt->destAuthId ); + layerCoordTransformElem.setAttribute( QStringLiteral( "srcDatumTransform" ), QString::number( coordIt->srcDatumTransform ) ); + layerCoordTransformElem.setAttribute( QStringLiteral( "destDatumTransform" ), QString::number( coordIt->destDatumTransform ) ); layerCoordTransformInfo.appendChild( layerCoordTransformElem ); } theNode.appendChild( layerCoordTransformInfo ); @@ -1129,10 +1129,10 @@ void QgsMapRenderer::readDefaultDatumTransformations() if ( envChar ) { QString envString( envChar ); - QStringList transformSplit = envString.split( ";" ); + QStringList transformSplit = envString.split( QStringLiteral( ";" ) ); for ( int i = 0; i < transformSplit.size(); ++i ) { - QStringList slashSplit = transformSplit.at( i ).split( "/" ); + QStringList slashSplit = transformSplit.at( i ).split( QStringLiteral( "/" ) ); if ( slashSplit.size() < 4 ) { continue; diff --git a/src/server/qgsmslayerbuilder.cpp b/src/server/qgsmslayerbuilder.cpp index 4a392837a261..23ffa293693e 100644 --- a/src/server/qgsmslayerbuilder.cpp +++ b/src/server/qgsmslayerbuilder.cpp @@ -46,25 +46,25 @@ QString QgsMSLayerBuilder::layerNameFromUri( const QString& uri ) const } //http based? - if ( uri.startsWith( "http", Qt::CaseInsensitive ) ) + if ( uri.startsWith( QLatin1String( "http" ), Qt::CaseInsensitive ) ) { return uri; } //database? - if ( uri.contains( "dbname" ) ) + if ( uri.contains( QLatin1String( "dbname" ) ) ) { //take tablename Q_FOREACH ( const QString& token, uri.split( " " ) ) { - if ( token.startsWith( "table" ) ) + if ( token.startsWith( QLatin1String( "table" ) ) ) { - return token.section( "=", 1, 1 ); + return token.section( QStringLiteral( "=" ), 1, 1 ); } } } - return ""; + return QLatin1String( "" ); } QString QgsMSLayerBuilder::createTempFile() const @@ -82,7 +82,7 @@ QString QgsMSLayerBuilder::createTempFile() const if ( !tempFileDir.exists() ) //make sure the directory exists { QDir tmpDir( QDir::tempPath() ); - tmpDir.mkdir( "qgis_wms_serv" ); + tmpDir.mkdir( QStringLiteral( "qgis_wms_serv" ) ); } tempFilePath = QDir::tempPath() + "/qgis_wms_serv/" + tempFileName; return tempFilePath; diff --git a/src/server/qgsmslayercache.cpp b/src/server/qgsmslayercache.cpp index 8e9ac788046b..ec7554175f34 100644 --- a/src/server/qgsmslayercache.cpp +++ b/src/server/qgsmslayercache.cpp @@ -61,7 +61,7 @@ QgsMSLayerCache::~QgsMSLayerCache() void QgsMSLayerCache::insertLayer( const QString& url, const QString& layerName, QgsMapLayer* layer, const QString& configFile, const QList& tempFiles ) { - QgsMessageLog::logMessage( "Layer cache: insert Layer '" + layerName + "' configFile: " + configFile, "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Layer cache: insert Layer '" + layerName + "' configFile: " + configFile, QStringLiteral( "Server" ), QgsMessageLog::INFO ); if ( mEntries.size() > qMax( mDefaultMaxLayers, mProjectMaxLayers ) ) //force cache layer examination after 10 inserted layers { updateEntries(); @@ -100,7 +100,7 @@ QgsMapLayer* QgsMSLayerCache::searchLayer( const QString& url, const QString& la QPair urlNamePair = qMakePair( url, layerName ); if ( !mEntries.contains( urlNamePair ) ) { - QgsMessageLog::logMessage( "Layer '" + layerName + "' configFile: " + configFile + " not found in layer cache'", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Layer '" + layerName + "' configFile: " + configFile + " not found in layer cache'", QStringLiteral( "Server" ), QgsMessageLog::INFO ); return nullptr; } else @@ -112,18 +112,18 @@ QgsMapLayer* QgsMSLayerCache::searchLayer( const QString& url, const QString& la if ( configFile.isEmpty() || layerIt->configFile == configFile ) { layerIt->lastUsedTime = time( nullptr ); - QgsMessageLog::logMessage( "Layer '" + layerName + "' configFile: " + configFile + " found in layer cache", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Layer '" + layerName + "' configFile: " + configFile + " found in layer cache", QStringLiteral( "Server" ), QgsMessageLog::INFO ); return layerIt->layerPointer; } } - QgsMessageLog::logMessage( "Layer '" + layerName + "' configFile: " + configFile + " not found in layer cache'", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Layer '" + layerName + "' configFile: " + configFile + " not found in layer cache'", QStringLiteral( "Server" ), QgsMessageLog::INFO ); return nullptr; } } void QgsMSLayerCache::removeProjectFileLayers( const QString& project ) { - QgsMessageLog::logMessage( "Removing cache entries for project file: " + project, "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Removing cache entries for project file: " + project, QStringLiteral( "Server" ), QgsMessageLog::INFO ); QVector< QPair< QString, QString > > removeEntries; QVector< QgsMSLayerCacheEntry > removeEntriesValues; @@ -142,7 +142,7 @@ void QgsMSLayerCache::removeProjectFileLayers( const QString& project ) { const QgsMSLayerCacheEntry& removeEntry = removeEntriesValues.at( i ); const QPair< QString, QString > removeKey = removeEntries.at( i ); - QgsMessageLog::logMessage( "Removing cache entry for url:" + removeKey.first + " layerName:" + removeKey.second + " project file:" + project, "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Removing cache entry for url:" + removeKey.first + " layerName:" + removeKey.second + " project file:" + project, QStringLiteral( "Server" ), QgsMessageLog::INFO ); mEntries.remove( removeKey, removeEntry ); } } @@ -182,7 +182,7 @@ void QgsMSLayerCache::removeLeastUsedEntry() } } - QgsMessageLog::logMessage( "Removing last accessed layer '" + lowest_it.value().layerPointer->name() + "' project file " + lowest_it.value().configFile + " from cache" , "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Removing last accessed layer '" + lowest_it.value().layerPointer->name() + "' project file " + lowest_it.value().configFile + " from cache" , QStringLiteral( "Server" ), QgsMessageLog::INFO ); freeEntryRessources( *lowest_it ); mEntries.erase( lowest_it ); } @@ -225,11 +225,11 @@ void QgsMSLayerCache::freeEntryRessources( QgsMSLayerCacheEntry& entry ) void QgsMSLayerCache::logCacheContents() const { - QgsMessageLog::logMessage( "Layer cache contents:" , "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "Layer cache contents:" ) , QStringLiteral( "Server" ), QgsMessageLog::INFO ); QHash, QgsMSLayerCacheEntry>::const_iterator it = mEntries.constBegin(); for ( ; it != mEntries.constEnd(); ++it ) { - QgsMessageLog::logMessage( "Url: " + it.value().url + " Layer name: " + it.value().layerPointer->name() + " Project: " + it.value().configFile, "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Url: " + it.value().url + " Layer name: " + it.value().layerPointer->name() + " Project: " + it.value().configFile, QStringLiteral( "Server" ), QgsMessageLog::INFO ); } } diff --git a/src/server/qgsmsutils.cpp b/src/server/qgsmsutils.cpp index 54f992bedbd3..99b8f922f018 100644 --- a/src/server/qgsmsutils.cpp +++ b/src/server/qgsmsutils.cpp @@ -39,11 +39,11 @@ QString QgsMSUtils::createTempFilePath() //on windows, store the temporary file in current_path/tmp directory, //on unix, store it in /tmp/qgis_wms_serv #ifndef Q_OS_WIN - QDir tempFileDir( "/tmp/qgis_map_serv" ); + QDir tempFileDir( QStringLiteral( "/tmp/qgis_map_serv" ) ); if ( !tempFileDir.exists() ) //make sure the directory exists { - QDir tmpDir( "/tmp" ); - tmpDir.mkdir( "qgis_map_serv" ); + QDir tmpDir( QStringLiteral( "/tmp" ) ); + tmpDir.mkdir( QStringLiteral( "qgis_map_serv" ) ); } tempFilePath = "/tmp/qgis_map_serv/" + tempFileName; #else @@ -60,7 +60,7 @@ QString QgsMSUtils::createTempFilePath() while ( testFile.exists() ) { //change the name - tempFilePath += "1"; + tempFilePath += QLatin1String( "1" ); testFile.setFile( tempFilePath ); } QgsDebugMsg( tempFilePath ); diff --git a/src/server/qgsowsserver.cpp b/src/server/qgsowsserver.cpp index 5768aa08df90..9cae708eee35 100644 --- a/src/server/qgsowsserver.cpp +++ b/src/server/qgsowsserver.cpp @@ -41,7 +41,7 @@ void QgsOWSServer::applyAccessControlLayerFilters( QgsMapLayer* mapLayer, QHash< } if ( !layer->setSubsetString( sql ) ) { - QgsMessageLog::logMessage( "Layer does not support Subset String" ); + QgsMessageLog::logMessage( QStringLiteral( "Layer does not support Subset String" ) ); } } } diff --git a/src/server/qgspostrequesthandler.cpp b/src/server/qgspostrequesthandler.cpp index 842d79729ca4..e391603191e1 100644 --- a/src/server/qgspostrequesthandler.cpp +++ b/src/server/qgspostrequesthandler.cpp @@ -30,7 +30,7 @@ QgsPostRequestHandler::~QgsPostRequestHandler() void QgsPostRequestHandler::parseInput() { - QgsMessageLog::logMessage( "QgsPostRequestHandler::parseInput" ); + QgsMessageLog::logMessage( QStringLiteral( "QgsPostRequestHandler::parseInput" ) ); QString inputString = readPostBody(); QgsMessageLog::logMessage( inputString ); @@ -44,7 +44,7 @@ void QgsPostRequestHandler::parseInput() { queryString = QString( qs ); requestStringToParameterMap( queryString, getParameters ); - mapParameter = getParameters.value( "MAP" ); + mapParameter = getParameters.value( QStringLiteral( "MAP" ) ); } QDomDocument doc; @@ -56,7 +56,7 @@ void QgsPostRequestHandler::parseInput() char* requestMethod = getenv( "REQUEST_METHOD" ); if ( requestMethod && strcmp( requestMethod, "POST" ) == 0 ) { - QgsMessageLog::logMessage( QString( "Error at line %1, column %2: %3." ).arg( line ).arg( column ).arg( errorMsg ) ); + QgsMessageLog::logMessage( QStringLiteral( "Error at line %1, column %2: %3." ).arg( line ).arg( column ).arg( errorMsg ) ); } requestStringToParameterMap( inputString, mParameterMap ); } @@ -71,23 +71,23 @@ void QgsPostRequestHandler::parseInput() } else { - QgsMessageLog::logMessage( "error, no query string found but a QDomDocument" ); + QgsMessageLog::logMessage( QStringLiteral( "error, no query string found but a QDomDocument" ) ); return; //no query string? something must be wrong... } requestStringToParameterMap( queryString, mParameterMap ); QDomElement docElem = doc.documentElement(); - if ( docElem.hasAttribute( "version" ) ) - mParameterMap.insert( "VERSION", docElem.attribute( "version" ) ); - if ( docElem.hasAttribute( "service" ) ) - mParameterMap.insert( "SERVICE", docElem.attribute( "service" ) ); - mParameterMap.insert( "REQUEST", docElem.tagName() ); - mParameterMap.insert( "REQUEST_BODY", inputString ); + if ( docElem.hasAttribute( QStringLiteral( "version" ) ) ) + mParameterMap.insert( QStringLiteral( "VERSION" ), docElem.attribute( QStringLiteral( "version" ) ) ); + if ( docElem.hasAttribute( QStringLiteral( "service" ) ) ) + mParameterMap.insert( QStringLiteral( "SERVICE" ), docElem.attribute( QStringLiteral( "service" ) ) ); + mParameterMap.insert( QStringLiteral( "REQUEST" ), docElem.tagName() ); + mParameterMap.insert( QStringLiteral( "REQUEST_BODY" ), inputString ); } - if ( !mapParameter.isEmpty() && !mParameterMap.contains( "MAP" ) ) + if ( !mapParameter.isEmpty() && !mParameterMap.contains( QStringLiteral( "MAP" ) ) ) { - mParameterMap.insert( "MAP", mapParameter ); + mParameterMap.insert( QStringLiteral( "MAP" ), mapParameter ); } } diff --git a/src/server/qgsremotedatasourcebuilder.cpp b/src/server/qgsremotedatasourcebuilder.cpp index 3b6f758dadf5..8fd3ae7045fe 100644 --- a/src/server/qgsremotedatasourcebuilder.cpp +++ b/src/server/qgsremotedatasourcebuilder.cpp @@ -39,11 +39,11 @@ QgsRemoteDataSourceBuilder::~QgsRemoteDataSourceBuilder() QgsMapLayer* QgsRemoteDataSourceBuilder::createMapLayer( const QDomElement& elem, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching ) const { QgsMapLayer* theLayer = nullptr; - if ( elem.tagName() == "RemoteRDS" ) + if ( elem.tagName() == QLatin1String( "RemoteRDS" ) ) { theLayer = rasterLayerFromRemoteRDS( elem, layerName, filesToRemove, layersToRemove, allowCaching ); } - else if ( elem.tagName() == "RemoteVDS" ) + else if ( elem.tagName() == QLatin1String( "RemoteVDS" ) ) { theLayer = vectorLayerFromRemoteVDS( elem, layerName, filesToRemove, layersToRemove, allowCaching ); } @@ -103,10 +103,10 @@ QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDom Q_UNUSED( layerName ); Q_UNUSED( allowCaching ); QString providerString; - QString formatString = remoteVDSElem.attribute( "format" ); - if ( formatString.compare( "gml", Qt::CaseInsensitive ) == 0 ) + QString formatString = remoteVDSElem.attribute( QStringLiteral( "format" ) ); + if ( formatString.compare( QLatin1String( "gml" ), Qt::CaseInsensitive ) == 0 ) { - providerString = "WFS"; + providerString = QStringLiteral( "WFS" ); } else { @@ -140,7 +140,7 @@ QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDom //create vector layer //SOS has a special datasource key... - if ( formatString.compare( "SOS", Qt::CaseInsensitive ) == 0 ) + if ( formatString.compare( QLatin1String( "SOS" ), Qt::CaseInsensitive ) == 0 ) { QString url = "url=" + tmpFile->fileName() + " method=FILE xml="; vl = new QgsVectorLayer( url, layerNameFromUri( tmpFile->fileName() ), providerString ); diff --git a/src/server/qgsremoteowsbuilder.cpp b/src/server/qgsremoteowsbuilder.cpp index d597a70ae44e..3183fb36fc5e 100644 --- a/src/server/qgsremoteowsbuilder.cpp +++ b/src/server/qgsremoteowsbuilder.cpp @@ -57,7 +57,7 @@ QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer( } //parse service element - QDomNode serviceNode = elem.namedItem( "Service" ); + QDomNode serviceNode = elem.namedItem( QStringLiteral( "Service" ) ); if ( serviceNode.isNull() ) { QgsDebugMsg( "No node found, returning 0" ); @@ -65,7 +65,7 @@ QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer( } //parse OnlineResource element - QDomNode onlineResourceNode = elem.namedItem( "OnlineResource" ); + QDomNode onlineResourceNode = elem.namedItem( QStringLiteral( "OnlineResource" ) ); if ( onlineResourceNode.isNull() ) { QgsDebugMsg( "No element, returning 0" ); @@ -74,17 +74,17 @@ QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer( //get uri QDomElement onlineResourceElement = onlineResourceNode.toElement(); - QString url = onlineResourceElement.attribute( "href" ); + QString url = onlineResourceElement.attribute( QStringLiteral( "href" ) ); QgsMapLayer* result = nullptr; QString serviceName = serviceNode.toElement().text(); //append missing ? or & at the end of the url, but only for WFS and WMS - if ( serviceName == "WFS" || serviceName == "WMS" ) + if ( serviceName == QLatin1String( "WFS" ) || serviceName == QLatin1String( "WMS" ) ) { - if ( !url.endsWith( "?" ) && !url.endsWith( "&" ) ) + if ( !url.endsWith( QLatin1String( "?" ) ) && !url.endsWith( QLatin1String( "&" ) ) ) { - if ( url.contains( "?" ) ) + if ( url.contains( QLatin1String( "?" ) ) ) { url.append( "&" ); } @@ -96,10 +96,10 @@ QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer( } - if ( serviceName == "WFS" ) + if ( serviceName == QLatin1String( "WFS" ) ) { //support for old format where type is explicitly given and not part of url - QString tname = onlineResourceElement.attribute( "type" ); + QString tname = onlineResourceElement.attribute( QStringLiteral( "type" ) ); if ( !tname.isEmpty() ) { url.append( "SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=" + tname ); @@ -113,7 +113,7 @@ QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer( { return result; } - result = new QgsVectorLayer( url, layerNameFromUri( url ), "WFS" ); + result = new QgsVectorLayer( url, layerNameFromUri( url ), QStringLiteral( "WFS" ) ); if ( result->isValid() ) { if ( allowCaching ) @@ -126,16 +126,16 @@ QgsMapLayer* QgsRemoteOWSBuilder::createMapLayer( } } } - else if ( serviceName == "WMS" ) + else if ( serviceName == QLatin1String( "WMS" ) ) { result = wmsLayerFromUrl( url, layerName, layersToRemove, allowCaching ); } - else if ( serviceName == "WCS" ) + else if ( serviceName == QLatin1String( "WCS" ) ) { QgsDebugMsg( "Trying to get WCS layer" ); result = wcsLayerFromUrl( url, layerName, filesToRemove, layersToRemove ); } - else if ( serviceName == "SOS" ) + else if ( serviceName == QLatin1String( "SOS" ) ) { result = sosLayer( elem, url, layerName, layersToRemove, allowCaching ); } @@ -170,36 +170,36 @@ QgsRasterLayer* QgsRemoteOWSBuilder::wmsLayerFromUrl( const QString& url, const return result; } - QStringList urlList = url.split( "?" ); + QStringList urlList = url.split( QStringLiteral( "?" ) ); if ( urlList.size() < 2 ) { return nullptr; } baseUrl = urlList.at( 0 ); - QStringList paramList = urlList.at( 1 ).split( "&" ); + QStringList paramList = urlList.at( 1 ).split( QStringLiteral( "&" ) ); QStringList::const_iterator paramIt; for ( paramIt = paramList.constBegin(); paramIt != paramList.constEnd(); ++paramIt ) { - if ( paramIt->startsWith( "http", Qt::CaseInsensitive ) ) + if ( paramIt->startsWith( QLatin1String( "http" ), Qt::CaseInsensitive ) ) { - baseUrl = paramIt->split( "=" ).at( 1 ); + baseUrl = paramIt->split( QStringLiteral( "=" ) ).at( 1 ); } - else if ( paramIt->startsWith( "FORMAT", Qt::CaseInsensitive ) ) + else if ( paramIt->startsWith( QLatin1String( "FORMAT" ), Qt::CaseInsensitive ) ) { - format = paramIt->split( "=" ).at( 1 ); + format = paramIt->split( QStringLiteral( "=" ) ).at( 1 ); } - else if ( paramIt->startsWith( "CRS", Qt::CaseInsensitive ) ) + else if ( paramIt->startsWith( QLatin1String( "CRS" ), Qt::CaseInsensitive ) ) { - crs = paramIt->split( "=" ).at( 1 ); + crs = paramIt->split( QStringLiteral( "=" ) ).at( 1 ); } - else if ( paramIt->startsWith( "LAYERS", Qt::CaseInsensitive ) ) + else if ( paramIt->startsWith( QLatin1String( "LAYERS" ), Qt::CaseInsensitive ) ) { - layerList = paramIt->split( "=" ).at( 1 ).split( "," ); + layerList = paramIt->split( QStringLiteral( "=" ) ).at( 1 ).split( QStringLiteral( "," ) ); } - else if ( paramIt->startsWith( "STYLES", Qt::CaseInsensitive ) ) + else if ( paramIt->startsWith( QLatin1String( "STYLES" ), Qt::CaseInsensitive ) ) { - styleList = paramIt->split( "=" ).at( 1 ).split( "," ); + styleList = paramIt->split( QStringLiteral( "=" ) ).at( 1 ).split( QStringLiteral( "," ) ); } } @@ -210,12 +210,12 @@ QgsRasterLayer* QgsRemoteOWSBuilder::wmsLayerFromUrl( const QString& url, const QgsDebugMsg( "styleList first item: " + styleList.at( 0 ) ); QgsDataSourceUri uri; - uri.setParam( "url", baseUrl ); - uri.setParam( "format", format ); - uri.setParam( "crs", crs ); - uri.setParam( "layers", layerList ); - uri.setParam( "styles", styleList ); - result = new QgsRasterLayer( uri.encodedUri(), "", QString( "wms" ) ); + uri.setParam( QStringLiteral( "url" ), baseUrl ); + uri.setParam( QStringLiteral( "format" ), format ); + uri.setParam( QStringLiteral( "crs" ), crs ); + uri.setParam( QStringLiteral( "layers" ), layerList ); + uri.setParam( QStringLiteral( "styles" ), styleList ); + result = new QgsRasterLayer( uri.encodedUri(), QLatin1String( "" ), QStringLiteral( "wms" ) ); if ( !result->isValid() ) { return nullptr; @@ -371,7 +371,7 @@ QgsRasterLayer* QgsRemoteOWSBuilder::wcsLayerFromUrl( const QString &url, QgsVectorLayer* QgsRemoteOWSBuilder::sosLayer( const QDomElement& remoteOWSElem, const QString& url, const QString& layerName, QList& layersToRemove, bool allowCaching ) const { //url for sos provider is: "url=... method=... xml=.... - QString method = remoteOWSElem.attribute( "method", "POST" ); //possible GET/POST/SOAP + QString method = remoteOWSElem.attribute( QStringLiteral( "method" ), QStringLiteral( "POST" ) ); //possible GET/POST/SOAP //search for node that is sibling of remoteOSW element //parent element of (normally ) @@ -385,14 +385,14 @@ QgsVectorLayer* QgsRemoteOWSBuilder::sosLayer( const QDomElement& remoteOWSElem, //Root element of the request (can be 'GetObservation' or 'GetObservationById' at the moment, probably also 'GetFeatureOfInterest' or 'GetFeatureOfInterestTime' in the future) QDomElement requestRootElem; - QDomNodeList getObservationNodeList = parentElem.elementsByTagName( "GetObservation" ); + QDomNodeList getObservationNodeList = parentElem.elementsByTagName( QStringLiteral( "GetObservation" ) ); if ( !getObservationNodeList.isEmpty() ) { requestRootElem = getObservationNodeList.at( 0 ).toElement(); } else //GetObservationById? { - QDomNodeList getObservationByIdNodeList = parentElem.elementsByTagName( "GetObservationById" ); + QDomNodeList getObservationByIdNodeList = parentElem.elementsByTagName( QStringLiteral( "GetObservationById" ) ); if ( !getObservationByIdNodeList.isEmpty() ) { requestRootElem = getObservationByIdNodeList.at( 0 ).toElement(); @@ -421,7 +421,7 @@ QgsVectorLayer* QgsRemoteOWSBuilder::sosLayer( const QDomElement& remoteOWSElem, } } - sosLayer = new QgsVectorLayer( providerUrl, "Sensor layer", "SOS" ); + sosLayer = new QgsVectorLayer( providerUrl, QStringLiteral( "Sensor layer" ), QStringLiteral( "SOS" ) ); if ( !sosLayer->isValid() ) { diff --git a/src/server/qgssentdatasourcebuilder.cpp b/src/server/qgssentdatasourcebuilder.cpp index 0b76deebfb97..ca09f1fba521 100644 --- a/src/server/qgssentdatasourcebuilder.cpp +++ b/src/server/qgssentdatasourcebuilder.cpp @@ -42,11 +42,11 @@ QgsMapLayer* QgsSentDataSourceBuilder::createMapLayer( const QDomElement& elem, { Q_UNUSED( layerName ); Q_UNUSED( allowCaching ); - if ( elem.tagName() == "SentRDS" ) + if ( elem.tagName() == QLatin1String( "SentRDS" ) ) { return rasterLayerFromSentRDS( elem, filesToRemove, layersToRemove ); } - else if ( elem.tagName() == "SentVDS" ) + else if ( elem.tagName() == QLatin1String( "SentVDS" ) ) { return vectorLayerFromSentVDS( elem, filesToRemove, layersToRemove ); } @@ -55,7 +55,7 @@ QgsMapLayer* QgsSentDataSourceBuilder::createMapLayer( const QDomElement& elem, QgsVectorLayer* QgsSentDataSourceBuilder::vectorLayerFromSentVDS( const QDomElement& sentVDSElem, QList& filesToRemove, QList& layersToRemove ) const { - if ( sentVDSElem.attribute( "format" ) == "GML" ) + if ( sentVDSElem.attribute( QStringLiteral( "format" ) ) == QLatin1String( "GML" ) ) { QTemporaryFile* tmpFile = new QTemporaryFile(); if ( tmpFile->open() ) @@ -70,7 +70,7 @@ QgsVectorLayer* QgsSentDataSourceBuilder::vectorLayerFromSentVDS( const QDomElem return nullptr; } - QgsVectorLayer* theVectorLayer = new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), "WFS" ); + QgsVectorLayer* theVectorLayer = new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), QStringLiteral( "WFS" ) ); if ( !theVectorLayer || !theVectorLayer->isValid() ) { QgsDebugMsg( "invalid maplayer" ); @@ -101,9 +101,9 @@ QgsRasterLayer* QgsSentDataSourceBuilder::rasterLayerFromSentRDS( const QDomElem QTemporaryFile* tmpFile = new QTemporaryFile(); - QString encoding = sentRDSElem.attribute( "encoding" ); + QString encoding = sentRDSElem.attribute( QStringLiteral( "encoding" ) ); - if ( encoding == "base64" ) + if ( encoding == QLatin1String( "base64" ) ) { if ( tmpFile->open() ) { diff --git a/src/server/qgsserver.cpp b/src/server/qgsserver.cpp index 36ad91d9d38d..72e54ee0ed44 100644 --- a/src/server/qgsserver.cpp +++ b/src/server/qgsserver.cpp @@ -93,14 +93,14 @@ QgsServer::~QgsServer() QString& QgsServer::serverName() { - static QString* name = new QString( "qgis_server" ); + static QString* name = new QString( QStringLiteral( "qgis_server" ) ); return *name; } QFileInfo QgsServer::defaultAdminSLD() { - return QFileInfo( "admin.sld" ); + return QFileInfo( QStringLiteral( "admin.sld" ) ); } @@ -112,16 +112,16 @@ void QgsServer::setupNetworkAccessManager() QSettings settings; QgsNetworkAccessManager *nam = QgsNetworkAccessManager::instance(); QNetworkDiskCache *cache = new QNetworkDiskCache( nullptr ); - QString cacheDirectory = settings.value( "cache/directory" ).toString(); + QString cacheDirectory = settings.value( QStringLiteral( "cache/directory" ) ).toString(); if ( cacheDirectory.isEmpty() ) cacheDirectory = QgsApplication::qgisSettingsDirPath() + "cache"; - qint64 cacheSize = settings.value( "cache/size", 50 * 1024 * 1024 ).toULongLong(); - QgsMessageLog::logMessage( QString( "setCacheDirectory: %1" ).arg( cacheDirectory ), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( QString( "setMaximumCacheSize: %1" ).arg( cacheSize ), "Server", QgsMessageLog::INFO ); + qint64 cacheSize = settings.value( QStringLiteral( "cache/size" ), 50 * 1024 * 1024 ).toULongLong(); + QgsMessageLog::logMessage( QStringLiteral( "setCacheDirectory: %1" ).arg( cacheDirectory ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "setMaximumCacheSize: %1" ).arg( cacheSize ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); cache->setCacheDirectory( cacheDirectory ); cache->setMaximumCacheSize( cacheSize ); - QgsMessageLog::logMessage( QString( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( QString( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "cacheDirectory: %1" ).arg( cache->cacheDirectory() ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "maximumCacheSize: %1" ).arg( cache->maximumCacheSize() ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); nam->setCache( cache ); } @@ -162,11 +162,11 @@ QFileInfo QgsServer::defaultProjectFile() QDir currentDir; fprintf( FCGI_stderr, "current directory: %s\n", currentDir.absolutePath().toUtf8().constData() ); QStringList nameFilterList; - nameFilterList << "*.qgs"; + nameFilterList << QStringLiteral( "*.qgs" ); QFileInfoList projectFiles = currentDir.entryInfoList( nameFilterList, QDir::Files, QDir::Name ); for ( int x = 0; x < projectFiles.size(); x++ ) { - QgsMessageLog::logMessage( projectFiles.at( x ).absoluteFilePath(), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( projectFiles.at( x ).absoluteFilePath(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( projectFiles.size() < 1 ) { @@ -190,7 +190,7 @@ void QgsServer::printRequestParameters( const QMap< QString, QString>& parameter QMap< QString, QString>::const_iterator pIt = parameterMap.constBegin(); for ( ; pIt != parameterMap.constEnd(); ++pIt ) { - QgsMessageLog::logMessage( pIt.key() + ":" + pIt.value(), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( pIt.key() + ":" + pIt.value(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } } @@ -199,46 +199,46 @@ void QgsServer::printRequestParameters( const QMap< QString, QString>& parameter */ void QgsServer::printRequestInfos() { - QgsMessageLog::logMessage( "********************new request***************", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "********************new request***************" ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); if ( getenv( "REMOTE_ADDR" ) ) { - QgsMessageLog::logMessage( "remote ip: " + QString( getenv( "REMOTE_ADDR" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "remote ip: " + QString( getenv( "REMOTE_ADDR" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "REMOTE_HOST" ) ) { - QgsMessageLog::logMessage( "remote ip: " + QString( getenv( "REMOTE_HOST" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "remote ip: " + QString( getenv( "REMOTE_HOST" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "REMOTE_USER" ) ) { - QgsMessageLog::logMessage( "remote user: " + QString( getenv( "REMOTE_USER" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "remote user: " + QString( getenv( "REMOTE_USER" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "REMOTE_IDENT" ) ) { - QgsMessageLog::logMessage( "REMOTE_IDENT: " + QString( getenv( "REMOTE_IDENT" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "REMOTE_IDENT: " + QString( getenv( "REMOTE_IDENT" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "CONTENT_TYPE" ) ) { - QgsMessageLog::logMessage( "CONTENT_TYPE: " + QString( getenv( "CONTENT_TYPE" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "CONTENT_TYPE: " + QString( getenv( "CONTENT_TYPE" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "AUTH_TYPE" ) ) { - QgsMessageLog::logMessage( "AUTH_TYPE: " + QString( getenv( "AUTH_TYPE" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "AUTH_TYPE: " + QString( getenv( "AUTH_TYPE" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "HTTP_USER_AGENT" ) ) { - QgsMessageLog::logMessage( "HTTP_USER_AGENT: " + QString( getenv( "HTTP_USER_AGENT" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "HTTP_USER_AGENT: " + QString( getenv( "HTTP_USER_AGENT" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "HTTP_PROXY" ) ) { - QgsMessageLog::logMessage( "HTTP_PROXY: " + QString( getenv( "HTTP_PROXY" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "HTTP_PROXY: " + QString( getenv( "HTTP_PROXY" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "HTTPS_PROXY" ) ) { - QgsMessageLog::logMessage( "HTTPS_PROXY: " + QString( getenv( "HTTPS_PROXY" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "HTTPS_PROXY: " + QString( getenv( "HTTPS_PROXY" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } if ( getenv( "NO_PROXY" ) ) { - QgsMessageLog::logMessage( "NO_PROXY: " + QString( getenv( "NO_PROXY" ) ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "NO_PROXY: " + QString( getenv( "NO_PROXY" ) ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } } @@ -291,10 +291,10 @@ QString QgsServer::configPath( const QString& defaultConfigPath, const QMap::const_iterator paramIt = parameters.find( "MAP" ); + QMap::const_iterator paramIt = parameters.find( QStringLiteral( "MAP" ) ); if ( paramIt == parameters.constEnd() ) { - QgsMessageLog::logMessage( QString( "Using default configuration file path: %1" ).arg( defaultConfigPath ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "Using default configuration file path: %1" ).arg( defaultConfigPath ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } else { @@ -329,7 +329,7 @@ bool QgsServer::init( ) QString optionsPath = getenv( "QGIS_OPTIONS_PATH" ); if ( !optionsPath.isEmpty() ) { - QgsMessageLog::logMessage( "Options PATH: " + optionsPath, "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Options PATH: " + optionsPath, QStringLiteral( "Server" ), QgsMessageLog::INFO ); QSettings::setDefaultFormat( QSettings::IniFormat ); QSettings::setPath( QSettings::IniFormat, QSettings::UserScope, optionsPath ); } @@ -356,12 +356,12 @@ bool QgsServer::init( ) // Instantiate the plugin directory so that providers are loaded QgsProviderRegistry::instance( QgsApplication::pluginPath() ); - QgsMessageLog::logMessage( "Prefix PATH: " + QgsApplication::prefixPath(), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( "Plugin PATH: " + QgsApplication::pluginPath(), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( "PkgData PATH: " + QgsApplication::pkgDataPath(), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( "User DB PATH: " + QgsApplication::qgisUserDbFilePath(), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( "Auth DB PATH: " + QgsApplication::qgisAuthDbFilePath(), "Server", QgsMessageLog::INFO ); - QgsMessageLog::logMessage( "SVG PATHS: " + QgsApplication::svgPaths().join( QDir::separator() ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Prefix PATH: " + QgsApplication::prefixPath(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Plugin PATH: " + QgsApplication::pluginPath(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "PkgData PATH: " + QgsApplication::pkgDataPath(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "User DB PATH: " + QgsApplication::qgisUserDbFilePath(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Auth DB PATH: " + QgsApplication::qgisAuthDbFilePath(), QStringLiteral( "Server" ), QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "SVG PATHS: " + QgsApplication::svgPaths().join( QDir::separator() ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); QgsApplication::createDB(); //init qgis.db (e.g. necessary for user crs) @@ -376,7 +376,7 @@ bool QgsServer::init( ) if ( projectFileInfo.exists() ) { defaultConfigFilePath = projectFileInfo.absoluteFilePath(); - QgsMessageLog::logMessage( "Using default project file: " + defaultConfigFilePath, "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Using default project file: " + defaultConfigFilePath, QStringLiteral( "Server" ), QgsMessageLog::INFO ); } else { @@ -395,7 +395,7 @@ bool QgsServer::init( ) sMapRenderer->setLabelingEngine( new QgsPalLabeling() ); #ifdef ENABLE_MS_TESTS - QgsFontUtils::loadStandardTestFonts( QStringList() << "Roman" << "Bold" ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Roman" ) << QStringLiteral( "Bold" ) ); #endif #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -405,18 +405,18 @@ bool QgsServer::init( ) // Init plugins if ( ! QgsServerPlugins::initPlugins( sServerInterface ) ) { - QgsMessageLog::logMessage( "No server python plugins are available", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "No server python plugins are available" ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } else { - QgsMessageLog::logMessage( "Server python plugins loaded", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "Server python plugins loaded" ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } } #endif QgsEditorWidgetRegistry::initEditors(); sInitialised = true; - QgsMessageLog::logMessage( "Server initialized", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "Server initialized" ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); return true; } @@ -448,7 +448,7 @@ QPair QgsServer::handleRequest( const QString& queryStri * to handleRequest without using os.environment */ if ( ! queryString.isEmpty() ) - putenv( "QUERY_STRING", queryString ); + putenv( QStringLiteral( "QUERY_STRING" ), queryString ); int logLevel = QgsServerLogger::instance()->logLevel(); QTime time; //used for measuring request time if loglevel < 1 @@ -478,7 +478,7 @@ QPair QgsServer::handleRequest( const QString& queryStri } catch ( QgsMapServiceException& e ) { - QgsMessageLog::logMessage( "Parse input exception: " + e.message(), "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( "Parse input exception: " + e.message(), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); theRequestHandler->setServiceException( e ); } @@ -514,30 +514,30 @@ QPair QgsServer::handleRequest( const QString& queryStri sServerInterface->setConfigFilePath( configFilePath ); #endif //Service parameter - QString serviceString = theRequestHandler->parameter( "SERVICE" ); + QString serviceString = theRequestHandler->parameter( QStringLiteral( "SERVICE" ) ); if ( serviceString.isEmpty() ) { // SERVICE not mandatory for WMS 1.3.0 GetMap & GetFeatureInfo - QString requestString = theRequestHandler->parameter( "REQUEST" ); - if ( requestString == "GetMap" || requestString == "GetFeatureInfo" ) + QString requestString = theRequestHandler->parameter( QStringLiteral( "REQUEST" ) ); + if ( requestString == QLatin1String( "GetMap" ) || requestString == QLatin1String( "GetFeatureInfo" ) ) { - serviceString = "WMS"; + serviceString = QStringLiteral( "WMS" ); } } //possibility for client to suggest a download filename - QString outputFileName = theRequestHandler->parameter( "FILE_NAME" ); + QString outputFileName = theRequestHandler->parameter( QStringLiteral( "FILE_NAME" ) ); if ( !outputFileName.isEmpty() ) { theRequestHandler->setDefaultHeaders(); - theRequestHandler->setHeader( "Content-Disposition", "attachment; filename=\"" + outputFileName + "\"" ); + theRequestHandler->setHeader( QStringLiteral( "Content-Disposition" ), "attachment; filename=\"" + outputFileName + "\"" ); } // Enter core services main switch if ( !theRequestHandler->exceptionRaised() ) { - if ( serviceString == "WCS" ) + if ( serviceString == QLatin1String( "WCS" ) ) { QgsWCSProjectParser* p = QgsConfigCache::instance()->wcsConfiguration( configFilePath @@ -547,7 +547,7 @@ QPair QgsServer::handleRequest( const QString& queryStri ); if ( !p ) { - theRequestHandler->setServiceException( QgsMapServiceException( "Project file error", "Error reading the project file" ) ); + theRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "Project file error" ), QStringLiteral( "Error reading the project file" ) ) ); } else { @@ -563,7 +563,7 @@ QPair QgsServer::handleRequest( const QString& queryStri wcsServer.executeRequest(); } } - else if ( serviceString == "WFS" ) + else if ( serviceString == QLatin1String( "WFS" ) ) { QgsWfsProjectParser* p = QgsConfigCache::instance()->wfsConfiguration( configFilePath @@ -573,7 +573,7 @@ QPair QgsServer::handleRequest( const QString& queryStri ); if ( !p ) { - theRequestHandler->setServiceException( QgsMapServiceException( "Project file error", "Error reading the project file" ) ); + theRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "Project file error" ), QStringLiteral( "Error reading the project file" ) ) ); } else { @@ -589,7 +589,7 @@ QPair QgsServer::handleRequest( const QString& queryStri wfsServer.executeRequest(); } } - else if ( serviceString == "WMS" ) + else if ( serviceString == QLatin1String( "WMS" ) ) { QgsWmsConfigParser* p = QgsConfigCache::instance()->wmsConfiguration( configFilePath @@ -599,7 +599,7 @@ QPair QgsServer::handleRequest( const QString& queryStri ); if ( !p ) { - theRequestHandler->setServiceException( QgsMapServiceException( "WMS configuration error", "There was an error reading the project file or the SLD configuration" ) ); + theRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "WMS configuration error" ), QStringLiteral( "There was an error reading the project file or the SLD configuration" ) ) ); } else { @@ -619,7 +619,7 @@ QPair QgsServer::handleRequest( const QString& queryStri } else { - theRequestHandler->setServiceException( QgsMapServiceException( "Service configuration error", "Service unknown or unsupported" ) ); + theRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "Service configuration error" ), QStringLiteral( "Service unknown or unsupported" ) ) ); } // end switch } // end if not exception raised @@ -639,7 +639,7 @@ QPair QgsServer::handleRequest( const QString& queryStri if ( logLevel < 1 ) { - QgsMessageLog::logMessage( "Request finished in " + QString::number( time.elapsed() ) + " ms", "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( "Request finished in " + QString::number( time.elapsed() ) + " ms", QStringLiteral( "Server" ), QgsMessageLog::INFO ); } // Returns the header and response bytestreams (to be used in Python bindings) return theRequestHandler->getResponse(); @@ -655,8 +655,8 @@ QPair QgsServer::testQPair( QPairgetPluginMetadata( pluginName, "server" ); - if ( pluginService == "True" ) + QString pluginService = sPythonUtils->getPluginMetadata( pluginName, QStringLiteral( "server" ) ); + if ( pluginService == QLatin1String( "True" ) ) { if ( sPythonUtils->loadPlugin( pluginName ) ) { @@ -110,16 +110,16 @@ bool QgsServerPlugins::initPlugins( QgsServerInterface *interface ) { atLeastOneEnabled = true; serverPlugins().append( pluginName ); - QgsMessageLog::logMessage( QString( "Server plugin %1 loaded!" ).arg( pluginName ), "Server", QgsMessageLog::INFO ); + QgsMessageLog::logMessage( QStringLiteral( "Server plugin %1 loaded!" ).arg( pluginName ), QStringLiteral( "Server" ), QgsMessageLog::INFO ); } else { - QgsMessageLog::logMessage( QString( "Error loading server plugin %1" ).arg( pluginName ), "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( QStringLiteral( "Error loading server plugin %1" ).arg( pluginName ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); } } else { - QgsMessageLog::logMessage( QString( "Error starting server plugin %1" ).arg( pluginName ), "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( QStringLiteral( "Error starting server plugin %1" ).arg( pluginName ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); } } } diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 0bdbcbe423da..d86a7a0c7fe8 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -44,7 +44,7 @@ QgsServerProjectParser::QgsServerProjectParser( QDomDocument* xmlDoc, const QStr //accelerate the search for layers, groups and the creation of annotation items if ( mXMLDoc ) { - QDomNodeList layerNodeList = mXMLDoc->elementsByTagName( "maplayer" ); + QDomNodeList layerNodeList = mXMLDoc->elementsByTagName( QStringLiteral( "maplayer" ) ); QDomElement currentElement; int nNodes = layerNodeList.size(); mProjectLayerElements.reserve( nNodes ); @@ -66,8 +66,8 @@ QgsServerProjectParser::QgsServerProjectParser( QDomDocument* xmlDoc, const QStr mCustomLayerOrder.clear(); - QDomElement customOrder = mXMLDoc->documentElement().firstChildElement( "layer-tree-canvas" ).firstChildElement( "custom-order" ); - if ( customOrder.attribute( "enabled" ) == "1" ) + QDomElement customOrder = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "layer-tree-canvas" ) ).firstChildElement( QStringLiteral( "custom-order" ) ); + if ( customOrder.attribute( QStringLiteral( "enabled" ) ) == QLatin1String( "1" ) ) { QDomNodeList items = customOrder.childNodes(); for ( int i = 0; i < items.size(); ++i ) @@ -112,7 +112,7 @@ void QgsServerProjectParser::projectLayerMap( QMap& layer QString QgsServerProjectParser::convertToAbsolutePath( const QString& file ) const { - if ( !file.startsWith( "./" ) && !file.startsWith( "../" ) ) + if ( !file.startsWith( QLatin1String( "./" ) ) && !file.startsWith( QLatin1String( "../" ) ) ) { return file; } @@ -127,8 +127,8 @@ QString QgsServerProjectParser::convertToAbsolutePath( const QString& file ) con bool uncPath = projPath.startsWith( "//" ); #endif - QStringList srcElems = srcPath.split( "/", QString::SkipEmptyParts ); - QStringList projElems = projPath.split( "/", QString::SkipEmptyParts ); + QStringList srcElems = srcPath.split( QStringLiteral( "/" ), QString::SkipEmptyParts ); + QStringList projElems = projPath.split( QStringLiteral( "/" ), QString::SkipEmptyParts ); #if defined(Q_OS_WIN) if ( uncPath ) @@ -143,11 +143,11 @@ QString QgsServerProjectParser::convertToAbsolutePath( const QString& file ) con // append source path elements projElems << srcElems; - projElems.removeAll( "." ); + projElems.removeAll( QStringLiteral( "." ) ); // resolve .. int pos; - while (( pos = projElems.indexOf( ".." ) ) > 0 ) + while (( pos = projElems.indexOf( QStringLiteral( ".." ) ) ) > 0 ) { // remove preceding element and .. projElems.removeAt( pos - 1 ); @@ -156,10 +156,10 @@ QString QgsServerProjectParser::convertToAbsolutePath( const QString& file ) con #if !defined(Q_OS_WIN) // make path absolute - projElems.prepend( "" ); + projElems.prepend( QLatin1String( "" ) ); #endif - return projElems.join( "/" ); + return projElems.join( QStringLiteral( "/" ) ); } QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& elem, bool useCache ) const @@ -172,7 +172,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& addJoinLayersForElement( elem ); addGetFeatureLayers( elem ); - QDomElement dataSourceElem = elem.firstChildElement( "datasource" ); + QDomElement dataSourceElem = elem.firstChildElement( QStringLiteral( "datasource" ) ); QString uri = dataSourceElem.text(); QString absoluteUri; // If QgsProject instance fileName is set, @@ -180,7 +180,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& if ( !dataSourceElem.isNull() ) { //convert relative pathes to absolute ones if necessary - if ( uri.startsWith( "dbname" ) ) //database + if ( uri.startsWith( QLatin1String( "dbname" ) ) ) //database { QgsDataSourceUri dsUri( uri ); if ( dsUri.host().isEmpty() ) //only convert path for file based databases @@ -196,14 +196,14 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& } } } - else if ( uri.startsWith( "file:" ) ) //a file based datasource in url notation (e.g. delimited text layer) + else if ( uri.startsWith( QLatin1String( "file:" ) ) ) //a file based datasource in url notation (e.g. delimited text layer) { - QString filePath = uri.mid( 5, uri.indexOf( "?" ) - 5 ); + QString filePath = uri.mid( 5, uri.indexOf( QLatin1String( "?" ) ) - 5 ); QString absoluteFilePath = convertToAbsolutePath( filePath ); if ( filePath != absoluteFilePath ) { QUrl destUrl = QUrl::fromEncoded( uri.toLatin1() ); - destUrl.setScheme( "file" ); + destUrl.setScheme( QStringLiteral( "file" ) ); destUrl.setPath( absoluteFilePath ); absoluteUri = destUrl.toEncoded(); QDomText absoluteTextNode = mXMLDoc->createTextNode( absoluteUri ); @@ -247,18 +247,18 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& return layer; } - QString type = elem.attribute( "type" ); - if ( type == "vector" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "vector" ) ) { layer = new QgsVectorLayer(); } - else if ( type == "raster" ) + else if ( type == QLatin1String( "raster" ) ) { layer = new QgsRasterLayer(); } - else if ( elem.attribute( "embedded" ) == "1" ) //layer is embedded from another project file + else if ( elem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) //layer is embedded from another project file { - QString project = convertToAbsolutePath( elem.attribute( "project" ) ); + QString project = convertToAbsolutePath( elem.attribute( QStringLiteral( "project" ) ) ); QgsDebugMsg( QString( "Project path: %1" ).arg( project ) ); QgsServerProjectParser* otherConfig = QgsConfigCache::instance()->serverConfiguration( project ); @@ -266,7 +266,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& { return nullptr; } - return otherConfig->mapLayerFromLayerId( elem.attribute( "id" ), useCache ); + return otherConfig->mapLayerFromLayerId( elem.attribute( QStringLiteral( "id" ) ), useCache ); } if ( layer ) @@ -318,12 +318,12 @@ QString QgsServerProjectParser::layerIdFromLegendLayer( const QDomElement& legen return QString(); } - QDomNodeList legendLayerFileList = legendLayer.elementsByTagName( "legendlayerfile" ); + QDomNodeList legendLayerFileList = legendLayer.elementsByTagName( QStringLiteral( "legendlayerfile" ) ); if ( legendLayerFileList.size() < 1 ) { return QString(); } - return legendLayerFileList.at( 0 ).toElement().attribute( "layerid" ); + return legendLayerFileList.at( 0 ).toElement().attribute( QStringLiteral( "layerid" ) ); } QString QgsServerProjectParser::layerId( const QDomElement& layerElem ) const @@ -333,11 +333,11 @@ QString QgsServerProjectParser::layerId( const QDomElement& layerElem ) const return QString(); } - QDomElement idElem = layerElem.firstChildElement( "id" ); + QDomElement idElem = layerElem.firstChildElement( QStringLiteral( "id" ) ); if ( idElem.isNull() ) { //embedded layer have id attribute instead of id child element - return layerElem.attribute( "id" ); + return layerElem.attribute( QStringLiteral( "id" ) ); } return idElem.text(); } @@ -349,12 +349,12 @@ QString QgsServerProjectParser::layerShortName( const QDomElement& layerElem ) c return QString(); } - QDomElement nameElem = layerElem.firstChildElement( "shortname" ); + QDomElement nameElem = layerElem.firstChildElement( QStringLiteral( "shortname" ) ); if ( nameElem.isNull() ) { return QString(); } - return nameElem.text().replace( ",", "%60" ); + return nameElem.text().replace( QLatin1String( "," ), QLatin1String( "%60" ) ); } QgsRectangle QgsServerProjectParser::projectExtent() const @@ -366,18 +366,18 @@ QgsRectangle QgsServerProjectParser::projectExtent() const } QDomElement qgisElem = mXMLDoc->documentElement(); - QDomElement mapCanvasElem = qgisElem.firstChildElement( "mapcanvas" ); + QDomElement mapCanvasElem = qgisElem.firstChildElement( QStringLiteral( "mapcanvas" ) ); if ( mapCanvasElem.isNull() ) { return extent; } - QDomElement extentElem = mapCanvasElem.firstChildElement( "extent" ); + QDomElement extentElem = mapCanvasElem.firstChildElement( QStringLiteral( "extent" ) ); bool xminOk, xmaxOk, yminOk, ymaxOk; - double xMin = extentElem.firstChildElement( "xmin" ).text().toDouble( &xminOk ); - double xMax = extentElem.firstChildElement( "xmax" ).text().toDouble( &xmaxOk ); - double yMin = extentElem.firstChildElement( "ymin" ).text().toDouble( &yminOk ); - double yMax = extentElem.firstChildElement( "ymax" ).text().toDouble( &ymaxOk ); + double xMin = extentElem.firstChildElement( QStringLiteral( "xmin" ) ).text().toDouble( &xminOk ); + double xMax = extentElem.firstChildElement( QStringLiteral( "xmax" ) ).text().toDouble( &xmaxOk ); + double yMin = extentElem.firstChildElement( QStringLiteral( "ymin" ) ).text().toDouble( &yminOk ); + double yMax = extentElem.firstChildElement( QStringLiteral( "ymax" ) ).text().toDouble( &ymaxOk ); if ( xminOk && xmaxOk && yminOk && ymaxOk ) { @@ -405,51 +405,51 @@ void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QD QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc ); return; } - QDomElement serviceElem = doc.createElement( "Service" ); + QDomElement serviceElem = doc.createElement( QStringLiteral( "Service" ) ); - QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( "WMSServiceCapabilities" ); - if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( "true", Qt::CaseInsensitive ) != 0 ) + QDomElement serviceCapabilityElem = propertiesElement.firstChildElement( QStringLiteral( "WMSServiceCapabilities" ) ); + if ( serviceCapabilityElem.isNull() || serviceCapabilityElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) != 0 ) { QgsConfigParserUtils::fallbackServiceCapabilities( parentElement, doc ); return; } //Service name - QDomElement wmsNameElem = doc.createElement( "Name" ); + QDomElement wmsNameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText wmsNameText = doc.createTextNode( service ); wmsNameElem.appendChild( wmsNameText ); serviceElem.appendChild( wmsNameElem ); //WMS title //why not use project title ? - QDomElement titleElem = propertiesElement.firstChildElement( "WMSServiceTitle" ); + QDomElement titleElem = propertiesElement.firstChildElement( QStringLiteral( "WMSServiceTitle" ) ); if ( !titleElem.isNull() ) { - QDomElement wmsTitleElem = doc.createElement( "Title" ); + QDomElement wmsTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText wmsTitleText = doc.createTextNode( titleElem.text() ); wmsTitleElem.appendChild( wmsTitleText ); serviceElem.appendChild( wmsTitleElem ); } //WMS abstract - QDomElement abstractElem = propertiesElement.firstChildElement( "WMSServiceAbstract" ); + QDomElement abstractElem = propertiesElement.firstChildElement( QStringLiteral( "WMSServiceAbstract" ) ); if ( !abstractElem.isNull() ) { - QDomElement wmsAbstractElem = doc.createElement( "Abstract" ); + QDomElement wmsAbstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() ); wmsAbstractElem.appendChild( wmsAbstractText ); serviceElem.appendChild( wmsAbstractElem ); } //keyword list - QDomElement keywordListElem = propertiesElement.firstChildElement( "WMSKeywordList" ); - if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) + QDomElement keywordListElem = propertiesElement.firstChildElement( QStringLiteral( "WMSKeywordList" ) ); + if ( service.compare( QLatin1String( "WMS" ), Qt::CaseInsensitive ) == 0 ) { - QDomElement wmsKeywordElem = doc.createElement( "KeywordList" ); + QDomElement wmsKeywordElem = doc.createElement( QStringLiteral( "KeywordList" ) ); //add default keyword - QDomElement keywordElem = doc.createElement( "Keyword" ); - keywordElem.setAttribute( "vocabulary", "ISO" ); - QDomText keywordText = doc.createTextNode( "infoMapAccessService" ); + QDomElement keywordElem = doc.createElement( QStringLiteral( "Keyword" ) ); + keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "ISO" ) ); + QDomText keywordText = doc.createTextNode( QStringLiteral( "infoMapAccessService" ) ); /* If WFS and WCS 2.0 is implemented if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 ) keywordText = doc.createTextNode( "infoFeatureAccessService" ); @@ -461,15 +461,15 @@ void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QD //add config keywords if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() ) { - QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" ); + QDomNodeList keywordList = keywordListElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < keywordList.size(); ++i ) { - keywordElem = doc.createElement( "Keyword" ); + keywordElem = doc.createElement( QStringLiteral( "Keyword" ) ); keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() ); keywordElem.appendChild( keywordText ); if ( sia2045 ) { - keywordElem.setAttribute( "vocabulary", "SIA_Geo405" ); + keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "SIA_Geo405" ) ); } wmsKeywordElem.appendChild( keywordElem ); } @@ -477,100 +477,100 @@ void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QD } else if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() ) { - QDomNodeList keywordNodeList = keywordListElem.elementsByTagName( "value" ); + QDomNodeList keywordNodeList = keywordListElem.elementsByTagName( QStringLiteral( "value" ) ); QStringList keywordList; for ( int i = 0; i < keywordNodeList.size(); ++i ) { keywordList.push_back( keywordNodeList.at( i ).toElement().text() ); } - QDomElement wmsKeywordElem = doc.createElement( "Keywords" ); - if ( service.compare( "WCS", Qt::CaseInsensitive ) == 0 ) - wmsKeywordElem = doc.createElement( "keywords" ); - QDomText keywordText = doc.createTextNode( keywordList.join( ", " ) ); + QDomElement wmsKeywordElem = doc.createElement( QStringLiteral( "Keywords" ) ); + if ( service.compare( QLatin1String( "WCS" ), Qt::CaseInsensitive ) == 0 ) + wmsKeywordElem = doc.createElement( QStringLiteral( "keywords" ) ); + QDomText keywordText = doc.createTextNode( keywordList.join( QStringLiteral( ", " ) ) ); wmsKeywordElem.appendChild( keywordText ); serviceElem.appendChild( wmsKeywordElem ); } //OnlineResource element is mandatory according to the WMS specification - QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( "WMSOnlineResource" ); + QDomElement wmsOnlineResourceElem = propertiesElement.firstChildElement( QStringLiteral( "WMSOnlineResource" ) ); if ( !wmsOnlineResourceElem.isNull() ) { - QDomElement onlineResourceElem = doc.createElement( "OnlineResource" ); - if ( service.compare( "WFS", Qt::CaseInsensitive ) == 0 ) + QDomElement onlineResourceElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + if ( service.compare( QLatin1String( "WFS" ), Qt::CaseInsensitive ) == 0 ) { QDomText onlineResourceText = doc.createTextNode( wmsOnlineResourceElem.text() ); onlineResourceElem.appendChild( onlineResourceText ); } else { - onlineResourceElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - onlineResourceElem.setAttribute( "xlink:type", "simple" ); - onlineResourceElem.setAttribute( "xlink:href", wmsOnlineResourceElem.text() ); + onlineResourceElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + onlineResourceElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + onlineResourceElem.setAttribute( QStringLiteral( "xlink:href" ), wmsOnlineResourceElem.text() ); } serviceElem.appendChild( onlineResourceElem ); } - if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0 + if ( service.compare( QLatin1String( "WMS" ), Qt::CaseInsensitive ) == 0 ) //no contact information in WFS 1.0 and WCS 1.0 { //Contact information - QDomElement contactInfoElem = doc.createElement( "ContactInformation" ); + QDomElement contactInfoElem = doc.createElement( QStringLiteral( "ContactInformation" ) ); //Contact person primary - QDomElement contactPersonPrimaryElem = doc.createElement( "ContactPersonPrimary" ); + QDomElement contactPersonPrimaryElem = doc.createElement( QStringLiteral( "ContactPersonPrimary" ) ); //Contact person - QDomElement contactPersonElem = propertiesElement.firstChildElement( "WMSContactPerson" ); + QDomElement contactPersonElem = propertiesElement.firstChildElement( QStringLiteral( "WMSContactPerson" ) ); QString contactPersonString; if ( !contactPersonElem.isNull() ) { contactPersonString = contactPersonElem.text(); } - QDomElement wmsContactPersonElem = doc.createElement( "ContactPerson" ); + QDomElement wmsContactPersonElem = doc.createElement( QStringLiteral( "ContactPerson" ) ); QDomText contactPersonText = doc.createTextNode( contactPersonString ); wmsContactPersonElem.appendChild( contactPersonText ); contactPersonPrimaryElem.appendChild( wmsContactPersonElem ); //Contact organisation - QDomElement contactOrganizationElem = propertiesElement.firstChildElement( "WMSContactOrganization" ); + QDomElement contactOrganizationElem = propertiesElement.firstChildElement( QStringLiteral( "WMSContactOrganization" ) ); QString contactOrganizationString; if ( !contactOrganizationElem.isNull() ) { contactOrganizationString = contactOrganizationElem.text(); } - QDomElement wmsContactOrganizationElem = doc.createElement( "ContactOrganization" ); + QDomElement wmsContactOrganizationElem = doc.createElement( QStringLiteral( "ContactOrganization" ) ); QDomText contactOrganizationText = doc.createTextNode( contactOrganizationString ); wmsContactOrganizationElem.appendChild( contactOrganizationText ); contactPersonPrimaryElem.appendChild( wmsContactOrganizationElem ); //Contact position - QDomElement contactPositionElem = propertiesElement.firstChildElement( "WMSContactPosition" ); + QDomElement contactPositionElem = propertiesElement.firstChildElement( QStringLiteral( "WMSContactPosition" ) ); QString contactPositionString; if ( !contactPositionElem.isNull() ) { contactPositionString = contactPositionElem.text(); } - QDomElement wmsContactPositionElem = doc.createElement( "ContactPosition" ); + QDomElement wmsContactPositionElem = doc.createElement( QStringLiteral( "ContactPosition" ) ); QDomText contactPositionText = doc.createTextNode( contactPositionString ); wmsContactPositionElem.appendChild( contactPositionText ); contactPersonPrimaryElem.appendChild( wmsContactPositionElem ); contactInfoElem.appendChild( contactPersonPrimaryElem ); //phone - QDomElement phoneElem = propertiesElement.firstChildElement( "WMSContactPhone" ); + QDomElement phoneElem = propertiesElement.firstChildElement( QStringLiteral( "WMSContactPhone" ) ); if ( !phoneElem.isNull() ) { - QDomElement wmsPhoneElem = doc.createElement( "ContactVoiceTelephone" ); + QDomElement wmsPhoneElem = doc.createElement( QStringLiteral( "ContactVoiceTelephone" ) ); QDomText wmsPhoneText = doc.createTextNode( phoneElem.text() ); wmsPhoneElem.appendChild( wmsPhoneText ); contactInfoElem.appendChild( wmsPhoneElem ); } //mail - QDomElement mailElem = propertiesElement.firstChildElement( "WMSContactMail" ); + QDomElement mailElem = propertiesElement.firstChildElement( QStringLiteral( "WMSContactMail" ) ); if ( !mailElem.isNull() ) { - QDomElement wmsMailElem = doc.createElement( "ContactElectronicMailAddress" ); + QDomElement wmsMailElem = doc.createElement( QStringLiteral( "ContactElectronicMailAddress" ) ); QDomText wmsMailText = doc.createTextNode( mailElem.text() ); wmsMailElem.appendChild( wmsMailText ); contactInfoElem.appendChild( wmsMailElem ); @@ -580,9 +580,9 @@ void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QD } //Fees - QDomElement feesElem = propertiesElement.firstChildElement( "WMSFees" ); - QDomElement wmsFeesElem = doc.createElement( "Fees" ); - QDomText wmsFeesText = doc.createTextNode( "conditions unknown" ); // default value if access conditions are unknown + QDomElement feesElem = propertiesElement.firstChildElement( QStringLiteral( "WMSFees" ) ); + QDomElement wmsFeesElem = doc.createElement( QStringLiteral( "Fees" ) ); + QDomText wmsFeesText = doc.createTextNode( QStringLiteral( "conditions unknown" ) ); // default value if access conditions are unknown if ( !feesElem.isNull() && !feesElem.text().isEmpty() ) { wmsFeesText = doc.createTextNode( feesElem.text() ); @@ -591,9 +591,9 @@ void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QD serviceElem.appendChild( wmsFeesElem ); //AccessConstraints - QDomElement accessConstraintsElem = propertiesElement.firstChildElement( "WMSAccessConstraints" ); - QDomElement wmsAccessConstraintsElem = doc.createElement( "AccessConstraints" ); - QDomText wmsAccessConstraintsText = doc.createTextNode( "None" ); // default value if access constraints are unknown + QDomElement accessConstraintsElem = propertiesElement.firstChildElement( QStringLiteral( "WMSAccessConstraints" ) ); + QDomElement wmsAccessConstraintsElem = doc.createElement( QStringLiteral( "AccessConstraints" ) ); + QDomText wmsAccessConstraintsText = doc.createTextNode( QStringLiteral( "None" ) ); // default value if access constraints are unknown if ( !accessConstraintsElem.isNull() && !accessConstraintsElem.text().isEmpty() ) { wmsAccessConstraintsText = doc.createTextNode( accessConstraintsElem.text() ); @@ -602,25 +602,25 @@ void QgsServerProjectParser::serviceCapabilities( QDomElement& parentElement, QD serviceElem.appendChild( wmsAccessConstraintsElem ); //max width, max height for WMS - if ( service.compare( "WMS", Qt::CaseInsensitive ) == 0 ) + if ( service.compare( QLatin1String( "WMS" ), Qt::CaseInsensitive ) == 0 ) { - QString version = doc.documentElement().attribute( "version" ); - if ( version != "1.1.1" ) + QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); + if ( version != QLatin1String( "1.1.1" ) ) { //max width - QDomElement mwElem = propertiesElement.firstChildElement( "WMSMaxWidth" ); + QDomElement mwElem = propertiesElement.firstChildElement( QStringLiteral( "WMSMaxWidth" ) ); if ( !mwElem.isNull() ) { - QDomElement maxWidthElem = doc.createElement( "MaxWidth" ); + QDomElement maxWidthElem = doc.createElement( QStringLiteral( "MaxWidth" ) ); QDomText maxWidthText = doc.createTextNode( mwElem.text() ); maxWidthElem.appendChild( maxWidthText ); serviceElem.appendChild( maxWidthElem ); } //max height - QDomElement mhElem = propertiesElement.firstChildElement( "WMSMaxHeight" ); + QDomElement mhElem = propertiesElement.firstChildElement( QStringLiteral( "WMSMaxHeight" ) ); if ( !mhElem.isNull() ) { - QDomElement maxHeightElem = doc.createElement( "MaxHeight" ); + QDomElement maxHeightElem = doc.createElement( QStringLiteral( "MaxHeight" ) ); QDomText maxHeightText = doc.createTextNode( mhElem.text() ); maxHeightElem.appendChild( maxHeightText ); serviceElem.appendChild( maxHeightElem ); @@ -637,12 +637,12 @@ QString QgsServerProjectParser::layerName( const QDomElement& layerElem ) const return QString(); } - QDomElement nameElem = layerElem.firstChildElement( "layername" ); + QDomElement nameElem = layerElem.firstChildElement( QStringLiteral( "layername" ) ); if ( nameElem.isNull() ) { return QString(); } - return nameElem.text().replace( ",", "%60" ); //commas are not allowed in layer names + return nameElem.text().replace( QLatin1String( "," ), QLatin1String( "%60" ) ); //commas are not allowed in layer names } QString QgsServerProjectParser::serviceUrl() const @@ -657,7 +657,7 @@ QString QgsServerProjectParser::serviceUrl() const QDomElement propertiesElement = propertiesElem(); if ( !propertiesElement.isNull() ) { - QDomElement wmsUrlElem = propertiesElement.firstChildElement( "WMSUrl" ); + QDomElement wmsUrlElem = propertiesElement.firstChildElement( QStringLiteral( "WMSUrl" ) ); if ( !wmsUrlElem.isNull() ) { url = wmsUrlElem.text(); @@ -678,7 +678,7 @@ QString QgsServerProjectParser::wfsServiceUrl() const QDomElement propertiesElement = propertiesElem(); if ( !propertiesElement.isNull() ) { - QDomElement wfsUrlElem = propertiesElement.firstChildElement( "WFSUrl" ); + QDomElement wfsUrlElem = propertiesElement.firstChildElement( QStringLiteral( "WFSUrl" ) ); if ( !wfsUrlElem.isNull() ) { url = wfsUrlElem.text(); @@ -699,7 +699,7 @@ QString QgsServerProjectParser::wcsServiceUrl() const QDomElement propertiesElement = propertiesElem(); if ( !propertiesElement.isNull() ) { - QDomElement wcsUrlElem = propertiesElement.firstChildElement( "WCSUrl" ); + QDomElement wcsUrlElem = propertiesElement.firstChildElement( QStringLiteral( "WCSUrl" ) ); if ( !wcsUrlElem.isNull() ) { url = wcsUrlElem.text(); @@ -720,7 +720,7 @@ void QgsServerProjectParser::combineExtentAndCrsOfGroupChildren( QDomElement& gr { QDomElement childElem = layerChildren.at( j ).toElement(); - if ( childElem.tagName() != "Layer" ) + if ( childElem.tagName() != QLatin1String( "Layer" ) ) continue; QgsRectangle bbox = layerBoundingBoxInProjectCrs( childElem, doc ); @@ -779,7 +779,7 @@ void QgsServerProjectParser::addLayerProjectSettings( QDomElement& layerElem, QD return; } // Layer tree name - QDomElement treeNameElem = doc.createElement( "TreeName" ); + QDomElement treeNameElem = doc.createElement( QStringLiteral( "TreeName" ) ); QDomText treeNameText = doc.createTextNode( currentLayer->name() ); treeNameElem.appendChild( treeNameText ); layerElem.appendChild( treeNameElem ); @@ -790,7 +790,7 @@ void QgsServerProjectParser::addLayerProjectSettings( QDomElement& layerElem, QD const QSet& excludedAttributes = vLayer->excludeAttributesWms(); int displayFieldIdx = -1; - QString displayField = "maptip"; + QString displayField = QStringLiteral( "maptip" ); QgsExpression exp( vLayer->displayExpression() ); if ( exp.isField() ) { @@ -799,7 +799,7 @@ void QgsServerProjectParser::addLayerProjectSettings( QDomElement& layerElem, QD } //attributes - QDomElement attributesElem = doc.createElement( "Attributes" ); + QDomElement attributesElem = doc.createElement( QStringLiteral( "Attributes" ) ); const QgsFields& layerFields = vLayer->pendingFields(); for ( int idx = 0; idx < layerFields.count(); ++idx ) { @@ -813,28 +813,28 @@ void QgsServerProjectParser::addLayerProjectSettings( QDomElement& layerElem, QD { displayField = vLayer->attributeDisplayName( idx ); } - QDomElement attributeElem = doc.createElement( "Attribute" ); - attributeElem.setAttribute( "name", field.name() ); - attributeElem.setAttribute( "type", QVariant::typeToName( field.type() ) ); - attributeElem.setAttribute( "typeName", field.typeName() ); + QDomElement attributeElem = doc.createElement( QStringLiteral( "Attribute" ) ); + attributeElem.setAttribute( QStringLiteral( "name" ), field.name() ); + attributeElem.setAttribute( QStringLiteral( "type" ), QVariant::typeToName( field.type() ) ); + attributeElem.setAttribute( QStringLiteral( "typeName" ), field.typeName() ); QString alias = field.alias(); if ( !alias.isEmpty() ) { - attributeElem.setAttribute( "alias", alias ); + attributeElem.setAttribute( QStringLiteral( "alias" ), alias ); } //edit type to text - attributeElem.setAttribute( "editType", vLayer->editFormConfig().widgetType( field.name() ) ); - attributeElem.setAttribute( "comment", field.comment() ); - attributeElem.setAttribute( "length", field.length() ); - attributeElem.setAttribute( "precision", field.precision() ); + attributeElem.setAttribute( QStringLiteral( "editType" ), vLayer->editFormConfig().widgetType( field.name() ) ); + attributeElem.setAttribute( QStringLiteral( "comment" ), field.comment() ); + attributeElem.setAttribute( QStringLiteral( "length" ), field.length() ); + attributeElem.setAttribute( QStringLiteral( "precision" ), field.precision() ); attributesElem.appendChild( attributeElem ); } //displayfield - layerElem.setAttribute( "displayField", displayField ); + layerElem.setAttribute( QStringLiteral( "displayField" ), displayField ); //geometry type - layerElem.setAttribute( "geometryType", QgsWkbTypes::displayString( vLayer->wkbType() ) ); + layerElem.setAttribute( QStringLiteral( "geometryType" ), QgsWkbTypes::displayString( vLayer->wkbType() ) ); layerElem.appendChild( attributesElem ); } @@ -849,7 +849,7 @@ QgsRectangle QgsServerProjectParser::layerBoundingBoxInProjectCrs( const QDomEle } //read box coordinates and layer auth. id - QDomElement boundingBoxElem = layerElem.firstChildElement( "BoundingBox" ); + QDomElement boundingBoxElem = layerElem.firstChildElement( QStringLiteral( "BoundingBox" ) ); if ( boundingBoxElem.isNull() ) { return BBox; @@ -857,32 +857,32 @@ QgsRectangle QgsServerProjectParser::layerBoundingBoxInProjectCrs( const QDomEle double minx, miny, maxx, maxy; bool conversionOk; - minx = boundingBoxElem.attribute( "minx" ).toDouble( &conversionOk ); + minx = boundingBoxElem.attribute( QStringLiteral( "minx" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } - miny = boundingBoxElem.attribute( "miny" ).toDouble( &conversionOk ); + miny = boundingBoxElem.attribute( QStringLiteral( "miny" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } - maxx = boundingBoxElem.attribute( "maxx" ).toDouble( &conversionOk ); + maxx = boundingBoxElem.attribute( QStringLiteral( "maxx" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } - maxy = boundingBoxElem.attribute( "maxy" ).toDouble( &conversionOk ); + maxy = boundingBoxElem.attribute( QStringLiteral( "maxy" ) ).toDouble( &conversionOk ); if ( !conversionOk ) { return BBox; } - QString version = doc.documentElement().attribute( "version" ); + QString version = doc.documentElement().attribute( QStringLiteral( "version" ) ); //create layer crs - QgsCoordinateReferenceSystem layerCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( boundingBoxElem.attribute( version == "1.1.1" ? "SRS" : "CRS" ) ); + QgsCoordinateReferenceSystem layerCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( boundingBoxElem.attribute( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS" ) ); if ( !layerCrs.isValid() ) { return BBox; @@ -893,7 +893,7 @@ QgsRectangle QgsServerProjectParser::layerBoundingBoxInProjectCrs( const QDomEle BBox.setYMinimum( miny ); BBox.setYMaximum( maxy ); - if ( version != "1.1.1" && layerCrs.hasAxisInverted() ) + if ( version != QLatin1String( "1.1.1" ) && layerCrs.hasAxisInverted() ) { BBox.invert(); } @@ -924,13 +924,13 @@ bool QgsServerProjectParser::crsSetForLayer( const QDomElement& layerElement, QS crsSet.clear(); QDomNodeList crsNodeList; - crsNodeList = layerElement.elementsByTagName( "CRS" ); // WMS 1.3.0 + crsNodeList = layerElement.elementsByTagName( QStringLiteral( "CRS" ) ); // WMS 1.3.0 for ( int i = 0; i < crsNodeList.size(); ++i ) { crsSet.insert( crsNodeList.at( i ).toElement().text() ); } - crsNodeList = layerElement.elementsByTagName( "SRS" ); // WMS 1.1.1 + crsNodeList = layerElement.elementsByTagName( QStringLiteral( "SRS" ) ); // WMS 1.1.1 for ( int i = 0; i < crsNodeList.size(); ++i ) { crsSet.insert( crsNodeList.at( i ).toElement().text() ); @@ -944,8 +944,8 @@ QgsCoordinateReferenceSystem QgsServerProjectParser::projectCrs() const //mapcanvas->destinationsrs->spatialrefsys->authid if ( mXMLDoc ) { - QDomElement authIdElem = mXMLDoc->documentElement().firstChildElement( "mapcanvas" ).firstChildElement( "destinationsrs" ). - firstChildElement( "spatialrefsys" ).firstChildElement( "authid" ); + QDomElement authIdElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "mapcanvas" ) ).firstChildElement( QStringLiteral( "destinationsrs" ) ). + firstChildElement( QStringLiteral( "spatialrefsys" ) ).firstChildElement( QStringLiteral( "authid" ) ); if ( !authIdElem.isNull() ) { return QgsCoordinateReferenceSystem::fromOgcWmsCrs( authIdElem.text() ); @@ -967,19 +967,19 @@ QgsRectangle QgsServerProjectParser::mapRectangle() const return QgsRectangle(); } - QDomElement propertiesElem = qgisElem.firstChildElement( "properties" ); + QDomElement propertiesElem = qgisElem.firstChildElement( QStringLiteral( "properties" ) ); if ( propertiesElem.isNull() ) { return QgsRectangle(); } - QDomElement extentElem = propertiesElem.firstChildElement( "WMSExtent" ); + QDomElement extentElem = propertiesElem.firstChildElement( QStringLiteral( "WMSExtent" ) ); if ( extentElem.isNull() ) { return QgsRectangle(); } - QDomNodeList valueNodeList = extentElem.elementsByTagName( "value" ); + QDomNodeList valueNodeList = extentElem.elementsByTagName( QStringLiteral( "value" ) ); if ( valueNodeList.size() < 4 ) { return QgsRectangle(); @@ -1006,15 +1006,15 @@ QStringList QgsServerProjectParser::supportedOutputCrsList() const { return crsList; } - QDomElement propertiesElem = qgisElem.firstChildElement( "properties" ); + QDomElement propertiesElem = qgisElem.firstChildElement( QStringLiteral( "properties" ) ); if ( propertiesElem.isNull() ) { return crsList; } - QDomElement wmsCrsElem = propertiesElem.firstChildElement( "WMSCrsList" ); + QDomElement wmsCrsElem = propertiesElem.firstChildElement( QStringLiteral( "WMSCrsList" ) ); if ( !wmsCrsElem.isNull() ) { - QDomNodeList valueList = wmsCrsElem.elementsByTagName( "value" ); + QDomNodeList valueList = wmsCrsElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { crsList.append( valueList.at( i ).toElement().text() ); @@ -1022,17 +1022,17 @@ QStringList QgsServerProjectParser::supportedOutputCrsList() const } else { - QDomElement wmsEpsgElem = propertiesElem.firstChildElement( "WMSEpsgList" ); + QDomElement wmsEpsgElem = propertiesElem.firstChildElement( QStringLiteral( "WMSEpsgList" ) ); if ( !wmsEpsgElem.isNull() ) { - QDomNodeList valueList = wmsEpsgElem.elementsByTagName( "value" ); + QDomNodeList valueList = wmsEpsgElem.elementsByTagName( QStringLiteral( "value" ) ); bool conversionOk; for ( int i = 0; i < valueList.size(); ++i ) { int epsgNr = valueList.at( i ).toElement().text().toInt( &conversionOk ); if ( conversionOk ) { - crsList.append( QString( "EPSG:%1" ).arg( epsgNr ) ); + crsList.append( QStringLiteral( "EPSG:%1" ).arg( epsgNr ) ); } } } @@ -1041,13 +1041,13 @@ QStringList QgsServerProjectParser::supportedOutputCrsList() const //no CRS restriction defined in the project. Provide project CRS, wgs84 and pseudo mercator QString projectCrsId = projectCrs().authid(); crsList.append( projectCrsId ); - if ( projectCrsId.compare( "EPSG:4326", Qt::CaseInsensitive ) != 0 ) + if ( projectCrsId.compare( QLatin1String( "EPSG:4326" ), Qt::CaseInsensitive ) != 0 ) { - crsList.append( QString( "EPSG:%1" ).arg( 4326 ) ); + crsList.append( QStringLiteral( "EPSG:%1" ).arg( 4326 ) ); } - if ( projectCrsId.compare( "EPSG:3857", Qt::CaseInsensitive ) != 0 ) + if ( projectCrsId.compare( QLatin1String( "EPSG:3857" ), Qt::CaseInsensitive ) != 0 ) { - crsList.append( QString( "EPSG:%1" ).arg( 3857 ) ); + crsList.append( QStringLiteral( "EPSG:%1" ).arg( 3857 ) ); } } } @@ -1068,7 +1068,7 @@ QString QgsServerProjectParser::projectTitle() const return QString(); } - QDomElement titleElem = qgisElem.firstChildElement( "title" ); + QDomElement titleElem = qgisElem.firstChildElement( QStringLiteral( "title" ) ); if ( !titleElem.isNull() ) { QString title = titleElem.text(); @@ -1089,7 +1089,7 @@ QDomElement QgsServerProjectParser::legendElem() const { return QDomElement(); } - return mXMLDoc->documentElement().firstChildElement( "legend" ); + return mXMLDoc->documentElement().firstChildElement( QStringLiteral( "legend" ) ); } QDomElement QgsServerProjectParser::propertiesElem() const @@ -1099,7 +1099,7 @@ QDomElement QgsServerProjectParser::propertiesElem() const return QDomElement(); } - return mXMLDoc->documentElement().firstChildElement( "properties" ); + return mXMLDoc->documentElement().firstChildElement( QStringLiteral( "properties" ) ); } QSet QgsServerProjectParser::findRestrictedLayers() const @@ -1112,14 +1112,14 @@ QSet QgsServerProjectParser::findRestrictedLayers() const } //names of unpublished layers / groups - QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" ); + QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "properties" ) ); if ( !propertiesElem.isNull() ) { - QDomElement wmsLayerRestrictionElem = propertiesElem.firstChildElement( "WMSRestrictedLayers" ); + QDomElement wmsLayerRestrictionElem = propertiesElem.firstChildElement( QStringLiteral( "WMSRestrictedLayers" ) ); if ( !wmsLayerRestrictionElem.isNull() ) { QStringList restrictedLayersAndGroups; - QDomNodeList wmsLayerRestrictionValues = wmsLayerRestrictionElem.elementsByTagName( "value" ); + QDomNodeList wmsLayerRestrictionValues = wmsLayerRestrictionElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < wmsLayerRestrictionValues.size(); ++i ) { restrictedLayerSet.insert( wmsLayerRestrictionValues.at( i ).toElement().text() ); @@ -1133,37 +1133,37 @@ QSet QgsServerProjectParser::findRestrictedLayers() const return restrictedLayerSet; } - QDomElement legendElem = mXMLDoc->documentElement().firstChildElement( "legend" ); + QDomElement legendElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "legend" ) ); if ( legendElem.isNull() ) { return restrictedLayerSet; } //go through all legend groups and insert names of subgroups / sublayers if there is a match - QDomNodeList legendGroupList = legendElem.elementsByTagName( "legendgroup" ); + QDomNodeList legendGroupList = legendElem.elementsByTagName( QStringLiteral( "legendgroup" ) ); for ( int i = 0; i < legendGroupList.size(); ++i ) { //get name QDomElement groupElem = legendGroupList.at( i ).toElement(); - QString groupName = groupElem.attribute( "name" ); + QString groupName = groupElem.attribute( QStringLiteral( "name" ) ); if ( restrictedLayerSet.contains( groupName ) ) //match: add names of subgroups and sublayers to set { //embedded group? -> also get names of subgroups and sublayers from embedded projects - if ( groupElem.attribute( "embedded" ) == "1" ) + if ( groupElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { - sublayersOfEmbeddedGroup( convertToAbsolutePath( groupElem.attribute( "project" ) ), groupName, restrictedLayerSet ); + sublayersOfEmbeddedGroup( convertToAbsolutePath( groupElem.attribute( QStringLiteral( "project" ) ) ), groupName, restrictedLayerSet ); } else //local group { - QDomNodeList subgroupList = groupElem.elementsByTagName( "legendgroup" ); + QDomNodeList subgroupList = groupElem.elementsByTagName( QStringLiteral( "legendgroup" ) ); for ( int j = 0; j < subgroupList.size(); ++j ) { - restrictedLayerSet.insert( subgroupList.at( j ).toElement().attribute( "name" ) ); + restrictedLayerSet.insert( subgroupList.at( j ).toElement().attribute( QStringLiteral( "name" ) ) ); } - QDomNodeList sublayerList = groupElem.elementsByTagName( "legendlayer" ); + QDomNodeList sublayerList = groupElem.elementsByTagName( QStringLiteral( "legendlayer" ) ); for ( int k = 0; k < sublayerList.size(); ++k ) { - restrictedLayerSet.insert( sublayerList.at( k ).toElement().attribute( "name" ) ); + restrictedLayerSet.insert( sublayerList.at( k ).toElement().attribute( QStringLiteral( "name" ) ) ); } } } @@ -1172,20 +1172,20 @@ QSet QgsServerProjectParser::findRestrictedLayers() const // wmsLayerRestrictionValues contains LayerIDs if ( mUseLayerIDs ) { - QDomNodeList legendLayerList = legendElem.elementsByTagName( "legendlayer" ); + QDomNodeList legendLayerList = legendElem.elementsByTagName( QStringLiteral( "legendlayer" ) ); for ( int i = 0; i < legendLayerList.size(); ++i ) { //get name QDomElement layerElem = legendLayerList.at( i ).toElement(); - QString layerName = layerElem.attribute( "name" ); + QString layerName = layerElem.attribute( QStringLiteral( "name" ) ); if ( restrictedLayerSet.contains( layerName ) ) //match: add layer id { // get legend layer file element - QDomNodeList layerfileList = layerElem.elementsByTagName( "legendlayerfile" ); + QDomNodeList layerfileList = layerElem.elementsByTagName( QStringLiteral( "legendlayerfile" ) ); if ( !layerfileList.isEmpty() ) { // add layer id - restrictedLayerSet.insert( layerfileList.at( 0 ).toElement().attribute( "layerid" ) ); + restrictedLayerSet.insert( layerfileList.at( 0 ).toElement().attribute( QStringLiteral( "layerid" ) ) ); } } } @@ -1198,20 +1198,20 @@ bool QgsServerProjectParser::findUseLayerIds() const if ( !mXMLDoc ) return false; - QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" ); + QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "properties" ) ); if ( propertiesElem.isNull() ) return false; - QDomElement wktElem = propertiesElem.firstChildElement( "WMSUseLayerIDs" ); + QDomElement wktElem = propertiesElem.firstChildElement( QStringLiteral( "WMSUseLayerIDs" ) ); if ( wktElem.isNull() ) return false; - return wktElem.text().compare( "true", Qt::CaseInsensitive ) == 0; + return wktElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0; } void QgsServerProjectParser::layerFromLegendLayer( const QDomElement& legendLayerElem, QMap< int, QgsMapLayer*>& layers, bool useCache ) const { - QString id = legendLayerElem.firstChild().firstChild().toElement().attribute( "layerid" ); + QString id = legendLayerElem.firstChild().firstChild().toElement().attribute( QStringLiteral( "layerid" ) ); int drawingOrder = updateLegendDrawingOrder() ? -1 : mCustomLayerOrder.indexOf( id ); QHash< QString, QDomElement >::const_iterator layerIt = mProjectLayerElementsById.find( id ); @@ -1230,13 +1230,13 @@ QList QgsServerProjectParser::findLegendGroupElements() const QList LegendGroupElemList; QgsLayerTreeGroup* rootLayerTreeGroup = new QgsLayerTreeGroup; - QDomElement layerTreeElem = mXMLDoc->documentElement().firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "layer-tree-group" ) ); if ( !layerTreeElem.isNull() ) { rootLayerTreeGroup = QgsLayerTreeGroup::readXml( layerTreeElem ); } - QDomElement legendElement = mXMLDoc->documentElement().firstChildElement( "legend" ); + QDomElement legendElement = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "legend" ) ); if ( !legendElement.isNull() && rootLayerTreeGroup ) { LegendGroupElemList.append( setLegendGroupElementsWithLayerTree( rootLayerTreeGroup, legendElement ) ); @@ -1244,7 +1244,7 @@ QList QgsServerProjectParser::findLegendGroupElements() const if ( !legendElement.isNull() ) { - QDomNodeList groupNodeList = legendElement.elementsByTagName( "legendgroup" ); + QDomNodeList groupNodeList = legendElement.elementsByTagName( QStringLiteral( "legendgroup" ) ); for ( int i = 0; i < groupNodeList.size(); ++i ) { LegendGroupElemList.push_back( groupNodeList.at( i ).toElement() ); @@ -1266,7 +1266,7 @@ QList QgsServerProjectParser::setLegendGroupElementsWithLayerTree( if ( !legendElementNode.isElement() ) continue; QDomElement legendElement = legendElementNode.toElement(); - if ( legendElement.tagName() != "legendgroup" ) + if ( legendElement.tagName() != QLatin1String( "legendgroup" ) ) continue; for ( int j = g; j < i + 1; ++j ) { @@ -1274,15 +1274,15 @@ QList QgsServerProjectParser::setLegendGroupElementsWithLayerTree( if ( layerTreeNode->nodeType() != QgsLayerTreeNode::NodeGroup ) continue; QgsLayerTreeGroup* layerTreeGroup = static_cast( layerTreeNode ); - if ( layerTreeGroup->name() == legendElement.attribute( "name" ) ) + if ( layerTreeGroup->name() == legendElement.attribute( QStringLiteral( "name" ) ) ) { g = j; - QString shortName = layerTreeGroup->customProperty( "wmsShortName" ).toString(); + QString shortName = layerTreeGroup->customProperty( QStringLiteral( "wmsShortName" ) ).toString(); if ( !shortName.isEmpty() ) - legendElement.setAttribute( "shortName", shortName ); - QString title = layerTreeGroup->customProperty( "wmsTitle" ).toString(); + legendElement.setAttribute( QStringLiteral( "shortName" ), shortName ); + QString title = layerTreeGroup->customProperty( QStringLiteral( "wmsTitle" ) ).toString(); if ( !title.isEmpty() ) - legendElement.setAttribute( "title", title ); + legendElement.setAttribute( QStringLiteral( "title" ), title ); LegendGroupElemList.append( setLegendGroupElementsWithLayerTree( layerTreeGroup, legendElement ) ); } } @@ -1306,33 +1306,33 @@ void QgsServerProjectParser::sublayersOfEmbeddedGroup( const QString& projectFil } //go to legend node - QDomElement legendElem = xmlDoc.documentElement().firstChildElement( "legend" ); + QDomElement legendElem = xmlDoc.documentElement().firstChildElement( QStringLiteral( "legend" ) ); if ( legendElem.isNull() ) { return; } //get group node list of embedded project - QDomNodeList groupNodes = legendElem.elementsByTagName( "legendgroup" ); + QDomNodeList groupNodes = legendElem.elementsByTagName( QStringLiteral( "legendgroup" ) ); QDomElement groupElem; for ( int i = 0; i < groupNodes.size(); ++i ) { groupElem = groupNodes.at( i ).toElement(); - if ( groupElem.attribute( "name" ) == groupName ) + if ( groupElem.attribute( QStringLiteral( "name" ) ) == groupName ) { //get all subgroups and sublayers and add to layerSet QDomElement subElem; - QDomNodeList subGroupList = groupElem.elementsByTagName( "legendgroup" ); + QDomNodeList subGroupList = groupElem.elementsByTagName( QStringLiteral( "legendgroup" ) ); for ( int j = 0; j < subGroupList.size(); ++j ) { subElem = subGroupList.at( j ).toElement(); - layerSet.insert( subElem.attribute( "name" ) ); + layerSet.insert( subElem.attribute( QStringLiteral( "name" ) ) ); } - QDomNodeList subLayerList = groupElem.elementsByTagName( "legendlayer" ); + QDomNodeList subLayerList = groupElem.elementsByTagName( QStringLiteral( "legendlayer" ) ); for ( int j = 0; j < subLayerList.size(); ++j ) { subElem = subLayerList.at( j ).toElement(); - layerSet.insert( subElem.attribute( "name" ) ); + layerSet.insert( subElem.attribute( QStringLiteral( "name" ) ) ); } } } @@ -1403,17 +1403,17 @@ QDomElement QgsServerProjectParser::firstComposerLegendElement() const return QDomElement(); } - QDomElement composerElem = documentElem.firstChildElement( "Composer" ); + QDomElement composerElem = documentElem.firstChildElement( QStringLiteral( "Composer" ) ); if ( composerElem.isNull() ) { return QDomElement(); } - QDomElement compositionElem = composerElem.firstChildElement( "Composition" ); + QDomElement compositionElem = composerElem.firstChildElement( QStringLiteral( "Composition" ) ); if ( compositionElem.isNull() ) { return QDomElement(); } - return compositionElem.firstChildElement( "ComposerLegend" ); + return compositionElem.firstChildElement( QStringLiteral( "ComposerLegend" ) ); } QList QgsServerProjectParser::publishedComposerElements() const @@ -1424,10 +1424,10 @@ QList QgsServerProjectParser::publishedComposerElements() const return composerElemList; } - QDomNodeList composerNodeList = mXMLDoc->elementsByTagName( "Composer" ); + QDomNodeList composerNodeList = mXMLDoc->elementsByTagName( QStringLiteral( "Composer" ) ); - QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" ); - QDomElement wmsRestrictedComposersElem = propertiesElem.firstChildElement( "WMSRestrictedComposers" ); + QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "properties" ) ); + QDomElement wmsRestrictedComposersElem = propertiesElem.firstChildElement( QStringLiteral( "WMSRestrictedComposers" ) ); if ( wmsRestrictedComposersElem.isNull() ) { for ( int i = 0; i < composerNodeList.size(); ++i ) @@ -1438,7 +1438,7 @@ QList QgsServerProjectParser::publishedComposerElements() const } QSet restrictedComposerNames; - QDomNodeList valueList = wmsRestrictedComposersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wmsRestrictedComposersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { restrictedComposerNames.insert( valueList.at( i ).toElement().text() ); @@ -1450,7 +1450,7 @@ QList QgsServerProjectParser::publishedComposerElements() const for ( int i = 0; i < composerNodeList.size(); ++i ) { currentElem = composerNodeList.at( i ).toElement(); - currentComposerName = currentElem.attribute( "title" ); + currentComposerName = currentElem.attribute( QStringLiteral( "title" ) ); if ( !restrictedComposerNames.contains( currentComposerName ) ) { composerElemList.push_back( currentElem ); @@ -1464,24 +1464,24 @@ QList< QPair< QString, QgsLayerCoordinateTransform > > QgsServerProjectParser::l { QList< QPair< QString, QgsLayerCoordinateTransform > > layerTransformList; - QDomElement coordTransformInfoElem = mXMLDoc->documentElement().firstChildElement( "mapcanvas" ).firstChildElement( "layer_coordinate_transform_info" ); + QDomElement coordTransformInfoElem = mXMLDoc->documentElement().firstChildElement( QStringLiteral( "mapcanvas" ) ).firstChildElement( QStringLiteral( "layer_coordinate_transform_info" ) ); if ( coordTransformInfoElem.isNull() ) { return layerTransformList; } - QDomNodeList layerTransformNodeList = coordTransformInfoElem.elementsByTagName( "layer_coordinate_transform" ); + QDomNodeList layerTransformNodeList = coordTransformInfoElem.elementsByTagName( QStringLiteral( "layer_coordinate_transform" ) ); layerTransformList.reserve( layerTransformNodeList.size() ); for ( int i = 0; i < layerTransformNodeList.size(); ++i ) { QPair< QString, QgsLayerCoordinateTransform > layerEntry; QDomElement layerTransformElem = layerTransformNodeList.at( i ).toElement(); - layerEntry.first = layerTransformElem.attribute( "layerid" ); + layerEntry.first = layerTransformElem.attribute( QStringLiteral( "layerid" ) ); QgsLayerCoordinateTransform t; - t.srcAuthId = layerTransformElem.attribute( "srcAuthId" ); - t.destAuthId = layerTransformElem.attribute( "destAuthId" ); - t.srcDatumTransform = layerTransformElem.attribute( "srcDatumTransform", "-1" ).toInt(); - t.destDatumTransform = layerTransformElem.attribute( "destDatumTransform", "-1" ).toInt(); + t.srcAuthId = layerTransformElem.attribute( QStringLiteral( "srcAuthId" ) ); + t.destAuthId = layerTransformElem.attribute( QStringLiteral( "destAuthId" ) ); + t.srcDatumTransform = layerTransformElem.attribute( QStringLiteral( "srcDatumTransform" ), QStringLiteral( "-1" ) ).toInt(); + t.destDatumTransform = layerTransformElem.attribute( QStringLiteral( "destDatumTransform" ), QStringLiteral( "-1" ) ).toInt(); layerEntry.second = t; layerTransformList.push_back( layerEntry ); } @@ -1501,17 +1501,17 @@ QStringList QgsServerProjectParser::wfsLayers() const { return wfsList; } - QDomElement propertiesElem = qgisElem.firstChildElement( "properties" ); + QDomElement propertiesElem = qgisElem.firstChildElement( QStringLiteral( "properties" ) ); if ( propertiesElem.isNull() ) { return wfsList; } - QDomElement wfsLayersElem = propertiesElem.firstChildElement( "WFSLayers" ); + QDomElement wfsLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WFSLayers" ) ); if ( wfsLayersElem.isNull() ) { return wfsList; } - QDomNodeList valueList = wfsLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wfsLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { wfsList << valueList.at( i ).toElement().text(); @@ -1532,17 +1532,17 @@ QStringList QgsServerProjectParser::wcsLayers() const { return wcsList; } - QDomElement propertiesElem = qgisElem.firstChildElement( "properties" ); + QDomElement propertiesElem = qgisElem.firstChildElement( QStringLiteral( "properties" ) ); if ( propertiesElem.isNull() ) { return wcsList; } - QDomElement wcsLayersElem = propertiesElem.firstChildElement( "WCSLayers" ); + QDomElement wcsLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WCSLayers" ) ); if ( wcsLayersElem.isNull() ) { return wcsList; } - QDomNodeList valueList = wcsLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wcsLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { wcsList << valueList.at( i ).toElement().text(); @@ -1552,16 +1552,16 @@ QStringList QgsServerProjectParser::wcsLayers() const void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerElem ) const { - QDomElement vectorJoinsElem = layerElem.firstChildElement( "vectorjoins" ); + QDomElement vectorJoinsElem = layerElem.firstChildElement( QStringLiteral( "vectorjoins" ) ); if ( vectorJoinsElem.isNull() ) { return; } - QDomNodeList joinNodeList = vectorJoinsElem.elementsByTagName( "join" ); + QDomNodeList joinNodeList = vectorJoinsElem.elementsByTagName( QStringLiteral( "join" ) ); for ( int i = 0; i < joinNodeList.size(); ++i ) { - QString id = joinNodeList.at( i ).toElement().attribute( "joinLayerId" ); + QString id = joinNodeList.at( i ).toElement().attribute( QStringLiteral( "joinLayerId" ) ); QgsMapLayer* layer = mapLayerFromLayerId( id ); if ( layer && !QgsMapLayerRegistry::instance()->mapLayer( id ) ) { @@ -1578,14 +1578,14 @@ void QgsServerProjectParser::addValueRelationLayersForLayer( const QgsVectorLaye for ( int idx = 0; idx < vl->pendingFields().size(); idx++ ) { const QString name = vl->pendingFields().field( idx ).name(); - if ( vl->editFormConfig().widgetType( name ) != "ValueRelation" ) + if ( vl->editFormConfig().widgetType( name ) != QLatin1String( "ValueRelation" ) ) continue; QgsEditorWidgetConfig cfg( vl->editFormConfig().widgetConfig( name ) ); - if ( !cfg.contains( "Layer" ) ) + if ( !cfg.contains( QStringLiteral( "Layer" ) ) ) continue; - QString layerId = cfg.value( "Layer" ).toString(); + QString layerId = cfg.value( QStringLiteral( "Layer" ) ).toString(); if ( QgsMapLayerRegistry::instance()->mapLayer( layerId ) ) continue; diff --git a/src/server/qgsserverstreamingdevice.cpp b/src/server/qgsserverstreamingdevice.cpp index 8977927d0621..8682c8c5c4b1 100644 --- a/src/server/qgsserverstreamingdevice.cpp +++ b/src/server/qgsserverstreamingdevice.cpp @@ -36,7 +36,7 @@ bool QgsServerStreamingDevice::open( OpenMode mode ) return false; } - mRequestHandler->setHeader( "Content-Type", mFormatName ); + mRequestHandler->setHeader( QStringLiteral( "Content-Type" ), mFormatName ); mRequestHandler->sendResponse(); return QIODevice::open( mode ); } diff --git a/src/server/qgssldconfigparser.cpp b/src/server/qgssldconfigparser.cpp index 8321402d3583..04064cba2cf7 100644 --- a/src/server/qgssldconfigparser.cpp +++ b/src/server/qgssldconfigparser.cpp @@ -58,7 +58,7 @@ QgsSLDConfigParser::QgsSLDConfigParser( QDomDocument* doc, const QMapdocumentElement(); if ( !sldElement.isNull() ) { - QString unitString = sldElement.attribute( "units" ); + QString unitString = sldElement.attribute( QStringLiteral( "units" ) ); if ( !unitString.isEmpty() ) { - if ( unitString == "mm" ) + if ( unitString == QLatin1String( "mm" ) ) { mOutputUnits = QgsMapRenderer::Millimeters; } - else if ( unitString == "pixel" ) + else if ( unitString == QLatin1String( "pixel" ) ) { mOutputUnits = QgsMapRenderer::Pixels; } @@ -106,38 +106,38 @@ void QgsSLDConfigParser::layersAndStylesCapabilities( QDomElement& parentElement //QgsCoordinateReferenceSystem wgs84; //wgs84.createFromEpsg(4326); - QDomNodeList layerNodeList = sldNode.toElement().elementsByTagName( "UserLayer" ); + QDomNodeList layerNodeList = sldNode.toElement().elementsByTagName( QStringLiteral( "UserLayer" ) ); for ( int i = 0; i < layerNodeList.size(); ++i ) { - QDomElement layerElement = doc.createElement( "Layer" ); - layerElement.setAttribute( "queryable", "1" ); //support GetFeatureInfo for all layers + QDomElement layerElement = doc.createElement( QStringLiteral( "Layer" ) ); + layerElement.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "1" ) ); //support GetFeatureInfo for all layers parentElement.appendChild( layerElement ); //add name - QDomNodeList nameList = layerNodeList.item( i ).toElement().elementsByTagName( "Name" ); + QDomNodeList nameList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { //layer name - QDomElement layerNameElement = doc.createElement( "Name" ); + QDomElement layerNameElement = doc.createElement( QStringLiteral( "Name" ) ); QDomText layerNameText = doc.createTextNode( nameList.item( 0 ).toElement().text() ); layerNameElement.appendChild( layerNameText ); layerElement.appendChild( layerNameElement ); } //add title - QDomNodeList titleList = layerNodeList.item( i ).toElement().elementsByTagName( "Title" ); + QDomNodeList titleList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "Title" ) ); if ( !titleList.isEmpty() ) { - QDomElement layerTitleElement = doc.createElement( "Title" ); + QDomElement layerTitleElement = doc.createElement( QStringLiteral( "Title" ) ); QDomText layerTitleText = doc.createTextNode( titleList.item( 0 ).toElement().text() ); layerTitleElement.appendChild( layerTitleText ); layerElement.appendChild( layerTitleElement ); } //add abstract - QDomNodeList abstractList = layerNodeList.item( i ).toElement().elementsByTagName( "Abstract" ); + QDomNodeList abstractList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "Abstract" ) ); if ( !abstractList.isEmpty() ) { - QDomElement layerAbstractElement = doc.createElement( "Abstract" ); + QDomElement layerAbstractElement = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText layerAbstractText = doc.createTextNode( abstractList.item( 0 ).toElement().text() ); layerAbstractElement.appendChild( layerAbstractText ); layerElement.appendChild( layerAbstractElement ); @@ -145,7 +145,7 @@ void QgsSLDConfigParser::layersAndStylesCapabilities( QDomElement& parentElement //get QgsMapLayer object to add Ex_GeographicalBoundingBox, Bounding Box - QList layerList = mapLayerFromStyle( nameList.item( 0 ).toElement().text(), "" ); + QList layerList = mapLayerFromStyle( nameList.item( 0 ).toElement().text(), QLatin1String( "" ) ); if ( layerList.size() < 1 )//error while generating the layer { QgsDebugMsg( "Error, no maplayer in layer list" ); @@ -167,39 +167,39 @@ void QgsSLDConfigParser::layersAndStylesCapabilities( QDomElement& parentElement QgsConfigParserUtils::appendLayerBoundingBoxes( layerElement, doc, theMapLayer->extent(), theMapLayer->crs(), crsNumbers, crsRestriction ); //iterate over all nodes within a user layer - QDomNodeList userStyleList = layerNodeList.item( i ).toElement().elementsByTagName( "UserStyle" ); + QDomNodeList userStyleList = layerNodeList.item( i ).toElement().elementsByTagName( QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); ++j ) { - QDomElement styleElement = doc.createElement( "Style" ); + QDomElement styleElement = doc.createElement( QStringLiteral( "Style" ) ); layerElement.appendChild( styleElement ); //Name - QDomNodeList nameList = userStyleList.item( j ).toElement().elementsByTagName( "Name" ); + QDomNodeList nameList = userStyleList.item( j ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { - QDomElement styleNameElement = doc.createElement( "Name" ); + QDomElement styleNameElement = doc.createElement( QStringLiteral( "Name" ) ); QDomText styleNameText = doc.createTextNode( nameList.item( 0 ).toElement().text() ); styleNameElement.appendChild( styleNameText ); styleElement.appendChild( styleNameElement ); - QDomElement styleTitleElement = doc.createElement( "Title" ); + QDomElement styleTitleElement = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( nameList.item( 0 ).toElement().text() ); styleTitleElement.appendChild( styleTitleText ); styleElement.appendChild( styleTitleElement ); } //Title - QDomNodeList titleList = userStyleList.item( j ).toElement().elementsByTagName( "Title" ); + QDomNodeList titleList = userStyleList.item( j ).toElement().elementsByTagName( QStringLiteral( "Title" ) ); if ( !titleList.isEmpty() ) { - QDomElement styleTitleElement = doc.createElement( "Title" ); + QDomElement styleTitleElement = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( titleList.item( 0 ).toElement().text() ); styleTitleElement.appendChild( styleTitleText ); styleElement.appendChild( styleTitleElement ); } //Abstract - QDomNodeList abstractList = userStyleList.item( j ).toElement().elementsByTagName( "Abstract" ); + QDomNodeList abstractList = userStyleList.item( j ).toElement().elementsByTagName( QStringLiteral( "Abstract" ) ); if ( !abstractList.isEmpty() ) { - QDomElement styleAbstractElement = doc.createElement( "Abstract" ); + QDomElement styleAbstractElement = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText styleAbstractText = doc.createTextNode( abstractList.item( 0 ).toElement().text() ); styleAbstractElement.appendChild( styleAbstractText ); styleElement.appendChild( styleAbstractElement ); @@ -222,7 +222,7 @@ QList QgsSLDConfigParser::mapLayerFromStyle( const QString& lName, QDomElement userStyleElement = findUserStyleElement( namedLayerElemList[i], styleName ); if ( !userStyleElement.isNull() ) { - fallbackLayerList = mFallbackParser->mapLayerFromStyle( lName, "", false ); + fallbackLayerList = mFallbackParser->mapLayerFromStyle( lName, QLatin1String( "" ), false ); if ( !fallbackLayerList.isEmpty() ) { QgsVectorLayer* v = dynamic_cast( fallbackLayerList.at( 0 ) ); @@ -357,11 +357,11 @@ int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& style for ( int i = 0; i < layerNodes.size(); ++i ) { QDomElement currentLayerElement = layerNodes.item( i ).toElement(); - if ( currentLayerElement.localName() == "NamedLayer" ) + if ( currentLayerElement.localName() == QLatin1String( "NamedLayer" ) ) { QgsDebugMsg( "Found a NamedLayer" ); //layer name - QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ "Name" ); + QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( nameList.length() < 1 ) { continue; //a layer name is mandatory @@ -369,10 +369,10 @@ int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& style QString layerName = nameList.item( 0 ).toElement().text(); //find the Named Styles and the corresponding names - QDomNodeList namedStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ "NamedStyle" ); + QDomNodeList namedStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "NamedStyle" ) ); for ( int j = 0; j < namedStyleList.size(); ++j ) { - QDomNodeList styleNameList = namedStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ "Name" ); + QDomNodeList styleNameList = namedStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( styleNameList.size() < 1 ) { continue; //a layer name is mandatory @@ -384,10 +384,10 @@ int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& style } //named layers can also have User Styles - QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ "UserStyle" ); + QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); ++j ) { - QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ "Name" ); + QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( styleNameList.size() < 1 ) { continue; //a layer name is mandatory @@ -398,11 +398,11 @@ int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& style styles.push_back( styleName ); } } - else if ( currentLayerElement.localName() == "UserLayer" ) + else if ( currentLayerElement.localName() == QLatin1String( "UserLayer" ) ) { QgsDebugMsg( "Found a UserLayer" ); //layer name - QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ "Name" ); + QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( nameList.length() < 1 ) { QgsDebugMsg( "Namelist size is <1" ); @@ -411,10 +411,10 @@ int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& style QString layerName = nameList.item( 0 ).toElement().text(); QgsDebugMsg( "layerName is: " + layerName ); //find the User Styles and the corresponding names - QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ "UserStyle" ); + QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); ++j ) { - QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ "Name" ); + QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) ); if ( styleNameList.size() < 1 ) { QgsDebugMsg( "Namelist size is <1" ); @@ -443,14 +443,14 @@ QDomDocument QgsSLDConfigParser::getStyle( const QString& styleName, const QStri if ( userLayerElement.isNull() ) { - throw QgsMapServiceException( "LayerNotDefined", "Operation request is for a Layer not offered by the server." ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a Layer not offered by the server." ) ); } QDomElement userStyleElement = findUserStyleElement( userLayerElement, styleName ); if ( userStyleElement.isNull() ) { - throw QgsMapServiceException( "StyleNotDefined", "Operation request references a Style not offered by the server." ); + throw QgsMapServiceException( QStringLiteral( "StyleNotDefined" ), QStringLiteral( "Operation request references a Style not offered by the server." ) ); } QDomDocument styleDoc; @@ -468,9 +468,9 @@ QDomDocument QgsSLDConfigParser::getStyles( QStringList& layerList ) const QDomElement userLayerElement = findUserLayerElement( layerName ); if ( userLayerElement.isNull() ) { - throw QgsMapServiceException( "LayerNotDefined", "Operation request is for a Layer not offered by the server." ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a Layer not offered by the server." ) ); } - QDomNodeList userStyleList = userLayerElement.elementsByTagName( "UserStyle" ); + QDomNodeList userStyleList = userLayerElement.elementsByTagName( QStringLiteral( "UserStyle" ) ); for ( int j = 0; j < userStyleList.size(); j++ ) { QDomElement userStyleElement = userStyleList.item( i ).toElement(); @@ -779,7 +779,7 @@ int QgsSLDConfigParser::nLayers() const QDomNode sldNode = mXMLDoc->documentElement(); if ( !sldNode.isNull() ) { - QDomNodeList layerNodeList = sldNode.toElement().elementsByTagName( "UserLayer" ); + QDomNodeList layerNodeList = sldNode.toElement().elementsByTagName( QStringLiteral( "UserLayer" ) ); return layerNodeList.size(); } } @@ -806,10 +806,10 @@ QList QgsSLDConfigParser::findNamedLayerElements( const QString& la QDomElement sldElement = mXMLDoc->documentElement(); if ( !sldElement.isNull() ) { - QDomNodeList NamedLayerList = sldElement.elementsByTagName( "NamedLayer" ); + QDomNodeList NamedLayerList = sldElement.elementsByTagName( QStringLiteral( "NamedLayer" ) ); for ( int i = 0; i < NamedLayerList.size(); ++i ) { - QDomNodeList nameList = NamedLayerList.item( i ).toElement().elementsByTagName( "Name" ); + QDomNodeList nameList = NamedLayerList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { if ( nameList.item( 0 ).toElement().text() == layerName ) @@ -828,10 +828,10 @@ QDomElement QgsSLDConfigParser::findUserStyleElement( const QDomElement& userLay QDomElement defaultResult; if ( !userLayerElement.isNull() ) { - QDomNodeList userStyleList = userLayerElement.elementsByTagName( "UserStyle" ); + QDomNodeList userStyleList = userLayerElement.elementsByTagName( QStringLiteral( "UserStyle" ) ); for ( int i = 0; i < userStyleList.size(); ++i ) { - QDomNodeList nameList = userStyleList.item( i ).toElement().elementsByTagName( "Name" ); + QDomNodeList nameList = userStyleList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { if ( nameList.item( 0 ).toElement().text() == styleName ) @@ -849,10 +849,10 @@ QDomElement QgsSLDConfigParser::findNamedStyleElement( const QDomElement& layerE QDomElement defaultResult; if ( !layerElement.isNull() ) { - QDomNodeList styleList = layerElement.elementsByTagName( "NamedStyle" ); + QDomNodeList styleList = layerElement.elementsByTagName( QStringLiteral( "NamedStyle" ) ); for ( int i = 0; i < styleList.size(); ++i ) { - QDomNodeList nameList = styleList.item( i ).toElement().elementsByTagName( "Name" ); + QDomNodeList nameList = styleList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { if ( nameList.item( 0 ).toElement().text() == styleName ) @@ -878,7 +878,7 @@ QgsFeatureRenderer* QgsSLDConfigParser::rendererFromUserStyle( const QDomElement QgsFeatureRenderer* renderer = QgsFeatureRenderer::loadSld( userStyleElement.parentNode(), vec->geometryType(), errorMessage ); if ( !renderer ) { - throw QgsMapServiceException( "SLD error", errorMessage ); + throw QgsMapServiceException( QStringLiteral( "SLD error" ), errorMessage ); } return renderer; } @@ -995,7 +995,7 @@ QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& u } //get element - QDomNodeList contourNodeList = userStyleElem.elementsByTagName( "ContourSymbolizer" ); + QDomNodeList contourNodeList = userStyleElem.elementsByTagName( QStringLiteral( "ContourSymbolizer" ) ); if ( contourNodeList.size() < 1 ) { return nullptr; @@ -1010,11 +1010,11 @@ QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& u double equidistance, minValue, maxValue, offset; QString propertyName; - equidistance = contourSymbolizerElem.attribute( "equidistance" ).toDouble(); - minValue = contourSymbolizerElem.attribute( "minValue" ).toDouble(); - maxValue = contourSymbolizerElem.attribute( "maxValue" ).toDouble(); - offset = contourSymbolizerElem.attribute( "offset" ).toDouble(); - propertyName = contourSymbolizerElem.attribute( "propertyName" ); + equidistance = contourSymbolizerElem.attribute( QStringLiteral( "equidistance" ) ).toDouble(); + minValue = contourSymbolizerElem.attribute( QStringLiteral( "minValue" ) ).toDouble(); + maxValue = contourSymbolizerElem.attribute( QStringLiteral( "maxValue" ) ).toDouble(); + offset = contourSymbolizerElem.attribute( QStringLiteral( "offset" ) ).toDouble(); + propertyName = contourSymbolizerElem.attribute( QStringLiteral( "propertyName" ) ); if ( equidistance <= 0.0 ) { @@ -1073,7 +1073,7 @@ QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& u if ( !hSrcDS ) { delete [] adfFixedLevels; - throw QgsMapServiceException( "LayerNotDefined", "Operation request is for a file not available on the server." ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) ); } hBand = GDALGetRasterBand( hSrcDS, nBandIn ); @@ -1110,14 +1110,14 @@ QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& u { //fprintf( FCGI_stderr, "Unable to find format driver named 'ESRI Shapefile'.\n" ); delete [] adfFixedLevels; - throw QgsMapServiceException( "LayerNotDefined", "Operation request is for a file not available on the server." ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request is for a file not available on the server." ) ); } hDS = OGR_Dr_CreateDataSource( hDriver, TO8( tmpFileName ), nullptr ); if ( !hDS ) { delete [] adfFixedLevels; - throw QgsMapServiceException( "LayerNotDefined", "Operation request cannot create data source." ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request cannot create data source." ) ); } hLayer = OGR_DS_CreateLayer( hDS, "contour", hSRS, @@ -1126,7 +1126,7 @@ QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& u if ( !hLayer ) { delete [] adfFixedLevels; - throw QgsMapServiceException( "LayerNotDefined", "Operation request could not create contour file." ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Operation request could not create contour file." ) ); } hFld = OGR_Fld_Create( "ID", OFTInteger ); @@ -1164,7 +1164,7 @@ QgsVectorLayer* QgsSLDConfigParser::contourLayerFromRaster( const QDomElement& u mFilePathsToRemove.push_back( tmpBaseName + ".dbf" ); mFilePathsToRemove.push_back( tmpBaseName + ".shx" ); - QgsVectorLayer* contourLayer = new QgsVectorLayer( tmpFileName, "layer", "ogr" ); + QgsVectorLayer* contourLayer = new QgsVectorLayer( tmpFileName, QStringLiteral( "layer" ), QStringLiteral( "ogr" ) ); //create renderer QgsFeatureRenderer* theRenderer = rendererFromUserStyle( userStyleElem, contourLayer ); @@ -1185,10 +1185,10 @@ QDomElement QgsSLDConfigParser::findUserLayerElement( const QString& layerName ) QDomElement sldElement = mXMLDoc->documentElement(); if ( !sldElement.isNull() ) { - QDomNodeList UserLayerList = sldElement.elementsByTagName( "UserLayer" ); + QDomNodeList UserLayerList = sldElement.elementsByTagName( QStringLiteral( "UserLayer" ) ); for ( int i = 0; i < UserLayerList.size(); ++i ) { - QDomNodeList nameList = UserLayerList.item( i ).toElement().elementsByTagName( "Name" ); + QDomNodeList nameList = UserLayerList.item( i ).toElement().elementsByTagName( QStringLiteral( "Name" ) ); if ( !nameList.isEmpty() ) { if ( nameList.item( 0 ).toElement().text() == layerName ) @@ -1209,7 +1209,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL QDomElement builderRootElement; //hosted vector data? - QDomNode hostedVDSNode = userLayerElem.namedItem( "HostedVDS" ); + QDomNode hostedVDSNode = userLayerElem.namedItem( QStringLiteral( "HostedVDS" ) ); if ( !hostedVDSNode.isNull() ) { builderRootElement = hostedVDSNode.toElement(); @@ -1217,7 +1217,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL } //hosted raster data? - QDomNode hostedRDSNode = userLayerElem.namedItem( "HostedRDS" ); + QDomNode hostedRDSNode = userLayerElem.namedItem( QStringLiteral( "HostedRDS" ) ); if ( !layerBuilder && !hostedRDSNode.isNull() ) { builderRootElement = hostedRDSNode.toElement(); @@ -1225,7 +1225,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL } //remote OWS (WMS, WFS, WCS)? - QDomNode remoteOWSNode = userLayerElem.namedItem( "RemoteOWS" ); + QDomNode remoteOWSNode = userLayerElem.namedItem( QStringLiteral( "RemoteOWS" ) ); if ( !layerBuilder && !remoteOWSNode.isNull() ) { builderRootElement = remoteOWSNode.toElement(); @@ -1233,7 +1233,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL } //remote vector/raster datasource - QDomNode remoteRDSNode = userLayerElem.namedItem( "RemoteRDS" ); + QDomNode remoteRDSNode = userLayerElem.namedItem( QStringLiteral( "RemoteRDS" ) ); if ( !layerBuilder && !remoteRDSNode.isNull() ) { builderRootElement = remoteRDSNode.toElement(); @@ -1241,7 +1241,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL QgsDebugMsg( "Detected remote raster datasource" ); } - QDomNode remoteVDSNode = userLayerElem.namedItem( "RemoteVDS" ); + QDomNode remoteVDSNode = userLayerElem.namedItem( QStringLiteral( "RemoteVDS" ) ); if ( !layerBuilder && !remoteVDSNode.isNull() ) { builderRootElement = remoteVDSNode.toElement(); @@ -1250,14 +1250,14 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL } //sent vector/raster datasource - QDomNode sentVDSNode = userLayerElem.namedItem( "SentVDS" ); + QDomNode sentVDSNode = userLayerElem.namedItem( QStringLiteral( "SentVDS" ) ); if ( !layerBuilder && !sentVDSNode.isNull() ) { builderRootElement = sentVDSNode.toElement(); layerBuilder = new QgsSentDataSourceBuilder(); } - QDomNode sentRDSNode = userLayerElem.namedItem( "SentRDS" ); + QDomNode sentRDSNode = userLayerElem.namedItem( QStringLiteral( "SentRDS" ) ); if ( !layerBuilder && !sentRDSNode.isNull() ) { builderRootElement = sentRDSNode.toElement(); @@ -1278,7 +1278,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL //maybe the datasource is defined in the fallback SLD? if ( !theMapLayer && mFallbackParser ) { - QList fallbackList = mFallbackParser->mapLayerFromStyle( layerName, "", allowCaching ); + QList fallbackList = mFallbackParser->mapLayerFromStyle( layerName, QLatin1String( "" ), allowCaching ); if ( !fallbackList.isEmpty() ) { QgsMapLayer* fallbackLayer = fallbackList.at( 0 ); //todo: prevent crash if layer list is empty @@ -1305,7 +1305,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL //raster layer from interpolation - QDomNode rasterInterpolationNode = userLayerElem.namedItem( "RasterInterpolation" ); + QDomNode rasterInterpolationNode = userLayerElem.namedItem( QStringLiteral( "RasterInterpolation" ) ); if ( !rasterInterpolationNode.isNull() ) { QgsVectorLayer* vectorCast = dynamic_cast( theMapLayer ); @@ -1323,7 +1323,7 @@ QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userL void QgsSLDConfigParser::setCrsForLayer( const QDomElement& layerElem, QgsMapLayer* ml ) const { //create CRS if specified as attribute ("epsg" or "proj") - QString epsg = layerElem.attribute( "epsg", "" ); + QString epsg = layerElem.attribute( QStringLiteral( "epsg" ), QLatin1String( "" ) ); if ( !epsg.isEmpty() ) { bool conversionOk; @@ -1331,13 +1331,13 @@ void QgsSLDConfigParser::setCrsForLayer( const QDomElement& layerElem, QgsMapLay if ( conversionOk ) { //set spatial ref sys - QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QString( "EPSG:%1" ).arg( epsgnr ) ); + QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:%1" ).arg( epsgnr ) ); ml->setCrs( srs ); } } else { - QString projString = layerElem.attribute( "proj", "" ); + QString projString = layerElem.attribute( QStringLiteral( "proj" ), QLatin1String( "" ) ); if ( !projString.isEmpty() ) { QgsCoordinateReferenceSystem srs = QgsCoordinateReferenceSystem::fromProj4( projString ); @@ -1347,7 +1347,7 @@ void QgsSLDConfigParser::setCrsForLayer( const QDomElement& layerElem, QgsMapLay // familiar with the code (should also give a more descriptive name to the generated CRS) if ( srs.srsid() == 0 ) { - QString myName = QString( " * %1 (%2)" ) + QString myName = QStringLiteral( " * %1 (%2)" ) .arg( QObject::tr( "Generated CRS", "A CRS automatically generated from layer info get this prefix for description" ), srs.toProj4() ); srs.saveAsUserCrs( myName ); diff --git a/src/server/qgssoaprequesthandler.cpp b/src/server/qgssoaprequesthandler.cpp index 4323387f4cdd..67258f8e8688 100644 --- a/src/server/qgssoaprequesthandler.cpp +++ b/src/server/qgssoaprequesthandler.cpp @@ -51,7 +51,7 @@ void QgsSOAPRequestHandler::parseInput() QgsDebugMsg( "error message: " + errorMsg ); QgsDebugMsg( "the xml string was:" ); QgsDebugMsg( inputString ); - throw QgsMapServiceException( "InvalidXML", "XML error: " + errorMsg ); + throw QgsMapServiceException( QStringLiteral( "InvalidXML" ), "XML error: " + errorMsg ); } // if xml reading was successfull, save the inputXML in a file @@ -59,98 +59,98 @@ void QgsSOAPRequestHandler::parseInput() QTextStream soapStream; //go through soap envelope->soap body, search for either GetCapabilities or GetMap - QDomNodeList envelopeNodeList = inputXML.elementsByTagNameNS( "http://schemas.xmlsoap.org/soap/envelope/", "Envelope" ); + QDomNodeList envelopeNodeList = inputXML.elementsByTagNameNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "Envelope" ) ); if ( envelopeNodeList.size() < 1 ) { QgsDebugMsg( "Envelope element not found" ); - throw QgsMapServiceException( "SOAPError", "Element not found" ); + throw QgsMapServiceException( QStringLiteral( "SOAPError" ), QStringLiteral( "Element not found" ) ); } - QDomNodeList bodyNodeList = envelopeNodeList.item( 0 ).toElement().elementsByTagNameNS( "http://schemas.xmlsoap.org/soap/envelope/", "Body" ); + QDomNodeList bodyNodeList = envelopeNodeList.item( 0 ).toElement().elementsByTagNameNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "Body" ) ); if ( bodyNodeList.size() < 1 ) { QgsDebugMsg( "body node not found" ); - throw QgsMapServiceException( "SOAPError", "Element not found" ); + throw QgsMapServiceException( QStringLiteral( "SOAPError" ), QStringLiteral( "Element not found" ) ); } QDomElement bodyElement = bodyNodeList.item( 0 ).toElement(); QDomElement firstChildElement = bodyElement.firstChild().toElement(); - QString serviceString = firstChildElement.attribute( "service" ); - if ( serviceString == "MS" ) + QString serviceString = firstChildElement.attribute( QStringLiteral( "service" ) ); + if ( serviceString == QLatin1String( "MS" ) ) { QgsDebugMsg( "service = MS " ); - mParameterMap.insert( "SERVICE", "MS" ); - mService = "MS"; + mParameterMap.insert( QStringLiteral( "SERVICE" ), QStringLiteral( "MS" ) ); + mService = QStringLiteral( "MS" ); } - else if ( serviceString == "WMS" ) + else if ( serviceString == QLatin1String( "WMS" ) ) { - mParameterMap.insert( "SERVICE", "WMS" ); - mService = "WMS"; + mParameterMap.insert( QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); + mService = QStringLiteral( "WMS" ); } - else if ( serviceString == "MDS" ) + else if ( serviceString == QLatin1String( "MDS" ) ) { - mParameterMap.insert( "SERVICE", "MDS" ); - mService = "MDS"; + mParameterMap.insert( QStringLiteral( "SERVICE" ), QStringLiteral( "MDS" ) ); + mService = QStringLiteral( "MDS" ); } - else if ( serviceString == "MAS" ) + else if ( serviceString == QLatin1String( "MAS" ) ) { - mParameterMap.insert( "SERVICE", "MAS" ); - mService = "MAS"; + mParameterMap.insert( QStringLiteral( "SERVICE" ), QStringLiteral( "MAS" ) ); + mService = QStringLiteral( "MAS" ); } else { - mParameterMap.insert( "SERVICE", "DISCOVERY" ); - mService = "DISCOVERY"; + mParameterMap.insert( QStringLiteral( "SERVICE" ), QStringLiteral( "DISCOVERY" ) ); + mService = QStringLiteral( "DISCOVERY" ); } //GetCapabilities request //if(firstChildElement.localName().compare("getCapabilities", Qt::CaseInsensitive) == 0) - if ( firstChildElement.localName() == "GetCapabilities" || firstChildElement.localName() == "getCapabilities" ) + if ( firstChildElement.localName() == QLatin1String( "GetCapabilities" ) || firstChildElement.localName() == QLatin1String( "getCapabilities" ) ) { - mParameterMap.insert( "REQUEST", "GetCapabilities" ); + mParameterMap.insert( QStringLiteral( "REQUEST" ), QStringLiteral( "GetCapabilities" ) ); } //GetMap request //else if(firstChildElement.tagName().compare("getMap",Qt::CaseInsensitive) == 0) - else if ( firstChildElement.localName() == "GetMap" || firstChildElement.localName() == "getMap" ) + else if ( firstChildElement.localName() == QLatin1String( "GetMap" ) || firstChildElement.localName() == QLatin1String( "getMap" ) ) { - mParameterMap.insert( "REQUEST", "GetMap" ); + mParameterMap.insert( QStringLiteral( "REQUEST" ), QStringLiteral( "GetMap" ) ); parseGetMapElement( mParameterMap, firstChildElement ); } //GetDiagram request //else if(firstChildElement.tagName().compare("getDiagram", Qt::CaseInsensitive) == 0) - else if ( firstChildElement.localName() == "GetDiagram" ) + else if ( firstChildElement.localName() == QLatin1String( "GetDiagram" ) ) { - mParameterMap.insert( "REQUEST", "GetDiagram" ); + mParameterMap.insert( QStringLiteral( "REQUEST" ), QStringLiteral( "GetDiagram" ) ); parseGetMapElement( mParameterMap, firstChildElement ); //reuse the method for GetMap } //GetFeatureInfo request - else if ( firstChildElement.localName() == "GetFeatureInfo" ) + else if ( firstChildElement.localName() == QLatin1String( "GetFeatureInfo" ) ) { - mParameterMap.insert( "REQUEST", "GetFeatureInfo" ); + mParameterMap.insert( QStringLiteral( "REQUEST" ), QStringLiteral( "GetFeatureInfo" ) ); parseGetFeatureInfoElement( mParameterMap, firstChildElement ); } //set mFormat - QString formatString = mParameterMap.value( "FORMAT" ); + QString formatString = mParameterMap.value( QStringLiteral( "FORMAT" ) ); if ( !formatString.isEmpty() ) { //remove the image/ in front of the format - if ( formatString == "image/jpeg" || formatString == "JPG" || formatString == "jpg" ) + if ( formatString == QLatin1String( "image/jpeg" ) || formatString == QLatin1String( "JPG" ) || formatString == QLatin1String( "jpg" ) ) { - formatString = "JPG"; + formatString = QStringLiteral( "JPG" ); } - else if ( formatString == "image/png" || formatString == "PNG" || formatString == "png" ) + else if ( formatString == QLatin1String( "image/png" ) || formatString == QLatin1String( "PNG" ) || formatString == QLatin1String( "png" ) ) { - formatString = "PNG"; + formatString = QStringLiteral( "PNG" ); } - else if ( formatString == "image/gif" || formatString == "GIF" || formatString == "gif" ) + else if ( formatString == QLatin1String( "image/gif" ) || formatString == QLatin1String( "GIF" ) || formatString == QLatin1String( "gif" ) ) { - formatString = "GIF"; + formatString = QStringLiteral( "GIF" ); } else { - throw QgsMapServiceException( "InvalidFormat", "Invalid format " + formatString + ", only jpg and png are supported" ); + throw QgsMapServiceException( QStringLiteral( "InvalidFormat" ), "Invalid format " + formatString + ", only jpg and png are supported" ); } mFormat = formatString; @@ -159,15 +159,15 @@ void QgsSOAPRequestHandler::parseInput() void QgsSOAPRequestHandler::setGetMapResponse( const QString& service, QImage* img ) { - QgsMapServiceException ex( "set error", "Error, could not set Image" ); - if ( service == "WMS" ) + QgsMapServiceException ex( QStringLiteral( "set error" ), QStringLiteral( "Error, could not set Image" ) ); + if ( service == QLatin1String( "WMS" ) ) { if ( setUrlToFile( img ) != 0 ) { setServiceException( ex ); } } - else if ( service == "MAS" || service == "MS" || service == "MDS" ) + else if ( service == QLatin1String( "MAS" ) || service == QLatin1String( "MS" ) || service == QLatin1String( "MDS" ) ) { if ( setSOAPWithAttachments( img ) != 0 ) @@ -187,39 +187,39 @@ void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc QDomElement DocCapabilitiesElement = doc.firstChildElement(); if ( !DocCapabilitiesElement.isNull() ) { - QDomNodeList capabilitiesNodes = DocCapabilitiesElement.elementsByTagName( "Capability" ); + QDomNodeList capabilitiesNodes = DocCapabilitiesElement.elementsByTagName( QStringLiteral( "Capability" ) ); if ( !capabilitiesNodes.isEmpty() ) { //create response document QDomDocument soapResponseDoc; //Envelope element - QDomElement soapEnvelopeElement = soapResponseDoc.createElement( "soap:Envelope" ); - soapEnvelopeElement.setAttribute( "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/" ); - soapEnvelopeElement.setAttribute( "soap:encoding", "http://schemas.xmlsoap.org/soap/encoding/" ); + QDomElement soapEnvelopeElement = soapResponseDoc.createElement( QStringLiteral( "soap:Envelope" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "xmlns:soap" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "soap:encoding" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/encoding/" ) ); soapResponseDoc.appendChild( soapEnvelopeElement ); //Body element - QDomElement soapBodyElement = soapResponseDoc.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "soap:Body" ); + QDomElement soapBodyElement = soapResponseDoc.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "soap:Body" ) ); soapEnvelopeElement.appendChild( soapBodyElement ); // check if WMS or MS SOAP request - if ( mService == "MS" || mService == "MDS" || mService == "MAS" ) + if ( mService == QLatin1String( "MS" ) || mService == QLatin1String( "MDS" ) || mService == QLatin1String( "MAS" ) ) { //OA_MI_MS_Capabilities element - QDomElement msCapabilitiesElement = soapResponseDoc.createElement( "ms:OA_MI_Service_Capabilities" ); - msCapabilitiesElement.setAttribute( "service", "MS" ); - msCapabilitiesElement.setAttribute( "version", "1.1" ); - msCapabilitiesElement.setAttribute( "xmlns:ms", "http://www.eu-orchestra.org/services/ms" ); - msCapabilitiesElement.setAttribute( "xmlns", "http://www.eu-orchestra.org/services/oas/oa_basic" ); - msCapabilitiesElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); - msCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - msCapabilitiesElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); + QDomElement msCapabilitiesElement = soapResponseDoc.createElement( QStringLiteral( "ms:OA_MI_Service_Capabilities" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "service" ), QStringLiteral( "MS" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.1" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:ms" ), QStringLiteral( "http://www.eu-orchestra.org/services/ms" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.eu-orchestra.org/services/oas/oa_basic" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:gml" ), QStringLiteral( "http://www.opengis.net/gml" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsd" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); soapBodyElement.appendChild( msCapabilitiesElement ); // import the orchestra common capabilities - QFile common( "common.xml" ); + QFile common( QStringLiteral( "common.xml" ) ); if ( !common.open( QIODevice::ReadOnly ) ) { //throw an exception... @@ -243,27 +243,27 @@ void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc msCapabilitiesElement.appendChild( orchestraCommon ); // write specific capabilities - QDomElement msSpecificCapabilitiesElement = soapResponseDoc.createElement( "serviceSpecificCapabilities" ); + QDomElement msSpecificCapabilitiesElement = soapResponseDoc.createElement( QStringLiteral( "serviceSpecificCapabilities" ) ); soapBodyElement.appendChild( msSpecificCapabilitiesElement ); QDomElement capabilitiesElement = capabilitiesNodes.item( 0 ).toElement(); msSpecificCapabilitiesElement.appendChild( capabilitiesElement ); // to do supportedOperations - QDomNodeList requestNodes = capabilitiesElement.elementsByTagName( "Request" ); + QDomNodeList requestNodes = capabilitiesElement.elementsByTagName( QStringLiteral( "Request" ) ); if ( !requestNodes.isEmpty() ) { QDomElement requestElement = requestNodes.item( 0 ).toElement(); QDomNodeList requestChildNodes = requestElement.childNodes(); //append an array element for 'supportedOperations' to the soap document - QDomElement supportedOperationsElement = soapResponseDoc.createElement( "supportedOperations" ); - supportedOperationsElement.setAttribute( "xsi:type", "soapenc:Array" ); - supportedOperationsElement.setAttribute( "soap:arrayType", "xsd:string[" + QString::number( requestChildNodes.size() ) + "]" ); + QDomElement supportedOperationsElement = soapResponseDoc.createElement( QStringLiteral( "supportedOperations" ) ); + supportedOperationsElement.setAttribute( QStringLiteral( "xsi:type" ), QStringLiteral( "soapenc:Array" ) ); + supportedOperationsElement.setAttribute( QStringLiteral( "soap:arrayType" ), "xsd:string[" + QString::number( requestChildNodes.size() ) + "]" ); for ( int i = 0; i < requestChildNodes.size(); ++i ) { - QDomElement itemElement = soapResponseDoc.createElement( "item" ); + QDomElement itemElement = soapResponseDoc.createElement( QStringLiteral( "item" ) ); QDomText itemText = soapResponseDoc.createTextNode( requestChildNodes.item( i ).toElement().tagName() ); itemElement.appendChild( itemText ); supportedOperationsElement.appendChild( itemElement ); @@ -281,19 +281,19 @@ void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc } - else if ( mService == "WMS" ) + else if ( mService == QLatin1String( "WMS" ) ) { //WMS_Capabilities element - QDomElement msCapabilitiesElement = soapResponseDoc.createElement( "wms:Capabilities" ); - msCapabilitiesElement.setAttribute( "service", "WMS" ); - msCapabilitiesElement.setAttribute( "version", "1.3.0" ); - msCapabilitiesElement.setAttribute( "xmlns:wms", "http://www.opengis.net/wms" ); - msCapabilitiesElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); - msCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - msCapabilitiesElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); + QDomElement msCapabilitiesElement = soapResponseDoc.createElement( QStringLiteral( "wms:Capabilities" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "service" ), QStringLiteral( "WMS" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.3.0" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:wms" ), QStringLiteral( "http://www.opengis.net/wms" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:gml" ), QStringLiteral( "http://www.opengis.net/gml" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsd" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); soapBodyElement.appendChild( msCapabilitiesElement ); - QFile wmsService( "wms_metadata.xml" ); + QFile wmsService( QStringLiteral( "wms_metadata.xml" ) ); if ( !wmsService.open( QIODevice::ReadOnly ) ) { //throw an exception... @@ -317,7 +317,7 @@ void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc msCapabilitiesElement.appendChild( service ); } - QDomElement msServiceElement = soapResponseDoc.createElement( "Service" ); + QDomElement msServiceElement = soapResponseDoc.createElement( QStringLiteral( "Service" ) ); msCapabilitiesElement.appendChild( msServiceElement ); QDomElement capabilitiesElement = capabilitiesNodes.item( 0 ).toElement(); @@ -329,18 +329,18 @@ void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc else { //OA_MI_MS_Capabilities element - QDomElement msCapabilitiesElement = soapResponseDoc.createElement( "ms:OA_MI_Service_Capabilities" ); - msCapabilitiesElement.setAttribute( "service", "MS" ); - msCapabilitiesElement.setAttribute( "version", "1.1" ); - msCapabilitiesElement.setAttribute( "xmlns:ms", "http://www.eu-orchestra.org/services/ms" ); - msCapabilitiesElement.setAttribute( "xmlns", "http://www.eu-orchestra.org/services/oas/oa_basic" ); - msCapabilitiesElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); - msCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - msCapabilitiesElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); + QDomElement msCapabilitiesElement = soapResponseDoc.createElement( QStringLiteral( "ms:OA_MI_Service_Capabilities" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "service" ), QStringLiteral( "MS" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.1" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:ms" ), QStringLiteral( "http://www.eu-orchestra.org/services/ms" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.eu-orchestra.org/services/oas/oa_basic" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:gml" ), QStringLiteral( "http://www.opengis.net/gml" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + msCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsd" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); soapBodyElement.appendChild( msCapabilitiesElement ); // import the orchestra common capabilities - QFile common( "common.xml" ); + QFile common( QStringLiteral( "common.xml" ) ); if ( !common.open( QIODevice::ReadOnly ) ) { //throw an exception... @@ -366,7 +366,7 @@ void QgsSOAPRequestHandler::setGetCapabilitiesResponse( const QDomDocument& doc } QByteArray ba = soapResponseDoc.toByteArray(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } } } @@ -377,20 +377,20 @@ void QgsSOAPRequestHandler::setGetFeatureInfoResponse( const QDomDocument& infoD QDomDocument featureInfoResponseDoc; //Envelope - QDomElement soapEnvelopeElement = featureInfoResponseDoc.createElement( "soap:Envelope" ); - soapEnvelopeElement.setAttribute( "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/" ); - soapEnvelopeElement.setAttribute( "soap:encoding", "http://schemas.xmlsoap.org/soap/encoding/" ); + QDomElement soapEnvelopeElement = featureInfoResponseDoc.createElement( QStringLiteral( "soap:Envelope" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "xmlns:soap" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "soap:encoding" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/encoding/" ) ); featureInfoResponseDoc.appendChild( soapEnvelopeElement ); //Body - QDomElement soapBodyElement = featureInfoResponseDoc.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "soap:Body" ); + QDomElement soapBodyElement = featureInfoResponseDoc.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "soap:Body" ) ); soapEnvelopeElement.appendChild( soapBodyElement ); soapBodyElement.appendChild( infoDoc.documentElement() ); //now set message QByteArray ba = featureInfoResponseDoc.toByteArray(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } void QgsSOAPRequestHandler::setXmlResponse( const QDomDocument& infoDoc ) @@ -398,20 +398,20 @@ void QgsSOAPRequestHandler::setXmlResponse( const QDomDocument& infoDoc ) QDomDocument featureInfoResponseDoc; //Envelope - QDomElement soapEnvelopeElement = featureInfoResponseDoc.createElement( "soap:Envelope" ); - soapEnvelopeElement.setAttribute( "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/" ); - soapEnvelopeElement.setAttribute( "soap:encoding", "http://schemas.xmlsoap.org/soap/encoding/" ); + QDomElement soapEnvelopeElement = featureInfoResponseDoc.createElement( QStringLiteral( "soap:Envelope" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "xmlns:soap" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "soap:encoding" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/encoding/" ) ); featureInfoResponseDoc.appendChild( soapEnvelopeElement ); //Body - QDomElement soapBodyElement = featureInfoResponseDoc.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "soap:Body" ); + QDomElement soapBodyElement = featureInfoResponseDoc.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "soap:Body" ) ); soapEnvelopeElement.appendChild( soapBodyElement ); soapBodyElement.appendChild( infoDoc.documentElement() ); //now set message QByteArray ba = featureInfoResponseDoc.toByteArray(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } void QgsSOAPRequestHandler::setXmlResponse( const QDomDocument& infoDoc, const QString& mimeType ) @@ -431,75 +431,75 @@ void QgsSOAPRequestHandler::setServiceException( const QgsMapServiceException& e //create response document QDomDocument soapResponseDoc; //Envelope element - QDomElement soapEnvelopeElement = soapResponseDoc.createElement( "soap:Envelope" ); - soapEnvelopeElement.setAttribute( "xmlns:soap", "http://schemas.xmlsoap.org/soap/envelope/" ); - soapEnvelopeElement.setAttribute( "soap:encoding", "http://schemas.xmlsoap.org/soap/encoding/" ); + QDomElement soapEnvelopeElement = soapResponseDoc.createElement( QStringLiteral( "soap:Envelope" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "xmlns:soap" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ) ); + soapEnvelopeElement.setAttribute( QStringLiteral( "soap:encoding" ), QStringLiteral( "http://schemas.xmlsoap.org/soap/encoding/" ) ); soapResponseDoc.appendChild( soapEnvelopeElement ); //Body element - QDomElement soapBodyElement = soapResponseDoc.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "soap:Body" ); + QDomElement soapBodyElement = soapResponseDoc.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "soap:Body" ) ); soapEnvelopeElement.appendChild( soapBodyElement ); - QDomElement msExceptionsElement = soapResponseDoc.createElement( "Exception" ); - msExceptionsElement.setAttribute( "format", "text/xml" ); + QDomElement msExceptionsElement = soapResponseDoc.createElement( QStringLiteral( "Exception" ) ); + msExceptionsElement.setAttribute( QStringLiteral( "format" ), QStringLiteral( "text/xml" ) ); soapBodyElement.appendChild( msExceptionsElement ); QDomText msExceptionMessage = soapResponseDoc.createTextNode( QString( ex.message() ) ); msExceptionsElement.appendChild( msExceptionMessage ); QByteArray ba = soapResponseDoc.toByteArray(); - setHttpResponse( &ba, "text/xml" ); + setHttpResponse( &ba, QStringLiteral( "text/xml" ) ); } int QgsSOAPRequestHandler::parseGetMapElement( QMap& parameterMap, const QDomElement& getMapElement ) const { - QDomNodeList boundingBoxList = getMapElement.elementsByTagName( "BoundingBox" ); + QDomNodeList boundingBoxList = getMapElement.elementsByTagName( QStringLiteral( "BoundingBox" ) ); if ( !boundingBoxList.isEmpty() ) { parseBoundingBoxElement( parameterMap, boundingBoxList.item( 0 ).toElement() ); } - QDomNodeList CRSList = getMapElement.elementsByTagName( "coordinateReferenceSystem" ); + QDomNodeList CRSList = getMapElement.elementsByTagName( QStringLiteral( "coordinateReferenceSystem" ) ); if ( !CRSList.isEmpty() ) { QString crsText = CRSList.item( 0 ).toElement().text(); QString epsgNumber; - if ( !crsText.startsWith( "EPSG_" ) ) //use underscore in SOAP because ':' is reserved for namespaces + if ( !crsText.startsWith( QLatin1String( "EPSG_" ) ) ) //use underscore in SOAP because ':' is reserved for namespaces { //error } else { - epsgNumber = crsText.replace( 4, 1, ":" );//replace the underscore with a ':' to make it WMS compatible + epsgNumber = crsText.replace( 4, 1, QStringLiteral( ":" ) );//replace the underscore with a ':' to make it WMS compatible } - parameterMap.insert( "CRS", epsgNumber ); + parameterMap.insert( QStringLiteral( "CRS" ), epsgNumber ); } - QDomNodeList GMLList = getMapElement.elementsByTagNameNS( "http://www.eu-orchestra.org/services/ms", "GML" ); + QDomNodeList GMLList = getMapElement.elementsByTagNameNS( QStringLiteral( "http://www.eu-orchestra.org/services/ms" ), QStringLiteral( "GML" ) ); if ( !GMLList.isEmpty() ) { QString gmlText; QTextStream gmlStream( &gmlText ); GMLList.at( 0 ).save( gmlStream, 2 ); - parameterMap.insert( "GML", gmlText ); + parameterMap.insert( QStringLiteral( "GML" ), gmlText ); } //outputAttributes - QDomNodeList imageDocumentAttributesList = getMapElement.elementsByTagName( "Output" ); + QDomNodeList imageDocumentAttributesList = getMapElement.elementsByTagName( QStringLiteral( "Output" ) ); if ( !imageDocumentAttributesList.isEmpty() ) { parseOutputAttributesElement( parameterMap, imageDocumentAttributesList.item( 0 ).toElement() ); } //SLD - QDomNodeList sldList = getMapElement.elementsByTagName( "StyledLayerDescriptor" ); + QDomNodeList sldList = getMapElement.elementsByTagName( QStringLiteral( "StyledLayerDescriptor" ) ); if ( !sldList.isEmpty() ) { QString sldString; QTextStream sldStream( &sldString ); sldList.item( 0 ).save( sldStream, 0 ); //Replace some special characters - sldString.replace( "<", "<" ); - sldString.replace( ">", ">" ); - parameterMap.insert( "SLD", sldString ); + sldString.replace( QLatin1String( "<" ), QLatin1String( "<" ) ); + sldString.replace( QLatin1String( ">" ), QLatin1String( ">" ) ); + parameterMap.insert( QStringLiteral( "SLD" ), sldString ); } return 0; @@ -507,7 +507,7 @@ int QgsSOAPRequestHandler::parseGetMapElement( QMap& parameter int QgsSOAPRequestHandler::parseGetFeatureInfoElement( QMap& parameterMap, const QDomElement& getFeatureInfoElement ) const { - QDomNodeList queryList = getFeatureInfoElement.elementsByTagName( "Query" ); + QDomNodeList queryList = getFeatureInfoElement.elementsByTagName( QStringLiteral( "Query" ) ); if ( queryList.size() < 1 ) { return 1; @@ -515,16 +515,16 @@ int QgsSOAPRequestHandler::parseGetFeatureInfoElement( QMap& p QDomElement queryElem = queryList.at( 0 ).toElement(); //find - QDomNodeList queryLayerList = queryElem.elementsByTagName( "QueryLayer" ); + QDomNodeList queryLayerList = queryElem.elementsByTagName( QStringLiteral( "QueryLayer" ) ); if ( queryLayerList.size() < 1 ) { return 0; //no error, but nothing to do } QString queryLayerString = queryLayerList.at( 0 ).toElement().text(); - parameterMap.insert( "QUERY_LAYERS", queryLayerString ); + parameterMap.insert( QStringLiteral( "QUERY_LAYERS" ), queryLayerString ); //find - QDomNodeList xImageList = queryElem.elementsByTagName( "XImagePoint" ); + QDomNodeList xImageList = queryElem.elementsByTagName( QStringLiteral( "XImagePoint" ) ); if ( xImageList.size() < 1 ) { return 2; //mandatory @@ -535,10 +535,10 @@ int QgsSOAPRequestHandler::parseGetFeatureInfoElement( QMap& p { return 4; } - parameterMap.insert( "I", QString::number( xPoint ) ); + parameterMap.insert( QStringLiteral( "I" ), QString::number( xPoint ) ); //find - QDomNodeList yImageList = queryElem.elementsByTagName( "YImagePoint" ); + QDomNodeList yImageList = queryElem.elementsByTagName( QStringLiteral( "YImagePoint" ) ); if ( yImageList.size() < 1 ) { return 5; //mandatory @@ -548,21 +548,21 @@ int QgsSOAPRequestHandler::parseGetFeatureInfoElement( QMap& p { return 6; } - parameterMap.insert( "J", QString::number( yPoint ) ); + parameterMap.insert( QStringLiteral( "J" ), QString::number( yPoint ) ); //find - QDomNodeList featureCountList = queryElem.elementsByTagName( "FeatureCount" ); + QDomNodeList featureCountList = queryElem.elementsByTagName( QStringLiteral( "FeatureCount" ) ); if ( !featureCountList.isEmpty() ) //optional { int featureCount = featureCountList.at( 0 ).toElement().text().toInt( &conversionSuccess ); if ( conversionSuccess ) { - parameterMap.insert( "FEATURE_COUNT", QString::number( featureCount ) ); + parameterMap.insert( QStringLiteral( "FEATURE_COUNT" ), QString::number( featureCount ) ); } } //RequestCopy - QDomNodeList requestCopyList = getFeatureInfoElement.elementsByTagName( "RequestCopy" ); + QDomNodeList requestCopyList = getFeatureInfoElement.elementsByTagName( QStringLiteral( "RequestCopy" ) ); if ( requestCopyList.size() < 1 ) { return 7; @@ -581,75 +581,75 @@ int QgsSOAPRequestHandler::parseBoundingBoxElement( QMap& para QString minx, miny, maxx, maxy; //leftBound - QDomNodeList leftBoundList = boundingBoxElement.elementsByTagName( "leftBound" ); + QDomNodeList leftBoundList = boundingBoxElement.elementsByTagName( QStringLiteral( "leftBound" ) ); if ( !leftBoundList.isEmpty() ) { minx = leftBoundList.item( 0 ).toElement().text(); } //rightBound - QDomNodeList rightBoundList = boundingBoxElement.elementsByTagName( "rightBound" ); + QDomNodeList rightBoundList = boundingBoxElement.elementsByTagName( QStringLiteral( "rightBound" ) ); if ( !rightBoundList.isEmpty() ) { maxx = rightBoundList.item( 0 ).toElement().text(); } //lowerBound - QDomNodeList lowerBoundList = boundingBoxElement.elementsByTagName( "lowerBound" ); + QDomNodeList lowerBoundList = boundingBoxElement.elementsByTagName( QStringLiteral( "lowerBound" ) ); if ( !lowerBoundList.isEmpty() ) { miny = lowerBoundList.item( 0 ).toElement().text(); } //upperBound - QDomNodeList upperBoundList = boundingBoxElement.elementsByTagName( "upperBound" ); + QDomNodeList upperBoundList = boundingBoxElement.elementsByTagName( QStringLiteral( "upperBound" ) ); if ( !upperBoundList.isEmpty() ) { maxy = upperBoundList.item( 0 ).toElement().text(); } - parameterMap.insert( "BBOX", minx + "," + miny + "," + maxx + "," + maxy ); + parameterMap.insert( QStringLiteral( "BBOX" ), minx + "," + miny + "," + maxx + "," + maxy ); return 0; } int QgsSOAPRequestHandler::parseOutputAttributesElement( QMap& parameterMap, const QDomElement& outputAttributesElement ) const { //height - QDomNodeList heightList = outputAttributesElement.elementsByTagName( "Height" ); + QDomNodeList heightList = outputAttributesElement.elementsByTagName( QStringLiteral( "Height" ) ); if ( !heightList.isEmpty() ) { QString heightString = heightList.item( 0 ).toElement().text(); - parameterMap.insert( "HEIGHT", heightString ); + parameterMap.insert( QStringLiteral( "HEIGHT" ), heightString ); } //width - QDomNodeList widthList = outputAttributesElement.elementsByTagName( "Width" ); + QDomNodeList widthList = outputAttributesElement.elementsByTagName( QStringLiteral( "Width" ) ); if ( !widthList.isEmpty() ) { QString widthString = widthList.item( 0 ).toElement().text(); - parameterMap.insert( "WIDTH", widthString ); + parameterMap.insert( QStringLiteral( "WIDTH" ), widthString ); } //format - QDomNodeList formatList = outputAttributesElement.elementsByTagName( "Format" ); + QDomNodeList formatList = outputAttributesElement.elementsByTagName( QStringLiteral( "Format" ) ); if ( !formatList.isEmpty() ) { QString formatString = formatList.item( 0 ).toElement().text(); - parameterMap.insert( "FORMAT", formatString ); + parameterMap.insert( QStringLiteral( "FORMAT" ), formatString ); } //background transparendy - QDomNodeList bgTransparencyList = outputAttributesElement.elementsByTagName/*NS*/( /*"http://www.eu-orchestra.org/services/ms",*/ "Transparent" ); + QDomNodeList bgTransparencyList = outputAttributesElement.elementsByTagName/*NS*/( /*"http://www.eu-orchestra.org/services/ms",*/ QStringLiteral( "Transparent" ) ); if ( !bgTransparencyList.isEmpty() ) { QString bgTransparencyString = bgTransparencyList.item( 0 ).toElement().text(); - if ( bgTransparencyString.compare( "true", Qt::CaseInsensitive ) == 0 - || bgTransparencyString == "1" ) + if ( bgTransparencyString.compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 + || bgTransparencyString == QLatin1String( "1" ) ) { - parameterMap.insert( "TRANSPARENT", "TRUE" ); + parameterMap.insert( QStringLiteral( "TRANSPARENT" ), QStringLiteral( "TRUE" ) ); } else { - parameterMap.insert( "TRANSPARENT", "FALSE" ); + parameterMap.insert( QStringLiteral( "TRANSPARENT" ), QStringLiteral( "FALSE" ) ); } } return 0; @@ -660,16 +660,16 @@ int QgsSOAPRequestHandler::setSOAPWithAttachments( QImage* img ) QgsDebugMsg( "Entering." ); //create response xml document QDomDocument xmlResponse; //response xml, save this into mimeString - QDomElement envelopeElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Envelope" ); + QDomElement envelopeElement = xmlResponse.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "Envelope" ) ); xmlResponse.appendChild( envelopeElement ); - QDomElement bodyElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Body" ); + QDomElement bodyElement = xmlResponse.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "Body" ) ); envelopeElement.appendChild( bodyElement ); - QDomElement getMapResponseElement = xmlResponse.createElementNS( "http://www.eu-orchestra.org/services/ms", "getMapResponse" ); + QDomElement getMapResponseElement = xmlResponse.createElementNS( QStringLiteral( "http://www.eu-orchestra.org/services/ms" ), QStringLiteral( "getMapResponse" ) ); bodyElement.appendChild( getMapResponseElement ); - QDomElement returnElement = xmlResponse.createElementNS( "http://www.eu-orchestra.org/services/ms", "return" ); - returnElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - returnElement.setAttribute( "xsi:type", "OA_ImageDocument" ); - returnElement.setAttribute( "href", "image@mapservice" ); + QDomElement returnElement = xmlResponse.createElementNS( QStringLiteral( "http://www.eu-orchestra.org/services/ms" ), QStringLiteral( "return" ) ); + returnElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + returnElement.setAttribute( QStringLiteral( "xsi:type" ), QStringLiteral( "OA_ImageDocument" ) ); + returnElement.setAttribute( QStringLiteral( "href" ), QStringLiteral( "image@mapservice" ) ); getMapResponseElement.appendChild( returnElement ); //create image buffer @@ -681,8 +681,8 @@ int QgsSOAPRequestHandler::setSOAPWithAttachments( QImage* img ) QByteArray xmlByteArray = xmlResponse.toString().toLocal8Bit(); // Set headers - setHeader( "MIME-Version", "1.0" ); - setHeader( "Content-Type", "Multipart/Related; boundary=\"MIME_boundary\"; type=\"text/xml\"; start=\"\"" ); + setHeader( QStringLiteral( "MIME-Version" ), QStringLiteral( "1.0" ) ); + setHeader( QStringLiteral( "Content-Type" ), QStringLiteral( "Multipart/Related; boundary=\"MIME_boundary\"; type=\"text/xml\"; start=\"\"" ) ); // Start body appendBody( "--MIME_boundary\r\n" ); appendBody( "Content-Type: text/xml\n" ); @@ -693,11 +693,11 @@ int QgsSOAPRequestHandler::setSOAPWithAttachments( QImage* img ) appendBody( "\n" ); appendBody( "\r\n" ); appendBody( "--MIME_boundary\r\n" ); - if ( mFormat == "JPG" ) + if ( mFormat == QLatin1String( "JPG" ) ) { appendBody( "Content-Type: image/jpg\n" ); } - else if ( mFormat == "PNG" ) + else if ( mFormat == QLatin1String( "PNG" ) ) { appendBody( "Content-Type: image/png\n" ); } @@ -731,7 +731,7 @@ int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) } tmpDir = QDir( QDir::currentPath() + "/tmp" ); #else // Q_OS_WIN - tmpDir = QDir( "/tmp" ); + tmpDir = QDir( QStringLiteral( "/tmp" ) ); #endif QgsDebugMsg( "Path to tmpDir is: " + tmpDir.absolutePath() ); @@ -744,7 +744,7 @@ int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) if ( !QFile::exists( tmpDir.absolutePath() + "/mas_tmp" ) ) { QgsDebugMsg( "Trying to create mas_tmp folder" ); - if ( !tmpDir.mkdir( "mas_tmp" ) ) + if ( !tmpDir.mkdir( QStringLiteral( "mas_tmp" ) ) ) { return 2; } @@ -758,12 +758,12 @@ int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) QgsDebugMsg( "Temp. folder is: " + tmpMasDir.absolutePath() + "/" + folderName ); - if ( mFormat == "JPG" ) + if ( mFormat == QLatin1String( "JPG" ) ) { theFile.setFileName( tmpMasDir.absolutePath() + "/" + folderName + "/map.jpg" ); uri.append( "/mas_tmp/" + folderName + "/map.jpg" ); } - else if ( mFormat == "PNG" ) + else if ( mFormat == QLatin1String( "PNG" ) ) { theFile.setFileName( tmpMasDir.absolutePath() + "/" + folderName + "/map.png" ); uri.append( "/mas_tmp/" + folderName + "/map.png" ); @@ -781,13 +781,13 @@ int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) } QDomDocument xmlResponse; - QDomElement envelopeElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Envelope" ); + QDomElement envelopeElement = xmlResponse.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "Envelope" ) ); xmlResponse.appendChild( envelopeElement ); - QDomElement bodyElement = xmlResponse.createElementNS( "http://schemas.xmlsoap.org/soap/envelope/", "Body" ); + QDomElement bodyElement = xmlResponse.createElementNS( QStringLiteral( "http://schemas.xmlsoap.org/soap/envelope/" ), QStringLiteral( "Body" ) ); envelopeElement.appendChild( bodyElement ); - QDomElement getMapResponseElement = xmlResponse.createElementNS( "http://www.eu-orchestra.org/services/ms", "getMapResponse" ); - QDomElement ahrefElement = xmlResponse.createElement( "a" ); - ahrefElement.setAttribute( "href", uri ); + QDomElement getMapResponseElement = xmlResponse.createElementNS( QStringLiteral( "http://www.eu-orchestra.org/services/ms" ), QStringLiteral( "getMapResponse" ) ); + QDomElement ahrefElement = xmlResponse.createElement( QStringLiteral( "a" ) ); + ahrefElement.setAttribute( QStringLiteral( "href" ), uri ); //QString href(""+uri+""); QDomText uriNode = xmlResponse.createTextNode( uri ); ahrefElement.appendChild( uriNode ); @@ -796,14 +796,14 @@ int QgsSOAPRequestHandler::setUrlToFile( QImage* img ) bodyElement.appendChild( getMapResponseElement ); QByteArray xmlByteArray = xmlResponse.toByteArray(); - setHttpResponse( &xmlByteArray, "text/xml" ); + setHttpResponse( &xmlByteArray, QStringLiteral( "text/xml" ) ); return 0; } int QgsSOAPRequestHandler::findOutHostAddress( QString& address ) const { QDomDocument wmsMetadataDoc; - QFile wmsMetadataFile( "wms_metadata.xml" ); + QFile wmsMetadataFile( QStringLiteral( "wms_metadata.xml" ) ); if ( !wmsMetadataFile.open( QIODevice::ReadOnly ) ) { @@ -813,12 +813,12 @@ int QgsSOAPRequestHandler::findOutHostAddress( QString& address ) const { return 2; } - QDomNodeList onlineResourceList = wmsMetadataDoc.elementsByTagName( "OnlineResource" ); + QDomNodeList onlineResourceList = wmsMetadataDoc.elementsByTagName( QStringLiteral( "OnlineResource" ) ); if ( onlineResourceList.size() < 1 ) { return 3; } - address = onlineResourceList.at( 0 ).toElement().attribute( "href" ); + address = onlineResourceList.at( 0 ).toElement().attribute( QStringLiteral( "href" ) ); QgsDebugMsg( "address found: " + address ); if ( address.isEmpty() ) { diff --git a/src/server/qgswcsprojectparser.cpp b/src/server/qgswcsprojectparser.cpp index 5b0b0a70ecb4..5209c761752c 100644 --- a/src/server/qgswcsprojectparser.cpp +++ b/src/server/qgswcsprojectparser.cpp @@ -50,7 +50,7 @@ QgsWCSProjectParser::~QgsWCSProjectParser() void QgsWCSProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc ) const { - mProjectParser->serviceCapabilities( parentElement, doc, "WCS" ); + mProjectParser->serviceCapabilities( parentElement, doc, QStringLiteral( "WCS" ) ); } QString QgsWCSProjectParser::wcsServiceUrl() const @@ -65,7 +65,7 @@ QString QgsWCSProjectParser::wcsServiceUrl() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement wcsUrlElem = propertiesElem.firstChildElement( "WCSUrl" ); + QDomElement wcsUrlElem = propertiesElem.firstChildElement( QStringLiteral( "WCSUrl" ) ); if ( !wcsUrlElem.isNull() ) { url = wcsUrlElem.text(); @@ -93,8 +93,8 @@ void QgsWCSProjectParser::wcsContentMetadata( QDomElement& parentElement, QDomDo Q_FOREACH ( const QDomElement &elem, projectLayerElements ) { - QString type = elem.attribute( "type" ); - if ( type == "raster" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "raster" ) ) { QgsMapLayer *layer = mProjectParser->createLayerFromElement( elem ); if ( layer && wcsLayersId.contains( layer->id() ) ) @@ -108,19 +108,19 @@ void QgsWCSProjectParser::wcsContentMetadata( QDomElement& parentElement, QDomDo QgsDebugMsg( QString( "add layer %1 to map" ).arg( layer->id() ) ); layerMap.insert( layer->id(), layer ); - QDomElement layerElem = doc.createElement( "CoverageOfferingBrief" ); - QDomElement nameElem = doc.createElement( "name" ); + QDomElement layerElem = doc.createElement( QStringLiteral( "CoverageOfferingBrief" ) ); + QDomElement nameElem = doc.createElement( QStringLiteral( "name" ) ); //We use the layer name even though it might not be unique. //Because the id sometimes contains user/pw information and the name is more descriptive QString typeName = layer->name(); if ( !layer->shortName().isEmpty() ) typeName = layer->shortName(); - typeName = typeName.replace( " ", "_" ); + typeName = typeName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); QDomText nameText = doc.createTextNode( typeName ); nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); - QDomElement labelElem = doc.createElement( "label" ); + QDomElement labelElem = doc.createElement( QStringLiteral( "label" ) ); QString titleName = layer->title(); if ( titleName.isEmpty() ) { @@ -130,11 +130,11 @@ void QgsWCSProjectParser::wcsContentMetadata( QDomElement& parentElement, QDomDo labelElem.appendChild( labelText ); layerElem.appendChild( labelElem ); - QDomElement descriptionElem = doc.createElement( "description" ); + QDomElement descriptionElem = doc.createElement( QStringLiteral( "description" ) ); QString abstractName = layer->abstract(); if ( abstractName.isEmpty() ) { - abstractName = ""; + abstractName = QLatin1String( "" ); } QDomText descriptionText = doc.createTextNode( abstractName ); descriptionElem.appendChild( descriptionText ); @@ -154,13 +154,13 @@ void QgsWCSProjectParser::wcsContentMetadata( QDomElement& parentElement, QDomDo QgsDebugMsg( QString( "Transform error caught: %1. Using original layer extent." ).arg( e.what() ) ); BBox = layer->extent(); } - QDomElement lonLatElem = doc.createElement( "lonLatEnvelope" ); - lonLatElem.setAttribute( "srsName", "urn:ogc:def:crs:OGC:1.3:CRS84" ); - QDomElement lowerPosElem = doc.createElement( "gml:pos" ); + QDomElement lonLatElem = doc.createElement( QStringLiteral( "lonLatEnvelope" ) ); + lonLatElem.setAttribute( QStringLiteral( "srsName" ), QStringLiteral( "urn:ogc:def:crs:OGC:1.3:CRS84" ) ); + QDomElement lowerPosElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText lowerPosText = doc.createTextNode( QString::number( BBox.xMinimum() ) + " " + QString::number( BBox.yMinimum() ) ); lowerPosElem.appendChild( lowerPosText ); lonLatElem.appendChild( lowerPosElem ); - QDomElement upperPosElem = doc.createElement( "gml:pos" ); + QDomElement upperPosElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText upperPosText = doc.createTextNode( QString::number( BBox.xMaximum() ) + " " + QString::number( BBox.yMaximum() ) ); upperPosElem.appendChild( upperPosText ); lonLatElem.appendChild( upperPosElem ); @@ -185,12 +185,12 @@ QStringList QgsWCSProjectParser::wcsLayers() const { return wcsList; } - QDomElement wcsLayersElem = propertiesElem.firstChildElement( "WCSLayers" ); + QDomElement wcsLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WCSLayers" ) ); if ( wcsLayersElem.isNull() ) { return wcsList; } - QDomNodeList valueList = wcsLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wcsLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { wcsList << valueList.at( i ).toElement().text(); @@ -208,9 +208,9 @@ void QgsWCSProjectParser::describeCoverage( const QString& aCoveName, QDomElemen QStringList wcsLayersId = wcsLayers(); QStringList coveNameList; - if ( aCoveName != "" ) + if ( aCoveName != QLatin1String( "" ) ) { - QStringList coveNameSplit = aCoveName.split( "," ); + QStringList coveNameSplit = aCoveName.split( QStringLiteral( "," ) ); Q_FOREACH ( const QString &str, coveNameSplit ) { coveNameList << str; @@ -221,8 +221,8 @@ void QgsWCSProjectParser::describeCoverage( const QString& aCoveName, QDomElemen Q_FOREACH ( const QDomElement &elem, projectLayerElements ) { - QString type = elem.attribute( "type" ); - if ( type == "raster" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "raster" ) ) { QgsRasterLayer *rLayer = qobject_cast( mProjectParser->createLayerFromElement( elem ) ); if ( !rLayer ) @@ -238,25 +238,25 @@ void QgsWCSProjectParser::describeCoverage( const QString& aCoveName, QDomElemen QString coveName = rLayer->name(); if ( !rLayer->shortName().isEmpty() ) coveName = rLayer->shortName(); - coveName = coveName.replace( " ", "_" ); - if ( wcsLayersId.contains( rLayer->id() ) && ( aCoveName == "" || coveNameList.contains( coveName ) ) ) + coveName = coveName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); + if ( wcsLayersId.contains( rLayer->id() ) && ( aCoveName == QLatin1String( "" ) || coveNameList.contains( coveName ) ) ) { QgsDebugMsg( QString( "add layer %1 to map" ).arg( rLayer->id() ) ); layerMap.insert( rLayer->id(), rLayer ); - QDomElement layerElem = doc.createElement( "CoverageOffering" ); - QDomElement nameElem = doc.createElement( "name" ); + QDomElement layerElem = doc.createElement( QStringLiteral( "CoverageOffering" ) ); + QDomElement nameElem = doc.createElement( QStringLiteral( "name" ) ); //We use the layer name even though it might not be unique. //Because the id sometimes contains user/pw information and the name is more descriptive QString typeName = rLayer->name(); if ( !rLayer->shortName().isEmpty() ) typeName = rLayer->shortName(); - typeName = typeName.replace( " ", "_" ); + typeName = typeName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); QDomText nameText = doc.createTextNode( typeName ); nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); - QDomElement labelElem = doc.createElement( "label" ); + QDomElement labelElem = doc.createElement( QStringLiteral( "label" ) ); QString titleName = rLayer->title(); if ( titleName.isEmpty() ) { @@ -266,11 +266,11 @@ void QgsWCSProjectParser::describeCoverage( const QString& aCoveName, QDomElemen labelElem.appendChild( labelText ); layerElem.appendChild( labelElem ); - QDomElement descriptionElem = doc.createElement( "description" ); + QDomElement descriptionElem = doc.createElement( QStringLiteral( "description" ) ); QString abstractName = rLayer->abstract(); if ( abstractName.isEmpty() ) { - abstractName = ""; + abstractName = QLatin1String( "" ); } QDomText descriptionText = doc.createTextNode( abstractName ); descriptionElem.appendChild( descriptionText ); @@ -291,126 +291,126 @@ void QgsWCSProjectParser::describeCoverage( const QString& aCoveName, QDomElemen QgsDebugMsg( QString( "Transform error caught: %1" ).arg( e.what() ) ); } - QDomElement lonLatElem = doc.createElement( "lonLatEnvelope" ); - lonLatElem.setAttribute( "srsName", "urn:ogc:def:crs:OGC:1.3:CRS84" ); - QDomElement lowerPosElem = doc.createElement( "gml:pos" ); + QDomElement lonLatElem = doc.createElement( QStringLiteral( "lonLatEnvelope" ) ); + lonLatElem.setAttribute( QStringLiteral( "srsName" ), QStringLiteral( "urn:ogc:def:crs:OGC:1.3:CRS84" ) ); + QDomElement lowerPosElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText lowerPosText = doc.createTextNode( QString::number( BBox.xMinimum() ) + " " + QString::number( BBox.yMinimum() ) ); lowerPosElem.appendChild( lowerPosText ); lonLatElem.appendChild( lowerPosElem ); - QDomElement upperPosElem = doc.createElement( "gml:pos" ); + QDomElement upperPosElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText upperPosText = doc.createTextNode( QString::number( BBox.xMaximum() ) + " " + QString::number( BBox.yMaximum() ) ); upperPosElem.appendChild( upperPosText ); lonLatElem.appendChild( upperPosElem ); layerElem.appendChild( lonLatElem ); - QDomElement domainSetElem = doc.createElement( "domainSet" ); + QDomElement domainSetElem = doc.createElement( QStringLiteral( "domainSet" ) ); layerElem.appendChild( domainSetElem ); - QDomElement spatialDomainElem = doc.createElement( "spatialDomain" ); + QDomElement spatialDomainElem = doc.createElement( QStringLiteral( "spatialDomain" ) ); domainSetElem.appendChild( spatialDomainElem ); QgsRectangle layerBBox = rLayer->extent(); - QDomElement envelopeElem = doc.createElement( "gml:Envelope" ); - envelopeElem.setAttribute( "srsName", layerCrs.authid() ); - QDomElement lowerCornerElem = doc.createElement( "gml:pos" ); + QDomElement envelopeElem = doc.createElement( QStringLiteral( "gml:Envelope" ) ); + envelopeElem.setAttribute( QStringLiteral( "srsName" ), layerCrs.authid() ); + QDomElement lowerCornerElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText lowerCornerText = doc.createTextNode( QString::number( layerBBox.xMinimum() ) + " " + QString::number( layerBBox.yMinimum() ) ); lowerCornerElem.appendChild( lowerCornerText ); envelopeElem.appendChild( lowerCornerElem ); - QDomElement upperCornerElem = doc.createElement( "gml:pos" ); + QDomElement upperCornerElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText upperCornerText = doc.createTextNode( QString::number( layerBBox.xMaximum() ) + " " + QString::number( layerBBox.yMaximum() ) ); upperCornerElem.appendChild( upperCornerText ); envelopeElem.appendChild( upperCornerElem ); spatialDomainElem.appendChild( envelopeElem ); - QDomElement rectGridElem = doc.createElement( "gml:RectifiedGrid" ); - rectGridElem.setAttribute( "dimension", 2 ); - QDomElement limitsElem = doc.createElement( "gml:limits" ); + QDomElement rectGridElem = doc.createElement( QStringLiteral( "gml:RectifiedGrid" ) ); + rectGridElem.setAttribute( QStringLiteral( "dimension" ), 2 ); + QDomElement limitsElem = doc.createElement( QStringLiteral( "gml:limits" ) ); rectGridElem.appendChild( limitsElem ); - QDomElement gridEnvElem = doc.createElement( "gml:GridEnvelope" ); + QDomElement gridEnvElem = doc.createElement( QStringLiteral( "gml:GridEnvelope" ) ); limitsElem.appendChild( gridEnvElem ); - QDomElement lowElem = doc.createElement( "gml:low" ); - QDomText lowText = doc.createTextNode( "0 0" ); + QDomElement lowElem = doc.createElement( QStringLiteral( "gml:low" ) ); + QDomText lowText = doc.createTextNode( QStringLiteral( "0 0" ) ); lowElem.appendChild( lowText ); gridEnvElem.appendChild( lowElem ); - QDomElement highElem = doc.createElement( "gml:high" ); + QDomElement highElem = doc.createElement( QStringLiteral( "gml:high" ) ); QDomText highText = doc.createTextNode( QString::number( rLayer->width() ) + " " + QString::number( rLayer->height() ) ); highElem.appendChild( highText ); gridEnvElem.appendChild( highElem ); spatialDomainElem.appendChild( rectGridElem ); - QDomElement xAxisElem = doc.createElement( "gml:axisName" ); - QDomText xAxisText = doc.createTextNode( "x" ); + QDomElement xAxisElem = doc.createElement( QStringLiteral( "gml:axisName" ) ); + QDomText xAxisText = doc.createTextNode( QStringLiteral( "x" ) ); xAxisElem.appendChild( xAxisText ); spatialDomainElem.appendChild( xAxisElem ); - QDomElement yAxisElem = doc.createElement( "gml:axisName" ); - QDomText yAxisText = doc.createTextNode( "y" ); + QDomElement yAxisElem = doc.createElement( QStringLiteral( "gml:axisName" ) ); + QDomText yAxisText = doc.createTextNode( QStringLiteral( "y" ) ); yAxisElem.appendChild( yAxisText ); spatialDomainElem.appendChild( yAxisElem ); - QDomElement originElem = doc.createElement( "gml:origin" ); - QDomElement originPosElem = doc.createElement( "gml:pos" ); + QDomElement originElem = doc.createElement( QStringLiteral( "gml:origin" ) ); + QDomElement originPosElem = doc.createElement( QStringLiteral( "gml:pos" ) ); QDomText originPosText = doc.createTextNode( QString::number( layerBBox.xMinimum() ) + " " + QString::number( layerBBox.yMaximum() ) ); originPosElem.appendChild( originPosText ); spatialDomainElem.appendChild( originElem ); - QDomElement xOffsetElem = doc.createElement( "gml:offsetVector" ); + QDomElement xOffsetElem = doc.createElement( QStringLiteral( "gml:offsetVector" ) ); QDomText xOffsetText = doc.createTextNode( QString::number( rLayer->rasterUnitsPerPixelX() ) + " 0" ); xOffsetElem.appendChild( xOffsetText ); spatialDomainElem.appendChild( xOffsetElem ); - QDomElement yOffsetElem = doc.createElement( "gml:offsetVector" ); + QDomElement yOffsetElem = doc.createElement( QStringLiteral( "gml:offsetVector" ) ); QDomText yOffsetText = doc.createTextNode( "0 " + QString::number( rLayer->rasterUnitsPerPixelY() ) ); yOffsetElem.appendChild( yOffsetText ); spatialDomainElem.appendChild( yOffsetElem ); - QDomElement rangeSetElem = doc.createElement( "rangeSet" ); + QDomElement rangeSetElem = doc.createElement( QStringLiteral( "rangeSet" ) ); layerElem.appendChild( rangeSetElem ); - QDomElement RangeSetElem = doc.createElement( "RangeSet" ); + QDomElement RangeSetElem = doc.createElement( QStringLiteral( "RangeSet" ) ); rangeSetElem.appendChild( RangeSetElem ); - QDomElement rsNameElem = doc.createElement( "name" ); - QDomText rsNameText = doc.createTextNode( "Bands" ); + QDomElement rsNameElem = doc.createElement( QStringLiteral( "name" ) ); + QDomText rsNameText = doc.createTextNode( QStringLiteral( "Bands" ) ); rsNameElem.appendChild( rsNameText ); RangeSetElem.appendChild( rsNameElem ); - QDomElement axisDescElem = doc.createElement( "axisDescription" ); + QDomElement axisDescElem = doc.createElement( QStringLiteral( "axisDescription" ) ); RangeSetElem.appendChild( axisDescElem ); - QDomElement AxisDescElem = doc.createElement( "AxisDescription" ); + QDomElement AxisDescElem = doc.createElement( QStringLiteral( "AxisDescription" ) ); axisDescElem.appendChild( AxisDescElem ); - QDomElement adNameElem = doc.createElement( "name" ); - QDomText adNameText = doc.createTextNode( "bands" ); + QDomElement adNameElem = doc.createElement( QStringLiteral( "name" ) ); + QDomText adNameText = doc.createTextNode( QStringLiteral( "bands" ) ); adNameElem.appendChild( adNameText ); AxisDescElem.appendChild( adNameElem ); - QDomElement adValuesElem = doc.createElement( "values" ); + QDomElement adValuesElem = doc.createElement( QStringLiteral( "values" ) ); for ( int idx = 0; idx < rLayer->bandCount(); ++idx ) { - QDomElement adValueElem = doc.createElement( "value" ); + QDomElement adValueElem = doc.createElement( QStringLiteral( "value" ) ); QDomText adValueText = doc.createTextNode( QString::number( idx + 1 ) ); adValueElem.appendChild( adValueText ); adValuesElem.appendChild( adValueElem ); } AxisDescElem.appendChild( adValuesElem ); - QDomElement sCRSElem = doc.createElement( "supportedCRSs" ); - QDomElement rCRSElem = doc.createElement( "requestResponseCRSs" ); + QDomElement sCRSElem = doc.createElement( QStringLiteral( "supportedCRSs" ) ); + QDomElement rCRSElem = doc.createElement( QStringLiteral( "requestResponseCRSs" ) ); QDomText rCRSText = doc.createTextNode( layerCrs.authid() ); rCRSElem.appendChild( rCRSText ); sCRSElem.appendChild( rCRSElem ); - QDomElement nCRSElem = doc.createElement( "nativeCRSs" ); + QDomElement nCRSElem = doc.createElement( QStringLiteral( "nativeCRSs" ) ); QDomText nCRSText = doc.createTextNode( layerCrs.authid() ); nCRSElem.appendChild( nCRSText ); sCRSElem.appendChild( nCRSElem ); layerElem.appendChild( sCRSElem ); - QDomElement sFormatsElem = doc.createElement( "supportedFormats" ); - sFormatsElem.setAttribute( "nativeFormat", "raw binary" ); - QDomElement formatsElem = doc.createElement( "formats" ); - QDomText formatsText = doc.createTextNode( "GeoTIFF" ); + QDomElement sFormatsElem = doc.createElement( QStringLiteral( "supportedFormats" ) ); + sFormatsElem.setAttribute( QStringLiteral( "nativeFormat" ), QStringLiteral( "raw binary" ) ); + QDomElement formatsElem = doc.createElement( QStringLiteral( "formats" ) ); + QDomText formatsText = doc.createTextNode( QStringLiteral( "GeoTIFF" ) ); formatsElem.appendChild( formatsText ); sFormatsElem.appendChild( formatsElem ); layerElem.appendChild( sFormatsElem ); @@ -435,8 +435,8 @@ QList QgsWCSProjectParser::mapLayerFromCoverage( const QString& cN Q_FOREACH ( const QDomElement &elem, projectLayerElements ) { - QString type = elem.attribute( "type" ); - if ( type == "raster" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "raster" ) ) { QgsMapLayer *mLayer = mProjectParser->createLayerFromElement( elem, useCache ); QgsRasterLayer* layer = qobject_cast( mLayer ); @@ -446,7 +446,7 @@ QList QgsWCSProjectParser::mapLayerFromCoverage( const QString& cN QString coveName = layer->name(); if ( !layer->shortName().isEmpty() ) coveName = layer->shortName(); - coveName = coveName.replace( " ", "_" ); + coveName = coveName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); if ( cName == coveName ) { layerList.push_back( mLayer ); diff --git a/src/server/qgswcsserver.cpp b/src/server/qgswcsserver.cpp index 2b02215da147..02a1fc84b7af 100644 --- a/src/server/qgswcsserver.cpp +++ b/src/server/qgswcsserver.cpp @@ -34,9 +34,9 @@ #include #endif -static const QString WCS_NAMESPACE = "http://www.opengis.net/wcs"; -static const QString GML_NAMESPACE = "http://www.opengis.net/gml"; -static const QString OGC_NAMESPACE = "http://www.opengis.net/ogc"; +static const QString WCS_NAMESPACE = QStringLiteral( "http://www.opengis.net/wcs" ); +static const QString GML_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml" ); +static const QString OGC_NAMESPACE = QStringLiteral( "http://www.opengis.net/ogc" ); QgsWCSServer::QgsWCSServer( const QString& configFilePath @@ -81,16 +81,16 @@ QgsWCSServer::~QgsWCSServer() void QgsWCSServer::executeRequest() { //request type - QString request = mParameters.value( "REQUEST" ); + QString request = mParameters.value( QStringLiteral( "REQUEST" ) ); if ( request.isEmpty() ) { //do some error handling QgsDebugMsg( "unable to find 'REQUEST' parameter, exiting..." ); - mRequestHandler->setServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) ); + mRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "OperationNotSupported" ), QStringLiteral( "Please check the value of the REQUEST parameter" ) ) ); return; } - if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 ) + if ( request.compare( QLatin1String( "GetCapabilities" ), Qt::CaseInsensitive ) == 0 ) { QDomDocument capabilitiesDocument; try @@ -106,7 +106,7 @@ void QgsWCSServer::executeRequest() mRequestHandler->setGetCapabilitiesResponse( capabilitiesDocument ); return; } - else if ( request.compare( "DescribeCoverage", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "DescribeCoverage" ), Qt::CaseInsensitive ) == 0 ) { QDomDocument describeDocument; try @@ -122,7 +122,7 @@ void QgsWCSServer::executeRequest() mRequestHandler->setGetCapabilitiesResponse( describeDocument ); return; } - else if ( request.compare( "GetCoverage", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetCoverage" ), Qt::CaseInsensitive ) == 0 ) { QByteArray* coverageOutput; try @@ -148,14 +148,14 @@ QDomDocument QgsWCSServer::getCapabilities() QDomDocument doc; //wcs:WCS_Capabilities element - QDomElement wcsCapabilitiesElement = doc.createElement( "WCS_Capabilities"/*wcs:WCS_Capabilities*/ ); - wcsCapabilitiesElement.setAttribute( "xmlns", WCS_NAMESPACE ); - wcsCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - wcsCapabilitiesElement.setAttribute( "xsi:schemaLocation", WCS_NAMESPACE + " http://schemas.opengis.net/wcs/1.0.0/wcsCapabilities.xsd" ); - wcsCapabilitiesElement.setAttribute( "xmlns:gml", GML_NAMESPACE ); - wcsCapabilitiesElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - wcsCapabilitiesElement.setAttribute( "version", "1.0.0" ); - wcsCapabilitiesElement.setAttribute( "updateSequence", "0" ); + QDomElement wcsCapabilitiesElement = doc.createElement( QStringLiteral( "WCS_Capabilities" )/*wcs:WCS_Capabilities*/ ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), WCS_NAMESPACE ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WCS_NAMESPACE + " http://schemas.opengis.net/wcs/1.0.0/wcsCapabilities.xsd" ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) ); + wcsCapabilitiesElement.setAttribute( QStringLiteral( "updateSequence" ), QStringLiteral( "0" ) ); doc.appendChild( wcsCapabilitiesElement ); if ( mConfigParser ) @@ -166,20 +166,20 @@ QDomDocument QgsWCSServer::getCapabilities() //INSERT Service //wcs:Capability element - QDomElement capabilityElement = doc.createElement( "Capability"/*wcs:Capability*/ ); + QDomElement capabilityElement = doc.createElement( QStringLiteral( "Capability" )/*wcs:Capability*/ ); wcsCapabilitiesElement.appendChild( capabilityElement ); //wcs:Request element - QDomElement requestElement = doc.createElement( "Request"/*wcs:Request*/ ); + QDomElement requestElement = doc.createElement( QStringLiteral( "Request" )/*wcs:Request*/ ); capabilityElement.appendChild( requestElement ); //wcs:GetCapabilities - QDomElement getCapabilitiesElement = doc.createElement( "GetCapabilities"/*wcs:GetCapabilities*/ ); + QDomElement getCapabilitiesElement = doc.createElement( QStringLiteral( "GetCapabilities" )/*wcs:GetCapabilities*/ ); requestElement.appendChild( getCapabilitiesElement ); - QDomElement dcpTypeElement = doc.createElement( "DCPType"/*wcs:DCPType*/ ); + QDomElement dcpTypeElement = doc.createElement( QStringLiteral( "DCPType" )/*wcs:DCPType*/ ); getCapabilitiesElement.appendChild( dcpTypeElement ); - QDomElement httpElement = doc.createElement( "HTTP"/*wcs:HTTP*/ ); + QDomElement httpElement = doc.createElement( QStringLiteral( "HTTP" )/*wcs:HTTP*/ ); dcpTypeElement.appendChild( httpElement ); //Prepare url @@ -197,29 +197,29 @@ QDomDocument QgsWCSServer::getCapabilities() hrefString = serviceUrl(); } - QDomElement getElement = doc.createElement( "Get"/*wcs:Get*/ ); + QDomElement getElement = doc.createElement( QStringLiteral( "Get" )/*wcs:Get*/ ); httpElement.appendChild( getElement ); - QDomElement onlineResourceElement = doc.createElement( "OnlineResource"/*wcs:OnlineResource*/ ); - onlineResourceElement.setAttribute( "xlink:type", "simple" ); - onlineResourceElement.setAttribute( "xlink:href", hrefString ); + QDomElement onlineResourceElement = doc.createElement( QStringLiteral( "OnlineResource" )/*wcs:OnlineResource*/ ); + onlineResourceElement.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + onlineResourceElement.setAttribute( QStringLiteral( "xlink:href" ), hrefString ); getElement.appendChild( onlineResourceElement ); QDomElement getCapabilitiesDhcTypePostElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' - getCapabilitiesDhcTypePostElement.firstChild().firstChild().toElement().setTagName( "Post" ); + getCapabilitiesDhcTypePostElement.firstChild().firstChild().toElement().setTagName( QStringLiteral( "Post" ) ); getCapabilitiesElement.appendChild( getCapabilitiesDhcTypePostElement ); QDomElement describeCoverageElement = getCapabilitiesElement.cloneNode().toElement();//this is the same as 'GetCapabilities' - describeCoverageElement.setTagName( "DescribeCoverage" ); + describeCoverageElement.setTagName( QStringLiteral( "DescribeCoverage" ) ); requestElement.appendChild( describeCoverageElement ); QDomElement getCoverageElement = getCapabilitiesElement.cloneNode().toElement();//this is the same as 'GetCapabilities' - getCoverageElement.setTagName( "GetCoverage" ); + getCoverageElement.setTagName( QStringLiteral( "GetCoverage" ) ); requestElement.appendChild( getCoverageElement ); /* * Adding layer list in ContentMetadata */ - QDomElement contentMetadataElement = doc.createElement( "ContentMetadata"/*wcs:ContentMetadata*/ ); + QDomElement contentMetadataElement = doc.createElement( QStringLiteral( "ContentMetadata" )/*wcs:ContentMetadata*/ ); wcsCapabilitiesElement.appendChild( contentMetadataElement ); /* * Adding layer list in contentMetadataElement @@ -238,27 +238,27 @@ QDomDocument QgsWCSServer::describeCoverage() QDomDocument doc; //wcs:WCS_Capabilities element - QDomElement coveDescElement = doc.createElement( "CoverageDescription"/*wcs:CoverageDescription*/ ); - coveDescElement.setAttribute( "xmlns", WCS_NAMESPACE ); - coveDescElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - coveDescElement.setAttribute( "xsi:schemaLocation", WCS_NAMESPACE + " http://schemas.opengis.net/wcs/1.0.0/describeCoverage.xsd" ); - coveDescElement.setAttribute( "xmlns:gml", GML_NAMESPACE ); - coveDescElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - coveDescElement.setAttribute( "version", "1.0.0" ); - coveDescElement.setAttribute( "updateSequence", "0" ); + QDomElement coveDescElement = doc.createElement( QStringLiteral( "CoverageDescription" )/*wcs:CoverageDescription*/ ); + coveDescElement.setAttribute( QStringLiteral( "xmlns" ), WCS_NAMESPACE ); + coveDescElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + coveDescElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WCS_NAMESPACE + " http://schemas.opengis.net/wcs/1.0.0/describeCoverage.xsd" ); + coveDescElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE ); + coveDescElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + coveDescElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) ); + coveDescElement.setAttribute( QStringLiteral( "updateSequence" ), QStringLiteral( "0" ) ); doc.appendChild( coveDescElement ); //defining coverage name - QString coveName = ""; + QString coveName = QLatin1String( "" ); //read COVERAGE - QMap::const_iterator cove_name_it = mParameters.constFind( "COVERAGE" ); + QMap::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "COVERAGE" ) ); if ( cove_name_it != mParameters.constEnd() ) { coveName = cove_name_it.value(); } - if ( coveName == "" ) + if ( coveName == QLatin1String( "" ) ) { - QMap::const_iterator cove_name_it = mParameters.constFind( "IDENTIFIER" ); + QMap::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "IDENTIFIER" ) ); if ( cove_name_it != mParameters.constEnd() ) { coveName = cove_name_it.value(); @@ -277,31 +277,31 @@ QByteArray* QgsWCSServer::getCoverage() QStringList mErrors = QStringList(); //defining coverage name - QString coveName = ""; + QString coveName = QLatin1String( "" ); //read COVERAGE - QMap::const_iterator cove_name_it = mParameters.constFind( "COVERAGE" ); + QMap::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "COVERAGE" ) ); if ( cove_name_it != mParameters.constEnd() ) { coveName = cove_name_it.value(); } - if ( coveName == "" ) + if ( coveName == QLatin1String( "" ) ) { - QMap::const_iterator cove_name_it = mParameters.constFind( "IDENTIFIER" ); + QMap::const_iterator cove_name_it = mParameters.constFind( QStringLiteral( "IDENTIFIER" ) ); if ( cove_name_it != mParameters.constEnd() ) { coveName = cove_name_it.value(); } } - if ( coveName == "" ) + if ( coveName == QLatin1String( "" ) ) { - mErrors << QString( "COVERAGE is mandatory" ); + mErrors << QStringLiteral( "COVERAGE is mandatory" ); } layerList = mConfigParser->mapLayerFromCoverage( coveName ); if ( layerList.size() < 1 ) { - mErrors << QString( "The layer for the COVERAGE '%1' is not found" ).arg( coveName ); + mErrors << QStringLiteral( "The layer for the COVERAGE '%1' is not found" ).arg( coveName ); } bool conversionSuccess; @@ -311,10 +311,10 @@ QByteArray* QgsWCSServer::getCoverage() // WIDTh and HEIGHT int width = 0, height = 0; // CRS - QString crs = ""; + QString crs = QLatin1String( "" ); // read BBOX - QMap::const_iterator bbIt = mParameters.constFind( "BBOX" ); + QMap::const_iterator bbIt = mParameters.constFind( QStringLiteral( "BBOX" ) ); if ( bbIt == mParameters.constEnd() ) { minx = 0; @@ -326,26 +326,26 @@ QByteArray* QgsWCSServer::getCoverage() { bboxOk = true; QString bbString = bbIt.value(); - minx = bbString.section( ",", 0, 0 ).toDouble( &conversionSuccess ); + minx = bbString.section( QStringLiteral( "," ), 0, 0 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} - miny = bbString.section( ",", 1, 1 ).toDouble( &conversionSuccess ); + miny = bbString.section( QStringLiteral( "," ), 1, 1 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} - maxx = bbString.section( ",", 2, 2 ).toDouble( &conversionSuccess ); + maxx = bbString.section( QStringLiteral( "," ), 2, 2 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} - maxy = bbString.section( ",", 3, 3 ).toDouble( &conversionSuccess ); + maxy = bbString.section( QStringLiteral( "," ), 3, 3 ).toDouble( &conversionSuccess ); if ( !conversionSuccess ) {bboxOk = false;} } if ( !bboxOk ) { - mErrors << QString( "The BBOX is mandatory and has to be xx.xxx,yy.yyy,xx.xxx,yy.yyy" ); + mErrors << QStringLiteral( "The BBOX is mandatory and has to be xx.xxx,yy.yyy,xx.xxx,yy.yyy" ); } // read WIDTH - width = mParameters.value( "WIDTH", "0" ).toInt( &conversionSuccess ); + width = mParameters.value( QStringLiteral( "WIDTH" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) width = 0; // read HEIGHT - height = mParameters.value( "HEIGHT", "0" ).toInt( &conversionSuccess ); + height = mParameters.value( QStringLiteral( "HEIGHT" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { height = 0; @@ -353,25 +353,25 @@ QByteArray* QgsWCSServer::getCoverage() if ( width < 0 || height < 0 ) { - mErrors << QString( "The WIDTH and HEIGHT are mandatory and have to be integer" ); + mErrors << QStringLiteral( "The WIDTH and HEIGHT are mandatory and have to be integer" ); } - crs = mParameters.value( "CRS", "" ); - if ( crs == "" ) + crs = mParameters.value( QStringLiteral( "CRS" ), QLatin1String( "" ) ); + if ( crs == QLatin1String( "" ) ) { - mErrors << QString( "The CRS is mandatory" ); + mErrors << QStringLiteral( "The CRS is mandatory" ); } if ( mErrors.count() != 0 ) { - throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) ); } QgsCoordinateReferenceSystem requestCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs ); if ( !requestCRS.isValid() ) { - mErrors << QString( "Could not create request CRS" ); - throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) ); + mErrors << QStringLiteral( "Could not create request CRS" ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) ); } QgsRectangle rect( minx, miny, maxx, maxy ); @@ -383,14 +383,14 @@ QByteArray* QgsWCSServer::getCoverage() #ifdef HAVE_SERVER_PYTHON_PLUGINS if ( !mAccessControl->layerReadPermission( rLayer ) ) { - throw QgsMapServiceException( "Security", "You are not allowed to access to this coverage" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "You are not allowed to access to this coverage" ) ); } #endif // RESPONSE_CRS QgsCoordinateReferenceSystem responseCRS = rLayer->crs(); - crs = mParameters.value( "RESPONSE_CRS", "" ); - if ( crs != "" ) + crs = mParameters.value( QStringLiteral( "RESPONSE_CRS" ), QLatin1String( "" ) ); + if ( crs != QLatin1String( "" ) ) { responseCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs ); if ( !responseCRS.isValid() ) @@ -414,8 +414,8 @@ QByteArray* QgsWCSServer::getCoverage() QgsRasterPipe* pipe = new QgsRasterPipe(); if ( !pipe->set( rLayer->dataProvider()->clone() ) ) { - mErrors << QString( "Cannot set pipe provider" ); - throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) ); + mErrors << QStringLiteral( "Cannot set pipe provider" ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) ); } // add projector if necessary @@ -425,16 +425,16 @@ QByteArray* QgsWCSServer::getCoverage() projector->setCrs( rLayer->crs(), responseCRS ); if ( !pipe->insert( 2, projector ) ) { - mErrors << QString( "Cannot set pipe projector" ); - throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) ); + mErrors << QStringLiteral( "Cannot set pipe projector" ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) ); } } QgsRasterFileWriter::WriterError err = fileWriter.writeRaster( pipe, width, height, rect, responseCRS ); if ( err != QgsRasterFileWriter::NoError ) { - mErrors << QString( "Cannot write raster error code: %1" ).arg( err ); - throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) ); + mErrors << QStringLiteral( "Cannot write raster error code: %1" ).arg( err ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), mErrors.join( QStringLiteral( ". " ) ) ); } delete pipe; QByteArray* ba = nullptr; @@ -466,32 +466,32 @@ QString QgsWCSServer::serviceUrl() const } } - if ( QString( getenv( "HTTPS" ) ).compare( "on", Qt::CaseInsensitive ) == 0 ) + if ( QString( getenv( "HTTPS" ) ).compare( QLatin1String( "on" ), Qt::CaseInsensitive ) == 0 ) { - mapUrl.setScheme( "https" ); + mapUrl.setScheme( QStringLiteral( "https" ) ); } else { - mapUrl.setScheme( "http" ); + mapUrl.setScheme( QStringLiteral( "http" ) ); } QList > queryItems = mapUrl.queryItems(); QList >::const_iterator queryIt = queryItems.constBegin(); for ( ; queryIt != queryItems.constEnd(); ++queryIt ) { - if ( queryIt->first.compare( "REQUEST", Qt::CaseInsensitive ) == 0 ) + if ( queryIt->first.compare( QLatin1String( "REQUEST" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "VERSION", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "VERSION" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "SERVICE", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "SERVICE" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "_DC", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "_DC" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } diff --git a/src/server/qgswfsprojectparser.cpp b/src/server/qgswfsprojectparser.cpp index 4821cf142d37..bae0849e71a5 100644 --- a/src/server/qgswfsprojectparser.cpp +++ b/src/server/qgswfsprojectparser.cpp @@ -45,7 +45,7 @@ QgsWfsProjectParser::~QgsWfsProjectParser() void QgsWfsProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc ) const { - mProjectParser->serviceCapabilities( parentElement, doc, "WFS" ); + mProjectParser->serviceCapabilities( parentElement, doc, QStringLiteral( "WFS" ) ); } QString QgsWfsProjectParser::serviceUrl() const @@ -75,8 +75,8 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum Q_FOREACH ( const QDomElement &elem, projectLayerElements ) { - QString type = elem.attribute( "type" ); - if ( type == "vector" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "vector" ) ) { QString layerId = mProjectParser->layerId( elem ); if ( !wfsLayersId.contains( layerId ) ) @@ -97,19 +97,19 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum QgsDebugMsg( QString( "add layer %1 to map" ).arg( layer->id() ) ); layerMap.insert( layer->id(), layer ); - QDomElement layerElem = doc.createElement( "FeatureType" ); - QDomElement nameElem = doc.createElement( "Name" ); + QDomElement layerElem = doc.createElement( QStringLiteral( "FeatureType" ) ); + QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) ); //We use the layer name even though it might not be unique. //Because the id sometimes contains user/pw information and the name is more descriptive QString typeName = layer->name(); if ( !layer->shortName().isEmpty() ) typeName = layer->shortName(); - typeName = typeName.replace( " ", "_" ); + typeName = typeName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); QDomText nameText = doc.createTextNode( typeName ); nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); - QDomElement titleElem = doc.createElement( "Title" ); + QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) ); QString titleName = layer->title(); if ( titleName.isEmpty() ) { @@ -119,11 +119,11 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum titleElem.appendChild( titleText ); layerElem.appendChild( titleElem ); - QDomElement abstractElem = doc.createElement( "Abstract" ); + QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QString abstractName = layer->abstract(); if ( abstractName.isEmpty() ) { - abstractName = ""; + abstractName = QLatin1String( "" ); } QDomText abstractText = doc.createTextNode( abstractName ); abstractElem.appendChild( abstractText ); @@ -132,7 +132,7 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum //keyword list if ( !layer->keywordList().isEmpty() ) { - QDomElement keywordsElem = doc.createElement( "Keywords" ); + QDomElement keywordsElem = doc.createElement( QStringLiteral( "Keywords" ) ); QDomText keywordsText = doc.createTextNode( layer->keywordList() ); keywordsElem.appendChild( keywordsText ); layerElem.appendChild( keywordsElem ); @@ -140,15 +140,15 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum //appendExGeographicBoundingBox( layerElem, doc, layer->extent(), layer->crs() ); - QDomElement srsElem = doc.createElement( "SRS" ); + QDomElement srsElem = doc.createElement( QStringLiteral( "SRS" ) ); QDomText srsText = doc.createTextNode( layer->crs().authid() ); srsElem.appendChild( srsText ); layerElem.appendChild( srsElem ); //wfs:Operations element - QDomElement operationsElement = doc.createElement( "Operations"/*wfs:Operations*/ ); + QDomElement operationsElement = doc.createElement( QStringLiteral( "Operations" )/*wfs:Operations*/ ); //wfs:Query element - QDomElement queryElement = doc.createElement( "Query"/*wfs:Query*/ ); + QDomElement queryElement = doc.createElement( QStringLiteral( "Query" )/*wfs:Query*/ ); operationsElement.appendChild( queryElement ); QgsVectorLayer* vlayer = qobject_cast( layer ); @@ -156,7 +156,7 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum if (( provider->capabilities() & QgsVectorDataProvider::AddFeatures ) && wfstInsertLayersId.contains( layer->id() ) ) { //wfs:Insert element - QDomElement insertElement = doc.createElement( "Insert"/*wfs:Insert*/ ); + QDomElement insertElement = doc.createElement( QStringLiteral( "Insert" )/*wfs:Insert*/ ); operationsElement.appendChild( insertElement ); } if (( provider->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) && @@ -164,41 +164,41 @@ void QgsWfsProjectParser::featureTypeList( QDomElement& parentElement, QDomDocum wfstUpdateLayersId.contains( layer->id() ) ) { //wfs:Update element - QDomElement updateElement = doc.createElement( "Update"/*wfs:Update*/ ); + QDomElement updateElement = doc.createElement( QStringLiteral( "Update" )/*wfs:Update*/ ); operationsElement.appendChild( updateElement ); } if (( provider->capabilities() & QgsVectorDataProvider::DeleteFeatures ) && wfstDeleteLayersId.contains( layer->id() ) ) { //wfs:Delete element - QDomElement deleteElement = doc.createElement( "Delete"/*wfs:Delete*/ ); + QDomElement deleteElement = doc.createElement( QStringLiteral( "Delete" )/*wfs:Delete*/ ); operationsElement.appendChild( deleteElement ); } layerElem.appendChild( operationsElement ); QgsRectangle layerExtent = layer->extent(); - QDomElement bBoxElement = doc.createElement( "LatLongBoundingBox" ); - bBoxElement.setAttribute( "minx", QString::number( layerExtent.xMinimum() ) ); - bBoxElement.setAttribute( "miny", QString::number( layerExtent.yMinimum() ) ); - bBoxElement.setAttribute( "maxx", QString::number( layerExtent.xMaximum() ) ); - bBoxElement.setAttribute( "maxy", QString::number( layerExtent.yMaximum() ) ); + QDomElement bBoxElement = doc.createElement( QStringLiteral( "LatLongBoundingBox" ) ); + bBoxElement.setAttribute( QStringLiteral( "minx" ), QString::number( layerExtent.xMinimum() ) ); + bBoxElement.setAttribute( QStringLiteral( "miny" ), QString::number( layerExtent.yMinimum() ) ); + bBoxElement.setAttribute( QStringLiteral( "maxx" ), QString::number( layerExtent.xMaximum() ) ); + bBoxElement.setAttribute( QStringLiteral( "maxy" ), QString::number( layerExtent.yMaximum() ) ); layerElem.appendChild( bBoxElement ); // layer metadata URL QString metadataUrl = layer->metadataUrl(); if ( !metadataUrl.isEmpty() ) { - QDomElement metaUrlElem = doc.createElement( "MetadataURL" ); + QDomElement metaUrlElem = doc.createElement( QStringLiteral( "MetadataURL" ) ); QString metadataUrlType = layer->metadataUrlType(); - metaUrlElem.setAttribute( "type", metadataUrlType ); + metaUrlElem.setAttribute( QStringLiteral( "type" ), metadataUrlType ); QString metadataUrlFormat = layer->metadataUrlFormat(); - if ( metadataUrlFormat == "text/xml" ) + if ( metadataUrlFormat == QLatin1String( "text/xml" ) ) { - metaUrlElem.setAttribute( "format", "XML" ); + metaUrlElem.setAttribute( QStringLiteral( "format" ), QStringLiteral( "XML" ) ); } else { - metaUrlElem.setAttribute( "format", "TXT" ); + metaUrlElem.setAttribute( QStringLiteral( "format" ), QStringLiteral( "TXT" ) ); } QDomText metaUrlText = doc.createTextNode( metadataUrl ); metaUrlElem.appendChild( metaUrlText ); @@ -225,17 +225,17 @@ QSet QgsWfsProjectParser::wfstUpdateLayers() const { return wfsList; } - QDomElement wfstLayersElem = propertiesElem.firstChildElement( "WFSTLayers" ); + QDomElement wfstLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WFSTLayers" ) ); if ( wfstLayersElem.isNull() ) { return wfsList; } - QDomElement wfstUpdateLayersElem = wfstLayersElem.firstChildElement( "Update" ); + QDomElement wfstUpdateLayersElem = wfstLayersElem.firstChildElement( QStringLiteral( "Update" ) ); if ( wfstUpdateLayersElem.isNull() ) { return wfsList; } - QDomNodeList valueList = wfstUpdateLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wfstUpdateLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { QString id = valueList.at( i ).toElement().text(); @@ -261,17 +261,17 @@ QSet QgsWfsProjectParser::wfstInsertLayers() const { return wfsList; } - QDomElement wfstLayersElem = propertiesElem.firstChildElement( "WFSTLayers" ); + QDomElement wfstLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WFSTLayers" ) ); if ( wfstLayersElem.isNull() ) { return wfsList; } - QDomElement wfstInsertLayersElem = wfstLayersElem.firstChildElement( "Insert" ); + QDomElement wfstInsertLayersElem = wfstLayersElem.firstChildElement( QStringLiteral( "Insert" ) ); if ( wfstInsertLayersElem.isNull() ) { return wfsList; } - QDomNodeList valueList = wfstInsertLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wfstInsertLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { QString id = valueList.at( i ).toElement().text(); @@ -297,17 +297,17 @@ QSet QgsWfsProjectParser::wfstDeleteLayers() const { return wfsList; } - QDomElement wfstLayersElem = propertiesElem.firstChildElement( "WFSTLayers" ); + QDomElement wfstLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WFSTLayers" ) ); if ( wfstLayersElem.isNull() ) { return wfsList; } - QDomElement wfstDeleteLayersElem = wfstLayersElem.firstChildElement( "Delete" ); + QDomElement wfstDeleteLayersElem = wfstLayersElem.firstChildElement( QStringLiteral( "Delete" ) ); if ( wfstDeleteLayersElem.isNull() ) { return wfsList; } - QDomNodeList valueList = wfstDeleteLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = wfstDeleteLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { QString id = valueList.at( i ).toElement().text(); @@ -329,13 +329,13 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle QStringList wfsLayersId = mProjectParser->wfsLayers(); QStringList typeNameList; - if ( aTypeName != "" ) + if ( aTypeName != QLatin1String( "" ) ) { - QStringList typeNameSplit = aTypeName.split( "," ); + QStringList typeNameSplit = aTypeName.split( QStringLiteral( "," ) ); Q_FOREACH ( const QString &str, typeNameSplit ) { - if ( str.contains( ":" ) ) - typeNameList << str.section( ":", 1, 1 ); + if ( str.contains( QLatin1String( ":" ) ) ) + typeNameList << str.section( QStringLiteral( ":" ), 1, 1 ); else typeNameList << str; } @@ -343,8 +343,8 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle Q_FOREACH ( const QDomElement &elem, projectLayerElements ) { - QString type = elem.attribute( "type" ); - if ( type == "vector" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "vector" ) ) { QgsMapLayer *mLayer = mProjectParser->createLayerFromElement( elem ); QgsVectorLayer* layer = qobject_cast( mLayer ); @@ -361,9 +361,9 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle QString typeName = layer->name(); if ( !layer->shortName().isEmpty() ) typeName = layer->shortName(); - typeName = typeName.replace( " ", "_" ); + typeName = typeName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); - if ( wfsLayersId.contains( layer->id() ) && ( aTypeName == "" || typeNameList.contains( typeName ) ) ) + if ( wfsLayersId.contains( layer->id() ) && ( aTypeName == QLatin1String( "" ) || typeNameList.contains( typeName ) ) ) { //do a select with searchRect and go through all the features QgsVectorDataProvider* provider = layer->dataProvider(); @@ -376,41 +376,41 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle const QSet& layerExcludedAttributes = layer->excludeAttributesWfs(); //xsd:element - QDomElement elementElem = doc.createElement( "element"/*xsd:element*/ ); - elementElem.setAttribute( "name", typeName ); - elementElem.setAttribute( "type", "qgs:" + typeName + "Type" ); - elementElem.setAttribute( "substitutionGroup", "gml:_Feature" ); + QDomElement elementElem = doc.createElement( QStringLiteral( "element" )/*xsd:element*/ ); + elementElem.setAttribute( QStringLiteral( "name" ), typeName ); + elementElem.setAttribute( QStringLiteral( "type" ), "qgs:" + typeName + "Type" ); + elementElem.setAttribute( QStringLiteral( "substitutionGroup" ), QStringLiteral( "gml:_Feature" ) ); parentElement.appendChild( elementElem ); //xsd:complexType - QDomElement complexTypeElem = doc.createElement( "complexType"/*xsd:complexType*/ ); - complexTypeElem.setAttribute( "name", typeName + "Type" ); + QDomElement complexTypeElem = doc.createElement( QStringLiteral( "complexType" )/*xsd:complexType*/ ); + complexTypeElem.setAttribute( QStringLiteral( "name" ), typeName + "Type" ); parentElement.appendChild( complexTypeElem ); //xsd:complexType - QDomElement complexContentElem = doc.createElement( "complexContent"/*xsd:complexContent*/ ); + QDomElement complexContentElem = doc.createElement( QStringLiteral( "complexContent" )/*xsd:complexContent*/ ); complexTypeElem.appendChild( complexContentElem ); //xsd:extension - QDomElement extensionElem = doc.createElement( "extension"/*xsd:extension*/ ); - extensionElem.setAttribute( "base", "gml:AbstractFeatureType" ); + QDomElement extensionElem = doc.createElement( QStringLiteral( "extension" )/*xsd:extension*/ ); + extensionElem.setAttribute( QStringLiteral( "base" ), QStringLiteral( "gml:AbstractFeatureType" ) ); complexContentElem.appendChild( extensionElem ); //xsd:sequence - QDomElement sequenceElem = doc.createElement( "sequence"/*xsd:sequence*/ ); + QDomElement sequenceElem = doc.createElement( QStringLiteral( "sequence" )/*xsd:sequence*/ ); extensionElem.appendChild( sequenceElem ); //xsd:element if ( layer->hasGeometryType() ) { - QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ ); - geomElem.setAttribute( "name", "geometry" ); - if ( provider->name() == "ogr" ) + QDomElement geomElem = doc.createElement( QStringLiteral( "element" )/*xsd:element*/ ); + geomElem.setAttribute( QStringLiteral( "name" ), QStringLiteral( "geometry" ) ); + if ( provider->name() == QLatin1String( "ogr" ) ) { // because some ogr drivers (e.g. ESRI ShapeFile, GML) // are not able to determine the geometry type of a layer. // we set to GeometryType - geomElem.setAttribute( "type", "gml:GeometryPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:GeometryPropertyType" ) ); } else { @@ -419,35 +419,35 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle { case QgsWkbTypes::Point25D: case QgsWkbTypes::Point: - geomElem.setAttribute( "type", "gml:PointPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:PointPropertyType" ) ); break; case QgsWkbTypes::LineString25D: case QgsWkbTypes::LineString: - geomElem.setAttribute( "type", "gml:LineStringPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:LineStringPropertyType" ) ); break; case QgsWkbTypes::Polygon25D: case QgsWkbTypes::Polygon: - geomElem.setAttribute( "type", "gml:PolygonPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:PolygonPropertyType" ) ); break; case QgsWkbTypes::MultiPoint25D: case QgsWkbTypes::MultiPoint: - geomElem.setAttribute( "type", "gml:MultiPointPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:MultiPointPropertyType" ) ); break; case QgsWkbTypes::MultiLineString25D: case QgsWkbTypes::MultiLineString: - geomElem.setAttribute( "type", "gml:MultiLineStringPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:MultiLineStringPropertyType" ) ); break; case QgsWkbTypes::MultiPolygon25D: case QgsWkbTypes::MultiPolygon: - geomElem.setAttribute( "type", "gml:MultiPolygonPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:MultiPolygonPropertyType" ) ); break; default: - geomElem.setAttribute( "type", "gml:GeometryPropertyType" ); + geomElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "gml:GeometryPropertyType" ) ); break; } } - geomElem.setAttribute( "minOccurs", "0" ); - geomElem.setAttribute( "maxOccurs", "1" ); + geomElem.setAttribute( QStringLiteral( "minOccurs" ), QStringLiteral( "0" ) ); + geomElem.setAttribute( QStringLiteral( "maxOccurs" ), QStringLiteral( "1" ) ); sequenceElem.appendChild( geomElem ); } @@ -464,32 +464,32 @@ void QgsWfsProjectParser::describeFeatureType( const QString& aTypeName, QDomEle } //xsd:element - QDomElement attElem = doc.createElement( "element"/*xsd:element*/ ); - attElem.setAttribute( "name", attributeName ); + QDomElement attElem = doc.createElement( QStringLiteral( "element" )/*xsd:element*/ ); + attElem.setAttribute( QStringLiteral( "name" ), attributeName ); QVariant::Type attributeType = fields.at( idx ).type(); if ( attributeType == QVariant::Int ) - attElem.setAttribute( "type", "integer" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "integer" ) ); else if ( attributeType == QVariant::LongLong ) - attElem.setAttribute( "type", "long" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "long" ) ); else if ( attributeType == QVariant::Double ) - attElem.setAttribute( "type", "double" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "double" ) ); else if ( attributeType == QVariant::Bool ) - attElem.setAttribute( "type", "boolean" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "boolean" ) ); else if ( attributeType == QVariant::Date ) - attElem.setAttribute( "type", "date" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "date" ) ); else if ( attributeType == QVariant::Time ) - attElem.setAttribute( "type", "time" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "time" ) ); else if ( attributeType == QVariant::DateTime ) - attElem.setAttribute( "type", "dateTime" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "dateTime" ) ); else - attElem.setAttribute( "type", "string" ); + attElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "string" ) ); sequenceElem.appendChild( attElem ); QString alias = fields.at( idx ).alias(); if ( !alias.isEmpty() ) { - attElem.setAttribute( "alias", alias ); + attElem.setAttribute( QStringLiteral( "alias" ), alias ); } } } @@ -520,7 +520,7 @@ int QgsWfsProjectParser::wfsLayerPrecision( const QString& aLayerId ) const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement wfsPrecElem = propertiesElem.firstChildElement( "WFSLayersPrecision" ); + QDomElement wfsPrecElem = propertiesElem.firstChildElement( QStringLiteral( "WFSLayersPrecision" ) ); if ( !wfsPrecElem.isNull() ) { QDomElement wfsLayerPrecElem = wfsPrecElem.firstChildElement( aLayerId ); @@ -548,13 +548,13 @@ QList QgsWfsProjectParser::mapLayerFromTypeName( const QString& aT QStringList wfsLayersId = wfsLayers(); QStringList typeNameList; - if ( aTypeName != "" ) + if ( aTypeName != QLatin1String( "" ) ) { - QStringList typeNameSplit = aTypeName.split( "," ); + QStringList typeNameSplit = aTypeName.split( QStringLiteral( "," ) ); Q_FOREACH ( const QString &str, typeNameSplit ) { - if ( str.contains( ":" ) ) - typeNameList << str.section( ":", 1, 1 ); + if ( str.contains( QLatin1String( ":" ) ) ) + typeNameList << str.section( QStringLiteral( ":" ), 1, 1 ); else typeNameList << str; } @@ -562,8 +562,8 @@ QList QgsWfsProjectParser::mapLayerFromTypeName( const QString& aT Q_FOREACH ( const QDomElement &elem, projectLayerElements ) { - QString type = elem.attribute( "type" ); - if ( type == "vector" ) + QString type = elem.attribute( QStringLiteral( "type" ) ); + if ( type == QLatin1String( "vector" ) ) { QgsMapLayer *mLayer = mProjectParser->createLayerFromElement( elem ); QgsVectorLayer* layer = qobject_cast( mLayer ); @@ -573,9 +573,9 @@ QList QgsWfsProjectParser::mapLayerFromTypeName( const QString& aT QString typeName = layer->name(); if ( !layer->shortName().isEmpty() ) typeName = layer->shortName(); - typeName = typeName.replace( " ", "_" ); + typeName = typeName.replace( QLatin1String( " " ), QLatin1String( "_" ) ); - if ( wfsLayersId.contains( layer->id() ) && ( aTypeName == "" || typeNameList.contains( typeName ) ) ) + if ( wfsLayersId.contains( layer->id() ) && ( aTypeName == QLatin1String( "" ) || typeNameList.contains( typeName ) ) ) layerList.push_back( mLayer ); } } diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index 600298eb749e..c7615c4c1880 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -60,10 +60,10 @@ #include #endif -static const QString WFS_NAMESPACE = "http://www.opengis.net/wfs"; -static const QString GML_NAMESPACE = "http://www.opengis.net/gml"; -static const QString OGC_NAMESPACE = "http://www.opengis.net/ogc"; -static const QString QGS_NAMESPACE = "http://www.qgis.org/gml"; +static const QString WFS_NAMESPACE = QStringLiteral( "http://www.opengis.net/wfs" ); +static const QString GML_NAMESPACE = QStringLiteral( "http://www.opengis.net/gml" ); +static const QString OGC_NAMESPACE = QStringLiteral( "http://www.opengis.net/ogc" ); +static const QString QGS_NAMESPACE = QStringLiteral( "http://www.qgis.org/gml" ); QgsWfsServer::QgsWfsServer( const QString& configFilePath @@ -113,16 +113,16 @@ void QgsWfsServer::executeRequest() } //request type - QString request = mParameters.value( "REQUEST" ); + QString request = mParameters.value( QStringLiteral( "REQUEST" ) ); if ( request.isEmpty() ) { //do some error handling - QgsMessageLog::logMessage( "unable to find 'REQUEST' parameter, exiting..." ); - mRequestHandler->setServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) ); + QgsMessageLog::logMessage( QStringLiteral( "unable to find 'REQUEST' parameter, exiting..." ) ); + mRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "OperationNotSupported" ), QStringLiteral( "Please check the value of the REQUEST parameter" ) ) ); return; } - if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 ) + if ( request.compare( QLatin1String( "GetCapabilities" ), Qt::CaseInsensitive ) == 0 ) { QDomDocument capabilitiesDocument; try @@ -134,11 +134,11 @@ void QgsWfsServer::executeRequest() mRequestHandler->setServiceException( ex ); return; } - QgsMessageLog::logMessage( "Setting GetCapabilities response" ); + QgsMessageLog::logMessage( QStringLiteral( "Setting GetCapabilities response" ) ); mRequestHandler->setGetCapabilitiesResponse( capabilitiesDocument ); return; } - else if ( request.compare( "DescribeFeatureType", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "DescribeFeatureType" ), Qt::CaseInsensitive ) == 0 ) { QDomDocument describeDocument; try @@ -150,14 +150,14 @@ void QgsWfsServer::executeRequest() mRequestHandler->setServiceException( ex ); return; } - QgsMessageLog::logMessage( "Setting GetCapabilities response" ); + QgsMessageLog::logMessage( QStringLiteral( "Setting GetCapabilities response" ) ); mRequestHandler->setGetCapabilitiesResponse( describeDocument ); return; } - else if ( request.compare( "GetFeature", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetFeature" ), Qt::CaseInsensitive ) == 0 ) { //output format for GetFeature - QString outputFormat = mParameters.value( "OUTPUTFORMAT" ); + QString outputFormat = mParameters.value( QStringLiteral( "OUTPUTFORMAT" ) ); try { getFeature( *mRequestHandler, outputFormat ); @@ -169,19 +169,19 @@ void QgsWfsServer::executeRequest() return; } - else if ( request.compare( "Transaction", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "Transaction" ), Qt::CaseInsensitive ) == 0 ) { QDomDocument transactionDocument; try { - transactionDocument = transaction( mParameters.value( "REQUEST_BODY" ) ); + transactionDocument = transaction( mParameters.value( QStringLiteral( "REQUEST_BODY" ) ) ); } catch ( QgsMapServiceException& ex ) { mRequestHandler->setServiceException( ex ); return; } - QgsMessageLog::logMessage( "Setting Transaction response" ); + QgsMessageLog::logMessage( QStringLiteral( "Setting Transaction response" ) ); mRequestHandler->setGetCapabilitiesResponse( transactionDocument ); return; } @@ -189,20 +189,20 @@ void QgsWfsServer::executeRequest() QDomDocument QgsWfsServer::getCapabilities() { - QgsMessageLog::logMessage( "Entering." ); + QgsMessageLog::logMessage( QStringLiteral( "Entering." ) ); QDomDocument doc; //wfs:WFS_Capabilities element - QDomElement wfsCapabilitiesElement = doc.createElement( "WFS_Capabilities"/*wms:WFS_Capabilities*/ ); - wfsCapabilitiesElement.setAttribute( "xmlns", WFS_NAMESPACE ); - wfsCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - wfsCapabilitiesElement.setAttribute( "xsi:schemaLocation", WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/WFS-capabilities.xsd" ); - wfsCapabilitiesElement.setAttribute( "xmlns:ogc", OGC_NAMESPACE ); - wfsCapabilitiesElement.setAttribute( "xmlns:gml", GML_NAMESPACE ); - wfsCapabilitiesElement.setAttribute( "xmlns:ows", "http://www.opengis.net/ows" ); - wfsCapabilitiesElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - wfsCapabilitiesElement.setAttribute( "version", "1.0.0" ); - wfsCapabilitiesElement.setAttribute( "updateSequence", "0" ); + QDomElement wfsCapabilitiesElement = doc.createElement( QStringLiteral( "WFS_Capabilities" )/*wms:WFS_Capabilities*/ ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/WFS-capabilities.xsd" ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:ows" ), QStringLiteral( "http://www.opengis.net/ows" ) ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) ); + wfsCapabilitiesElement.setAttribute( QStringLiteral( "updateSequence" ), QStringLiteral( "0" ) ); doc.appendChild( wfsCapabilitiesElement ); if ( mConfigParser ) @@ -211,19 +211,19 @@ QDomDocument QgsWfsServer::getCapabilities() } //wfs:Capability element - QDomElement capabilityElement = doc.createElement( "Capability"/*wfs:Capability*/ ); + QDomElement capabilityElement = doc.createElement( QStringLiteral( "Capability" )/*wfs:Capability*/ ); wfsCapabilitiesElement.appendChild( capabilityElement ); //wfs:Request element - QDomElement requestElement = doc.createElement( "Request"/*wfs:Request*/ ); + QDomElement requestElement = doc.createElement( QStringLiteral( "Request" )/*wfs:Request*/ ); capabilityElement.appendChild( requestElement ); //wfs:GetCapabilities - QDomElement getCapabilitiesElement = doc.createElement( "GetCapabilities"/*wfs:GetCapabilities*/ ); + QDomElement getCapabilitiesElement = doc.createElement( QStringLiteral( "GetCapabilities" )/*wfs:GetCapabilities*/ ); requestElement.appendChild( getCapabilitiesElement ); - QDomElement dcpTypeElement = doc.createElement( "DCPType"/*wfs:DCPType*/ ); + QDomElement dcpTypeElement = doc.createElement( QStringLiteral( "DCPType" )/*wfs:DCPType*/ ); getCapabilitiesElement.appendChild( dcpTypeElement ); - QDomElement httpElement = doc.createElement( "HTTP"/*wfs:HTTP*/ ); + QDomElement httpElement = doc.createElement( QStringLiteral( "HTTP" )/*wfs:HTTP*/ ); dcpTypeElement.appendChild( httpElement ); //Prepare url @@ -242,58 +242,58 @@ QDomDocument QgsWfsServer::getCapabilities() } //only Get supported for the moment - QDomElement getElement = doc.createElement( "Get"/*wfs:Get*/ ); + QDomElement getElement = doc.createElement( QStringLiteral( "Get" )/*wfs:Get*/ ); httpElement.appendChild( getElement ); - getElement.setAttribute( "onlineResource", hrefString ); + getElement.setAttribute( QStringLiteral( "onlineResource" ), hrefString ); QDomElement getCapabilitiesDhcTypePostElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' - getCapabilitiesDhcTypePostElement.firstChild().firstChild().toElement().setTagName( "Post" ); + getCapabilitiesDhcTypePostElement.firstChild().firstChild().toElement().setTagName( QStringLiteral( "Post" ) ); getCapabilitiesElement.appendChild( getCapabilitiesDhcTypePostElement ); //wfs:DescribeFeatureType - QDomElement describeFeatureTypeElement = doc.createElement( "DescribeFeatureType"/*wfs:DescribeFeatureType*/ ); + QDomElement describeFeatureTypeElement = doc.createElement( QStringLiteral( "DescribeFeatureType" )/*wfs:DescribeFeatureType*/ ); requestElement.appendChild( describeFeatureTypeElement ); - QDomElement schemaDescriptionLanguageElement = doc.createElement( "SchemaDescriptionLanguage"/*wfs:SchemaDescriptionLanguage*/ ); + QDomElement schemaDescriptionLanguageElement = doc.createElement( QStringLiteral( "SchemaDescriptionLanguage" )/*wfs:SchemaDescriptionLanguage*/ ); describeFeatureTypeElement.appendChild( schemaDescriptionLanguageElement ); - QDomElement xmlSchemaElement = doc.createElement( "XMLSCHEMA"/*wfs:XMLSCHEMA*/ ); + QDomElement xmlSchemaElement = doc.createElement( QStringLiteral( "XMLSCHEMA" )/*wfs:XMLSCHEMA*/ ); schemaDescriptionLanguageElement.appendChild( xmlSchemaElement ); QDomElement describeFeatureTypeDhcTypeElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' describeFeatureTypeElement.appendChild( describeFeatureTypeDhcTypeElement ); QDomElement describeFeatureTypeDhcTypePostElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' - describeFeatureTypeDhcTypePostElement.firstChild().firstChild().toElement().setTagName( "Post" ); + describeFeatureTypeDhcTypePostElement.firstChild().firstChild().toElement().setTagName( QStringLiteral( "Post" ) ); describeFeatureTypeElement.appendChild( describeFeatureTypeDhcTypePostElement ); //wfs:GetFeature - QDomElement getFeatureElement = doc.createElement( "GetFeature"/*wfs:GetFeature*/ ); + QDomElement getFeatureElement = doc.createElement( QStringLiteral( "GetFeature" )/*wfs:GetFeature*/ ); requestElement.appendChild( getFeatureElement ); - QDomElement getFeatureFormatElement = doc.createElement( "ResultFormat" );/*wfs:ResultFormat*/ + QDomElement getFeatureFormatElement = doc.createElement( QStringLiteral( "ResultFormat" ) );/*wfs:ResultFormat*/ getFeatureElement.appendChild( getFeatureFormatElement ); - QDomElement gmlFormatElement = doc.createElement( "GML2" );/*wfs:GML2*/ + QDomElement gmlFormatElement = doc.createElement( QStringLiteral( "GML2" ) );/*wfs:GML2*/ getFeatureFormatElement.appendChild( gmlFormatElement ); - QDomElement gml3FormatElement = doc.createElement( "GML3" );/*wfs:GML3*/ + QDomElement gml3FormatElement = doc.createElement( QStringLiteral( "GML3" ) );/*wfs:GML3*/ getFeatureFormatElement.appendChild( gml3FormatElement ); - QDomElement geojsonFormatElement = doc.createElement( "GeoJSON" );/*wfs:GeoJSON*/ + QDomElement geojsonFormatElement = doc.createElement( QStringLiteral( "GeoJSON" ) );/*wfs:GeoJSON*/ getFeatureFormatElement.appendChild( geojsonFormatElement ); QDomElement getFeatureDhcTypeGetElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' getFeatureElement.appendChild( getFeatureDhcTypeGetElement ); QDomElement getFeatureDhcTypePostElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' - getFeatureDhcTypePostElement.firstChild().firstChild().toElement().setTagName( "Post" ); + getFeatureDhcTypePostElement.firstChild().firstChild().toElement().setTagName( QStringLiteral( "Post" ) ); getFeatureElement.appendChild( getFeatureDhcTypePostElement ); //wfs:Transaction - QDomElement transactionElement = doc.createElement( "Transaction"/*wfs:Transaction*/ ); + QDomElement transactionElement = doc.createElement( QStringLiteral( "Transaction" )/*wfs:Transaction*/ ); requestElement.appendChild( transactionElement ); QDomElement transactionDhcTypeElement = dcpTypeElement.cloneNode().toElement();//this is the same as for 'GetCapabilities' - transactionDhcTypeElement.firstChild().firstChild().toElement().setTagName( "Post" ); + transactionDhcTypeElement.firstChild().firstChild().toElement().setTagName( QStringLiteral( "Post" ) ); transactionElement.appendChild( transactionDhcTypeElement ); //wfs:FeatureTypeList element - QDomElement featureTypeListElement = doc.createElement( "FeatureTypeList"/*wfs:FeatureTypeList*/ ); + QDomElement featureTypeListElement = doc.createElement( QStringLiteral( "FeatureTypeList" )/*wfs:FeatureTypeList*/ ); wfsCapabilitiesElement.appendChild( featureTypeListElement ); //wfs:Operations element - QDomElement operationsElement = doc.createElement( "Operations"/*wfs:Operations*/ ); + QDomElement operationsElement = doc.createElement( QStringLiteral( "Operations" )/*wfs:Operations*/ ); featureTypeListElement.appendChild( operationsElement ); //wfs:Query element - QDomElement queryElement = doc.createElement( "Query"/*wfs:Query*/ ); + QDomElement queryElement = doc.createElement( QStringLiteral( "Query" )/*wfs:Query*/ ); operationsElement.appendChild( queryElement ); /* * Adding layer liste in featureTypeListElement @@ -307,60 +307,60 @@ QDomDocument QgsWfsServer::getCapabilities() * Adding ogc:Filter_Capabilities in capabilityElement */ //ogc:Filter_Capabilities element - QDomElement filterCapabilitiesElement = doc.createElement( "ogc:Filter_Capabilities"/*ogc:Filter_Capabilities*/ ); + QDomElement filterCapabilitiesElement = doc.createElement( QStringLiteral( "ogc:Filter_Capabilities" )/*ogc:Filter_Capabilities*/ ); wfsCapabilitiesElement.appendChild( filterCapabilitiesElement ); - QDomElement spatialCapabilitiesElement = doc.createElement( "ogc:Spatial_Capabilities"/*ogc:Spatial_Capabilities*/ ); + QDomElement spatialCapabilitiesElement = doc.createElement( QStringLiteral( "ogc:Spatial_Capabilities" )/*ogc:Spatial_Capabilities*/ ); filterCapabilitiesElement.appendChild( spatialCapabilitiesElement ); - QDomElement spatialOperatorsElement = doc.createElement( "ogc:Spatial_Operators"/*ogc:Spatial_Operators*/ ); + QDomElement spatialOperatorsElement = doc.createElement( QStringLiteral( "ogc:Spatial_Operators" )/*ogc:Spatial_Operators*/ ); spatialCapabilitiesElement.appendChild( spatialOperatorsElement ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:BBOX"/*ogc:BBOX*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Disjoint"/*ogc:Disjoint*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Intersect"/*ogc:Intersects*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Touches"/*ogc:Touches*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Crosses"/*ogc:Crosses*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Contains"/*ogc:Contains*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Overlaps"/*ogc:Overlaps*/ ) ); - spatialOperatorsElement.appendChild( doc.createElement( "ogc:Within"/*ogc:Within*/ ) ); - QDomElement scalarCapabilitiesElement = doc.createElement( "ogc:Scalar_Capabilities"/*ogc:Scalar_Capabilities*/ ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:BBOX" )/*ogc:BBOX*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Disjoint" )/*ogc:Disjoint*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Intersect" )/*ogc:Intersects*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Touches" )/*ogc:Touches*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Crosses" )/*ogc:Crosses*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Contains" )/*ogc:Contains*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Overlaps" )/*ogc:Overlaps*/ ) ); + spatialOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Within" )/*ogc:Within*/ ) ); + QDomElement scalarCapabilitiesElement = doc.createElement( QStringLiteral( "ogc:Scalar_Capabilities" )/*ogc:Scalar_Capabilities*/ ); filterCapabilitiesElement.appendChild( scalarCapabilitiesElement ); - QDomElement comparisonOperatorsElement = doc.createElement( "ogc:Comparison_Operators"/*ogc:Comparison_Operators*/ ); + QDomElement comparisonOperatorsElement = doc.createElement( QStringLiteral( "ogc:Comparison_Operators" )/*ogc:Comparison_Operators*/ ); scalarCapabilitiesElement.appendChild( comparisonOperatorsElement ); - comparisonOperatorsElement.appendChild( doc.createElement( "ogc:Simple_Comparisons"/*ogc:Simple_Comparisons*/ ) ); - comparisonOperatorsElement.appendChild( doc.createElement( "ogc:Between"/*ogc:Between*/ ) ); - comparisonOperatorsElement.appendChild( doc.createElement( "ogc:Like"/*ogc:Like*/ ) ); + comparisonOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Simple_Comparisons" )/*ogc:Simple_Comparisons*/ ) ); + comparisonOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Between" )/*ogc:Between*/ ) ); + comparisonOperatorsElement.appendChild( doc.createElement( QStringLiteral( "ogc:Like" )/*ogc:Like*/ ) ); return doc; } QDomDocument QgsWfsServer::describeFeatureType() { - QgsMessageLog::logMessage( "Entering." ); + QgsMessageLog::logMessage( QStringLiteral( "Entering." ) ); QDomDocument doc; //xsd:schema - QDomElement schemaElement = doc.createElement( "schema"/*xsd:schema*/ ); - schemaElement.setAttribute( "xmlns", "http://www.w3.org/2001/XMLSchema" ); - schemaElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" ); - schemaElement.setAttribute( "xmlns:ogc", OGC_NAMESPACE ); - schemaElement.setAttribute( "xmlns:gml", GML_NAMESPACE ); - schemaElement.setAttribute( "xmlns:qgs", QGS_NAMESPACE ); - schemaElement.setAttribute( "targetNamespace", QGS_NAMESPACE ); - schemaElement.setAttribute( "elementFormDefault", "qualified" ); - schemaElement.setAttribute( "version", "1.0" ); + QDomElement schemaElement = doc.createElement( QStringLiteral( "schema" )/*xsd:schema*/ ); + schemaElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); + schemaElement.setAttribute( QStringLiteral( "xmlns:xsd" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema" ) ); + schemaElement.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE ); + schemaElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE ); + schemaElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE ); + schemaElement.setAttribute( QStringLiteral( "targetNamespace" ), QGS_NAMESPACE ); + schemaElement.setAttribute( QStringLiteral( "elementFormDefault" ), QStringLiteral( "qualified" ) ); + schemaElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0" ) ); doc.appendChild( schemaElement ); //xsd:import - QDomElement importElement = doc.createElement( "import"/*xsd:import*/ ); - importElement.setAttribute( "namespace", GML_NAMESPACE ); - importElement.setAttribute( "schemaLocation", "http://schemas.opengis.net/gml/2.1.2/feature.xsd" ); + QDomElement importElement = doc.createElement( QStringLiteral( "import" )/*xsd:import*/ ); + importElement.setAttribute( QStringLiteral( "namespace" ), GML_NAMESPACE ); + importElement.setAttribute( QStringLiteral( "schemaLocation" ), QStringLiteral( "http://schemas.opengis.net/gml/2.1.2/feature.xsd" ) ); schemaElement.appendChild( importElement ); //defining typename - QString typeName = ""; + QString typeName = QLatin1String( "" ); QDomDocument queryDoc; QString errorMsg; - if ( queryDoc.setContent( mParameters.value( "REQUEST_BODY" ), true, &errorMsg ) ) + if ( queryDoc.setContent( mParameters.value( QStringLiteral( "REQUEST_BODY" ) ), true, &errorMsg ) ) { //read doc QDomElement queryDocElem = queryDoc.documentElement(); @@ -370,9 +370,9 @@ QDomDocument QgsWfsServer::describeFeatureType() for ( int i = 0; i < docChildNodes.size(); i++ ) { QDomElement docChildElem = docChildNodes.at( i ).toElement(); - if ( docChildElem.tagName() == "TypeName" ) + if ( docChildElem.tagName() == QLatin1String( "TypeName" ) ) { - if ( typeName == "" ) + if ( typeName == QLatin1String( "" ) ) typeName = docChildElem.text(); else typeName += "," + docChildElem.text(); @@ -384,7 +384,7 @@ QDomDocument QgsWfsServer::describeFeatureType() else { //read TYPENAME - QMap::const_iterator type_name_it = mParameters.constFind( "TYPENAME" ); + QMap::const_iterator type_name_it = mParameters.constFind( QStringLiteral( "TYPENAME" ) ); if ( type_name_it != mParameters.constEnd() ) { typeName = type_name_it.value(); @@ -427,44 +427,44 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //there's LOTS of potential exit paths here, so we avoid having to restore the filters manually QScopedPointer< QgsOWSServerFilterRestorer > filterRestorer( new QgsOWSServerFilterRestorer() ); - if ( doc.setContent( mParameters.value( "REQUEST_BODY" ), true, &errorMsg ) ) + if ( doc.setContent( mParameters.value( QStringLiteral( "REQUEST_BODY" ) ), true, &errorMsg ) ) { QDomElement docElem = doc.documentElement(); - if ( docElem.hasAttribute( "maxFeatures" ) ) + if ( docElem.hasAttribute( QStringLiteral( "maxFeatures" ) ) ) { hasFeatureLimit = true; - maxFeatures = docElem.attribute( "maxFeatures" ).toLong(); + maxFeatures = docElem.attribute( QStringLiteral( "maxFeatures" ) ).toLong(); } - if ( docElem.hasAttribute( "startIndex" ) ) + if ( docElem.hasAttribute( QStringLiteral( "startIndex" ) ) ) { - startIndex = docElem.attribute( "startIndex" ).toLong(); + startIndex = docElem.attribute( QStringLiteral( "startIndex" ) ).toLong(); } - QDomNodeList queryNodes = docElem.elementsByTagName( "Query" ); + QDomNodeList queryNodes = docElem.elementsByTagName( QStringLiteral( "Query" ) ); QDomElement queryElem; for ( int i = 0; i < queryNodes.size(); i++ ) { queryElem = queryNodes.at( 0 ).toElement(); - mTypeName = queryElem.attribute( "typeName", "" ); - if ( mTypeName.contains( ":" ) ) + mTypeName = queryElem.attribute( QStringLiteral( "typeName" ), QLatin1String( "" ) ); + if ( mTypeName.contains( QLatin1String( ":" ) ) ) { - mTypeName = mTypeName.section( ":", 1, 1 ); + mTypeName = mTypeName.section( QStringLiteral( ":" ), 1, 1 ); } mTypeNames << mTypeName; } for ( int i = 0; i < queryNodes.size(); i++ ) { queryElem = queryNodes.at( 0 ).toElement(); - mTypeName = queryElem.attribute( "typeName", "" ); - if ( mTypeName.contains( ":" ) ) + mTypeName = queryElem.attribute( QStringLiteral( "typeName" ), QLatin1String( "" ) ); + if ( mTypeName.contains( QLatin1String( ":" ) ) ) { - mTypeName = mTypeName.section( ":", 1, 1 ); + mTypeName = mTypeName.section( QStringLiteral( ":" ), 1, 1 ); } layerList = mConfigParser->mapLayerFromTypeName( mTypeName ); if ( layerList.size() < 1 ) { - mErrors << QString( "The layer for the TypeName '%1' is not found" ).arg( mTypeName ); + mErrors << QStringLiteral( "The layer for the TypeName '%1' is not found" ).arg( mTypeName ); continue; } @@ -475,7 +475,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format #ifdef HAVE_SERVER_PYTHON_PLUGINS if ( !mAccessControl->layerReadPermission( currentLayer ) ) { - throw QgsMapServiceException( "Security", "Feature access permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature access permission denied" ) ); } applyAccessControlLayerFilters( currentLayer, filterRestorer->originalFilters() ); #endif @@ -505,7 +505,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QgsVectorDataProvider* provider = layer->dataProvider(); if ( !provider ) { - mErrors << QString( "The layer's provider for the TypeName '%1' is not found" ).arg( mTypeName ); + mErrors << QStringLiteral( "The layer's provider for the TypeName '%1' is not found" ).arg( mTypeName ); continue; } @@ -527,12 +527,12 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format for ( int q = 0; q < queryChildNodes.size(); q++ ) { QDomElement queryChildElem = queryChildNodes.at( q ).toElement(); - if ( queryChildElem.tagName() == "PropertyName" ) + if ( queryChildElem.tagName() == QLatin1String( "PropertyName" ) ) { fieldName = queryChildElem.text(); - if ( fieldName.contains( ":" ) ) + if ( fieldName.contains( QLatin1String( ":" ) ) ) { - fieldName = fieldName.section( ":", 1, 1 ); + fieldName = fieldName.section( QStringLiteral( ":" ), 1, 1 ); } int fieldNameIdx = fields.lookupField( fieldName ); if ( fieldNameIdx > -1 ) @@ -572,24 +572,24 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QgsFeatureIterator fit = layer->getFeatures( fReq ); - QDomNodeList filterNodes = queryElem.elementsByTagName( "Filter" ); + QDomNodeList filterNodes = queryElem.elementsByTagName( QStringLiteral( "Filter" ) ); if ( !filterNodes.isEmpty() ) { QDomElement filterElem = filterNodes.at( 0 ).toElement(); - QDomNodeList fidNodes = filterElem.elementsByTagName( "FeatureId" ); + QDomNodeList fidNodes = filterElem.elementsByTagName( QStringLiteral( "FeatureId" ) ); if ( !fidNodes.isEmpty() ) { QDomElement fidElem; - QString fid = ""; + QString fid = QLatin1String( "" ); for ( int f = 0; f < fidNodes.size(); f++ ) { fidElem = fidNodes.at( f ).toElement(); - fid = fidElem.attribute( "fid" ); - if ( fid.contains( "." ) ) + fid = fidElem.attribute( QStringLiteral( "fid" ) ); + if ( fid.contains( QLatin1String( "." ) ) ) { - if ( fid.section( ".", 0, 0 ) != mTypeName ) + if ( fid.section( QStringLiteral( "." ), 0, 0 ) != mTypeName ) continue; - fid = fid.section( ".", 1, 1 ); + fid = fid.section( QStringLiteral( "." ), 1, 1 ); } //Need to be test for propertyname @@ -604,12 +604,12 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format setGetFeature( request, format, &feature, featCounter, layerPrec, layerCrs, attrIndexes, layerExcludedAttributes ); - fid = ""; + fid = QLatin1String( "" ); ++featCounter; ++featureCounter; } } - else if ( filterElem.firstChildElement().tagName() == "BBOX" ) + else if ( filterElem.firstChildElement().tagName() == QLatin1String( "BBOX" ) ) { QDomElement bboxElem = filterElem.firstChildElement(); QDomElement childElem = bboxElem.firstChildElement(); @@ -619,11 +619,11 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format while ( !childElem.isNull() ) { - if ( childElem.tagName() == "Box" ) + if ( childElem.tagName() == QLatin1String( "Box" ) ) { req.setFilterRect( QgsOgcUtils::rectangleFromGMLBox( childElem ) ); } - else if ( childElem.tagName() != "PropertyName" ) + else if ( childElem.tagName() != QLatin1String( "PropertyName" ) ) { QgsGeometry geom = QgsOgcUtils::geometryFromGML( childElem ); req.setFilterRect( geom.boundingBox() ); @@ -653,7 +653,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format { if ( filter->hasParserError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", filter->parserErrorString() ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), filter->parserErrorString() ); } while ( fit.nextFeature( feature ) && ( !hasFeatureLimit || featureCounter < maxFeatures + startIndex ) ) { @@ -662,7 +662,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QVariant res = filter->evaluate( &expressionContext ); if ( filter->hasEvalError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", filter->evalErrorString() ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), filter->evalErrorString() ); } if ( res.toInt() != 0 ) { @@ -698,7 +698,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format } else { - mErrors << QString( "The layer for the TypeName '%1' is not a WFS layer" ).arg( mTypeName ); + mErrors << QStringLiteral( "The layer for the TypeName '%1' is not a WFS layer" ).arg( mTypeName ); } } @@ -706,7 +706,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //force restoration of original layer filters filterRestorer.reset(); - QgsMessageLog::logMessage( mErrors.join( "\n" ) ); + QgsMessageLog::logMessage( mErrors.join( QStringLiteral( "\n" ) ) ); QgsMapLayerRegistry::instance()->removeAllMapLayers(); if ( featureCounter <= startIndex ) @@ -729,47 +729,47 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //read FEATUREDID bool featureIdOk = false; QStringList featureIdList; - QMap::const_iterator feature_id_it = mParameters.constFind( "FEATUREID" ); + QMap::const_iterator feature_id_it = mParameters.constFind( QStringLiteral( "FEATUREID" ) ); if ( feature_id_it != mParameters.constEnd() ) { featureIdOk = true; - featureIdList = feature_id_it.value().split( "," ); + featureIdList = feature_id_it.value().split( QStringLiteral( "," ) ); QStringList typeNameList; Q_FOREACH ( const QString &fidStr, featureIdList ) { // testing typename in the WFS featureID - if ( !fidStr.contains( "." ) ) - throw QgsMapServiceException( "RequestNotWellFormed", "FEATUREID has to have TYPENAME in the values" ); + if ( !fidStr.contains( QLatin1String( "." ) ) ) + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "FEATUREID has to have TYPENAME in the values" ) ); - QString typeName = fidStr.section( ".", 0, 0 ); + QString typeName = fidStr.section( QStringLiteral( "." ), 0, 0 ); if ( !typeNameList.contains( typeName ) ) typeNameList << typeName; } - mTypeName = typeNameList.join( "," ); + mTypeName = typeNameList.join( QStringLiteral( "," ) ); } if ( !featureIdOk ) { //read TYPENAME - QMap::const_iterator type_name_it = mParameters.constFind( "TYPENAME" ); + QMap::const_iterator type_name_it = mParameters.constFind( QStringLiteral( "TYPENAME" ) ); if ( type_name_it != mParameters.constEnd() ) { mTypeName = type_name_it.value(); } else { - throw QgsMapServiceException( "RequestNotWellFormed", "TYPENAME is MANDATORY" ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "TYPENAME is MANDATORY" ) ); } //read FILTER - QMap::const_iterator filterIt = mParameters.constFind( "FILTER" ); + QMap::const_iterator filterIt = mParameters.constFind( QStringLiteral( "FILTER" ) ); if ( filterIt != mParameters.constEnd() ) { QString errorMsg; if ( !filter.setContent( filterIt.value(), true, &errorMsg ) ) { - throw QgsMapServiceException( "RequestNotWellFormed", QString( "error message: %1. The XML string was: %2" ).arg( errorMsg, filterIt.value() ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "error message: %1. The XML string was: %2" ).arg( errorMsg, filterIt.value() ) ); } else { @@ -780,7 +780,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //read EXP_FILTER if ( !filterOk ) { - QMap::const_iterator expFilterIt = mParameters.constFind( "EXP_FILTER" ); + QMap::const_iterator expFilterIt = mParameters.constFind( QStringLiteral( "EXP_FILTER" ) ); if ( expFilterIt != mParameters.constEnd() ) { expFilterOk = true; @@ -791,7 +791,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //read BBOX if ( !filterOk ) { - QMap::const_iterator bbIt = mParameters.constFind( "BBOX" ); + QMap::const_iterator bbIt = mParameters.constFind( QStringLiteral( "BBOX" ) ); if ( bbIt == mParameters.constEnd() ) { minx = 0; @@ -804,20 +804,20 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format bool conversionSuccess; bboxOk = true; QString bbString = bbIt.value(); - minx = bbString.section( ",", 0, 0 ).toDouble( &conversionSuccess ); + minx = bbString.section( QStringLiteral( "," ), 0, 0 ).toDouble( &conversionSuccess ); bboxOk &= conversionSuccess; - miny = bbString.section( ",", 1, 1 ).toDouble( &conversionSuccess ); + miny = bbString.section( QStringLiteral( "," ), 1, 1 ).toDouble( &conversionSuccess ); bboxOk &= conversionSuccess; - maxx = bbString.section( ",", 2, 2 ).toDouble( &conversionSuccess ); + maxx = bbString.section( QStringLiteral( "," ), 2, 2 ).toDouble( &conversionSuccess ); bboxOk &= conversionSuccess; - maxy = bbString.section( ",", 3, 3 ).toDouble( &conversionSuccess ); + maxy = bbString.section( QStringLiteral( "," ), 3, 3 ).toDouble( &conversionSuccess ); bboxOk &= conversionSuccess; } } } //read MAXFEATURES - QMap::const_iterator mfIt = mParameters.constFind( "MAXFEATURES" ); + QMap::const_iterator mfIt = mParameters.constFind( QStringLiteral( "MAXFEATURES" ) ); if ( mfIt != mParameters.constEnd() ) { QString mfString = mfIt.value(); @@ -827,7 +827,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format } //read STARTINDEX - QMap::const_iterator siIt = mParameters.constFind( "STARTINDEX" ); + QMap::const_iterator siIt = mParameters.constFind( QStringLiteral( "STARTINDEX" ) ); if ( siIt != mParameters.constEnd() ) { QString siString = siIt.value(); @@ -837,27 +837,27 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //read PROPERTYNAME mWithGeom = true; - mPropertyName = "*"; - QMap::const_iterator pnIt = mParameters.constFind( "PROPERTYNAME" ); + mPropertyName = QStringLiteral( "*" ); + QMap::const_iterator pnIt = mParameters.constFind( QStringLiteral( "PROPERTYNAME" ) ); if ( pnIt != mParameters.constEnd() ) { mPropertyName = pnIt.value(); } - mGeometryName = ""; - QMap::const_iterator gnIt = mParameters.constFind( "GEOMETRYNAME" ); + mGeometryName = QLatin1String( "" ); + QMap::const_iterator gnIt = mParameters.constFind( QStringLiteral( "GEOMETRYNAME" ) ); if ( gnIt != mParameters.constEnd() ) { mGeometryName = gnIt.value().toUpper(); } - mTypeNames = mTypeName.split( "," ); + mTypeNames = mTypeName.split( QStringLiteral( "," ) ); Q_FOREACH ( const QString &tnStr, mTypeNames ) { mTypeName = tnStr; layerList = mConfigParser->mapLayerFromTypeName( tnStr ); if ( layerList.size() < 1 ) { - mErrors << QString( "The layer for the TypeName '%1' is not found" ).arg( tnStr ); + mErrors << QStringLiteral( "The layer for the TypeName '%1' is not found" ).arg( tnStr ); continue; } @@ -891,7 +891,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QgsVectorDataProvider* provider = layer->dataProvider(); if ( !provider ) { - mErrors << QString( "The layer's provider for the TypeName '%1' is not found" ).arg( tnStr ); + mErrors << QStringLiteral( "The layer's provider for the TypeName '%1' is not found" ).arg( tnStr ); continue; } @@ -902,9 +902,9 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format //Using pending attributes and pending fields QgsAttributeList attrIndexes = layer->pendingAllAttributesList(); - if ( mPropertyName != "*" ) + if ( mPropertyName != QLatin1String( "*" ) ) { - QStringList attrList = mPropertyName.split( "," ); + QStringList attrList = mPropertyName.split( QStringLiteral( "," ) ); if ( !attrList.isEmpty() ) { QStringList::const_iterator alstIt; @@ -944,7 +944,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format continue; //Need to be test for propertyname layer->getFeatures( QgsFeatureRequest() - .setFilterFid( fidStr.section( ".", 1, 1 ).toInt() ) + .setFilterFid( fidStr.section( QStringLiteral( "." ), 1, 1 ).toInt() ) .setFlags( mWithGeom ? QgsFeatureRequest::NoFlags : QgsFeatureRequest::NoGeometry ) .setSubsetOfAttributes( attrIndexes ) ).nextFeature( feature ); @@ -984,7 +984,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format { if ( filter->hasParserError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", QString( "Expression filter error message: %1." ).arg( filter->parserErrorString() ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "Expression filter error message: %1." ).arg( filter->parserErrorString() ) ); } while ( fit.nextFeature( feature ) && ( !hasFeatureLimit || featureCounter < maxFeatures + startIndex ) ) { @@ -992,7 +992,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QVariant res = filter->evaluate( &expressionContext ); if ( filter->hasEvalError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", QString( "Expression filter eval error message: %1." ).arg( filter->evalErrorString() ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "Expression filter eval error message: %1." ).arg( filter->evalErrorString() ) ); } if ( res.toInt() != 0 ) { @@ -1012,20 +1012,20 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format else if ( filterOk ) { QDomElement filterElem = filter.firstChildElement(); - QDomNodeList fidNodes = filterElem.elementsByTagName( "FeatureId" ); + QDomNodeList fidNodes = filterElem.elementsByTagName( QStringLiteral( "FeatureId" ) ); if ( !fidNodes.isEmpty() ) { QDomElement fidElem; - QString fid = ""; + QString fid = QLatin1String( "" ); for ( int f = 0; f < fidNodes.size(); f++ ) { fidElem = fidNodes.at( f ).toElement(); - fid = fidElem.attribute( "fid" ); - if ( fid.contains( "." ) ) + fid = fidElem.attribute( QStringLiteral( "fid" ) ); + if ( fid.contains( QLatin1String( "." ) ) ) { - if ( fid.section( ".", 0, 0 ) != mTypeName ) + if ( fid.section( QStringLiteral( "." ), 0, 0 ) != mTypeName ) continue; - fid = fid.section( ".", 1, 1 ); + fid = fid.section( QStringLiteral( "." ), 1, 1 ); } //Need to be test for propertyname @@ -1040,12 +1040,12 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format setGetFeature( request, format, &feature, featCounter, layerPrec, layerCrs, attrIndexes, layerExcludedAttributes ); - fid = ""; + fid = QLatin1String( "" ); ++featCounter; ++featureCounter; } } - else if ( filterElem.firstChildElement().tagName() == "BBOX" ) + else if ( filterElem.firstChildElement().tagName() == QLatin1String( "BBOX" ) ) { QDomElement bboxElem = filterElem.firstChildElement(); QDomElement childElem = bboxElem.firstChildElement(); @@ -1055,11 +1055,11 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format while ( !childElem.isNull() ) { - if ( childElem.tagName() == "Box" ) + if ( childElem.tagName() == QLatin1String( "Box" ) ) { req.setFilterRect( QgsOgcUtils::rectangleFromGMLBox( childElem ) ); } - else if ( childElem.tagName() != "PropertyName" ) + else if ( childElem.tagName() != QLatin1String( "PropertyName" ) ) { QgsGeometry geom = QgsOgcUtils::geometryFromGML( childElem ); req.setFilterRect( geom.boundingBox() ); @@ -1089,7 +1089,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format { if ( filter->hasParserError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", QString( "OGC expression filter error message: %1." ).arg( filter->parserErrorString() ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "OGC expression filter error message: %1." ).arg( filter->parserErrorString() ) ); } QgsFeatureRequest req; if ( layer->wkbType() != QgsWkbTypes::NoGeometry ) @@ -1116,7 +1116,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QVariant res = filter->evaluate( &expressionContext ); if ( filter->hasEvalError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", QString( "OGC expression filter eval error message: %1." ).arg( filter->evalErrorString() ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "OGC expression filter eval error message: %1." ).arg( filter->evalErrorString() ) ); } if ( res.toInt() != 0 ) { @@ -1158,7 +1158,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format QgsFeatureIterator fit = layer->getFeatures( req ); while ( fit.nextFeature( feature ) && ( !hasFeatureLimit || featureCounter < maxFeatures + startIndex ) ) { - mErrors << QString( "The feature %2 of layer for the TypeName '%1'" ).arg( tnStr ).arg( featureCounter ); + mErrors << QStringLiteral( "The feature %2 of layer for the TypeName '%1'" ).arg( tnStr ).arg( featureCounter ); if ( featureCounter == startIndex ) startGetFeature( request, format, layerPrec, layerCrs, &searchRect ); @@ -1174,7 +1174,7 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format } else { - mErrors << QString( "The layer for the TypeName '%1' is not a WFS layer" ).arg( tnStr ); + mErrors << QStringLiteral( "The layer for the TypeName '%1' is not a WFS layer" ).arg( tnStr ); } } @@ -1191,11 +1191,11 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f { QByteArray result; QString fcString; - if ( format == "GeoJSON" ) + if ( format == QLatin1String( "GeoJSON" ) ) { - fcString = "{\"type\": \"FeatureCollection\",\n"; + fcString = QStringLiteral( "{\"type\": \"FeatureCollection\",\n" ); fcString += " \"bbox\": [ " + qgsDoubleToString( rect->xMinimum(), prec ) + ", " + qgsDoubleToString( rect->yMinimum(), prec ) + ", " + qgsDoubleToString( rect->xMaximum(), prec ) + ", " + qgsDoubleToString( rect->yMaximum(), prec ) + "],\n"; - fcString += " \"features\": [\n"; + fcString += QLatin1String( " \"features\": [\n" ); result = fcString.toUtf8(); request.startGetFeatureResponse( &result, format ); } @@ -1212,91 +1212,91 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f hrefString = serviceUrl(); } QUrl mapUrl( hrefString ); - mapUrl.addQueryItem( "SERVICE", "WFS" ); - mapUrl.addQueryItem( "VERSION", "1.0.0" ); + mapUrl.addQueryItem( QStringLiteral( "SERVICE" ), QStringLiteral( "WFS" ) ); + mapUrl.addQueryItem( QStringLiteral( "VERSION" ), QStringLiteral( "1.0.0" ) ); QList > queryItems = mapUrl.queryItems(); QList >::const_iterator queryIt = queryItems.constBegin(); for ( ; queryIt != queryItems.constEnd(); ++queryIt ) { - if ( queryIt->first.compare( "REQUEST", Qt::CaseInsensitive ) == 0 ) + if ( queryIt->first.compare( QLatin1String( "REQUEST" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "FORMAT", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "FORMAT" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "OUTPUTFORMAT", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "OUTPUTFORMAT" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "BBOX", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "BBOX" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "FEATUREID", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "FEATUREID" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "TYPENAME", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "TYPENAME" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "FILTER", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "FILTER" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "EXP_FILTER", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "EXP_FILTER" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "MAXFEATURES", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "MAXFEATURES" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "STARTINDEX", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "STARTINDEX" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "PROPERTYNAME", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "PROPERTYNAME" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "_DC", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "_DC" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } } - mapUrl.addQueryItem( "REQUEST", "DescribeFeatureType" ); - mapUrl.addQueryItem( "TYPENAME", mTypeNames.join( "," ) ); - mapUrl.addQueryItem( "OUTPUTFORMAT", "XMLSCHEMA" ); + mapUrl.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "DescribeFeatureType" ) ); + mapUrl.addQueryItem( QStringLiteral( "TYPENAME" ), mTypeNames.join( QStringLiteral( "," ) ) ); + mapUrl.addQueryItem( QStringLiteral( "OUTPUTFORMAT" ), QStringLiteral( "XMLSCHEMA" ) ); hrefString = mapUrl.toString(); //wfs:FeatureCollection valid - fcString = "" ); result = fcString.toUtf8(); request.startGetFeatureResponse( &result, format ); QDomDocument doc; - QDomElement bbElem = doc.createElement( "gml:boundedBy" ); - if ( format == "GML3" ) + QDomElement bbElem = doc.createElement( QStringLiteral( "gml:boundedBy" ) ); + if ( format == QLatin1String( "GML3" ) ) { QDomElement envElem = QgsOgcUtils::rectangleToGMLEnvelope( rect, doc, prec ); if ( !envElem.isNull() ) { if ( crs.isValid() ) { - envElem.setAttribute( "srsName", crs.authid() ); + envElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } bbElem.appendChild( envElem ); doc.appendChild( bbElem ); @@ -1309,7 +1309,7 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f { if ( crs.isValid() ) { - boxElem.setAttribute( "srsName", crs.authid() ); + boxElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } bbElem.appendChild( boxElem ); doc.appendChild( bbElem ); @@ -1318,7 +1318,7 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f result = doc.toByteArray(); request.setGetFeatureResponse( &result ); } - fcString = ""; + fcString = QLatin1String( "" ); } void QgsWfsServer::setGetFeature( QgsRequestHandler& request, const QString& format, QgsFeature* feat, int featIdx, int prec, QgsCoordinateReferenceSystem& crs, const QgsAttributeList& attrIndexes, const QSet& excludedAttributes ) /*const*/ @@ -1327,25 +1327,25 @@ void QgsWfsServer::setGetFeature( QgsRequestHandler& request, const QString& for return; QByteArray result; - if ( format == "GeoJSON" ) + if ( format == QLatin1String( "GeoJSON" ) ) { QString fcString; if ( featIdx == 0 ) - fcString += " "; + fcString += QLatin1String( " " ); else - fcString += " ,"; + fcString += QLatin1String( " ," ); fcString += createFeatureGeoJSON( feat, prec, crs, attrIndexes, excludedAttributes ); - fcString += "\n"; + fcString += QLatin1String( "\n" ); result = fcString.toUtf8(); request.setGetFeatureResponse( &result ); - fcString = ""; + fcString = QLatin1String( "" ); } else { QDomDocument gmlDoc; QDomElement featureElement; - if ( format == "GML3" ) + if ( format == QLatin1String( "GML3" ) ) { featureElement = createFeatureGML3( feat, gmlDoc, prec, crs, attrIndexes, excludedAttributes ); gmlDoc.appendChild( featureElement ); @@ -1366,21 +1366,21 @@ void QgsWfsServer::endGetFeature( QgsRequestHandler& request, const QString& for { QByteArray result; QString fcString; - if ( format == "GeoJSON" ) + if ( format == QLatin1String( "GeoJSON" ) ) { - fcString += " ]\n"; - fcString += "}"; + fcString += QLatin1String( " ]\n" ); + fcString += QLatin1String( "}" ); result = fcString.toUtf8(); request.endGetFeatureResponse( &result ); - fcString = ""; + fcString = QLatin1String( "" ); } else { - fcString = "\n"; + fcString = QStringLiteral( "\n" ); result = fcString.toUtf8(); request.endGetFeatureResponse( &result ); - fcString = ""; + fcString = QLatin1String( "" ); } } @@ -1392,7 +1392,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) QString errorMsg; if ( !doc.setContent( requestBody, true, &errorMsg ) ) { - throw QgsMapServiceException( "RequestNotWellFormed", errorMsg ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), errorMsg ); } QDomElement docElem = doc.documentElement(); @@ -1400,13 +1400,13 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) // Re-organize the transaction document QDomDocument mDoc; - QDomElement mDocElem = mDoc.createElement( "myTransactionDocument" ); - mDocElem.setAttribute( "xmlns", QGS_NAMESPACE ); - mDocElem.setAttribute( "xmlns:wfs", WFS_NAMESPACE ); - mDocElem.setAttribute( "xmlns:gml", GML_NAMESPACE ); - mDocElem.setAttribute( "xmlns:ogc", OGC_NAMESPACE ); - mDocElem.setAttribute( "xmlns:qgs", QGS_NAMESPACE ); - mDocElem.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) ); + mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE ); + mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE ); + mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE ); + mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE ); + mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE ); + mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); mDoc.appendChild( mDocElem ); QDomElement actionElem; @@ -1419,22 +1419,22 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) actionElem = docChildNodes.at( i - 1 ).toElement(); actionName = actionElem.localName(); - if ( actionName == "Insert" ) + if ( actionName == QLatin1String( "Insert" ) ) { QDomElement featureElem = actionElem.firstChild().toElement(); typeName = featureElem.localName(); } - else if ( actionName == "Update" ) + else if ( actionName == QLatin1String( "Update" ) ) { - typeName = actionElem.attribute( "typeName" ); + typeName = actionElem.attribute( QStringLiteral( "typeName" ) ); } - else if ( actionName == "Delete" ) + else if ( actionName == QLatin1String( "Delete" ) ) { - typeName = actionElem.attribute( "typeName" ); + typeName = actionElem.attribute( QStringLiteral( "typeName" ) ); } - if ( typeName.contains( ":" ) ) - typeName = typeName.section( ":", 1, 1 ); + if ( typeName.contains( QLatin1String( ":" ) ) ) + typeName = typeName.section( QStringLiteral( ":" ), 1, 1 ); QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName ); if ( typeNameList.count() == 0 ) @@ -1452,12 +1452,12 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) // Create the response document QDomDocument resp; //wfs:WFS_TransactionRespone element - QDomElement respElem = resp.createElement( "WFS_TransactionResponse"/*wfs:WFS_TransactionResponse*/ ); - respElem.setAttribute( "xmlns", WFS_NAMESPACE ); - respElem.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - respElem.setAttribute( "xsi:schemaLocation", WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" ); - respElem.setAttribute( "xmlns:ogc", OGC_NAMESPACE ); - respElem.setAttribute( "version", "1.0.0" ); + QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ ); + respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE ); + respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" ); + respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE ); + respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) ); resp.appendChild( respElem ); // Store the created feature id for WFS @@ -1484,7 +1484,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) } else { - throw QgsMapServiceException( "RequestNotWellFormed", QString( "Wrong TypeName: %1" ).arg( mTypeName ) ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "Wrong TypeName: %1" ).arg( mTypeName ) ); } QgsVectorLayer* layer = qobject_cast( currentLayer ); @@ -1492,25 +1492,25 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) if ( layer && wfsLayersId.contains( layer->id() ) ) { #ifdef HAVE_SERVER_PYTHON_PLUGINS - if ( actionName == "Insert" ) + if ( actionName == QLatin1String( "Insert" ) ) { if ( !mAccessControl->layerInsertPermission( layer ) ) { - throw QgsMapServiceException( "Security", "Feature insert permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature insert permission denied" ) ); } } - else if ( actionName == "Update" ) + else if ( actionName == QLatin1String( "Update" ) ) { if ( !mAccessControl->layerUpdatePermission( layer ) ) { - throw QgsMapServiceException( "Security", "Feature update permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature update permission denied" ) ); } } - else if ( actionName == "Delete" ) + else if ( actionName == QLatin1String( "Delete" ) ) { if ( !mAccessControl->layerDeletePermission( layer ) ) { - throw QgsMapServiceException( "Security", "Feature delete permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature delete permission denied" ) ); } } #endif @@ -1529,27 +1529,27 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) ) { // Loop through the update elements for this layer - QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, "Update" ); + QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) ); for ( int j = 0; j < upNodeList.count(); ++j ) { if ( !mConfigParser->wfstUpdateLayers().contains( layer->id() ) ) { //no wfs permissions to do updates QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'"; - QgsMessageLog::logMessage( errorMsg, "Server", QgsMessageLog::CRITICAL ); - addTransactionResult( resp, respElem, "FAILED", "Update", errorMsg ); + QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); + addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg ); return resp; } actionElem = upNodeList.at( j ).toElement(); // Get the Feature Ids for this filter on the layer - QDomElement filterElem = actionElem.elementsByTagName( "Filter" ).at( 0 ).toElement(); + QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement(); QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer ); // Loop through the property elements // Store properties and the geometry element - QDomNodeList propertyNodeList = actionElem.elementsByTagName( "Property" ); + QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) ); QMap propertyMap; QDomElement propertyElem; QDomElement nameElem; @@ -1559,9 +1559,9 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) for ( int l = 0; l < propertyNodeList.count(); ++l ) { propertyElem = propertyNodeList.at( l ).toElement(); - nameElem = propertyElem.elementsByTagName( "Name" ).at( 0 ).toElement(); - valueElem = propertyElem.elementsByTagName( "Value" ).at( 0 ).toElement(); - if ( nameElem.text() != "geometry" ) + nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement(); + valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement(); + if ( nameElem.text() != QLatin1String( "geometry" ) ) { propertyMap.insert( nameElem.text(), valueElem.text() ); } @@ -1588,7 +1588,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) { if ( !mAccessControl->allowToEdit( layer, feature ) ) { - throw QgsMapServiceException( "Security", "Feature modify permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature modify permission denied" ) ); } } #endif @@ -1616,7 +1616,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem ); if ( !layer->changeGeometry( *fidIt, g ) ) { - throw QgsMapServiceException( "RequestNotWellFormed", "Error in change geometry" ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), QStringLiteral( "Error in change geometry" ) ); } } @@ -1627,7 +1627,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) if ( !mAccessControl->allowToEdit( layer, feature ) ) { layer->rollBack(); - throw QgsMapServiceException( "Security", "Feature modify permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature modify permission denied" ) ); } } #endif @@ -1637,7 +1637,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) // Commit the changes of the update elements if ( !layer->commitChanges() ) { - addTransactionResult( resp, respElem, "PARTIAL", "Update", layer->commitErrors().join( "\n " ) ); + addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n " ) ) ); return resp; } // Start the delete transaction @@ -1645,15 +1645,15 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) if (( cap & QgsVectorDataProvider::DeleteFeatures ) ) { // Loop through the delete elements - QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, "Delete" ); + QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) ); for ( int j = 0; j < delNodeList.count(); ++j ) { if ( !mConfigParser->wfstDeleteLayers().contains( layer->id() ) ) { //no wfs permissions to do updates QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'"; - QgsMessageLog::logMessage( errorMsg, "Server", QgsMessageLog::CRITICAL ); - addTransactionResult( resp, respElem, "FAILED", "Delete", errorMsg ); + QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); + addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg ); return resp; } @@ -1672,7 +1672,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) { if ( !mAccessControl->allowToEdit( layer, feature ) ) { - throw QgsMapServiceException( "Security", "Feature modify permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature modify permission denied" ) ); } } } @@ -1685,7 +1685,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) // Commit the changes of the delete elements if ( !layer->commitChanges() ) { - addTransactionResult( resp, respElem, "PARTIAL", "Delete", layer->commitErrors().join( "\n " ) ); + addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n " ) ) ); return resp; } @@ -1699,15 +1699,15 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) QMap::const_iterator fieldMapIt; // Loop through the insert elements - QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, "Insert" ); + QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) ); for ( int j = 0; j < inNodeList.count(); ++j ) { if ( !mConfigParser->wfstInsertLayers().contains( layer->id() ) ) { //no wfs permissions to do updates QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'"; - QgsMessageLog::logMessage( errorMsg, "Server", QgsMessageLog::CRITICAL ); - addTransactionResult( resp, respElem, "FAILED", "Insert", errorMsg ); + QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); + addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg ); return resp; } @@ -1730,9 +1730,9 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) QDomElement currentAttributeElement = currentAttributeChild.toElement(); QString attrName = currentAttributeElement.localName(); - if ( attrName != "boundedBy" ) + if ( attrName != QLatin1String( "boundedBy" ) ) { - if ( attrName != "geometry" ) //a normal attribute + if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute { fieldMapIt = fieldMap.find( attrName ); if ( fieldMapIt == fieldMap.constEnd() ) @@ -1742,7 +1742,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) QgsField field = fields.at( fieldMapIt.value() ); QString attrValue = currentAttributeElement.text(); int attrType = field.type(); - QgsMessageLog::logMessage( QString( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) ); + QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) ); if ( attrType == QVariant::Int ) inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() ); else if ( attrType == QVariant::Double ) @@ -1767,7 +1767,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) { if ( !mAccessControl->allowToEdit( layer, *featureIt ) ) { - throw QgsMapServiceException( "Security", "Feature modify permission denied" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "Feature modify permission denied" ) ); } featureIt++; } @@ -1776,7 +1776,7 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) // add the features if ( !provider->addFeatures( inFeatList ) ) { - addTransactionResult( resp, respElem, "Partial", "Insert", layer->commitErrors().join( "\n " ) ); + addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n " ) ) ); if ( provider->hasErrors() ) { provider->clearErrors(); @@ -1796,18 +1796,18 @@ QDomDocument QgsWfsServer::transaction( const QString& requestBody ) { Q_FOREACH ( const QString &fidStr, insertResults ) { - QDomElement irElem = doc.createElement( "InsertResult" ); - QDomElement fiElem = doc.createElement( "ogc:FeatureId" ); - fiElem.setAttribute( "fid", fidStr ); + QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) ); + QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) ); + fiElem.setAttribute( QStringLiteral( "fid" ), fidStr ); irElem.appendChild( fiElem ); respElem.appendChild( irElem ); } } // Set the transaction reposne for success - QDomElement trElem = doc.createElement( "TransactionResult" ); - QDomElement stElem = doc.createElement( "Status" ); - QDomElement successElem = doc.createElement( "SUCCESS" ); + QDomElement trElem = doc.createElement( QStringLiteral( "TransactionResult" ) ); + QDomElement stElem = doc.createElement( QStringLiteral( "Status" ) ); + QDomElement successElem = doc.createElement( QStringLiteral( "SUCCESS" ) ); stElem.appendChild( successElem ); trElem.appendChild( stElem ); respElem.appendChild( trElem ); @@ -1820,7 +1820,7 @@ QgsFeatureIds QgsWfsServer::getFeatureIdsFromFilter( const QDomElement& filterEl QgsFeatureIds fids; QgsVectorDataProvider *provider = layer->dataProvider(); - QDomNodeList fidNodes = filterElem.elementsByTagName( "FeatureId" ); + QDomNodeList fidNodes = filterElem.elementsByTagName( QStringLiteral( "FeatureId" ) ); if ( fidNodes.size() != 0 ) { @@ -1830,9 +1830,9 @@ QgsFeatureIds QgsWfsServer::getFeatureIdsFromFilter( const QDomElement& filterEl for ( int i = 0; i < fidNodes.size(); ++i ) { fidElem = fidNodes.at( i ).toElement(); - fid = fidElem.attribute( "fid" ); - if ( fid.contains( "." ) ) - fid = fid.section( ".", 1, 1 ); + fid = fidElem.attribute( QStringLiteral( "fid" ) ); + if ( fid.contains( QLatin1String( "." ) ) ) + fid = fid.section( QStringLiteral( "." ), 1, 1 ); fids.insert( fid.toLongLong( &conversionSuccess ) ); } } @@ -1843,7 +1843,7 @@ QgsFeatureIds QgsWfsServer::getFeatureIdsFromFilter( const QDomElement& filterEl { if ( filter->hasParserError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", filter->parserErrorString() ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), filter->parserErrorString() ); } QgsFeature feature; QgsFields fields = provider->fields(); @@ -1856,7 +1856,7 @@ QgsFeatureIds QgsWfsServer::getFeatureIdsFromFilter( const QDomElement& filterEl QVariant res = filter->evaluate( &context ); if ( filter->hasEvalError() ) { - throw QgsMapServiceException( "RequestNotWellFormed", filter->evalErrorString() ); + throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), filter->evalErrorString() ); } if ( res.toInt() != 0 ) { @@ -1871,7 +1871,7 @@ QgsFeatureIds QgsWfsServer::getFeatureIdsFromFilter( const QDomElement& filterEl QString QgsWfsServer::createFeatureGeoJSON( QgsFeature* feat, int prec, QgsCoordinateReferenceSystem& crs, const QgsAttributeList& attrIndexes, const QSet& excludedAttributes ) /*const*/ { - QString id = QString( "%1.%2" ).arg( mTypeName, FID_TO_STRING( feat->id() ) ); + QString id = QStringLiteral( "%1.%2" ).arg( mTypeName, FID_TO_STRING( feat->id() ) ); QgsJSONExporter exporter; exporter.setSourceCrs( crs ); @@ -1881,15 +1881,15 @@ QString QgsWfsServer::createFeatureGeoJSON( QgsFeature* feat, int prec, QgsCoord QgsFeature f( *feat ); QgsGeometry geom = feat->geometry(); exporter.setIncludeGeometry( false ); - if ( !geom.isEmpty() && mWithGeom && mGeometryName != "NONE" ) + if ( !geom.isEmpty() && mWithGeom && mGeometryName != QLatin1String( "NONE" ) ) { exporter.setIncludeGeometry( true ); - if ( mGeometryName == "EXTENT" ) + if ( mGeometryName == QLatin1String( "EXTENT" ) ) { QgsRectangle box = geom.boundingBox(); f.setGeometry( QgsGeometry::fromRect( box ) ); } - else if ( mGeometryName == "CENTROID" ) + else if ( mGeometryName == QLatin1String( "CENTROID" ) ) { f.setGeometry( geom.centroid() ); } @@ -1923,26 +1923,26 @@ QString QgsWfsServer::createFeatureGeoJSON( QgsFeature* feat, int prec, QgsCoord QDomElement QgsWfsServer::createFeatureGML2( QgsFeature* feat, QDomDocument& doc, int prec, QgsCoordinateReferenceSystem& crs, const QgsAttributeList& attrIndexes, const QSet& excludedAttributes ) /*const*/ { //gml:FeatureMember - QDomElement featureElement = doc.createElement( "gml:featureMember"/*wfs:FeatureMember*/ ); + QDomElement featureElement = doc.createElement( QStringLiteral( "gml:featureMember" )/*wfs:FeatureMember*/ ); //qgs:%TYPENAME% QDomElement typeNameElement = doc.createElement( "qgs:" + mTypeName /*qgs:%TYPENAME%*/ ); - typeNameElement.setAttribute( "fid", mTypeName + "." + QString::number( feat->id() ) ); + typeNameElement.setAttribute( QStringLiteral( "fid" ), mTypeName + "." + QString::number( feat->id() ) ); featureElement.appendChild( typeNameElement ); - if ( mWithGeom && mGeometryName != "NONE" ) + if ( mWithGeom && mGeometryName != QLatin1String( "NONE" ) ) { //add geometry column (as gml) QgsGeometry geom = feat->geometry(); - QDomElement geomElem = doc.createElement( "qgs:geometry" ); + QDomElement geomElem = doc.createElement( QStringLiteral( "qgs:geometry" ) ); QDomElement gmlElem; - if ( mGeometryName == "EXTENT" ) + if ( mGeometryName == QLatin1String( "EXTENT" ) ) { QgsGeometry bbox = QgsGeometry::fromRect( geom.boundingBox() ); gmlElem = QgsOgcUtils::geometryToGML( &bbox , doc, prec ); } - else if ( mGeometryName == "CENTROID" ) + else if ( mGeometryName == QLatin1String( "CENTROID" ) ) { QgsGeometry centroid = geom.centroid(); gmlElem = QgsOgcUtils::geometryToGML( ¢roid, doc, prec ); @@ -1952,13 +1952,13 @@ QDomElement QgsWfsServer::createFeatureGML2( QgsFeature* feat, QDomDocument& doc if ( !gmlElem.isNull() ) { QgsRectangle box = geom.boundingBox(); - QDomElement bbElem = doc.createElement( "gml:boundedBy" ); + QDomElement bbElem = doc.createElement( QStringLiteral( "gml:boundedBy" ) ); QDomElement boxElem = QgsOgcUtils::rectangleToGMLBox( &box, doc, prec ); if ( crs.isValid() ) { - boxElem.setAttribute( "srsName", crs.authid() ); - gmlElem.setAttribute( "srsName", crs.authid() ); + boxElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); + gmlElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } bbElem.appendChild( boxElem ); @@ -1986,7 +1986,7 @@ QDomElement QgsWfsServer::createFeatureGML2( QgsFeature* feat, QDomDocument& doc continue; } - QDomElement fieldElem = doc.createElement( "qgs:" + attributeName.replace( QString( " " ), QString( "_" ) ) ); + QDomElement fieldElem = doc.createElement( "qgs:" + attributeName.replace( QStringLiteral( " " ), QStringLiteral( "_" ) ) ); QDomText fieldText = doc.createTextNode( featureAttributes[idx].toString() ); fieldElem.appendChild( fieldText ); typeNameElement.appendChild( fieldElem ); @@ -1998,42 +1998,42 @@ QDomElement QgsWfsServer::createFeatureGML2( QgsFeature* feat, QDomDocument& doc QDomElement QgsWfsServer::createFeatureGML3( QgsFeature* feat, QDomDocument& doc, int prec, QgsCoordinateReferenceSystem& crs, const QgsAttributeList& attrIndexes, const QSet& excludedAttributes ) /*const*/ { //gml:FeatureMember - QDomElement featureElement = doc.createElement( "gml:featureMember"/*wfs:FeatureMember*/ ); + QDomElement featureElement = doc.createElement( QStringLiteral( "gml:featureMember" )/*wfs:FeatureMember*/ ); //qgs:%TYPENAME% QDomElement typeNameElement = doc.createElement( "qgs:" + mTypeName /*qgs:%TYPENAME%*/ ); - typeNameElement.setAttribute( "gml:id", mTypeName + "." + QString::number( feat->id() ) ); + typeNameElement.setAttribute( QStringLiteral( "gml:id" ), mTypeName + "." + QString::number( feat->id() ) ); featureElement.appendChild( typeNameElement ); - if ( mWithGeom && mGeometryName != "NONE" ) + if ( mWithGeom && mGeometryName != QLatin1String( "NONE" ) ) { //add geometry column (as gml) QgsGeometry geom = feat->geometry(); - QDomElement geomElem = doc.createElement( "qgs:geometry" ); + QDomElement geomElem = doc.createElement( QStringLiteral( "qgs:geometry" ) ); QDomElement gmlElem; - if ( mGeometryName == "EXTENT" ) + if ( mGeometryName == QLatin1String( "EXTENT" ) ) { QgsGeometry bbox = QgsGeometry::fromRect( geom.boundingBox() ); - gmlElem = QgsOgcUtils::geometryToGML( &bbox, doc, "GML3", prec ); + gmlElem = QgsOgcUtils::geometryToGML( &bbox, doc, QStringLiteral( "GML3" ), prec ); } - else if ( mGeometryName == "CENTROID" ) + else if ( mGeometryName == QLatin1String( "CENTROID" ) ) { QgsGeometry centroid = geom.centroid(); - gmlElem = QgsOgcUtils::geometryToGML( ¢roid, doc, "GML3", prec ); + gmlElem = QgsOgcUtils::geometryToGML( ¢roid, doc, QStringLiteral( "GML3" ), prec ); } else - gmlElem = QgsOgcUtils::geometryToGML( &geom, doc, "GML3", prec ); + gmlElem = QgsOgcUtils::geometryToGML( &geom, doc, QStringLiteral( "GML3" ), prec ); if ( !gmlElem.isNull() ) { QgsRectangle box = geom.boundingBox(); - QDomElement bbElem = doc.createElement( "gml:boundedBy" ); + QDomElement bbElem = doc.createElement( QStringLiteral( "gml:boundedBy" ) ); QDomElement boxElem = QgsOgcUtils::rectangleToGMLEnvelope( &box, doc, prec ); if ( crs.isValid() ) { - boxElem.setAttribute( "srsName", crs.authid() ); - gmlElem.setAttribute( "srsName", crs.authid() ); + boxElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); + gmlElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } bbElem.appendChild( boxElem ); @@ -2061,7 +2061,7 @@ QDomElement QgsWfsServer::createFeatureGML3( QgsFeature* feat, QDomDocument& doc continue; } - QDomElement fieldElem = doc.createElement( "qgs:" + attributeName.replace( QString( " " ), QString( "_" ) ) ); + QDomElement fieldElem = doc.createElement( "qgs:" + attributeName.replace( QStringLiteral( " " ), QStringLiteral( "_" ) ) ); QDomText fieldText = doc.createTextNode( featureAttributes[idx].toString() ); fieldElem.appendChild( fieldText ); typeNameElement.appendChild( fieldElem ); @@ -2090,32 +2090,32 @@ QString QgsWfsServer::serviceUrl() const } } - if ( QString( getenv( "HTTPS" ) ).compare( "on", Qt::CaseInsensitive ) == 0 ) + if ( QString( getenv( "HTTPS" ) ).compare( QLatin1String( "on" ), Qt::CaseInsensitive ) == 0 ) { - mapUrl.setScheme( "https" ); + mapUrl.setScheme( QStringLiteral( "https" ) ); } else { - mapUrl.setScheme( "http" ); + mapUrl.setScheme( QStringLiteral( "http" ) ); } QList > queryItems = mapUrl.queryItems(); QList >::const_iterator queryIt = queryItems.constBegin(); for ( ; queryIt != queryItems.constEnd(); ++queryIt ) { - if ( queryIt->first.compare( "REQUEST", Qt::CaseInsensitive ) == 0 ) + if ( queryIt->first.compare( QLatin1String( "REQUEST" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "VERSION", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "VERSION" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "SERVICE", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "SERVICE" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "_DC", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "_DC" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } @@ -2125,18 +2125,18 @@ QString QgsWfsServer::serviceUrl() const void QgsWfsServer::addTransactionResult( QDomDocument& responseDoc, QDomElement& responseElem, const QString& status, const QString& locator, const QString& message ) { - QDomElement trElem = responseDoc.createElement( "TransactionResult" ); - QDomElement stElem = responseDoc.createElement( "Status" ); + QDomElement trElem = responseDoc.createElement( QStringLiteral( "TransactionResult" ) ); + QDomElement stElem = responseDoc.createElement( QStringLiteral( "Status" ) ); QDomElement successElem = responseDoc.createElement( status ); stElem.appendChild( successElem ); trElem.appendChild( stElem ); responseElem.appendChild( trElem ); - QDomElement locElem = responseDoc.createElement( "Locator" ); + QDomElement locElem = responseDoc.createElement( QStringLiteral( "Locator" ) ); locElem.appendChild( responseDoc.createTextNode( locator ) ); trElem.appendChild( locElem ); - QDomElement mesElem = responseDoc.createElement( "Message" ); + QDomElement mesElem = responseDoc.createElement( QStringLiteral( "Message" ) ); mesElem.appendChild( responseDoc.createTextNode( message ) ); trElem.appendChild( mesElem ); } diff --git a/src/server/qgswmsconfigparser.cpp b/src/server/qgswmsconfigparser.cpp index 8cf99e92de13..50b4d40aefc5 100644 --- a/src/server/qgswmsconfigparser.cpp +++ b/src/server/qgswmsconfigparser.cpp @@ -64,7 +64,7 @@ QgsComposition* QgsWmsConfigParser::createPrintComposition( const QString& compo return nullptr; } - QString dpi = parameterMap.value( "DPI" ); + QString dpi = parameterMap.value( QStringLiteral( "DPI" ) ); if ( !dpi.isEmpty() ) { c->setPrintResolution( dpi.toInt() ); @@ -89,7 +89,7 @@ QgsComposition* QgsWmsConfigParser::createPrintComposition( const QString& compo continue; } - QStringList coordList = extent.split( "," ); + QStringList coordList = extent.split( QStringLiteral( "," ) ); if ( coordList.size() < 4 ) { c->removeItem( currentMap ); @@ -112,8 +112,8 @@ QgsComposition* QgsWmsConfigParser::createPrintComposition( const QString& compo QgsRectangle r( xmin, ymin, xmax, ymax ); //Change x- and y- of extent for WMS 1.3.0 if axis inverted - QString version = parameterMap.value( "VERSION" ); - if ( version == "1.3.0" && mapRenderer && mapRenderer->destinationCrs().hasAxisInverted() ) + QString version = parameterMap.value( QStringLiteral( "VERSION" ) ); + if ( version == QLatin1String( "1.3.0" ) && mapRenderer && mapRenderer->destinationCrs().hasAxisInverted() ) { r.invert(); } @@ -157,16 +157,16 @@ QgsComposition* QgsWmsConfigParser::createPrintComposition( const QString& compo if ( layers.isEmpty() ) { - layers = parameterMap.value( "LAYERS" ); - styles = parameterMap.value( "STYLES" ); + layers = parameterMap.value( QStringLiteral( "LAYERS" ) ); + styles = parameterMap.value( QStringLiteral( "STYLES" ) ); } - QStringList wmsLayerList = layers.split( "," ); + QStringList wmsLayerList = layers.split( QStringLiteral( "," ) ); QStringList wmsStyleList; if ( !styles.isEmpty() ) { - wmsStyleList = styles.split( "," ); + wmsStyleList = styles.split( QStringLiteral( "," ) ); } for ( int i = 0; i < wmsLayerList.size(); ++i ) @@ -301,7 +301,7 @@ QStringList QgsWmsConfigParser::addHighlightLayers( const QMap return highlightLayers; } - QString crsString = parameterMap.contains( "CRS" ) ? parameterMap.value( "CRS" ) : parameterMap.value( "SRS" ); + QString crsString = parameterMap.contains( QStringLiteral( "CRS" ) ) ? parameterMap.value( QStringLiteral( "CRS" ) ) : parameterMap.value( QStringLiteral( "SRS" ) ); int nHighlights = qMin( geomSplit.size(), symbolSplit.size() ); for ( int i = 0; i < nHighlights; ++i ) @@ -359,18 +359,18 @@ QgsVectorLayer* QgsWmsConfigParser::createHighlightLayer( int i, const QString& } QgsWkbTypes::GeometryType geomType = geom->type(); - QString typeName = QString( QgsWkbTypes::displayString( geom->wkbType() ) ).replace( "WKB", "" ); + QString typeName = QString( QgsWkbTypes::displayString( geom->wkbType() ) ).replace( QLatin1String( "WKB" ), QLatin1String( "" ) ); QString url = typeName + "?crs=" + crsString; if ( !labelString.isEmpty() ) { - url += "&field=label:string"; + url += QLatin1String( "&field=label:string" ); if ( geomType == QgsWkbTypes::PolygonGeometry ) { - url += "&field=x:double&field=y:double&field=hali:string&field=vali:string"; + url += QLatin1String( "&field=x:double&field=y:double&field=hali:string&field=vali:string" ); } } - QgsVectorLayer* layer = new QgsVectorLayer( url, "highlight_" + QString::number( i ), "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( url, "highlight_" + QString::number( i ), QStringLiteral( "memory" ) ); if ( !layer->isValid() ) { delete layer; @@ -394,51 +394,51 @@ QgsVectorLayer* QgsWmsConfigParser::createHighlightLayer( int i, const QString& } } - layer->setCustomProperty( "labeling/fieldName", "label" ); - layer->setCustomProperty( "labeling/enabled", "true" ); - layer->setCustomProperty( "labeling", "pal" ); + layer->setCustomProperty( QStringLiteral( "labeling/fieldName" ), "label" ); + layer->setCustomProperty( QStringLiteral( "labeling/enabled" ), "true" ); + layer->setCustomProperty( QStringLiteral( "labeling" ), "pal" ); //give highest priority to highlight layers and make sure the labels are always drawn - layer->setCustomProperty( "labeling/priority", "10" ); - layer->setCustomProperty( "labeling/displayAll", "true" ); + layer->setCustomProperty( QStringLiteral( "labeling/priority" ), "10" ); + layer->setCustomProperty( QStringLiteral( "labeling/displayAll" ), "true" ); //fontsize? if ( i < labelSizeSplit.size() ) { - layer->setCustomProperty( "labeling/fontSize", labelSizeSplit.at( i ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontSize" ), labelSizeSplit.at( i ) ); } //font color if ( i < labelColorSplit.size() ) { QColor c( labelColorSplit.at( i ) ); - layer->setCustomProperty( "labeling/textColorR", c.red() ); - layer->setCustomProperty( "labeling/textColorG", c.green() ); - layer->setCustomProperty( "labeling/textColorB", c.blue() ); + layer->setCustomProperty( QStringLiteral( "labeling/textColorR" ), c.red() ); + layer->setCustomProperty( QStringLiteral( "labeling/textColorG" ), c.green() ); + layer->setCustomProperty( QStringLiteral( "labeling/textColorB" ), c.blue() ); } //font weight if ( i < labelWeightSplit.size() ) { - layer->setCustomProperty( "labeling/fontWeight", labelWeightSplit.at( i ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontWeight" ), labelWeightSplit.at( i ) ); } //font family list if ( i < labelFontSplit.size() ) { - layer->setCustomProperty( "labeling/fontFamily", labelFontSplit.at( i ) ); + layer->setCustomProperty( QStringLiteral( "labeling/fontFamily" ), labelFontSplit.at( i ) ); } //buffer if ( i < labelBufferSizeSplit.size() ) { - layer->setCustomProperty( "labeling/bufferSize", labelBufferSizeSplit.at( i ) ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferSize" ), labelBufferSizeSplit.at( i ) ); } //buffer color if ( i < labelBufferColorSplit.size() ) { QColor c( labelBufferColorSplit.at( i ) ); - layer->setCustomProperty( "labeling/bufferColorR", c.red() ); - layer->setCustomProperty( "labeling/bufferColorG", c.green() ); - layer->setCustomProperty( "labeling/bufferColorB", c.blue() ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferColorR" ), c.red() ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferColorG" ), c.green() ); + layer->setCustomProperty( QStringLiteral( "labeling/bufferColorB" ), c.blue() ); } //placement @@ -447,21 +447,21 @@ QgsVectorLayer* QgsWmsConfigParser::createHighlightLayer( int i, const QString& { case QgsWkbTypes::PointGeometry: placement = 0; - layer->setCustomProperty( "labeling/dist", 2 ); - layer->setCustomProperty( "labeling/placementFlags", 0 ); + layer->setCustomProperty( QStringLiteral( "labeling/dist" ), 2 ); + layer->setCustomProperty( QStringLiteral( "labeling/placementFlags" ), 0 ); break; case QgsWkbTypes::PolygonGeometry: - layer->setCustomProperty( "labeling/dataDefinedProperty9", 1 ); - layer->setCustomProperty( "labeling/dataDefinedProperty10", 2 ); - layer->setCustomProperty( "labeling/dataDefinedProperty11", 3 ); - layer->setCustomProperty( "labeling/dataDefinedProperty12", 4 ); + layer->setCustomProperty( QStringLiteral( "labeling/dataDefinedProperty9" ), 1 ); + layer->setCustomProperty( QStringLiteral( "labeling/dataDefinedProperty10" ), 2 ); + layer->setCustomProperty( QStringLiteral( "labeling/dataDefinedProperty11" ), 3 ); + layer->setCustomProperty( QStringLiteral( "labeling/dataDefinedProperty12" ), 4 ); break; default: placement = 2; //parallel placement for line - layer->setCustomProperty( "labeling/dist", 2 ); - layer->setCustomProperty( "labeling/placementFlags", 10 ); + layer->setCustomProperty( QStringLiteral( "labeling/dist" ), 2 ); + layer->setCustomProperty( QStringLiteral( "labeling/placementFlags" ), 10 ); } - layer->setCustomProperty( "labeling/placement", placement ); + layer->setCustomProperty( QStringLiteral( "labeling/placement" ), placement ); } fet.setGeometry( *geom ); @@ -488,8 +488,8 @@ void QgsWmsConfigParser::highlightParameters( const QMap& para QString labelBufferColorParam = parameterMap.value( parameterPrefix + "HIGHLIGHT_LABELBUFFERCOLOR" ); QString labelBufferSizeParam = parameterMap.value( parameterPrefix + "HIGHLIGHT_LABELBUFFERSIZE" ); - geom = geomParam.split( ";" ); - symbol = symbolParam.split( ";" ); + geom = geomParam.split( QStringLiteral( ";" ) ); + symbol = symbolParam.split( QStringLiteral( ";" ) ); label.clear(); labelFont.clear(); @@ -501,31 +501,31 @@ void QgsWmsConfigParser::highlightParameters( const QMap& para if ( !labelParam.isEmpty() ) { - label = labelParam.split( ";" ); + label = labelParam.split( QStringLiteral( ";" ) ); } if ( !labelFontParam.isEmpty() ) { - labelFont = labelFontParam.split( ";" ); + labelFont = labelFontParam.split( QStringLiteral( ";" ) ); } if ( !labelSizeParam.isEmpty() ) { - labelSize = labelSizeParam.split( ";" ); + labelSize = labelSizeParam.split( QStringLiteral( ";" ) ); } if ( !labelWeightParam.isEmpty() ) { - labelWeight = labelWeightParam.split( ";" ); + labelWeight = labelWeightParam.split( QStringLiteral( ";" ) ); } if ( !labelColorParam.isEmpty() ) { - labelColor = labelColorParam.split( ";" ); + labelColor = labelColorParam.split( QStringLiteral( ";" ) ); } if ( !labelBufferColorParam.isEmpty() ) { - labelBufferColor = labelBufferColorParam.split( ";" ); + labelBufferColor = labelBufferColorParam.split( QStringLiteral( ";" ) ); } if ( !labelBufferSizeParam.isEmpty() ) { - labelBufferSize = labelBufferSizeParam.split( ";" ); + labelBufferSize = labelBufferSizeParam.split( QStringLiteral( ";" ) ); } } diff --git a/src/server/qgswmsprojectparser.cpp b/src/server/qgswmsprojectparser.cpp index 75a8cbb3766b..3e43aefcc254 100644 --- a/src/server/qgswmsprojectparser.cpp +++ b/src/server/qgswmsprojectparser.cpp @@ -61,8 +61,8 @@ QgsWmsProjectParser::QgsWmsProjectParser( #endif { mProjectParser = QgsConfigCache::instance()->serverConfiguration( filePath ); - mLegendLayerFont.fromString( mProjectParser->firstComposerLegendElement().attribute( "layerFont" ) ); - mLegendItemFont.fromString( mProjectParser->firstComposerLegendElement().attribute( "itemFont" ) ); + mLegendLayerFont.fromString( mProjectParser->firstComposerLegendElement().attribute( QStringLiteral( "layerFont" ) ) ); + mLegendItemFont.fromString( mProjectParser->firstComposerLegendElement().attribute( QStringLiteral( "itemFont" ) ) ); createTextAnnotationItems(); createSvgAnnotationItems(); } @@ -89,12 +89,12 @@ void QgsWmsProjectParser::layersAndStylesCapabilities( QDomElement& parentElemen //According to the WMS spec, there can be only one toplevel layer. //So we create an artificial one here to be in accordance with the schema QString projTitle = mProjectParser->projectTitle(); - QDomElement layerParentElem = doc.createElement( "Layer" ); - layerParentElem.setAttribute( "queryable", "1" ); + QDomElement layerParentElem = doc.createElement( QStringLiteral( "Layer" ) ); + layerParentElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "1" ) ); - QDomElement layerParentNameElem = doc.createElement( "Name" ); + QDomElement layerParentNameElem = doc.createElement( QStringLiteral( "Name" ) ); //WMS Name - QDomElement nameElem = mProjectParser->propertiesElem().firstChildElement( "WMSRootName" ); + QDomElement nameElem = mProjectParser->propertiesElem().firstChildElement( QStringLiteral( "WMSRootName" ) ); if ( !nameElem.isNull() && !nameElem.text().isEmpty() ) { QDomText layerParentNameText = doc.createTextNode( nameElem.text() ); @@ -107,7 +107,7 @@ void QgsWmsProjectParser::layersAndStylesCapabilities( QDomElement& parentElemen } layerParentElem.appendChild( layerParentNameElem ); // Why not use WMSServiceTitle ? - QDomElement layerParentTitleElem = doc.createElement( "Title" ); + QDomElement layerParentTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText layerParentTitleText = doc.createTextNode( projTitle ); layerParentTitleElem.appendChild( layerParentTitleText ); layerParentElem.appendChild( layerParentTitleElem ); @@ -115,7 +115,7 @@ void QgsWmsProjectParser::layersAndStylesCapabilities( QDomElement& parentElemen if ( fullProjectSettings ) { // Layer tree name - QDomElement treeNameElem = doc.createElement( "TreeName" ); + QDomElement treeNameElem = doc.createElement( QStringLiteral( "TreeName" ) ); QDomText treeNameText = doc.createTextNode( projTitle ); treeNameElem.appendChild( treeNameText ); layerParentElem.appendChild( treeNameElem ); @@ -161,7 +161,7 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName { // try to apply the specified style if ( !ml->styleManager()->setCurrentStyle( styleName != EMPTY_STYLE_NAME ? styleName : QString() ) ) - throw QgsMapServiceException( "StyleNotDefined", QString( "Style \"%1\" does not exist for layer \"%2\"" ).arg( styleName, lName ) ); + throw QgsMapServiceException( QStringLiteral( "StyleNotDefined" ), QStringLiteral( "Style \"%1\" does not exist for layer \"%2\"" ).arg( styleName, lName ) ); } return QList() << ml; } @@ -174,7 +174,7 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName } else { - QDomElement nameElem = mProjectParser->propertiesElem().firstChildElement( "WMSRootName" ); + QDomElement nameElem = mProjectParser->propertiesElem().firstChildElement( QStringLiteral( "WMSRootName" ) ); if ( !nameElem.isNull() && lName == nameElem.text() ) { groupElement = mProjectParser->legendElem(); @@ -185,12 +185,12 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName QList::const_iterator groupIt = legendGroupElements.constBegin(); for ( ; groupIt != legendGroupElements.constEnd(); ++groupIt ) { - if ( groupIt->attribute( "name" ) == lName ) + if ( groupIt->attribute( QStringLiteral( "name" ) ) == lName ) { groupElement = *groupIt; break; } - else if ( groupIt->attribute( "shortName" ) == lName ) + else if ( groupIt->attribute( QStringLiteral( "shortName" ) ) == lName ) { groupElement = *groupIt; break; @@ -207,11 +207,11 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName //still not found. Check if it is a single embedded layer (embedded layers are not contained in mProjectLayerElementsByName) QDomElement legendElement = mProjectParser->legendElem(); - QDomNodeList legendLayerList = legendElement.elementsByTagName( "legendlayer" ); + QDomNodeList legendLayerList = legendElement.elementsByTagName( QStringLiteral( "legendlayer" ) ); for ( int i = 0; i < legendLayerList.size(); ++i ) { QDomElement legendLayerElem = legendLayerList.at( i ).toElement(); - if ( legendLayerElem.attribute( "name" ) == lName ) + if ( legendLayerElem.attribute( QStringLiteral( "name" ) ) == lName ) { mProjectParser->layerFromLegendLayer( legendLayerElem, layers, useCache ); } @@ -225,9 +225,9 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName QList::const_iterator legendIt = legendGroupElements.constBegin(); for ( ; legendIt != legendGroupElements.constEnd(); ++legendIt ) { - if ( legendIt->attribute( "embedded" ) == "1" ) + if ( legendIt->attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { - QString project = mProjectParser->convertToAbsolutePath( legendIt->attribute( "project" ) ); + QString project = mProjectParser->convertToAbsolutePath( legendIt->attribute( QStringLiteral( "project" ) ) ); QgsWmsProjectParser* p = dynamic_cast( QgsConfigCache::instance()->wmsConfiguration( project #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -248,7 +248,7 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName QList::const_iterator pLegendGroupIt = legendGroupElements.constBegin(); for ( ; pLegendGroupIt != legendGroupElements.constEnd(); ++pLegendGroupIt ) { - if ( pLegendGroupIt->attribute( "name" ) == lName ) + if ( pLegendGroupIt->attribute( QStringLiteral( "name" ) ) == lName ) { addLayersFromGroup( *pLegendGroupIt, layers, useCache ); break; @@ -259,7 +259,7 @@ QList QgsWmsProjectParser::mapLayerFromStyle( const QString& lName } if ( layers.isEmpty() ) - throw QgsMapServiceException( "LayerNotDefined", QString( "Layer \"%1\" does not exist" ).arg( lName ) ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), QStringLiteral( "Layer \"%1\" does not exist" ).arg( lName ) ); return layers.values(); } @@ -271,12 +271,12 @@ void QgsWmsProjectParser::addLayersFromGroup( const QDomElement& legendGroupElem return; } - if ( legendGroupElem.attribute( "embedded" ) == "1" ) //embedded group + if ( legendGroupElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) //embedded group { - QString groupName = legendGroupElem.attribute( "name" ); - int drawingOrder = mProjectParser->updateLegendDrawingOrder() ? legendGroupElem.attribute( "drawingOrder", "-1" ).toInt() : -1; + QString groupName = legendGroupElem.attribute( QStringLiteral( "name" ) ); + int drawingOrder = mProjectParser->updateLegendDrawingOrder() ? legendGroupElem.attribute( QStringLiteral( "drawingOrder" ), QStringLiteral( "-1" ) ).toInt() : -1; - QString project = mProjectParser->convertToAbsolutePath( legendGroupElem.attribute( "project" ) ); + QString project = mProjectParser->convertToAbsolutePath( legendGroupElem.attribute( QStringLiteral( "project" ) ) ); QgsWmsProjectParser* p = dynamic_cast( QgsConfigCache::instance()->wmsConfiguration( project #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -290,7 +290,7 @@ void QgsWmsProjectParser::addLayersFromGroup( const QDomElement& legendGroupElem QList::const_iterator legendIt = legendGroups.constBegin(); for ( ; legendIt != legendGroups.constEnd(); ++legendIt ) { - if ( legendIt->attribute( "name" ) == groupName ) + if ( legendIt->attribute( QStringLiteral( "name" ) ) == groupName ) { QMap< int, QgsMapLayer*> embeddedGroupLayers; p->addLayersFromGroup( *legendIt, embeddedGroupLayers, useCache ); @@ -315,11 +315,11 @@ void QgsWmsProjectParser::addLayersFromGroup( const QDomElement& legendGroupElem for ( int i = groupElemChildren.size() - 1; i >= 0 ; --i ) { QDomElement elem = groupElemChildren.at( i ).toElement(); - if ( elem.tagName() == "legendgroup" ) + if ( elem.tagName() == QLatin1String( "legendgroup" ) ) { addLayersFromGroup( elem, layers, useCache ); } - else if ( elem.tagName() == "legendlayer" ) + else if ( elem.tagName() == QLatin1String( "legendlayer" ) ) { mProjectParser->layerFromLegendLayer( elem, layers, useCache ); } @@ -340,43 +340,43 @@ QStringList QgsWmsProjectParser::wfsLayerNames() const double QgsWmsProjectParser::legendBoxSpace() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 2.0 : legendElem.attribute( "boxSpace" ).toDouble(); + return legendElem.isNull() ? 2.0 : legendElem.attribute( QStringLiteral( "boxSpace" ) ).toDouble(); } double QgsWmsProjectParser::legendLayerSpace() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 3.0 : legendElem.attribute( "layerSpace" ).toDouble(); + return legendElem.isNull() ? 3.0 : legendElem.attribute( QStringLiteral( "layerSpace" ) ).toDouble(); } double QgsWmsProjectParser::legendLayerTitleSpace() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 3.0 : legendElem.attribute( "layerTitleSpace" ).toDouble(); + return legendElem.isNull() ? 3.0 : legendElem.attribute( QStringLiteral( "layerTitleSpace" ) ).toDouble(); } double QgsWmsProjectParser::legendSymbolSpace() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 2.0 : legendElem.attribute( "symbolSpace" ).toDouble(); + return legendElem.isNull() ? 2.0 : legendElem.attribute( QStringLiteral( "symbolSpace" ) ).toDouble(); } double QgsWmsProjectParser::legendIconLabelSpace() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 2.0 : legendElem.attribute( "iconLabelSpace" ).toDouble(); + return legendElem.isNull() ? 2.0 : legendElem.attribute( QStringLiteral( "iconLabelSpace" ) ).toDouble(); } double QgsWmsProjectParser::legendSymbolWidth() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 7.0 : legendElem.attribute( "symbolWidth" ).toDouble(); + return legendElem.isNull() ? 7.0 : legendElem.attribute( QStringLiteral( "symbolWidth" ) ).toDouble(); } double QgsWmsProjectParser::legendSymbolHeight() const { QDomElement legendElem = mProjectParser->firstComposerLegendElement(); - return legendElem.isNull() ? 4.0 : legendElem.attribute( "symbolHeight" ).toDouble(); + return legendElem.isNull() ? 4.0 : legendElem.attribute( QStringLiteral( "symbolHeight" ) ).toDouble(); } const QFont& QgsWmsProjectParser::legendLayerFont() const @@ -395,7 +395,7 @@ double QgsWmsProjectParser::maxWidth() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement maxWidthElem = propertiesElem.firstChildElement( "WMSMaxWidth" ); + QDomElement maxWidthElem = propertiesElem.firstChildElement( QStringLiteral( "WMSMaxWidth" ) ); if ( !maxWidthElem.isNull() ) { maxWidth = maxWidthElem.text().toInt(); @@ -410,7 +410,7 @@ double QgsWmsProjectParser::maxHeight() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement maxWidthElem = propertiesElem.firstChildElement( "WMSMaxHeight" ); + QDomElement maxWidthElem = propertiesElem.firstChildElement( QStringLiteral( "WMSMaxHeight" ) ); if ( !maxWidthElem.isNull() ) { maxHeight = maxWidthElem.text().toInt(); @@ -425,7 +425,7 @@ double QgsWmsProjectParser::imageQuality() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement imageQualityElem = propertiesElem.firstChildElement( "WMSImageQuality" ); + QDomElement imageQualityElem = propertiesElem.firstChildElement( QStringLiteral( "WMSImageQuality" ) ); if ( !imageQualityElem.isNull() ) { imageQuality = imageQualityElem.text().toInt(); @@ -440,7 +440,7 @@ int QgsWmsProjectParser::wmsPrecision() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement WMSPrecisionElem = propertiesElem.firstChildElement( "WMSPrecision" ); + QDomElement WMSPrecisionElem = propertiesElem.firstChildElement( QStringLiteral( "WMSPrecision" ) ); if ( !WMSPrecisionElem.isNull() ) { WMSPrecision = WMSPrecisionElem.text().toInt(); @@ -455,10 +455,10 @@ bool QgsWmsProjectParser::wmsInspireActivated() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( !propertiesElem.isNull() ) { - QDomElement inspireElem = propertiesElem.firstChildElement( "WMSInspire" ); + QDomElement inspireElem = propertiesElem.firstChildElement( QStringLiteral( "WMSInspire" ) ); if ( !inspireElem.isNull() ) { - QDomElement inspireActivatedElem = inspireElem.firstChildElement( "activated" ); + QDomElement inspireActivatedElem = inspireElem.firstChildElement( QStringLiteral( "activated" ) ); if ( !inspireActivatedElem.isNull() ) { inspireActivated = QVariant( inspireActivatedElem.text() ).toBool(); @@ -474,10 +474,10 @@ QgsComposition* QgsWmsProjectParser::initComposition( const QString& composerTem QDomElement composerElem = composerByName( composerTemplate ); if ( composerElem.isNull() ) { - throw QgsMapServiceException( "Error", "Composer template not found" ); + throw QgsMapServiceException( QStringLiteral( "Error" ), QStringLiteral( "Composer template not found" ) ); } - QDomElement compositionElem = composerElem.firstChildElement( "Composition" ); + QDomElement compositionElem = composerElem.firstChildElement( QStringLiteral( "Composition" ) ); if ( compositionElem.isNull() ) { return nullptr; @@ -604,75 +604,75 @@ void QgsWmsProjectParser::printCapabilities( QDomElement& parentElement, QDomDoc return; } - QDomElement composerTemplatesElem = doc.createElement( "ComposerTemplates" ); + QDomElement composerTemplatesElem = doc.createElement( QStringLiteral( "ComposerTemplates" ) ); QList::const_iterator composerElemIt = composerElemList.constBegin(); for ( ; composerElemIt != composerElemList.constEnd(); ++composerElemIt ) { - QDomElement composerTemplateElem = doc.createElement( "ComposerTemplate" ); + QDomElement composerTemplateElem = doc.createElement( QStringLiteral( "ComposerTemplate" ) ); QDomElement currentComposerElem = *composerElemIt; if ( currentComposerElem.isNull() ) { continue; } - composerTemplateElem.setAttribute( "name", currentComposerElem.attribute( "title" ) ); + composerTemplateElem.setAttribute( QStringLiteral( "name" ), currentComposerElem.attribute( QStringLiteral( "title" ) ) ); //get paper width and hight in mm from composition - QDomElement compositionElem = currentComposerElem.firstChildElement( "Composition" ); + QDomElement compositionElem = currentComposerElem.firstChildElement( QStringLiteral( "Composition" ) ); if ( compositionElem.isNull() ) { continue; } - composerTemplateElem.setAttribute( "width", compositionElem.attribute( "paperWidth" ) ); - composerTemplateElem.setAttribute( "height", compositionElem.attribute( "paperHeight" ) ); + composerTemplateElem.setAttribute( QStringLiteral( "width" ), compositionElem.attribute( QStringLiteral( "paperWidth" ) ) ); + composerTemplateElem.setAttribute( QStringLiteral( "height" ), compositionElem.attribute( QStringLiteral( "paperHeight" ) ) ); //add available composer maps and their size in mm - QDomNodeList composerMapList = currentComposerElem.elementsByTagName( "ComposerMap" ); + QDomNodeList composerMapList = currentComposerElem.elementsByTagName( QStringLiteral( "ComposerMap" ) ); for ( int j = 0; j < composerMapList.size(); ++j ) { QDomElement cmap = composerMapList.at( j ).toElement(); - QDomElement citem = cmap.firstChildElement( "ComposerItem" ); + QDomElement citem = cmap.firstChildElement( QStringLiteral( "ComposerItem" ) ); if ( citem.isNull() ) { continue; } - QDomElement composerMapElem = doc.createElement( "ComposerMap" ); - composerMapElem.setAttribute( "name", "map" + cmap.attribute( "id" ) ); - composerMapElem.setAttribute( "width", citem.attribute( "width" ) ); - composerMapElem.setAttribute( "height", citem.attribute( "height" ) ); + QDomElement composerMapElem = doc.createElement( QStringLiteral( "ComposerMap" ) ); + composerMapElem.setAttribute( QStringLiteral( "name" ), "map" + cmap.attribute( QStringLiteral( "id" ) ) ); + composerMapElem.setAttribute( QStringLiteral( "width" ), citem.attribute( QStringLiteral( "width" ) ) ); + composerMapElem.setAttribute( QStringLiteral( "height" ), citem.attribute( QStringLiteral( "height" ) ) ); composerTemplateElem.appendChild( composerMapElem ); } //add available composer labels - QDomNodeList composerLabelList = currentComposerElem.elementsByTagName( "ComposerLabel" ); + QDomNodeList composerLabelList = currentComposerElem.elementsByTagName( QStringLiteral( "ComposerLabel" ) ); for ( int j = 0; j < composerLabelList.size(); ++j ) { - QDomElement citem = composerLabelList.at( j ).firstChildElement( "ComposerItem" ); - QString id = citem.attribute( "id" ); + QDomElement citem = composerLabelList.at( j ).firstChildElement( QStringLiteral( "ComposerItem" ) ); + QString id = citem.attribute( QStringLiteral( "id" ) ); if ( id.isEmpty() ) //only export labels with ids for text replacement { continue; } - QDomElement composerLabelElem = doc.createElement( "ComposerLabel" ); - composerLabelElem.setAttribute( "name", id ); + QDomElement composerLabelElem = doc.createElement( QStringLiteral( "ComposerLabel" ) ); + composerLabelElem.setAttribute( QStringLiteral( "name" ), id ); composerTemplateElem.appendChild( composerLabelElem ); } //add available composer HTML - QDomNodeList composerHtmlList = currentComposerElem.elementsByTagName( "ComposerHtml" ); + QDomNodeList composerHtmlList = currentComposerElem.elementsByTagName( QStringLiteral( "ComposerHtml" ) ); for ( int j = 0; j < composerHtmlList.size(); ++j ) { - QDomElement citem = composerHtmlList.at( j ).firstChildElement( "ComposerFrame" ).firstChildElement( "ComposerItem" ); - QString id = citem.attribute( "id" ); + QDomElement citem = composerHtmlList.at( j ).firstChildElement( QStringLiteral( "ComposerFrame" ) ).firstChildElement( QStringLiteral( "ComposerItem" ) ); + QString id = citem.attribute( QStringLiteral( "id" ) ); if ( id.isEmpty() ) //only export labels with ids for text replacement { continue; } - QDomElement composerHtmlElem = doc.createElement( "ComposerHtml" ); - composerHtmlElem.setAttribute( "name", id ); + QDomElement composerHtmlElem = doc.createElement( QStringLiteral( "ComposerHtml" ) ); + composerHtmlElem.setAttribute( QStringLiteral( "name" ), id ); composerTemplateElem.appendChild( composerHtmlElem ); } @@ -692,28 +692,28 @@ void QgsWmsProjectParser::inspireCapabilities( QDomElement& parentElement, QDomD return; } - QDomElement inspireElem = propertiesElem.firstChildElement( "WMSInspire" ); + QDomElement inspireElem = propertiesElem.firstChildElement( QStringLiteral( "WMSInspire" ) ); if ( inspireElem.isNull() ) { return; } - QDomElement inspireCapabilitiesElem = doc.createElement( "inspire_vs:ExtendedCapabilities" ); + QDomElement inspireCapabilitiesElem = doc.createElement( QStringLiteral( "inspire_vs:ExtendedCapabilities" ) ); - QDomElement inspireMetadataUrlElem = inspireElem.firstChildElement( "metadataUrl" ); + QDomElement inspireMetadataUrlElem = inspireElem.firstChildElement( QStringLiteral( "metadataUrl" ) ); if ( !inspireMetadataUrlElem.isNull() ) { - QDomElement inspireCommonMetadataUrlElem = doc.createElement( "inspire_common:MetadataUrl" ); - inspireCommonMetadataUrlElem.setAttribute( "xsi:type", "inspire_common:resourceLocatorType" ); + QDomElement inspireCommonMetadataUrlElem = doc.createElement( QStringLiteral( "inspire_common:MetadataUrl" ) ); + inspireCommonMetadataUrlElem.setAttribute( QStringLiteral( "xsi:type" ), QStringLiteral( "inspire_common:resourceLocatorType" ) ); - QDomElement inspireCommonMetadataUrlUrlElem = doc.createElement( "inspire_common:URL" ); + QDomElement inspireCommonMetadataUrlUrlElem = doc.createElement( QStringLiteral( "inspire_common:URL" ) ); inspireCommonMetadataUrlUrlElem.appendChild( doc.createTextNode( inspireMetadataUrlElem.text() ) ); inspireCommonMetadataUrlElem.appendChild( inspireCommonMetadataUrlUrlElem ); - QDomElement inspireMetadataUrlTypeElem = inspireElem.firstChildElement( "metadataUrlType" ); + QDomElement inspireMetadataUrlTypeElem = inspireElem.firstChildElement( QStringLiteral( "metadataUrlType" ) ); if ( !inspireMetadataUrlTypeElem.isNull() ) { - QDomElement inspireCommonMetadataUrlMediaTypeElem = doc.createElement( "inspire_common:MediaType" ); + QDomElement inspireCommonMetadataUrlMediaTypeElem = doc.createElement( QStringLiteral( "inspire_common:MediaType" ) ); inspireCommonMetadataUrlMediaTypeElem.appendChild( doc.createTextNode( inspireMetadataUrlTypeElem.text() ) ); inspireCommonMetadataUrlElem.appendChild( inspireCommonMetadataUrlMediaTypeElem ); } @@ -722,36 +722,36 @@ void QgsWmsProjectParser::inspireCapabilities( QDomElement& parentElement, QDomD } else { - QDomElement inspireCommonResourceTypeElem = doc.createElement( "inspire_common:ResourceType" ); - inspireCommonResourceTypeElem.appendChild( doc.createTextNode( "service" ) ); + QDomElement inspireCommonResourceTypeElem = doc.createElement( QStringLiteral( "inspire_common:ResourceType" ) ); + inspireCommonResourceTypeElem.appendChild( doc.createTextNode( QStringLiteral( "service" ) ) ); inspireCapabilitiesElem.appendChild( inspireCommonResourceTypeElem ); - QDomElement inspireCommonSpatialDataServiceTypeElem = doc.createElement( "inspire_common:SpatialDataServiceType" ); - inspireCommonSpatialDataServiceTypeElem.appendChild( doc.createTextNode( "view" ) ); + QDomElement inspireCommonSpatialDataServiceTypeElem = doc.createElement( QStringLiteral( "inspire_common:SpatialDataServiceType" ) ); + inspireCommonSpatialDataServiceTypeElem.appendChild( doc.createTextNode( QStringLiteral( "view" ) ) ); inspireCapabilitiesElem.appendChild( inspireCommonSpatialDataServiceTypeElem ); - QDomElement inspireTemporalReferenceElem = inspireElem.firstChildElement( "temporalReference" ); + QDomElement inspireTemporalReferenceElem = inspireElem.firstChildElement( QStringLiteral( "temporalReference" ) ); if ( !inspireTemporalReferenceElem.isNull() ) { - QDomElement inspireCommonTemporalReferenceElem = doc.createElement( "inspire_common:TemporalReference" ); - QDomElement inspireCommonDateOfLastRevisionElem = doc.createElement( "inspire_common:DateOfLastRevision" ); + QDomElement inspireCommonTemporalReferenceElem = doc.createElement( QStringLiteral( "inspire_common:TemporalReference" ) ); + QDomElement inspireCommonDateOfLastRevisionElem = doc.createElement( QStringLiteral( "inspire_common:DateOfLastRevision" ) ); inspireCommonDateOfLastRevisionElem.appendChild( doc.createTextNode( inspireTemporalReferenceElem.text() ) ); inspireCommonTemporalReferenceElem.appendChild( inspireCommonDateOfLastRevisionElem ); inspireCapabilitiesElem.appendChild( inspireCommonTemporalReferenceElem ); } - QDomElement inspireCommonMetadataPointOfContactElem = doc.createElement( "inspire_common:MetadataPointOfContact" ); + QDomElement inspireCommonMetadataPointOfContactElem = doc.createElement( QStringLiteral( "inspire_common:MetadataPointOfContact" ) ); - QDomElement contactOrganizationElem = propertiesElem.firstChildElement( "WMSContactOrganization" ); - QDomElement inspireCommonOrganisationNameElem = doc.createElement( "inspire_common:OrganisationName" ); + QDomElement contactOrganizationElem = propertiesElem.firstChildElement( QStringLiteral( "WMSContactOrganization" ) ); + QDomElement inspireCommonOrganisationNameElem = doc.createElement( QStringLiteral( "inspire_common:OrganisationName" ) ); if ( !contactOrganizationElem.isNull() ) { inspireCommonOrganisationNameElem.appendChild( doc.createTextNode( contactOrganizationElem.text() ) ); } inspireCommonMetadataPointOfContactElem.appendChild( inspireCommonOrganisationNameElem ); - QDomElement contactMailElem = propertiesElem.firstChildElement( "WMSContactMail" ); - QDomElement inspireCommonEmailAddressElem = doc.createElement( "inspire_common:EmailAddress" ); + QDomElement contactMailElem = propertiesElem.firstChildElement( QStringLiteral( "WMSContactMail" ) ); + QDomElement inspireCommonEmailAddressElem = doc.createElement( QStringLiteral( "inspire_common:EmailAddress" ) ); if ( !contactMailElem.isNull() ) { inspireCommonEmailAddressElem.appendChild( doc.createTextNode( contactMailElem.text() ) ); @@ -760,25 +760,25 @@ void QgsWmsProjectParser::inspireCapabilities( QDomElement& parentElement, QDomD inspireCapabilitiesElem.appendChild( inspireCommonMetadataPointOfContactElem ); - QDomElement inspireMetadataDateElem = inspireElem.firstChildElement( "metadataDate" ); + QDomElement inspireMetadataDateElem = inspireElem.firstChildElement( QStringLiteral( "metadataDate" ) ); if ( !inspireMetadataDateElem.isNull() ) { - QDomElement inspireCommonMetadataDateElem = doc.createElement( "inspire_common:MetadataDate" ); + QDomElement inspireCommonMetadataDateElem = doc.createElement( QStringLiteral( "inspire_common:MetadataDate" ) ); inspireCommonMetadataDateElem.appendChild( doc.createTextNode( inspireMetadataDateElem.text() ) ); inspireCapabilitiesElem.appendChild( inspireCommonMetadataDateElem ); } } - QDomElement inspireLanguageElem = inspireElem.firstChildElement( "language" ); + QDomElement inspireLanguageElem = inspireElem.firstChildElement( QStringLiteral( "language" ) ); if ( !inspireLanguageElem.isNull() ) { - QDomElement inspireCommonSupportedLanguagesElem = doc.createElement( "inspire_common:SupportedLanguages" ); - inspireCommonSupportedLanguagesElem.setAttribute( "xsi:type", "inspire_common:supportedLanguagesType" ); + QDomElement inspireCommonSupportedLanguagesElem = doc.createElement( QStringLiteral( "inspire_common:SupportedLanguages" ) ); + inspireCommonSupportedLanguagesElem.setAttribute( QStringLiteral( "xsi:type" ), QStringLiteral( "inspire_common:supportedLanguagesType" ) ); - QDomElement inspireCommonLanguageElem = doc.createElement( "inspire_common:Language" ); + QDomElement inspireCommonLanguageElem = doc.createElement( QStringLiteral( "inspire_common:Language" ) ); inspireCommonLanguageElem.appendChild( doc.createTextNode( inspireLanguageElem.text() ) ); - QDomElement inspireCommonDefaultLanguageElem = doc.createElement( "inspire_common:DefaultLanguage" ); + QDomElement inspireCommonDefaultLanguageElem = doc.createElement( QStringLiteral( "inspire_common:DefaultLanguage" ) ); inspireCommonDefaultLanguageElem.appendChild( inspireCommonLanguageElem ); inspireCommonSupportedLanguagesElem.appendChild( inspireCommonDefaultLanguageElem ); @@ -791,7 +791,7 @@ void QgsWmsProjectParser::inspireCapabilities( QDomElement& parentElement, QDomD inspireCapabilitiesElem.appendChild( inspireCommonSupportedLanguagesElem ); - QDomElement inspireCommonResponseLanguageElem = doc.createElement( "inspire_common:ResponseLanguage" ); + QDomElement inspireCommonResponseLanguageElem = doc.createElement( QStringLiteral( "inspire_common:ResponseLanguage" ) ); inspireCommonResponseLanguageElem.appendChild( inspireCommonLanguageElem.cloneNode().toElement() ); inspireCapabilitiesElem.appendChild( inspireCommonResponseLanguageElem ); } @@ -808,12 +808,12 @@ void QgsWmsProjectParser::owsGeneralAndResourceList( QDomElement& parentElement, { // set parentElement id QFileInfo projectFileInfo( mProjectParser->projectPath() ); - parentElement.setAttribute( "id", "ows-context-" + projectFileInfo.baseName() ); + parentElement.setAttribute( QStringLiteral( "id" ), "ows-context-" + projectFileInfo.baseName() ); QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( propertiesElem.isNull() ) { - QFile wmsService( "wms_metadata.xml" ); + QFile wmsService( QStringLiteral( "wms_metadata.xml" ) ); if ( wmsService.open( QIODevice::ReadOnly ) ) { QDomDocument externServiceDoc; @@ -830,50 +830,50 @@ void QgsWmsProjectParser::owsGeneralAndResourceList( QDomElement& parentElement, } // OWSContext General element - QDomElement generalElem = doc.createElement( "General" ); + QDomElement generalElem = doc.createElement( QStringLiteral( "General" ) ); - QDomElement windowElem = doc.createElement( "Window" ); - windowElem.setAttribute( "height", "600" ); - windowElem.setAttribute( "width", "800" ); + QDomElement windowElem = doc.createElement( QStringLiteral( "Window" ) ); + windowElem.setAttribute( QStringLiteral( "height" ), QStringLiteral( "600" ) ); + windowElem.setAttribute( QStringLiteral( "width" ), QStringLiteral( "800" ) ); generalElem.appendChild( windowElem ); //WMS title //why not use project title ? - QDomElement titleElem = propertiesElem.firstChildElement( "WMSServiceTitle" ); + QDomElement titleElem = propertiesElem.firstChildElement( QStringLiteral( "WMSServiceTitle" ) ); if ( !titleElem.isNull() ) { - QDomElement wmsTitleElem = doc.createElement( "ows:Title" ); + QDomElement wmsTitleElem = doc.createElement( QStringLiteral( "ows:Title" ) ); QDomText wmsTitleText = doc.createTextNode( titleElem.text() ); wmsTitleElem.appendChild( wmsTitleText ); generalElem.appendChild( wmsTitleElem ); } //WMS abstract - QDomElement abstractElem = propertiesElem.firstChildElement( "WMSServiceAbstract" ); + QDomElement abstractElem = propertiesElem.firstChildElement( QStringLiteral( "WMSServiceAbstract" ) ); if ( !abstractElem.isNull() ) { - QDomElement wmsAbstractElem = doc.createElement( "ows:Abstract" ); + QDomElement wmsAbstractElem = doc.createElement( QStringLiteral( "ows:Abstract" ) ); QDomText wmsAbstractText = doc.createTextNode( abstractElem.text() ); wmsAbstractElem.appendChild( wmsAbstractText ); generalElem.appendChild( wmsAbstractElem ); } //keyword list - QDomElement keywordListElem = propertiesElem.firstChildElement( "WMSKeywordList" ); + QDomElement keywordListElem = propertiesElem.firstChildElement( QStringLiteral( "WMSKeywordList" ) ); if ( !keywordListElem.isNull() && !keywordListElem.text().isEmpty() ) { bool siaFormat = featureInfoFormatSIA2045(); - QDomElement keywordsElem = doc.createElement( "ows:Keywords" ); - QDomNodeList keywordList = keywordListElem.elementsByTagName( "value" ); + QDomElement keywordsElem = doc.createElement( QStringLiteral( "ows:Keywords" ) ); + QDomNodeList keywordList = keywordListElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < keywordList.size(); ++i ) { - QDomElement keywordElem = doc.createElement( "ows:Keyword" ); + QDomElement keywordElem = doc.createElement( QStringLiteral( "ows:Keyword" ) ); QDomText keywordText = doc.createTextNode( keywordList.at( i ).toElement().text() ); keywordElem.appendChild( keywordText ); if ( siaFormat ) { - keywordElem.setAttribute( "vocabulary", "SIA_Geo405" ); + keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "SIA_Geo405" ) ); } keywordsElem.appendChild( keywordElem ); } @@ -899,9 +899,9 @@ void QgsWmsProjectParser::owsGeneralAndResourceList( QDomElement& parentElement, QDomElement legendElem = mProjectParser->legendElem(); - QDomElement resourceListElem = doc.createElement( "ResourceList" ); + QDomElement resourceListElem = doc.createElement( QStringLiteral( "ResourceList" ) ); - addOWSLayers( doc, resourceListElem, legendElem, layerMap, nonIdentifiableLayers, strHref, combinedBBox, "" ); + addOWSLayers( doc, resourceListElem, legendElem, layerMap, nonIdentifiableLayers, strHref, combinedBBox, QLatin1String( "" ) ); parentElement.appendChild( resourceListElem ); @@ -911,17 +911,17 @@ void QgsWmsProjectParser::owsGeneralAndResourceList( QDomElement& parentElement, combinedBBox = mapRect; } QgsCoordinateReferenceSystem projectCrs = mProjectParser->projectCrs(); - QDomElement bboxElem = doc.createElement( "ows:BoundingBox" ); - bboxElem.setAttribute( "crs", projectCrs.authid() ); + QDomElement bboxElem = doc.createElement( QStringLiteral( "ows:BoundingBox" ) ); + bboxElem.setAttribute( QStringLiteral( "crs" ), projectCrs.authid() ); if ( projectCrs.hasAxisInverted() ) { combinedBBox.invert(); } - QDomElement lowerCornerElem = doc.createElement( "ows:LowerCorner" ); + QDomElement lowerCornerElem = doc.createElement( QStringLiteral( "ows:LowerCorner" ) ); QDomText lowerCornerText = doc.createTextNode( QString::number( combinedBBox.xMinimum() ) + " " + QString::number( combinedBBox.yMinimum() ) ); lowerCornerElem.appendChild( lowerCornerText ); bboxElem.appendChild( lowerCornerElem ); - QDomElement upperCornerElem = doc.createElement( "ows:UpperCorner" ); + QDomElement upperCornerElem = doc.createElement( QStringLiteral( "ows:UpperCorner" ) ); QDomText upperCornerText = doc.createTextNode( QString::number( combinedBBox.xMaximum() ) + " " + QString::number( combinedBBox.yMaximum() ) ); upperCornerElem.appendChild( upperCornerText ); bboxElem.appendChild( upperCornerElem ); @@ -943,22 +943,22 @@ QStringList QgsWmsProjectParser::identifyDisabledLayers() const { return disabledList; } - QDomElement propertiesElem = qgisElem.firstChildElement( "properties" ); + QDomElement propertiesElem = qgisElem.firstChildElement( QStringLiteral( "properties" ) ); if ( propertiesElem.isNull() ) { return disabledList; } - QDomElement identifyElem = propertiesElem.firstChildElement( "Identify" ); + QDomElement identifyElem = propertiesElem.firstChildElement( QStringLiteral( "Identify" ) ); if ( identifyElem.isNull() ) { return disabledList; } - QDomElement disabledLayersElem = identifyElem.firstChildElement( "disabledLayers" ); + QDomElement disabledLayersElem = identifyElem.firstChildElement( QStringLiteral( "disabledLayers" ) ); if ( disabledLayersElem.isNull() ) { return disabledList; } - QDomNodeList valueList = disabledLayersElem.elementsByTagName( "value" ); + QDomNodeList valueList = disabledLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < valueList.size(); ++i ) { disabledList << valueList.at( i ).toElement().text(); @@ -1000,8 +1000,8 @@ void QgsWmsProjectParser::addDrawingOrder( QDomElement& parentElem, QDomDocument for ( int i = layerList.size() - 1; i >= 0; --i ) reversedList << layerList[ i ]; - QDomElement layerDrawingOrderElem = doc.createElement( "LayerDrawingOrder" ); - QDomText drawingOrderText = doc.createTextNode( reversedList.join( "," ) ); + QDomElement layerDrawingOrderElem = doc.createElement( QStringLiteral( "LayerDrawingOrder" ) ); + QDomText drawingOrderText = doc.createTextNode( reversedList.join( QStringLiteral( "," ) ) ); layerDrawingOrderElem.appendChild( drawingOrderText ); parentElem.appendChild( layerDrawingOrderElem ); } @@ -1014,18 +1014,18 @@ void QgsWmsProjectParser::addLayerStyles( QgsMapLayer* currentLayer, QDomDocumen if ( styleName.isEmpty() ) styleName = EMPTY_STYLE_NAME; - QDomElement styleElem = doc.createElement( "Style" ); - QDomElement styleNameElem = doc.createElement( "Name" ); + QDomElement styleElem = doc.createElement( QStringLiteral( "Style" ) ); + QDomElement styleNameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText styleNameText = doc.createTextNode( styleName ); styleNameElem.appendChild( styleNameText ); - QDomElement styleTitleElem = doc.createElement( "Title" ); + QDomElement styleTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( styleName ); styleTitleElem.appendChild( styleTitleText ); styleElem.appendChild( styleNameElem ); styleElem.appendChild( styleTitleElem ); // QString LegendURL for explicit layerbased GetLegendGraphic request - QDomElement getLayerLegendGraphicElem = doc.createElement( "LegendURL" ); + QDomElement getLayerLegendGraphicElem = doc.createElement( QStringLiteral( "LegendURL" ) ); QString hrefString = currentLayer->legendUrl(); bool customHrefString; if ( !hrefString.isEmpty() ) @@ -1046,7 +1046,7 @@ void QgsWmsProjectParser::addLayerStyles( QgsMapLayer* currentLayer, QDomDocumen QStringList getLayerLegendGraphicFormats; if ( !customHrefString ) { - getLayerLegendGraphicFormats << "image/png"; // << "jpeg" << "image/jpeg" + getLayerLegendGraphicFormats << QStringLiteral( "image/png" ); // << "jpeg" << "image/jpeg" } else @@ -1056,7 +1056,7 @@ void QgsWmsProjectParser::addLayerStyles( QgsMapLayer* currentLayer, QDomDocumen for ( int i = 0; i < getLayerLegendGraphicFormats.size(); ++i ) { - QDomElement getLayerLegendGraphicFormatElem = doc.createElement( "Format" ); + QDomElement getLayerLegendGraphicFormatElem = doc.createElement( QStringLiteral( "Format" ) ); QString getLayerLegendGraphicFormat = getLayerLegendGraphicFormats[i]; QDomText getLayerLegendGraphicFormatText = doc.createTextNode( getLayerLegendGraphicFormat ); getLayerLegendGraphicFormatElem.appendChild( getLayerLegendGraphicFormatText ); @@ -1072,23 +1072,23 @@ void QgsWmsProjectParser::addLayerStyles( QgsMapLayer* currentLayer, QDomDocumen else if ( !currentLayer->shortName().isEmpty() ) layerName = currentLayer->shortName(); QUrl mapUrl( hrefString ); - mapUrl.addQueryItem( "SERVICE", "WMS" ); - mapUrl.addQueryItem( "VERSION", version ); - mapUrl.addQueryItem( "REQUEST", "GetLegendGraphic" ); - mapUrl.addQueryItem( "LAYER", layerName ); - mapUrl.addQueryItem( "FORMAT", "image/png" ); - mapUrl.addQueryItem( "STYLE", styleNameText.data() ); - if ( version == "1.3.0" ) + mapUrl.addQueryItem( QStringLiteral( "SERVICE" ), QStringLiteral( "WMS" ) ); + mapUrl.addQueryItem( QStringLiteral( "VERSION" ), version ); + mapUrl.addQueryItem( QStringLiteral( "REQUEST" ), QStringLiteral( "GetLegendGraphic" ) ); + mapUrl.addQueryItem( QStringLiteral( "LAYER" ), layerName ); + mapUrl.addQueryItem( QStringLiteral( "FORMAT" ), QStringLiteral( "image/png" ) ); + mapUrl.addQueryItem( QStringLiteral( "STYLE" ), styleNameText.data() ); + if ( version == QLatin1String( "1.3.0" ) ) { - mapUrl.addQueryItem( "SLD_VERSION", "1.1.0" ); + mapUrl.addQueryItem( QStringLiteral( "SLD_VERSION" ), QStringLiteral( "1.1.0" ) ); } hrefString = mapUrl.toString(); } - QDomElement getLayerLegendGraphicORElem = doc.createElement( "OnlineResource" ); - getLayerLegendGraphicORElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - getLayerLegendGraphicORElem.setAttribute( "xlink:type", "simple" ); - getLayerLegendGraphicORElem.setAttribute( "xlink:href", hrefString ); + QDomElement getLayerLegendGraphicORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + getLayerLegendGraphicORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + getLayerLegendGraphicORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + getLayerLegendGraphicORElem.setAttribute( QStringLiteral( "xlink:href" ), hrefString ); getLayerLegendGraphicElem.appendChild( getLayerLegendGraphicORElem ); styleElem.appendChild( getLayerLegendGraphicElem ); } @@ -1114,16 +1114,16 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, for ( int i = 0; i < legendChildren.size(); ++i ) { QDomElement currentChildElem = legendChildren.at( i ).toElement(); - QDomElement layerElem = doc.createElement( "Layer" ); + QDomElement layerElem = doc.createElement( QStringLiteral( "Layer" ) ); if ( fullProjectSettings ) { - layerElem.setAttribute( "visible", currentChildElem.attribute( "checked" ) != "Qt::Unchecked" ); + layerElem.setAttribute( QStringLiteral( "visible" ), currentChildElem.attribute( QStringLiteral( "checked" ) ) != QLatin1String( "Qt::Unchecked" ) ); } - if ( currentChildElem.tagName() == "legendgroup" ) + if ( currentChildElem.tagName() == QLatin1String( "legendgroup" ) ) { - layerElem.setAttribute( "queryable", "1" ); - QString name = currentChildElem.attribute( "name" ); + layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "1" ) ); + QString name = currentChildElem.attribute( QStringLiteral( "name" ) ); if ( mProjectParser->restrictedLayers().contains( name ) ) //unpublished group { continue; @@ -1138,7 +1138,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, if ( layerTreeChildNode->nodeType() != QgsLayerTreeNode::NodeGroup ) continue; QgsLayerTreeGroup* layerTreeChildGroup = static_cast( layerTreeChildNode ); - if ( layerTreeChildGroup->name() != currentChildElem.attribute( "name" ) ) + if ( layerTreeChildGroup->name() != currentChildElem.attribute( QStringLiteral( "name" ) ) ) continue; ltGroup = layerTreeChildGroup; g = j; @@ -1151,10 +1151,10 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, QgsDebugMsg( QString( "Skipping group %1, it could not be found" ).arg( name ) ); continue; } - QString shortName = ltGroup->customProperty( "wmsShortName" ).toString(); - QString title = ltGroup->customProperty( "wmsTitle" ).toString(); + QString shortName = ltGroup->customProperty( QStringLiteral( "wmsShortName" ) ).toString(); + QString title = ltGroup->customProperty( QStringLiteral( "wmsTitle" ) ).toString(); - QDomElement nameElem = doc.createElement( "Name" ); + QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText nameText; if ( !shortName.isEmpty() ) nameText = doc.createTextNode( shortName ); @@ -1163,7 +1163,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); - QDomElement titleElem = doc.createElement( "Title" ); + QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText titleText; if ( !title.isEmpty() ) titleText = doc.createTextNode( title ); @@ -1172,10 +1172,10 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, titleElem.appendChild( titleText ); layerElem.appendChild( titleElem ); - QString abstract = ltGroup->customProperty( "wmsAbstract" ).toString(); + QString abstract = ltGroup->customProperty( QStringLiteral( "wmsAbstract" ) ).toString(); if ( !abstract.isEmpty() ) { - QDomElement abstractElem = doc.createElement( "Abstract" ); + QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText abstractText = doc.createTextNode( abstract ); abstractElem.appendChild( abstractText ); layerElem.appendChild( abstractElem ); @@ -1184,18 +1184,18 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, if ( fullProjectSettings ) { // Layer tree name - QDomElement treeNameElem = doc.createElement( "TreeName" ); + QDomElement treeNameElem = doc.createElement( QStringLiteral( "TreeName" ) ); QDomText treeNameText = doc.createTextNode( name ); treeNameElem.appendChild( treeNameText ); layerElem.appendChild( treeNameElem ); } - if ( currentChildElem.attribute( "embedded" ) == "1" ) + if ( currentChildElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { //add layers from other project files and embed into this group - QString project = mProjectParser->convertToAbsolutePath( currentChildElem.attribute( "project" ) ); + QString project = mProjectParser->convertToAbsolutePath( currentChildElem.attribute( QStringLiteral( "project" ) ) ); QgsDebugMsg( QString( "Project path: %1" ).arg( project ) ); - QString embeddedGroupName = currentChildElem.attribute( "name" ); + QString embeddedGroupName = currentChildElem.attribute( QStringLiteral( "name" ) ); QgsWmsProjectParser* p = dynamic_cast( QgsConfigCache::instance()->wmsConfiguration( project #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -1212,7 +1212,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, QDomElement embeddedGroupElem; Q_FOREACH ( const QDomElement &elem, embeddedGroupElements ) { - if ( elem.attribute( "name" ) == embeddedGroupName ) + if ( elem.attribute( QStringLiteral( "name" ) ) == embeddedGroupName ) { embeddedGroupElem = elem; break; @@ -1237,7 +1237,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, // combine bounding boxes of children (groups/layers) mProjectParser->combineExtentAndCrsOfGroupChildren( layerElem, doc ); } - else if ( currentChildElem.tagName() == "legendlayer" ) + else if ( currentChildElem.tagName() == QLatin1String( "legendlayer" ) ) { QString id = mProjectParser->layerIdFromLegendLayer( currentChildElem ); @@ -1273,14 +1273,14 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, // queryable layer if ( nonIdentifiableLayers.contains( currentLayer->id() ) ) { - layerElem.setAttribute( "queryable", "0" ); + layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "0" ) ); } else { - layerElem.setAttribute( "queryable", "1" ); + layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "1" ) ); } - QDomElement nameElem = doc.createElement( "Name" ); + QDomElement nameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText nameText = doc.createTextNode( layerName ); nameElem.appendChild( nameText ); layerElem.appendChild( nameElem ); @@ -1288,7 +1288,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, layerIDList << id; idNameMap.insert( id, currentLayer->name() ); - QDomElement titleElem = doc.createElement( "Title" ); + QDomElement titleElem = doc.createElement( QStringLiteral( "Title" ) ); QString titleName = currentLayer->title(); if ( titleName.isEmpty() ) { @@ -1301,7 +1301,7 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, QString abstract = currentLayer->abstract(); if ( !abstract.isEmpty() ) { - QDomElement abstractElem = doc.createElement( "Abstract" ); + QDomElement abstractElem = doc.createElement( QStringLiteral( "Abstract" ) ); QDomText abstractText = doc.createTextNode( abstract ); abstractElem.appendChild( abstractText ); layerElem.appendChild( abstractElem ); @@ -1310,18 +1310,18 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, //keyword list if ( !currentLayer->keywordList().isEmpty() ) { - QStringList keywordStringList = currentLayer->keywordList().split( "," ); + QStringList keywordStringList = currentLayer->keywordList().split( QStringLiteral( "," ) ); bool siaFormat = featureInfoFormatSIA2045(); - QDomElement keywordListElem = doc.createElement( "KeywordList" ); + QDomElement keywordListElem = doc.createElement( QStringLiteral( "KeywordList" ) ); for ( int i = 0; i < keywordStringList.size(); ++i ) { - QDomElement keywordElem = doc.createElement( "Keyword" ); + QDomElement keywordElem = doc.createElement( QStringLiteral( "Keyword" ) ); QDomText keywordText = doc.createTextNode( keywordStringList.at( i ).trimmed() ); keywordElem.appendChild( keywordText ); if ( siaFormat ) { - keywordElem.setAttribute( "vocabulary", "SIA_Geo405" ); + keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "SIA_Geo405" ) ); } keywordListElem.appendChild( keywordElem ); } @@ -1358,26 +1358,26 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, //min/max scale denominatormScaleBasedVisibility if ( currentLayer->hasScaleBasedVisibility() ) { - if ( version == "1.1.1" ) + if ( version == QLatin1String( "1.1.1" ) ) { double OGC_PX_M = 0.00028; // OGC reference pixel size in meter, also used by qgis double SCALE_TO_SCALEHINT = OGC_PX_M * sqrt( 2.0 ); - QDomElement scaleHintElem = doc.createElement( "ScaleHint" ); - scaleHintElem.setAttribute( "min", QString::number( currentLayer->minimumScale() * SCALE_TO_SCALEHINT ) ); - scaleHintElem.setAttribute( "max", QString::number( currentLayer->maximumScale() * SCALE_TO_SCALEHINT ) ); + QDomElement scaleHintElem = doc.createElement( QStringLiteral( "ScaleHint" ) ); + scaleHintElem.setAttribute( QStringLiteral( "min" ), QString::number( currentLayer->minimumScale() * SCALE_TO_SCALEHINT ) ); + scaleHintElem.setAttribute( QStringLiteral( "max" ), QString::number( currentLayer->maximumScale() * SCALE_TO_SCALEHINT ) ); layerElem.appendChild( scaleHintElem ); } else { QString minScaleString = QString::number( currentLayer->minimumScale() ); - QDomElement minScaleElem = doc.createElement( "MinScaleDenominator" ); + QDomElement minScaleElem = doc.createElement( QStringLiteral( "MinScaleDenominator" ) ); QDomText minScaleText = doc.createTextNode( minScaleString ); minScaleElem.appendChild( minScaleText ); layerElem.appendChild( minScaleElem ); QString maxScaleString = QString::number( currentLayer->maximumScale() ); - QDomElement maxScaleElem = doc.createElement( "MaxScaleDenominator" ); + QDomElement maxScaleElem = doc.createElement( QStringLiteral( "MaxScaleDenominator" ) ); QDomText maxScaleText = doc.createTextNode( maxScaleString ); maxScaleElem.appendChild( maxScaleText ); layerElem.appendChild( maxScaleElem ); @@ -1388,16 +1388,16 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, QString dataUrl = currentLayer->dataUrl(); if ( !dataUrl.isEmpty() ) { - QDomElement dataUrlElem = doc.createElement( "DataURL" ); - QDomElement dataUrlFormatElem = doc.createElement( "Format" ); + QDomElement dataUrlElem = doc.createElement( QStringLiteral( "DataURL" ) ); + QDomElement dataUrlFormatElem = doc.createElement( QStringLiteral( "Format" ) ); QString dataUrlFormat = currentLayer->dataUrlFormat(); QDomText dataUrlFormatText = doc.createTextNode( dataUrlFormat ); dataUrlFormatElem.appendChild( dataUrlFormatText ); dataUrlElem.appendChild( dataUrlFormatElem ); - QDomElement dataORElem = doc.createElement( "OnlineResource" ); - dataORElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - dataORElem.setAttribute( "xlink:type", "simple" ); - dataORElem.setAttribute( "xlink:href", dataUrl ); + QDomElement dataORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + dataORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + dataORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + dataORElem.setAttribute( QStringLiteral( "xlink:href" ), dataUrl ); dataUrlElem.appendChild( dataORElem ); layerElem.appendChild( dataUrlElem ); } @@ -1406,18 +1406,18 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, QString attribution = currentLayer->attribution(); if ( !attribution.isEmpty() ) { - QDomElement attribElem = doc.createElement( "Attribution" ); - QDomElement attribTitleElem = doc.createElement( "Title" ); + QDomElement attribElem = doc.createElement( QStringLiteral( "Attribution" ) ); + QDomElement attribTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText attribText = doc.createTextNode( attribution ); attribTitleElem.appendChild( attribText ); attribElem.appendChild( attribTitleElem ); QString attributionUrl = currentLayer->attributionUrl(); if ( !attributionUrl.isEmpty() ) { - QDomElement attribORElem = doc.createElement( "OnlineResource" ); - attribORElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - attribORElem.setAttribute( "xlink:type", "simple" ); - attribORElem.setAttribute( "xlink:href", attributionUrl ); + QDomElement attribORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + attribORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + attribORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + attribORElem.setAttribute( QStringLiteral( "xlink:href" ), attributionUrl ); attribElem.appendChild( attribORElem ); } layerElem.appendChild( attribElem ); @@ -1427,36 +1427,36 @@ void QgsWmsProjectParser::addLayers( QDomDocument &doc, QString metadataUrl = currentLayer->metadataUrl(); if ( !metadataUrl.isEmpty() ) { - QDomElement metaUrlElem = doc.createElement( "MetadataURL" ); + QDomElement metaUrlElem = doc.createElement( QStringLiteral( "MetadataURL" ) ); QString metadataUrlType = currentLayer->metadataUrlType(); - if ( version == "1.1.1" ) + if ( version == QLatin1String( "1.1.1" ) ) { - metaUrlElem.setAttribute( "type", metadataUrlType ); + metaUrlElem.setAttribute( QStringLiteral( "type" ), metadataUrlType ); } - else if ( metadataUrlType == "FGDC" ) + else if ( metadataUrlType == QLatin1String( "FGDC" ) ) { - metaUrlElem.setAttribute( "type", "FGDC:1998" ); + metaUrlElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "FGDC:1998" ) ); } - else if ( metadataUrlType == "TC211" ) + else if ( metadataUrlType == QLatin1String( "TC211" ) ) { - metaUrlElem.setAttribute( "type", "ISO19115:2003" ); + metaUrlElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "ISO19115:2003" ) ); } else { - metaUrlElem.setAttribute( "type", metadataUrlType ); + metaUrlElem.setAttribute( QStringLiteral( "type" ), metadataUrlType ); } QString metadataUrlFormat = currentLayer->metadataUrlFormat(); if ( !metadataUrlFormat.isEmpty() ) { - QDomElement metaUrlFormatElem = doc.createElement( "Format" ); + QDomElement metaUrlFormatElem = doc.createElement( QStringLiteral( "Format" ) ); QDomText metaUrlFormatText = doc.createTextNode( metadataUrlFormat ); metaUrlFormatElem.appendChild( metaUrlFormatText ); metaUrlElem.appendChild( metaUrlFormatElem ); } - QDomElement metaUrlORElem = doc.createElement( "OnlineResource" ); - metaUrlORElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - metaUrlORElem.setAttribute( "xlink:type", "simple" ); - metaUrlORElem.setAttribute( "xlink:href", metadataUrl ); + QDomElement metaUrlORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + metaUrlORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + metaUrlORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + metaUrlORElem.setAttribute( QStringLiteral( "xlink:href" ), metadataUrl ); metaUrlElem.appendChild( metaUrlORElem ); layerElem.appendChild( metaUrlElem ); } @@ -1484,14 +1484,14 @@ void QgsWmsProjectParser::addOWSLayerStyles( QgsMapLayer* currentLayer, QDomDocu if ( styleName.isEmpty() ) styleName = EMPTY_STYLE_NAME; - QDomElement styleListElem = doc.createElement( "StyleList" ); + QDomElement styleListElem = doc.createElement( QStringLiteral( "StyleList" ) ); //only one default style in project file mode - QDomElement styleElem = doc.createElement( "Style" ); - styleElem.setAttribute( "current", "true" ); - QDomElement styleNameElem = doc.createElement( "Name" ); + QDomElement styleElem = doc.createElement( QStringLiteral( "Style" ) ); + styleElem.setAttribute( QStringLiteral( "current" ), QStringLiteral( "true" ) ); + QDomElement styleNameElem = doc.createElement( QStringLiteral( "Name" ) ); QDomText styleNameText = doc.createTextNode( styleName ); styleNameElem.appendChild( styleNameText ); - QDomElement styleTitleElem = doc.createElement( "Title" ); + QDomElement styleTitleElem = doc.createElement( QStringLiteral( "Title" ) ); QDomText styleTitleText = doc.createTextNode( styleName ); styleTitleElem.appendChild( styleTitleText ); styleElem.appendChild( styleNameElem ); @@ -1517,9 +1517,9 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, { QDomElement currentChildElem = legendChildren.at( i ).toElement(); - if ( currentChildElem.tagName() == "legendgroup" ) + if ( currentChildElem.tagName() == QLatin1String( "legendgroup" ) ) { - QString name = currentChildElem.attribute( "name" ); + QString name = currentChildElem.attribute( QStringLiteral( "name" ) ); if ( mProjectParser->restrictedLayers().contains( name ) ) //unpublished group { continue; @@ -1534,12 +1534,12 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, group = strGroup + "/" + name; } - if ( currentChildElem.attribute( "embedded" ) == "1" ) + if ( currentChildElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) ) { //add layers from other project files and embed into this group - QString project = mProjectParser->convertToAbsolutePath( currentChildElem.attribute( "project" ) ); + QString project = mProjectParser->convertToAbsolutePath( currentChildElem.attribute( QStringLiteral( "project" ) ) ); QgsDebugMsg( QString( "Project path: %1" ).arg( project ) ); - QString embeddedGroupName = currentChildElem.attribute( "name" ); + QString embeddedGroupName = currentChildElem.attribute( QStringLiteral( "name" ) ); QgsWmsProjectParser* p = dynamic_cast( QgsConfigCache::instance()->wmsConfiguration( project #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -1555,7 +1555,7 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, QDomElement embeddedGroupElem; Q_FOREACH ( const QDomElement &elem, embeddedGroupElements ) { - if ( elem.attribute( "name" ) == embeddedGroupName ) + if ( elem.attribute( QStringLiteral( "name" ) ) == embeddedGroupName ) { embeddedGroupElem = elem; break; @@ -1580,9 +1580,9 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, // combine bounding boxes of children (groups/layers) // combineExtentAndCrsOfGroupChildren( layerElem, doc ); } - else if ( currentChildElem.tagName() == "legendlayer" ) + else if ( currentChildElem.tagName() == QLatin1String( "legendlayer" ) ) { - QDomElement layerElem = doc.createElement( "Layer" ); + QDomElement layerElem = doc.createElement( QStringLiteral( "Layer" ) ); QString id = mProjectParser->layerIdFromLegendLayer( currentChildElem ); if ( !layerMap.contains( id ) ) @@ -1609,42 +1609,42 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, } if ( nonIdentifiableLayers.contains( currentLayer->id() ) ) { - layerElem.setAttribute( "queryable", "false" ); + layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "false" ) ); } else { - layerElem.setAttribute( "queryable", "true" ); + layerElem.setAttribute( QStringLiteral( "queryable" ), QStringLiteral( "true" ) ); } // is the layer visible ? - if ( currentChildElem.firstChildElement().firstChildElement().attribute( "visible" ) == "1" ) + if ( currentChildElem.firstChildElement().firstChildElement().attribute( QStringLiteral( "visible" ) ) == QLatin1String( "1" ) ) { - layerElem.setAttribute( "hidden", "false" ); + layerElem.setAttribute( QStringLiteral( "hidden" ), QStringLiteral( "false" ) ); } else { - layerElem.setAttribute( "hidden", "true" ); + layerElem.setAttribute( QStringLiteral( "hidden" ), QStringLiteral( "true" ) ); } if ( !strGroup.isEmpty() ) { - layerElem.setAttribute( "group", strGroup ); + layerElem.setAttribute( QStringLiteral( "group" ), strGroup ); } // Because Layer transparency is used for the rendering // OWSContext Layer opacity is set to 1 - layerElem.setAttribute( "opacity", 1 ); + layerElem.setAttribute( QStringLiteral( "opacity" ), 1 ); QString lyrname = currentLayer->name(); if ( mProjectParser && mProjectParser->useLayerIds() ) lyrname = currentLayer->id(); else if ( !currentLayer->shortName().isEmpty() ) lyrname = currentLayer->shortName(); - layerElem.setAttribute( "name", lyrname ); + layerElem.setAttribute( QStringLiteral( "name" ), lyrname ); // define an id based on layer name - layerElem.setAttribute( "id", lyrname.replace( QRegExp( "[\\W]" ), "_" ) ); + layerElem.setAttribute( QStringLiteral( "id" ), lyrname.replace( QRegExp( "[\\W]" ), QStringLiteral( "_" ) ) ); - QDomElement titleElem = doc.createElement( "ows:Title" ); + QDomElement titleElem = doc.createElement( QStringLiteral( "ows:Title" ) ); QString titleName = currentLayer->title(); if ( titleName.isEmpty() ) { @@ -1654,24 +1654,24 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, titleElem.appendChild( titleText ); layerElem.appendChild( titleElem ); - QDomElement formatElem = doc.createElement( "ows:OutputFormat" ); - QDomText formatText = doc.createTextNode( "image/png" ); + QDomElement formatElem = doc.createElement( QStringLiteral( "ows:OutputFormat" ) ); + QDomText formatText = doc.createTextNode( QStringLiteral( "image/png" ) ); formatElem.appendChild( formatText ); layerElem.appendChild( formatElem ); - QDomElement serverElem = doc.createElement( "Server" ); - serverElem.setAttribute( "service", "urn:ogc:serviceType:WMS" ); - serverElem.setAttribute( "version", "1.3.0" ); - serverElem.setAttribute( "default", "true" ); - QDomElement orServerElem = doc.createElement( "OnlineResource" ); - orServerElem.setAttribute( "xlink:href", strHref ); + QDomElement serverElem = doc.createElement( QStringLiteral( "Server" ) ); + serverElem.setAttribute( QStringLiteral( "service" ), QStringLiteral( "urn:ogc:serviceType:WMS" ) ); + serverElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.3.0" ) ); + serverElem.setAttribute( QStringLiteral( "default" ), QStringLiteral( "true" ) ); + QDomElement orServerElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + orServerElem.setAttribute( QStringLiteral( "xlink:href" ), strHref ); serverElem.appendChild( orServerElem ); layerElem.appendChild( serverElem ); QString abstract = currentLayer->abstract(); if ( !abstract.isEmpty() ) { - QDomElement abstractElem = doc.createElement( "ows:Abstract" ); + QDomElement abstractElem = doc.createElement( QStringLiteral( "ows:Abstract" ) ); QDomText abstractText = doc.createTextNode( abstract ); abstractElem.appendChild( abstractText ); layerElem.appendChild( abstractElem ); @@ -1682,11 +1682,11 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, { QString minScaleString = QString::number( currentLayer->minimumScale() ); QString maxScaleString = QString::number( currentLayer->maximumScale() ); - QDomElement minScaleElem = doc.createElement( "sld:MinScaleDenominator" ); + QDomElement minScaleElem = doc.createElement( QStringLiteral( "sld:MinScaleDenominator" ) ); QDomText minScaleText = doc.createTextNode( minScaleString ); minScaleElem.appendChild( minScaleText ); layerElem.appendChild( minScaleElem ); - QDomElement maxScaleElem = doc.createElement( "sld:MaxScaleDenominator" ); + QDomElement maxScaleElem = doc.createElement( QStringLiteral( "sld:MaxScaleDenominator" ) ); QDomText maxScaleText = doc.createTextNode( maxScaleString ); maxScaleElem.appendChild( maxScaleText ); layerElem.appendChild( maxScaleElem ); @@ -1720,18 +1720,18 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, //keyword list if ( !currentLayer->keywordList().isEmpty() ) { - QStringList keywordStringList = currentLayer->keywordList().split( "," ); + QStringList keywordStringList = currentLayer->keywordList().split( QStringLiteral( "," ) ); bool siaFormat = featureInfoFormatSIA2045(); - QDomElement keywordsElem = doc.createElement( "ows:Keywords" ); + QDomElement keywordsElem = doc.createElement( QStringLiteral( "ows:Keywords" ) ); for ( int i = 0; i < keywordStringList.size(); ++i ) { - QDomElement keywordElem = doc.createElement( "ows:Keyword" ); + QDomElement keywordElem = doc.createElement( QStringLiteral( "ows:Keyword" ) ); QDomText keywordText = doc.createTextNode( keywordStringList.at( i ).trimmed() ); keywordElem.appendChild( keywordText ); if ( siaFormat ) { - keywordElem.setAttribute( "vocabulary", "SIA_Geo405" ); + keywordElem.setAttribute( QStringLiteral( "vocabulary" ), QStringLiteral( "SIA_Geo405" ) ); } keywordsElem.appendChild( keywordElem ); } @@ -1742,13 +1742,13 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, QString dataUrl = currentLayer->dataUrl(); if ( !dataUrl.isEmpty() ) { - QDomElement dataUrlElem = doc.createElement( "DataURL" ); + QDomElement dataUrlElem = doc.createElement( QStringLiteral( "DataURL" ) ); QString dataUrlFormat = currentLayer->dataUrlFormat(); - dataUrlElem.setAttribute( "format", dataUrlFormat ); - QDomElement dataORElem = doc.createElement( "OnlineResource" ); - dataORElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - dataORElem.setAttribute( "xlink:type", "simple" ); - dataORElem.setAttribute( "xlink:href", dataUrl ); + dataUrlElem.setAttribute( QStringLiteral( "format" ), dataUrlFormat ); + QDomElement dataORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + dataORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + dataORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + dataORElem.setAttribute( QStringLiteral( "xlink:href" ), dataUrl ); dataUrlElem.appendChild( dataORElem ); layerElem.appendChild( dataUrlElem ); } @@ -1757,13 +1757,13 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, QString metadataUrl = currentLayer->metadataUrl(); if ( !metadataUrl.isEmpty() ) { - QDomElement metaUrlElem = doc.createElement( "MetadataURL" ); + QDomElement metaUrlElem = doc.createElement( QStringLiteral( "MetadataURL" ) ); QString metadataUrlFormat = currentLayer->metadataUrlFormat(); - metaUrlElem.setAttribute( "format", metadataUrlFormat ); - QDomElement metaUrlORElem = doc.createElement( "OnlineResource" ); - metaUrlORElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - metaUrlORElem.setAttribute( "xlink:type", "simple" ); - metaUrlORElem.setAttribute( "xlink:href", metadataUrl ); + metaUrlElem.setAttribute( QStringLiteral( "format" ), metadataUrlFormat ); + QDomElement metaUrlORElem = doc.createElement( QStringLiteral( "OnlineResource" ) ); + metaUrlORElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + metaUrlORElem.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + metaUrlORElem.setAttribute( QStringLiteral( "xlink:href" ), metadataUrl ); metaUrlElem.appendChild( metaUrlORElem ); layerElem.appendChild( metaUrlElem ); } @@ -1815,17 +1815,17 @@ QDomDocument QgsWmsProjectParser::getStyles( QStringList& layerList ) const { QDomDocument myDocument = QDomDocument(); - QDomNode header = myDocument.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" ); + QDomNode header = myDocument.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"UTF-8\"" ) ); myDocument.appendChild( header ); // Create the root element - QDomElement root = myDocument.createElementNS( "http://www.opengis.net/sld", "StyledLayerDescriptor" ); - root.setAttribute( "version", "1.1.0" ); - root.setAttribute( "xsi:schemaLocation", "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" ); - root.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" ); - root.setAttribute( "xmlns:se", "http://www.opengis.net/se" ); - root.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + QDomElement root = myDocument.createElementNS( QStringLiteral( "http://www.opengis.net/sld" ), QStringLiteral( "StyledLayerDescriptor" ) ); + root.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.1.0" ) ); + root.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/StyledLayerDescriptor.xsd" ) ); + root.setAttribute( QStringLiteral( "xmlns:ogc" ), QStringLiteral( "http://www.opengis.net/ogc" ) ); + root.setAttribute( QStringLiteral( "xmlns:se" ), QStringLiteral( "http://www.opengis.net/se" ) ); + root.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + root.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); myDocument.appendChild( root ); for ( int i = 0; i < layerList.size(); i++ ) @@ -1833,10 +1833,10 @@ QDomDocument QgsWmsProjectParser::getStyles( QStringList& layerList ) const QString layerName; layerName = layerList.at( i ); // don't use a cache - we may be changing styles - QList currentLayerList = mapLayerFromStyle( layerName, "", false ); + QList currentLayerList = mapLayerFromStyle( layerName, QLatin1String( "" ), false ); if ( currentLayerList.size() < 1 ) { - throw QgsMapServiceException( "Error", QString( "The layer for the TypeName '%1' is not found" ).arg( layerName ) ); + throw QgsMapServiceException( QStringLiteral( "Error" ), QStringLiteral( "The layer for the TypeName '%1' is not found" ).arg( layerName ) ); } for ( int j = 0; j < currentLayerList.size(); j++ ) { @@ -1844,14 +1844,14 @@ QDomDocument QgsWmsProjectParser::getStyles( QStringList& layerList ) const QgsVectorLayer* layer = qobject_cast( currentLayer ); if ( !layer ) { - throw QgsMapServiceException( "Error", QString( "Could not get style because:\n%1" ).arg( "Non-vector layers not supported yet" ) ); + throw QgsMapServiceException( QStringLiteral( "Error" ), QStringLiteral( "Could not get style because:\n%1" ).arg( QStringLiteral( "Non-vector layers not supported yet" ) ) ); } // Create the NamedLayer element - QDomElement namedLayerNode = myDocument.createElement( "NamedLayer" ); + QDomElement namedLayerNode = myDocument.createElement( QStringLiteral( "NamedLayer" ) ); root.appendChild( namedLayerNode ); // store the Name element - QDomElement nameNode = myDocument.createElement( "se:Name" ); + QDomElement nameNode = myDocument.createElement( QStringLiteral( "se:Name" ) ); nameNode.appendChild( myDocument.createTextNode( layerName ) ); namedLayerNode.appendChild( nameNode ); @@ -1875,21 +1875,21 @@ QDomDocument QgsWmsProjectParser::describeLayer( QStringList& layerList, const Q { QDomDocument myDocument = QDomDocument(); - QDomNode header = myDocument.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" ); + QDomNode header = myDocument.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"UTF-8\"" ) ); myDocument.appendChild( header ); // Create the root element - QDomElement root = myDocument.createElementNS( "http://www.opengis.net/sld", "DescribeLayerResponse" ); - root.setAttribute( "xsi:schemaLocation", "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/DescribeLayer.xsd" ); - root.setAttribute( "xmlns:ows", "http://www.opengis.net/ows" ); - root.setAttribute( "xmlns:se", "http://www.opengis.net/se" ); - root.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + QDomElement root = myDocument.createElementNS( QStringLiteral( "http://www.opengis.net/sld" ), QStringLiteral( "DescribeLayerResponse" ) ); + root.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/sld http://schemas.opengis.net/sld/1.1.0/DescribeLayer.xsd" ) ); + root.setAttribute( QStringLiteral( "xmlns:ows" ), QStringLiteral( "http://www.opengis.net/ows" ) ); + root.setAttribute( QStringLiteral( "xmlns:se" ), QStringLiteral( "http://www.opengis.net/se" ) ); + root.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + root.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); myDocument.appendChild( root ); // store the Version element - QDomElement versionNode = myDocument.createElement( "Version" ); - versionNode.appendChild( myDocument.createTextNode( "1.1.0" ) ); + QDomElement versionNode = myDocument.createElement( QStringLiteral( "Version" ) ); + versionNode.appendChild( myDocument.createTextNode( QStringLiteral( "1.1.0" ) ) ); root.appendChild( versionNode ); //Prepare url @@ -1914,10 +1914,10 @@ QDomDocument QgsWmsProjectParser::describeLayer( QStringList& layerList, const Q QString layerName; layerName = layerList.at( i ); // don't use a cache - we may be changing styles - QList currentLayerList = mapLayerFromStyle( layerName, "", false ); + QList currentLayerList = mapLayerFromStyle( layerName, QLatin1String( "" ), false ); if ( currentLayerList.size() < 1 ) { - throw QgsMapServiceException( "InvalidParameterValue", QString( "The layer '%1' is not found" ).arg( layerName ) ); + throw QgsMapServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "The layer '%1' is not found" ).arg( layerName ) ); } for ( int j = 0; j < currentLayerList.size(); j++ ) { @@ -1926,7 +1926,7 @@ QDomDocument QgsWmsProjectParser::describeLayer( QStringList& layerList, const Q #ifdef HAVE_SERVER_PYTHON_PLUGINS if ( !mAccessControl->layerReadPermission( currentLayer ) ) { - throw QgsMapServiceException( "Security", "You are not allowed to access to this layer" ); + throw QgsMapServiceException( QStringLiteral( "Security" ), QStringLiteral( "You are not allowed to access to this layer" ) ); } #endif @@ -1937,41 +1937,41 @@ QDomDocument QgsWmsProjectParser::describeLayer( QStringList& layerList, const Q layerTypeName = currentLayer->shortName(); // Create the NamedLayer element - QDomElement layerNode = myDocument.createElement( "LayerDescription" ); + QDomElement layerNode = myDocument.createElement( QStringLiteral( "LayerDescription" ) ); root.appendChild( layerNode ); // store the owsType element - QDomElement typeNode = myDocument.createElement( "owsType" ); + QDomElement typeNode = myDocument.createElement( QStringLiteral( "owsType" ) ); // store the se:OnlineResource element - QDomElement oResNode = myDocument.createElement( "se:OnlineResource" ); - oResNode.setAttribute( "xlink:type", "simple" ); + QDomElement oResNode = myDocument.createElement( QStringLiteral( "se:OnlineResource" ) ); + oResNode.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); // store the TypeName element - QDomElement nameNode = myDocument.createElement( "TypeName" ); + QDomElement nameNode = myDocument.createElement( QStringLiteral( "TypeName" ) ); if ( currentLayer->type() == QgsMapLayer::VectorLayer ) { - typeNode.appendChild( myDocument.createTextNode( "wfs" ) ); + typeNode.appendChild( myDocument.createTextNode( QStringLiteral( "wfs" ) ) ); if ( wfsLayers.indexOf( layerTypeName ) != -1 ) { - oResNode.setAttribute( "xlink:href", wfsHrefString ); + oResNode.setAttribute( QStringLiteral( "xlink:href" ), wfsHrefString ); } // store the se:FeatureTypeName element - QDomElement typeNameNode = myDocument.createElement( "se:FeatureTypeName" ); + QDomElement typeNameNode = myDocument.createElement( QStringLiteral( "se:FeatureTypeName" ) ); typeNameNode.appendChild( myDocument.createTextNode( layerTypeName ) ); nameNode.appendChild( typeNameNode ); } else if ( currentLayer->type() == QgsMapLayer::RasterLayer ) { - typeNode.appendChild( myDocument.createTextNode( "wcs" ) ); + typeNode.appendChild( myDocument.createTextNode( QStringLiteral( "wcs" ) ) ); if ( wcsLayers.indexOf( layerTypeName ) != -1 ) { - oResNode.setAttribute( "xlink:href", wcsHrefString ); + oResNode.setAttribute( QStringLiteral( "xlink:href" ), wcsHrefString ); } // store the se:CoverageTypeName element - QDomElement typeNameNode = myDocument.createElement( "se:CoverageTypeName" ); + QDomElement typeNameNode = myDocument.createElement( QStringLiteral( "se:CoverageTypeName" ) ); typeNameNode.appendChild( myDocument.createTextNode( layerTypeName ) ); nameNode.appendChild( typeNameNode ); } @@ -2002,13 +2002,13 @@ bool QgsWmsProjectParser::featureInfoWithWktGeometry() const { return false; } - QDomElement wktElem = propertiesElem.firstChildElement( "WMSAddWktGeometry" ); + QDomElement wktElem = propertiesElem.firstChildElement( QStringLiteral( "WMSAddWktGeometry" ) ); if ( wktElem.isNull() ) { return false; } - return ( wktElem.text().compare( "true", Qt::CaseInsensitive ) == 0 ); + return ( wktElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); } bool QgsWmsProjectParser::segmentizeFeatureInfoWktGeometry() const @@ -2024,13 +2024,13 @@ bool QgsWmsProjectParser::segmentizeFeatureInfoWktGeometry() const return false; } - QDomElement segmentizeElem = propertiesElem.firstChildElement( "WMSSegmentizeFeatureInfoGeometry" ); + QDomElement segmentizeElem = propertiesElem.firstChildElement( QStringLiteral( "WMSSegmentizeFeatureInfoGeometry" ) ); if ( segmentizeElem.isNull() ) { return false; } - return( segmentizeElem.text().compare( "true", Qt::CaseInsensitive ) == 0 ); + return( segmentizeElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); } QHash QgsWmsProjectParser::featureInfoLayerAliasMap() const @@ -2044,12 +2044,12 @@ QHash QgsWmsProjectParser::featureInfoLayerAliasMap() const //WMSFeatureInfoAliasLayers QStringList aliasLayerStringList; - QDomElement featureInfoAliasLayersElem = propertiesElem.firstChildElement( "WMSFeatureInfoAliasLayers" ); + QDomElement featureInfoAliasLayersElem = propertiesElem.firstChildElement( QStringLiteral( "WMSFeatureInfoAliasLayers" ) ); if ( featureInfoAliasLayersElem.isNull() ) { return aliasMap; } - QDomNodeList aliasLayerValueList = featureInfoAliasLayersElem.elementsByTagName( "value" ); + QDomNodeList aliasLayerValueList = featureInfoAliasLayersElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < aliasLayerValueList.size(); ++i ) { aliasLayerStringList << aliasLayerValueList.at( i ).toElement().text(); @@ -2057,12 +2057,12 @@ QHash QgsWmsProjectParser::featureInfoLayerAliasMap() const //WMSFeatureInfoLayerAliases QStringList layerAliasStringList; - QDomElement featureInfoLayerAliasesElem = propertiesElem.firstChildElement( "WMSFeatureInfoLayerAliases" ); + QDomElement featureInfoLayerAliasesElem = propertiesElem.firstChildElement( QStringLiteral( "WMSFeatureInfoLayerAliases" ) ); if ( featureInfoLayerAliasesElem.isNull() ) { return aliasMap; } - QDomNodeList layerAliasesValueList = featureInfoLayerAliasesElem.elementsByTagName( "value" ); + QDomNodeList layerAliasesValueList = featureInfoLayerAliasesElem.elementsByTagName( QStringLiteral( "value" ) ); for ( int i = 0; i < layerAliasesValueList.size(); ++i ) { layerAliasStringList << layerAliasesValueList.at( i ).toElement().text(); @@ -2084,7 +2084,7 @@ QString QgsWmsProjectParser::featureInfoDocumentElement( const QString& defaultV { return defaultValue; } - QDomElement featureInfoDocumentElem = propertiesElem.firstChildElement( "WMSFeatureInfoDocumentElement" ); + QDomElement featureInfoDocumentElem = propertiesElem.firstChildElement( QStringLiteral( "WMSFeatureInfoDocumentElement" ) ); if ( featureInfoDocumentElem.isNull() ) { return defaultValue; @@ -2097,12 +2097,12 @@ QString QgsWmsProjectParser::featureInfoDocumentElementNS() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( propertiesElem.isNull() ) { - return ""; + return QLatin1String( "" ); } - QDomElement featureInfoDocumentNSElem = propertiesElem.firstChildElement( "WMSFeatureInfoDocumentElementNS" ); + QDomElement featureInfoDocumentNSElem = propertiesElem.firstChildElement( QStringLiteral( "WMSFeatureInfoDocumentElementNS" ) ); if ( featureInfoDocumentNSElem.isNull() ) { - return ""; + return QLatin1String( "" ); } return featureInfoDocumentNSElem.text(); } @@ -2112,12 +2112,12 @@ QString QgsWmsProjectParser::featureInfoSchema() const QDomElement propertiesElem = mProjectParser->propertiesElem(); if ( propertiesElem.isNull() ) { - return ""; + return QLatin1String( "" ); } - QDomElement featureInfoSchemaElem = propertiesElem.firstChildElement( "WMSFeatureInfoSchema" ); + QDomElement featureInfoSchemaElem = propertiesElem.firstChildElement( QStringLiteral( "WMSFeatureInfoSchema" ) ); if ( featureInfoSchemaElem.isNull() ) { - return ""; + return QLatin1String( "" ); } return featureInfoSchemaElem.text(); } @@ -2131,14 +2131,14 @@ bool QgsWmsProjectParser::featureInfoFormatSIA2045() const return false; } - QDomElement sia2045Elem = propertiesElem.firstChildElement( "WMSInfoFormatSIA2045" ); + QDomElement sia2045Elem = propertiesElem.firstChildElement( QStringLiteral( "WMSInfoFormatSIA2045" ) ); if ( sia2045Elem.isNull() ) { return false; } - if ( sia2045Elem.text().compare( "enabled", Qt::CaseInsensitive ) == 0 - || sia2045Elem.text().compare( "true", Qt::CaseInsensitive ) == 0 ) + if ( sia2045Elem.text().compare( QLatin1String( "enabled" ), Qt::CaseInsensitive ) == 0 + || sia2045Elem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ) { return true; } @@ -2164,8 +2164,8 @@ void QgsWmsProjectParser::drawOverlays( QPainter* p, int dpi, int width, int hei continue; } - int itemWidth = annotationElem.attribute( "frameWidth", "0" ).toInt(); - int itemHeight = annotationElem.attribute( "frameHeight", "0" ).toInt(); + int itemWidth = annotationElem.attribute( QStringLiteral( "frameWidth" ), QStringLiteral( "0" ) ).toInt(); + int itemHeight = annotationElem.attribute( QStringLiteral( "frameHeight" ), QStringLiteral( "0" ) ).toInt(); //calculate item position double xPos, yPos; @@ -2189,8 +2189,8 @@ void QgsWmsProjectParser::drawOverlays( QPainter* p, int dpi, int width, int hei for ( ; svgIt != mSvgAnnotationElems.constEnd(); ++svgIt ) { annotationElem = svgIt->second; - int itemWidth = annotationElem.attribute( "frameWidth", "0" ).toInt() * scaleFactor; - int itemHeight = annotationElem.attribute( "frameHeight", "0" ).toInt() * scaleFactor; + int itemWidth = annotationElem.attribute( QStringLiteral( "frameWidth" ), QStringLiteral( "0" ) ).toInt() * scaleFactor; + int itemHeight = annotationElem.attribute( QStringLiteral( "frameHeight" ), QStringLiteral( "0" ) ).toInt() * scaleFactor; //calculate item position double xPos, yPos; @@ -2237,7 +2237,7 @@ void QgsWmsProjectParser::loadLabelSettings( QgsLabelingEngineInterface* lbl ) c return; } - QDomElement palElem = propertiesElem.firstChildElement( "PAL" ); + QDomElement palElem = propertiesElem.firstChildElement( QStringLiteral( "PAL" ) ); if ( palElem.isNull() ) { return; @@ -2248,21 +2248,21 @@ void QgsWmsProjectParser::loadLabelSettings( QgsLabelingEngineInterface* lbl ) c pal->numCandidatePositions( candPoint, candLine, candPoly ); //mCandPoint - QDomElement candPointElem = palElem.firstChildElement( "CandidatesPoint" ); + QDomElement candPointElem = palElem.firstChildElement( QStringLiteral( "CandidatesPoint" ) ); if ( !candPointElem.isNull() ) { candPoint = candPointElem.text().toInt(); } //mCandLine - QDomElement candLineElem = palElem.firstChildElement( "CandidatesLine" ); + QDomElement candLineElem = palElem.firstChildElement( QStringLiteral( "CandidatesLine" ) ); if ( !candLineElem.isNull() ) { candLine = candLineElem.text().toInt(); } //mCandPolygon - QDomElement candPolyElem = palElem.firstChildElement( "CandidatesPolygon" ); + QDomElement candPolyElem = palElem.firstChildElement( QStringLiteral( "CandidatesPolygon" ) ); if ( !candPolyElem.isNull() ) { candPoly = candPolyElem.text().toInt(); @@ -2271,24 +2271,24 @@ void QgsWmsProjectParser::loadLabelSettings( QgsLabelingEngineInterface* lbl ) c pal->setNumCandidatePositions( candPoint, candLine, candPoly ); //mShowingCandidates - QDomElement showCandElem = palElem.firstChildElement( "ShowingCandidates" ); + QDomElement showCandElem = palElem.firstChildElement( QStringLiteral( "ShowingCandidates" ) ); if ( !showCandElem.isNull() ) { - pal->setShowingCandidates( showCandElem.text().compare( "true", Qt::CaseInsensitive ) == 0 ); + pal->setShowingCandidates( showCandElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); } //mShowingAllLabels - QDomElement showAllLabelsElem = palElem.firstChildElement( "ShowingAllLabels" ); + QDomElement showAllLabelsElem = palElem.firstChildElement( QStringLiteral( "ShowingAllLabels" ) ); if ( !showAllLabelsElem.isNull() ) { - pal->setShowingAllLabels( showAllLabelsElem.text().compare( "true", Qt::CaseInsensitive ) == 0 ); + pal->setShowingAllLabels( showAllLabelsElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); } //mShowingPartialsLabels - QDomElement showPartialsLabelsElem = palElem.firstChildElement( "ShowingPartialsLabels" ); + QDomElement showPartialsLabelsElem = palElem.firstChildElement( QStringLiteral( "ShowingPartialsLabels" ) ); if ( !showPartialsLabelsElem.isNull() ) { - pal->setShowingPartialsLabels( showPartialsLabelsElem.text().compare( "true", Qt::CaseInsensitive ) == 0 ); + pal->setShowingPartialsLabels( showPartialsLabelsElem.text().compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0 ); } //mDrawOutlineLabels @@ -2307,7 +2307,7 @@ int QgsWmsProjectParser::nLayers() const void QgsWmsProjectParser::serviceCapabilities( QDomElement& parentElement, QDomDocument& doc ) const { - mProjectParser->serviceCapabilities( parentElement, doc, "WMS", featureInfoFormatSIA2045() ); + mProjectParser->serviceCapabilities( parentElement, doc, QStringLiteral( "WMS" ), featureInfoFormatSIA2045() ); } QDomElement QgsWmsProjectParser::composerByName( const QString& composerName ) const @@ -2323,7 +2323,7 @@ QDomElement QgsWmsProjectParser::composerByName( const QString& composerName ) c for ( ; composerIt != composerElemList.constEnd(); ++composerIt ) { QDomElement currentComposerElem = *composerIt; - if ( currentComposerElem.attribute( "title" ) == composerName ) + if ( currentComposerElem.attribute( QStringLiteral( "title" ) ) == composerName ) { return currentComposerElem; } @@ -2346,7 +2346,7 @@ QgsLayerTreeGroup* QgsWmsProjectParser::projectLayerTreeGroup() const { return rootGroup; } - QDomElement layerTreeElem = qgisElem.firstChildElement( "layer-tree-group" ); + QDomElement layerTreeElem = qgisElem.firstChildElement( QStringLiteral( "layer-tree-group" ) ); if ( layerTreeElem.isNull() ) { QgsLayerTreeUtils::readOldLegend( rootGroup, mProjectParser->legendElem() ); @@ -2359,8 +2359,8 @@ bool QgsWmsProjectParser::annotationPosition( const QDomElement& elem, double sc { Q_UNUSED( scaleFactor ); - xPos = elem.attribute( "canvasPosX" ).toDouble() / scaleFactor; - yPos = elem.attribute( "canvasPosY" ).toDouble() / scaleFactor; + xPos = elem.attribute( QStringLiteral( "canvasPosX" ) ).toDouble() / scaleFactor; + yPos = elem.attribute( QStringLiteral( "canvasPosY" ) ).toDouble() / scaleFactor; return true; } @@ -2372,13 +2372,13 @@ void QgsWmsProjectParser::drawAnnotationRectangle( QPainter* p, const QDomElemen return; } - QColor backgroundColor( elem.attribute( "frameBackgroundColor", "#000000" ) ); - backgroundColor.setAlpha( elem.attribute( "frameBackgroundColorAlpha", "255" ).toInt() ); + QColor backgroundColor( elem.attribute( QStringLiteral( "frameBackgroundColor" ), QStringLiteral( "#000000" ) ) ); + backgroundColor.setAlpha( elem.attribute( QStringLiteral( "frameBackgroundColorAlpha" ), QStringLiteral( "255" ) ).toInt() ); p->setBrush( QBrush( backgroundColor ) ); - QColor frameColor( elem.attribute( "frameColor", "#000000" ) ); - frameColor.setAlpha( elem.attribute( "frameColorAlpha", "255" ).toInt() ); + QColor frameColor( elem.attribute( QStringLiteral( "frameColor" ), QStringLiteral( "#000000" ) ) ); + frameColor.setAlpha( elem.attribute( QStringLiteral( "frameColorAlpha" ), QStringLiteral( "255" ) ).toInt() ); QPen framePen( frameColor ); - framePen.setWidth( elem.attribute( "frameBorderWidth", "1" ).toInt() ); + framePen.setWidth( elem.attribute( QStringLiteral( "frameBorderWidth" ), QStringLiteral( "1" ) ).toInt() ); p->setPen( framePen ); p->drawRect( QRectF( xPos, yPos, itemWidth, itemHeight ) ); @@ -2396,17 +2396,17 @@ void QgsWmsProjectParser::createTextAnnotationItems() //text annotations QDomElement qgisElem = xmlDoc->documentElement(); - QDomNodeList textAnnotationList = qgisElem.elementsByTagName( "TextAnnotationItem" ); + QDomNodeList textAnnotationList = qgisElem.elementsByTagName( QStringLiteral( "TextAnnotationItem" ) ); QDomElement textAnnotationElem; QDomElement annotationElem; for ( int i = 0; i < textAnnotationList.size(); ++i ) { textAnnotationElem = textAnnotationList.at( i ).toElement(); - annotationElem = textAnnotationElem.firstChildElement( "AnnotationItem" ); - if ( !annotationElem.isNull() && annotationElem.attribute( "mapPositionFixed" ) != "1" ) + annotationElem = textAnnotationElem.firstChildElement( QStringLiteral( "AnnotationItem" ) ); + if ( !annotationElem.isNull() && annotationElem.attribute( QStringLiteral( "mapPositionFixed" ) ) != QLatin1String( "1" ) ) { QTextDocument* textDoc = new QTextDocument(); - textDoc->setHtml( textAnnotationElem.attribute( "document" ) ); + textDoc->setHtml( textAnnotationElem.attribute( QStringLiteral( "document" ) ) ); mTextAnnotationItems.push_back( qMakePair( textDoc, annotationElem ) ); } } @@ -2422,17 +2422,17 @@ void QgsWmsProjectParser::createSvgAnnotationItems() } QDomElement qgisElem = xmlDoc->documentElement(); - QDomNodeList svgAnnotationList = qgisElem.elementsByTagName( "SVGAnnotationItem" ); + QDomNodeList svgAnnotationList = qgisElem.elementsByTagName( QStringLiteral( "SVGAnnotationItem" ) ); QDomElement svgAnnotationElem; QDomElement annotationElem; for ( int i = 0; i < svgAnnotationList.size(); ++i ) { svgAnnotationElem = svgAnnotationList.at( i ).toElement(); - annotationElem = svgAnnotationElem.firstChildElement( "AnnotationItem" ); - if ( !annotationElem.isNull() && annotationElem.attribute( "mapPositionFixed" ) != "1" ) + annotationElem = svgAnnotationElem.firstChildElement( QStringLiteral( "AnnotationItem" ) ); + if ( !annotationElem.isNull() && annotationElem.attribute( QStringLiteral( "mapPositionFixed" ) ) != QLatin1String( "1" ) ) { QSvgRenderer* svg = new QSvgRenderer(); - if ( svg->load( mProjectParser->convertToAbsolutePath( svgAnnotationElem.attribute( "file" ) ) ) ) + if ( svg->load( mProjectParser->convertToAbsolutePath( svgAnnotationElem.attribute( QStringLiteral( "file" ) ) ) ) ) { mSvgAnnotationElems.push_back( qMakePair( svg, annotationElem ) ); } @@ -2467,14 +2467,14 @@ void QgsWmsProjectParser::cleanupTextAnnotationItems() QString QgsWmsProjectParser::getCapaServiceUrl( QDomDocument& doc ) const { QString url; - QDomNodeList getCapNodeList = doc.elementsByTagName( "GetCapabilities" ); + QDomNodeList getCapNodeList = doc.elementsByTagName( QStringLiteral( "GetCapabilities" ) ); if ( getCapNodeList.count() > 0 ) { QDomElement getCapElem = getCapNodeList.at( 0 ).toElement(); - QDomNodeList getCapORNodeList = getCapElem.elementsByTagName( "OnlineResource" ); + QDomNodeList getCapORNodeList = getCapElem.elementsByTagName( QStringLiteral( "OnlineResource" ) ); if ( getCapORNodeList.count() > 0 ) { - url = getCapORNodeList.at( 0 ).toElement().attribute( "xlink:href", "" ); + url = getCapORNodeList.at( 0 ).toElement().attribute( QStringLiteral( "xlink:href" ), QLatin1String( "" ) ); } } diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index 349d1072374a..ce9047ad6ee9 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -140,38 +140,38 @@ void QgsWmsServer::executeRequest() } //request type - QString request = mParameters.value( "REQUEST" ); + QString request = mParameters.value( QStringLiteral( "REQUEST" ) ); if ( request.isEmpty() ) { - QgsMessageLog::logMessage( "unable to find 'REQUEST' parameter, exiting..." ); - mRequestHandler->setServiceException( QgsMapServiceException( "OperationNotSupported", "Please check the value of the REQUEST parameter" ) ); + QgsMessageLog::logMessage( QStringLiteral( "unable to find 'REQUEST' parameter, exiting..." ) ); + mRequestHandler->setServiceException( QgsMapServiceException( QStringLiteral( "OperationNotSupported" ), QStringLiteral( "Please check the value of the REQUEST parameter" ) ) ); cleanupAfterRequest(); return; } //version - QString version = mParameters.value( "VERSION", "1.3.0" ); - bool getProjectSettings = ( request.compare( "GetProjectSettings", Qt::CaseInsensitive ) == 0 ); + QString version = mParameters.value( QStringLiteral( "VERSION" ), QStringLiteral( "1.3.0" ) ); + bool getProjectSettings = ( request.compare( QLatin1String( "GetProjectSettings" ), Qt::CaseInsensitive ) == 0 ); if ( getProjectSettings ) { - version = "1.3.0"; //getProjectSettings extends WMS 1.3.0 capabilities + version = QStringLiteral( "1.3.0" ); //getProjectSettings extends WMS 1.3.0 capabilities } //GetCapabilities - if ( request.compare( "GetCapabilities", Qt::CaseInsensitive ) == 0 || getProjectSettings ) + if ( request.compare( QLatin1String( "GetCapabilities" ), Qt::CaseInsensitive ) == 0 || getProjectSettings ) { QStringList cacheKeyList; - cacheKeyList << ( getProjectSettings ? "projectSettings" : version ); + cacheKeyList << ( getProjectSettings ? QStringLiteral( "projectSettings" ) : version ); cacheKeyList << getenv( "SERVER_NAME" ); bool cache = true; #ifdef HAVE_SERVER_PYTHON_PLUGINS cache = mAccessControl->fillCacheKey( cacheKeyList ); #endif - QString cacheKey = cacheKeyList.join( "-" ); + QString cacheKey = cacheKeyList.join( QStringLiteral( "-" ) ); const QDomDocument* capabilitiesDocument = mCapabilitiesCache->searchCapabilitiesDocument( mConfigFilePath, cacheKey ); if ( !capabilitiesDocument ) //capabilities xml not in cache. Create a new one { - QgsMessageLog::logMessage( "Capabilities document not found in cache" ); + QgsMessageLog::logMessage( QStringLiteral( "Capabilities document not found in cache" ) ); QDomDocument doc; try { @@ -196,7 +196,7 @@ void QgsWmsServer::executeRequest() } else { - QgsMessageLog::logMessage( "Found capabilities document in cache" ); + QgsMessageLog::logMessage( QStringLiteral( "Found capabilities document in cache" ) ); } if ( capabilitiesDocument ) @@ -205,11 +205,11 @@ void QgsWmsServer::executeRequest() } } //GetMap - else if ( request.compare( "GetMap", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetMap" ), Qt::CaseInsensitive ) == 0 ) { //export as dxf - QString format = mParameters.value( "FORMAT" ); - if ( format.compare( "application/dxf", Qt::CaseInsensitive ) == 0 ) + QString format = mParameters.value( QStringLiteral( "FORMAT" ) ); + if ( format.compare( QLatin1String( "application/dxf" ), Qt::CaseInsensitive ) == 0 ) { try { @@ -219,7 +219,7 @@ void QgsWmsServer::executeRequest() } catch ( QgsMapServiceException& ex ) { - QgsMessageLog::logMessage( "Caught exception during GetMap request" ); + QgsMessageLog::logMessage( QStringLiteral( "Caught exception during GetMap request" ) ); mRequestHandler->setServiceException( ex ); cleanupAfterRequest(); return; @@ -233,7 +233,7 @@ void QgsWmsServer::executeRequest() } catch ( QgsMapServiceException& ex ) { - QgsMessageLog::logMessage( "Caught exception during GetMap request" ); + QgsMessageLog::logMessage( QStringLiteral( "Caught exception during GetMap request" ) ); mRequestHandler->setServiceException( ex ); cleanupAfterRequest(); return; @@ -241,19 +241,19 @@ void QgsWmsServer::executeRequest() if ( result ) { - QgsMessageLog::logMessage( "Setting GetMap response" ); - mRequestHandler->setGetMapResponse( "WMS", result, getImageQuality() ); - QgsMessageLog::logMessage( "Response sent" ); + QgsMessageLog::logMessage( QStringLiteral( "Setting GetMap response" ) ); + mRequestHandler->setGetMapResponse( QStringLiteral( "WMS" ), result, getImageQuality() ); + QgsMessageLog::logMessage( QStringLiteral( "Response sent" ) ); } else { //do some error handling - QgsMessageLog::logMessage( "result image is 0" ); + QgsMessageLog::logMessage( QStringLiteral( "result image is 0" ) ); } delete result; } //GetFeatureInfo - else if ( request.compare( "GetFeatureInfo", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetFeatureInfo" ), Qt::CaseInsensitive ) == 0 ) { QDomDocument featureInfoDoc; try @@ -271,11 +271,11 @@ void QgsWmsServer::executeRequest() return; } - QString infoFormat = mParameters.value( "INFO_FORMAT", "text/plain" ); + QString infoFormat = mParameters.value( QStringLiteral( "INFO_FORMAT" ), QStringLiteral( "text/plain" ) ); mRequestHandler->setGetFeatureInfoResponse( featureInfoDoc, infoFormat ); } //GetContext - else if ( request.compare( "GetContext", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetContext" ), Qt::CaseInsensitive ) == 0 ) { try { @@ -288,7 +288,7 @@ void QgsWmsServer::executeRequest() } } //GetSchemaExtension - else if ( request.compare( "GetSchemaExtension", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetSchemaExtension" ), Qt::CaseInsensitive ) == 0 ) { try { @@ -301,7 +301,7 @@ void QgsWmsServer::executeRequest() } } //GetStyle for compatibility with earlier QGIS versions - else if ( request.compare( "GetStyle", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetStyle" ), Qt::CaseInsensitive ) == 0 ) { try { @@ -314,7 +314,7 @@ void QgsWmsServer::executeRequest() } } //GetStyles - else if ( request.compare( "GetStyles", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetStyles" ), Qt::CaseInsensitive ) == 0 ) { // GetStyles is defined for WMS1.1.1/SLD1.0 // and in qgis-server WMS1.3.0 extension @@ -329,7 +329,7 @@ void QgsWmsServer::executeRequest() } } //GetStyles - else if ( request.compare( "DescribeLayer", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "DescribeLayer" ), Qt::CaseInsensitive ) == 0 ) { // DescribeLayer is defined for WMS1.1.1/SLD1.0 // and in qgis-server WMS1.3.0 extension @@ -344,8 +344,8 @@ void QgsWmsServer::executeRequest() } } //GetLegendGraphic - else if ( request.compare( "GetLegendGraphic", Qt::CaseInsensitive ) == 0 || - request.compare( "GetLegendGraphics", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetLegendGraphic" ), Qt::CaseInsensitive ) == 0 || + request.compare( QLatin1String( "GetLegendGraphics" ), Qt::CaseInsensitive ) == 0 ) // GetLegendGraphics for compatibility with earlier QGIS versions { QImage* result = nullptr; @@ -355,26 +355,26 @@ void QgsWmsServer::executeRequest() } catch ( QgsMapServiceException& ex ) { - QgsMessageLog::logMessage( "Caught exception during GetLegendGraphic request" ); + QgsMessageLog::logMessage( QStringLiteral( "Caught exception during GetLegendGraphic request" ) ); mRequestHandler->setServiceException( ex ); } if ( result ) { - QgsMessageLog::logMessage( "Setting GetLegendGraphic response" ); + QgsMessageLog::logMessage( QStringLiteral( "Setting GetLegendGraphic response" ) ); //setting is the same for GetMap and GetLegendGraphic - mRequestHandler->setGetMapResponse( "WMS", result, getImageQuality() ); - QgsMessageLog::logMessage( "Response sent" ); + mRequestHandler->setGetMapResponse( QStringLiteral( "WMS" ), result, getImageQuality() ); + QgsMessageLog::logMessage( QStringLiteral( "Response sent" ) ); } else { //do some error handling - QgsMessageLog::logMessage( "result image is 0" ); + QgsMessageLog::logMessage( QStringLiteral( "result image is 0" ) ); } delete result; } //GetPrint - else if ( request.compare( "GetPrint", Qt::CaseInsensitive ) == 0 ) + else if ( request.compare( QLatin1String( "GetPrint" ), Qt::CaseInsensitive ) == 0 ) { QByteArray* printOutput = nullptr; try @@ -394,7 +394,7 @@ void QgsWmsServer::executeRequest() } else//unknown request { - QgsMapServiceException e( "OperationNotSupported", "Operation " + request + " not supported" ); + QgsMapServiceException e( QStringLiteral( "OperationNotSupported" ), "Operation " + request + " not supported" ); mRequestHandler->setServiceException( e ); } cleanupAfterRequest(); @@ -404,7 +404,7 @@ void QgsWmsServer::appendFormats( QDomDocument &doc, QDomElement &elem, const QS { Q_FOREACH ( const QString& format, formats ) { - QDomElement formatElem = doc.createElement( "Format"/*wms:Format*/ ); + QDomElement formatElem = doc.createElement( QStringLiteral( "Format" )/*wms:Format*/ ); formatElem.appendChild( doc.createTextNode( format ) ); elem.appendChild( formatElem ); } @@ -412,7 +412,7 @@ void QgsWmsServer::appendFormats( QDomDocument &doc, QDomElement &elem, const QS QDomDocument QgsWmsServer::getCapabilities( const QString& version, bool fullProjectInformation ) { - QgsMessageLog::logMessage( "Entering." ); + QgsMessageLog::logMessage( QStringLiteral( "Entering." ) ); QDomDocument doc; QDomElement wmsCapabilitiesElement; @@ -427,36 +427,36 @@ QDomDocument QgsWmsServer::getCapabilities( const QString& version, bool fullPro hrefString = serviceUrl(); } - if ( version == "1.1.1" ) + if ( version == QLatin1String( "1.1.1" ) ) { - doc = QDomDocument( "WMT_MS_Capabilities SYSTEM 'http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd'" ); //WMS 1.1.1 needs DOCTYPE "SYSTEM http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd" + doc = QDomDocument( QStringLiteral( "WMT_MS_Capabilities SYSTEM 'http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd'" ) ); //WMS 1.1.1 needs DOCTYPE "SYSTEM http://schemas.opengis.net/wms/1.1.1/WMS_MS_Capabilities.dtd" addXmlDeclaration( doc ); - wmsCapabilitiesElement = doc.createElement( "WMT_MS_Capabilities"/*wms:WMS_Capabilities*/ ); + wmsCapabilitiesElement = doc.createElement( QStringLiteral( "WMT_MS_Capabilities" )/*wms:WMS_Capabilities*/ ); } else // 1.3.0 as default { addXmlDeclaration( doc ); - wmsCapabilitiesElement = doc.createElement( "WMS_Capabilities"/*wms:WMS_Capabilities*/ ); - wmsCapabilitiesElement.setAttribute( "xmlns", "http://www.opengis.net/wms" ); - wmsCapabilitiesElement.setAttribute( "xmlns:sld", "http://www.opengis.net/sld" ); - wmsCapabilitiesElement.setAttribute( "xmlns:qgs", "http://www.qgis.org/wms" ); - wmsCapabilitiesElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - QString schemaLocation = "http://www.opengis.net/wms"; - schemaLocation += " http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd"; - schemaLocation += " http://www.opengis.net/sld"; - schemaLocation += " http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd"; - schemaLocation += " http://www.qgis.org/wms"; + wmsCapabilitiesElement = doc.createElement( QStringLiteral( "WMS_Capabilities" )/*wms:WMS_Capabilities*/ ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.opengis.net/wms" ) ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:sld" ), QStringLiteral( "http://www.opengis.net/sld" ) ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QStringLiteral( "http://www.qgis.org/wms" ) ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + QString schemaLocation = QStringLiteral( "http://www.opengis.net/wms" ); + schemaLocation += QLatin1String( " http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd" ); + schemaLocation += QLatin1String( " http://www.opengis.net/sld" ); + schemaLocation += QLatin1String( " http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd" ); + schemaLocation += QLatin1String( " http://www.qgis.org/wms" ); if ( mConfigParser && mConfigParser->wmsInspireActivated() ) { - wmsCapabilitiesElement.setAttribute( "xmlns:inspire_common", "http://inspire.ec.europa.eu/schemas/common/1.0" ); - wmsCapabilitiesElement.setAttribute( "xmlns:inspire_vs", "http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" ); - schemaLocation += " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0"; - schemaLocation += " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0/inspire_vs.xsd"; + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:inspire_common" ), QStringLiteral( "http://inspire.ec.europa.eu/schemas/common/1.0" ) ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xmlns:inspire_vs" ), QStringLiteral( "http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" ) ); + schemaLocation += QLatin1String( " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0" ); + schemaLocation += QLatin1String( " http://inspire.ec.europa.eu/schemas/inspire_vs/1.0/inspire_vs.xsd" ); } schemaLocation += " " + hrefString + "SERVICE=WMS&REQUEST=GetSchemaExtension"; - wmsCapabilitiesElement.setAttribute( "xsi:schemaLocation", schemaLocation ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), schemaLocation ); } - wmsCapabilitiesElement.setAttribute( "version", version ); + wmsCapabilitiesElement.setAttribute( QStringLiteral( "version" ), version ); doc.appendChild( wmsCapabilitiesElement ); //todo: add service capabilities @@ -466,45 +466,45 @@ QDomDocument QgsWmsServer::getCapabilities( const QString& version, bool fullPro } //wms:Capability element - QDomElement capabilityElement = doc.createElement( "Capability"/*wms:Capability*/ ); + QDomElement capabilityElement = doc.createElement( QStringLiteral( "Capability" )/*wms:Capability*/ ); wmsCapabilitiesElement.appendChild( capabilityElement ); //wms:Request element - QDomElement requestElement = doc.createElement( "Request"/*wms:Request*/ ); + QDomElement requestElement = doc.createElement( QStringLiteral( "Request" )/*wms:Request*/ ); capabilityElement.appendChild( requestElement ); - QDomElement dcpTypeElement = doc.createElement( "DCPType"/*wms:DCPType*/ ); - QDomElement httpElement = doc.createElement( "HTTP"/*wms:HTTP*/ ); + QDomElement dcpTypeElement = doc.createElement( QStringLiteral( "DCPType" )/*wms:DCPType*/ ); + QDomElement httpElement = doc.createElement( QStringLiteral( "HTTP" )/*wms:HTTP*/ ); dcpTypeElement.appendChild( httpElement ); QDomElement elem; //wms:GetCapabilities - elem = doc.createElement( "GetCapabilities"/*wms:GetCapabilities*/ ); - appendFormats( doc, elem, QStringList() << ( version == "1.1.1" ? "application/vnd.ogc.wms_xml" : "text/xml" ) ); + elem = doc.createElement( QStringLiteral( "GetCapabilities" )/*wms:GetCapabilities*/ ); + appendFormats( doc, elem, QStringList() << ( version == QLatin1String( "1.1.1" ) ? "application/vnd.ogc.wms_xml" : "text/xml" ) ); elem.appendChild( dcpTypeElement ); requestElement.appendChild( elem ); // SOAP platform //only give this information if it is not a WMS request to be in sync with the WMS capabilities schema - QMap::const_iterator service_it = mParameters.constFind( "SERVICE" ); - if ( service_it != mParameters.constEnd() && service_it.value().compare( "WMS", Qt::CaseInsensitive ) != 0 ) + QMap::const_iterator service_it = mParameters.constFind( QStringLiteral( "SERVICE" ) ); + if ( service_it != mParameters.constEnd() && service_it.value().compare( QLatin1String( "WMS" ), Qt::CaseInsensitive ) != 0 ) { - QDomElement soapElement = doc.createElement( "SOAP"/*wms:SOAP*/ ); + QDomElement soapElement = doc.createElement( QStringLiteral( "SOAP" )/*wms:SOAP*/ ); httpElement.appendChild( soapElement ); - QDomElement soapResourceElement = doc.createElement( "OnlineResource"/*wms:OnlineResource*/ ); - soapResourceElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - soapResourceElement.setAttribute( "xlink:type", "simple" ); - soapResourceElement.setAttribute( "xlink:href", hrefString ); + QDomElement soapResourceElement = doc.createElement( QStringLiteral( "OnlineResource" )/*wms:OnlineResource*/ ); + soapResourceElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + soapResourceElement.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + soapResourceElement.setAttribute( QStringLiteral( "xlink:href" ), hrefString ); soapElement.appendChild( soapResourceElement ); } //only Get supported for the moment - QDomElement getElement = doc.createElement( "Get"/*wms:Get*/ ); + QDomElement getElement = doc.createElement( QStringLiteral( "Get" )/*wms:Get*/ ); httpElement.appendChild( getElement ); - QDomElement olResourceElement = doc.createElement( "OnlineResource"/*wms:OnlineResource*/ ); - olResourceElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - olResourceElement.setAttribute( "xlink:type", "simple" ); - olResourceElement.setAttribute( "xlink:href", hrefString ); + QDomElement olResourceElement = doc.createElement( QStringLiteral( "OnlineResource" )/*wms:OnlineResource*/ ); + olResourceElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + olResourceElement.setAttribute( QStringLiteral( "xlink:type" ), QStringLiteral( "simple" ) ); + olResourceElement.setAttribute( QStringLiteral( "xlink:href" ), hrefString ); getElement.appendChild( olResourceElement ); #if 0 @@ -520,59 +520,59 @@ QDomDocument QgsWmsServer::getCapabilities( const QString& version, bool fullPro #endif //wms:GetMap - elem = doc.createElement( "GetMap"/*wms:GetMap*/ ); - appendFormats( doc, elem, QStringList() << "image/jpeg" << "image/png" << "image/png; mode=16bit" << "image/png; mode=8bit" << "image/png; mode=1bit" << "application/dxf" ); + elem = doc.createElement( QStringLiteral( "GetMap" )/*wms:GetMap*/ ); + appendFormats( doc, elem, QStringList() << QStringLiteral( "image/jpeg" ) << QStringLiteral( "image/png" ) << QStringLiteral( "image/png; mode=16bit" ) << QStringLiteral( "image/png; mode=8bit" ) << QStringLiteral( "image/png; mode=1bit" ) << QStringLiteral( "application/dxf" ) ); elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElement.appendChild( elem ); //wms:GetFeatureInfo - elem = doc.createElement( "GetFeatureInfo" ); - appendFormats( doc, elem, QStringList() << "text/plain" << "text/html" << "text/xml" << "application/vnd.ogc.gml" << "application/vnd.ogc.gml/3.1.1" ); + elem = doc.createElement( QStringLiteral( "GetFeatureInfo" ) ); + appendFormats( doc, elem, QStringList() << QStringLiteral( "text/plain" ) << QStringLiteral( "text/html" ) << QStringLiteral( "text/xml" ) << QStringLiteral( "application/vnd.ogc.gml" ) << QStringLiteral( "application/vnd.ogc.gml/3.1.1" ) ); elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElement.appendChild( elem ); //wms:GetLegendGraphic - elem = doc.createElement(( version == "1.1.1" ? "GetLegendGraphic" : "sld:GetLegendGraphic" )/*wms:GetLegendGraphic*/ ); - appendFormats( doc, elem, QStringList() << "image/jpeg" << "image/png" ); + elem = doc.createElement(( version == QLatin1String( "1.1.1" ) ? "GetLegendGraphic" : "sld:GetLegendGraphic" )/*wms:GetLegendGraphic*/ ); + appendFormats( doc, elem, QStringList() << QStringLiteral( "image/jpeg" ) << QStringLiteral( "image/png" ) ); elem.appendChild( dcpTypeElement.cloneNode().toElement() ); // this is the same as for 'GetCapabilities' requestElement.appendChild( elem ); //wms:DescribeLayer - elem = doc.createElement(( version == "1.1.1" ? "DescribeLayer" : "sld:DescribeLayer" )/*wms:GetLegendGraphic*/ ); - appendFormats( doc, elem, QStringList() << "text/xml" ); + elem = doc.createElement(( version == QLatin1String( "1.1.1" ) ? "DescribeLayer" : "sld:DescribeLayer" )/*wms:GetLegendGraphic*/ ); + appendFormats( doc, elem, QStringList() << QStringLiteral( "text/xml" ) ); elem.appendChild( dcpTypeElement.cloneNode().toElement() ); // this is the same as for 'GetCapabilities' requestElement.appendChild( elem ); //wms:GetStyles - elem = doc.createElement(( version == "1.1.1" ? "GetStyles" : "qgs:GetStyles" )/*wms:GetStyles*/ ); - appendFormats( doc, elem, QStringList() << "text/xml" ); + elem = doc.createElement(( version == QLatin1String( "1.1.1" ) ? "GetStyles" : "qgs:GetStyles" )/*wms:GetStyles*/ ); + appendFormats( doc, elem, QStringList() << QStringLiteral( "text/xml" ) ); elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElement.appendChild( elem ); if ( fullProjectInformation ) //remove composer templates from GetCapabilities in the long term { //wms:GetPrint - elem = doc.createElement( "GetPrint" /*wms:GetPrint*/ ); - appendFormats( doc, elem, QStringList() << "svg" << "png" << "pdf" ); + elem = doc.createElement( QStringLiteral( "GetPrint" ) /*wms:GetPrint*/ ); + appendFormats( doc, elem, QStringList() << QStringLiteral( "svg" ) << QStringLiteral( "png" ) << QStringLiteral( "pdf" ) ); elem.appendChild( dcpTypeElement.cloneNode().toElement() ); //this is the same as for 'GetCapabilities' requestElement.appendChild( elem ); } //Exception element is mandatory - elem = doc.createElement( "Exception" ); - appendFormats( doc, elem, QStringList() << ( version == "1.1.1" ? "application/vnd.ogc.se_xml" : "text/xml" ) ); + elem = doc.createElement( QStringLiteral( "Exception" ) ); + appendFormats( doc, elem, QStringList() << ( version == QLatin1String( "1.1.1" ) ? "application/vnd.ogc.se_xml" : "text/xml" ) ); capabilityElement.appendChild( elem ); //UserDefinedSymbolization element - if ( version == "1.3.0" ) - { - elem = doc.createElement( "sld:UserDefinedSymbolization" ); - elem.setAttribute( "SupportSLD", "1" ); - elem.setAttribute( "UserLayer", "0" ); - elem.setAttribute( "UserStyle", "1" ); - elem.setAttribute( "RemoteWFS", "0" ); - elem.setAttribute( "InlineFeature", "0" ); - elem.setAttribute( "RemoteWCS", "0" ); + if ( version == QLatin1String( "1.3.0" ) ) + { + elem = doc.createElement( QStringLiteral( "sld:UserDefinedSymbolization" ) ); + elem.setAttribute( QStringLiteral( "SupportSLD" ), QStringLiteral( "1" ) ); + elem.setAttribute( QStringLiteral( "UserLayer" ), QStringLiteral( "0" ) ); + elem.setAttribute( QStringLiteral( "UserStyle" ), QStringLiteral( "1" ) ); + elem.setAttribute( QStringLiteral( "RemoteWFS" ), QStringLiteral( "0" ) ); + elem.setAttribute( QStringLiteral( "InlineFeature" ), QStringLiteral( "0" ) ); + elem.setAttribute( QStringLiteral( "RemoteWCS" ), QStringLiteral( "0" ) ); capabilityElement.appendChild( elem ); if ( mConfigParser && mConfigParser->wmsInspireActivated() ) @@ -593,12 +593,12 @@ QDomDocument QgsWmsServer::getCapabilities( const QString& version, bool fullPro QStringList wfsLayers = mConfigParser->wfsLayerNames(); if ( !wfsLayers.isEmpty() ) { - QDomElement wfsLayersElem = doc.createElement( "WFSLayers" ); + QDomElement wfsLayersElem = doc.createElement( QStringLiteral( "WFSLayers" ) ); QStringList::const_iterator wfsIt = wfsLayers.constBegin(); for ( ; wfsIt != wfsLayers.constEnd(); ++wfsIt ) { - QDomElement wfsLayerElem = doc.createElement( "WFSLayer" ); - wfsLayerElem.setAttribute( "name", *wfsIt ); + QDomElement wfsLayerElem = doc.createElement( QStringLiteral( "WFSLayer" ) ); + wfsLayerElem.setAttribute( QStringLiteral( "name" ), *wfsIt ); wfsLayersElem.appendChild( wfsLayerElem ); } capabilityElement.appendChild( wfsLayersElem ); @@ -606,12 +606,12 @@ QDomDocument QgsWmsServer::getCapabilities( const QString& version, bool fullPro } //add the xml content for the individual layers/styles - QgsMessageLog::logMessage( "calling layersAndStylesCapabilities" ); + QgsMessageLog::logMessage( QStringLiteral( "calling layersAndStylesCapabilities" ) ); if ( mConfigParser ) { mConfigParser->layersAndStylesCapabilities( capabilityElement, doc, version, fullProjectInformation ); } - QgsMessageLog::logMessage( "layersAndStylesCapabilities returned" ); + QgsMessageLog::logMessage( QStringLiteral( "layersAndStylesCapabilities returned" ) ); #if 0 //for debugging: save the document to disk @@ -630,20 +630,20 @@ QDomDocument QgsWmsServer::getContext() { QDomDocument doc; addXmlDeclaration( doc ); - QDomElement owsContextElem = doc.createElement( "OWSContext" ); - owsContextElem.setAttribute( "xmlns", "http://www.opengis.net/ows-context" ); - owsContextElem.setAttribute( "xmlns:ows-context", "http://www.opengis.net/ows-context" ); - owsContextElem.setAttribute( "xmlns:context", "http://www.opengis.net/context" ); - owsContextElem.setAttribute( "xmlns:ows", "http://www.opengis.net/ows" ); - owsContextElem.setAttribute( "xmlns:sld", "http://www.opengis.net/sld" ); - owsContextElem.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" ); - owsContextElem.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); - owsContextElem.setAttribute( "xmlns:kml", "http://www.opengis.net/kml/2.2" ); - owsContextElem.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - owsContextElem.setAttribute( "xmlns:ns9", "http://www.w3.org/2005/Atom" ); - owsContextElem.setAttribute( "xmlns:xal", "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" ); - owsContextElem.setAttribute( "xmlns:ins", "http://www.inspire.org" ); - owsContextElem.setAttribute( "version", "0.3.1" ); + QDomElement owsContextElem = doc.createElement( QStringLiteral( "OWSContext" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns" ), QStringLiteral( "http://www.opengis.net/ows-context" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:ows-context" ), QStringLiteral( "http://www.opengis.net/ows-context" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:context" ), QStringLiteral( "http://www.opengis.net/context" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:ows" ), QStringLiteral( "http://www.opengis.net/ows" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:sld" ), QStringLiteral( "http://www.opengis.net/sld" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:ogc" ), QStringLiteral( "http://www.opengis.net/ogc" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:gml" ), QStringLiteral( "http://www.opengis.net/gml" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:kml" ), QStringLiteral( "http://www.opengis.net/kml/2.2" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:ns9" ), QStringLiteral( "http://www.w3.org/2005/Atom" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:xal" ), QStringLiteral( "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" ) ); + owsContextElem.setAttribute( QStringLiteral( "xmlns:ins" ), QStringLiteral( "http://www.inspire.org" ) ); + owsContextElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "0.3.1" ) ); doc.appendChild( owsContextElem ); if ( mConfigParser ) @@ -679,7 +679,7 @@ static QgsRectangle _parseBBOX( const QString &bboxStr, bool &ok ) { ok = false; - QStringList lst = bboxStr.split( "," ); + QStringList lst = bboxStr.split( QStringLiteral( "," ) ); if ( lst.count() != 4 ) return QgsRectangle(); @@ -687,7 +687,7 @@ static QgsRectangle _parseBBOX( const QString &bboxStr, bool &ok ) for ( int i = 0; i < 4; i++ ) { bool ok; - lst[i].replace( " ", "+" ); + lst[i].replace( QLatin1String( " " ), QLatin1String( "+" ) ); d[i] = lst[i].toDouble( &ok ); if ( !ok ) return QgsRectangle(); @@ -704,36 +704,36 @@ QImage* QgsWmsServer::getLegendGraphics() { return nullptr; } - if ( !mParameters.contains( "LAYER" ) && !mParameters.contains( "LAYERS" ) ) + if ( !mParameters.contains( QStringLiteral( "LAYER" ) ) && !mParameters.contains( QStringLiteral( "LAYERS" ) ) ) { - throw QgsMapServiceException( "LayerNotSpecified", "LAYER is mandatory for GetLegendGraphic operation" ); + throw QgsMapServiceException( QStringLiteral( "LayerNotSpecified" ), QStringLiteral( "LAYER is mandatory for GetLegendGraphic operation" ) ); } - if ( !mParameters.contains( "FORMAT" ) ) + if ( !mParameters.contains( QStringLiteral( "FORMAT" ) ) ) { - throw QgsMapServiceException( "FormatNotSpecified", "FORMAT is mandatory for GetLegendGraphic operation" ); + throw QgsMapServiceException( QStringLiteral( "FormatNotSpecified" ), QStringLiteral( "FORMAT is mandatory for GetLegendGraphic operation" ) ); } bool contentBasedLegend = false; QgsRectangle contentBasedLegendExtent; - if ( mParameters.contains( "BBOX" ) ) + if ( mParameters.contains( QStringLiteral( "BBOX" ) ) ) { contentBasedLegend = true; bool bboxOk; - contentBasedLegendExtent = _parseBBOX( mParameters["BBOX"], bboxOk ); + contentBasedLegendExtent = _parseBBOX( mParameters[QStringLiteral( "BBOX" )], bboxOk ); if ( !bboxOk || contentBasedLegendExtent.isEmpty() ) - throw QgsMapServiceException( "InvalidParameterValue", "Invalid BBOX parameter" ); + throw QgsMapServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "Invalid BBOX parameter" ) ); - if ( mParameters.contains( "RULE" ) ) - throw QgsMapServiceException( "InvalidParameterValue", "BBOX parameter cannot be combined with RULE" ); + if ( mParameters.contains( QStringLiteral( "RULE" ) ) ) + throw QgsMapServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "BBOX parameter cannot be combined with RULE" ) ); } QStringList layersList, stylesList; if ( readLayersAndStyles( layersList, stylesList ) != 0 ) { - QgsMessageLog::logMessage( "error reading layers and styles" ); + QgsMessageLog::logMessage( QStringLiteral( "error reading layers and styles" ) ); return nullptr; } @@ -744,7 +744,7 @@ QImage* QgsWmsServer::getLegendGraphics() //scale double scaleDenominator = -1; - QMap::const_iterator scaleIt = mParameters.constFind( "SCALE" ); + QMap::const_iterator scaleIt = mParameters.constFind( QStringLiteral( "SCALE" ) ); if ( scaleIt != mParameters.constEnd() ) { bool conversionSuccess; @@ -771,12 +771,12 @@ QImage* QgsWmsServer::getLegendGraphics() QString rule; int ruleSymbolWidth = 0, ruleSymbolHeight = 0; - QMap::const_iterator ruleIt = mParameters.constFind( "RULE" ); + QMap::const_iterator ruleIt = mParameters.constFind( QStringLiteral( "RULE" ) ); if ( ruleIt != mParameters.constEnd() ) { rule = ruleIt.value(); - QMap::const_iterator widthIt = mParameters.constFind( "WIDTH" ); + QMap::const_iterator widthIt = mParameters.constFind( QStringLiteral( "WIDTH" ) ); if ( widthIt != mParameters.constEnd() ) { bool conversionSuccess; @@ -787,7 +787,7 @@ QImage* QgsWmsServer::getLegendGraphics() } } - QMap::const_iterator heightIt = mParameters.constFind( "HEIGHT" ); + QMap::const_iterator heightIt = mParameters.constFind( QStringLiteral( "HEIGHT" ) ); if ( heightIt != mParameters.constEnd() ) { bool conversionSuccess; @@ -801,8 +801,8 @@ QImage* QgsWmsServer::getLegendGraphics() // Checks showFeatureCount parameter bool showFeatureCount = false; - if ( mParameters.contains( "SHOWFEATURECOUNT" ) ) - showFeatureCount = QVariant( mParameters[ "SHOWFEATURECOUNT" ] ).toBool(); + if ( mParameters.contains( QStringLiteral( "SHOWFEATURECOUNT" ) ) ) + showFeatureCount = QVariant( mParameters[ QStringLiteral( "SHOWFEATURECOUNT" )] ).toBool(); // Create the layer tree root QgsLayerTreeGroup rootGroup; @@ -822,7 +822,7 @@ QImage* QgsWmsServer::getLegendGraphics() layer->setLayerName( ml->title() ); // set show feature count if ( showFeatureCount ) - layer->setCustomProperty( "showFeatureCount", showFeatureCount ); + layer->setCustomProperty( QStringLiteral( "showFeatureCount" ), showFeatureCount ); } QgsLayerTreeModel legendModel( &rootGroup ); @@ -928,7 +928,7 @@ QImage* QgsWmsServer::getLegendGraphics() #ifdef HAVE_SERVER_PYTHON_PLUGINS if ( !mAccessControl->layerReadPermission( nodeLayer->layer() ) ) { - throw QgsMapServiceException( "Security", "You are not allowed to access to the layer: " + nodeLayer->layer()->name() ); + throw QgsMapServiceException( QStringLiteral( "Security" ), "You are not allowed to access to the layer: " + nodeLayer->layer()->name() ); } #endif @@ -940,7 +940,7 @@ QImage* QgsWmsServer::getLegendGraphics() { Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, legendModel.layerLegendNodes( nodeLayer ) ) { - legendNode->setUserLabel( " " ); // empty string = no override, so let's use one space + legendNode->setUserLabel( QStringLiteral( " " ) ); // empty string = no override, so let's use one space } } else if ( !mDrawLegendLayerLabel ) @@ -1050,41 +1050,41 @@ void QgsWmsServer::legendParameters( double& boxSpace, double& layerSpace, doubl QFont& layerFont, QFont& itemFont, QColor& layerFontColor, QColor& itemFontColor ) { //spaces between legend elements - QMap::const_iterator boxSpaceIt = mParameters.constFind( "BOXSPACE" ); + QMap::const_iterator boxSpaceIt = mParameters.constFind( QStringLiteral( "BOXSPACE" ) ); boxSpace = ( boxSpaceIt == mParameters.constEnd() ) ? mConfigParser->legendBoxSpace() : boxSpaceIt.value().toDouble(); - QMap::const_iterator layerSpaceIt = mParameters.constFind( "LAYERSPACE" ); + QMap::const_iterator layerSpaceIt = mParameters.constFind( QStringLiteral( "LAYERSPACE" ) ); layerSpace = ( layerSpaceIt == mParameters.constEnd() ) ? mConfigParser->legendLayerSpace() : layerSpaceIt.value().toDouble(); - QMap::const_iterator layerTitleSpaceIt = mParameters.constFind( "LAYERTITLESPACE" ); + QMap::const_iterator layerTitleSpaceIt = mParameters.constFind( QStringLiteral( "LAYERTITLESPACE" ) ); layerTitleSpace = ( layerTitleSpaceIt == mParameters.constEnd() ) ? mConfigParser->legendLayerTitleSpace() : layerTitleSpaceIt.value().toDouble(); - QMap::const_iterator symbolSpaceIt = mParameters.constFind( "SYMBOLSPACE" ); + QMap::const_iterator symbolSpaceIt = mParameters.constFind( QStringLiteral( "SYMBOLSPACE" ) ); symbolSpace = ( symbolSpaceIt == mParameters.constEnd() ) ? mConfigParser->legendSymbolSpace() : symbolSpaceIt.value().toDouble(); - QMap::const_iterator iconLabelSpaceIt = mParameters.constFind( "ICONLABELSPACE" ); + QMap::const_iterator iconLabelSpaceIt = mParameters.constFind( QStringLiteral( "ICONLABELSPACE" ) ); iconLabelSpace = ( iconLabelSpaceIt == mParameters.constEnd() ) ? mConfigParser->legendIconLabelSpace() : iconLabelSpaceIt.value().toDouble(); - QMap::const_iterator symbolWidthIt = mParameters.constFind( "SYMBOLWIDTH" ); + QMap::const_iterator symbolWidthIt = mParameters.constFind( QStringLiteral( "SYMBOLWIDTH" ) ); symbolWidth = ( symbolWidthIt == mParameters.constEnd() ) ? mConfigParser->legendSymbolWidth() : symbolWidthIt.value().toDouble(); - QMap::const_iterator symbolHeightIt = mParameters.constFind( "SYMBOLHEIGHT" ); + QMap::const_iterator symbolHeightIt = mParameters.constFind( QStringLiteral( "SYMBOLHEIGHT" ) ); symbolHeight = ( symbolHeightIt == mParameters.constEnd() ) ? mConfigParser->legendSymbolHeight() : symbolHeightIt.value().toDouble(); //font properties layerFont = mConfigParser->legendLayerFont(); - QMap::const_iterator layerFontFamilyIt = mParameters.constFind( "LAYERFONTFAMILY" ); + QMap::const_iterator layerFontFamilyIt = mParameters.constFind( QStringLiteral( "LAYERFONTFAMILY" ) ); if ( layerFontFamilyIt != mParameters.constEnd() ) { layerFont.setFamily( layerFontFamilyIt.value() ); } - QMap::const_iterator layerFontBoldIt = mParameters.constFind( "LAYERFONTBOLD" ); + QMap::const_iterator layerFontBoldIt = mParameters.constFind( QStringLiteral( "LAYERFONTBOLD" ) ); if ( layerFontBoldIt != mParameters.constEnd() ) { - layerFont.setBold( layerFontBoldIt.value().compare( "TRUE", Qt::CaseInsensitive ) == 0 ); + layerFont.setBold( layerFontBoldIt.value().compare( QLatin1String( "TRUE" ), Qt::CaseInsensitive ) == 0 ); } - QMap::const_iterator layerFontItalicIt = mParameters.constFind( "LAYERFONTITALIC" ); + QMap::const_iterator layerFontItalicIt = mParameters.constFind( QStringLiteral( "LAYERFONTITALIC" ) ); if ( layerFontItalicIt != mParameters.constEnd() ) { - layerFont.setItalic( layerFontItalicIt.value().compare( "TRUE", Qt::CaseInsensitive ) == 0 ); + layerFont.setItalic( layerFontItalicIt.value().compare( QLatin1String( "TRUE" ), Qt::CaseInsensitive ) == 0 ); } - QMap::const_iterator layerFontSizeIt = mParameters.constFind( "LAYERFONTSIZE" ); + QMap::const_iterator layerFontSizeIt = mParameters.constFind( QStringLiteral( "LAYERFONTSIZE" ) ); layerFont.setPointSizeF( layerFontSizeIt != mParameters.constEnd() ? layerFontSizeIt.value().toDouble() : layerFont.pointSizeF() ); - QMap::const_iterator layerFontColorIt = mParameters.constFind( "LAYERFONTCOLOR" ); + QMap::const_iterator layerFontColorIt = mParameters.constFind( QStringLiteral( "LAYERFONTCOLOR" ) ); if ( layerFontColorIt != mParameters.constEnd() ) { layerFontColor.setNamedColor( layerFontColorIt.value() ); @@ -1093,10 +1093,10 @@ void QgsWmsServer::legendParameters( double& boxSpace, double& layerSpace, doubl { layerFontColor = QColor( 0, 0, 0 ); } - QMap::const_iterator layerTitleIt = mParameters.constFind( "LAYERTITLE" ); + QMap::const_iterator layerTitleIt = mParameters.constFind( QStringLiteral( "LAYERTITLE" ) ); if ( layerTitleIt != mParameters.constEnd() ) { - mDrawLegendLayerLabel = ( layerTitleIt.value().compare( "TRUE", Qt::CaseInsensitive ) == 0 ); + mDrawLegendLayerLabel = ( layerTitleIt.value().compare( QLatin1String( "TRUE" ), Qt::CaseInsensitive ) == 0 ); } else { @@ -1105,24 +1105,24 @@ void QgsWmsServer::legendParameters( double& boxSpace, double& layerSpace, doubl itemFont = mConfigParser->legendItemFont(); - QMap::const_iterator itemFontFamilyIt = mParameters.constFind( "ITEMFONTFAMILY" ); + QMap::const_iterator itemFontFamilyIt = mParameters.constFind( QStringLiteral( "ITEMFONTFAMILY" ) ); if ( itemFontFamilyIt != mParameters.constEnd() ) { itemFont.setFamily( itemFontFamilyIt.value() ); } - QMap::const_iterator itemFontBoldIt = mParameters.constFind( "ITEMFONTBOLD" ); + QMap::const_iterator itemFontBoldIt = mParameters.constFind( QStringLiteral( "ITEMFONTBOLD" ) ); if ( itemFontBoldIt != mParameters.constEnd() ) { - itemFont.setBold( itemFontBoldIt.value().compare( "TRUE", Qt::CaseInsensitive ) == 0 ); + itemFont.setBold( itemFontBoldIt.value().compare( QLatin1String( "TRUE" ), Qt::CaseInsensitive ) == 0 ); } - QMap::const_iterator itemFontItalicIt = mParameters.constFind( "ITEMFONTITALIC" ); + QMap::const_iterator itemFontItalicIt = mParameters.constFind( QStringLiteral( "ITEMFONTITALIC" ) ); if ( itemFontItalicIt != mParameters.constEnd() ) { - itemFont.setItalic( itemFontItalicIt.value().compare( "TRUE", Qt::CaseInsensitive ) == 0 ); + itemFont.setItalic( itemFontItalicIt.value().compare( QLatin1String( "TRUE" ), Qt::CaseInsensitive ) == 0 ); } - QMap::const_iterator itemFontSizeIt = mParameters.constFind( "ITEMFONTSIZE" ); + QMap::const_iterator itemFontSizeIt = mParameters.constFind( QStringLiteral( "ITEMFONTSIZE" ) ); itemFont.setPointSizeF( itemFontSizeIt != mParameters.constEnd() ? itemFontSizeIt.value().toDouble() : itemFont.pointSizeF() ); - QMap::const_iterator itemFontColorIt = mParameters.constFind( "ITEMFONTCOLOR" ); + QMap::const_iterator itemFontColorIt = mParameters.constFind( QStringLiteral( "ITEMFONTCOLOR" ) ); if ( itemFontColorIt != mParameters.constEnd() ) { itemFontColor.setNamedColor( itemFontColorIt.value() ); @@ -1131,10 +1131,10 @@ void QgsWmsServer::legendParameters( double& boxSpace, double& layerSpace, doubl { itemFontColor = QColor( 0, 0, 0 ); } - QMap::const_iterator itemLabelIt = mParameters.constFind( "RULELABEL" ); + QMap::const_iterator itemLabelIt = mParameters.constFind( QStringLiteral( "RULELABEL" ) ); if ( itemLabelIt != mParameters.constEnd() ) { - mDrawLegendItemLabel = ( itemLabelIt.value().compare( "TRUE", Qt::CaseInsensitive ) == 0 ); + mDrawLegendItemLabel = ( itemLabelIt.value().compare( QLatin1String( "TRUE" ), Qt::CaseInsensitive ) == 0 ); } else { @@ -1146,10 +1146,10 @@ QDomDocument QgsWmsServer::getSchemaExtension() { QDomDocument xsdDoc; - QFileInfo xsdFileInfo( "schemaExtension.xsd" ); + QFileInfo xsdFileInfo( QStringLiteral( "schemaExtension.xsd" ) ); if ( !xsdFileInfo.exists() ) { - QgsMessageLog::logMessage( "Error, xsd file 'schemaExtension.xsd' does not exist", "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( QStringLiteral( "Error, xsd file 'schemaExtension.xsd' does not exist" ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); return xsdDoc; } @@ -1157,13 +1157,13 @@ QDomDocument QgsWmsServer::getSchemaExtension() QFile xsdFile( xsdFilePath ); if ( !xsdFile.exists() ) { - QgsMessageLog::logMessage( "Error, xsd file 'schemaExtension.xsd' does not exist", "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( QStringLiteral( "Error, xsd file 'schemaExtension.xsd' does not exist" ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); return xsdDoc; } if ( !xsdFile.open( QIODevice::ReadOnly ) ) { - QgsMessageLog::logMessage( "Error, cannot open xsd file 'schemaExtension.xsd' does not exist", "Server", QgsMessageLog::CRITICAL ); + QgsMessageLog::logMessage( QStringLiteral( "Error, cannot open xsd file 'schemaExtension.xsd' does not exist" ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); return xsdDoc; } @@ -1172,7 +1172,7 @@ QDomDocument QgsWmsServer::getSchemaExtension() if ( !xsdDoc.setContent( &xsdFile, true, &errorMsg, &line, &column ) ) { QgsMessageLog::logMessage( "Error parsing file 'schemaExtension.xsd" + - QString( "': parse error %1 at row %2, column %3" ).arg( errorMsg ).arg( line ).arg( column ), "Server", QgsMessageLog::CRITICAL ); + QStringLiteral( "': parse error %1 at row %2, column %3" ).arg( errorMsg ).arg( line ).arg( column ), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); return xsdDoc; } return xsdDoc; @@ -1181,18 +1181,18 @@ QDomDocument QgsWmsServer::getSchemaExtension() QDomDocument QgsWmsServer::getStyle() { QDomDocument doc; - if ( !mParameters.contains( "STYLE" ) ) + if ( !mParameters.contains( QStringLiteral( "STYLE" ) ) ) { - throw QgsMapServiceException( "StyleNotSpecified", "Style is mandatory for GetStyle operation" ); + throw QgsMapServiceException( QStringLiteral( "StyleNotSpecified" ), QStringLiteral( "Style is mandatory for GetStyle operation" ) ); } - if ( !mParameters.contains( "LAYER" ) ) + if ( !mParameters.contains( QStringLiteral( "LAYER" ) ) ) { - throw QgsMapServiceException( "LayerNotSpecified", "Layer is mandatory for GetStyle operation" ); + throw QgsMapServiceException( QStringLiteral( "LayerNotSpecified" ), QStringLiteral( "Layer is mandatory for GetStyle operation" ) ); } - QString styleName = mParameters[ "STYLE" ]; - QString layerName = mParameters[ "LAYER" ]; + QString styleName = mParameters[ QStringLiteral( "STYLE" )]; + QString layerName = mParameters[ QStringLiteral( "LAYER" )]; return mConfigParser->getStyle( styleName, layerName ); } @@ -1201,15 +1201,15 @@ QDomDocument QgsWmsServer::getStyle() QDomDocument QgsWmsServer::getStyles() { QDomDocument doc; - if ( !mParameters.contains( "LAYERS" ) ) + if ( !mParameters.contains( QStringLiteral( "LAYERS" ) ) ) { - throw QgsMapServiceException( "LayerNotSpecified", "Layers is mandatory for GetStyles operation" ); + throw QgsMapServiceException( QStringLiteral( "LayerNotSpecified" ), QStringLiteral( "Layers is mandatory for GetStyles operation" ) ); } - QStringList layersList = mParameters[ "LAYERS" ].split( ",", QString::SkipEmptyParts ); + QStringList layersList = mParameters[ QStringLiteral( "LAYERS" )].split( QStringLiteral( "," ), QString::SkipEmptyParts ); if ( layersList.size() < 1 ) { - throw QgsMapServiceException( "LayerNotSpecified", "Layers is mandatory for GetStyles operation" ); + throw QgsMapServiceException( QStringLiteral( "LayerNotSpecified" ), QStringLiteral( "Layers is mandatory for GetStyles operation" ) ); } return mConfigParser->getStyles( layersList ); @@ -1218,24 +1218,24 @@ QDomDocument QgsWmsServer::getStyles() // DescribeLayer is defined for WMS1.1.1/SLD1.0 and in WMS 1.3.0 SLD Extension QDomDocument QgsWmsServer::describeLayer() { - if ( !mParameters.contains( "SLD_VERSION" ) ) + if ( !mParameters.contains( QStringLiteral( "SLD_VERSION" ) ) ) { - throw QgsMapServiceException( "MissingParameterValue", "SLD_VERSION is mandatory for DescribeLayer operation" ); + throw QgsMapServiceException( QStringLiteral( "MissingParameterValue" ), QStringLiteral( "SLD_VERSION is mandatory for DescribeLayer operation" ) ); } - if ( mParameters[ "SLD_VERSION" ] != "1.1.0" ) + if ( mParameters[ QStringLiteral( "SLD_VERSION" )] != QLatin1String( "1.1.0" ) ) { - throw QgsMapServiceException( "InvalidParameterValue", QString( "SLD_VERSION = %1 is not supported" ).arg( mParameters[ "SLD_VERSION" ] ) ); + throw QgsMapServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "SLD_VERSION = %1 is not supported" ).arg( mParameters[ QStringLiteral( "SLD_VERSION" )] ) ); } - if ( !mParameters.contains( "LAYERS" ) ) + if ( !mParameters.contains( QStringLiteral( "LAYERS" ) ) ) { - throw QgsMapServiceException( "MissingParameterValue", "LAYERS is mandatory for DescribeLayer operation" ); + throw QgsMapServiceException( QStringLiteral( "MissingParameterValue" ), QStringLiteral( "LAYERS is mandatory for DescribeLayer operation" ) ); } - QStringList layersList = mParameters[ "LAYERS" ].split( ",", QString::SkipEmptyParts ); + QStringList layersList = mParameters[ QStringLiteral( "LAYERS" )].split( QStringLiteral( "," ), QString::SkipEmptyParts ); if ( layersList.size() < 1 ) { - throw QgsMapServiceException( "InvalidParameterValue", "Layers is empty" ); + throw QgsMapServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "Layers is empty" ) ); } //Prepare url @@ -1263,7 +1263,7 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) { if ( !mAccessControl->layerReadPermission( layer ) ) { - throw QgsMapServiceException( "Security", "You are not allowed to access to the layer: " + layer->name() ); + throw QgsMapServiceException( QStringLiteral( "Security" ), "You are not allowed to access to the layer: " + layer->name() ); } } #endif @@ -1281,10 +1281,10 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) QStringList selectedLayerIdList = applyFeatureSelections( layersList ); //GetPrint request needs a template parameter - if ( !mParameters.contains( "TEMPLATE" ) ) + if ( !mParameters.contains( QStringLiteral( "TEMPLATE" ) ) ) { clearFeatureSelections( selectedLayerIdList ); - throw QgsMapServiceException( "ParameterMissing", "The TEMPLATE parameter is required for the GetPrint request" ); + throw QgsMapServiceException( QStringLiteral( "ParameterMissing" ), QStringLiteral( "The TEMPLATE parameter is required for the GetPrint request" ) ); } QList< QPair< QgsVectorLayer*, QgsFeatureRenderer*> > bkVectorRenderers; @@ -1295,7 +1295,7 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) applyOpacities( layersList, bkVectorRenderers, bkRasterRenderers, labelTransparencies, labelBufferTransparencies ); QStringList highlightLayers; - QgsComposition* c = mConfigParser->createPrintComposition( mParameters[ "TEMPLATE" ], mMapRenderer, QMap( mParameters ), highlightLayers ); + QgsComposition* c = mConfigParser->createPrintComposition( mParameters[ QStringLiteral( "TEMPLATE" )], mMapRenderer, QMap( mParameters ), highlightLayers ); if ( !c ) { restoreOpacities( bkVectorRenderers, bkRasterRenderers, labelTransparencies, labelBufferTransparencies ); @@ -1308,7 +1308,7 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) c->setPlotStyle( QgsComposition::Print ); //SVG export without a running X-Server is a problem. See e.g. http://developer.qt.nokia.com/forums/viewthread/2038 - if ( formatString.compare( "svg", Qt::CaseInsensitive ) == 0 ) + if ( formatString.compare( QLatin1String( "svg" ), Qt::CaseInsensitive ) == 0 ) { c->setPlotStyle( QgsComposition::Print ); @@ -1333,7 +1333,7 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) } p.end(); } - else if ( formatString.compare( "png", Qt::CaseInsensitive ) == 0 || formatString.compare( "jpg", Qt::CaseInsensitive ) == 0 ) + else if ( formatString.compare( QLatin1String( "png" ), Qt::CaseInsensitive ) == 0 || formatString.compare( QLatin1String( "jpg" ), Qt::CaseInsensitive ) == 0 ) { QImage image = c->printPageAsRaster( 0 ); //can only return the first page if pixmap is requested @@ -1342,7 +1342,7 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) buffer.open( QIODevice::WriteOnly ); image.save( &buffer, formatString.toLocal8Bit().data(), -1 ); } - else if ( formatString.compare( "pdf", Qt::CaseInsensitive ) == 0 ) + else if ( formatString.compare( QLatin1String( "pdf" ), Qt::CaseInsensitive ) == 0 ) { QTemporaryFile tempFile; if ( !tempFile.open() ) @@ -1361,7 +1361,7 @@ QByteArray* QgsWmsServer::getPrint( const QString& formatString ) { restoreOpacities( bkVectorRenderers, bkRasterRenderers, labelTransparencies, labelBufferTransparencies ); clearFeatureSelections( selectedLayerIdList ); - throw QgsMapServiceException( "InvalidFormat", "Output format '" + formatString + "' is not supported in the GetPrint request" ); + throw QgsMapServiceException( QStringLiteral( "InvalidFormat" ), "Output format '" + formatString + "' is not supported in the GetPrint request" ); } restoreOpacities( bkVectorRenderers, bkRasterRenderers, labelTransparencies, labelBufferTransparencies ); @@ -1394,7 +1394,7 @@ QImage* QgsWmsServer::getMap( HitTest* hitTest ) { if ( !checkMaximumWidthHeight() ) { - throw QgsMapServiceException( "Size error", "The requested map size is too large" ); + throw QgsMapServiceException( QStringLiteral( "Size error" ), QStringLiteral( "The requested map size is too large" ) ); } QStringList layersList, stylesList, layerIdList; QImage* theImage = initializeRendering( layersList, stylesList, layerIdList ); @@ -1411,7 +1411,7 @@ QImage* QgsWmsServer::getMap( HitTest* hitTest ) { if ( !mAccessControl->layerReadPermission( layer ) ) { - throw QgsMapServiceException( "Security", "You are not allowed to access to the layer: " + layer->name() ); + throw QgsMapServiceException( QStringLiteral( "Security" ), "You are not allowed to access to the layer: " + layer->name() ); } } #endif @@ -1465,17 +1465,17 @@ QImage* QgsWmsServer::getMap( HitTest* hitTest ) void QgsWmsServer::getMapAsDxf() { - QgsServerStreamingDevice d( "application/dxf" , mRequestHandler ); + QgsServerStreamingDevice d( QStringLiteral( "application/dxf" ) , mRequestHandler ); if ( !d.open( QIODevice::WriteOnly ) ) { - throw QgsMapServiceException( "Internal server error", "Error opening output device for writing" ); + throw QgsMapServiceException( QStringLiteral( "Internal server error" ), QStringLiteral( "Error opening output device for writing" ) ); } QgsDxfExport dxf; //BBOX bool bboxOk; - QgsRectangle extent = _parseBBOX( mParameters.value( "BBOX", "0,0,0,0" ), bboxOk ); + QgsRectangle extent = _parseBBOX( mParameters.value( QStringLiteral( "BBOX" ), QStringLiteral( "0,0,0,0" ) ), bboxOk ); if ( !bboxOk ) { extent = QgsRectangle(); @@ -1490,10 +1490,10 @@ void QgsWmsServer::getMapAsDxf() readDxfLayerSettings( layers, formatOptionsMap ); dxf.addLayers( layers ); - dxf.setLayerTitleAsName( formatOptionsMap.contains( "USE_TITLE_AS_LAYERNAME" ) ); + dxf.setLayerTitleAsName( formatOptionsMap.contains( QStringLiteral( "USE_TITLE_AS_LAYERNAME" ) ) ); //MODE - QMap::const_iterator modeIt = formatOptionsMap.find( "MODE" ); + QMap::const_iterator modeIt = formatOptionsMap.find( QStringLiteral( "MODE" ) ); QgsDxfExport::SymbologyExport se; if ( modeIt == formatOptionsMap.constEnd() ) @@ -1502,11 +1502,11 @@ void QgsWmsServer::getMapAsDxf() } else { - if ( modeIt->compare( "SymbolLayerSymbology", Qt::CaseInsensitive ) == 0 ) + if ( modeIt->compare( QLatin1String( "SymbolLayerSymbology" ), Qt::CaseInsensitive ) == 0 ) { se = QgsDxfExport::SymbolLayerSymbology; } - else if ( modeIt->compare( "FeatureSymbology", Qt::CaseInsensitive ) == 0 ) + else if ( modeIt->compare( QLatin1String( "FeatureSymbology" ), Qt::CaseInsensitive ) == 0 ) { se = QgsDxfExport::FeatureSymbology; } @@ -1518,17 +1518,17 @@ void QgsWmsServer::getMapAsDxf() dxf.setSymbologyExport( se ); //SCALE - QMap::const_iterator scaleIt = formatOptionsMap.find( "SCALE" ); + QMap::const_iterator scaleIt = formatOptionsMap.find( QStringLiteral( "SCALE" ) ); if ( scaleIt != formatOptionsMap.constEnd() ) { dxf.setSymbologyScaleDenominator( scaleIt->toDouble() ); } - QString codec = "ISO-8859-1"; - QMap::const_iterator codecIt = formatOptionsMap.find( "CODEC" ); + QString codec = QStringLiteral( "ISO-8859-1" ); + QMap::const_iterator codecIt = formatOptionsMap.find( QStringLiteral( "CODEC" ) ); if ( codecIt != formatOptionsMap.constEnd() ) { - codec = formatOptionsMap.value( "CODEC" ); + codec = formatOptionsMap.value( QStringLiteral( "CODEC" ) ); } dxf.writeToFile( &d, codec ); @@ -1548,7 +1548,7 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) for ( QMap::const_iterator it = mParameters.constBegin(); it != mParameters.constEnd(); ++it ) { - QgsMessageLog::logMessage( QString( "%1 // %2" ).arg( it.key(), it.value() ) ); + QgsMessageLog::logMessage( QStringLiteral( "%1 // %2" ).arg( it.key(), it.value() ) ); } if ( readLayersAndStyles( layersList, stylesList ) != 0 ) @@ -1573,8 +1573,8 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) } QgsMessageLog::logMessage( "mMapRenderer->extent(): " + mMapRenderer->extent().toString() ); - QgsMessageLog::logMessage( QString( "mMapRenderer width = %1 height = %2" ).arg( mMapRenderer->outputSize().width() ).arg( mMapRenderer->outputSize().height() ) ); - QgsMessageLog::logMessage( QString( "mMapRenderer->mapUnitsPerPixel() = %1" ).arg( mMapRenderer->mapUnitsPerPixel() ) ); + QgsMessageLog::logMessage( QStringLiteral( "mMapRenderer width = %1 height = %2" ).arg( mMapRenderer->outputSize().width() ).arg( mMapRenderer->outputSize().height() ) ); + QgsMessageLog::logMessage( QStringLiteral( "mMapRenderer->mapUnitsPerPixel() = %1" ).arg( mMapRenderer->mapUnitsPerPixel() ) ); //find out the current scale denominator and set it to the SLD parser QgsScaleCalculator scaleCalc(( outputImage->logicalDpiX() + outputImage->logicalDpiY() ) / 2, mMapRenderer->destinationCrs().mapUnits() ); @@ -1585,9 +1585,9 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) //read FEATURE_COUNT int featureCount = 1; - if ( mParameters.contains( "FEATURE_COUNT" ) ) + if ( mParameters.contains( QStringLiteral( "FEATURE_COUNT" ) ) ) { - featureCount = mParameters[ "FEATURE_COUNT" ].toInt( &conversionSuccess ); + featureCount = mParameters[ QStringLiteral( "FEATURE_COUNT" )].toInt( &conversionSuccess ); if ( !conversionSuccess ) { featureCount = 1; @@ -1595,26 +1595,26 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) } //read QUERY_LAYERS - if ( !mParameters.contains( "QUERY_LAYERS" ) ) + if ( !mParameters.contains( QStringLiteral( "QUERY_LAYERS" ) ) ) { return 3; } - QStringList queryLayerList = mParameters[ "QUERY_LAYERS" ].split( ",", QString::SkipEmptyParts ); + QStringList queryLayerList = mParameters[ QStringLiteral( "QUERY_LAYERS" )].split( QStringLiteral( "," ), QString::SkipEmptyParts ); if ( queryLayerList.size() < 1 ) { return 4; } //read I,J resp. X,Y - QString iString = mParameters.value( "I", mParameters.value( "X" ) ); + QString iString = mParameters.value( QStringLiteral( "I" ), mParameters.value( QStringLiteral( "X" ) ) ); int i = iString.toInt( &conversionSuccess ); if ( !conversionSuccess ) { i = -1; } - QString jString = mParameters.value( "J", mParameters.value( "Y" ) ); + QString jString = mParameters.value( QStringLiteral( "J" ), mParameters.value( QStringLiteral( "Y" ) ) ); int j = jString.toInt( &conversionSuccess ); if ( !conversionSuccess ) { @@ -1629,13 +1629,13 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) if ( i == -1 || j == -1 ) { - if ( mParameters.contains( "FILTER" ) ) + if ( mParameters.contains( QStringLiteral( "FILTER" ) ) ) { featuresRect = new QgsRectangle(); } else { - throw QgsMapServiceException( "ParameterMissing", "I/J parameters are required for GetFeatureInfo" ); + throw QgsMapServiceException( QStringLiteral( "ParameterMissing" ), QStringLiteral( "I/J parameters are required for GetFeatureInfo" ) ); } } else @@ -1660,22 +1660,22 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) #endif QDomElement getFeatureInfoElement; - QString infoFormat = mParameters.value( "INFO_FORMAT" ); - if ( infoFormat.startsWith( "application/vnd.ogc.gml" ) ) - { - getFeatureInfoElement = result.createElement( "wfs:FeatureCollection" ); - getFeatureInfoElement.setAttribute( "xmlns:wfs", "http://www.opengis.net/wfs" ); - getFeatureInfoElement.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" ); - getFeatureInfoElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" ); - getFeatureInfoElement.setAttribute( "xmlns:ows", "http://www.opengis.net/ows" ); - getFeatureInfoElement.setAttribute( "xmlns:xlink", "http://www.w3.org/1999/xlink" ); - getFeatureInfoElement.setAttribute( "xmlns:qgs", "http://qgis.org/gml" ); - getFeatureInfoElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - getFeatureInfoElement.setAttribute( "xsi:schemaLocation", "http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd http://qgis.org/gml" ); + QString infoFormat = mParameters.value( QStringLiteral( "INFO_FORMAT" ) ); + if ( infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml" ) ) ) + { + getFeatureInfoElement = result.createElement( QStringLiteral( "wfs:FeatureCollection" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:wfs" ), QStringLiteral( "http://www.opengis.net/wfs" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:ogc" ), QStringLiteral( "http://www.opengis.net/ogc" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:gml" ), QStringLiteral( "http://www.opengis.net/gml" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:ows" ), QStringLiteral( "http://www.opengis.net/ows" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:qgs" ), QStringLiteral( "http://qgis.org/gml" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), QStringLiteral( "http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd http://qgis.org/gml" ) ); } else { - QString featureInfoElemName = mConfigParser->featureInfoDocumentElement( "GetFeatureInfoResponse" ); + QString featureInfoElemName = mConfigParser->featureInfoDocumentElement( QStringLiteral( "GetFeatureInfoResponse" ) ); QString featureInfoElemNS = mConfigParser->featureInfoDocumentElementNS(); if ( featureInfoElemNS.isEmpty() ) { @@ -1689,8 +1689,8 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) QString featureInfoSchema = mConfigParser->featureInfoSchema(); if ( !featureInfoSchema.isEmpty() ) { - getFeatureInfoElement.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); - getFeatureInfoElement.setAttribute( "xsi:schemaLocation", featureInfoSchema ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) ); + getFeatureInfoElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), featureInfoSchema ); } } result.appendChild( getFeatureInfoElement ); @@ -1720,7 +1720,7 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) for ( layerIt = queryLayerList.constBegin(); layerIt != queryLayerList.constEnd(); ++layerIt ) { //create maplayers from sld parser (several layers are possible in case of feature info on a group) - layerList = mConfigParser->mapLayerFromStyle( *layerIt, "" ); + layerList = mConfigParser->mapLayerFromStyle( *layerIt, QLatin1String( "" ) ); QList::iterator layerListIt = layerList.begin(); for ( ; layerListIt != layerList.end(); ++layerListIt ) { @@ -1738,7 +1738,7 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) #ifdef HAVE_SERVER_PYTHON_PLUGINS if ( !mAccessControl->layerReadPermission( currentLayer ) ) { - throw QgsMapServiceException( "Security", "You are not allowed to access to the layer: " + currentLayer->name() ); + throw QgsMapServiceException( QStringLiteral( "Security" ), "You are not allowed to access to the layer: " + currentLayer->name() ); } #endif @@ -1753,13 +1753,13 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) QgsVectorLayer* vectorLayer = qobject_cast( currentLayer ); QDomElement layerElement; - if ( infoFormat.startsWith( "application/vnd.ogc.gml" ) ) + if ( infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml" ) ) ) { layerElement = getFeatureInfoElement; } else { - layerElement = result.createElement( "Layer" ); + layerElement = result.createElement( QStringLiteral( "Layer" ) ); QString layerName = currentLayer->name(); if ( mConfigParser && mConfigParser->useLayerIds() ) layerName = currentLayer->id(); @@ -1772,11 +1772,11 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) { layerName = layerAliasIt.value(); } - layerElement.setAttribute( "name", layerName ); + layerElement.setAttribute( QStringLiteral( "name" ), layerName ); getFeatureInfoElement.appendChild( layerElement ); if ( sia2045 ) //the name might not be unique after alias replacement { - layerElement.setAttribute( "id", currentLayer->id() ); + layerElement.setAttribute( QStringLiteral( "id" ), currentLayer->id() ); } } @@ -1790,9 +1790,9 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) } else //raster layer { - if ( infoFormat.startsWith( "application/vnd.ogc.gml" ) ) + if ( infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml" ) ) ) { - layerElement = result.createElement( "gml:featureMember"/*wfs:FeatureMember*/ ); + layerElement = result.createElement( QStringLiteral( "gml:featureMember" )/*wfs:FeatureMember*/ ); getFeatureInfoElement.appendChild( layerElement ); } @@ -1819,11 +1819,11 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) if ( featuresRect ) { - if ( infoFormat.startsWith( "application/vnd.ogc.gml" ) ) + if ( infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml" ) ) ) { - QDomElement bBoxElem = result.createElement( "gml:boundedBy" ); + QDomElement bBoxElem = result.createElement( QStringLiteral( "gml:boundedBy" ) ); QDomElement boxElem; - int gmlVersion = infoFormat.startsWith( "application/vnd.ogc.gml/3" ) ? 3 : 2; + int gmlVersion = infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml/3" ) ) ? 3 : 2; if ( gmlVersion < 3 ) { boxElem = QgsOgcUtils::rectangleToGMLBox( featuresRect, result, 8 ); @@ -1836,24 +1836,24 @@ int QgsWmsServer::getFeatureInfo( QDomDocument& result, const QString& version ) QgsCoordinateReferenceSystem crs = mMapRenderer->destinationCrs(); if ( crs.isValid() ) { - boxElem.setAttribute( "srsName", crs.authid() ); + boxElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } bBoxElem.appendChild( boxElem ); getFeatureInfoElement.insertBefore( bBoxElem, QDomNode() ); //insert as first child } else { - QDomElement bBoxElem = result.createElement( "BoundingBox" ); - bBoxElem.setAttribute( "CRS", mMapRenderer->destinationCrs().authid() ); - bBoxElem.setAttribute( "minx", qgsDoubleToString( featuresRect->xMinimum(), 8 ) ); - bBoxElem.setAttribute( "maxx", qgsDoubleToString( featuresRect->xMaximum(), 8 ) ); - bBoxElem.setAttribute( "miny", qgsDoubleToString( featuresRect->yMinimum(), 8 ) ); - bBoxElem.setAttribute( "maxy", qgsDoubleToString( featuresRect->yMaximum(), 8 ) ); + QDomElement bBoxElem = result.createElement( QStringLiteral( "BoundingBox" ) ); + bBoxElem.setAttribute( QStringLiteral( "CRS" ), mMapRenderer->destinationCrs().authid() ); + bBoxElem.setAttribute( QStringLiteral( "minx" ), qgsDoubleToString( featuresRect->xMinimum(), 8 ) ); + bBoxElem.setAttribute( QStringLiteral( "maxx" ), qgsDoubleToString( featuresRect->xMaximum(), 8 ) ); + bBoxElem.setAttribute( QStringLiteral( "miny" ), qgsDoubleToString( featuresRect->yMinimum(), 8 ) ); + bBoxElem.setAttribute( QStringLiteral( "maxy" ), qgsDoubleToString( featuresRect->yMaximum(), 8 ) ); getFeatureInfoElement.insertBefore( bBoxElem, QDomNode() ); //insert as first child } } - if ( sia2045 && infoFormat.compare( "text/xml", Qt::CaseInsensitive ) == 0 ) + if ( sia2045 && infoFormat.compare( QLatin1String( "text/xml" ), Qt::CaseInsensitive ) == 0 ) { convertFeatureInfoToSIA2045( result ); } @@ -1870,19 +1870,19 @@ QImage* QgsWmsServer::initializeRendering( QStringList& layersList, QStringList& { if ( !mConfigParser ) { - QgsMessageLog::logMessage( "Error: mSLDParser is 0" ); + QgsMessageLog::logMessage( QStringLiteral( "Error: mSLDParser is 0" ) ); return nullptr; } if ( !mMapRenderer ) { - QgsMessageLog::logMessage( "Error: mMapRenderer is 0" ); + QgsMessageLog::logMessage( QStringLiteral( "Error: mMapRenderer is 0" ) ); return nullptr; } if ( readLayersAndStyles( layersList, stylesList ) != 0 ) { - QgsMessageLog::logMessage( "error reading layers and styles" ); + QgsMessageLog::logMessage( QStringLiteral( "error reading layers and styles" ) ); return nullptr; } @@ -1891,19 +1891,19 @@ QImage* QgsWmsServer::initializeRendering( QStringList& layersList, QStringList& return nullptr; } //pass external GML to the SLD parser. - QString gml = mParameters.value( "GML" ); + QString gml = mParameters.value( QStringLiteral( "GML" ) ); if ( !gml.isEmpty() ) { QDomDocument* gmlDoc = new QDomDocument(); if ( gmlDoc->setContent( gml, true ) ) { - QString layerName = gmlDoc->documentElement().attribute( "layerName" ); + QString layerName = gmlDoc->documentElement().attribute( QStringLiteral( "layerName" ) ); QgsMessageLog::logMessage( "Adding entry with key: " + layerName + " to external GML data" ); mConfigParser->addExternalGMLData( layerName, gmlDoc ); } else { - QgsMessageLog::logMessage( "Error, could not add external GML to QgsSLDParser" ); + QgsMessageLog::logMessage( QStringLiteral( "Error, could not add external GML to QgsSLDParser" ) ); delete gmlDoc; } } @@ -1927,7 +1927,7 @@ QImage* QgsWmsServer::initializeRendering( QStringList& layersList, QStringList& layerIdList = layerSet( layersList, stylesList, mMapRenderer->destinationCrs() ); #ifdef QGISDEBUG - QgsMessageLog::logMessage( QString( "Number of layers to be rendered. %1" ).arg( layerIdList.count() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Number of layers to be rendered. %1" ).arg( layerIdList.count() ) ); #endif mMapRenderer->setLayerSet( layerIdList ); @@ -1943,14 +1943,14 @@ QImage* QgsWmsServer::createImage( int width, int height ) const if ( width < 0 ) { - width = mParameters.value( "WIDTH", "0" ).toInt( &conversionSuccess ); + width = mParameters.value( QStringLiteral( "WIDTH" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) width = 0; } if ( height < 0 ) { - height = mParameters.value( "HEIGHT", "0" ).toInt( &conversionSuccess ); + height = mParameters.value( QStringLiteral( "HEIGHT" ), QStringLiteral( "0" ) ).toInt( &conversionSuccess ); if ( !conversionSuccess ) { height = 0; @@ -1965,13 +1965,13 @@ QImage* QgsWmsServer::createImage( int width, int height ) const QImage* theImage = nullptr; //is format jpeg? - QString format = mParameters.value( "FORMAT" ); - bool jpeg = format.compare( "jpg", Qt::CaseInsensitive ) == 0 - || format.compare( "jpeg", Qt::CaseInsensitive ) == 0 - || format.compare( "image/jpeg", Qt::CaseInsensitive ) == 0; + QString format = mParameters.value( QStringLiteral( "FORMAT" ) ); + bool jpeg = format.compare( QLatin1String( "jpg" ), Qt::CaseInsensitive ) == 0 + || format.compare( QLatin1String( "jpeg" ), Qt::CaseInsensitive ) == 0 + || format.compare( QLatin1String( "image/jpeg" ), Qt::CaseInsensitive ) == 0; //transparent parameter - bool transparent = mParameters.value( "TRANSPARENT" ).compare( "true", Qt::CaseInsensitive ) == 0; + bool transparent = mParameters.value( QStringLiteral( "TRANSPARENT" ) ).compare( QLatin1String( "true" ), Qt::CaseInsensitive ) == 0; //use alpha channel only if necessary because it slows down performance if ( transparent && !jpeg ) @@ -1994,9 +1994,9 @@ QImage* QgsWmsServer::createImage( int width, int height ) const //Because of backwards compatibility, this parameter is optional double OGC_PX_M = 0.00028; // OGC reference pixel size in meter, also used by qgis int dpm = 1 / OGC_PX_M; - if ( mParameters.contains( "DPI" ) ) + if ( mParameters.contains( QStringLiteral( "DPI" ) ) ) { - int dpi = mParameters[ "DPI" ].toInt( &conversionSuccess ); + int dpi = mParameters[ QStringLiteral( "DPI" )].toInt( &conversionSuccess ); if ( conversionSuccess ) { dpm = dpi / 0.0254; @@ -2019,16 +2019,16 @@ int QgsWmsServer::configureMapRender( const QPaintDevice* paintDevice ) const //map extent bool bboxOk; - QgsRectangle mapExtent = _parseBBOX( mParameters.value( "BBOX", "0,0,0,0" ), bboxOk ); + QgsRectangle mapExtent = _parseBBOX( mParameters.value( QStringLiteral( "BBOX" ), QStringLiteral( "0,0,0,0" ) ), bboxOk ); if ( !bboxOk ) { //throw a service exception - throw QgsMapServiceException( "InvalidParameterValue", "Invalid BBOX parameter" ); + throw QgsMapServiceException( QStringLiteral( "InvalidParameterValue" ), QStringLiteral( "Invalid BBOX parameter" ) ); } QgsUnitTypes::DistanceUnit mapUnits = QgsUnitTypes::DistanceDegrees; - QString crs = mParameters.value( "CRS", mParameters.value( "SRS" ) ); + QString crs = mParameters.value( QStringLiteral( "CRS" ), mParameters.value( QStringLiteral( "SRS" ) ) ); QgsCoordinateReferenceSystem outputCRS; @@ -2037,20 +2037,20 @@ int QgsWmsServer::configureMapRender( const QPaintDevice* paintDevice ) const if ( crs.isEmpty() ) { //disable on the fly projection - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectionsEnabled", 0 ); + QgsProject::instance()->writeEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectionsEnabled" ), 0 ); } else { //enable on the fly projection - QgsMessageLog::logMessage( "enable on the fly projection" ); - QgsProject::instance()->writeEntry( "SpatialRefSys", "/ProjectionsEnabled", 1 ); + QgsMessageLog::logMessage( QStringLiteral( "enable on the fly projection" ) ); + QgsProject::instance()->writeEntry( QStringLiteral( "SpatialRefSys" ), QStringLiteral( "/ProjectionsEnabled" ), 1 ); //destination SRS outputCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( crs ); if ( !outputCRS.isValid() ) { - QgsMessageLog::logMessage( "Error, could not create output CRS from EPSG" ); - throw QgsMapServiceException( "InvalidCRS", "Could not create output CRS" ); + QgsMessageLog::logMessage( QStringLiteral( "Error, could not create output CRS from EPSG" ) ); + throw QgsMapServiceException( QStringLiteral( "InvalidCRS" ), QStringLiteral( "Could not create output CRS" ) ); } //read layer coordinate transforms from project file (e.g. ct with special datum shift) @@ -2073,8 +2073,8 @@ int QgsWmsServer::configureMapRender( const QPaintDevice* paintDevice ) const mMapRenderer->setMapUnits( mapUnits ); // Change x- and y- of BBOX for WMS 1.3.0 if axis inverted - QString version = mParameters.value( "VERSION", "1.3.0" ); - if ( version != "1.1.1" && outputCRS.hasAxisInverted() ) + QString version = mParameters.value( QStringLiteral( "VERSION" ), QStringLiteral( "1.3.0" ) ); + if ( version != QLatin1String( "1.1.1" ) && outputCRS.hasAxisInverted() ) { mapExtent.invert(); } @@ -2096,29 +2096,29 @@ int QgsWmsServer::configureMapRender( const QPaintDevice* paintDevice ) const int QgsWmsServer::readLayersAndStyles( QStringList& layersList, QStringList& stylesList ) const { //get layer and style lists from the parameters trying LAYERS and LAYER as well as STYLE and STYLES for GetLegendGraphic compatibility - layersList = mParameters.value( "LAYER" ).split( ",", QString::SkipEmptyParts ); - layersList = layersList + mParameters.value( "LAYERS" ).split( ",", QString::SkipEmptyParts ); - stylesList = mParameters.value( "STYLE" ).split( ",", QString::SkipEmptyParts ); - stylesList = stylesList + mParameters.value( "STYLES" ).split( ",", QString::SkipEmptyParts ); + layersList = mParameters.value( QStringLiteral( "LAYER" ) ).split( QStringLiteral( "," ), QString::SkipEmptyParts ); + layersList = layersList + mParameters.value( QStringLiteral( "LAYERS" ) ).split( QStringLiteral( "," ), QString::SkipEmptyParts ); + stylesList = mParameters.value( QStringLiteral( "STYLE" ) ).split( QStringLiteral( "," ), QString::SkipEmptyParts ); + stylesList = stylesList + mParameters.value( QStringLiteral( "STYLES" ) ).split( QStringLiteral( "," ), QString::SkipEmptyParts ); return 0; } int QgsWmsServer::initializeSLDParser( QStringList& layersList, QStringList& stylesList ) { - QString xml = mParameters.value( "SLD" ); + QString xml = mParameters.value( QStringLiteral( "SLD" ) ); if ( !xml.isEmpty() ) { //ignore LAYERS and STYLES and take those information from the SLD - QDomDocument* theDocument = new QDomDocument( "user.sld" ); + QDomDocument* theDocument = new QDomDocument( QStringLiteral( "user.sld" ) ); QString errorMsg; int errorLine, errorColumn; if ( !theDocument->setContent( xml, true, &errorMsg, &errorLine, &errorColumn ) ) { //std::cout << xml.toLatin1().data() << std::endl; - QgsMessageLog::logMessage( "Error, could not create DomDocument from SLD" ); - QgsMessageLog::logMessage( QString( "The error message is: %1" ).arg( errorMsg ) ); + QgsMessageLog::logMessage( QStringLiteral( "Error, could not create DomDocument from SLD" ) ); + QgsMessageLog::logMessage( QStringLiteral( "The error message is: %1" ).arg( errorMsg ) ); delete theDocument; return 1; } @@ -2134,7 +2134,7 @@ int QgsWmsServer::initializeSLDParser( QStringList& layersList, QStringList& sty QStringList stylesSTDList; if ( mConfigParser->layersAndStyles( layersSTDList, stylesSTDList ) != 0 ) { - QgsMessageLog::logMessage( "Error, no layers and styles found in SLD" ); + QgsMessageLog::logMessage( QStringLiteral( "Error, no layers and styles found in SLD" ) ); return 2; } QStringList::const_iterator layersIt; @@ -2190,7 +2190,7 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, { searchRect = featureInfoSearchRect( layer, mapRender, renderContext, *infoPoint ); } - else if ( mParameters.contains( "BBOX" ) ) + else if ( mParameters.contains( QStringLiteral( "BBOX" ) ) ) { searchRect = layerRect; } @@ -2294,10 +2294,10 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, outputCrs = mapRender->destinationCrs(); } - if ( infoFormat == "application/vnd.ogc.gml" ) + if ( infoFormat == QLatin1String( "application/vnd.ogc.gml" ) ) { bool withGeom = layer->wkbType() != QgsWkbTypes::NoGeometry && addWktGeometry; - int version = infoFormat.startsWith( "application/vnd.ogc.gml/3" ) ? 3 : 2; + int version = infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml/3" ) ) ? 3 : 2; QString typeName = layer->name(); if ( mConfigParser && mConfigParser->useLayerIds() ) typeName = layer->id(); @@ -2309,15 +2309,15 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, , &attributes #endif ); - QDomElement featureMemberElem = infoDocument.createElement( "gml:featureMember"/*wfs:FeatureMember*/ ); + QDomElement featureMemberElem = infoDocument.createElement( QStringLiteral( "gml:featureMember" )/*wfs:FeatureMember*/ ); featureMemberElem.appendChild( elem ); layerElement.appendChild( featureMemberElem ); continue; } else { - QDomElement featureElement = infoDocument.createElement( "Feature" ); - featureElement.setAttribute( "id", FID_TO_STRING( feature.id() ) ); + QDomElement featureElement = infoDocument.createElement( QStringLiteral( "Feature" ) ); + featureElement.setAttribute( QStringLiteral( "id" ), FID_TO_STRING( feature.id() ) ); layerElement.appendChild( featureElement ); //read all attribute values from the feature @@ -2340,9 +2340,9 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, //replace attribute name if there is an attribute alias? QString attributeName = layer->attributeDisplayName( i ); - QDomElement attributeElement = infoDocument.createElement( "Attribute" ); - attributeElement.setAttribute( "name", attributeName ); - attributeElement.setAttribute( "value", + QDomElement attributeElement = infoDocument.createElement( QStringLiteral( "Attribute" ) ); + attributeElement.setAttribute( QStringLiteral( "name" ), attributeName ); + attributeElement.setAttribute( QStringLiteral( "value" ), replaceValueMapAndRelation( layer, i, featureAttributes[i].isNull() ? QString::null : QgsExpression::replaceExpressionText( featureAttributes[i].toString(), &renderContext.expressionContext() ) @@ -2355,21 +2355,21 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, QString mapTip = layer->mapTipTemplate(); if ( !mapTip.isEmpty() ) { - QDomElement maptipElem = infoDocument.createElement( "Attribute" ); - maptipElem.setAttribute( "name", "maptip" ); - maptipElem.setAttribute( "value", QgsExpression::replaceExpressionText( mapTip, &renderContext.expressionContext() ) ); + QDomElement maptipElem = infoDocument.createElement( QStringLiteral( "Attribute" ) ); + maptipElem.setAttribute( QStringLiteral( "name" ), QStringLiteral( "maptip" ) ); + maptipElem.setAttribute( QStringLiteral( "value" ), QgsExpression::replaceExpressionText( mapTip, &renderContext.expressionContext() ) ); featureElement.appendChild( maptipElem ); } //append feature bounding box to feature info xml if ( layer->wkbType() != QgsWkbTypes::NoGeometry && hasGeometry && mapRender && mConfigParser ) { - QDomElement bBoxElem = infoDocument.createElement( "BoundingBox" ); - bBoxElem.setAttribute( version == "1.1.1" ? "SRS" : "CRS", outputCrs.authid() ); - bBoxElem.setAttribute( "minx", qgsDoubleToString( box.xMinimum(), getWMSPrecision( 8 ) ) ); - bBoxElem.setAttribute( "maxx", qgsDoubleToString( box.xMaximum(), getWMSPrecision( 8 ) ) ); - bBoxElem.setAttribute( "miny", qgsDoubleToString( box.yMinimum(), getWMSPrecision( 8 ) ) ); - bBoxElem.setAttribute( "maxy", qgsDoubleToString( box.yMaximum(), getWMSPrecision( 8 ) ) ); + QDomElement bBoxElem = infoDocument.createElement( QStringLiteral( "BoundingBox" ) ); + bBoxElem.setAttribute( version == QLatin1String( "1.1.1" ) ? "SRS" : "CRS", outputCrs.authid() ); + bBoxElem.setAttribute( QStringLiteral( "minx" ), qgsDoubleToString( box.xMinimum(), getWMSPrecision( 8 ) ) ); + bBoxElem.setAttribute( QStringLiteral( "maxx" ), qgsDoubleToString( box.xMaximum(), getWMSPrecision( 8 ) ) ); + bBoxElem.setAttribute( QStringLiteral( "miny" ), qgsDoubleToString( box.yMinimum(), getWMSPrecision( 8 ) ) ); + bBoxElem.setAttribute( QStringLiteral( "maxy" ), qgsDoubleToString( box.yMaximum(), getWMSPrecision( 8 ) ) ); featureElement.appendChild( bBoxElem ); } @@ -2398,10 +2398,10 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, } } } - QDomElement geometryElement = infoDocument.createElement( "Attribute" ); - geometryElement.setAttribute( "name", "geometry" ); - geometryElement.setAttribute( "value", geom.exportToWkt( getWMSPrecision( 8 ) ) ); - geometryElement.setAttribute( "type", "derived" ); + QDomElement geometryElement = infoDocument.createElement( QStringLiteral( "Attribute" ) ); + geometryElement.setAttribute( QStringLiteral( "name" ), QStringLiteral( "geometry" ) ); + geometryElement.setAttribute( QStringLiteral( "value" ), geom.exportToWkt( getWMSPrecision( 8 ) ) ); + geometryElement.setAttribute( QStringLiteral( "type" ), QStringLiteral( "derived" ) ); featureElement.appendChild( geometryElement ); } } @@ -2429,7 +2429,7 @@ int QgsWmsServer::featureInfoFromRasterLayer( QgsRasterLayer* layer, return 1; } - QgsMessageLog::logMessage( QString( "infoPoint: %1 %2" ).arg( infoPoint->x() ).arg( infoPoint->y() ) ); + QgsMessageLog::logMessage( QStringLiteral( "infoPoint: %1 %2" ).arg( infoPoint->x() ).arg( infoPoint->y() ) ); if ( !( layer->dataProvider()->capabilities() & QgsRasterDataProvider::IdentifyValue ) ) { @@ -2448,7 +2448,7 @@ int QgsWmsServer::featureInfoFromRasterLayer( QgsRasterLayer* layer, attributes = layer->dataProvider()->identify( *infoPoint, QgsRaster::IdentifyFormatValue, mMapRenderer->extent(), mMapRenderer->outputSize().width(), mMapRenderer->outputSize().height() ).results(); } - if ( infoFormat == "application/vnd.ogc.gml" ) + if ( infoFormat == QLatin1String( "application/vnd.ogc.gml" ) ) { QgsFeature feature; QgsFields fields; @@ -2462,7 +2462,7 @@ int QgsWmsServer::featureInfoFromRasterLayer( QgsRasterLayer* layer, feature.setFields( fields ); QgsCoordinateReferenceSystem layerCrs = layer->crs(); - int version = infoFormat.startsWith( "application/vnd.ogc.gml/3" ) ? 3 : 2; + int version = infoFormat.startsWith( QLatin1String( "application/vnd.ogc.gml/3" ) ) ? 3 : 2; QString typeName = layer->name(); if ( mConfigParser && mConfigParser->useLayerIds() ) typeName = layer->id(); @@ -2476,9 +2476,9 @@ int QgsWmsServer::featureInfoFromRasterLayer( QgsRasterLayer* layer, { for ( QMap::const_iterator it = attributes.constBegin(); it != attributes.constEnd(); ++it ) { - QDomElement attributeElement = infoDocument.createElement( "Attribute" ); - attributeElement.setAttribute( "name", layer->bandName( it.key() ) ); - attributeElement.setAttribute( "value", QString::number( it.value().toDouble() ) ); + QDomElement attributeElement = infoDocument.createElement( QStringLiteral( "Attribute" ) ); + attributeElement.setAttribute( QStringLiteral( "name" ), layer->bandName( it.key() ) ); + attributeElement.setAttribute( QStringLiteral( "value" ), QString::number( it.value().toDouble() ) ); layerElement.appendChild( attributeElement ); } } @@ -2494,7 +2494,7 @@ QStringList QgsWmsServer::layerSet( const QStringList &layersList, QStringList::const_iterator llstIt; QStringList::const_iterator slstIt; QgsMapLayer* theMapLayer = nullptr; - QgsMessageLog::logMessage( QString( "Calculating layerset using %1 layers, %2 styles and CRS %3" ).arg( layersList.count() ).arg( stylesList.count() ).arg( destCRS.description() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Calculating layerset using %1 layers, %2 styles and CRS %3" ).arg( layersList.count() ).arg( stylesList.count() ).arg( destCRS.description() ) ); for ( llstIt = layersList.begin(), slstIt = stylesList.begin(); llstIt != layersList.end(); ++llstIt ) { QString styleName; @@ -2526,7 +2526,7 @@ QStringList QgsWmsServer::layerSet( const QStringList &layersList, lName = theMapLayer->id(); else if ( !theMapLayer->shortName().isEmpty() ) lName = theMapLayer->shortName(); - QgsMessageLog::logMessage( QString( "Checking layer: %1" ).arg( lName ) ); + QgsMessageLog::logMessage( QStringLiteral( "Checking layer: %1" ).arg( lName ) ); //test if layer is visible in requested scale bool useScaleConstraint = ( scaleDenominator > 0 && theMapLayer->hasScaleBasedVisibility() ); if ( !useScaleConstraint || @@ -2539,8 +2539,8 @@ QStringList QgsWmsServer::layerSet( const QStringList &layersList, } else { - QgsMessageLog::logMessage( "Layer or style not defined, aborting" ); - throw QgsMapServiceException( "LayerNotDefined", "Layer '" + *llstIt + "' and/or style '" + styleName + "' not defined" ); + QgsMessageLog::logMessage( QStringLiteral( "Layer or style not defined, aborting" ) ); + throw QgsMapServiceException( QStringLiteral( "LayerNotDefined" ), "Layer '" + *llstIt + "' and/or style '" + styleName + "' not defined" ); } } @@ -2560,14 +2560,14 @@ void QgsWmsServer::applyRequestedLayerFilters( const QStringList& layerList , QH return; } - QString filterParameter = mParameters.value( "FILTER" ); + QString filterParameter = mParameters.value( QStringLiteral( "FILTER" ) ); if ( !filterParameter.isEmpty() ) { - QStringList layerSplit = filterParameter.split( ";" ); + QStringList layerSplit = filterParameter.split( QStringLiteral( ";" ) ); QStringList::const_iterator layerIt = layerSplit.constBegin(); for ( ; layerIt != layerSplit.constEnd(); ++layerIt ) { - QStringList eqSplit = layerIt->split( ":" ); + QStringList eqSplit = layerIt->split( QStringLiteral( ":" ) ); if ( eqSplit.size() < 2 ) { continue; @@ -2576,7 +2576,7 @@ void QgsWmsServer::applyRequestedLayerFilters( const QStringList& layerList , QH //filter string could be unsafe (danger of sql injection) if ( !testFilterStringSafety( eqSplit.at( 1 ) ) ) { - throw QgsMapServiceException( "Filter string rejected", "The filter string " + eqSplit.at( 1 ) + + throw QgsMapServiceException( QStringLiteral( "Filter string rejected" ), "The filter string " + eqSplit.at( 1 ) + " has been rejected because of security reasons. Note: Text strings have to be enclosed in single or double quotes. " + "A space between each word / special character is mandatory. Allowed Keywords and special characters are " + "AND,OR,IN,<,>=,>,>=,!=,',',(,),DMETAPHONE,SOUNDEX. Not allowed are semicolons in the filter expression." ); @@ -2662,36 +2662,36 @@ void QgsWmsServer::applyAccessControlLayersFilters( const QStringList& layerList bool QgsWmsServer::testFilterStringSafety( const QString& filter ) const { //; too dangerous for sql injections - if ( filter.contains( ";" ) ) + if ( filter.contains( QLatin1String( ";" ) ) ) { return false; } - QStringList tokens = filter.split( " ", QString::SkipEmptyParts ); - groupStringList( tokens, "'" ); - groupStringList( tokens, "\"" ); + QStringList tokens = filter.split( QStringLiteral( " " ), QString::SkipEmptyParts ); + groupStringList( tokens, QStringLiteral( "'" ) ); + groupStringList( tokens, QStringLiteral( "\"" ) ); QStringList::const_iterator tokenIt = tokens.constBegin(); for ( ; tokenIt != tokens.constEnd(); ++tokenIt ) { //whitelist of allowed characters and keywords - if ( tokenIt->compare( "," ) == 0 - || tokenIt->compare( "(" ) == 0 - || tokenIt->compare( ")" ) == 0 - || tokenIt->compare( "=" ) == 0 - || tokenIt->compare( "!=" ) == 0 - || tokenIt->compare( "<" ) == 0 - || tokenIt->compare( "<=" ) == 0 - || tokenIt->compare( ">" ) == 0 - || tokenIt->compare( ">=" ) == 0 - || tokenIt->compare( "%" ) == 0 - || tokenIt->compare( "AND", Qt::CaseInsensitive ) == 0 - || tokenIt->compare( "OR", Qt::CaseInsensitive ) == 0 - || tokenIt->compare( "IN", Qt::CaseInsensitive ) == 0 - || tokenIt->compare( "LIKE", Qt::CaseInsensitive ) == 0 - || tokenIt->compare( "ILIKE", Qt::CaseInsensitive ) == 0 - || tokenIt->compare( "DMETAPHONE", Qt::CaseInsensitive ) == 0 - || tokenIt->compare( "SOUNDEX", Qt::CaseInsensitive ) == 0 ) + if ( tokenIt->compare( QLatin1String( "," ) ) == 0 + || tokenIt->compare( QLatin1String( "(" ) ) == 0 + || tokenIt->compare( QLatin1String( ")" ) ) == 0 + || tokenIt->compare( QLatin1String( "=" ) ) == 0 + || tokenIt->compare( QLatin1String( "!=" ) ) == 0 + || tokenIt->compare( QLatin1String( "<" ) ) == 0 + || tokenIt->compare( QLatin1String( "<=" ) ) == 0 + || tokenIt->compare( QLatin1String( ">" ) ) == 0 + || tokenIt->compare( QLatin1String( ">=" ) ) == 0 + || tokenIt->compare( QLatin1String( "%" ) ) == 0 + || tokenIt->compare( QLatin1String( "AND" ), Qt::CaseInsensitive ) == 0 + || tokenIt->compare( QLatin1String( "OR" ), Qt::CaseInsensitive ) == 0 + || tokenIt->compare( QLatin1String( "IN" ), Qt::CaseInsensitive ) == 0 + || tokenIt->compare( QLatin1String( "LIKE" ), Qt::CaseInsensitive ) == 0 + || tokenIt->compare( QLatin1String( "ILIKE" ), Qt::CaseInsensitive ) == 0 + || tokenIt->compare( QLatin1String( "DMETAPHONE" ), Qt::CaseInsensitive ) == 0 + || tokenIt->compare( QLatin1String( "SOUNDEX" ), Qt::CaseInsensitive ) == 0 ) { continue; } @@ -2707,7 +2707,7 @@ bool QgsWmsServer::testFilterStringSafety( const QString& filter ) const //numeric strings need to be quoted once either with single or with double quotes //empty strings are ok - if ( *tokenIt == "''" ) + if ( *tokenIt == QLatin1String( "''" ) ) { continue; } @@ -2793,7 +2793,7 @@ QStringList QgsWmsServer::applyFeatureSelections( const QStringList& layerList ) return layersWithSelections; } - QString selectionString = mParameters.value( "SELECTION" ); + QString selectionString = mParameters.value( QStringLiteral( "SELECTION" ) ); if ( selectionString.isEmpty() ) { return layersWithSelections; @@ -2802,7 +2802,7 @@ QStringList QgsWmsServer::applyFeatureSelections( const QStringList& layerList ) Q_FOREACH ( const QString& selectionLayer, selectionString.split( ";" ) ) { //separate layer name from id list - QStringList layerIdSplit = selectionLayer.split( ":" ); + QStringList layerIdSplit = selectionLayer.split( QStringLiteral( ":" ) ); if ( layerIdSplit.size() < 2 ) { continue; @@ -2835,7 +2835,7 @@ QStringList QgsWmsServer::applyFeatureSelections( const QStringList& layerList ) continue; } - QStringList idList = layerIdSplit.at( 1 ).split( "," ); + QStringList idList = layerIdSplit.at( 1 ).split( QStringLiteral( "," ) ); QgsFeatureIds selectedIds; Q_FOREACH ( const QString& id, idList ) @@ -2872,12 +2872,12 @@ void QgsWmsServer::applyOpacities( const QStringList& layerList, QList< QPair< Q QList< QPair< QgsVectorLayer*, double > >& labelBufferTransparencies ) { //get opacity list - QMap::const_iterator opIt = mParameters.constFind( "OPACITIES" ); + QMap::const_iterator opIt = mParameters.constFind( QStringLiteral( "OPACITIES" ) ); if ( opIt == mParameters.constEnd() ) { return; } - QStringList opacityList = opIt.value().split( "," ); + QStringList opacityList = opIt.value().split( QStringLiteral( "," ) ); //collect leaf layers and their opacity QVector< QPair< QgsMapLayer*, int > > layerOpacityList; @@ -2891,7 +2891,7 @@ void QgsWmsServer::applyOpacities( const QStringList& layerList, QList< QPair< Q { continue; } - QList llist = mConfigParser->mapLayerFromStyle( *lIt, "" ); + QList llist = mConfigParser->mapLayerFromStyle( *lIt, QLatin1String( "" ) ); QList::const_iterator lListIt = llist.constBegin(); for ( ; lListIt != llist.constEnd(); ++lListIt ) { @@ -2933,14 +2933,14 @@ void QgsWmsServer::applyOpacities( const QStringList& layerList, QList< QPair< Q } //labeling - if ( vl->customProperty( "labeling/enabled" ).toString() == "true" ) + if ( vl->customProperty( QStringLiteral( "labeling/enabled" ) ).toString() == QLatin1String( "true" ) ) { - double labelTransparency = vl->customProperty( "labeling/textTransp" ).toDouble(); + double labelTransparency = vl->customProperty( QStringLiteral( "labeling/textTransp" ) ).toDouble(); labelTransparencies.push_back( qMakePair( vl, labelTransparency ) ); - vl->setCustomProperty( "labeling/textTransp", labelTransparency + ( 100 - labelTransparency ) * ( 1.0 - opacityRatio ) ); - double bufferTransparency = vl->customProperty( "labeling/bufferTransp" ).toDouble(); + vl->setCustomProperty( QStringLiteral( "labeling/textTransp" ), labelTransparency + ( 100 - labelTransparency ) * ( 1.0 - opacityRatio ) ); + double bufferTransparency = vl->customProperty( QStringLiteral( "labeling/bufferTransp" ) ).toDouble(); labelBufferTransparencies.push_back( qMakePair( vl, bufferTransparency ) ); - vl->setCustomProperty( "labeling/bufferTransp", bufferTransparency + ( 100 - bufferTransparency )* ( 1.0 - opacityRatio ) ); + vl->setCustomProperty( QStringLiteral( "labeling/bufferTransp" ), bufferTransparency + ( 100 - bufferTransparency )* ( 1.0 - opacityRatio ) ); } } else if ( ml->type() == QgsMapLayer::RasterLayer ) @@ -2984,13 +2984,13 @@ void QgsWmsServer::restoreOpacities( QList< QPair< QgsVectorLayer*, QgsFeatureRe QList< QPair< QgsVectorLayer*, double > >::iterator loIt = labelOpacities.begin(); for ( ; loIt != labelOpacities.end(); ++loIt ) { - ( *loIt ).first->setCustomProperty( "labeling/textTransp", ( *loIt ).second ); + ( *loIt ).first->setCustomProperty( QStringLiteral( "labeling/textTransp" ), ( *loIt ).second ); } QList< QPair< QgsVectorLayer*, double > >::iterator lboIt = labelBufferOpacities.begin(); for ( ; lboIt != labelBufferOpacities.end(); ++lboIt ) { - ( *lboIt ).first->setCustomProperty( "labeling/bufferTransp", ( *lboIt ).second ); + ( *lboIt ).first->setCustomProperty( QStringLiteral( "labeling/bufferTransp" ), ( *lboIt ).second ); } } @@ -2999,7 +2999,7 @@ bool QgsWmsServer::checkMaximumWidthHeight() const //test if maxWidth / maxHeight set and WIDTH / HEIGHT parameter is in the range if ( mConfigParser->maxWidth() != -1 ) { - QMap::const_iterator widthIt = mParameters.find( "WIDTH" ); + QMap::const_iterator widthIt = mParameters.find( QStringLiteral( "WIDTH" ) ); if ( widthIt != mParameters.constEnd() ) { if ( widthIt->toInt() > mConfigParser->maxWidth() ) @@ -3010,7 +3010,7 @@ bool QgsWmsServer::checkMaximumWidthHeight() const } if ( mConfigParser->maxHeight() != -1 ) { - QMap::const_iterator heightIt = mParameters.find( "HEIGHT" ); + QMap::const_iterator heightIt = mParameters.find( QStringLiteral( "HEIGHT" ) ); if ( heightIt != mParameters.constEnd() ) { if ( heightIt->toInt() > mConfigParser->maxHeight() ) @@ -3049,40 +3049,40 @@ QString QgsWmsServer::serviceUrl() const } } - if ( QString( getenv( "HTTPS" ) ).compare( "on", Qt::CaseInsensitive ) == 0 ) + if ( QString( getenv( "HTTPS" ) ).compare( QLatin1String( "on" ), Qt::CaseInsensitive ) == 0 ) { - mapUrl.setScheme( "https" ); + mapUrl.setScheme( QStringLiteral( "https" ) ); } else { - mapUrl.setScheme( "http" ); + mapUrl.setScheme( QStringLiteral( "http" ) ); } QList > queryItems = mapUrl.queryItems(); QList >::const_iterator queryIt = queryItems.constBegin(); for ( ; queryIt != queryItems.constEnd(); ++queryIt ) { - if ( queryIt->first.compare( "REQUEST", Qt::CaseInsensitive ) == 0 ) + if ( queryIt->first.compare( QLatin1String( "REQUEST" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "VERSION", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "VERSION" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "SERVICE", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "SERVICE" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "LAYERS", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "LAYERS" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "SLD_VERSION", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "SLD_VERSION" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } - else if ( queryIt->first.compare( "_DC", Qt::CaseInsensitive ) == 0 ) + else if ( queryIt->first.compare( QLatin1String( "_DC" ), Qt::CaseInsensitive ) == 0 ) { mapUrl.removeQueryItem( queryIt->first ); } @@ -3092,7 +3092,7 @@ QString QgsWmsServer::serviceUrl() const void QgsWmsServer::addXmlDeclaration( QDomDocument& doc ) const { - QDomProcessingInstruction xmlDeclaration = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"utf-8\"" ); + QDomProcessingInstruction xmlDeclaration = doc.createProcessingInstruction( QStringLiteral( "xml" ), QStringLiteral( "version=\"1.0\" encoding=\"utf-8\"" ) ); doc.appendChild( xmlDeclaration ); } @@ -3108,19 +3108,19 @@ void QgsWmsServer::convertFeatureInfoToSIA2045( QDomDocument& doc ) QDomElement currentAttributeElem; QString currentLayerName; QDomElement currentLayerElem; - QDomNodeList layerNodeList = infoDocElement.elementsByTagName( "Layer" ); + QDomNodeList layerNodeList = infoDocElement.elementsByTagName( QStringLiteral( "Layer" ) ); for ( int i = 0; i < layerNodeList.size(); ++i ) { currentLayerElem = layerNodeList.at( i ).toElement(); - currentLayerName = currentLayerElem.attribute( "name" ); + currentLayerName = currentLayerElem.attribute( QStringLiteral( "name" ) ); QDomElement currentFeatureElem; - QDomNodeList featureList = currentLayerElem.elementsByTagName( "Feature" ); + QDomNodeList featureList = currentLayerElem.elementsByTagName( QStringLiteral( "Feature" ) ); if ( featureList.size() < 1 ) { //raster? - QDomNodeList attributeList = currentLayerElem.elementsByTagName( "Attribute" ); + QDomNodeList attributeList = currentLayerElem.elementsByTagName( QStringLiteral( "Attribute" ) ); QDomElement rasterLayerElem; if ( !attributeList.isEmpty() ) { @@ -3129,8 +3129,8 @@ void QgsWmsServer::convertFeatureInfoToSIA2045( QDomDocument& doc ) for ( int j = 0; j < attributeList.size(); ++j ) { currentAttributeElem = attributeList.at( j ).toElement(); - currentAttributeName = currentAttributeElem.attribute( "name" ); - currentAttributeValue = currentAttributeElem.attribute( "value" ); + currentAttributeName = currentAttributeElem.attribute( QStringLiteral( "name" ) ); + currentAttributeValue = currentAttributeElem.attribute( QStringLiteral( "value" ) ); QDomElement outAttributeElem = SIAInfoDoc.createElement( currentAttributeName ); QDomText outAttributeText = SIAInfoDoc.createTextNode( currentAttributeValue ); outAttributeElem.appendChild( outAttributeText ); @@ -3145,16 +3145,16 @@ void QgsWmsServer::convertFeatureInfoToSIA2045( QDomDocument& doc ) { //property attributes QSet layerPropertyAttributes; - QString currentLayerId = currentLayerElem.attribute( "id" ); + QString currentLayerId = currentLayerElem.attribute( QStringLiteral( "id" ) ); if ( !currentLayerId.isEmpty() ) { QgsMapLayer* currentLayer = QgsMapLayerRegistry::instance()->mapLayer( currentLayerId ); if ( currentLayer ) { - QString WMSPropertyAttributesString = currentLayer->customProperty( "WMSPropertyAttributes" ).toString(); + QString WMSPropertyAttributesString = currentLayer->customProperty( QStringLiteral( "WMSPropertyAttributes" ) ).toString(); if ( !WMSPropertyAttributesString.isEmpty() ) { - QStringList propertyList = WMSPropertyAttributesString.split( "//" ); + QStringList propertyList = WMSPropertyAttributesString.split( QStringLiteral( "//" ) ); QStringList::const_iterator propertyIt = propertyList.constBegin(); for ( ; propertyIt != propertyList.constEnd(); ++propertyIt ) { @@ -3169,20 +3169,20 @@ void QgsWmsServer::convertFeatureInfoToSIA2045( QDomDocument& doc ) { QDomElement SIAFeatureElem = SIAInfoDoc.createElement( currentLayerName ); currentFeatureElem = featureList.at( j ).toElement(); - QDomNodeList attributeList = currentFeatureElem.elementsByTagName( "Attribute" ); + QDomNodeList attributeList = currentFeatureElem.elementsByTagName( QStringLiteral( "Attribute" ) ); for ( int k = 0; k < attributeList.size(); ++k ) { currentAttributeElem = attributeList.at( k ).toElement(); - currentAttributeName = currentAttributeElem.attribute( "name" ); - currentAttributeValue = currentAttributeElem.attribute( "value" ); + currentAttributeName = currentAttributeElem.attribute( QStringLiteral( "name" ) ); + currentAttributeValue = currentAttributeElem.attribute( QStringLiteral( "value" ) ); if ( layerPropertyAttributes.contains( currentAttributeName ) ) { - QDomElement propertyElem = SIAInfoDoc.createElement( "property" ); - QDomElement identifierElem = SIAInfoDoc.createElement( "identifier" ); + QDomElement propertyElem = SIAInfoDoc.createElement( QStringLiteral( "property" ) ); + QDomElement identifierElem = SIAInfoDoc.createElement( QStringLiteral( "identifier" ) ); QDomText identifierText = SIAInfoDoc.createTextNode( currentAttributeName ); identifierElem.appendChild( identifierText ); - QDomElement valueElem = SIAInfoDoc.createElement( "value" ); + QDomElement valueElem = SIAInfoDoc.createElement( QStringLiteral( "value" ) ); QDomText valueText = SIAInfoDoc.createTextNode( currentAttributeValue ); valueElem.appendChild( valueText ); propertyElem.appendChild( identifierElem ); @@ -3224,7 +3224,7 @@ QDomElement QgsWmsServer::createFeatureGML( { //qgs:%TYPENAME% QDomElement typeNameElement = doc.createElement( "qgs:" + typeName /*qgs:%TYPENAME%*/ ); - typeNameElement.setAttribute( "fid", typeName + "." + QString::number( feat->id() ) ); + typeNameElement.setAttribute( QStringLiteral( "fid" ), typeName + "." + QString::number( feat->id() ) ); QgsCoordinateTransform transform; if ( layer && layer->crs() != crs ) @@ -3254,11 +3254,11 @@ QDomElement QgsWmsServer::createFeatureGML( } catch ( QgsCsException &e ) { - QgsMessageLog::logMessage( QString( "Transform error caught: %1" ).arg( e.what() ) ); + QgsMessageLog::logMessage( QStringLiteral( "Transform error caught: %1" ).arg( e.what() ) ); } } - QDomElement bbElem = doc.createElement( "gml:boundedBy" ); + QDomElement bbElem = doc.createElement( QStringLiteral( "gml:boundedBy" ) ); QDomElement boxElem; if ( version < 3 ) { @@ -3271,7 +3271,7 @@ QDomElement QgsWmsServer::createFeatureGML( if ( crs.isValid() ) { - boxElem.setAttribute( "srsName", crs.authid() ); + boxElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } bbElem.appendChild( boxElem ); typeNameElement.appendChild( bbElem ); @@ -3286,7 +3286,7 @@ QDomElement QgsWmsServer::createFeatureGML( geom.transform( transform ); } - QDomElement geomElem = doc.createElement( "qgs:geometry" ); + QDomElement geomElem = doc.createElement( QStringLiteral( "qgs:geometry" ) ); QDomElement gmlElem; if ( version < 3 ) { @@ -3294,14 +3294,14 @@ QDomElement QgsWmsServer::createFeatureGML( } else { - gmlElem = QgsOgcUtils::geometryToGML( &geom, doc, "GML3", 8 ); + gmlElem = QgsOgcUtils::geometryToGML( &geom, doc, QStringLiteral( "GML3" ), 8 ); } if ( !gmlElem.isNull() ) { if ( crs.isValid() ) { - gmlElem.setAttribute( "srsName", crs.authid() ); + gmlElem.setAttribute( QStringLiteral( "srsName" ), crs.authid() ); } geomElem.appendChild( gmlElem ); typeNameElement.appendChild( geomElem ); @@ -3325,7 +3325,7 @@ QDomElement QgsWmsServer::createFeatureGML( continue; } - QDomElement fieldElem = doc.createElement( "qgs:" + attributeName.replace( QString( " " ), QString( "_" ) ) ); + QDomElement fieldElem = doc.createElement( "qgs:" + attributeName.replace( QStringLiteral( " " ), QStringLiteral( "_" ) ) ); QString fieldTextString = featureAttributes.at( i ).toString(); if ( layer ) { @@ -3344,7 +3344,7 @@ QDomElement QgsWmsServer::createFeatureGML( if ( !mapTip.isEmpty() ) { QString fieldTextString = QgsExpression::replaceExpressionText( mapTip, &expressionContext ); - QDomElement fieldElem = doc.createElement( "qgs:maptip" ); + QDomElement fieldElem = doc.createElement( QStringLiteral( "qgs:maptip" ) ); QDomText maptipText = doc.createTextNode( fieldTextString ); fieldElem.appendChild( maptipText ); typeNameElement.appendChild( fieldElem ); @@ -3360,14 +3360,14 @@ QString QgsWmsServer::replaceValueMapAndRelation( QgsVectorLayer* vl, int idx, c if ( QgsEditorWidgetFactory *factory = QgsEditorWidgetRegistry::instance()->factory( setup.type() ) ) { QString value( factory->representValue( vl, idx, setup.config(), QVariant(), attributeVal ) ); - if ( setup.config().value( "AllowMulti" ).toBool() && value.startsWith( "{" ) && value.endsWith( "}" ) ) + if ( setup.config().value( QStringLiteral( "AllowMulti" ) ).toBool() && value.startsWith( QLatin1String( "{" ) ) && value.endsWith( QLatin1String( "}" ) ) ) { value = value.mid( 1, value.size() - 2 ); } return value; } else - return QString( "(%1)" ).arg( attributeVal ); + return QStringLiteral( "(%1)" ).arg( attributeVal ); } int QgsWmsServer::getImageQuality() const @@ -3377,11 +3377,11 @@ int QgsWmsServer::getImageQuality() const int imageQuality = mConfigParser->imageQuality(); // Then checks if a parameter is given, if so use it instead - if ( mParameters.contains( "IMAGE_QUALITY" ) ) + if ( mParameters.contains( QStringLiteral( "IMAGE_QUALITY" ) ) ) { bool conversionSuccess; int imageQualityParameter; - imageQualityParameter = mParameters[ "IMAGE_QUALITY" ].toInt( &conversionSuccess ); + imageQualityParameter = mParameters[ QStringLiteral( "IMAGE_QUALITY" )].toInt( &conversionSuccess ); if ( conversionSuccess ) { imageQuality = imageQualityParameter; @@ -3396,11 +3396,11 @@ int QgsWmsServer::getWMSPrecision( int defaultValue = 8 ) const int WMSPrecision = mConfigParser->wmsPrecision(); // Then checks if a parameter is given, if so use it instead - if ( mParameters.contains( "WMS_PRECISION" ) ) + if ( mParameters.contains( QStringLiteral( "WMS_PRECISION" ) ) ) { bool conversionSuccess; int WMSPrecisionParameter; - WMSPrecisionParameter = mParameters[ "WMS_PRECISION" ].toInt( &conversionSuccess ); + WMSPrecisionParameter = mParameters[ QStringLiteral( "WMS_PRECISION" )].toInt( &conversionSuccess ); if ( conversionSuccess ) { WMSPrecision = WMSPrecisionParameter; @@ -3423,7 +3423,7 @@ QgsRectangle QgsWmsServer::featureInfoSearchRect( QgsVectorLayer* ml, QgsMapRend double mapUnitTolerance = 0.0; if ( ml->geometryType() == QgsWkbTypes::PolygonGeometry ) { - QMap::const_iterator tolIt = mParameters.find( "FI_POLYGON_TOLERANCE" ); + QMap::const_iterator tolIt = mParameters.find( QStringLiteral( "FI_POLYGON_TOLERANCE" ) ); if ( tolIt != mParameters.constEnd() ) { mapUnitTolerance = tolIt.value().toInt() * rct.mapToPixel().mapUnitsPerPixel(); @@ -3435,7 +3435,7 @@ QgsRectangle QgsWmsServer::featureInfoSearchRect( QgsVectorLayer* ml, QgsMapRend } else if ( ml->geometryType() == QgsWkbTypes::LineGeometry ) { - QMap::const_iterator tolIt = mParameters.find( "FI_LINE_TOLERANCE" ); + QMap::const_iterator tolIt = mParameters.find( QStringLiteral( "FI_LINE_TOLERANCE" ) ); if ( tolIt != mParameters.constEnd() ) { mapUnitTolerance = tolIt.value().toInt() * rct.mapToPixel().mapUnitsPerPixel(); @@ -3447,7 +3447,7 @@ QgsRectangle QgsWmsServer::featureInfoSearchRect( QgsVectorLayer* ml, QgsMapRend } else //points { - QMap::const_iterator tolIt = mParameters.find( "FI_POINT_TOLERANCE" ); + QMap::const_iterator tolIt = mParameters.find( QStringLiteral( "FI_POINT_TOLERANCE" ) ); if ( tolIt != mParameters.constEnd() ) { mapUnitTolerance = tolIt.value().toInt() * rct.mapToPixel().mapUnitsPerPixel(); @@ -3466,12 +3466,12 @@ QgsRectangle QgsWmsServer::featureInfoSearchRect( QgsVectorLayer* ml, QgsMapRend void QgsWmsServer::readFormatOptions( QMap& formatOptions ) const { formatOptions.clear(); - QString fo = mParameters.value( "FORMAT_OPTIONS" ); - QStringList formatOptionsList = fo.split( ";" ); + QString fo = mParameters.value( QStringLiteral( "FORMAT_OPTIONS" ) ); + QStringList formatOptionsList = fo.split( QStringLiteral( ";" ) ); QStringList::const_iterator optionsIt = formatOptionsList.constBegin(); for ( ; optionsIt != formatOptionsList.constEnd(); ++optionsIt ) { - int equalIdx = optionsIt->indexOf( ":" ); + int equalIdx = optionsIt->indexOf( QLatin1String( ":" ) ); if ( equalIdx > 0 && equalIdx < ( optionsIt->length() - 1 ) ) { formatOptions.insert( optionsIt->left( equalIdx ).toUpper(), optionsIt->right( optionsIt->length() - equalIdx - 1 ).toUpper() ); @@ -3486,10 +3486,10 @@ void QgsWmsServer::readDxfLayerSettings( QList< QPair >& QSet wfsLayers = QSet::fromList( mConfigParser->wfsLayerNames() ); QStringList layerAttributes; - QMap::const_iterator layerAttributesIt = formatOptionsMap.find( "LAYERATTRIBUTES" ); + QMap::const_iterator layerAttributesIt = formatOptionsMap.find( QStringLiteral( "LAYERATTRIBUTES" ) ); if ( layerAttributesIt != formatOptionsMap.constEnd() ) { - layerAttributes = formatOptionsMap.value( "LAYERATTRIBUTES" ).split( "," ); + layerAttributes = formatOptionsMap.value( QStringLiteral( "LAYERATTRIBUTES" ) ).split( QStringLiteral( "," ) ); } //LAYERS and STYLES diff --git a/src/server/qgswmsserver.h b/src/server/qgswmsserver.h index 5053531e9891..5c3cef438912 100644 --- a/src/server/qgswmsserver.h +++ b/src/server/qgswmsserver.h @@ -81,7 +81,7 @@ class QgsWmsServer: public QgsOWSServer /** Returns an XML file with the capabilities description (as described in the WMS specs) @param version WMS version (1.1.1 or 1.3.0) @param fullProjectInformation If true: add extended project information (does not validate against WMS schema)*/ - QDomDocument getCapabilities( const QString &version = "1.3.0", bool fullProjectInformation = false ); + QDomDocument getCapabilities( const QString &version = QStringLiteral( "1.3.0" ), bool fullProjectInformation = false ); QDomDocument getContext(); /** Returns the map legend as an image (or a null pointer in case of error). The caller takes ownership @@ -111,7 +111,7 @@ class QgsWmsServer: public QgsOWSServer /** Creates an xml document that describes the result of the getFeatureInfo request. @return 0 in case of success*/ - int getFeatureInfo( QDomDocument& result, const QString& version = "1.3.0" ); + int getFeatureInfo( QDomDocument& result, const QString& version = QStringLiteral( "1.3.0" ) ); /** Sets configuration parser for administration settings. Does not take ownership*/ void setAdminConfigParser( QgsWmsConfigParser* parser ) { mConfigParser = parser; } diff --git a/tests/bench/main.cpp b/tests/bench/main.cpp index a1c542a1c75f..c5e7103e9e99 100644 --- a/tests/bench/main.cpp +++ b/tests/bench/main.cpp @@ -105,7 +105,7 @@ void usage( std::string const & appName ) // AppleEvent handler as well as by the main routine argv processing // This behaviour will cause QGIS to autoload a project -static QString myProjectFileName = ""; +static QString myProjectFileName = QLatin1String( "" ); // This is the 'leftover' arguments collection static QStringList myFileList; @@ -131,22 +131,22 @@ int main( int argc, char *argv[] ) // int myIterations = 1; - QString mySnapshotFileName = ""; - QString myLogFileName = ""; - QString myPrefixPath = ""; + QString mySnapshotFileName = QLatin1String( "" ); + QString myLogFileName = QLatin1String( "" ); + QString myPrefixPath = QLatin1String( "" ); int mySnapshotWidth = 800; int mySnapshotHeight = 600; - QString myQuality = ""; + QString myQuality = QLatin1String( "" ); bool myParallel = false; - QString myPrintTime = "total"; + QString myPrintTime = QStringLiteral( "total" ); // This behaviour will set initial extent of map canvas, but only if // there are no command line arguments. This gives a usable map // extent when qgis starts with no layers loaded. When layers are // loaded, we let the layers define the initial extent. - QString myInitialExtent = ""; + QString myInitialExtent = QLatin1String( "" ); if ( argc == 1 ) - myInitialExtent = "-1,-1,1,1"; + myInitialExtent = QStringLiteral( "-1,-1,1,1" ); // The user can specify a path which will override the default path of custom // user settings (~/.qgis) and it will be used for QSettings INI file @@ -392,9 +392,9 @@ int main( int argc, char *argv[] ) QgsApplication::setPrefixPath( myPrefixPath, true ); // Set up the QSettings environment must be done after qapp is created - QgsApplication::setOrganizationName( "QGIS" ); - QgsApplication::setOrganizationDomain( "qgis.org" ); - QgsApplication::setApplicationName( "QGIS3" ); + QgsApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QgsApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QgsApplication::setApplicationName( QStringLiteral( "QGIS3" ) ); QgsProviderRegistry::instance( QgsApplication::pluginPath() ); @@ -475,7 +475,7 @@ int main( int argc, char *argv[] ) for ( int i = 0; i < argc; i++ ) { QString arg = QDir::toNativeSeparators( QFileInfo( QFile::decodeName( argv[i] ) ).absoluteFilePath() ); - if ( arg.contains( ".qgs" ) ) + if ( arg.contains( QLatin1String( ".qgs" ) ) ) { myProjectFileName = arg; break; @@ -501,10 +501,10 @@ int main( int argc, char *argv[] ) QStringList list = myQuality.split( ',' ); Q_FOREACH ( const QString& q, list ) { - if ( q == "Antialiasing" ) hints |= QPainter::Antialiasing; - else if ( q == "TextAntialiasing" ) hints |= QPainter::TextAntialiasing; - else if ( q == "SmoothPixmapTransform" ) hints |= QPainter::SmoothPixmapTransform; - else if ( q == "NonCosmeticDefaultPen" ) hints |= QPainter::NonCosmeticDefaultPen; + if ( q == QLatin1String( "Antialiasing" ) ) hints |= QPainter::Antialiasing; + else if ( q == QLatin1String( "TextAntialiasing" ) ) hints |= QPainter::TextAntialiasing; + else if ( q == QLatin1String( "SmoothPixmapTransform" ) ) hints |= QPainter::SmoothPixmapTransform; + else if ( q == QLatin1String( "NonCosmeticDefaultPen" ) ) hints |= QPainter::NonCosmeticDefaultPen; else { fprintf( stderr, "Unknown quality option\n" ); @@ -526,7 +526,7 @@ int main( int argc, char *argv[] ) QgsDebugMsg( QString( "Trying to load file : %1" ).arg(( *myIterator ) ) ); QString myLayerName = *myIterator; // don't load anything with a .qgs extension - these are project files - if ( !myLayerName.contains( ".qgs" ) ) + if ( !myLayerName.contains( QLatin1String( ".qgs" ) ) ) { fprintf( stderr, "Data files not yet supported\n" ); return 1; @@ -582,12 +582,12 @@ int main( int argc, char *argv[] ) qbench->render(); - if ( mySnapshotFileName != "" ) + if ( mySnapshotFileName != QLatin1String( "" ) ) { qbench->saveSnapsot( mySnapshotFileName ); } - if ( myLogFileName != "" ) + if ( myLogFileName != QLatin1String( "" ) ) { qbench->saveLog( myLogFileName ); } diff --git a/tests/bench/qgsbench.cpp b/tests/bench/qgsbench.cpp index 02ab98eab824..122bf6c12ef1 100644 --- a/tests/bench/qgsbench.cpp +++ b/tests/bench/qgsbench.cpp @@ -148,13 +148,13 @@ bool QgsBench::openProject( const QString & theFileName ) { return false; } - mLogMap.insert( "project", theFileName ); + mLogMap.insert( QStringLiteral( "project" ), theFileName ); return true; } void QgsBench::readProject( const QDomDocument &doc ) { - QDomNodeList nodes = doc.elementsByTagName( "mapcanvas" ); + QDomNodeList nodes = doc.elementsByTagName( QStringLiteral( "mapcanvas" ) ); if ( nodes.count() ) { QDomNode node = nodes.item( 0 ); @@ -222,8 +222,8 @@ void QgsBench::render() } - mLogMap.insert( "iterations", mTimes.size() ); - mLogMap.insert( "revision", QGSVERSION ); + mLogMap.insert( QStringLiteral( "iterations" ), mTimes.size() ); + mLogMap.insert( QStringLiteral( "revision" ), QGSVERSION ); // Calc stats: user, sys, total double min[4], max[4]; @@ -260,15 +260,15 @@ void QgsBench::render() QMap map; - map.insert( "min", min[t] ); - map.insert( "max", max[t] ); - map.insert( "avg", avg[t] ); - map.insert( "stdev", stdev[t] ); - map.insert( "maxdev", maxdev[t] ); + map.insert( QStringLiteral( "min" ), min[t] ); + map.insert( QStringLiteral( "max" ), max[t] ); + map.insert( QStringLiteral( "avg" ), avg[t] ); + map.insert( QStringLiteral( "stdev" ), stdev[t] ); + map.insert( QStringLiteral( "maxdev" ), maxdev[t] ); timesMap.insert( pre[t], map ); } - mLogMap.insert( "times", timesMap ); + mLogMap.insert( QStringLiteral( "times" ), timesMap ); } void QgsBench::saveSnapsot( const QString & fileName ) @@ -279,7 +279,7 @@ void QgsBench::saveSnapsot( const QString & fileName ) void QgsBench::printLog( const QString& printTime ) { - std::cout << "iterations: " << mLogMap["iterations"].toString().toAscii().constData() << std::endl; + std::cout << "iterations: " << mLogMap[QStringLiteral( "iterations" )].toString().toAscii().constData() << std::endl; bool validPrintTime = false; for ( int x = 0; x < 4; ++x ) @@ -292,7 +292,7 @@ void QgsBench::printLog( const QString& printTime ) return; } - QMap timesMap = mLogMap["times"].toMap(); + QMap timesMap = mLogMap[QStringLiteral( "times" )].toMap(); QMap totalMap = timesMap[printTime].toMap(); QMap::iterator i = totalMap.begin(); while ( i != totalMap.end() ) @@ -306,21 +306,21 @@ void QgsBench::printLog( const QString& printTime ) QString QgsBench::serialize( const QMap& theMap, int level ) { QStringList list; - QString space = QString( " " ).repeated( level * 2 ); - QString space2 = QString( " " ).repeated( level * 2 + 2 ); + QString space = QStringLiteral( " " ).repeated( level * 2 ); + QString space2 = QStringLiteral( " " ).repeated( level * 2 + 2 ); QMap::const_iterator i = theMap.constBegin(); while ( i != theMap.constEnd() ) { switch ( static_cast< QMetaType::Type >( i.value().type() ) ) { case QMetaType::Int: - list.append( space2 + '\"' + i.key() + "\": " + QString( "%1" ).arg( i.value().toInt() ) ); + list.append( space2 + '\"' + i.key() + "\": " + QStringLiteral( "%1" ).arg( i.value().toInt() ) ); break; case QMetaType::Double: - list.append( space2 + '\"' + i.key() + "\": " + QString( "%1" ).arg( i.value().toDouble(), 0, 'f', 3 ) ); + list.append( space2 + '\"' + i.key() + "\": " + QStringLiteral( "%1" ).arg( i.value().toDouble(), 0, 'f', 3 ) ); break; case QMetaType::QString: - list.append( space2 + '\"' + i.key() + "\": \"" + i.value().toString().replace( '\\', "\\\\" ).replace( '\"', "\\\"" ) + '\"' ); + list.append( space2 + '\"' + i.key() + "\": \"" + i.value().toString().replace( '\\', QLatin1String( "\\\\" ) ).replace( '\"', QLatin1String( "\\\"" ) ) + '\"' ); break; //case QMetaType::QMap: QMap is not in QMetaType default: @@ -329,7 +329,7 @@ QString QgsBench::serialize( const QMap& theMap, int level ) } ++i; } - return space + "{\n" + list.join( ",\n" ) + '\n' + space + '}'; + return space + "{\n" + list.join( QStringLiteral( ",\n" ) ) + '\n' + space + '}'; } void QgsBench::saveLog( const QString & fileName ) diff --git a/tests/src/analysis/testopenstreetmap.cpp b/tests/src/analysis/testopenstreetmap.cpp index fe29dcf8f30e..9a900d1a8320 100644 --- a/tests/src/analysis/testopenstreetmap.cpp +++ b/tests/src/analysis/testopenstreetmap.cpp @@ -170,14 +170,14 @@ void TestOpenStreetMap::importAndQueries() QCOMPARE( ways.next().isValid(), false ); ways.close(); - bool exportRes1 = db.exportSpatiaLite( QgsOSMDatabase::Point, "sl_points", QStringList( "addr:postcode" ) ); + bool exportRes1 = db.exportSpatiaLite( QgsOSMDatabase::Point, QStringLiteral( "sl_points" ), QStringList( QStringLiteral( "addr:postcode" ) ) ); //bool exportRes = db.exportSpatiaLite( QStringList("amenity") << "name" << "highway" ); if ( !db.errorString().isEmpty() ) qDebug( "EXPORT-1 ERR: %s", db.errorString().toAscii().data() ); QCOMPARE( exportRes1, true ); - bool exportRes2 = db.exportSpatiaLite( QgsOSMDatabase::Polyline, "sl_lines", QStringList( "building" ) ); + bool exportRes2 = db.exportSpatiaLite( QgsOSMDatabase::Polyline, QStringLiteral( "sl_lines" ), QStringList( QStringLiteral( "building" ) ) ); //bool exportRes2 = db.exportSpatiaLite( QStringList("amenity") << "name" << "highway" ); if ( !db.errorString().isEmpty() ) qDebug( "EXPORT-2 ERR: %s", db.errorString().toAscii().data() ); diff --git a/tests/src/analysis/testqgsalignraster.cpp b/tests/src/analysis/testqgsalignraster.cpp index dbeb79b867f3..8090bdb46238 100644 --- a/tests/src/analysis/testqgsalignraster.cpp +++ b/tests/src/analysis/testqgsalignraster.cpp @@ -28,7 +28,7 @@ static QString _tempFile( const QString& name ) { - return QString( "%1/aligntest-%2.tif" ).arg( QDir::tempPath(), name ); + return QStringLiteral( "%1/aligntest-%2.tif" ).arg( QDir::tempPath(), name ); } @@ -43,7 +43,7 @@ class TestAlignRaster : public QObject { GDALAllRegister(); - SRC_FILE = QString( TEST_DATA_DIR ) + "/float1-16.tif"; + SRC_FILE = QStringLiteral( TEST_DATA_DIR ) + "/float1-16.tif"; QgsApplication::init(); // needed for CRS database } @@ -59,7 +59,7 @@ class TestAlignRaster : public QObject void testClip() { - QString tmpFile( _tempFile( "clip" ) ); + QString tmpFile( _tempFile( QStringLiteral( "clip" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -80,7 +80,7 @@ class TestAlignRaster : public QObject void testClipOutside() { - QString tmpFile( _tempFile( "clip-outside" ) ); + QString tmpFile( _tempFile( QStringLiteral( "clip-outside" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -94,7 +94,7 @@ class TestAlignRaster : public QObject void testChangeGridOffsetNN() { - QString tmpFile( _tempFile( "change-grid-offset-nn" ) ); + QString tmpFile( _tempFile( QStringLiteral( "change-grid-offset-nn" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -118,7 +118,7 @@ class TestAlignRaster : public QObject void testChangeGridOffsetBilinear() { - QString tmpFile( _tempFile( "change-grid-offset-bilinear" ) ); + QString tmpFile( _tempFile( QStringLiteral( "change-grid-offset-bilinear" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -141,7 +141,7 @@ class TestAlignRaster : public QObject void testSmallerCellSize() { - QString tmpFile( _tempFile( "smaller-cell-size" ) ); + QString tmpFile( _tempFile( QStringLiteral( "smaller-cell-size" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -164,7 +164,7 @@ class TestAlignRaster : public QObject void testBiggerCellSize() { - QString tmpFile( _tempFile( "bigger-cell-size" ) ); + QString tmpFile( _tempFile( QStringLiteral( "bigger-cell-size" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -185,7 +185,7 @@ class TestAlignRaster : public QObject void testRescaleBiggerCellSize() { - QString tmpFile( _tempFile( "rescale-bigger-cell-size" ) ); + QString tmpFile( _tempFile( QStringLiteral( "rescale-bigger-cell-size" ) ) ); QgsAlignRaster align; QgsAlignRaster::List rasters; @@ -206,12 +206,12 @@ class TestAlignRaster : public QObject void testReprojectToOtherCRS() { - QString tmpFile( _tempFile( "reproject-utm-47n" ) ); + QString tmpFile( _tempFile( QStringLiteral( "reproject-utm-47n" ) ) ); // reproject from WGS84 to UTM zone 47N // (the true UTM zone for this raster is 48N, but here it is // more obvious the different shape of the resulting raster) - QgsCoordinateReferenceSystem destCRS( "EPSG:32647" ); + QgsCoordinateReferenceSystem destCRS( QStringLiteral( "EPSG:32647" ) ); QVERIFY( destCRS.isValid() ); QgsAlignRaster align; @@ -237,10 +237,10 @@ class TestAlignRaster : public QObject void testInvalidReprojection() { - QString tmpFile( _tempFile( "reproject-invalid" ) ); + QString tmpFile( _tempFile( QStringLiteral( "reproject-invalid" ) ) ); // reprojection to British National Grid with raster in Jakarta area clearly cannot work - QgsCoordinateReferenceSystem destCRS( "EPSG:27700" ); + QgsCoordinateReferenceSystem destCRS( QStringLiteral( "EPSG:27700" ) ); QVERIFY( destCRS.isValid() ); QgsAlignRaster align; diff --git a/tests/src/analysis/testqgsrastercalculator.cpp b/tests/src/analysis/testqgsrastercalculator.cpp index f61e02033281..5400448f2e2f 100644 --- a/tests/src/analysis/testqgsrastercalculator.cpp +++ b/tests/src/analysis/testqgsrastercalculator.cpp @@ -73,7 +73,7 @@ void TestQgsRasterCalculator::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); - QString testDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + QString testDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt QString landsatFileName = testDataDir + "landsat.tif"; QFileInfo landsatRasterFileInfo( landsatFileName ); @@ -353,7 +353,7 @@ void TestQgsRasterCalculator::dualOpMatrixMatrix() void TestQgsRasterCalculator::rasterRefOp() { // test single op run on raster ref - QgsRasterCalcNode node( QgsRasterCalcNode::opSIGN, new QgsRasterCalcNode( "raster" ), 0 ); + QgsRasterCalcNode node( QgsRasterCalcNode::opSIGN, new QgsRasterCalcNode( QStringLiteral( "raster" ) ), 0 ); QgsRasterMatrix result; result.setNodataValue( -9999 ); @@ -370,7 +370,7 @@ void TestQgsRasterCalculator::rasterRefOp() m.setValue( 1, 1, 4.0 ); m.setValue( 2, 0, 5.0 ); m.setValue( 2, 1, -1.0 ); - rasterData.insert( "raster", &m ); + rasterData.insert( QStringLiteral( "raster" ), &m ); QVERIFY( node.calculate( rasterData, result ) ); QCOMPARE( result.data()[0], -1.0 ); @@ -393,7 +393,7 @@ void TestQgsRasterCalculator::dualOpRasterRaster() m1.setValue( 2, 0, 5.0 ); m1.setValue( 2, 1, -1.0 ); //nodata QMap rasterData; - rasterData.insert( "raster1", &m1 ); + rasterData.insert( QStringLiteral( "raster1" ), &m1 ); QgsRasterBlock m2( Qgis::Float32, 2, 3, -2.0 ); //different no data value m2.setValue( 0, 0, -1.0 ); @@ -402,9 +402,9 @@ void TestQgsRasterCalculator::dualOpRasterRaster() m2.setValue( 1, 1, -2.0 ); //nodata m2.setValue( 2, 0, 15.0 ); m2.setValue( 2, 1, -1.0 ); - rasterData.insert( "raster2", &m2 ); + rasterData.insert( QStringLiteral( "raster2" ), &m2 ); - QgsRasterCalcNode node( QgsRasterCalcNode::opPLUS, new QgsRasterCalcNode( "raster1" ), new QgsRasterCalcNode( "raster2" ) ); + QgsRasterCalcNode node( QgsRasterCalcNode::opPLUS, new QgsRasterCalcNode( QStringLiteral( "raster1" ) ), new QgsRasterCalcNode( QStringLiteral( "raster2" ) ) ); QgsRasterMatrix result; result.setNodataValue( -9999 ); @@ -423,12 +423,12 @@ void TestQgsRasterCalculator::calcWithLayers() QgsRasterCalculatorEntry entry1; entry1.bandNumber = 1; entry1.raster = mpLandsatRasterLayer; - entry1.ref = "landsat@1"; + entry1.ref = QStringLiteral( "landsat@1" ); QgsRasterCalculatorEntry entry2; entry2.bandNumber = 2; entry2.raster = mpLandsatRasterLayer; - entry2.ref = "landsat@2"; + entry2.ref = QStringLiteral( "landsat@2" ); QVector entries; entries << entry1 << entry2; @@ -442,14 +442,14 @@ void TestQgsRasterCalculator::calcWithLayers() QString tmpName = tmpFile.fileName(); tmpFile.close(); - QgsRasterCalculator rc( QString( "\"landsat@1\" + 2" ), + QgsRasterCalculator rc( QStringLiteral( "\"landsat@1\" + 2" ), tmpName, - "GTiff", + QStringLiteral( "GTiff" ), extent, crs, 2, 3, entries ); QCOMPARE( rc.processCalculation(), 0 ); //open output file and check results - QgsRasterLayer* result = new QgsRasterLayer( tmpName, "result" ); + QgsRasterLayer* result = new QgsRasterLayer( tmpName, QStringLiteral( "result" ) ); QCOMPARE( result->width(), 2 ); QCOMPARE( result->height(), 3 ); QgsRasterBlock* block = result->dataProvider()->block( 1, extent, 2, 3 ); @@ -463,14 +463,14 @@ void TestQgsRasterCalculator::calcWithLayers() delete block; //now try with 2 raster bands - QgsRasterCalculator rc2( QString( "\"landsat@1\" + \"landsat@2\"" ), + QgsRasterCalculator rc2( QStringLiteral( "\"landsat@1\" + \"landsat@2\"" ), tmpName, - "GTiff", + QStringLiteral( "GTiff" ), extent, crs, 2, 3, entries ); QCOMPARE( rc2.processCalculation(), 0 ); //open output file and check results - result = new QgsRasterLayer( tmpName, "result" ); + result = new QgsRasterLayer( tmpName, QStringLiteral( "result" ) ); QCOMPARE( result->width(), 2 ); QCOMPARE( result->height(), 3 ); block = result->dataProvider()->block( 1, extent, 2, 3 ); @@ -489,12 +489,12 @@ void TestQgsRasterCalculator::calcWithReprojectedLayers() QgsRasterCalculatorEntry entry1; entry1.bandNumber = 1; entry1.raster = mpLandsatRasterLayer; - entry1.ref = "landsat@1"; + entry1.ref = QStringLiteral( "landsat@1" ); QgsRasterCalculatorEntry entry2; entry2.bandNumber = 2; entry2.raster = mpLandsatRasterLayer4326; - entry2.ref = "landsat_4326@2"; + entry2.ref = QStringLiteral( "landsat_4326@2" ); QVector entries; entries << entry1 << entry2; @@ -508,14 +508,14 @@ void TestQgsRasterCalculator::calcWithReprojectedLayers() QString tmpName = tmpFile.fileName(); tmpFile.close(); - QgsRasterCalculator rc( QString( "\"landsat@1\" + \"landsat_4326@2\"" ), + QgsRasterCalculator rc( QStringLiteral( "\"landsat@1\" + \"landsat_4326@2\"" ), tmpName, - "GTiff", + QStringLiteral( "GTiff" ), extent, crs, 2, 3, entries ); QCOMPARE( rc.processCalculation(), 0 ); //open output file and check results - QgsRasterLayer* result = new QgsRasterLayer( tmpName, "result" ); + QgsRasterLayer* result = new QgsRasterLayer( tmpName, QStringLiteral( "result" ) ); QCOMPARE( result->width(), 2 ); QCOMPARE( result->height(), 3 ); QgsRasterBlock* block = result->dataProvider()->block( 1, extent, 2, 3 ); diff --git a/tests/src/analysis/testqgsvectoranalyzer.cpp b/tests/src/analysis/testqgsvectoranalyzer.cpp index d98c50ff4c58..cfa309cb288b 100644 --- a/tests/src/analysis/testqgsvectoranalyzer.cpp +++ b/tests/src/analysis/testqgsvectoranalyzer.cpp @@ -66,24 +66,24 @@ void TestQgsVectorAnalyzer::initTestCase() //create some objects that will be used in all tests... //create a map layer that will be used in all tests... QString myBaseFileName( TEST_DATA_DIR ); //defined in CmakeLists.txt - QString myEndName = "lines.shp"; + QString myEndName = QStringLiteral( "lines.shp" ); QString myFileName = myBaseFileName + '/' + myEndName; qDebug() << myFileName; QFileInfo myLineInfo( myFileName ); mpLineLayer = new QgsVectorLayer( myLineInfo.filePath(), - myLineInfo.completeBaseName(), "ogr" ); + myLineInfo.completeBaseName(), QStringLiteral( "ogr" ) ); - myEndName = "polys.shp"; + myEndName = QStringLiteral( "polys.shp" ); myFileName = myBaseFileName + '/' + myEndName; QFileInfo myPolyInfo( myFileName ); mpPolyLayer = new QgsVectorLayer( myPolyInfo.filePath(), - myPolyInfo.completeBaseName(), "ogr" ); + myPolyInfo.completeBaseName(), QStringLiteral( "ogr" ) ); - myEndName = "points.shp"; + myEndName = QStringLiteral( "points.shp" ); myFileName = myBaseFileName + '/' + myEndName; QFileInfo myPointInfo( myFileName ); mpPointLayer = new QgsVectorLayer( myPointInfo.filePath(), - myPointInfo.completeBaseName(), "ogr" ); + myPointInfo.completeBaseName(), QStringLiteral( "ogr" ) ); } void TestQgsVectorAnalyzer::cleanupTestCase() { diff --git a/tests/src/analysis/testqgszonalstatistics.cpp b/tests/src/analysis/testqgszonalstatistics.cpp index 3a342e007db7..3d3b3b0dd906 100644 --- a/tests/src/analysis/testqgszonalstatistics.cpp +++ b/tests/src/analysis/testqgszonalstatistics.cpp @@ -70,7 +70,7 @@ void TestQgsZonalStatistics::initTestCase() QVERIFY( QFile::copy( myTestDataPath + files.at( i ), myTempPath + files.at( i ) ) ); } - mVectorLayer = new QgsVectorLayer( myTempPath + "polys.shp", "poly", "ogr" ); + mVectorLayer = new QgsVectorLayer( myTempPath + "polys.shp", QStringLiteral( "poly" ), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mVectorLayer ); @@ -84,7 +84,7 @@ void TestQgsZonalStatistics::cleanupTestCase() void TestQgsZonalStatistics::testStatistics() { - QgsZonalStatistics zs( mVectorLayer, mRasterPath, "", 1 ); + QgsZonalStatistics zs( mVectorLayer, mRasterPath, QLatin1String( "" ), 1 ); zs.calculateStatistics( nullptr ); QgsFeature f; @@ -111,7 +111,7 @@ void TestQgsZonalStatistics::testStatistics() QCOMPARE( f.attribute( "mean" ).toDouble(), 0.833333333333333 ); // same with long prefix to ensure that field name truncation handled correctly - QgsZonalStatistics zsl( mVectorLayer, mRasterPath, "myqgis2_", 1 ); + QgsZonalStatistics zsl( mVectorLayer, mRasterPath, QStringLiteral( "myqgis2_" ), 1 ); zsl.calculateStatistics( nullptr ); request.setFilterFid( 0 ); diff --git a/tests/src/app/testqgisappclipboard.cpp b/tests/src/app/testqgisappclipboard.cpp index b0d78175336c..29ff947d152c 100644 --- a/tests/src/app/testqgisappclipboard.cpp +++ b/tests/src/app/testqgisappclipboard.cpp @@ -68,15 +68,15 @@ TestQgisAppClipboard::TestQgisAppClipboard() void TestQgisAppClipboard::initTestCase() { // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); qDebug() << "TestQgisAppClipboard::initTestCase()"; // init QGIS's paths - true means that all path will be inited from prefix QgsApplication::init(); QgsApplication::initQgis(); - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt mQgisApp = new QgisApp(); } @@ -91,16 +91,16 @@ void TestQgisAppClipboard::copyPaste() qDebug() << "TestQgisAppClipboard::copyPaste()"; QMap filesCounts; - filesCounts.insert( "points.shp", 17 ); - filesCounts.insert( "lines.shp", 6 ); - filesCounts.insert( "polys.shp", 10 ); + filesCounts.insert( QStringLiteral( "points.shp" ), 17 ); + filesCounts.insert( QStringLiteral( "lines.shp" ), 6 ); + filesCounts.insert( QStringLiteral( "polys.shp" ), 10 ); Q_FOREACH ( const QString& fileName, filesCounts.keys() ) { // add vector layer QString filePath = mTestDataDir + fileName; qDebug() << "add vector layer: " << filePath; - QgsVectorLayer *inputLayer = mQgisApp->addVectorLayer( filePath, fileName, "ogr" ); + QgsVectorLayer *inputLayer = mQgisApp->addVectorLayer( filePath, fileName, QStringLiteral( "ogr" ) ); QVERIFY( inputLayer->isValid() ); // copy all features to clipboard @@ -112,7 +112,7 @@ void TestQgisAppClipboard::copyPaste() QVERIFY( features.size() == filesCounts.value( fileName ) ); - QgsVectorLayer *pastedLayer = mQgisApp->pasteAsNewMemoryVector( "pasted" ); + QgsVectorLayer *pastedLayer = mQgisApp->pasteAsNewMemoryVector( QStringLiteral( "pasted" ) ); QVERIFY( pastedLayer ); QVERIFY( pastedLayer->isValid() ); qDebug() << pastedLayer->featureCount() << " features in pasted layer"; @@ -124,15 +124,15 @@ void TestQgisAppClipboard::copyToText() { //set clipboard to some QgsFeatures QgsFields fields; - fields.append( QgsField( "int_field", QVariant::Int ) ); - fields.append( QgsField( "string_field", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "int_field" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "string_field" ), QVariant::String ) ); QgsFeature feat( fields, 5 ); - feat.setAttribute( "int_field", 9 ); - feat.setAttribute( "string_field", "val" ); + feat.setAttribute( QStringLiteral( "int_field" ), 9 ); + feat.setAttribute( QStringLiteral( "string_field" ), "val" ); feat.setGeometry( QgsGeometry( new QgsPointV2( 5, 6 ) ) ); QgsFeature feat2( fields, 6 ); - feat2.setAttribute( "int_field", 19 ); - feat2.setAttribute( "string_field", "val2" ); + feat2.setAttribute( QStringLiteral( "int_field" ), 19 ); + feat2.setAttribute( QStringLiteral( "string_field" ), "val2" ); feat2.setGeometry( QgsGeometry( new QgsPointV2( 7, 8 ) ) ); QgsFeatureStore feats; feats.addFeature( feat ); @@ -142,17 +142,17 @@ void TestQgisAppClipboard::copyToText() // attributes only QSettings settings; - settings.setValue( "/qgis/copyFeatureFormat", QgsClipboard::AttributesOnly ); + settings.setValue( QStringLiteral( "/qgis/copyFeatureFormat" ), QgsClipboard::AttributesOnly ); QString result = mQgisApp->clipboard()->generateClipboardText(); QCOMPARE( result, QString( "int_field\tstring_field\n9\tval\n19\tval2" ) ); // attributes with WKT - settings.setValue( "/qgis/copyFeatureFormat", QgsClipboard::AttributesWithWKT ); + settings.setValue( QStringLiteral( "/qgis/copyFeatureFormat" ), QgsClipboard::AttributesWithWKT ); result = mQgisApp->clipboard()->generateClipboardText(); QCOMPARE( result, QString( "wkt_geom\tint_field\tstring_field\nPoint (5 6)\t9\tval\nPoint (7 8)\t19\tval2" ) ); // GeoJSON - settings.setValue( "/qgis/copyFeatureFormat", QgsClipboard::GeoJSON ); + settings.setValue( QStringLiteral( "/qgis/copyFeatureFormat" ), QgsClipboard::GeoJSON ); result = mQgisApp->clipboard()->generateClipboardText(); QString expected = "{ \"type\": \"FeatureCollection\",\n \"features\":[\n" "{\n \"type\":\"Feature\",\n" @@ -202,7 +202,7 @@ void TestQgisAppClipboard::copyToText() void TestQgisAppClipboard::pasteWkt() { - mQgisApp->clipboard()->setText( "POINT (125 10)\nPOINT (111 30)" ); + mQgisApp->clipboard()->setText( QStringLiteral( "POINT (125 10)\nPOINT (111 30)" ) ); QgsFeatureList features = mQgisApp->clipboard()->copyOf(); QCOMPARE( features.length(), 2 ); @@ -222,8 +222,8 @@ void TestQgisAppClipboard::pasteWkt() void TestQgisAppClipboard::pasteGeoJson() { QgsFields fields; - fields.append( QgsField( "name", QVariant::String ) ); - mQgisApp->clipboard()->setText( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ); + fields.append( QgsField( QStringLiteral( "name" ), QVariant::String ) ); + mQgisApp->clipboard()->setText( QStringLiteral( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ) ); QgsFeatureList features = mQgisApp->clipboard()->copyOf( fields ); QCOMPARE( features.length(), 1 ); @@ -239,18 +239,18 @@ void TestQgisAppClipboard::pasteGeoJson() void TestQgisAppClipboard::retrieveFields() { //empty string - mQgisApp->clipboard()->setText( "" ); + mQgisApp->clipboard()->setText( QLatin1String( "" ) ); QgsFields fields = mQgisApp->clipboard()->fields(); QCOMPARE( fields.count(), 0 ); // bad string - mQgisApp->clipboard()->setText( "asdasdas" ); + mQgisApp->clipboard()->setText( QStringLiteral( "asdasdas" ) ); fields = mQgisApp->clipboard()->fields(); QCOMPARE( fields.count(), 0 ); // geojson string - mQgisApp->clipboard()->setText( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\",\"height\":5.5}}" ); + mQgisApp->clipboard()->setText( QStringLiteral( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\",\"height\":5.5}}" ) ); fields = mQgisApp->clipboard()->fields(); QCOMPARE( fields.count(), 2 ); QCOMPARE( fields.at( 0 ).name(), QString( "name" ) ); @@ -262,7 +262,7 @@ void TestQgisAppClipboard::retrieveFields() void TestQgisAppClipboard::clipboardLogic() { //start by setting clipboard contents as text - mQgisApp->clipboard()->setText( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ); + mQgisApp->clipboard()->setText( QStringLiteral( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ) ); QgsFields fields = mQgisApp->clipboard()->fields(); QCOMPARE( fields.count(), 1 ); QCOMPARE( fields.at( 0 ).name(), QString( "name" ) ); @@ -273,14 +273,14 @@ void TestQgisAppClipboard::clipboardLogic() //set clipboard to some QgsFeatures fields = QgsFields(); - fields.append( QgsField( "int_field", QVariant::Int ) ); - fields.append( QgsField( "date_field", QVariant::Date ) ); + fields.append( QgsField( QStringLiteral( "int_field" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "date_field" ), QVariant::Date ) ); QgsFeature feat( fields, 5 ); - feat.setAttribute( "int_field", 9 ); - feat.setAttribute( "date_field", QVariant( QDate( 2010, 9, 5 ) ) ); + feat.setAttribute( QStringLiteral( "int_field" ), 9 ); + feat.setAttribute( QStringLiteral( "date_field" ), QVariant( QDate( 2010, 9, 5 ) ) ); QgsFeature feat2( fields, 6 ); - feat2.setAttribute( "int_field", 19 ); - feat2.setAttribute( "date_field", QVariant( QDate( 2011, 9, 5 ) ) ); + feat2.setAttribute( QStringLiteral( "int_field" ), 19 ); + feat2.setAttribute( QStringLiteral( "date_field" ), QVariant( QDate( 2011, 9, 5 ) ) ); QgsFeatureStore feats; feats.addFeature( feat ); feats.addFeature( feat2 ); @@ -307,7 +307,7 @@ void TestQgisAppClipboard::clipboardLogic() QCOMPARE( features.at( 1 ).attribute( "date_field" ).toDate(), QDate( 2011, 9, 5 ) ); //replace with text again, make sure system clipboard is used rather than internal clipboard - mQgisApp->clipboard()->setText( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ); + mQgisApp->clipboard()->setText( QStringLiteral( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ) ); fields = mQgisApp->clipboard()->fields(); QCOMPARE( fields.count(), 1 ); QCOMPARE( fields.at( 0 ).name(), QString( "name" ) ); diff --git a/tests/src/app/testqgisapppython.cpp b/tests/src/app/testqgisapppython.cpp index e360ccd59e89..00ae53bdb47a 100644 --- a/tests/src/app/testqgisapppython.cpp +++ b/tests/src/app/testqgisapppython.cpp @@ -57,15 +57,15 @@ TestQgisAppPython::TestQgisAppPython() void TestQgisAppPython::initTestCase() { // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); qDebug() << "TestQgisAppClipboard::initTestCase()"; // init QGIS's paths - true means that all path will be inited from prefix QgsApplication::init(); QgsApplication::initQgis(); - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt mQgisApp = new QgisApp(); mQgisApp->loadPythonSupport(); } diff --git a/tests/src/app/testqgsattributetable.cpp b/tests/src/app/testqgsattributetable.cpp index b4600508fa13..ae2cc96f3928 100644 --- a/tests/src/app/testqgsattributetable.cpp +++ b/tests/src/app/testqgsattributetable.cpp @@ -73,11 +73,11 @@ void TestQgsAttributeTable::testFieldCalculation() //test field calculation //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "LineString?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline line3111; line3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ); QgsGeometry line3111G = QgsGeometry::fromPolyline( line3111 ) ; @@ -88,13 +88,13 @@ void TestQgsAttributeTable::testFieldCalculation() QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); // run length calculation QScopedPointer< QgsAttributeTableDialog > dlg( new QgsAttributeTableDialog( tempLayer.data() ) ); tempLayer->startEditing(); - dlg->runFieldCalculation( tempLayer.data(), "col1", "$length" ); + dlg->runFieldCalculation( tempLayer.data(), QStringLiteral( "col1" ), QStringLiteral( "$length" ) ); tempLayer->commitChanges(); // check result QgsFeatureIterator fit = tempLayer->dataProvider()->getFeatures(); @@ -107,7 +107,7 @@ void TestQgsAttributeTable::testFieldCalculation() QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceFeet ); QScopedPointer< QgsAttributeTableDialog > dlg2( new QgsAttributeTableDialog( tempLayer.data() ) ); tempLayer->startEditing(); - dlg2->runFieldCalculation( tempLayer.data(), "col1", "$length" ); + dlg2->runFieldCalculation( tempLayer.data(), QStringLiteral( "col1" ), QStringLiteral( "$length" ) ); tempLayer->commitChanges(); // check result fit = tempLayer->dataProvider()->getFeatures(); @@ -121,11 +121,11 @@ void TestQgsAttributeTable::testFieldCalculationArea() //test $area field calculation //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline polygonRing3111; polygonRing3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ) << QgsPoint( 2520109, 2397715 ) << QgsPoint( 2520792, 2425494 ) << QgsPoint( 2484588, 2425722 ); @@ -139,13 +139,13 @@ void TestQgsAttributeTable::testFieldCalculationArea() QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); // run area calculation QScopedPointer< QgsAttributeTableDialog > dlg( new QgsAttributeTableDialog( tempLayer.data() ) ); tempLayer->startEditing(); - dlg->runFieldCalculation( tempLayer.data(), "col1", "$area" ); + dlg->runFieldCalculation( tempLayer.data(), QStringLiteral( "col1" ), QStringLiteral( "$area" ) ); tempLayer->commitChanges(); // check result QgsFeatureIterator fit = tempLayer->dataProvider()->getFeatures(); @@ -158,7 +158,7 @@ void TestQgsAttributeTable::testFieldCalculationArea() QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMiles ); QScopedPointer< QgsAttributeTableDialog > dlg2( new QgsAttributeTableDialog( tempLayer.data() ) ); tempLayer->startEditing(); - dlg2->runFieldCalculation( tempLayer.data(), "col1", "$area" ); + dlg2->runFieldCalculation( tempLayer.data(), QStringLiteral( "col1" ), QStringLiteral( "$area" ) ); tempLayer->commitChanges(); // check result fit = tempLayer->dataProvider()->getFeatures(); diff --git a/tests/src/app/testqgsfieldcalculator.cpp b/tests/src/app/testqgsfieldcalculator.cpp index ec656a2b070f..eae641ab2a1f 100644 --- a/tests/src/app/testqgsfieldcalculator.cpp +++ b/tests/src/app/testqgsfieldcalculator.cpp @@ -73,11 +73,11 @@ void TestQgsFieldCalculator::testLengthCalculations() //test length calculation respects ellipsoid and project distance units //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "LineString?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline line3111; line3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ); QgsGeometry line3111G = QgsGeometry::fromPolyline( line3111 ) ; @@ -88,7 +88,7 @@ void TestQgsFieldCalculator::testLengthCalculations() QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); // run length calculation @@ -98,7 +98,7 @@ void TestQgsFieldCalculator::testLengthCalculations() // this next part is fragile, and may need to be modified if the dialog changes: calc->mUpdateExistingGroupBox->setChecked( true ); calc->mExistingFieldComboBox->setCurrentIndex( 1 ); - calc->builder->setExpressionText( "$length" ); + calc->builder->setExpressionText( QStringLiteral( "$length" ) ); calc->accept(); tempLayer->commitChanges(); @@ -116,7 +116,7 @@ void TestQgsFieldCalculator::testLengthCalculations() QScopedPointer< QgsFieldCalculator > calc2( new QgsFieldCalculator( tempLayer.data() ) ); calc2->mUpdateExistingGroupBox->setChecked( true ); calc2->mExistingFieldComboBox->setCurrentIndex( 1 ); - calc2->builder->setExpressionText( "$length" ); + calc2->builder->setExpressionText( QStringLiteral( "$length" ) ); calc2->accept(); tempLayer->commitChanges(); // check result @@ -132,11 +132,11 @@ void TestQgsFieldCalculator::testAreaCalculations() //test area calculation respects ellipsoid and project area units //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline polygonRing3111; polygonRing3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ) << QgsPoint( 2520109, 2397715 ) << QgsPoint( 2520792, 2425494 ) << QgsPoint( 2484588, 2425722 ); @@ -150,7 +150,7 @@ void TestQgsFieldCalculator::testAreaCalculations() QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); QgsCoordinateReferenceSystem srs( 3111, QgsCoordinateReferenceSystem::EpsgCrsId ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); // run area calculation @@ -160,7 +160,7 @@ void TestQgsFieldCalculator::testAreaCalculations() // this next part is fragile, and may need to be modified if the dialog changes: calc->mUpdateExistingGroupBox->setChecked( true ); calc->mExistingFieldComboBox->setCurrentIndex( 1 ); - calc->builder->setExpressionText( "$area" ); + calc->builder->setExpressionText( QStringLiteral( "$area" ) ); calc->accept(); tempLayer->commitChanges(); @@ -178,7 +178,7 @@ void TestQgsFieldCalculator::testAreaCalculations() QScopedPointer< QgsFieldCalculator > calc2( new QgsFieldCalculator( tempLayer.data() ) ); calc2->mUpdateExistingGroupBox->setChecked( true ); calc2->mExistingFieldComboBox->setCurrentIndex( 1 ); - calc2->builder->setExpressionText( "$area" ); + calc2->builder->setExpressionText( QStringLiteral( "$area" ) ); calc2->accept(); tempLayer->commitChanges(); // check result diff --git a/tests/src/app/testqgsmaptoolidentifyaction.cpp b/tests/src/app/testqgsmaptoolidentifyaction.cpp index 399e1f51c4e3..bce3db0dff83 100644 --- a/tests/src/app/testqgsmaptoolidentifyaction.cpp +++ b/tests/src/app/testqgsmaptoolidentifyaction.cpp @@ -82,9 +82,9 @@ void TestQgsMapToolIdentifyAction::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); QgsApplication::showSettings(); @@ -111,14 +111,14 @@ void TestQgsMapToolIdentifyAction::cleanup() void TestQgsMapToolIdentifyAction::lengthCalculation() { QSettings s; - s.setValue( "/qgis/measure/keepbaseunit", true ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ); //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "LineString?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline line3111; line3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ); QgsGeometry line3111G = QgsGeometry::fromPolyline( line3111 ) ; @@ -131,7 +131,7 @@ void TestQgsMapToolIdentifyAction::lengthCalculation() canvas->setDestinationCrs( srs ); canvas->setExtent( f1.geometry().boundingBox() ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( 2484588, 2425722 ); @@ -152,7 +152,7 @@ void TestQgsMapToolIdentifyAction::lengthCalculation() QVERIFY( qgsDoubleNear( length, 88360.1, 0.1 ) ); //test unchecked "keep base units" setting - s.setValue( "/qgis/measure/keepbaseunit", false ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), false ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); derivedLength = result.at( 0 ).mDerivedAttributes[tr( "Length" )]; @@ -163,14 +163,14 @@ void TestQgsMapToolIdentifyAction::lengthCalculation() void TestQgsMapToolIdentifyAction::perimeterCalculation() { QSettings s; - s.setValue( "/qgis/measure/keepbaseunit", true ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ); //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline polygonRing3111; polygonRing3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ) << QgsPoint( 2520109, 2397715 ) << QgsPoint( 2520792, 2425494 ) << QgsPoint( 2484588, 2425722 ); QgsPolygon polygon3111; @@ -185,7 +185,7 @@ void TestQgsMapToolIdentifyAction::perimeterCalculation() canvas->setDestinationCrs( srs ); canvas->setExtent( f1.geometry().boundingBox() ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( 2484588, 2425722 ); @@ -206,7 +206,7 @@ void TestQgsMapToolIdentifyAction::perimeterCalculation() QVERIFY( qgsDoubleNear( perimeter, 420896.0, 0.1 ) ); //test unchecked "keep base units" setting - s.setValue( "/qgis/measure/keepbaseunit", false ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), false ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); derivedPerimeter = result.at( 0 ).mDerivedAttributes[tr( "Perimeter" )]; @@ -217,14 +217,14 @@ void TestQgsMapToolIdentifyAction::perimeterCalculation() void TestQgsMapToolIdentifyAction::areaCalculation() { QSettings s; - s.setValue( "/qgis/measure/keepbaseunit", true ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ); //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "Polygon?crs=epsg:3111&field=pk:int&field=col1:double" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); QgsFeature f1( tempLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); - f1.setAttribute( "col1", 0.0 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 0.0 ); QgsPolyline polygonRing3111; polygonRing3111 << QgsPoint( 2484588, 2425722 ) << QgsPoint( 2482767, 2398853 ) << QgsPoint( 2520109, 2397715 ) << QgsPoint( 2520792, 2425494 ) << QgsPoint( 2484588, 2425722 ); @@ -240,7 +240,7 @@ void TestQgsMapToolIdentifyAction::areaCalculation() canvas->setDestinationCrs( srs ); canvas->setExtent( f1.geometry().boundingBox() ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( 2484588, 2425722 ); @@ -261,7 +261,7 @@ void TestQgsMapToolIdentifyAction::areaCalculation() QVERIFY( qgsDoubleNear( area, 389.6117, 0.001 ) ); //test unchecked "keep base units" setting - s.setValue( "/qgis/measure/keepbaseunit", false ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), false ); QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareFeet ); result = action->identify( mapPoint.x(), mapPoint.y(), QList() << tempLayer.data() ); QCOMPARE( result.length(), 1 ); @@ -277,8 +277,8 @@ QString TestQgsMapToolIdentifyAction::testIdentifyRaster( QgsRasterLayer* layer, QgsPoint mapPoint = canvas->getCoordinateTransform()->transform( xGeoref, yGeoref ); QList result = action->identify( mapPoint.x(), mapPoint.y(), QList() << layer ); if ( result.length() != 1 ) - return ""; - return result[0].mAttributes["Band 1"]; + return QLatin1String( "" ); + return result[0].mAttributes[QStringLiteral( "Band 1" )]; } // private @@ -294,7 +294,7 @@ TestQgsMapToolIdentifyAction::testIdentifyVector( QgsVectorLayer* layer, double void TestQgsMapToolIdentifyAction::identifyRasterFloat32() { //create a temporary layer - QString raster = QString( TEST_DATA_DIR ) + "/raster/test.asc"; + QString raster = QStringLiteral( TEST_DATA_DIR ) + "/raster/test.asc"; // By default the QgsRasterLayer forces AAIGRID_DATATYPE=Float64 CPLSetConfigOption( "AAIGRID_DATATYPE", "Float32" ); @@ -329,7 +329,7 @@ void TestQgsMapToolIdentifyAction::identifyRasterFloat32() void TestQgsMapToolIdentifyAction::identifyRasterFloat64() { //create a temporary layer - QString raster = QString( TEST_DATA_DIR ) + "/raster/test.asc"; + QString raster = QStringLiteral( TEST_DATA_DIR ) + "/raster/test.asc"; QScopedPointer< QgsRasterLayer> tempLayer( new QgsRasterLayer( raster ) ); QVERIFY( tempLayer->isValid() ); @@ -353,10 +353,10 @@ void TestQgsMapToolIdentifyAction::identifyRasterFloat64() void TestQgsMapToolIdentifyAction::identifyInvalidPolygons() { //create a temporary layer - QScopedPointer< QgsVectorLayer > memoryLayer( new QgsVectorLayer( "Polygon?field=pk:int", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer > memoryLayer( new QgsVectorLayer( QStringLiteral( "Polygon?field=pk:int" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( memoryLayer->isValid() ); QgsFeature f1( memoryLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); // This geometry is an invalid polygon (3 distinct vertices). // GEOS reported invalidity: Points of LinearRing do not form a closed linestring f1.setGeometry( geomFromHexWKB( diff --git a/tests/src/app/testqgsmaptoolselect.cpp b/tests/src/app/testqgsmaptoolselect.cpp index a2118e6edbcf..35b5ae76a679 100644 --- a/tests/src/app/testqgsmaptoolselect.cpp +++ b/tests/src/app/testqgsmaptoolselect.cpp @@ -78,9 +78,9 @@ void TestQgsMapToolSelect::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); QgsApplication::showSettings(); @@ -130,10 +130,10 @@ TestQgsMapToolSelect::testSelectVector( QgsVectorLayer* layer, double xGeoref, d void TestQgsMapToolSelect::selectInvalidPolygons() { //create a temporary layer - QScopedPointer< QgsVectorLayer > memoryLayer( new QgsVectorLayer( "Polygon?field=pk:int", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer > memoryLayer( new QgsVectorLayer( QStringLiteral( "Polygon?field=pk:int" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( memoryLayer->isValid() ); QgsFeature f1( memoryLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "pk", 1 ); + f1.setAttribute( QStringLiteral( "pk" ), 1 ); // This geometry is an invalid polygon (3 distinct vertices). // GEOS reported invalidity: Points of LinearRing do not form a closed linestring f1.setGeometry( geomFromHexWKB( diff --git a/tests/src/app/testqgsmeasuretool.cpp b/tests/src/app/testqgsmeasuretool.cpp index 84a1de0cb95f..cac422a9f51f 100644 --- a/tests/src/app/testqgsmeasuretool.cpp +++ b/tests/src/app/testqgsmeasuretool.cpp @@ -64,9 +64,9 @@ void TestQgsMeasureTool::initTestCase() QgsApplication::initQgis(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); mQgisApp = new QgisApp(); mCanvas = new QgsMapCanvas(); @@ -87,7 +87,7 @@ void TestQgsMeasureTool::testLengthCalculation() { //test length measurement QSettings s; - s.setValue( "/qgis/measure/keepbaseunit", true ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ); // set project CRS and ellipsoid QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); @@ -95,7 +95,7 @@ void TestQgsMeasureTool::testLengthCalculation() mCanvas->setCrsTransformEnabled( true ); mCanvas->setDestinationCrs( srs ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setDistanceUnits( QgsUnitTypes::DistanceMeters ); // run length calculation @@ -154,7 +154,7 @@ void TestQgsMeasureTool::testAreaCalculation() { //test area measurement QSettings s; - s.setValue( "/qgis/measure/keepbaseunit", true ); + s.setValue( QStringLiteral( "/qgis/measure/keepbaseunit" ), true ); // set project CRS and ellipsoid QgisApp::instance()->mapCanvas()->setCrsTransformEnabled( true ); @@ -162,7 +162,7 @@ void TestQgsMeasureTool::testAreaCalculation() mCanvas->setCrsTransformEnabled( true ); mCanvas->setDestinationCrs( srs ); QgsProject::instance()->setCrs( srs ); - QgsProject::instance()->setEllipsoid( QString( "WGS84" ) ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); QgsProject::instance()->setAreaUnits( QgsUnitTypes::AreaSquareMeters ); // run length calculation diff --git a/tests/src/app/testqgsvectorlayersaveasdialog.cpp b/tests/src/app/testqgsvectorlayersaveasdialog.cpp index 8be54182397d..2715beb50ba2 100644 --- a/tests/src/app/testqgsvectorlayersaveasdialog.cpp +++ b/tests/src/app/testqgsvectorlayersaveasdialog.cpp @@ -71,21 +71,21 @@ void TestQgsVectorLayerSaveAsDialog::cleanupTestCase() void TestQgsVectorLayerSaveAsDialog::testAttributesAsDisplayedValues() { //create a temporary layer - QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( "none?field=code:int&field=regular:string", "vl", "memory" ) ); + QScopedPointer< QgsVectorLayer> tempLayer( new QgsVectorLayer( QStringLiteral( "none?field=code:int&field=regular:string" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ) ); QVERIFY( tempLayer->isValid() ); // Set a widget QgsEditFormConfig editFormConfig = tempLayer->editFormConfig(); - editFormConfig.setWidgetType( 0, "ValueRelation" ); + editFormConfig.setWidgetType( 0, QStringLiteral( "ValueRelation" ) ); tempLayer->setEditFormConfig( editFormConfig ); QgsVectorLayerSaveAsDialog d( tempLayer.data() ); - QPushButton* mDeselectAllAttributes = d.findChild( "mDeselectAllAttributes" ); + QPushButton* mDeselectAllAttributes = d.findChild( QStringLiteral( "mDeselectAllAttributes" ) ); QTest::mouseClick( mDeselectAllAttributes, Qt::LeftButton ); - QTableWidget* mAttributeTable = d.findChild( "mAttributeTable" ); - QCheckBox* mReplaceRawFieldValues = d.findChild( "mReplaceRawFieldValues" ); + QTableWidget* mAttributeTable = d.findChild( QStringLiteral( "mAttributeTable" ) ); + QCheckBox* mReplaceRawFieldValues = d.findChild( QStringLiteral( "mReplaceRawFieldValues" ) ); QCOMPARE( mAttributeTable->rowCount(), 2 ); QCOMPARE( mAttributeTable->columnCount(), 3 ); diff --git a/tests/src/core/testcontrastenhancements.cpp b/tests/src/core/testcontrastenhancements.cpp index 45f3bbb4645c..19223110f33c 100644 --- a/tests/src/core/testcontrastenhancements.cpp +++ b/tests/src/core/testcontrastenhancements.cpp @@ -47,7 +47,7 @@ class TestContrastEnhancements: public QObject //runs before all tests void TestContrastEnhancements::initTestCase() { - mReport += "

                                                                                                                                                                                    Raster Contrast Enhancement Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster Contrast Enhancement Tests

                                                                                                                                                                                    \n" ); } //runs after all tests void TestContrastEnhancements::cleanupTestCase() diff --git a/tests/src/core/testqgis.cpp b/tests/src/core/testqgis.cpp index d31f47a13c1d..00d35a5ea750 100644 --- a/tests/src/core/testqgis.cpp +++ b/tests/src/core/testqgis.cpp @@ -49,7 +49,7 @@ class TestQgis : public QObject //runs before all tests void TestQgis::initTestCase() { - mReport = "

                                                                                                                                                                                    Qgis Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Qgis Tests

                                                                                                                                                                                    \n" ); } //runs after all tests @@ -69,34 +69,34 @@ void TestQgis::permissiveToDouble() { //good inputs bool ok = false; - double result = qgsPermissiveToDouble( QString( "1000" ), ok ); + double result = qgsPermissiveToDouble( QStringLiteral( "1000" ), ok ); QVERIFY( ok ); QCOMPARE( result, 1000.0 ); ok = false; - result = qgsPermissiveToDouble( QString( "1" ) + QLocale::system().groupSeparator() + "000", ok ); + result = qgsPermissiveToDouble( QStringLiteral( "1" ) + QLocale::system().groupSeparator() + "000", ok ); QVERIFY( ok ); QCOMPARE( result, 1000.0 ); ok = false; - result = qgsPermissiveToDouble( QString( "5" ) + QLocale::system().decimalPoint() + "5", ok ); + result = qgsPermissiveToDouble( QStringLiteral( "5" ) + QLocale::system().decimalPoint() + "5", ok ); QVERIFY( ok ); QCOMPARE( result, 5.5 ); ok = false; - result = qgsPermissiveToDouble( QString( "1" ) + QLocale::system().groupSeparator() + "000" + QLocale::system().decimalPoint() + "5", ok ); + result = qgsPermissiveToDouble( QStringLiteral( "1" ) + QLocale::system().groupSeparator() + "000" + QLocale::system().decimalPoint() + "5", ok ); QVERIFY( ok ); QCOMPARE( result, 1000.5 ); //bad input ok = false; - ( void ) qgsPermissiveToDouble( QString( "a" ), ok ); + ( void ) qgsPermissiveToDouble( QStringLiteral( "a" ), ok ); QVERIFY( !ok ); //messy input (invalid thousand separator position), should still be converted ok = false; - result = qgsPermissiveToDouble( QString( "10" ) + QLocale::system().groupSeparator() + "00", ok ); + result = qgsPermissiveToDouble( QStringLiteral( "10" ) + QLocale::system().groupSeparator() + "00", ok ); QVERIFY( ok ); QCOMPARE( result, 1000.0 ); ok = false; - result = qgsPermissiveToDouble( QString( "10" ) + QLocale::system().groupSeparator() + "00" + QLocale::system().decimalPoint() + "5", ok ); + result = qgsPermissiveToDouble( QStringLiteral( "10" ) + QLocale::system().groupSeparator() + "00" + QLocale::system().decimalPoint() + "5", ok ); QVERIFY( ok ); QCOMPARE( result, 1000.5 ); } @@ -105,22 +105,22 @@ void TestQgis::permissiveToInt() { //good inputs bool ok = false; - int result = qgsPermissiveToInt( QString( "1000" ), ok ); + int result = qgsPermissiveToInt( QStringLiteral( "1000" ), ok ); QVERIFY( ok ); QCOMPARE( result, 1000 ); ok = false; - result = qgsPermissiveToInt( QString( "1%01000" ).arg( QLocale::system().groupSeparator() ), ok ); + result = qgsPermissiveToInt( QStringLiteral( "1%01000" ).arg( QLocale::system().groupSeparator() ), ok ); QVERIFY( ok ); QCOMPARE( result, 1000 ); //bad input ok = false; - ( void ) qgsPermissiveToInt( QString( "a" ), ok ); + ( void ) qgsPermissiveToInt( QStringLiteral( "a" ), ok ); QVERIFY( !ok ); //messy input (invalid thousand separator position), should still be converted ok = false; - result = qgsPermissiveToInt( QString( "10%0100" ).arg( QLocale::system().groupSeparator() ), ok ); + result = qgsPermissiveToInt( QStringLiteral( "10%0100" ).arg( QLocale::system().groupSeparator() ), ok ); QVERIFY( ok ); QCOMPARE( result, 1000 ); } @@ -271,12 +271,12 @@ void TestQgis::qVariantCompare_data() QTest::newRow( "qvariantlist 4" ) << QVariant( QVariant( QVariantList() << QVariant( 5 ) << QVariant( 6 ) ) ) << QVariant( QVariantList() << QVariant( 5 ) << QVariant( 3 ) ) << false << true; QTest::newRow( "qvariantlist 5" ) << QVariant( QVariantList() << QVariant( 5 ) ) << QVariant( QVariantList() << QVariant( 5 ) << QVariant( 6 ) ) << true << false; QTest::newRow( "qvariantlist 5" ) << QVariant( QVariantList() << QVariant( 5 ) << QVariant( 6 ) ) << QVariant( QVariantList() << QVariant( 5 ) ) << false << true; - QTest::newRow( "qstringlist" ) << QVariant( QStringList() << "aa" ) << QVariant( QStringList() << "bb" ) << true << false; - QTest::newRow( "qstringlist 2" ) << QVariant( QStringList() << "bb" ) << QVariant( QStringList() << "aa" ) << false << true; - QTest::newRow( "qstringlist 3" ) << QVariant( QStringList() << "aa" << "cc" ) << QVariant( QStringList() << "aa" << "xx" ) << true << false; - QTest::newRow( "qstringlist 4" ) << QVariant( QStringList() << "aa" << "xx" ) << QVariant( QStringList() << "aa" << "cc" ) << false << true; - QTest::newRow( "qstringlist 5" ) << QVariant( QStringList() << "aa" ) << QVariant( QStringList() << "aa" << "xx" ) << true << false; - QTest::newRow( "qstringlist 6" ) << QVariant( QStringList() << "aa" << "xx" ) << QVariant( QStringList() << "aa" ) << false << true; + QTest::newRow( "qstringlist" ) << QVariant( QStringList() << QStringLiteral( "aa" ) ) << QVariant( QStringList() << QStringLiteral( "bb" ) ) << true << false; + QTest::newRow( "qstringlist 2" ) << QVariant( QStringList() << QStringLiteral( "bb" ) ) << QVariant( QStringList() << QStringLiteral( "aa" ) ) << false << true; + QTest::newRow( "qstringlist 3" ) << QVariant( QStringList() << QStringLiteral( "aa" ) << QStringLiteral( "cc" ) ) << QVariant( QStringList() << QStringLiteral( "aa" ) << QStringLiteral( "xx" ) ) << true << false; + QTest::newRow( "qstringlist 4" ) << QVariant( QStringList() << QStringLiteral( "aa" ) << QStringLiteral( "xx" ) ) << QVariant( QStringList() << QStringLiteral( "aa" ) << QStringLiteral( "cc" ) ) << false << true; + QTest::newRow( "qstringlist 5" ) << QVariant( QStringList() << QStringLiteral( "aa" ) ) << QVariant( QStringList() << QStringLiteral( "aa" ) << QStringLiteral( "xx" ) ) << true << false; + QTest::newRow( "qstringlist 6" ) << QVariant( QStringList() << QStringLiteral( "aa" ) << QStringLiteral( "xx" ) ) << QVariant( QStringList() << QStringLiteral( "aa" ) ) << false << true; QTest::newRow( "string" ) << QVariant( "a b c" ) << QVariant( "d e f" ) << true << false; QTest::newRow( "string 2" ) << QVariant( "d e f" ) << QVariant( "a b c" ) << false << true; } diff --git a/tests/src/core/testqgs25drenderer.cpp b/tests/src/core/testqgs25drenderer.cpp index 762b8b52178e..b7cce290be3b 100644 --- a/tests/src/core/testqgs25drenderer.cpp +++ b/tests/src/core/testqgs25drenderer.cpp @@ -80,22 +80,22 @@ void TestQgs25DRenderer::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); mpPolysLayer->setSimplifyMethod( simplifyMethod ); //need a very high height to check for stacking - QgsExpressionContextUtils::setLayerVariable( mpPolysLayer, "qgis_25d_height", 8 ); - QgsExpressionContextUtils::setLayerVariable( mpPolysLayer, "qgis_25d_angle", 45 ); + QgsExpressionContextUtils::setLayerVariable( mpPolysLayer, QStringLiteral( "qgis_25d_height" ), 8 ); + QgsExpressionContextUtils::setLayerVariable( mpPolysLayer, QStringLiteral( "qgis_25d_angle" ), 45 ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPolysLayer ); mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    25D Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    25D Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgs25DRenderer::cleanupTestCase() @@ -114,7 +114,7 @@ void TestQgs25DRenderer::cleanupTestCase() void TestQgs25DRenderer::render() { - mReport += "

                                                                                                                                                                                    Render

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Render

                                                                                                                                                                                    \n" ); //setup 25d renderer Qgs25DRenderer* renderer = new Qgs25DRenderer( ); @@ -135,8 +135,8 @@ void TestQgs25DRenderer::renderComposition() composition->addComposerMap( map ); map->setNewExtent( mpPolysLayer->extent() ); - QgsCompositionChecker checker( "25d_composer", composition ); - checker.setControlPathPrefix( "25d_renderer" ); + QgsCompositionChecker checker( QStringLiteral( "25d_composer" ), composition ); + checker.setControlPathPrefix( QStringLiteral( "25d_renderer" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } @@ -152,7 +152,7 @@ bool TestQgs25DRenderer::imageCheck( const QString& theTestType ) context << QgsExpressionContextUtils::mapSettingsScope( mMapSettings ); mMapSettings.setExpressionContext( context ); QgsMultiRenderChecker myChecker; - myChecker.setControlPathPrefix( "25d_renderer" ); + myChecker.setControlPathPrefix( QStringLiteral( "25d_renderer" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); myChecker.setColorTolerance( 20 ); diff --git a/tests/src/core/testqgsapplication.cpp b/tests/src/core/testqgsapplication.cpp index 35a127569c8b..c78fd0ebcca5 100644 --- a/tests/src/core/testqgsapplication.cpp +++ b/tests/src/core/testqgsapplication.cpp @@ -58,14 +58,14 @@ void TestQgsApplication::cleanupTestCase() void TestQgsApplication::accountName() { QString loginName = QgsApplication::userLoginName(); - qDebug() << QString( "Got login name: '%1'" ).arg( loginName ); + qDebug() << QStringLiteral( "Got login name: '%1'" ).arg( loginName ); QVERIFY( !loginName.isEmpty() ); //test cached return works correctly QCOMPARE( loginName, QgsApplication::userLoginName() ); //can't test contents, as it can be validly empty (eg on Travis). Just testing that we don't crash QString fullName = QgsApplication::userFullName(); - qDebug() << QString( "Got full name: '%1'" ).arg( fullName ); + qDebug() << QStringLiteral( "Got full name: '%1'" ).arg( fullName ); //test cached return works correctly QCOMPARE( fullName, QgsApplication::userFullName() ); } @@ -73,7 +73,7 @@ void TestQgsApplication::accountName() void TestQgsApplication::osName() { // can't test expected result, so just check for non-empty result - qDebug() << QString( "Got OS name: '%1'" ).arg( QgsApplication::osName() ); + qDebug() << QStringLiteral( "Got OS name: '%1'" ).arg( QgsApplication::osName() ); QVERIFY( !QgsApplication::osName().isEmpty() ); } @@ -95,9 +95,9 @@ void TestQgsApplication::checkPaths() void TestQgsApplication::checkGdalSkip() { GDALAllRegister(); - QgsApplication::skipGdalDriver( "GTiff" ); + QgsApplication::skipGdalDriver( QStringLiteral( "GTiff" ) ); QVERIFY( QgsApplication::skippedGdalDrivers().contains( "GTiff" ) ); - QgsApplication::restoreGdalDriver( "GTiff" ); + QgsApplication::restoreGdalDriver( QStringLiteral( "GTiff" ) ); QVERIFY( !QgsApplication::skippedGdalDrivers().contains( "GTiff" ) ); } diff --git a/tests/src/core/testqgsatlascomposition.cpp b/tests/src/core/testqgsatlascomposition.cpp index 3e86f97b85a8..618f5f38b861 100644 --- a/tests/src/core/testqgsatlascomposition.cpp +++ b/tests/src/core/testqgsatlascomposition.cpp @@ -99,13 +99,13 @@ void TestQgsAtlasComposition::initTestCase() mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo vectorFileInfo( QString( TEST_DATA_DIR ) + "/france_parts.shp" ); + QFileInfo vectorFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/france_parts.shp" ); mVectorLayer = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); mVectorLayer2 = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -113,7 +113,7 @@ void TestQgsAtlasComposition::initTestCase() QgsMapLayerRegistry::instance()->addMapLayers( QList() << mVectorLayer ); - mReport = "

                                                                                                                                                                                    Composer Atlas Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Atlas Tests

                                                                                                                                                                                    \n" ); } TestQgsAtlasComposition::~TestQgsAtlasComposition() @@ -153,7 +153,7 @@ void TestQgsAtlasComposition::init() // fix the renderer, fill with green QgsStringMap props; - props.insert( "color", "0,127,0" ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "0,127,0" ) ); QgsFillSymbol* fillSymbol = QgsFillSymbol::createSimple( props ); QgsSingleSymbolRenderer* renderer = new QgsSingleSymbolRenderer( fillSymbol ); mVectorLayer->setRenderer( renderer ); @@ -180,14 +180,14 @@ void TestQgsAtlasComposition::init() // set the fill symbol of the overview map QgsStringMap props2; - props2.insert( "color", "127,0,0,127" ); + props2.insert( QStringLiteral( "color" ), QStringLiteral( "127,0,0,127" ) ); QgsFillSymbol* fillSymbol2 = QgsFillSymbol::createSimple( props2 ); mOverview->overview()->setFrameSymbol( fillSymbol2 ); // header label mLabel1 = new QgsComposerLabel( mComposition ); mComposition->addComposerLabel( mLabel1 ); - mLabel1->setText( "[% \"NAME_1\" %] area" ); + mLabel1->setText( QStringLiteral( "[% \"NAME_1\" %] area" ) ); mLabel1->setFont( QgsFontUtils::getStandardTestFont() ); //need to explictly set width, since expression hasn't been evaluated against //an atlas feature yet and will be shorter than required @@ -196,7 +196,7 @@ void TestQgsAtlasComposition::init() // feature number label mLabel2 = new QgsComposerLabel( mComposition ); mComposition->addComposerLabel( mLabel2 ); - mLabel2->setText( "# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]" ); + mLabel2->setText( QStringLiteral( "# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]" ) ); mLabel2->setFont( QgsFontUtils::getStandardTestFont() ); mLabel2->setSceneRect( QRectF( 150, 200, 60, 15 ) ); @@ -212,12 +212,12 @@ void TestQgsAtlasComposition::cleanup() void TestQgsAtlasComposition::filename() { - mAtlas->setFilenamePattern( "'output_' || @atlas_featurenumber" ); + mAtlas->setFilenamePattern( QStringLiteral( "'output_' || @atlas_featurenumber" ) ); mAtlas->beginRender(); for ( int fi = 0; fi < mAtlas->numFeatures(); ++fi ) { mAtlas->prepareForFeature( fi ); - QString expected = QString( "output_%1" ).arg(( int )( fi + 1 ) ); + QString expected = QStringLiteral( "output_%1" ).arg(( int )( fi + 1 ) ); QCOMPARE( mAtlas->currentFilename(), expected ); } mAtlas->endRender(); @@ -237,8 +237,8 @@ void TestQgsAtlasComposition::autoscale_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_autoscale%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_autoscale%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); @@ -259,8 +259,8 @@ void TestQgsAtlasComposition::fixedscale_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_fixedscale%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_fixedscale%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); @@ -294,8 +294,8 @@ void TestQgsAtlasComposition::predefinedscales_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_predefinedscales%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_predefinedscales%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); @@ -317,8 +317,8 @@ void TestQgsAtlasComposition::two_map_autoscale_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_two_maps%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_two_maps%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); @@ -338,8 +338,8 @@ void TestQgsAtlasComposition::hiding_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_hiding%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_hiding%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); @@ -353,7 +353,7 @@ void TestQgsAtlasComposition::sorting_render() mAtlas->setHideCoverage( false ); mAtlas->setSortFeatures( true ); - mAtlas->setSortKeyAttributeName( "NAME_1" ); // departement name + mAtlas->setSortKeyAttributeName( QStringLiteral( "NAME_1" ) ); // departement name mAtlas->setSortAscending( false ); mAtlas->beginRender(); @@ -363,8 +363,8 @@ void TestQgsAtlasComposition::sorting_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_sorting%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_sorting%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); @@ -380,7 +380,7 @@ void TestQgsAtlasComposition::filtering_render() mAtlas->setSortFeatures( false ); mAtlas->setFilterFeatures( true ); - mAtlas->setFeatureFilter( "substr(NAME_1,1,1)='P'" ); // select only 'Pays de la Loire' + mAtlas->setFeatureFilter( QStringLiteral( "substr(NAME_1,1,1)='P'" ) ); // select only 'Pays de la Loire' mAtlas->beginRender(); @@ -389,8 +389,8 @@ void TestQgsAtlasComposition::filtering_render() mAtlas->prepareForFeature( fit ); mLabel1->adjustSizeToText(); - QgsCompositionChecker checker( QString( "atlas_filtering%1" ).arg((( int )fit ) + 1 ), mComposition ); - checker.setControlPathPrefix( "atlas" ); + QgsCompositionChecker checker( QStringLiteral( "atlas_filtering%1" ).arg((( int )fit ) + 1 ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "atlas" ) ); QVERIFY( checker.testComposition( mReport, 0, 100 ) ); } mAtlas->endRender(); diff --git a/tests/src/core/testqgsauthconfig.cpp b/tests/src/core/testqgsauthconfig.cpp index e8371b01c11b..51ed3f8be270 100644 --- a/tests/src/core/testqgsauthconfig.cpp +++ b/tests/src/core/testqgsauthconfig.cpp @@ -44,7 +44,7 @@ class TestQgsAuthConfig: public QObject static QString smPkiData; }; -QString TestQgsAuthConfig::smPkiData = QString( TEST_DATA_DIR ) + "/auth_system/certs_keys"; +QString TestQgsAuthConfig::smPkiData = QStringLiteral( TEST_DATA_DIR ) + "/auth_system/certs_keys"; void TestQgsAuthConfig::initTestCase() @@ -65,15 +65,15 @@ void TestQgsAuthConfig::testMethodConfig() QgsAuthMethodConfig mconfig; QVERIFY( !mconfig.isValid() ); - mconfig.setName( "Some Name" ); - mconfig.setMethod( "MethodKey" ); + mconfig.setName( QStringLiteral( "Some Name" ) ); + mconfig.setMethod( QStringLiteral( "MethodKey" ) ); QVERIFY( mconfig.isValid() ); - mconfig.setId( "0000000" ); + mconfig.setId( QStringLiteral( "0000000" ) ); QVERIFY( mconfig.isValid( true ) ); mconfig.setVersion( 1 ); - mconfig.setUri( "http://example.com" ); + mconfig.setUri( QStringLiteral( "http://example.com" ) ); QCOMPARE( mconfig.name(), QString( "Some Name" ) ); QCOMPARE( mconfig.method(), QString( "MethodKey" ) ); @@ -81,11 +81,11 @@ void TestQgsAuthConfig::testMethodConfig() QCOMPARE( mconfig.version(), 1 ); QCOMPARE( mconfig.uri(), QString( "http://example.com" ) ); - QString confstr( "key1:::value1|||key2:::value2|||key3:::value3a```value3b```value3c" ); + QString confstr( QStringLiteral( "key1:::value1|||key2:::value2|||key3:::value3a```value3b```value3c" ) ); QgsStringMap confmap; - confmap.insert( "key1", "value1" ); - confmap.insert( "key2", "value2" ); - confmap.insert( "key3", "value3a```value3b```value3c" ); + confmap.insert( QStringLiteral( "key1" ), QStringLiteral( "value1" ) ); + confmap.insert( QStringLiteral( "key2" ), QStringLiteral( "value2" ) ); + confmap.insert( QStringLiteral( "key3" ), QStringLiteral( "value3a```value3b```value3c" ) ); mconfig.setConfigMap( confmap ); QCOMPARE( mconfig.configMap(), confmap ); @@ -94,11 +94,11 @@ void TestQgsAuthConfig::testMethodConfig() mconfig.clearConfigMap(); QVERIFY( mconfig.configMap().isEmpty() ); - mconfig.setConfig( "key1", "value1" ); - mconfig.setConfig( "key2", "value2" ); + mconfig.setConfig( QStringLiteral( "key1" ), QStringLiteral( "value1" ) ); + mconfig.setConfig( QStringLiteral( "key2" ), QStringLiteral( "value2" ) ); QStringList key3list; - key3list << "value3a" << "value3b" << "value3c"; - mconfig.setConfigList( "key3", key3list ); + key3list << QStringLiteral( "value3a" ) << QStringLiteral( "value3b" ) << QStringLiteral( "value3c" ); + mconfig.setConfigList( QStringLiteral( "key3" ), key3list ); QCOMPARE( mconfig.configMap(), confmap ); QCOMPARE( mconfig.configString(), confstr ); @@ -106,7 +106,7 @@ void TestQgsAuthConfig::testMethodConfig() QCOMPARE( mconfig.configList( "key3" ), key3list ); QVERIFY( mconfig.hasConfig( "key2" ) ); - mconfig.removeConfig( "key2" ); + mconfig.removeConfig( QStringLiteral( "key2" ) ); QVERIFY( !mconfig.hasConfig( "key2" ) ); mconfig.loadConfigString( confstr ); @@ -116,7 +116,7 @@ void TestQgsAuthConfig::testMethodConfig() QgsAuthMethodConfig mconfig2( mconfig ); QVERIFY( mconfig2 == mconfig ); - mconfig.setMethod( "MethodKey2" ); + mconfig.setMethod( QStringLiteral( "MethodKey2" ) ); QVERIFY( mconfig2 != mconfig ); } @@ -131,7 +131,7 @@ void TestQgsAuthConfig::testPkiBundle() QCOMPARE( cacerts.size(), 3 ); QgsPkiBundle bundle2( QgsPkiBundle::fromPemPaths( smPkiData + "/fra_cert.pem", smPkiData + "/fra_key_w-pass.pem", - "password", + QStringLiteral( "password" ), cacerts ) ); QVERIFY( !bundle2.isNull() ); QVERIFY( bundle2.isValid() ); @@ -156,7 +156,7 @@ void TestQgsAuthConfig::testPkiBundle() QVERIFY( bundle.isValid() ); QgsPkiBundle bundle4( QgsPkiBundle::fromPkcs12Paths( smPkiData + "/fra_w-chain.p12", - "password" ) ); + QStringLiteral( "password" ) ) ); QVERIFY( !bundle4.isNull() ); QVERIFY( bundle4.isValid() ); QList cachain4( bundle2.caChain() ); @@ -167,11 +167,11 @@ void TestQgsAuthConfig::testPkiBundle() void TestQgsAuthConfig::testPkiConfigBundle() { QgsAuthMethodConfig mconfig; - mconfig.setName( "Some Name" ); - mconfig.setMethod( "MethodKey" ); - mconfig.setId( "0000000" ); + mconfig.setName( QStringLiteral( "Some Name" ) ); + mconfig.setMethod( QStringLiteral( "MethodKey" ) ); + mconfig.setId( QStringLiteral( "0000000" ) ); mconfig.setVersion( 1 ); - mconfig.setUri( "http://example.com" ); + mconfig.setUri( QStringLiteral( "http://example.com" ) ); QVERIFY( mconfig.isValid( true ) ); QSslCertificate clientcert( QSslCertificate::fromPath( smPkiData + "/gerardus_cert.pem" ).at( 0 ) ); @@ -199,8 +199,8 @@ void TestQgsAuthConfig::testPkiConfigBundle() void TestQgsAuthConfig::testConfigSslServer() { - QString hostport( "localhost:443" ); - QString confstr( "2|||470|||2|||10~~19|||0~~2" ); + QString hostport( QStringLiteral( "localhost:443" ) ); + QString confstr( QStringLiteral( "2|||470|||2|||10~~19|||0~~2" ) ); QSslCertificate sslcert( QSslCertificate::fromPath( smPkiData + "/localhost_ssl_cert.pem" ).at( 0 ) ); QgsAuthConfigSslServer sslconfig; diff --git a/tests/src/core/testqgsauthcrypto.cpp b/tests/src/core/testqgsauthcrypto.cpp index fa78918fb234..8a3932153e01 100644 --- a/tests/src/core/testqgsauthcrypto.cpp +++ b/tests/src/core/testqgsauthcrypto.cpp @@ -48,10 +48,10 @@ class TestQgsAuthCrypto: public QObject static const QString smCrypt; }; -const QString TestQgsAuthCrypto::smPass = "password"; -const QString TestQgsAuthCrypto::smSalt = "f48b706946df69d4d2b45bd0603c95af"; -const QString TestQgsAuthCrypto::smHash = "0be18c3f1bf872194d6042f5f4a0c116"; -const QString TestQgsAuthCrypto::smCiv = QString( +const QString TestQgsAuthCrypto::smPass = QStringLiteral( "password" ); +const QString TestQgsAuthCrypto::smSalt = QStringLiteral( "f48b706946df69d4d2b45bd0603c95af" ); +const QString TestQgsAuthCrypto::smHash = QStringLiteral( "0be18c3f1bf872194d6042f5f4a0c116" ); +const QString TestQgsAuthCrypto::smCiv = QStringLiteral( "1c18c442b6723ee465bcbb60568412179fcc3313eb0187b4546ca96d869fbdc1" ); const QString TestQgsAuthCrypto::smText = QString( diff --git a/tests/src/core/testqgsauthmanager.cpp b/tests/src/core/testqgsauthmanager.cpp index 3ffbf414c3f2..9b6339c4c94c 100644 --- a/tests/src/core/testqgsauthmanager.cpp +++ b/tests/src/core/testqgsauthmanager.cpp @@ -63,7 +63,7 @@ class TestQgsAuthManager: public QObject TestQgsAuthManager::TestQgsAuthManager() - : mPkiData( QString( TEST_DATA_DIR ) + "/auth_system/certs_keys" ) + : mPkiData( QStringLiteral( TEST_DATA_DIR ) + "/auth_system/certs_keys" ) , mTempDir( QDir::tempPath() + "/auth" ) , mPass( "pass" ) { @@ -73,7 +73,7 @@ void TestQgsAuthManager::initTestCase() { cleanupTempDir(); - mReport += "

                                                                                                                                                                                    QgsAuthManager Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    QgsAuthManager Tests

                                                                                                                                                                                    \n" ); // make QGIS_AUTH_DB_DIR_PATH temp dir for qgis-auth.db and master password file QDir tmpDir = QDir::temp(); @@ -87,7 +87,7 @@ void TestQgsAuthManager::initTestCase() "Authentication system is DISABLED" ); QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( '\n', "
                                                                                                                                                                                    \n" ); + mySettings = mySettings.replace( '\n', QLatin1String( "
                                                                                                                                                                                    \n" ) ); mReport += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    \n"; // verify QGIS_AUTH_DB_DIR_PATH (temp auth db path) worked @@ -362,12 +362,12 @@ QList TestQgsAuthManager::registerAuthConfigs() // Basic QgsAuthMethodConfig b_config; - b_config.setName( "Basic" ); - b_config.setMethod( "Basic" ); - b_config.setUri( "http://example.com" ); - b_config.setConfig( "username", "username" ); - b_config.setConfig( "password", "password" ); - b_config.setConfig( "realm", "Realm" ); + b_config.setName( QStringLiteral( "Basic" ) ); + b_config.setMethod( QStringLiteral( "Basic" ) ); + b_config.setUri( QStringLiteral( "http://example.com" ) ); + b_config.setConfig( QStringLiteral( "username" ), QStringLiteral( "username" ) ); + b_config.setConfig( QStringLiteral( "password" ), QStringLiteral( "password" ) ); + b_config.setConfig( QStringLiteral( "realm" ), QStringLiteral( "Realm" ) ); if ( !b_config.isValid() ) { return configs; @@ -375,11 +375,11 @@ QList TestQgsAuthManager::registerAuthConfigs() // PKI-Paths QgsAuthMethodConfig p_config; - p_config.setName( "PKI-Paths" ); - p_config.setMethod( "PKI-Paths" ); - p_config.setUri( "http://example.com" ); - p_config.setConfig( "certpath", mPkiData + "/gerardus_cert.pem" ); - p_config.setConfig( "keypath", mPkiData + "gerardus_key_w-pass.pem" ); + p_config.setName( QStringLiteral( "PKI-Paths" ) ); + p_config.setMethod( QStringLiteral( "PKI-Paths" ) ); + p_config.setUri( QStringLiteral( "http://example.com" ) ); + p_config.setConfig( QStringLiteral( "certpath" ), mPkiData + "/gerardus_cert.pem" ); + p_config.setConfig( QStringLiteral( "keypath" ), mPkiData + "gerardus_key_w-pass.pem" ); if ( !p_config.isValid() ) { return configs; @@ -387,11 +387,11 @@ QList TestQgsAuthManager::registerAuthConfigs() // PKI-PKCS#12 QgsAuthMethodConfig k_config; - k_config.setName( "PKI-PKCS#12" ); - k_config.setMethod( "PKI-PKCS#12" ); - k_config.setUri( "http://example.com" ); - k_config.setConfig( "bundlepath", mPkiData + "/gerardus.p12" ); - k_config.setConfig( "bundlepass", "password" ); + k_config.setName( QStringLiteral( "PKI-PKCS#12" ) ); + k_config.setMethod( QStringLiteral( "PKI-PKCS#12" ) ); + k_config.setUri( QStringLiteral( "http://example.com" ) ); + k_config.setConfig( QStringLiteral( "bundlepath" ), mPkiData + "/gerardus.p12" ); + k_config.setConfig( QStringLiteral( "bundlepass" ), QStringLiteral( "password" ) ); if ( !k_config.isValid() ) { return configs; diff --git a/tests/src/core/testqgsblendmodes.cpp b/tests/src/core/testqgsblendmodes.cpp index 687044c330c8..47ccf1bdb289 100644 --- a/tests/src/core/testqgsblendmodes.cpp +++ b/tests/src/core/testqgsblendmodes.cpp @@ -96,7 +96,7 @@ void TestQgsBlendModes::initTestCase() QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mpPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPointsLayer ); @@ -104,7 +104,7 @@ void TestQgsBlendModes::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -117,7 +117,7 @@ void TestQgsBlendModes::initTestCase() QString myLinesFileName = mTestDataDir + "lines.shp"; QFileInfo myLineFileInfo( myLinesFileName ); mpLinesLayer = new QgsVectorLayer( myLineFileInfo.filePath(), - myLineFileInfo.completeBaseName(), "ogr" ); + myLineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); mpLinesLayer->setSimplifyMethod( simplifyMethod ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpLinesLayer ); @@ -165,7 +165,7 @@ void TestQgsBlendModes::vectorBlending() mpLinesLayer->setBlendMode( QPainter::CompositionMode_Difference ); mpPolysLayer->setBlendMode( QPainter::CompositionMode_Difference ); mMapSettings->setExtent( mExtent ); - bool res = imageCheck( "vector_blendmodes" ); + bool res = imageCheck( QStringLiteral( "vector_blendmodes" ) ); //Reset layers mpLinesLayer->setBlendMode( QPainter::CompositionMode_SourceOver ); @@ -185,7 +185,7 @@ void TestQgsBlendModes::featureBlending() //Set feature blending modes for point layer mpLinesLayer->setFeatureBlendMode( QPainter::CompositionMode_Plus ); mMapSettings->setExtent( mExtent ); - bool res = imageCheck( "vector_featureblendmodes" ); + bool res = imageCheck( QStringLiteral( "vector_featureblendmodes" ) ); //Reset layers mpLinesLayer->setFeatureBlendMode( QPainter::CompositionMode_SourceOver ); @@ -204,7 +204,7 @@ void TestQgsBlendModes::vectorLayerTransparency() //Set feature blending modes for point layer mpLinesLayer->setLayerTransparency( 50 ); mMapSettings->setExtent( mExtent ); - bool res = imageCheck( "vector_layertransparency" ); + bool res = imageCheck( QStringLiteral( "vector_layertransparency" ) ); //Reset layers mpLinesLayer->setLayerTransparency( 0 ); diff --git a/tests/src/core/testqgscentroidfillsymbol.cpp b/tests/src/core/testqgscentroidfillsymbol.cpp index d2c4c10ca575..1030548b4abc 100644 --- a/tests/src/core/testqgscentroidfillsymbol.cpp +++ b/tests/src/core/testqgscentroidfillsymbol.cpp @@ -91,7 +91,7 @@ void TestQgsCentroidFillSymbol::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -113,7 +113,7 @@ void TestQgsCentroidFillSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Centroid Fill Symbol Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Centroid Fill Symbol Tests

                                                                                                                                                                                    \n" ); } void TestQgsCentroidFillSymbol::cleanupTestCase() @@ -132,7 +132,7 @@ void TestQgsCentroidFillSymbol::cleanupTestCase() void TestQgsCentroidFillSymbol::centroidFillSymbol() { - mReport += "

                                                                                                                                                                                    Line fill symbol renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Line fill symbol renderer test

                                                                                                                                                                                    \n" ); QVERIFY( imageCheck( "symbol_centroidfill" ) ); } @@ -156,7 +156,7 @@ bool TestQgsCentroidFillSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPolysLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_centroidfill" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_centroidfill" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgscolorscheme.cpp b/tests/src/core/testqgscolorscheme.cpp index 7662d0d6e114..fac090b4af20 100644 --- a/tests/src/core/testqgscolorscheme.cpp +++ b/tests/src/core/testqgscolorscheme.cpp @@ -29,23 +29,23 @@ class DummyColorScheme : public QgsColorScheme virtual ~DummyColorScheme() {} - virtual QString schemeName() const override { return QString( "Dummy scheme" ); } + virtual QString schemeName() const override { return QStringLiteral( "Dummy scheme" ); } virtual QgsNamedColorList fetchColors( const QString &context = QString(), const QColor &baseColor = QColor() ) override { QList< QPair< QColor, QString> > colors; - if ( context == "testscheme" ) + if ( context == QLatin1String( "testscheme" ) ) { - colors << qMakePair( QColor( 255, 255, 0 ), QString( "schemetest" ) ); + colors << qMakePair( QColor( 255, 255, 0 ), QStringLiteral( "schemetest" ) ); } else if ( baseColor.isValid() ) { - colors << qMakePair( baseColor, QString( "base" ) ); + colors << qMakePair( baseColor, QStringLiteral( "base" ) ); } else { - colors << qMakePair( QColor( 255, 0, 0 ), QString( "red" ) ) << qMakePair( QColor( 0, 255, 0 ), QString() ); + colors << qMakePair( QColor( 255, 0, 0 ), QStringLiteral( "red" ) ) << qMakePair( QColor( 0, 255, 0 ), QString() ); } return colors; } @@ -133,7 +133,7 @@ void TestQgsColorScheme::colorsWithBase() void TestQgsColorScheme::colorsWithScheme() { QSharedPointer dummyScheme( new DummyColorScheme() ); - QgsNamedColorList colors = dummyScheme->fetchColors( QString( "testscheme" ) ); + QgsNamedColorList colors = dummyScheme->fetchColors( QStringLiteral( "testscheme" ) ); QCOMPARE( colors.length(), 1 ); QCOMPARE( colors.at( 0 ).first, QColor( 255, 255, 0 ) ); QCOMPARE( colors.at( 0 ).second, QString( "schemetest" ) ); diff --git a/tests/src/core/testqgscolorschemeregistry.cpp b/tests/src/core/testqgscolorschemeregistry.cpp index 5301aa61c262..2e7d1a47eb72 100644 --- a/tests/src/core/testqgscolorschemeregistry.cpp +++ b/tests/src/core/testqgscolorschemeregistry.cpp @@ -30,23 +30,23 @@ class DummyColorScheme : public QgsColorScheme virtual ~DummyColorScheme() {} - virtual QString schemeName() const override { return QString( "Dummy scheme" ); } + virtual QString schemeName() const override { return QStringLiteral( "Dummy scheme" ); } virtual QgsNamedColorList fetchColors( const QString &context = QString(), const QColor &baseColor = QColor() ) override { QList< QPair< QColor, QString> > colors; - if ( context == "testscheme" ) + if ( context == QLatin1String( "testscheme" ) ) { - colors << qMakePair( QColor( 255, 255, 0 ), QString( "schemetest" ) ); + colors << qMakePair( QColor( 255, 255, 0 ), QStringLiteral( "schemetest" ) ); } else if ( baseColor.isValid() ) { - colors << qMakePair( baseColor, QString( "base" ) ); + colors << qMakePair( baseColor, QStringLiteral( "base" ) ); } else { - colors << qMakePair( QColor( 255, 0, 0 ), QString( "red" ) ) << qMakePair( QColor( 0, 255, 0 ), QString() ); + colors << qMakePair( QColor( 255, 0, 0 ), QStringLiteral( "red" ) ) << qMakePair( QColor( 0, 255, 0 ), QString() ); } return colors; } diff --git a/tests/src/core/testqgscomposerdd.cpp b/tests/src/core/testqgscomposerdd.cpp index d5331f88eeda..600846f32772 100644 --- a/tests/src/core/testqgscomposerdd.cpp +++ b/tests/src/core/testqgscomposerdd.cpp @@ -69,10 +69,10 @@ void TestQgsComposerDD::initTestCase() mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo vectorFileInfo( QString( TEST_DATA_DIR ) + "/france_parts.shp" ); + QFileInfo vectorFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/france_parts.shp" ); mVectorLayer = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -94,7 +94,7 @@ void TestQgsComposerDD::initTestCase() // fix the renderer, fill with green QgsStringMap props; - props.insert( "color", "0,127,0" ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "0,127,0" ) ); QgsFillSymbol* fillSymbol = QgsFillSymbol::createSimple( props ); QgsSingleSymbolRenderer* renderer = new QgsSingleSymbolRenderer( fillSymbol ); mVectorLayer->setRenderer( renderer ); @@ -109,7 +109,7 @@ void TestQgsComposerDD::initTestCase() mAtlas->setEnabled( true ); mComposition->setAtlasMode( QgsComposition::ExportAtlas ); - mReport = "

                                                                                                                                                                                    Composer Data Defined Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Data Defined Tests

                                                                                                                                                                                    \n" ); } @@ -140,7 +140,7 @@ void TestQgsComposerDD::cleanup() void TestQgsComposerDD::ddEvaluate() { //set a data defined property - mAtlasMap->setDataDefinedProperty( QgsComposerItem::PositionY, true, true, QString( "20+30" ), QString() ); + mAtlasMap->setDataDefinedProperty( QgsComposerItem::PositionY, true, true, QStringLiteral( "20+30" ), QString() ); //evaluate property mAtlasMap->refreshDataDefinedProperty( QgsComposerItem::PositionY ); QCOMPARE( mAtlasMap->pos().y(), 50.0 ); diff --git a/tests/src/core/testqgscomposereffects.cpp b/tests/src/core/testqgscomposereffects.cpp index fc08db8f2960..11c053140d38 100644 --- a/tests/src/core/testqgscomposereffects.cpp +++ b/tests/src/core/testqgscomposereffects.cpp @@ -72,7 +72,7 @@ void TestQgsComposerEffects::initTestCase() mComposerRect2->setShapeType( QgsComposerShape::Rectangle ); mComposition->addComposerShape( mComposerRect2 ); - mReport = "

                                                                                                                                                                                    Composer Effects Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Effects Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerEffects::cleanupTestCase() @@ -106,8 +106,8 @@ void TestQgsComposerEffects::blend_modes() { mComposerRect2->setBlendMode( QPainter::CompositionMode_Multiply ); - QgsCompositionChecker checker( "composereffects_blend", mComposition ); - checker.setControlPathPrefix( "composer_effects" ); + QgsCompositionChecker checker( QStringLiteral( "composereffects_blend" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_effects" ) ); QVERIFY( checker.testComposition( mReport ) ); // reset blending mComposerRect2->setBlendMode( QPainter::CompositionMode_SourceOver ); @@ -117,8 +117,8 @@ void TestQgsComposerEffects::transparency() { mComposerRect2->setTransparency( 50 ); - QgsCompositionChecker checker( "composereffects_transparency", mComposition ); - checker.setControlPathPrefix( "composer_effects" ); + QgsCompositionChecker checker( QStringLiteral( "composereffects_transparency" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_effects" ) ); QVERIFY( checker.testComposition( mReport ) ); } diff --git a/tests/src/core/testqgscomposergroup.cpp b/tests/src/core/testqgscomposergroup.cpp index 2faad8125de9..e0f1e7c0266f 100644 --- a/tests/src/core/testqgscomposergroup.cpp +++ b/tests/src/core/testqgscomposergroup.cpp @@ -52,7 +52,7 @@ class TestQgsComposerGroup : public QObject private: - void dumpUndoStack( const QUndoStack&, QString prefix = "" ) const; + void dumpUndoStack( const QUndoStack&, QString prefix = QLatin1String( QLatin1String( "" ) ) ) const; QgsComposition *mComposition; QgsMapSettings *mMapSettings; @@ -65,7 +65,7 @@ class TestQgsComposerGroup : public QObject // private void TestQgsComposerGroup::dumpUndoStack( const QUndoStack& us, QString prefix ) const { - if ( ! prefix.isEmpty() ) prefix += ": "; + if ( ! prefix.isEmpty() ) prefix += QLatin1String( ": " ); for ( int i = 0; i < us.count(); ++i ) { QgsDebugMsg( QString( "%4US %1: %2%3" ) @@ -91,7 +91,7 @@ void TestQgsComposerGroup::initTestCase() mGroup = 0; - mReport = "

                                                                                                                                                                                    Composer Grouped Item Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Grouped Item Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerGroup::cleanupTestCase() @@ -250,7 +250,7 @@ void TestQgsComposerGroup::undoRedo() //move group QgsDebugMsg( QString( "moving group" ) ); - mGroup->beginCommand( "move group" ); + mGroup->beginCommand( QStringLiteral( "move group" ) ); mGroup->move( 10.0, 20.0 ); mGroup->endCommand(); QCOMPARE( spyPolygonAdded.count(), polygonsAdded ); diff --git a/tests/src/core/testqgscomposerhtml.cpp b/tests/src/core/testqgscomposerhtml.cpp index d5ed173c0072..c6873bfba6b9 100644 --- a/tests/src/core/testqgscomposerhtml.cpp +++ b/tests/src/core/testqgscomposerhtml.cpp @@ -73,10 +73,10 @@ void TestQgsComposerHtml::initTestCase() mComposition = new QgsComposition( *mMapSettings ); mComposition->setPaperSize( 297, 210 ); //A4 landscape - mReport = "

                                                                                                                                                                                    Composer HTML Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer HTML Tests

                                                                                                                                                                                    \n" ); - QgsFontUtils::loadStandardTestFonts( QStringList() << "Oblique" ); - mTestFont = QgsFontUtils::getStandardTestFont( "Oblique " ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Oblique" ) ); + mTestFont = QgsFontUtils::getStandardTestFont( QStringLiteral( "Oblique " ) ); } void TestQgsComposerHtml::cleanupTestCase() @@ -112,11 +112,11 @@ void TestQgsComposerHtml::sourceMode() htmlFrame->setFrameEnabled( true ); htmlItem->addFrame( htmlFrame ); htmlItem->setContentMode( QgsComposerHtml::ManualHtml ); - htmlItem->setHtml( QString( "
                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "
                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); - QgsCompositionChecker checker( "composerhtml_manual", mComposition ); - checker.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker( QStringLiteral( "composerhtml_manual" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker.testComposition( mReport, 0, 100 ); mComposition->removeMultiFrame( htmlItem ); delete htmlItem; @@ -130,15 +130,15 @@ void TestQgsComposerHtml::userStylesheets() htmlFrame->setFrameEnabled( true ); htmlItem->addFrame( htmlFrame ); htmlItem->setContentMode( QgsComposerHtml::ManualHtml ); - htmlItem->setHtml( QString( "
                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "
                                                                                                                                                                                    " ) ); //set user stylesheet - htmlItem->setUserStylesheet( QString( "div { background-color: green !important; }" ) ); + htmlItem->setUserStylesheet( QStringLiteral( "div { background-color: green !important; }" ) ); //setting user stylesheet enabled automatically loads html htmlItem->setUserStylesheetEnabled( true ); - QgsCompositionChecker checker( "composerhtml_userstylesheet", mComposition ); - checker.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker( QStringLiteral( "composerhtml_userstylesheet" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker.testComposition( mReport, 0, 100 ); mComposition->removeMultiFrame( htmlItem ); delete htmlItem; @@ -153,12 +153,12 @@ void TestQgsComposerHtml::evalExpressions() htmlItem->addFrame( htmlFrame ); htmlItem->setContentMode( QgsComposerHtml::ManualHtml ); htmlItem->setEvaluateExpressions( true ); - htmlItem->setHtml( QString( "
                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "
                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); - QgsCompositionChecker checker( "composerhtml_expressions_enabled", mComposition ); - checker.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker( QStringLiteral( "composerhtml_expressions_enabled" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker.testComposition( mReport ); mComposition->removeMultiFrame( htmlItem ); delete htmlItem; @@ -173,11 +173,11 @@ void TestQgsComposerHtml::evalExpressionsOff() htmlItem->addFrame( htmlFrame ); htmlItem->setContentMode( QgsComposerHtml::ManualHtml ); htmlItem->setEvaluateExpressions( false ); - htmlItem->setHtml( QString( "
                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "
                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); - QgsCompositionChecker checker( "composerhtml_expressions_disabled", mComposition ); - checker.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker( QStringLiteral( "composerhtml_expressions_disabled" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker.testComposition( mReport ); mComposition->removeMultiFrame( htmlItem ); delete htmlItem; @@ -190,10 +190,10 @@ void TestQgsComposerHtml::table() QgsComposerFrame* htmlFrame = new QgsComposerFrame( mComposition, htmlItem, 0, 0, 100, 200 ); htmlFrame->setFrameEnabled( true ); htmlItem->addFrame( htmlFrame ); - htmlItem->setUrl( QUrl( QString( "file:///%1/test_html.html" ).arg( TEST_DATA_DIR ) ) ); + htmlItem->setUrl( QUrl( QStringLiteral( "file:///%1/test_html.html" ).arg( TEST_DATA_DIR ) ) ); - QgsCompositionChecker checker( "composerhtml_table", mComposition ); - checker.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker( QStringLiteral( "composerhtml_table" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker.testComposition( mReport ); mComposition->removeMultiFrame( htmlItem ); delete htmlItem; @@ -209,15 +209,15 @@ void TestQgsComposerHtml::tableMultiFrame() htmlItem->setUseSmartBreaks( false ); //page1 - htmlItem->setUrl( QUrl( QString( "file:///%1/test_html.html" ).arg( TEST_DATA_DIR ) ) ); + htmlItem->setUrl( QUrl( QStringLiteral( "file:///%1/test_html.html" ).arg( TEST_DATA_DIR ) ) ); htmlItem->frame( 0 )->setFrameEnabled( true ); - QgsCompositionChecker checker1( "composerhtml_multiframe1", mComposition ); - checker1.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker1( QStringLiteral( "composerhtml_multiframe1" ), mComposition ); + checker1.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker1.testComposition( mReport ); //page2 - QgsCompositionChecker checker2( "composerhtml_multiframe2", mComposition ); - checker2.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker2( QStringLiteral( "composerhtml_multiframe2" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_html" ) ); result = checker2.testComposition( mReport, 1 ) && result; mComposition->removeMultiFrame( htmlItem ); @@ -234,15 +234,15 @@ void TestQgsComposerHtml::htmlMultiFrameSmartBreak() htmlItem->setUseSmartBreaks( true ); //page1 - htmlItem->setUrl( QUrl( QString( "file:///%1/test_html.html" ).arg( TEST_DATA_DIR ) ) ); + htmlItem->setUrl( QUrl( QStringLiteral( "file:///%1/test_html.html" ).arg( TEST_DATA_DIR ) ) ); htmlItem->frame( 0 )->setFrameEnabled( true ); - QgsCompositionChecker checker1( "composerhtml_smartbreaks1", mComposition ); - checker1.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker1( QStringLiteral( "composerhtml_smartbreaks1" ), mComposition ); + checker1.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker1.testComposition( mReport, 0, 200 ); //page2 - QgsCompositionChecker checker2( "composerhtml_smartbreaks2", mComposition ); - checker2.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker2( QStringLiteral( "composerhtml_smartbreaks2" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_html" ) ); result = checker2.testComposition( mReport, 1, 200 ) && result; mComposition->removeMultiFrame( htmlItem ); @@ -257,7 +257,7 @@ void TestQgsComposerHtml::javascriptSetFeature() // first need to setup some layers with a relation //parent layer - QgsVectorLayer* parentLayer = new QgsVectorLayer( "Point?field=fldtxt:string&field=fldint:integer&field=foreignkey:integer", "parent", "memory" ); + QgsVectorLayer* parentLayer = new QgsVectorLayer( QStringLiteral( "Point?field=fldtxt:string&field=fldint:integer&field=foreignkey:integer" ), QStringLiteral( "parent" ), QStringLiteral( "memory" ) ); QgsVectorDataProvider* pr = parentLayer->dataProvider(); QgsFeature pf1; pf1.setFields( parentLayer->fields() ); @@ -268,7 +268,7 @@ void TestQgsComposerHtml::javascriptSetFeature() QVERIFY( pr->addFeatures( QgsFeatureList() << pf1 << pf2 ) ); // child layer - QgsVectorLayer* childLayer = new QgsVectorLayer( "Point?field=x:string&field=y:integer&field=z:integer", "referencedlayer", "memory" ); + QgsVectorLayer* childLayer = new QgsVectorLayer( QStringLiteral( "Point?field=x:string&field=y:integer&field=z:integer" ), QStringLiteral( "referencedlayer" ), QStringLiteral( "memory" ) ); pr = childLayer->dataProvider(); QgsFeature f1; f1.setFields( childLayer->fields() ); @@ -288,11 +288,11 @@ void TestQgsComposerHtml::javascriptSetFeature() mComposition->atlasComposition().setEnabled( true ); QgsRelation rel; - rel.setRelationId( "rel1" ); - rel.setRelationName( "relation one" ); + rel.setRelationId( QStringLiteral( "rel1" ) ); + rel.setRelationName( QStringLiteral( "relation one" ) ); rel.setReferencingLayer( childLayer->id() ); rel.setReferencedLayer( parentLayer->id() ); - rel.addFieldPair( "y", "foreignkey" ); + rel.addFieldPair( QStringLiteral( "y" ), QStringLiteral( "foreignkey" ) ); QgsProject::instance()->relationManager()->addRelation( rel ); QgsComposerHtml* htmlItem = new QgsComposerHtml( mComposition, false ); @@ -314,8 +314,8 @@ void TestQgsComposerHtml::javascriptSetFeature() htmlItem->loadHtml(); - QgsCompositionChecker checker( "composerhtml_setfeature", mComposition ); - checker.setControlPathPrefix( "composer_html" ); + QgsCompositionChecker checker( QStringLiteral( "composerhtml_setfeature" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_html" ) ); bool result = checker.testComposition( mReport ); mComposition->removeMultiFrame( htmlItem ); delete htmlItem; diff --git a/tests/src/core/testqgscomposerlabel.cpp b/tests/src/core/testqgscomposerlabel.cpp index 2bea4906a76a..3927caaace55 100644 --- a/tests/src/core/testqgscomposerlabel.cpp +++ b/tests/src/core/testqgscomposerlabel.cpp @@ -73,10 +73,10 @@ void TestQgsComposerLabel::initTestCase() mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo vectorFileInfo( QString( TEST_DATA_DIR ) + '/' + "france_parts.shp" ); + QFileInfo vectorFileInfo( QStringLiteral( TEST_DATA_DIR ) + '/' + "france_parts.shp" ); mVectorLayer = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mVectorLayer ); //create composition with composer map @@ -127,15 +127,15 @@ void TestQgsComposerLabel::evaluation() { // $CURRENT_DATE evaluation QString expected = "__" + QDate::currentDate().toString() + "__"; - mComposerLabel->setText( "__$CURRENT_DATE__" ); + mComposerLabel->setText( QStringLiteral( "__$CURRENT_DATE__" ) ); QString evaluated = mComposerLabel->displayText(); QCOMPARE( evaluated, expected ); } { // $CURRENT_DATE() evaluation QDateTime now = QDateTime::currentDateTime(); - QString expected = "__" + now.toString( "dd" ) + "(ok)__"; - mComposerLabel->setText( "__$CURRENT_DATE(dd)(ok)__" ); + QString expected = "__" + now.toString( QStringLiteral( "dd" ) ) + "(ok)__"; + mComposerLabel->setText( QStringLiteral( "__$CURRENT_DATE(dd)(ok)__" ) ); QString evaluated = mComposerLabel->displayText(); QCOMPARE( evaluated, expected ); } @@ -144,15 +144,15 @@ void TestQgsComposerLabel::evaluation() QDate now = QDate::currentDate(); int dd = now.day(); - QString expected = "__" + QString( "%1" ).arg( dd + 1 ) + "(ok)__"; - mComposerLabel->setText( "__[%$CURRENT_DATE(dd) + 1%](ok)__" ); + QString expected = "__" + QStringLiteral( "%1" ).arg( dd + 1 ) + "(ok)__"; + mComposerLabel->setText( QStringLiteral( "__[%$CURRENT_DATE(dd) + 1%](ok)__" ) ); QString evaluated = mComposerLabel->displayText(); QCOMPARE( evaluated, expected ); } { // expression evaluation (without feature) - QString expected = "__[NAME_1]42__"; - mComposerLabel->setText( "__[%\"NAME_1\"%][%21*2%]__" ); + QString expected = QStringLiteral( "__[NAME_1]42__" ); + mComposerLabel->setText( QStringLiteral( "__[%\"NAME_1\"%][%21*2%]__" ) ); QString evaluated = mComposerLabel->displayText(); QCOMPARE( evaluated, expected ); } @@ -166,17 +166,17 @@ void TestQgsComposerLabel::feature_evaluation() mComposition->atlasComposition().prepareForFeature( 0 ); { // evaluation with a feature - mComposerLabel->setText( "[%\"NAME_1\"||'_ok'%]" ); + mComposerLabel->setText( QStringLiteral( "[%\"NAME_1\"||'_ok'%]" ) ); QString evaluated = mComposerLabel->displayText(); - QString expected = "Basse-Normandie_ok"; + QString expected = QStringLiteral( "Basse-Normandie_ok" ); QCOMPARE( evaluated, expected ); } mComposition->atlasComposition().prepareForFeature( 1 ); { // evaluation with a feature - mComposerLabel->setText( "[%\"NAME_1\"||'_ok'%]" ); + mComposerLabel->setText( QStringLiteral( "[%\"NAME_1\"||'_ok'%]" ) ); QString evaluated = mComposerLabel->displayText(); - QString expected = "Bretagne_ok"; + QString expected = QStringLiteral( "Bretagne_ok" ); QCOMPARE( evaluated, expected ); } mComposition->atlasComposition().setEnabled( false ); @@ -186,9 +186,9 @@ void TestQgsComposerLabel::page_evaluation() { mComposition->setNumPages( 2 ); { - mComposerLabel->setText( "[%@layout_page||'/'||@layout_numpages%]" ); + mComposerLabel->setText( QStringLiteral( "[%@layout_page||'/'||@layout_numpages%]" ) ); QString evaluated = mComposerLabel->displayText(); - QString expected = "1/2"; + QString expected = QStringLiteral( "1/2" ); QCOMPARE( evaluated, expected ); // move to the second page and re-evaluate @@ -213,7 +213,7 @@ void TestQgsComposerLabel::marginMethods() //test reading label margins from pre 2.7 projects QDomDocument labelDoc; QString labelXml; - labelXml = "=2.7 projects - labelXml = "setText( "test label" ); - mComposerLabel->setFont( QgsFontUtils::getStandardTestFont( "Bold", 48 ) ); + mComposerLabel->setText( QStringLiteral( "test label" ) ); + mComposerLabel->setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ), 48 ) ); mComposerLabel->setPos( 70, 70 ); mComposerLabel->adjustSizeToText(); - QgsCompositionChecker checker( "composerlabel_render", mComposition ); - checker.setControlPathPrefix( "composer_label" ); + QgsCompositionChecker checker( QStringLiteral( "composerlabel_render" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_label" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } void TestQgsComposerLabel::renderAsHtml() { mComposerLabel->setFontColor( QColor( 200, 40, 60 ) ); - mComposerLabel->setText( "test html" ); - mComposerLabel->setFont( QgsFontUtils::getStandardTestFont( "Bold", 48 ) ); + mComposerLabel->setText( QStringLiteral( "test html" ) ); + mComposerLabel->setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ), 48 ) ); mComposerLabel->setPos( 70, 70 ); mComposerLabel->adjustSizeToText(); mComposerLabel->setHtmlState( 1 ); mComposerLabel->update(); - QgsCompositionChecker checker( "composerlabel_renderhtml", mComposition ); - checker.setControlPathPrefix( "composer_label" ); + QgsCompositionChecker checker( QStringLiteral( "composerlabel_renderhtml" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_label" ) ); QVERIFY( checker.testComposition( mReport, 0, 10 ) ); } void TestQgsComposerLabel::renderAsHtmlRelative() { - QgsProject::instance()->setFileName( QString( TEST_DATA_DIR ) + QDir::separator() + "test.qgs" ); + QgsProject::instance()->setFileName( QStringLiteral( TEST_DATA_DIR ) + QDir::separator() + "test.qgs" ); mComposerLabel->setFontColor( QColor( 200, 40, 60 ) ); - mComposerLabel->setText( "test " ); - mComposerLabel->setFont( QgsFontUtils::getStandardTestFont( "Bold", 48 ) ); + mComposerLabel->setText( QStringLiteral( "test " ) ); + mComposerLabel->setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ), 48 ) ); mComposerLabel->setPos( 70, 70 ); mComposerLabel->adjustSizeToText(); mComposerLabel->setHtmlState( 1 ); mComposerLabel->update(); - QgsCompositionChecker checker( "composerlabel_renderhtmlrelative", mComposition ); - checker.setControlPathPrefix( "composer_label" ); + QgsCompositionChecker checker( QStringLiteral( "composerlabel_renderhtmlrelative" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_label" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } diff --git a/tests/src/core/testqgscomposermap.cpp b/tests/src/core/testqgscomposermap.cpp index 8bbfe727d05d..b32d04fe5f09 100644 --- a/tests/src/core/testqgscomposermap.cpp +++ b/tests/src/core/testqgscomposermap.cpp @@ -74,26 +74,26 @@ void TestQgsComposerMap::initTestCase() QgsApplication::initQgis(); //create maplayers from testdata and add to layer registry - QFileInfo rasterFileInfo( QString( TEST_DATA_DIR ) + "/landsat.tif" ); + QFileInfo rasterFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/landsat.tif" ); mRasterLayer = new QgsRasterLayer( rasterFileInfo.filePath(), rasterFileInfo.completeBaseName() ); QgsMultiBandColorRenderer* rasterRenderer = new QgsMultiBandColorRenderer( mRasterLayer->dataProvider(), 2, 3, 4 ); mRasterLayer->setRenderer( rasterRenderer ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mRasterLayer ); - QFileInfo pointFileInfo( QString( TEST_DATA_DIR ) + "/points.shp" ); + QFileInfo pointFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/points.shp" ); mPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mPointsLayer ); - QFileInfo polyFileInfo( QString( TEST_DATA_DIR ) + "/polys.shp" ); + QFileInfo polyFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/polys.shp" ); mPolysLayer = new QgsVectorLayer( polyFileInfo.filePath(), - polyFileInfo.completeBaseName(), "ogr" ); + polyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mPolysLayer ); - QFileInfo lineFileInfo( QString( TEST_DATA_DIR ) + "/lines.shp" ); + QFileInfo lineFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/lines.shp" ); mLinesLayer = new QgsVectorLayer( lineFileInfo.filePath(), - lineFileInfo.completeBaseName(), "ogr" ); + lineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << mLinesLayer ); } @@ -124,7 +124,7 @@ void TestQgsComposerMap::init() mComposerMap->setFrameEnabled( true ); mComposition->addComposerMap( mComposerMap ); - mReport = "

                                                                                                                                                                                    Composer Map Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Map Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerMap::cleanup() @@ -136,8 +136,8 @@ void TestQgsComposerMap::cleanup() void TestQgsComposerMap::render() { mComposerMap->setNewExtent( QgsRectangle( 781662.375, 3339523.125, 793062.375, 3345223.125 ) ); - QgsCompositionChecker checker( "composermap_render", mComposition ); - checker.setControlPathPrefix( "composer_map" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_render" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_map" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } @@ -145,7 +145,7 @@ void TestQgsComposerMap::render() void TestQgsComposerMap::uniqueId() { QDomDocument doc; - QDomElement documentElement = doc.createElement( "ComposerItemClipboard" ); + QDomElement documentElement = doc.createElement( QStringLiteral( "ComposerItemClipboard" ) ); mComposerMap->writeXml( documentElement, doc ); mComposition->addItemsFromXml( documentElement, doc, 0, false ); @@ -270,17 +270,17 @@ void TestQgsComposerMap::dataDefinedLayers() mComposition->addComposerMap( mComposerMap ); //test malformed layer set string - mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, "'x'", QString() ); + mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, QStringLiteral( "'x'" ), QString() ); QStringList result = mComposerMap->layersToRender(); QVERIFY( result.isEmpty() ); - mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, "'x|'", QString() ); + mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, QStringLiteral( "'x|'" ), QString() ); result = mComposerMap->layersToRender(); QVERIFY( result.isEmpty() ); //test subset of valid layers mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, - QString( "'%1|%2'" ).arg( mPolysLayer->name(), mRasterLayer->name() ), QString() ); + QStringLiteral( "'%1|%2'" ).arg( mPolysLayer->name(), mRasterLayer->name() ), QString() ); result = mComposerMap->layersToRender(); QCOMPARE( result.count(), 2 ); QVERIFY( result.contains( mPolysLayer->id() ) ); @@ -288,7 +288,7 @@ void TestQgsComposerMap::dataDefinedLayers() //test non-existant layer mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, - QString( "'x|%1|%2'" ).arg( mLinesLayer->name(), mPointsLayer->name() ), QString() ); + QStringLiteral( "'x|%1|%2'" ).arg( mLinesLayer->name(), mPointsLayer->name() ), QString() ); result = mComposerMap->layersToRender(); QCOMPARE( result.count(), 2 ); QVERIFY( result.contains( mLinesLayer->id() ) ); @@ -296,18 +296,18 @@ void TestQgsComposerMap::dataDefinedLayers() //test no layers mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, - QString( "''" ), QString() ); + QStringLiteral( "''" ), QString() ); result = mComposerMap->layersToRender(); QVERIFY( result.isEmpty() ); //test with atlas feature evaluation - QgsVectorLayer* atlasLayer = new QgsVectorLayer( "Point?field=col1:string", "atlas", "memory" ); + QgsVectorLayer* atlasLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string" ), QStringLiteral( "atlas" ), QStringLiteral( "memory" ) ); QVERIFY( atlasLayer->isValid() ); QgsFeature f1( atlasLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", mLinesLayer->name() ); + f1.setAttribute( QStringLiteral( "col1" ), mLinesLayer->name() ); QgsFeature f2( atlasLayer->dataProvider()->fields(), 1 ); - f2.setAttribute( "col1", mPointsLayer->name() ); + f2.setAttribute( QStringLiteral( "col1" ), mPointsLayer->name() ); atlasLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 ); mComposition->atlasComposition().setCoverageLayer( atlasLayer ); mComposition->atlasComposition().setEnabled( true ); @@ -315,7 +315,7 @@ void TestQgsComposerMap::dataDefinedLayers() mComposition->atlasComposition().beginRender(); mComposition->atlasComposition().prepareForFeature( 0 ); - mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, QString( "\"col1\"" ), QString() ); + mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, QStringLiteral( "\"col1\"" ), QString() ); result = mComposerMap->layersToRender(); QCOMPARE( result.count(), 1 ); QCOMPARE( result.at( 0 ), mLinesLayer->id() ); @@ -328,11 +328,11 @@ void TestQgsComposerMap::dataDefinedLayers() //render test mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, - QString( "'%1|%2'" ).arg( mPolysLayer->name(), mPointsLayer->name() ), QString() ); + QStringLiteral( "'%1|%2'" ).arg( mPolysLayer->name(), mPointsLayer->name() ), QString() ); mComposerMap->setNewExtent( QgsRectangle( -110.0, 25.0, -90, 40.0 ) ); - QgsCompositionChecker checker( "composermap_ddlayers", mComposition ); - checker.setControlPathPrefix( "composer_map" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_ddlayers" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_map" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } @@ -352,22 +352,22 @@ void TestQgsComposerMap::dataDefinedStyles() QgsMapThemeCollection::MapThemeRecord rec; rec.setVisibleLayerIds( QStringList() << mPointsLayer->id() << mLinesLayer->id() ); - QgsProject::instance()->mapThemeCollection()->insert( "test preset", rec ); + QgsProject::instance()->mapThemeCollection()->insert( QStringLiteral( "test preset" ), rec ); // test following of preset mComposerMap->setFollowVisibilityPreset( true ); - mComposerMap->setFollowVisibilityPresetName( "test preset" ); + mComposerMap->setFollowVisibilityPresetName( QStringLiteral( "test preset" ) ); QSet result = mComposerMap->layersToRender().toSet(); QCOMPARE( result.count(), 2 ); mComposerMap->setFollowVisibilityPresetName( QString() ); //test malformed style string - mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, "5", QString() ); + mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, QStringLiteral( "5" ), QString() ); result = mComposerMap->layersToRender().toSet(); QCOMPARE( result, ms.layers().toSet() ); //test valid preset - mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, QString( "'test preset'" ), QString() ); + mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, QStringLiteral( "'test preset'" ), QString() ); result = mComposerMap->layersToRender().toSet(); QCOMPARE( result.count(), 2 ); QVERIFY( result.contains( mLinesLayer->id() ) ); @@ -375,14 +375,14 @@ void TestQgsComposerMap::dataDefinedStyles() //test non-existant preset mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, - QString( "'bad preset'" ), QString() ); + QStringLiteral( "'bad preset'" ), QString() ); result = mComposerMap->layersToRender().toSet(); QCOMPARE( result, ms.layers().toSet() ); //test that dd layer set overrides style layers - mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, QString( "'test preset'" ), QString() ); + mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, QStringLiteral( "'test preset'" ), QString() ); mComposerMap->setDataDefinedProperty( QgsComposerObject::MapLayers, true, true, - QString( "'%1'" ).arg( mPolysLayer->name() ), QString() ); + QStringLiteral( "'%1'" ).arg( mPolysLayer->name() ), QString() ); result = mComposerMap->layersToRender().toSet(); QCOMPARE( result.count(), 1 ); QVERIFY( result.contains( mPolysLayer->id() ) ); @@ -390,11 +390,11 @@ void TestQgsComposerMap::dataDefinedStyles() //render test mComposerMap->setDataDefinedProperty( QgsComposerObject::MapStylePreset, true, true, - QString( "'test preset'" ), QString() ); + QStringLiteral( "'test preset'" ), QString() ); mComposerMap->setNewExtent( QgsRectangle( -110.0, 25.0, -90, 40.0 ) ); - QgsCompositionChecker checker( "composermap_ddstyles", mComposition ); - checker.setControlPathPrefix( "composer_map" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_ddstyles" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_map" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } diff --git a/tests/src/core/testqgscomposermapgrid.cpp b/tests/src/core/testqgscomposermapgrid.cpp index 0aa0b379f24e..915c8a960978 100644 --- a/tests/src/core/testqgscomposermapgrid.cpp +++ b/tests/src/core/testqgscomposermapgrid.cpp @@ -77,7 +77,7 @@ void TestQgsComposerMapGrid::initTestCase() QgsApplication::initQgis(); mMapSettings = new QgsMapSettings(); - mReport = "

                                                                                                                                                                                    Composer Map Grid Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Map Grid Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerMapGrid::cleanupTestCase() @@ -138,8 +138,8 @@ void TestQgsComposerMapGrid::grid() mComposerMap->grid()->setBlendMode( QPainter::CompositionMode_Overlay ); mComposerMap->updateBoundingRect(); qWarning() << "grid annotation font: " << mComposerMap->grid()->annotationFont().toString() << " exactMatch:" << mComposerMap->grid()->annotationFont().exactMatch(); - QgsCompositionChecker checker( "composermap_grid", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_grid" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposerMap->grid()->setEnabled( false ); @@ -161,8 +161,8 @@ void TestQgsComposerMapGrid::reprojected() mComposerMap->grid()->setFrameWidth( 10 ); mComposerMap->setFrameEnabled( false ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_gridreprojected", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_gridreprojected" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposerMap->grid()->setEnabled( false ); @@ -182,8 +182,8 @@ void TestQgsComposerMapGrid::crossGrid() mComposerMap->grid()->setGridLineColor( QColor( 0, 255, 0 ) ); mComposerMap->grid()->setBlendMode( QPainter::CompositionMode_SourceOver ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_crossgrid", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_crossgrid" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposerMap->grid()->setStyle( QgsComposerMapGrid::Solid ); @@ -200,8 +200,8 @@ void TestQgsComposerMapGrid::markerGrid() mComposerMap->grid()->setAnnotationEnabled( false ); mComposerMap->grid()->setBlendMode( QPainter::CompositionMode_SourceOver ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_markergrid", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_markergrid" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposerMap->grid()->setStyle( QgsComposerMapGrid::Solid ); @@ -222,8 +222,8 @@ void TestQgsComposerMapGrid::frameOnly() mComposerMap->grid()->setFramePenSize( 0.5 ); mComposerMap->grid()->setBlendMode( QPainter::CompositionMode_SourceOver ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_gridframeonly", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_gridframeonly" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposerMap->grid()->setStyle( QgsComposerMapGrid::Solid ); @@ -248,8 +248,8 @@ void TestQgsComposerMapGrid::zebraStyle() mComposerMap->grid()->setEnabled( true ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_zebrastyle", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_zebrastyle" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -275,22 +275,22 @@ void TestQgsComposerMapGrid::zebraStyleSides() mComposerMap->grid()->setFrameSideFlag( QgsComposerMapGrid::FrameBottom, false ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_zebrastyle_left", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_zebrastyle_left" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); mComposerMap->grid()->setFrameSideFlag( QgsComposerMapGrid::FrameTop, true ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_zebrastyle_lefttop", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_zebrastyle_lefttop" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult2 = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult2 ); mComposerMap->grid()->setFrameSideFlag( QgsComposerMapGrid::FrameRight, true ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker3( "composermap_zebrastyle_lefttopright", mComposition ); - checker3.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker3( QStringLiteral( "composermap_zebrastyle_lefttopright" ), mComposition ); + checker3.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult3 = checker3.testComposition( mReport, 0, 0 ); QVERIFY( testResult3 ); @@ -321,8 +321,8 @@ void TestQgsComposerMapGrid::frameDivisions() mComposerMap->grid()->setFrameSideFlag( QgsComposerMapGrid::FrameBottom, true ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_rotatedframe", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_rotatedframe" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -332,8 +332,8 @@ void TestQgsComposerMapGrid::frameDivisions() mComposerMap->grid()->setFrameDivisions( QgsComposerMapGrid::LongitudeOnly, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_framedivisions", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_framedivisions" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); testResult = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -364,8 +364,8 @@ void TestQgsComposerMapGrid::annotationFilter() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_rotatedannotations", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_rotatedannotations" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -375,8 +375,8 @@ void TestQgsComposerMapGrid::annotationFilter() mComposerMap->grid()->setAnnotationDisplay( QgsComposerMapGrid::LongitudeOnly, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_filteredannotations", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_filteredannotations" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); testResult = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -400,8 +400,8 @@ void TestQgsComposerMapGrid::interiorTicks() mComposerMap->grid()->setStyle( QgsComposerMapGrid::FrameAnnotationsOnly ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_interiorticks", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_interiorticks" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -426,8 +426,8 @@ void TestQgsComposerMapGrid::interiorTicksAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::InsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_interiorticks_annotated", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_interiorticks_annotated" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -437,8 +437,8 @@ void TestQgsComposerMapGrid::interiorTicksAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_interiorticks_annotated2", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_interiorticks_annotated2" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult2 = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult2 ); @@ -458,8 +458,8 @@ void TestQgsComposerMapGrid::exteriorTicks() mComposerMap->grid()->setStyle( QgsComposerMapGrid::FrameAnnotationsOnly ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_exteriorticks", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_exteriorticks" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -484,8 +484,8 @@ void TestQgsComposerMapGrid::exteriorTicksAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::InsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_exteriorticks_annotated", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_exteriorticks_annotated" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -495,8 +495,8 @@ void TestQgsComposerMapGrid::exteriorTicksAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_exteriorticks_annotated2", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_exteriorticks_annotated2" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult2 = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult2 ); @@ -516,8 +516,8 @@ void TestQgsComposerMapGrid::interiorExteriorTicks() mComposerMap->grid()->setStyle( QgsComposerMapGrid::FrameAnnotationsOnly ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_interiorexteriorticks", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_interiorexteriorticks" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -542,8 +542,8 @@ void TestQgsComposerMapGrid::interiorExteriorTicksAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::InsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_interiorexteriorticks_annotated", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_interiorexteriorticks_annotated" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -553,8 +553,8 @@ void TestQgsComposerMapGrid::interiorExteriorTicksAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_interiorexteriorticks_annotated2", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_interiorexteriorticks_annotated2" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult2 = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult2 ); @@ -574,8 +574,8 @@ void TestQgsComposerMapGrid::lineBorder() mComposerMap->grid()->setStyle( QgsComposerMapGrid::FrameAnnotationsOnly ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_lineborder", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_lineborder" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -600,8 +600,8 @@ void TestQgsComposerMapGrid::lineBorderAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::InsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_lineborder_annotated", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_lineborder_annotated" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -611,8 +611,8 @@ void TestQgsComposerMapGrid::lineBorderAnnotated() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_lineborder_annotated2", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_lineborder_annotated2" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult2 = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult2 ); @@ -628,9 +628,9 @@ void TestQgsComposerMapGrid::annotationFormats() QgsCoordinateReferenceSystem geographicCrs; geographicCrs.createFromSrid( 4326 ); - QgsComposerMapGrid gridGeographic( "geographic grid", mComposerMap ); + QgsComposerMapGrid gridGeographic( QStringLiteral( "geographic grid" ), mComposerMap ); gridGeographic.setCrs( geographicCrs ); - QgsComposerMapGrid gridProjected( "projected grid", mComposerMap ); + QgsComposerMapGrid gridProjected( QStringLiteral( "projected grid" ), mComposerMap ); gridProjected.setCrs( projectedCrs ); //decimal degrees format @@ -663,7 +663,7 @@ void TestQgsComposerMapGrid::annotationFormats() //Custom format annotations gridProjected.setAnnotationFormat( QgsComposerMapGrid::CustomFormat ); - gridProjected.setAnnotationExpression( "(@grid_number/10) || case when @grid_axis ='x' then 'a' else 'b' end" ); + gridProjected.setAnnotationExpression( QStringLiteral( "(@grid_number/10) || case when @grid_axis ='x' then 'a' else 'b' end" ) ); QCOMPARE( gridProjected.gridAnnotationString( 45, QgsComposerMapGrid::Latitude, expressionContext ), QString( "4.5b" ) ); QCOMPARE( gridProjected.gridAnnotationString( 33, QgsComposerMapGrid::Longitude, expressionContext ), QString( "3.3a" ) ); } @@ -687,8 +687,8 @@ void TestQgsComposerMapGrid::descendingAnnotations() mComposerMap->grid()->setAnnotationDirection( QgsComposerMapGrid::VerticalDescending, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker( "composermap_verticaldescending_inside", mComposition ); - checker.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_verticaldescending_inside" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); QVERIFY( testResult ); @@ -698,8 +698,8 @@ void TestQgsComposerMapGrid::descendingAnnotations() mComposerMap->grid()->setAnnotationPosition( QgsComposerMapGrid::OutsideMapFrame, QgsComposerMapGrid::Bottom ); mComposerMap->updateBoundingRect(); - QgsCompositionChecker checker2( "composermap_verticaldescending_outside", mComposition ); - checker2.setControlPathPrefix( "composer_mapgrid" ); + QgsCompositionChecker checker2( QStringLiteral( "composermap_verticaldescending_outside" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_mapgrid" ) ); bool testResult2 = checker2.testComposition( mReport, 0, 0 ); QVERIFY( testResult2 ); diff --git a/tests/src/core/testqgscomposermapoverview.cpp b/tests/src/core/testqgscomposermapoverview.cpp index 424d7a59f232..c44633ef4dab 100644 --- a/tests/src/core/testqgscomposermapoverview.cpp +++ b/tests/src/core/testqgscomposermapoverview.cpp @@ -68,7 +68,7 @@ void TestQgsComposerMapOverview::initTestCase() mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo rasterFileInfo( QString( TEST_DATA_DIR ) + "/rgb256x256.png" ); + QFileInfo rasterFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/rgb256x256.png" ); mRasterLayer = new QgsRasterLayer( rasterFileInfo.filePath(), rasterFileInfo.completeBaseName() ); QgsMultiBandColorRenderer* rasterRenderer = new QgsMultiBandColorRenderer( mRasterLayer->dataProvider(), 1, 2, 3 ); @@ -85,7 +85,7 @@ void TestQgsComposerMapOverview::initTestCase() mComposerMap->setFrameEnabled( true ); mComposition->addComposerMap( mComposerMap ); - mReport = "

                                                                                                                                                                                    Composer Map Overview Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Map Overview Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerMapOverview::cleanupTestCase() @@ -121,8 +121,8 @@ void TestQgsComposerMapOverview::overviewMap() mComposerMap->setNewExtent( QgsRectangle( 96, -152, 160, -120 ) ); //zoom in overviewMap->setNewExtent( QgsRectangle( 0, -256, 256, 0 ) ); overviewMap->overview()->setFrameMap( mComposerMap->id() ); - QgsCompositionChecker checker( "composermap_overview", mComposition ); - checker.setControlPathPrefix( "composer_mapoverview" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_overview" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapoverview" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposition->removeComposerItem( overviewMap ); @@ -138,8 +138,8 @@ void TestQgsComposerMapOverview::overviewMapRotated() mComposerMap->setMapRotation( 30 ); overviewMap->setNewExtent( QgsRectangle( 0, -256, 256, 0 ) ); overviewMap->overview()->setFrameMap( mComposerMap->id() ); - QgsCompositionChecker checker( "composermap_overview_rotated", mComposition ); - checker.setControlPathPrefix( "composer_mapoverview" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_overview_rotated" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapoverview" ) ); bool testResult = checker.testComposition( mReport, 0, 600 ); mComposition->removeComposerItem( overviewMap ); @@ -156,8 +156,8 @@ void TestQgsComposerMapOverview::overviewMapRotated2() overviewMap->setMapRotation( 30 ); overviewMap->setNewExtent( QgsRectangle( 0, -256, 256, 0 ) ); overviewMap->overview()->setFrameMap( mComposerMap->id() ); - QgsCompositionChecker checker( "composermap_overview_rotated2", mComposition ); - checker.setControlPathPrefix( "composer_mapoverview" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_overview_rotated2" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapoverview" ) ); bool testResult = checker.testComposition( mReport, 0, 600 ); mComposition->removeComposerItem( overviewMap ); @@ -174,8 +174,8 @@ void TestQgsComposerMapOverview::overviewMapBlending() overviewMapBlend->overview()->setFrameMap( mComposerMap->id() ); overviewMapBlend->overview()->setBlendMode( QPainter::CompositionMode_Multiply ); - QgsCompositionChecker checker( "composermap_overview_blending", mComposition ); - checker.setControlPathPrefix( "composer_mapoverview" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_overview_blending" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapoverview" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposition->removeComposerItem( overviewMapBlend ); @@ -192,8 +192,8 @@ void TestQgsComposerMapOverview::overviewMapInvert() overviewMapInvert->overview()->setFrameMap( mComposerMap->id() ); overviewMapInvert->overview()->setInverted( true ); - QgsCompositionChecker checker( "composermap_overview_invert", mComposition ); - checker.setControlPathPrefix( "composer_mapoverview" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_overview_invert" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapoverview" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposition->removeComposerItem( overviewMapInvert ); @@ -210,8 +210,8 @@ void TestQgsComposerMapOverview::overviewMapCenter() overviewMapCenter->overview()->setFrameMap( mComposerMap->id() ); overviewMapCenter->overview()->setCentered( true ); - QgsCompositionChecker checker( "composermap_overview_center", mComposition ); - checker.setControlPathPrefix( "composer_mapoverview" ); + QgsCompositionChecker checker( QStringLiteral( "composermap_overview_center" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_mapoverview" ) ); bool testResult = checker.testComposition( mReport, 0, 0 ); mComposition->removeComposerItem( overviewMapCenter ); diff --git a/tests/src/core/testqgscomposermultiframe.cpp b/tests/src/core/testqgscomposermultiframe.cpp index 921ebd7c7d23..c983d49674d5 100644 --- a/tests/src/core/testqgscomposermultiframe.cpp +++ b/tests/src/core/testqgscomposermultiframe.cpp @@ -64,7 +64,7 @@ void TestQgsComposerMultiFrame::initTestCase() mComposition = new QgsComposition( *mMapSettings ); mComposition->setPaperSize( 297, 210 ); //A4 landscape - mReport = "

                                                                                                                                                                                    Composer MultiFrame Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer MultiFrame Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerMultiFrame::cleanupTestCase() @@ -147,21 +147,21 @@ void TestQgsComposerMultiFrame::frameIsEmpty() htmlItem->addFrame( frame2 ); htmlItem->setContentMode( QgsComposerHtml::ManualHtml ); //short content, so frame 2 should be empty - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( frame1->isEmpty(), false ); QCOMPARE( frame2->isEmpty(), true ); //long content, so frame 2 should not be empty - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( frame1->isEmpty(), false ); QCOMPARE( frame2->isEmpty(), false ); //..and back again.. - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( frame1->isEmpty(), false ); @@ -180,7 +180,7 @@ void TestQgsComposerMultiFrame::addRemovePage() htmlItem->setResizeMode( QgsComposerMultiFrame::RepeatUntilFinished ); //short content, so should fit in one frame - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); //should be one page @@ -188,14 +188,14 @@ void TestQgsComposerMultiFrame::addRemovePage() QCOMPARE( mComposition->numPages(), 1 ); //long content, so we require 3 frames - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( htmlItem->frameCount(), 3 ); QCOMPARE( mComposition->numPages(), 3 ); //..and back again.. - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( htmlItem->frameCount(), 1 ); @@ -208,14 +208,14 @@ void TestQgsComposerMultiFrame::addRemovePage() label1->setItemPosition( 10, 10, 50, 50, QgsComposerItem::UpperLeft, false, 3 ); //long content, so we require 4 pages - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( htmlItem->frameCount(), 4 ); QCOMPARE( mComposition->numPages(), 4 ); //..and back again. Since there's an item on page 3, only page 4 should be removed - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( htmlItem->frameCount(), 1 ); @@ -234,31 +234,31 @@ void TestQgsComposerMultiFrame::undoRedo() htmlItem->setResizeMode( QgsComposerMultiFrame::RepeatUntilFinished ); //short content, so should fit in one frame - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test content

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test content

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); //do some combinations of undo/redo commands for both the frame and multiframe //to try to trigger a crash - frame1->beginCommand( "move" ); + frame1->beginCommand( QStringLiteral( "move" ) ); frame1->setSceneRect( QRectF( 10, 10, 20, 20 ) ); frame1->endCommand(); - frame1->beginCommand( "outline", QgsComposerMergeCommand::ItemOutlineWidth ); + frame1->beginCommand( QStringLiteral( "outline" ), QgsComposerMergeCommand::ItemOutlineWidth ); frame1->setFrameOutlineWidth( 4.0 ); frame1->endCommand(); - frame1->beginCommand( "outline", QgsComposerMergeCommand::ItemOutlineWidth ); + frame1->beginCommand( QStringLiteral( "outline" ), QgsComposerMergeCommand::ItemOutlineWidth ); frame1->setFrameOutlineWidth( 7.0 ); frame1->endCommand(); //multiframe commands - mComposition->beginMultiFrameCommand( htmlItem, "maxbreak" ); + mComposition->beginMultiFrameCommand( htmlItem, QStringLiteral( "maxbreak" ) ); htmlItem->setMaxBreakDistance( 100 ); mComposition->endMultiFrameCommand(); //another frame command - frame1->beginCommand( "bgcolor", QgsComposerMergeCommand::ItemTransparency ); + frame1->beginCommand( QStringLiteral( "bgcolor" ), QgsComposerMergeCommand::ItemTransparency ); frame1->setBackgroundColor( QColor( 255, 255, 0 ) ); frame1->endCommand(); - frame1->beginCommand( "bgcolor", QgsComposerMergeCommand::ItemTransparency ); + frame1->beginCommand( QStringLiteral( "bgcolor" ), QgsComposerMergeCommand::ItemTransparency ); frame1->setBackgroundColor( QColor( 255, 0, 0 ) ); frame1->endCommand(); @@ -310,23 +310,23 @@ void TestQgsComposerMultiFrame::undoRedoRemovedFrame() htmlItem->setResizeMode( QgsComposerMultiFrame::RepeatUntilFinished ); //long content, so should require multiple frames - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test content

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test content

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QVERIFY( htmlItem->frameCount() > 1 ); //do a command on the first frame - htmlItem->frame( 0 )->beginCommand( "outline", QgsComposerMergeCommand::ItemOutlineWidth ); + htmlItem->frame( 0 )->beginCommand( QStringLiteral( "outline" ), QgsComposerMergeCommand::ItemOutlineWidth ); htmlItem->frame( 0 )->setFrameOutlineWidth( 4.0 ); htmlItem->frame( 0 )->endCommand(); //do a command on the second frame - htmlItem->frame( 1 )->beginCommand( "outline", QgsComposerMergeCommand::ItemOutlineWidth ); + htmlItem->frame( 1 )->beginCommand( QStringLiteral( "outline" ), QgsComposerMergeCommand::ItemOutlineWidth ); htmlItem->frame( 1 )->setFrameOutlineWidth( 8.0 ); htmlItem->frame( 1 )->endCommand(); //do a multiframe command which removes extra frames - mComposition->beginMultiFrameCommand( htmlItem, "source" ); - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test content

                                                                                                                                                                                    " ) ); + mComposition->beginMultiFrameCommand( htmlItem, QStringLiteral( "source" ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test content

                                                                                                                                                                                    " ) ); mComposition->endMultiFrameCommand(); //wipes the second frame diff --git a/tests/src/core/testqgscomposerobject.cpp b/tests/src/core/testqgscomposerobject.cpp index e6d00fb21030..eecd1d4ae6e9 100644 --- a/tests/src/core/testqgscomposerobject.cpp +++ b/tests/src/core/testqgscomposerobject.cpp @@ -67,7 +67,7 @@ void TestQgsComposerObject::initTestCase() mComposition = new QgsComposition( *mMapSettings ); mComposition->setPaperSize( 297, 210 ); //A4 landscape - mReport = "

                                                                                                                                                                                    Composer Object Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Object Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerObject::cleanupTestCase() @@ -115,21 +115,21 @@ void TestQgsComposerObject::writeReadXml() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); //test writing with no node - QDomElement rootNode = doc.createElement( "qgis" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); QDomElement noNode; QCOMPARE( object->writeXml( noNode, doc ), false ); //test writing with node - QDomElement composerObjectElem = doc.createElement( "ComposerObject" ); + QDomElement composerObjectElem = doc.createElement( QStringLiteral( "ComposerObject" ) ); rootNode.appendChild( composerObjectElem ); QVERIFY( object->writeXml( composerObjectElem, doc ) ); //check if object node was written - QDomNodeList evalNodeList = rootNode.elementsByTagName( "ComposerObject" ); + QDomNodeList evalNodeList = rootNode.elementsByTagName( QStringLiteral( "ComposerObject" ) ); QCOMPARE( evalNodeList.count(), 1 ); //test reading node @@ -148,7 +148,7 @@ void TestQgsComposerObject::writeReadXml() void TestQgsComposerObject::setRetrieveDDProperty() { QgsComposerObject* object = new QgsComposerObject( mComposition ); - object->setDataDefinedProperty( QgsComposerObject::Transparency, true, true, QString( "10 + 40" ), QString() ); + object->setDataDefinedProperty( QgsComposerObject::Transparency, true, true, QStringLiteral( "10 + 40" ), QString() ); object->prepareDataDefinedExpressions(); //test retrieving bad properties @@ -174,7 +174,7 @@ void TestQgsComposerObject::setRetrieveDDProperty() void TestQgsComposerObject::evaluateDDProperty() { QgsComposerObject* object = new QgsComposerObject( mComposition ); - object->setDataDefinedProperty( QgsComposerObject::Transparency, true, true, QString( "10 + 40" ), QString() ); + object->setDataDefinedProperty( QgsComposerObject::Transparency, true, true, QStringLiteral( "10 + 40" ), QString() ); object->prepareDataDefinedExpressions(); QVariant result; @@ -194,22 +194,22 @@ void TestQgsComposerObject::evaluateDDProperty() void TestQgsComposerObject::writeRetrieveDDProperty() { QgsComposerObject* object = new QgsComposerObject( mComposition ); - object->setDataDefinedProperty( QgsComposerObject::TestProperty, true, true, QString( "10 + 40" ), QString() ); + object->setDataDefinedProperty( QgsComposerObject::TestProperty, true, true, QStringLiteral( "10 + 40" ), QString() ); object->prepareDataDefinedExpressions(); //test writing object with dd settings QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement rootNode = doc.createElement( "qgis" ); - QDomElement composerObjectElem = doc.createElement( "ComposerObject" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); + QDomElement composerObjectElem = doc.createElement( QStringLiteral( "ComposerObject" ) ); rootNode.appendChild( composerObjectElem ); QVERIFY( object->writeXml( composerObjectElem, doc ) ); //check if object node was written - QDomNodeList evalNodeList = rootNode.elementsByTagName( "ComposerObject" ); + QDomNodeList evalNodeList = rootNode.elementsByTagName( QStringLiteral( "ComposerObject" ) ); QCOMPARE( evalNodeList.count(), 1 ); //test reading node containing dd settings @@ -240,20 +240,20 @@ void TestQgsComposerObject::customProperties() QCOMPARE( object->customProperty( "noprop", "defaultval" ).toString(), QString( "defaultval" ) ); QVERIFY( object->customProperties().isEmpty() ); - object->setCustomProperty( "testprop", "testval" ); + object->setCustomProperty( QStringLiteral( "testprop" ), "testval" ); QCOMPARE( object->customProperty( "testprop", "defaultval" ).toString(), QString( "testval" ) ); QCOMPARE( object->customProperties().length(), 1 ); QCOMPARE( object->customProperties().at( 0 ), QString( "testprop" ) ); //test no crash - object->removeCustomProperty( "badprop" ); + object->removeCustomProperty( QStringLiteral( "badprop" ) ); - object->removeCustomProperty( "testprop" ); + object->removeCustomProperty( QStringLiteral( "testprop" ) ); QVERIFY( object->customProperties().isEmpty() ); QCOMPARE( object->customProperty( "noprop", "defaultval" ).toString(), QString( "defaultval" ) ); - object->setCustomProperty( "testprop1", "testval1" ); - object->setCustomProperty( "testprop2", "testval2" ); + object->setCustomProperty( QStringLiteral( "testprop1" ), "testval1" ); + object->setCustomProperty( QStringLiteral( "testprop2" ), "testval2" ); QStringList keys = object->customProperties(); QCOMPARE( keys.length(), 2 ); QVERIFY( keys.contains( "testprop1" ) ); @@ -265,22 +265,22 @@ void TestQgsComposerObject::customProperties() void TestQgsComposerObject::writeRetrieveCustomProperties() { QgsComposerObject* object = new QgsComposerObject( mComposition ); - object->setCustomProperty( "testprop", "testval" ); - object->setCustomProperty( "testprop2", 5 ); + object->setCustomProperty( QStringLiteral( "testprop" ), "testval" ); + object->setCustomProperty( QStringLiteral( "testprop2" ), 5 ); //test writing object with custom properties QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement rootNode = doc.createElement( "qgis" ); - QDomElement composerObjectElem = doc.createElement( "ComposerObject" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); + QDomElement composerObjectElem = doc.createElement( QStringLiteral( "ComposerObject" ) ); rootNode.appendChild( composerObjectElem ); QVERIFY( object->writeXml( composerObjectElem, doc ) ); //check if object node was written - QDomNodeList evalNodeList = rootNode.elementsByTagName( "ComposerObject" ); + QDomNodeList evalNodeList = rootNode.elementsByTagName( QStringLiteral( "ComposerObject" ) ); QCOMPARE( evalNodeList.count(), 1 ); //test reading node containing custom properties diff --git a/tests/src/core/testqgscomposerpaper.cpp b/tests/src/core/testqgscomposerpaper.cpp index ecb32ad0cd53..532511f80635 100644 --- a/tests/src/core/testqgscomposerpaper.cpp +++ b/tests/src/core/testqgscomposerpaper.cpp @@ -68,7 +68,7 @@ void TestQgsComposerPaper::initTestCase() mComposition = new QgsComposition( *mMapSettings ); mComposition->setPaperSize( 297, 210 ); //A4 landscape - mReport = "

                                                                                                                                                                                    Composer Paper Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Paper Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerPaper::cleanupTestCase() @@ -99,8 +99,8 @@ void TestQgsComposerPaper::cleanup() void TestQgsComposerPaper::defaultPaper() { - QgsCompositionChecker checker( "composerpaper_default", mComposition ); - checker.setControlPathPrefix( "composer_paper" ); + QgsCompositionChecker checker( QStringLiteral( "composerpaper_default" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_paper" ) ); QVERIFY( checker.testComposition( mReport ) ); } @@ -114,8 +114,8 @@ void TestQgsComposerPaper::transparentPaper() mComposition->setPageStyleSymbol( fillSymbol ); delete fillSymbol; - QgsCompositionChecker checker( "composerpaper_transparent", mComposition ); - checker.setControlPathPrefix( "composer_paper" ); + QgsCompositionChecker checker( QStringLiteral( "composerpaper_transparent" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_paper" ) ); QVERIFY( checker.testComposition( mReport ) ); } @@ -130,8 +130,8 @@ void TestQgsComposerPaper::borderedPaper() mComposition->setPageStyleSymbol( fillSymbol ); delete fillSymbol; - QgsCompositionChecker checker( "composerpaper_bordered", mComposition ); - checker.setControlPathPrefix( "composer_paper" ); + QgsCompositionChecker checker( QStringLiteral( "composerpaper_bordered" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_paper" ) ); QVERIFY( checker.testComposition( mReport ) ); } @@ -143,8 +143,8 @@ void TestQgsComposerPaper::markerLinePaper() mComposition->setPageStyleSymbol( markerLineSymbol ); delete markerLineSymbol; - QgsCompositionChecker checker( "composerpaper_markerborder", mComposition ); - checker.setControlPathPrefix( "composer_paper" ); + QgsCompositionChecker checker( QStringLiteral( "composerpaper_markerborder" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_paper" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } @@ -159,8 +159,8 @@ void TestQgsComposerPaper::hiddenPages() delete fillSymbol; mComposition->setPagesVisible( false ); - QgsCompositionChecker checker( "composerpaper_hidden", mComposition ); - checker.setControlPathPrefix( "composer_paper" ); + QgsCompositionChecker checker( QStringLiteral( "composerpaper_hidden" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_paper" ) ); bool result = checker.testComposition( mReport ); mComposition->setPagesVisible( true ); QVERIFY( result ); diff --git a/tests/src/core/testqgscomposerpicture.cpp b/tests/src/core/testqgscomposerpicture.cpp index 226a2aa5b71f..e3c08902bc9e 100644 --- a/tests/src/core/testqgscomposerpicture.cpp +++ b/tests/src/core/testqgscomposerpicture.cpp @@ -87,9 +87,9 @@ void TestQgsComposerPicture::initTestCase() mMapSettings = new QgsMapSettings(); - mPngImage = QString( TEST_DATA_DIR ) + "/sample_image.png"; - mSvgImage = QString( TEST_DATA_DIR ) + "/sample_svg.svg"; - mSvgParamsImage = QString( TEST_DATA_DIR ) + "/svg_params.svg"; + mPngImage = QStringLiteral( TEST_DATA_DIR ) + "/sample_image.png"; + mSvgImage = QStringLiteral( TEST_DATA_DIR ) + "/sample_svg.svg"; + mSvgParamsImage = QStringLiteral( TEST_DATA_DIR ) + "/svg_params.svg"; mComposition = new QgsComposition( *mMapSettings ); mComposition->setPaperSize( 297, 210 ); //A4 landscape @@ -99,7 +99,7 @@ void TestQgsComposerPicture::initTestCase() mComposerPicture->setSceneRect( QRectF( 70, 70, 100, 100 ) ); mComposerPicture->setFrameEnabled( true ); - mReport = "

                                                                                                                                                                                    Composer Picture Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Picture Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerPicture::cleanupTestCase() @@ -135,8 +135,8 @@ void TestQgsComposerPicture::pictureRotation() mComposition->addComposerPicture( mComposerPicture ); mComposerPicture->setPictureRotation( 45 ); - QgsCompositionChecker checker( "composerpicture_rotation", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_rotation" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -149,8 +149,8 @@ void TestQgsComposerPicture::pictureItemRotation() mComposition->addComposerPicture( mComposerPicture ); mComposerPicture->setItemRotation( 45, true ); - QgsCompositionChecker checker( "composerpicture_itemrotation", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_itemrotation" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -163,8 +163,8 @@ void TestQgsComposerPicture::pictureResizeZoom() mComposition->addComposerPicture( mComposerPicture ); mComposerPicture->setResizeMode( QgsComposerPicture::Zoom ); - QgsCompositionChecker checker( "composerpicture_resize_zoom", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_resize_zoom" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -176,8 +176,8 @@ void TestQgsComposerPicture::pictureResizeStretch() mComposition->addComposerPicture( mComposerPicture ); mComposerPicture->setResizeMode( QgsComposerPicture::Stretch ); - QgsCompositionChecker checker( "composerpicture_resize_stretch", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_resize_stretch" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -191,8 +191,8 @@ void TestQgsComposerPicture::pictureResizeClip() mComposerPicture->setResizeMode( QgsComposerPicture::Clip ); mComposerPicture->setSceneRect( QRectF( 70, 70, 30, 50 ) ); - QgsCompositionChecker checker( "composerpicture_resize_clip", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_resize_clip" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -207,8 +207,8 @@ void TestQgsComposerPicture::pictureResizeZoomAndResize() mComposerPicture->setResizeMode( QgsComposerPicture::ZoomResizeFrame ); mComposerPicture->setSceneRect( QRectF( 70, 70, 50, 300 ) ); - QgsCompositionChecker checker( "composerpicture_resize_zoomresize", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_resize_zoomresize" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -223,8 +223,8 @@ void TestQgsComposerPicture::pictureResizeFrameToImage() mComposerPicture->setResizeMode( QgsComposerPicture::FrameToImageSize ); mComposerPicture->setSceneRect( QRectF( 70, 70, 50, 300 ) ); - QgsCompositionChecker checker( "composerpicture_resize_frametoimage", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_resize_frametoimage" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -240,8 +240,8 @@ void TestQgsComposerPicture::pictureClipAnchor() mComposerPicture->setSceneRect( QRectF( 70, 70, 30, 50 ) ); mComposerPicture->setPictureAnchor( QgsComposerItem::LowerRight ); - QgsCompositionChecker checker( "composerpicture_clip_anchor", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_clip_anchor" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -258,8 +258,8 @@ void TestQgsComposerPicture::pictureClipAnchorOversize() mComposerPicture->setSceneRect( QRectF( 70, 70, 150, 120 ) ); mComposerPicture->setPictureAnchor( QgsComposerItem::LowerMiddle ); - QgsCompositionChecker checker( "composerpicture_clip_anchoroversize", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_clip_anchoroversize" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -276,8 +276,8 @@ void TestQgsComposerPicture::pictureZoomAnchor() mComposerPicture->setSceneRect( QRectF( 70, 10, 30, 100 ) ); mComposerPicture->setPictureAnchor( QgsComposerItem::LowerMiddle ); - QgsCompositionChecker checker( "composerpicture_zoom_anchor", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_zoom_anchor" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -292,8 +292,8 @@ void TestQgsComposerPicture::pictureSvgZoom() mComposerPicture->setResizeMode( QgsComposerPicture::Zoom ); mComposerPicture->setPicturePath( mSvgImage ); - QgsCompositionChecker checker( "composerpicture_svg_zoom", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_svg_zoom" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -308,8 +308,8 @@ void TestQgsComposerPicture::pictureSvgStretch() mComposerPicture->setPicturePath( mSvgImage ); mComposerPicture->setSceneRect( QRectF( 70, 70, 20, 100 ) ); - QgsCompositionChecker checker( "composerpicture_svg_stretch", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_svg_stretch" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -326,8 +326,8 @@ void TestQgsComposerPicture::pictureSvgZoomAndResize() mComposerPicture->setPicturePath( mSvgImage ); mComposerPicture->setSceneRect( QRectF( 70, 70, 50, 300 ) ); - QgsCompositionChecker checker( "composerpicture_svg_zoomresize", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_svg_zoomresize" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -343,8 +343,8 @@ void TestQgsComposerPicture::pictureSvgFrameToImage() mComposerPicture->setResizeMode( QgsComposerPicture::FrameToImageSize ); mComposerPicture->setPicturePath( mSvgImage ); - QgsCompositionChecker checker( "composerpicture_svg_frametoimage", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_svg_frametoimage" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -363,8 +363,8 @@ void TestQgsComposerPicture::svgParameters() mComposerPicture->setSvgBorderColor( QColor( 255, 45, 20, 200 ) ); mComposerPicture->setSvgBorderWidth( 2.2 ); - QgsCompositionChecker checker( "composerpicture_svg_params", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_svg_params" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -377,10 +377,10 @@ void TestQgsComposerPicture::issue_14644() //test rendering SVG file with text mComposition->addComposerPicture( mComposerPicture ); mComposerPicture->setResizeMode( QgsComposerPicture::Zoom ); - mComposerPicture->setPicturePath( QString( TEST_DATA_DIR ) + "/svg/issue_14644.svg" ); + mComposerPicture->setPicturePath( QStringLiteral( TEST_DATA_DIR ) + "/svg/issue_14644.svg" ); - QgsCompositionChecker checker( "composerpicture_issue_14644", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_issue_14644" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -393,13 +393,13 @@ void TestQgsComposerPicture::pictureExpression() //test picture source via expression mComposition->addComposerPicture( mComposerPicture ); - QString expr = QString( "'%1' || '/sample_svg.svg'" ).arg( TEST_DATA_DIR ); + QString expr = QStringLiteral( "'%1' || '/sample_svg.svg'" ).arg( TEST_DATA_DIR ); mComposerPicture->setDataDefinedProperty( QgsComposerObject::PictureSource, true, true, expr, QString() ); mComposerPicture->refreshPicture(); - QgsCompositionChecker checker( "composerpicture_expression", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_expression" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); @@ -412,13 +412,13 @@ void TestQgsComposerPicture::pictureInvalidExpression() //test picture source via bad expression mComposition->addComposerPicture( mComposerPicture ); - QString expr = QString( "bad expression" ); + QString expr = QStringLiteral( "bad expression" ); mComposerPicture->setDataDefinedProperty( QgsComposerObject::PictureSource, true, true, expr, QString() ); mComposerPicture->refreshPicture(); - QgsCompositionChecker checker( "composerpicture_badexpression", mComposition ); - checker.setControlPathPrefix( "composer_picture" ); + QgsCompositionChecker checker( QStringLiteral( "composerpicture_badexpression" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_picture" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); mComposition->removeItem( mComposerPicture ); diff --git a/tests/src/core/testqgscomposerrotation.cpp b/tests/src/core/testqgscomposerrotation.cpp index 141057aee1e5..2c4d0497a300 100644 --- a/tests/src/core/testqgscomposerrotation.cpp +++ b/tests/src/core/testqgscomposerrotation.cpp @@ -74,7 +74,7 @@ void TestQgsComposerRotation::initTestCase() mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo rasterFileInfo( QString( TEST_DATA_DIR ) + "/rgb256x256.png" ); + QFileInfo rasterFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/rgb256x256.png" ); mRasterLayer = new QgsRasterLayer( rasterFileInfo.filePath(), rasterFileInfo.completeBaseName() ); QgsMultiBandColorRenderer* rasterRenderer = new QgsMultiBandColorRenderer( mRasterLayer->dataProvider(), 1, 2, 3 ); @@ -93,14 +93,14 @@ void TestQgsComposerRotation::initTestCase() mComposerRect->setBackgroundColor( QColor::fromRgb( 255, 150, 0 ) ); mComposerLabel = new QgsComposerLabel( mComposition ); - mComposerLabel->setText( "test label" ); + mComposerLabel->setText( QStringLiteral( "test label" ) ); mComposerLabel->setFont( QgsFontUtils::getStandardTestFont() ); mComposerLabel->setPos( 70, 70 ); mComposerLabel->adjustSizeToText(); mComposerLabel->setBackgroundColor( QColor::fromRgb( 255, 150, 0 ) ); mComposerLabel->setBackgroundEnabled( true ); - mReport = "

                                                                                                                                                                                    Composer Rotation Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Rotation Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerRotation::cleanupTestCase() @@ -144,8 +144,8 @@ void TestQgsComposerRotation::shapeRotation() mComposerRect->setItemRotation( 45, true ); - QgsCompositionChecker checker( "composerrotation_shape", mComposition ); - checker.setControlPathPrefix( "composer_items" ); + QgsCompositionChecker checker( QStringLiteral( "composerrotation_shape" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_items" ) ); QVERIFY( checker.testComposition( mReport ) ); mComposition->removeItem( mComposerRect ); @@ -157,8 +157,8 @@ void TestQgsComposerRotation::labelRotation() mComposition->addComposerLabel( mComposerLabel ); mComposerLabel->setItemRotation( 135, true ); - QgsCompositionChecker checker( "composerrotation_label", mComposition ); - checker.setControlPathPrefix( "composer_items" ); + QgsCompositionChecker checker( QStringLiteral( "composerrotation_label" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_items" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } @@ -175,8 +175,8 @@ void TestQgsComposerRotation::mapRotation() mComposerMap->setNewExtent( QgsRectangle( 0, -192, 256, -64 ) ); mComposerMap->setMapRotation( 90 ); - QgsCompositionChecker checker( "composerrotation_maprotation", mComposition ); - checker.setControlPathPrefix( "composer_items" ); + QgsCompositionChecker checker( QStringLiteral( "composerrotation_maprotation" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_items" ) ); QVERIFY( checker.testComposition( mReport, 0, 200 ) ); } @@ -193,8 +193,8 @@ void TestQgsComposerRotation::mapItemRotation() mComposerMap->setNewExtent( QgsRectangle( 0, -192, 256, -64 ) ); mComposerMap->setItemRotation( 90, true ); - QgsCompositionChecker checker( "composerrotation_mapitemrotation", mComposition ); - checker.setControlPathPrefix( "composer_items" ); + QgsCompositionChecker checker( QStringLiteral( "composerrotation_mapitemrotation" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_items" ) ); QVERIFY( checker.testComposition( mReport ) ); } diff --git a/tests/src/core/testqgscomposerscalebar.cpp b/tests/src/core/testqgscomposerscalebar.cpp index 6b7159a90554..bdeff0a4aff5 100644 --- a/tests/src/core/testqgscomposerscalebar.cpp +++ b/tests/src/core/testqgscomposerscalebar.cpp @@ -76,12 +76,12 @@ void TestQgsComposerScaleBar::initTestCase() // so we enforce C locale to make sure we get expected result QLocale::setDefault( QLocale::c() ); - QgsProject::instance()->setEllipsoid( "WGS84" ); + QgsProject::instance()->setEllipsoid( QStringLiteral( "WGS84" ) ); mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo rasterFileInfo( QString( TEST_DATA_DIR ) + "/landsat.tif" ); + QFileInfo rasterFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/landsat.tif" ); mRasterLayer = new QgsRasterLayer( rasterFileInfo.filePath(), rasterFileInfo.completeBaseName() ); QgsMultiBandColorRenderer* rasterRenderer = new QgsMultiBandColorRenderer( mRasterLayer->dataProvider(), 2, 3, 4 ); @@ -121,7 +121,7 @@ void TestQgsComposerScaleBar::initTestCase() qWarning() << "scalebar font: " << mComposerScaleBar->font().toString() << " exactMatch:" << mComposerScaleBar->font().exactMatch(); - mReport = "

                                                                                                                                                                                    Composer Scalebar Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Scalebar Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerScaleBar::cleanupTestCase() @@ -153,15 +153,15 @@ void TestQgsComposerScaleBar::cleanup() void TestQgsComposerScaleBar::singleBox() { - mComposerScaleBar->setStyle( "Single Box" ); - QgsCompositionChecker checker( "composerscalebar_singlebox", mComposition ); - checker.setControlPathPrefix( "composer_scalebar" ); + mComposerScaleBar->setStyle( QStringLiteral( "Single Box" ) ); + QgsCompositionChecker checker( QStringLiteral( "composerscalebar_singlebox" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_scalebar" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } void TestQgsComposerScaleBar::singleBoxAlpha() { - mComposerScaleBar->setStyle( "Single Box" ); + mComposerScaleBar->setStyle( QStringLiteral( "Single Box" ) ); mComposerScaleBar->setBrush( QBrush( QColor( 255, 0, 0, 100 ) ) ); mComposerScaleBar->setBrush2( QBrush( QColor( 0, 255, 0, 50 ) ) ); mPrevPen = mComposerScaleBar->pen(); @@ -169,8 +169,8 @@ void TestQgsComposerScaleBar::singleBoxAlpha() newPen.setColor( QColor( 0, 0, 255, 150 ) ); mComposerScaleBar->setPen( newPen ); mComposerScaleBar->setFontColor( QColor( 255, 0, 255, 100 ) ); - QgsCompositionChecker checker( "composerscalebar_singlebox_alpha", mComposition ); - checker.setControlPathPrefix( "composer_scalebar" ); + QgsCompositionChecker checker( QStringLiteral( "composerscalebar_singlebox_alpha" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_scalebar" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } @@ -181,27 +181,27 @@ void TestQgsComposerScaleBar::doubleBox() mComposerScaleBar->setBrush2( QBrush( Qt::white ) ); mComposerScaleBar->setPen( mPrevPen ); mComposerScaleBar->setFontColor( Qt::black ); - mComposerScaleBar->setStyle( "Double Box" ); + mComposerScaleBar->setStyle( QStringLiteral( "Double Box" ) ); - QgsCompositionChecker checker( "composerscalebar_doublebox", mComposition ); - checker.setControlPathPrefix( "composer_scalebar" ); + QgsCompositionChecker checker( QStringLiteral( "composerscalebar_doublebox" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_scalebar" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } void TestQgsComposerScaleBar::numeric() { - mComposerScaleBar->setStyle( "Numeric" ); + mComposerScaleBar->setStyle( QStringLiteral( "Numeric" ) ); mComposerScaleBar->setSceneRect( QRectF( 20, 180, 50, 20 ) ); - QgsCompositionChecker checker( "composerscalebar_numeric", mComposition ); - checker.setControlPathPrefix( "composer_scalebar" ); + QgsCompositionChecker checker( QStringLiteral( "composerscalebar_numeric" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_scalebar" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } void TestQgsComposerScaleBar::tick() { - mComposerScaleBar->setStyle( "Line Ticks Up" ); - QgsCompositionChecker checker( "composerscalebar_tick", mComposition ); - checker.setControlPathPrefix( "composer_scalebar" ); + mComposerScaleBar->setStyle( QStringLiteral( "Line Ticks Up" ) ); + QgsCompositionChecker checker( QStringLiteral( "composerscalebar_tick" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_scalebar" ) ); QVERIFY( checker.testComposition( mReport, 0, 0 ) ); } diff --git a/tests/src/core/testqgscomposershapes.cpp b/tests/src/core/testqgscomposershapes.cpp index eef9e20cee56..c1e2cac334f3 100644 --- a/tests/src/core/testqgscomposershapes.cpp +++ b/tests/src/core/testqgscomposershapes.cpp @@ -71,7 +71,7 @@ void TestQgsComposerShapes::initTestCase() mComposerShape->setBackgroundColor( QColor::fromRgb( 255, 150, 0 ) ); mComposition->addComposerShape( mComposerShape ); - mReport = "

                                                                                                                                                                                    Composer Shape Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Shape Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerShapes::cleanupTestCase() @@ -104,8 +104,8 @@ void TestQgsComposerShapes::rectangle() { mComposerShape->setShapeType( QgsComposerShape::Rectangle ); - QgsCompositionChecker checker( "composershapes_rectangle", mComposition ); - checker.setControlPathPrefix( "composer_shapes" ); + QgsCompositionChecker checker( QStringLiteral( "composershapes_rectangle" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_shapes" ) ); QVERIFY( checker.testComposition( mReport ) ); } @@ -113,8 +113,8 @@ void TestQgsComposerShapes::triangle() { mComposerShape->setShapeType( QgsComposerShape::Triangle ); - QgsCompositionChecker checker( "composershapes_triangle", mComposition ); - checker.setControlPathPrefix( "composer_shapes" ); + QgsCompositionChecker checker( QStringLiteral( "composershapes_triangle" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_shapes" ) ); QVERIFY( checker.testComposition( mReport ) ); } @@ -122,8 +122,8 @@ void TestQgsComposerShapes::ellipse() { mComposerShape->setShapeType( QgsComposerShape::Ellipse ); - QgsCompositionChecker checker( "composershapes_ellipse", mComposition ); - checker.setControlPathPrefix( "composer_shapes" ); + QgsCompositionChecker checker( QStringLiteral( "composershapes_ellipse" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_shapes" ) ); QVERIFY( checker.testComposition( mReport ) ); } @@ -132,8 +132,8 @@ void TestQgsComposerShapes::roundedRectangle() mComposerShape->setShapeType( QgsComposerShape::Rectangle ); mComposerShape->setCornerRadius( 30 ); - QgsCompositionChecker checker( "composershapes_roundedrect", mComposition ); - checker.setControlPathPrefix( "composer_shapes" ); + QgsCompositionChecker checker( QStringLiteral( "composershapes_roundedrect" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_shapes" ) ); QVERIFY( checker.testComposition( mReport ) ); mComposerShape->setCornerRadius( 0 ); } @@ -154,8 +154,8 @@ void TestQgsComposerShapes::symbol() mComposerShape->setUseSymbol( true ); delete fillSymbol; - QgsCompositionChecker checker( "composershapes_symbol", mComposition ); - checker.setControlPathPrefix( "composer_shapes" ); + QgsCompositionChecker checker( QStringLiteral( "composershapes_symbol" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_shapes" ) ); QVERIFY( checker.testComposition( mReport ) ); } diff --git a/tests/src/core/testqgscomposertablev2.cpp b/tests/src/core/testqgscomposertablev2.cpp index 8202906ae9fd..3066e249498b 100644 --- a/tests/src/core/testqgscomposertablev2.cpp +++ b/tests/src/core/testqgscomposertablev2.cpp @@ -99,16 +99,16 @@ void TestQgsComposerTableV2::initTestCase() mMapSettings = new QgsMapSettings(); //create maplayers from testdata and add to layer registry - QFileInfo vectorFileInfo( QString( TEST_DATA_DIR ) + "/points.shp" ); + QFileInfo vectorFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/points.shp" ); mVectorLayer = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayer( mVectorLayer ); mMapSettings->setLayers( QStringList() << mVectorLayer->id() ); mMapSettings->setCrsTransformEnabled( false ); - mReport = "

                                                                                                                                                                                    Composer TableV2 Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer TableV2 Tests

                                                                                                                                                                                    \n" ); } void TestQgsComposerTableV2::cleanupTestCase() @@ -162,7 +162,7 @@ void TestQgsComposerTableV2::attributeTableHeadings() { //test retrieving attribute table headers QStringList expectedHeaders; - expectedHeaders << "Class" << "Heading" << "Importance" << "Pilots" << "Cabin Crew" << "Staff"; + expectedHeaders << QStringLiteral( "Class" ) << QStringLiteral( "Heading" ) << QStringLiteral( "Importance" ) << QStringLiteral( "Pilots" ) << QStringLiteral( "Cabin Crew" ) << QStringLiteral( "Staff" ); //get header labels and compare QMap headerMap = mComposerAttributeTable->headerLabels(); @@ -213,13 +213,13 @@ void TestQgsComposerTableV2::attributeTableRows() QList expectedRows; QStringList row; - row << "Jet" << "90" << "3" << "2" << "0" << "2"; + row << QStringLiteral( "Jet" ) << QStringLiteral( "90" ) << QStringLiteral( "3" ) << QStringLiteral( "2" ) << QStringLiteral( "0" ) << QStringLiteral( "2" ); expectedRows.append( row ); row.clear(); - row << "Biplane" << "0" << "1" << "3" << "3" << "6"; + row << QStringLiteral( "Biplane" ) << QStringLiteral( "0" ) << QStringLiteral( "1" ) << QStringLiteral( "3" ) << QStringLiteral( "3" ) << QStringLiteral( "6" ); expectedRows.append( row ); row.clear(); - row << "Jet" << "85" << "3" << "1" << "1" << "2"; + row << QStringLiteral( "Jet" ) << QStringLiteral( "85" ) << QStringLiteral( "3" ) << QStringLiteral( "1" ) << QStringLiteral( "1" ) << QStringLiteral( "2" ); expectedRows.append( row ); //retrieve rows and check @@ -231,21 +231,21 @@ void TestQgsComposerTableV2::attributeTableFilterFeatures() { //test filtering attribute table rows mComposerAttributeTable->setMaximumNumberOfFeatures( 10 ); - mComposerAttributeTable->setFeatureFilter( QString( "\"Class\"='B52'" ) ); + mComposerAttributeTable->setFeatureFilter( QStringLiteral( "\"Class\"='B52'" ) ); mComposerAttributeTable->setFilterFeatures( true ); QList expectedRows; QStringList row; - row << "B52" << "0" << "10" << "2" << "1" << "3"; + row << QStringLiteral( "B52" ) << QStringLiteral( "0" ) << QStringLiteral( "10" ) << QStringLiteral( "2" ) << QStringLiteral( "1" ) << QStringLiteral( "3" ); expectedRows.append( row ); row.clear(); - row << "B52" << "12" << "10" << "1" << "1" << "2"; + row << QStringLiteral( "B52" ) << QStringLiteral( "12" ) << QStringLiteral( "10" ) << QStringLiteral( "1" ) << QStringLiteral( "1" ) << QStringLiteral( "2" ); expectedRows.append( row ); row.clear(); - row << "B52" << "34" << "10" << "2" << "1" << "3"; + row << QStringLiteral( "B52" ) << QStringLiteral( "34" ) << QStringLiteral( "10" ) << QStringLiteral( "2" ) << QStringLiteral( "1" ) << QStringLiteral( "3" ); expectedRows.append( row ); row.clear(); - row << "B52" << "80" << "10" << "2" << "1" << "3"; + row << QStringLiteral( "B52" ) << QStringLiteral( "80" ) << QStringLiteral( "10" ) << QStringLiteral( "2" ) << QStringLiteral( "1" ) << QStringLiteral( "3" ); expectedRows.append( row ); //retrieve rows and check @@ -258,13 +258,13 @@ void TestQgsComposerTableV2::attributeTableSetAttributes() { //test subset of attributes in table QStringList attributes; - attributes << "Class" << "Pilots" << "Cabin Crew"; + attributes << QStringLiteral( "Class" ) << QStringLiteral( "Pilots" ) << QStringLiteral( "Cabin Crew" ); mComposerAttributeTable->setDisplayedFields( attributes ); mComposerAttributeTable->setMaximumNumberOfFeatures( 3 ); //check headers QStringList expectedHeaders; - expectedHeaders << "Class" << "Pilots" << "Cabin Crew"; + expectedHeaders << QStringLiteral( "Class" ) << QStringLiteral( "Pilots" ) << QStringLiteral( "Cabin Crew" ); //get header labels and compare QMap headerMap = mComposerAttributeTable->headerLabels(); @@ -280,13 +280,13 @@ void TestQgsComposerTableV2::attributeTableSetAttributes() QList expectedRows; QStringList row; - row << "Jet" << "2" << "0"; + row << QStringLiteral( "Jet" ) << QStringLiteral( "2" ) << QStringLiteral( "0" ); expectedRows.append( row ); row.clear(); - row << "Biplane" << "3" << "3"; + row << QStringLiteral( "Biplane" ) << QStringLiteral( "3" ) << QStringLiteral( "3" ); expectedRows.append( row ); row.clear(); - row << "Jet" << "1" << "1"; + row << QStringLiteral( "Jet" ) << QStringLiteral( "1" ) << QStringLiteral( "1" ); expectedRows.append( row ); //retrieve rows and check @@ -309,13 +309,13 @@ void TestQgsComposerTableV2::attributeTableVisibleOnly() QList expectedRows; QStringList row; - row << "Jet" << "90" << "3" << "2" << "0" << "2"; + row << QStringLiteral( "Jet" ) << QStringLiteral( "90" ) << QStringLiteral( "3" ) << QStringLiteral( "2" ) << QStringLiteral( "0" ) << QStringLiteral( "2" ); expectedRows.append( row ); row.clear(); - row << "Biplane" << "240" << "1" << "3" << "2" << "5"; + row << QStringLiteral( "Biplane" ) << QStringLiteral( "240" ) << QStringLiteral( "1" ) << QStringLiteral( "3" ) << QStringLiteral( "2" ) << QStringLiteral( "5" ); expectedRows.append( row ); row.clear(); - row << "Jet" << "180" << "3" << "1" << "0" << "1"; + row << QStringLiteral( "Jet" ) << QStringLiteral( "180" ) << QStringLiteral( "3" ) << QStringLiteral( "1" ) << QStringLiteral( "0" ) << QStringLiteral( "1" ); expectedRows.append( row ); //retrieve rows and check @@ -329,8 +329,8 @@ void TestQgsComposerTableV2::attributeTableVisibleOnly() void TestQgsComposerTableV2::attributeTableRender() { mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); - QgsCompositionChecker checker( "composerattributetable_render", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_render" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport ); QVERIFY( result ); } @@ -339,8 +339,8 @@ void TestQgsComposerTableV2::manualColumnWidth() { mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); mComposerAttributeTable->columns()->at( 0 )->setWidth( 5 ); - QgsCompositionChecker checker( "composerattributetable_columnwidth", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_columnwidth" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport, 0 ); mComposerAttributeTable->columns()->at( 0 )->setWidth( 0 ); QVERIFY( result ); @@ -350,23 +350,23 @@ void TestQgsComposerTableV2::attributeTableEmpty() { mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); //hide all features from table - mComposerAttributeTable->setFeatureFilter( QString( "1=2" ) ); + mComposerAttributeTable->setFeatureFilter( QStringLiteral( "1=2" ) ); mComposerAttributeTable->setFilterFeatures( true ); mComposerAttributeTable->setEmptyTableBehaviour( QgsComposerTableV2::HeadersOnly ); - QgsCompositionChecker checker( "composerattributetable_headersonly", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_headersonly" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); QVERIFY( checker.testComposition( mReport, 0 ) ); mComposerAttributeTable->setEmptyTableBehaviour( QgsComposerTableV2::HideTable ); - QgsCompositionChecker checker2( "composerattributetable_hidetable", mComposition ); - checker2.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker2( QStringLiteral( "composerattributetable_hidetable" ), mComposition ); + checker2.setControlPathPrefix( QStringLiteral( "composer_table" ) ); QVERIFY( checker2.testComposition( mReport, 0 ) ); mComposerAttributeTable->setEmptyTableBehaviour( QgsComposerTableV2::ShowMessage ); - mComposerAttributeTable->setEmptyTableMessage( "no rows" ); - QgsCompositionChecker checker3( "composerattributetable_showmessage", mComposition ); - checker3.setControlPathPrefix( "composer_table" ); + mComposerAttributeTable->setEmptyTableMessage( QStringLiteral( "no rows" ) ); + QgsCompositionChecker checker3( QStringLiteral( "composerattributetable_showmessage" ), mComposition ); + checker3.setControlPathPrefix( QStringLiteral( "composer_table" ) ); QVERIFY( checker3.testComposition( mReport, 0 ) ); mComposerAttributeTable->setFilterFeatures( false ); @@ -376,8 +376,8 @@ void TestQgsComposerTableV2::showEmptyRows() { mComposerAttributeTable->setMaximumNumberOfFeatures( 3 ); mComposerAttributeTable->setShowEmptyRows( true ); - QgsCompositionChecker checker( "composerattributetable_drawempty", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_drawempty" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); QVERIFY( checker.testComposition( mReport, 0 ) ); mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); mComposerAttributeTable->setShowEmptyRows( false ); @@ -434,10 +434,10 @@ void TestQgsComposerTableV2::attributeTableAtlasSource() //setup atlas QgsVectorLayer* vectorLayer; - QFileInfo vectorFileInfo( QString( TEST_DATA_DIR ) + "/points.shp" ); + QFileInfo vectorFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/points.shp" ); vectorLayer = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayer( vectorLayer ); mComposition->atlasComposition().setCoverageLayer( vectorLayer ); mComposition->atlasComposition().setEnabled( true ); @@ -490,10 +490,10 @@ void TestQgsComposerTableV2::attributeTableAtlasSource() void TestQgsComposerTableV2::attributeTableRelationSource() { - QFileInfo vectorFileInfo( QString( TEST_DATA_DIR ) + "/points_relations.shp" ); + QFileInfo vectorFileInfo( QStringLiteral( TEST_DATA_DIR ) + "/points_relations.shp" ); QgsVectorLayer* atlasLayer = new QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), - "ogr" ); + QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayer( atlasLayer ); @@ -503,10 +503,10 @@ void TestQgsComposerTableV2::attributeTableRelationSource() //create a relation QgsRelation relation; - relation.setRelationId( "testrelation" ); + relation.setRelationId( QStringLiteral( "testrelation" ) ); relation.setReferencedLayer( atlasLayer->id() ); relation.setReferencingLayer( mVectorLayer->id() ); - relation.addFieldPair( "Class", "Class" ); + relation.addFieldPair( QStringLiteral( "Class" ), QStringLiteral( "Class" ) ); QgsProject::instance()->relationManager()->addRelation( relation ); QgsComposerAttributeTableV2* table = new QgsComposerAttributeTableV2( mComposition, false ); @@ -578,14 +578,14 @@ void TestQgsComposerTableV2::contentsContainsRow() { QgsComposerTableContents testContents; QgsComposerTableRow row1; - row1 << QVariant( QString( "string 1" ) ) << QVariant( 2 ) << QVariant( 1.5 ) << QVariant( QString( "string 2" ) ); + row1 << QVariant( QStringLiteral( "string 1" ) ) << QVariant( 2 ) << QVariant( 1.5 ) << QVariant( QStringLiteral( "string 2" ) ); QgsComposerTableRow row2; - row2 << QVariant( QString( "string 2" ) ) << QVariant( 2 ) << QVariant( 1.5 ) << QVariant( QString( "string 2" ) ); + row2 << QVariant( QStringLiteral( "string 2" ) ) << QVariant( 2 ) << QVariant( 1.5 ) << QVariant( QStringLiteral( "string 2" ) ); //same as row1 QgsComposerTableRow row3; - row3 << QVariant( QString( "string 1" ) ) << QVariant( 2 ) << QVariant( 1.5 ) << QVariant( QString( "string 2" ) ); + row3 << QVariant( QStringLiteral( "string 1" ) ) << QVariant( 2 ) << QVariant( 1.5 ) << QVariant( QStringLiteral( "string 2" ) ); QgsComposerTableRow row4; - row4 << QVariant( QString( "string 1" ) ) << QVariant( 2 ) << QVariant( 1.7 ) << QVariant( QString( "string 2" ) ); + row4 << QVariant( QStringLiteral( "string 1" ) ) << QVariant( 2 ) << QVariant( 1.7 ) << QVariant( QStringLiteral( "string 2" ) ); testContents << row1; testContents << row2; @@ -598,24 +598,24 @@ void TestQgsComposerTableV2::contentsContainsRow() void TestQgsComposerTableV2::removeDuplicates() { - QgsVectorLayer* dupesLayer = new QgsVectorLayer( "Point?field=col1:integer&field=col2:integer&field=col3:integer", "dupes", "memory" ); + QgsVectorLayer* dupesLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer&field=col2:integer&field=col3:integer" ), QStringLiteral( "dupes" ), QStringLiteral( "memory" ) ); QVERIFY( dupesLayer->isValid() ); QgsFeature f1( dupesLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", 1 ); - f1.setAttribute( "col2", 1 ); - f1.setAttribute( "col3", 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 1 ); + f1.setAttribute( QStringLiteral( "col2" ), 1 ); + f1.setAttribute( QStringLiteral( "col3" ), 1 ); QgsFeature f2( dupesLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", 1 ); - f2.setAttribute( "col2", 2 ); - f2.setAttribute( "col3", 2 ); + f2.setAttribute( QStringLiteral( "col1" ), 1 ); + f2.setAttribute( QStringLiteral( "col2" ), 2 ); + f2.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature f3( dupesLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", 1 ); - f3.setAttribute( "col2", 2 ); - f3.setAttribute( "col3", 3 ); + f3.setAttribute( QStringLiteral( "col1" ), 1 ); + f3.setAttribute( QStringLiteral( "col2" ), 2 ); + f3.setAttribute( QStringLiteral( "col3" ), 3 ); QgsFeature f4( dupesLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", 1 ); - f4.setAttribute( "col2", 1 ); - f4.setAttribute( "col3", 1 ); + f4.setAttribute( QStringLiteral( "col1" ), 1 ); + f4.setAttribute( QStringLiteral( "col2" ), 1 ); + f4.setAttribute( QStringLiteral( "col3" ), 1 ); dupesLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); QgsComposerAttributeTableV2* table = new QgsComposerAttributeTableV2( mComposition, false ); @@ -645,32 +645,32 @@ void TestQgsComposerTableV2::removeDuplicates() void TestQgsComposerTableV2::multiLineText() { - QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string&field=col2:string&field=col3:string" ), QStringLiteral( "multiline" ), QStringLiteral( "memory" ) ); QVERIFY( multiLineLayer->isValid() ); QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", "multiline\nstring" ); - f1.setAttribute( "col2", "singleline string" ); - f1.setAttribute( "col3", "singleline" ); + f1.setAttribute( QStringLiteral( "col1" ), "multiline\nstring" ); + f1.setAttribute( QStringLiteral( "col2" ), "singleline string" ); + f1.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", "singleline string" ); - f2.setAttribute( "col2", "multiline\nstring" ); - f2.setAttribute( "col3", "singleline" ); + f2.setAttribute( QStringLiteral( "col1" ), "singleline string" ); + f2.setAttribute( QStringLiteral( "col2" ), "multiline\nstring" ); + f2.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", "singleline" ); - f3.setAttribute( "col2", "singleline" ); - f3.setAttribute( "col3", "multiline\nstring" ); + f3.setAttribute( QStringLiteral( "col1" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col2" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col3" ), "multiline\nstring" ); QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", "long triple\nline\nstring" ); - f4.setAttribute( "col2", "double\nlinestring" ); - f4.setAttribute( "col3", "singleline" ); + f4.setAttribute( QStringLiteral( "col1" ), "long triple\nline\nstring" ); + f4.setAttribute( QStringLiteral( "col2" ), "double\nlinestring" ); + f4.setAttribute( QStringLiteral( "col3" ), "singleline" ); multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); mFrame2->setSceneRect( QRectF( 5, 40, 100, 90 ) ); mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); mComposerAttributeTable->setVectorLayer( multiLineLayer ); - QgsCompositionChecker checker( "composerattributetable_multiline", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_multiline" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport ); QVERIFY( result ); @@ -679,24 +679,24 @@ void TestQgsComposerTableV2::multiLineText() void TestQgsComposerTableV2::horizontalGrid() { - QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string&field=col2:string&field=col3:string" ), QStringLiteral( "multiline" ), QStringLiteral( "memory" ) ); QVERIFY( multiLineLayer->isValid() ); QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", "multiline\nstring" ); - f1.setAttribute( "col2", "singleline string" ); - f1.setAttribute( "col3", "singleline" ); + f1.setAttribute( QStringLiteral( "col1" ), "multiline\nstring" ); + f1.setAttribute( QStringLiteral( "col2" ), "singleline string" ); + f1.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", "singleline string" ); - f2.setAttribute( "col2", "multiline\nstring" ); - f2.setAttribute( "col3", "singleline" ); + f2.setAttribute( QStringLiteral( "col1" ), "singleline string" ); + f2.setAttribute( QStringLiteral( "col2" ), "multiline\nstring" ); + f2.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", "singleline" ); - f3.setAttribute( "col2", "singleline" ); - f3.setAttribute( "col3", "multiline\nstring" ); + f3.setAttribute( QStringLiteral( "col1" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col2" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col3" ), "multiline\nstring" ); QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", "long triple\nline\nstring" ); - f4.setAttribute( "col2", "double\nlinestring" ); - f4.setAttribute( "col3", "singleline" ); + f4.setAttribute( QStringLiteral( "col1" ), "long triple\nline\nstring" ); + f4.setAttribute( QStringLiteral( "col2" ), "double\nlinestring" ); + f4.setAttribute( QStringLiteral( "col3" ), "singleline" ); multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); mFrame1->setFrameEnabled( false ); @@ -708,8 +708,8 @@ void TestQgsComposerTableV2::horizontalGrid() mComposerAttributeTable->setHorizontalGrid( true ); mComposerAttributeTable->setVerticalGrid( false ); mComposerAttributeTable->setVectorLayer( multiLineLayer ); - QgsCompositionChecker checker( "composerattributetable_horizontalgrid", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_horizontalgrid" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport ); QVERIFY( result ); @@ -718,24 +718,24 @@ void TestQgsComposerTableV2::horizontalGrid() void TestQgsComposerTableV2::verticalGrid() { - QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string&field=col2:string&field=col3:string" ), QStringLiteral( "multiline" ), QStringLiteral( "memory" ) ); QVERIFY( multiLineLayer->isValid() ); QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", "multiline\nstring" ); - f1.setAttribute( "col2", "singleline string" ); - f1.setAttribute( "col3", "singleline" ); + f1.setAttribute( QStringLiteral( "col1" ), "multiline\nstring" ); + f1.setAttribute( QStringLiteral( "col2" ), "singleline string" ); + f1.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", "singleline string" ); - f2.setAttribute( "col2", "multiline\nstring" ); - f2.setAttribute( "col3", "singleline" ); + f2.setAttribute( QStringLiteral( "col1" ), "singleline string" ); + f2.setAttribute( QStringLiteral( "col2" ), "multiline\nstring" ); + f2.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", "singleline" ); - f3.setAttribute( "col2", "singleline" ); - f3.setAttribute( "col3", "multiline\nstring" ); + f3.setAttribute( QStringLiteral( "col1" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col2" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col3" ), "multiline\nstring" ); QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", "long triple\nline\nstring" ); - f4.setAttribute( "col2", "double\nlinestring" ); - f4.setAttribute( "col3", "singleline" ); + f4.setAttribute( QStringLiteral( "col1" ), "long triple\nline\nstring" ); + f4.setAttribute( QStringLiteral( "col2" ), "double\nlinestring" ); + f4.setAttribute( QStringLiteral( "col3" ), "singleline" ); multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); mFrame1->setFrameEnabled( false ); @@ -747,8 +747,8 @@ void TestQgsComposerTableV2::verticalGrid() mComposerAttributeTable->setHorizontalGrid( false ); mComposerAttributeTable->setVerticalGrid( true ); mComposerAttributeTable->setVectorLayer( multiLineLayer ); - QgsCompositionChecker checker( "composerattributetable_verticalgrid", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_verticalgrid" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport ); QVERIFY( result ); @@ -757,24 +757,24 @@ void TestQgsComposerTableV2::verticalGrid() void TestQgsComposerTableV2::align() { - QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string&field=col2:string&field=col3:string" ), QStringLiteral( "multiline" ), QStringLiteral( "memory" ) ); QVERIFY( multiLineLayer->isValid() ); QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", "multiline\nstring" ); - f1.setAttribute( "col2", "singleline string" ); - f1.setAttribute( "col3", "singleline" ); + f1.setAttribute( QStringLiteral( "col1" ), "multiline\nstring" ); + f1.setAttribute( QStringLiteral( "col2" ), "singleline string" ); + f1.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", "singleline string" ); - f2.setAttribute( "col2", "multiline\nstring" ); - f2.setAttribute( "col3", "singleline" ); + f2.setAttribute( QStringLiteral( "col1" ), "singleline string" ); + f2.setAttribute( QStringLiteral( "col2" ), "multiline\nstring" ); + f2.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", "singleline" ); - f3.setAttribute( "col2", "singleline" ); - f3.setAttribute( "col3", "multiline\nstring" ); + f3.setAttribute( QStringLiteral( "col1" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col2" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col3" ), "multiline\nstring" ); QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", "long triple\nline\nstring" ); - f4.setAttribute( "col2", "double\nlinestring" ); - f4.setAttribute( "col3", "singleline" ); + f4.setAttribute( QStringLiteral( "col1" ), "long triple\nline\nstring" ); + f4.setAttribute( QStringLiteral( "col2" ), "double\nlinestring" ); + f4.setAttribute( QStringLiteral( "col3" ), "singleline" ); multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); mFrame2->setSceneRect( QRectF( 5, 40, 100, 90 ) ); @@ -788,8 +788,8 @@ void TestQgsComposerTableV2::align() mComposerAttributeTable->columns()->at( 1 )->setVAlignment( Qt::AlignVCenter ); mComposerAttributeTable->columns()->at( 2 )->setHAlignment( Qt::AlignRight ); mComposerAttributeTable->columns()->at( 2 )->setVAlignment( Qt::AlignBottom ); - QgsCompositionChecker checker( "composerattributetable_align", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_align" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport ); QVERIFY( result ); @@ -798,21 +798,21 @@ void TestQgsComposerTableV2::align() void TestQgsComposerTableV2::wrapChar() { - QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string&field=col2:string&field=col3:string" ), QStringLiteral( "multiline" ), QStringLiteral( "memory" ) ); QVERIFY( multiLineLayer->isValid() ); QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", "multiline\nstring" ); - f1.setAttribute( "col2", "singleline string" ); - f1.setAttribute( "col3", "singleline" ); + f1.setAttribute( QStringLiteral( "col1" ), "multiline\nstring" ); + f1.setAttribute( QStringLiteral( "col2" ), "singleline string" ); + f1.setAttribute( QStringLiteral( "col3" ), "singleline" ); multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 ); mComposerAttributeTable->setMaximumNumberOfFeatures( 1 ); mComposerAttributeTable->setVectorLayer( multiLineLayer ); - mComposerAttributeTable->setWrapString( "in" ); + mComposerAttributeTable->setWrapString( QStringLiteral( "in" ) ); QList expectedRows; QStringList row; - row << "multil\ne\nstr\ng" << "s\nglel\ne str\ng" << "s\nglel\ne"; + row << QStringLiteral( "multil\ne\nstr\ng" ) << QStringLiteral( "s\nglel\ne str\ng" ) << QStringLiteral( "s\nglel\ne" ); expectedRows.append( row ); //retrieve rows and check @@ -821,24 +821,24 @@ void TestQgsComposerTableV2::wrapChar() void TestQgsComposerTableV2::autoWrap() { - QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:string&field=col2:string&field=col3:string" ), QStringLiteral( "multiline" ), QStringLiteral( "memory" ) ); QVERIFY( multiLineLayer->isValid() ); QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", "long multiline\nstring" ); - f1.setAttribute( "col2", "singleline string" ); - f1.setAttribute( "col3", "singleline" ); + f1.setAttribute( QStringLiteral( "col1" ), "long multiline\nstring" ); + f1.setAttribute( QStringLiteral( "col2" ), "singleline string" ); + f1.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", "singleline string" ); - f2.setAttribute( "col2", "multiline\nstring" ); - f2.setAttribute( "col3", "singleline" ); + f2.setAttribute( QStringLiteral( "col1" ), "singleline string" ); + f2.setAttribute( QStringLiteral( "col2" ), "multiline\nstring" ); + f2.setAttribute( QStringLiteral( "col3" ), "singleline" ); QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", "singleline" ); - f3.setAttribute( "col2", "singleline" ); - f3.setAttribute( "col3", "multiline\nstring" ); + f3.setAttribute( QStringLiteral( "col1" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col2" ), "singleline" ); + f3.setAttribute( QStringLiteral( "col3" ), "multiline\nstring" ); QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", "a bit long triple line string" ); - f4.setAttribute( "col2", "double toolongtofitononeline string with some more lines on the end andanotherreallylongline" ); - f4.setAttribute( "col3", "singleline" ); + f4.setAttribute( QStringLiteral( "col1" ), "a bit long triple line string" ); + f4.setAttribute( QStringLiteral( "col2" ), "double toolongtofitononeline string with some more lines on the end andanotherreallylongline" ); + f4.setAttribute( QStringLiteral( "col3" ), "singleline" ); multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); mFrame2->setSceneRect( QRectF( 5, 40, 100, 90 ) ); @@ -849,8 +849,8 @@ void TestQgsComposerTableV2::autoWrap() mComposerAttributeTable->columns()->at( 0 )->setWidth( 25 ); mComposerAttributeTable->columns()->at( 1 )->setWidth( 25 ); - QgsCompositionChecker checker( "composerattributetable_autowrap", mComposition ); - checker.setControlPathPrefix( "composer_table" ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_autowrap" ), mComposition ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); bool result = checker.testComposition( mReport, 0 ); mComposerAttributeTable->columns()->at( 0 )->setWidth( 0 ); QVERIFY( result ); @@ -866,11 +866,11 @@ void TestQgsComposerTableV2::cellStyles() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); //test writing with no node - QDomElement node = doc.createElement( "style" ); + QDomElement node = doc.createElement( QStringLiteral( "style" ) ); QVERIFY( original.writeXml( node, doc ) ); //read from xml @@ -895,7 +895,7 @@ void TestQgsComposerTableV2::cellStyles() originalTable.setCellStyle( QgsComposerTableV2::LastColumn, style2 ); //write to XML - QDomElement tableElement = doc.createElement( "table" ); + QDomElement tableElement = doc.createElement( QStringLiteral( "table" ) ); QVERIFY( originalTable.writeXml( tableElement, doc, true ) ); //read from XML @@ -1067,9 +1067,9 @@ void TestQgsComposerTableV2::cellStylesRender() style.cellBackgroundColor = QColor( 50, 200, 200, 200 ); mComposerAttributeTable->setCellStyle( QgsComposerTableV2::LastRow, style ); - QgsCompositionChecker checker( "composerattributetable_cellstyle", mComposition ); + QgsCompositionChecker checker( QStringLiteral( "composerattributetable_cellstyle" ), mComposition ); checker.setColorTolerance( 10 ); - checker.setControlPathPrefix( "composer_table" ); + checker.setControlPathPrefix( QStringLiteral( "composer_table" ) ); QVERIFY( checker.testComposition( mReport, 0 ) ); mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); mComposerAttributeTable->setShowEmptyRows( false ); diff --git a/tests/src/core/testqgscomposerutils.cpp b/tests/src/core/testqgscomposerutils.cpp index 2994777bb2e7..4b8fb622f7a9 100644 --- a/tests/src/core/testqgscomposerutils.cpp +++ b/tests/src/core/testqgscomposerutils.cpp @@ -86,10 +86,10 @@ void TestQgsComposerUtils::initTestCase() mComposition = new QgsComposition( *mMapSettings ); mComposition->setPaperSize( 297, 210 ); //A4 landscape - mReport = "

                                                                                                                                                                                    Composer Utils Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composer Utils Tests

                                                                                                                                                                                    \n" ); - QgsFontUtils::loadStandardTestFonts( QStringList() << "Oblique" ); - mTestFont = QgsFontUtils::getStandardTestFont( "Oblique " ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Oblique" ) ); + mTestFont = QgsFontUtils::getStandardTestFont( QStringLiteral( "Oblique " ) ); mTestFont.setItalic( true ); } @@ -381,15 +381,15 @@ void TestQgsComposerUtils::decodePaperOrientation() { QgsComposition::PaperOrientation orientation; bool ok = false; - orientation = QgsComposerUtils::decodePaperOrientation( "bad string", ok ); + orientation = QgsComposerUtils::decodePaperOrientation( QStringLiteral( "bad string" ), ok ); QVERIFY( !ok ); QCOMPARE( orientation, QgsComposition::Landscape ); //should default to landscape ok = false; - orientation = QgsComposerUtils::decodePaperOrientation( "portrait", ok ); + orientation = QgsComposerUtils::decodePaperOrientation( QStringLiteral( "portrait" ), ok ); QVERIFY( ok ); QCOMPARE( orientation, QgsComposition::Portrait ); ok = false; - orientation = QgsComposerUtils::decodePaperOrientation( "LANDSCAPE", ok ); + orientation = QgsComposerUtils::decodePaperOrientation( QStringLiteral( "LANDSCAPE" ), ok ); QVERIFY( ok ); QCOMPARE( orientation, QgsComposition::Landscape ); } @@ -421,17 +421,17 @@ void TestQgsComposerUtils::readDataDefinedProperty() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement rootNode = doc.createElement( "qgis" ); - QDomElement itemElem = doc.createElement( "item" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); + QDomElement itemElem = doc.createElement( QStringLiteral( "item" ) ); //dd element - QDomElement ddElem = doc.createElement( "dataDefinedProperty" ); - ddElem.setAttribute( "active", "true" ); - ddElem.setAttribute( "useExpr", "true" ); - ddElem.setAttribute( "expr", "test expression" ); - ddElem.setAttribute( "field", "test field" ); + QDomElement ddElem = doc.createElement( QStringLiteral( "dataDefinedProperty" ) ); + ddElem.setAttribute( QStringLiteral( "active" ), QStringLiteral( "true" ) ); + ddElem.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "true" ) ); + ddElem.setAttribute( QStringLiteral( "expr" ), QStringLiteral( "test expression" ) ); + ddElem.setAttribute( QStringLiteral( "field" ), QStringLiteral( "test field" ) ); itemElem.appendChild( ddElem ); rootNode.appendChild( itemElem ); @@ -453,9 +453,9 @@ void TestQgsComposerUtils::readDataDefinedProperty() QCOMPARE(( dataDefinedProperties.value( QgsComposerObject::TestProperty ) )->field(), QString( "test field" ) ); //reading false parameters - QDomElement ddElem2 = doc.createElement( "dataDefinedProperty2" ); - ddElem2.setAttribute( "active", "false" ); - ddElem2.setAttribute( "useExpr", "false" ); + QDomElement ddElem2 = doc.createElement( QStringLiteral( "dataDefinedProperty2" ) ); + ddElem2.setAttribute( QStringLiteral( "active" ), QStringLiteral( "false" ) ); + ddElem2.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "false" ) ); itemElem.appendChild( ddElem2 ); QgsComposerUtils::readDataDefinedProperty( QgsComposerObject::TestProperty, ddElem2, &dataDefinedProperties ); QCOMPARE( dataDefinedProperties.count(), 1 ); @@ -473,38 +473,38 @@ void TestQgsComposerUtils::readDataDefinedPropertyMap() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement rootNode = doc.createElement( "qgis" ); - QDomElement itemElem = doc.createElement( "item" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); + QDomElement itemElem = doc.createElement( QStringLiteral( "item" ) ); //dd elements - QDomElement ddElem = doc.createElement( "dataDefinedProperty" ); - ddElem.setAttribute( "active", "true" ); - ddElem.setAttribute( "useExpr", "true" ); - ddElem.setAttribute( "expr", "test expression" ); - ddElem.setAttribute( "field", "test field" ); + QDomElement ddElem = doc.createElement( QStringLiteral( "dataDefinedProperty" ) ); + ddElem.setAttribute( QStringLiteral( "active" ), QStringLiteral( "true" ) ); + ddElem.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "true" ) ); + ddElem.setAttribute( QStringLiteral( "expr" ), QStringLiteral( "test expression" ) ); + ddElem.setAttribute( QStringLiteral( "field" ), QStringLiteral( "test field" ) ); itemElem.appendChild( ddElem ); - QDomElement ddElem2 = doc.createElement( "dataDefinedProperty2" ); - ddElem2.setAttribute( "active", "false" ); - ddElem2.setAttribute( "useExpr", "false" ); - ddElem2.setAttribute( "expr", "test expression 2" ); - ddElem2.setAttribute( "field", "test field 2" ); + QDomElement ddElem2 = doc.createElement( QStringLiteral( "dataDefinedProperty2" ) ); + ddElem2.setAttribute( QStringLiteral( "active" ), QStringLiteral( "false" ) ); + ddElem2.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "false" ) ); + ddElem2.setAttribute( QStringLiteral( "expr" ), QStringLiteral( "test expression 2" ) ); + ddElem2.setAttribute( QStringLiteral( "field" ), QStringLiteral( "test field 2" ) ); itemElem.appendChild( ddElem2 ); - QDomElement ddElem3 = doc.createElement( "dataDefinedProperty3" ); - ddElem3.setAttribute( "active", "true" ); - ddElem3.setAttribute( "useExpr", "false" ); - ddElem3.setAttribute( "expr", "test expression 3" ); - ddElem3.setAttribute( "field", "test field 3" ); + QDomElement ddElem3 = doc.createElement( QStringLiteral( "dataDefinedProperty3" ) ); + ddElem3.setAttribute( QStringLiteral( "active" ), QStringLiteral( "true" ) ); + ddElem3.setAttribute( QStringLiteral( "useExpr" ), QStringLiteral( "false" ) ); + ddElem3.setAttribute( QStringLiteral( "expr" ), QStringLiteral( "test expression 3" ) ); + ddElem3.setAttribute( QStringLiteral( "field" ), QStringLiteral( "test field 3" ) ); itemElem.appendChild( ddElem3 ); rootNode.appendChild( itemElem ); //try reading dd elements QMap< QgsComposerObject::DataDefinedProperty, QgsDataDefined* > dataDefinedProperties; QMap dataDefinedNames; - dataDefinedNames[ QgsComposerObject::BlendMode ] = QString( "dataDefinedProperty" ); - dataDefinedNames[ QgsComposerObject::Transparency ] = QString( "dataDefinedProperty2" ); - dataDefinedNames[ QgsComposerObject::TestProperty ] = QString( "dataDefinedProperty3" ); + dataDefinedNames[ QgsComposerObject::BlendMode ] = QStringLiteral( "dataDefinedProperty" ); + dataDefinedNames[ QgsComposerObject::Transparency ] = QStringLiteral( "dataDefinedProperty2" ); + dataDefinedNames[ QgsComposerObject::TestProperty ] = QStringLiteral( "dataDefinedProperty3" ); QgsComposerUtils::readDataDefinedPropertyMap( itemElem, &dataDefinedNames, &dataDefinedProperties ); //check returned values @@ -530,26 +530,26 @@ void TestQgsComposerUtils::writeDataDefinedPropertyMap() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement itemElem = doc.createElement( "item" ); + QDomElement itemElem = doc.createElement( QStringLiteral( "item" ) ); //create some data defined properties QMap dataDefinedNames; - dataDefinedNames[ QgsComposerObject::BlendMode ] = QString( "dataDefinedProperty" ); - dataDefinedNames[ QgsComposerObject::Transparency ] = QString( "dataDefinedProperty2" ); - dataDefinedNames[ QgsComposerObject::TestProperty ] = QString( "dataDefinedProperty3" ); + dataDefinedNames[ QgsComposerObject::BlendMode ] = QStringLiteral( "dataDefinedProperty" ); + dataDefinedNames[ QgsComposerObject::Transparency ] = QStringLiteral( "dataDefinedProperty2" ); + dataDefinedNames[ QgsComposerObject::TestProperty ] = QStringLiteral( "dataDefinedProperty3" ); QMap< QgsComposerObject::DataDefinedProperty, QgsDataDefined* > dataDefinedProperties; - dataDefinedProperties[ QgsComposerObject::BlendMode ] = new QgsDataDefined( true, true, QString( "expression 1" ), QString( "field 1" ) ); - dataDefinedProperties[ QgsComposerObject::Transparency ] = new QgsDataDefined( false, false, QString( "expression 2" ), QString( "field 2" ) ); - dataDefinedProperties[ QgsComposerObject::TestProperty ] = new QgsDataDefined( false, true, QString( "expression 3" ), QString( "field 3" ) ); + dataDefinedProperties[ QgsComposerObject::BlendMode ] = new QgsDataDefined( true, true, QStringLiteral( "expression 1" ), QStringLiteral( "field 1" ) ); + dataDefinedProperties[ QgsComposerObject::Transparency ] = new QgsDataDefined( false, false, QStringLiteral( "expression 2" ), QStringLiteral( "field 2" ) ); + dataDefinedProperties[ QgsComposerObject::TestProperty ] = new QgsDataDefined( false, true, QStringLiteral( "expression 3" ), QStringLiteral( "field 3" ) ); //write the property map QgsComposerUtils::writeDataDefinedPropertyMap( itemElem, doc, &dataDefinedNames, &dataDefinedProperties ); //now check it - QDomNodeList dd1NodeList = itemElem.elementsByTagName( "dataDefinedProperty" ); + QDomNodeList dd1NodeList = itemElem.elementsByTagName( QStringLiteral( "dataDefinedProperty" ) ); QCOMPARE( dd1NodeList.count(), 1 ); QDomElement dd1Elem = dd1NodeList.at( 0 ).toElement(); QCOMPARE( dd1Elem.attribute( "active", "bad" ), QString( "true" ) ); @@ -557,7 +557,7 @@ void TestQgsComposerUtils::writeDataDefinedPropertyMap() QCOMPARE( dd1Elem.attribute( "expr", "bad" ), QString( "expression 1" ) ); QCOMPARE( dd1Elem.attribute( "field", "bad" ), QString( "field 1" ) ); - QDomNodeList dd2NodeList = itemElem.elementsByTagName( "dataDefinedProperty2" ); + QDomNodeList dd2NodeList = itemElem.elementsByTagName( QStringLiteral( "dataDefinedProperty2" ) ); QCOMPARE( dd2NodeList.count(), 1 ); QDomElement dd2Elem = dd2NodeList.at( 0 ).toElement(); QCOMPARE( dd2Elem.attribute( "active", "bad" ), QString( "false" ) ); @@ -565,7 +565,7 @@ void TestQgsComposerUtils::writeDataDefinedPropertyMap() QCOMPARE( dd2Elem.attribute( "expr", "bad" ), QString( "expression 2" ) ); QCOMPARE( dd2Elem.attribute( "field", "bad" ), QString( "field 2" ) ); - QDomNodeList dd3NodeList = itemElem.elementsByTagName( "dataDefinedProperty3" ); + QDomNodeList dd3NodeList = itemElem.elementsByTagName( QStringLiteral( "dataDefinedProperty3" ) ); QCOMPARE( dd3NodeList.count(), 1 ); QDomElement dd3Elem = dd3NodeList.at( 0 ).toElement(); QCOMPARE( dd3Elem.attribute( "active", "bad" ), QString( "false" ) ); @@ -639,7 +639,7 @@ void TestQgsComposerUtils::textHeightMM() void TestQgsComposerUtils::drawTextPos() { //test drawing with no painter - QgsComposerUtils::drawText( 0, QPointF( 5, 15 ), QString( "Abc123" ), mTestFont ); + QgsComposerUtils::drawText( 0, QPointF( 5, 15 ), QStringLiteral( "Abc123" ), mTestFont ); //test drawing text on to image mTestFont.setPointSize( 48 ); @@ -647,7 +647,7 @@ void TestQgsComposerUtils::drawTextPos() testImage.fill( qRgb( 152, 219, 249 ) ); QPainter testPainter; testPainter.begin( &testImage ); - QgsComposerUtils::drawText( &testPainter, QPointF( 5, 15 ), QString( "Abc123" ), mTestFont, Qt::white ); + QgsComposerUtils::drawText( &testPainter, QPointF( 5, 15 ), QStringLiteral( "Abc123" ), mTestFont, Qt::white ); testPainter.end(); QVERIFY( renderCheck( "composerutils_drawtext_pos", testImage, 100 ) ); @@ -656,7 +656,7 @@ void TestQgsComposerUtils::drawTextPos() testImage.fill( qRgb( 152, 219, 249 ) ); testPainter.begin( &testImage ); testPainter.setPen( QPen( Qt::green ) ); - QgsComposerUtils::drawText( &testPainter, QPointF( 5, 15 ), QString( "Abc123" ), mTestFont ); + QgsComposerUtils::drawText( &testPainter, QPointF( 5, 15 ), QStringLiteral( "Abc123" ), mTestFont ); testPainter.end(); QVERIFY( renderCheck( "composerutils_drawtext_posnocolor", testImage, 100 ) ); } @@ -664,7 +664,7 @@ void TestQgsComposerUtils::drawTextPos() void TestQgsComposerUtils::drawTextRect() { //test drawing with no painter - QgsComposerUtils::drawText( 0, QRectF( 5, 15, 200, 50 ), QString( "Abc123" ), mTestFont ); + QgsComposerUtils::drawText( 0, QRectF( 5, 15, 200, 50 ), QStringLiteral( "Abc123" ), mTestFont ); //test drawing text on to image mTestFont.setPointSize( 48 ); @@ -672,7 +672,7 @@ void TestQgsComposerUtils::drawTextRect() testImage.fill( qRgb( 152, 219, 249 ) ); QPainter testPainter; testPainter.begin( &testImage ); - QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 200, 50 ), QString( "Abc123" ), mTestFont, Qt::white ); + QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 200, 50 ), QStringLiteral( "Abc123" ), mTestFont, Qt::white ); testPainter.end(); QVERIFY( renderCheck( "composerutils_drawtext_rect", testImage, 100 ) ); @@ -681,21 +681,21 @@ void TestQgsComposerUtils::drawTextRect() testImage.fill( qRgb( 152, 219, 249 ) ); testPainter.begin( &testImage ); testPainter.setPen( QPen( Qt::green ) ); - QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 200, 50 ), QString( "Abc123" ), mTestFont ); + QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 200, 50 ), QStringLiteral( "Abc123" ), mTestFont ); testPainter.end(); QVERIFY( renderCheck( "composerutils_drawtext_rectnocolor", testImage, 100 ) ); //test alignment settings testImage.fill( qRgb( 152, 219, 249 ) ); testPainter.begin( &testImage ); - QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 200, 50 ), QString( "Abc123" ), mTestFont, Qt::black, Qt::AlignRight, Qt::AlignBottom ); + QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 200, 50 ), QStringLiteral( "Abc123" ), mTestFont, Qt::black, Qt::AlignRight, Qt::AlignBottom ); testPainter.end(); QVERIFY( renderCheck( "composerutils_drawtext_rectalign", testImage, 100 ) ); //test extra flags - render without clipping testImage.fill( qRgb( 152, 219, 249 ) ); testPainter.begin( &testImage ); - QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 20, 50 ), QString( "Abc123" ), mTestFont, Qt::white, Qt::AlignLeft, Qt::AlignTop, Qt::TextDontClip ); + QgsComposerUtils::drawText( &testPainter, QRectF( 5, 15, 20, 50 ), QStringLiteral( "Abc123" ), mTestFont, Qt::white, Qt::AlignLeft, Qt::AlignTop, Qt::TextDontClip ); testPainter.end(); QVERIFY( renderCheck( "composerutils_drawtext_rectflag", testImage, 100 ) ); } @@ -707,7 +707,7 @@ bool TestQgsComposerUtils::renderCheck( const QString& testName, QImage &image, QString myFileName = myTmpDir + testName + ".png"; image.save( myFileName, "PNG" ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "composer_utils" ); + myChecker.setControlPathPrefix( QStringLiteral( "composer_utils" ) ); myChecker.setControlName( "expected_" + testName ); myChecker.setRenderedImage( myFileName ); bool myResultFlag = myChecker.compareImages( testName, mismatchCount ); diff --git a/tests/src/core/testqgscomposition.cpp b/tests/src/core/testqgscomposition.cpp index bb72ce520df6..12ee7a611b62 100644 --- a/tests/src/core/testqgscomposition.cpp +++ b/tests/src/core/testqgscomposition.cpp @@ -82,7 +82,7 @@ void TestQgsComposition::initTestCase() mComposition->setPaperSize( 297, 210 ); //A4 landscape mComposition->setNumPages( 3 ); - mReport = "

                                                                                                                                                                                    Composition Tests

                                                                                                                                                                                    \n"; + mReport = QStringLiteral( "

                                                                                                                                                                                    Composition Tests

                                                                                                                                                                                    \n" ); } @@ -213,21 +213,21 @@ void TestQgsComposition::shouldExportPage() htmlItem->addFrame( frame2 ); htmlItem->setContentMode( QgsComposerHtml::ManualHtml ); //short content, so frame 2 should be empty - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( mComposition->shouldExportPage( 1 ), true ); QCOMPARE( mComposition->shouldExportPage( 2 ), false ); //long content, so frame 2 should not be empty - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( mComposition->shouldExportPage( 1 ), true ); QCOMPARE( mComposition->shouldExportPage( 2 ), true ); //...and back again... - htmlItem->setHtml( QString( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); + htmlItem->setHtml( QStringLiteral( "

                                                                                                                                                                                    Test manual html

                                                                                                                                                                                    " ) ); htmlItem->loadHtml(); QCOMPARE( mComposition->shouldExportPage( 1 ), true ); @@ -273,20 +273,20 @@ void TestQgsComposition::customProperties() QCOMPARE( composition->customProperty( "noprop", "defaultval" ).toString(), QString( "defaultval" ) ); QVERIFY( composition->customProperties().isEmpty() ); - composition->setCustomProperty( "testprop", "testval" ); + composition->setCustomProperty( QStringLiteral( "testprop" ), "testval" ); QCOMPARE( composition->customProperty( "testprop", "defaultval" ).toString(), QString( "testval" ) ); QCOMPARE( composition->customProperties().length(), 1 ); QCOMPARE( composition->customProperties().at( 0 ), QString( "testprop" ) ); //test no crash - composition->removeCustomProperty( "badprop" ); + composition->removeCustomProperty( QStringLiteral( "badprop" ) ); - composition->removeCustomProperty( "testprop" ); + composition->removeCustomProperty( QStringLiteral( "testprop" ) ); QVERIFY( composition->customProperties().isEmpty() ); QCOMPARE( composition->customProperty( "noprop", "defaultval" ).toString(), QString( "defaultval" ) ); - composition->setCustomProperty( "testprop1", "testval1" ); - composition->setCustomProperty( "testprop2", "testval2" ); + composition->setCustomProperty( QStringLiteral( "testprop1" ), "testval1" ); + composition->setCustomProperty( QStringLiteral( "testprop2" ), "testval2" ); QStringList keys = composition->customProperties(); QCOMPARE( keys.length(), 2 ); QVERIFY( keys.contains( "testprop1" ) ); @@ -298,20 +298,20 @@ void TestQgsComposition::customProperties() void TestQgsComposition::writeRetrieveCustomProperties() { QgsComposition* composition = new QgsComposition( *mMapSettings ); - composition->setCustomProperty( "testprop", "testval" ); - composition->setCustomProperty( "testprop2", 5 ); + composition->setCustomProperty( QStringLiteral( "testprop" ), "testval" ); + composition->setCustomProperty( QStringLiteral( "testprop2" ), 5 ); //test writing composition with custom properties QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); - QDomElement rootNode = doc.createElement( "qgis" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); QVERIFY( composition->writeXml( rootNode, doc ) ); //check if composition node was written - QDomNodeList evalNodeList = rootNode.elementsByTagName( "Composition" ); + QDomNodeList evalNodeList = rootNode.elementsByTagName( QStringLiteral( "Composition" ) ); QCOMPARE( evalNodeList.count(), 1 ); QDomElement compositionElem = evalNodeList.at( 0 ).toElement(); @@ -420,9 +420,9 @@ void TestQgsComposition::resizeToContents() //resize to contents, no margin composition->resizePageToContents(); - QgsCompositionChecker checker( "composition_bounds", composition ); + QgsCompositionChecker checker( QStringLiteral( "composition_bounds" ), composition ); checker.setSize( QSize( 774, 641 ) ); - checker.setControlPathPrefix( "composition" ); + checker.setControlPathPrefix( QStringLiteral( "composition" ) ); QVERIFY( checker.testComposition( mReport ) ); delete composition; @@ -461,9 +461,9 @@ void TestQgsComposition::resizeToContentsMargin() //resize to contents, with margin composition->resizePageToContents( 30, 20, 50, 40 ); - QgsCompositionChecker checker( "composition_bounds_margin", composition ); + QgsCompositionChecker checker( QStringLiteral( "composition_bounds_margin" ), composition ); checker.setSize( QSize( 1000, 942 ) ); - checker.setControlPathPrefix( "composition" ); + checker.setControlPathPrefix( QStringLiteral( "composition" ) ); QVERIFY( checker.testComposition( mReport ) ); delete composition; @@ -506,9 +506,9 @@ void TestQgsComposition::resizeToContentsMultiPage() QCOMPARE( composition->numPages(), 1 ); - QgsCompositionChecker checker( "composition_bounds_multipage", composition ); + QgsCompositionChecker checker( QStringLiteral( "composition_bounds_multipage" ), composition ); checker.setSize( QSize( 394, 996 ) ); - checker.setControlPathPrefix( "composition" ); + checker.setControlPathPrefix( QStringLiteral( "composition" ) ); QVERIFY( checker.testComposition( mReport ) ); delete composition; @@ -590,11 +590,11 @@ void TestQgsComposition::variablesEdited() QgsComposition c( ms ); QSignalSpy spyVariablesChanged( &c, SIGNAL( variablesChanged() ) ); - c.setCustomProperty( "not a variable", "1" ); + c.setCustomProperty( QStringLiteral( "not a variable" ), "1" ); QVERIFY( spyVariablesChanged.count() == 0 ); - c.setCustomProperty( "variableNames", "1" ); + c.setCustomProperty( QStringLiteral( "variableNames" ), "1" ); QVERIFY( spyVariablesChanged.count() == 1 ); - c.setCustomProperty( "variableValues", "1" ); + c.setCustomProperty( QStringLiteral( "variableValues" ), "1" ); QVERIFY( spyVariablesChanged.count() == 2 ); } diff --git a/tests/src/core/testqgsconnectionpool.cpp b/tests/src/core/testqgsconnectionpool.cpp index 23121994691f..f5faee75874a 100644 --- a/tests/src/core/testqgsconnectionpool.cpp +++ b/tests/src/core/testqgsconnectionpool.cpp @@ -74,29 +74,29 @@ void TestQgsConnectionPool::layersFromSameDatasetGPX() int nWaypoints = 100000; int nRoutes = 100000; int nRoutePts = 10; - QTemporaryFile testFile( "testXXXXXX.gpx" ); + QTemporaryFile testFile( QStringLiteral( "testXXXXXX.gpx" ) ); testFile.setAutoRemove( false ); testFile.open(); testFile.write( "\n" ); for ( int i = 0; i < nWaypoints; ++i ) { - testFile.write( QString( "\n" ).arg( i ).toLocal8Bit() ); + testFile.write( QStringLiteral( "\n" ).arg( i ).toLocal8Bit() ); } for ( int i = 0; i < nRoutes; ++i ) { testFile.write( "\n" ); for ( int j = 0; j < nRoutePts; ++j ) { - testFile.write( QString( "\n" ).arg( j ).arg( i ).toLocal8Bit() ); + testFile.write( QStringLiteral( "\n" ).arg( j ).arg( i ).toLocal8Bit() ); } testFile.write( "\n" ); } testFile.write( "\n" ); testFile.close(); - QgsVectorLayer* layer1 = new QgsVectorLayer( testFile.fileName() + "|layername=waypoints", "Waypoints", "ogr" ); + QgsVectorLayer* layer1 = new QgsVectorLayer( testFile.fileName() + "|layername=waypoints", QStringLiteral( "Waypoints" ), QStringLiteral( "ogr" ) ); QVERIFY( layer1->isValid() ); - QgsVectorLayer* layer2 = new QgsVectorLayer( testFile.fileName() + "|layername=routes", "Routes", "ogr" ); + QgsVectorLayer* layer2 = new QgsVectorLayer( testFile.fileName() + "|layername=routes", QStringLiteral( "Routes" ), QStringLiteral( "ogr" ) ); QVERIFY( layer2->isValid() ); QList jobs = QList() << ReadJob( layer1 ) << ReadJob( layer2 ); diff --git a/tests/src/core/testqgscoordinatereferencesystem.cpp b/tests/src/core/testqgscoordinatereferencesystem.cpp index 6dad514c071f..4b586254635a 100644 --- a/tests/src/core/testqgscoordinatereferencesystem.cpp +++ b/tests/src/core/testqgscoordinatereferencesystem.cpp @@ -189,41 +189,41 @@ void TestQgsCoordinateReferenceSystem::createFromOgcWmsCrs() //check fails if passed an empty string QVERIFY( !myCrs.createFromOgcWmsCrs( QString() ) ); - myCrs.createFromOgcWmsCrs( "EPSG:4326" ); + myCrs.createFromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); QVERIFY( myCrs.isValid() ); QCOMPARE( myCrs.authid(), QString( "EPSG:4326" ) ); - myCrs.createFromOgcWmsCrs( "i am not a CRS" ); + myCrs.createFromOgcWmsCrs( QStringLiteral( "i am not a CRS" ) ); QVERIFY( !myCrs.isValid() ); } void TestQgsCoordinateReferenceSystem::fromOgcWmsCrs() { - QgsCoordinateReferenceSystem myCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); + QgsCoordinateReferenceSystem myCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); QVERIFY( myCrs.isValid() ); QCOMPARE( myCrs.authid(), QString( "EPSG:4326" ) ); - myCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "not a crs" ); + myCrs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "not a crs" ) ); QVERIFY( !myCrs.isValid() ); } void TestQgsCoordinateReferenceSystem::ogcWmsCrsCache() { // test that crs can be retrieved correctly from cache - QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); + QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); QVERIFY( crs.isValid() ); QCOMPARE( crs.authid(), QString( "EPSG:4326" ) ); QVERIFY( QgsCoordinateReferenceSystem::mOgcCache.contains( "EPSG:4326" ) ); // a second time, so crs is fetched from cache - QgsCoordinateReferenceSystem crs2 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "EPSG:4326" ); + QgsCoordinateReferenceSystem crs2 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); QVERIFY( crs2.isValid() ); QCOMPARE( crs2.authid(), QString( "EPSG:4326" ) ); // invalid - QgsCoordinateReferenceSystem crs3 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "not a CRS" ); + QgsCoordinateReferenceSystem crs3 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "not a CRS" ) ); QVERIFY( !crs3.isValid() ); QVERIFY( QgsCoordinateReferenceSystem::mOgcCache.contains( "not a CRS" ) ); // a second time, so invalid crs is fetched from cache - QgsCoordinateReferenceSystem crs4 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "not a CRS" ); + QgsCoordinateReferenceSystem crs4 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( QStringLiteral( "not a CRS" ) ); QVERIFY( !crs4.isValid() ); QgsCoordinateReferenceSystem::invalidateCache(); @@ -281,7 +281,7 @@ void TestQgsCoordinateReferenceSystem::fromWkt() QgsCoordinateReferenceSystem myCrs = QgsCoordinateReferenceSystem::fromWkt( GEOWKT ); QVERIFY( myCrs.isValid() ); QCOMPARE( myCrs.srsid(), GEOCRS_ID ); - myCrs = QgsCoordinateReferenceSystem::fromWkt( "not wkt" ); + myCrs = QgsCoordinateReferenceSystem::fromWkt( QStringLiteral( "not wkt" ) ); QVERIFY( !myCrs.isValid() ); } @@ -301,12 +301,12 @@ void TestQgsCoordinateReferenceSystem::wktCache() // invalid QgsCoordinateReferenceSystem crs3; - crs3.createFromWkt( "bad wkt" ); + crs3.createFromWkt( QStringLiteral( "bad wkt" ) ); QVERIFY( !crs3.isValid() ); QVERIFY( QgsCoordinateReferenceSystem::mWktCache.contains( "bad wkt" ) ); // a second time, so invalid crs is fetched from cache QgsCoordinateReferenceSystem crs4; - crs4.createFromWkt( "bad wkt" ); + crs4.createFromWkt( QStringLiteral( "bad wkt" ) ); QVERIFY( !crs4.isValid() ); QgsCoordinateReferenceSystem::invalidateCache(); @@ -318,20 +318,20 @@ QString TestQgsCoordinateReferenceSystem::testESRIWkt( int i, QgsCoordinateRefer debugPrint( myCrs ); if ( ! myCrs.isValid() ) - return QString( "test %1 crs is invalid" ); + return QStringLiteral( "test %1 crs is invalid" ); #if 0 if ( myCrs.toProj4() != myProj4Strings[i] ) return QString( "test %1 PROJ.4 = [ %2 ] expecting [ %3 ]" ).arg( i ).arg( myCrs.toProj4() ).arg( myProj4Strings[i] ); #endif if ( myCrs.toProj4().indexOf( myTOWGS84Strings[i] ) == -1 ) - return QString( "test %1 [%2] not found, PROJ.4 = [%3] expecting [%4]" - ).arg( i ).arg( myTOWGS84Strings[i], myCrs.toProj4(), myProj4Strings[i] ); + return QStringLiteral( "test %1 [%2] not found, PROJ.4 = [%3] expecting [%4]" + ).arg( i ).arg( myTOWGS84Strings[i], myCrs.toProj4(), myProj4Strings[i] ); if ( myCrs.authid() != myAuthIdStrings[i] ) - return QString( "test %1 AUTHID = [%2] expecting [%3]" - ).arg( i ).arg( myCrs.authid(), myAuthIdStrings[i] ); + return QStringLiteral( "test %1 AUTHID = [%2] expecting [%3]" + ).arg( i ).arg( myCrs.authid(), myAuthIdStrings[i] ); - return ""; + return QLatin1String( "" ); } void TestQgsCoordinateReferenceSystem::createFromESRIWkt() { @@ -342,34 +342,34 @@ void TestQgsCoordinateReferenceSystem::createFromESRIWkt() // for more tests add definitions here // this example file taken from bug #5598 - myWktStrings << "PROJCS[\"Indian_1960_UTM_Zone_48N\",GEOGCS[\"GCS_Indian_1960\",DATUM[\"D_Indian_1960\",SPHEROID[\"Everest_Adjustment_1937\",6377276.345,300.8017]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",0.9996],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"; + myWktStrings << QStringLiteral( "PROJCS[\"Indian_1960_UTM_Zone_48N\",GEOGCS[\"GCS_Indian_1960\",DATUM[\"D_Indian_1960\",SPHEROID[\"Everest_Adjustment_1937\",6377276.345,300.8017]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",105.0],PARAMETER[\"Scale_Factor\",0.9996],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]" ); myGdalVersionOK << 1800; - myFiles << "bug5598.shp"; - myProj4Strings << "+proj=utm +zone=48 +a=6377276.345 +b=6356075.41314024 +towgs84=198,881,317,0,0,0,0 +units=m +no_defs"; - myTOWGS84Strings << "+towgs84=198,881,317,0,0,0,0"; - myAuthIdStrings << "EPSG:3148"; + myFiles << QStringLiteral( "bug5598.shp" ); + myProj4Strings << QStringLiteral( "+proj=utm +zone=48 +a=6377276.345 +b=6356075.41314024 +towgs84=198,881,317,0,0,0,0 +units=m +no_defs" ); + myTOWGS84Strings << QStringLiteral( "+towgs84=198,881,317,0,0,0,0" ); + myAuthIdStrings << QStringLiteral( "EPSG:3148" ); // this example file taken from bug #5598 - geographic CRS only, supported since gdal 1.9 - myWktStrings << "GEOGCS[\"GCS_Indian_1960\",DATUM[\"D_Indian_1960\",SPHEROID[\"Everest_Adjustment_1937\",6377276.345,300.8017]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]"; - myFiles << ""; + myWktStrings << QStringLiteral( "GEOGCS[\"GCS_Indian_1960\",DATUM[\"D_Indian_1960\",SPHEROID[\"Everest_Adjustment_1937\",6377276.345,300.8017]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]" ); + myFiles << QLatin1String( "" ); myGdalVersionOK << 1900; - myProj4Strings << "+proj=longlat +a=6377276.345 +b=6356075.41314024 +towgs84=198,881,317,0,0,0,0 +no_defs"; - myTOWGS84Strings << "+towgs84=198,881,317,0,0,0,0"; - myAuthIdStrings << "EPSG:4131"; + myProj4Strings << QStringLiteral( "+proj=longlat +a=6377276.345 +b=6356075.41314024 +towgs84=198,881,317,0,0,0,0 +no_defs" ); + myTOWGS84Strings << QStringLiteral( "+towgs84=198,881,317,0,0,0,0" ); + myAuthIdStrings << QStringLiteral( "EPSG:4131" ); // SAD69 geographic CRS, supported since gdal 1.9 - myWktStrings << "GEOGCS[\"GCS_South_American_1969\",DATUM[\"D_South_American_1969\",SPHEROID[\"GRS_1967_Truncated\",6378160.0,298.25]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]"; - myFiles << ""; + myWktStrings << QStringLiteral( "GEOGCS[\"GCS_South_American_1969\",DATUM[\"D_South_American_1969\",SPHEROID[\"GRS_1967_Truncated\",6378160.0,298.25]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]" ); + myFiles << QLatin1String( "" ); myGdalVersionOK << 1900; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 //proj definition for EPSG:4618 was updated in GDAL 2.0 - see https://github.com/OSGeo/proj.4/issues/241 myProj4Strings << "+proj=longlat +ellps=aust_SA +towgs84=-66.87,4.37,-38.52,0,0,0,0 +no_defs"; myTOWGS84Strings << "+towgs84=-66.87,4.37,-38.52,0,0,0,0"; #else - myProj4Strings << "+proj=longlat +ellps=aust_SA +towgs84=-57,1,-41,0,0,0,0 +no_defs"; - myTOWGS84Strings << "+towgs84=-57,1,-41,0,0,0,0"; + myProj4Strings << QStringLiteral( "+proj=longlat +ellps=aust_SA +towgs84=-57,1,-41,0,0,0,0 +no_defs" ); + myTOWGS84Strings << QStringLiteral( "+towgs84=-57,1,-41,0,0,0,0" ); #endif - myAuthIdStrings << "EPSG:4618"; + myAuthIdStrings << QStringLiteral( "EPSG:4618" ); // do test with WKT definitions for ( int i = 0; i < myWktStrings.size() ; i++ ) @@ -391,17 +391,17 @@ void TestQgsCoordinateReferenceSystem::createFromESRIWkt() // do test with shapefiles CPLSetConfigOption( "GDAL_FIX_ESRI_WKT", configOld ); - if ( myFiles[i] != "" ) + if ( myFiles[i] != QLatin1String( "" ) ) { // use ogr to open file, make sure CRS is ok // this probably could be in another test, but leaving it here since it deals with CRS - QString fileStr = QString( TEST_DATA_DIR ) + '/' + myFiles[i]; + QString fileStr = QStringLiteral( TEST_DATA_DIR ) + '/' + myFiles[i]; QgsDebugMsg( QString( "i=%1 file=%2" ).arg( i ).arg( fileStr ) ); - QgsVectorLayer *myLayer = new QgsVectorLayer( fileStr, "", "ogr" ); + QgsVectorLayer *myLayer = new QgsVectorLayer( fileStr, QLatin1String( "" ), QStringLiteral( "ogr" ) ); if ( !myLayer || ! myLayer->isValid() ) { - qWarning() << QString( "test %1 did not get valid vector layer from %2" ).arg( i ).arg( fileStr ); + qWarning() << QStringLiteral( "test %1 did not get valid vector layer from %2" ).arg( i ).arg( fileStr ); QVERIFY2( false, "no valid vector layer" ); } else @@ -489,7 +489,7 @@ void TestQgsCoordinateReferenceSystem::fromProj4() debugPrint( myCrs ); QVERIFY( myCrs.isValid() ); QCOMPARE( myCrs.srsid(), GEOCRS_ID ); - myCrs = QgsCoordinateReferenceSystem::fromProj4( "" ); + myCrs = QgsCoordinateReferenceSystem::fromProj4( QLatin1String( "" ) ); QVERIFY( !myCrs.isValid() ); } @@ -509,12 +509,12 @@ void TestQgsCoordinateReferenceSystem::proj4Cache() // invalid QgsCoordinateReferenceSystem crs3; - crs3.createFromProj4( "bad proj4" ); + crs3.createFromProj4( QStringLiteral( "bad proj4" ) ); QVERIFY( !crs3.isValid() ); QVERIFY( QgsCoordinateReferenceSystem::mProj4Cache.contains( "bad proj4" ) ); // a second time, so invalid crs is fetched from cache QgsCoordinateReferenceSystem crs4; - crs4.createFromProj4( "bad proj4" ); + crs4.createFromProj4( QStringLiteral( "bad proj4" ) ); QVERIFY( !crs4.isValid() ); QgsCoordinateReferenceSystem::invalidateCache(); @@ -525,24 +525,24 @@ void TestQgsCoordinateReferenceSystem::fromStringCache() { // test that crs can be retrieved correctly from cache QgsCoordinateReferenceSystem crs; - crs.createFromString( "EPSG:3113" ); + crs.createFromString( QStringLiteral( "EPSG:3113" ) ); QVERIFY( crs.isValid() ); QCOMPARE( crs.authid(), QString( "EPSG:3113" ) ); QVERIFY( QgsCoordinateReferenceSystem::mStringCache.contains( "EPSG:3113" ) ); // a second time, so crs is fetched from cache QgsCoordinateReferenceSystem crs2; - crs2.createFromString( "EPSG:3113" ); + crs2.createFromString( QStringLiteral( "EPSG:3113" ) ); QVERIFY( crs2.isValid() ); QCOMPARE( crs2.authid(), QString( "EPSG:3113" ) ); // invalid QgsCoordinateReferenceSystem crs3; - crs3.createFromString( "bad string" ); + crs3.createFromString( QStringLiteral( "bad string" ) ); QVERIFY( !crs3.isValid() ); QVERIFY( QgsCoordinateReferenceSystem::mStringCache.contains( "bad string" ) ); // a second time, so invalid crs is fetched from cache QgsCoordinateReferenceSystem crs4; - crs4.createFromString( "bad string" ); + crs4.createFromString( QStringLiteral( "bad string" ) ); QVERIFY( !crs4.isValid() ); QgsCoordinateReferenceSystem::invalidateCache(); @@ -685,7 +685,7 @@ void TestQgsCoordinateReferenceSystem::mapUnits() void TestQgsCoordinateReferenceSystem::setValidationHint() { QgsCoordinateReferenceSystem myCrs; - myCrs.setValidationHint( "" ); + myCrs.setValidationHint( QStringLiteral( "" ) ); QVERIFY( myCrs.validationHint() == "" ); debugPrint( myCrs ); } @@ -695,13 +695,13 @@ void TestQgsCoordinateReferenceSystem::hasAxisInverted() // this is used by WMS 1.3 to determine whether to switch axes or not QgsCoordinateReferenceSystem crs; - crs.createFromOgcWmsCrs( "EPSG:4326" ); // WGS 84 with inverted axes + crs.createFromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); // WGS 84 with inverted axes QVERIFY( crs.hasAxisInverted() ); - crs.createFromOgcWmsCrs( "CRS:84" ); // WGS 84 without inverted axes + crs.createFromOgcWmsCrs( QStringLiteral( "CRS:84" ) ); // WGS 84 without inverted axes QVERIFY( !crs.hasAxisInverted() ); - crs.createFromOgcWmsCrs( "EPSG:32633" ); // "WGS 84 / UTM zone 33N" - projected CRS without invertex axes + crs.createFromOgcWmsCrs( QStringLiteral( "EPSG:32633" ) ); // "WGS 84 / UTM zone 33N" - projected CRS without invertex axes QVERIFY( !crs.hasAxisInverted() ); } diff --git a/tests/src/core/testqgsdatadefined.cpp b/tests/src/core/testqgsdatadefined.cpp index 73970942a8b2..2419b89bb29d 100644 --- a/tests/src/core/testqgsdatadefined.cpp +++ b/tests/src/core/testqgsdatadefined.cpp @@ -71,20 +71,20 @@ void TestQgsDataDefined::cleanup() void TestQgsDataDefined::create() { - QSharedPointer dd( new QgsDataDefined( true, true, QString( "exp" ), QString( "field" ) ) ); + QSharedPointer dd( new QgsDataDefined( true, true, QStringLiteral( "exp" ), QStringLiteral( "field" ) ) ); QVERIFY( dd->isActive() ); QVERIFY( dd->useExpression() ); QCOMPARE( dd->expressionString(), QString( "exp" ) ); QCOMPARE( dd->field(), QString( "field" ) ); //test with string constructor - QScopedPointer stringConstructorField( new QgsDataDefined( QString( "\"col1\"" ) ) ); + QScopedPointer stringConstructorField( new QgsDataDefined( QStringLiteral( "\"col1\"" ) ) ); QVERIFY( stringConstructorField->isActive() ); QVERIFY( ! stringConstructorField->useExpression() ); QVERIFY( stringConstructorField->expressionString().isEmpty() ); QCOMPARE( stringConstructorField->field(), QString( "col1" ) ); - QScopedPointer stringConstructorExp( new QgsDataDefined( QString( "1 + 2" ) ) ); + QScopedPointer stringConstructorExp( new QgsDataDefined( QStringLiteral( "1 + 2" ) ) ); QVERIFY( stringConstructorExp->isActive() ); QVERIFY( stringConstructorExp->useExpression() ); QCOMPARE( stringConstructorExp->expressionString(), QString( "1 + 2" ) ); @@ -96,7 +96,7 @@ void TestQgsDataDefined::create() void TestQgsDataDefined::copy() { - QgsDataDefined original( true, true, QString( "sqrt(2)" ), QString( "field" ) ); + QgsDataDefined original( true, true, QStringLiteral( "sqrt(2)" ), QStringLiteral( "field" ) ); original.prepareExpression(); QgsDataDefined copy( original ); QVERIFY( copy == original ); @@ -108,7 +108,7 @@ void TestQgsDataDefined::copy() void TestQgsDataDefined::assignment() { - QgsDataDefined original( true, true, QString( "sqrt(2)" ), QString( "field" ) ); + QgsDataDefined original( true, true, QStringLiteral( "sqrt(2)" ), QStringLiteral( "field" ) ); QgsDataDefined copy; copy = original; QVERIFY( copy == original ); @@ -131,10 +131,10 @@ void TestQgsDataDefined::gettersSetters() dd.setUseExpression( true ); QVERIFY( dd.useExpression() ); - dd.setExpressionString( QString( "expression" ) ); + dd.setExpressionString( QStringLiteral( "expression" ) ); QCOMPARE( dd.expressionString(), QString( "expression" ) ); - dd.setField( QString( "field" ) ); + dd.setField( QStringLiteral( "field" ) ); QCOMPARE( dd.field(), QString( "field" ) ); } @@ -150,11 +150,11 @@ void TestQgsDataDefined::defaultValues() QVERIFY( !dd->hasDefaultValues() ); delete dd; dd = new QgsDataDefined(); - dd->setExpressionString( QString( "expression" ) ); + dd->setExpressionString( QStringLiteral( "expression" ) ); QVERIFY( !dd->hasDefaultValues() ); delete dd; dd = new QgsDataDefined(); - dd->setField( QString( "field" ) ); + dd->setField( QStringLiteral( "field" ) ); QVERIFY( !dd->hasDefaultValues() ); delete dd; } @@ -163,13 +163,13 @@ void TestQgsDataDefined::equality() { QgsDataDefined dd1; dd1.setActive( true ); - dd1.setField( QString( "field" ) ); - dd1.setExpressionString( QString( "expression" ) ); + dd1.setField( QStringLiteral( "field" ) ); + dd1.setExpressionString( QStringLiteral( "expression" ) ); dd1.setUseExpression( true ); QgsDataDefined dd2; dd2.setActive( true ); - dd2.setField( QString( "field" ) ); - dd2.setExpressionString( QString( "expression" ) ); + dd2.setField( QStringLiteral( "field" ) ); + dd2.setExpressionString( QStringLiteral( "expression" ) ); dd2.setUseExpression( true ); QVERIFY( dd1 == dd2 ); QVERIFY( !( dd1 != dd2 ) ); @@ -179,14 +179,14 @@ void TestQgsDataDefined::equality() QVERIFY( !( dd1 == dd2 ) ); QVERIFY( dd1 != dd2 ); dd2.setActive( true ); - dd2.setField( QString( "a" ) ); + dd2.setField( QStringLiteral( "a" ) ); QVERIFY( !( dd1 == dd2 ) ); QVERIFY( dd1 != dd2 ); - dd2.setField( QString( "field" ) ); - dd2.setExpressionString( QString( "b" ) ); + dd2.setField( QStringLiteral( "field" ) ); + dd2.setExpressionString( QStringLiteral( "b" ) ); QVERIFY( !( dd1 == dd2 ) ); QVERIFY( dd1 != dd2 ); - dd2.setExpressionString( QString( "expression" ) ); + dd2.setExpressionString( QStringLiteral( "expression" ) ); dd2.setUseExpression( false ); QVERIFY( !( dd1 == dd2 ) ); QVERIFY( dd1 != dd2 ); @@ -198,15 +198,15 @@ void TestQgsDataDefined::xmlMethods() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); QgsDataDefined dd1; dd1.setActive( true ); - dd1.setField( QString( "field" ) ); - dd1.setExpressionString( QString( "expression" ) ); + dd1.setField( QStringLiteral( "field" ) ); + dd1.setExpressionString( QStringLiteral( "expression" ) ); dd1.setUseExpression( true ); - QDomElement ddElem = dd1.toXmlElement( doc, "test" ); + QDomElement ddElem = dd1.toXmlElement( doc, QStringLiteral( "test" ) ); //test reading QgsDataDefined dd2; @@ -229,8 +229,8 @@ void TestQgsDataDefined::mapMethods() //no base name QgsDataDefined dd1; dd1.setActive( true ); - dd1.setField( QString( "field" ) ); - dd1.setExpressionString( QString( "expression" ) ); + dd1.setField( QStringLiteral( "field" ) ); + dd1.setExpressionString( QStringLiteral( "expression" ) ); dd1.setUseExpression( true ); QgsStringMap map1 = dd1.toMap(); @@ -241,22 +241,22 @@ void TestQgsDataDefined::mapMethods() //base name QgsDataDefined dd3; dd3.setActive( false ); - dd3.setField( QString( "field2" ) ); - dd3.setExpressionString( QString( "expression2" ) ); + dd3.setField( QStringLiteral( "field2" ) ); + dd3.setExpressionString( QStringLiteral( "expression2" ) ); dd3.setUseExpression( false ); - QgsStringMap map2 = dd3.toMap( QString( "basename" ) ); + QgsStringMap map2 = dd3.toMap( QStringLiteral( "basename" ) ); - QgsDataDefined* dd4 = QgsDataDefined::fromMap( map2, QString( "basename" ) ); + QgsDataDefined* dd4 = QgsDataDefined::fromMap( map2, QStringLiteral( "basename" ) ); QCOMPARE( *dd4, dd3 ); delete dd4; // read with invalid basename - dd4 = QgsDataDefined::fromMap( map2, QString( "xx" ) ); + dd4 = QgsDataDefined::fromMap( map2, QStringLiteral( "xx" ) ); QVERIFY( !dd4 ); //test read map with only an expression QgsStringMap expMapOnly; - expMapOnly.insert( QString( "expression" ), QString( "test_exp" ) ); + expMapOnly.insert( QStringLiteral( "expression" ), QStringLiteral( "test_exp" ) ); dd4 = QgsDataDefined::fromMap( expMapOnly ); QVERIFY( dd4 ); @@ -277,14 +277,14 @@ void TestQgsDataDefined::referencedColumns() QVERIFY( cols.isEmpty() ); //set as expression - dd.setExpressionString( "1+col1+col2" ); + dd.setExpressionString( QStringLiteral( "1+col1+col2" ) ); cols = dd.referencedColumns(); QCOMPARE( cols.size(), 2 ); QVERIFY( cols.contains( QString( "col1" ) ) ); QVERIFY( cols.contains( QString( "col2" ) ) ); //alter expression and check that referenced columns is updated - dd.setExpressionString( "1+col1+col2+col3" ); + dd.setExpressionString( QStringLiteral( "1+col1+col2+col3" ) ); cols = dd.referencedColumns(); QCOMPARE( cols.size(), 3 ); QVERIFY( cols.contains( QString( "col1" ) ) ); @@ -296,7 +296,7 @@ void TestQgsDataDefined::referencedColumns() cols = dd.referencedColumns(); QVERIFY( cols.isEmpty() ); - dd.setField( "field" ); + dd.setField( QStringLiteral( "field" ) ); cols = dd.referencedColumns(); QCOMPARE( cols.size(), 1 ); QVERIFY( cols.contains( QString( "field" ) ) ); @@ -314,8 +314,8 @@ void TestQgsDataDefined::expressionOrString() { QgsDataDefined dd; dd.setActive( true ); - dd.setField( "field" ); - dd.setExpressionString( "1+col1+col2" ); + dd.setField( QStringLiteral( "field" ) ); + dd.setExpressionString( QStringLiteral( "1+col1+col2" ) ); dd.setUseExpression( true ); QCOMPARE( dd.expressionOrField(), QString( "1+col1+col2" ) ); diff --git a/tests/src/core/testqgsdataitem.cpp b/tests/src/core/testqgsdataitem.cpp index 5736a51c6d71..231935b1fd38 100644 --- a/tests/src/core/testqgsdataitem.cpp +++ b/tests/src/core/testqgsdataitem.cpp @@ -66,22 +66,22 @@ void TestQgsDataItem::initTestCase() QgsApplication::showSettings(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); // save current scanItemsSetting value QSettings settings; - mScanItemsSetting = settings.value( "/qgis/scanItemsInBrowser2", QVariant( "" ) ).toString(); + mScanItemsSetting = settings.value( QStringLiteral( "/qgis/scanItemsInBrowser2" ), QVariant( "" ) ).toString(); //create a directory item that will be used in all tests... - mDirItem = new QgsDirectoryItem( 0, "Test", TEST_DATA_DIR ); + mDirItem = new QgsDirectoryItem( 0, QStringLiteral( "Test" ), TEST_DATA_DIR ); } void TestQgsDataItem::cleanupTestCase() { // restore scanItemsSetting QSettings settings; - settings.setValue( "/qgis/scanItemsInBrowser2", mScanItemsSetting ); + settings.setValue( QStringLiteral( "/qgis/scanItemsInBrowser2" ), mScanItemsSetting ); if ( mDirItem ) delete mDirItem; @@ -106,11 +106,11 @@ void TestQgsDataItem::testDirItemChildren() { QSettings settings; QStringList tmpSettings; - tmpSettings << "" << "contents" << "extension"; + tmpSettings << QLatin1String( "" ) << QStringLiteral( "contents" ) << QStringLiteral( "extension" ); Q_FOREACH ( const QString& tmpSetting, tmpSettings ) { - settings.setValue( "/qgis/scanItemsInBrowser2", tmpSetting ); - QgsDirectoryItem* dirItem = new QgsDirectoryItem( 0, "Test", TEST_DATA_DIR ); + settings.setValue( QStringLiteral( "/qgis/scanItemsInBrowser2" ), tmpSetting ); + QgsDirectoryItem* dirItem = new QgsDirectoryItem( 0, QStringLiteral( "Test" ), TEST_DATA_DIR ); QVERIFY( isValidDirItem( dirItem ) ); QVector children = dirItem->createChildren(); @@ -125,48 +125,48 @@ void TestQgsDataItem::testDirItemChildren() QFileInfo info( layerItem->path() ); QString lFile = info.fileName(); QString lProvider = layerItem->providerKey(); - QString errStr = QString( "layer #%1 - %2 provider = %3 tmpSetting = %4" ).arg( i ).arg( lFile, lProvider, tmpSetting ); + QString errStr = QStringLiteral( "layer #%1 - %2 provider = %3 tmpSetting = %4" ).arg( i ).arg( lFile, lProvider, tmpSetting ); QgsDebugMsg( QString( "testing child name=%1 provider=%2 path=%3 tmpSetting = %4" ).arg( layerItem->name(), lProvider, lFile, tmpSetting ) ); - if ( lFile == "landsat.tif" ) + if ( lFile == QLatin1String( "landsat.tif" ) ) { QVERIFY2( lProvider == "gdal", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "points.vrt" ) + else if ( lFile == QLatin1String( "points.vrt" ) ) { QVERIFY2( lProvider == "ogr", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "landsat.vrt" ) + else if ( lFile == QLatin1String( "landsat.vrt" ) ) { QVERIFY2( lProvider == "gdal", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "landsat_b1.tif.gz" ) + else if ( lFile == QLatin1String( "landsat_b1.tif.gz" ) ) { QVERIFY2( lProvider == "gdal", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "points3.geojson.gz" ) + else if ( lFile == QLatin1String( "points3.geojson.gz" ) ) { QVERIFY2( lProvider == "ogr", errStr.toLocal8Bit().constData() ); } // test layerName() does not include extension for gdal and ogr items (bug #5621) QString lName = layerItem->layerName(); - errStr = QString( "layer #%1 - %2 lName = %3 tmpSetting = %4" ).arg( i ).arg( lFile, lName, tmpSetting ); + errStr = QStringLiteral( "layer #%1 - %2 lName = %3 tmpSetting = %4" ).arg( i ).arg( lFile, lName, tmpSetting ); - if ( lFile == "landsat.tif" ) + if ( lFile == QLatin1String( "landsat.tif" ) ) { QVERIFY2( lName == "landsat", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "points.shp" ) + else if ( lFile == QLatin1String( "points.shp" ) ) { QVERIFY2( lName == "points", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "landsat_b1.tif.gz" ) + else if ( lFile == QLatin1String( "landsat_b1.tif.gz" ) ) { QVERIFY2( lName == "landsat_b1", errStr.toLocal8Bit().constData() ); } - else if ( lFile == "points3.geojson.gz" ) + else if ( lFile == QLatin1String( "points3.geojson.gz" ) ) { QVERIFY2( lName == "points3", errStr.toLocal8Bit().constData() ); } diff --git a/tests/src/core/testqgsdiagram.cpp b/tests/src/core/testqgsdiagram.cpp index 2332c69f50be..9a5d0418d1a6 100644 --- a/tests/src/core/testqgsdiagram.cpp +++ b/tests/src/core/testqgsdiagram.cpp @@ -86,7 +86,7 @@ class TestQgsDiagram : public QObject QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayer( mPointsLayer ); @@ -94,7 +94,7 @@ class TestQgsDiagram : public QObject // Create map composition to draw on mMapSettings->setLayers( QStringList() << mPointsLayer->id() ); - mReport += "

                                                                                                                                                                                    Diagram Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Diagram Tests

                                                                                                                                                                                    \n" ); } // will be called after the last testfunction was executed. @@ -136,7 +136,7 @@ class TestQgsDiagram : public QObject col1.setAlphaF( 0.5 ); col2.setAlphaF( 0.5 ); ds.categoryColors = QList() << col1 << col2; - ds.categoryAttributes = QList() << "\"Pilots\"" << "\"Cabin Crew\""; + ds.categoryAttributes = QList() << QStringLiteral( "\"Pilots\"" ) << QStringLiteral( "\"Cabin Crew\"" ); ds.maxScaleDenominator = -1; ds.minScaleDenominator = -1; ds.minimumSize = 0; @@ -173,7 +173,7 @@ class TestQgsDiagram : public QObject col1.setAlphaF( 0.5 ); col2.setAlphaF( 0.5 ); ds.categoryColors = QList() << col1 << col2; - ds.categoryAttributes = QList() << "ln(Pilots + 1)" << "ln(\"Cabin Crew\" + 1)"; + ds.categoryAttributes = QList() << QStringLiteral( "ln(Pilots + 1)" ) << QStringLiteral( "ln(\"Cabin Crew\" + 1)" ); ds.maxScaleDenominator = -1; ds.minScaleDenominator = -1; ds.minimumSize = 0; @@ -190,7 +190,7 @@ class TestQgsDiagram : public QObject dr->setUpperValue( 10 ); dr->setUpperSize( QSizeF( 40, 40 ) ); dr->setClassificationAttributeIsExpression( true ); - dr->setClassificationAttributeExpression( "ln(Staff + 1)" ); + dr->setClassificationAttributeExpression( QStringLiteral( "ln(Staff + 1)" ) ); dr->setDiagram( new QgsPieDiagram() ); dr->setDiagramSettings( ds ); diff --git a/tests/src/core/testqgsdistancearea.cpp b/tests/src/core/testqgsdistancearea.cpp index bcb4d309b61f..b6b3925a060c 100644 --- a/tests/src/core/testqgsdistancearea.cpp +++ b/tests/src/core/testqgsdistancearea.cpp @@ -75,7 +75,7 @@ void TestQgsDistanceArea::basic() // Now, on an ellipsoid. Always less? daA.setSourceCrs( 3006 ); - daA.setEllipsoid( "WGS84" ); + daA.setEllipsoid( QStringLiteral( "WGS84" ) ); daA.setEllipsoidalMode( true ); resultA = daA.measureLine( p1, p2 ); QVERIFY( resultA < 5.0 ); @@ -86,7 +86,7 @@ void TestQgsDistanceArea::basic() QCOMPARE( resultA, resultB ); // Different Ellipsoid - daB.setEllipsoid( "WGS72" ); + daB.setEllipsoid( QStringLiteral( "WGS72" ) ); resultB = daB.measureLine( p1, p2 ); QVERIFY( ! qFuzzyCompare( resultA, resultB ) ); @@ -115,11 +115,11 @@ void TestQgsDistanceArea::test_distances() // Set up DA QgsDistanceArea myDa; - myDa.setSourceAuthId( "EPSG:4030" ); + myDa.setSourceAuthId( QStringLiteral( "EPSG:4030" ) ); myDa.setEllipsoidalMode( true ); - myDa.setEllipsoid( "WGS84" ); + myDa.setEllipsoid( QStringLiteral( "WGS84" ) ); - QString myFileName = QString( TEST_DATA_DIR ) + "/GeodTest-nano.dat"; + QString myFileName = QStringLiteral( TEST_DATA_DIR ) + "/GeodTest-nano.dat"; QFile myFile( myFileName ); if ( ! myFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) @@ -155,9 +155,9 @@ void TestQgsDistanceArea::regression13601() //test regression #13601 QgsDistanceArea calc; calc.setEllipsoidalMode( true ); - calc.setEllipsoid( "NONE" ); + calc.setEllipsoid( QStringLiteral( "NONE" ) ); calc.setSourceCrs( 1108L ); - QgsGeometry geom( QgsGeometryFactory::geomFromWkt( "Polygon ((252000 1389000, 265000 1389000, 265000 1385000, 252000 1385000, 252000 1389000))" ) ); + QgsGeometry geom( QgsGeometryFactory::geomFromWkt( QStringLiteral( "Polygon ((252000 1389000, 265000 1389000, 265000 1385000, 252000 1385000, 252000 1389000))" ) ) ); QGSCOMPARENEAR( calc.measureArea( &geom ), 52000000, 0.0001 ); } @@ -165,26 +165,26 @@ void TestQgsDistanceArea::collections() { //test measuring for collections QgsDistanceArea myDa; - myDa.setSourceAuthId( "EPSG:4030" ); + myDa.setSourceAuthId( QStringLiteral( "EPSG:4030" ) ); myDa.setEllipsoidalMode( true ); - myDa.setEllipsoid( "WGS84" ); + myDa.setEllipsoid( QStringLiteral( "WGS84" ) ); //collection of lines, should be sum of line length - QgsGeometry lines( QgsGeometryFactory::geomFromWkt( "GeometryCollection( LineString(0 36.53, 5.76 -48.16), LineString(0 25.54, 24.20 36.70) )" ) ); + QgsGeometry lines( QgsGeometryFactory::geomFromWkt( QStringLiteral( "GeometryCollection( LineString(0 36.53, 5.76 -48.16), LineString(0 25.54, 24.20 36.70) )" ) ) ); double result = myDa.measureLength( &lines ); QGSCOMPARENEAR( result, 12006159, 1 ); result = myDa.measureArea( &lines ); QVERIFY( qgsDoubleNear( result, 0 ) ); //collection of polygons - QgsGeometry polys( QgsGeometryFactory::geomFromWkt( "GeometryCollection( Polygon((0 36.53, 5.76 -48.16, 0 25.54, 0 36.53)), Polygon((10 20, 15 20, 15 10, 10 20)) )" ) ); + QgsGeometry polys( QgsGeometryFactory::geomFromWkt( QStringLiteral( "GeometryCollection( Polygon((0 36.53, 5.76 -48.16, 0 25.54, 0 36.53)), Polygon((10 20, 15 20, 15 10, 10 20)) )" ) ) ); result = myDa.measureArea( &polys ); QGSCOMPARENEAR( result, 670434859475LL, 1 ); result = myDa.measureLength( &polys ); QVERIFY( qgsDoubleNear( result, 0 ) ); //mixed collection - QgsGeometry mixed( QgsGeometryFactory::geomFromWkt( "GeometryCollection( LineString(0 36.53, 5.76 -48.16), LineString(0 25.54, 24.20 36.70), Polygon((0 36.53, 5.76 -48.16, 0 25.54, 0 36.53)), Polygon((10 20, 15 20, 15 10, 10 20)) )" ) ); + QgsGeometry mixed( QgsGeometryFactory::geomFromWkt( QStringLiteral( "GeometryCollection( LineString(0 36.53, 5.76 -48.16), LineString(0 25.54, 24.20 36.70), Polygon((0 36.53, 5.76 -48.16, 0 25.54, 0 36.53)), Polygon((10 20, 15 20, 15 10, 10 20)) )" ) ) ); //measure area specifically result = myDa.measureArea( &mixed ); QGSCOMPARENEAR( result, 670434859475LL, 1 ); @@ -198,7 +198,7 @@ void TestQgsDistanceArea::measureUnits() //test regression #13610 QgsDistanceArea calc; calc.setEllipsoidalMode( false ); - calc.setEllipsoid( "NONE" ); + calc.setEllipsoid( QStringLiteral( "NONE" ) ); calc.setSourceCrs( 254L ); QgsUnitTypes::DistanceUnit units; QgsPoint p1( 1341683.9854275715, 408256.9562717728 ); @@ -210,7 +210,7 @@ void TestQgsDistanceArea::measureUnits() QGSCOMPARENEAR( result, 7637.7952755903825, 0.001 ); calc.setEllipsoidalMode( true ); - calc.setEllipsoid( "WGS84" ); + calc.setEllipsoid( QStringLiteral( "WGS84" ) ); result = calc.measureLine( p1, p2, units ); //OTF, result will be in meters QCOMPARE( units, QgsUnitTypes::DistanceMeters ); @@ -222,7 +222,7 @@ void TestQgsDistanceArea::measureAreaAndUnits() QgsDistanceArea da; da.setSourceCrs( 3452 ); da.setEllipsoidalMode( false ); - da.setEllipsoid( "NONE" ); + da.setEllipsoid( QStringLiteral( "NONE" ) ); QgsCoordinateReferenceSystem daCRS; daCRS.createFromSrsId( da.sourceCrsId() ); QgsPolyline ring; @@ -248,7 +248,7 @@ void TestQgsDistanceArea::measureAreaAndUnits() QVERIFY(( qgsDoubleNear( area, 3.0, 0.00000001 ) && units == QgsUnitTypes::AreaSquareDegrees ) || ( qgsDoubleNear( area, 37176087091.5, 0.1 ) && units == QgsUnitTypes::AreaSquareMeters ) ); - da.setEllipsoid( "WGS84" ); + da.setEllipsoid( QStringLiteral( "WGS84" ) ); area = da.measureArea( &polygon ); units = da.areaUnits(); @@ -314,7 +314,7 @@ void TestQgsDistanceArea::emptyPolygon() QgsDistanceArea da; da.setSourceCrs( 3452 ); da.setEllipsoidalMode( true ); - da.setEllipsoid( "WGS84" ); + da.setEllipsoid( QStringLiteral( "WGS84" ) ); //test that measuring an empty polygon doesn't crash da.measurePolygon( QList< QgsPoint >() ); @@ -325,9 +325,9 @@ void TestQgsDistanceArea::regression14675() //test regression #14675 QgsDistanceArea calc; calc.setEllipsoidalMode( true ); - calc.setEllipsoid( "GRS80" ); + calc.setEllipsoid( QStringLiteral( "GRS80" ) ); calc.setSourceCrs( 145L ); - QgsGeometry geom( QgsGeometryFactory::geomFromWkt( "Polygon ((917593.5791854317067191 6833700.00807378999888897, 917596.43389983859378844 6833700.67099479306489229, 917599.53056440979707986 6833700.78673478215932846, 917593.5791854317067191 6833700.00807378999888897))" ) ); + QgsGeometry geom( QgsGeometryFactory::geomFromWkt( QStringLiteral( "Polygon ((917593.5791854317067191 6833700.00807378999888897, 917596.43389983859378844 6833700.67099479306489229, 917599.53056440979707986 6833700.78673478215932846, 917593.5791854317067191 6833700.00807378999888897))" ) ) ); //lots of tolerance here - the formulas get quite unstable with small areas due to division by very small floats QGSCOMPARENEAR( calc.measureArea( &geom ), 0.83301, 0.02 ); } diff --git a/tests/src/core/testqgsellipsemarker.cpp b/tests/src/core/testqgsellipsemarker.cpp index d66ee388a338..5c2936d9e839 100644 --- a/tests/src/core/testqgsellipsemarker.cpp +++ b/tests/src/core/testqgsellipsemarker.cpp @@ -96,7 +96,7 @@ void TestQgsEllipseMarkerSymbol::initTestCase() QString pointFileName = mTestDataDir + "points.shp"; QFileInfo pointFileInfo( pointFileName ); mpPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( @@ -114,7 +114,7 @@ void TestQgsEllipseMarkerSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPointsLayer->id() ); - mReport += "

                                                                                                                                                                                    Ellipse Marker Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Ellipse Marker Tests

                                                                                                                                                                                    \n" ); } void TestQgsEllipseMarkerSymbol::cleanupTestCase() @@ -133,11 +133,11 @@ void TestQgsEllipseMarkerSymbol::cleanupTestCase() void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbol() { - mReport += "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n" ); mEllipseMarkerLayer->setFillColor( Qt::blue ); mEllipseMarkerLayer->setOutlineColor( Qt::black ); - mEllipseMarkerLayer->setSymbolName( "circle" ); + mEllipseMarkerLayer->setSymbolName( QStringLiteral( "circle" ) ); mEllipseMarkerLayer->setSymbolHeight( 3 ); mEllipseMarkerLayer->setSymbolWidth( 6 ); mEllipseMarkerLayer->setOutlineWidth( 0.8 ); @@ -146,11 +146,11 @@ void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbol() void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbolBevelJoin() { - mReport += "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n" ); mEllipseMarkerLayer->setFillColor( Qt::blue ); mEllipseMarkerLayer->setOutlineColor( Qt::black ); - mEllipseMarkerLayer->setSymbolName( "triangle" ); + mEllipseMarkerLayer->setSymbolName( QStringLiteral( "triangle" ) ); mEllipseMarkerLayer->setSymbolHeight( 25 ); mEllipseMarkerLayer->setSymbolWidth( 20 ); mEllipseMarkerLayer->setOutlineWidth( 3 ); @@ -160,11 +160,11 @@ void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbolBevelJoin() void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbolMiterJoin() { - mReport += "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n" ); mEllipseMarkerLayer->setFillColor( Qt::blue ); mEllipseMarkerLayer->setOutlineColor( Qt::black ); - mEllipseMarkerLayer->setSymbolName( "triangle" ); + mEllipseMarkerLayer->setSymbolName( QStringLiteral( "triangle" ) ); mEllipseMarkerLayer->setSymbolHeight( 25 ); mEllipseMarkerLayer->setSymbolWidth( 20 ); mEllipseMarkerLayer->setOutlineWidth( 3 ); @@ -174,11 +174,11 @@ void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbolMiterJoin() void TestQgsEllipseMarkerSymbol::ellipseMarkerSymbolRoundJoin() { - mReport += "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Ellipse marker symbol layer test

                                                                                                                                                                                    \n" ); mEllipseMarkerLayer->setFillColor( Qt::blue ); mEllipseMarkerLayer->setOutlineColor( Qt::black ); - mEllipseMarkerLayer->setSymbolName( "triangle" ); + mEllipseMarkerLayer->setSymbolName( QStringLiteral( "triangle" ) ); mEllipseMarkerLayer->setSymbolHeight( 25 ); mEllipseMarkerLayer->setSymbolWidth( 20 ); mEllipseMarkerLayer->setOutlineWidth( 3 ); @@ -190,14 +190,14 @@ void TestQgsEllipseMarkerSymbol::bounds() { mEllipseMarkerLayer->setFillColor( Qt::blue ); mEllipseMarkerLayer->setOutlineColor( Qt::black ); - mEllipseMarkerLayer->setSymbolName( "circle" ); + mEllipseMarkerLayer->setSymbolName( QStringLiteral( "circle" ) ); mEllipseMarkerLayer->setSymbolHeight( 3 ); mEllipseMarkerLayer->setSymbolWidth( 6 ); - mEllipseMarkerLayer->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "min(\"importance\" * 2, 6)" ) ); + mEllipseMarkerLayer->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "min(\"importance\" * 2, 6)" ) ) ); mEllipseMarkerLayer->setOutlineWidth( 0.5 ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "ellipsemarker_bounds" ); + bool result = imageCheck( QStringLiteral( "ellipsemarker_bounds" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); QVERIFY( result ); } @@ -215,7 +215,7 @@ bool TestQgsEllipseMarkerSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPointsLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_ellipsemarker" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_ellipsemarker" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 0b4656a918c0..c566ef7758a7 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -39,7 +39,7 @@ static void _parseAndEvalExpr( int arg ) Q_UNUSED( arg ); for ( int i = 0; i < 100; ++i ) { - QgsExpression exp( "1 + 2 * 2" ); + QgsExpression exp( QStringLiteral( "1 + 2 * 2" ) ); exp.evaluate(); } } @@ -79,106 +79,106 @@ class TestQgsExpression: public QObject QgsApplication::showSettings(); //create a point layer that will be used in all tests... - QString testDataDir = QString( TEST_DATA_DIR ) + '/'; + QString testDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; QString pointsFileName = testDataDir + "points.shp"; QFileInfo pointFileInfo( pointsFileName ); mPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayer( mPointsLayer ); - mPointsLayer->setTitle( "layer title" ); - mPointsLayer->setAbstract( "layer abstract" ); - mPointsLayer->setKeywordList( "layer,keywords" ); - mPointsLayer->setDataUrl( "data url" ); - mPointsLayer->setAttribution( "layer attribution" ); - mPointsLayer->setAttributionUrl( "attribution url" ); + mPointsLayer->setTitle( QStringLiteral( "layer title" ) ); + mPointsLayer->setAbstract( QStringLiteral( "layer abstract" ) ); + mPointsLayer->setKeywordList( QStringLiteral( "layer,keywords" ) ); + mPointsLayer->setDataUrl( QStringLiteral( "data url" ) ); + mPointsLayer->setAttribution( QStringLiteral( "layer attribution" ) ); + mPointsLayer->setAttributionUrl( QStringLiteral( "attribution url" ) ); mPointsLayer->setMaximumScale( 500 ); mPointsLayer->setMinimumScale( 1000 ); // test memory layer for get_feature tests - mMemoryLayer = new QgsVectorLayer( "Point?field=col1:integer&field=col2:string", "test", "memory" ); + mMemoryLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer&field=col2:string" ), QStringLiteral( "test" ), QStringLiteral( "memory" ) ); QVERIFY( mMemoryLayer->isValid() ); QgsFeature f1( mMemoryLayer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", 10 ); - f1.setAttribute( "col2", "test1" ); + f1.setAttribute( QStringLiteral( "col1" ), 10 ); + f1.setAttribute( QStringLiteral( "col2" ), "test1" ); QgsFeature f2( mMemoryLayer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", 11 ); - f2.setAttribute( "col2", "test2" ); + f2.setAttribute( QStringLiteral( "col1" ), 11 ); + f2.setAttribute( QStringLiteral( "col2" ), "test2" ); QgsFeature f3( mMemoryLayer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", 3 ); - f3.setAttribute( "col2", "test3" ); + f3.setAttribute( QStringLiteral( "col1" ), 3 ); + f3.setAttribute( QStringLiteral( "col2" ), "test3" ); QgsFeature f4( mMemoryLayer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", 41 ); - f4.setAttribute( "col2", "test4" ); + f4.setAttribute( QStringLiteral( "col1" ), 41 ); + f4.setAttribute( QStringLiteral( "col2" ), "test4" ); mMemoryLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); QgsMapLayerRegistry::instance()->addMapLayer( mMemoryLayer ); // test layer for aggregates - mAggregatesLayer = new QgsVectorLayer( "Point?field=col1:integer&field=col2:string&field=col3:integer", "aggregate_layer", "memory" ); + mAggregatesLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer&field=col2:string&field=col3:integer" ), QStringLiteral( "aggregate_layer" ), QStringLiteral( "memory" ) ); QVERIFY( mAggregatesLayer->isValid() ); QgsFeature af1( mAggregatesLayer->dataProvider()->fields(), 1 ); af1.setGeometry( QgsGeometry::fromPoint( QgsPoint( 0, 0 ) ) ); - af1.setAttribute( "col1", 4 ); - af1.setAttribute( "col2", "test" ); - af1.setAttribute( "col3", 2 ); + af1.setAttribute( QStringLiteral( "col1" ), 4 ); + af1.setAttribute( QStringLiteral( "col2" ), "test" ); + af1.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature af2( mAggregatesLayer->dataProvider()->fields(), 2 ); af2.setGeometry( QgsGeometry::fromPoint( QgsPoint( 1, 0 ) ) ); - af2.setAttribute( "col1", 2 ); - af2.setAttribute( "col2", QVariant( QVariant::String ) ); - af2.setAttribute( "col3", 1 ); + af2.setAttribute( QStringLiteral( "col1" ), 2 ); + af2.setAttribute( QStringLiteral( "col2" ), QVariant( QVariant::String ) ); + af2.setAttribute( QStringLiteral( "col3" ), 1 ); QgsFeature af3( mAggregatesLayer->dataProvider()->fields(), 3 ); af3.setGeometry( QgsGeometry::fromPoint( QgsPoint( 2, 0 ) ) ); - af3.setAttribute( "col1", 3 ); - af3.setAttribute( "col2", "test333" ); - af3.setAttribute( "col3", 2 ); + af3.setAttribute( QStringLiteral( "col1" ), 3 ); + af3.setAttribute( QStringLiteral( "col2" ), "test333" ); + af3.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature af4( mAggregatesLayer->dataProvider()->fields(), 4 ); af4.setGeometry( QgsGeometry::fromPoint( QgsPoint( 3, 0 ) ) ); - af4.setAttribute( "col1", 2 ); - af4.setAttribute( "col2", "test4" ); - af4.setAttribute( "col3", 2 ); + af4.setAttribute( QStringLiteral( "col1" ), 2 ); + af4.setAttribute( QStringLiteral( "col2" ), "test4" ); + af4.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature af5( mAggregatesLayer->dataProvider()->fields(), 5 ); af5.setGeometry( QgsGeometry::fromPoint( QgsPoint( 4, 0 ) ) ); - af5.setAttribute( "col1", 5 ); - af5.setAttribute( "col2", QVariant( QVariant::String ) ); - af5.setAttribute( "col3", 3 ); + af5.setAttribute( QStringLiteral( "col1" ), 5 ); + af5.setAttribute( QStringLiteral( "col2" ), QVariant( QVariant::String ) ); + af5.setAttribute( QStringLiteral( "col3" ), 3 ); QgsFeature af6( mAggregatesLayer->dataProvider()->fields(), 6 ); af6.setGeometry( QgsGeometry::fromPoint( QgsPoint( 5, 0 ) ) ); - af6.setAttribute( "col1", 8 ); - af6.setAttribute( "col2", "test4" ); - af6.setAttribute( "col3", 3 ); + af6.setAttribute( QStringLiteral( "col1" ), 8 ); + af6.setAttribute( QStringLiteral( "col2" ), "test4" ); + af6.setAttribute( QStringLiteral( "col3" ), 3 ); mAggregatesLayer->dataProvider()->addFeatures( QgsFeatureList() << af1 << af2 << af3 << af4 << af5 << af6 ); QgsMapLayerRegistry::instance()->addMapLayer( mAggregatesLayer ); - mChildLayer = new QgsVectorLayer( "Point?field=parent:integer&field=col2:string&field=col3:integer", "child_layer", "memory" ); + mChildLayer = new QgsVectorLayer( QStringLiteral( "Point?field=parent:integer&field=col2:string&field=col3:integer" ), QStringLiteral( "child_layer" ), QStringLiteral( "memory" ) ); QVERIFY( mChildLayer->isValid() ); QgsFeature cf1( mChildLayer->dataProvider()->fields(), 1 ); - cf1.setAttribute( "parent", 4 ); - cf1.setAttribute( "col2", "test" ); - cf1.setAttribute( "col3", 2 ); + cf1.setAttribute( QStringLiteral( "parent" ), 4 ); + cf1.setAttribute( QStringLiteral( "col2" ), "test" ); + cf1.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature cf2( mChildLayer->dataProvider()->fields(), 2 ); - cf2.setAttribute( "parent", 4 ); - cf2.setAttribute( "col2", QVariant( QVariant::String ) ); - cf2.setAttribute( "col3", 1 ); + cf2.setAttribute( QStringLiteral( "parent" ), 4 ); + cf2.setAttribute( QStringLiteral( "col2" ), QVariant( QVariant::String ) ); + cf2.setAttribute( QStringLiteral( "col3" ), 1 ); QgsFeature cf3( mChildLayer->dataProvider()->fields(), 3 ); - cf3.setAttribute( "parent", 4 ); - cf3.setAttribute( "col2", "test333" ); - cf3.setAttribute( "col3", 2 ); + cf3.setAttribute( QStringLiteral( "parent" ), 4 ); + cf3.setAttribute( QStringLiteral( "col2" ), "test333" ); + cf3.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature cf4( mChildLayer->dataProvider()->fields(), 4 ); - cf4.setAttribute( "parent", 3 ); - cf4.setAttribute( "col2", "test4" ); - cf4.setAttribute( "col3", 2 ); + cf4.setAttribute( QStringLiteral( "parent" ), 3 ); + cf4.setAttribute( QStringLiteral( "col2" ), "test4" ); + cf4.setAttribute( QStringLiteral( "col3" ), 2 ); QgsFeature cf5( mChildLayer->dataProvider()->fields(), 5 ); - cf5.setAttribute( "parent", 3 ); - cf5.setAttribute( "col2", QVariant( QVariant::String ) ); - cf5.setAttribute( "col3", 7 ); + cf5.setAttribute( QStringLiteral( "parent" ), 3 ); + cf5.setAttribute( QStringLiteral( "col2" ), QVariant( QVariant::String ) ); + cf5.setAttribute( QStringLiteral( "col3" ), 7 ); mChildLayer->dataProvider()->addFeatures( QgsFeatureList() << cf1 << cf2 << cf3 << cf4 << cf5 ); QgsMapLayerRegistry::instance()->addMapLayer( mChildLayer ); QgsRelation rel; - rel.setRelationId( "my_rel" ); - rel.setRelationName( "relation name" ); + rel.setRelationId( QStringLiteral( "my_rel" ) ); + rel.setRelationName( QStringLiteral( "relation name" ) ); rel.setReferencedLayer( mAggregatesLayer->id() ); rel.setReferencingLayer( mChildLayer->id() ); - rel.addFieldPair( "parent", "col1" ); + rel.addFieldPair( QStringLiteral( "parent" ), QStringLiteral( "col1" ) ); QVERIFY( rel.isValid() ); QgsProject::instance()->relationManager()->addRelation( rel ); } @@ -259,7 +259,7 @@ class TestQgsExpression: public QObject char* new_locale = setlocale( LC_NUMERIC, nullptr ); qDebug( "New locale: %s", new_locale ); - QgsExpression exp( "1.23 + 4.56" ); + QgsExpression exp( QStringLiteral( "1.23 + 4.56" ) ); QVERIFY( !exp.hasParserError() ); setlocale( LC_NUMERIC, "" ); @@ -609,39 +609,39 @@ class TestQgsExpression: public QObject QTest::newRow( "num_geometries empty collection" ) << "num_geometries(geom_from_wkt('GEOMETRYCOLLECTION()'))" << false << QVariant( 0 ); QTest::newRow( "nodes_to_points not geom" ) << "nodes_to_points('g')" << true << QVariant(); QTest::newRow( "nodes_to_points null" ) << "nodes_to_points(NULL)" << false << QVariant(); - QTest::newRow( "nodes_to_points point" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POINT(1 2)')))" << false << QVariant( QString( "MultiPoint ((1 2))" ) ); - QTest::newRow( "nodes_to_points polygon" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))')))" << false << QVariant( QString( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2),(-1 -1))" ) ); + QTest::newRow( "nodes_to_points point" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POINT(1 2)')))" << false << QVariant( QStringLiteral( "MultiPoint ((1 2))" ) ); + QTest::newRow( "nodes_to_points polygon" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))')))" << false << QVariant( QStringLiteral( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2),(-1 -1))" ) ); QTest::newRow( "nodes_to_points polygon with rings" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1),(-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1),(-0.3 -0.9, -0.3 0, 4 -0.1, 0.1 2.1, -0.3 -0.9))')))" << false - << QVariant( QString( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2),(-1 -1),(-0.1 -0.1),(0.4 0),(0.4 0.2),(0 0.2),(-0.1 -0.1),(-0.3 -0.9),(-0.3 0),(4 -0.1),(0.1 2.1),(-0.3 -0.9))" ) ); + << QVariant( QStringLiteral( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2),(-1 -1),(-0.1 -0.1),(0.4 0),(0.4 0.2),(0 0.2),(-0.1 -0.1),(-0.3 -0.9),(-0.3 0),(4 -0.1),(0.1 2.1),(-0.3 -0.9))" ) ); QTest::newRow( "nodes_to_points line" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('LINESTRING(0 0, 1 1, 2 2)')))" << false - << QVariant( QString( "MultiPoint ((0 0),(1 1),(2 2))" ) ); + << QVariant( QStringLiteral( "MultiPoint ((0 0),(1 1),(2 2))" ) ); QTest::newRow( "nodes_to_points collection 1" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))')))" << false - << QVariant( QString( "MultiPoint ((0 1),(0 0),(1 0),(1 1))" ) ); + << QVariant( QStringLiteral( "MultiPoint ((0 1),(0 0),(1 0),(1 1))" ) ); QTest::newRow( "nodes_to_points collection 2" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('GEOMETRYCOLLECTION(POINTZM(0 1 2 3), POINTZM(0 0 3 4), POINTZM(1 1 5 6), POLYGONZM((-1 -1 7 8, 4 0 1 2, 4 2 7 6, 0 2 1 3, -1 -1 7 8),(-0.1 -0.1 5 4, 0.4 0 9 8, 0.4 0.2 7 10, 0 0.2 0 0, -0.1 -0.1 5 4),(-1 -1 0 0, 4 0 0 1, 4 2 1 2, 0 2 2 3, -1 -1 0 0)), POINTZM(1 0 1 2))')))" << false - << QVariant( QString( "MultiPointZM ((0 1 2 3),(0 0 3 4),(1 1 5 6),(-1 -1 7 8),(4 0 1 2),(4 2 7 6),(0 2 1 3),(-1 -1 7 8),(-0.1 -0.1 5 4),(0.4 0 9 8),(0.4 0.2 7 10),(0 0.2 0 0),(-0.1 -0.1 5 4),(-1 -1 0 0),(4 0 0 1),(4 2 1 2),(0 2 2 3),(-1 -1 0 0),(1 0 1 2))" ) ); + << QVariant( QStringLiteral( "MultiPointZM ((0 1 2 3),(0 0 3 4),(1 1 5 6),(-1 -1 7 8),(4 0 1 2),(4 2 7 6),(0 2 1 3),(-1 -1 7 8),(-0.1 -0.1 5 4),(0.4 0 9 8),(0.4 0.2 7 10),(0 0.2 0 0),(-0.1 -0.1 5 4),(-1 -1 0 0),(4 0 0 1),(4 2 1 2),(0 2 2 3),(-1 -1 0 0),(1 0 1 2))" ) ); QTest::newRow( "nodes_to_points empty collection" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('GEOMETRYCOLLECTION()')))" << false << - QVariant( QString( "MultiPoint ()" ) ); - QTest::newRow( "nodes_to_points no close polygon" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))'),true))" << false << QVariant( QString( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2))" ) ); + QVariant( QStringLiteral( "MultiPoint ()" ) ); + QTest::newRow( "nodes_to_points no close polygon" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))'),true))" << false << QVariant( QStringLiteral( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2))" ) ); QTest::newRow( "nodes_to_points no close polygon with rings" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1),(-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1),(-0.3 -0.9, -0.3 0, 4 -0.1, 0.1 2.1, -0.3 -0.9))'),true))" << false - << QVariant( QString( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2),(-0.1 -0.1),(0.4 0),(0.4 0.2),(0 0.2),(-0.3 -0.9),(-0.3 0),(4 -0.1),(0.1 2.1))" ) ); + << QVariant( QStringLiteral( "MultiPoint ((-1 -1),(4 0),(4 2),(0 2),(-0.1 -0.1),(0.4 0),(0.4 0.2),(0 0.2),(-0.3 -0.9),(-0.3 0),(4 -0.1),(0.1 2.1))" ) ); QTest::newRow( "nodes_to_points no close unclosed line" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('LINESTRING(0 0, 1 1, 2 2)'),true))" << false - << QVariant( QString( "MultiPoint ((0 0),(1 1),(2 2))" ) ); + << QVariant( QStringLiteral( "MultiPoint ((0 0),(1 1),(2 2))" ) ); QTest::newRow( "nodes_to_points no close closed line" ) << "geom_to_wkt(nodes_to_points(geom_from_wkt('LINESTRING(0 0, 1 1, 2 2, 0 0)'),true))" << false - << QVariant( QString( "MultiPoint ((0 0),(1 1),(2 2))" ) ); + << QVariant( QStringLiteral( "MultiPoint ((0 0),(1 1),(2 2))" ) ); QTest::newRow( "segments_to_lines not geom" ) << "segments_to_lines('g')" << true << QVariant(); QTest::newRow( "segments_to_lines null" ) << "segments_to_lines(NULL)" << false << QVariant(); - QTest::newRow( "segments_to_lines point" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('POINT(1 2)')))" << false << QVariant( QString( "MultiLineString ()" ) ); - QTest::newRow( "segments_to_lines polygon" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))')))" << false << QVariant( QString( "MultiLineString ((-1 -1, 4 0),(4 0, 4 2),(4 2, 0 2),(0 2, -1 -1))" ) ); + QTest::newRow( "segments_to_lines point" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('POINT(1 2)')))" << false << QVariant( QStringLiteral( "MultiLineString ()" ) ); + QTest::newRow( "segments_to_lines polygon" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))')))" << false << QVariant( QStringLiteral( "MultiLineString ((-1 -1, 4 0),(4 0, 4 2),(4 2, 0 2),(0 2, -1 -1))" ) ); QTest::newRow( "segments_to_lines polygon with rings" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1),(-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1),(-0.3 -0.9, -0.3 0, 4 -0.1, 0.1 2.1, -0.3 -0.9))')))" << false - << QVariant( QString( "MultiLineString ((-1 -1, 4 0),(4 0, 4 2),(4 2, 0 2),(0 2, -1 -1),(-0.1 -0.1, 0.4 0),(0.4 0, 0.4 0.2),(0.4 0.2, 0 0.2),(0 0.2, -0.1 -0.1),(-0.3 -0.9, -0.3 0),(-0.3 0, 4 -0.1),(4 -0.1, 0.1 2.1),(0.1 2.1, -0.3 -0.9))" ) ); + << QVariant( QStringLiteral( "MultiLineString ((-1 -1, 4 0),(4 0, 4 2),(4 2, 0 2),(0 2, -1 -1),(-0.1 -0.1, 0.4 0),(0.4 0, 0.4 0.2),(0.4 0.2, 0 0.2),(0 0.2, -0.1 -0.1),(-0.3 -0.9, -0.3 0),(-0.3 0, 4 -0.1),(4 -0.1, 0.1 2.1),(0.1 2.1, -0.3 -0.9))" ) ); QTest::newRow( "segments_to_lines line" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('LINESTRING(0 0, 1 1, 2 2)')))" << false - << QVariant( QString( "MultiLineString ((0 0, 1 1),(1 1, 2 2))" ) ); + << QVariant( QStringLiteral( "MultiLineString ((0 0, 1 1),(1 1, 2 2))" ) ); QTest::newRow( "segments_to_lines collection 1" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))')))" << false - << QVariant( QString( "MultiLineString ()" ) ); + << QVariant( QStringLiteral( "MultiLineString ()" ) ); QTest::newRow( "segments_to_lines collection 2" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('GEOMETRYCOLLECTION(POINTZM(0 1 2 3), LINESTRINGZM(0 0 1 2, 1 1 3 4, 2 2 5 6), POINTZM(1 1 5 6), POLYGONZM((-1 -1 7 8, 4 0 1 2, 4 2 7 6, 0 2 1 3, -1 -1 7 8)), POINTZM(1 0 1 2))')))" << false - << QVariant( QString( "MultiLineStringZM ((0 0 1 2, 1 1 3 4),(1 1 3 4, 2 2 5 6),(-1 -1 7 8, 4 0 1 2),(4 0 1 2, 4 2 7 6),(4 2 7 6, 0 2 1 3),(0 2 1 3, -1 -1 7 8))" ) ); + << QVariant( QStringLiteral( "MultiLineStringZM ((0 0 1 2, 1 1 3 4),(1 1 3 4, 2 2 5 6),(-1 -1 7 8, 4 0 1 2),(4 0 1 2, 4 2 7 6),(4 2 7 6, 0 2 1 3),(0 2 1 3, -1 -1 7 8))" ) ); QTest::newRow( "segments_to_lines empty collection" ) << "geom_to_wkt(segments_to_lines(geom_from_wkt('GEOMETRYCOLLECTION()')))" << false << - QVariant( QString( "MultiLineString ()" ) ); + QVariant( QStringLiteral( "MultiLineString ()" ) ); QTest::newRow( "length line" ) << "length(geom_from_wkt('LINESTRING(0 0, 4 0)'))" << false << QVariant( 4.0 ); QTest::newRow( "length polygon" ) << "length(geom_from_wkt('POLYGON((0 0, 4 0, 4 2, 0 2, 0 0))'))" << false << QVariant(); QTest::newRow( "length point" ) << "length(geom_from_wkt('POINT(0 0)'))" << false << QVariant(); @@ -662,7 +662,7 @@ class TestQgsExpression: public QObject QTest::newRow( "interior_ring_n point" ) << "interior_ring_n(geom_from_wkt('POINT(1 2)'), 1)" << false << QVariant(); QTest::newRow( "interior_ring_n polygon no rings" ) << "interior_ring_n(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))'),1)" << false << QVariant(); QTest::newRow( "interior_ring_n polygon with rings" ) << "geom_to_wkt(interior_ring_n(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1),(-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1),(-1 -1, 4 0, 4 2, 0 2, -1 -1))'),1))" << false - << QVariant( QString( "LineString (-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1)" ) ); + << QVariant( QStringLiteral( "LineString (-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1)" ) ); QTest::newRow( "interior_ring_n polygon with rings bad index 1" ) << "interior_ring_n(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1),(-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1),(-1 -1, 4 0, 4 2, 0 2, -1 -1))'),0)" << false << QVariant(); QTest::newRow( "interior_ring_n polygon with rings bad index 2" ) << "interior_ring_n(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1),(-0.1 -0.1, 0.4 0, 0.4 0.2, 0 0.2, -0.1 -0.1),(-1 -1, 4 0, 4 2, 0 2, -1 -1))'),3)" << false @@ -674,7 +674,7 @@ class TestQgsExpression: public QObject QTest::newRow( "geometry_n point" ) << "geometry_n(geom_from_wkt('POINT(1 2)'), 1)" << false << QVariant(); QTest::newRow( "geometry_n polygon" ) << "geometry_n(geom_from_wkt('POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))'),1)" << false << QVariant(); QTest::newRow( "geometry_n line" ) << "geometry_n(geom_from_wkt('LINESTRING(0 0, 1 1, 2 2)'), 1)" << false << QVariant(); - QTest::newRow( "geometry_n collection" ) << "geom_to_wkt(geometry_n(geom_from_wkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))'),3))" << false << QVariant( QString( "Point (1 0)" ) ); + QTest::newRow( "geometry_n collection" ) << "geom_to_wkt(geometry_n(geom_from_wkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))'),3))" << false << QVariant( QStringLiteral( "Point (1 0)" ) ); QTest::newRow( "geometry_n collection bad index 1" ) << "geometry_n(geom_from_wkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))'),0)" << false << QVariant(); QTest::newRow( "geometry_n collection bad index 2" ) << "geometry_n(geom_from_wkt('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))'),5)" << false << QVariant(); QTest::newRow( "boundary not geom" ) << "boundary('g')" << true << QVariant(); @@ -985,40 +985,40 @@ class TestQgsExpression: public QObject // layer_property tests QTest::newRow( "layer_property no layer" ) << "layer_property('','title')" << false << QVariant(); QTest::newRow( "layer_property bad layer" ) << "layer_property('bad','title')" << false << QVariant(); - QTest::newRow( "layer_property no property" ) << QString( "layer_property('%1','')" ).arg( mPointsLayer->name() ) << false << QVariant(); - QTest::newRow( "layer_property bad property" ) << QString( "layer_property('%1','bad')" ).arg( mPointsLayer->name() ) << false << QVariant(); - QTest::newRow( "layer_property by id" ) << QString( "layer_property('%1','name')" ).arg( mPointsLayer->id() ) << false << QVariant( mPointsLayer->name() ); - QTest::newRow( "layer_property name" ) << QString( "layer_property('%1','name')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->name() ); - QTest::newRow( "layer_property id" ) << QString( "layer_property('%1','id')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->id() ); - QTest::newRow( "layer_property title" ) << QString( "layer_property('%1','title')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->title() ); - QTest::newRow( "layer_property abstract" ) << QString( "layer_property('%1','abstract')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->abstract() ); - QTest::newRow( "layer_property keywords" ) << QString( "layer_property('%1','keywords')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->keywordList() ); - QTest::newRow( "layer_property data_url" ) << QString( "layer_property('%1','data_url')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->dataUrl() ); - QTest::newRow( "layer_property attribution" ) << QString( "layer_property('%1','attribution')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->attribution() ); - QTest::newRow( "layer_property attribution_url" ) << QString( "layer_property('%1','attribution_url')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->attributionUrl() ); - QTest::newRow( "layer_property source" ) << QString( "layer_property('%1','source')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->publicSource() ); - QTest::newRow( "layer_property min_scale" ) << QString( "layer_property('%1','min_scale')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->minimumScale() ); - QTest::newRow( "layer_property max_scale" ) << QString( "layer_property('%1','max_scale')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->maximumScale() ); - QTest::newRow( "layer_property crs" ) << QString( "layer_property('%1','crs')" ).arg( mPointsLayer->name() ) << false << QVariant( "EPSG:4326" ); - QTest::newRow( "layer_property extent" ) << QString( "geom_to_wkt(layer_property('%1','extent'))" ).arg( mPointsLayer->name() ) << false << QVariant( "Polygon ((-118.88888889 22.80020704, -83.33333333 22.80020704, -83.33333333 46.87198068, -118.88888889 46.87198068, -118.88888889 22.80020704))" ); - QTest::newRow( "layer_property type" ) << QString( "layer_property('%1','type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Vector" ); - QTest::newRow( "layer_property storage_type" ) << QString( "layer_property('%1','storage_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "ESRI Shapefile" ); - QTest::newRow( "layer_property geometry_type" ) << QString( "layer_property('%1','geometry_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Point" ); + QTest::newRow( "layer_property no property" ) << QStringLiteral( "layer_property('%1','')" ).arg( mPointsLayer->name() ) << false << QVariant(); + QTest::newRow( "layer_property bad property" ) << QStringLiteral( "layer_property('%1','bad')" ).arg( mPointsLayer->name() ) << false << QVariant(); + QTest::newRow( "layer_property by id" ) << QStringLiteral( "layer_property('%1','name')" ).arg( mPointsLayer->id() ) << false << QVariant( mPointsLayer->name() ); + QTest::newRow( "layer_property name" ) << QStringLiteral( "layer_property('%1','name')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->name() ); + QTest::newRow( "layer_property id" ) << QStringLiteral( "layer_property('%1','id')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->id() ); + QTest::newRow( "layer_property title" ) << QStringLiteral( "layer_property('%1','title')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->title() ); + QTest::newRow( "layer_property abstract" ) << QStringLiteral( "layer_property('%1','abstract')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->abstract() ); + QTest::newRow( "layer_property keywords" ) << QStringLiteral( "layer_property('%1','keywords')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->keywordList() ); + QTest::newRow( "layer_property data_url" ) << QStringLiteral( "layer_property('%1','data_url')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->dataUrl() ); + QTest::newRow( "layer_property attribution" ) << QStringLiteral( "layer_property('%1','attribution')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->attribution() ); + QTest::newRow( "layer_property attribution_url" ) << QStringLiteral( "layer_property('%1','attribution_url')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->attributionUrl() ); + QTest::newRow( "layer_property source" ) << QStringLiteral( "layer_property('%1','source')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->publicSource() ); + QTest::newRow( "layer_property min_scale" ) << QStringLiteral( "layer_property('%1','min_scale')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->minimumScale() ); + QTest::newRow( "layer_property max_scale" ) << QStringLiteral( "layer_property('%1','max_scale')" ).arg( mPointsLayer->name() ) << false << QVariant( mPointsLayer->maximumScale() ); + QTest::newRow( "layer_property crs" ) << QStringLiteral( "layer_property('%1','crs')" ).arg( mPointsLayer->name() ) << false << QVariant( "EPSG:4326" ); + QTest::newRow( "layer_property extent" ) << QStringLiteral( "geom_to_wkt(layer_property('%1','extent'))" ).arg( mPointsLayer->name() ) << false << QVariant( "Polygon ((-118.88888889 22.80020704, -83.33333333 22.80020704, -83.33333333 46.87198068, -118.88888889 46.87198068, -118.88888889 22.80020704))" ); + QTest::newRow( "layer_property type" ) << QStringLiteral( "layer_property('%1','type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Vector" ); + QTest::newRow( "layer_property storage_type" ) << QStringLiteral( "layer_property('%1','storage_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "ESRI Shapefile" ); + QTest::newRow( "layer_property geometry_type" ) << QStringLiteral( "layer_property('%1','geometry_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Point" ); //test conversions to bool - QTest::newRow( "feature to bool false" ) << QString( "case when get_feature('none','none',499) then true else false end" ) << false << QVariant( false ); - QTest::newRow( "feature to bool true" ) << QString( "case when get_feature('test','col1',10) then true else false end" ) << false << QVariant( true ); - QTest::newRow( "geometry to bool false" ) << QString( "case when geom_from_wkt('') then true else false end" ) << false << QVariant( false ); - QTest::newRow( "geometry to bool true" ) << QString( "case when geom_from_wkt('Point(3 4)') then true else false end" ) << false << QVariant( true ); + QTest::newRow( "feature to bool false" ) << QStringLiteral( "case when get_feature('none','none',499) then true else false end" ) << false << QVariant( false ); + QTest::newRow( "feature to bool true" ) << QStringLiteral( "case when get_feature('test','col1',10) then true else false end" ) << false << QVariant( true ); + QTest::newRow( "geometry to bool false" ) << QStringLiteral( "case when geom_from_wkt('') then true else false end" ) << false << QVariant( false ); + QTest::newRow( "geometry to bool true" ) << QStringLiteral( "case when geom_from_wkt('Point(3 4)') then true else false end" ) << false << QVariant( true ); // is not - QTest::newRow( "1 is (not 2)" ) << QString( "1 is (not 2)" ) << false << QVariant( 0 ); - QTest::newRow( "1 is not 2" ) << QString( "1 is not 2" ) << false << QVariant( 1 ); - QTest::newRow( "1 is not 2" ) << QString( "1 is not 2" ) << false << QVariant( 1 ); + QTest::newRow( "1 is (not 2)" ) << QStringLiteral( "1 is (not 2)" ) << false << QVariant( 0 ); + QTest::newRow( "1 is not 2" ) << QStringLiteral( "1 is not 2" ) << false << QVariant( 1 ); + QTest::newRow( "1 is not 2" ) << QStringLiteral( "1 is not 2" ) << false << QVariant( 1 ); // not like - QTest::newRow( "'a' not like 'a%'" ) << QString( "'a' not like 'a%'" ) << false << QVariant( 0 ); - QTest::newRow( "'a' not like 'a%'" ) << QString( "'a' not like 'a%'" ) << false << QVariant( 0 ); + QTest::newRow( "'a' not like 'a%'" ) << QStringLiteral( "'a' not like 'a%'" ) << false << QVariant( 0 ); + QTest::newRow( "'a' not like 'a%'" ) << QStringLiteral( "'a' not like 'a%'" ) << false << QVariant( 0 ); } void run_evaluation_test( QgsExpression& exp, bool evalError, QVariant& expected ) @@ -1112,9 +1112,9 @@ class TestQgsExpression: public QObject void eval_columns() { QgsFields fields; - fields.append( QgsField( "x1" ) ); - fields.append( QgsField( "x2" ) ); - fields.append( QgsField( "foo", QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "x1" ) ) ); + fields.append( QgsField( QStringLiteral( "x2" ) ) ); + fields.append( QgsField( QStringLiteral( "foo" ), QVariant::Int ) ); QgsFeature f; f.initAttributes( 3 ); @@ -1123,7 +1123,7 @@ class TestQgsExpression: public QObject QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, fields ); // good exp - QgsExpression exp( "foo + 1" ); + QgsExpression exp( QStringLiteral( "foo + 1" ) ); bool prepareRes = exp.prepare( &context ); QCOMPARE( prepareRes, true ); QCOMPARE( exp.hasEvalError(), false ); @@ -1132,7 +1132,7 @@ class TestQgsExpression: public QObject QCOMPARE( res.toInt(), 21 ); // bad exp - QgsExpression exp2( "bar + 1" ); + QgsExpression exp2( QStringLiteral( "bar + 1" ) ); bool prepareRes2 = exp2.prepare( &context ); QCOMPARE( prepareRes2, false ); QCOMPARE( exp2.hasEvalError(), true ); @@ -1143,7 +1143,7 @@ class TestQgsExpression: public QObject void eval_feature_id() { QgsFeature f( 100 ); - QgsExpression exp( "$id * 2" ); + QgsExpression exp( QStringLiteral( "$id * 2" ) ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); QVariant v = exp.evaluate( &context ); QCOMPARE( v.toInt(), 200 ); @@ -1152,7 +1152,7 @@ class TestQgsExpression: public QObject void eval_current_feature() { QgsFeature f( 100 ); - QgsExpression exp( "$currentfeature" ); + QgsExpression exp( QStringLiteral( "$currentfeature" ) ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); QVariant v = exp.evaluate( &context ); QgsFeature evalFeature = v.value(); @@ -1163,17 +1163,17 @@ class TestQgsExpression: public QObject { QgsFeature f( 100 ); QgsFields fields; - fields.append( QgsField( "col1" ) ); - fields.append( QgsField( "second_column", QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "col1" ) ) ); + fields.append( QgsField( QStringLiteral( "second_column" ), QVariant::Int ) ); f.setFields( fields, true ); - f.setAttribute( QString( "col1" ), QString( "test value" ) ); - f.setAttribute( QString( "second_column" ), 5 ); - QgsExpression exp( "attribute($currentfeature,'col1')" ); + f.setAttribute( QStringLiteral( "col1" ), QStringLiteral( "test value" ) ); + f.setAttribute( QStringLiteral( "second_column" ), 5 ); + QgsExpression exp( QStringLiteral( "attribute($currentfeature,'col1')" ) ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); QVariant v = exp.evaluate( &context ); QCOMPARE( v.toString(), QString( "test value" ) ); - QgsExpression exp2( "attribute($currentfeature,'second'||'_column')" ); + QgsExpression exp2( QStringLiteral( "attribute($currentfeature,'second'||'_column')" ) ); v = exp2.evaluate( &context ); QCOMPARE( v.toInt(), 5 ); } @@ -1197,8 +1197,8 @@ class TestQgsExpression: public QObject QTest::newRow( "get_feature 8" ) << "get_feature('test','col2','test4')" << true << 4; //by layer id - QTest::newRow( "get_feature 3" ) << QString( "get_feature('%1','col1',11)" ).arg( mMemoryLayer->id() ) << true << 2; - QTest::newRow( "get_feature 4" ) << QString( "get_feature('%1','col2','test2')" ).arg( mMemoryLayer->id() ) << true << 2; + QTest::newRow( "get_feature 3" ) << QStringLiteral( "get_feature('%1','col1',11)" ).arg( mMemoryLayer->id() ) << true << 2; + QTest::newRow( "get_feature 4" ) << QStringLiteral( "get_feature('%1','col2','test2')" ).arg( mMemoryLayer->id() ) << true << 2; //no matching features QTest::newRow( "get_feature no match1" ) << "get_feature('test','col1',499)" << false << -1; @@ -1249,7 +1249,7 @@ class TestQgsExpression: public QObject QTest::newRow( "string aggregate 2" ) << "aggregate('test','min_length',\"col2\")" << false << QVariant( 5 ); QTest::newRow( "string concatenate" ) << "aggregate('test','concatenate',\"col2\",concatenator:=' , ')" << false << QVariant( "test1 , test2 , test3 , test4" ); - QTest::newRow( "geometry collect" ) << "geom_to_wkt(aggregate('aggregate_layer','collect',$geometry))" << false << QVariant( QString( "MultiPoint ((0 0),(1 0),(2 0),(3 0),(4 0),(5 0))" ) ); + QTest::newRow( "geometry collect" ) << "geom_to_wkt(aggregate('aggregate_layer','collect',$geometry))" << false << QVariant( QStringLiteral( "MultiPoint ((0 0),(1 0),(2 0),(3 0),(4 0),(5 0))" ) ); QTest::newRow( "sub expression" ) << "aggregate('test','sum',\"col1\" * 2)" << false << QVariant( 65 * 2 ); QTest::newRow( "bad sub expression" ) << "aggregate('test','sum',\"xcvxcv\" * 2)" << true << QVariant(); @@ -1264,7 +1264,7 @@ class TestQgsExpression: public QObject { QgsExpressionContext context; QgsExpressionContextScope* scope = new QgsExpressionContextScope(); - scope->setVariable( "test_var", 10 ); + scope->setVariable( QStringLiteral( "test_var" ), 10 ); context << scope; QFETCH( QString, string ); @@ -1279,7 +1279,7 @@ class TestQgsExpression: public QObject QVariant res; //try evaluating once without context (only if variables aren't required) - if ( !string.contains( "@" ) ) + if ( !string.contains( QLatin1String( "@" ) ) ) { res = exp.evaluate(); if ( exp.hasEvalError() ) @@ -1327,7 +1327,7 @@ class TestQgsExpression: public QObject QTest::newRow( "max_length" ) << "max_length(\"col2\")" << false << QVariant( 7 ); QTest::newRow( "concatenate" ) << "concatenate(\"col2\",concatenator:=',')" << false << QVariant( "test,,test333,test4,,test4" ); - QTest::newRow( "geometry collect" ) << "geom_to_wkt(collect($geometry))" << false << QVariant( QString( "MultiPoint ((0 0),(1 0),(2 0),(3 0),(4 0),(5 0))" ) ); + QTest::newRow( "geometry collect" ) << "geom_to_wkt(collect($geometry))" << false << QVariant( QStringLiteral( "MultiPoint ((0 0),(1 0),(2 0),(3 0),(4 0),(5 0))" ) ); QTest::newRow( "bad expression" ) << "sum(\"xcvxcvcol1\")" << true << QVariant(); QTest::newRow( "aggregate named" ) << "sum(expression:=\"col1\")" << false << QVariant( 24.0 ); @@ -1352,9 +1352,9 @@ class TestQgsExpression: public QObject context.appendScope( QgsExpressionContextUtils::layerScope( mAggregatesLayer ) ); QgsFeature af1( mAggregatesLayer->dataProvider()->fields(), 1 ); - af1.setAttribute( "col1", 4 ); - af1.setAttribute( "col2", "test" ); - af1.setAttribute( "col3", 2 ); + af1.setAttribute( QStringLiteral( "col1" ), 4 ); + af1.setAttribute( QStringLiteral( "col2" ), "test" ); + af1.setAttribute( QStringLiteral( "col3" ), 2 ); context.setFeature( af1 ); QFETCH( QString, string ); @@ -1415,7 +1415,7 @@ class TestQgsExpression: public QObject context.appendScope( QgsExpressionContextUtils::layerScope( mAggregatesLayer ) ); QgsFeature af1( mAggregatesLayer->dataProvider()->fields(), 1 ); - af1.setAttribute( "col1", parentKey ); + af1.setAttribute( QStringLiteral( "col1" ), parentKey ); context.setFeature( af1 ); QgsExpression exp( string ); @@ -1441,7 +1441,7 @@ class TestQgsExpression: public QObject void get_feature_geometry() { //test that get_feature fetches feature's geometry - QgsExpression exp( QString( "x(geometry(get_feature('%1','heading',340)))" ).arg( mPointsLayer->id() ) ); + QgsExpression exp( QStringLiteral( "x(geometry(get_feature('%1','heading',340)))" ).arg( mPointsLayer->id() ) ); QCOMPARE( exp.hasParserError(), false ); if ( exp.hasParserError() ) qDebug() << exp.parserErrorString(); @@ -1456,34 +1456,34 @@ class TestQgsExpression: public QObject void eval_rand() { - QgsExpression exp1( "rand(1,10)" ); + QgsExpression exp1( QStringLiteral( "rand(1,10)" ) ); QVariant v1 = exp1.evaluate(); QCOMPARE( v1.toInt() <= 10, true ); QCOMPARE( v1.toInt() >= 1, true ); - QgsExpression exp2( "rand(min:=-5,max:=-5)" ); + QgsExpression exp2( QStringLiteral( "rand(min:=-5,max:=-5)" ) ); QVariant v2 = exp2.evaluate(); QCOMPARE( v2.toInt(), -5 ); // Invalid expression since max= 1.5, true ); - QgsExpression exp2( "randf(min:=-0.0005,max:=-0.0005)" ); + QgsExpression exp2( QStringLiteral( "randf(min:=-0.0005,max:=-0.0005)" ) ); QVariant v2 = exp2.evaluate(); QCOMPARE( v2.toDouble(), -0.0005 ); // Invalid expression since max expectedCols; - expectedCols << "foo" << "bar" << "ppp" << "qqq" << "rrr"; - QgsExpression exp( "length(Bar || FOO) = 4 or foo + sqrt(bar) > 0 or case when ppp then qqq else rrr end" ); + expectedCols << QStringLiteral( "foo" ) << QStringLiteral( "bar" ) << QStringLiteral( "ppp" ) << QStringLiteral( "qqq" ) << QStringLiteral( "rrr" ); + QgsExpression exp( QStringLiteral( "length(Bar || FOO) = 4 or foo + sqrt(bar) > 0 or case when ppp then qqq else rrr end" ) ); QCOMPARE( exp.hasParserError(), false ); QSet refCols = exp.referencedColumns(); // make sure we have lower case @@ -1505,7 +1505,7 @@ class TestQgsExpression: public QObject void referenced_columns_all_attributes() { - QgsExpression exp( "attribute($currentfeature,'test')" ); + QgsExpression exp( QStringLiteral( "attribute($currentfeature,'test')" ) ); QCOMPARE( exp.hasParserError(), false ); QSet refCols = exp.referencedColumns(); // make sure we get the all attributes flag @@ -1599,22 +1599,22 @@ class TestQgsExpression: public QObject QgsExpressionContext context; - QgsExpression exp1( "$area" ); + QgsExpression exp1( QStringLiteral( "$area" ) ); context.setFeature( fPolygon ); QVariant vArea = exp1.evaluate( &context ); QCOMPARE( vArea.toDouble(), 40. ); - QgsExpression exp2( "$length" ); + QgsExpression exp2( QStringLiteral( "$length" ) ); context.setFeature( fPolyline ); QVariant vLength = exp2.evaluate( &context ); QCOMPARE( vLength.toDouble(), 10. ); - QgsExpression exp3( "$perimeter" ); + QgsExpression exp3( QStringLiteral( "$perimeter" ) ); context.setFeature( fPolygon ); QVariant vPerimeter = exp3.evaluate( &context ); QCOMPARE( vPerimeter.toDouble(), 26. ); - QgsExpression deprecatedExpXAt( "$x_at(1)" ); + QgsExpression deprecatedExpXAt( QStringLiteral( "$x_at(1)" ) ); context.setFeature( fPolygon ); QVariant xAt = deprecatedExpXAt.evaluate( &context ); QCOMPARE( xAt.toDouble(), 10.0 ); @@ -1622,26 +1622,26 @@ class TestQgsExpression: public QObject xAt = deprecatedExpXAt.evaluate( &context ); QCOMPARE( xAt.toDouble(), 10.0 ); - QgsExpression deprecatedExpXAtNeg( "$x_at(-2)" ); + QgsExpression deprecatedExpXAtNeg( QStringLiteral( "$x_at(-2)" ) ); context.setFeature( fPolygon ); xAt = deprecatedExpXAtNeg.evaluate( &context ); QCOMPARE( xAt.toDouble(), 2.0 ); - QgsExpression deprecatedExpYAt( "$y_at(2)" ); + QgsExpression deprecatedExpYAt( QStringLiteral( "$y_at(2)" ) ); context.setFeature( fPolygon ); QVariant yAt = deprecatedExpYAt.evaluate( &context ); QCOMPARE( yAt.toDouble(), 6.0 ); - QgsExpression deprecatedExpYAt2( "$y_at(1)" ); + QgsExpression deprecatedExpYAt2( QStringLiteral( "$y_at(1)" ) ); context.setFeature( fPolyline ); yAt = deprecatedExpYAt2.evaluate( &context ); QCOMPARE( yAt.toDouble(), 0.0 ); - QgsExpression deprecatedExpYAtNeg( "$y_at(-2)" ); + QgsExpression deprecatedExpYAtNeg( QStringLiteral( "$y_at(-2)" ) ); context.setFeature( fPolygon ); yAt = deprecatedExpYAtNeg.evaluate( &context ); QCOMPARE( yAt.toDouble(), 6.0 ); - QgsExpression expXAt( "x_at(1)" ); + QgsExpression expXAt( QStringLiteral( "x_at(1)" ) ); context.setFeature( fPolygon ); xAt = expXAt.evaluate( &context ); QCOMPARE( xAt.toDouble(), 10.0 ); @@ -1649,65 +1649,65 @@ class TestQgsExpression: public QObject xAt = expXAt.evaluate( &context ); QCOMPARE( xAt.toDouble(), 10.0 ); - QgsExpression expXAtNeg( "x_at(-2)" ); + QgsExpression expXAtNeg( QStringLiteral( "x_at(-2)" ) ); context.setFeature( fPolygon ); xAt = expXAtNeg.evaluate( &context ); QCOMPARE( xAt.toDouble(), 2.0 ); - QgsExpression expYAt( "y_at(2)" ); + QgsExpression expYAt( QStringLiteral( "y_at(2)" ) ); context.setFeature( fPolygon ); yAt = expYAt.evaluate( &context ); QCOMPARE( yAt.toDouble(), 6.0 ); - QgsExpression expYAt2( "$y_at(1)" ); + QgsExpression expYAt2( QStringLiteral( "$y_at(1)" ) ); context.setFeature( fPolyline ); yAt = expYAt2.evaluate( &context ); QCOMPARE( yAt.toDouble(), 0.0 ); - QgsExpression expYAtNeg( "y_at(-2)" ); + QgsExpression expYAtNeg( QStringLiteral( "y_at(-2)" ) ); context.setFeature( fPolygon ); yAt = expYAtNeg.evaluate( &context ); QCOMPARE( yAt.toDouble(), 6.0 ); - QgsExpression exp4( "bounds_width($geometry)" ); + QgsExpression exp4( QStringLiteral( "bounds_width($geometry)" ) ); context.setFeature( fPolygon ); QVariant vBoundsWidth = exp4.evaluate( &context ); QCOMPARE( vBoundsWidth.toDouble(), 8.0 ); - QgsExpression exp5( "bounds_height($geometry)" ); + QgsExpression exp5( QStringLiteral( "bounds_height($geometry)" ) ); QVariant vBoundsHeight = exp5.evaluate( &context ); QCOMPARE( vBoundsHeight.toDouble(), 5.0 ); - QgsExpression exp6( "xmin($geometry)" ); + QgsExpression exp6( QStringLiteral( "xmin($geometry)" ) ); QVariant vXMin = exp6.evaluate( &context ); QCOMPARE( vXMin.toDouble(), 2.0 ); - QgsExpression exp7( "xmax($geometry)" ); + QgsExpression exp7( QStringLiteral( "xmax($geometry)" ) ); QVariant vXMax = exp7.evaluate( &context ); QCOMPARE( vXMax.toDouble(), 10.0 ); - QgsExpression exp8( "ymin($geometry)" ); + QgsExpression exp8( QStringLiteral( "ymin($geometry)" ) ); QVariant vYMin = exp8.evaluate( &context ); QCOMPARE( vYMin.toDouble(), 1.0 ); - QgsExpression exp9( "ymax($geometry)" ); + QgsExpression exp9( QStringLiteral( "ymax($geometry)" ) ); QVariant vYMax = exp9.evaluate( &context ); QCOMPARE( vYMax.toDouble(), 6.0 ); - QgsExpression exp10( "num_points($geometry)" ); + QgsExpression exp10( QStringLiteral( "num_points($geometry)" ) ); QVariant vVertices = exp10.evaluate( &context ); QCOMPARE( vVertices.toInt(), 5 ); context.setFeature( fPolyline ); - QgsExpression exp11( "length($geometry)" ); + QgsExpression exp11( QStringLiteral( "length($geometry)" ) ); QVariant vLengthLine = exp11.evaluate( &context ); QCOMPARE( vLengthLine.toDouble(), 10.0 ); context.setFeature( fPolygon ); - QgsExpression exp12( "area($geometry)" ); + QgsExpression exp12( QStringLiteral( "area($geometry)" ) ); QVariant vAreaPoly = exp12.evaluate( &context ); QCOMPARE( vAreaPoly.toDouble(), 40.0 ); - QgsExpression exp13( "perimeter($geometry)" ); + QgsExpression exp13( QStringLiteral( "perimeter($geometry)" ) ); QVariant vPerimeterPoly = exp13.evaluate( &context ); QCOMPARE( vPerimeterPoly.toDouble(), 26.0 ); } @@ -1716,8 +1716,8 @@ class TestQgsExpression: public QObject { //test calculations with and without geometry calculator set QgsDistanceArea da; - da.setSourceAuthId( "EPSG:3111" ); - da.setEllipsoid( "WGS84" ); + da.setSourceAuthId( QStringLiteral( "EPSG:3111" ) ); + da.setEllipsoid( QStringLiteral( "WGS84" ) ); da.setEllipsoidalMode( true ); QgsFeature feat; @@ -1731,7 +1731,7 @@ class TestQgsExpression: public QObject context.setFeature( feat ); // test area without geomCalculator - QgsExpression expArea( "$area" ); + QgsExpression expArea( QStringLiteral( "$area" ) ); QVariant vArea = expArea.evaluate( &context ); double expected = 1005640568.0; QVERIFY( qgsDoubleNear( vArea.toDouble(), expected, 1.0 ) ); @@ -1744,7 +1744,7 @@ class TestQgsExpression: public QObject QVERIFY( qgsDoubleNear( vArea.toDouble(), expected, 1.0 ) ); // test area with geomCalculator - QgsExpression expArea2( "$area" ); + QgsExpression expArea2( QStringLiteral( "$area" ) ); expArea2.setGeomCalculator( &da ); vArea = expArea2.evaluate( &context ); expected = 1009089817.0; @@ -1762,7 +1762,7 @@ class TestQgsExpression: public QObject QVERIFY( qgsDoubleNear( vArea.toDouble(), expected, 0.001 ) ); // test perimeter without geomCalculator - QgsExpression expPerimeter( "$perimeter" ); + QgsExpression expPerimeter( QStringLiteral( "$perimeter" ) ); QVariant vPerimeter = expPerimeter.evaluate( &context ); expected = 128282.086; QVERIFY( qgsDoubleNear( vPerimeter.toDouble(), expected, 0.001 ) ); @@ -1775,7 +1775,7 @@ class TestQgsExpression: public QObject QVERIFY( qgsDoubleNear( vPerimeter.toDouble(), expected, 0.001 ) ); // test perimeter with geomCalculator - QgsExpression expPerimeter2( "$perimeter" ); + QgsExpression expPerimeter2( QStringLiteral( "$perimeter" ) ); expPerimeter2.setGeomCalculator( &da ); vPerimeter = expPerimeter2.evaluate( &context ); expected = 128289.074; @@ -1799,7 +1799,7 @@ class TestQgsExpression: public QObject feat.setGeometry( line3111G ); context.setFeature( feat ); - QgsExpression expLength( "$length" ); + QgsExpression expLength( QStringLiteral( "$length" ) ); QVariant vLength = expLength.evaluate( &context ); expected = 26930.637; QVERIFY( qgsDoubleNear( vLength.toDouble(), expected, 0.001 ) ); @@ -1812,7 +1812,7 @@ class TestQgsExpression: public QObject QVERIFY( qgsDoubleNear( vLength.toDouble(), expected, 0.001 ) ); // test length with geomCalculator - QgsExpression expLength2( "$length" ); + QgsExpression expLength2( QStringLiteral( "$length" ) ); expLength2.setGeomCalculator( &da ); vLength = expLength2.evaluate( &context ); expected = 26932.156; @@ -1849,22 +1849,22 @@ class TestQgsExpression: public QObject QgsExpressionContext context; - QgsExpression exp1( "geomToWKT($geometry)" ); + QgsExpression exp1( QStringLiteral( "geomToWKT($geometry)" ) ); context.setFeature( fPolyline ); QVariant vWktLine = exp1.evaluate( &context ); QCOMPARE( vWktLine.toString(), QString( "LineString (0 0, 10 0)" ) ); - QgsExpression exp2( "geomToWKT($geometry)" ); + QgsExpression exp2( QStringLiteral( "geomToWKT($geometry)" ) ); context.setFeature( fPolygon ); QVariant vWktPolygon = exp2.evaluate( &context ); QCOMPARE( vWktPolygon.toString(), QString( "Polygon ((2 1, 10 1, 10 6, 2 6, 2 1))" ) ); - QgsExpression exp3( "geomToWKT($geometry)" ); + QgsExpression exp3( QStringLiteral( "geomToWKT($geometry)" ) ); context.setFeature( fPoint ); QVariant vWktPoint = exp3.evaluate( &context ); QCOMPARE( vWktPoint.toString(), QString( "Point (-1.23456789 9.87654321)" ) ); - QgsExpression exp4( "geomToWKT($geometry, 3)" ); + QgsExpression exp4( QStringLiteral( "geomToWKT($geometry, 3)" ) ); QVariant vWktPointSimplify = exp4.evaluate( &context ); QCOMPARE( vWktPointSimplify.toString(), QString( "Point (-1.235 9.877)" ) ); } @@ -1955,9 +1955,9 @@ class TestQgsExpression: public QObject QTest::newRow( "geometry Polygon" ) << "geometry( $currentfeature )" << QgsGeometry::fromPolygon( polygon ) << false << true; QgsCoordinateReferenceSystem s; - s.createFromOgcWmsCrs( "EPSG:4326" ); + s.createFromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); QgsCoordinateReferenceSystem d; - d.createFromOgcWmsCrs( "EPSG:3857" ); + d.createFromOgcWmsCrs( QStringLiteral( "EPSG:3857" ) ); QgsCoordinateTransform t( s, d ); QgsGeometry tLine = QgsGeometry::fromPolyline( line ); @@ -2078,25 +2078,25 @@ class TestQgsExpression: public QObject QTest::newRow( "union" ) << "union( $geometry, geomFromWKT('" + pnt2.exportToWkt() + "') )" << pnt1 << false << true << pnt1.combine( pnt2 ); geom = QgsGeometry::fromPolygon( polygon ); - QTest::newRow( "intersection" ) << "intersection( $geometry, geomFromWKT('POLYGON((0 0, 0 10, 10 0, 0 0))') )" << geom << false << true << QgsGeometry::fromWkt( "POLYGON ((0 0,5 5,10 0,0 0))" ); + QTest::newRow( "intersection" ) << "intersection( $geometry, geomFromWKT('POLYGON((0 0, 0 10, 10 0, 0 0))') )" << geom << false << true << QgsGeometry::fromWkt( QStringLiteral( "POLYGON ((0 0,5 5,10 0,0 0))" ) ); geom = QgsGeometry::fromPolygon( polygon ); - QTest::newRow( "difference" ) << "difference( $geometry, geomFromWKT('POLYGON((0 0, 0 10, 10 0, 0 0))') )" << geom << false << true << QgsGeometry::fromWkt( "POLYGON ((5 5,10 10,10 0,5 5))" ); + QTest::newRow( "difference" ) << "difference( $geometry, geomFromWKT('POLYGON((0 0, 0 10, 10 0, 0 0))') )" << geom << false << true << QgsGeometry::fromWkt( QStringLiteral( "POLYGON ((5 5,10 10,10 0,5 5))" ) ); geom = QgsGeometry::fromPolygon( polygon ); - QTest::newRow( "symDifference" ) << "symDifference( $geometry, geomFromWKT('POLYGON((0 0, 0 10, 10 0, 0 0))') )" << geom << false << true << QgsGeometry::fromWkt( "MULTIPOLYGON(((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))" ); + QTest::newRow( "symDifference" ) << "symDifference( $geometry, geomFromWKT('POLYGON((0 0, 0 10, 10 0, 0 0))') )" << geom << false << true << QgsGeometry::fromWkt( QStringLiteral( "MULTIPOLYGON(((5 5,0 0,0 10,5 5)),((5 5,10 10,10 0,5 5)))" ) ); geom = QgsGeometry::fromPolygon( polygon ); QTest::newRow( "convexHull simple" ) << "convexHull( $geometry )" << geom << false << true << geom.convexHull(); geom = QgsGeometry::fromPolygon( polygon ); - QTest::newRow( "convexHull multi" ) << "convexHull( geomFromWKT('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))') )" << geom << false << false << QgsGeometry::fromWkt( "POLYGON ((0 0,0 1,1 1,1 0,0 0))" ); + QTest::newRow( "convexHull multi" ) << "convexHull( geomFromWKT('GEOMETRYCOLLECTION(POINT(0 1), POINT(0 0), POINT(1 0), POINT(1 1))') )" << geom << false << false << QgsGeometry::fromWkt( QStringLiteral( "POLYGON ((0 0,0 1,1 1,1 0,0 0))" ) ); geom = QgsGeometry::fromPolygon( polygon ); QTest::newRow( "bounds" ) << "bounds( $geometry )" << geom << false << true << QgsGeometry::fromRect( geom.boundingBox() ); geom = QgsGeometry::fromPolygon( polygon ); - QTest::newRow( "translate" ) << "translate( $geometry, 1, 2)" << geom << false << true << QgsGeometry::fromWkt( "POLYGON ((1 2,11 12,11 2,1 2))" ); + QTest::newRow( "translate" ) << "translate( $geometry, 1, 2)" << geom << false << true << QgsGeometry::fromWkt( QStringLiteral( "POLYGON ((1 2,11 12,11 2,1 2))" ) ); geom = QgsGeometry::fromPolyline( line ); - QTest::newRow( "translate" ) << "translate( $geometry, -1, 2)" << geom << false << true << QgsGeometry::fromWkt( "LINESTRING (-1 2, 9 12)" ); + QTest::newRow( "translate" ) << "translate( $geometry, -1, 2)" << geom << false << true << QgsGeometry::fromWkt( QStringLiteral( "LINESTRING (-1 2, 9 12)" ) ); geom = QgsGeometry::fromPoint( point ); - QTest::newRow( "translate" ) << "translate( $geometry, 1, -2)" << geom << false << true << QgsGeometry::fromWkt( "POINT(1 -2)" ); + QTest::newRow( "translate" ) << "translate( $geometry, 1, -2)" << geom << false << true << QgsGeometry::fromWkt( QStringLiteral( "POINT(1 -2)" ) ); } void eval_geometry_method() @@ -2127,28 +2127,28 @@ class TestQgsExpression: public QObject { QgsFeature f( 100 ); QgsFields fields; - fields.append( QgsField( "col1" ) ); - fields.append( QgsField( "second_column", QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "col1" ) ) ); + fields.append( QgsField( QStringLiteral( "second_column" ), QVariant::Int ) ); f.setFields( fields, true ); - f.setAttribute( QString( "col1" ), QString( "test value" ) ); - f.setAttribute( QString( "second_column" ), 5 ); + f.setAttribute( QStringLiteral( "col1" ), QStringLiteral( "test value" ) ); + f.setAttribute( QStringLiteral( "second_column" ), 5 ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); - QgsExpression exp1( "eval()" ); + QgsExpression exp1( QStringLiteral( "eval()" ) ); QVariant v1 = exp1.evaluate( &context ); Q_ASSERT( !v1.isValid() ); - QgsExpression exp2( "eval('4')" ); + QgsExpression exp2( QStringLiteral( "eval('4')" ) ); QVariant v2 = exp2.evaluate( &context ); QCOMPARE( v2, QVariant( 4 ) ); - QgsExpression exp3( "eval('\"second_column\" * 2')" ); + QgsExpression exp3( QStringLiteral( "eval('\"second_column\" * 2')" ) ); QVariant v3 = exp3.evaluate( &context ); QCOMPARE( v3, QVariant( 10 ) ); - QgsExpression exp4( "eval('\"col1\"')" ); + QgsExpression exp4( QStringLiteral( "eval('\"col1\"')" ) ); QVariant v4 = exp4.evaluate( &context ); QCOMPARE( v4, QVariant( "test value" ) ); } @@ -2157,13 +2157,13 @@ class TestQgsExpression: public QObject { QgsFeature f( 100 ); QgsFields fields; - fields.append( QgsField( "col1" ) ); - fields.append( QgsField( "strings", QVariant::StringList, "string[]", 0, 0, QString(), QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "col1" ) ) ); + fields.append( QgsField( QStringLiteral( "strings" ), QVariant::StringList, QStringLiteral( "string[]" ), 0, 0, QString(), QVariant::String ) ); f.setFields( fields, true ); - f.setAttribute( "col1", QString( "test value" ) ); + f.setAttribute( QStringLiteral( "col1" ), QStringLiteral( "test value" ) ); QStringList array; - array << "one" << "two"; - f.setAttribute( "strings", array ); + array << QStringLiteral( "one" ) << QStringLiteral( "two" ); + f.setAttribute( QStringLiteral( "strings" ), array ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); @@ -2187,15 +2187,15 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression( "array_get(\"strings\", -1)" ).evaluate( &context ), QVariant() ); QStringList appendExpected = array; - appendExpected << "three"; + appendExpected << QStringLiteral( "three" ); QCOMPARE( QgsExpression( "array_append(\"strings\", 'three')" ).evaluate( &context ), QVariant( appendExpected ) ); QStringList prependExpected = array; - prependExpected.prepend( "zero" ); + prependExpected.prepend( QStringLiteral( "zero" ) ); QCOMPARE( QgsExpression( "array_prepend(\"strings\", 'zero')" ).evaluate( &context ), QVariant( prependExpected ) ); QStringList insertExpected = array; - insertExpected.insert( 1, "one and a half" ); + insertExpected.insert( 1, QStringLiteral( "one and a half" ) ); QCOMPARE( QgsExpression( "array_insert(\"strings\", 1, 'one and a half')" ).evaluate( &context ), QVariant( insertExpected ) ); QStringList removeAtExpected = array; @@ -2203,11 +2203,11 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression( "array_remove_at(\"strings\", 0)" ).evaluate( &context ), QVariant( removeAtExpected ) ); QStringList removeAllExpected; - removeAllExpected << "a" << "b" << "d"; + removeAllExpected << QStringLiteral( "a" ) << QStringLiteral( "b" ) << QStringLiteral( "d" ); QCOMPARE( QgsExpression( "array_remove_all(array('a', 'b', 'c', 'd', 'c'), 'c')" ).evaluate( &context ), QVariant( removeAllExpected ) ); QStringList concatExpected = array; - concatExpected << "a" << "b" << "c"; + concatExpected << QStringLiteral( "a" ) << QStringLiteral( "b" ) << QStringLiteral( "c" ); QCOMPARE( QgsExpression( "array_cat(\"strings\", array('a', 'b'), array('c'))" ).evaluate( &context ), QVariant( concatExpected ) ); QCOMPARE( QgsExpression( "array_intersect(array('1', '2', '3', '4'), array('4', '0', '2', '5'))" ).evaluate( &context ), QVariant( true ) ); @@ -2218,13 +2218,13 @@ class TestQgsExpression: public QObject { QgsFeature f( 100 ); QgsFields fields; - fields.append( QgsField( "col1" ) ); - fields.append( QgsField( "ints", QVariant::List, "int[]", 0, 0, QString(), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "col1" ) ) ); + fields.append( QgsField( QStringLiteral( "ints" ), QVariant::List, QStringLiteral( "int[]" ), 0, 0, QString(), QVariant::Int ) ); f.setFields( fields, true ); - f.setAttribute( "col1", QString( "test value" ) ); + f.setAttribute( QStringLiteral( "col1" ), QStringLiteral( "test value" ) ); QVariantList array; array << 1 << -2; - f.setAttribute( "ints", array ); + f.setAttribute( QStringLiteral( "ints" ), array ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); @@ -2272,7 +2272,7 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression( "array_intersect(array(1, 2, 3, 4), array(4, 0, 2, 5))" ).evaluate( &context ), QVariant( true ) ); QCOMPARE( QgsExpression( "array_intersect(array(1, 2, 3, 4), array(0, 5))" ).evaluate( &context ), QVariant( false ) ); - QgsExpression badArray( "array_get('not an array', 0)" ); + QgsExpression badArray( QStringLiteral( "array_get('not an array', 0)" ) ); QCOMPARE( badArray.evaluate( &context ), QVariant() ); QVERIFY( badArray.hasEvalError() ); QCOMPARE( badArray.evalErrorString(), QString( "Cannot convert 'not an array' to array" ) ); @@ -2282,22 +2282,22 @@ class TestQgsExpression: public QObject { QgsFeature f( 100 ); QgsFields fields; - fields.append( QgsField( "col1" ) ); - fields.append( QgsField( "map", QVariant::Map, "map", 0, 0, QString(), QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "col1" ) ) ); + fields.append( QgsField( QStringLiteral( "map" ), QVariant::Map, QStringLiteral( "map" ), 0, 0, QString(), QVariant::String ) ); f.setFields( fields, true ); - f.setAttribute( "col1", QString( "test value" ) ); + f.setAttribute( QStringLiteral( "col1" ), QStringLiteral( "test value" ) ); QVariantMap map; - map["1"] = "one"; - map["2"] = "two"; - f.setAttribute( "map", map ); + map[QStringLiteral( "1" )] = "one"; + map[QStringLiteral( "2" )] = "two"; + f.setAttribute( QStringLiteral( "map" ), map ); QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); QVariantMap builderExpected; QCOMPARE( QgsExpression( "map()" ).evaluate( &context ), QVariant( ) ); - builderExpected["1"] = "hello"; + builderExpected[QStringLiteral( "1" )] = "hello"; QCOMPARE( QgsExpression( "map('1', 'hello')" ).evaluate( &context ), QVariant( builderExpected ) ); - builderExpected["2"] = "world"; + builderExpected[QStringLiteral( "2" )] = "world"; QCOMPARE( QgsExpression( "map('1', 'hello', '2', 'world')" ).evaluate( &context ), QVariant( builderExpected ) ); QCOMPARE( QgsExpression( "map('1', 'hello', '2', 'world', 'ignoredOddParam')" ).evaluate( &context ), QVariant( builderExpected ) ); @@ -2308,29 +2308,29 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression( "map_exist(\"map\", '3')" ).evaluate( &context ), QVariant( false ) ); QVariantMap deleteExpected = map; - deleteExpected.remove( "1" ); + deleteExpected.remove( QStringLiteral( "1" ) ); QCOMPARE( QgsExpression( "map_delete(\"map\", '1')" ).evaluate( &context ), QVariant( deleteExpected ) ); QCOMPARE( QgsExpression( "map_delete(\"map\", '3')" ).evaluate( &context ), QVariant( map ) ); QVariantMap insertExpected = map; - insertExpected.insert( "3", "three" ); + insertExpected.insert( QStringLiteral( "3" ), "three" ); QCOMPARE( QgsExpression( "map_insert(\"map\", '3', 'three')" ).evaluate( &context ), QVariant( insertExpected ) ); QVariantMap concatExpected; - concatExpected["1"] = "one"; - concatExpected["2"] = "two"; - concatExpected["3"] = "three"; + concatExpected[QStringLiteral( "1" )] = "one"; + concatExpected[QStringLiteral( "2" )] = "two"; + concatExpected[QStringLiteral( "3" )] = "three"; QCOMPARE( QgsExpression( "map_concat(map('1', 'one', '2', 'overridden by next map'), map('2', 'two', '3', 'three'))" ).evaluate( &context ), QVariant( concatExpected ) ); QStringList keysExpected; - keysExpected << "1" << "2"; + keysExpected << QStringLiteral( "1" ) << QStringLiteral( "2" ); QCOMPARE( QgsExpression( "map_akeys(\"map\")" ).evaluate( &context ), QVariant( keysExpected ) ); QVariantList valuesExpected; valuesExpected << "one" << "two"; QCOMPARE( QgsExpression( "map_avals(\"map\")" ).evaluate( &context ), QVariant( valuesExpected ) ); - QgsExpression badMap( "map_get('not a map', '0')" ); + QgsExpression badMap( QStringLiteral( "map_get('not a map', '0')" ) ); QCOMPARE( badMap.evaluate( &context ), QVariant() ); QVERIFY( badMap.hasEvalError() ); QCOMPARE( badMap.evalErrorString(), QString( "Cannot convert 'not a map' to map" ) ); @@ -2407,7 +2407,7 @@ class TestQgsExpression: public QObject void test_implicitSharing() { - QgsExpression* exp = new QgsExpression( "Pilots > 2" ); + QgsExpression* exp = new QgsExpression( QStringLiteral( "Pilots > 2" ) ); QgsExpression expcopy( *exp ); @@ -2444,7 +2444,7 @@ class TestQgsExpression: public QObject // Let's remove the field referenced in the expression mPointsLayer->startEditing(); - mPointsLayer->deleteAttribute( mPointsLayer->fields().lookupField( "Pilots" ) ); + mPointsLayer->deleteAttribute( mPointsLayer->fields().lookupField( QStringLiteral( "Pilots" ) ) ); // Now the prepared expression is broken // The cached field index points to the index which now is @@ -2476,7 +2476,7 @@ class TestQgsExpression: public QObject QCOMPARE( count, 0 ); // Detach a more complex expression - QgsExpression nodeExpression( "1 IN (1, 2, 3, 4)" ); + QgsExpression nodeExpression( QStringLiteral( "1 IN (1, 2, 3, 4)" ) ); QgsExpression nodeExpression2( nodeExpression ); } @@ -2486,18 +2486,18 @@ class TestQgsExpression: public QObject //should take precedence over feature's field collection QgsFields fields; - fields.append( QgsField( "f1", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "f1" ), QVariant::String ) ); QgsFeature f( 1 ); f.setFields( fields ); //also add a joined field - this will not be available in feature's field collection - fields.append( QgsField( "j1", QVariant::String ), QgsFields::OriginJoin, 1 ); + fields.append( QgsField( QStringLiteral( "j1" ), QVariant::String ), QgsFields::OriginJoin, 1 ); f.setAttributes( QgsAttributes() << QVariant( "f1" ) << QVariant( "j1" ) ); f.setValid( true ); - QgsExpression e( "\"f1\"" ); + QgsExpression e( QStringLiteral( "\"f1\"" ) ); QgsExpressionContext context; context.setFeature( f ); context.setFields( fields ); @@ -2505,17 +2505,17 @@ class TestQgsExpression: public QObject QCOMPARE( result.toString(), QString( "f1" ) ); //test joined field - QgsExpression e2( "\"j1\"" ); + QgsExpression e2( QStringLiteral( "\"j1\"" ) ); result = e2.evaluate( &context ); QCOMPARE( result.toString(), QString( "j1" ) ); // final test - check that feature's field collection is also used when corresponding field NOT found // in explicitly passed field collection - fields.append( QgsField( "f2", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "f2" ), QVariant::String ) ); f.setFields( fields ); f.setAttributes( QgsAttributes() << QVariant( "f1" ) << QVariant( "j1" ) << QVariant( "f2" ) ); context.setFeature( f ); - QgsExpression e3( "\"f2\"" ); + QgsExpression e3( QStringLiteral( "\"f2\"" ) ); result = e3.evaluate( &context ); QCOMPARE( result.toString(), QString( "f2" ) ); } @@ -2526,10 +2526,10 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression::formatPreviewString( QVariant( QVariantMap() ) ), QString( "<map: >" ) ); QVariantMap map; - map["1"] = "One"; - map["2"] = "Two"; + map[QStringLiteral( "1" )] = "One"; + map[QStringLiteral( "2" )] = "Two"; QCOMPARE( QgsExpression::formatPreviewString( QVariant( map ) ), QString( "<map: 1: 'One', 2: 'Two'>" ) ); - map["3"] = "A very long string that is going to be truncated"; + map[QStringLiteral( "3" )] = "A very long string that is going to be truncated"; QCOMPARE( QgsExpression::formatPreviewString( QVariant( map ) ), QString( "<map: 1: 'One', 2: 'Two', 3: 'A very long string that is going to ...>" ) ); QVariantList list; @@ -2537,7 +2537,7 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression::formatPreviewString( QVariant( list ) ), QString( "<array: 1, 2, 3>" ) ); QStringList stringList; - stringList << "One" << "Two" << "A very long string that is going to be truncated"; + stringList << QStringLiteral( "One" ) << QStringLiteral( "Two" ) << QStringLiteral( "A very long string that is going to be truncated" ); QCOMPARE( QgsExpression::formatPreviewString( QVariant( stringList ) ), QString( "<array: 'One', 'Two', 'A very long string that is going to be trunca...>" ) ); } diff --git a/tests/src/core/testqgsexpressioncontext.cpp b/tests/src/core/testqgsexpressioncontext.cpp index c20bf0d7b7b6..70e6fd8e94f8 100644 --- a/tests/src/core/testqgsexpressioncontext.cpp +++ b/tests/src/core/testqgsexpressioncontext.cpp @@ -57,7 +57,7 @@ class TestQgsExpressionContext : public QObject { public: GetTestValueFunction() - : QgsScopedExpressionFunction( "get_test_value", 1, "test" ) {} + : QgsScopedExpressionFunction( QStringLiteral( "get_test_value" ), 1, QStringLiteral( "test" ) ) {} virtual QVariant func( const QVariantList&, const QgsExpressionContext*, QgsExpression* ) override { @@ -75,7 +75,7 @@ class TestQgsExpressionContext : public QObject { public: GetTestValueFunction2() - : QgsScopedExpressionFunction( "get_test_value", 1, "test" ) {} + : QgsScopedExpressionFunction( QStringLiteral( "get_test_value" ), 1, QStringLiteral( "test" ) ) {} virtual QVariant func( const QVariantList&, const QgsExpressionContext*, QgsExpression* ) override { @@ -92,7 +92,7 @@ class TestQgsExpressionContext : public QObject { public: explicit ModifiableFunction( int* v ) - : QgsScopedExpressionFunction( "test_function", 1, "test" ) + : QgsScopedExpressionFunction( QStringLiteral( "test_function" ), 1, QStringLiteral( "test" ) ) , mVal( v ) {} @@ -121,9 +121,9 @@ void TestQgsExpressionContext::initTestCase() QgsApplication::initQgis(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); } void TestQgsExpressionContext::cleanupTestCase() @@ -143,7 +143,7 @@ void TestQgsExpressionContext::cleanup() void TestQgsExpressionContext::contextScope() { - QgsExpressionContextScope scope( "scope name" ); + QgsExpressionContextScope scope( QStringLiteral( "scope name" ) ); QCOMPARE( scope.name(), QString( "scope name" ) ); QVERIFY( !scope.hasVariable( "test" ) ); @@ -151,7 +151,7 @@ void TestQgsExpressionContext::contextScope() QCOMPARE( scope.variableNames().length(), 0 ); QCOMPARE( scope.variableCount(), 0 ); - scope.setVariable( "test", 5 ); + scope.setVariable( QStringLiteral( "test" ), 5 ); QVERIFY( scope.hasVariable( "test" ) ); QVERIFY( scope.variable( "test" ).isValid() ); QCOMPARE( scope.variable( "test" ).toInt(), 5 ); @@ -159,21 +159,21 @@ void TestQgsExpressionContext::contextScope() QCOMPARE( scope.variableCount(), 1 ); QCOMPARE( scope.variableNames().at( 0 ), QString( "test" ) ); - scope.addVariable( QgsExpressionContextScope::StaticVariable( "readonly", QString( "readonly_test" ), true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "readonly" ), QStringLiteral( "readonly_test" ), true ) ); QVERIFY( scope.isReadOnly( "readonly" ) ); - scope.addVariable( QgsExpressionContextScope::StaticVariable( "notreadonly", QString( "not_readonly_test" ), false ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "notreadonly" ), QStringLiteral( "not_readonly_test" ), false ) ); QVERIFY( !scope.isReadOnly( "notreadonly" ) ); //updating a read only variable should remain read only - scope.setVariable( "readonly", "newvalue" ); + scope.setVariable( QStringLiteral( "readonly" ), "newvalue" ); QVERIFY( scope.isReadOnly( "readonly" ) ); //test retrieving filtered variable names - scope.setVariable( "_hidden_", "hidden" ); + scope.setVariable( QStringLiteral( "_hidden_" ), "hidden" ); QCOMPARE( scope.filteredVariableNames(), QStringList() << "readonly" << "notreadonly" << "test" ); //removal - scope.setVariable( "toremove", 5 ); + scope.setVariable( QStringLiteral( "toremove" ), 5 ); QVERIFY( scope.hasVariable( "toremove" ) ); QVERIFY( !scope.removeVariable( "missing" ) ); QVERIFY( scope.removeVariable( "toremove" ) ); @@ -182,9 +182,9 @@ void TestQgsExpressionContext::contextScope() void TestQgsExpressionContext::contextScopeCopy() { - QgsExpressionContextScope scope( "scope name" ); - scope.setVariable( "test", 5 ); - scope.addFunction( "get_test_value", new GetTestValueFunction() ); + QgsExpressionContextScope scope( QStringLiteral( "scope name" ) ); + scope.setVariable( QStringLiteral( "test" ), 5 ); + scope.addFunction( QStringLiteral( "get_test_value" ), new GetTestValueFunction() ); //copy constructor QgsExpressionContextScope copy( scope ); @@ -205,14 +205,14 @@ void TestQgsExpressionContext::contextScopeFunctions() QVERIFY( !scope.hasFunction( "get_test_value" ) ); QVERIFY( !scope.function( "get_test_value" ) ); - scope.addFunction( "get_test_value", new GetTestValueFunction() ); + scope.addFunction( QStringLiteral( "get_test_value" ), new GetTestValueFunction() ); QVERIFY( scope.hasFunction( "get_test_value" ) ); QVERIFY( scope.function( "get_test_value" ) ); QgsExpressionContext temp; QCOMPARE( scope.function( "get_test_value" )->func( QVariantList(), &temp, 0 ).toInt(), 42 ); //test functionNames - scope.addFunction( "get_test_value2", new GetTestValueFunction() ); + scope.addFunction( QStringLiteral( "get_test_value2" ), new GetTestValueFunction() ); QStringList functionNames = scope.functionNames(); QCOMPARE( functionNames.count(), 2 ); QVERIFY( functionNames.contains( "get_test_value" ) ); @@ -252,7 +252,7 @@ void TestQgsExpressionContext::contextStack() QCOMPARE( context.indexOfScope( &scopeNotInContext ), -1 ); //now add a variable to the first scope - scope1->setVariable( "test", 1 ); + scope1->setVariable( QStringLiteral( "test" ), 1 ); QVERIFY( context.hasVariable( "test" ) ); QCOMPARE( context.variable( "test" ).toInt(), 1 ); QCOMPARE( context.variableNames().length(), 1 ); @@ -268,19 +268,19 @@ void TestQgsExpressionContext::contextStack() QVERIFY( context.hasVariable( "test" ) ); QCOMPARE( context.variable( "test" ).toInt(), 1 ); QCOMPARE( context.variableNames().length(), 1 ); - scope2->setVariable( "test", 2 ); + scope2->setVariable( QStringLiteral( "test" ), 2 ); QVERIFY( context.hasVariable( "test" ) ); QCOMPARE( context.variable( "test" ).toInt(), 2 ); QCOMPARE( context.variableNames().length(), 1 ); //make sure context falls back to earlier scopes - scope1->setVariable( "test2", 11 ); + scope1->setVariable( QStringLiteral( "test2" ), 11 ); QVERIFY( context.hasVariable( "test2" ) ); QCOMPARE( context.variable( "test2" ).toInt(), 11 ); QCOMPARE( context.variableNames().length(), 2 ); //check filteredVariableNames method - scope2->setVariable( "_hidden", 5 ); + scope2->setVariable( QStringLiteral( "_hidden" ), 5 ); QStringList filteredNames = context.filteredVariableNames(); QCOMPARE( filteredNames.count(), 2 ); QCOMPARE( filteredNames.at( 0 ), QString( "test" ) ); @@ -293,7 +293,7 @@ void TestQgsExpressionContext::contextStack() QCOMPARE( scopes.at( 1 ), scope2 ); //check isReadOnly - scope2->addVariable( QgsExpressionContextScope::StaticVariable( "readonly", 5, true ) ); + scope2->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "readonly" ), 5, true ) ); QVERIFY( context.isReadOnly( "readonly" ) ); QVERIFY( !context.isReadOnly( "test" ) ); @@ -307,8 +307,8 @@ void TestQgsExpressionContext::scopeByName() { QgsExpressionContext context; QCOMPARE( context.indexOfScope( "test1" ), -1 ); - context << new QgsExpressionContextScope( "test1" ); - context << new QgsExpressionContextScope( "test2" ); + context << new QgsExpressionContextScope( QStringLiteral( "test1" ) ); + context << new QgsExpressionContextScope( QStringLiteral( "test2" ) ); QCOMPARE( context.indexOfScope( "test1" ), 0 ); QCOMPARE( context.indexOfScope( "test2" ), 1 ); QCOMPARE( context.indexOfScope( "not in context" ), -1 ); @@ -318,7 +318,7 @@ void TestQgsExpressionContext::contextCopy() { QgsExpressionContext context; context << new QgsExpressionContextScope(); - context.scope( 0 )->setVariable( "test", 1 ); + context.scope( 0 )->setVariable( QStringLiteral( "test" ), 1 ); //copy constructor QgsExpressionContext copy( context ); @@ -344,7 +344,7 @@ void TestQgsExpressionContext::contextStackFunctions() //now add a function to the first scope QgsExpressionContextScope* scope1 = context.scope( 0 ); - scope1->addFunction( "get_test_value", new GetTestValueFunction() ); + scope1->addFunction( QStringLiteral( "get_test_value" ), new GetTestValueFunction() ); QVERIFY( context.hasFunction( "get_test_value" ) ); QVERIFY( context.function( "get_test_value" ) ); QgsExpressionContext temp; @@ -359,13 +359,13 @@ void TestQgsExpressionContext::contextStackFunctions() //then set the variable so it overrides QgsExpressionContextScope* scope2 = context.scope( 1 ); - scope2->addFunction( "get_test_value", new GetTestValueFunction2() ); + scope2->addFunction( QStringLiteral( "get_test_value" ), new GetTestValueFunction2() ); QVERIFY( context.hasFunction( "get_test_value" ) ); QVERIFY( context.function( "get_test_value" ) ); QCOMPARE( context.function( "get_test_value" )->func( QVariantList(), &temp, 0 ).toInt(), 43 ); //make sure stack falls back to earlier contexts - scope2->addFunction( "get_test_value2", new GetTestValueFunction() ); + scope2->addFunction( QStringLiteral( "get_test_value2" ), new GetTestValueFunction() ); QVERIFY( context.hasFunction( "get_test_value2" ) ); QVERIFY( context.function( "get_test_value2" ) ); QCOMPARE( context.function( "get_test_value2" )->func( QVariantList(), &temp, 0 ).toInt(), 42 ); @@ -379,39 +379,39 @@ void TestQgsExpressionContext::contextStackFunctions() void TestQgsExpressionContext::evaluate() { - QgsExpression exp( "1 + 2" ); + QgsExpression exp( QStringLiteral( "1 + 2" ) ); QCOMPARE( exp.evaluate().toInt(), 3 ); QgsExpressionContext context; context << new QgsExpressionContextScope(); QgsExpressionContextScope* s = context.scope( 0 ); - s->setVariable( "test", 5 ); + s->setVariable( QStringLiteral( "test" ), 5 ); QCOMPARE( exp.evaluate( &context ).toInt(), 3 ); - QgsExpression expWithVariable( "var('test')" ); + QgsExpression expWithVariable( QStringLiteral( "var('test')" ) ); QCOMPARE( expWithVariable.evaluate( &context ).toInt(), 5 ); - s->setVariable( "test", 7 ); + s->setVariable( QStringLiteral( "test" ), 7 ); QCOMPARE( expWithVariable.evaluate( &context ).toInt(), 7 ); - QgsExpression expWithVariable2( "var('test') + var('test2')" ); - s->setVariable( "test2", 9 ); + QgsExpression expWithVariable2( QStringLiteral( "var('test') + var('test2')" ) ); + s->setVariable( QStringLiteral( "test2" ), 9 ); QCOMPARE( expWithVariable2.evaluate( &context ).toInt(), 16 ); - QgsExpression expWithVariableBad( "var('bad')" ); + QgsExpression expWithVariableBad( QStringLiteral( "var('bad')" ) ); QVERIFY( !expWithVariableBad.evaluate( &context ).isValid() ); //test shorthand variables - QgsExpression expShorthand( "@test" ); + QgsExpression expShorthand( QStringLiteral( "@test" ) ); QCOMPARE( expShorthand.evaluate( &context ).toInt(), 7 ); - QgsExpression expShorthandBad( "@bad" ); + QgsExpression expShorthandBad( QStringLiteral( "@bad" ) ); QVERIFY( !expShorthandBad.evaluate( &context ).isValid() ); //test with a function provided by a context QgsExpression::registerFunction( new ModifiableFunction( 0 ), true ); - QgsExpression testExpWContextFunction( "test_function(1)" ); + QgsExpression testExpWContextFunction( QStringLiteral( "test_function(1)" ) ); QVERIFY( !testExpWContextFunction.evaluate().isValid() ); int val1 = 5; - s->addFunction( "test_function", new ModifiableFunction( &val1 ) ); + s->addFunction( QStringLiteral( "test_function" ), new ModifiableFunction( &val1 ) ); testExpWContextFunction.prepare( &context ); QCOMPARE( testExpWContextFunction.evaluate( &context ).toInt(), 6 ); QCOMPARE( testExpWContextFunction.evaluate( &context ).toInt(), 7 ); @@ -422,7 +422,7 @@ void TestQgsExpressionContext::evaluate() context2 << new QgsExpressionContextScope(); QgsExpressionContextScope* s2 = context2.scope( 0 ); int val2 = 50; - s2->addFunction( "test_function", new ModifiableFunction( &val2 ) ); + s2->addFunction( QStringLiteral( "test_function" ), new ModifiableFunction( &val2 ) ); QCOMPARE( testExpWContextFunction.evaluate( &context2 ).toInt(), 51 ); QCOMPARE( testExpWContextFunction.evaluate( &context2 ).toInt(), 52 ); } @@ -457,7 +457,7 @@ void TestQgsExpressionContext::setFeature() void TestQgsExpressionContext::setFields() { QgsFields fields; - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); QgsExpressionContextScope scope; @@ -486,7 +486,7 @@ void TestQgsExpressionContext::setFields() void TestQgsExpressionContext::globalScope() { - QgsExpressionContextUtils::setGlobalVariable( "test", "testval" ); + QgsExpressionContextUtils::setGlobalVariable( QStringLiteral( "test" ), "testval" ); QgsExpressionContext context; QgsExpressionContextScope* globalScope = QgsExpressionContextUtils::globalScope(); @@ -495,17 +495,17 @@ void TestQgsExpressionContext::globalScope() QCOMPARE( context.variable( "test" ).toString(), QString( "testval" ) ); - QgsExpression expGlobal( "var('test')" ); + QgsExpression expGlobal( QStringLiteral( "var('test')" ) ); QCOMPARE( expGlobal.evaluate( &context ).toString(), QString( "testval" ) ); //test some other recognized global variables - QgsExpression expVersion( "var('qgis_version')" ); - QgsExpression expVersionNo( "var('qgis_version_no')" ); - QgsExpression expReleaseName( "var('qgis_release_name')" ); - QgsExpression expAccountName( "var('user_account_name')" ); - QgsExpression expUserFullName( "var('user_full_name')" ); - QgsExpression expOsName( "var('qgis_os_name')" ); - QgsExpression expPlatform( "var('qgis_platform')" ); + QgsExpression expVersion( QStringLiteral( "var('qgis_version')" ) ); + QgsExpression expVersionNo( QStringLiteral( "var('qgis_version_no')" ) ); + QgsExpression expReleaseName( QStringLiteral( "var('qgis_release_name')" ) ); + QgsExpression expAccountName( QStringLiteral( "var('user_account_name')" ) ); + QgsExpression expUserFullName( QStringLiteral( "var('user_full_name')" ) ); + QgsExpression expOsName( QStringLiteral( "var('qgis_os_name')" ) ); + QgsExpression expPlatform( QStringLiteral( "var('qgis_platform')" ) ); QCOMPARE( expVersion.evaluate( &context ).toString(), Qgis::QGIS_VERSION ); QCOMPARE( expVersionNo.evaluate( &context ).toInt(), Qgis::QGIS_VERSION_INT ); @@ -517,8 +517,8 @@ void TestQgsExpressionContext::globalScope() //test setGlobalVariables QgsStringMap vars; - vars.insert( "newvar1", "val1" ); - vars.insert( "newvar2", "val2" ); + vars.insert( QStringLiteral( "newvar1" ), QStringLiteral( "val1" ) ); + vars.insert( QStringLiteral( "newvar2" ), QStringLiteral( "val2" ) ); QgsExpressionContextUtils::setGlobalVariables( vars ); QgsExpressionContextScope* globalScope2 = QgsExpressionContextUtils::globalScope(); @@ -531,8 +531,8 @@ void TestQgsExpressionContext::globalScope() void TestQgsExpressionContext::projectScope() { - QgsExpressionContextUtils::setProjectVariable( "test", "testval" ); - QgsExpressionContextUtils::setProjectVariable( "testdouble", 5.2 ); + QgsExpressionContextUtils::setProjectVariable( QStringLiteral( "test" ), "testval" ); + QgsExpressionContextUtils::setProjectVariable( QStringLiteral( "testdouble" ), 5.2 ); QgsExpressionContext context; QgsExpressionContextScope* scope = QgsExpressionContextUtils::projectScope(); @@ -542,7 +542,7 @@ void TestQgsExpressionContext::projectScope() QCOMPARE( context.variable( "test" ).toString(), QString( "testval" ) ); QCOMPARE( context.variable( "testdouble" ).toDouble(), 5.2 ); - QgsExpression expProject( "var('test')" ); + QgsExpression expProject( QStringLiteral( "var('test')" ) ); QCOMPARE( expProject.evaluate( &context ).toString(), QString( "testval" ) ); //test clearing project variables @@ -554,7 +554,7 @@ void TestQgsExpressionContext::projectScope() QVERIFY( !projectScope->hasVariable( "test" ) ); //test a preset project variable - QgsProject::instance()->setTitle( "test project" ); + QgsProject::instance()->setTitle( QStringLiteral( "test project" ) ); delete projectScope; projectScope = QgsExpressionContextUtils::projectScope(); QCOMPARE( projectScope->variable( "project_title" ).toString(), QString( "test project" ) ); @@ -562,8 +562,8 @@ void TestQgsExpressionContext::projectScope() //test setProjectVariables QgsStringMap vars; - vars.insert( "newvar1", "val1" ); - vars.insert( "newvar2", "val2" ); + vars.insert( QStringLiteral( "newvar1" ), QStringLiteral( "val1" ) ); + vars.insert( QStringLiteral( "newvar2" ), QStringLiteral( "val2" ) ); QgsExpressionContextUtils::setProjectVariables( vars ); projectScope = QgsExpressionContextUtils::projectScope(); @@ -578,18 +578,18 @@ void TestQgsExpressionContext::projectScope() //project_color function QgsProjectColorScheme s; QgsNamedColorList colorList; - colorList << qMakePair( QColor( 200, 255, 0 ), QString( "vomit yellow" ) ); - colorList << qMakePair( QColor( 30, 60, 20 ), QString( "murky depths of hades" ) ); + colorList << qMakePair( QColor( 200, 255, 0 ), QStringLiteral( "vomit yellow" ) ); + colorList << qMakePair( QColor( 30, 60, 20 ), QStringLiteral( "murky depths of hades" ) ); s.setColors( colorList ); QgsExpressionContext contextColors; contextColors << QgsExpressionContextUtils::projectScope(); - QgsExpression expProjectColor( "project_color('murky depths of hades')" ); + QgsExpression expProjectColor( QStringLiteral( "project_color('murky depths of hades')" ) ); QCOMPARE( expProjectColor.evaluate( &contextColors ).toString(), QString( "30,60,20" ) ); //matching color names should be case insensitive - QgsExpression expProjectColorCaseInsensitive( "project_color('Murky Depths of hades')" ); + QgsExpression expProjectColorCaseInsensitive( QStringLiteral( "project_color('Murky Depths of hades')" ) ); QCOMPARE( expProjectColorCaseInsensitive.evaluate( &contextColors ).toString(), QString( "30,60,20" ) ); - QgsExpression badProjectColor( "project_color('dusk falls in san juan del sur')" ); + QgsExpression badProjectColor( QStringLiteral( "project_color('dusk falls in san juan del sur')" ) ); QCOMPARE( badProjectColor.evaluate( &contextColors ), QVariant() ); } @@ -603,7 +603,7 @@ void TestQgsExpressionContext::layerScope() layerScope = 0; //create a map layer - QScopedPointer vectorLayer( new QgsVectorLayer( "Point?field=col1:integer&field=col2:integer&field=col3:integer", "test layer", "memory" ) ); + QScopedPointer vectorLayer( new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer&field=col2:integer&field=col3:integer" ), QStringLiteral( "test layer" ), QStringLiteral( "memory" ) ) ); QgsExpressionContext context; context << QgsExpressionContextUtils::layerScope( vectorLayer.data() ); @@ -611,7 +611,7 @@ void TestQgsExpressionContext::layerScope() QCOMPARE( context.variable( "layer_name" ).toString(), vectorLayer->name() ); QCOMPARE( context.variable( "layer_id" ).toString(), vectorLayer->id() ); - QgsExpression expProject( "var('layer_name')" ); + QgsExpression expProject( QStringLiteral( "var('layer_name')" ) ); QCOMPARE( expProject.evaluate( &context ).toString(), vectorLayer->name() ); //check that fields were set @@ -619,14 +619,14 @@ void TestQgsExpressionContext::layerScope() QCOMPARE( fromVar, vectorLayer->fields() ); //test setting layer variables - QgsExpressionContextUtils::setLayerVariable( vectorLayer.data(), "testvar", "testval" ); + QgsExpressionContextUtils::setLayerVariable( vectorLayer.data(), QStringLiteral( "testvar" ), "testval" ); delete layerScope; layerScope = QgsExpressionContextUtils::layerScope( vectorLayer.data() ); QCOMPARE( layerScope->variable( "testvar" ).toString(), QString( "testval" ) ); QgsStringMap variables; - variables.insert( "var1", "val1" ); - variables.insert( "var2", "val2" ); + variables.insert( QStringLiteral( "var1" ), QStringLiteral( "val1" ) ); + variables.insert( QStringLiteral( "var2" ), QStringLiteral( "val2" ) ); QgsExpressionContextUtils::setLayerVariables( vectorLayer.data(), variables ); delete layerScope; layerScope = QgsExpressionContextUtils::layerScope( vectorLayer.data() ); @@ -639,9 +639,9 @@ void TestQgsExpressionContext::layerScope() void TestQgsExpressionContext::featureBasedContext() { QgsFields fields; - fields.append( QgsField( "x1" ) ); - fields.append( QgsField( "x2" ) ); - fields.append( QgsField( "foo", QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "x1" ) ) ); + fields.append( QgsField( QStringLiteral( "x2" ) ) ); + fields.append( QgsField( QStringLiteral( "foo" ), QVariant::Int ) ); QgsFeature f; f.initAttributes( 3 ); @@ -649,8 +649,8 @@ void TestQgsExpressionContext::featureBasedContext() QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, fields ); - QgsFeature evalFeature = qvariant_cast( context.variable( "_feature_" ) ); - QgsFields evalFields = qvariant_cast( context.variable( "_fields_" ) ); + QgsFeature evalFeature = qvariant_cast( context.variable( QStringLiteral( "_feature_" ) ) ); + QgsFields evalFields = qvariant_cast( context.variable( QStringLiteral( "_fields_" ) ) ); QCOMPARE( evalFeature.attributes(), f.attributes() ); QCOMPARE( evalFields, fields ); } @@ -666,7 +666,7 @@ void TestQgsExpressionContext::cache() QVERIFY( !c.hasCachedValue( "test" ) ); QVERIFY( !c.cachedValue( "test" ).isValid() ); - c.setCachedValue( "test", "my value" ); + c.setCachedValue( QStringLiteral( "test" ), "my value" ); QVERIFY( c.hasCachedValue( "test" ) ); QCOMPARE( c.cachedValue( "test" ), QVariant( "my value" ) ); diff --git a/tests/src/core/testqgsfeature.cpp b/tests/src/core/testqgsfeature.cpp index f005f33c3bfa..5536a87ec24c 100644 --- a/tests/src/core/testqgsfeature.cpp +++ b/tests/src/core/testqgsfeature.cpp @@ -57,18 +57,18 @@ class TestQgsFeature: public QObject void TestQgsFeature::initTestCase() { //add fields - QgsField field( "field1" ); + QgsField field( QStringLiteral( "field1" ) ); mFields.append( field ); - QgsField field2( "field2" ); + QgsField field2( QStringLiteral( "field2" ) ); mFields.append( field2 ); - QgsField field3( "field3" ); + QgsField field3( QStringLiteral( "field3" ) ); mFields.append( field3 ); //test attributes mAttrs << QVariant( 5 ) << QVariant( 7 ) << QVariant( "val" ); - mGeometry = QgsGeometry::fromWkt( "MULTILINESTRING((0 0, 10 0, 10 10, 20 10),(30 30, 40 30, 40 40, 50 40))" ); - mGeometry2 = QgsGeometry::fromWkt( "MULTILINESTRING((0 5, 15 0, 15 10, 25 10))" ); + mGeometry = QgsGeometry::fromWkt( QStringLiteral( "MULTILINESTRING((0 0, 10 0, 10 10, 20 10),(30 30, 40 30, 40 40, 50 40))" ) ); + mGeometry2 = QgsGeometry::fromWkt( QStringLiteral( "MULTILINESTRING((0 5, 15 0, 15 10, 25 10))" ) ); } void TestQgsFeature::cleanupTestCase() @@ -365,9 +365,9 @@ void TestQgsFeature::equality() QgsFeature feature; feature.setFields( mFields, true ); - feature.setAttribute( 0, QString( "attr1" ) ); - feature.setAttribute( 1, QString( "attr2" ) ); - feature.setAttribute( 2, QString( "attr3" ) ); + feature.setAttribute( 0, QStringLiteral( "attr1" ) ); + feature.setAttribute( 1, QStringLiteral( "attr2" ) ); + feature.setAttribute( 2, QStringLiteral( "attr3" ) ); feature.setValid( true ); feature.setId( 1 ); feature.setGeometry( QgsGeometry( new QgsPointV2( 1, 2 ) ) ); @@ -383,9 +383,9 @@ void TestQgsFeature::equality() QgsFeature feature3; feature3.setFields( mFields, true ); - feature3.setAttribute( 0, QString( "attr1" ) ); - feature3.setAttribute( 1, QString( "attr2" ) ); - feature3.setAttribute( 2, QString( "attr3" ) ); + feature3.setAttribute( 0, QStringLiteral( "attr1" ) ); + feature3.setAttribute( 1, QStringLiteral( "attr2" ) ); + feature3.setAttribute( 2, QStringLiteral( "attr3" ) ); feature3.setValid( true ); feature3.setId( 1 ); feature3.setGeometry( QgsGeometry( new QgsPointV2( 1, 2 ) ) ); @@ -403,9 +403,9 @@ void TestQgsFeature::equality() QgsFeature feature5; feature5.setFields( mFields, true ); - feature5.setAttribute( 0, QString( "attr1" ) ); - feature5.setAttribute( 1, QString( "attr2" ) ); - feature5.setAttribute( 2, QString( "attr3" ) ); + feature5.setAttribute( 0, QStringLiteral( "attr1" ) ); + feature5.setAttribute( 1, QStringLiteral( "attr2" ) ); + feature5.setAttribute( 2, QStringLiteral( "attr3" ) ); feature5.setValid( false ); feature5.setId( 1 ); feature5.setGeometry( QgsGeometry( new QgsPointV2( 1, 2 ) ) ); @@ -414,9 +414,9 @@ void TestQgsFeature::equality() QgsFeature feature6; feature6.setFields( mFields, true ); - feature6.setAttribute( 0, QString( "attr1" ) ); - feature6.setAttribute( 1, QString( "attr2" ) ); - feature6.setAttribute( 2, QString( "attr3" ) ); + feature6.setAttribute( 0, QStringLiteral( "attr1" ) ); + feature6.setAttribute( 1, QStringLiteral( "attr2" ) ); + feature6.setAttribute( 2, QStringLiteral( "attr3" ) ); feature6.setValid( true ); feature6.setId( 2 ); feature6.setGeometry( QgsGeometry( new QgsPointV2( 1, 2 ) ) ); @@ -425,9 +425,9 @@ void TestQgsFeature::equality() QgsFeature feature7; feature7.setFields( mFields, true ); - feature7.setAttribute( 0, QString( "attr1" ) ); - feature7.setAttribute( 1, QString( "attr2" ) ); - feature7.setAttribute( 2, QString( "attr3" ) ); + feature7.setAttribute( 0, QStringLiteral( "attr1" ) ); + feature7.setAttribute( 1, QStringLiteral( "attr2" ) ); + feature7.setAttribute( 2, QStringLiteral( "attr3" ) ); feature7.setValid( true ); feature7.setId( 1 ); feature7.setGeometry( QgsGeometry( new QgsPointV2( 1, 3 ) ) ); @@ -439,9 +439,9 @@ void TestQgsFeature::attributeUsingField() { QgsFeature feature; feature.setFields( mFields, true ); - feature.setAttribute( 0, QString( "attr1" ) ); - feature.setAttribute( 1, QString( "attr2" ) ); - feature.setAttribute( 2, QString( "attr3" ) ); + feature.setAttribute( 0, QStringLiteral( "attr1" ) ); + feature.setAttribute( 1, QStringLiteral( "attr2" ) ); + feature.setAttribute( 2, QStringLiteral( "attr3" ) ); QVERIFY( !feature.attribute( "bad" ).isValid() ); QCOMPARE( feature.attribute( "field1" ).toString(), QString( "attr1" ) ); diff --git a/tests/src/core/testqgsfield.cpp b/tests/src/core/testqgsfield.cpp index 4425ad675b0e..dc05ae74fea1 100644 --- a/tests/src/core/testqgsfield.cpp +++ b/tests/src/core/testqgsfield.cpp @@ -50,9 +50,9 @@ class TestQgsField: public QObject void TestQgsField::initTestCase() { // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); } void TestQgsField::cleanupTestCase() @@ -72,7 +72,7 @@ void TestQgsField::cleanup() void TestQgsField::create() { - QScopedPointer field( new QgsField( "name", QVariant::Double, "double", 5, 2, "comment" ) ); + QScopedPointer field( new QgsField( QStringLiteral( "name" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ) ); QCOMPARE( field->name(), QString( "name" ) ); QCOMPARE( field->type(), QVariant::Double ); QCOMPARE( field->typeName(), QString( "double" ) ); @@ -83,23 +83,23 @@ void TestQgsField::create() void TestQgsField::copy() { - QgsField original( "original", QVariant::Double, "double", 5, 2, "comment" ); + QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); QgsField copy( original ); QVERIFY( copy == original ); - copy.setName( "copy" ); + copy.setName( QStringLiteral( "copy" ) ); QCOMPARE( original.name(), QString( "original" ) ); QVERIFY( copy != original ); } void TestQgsField::assignment() { - QgsField original( "original", QVariant::Double, "double", 5, 2, "comment" ); + QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); QgsField copy; copy = original; QVERIFY( copy == original ); - copy.setName( "copy" ); + copy.setName( QStringLiteral( "copy" ) ); QCOMPARE( original.name(), QString( "original" ) ); QVERIFY( copy != original ); } @@ -107,21 +107,21 @@ void TestQgsField::assignment() void TestQgsField::gettersSetters() { QgsField field; - field.setName( "name" ); + field.setName( QStringLiteral( "name" ) ); QCOMPARE( field.name(), QString( "name" ) ); field.setType( QVariant::Int ); QCOMPARE( field.type(), QVariant::Int ); - field.setTypeName( "typeName" ); + field.setTypeName( QStringLiteral( "typeName" ) ); QCOMPARE( field.typeName(), QString( "typeName" ) ); field.setLength( 5 ); QCOMPARE( field.length(), 5 ); field.setPrecision( 2 ); QCOMPARE( field.precision(), 2 ); - field.setComment( "comment" ); + field.setComment( QStringLiteral( "comment" ) ); QCOMPARE( field.comment(), QString( "comment" ) ); - field.setAlias( "alias" ); + field.setAlias( QStringLiteral( "alias" ) ); QCOMPARE( field.alias(), QString( "alias" ) ); - field.setDefaultValueExpression( "1+2" ); + field.setDefaultValueExpression( QStringLiteral( "1+2" ) ); QCOMPARE( field.defaultValueExpression(), QString( "1+2" ) ); } @@ -151,27 +151,27 @@ void TestQgsField::isNumeric() void TestQgsField::equality() { QgsField field1; - field1.setName( "name" ); + field1.setName( QStringLiteral( "name" ) ); field1.setType( QVariant::Int ); field1.setLength( 5 ); field1.setPrecision( 2 ); - field1.setTypeName( "typename1" ); //typename is NOT required for equality - field1.setComment( "comment1" ); //comment is NOT required for equality + field1.setTypeName( QStringLiteral( "typename1" ) ); //typename is NOT required for equality + field1.setComment( QStringLiteral( "comment1" ) ); //comment is NOT required for equality QgsField field2; - field2.setName( "name" ); + field2.setName( QStringLiteral( "name" ) ); field2.setType( QVariant::Int ); field2.setLength( 5 ); field2.setPrecision( 2 ); - field2.setTypeName( "typename2" ); //typename is NOT required for equality - field2.setComment( "comment2" ); //comment is NOT required for equality + field2.setTypeName( QStringLiteral( "typename2" ) ); //typename is NOT required for equality + field2.setComment( QStringLiteral( "comment2" ) ); //comment is NOT required for equality QVERIFY( field1 == field2 ); QVERIFY( !( field1 != field2 ) ); //test that all applicable components contribute to equality - field2.setName( "name2" ); + field2.setName( QStringLiteral( "name2" ) ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - field2.setName( "name" ); + field2.setName( QStringLiteral( "name" ) ); field2.setType( QVariant::Double ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); @@ -184,11 +184,11 @@ void TestQgsField::equality() QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); field2.setPrecision( 2 ); - field2.setAlias( "alias " ); + field2.setAlias( QStringLiteral( "alias " ) ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); field2.setAlias( QString() ); - field2.setDefaultValueExpression( "1+2" ); + field2.setDefaultValueExpression( QStringLiteral( "1+2" ) ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); field2.setDefaultValueExpression( QString() ); @@ -196,7 +196,7 @@ void TestQgsField::equality() void TestQgsField::asVariant() { - QgsField original( "original", QVariant::Double, "double", 5, 2, "comment" ); + QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); //convert to and from a QVariant QVariant var = QVariant::fromValue( original ); @@ -208,27 +208,27 @@ void TestQgsField::asVariant() void TestQgsField::displayString() { - QgsField stringField( "string", QVariant::String, "string" ); + QgsField stringField( QStringLiteral( "string" ), QVariant::String, QStringLiteral( "string" ) ); //test string value - QString test( "test string" ); + QString test( QStringLiteral( "test string" ) ); QCOMPARE( stringField.displayString( test ), test ); //test NULL QSettings s; - s.setValue( "qgis/nullValue", "TEST NULL" ); + s.setValue( QStringLiteral( "qgis/nullValue" ), "TEST NULL" ); QVariant nullString = QVariant( QVariant::String ); QCOMPARE( stringField.displayString( nullString ), QString( "TEST NULL" ) ); //test int value - QgsField intField( "int", QVariant::String, "int" ); + QgsField intField( QStringLiteral( "int" ), QVariant::String, QStringLiteral( "int" ) ); QCOMPARE( intField.displayString( 5 ), QString( "5" ) ); //test NULL int QVariant nullInt = QVariant( QVariant::Int ); QCOMPARE( intField.displayString( nullInt ), QString( "TEST NULL" ) ); //test double value - QgsField doubleField( "double", QVariant::Double, "double", 10, 3 ); + QgsField doubleField( QStringLiteral( "double" ), QVariant::Double, QStringLiteral( "double" ), 10, 3 ); QCOMPARE( doubleField.displayString( 5.005005 ), QString( "5.005" ) ); //test NULL double QVariant nullDouble = QVariant( QVariant::Double ); @@ -239,7 +239,7 @@ void TestQgsField::displayString() void TestQgsField::convertCompatible() { //test string field - QgsField stringField( "string", QVariant::String, "string" ); + QgsField stringField( QStringLiteral( "string" ), QVariant::String, QStringLiteral( "string" ) ); QVariant stringVar( "test string" ); QVERIFY( stringField.convertCompatible( stringVar ) ); @@ -266,7 +266,7 @@ void TestQgsField::convertCompatible() QVERIFY( nullDouble.isNull() ); //test double - QgsField doubleField( "double", QVariant::Double, "double" ); + QgsField doubleField( QStringLiteral( "double" ), QVariant::Double, QStringLiteral( "double" ) ); stringVar = QVariant( "test string" ); QVERIFY( !doubleField.convertCompatible( stringVar ) ); @@ -296,7 +296,7 @@ void TestQgsField::convertCompatible() //test special rules //conversion of double to int - QgsField intField( "int", QVariant::Int, "int" ); + QgsField intField( QStringLiteral( "int" ), QVariant::Int, QStringLiteral( "int" ) ); //small double, should be rounded QVariant smallDouble( 45.7 ); QVERIFY( intField.convertCompatible( smallDouble ) ); @@ -342,14 +342,14 @@ void TestQgsField::convertCompatible() QCOMPARE( smallLonglong.type(), QVariant::Int ); QCOMPARE( smallLonglong, QVariant( 99 ) ); //conversion of longlong to longlong field - QgsField longlongField( "long", QVariant::LongLong, "longlong" ); + QgsField longlongField( QStringLiteral( "long" ), QVariant::LongLong, QStringLiteral( "longlong" ) ); longlong = QVariant( 99999999999999999LL ); QVERIFY( longlongField.convertCompatible( longlong ) ); QCOMPARE( longlong.type(), QVariant::LongLong ); QCOMPARE( longlong, QVariant( 99999999999999999LL ) ); //double with precision - QgsField doubleWithPrecField( "double", QVariant::Double, "double", 10, 3 ); + QgsField doubleWithPrecField( QStringLiteral( "double" ), QVariant::Double, QStringLiteral( "double" ), 10, 3 ); doubleVar = QVariant( 10.12345678 ); //note - this returns true! QVERIFY( doubleWithPrecField.convertCompatible( doubleVar ) ); @@ -357,7 +357,7 @@ void TestQgsField::convertCompatible() QCOMPARE( doubleVar.toDouble(), 10.123 ); //truncating string length - QgsField stringWithLen( "string", QVariant::String, "string", 3 ); + QgsField stringWithLen( QStringLiteral( "string" ), QVariant::String, QStringLiteral( "string" ), 3 ); stringVar = QVariant( "longstring" ); QVERIFY( !stringWithLen.convertCompatible( stringVar ) ); QCOMPARE( stringVar.type(), QVariant::String ); @@ -367,14 +367,14 @@ void TestQgsField::convertCompatible() void TestQgsField::dataStream() { QgsField original; - original.setName( "name" ); + original.setName( QStringLiteral( "name" ) ); original.setType( QVariant::Int ); original.setLength( 5 ); original.setPrecision( 2 ); - original.setTypeName( "typename1" ); - original.setComment( "comment1" ); - original.setAlias( "alias" ); - original.setDefaultValueExpression( "default" ); + original.setTypeName( QStringLiteral( "typename1" ) ); + original.setComment( QStringLiteral( "comment1" ) ); + original.setAlias( QStringLiteral( "alias" ) ); + original.setDefaultValueExpression( QStringLiteral( "default" ) ); QByteArray ba; QDataStream ds( &ba, QIODevice::ReadWrite ); @@ -392,9 +392,9 @@ void TestQgsField::dataStream() void TestQgsField::displayName() { QgsField field; - field.setName( "name" ); + field.setName( QStringLiteral( "name" ) ); QCOMPARE( field.displayName(), QString( "name" ) ); - field.setAlias( "alias" ); + field.setAlias( QStringLiteral( "alias" ) ); QCOMPARE( field.displayName(), QString( "alias" ) ); field.setAlias( QString() ); QCOMPARE( field.displayName(), QString( "name" ) ); @@ -404,8 +404,8 @@ void TestQgsField::editorWidgetSetup() { QgsField field; QgsEditorWidgetConfig config; - config.insert( "a", "value_a" ); - const QgsEditorWidgetSetup setup( "test", config ); + config.insert( QStringLiteral( "a" ), "value_a" ); + const QgsEditorWidgetSetup setup( QStringLiteral( "test" ), config ); field.setEditorWidgetSetup( setup ); QCOMPARE( field.editorWidgetSetup().type(), setup.type() ); @@ -414,7 +414,7 @@ void TestQgsField::editorWidgetSetup() void TestQgsField::collection() { - QgsField field( "collection", QVariant::List, "_int32", 0, 0, QString(), QVariant::Int ); + QgsField field( QStringLiteral( "collection" ), QVariant::List, QStringLiteral( "_int32" ), 0, 0, QString(), QVariant::Int ); QCOMPARE( field.subType(), QVariant::Int ); field.setSubType( QVariant::Double ); QCOMPARE( field.subType(), QVariant::Double ); diff --git a/tests/src/core/testqgsfields.cpp b/tests/src/core/testqgsfields.cpp index 0b20caede330..5c435042e311 100644 --- a/tests/src/core/testqgsfields.cpp +++ b/tests/src/core/testqgsfields.cpp @@ -88,14 +88,14 @@ void TestQgsFields::copy() { QgsFields original; //add field - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); original.append( field ); QCOMPARE( original.count(), 1 ); QgsFields copy( original ); QCOMPARE( copy.count(), 1 ); QVERIFY( copy == original ); - QgsField copyfield( "copyfield" ); + QgsField copyfield( QStringLiteral( "copyfield" ) ); copy.append( copyfield ); QCOMPARE( copy.count(), 2 ); QCOMPARE( original.count(), 1 ); @@ -106,14 +106,14 @@ void TestQgsFields::assignment() { QgsFields original; //add field - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); original.append( field ); QgsFields copy; copy = original; QVERIFY( copy == original ); - QgsField copyfield( "copyfield" ); + QgsField copyfield( QStringLiteral( "copyfield" ) ); copy.append( copyfield ); QCOMPARE( original.count(), 1 ); QCOMPARE( copy.count(), 2 ); @@ -130,9 +130,9 @@ void TestQgsFields::equality() //append an identical fields to both and retest QgsField field1; - field1.setName( "name" ); + field1.setName( QStringLiteral( "name" ) ); QgsField field2; - field2.setName( "name" ); + field2.setName( QStringLiteral( "name" ) ); QCOMPARE( field1, field2 ); fields1.append( field1 ); fields2.append( field2 ); @@ -149,9 +149,9 @@ void TestQgsFields::equality() void TestQgsFields::asVariant() { QgsField field1; - field1.setName( "name" ); + field1.setName( QStringLiteral( "name" ) ); QgsField field2; - field2.setName( "name" ); + field2.setName( QStringLiteral( "name" ) ); QgsFields original; original.append( field1 ); original.append( field2 ); @@ -167,7 +167,7 @@ void TestQgsFields::asVariant() void TestQgsFields::clear() { QgsFields original; - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); original.append( field ); QCOMPARE( original.count(), 1 ); QgsFields copy( original ); @@ -180,7 +180,7 @@ void TestQgsFields::clear() void TestQgsFields::exists() { QgsFields fields; - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); QVERIFY( !fields.exists( -1 ) ); @@ -194,12 +194,12 @@ void TestQgsFields::count() QCOMPARE( fields.count(), 0 ); QCOMPARE( fields.size(), 0 ); - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); QCOMPARE( fields.count(), 1 ); QCOMPARE( fields.size(), 1 ); - QgsField field2( "testfield2" ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); QCOMPARE( fields.count(), 2 ); QCOMPARE( fields.size(), 2 ); @@ -210,7 +210,7 @@ void TestQgsFields::isEmpty() QgsFields fields; QVERIFY( fields.isEmpty() ); - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); QVERIFY( !fields.isEmpty() ); } @@ -222,9 +222,9 @@ void TestQgsFields::remove() //test for no crash fields.remove( 1 ); - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); - QgsField field2( "testfield2" ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); //test for no crash @@ -241,15 +241,15 @@ void TestQgsFields::remove() void TestQgsFields::extend() { QgsFields destination; - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); destination.append( field ); - QgsField field2( "testfield2" ); + QgsField field2( QStringLiteral( "testfield2" ) ); destination.append( field2 ); QgsFields source; - QgsField field3( "testfield3" ); + QgsField field3( QStringLiteral( "testfield3" ) ); source.append( field3, QgsFields::OriginJoin, 5 ); - QgsField field4( "testfield4" ); + QgsField field4( QStringLiteral( "testfield4" ) ); source.append( field4 ); QCOMPARE( destination.count(), 2 ); @@ -262,9 +262,9 @@ void TestQgsFields::extend() void TestQgsFields::byIndex() { QgsFields fields; - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); - QgsField field2( "testfield2" ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); QCOMPARE( fields[0], field ); @@ -282,9 +282,9 @@ void TestQgsFields::byIndex() void TestQgsFields::byName() { QgsFields fields; - QgsField field( "testfield" ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); - QgsField field2( "testfield2" ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); QCOMPARE( fields.field( "testfield" ), field ); @@ -294,9 +294,9 @@ void TestQgsFields::byName() void TestQgsFields::fieldOrigin() { QgsFields fields; - QgsField field( QString( "testfield" ) ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field , QgsFields::OriginJoin ); - QgsField field2( QString( "testfield2" ) ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2, QgsFields::OriginExpression ); QCOMPARE( fields.fieldOrigin( 0 ), QgsFields::OriginJoin ); @@ -307,20 +307,20 @@ void TestQgsFields::fieldOrigin() void TestQgsFields::fieldOriginIndex() { QgsFields fields; - QgsField field( QString( "testfield" ) ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field , QgsFields::OriginProvider, 5 ); QCOMPARE( fields.fieldOriginIndex( 0 ), 5 ); - QgsField field2( QString( "testfield2" ) ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2, QgsFields::OriginProvider, 10 ); QCOMPARE( fields.fieldOriginIndex( 1 ), 10 ); - QgsField field3( QString( "testfield3" ) ); + QgsField field3( QStringLiteral( "testfield3" ) ); //field origin index not specified with OriginProvider, should be automatic fields.append( field3, QgsFields::OriginProvider ); QCOMPARE( fields.fieldOriginIndex( 2 ), 2 ); - QgsField field4( QString( "testfield4" ) ); + QgsField field4( QStringLiteral( "testfield4" ) ); //field origin index not specified with other than OriginProvider, should remain -1 fields.append( field4, QgsFields::OriginEdit ); QCOMPARE( fields.fieldOriginIndex( 3 ), -1 ); @@ -329,12 +329,12 @@ void TestQgsFields::fieldOriginIndex() void TestQgsFields::indexFromName() { QgsFields fields; - QgsField field( QString( "testfield" ) ); - field.setAlias( "testfieldAlias" ); + QgsField field( QStringLiteral( "testfield" ) ); + field.setAlias( QStringLiteral( "testfieldAlias" ) ); fields.append( field ); - QgsField field2( QString( "testfield2" ) ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); - QgsField field3( QString( "testfield3" ) ); + QgsField field3( QStringLiteral( "testfield3" ) ); fields.append( field3 ); QCOMPARE( fields.indexFromName( QString( "bad" ) ), -1 ); @@ -349,7 +349,7 @@ void TestQgsFields::indexFromName() QCOMPARE( fields.lookupField( QString( "teStFiEld2" ) ), 1 ); //test that fieldNameIndex prefers exact case matches over case insensitive matches - QgsField sameNameDifferentCase( QString( "teStFielD" ) ); + QgsField sameNameDifferentCase( QStringLiteral( "teStFielD" ) ); fields.append( sameNameDifferentCase ); QCOMPARE( fields.lookupField( QString( "teStFielD" ) ), 3 ); @@ -365,11 +365,11 @@ void TestQgsFields::toList() QList list = fields.toList(); QVERIFY( list.isEmpty() ); - QgsField field( QString( "testfield" ) ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); - QgsField field2( QString( "testfield2" ) ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); - QgsField field3( QString( "testfield3" ) ); + QgsField field3( QStringLiteral( "testfield3" ) ); fields.append( field3 ); list = fields.toList(); @@ -384,11 +384,11 @@ void TestQgsFields::allAttrsList() QgsAttributeList attrList = fields.allAttributesList(); QVERIFY( attrList.isEmpty() ); - QgsField field( QString( "testfield" ) ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); - QgsField field2( QString( "testfield2" ) ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); - QgsField field3( QString( "testfield3" ) ); + QgsField field3( QStringLiteral( "testfield3" ) ); fields.append( field3 ); attrList = fields.allAttributesList(); @@ -400,16 +400,16 @@ void TestQgsFields::allAttrsList() void TestQgsFields::appendExpressionField() { QgsFields fields; - QgsField field( QString( "testfield" ) ); + QgsField field( QStringLiteral( "testfield" ) ); fields.append( field ); - QgsField field2( QString( "testfield2" ) ); + QgsField field2( QStringLiteral( "testfield2" ) ); fields.append( field2 ); - QgsField dupeName( QString( "testfield" ) ); + QgsField dupeName( QStringLiteral( "testfield" ) ); QVERIFY( !fields.appendExpressionField( dupeName, 1 ) ); //good name - QgsField exprField( QString( "expression" ) ); + QgsField exprField( QStringLiteral( "expression" ) ); QVERIFY( fields.appendExpressionField( exprField, 5 ) ); QCOMPARE( fields.count(), 3 ); QCOMPARE( fields.fieldOrigin( 2 ), QgsFields::OriginExpression ); @@ -419,20 +419,20 @@ void TestQgsFields::appendExpressionField() void TestQgsFields::dataStream() { QgsField original1; - original1.setName( "name" ); + original1.setName( QStringLiteral( "name" ) ); original1.setType( QVariant::Int ); original1.setLength( 5 ); original1.setPrecision( 2 ); - original1.setTypeName( "typename1" ); - original1.setComment( "comment1" ); + original1.setTypeName( QStringLiteral( "typename1" ) ); + original1.setComment( QStringLiteral( "comment1" ) ); QgsField original2; - original2.setName( "next name" ); + original2.setName( QStringLiteral( "next name" ) ); original2.setType( QVariant::Double ); original2.setLength( 15 ); original2.setPrecision( 3 ); - original2.setTypeName( "double" ); - original2.setComment( "comment for field 2" ); + original2.setTypeName( QStringLiteral( "double" ) ); + original2.setComment( QStringLiteral( "comment for field 2" ) ); QgsFields originalFields; originalFields.append( original1 ); @@ -456,7 +456,7 @@ void TestQgsFields::dataStream() void TestQgsFields::field() { QgsField original; - original.setName( "name" ); + original.setName( QStringLiteral( "name" ) ); original.setType( QVariant::Int ); original.setLength( 5 ); original.setPrecision( 2 ); @@ -484,9 +484,9 @@ void TestQgsFields::field() void TestQgsFields::qforeach() { QgsFields fields; - QgsField field( QString( "1" ) ); + QgsField field( QStringLiteral( "1" ) ); fields.append( field ); - QgsField field2( QString( "2" ) ); + QgsField field2( QStringLiteral( "2" ) ); fields.append( field2 ); int i = 0; @@ -504,9 +504,9 @@ void TestQgsFields::iterator() //test with empty fields QCOMPARE( fields.begin(), fields.end() ); - QgsField field( QString( "1" ) ); + QgsField field( QStringLiteral( "1" ) ); fields.append( field ); - QgsField field2( QString( "2" ) ); + QgsField field2( QStringLiteral( "2" ) ); fields.append( field2 ); QgsFields::iterator it = fields.begin(); @@ -516,7 +516,7 @@ void TestQgsFields::iterator() QCOMPARE(( --it )->name(), QString( "1" ) ); QCOMPARE(( it++ )->name(), QString( "1" ) ); QCOMPARE( it->name(), QString( "2" ) ); - it->setName( "Test" ); + it->setName( QStringLiteral( "Test" ) ); QCOMPARE(( it-- )->name(), QString( "Test" ) ); QCOMPARE( it->name(), QString( "1" ) ); QCOMPARE( it[1].name(), QString( "Test" ) ); @@ -552,9 +552,9 @@ void TestQgsFields::constIterator() QVERIFY( false ); } - QgsField field( QString( QString( "1" ) ) ); + QgsField field( QString( QStringLiteral( "1" ) ) ); fields.append( field ); - QgsField field2( QString( QString( "2" ) ) ); + QgsField field2( QString( QStringLiteral( "2" ) ) ); fields.append( field2 ); const QgsFields constFields( fields ); diff --git a/tests/src/core/testqgsfilledmarker.cpp b/tests/src/core/testqgsfilledmarker.cpp index 8bbf9b742731..d05388c98025 100644 --- a/tests/src/core/testqgsfilledmarker.cpp +++ b/tests/src/core/testqgsfilledmarker.cpp @@ -94,7 +94,7 @@ void TestQgsFilledMarkerSymbol::initTestCase() QString pointFileName = mTestDataDir + "points.shp"; QFileInfo pointFileInfo( pointFileName ); mpPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( @@ -125,7 +125,7 @@ void TestQgsFilledMarkerSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPointsLayer->id() ); - mReport += "

                                                                                                                                                                                    Filled Marker Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Filled Marker Tests

                                                                                                                                                                                    \n" ); } void TestQgsFilledMarkerSymbol::cleanupTestCase() @@ -153,9 +153,9 @@ void TestQgsFilledMarkerSymbol::dataDefinedShape() { mFilledMarkerLayer->setShape( QgsSimpleMarkerSymbolLayerBase::Circle ); mFilledMarkerLayer->setSize( 10 ); - mFilledMarkerLayer->setDataDefinedProperty( "name", new QgsDataDefined( true, true, "if(\"class\"='Jet','square','star')" ) ); - bool result = imageCheck( "filledmarker_datadefinedshape" ); - mFilledMarkerLayer->removeDataDefinedProperty( "name" ); + mFilledMarkerLayer->setDataDefinedProperty( QStringLiteral( "name" ), new QgsDataDefined( true, true, QStringLiteral( "if(\"class\"='Jet','square','star')" ) ) ); + bool result = imageCheck( QStringLiteral( "filledmarker_datadefinedshape" ) ); + mFilledMarkerLayer->removeDataDefinedProperty( QStringLiteral( "name" ) ); QVERIFY( result ); } @@ -164,12 +164,12 @@ void TestQgsFilledMarkerSymbol::bounds() mFilledMarkerLayer->setColor( QColor( 200, 200, 200 ) ); mFilledMarkerLayer->setShape( QgsSimpleMarkerSymbolLayerBase::Circle ); mFilledMarkerLayer->setSize( 5 ); - mFilledMarkerLayer->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "min(\"importance\" * 2, 6)" ) ); + mFilledMarkerLayer->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "min(\"importance\" * 2, 6)" ) ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "filledmarker_bounds" ); + bool result = imageCheck( QStringLiteral( "filledmarker_bounds" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); - mFilledMarkerLayer->removeDataDefinedProperty( "size" ); + mFilledMarkerLayer->removeDataDefinedProperty( QStringLiteral( "size" ) ); QVERIFY( result ); } @@ -185,7 +185,7 @@ bool TestQgsFilledMarkerSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPointsLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_filledmarker" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_filledmarker" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgsfontmarker.cpp b/tests/src/core/testqgsfontmarker.cpp index 6af38ffcf086..d4ee38ba1e2b 100644 --- a/tests/src/core/testqgsfontmarker.cpp +++ b/tests/src/core/testqgsfontmarker.cpp @@ -94,7 +94,7 @@ void TestQgsFontMarkerSymbol::initTestCase() QString pointFileName = mTestDataDir + "points.shp"; QFileInfo pointFileInfo( pointFileName ); mpPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( @@ -112,7 +112,7 @@ void TestQgsFontMarkerSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPointsLayer->id() ); - mReport += "

                                                                                                                                                                                    Font Marker Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Font Marker Tests

                                                                                                                                                                                    \n" ); } void TestQgsFontMarkerSymbol::cleanupTestCase() @@ -131,10 +131,10 @@ void TestQgsFontMarkerSymbol::cleanupTestCase() void TestQgsFontMarkerSymbol::fontMarkerSymbol() { - mReport += "

                                                                                                                                                                                    Font marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Font marker symbol layer test

                                                                                                                                                                                    \n" ); mFontMarkerLayer->setColor( Qt::blue ); - QFont font = QgsFontUtils::getStandardTestFont( "Bold" ); + QFont font = QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ); mFontMarkerLayer->setFontFamily( font.family() ); mFontMarkerLayer->setCharacter( 'A' ); mFontMarkerLayer->setSize( 12 ); @@ -144,7 +144,7 @@ void TestQgsFontMarkerSymbol::fontMarkerSymbol() void TestQgsFontMarkerSymbol::fontMarkerSymbolOutline() { mFontMarkerLayer->setColor( Qt::blue ); - QFont font = QgsFontUtils::getStandardTestFont( "Bold" ); + QFont font = QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ); mFontMarkerLayer->setFontFamily( font.family() ); mFontMarkerLayer->setCharacter( 'A' ); mFontMarkerLayer->setSize( 30 ); @@ -155,16 +155,16 @@ void TestQgsFontMarkerSymbol::fontMarkerSymbolOutline() void TestQgsFontMarkerSymbol::bounds() { mFontMarkerLayer->setColor( Qt::blue ); - QFont font = QgsFontUtils::getStandardTestFont( "Bold" ); + QFont font = QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ); mFontMarkerLayer->setFontFamily( font.family() ); //use a narrow character to test that width is correctly calculated mFontMarkerLayer->setCharacter( 'l' ); mFontMarkerLayer->setSize( 12 ); mFontMarkerLayer->setOutlineWidth( 0 ); - mFontMarkerLayer->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "min(\"importance\" * 4.47214, 7.07106)" ) ); + mFontMarkerLayer->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "min(\"importance\" * 4.47214, 7.07106)" ) ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "fontmarker_bounds" ); + bool result = imageCheck( QStringLiteral( "fontmarker_bounds" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); QVERIFY( result ); } @@ -182,7 +182,7 @@ bool TestQgsFontMarkerSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPointsLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_fontmarker" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_fontmarker" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType, 30 ); diff --git a/tests/src/core/testqgsfontutils.cpp b/tests/src/core/testqgsfontutils.cpp index ccb8323ad72b..5499c102af06 100644 --- a/tests/src/core/testqgsfontutils.cpp +++ b/tests/src/core/testqgsfontutils.cpp @@ -66,12 +66,12 @@ void TestQgsFontUtils::xmlMethods() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); QFont f1 = QgsFontUtils::getStandardTestFont(); f1.setPointSize( 48 ); - QDomElement fontElem = QgsFontUtils::toXmlElement( f1, doc, "test" ); + QDomElement fontElem = QgsFontUtils::toXmlElement( f1, doc, QStringLiteral( "test" ) ); //test reading QFont f2; @@ -84,8 +84,8 @@ void TestQgsFontUtils::xmlMethods() QCOMPARE( f2.styleName(), f1.styleName() ); //test writing/reading with styles - f1 = QgsFontUtils::getStandardTestFont( "Bold" ); - fontElem = QgsFontUtils::toXmlElement( f1, doc, "test" ); + f1 = QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ); + fontElem = QgsFontUtils::toXmlElement( f1, doc, QStringLiteral( "test" ) ); #ifndef Q_OS_WIN QVERIFY( f2.styleName() != f1.styleName() ); #else @@ -104,7 +104,7 @@ void TestQgsFontUtils::xmlMethods() //test numeric weight f1.setWeight( 5 ); - fontElem = QgsFontUtils::toXmlElement( f1, doc, "test" ); + fontElem = QgsFontUtils::toXmlElement( f1, doc, QStringLiteral( "test" ) ); QVERIFY( f2.weight() != f1.weight() ); QVERIFY( QgsFontUtils::setFromXmlElement( f2, fontElem ) ); QCOMPARE( f2.weight(), f1.weight() ); @@ -120,13 +120,13 @@ void TestQgsFontUtils::fromChildNode() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); QFont f1 = QgsFontUtils::getStandardTestFont(); f1.setPointSize( 48 ); - QDomElement fontElem = QgsFontUtils::toXmlElement( f1, doc, "testNode" ); - QDomElement parentElem = doc.createElement( "parent" ); + QDomElement fontElem = QgsFontUtils::toXmlElement( f1, doc, QStringLiteral( "testNode" ) ); + QDomElement parentElem = doc.createElement( QStringLiteral( "parent" ) ); //first try with no child element QFont f2; diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index d3d856f30b2f..140dccd292b5 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -112,7 +112,7 @@ class TestQgsGeometry : public QObject private: /** A helper method to do a render check to see if the geometry op is as expected */ - bool renderCheck( const QString& theTestName, const QString& theComment = "", int mismatchCount = 0 ); + bool renderCheck( const QString& theTestName, const QString& theComment = QLatin1String( QLatin1String( "" ) ), int mismatchCount = 0 ); /** A helper method to dump to qdebug the geometry of a multipolygon */ void dumpMultiPolygon( QgsMultiPolygon &theMultiPolygon ); /** A helper method to dump to qdebug the geometry of a polygon */ @@ -188,10 +188,10 @@ void TestQgsGeometry::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); QgsApplication::showSettings(); - mReport += "

                                                                                                                                                                                    Geometry Tests

                                                                                                                                                                                    \n"; - mReport += "

                                                                                                                                                                                    Green = polygonA

                                                                                                                                                                                    \n"; - mReport += "

                                                                                                                                                                                    Red = polygonB

                                                                                                                                                                                    \n"; - mReport += "

                                                                                                                                                                                    Blue = polygonC

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Geometry Tests

                                                                                                                                                                                    \n" ); + mReport += QLatin1String( "

                                                                                                                                                                                    Green = polygonA

                                                                                                                                                                                    \n" ); + mReport += QLatin1String( "

                                                                                                                                                                                    Red = polygonB

                                                                                                                                                                                    \n" ); + mReport += QLatin1String( "

                                                                                                                                                                                    Blue = polygonC

                                                                                                                                                                                    \n" ); } @@ -229,7 +229,7 @@ void TestQgsGeometry::init() mPointY = QgsPoint( 240.0, 240.0 ); mPointZ = QgsPoint( 200.0, 240.0 ); - mWktLine = QString( "LINESTRING(117.623198 35.198654, 117.581274 35.198654, 117.078178 35.324427, 116.868555 35.534051, 116.617007 35.869448, 116.491233 35.953297, 116.155836 36.288694, 116.071987 36.372544, 115.443117 36.749865, 114.814247 37.043338, 114.311152 37.169112, 113.388810 37.378735, 113.095337 37.378735, 112.592241 37.378735, 111.753748 37.294886, 111.502201 37.252961, 111.082954 37.127187, 110.747557 37.127187, 110.160612 36.917564, 110.034838 36.833715, 109.741366 36.749865, 109.573667 36.666016, 109.238270 36.498317, 109.070571 36.414468, 108.819023 36.288694, 108.693250 36.246770, 108.483626 36.162920, 107.645134 35.911372, 106.597017 35.869448, 106.051997 35.701749, 105.800449 35.617900, 105.590826 35.575975, 105.297354 35.575975, 104.961956 35.575975, 104.710409 35.534051, 104.458861 35.492126, 103.871916 35.492126, 103.788066 35.492126, 103.326895 35.408277, 102.949574 35.408277, 102.488402 35.450201, 102.069156 35.450201, 101.482211 35.450201, 100.937191 35.659825, 100.308321 35.869448, 100.056773 36.037146, 99.050582 36.079071, 97.667069 35.743674, 97.163973 35.617900, 96.115857 35.534051, 95.612761 35.534051, 94.396947 35.911372, 93.684228 36.288694, 92.929584 36.833715, 92.258790 37.169112, 91.629920 37.504509, 90.414105 37.881831, 90.414105 37.881831, 90.246407 37.923755, 89.491763 37.839906, 89.156366 37.672207, 88.485572 37.504509, 87.814778 37.252961, 87.563230 37.169112, 87.143983 37.043338, 85.970093 36.875639, 85.802395 36.875639, 84.083484 36.959489, 84.041560 37.043338, 82.951519 37.546433, 82.699971 37.630283)" ); + mWktLine = QStringLiteral( "LINESTRING(117.623198 35.198654, 117.581274 35.198654, 117.078178 35.324427, 116.868555 35.534051, 116.617007 35.869448, 116.491233 35.953297, 116.155836 36.288694, 116.071987 36.372544, 115.443117 36.749865, 114.814247 37.043338, 114.311152 37.169112, 113.388810 37.378735, 113.095337 37.378735, 112.592241 37.378735, 111.753748 37.294886, 111.502201 37.252961, 111.082954 37.127187, 110.747557 37.127187, 110.160612 36.917564, 110.034838 36.833715, 109.741366 36.749865, 109.573667 36.666016, 109.238270 36.498317, 109.070571 36.414468, 108.819023 36.288694, 108.693250 36.246770, 108.483626 36.162920, 107.645134 35.911372, 106.597017 35.869448, 106.051997 35.701749, 105.800449 35.617900, 105.590826 35.575975, 105.297354 35.575975, 104.961956 35.575975, 104.710409 35.534051, 104.458861 35.492126, 103.871916 35.492126, 103.788066 35.492126, 103.326895 35.408277, 102.949574 35.408277, 102.488402 35.450201, 102.069156 35.450201, 101.482211 35.450201, 100.937191 35.659825, 100.308321 35.869448, 100.056773 36.037146, 99.050582 36.079071, 97.667069 35.743674, 97.163973 35.617900, 96.115857 35.534051, 95.612761 35.534051, 94.396947 35.911372, 93.684228 36.288694, 92.929584 36.833715, 92.258790 37.169112, 91.629920 37.504509, 90.414105 37.881831, 90.414105 37.881831, 90.246407 37.923755, 89.491763 37.839906, 89.156366 37.672207, 88.485572 37.504509, 87.814778 37.252961, 87.563230 37.169112, 87.143983 37.043338, 85.970093 36.875639, 85.802395 36.875639, 84.083484 36.959489, 84.041560 37.043338, 82.951519 37.546433, 82.699971 37.630283)" ); mPolygonA.clear(); mPolygonB.clear(); @@ -582,22 +582,22 @@ void TestQgsGeometry::point() //asGML2 QgsPointV2 exportPoint( 1, 2 ); QgsPointV2 exportPointFloat( 1 / 3.0, 2 / 3.0 ); - QDomDocument doc( "gml" ); - QString expectedGML2( "1,2" ); + QDomDocument doc( QStringLiteral( "gml" ) ); + QString expectedGML2( QStringLiteral( "1,2" ) ); QCOMPARE( elemToString( exportPoint.asGML2( doc ) ), expectedGML2 ); - QString expectedGML2prec3( "0.333,0.667" ); + QString expectedGML2prec3( QStringLiteral( "0.333,0.667" ) ); QCOMPARE( elemToString( exportPointFloat.asGML2( doc, 3 ) ), expectedGML2prec3 ); //asGML3 - QString expectedGML3( "1 2" ); + QString expectedGML3( QStringLiteral( "1 2" ) ); QCOMPARE( elemToString( exportPoint.asGML3( doc ) ), expectedGML3 ); - QString expectedGML3prec3( "0.333 0.667" ); + QString expectedGML3prec3( QStringLiteral( "0.333 0.667" ) ); QCOMPARE( elemToString( exportPointFloat.asGML3( doc, 3 ) ), expectedGML3prec3 ); //asJSON - QString expectedJson( "{\"type\": \"Point\", \"coordinates\": [1, 2]}" ); + QString expectedJson( QStringLiteral( "{\"type\": \"Point\", \"coordinates\": [1, 2]}" ) ); QCOMPARE( exportPoint.asJSON(), expectedJson ); - QString expectedJsonPrec3( "{\"type\": \"Point\", \"coordinates\": [0.333, 0.667]}" ); + QString expectedJsonPrec3( QStringLiteral( "{\"type\": \"Point\", \"coordinates\": [0.333, 0.667]}" ) ); QCOMPARE( exportPointFloat.asJSON( 3 ), expectedJsonPrec3 ); //bounding box @@ -1428,22 +1428,22 @@ void TestQgsGeometry::lineString() exportLineFloat.setPoints( QgsPointSequence() << QgsPointV2( 1 / 3.0, 2 / 3.0 ) << QgsPointV2( 1 + 1 / 3.0, 1 + 2 / 3.0 ) << QgsPointV2( 2 + 1 / 3.0, 2 + 2 / 3.0 ) ); - QDomDocument doc( "gml" ); - QString expectedGML2( "31,32 41,42 51,52" ); + QDomDocument doc( QStringLiteral( "gml" ) ); + QString expectedGML2( QStringLiteral( "31,32 41,42 51,52" ) ); QCOMPARE( elemToString( exportLine.asGML2( doc ) ), expectedGML2 ); - QString expectedGML2prec3( "0.333,0.667 1.333,1.667 2.333,2.667" ); + QString expectedGML2prec3( QStringLiteral( "0.333,0.667 1.333,1.667 2.333,2.667" ) ); QCOMPARE( elemToString( exportLineFloat.asGML2( doc, 3 ) ), expectedGML2prec3 ); //asGML3 - QString expectedGML3( "31 32 41 42 51 52" ); + QString expectedGML3( QStringLiteral( "31 32 41 42 51 52" ) ); QCOMPARE( elemToString( exportLine.asGML3( doc ) ), expectedGML3 ); - QString expectedGML3prec3( "0.333 0.667 1.333 1.667 2.333 2.667" ); + QString expectedGML3prec3( QStringLiteral( "0.333 0.667 1.333 1.667 2.333 2.667" ) ); QCOMPARE( elemToString( exportLineFloat.asGML3( doc, 3 ) ), expectedGML3prec3 ); //asJSON - QString expectedJson( "{\"type\": \"LineString\", \"coordinates\": [ [31, 32], [41, 42], [51, 52]]}" ); + QString expectedJson( QStringLiteral( "{\"type\": \"LineString\", \"coordinates\": [ [31, 32], [41, 42], [51, 52]]}" ) ); QCOMPARE( exportLine.asJSON(), expectedJson ); - QString expectedJsonPrec3( "{\"type\": \"LineString\", \"coordinates\": [ [0.333, 0.667], [1.333, 1.667], [2.333, 2.667]]}" ); + QString expectedJsonPrec3( QStringLiteral( "{\"type\": \"LineString\", \"coordinates\": [ [0.333, 0.667], [1.333, 1.667], [2.333, 2.667]]}" ) ); QCOMPARE( exportLineFloat.asJSON( 3 ), expectedJsonPrec3 ); //length @@ -2123,7 +2123,7 @@ void TestQgsGeometry::lineString() delete[] wkb; wkb = 0; QCOMPARE( l37.boundingBox(), QgsRectangle( 1, 0, 4, 2 ) ); - l37.fromWkt( QString( "LineString( 1 5, 3 4, 6 3 )" ) ); + l37.fromWkt( QStringLiteral( "LineString( 1 5, 3 4, 6 3 )" ) ); QCOMPARE( l37.boundingBox(), QgsRectangle( 1, 3, 6, 5 ) ); l37.insertVertex( QgsVertexId( 0, 0, 1 ), QgsPointV2( -1, 7 ) ); QCOMPARE( l37.boundingBox(), QgsRectangle( -1, 3, 6, 7 ) ); @@ -2889,7 +2889,7 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::Point, 9, 1 ) << QgsPointV2( QgsWkbTypes::Point, 1, 1 ) ); exportPolygon.addInteriorRing( ring ); - QString expectedJson( "{\"type\": \"Polygon\", \"coordinates\": [[ [0, 0], [0, 10], [10, 10], [10, 0], [0, 0]], [ [1, 1], [1, 9], [9, 9], [9, 1], [1, 1]]] }" ); + QString expectedJson( QStringLiteral( "{\"type\": \"Polygon\", \"coordinates\": [[ [0, 0], [0, 10], [10, 10], [10, 0], [0, 0]], [ [1, 1], [1, 9], [9, 9], [9, 1], [1, 1]]] }" ) ); QCOMPARE( exportPolygon.asJSON(), expectedJson ); QgsPolygonV2 exportPolygonFloat; @@ -2904,24 +2904,24 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::Point, 4 / 3.0, 2 / 3.0 ) << QgsPointV2( QgsWkbTypes::Point, 2 / 3.0, 2 / 3.0 ) ); exportPolygonFloat.addInteriorRing( ring ); - QString expectedJsonPrec3( "{\"type\": \"Polygon\", \"coordinates\": [[ [1.111, 1.111], [1.111, 11.111], [11.111, 11.111], [11.111, 1.111], [1.111, 1.111]], [ [0.667, 0.667], [0.667, 1.333], [1.333, 1.333], [1.333, 0.667], [0.667, 0.667]]] }" ); + QString expectedJsonPrec3( QStringLiteral( "{\"type\": \"Polygon\", \"coordinates\": [[ [1.111, 1.111], [1.111, 11.111], [11.111, 11.111], [11.111, 1.111], [1.111, 1.111]], [ [0.667, 0.667], [0.667, 1.333], [1.333, 1.333], [1.333, 0.667], [0.667, 0.667]]] }" ) ); QCOMPARE( exportPolygonFloat.asJSON( 3 ), expectedJsonPrec3 ); // as GML2 - QDomDocument doc( "gml" ); - QString expectedGML2( "0,0 0,10 10,10 10,0 0,0" ); - expectedGML2 += QString( "1,1 1,9 9,9 9,1 1,1" ); + QDomDocument doc( QStringLiteral( "gml" ) ); + QString expectedGML2( QStringLiteral( "0,0 0,10 10,10 10,0 0,0" ) ); + expectedGML2 += QStringLiteral( "1,1 1,9 9,9 9,1 1,1" ); QCOMPARE( elemToString( exportPolygon.asGML2( doc ) ), expectedGML2 ); - QString expectedGML2prec3( "1.111,1.111 1.111,11.111 11.111,11.111 11.111,1.111 1.111,1.111" ); - expectedGML2prec3 += QString( "0.667,0.667 0.667,1.333 1.333,1.333 1.333,0.667 0.667,0.667" ); + QString expectedGML2prec3( QStringLiteral( "1.111,1.111 1.111,11.111 11.111,11.111 11.111,1.111 1.111,1.111" ) ); + expectedGML2prec3 += QStringLiteral( "0.667,0.667 0.667,1.333 1.333,1.333 1.333,0.667 0.667,0.667" ); QCOMPARE( elemToString( exportPolygonFloat.asGML2( doc, 3 ) ), expectedGML2prec3 ); //as GML3 - QString expectedGML3( "0,0 0,10 10,10 10,0 0,0" ); - expectedGML3 += QString( "1,1 1,9 9,9 9,1 1,1" ); + QString expectedGML3( QStringLiteral( "0,0 0,10 10,10 10,0 0,0" ) ); + expectedGML3 += QStringLiteral( "1,1 1,9 9,9 9,1 1,1" ); QCOMPARE( elemToString( exportPolygon.asGML3( doc ) ), expectedGML3 ); - QString expectedGML3prec3( "1.111,1.111 1.111,11.111 11.111,11.111 11.111,1.111 1.111,1.111" ); - expectedGML3prec3 += QString( "0.667,0.667 0.667,1.333 1.333,1.333 1.333,0.667 0.667,0.667" ); + QString expectedGML3prec3( QStringLiteral( "1.111,1.111 1.111,11.111 11.111,11.111 11.111,1.111 1.111,1.111" ) ); + expectedGML3prec3 += QStringLiteral( "0.667,0.667 0.667,1.333 1.333,1.333 1.333,0.667 0.667,0.667" ); QCOMPARE( elemToString( exportPolygonFloat.asGML3( doc, 3 ) ), expectedGML3prec3 ); //removing the fourth to last vertex removes the whole ring @@ -3388,31 +3388,31 @@ void TestQgsGeometry::intersectionCheck2() void TestQgsGeometry::translateCheck1() { - QString wkt = "LineString (0 0, 10 0, 10 10)"; + QString wkt = QStringLiteral( "LineString (0 0, 10 0, 10 10)" ); QgsGeometry geom( QgsGeometry::fromWkt( wkt ) ); geom.translate( 10, -5 ); QString obtained = geom.exportToWkt(); - QString expected = "LineString (10 -5, 20 -5, 20 5)"; + QString expected = QStringLiteral( "LineString (10 -5, 20 -5, 20 5)" ); QCOMPARE( obtained, expected ); geom.translate( -10, 5 ); obtained = geom.exportToWkt(); QCOMPARE( obtained, wkt ); - wkt = "Polygon ((-2 4, -2 -10, 2 3, -2 4),(1 1, -1 1, -1 -1, 1 1))"; + wkt = QStringLiteral( "Polygon ((-2 4, -2 -10, 2 3, -2 4),(1 1, -1 1, -1 -1, 1 1))" ); geom = QgsGeometry::fromWkt( wkt ); geom.translate( -2, 10 ); obtained = geom.exportToWkt(); - expected = "Polygon ((-4 14, -4 0, 0 13, -4 14),(-1 11, -3 11, -3 9, -1 11))"; + expected = QStringLiteral( "Polygon ((-4 14, -4 0, 0 13, -4 14),(-1 11, -3 11, -3 9, -1 11))" ); QCOMPARE( obtained, expected ); geom.translate( 2, -10 ); obtained = geom.exportToWkt(); QCOMPARE( obtained, wkt ); - wkt = "Point (40 50)"; + wkt = QStringLiteral( "Point (40 50)" ); geom = QgsGeometry::fromWkt( wkt ); geom.translate( -2, 10 ); obtained = geom.exportToWkt(); - expected = "Point (38 60)"; + expected = QStringLiteral( "Point (38 60)" ); QCOMPARE( obtained, expected ); geom.translate( 2, -10 ); obtained = geom.exportToWkt(); @@ -3422,37 +3422,37 @@ void TestQgsGeometry::translateCheck1() void TestQgsGeometry::rotateCheck1() { - QString wkt = "LineString (0 0, 10 0, 10 10)"; + QString wkt = QStringLiteral( "LineString (0 0, 10 0, 10 10)" ); QgsGeometry geom( QgsGeometry::fromWkt( wkt ) ); geom.rotate( 90, QgsPoint( 0, 0 ) ); QString obtained = geom.exportToWkt(); - QString expected = "LineString (0 0, 0 -10, 10 -10)"; + QString expected = QStringLiteral( "LineString (0 0, 0 -10, 10 -10)" ); QCOMPARE( obtained, expected ); geom.rotate( -90, QgsPoint( 0, 0 ) ); obtained = geom.exportToWkt(); QCOMPARE( obtained, wkt ); - wkt = "Polygon ((-2 4, -2 -10, 2 3, -2 4),(1 1, -1 1, -1 -1, 1 1))"; + wkt = QStringLiteral( "Polygon ((-2 4, -2 -10, 2 3, -2 4),(1 1, -1 1, -1 -1, 1 1))" ); geom = QgsGeometry::fromWkt( wkt ); geom.rotate( 90, QgsPoint( 0, 0 ) ); obtained = geom.exportToWkt(); - expected = "Polygon ((4 2, -10 2, 3 -2, 4 2),(1 -1, 1 1, -1 1, 1 -1))"; + expected = QStringLiteral( "Polygon ((4 2, -10 2, 3 -2, 4 2),(1 -1, 1 1, -1 1, 1 -1))" ); QCOMPARE( obtained, expected ); geom.rotate( -90, QgsPoint( 0, 0 ) ); obtained = geom.exportToWkt(); QCOMPARE( obtained, wkt ); - wkt = "Point (40 50)"; + wkt = QStringLiteral( "Point (40 50)" ); geom = QgsGeometry::fromWkt( wkt ); geom.rotate( 90, QgsPoint( 0, 0 ) ); obtained = geom.exportToWkt(); - expected = "Point (50 -40)"; + expected = QStringLiteral( "Point (50 -40)" ); QCOMPARE( obtained, expected ); geom.rotate( -90, QgsPoint( 0, 0 ) ); obtained = geom.exportToWkt(); QCOMPARE( obtained, wkt ); geom.rotate( 180, QgsPoint( 40, 0 ) ); - expected = "Point (40 -50)"; + expected = QStringLiteral( "Point (40 -50)" ); obtained = geom.exportToWkt(); QCOMPARE( obtained, expected ); geom.rotate( 180, QgsPoint( 40, 0 ) ); // round-trip @@ -3523,14 +3523,14 @@ void TestQgsGeometry::bufferCheck() void TestQgsGeometry::smoothCheck() { //can't smooth a point - QString wkt = "Point (40 50)"; + QString wkt = QStringLiteral( "Point (40 50)" ); QgsGeometry geom( QgsGeometry::fromWkt( wkt ) ); QgsGeometry result = geom.smooth( 1, 0.25 ); QString obtained = result.exportToWkt(); QCOMPARE( obtained, wkt ); //linestring - wkt = "LineString(0 0, 10 0, 10 10, 20 10)"; + wkt = QStringLiteral( "LineString(0 0, 10 0, 10 10, 20 10)" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25 ); QgsPolyline line = result.asPolyline(); @@ -3540,7 +3540,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( line, expectedLine ) ); //linestring, with min distance - wkt = "LineString(0 0, 10 0, 10 10, 15 10, 15 20)"; + wkt = QStringLiteral( "LineString(0 0, 10 0, 10 10, 15 10, 15 20)" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25, 6 ); line = result.asPolyline(); @@ -3550,7 +3550,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( line, expectedLine ) ); //linestring, with max angle - wkt = "LineString(0 0, 10 0, 15 5, 25 -5, 30 -5 )"; + wkt = QStringLiteral( "LineString(0 0, 10 0, 15 5, 25 -5, 30 -5 )" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25, 0, 50 ); line = result.asPolyline(); @@ -3560,7 +3560,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( line, expectedLine ) ); //linestring, with max angle, other direction - wkt = "LineString( 30 -5, 25 -5, 15 5, 10 0, 0 0 )"; + wkt = QStringLiteral( "LineString( 30 -5, 25 -5, 15 5, 10 0, 0 0 )" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25, 0, 50 ); line = result.asPolyline(); @@ -3570,7 +3570,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( line, expectedLine ) ); //linestring, max angle, first corner sharp - wkt = "LineString(0 0, 10 0, 10 10 )"; + wkt = QStringLiteral( "LineString(0 0, 10 0, 10 10 )" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25, 0, 50 ); line = result.asPolyline(); @@ -3578,7 +3578,7 @@ void TestQgsGeometry::smoothCheck() expectedLine << QgsPoint( 0, 0 ) << QgsPoint( 10, 0 ) << QgsPoint( 10, 10 ); QVERIFY( QgsGeometry::compare( line, expectedLine ) ); - wkt = "MultiLineString ((0 0, 10 0, 10 10, 20 10),(30 30, 40 30, 40 40, 50 40))"; + wkt = QStringLiteral( "MultiLineString ((0 0, 10 0, 10 10, 20 10),(30 30, 40 30, 40 40, 50 40))" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25 ); QgsMultiPolyline multiLine = result.asMultiPolyline(); @@ -3590,7 +3590,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( multiLine, expectedMultiline ) ); //polygon - wkt = "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0 ),(2 2, 4 2, 4 4, 2 4, 2 2))"; + wkt = QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0 ),(2 2, 4 2, 4 4, 2 4, 2 2))" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25 ); QgsPolygon poly = result.asPolygon(); @@ -3604,7 +3604,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( poly, expectedPolygon ) ); //polygon with max angle - should be unchanged - wkt = "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))"; + wkt = QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.25, -1, 50 ); poly = result.asPolygon(); @@ -3614,7 +3614,7 @@ void TestQgsGeometry::smoothCheck() QVERIFY( QgsGeometry::compare( poly, expectedPolygon ) ); //multipolygon) - wkt = "MultiPolygon (((0 0, 10 0, 10 10, 0 10, 0 0 )),((2 2, 4 2, 4 4, 2 4, 2 2)))"; + wkt = QStringLiteral( "MultiPolygon (((0 0, 10 0, 10 10, 0 10, 0 0 )),((2 2, 4 2, 4 4, 2 4, 2 2)))" ); geom = QgsGeometry::fromWkt( wkt ); result = geom.smooth( 1, 0.1 ); QgsMultiPolygon multipoly = result.asMultiPolygon(); @@ -3632,8 +3632,8 @@ void TestQgsGeometry::smoothCheck() void TestQgsGeometry::unaryUnion() { //test QgsGeometry::unaryUnion with null geometry - QString wkt1 = "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0 ))"; - QString wkt2 = "Polygon ((2 2, 4 2, 4 4, 2 4, 2 2))"; + QString wkt1 = QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0 ))" ); + QString wkt2 = QStringLiteral( "Polygon ((2 2, 4 2, 4 4, 2 4, 2 2))" ); QgsGeometry geom1( QgsGeometry::fromWkt( wkt1 ) ); QgsGeometry geom2( QgsGeometry::fromWkt( wkt2 ) ); QgsGeometry empty; @@ -3646,7 +3646,7 @@ void TestQgsGeometry::unaryUnion() void TestQgsGeometry::dataStream() { - QString wkt = "Point (40 50)"; + QString wkt = QStringLiteral( "Point (40 50)" ); QgsGeometry geom( QgsGeometry::fromWkt( wkt ) ); QByteArray ba; @@ -3675,51 +3675,51 @@ void TestQgsGeometry::dataStream() void TestQgsGeometry::exportToGeoJSON() { //Point - QString wkt = "Point (40 50)"; + QString wkt = QStringLiteral( "Point (40 50)" ); QgsGeometry geom( QgsGeometry::fromWkt( wkt ) ); QString obtained = geom.exportToGeoJSON(); - QString geojson = "{\"type\": \"Point\", \"coordinates\": [40, 50]}"; + QString geojson = QStringLiteral( "{\"type\": \"Point\", \"coordinates\": [40, 50]}" ); QCOMPARE( obtained, geojson ); //MultiPoint - wkt = "MultiPoint (0 0, 10 0, 10 10, 20 10)"; + wkt = QStringLiteral( "MultiPoint (0 0, 10 0, 10 10, 20 10)" ); geom = QgsGeometry::fromWkt( wkt ); obtained = geom.exportToGeoJSON(); - geojson = "{\"type\": \"MultiPoint\", \"coordinates\": [ [0, 0], [10, 0], [10, 10], [20, 10]] }"; + geojson = QStringLiteral( "{\"type\": \"MultiPoint\", \"coordinates\": [ [0, 0], [10, 0], [10, 10], [20, 10]] }" ); QCOMPARE( obtained, geojson ); //Linestring - wkt = "LineString(0 0, 10 0, 10 10, 20 10)"; + wkt = QStringLiteral( "LineString(0 0, 10 0, 10 10, 20 10)" ); geom = QgsGeometry::fromWkt( wkt ); obtained = geom.exportToGeoJSON(); - geojson = "{\"type\": \"LineString\", \"coordinates\": [ [0, 0], [10, 0], [10, 10], [20, 10]]}"; + geojson = QStringLiteral( "{\"type\": \"LineString\", \"coordinates\": [ [0, 0], [10, 0], [10, 10], [20, 10]]}" ); QCOMPARE( obtained, geojson ); //MultiLineString - wkt = "MultiLineString ((0 0, 10 0, 10 10, 20 10),(30 30, 40 30, 40 40, 50 40))"; + wkt = QStringLiteral( "MultiLineString ((0 0, 10 0, 10 10, 20 10),(30 30, 40 30, 40 40, 50 40))" ); geom = QgsGeometry::fromWkt( wkt ); obtained = geom.exportToGeoJSON(); - geojson = "{\"type\": \"MultiLineString\", \"coordinates\": [[ [0, 0], [10, 0], [10, 10], [20, 10]], [ [30, 30], [40, 30], [40, 40], [50, 40]]] }"; + geojson = QStringLiteral( "{\"type\": \"MultiLineString\", \"coordinates\": [[ [0, 0], [10, 0], [10, 10], [20, 10]], [ [30, 30], [40, 30], [40, 40], [50, 40]]] }" ); QCOMPARE( obtained, geojson ); //Polygon - wkt = "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0 ),(2 2, 4 2, 4 4, 2 4, 2 2))"; + wkt = QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0 ),(2 2, 4 2, 4 4, 2 4, 2 2))" ); geom = QgsGeometry::fromWkt( wkt ); obtained = geom.exportToGeoJSON(); - geojson = "{\"type\": \"Polygon\", \"coordinates\": [[ [0, 0], [10, 0], [10, 10], [0, 10], [0, 0]], [ [2, 2], [4, 2], [4, 4], [2, 4], [2, 2]]] }"; + geojson = QStringLiteral( "{\"type\": \"Polygon\", \"coordinates\": [[ [0, 0], [10, 0], [10, 10], [0, 10], [0, 0]], [ [2, 2], [4, 2], [4, 4], [2, 4], [2, 2]]] }" ); QCOMPARE( obtained, geojson ); //MultiPolygon - wkt = "MultiPolygon (((0 0, 10 0, 10 10, 0 10, 0 0 )),((2 2, 4 2, 4 4, 2 4, 2 2)))"; + wkt = QStringLiteral( "MultiPolygon (((0 0, 10 0, 10 10, 0 10, 0 0 )),((2 2, 4 2, 4 4, 2 4, 2 2)))" ); geom = QgsGeometry::fromWkt( wkt ); obtained = geom.exportToGeoJSON(); - geojson = "{\"type\": \"MultiPolygon\", \"coordinates\": [[[ [0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]], [[ [2, 2], [4, 2], [4, 4], [2, 4], [2, 2]]]] }"; + geojson = QStringLiteral( "{\"type\": \"MultiPolygon\", \"coordinates\": [[[ [0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]], [[ [2, 2], [4, 2], [4, 4], [2, 4], [2, 2]]]] }" ); QCOMPARE( obtained, geojson ); // no geometry QgsGeometry nullGeom( nullptr ); obtained = nullGeom.exportToGeoJSON(); - geojson = "null"; + geojson = QStringLiteral( "null" ); QCOMPARE( obtained, geojson ); } @@ -3825,7 +3825,7 @@ void TestQgsGeometry::wkbInOut() void TestQgsGeometry::segmentizeCircularString() { - QString wkt( "CIRCULARSTRING( 0 0, 0.5 0.5, 2 0 )" ); + QString wkt( QStringLiteral( "CIRCULARSTRING( 0 0, 0.5 0.5, 2 0 )" ) ); QgsCircularString* circularString = dynamic_cast( QgsGeometryFactory::geomFromWkt( wkt ) ); QVERIFY( circularString ); QgsLineString* lineString = circularString->curveToLine(); diff --git a/tests/src/core/testqgsgml.cpp b/tests/src/core/testqgsgml.cpp index 442c859dab8d..656cdf5ef3de 100644 --- a/tests/src/core/testqgsgml.cpp +++ b/tests/src/core/testqgsgml.cpp @@ -101,8 +101,8 @@ const QString data1( " featureMaps = gmlParser.featuresMap(); @@ -137,12 +137,12 @@ void TestQgsGML::testFromByteArray() void TestQgsGML::testStreamingParser() { QgsFields fields; - fields.append( QgsField( "intfield", QVariant::Int, "int" ) ); - fields.append( QgsField( "longfield", QVariant::LongLong, "longlong" ) ); - fields.append( QgsField( "doublefield", QVariant::Double, "double" ) ); - fields.append( QgsField( "strfield", QVariant::String, "string" ) ); - fields.append( QgsField( "datetimefield", QVariant::DateTime, "datetime" ) ); - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + fields.append( QgsField( QStringLiteral( "intfield" ), QVariant::Int, QStringLiteral( "int" ) ) ); + fields.append( QgsField( QStringLiteral( "longfield" ), QVariant::LongLong, QStringLiteral( "longlong" ) ) ); + fields.append( QgsField( QStringLiteral( "doublefield" ), QVariant::Double, QStringLiteral( "double" ) ) ); + fields.append( QgsField( QStringLiteral( "strfield" ), QVariant::String, QStringLiteral( "string" ) ) ); + fields.append( QgsField( QStringLiteral( "datetimefield" ), QVariant::DateTime, QStringLiteral( "datetime" ) ) ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( data1.mid( 0, data1.size() / 2 ).toAscii(), false ), true ); QCOMPARE( gmlParser.getAndStealReadyFeatures().size(), 0 ); QCOMPARE( gmlParser.processData( data1.mid( data1.size() / 2 ).toAscii(), true ), true ); @@ -168,7 +168,7 @@ void TestQgsGML::testStreamingParser() void TestQgsGML::testStreamingParserInvalidGML() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( "", true ), false ); QCOMPARE( gmlParser.getAndStealReadyFeatures().size(), 0 ); } @@ -176,7 +176,7 @@ void TestQgsGML::testStreamingParserInvalidGML() void TestQgsGML::testPointGML2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -202,7 +202,7 @@ void TestQgsGML::testPointGML2() void TestQgsGML::testLineStringGML2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -231,7 +231,7 @@ void TestQgsGML::testLineStringGML2() void TestQgsGML::testPolygonGML2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -269,7 +269,7 @@ void TestQgsGML::testPolygonGML2() void TestQgsGML::testMultiPointGML2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -307,7 +307,7 @@ void TestQgsGML::testMultiPointGML2() void TestQgsGML::testMultiLineStringGML2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -347,7 +347,7 @@ void TestQgsGML::testMultiLineStringGML2() void TestQgsGML::testMultiPolygonGML2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -384,7 +384,7 @@ void TestQgsGML::testMultiPolygonGML2() void TestQgsGML::testPointGML3() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -412,7 +412,7 @@ void TestQgsGML::testPointGML3() void TestQgsGML::testPointGML3_EPSG_4326() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -440,7 +440,7 @@ void TestQgsGML::testPointGML3_EPSG_4326() void TestQgsGML::testPointGML3_urn_EPSG_4326() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -468,7 +468,7 @@ void TestQgsGML::testPointGML3_urn_EPSG_4326() void TestQgsGML::testPointGML3_EPSG_4326_honour_EPSG() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields, QgsGmlStreamingParser::Honour_EPSG ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields, QgsGmlStreamingParser::Honour_EPSG ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -496,7 +496,7 @@ void TestQgsGML::testPointGML3_EPSG_4326_honour_EPSG() void TestQgsGML::testPointGML3_EPSG_4326_honour_EPSG_invert() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields, QgsGmlStreamingParser::Honour_EPSG, true ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields, QgsGmlStreamingParser::Honour_EPSG, true ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -524,7 +524,7 @@ void TestQgsGML::testPointGML3_EPSG_4326_honour_EPSG_invert() void TestQgsGML::testLineStringGML3() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -553,7 +553,7 @@ void TestQgsGML::testLineStringGML3() void TestQgsGML::testLineStringGML3_LineStringSegment() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -580,7 +580,7 @@ void TestQgsGML::testLineStringGML3_LineStringSegment() void TestQgsGML::testPolygonGML3() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -618,7 +618,7 @@ void TestQgsGML::testPolygonGML3() void TestQgsGML::testPolygonGML3_srsDimension_on_Polygon() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -650,7 +650,7 @@ void TestQgsGML::testPolygonGML3_srsDimension_on_Polygon() void TestQgsGML::testMultiLineStringGML3() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -690,7 +690,7 @@ void TestQgsGML::testMultiLineStringGML3() void TestQgsGML::testMultiPolygonGML3() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -736,7 +736,7 @@ void TestQgsGML::testMultiPolygonGML3() void TestQgsGML::testPointGML3_2() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -793,7 +793,7 @@ void TestQgsGML::testBoundingBoxGML2() void TestQgsGML::testBoundingBoxGML3() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -824,7 +824,7 @@ void TestQgsGML::testNumberMatchedNumberReturned() QgsFields fields; // No attribute { - QgsGmlStreamingParser gmlParser( "", "", fields ); + QgsGmlStreamingParser gmlParser( QLatin1String( "" ), QLatin1String( "" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -834,7 +834,7 @@ void TestQgsGML::testNumberMatchedNumberReturned() } // Valid numberOfFeatures { - QgsGmlStreamingParser gmlParser( "", "", fields ); + QgsGmlStreamingParser gmlParser( QLatin1String( "" ), QLatin1String( "" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" " " " my_exception" @@ -909,19 +909,19 @@ void TestQgsGML::testException() void TestQgsGML::testTuple() { QgsFields fields; - fields.append( QgsField( "my_first_attr", QVariant::Int, "int" ) ); - fields.append( QgsField( "my_second_attr", QVariant::Int, "int" ) ); + fields.append( QgsField( QStringLiteral( "my_first_attr" ), QVariant::Int, QStringLiteral( "int" ) ) ); + fields.append( QgsField( QStringLiteral( "my_second_attr" ), QVariant::Int, QStringLiteral( "int" ) ) ); QList layerProperties; QgsGmlStreamingParser::LayerProperties prop; - prop.mName = "ns:firstlayer"; - prop.mGeometryAttribute = "geom"; + prop.mName = QStringLiteral( "ns:firstlayer" ); + prop.mGeometryAttribute = QStringLiteral( "geom" ); layerProperties.append( prop ); - prop.mName = "ns:secondlayer"; - prop.mGeometryAttribute = "geom"; + prop.mName = QStringLiteral( "ns:secondlayer" ); + prop.mGeometryAttribute = QStringLiteral( "geom" ); layerProperties.append( prop ); QMap< QString, QPair > mapFieldNameToSrcLayerNameFieldName; - mapFieldNameToSrcLayerNameFieldName.insert( "my_first_attr", QPair( "ns:firstlayer", "a" ) ); - mapFieldNameToSrcLayerNameFieldName.insert( "my_second_attr", QPair( "ns:secondlayer", "a" ) ); + mapFieldNameToSrcLayerNameFieldName.insert( QStringLiteral( "my_first_attr" ), QPair( QStringLiteral( "ns:firstlayer" ), QStringLiteral( "a" ) ) ); + mapFieldNameToSrcLayerNameFieldName.insert( QStringLiteral( "my_second_attr" ), QPair( QStringLiteral( "ns:secondlayer" ), QStringLiteral( "a" ) ) ); QgsGmlStreamingParser gmlParser( layerProperties, fields, mapFieldNameToSrcLayerNameFieldName ); QCOMPARE( gmlParser.processData( QByteArray( " layerProperties; QgsGmlStreamingParser::LayerProperties prop; - prop.mName = "ns:mylayer"; - prop.mGeometryAttribute = "geom"; + prop.mName = QStringLiteral( "ns:mylayer" ); + prop.mGeometryAttribute = QStringLiteral( "geom" ); layerProperties.append( prop ); QMap< QString, QPair > mapFieldNameToSrcLayerNameFieldName; - mapFieldNameToSrcLayerNameFieldName.insert( "my_first_attr", QPair( "ns:mylayer", "b" ) ); + mapFieldNameToSrcLayerNameFieldName.insert( QStringLiteral( "my_first_attr" ), QPair( QStringLiteral( "ns:mylayer" ), QStringLiteral( "b" ) ) ); QgsGmlStreamingParser gmlParser( layerProperties, fields, mapFieldNameToSrcLayerNameFieldName ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -1015,7 +1015,7 @@ void TestQgsGML::testTruncatedResponse() void TestQgsGML::testPartialFeature() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -1032,7 +1032,7 @@ void TestQgsGML::testPartialFeature() void TestQgsGML::testThroughOGRGeometry() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" @@ -1068,7 +1068,7 @@ void TestQgsGML::testThroughOGRGeometry() void TestQgsGML::testThroughOGRGeometry_urn_EPSG_4326() { QgsFields fields; - QgsGmlStreamingParser gmlParser( "mytypename", "mygeom", fields ); + QgsGmlStreamingParser gmlParser( QStringLiteral( "mytypename" ), QStringLiteral( "mygeom" ), fields ); QCOMPARE( gmlParser.processData( QByteArray( "" diff --git a/tests/src/core/testqgsgradients.cpp b/tests/src/core/testqgsgradients.cpp index 18effc21cc1e..cb53659c7807 100644 --- a/tests/src/core/testqgsgradients.cpp +++ b/tests/src/core/testqgsgradients.cpp @@ -100,7 +100,7 @@ void TestQgsGradients::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -122,7 +122,7 @@ void TestQgsGradients::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Gradient Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsGradients::cleanupTestCase() @@ -141,7 +141,7 @@ void TestQgsGradients::cleanupTestCase() void TestQgsGradients::gradientSymbol() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer test

                                                                                                                                                                                    \n" ); mGradientFill->setColor( QColor( "red" ) ); mGradientFill->setColor2( QColor( "blue" ) ); mGradientFill->setGradientType( QgsGradientFillSymbolLayer::Linear ); @@ -155,7 +155,7 @@ void TestQgsGradients::gradientSymbol() void TestQgsGradients::gradientSymbolColors() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer color test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer color test

                                                                                                                                                                                    \n" ); mGradientFill->setColor( QColor( "green" ) ); mGradientFill->setColor2( QColor( "white" ) ); QVERIFY( imageCheck( "gradient_colors" ) ); @@ -178,7 +178,7 @@ void TestQgsGradients::gradientSymbolRamp() void TestQgsGradients::gradientSymbolRadial() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer radial test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer radial test

                                                                                                                                                                                    \n" ); mGradientFill->setGradientType( QgsGradientFillSymbolLayer::Radial ); QVERIFY( imageCheck( "gradient_radial" ) ); mGradientFill->setGradientType( QgsGradientFillSymbolLayer::Linear ); @@ -186,7 +186,7 @@ void TestQgsGradients::gradientSymbolRadial() void TestQgsGradients::gradientSymbolConical() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer conical test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer conical test

                                                                                                                                                                                    \n" ); mGradientFill->setGradientType( QgsGradientFillSymbolLayer::Conical ); mGradientFill->setReferencePoint1( QPointF( 0.5, 0.5 ) ); QVERIFY( imageCheck( "gradient_conical" ) ); @@ -196,7 +196,7 @@ void TestQgsGradients::gradientSymbolConical() void TestQgsGradients::gradientSymbolViewport() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer viewport test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer viewport test

                                                                                                                                                                                    \n" ); mGradientFill->setCoordinateMode( QgsGradientFillSymbolLayer::Viewport ); QVERIFY( imageCheck( "gradient_viewport" ) ); mGradientFill->setCoordinateMode( QgsGradientFillSymbolLayer::Feature ); @@ -204,7 +204,7 @@ void TestQgsGradients::gradientSymbolViewport() void TestQgsGradients::gradientSymbolReferencePoints() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer reference points test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer reference points test

                                                                                                                                                                                    \n" ); mGradientFill->setReferencePoint1( QPointF( 0.5, 0.4 ) ); mGradientFill->setReferencePoint2( QPointF( 0, 0.2 ) ); QVERIFY( imageCheck( "gradient_refpoints" ) ); @@ -214,7 +214,7 @@ void TestQgsGradients::gradientSymbolReferencePoints() void TestQgsGradients::gradientSymbolCentroid() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer centroid reference point test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer centroid reference point test

                                                                                                                                                                                    \n" ); mGradientFill->setReferencePoint1IsCentroid( true ); QVERIFY( imageCheck( "gradient_ref1centroid" ) ); mGradientFill->setReferencePoint1IsCentroid( false ); @@ -225,7 +225,7 @@ void TestQgsGradients::gradientSymbolCentroid() void TestQgsGradients::gradientSymbolReflectSpread() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer reflect spread test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer reflect spread test

                                                                                                                                                                                    \n" ); mGradientFill->setReferencePoint2( QPointF( 0.5, 0.5 ) ); mGradientFill->setGradientSpread( QgsGradientFillSymbolLayer::Reflect ); QVERIFY( imageCheck( "gradient_reflect" ) ); @@ -235,7 +235,7 @@ void TestQgsGradients::gradientSymbolReflectSpread() void TestQgsGradients::gradientSymbolRepeatSpread() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer repeat spread test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer repeat spread test

                                                                                                                                                                                    \n" ); mGradientFill->setReferencePoint2( QPointF( 0.5, 0.5 ) ); mGradientFill->setGradientSpread( QgsGradientFillSymbolLayer::Repeat ); QVERIFY( imageCheck( "gradient_repeat" ) ); @@ -245,7 +245,7 @@ void TestQgsGradients::gradientSymbolRepeatSpread() void TestQgsGradients::gradientSymbolRotate() { - mReport += "

                                                                                                                                                                                    Gradient symbol renderer rotate test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol renderer rotate test

                                                                                                                                                                                    \n" ); mGradientFill->setAngle( 90 ); QVERIFY( imageCheck( "gradient_rotate" ) ); mGradientFill->setAngle( 0 ); @@ -253,7 +253,7 @@ void TestQgsGradients::gradientSymbolRotate() void TestQgsGradients::gradientSymbolFromQml() { - mReport += "

                                                                                                                                                                                    Gradient symbol from QML test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Gradient symbol from QML test

                                                                                                                                                                                    \n" ); QVERIFY( setQml( "gradient" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -288,7 +288,7 @@ bool TestQgsGradients::imageCheck( const QString& theTestType ) //ensure the rendered output matches our control image mMapSettings.setExtent( mpPolysLayer->extent() ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_gradient" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_gradient" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgshistogram.cpp b/tests/src/core/testqgshistogram.cpp index 97600bf2e260..c7055d94d1f8 100644 --- a/tests/src/core/testqgshistogram.cpp +++ b/tests/src/core/testqgshistogram.cpp @@ -132,13 +132,13 @@ void TestQgsHistogram::fromLayer() QVERIFY( !h.setValues( 0, QString() ) ); - QgsVectorLayer* layer = new QgsVectorLayer( "Point?field=col1:real", "layer", "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:real" ), QStringLiteral( "layer" ), QStringLiteral( "memory" ) ); QVERIFY( layer->isValid() ); QgsFeatureList features; for ( int i = 1; i <= 10; ++i ) { QgsFeature f( layer->dataProvider()->fields(), i ); - f.setAttribute( "col1", i ); + f.setAttribute( QStringLiteral( "col1" ), i ); features << f; } layer->dataProvider()->addFeatures( features ); diff --git a/tests/src/core/testqgsimageoperation.cpp b/tests/src/core/testqgsimageoperation.cpp index 18e76ea4659c..179f7ae2daa0 100644 --- a/tests/src/core/testqgsimageoperation.cpp +++ b/tests/src/core/testqgsimageoperation.cpp @@ -95,9 +95,9 @@ void TestQgsImageOperation::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); - mReport += "

                                                                                                                                                                                    Image Operation Tests

                                                                                                                                                                                    \n"; - mSampleImage = QString( TEST_DATA_DIR ) + "/sample_image.png"; - mTransparentSampleImage = QString( TEST_DATA_DIR ) + "/sample_alpha_image.png"; + mReport += QLatin1String( "

                                                                                                                                                                                    Image Operation Tests

                                                                                                                                                                                    \n" ); + mSampleImage = QStringLiteral( TEST_DATA_DIR ) + "/sample_image.png"; + mTransparentSampleImage = QStringLiteral( TEST_DATA_DIR ) + "/sample_alpha_image.png"; } void TestQgsImageOperation::cleanupTestCase() @@ -123,10 +123,10 @@ void TestQgsImageOperation::cleanup() void TestQgsImageOperation::smallImageOp() { - QImage image( QString( TEST_DATA_DIR ) + "/small_sample_image.png" ); + QImage image( QStringLiteral( TEST_DATA_DIR ) + "/small_sample_image.png" ); QgsImageOperation::convertToGrayscale( image, QgsImageOperation::GrayscaleLightness ); - bool result = imageCheck( QString( "imageop_smallimage" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_smallimage" ), image, 0 ); QVERIFY( result ); } @@ -135,7 +135,7 @@ void TestQgsImageOperation::grayscaleLightness() QImage image( mSampleImage ); QgsImageOperation::convertToGrayscale( image, QgsImageOperation::GrayscaleLightness ); - bool result = imageCheck( QString( "imageop_graylightness" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_graylightness" ), image, 0 ); QVERIFY( result ); } @@ -144,7 +144,7 @@ void TestQgsImageOperation::grayscaleLuminosity() QImage image( mSampleImage ); QgsImageOperation::convertToGrayscale( image, QgsImageOperation::GrayscaleLuminosity ); - bool result = imageCheck( QString( "imageop_grayluminosity" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_grayluminosity" ), image, 0 ); QVERIFY( result ); } @@ -153,7 +153,7 @@ void TestQgsImageOperation::grayscaleAverage() QImage image( mSampleImage ); QgsImageOperation::convertToGrayscale( image, QgsImageOperation::GrayscaleAverage ); - bool result = imageCheck( QString( "imageop_grayaverage" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_grayaverage" ), image, 0 ); QVERIFY( result ); } @@ -162,7 +162,7 @@ void TestQgsImageOperation::brightnessContrastNoChange() QImage image( mSampleImage ); QgsImageOperation::adjustBrightnessContrast( image, 0, 1.0 ); - bool result = imageCheck( QString( "imageop_bcnochange" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_bcnochange" ), image, 0 ); QVERIFY( result ); } @@ -171,7 +171,7 @@ void TestQgsImageOperation::increaseBrightness() QImage image( mSampleImage ); QgsImageOperation::adjustBrightnessContrast( image, 50, 1.0 ); - bool result = imageCheck( QString( "imageop_increasebright" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_increasebright" ), image, 0 ); QVERIFY( result ); } @@ -180,7 +180,7 @@ void TestQgsImageOperation::decreaseBrightness() QImage image( mSampleImage ); QgsImageOperation::adjustBrightnessContrast( image, -50, 1.0 ); - bool result = imageCheck( QString( "imageop_decreasebright" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_decreasebright" ), image, 0 ); QVERIFY( result ); } @@ -189,7 +189,7 @@ void TestQgsImageOperation::increaseContrast() QImage image( mSampleImage ); QgsImageOperation::adjustBrightnessContrast( image, 0, 30.0 ); - bool result = imageCheck( QString( "imageop_increasecontrast" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_increasecontrast" ), image, 0 ); QVERIFY( result ); } @@ -198,7 +198,7 @@ void TestQgsImageOperation::decreaseContrast() QImage image( mSampleImage ); QgsImageOperation::adjustBrightnessContrast( image, 0, 0.1 ); - bool result = imageCheck( QString( "imageop_decreasecontrast" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_decreasecontrast" ), image, 0 ); QVERIFY( result ); } @@ -207,7 +207,7 @@ void TestQgsImageOperation::hueSaturationNoChange() QImage image( mSampleImage ); QgsImageOperation::adjustHueSaturation( image, 1.0 ); - bool result = imageCheck( QString( "imageop_satnochange" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_satnochange" ), image, 0 ); QVERIFY( result ); } @@ -216,7 +216,7 @@ void TestQgsImageOperation::increaseSaturation() QImage image( mSampleImage ); QgsImageOperation::adjustHueSaturation( image, 5.0 ); - bool result = imageCheck( QString( "imageop_increasesat" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_increasesat" ), image, 0 ); QVERIFY( result ); } @@ -225,7 +225,7 @@ void TestQgsImageOperation::decreaseSaturation() QImage image( mSampleImage ); QgsImageOperation::adjustHueSaturation( image, 0.5 ); - bool result = imageCheck( QString( "imageop_decreasesat" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_decreasesat" ), image, 0 ); QVERIFY( result ); } @@ -234,7 +234,7 @@ void TestQgsImageOperation::colorizeFull() QImage image( mSampleImage ); QgsImageOperation::adjustHueSaturation( image, 1.0, QColor( 255, 255, 0 ), 1.0 ); - bool result = imageCheck( QString( "imageop_colorizefull" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_colorizefull" ), image, 0 ); QVERIFY( result ); } @@ -243,7 +243,7 @@ void TestQgsImageOperation::colorizePartial() QImage image( mSampleImage ); QgsImageOperation::adjustHueSaturation( image, 1.0, QColor( 255, 255, 0 ), 0.5 ); - bool result = imageCheck( QString( "imageop_colorizepartial" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_colorizepartial" ), image, 0 ); QVERIFY( result ); } @@ -252,7 +252,7 @@ void TestQgsImageOperation::opacityNoChange() QImage image( mSampleImage ); QgsImageOperation::multiplyOpacity( image, 1.0 ); - bool result = imageCheck( QString( "imageop_opacitynochange" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_opacitynochange" ), image, 0 ); QVERIFY( result ); } @@ -261,7 +261,7 @@ void TestQgsImageOperation::opacityIncrease() QImage image( mSampleImage ); QgsImageOperation::multiplyOpacity( image, 2.0 ); - bool result = imageCheck( QString( "imageop_opacityincrease" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_opacityincrease" ), image, 0 ); QVERIFY( result ); } @@ -270,7 +270,7 @@ void TestQgsImageOperation::opacityDecrease() QImage image( mSampleImage ); QgsImageOperation::multiplyOpacity( image, 0.5 ); - bool result = imageCheck( QString( "imageop_opacitydecrease" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_opacitydecrease" ), image, 0 ); QVERIFY( result ); } @@ -279,7 +279,7 @@ void TestQgsImageOperation::overlayColor() QImage image( mSampleImage ); QgsImageOperation::overlayColor( image, QColor( 0, 255, 255 ) ); - bool result = imageCheck( QString( "imageop_overlaycolor" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_overlaycolor" ), image, 0 ); QVERIFY( result ); } @@ -294,7 +294,7 @@ void TestQgsImageOperation::distanceTransformMaxDist() QgsImageOperation::distanceTransform( image, props ); - bool result = imageCheck( QString( "imageop_dt_max" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_dt_max" ), image, 0 ); QVERIFY( result ); } @@ -310,7 +310,7 @@ void TestQgsImageOperation::distanceTransformSetSpread() QgsImageOperation::distanceTransform( image, props ); - bool result = imageCheck( QString( "imageop_dt_spread" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_dt_spread" ), image, 0 ); QVERIFY( result ); } @@ -325,7 +325,7 @@ void TestQgsImageOperation::distanceTransformInterior() QgsImageOperation::distanceTransform( image, props ); - bool result = imageCheck( QString( "imageop_dt_interior" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_dt_interior" ), image, 0 ); QVERIFY( result ); } @@ -338,7 +338,7 @@ void TestQgsImageOperation::distanceTransformMisc() props.ramp = nullptr; props.shadeExterior = false; QgsImageOperation::distanceTransform( image, props ); - bool result = imageCheck( QString( "imageop_nochange" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_nochange" ), image, 0 ); QVERIFY( result ); //zero spread @@ -350,7 +350,7 @@ void TestQgsImageOperation::distanceTransformMisc() props2.ramp = &ramp; props2.shadeExterior = false; QgsImageOperation::distanceTransform( image2, props2 ); - result = imageCheck( QString( "imageop_zerospread" ), image2, 0 ); + result = imageCheck( QStringLiteral( "imageop_zerospread" ), image2, 0 ); QVERIFY( result ); } @@ -359,7 +359,7 @@ void TestQgsImageOperation::stackBlur() QImage image( mSampleImage ); QgsImageOperation::stackBlur( image, 10 ); - bool result = imageCheck( QString( "imageop_stackblur" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_stackblur" ), image, 0 ); QVERIFY( result ); QCOMPARE( image.format(), QImage::Format_ARGB32 ); } @@ -370,25 +370,25 @@ void TestQgsImageOperation::stackBlurPremultiplied() image = image.convertToFormat( QImage::Format_ARGB32_Premultiplied ); QgsImageOperation::stackBlur( image, 10 ); - bool result = imageCheck( QString( "imageop_stackblur" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_stackblur" ), image, 0 ); QVERIFY( result ); QCOMPARE( image.format(), QImage::Format_ARGB32_Premultiplied ); } void TestQgsImageOperation::alphaOnlyBlur() { - QImage image( QString( TEST_DATA_DIR ) + "/small_sample_image.png" ); + QImage image( QStringLiteral( TEST_DATA_DIR ) + "/small_sample_image.png" ); QgsImageOperation::stackBlur( image, 10, true ); - bool result = imageCheck( QString( "imageop_stackblur_alphaonly" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_stackblur_alphaonly" ), image, 0 ); QVERIFY( result ); QCOMPARE( image.format(), QImage::Format_ARGB32 ); - QImage premultImage( QString( TEST_DATA_DIR ) + "/small_sample_image.png" ); + QImage premultImage( QStringLiteral( TEST_DATA_DIR ) + "/small_sample_image.png" ); premultImage = premultImage.convertToFormat( QImage::Format_ARGB32_Premultiplied ); QgsImageOperation::stackBlur( premultImage, 10, true ); - result = imageCheck( QString( "imageop_stackblur_alphaonly" ), premultImage, 0 ); + result = imageCheck( QStringLiteral( "imageop_stackblur_alphaonly" ), premultImage, 0 ); QVERIFY( result ); QCOMPARE( premultImage.format(), QImage::Format_ARGB32_Premultiplied ); } @@ -398,7 +398,7 @@ void TestQgsImageOperation::gaussianBlur() QImage image( mSampleImage ); QImage* blurredImage = QgsImageOperation::gaussianBlur( image, 30 ); - bool result = imageCheck( QString( "imageop_gaussianblur" ), *blurredImage, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_gaussianblur" ), *blurredImage, 0 ); QCOMPARE( blurredImage->format(), QImage::Format_ARGB32 ); delete blurredImage; QVERIFY( result ); @@ -407,13 +407,13 @@ void TestQgsImageOperation::gaussianBlur() //todo small, zero radius void TestQgsImageOperation::gaussianBlurSmall() { - QImage image( QString( TEST_DATA_DIR ) + "/small_sample_image.png" ); + QImage image( QStringLiteral( TEST_DATA_DIR ) + "/small_sample_image.png" ); image = image.convertToFormat( QImage::Format_ARGB32_Premultiplied ); QImage* blurredImage = QgsImageOperation::gaussianBlur( image, 10 ); QCOMPARE( blurredImage->format(), QImage::Format_ARGB32_Premultiplied ); - bool result = imageCheck( QString( "imageop_gaussianblur_small" ), *blurredImage, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_gaussianblur_small" ), *blurredImage, 0 ); delete blurredImage; QVERIFY( result ); } @@ -423,7 +423,7 @@ void TestQgsImageOperation::gaussianBlurNoChange() QImage image( mSampleImage ); QImage* blurredImage = QgsImageOperation::gaussianBlur( image, 0 ); - bool result = imageCheck( QString( "imageop_nochange" ), *blurredImage, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_nochange" ), *blurredImage, 0 ); delete blurredImage; QVERIFY( result ); } @@ -433,7 +433,7 @@ void TestQgsImageOperation::flipHorizontal() QImage image( mSampleImage ); QgsImageOperation::flipImage( image, QgsImageOperation::FlipHorizontal ); - bool result = imageCheck( QString( "imageop_fliphoz" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_fliphoz" ), image, 0 ); QVERIFY( result ); } @@ -442,7 +442,7 @@ void TestQgsImageOperation::flipVertical() QImage image( mSampleImage ); QgsImageOperation::flipImage( image, QgsImageOperation::FlipVertical ); - bool result = imageCheck( QString( "imageop_flipvert" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "imageop_flipvert" ), image, 0 ); QVERIFY( result ); } @@ -464,7 +464,7 @@ bool TestQgsImageOperation::imageCheck( const QString& testName, QImage &image, QString fileName = tempDir + testName + ".png"; imageWithBackground.save( fileName, "PNG" ); QgsRenderChecker checker; - checker.setControlPathPrefix( "image_operations" ); + checker.setControlPathPrefix( QStringLiteral( "image_operations" ) ); checker.setControlName( "expected_" + testName ); checker.setRenderedImage( fileName ); checker.setColorTolerance( 2 ); diff --git a/tests/src/core/testqgsinvertedpolygonrenderer.cpp b/tests/src/core/testqgsinvertedpolygonrenderer.cpp index ab02f72036c2..cf3742e7fd7c 100644 --- a/tests/src/core/testqgsinvertedpolygonrenderer.cpp +++ b/tests/src/core/testqgsinvertedpolygonrenderer.cpp @@ -89,7 +89,7 @@ void TestQgsInvertedPolygon::initTestCase() QString myPolysFileName = mTestDataDir + "polys_overlapping.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); mpPolysLayer->setSimplifyMethod( simplifyMethod ); @@ -98,7 +98,7 @@ void TestQgsInvertedPolygon::initTestCase() QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPolysLayer ); mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Inverted Polygon Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Inverted Polygon Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsInvertedPolygon::cleanupTestCase() @@ -117,14 +117,14 @@ void TestQgsInvertedPolygon::cleanupTestCase() void TestQgsInvertedPolygon::singleSubRenderer() { - mReport += "

                                                                                                                                                                                    Inverted polygon renderer, single sub renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Inverted polygon renderer, single sub renderer test

                                                                                                                                                                                    \n" ); QVERIFY( setQml( mpPolysLayer, "inverted_polys_single.qml" ) ); QVERIFY( imageCheck( "inverted_polys_single" ) ); } void TestQgsInvertedPolygon::graduatedSubRenderer() { - mReport += "

                                                                                                                                                                                    Inverted polygon renderer, graduated sub renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Inverted polygon renderer, graduated sub renderer test

                                                                                                                                                                                    \n" ); QVERIFY( setQml( mpPolysLayer, "inverted_polys_graduated.qml" ) ); QVERIFY( imageCheck( "inverted_polys_graduated" ) ); } @@ -132,15 +132,15 @@ void TestQgsInvertedPolygon::graduatedSubRenderer() void TestQgsInvertedPolygon::preprocess() { // FIXME will have to find some overlapping polygons - mReport += "

                                                                                                                                                                                    Inverted polygon renderer, preprocessing test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Inverted polygon renderer, preprocessing test

                                                                                                                                                                                    \n" ); QVERIFY( setQml( mpPolysLayer, "inverted_polys_preprocess.qml" ) ); QVERIFY( imageCheck( "inverted_polys_preprocess" ) ); } void TestQgsInvertedPolygon::projectionTest() { - mReport += "

                                                                                                                                                                                    Inverted polygon renderer, projection test

                                                                                                                                                                                    \n"; - mMapSettings.setDestinationCrs( QgsCoordinateReferenceSystem( "EPSG:2154" ) ); + mReport += QLatin1String( "

                                                                                                                                                                                    Inverted polygon renderer, projection test

                                                                                                                                                                                    \n" ); + mMapSettings.setDestinationCrs( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:2154" ) ) ); mMapSettings.setCrsTransformEnabled( true ); QgsRectangle extent( QgsPoint( -8639421, 8382691 ), QgsPoint( -3969110, 12570905 ) ); QVERIFY( setQml( mpPolysLayer, "inverted_polys_single.qml" ) ); @@ -203,7 +203,7 @@ bool TestQgsInvertedPolygon::imageCheck( const QString& theTestType, const QgsRe } mMapSettings.setOutputDpi( 96 ); QgsMultiRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_invertedpolygon" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_invertedpolygon" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); myChecker.setColorTolerance( 20 ); diff --git a/tests/src/core/testqgsjsonutils.cpp b/tests/src/core/testqgsjsonutils.cpp index 99fce4ca88ba..b492488326a5 100644 --- a/tests/src/core/testqgsjsonutils.cpp +++ b/tests/src/core/testqgsjsonutils.cpp @@ -32,7 +32,7 @@ class TestQgsJSONUtils : public QObject } { - list << "one" << "<',\"\\>" << "two"; + list << QStringLiteral( "one" ) << QStringLiteral( "<',\"\\>" ) << QStringLiteral( "two" ); const QString json = QgsJSONUtils::encodeValue( list ); QCOMPARE( json, QString( "[\"one\",\"<',\\\"\\\\>\",\"two\"]" ) ); const QVariant back = QgsJSONUtils::parseArray( json, QVariant::String ); @@ -54,7 +54,7 @@ class TestQgsJSONUtils : public QObject } { // check invalid entries are ignored - const QVariantList back = QgsJSONUtils::parseArray( "[1,\"a\",-2]", QVariant::Int ); + const QVariantList back = QgsJSONUtils::parseArray( QStringLiteral( "[1,\"a\",-2]" ), QVariant::Int ); QCOMPARE( back, list ); } } diff --git a/tests/src/core/testqgslabelingengine.cpp b/tests/src/core/testqgslabelingengine.cpp index a46a8266fe3c..2ca9e17537c0 100644 --- a/tests/src/core/testqgslabelingengine.cpp +++ b/tests/src/core/testqgslabelingengine.cpp @@ -58,12 +58,12 @@ class TestQgsLabelingEngine : public QObject void TestQgsLabelingEngine::initTestCase() { - mReport += "

                                                                                                                                                                                    Labeling Engine Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Labeling Engine Tests

                                                                                                                                                                                    \n" ); QgsApplication::init(); QgsApplication::initQgis(); QgsApplication::showSettings(); - QgsFontUtils::loadStandardTestFonts( QStringList() << "Bold" ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Bold" ) ); } void TestQgsLabelingEngine::cleanupTestCase() @@ -81,8 +81,8 @@ void TestQgsLabelingEngine::cleanupTestCase() void TestQgsLabelingEngine::init() { - QString filename = QString( TEST_DATA_DIR ) + "/points.shp"; - vl = new QgsVectorLayer( filename, "points", "ogr" ); + QString filename = QStringLiteral( TEST_DATA_DIR ) + "/points.shp"; + vl = new QgsVectorLayer( filename, QStringLiteral( "points" ), QStringLiteral( "ogr" ) ); Q_ASSERT( vl->isValid() ); QgsMapLayerRegistry::instance()->addMapLayer( vl ); } @@ -95,12 +95,12 @@ void TestQgsLabelingEngine::cleanup() void TestQgsLabelingEngine::setDefaultLabelParams( QgsVectorLayer* layer ) { - layer->setCustomProperty( "labeling/fontFamily", QgsFontUtils::getStandardTestFont( "Bold" ).family() ); - layer->setCustomProperty( "labeling/fontSize", 12 ); - layer->setCustomProperty( "labeling/namedStyle", "Bold" ); - layer->setCustomProperty( "labeling/textColorR", "200" ); - layer->setCustomProperty( "labeling/textColorG", "0" ); - layer->setCustomProperty( "labeling/textColorB", "200" ); + layer->setCustomProperty( QStringLiteral( "labeling/fontFamily" ), QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ).family() ); + layer->setCustomProperty( QStringLiteral( "labeling/fontSize" ), 12 ); + layer->setCustomProperty( QStringLiteral( "labeling/namedStyle" ), "Bold" ); + layer->setCustomProperty( QStringLiteral( "labeling/textColorR" ), "200" ); + layer->setCustomProperty( QStringLiteral( "labeling/textColorG" ), "0" ); + layer->setCustomProperty( QStringLiteral( "labeling/textColorB" ), "200" ); } void TestQgsLabelingEngine::testBasic() @@ -124,9 +124,9 @@ void TestQgsLabelingEngine::testBasic() QgsRenderContext context = QgsRenderContext::fromMapSettings( mapSettings ); context.setPainter( &p ); - vl->setCustomProperty( "labeling", "pal" ); - vl->setCustomProperty( "labeling/enabled", true ); - vl->setCustomProperty( "labeling/fieldName", "Class" ); + vl->setCustomProperty( QStringLiteral( "labeling" ), "pal" ); + vl->setCustomProperty( QStringLiteral( "labeling/enabled" ), true ); + vl->setCustomProperty( QStringLiteral( "labeling/fieldName" ), "Class" ); setDefaultLabelParams( vl ); QgsLabelingEngine engine; @@ -146,7 +146,7 @@ void TestQgsLabelingEngine::testBasic() job.waitForFinished(); QImage img2 = job.renderedImage(); - vl->setCustomProperty( "labeling/enabled", false ); + vl->setCustomProperty( QStringLiteral( "labeling/enabled" ), false ); QVERIFY( imageCheck( "labeling_basic", img2, 20 ) ); } @@ -174,7 +174,7 @@ void TestQgsLabelingEngine::testDiagrams() context.setPainter( &p ); bool res; - vl->loadNamedStyle( QString( TEST_DATA_DIR ) + "/points_diagrams.qml", res ); + vl->loadNamedStyle( QStringLiteral( TEST_DATA_DIR ) + "/points_diagrams.qml", res ); Q_ASSERT( res ); QgsLabelingEngine engine; @@ -210,13 +210,13 @@ void TestQgsLabelingEngine::testRuleBased() QgsPalLayerSettings s1; s1.enabled = true; - s1.fieldName = "Class"; + s1.fieldName = QStringLiteral( "Class" ); s1.obstacle = false; s1.dist = 2; s1.distInMapUnits = false; QgsTextFormat format = s1.format(); format.setColor( QColor( 200, 0, 200 ) ); - format.setFont( QgsFontUtils::getStandardTestFont( "Bold" ) ); + format.setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ) ); format.setSize( 12 ); s1.setFormat( format ); s1.placement = QgsPalLayerSettings::OverPoint; @@ -227,19 +227,19 @@ void TestQgsLabelingEngine::testRuleBased() QgsPalLayerSettings s2; s2.enabled = true; - s2.fieldName = "Class"; + s2.fieldName = QStringLiteral( "Class" ); s2.obstacle = false; s2.dist = 2; format = s2.format(); format.setColor( Qt::red ); - format.setFont( QgsFontUtils::getStandardTestFont( "Bold" ) ); + format.setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ) ); s2.setFormat( format ); s2.placement = QgsPalLayerSettings::OverPoint; s2.quadOffset = QgsPalLayerSettings::QuadrantBelowRight; s2.displayAll = true; - s2.setDataDefinedProperty( QgsPalLayerSettings::Size, true, true, "18", QString() ); + s2.setDataDefinedProperty( QgsPalLayerSettings::Size, true, true, QStringLiteral( "18" ), QString() ); - root->appendChild( new QgsRuleBasedLabeling::Rule( new QgsPalLayerSettings( s2 ), 0, 0, "Class = 'Jet'" ) ); + root->appendChild( new QgsRuleBasedLabeling::Rule( new QgsPalLayerSettings( s2 ), 0, 0, QStringLiteral( "Class = 'Jet'" ) ) ); vl->setLabeling( new QgsRuleBasedLabeling( root ) ); setDefaultLabelParams( vl ); @@ -301,18 +301,18 @@ void TestQgsLabelingEngine::zOrder() QgsPalLayerSettings pls1; pls1.enabled = true; - pls1.fieldName = "Class"; + pls1.fieldName = QStringLiteral( "Class" ); pls1.placement = QgsPalLayerSettings::OverPoint; pls1.quadOffset = QgsPalLayerSettings::QuadrantAboveRight; pls1.displayAll = true; QgsTextFormat format = pls1.format(); - format.setFont( QgsFontUtils::getStandardTestFont( "Bold" ) ); + format.setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ) ); format.setSize( 70 ); pls1.setFormat( format ); //use data defined coloring and font size so that stacking order of labels can be determined - pls1.setDataDefinedProperty( QgsPalLayerSettings::Color, true, true, "case when \"Class\"='Jet' then '#ff5500' when \"Class\"='B52' then '#00ffff' else '#ff00ff' end", QString() ); - pls1.setDataDefinedProperty( QgsPalLayerSettings::Size, true, true, "case when \"Class\"='Jet' then 100 when \"Class\"='B52' then 30 else 50 end", QString() ); + pls1.setDataDefinedProperty( QgsPalLayerSettings::Color, true, true, QStringLiteral( "case when \"Class\"='Jet' then '#ff5500' when \"Class\"='B52' then '#00ffff' else '#ff00ff' end" ), QString() ); + pls1.setDataDefinedProperty( QgsPalLayerSettings::Size, true, true, QStringLiteral( "case when \"Class\"='Jet' then 100 when \"Class\"='B52' then 30 else 50 end" ), QString() ); QgsVectorLayerLabelProvider* provider1 = new QgsVectorLayerLabelProvider( vl, QString(), true, &pls1 ); QgsLabelingEngine engine; @@ -329,7 +329,7 @@ void TestQgsLabelingEngine::zOrder() img = job.renderedImage(); //test data defined z-index - pls1.setDataDefinedProperty( QgsPalLayerSettings::ZIndex, true, true, "case when \"Class\"='Jet' then 3 when \"Class\"='B52' then 1 else 2 end", QString() ); + pls1.setDataDefinedProperty( QgsPalLayerSettings::ZIndex, true, true, QStringLiteral( "case when \"Class\"='Jet' then 3 when \"Class\"='B52' then 1 else 2 end" ), QString() ); provider1 = new QgsVectorLayerLabelProvider( vl, QString(), true, &pls1 ); engine.addProvider( provider1 ); p.begin( &img ); @@ -350,8 +350,8 @@ void TestQgsLabelingEngine::zOrder() engine.addProvider( provider1 ); //add a second layer - QString filename = QString( TEST_DATA_DIR ) + "/points.shp"; - QgsVectorLayer* vl2 = new QgsVectorLayer( filename, "points", "ogr" ); + QString filename = QStringLiteral( TEST_DATA_DIR ) + "/points.shp"; + QgsVectorLayer* vl2 = new QgsVectorLayer( filename, QStringLiteral( "points" ), QStringLiteral( "ogr" ) ); Q_ASSERT( vl2->isValid() ); QgsMapLayerRegistry::instance()->addMapLayer( vl2 ); @@ -386,7 +386,7 @@ void TestQgsLabelingEngine::zOrder() //try mixing layer order and z-index engine.removeProvider( provider1 ); - pls1.setDataDefinedProperty( QgsPalLayerSettings::ZIndex, true, true, "if(\"Class\"='Jet',3,0)", QString() ); + pls1.setDataDefinedProperty( QgsPalLayerSettings::ZIndex, true, true, QStringLiteral( "if(\"Class\"='Jet',3,0)" ), QString() ); provider1 = new QgsVectorLayerLabelProvider( vl, QString(), true, &pls1 ); engine.addProvider( provider1 ); @@ -422,7 +422,7 @@ void TestQgsLabelingEngine::testEncodeDecodePositionOrder() QCOMPARE( decoded, original ); //test decoding with a messy string - decoded = QgsLabelingUtils::decodePredefinedPositionOrder( ",tr,x,BSR, L, t,," ); + decoded = QgsLabelingUtils::decodePredefinedPositionOrder( QStringLiteral( ",tr,x,BSR, L, t,," ) ); QVector< QgsPalLayerSettings::PredefinedPointPosition > expected; expected << QgsPalLayerSettings::TopRight << QgsPalLayerSettings::BottomSlightlyRight << QgsPalLayerSettings::MiddleLeft << QgsPalLayerSettings::TopMiddle; @@ -433,12 +433,12 @@ void TestQgsLabelingEngine::testSubstitutions() { QgsPalLayerSettings settings; settings.useSubstitutions = false; - QgsStringReplacementCollection collection( QList< QgsStringReplacement >() << QgsStringReplacement( "aa", "bb" ) ); + QgsStringReplacementCollection collection( QList< QgsStringReplacement >() << QgsStringReplacement( QStringLiteral( "aa" ), QStringLiteral( "bb" ) ) ); settings.substitutions = collection; - settings.fieldName = QString( "'aa label'" ); + settings.fieldName = QStringLiteral( "'aa label'" ); settings.isExpression = true; - QgsVectorLayerLabelProvider* provider = new QgsVectorLayerLabelProvider( vl, "test", true, &settings ); + QgsVectorLayerLabelProvider* provider = new QgsVectorLayerLabelProvider( vl, QStringLiteral( "test" ), true, &settings ); QgsFeature f( vl->fields(), 1 ); f.setGeometry( QgsGeometry::fromPoint( QgsPoint( 1, 2 ) ) ); @@ -461,7 +461,7 @@ void TestQgsLabelingEngine::testSubstitutions() //with substitution settings.useSubstitutions = true; - QgsVectorLayerLabelProvider* provider2 = new QgsVectorLayerLabelProvider( vl, "test2", true, &settings ); + QgsVectorLayerLabelProvider* provider2 = new QgsVectorLayerLabelProvider( vl, QStringLiteral( "test2" ), true, &settings ); engine.addProvider( provider2 ); provider2->prepare( context, attributes ); @@ -493,10 +493,10 @@ void TestQgsLabelingEngine::testCapitalization() font.setCapitalization( QFont::MixedCase ); format.setFont( font ); settings.setFormat( format ); - settings.fieldName = QString( "'a teSt LABEL'" ); + settings.fieldName = QStringLiteral( "'a teSt LABEL'" ); settings.isExpression = true; - QgsVectorLayerLabelProvider* provider = new QgsVectorLayerLabelProvider( vl, "test", true, &settings ); + QgsVectorLayerLabelProvider* provider = new QgsVectorLayerLabelProvider( vl, QStringLiteral( "test" ), true, &settings ); engine.addProvider( provider ); provider->prepare( context, attributes ); provider->registerFeature( f, context ); @@ -506,7 +506,7 @@ void TestQgsLabelingEngine::testCapitalization() font.setCapitalization( QFont::AllUppercase ); format.setFont( font ); settings.setFormat( format ); - QgsVectorLayerLabelProvider* provider2 = new QgsVectorLayerLabelProvider( vl, "test2", true, &settings ); + QgsVectorLayerLabelProvider* provider2 = new QgsVectorLayerLabelProvider( vl, QStringLiteral( "test2" ), true, &settings ); engine.addProvider( provider2 ); provider2->prepare( context, attributes ); provider2->registerFeature( f, context ); @@ -516,7 +516,7 @@ void TestQgsLabelingEngine::testCapitalization() font.setCapitalization( QFont::AllLowercase ); format.setFont( font ); settings.setFormat( format ); - QgsVectorLayerLabelProvider* provider3 = new QgsVectorLayerLabelProvider( vl, "test3", true, &settings ); + QgsVectorLayerLabelProvider* provider3 = new QgsVectorLayerLabelProvider( vl, QStringLiteral( "test3" ), true, &settings ); engine.addProvider( provider3 ); provider3->prepare( context, attributes ); provider3->registerFeature( f, context ); @@ -526,7 +526,7 @@ void TestQgsLabelingEngine::testCapitalization() font.setCapitalization( QFont::Capitalize ); format.setFont( font ); settings.setFormat( format ); - QgsVectorLayerLabelProvider* provider4 = new QgsVectorLayerLabelProvider( vl, "test4", true, &settings ); + QgsVectorLayerLabelProvider* provider4 = new QgsVectorLayerLabelProvider( vl, QStringLiteral( "test4" ), true, &settings ); engine.addProvider( provider4 ); provider4->prepare( context, attributes ); provider4->registerFeature( f, context ); @@ -547,7 +547,7 @@ bool TestQgsLabelingEngine::imageCheck( const QString& testName, QImage &image, QString fileName = tempDir + testName + ".png"; imageWithBackground.save( fileName, "PNG" ); QgsRenderChecker checker; - checker.setControlPathPrefix( "labelingengine" ); + checker.setControlPathPrefix( QStringLiteral( "labelingengine" ) ); checker.setControlName( "expected_" + testName ); checker.setRenderedImage( fileName ); checker.setColorTolerance( 2 ); diff --git a/tests/src/core/testqgslayertree.cpp b/tests/src/core/testqgslayertree.cpp index bf72d93e23b3..498f23b89f5c 100644 --- a/tests/src/core/testqgslayertree.cpp +++ b/tests/src/core/testqgslayertree.cpp @@ -67,9 +67,9 @@ void TestQgsLayerTree::initTestCase() QgsApplication::initQgis(); mRoot = new QgsLayerTreeGroup(); - mRoot->addGroup( "grp1" ); - mRoot->addGroup( "grp2" ); - mRoot->addGroup( "grp3" ); + mRoot->addGroup( QStringLiteral( "grp1" ) ); + mRoot->addGroup( QStringLiteral( "grp2" ) ); + mRoot->addGroup( QStringLiteral( "grp3" ) ); // all cases start with all items checked } @@ -167,7 +167,7 @@ void TestQgsLayerTree::testCheckStateMutuallyExclusive() QCOMPARE( mRoot->isVisible(), Qt::Checked ); // add the group back - will not be checked - mRoot->insertGroup( 0, "grp1" ); + mRoot->insertGroup( 0, QStringLiteral( "grp1" ) ); QCOMPARE( childState( 0 ), Qt::Unchecked ); QCOMPARE( childState( 1 ), Qt::Unchecked ); QCOMPARE( childState( 2 ), Qt::Checked ); @@ -186,7 +186,7 @@ void TestQgsLayerTree::testCheckStateMutuallyExclusive() QCOMPARE( mRoot->isVisible(), Qt::Checked ); // add the item back - mRoot->addGroup( "grp3" ); + mRoot->addGroup( QStringLiteral( "grp3" ) ); QCOMPARE( childState( 0 ), Qt::Checked ); QCOMPARE( childState( 1 ), Qt::Unchecked ); QCOMPARE( childState( 2 ), Qt::Unchecked ); @@ -205,9 +205,9 @@ void TestQgsLayerTree::testCheckStateMutuallyExclusiveEdgeCases() // starting with empty mutually exclusive group QgsLayerTreeGroup* root2 = new QgsLayerTreeGroup(); root2->setIsMutuallyExclusive( true ); - root2->addGroup( "1" ); + root2->addGroup( QStringLiteral( "1" ) ); QCOMPARE( QgsLayerTree::toGroup( root2->children().at( 0 ) )->isVisible(), Qt::Checked ); - root2->addGroup( "2" ); + root2->addGroup( QStringLiteral( "2" ) ); QCOMPARE( QgsLayerTree::toGroup( root2->children().at( 0 ) )->isVisible(), Qt::Checked ); QCOMPARE( QgsLayerTree::toGroup( root2->children().at( 1 ) )->isVisible(), Qt::Unchecked ); delete root2; @@ -215,7 +215,7 @@ void TestQgsLayerTree::testCheckStateMutuallyExclusiveEdgeCases() // check-uncheck the only child QgsLayerTreeGroup* root3 = new QgsLayerTreeGroup(); root3->setIsMutuallyExclusive( true ); - root3->addGroup( "1" ); + root3->addGroup( QStringLiteral( "1" ) ); QCOMPARE( QgsLayerTree::toGroup( root3->children().at( 0 ) )->isVisible(), Qt::Checked ); QgsLayerTree::toGroup( root3->children().at( 0 ) )->setVisible( Qt::Unchecked ); QCOMPARE( QgsLayerTree::toGroup( root3->children().at( 0 ) )->isVisible(), Qt::Unchecked ); @@ -229,18 +229,18 @@ void TestQgsLayerTree::testCheckStateMutuallyExclusiveEdgeCases() void TestQgsLayerTree::testShowHideAllSymbolNodes() { //new memory layer - QgsVectorLayer* vl = new QgsVectorLayer( "Point?field=col1:integer", "vl", "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); QVERIFY( vl->isValid() ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << vl ); //create a categorized renderer for layer QgsCategorizedSymbolRenderer* renderer = new QgsCategorizedSymbolRenderer(); - renderer->setClassAttribute( "col1" ); + renderer->setClassAttribute( QStringLiteral( "col1" ) ); renderer->setSourceSymbol( QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ) ); - renderer->addCategory( QgsRendererCategory( "a", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), "a" ) ); - renderer->addCategory( QgsRendererCategory( "b", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), "b" ) ); - renderer->addCategory( QgsRendererCategory( "c", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), "c" ) ); + renderer->addCategory( QgsRendererCategory( "a", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), QStringLiteral( "a" ) ) ); + renderer->addCategory( QgsRendererCategory( "b", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), QStringLiteral( "b" ) ) ); + renderer->addCategory( QgsRendererCategory( "c", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), QStringLiteral( "c" ) ) ); vl->setRenderer( renderer ); //create legend with symbology nodes for categorized renderer @@ -279,18 +279,18 @@ void TestQgsLayerTree::testShowHideAllSymbolNodes() void TestQgsLayerTree::testFindLegendNode() { //new memory layer - QgsVectorLayer* vl = new QgsVectorLayer( "Point?field=col1:integer", "vl", "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); QVERIFY( vl->isValid() ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << vl ); //create a categorized renderer for layer QgsCategorizedSymbolRenderer* renderer = new QgsCategorizedSymbolRenderer(); - renderer->setClassAttribute( "col1" ); + renderer->setClassAttribute( QStringLiteral( "col1" ) ); renderer->setSourceSymbol( QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ) ); - renderer->addCategory( QgsRendererCategory( "a", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), "a" ) ); - renderer->addCategory( QgsRendererCategory( "b", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), "b" ) ); - renderer->addCategory( QgsRendererCategory( "c", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), "c" ) ); + renderer->addCategory( QgsRendererCategory( "a", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), QStringLiteral( "a" ) ) ); + renderer->addCategory( QgsRendererCategory( "b", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), QStringLiteral( "b" ) ) ); + renderer->addCategory( QgsRendererCategory( "c", QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ), QStringLiteral( "c" ) ) ); vl->setRenderer( renderer ); //create legend with symbology nodes for categorized renderer @@ -322,15 +322,15 @@ void TestQgsLayerTree::testLegendSymbolCategorized() { //test retrieving/setting a categorized renderer's symbol through the legend node QgsCategorizedSymbolRenderer* renderer = new QgsCategorizedSymbolRenderer(); - renderer->setClassAttribute( "col1" ); + renderer->setClassAttribute( QStringLiteral( "col1" ) ); renderer->setSourceSymbol( QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ) ); QgsStringMap props; - props.insert( "color", "#ff0000" ); - renderer->addCategory( QgsRendererCategory( "a", QgsMarkerSymbol::createSimple( props ), "a" ) ); - props.insert( "color", "#00ff00" ); - renderer->addCategory( QgsRendererCategory( "b", QgsMarkerSymbol::createSimple( props ), "b" ) ); - props.insert( "color", "#0000ff" ); - renderer->addCategory( QgsRendererCategory( "c", QgsMarkerSymbol::createSimple( props ), "c" ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#ff0000" ) ); + renderer->addCategory( QgsRendererCategory( "a", QgsMarkerSymbol::createSimple( props ), QStringLiteral( "a" ) ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#00ff00" ) ); + renderer->addCategory( QgsRendererCategory( "b", QgsMarkerSymbol::createSimple( props ), QStringLiteral( "b" ) ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#0000ff" ) ); + renderer->addCategory( QgsRendererCategory( "c", QgsMarkerSymbol::createSimple( props ), QStringLiteral( "c" ) ) ); testRendererLegend( renderer ); } @@ -338,15 +338,15 @@ void TestQgsLayerTree::testLegendSymbolGraduated() { //test retrieving/setting a graduated renderer's symbol through the legend node QgsGraduatedSymbolRenderer* renderer = new QgsGraduatedSymbolRenderer(); - renderer->setClassAttribute( "col1" ); + renderer->setClassAttribute( QStringLiteral( "col1" ) ); renderer->setSourceSymbol( QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ) ); QgsStringMap props; - props.insert( "color", "#ff0000" ); - renderer->addClass( QgsRendererRange( 1, 2, QgsMarkerSymbol::createSimple( props ), "a" ) ); - props.insert( "color", "#00ff00" ); - renderer->addClass( QgsRendererRange( 2, 3, QgsMarkerSymbol::createSimple( props ), "b" ) ); - props.insert( "color", "#0000ff" ); - renderer->addClass( QgsRendererRange( 3, 4, QgsMarkerSymbol::createSimple( props ), "c" ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#ff0000" ) ); + renderer->addClass( QgsRendererRange( 1, 2, QgsMarkerSymbol::createSimple( props ), QStringLiteral( "a" ) ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#00ff00" ) ); + renderer->addClass( QgsRendererRange( 2, 3, QgsMarkerSymbol::createSimple( props ), QStringLiteral( "b" ) ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#0000ff" ) ); + renderer->addClass( QgsRendererRange( 3, 4, QgsMarkerSymbol::createSimple( props ), QStringLiteral( "c" ) ) ); testRendererLegend( renderer ); } @@ -355,12 +355,12 @@ void TestQgsLayerTree::testLegendSymbolRuleBased() //test retrieving/setting a rule based renderer's symbol through the legend node QgsRuleBasedRenderer::Rule* root = new QgsRuleBasedRenderer::Rule( 0 ); QgsStringMap props; - props.insert( "color", "#ff0000" ); - root->appendChild( new QgsRuleBasedRenderer::Rule( QgsMarkerSymbol::createSimple( props ), 0, 0, "\"col1\"=1" ) ); - props.insert( "color", "#00ff00" ); - root->appendChild( new QgsRuleBasedRenderer::Rule( QgsMarkerSymbol::createSimple( props ), 0, 0, "\"col1\"=2" ) ); - props.insert( "color", "#0000ff" ); - root->appendChild( new QgsRuleBasedRenderer::Rule( QgsMarkerSymbol::createSimple( props ), 0, 0, "ELSE" ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#ff0000" ) ); + root->appendChild( new QgsRuleBasedRenderer::Rule( QgsMarkerSymbol::createSimple( props ), 0, 0, QStringLiteral( "\"col1\"=1" ) ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#00ff00" ) ); + root->appendChild( new QgsRuleBasedRenderer::Rule( QgsMarkerSymbol::createSimple( props ), 0, 0, QStringLiteral( "\"col1\"=2" ) ) ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#0000ff" ) ); + root->appendChild( new QgsRuleBasedRenderer::Rule( QgsMarkerSymbol::createSimple( props ), 0, 0, QStringLiteral( "ELSE" ) ) ); QgsRuleBasedRenderer* renderer = new QgsRuleBasedRenderer( root ); testRendererLegend( renderer ); } @@ -373,7 +373,7 @@ void TestQgsLayerTree::testRendererLegend( QgsFeatureRenderer* renderer ) // #ff0000, #00ff00, #0000ff //new memory layer - QgsVectorLayer* vl = new QgsVectorLayer( "Point?field=col1:integer", "vl", "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); QVERIFY( vl->isValid() ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << vl ); @@ -407,7 +407,7 @@ void TestQgsLayerTree::testRendererLegend( QgsFeatureRenderer* renderer ) //another test - check directly setting symbol at renderer QgsStringMap props; - props.insert( "color", "#00ffff" ); + props.insert( QStringLiteral( "color" ), QStringLiteral( "#00ffff" ) ); renderer->setLegendSymbolItem( symbolList.at( 2 ).ruleKey(), QgsMarkerSymbol::createSimple( props ) ); m->refreshLayerLegend( n ); symbolNode = dynamic_cast< QgsSymbolLegendNode* >( m->findLegendNode( vl->id(), symbolList.at( 2 ).ruleKey() ) ); diff --git a/tests/src/core/testqgslegendrenderer.cpp b/tests/src/core/testqgslegendrenderer.cpp index 1cf9ba354f22..7125571ab3aa 100644 --- a/tests/src/core/testqgslegendrenderer.cpp +++ b/tests/src/core/testqgslegendrenderer.cpp @@ -41,7 +41,7 @@ static QString _fileNameForTest( const QString& testName ) return QDir::tempPath() + '/' + testName + ".png"; } -static void _setStandardTestFont( QgsLegendSettings& settings, const QString& style = "Roman" ) +static void _setStandardTestFont( QgsLegendSettings& settings, const QString& style = QStringLiteral( "Roman" ) ) { QList< QgsComposerLegendStyle::Style> styles; styles << QgsComposerLegendStyle::Title @@ -64,7 +64,7 @@ static void _renderLegend( const QString& testName, QgsLayerTreeModel* legendMod int dpi = 96; qreal dpmm = dpi / 25.4; QSize s( size.width() * dpmm, size.height() * dpmm ); - qDebug() << QString( "testName:%1 size=%2x%3 dpmm=%4 s=%5x%6" ).arg( testName ).arg( size.width() ).arg( size.height() ).arg( dpmm ).arg( s.width() ).arg( s.height() ); + qDebug() << QStringLiteral( "testName:%1 size=%2x%3 dpmm=%4 s=%5x%6" ).arg( testName ).arg( size.width() ).arg( size.height() ).arg( dpmm ).arg( s.width() ).arg( s.height() ); QImage img( s, QImage::Format_ARGB32_Premultiplied ); img.fill( Qt::white ); @@ -79,7 +79,7 @@ static void _renderLegend( const QString& testName, QgsLayerTreeModel* legendMod static bool _verifyImage( const QString& testName, QString &report ) { QgsRenderChecker checker; - checker.setControlPathPrefix( "legend" ); + checker.setControlPathPrefix( QStringLiteral( "legend" ) ); checker.setControlName( "expected_" + testName ); checker.setRenderedImage( _fileNameForTest( testName ) ); checker.setSizeTolerance( 3, 3 ); @@ -143,7 +143,7 @@ void TestQgsLegendRenderer::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); - mReport += "

                                                                                                                                                                                    Legend Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Legend Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsLegendRenderer::cleanupTestCase() @@ -162,25 +162,25 @@ void TestQgsLegendRenderer::cleanupTestCase() void TestQgsLegendRenderer::init() { - mVL1 = new QgsVectorLayer( "LineString", "Line Layer", "memory" ); + mVL1 = new QgsVectorLayer( QStringLiteral( "LineString" ), QStringLiteral( "Line Layer" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( mVL1 ); QgsLineSymbol* sym1 = new QgsLineSymbol(); sym1->setColor( Qt::magenta ); mVL1->setRenderer( new QgsSingleSymbolRenderer( sym1 ) ); - mVL2 = new QgsVectorLayer( "Polygon", "Polygon Layer", "memory" ); + mVL2 = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "Polygon Layer" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( mVL2 ); QgsFillSymbol* sym2 = new QgsFillSymbol(); sym2->setColor( Qt::cyan ); mVL2->setRenderer( new QgsSingleSymbolRenderer( sym2 ) ); - mVL3 = new QgsVectorLayer( "Point", "Point Layer", "memory" ); + mVL3 = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "Point Layer" ), QStringLiteral( "memory" ) ); { QgsVectorDataProvider* pr = mVL3->dataProvider(); QList attrs; - attrs << QgsField( "test_attr", QVariant::Int ); + attrs << QgsField( QStringLiteral( "test_attr" ), QVariant::Int ); pr->addAttributes( attrs ); QgsFields fields; @@ -206,25 +206,25 @@ void TestQgsLegendRenderer::init() QgsMapLayerRegistry::instance()->addMapLayer( mVL3 ); static char raster_array[] = { 1, 2, 2, 1 }; - QString rasterUri = QString( "MEM:::DATAPOINTER=%1,PIXELS=2,LINES=2" ).arg(( qulonglong ) raster_array ); - mRL = new QgsRasterLayer( rasterUri, QString( "Raster Layer" ), QString( "gdal" ) ); + QString rasterUri = QStringLiteral( "MEM:::DATAPOINTER=%1,PIXELS=2,LINES=2" ).arg(( qulonglong ) raster_array ); + mRL = new QgsRasterLayer( rasterUri, QStringLiteral( "Raster Layer" ), QStringLiteral( "gdal" ) ); QgsMapLayerRegistry::instance()->addMapLayer( mRL ); QgsCategoryList cats; QgsMarkerSymbol* sym3_1 = new QgsMarkerSymbol(); sym3_1->setColor( Qt::red ); - cats << QgsRendererCategory( 1, sym3_1, "Red" ); + cats << QgsRendererCategory( 1, sym3_1, QStringLiteral( "Red" ) ); QgsMarkerSymbol* sym3_2 = new QgsMarkerSymbol(); sym3_2->setColor( Qt::green ); - cats << QgsRendererCategory( 2, sym3_2, "Green" ); + cats << QgsRendererCategory( 2, sym3_2, QStringLiteral( "Green" ) ); QgsMarkerSymbol* sym3_3 = new QgsMarkerSymbol(); sym3_3->setColor( Qt::blue ); - cats << QgsRendererCategory( 3, sym3_3, "Blue" ); - QgsCategorizedSymbolRenderer* r3 = new QgsCategorizedSymbolRenderer( "test_attr", cats ); + cats << QgsRendererCategory( 3, sym3_3, QStringLiteral( "Blue" ) ); + QgsCategorizedSymbolRenderer* r3 = new QgsCategorizedSymbolRenderer( QStringLiteral( "test_attr" ), cats ); mVL3->setRenderer( r3 ); mRoot = new QgsLayerTreeGroup(); - QgsLayerTreeGroup* grp1 = mRoot->addGroup( "Line + Polygon" ); + QgsLayerTreeGroup* grp1 = mRoot->addGroup( QStringLiteral( "Line + Polygon" ) ); grp1->addLayer( mVL1 ); grp1->addLayer( mVL2 ); mRoot->addLayer( mVL3 ); @@ -258,7 +258,7 @@ void TestQgsLegendRenderer::testModel() QCOMPARE( lstNodes[0]->data( Qt::DisplayRole ).toString(), QString( "Line Layer" ) ); // set user text - QgsMapLayerLegendUtils::setLegendNodeUserLabel( nodeVL1, 0, "Hurray" ); + QgsMapLayerLegendUtils::setLegendNodeUserLabel( nodeVL1, 0, QStringLiteral( "Hurray" ) ); legendModel.refreshLayerLegend( nodeVL1 ); @@ -272,7 +272,7 @@ void TestQgsLegendRenderer::testModel() void TestQgsLegendRenderer::testBasic() { - QString testName = "legend_basic"; + QString testName = QStringLiteral( "legend_basic" ); QgsLayerTreeModel legendModel( mRoot ); @@ -284,7 +284,7 @@ void TestQgsLegendRenderer::testBasic() void TestQgsLegendRenderer::testBigMarker() { - QString testName = "legend_big_marker"; + QString testName = QStringLiteral( "legend_big_marker" ); QgsMarkerSymbol* sym = new QgsMarkerSymbol(); sym->setColor( Qt::red ); @@ -305,7 +305,7 @@ void TestQgsLegendRenderer::testBigMarker() void TestQgsLegendRenderer::testMapUnits() { - QString testName = "legend_mapunits"; + QString testName = QStringLiteral( "legend_mapunits" ); QgsMarkerSymbol* sym = new QgsMarkerSymbol(); sym->setColor( Qt::red ); @@ -341,38 +341,38 @@ void TestQgsLegendRenderer::testMapUnits() void TestQgsLegendRenderer::testTallSymbol() { - QString testName = "legend_tall_symbol"; + QString testName = QStringLiteral( "legend_tall_symbol" ); QgsCategorizedSymbolRenderer* catRenderer = dynamic_cast( mVL3->renderer() ); QVERIFY( catRenderer ); - catRenderer->updateCategoryLabel( 1, "This is\nthree lines\nlong label" ); + catRenderer->updateCategoryLabel( 1, QStringLiteral( "This is\nthree lines\nlong label" ) ); - mVL2->setName( "This is a two lines\nlong label" ); + mVL2->setName( QStringLiteral( "This is a two lines\nlong label" ) ); QgsLayerTreeModel legendModel( mRoot ); QgsLegendSettings settings; - settings.setWrapChar( "\n" ); + settings.setWrapChar( QStringLiteral( "\n" ) ); settings.setSymbolSize( QSizeF( 10.0, 10.0 ) ); _setStandardTestFont( settings ); _renderLegend( testName, &legendModel, settings ); QVERIFY( _verifyImage( testName, mReport ) ); - mVL2->setName( "Polygon Layer" ); + mVL2->setName( QStringLiteral( "Polygon Layer" ) ); } void TestQgsLegendRenderer::testLongSymbolText() { - QString testName = "legend_long_symbol_text"; + QString testName = QStringLiteral( "legend_long_symbol_text" ); QgsCategorizedSymbolRenderer* catRenderer = dynamic_cast( mVL3->renderer() ); QVERIFY( catRenderer ); - catRenderer->updateCategoryLabel( 1, "This is\nthree lines\nlong label" ); + catRenderer->updateCategoryLabel( 1, QStringLiteral( "This is\nthree lines\nlong label" ) ); QgsLayerTreeModel legendModel( mRoot ); QgsLegendSettings settings; - settings.setWrapChar( "\n" ); + settings.setWrapChar( QStringLiteral( "\n" ) ); _setStandardTestFont( settings ); _renderLegend( testName, &legendModel, settings ); QVERIFY( _verifyImage( testName, mReport ) ); @@ -380,7 +380,7 @@ void TestQgsLegendRenderer::testLongSymbolText() void TestQgsLegendRenderer::testThreeColumns() { - QString testName = "legend_three_columns"; + QString testName = QStringLiteral( "legend_three_columns" ); QgsLayerTreeModel legendModel( mRoot ); @@ -393,7 +393,7 @@ void TestQgsLegendRenderer::testThreeColumns() void TestQgsLegendRenderer::testFilterByMap() { - QString testName = "legend_filter_by_map"; + QString testName = QStringLiteral( "legend_filter_by_map" ); QgsLayerTreeModel legendModel( mRoot ); @@ -419,11 +419,11 @@ void TestQgsLegendRenderer::testFilterByMap() void TestQgsLegendRenderer::testFilterByMapSameSymbol() { - QgsVectorLayer* vl4 = new QgsVectorLayer( "Point", "Point Layer", "memory" ); + QgsVectorLayer* vl4 = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "Point Layer" ), QStringLiteral( "memory" ) ); { QgsVectorDataProvider* pr = vl4->dataProvider(); QList attrs; - attrs << QgsField( "test_attr", QVariant::Int ); + attrs << QgsField( QStringLiteral( "test_attr" ), QVariant::Int ); pr->addAttributes( attrs ); QgsFields fields; @@ -452,17 +452,17 @@ void TestQgsLegendRenderer::testFilterByMapSameSymbol() QgsCategoryList cats; QgsMarkerSymbol* sym4_1 = new QgsMarkerSymbol(); sym4_1->setColor( Qt::red ); - cats << QgsRendererCategory( 1, sym4_1, "Red1" ); + cats << QgsRendererCategory( 1, sym4_1, QStringLiteral( "Red1" ) ); QgsMarkerSymbol* sym4_2 = new QgsMarkerSymbol(); sym4_2->setColor( Qt::red ); - cats << QgsRendererCategory( 2, sym4_2, "Red2" ); + cats << QgsRendererCategory( 2, sym4_2, QStringLiteral( "Red2" ) ); QgsMarkerSymbol* sym4_3 = new QgsMarkerSymbol(); sym4_3->setColor( Qt::red ); - cats << QgsRendererCategory( 3, sym4_3, "Red3" ); - QgsCategorizedSymbolRenderer* r4 = new QgsCategorizedSymbolRenderer( "test_attr", cats ); + cats << QgsRendererCategory( 3, sym4_3, QStringLiteral( "Red3" ) ); + QgsCategorizedSymbolRenderer* r4 = new QgsCategorizedSymbolRenderer( QStringLiteral( "test_attr" ), cats ); vl4->setRenderer( r4 ); - QString testName = "legend_filter_by_map_dupe"; + QString testName = QStringLiteral( "legend_filter_by_map_dupe" ); QgsLayerTreeGroup* root = new QgsLayerTreeGroup(); root->addLayer( vl4 ); @@ -478,7 +478,7 @@ void TestQgsLegendRenderer::testFilterByMapSameSymbol() legendModel.setLegendFilterByMap( &mapSettings ); QgsLegendSettings settings; - _setStandardTestFont( settings, "Bold" ); + _setStandardTestFont( settings, QStringLiteral( "Bold" ) ); _renderLegend( testName, &legendModel, settings ); QVERIFY( _verifyImage( testName, mReport ) ); @@ -495,7 +495,7 @@ bool TestQgsLegendRenderer::_testLegendColumns( int itemCount, int columnCount, QList< QgsVectorLayer* > layers; for ( int i = 1; i <= itemCount; ++i ) { - QgsVectorLayer* vl = new QgsVectorLayer( "Polygon", QString( "Layer %1" ).arg( i ), "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "Layer %1" ).arg( i ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( vl ); vl->setRenderer( new QgsSingleSymbolRenderer( sym->clone() ) ); root->addLayer( vl ); @@ -506,7 +506,7 @@ bool TestQgsLegendRenderer::_testLegendColumns( int itemCount, int columnCount, QgsLayerTreeModel legendModel( root ); QgsLegendSettings settings; settings.setColumnCount( columnCount ); - _setStandardTestFont( settings, "Bold" ); + _setStandardTestFont( settings, QStringLiteral( "Bold" ) ); _renderLegend( testName, &legendModel, settings ); bool result = _verifyImage( testName, mReport ); @@ -546,7 +546,7 @@ void TestQgsLegendRenderer::testColumns() void TestQgsLegendRenderer::testRasterBorder() { - QString testName = "legend_raster_border"; + QString testName = QStringLiteral( "legend_raster_border" ); QgsLayerTreeGroup* root = new QgsLayerTreeGroup(); root->addLayer( mRL ); @@ -563,7 +563,7 @@ void TestQgsLegendRenderer::testRasterBorder() void TestQgsLegendRenderer::testFilterByPolygon() { - QString testName = "legend_filter_by_polygon"; + QString testName = QStringLiteral( "legend_filter_by_polygon" ); QgsLayerTreeModel legendModel( mRoot ); @@ -580,7 +580,7 @@ void TestQgsLegendRenderer::testFilterByPolygon() mapSettings.setLayers( ll ); // select only within a polygon - QgsGeometry geom( QgsGeometry::fromWkt( "POLYGON((0 0,2 0,2 2,0 2,0 0))" ) ); + QgsGeometry geom( QgsGeometry::fromWkt( QStringLiteral( "POLYGON((0 0,2 0,2 2,0 2,0 0))" ) ) ); legendModel.setLegendFilter( &mapSettings, /*useExtent*/ false, geom ); QgsLegendSettings settings; @@ -600,7 +600,7 @@ void TestQgsLegendRenderer::testFilterByPolygon() void TestQgsLegendRenderer::testFilterByExpression() { - QString testName = "legend_filter_by_expression"; + QString testName = QStringLiteral( "legend_filter_by_expression" ); QgsLayerTreeModel legendModel( mRoot ); @@ -619,7 +619,7 @@ void TestQgsLegendRenderer::testFilterByExpression() // use an expression to only include the red point QgsLayerTreeLayer* layer = legendModel.rootGroup()->findLayer( mVL3->id() ); QVERIFY( layer ); - QgsLayerTreeUtils::setLegendFilterByExpression( *layer, "test_attr=1" ); + QgsLayerTreeUtils::setLegendFilterByExpression( *layer, QStringLiteral( "test_attr=1" ) ); legendModel.setLegendFilterByMap( &mapSettings ); @@ -641,13 +641,13 @@ void TestQgsLegendRenderer::testFilterByExpression() void TestQgsLegendRenderer::testDiagramAttributeLegend() { - QgsVectorLayer* vl4 = new QgsVectorLayer( "Point", "Point Layer", "memory" ); + QgsVectorLayer* vl4 = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "Point Layer" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( vl4 ); QgsDiagramSettings ds; ds.categoryColors = QList() << QColor( 255, 0, 0 ) << QColor( 0, 255, 0 ); - ds.categoryAttributes = QList() << "\"cat1\"" << "\"cat2\""; - ds.categoryLabels = QStringList() << "cat 1" << "cat 2"; + ds.categoryAttributes = QList() << QStringLiteral( "\"cat1\"" ) << QStringLiteral( "\"cat2\"" ); + ds.categoryLabels = QStringList() << QStringLiteral( "cat 1" ) << QStringLiteral( "cat 2" ); QgsLinearlyInterpolatedDiagramRenderer *dr = new QgsLinearlyInterpolatedDiagramRenderer(); dr->setLowerValue( 0.0 ); @@ -671,8 +671,8 @@ void TestQgsLegendRenderer::testDiagramAttributeLegend() QgsLayerTreeModel legendModel( root ); QgsLegendSettings settings; - _setStandardTestFont( settings, "Bold" ); - _renderLegend( "legend_diagram_attributes", &legendModel, settings ); + _setStandardTestFont( settings, QStringLiteral( "Bold" ) ); + _renderLegend( QStringLiteral( "legend_diagram_attributes" ), &legendModel, settings ); QVERIFY( _verifyImage( "legend_diagram_attributes", mReport ) ); QgsMapLayerRegistry::instance()->removeMapLayer( vl4 ); @@ -680,13 +680,13 @@ void TestQgsLegendRenderer::testDiagramAttributeLegend() void TestQgsLegendRenderer::testDiagramSizeLegend() { - QgsVectorLayer* vl4 = new QgsVectorLayer( "Point", "Point Layer", "memory" ); + QgsVectorLayer* vl4 = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "Point Layer" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( vl4 ); QgsDiagramSettings ds; ds.categoryColors = QList() << QColor( 255, 0, 0 ) << QColor( 0, 255, 0 ); - ds.categoryAttributes = QList() << "\"cat1\"" << "\"cat2\""; - ds.categoryLabels = QStringList() << "cat 1" << "cat 2"; + ds.categoryAttributes = QList() << QStringLiteral( "\"cat1\"" ) << QStringLiteral( "\"cat2\"" ); + ds.categoryLabels = QStringList() << QStringLiteral( "cat 1" ) << QStringLiteral( "cat 2" ); ds.scaleByArea = false; QgsLinearlyInterpolatedDiagramRenderer *dr = new QgsLinearlyInterpolatedDiagramRenderer(); @@ -711,8 +711,8 @@ void TestQgsLegendRenderer::testDiagramSizeLegend() QgsLayerTreeModel legendModel( root ); QgsLegendSettings settings; - _setStandardTestFont( settings, "Bold" ); - _renderLegend( "legend_diagram_size", &legendModel, settings ); + _setStandardTestFont( settings, QStringLiteral( "Bold" ) ); + _renderLegend( QStringLiteral( "legend_diagram_size" ), &legendModel, settings ); QVERIFY( _verifyImage( "legend_diagram_size", mReport ) ); QgsMapLayerRegistry::instance()->removeMapLayer( vl4 ); diff --git a/tests/src/core/testqgslinefillsymbol.cpp b/tests/src/core/testqgslinefillsymbol.cpp index 58ce6d5298e5..c738c5446d17 100644 --- a/tests/src/core/testqgslinefillsymbol.cpp +++ b/tests/src/core/testqgslinefillsymbol.cpp @@ -93,7 +93,7 @@ void TestQgsLineFillSymbol::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -115,7 +115,7 @@ void TestQgsLineFillSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Line Fill Symbol Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Line Fill Symbol Tests

                                                                                                                                                                                    \n" ); } void TestQgsLineFillSymbol::cleanupTestCase() @@ -134,12 +134,12 @@ void TestQgsLineFillSymbol::cleanupTestCase() void TestQgsLineFillSymbol::lineFillSymbol() { - mReport += "

                                                                                                                                                                                    Line fill symbol renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Line fill symbol renderer test

                                                                                                                                                                                    \n" ); QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "width", "1" ); - properties.insert( "capstyle", "flat" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "width" ), QStringLiteral( "1" ) ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "flat" ) ); QgsLineSymbol* lineSymbol = QgsLineSymbol::createSimple( properties ); mLineFill->setSubSymbol( lineSymbol ); @@ -148,14 +148,14 @@ void TestQgsLineFillSymbol::lineFillSymbol() void TestQgsLineFillSymbol::dataDefinedSubSymbol() { - mReport += "

                                                                                                                                                                                    Line fill symbol data defined sub symbol test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Line fill symbol data defined sub symbol test

                                                                                                                                                                                    \n" ); QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "width", "1" ); - properties.insert( "capstyle", "flat" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "width" ), QStringLiteral( "1" ) ); + properties.insert( QStringLiteral( "capstyle" ), QStringLiteral( "flat" ) ); QgsLineSymbol* lineSymbol = QgsLineSymbol::createSimple( properties ); - lineSymbol->symbolLayer( 0 )->setDataDefinedProperty( "color", new QgsDataDefined( QString( "if(\"Name\" ='Lake','#ff0000','#ff00ff')" ) ) ); + lineSymbol->symbolLayer( 0 )->setDataDefinedProperty( QStringLiteral( "color" ), new QgsDataDefined( QStringLiteral( "if(\"Name\" ='Lake','#ff0000','#ff00ff')" ) ) ); mLineFill->setSubSymbol( lineSymbol ); QVERIFY( imageCheck( "datadefined_subsymbol" ) ); } @@ -172,7 +172,7 @@ bool TestQgsLineFillSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPolysLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_linefill" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_linefill" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgsmaplayer.cpp b/tests/src/core/testqgsmaplayer.cpp index a80088c09dfd..f0290806b10a 100644 --- a/tests/src/core/testqgsmaplayer.cpp +++ b/tests/src/core/testqgsmaplayer.cpp @@ -93,7 +93,7 @@ void TestQgsMapLayer::init() myFileName = myFileName + "/points.shp"; QFileInfo myMapFileInfo( myFileName ); mpLayer = new QgsVectorLayer( myMapFileInfo.filePath(), - myMapFileInfo.completeBaseName(), "ogr" ); + myMapFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); } void TestQgsMapLayer::cleanup() diff --git a/tests/src/core/testqgsmaplayerstylemanager.cpp b/tests/src/core/testqgsmaplayerstylemanager.cpp index 8e8a311523ba..65e04cf377cf 100644 --- a/tests/src/core/testqgsmaplayerstylemanager.cpp +++ b/tests/src/core/testqgsmaplayerstylemanager.cpp @@ -59,7 +59,7 @@ void TestQgsMapLayerStyleManager::cleanupTestCase() void TestQgsMapLayerStyleManager::init() { - mVL = new QgsVectorLayer( "LineString", "Line Layer", "memory" ); + mVL = new QgsVectorLayer( QStringLiteral( "LineString" ), QStringLiteral( "Line Layer" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( mVL ); } @@ -125,8 +125,8 @@ void TestQgsMapLayerStyleManager::testReadWrite() QgsMapLayerStyleManager sm0( mVL ); - sm0.addStyleFromLayer( "blue" ); - sm0.setCurrentStyle( "blue" ); + sm0.addStyleFromLayer( QStringLiteral( "blue" ) ); + sm0.setCurrentStyle( QStringLiteral( "blue" ) ); QgsSingleSymbolRenderer* r1 = dynamic_cast( mVL->renderer() ); QVERIFY( r1 ); r1->symbol()->setColor( Qt::blue ); @@ -134,7 +134,7 @@ void TestQgsMapLayerStyleManager::testReadWrite() // read and write QDomDocument doc; - QDomElement mgrElem = doc.createElement( "map-layer-style-manager" ); + QDomElement mgrElem = doc.createElement( QStringLiteral( "map-layer-style-manager" ) ); doc.appendChild( mgrElem ); sm0.writeXml( mgrElem ); @@ -179,8 +179,8 @@ void TestQgsMapLayerStyleManager::testSwitchingStyles() { _setVLColor( mVL, Qt::red ); - mVL->styleManager()->addStyleFromLayer( "s1" ); - mVL->styleManager()->setCurrentStyle( "s1" ); + mVL->styleManager()->addStyleFromLayer( QStringLiteral( "s1" ) ); + mVL->styleManager()->setCurrentStyle( QStringLiteral( "s1" ) ); QCOMPARE( mVL->styleManager()->currentStyle(), QString( "s1" ) ); QCOMPARE( _getVLColor( mVL ), QColor( Qt::red ) ); @@ -190,7 +190,7 @@ void TestQgsMapLayerStyleManager::testSwitchingStyles() mVL->styleManager()->setCurrentStyle( QString() ); QCOMPARE( _getVLColor( mVL ), QColor( Qt::red ) ); - mVL->styleManager()->setCurrentStyle( "s1" ); + mVL->styleManager()->setCurrentStyle( QStringLiteral( "s1" ) ); QCOMPARE( _getVLColor( mVL ), QColor( Qt::green ) ); _setVLColor( mVL, Qt::blue ); @@ -198,7 +198,7 @@ void TestQgsMapLayerStyleManager::testSwitchingStyles() mVL->styleManager()->setCurrentStyle( QString() ); QCOMPARE( _getVLColor( mVL ), QColor( Qt::red ) ); - mVL->styleManager()->setCurrentStyle( "s1" ); + mVL->styleManager()->setCurrentStyle( QStringLiteral( "s1" ) ); QCOMPARE( _getVLColor( mVL ), QColor( Qt::blue ) ); } diff --git a/tests/src/core/testqgsmaprendererjob.cpp b/tests/src/core/testqgsmaprendererjob.cpp index 5c802fd69b4f..1fe8166f48ba 100644 --- a/tests/src/core/testqgsmaprendererjob.cpp +++ b/tests/src/core/testqgsmaprendererjob.cpp @@ -101,8 +101,8 @@ void TestQgsMapRendererJob::initTestCase() mMapSettings = new QgsMapSettings(); //create some objects that will be used in all tests... - mEncoding = "UTF-8"; - QgsField myField1( "Value", QVariant::Int, "int", 10, 0, "Value on lon" ); + mEncoding = QStringLiteral( "UTF-8" ); + QgsField myField1( QStringLiteral( "Value" ), QVariant::Int, QStringLiteral( "int" ), 10, 0, QStringLiteral( "Value on lon" ) ); mFields.append( myField1 ); mCRS = QgsCoordinateReferenceSystem( GEOWKT ); // @@ -180,13 +180,13 @@ void TestQgsMapRendererJob::initTestCase() // QFileInfo myPolyFileInfo( myFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QVERIFY( mpPolysLayer->isValid() ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPolysLayer ); // add the test layer to the maprender mMapSettings->setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Map Render Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Map Render Tests

                                                                                                                                                                                    \n" ); } void TestQgsMapRendererJob::cleanupTestCase() @@ -208,11 +208,11 @@ void TestQgsMapRendererJob::performanceTest() { mMapSettings->setExtent( mpPolysLayer->extent() ); QgsRenderChecker myChecker; - myChecker.setControlName( "expected_maprender" ); + myChecker.setControlName( QStringLiteral( "expected_maprender" ) ); mMapSettings->setFlag( QgsMapSettings::Antialiasing ); myChecker.setMapSettings( *mMapSettings ); myChecker.setColorTolerance( 5 ); - bool myResultFlag = myChecker.runTest( "maprender" ); + bool myResultFlag = myChecker.runTest( QStringLiteral( "maprender" ) ); mReport += myChecker.report(); QVERIFY( myResultFlag ); } @@ -224,32 +224,32 @@ void TestQgsMapRendererJob::testFourAdjacentTiles_data() QTest::addColumn( "shapeFile" ); QTest::addColumn( "qmlFile" ); - QString shapeFile = TEST_DATA_DIR + QString( "/france_parts.shp" ); - QString qmlFile = TEST_DATA_DIR + QString( "/adjacent_tiles/line_pattern_30_degree.qml" ); - QString controlName = "expected_adjacent_line_fill"; + QString shapeFile = TEST_DATA_DIR + QStringLiteral( "/france_parts.shp" ); + QString qmlFile = TEST_DATA_DIR + QStringLiteral( "/adjacent_tiles/line_pattern_30_degree.qml" ); + QString controlName = QStringLiteral( "expected_adjacent_line_fill" ); QStringList bboxList1; - bboxList1 << "-1.5,48,-0.5,49"; - bboxList1 << "-0.5,48,0.5,49"; - bboxList1 << "-1.5,47,-0.5,48"; - bboxList1 << "-0.5,47,0.5,48"; + bboxList1 << QStringLiteral( "-1.5,48,-0.5,49" ); + bboxList1 << QStringLiteral( "-0.5,48,0.5,49" ); + bboxList1 << QStringLiteral( "-1.5,47,-0.5,48" ); + bboxList1 << QStringLiteral( "-0.5,47,0.5,48" ); QTest::newRow( "adjacent_line_fill" ) << bboxList1 << controlName << shapeFile << qmlFile; - qmlFile = TEST_DATA_DIR + QString( "/adjacent_tiles/point_pattern_simple_marker.qml" ); - controlName = "expected_adjacent_marker_fill"; + qmlFile = TEST_DATA_DIR + QStringLiteral( "/adjacent_tiles/point_pattern_simple_marker.qml" ); + controlName = QStringLiteral( "expected_adjacent_marker_fill" ); QTest::newRow( "adjacent_marker_fill" ) << bboxList1 << controlName << shapeFile << qmlFile; - shapeFile = TEST_DATA_DIR + QString( "/lines.shp" ); - qmlFile = TEST_DATA_DIR + QString( "/adjacent_tiles/simple_line_dashed.qml" ); - controlName = "expected_adjacent_dashed_line"; + shapeFile = TEST_DATA_DIR + QStringLiteral( "/lines.shp" ); + qmlFile = TEST_DATA_DIR + QStringLiteral( "/adjacent_tiles/simple_line_dashed.qml" ); + controlName = QStringLiteral( "expected_adjacent_dashed_line" ); QStringList bboxList2; - bboxList2 << "-105,35,-95,45"; - bboxList2 << "-95,35,-85,45"; - bboxList2 << "-105,25,-95,35"; - bboxList2 << "-95,25,-85,35"; + bboxList2 << QStringLiteral( "-105,35,-95,45" ); + bboxList2 << QStringLiteral( "-95,35,-85,45" ); + bboxList2 << QStringLiteral( "-105,25,-95,35" ); + bboxList2 << QStringLiteral( "-95,25,-85,35" ); QTest::newRow( "adjacent_dashed_line" ) << bboxList2 << controlName << shapeFile << qmlFile; } @@ -264,7 +264,7 @@ void TestQgsMapRendererJob::testFourAdjacentTiles() QVERIFY( bboxList.size() == 4 ); //create maplayer, set QML and add to maplayer registry - QgsVectorLayer* vectorLayer = new QgsVectorLayer( shapeFile, "testshape", "ogr" ); + QgsVectorLayer* vectorLayer = new QgsVectorLayer( shapeFile, QStringLiteral( "testshape" ), QStringLiteral( "ogr" ) ); //todo: read QML QFile symbologyFile( qmlFile ); @@ -296,7 +296,7 @@ void TestQgsMapRendererJob::testFourAdjacentTiles() QgsMapSettings mapSettings; //extent - QStringList rectCoords = bboxList.at( i ).split( "," ); + QStringList rectCoords = bboxList.at( i ).split( QStringLiteral( "," ) ); if ( rectCoords.size() != 4 ) { QFAIL( "bbox string invalid" ); @@ -319,12 +319,12 @@ void TestQgsMapRendererJob::testFourAdjacentTiles() QgsMapLayerRegistry::instance()->removeMapLayers( QStringList() << vectorLayer->id() ); - QString renderedImagePath = QDir::tempPath() + "/" + QTest::currentDataTag() + QString( ".png" ); + QString renderedImagePath = QDir::tempPath() + "/" + QTest::currentDataTag() + QStringLiteral( ".png" ); globalImage.save( renderedImagePath ); QgsRenderChecker checker; - checker.setControlPathPrefix( "adjacent_tiles" ); + checker.setControlPathPrefix( QStringLiteral( "adjacent_tiles" ) ); checker.setControlName( controlName ); bool result = checker.compareImages( QTest::currentDataTag(), 100, renderedImagePath ); mReport += checker.report(); diff --git a/tests/src/core/testqgsmaprotation.cpp b/tests/src/core/testqgsmaprotation.cpp index 417841d73568..3643ef892cbe 100644 --- a/tests/src/core/testqgsmaprotation.cpp +++ b/tests/src/core/testqgsmaprotation.cpp @@ -46,7 +46,7 @@ class TestQgsMapRotation : public QObject , mLinesLayer( 0 ) , mMapSettings( 0 ) { - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; } ~TestQgsMapRotation(); @@ -96,14 +96,14 @@ void TestQgsMapRotation::initTestCase() QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); mapLayers << mPointsLayer; //create a line layer that will be used in all tests... QString myLinesFileName = mTestDataDir + "lines_cardinals.shp"; QFileInfo myLinesFileInfo( myLinesFileName ); mLinesLayer = new QgsVectorLayer( myLinesFileInfo.filePath(), - myLinesFileInfo.completeBaseName(), "ogr" ); + myLinesFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); mapLayers << mLinesLayer; // Register all layers with the registry @@ -114,9 +114,9 @@ void TestQgsMapRotation::initTestCase() // re-set it to the size of the expected image mMapSettings->setOutputSize( QSize( 256, 256 ) ); - mReport += "

                                                                                                                                                                                    Map Rotation Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Map Rotation Tests

                                                                                                                                                                                    \n" ); - QgsFontUtils::loadStandardTestFonts( QStringList() << "Bold" ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Bold" ) ); } TestQgsMapRotation::~TestQgsMapRotation() @@ -211,7 +211,7 @@ void TestQgsMapRotation::linesLayer() QgsPalLayerSettings palSettings; palSettings.readFromLayer( mLinesLayer ); QgsTextFormat format = palSettings.format(); - format.setFont( QgsFontUtils::getStandardTestFont( "Bold" ) ); + format.setFont( QgsFontUtils::getStandardTestFont( QStringLiteral( "Bold" ) ) ); format.setSize( 16 ); palSettings.setFormat( format ); palSettings.writeToLayer( mLinesLayer ); @@ -230,7 +230,7 @@ bool TestQgsMapRotation::render( const QString& theTestType ) mReport += "

                                                                                                                                                                                    " + theTestType + "

                                                                                                                                                                                    \n"; mMapSettings->setOutputDpi( 96 ); QgsRenderChecker checker; - checker.setControlPathPrefix( "maprotation" ); + checker.setControlPathPrefix( QStringLiteral( "maprotation" ) ); checker.setControlName( "expected_" + theTestType ); checker.setMapSettings( *mMapSettings ); bool result = checker.runTest( theTestType ); diff --git a/tests/src/core/testqgsmapsettings.cpp b/tests/src/core/testqgsmapsettings.cpp index c94b8825f636..0839d7078f79 100644 --- a/tests/src/core/testqgsmapsettings.cpp +++ b/tests/src/core/testqgsmapsettings.cpp @@ -50,7 +50,7 @@ QString TestQgsMapSettings::toString( const QPolygonF& p, int dec ) const double r = pow( 10.0, dec ); for ( int i = 0; i < p.size(); ++i ) { - s += QString( "%1%2 %3" ).arg( sep ) + s += QStringLiteral( "%1%2 %3" ).arg( sep ) .arg( int( p[i].x() * r ) / r ) .arg( int( p[i].y() * r ) / r ); sep = ","; diff --git a/tests/src/core/testqgsmaptopixelgeometrysimplifier.cpp b/tests/src/core/testqgsmaptopixelgeometrysimplifier.cpp index 84249584017a..da0afa47e7eb 100644 --- a/tests/src/core/testqgsmaptopixelgeometrysimplifier.cpp +++ b/tests/src/core/testqgsmaptopixelgeometrysimplifier.cpp @@ -121,7 +121,7 @@ void TestQgsMapToPixelGeometrySimplifier::testLine1() { // NOTE: we need more than 4 vertices, or the line will not be // reduced at all by the algorithm - QgsGeometry g( QgsGeometry::fromWkt( "LINESTRING(0 0,1 1,2 0,3 1,4 0,20 1,20 0,10 0,5 0)" ) ); + QgsGeometry g( QgsGeometry::fromWkt( QStringLiteral( "LINESTRING(0 0,1 1,2 0,3 1,4 0,20 1,20 0,10 0,5 0)" ) ) ); int fl; QString wkt; @@ -188,7 +188,7 @@ void TestQgsMapToPixelGeometrySimplifier::testWkbDimensionMismatch() void TestQgsMapToPixelGeometrySimplifier::testCircularString() { - static const QString WKT( "MultiCurve (LineString (5 5, 3 5, 3 3, 0 3),CircularString (0 0, 2 1, 2 2))" ); + static const QString WKT( QStringLiteral( "MultiCurve (LineString (5 5, 3 5, 3 3, 0 3),CircularString (0 0, 2 1, 2 2))" ) ); const QgsGeometry g( QgsGeometry::fromWkt( WKT ) ); const QgsMapToPixelSimplifier simplifier( QgsMapToPixelSimplifier::SimplifyGeometry, 0.1 ); @@ -197,11 +197,11 @@ void TestQgsMapToPixelGeometrySimplifier::testCircularString() void TestQgsMapToPixelGeometrySimplifier::testVisvalingam() { - QString wkt( "LineString (0 0, 30 0, 31 30, 32 0, 40 0, 41 100, 42 0, 50 0)" ); + QString wkt( QStringLiteral( "LineString (0 0, 30 0, 31 30, 32 0, 40 0, 41 100, 42 0, 50 0)" ) ); QgsGeometry g = QgsGeometry::fromWkt( wkt ); const QgsMapToPixelSimplifier simplifier( QgsMapToPixelSimplifier::SimplifyGeometry, 7, QgsMapToPixelSimplifier::Visvalingam ); - QString expectedWkt( "LineString (0 0, 40 0, 41 100, 42 0, 50 0)" ); + QString expectedWkt( QStringLiteral( "LineString (0 0, 40 0, 41 100, 42 0, 50 0)" ) ); QCOMPARE( simplifier.simplify( g ).exportToWkt(), expectedWkt ); } diff --git a/tests/src/core/testqgsmarkerlinesymbol.cpp b/tests/src/core/testqgsmarkerlinesymbol.cpp index 9eae4042c1f4..b61b3db7cfb3 100644 --- a/tests/src/core/testqgsmarkerlinesymbol.cpp +++ b/tests/src/core/testqgsmarkerlinesymbol.cpp @@ -47,7 +47,7 @@ class TestQgsMarkerLineSymbol : public QObject : mLinesLayer( 0 ) , mMapSettings( 0 ) { - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; } ~TestQgsMarkerLineSymbol(); @@ -86,7 +86,7 @@ void TestQgsMarkerLineSymbol::initTestCase() QString myLinesFileName = mTestDataDir + "lines_cardinals.shp"; QFileInfo myLinesFileInfo( myLinesFileName ); mLinesLayer = new QgsVectorLayer( myLinesFileInfo.filePath(), - myLinesFileInfo.completeBaseName(), "ogr" ); + myLinesFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); mapLayers << mLinesLayer; // Register all layers with the registry @@ -97,9 +97,9 @@ void TestQgsMarkerLineSymbol::initTestCase() // re-set it to the size of the expected image mMapSettings->setOutputSize( QSize( 256, 256 ) ); - mReport += "

                                                                                                                                                                                    Line Marker Symbol Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Line Marker Symbol Tests

                                                                                                                                                                                    \n" ); - QgsFontUtils::loadStandardTestFonts( QStringList() << "Bold" ); + QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Bold" ) ); } TestQgsMarkerLineSymbol::~TestQgsMarkerLineSymbol() @@ -155,12 +155,12 @@ void TestQgsMarkerLineSymbol::pointNumInterval() // make sub-symbol QgsStringMap props; - props["color"] = "255,0,0"; - props["size"] = "2"; - props["outline_style"] = "no"; + props[QStringLiteral( "color" )] = QStringLiteral( "255,0,0" ); + props[QStringLiteral( "size" )] = QStringLiteral( "2" ); + props[QStringLiteral( "outline_style" )] = QStringLiteral( "no" ); QgsSimpleMarkerSymbolLayer* marker = static_cast< QgsSimpleMarkerSymbolLayer* >( QgsSimpleMarkerSymbolLayer::create( props ) ); - marker->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "@geometry_point_num * 2" ) ); + marker->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "@geometry_point_num * 2" ) ) ); QgsMarkerSymbol* subSymbol = new QgsMarkerSymbol(); subSymbol->changeSymbolLayer( 0, marker ); @@ -184,12 +184,12 @@ void TestQgsMarkerLineSymbol::pointNumVertex() // make sub-symbol QgsStringMap props; - props["color"] = "255,0,0"; - props["size"] = "2"; - props["outline_style"] = "no"; + props[QStringLiteral( "color" )] = QStringLiteral( "255,0,0" ); + props[QStringLiteral( "size" )] = QStringLiteral( "2" ); + props[QStringLiteral( "outline_style" )] = QStringLiteral( "no" ); QgsSimpleMarkerSymbolLayer* marker = static_cast< QgsSimpleMarkerSymbolLayer* >( QgsSimpleMarkerSymbolLayer::create( props ) ); - marker->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "@geometry_point_num * 2" ) ); + marker->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "@geometry_point_num * 2" ) ) ); QgsMarkerSymbol* subSymbol = new QgsMarkerSymbol(); subSymbol->changeSymbolLayer( 0, marker ); @@ -206,7 +206,7 @@ bool TestQgsMarkerLineSymbol::render( const QString& theTestType ) mReport += "

                                                                                                                                                                                    " + theTestType + "

                                                                                                                                                                                    \n"; mMapSettings->setOutputDpi( 96 ); QgsRenderChecker checker; - checker.setControlPathPrefix( "symbol_markerline" ); + checker.setControlPathPrefix( QStringLiteral( "symbol_markerline" ) ); checker.setControlName( "expected_" + theTestType ); checker.setMapSettings( *mMapSettings ); bool result = checker.runTest( theTestType ); diff --git a/tests/src/core/testqgsnetworkcontentfetcher.cpp b/tests/src/core/testqgsnetworkcontentfetcher.cpp index a52e394b5717..44407d5bb5d8 100644 --- a/tests/src/core/testqgsnetworkcontentfetcher.cpp +++ b/tests/src/core/testqgsnetworkcontentfetcher.cpp @@ -83,7 +83,7 @@ void TestQgsNetworkContentFetcher::fetchBadUrl() QgsNetworkContentFetcher fetcher; //test fetching from a bad url mLoaded = false; - fetcher.fetchContent( QUrl( "http://x" ) ); + fetcher.fetchContent( QUrl( QStringLiteral( "http://x" ) ) ); connect( &fetcher, SIGNAL( finished() ), this, SLOT( contentLoaded() ) ); while ( !mLoaded ) { @@ -98,7 +98,7 @@ void TestQgsNetworkContentFetcher::fetchEncodedContent() QgsNetworkContentFetcher fetcher; //test fetching encoded content as string mLoaded = false; - fetcher.fetchContent( QUrl::fromLocalFile( QString( TEST_DATA_DIR ) + '/' + "encoded_html.html" ) ); + fetcher.fetchContent( QUrl::fromLocalFile( QStringLiteral( TEST_DATA_DIR ) + '/' + "encoded_html.html" ) ); connect( &fetcher, SIGNAL( finished() ), this, SLOT( contentLoaded() ) ); while ( !mLoaded ) { diff --git a/tests/src/core/testqgsogcutils.cpp b/tests/src/core/testqgsogcutils.cpp index 9fd87c395caf..2a7f7a50a84c 100644 --- a/tests/src/core/testqgsogcutils.cpp +++ b/tests/src/core/testqgsogcutils.cpp @@ -72,23 +72,23 @@ class TestQgsOgcUtils : public QObject void TestQgsOgcUtils::testGeometryFromGML() { // Test GML2 - QgsGeometry geom( QgsOgcUtils::geometryFromGML( "123,456" ) ); + QgsGeometry geom( QgsOgcUtils::geometryFromGML( QStringLiteral( "123,456" ) ) ); QVERIFY( geom ); QVERIFY( geom.wkbType() == QgsWkbTypes::Point ); QVERIFY( geom.asPoint() == QgsPoint( 123, 456 ) ); - QgsGeometry geomBox( QgsOgcUtils::geometryFromGML( "135.2239,34.4879 135.8578,34.8471" ) ); + QgsGeometry geomBox( QgsOgcUtils::geometryFromGML( QStringLiteral( "135.2239,34.4879 135.8578,34.8471" ) ) ); QVERIFY( geomBox ); QVERIFY( geomBox.wkbType() == QgsWkbTypes::Polygon ); // Test GML3 - geom = QgsOgcUtils::geometryFromGML( "123 456" ); + geom = QgsOgcUtils::geometryFromGML( QStringLiteral( "123 456" ) ); QVERIFY( geom ); QVERIFY( geom.wkbType() == QgsWkbTypes::Point ); QVERIFY( geom.asPoint() == QgsPoint( 123, 456 ) ); - geomBox = QgsOgcUtils::geometryFromGML( "135.2239 34.4879135.8578 34.8471" ); + geomBox = QgsOgcUtils::geometryFromGML( QStringLiteral( "135.2239 34.4879135.8578 34.8471" ) ); QVERIFY( geomBox ); QVERIFY( geomBox.wkbType() == QgsWkbTypes::Polygon ); } @@ -96,9 +96,9 @@ void TestQgsOgcUtils::testGeometryFromGML() static bool compareElements( QDomElement& element1, QDomElement& element2 ) { QString tag1 = element1.tagName(); - tag1.replace( QRegExp( ".*:" ), "" ); + tag1.replace( QRegExp( ".*:" ), QLatin1String( "" ) ); QString tag2 = element2.tagName(); - tag2.replace( QRegExp( ".*:" ), "" ); + tag2.replace( QRegExp( ".*:" ), QLatin1String( "" ) ); if ( tag1 != tag2 ) { qDebug( "Different tag names: %s, %s", tag1.toAscii().data(), tag2.toAscii().data() ); @@ -207,7 +207,7 @@ void TestQgsOgcUtils::testGeometryToGML() { QDomDocument doc; QgsGeometry geomPoint( QgsGeometry::fromPoint( QgsPoint( 111, 222 ) ) ); - QgsGeometry geomLine( QgsGeometry::fromWkt( "LINESTRING(111 222, 222 222)" ) ); + QgsGeometry geomLine( QgsGeometry::fromWkt( QStringLiteral( "LINESTRING(111 222, 222 222)" ) ) ); // Elements to compare QDomElement xmlElem; @@ -221,7 +221,7 @@ void TestQgsOgcUtils::testGeometryToGML() QVERIFY( !elemPoint.isNull() ); doc.appendChild( elemPoint ); - xmlElem = comparableElement( QString( "111,222" ) ); + xmlElem = comparableElement( QStringLiteral( "111,222" ) ); ogcElem = comparableElement( doc.toString( -1 ) ); QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemPoint ); @@ -230,29 +230,29 @@ void TestQgsOgcUtils::testGeometryToGML() QVERIFY( !elemLine.isNull() ); doc.appendChild( elemLine ); - xmlElem = comparableElement( QString( "111,222 222,222" ) ); + xmlElem = comparableElement( QStringLiteral( "111,222 222,222" ) ); ogcElem = comparableElement( doc.toString( -1 ) ); QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemLine ); // Test GML3 - elemInvalid = QgsOgcUtils::geometryToGML( 0, doc, "GML3" ); + elemInvalid = QgsOgcUtils::geometryToGML( 0, doc, QStringLiteral( "GML3" ) ); QVERIFY( elemInvalid.isNull() ); - elemPoint = QgsOgcUtils::geometryToGML( &geomPoint, doc, "GML3" ); + elemPoint = QgsOgcUtils::geometryToGML( &geomPoint, doc, QStringLiteral( "GML3" ) ); QVERIFY( !elemPoint.isNull() ); doc.appendChild( elemPoint ); - xmlElem = comparableElement( QString( "111 222" ) ); + xmlElem = comparableElement( QStringLiteral( "111 222" ) ); ogcElem = comparableElement( doc.toString( -1 ) ); QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemPoint ); - elemLine = QgsOgcUtils::geometryToGML( &geomLine, doc, "GML3" ); + elemLine = QgsOgcUtils::geometryToGML( &geomLine, doc, QStringLiteral( "GML3" ) ); QVERIFY( !elemLine.isNull() ); doc.appendChild( elemLine ); - xmlElem = comparableElement( QString( "111 222 222 222" ) ); + xmlElem = comparableElement( QStringLiteral( "111 222 222 222" ) ); ogcElem = comparableElement( doc.toString( -1 ) ); QVERIFY( compareElements( xmlElem, ogcElem ) ); doc.removeChild( elemLine ); @@ -269,14 +269,14 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "NAME" "New York" "" ) - << QString( "NAME = 'New York'" ); + << QStringLiteral( "NAME = 'New York'" ); QTest::newRow( ">" ) << QString( "" "COUNT" "3" "" ) - << QString( "COUNT > 3" ); + << QStringLiteral( "COUNT > 3" ); QTest::newRow( "AND" ) << QString( "" @@ -291,7 +291,7 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "" "" "" ) - << QString( "pop >= 50000 AND pop < 100000" ); + << QStringLiteral( "pop >= 50000 AND pop < 100000" ); // TODO: should work also without tags in Lower/Upper-Boundary tags? QTest::newRow( "between" ) << QString( @@ -300,7 +300,7 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "100" "200" "" ) - << QString( "POPULATION >= 100 AND POPULATION <= 200" ); + << QStringLiteral( "POPULATION >= 100 AND POPULATION <= 200" ); // handle different wildcards, single chars, escape chars QTest::newRow( "like" ) << QString( @@ -308,13 +308,13 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "" "NAME*QGIS*" "" ) - << QString( "NAME LIKE '*QGIS*'" ); + << QStringLiteral( "NAME LIKE '*QGIS*'" ); QTest::newRow( "ilike" ) << QString( "" "" "NAME*QGIS*" "" ) - << QString( "NAME ILIKE '*QGIS*'" ); + << QStringLiteral( "NAME ILIKE '*QGIS*'" ); // different wildCards QTest::newRow( "like wildCard" ) << QString( @@ -322,21 +322,21 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "" "NAME*%QGIS*\\*" "" ) - << QString( "NAME LIKE '%\\\\%QGIS%*'" ); + << QStringLiteral( "NAME LIKE '%\\\\%QGIS%*'" ); // different single chars QTest::newRow( "like single char" ) << QString( "" "" "NAME._QGIS.\\." "" ) - << QString( "NAME LIKE '_\\\\_QGIS_.'" ); + << QStringLiteral( "NAME LIKE '_\\\\_QGIS_.'" ); // different single chars QTest::newRow( "like escape char" ) << QString( "" "" "NAME_QGIS.!.!!%QGIS*!*" "" ) - << QString( "NAME LIKE '\\\\_QGIS_.!\\\\%QGIS%*'" ); + << QStringLiteral( "NAME LIKE '\\\\_QGIS_.!\\\\%QGIS%*'" ); QTest::newRow( "is null" ) << QString( "" @@ -344,14 +344,14 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "FIRST_NAME" "" "" ) - << QString( "FIRST_NAME IS NULL" ); + << QStringLiteral( "FIRST_NAME IS NULL" ); QTest::newRow( "bbox with GML2 Box" ) << QString( "" "Name>NAME" "135.2239,34.4879 135.8578,34.8471" "" ) - << QString( "intersects_bbox($geometry, geom_from_gml('135.2239,34.4879 135.8578,34.8471'))" ); + << QStringLiteral( "intersects_bbox($geometry, geom_from_gml('135.2239,34.4879 135.8578,34.8471'))" ); QTest::newRow( "Intersects" ) << QString( "" @@ -362,7 +362,7 @@ void TestQgsOgcUtils::testExpressionFromOgcFilter_data() "" "" "" ) - << QString( "intersects($geometry, geom_from_gml('123,456'))" ); + << QStringLiteral( "intersects($geometry, geom_from_gml('123,456'))" ); } void TestQgsOgcUtils::testExpressionFromOgcFilter() @@ -420,21 +420,21 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() QTest::addColumn( "exprText" ); QTest::addColumn( "xmlText" ); - QTest::newRow( "=" ) << QString( "NAME = 'New York'" ) << QString( + QTest::newRow( "=" ) << QStringLiteral( "NAME = 'New York'" ) << QString( "" "" "NAME" "New York" "" ); - QTest::newRow( ">" ) << QString( "\"COUNT\" > 3" ) << QString( + QTest::newRow( ">" ) << QStringLiteral( "\"COUNT\" > 3" ) << QString( "" "" "COUNT" "3" "" ); - QTest::newRow( "and+or" ) << QString( "(FIELD1 = 10 OR FIELD1 = 20) AND STATUS = 'VALID'" ) << QString( + QTest::newRow( "and+or" ) << QStringLiteral( "(FIELD1 = 10 OR FIELD1 = 20) AND STATUS = 'VALID'" ) << QString( "" "" "" @@ -454,7 +454,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "like" ) << QString( "NAME LIKE '*QGIS*'" ) << QString( + QTest::newRow( "like" ) << QStringLiteral( "NAME LIKE '*QGIS*'" ) << QString( "" "" "NAME" @@ -462,7 +462,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "ilike" ) << QString( "NAME ILIKE '*QGIS*'" ) << QString( + QTest::newRow( "ilike" ) << QStringLiteral( "NAME ILIKE '*QGIS*'" ) << QString( "" "" "NAME" @@ -470,14 +470,14 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "is null" ) << QString( "A IS NULL" ) << QString( + QTest::newRow( "is null" ) << QStringLiteral( "A IS NULL" ) << QString( "" "" "A" "" "" ); - QTest::newRow( "is not null" ) << QString( "A IS NOT NULL" ) << QString( + QTest::newRow( "is not null" ) << QStringLiteral( "A IS NOT NULL" ) << QString( "" "" "" @@ -486,7 +486,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "in" ) << QString( "A IN (10,20,30)" ) << QString( + QTest::newRow( "in" ) << QStringLiteral( "A IN (10,20,30)" ) << QString( "" "" "" @@ -504,7 +504,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "not in" ) << QString( "A NOT IN (10,20,30)" ) << QString( + QTest::newRow( "not in" ) << QStringLiteral( "A NOT IN (10,20,30)" ) << QString( "" "" "" @@ -524,7 +524,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "intersects_bbox" ) << QString( "intersects_bbox($geometry, geomFromWKT('POINT (5 6)'))" ) << QString( + QTest::newRow( "intersects_bbox" ) << QStringLiteral( "intersects_bbox($geometry, geomFromWKT('POINT (5 6)'))" ) << QString( "" "" "geometry" @@ -532,7 +532,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "intersects + wkt" ) << QString( "intersects($geometry, geomFromWKT('POINT (5 6)'))" ) << QString( + QTest::newRow( "intersects + wkt" ) << QStringLiteral( "intersects($geometry, geomFromWKT('POINT (5 6)'))" ) << QString( "" "" "geometry" @@ -540,7 +540,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilter_data() "" "" ); - QTest::newRow( "contains + gml" ) << QString( "contains($geometry, geomFromGML('5,6'))" ) << QString( + QTest::newRow( "contains + gml" ) << QStringLiteral( "contains($geometry, geomFromGML('5,6'))" ) << QString( "" "" "geometry" @@ -561,7 +561,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS11() QString errorMsg; QDomDocument doc; QDomElement filterElem = QgsOgcUtils::expressionToOgcFilter( exp, doc, - QgsOgcUtils::GML_3_1_0, QgsOgcUtils::FILTER_OGC_1_1, "my_geometry_name", srsName, true, false, &errorMsg ); + QgsOgcUtils::GML_3_1_0, QgsOgcUtils::FILTER_OGC_1_1, QStringLiteral( "my_geometry_name" ), srsName, true, false, &errorMsg ); if ( !errorMsg.isEmpty() ) qDebug( "ERROR: %s", errorMsg.toAscii().data() ); @@ -587,8 +587,8 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS11_data() QTest::addColumn( "xmlText" ); QTest::newRow( "bbox" ) - << QString( "intersects_bbox($geometry, geomFromWKT('POLYGON((2 49,2 50,3 50,3 49,2 49))'))" ) - << QString( "urn:ogc:def:crs:EPSG::4326" ) + << QStringLiteral( "intersects_bbox($geometry, geomFromWKT('POLYGON((2 49,2 50,3 50,3 49,2 49))'))" ) + << QStringLiteral( "urn:ogc:def:crs:EPSG::4326" ) << QString( "" "" @@ -613,7 +613,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS20() QString errorMsg; QDomDocument doc; QDomElement filterElem = QgsOgcUtils::expressionToOgcFilter( exp, doc, - QgsOgcUtils::GML_3_2_1, QgsOgcUtils::FILTER_FES_2_0, "my_geometry_name", srsName, true, false, &errorMsg ); + QgsOgcUtils::GML_3_2_1, QgsOgcUtils::FILTER_FES_2_0, QStringLiteral( "my_geometry_name" ), srsName, true, false, &errorMsg ); if ( !errorMsg.isEmpty() ) qDebug( "ERROR: %s", errorMsg.toAscii().data() ); @@ -637,7 +637,7 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS20_data() QTest::addColumn( "srsName" ); QTest::addColumn( "xmlText" ); - QTest::newRow( "=" ) << QString( "NAME = 'New York'" ) << QString() << QString( + QTest::newRow( "=" ) << QStringLiteral( "NAME = 'New York'" ) << QString() << QString( "" "" "NAME" @@ -645,8 +645,8 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS20_data() "" ); QTest::newRow( "bbox" ) - << QString( "intersects_bbox($geometry, geomFromWKT('POLYGON((2 49,2 50,3 50,3 49,2 49))'))" ) - << QString( "urn:ogc:def:crs:EPSG::4326" ) + << QStringLiteral( "intersects_bbox($geometry, geomFromWKT('POLYGON((2 49,2 50,3 50,3 49,2 49))'))" ) + << QStringLiteral( "urn:ogc:def:crs:EPSG::4326" ) << QString( "" "" @@ -659,8 +659,8 @@ void TestQgsOgcUtils::testExpressionToOgcFilterWFS20_data() "" ); QTest::newRow( "intersects" ) - << QString( "intersects($geometry, geomFromWKT('POLYGON((2 49,2 50,3 50,3 49,2 49))'))" ) - << QString( "urn:ogc:def:crs:EPSG::4326" ) + << QStringLiteral( "intersects($geometry, geomFromWKT('POLYGON((2 49,2 50,3 50,3 49,2 49))'))" ) + << QStringLiteral( "urn:ogc:def:crs:EPSG::4326" ) << QString( "" "" @@ -743,7 +743,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() QTest::addColumn< QList >( "layerProperties" ); QTest::addColumn( "xmlText" ); - QTest::newRow( "= 1.0" ) << QString( "SELECT * FROM t WHERE NAME = 'New York'" ) << + QTest::newRow( "= 1.0" ) << QStringLiteral( "SELECT * FROM t WHERE NAME = 'New York'" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" @@ -753,7 +753,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "= 2.0" ) << QString( "SELECT * FROM t WHERE NAME = 'New York'" ) << + QTest::newRow( "= 2.0" ) << QStringLiteral( "SELECT * FROM t WHERE NAME = 'New York'" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" @@ -763,7 +763,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( ">" ) << QString( "SELECT * FROM t WHERE COUNT > 3" ) << + QTest::newRow( ">" ) << QStringLiteral( "SELECT * FROM t WHERE COUNT > 3" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" @@ -772,7 +772,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "3" "" ); - QTest::newRow( "and+or" ) << QString( "SELECT * FROM t WHERE (FIELD1 <= 10 OR FIELD1 > 20) AND STATUS >= 1.5" ) << + QTest::newRow( "and+or" ) << QStringLiteral( "SELECT * FROM t WHERE (FIELD1 <= 10 OR FIELD1 > 20) AND STATUS >= 1.5" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -793,7 +793,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "is null" ) << QString( "SELECT * FROM t WHERE A IS NULL" ) << + QTest::newRow( "is null" ) << QStringLiteral( "SELECT * FROM t WHERE A IS NULL" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -801,7 +801,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "is not null" ) << QString( "SELECT * FROM t WHERE A IS NOT NULL" ) << + QTest::newRow( "is not null" ) << QStringLiteral( "SELECT * FROM t WHERE A IS NOT NULL" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -811,7 +811,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "in" ) << QString( "SELECT * FROM t WHERE A IN (10,20,30)" ) << + QTest::newRow( "in" ) << QStringLiteral( "SELECT * FROM t WHERE A IN (10,20,30)" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -830,7 +830,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "not in" ) << QString( "SELECT * FROM t WHERE A NOT IN (10,20,30)" ) << + QTest::newRow( "not in" ) << QStringLiteral( "SELECT * FROM t WHERE A NOT IN (10,20,30)" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -851,7 +851,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "between" ) << QString( "SELECT * FROM t WHERE A BETWEEN 1 AND 2" ) << + QTest::newRow( "between" ) << QStringLiteral( "SELECT * FROM t WHERE A BETWEEN 1 AND 2" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -861,7 +861,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "not between" ) << QString( "SELECT * FROM t WHERE A NOT BETWEEN 1 AND 2" ) << + QTest::newRow( "not between" ) << QStringLiteral( "SELECT * FROM t WHERE A NOT BETWEEN 1 AND 2" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -873,7 +873,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "intersects + wkt" ) << QString( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)'))" ) << + QTest::newRow( "intersects + wkt" ) << QStringLiteral( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)'))" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -882,7 +882,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "contains + gml" ) << QString( "SELECT * FROM t WHERE ST_Contains(geom, ST_GeomFromGML('5,6'))" ) << + QTest::newRow( "contains + gml" ) << QStringLiteral( "SELECT * FROM t WHERE ST_Contains(geom, ST_GeomFromGML('5,6'))" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -891,7 +891,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "abs" ) << QString( "SELECT * FROM t WHERE ABS(x) < 5" ) << + QTest::newRow( "abs" ) << QStringLiteral( "SELECT * FROM t WHERE ABS(x) < 5" ) << QgsOgcUtils::GML_2_1_2 << QgsOgcUtils::FILTER_OGC_1_0 << layerProperties << QString( "" "" @@ -902,7 +902,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "bbox + wkt + explicit srs" ) << QString( "SELECT * FROM t WHERE BBOX(geom, ST_MakeEnvelope(2.2, 49, 3, 50, 4326))" ) << + QTest::newRow( "bbox + wkt + explicit srs" ) << QStringLiteral( "SELECT * FROM t WHERE BBOX(geom, ST_MakeEnvelope(2.2, 49, 3, 50, 4326))" ) << QgsOgcUtils::GML_3_1_0 << QgsOgcUtils::FILTER_OGC_1_1 << layerProperties << QString( "" "" @@ -914,7 +914,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "intersects + wkt + explicit srs" ) << QString( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)', 'urn:ogc:def:crs:EPSG::4326'))" ) << + QTest::newRow( "intersects + wkt + explicit srs" ) << QStringLiteral( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)', 'urn:ogc:def:crs:EPSG::4326'))" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -925,7 +925,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "intersects + wkt + explicit srs int" ) << QString( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)', 4326))" ) << + QTest::newRow( "intersects + wkt + explicit srs int" ) << QStringLiteral( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)', 4326))" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -936,7 +936,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "dwithin + wkt" ) << QString( "SELECT * FROM t WHERE ST_DWithin(geom, ST_GeometryFromText('POINT (5 6)', 'urn:ogc:def:crs:EPSG::4326'), '3 m')" ) << + QTest::newRow( "dwithin + wkt" ) << QStringLiteral( "SELECT * FROM t WHERE ST_DWithin(geom, ST_GeometryFromText('POINT (5 6)', 'urn:ogc:def:crs:EPSG::4326'), '3 m')" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -950,11 +950,11 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() QList layerProperties4326_FES20; QgsOgcUtils::LayerProperties prop; - prop.mSRSName = "urn:ogc:def:crs:EPSG::4326"; - prop.mGeometryAttribute = "geom"; + prop.mSRSName = QStringLiteral( "urn:ogc:def:crs:EPSG::4326" ); + prop.mGeometryAttribute = QStringLiteral( "geom" ); layerProperties4326_FES20.append( prop ); - QTest::newRow( "intersects + wkt + implicit SRS" ) << QString( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)'))" ) << + QTest::newRow( "intersects + wkt + implicit SRS" ) << QStringLiteral( "SELECT * FROM t WHERE ST_Intersects(geom, ST_GeometryFromText('POINT (5 6)'))" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties4326_FES20 << QString( "" "" @@ -965,7 +965,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "intersects join 2.0" ) << QString( "SELECT * FROM t, t2 WHERE ST_Intersects(t.geom, t2.geom)" ) << + QTest::newRow( "intersects join 2.0" ) << QStringLiteral( "SELECT * FROM t, t2 WHERE ST_Intersects(t.geom, t2.geom)" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -974,7 +974,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "attrib join USING 2.0" ) << QString( "SELECT * FROM t JOIN t2 USING (a)" ) << + QTest::newRow( "attrib join USING 2.0" ) << QStringLiteral( "SELECT * FROM t JOIN t2 USING (a)" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -983,7 +983,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "attrib join multi USING 2.0" ) << QString( "SELECT * FROM t JOIN t2 USING (a, b)" ) << + QTest::newRow( "attrib join multi USING 2.0" ) << QStringLiteral( "SELECT * FROM t JOIN t2 USING (a, b)" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -998,7 +998,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "attrib join ON 2.0" ) << QString( "SELECT * FROM t aliased_t JOIN t2 aliasted_t2 ON aliased_t.a = aliasted_t2.b" ) << + QTest::newRow( "attrib join ON 2.0" ) << QStringLiteral( "SELECT * FROM t aliased_t JOIN t2 aliasted_t2 ON aliased_t.a = aliasted_t2.b" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" @@ -1007,7 +1007,7 @@ void TestQgsOgcUtils::testSQLStatementToOgcFilter_data() "" "" ); - QTest::newRow( "attrib multi join 2.0" ) << QString( "SELECT * FROM t aliased_t JOIN t2 aliasted_t2 ON aliased_t.a = aliasted_t2.b JOIN t3 USING (c)" ) << + QTest::newRow( "attrib multi join 2.0" ) << QStringLiteral( "SELECT * FROM t aliased_t JOIN t2 aliasted_t2 ON aliased_t.a = aliasted_t2.b JOIN t3 USING (c)" ) << QgsOgcUtils::GML_3_2_1 << QgsOgcUtils::FILTER_FES_2_0 << layerProperties << QString( "" "" diff --git a/tests/src/core/testqgsogrutils.cpp b/tests/src/core/testqgsogrutils.cpp index d9a7ec5659ea..0efd8b77ef4a 100644 --- a/tests/src/core/testqgsogrutils.cpp +++ b/tests/src/core/testqgsogrutils.cpp @@ -163,12 +163,12 @@ void TestQgsOgrUtils::getOgrFeatureAttribute() oFeat = OGR_L_GetNextFeature( ogrLayer ); QVERIFY( oFeat ); - fields.append( QgsField( "int_field", QVariant::Int ) ); - fields.append( QgsField( "dbl_field", QVariant::Double ) ); - fields.append( QgsField( "date_field", QVariant::Date ) ); - fields.append( QgsField( "time_field", QVariant::Time ) ); - fields.append( QgsField( "datetime_field", QVariant::DateTime ) ); - fields.append( QgsField( "string_field", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "int_field" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "dbl_field" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "date_field" ), QVariant::Date ) ); + fields.append( QgsField( QStringLiteral( "time_field" ), QVariant::Time ) ); + fields.append( QgsField( QStringLiteral( "datetime_field" ), QVariant::DateTime ) ); + fields.append( QgsField( QStringLiteral( "string_field" ), QVariant::String ) ); // attribute index out of range val = QgsOgrUtils::getOgrFeatureAttribute( oFeat, fields, -1, QTextCodec::codecForName( "System" ), &ok ); @@ -230,12 +230,12 @@ void TestQgsOgrUtils::readOgrFeatureAttributes() oFeat = OGR_L_GetNextFeature( ogrLayer ); QVERIFY( oFeat ); - fields.append( QgsField( "int_field", QVariant::Int ) ); - fields.append( QgsField( "dbl_field", QVariant::Double ) ); - fields.append( QgsField( "date_field", QVariant::Date ) ); - fields.append( QgsField( "time_field", QVariant::Time ) ); - fields.append( QgsField( "datetime_field", QVariant::DateTime ) ); - fields.append( QgsField( "string_field", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "int_field" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "dbl_field" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "date_field" ), QVariant::Date ) ); + fields.append( QgsField( QStringLiteral( "time_field" ), QVariant::Time ) ); + fields.append( QgsField( QStringLiteral( "datetime_field" ), QVariant::DateTime ) ); + fields.append( QgsField( QStringLiteral( "string_field" ), QVariant::String ) ); QVERIFY( QgsOgrUtils::readOgrFeatureAttributes( oFeat, fields, f, QTextCodec::codecForName( "System" ) ) ); QCOMPARE( f.attribute( "int_field" ), QVariant( 5 ) ); @@ -267,12 +267,12 @@ void TestQgsOgrUtils::readOgrFeature() oFeat = OGR_L_GetNextFeature( ogrLayer ); QVERIFY( oFeat ); - fields.append( QgsField( "int_field", QVariant::Int ) ); - fields.append( QgsField( "dbl_field", QVariant::Double ) ); - fields.append( QgsField( "date_field", QVariant::Date ) ); - fields.append( QgsField( "time_field", QVariant::Time ) ); - fields.append( QgsField( "datetime_field", QVariant::DateTime ) ); - fields.append( QgsField( "string_field", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "int_field" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "dbl_field" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "date_field" ), QVariant::Date ) ); + fields.append( QgsField( QStringLiteral( "time_field" ), QVariant::Time ) ); + fields.append( QgsField( QStringLiteral( "datetime_field" ), QVariant::DateTime ) ); + fields.append( QgsField( QStringLiteral( "string_field" ), QVariant::String ) ); f = QgsOgrUtils::readOgrFeature( oFeat, fields, QTextCodec::codecForName( "System" ) ); QVERIFY( f.isValid() ); @@ -329,17 +329,17 @@ void TestQgsOgrUtils::readOgrFields() void TestQgsOgrUtils::stringToFeatureList() { QgsFields fields; - fields.append( QgsField( "name", QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "name" ), QVariant::String ) ); //empty string - QgsFeatureList features = QgsOgrUtils::stringToFeatureList( "", fields, QTextCodec::codecForName( "System" ) ); + QgsFeatureList features = QgsOgrUtils::stringToFeatureList( QLatin1String( "" ), fields, QTextCodec::codecForName( "System" ) ); QVERIFY( features.isEmpty() ); // bad string - features = QgsOgrUtils::stringToFeatureList( "asdasdas", fields, QTextCodec::codecForName( "System" ) ); + features = QgsOgrUtils::stringToFeatureList( QStringLiteral( "asdasdas" ), fields, QTextCodec::codecForName( "System" ) ); QVERIFY( features.isEmpty() ); // geojson string with 1 feature - features = QgsOgrUtils::stringToFeatureList( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}", fields, QTextCodec::codecForName( "System" ) ); + features = QgsOgrUtils::stringToFeatureList( QStringLiteral( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\"}}" ), fields, QTextCodec::codecForName( "System" ) ); QCOMPARE( features.length(), 1 ); QVERIFY( features.at( 0 ).hasGeometry() && !features.at( 0 ).geometry().isEmpty() ); QCOMPARE( features.at( 0 ).geometry().geometry()->wkbType(), QgsWkbTypes::Point ); @@ -372,14 +372,14 @@ void TestQgsOgrUtils::stringToFeatureList() void TestQgsOgrUtils::stringToFields() { //empty string - QgsFields fields = QgsOgrUtils::stringToFields( "", QTextCodec::codecForName( "System" ) ); + QgsFields fields = QgsOgrUtils::stringToFields( QLatin1String( "" ), QTextCodec::codecForName( "System" ) ); QCOMPARE( fields.count(), 0 ); // bad string - fields = QgsOgrUtils::stringToFields( "asdasdas", QTextCodec::codecForName( "System" ) ); + fields = QgsOgrUtils::stringToFields( QStringLiteral( "asdasdas" ), QTextCodec::codecForName( "System" ) ); QCOMPARE( fields.count(), 0 ); // geojson string - fields = QgsOgrUtils::stringToFields( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\",\"height\":5.5}}", QTextCodec::codecForName( "System" ) ); + fields = QgsOgrUtils::stringToFields( QStringLiteral( "{\n\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\",\"coordinates\": [125, 10]},\"properties\": {\"name\": \"Dinagat Islands\",\"height\":5.5}}" ), QTextCodec::codecForName( "System" ) ); QCOMPARE( fields.count(), 2 ); QCOMPARE( fields.at( 0 ).name(), QString( "name" ) ); QCOMPARE( fields.at( 0 ).type(), QVariant::String ); diff --git a/tests/src/core/testqgspainteffect.cpp b/tests/src/core/testqgspainteffect.cpp index acc0f95b18ac..16a6c08bf9e8 100644 --- a/tests/src/core/testqgspainteffect.cpp +++ b/tests/src/core/testqgspainteffect.cpp @@ -53,20 +53,20 @@ class DummyPaintEffect : public QgsPaintEffect , mProp2( prop2 ) {} virtual ~DummyPaintEffect() {} - virtual QString type() const override { return "Dummy"; } + virtual QString type() const override { return QStringLiteral( "Dummy" ); } virtual QgsPaintEffect* clone() const override { return new DummyPaintEffect( mProp1, mProp2 ); } - static QgsPaintEffect* create( const QgsStringMap& props ) { return new DummyPaintEffect( props["testProp"], props["testProp2"] ); } + static QgsPaintEffect* create( const QgsStringMap& props ) { return new DummyPaintEffect( props[QStringLiteral( "testProp" )], props[QStringLiteral( "testProp2" )] ); } virtual QgsStringMap properties() const override { QgsStringMap props; - props["testProp"] = mProp1; - props["testProp2"] = mProp2; + props[QStringLiteral( "testProp" )] = mProp1; + props[QStringLiteral( "testProp2" )] = mProp2; return props; } virtual void readProperties( const QgsStringMap& props ) override { - mProp1 = props["testProp"]; - mProp2 = props["testProp2"]; + mProp1 = props[QStringLiteral( "testProp" )]; + mProp2 = props[QStringLiteral( "testProp2" )]; } QString prop1() { return mProp1; } @@ -139,11 +139,11 @@ void TestQgsPaintEffect::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); - mReport += "

                                                                                                                                                                                    Paint Effect Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Paint Effect Tests

                                                                                                                                                                                    \n" ); mPicture = 0; QgsPaintEffectRegistry* registry = QgsPaintEffectRegistry::instance(); - registry->addEffectType( new QgsPaintEffectMetadata( "Dummy", "Dummy effect", DummyPaintEffect::create ) ); + registry->addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "Dummy" ), QStringLiteral( "Dummy effect" ), DummyPaintEffect::create ) ); QString myDataDir( TEST_DATA_DIR ); //defined in CmakeLists.txt mTestDataDir = myDataDir + '/'; @@ -180,26 +180,26 @@ void TestQgsPaintEffect::cleanup() void TestQgsPaintEffect::saveRestore() { - DummyPaintEffect* effect = new DummyPaintEffect( "a", "b" ); + DummyPaintEffect* effect = new DummyPaintEffect( QStringLiteral( "a" ), QStringLiteral( "b" ) ); QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); //test writing with no node - QDomElement rootNode = doc.createElement( "qgis" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); QDomElement noNode; QCOMPARE( effect->saveProperties( doc, noNode ), false ); //test writing with node - QDomElement effectParentElem = doc.createElement( "parent" ); + QDomElement effectParentElem = doc.createElement( QStringLiteral( "parent" ) ); rootNode.appendChild( effectParentElem ); QVERIFY( effect->saveProperties( doc, effectParentElem ) ); //check if effect node was written - QDomNodeList evalNodeList = effectParentElem.elementsByTagName( "effect" ); + QDomNodeList evalNodeList = effectParentElem.elementsByTagName( QStringLiteral( "effect" ) ); QCOMPARE( evalNodeList.count(), 1 ); QDomElement effectElem = evalNodeList.at( 0 ).toElement(); @@ -210,8 +210,8 @@ void TestQgsPaintEffect::saveRestore() QVERIFY( !restoredEffect ); //test reading bad node - QDomElement badEffectElem = doc.createElement( "parent" ); - badEffectElem.setAttribute( "type", "bad" ); + QDomElement badEffectElem = doc.createElement( QStringLiteral( "parent" ) ); + badEffectElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "bad" ) ); restoredEffect = QgsPaintEffectRegistry::instance()->createEffect( badEffectElem ); QVERIFY( !restoredEffect ); @@ -242,16 +242,16 @@ void TestQgsPaintEffect::stackSaveRestore() QDomImplementation DomImplementation; QDomDocumentType documentType = DomImplementation.createDocumentType( - "qgis", "http://mrcc.com/qgis.dtd", "SYSTEM" ); + QStringLiteral( "qgis" ), QStringLiteral( "http://mrcc.com/qgis.dtd" ), QStringLiteral( "SYSTEM" ) ); QDomDocument doc( documentType ); //test writing with no node - QDomElement rootNode = doc.createElement( "qgis" ); + QDomElement rootNode = doc.createElement( QStringLiteral( "qgis" ) ); QDomElement noNode; QCOMPARE( stack->saveProperties( doc, noNode ), false ); //test writing with node - QDomElement effectParentElem = doc.createElement( "parent" ); + QDomElement effectParentElem = doc.createElement( QStringLiteral( "parent" ) ); rootNode.appendChild( effectParentElem ); QVERIFY( stack->saveProperties( doc, effectParentElem ) ); @@ -262,7 +262,7 @@ void TestQgsPaintEffect::stackSaveRestore() QCOMPARE( effectElem.attribute( "type" ), stack->type() ); //should be two effect child nodes - QDomNodeList childNodeList = effectElem.elementsByTagName( "effect" ); + QDomNodeList childNodeList = effectElem.elementsByTagName( QStringLiteral( "effect" ) ); QCOMPARE( childNodeList.count(), 2 ); QCOMPARE( childNodeList.at( 0 ).toElement().attribute( "type" ), blur->type() ); QCOMPARE( childNodeList.at( 1 ).toElement().attribute( "type" ), shadow->type() ); @@ -343,7 +343,7 @@ void TestQgsPaintEffect::drawSource() effect->render( *mPicture, context ); painter.end(); - bool result = imageCheck( QString( "painteffect_drawsource" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "painteffect_drawsource" ), image, 0 ); delete effect; QVERIFY( result ); @@ -417,7 +417,7 @@ void TestQgsPaintEffect::blur() effect->render( *mPicture, context ); painter.end(); - bool result = imageCheck( QString( "painteffect_blur" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "painteffect_blur" ), image, 0 ); delete effect; QVERIFY( result ); @@ -515,7 +515,7 @@ void TestQgsPaintEffect::dropShadow() effect->render( *mPicture, context ); painter.end(); - bool result = imageCheck( QString( "painteffect_dropshadow" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "painteffect_dropshadow" ), image, 0 ); delete effect; QVERIFY( result ); } @@ -621,7 +621,7 @@ void TestQgsPaintEffect::glow() delete effect; - bool result = imageCheck( QString( "painteffect_outerglow" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "painteffect_outerglow" ), image, 0 ); QVERIFY( result ); //TODO - inner glow @@ -685,7 +685,7 @@ void TestQgsPaintEffect::stack() effect->render( *mPicture, context ); painter.end(); - bool result = imageCheck( QString( "painteffect_stack" ), image, 0 ); + bool result = imageCheck( QStringLiteral( "painteffect_stack" ), image, 0 ); delete effect; QVERIFY( result ); @@ -698,7 +698,7 @@ void TestQgsPaintEffect::layerEffectPolygon() QString polysFileName = mTestDataDir + "polys.shp"; QFileInfo polyFileInfo( polysFileName ); QgsVectorLayer* polysLayer = new QgsVectorLayer( polyFileInfo.filePath(), - polyFileInfo.completeBaseName(), "ogr" ); + polyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); polysLayer->setSimplifyMethod( simplifyMethod ); @@ -718,8 +718,8 @@ void TestQgsPaintEffect::layerEffectPolygon() ms.setLayers( QStringList() << polysLayer->id() ); ms.setExtent( polysLayer->extent() ); - mReport += "

                                                                                                                                                                                    Paint effect symbol layer test (polygon)

                                                                                                                                                                                    \n"; - bool result = mapRenderCheck( "painteffect_poly", ms ); + mReport += QLatin1String( "

                                                                                                                                                                                    Paint effect symbol layer test (polygon)

                                                                                                                                                                                    \n" ); + bool result = mapRenderCheck( QStringLiteral( "painteffect_poly" ), ms ); QVERIFY( result ); } @@ -729,7 +729,7 @@ void TestQgsPaintEffect::layerEffectLine() QString linesFileName = mTestDataDir + "lines.shp"; QFileInfo lineFileInfo( linesFileName ); QgsVectorLayer* lineLayer = new QgsVectorLayer( lineFileInfo.filePath(), - lineFileInfo.completeBaseName(), "ogr" ); + lineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); lineLayer->setSimplifyMethod( simplifyMethod ); @@ -750,8 +750,8 @@ void TestQgsPaintEffect::layerEffectLine() ms.setLayers( QStringList() << lineLayer->id() ); ms.setExtent( lineLayer->extent() ); - mReport += "

                                                                                                                                                                                    Paint effect symbol layer test (line)

                                                                                                                                                                                    \n"; - bool result = mapRenderCheck( "painteffect_line", ms ); + mReport += QLatin1String( "

                                                                                                                                                                                    Paint effect symbol layer test (line)

                                                                                                                                                                                    \n" ); + bool result = mapRenderCheck( QStringLiteral( "painteffect_line" ), ms ); QVERIFY( result ); } @@ -761,7 +761,7 @@ void TestQgsPaintEffect::layerEffectMarker() QString pointFileName = mTestDataDir + "points.shp"; QFileInfo pointFileInfo( pointFileName ); QgsVectorLayer* pointLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsMapLayerRegistry::instance()->addMapLayers( QList() << pointLayer ); QgsMapSettings ms; @@ -778,8 +778,8 @@ void TestQgsPaintEffect::layerEffectMarker() ms.setLayers( QStringList() << pointLayer->id() ); ms.setExtent( pointLayer->extent() ); - mReport += "

                                                                                                                                                                                    Paint effect symbol layer test (point)

                                                                                                                                                                                    \n"; - bool result = mapRenderCheck( "painteffect_marker", ms ); + mReport += QLatin1String( "

                                                                                                                                                                                    Paint effect symbol layer test (point)

                                                                                                                                                                                    \n" ); + bool result = mapRenderCheck( QStringLiteral( "painteffect_marker" ), ms ); QVERIFY( result ); } @@ -789,7 +789,7 @@ void TestQgsPaintEffect::vectorLayerEffect() QString polysFileName = mTestDataDir + "polys.shp"; QFileInfo polyFileInfo( polysFileName ); QgsVectorLayer* polysLayer = new QgsVectorLayer( polyFileInfo.filePath(), - polyFileInfo.completeBaseName(), "ogr" ); + polyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); polysLayer->setSimplifyMethod( simplifyMethod ); @@ -813,8 +813,8 @@ void TestQgsPaintEffect::vectorLayerEffect() ms.setLayers( QStringList() << polysLayer->id() ); ms.setExtent( polysLayer->extent() ); - mReport += "

                                                                                                                                                                                    Paint effect layer test

                                                                                                                                                                                    \n"; - bool result = mapRenderCheck( "painteffect_layer", ms ); + mReport += QLatin1String( "

                                                                                                                                                                                    Paint effect layer test

                                                                                                                                                                                    \n" ); + bool result = mapRenderCheck( QStringLiteral( "painteffect_layer" ), ms ); QVERIFY( result ); } @@ -824,7 +824,7 @@ void TestQgsPaintEffect::mapUnits() QString linesFileName = mTestDataDir + "lines.shp"; QFileInfo lineFileInfo( linesFileName ); QgsVectorLayer* lineLayer = new QgsVectorLayer( lineFileInfo.filePath(), - lineFileInfo.completeBaseName(), "ogr" ); + lineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); lineLayer->setSimplifyMethod( simplifyMethod ); @@ -848,8 +848,8 @@ void TestQgsPaintEffect::mapUnits() ms.setLayers( QStringList() << lineLayer->id() ); ms.setExtent( lineLayer->extent() ); - mReport += "

                                                                                                                                                                                    Paint effect map units test

                                                                                                                                                                                    \n"; - bool result = mapRenderCheck( "painteffect_mapunits", ms ); + mReport += QLatin1String( "

                                                                                                                                                                                    Paint effect map units test

                                                                                                                                                                                    \n" ); + bool result = mapRenderCheck( QStringLiteral( "painteffect_mapunits" ), ms ); QVERIFY( result ); } @@ -860,7 +860,7 @@ void TestQgsPaintEffect::composer() QString linesFileName = mTestDataDir + "lines.shp"; QFileInfo lineFileInfo( linesFileName ); QgsVectorLayer* lineLayer = new QgsVectorLayer( lineFileInfo.filePath(), - lineFileInfo.completeBaseName(), "ogr" ); + lineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); lineLayer->setSimplifyMethod( simplifyMethod ); @@ -899,7 +899,7 @@ void TestQgsPaintEffect::composer() composition->renderPage( &p, 0 ); p.end(); - bool result = imageCheck( "painteffect_composer", outputImage ); + bool result = imageCheck( QStringLiteral( "painteffect_composer" ), outputImage ); delete composition; QVERIFY( result ); } @@ -923,7 +923,7 @@ bool TestQgsPaintEffect::imageCheck( const QString& testName, QImage &image, int QString fileName = tempDir + testName + ".png"; imageWithBackground.save( fileName, "PNG" ); QgsRenderChecker checker; - checker.setControlPathPrefix( "effects" ); + checker.setControlPathPrefix( QStringLiteral( "effects" ) ); checker.setControlName( "expected_" + testName ); checker.setRenderedImage( fileName ); checker.setColorTolerance( 2 ); @@ -935,7 +935,7 @@ bool TestQgsPaintEffect::imageCheck( const QString& testName, QImage &image, int bool TestQgsPaintEffect::mapRenderCheck( const QString& testName, QgsMapSettings& mapSettings, int mismatchCount ) { QgsMultiRenderChecker checker; - checker.setControlPathPrefix( "effects" ); + checker.setControlPathPrefix( QStringLiteral( "effects" ) ); mapSettings.setOutputDpi( 96 ); checker.setControlName( "expected_" + testName ); checker.setMapSettings( mapSettings ); diff --git a/tests/src/core/testqgspainteffectregistry.cpp b/tests/src/core/testqgspainteffectregistry.cpp index 93fc495405df..2b6f4f82929b 100644 --- a/tests/src/core/testqgspainteffectregistry.cpp +++ b/tests/src/core/testqgspainteffectregistry.cpp @@ -29,7 +29,7 @@ class DummyPaintEffect : public QgsPaintEffect public: DummyPaintEffect() {} virtual ~DummyPaintEffect() {} - virtual QString type() const override { return "Dummy"; } + virtual QString type() const override { return QStringLiteral( "Dummy" ); } virtual QgsPaintEffect* clone() const override { return new DummyPaintEffect(); } static QgsPaintEffect* create( const QgsStringMap& ) { return new DummyPaintEffect(); } virtual QgsStringMap properties() const override { return QgsStringMap(); } @@ -81,7 +81,7 @@ void TestQgsPaintEffectRegistry::cleanup() void TestQgsPaintEffectRegistry::metadata() { - QgsPaintEffectMetadata metadata = QgsPaintEffectMetadata( "name", "display name", DummyPaintEffect::create ); + QgsPaintEffectMetadata metadata = QgsPaintEffectMetadata( QStringLiteral( "name" ), QStringLiteral( "display name" ), DummyPaintEffect::create ); QCOMPARE( metadata.name(), QString( "name" ) ); QCOMPARE( metadata.visibleName(), QString( "display name" ) ); @@ -114,10 +114,10 @@ void TestQgsPaintEffectRegistry::addEffect() QgsPaintEffectRegistry* registry = QgsPaintEffectRegistry::instance(); int previousCount = registry->effects().length(); - registry->addEffectType( new QgsPaintEffectMetadata( "Dummy", "Dummy effect", DummyPaintEffect::create ) ); + registry->addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "Dummy" ), QStringLiteral( "Dummy effect" ), DummyPaintEffect::create ) ); QCOMPARE( registry->effects().length(), previousCount + 1 ); //try adding again, should have no effect - registry->addEffectType( new QgsPaintEffectMetadata( "Dummy", "Dummy effect", DummyPaintEffect::create ) ); + registry->addEffectType( new QgsPaintEffectMetadata( QStringLiteral( "Dummy" ), QStringLiteral( "Dummy effect" ), DummyPaintEffect::create ) ); QCOMPARE( registry->effects().length(), previousCount + 1 ); //try adding empty metadata @@ -132,18 +132,18 @@ void TestQgsPaintEffectRegistry::fetchEffects() QVERIFY( effects.contains( "Dummy" ) ); - QgsPaintEffectAbstractMetadata* metadata = registry->effectMetadata( QString( "Dummy" ) ); + QgsPaintEffectAbstractMetadata* metadata = registry->effectMetadata( QStringLiteral( "Dummy" ) ); QCOMPARE( metadata->name(), QString( "Dummy" ) ); //metadata for bad effect - metadata = registry->effectMetadata( QString( "bad effect" ) ); + metadata = registry->effectMetadata( QStringLiteral( "bad effect" ) ); QVERIFY( !metadata ); } void TestQgsPaintEffectRegistry::createEffect() { QgsPaintEffectRegistry* registry = QgsPaintEffectRegistry::instance(); - QgsPaintEffect* effect = registry->createEffect( QString( "Dummy" ) ); + QgsPaintEffect* effect = registry->createEffect( QStringLiteral( "Dummy" ) ); QVERIFY( effect ); DummyPaintEffect* dummyEffect = dynamic_cast( effect ); @@ -151,7 +151,7 @@ void TestQgsPaintEffectRegistry::createEffect() delete effect; //try creating a bad effect - effect = registry->createEffect( QString( "bad effect" ) ); + effect = registry->createEffect( QStringLiteral( "bad effect" ) ); QVERIFY( !effect ); } diff --git a/tests/src/core/testqgspoint.cpp b/tests/src/core/testqgspoint.cpp index 31a53cbc215c..15438f311110 100644 --- a/tests/src/core/testqgspoint.cpp +++ b/tests/src/core/testqgspoint.cpp @@ -160,7 +160,7 @@ void TestQgsPoint::initTestCase() // init QGIS's paths - true means that all path will be inited from prefix QgsApplication::init(); QgsApplication::showSettings(); - mReport += "

                                                                                                                                                                                    Point Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Point Tests

                                                                                                                                                                                    \n" ); } @@ -183,7 +183,7 @@ void TestQgsPoint::cleanupTestCase() void TestQgsPoint::toString() { - mReport += "

                                                                                                                                                                                    Testing toString()

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Testing toString()

                                                                                                                                                                                    " ); mReport += "

                                                                                                                                                                                    " + mPoint1.toString( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint2.toString( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint3.toString( 2 ) + "

                                                                                                                                                                                    "; @@ -193,165 +193,165 @@ void TestQgsPoint::toString() void TestQgsPoint::toDegreesMinutesSeconds() { - mReport += "

                                                                                                                                                                                    Testing toDegreesMinutesSeconds()

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Testing toDegreesMinutesSeconds()

                                                                                                                                                                                    " ); mReport += "

                                                                                                                                                                                    " + mPoint1.toDegreesMinutesSeconds( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint2.toDegreesMinutesSeconds( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint3.toDegreesMinutesSeconds( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint4.toDegreesMinutesSeconds( 2 ) + "

                                                                                                                                                                                    "; qDebug() << mPoint4.toDegreesMinutesSeconds( 2 ); - QString myControlString = QString( "80" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + + QString myControlString = QStringLiteral( "80" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + - QString( "E,20" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( "N" ); + QStringLiteral( "E,20" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( "N" ); qDebug() << myControlString; QCOMPARE( mPoint4.toDegreesMinutesSeconds( 2 ), myControlString ); //check if longitudes > 180 or <-180 wrap around - myControlString = QString( "10" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "10" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 370, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "10" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "10" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( -370, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 181, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( -181, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "1" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "1" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 359, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "1" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "1" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( -359, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); //check if latitudes > 90 or <-90 wrap around - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( ",10" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "N" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( ",10" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, 190 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( ",10" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "S" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( ",10" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, -190 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( ",89" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "S" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( ",89" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, 91 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( ",89" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "N" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( ",89" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, -91 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( ",1" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "S" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( ",1" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, 179 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + - QString( ",1" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "N" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + + QStringLiteral( ",1" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, -179 ).toDegreesMinutesSeconds( 2 ), myControlString ); //should be no directional suffixes for 0 degree coordinates - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 0, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); //should also be no directional suffix for 0 degree coordinates within specified precision QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutesSeconds( 2 ), myControlString ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutesSeconds( 2 ), myControlString ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + QChar( 0x2033 ) + QString( "N" ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutesSeconds( 5 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + QChar( 0x2033 ) + QString( "S" ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutesSeconds( 5 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutesSeconds( 5 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + QChar( 0x2033 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutesSeconds( 5 ), myControlString ); //test rounding does not create seconds >= 60 - myControlString = QString( "100" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",90" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ) + QString( "N" ); + myControlString = QStringLiteral( "100" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",90" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 99.999999, 89.999999 ).toDegreesMinutesSeconds( 2 ), myControlString ); //should be no directional suffixes for 180 degree longitudes - myControlString = QString( "180" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + + myControlString = QStringLiteral( "180" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 180, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); //should also be no directional suffix for 180 degree longitudes within specified precision QCOMPARE( QgsPoint( 180.000001, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); QCOMPARE( QgsPoint( 179.999999, 0 ).toDegreesMinutesSeconds( 2 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "59" ) + QChar( 0x2032 ) + QString( "59.99640" ) + QChar( 0x2033 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "59" ) + QChar( 0x2032 ) + QStringLiteral( "59.99640" ) + QChar( 0x2033 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 180.000001, 0 ).toDegreesMinutesSeconds( 5 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "59" ) + QChar( 0x2032 ) + QString( "59.99640" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "59" ) + QChar( 0x2032 ) + QStringLiteral( "59.99640" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 179.999999, 0 ).toDegreesMinutesSeconds( 5 ), myControlString ); } void TestQgsPoint::toDegreesMinutesSecondsNoSuffix() { - QString myControlString = QString( "80" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + + QString myControlString = QStringLiteral( "80" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + - QString( ",20" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + QStringLiteral( ",20" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QCOMPARE( mPoint4.toDegreesMinutesSeconds( 2, false ), myControlString ); //test 0 lat/long - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00" ) + QChar( 0x2033 ); QVERIFY( QgsPoint( 0, 0 ).toDegreesMinutesSeconds( 2, false ) == myControlString ); //test near zero lat/long QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutesSeconds( 2, false ), myControlString ); @@ -360,200 +360,200 @@ void TestQgsPoint::toDegreesMinutesSecondsNoSuffix() QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutesSeconds( 2, false ), myControlString ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutesSeconds( 2, false ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutesSeconds( 5, false ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ) + - QString( ",-0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + QChar( 0x2033 ); + QStringLiteral( ",-0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutesSeconds( 5, false ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutesSeconds( 5, false ), myControlString ); - myControlString = QString( "-0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00360" ) + + myControlString = QStringLiteral( "-0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00360" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0" ) + QChar( 0x2032 ) + QString( "0.00000" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0" ) + QChar( 0x2032 ) + QStringLiteral( "0.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutesSeconds( 5, false ), myControlString ); } void TestQgsPoint::toDegreesMinutesSecondsPadded() { - QString myControlString = QString( "80" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00" ) + + QString myControlString = QStringLiteral( "80" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00" ) + QChar( 0x2033 ) + - QString( "E,20" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00" ) + QChar( 0x2033 ) + - QString( "N" ); + QStringLiteral( "E,20" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00" ) + QChar( 0x2033 ) + + QStringLiteral( "N" ); qDebug() << myControlString; QCOMPARE( mPoint4.toDegreesMinutesSeconds( 2, true, true ), myControlString ); //should be no directional suffixes for 0 degree coordinates - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00" ) + QChar( 0x2033 ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00" ) + QChar( 0x2033 ); QVERIFY( QgsPoint( 0, 0 ).toDegreesMinutesSeconds( 2, true, true ) == myControlString ); //should also be no directional suffix for 0 degree coordinates within specified precision QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutesSeconds( 2, true, true ), myControlString ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutesSeconds( 2, true, true ), myControlString ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutesSeconds( 2, true, true ), myControlString ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutesSeconds( 2, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00000" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00000" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00360" ) + QChar( 0x2033 ) + QString( "N" ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00360" ) + QChar( 0x2033 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutesSeconds( 5, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00000" ) + + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00000" ) + QChar( 0x2033 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00360" ) + QChar( 0x2033 ) + QString( "S" ); + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00360" ) + QChar( 0x2033 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutesSeconds( 5, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00360" ) + QChar( 0x2033 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00000" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00360" ) + QChar( 0x2033 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutesSeconds( 5, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00360" ) + QChar( 0x2033 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00" ) + QChar( 0x2032 ) + QString( "00.00000" ) + QChar( 0x2033 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00360" ) + QChar( 0x2033 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00" ) + QChar( 0x2032 ) + QStringLiteral( "00.00000" ) + QChar( 0x2033 ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutesSeconds( 5, true, true ), myControlString ); } void TestQgsPoint::toDegreesMinutes() { - mReport += "

                                                                                                                                                                                    Testing toDegreesMinutes()

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Testing toDegreesMinutes()

                                                                                                                                                                                    " ); mReport += "

                                                                                                                                                                                    " + mPoint1.toDegreesMinutes( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint2.toDegreesMinutes( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint3.toDegreesMinutes( 2 ) + "

                                                                                                                                                                                    "; mReport += "

                                                                                                                                                                                    " + mPoint4.toDegreesMinutes( 2 ) + "

                                                                                                                                                                                    "; qDebug() << mPoint4.toDegreesMinutes( 2 ); - QString myControlString = QString( "80" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + - QString( "E,20" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "N" ); + QString myControlString = QStringLiteral( "80" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + + QStringLiteral( "E,20" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "N" ); qDebug() << myControlString; QCOMPARE( mPoint4.toDegreesMinutes( 2 ), myControlString ); //check if longitudes > 180 or <-180 wrap around - myControlString = QString( "10" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "10" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 370, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "10" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "10" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( -370, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 181, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( -181, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "1" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "1" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 359, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "1" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "1" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( -359, 0 ).toDegreesMinutes( 2 ), myControlString ); //should be no directional suffixes for 0 degree coordinates - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QVERIFY( QgsPoint( 0, 0 ).toDegreesMinutes( 2 ) == myControlString ); //should also be no directional suffix for 0 degree coordinates within specified precision QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutes( 2 ), myControlString ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutes( 2 ), myControlString ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutes( 2 ), myControlString ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ) + QString( "N" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutes( 5 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ) + QString( "S" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutes( 5 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutes( 5 ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutes( 5 ), myControlString ); //test rounding does not create minutes >= 60 - myControlString = QString( "100" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",100" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + QString( "N" ); + myControlString = QStringLiteral( "100" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",100" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 99.999999, 99.999999 ).toDegreesMinutes( 2 ), myControlString ); //should be no directional suffixes for 180 degree longitudes - myControlString = QString( "180" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "180" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 180, 0 ).toDegreesMinutes( 2 ), myControlString ); //should also be no directional suffix for 180 degree longitudes within specified precision QCOMPARE( QgsPoint( 180.000001, 0 ).toDegreesMinutes( 2 ), myControlString ); QCOMPARE( QgsPoint( 179.999999, 0 ).toDegreesMinutes( 2 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "59.99994" ) + QChar( 0x2032 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "59.99994" ) + QChar( 0x2032 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 180.000001, 0 ).toDegreesMinutes( 5 ), myControlString ); - myControlString = QString( "179" ) + QChar( 176 ) + - QString( "59.99994" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "179" ) + QChar( 176 ) + + QStringLiteral( "59.99994" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 179.999999, 0 ).toDegreesMinutes( 5 ), myControlString ); } void TestQgsPoint::toDegreesMinutesNoSuffix() { - QString myControlString = QString( "80" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + - QString( ",20" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + QString myControlString = QStringLiteral( "80" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + + QStringLiteral( ",20" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QCOMPARE( mPoint4.toDegreesMinutes( 2, false ), myControlString ); //test 0 lat/long - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00" ) + QChar( 0x2032 ); QVERIFY( QgsPoint( 0, 0 ).toDegreesMinutes( 2, false ) == myControlString ); //test near zero lat/long QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutes( 2, false ), myControlString ); @@ -562,67 +562,67 @@ void TestQgsPoint::toDegreesMinutesNoSuffix() QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutes( 2, false ), myControlString ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutes( 2, false ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutes( 5, false ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ) + - QString( ",-0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ) + + QStringLiteral( ",-0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutes( 5, false ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutes( 5, false ), myControlString ); - myControlString = QString( "-0" ) + QChar( 176 ) + - QString( "0.00006" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "0.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "-0" ) + QChar( 176 ) + + QStringLiteral( "0.00006" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "0.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutes( 5, false ), myControlString ); } void TestQgsPoint::toDegreesMinutesPadded() { - QString myControlString = QString( "80" ) + QChar( 176 ) + - QString( "00.00" ) + QChar( 0x2032 ) + - QString( "E,20" ) + QChar( 176 ) + - QString( "00.00" ) + QChar( 0x2032 ) + QString( "N" ); + QString myControlString = QStringLiteral( "80" ) + QChar( 176 ) + + QStringLiteral( "00.00" ) + QChar( 0x2032 ) + + QStringLiteral( "E,20" ) + QChar( 176 ) + + QStringLiteral( "00.00" ) + QChar( 0x2032 ) + QStringLiteral( "N" ); qDebug() << myControlString; QCOMPARE( mPoint4.toDegreesMinutes( 2, true, true ), myControlString ); //should be no directional suffixes for 0 degree coordinates - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00.00" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00.00" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00.00" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00.00" ) + QChar( 0x2032 ); QVERIFY( QgsPoint( 0, 0 ).toDegreesMinutes( 2, true, true ) == myControlString ); //should also be no directional suffix for 0 degree coordinates within specified precision QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutes( 2, true, true ), myControlString ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutes( 2, true, true ), myControlString ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutes( 2, true, true ), myControlString ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutes( 2, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00.00000" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00.00006" ) + QChar( 0x2032 ) + QString( "N" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00.00000" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00.00006" ) + QChar( 0x2032 ) + QStringLiteral( "N" ); QCOMPARE( QgsPoint( 0, 0.000001 ).toDegreesMinutes( 5, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00.00000" ) + QChar( 0x2032 ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00.00006" ) + QChar( 0x2032 ) + QString( "S" ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00.00000" ) + QChar( 0x2032 ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00.00006" ) + QChar( 0x2032 ) + QStringLiteral( "S" ); QCOMPARE( QgsPoint( 0, -0.000001 ).toDegreesMinutes( 5, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00.00006" ) + QChar( 0x2032 ) + QString( "E" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00.00006" ) + QChar( 0x2032 ) + QStringLiteral( "E" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( 0.000001, 0 ).toDegreesMinutes( 5, true, true ), myControlString ); - myControlString = QString( "0" ) + QChar( 176 ) + - QString( "00.00006" ) + QChar( 0x2032 ) + QString( "W" ) + - QString( ",0" ) + QChar( 176 ) + - QString( "00.00000" ) + QChar( 0x2032 ); + myControlString = QStringLiteral( "0" ) + QChar( 176 ) + + QStringLiteral( "00.00006" ) + QChar( 0x2032 ) + QStringLiteral( "W" ) + + QStringLiteral( ",0" ) + QChar( 176 ) + + QStringLiteral( "00.00000" ) + QChar( 0x2032 ); QCOMPARE( QgsPoint( -0.000001, 0 ).toDegreesMinutes( 5, true, true ), myControlString ); } diff --git a/tests/src/core/testqgspointlocator.cpp b/tests/src/core/testqgspointlocator.cpp index b45019755097..15c351ac82fc 100644 --- a/tests/src/core/testqgspointlocator.cpp +++ b/tests/src/core/testqgspointlocator.cpp @@ -79,7 +79,7 @@ class TestQgsPointLocator : public QObject // \ | // \| // + (1,0) - mVL = new QgsVectorLayer( "Polygon", "x", "memory" ); + mVL = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); QgsFeature ff( 0 ); QgsPolygon polygon; QgsPolyline polyline; diff --git a/tests/src/core/testqgspointpatternfillsymbol.cpp b/tests/src/core/testqgspointpatternfillsymbol.cpp index 24c250a2c496..65e6d0e63779 100644 --- a/tests/src/core/testqgspointpatternfillsymbol.cpp +++ b/tests/src/core/testqgspointpatternfillsymbol.cpp @@ -93,7 +93,7 @@ void TestQgsPointPatternFillSymbol::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -115,7 +115,7 @@ void TestQgsPointPatternFillSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Point Pattern Fill Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Point Pattern Fill Tests

                                                                                                                                                                                    \n" ); } void TestQgsPointPatternFillSymbol::cleanupTestCase() @@ -134,12 +134,12 @@ void TestQgsPointPatternFillSymbol::cleanupTestCase() void TestQgsPointPatternFillSymbol::pointPatternFillSymbol() { - mReport += "

                                                                                                                                                                                    Point pattern fill symbol renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Point pattern fill symbol renderer test

                                                                                                                                                                                    \n" ); QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "name", "circle" ); - properties.insert( "size", "5.0" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "name" ), QStringLiteral( "circle" ) ); + properties.insert( QStringLiteral( "size" ), QStringLiteral( "5.0" ) ); QgsMarkerSymbol* pointSymbol = QgsMarkerSymbol::createSimple( properties ); mPointPatternFill->setSubSymbol( pointSymbol ); @@ -148,14 +148,14 @@ void TestQgsPointPatternFillSymbol::pointPatternFillSymbol() void TestQgsPointPatternFillSymbol::dataDefinedSubSymbol() { - mReport += "

                                                                                                                                                                                    Point pattern symbol data defined sub symbol test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Point pattern symbol data defined sub symbol test

                                                                                                                                                                                    \n" ); QgsStringMap properties; - properties.insert( "color", "0,0,0,255" ); - properties.insert( "name", "circle" ); - properties.insert( "size", "5.0" ); + properties.insert( QStringLiteral( "color" ), QStringLiteral( "0,0,0,255" ) ); + properties.insert( QStringLiteral( "name" ), QStringLiteral( "circle" ) ); + properties.insert( QStringLiteral( "size" ), QStringLiteral( "5.0" ) ); QgsMarkerSymbol* pointSymbol = QgsMarkerSymbol::createSimple( properties ); - pointSymbol->symbolLayer( 0 )->setDataDefinedProperty( "color", new QgsDataDefined( QString( "if(\"Name\" ='Lake','#ff0000','#ff00ff')" ) ) ); + pointSymbol->symbolLayer( 0 )->setDataDefinedProperty( QStringLiteral( "color" ), new QgsDataDefined( QStringLiteral( "if(\"Name\" ='Lake','#ff0000','#ff00ff')" ) ) ); mPointPatternFill->setSubSymbol( pointSymbol ); QVERIFY( imageCheck( "datadefined_subsymbol" ) ); } @@ -172,7 +172,7 @@ bool TestQgsPointPatternFillSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPolysLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_pointpatternfill" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_pointpatternfill" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgsproject.cpp b/tests/src/core/testqgsproject.cpp index e83cdc3e85e9..5eefc718f6b3 100644 --- a/tests/src/core/testqgsproject.cpp +++ b/tests/src/core/testqgsproject.cpp @@ -48,9 +48,9 @@ void TestQgsProject::initTestCase() // Runs once before any tests are run // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); } @@ -69,7 +69,7 @@ void TestQgsProject::testReadPath() #endif prj->setFileName( prefix + "/home/qgis/a-project-file.qgs" ); // not expected to exist // make sure we work with relative paths! - prj->writeEntry( "Paths", "Absolute", false ); + prj->writeEntry( QStringLiteral( "Paths" ), QStringLiteral( "Absolute" ), false ); QCOMPARE( prj->readPath( "./x.shp" ), QString( prefix + "/home/qgis/x.shp" ) ); QCOMPARE( prj->readPath( "../x.shp" ), QString( prefix + "/home/x.shp" ) ); @@ -92,7 +92,7 @@ void TestQgsProject::testProjectUnits() //first set a default QGIS distance unit QSettings s; - s.setValue( "/qgis/measure/displayunits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); + s.setValue( QStringLiteral( "/qgis/measure/displayunits" ), QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceFeet ) ); QgsProject* prj = QgsProject::instance(); // new project should inherit QGIS default distance unit @@ -100,7 +100,7 @@ void TestQgsProject::testProjectUnits() QCOMPARE( prj->distanceUnits(), QgsUnitTypes::DistanceFeet ); //changing default QGIS unit should not affect existing project - s.setValue( "/qgis/measure/displayunits", QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceNauticalMiles ) ); + s.setValue( QStringLiteral( "/qgis/measure/displayunits" ), QgsUnitTypes::encodeUnit( QgsUnitTypes::DistanceNauticalMiles ) ); QCOMPARE( prj->distanceUnits(), QgsUnitTypes::DistanceFeet ); //test setting new units for project @@ -110,14 +110,14 @@ void TestQgsProject::testProjectUnits() // AREA //first set a default QGIS area unit - s.setValue( "/qgis/measure/areaunits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareYards ) ); + s.setValue( QStringLiteral( "/qgis/measure/areaunits" ), QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaSquareYards ) ); // new project should inherit QGIS default area unit prj->clear(); QCOMPARE( prj->areaUnits(), QgsUnitTypes::AreaSquareYards ); //changing default QGIS unit should not affect existing project - s.setValue( "/qgis/measure/areaunits", QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaAcres ) ); + s.setValue( QStringLiteral( "/qgis/measure/areaunits" ), QgsUnitTypes::encodeUnit( QgsUnitTypes::AreaAcres ) ); QCOMPARE( prj->areaUnits(), QgsUnitTypes::AreaSquareYards ); //test setting new units for project @@ -129,7 +129,7 @@ void TestQgsProject::variablesChanged() { QSignalSpy spyVariablesChanged( QgsProject::instance(), SIGNAL( variablesChanged() ) ); QgsStringMap vars; - vars.insert( "variable", "1" ); + vars.insert( QStringLiteral( "variable" ), QStringLiteral( "1" ) ); QgsProject::instance()->setVariables( vars ); QVERIFY( spyVariablesChanged.count() == 1 ); } diff --git a/tests/src/core/testqgsrasterfilewriter.cpp b/tests/src/core/testqgsrasterfilewriter.cpp index bb4138f88e5e..be794e21f94a 100644 --- a/tests/src/core/testqgsrasterfilewriter.cpp +++ b/tests/src/core/testqgsrasterfilewriter.cpp @@ -64,11 +64,11 @@ void TestQgsRasterFileWriter::initTestCase() // disable any PAM stuff to make sure stats are consistent CPLSetConfigOption( "GDAL_PAM_ENABLED", "NO" ); QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( '\n', "
                                                                                                                                                                                    " ); + mySettings = mySettings.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); //create some objects that will be used in all tests... //create a raster layer that will be used in all tests... - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt - mReport += "

                                                                                                                                                                                    Raster File Writer Tests

                                                                                                                                                                                    \n"; + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mReport += QLatin1String( "

                                                                                                                                                                                    Raster File Writer Tests

                                                                                                                                                                                    \n" ); mReport += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    "; } //runs after all tests @@ -90,7 +90,7 @@ void TestQgsRasterFileWriter::writeTest() QDir dir( mTestDataDir + "/raster" ); QStringList filters; - filters << "*.tif"; + filters << QStringLiteral( "*.tif" ); QStringList rasterNames = dir.entryList( filters, QDir::Files ); bool allOK = true; Q_FOREACH ( const QString& rasterName, rasterNames ) @@ -133,7 +133,7 @@ bool TestQgsRasterFileWriter::writeTest( const QString& theRasterName ) QgsRasterPipe* pipe = new QgsRasterPipe(); if ( !pipe->set( provider->clone() ) ) { - logError( "Cannot set pipe provider" ); + logError( QStringLiteral( "Cannot set pipe provider" ) ); delete pipe; return false; } @@ -147,7 +147,7 @@ bool TestQgsRasterFileWriter::writeTest( const QString& theRasterName ) } if ( !pipe->insert( 1, nuller ) ) { - logError( "Cannot set pipe nuller" ); + logError( QStringLiteral( "Cannot set pipe nuller" ) ); delete pipe; return false; } @@ -158,7 +158,7 @@ bool TestQgsRasterFileWriter::writeTest( const QString& theRasterName ) projector->setCrs( provider->crs(), provider->crs() ); if ( !pipe->insert( 2, projector ) ) { - logError( "Cannot set pipe projector" ); + logError( QStringLiteral( "Cannot set pipe projector" ) ); delete pipe; return false; } @@ -169,7 +169,7 @@ bool TestQgsRasterFileWriter::writeTest( const QString& theRasterName ) delete pipe; QgsRasterChecker checker; - bool ok = checker.runTest( "gdal", tmpName, "gdal", myRasterFileInfo.filePath() ); + bool ok = checker.runTest( QStringLiteral( "gdal" ), tmpName, QStringLiteral( "gdal" ), myRasterFileInfo.filePath() ); mReport += checker.report(); // All OK, we can delete the file diff --git a/tests/src/core/testqgsrasterfill.cpp b/tests/src/core/testqgsrasterfill.cpp index 76a5d9703beb..5d7239308aaf 100644 --- a/tests/src/core/testqgsrasterfill.cpp +++ b/tests/src/core/testqgsrasterfill.cpp @@ -94,7 +94,7 @@ void TestQgsRasterFill::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -116,7 +116,7 @@ void TestQgsRasterFill::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Raster Fill Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster Fill Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsRasterFill::cleanupTestCase() @@ -135,7 +135,7 @@ void TestQgsRasterFill::cleanupTestCase() void TestQgsRasterFill::init() { - mRasterFill->setImageFilePath( mTestDataDir + QLatin1String( "sample_image.png" ) ); + mRasterFill->setImageFilePath( mTestDataDir + QStringLiteral( "sample_image.png" ) ); mRasterFill->setWidth( 30.0 ); mRasterFill->setWidthUnit( QgsUnitTypes::RenderPixels ); mRasterFill->setCoordinateMode( QgsRasterFillSymbolLayer::Feature ); @@ -150,41 +150,41 @@ void TestQgsRasterFill::cleanup() void TestQgsRasterFill::rasterFillSymbol() { - mReport += "

                                                                                                                                                                                    Raster fill symbol renderer test

                                                                                                                                                                                    \n"; - bool result = imageCheck( "rasterfill" ); + mReport += QLatin1String( "

                                                                                                                                                                                    Raster fill symbol renderer test

                                                                                                                                                                                    \n" ); + bool result = imageCheck( QStringLiteral( "rasterfill" ) ); QVERIFY( result ); } void TestQgsRasterFill::coordinateMode() { - mReport += "

                                                                                                                                                                                    Raster fill viewport mode

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster fill viewport mode

                                                                                                                                                                                    \n" ); mRasterFill->setCoordinateMode( QgsRasterFillSymbolLayer::Viewport ); - bool result = imageCheck( "rasterfill_viewport" ); + bool result = imageCheck( QStringLiteral( "rasterfill_viewport" ) ); QVERIFY( result ); } void TestQgsRasterFill::alpha() { - mReport += "

                                                                                                                                                                                    Raster fill alpha

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster fill alpha

                                                                                                                                                                                    \n" ); mRasterFill->setAlpha( 0.5 ); - bool result = imageCheck( "rasterfill_alpha" ); + bool result = imageCheck( QStringLiteral( "rasterfill_alpha" ) ); QVERIFY( result ); } void TestQgsRasterFill::offset() { - mReport += "

                                                                                                                                                                                    Raster fill offset

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster fill offset

                                                                                                                                                                                    \n" ); mRasterFill->setOffset( QPointF( 5, 10 ) ); - bool result = imageCheck( "rasterfill_offset" ); + bool result = imageCheck( QStringLiteral( "rasterfill_offset" ) ); QVERIFY( result ); } void TestQgsRasterFill::width() { - mReport += "

                                                                                                                                                                                    Raster fill width

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster fill width

                                                                                                                                                                                    \n" ); mRasterFill->setWidthUnit( QgsUnitTypes::RenderMillimeters ); mRasterFill->setWidth( 5.0 ); - bool result = imageCheck( "rasterfill_width" ); + bool result = imageCheck( QStringLiteral( "rasterfill_width" ) ); QVERIFY( result ); } @@ -214,7 +214,7 @@ bool TestQgsRasterFill::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPolysLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsMultiRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_rasterfill" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_rasterfill" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); myChecker.setColorTolerance( 20 ); diff --git a/tests/src/core/testqgsrasterlayer.cpp b/tests/src/core/testqgsrasterlayer.cpp index 64803a0a9f5d..aa181ca6bc78 100644 --- a/tests/src/core/testqgsrasterlayer.cpp +++ b/tests/src/core/testqgsrasterlayer.cpp @@ -141,10 +141,10 @@ void TestQgsRasterLayer::initTestCase() // disable any PAM stuff to make sure stats are consistent CPLSetConfigOption( "GDAL_PAM_ENABLED", "NO" ); QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( '\n', "
                                                                                                                                                                                    " ); + mySettings = mySettings.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); //create some objects that will be used in all tests... //create a raster layer that will be used in all tests... - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt QString myFileName = mTestDataDir + "tenbytenraster.asc"; QString myLandsatFileName = mTestDataDir + "landsat.tif"; QString myFloat32FileName = mTestDataDir + "/raster/band1_float32_noct_epsg4326.tif"; @@ -184,7 +184,7 @@ void TestQgsRasterLayer::initTestCase() // add the test layer to the maprender mMapSettings->setLayers( QStringList() << mpRasterLayer->id() ); - mReport += "

                                                                                                                                                                                    Raster Layer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster Layer Tests

                                                                                                                                                                                    \n" ); mReport += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    "; } //runs after all tests @@ -325,7 +325,7 @@ void TestQgsRasterLayer::colorRamp1() void TestQgsRasterLayer::colorRamp2() { - QgsColorBrewerColorRamp ramp( "BrBG", 10 ); + QgsColorBrewerColorRamp ramp( QStringLiteral( "BrBG" ), 10 ); // ColorBrewer ramp QVERIFY( testColorRamp( "raster_colorRamp2", &ramp, @@ -336,7 +336,7 @@ void TestQgsRasterLayer::colorRamp3() { // cpt-city ramp, discrete QgsCptCityArchive::initArchives(); - QgsCptCityColorRamp ramp( "cb/div/BrBG", "_10" ); + QgsCptCityColorRamp ramp( QStringLiteral( "cb/div/BrBG" ), QStringLiteral( "_10" ) ); QVERIFY( testColorRamp( "raster_colorRamp3", &ramp, QgsColorRampShader::DISCRETE, 10 ) ); @@ -346,7 +346,7 @@ void TestQgsRasterLayer::colorRamp3() void TestQgsRasterLayer::colorRamp4() { // cpt-city ramp, continuous - QgsCptCityColorRamp ramp( "grass/elevation", "" ); + QgsCptCityColorRamp ramp( QStringLiteral( "grass/elevation" ), QLatin1String( "" ) ); QVERIFY( testColorRamp( "raster_colorRamp4", &ramp, QgsColorRampShader::DISCRETE, 10 ) ); @@ -368,25 +368,25 @@ void TestQgsRasterLayer::landsatBasic875Qml() mMapSettings->setLayers( QStringList() << mpLandsatRasterLayer->id() ); mMapSettings->setExtent( mpLandsatRasterLayer->extent() ); QString msg; - bool result = setQml( "875", msg ); + bool result = setQml( QStringLiteral( "875" ), msg ); QVERIFY2( result, msg.toLocal8Bit().constData() ); QVERIFY( render( "landsat_875" ) ); } void TestQgsRasterLayer::checkDimensions() { - mReport += "

                                                                                                                                                                                    Check Dimensions

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Check Dimensions

                                                                                                                                                                                    \n" ); QVERIFY( mpRasterLayer->width() == 10 ); QVERIFY( mpRasterLayer->height() == 10 ); // regression check for ticket #832 // note bandStatistics call is base 1 // TODO: elementCount is not collected by GDAL, use other stats. //QVERIFY( mpRasterLayer->dataProvider()->bandStatistics( 1 ).elementCount == 100 ); - mReport += "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    " ); } void TestQgsRasterLayer::checkStats() { - mReport += "

                                                                                                                                                                                    Check Stats

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Check Stats

                                                                                                                                                                                    \n" ); QgsRasterBandStats myStatistics = mpRasterLayer->dataProvider()->bandStatistics( 1, QgsRasterBandStats::Min | QgsRasterBandStats::Max | QgsRasterBandStats::Mean | QgsRasterBandStats::StdDev ); @@ -398,16 +398,16 @@ void TestQgsRasterLayer::checkStats() QVERIFY( qgsDoubleNear( myStatistics.mean, 4.5 ) ); double stdDev = 2.87228132326901431; // TODO: verify why GDAL stdDev is so different from generic (2.88675) - mReport += QString( "stdDev = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( myStatistics.stdDev ).arg( stdDev ); + mReport += QStringLiteral( "stdDev = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( myStatistics.stdDev ).arg( stdDev ); QVERIFY( qgsDoubleNear( myStatistics.stdDev, stdDev, 0.00000000000001 ) ); - mReport += "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    " ); } // test scale_factor and offset - uses netcdf file which may not be supported // see http://hub.qgis.org/issues/8417 void TestQgsRasterLayer::checkScaleOffset() { - mReport += "

                                                                                                                                                                                    Check Stats with scale/offset

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Check Stats with scale/offset

                                                                                                                                                                                    \n" ); QFileInfo myRasterFileInfo( mTestDataDir + "scaleoffset.tif" ); QgsRasterLayer * myRasterLayer; @@ -416,8 +416,8 @@ void TestQgsRasterLayer::checkScaleOffset() QVERIFY( myRasterLayer ); if ( ! myRasterLayer->isValid() ) { - qDebug() << QString( "raster layer %1 invalid" ).arg( myRasterFileInfo.filePath() ); - mReport += QString( "raster layer %1 invalid" ).arg( myRasterFileInfo.filePath() ); + qDebug() << QStringLiteral( "raster layer %1 invalid" ).arg( myRasterFileInfo.filePath() ); + mReport += QStringLiteral( "raster layer %1 invalid" ).arg( myRasterFileInfo.filePath() ); delete myRasterLayer; QVERIFY( false ); return; @@ -427,23 +427,23 @@ void TestQgsRasterLayer::checkScaleOffset() QgsRasterBandStats myStatistics = myRasterLayer->dataProvider()->bandStatistics( 1, QgsRasterBandStats::Min | QgsRasterBandStats::Max | QgsRasterBandStats::Mean | QgsRasterBandStats::StdDev ); - mReport += QString( "raster min: %1 max: %2 mean: %3" ).arg( myStatistics.minimumValue ).arg( myStatistics.maximumValue ).arg( myStatistics.mean ); + mReport += QStringLiteral( "raster min: %1 max: %2 mean: %3" ).arg( myStatistics.minimumValue ).arg( myStatistics.maximumValue ).arg( myStatistics.mean ); QVERIFY( myRasterLayer->width() == 10 ); QVERIFY( myRasterLayer->height() == 10 ); //QVERIFY( myStatistics.elementCount == 100 ); double minVal = 0.0; - mReport += QString( "min = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.minimumValue ).arg( minVal ).arg( fabs( myStatistics.minimumValue - minVal ) ); + mReport += QStringLiteral( "min = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.minimumValue ).arg( minVal ).arg( fabs( myStatistics.minimumValue - minVal ) ); double maxVal = 9.0; - mReport += QString( "max = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.maximumValue ).arg( maxVal ).arg( fabs( myStatistics.maximumValue - maxVal ) ); + mReport += QStringLiteral( "max = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.maximumValue ).arg( maxVal ).arg( fabs( myStatistics.maximumValue - maxVal ) ); double meanVal = 4.5; - mReport += QString( "min = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.mean ).arg( meanVal ).arg( fabs( myStatistics.mean - meanVal ) ); + mReport += QStringLiteral( "min = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.mean ).arg( meanVal ).arg( fabs( myStatistics.mean - meanVal ) ); QVERIFY( fabs( myStatistics.minimumValue - minVal ) < 0.0000001 ); QVERIFY( fabs( myStatistics.maximumValue - maxVal ) < 0.0000001 ); QVERIFY( fabs( myStatistics.mean - meanVal ) < 0.0000001 ); double stdDev = 2.87228615; // TODO: verify why GDAL stdDev is so different from generic (2.88675) - mReport += QString( "stdDev = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.stdDev ).arg( stdDev ).arg( fabs( myStatistics.stdDev - stdDev ) ); + mReport += QStringLiteral( "stdDev = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( myStatistics.stdDev ).arg( stdDev ).arg( fabs( myStatistics.stdDev - stdDev ) ); QVERIFY( fabs( myStatistics.stdDev - stdDev ) < 0.0000001 ); QgsRasterDataProvider* myProvider = myRasterLayer->dataProvider(); @@ -460,7 +460,7 @@ void TestQgsRasterLayer::checkScaleOffset() if ( values.value( bandNo ).isNull() ) { valueString = tr( "no data" ); - mReport += QString( " %1 = %2
                                                                                                                                                                                    \n" ).arg( myProvider->generateBandName( bandNo ), valueString ); + mReport += QStringLiteral( " %1 = %2
                                                                                                                                                                                    \n" ).arg( myProvider->generateBandName( bandNo ), valueString ); delete myRasterLayer; QVERIFY( false ); return; @@ -470,8 +470,8 @@ void TestQgsRasterLayer::checkScaleOffset() double expected = 0.99995432; double value = values.value( bandNo ).toDouble(); valueString = QgsRasterBlock::printValue( value ); - mReport += QString( " %1 = %2
                                                                                                                                                                                    \n" ).arg( myProvider->generateBandName( bandNo ), valueString ); - mReport += QString( " value = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( value ).arg( expected ).arg( fabs( value - expected ) ); + mReport += QStringLiteral( " %1 = %2
                                                                                                                                                                                    \n" ).arg( myProvider->generateBandName( bandNo ), valueString ); + mReport += QStringLiteral( " value = %1 expected = %2 diff = %3
                                                                                                                                                                                    \n" ).arg( value ).arg( expected ).arg( fabs( value - expected ) ); QVERIFY( fabs( value - expected ) < 0.0000001 ); } } @@ -483,7 +483,7 @@ void TestQgsRasterLayer::checkScaleOffset() return; } - mReport += "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    " ); delete myRasterLayer; } @@ -514,7 +514,7 @@ void TestQgsRasterLayer::buildExternalOverviews() } //now actually make the pyramids QString myResult = - mypLayer->dataProvider()->buildPyramids( myPyramidList, "NEAREST", myFormatFlag ); + mypLayer->dataProvider()->buildPyramids( myPyramidList, QStringLiteral( "NEAREST" ), myFormatFlag ); qDebug( "%s", myResult.toLocal8Bit().constData() ); QVERIFY( myResult.isEmpty() ); // @@ -547,11 +547,11 @@ void TestQgsRasterLayer::buildExternalOverviews() // Test with options QStringList optionList; - optionList << "COMPRESS_OVERVIEW=DEFLATE"; - optionList << "invalid"; + optionList << QStringLiteral( "COMPRESS_OVERVIEW=DEFLATE" ); + optionList << QStringLiteral( "invalid" ); myResult = - mypLayer->dataProvider()->buildPyramids( myPyramidList, "NEAREST", myFormatFlag, optionList ); + mypLayer->dataProvider()->buildPyramids( myPyramidList, QStringLiteral( "NEAREST" ), myFormatFlag, optionList ); qDebug( "%s", myResult.toLocal8Bit().constData() ); QVERIFY( myResult.isEmpty() ); QVERIFY( QFile::exists( myTempPath + "landsat.tif.ovr" ) ); @@ -567,8 +567,8 @@ void TestQgsRasterLayer::buildExternalOverviews() QVERIFY( pszCompression && EQUAL( pszCompression, "DEFLATE" ) ); GDALClose( hDS ); - mReport += "

                                                                                                                                                                                    Check Overviews

                                                                                                                                                                                    \n"; - mReport += "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Check Overviews

                                                                                                                                                                                    \n" ); + mReport += QLatin1String( "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    " ); } @@ -610,7 +610,7 @@ bool TestQgsRasterLayer::setQml( const QString& theType, QString& msg ) //load a qml style and apply to our layer if ( !mpLandsatRasterLayer->isValid() ) { - msg = " **** setQml -> mpLandsatRasterLayer is invalid"; + msg = QStringLiteral( " **** setQml -> mpLandsatRasterLayer is invalid" ); return false; } @@ -620,7 +620,7 @@ bool TestQgsRasterLayer::setQml( const QString& theType, QString& msg ) loadStyleMsg = mpLandsatRasterLayer->loadNamedStyle( myFileName, myStyleFlag ); if ( !myStyleFlag ) { - msg = QString( "Loading QML %1 failed: %2" ).arg( myFileName, loadStyleMsg ); + msg = QStringLiteral( "Loading QML %1 failed: %2" ).arg( myFileName, loadStyleMsg ); return false; } return true; diff --git a/tests/src/core/testqgsrastersublayer.cpp b/tests/src/core/testqgsrastersublayer.cpp index 915fecc1ae75..8278ddbe335d 100644 --- a/tests/src/core/testqgsrastersublayer.cpp +++ b/tests/src/core/testqgsrastersublayer.cpp @@ -83,17 +83,17 @@ void TestQgsRasterSubLayer::initTestCase() // disable any PAM stuff to make sure stats are consistent CPLSetConfigOption( "GDAL_PAM_ENABLED", "NO" ); QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( '\n', "
                                                                                                                                                                                    " ); - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mySettings = mySettings.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt GDALAllRegister(); - QString format = "netCDF"; + QString format = QStringLiteral( "netCDF" ); GDALDriverH myGdalDriver = GDALGetDriverByName( format.toLocal8Bit().constData() ); mHasNetCDF = myGdalDriver != 0; mFileName = mTestDataDir + "landsat2.nc"; - mReport += "

                                                                                                                                                                                    Raster Sub Layer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Raster Sub Layer Tests

                                                                                                                                                                                    \n" ); //mReport += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    "; if ( mHasNetCDF ) @@ -106,7 +106,7 @@ void TestQgsRasterSubLayer::initTestCase() } else { - mReport += "

                                                                                                                                                                                    NetCDF format is not compiled in GDAL library, cannot test sub layers.

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    NetCDF format is not compiled in GDAL library, cannot test sub layers.

                                                                                                                                                                                    " ); } } @@ -129,15 +129,15 @@ void TestQgsRasterSubLayer::subLayersList() { if ( mHasNetCDF ) { - mReport += "

                                                                                                                                                                                    Check Sublayers List

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Check Sublayers List

                                                                                                                                                                                    \n" ); // Layer with sublayers is not valid //QVERIFY( mpRasterLayer->isValid() ); QStringList expected; // Sublayer format: NETCDF:"/path/to/landsat2.nc":Band1 // NETCDF:"c:/path/to/landsat2.nc":Band1 // File path is delicate on Windows -> compare only sublayers - expected << "Band1"; - expected << "Band2"; + expected << QStringLiteral( "Band1" ); + expected << QStringLiteral( "Band2" ); QStringList sublayers; Q_FOREACH ( const QString& s, mpRasterLayer->subLayers() ) @@ -145,11 +145,11 @@ void TestQgsRasterSubLayer::subLayersList() qDebug() << "sublayer: " << s; sublayers << s.split( ':' ).last(); } - qDebug() << "sublayers: " << sublayers.join( "," ); - mReport += QString( "sublayers:
                                                                                                                                                                                    %1
                                                                                                                                                                                    \n" ).arg( sublayers.join( "
                                                                                                                                                                                    " ) ); - mReport += QString( "expected:
                                                                                                                                                                                    %1
                                                                                                                                                                                    \n" ).arg( expected.join( "
                                                                                                                                                                                    " ) ); + qDebug() << "sublayers: " << sublayers.join( QStringLiteral( "," ) ); + mReport += QStringLiteral( "sublayers:
                                                                                                                                                                                    %1
                                                                                                                                                                                    \n" ).arg( sublayers.join( QStringLiteral( "
                                                                                                                                                                                    " ) ) ); + mReport += QStringLiteral( "expected:
                                                                                                                                                                                    %1
                                                                                                                                                                                    \n" ).arg( expected.join( QStringLiteral( "
                                                                                                                                                                                    " ) ) ); QVERIFY( sublayers == expected ); - mReport += "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    " ); } } @@ -157,11 +157,11 @@ void TestQgsRasterSubLayer::checkStats() { if ( mHasNetCDF ) { - mReport += "

                                                                                                                                                                                    Check Stats

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Check Stats

                                                                                                                                                                                    \n" ); QString sublayerUri = mpRasterLayer->subLayers().value( 0 ); mReport += "sublayer: " + sublayerUri + "
                                                                                                                                                                                    \n"; - QgsRasterLayer *sublayer = new QgsRasterLayer( sublayerUri, "Sublayer 1" ); + QgsRasterLayer *sublayer = new QgsRasterLayer( sublayerUri, QStringLiteral( "Sublayer 1" ) ); QgsRasterBandStats myStatistics = sublayer->dataProvider()->bandStatistics( 1, QgsRasterBandStats::Min | QgsRasterBandStats::Max ); @@ -169,16 +169,16 @@ void TestQgsRasterSubLayer::checkStats() int height = 200; double min = 122; double max = 130; - mReport += QString( "width = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( sublayer->width() ).arg( width ); - mReport += QString( "height = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( sublayer->height() ).arg( height ); - mReport += QString( "min = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( myStatistics.minimumValue ).arg( min ); - mReport += QString( "max = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( myStatistics.maximumValue ).arg( max ); + mReport += QStringLiteral( "width = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( sublayer->width() ).arg( width ); + mReport += QStringLiteral( "height = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( sublayer->height() ).arg( height ); + mReport += QStringLiteral( "min = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( myStatistics.minimumValue ).arg( min ); + mReport += QStringLiteral( "max = %1 expected = %2
                                                                                                                                                                                    \n" ).arg( myStatistics.maximumValue ).arg( max ); QVERIFY( sublayer->width() == width ); QVERIFY( sublayer->height() == height ); QVERIFY( qgsDoubleNear( myStatistics.minimumValue, min ) ); QVERIFY( qgsDoubleNear( myStatistics.maximumValue, max ) ); - mReport += "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    "; + mReport += QLatin1String( "

                                                                                                                                                                                    Passed

                                                                                                                                                                                    " ); delete sublayer; } } diff --git a/tests/src/core/testqgsrenderers.cpp b/tests/src/core/testqgsrenderers.cpp index ec2ab16cfe3a..bb3071c5f82a 100644 --- a/tests/src/core/testqgsrenderers.cpp +++ b/tests/src/core/testqgsrenderers.cpp @@ -94,7 +94,7 @@ void TestQgsRenderers::initTestCase() QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mpPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPointsLayer ); @@ -105,7 +105,7 @@ void TestQgsRenderers::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPolysLayer ); @@ -117,7 +117,7 @@ void TestQgsRenderers::initTestCase() QString myLinesFileName = mTestDataDir + "lines.shp"; QFileInfo myLineFileInfo( myLinesFileName ); mpLinesLayer = new QgsVectorLayer( myLineFileInfo.filePath(), - myLineFileInfo.completeBaseName(), "ogr" ); + myLineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpLinesLayer ); @@ -128,7 +128,7 @@ void TestQgsRenderers::initTestCase() // mMapSettings->setLayers( QStringList() << mpPointsLayer->id() << mpPolysLayer->id() << mpLinesLayer->id() ); - mReport += "

                                                                                                                                                                                    Vector Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Vector Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsRenderers::cleanupTestCase() { @@ -147,7 +147,7 @@ void TestQgsRenderers::cleanupTestCase() void TestQgsRenderers::singleSymbol() { - mReport += "

                                                                                                                                                                                    Single symbol renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Single symbol renderer test

                                                                                                                                                                                    \n" ); QVERIFY( setQml( "single" ) ); QVERIFY( imageCheck( "single" ) ); } diff --git a/tests/src/core/testqgsrulebasedrenderer.cpp b/tests/src/core/testqgsrulebasedrenderer.cpp index 3ba0a43f3ae7..55b77c7fd08b 100644 --- a/tests/src/core/testqgsrulebasedrenderer.cpp +++ b/tests/src/core/testqgsrulebasedrenderer.cpp @@ -44,7 +44,7 @@ class TestQgsRuleBasedRenderer: public QObject void test_load_xml() { QDomDocument doc; - xml2domElement( "rulebasedrenderer_simple.xml", doc ); + xml2domElement( QStringLiteral( "rulebasedrenderer_simple.xml" ), doc ); QDomElement elem = doc.documentElement(); QgsRuleBasedRenderer* r = static_cast( QgsRuleBasedRenderer::create( elem ) ); @@ -56,7 +56,7 @@ class TestQgsRuleBasedRenderer: public QObject void test_load_invalid_xml() { QDomDocument doc; - xml2domElement( "rulebasedrenderer_invalid.xml", doc ); + xml2domElement( QStringLiteral( "rulebasedrenderer_invalid.xml" ), doc ); QDomElement elem = doc.documentElement(); QSharedPointer r( static_cast( QgsRuleBasedRenderer::create( elem ) ) ); @@ -66,8 +66,8 @@ class TestQgsRuleBasedRenderer: public QObject void test_willRenderFeature_symbolsForFeature() { // prepare features - QgsVectorLayer* layer = new QgsVectorLayer( "point?field=fld:int", "x", "memory" ); - int idx = layer->fields().indexFromName( "fld" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "point?field=fld:int" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + int idx = layer->fields().indexFromName( QStringLiteral( "fld" ) ); QVERIFY( idx != -1 ); QgsFeature f1; f1.initAttributes( 1 ); @@ -83,8 +83,8 @@ class TestQgsRuleBasedRenderer: public QObject QgsSymbol* s1 = QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ); QgsSymbol* s2 = QgsSymbol::defaultSymbol( QgsWkbTypes::PointGeometry ); RRule* rootRule = new RRule( nullptr ); - rootRule->appendChild( new RRule( s1, 0, 0, "fld >= 5 and fld <= 20" ) ); - rootRule->appendChild( new RRule( s2, 0, 0, "fld <= 10" ) ); + rootRule->appendChild( new RRule( s1, 0, 0, QStringLiteral( "fld >= 5 and fld <= 20" ) ) ); + rootRule->appendChild( new RRule( s2, 0, 0, QStringLiteral( "fld <= 10" ) ) ); QgsRuleBasedRenderer r( rootRule ); QVERIFY( r.capabilities() & QgsFeatureRenderer::MoreSymbolsPerFeature ); @@ -120,9 +120,9 @@ class TestQgsRuleBasedRenderer: public QObject void test_clone_ruleKey() { RRule* rootRule = new RRule( 0 ); - RRule* sub1Rule = new RRule( 0, 0, 0, "fld > 1" ); - RRule* sub2Rule = new RRule( 0, 0, 0, "fld > 2" ); - RRule* sub3Rule = new RRule( 0, 0, 0, "fld > 3" ); + RRule* sub1Rule = new RRule( 0, 0, 0, QStringLiteral( "fld > 1" ) ); + RRule* sub2Rule = new RRule( 0, 0, 0, QStringLiteral( "fld > 2" ) ); + RRule* sub3Rule = new RRule( 0, 0, 0, QStringLiteral( "fld > 3" ) ); rootRule->appendChild( sub1Rule ); sub1Rule->appendChild( sub2Rule ); sub2Rule->appendChild( sub3Rule ); @@ -145,7 +145,7 @@ class TestQgsRuleBasedRenderer: public QObject private: void xml2domElement( const QString& testFile, QDomDocument& doc ) { - QString fileName = QString( TEST_DATA_DIR ) + '/' + testFile; + QString fileName = QStringLiteral( TEST_DATA_DIR ) + '/' + testFile; QFile f( fileName ); bool fileOpen = f.open( QIODevice::ReadOnly ); QVERIFY( fileOpen ); diff --git a/tests/src/core/testqgsscaleexpression.cpp b/tests/src/core/testqgsscaleexpression.cpp index 8c0fa77817ae..292e0d00c3a6 100644 --- a/tests/src/core/testqgsscaleexpression.cpp +++ b/tests/src/core/testqgsscaleexpression.cpp @@ -38,7 +38,7 @@ class TestQgsScaleExpression: public QObject void parsing() { { - QgsScaleExpression exp( "coalesce(scale_linear(column, 1, 7, 2, 10), 0)" ); + QgsScaleExpression exp( QStringLiteral( "coalesce(scale_linear(column, 1, 7, 2, 10), 0)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Linear ); QCOMPARE( exp.baseExpression(), QString( "column" ) ); @@ -48,17 +48,17 @@ class TestQgsScaleExpression: public QObject QCOMPARE( exp.maxSize(), 10. ); } { - QgsScaleExpression exp( "coalesce(scale_exp(column, 1, 7, 2, 10, 0.5), 0)" ); + QgsScaleExpression exp( QStringLiteral( "coalesce(scale_exp(column, 1, 7, 2, 10, 0.5), 0)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Area ); } { - QgsScaleExpression exp( "coalesce(scale_exp(column, 1, 7, 2, 10, 0.57), 0)" ); + QgsScaleExpression exp( QStringLiteral( "coalesce(scale_exp(column, 1, 7, 2, 10, 0.57), 0)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Flannery ); } { - QgsScaleExpression exp( "scale_linear(column, 1, 7, 2, 10)" ); + QgsScaleExpression exp( QStringLiteral( "scale_linear(column, 1, 7, 2, 10)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Linear ); QCOMPARE( exp.baseExpression(), QString( "column" ) ); @@ -68,32 +68,32 @@ class TestQgsScaleExpression: public QObject QCOMPARE( exp.maxSize(), 10. ); } { - QgsScaleExpression exp( "scale_exp(column, 1, 7, 2, 10, 0.5)" ); + QgsScaleExpression exp( QStringLiteral( "scale_exp(column, 1, 7, 2, 10, 0.5)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Area ); } { - QgsScaleExpression exp( "scale_exp(column, 1, 7, 2, 10, 0.57)" ); + QgsScaleExpression exp( QStringLiteral( "scale_exp(column, 1, 7, 2, 10, 0.57)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Flannery ); } { - QgsScaleExpression exp( "coalesce(scale_exp(column, 1, 7, 2, 10, 0.51), 0)" ); + QgsScaleExpression exp( QStringLiteral( "coalesce(scale_exp(column, 1, 7, 2, 10, 0.51), 0)" ) ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Exponential ); } { - QgsScaleExpression exp( "coalesce(scale_exp(column, 1, 7, a, 10, 0.5), 0)" ); + QgsScaleExpression exp( QStringLiteral( "coalesce(scale_exp(column, 1, 7, a, 10, 0.5), 0)" ) ); QCOMPARE( bool( exp ), false ); QCOMPARE( exp.type(), QgsScaleExpression::Unknown ); } { - QgsScaleExpression exp( "coalesce(scale_exp(column, 1, 7), 0)" ); + QgsScaleExpression exp( QStringLiteral( "coalesce(scale_exp(column, 1, 7), 0)" ) ); QCOMPARE( bool( exp ), false ); QCOMPARE( exp.type(), QgsScaleExpression::Unknown ); } { - QgsScaleExpression exp( QgsScaleExpression::Linear, "column", 1, 7, 2, 10 ); + QgsScaleExpression exp( QgsScaleExpression::Linear, QStringLiteral( "column" ), 1, 7, 2, 10 ); QCOMPARE( bool( exp ), true ); QCOMPARE( exp.type(), QgsScaleExpression::Linear ); QCOMPARE( exp.baseExpression(), QString( "column" ) ); diff --git a/tests/src/core/testqgsshapeburst.cpp b/tests/src/core/testqgsshapeburst.cpp index 7346505d6ccc..42eeccc082b4 100644 --- a/tests/src/core/testqgsshapeburst.cpp +++ b/tests/src/core/testqgsshapeburst.cpp @@ -97,7 +97,7 @@ void TestQgsShapeburst::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -119,7 +119,7 @@ void TestQgsShapeburst::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPolysLayer->id() ); - mReport += "

                                                                                                                                                                                    Shapeburst Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsShapeburst::cleanupTestCase() @@ -138,7 +138,7 @@ void TestQgsShapeburst::cleanupTestCase() void TestQgsShapeburst::shapeburstSymbol() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer test

                                                                                                                                                                                    \n" ); mShapeburstFill->setColor( QColor( "red" ) ); mShapeburstFill->setColor2( QColor( "blue" ) ); mShapeburstFill->setBlurRadius( 0 ); @@ -148,7 +148,7 @@ void TestQgsShapeburst::shapeburstSymbol() void TestQgsShapeburst::shapeburstSymbolColors() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer color test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer color test

                                                                                                                                                                                    \n" ); mShapeburstFill->setColor( QColor( "green" ) ); mShapeburstFill->setColor2( QColor( "white" ) ); QVERIFY( imageCheck( "shapeburst_colors" ) ); @@ -158,7 +158,7 @@ void TestQgsShapeburst::shapeburstSymbolColors() void TestQgsShapeburst::shapeburstSymbolRamp() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer ramp test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer ramp test

                                                                                                                                                                                    \n" ); QgsGradientColorRamp* gradientRamp = new QgsGradientColorRamp( QColor( Qt::yellow ), QColor( 255, 105, 180 ) ); QgsGradientStopsList stops; @@ -173,7 +173,7 @@ void TestQgsShapeburst::shapeburstSymbolRamp() void TestQgsShapeburst::shapeburstBlur() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer blur test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer blur test

                                                                                                                                                                                    \n" ); mShapeburstFill->setBlurRadius( 17 ); QVERIFY( imageCheck( "shapeburst_blur" ) ); mShapeburstFill->setBlurRadius( 0 ); @@ -181,7 +181,7 @@ void TestQgsShapeburst::shapeburstBlur() void TestQgsShapeburst::shapeburstMaxDistanceMm() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer maximum distance MM

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer maximum distance MM

                                                                                                                                                                                    \n" ); mShapeburstFill->setUseWholeShape( false ); mShapeburstFill->setMaxDistance( 3 ); mShapeburstFill->setDistanceUnit( QgsUnitTypes::RenderMillimeters ); @@ -191,7 +191,7 @@ void TestQgsShapeburst::shapeburstMaxDistanceMm() void TestQgsShapeburst::shapeburstMaxDistanceMapUnits() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer maximum distance map units

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer maximum distance map units

                                                                                                                                                                                    \n" ); mShapeburstFill->setUseWholeShape( false ); mShapeburstFill->setMaxDistance( 10 ); mShapeburstFill->setDistanceUnit( QgsUnitTypes::RenderMapUnits ); @@ -202,7 +202,7 @@ void TestQgsShapeburst::shapeburstMaxDistanceMapUnits() void TestQgsShapeburst::shapeburstIgnoreRings() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol renderer ignore rings

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol renderer ignore rings

                                                                                                                                                                                    \n" ); mShapeburstFill->setIgnoreRings( true ); QVERIFY( imageCheck( "shapeburst_ignorerings" ) ); mShapeburstFill->setIgnoreRings( false ); @@ -210,7 +210,7 @@ void TestQgsShapeburst::shapeburstIgnoreRings() void TestQgsShapeburst::shapeburstSymbolFromQml() { - mReport += "

                                                                                                                                                                                    Shapeburst symbol from QML test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Shapeburst symbol from QML test

                                                                                                                                                                                    \n" ); QVERIFY( setQml( "shapeburst" ) ); QgsVectorSimplifyMethod simplifyMethod; simplifyMethod.setSimplifyHints( QgsVectorSimplifyMethod::NoSimplification ); @@ -244,7 +244,7 @@ bool TestQgsShapeburst::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPolysLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsMultiRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_shapeburst" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_shapeburst" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); myChecker.setColorTolerance( 20 ); diff --git a/tests/src/core/testqgssimplemarker.cpp b/tests/src/core/testqgssimplemarker.cpp index 69d1aa76e6ef..27d738db1510 100644 --- a/tests/src/core/testqgssimplemarker.cpp +++ b/tests/src/core/testqgssimplemarker.cpp @@ -99,7 +99,7 @@ void TestQgsSimpleMarkerSymbol::initTestCase() QString pointFileName = mTestDataDir + "points.shp"; QFileInfo pointFileInfo( pointFileName ); mpPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( @@ -117,7 +117,7 @@ void TestQgsSimpleMarkerSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPointsLayer->id() ); - mReport += "

                                                                                                                                                                                    Simple Marker Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Simple Marker Tests

                                                                                                                                                                                    \n" ); } void TestQgsSimpleMarkerSymbol::cleanupTestCase() @@ -136,7 +136,7 @@ void TestQgsSimpleMarkerSymbol::cleanupTestCase() void TestQgsSimpleMarkerSymbol::simpleMarkerSymbol() { - mReport += "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n" ); mSimpleMarkerLayer->setColor( Qt::blue ); mSimpleMarkerLayer->setBorderColor( Qt::black ); @@ -148,7 +148,7 @@ void TestQgsSimpleMarkerSymbol::simpleMarkerSymbol() void TestQgsSimpleMarkerSymbol::simpleMarkerSymbolBevelJoin() { - mReport += "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n" ); mSimpleMarkerLayer->setColor( Qt::blue ); mSimpleMarkerLayer->setBorderColor( Qt::black ); @@ -161,7 +161,7 @@ void TestQgsSimpleMarkerSymbol::simpleMarkerSymbolBevelJoin() void TestQgsSimpleMarkerSymbol::simpleMarkerSymbolMiterJoin() { - mReport += "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n" ); mSimpleMarkerLayer->setColor( Qt::blue ); mSimpleMarkerLayer->setBorderColor( Qt::black ); @@ -174,7 +174,7 @@ void TestQgsSimpleMarkerSymbol::simpleMarkerSymbolMiterJoin() void TestQgsSimpleMarkerSymbol::simpleMarkerSymbolRoundJoin() { - mReport += "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Simple marker symbol layer test

                                                                                                                                                                                    \n" ); mSimpleMarkerLayer->setColor( Qt::blue ); mSimpleMarkerLayer->setBorderColor( Qt::black ); @@ -191,13 +191,13 @@ void TestQgsSimpleMarkerSymbol::bounds() mSimpleMarkerLayer->setBorderColor( QColor( 0, 0, 0 ) ); mSimpleMarkerLayer->setShape( QgsSimpleMarkerSymbolLayerBase::Circle ); mSimpleMarkerLayer->setSize( 5 ); - mSimpleMarkerLayer->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "min(\"importance\" * 2, 6)" ) ); + mSimpleMarkerLayer->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "min(\"importance\" * 2, 6)" ) ) ); mSimpleMarkerLayer->setOutlineWidth( 0.5 ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "simplemarker_bounds" ); + bool result = imageCheck( QStringLiteral( "simplemarker_bounds" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); - mSimpleMarkerLayer->removeDataDefinedProperty( "size" ); + mSimpleMarkerLayer->removeDataDefinedProperty( QStringLiteral( "size" ) ); QVERIFY( result ); } @@ -207,13 +207,13 @@ void TestQgsSimpleMarkerSymbol::boundsWithOffset() mSimpleMarkerLayer->setBorderColor( QColor( 0, 0, 0 ) ); mSimpleMarkerLayer->setShape( QgsSimpleMarkerSymbolLayerBase::Circle ); mSimpleMarkerLayer->setSize( 5 ); - mSimpleMarkerLayer->setDataDefinedProperty( "offset", new QgsDataDefined( true, true, "if(importance > 2, '5,10', '10, 5')" ) ); + mSimpleMarkerLayer->setDataDefinedProperty( QStringLiteral( "offset" ), new QgsDataDefined( true, true, QStringLiteral( "if(importance > 2, '5,10', '10, 5')" ) ) ); mSimpleMarkerLayer->setOutlineWidth( 0.5 ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "simplemarker_boundsoffset" ); + bool result = imageCheck( QStringLiteral( "simplemarker_boundsoffset" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); - mSimpleMarkerLayer->removeDataDefinedProperty( "offset" ); + mSimpleMarkerLayer->removeDataDefinedProperty( QStringLiteral( "offset" ) ); QVERIFY( result ); } @@ -223,13 +223,13 @@ void TestQgsSimpleMarkerSymbol::boundsWithRotation() mSimpleMarkerLayer->setBorderColor( QColor( 0, 0, 0 ) ); mSimpleMarkerLayer->setShape( QgsSimpleMarkerSymbolLayerBase::Square ); mSimpleMarkerLayer->setSize( 5 ); - mSimpleMarkerLayer->setDataDefinedProperty( "angle", new QgsDataDefined( true, true, "importance * 20" ) ); + mSimpleMarkerLayer->setDataDefinedProperty( QStringLiteral( "angle" ), new QgsDataDefined( true, true, QStringLiteral( "importance * 20" ) ) ); mSimpleMarkerLayer->setOutlineWidth( 0.5 ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "simplemarker_boundsrotation" ); + bool result = imageCheck( QStringLiteral( "simplemarker_boundsrotation" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); - mSimpleMarkerLayer->removeDataDefinedProperty( "angle" ); + mSimpleMarkerLayer->removeDataDefinedProperty( QStringLiteral( "angle" ) ); QVERIFY( result ); } @@ -239,15 +239,15 @@ void TestQgsSimpleMarkerSymbol::boundsWithRotationAndOffset() mSimpleMarkerLayer->setBorderColor( QColor( 0, 0, 0 ) ); mSimpleMarkerLayer->setShape( QgsSimpleMarkerSymbolLayerBase::Square ); mSimpleMarkerLayer->setSize( 5 ); - mSimpleMarkerLayer->setDataDefinedProperty( "offset", new QgsDataDefined( true, true, "if(importance > 2, '5,10', '10, 5')" ) ); - mSimpleMarkerLayer->setDataDefinedProperty( "angle", new QgsDataDefined( true, false, QString(), "heading" ) ); + mSimpleMarkerLayer->setDataDefinedProperty( QStringLiteral( "offset" ), new QgsDataDefined( true, true, QStringLiteral( "if(importance > 2, '5,10', '10, 5')" ) ) ); + mSimpleMarkerLayer->setDataDefinedProperty( QStringLiteral( "angle" ), new QgsDataDefined( true, false, QString(), QStringLiteral( "heading" ) ) ); mSimpleMarkerLayer->setOutlineWidth( 0.5 ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "simplemarker_boundsrotationoffset" ); + bool result = imageCheck( QStringLiteral( "simplemarker_boundsrotationoffset" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); - mSimpleMarkerLayer->removeDataDefinedProperty( "offset" ); - mSimpleMarkerLayer->removeDataDefinedProperty( "angle" ); + mSimpleMarkerLayer->removeDataDefinedProperty( QStringLiteral( "offset" ) ); + mSimpleMarkerLayer->removeDataDefinedProperty( QStringLiteral( "angle" ) ); QVERIFY( result ); } @@ -284,7 +284,7 @@ bool TestQgsSimpleMarkerSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPointsLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_simplemarker" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_simplemarker" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgssnappingutils.cpp b/tests/src/core/testqgssnappingutils.cpp index fd8ed395dae6..eb0bb95db30f 100644 --- a/tests/src/core/testqgssnappingutils.cpp +++ b/tests/src/core/testqgssnappingutils.cpp @@ -62,7 +62,7 @@ class TestQgsSnappingUtils : public QObject // \ | // \| // + (1,0) - mVL = new QgsVectorLayer( "Polygon", "x", "memory" ); + mVL = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); QgsFeature ff( 0 ); QgsPolygon polygon; QgsPolyline polyline; @@ -190,7 +190,7 @@ class TestQgsSnappingUtils : public QObject // \/ // /\ . // (0,0) x x (1,0) - QgsVectorLayer* vl = new QgsVectorLayer( "LineString", "x", "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "LineString" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); QgsPolyline polyline1, polyline2; polyline1 << QgsPoint( 0, 0 ) << QgsPoint( 1, 1 ); polyline2 << QgsPoint( 1, 0 ) << QgsPoint( 0, 1 ); diff --git a/tests/src/core/testqgsspatialindex.cpp b/tests/src/core/testqgsspatialindex.cpp index da66614072f3..b033c34079da 100644 --- a/tests/src/core/testqgsspatialindex.cpp +++ b/tests/src/core/testqgsspatialindex.cpp @@ -143,7 +143,7 @@ class TestQgsSpatialIndex : public QObject void benchmarkBulkLoad() { - QgsVectorLayer* vl = new QgsVectorLayer( "Point", "x", "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); for ( int i = 0; i < 100; ++i ) { QgsFeatureList flist; diff --git a/tests/src/core/testqgsstyle.cpp b/tests/src/core/testqgsstyle.cpp index ffa6a3ebf6e2..3ee9353d5dc4 100644 --- a/tests/src/core/testqgsstyle.cpp +++ b/tests/src/core/testqgsstyle.cpp @@ -82,15 +82,15 @@ void TestStyle::initTestCase() QgsApplication::init( QDir::tempPath() + "/dot-qgis" ); QgsApplication::initQgis(); QgsApplication::createDB(); - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt // output test environment QgsApplication::showSettings(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); // initialize with a clean style QFile styleFile( QgsApplication::userStylePath() ); @@ -105,7 +105,7 @@ void TestStyle::initTestCase() // cpt-city ramp, small selection available in /cpt-city QgsCptCityArchive::initArchives(); - mReport += "

                                                                                                                                                                                    Style Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Style Tests

                                                                                                                                                                                    \n" ); } void TestStyle::cleanupTestCase() @@ -168,47 +168,47 @@ void TestStyle::testCreateColorRamps() // color brewer ramp QgsColorBrewerColorRamp* cb1Ramp = new QgsColorBrewerColorRamp(); QVERIFY( mStyle->addColorRamp( "test_cb1", cb1Ramp, true ) ); - QgsColorBrewerColorRamp* cb2Ramp = new QgsColorBrewerColorRamp( "RdYlGn", 6 ); + QgsColorBrewerColorRamp* cb2Ramp = new QgsColorBrewerColorRamp( QStringLiteral( "RdYlGn" ), 6 ); QVERIFY( mStyle->addColorRamp( "test_cb2", cb2Ramp, true ) ); // discrete ramp with no variant - QgsCptCityColorRamp* cc1Ramp = new QgsCptCityColorRamp( "cb/seq/PuBuGn_06", "" ); + QgsCptCityColorRamp* cc1Ramp = new QgsCptCityColorRamp( QStringLiteral( "cb/seq/PuBuGn_06" ), QLatin1String( "" ) ); QVERIFY( mStyle->addColorRamp( "test_cc1", cc1Ramp, true ) ); // discrete ramp with variant - QgsCptCityColorRamp* cc2Ramp = new QgsCptCityColorRamp( "cb/div/PiYG", "_10" ); + QgsCptCityColorRamp* cc2Ramp = new QgsCptCityColorRamp( QStringLiteral( "cb/div/PiYG" ), QStringLiteral( "_10" ) ); QVERIFY( mStyle->addColorRamp( "test_cc2", cc2Ramp, true ) ); // continuous ramp - QgsCptCityColorRamp* cc3Ramp = new QgsCptCityColorRamp( "grass/byr", "" ); + QgsCptCityColorRamp* cc3Ramp = new QgsCptCityColorRamp( QStringLiteral( "grass/byr" ), QLatin1String( "" ) ); QVERIFY( mStyle->addColorRamp( "test_cc3", cc3Ramp, true ) ); } void TestStyle::testLoadColorRamps() { QStringList colorRamps = mStyle->colorRampNames(); - QStringList colorRampsTest = QStringList() << "BrBG" << "Spectral" - << "test_gradient" << "test_random" - << "test_cb1" << "test_cb2"; + QStringList colorRampsTest = QStringList() << QStringLiteral( "BrBG" ) << QStringLiteral( "Spectral" ) + << QStringLiteral( "test_gradient" ) << QStringLiteral( "test_random" ) + << QStringLiteral( "test_cb1" ) << QStringLiteral( "test_cb2" ); // values for color tests QMultiMap< QString, QPair< double, QColor> > colorTests; - colorTests.insert( "test_gradient", qMakePair( 0.25, QColor( "#ff8080" ) ) ); - colorTests.insert( "test_gradient", qMakePair( 0.66, QColor( "#aeaeff" ) ) ); + colorTests.insert( QStringLiteral( "test_gradient" ), qMakePair( 0.25, QColor( "#ff8080" ) ) ); + colorTests.insert( QStringLiteral( "test_gradient" ), qMakePair( 0.66, QColor( "#aeaeff" ) ) ); // cannot test random colors! - colorTests.insert( "test_cb1", qMakePair( 0.25, QColor( "#fdae61" ) ) ); - colorTests.insert( "test_cb1", qMakePair( 0.66, QColor( "#abdda4" ) ) ); - colorTests.insert( "test_cb2", qMakePair( 0.25, QColor( "#fc8d59" ) ) ); - colorTests.insert( "test_cb2", qMakePair( 0.66, QColor( "#d9ef8b" ) ) ); + colorTests.insert( QStringLiteral( "test_cb1" ), qMakePair( 0.25, QColor( "#fdae61" ) ) ); + colorTests.insert( QStringLiteral( "test_cb1" ), qMakePair( 0.66, QColor( "#abdda4" ) ) ); + colorTests.insert( QStringLiteral( "test_cb2" ), qMakePair( 0.25, QColor( "#fc8d59" ) ) ); + colorTests.insert( QStringLiteral( "test_cb2" ), qMakePair( 0.66, QColor( "#d9ef8b" ) ) ); // cpt-city - colorRampsTest << "test_cc1"; - colorTests.insert( "test_cc1", qMakePair( 0.25, QColor( "#d0d1e6" ) ) ); - colorTests.insert( "test_cc1", qMakePair( 0.66, QColor( "#67a9cf" ) ) ); - colorRampsTest << "test_cc2"; - colorTests.insert( "test_cc2", qMakePair( 0.25, QColor( "#de77ae" ) ) ); - colorTests.insert( "test_cc2", qMakePair( 0.66, QColor( "#b8e186" ) ) ); - colorRampsTest << "test_cc3"; - colorTests.insert( "test_cc3", qMakePair( 0.25, QColor( "#808080" ) ) ); - colorTests.insert( "test_cc3", qMakePair( 0.66, QColor( "#ffae00" ) ) ); + colorRampsTest << QStringLiteral( "test_cc1" ); + colorTests.insert( QStringLiteral( "test_cc1" ), qMakePair( 0.25, QColor( "#d0d1e6" ) ) ); + colorTests.insert( QStringLiteral( "test_cc1" ), qMakePair( 0.66, QColor( "#67a9cf" ) ) ); + colorRampsTest << QStringLiteral( "test_cc2" ); + colorTests.insert( QStringLiteral( "test_cc2" ), qMakePair( 0.25, QColor( "#de77ae" ) ) ); + colorTests.insert( QStringLiteral( "test_cc2" ), qMakePair( 0.66, QColor( "#b8e186" ) ) ); + colorRampsTest << QStringLiteral( "test_cc3" ); + colorTests.insert( QStringLiteral( "test_cc3" ), qMakePair( 0.25, QColor( "#808080" ) ) ); + colorTests.insert( QStringLiteral( "test_cc3" ), qMakePair( 0.66, QColor( "#ffae00" ) ) ); QgsDebugMsg( "loaded colorRamps: " + colorRamps.join( " " ) ); @@ -243,7 +243,7 @@ void TestStyle::testSaveLoad() QStringList colorRamps = mStyle->colorRampNames(); QgsDebugMsg( "loaded colorRamps: " + colorRamps.join( " " ) ); - QStringList colorRampsTest = QStringList() << "test_gradient"; + QStringList colorRampsTest = QStringList() << QStringLiteral( "test_gradient" ); Q_FOREACH ( const QString& name, colorRampsTest ) { @@ -262,15 +262,15 @@ void TestStyle::testTags() { mStyle->clear(); //add some tags - int id = mStyle->addTag( "red" ); + int id = mStyle->addTag( QStringLiteral( "red" ) ); QCOMPARE( id, mStyle->tagId( "red" ) ); - id = mStyle->addTag( "starry" ); + id = mStyle->addTag( QStringLiteral( "starry" ) ); QCOMPARE( id, mStyle->tagId( "starry" ) ); - id = mStyle->addTag( "circle" ); + id = mStyle->addTag( QStringLiteral( "circle" ) ); QCOMPARE( id, mStyle->tagId( "circle" ) ); - id = mStyle->addTag( "blue" ); + id = mStyle->addTag( QStringLiteral( "blue" ) ); QCOMPARE( id, mStyle->tagId( "blue" ) ); - id = mStyle->addTag( "purple" ); + id = mStyle->addTag( QStringLiteral( "purple" ) ); QCOMPARE( id, mStyle->tagId( "purple" ) ); QStringList tags = mStyle->tags(); @@ -282,7 +282,7 @@ void TestStyle::testTags() QVERIFY( tags.contains( "purple" ) ); //remove tag - mStyle->remove( QgsStyle::TagEntity, mStyle->tagId( "purple" ) ); + mStyle->remove( QgsStyle::TagEntity, mStyle->tagId( QStringLiteral( "purple" ) ) ); mStyle->remove( QgsStyle::TagEntity, -999 ); //bad id tags = mStyle->tags(); QCOMPARE( tags.count(), 4 ); @@ -290,8 +290,8 @@ void TestStyle::testTags() //add some symbols QVERIFY( mStyle->saveSymbol( "symbol1", QgsMarkerSymbol::createSimple( QgsStringMap() ), 0, QStringList() << "red" << "starry" ) ); - mStyle->addSymbol( "blue starry", QgsMarkerSymbol::createSimple( QgsStringMap() ), true ); - mStyle->addSymbol( "red circle", QgsMarkerSymbol::createSimple( QgsStringMap() ), true ); + mStyle->addSymbol( QStringLiteral( "blue starry" ), QgsMarkerSymbol::createSimple( QgsStringMap() ), true ); + mStyle->addSymbol( QStringLiteral( "red circle" ), QgsMarkerSymbol::createSimple( QgsStringMap() ), true ); //tag them QVERIFY( mStyle->tagSymbol( QgsStyle::SymbolEntity, "blue starry", QStringList() << "blue" << "starry" ) ); @@ -304,23 +304,23 @@ void TestStyle::testTags() QVERIFY( tags.contains( "round" ) ); //check that tags have been applied - tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, "blue starry" ); + tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, QStringLiteral( "blue starry" ) ); QCOMPARE( tags.count(), 2 ); QVERIFY( tags.contains( "blue" ) ); QVERIFY( tags.contains( "starry" ) ); - tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, "red circle" ); + tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, QStringLiteral( "red circle" ) ); QCOMPARE( tags.count(), 3 ); QVERIFY( tags.contains( "red" ) ); QVERIFY( tags.contains( "circle" ) ); QVERIFY( tags.contains( "round" ) ); - tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, "symbol1" ); + tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, QStringLiteral( "symbol1" ) ); QCOMPARE( tags.count(), 2 ); QVERIFY( tags.contains( "red" ) ); QVERIFY( tags.contains( "starry" ) ); //remove a tag, including a non-present tag QVERIFY( mStyle->detagSymbol( QgsStyle::SymbolEntity, "blue starry", QStringList() << "bad" << "blue" ) ); - tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, "blue starry" ); + tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, QStringLiteral( "blue starry" ) ); QCOMPARE( tags.count(), 1 ); QVERIFY( tags.contains( "starry" ) ); @@ -328,41 +328,41 @@ void TestStyle::testTags() QVERIFY( !mStyle->detagSymbol( QgsStyle::SymbolEntity, "no symbol!", QStringList() << "bad" << "blue" ) ); //check symbols with tag - QStringList symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( "red" ) ); + QStringList symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( QStringLiteral( "red" ) ) ); QCOMPARE( symbols.count(), 2 ); QVERIFY( symbols.contains( "symbol1" ) ); QVERIFY( symbols.contains( "red circle" ) ); - symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( "starry" ) ); + symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( QStringLiteral( "starry" ) ) ); QCOMPARE( symbols.count(), 2 ); QVERIFY( symbols.contains( "symbol1" ) ); QVERIFY( symbols.contains( "blue starry" ) ); - symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( "circle" ) ); + symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( QStringLiteral( "circle" ) ) ); QCOMPARE( symbols.count(), 1 ); QVERIFY( symbols.contains( "red circle" ) ); - symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( "round" ) ); + symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( QStringLiteral( "round" ) ) ); QCOMPARE( symbols.count(), 1 ); QVERIFY( symbols.contains( "red circle" ) ); - symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( "blue" ) ); + symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( QStringLiteral( "blue" ) ) ); QVERIFY( symbols.isEmpty() ); - symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( "no tag" ) ); + symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( QStringLiteral( "no tag" ) ) ); QVERIFY( symbols.isEmpty() ); //searching returns symbols with matching tags - symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, "red" ); + symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, QStringLiteral( "red" ) ); QCOMPARE( symbols.count(), 2 ); QVERIFY( symbols.contains( "symbol1" ) ); QVERIFY( symbols.contains( "red circle" ) ); - symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, "symbol1" ); + symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, QStringLiteral( "symbol1" ) ); QCOMPARE( symbols.count(), 1 ); QVERIFY( symbols.contains( "symbol1" ) ); - symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, "starry" ); + symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, QStringLiteral( "starry" ) ); QCOMPARE( symbols.count(), 2 ); QVERIFY( symbols.contains( "symbol1" ) ); QVERIFY( symbols.contains( "blue starry" ) ); - symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, "blue" ); + symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, QStringLiteral( "blue" ) ); QCOMPARE( symbols.count(), 1 ); QVERIFY( symbols.contains( "blue starry" ) ); - symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, "round" ); + symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, QStringLiteral( "round" ) ); QCOMPARE( symbols.count(), 1 ); QVERIFY( symbols.contains( "red circle" ) ); } diff --git a/tests/src/core/testqgssvgmarker.cpp b/tests/src/core/testqgssvgmarker.cpp index 6bd1ecbbeb7a..02bca206e83b 100644 --- a/tests/src/core/testqgssvgmarker.cpp +++ b/tests/src/core/testqgssvgmarker.cpp @@ -92,7 +92,7 @@ void TestQgsSvgMarkerSymbol::initTestCase() QString pointFileName = mTestDataDir + "points.shp"; QFileInfo pointFileInfo( pointFileName ); mpPointsLayer = new QgsVectorLayer( pointFileInfo.filePath(), - pointFileInfo.completeBaseName(), "ogr" ); + pointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( @@ -110,7 +110,7 @@ void TestQgsSvgMarkerSymbol::initTestCase() // and is more light weight // mMapSettings.setLayers( QStringList() << mpPointsLayer->id() ); - mReport += "

                                                                                                                                                                                    SVG Marker Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    SVG Marker Tests

                                                                                                                                                                                    \n" ); } void TestQgsSvgMarkerSymbol::cleanupTestCase() @@ -129,9 +129,9 @@ void TestQgsSvgMarkerSymbol::cleanupTestCase() void TestQgsSvgMarkerSymbol::svgMarkerSymbol() { - mReport += "

                                                                                                                                                                                    SVG marker symbol layer test

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    SVG marker symbol layer test

                                                                                                                                                                                    \n" ); - mSvgMarkerLayer->setPath( "/transport/transport_airport.svg" ); + mSvgMarkerLayer->setPath( QStringLiteral( "/transport/transport_airport.svg" ) ); mSvgMarkerLayer->setOutlineColor( Qt::black ); mSvgMarkerLayer->setColor( Qt::blue ); mSvgMarkerLayer->setSize( 10 ); @@ -146,10 +146,10 @@ void TestQgsSvgMarkerSymbol::bounds() mSvgMarkerLayer->setOutlineColor( Qt::black ); mSvgMarkerLayer->setColor( Qt::blue ); mSvgMarkerLayer->setOutlineWidth( 0.5 ); - mSvgMarkerLayer->setDataDefinedProperty( "size", new QgsDataDefined( true, true, "min(\"importance\" * 2, 6)" ) ); + mSvgMarkerLayer->setDataDefinedProperty( QStringLiteral( "size" ), new QgsDataDefined( true, true, QStringLiteral( "min(\"importance\" * 2, 6)" ) ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, true ); - bool result = imageCheck( "svgmarker_bounds" ); + bool result = imageCheck( QStringLiteral( "svgmarker_bounds" ) ); mMapSettings.setFlag( QgsMapSettings::DrawSymbolBounds, false ); QVERIFY( result ); } @@ -166,7 +166,7 @@ bool TestQgsSvgMarkerSymbol::imageCheck( const QString& theTestType ) mMapSettings.setExtent( mpPointsLayer->extent() ); mMapSettings.setOutputDpi( 96 ); QgsRenderChecker myChecker; - myChecker.setControlPathPrefix( "symbol_svgmarker" ); + myChecker.setControlPathPrefix( QStringLiteral( "symbol_svgmarker" ) ); myChecker.setControlName( "expected_" + theTestType ); myChecker.setMapSettings( mMapSettings ); bool myResultFlag = myChecker.runTest( theTestType ); diff --git a/tests/src/core/testqgssymbol.cpp b/tests/src/core/testqgssymbol.cpp index 5a9d470bf513..551f079f00e5 100644 --- a/tests/src/core/testqgssymbol.cpp +++ b/tests/src/core/testqgssymbol.cpp @@ -85,15 +85,15 @@ void TestQgsSymbol::initTestCase() QgsApplication::init( QDir::tempPath() + "/dot-qgis" ); QgsApplication::initQgis(); QgsApplication::createDB(); - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt // output test environment QgsApplication::showSettings(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); // initialize with a clean style QFile styleFile( QgsApplication::userStylePath() ); @@ -111,7 +111,7 @@ void TestQgsSymbol::initTestCase() QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mpPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPointsLayer ); @@ -122,7 +122,7 @@ void TestQgsSymbol::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPolysLayer ); @@ -134,12 +134,12 @@ void TestQgsSymbol::initTestCase() QString myLinesFileName = mTestDataDir + "lines.shp"; QFileInfo myLineFileInfo( myLinesFileName ); mpLinesLayer = new QgsVectorLayer( myLineFileInfo.filePath(), - myLineFileInfo.completeBaseName(), "ogr" ); + myLineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpLinesLayer ); - mReport += "

                                                                                                                                                                                    StyleV2 Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    StyleV2 Tests

                                                                                                                                                                                    \n" ); } void TestQgsSymbol::cleanupTestCase() @@ -177,7 +177,7 @@ void TestQgsSymbol::testCanvasClip() ms.setFlag( QgsMapSettings::ForceVectorOutput ); //line - mReport += "

                                                                                                                                                                                    Line canvas clip

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Line canvas clip

                                                                                                                                                                                    \n" ); ms.setLayers( QStringList() << mpLinesLayer->id() ); QgsMarkerLineSymbolLayer* markerLine = new QgsMarkerLineSymbolLayer(); @@ -189,15 +189,15 @@ void TestQgsSymbol::testCanvasClip() bool result; lineSymbol->setClipFeaturesToExtent( true ); - result = imageCheck( ms, "style_linecanvasclip" ); + result = imageCheck( ms, QStringLiteral( "style_linecanvasclip" ) ); QVERIFY( result ); lineSymbol->setClipFeaturesToExtent( false ); - result = imageCheck( ms, "style_linecanvasclip_off" ); + result = imageCheck( ms, QStringLiteral( "style_linecanvasclip_off" ) ); QVERIFY( result ); //poly - mReport += "

                                                                                                                                                                                    Polygon canvas clip

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Polygon canvas clip

                                                                                                                                                                                    \n" ); ms.setLayers( QStringList() << mpPolysLayer->id() ); QgsCentroidFillSymbolLayer* centroidFill = new QgsCentroidFillSymbolLayer(); @@ -210,11 +210,11 @@ void TestQgsSymbol::testCanvasClip() ms.setExtent( extent ); fillSymbol->setClipFeaturesToExtent( true ); - result = imageCheck( ms, "style_polycanvasclip" ); + result = imageCheck( ms, QStringLiteral( "style_polycanvasclip" ) ); QVERIFY( result ); fillSymbol->setClipFeaturesToExtent( false ); - result = imageCheck( ms, "style_polycanvasclip_off" ); + result = imageCheck( ms, QStringLiteral( "style_polycanvasclip_off" ) ); QVERIFY( result ); } @@ -223,69 +223,69 @@ void TestQgsSymbol::testParseColor() { // values for color tests QMap< QString, QPair< QColor, bool> > colorTests; - colorTests.insert( "bad color", qMakePair( QColor(), false ) ); - colorTests.insert( "red", qMakePair( QColor( 255, 0, 0 ), false ) ); - colorTests.insert( "#ff00ff", qMakePair( QColor( 255, 0, 255 ), false ) ); - colorTests.insert( "#99AA00", qMakePair( QColor( 153, 170, 0 ), false ) ); - colorTests.insert( "#GG0000", qMakePair( QColor(), false ) ); - colorTests.insert( "000000", qMakePair( QColor( 0, 0, 0 ), false ) ); - colorTests.insert( "00ff00", qMakePair( QColor( 0, 255, 0 ), false ) ); - colorTests.insert( "00gg00", qMakePair( QColor(), false ) ); - colorTests.insert( "00ff000", qMakePair( QColor(), false ) ); - colorTests.insert( "fff", qMakePair( QColor( 255, 255, 255 ), false ) ); - colorTests.insert( "fff0", qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "bad color" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "red" ), qMakePair( QColor( 255, 0, 0 ), false ) ); + colorTests.insert( QStringLiteral( "#ff00ff" ), qMakePair( QColor( 255, 0, 255 ), false ) ); + colorTests.insert( QStringLiteral( "#99AA00" ), qMakePair( QColor( 153, 170, 0 ), false ) ); + colorTests.insert( QStringLiteral( "#GG0000" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "000000" ), qMakePair( QColor( 0, 0, 0 ), false ) ); + colorTests.insert( QStringLiteral( "00ff00" ), qMakePair( QColor( 0, 255, 0 ), false ) ); + colorTests.insert( QStringLiteral( "00gg00" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "00ff000" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "fff" ), qMakePair( QColor( 255, 255, 255 ), false ) ); + colorTests.insert( QStringLiteral( "fff0" ), qMakePair( QColor(), false ) ); // hex rrggbbaa colors - colorTests.insert( "#ff00ffaa", qMakePair( QColor( 255, 0, 255, 170 ), true ) ); - colorTests.insert( "#99AA0099", qMakePair( QColor( 153, 170, 0, 153 ), true ) ); - colorTests.insert( "#GG0000aa", qMakePair( QColor(), false ) ); - colorTests.insert( "00000000", qMakePair( QColor( 0, 0, 0, 0 ), true ) ); - colorTests.insert( "00ff0011", qMakePair( QColor( 0, 255, 0, 17 ), true ) ); - colorTests.insert( "00gg0011", qMakePair( QColor(), false ) ); - colorTests.insert( "00ff00000", qMakePair( QColor(), false ) ); - - colorTests.insert( "0,0,0", qMakePair( QColor( 0, 0, 0 ), false ) ); - colorTests.insert( "127,60,0", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "255,255,255", qMakePair( QColor( 255, 255, 255 ), false ) ); - colorTests.insert( "256,60,0", qMakePair( QColor(), false ) ); - colorTests.insert( "rgb(127,60,0)", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "rgb(255,255,255)", qMakePair( QColor( 255, 255, 255 ), false ) ); - colorTests.insert( "rgb(256,60,0)", qMakePair( QColor(), false ) ); - colorTests.insert( " rgb( 127, 60 , 0 ) ", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "rgb(127,60,0);", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "(127,60,0);", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "(127,60,0)", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "127,060,000", qMakePair( QColor( 127, 60, 0 ), false ) ); - colorTests.insert( "0,0,0,0", qMakePair( QColor( 0, 0, 0, 0 ), true ) ); - colorTests.insert( "127,60,0,0.5", qMakePair( QColor( 127, 60, 0, 128 ), true ) ); - colorTests.insert( "255,255,255,0.1", qMakePair( QColor( 255, 255, 255, 26 ), true ) ); - colorTests.insert( "rgba(127,60,0,1.0)", qMakePair( QColor( 127, 60, 0, 255 ), true ) ); - colorTests.insert( "rgba(255,255,255,0.0)", qMakePair( QColor( 255, 255, 255, 0 ), true ) ); - colorTests.insert( " rgba( 127, 60 , 0 , 0.2 ) ", qMakePair( QColor( 127, 60, 0, 51 ), true ) ); - colorTests.insert( "rgba(127,60,0,0.1);", qMakePair( QColor( 127, 60, 0, 26 ), true ) ); - colorTests.insert( "(127,60,0,1);", qMakePair( QColor( 127, 60, 0, 255 ), true ) ); - colorTests.insert( "(127,60,0,1.0)", qMakePair( QColor( 127, 60, 0, 255 ), true ) ); - colorTests.insert( "127,060,000,1", qMakePair( QColor( 127, 60, 0, 255 ), true ) ); - colorTests.insert( "0%,0%,0%", qMakePair( QColor( 0, 0, 0 ), false ) ); - colorTests.insert( "50 %,60 %,0 %", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "100%, 100%, 100%", qMakePair( QColor( 255, 255, 255 ), false ) ); - colorTests.insert( "rgb(50%,60%,0%)", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "rgb(100%, 100%, 100%)", qMakePair( QColor( 255, 255, 255 ), false ) ); - colorTests.insert( " rgb( 50 % , 60 % , 0 % ) ", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "rgb(50%,60%,0%);", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "(50%,60%,0%);", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "(50%,60%,0%)", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "050%,060%,000%", qMakePair( QColor( 127, 153, 0 ), false ) ); - colorTests.insert( "0%,0%,0%,0", qMakePair( QColor( 0, 0, 0, 0 ), true ) ); - colorTests.insert( "50 %,60 %,0 %,0.5", qMakePair( QColor( 127, 153, 0, 128 ), true ) ); - colorTests.insert( "100%, 100%, 100%, 1.0", qMakePair( QColor( 255, 255, 255, 255 ), true ) ); - colorTests.insert( "rgba(50%,60%,0%, 1.0)", qMakePair( QColor( 127, 153, 0, 255 ), true ) ); - colorTests.insert( "rgba(100%, 100%, 100%, 0.0)", qMakePair( QColor( 255, 255, 255, 0 ), true ) ); - colorTests.insert( " rgba( 50 % , 60 % , 0 %, 0.5 ) ", qMakePair( QColor( 127, 153, 0, 128 ), true ) ); - colorTests.insert( "rgba(50%,60%,0%,0);", qMakePair( QColor( 127, 153, 0, 0 ), true ) ); - colorTests.insert( "(50%,60%,0%,1);", qMakePair( QColor( 127, 153, 0, 255 ), true ) ); - colorTests.insert( "(50%,60%,0%,1.0)", qMakePair( QColor( 127, 153, 0, 255 ), true ) ); - colorTests.insert( "050%,060%,000%,0", qMakePair( QColor( 127, 153, 0, 0 ), true ) ); + colorTests.insert( QStringLiteral( "#ff00ffaa" ), qMakePair( QColor( 255, 0, 255, 170 ), true ) ); + colorTests.insert( QStringLiteral( "#99AA0099" ), qMakePair( QColor( 153, 170, 0, 153 ), true ) ); + colorTests.insert( QStringLiteral( "#GG0000aa" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "00000000" ), qMakePair( QColor( 0, 0, 0, 0 ), true ) ); + colorTests.insert( QStringLiteral( "00ff0011" ), qMakePair( QColor( 0, 255, 0, 17 ), true ) ); + colorTests.insert( QStringLiteral( "00gg0011" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "00ff00000" ), qMakePair( QColor(), false ) ); + + colorTests.insert( QStringLiteral( "0,0,0" ), qMakePair( QColor( 0, 0, 0 ), false ) ); + colorTests.insert( QStringLiteral( "127,60,0" ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "255,255,255" ), qMakePair( QColor( 255, 255, 255 ), false ) ); + colorTests.insert( QStringLiteral( "256,60,0" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( "rgb(127,60,0)" ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "rgb(255,255,255)" ), qMakePair( QColor( 255, 255, 255 ), false ) ); + colorTests.insert( QStringLiteral( "rgb(256,60,0)" ), qMakePair( QColor(), false ) ); + colorTests.insert( QStringLiteral( " rgb( 127, 60 , 0 ) " ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "rgb(127,60,0);" ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "(127,60,0);" ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "(127,60,0)" ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "127,060,000" ), qMakePair( QColor( 127, 60, 0 ), false ) ); + colorTests.insert( QStringLiteral( "0,0,0,0" ), qMakePair( QColor( 0, 0, 0, 0 ), true ) ); + colorTests.insert( QStringLiteral( "127,60,0,0.5" ), qMakePair( QColor( 127, 60, 0, 128 ), true ) ); + colorTests.insert( QStringLiteral( "255,255,255,0.1" ), qMakePair( QColor( 255, 255, 255, 26 ), true ) ); + colorTests.insert( QStringLiteral( "rgba(127,60,0,1.0)" ), qMakePair( QColor( 127, 60, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "rgba(255,255,255,0.0)" ), qMakePair( QColor( 255, 255, 255, 0 ), true ) ); + colorTests.insert( QStringLiteral( " rgba( 127, 60 , 0 , 0.2 ) " ), qMakePair( QColor( 127, 60, 0, 51 ), true ) ); + colorTests.insert( QStringLiteral( "rgba(127,60,0,0.1);" ), qMakePair( QColor( 127, 60, 0, 26 ), true ) ); + colorTests.insert( QStringLiteral( "(127,60,0,1);" ), qMakePair( QColor( 127, 60, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "(127,60,0,1.0)" ), qMakePair( QColor( 127, 60, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "127,060,000,1" ), qMakePair( QColor( 127, 60, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "0%,0%,0%" ), qMakePair( QColor( 0, 0, 0 ), false ) ); + colorTests.insert( QStringLiteral( "50 %,60 %,0 %" ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "100%, 100%, 100%" ), qMakePair( QColor( 255, 255, 255 ), false ) ); + colorTests.insert( QStringLiteral( "rgb(50%,60%,0%)" ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "rgb(100%, 100%, 100%)" ), qMakePair( QColor( 255, 255, 255 ), false ) ); + colorTests.insert( QStringLiteral( " rgb( 50 % , 60 % , 0 % ) " ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "rgb(50%,60%,0%);" ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%);" ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%)" ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "050%,060%,000%" ), qMakePair( QColor( 127, 153, 0 ), false ) ); + colorTests.insert( QStringLiteral( "0%,0%,0%,0" ), qMakePair( QColor( 0, 0, 0, 0 ), true ) ); + colorTests.insert( QStringLiteral( "50 %,60 %,0 %,0.5" ), qMakePair( QColor( 127, 153, 0, 128 ), true ) ); + colorTests.insert( QStringLiteral( "100%, 100%, 100%, 1.0" ), qMakePair( QColor( 255, 255, 255, 255 ), true ) ); + colorTests.insert( QStringLiteral( "rgba(50%,60%,0%, 1.0)" ), qMakePair( QColor( 127, 153, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "rgba(100%, 100%, 100%, 0.0)" ), qMakePair( QColor( 255, 255, 255, 0 ), true ) ); + colorTests.insert( QStringLiteral( " rgba( 50 % , 60 % , 0 %, 0.5 ) " ), qMakePair( QColor( 127, 153, 0, 128 ), true ) ); + colorTests.insert( QStringLiteral( "rgba(50%,60%,0%,0);" ), qMakePair( QColor( 127, 153, 0, 0 ), true ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%,1);" ), qMakePair( QColor( 127, 153, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%,1.0)" ), qMakePair( QColor( 127, 153, 0, 255 ), true ) ); + colorTests.insert( QStringLiteral( "050%,060%,000%,0" ), qMakePair( QColor( 127, 153, 0, 0 ), true ) ); QMap >::const_iterator i = colorTests.constBegin(); while ( i != colorTests.constEnd() ) @@ -304,69 +304,69 @@ void TestQgsSymbol::testParseColorList() //ensure that majority of single parseColor tests work for lists //note that some are not possible, as the colors may be ambiguous when treated as a list QMap< QString, QColor > colorTests; - colorTests.insert( "bad color", QColor() ); - colorTests.insert( "red", QColor( 255, 0, 0 ) ); - colorTests.insert( "#ff00ff", QColor( 255, 0, 255 ) ); - colorTests.insert( "#99AA00", QColor( 153, 170, 0 ) ); - colorTests.insert( "#GG0000", QColor() ); + colorTests.insert( QStringLiteral( "bad color" ), QColor() ); + colorTests.insert( QStringLiteral( "red" ), QColor( 255, 0, 0 ) ); + colorTests.insert( QStringLiteral( "#ff00ff" ), QColor( 255, 0, 255 ) ); + colorTests.insert( QStringLiteral( "#99AA00" ), QColor( 153, 170, 0 ) ); + colorTests.insert( QStringLiteral( "#GG0000" ), QColor() ); //colorTests.insert( "000000", QColor( 0, 0, 0 ) ); //colorTests.insert( "00ff00", QColor( 0, 255, 0 ) ); //colorTests.insert( "00gg00", QColor() ); - colorTests.insert( "00ff000", QColor() ); + colorTests.insert( QStringLiteral( "00ff000" ), QColor() ); //colorTests.insert( "fff", QColor( 255, 255, 255 ) ); - colorTests.insert( "fff0", QColor() ); + colorTests.insert( QStringLiteral( "fff0" ), QColor() ); // hex rrggbbaa colors - colorTests.insert( "#ff00ffaa", QColor( 255, 0, 255, 170 ) ); - colorTests.insert( "#99AA0099", QColor( 153, 170, 0, 153 ) ); - colorTests.insert( "#GG0000aa", QColor() ); - colorTests.insert( "00000000", QColor( 0, 0, 0, 0 ) ); - colorTests.insert( "00ff0011", QColor( 0, 255, 0, 17 ) ); - colorTests.insert( "00gg0011", QColor() ); - colorTests.insert( "00ff00000", QColor() ); - - colorTests.insert( "0,0,0", QColor( 0, 0, 0 ) ); - colorTests.insert( "127,60,0", QColor( 127, 60, 0 ) ); - colorTests.insert( "255,255,255", QColor( 255, 255, 255 ) ); + colorTests.insert( QStringLiteral( "#ff00ffaa" ), QColor( 255, 0, 255, 170 ) ); + colorTests.insert( QStringLiteral( "#99AA0099" ), QColor( 153, 170, 0, 153 ) ); + colorTests.insert( QStringLiteral( "#GG0000aa" ), QColor() ); + colorTests.insert( QStringLiteral( "00000000" ), QColor( 0, 0, 0, 0 ) ); + colorTests.insert( QStringLiteral( "00ff0011" ), QColor( 0, 255, 0, 17 ) ); + colorTests.insert( QStringLiteral( "00gg0011" ), QColor() ); + colorTests.insert( QStringLiteral( "00ff00000" ), QColor() ); + + colorTests.insert( QStringLiteral( "0,0,0" ), QColor( 0, 0, 0 ) ); + colorTests.insert( QStringLiteral( "127,60,0" ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "255,255,255" ), QColor( 255, 255, 255 ) ); //colorTests.insert( "256,60,0", QColor() ); - colorTests.insert( "rgb(127,60,0)", QColor( 127, 60, 0 ) ); - colorTests.insert( "rgb(255,255,255)", QColor( 255, 255, 255 ) ); - colorTests.insert( "rgb(256,60,0)", QColor() ); - colorTests.insert( " rgb( 127, 60 , 0 ) ", QColor( 127, 60, 0 ) ); - colorTests.insert( "rgb(127,60,0);", QColor( 127, 60, 0 ) ); - colorTests.insert( "(127,60,0);", QColor( 127, 60, 0 ) ); - colorTests.insert( "(127,60,0)", QColor( 127, 60, 0 ) ); - colorTests.insert( "127,060,000", QColor( 127, 60, 0 ) ); - colorTests.insert( "0,0,0,0", QColor( 0, 0, 0, 0 ) ); - colorTests.insert( "127,60,0,0.5", QColor( 127, 60, 0, 128 ) ); - colorTests.insert( "255,255,255,0.1", QColor( 255, 255, 255, 26 ) ); - colorTests.insert( "rgba(127,60,0,1.0)", QColor( 127, 60, 0, 255 ) ); - colorTests.insert( "rgba(255,255,255,0.0)", QColor( 255, 255, 255, 0 ) ); - colorTests.insert( " rgba( 127, 60 , 0 , 0.2 ) ", QColor( 127, 60, 0, 51 ) ); - colorTests.insert( "rgba(127,60,0,0.1);", QColor( 127, 60, 0, 26 ) ); - colorTests.insert( "(127,60,0,1);", QColor( 127, 60, 0, 255 ) ); - colorTests.insert( "(127,60,0,1.0)", QColor( 127, 60, 0, 255 ) ); - colorTests.insert( "127,060,000,1", QColor( 127, 60, 0, 255 ) ); - colorTests.insert( "0%,0%,0%", QColor( 0, 0, 0 ) ); - colorTests.insert( "50 %,60 %,0 %", QColor( 127, 153, 0 ) ); - colorTests.insert( "100%, 100%, 100%", QColor( 255, 255, 255 ) ); - colorTests.insert( "rgb(50%,60%,0%)", QColor( 127, 153, 0 ) ); - colorTests.insert( "rgb(100%, 100%, 100%)", QColor( 255, 255, 255 ) ); - colorTests.insert( " rgb( 50 % , 60 % , 0 % ) ", QColor( 127, 153, 0 ) ); - colorTests.insert( "rgb(50%,60%,0%);", QColor( 127, 153, 0 ) ); - colorTests.insert( "(50%,60%,0%);", QColor( 127, 153, 0 ) ); - colorTests.insert( "(50%,60%,0%)", QColor( 127, 153, 0 ) ); - colorTests.insert( "050%,060%,000%", QColor( 127, 153, 0 ) ); - colorTests.insert( "0%,0%,0%,0", QColor( 0, 0, 0, 0 ) ); - colorTests.insert( "50 %,60 %,0 %,0.5", QColor( 127, 153, 0, 128 ) ); - colorTests.insert( "100%, 100%, 100%, 1.0", QColor( 255, 255, 255, 255 ) ); - colorTests.insert( "rgba(50%,60%,0%, 1.0)", QColor( 127, 153, 0, 255 ) ); - colorTests.insert( "rgba(100%, 100%, 100%, 0.0)", QColor( 255, 255, 255, 0 ) ); - colorTests.insert( " rgba( 50 % , 60 % , 0 %, 0.5 ) ", QColor( 127, 153, 0, 128 ) ); - colorTests.insert( "rgba(50%,60%,0%,0);", QColor( 127, 153, 0, 0 ) ); - colorTests.insert( "(50%,60%,0%,1);", QColor( 127, 153, 0, 255 ) ); - colorTests.insert( "(50%,60%,0%,1.0)", QColor( 127, 153, 0, 255 ) ); - colorTests.insert( "050%,060%,000%,0", QColor( 127, 153, 0, 0 ) ); + colorTests.insert( QStringLiteral( "rgb(127,60,0)" ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "rgb(255,255,255)" ), QColor( 255, 255, 255 ) ); + colorTests.insert( QStringLiteral( "rgb(256,60,0)" ), QColor() ); + colorTests.insert( QStringLiteral( " rgb( 127, 60 , 0 ) " ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "rgb(127,60,0);" ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "(127,60,0);" ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "(127,60,0)" ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "127,060,000" ), QColor( 127, 60, 0 ) ); + colorTests.insert( QStringLiteral( "0,0,0,0" ), QColor( 0, 0, 0, 0 ) ); + colorTests.insert( QStringLiteral( "127,60,0,0.5" ), QColor( 127, 60, 0, 128 ) ); + colorTests.insert( QStringLiteral( "255,255,255,0.1" ), QColor( 255, 255, 255, 26 ) ); + colorTests.insert( QStringLiteral( "rgba(127,60,0,1.0)" ), QColor( 127, 60, 0, 255 ) ); + colorTests.insert( QStringLiteral( "rgba(255,255,255,0.0)" ), QColor( 255, 255, 255, 0 ) ); + colorTests.insert( QStringLiteral( " rgba( 127, 60 , 0 , 0.2 ) " ), QColor( 127, 60, 0, 51 ) ); + colorTests.insert( QStringLiteral( "rgba(127,60,0,0.1);" ), QColor( 127, 60, 0, 26 ) ); + colorTests.insert( QStringLiteral( "(127,60,0,1);" ), QColor( 127, 60, 0, 255 ) ); + colorTests.insert( QStringLiteral( "(127,60,0,1.0)" ), QColor( 127, 60, 0, 255 ) ); + colorTests.insert( QStringLiteral( "127,060,000,1" ), QColor( 127, 60, 0, 255 ) ); + colorTests.insert( QStringLiteral( "0%,0%,0%" ), QColor( 0, 0, 0 ) ); + colorTests.insert( QStringLiteral( "50 %,60 %,0 %" ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "100%, 100%, 100%" ), QColor( 255, 255, 255 ) ); + colorTests.insert( QStringLiteral( "rgb(50%,60%,0%)" ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "rgb(100%, 100%, 100%)" ), QColor( 255, 255, 255 ) ); + colorTests.insert( QStringLiteral( " rgb( 50 % , 60 % , 0 % ) " ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "rgb(50%,60%,0%);" ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%);" ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%)" ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "050%,060%,000%" ), QColor( 127, 153, 0 ) ); + colorTests.insert( QStringLiteral( "0%,0%,0%,0" ), QColor( 0, 0, 0, 0 ) ); + colorTests.insert( QStringLiteral( "50 %,60 %,0 %,0.5" ), QColor( 127, 153, 0, 128 ) ); + colorTests.insert( QStringLiteral( "100%, 100%, 100%, 1.0" ), QColor( 255, 255, 255, 255 ) ); + colorTests.insert( QStringLiteral( "rgba(50%,60%,0%, 1.0)" ), QColor( 127, 153, 0, 255 ) ); + colorTests.insert( QStringLiteral( "rgba(100%, 100%, 100%, 0.0)" ), QColor( 255, 255, 255, 0 ) ); + colorTests.insert( QStringLiteral( " rgba( 50 % , 60 % , 0 %, 0.5 ) " ), QColor( 127, 153, 0, 128 ) ); + colorTests.insert( QStringLiteral( "rgba(50%,60%,0%,0);" ), QColor( 127, 153, 0, 0 ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%,1);" ), QColor( 127, 153, 0, 255 ) ); + colorTests.insert( QStringLiteral( "(50%,60%,0%,1.0)" ), QColor( 127, 153, 0, 255 ) ); + colorTests.insert( QStringLiteral( "050%,060%,000%,0" ), QColor( 127, 153, 0, 0 ) ); QMap::const_iterator i = colorTests.constBegin(); while ( i != colorTests.constEnd() ) @@ -387,24 +387,24 @@ void TestQgsSymbol::testParseColorList() QVector< QPair< QString, QList > > colorListTests; QList list1; - list1 << QColor( QString( "blue" ) ) << QColor( QString( "red" ) ) << QColor( QString( "green" ) ); - colorListTests.append( qMakePair( QString( "blue red green" ), list1 ) ); - colorListTests.append( qMakePair( QString( "blue,red,green" ), list1 ) ); - colorListTests.append( qMakePair( QString( "blue\nred\ngreen" ), list1 ) ); - colorListTests.append( qMakePair( QString( "blue\nred green" ), list1 ) ); - colorListTests.append( qMakePair( QString( "blue\nred,green" ), list1 ) ); + list1 << QColor( QStringLiteral( "blue" ) ) << QColor( QStringLiteral( "red" ) ) << QColor( QStringLiteral( "green" ) ); + colorListTests.append( qMakePair( QStringLiteral( "blue red green" ), list1 ) ); + colorListTests.append( qMakePair( QStringLiteral( "blue,red,green" ), list1 ) ); + colorListTests.append( qMakePair( QStringLiteral( "blue\nred\ngreen" ), list1 ) ); + colorListTests.append( qMakePair( QStringLiteral( "blue\nred green" ), list1 ) ); + colorListTests.append( qMakePair( QStringLiteral( "blue\nred,green" ), list1 ) ); QList list2; - list2 << QColor( QString( "#ff0000" ) ) << QColor( QString( "#00ff00" ) ) << QColor( QString( "#0000ff" ) ); - colorListTests.append( qMakePair( QString( "#ff0000 #00ff00 #0000ff" ), list2 ) ); - colorListTests.append( qMakePair( QString( "#ff0000,#00ff00,#0000ff" ), list2 ) ); - colorListTests.append( qMakePair( QString( "#ff0000\n#00ff00\n#0000ff" ), list2 ) ); - colorListTests.append( qMakePair( QString( "#ff0000\n#00ff00 #0000ff" ), list2 ) ); - colorListTests.append( qMakePair( QString( "#ff0000\n#00ff00,#0000ff" ), list2 ) ); + list2 << QColor( QStringLiteral( "#ff0000" ) ) << QColor( QStringLiteral( "#00ff00" ) ) << QColor( QStringLiteral( "#0000ff" ) ); + colorListTests.append( qMakePair( QStringLiteral( "#ff0000 #00ff00 #0000ff" ), list2 ) ); + colorListTests.append( qMakePair( QStringLiteral( "#ff0000,#00ff00,#0000ff" ), list2 ) ); + colorListTests.append( qMakePair( QStringLiteral( "#ff0000\n#00ff00\n#0000ff" ), list2 ) ); + colorListTests.append( qMakePair( QStringLiteral( "#ff0000\n#00ff00 #0000ff" ), list2 ) ); + colorListTests.append( qMakePair( QStringLiteral( "#ff0000\n#00ff00,#0000ff" ), list2 ) ); QList list3; - list3 << QColor( QString( "#ff0000" ) ) << QColor( QString( "#00ff00" ) ) << QColor( QString( "#0000ff" ) ); - colorListTests.append( qMakePair( QString( "rgb(255,0,0) rgb(0,255,0) rgb(0,0,255)" ), list3 ) ); - colorListTests.append( qMakePair( QString( "rgb(255,0,0)\nrgb(0,255,0)\nrgb(0,0,255)" ), list3 ) ); - colorListTests.append( qMakePair( QString( "rgb(255,0,0)\nrgb(0,255,0) rgb(0,0,255)" ), list3 ) ); + list3 << QColor( QStringLiteral( "#ff0000" ) ) << QColor( QStringLiteral( "#00ff00" ) ) << QColor( QStringLiteral( "#0000ff" ) ); + colorListTests.append( qMakePair( QStringLiteral( "rgb(255,0,0) rgb(0,255,0) rgb(0,0,255)" ), list3 ) ); + colorListTests.append( qMakePair( QStringLiteral( "rgb(255,0,0)\nrgb(0,255,0)\nrgb(0,0,255)" ), list3 ) ); + colorListTests.append( qMakePair( QStringLiteral( "rgb(255,0,0)\nrgb(0,255,0) rgb(0,0,255)" ), list3 ) ); QVector< QPair< QString, QList > >::const_iterator it = colorListTests.constBegin(); while ( it != colorListTests.constEnd() ) diff --git a/tests/src/core/testqgstracer.cpp b/tests/src/core/testqgstracer.cpp index 20ca4696e37c..0da6e3146056 100644 --- a/tests/src/core/testqgstracer.cpp +++ b/tests/src/core/testqgstracer.cpp @@ -62,7 +62,7 @@ static QgsFeature make_feature( const QString& wkt ) static QgsVectorLayer* make_layer( const QStringList& wkts ) { - QgsVectorLayer* vl = new QgsVectorLayer( "LineString", "x", "memory" ); + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "LineString" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); Q_ASSERT( vl->isValid() ); vl->startEditing(); @@ -105,10 +105,10 @@ void TestQgsTracer::cleanupTestCase() void TestQgsTracer::testSimple() { QStringList wkts; - wkts << "LINESTRING(0 0, 0 10)" - << "LINESTRING(0 0, 10 0)" - << "LINESTRING(0 10, 20 10)" - << "LINESTRING(10 0, 20 10)"; + wkts << QStringLiteral( "LINESTRING(0 0, 0 10)" ) + << QStringLiteral( "LINESTRING(0 0, 10 0)" ) + << QStringLiteral( "LINESTRING(0 10, 20 10)" ) + << QStringLiteral( "LINESTRING(10 0, 20 10)" ); /* This shape - nearly a square (one side is shifted to have exactly one shortest * path between corners): @@ -162,7 +162,7 @@ void TestQgsTracer::testPolygon() // to check extraction from polygons work + routing along one ring works QStringList wkts; - wkts << "POLYGON((0 0, 0 10, 20 10, 10 0, 0 0))"; + wkts << QStringLiteral( "POLYGON((0 0, 0 10, 20 10, 10 0, 0 0))" ); QgsVectorLayer* vl = make_layer( wkts ); @@ -183,7 +183,7 @@ void TestQgsTracer::testButterfly() // checks whether tracer internally splits linestrings at intersections QStringList wkts; - wkts << "LINESTRING(0 0, 0 10, 10 0, 10 10, 0 0)"; + wkts << QStringLiteral( "LINESTRING(0 0, 0 10, 10 0, 10 10, 0 0)" ); /* This shape (without a vertex where the linestring crosses itself): * + + 10,10 @@ -214,10 +214,10 @@ void TestQgsTracer::testLayerUpdates() // same shape as in testSimple() QStringList wkts; - wkts << "LINESTRING(0 0, 0 10)" - << "LINESTRING(0 0, 10 0)" - << "LINESTRING(0 10, 20 10)" - << "LINESTRING(10 0, 20 10)"; + wkts << QStringLiteral( "LINESTRING(0 0, 0 10)" ) + << QStringLiteral( "LINESTRING(0 0, 10 0)" ) + << QStringLiteral( "LINESTRING(0 10, 20 10)" ) + << QStringLiteral( "LINESTRING(10 0, 20 10)" ); QgsVectorLayer* vl = make_layer( wkts ); @@ -234,7 +234,7 @@ void TestQgsTracer::testLayerUpdates() vl->startEditing(); // add a shortcut - QgsFeature f( make_feature( "LINESTRING(10 0, 10 10)" ) ); + QgsFeature f( make_feature( QStringLiteral( "LINESTRING(10 0, 10 10)" ) ) ); vl->addFeature( f ); QgsPolyline points2 = tracer.findShortestPath( QgsPoint( 10, 0 ), QgsPoint( 10, 10 ) ); @@ -252,7 +252,7 @@ void TestQgsTracer::testLayerUpdates() QCOMPARE( points3[2], QgsPoint( 10, 10 ) ); // make the shortcut again from a different feature - QgsGeometry g = QgsGeometry::fromWkt( "LINESTRING(10 0, 10 10)" ); + QgsGeometry g = QgsGeometry::fromWkt( QStringLiteral( "LINESTRING(10 0, 10 10)" ) ); vl->changeGeometry( 2, g ); // change bottom line (second item in wkts) QgsPolyline points4 = tracer.findShortestPath( QgsPoint( 10, 0 ), QgsPoint( 10, 10 ) ); @@ -278,10 +278,10 @@ void TestQgsTracer::testExtent() // same shape as in testSimple() QStringList wkts; - wkts << "LINESTRING(0 0, 0 10)" - << "LINESTRING(0 0, 10 0)" - << "LINESTRING(0 10, 20 10)" - << "LINESTRING(10 0, 20 10)"; + wkts << QStringLiteral( "LINESTRING(0 0, 0 10)" ) + << QStringLiteral( "LINESTRING(0 0, 10 0)" ) + << QStringLiteral( "LINESTRING(0 10, 20 10)" ) + << QStringLiteral( "LINESTRING(10 0, 20 10)" ); QgsVectorLayer* vl = make_layer( wkts ); @@ -302,12 +302,12 @@ void TestQgsTracer::testExtent() void TestQgsTracer::testReprojection() { QStringList wkts; - wkts << "LINESTRING(1 0, 2 0)"; + wkts << QStringLiteral( "LINESTRING(1 0, 2 0)" ); QgsVectorLayer* vl = make_layer( wkts ); - QgsCoordinateReferenceSystem dstCrs( "EPSG:3857" ); - QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( "EPSG:4326" ), dstCrs ); + QgsCoordinateReferenceSystem dstCrs( QStringLiteral( "EPSG:3857" ) ); + QgsCoordinateTransform ct( QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ), dstCrs ); QgsPoint p1 = ct.transform( QgsPoint( 1, 0 ) ); QgsPoint p2 = ct.transform( QgsPoint( 2, 0 ) ); @@ -324,7 +324,7 @@ void TestQgsTracer::testReprojection() void TestQgsTracer::testCurved() { QStringList wkts; - wkts << "CIRCULARSTRING(0 0, 10 10, 20 0)"; + wkts << QStringLiteral( "CIRCULARSTRING(0 0, 10 10, 20 0)" ); /* This shape - half of a circle (r = 10) * 10,10 _ diff --git a/tests/src/core/testqgsvectordataprovider.cpp b/tests/src/core/testqgsvectordataprovider.cpp index 6e115d2c4df7..a321ae463818 100644 --- a/tests/src/core/testqgsvectordataprovider.cpp +++ b/tests/src/core/testqgsvectordataprovider.cpp @@ -64,16 +64,16 @@ void TestQgsVectorDataProvider::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); - QString layerPointsUrl = QString( TEST_DATA_DIR ) + "/points.shp"; - QString layerLinesUrl = QString( TEST_DATA_DIR ) + "/lines.shp"; + QString layerPointsUrl = QStringLiteral( TEST_DATA_DIR ) + "/points.shp"; + QString layerLinesUrl = QStringLiteral( TEST_DATA_DIR ) + "/lines.shp"; // load layers - vlayerPoints = new QgsVectorLayer( layerPointsUrl, "testlayer", "ogr" ); + vlayerPoints = new QgsVectorLayer( layerPointsUrl, QStringLiteral( "testlayer" ), QStringLiteral( "ogr" ) ); QVERIFY( vlayerPoints ); QVERIFY( vlayerPoints->isValid() ); - vlayerLines = new QgsVectorLayer( layerLinesUrl, "testlayer", "ogr" ); + vlayerLines = new QgsVectorLayer( layerLinesUrl, QStringLiteral( "testlayer" ), QStringLiteral( "ogr" ) ); QVERIFY( vlayerLines ); QVERIFY( vlayerLines->isValid() ); } diff --git a/tests/src/core/testqgsvectorfilewriter.cpp b/tests/src/core/testqgsvectorfilewriter.cpp index be266dd51a8f..b0226bc9171c 100644 --- a/tests/src/core/testqgsvectorfilewriter.cpp +++ b/tests/src/core/testqgsvectorfilewriter.cpp @@ -111,8 +111,8 @@ void TestQgsVectorFileWriter::initTestCase() QgsApplication::showSettings(); //create some objects that will be used in all tests... - mEncoding = "UTF-8"; - QgsField myField1( "Field1", QVariant::String, "String", 10, 0, "Field 1 comment" ); + mEncoding = QStringLiteral( "UTF-8" ); + QgsField myField1( QStringLiteral( "Field1" ), QVariant::String, QStringLiteral( "String" ), 10, 0, QStringLiteral( "Field 1 comment" ) ); mFields.append( myField1 ); mCRS = QgsCoordinateReferenceSystem( GEOWKT ); mPoint1 = QgsPoint( 10.0, 10.0 ); @@ -133,7 +133,7 @@ void TestQgsVectorFileWriter::createPoint() // // Remove old copies that may be lying around // - QString myFileName = "/testpt.shp"; + QString myFileName = QStringLiteral( "/testpt.shp" ); myFileName = QDir::tempPath() + myFileName; QVERIFY( QgsVectorFileWriter::deleteShapeFile( myFileName ) ); QgsVectorFileWriter myWriter( myFileName, @@ -176,7 +176,7 @@ void TestQgsVectorFileWriter::createLine() // // Remove old copies that may be lying around // - QString myFileName = "/testln.shp"; + QString myFileName = QStringLiteral( "/testln.shp" ); myFileName = QDir::tempPath() + myFileName; QVERIFY( QgsVectorFileWriter::deleteShapeFile( myFileName ) ); QgsVectorFileWriter myWriter( myFileName, @@ -221,7 +221,7 @@ void TestQgsVectorFileWriter::createPolygon() // // Remove old copies that may be lying around // - QString myFileName = "/testply.shp"; + QString myFileName = QStringLiteral( "/testply.shp" ); myFileName = QDir::tempPath() + myFileName; QVERIFY( QgsVectorFileWriter::deleteShapeFile( myFileName ) ); QgsVectorFileWriter myWriter( myFileName, @@ -269,7 +269,7 @@ void TestQgsVectorFileWriter::polygonGridTest() // // Remove old copies that may be lying around // - QString myFileName = "/testgrid.shp"; + QString myFileName = QStringLiteral( "/testgrid.shp" ); myFileName = QDir::tempPath() + myFileName; QVERIFY( QgsVectorFileWriter::deleteShapeFile( myFileName ) ); QgsVectorFileWriter myWriter( myFileName, @@ -329,7 +329,7 @@ void TestQgsVectorFileWriter::projectedPlygonGridTest() // // Remove old copies that may be lying around // - QString myFileName = "/testprjgrid.shp"; + QString myFileName = QStringLiteral( "/testprjgrid.shp" ); myFileName = QDir::tempPath() + myFileName; QVERIFY( QgsVectorFileWriter::deleteShapeFile( myFileName ) ); // @@ -407,8 +407,8 @@ void TestQgsVectorFileWriter::regression1141() #endif //create some objects that will be used in all tests... - QString encoding = "UTF-8"; - QgsField myField( "ąęćń", QVariant::Int, "int", 10, 0, "Value on lon" ); + QString encoding = QStringLiteral( "UTF-8" ); + QgsField myField( QStringLiteral( "ąęćń" ), QVariant::Int, QStringLiteral( "int" ), 10, 0, QStringLiteral( "Value on lon" ) ); QgsFields fields; fields.append( myField ); QgsCoordinateReferenceSystem crs; diff --git a/tests/src/core/testqgsvectorlayer.cpp b/tests/src/core/testqgsvectorlayer.cpp index 2209cac88fe1..9399b7e2b383 100644 --- a/tests/src/core/testqgsvectorlayer.cpp +++ b/tests/src/core/testqgsvectorlayer.cpp @@ -122,7 +122,7 @@ void TestQgsVectorLayer::initTestCase() QString myDbfFileName = mTestDataDir + "nonspatial.dbf"; QFileInfo myDbfFileInfo( myDbfFileName ); mpNonSpatialLayer = new QgsVectorLayer( myDbfFileInfo.filePath(), - myDbfFileInfo.completeBaseName(), "ogr" ); + myDbfFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpNonSpatialLayer ); @@ -132,7 +132,7 @@ void TestQgsVectorLayer::initTestCase() QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mpPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPointsLayer ); @@ -143,7 +143,7 @@ void TestQgsVectorLayer::initTestCase() QString myPolysFileName = mTestDataDir + "polys.shp"; QFileInfo myPolyFileInfo( myPolysFileName ); mpPolysLayer = new QgsVectorLayer( myPolyFileInfo.filePath(), - myPolyFileInfo.completeBaseName(), "ogr" ); + myPolyFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpPolysLayer ); @@ -155,12 +155,12 @@ void TestQgsVectorLayer::initTestCase() QString myLinesFileName = mTestDataDir + "lines.shp"; QFileInfo myLineFileInfo( myLinesFileName ); mpLinesLayer = new QgsVectorLayer( myLineFileInfo.filePath(), - myLineFileInfo.completeBaseName(), "ogr" ); + myLineFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // Register the layer with the registry QgsMapLayerRegistry::instance()->addMapLayers( QList() << mpLinesLayer ); - mReport += "

                                                                                                                                                                                    Vector Renderer Tests

                                                                                                                                                                                    \n"; + mReport += QLatin1String( "

                                                                                                                                                                                    Vector Renderer Tests

                                                                                                                                                                                    \n" ); } void TestQgsVectorLayer::cleanupTestCase() @@ -194,16 +194,16 @@ void TestQgsVectorLayer::QgsVectorLayerNonSpatialIterator() void TestQgsVectorLayer::QgsVectorLayerGetValues() { - QgsVectorLayer* layer = new QgsVectorLayer( "Point?field=col1:real", "layer", "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:real" ), QStringLiteral( "layer" ), QStringLiteral( "memory" ) ); QVERIFY( layer->isValid() ); QgsFeature f1( layer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 1 ); QgsFeature f2( layer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", 2 ); + f2.setAttribute( QStringLiteral( "col1" ), 2 ); QgsFeature f3( layer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", 3 ); + f3.setAttribute( QStringLiteral( "col1" ), 3 ); QgsFeature f4( layer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", QVariant() ); + f4.setAttribute( QStringLiteral( "col1" ), QVariant() ); layer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); //make a selection @@ -212,7 +212,7 @@ void TestQgsVectorLayer::QgsVectorLayerGetValues() layer->selectByIds( ids ); bool ok; - QList varList = layer->getValues( "col1", ok ); + QList varList = layer->getValues( QStringLiteral( "col1" ), ok ); QVERIFY( ok ); QCOMPARE( varList.length(), 4 ); QCOMPARE( varList.at( 0 ), QVariant( 1 ) ); @@ -221,14 +221,14 @@ void TestQgsVectorLayer::QgsVectorLayerGetValues() QCOMPARE( varList.at( 3 ), QVariant() ); //check with selected features - varList = layer->getValues( "col1", ok, true ); + varList = layer->getValues( QStringLiteral( "col1" ), ok, true ); QVERIFY( ok ); QCOMPARE( varList.length(), 2 ); QCOMPARE( varList.at( 0 ), QVariant( 2 ) ); QCOMPARE( varList.at( 1 ), QVariant( 3 ) ); int nulls = 0; - QList doubleList = layer->getDoubleValues( "col1", ok, false, &nulls ); + QList doubleList = layer->getDoubleValues( QStringLiteral( "col1" ), ok, false, &nulls ); QVERIFY( ok ); QCOMPARE( doubleList.length(), 3 ); QCOMPARE( doubleList.at( 0 ), 1.0 ); @@ -237,14 +237,14 @@ void TestQgsVectorLayer::QgsVectorLayerGetValues() QCOMPARE( nulls, 1 ); //check with selected features - doubleList = layer->getDoubleValues( "col1", ok, true, &nulls ); + doubleList = layer->getDoubleValues( QStringLiteral( "col1" ), ok, true, &nulls ); QVERIFY( ok ); QCOMPARE( doubleList.length(), 2 ); QCOMPARE( doubleList.at( 0 ), 2.0 ); QCOMPARE( doubleList.at( 1 ), 3.0 ); QCOMPARE( nulls, 0 ); - QList expVarList = layer->getValues( "tostring(col1) || ' '", ok ); + QList expVarList = layer->getValues( QStringLiteral( "tostring(col1) || ' '" ), ok ); QVERIFY( ok ); QCOMPARE( expVarList.length(), 4 ); QCOMPARE( expVarList.at( 0 ).toString(), QString( "1 " ) ); @@ -252,7 +252,7 @@ void TestQgsVectorLayer::QgsVectorLayerGetValues() QCOMPARE( expVarList.at( 2 ).toString(), QString( "3 " ) ); QCOMPARE( expVarList.at( 3 ), QVariant() ); - QList expDoubleList = layer->getDoubleValues( "col1 * 2", ok, false, &nulls ); + QList expDoubleList = layer->getDoubleValues( QStringLiteral( "col1 * 2" ), ok, false, &nulls ); QVERIFY( ok ); QCOMPARE( expDoubleList.length(), 3 ); QCOMPARE( expDoubleList.at( 0 ), 2.0 ); diff --git a/tests/src/core/testqgsvectorlayercache.cpp b/tests/src/core/testqgsvectorlayercache.cpp index 0781b21e07de..5cd564feb8a2 100644 --- a/tests/src/core/testqgsvectorlayercache.cpp +++ b/tests/src/core/testqgsvectorlayercache.cpp @@ -72,7 +72,7 @@ void TestVectorLayerCache::initTestCase() // Backup test shape file and attributes QStringList backupFiles; - backupFiles << "points.shp" << "points.shx" << "points.dbf" << "points.prj"; + backupFiles << QStringLiteral( "points.shp" ) << QStringLiteral( "points.shx" ) << QStringLiteral( "points.dbf" ) << QStringLiteral( "points.prj" ); QString myDataDir( TEST_DATA_DIR ); //defined in CmakeLists.txt QString myTestDataDir = myDataDir + '/'; @@ -96,7 +96,7 @@ void TestVectorLayerCache::initTestCase() QString myPointsFileName = mTmpFiles.value( myTestDataDir + "points.shp" ); QFileInfo myPointFileInfo( myPointsFileName ); mPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); } void TestVectorLayerCache::init() @@ -127,7 +127,7 @@ void TestVectorLayerCache::cleanupTestCase() } // also clean up newly created .qix file - QFile::remove( QString( TEST_DATA_DIR ) + "/points.qix" ); + QFile::remove( QStringLiteral( TEST_DATA_DIR ) + "/points.qix" ); QgsApplication::exitQgis(); } @@ -156,14 +156,14 @@ void TestVectorLayerCache::testCacheAttrActions() // Add an attribute, make sure it is returned also if a cached feature is requested mPointsLayer->startEditing(); QVariant::Type attrType = QVariant::Int; - mPointsLayer->addAttribute( QgsField( "newAttr", attrType, "Int", 5, 0 ) ); + mPointsLayer->addAttribute( QgsField( QStringLiteral( "newAttr" ), attrType, QStringLiteral( "Int" ), 5, 0 ) ); mPointsLayer->commitChanges(); QVERIFY( mVectorLayerCache->featureAtId( 15, f ) ); QVERIFY( f.attribute( "newAttr" ).isValid() ); QgsFields allFields = mPointsLayer->fields(); - int idx = allFields.indexFromName( "newAttr" ); + int idx = allFields.indexFromName( QStringLiteral( "newAttr" ) ); mPointsLayer->startEditing(); mPointsLayer->deleteAttribute( idx ); @@ -206,7 +206,7 @@ void TestVectorLayerCache::testSubsetRequest() QgsFields fields = mPointsLayer->fields(); QStringList requiredFields; - requiredFields << "Class" << "Cabin Crew"; + requiredFields << QStringLiteral( "Class" ) << QStringLiteral( "Cabin Crew" ); mVectorLayerCache->featureAtId( 16, f ); QVariant a = f.attribute( 3 ); diff --git a/tests/src/core/testqgsvectorlayerjoinbuffer.cpp b/tests/src/core/testqgsvectorlayerjoinbuffer.cpp index a8821edcaa08..ad0d040b2d90 100644 --- a/tests/src/core/testqgsvectorlayerjoinbuffer.cpp +++ b/tests/src/core/testqgsvectorlayerjoinbuffer.cpp @@ -75,35 +75,35 @@ void TestVectorLayerJoinBuffer::initTestCase() QgsApplication::initQgis(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); - mProviders = QList() << "memory"; + mProviders = QList() << QStringLiteral( "memory" ); // Create memory layers // LAYER A // - QgsVectorLayer* vlA = new QgsVectorLayer( "Point?field=id_a:integer", "A", "memory" ); + QgsVectorLayer* vlA = new QgsVectorLayer( QStringLiteral( "Point?field=id_a:integer" ), QStringLiteral( "A" ), QStringLiteral( "memory" ) ); QVERIFY( vlA->isValid() ); QVERIFY( vlA->fields().count() == 1 ); // LAYER B // - QgsVectorLayer* vlB = new QgsVectorLayer( "Point?field=id_b:integer&field=value_b", "B", "memory" ); + QgsVectorLayer* vlB = new QgsVectorLayer( QStringLiteral( "Point?field=id_b:integer&field=value_b" ), QStringLiteral( "B" ), QStringLiteral( "memory" ) ); QVERIFY( vlB->isValid() ); QVERIFY( vlB->fields().count() == 2 ); // LAYER C // - QgsVectorLayer* vlC = new QgsVectorLayer( "Point?field=id_c:integer&field=value_c", "C", "memory" ); + QgsVectorLayer* vlC = new QgsVectorLayer( QStringLiteral( "Point?field=id_c:integer&field=value_c" ), QStringLiteral( "C" ), QStringLiteral( "memory" ) ); QVERIFY( vlC->isValid() ); QVERIFY( vlC->fields().count() == 2 ); // LAYER X // - QgsVectorLayer* vlX = new QgsVectorLayer( "Point?field=id_x:integer&field=value_x1:integer&field=value_x2", "X", "memory" ); + QgsVectorLayer* vlX = new QgsVectorLayer( QStringLiteral( "Point?field=id_x:integer&field=value_x1:integer&field=value_x2" ), QStringLiteral( "X" ), QStringLiteral( "memory" ) ); QVERIFY( vlX->isValid() ); QVERIFY( vlX->fields().count() == 3 ); mLayers = QMap, QgsVectorLayer*>(); - mLayers.insert( QPair( "A", "memory" ), vlA ); - mLayers.insert( QPair( "B", "memory" ), vlB ); - mLayers.insert( QPair( "C", "memory" ), vlC ); - mLayers.insert( QPair( "X", "memory" ), vlX ); + mLayers.insert( QPair( QStringLiteral( "A" ), QStringLiteral( "memory" ) ), vlA ); + mLayers.insert( QPair( QStringLiteral( "B" ), QStringLiteral( "memory" ) ), vlB ); + mLayers.insert( QPair( QStringLiteral( "C" ), QStringLiteral( "memory" ) ), vlC ); + mLayers.insert( QPair( QStringLiteral( "X" ), QStringLiteral( "memory" ) ), vlX ); // Add PG layers #ifdef ENABLE_PGTEST @@ -133,27 +133,27 @@ void TestVectorLayerJoinBuffer::initTestCase() // Create features QgsFeature fA1( vlA->dataProvider()->fields(), 1 ); - fA1.setAttribute( "id_a", 1 ); + fA1.setAttribute( QStringLiteral( "id_a" ), 1 ); QgsFeature fA2( vlA->dataProvider()->fields(), 2 ); - fA2.setAttribute( "id_a", 2 ); + fA2.setAttribute( QStringLiteral( "id_a" ), 2 ); QgsFeature fB1( vlB->dataProvider()->fields(), 1 ); - fB1.setAttribute( "id_b", 1 ); - fB1.setAttribute( "value_b", 11 ); + fB1.setAttribute( QStringLiteral( "id_b" ), 1 ); + fB1.setAttribute( QStringLiteral( "value_b" ), 11 ); QgsFeature fB2( vlB->dataProvider()->fields(), 2 ); - fB2.setAttribute( "id_b", 2 ); - fB2.setAttribute( "value_b", 12 ); + fB2.setAttribute( QStringLiteral( "id_b" ), 2 ); + fB2.setAttribute( QStringLiteral( "value_b" ), 12 ); QgsFeature fC1( vlC->dataProvider()->fields(), 1 ); - fC1.setAttribute( "id_c", 1 ); - fC1.setAttribute( "value_c", 101 ); + fC1.setAttribute( QStringLiteral( "id_c" ), 1 ); + fC1.setAttribute( QStringLiteral( "value_c" ), 101 ); QgsFeature fX1( vlX->dataProvider()->fields(), 1 ); - fX1.setAttribute( "id_x", 1 ); - fX1.setAttribute( "value_x1", 111 ); - fX1.setAttribute( "value_x2", 222 ); + fX1.setAttribute( QStringLiteral( "id_x" ), 1 ); + fX1.setAttribute( QStringLiteral( "value_x1" ), 111 ); + fX1.setAttribute( QStringLiteral( "value_x2" ), 222 ); // Commit features and layers to qgis Q_FOREACH ( const QString provider, mProviders ) { - QgsVectorLayer* vl = mLayers.value( QPair( "A", provider ) ); + QgsVectorLayer* vl = mLayers.value( QPair( QStringLiteral( "A" ), provider ) ); vl->dataProvider()->addFeatures( QgsFeatureList() << fA1 << fA2 ); QVERIFY( vl->featureCount() == 2 ); QgsMapLayerRegistry::instance()->addMapLayer( vl ); @@ -161,7 +161,7 @@ void TestVectorLayerJoinBuffer::initTestCase() Q_FOREACH ( const QString provider, mProviders ) { - QgsVectorLayer* vl = mLayers.value( QPair( "B", provider ) ); + QgsVectorLayer* vl = mLayers.value( QPair( QStringLiteral( "B" ), provider ) ); vl->dataProvider()->addFeatures( QgsFeatureList() << fB1 << fB2 ); QVERIFY( vl->featureCount() == 2 ); QgsMapLayerRegistry::instance()->addMapLayer( vl ); @@ -169,7 +169,7 @@ void TestVectorLayerJoinBuffer::initTestCase() Q_FOREACH ( const QString provider, mProviders ) { - QgsVectorLayer* vl = mLayers.value( QPair( "C", provider ) ); + QgsVectorLayer* vl = mLayers.value( QPair( QStringLiteral( "C" ), provider ) ); vl->dataProvider()->addFeatures( QgsFeatureList() << fC1 ); QVERIFY( vl->featureCount() == 1 ); QgsMapLayerRegistry::instance()->addMapLayer( vl ); @@ -177,7 +177,7 @@ void TestVectorLayerJoinBuffer::initTestCase() Q_FOREACH ( const QString provider, mProviders ) { - QgsVectorLayer* vl = mLayers.value( QPair( "X", provider ) ); + QgsVectorLayer* vl = mLayers.value( QPair( QStringLiteral( "X" ), provider ) ); vl->dataProvider()->addFeatures( QgsFeatureList() << fX1 ); QVERIFY( vl->featureCount() == 1 ); QgsMapLayerRegistry::instance()->addMapLayer( vl ); @@ -218,17 +218,17 @@ void TestVectorLayerJoinBuffer::testJoinBasic() QFETCH( bool, memoryCache ); QFETCH( QString, provider ); - QgsVectorLayer* vlA = mLayers.value( QPair( "A", provider ) ); - QgsVectorLayer* vlB = mLayers.value( QPair( "B", provider ) ); + QgsVectorLayer* vlA = mLayers.value( QPair( QStringLiteral( "A" ), provider ) ); + QgsVectorLayer* vlB = mLayers.value( QPair( QStringLiteral( "B" ), provider ) ); QVERIFY( vlA->fields().count() == 1 ); QgsVectorJoinInfo joinInfo; - joinInfo.targetFieldName = "id_a"; + joinInfo.targetFieldName = QStringLiteral( "id_a" ); joinInfo.joinLayerId = vlB->id(); - joinInfo.joinFieldName = "id_b"; + joinInfo.joinFieldName = QStringLiteral( "id_b" ); joinInfo.memoryCache = memoryCache; - joinInfo.prefix = "B_"; + joinInfo.prefix = QStringLiteral( "B_" ); vlA->addJoin( joinInfo ); QVERIFY( vlA->fields().count() == 2 ); @@ -261,9 +261,9 @@ void TestVectorLayerJoinBuffer::testJoinTransitive() QFETCH( QString, provider ); - QgsVectorLayer* vlA = mLayers.value( QPair( "A", provider ) ); - QgsVectorLayer* vlB = mLayers.value( QPair( "B", provider ) ); - QgsVectorLayer* vlC = mLayers.value( QPair( "C", provider ) ); + QgsVectorLayer* vlA = mLayers.value( QPair( QStringLiteral( "A" ), provider ) ); + QgsVectorLayer* vlB = mLayers.value( QPair( QStringLiteral( "B" ), provider ) ); + QgsVectorLayer* vlC = mLayers.value( QPair( QStringLiteral( "C" ), provider ) ); // test join A -> B -> C // first we join A -> B and after that B -> C @@ -274,22 +274,22 @@ void TestVectorLayerJoinBuffer::testJoinTransitive() // add join A -> B QgsVectorJoinInfo joinInfo1; - joinInfo1.targetFieldName = "id_a"; + joinInfo1.targetFieldName = QStringLiteral( "id_a" ); joinInfo1.joinLayerId = vlB->id(); - joinInfo1.joinFieldName = "id_b"; + joinInfo1.joinFieldName = QStringLiteral( "id_b" ); joinInfo1.memoryCache = true; - joinInfo1.prefix = "B_"; + joinInfo1.prefix = QStringLiteral( "B_" ); vlA->addJoin( joinInfo1 ); QVERIFY( vlA->fields().count() == 2 ); // id_a, B_value_b // add join B -> C QgsVectorJoinInfo joinInfo2; - joinInfo2.targetFieldName = "id_b"; + joinInfo2.targetFieldName = QStringLiteral( "id_b" ); joinInfo2.joinLayerId = vlC->id(); - joinInfo2.joinFieldName = "id_c"; + joinInfo2.joinFieldName = QStringLiteral( "id_c" ); joinInfo2.memoryCache = true; - joinInfo2.prefix = "C_"; + joinInfo2.prefix = QStringLiteral( "C_" ); vlB->addJoin( joinInfo2 ); QVERIFY( vlB->fields().count() == 3 ); // id_b, value_b, C_value_c @@ -304,7 +304,7 @@ void TestVectorLayerJoinBuffer::testJoinTransitive() QCOMPARE( fA1.attribute( "B_C_value_c" ).toInt(), 101 ); // test that layer A gets updated when layer C changes its fields - vlC->addExpressionField( "123", QgsField( "dummy", QVariant::Int ) ); + vlC->addExpressionField( QStringLiteral( "123" ), QgsField( QStringLiteral( "dummy" ), QVariant::Int ) ); QVERIFY( vlA->fields().count() == 4 ); // id_a, B_value_b, B_C_value_c, B_C_dummy vlC->removeExpressionField( 0 ); @@ -326,25 +326,25 @@ void TestVectorLayerJoinBuffer::testJoinDetectCycle() { QFETCH( QString, provider ); - QgsVectorLayer* vlA = mLayers.value( QPair( "A", provider ) ); - QgsVectorLayer* vlB = mLayers.value( QPair( "B", provider ) ); + QgsVectorLayer* vlA = mLayers.value( QPair( QStringLiteral( "A" ), provider ) ); + QgsVectorLayer* vlB = mLayers.value( QPair( QStringLiteral( "B" ), provider ) ); // if A joins B and B joins A, we may get to an infinite loop if the case is not handled properly QgsVectorJoinInfo joinInfo; - joinInfo.targetFieldName = "id_a"; + joinInfo.targetFieldName = QStringLiteral( "id_a" ); joinInfo.joinLayerId = vlB->id(); - joinInfo.joinFieldName = "id_b"; + joinInfo.joinFieldName = QStringLiteral( "id_b" ); joinInfo.memoryCache = true; - joinInfo.prefix = "B_"; + joinInfo.prefix = QStringLiteral( "B_" ); vlA->addJoin( joinInfo ); QgsVectorJoinInfo joinInfo2; - joinInfo2.targetFieldName = "id_b"; + joinInfo2.targetFieldName = QStringLiteral( "id_b" ); joinInfo2.joinLayerId = vlA->id(); - joinInfo2.joinFieldName = "id_a"; + joinInfo2.joinFieldName = QStringLiteral( "id_a" ); joinInfo2.memoryCache = true; - joinInfo2.prefix = "A_"; + joinInfo2.prefix = QStringLiteral( "A_" ); bool res = vlB->addJoin( joinInfo2 ); QVERIFY( !res ); @@ -378,17 +378,17 @@ void TestVectorLayerJoinBuffer::testJoinSubset() QVERIFY( QgsMapLayerRegistry::instance()->mapLayers().count() == 4*mProviders.count() ); - QgsVectorLayer* vlA = mLayers.value( QPair( "A", provider ) ); - QgsVectorLayer* vlX = mLayers.value( QPair( "X", provider ) ); + QgsVectorLayer* vlA = mLayers.value( QPair( QStringLiteral( "A" ), provider ) ); + QgsVectorLayer* vlX = mLayers.value( QPair( QStringLiteral( "X" ), provider ) ); // case 1: join without subset QgsVectorJoinInfo joinInfo; - joinInfo.targetFieldName = "id_a"; + joinInfo.targetFieldName = QStringLiteral( "id_a" ); joinInfo.joinLayerId = vlX->id(); - joinInfo.joinFieldName = "id_x"; + joinInfo.joinFieldName = QStringLiteral( "id_x" ); joinInfo.memoryCache = memoryCache; - joinInfo.prefix = "X_"; + joinInfo.prefix = QStringLiteral( "X_" ); bool res = vlA->addJoin( joinInfo ); QVERIFY( res ); @@ -405,7 +405,7 @@ void TestVectorLayerJoinBuffer::testJoinSubset() // case 2: join with subset QStringList* subset = new QStringList; - *subset << "value_x2"; + *subset << QStringLiteral( "value_x2" ); joinInfo.setJoinFieldNamesSubset( subset ); vlA->addJoin( joinInfo ); @@ -433,25 +433,25 @@ void TestVectorLayerJoinBuffer::testJoinTwoTimes() QFETCH( QString, provider ); - QgsVectorLayer* vlA = mLayers.value( QPair( "A", provider ) ); - QgsVectorLayer* vlB = mLayers.value( QPair( "B", provider ) ); + QgsVectorLayer* vlA = mLayers.value( QPair( QStringLiteral( "A" ), provider ) ); + QgsVectorLayer* vlB = mLayers.value( QPair( QStringLiteral( "B" ), provider ) ); QVERIFY( vlA->fields().count() == 1 ); QgsVectorJoinInfo joinInfo1; - joinInfo1.targetFieldName = "id_a"; + joinInfo1.targetFieldName = QStringLiteral( "id_a" ); joinInfo1.joinLayerId = vlB->id(); - joinInfo1.joinFieldName = "id_b"; + joinInfo1.joinFieldName = QStringLiteral( "id_b" ); joinInfo1.memoryCache = true; - joinInfo1.prefix = "j1_"; + joinInfo1.prefix = QStringLiteral( "j1_" ); vlA->addJoin( joinInfo1 ); QgsVectorJoinInfo joinInfo2; - joinInfo2.targetFieldName = "id_a"; + joinInfo2.targetFieldName = QStringLiteral( "id_a" ); joinInfo2.joinLayerId = vlB->id(); - joinInfo2.joinFieldName = "id_b"; + joinInfo2.joinFieldName = QStringLiteral( "id_b" ); joinInfo2.memoryCache = true; - joinInfo2.prefix = "j2_"; + joinInfo2.prefix = QStringLiteral( "j2_" ); vlA->addJoin( joinInfo2 ); QCOMPARE( vlA->vectorJoins().count(), 2 ); @@ -478,26 +478,26 @@ void TestVectorLayerJoinBuffer::testJoinLayerDefinitionFile() QgsMapLayerRegistry::instance()->removeAllMapLayers(); // Create two layers - QgsVectorLayer* layerA = new QgsVectorLayer( "Point?crs=epsg:4326&field=key:integer&field=value:double&index=yes", "layerA", "memory" ); + QgsVectorLayer* layerA = new QgsVectorLayer( QStringLiteral( "Point?crs=epsg:4326&field=key:integer&field=value:double&index=yes" ), QStringLiteral( "layerA" ), QStringLiteral( "memory" ) ); QVERIFY( layerA ); QgsMapLayerRegistry::instance()->addMapLayer( layerA ); - QgsVectorLayer* layerB = new QgsVectorLayer( "Point?crs=epsg:4326&field=id:integer&index=yes", "layerB", "memory" ); + QgsVectorLayer* layerB = new QgsVectorLayer( QStringLiteral( "Point?crs=epsg:4326&field=id:integer&index=yes" ), QStringLiteral( "layerB" ), QStringLiteral( "memory" ) ); QVERIFY( layerB ); QgsMapLayerRegistry::instance()->addMapLayer( layerB ); // Create vector join QgsVectorJoinInfo joinInfo; - joinInfo.targetFieldName = "id"; + joinInfo.targetFieldName = QStringLiteral( "id" ); joinInfo.joinLayerId = layerA->id(); - joinInfo.joinFieldName = "key"; + joinInfo.joinFieldName = QStringLiteral( "key" ); joinInfo.memoryCache = true; - joinInfo.prefix = "joined_"; + joinInfo.prefix = QStringLiteral( "joined_" ); r = layerB->addJoin( joinInfo ); QVERIFY( r ); // Generate QLR - QDomDocument qlrDoc( "qgis-layer-definition" ); + QDomDocument qlrDoc( QStringLiteral( "qgis-layer-definition" ) ); QString errorMessage; r = QgsLayerDefinition::exportLayerDefinition( qlrDoc, QgsProject::instance()->layerTreeRoot()->children(), errorMessage ); QVERIFY2( r, errorMessage.toUtf8().constData() ); @@ -510,7 +510,7 @@ void TestVectorLayerJoinBuffer::testJoinLayerDefinitionFile() QVERIFY2( r, errorMessage.toUtf8().constData() ); // Get layer - QList mapLayers = QgsMapLayerRegistry::instance()->mapLayersByName( "layerB" ); + QList mapLayers = QgsMapLayerRegistry::instance()->mapLayersByName( QStringLiteral( "layerB" ) ); QCOMPARE( mapLayers.count(), 1 ); QgsVectorLayer* vLayer = dynamic_cast( mapLayers.value( 0 ) ); @@ -534,35 +534,35 @@ void TestVectorLayerJoinBuffer::testCacheUpdate() { QFETCH( bool, useCache ); - QgsVectorLayer* vlA = new QgsVectorLayer( "Point?field=id_a:integer", "cacheA", "memory" ); + QgsVectorLayer* vlA = new QgsVectorLayer( QStringLiteral( "Point?field=id_a:integer" ), QStringLiteral( "cacheA" ), QStringLiteral( "memory" ) ); QVERIFY( vlA->isValid() ); - QgsVectorLayer* vlB = new QgsVectorLayer( "Point?field=id_b:integer&field=value_b", "cacheB", "memory" ); + QgsVectorLayer* vlB = new QgsVectorLayer( QStringLiteral( "Point?field=id_b:integer&field=value_b" ), QStringLiteral( "cacheB" ), QStringLiteral( "memory" ) ); QVERIFY( vlB->isValid() ); QgsMapLayerRegistry::instance()->addMapLayer( vlA ); QgsMapLayerRegistry::instance()->addMapLayer( vlB ); QgsFeature fA1( vlA->dataProvider()->fields(), 1 ); - fA1.setAttribute( "id_a", 1 ); + fA1.setAttribute( QStringLiteral( "id_a" ), 1 ); QgsFeature fA2( vlA->dataProvider()->fields(), 2 ); - fA2.setAttribute( "id_a", 2 ); + fA2.setAttribute( QStringLiteral( "id_a" ), 2 ); vlA->dataProvider()->addFeatures( QgsFeatureList() << fA1 << fA2 ); QgsFeature fB1( vlB->dataProvider()->fields(), 1 ); - fB1.setAttribute( "id_b", 1 ); - fB1.setAttribute( "value_b", 11 ); + fB1.setAttribute( QStringLiteral( "id_b" ), 1 ); + fB1.setAttribute( QStringLiteral( "value_b" ), 11 ); QgsFeature fB2( vlB->dataProvider()->fields(), 2 ); - fB2.setAttribute( "id_b", 2 ); - fB2.setAttribute( "value_b", 12 ); + fB2.setAttribute( QStringLiteral( "id_b" ), 2 ); + fB2.setAttribute( QStringLiteral( "value_b" ), 12 ); vlB->dataProvider()->addFeatures( QgsFeatureList() << fB1 << fB2 ); QgsVectorJoinInfo joinInfo; - joinInfo.targetFieldName = "id_a"; + joinInfo.targetFieldName = QStringLiteral( "id_a" ); joinInfo.joinLayerId = vlB->id(); - joinInfo.joinFieldName = "id_b"; + joinInfo.joinFieldName = QStringLiteral( "id_b" ); joinInfo.memoryCache = useCache; - joinInfo.prefix = "B_"; + joinInfo.prefix = QStringLiteral( "B_" ); vlA->addJoin( joinInfo ); QgsFeatureIterator fi = vlA->getFeatures(); diff --git a/tests/src/core/testziplayer.cpp b/tests/src/core/testziplayer.cpp index b8b45abd6f0e..b7fc303e92f0 100644 --- a/tests/src/core/testziplayer.cpp +++ b/tests/src/core/testziplayer.cpp @@ -49,9 +49,9 @@ class TestZipLayer: public QObject // get map layer using QgsZipItem (only 1 child) QgsMapLayer * getZipLayer( const QString& myPath, const QString& myName ); // test item(s) in zip item (supply name or test all) - bool testZipItem( const QString& myFileName, const QString& myChildName = "", const QString& myDriverName = "" ); + bool testZipItem( const QString& myFileName, const QString& myChildName = QStringLiteral( "" ), const QString& myDriverName = QStringLiteral( "" ) ); // get layer transparency to test for .qml loading - int getLayerTransparency( const QString& myFileName, const QString& myProviderKey, const QString& myScanZipSetting = "basic" ); + int getLayerTransparency( const QString& myFileName, const QString& myProviderKey, const QString& myScanZipSetting = QStringLiteral( "basic" ) ); bool testZipItemTransparency( const QString& myFileName, const QString& myProviderKey, int myTarget ); private slots: @@ -98,20 +98,20 @@ class TestZipLayer: public QObject QgsMapLayer *TestZipLayer::getLayer( const QString& myPath, const QString& myName, const QString& myProviderKey ) { QString fullName = myName; - if ( fullName == "" ) + if ( fullName == QLatin1String( "" ) ) { QFileInfo myFileInfo( myPath ); fullName = myFileInfo.completeBaseName(); } QgsMapLayer *myLayer = nullptr; - if ( myProviderKey == "ogr" ) + if ( myProviderKey == QLatin1String( "ogr" ) ) { - myLayer = new QgsVectorLayer( myPath, fullName, "ogr" ); + myLayer = new QgsVectorLayer( myPath, fullName, QStringLiteral( "ogr" ) ); } - else if ( myProviderKey == "gdal" ) + else if ( myProviderKey == QLatin1String( "gdal" ) ) { - myLayer = new QgsRasterLayer( myPath, fullName, QString( "gdal" ) ); + myLayer = new QgsRasterLayer( myPath, fullName, QStringLiteral( "gdal" ) ); } // item should not have other provider key, but if it does will return nullptr @@ -121,7 +121,7 @@ QgsMapLayer *TestZipLayer::getLayer( const QString& myPath, const QString& myNam QgsMapLayer *TestZipLayer::getZipLayer( const QString& myPath, const QString& myName ) { QgsMapLayer *myLayer = nullptr; - QgsDirectoryItem *dirItem = new QgsDirectoryItem( nullptr, "/", "" ); + QgsDirectoryItem *dirItem = new QgsDirectoryItem( nullptr, QStringLiteral( "/" ), QLatin1String( "" ) ); QgsDataItem* myItem = QgsZipItem::itemFromPath( dirItem, myPath, myName ); if ( myItem ) { @@ -136,7 +136,7 @@ QgsMapLayer *TestZipLayer::getZipLayer( const QString& myPath, const QString& my bool TestZipLayer::testZipItemPassthru( const QString& myFileName, const QString& myProviderKey ) { - QgsMapLayer * myLayer = getLayer( myFileName, "", myProviderKey ); + QgsMapLayer * myLayer = getLayer( myFileName, QLatin1String( "" ), myProviderKey ); bool ok = myLayer && myLayer->isValid(); if ( myLayer ) delete myLayer; @@ -173,7 +173,7 @@ bool TestZipLayer::testZipItem( const QString& myFileName, const QString& myChil if ( layerItem ) { QgsDebugMsg( QString( "child name=%1 provider=%2 path=%3" ).arg( layerItem->name(), layerItem->providerKey(), layerItem->path() ) ); - if ( myChildName == "" || myChildName == item->name() ) + if ( myChildName == QLatin1String( "" ) || myChildName == item->name() ) { QgsMapLayer* layer = getLayer( layerItem->path(), layerItem->name(), layerItem->providerKey() ); if ( layer ) @@ -187,7 +187,7 @@ bool TestZipLayer::testZipItem( const QString& myFileName, const QString& myChil { QWARN( QString( "Invalid layer %1" ).arg( layerItem->path() ).toLocal8Bit().data() ); } - if ( myChildName == "" ) + if ( myChildName == QLatin1String( "" ) ) { if ( ! ok ) break; @@ -195,7 +195,7 @@ bool TestZipLayer::testZipItem( const QString& myFileName, const QString& myChil else { //verify correct provider was used - if ( myProviderName != "" ) + if ( myProviderName != QLatin1String( "" ) ) { ok = ( myProviderName == layerItem->providerKey() ); if ( ! ok ) @@ -234,10 +234,10 @@ int TestZipLayer::getLayerTransparency( const QString& myFileName, const QString return myTransparency; QgsMapLayer * myLayer = nullptr; - if ( myFileName.endsWith( ".gz", Qt::CaseInsensitive ) ) - myLayer = getLayer( myFileName, "", myProviderKey ); + if ( myFileName.endsWith( QLatin1String( ".gz" ), Qt::CaseInsensitive ) ) + myLayer = getLayer( myFileName, QLatin1String( "" ), myProviderKey ); else - myLayer = getZipLayer( myFileName, "" ); + myLayer = getZipLayer( myFileName, QLatin1String( "" ) ); if ( myLayer && myLayer->isValid() ) { // myTransparency = myLayer->getTransparency(); @@ -287,17 +287,17 @@ void TestZipLayer::initTestCase() // save data dir QFile::remove( QDir::tempPath() + "/testzip.zip" ); QVERIFY( QFile::copy( QString( TEST_DATA_DIR ) + "/zip/" + "testzip.zip", QDir::tempPath() + "/testzip.zip" ) ); - mDataDir = QString( TEST_DATA_DIR ) + "/zip/"; + mDataDir = QStringLiteral( TEST_DATA_DIR ) + "/zip/"; // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); // save current zipSetting value QSettings settings; - mSettingsKey = "/qgis/scanZipInBrowser2"; + mSettingsKey = QStringLiteral( "/qgis/scanZipInBrowser2" ); mScanZipSetting = settings.value( mSettingsKey, "" ).toString(); - mScanZipSettings << "" << "basic" << "full"; + mScanZipSettings << QLatin1String( "" ) << QStringLiteral( "basic" ) << QStringLiteral( "full" ); } void TestZipLayer::cleanupTestCase() diff --git a/tests/src/gui/testprojectionissues.cpp b/tests/src/gui/testprojectionissues.cpp index f1aa70d8f490..dd76357171c8 100644 --- a/tests/src/gui/testprojectionissues.cpp +++ b/tests/src/gui/testprojectionissues.cpp @@ -53,7 +53,7 @@ void TestProjectionIssues::initTestCase() QgsApplication::initQgis(); //create maplayer from testdata and add to layer registry - QFileInfo rasterFileInfo( QString( TEST_DATA_DIR ) + '/' + "checker360by180.asc" ); + QFileInfo rasterFileInfo( QStringLiteral( TEST_DATA_DIR ) + '/' + "checker360by180.asc" ); mRasterLayer = new QgsRasterLayer( rasterFileInfo.filePath(), rasterFileInfo.completeBaseName() ); // Set to WGS84 diff --git a/tests/src/gui/testqgsattributeform.cpp b/tests/src/gui/testqgsattributeform.cpp index 72e1296d5f7e..eb810812be41 100644 --- a/tests/src/gui/testqgsattributeform.cpp +++ b/tests/src/gui/testqgsattributeform.cpp @@ -65,13 +65,13 @@ void TestQgsAttributeForm::cleanup() void TestQgsAttributeForm::testFieldConstraint() { // make a temporary vector layer - QString def = "Point?field=col0:integer"; - QgsVectorLayer* layer = new QgsVectorLayer( def, "test", "memory" ); - layer->editFormConfig().setWidgetType( "col0", "TextEdit" ); + QString def = QStringLiteral( "Point?field=col0:integer" ); + QgsVectorLayer* layer = new QgsVectorLayer( def, QStringLiteral( "test" ), QStringLiteral( "memory" ) ); + layer->editFormConfig().setWidgetType( QStringLiteral( "col0" ), QStringLiteral( "TextEdit" ) ); // add a feature to the vector layer QgsFeature ft( layer->dataProvider()->fields(), 1 ); - ft.setAttribute( "col0", 0 ); + ft.setAttribute( QStringLiteral( "col0" ), 0 ); // build a form for this feature QgsAttributeForm form( layer ); @@ -79,8 +79,8 @@ void TestQgsAttributeForm::testFieldConstraint() // testing stuff QSignalSpy spy( &form, SIGNAL( attributeChanged( QString, QVariant ) ) ); - QString validLabel = "col0*"; - QString invalidLabel = "col0*"; + QString validLabel = QStringLiteral( "col0*" ); + QString invalidLabel = QStringLiteral( "col0*" ); // set constraint QgsEditFormConfig config = layer->editFormConfig(); @@ -96,7 +96,7 @@ void TestQgsAttributeForm::testFieldConstraint() QCOMPARE( label->text(), QString( "col0" ) ); // set a not null constraint - config.setConstraintExpression( 0, "col0 is not null" ); + config.setConstraintExpression( 0, QStringLiteral( "col0 is not null" ) ); layer->setEditFormConfig( config ); // set value to 1 @@ -120,15 +120,15 @@ void TestQgsAttributeForm::testFieldConstraint() void TestQgsAttributeForm::testFieldMultiConstraints() { // make a temporary layer to check through - QString def = "Point?field=col0:integer&field=col1:integer&field=col2:integer&field=col3:integer"; - QgsVectorLayer* layer = new QgsVectorLayer( def, "test", "memory" ); + QString def = QStringLiteral( "Point?field=col0:integer&field=col1:integer&field=col2:integer&field=col3:integer" ); + QgsVectorLayer* layer = new QgsVectorLayer( def, QStringLiteral( "test" ), QStringLiteral( "memory" ) ); // add features to the vector layer QgsFeature ft( layer->dataProvider()->fields(), 1 ); - ft.setAttribute( "col0", 0 ); - ft.setAttribute( "col1", 1 ); - ft.setAttribute( "col2", 2 ); - ft.setAttribute( "col3", 3 ); + ft.setAttribute( QStringLiteral( "col0" ), 0 ); + ft.setAttribute( QStringLiteral( "col1" ), 1 ); + ft.setAttribute( QStringLiteral( "col2" ), 2 ); + ft.setAttribute( QStringLiteral( "col3" ), 3 ); // set constraints for each field QgsEditFormConfig config = layer->editFormConfig(); @@ -144,8 +144,8 @@ void TestQgsAttributeForm::testFieldMultiConstraints() // testing stuff QSignalSpy spy( &form, SIGNAL( attributeChanged( QString, QVariant ) ) ); - QString val = "*"; - QString inv = "*"; + QString val = QStringLiteral( "*" ); + QString inv = QStringLiteral( "*" ); // get wrappers for each widget QgsEditorWidgetWrapper *ww0, *ww1, *ww2, *ww3; @@ -167,10 +167,10 @@ void TestQgsAttributeForm::testFieldMultiConstraints() QCOMPARE( label3->text(), QString( "col3" ) ); // update constraint - config.setConstraintExpression( 0, "col0 < (col1 * col2)" ); + config.setConstraintExpression( 0, QStringLiteral( "col0 < (col1 * col2)" ) ); config.setConstraintExpression( 1, QString() ); config.setConstraintExpression( 2, QString() ); - config.setConstraintExpression( 3, "col0 = 2" ); + config.setConstraintExpression( 3, QStringLiteral( "col0 = 2" ) ); layer->setEditFormConfig( config ); // change value @@ -196,12 +196,12 @@ void TestQgsAttributeForm::testFieldMultiConstraints() void TestQgsAttributeForm::testOKButtonStatus() { // make a temporary vector layer - QString def = "Point?field=col0:integer"; - QgsVectorLayer* layer = new QgsVectorLayer( def, "test", "memory" ); + QString def = QStringLiteral( "Point?field=col0:integer" ); + QgsVectorLayer* layer = new QgsVectorLayer( def, QStringLiteral( "test" ), QStringLiteral( "memory" ) ); // add a feature to the vector layer QgsFeature ft( layer->dataProvider()->fields(), 1 ); - ft.setAttribute( "col0", 0 ); + ft.setAttribute( QStringLiteral( "col0" ), 0 ); ft.setValid( true ); // set constraint @@ -235,13 +235,13 @@ void TestQgsAttributeForm::testOKButtonStatus() QCOMPARE( okButton->isEnabled(), true ); // invalid constraint and editable layer : OK button disabled - config.setConstraintExpression( 0, "col0 = 0" ); + config.setConstraintExpression( 0, QStringLiteral( "col0 = 0" ) ); layer->setEditFormConfig( config ); ww->setValue( 1 ); QCOMPARE( okButton->isEnabled(), false ); // valid constraint and editable layer : OK button enabled - config.setConstraintExpression( 0, "col0 = 2" ); + config.setConstraintExpression( 0, QStringLiteral( "col0 = 2" ) ); layer->setEditFormConfig( config ); ww->setValue( 2 ); QCOMPARE( okButton->isEnabled(), true ); diff --git a/tests/src/gui/testqgsdoublespinbox.cpp b/tests/src/gui/testqgsdoublespinbox.cpp index 0ce6207d595e..3af7231715c1 100644 --- a/tests/src/gui/testqgsdoublespinbox.cpp +++ b/tests/src/gui/testqgsdoublespinbox.cpp @@ -95,7 +95,7 @@ void TestQgsDoubleSpinBox::expression() QCOMPARE( spinBox->valueFromText( QString( "5/" ) ), 4.0 ); //invalid expression should reset to previous value //suffix tests - spinBox->setSuffix( QString( "mm" ) ); + spinBox->setSuffix( QStringLiteral( "mm" ) ); spinBox->setExpressionsEnabled( false ); QCOMPARE( spinBox->valueFromText( QString( "5mm" ) ), 5.0 ); QCOMPARE( spinBox->valueFromText( QString( "5+2mm" ) ), -10.0 ); @@ -112,7 +112,7 @@ void TestQgsDoubleSpinBox::expression() //prefix tests spinBox->setSuffix( QString() ); - spinBox->setPrefix( QString( "mm" ) ); + spinBox->setPrefix( QStringLiteral( "mm" ) ); spinBox->setExpressionsEnabled( false ); QCOMPARE( spinBox->valueFromText( QString( "mm5" ) ), 5.0 ); QCOMPARE( spinBox->valueFromText( QString( "mm5+2" ) ), -10.0 ); @@ -128,8 +128,8 @@ void TestQgsDoubleSpinBox::expression() QCOMPARE( spinBox->valueFromText( QString( "mm5/" ) ), 4.0 ); //invalid expression should reset to previous value //both suffix and prefix - spinBox->setSuffix( QString( "ll" ) ); - spinBox->setPrefix( QString( "mm" ) ); + spinBox->setSuffix( QStringLiteral( "ll" ) ); + spinBox->setPrefix( QStringLiteral( "mm" ) ); spinBox->setExpressionsEnabled( true ); QCOMPARE( spinBox->valueFromText( QString( "mm 5 ll" ) ), 5.0 ); QCOMPARE( spinBox->valueFromText( QString( "mm 5+2 ll" ) ), 7.0 ); diff --git a/tests/src/gui/testqgsdualview.cpp b/tests/src/gui/testqgsdualview.cpp index 144dc23bcfa5..5c84e09848a0 100644 --- a/tests/src/gui/testqgsdualview.cpp +++ b/tests/src/gui/testqgsdualview.cpp @@ -79,7 +79,7 @@ void TestQgsDualView::initTestCase() QString myPointsFileName = mTestDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); mPointsLayer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); mCanvas = new QgsMapCanvas(); } @@ -146,26 +146,26 @@ void TestQgsDualView::testSelectAll() void TestQgsDualView::testSort() { - mDualView->setSortExpression( "Class" ); + mDualView->setSortExpression( QStringLiteral( "Class" ) ); QStringList classes; - classes << "B52" - << "B52" - << "B52" - << "B52" - << "Biplane" - << "Biplane" - << "Biplane" - << "Biplane" - << "Biplane" - << "Jet" - << "Jet" - << "Jet" - << "Jet" - << "Jet" - << "Jet" - << "Jet" - << "Jet"; + classes << QStringLiteral( "B52" ) + << QStringLiteral( "B52" ) + << QStringLiteral( "B52" ) + << QStringLiteral( "B52" ) + << QStringLiteral( "Biplane" ) + << QStringLiteral( "Biplane" ) + << QStringLiteral( "Biplane" ) + << QStringLiteral( "Biplane" ) + << QStringLiteral( "Biplane" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ) + << QStringLiteral( "Jet" ); for ( int i = 0; i < classes.length(); ++i ) { @@ -174,25 +174,25 @@ void TestQgsDualView::testSort() } QStringList headings; - headings << "0" - << "0" - << "12" - << "34" - << "80" - << "85" - << "90" - << "90" - << "95" - << "100" - << "140" - << "160" - << "180" - << "240" - << "270" - << "300" - << "340"; - - mDualView->setSortExpression( "Heading" ); + headings << QStringLiteral( "0" ) + << QStringLiteral( "0" ) + << QStringLiteral( "12" ) + << QStringLiteral( "34" ) + << QStringLiteral( "80" ) + << QStringLiteral( "85" ) + << QStringLiteral( "90" ) + << QStringLiteral( "90" ) + << QStringLiteral( "95" ) + << QStringLiteral( "100" ) + << QStringLiteral( "140" ) + << QStringLiteral( "160" ) + << QStringLiteral( "180" ) + << QStringLiteral( "240" ) + << QStringLiteral( "270" ) + << QStringLiteral( "300" ) + << QStringLiteral( "340" ); + + mDualView->setSortExpression( QStringLiteral( "Heading" ) ); for ( int i = 0; i < headings.length(); ++i ) { @@ -209,28 +209,28 @@ void TestQgsDualView::testAttributeFormSharedValueScanning() QHash< int, QVariant > fieldSharedValues; // make a temporary layer to check through - QgsVectorLayer* layer = new QgsVectorLayer( "Point?field=col1:integer&field=col2:integer&field=col3:integer&field=col4:integer", "test", "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer&field=col2:integer&field=col3:integer&field=col4:integer" ), QStringLiteral( "test" ), QStringLiteral( "memory" ) ); QVERIFY( layer->isValid() ); QgsFeature f1( layer->dataProvider()->fields(), 1 ); - f1.setAttribute( "col1", 1 ); - f1.setAttribute( "col2", 1 ); - f1.setAttribute( "col3", 3 ); - f1.setAttribute( "col4", 1 ); + f1.setAttribute( QStringLiteral( "col1" ), 1 ); + f1.setAttribute( QStringLiteral( "col2" ), 1 ); + f1.setAttribute( QStringLiteral( "col3" ), 3 ); + f1.setAttribute( QStringLiteral( "col4" ), 1 ); QgsFeature f2( layer->dataProvider()->fields(), 2 ); - f2.setAttribute( "col1", 1 ); - f2.setAttribute( "col2", 2 ); - f2.setAttribute( "col3", 3 ); - f2.setAttribute( "col4", 2 ); + f2.setAttribute( QStringLiteral( "col1" ), 1 ); + f2.setAttribute( QStringLiteral( "col2" ), 2 ); + f2.setAttribute( QStringLiteral( "col3" ), 3 ); + f2.setAttribute( QStringLiteral( "col4" ), 2 ); QgsFeature f3( layer->dataProvider()->fields(), 3 ); - f3.setAttribute( "col1", 1 ); - f3.setAttribute( "col2", 2 ); - f3.setAttribute( "col3", 3 ); - f3.setAttribute( "col4", 2 ); + f3.setAttribute( QStringLiteral( "col1" ), 1 ); + f3.setAttribute( QStringLiteral( "col2" ), 2 ); + f3.setAttribute( QStringLiteral( "col3" ), 3 ); + f3.setAttribute( QStringLiteral( "col4" ), 2 ); QgsFeature f4( layer->dataProvider()->fields(), 4 ); - f4.setAttribute( "col1", 1 ); - f4.setAttribute( "col2", 1 ); - f4.setAttribute( "col3", 3 ); - f4.setAttribute( "col4", 2 ); + f4.setAttribute( QStringLiteral( "col1" ), 1 ); + f4.setAttribute( QStringLiteral( "col2" ), 1 ); + f4.setAttribute( QStringLiteral( "col3" ), 3 ); + f4.setAttribute( QStringLiteral( "col4" ), 2 ); layer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); QgsAttributeForm form( layer ); @@ -245,10 +245,10 @@ void TestQgsDualView::testAttributeFormSharedValueScanning() // add another feature so all attributes are different QgsFeature f5( layer->dataProvider()->fields(), 5 ); - f5.setAttribute( "col1", 11 ); - f5.setAttribute( "col2", 11 ); - f5.setAttribute( "col3", 13 ); - f5.setAttribute( "col4", 12 ); + f5.setAttribute( QStringLiteral( "col1" ), 11 ); + f5.setAttribute( QStringLiteral( "col2" ), 11 ); + f5.setAttribute( QStringLiteral( "col3" ), 13 ); + f5.setAttribute( QStringLiteral( "col4" ), 12 ); layer->dataProvider()->addFeatures( QgsFeatureList() << f5 ); it = layer->getFeatures(); diff --git a/tests/src/gui/testqgseditorwidgetregistry.cpp b/tests/src/gui/testqgseditorwidgetregistry.cpp index afb4dc7402e0..545604beaff0 100644 --- a/tests/src/gui/testqgseditorwidgetregistry.cpp +++ b/tests/src/gui/testqgseditorwidgetregistry.cpp @@ -28,10 +28,10 @@ class TestQgsEditorWidgetRegistry: public QObject QgsEditorWidgetSetup editorWidgetSetup( const QgsVectorLayer* vl, const QString& fieldName, int& score ) const override { Q_UNUSED( vl ) - if ( fieldName == "special" ) + if ( fieldName == QLatin1String( "special" ) ) { score = 100; - return QgsEditorWidgetSetup( "Special", QgsEditorWidgetConfig() ); + return QgsEditorWidgetSetup( QStringLiteral( "Special" ), QgsEditorWidgetConfig() ); } score = 0; return QgsEditorWidgetSetup(); @@ -55,55 +55,55 @@ class TestQgsEditorWidgetRegistry: public QObject void stringType() { - checkSimple( "string", "TextEdit" ); + checkSimple( QStringLiteral( "string" ), QStringLiteral( "TextEdit" ) ); } void datetimeType() { - checkSimple( "datetime", "DateTime" ); + checkSimple( QStringLiteral( "datetime" ), QStringLiteral( "DateTime" ) ); } void integerType() { - checkSimple( "integer", "Range" ); + checkSimple( QStringLiteral( "integer" ), QStringLiteral( "Range" ) ); } void longLongType() { - checkSimple( "int8", "TextEdit" ); // no current widget supports 64 bit integers => default to TextEdit + checkSimple( QStringLiteral( "int8" ), QStringLiteral( "TextEdit" ) ); // no current widget supports 64 bit integers => default to TextEdit } void doubleType() { - checkSimple( "double", "Range" ); + checkSimple( QStringLiteral( "double" ), QStringLiteral( "Range" ) ); } void arrayType() { - checkSimple( "double[]", "List" ); - checkSimple( "int[]", "List" ); - checkSimple( "string[]", "List" ); + checkSimple( QStringLiteral( "double[]" ), QStringLiteral( "List" ) ); + checkSimple( QStringLiteral( "int[]" ), QStringLiteral( "List" ) ); + checkSimple( QStringLiteral( "string[]" ), QStringLiteral( "List" ) ); } void configuredType() { - QgsVectorLayer vl( "LineString?crs=epsg:3111&field=pk:int&field=col1:string", "vl", "memory" ); + QgsVectorLayer vl( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=col1:string" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); QgsEditFormConfig formConfig = vl.editFormConfig(); - formConfig.setWidgetType( "col1", "FooEdit" ); + formConfig.setWidgetType( QStringLiteral( "col1" ), QStringLiteral( "FooEdit" ) ); QgsEditorWidgetConfig config; - config["a"] = QVariant( 12 ); - config["b"] = QVariant( "bar" ); - formConfig.setWidgetConfig( "col1", config ); + config[QStringLiteral( "a" )] = QVariant( 12 ); + config[QStringLiteral( "b" )] = QVariant( "bar" ); + formConfig.setWidgetConfig( QStringLiteral( "col1" ), config ); vl.setEditFormConfig( formConfig ); - const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, "col1" ); + const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, QStringLiteral( "col1" ) ); QCOMPARE( setup.type(), QString( "FooEdit" ) ); QCOMPARE( setup.config(), config ); } void wrongFieldName() { - const QgsVectorLayer vl( "LineString?crs=epsg:3111&field=pk:int&field=col1:string", "vl", "memory" ); - const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, "col2" ); + const QgsVectorLayer vl( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=col1:string" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); + const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, QStringLiteral( "col2" ) ); // an unknown fields leads to a default setup with a TextEdit QCOMPARE( setup.type(), QString( "TextEdit" ) ); QCOMPARE( setup.config().count(), 0 ); @@ -111,8 +111,8 @@ class TestQgsEditorWidgetRegistry: public QObject void typeFromPlugin() { - const QgsVectorLayer vl( "LineString?crs=epsg:3111&field=pk:int&field=special:string", "vl", "memory" ); - const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, "special" ); + const QgsVectorLayer vl( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=special:string" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); + const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, QStringLiteral( "special" ) ); QCOMPARE( setup.type(), QString( "Special" ) ); } @@ -120,8 +120,8 @@ class TestQgsEditorWidgetRegistry: public QObject static void checkSimple( const QString& dataType, const QString& widgetType ) { - const QgsVectorLayer vl( "LineString?crs=epsg:3111&field=pk:int&field=col1:" + dataType, "vl", "memory" ); - const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, "col1" ); + const QgsVectorLayer vl( "LineString?crs=epsg:3111&field=pk:int&field=col1:" + dataType, QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); + const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl, QStringLiteral( "col1" ) ); QCOMPARE( setup.type(), widgetType ); QCOMPARE( setup.config().count(), 0 ); } diff --git a/tests/src/gui/testqgsfieldexpressionwidget.cpp b/tests/src/gui/testqgsfieldexpressionwidget.cpp index 7868f9c2aefb..97c87e9d2080 100644 --- a/tests/src/gui/testqgsfieldexpressionwidget.cpp +++ b/tests/src/gui/testqgsfieldexpressionwidget.cpp @@ -65,18 +65,18 @@ void TestQgsFieldExpressionWidget::initTestCase() QgsApplication::initQgis(); // Set up the QSettings environment - QCoreApplication::setOrganizationName( "QGIS" ); - QCoreApplication::setOrganizationDomain( "qgis.org" ); - QCoreApplication::setApplicationName( "QGIS-TEST" ); + QCoreApplication::setOrganizationName( QStringLiteral( "QGIS" ) ); + QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); + QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); // Create memory layers // LAYER A // - mLayerA = new QgsVectorLayer( "Point?field=id_a:integer", "A", "memory" ); + mLayerA = new QgsVectorLayer( QStringLiteral( "Point?field=id_a:integer" ), QStringLiteral( "A" ), QStringLiteral( "memory" ) ); QVERIFY( mLayerA->isValid() ); QVERIFY( mLayerA->fields().count() == 1 ); QgsMapLayerRegistry::instance()->addMapLayer( mLayerA ); // LAYER B // - mLayerB = new QgsVectorLayer( "Point?field=id_b:integer&field=value_b", "B", "memory" ); + mLayerB = new QgsVectorLayer( QStringLiteral( "Point?field=id_b:integer&field=value_b" ), QStringLiteral( "B" ), QStringLiteral( "memory" ) ); QVERIFY( mLayerB->isValid() ); QVERIFY( mLayerB->fields().count() == 2 ); QgsMapLayerRegistry::instance()->addMapLayer( mLayerB ); @@ -107,16 +107,16 @@ void TestQgsFieldExpressionWidget::testRemoveJoin() QVERIFY( mLayerA->fields().count() == 1 ); QgsVectorJoinInfo joinInfo; - joinInfo.targetFieldName = "id_a"; + joinInfo.targetFieldName = QStringLiteral( "id_a" ); joinInfo.joinLayerId = mLayerB->id(); - joinInfo.joinFieldName = "id_b"; + joinInfo.joinFieldName = QStringLiteral( "id_b" ); joinInfo.memoryCache = false; - joinInfo.prefix = "B_"; + joinInfo.prefix = QStringLiteral( "B_" ); mLayerA->addJoin( joinInfo ); QVERIFY( mLayerA->fields().count() == 2 ); - const QString expr = "'hello '|| B_value_b"; + const QString expr = QStringLiteral( "'hello '|| B_value_b" ); mWidget->setField( expr ); bool isExpression, isValid; @@ -138,26 +138,26 @@ void TestQgsFieldExpressionWidget::testRemoveJoin() void TestQgsFieldExpressionWidget::asExpression() { - QgsVectorLayer* layer = new QgsVectorLayer( "point?field=fld:int&field=fld2:int&field=fld3:int", "x", "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "point?field=fld:int&field=fld2:int&field=fld3:int" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( layer ); QScopedPointer< QgsFieldExpressionWidget > widget( new QgsFieldExpressionWidget() ); widget->setLayer( layer ); // check with field set - widget->setField( "fld" ); + widget->setField( QStringLiteral( "fld" ) ); QCOMPARE( widget->asExpression(), QString( "\"fld\"" ) ); // check with expressions set - widget->setField( "fld + 1" ); + widget->setField( QStringLiteral( "fld + 1" ) ); QCOMPARE( widget->asExpression(), QString( "fld + 1" ) ); - widget->setField( "1" ); + widget->setField( QStringLiteral( "1" ) ); QCOMPARE( widget->asExpression(), QString( "1" ) ); - widget->setField( "\"fld2\"" ); + widget->setField( QStringLiteral( "\"fld2\"" ) ); QCOMPARE( widget->asExpression(), QString( "\"fld2\"" ) ); // check switching back to a field - widget->setField( "fld3" ); + widget->setField( QStringLiteral( "fld3" ) ); QCOMPARE( widget->asExpression(), QString( "\"fld3\"" ) ); QgsMapLayerRegistry::instance()->removeMapLayer( layer ); @@ -165,7 +165,7 @@ void TestQgsFieldExpressionWidget::asExpression() void TestQgsFieldExpressionWidget::testIsValid() { - QgsVectorLayer* layer = new QgsVectorLayer( "point?field=fld:int&field=name%20with%20space:string", "x", "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "point?field=fld:int&field=name%20with%20space:string" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( layer ); QScopedPointer< QgsFieldExpressionWidget > widget( new QgsFieldExpressionWidget() ); @@ -177,7 +177,7 @@ void TestQgsFieldExpressionWidget::testIsValid() // check with simple field name set bool isExpression = false; bool isValid = false; - widget->setField( "fld" ); + widget->setField( QStringLiteral( "fld" ) ); QCOMPARE( widget->currentField( &isExpression, &isValid ), QString( "fld" ) ); QVERIFY( !isExpression ); QVERIFY( isValid ); @@ -188,7 +188,7 @@ void TestQgsFieldExpressionWidget::testIsValid() //check with complex field name set - widget->setField( "name with space" ); + widget->setField( QStringLiteral( "name with space" ) ); QCOMPARE( widget->currentField( &isExpression, &isValid ), QString( "name with space" ) ); QVERIFY( !isExpression ); QVERIFY( isValid ); @@ -198,7 +198,7 @@ void TestQgsFieldExpressionWidget::testIsValid() QVERIFY( spy.last().at( 1 ).toBool() ); //check with valid expression set - widget->setField( "2 * 4" ); + widget->setField( QStringLiteral( "2 * 4" ) ); QCOMPARE( widget->currentField( &isExpression, &isValid ), QString( "2 * 4" ) ); QVERIFY( isExpression ); QVERIFY( isValid ); @@ -208,7 +208,7 @@ void TestQgsFieldExpressionWidget::testIsValid() QVERIFY( spy.last().at( 1 ).toBool() ); //check with invalid expression set - widget->setField( "2 *" ); + widget->setField( QStringLiteral( "2 *" ) ); QCOMPARE( widget->currentField( &isExpression, &isValid ), QString( "2 *" ) ); QVERIFY( isExpression ); QVERIFY( !isValid ); @@ -222,7 +222,7 @@ void TestQgsFieldExpressionWidget::testIsValid() void TestQgsFieldExpressionWidget::testFilters() { - QgsVectorLayer* layer = new QgsVectorLayer( "point?field=intfld:int&field=stringfld:string&field=string2fld:string&field=longfld:long&field=doublefld:double&field=datefld:date&field=timefld:time&field=datetimefld:datetime", "x", "memory" ); + QgsVectorLayer* layer = new QgsVectorLayer( QStringLiteral( "point?field=intfld:int&field=stringfld:string&field=string2fld:string&field=longfld:long&field=doublefld:double&field=datefld:date&field=timefld:time&field=datetimefld:datetime" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); QgsMapLayerRegistry::instance()->addMapLayer( layer ); QScopedPointer< QgsFieldExpressionWidget > widget( new QgsFieldExpressionWidget() ); diff --git a/tests/src/gui/testqgsfilewidget.cpp b/tests/src/gui/testqgsfilewidget.cpp index 18358c293760..69af72b62e08 100644 --- a/tests/src/gui/testqgsfilewidget.cpp +++ b/tests/src/gui/testqgsfilewidget.cpp @@ -52,7 +52,7 @@ void TestQgsFileWidget::cleanup() void TestQgsFileWidget::relativePath() { QgsFileWidget* w = new QgsFileWidget(); - w->setDefaultRoot( "/home/test" ); + w->setDefaultRoot( QStringLiteral( "/home/test" ) ); w->setRelativeStorage( QgsFileWidget::Absolute ); QCOMPARE( w->relativePath( "/home/test2/file1.ext", true ), QString( "/home/test2/file1.ext" ) ); QCOMPARE( w->relativePath( "/home/test2/file2.ext", false ), QString( "/home/test2/file2.ext" ) ); @@ -66,7 +66,7 @@ void TestQgsFileWidget::relativePath() void TestQgsFileWidget::toUrl() { QgsFileWidget* w = new QgsFileWidget(); - w->setDefaultRoot( "/home/test" ); + w->setDefaultRoot( QStringLiteral( "/home/test" ) ); w->setRelativeStorage( QgsFileWidget::Absolute ); w->setFullUrl( true ); QCOMPARE( w->toUrl( "/home/test2/file1.ext" ), QString( "/home/test2/file1.ext" ) ); diff --git a/tests/src/gui/testqgsgui.cpp b/tests/src/gui/testqgsgui.cpp index 1fafad3d7c32..26521b2cdb9f 100644 --- a/tests/src/gui/testqgsgui.cpp +++ b/tests/src/gui/testqgsgui.cpp @@ -27,16 +27,16 @@ class TestQgsGui : public QObject void TestQgsGui::createFileFilterForFormat() { - QString expected = "FOO format (*.foo *.FOO)"; - QString actual = QgisGui::createFileFilter_( "foo" ); + QString expected = QStringLiteral( "FOO format (*.foo *.FOO)" ); + QString actual = QgisGui::createFileFilter_( QStringLiteral( "foo" ) ); QCOMPARE( actual, expected ); } void TestQgsGui::createFileFilter() { - QString expected = "My Description (my_regex MY_REGEX)"; - QString actual = QgisGui::createFileFilter_( "My Description", "my_regex" ); + QString expected = QStringLiteral( "My Description (my_regex MY_REGEX)" ); + QString actual = QgisGui::createFileFilter_( QStringLiteral( "My Description" ), QStringLiteral( "my_regex" ) ); QCOMPARE( actual, expected ); } diff --git a/tests/src/gui/testqgskeyvaluewidget.cpp b/tests/src/gui/testqgskeyvaluewidget.cpp index edaa0784403a..8483f14ce53a 100644 --- a/tests/src/gui/testqgskeyvaluewidget.cpp +++ b/tests/src/gui/testqgskeyvaluewidget.cpp @@ -40,7 +40,7 @@ class TestQgsKeyValueWidget : public QObject void testUpdate() { - const QgsKeyValueWidgetFactory factory( "testKeyValue" ); + const QgsKeyValueWidgetFactory factory( QStringLiteral( "testKeyValue" ) ); QgsEditorWidgetWrapper* wrapper = factory.create( nullptr, 0, nullptr, nullptr ); QVERIFY( wrapper ); QSignalSpy spy( wrapper, SIGNAL( valueChanged( const QVariant& ) ) ); @@ -49,8 +49,8 @@ class TestQgsKeyValueWidget : public QObject QVERIFY( widget ); QVariantMap initial; - initial["1"] = "one"; - initial["2"] = "two"; + initial[QStringLiteral( "1" )] = "one"; + initial[QStringLiteral( "2" )] = "two"; wrapper->setValue( initial ); const QVariant value = wrapper->value(); @@ -63,7 +63,7 @@ class TestQgsKeyValueWidget : public QObject QCOMPARE( spy.count(), 1 ); QVariantMap expected = initial; - expected["1"] = "hello"; + expected[QStringLiteral( "1" )] = "hello"; QVariant eventValue = spy.at( 0 ).at( 0 ).value(); QCOMPARE( int( eventValue.type() ), int( QVariant::Map ) ); QCOMPARE( eventValue.toMap(), expected ); diff --git a/tests/src/gui/testqgslistwidget.cpp b/tests/src/gui/testqgslistwidget.cpp index 83ebfdcaa991..394157dd9da1 100644 --- a/tests/src/gui/testqgslistwidget.cpp +++ b/tests/src/gui/testqgslistwidget.cpp @@ -38,8 +38,8 @@ class TestQgsListWidget : public QObject void testStringUpdate() { - const QgsListWidgetFactory factory( "testList" ); - QgsVectorLayer vl( "Point?field=fld:string[]", "test", "memory" ); + const QgsListWidgetFactory factory( QStringLiteral( "testList" ) ); + QgsVectorLayer vl( QStringLiteral( "Point?field=fld:string[]" ), QStringLiteral( "test" ), QStringLiteral( "memory" ) ); QgsEditorWidgetWrapper* wrapper = factory.create( &vl, 0, nullptr, nullptr ); QVERIFY( wrapper ); QSignalSpy spy( wrapper, SIGNAL( valueChanged( const QVariant& ) ) ); @@ -48,7 +48,7 @@ class TestQgsListWidget : public QObject QVERIFY( widget ); QStringList initial; - initial << "one" << "two"; + initial << QStringLiteral( "one" ) << QStringLiteral( "two" ); wrapper->setValue( initial ); const QVariant value = wrapper->value(); @@ -62,7 +62,7 @@ class TestQgsListWidget : public QObject QVERIFY( widget->valid() ); QStringList expected = initial; - expected[0] = "hello"; + expected[0] = QStringLiteral( "hello" ); QVariant eventValue = spy.at( 0 ).at( 0 ).value(); QCOMPARE( int( eventValue.type() ), int( QVariant::StringList ) ); QCOMPARE( eventValue.toStringList(), expected ); @@ -73,8 +73,8 @@ class TestQgsListWidget : public QObject void testIntUpdate() { - const QgsListWidgetFactory factory( "testList" ); - QgsVectorLayer vl( "Point?field=fld:int[]", "test", "memory" ); + const QgsListWidgetFactory factory( QStringLiteral( "testList" ) ); + QgsVectorLayer vl( QStringLiteral( "Point?field=fld:int[]" ), QStringLiteral( "test" ), QStringLiteral( "memory" ) ); QgsEditorWidgetWrapper* wrapper = factory.create( &vl, 0, nullptr, nullptr ); QVERIFY( wrapper ); QSignalSpy spy( wrapper, SIGNAL( valueChanged( const QVariant& ) ) ); diff --git a/tests/src/gui/testqgsmapcanvas.cpp b/tests/src/gui/testqgsmapcanvas.cpp index fd0116503ffa..4dc2f6fe1c56 100644 --- a/tests/src/gui/testqgsmapcanvas.cpp +++ b/tests/src/gui/testqgsmapcanvas.cpp @@ -111,12 +111,12 @@ void TestQgsMapCanvas::testPanByKeyboard() void TestQgsMapCanvas::testMagnification() { // test directory - QString testDataDir = QString( TEST_DATA_DIR ) + '/'; + QString testDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; QString controlImageDir = testDataDir + "control_images/expected_map_magnification/"; // prepare spy and unit testing stuff QgsRenderChecker checker; - checker.setControlPathPrefix( "mapcanvas" ); + checker.setControlPathPrefix( QStringLiteral( "mapcanvas" ) ); checker.setColorTolerance( 5 ); QSignalSpy spy( mCanvas, SIGNAL( mapCanvasRefreshed() ) ); @@ -137,7 +137,7 @@ void TestQgsMapCanvas::testMagnification() QString myPointsFileName = testDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); QgsVectorLayer *layer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // prepare map canvas QList layers; @@ -157,7 +157,7 @@ void TestQgsMapCanvas::testMagnification() // control image with magnification factor 1.0 mCanvas->saveAsImage( tmpName ); - checker.setControlName( "expected_map_magnification" ); + checker.setControlName( QStringLiteral( "expected_map_magnification" ) ); checker.setRenderedImage( tmpName ); checker.setSizeTolerance( 10, 10 ); QCOMPARE( checker.compareImages( "map_magnification", 100 ), true ); @@ -176,7 +176,7 @@ void TestQgsMapCanvas::testMagnification() mCanvas->saveAsImage( tmpName ); checker.setRenderedImage( tmpName ); - checker.setControlName( "expected_map_magnification_6_5" ); + checker.setControlName( QStringLiteral( "expected_map_magnification_6_5" ) ); controlImageDir = testDataDir + "control_images/"; checker.setSizeTolerance( 10, 10 ); QCOMPARE( checker.compareImages( "map_magnification_6_5", 100 ), true ); @@ -194,7 +194,7 @@ void TestQgsMapCanvas::testMagnification() // control image with magnification factor 1.0 mCanvas->saveAsImage( tmpName ); - checker.setControlName( "expected_map_magnification" ); + checker.setControlName( QStringLiteral( "expected_map_magnification" ) ); checker.setRenderedImage( tmpName ); checker.setSizeTolerance( 10, 10 ); QCOMPARE( checker.compareImages( "map_magnification", 100 ), true ); @@ -212,11 +212,11 @@ void compareExtent( const QgsRectangle &initialExtent, void TestQgsMapCanvas::testMagnificationExtent() { // build vector layer - QString testDataDir = QString( TEST_DATA_DIR ) + '/'; + QString testDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; QString myPointsFileName = testDataDir + "points.shp"; QFileInfo myPointFileInfo( myPointsFileName ); QgsVectorLayer *layer = new QgsVectorLayer( myPointFileInfo.filePath(), - myPointFileInfo.completeBaseName(), "ogr" ); + myPointFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); // prepare map canvas QList layers; diff --git a/tests/src/gui/testqgsrubberband.cpp b/tests/src/gui/testqgsrubberband.cpp index 5db9aac70fb6..b8acbd1b3050 100644 --- a/tests/src/gui/testqgsrubberband.cpp +++ b/tests/src/gui/testqgsrubberband.cpp @@ -71,7 +71,7 @@ void TestQgsRubberband::initTestCase() QString myPolygonFileName = mTestDataDir + "polys.shp"; QFileInfo myPolygonFileInfo( myPolygonFileName ); mPolygonLayer = new QgsVectorLayer( myPolygonFileInfo.filePath(), - myPolygonFileInfo.completeBaseName(), "ogr" ); + myPolygonFileInfo.completeBaseName(), QStringLiteral( "ogr" ) ); mCanvas = new QgsMapCanvas(); mRubberband = 0; @@ -99,8 +99,8 @@ void TestQgsRubberband::cleanup() void TestQgsRubberband::testAddSingleMultiGeometries() { mRubberband = new QgsRubberBand( mCanvas, mPolygonLayer->geometryType() ); - QgsGeometry geomSinglePart( QgsGeometry::fromWkt( "POLYGON((-0.00022418 -0.00000279,-0.0001039 0.00002395,-0.00008677 -0.00005313,-0.00020705 -0.00007987,-0.00022418 -0.00000279))" ) ); - QgsGeometry geomMultiPart( QgsGeometry::fromWkt( "MULTIPOLYGON(((-0.00018203 0.00012178,-0.00009444 0.00014125,-0.00007861 0.00007001,-0.00016619 0.00005054,-0.00018203 0.00012178)),((-0.00030957 0.00009464,-0.00021849 0.00011489,-0.00020447 0.00005184,-0.00029555 0.00003158,-0.00030957 0.00009464)))" ) ); + QgsGeometry geomSinglePart( QgsGeometry::fromWkt( QStringLiteral( "POLYGON((-0.00022418 -0.00000279,-0.0001039 0.00002395,-0.00008677 -0.00005313,-0.00020705 -0.00007987,-0.00022418 -0.00000279))" ) ) ); + QgsGeometry geomMultiPart( QgsGeometry::fromWkt( QStringLiteral( "MULTIPOLYGON(((-0.00018203 0.00012178,-0.00009444 0.00014125,-0.00007861 0.00007001,-0.00016619 0.00005054,-0.00018203 0.00012178)),((-0.00030957 0.00009464,-0.00021849 0.00011489,-0.00020447 0.00005184,-0.00029555 0.00003158,-0.00030957 0.00009464)))" ) ) ); mCanvas->setExtent( QgsRectangle( -1e-3, -1e-3, 1e-3, 1e-3 ) ); // otherwise point cannot be converted to canvas coord @@ -123,7 +123,7 @@ void TestQgsRubberband::testBoundingRect() // Polygon extent is 10,10 to 30,30 QgsGeometry geom( QgsGeometry::fromWkt( - "POLYGON((10 10,10 30,30 30,30 10,10 10))" + QStringLiteral( "POLYGON((10 10,10 30,30 30,30 10,10 10))" ) ) ); mRubberband = new QgsRubberBand( mCanvas, mPolygonLayer->geometryType() ); mRubberband->setIconSize( 5 ); // default, but better be explicit @@ -173,7 +173,7 @@ void TestQgsRubberband::testVisibility() // Check visibility after setting to valid geometry QgsGeometry geom( QgsGeometry::fromWkt( - "POLYGON((10 10,10 30,30 30,30 10,10 10))" + QStringLiteral( "POLYGON((10 10,10 30,30 30,30 10,10 10))" ) ) ); mRubberband->setToGeometry( geom, mPolygonLayer ); QCOMPARE( mRubberband->isVisible(), true ); diff --git a/tests/src/gui/testqgsscalecombobox.cpp b/tests/src/gui/testqgsscalecombobox.cpp index 98d65e0ebfb4..1028b6fff4e1 100644 --- a/tests/src/gui/testqgsscalecombobox.cpp +++ b/tests/src/gui/testqgsscalecombobox.cpp @@ -68,7 +68,7 @@ void TestQgsScaleComboBox::init() void TestQgsScaleComboBox::basic() { // Testing conversion from "1:nnn". - enterScale( "1:2345" ); + enterScale( QStringLiteral( "1:2345" ) ); QCOMPARE( s->scaleString(), QString( "1:%1" ).arg( QLocale::system().toString( 2345 ) ) ); QCOMPARE( s->scale(), 1.0 / 2345.0 ); @@ -83,15 +83,15 @@ void TestQgsScaleComboBox::basic() QCOMPARE( s->scale(), 1.0 / 42.0 ); // Testing conversion from number to "1:x,000" - QString str = QString( "1%01000%01000" ).arg( QLocale::system().groupSeparator() ); + QString str = QStringLiteral( "1%01000%01000" ).arg( QLocale::system().groupSeparator() ); enterScale( str ); QCOMPARE( s->scaleString(), QString( "1:%1" ).arg( str ) ); QCOMPARE( s->scale(), 1.0 / 1000000.0 ); // Testing conversion from number to "1:x,000" with wonky separators //(eg four digits between thousands, which should be fixed automatically) - str = QString( "1%010000%01000" ).arg( QLocale::system().groupSeparator() ); - QString fixedStr = QString( "10%01000%01000" ).arg( QLocale::system().groupSeparator() ); + str = QStringLiteral( "1%010000%01000" ).arg( QLocale::system().groupSeparator() ); + QString fixedStr = QStringLiteral( "10%01000%01000" ).arg( QLocale::system().groupSeparator() ); enterScale( str ); QCOMPARE( s->scaleString(), QString( "1:%1" ).arg( fixedStr ) ); QCOMPARE( s->scale(), 1.0 / 10000000.0 ); @@ -100,7 +100,7 @@ void TestQgsScaleComboBox::basic() enterScale( 0.24 ); - enterScale( "1:x:2" ); + enterScale( QStringLiteral( "1:x:2" ) ); QCOMPARE( s->scaleString(), QString( "1:%1" ).arg( QLocale::system().toString( 4 ) ) ); QCOMPARE( s->scale(), 0.25 ); @@ -110,12 +110,12 @@ void TestQgsScaleComboBox::basic() QCOMPARE( s->scale(), 0.2 ); // Test setting programatically - s->setScaleString( QString( "1:240" ) ); + s->setScaleString( QStringLiteral( "1:240" ) ); QCOMPARE( s->scaleString(), QString( "1:%1" ).arg( QLocale::system().toString( 240 ) ) ); QCOMPARE( s->scale(), 1.0 / 240.0 ); // Test setting programatically illegal string - s->setScaleString( QString( "1:2" ) + QLocale::system().decimalPoint() + "4" ); + s->setScaleString( QStringLiteral( "1:2" ) + QLocale::system().decimalPoint() + "4" ); QCOMPARE( s->scaleString(), QString( "1:%1" ).arg( QLocale::system().toString( 240 ) ) ); QCOMPARE( s->scale(), 1.0 / 240.0 ); @@ -153,7 +153,7 @@ void TestQgsScaleComboBox::min_test() void TestQgsScaleComboBox::enterScale( const QString& scale ) { QLineEdit *l = s->lineEdit(); - l->setText( "" ); + l->setText( QLatin1String( "" ) ); QTest::keyClicks( l, scale ); QTest::keyClick( l, Qt::Key_Return ); } diff --git a/tests/src/gui/testqgsspinbox.cpp b/tests/src/gui/testqgsspinbox.cpp index 6c021ee128e7..ce8497f262d3 100644 --- a/tests/src/gui/testqgsspinbox.cpp +++ b/tests/src/gui/testqgsspinbox.cpp @@ -95,7 +95,7 @@ void TestQgsSpinBox::expression() QCOMPARE( spinBox->valueFromText( QString( "5/" ) ), 4 ); //invalid expression should reset to previous value //suffix tests - spinBox->setSuffix( QString( "mm" ) ); + spinBox->setSuffix( QStringLiteral( "mm" ) ); spinBox->setExpressionsEnabled( false ); QCOMPARE( spinBox->valueFromText( QString( "5mm" ) ), 5 ); QCOMPARE( spinBox->valueFromText( QString( "5+2mm" ) ), -10 ); @@ -112,7 +112,7 @@ void TestQgsSpinBox::expression() //prefix tests spinBox->setSuffix( QString() ); - spinBox->setPrefix( QString( "mm" ) ); + spinBox->setPrefix( QStringLiteral( "mm" ) ); spinBox->setExpressionsEnabled( false ); QCOMPARE( spinBox->valueFromText( QString( "mm5" ) ), 5 ); QCOMPARE( spinBox->valueFromText( QString( "mm5+2" ) ), -10 ); @@ -128,8 +128,8 @@ void TestQgsSpinBox::expression() QCOMPARE( spinBox->valueFromText( QString( "mm5/" ) ), 4 ); //invalid expression should reset to previous value //both suffix and prefix - spinBox->setSuffix( QString( "ll" ) ); - spinBox->setPrefix( QString( "mm" ) ); + spinBox->setSuffix( QStringLiteral( "ll" ) ); + spinBox->setPrefix( QStringLiteral( "mm" ) ); spinBox->setExpressionsEnabled( true ); QCOMPARE( spinBox->valueFromText( QString( "mm 5 ll" ) ), 5 ); QCOMPARE( spinBox->valueFromText( QString( "mm 5+2 ll" ) ), 7 ); diff --git a/tests/src/gui/testqgssqlcomposerdialog.cpp b/tests/src/gui/testqgssqlcomposerdialog.cpp index bd1a9264f9d1..ee296be3e528 100644 --- a/tests/src/gui/testqgssqlcomposerdialog.cpp +++ b/tests/src/gui/testqgssqlcomposerdialog.cpp @@ -49,77 +49,77 @@ bool TestQgsSQLComposerDialog::runTest() static QWidget* getQueryEdit( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mQueryEdit" ); + QWidget* widget = d.findChild( QStringLiteral( "mQueryEdit" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getColumnsEditor( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mColumnsEditor" ); + QWidget* widget = d.findChild( QStringLiteral( "mColumnsEditor" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getTablesEditor( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mTablesEditor" ); + QWidget* widget = d.findChild( QStringLiteral( "mTablesEditor" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getWhereEditor( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mWhereEditor" ); + QWidget* widget = d.findChild( QStringLiteral( "mWhereEditor" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getOrderEditor( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mOrderEditor" ); + QWidget* widget = d.findChild( QStringLiteral( "mOrderEditor" ) ); Q_ASSERT( widget ); return widget; } static QComboBox* getTablesCombo( QgsSQLComposerDialog& d ) { - QComboBox* widget = d.findChild( "mTablesCombo" ); + QComboBox* widget = d.findChild( QStringLiteral( "mTablesCombo" ) ); Q_ASSERT( widget ); return widget; } static QComboBox* getColumnsCombo( QgsSQLComposerDialog& d ) { - QComboBox* widget = d.findChild( "mColumnsCombo" ); + QComboBox* widget = d.findChild( QStringLiteral( "mColumnsCombo" ) ); Q_ASSERT( widget ); return widget; } static QComboBox* getFunctionsCombo( QgsSQLComposerDialog& d ) { - QComboBox* widget = d.findChild( "mFunctionsCombo" ); + QComboBox* widget = d.findChild( QStringLiteral( "mFunctionsCombo" ) ); Q_ASSERT( widget ); return widget; } static QComboBox* getSpatialPredicatesCombo( QgsSQLComposerDialog& d ) { - QComboBox* widget = d.findChild( "mSpatialPredicatesCombo" ); + QComboBox* widget = d.findChild( QStringLiteral( "mSpatialPredicatesCombo" ) ); Q_ASSERT( widget ); return widget; } static QComboBox* getOperatorsCombo( QgsSQLComposerDialog& d ) { - QComboBox* widget = d.findChild( "mOperatorsCombo" ); + QComboBox* widget = d.findChild( QStringLiteral( "mOperatorsCombo" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getResetButton( QgsSQLComposerDialog& d ) { - QDialogButtonBox* mButtonBox = d.findChild( "mButtonBox" ); + QDialogButtonBox* mButtonBox = d.findChild( QStringLiteral( "mButtonBox" ) ); Q_ASSERT( mButtonBox ); QPushButton* button = mButtonBox->button( QDialogButtonBox::Reset ); Q_ASSERT( button ); @@ -128,21 +128,21 @@ static QWidget* getResetButton( QgsSQLComposerDialog& d ) static QTableWidget* getTableJoins( QgsSQLComposerDialog& d ) { - QTableWidget* widget = d.findChild( "mTableJoins" ); + QTableWidget* widget = d.findChild( QStringLiteral( "mTableJoins" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getAddJoinButton( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mAddJoinButton" ); + QWidget* widget = d.findChild( QStringLiteral( "mAddJoinButton" ) ); Q_ASSERT( widget ); return widget; } static QWidget* getRemoveJoinButton( QgsSQLComposerDialog& d ) { - QWidget* widget = d.findChild( "mRemoveJoinButton" ); + QWidget* widget = d.findChild( QStringLiteral( "mRemoveJoinButton" ) ); Q_ASSERT( widget ); return widget; } @@ -161,18 +161,18 @@ void TestQgsSQLComposerDialog::testReciprocalEditorsUpdate() if ( !runTest() ) return; QgsSQLComposerDialog d; - QString oriSql( "SELECT a_column FROM my_table JOIN join_table ON cond WHERE where_expr ORDER BY column DESC" ); + QString oriSql( QStringLiteral( "SELECT a_column FROM my_table JOIN join_table ON cond WHERE where_expr ORDER BY column DESC" ) ); d.setSql( oriSql ); QCOMPARE( d.sql(), oriSql ); gotoEndOfLine( getColumnsEditor( d ) ); - QTest::keyClicks( getColumnsEditor( d ), ", another_column" ); + QTest::keyClicks( getColumnsEditor( d ), QStringLiteral( ", another_column" ) ); gotoEndOfLine( getTablesEditor( d ) ); - QTest::keyClicks( getTablesEditor( d ), ", another_from_table" ); + QTest::keyClicks( getTablesEditor( d ), QStringLiteral( ", another_from_table" ) ); gotoEndOfLine( getWhereEditor( d ) ); - QTest::keyClicks( getWhereEditor( d ), " AND another_cond" ); + QTest::keyClicks( getWhereEditor( d ), QStringLiteral( " AND another_cond" ) ); gotoEndOfLine( getOrderEditor( d ) ); - QTest::keyClicks( getOrderEditor( d ), ", another_column_asc" ); + QTest::keyClicks( getOrderEditor( d ), QStringLiteral( ", another_column_asc" ) ); QCOMPARE( d.sql(), QString( "SELECT a_column, another_column FROM my_table, another_from_table JOIN join_table ON cond WHERE where_expr AND another_cond ORDER BY column DESC, another_column_asc" ) ); QTest::mouseClick( getResetButton( d ), Qt::LeftButton ); @@ -190,13 +190,13 @@ void TestQgsSQLComposerDialog::testSelectTable() if ( !runTest() ) return; QgsSQLComposerDialog d; - d.addTableNames( QStringList() << "my_table" ); - d.addTableNames( QList() << QgsSQLComposerDialog::PairNameTitle( "another_table", "title" ) ); + d.addTableNames( QStringList() << QStringLiteral( "my_table" ) ); + d.addTableNames( QList() << QgsSQLComposerDialog::PairNameTitle( QStringLiteral( "another_table" ), QStringLiteral( "title" ) ) ); QCOMPARE( getTablesCombo( d )->itemText( 1 ), QString( "my_table" ) ); QCOMPARE( getTablesCombo( d )->itemText( 2 ), QString( "another_table (title)" ) ); - d.setSql( "SELECT * FROM " ); + d.setSql( QStringLiteral( "SELECT * FROM " ) ); gotoEndOfLine( getQueryEdit( d ) ); // Set focus in SQL zone @@ -225,13 +225,13 @@ void TestQgsSQLComposerDialog::testSelectColumn() return; QgsSQLComposerDialog d; d.addColumnNames( QList() << - QgsSQLComposerDialog::PairNameType( "a", "" ) << - QgsSQLComposerDialog::PairNameType( "b", "type" ), "my_table" ); + QgsSQLComposerDialog::PairNameType( QStringLiteral( "a" ), QLatin1String( "" ) ) << + QgsSQLComposerDialog::PairNameType( QStringLiteral( "b" ), QStringLiteral( "type" ) ), QStringLiteral( "my_table" ) ); QCOMPARE( getColumnsCombo( d )->itemText( 1 ), QString( "a" ) ); QCOMPARE( getColumnsCombo( d )->itemText( 2 ), QString( "b (type)" ) ); - d.setSql( "SELECT " ); + d.setSql( QStringLiteral( "SELECT " ) ); gotoEndOfLine( getQueryEdit( d ) ); // Set focus in SQL zone @@ -246,7 +246,7 @@ void TestQgsSQLComposerDialog::testSelectColumn() QCOMPARE( d.sql(), QString( "SELECT a" ) ); gotoEndOfLine( getQueryEdit( d ) ); - QTest::keyClicks( getQueryEdit( d ), " FROM my_table" ); + QTest::keyClicks( getQueryEdit( d ), QStringLiteral( " FROM my_table" ) ); QCOMPARE( d.sql(), QString( "SELECT a FROM my_table" ) ); @@ -281,49 +281,49 @@ void TestQgsSQLComposerDialog::testSelectFunction() QList functions; { QgsSQLComposerDialog::Function f; - f.name = "first_func"; + f.name = QStringLiteral( "first_func" ); functions << f; } { QgsSQLComposerDialog::Function f; - f.name = "second_func"; - f.returnType = "xs:int"; + f.name = QStringLiteral( "second_func" ); + f.returnType = QStringLiteral( "xs:int" ); functions << f; } { QgsSQLComposerDialog::Function f; - f.name = "third_func"; + f.name = QStringLiteral( "third_func" ); f.minArgs = 1; f.maxArgs = 1; functions << f; } { QgsSQLComposerDialog::Function f; - f.name = "fourth_func"; + f.name = QStringLiteral( "fourth_func" ); f.minArgs = 1; f.maxArgs = 2; functions << f; } { QgsSQLComposerDialog::Function f; - f.name = "fifth_func"; + f.name = QStringLiteral( "fifth_func" ); f.minArgs = 1; functions << f; } { QgsSQLComposerDialog::Function f; - f.name = "sixth_func"; - f.argumentList << QgsSQLComposerDialog::Argument( "arg1", "" ); - f.argumentList << QgsSQLComposerDialog::Argument( "arg2", "xs:double" ); - f.argumentList << QgsSQLComposerDialog::Argument( "arg3", "gml:AbstractGeometryType" ); - f.argumentList << QgsSQLComposerDialog::Argument( "number", "xs:int" ); + f.name = QStringLiteral( "sixth_func" ); + f.argumentList << QgsSQLComposerDialog::Argument( QStringLiteral( "arg1" ), QLatin1String( "" ) ); + f.argumentList << QgsSQLComposerDialog::Argument( QStringLiteral( "arg2" ), QStringLiteral( "xs:double" ) ); + f.argumentList << QgsSQLComposerDialog::Argument( QStringLiteral( "arg3" ), QStringLiteral( "gml:AbstractGeometryType" ) ); + f.argumentList << QgsSQLComposerDialog::Argument( QStringLiteral( "number" ), QStringLiteral( "xs:int" ) ); functions << f; } { QgsSQLComposerDialog::Function f; - f.name = "seventh_func"; - f.argumentList << QgsSQLComposerDialog::Argument( "arg1", "" ); - f.argumentList << QgsSQLComposerDialog::Argument( "arg2", "xs:double" ); + f.name = QStringLiteral( "seventh_func" ); + f.argumentList << QgsSQLComposerDialog::Argument( QStringLiteral( "arg1" ), QLatin1String( "" ) ); + f.argumentList << QgsSQLComposerDialog::Argument( QStringLiteral( "arg2" ), QStringLiteral( "xs:double" ) ); f.minArgs = 1; functions << f; } @@ -337,7 +337,7 @@ void TestQgsSQLComposerDialog::testSelectFunction() QCOMPARE( getFunctionsCombo( d )->itemText( 6 ), QString( "sixth_func(arg1, arg2: double, arg3: geometry, int)" ) ); QCOMPARE( getFunctionsCombo( d )->itemText( 7 ), QString( "seventh_func(arg1[, arg2: double])" ) ); - d.setSql( "SELECT * FROM my_table" ); + d.setSql( QStringLiteral( "SELECT * FROM my_table" ) ); // Set focus in where editor setFocusIn( getWhereEditor( d ) ); @@ -348,7 +348,7 @@ void TestQgsSQLComposerDialog::testSelectFunction() QCOMPARE( d.sql(), QString( "SELECT * FROM my_table WHERE first_func(" ) ); // Set focus in SQL zone - d.setSql( "SELECT * FROM my_table WHERE " ); + d.setSql( QStringLiteral( "SELECT * FROM my_table WHERE " ) ); setFocusIn( getQueryEdit( d ) ); gotoEndOfLine( getQueryEdit( d ) ); getFunctionsCombo( d )->setCurrentIndex( 0 ); @@ -362,9 +362,9 @@ void TestQgsSQLComposerDialog::testSelectSpatialPredicate() if ( !runTest() ) return; QgsSQLComposerDialog d; - d.addSpatialPredicates( QList() << QgsSQLComposerDialog::Function( "predicate", 2 ) ); + d.addSpatialPredicates( QList() << QgsSQLComposerDialog::Function( QStringLiteral( "predicate" ), 2 ) ); - d.setSql( "SELECT * FROM my_table" ); + d.setSql( QStringLiteral( "SELECT * FROM my_table" ) ); // Set focus in where editor setFocusIn( getWhereEditor( d ) ); @@ -374,7 +374,7 @@ void TestQgsSQLComposerDialog::testSelectSpatialPredicate() QCOMPARE( d.sql(), QString( "SELECT * FROM my_table WHERE predicate(" ) ); // Set focus in SQL zone - d.setSql( "SELECT * FROM my_table WHERE " ); + d.setSql( QStringLiteral( "SELECT * FROM my_table WHERE " ) ); setFocusIn( getQueryEdit( d ) ); gotoEndOfLine( getQueryEdit( d ) ); getSpatialPredicatesCombo( d )->setCurrentIndex( 0 ); @@ -389,7 +389,7 @@ void TestQgsSQLComposerDialog::testSelectOperator() return; QgsSQLComposerDialog d; - d.setSql( "SELECT * FROM my_table" ); + d.setSql( QStringLiteral( "SELECT * FROM my_table" ) ); // Set focus in where editor setFocusIn( getWhereEditor( d ) ); @@ -399,7 +399,7 @@ void TestQgsSQLComposerDialog::testSelectOperator() QCOMPARE( d.sql(), QString( "SELECT * FROM my_table WHERE AND" ) ); // Set focus in SQL zone - d.setSql( "SELECT * FROM my_table WHERE " ); + d.setSql( QStringLiteral( "SELECT * FROM my_table WHERE " ) ); setFocusIn( getQueryEdit( d ) ); gotoEndOfLine( getQueryEdit( d ) ); getOperatorsCombo( d )->setCurrentIndex( 0 ); @@ -413,29 +413,29 @@ void TestQgsSQLComposerDialog::testJoins() if ( !runTest() ) return; QgsSQLComposerDialog d; - d.setSql( "SELECT * FROM my_table" ); + d.setSql( QStringLiteral( "SELECT * FROM my_table" ) ); d.setSupportMultipleTables( true ); QTableWidget* table = getTableJoins( d ); QCOMPARE( table->rowCount(), 1 ); QCOMPARE( table->item( 0, 0 ) != nullptr, true ); - table->item( 0, 0 )->setText( "join_table" ); - table->item( 0, 1 )->setText( "join_expr" ); + table->item( 0, 0 )->setText( QStringLiteral( "join_table" ) ); + table->item( 0, 1 )->setText( QStringLiteral( "join_expr" ) ); QCOMPARE( d.sql(), QString( "SELECT * FROM my_table JOIN join_table ON join_expr" ) ); QTest::mouseClick( getAddJoinButton( d ), Qt::LeftButton ); QCOMPARE( table->rowCount(), 2 ); - table->item( 1, 0 )->setText( "join2_table" ); - table->item( 1, 1 )->setText( "join2_expr" ); + table->item( 1, 0 )->setText( QStringLiteral( "join2_table" ) ); + table->item( 1, 1 )->setText( QStringLiteral( "join2_expr" ) ); QCOMPARE( d.sql(), QString( "SELECT * FROM my_table JOIN join_table ON join_expr JOIN join2_table ON join2_expr" ) ); table->setCurrentCell( 0, 0 ); QTest::mouseClick( getAddJoinButton( d ), Qt::LeftButton ); QCOMPARE( table->rowCount(), 3 ); - table->item( 1, 0 )->setText( "join15_table" ); - table->item( 1, 1 )->setText( "join15_expr" ); + table->item( 1, 0 )->setText( QStringLiteral( "join15_table" ) ); + table->item( 1, 1 )->setText( QStringLiteral( "join15_expr" ) ); QCOMPARE( d.sql(), QString( "SELECT * FROM my_table JOIN join_table ON join_expr JOIN join15_table ON join15_expr JOIN join2_table ON join2_expr" ) ); diff --git a/tests/src/providers/grass/testqgsgrassprovider.cpp b/tests/src/providers/grass/testqgsgrassprovider.cpp index 637427c6e78b..858e8524feba 100644 --- a/tests/src/providers/grass/testqgsgrassprovider.cpp +++ b/tests/src/providers/grass/testqgsgrassprovider.cpp @@ -116,20 +116,20 @@ QString TestQgsGrassCommand::toString() const QString string; if ( command == StartEditing ) { - string += "StartEditing grassLayerCode: " + values["grassLayerCode"].toString(); - string += " expectedLayerType: " + values["expectedLayerType"].toString(); + string += "StartEditing grassLayerCode: " + values[QStringLiteral( "grassLayerCode" )].toString(); + string += " expectedLayerType: " + values[QStringLiteral( "expectedLayerType" )].toString(); } else if ( command == CommitChanges ) { - string += "CommitChanges"; + string += QLatin1String( "CommitChanges" ); } else if ( command == RollBack ) { - string += "RollBack"; + string += QLatin1String( "RollBack" ); } else if ( command == AddFeature ) { - string += "AddFeature "; + string += QLatin1String( "AddFeature " ); Q_FOREACH ( const TestQgsGrassFeature & grassFeature, grassFeatures ) { if ( grassFeature.hasGeometry() ) @@ -145,36 +145,36 @@ QString TestQgsGrassCommand::toString() const } else if ( command == DeleteFeature ) { - string += "DeleteFeature "; - string += QString( "fid: %1" ).arg( fid ); + string += QLatin1String( "DeleteFeature " ); + string += QStringLiteral( "fid: %1" ).arg( fid ); } else if ( command == ChangeGeometry ) { - string += "ChangeGeometry "; - string += QString( "fid: %1 geometry: %2" ).arg( fid ).arg( geometry->exportToWkt( 1 ) ); + string += QLatin1String( "ChangeGeometry " ); + string += QStringLiteral( "fid: %1 geometry: %2" ).arg( fid ).arg( geometry->exportToWkt( 1 ) ); } else if ( command == AddAttribute ) { - string += "AddAttribute "; + string += QLatin1String( "AddAttribute " ); string += "name: " + field.name() + " type: " + QVariant::typeToName( field.type() ); } else if ( command == DeleteAttribute ) { - string += "DeleteAttribute "; + string += QLatin1String( "DeleteAttribute " ); string += "name: " + field.name(); } else if ( command == ChangeAttributeValue ) { - string += "ChangeAttributeValue "; + string += QLatin1String( "ChangeAttributeValue " ); string += "name: " + field.name() + " value: " + value.toString(); } else if ( command == UndoAll ) { - string += "UndoAll"; + string += QLatin1String( "UndoAll" ); } else if ( command == RedoAll ) { - string += "RedoAll"; + string += QLatin1String( "RedoAll" ); } return string; } @@ -262,11 +262,11 @@ void TestQgsGrassProvider::initTestCase() // in version different form which we are testing here and it would also load GRASS libs in different version // and result in segfault when __do_global_dtors_aux() is called. // => we must set QGIS_PROVIDER_FILE before QgsApplication::initQgis() to avoid loading GRASS provider in different version - QgsGrass::putEnv( "QGIS_PROVIDER_FILE", QString( "gdal|ogr|memoryprovider|grassprovider%1" ).arg( GRASS_BUILD_VERSION ) ); + QgsGrass::putEnv( QStringLiteral( "QGIS_PROVIDER_FILE" ), QStringLiteral( "gdal|ogr|memoryprovider|grassprovider%1" ).arg( GRASS_BUILD_VERSION ) ); QgsApplication::initQgis(); QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( "\n", "
                                                                                                                                                                                    \n" ); - mReport += QString( "

                                                                                                                                                                                    GRASS %1 provider tests

                                                                                                                                                                                    \n" ).arg( GRASS_BUILD_VERSION ); + mySettings = mySettings.replace( QLatin1String( "\n" ), QLatin1String( "
                                                                                                                                                                                    \n" ) ); + mReport += QStringLiteral( "

                                                                                                                                                                                    GRASS %1 provider tests

                                                                                                                                                                                    \n" ).arg( GRASS_BUILD_VERSION ); mReport += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    \n"; #ifndef Q_OS_WIN @@ -283,9 +283,9 @@ void TestQgsGrassProvider::initTestCase() //create some objects that will be used in all tests... //create a raster layer that will be used in all tests... - mGisdbase = QString( TEST_DATA_DIR ) + "/grass"; - mLocation = "wgs84"; - mBuildMapset = QString( "test%1" ).arg( GRASS_BUILD_VERSION ); + mGisdbase = QStringLiteral( TEST_DATA_DIR ) + "/grass"; + mLocation = QStringLiteral( "wgs84" ); + mBuildMapset = QStringLiteral( "test%1" ).arg( GRASS_BUILD_VERSION ); reportRow( "mGisdbase: " + mGisdbase ); reportRow( "mLocation: " + mLocation ); reportRow( "mBuildMapset: " + mBuildMapset ); @@ -309,8 +309,8 @@ void TestQgsGrassProvider::cleanupTestCase() bool TestQgsGrassProvider::verify( bool ok ) { - reportRow( "" ); - reportRow( QString( "Test result: " ) + ( ok ? "ok" : "error" ) ); + reportRow( QLatin1String( "" ) ); + reportRow( QStringLiteral( "Test result: " ) + ( ok ? "ok" : "error" ) ); return ok; } @@ -351,18 +351,18 @@ bool TestQgsGrassProvider::compare( double expected, double got, bool& ok ) // G_fatal_error() handling void TestQgsGrassProvider::fatalError() { - reportHeader( "TestQgsGrassProvider::fatalError" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::fatalError" ) ); bool ok = true; - QString errorMessage = "test fatal error"; + QString errorMessage = QStringLiteral( "test fatal error" ); G_TRY { G_fatal_error( "%s", errorMessage.toAscii().data() ); ok = false; // should not be reached - reportRow( "G_fatal_error() did not throw exception" ); + reportRow( QStringLiteral( "G_fatal_error() did not throw exception" ) ); } G_CATCH( QgsGrass::Exception &e ) { - reportRow( QString( "Exception thrown and caught correctly" ) ); + reportRow( QStringLiteral( "Exception thrown and caught correctly" ) ); reportRow( "expected error message: " + errorMessage ); reportRow( "got error message: " + QString( e.what() ) ); compare( errorMessage, e.what(), ok ); @@ -373,20 +373,20 @@ void TestQgsGrassProvider::fatalError() void TestQgsGrassProvider::locations() { - reportHeader( "TestQgsGrassProvider::locations" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::locations" ) ); bool ok = true; QStringList expectedLocations; - expectedLocations << "wgs84"; + expectedLocations << QStringLiteral( "wgs84" ); QStringList locations = QgsGrass::locations( mGisdbase ); - reportRow( "expectedLocations: " + expectedLocations.join( ", " ) ); - reportRow( "locations: " + locations.join( ", " ) ); + reportRow( "expectedLocations: " + expectedLocations.join( QStringLiteral( ", " ) ) ); + reportRow( "locations: " + locations.join( QStringLiteral( ", " ) ) ); compare( expectedLocations, locations, ok ); GVERIFY( ok ); } void TestQgsGrassProvider::mapsets() { - reportHeader( "TestQgsGrassProvider::mapsets" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::mapsets" ) ); bool ok = true; // User must be owner of mapset if it has to be opened (locked) @@ -394,16 +394,16 @@ void TestQgsGrassProvider::mapsets() QString tmpGisdbase; if ( !copyLocation( tmpGisdbase ) ) { - reportRow( "cannot copy location" ); + reportRow( QStringLiteral( "cannot copy location" ) ); GVERIFY( false ); return; } QStringList expectedMapsets; - expectedMapsets << "PERMANENT" << "test" << "test6" << "test7"; + expectedMapsets << QStringLiteral( "PERMANENT" ) << QStringLiteral( "test" ) << QStringLiteral( "test6" ) << QStringLiteral( "test7" ); QStringList mapsets = QgsGrass::mapsets( tmpGisdbase, mLocation ); - reportRow( "expectedMapsets: " + expectedMapsets.join( ", " ) ); - reportRow( "mapsets: " + mapsets.join( ", " ) ); + reportRow( "expectedMapsets: " + expectedMapsets.join( QStringLiteral( ", " ) ) ); + reportRow( "mapsets: " + mapsets.join( QStringLiteral( ", " ) ) ); compare( expectedMapsets, mapsets, ok ); QgsGrass::setLocation( tmpGisdbase, mLocation ); // for G_is_mapset_in_search_path // Disabled because adding of all mapsets to search path was disabled in setLocation() @@ -421,7 +421,7 @@ void TestQgsGrassProvider::mapsets() // open/close mapset try twice to be sure that lock was not left etc. for ( int i = 1; i < 3; i++ ) { - reportRow( "" ); + reportRow( QLatin1String( "" ) ); reportRow( "Open/close mapset " + mBuildMapset + " for the " + QString::number( i ) + ". time" ); QString error = QgsGrass::openMapset( tmpGisdbase, mLocation, mBuildMapset ); if ( !error.isEmpty() ) @@ -431,10 +431,10 @@ void TestQgsGrassProvider::mapsets() } else { - reportRow( "mapset successfully opened" ); + reportRow( QStringLiteral( "mapset successfully opened" ) ); if ( !QgsGrass::activeMode() ) { - reportRow( "QgsGrass::activeMode() returns false after openMapset()" ); + reportRow( QStringLiteral( "QgsGrass::activeMode() returns false after openMapset()" ) ); ok = false; } @@ -447,12 +447,12 @@ void TestQgsGrassProvider::mapsets() } else { - reportRow( "mapset successfully closed" ); + reportRow( QStringLiteral( "mapset successfully closed" ) ); } if ( QgsGrass::activeMode() ) { - reportRow( "QgsGrass::activeMode() returns true after closeMapset()" ); + reportRow( QStringLiteral( "QgsGrass::activeMode() returns true after closeMapset()" ) ); ok = false; } } @@ -463,72 +463,72 @@ void TestQgsGrassProvider::mapsets() void TestQgsGrassProvider::maps() { - reportHeader( "TestQgsGrassProvider::maps" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::maps" ) ); bool ok = true; QStringList expectedVectors; - expectedVectors << "test"; + expectedVectors << QStringLiteral( "test" ); QStringList vectors = QgsGrass::vectors( mGisdbase, mLocation, mBuildMapset ); - reportRow( "expectedVectors: " + expectedVectors.join( ", " ) ); - reportRow( "vectors: " + vectors.join( ", " ) ); + reportRow( "expectedVectors: " + expectedVectors.join( QStringLiteral( ", " ) ) ); + reportRow( "vectors: " + vectors.join( QStringLiteral( ", " ) ) ); compare( expectedVectors, vectors, ok ); - reportRow( "" ); + reportRow( QLatin1String( "" ) ); QStringList expectedRasters; - expectedRasters << "cell" << "dcell" << "fcell"; - QStringList rasters = QgsGrass::rasters( mGisdbase, mLocation, "test" ); - reportRow( "expectedRasters: " + expectedRasters.join( ", " ) ); - reportRow( "rasters: " + rasters.join( ", " ) ); + expectedRasters << QStringLiteral( "cell" ) << QStringLiteral( "dcell" ) << QStringLiteral( "fcell" ); + QStringList rasters = QgsGrass::rasters( mGisdbase, mLocation, QStringLiteral( "test" ) ); + reportRow( "expectedRasters: " + expectedRasters.join( QStringLiteral( ", " ) ) ); + reportRow( "rasters: " + rasters.join( QStringLiteral( ", " ) ) ); compare( expectedRasters, rasters, ok ); GVERIFY( ok ); } void TestQgsGrassProvider::vectorLayers() { - reportHeader( "TestQgsGrassProvider::vectorLayers" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::vectorLayers" ) ); QString mapset = mBuildMapset; - QString mapName = "test"; + QString mapName = QStringLiteral( "test" ); QStringList expectedLayers; - expectedLayers << "1_point" << "2_line" << "3_polygon"; + expectedLayers << QStringLiteral( "1_point" ) << QStringLiteral( "2_line" ) << QStringLiteral( "3_polygon" ); reportRow( "mapset: " + mapset ); reportRow( "mapName: " + mapName ); - reportRow( "expectedLayers: " + expectedLayers.join( ", " ) ); + reportRow( "expectedLayers: " + expectedLayers.join( QStringLiteral( ", " ) ) ); bool ok = true; G_TRY { QStringList layers = QgsGrass::vectorLayers( mGisdbase, mLocation, mapset, mapName ); - reportRow( "layers: " + layers.join( ", " ) ); + reportRow( "layers: " + layers.join( QStringLiteral( ", " ) ) ); compare( expectedLayers, layers, ok ); } G_CATCH( QgsGrass::Exception &e ) { ok = false; - reportRow( QString( "ERROR: %1" ).arg( e.what() ) ); + reportRow( QStringLiteral( "ERROR: %1" ).arg( e.what() ) ); } GVERIFY( ok ); } void TestQgsGrassProvider::region() { - reportHeader( "TestQgsGrassProvider::region" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::region" ) ); struct Cell_head window; struct Cell_head windowCopy; bool ok = true; try { - QgsGrass::region( mGisdbase, mLocation, "PERMANENT", &window ); + QgsGrass::region( mGisdbase, mLocation, QStringLiteral( "PERMANENT" ), &window ); } catch ( QgsGrass::Exception &e ) { Q_UNUSED( e ); - reportRow( "QgsGrass::region() failed" ); + reportRow( QStringLiteral( "QgsGrass::region() failed" ) ); ok = false; } if ( ok ) { - QString expectedRegion = "proj:3;zone:0;north:90N;south:90S;east:180E;west:180W;cols:1000;rows:500;e-w resol:0:21:36;n-s resol:0:21:36;"; + QString expectedRegion = QStringLiteral( "proj:3;zone:0;north:90N;south:90S;east:180E;west:180W;cols:1000;rows:500;e-w resol:0:21:36;n-s resol:0:21:36;" ); QString region = QgsGrass::regionString( &window ); reportRow( "expectedRegion: " + expectedRegion ); reportRow( "region: " + region ); @@ -549,7 +549,7 @@ void TestQgsGrassProvider::region() void TestQgsGrassProvider::info() { // info() -> getInfo() -> runModule() -> startModule() - reportHeader( "TestQgsGrassProvider::info" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::info" ) ); bool ok = true; QgsRectangle expectedExtent( -5, -5, 5, 5 ); @@ -557,19 +557,19 @@ void TestQgsGrassProvider::info() QgsRasterBandStats es; es.minimumValue = -20; es.maximumValue = 20; - expectedStats.insert( "cell", es ); + expectedStats.insert( QStringLiteral( "cell" ), es ); es.minimumValue = -20.25; es.maximumValue = 20.25; - expectedStats.insert( "dcell", es ); + expectedStats.insert( QStringLiteral( "dcell" ), es ); es.minimumValue = -20.25; es.maximumValue = 20.25; - expectedStats.insert( "fcell", es ); + expectedStats.insert( QStringLiteral( "fcell" ), es ); Q_FOREACH ( const QString& map, expectedStats.keys() ) { es = expectedStats.value( map ); // TODO: QgsGrass::info() may open dialog window on error which blocks tests QString error; - QHash info = QgsGrass::info( mGisdbase, mLocation, "test", map, QgsGrassObject::Raster, "stats", + QHash info = QgsGrass::info( mGisdbase, mLocation, QStringLiteral( "test" ), map, QgsGrassObject::Raster, QStringLiteral( "stats" ), expectedExtent, 10, 10, 5000, error ); if ( !error.isEmpty() ) { @@ -580,15 +580,15 @@ void TestQgsGrassProvider::info() reportRow( "map: " + map ); QgsRasterBandStats s; - s.minimumValue = info["MIN"].toDouble(); - s.maximumValue = info["MAX"].toDouble(); + s.minimumValue = info[QStringLiteral( "MIN" )].toDouble(); + s.maximumValue = info[QStringLiteral( "MAX" )].toDouble(); - reportRow( QString( "expectedStats: min = %1 max = %2" ).arg( es.minimumValue ).arg( es.maximumValue ) ) ; - reportRow( QString( "stats: min = %1 max = %2" ).arg( s.minimumValue ).arg( s.maximumValue ) ) ; + reportRow( QStringLiteral( "expectedStats: min = %1 max = %2" ).arg( es.minimumValue ).arg( es.maximumValue ) ) ; + reportRow( QStringLiteral( "stats: min = %1 max = %2" ).arg( s.minimumValue ).arg( s.maximumValue ) ) ; compare( es.minimumValue, s.minimumValue, ok ); compare( es.maximumValue, s.maximumValue, ok ); - QgsRectangle extent = QgsGrass::extent( mGisdbase, mLocation, "test", map, QgsGrassObject::Raster, error ); + QgsRectangle extent = QgsGrass::extent( mGisdbase, mLocation, QStringLiteral( "test" ), map, QgsGrassObject::Raster, error ); reportRow( "expectedExtent: " + expectedExtent.toString() ); reportRow( "extent: " + extent.toString() ); if ( !error.isEmpty() ) @@ -602,9 +602,9 @@ void TestQgsGrassProvider::info() } } - reportRow( "" ); + reportRow( QLatin1String( "" ) ); QgsCoordinateReferenceSystem expectedCrs; - expectedCrs.createFromOgcWmsCrs( "EPSG:4326" ); + expectedCrs.createFromOgcWmsCrs( QStringLiteral( "EPSG:4326" ) ); reportRow( "expectedCrs: " + expectedCrs.toWkt() ); QString error; @@ -751,8 +751,8 @@ bool TestQgsGrassProvider::createTmpLocation( QString& tmpGisdbase, QString& tmp delete tmpFile; //tmpGisdbase = QDir::tempPath() + "/qgis-grass-test/test"; // debug reportRow( "tmpGisdbase: " + tmpGisdbase ); - tmpLocation = "test"; - tmpMapset = "PERMANENT"; + tmpLocation = QStringLiteral( "test" ); + tmpMapset = QStringLiteral( "PERMANENT" ); QString tmpMapsetPath = tmpGisdbase + "/" + tmpLocation + "/" + tmpMapset; reportRow( "tmpMapsetPath: " + tmpMapsetPath ); @@ -764,7 +764,7 @@ bool TestQgsGrassProvider::createTmpLocation( QString& tmpGisdbase, QString& tmp } QStringList cpFiles; - cpFiles << "DEFAULT_WIND" << "WIND" << "PROJ_INFO" << "PROJ_UNITS"; + cpFiles << QStringLiteral( "DEFAULT_WIND" ) << QStringLiteral( "WIND" ) << QStringLiteral( "PROJ_INFO" ) << QStringLiteral( "PROJ_UNITS" ); QString templateMapsetPath = mGisdbase + "/" + mLocation + "/PERMANENT"; Q_FOREACH ( const QString& cpFile, cpFiles ) { @@ -779,7 +779,7 @@ bool TestQgsGrassProvider::createTmpLocation( QString& tmpGisdbase, QString& tmp void TestQgsGrassProvider::rasterImport() { - reportHeader( "TestQgsGrassProvider::rasterImport" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::rasterImport" ) ); bool ok = true; QString tmpGisdbase; @@ -788,7 +788,7 @@ void TestQgsGrassProvider::rasterImport() if ( !createTmpLocation( tmpGisdbase, tmpLocation, tmpMapset ) ) { - reportRow( "cannot create temporary location" ); + reportRow( QStringLiteral( "cannot create temporary location" ) ); GVERIFY( false ); return; } @@ -797,16 +797,16 @@ void TestQgsGrassProvider::rasterImport() // tenbytenraster.asc does not have CRS, import to EPSG:4326 without reprojection fails // in G_adjust_Cell_head() (Illegal latitude for North) //rasterFiles << "tenbytenraster.asc"; - rasterFiles << "landsat.tif" << "raster/band1_byte_ct_epsg4326.tif" << "raster/band1_int16_noct_epsg4326.tif"; - rasterFiles << "raster/band1_float32_noct_epsg4326.tif" << "raster/band3_int16_noct_epsg4326.tif"; + rasterFiles << QStringLiteral( "landsat.tif" ) << QStringLiteral( "raster/band1_byte_ct_epsg4326.tif" ) << QStringLiteral( "raster/band1_int16_noct_epsg4326.tif" ); + rasterFiles << QStringLiteral( "raster/band1_float32_noct_epsg4326.tif" ) << QStringLiteral( "raster/band3_int16_noct_epsg4326.tif" ); QgsCoordinateReferenceSystem mapsetCrs = QgsGrass::crsDirect( mGisdbase, mLocation ); Q_FOREACH ( const QString& rasterFile, rasterFiles ) { - QString uri = QString( TEST_DATA_DIR ) + "/" + rasterFile; + QString uri = QStringLiteral( TEST_DATA_DIR ) + "/" + rasterFile; QString name = QFileInfo( uri ).baseName(); reportRow( "input raster: " + uri ); - QgsRasterDataProvider* provider = qobject_cast( QgsProviderRegistry::instance()->provider( "gdal", uri ) ); + QgsRasterDataProvider* provider = qobject_cast( QgsProviderRegistry::instance()->provider( QStringLiteral( "gdal" ), uri ) ); if ( !provider ) { reportRow( "Cannot create provider " + uri ); @@ -854,7 +854,7 @@ void TestQgsGrassProvider::rasterImport() void TestQgsGrassProvider::vectorImport() { - reportHeader( "TestQgsGrassProvider::vectorImport" ); + reportHeader( QStringLiteral( "TestQgsGrassProvider::vectorImport" ) ); bool ok = true; QString tmpGisdbase; @@ -863,22 +863,22 @@ void TestQgsGrassProvider::vectorImport() if ( !createTmpLocation( tmpGisdbase, tmpLocation, tmpMapset ) ) { - reportRow( "cannot create temporary location" ); + reportRow( QStringLiteral( "cannot create temporary location" ) ); GVERIFY( false ); return; } QStringList files; - files << "points.shp" << "multipoint.shp" << "lines.shp" << "polys.shp"; - files << "polys_overlapping.shp" << "bug5598.shp"; + files << QStringLiteral( "points.shp" ) << QStringLiteral( "multipoint.shp" ) << QStringLiteral( "lines.shp" ) << QStringLiteral( "polys.shp" ); + files << QStringLiteral( "polys_overlapping.shp" ) << QStringLiteral( "bug5598.shp" ); QgsCoordinateReferenceSystem mapsetCrs = QgsGrass::crsDirect( mGisdbase, mLocation ); Q_FOREACH ( const QString& file, files ) { - QString uri = QString( TEST_DATA_DIR ) + "/" + file; + QString uri = QStringLiteral( TEST_DATA_DIR ) + "/" + file; QString name = QFileInfo( uri ).baseName(); reportRow( "input vector: " + uri ); - QgsVectorDataProvider* provider = qobject_cast( QgsProviderRegistry::instance()->provider( "ogr", uri ) ); + QgsVectorDataProvider* provider = qobject_cast( QgsProviderRegistry::instance()->provider( QStringLiteral( "ogr" ), uri ) ); if ( !provider ) { reportRow( "Cannot create provider " + uri ); @@ -902,7 +902,7 @@ void TestQgsGrassProvider::vectorImport() delete import; QStringList layers = QgsGrass::vectorLayers( tmpGisdbase, tmpLocation, tmpMapset, name ); - reportRow( "created layers: " + layers.join( "," ) ); + reportRow( "created layers: " + layers.join( QStringLiteral( "," ) ) ); } removeRecursively( tmpGisdbase ); GVERIFY( ok ); @@ -921,8 +921,8 @@ QList< TestQgsGrassCommandGroup > TestQgsGrassProvider::createCommands() // Start editing command = TestQgsGrassCommand( TestQgsGrassCommand::StartEditing ); - command.values["grassLayerCode"] = "1_point"; - command.values["expectedLayerType"] = "Point"; + command.values[QStringLiteral( "grassLayerCode" )] = "1_point"; + command.values[QStringLiteral( "expectedLayerType" )] = "Point"; commandGroup.commands << command; // Add point @@ -944,19 +944,19 @@ QList< TestQgsGrassCommandGroup > TestQgsGrassProvider::createCommands() // Add field command = TestQgsGrassCommand( TestQgsGrassCommand::AddAttribute ); - command.field = QgsField( "field_int", QVariant::Int, "integer" ); + command.field = QgsField( QStringLiteral( "field_int" ), QVariant::Int, QStringLiteral( "integer" ) ); commandGroup.commands << command; // Change attribute command = TestQgsGrassCommand( TestQgsGrassCommand::ChangeAttributeValue ); command.fid = 1; - command.field.setName( "field_int" ); + command.field.setName( QStringLiteral( "field_int" ) ); command.value = 123; commandGroup.commands << command; // Delete field command = TestQgsGrassCommand( TestQgsGrassCommand::DeleteAttribute ); - command.field = QgsField( "field_int", QVariant::Int, "integer" ); + command.field = QgsField( QStringLiteral( "field_int" ), QVariant::Int, QStringLiteral( "integer" ) ); commandGroup.commands << command; // Delete feature @@ -993,7 +993,7 @@ QList< TestQgsGrassCommandGroup > TestQgsGrassProvider::createCommands() { if ( commands[i].command == TestQgsGrassCommand::StartEditing ) { - commands[i].values["grassLayerCode"] = "2_point"; + commands[i].values[QStringLiteral( "grassLayerCode" )] = "2_point"; } } @@ -1006,13 +1006,13 @@ QList< TestQgsGrassCommandGroup > TestQgsGrassProvider::createCommands() // Start editing command = TestQgsGrassCommand( TestQgsGrassCommand::StartEditing ); - command.values["grassLayerCode"] = "1_line"; - command.values["expectedLayerType"] = "LineString"; + command.values[QStringLiteral( "grassLayerCode" )] = "1_line"; + command.values[QStringLiteral( "expectedLayerType" )] = "LineString"; commandGroup.commands << command; // Add field command = TestQgsGrassCommand( TestQgsGrassCommand::AddAttribute ); - command.field = QgsField( "field_int", QVariant::Int, "integer" ); + command.field = QgsField( QStringLiteral( "field_int" ), QVariant::Int, QStringLiteral( "integer" ) ); commandGroup.commands << command; // Add line feature with attributes @@ -1030,7 +1030,7 @@ QList< TestQgsGrassCommandGroup > TestQgsGrassProvider::createCommands() delete geometry; command.grassFeatures << grassFeature; command.expectedFeature = grassFeature; - command.attributes["field_int"] = 456; + command.attributes[QStringLiteral( "field_int" )] = 456; commandGroup.commands << command; // Commit @@ -1128,7 +1128,7 @@ bool TestQgsGrassProvider::setAttributes( QgsFeature & feature, const QMapisValid() ) { - reportRow( "grassLayer is not valid" ); + reportRow( QStringLiteral( "grassLayer is not valid" ) ); commandOk = false; break; } grassProvider = qobject_cast( grassLayer->dataProvider() ); if ( !grassProvider ) { - reportRow( "cannot get grassProvider" ); + reportRow( QStringLiteral( "cannot get grassProvider" ) ); commandOk = false; break; } if ( expectedLayers.keys().contains( grassUri ) ) { - reportRow( "expectedLayer exists" ); + reportRow( QStringLiteral( "expectedLayer exists" ) ); expectedLayer = expectedLayers.value( grassUri ); } else { - reportRow( "create new expectedLayer" ); + reportRow( QStringLiteral( "create new expectedLayer" ) ); // Create memory vector for verification, it has no fields until added - expectedLayer = new QgsVectorLayer( command.values["expectedLayerType"].toString(), "test", "memory" ); + expectedLayer = new QgsVectorLayer( command.values[QStringLiteral( "expectedLayerType" )].toString(), QStringLiteral( "test" ), QStringLiteral( "memory" ) ); if ( !expectedLayer->isValid() ) { - reportRow( "expectedLayer is not valid" ); + reportRow( QStringLiteral( "expectedLayer is not valid" ) ); commandOk = false; break; } @@ -1221,7 +1221,7 @@ void TestQgsGrassProvider::edit() if ( !grassLayer || !grassProvider || !expectedLayer ) { - reportRow( "grassLayer, grassProvider or expectedLayer is null" ); + reportRow( QStringLiteral( "grassLayer, grassProvider or expectedLayer is null" ) ); commandOk = false; break; } @@ -1257,7 +1257,7 @@ void TestQgsGrassProvider::edit() if ( !grassLayer->addFeature( grassFeature ) ) { - reportRow( "cannot add feature" ); + reportRow( QStringLiteral( "cannot add feature" ) ); commandOk = false; break; } @@ -1279,7 +1279,7 @@ void TestQgsGrassProvider::edit() } if ( !expectedLayer->addFeature( expectedFeature ) ) { - reportRow( "cannot add expectedFeature" ); + reportRow( QStringLiteral( "cannot add expectedFeature" ) ); commandOk = false; } commandGroup.expectedFids.insert( expectedFid, expectedFeature.id() ); @@ -1291,13 +1291,13 @@ void TestQgsGrassProvider::edit() QgsFeatureId fid = commandGroup.fids.value( command.fid ); if ( !grassLayer->deleteFeature( fid ) ) { - reportRow( "cannot delete feature" ); + reportRow( QStringLiteral( "cannot delete feature" ) ); commandOk = false; } QgsFeatureId expectedFid = commandGroup.expectedFids.value( command.fid ); if ( !expectedLayer->deleteFeature( expectedFid ) ) { - reportRow( "cannot delete expected feature" ); + reportRow( QStringLiteral( "cannot delete expected feature" ) ); commandOk = false; } editCommands << command; @@ -1311,7 +1311,7 @@ void TestQgsGrassProvider::edit() } if ( !grassLayer->changeGeometry( fid, *command.geometry ) ) { - reportRow( "cannot change feature geometry" ); + reportRow( QStringLiteral( "cannot change feature geometry" ) ); commandOk = false; } QgsFeatureId expectedFid = command.fid; @@ -1321,7 +1321,7 @@ void TestQgsGrassProvider::edit() } if ( !expectedLayer->changeGeometry( expectedFid, *command.geometry ) ) { - reportRow( "cannot change expected feature geometry" ); + reportRow( QStringLiteral( "cannot change expected feature geometry" ) ); commandOk = false; } editCommands << command; @@ -1330,12 +1330,12 @@ void TestQgsGrassProvider::edit() { if ( !grassLayer->addAttribute( command.field ) ) { - reportRow( "cannot add field to layer" ); + reportRow( QStringLiteral( "cannot add field to layer" ) ); commandOk = false; } if ( !expectedLayer->addAttribute( command.field ) ) { - reportRow( "cannot add field to expectedLayer" ); + reportRow( QStringLiteral( "cannot add field to expectedLayer" ) ); commandOk = false; } editCommands << command; @@ -1345,13 +1345,13 @@ void TestQgsGrassProvider::edit() int index = grassLayer->fields().indexFromName( command.field.name() ); if ( !grassLayer->deleteAttribute( index ) ) { - reportRow( "cannot delete field from layer" ); + reportRow( QStringLiteral( "cannot delete field from layer" ) ); commandOk = false; } int expectedIndex = expectedLayer->fields().indexFromName( command.field.name() ); if ( !expectedLayer->deleteAttribute( expectedIndex ) ) { - reportRow( "cannot delete field from expected layer" ); + reportRow( QStringLiteral( "cannot delete field from expected layer" ) ); commandOk = false; } editCommands << command; @@ -1366,7 +1366,7 @@ void TestQgsGrassProvider::edit() int index = grassLayer->fields().indexFromName( command.field.name() ); if ( !grassLayer->changeAttributeValue( fid, index, command.value ) ) { - reportRow( "cannot change feature attribute" ); + reportRow( QStringLiteral( "cannot change feature attribute" ) ); commandOk = false; } QgsFeatureId expectedFid = command.fid; @@ -1377,7 +1377,7 @@ void TestQgsGrassProvider::edit() int expectedIndex = expectedLayer->fields().indexFromName( command.field.name() ); if ( !expectedLayer->changeAttributeValue( expectedFid, expectedIndex, command.value ) ) { - reportRow( "cannot change expected feature attribute" ); + reportRow( QStringLiteral( "cannot change expected feature attribute" ) ); commandOk = false; } editCommands << command; @@ -1387,7 +1387,7 @@ void TestQgsGrassProvider::edit() if ( grassLayer->undoStack()->count() != editCommands.size() || grassLayer->undoStack()->count() != expectedLayer->undoStack()->count() ) { - reportRow( QString( "Different undo stack size: %1, expected: %2, editCommands: %3" ) + reportRow( QStringLiteral( "Different undo stack size: %1, expected: %2, editCommands: %3" ) .arg( grassLayer->undoStack()->count() ).arg( expectedLayer->undoStack()->count() ).arg( editCommands.size() ) ); commandOk = false; } @@ -1400,13 +1400,13 @@ void TestQgsGrassProvider::edit() expectedLayer->undoStack()->undo(); if ( !compare( expectedLayers, ok ) ) { - reportRow( "undo failed" ); + reportRow( QStringLiteral( "undo failed" ) ); commandOk = false; break; } else { - reportRow( "undo ok" ); + reportRow( QStringLiteral( "undo ok" ) ); } } } @@ -1416,7 +1416,7 @@ void TestQgsGrassProvider::edit() if ( grassLayer->undoStack()->count() != editCommands.size() || grassLayer->undoStack()->count() != expectedLayer->undoStack()->count() ) { - reportRow( QString( "Different undo stack size: %1, expected: %2, editCommands: %3" ) + reportRow( QStringLiteral( "Different undo stack size: %1, expected: %2, editCommands: %3" ) .arg( grassLayer->undoStack()->count() ).arg( expectedLayer->undoStack()->count() ).arg( editCommands.size() ) ); commandOk = false; } @@ -1429,13 +1429,13 @@ void TestQgsGrassProvider::edit() expectedLayer->undoStack()->redo(); if ( !compare( expectedLayers, ok ) ) { - reportRow( "redo failed" ); + reportRow( QStringLiteral( "redo failed" ) ); commandOk = false; break; } else { - reportRow( "redo ok" ); + reportRow( QStringLiteral( "redo ok" ) ); } } } @@ -1443,14 +1443,14 @@ void TestQgsGrassProvider::edit() if ( !commandOk ) { - reportRow( "command failed" ); + reportRow( QStringLiteral( "command failed" ) ); ok = false; break; } if ( !command.verify ) { - reportRow( "partial command not verified" ); + reportRow( QStringLiteral( "partial command not verified" ) ); continue; } @@ -1458,12 +1458,12 @@ void TestQgsGrassProvider::edit() { if ( !compare( expectedLayers, ok ) ) { - reportRow( "command failed" ); + reportRow( QStringLiteral( "command failed" ) ); break; } else { - reportRow( "command ok" ); + reportRow( QStringLiteral( "command ok" ) ); } } } @@ -1504,7 +1504,7 @@ bool TestQgsGrassProvider::equal( QgsFeature feature, QgsFeature expectedFeature for ( int i = 0; i < feature.fields().size(); i++ ) { QString name = feature.fields().at( i ).name(); - if ( name == "cat" ) // skip cat + if ( name == QLatin1String( "cat" ) ) // skip cat { continue; } @@ -1522,13 +1522,13 @@ bool TestQgsGrassProvider::equal( QgsFeature feature, QgsFeature expectedFeature { names << feature.fields().at( j ).name(); } - reportRow( QString( "Attribute %1 not found, feature attributes: %2" ).arg( name, names.join( "," ) ) ); + reportRow( QStringLiteral( "Attribute %1 not found, feature attributes: %2" ).arg( name, names.join( QStringLiteral( "," ) ) ) ); return false; } indexes.remove( index ); if ( feature.attribute( index ) != expectedFeature.attribute( i ) ) { - reportRow( QString( "Attribute name %1, value: '%2' does not match expected value: '%3'" ) + reportRow( QStringLiteral( "Attribute name %1, value: '%2' does not match expected value: '%3'" ) .arg( name, feature.attribute( index ).toString(), expectedFeature.attribute( i ).toString() ) ); return false; } @@ -1541,7 +1541,7 @@ bool TestQgsGrassProvider::equal( QgsFeature feature, QgsFeature expectedFeature { names << feature.fields().at( i ).name(); } - reportRow( QString( "feature has %1 unexpected attributes: %2" ).arg( indexes.size() ).arg( names.join( "," ) ) ); + reportRow( QStringLiteral( "feature has %1 unexpected attributes: %2" ).arg( indexes.size() ).arg( names.join( QStringLiteral( "," ) ) ) ); return false; } return true; @@ -1552,7 +1552,7 @@ bool TestQgsGrassProvider::compare( QList features, QList features, QList expectedFeatures = getFeatures( expectedLayer ); // read the map using another layer/provider - QgsVectorLayer *layer = new QgsVectorLayer( uri, "test", "grass" ); + QgsVectorLayer *layer = new QgsVectorLayer( uri, QStringLiteral( "test" ), QStringLiteral( "grass" ) ); if ( !layer->isValid() ) { - reportRow( "shared layer is not valid" ); + reportRow( QStringLiteral( "shared layer is not valid" ) ); ok = false; return false; } @@ -1619,7 +1619,7 @@ bool TestQgsGrassProvider::compare( QString uri, QgsVectorLayer *expectedLayer, } else { - reportRow( "comparison with shared layer failed" ); + reportRow( QStringLiteral( "comparison with shared layer failed" ) ); } // We cannot test attribute table changes with independent layer in GRASS 6, which is using @@ -1660,10 +1660,10 @@ bool TestQgsGrassProvider::compare( QString uri, QgsVectorLayer *expectedLayer, QgsGrassVectorMapStore * mapStore = new QgsGrassVectorMapStore(); QgsGrassVectorMapStore::setStore( mapStore ); - layer = new QgsVectorLayer( uri, "test", "grass" ); + layer = new QgsVectorLayer( uri, QStringLiteral( "test" ), QStringLiteral( "grass" ) ); if ( !layer->isValid() ) { - reportRow( "independent layer is not valid" ); + reportRow( QStringLiteral( "independent layer is not valid" ) ); ok = false; return false; } @@ -1679,7 +1679,7 @@ bool TestQgsGrassProvider::compare( QString uri, QgsVectorLayer *expectedLayer, } else { - reportRow( "comparison with independent layer failed" ); + reportRow( QStringLiteral( "comparison with independent layer failed" ) ); } #endif // GRASS_VERSION_MAJOR >= 7 diff --git a/tests/src/providers/testqgsgdalprovider.cpp b/tests/src/providers/testqgsgdalprovider.cpp index d88af682ae68..e72aa6ac373d 100644 --- a/tests/src/providers/testqgsgdalprovider.cpp +++ b/tests/src/providers/testqgsgdalprovider.cpp @@ -61,8 +61,8 @@ void TestQgsGdalProvider::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); - mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt - mReport = "

                                                                                                                                                                                    GDAL Provider Tests

                                                                                                                                                                                    \n"; + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt + mReport = QStringLiteral( "

                                                                                                                                                                                    GDAL Provider Tests

                                                                                                                                                                                    \n" ); } //runs after all tests @@ -81,8 +81,8 @@ void TestQgsGdalProvider::cleanupTestCase() void TestQgsGdalProvider::scaleDataType() { - QString rasterWithOffset = QString( TEST_DATA_DIR ) + "/int_raster_with_scale.tif"; - QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( "gdal", rasterWithOffset ); + QString rasterWithOffset = QStringLiteral( TEST_DATA_DIR ) + "/int_raster_with_scale.tif"; + QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( QStringLiteral( "gdal" ), rasterWithOffset ); QgsRasterDataProvider* rp = dynamic_cast< QgsRasterDataProvider* >( provider ); QVERIFY( rp ); //raster is an integer data type, but has a scale < 1, so data type must be float @@ -93,8 +93,8 @@ void TestQgsGdalProvider::scaleDataType() void TestQgsGdalProvider::warpedVrt() { - QString raster = QString( TEST_DATA_DIR ) + "/requires_warped_vrt.tif"; - QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( "gdal", raster ); + QString raster = QStringLiteral( TEST_DATA_DIR ) + "/requires_warped_vrt.tif"; + QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( QStringLiteral( "gdal" ), raster ); QgsRasterDataProvider* rp = dynamic_cast< QgsRasterDataProvider* >( provider ); QVERIFY( rp ); @@ -112,8 +112,8 @@ void TestQgsGdalProvider::warpedVrt() void TestQgsGdalProvider::noData() { - QString raster = QString( TEST_DATA_DIR ) + "/raster/band1_byte_ct_epsg4326.tif"; - QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( "gdal", raster ); + QString raster = QStringLiteral( TEST_DATA_DIR ) + "/raster/band1_byte_ct_epsg4326.tif"; + QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( QStringLiteral( "gdal" ), raster ); QVERIFY( provider->isValid() ); QgsRasterDataProvider* rp = dynamic_cast< QgsRasterDataProvider* >( provider ); QVERIFY( rp ); @@ -126,8 +126,8 @@ void TestQgsGdalProvider::noData() void TestQgsGdalProvider::invalidNoDataInSourceIgnored() { - QString raster = QString( TEST_DATA_DIR ) + "/raster/byte_with_nan_nodata.tif"; - QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( "gdal", raster ); + QString raster = QStringLiteral( TEST_DATA_DIR ) + "/raster/byte_with_nan_nodata.tif"; + QgsDataProvider* provider = QgsProviderRegistry::instance()->provider( QStringLiteral( "gdal" ), raster ); QVERIFY( provider->isValid() ); QgsRasterDataProvider* rp = dynamic_cast< QgsRasterDataProvider* >( provider ); QVERIFY( rp ); diff --git a/tests/src/providers/testqgspostgresconn.cpp b/tests/src/providers/testqgspostgresconn.cpp index 26b63e0441e8..7907e61a3fae 100644 --- a/tests/src/providers/testqgspostgresconn.cpp +++ b/tests/src/providers/testqgspostgresconn.cpp @@ -10,8 +10,8 @@ class TestQgsPostgresConn: public QObject void quotedValueHstore() { QVariantMap map; - map["1"] = "2"; - map["a"] = "b \"c' \\x"; + map[QStringLiteral( "1" )] = "2"; + map[QStringLiteral( "a" )] = "b \"c' \\x"; const QString actual = QgsPostgresConn::quotedValue( map ); QCOMPARE( actual, QString( "E'\"1\"=>\"2\",\"a\"=>\"b \\\\\"c\\' \\\\\\\\x\"'::hstore" ) ); @@ -27,7 +27,7 @@ class TestQgsPostgresConn: public QObject void quotedValueStringArray() { QStringList list; - list << "a" << "b \"c' \\x"; + list << QStringLiteral( "a" ) << QStringLiteral( "b \"c' \\x" ); const QString actual = QgsPostgresConn::quotedValue( list ); QCOMPARE( actual, QString( "E'{\"a\",\"b \\\\\"c\\' \\\\\\\\x\"}'" ) ); } diff --git a/tests/src/providers/testqgspostgresprovider.cpp b/tests/src/providers/testqgspostgresprovider.cpp index 0f343d1dbd38..999da898d309 100644 --- a/tests/src/providers/testqgspostgresprovider.cpp +++ b/tests/src/providers/testqgspostgresprovider.cpp @@ -9,54 +9,54 @@ class TestQgsPostgresProvider: public QObject private slots: void decodeHstore() { - const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::Map, QVariant::String, "\"1\"=>\"2\", \"a\"=>\"b, \\\"c'\", \"backslash\"=>\"\\\\\"" ); + const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::Map, QVariant::String, QStringLiteral( "\"1\"=>\"2\", \"a\"=>\"b, \\\"c'\", \"backslash\"=>\"\\\\\"" ) ); QCOMPARE( decoded.type(), QVariant::Map ); QVariantMap expected; - expected["1"] = "2"; - expected["a"] = "b, \"c'"; - expected["backslash"] = "\\"; + expected[QStringLiteral( "1" )] = "2"; + expected[QStringLiteral( "a" )] = "b, \"c'"; + expected[QStringLiteral( "backslash" )] = "\\"; qDebug() << "actual: " << decoded; QCOMPARE( decoded.toMap(), expected ); } void decodeHstoreNoQuote() { - const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::Map, QVariant::String, "1=>2, a=>b c" ); + const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::Map, QVariant::String, QStringLiteral( "1=>2, a=>b c" ) ); QCOMPARE( decoded.type(), QVariant::Map ); QVariantMap expected; - expected["1"] = "2"; - expected["a"] = "b c"; + expected[QStringLiteral( "1" )] = "2"; + expected[QStringLiteral( "a" )] = "b c"; qDebug() << "actual: " << decoded; QCOMPARE( decoded.toMap(), expected ); } void decodeArray2StringList() { - const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::StringList, QVariant::String, "{\"1\",\"2\", \"a\\\\1\" , \"\\\\\",\"b, \\\"c'\"}" ); + const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::StringList, QVariant::String, QStringLiteral( "{\"1\",\"2\", \"a\\\\1\" , \"\\\\\",\"b, \\\"c'\"}" ) ); QCOMPARE( decoded.type(), QVariant::StringList ); QStringList expected; - expected << "1" << "2" << "a\\1" << "\\" << "b, \"c'"; + expected << QStringLiteral( "1" ) << QStringLiteral( "2" ) << QStringLiteral( "a\\1" ) << QStringLiteral( "\\" ) << QStringLiteral( "b, \"c'" ); qDebug() << "actual: " << decoded; QCOMPARE( decoded.toStringList(), expected ); } void decodeArray2StringListNoQuote() { - const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::StringList, QVariant::String, "{1,2, a ,b, c}" ); + const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::StringList, QVariant::String, QStringLiteral( "{1,2, a ,b, c}" ) ); QCOMPARE( decoded.type(), QVariant::StringList ); QStringList expected; - expected << "1" << "2" << "a" << "b" << "c"; + expected << QStringLiteral( "1" ) << QStringLiteral( "2" ) << QStringLiteral( "a" ) << QStringLiteral( "b" ) << QStringLiteral( "c" ); qDebug() << "actual: " << decoded; QCOMPARE( decoded.toStringList(), expected ); } void decodeArray2IntList() { - const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::StringList, QVariant::String, "{1, 2, 3,-5,10}" ); + const QVariant decoded = QgsPostgresProvider::convertValue( QVariant::StringList, QVariant::String, QStringLiteral( "{1, 2, 3,-5,10}" ) ); QCOMPARE( decoded.type(), QVariant::StringList ); QVariantList expected; diff --git a/tests/src/providers/testqgswcsprovider.cpp b/tests/src/providers/testqgswcsprovider.cpp index 89ae09aad59f..3230a756e0c4 100644 --- a/tests/src/providers/testqgswcsprovider.cpp +++ b/tests/src/providers/testqgswcsprovider.cpp @@ -56,8 +56,8 @@ void TestQgsWcsProvider::initTestCase() QgsApplication::init(); QgsApplication::initQgis(); QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( '\n', "
                                                                                                                                                                                    " ); - mReport += "

                                                                                                                                                                                    WCS provider tests

                                                                                                                                                                                    \n"; + mySettings = mySettings.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); + mReport += QLatin1String( "

                                                                                                                                                                                    WCS provider tests

                                                                                                                                                                                    \n" ); mReport += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    "; // Style is now inlined by QgsRasterChecker #if 0 @@ -71,10 +71,10 @@ void TestQgsWcsProvider::initTestCase() #endif //create some objects that will be used in all tests... //create a raster layer that will be used in all tests... - mTestDataDir = QString( TEST_DATA_DIR ) + "/raster"; + mTestDataDir = QStringLiteral( TEST_DATA_DIR ) + "/raster"; qDebug() << "mTestDataDir = " << mTestDataDir; - mUrl = QString( TEST_SERVER_URL ) + "/wcs"; + mUrl = QStringLiteral( TEST_SERVER_URL ) + "/wcs"; } //runs after all tests @@ -101,20 +101,20 @@ void TestQgsWcsProvider::read() // 1x1 pixel response if GRIDORIGIN coordinate has a negative value, but it has to be // verified if the problem is really on Mapserver side //versions << "1.0" << "1.1"; - versions << "1.0"; + versions << QStringLiteral( "1.0" ); QStringList identifiers; // identifiers in mapfile have the same name as files without .tif extension - identifiers << "band1_byte_noct_epsg4326"; - identifiers << "band1_int16_noct_epsg4326"; - identifiers << "band1_float32_noct_epsg4326"; - identifiers << "band3_byte_noct_epsg4326"; - identifiers << "band3_int16_noct_epsg4326"; - identifiers << "band3_float32_noct_epsg4326"; + identifiers << QStringLiteral( "band1_byte_noct_epsg4326" ); + identifiers << QStringLiteral( "band1_int16_noct_epsg4326" ); + identifiers << QStringLiteral( "band1_float32_noct_epsg4326" ); + identifiers << QStringLiteral( "band3_byte_noct_epsg4326" ); + identifiers << QStringLiteral( "band3_int16_noct_epsg4326" ); + identifiers << QStringLiteral( "band3_float32_noct_epsg4326" ); // How to reasonably log multiple fails within this loop? - QTemporaryFile* tmpFile = new QTemporaryFile( "qgis-wcs-test-XXXXXX.tif" ); + QTemporaryFile* tmpFile = new QTemporaryFile( QStringLiteral( "qgis-wcs-test-XXXXXX.tif" ) ); tmpFile->open(); QString tmpFilePath = tmpFile->fileName(); delete tmpFile; // removes the file @@ -127,17 +127,17 @@ void TestQgsWcsProvider::read() qDebug() << "copy " << testFilePath << " to " << tmpFilePath; if ( !QFile::copy( testFilePath, tmpFilePath ) ) { - mReport += QString( "Cannot copy %1 to %2" ).arg( testFilePath, tmpFilePath ); + mReport += QStringLiteral( "Cannot copy %1 to %2" ).arg( testFilePath, tmpFilePath ); ok = false; continue; } QgsDataSourceUri uri; - uri.setParam( "url", mUrl ); - uri.setParam( "identifier", identifier ); - uri.setParam( "crs", "epsg:4326" ); - uri.setParam( "version", version ); - uri.setParam( "cache", "AlwaysNetwork" ); + uri.setParam( QStringLiteral( "url" ), mUrl ); + uri.setParam( QStringLiteral( "identifier" ), identifier ); + uri.setParam( QStringLiteral( "crs" ), QStringLiteral( "epsg:4326" ) ); + uri.setParam( QStringLiteral( "version" ), version ); + uri.setParam( QStringLiteral( "cache" ), QStringLiteral( "AlwaysNetwork" ) ); if ( !read( identifier, uri.encodedUri(), tmpFilePath, mReport ) ) { @@ -151,10 +151,10 @@ void TestQgsWcsProvider::read() bool TestQgsWcsProvider::read( const QString& theIdentifier, const QString& theWcsUri, const QString& theFilePath, QString & theReport ) { - theReport += QString( "

                                                                                                                                                                                    Identifier (coverage): %1

                                                                                                                                                                                    " ).arg( theIdentifier ); + theReport += QStringLiteral( "

                                                                                                                                                                                    Identifier (coverage): %1

                                                                                                                                                                                    " ).arg( theIdentifier ); QgsRasterChecker checker; - bool ok = checker.runTest( "wcs", theWcsUri, "gdal", theFilePath ); + bool ok = checker.runTest( QStringLiteral( "wcs" ), theWcsUri, QStringLiteral( "gdal" ), theFilePath ); theReport += checker.report(); return ok; diff --git a/tests/src/providers/testqgswcspublicservers.cpp b/tests/src/providers/testqgswcspublicservers.cpp index a82e05607f04..281db5bf69dc 100644 --- a/tests/src/providers/testqgswcspublicservers.cpp +++ b/tests/src/providers/testqgswcspublicservers.cpp @@ -66,7 +66,7 @@ TestQgsWcsPublicServers::TestQgsWcsPublicServers( const QString & cacheDirPath, TestQgsWcsPublicServers::~TestQgsWcsPublicServers() { QSettings settings; - settings.setValue( "/qgis/networkAndProxy/networkTimeout", mOrigTimeout ); + settings.setValue( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), mOrigTimeout ); } //runs before all tests @@ -77,8 +77,8 @@ void TestQgsWcsPublicServers::init() // Unfortunately this seems to be the only way to set timeout, we try to reset it // at the end but it can be canceled before ... QSettings settings; - mOrigTimeout = settings.value( "/qgis/networkAndProxy/networkTimeout", "60000" ).toInt(); - settings.setValue( "/qgis/networkAndProxy/networkTimeout", mTimeout ); + mOrigTimeout = settings.value( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), "60000" ).toInt(); + settings.setValue( QStringLiteral( "/qgis/networkAndProxy/networkTimeout" ), mTimeout ); //mCacheDir = QDir( "./wcstestcache" ); mCacheDir = QDir( mCacheDirPath ); @@ -92,13 +92,13 @@ void TestQgsWcsPublicServers::init() } } - mHead << "Coverage"; + mHead << QStringLiteral( "Coverage" ); QStringList providers; - providers << "wcs" << "gdal"; + providers << QStringLiteral( "wcs" ) << QStringLiteral( "gdal" ); Q_FOREACH ( const QString& provider, providers ) { - QString prefix = provider == "gdal" ? "GDAL " : ""; + QString prefix = provider == QLatin1String( "gdal" ) ? "GDAL " : ""; mHead << prefix + "CRS"; mHead << prefix + "Width"; mHead << prefix + "Height"; @@ -130,13 +130,13 @@ void TestQgsWcsPublicServers::init() serverIt.next(); QScriptValue serverValue = serverIt.value(); - QString serverUrl = serverValue.property( "url" ).toString(); + QString serverUrl = serverValue.property( QStringLiteral( "url" ) ).toString(); QgsDebugMsg( "serverUrl: " + serverUrl ); Server server( serverUrl ); - server.description = serverValue.property( "description" ).toString(); + server.description = serverValue.property( QStringLiteral( "description" ) ).toString(); - QScriptValueIterator paramsIt( serverValue.property( "params" ) ); + QScriptValueIterator paramsIt( serverValue.property( QStringLiteral( "params" ) ) ); while ( paramsIt.hasNext() ) { paramsIt.next(); @@ -144,7 +144,7 @@ void TestQgsWcsPublicServers::init() server.params.insert( paramsIt.name(), paramsIt.value().toString() ); } - QScriptValue issuesValue = serverValue.property( "issues" ); + QScriptValue issuesValue = serverValue.property( QStringLiteral( "issues" ) ); QScriptValueIterator issuesIt( issuesValue ); while ( issuesIt.hasNext() ) @@ -152,13 +152,13 @@ void TestQgsWcsPublicServers::init() issuesIt.next(); QScriptValue issueValue = issuesIt.value(); - QString description = issueValue.property( "description" ).toString(); + QString description = issueValue.property( QStringLiteral( "description" ) ).toString(); QgsDebugMsg( "description: " + description ); Issue issue( description ); - issue.offender = issueValue.property( "offender" ).toString(); + issue.offender = issueValue.property( QStringLiteral( "offender" ) ).toString(); - QScriptValue coveragesValue = issueValue.property( "coverages" ); + QScriptValue coveragesValue = issueValue.property( QStringLiteral( "coverages" ) ); QScriptValueIterator coveragesIt( coveragesValue ); while ( coveragesIt.hasNext() ) { @@ -166,7 +166,7 @@ void TestQgsWcsPublicServers::init() issue.coverages << coveragesIt.value().toString(); } - QScriptValue versionsValue = issueValue.property( "versions" ); + QScriptValue versionsValue = issueValue.property( QStringLiteral( "versions" ) ); QScriptValueIterator versionsIt( versionsValue ); while ( versionsIt.hasNext() ) { @@ -230,7 +230,7 @@ int TestQgsWcsPublicServers::issueOffender( const QString & url, const QString & int offender = NoOffender; Q_FOREACH ( const Issue& myIssue, issues( url, coverage, version ) ) { - if ( myIssue.offender == "server" ) + if ( myIssue.offender == QLatin1String( "server" ) ) { offender |= ServerOffender; } @@ -257,7 +257,7 @@ void TestQgsWcsPublicServers::test() { //versions << "" << "1.0.0" << "1.1.0"; // empty for default // Empty is version is the same like "1.0.0" because QGIS will try "1.0.0" first - versions << "1.0.0" << "1.1.0"; + versions << QStringLiteral( "1.0.0" ) << QStringLiteral( "1.1.0" ); } @@ -279,7 +279,7 @@ void TestQgsWcsPublicServers::test() QStringList myServerLog; myServerLog << "server:" + serverUrl; QString myServerDirName = serverUrl; - myServerDirName.replace( QRegExp( "[:/]+" ), "." ); + myServerDirName.replace( QRegExp( "[:/]+" ), QStringLiteral( "." ) ); myServerDirName.remove( QRegExp( "\\.$" ) ); QgsDebugMsg( "myServerDirName = " + myServerDirName ); @@ -311,12 +311,12 @@ void TestQgsWcsPublicServers::test() QgsDataSourceUri myServerUri; - myServerUri.setParam( "url", serverUrl ); + myServerUri.setParam( QStringLiteral( "url" ), serverUrl ); if ( !version.isEmpty() ) { - myServerUri.setParam( "version", version ); + myServerUri.setParam( QStringLiteral( "version" ), version ); } - myServerUri.setParam( "cache", "AlwaysNetwork" ); + myServerUri.setParam( QStringLiteral( "cache" ), QStringLiteral( "AlwaysNetwork" ) ); Q_FOREACH ( const QString& key, myServer.params.keys() ) { @@ -340,11 +340,11 @@ void TestQgsWcsPublicServers::test() if ( !myCapabilities.supportedCoverages( myCoverages ) ) { QgsDebugMsg( "Cannot get list of coverages" ); - myVersionLog << "error:Cannot get list of coverages"; + myVersionLog << QStringLiteral( "error:Cannot get list of coverages" ); continue; } - myVersionLog << QString( "totalCoverages:%1" ).arg( myCoverages.size() ); + myVersionLog << QStringLiteral( "totalCoverages:%1" ).arg( myCoverages.size() ); int myCoverageCount = 0; int myStep = myCoverages.size() / qMin( mMaxCoverages, myCoverages.size() ); @@ -386,16 +386,16 @@ void TestQgsWcsPublicServers::test() myCapabilities.describeCoverage( myCoverage.identifier ); myCoverage = myCapabilities.coverage( myCoverage.identifier ); // get described QgsDataSourceUri myUri = myServerUri; - myUri.setParam( "identifier", myCoverage.identifier ); + myUri.setParam( QStringLiteral( "identifier" ), myCoverage.identifier ); if ( !myCoverage.times.isEmpty() ) { - myUri.setParam( "time", myCoverage.times.value( 0 ) ); + myUri.setParam( QStringLiteral( "time" ), myCoverage.times.value( 0 ) ); } myLog << "version:" + version; myLog << "describeCoverageUrl:" + myCapabilities.getDescribeCoverageUrl( myCoverage.identifier ); // Test time //myLog << "date:" + QString( "%1").arg( QDateTime::currentDateTime().toTime_t() ); - myLog << "date:" + QString( "%1" ).arg( QDateTime::currentDateTime().toString() ); + myLog << "date:" + QStringLiteral( "%1" ).arg( QDateTime::currentDateTime().toString() ); int myWidth = 100; int myHeight = 100; @@ -403,18 +403,18 @@ void TestQgsWcsPublicServers::test() { myHeight = static_cast( qRound( 1.0 * myWidth * myCoverage.height / myCoverage.width ) ); } - myLog << QString( "hasSize:%1" ).arg( myCoverage.hasSize ); + myLog << QStringLiteral( "hasSize:%1" ).arg( myCoverage.hasSize ); // Test QGIS provider and via GDAL QStringList providers; - providers << "wcs" << "gdal"; + providers << QStringLiteral( "wcs" ) << QStringLiteral( "gdal" ); Q_FOREACH ( const QString& provider, providers ) { QTime time; time.start(); QString uri; - if ( provider == "wcs" ) + if ( provider == QLatin1String( "wcs" ) ) { uri = myUri.encodedUri(); } @@ -428,7 +428,7 @@ void TestQgsWcsPublicServers::test() myStream << " " + serverUrl + '?' + "\n"; myStream << " " + myCoverage.identifier + "\n"; myStream << " " + version + "\n"; - myStream << QString( " %1\n" ).arg( mTimeout / 1000., 0, 'd' ); + myStream << QStringLiteral( " %1\n" ).arg( mTimeout / 1000., 0, 'd' ); myStream << "\n"; myGdalXmlFile.close(); @@ -492,7 +492,7 @@ void TestQgsWcsPublicServers::test() delete myBlock; } QgsDebugMsg( QString( "%1 values" ).arg( myValues.size() ) ); - myLog << provider + QString( "_valuesCount:%1" ).arg( myValues.size() ); + myLog << provider + QStringLiteral( "_valuesCount:%1" ).arg( myValues.size() ); // Verify image colors QSet myColors; @@ -505,14 +505,14 @@ void TestQgsWcsPublicServers::test() } } QgsDebugMsg( QString( "%1 colors" ).arg( myColors.size() ) ); - myLog << provider + QString( "_colorsCount:%1" ).arg( myColors.size() ); + myLog << provider + QStringLiteral( "_colorsCount:%1" ).arg( myColors.size() ); } else { QgsDebugMsg( "Layer is not valid" ); myLog << provider + "_error:Layer is not valid"; } - myLog << provider + QString( "_time:%1" ).arg( time.elapsed() / 1000., 0, 'f', 2 ); + myLog << provider + QStringLiteral( "_time:%1" ).arg( time.elapsed() / 1000., 0, 'f', 2 ); // Generate report for impatient people report(); } @@ -521,7 +521,7 @@ void TestQgsWcsPublicServers::test() Q_ASSERT( myLogFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) ); QTextStream myStream( &myLogFile ); - myStream << myLog.join( "\n" ); + myStream << myLog.join( QStringLiteral( "\n" ) ); myLogFile.close(); QgsMapLayerRegistry::instance()->removeAllMapLayers(); @@ -533,13 +533,13 @@ void TestQgsWcsPublicServers::test() QFile myVersionLogFile( myVersionLogPath ); Q_ASSERT( myVersionLogFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) ); QTextStream myVersionStream( &myVersionLogFile ); - myVersionStream << myVersionLog.join( "\n" ); + myVersionStream << myVersionLog.join( QStringLiteral( "\n" ) ); myVersionLogFile.close(); } QFile myServerLogFile( myServerLogPath ); Q_ASSERT( myServerLogFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) ); QTextStream myServerStream( &myServerLogFile ); - myServerStream << myServerLog.join( "\n" ); + myServerStream << myServerLog.join( QStringLiteral( "\n" ) ); myServerLogFile.close(); } } @@ -576,20 +576,20 @@ void TestQgsWcsPublicServers::report() QString myServerLogPath = myServerDir.absolutePath() + "/server.log"; QMap myServerLog = readLog( myServerLogPath ); - myReport += QString( "

                                                                                                                                                                                    Server: %1

                                                                                                                                                                                    " ).arg( myServerLog.value( "server" ) ); - Server myServer = getServer( myServerLog.value( "server" ) ); + myReport += QStringLiteral( "

                                                                                                                                                                                    Server: %1

                                                                                                                                                                                    " ).arg( myServerLog.value( QStringLiteral( "server" ) ) ); + Server myServer = getServer( myServerLog.value( QStringLiteral( "server" ) ) ); if ( !myServer.description.isEmpty() ) { myReport += myServer.description + "
                                                                                                                                                                                    \n"; } if ( !myServer.params.isEmpty() ) { - myReport += "
                                                                                                                                                                                    Additional params: "; + myReport += QLatin1String( "
                                                                                                                                                                                    Additional params: " ); Q_FOREACH ( const QString& key, myServer.params.keys() ) { myReport += key + '=' + myServer.params.value( key ) + " "; } - myReport += "
                                                                                                                                                                                    \n"; + myReport += QLatin1String( "
                                                                                                                                                                                    \n" ); } QString myServerReport; @@ -608,47 +608,47 @@ void TestQgsWcsPublicServers::report() QMap myVersionLog = readLog( myVersionLogPath ); QDir myVersionDir( myVersionDirPath ); - QString myVersion = myVersionLog.value( "version" ); - myServerReport += QString( "

                                                                                                                                                                                    Version: %2

                                                                                                                                                                                    " ).arg( myVersionLog.value( "getCapabilitiesUrl" ), myVersion.isEmpty() ? "(empty)" : myVersion ); + QString myVersion = myVersionLog.value( QStringLiteral( "version" ) ); + myServerReport += QStringLiteral( "

                                                                                                                                                                                    Version: %2

                                                                                                                                                                                    " ).arg( myVersionLog.value( QStringLiteral( "getCapabilitiesUrl" ) ), myVersion.isEmpty() ? QStringLiteral( "(empty)" ) : myVersion ); - if ( !myVersionLog.value( "error" ).isEmpty() ) + if ( !myVersionLog.value( QStringLiteral( "error" ) ).isEmpty() ) { // Server may have more errors, for each version //Q_FOREACH ( QString err, myServerLog.values( "error" ) ) //{ //myVersionReport += error( err ); //} - myVersionReport += error( myServerLog.value( "error" ) ); + myVersionReport += error( myServerLog.value( QStringLiteral( "error" ) ) ); myVersionErrCount++; } else { - myVersionReport += ""; + myVersionReport += QLatin1String( "
                                                                                                                                                                                    " ); myVersionReport += row( mHead ); QStringList filters; - filters << "*.log"; + filters << QStringLiteral( "*.log" ); myVersionDir.setNameFilters( filters ); Q_FOREACH ( const QString& myLogFileName, myVersionDir.entryList( QDir::Files ) ) { - if ( myLogFileName == "version.log" ) continue; + if ( myLogFileName == QLatin1String( "version.log" ) ) continue; myVersionCoverageCount++; myCoverageCount++; QString myLogPath = myVersionDir.absolutePath() + '/' + myLogFileName; QMapmyLog = readLog( myLogPath ); - myVersionReport += ""; + myVersionReport += QLatin1String( "" ); QStringList myValues; - myValues << QString( "%2" ).arg( myLog.value( "describeCoverageUrl" ), myLog.value( "identifier" ) ); + myValues << QStringLiteral( "%2" ).arg( myLog.value( QStringLiteral( "describeCoverageUrl" ) ), myLog.value( QStringLiteral( "identifier" ) ) ); //myValues << myLog.value( "hasSize" ); - myVersionReport += cells( myValues, "", 1, 2 ); + myVersionReport += cells( myValues, QLatin1String( "" ), 1, 2 ); myValues.clear(); - QStringList issues = issueDescriptions( myServerLog.value( "server" ), myLog.value( "identifier" ), myLog.value( "version" ) ); - QString issuesString = issues.join( "
                                                                                                                                                                                    " ); + QStringList issues = issueDescriptions( myServerLog.value( QStringLiteral( "server" ) ), myLog.value( QStringLiteral( "identifier" ) ), myLog.value( QStringLiteral( "version" ) ) ); + QString issuesString = issues.join( QStringLiteral( "
                                                                                                                                                                                    " ) ); QStringList providers; - providers << "wcs" << "gdal"; + providers << QStringLiteral( "wcs" ) << QStringLiteral( "gdal" ); bool hasErr = false; Q_FOREACH ( const QString& provider, providers ) @@ -660,26 +660,26 @@ void TestQgsWcsPublicServers::report() { myValues << myLog.value( provider + "_error" ); int offender = NoOffender; - if ( provider == "wcs" ) + if ( provider == QLatin1String( "wcs" ) ) { myValues << issuesString; - offender = issueOffender( myServerLog.value( "server" ), myLog.value( "identifier" ), myLog.value( "version" ) ); + offender = issueOffender( myServerLog.value( QStringLiteral( "server" ) ), myLog.value( QStringLiteral( "identifier" ) ), myLog.value( QStringLiteral( "version" ) ) ); myVersionErrCount++; hasErr = true; } QString cls; if ( offender == ServerOffender ) { - cls = "cell-err-server"; + cls = QStringLiteral( "cell-err-server" ); } else if ( offender == QgisOffender ) { - cls = "cell-err-qgis"; + cls = QStringLiteral( "cell-err-qgis" ); } else { - cls = "cell-err"; + cls = QStringLiteral( "cell-err" ); } myVersionReport += cells( myValues, cls, 12 ); myValues.clear(); @@ -689,7 +689,7 @@ void TestQgsWcsPublicServers::report() myValues << myLog.value( provider + "_crs" ); myValues << myLog.value( provider + "_width" ); myValues << myLog.value( provider + "_height" ); - myValues << QString( myLog.value( provider + "_extent" ) ).replace( ',', "
                                                                                                                                                                                    " ); + myValues << QString( myLog.value( provider + "_extent" ) ).replace( ',', QLatin1String( "
                                                                                                                                                                                    " ) ); myValues << ""; myValues << myLog.value( provider + "_bandCount" ); myValues << myLog.value( provider + "_srcType" ); @@ -704,8 +704,8 @@ void TestQgsWcsPublicServers::report() int myColorsCount = myLog.value( provider + "_colorsCount" ).toInt(); if ( myValuesCount < 4 ) { - cls = "cell-err"; - if ( provider == "wcs" ) + cls = QStringLiteral( "cell-err" ); + if ( provider == QLatin1String( "wcs" ) ) { myVersionErrCount++; myCoverageErrCount++; @@ -713,8 +713,8 @@ void TestQgsWcsPublicServers::report() } else if ( myColorsCount < 4 ) { - cls = "cell-warn"; - if ( provider == "wcs" ) + cls = QStringLiteral( "cell-warn" ); + if ( provider == QLatin1String( "wcs" ) ) { myVersionWarnCount++; myCoverageWarnCount++; @@ -724,7 +724,7 @@ void TestQgsWcsPublicServers::report() myValues.clear(); } } - myVersionReport += "\n"; + myVersionReport += QLatin1String( "\n" ); QString cls; if ( !issuesString.isEmpty() && !hasErr ) { @@ -732,19 +732,19 @@ void TestQgsWcsPublicServers::report() } else { - myValues << ""; - cls = "cell-empty"; + myValues << QLatin1String( "" ); + cls = QStringLiteral( "cell-empty" ); } myVersionReport += cells( myValues, cls, 24 ); myValues.clear(); - myVersionReport += "\n"; + myVersionReport += QLatin1String( "\n" ); } // coverages - myVersionReport += "
                                                                                                                                                                                    \n"; + myVersionReport += QLatin1String( "\n" ); // prepend counts - myVersionReport.prepend( QString( "Total coverages: %1
                                                                                                                                                                                    \n" ).arg( myVersionLog.value( "totalCoverages" ) ) + - QString( "Tested coverages: %1
                                                                                                                                                                                    \n" ).arg( myVersionCoverageCount ) + - QString( "Errors: %1
                                                                                                                                                                                    \n" ).arg( myVersionErrCount ) + - QString( "Warnings: %1

                                                                                                                                                                                    " ).arg( myVersionWarnCount ) ); + myVersionReport.prepend( QStringLiteral( "Total coverages: %1
                                                                                                                                                                                    \n" ).arg( myVersionLog.value( QStringLiteral( "totalCoverages" ) ) ) + + QStringLiteral( "Tested coverages: %1
                                                                                                                                                                                    \n" ).arg( myVersionCoverageCount ) + + QStringLiteral( "Errors: %1
                                                                                                                                                                                    \n" ).arg( myVersionErrCount ) + + QStringLiteral( "Warnings: %1

                                                                                                                                                                                    " ).arg( myVersionWarnCount ) ); myServerReport += myVersionReport; } if ( myVersionErrCount > 0 ) myServerErr = true; @@ -756,28 +756,28 @@ void TestQgsWcsPublicServers::report() } // servers QString mySettings = QgsApplication::showSettings(); - mySettings = mySettings.replace( '\n', "
                                                                                                                                                                                    " ); - QString myRep = "

                                                                                                                                                                                    WCS public servers test

                                                                                                                                                                                    \n"; + mySettings = mySettings.replace( '\n', QLatin1String( "
                                                                                                                                                                                    " ) ); + QString myRep = QStringLiteral( "

                                                                                                                                                                                    WCS public servers test

                                                                                                                                                                                    \n" ); myRep += "

                                                                                                                                                                                    " + mySettings + "

                                                                                                                                                                                    "; - myRep += ""; - - myRep += QString( "Servers: %1
                                                                                                                                                                                    \n" ).arg( myServerCount ); - myRep += QString( "Servers with error: %1
                                                                                                                                                                                    \n" ).arg( myServerErrCount ); - myRep += QString( "Servers with warning: %1
                                                                                                                                                                                    \n" ).arg( myServerWarnCount ); - myRep += QString( "Coverages: %1
                                                                                                                                                                                    \n" ).arg( myCoverageCount ); - myRep += QString( "Coverage errors: %1
                                                                                                                                                                                    \n" ).arg( myCoverageErrCount ); - myRep += QString( "Coverage warnings: %1
                                                                                                                                                                                    \n" ).arg( myCoverageWarnCount ); + myRep += QLatin1String( "" ); + + myRep += QStringLiteral( "Servers: %1
                                                                                                                                                                                    \n" ).arg( myServerCount ); + myRep += QStringLiteral( "Servers with error: %1
                                                                                                                                                                                    \n" ).arg( myServerErrCount ); + myRep += QStringLiteral( "Servers with warning: %1
                                                                                                                                                                                    \n" ).arg( myServerWarnCount ); + myRep += QStringLiteral( "Coverages: %1
                                                                                                                                                                                    \n" ).arg( myCoverageCount ); + myRep += QStringLiteral( "Coverage errors: %1
                                                                                                                                                                                    \n" ).arg( myCoverageErrCount ); + myRep += QStringLiteral( "Coverage warnings: %1
                                                                                                                                                                                    \n" ).arg( myCoverageWarnCount ); myRep += myReport; @@ -804,9 +804,9 @@ QMap TestQgsWcsPublicServers::readLog( const QString& theFileN QString TestQgsWcsPublicServers::error( const QString& theMessage ) { - QString myRow = "Error: "; + QString myRow = QStringLiteral( "Error: " ); myRow += theMessage; - myRow += ""; + myRow += QLatin1String( "" ); return myRow; } @@ -819,31 +819,31 @@ QString TestQgsWcsPublicServers::cells( const QStringList& theValues, const QStr QString colspanStr, rowspanStr; if ( colspan > 1 && i == theValues.size() - 1 ) { - colspanStr = QString( "colspan=%1" ).arg( colspan - theValues.size() + 1 ); + colspanStr = QStringLiteral( "colspan=%1" ).arg( colspan - theValues.size() + 1 ); } if ( rowspan > 1 ) { - rowspanStr = QString( "rowspan=%1" ).arg( rowspan ); + rowspanStr = QStringLiteral( "rowspan=%1" ).arg( rowspan ); } - myRow += QString( "%4" ).arg( theClass, colspanStr, rowspanStr, val ); + myRow += QStringLiteral( "%4" ).arg( theClass, colspanStr, rowspanStr, val ); } return myRow; } QString TestQgsWcsPublicServers::row( const QStringList& theValues, const QString& theClass ) { - QString myRow = ""; + QString myRow = QStringLiteral( "" ); for ( int i = 0; i < theValues.size(); i++ ) { QString val = theValues.value( i ); QString colspan; if ( theValues.size() < mHead.size() && i == ( theValues.size() - 1 ) ) { - colspan = QString( "colspan=%1" ).arg( mHead.size() - theValues.size() + 1 ); + colspan = QStringLiteral( "colspan=%1" ).arg( mHead.size() - theValues.size() + 1 ); } - myRow += QString( "%3" ).arg( theClass, colspan, val ); + myRow += QStringLiteral( "%3" ).arg( theClass, colspan, val ); } - myRow += "\n"; + myRow += QLatin1String( "\n" ); return myRow; } diff --git a/tests/src/providers/testqgswmscapabilities.cpp b/tests/src/providers/testqgswmscapabilities.cpp index 0f8a0d84dd40..099d8e87d9d0 100644 --- a/tests/src/providers/testqgswmscapabilities.cpp +++ b/tests/src/providers/testqgswmscapabilities.cpp @@ -44,7 +44,7 @@ class TestQgsWmsCapabilities: public QObject { QgsWmsCapabilities capabilities; - QFile file( QString( TEST_DATA_DIR ) + "/provider/GetCapabilities.xml" ); + QFile file( QStringLiteral( TEST_DATA_DIR ) + "/provider/GetCapabilities.xml" ); QVERIFY( file.open( QIODevice::ReadOnly | QIODevice::Text ) ); const QByteArray content = file.readAll(); QVERIFY( content.size() > 0 ); diff --git a/tests/src/providers/testqgswmsprovider.cpp b/tests/src/providers/testqgswmsprovider.cpp index 9b239cf24e21..c14e92bbbf3d 100644 --- a/tests/src/providers/testqgswmsprovider.cpp +++ b/tests/src/providers/testqgswmsprovider.cpp @@ -32,7 +32,7 @@ class TestQgsWmsProvider: public QObject QgsApplication::init(); QgsApplication::initQgis(); - QFile file( QString( TEST_DATA_DIR ) + "/provider/GetCapabilities.xml" ); + QFile file( QStringLiteral( TEST_DATA_DIR ) + "/provider/GetCapabilities.xml" ); QVERIFY( file.open( QIODevice::ReadOnly | QIODevice::Text ) ); const QByteArray content = file.readAll(); QVERIFY( content.size() > 0 ); @@ -51,26 +51,26 @@ class TestQgsWmsProvider: public QObject void legendGraphicsWithStyle() { - QgsWmsProvider provider( "http://localhost:8380/mapserv?xxx&layers=agri_zones&styles=fb_style&format=image/jpg", mCapabilities ); + QgsWmsProvider provider( QStringLiteral( "http://localhost:8380/mapserv?xxx&layers=agri_zones&styles=fb_style&format=image/jpg" ), mCapabilities ); QCOMPARE( provider.getLegendGraphicUrl(), QString( "http://www.example.com/fb.png?" ) ); } void legendGraphicsWithSecondStyle() { - QgsWmsProvider provider( "http://localhost:8380/mapserv?xxx&layers=agri_zones&styles=yt_style&format=image/jpg", mCapabilities ); + QgsWmsProvider provider( QStringLiteral( "http://localhost:8380/mapserv?xxx&layers=agri_zones&styles=yt_style&format=image/jpg" ), mCapabilities ); QCOMPARE( provider.getLegendGraphicUrl(), QString( "http://www.example.com/yt.png?" ) ); } void legendGraphicsWithoutStyleWithDefault() { - QgsWmsProvider provider( "http://localhost:8380/mapserv?xxx&layers=buildings&styles=&format=image/jpg", mCapabilities ); + QgsWmsProvider provider( QStringLiteral( "http://localhost:8380/mapserv?xxx&layers=buildings&styles=&format=image/jpg" ), mCapabilities ); //only one style, can guess default => use it QCOMPARE( provider.getLegendGraphicUrl(), QString( "http://www.example.com/buildings.png?" ) ); } void legendGraphicsWithoutStyleWithoutDefault() { - QgsWmsProvider provider( "http://localhost:8380/mapserv?xxx&layers=agri_zones&styles=&format=image/jpg", mCapabilities ); + QgsWmsProvider provider( QStringLiteral( "http://localhost:8380/mapserv?xxx&layers=agri_zones&styles=&format=image/jpg" ), mCapabilities ); //two style, cannot guess default => use the WMS GetLegendGraphics QCOMPARE( provider.getLegendGraphicUrl(), QString( "http://localhost:8380/mapserv?" ) ); } From 31cd7a81a3434e159920bd9ce40817ffcc40144a Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Mon, 24 Oct 2016 11:20:22 +0200 Subject: [PATCH 458/897] Add link to processing test document --- tests/README.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/README.md b/tests/README.md index 517b13da4482..a39c44f142c0 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,14 +1,12 @@ QGIS unit tests =============== -Build tests ------------ +# Build tests Make sure that you have enabled building of tests in CMake. `cmake -DENABLE_TESTS=ON ..` -Run tests ---------- +# Run tests You can run all tests using `make check`. @@ -41,10 +39,9 @@ with something like this: ``` -Advanced configuration ----------------------- +# Advanced configuration -### Postgres +## Postgres Make sure that you have enabled building of postgres test in CMake. `cmake -DENABLE_PGTEST=ON ..` @@ -74,3 +71,12 @@ For convenience, a shell script is provided to create the database and initialize it as needed: tests/testdata/provider/testdata_pg.sh + +# Write tests + +Instructions about wriing tests for the proessig framework +can be found in a local README file: + + ${TOP_SRCDIR}/python/plugins/processing/tests/README.md + +TODO: write more here From 96e7883b13f8e9bf0a603a25f8374f5450bdde10 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Mon, 24 Oct 2016 11:43:36 +0200 Subject: [PATCH 459/897] Add more links to test-relted README files --- tests/README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/README.md b/tests/README.md index a39c44f142c0..462eb12e511c 100644 --- a/tests/README.md +++ b/tests/README.md @@ -74,9 +74,19 @@ and initialize it as needed: # Write tests -Instructions about wriing tests for the proessig framework +Instructions about writing tests for the proessig framework can be found in a local README file: - ${TOP_SRCDIR}/python/plugins/processing/tests/README.md + ${TOP_SRCDIR}/python/plugins/processing/tests/README.md -TODO: write more here +Information about labeling tests design and organization: + + ${TOP_SRCDIR}/tests/testdata/labeling/README.rst + +WCS testing information can be found in: + + ${TOP_SRCDIR}/tests/testdata/raster/README.WCS + +Abot benchmark tests you can read: + + ${TOP_SRCDIR}/tests/bench/README From 8f13d4e2426a0496856570806e99047975b903cc Mon Sep 17 00:00:00 2001 From: Harrissou Sant-anna Date: Mon, 24 Oct 2016 12:29:08 +0200 Subject: [PATCH 460/897] typo fix --- tests/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/README.md b/tests/README.md index 462eb12e511c..dd6343833e2a 100644 --- a/tests/README.md +++ b/tests/README.md @@ -74,7 +74,7 @@ and initialize it as needed: # Write tests -Instructions about writing tests for the proessig framework +Instructions about writing tests for the processing framework can be found in a local README file: ${TOP_SRCDIR}/python/plugins/processing/tests/README.md @@ -87,6 +87,6 @@ WCS testing information can be found in: ${TOP_SRCDIR}/tests/testdata/raster/README.WCS -Abot benchmark tests you can read: +About benchmark tests you can read: ${TOP_SRCDIR}/tests/bench/README From cc0ada9f111ac10556d70094d48c4ea17a84e1a7 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 24 Oct 2016 14:37:28 +0200 Subject: [PATCH 461/897] Add a hyperlink to the processing tests readme --- tests/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/README.md b/tests/README.md index dd6343833e2a..88811e89a4b3 100644 --- a/tests/README.md +++ b/tests/README.md @@ -75,7 +75,7 @@ and initialize it as needed: # Write tests Instructions about writing tests for the processing framework -can be found in a local README file: +can be found in a [separate README file](../python/plugins/processing/tests/README.md): ${TOP_SRCDIR}/python/plugins/processing/tests/README.md From f84826d58d806e040937b1a8919f3af82d7a00b3 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Mon, 24 Oct 2016 17:01:58 +0200 Subject: [PATCH 462/897] [DB_Manager GPKG] Fix logic inversion in GDAL 1.X vs GDAL 2.X cases --- python/plugins/db_manager/db_plugins/gpkg/connector.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/db_manager/db_plugins/gpkg/connector.py b/python/plugins/db_manager/db_plugins/gpkg/connector.py index 07517248f59f..08776ff00c9b 100644 --- a/python/plugins/db_manager/db_plugins/gpkg/connector.py +++ b/python/plugins/db_manager/db_plugins/gpkg/connector.py @@ -181,7 +181,7 @@ def _execute(self, cursor, sql): return DBConnector._execute(self, cursor, sql) def _commit(self): - if not self.gdal2: + if self.gdal2: return try: From 794c8f3c85ff2415f10b9fb6640ff5be908dd4e4 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Mon, 24 Oct 2016 17:41:49 +0200 Subject: [PATCH 463/897] [DB_Manager GPKG] Fix creating and changing default values of columns --- .../db_manager/db_plugins/gpkg/connector.py | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/python/plugins/db_manager/db_plugins/gpkg/connector.py b/python/plugins/db_manager/db_plugins/gpkg/connector.py index 08776ff00c9b..aa6c6c423a41 100644 --- a/python/plugins/db_manager/db_plugins/gpkg/connector.py +++ b/python/plugins/db_manager/db_plugins/gpkg/connector.py @@ -505,12 +505,30 @@ def createOGRFieldDefnFromSQL(self, sql_fielddef): quoted_name = f_split[0] name = self.unquoteId(quoted_name) sql_type = f_split[1].upper() + if len(f_split) >= 3 and f_split[2].startswith('(') and f_split[2].endswith(')'): + sql_type += ' ' + f_split[2] + f_split = [f for f in f_split[3:]] + else: + f_split = [f for f in f_split[2:]] ogr_type, ogr_subtype, width = self.getOGRFieldTypeFromSQL(sql_type) fld_defn = ogr.FieldDefn(name, ogr_type) fld_defn.SetSubType(ogr_subtype) fld_defn.SetWidth(width) - if len(f_split) >= 4 and f_split[2] == 'NOT' and f_split[3] == 'NULL': + if len(f_split) >= 2 and f_split[0] == 'NOT' and f_split[1] == 'NULL': fld_defn.SetNullable(False) + f_split = [f for f in f_split[2:]] + elif len(f_split) >= 1: + f_split = [f for f in f_split[1:]] + if len(f_split) >= 2 and f_split[0] == 'DEFAULT': + new_default = f_split[1] + if new_default == '': + fld_defn.SetDefault(None) + elif new_default == 'NULL' or ogr_type in (ogr.OFTInteger, ogr.OFTReal): + fld_defn.SetDefault(new_default) + elif new_default.startswith("'") and new_default.endswith("'"): + fld_defn.SetDefault(new_default) + else: + fld_defn.SetDefault(self.quoteString(new_default)) return fld_defn def createTable(self, table, field_defs, pkey): @@ -641,6 +659,8 @@ def updateTableColumn(self, table, column, new_name, new_data_type=None, new_not new_fielddefn.SetDefault(None) elif new_default == 'NULL' or ogr_type in (ogr.OFTInteger, ogr.OFTReal): new_fielddefn.SetDefault(str(new_default)) + elif new_default.startswith("'") and new_default.endswith("'"): + new_fielddefn.SetDefault(str(new_default)) else: new_fielddefn.SetDefault(self.quoteString(new_default)) else: From af55c022b29c2b60fbe4e5acbf67f3cb8b571027 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 08:32:58 +1000 Subject: [PATCH 464/897] Followup 4166a3, don't use QStringLiteral in definitions Causes linker errors in some random cases --- src/analysis/network/qgsgraphbuilder.h | 2 +- src/analysis/network/qgsgraphbuilderintr.h | 2 +- src/analysis/vector/qgszonalstatistics.h | 2 +- src/app/pluginmanager/qgspluginsortfilterproxymodel.h | 2 +- src/app/qgisapp.h | 2 +- src/app/qgspluginregistry.h | 2 +- src/core/composer/qgscomposerlegenditem.h | 5 +---- src/core/geometry/qgsabstractgeometry.h | 4 ++-- src/core/geometry/qgscircularstring.h | 4 ++-- src/core/geometry/qgscompoundcurve.h | 4 ++-- src/core/geometry/qgscurvepolygon.h | 4 ++-- src/core/geometry/qgsgeometrycollection.h | 4 ++-- src/core/geometry/qgsgeometryutils.h | 2 +- src/core/geometry/qgslinestring.h | 4 ++-- src/core/geometry/qgsmulticurve.h | 4 ++-- src/core/geometry/qgsmultilinestring.h | 4 ++-- src/core/geometry/qgsmultipoint.h | 4 ++-- src/core/geometry/qgsmultipolygon.h | 4 ++-- src/core/geometry/qgsmultisurface.h | 4 ++-- src/core/geometry/qgspointv2.h | 4 ++-- src/core/qgsapplication.h | 6 +----- src/core/qgscolorramp.h | 5 +---- src/core/qgsdataprovider.h | 5 +---- src/core/qgsfontutils.h | 2 +- src/core/qgsmaplayer.h | 2 +- src/core/qgsprojectversion.h | 6 +----- src/core/qgsrenderchecker.h | 2 +- src/core/qgsvectorfilewriter.h | 6 +++--- src/core/qgsvirtuallayerdefinition.h | 4 ++-- src/core/raster/qgsrasterchecker.h | 2 +- src/core/raster/qgsrasterdataprovider.h | 2 +- src/core/raster/qgsrasterrenderer.h | 6 +----- src/core/symbology-ng/qgsfillsymbollayer.h | 6 +----- src/core/symbology-ng/qgsinvertedpolygonrenderer.h | 2 +- src/core/symbology-ng/qgspointdistancerenderer.h | 2 +- src/core/symbology-ng/qgsrenderer.h | 2 +- src/core/symbology-ng/qgsrulebasedrenderer.h | 4 ++-- src/core/symbology-ng/qgsstyle.h | 2 +- src/gui/auth/qgsauthguiutils.h | 6 +++--- src/gui/qgsbusyindicatordialog.h | 2 +- src/gui/qgscodeeditor.h | 2 +- src/gui/qgscolorbutton.h | 2 +- src/gui/qgsexpressionbuilderdialog.h | 6 +----- src/gui/qgsexpressionbuilderwidget.h | 10 +++++----- src/gui/qgsfieldvalidator.h | 7 +------ src/gui/qgsmanageconnectionsdialog.h | 9 ++++----- src/gui/qgsmapcanvas.h | 2 +- src/gui/qgsnewhttpconnection.h | 2 +- src/gui/qgsrasterformatsaveoptionswidget.h | 7 ++----- src/gui/qgsrasterpyramidsoptionswidget.h | 6 +----- src/gui/qgsshortcutsmanager.h | 2 +- src/gui/symbology-ng/qgssymbolslistwidget.h | 2 +- src/plugins/gps_importer/qgsbabelformat.h | 2 +- src/plugins/gps_importer/qgsgpsdevicedialog.h | 2 +- src/plugins/grass/qgsgrassmapcalc.h | 6 +++--- src/plugins/qgisplugin.h | 8 ++++---- src/providers/delimitedtext/qgsdelimitedtextfile.h | 2 +- src/providers/gdal/qgsgdalprovider.h | 2 +- src/providers/gpx/gpsdata.h | 6 +++--- src/providers/grass/qgsgrass.h | 2 +- src/providers/ogr/qgsogrprovider.h | 2 +- src/providers/postgres/qgspostgresconn.h | 2 +- src/providers/postgres/qgspostgresprovider.h | 2 +- src/providers/spatialite/qgsspatialiteprovider.h | 2 +- src/providers/virtual/qgsvirtuallayerprovider.h | 6 +++--- src/server/qgswmsserver.h | 4 ++-- 66 files changed, 102 insertions(+), 144 deletions(-) diff --git a/src/analysis/network/qgsgraphbuilder.h b/src/analysis/network/qgsgraphbuilder.h index 7ced28204dad..1a079a511b5d 100644 --- a/src/analysis/network/qgsgraphbuilder.h +++ b/src/analysis/network/qgsgraphbuilder.h @@ -39,7 +39,7 @@ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface /** * default constructor */ - QgsGraphBuilder( const QgsCoordinateReferenceSystem& crs, bool otfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = QStringLiteral( "WGS84" ) ); + QgsGraphBuilder( const QgsCoordinateReferenceSystem& crs, bool otfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ); ~QgsGraphBuilder(); diff --git a/src/analysis/network/qgsgraphbuilderintr.h b/src/analysis/network/qgsgraphbuilderintr.h index 6ffcca88d493..011be8541df6 100644 --- a/src/analysis/network/qgsgraphbuilderintr.h +++ b/src/analysis/network/qgsgraphbuilderintr.h @@ -41,7 +41,7 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface * @param topologyTolerance sqrt distance between source point as one graph vertex * @param ellipsoidID ellipsoid for edge measurement */ - QgsGraphBuilderInterface( const QgsCoordinateReferenceSystem& crs, bool ctfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = QStringLiteral( "WGS84" ) ) + QgsGraphBuilderInterface( const QgsCoordinateReferenceSystem& crs, bool ctfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ) : mCrs( crs ) , mCtfEnabled( ctfEnabled ) , mTopologyTolerance( topologyTolerance ) diff --git a/src/analysis/vector/qgszonalstatistics.h b/src/analysis/vector/qgszonalstatistics.h index d91bdef1b8ca..5044708a9130 100644 --- a/src/analysis/vector/qgszonalstatistics.h +++ b/src/analysis/vector/qgszonalstatistics.h @@ -55,7 +55,7 @@ class ANALYSIS_EXPORT QgsZonalStatistics /** * Constructor for QgsZonalStatistics. */ - QgsZonalStatistics( QgsVectorLayer* polygonLayer, const QString& rasterFile, const QString& attributePrefix = QLatin1String( "" ), int rasterBand = 1, + QgsZonalStatistics( QgsVectorLayer* polygonLayer, const QString& rasterFile, const QString& attributePrefix = "", int rasterBand = 1, Statistics stats = Statistics( Count | Sum | Mean ) ); /** Starts the calculation diff --git a/src/app/pluginmanager/qgspluginsortfilterproxymodel.h b/src/app/pluginmanager/qgspluginsortfilterproxymodel.h index 4ee7807ec3b8..827800d2a5f0 100644 --- a/src/app/pluginmanager/qgspluginsortfilterproxymodel.h +++ b/src/app/pluginmanager/qgspluginsortfilterproxymodel.h @@ -49,7 +49,7 @@ class QgsPluginSortFilterProxyModel : public QSortFilterProxyModel void setAcceptedStatuses( const QStringList& statuses ); //! (Re)configire the spacer filter - void setAcceptedSpacers( const QString& spacers = QStringLiteral( "" ) ); + void setAcceptedSpacers( const QString& spacers = "" ); //! Return number of item with status filter matching (no other filters are considered) int countWithCurrentStatus(); diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index 315cbe9d4dc0..26b15e59b467 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -230,7 +230,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void addUserInputWidget( QWidget* widget ); //! Set theme (icons) - void setTheme( const QString& themeName = QStringLiteral( "default" ) ); + void setTheme( const QString& themeName = "default" ); void setIconSizes( int size ); diff --git a/src/app/qgspluginregistry.h b/src/app/qgspluginregistry.h index e5565573511a..7403e8b60371 100644 --- a/src/app/qgspluginregistry.h +++ b/src/app/qgspluginregistry.h @@ -104,7 +104,7 @@ class APP_EXPORT QgsPluginRegistry //! Check current QGIS version against requested minimal and optionally maximal QGIS version //! if maxVersion not specified, the default value is assumed: floor(minVersion) + 0.99.99 - bool checkQgisVersion( const QString& minVersion, const QString& maxVersion = QLatin1String( "" ) ) const; + bool checkQgisVersion( const QString& minVersion, const QString& maxVersion = "" ) const; private: static QgsPluginRegistry* _instance; diff --git a/src/core/composer/qgscomposerlegenditem.h b/src/core/composer/qgscomposerlegenditem.h index 9a8571c7183b..99d65376d40a 100644 --- a/src/core/composer/qgscomposerlegenditem.h +++ b/src/core/composer/qgscomposerlegenditem.h @@ -157,10 +157,7 @@ class CORE_EXPORT QgsComposerLayerItem : public QgsComposerLegendItem void setShowFeatureCount( bool show ) { mShowFeatureCount = show; } bool showFeatureCount() const { return mShowFeatureCount; } - /** - * Sets the legend layer item to the appropriate default style for the specified legend rule. - */ - void setDefaultStyle( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ); + void setDefaultStyle( double scaleDenominator = -1, const QString& rule = "" ); private: QString mLayerID; diff --git a/src/core/geometry/qgsabstractgeometry.h b/src/core/geometry/qgsabstractgeometry.h index 6f69bdaf36ba..9db4b2f440d2 100644 --- a/src/core/geometry/qgsabstractgeometry.h +++ b/src/core/geometry/qgsabstractgeometry.h @@ -168,7 +168,7 @@ class CORE_EXPORT QgsAbstractGeometry * @see asGML3 * @see asJSON */ - virtual QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const = 0; + virtual QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const = 0; /** Returns a GML3 representation of the geometry. * @param doc DOM document @@ -179,7 +179,7 @@ class CORE_EXPORT QgsAbstractGeometry * @see asGML2 * @see asJSON */ - virtual QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const = 0; + virtual QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const = 0; /** Returns a GeoJSON representation of the geometry. * @param precision number of decimal places for coordinates diff --git a/src/core/geometry/qgscircularstring.h b/src/core/geometry/qgscircularstring.h index 0fe51cf6920e..cbf52042fdee 100644 --- a/src/core/geometry/qgscircularstring.h +++ b/src/core/geometry/qgscircularstring.h @@ -47,8 +47,8 @@ class CORE_EXPORT QgsCircularString: public QgsCurve int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; int numPoints() const override; diff --git a/src/core/geometry/qgscompoundcurve.h b/src/core/geometry/qgscompoundcurve.h index 8dc973ac4a3d..fcc03d4de4d3 100644 --- a/src/core/geometry/qgscompoundcurve.h +++ b/src/core/geometry/qgscompoundcurve.h @@ -48,8 +48,8 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; //curve interface diff --git a/src/core/geometry/qgscurvepolygon.h b/src/core/geometry/qgscurvepolygon.h index 8230a4e8695c..0dc0f84cc538 100644 --- a/src/core/geometry/qgscurvepolygon.h +++ b/src/core/geometry/qgscurvepolygon.h @@ -47,8 +47,8 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; //surface interface diff --git a/src/core/geometry/qgsgeometrycollection.h b/src/core/geometry/qgsgeometrycollection.h index 1e75edee163d..d644b967de77 100644 --- a/src/core/geometry/qgsgeometrycollection.h +++ b/src/core/geometry/qgsgeometrycollection.h @@ -84,8 +84,8 @@ class CORE_EXPORT QgsGeometryCollection: public QgsAbstractGeometry int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; virtual QgsRectangle boundingBox() const override; diff --git a/src/core/geometry/qgsgeometryutils.h b/src/core/geometry/qgsgeometryutils.h index 7d0a73e82636..412b790add07 100644 --- a/src/core/geometry/qgsgeometryutils.h +++ b/src/core/geometry/qgsgeometryutils.h @@ -240,7 +240,7 @@ class CORE_EXPORT QgsGeometryUtils * @param defaultType default geometry type for childen * @returns list of WKT child block strings, eg List("TYPE1 (contents1)", "TYPE2 (TYPE3 (contents3), TYPE4 (contents4))") */ - static QStringList wktGetChildBlocks( const QString& wkt , const QString &defaultType = QLatin1String( "" ) ); + static QStringList wktGetChildBlocks( const QString& wkt , const QString &defaultType = "" ); enum componentType { diff --git a/src/core/geometry/qgslinestring.h b/src/core/geometry/qgslinestring.h index 32c52379c0a9..1485904a33bc 100644 --- a/src/core/geometry/qgslinestring.h +++ b/src/core/geometry/qgslinestring.h @@ -133,8 +133,8 @@ class CORE_EXPORT QgsLineString: public QgsCurve int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; //curve interface diff --git a/src/core/geometry/qgsmulticurve.h b/src/core/geometry/qgsmulticurve.h index 306e858ccd69..853fce2a9aa9 100644 --- a/src/core/geometry/qgsmulticurve.h +++ b/src/core/geometry/qgsmulticurve.h @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiCurve: public QgsGeometryCollection // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; /** Adds a geometry and takes ownership. Returns true in case of success*/ diff --git a/src/core/geometry/qgsmultilinestring.h b/src/core/geometry/qgsmultilinestring.h index 7da12d5b7708..ddbda4d9b821 100644 --- a/src/core/geometry/qgsmultilinestring.h +++ b/src/core/geometry/qgsmultilinestring.h @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiLineString: public QgsMultiCurve // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; /** Adds a geometry and takes ownership. Returns true in case of success*/ diff --git a/src/core/geometry/qgsmultipoint.h b/src/core/geometry/qgsmultipoint.h index 996102601fc7..c3b793ad7635 100644 --- a/src/core/geometry/qgsmultipoint.h +++ b/src/core/geometry/qgsmultipoint.h @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiPointV2: public QgsGeometryCollection // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; diff --git a/src/core/geometry/qgsmultipolygon.h b/src/core/geometry/qgsmultipolygon.h index 1b72ac540104..faeda2128dfd 100644 --- a/src/core/geometry/qgsmultipolygon.h +++ b/src/core/geometry/qgsmultipolygon.h @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiPolygonV2: public QgsMultiSurface // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; /** Adds a geometry and takes ownership. Returns true in case of success*/ diff --git a/src/core/geometry/qgsmultisurface.h b/src/core/geometry/qgsmultisurface.h index 73dbab458312..6a198b70d004 100644 --- a/src/core/geometry/qgsmultisurface.h +++ b/src/core/geometry/qgsmultisurface.h @@ -36,8 +36,8 @@ class CORE_EXPORT QgsMultiSurface: public QgsGeometryCollection // inherited: int wkbSize() const; // inherited: unsigned char* asWkb( int& binarySize ) const; // inherited: QString asWkt( int precision = 17 ) const; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; diff --git a/src/core/geometry/qgspointv2.h b/src/core/geometry/qgspointv2.h index 167b0faed009..2fc43db99832 100644 --- a/src/core/geometry/qgspointv2.h +++ b/src/core/geometry/qgspointv2.h @@ -162,8 +162,8 @@ class CORE_EXPORT QgsPointV2: public QgsAbstractGeometry int wkbSize() const override; unsigned char* asWkb( int& binarySize ) const override; QString asWkt( int precision = 17 ) const override; - QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; - QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = QStringLiteral( "gml" ) ) const override; + QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; + QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; void draw( QPainter& p ) const override; void transform( const QgsCoordinateTransform& ct, QgsCoordinateTransform::TransformDirection d = QgsCoordinateTransform::ForwardTransform, diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index f64d46f057c5..cb468852a3fd 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -38,11 +38,7 @@ class CORE_EXPORT QgsApplication : public QApplication static const char* QGIS_ORGANIZATION_NAME; static const char* QGIS_ORGANIZATION_DOMAIN; static const char* QGIS_APPLICATION_NAME; - - /** - * Constructor for QgsApplication. - */ - QgsApplication( int & argc, char ** argv, bool GUIenabled, const QString& customConfigPath = QString(), const QString& platformName = QStringLiteral( "desktop" ) ); + QgsApplication( int & argc, char ** argv, bool GUIenabled, const QString& customConfigPath = QString(), const QString& platformName = "desktop" ); virtual ~QgsApplication(); /** This method initialises paths etc for QGIS. Called by the ctor or call it manually diff --git a/src/core/qgscolorramp.h b/src/core/qgscolorramp.h index 6543d2ebf1e4..ff7c504dccf7 100644 --- a/src/core/qgscolorramp.h +++ b/src/core/qgscolorramp.h @@ -553,10 +553,7 @@ class CORE_EXPORT QgsCptCityColorRamp : public QgsGradientColorRamp void setSchemeName( const QString& schemeName ) { mSchemeName = schemeName; mFileLoaded = false; } void setVariantName( const QString& variantName ) { mVariantName = variantName; mFileLoaded = false; } void setVariantList( const QStringList& variantList ) { mVariantList = variantList; } - /** - * Sets the name for the color ramp, based on a scheme, variant and list of variants. - */ - void setName( const QString& schemeName, const QString& variantName = QLatin1String( "" ), const QStringList& variantList = QStringList() ) + void setName( const QString& schemeName, const QString& variantName = "", const QStringList& variantList = QStringList() ) { mSchemeName = schemeName; mVariantName = variantName; mVariantList = variantList; mFileLoaded = false; } void loadPalette() { loadFile(); } diff --git a/src/core/qgsdataprovider.h b/src/core/qgsdataprovider.h index e682f03873ca..ba32bba08d3b 100644 --- a/src/core/qgsdataprovider.h +++ b/src/core/qgsdataprovider.h @@ -74,10 +74,7 @@ class CORE_EXPORT QgsDataProvider : public QObject CustomData = 3000 //!< Custom properties for 3rd party providers or very provider-specific properties which are not expected to be of interest for other providers can be added starting from this value up. }; - /** - * Constructor for QgsDataProvider. - */ - QgsDataProvider( QString const & uri = QLatin1String( "" ) ) + QgsDataProvider( QString const & uri = "" ) : mDataSourceURI( uri ) {} diff --git a/src/core/qgsfontutils.h b/src/core/qgsfontutils.h index 9e37aad8a75c..c0956b98be5a 100644 --- a/src/core/qgsfontutils.h +++ b/src/core/qgsfontutils.h @@ -82,7 +82,7 @@ class CORE_EXPORT QgsFontUtils * @returns QFont * @note Added in QGIS 2.1 */ - static QFont getStandardTestFont( const QString& style = QStringLiteral( "Roman" ), int pointsize = 12 ); + static QFont getStandardTestFont( const QString& style = "Roman", int pointsize = 12 ); /** Returns a DOM element containing the properties of the font. * @param font font diff --git a/src/core/qgsmaplayer.h b/src/core/qgsmaplayer.h index 848572cbd24e..5f86f5793c5f 100644 --- a/src/core/qgsmaplayer.h +++ b/src/core/qgsmaplayer.h @@ -790,7 +790,7 @@ class CORE_EXPORT QgsMapLayer : public QObject /** Read custom properties from project file. @param layerNode note to read from @param keyStartsWith reads only properties starting with the specified string (or all if the string is empty)*/ - void readCustomProperties( const QDomNode& layerNode, const QString& keyStartsWith = QLatin1String( "" ) ); + void readCustomProperties( const QDomNode& layerNode, const QString& keyStartsWith = "" ); /** Write custom properties to project file. */ void writeCustomProperties( QDomNode & layerNode, QDomDocument & doc ) const; diff --git a/src/core/qgsprojectversion.h b/src/core/qgsprojectversion.h index 4ac064615e3a..1e768a55c5e8 100644 --- a/src/core/qgsprojectversion.h +++ b/src/core/qgsprojectversion.h @@ -38,11 +38,7 @@ class CORE_EXPORT QgsProjectVersion , mSub( 0 ) {} ~QgsProjectVersion() {} - - /** - * Constructor for QgsProjectVersion which accepts a major, minor and sub version number and a release name. - */ - QgsProjectVersion( int major, int minor, int sub, const QString& name = QLatin1String( "" ) ); + QgsProjectVersion( int major, int minor, int sub, const QString& name = "" ); QgsProjectVersion( const QString& string ); int majorVersion() { return mMajor;} int minorVersion() { return mMinor;} diff --git a/src/core/qgsrenderchecker.h b/src/core/qgsrenderchecker.h index 1ec735be0298..aff922ad90b3 100644 --- a/src/core/qgsrenderchecker.h +++ b/src/core/qgsrenderchecker.h @@ -124,7 +124,7 @@ class CORE_EXPORT QgsRenderChecker * @param theRenderedImageFile to optionally override the output filename * @note: make sure to call setExpectedImage and setRenderedImage first. */ - bool compareImages( const QString& theTestName, unsigned int theMismatchCount = 0, const QString& theRenderedImageFile = QLatin1String( "" ) ); + bool compareImages( const QString& theTestName, unsigned int theMismatchCount = 0, const QString& theRenderedImageFile = "" ); /** Get a list of all the anomalies. An anomaly is a rendered difference * file where there is some red pixel content (indicating a render check * mismatch), but where the output was still acceptible. If the render diff --git a/src/core/qgsvectorfilewriter.h b/src/core/qgsvectorfilewriter.h index 034cc8c4beed..af9f44ac6f4b 100644 --- a/src/core/qgsvectorfilewriter.h +++ b/src/core/qgsvectorfilewriter.h @@ -264,7 +264,7 @@ class CORE_EXPORT QgsVectorFileWriter const QString& fileName, const QString& fileEncoding, const QgsCoordinateReferenceSystem& destCRS = QgsCoordinateReferenceSystem(), - const QString& driverName = QStringLiteral( "ESRI Shapefile" ), + const QString& driverName = "ESRI Shapefile", bool onlySelected = false, QString *errorMessage = nullptr, const QStringList &datasourceOptions = QStringList(), @@ -309,7 +309,7 @@ class CORE_EXPORT QgsVectorFileWriter const QString& fileName, const QString& fileEncoding, const QgsCoordinateTransform& ct, - const QString& driverName = QStringLiteral( "ESRI Shapefile" ), + const QString& driverName = "ESRI Shapefile", bool onlySelected = false, QString *errorMessage = nullptr, const QStringList &datasourceOptions = QStringList(), @@ -414,7 +414,7 @@ class CORE_EXPORT QgsVectorFileWriter const QgsFields& fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem& srs = QgsCoordinateReferenceSystem(), - const QString& driverName = QStringLiteral( "ESRI Shapefile" ), + const QString& driverName = "ESRI Shapefile", const QStringList &datasourceOptions = QStringList(), const QStringList &layerOptions = QStringList(), QString *newFilename = nullptr, diff --git a/src/core/qgsvirtuallayerdefinition.h b/src/core/qgsvirtuallayerdefinition.h index e9a4a2eb5653..af04f5f05df0 100644 --- a/src/core/qgsvirtuallayerdefinition.h +++ b/src/core/qgsvirtuallayerdefinition.h @@ -76,7 +76,7 @@ class CORE_EXPORT QgsVirtualLayerDefinition }; //! Constructor with an optional file path - QgsVirtualLayerDefinition( const QString& filePath = QStringLiteral( "" ) ); + QgsVirtualLayerDefinition( const QString& filePath = "" ); //! Constructor to build a definition from a QUrl //! The path part of the URL is extracted as well as the following optional keys: @@ -102,7 +102,7 @@ class CORE_EXPORT QgsVirtualLayerDefinition void addSource( const QString& name, const QString& ref ); //! Add a layer with a source, a provider and an encoding - void addSource( const QString& name, const QString& source, const QString& provider, const QString& encoding = QStringLiteral( "" ) ); + void addSource( const QString& name, const QString& source, const QString& provider, const QString& encoding = "" ); //! List of source layers typedef QList SourceLayers; diff --git a/src/core/raster/qgsrasterchecker.h b/src/core/raster/qgsrasterchecker.h index 8f31e7440af3..2582311d73e0 100644 --- a/src/core/raster/qgsrasterchecker.h +++ b/src/core/raster/qgsrasterchecker.h @@ -61,7 +61,7 @@ class CORE_EXPORT QgsRasterChecker bool compare( double verifiedVal, double expectedVal, double theTolerance ); void compare( const QString& theParamName, int verifiedVal, int expectedVal, QString &theReport, bool &theOk ); void compare( const QString& theParamName, double verifiedVal, double expectedVal, QString &theReport, bool &theOk, double theTolerance = 0 ); - void compareRow( const QString& theParamName, const QString& verifiedVal, const QString& expectedVal, QString &theReport, bool theOk, const QString& theDifference = QStringLiteral( "" ), const QString& theTolerance = QStringLiteral( "" ) ); + void compareRow( const QString& theParamName, const QString& verifiedVal, const QString& expectedVal, QString &theReport, bool theOk, const QString& theDifference = "", const QString& theTolerance = "" ); double tolerance( double val, int places = 6 ); }; // class QgsRasterChecker diff --git a/src/core/raster/qgsrasterdataprovider.h b/src/core/raster/qgsrasterdataprovider.h index ab562332e171..6560e7499dc0 100644 --- a/src/core/raster/qgsrasterdataprovider.h +++ b/src/core/raster/qgsrasterdataprovider.h @@ -268,7 +268,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast /** \brief Create pyramid overviews */ virtual QString buildPyramids( const QList & thePyramidList, - const QString & theResamplingMethod = QStringLiteral( "NEAREST" ), + const QString & theResamplingMethod = "NEAREST", QgsRaster::RasterPyramidsFormat theFormat = QgsRaster::PyramidsGTiff, const QStringList & theConfigOptions = QStringList() ) { diff --git a/src/core/raster/qgsrasterrenderer.h b/src/core/raster/qgsrasterrenderer.h index bc1ae595b563..d6ef8b9c8bb5 100644 --- a/src/core/raster/qgsrasterrenderer.h +++ b/src/core/raster/qgsrasterrenderer.h @@ -55,11 +55,7 @@ class CORE_EXPORT QgsRasterRenderer : public QgsRasterInterface static const QRgb NODATA_COLOR; - /** - * Constructor for QgsRasterRenderer. - */ - QgsRasterRenderer( QgsRasterInterface* input = nullptr, const QString& type = QLatin1String( "" ) ); - + QgsRasterRenderer( QgsRasterInterface* input = nullptr, const QString& type = "" ); virtual ~QgsRasterRenderer(); QgsRasterRenderer * clone() const override = 0; diff --git a/src/core/symbology-ng/qgsfillsymbollayer.h b/src/core/symbology-ng/qgsfillsymbollayer.h index 640c3a20bd23..837a32af3486 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.h +++ b/src/core/symbology-ng/qgsfillsymbollayer.h @@ -817,11 +817,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer class CORE_EXPORT QgsSVGFillSymbolLayer: public QgsImageFillSymbolLayer { public: - - /** - * Constructor for QgsSVGFillSymbolLayer which accepts the path to an SVG file. - */ - QgsSVGFillSymbolLayer( const QString& svgFilePath = QLatin1String( "" ), double width = 20, double rotation = 0.0 ); + QgsSVGFillSymbolLayer( const QString& svgFilePath = "", double width = 20, double rotation = 0.0 ); QgsSVGFillSymbolLayer( const QByteArray& svgData, double width = 20, double rotation = 0.0 ); ~QgsSVGFillSymbolLayer(); diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h index c83f78a70c80..a7e510acff2e 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h @@ -94,7 +94,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer /** Proxy that will call this method on the embedded renderer. * @note not available in python bindings */ - virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) override; + virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; /** Proxy that will call this method on the embedded renderer. */ virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index 10e27dd06ab8..21f34ae67d3f 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -87,7 +87,7 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer virtual void startRender( QgsRenderContext& context, const QgsFields& fields ) override; void stopRender( QgsRenderContext& context ) override; QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ) override; - QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) override; + QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; void setEmbeddedRenderer( QgsFeatureRenderer* r ) override; const QgsFeatureRenderer* embeddedRenderer() const override; void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) override; diff --git a/src/core/symbology-ng/qgsrenderer.h b/src/core/symbology-ng/qgsrenderer.h index 5299f8eafd7d..2aa547305c6f 100644 --- a/src/core/symbology-ng/qgsrenderer.h +++ b/src/core/symbology-ng/qgsrenderer.h @@ -270,7 +270,7 @@ class CORE_EXPORT QgsFeatureRenderer //! return a list of item text / symbol //! @note not available in python bindings - virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ); + virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ); //! Return a list of symbology items for the legend. Better choice than legendSymbolItems(). //! Default fallback implementation just uses legendSymbolItems() implementation diff --git a/src/core/symbology-ng/qgsrulebasedrenderer.h b/src/core/symbology-ng/qgsrulebasedrenderer.h index f62b7cde9280..e7e299939abf 100644 --- a/src/core/symbology-ng/qgsrulebasedrenderer.h +++ b/src/core/symbology-ng/qgsrulebasedrenderer.h @@ -145,7 +145,7 @@ class CORE_EXPORT QgsRuleBasedRenderer : public QgsFeatureRenderer QgsSymbolList symbols( const QgsRenderContext& context = QgsRenderContext() ) const; //! @note not available in python bindings - QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) const; + QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) const; //! @note added in 2.6 QgsLegendSymbolListV2 legendSymbolItemsV2( int currentLevel = -1 ) const; @@ -440,7 +440,7 @@ class CORE_EXPORT QgsRuleBasedRenderer : public QgsFeatureRenderer virtual void checkLegendSymbolItem( const QString& key, bool state = true ) override; virtual void setLegendSymbolItem( const QString& key, QgsSymbol* symbol ) override; - virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = QLatin1String( "" ) ) override; + virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; virtual QgsLegendSymbolListV2 legendSymbolItemsV2() const override; virtual QString dump() const override; virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index 4593e1ed84a8..6c0edcf32629 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -131,7 +131,7 @@ class CORE_EXPORT QgsStyle : public QObject QStringList tags() const; //! return a map of groupid and names for the given parent group - QgsSymbolGroupMap childGroupNames( const QString& parent = QStringLiteral( "" ) ); + QgsSymbolGroupMap childGroupNames( const QString& parent = "" ); //! remove all contents of the style void clear(); diff --git a/src/gui/auth/qgsauthguiutils.h b/src/gui/auth/qgsauthguiutils.h index b06fd7caecde..3ec09b6485d3 100644 --- a/src/gui/auth/qgsauthguiutils.h +++ b/src/gui/auth/qgsauthguiutils.h @@ -44,13 +44,13 @@ class GUI_EXPORT QgsAuthGuiUtils static QColor yellowColor(); /** Green text stylesheet representing valid, trusted, etc. certificate */ - static QString greenTextStyleSheet( const QString& selector = QStringLiteral( "*" ) ); + static QString greenTextStyleSheet( const QString& selector = "*" ); /** Orange text stylesheet representing loaded component, but not stored in database */ - static QString orangeTextStyleSheet( const QString& selector = QStringLiteral( "*" ) ); + static QString orangeTextStyleSheet( const QString& selector = "*" ); /** Red text stylesheet representing invalid, untrusted, etc. certificate */ - static QString redTextStyleSheet( const QString& selector = QStringLiteral( "*" ) ); + static QString redTextStyleSheet( const QString& selector = "*" ); /** Verify the authentication system is active, else notify user */ diff --git a/src/gui/qgsbusyindicatordialog.h b/src/gui/qgsbusyindicatordialog.h index 5765601f0fe4..bf17c945116c 100644 --- a/src/gui/qgsbusyindicatordialog.h +++ b/src/gui/qgsbusyindicatordialog.h @@ -38,7 +38,7 @@ class GUI_EXPORT QgsBusyIndicatorDialog : public QDialog * @param parent parent object (owner) * @param fl widget flags */ - QgsBusyIndicatorDialog( const QString& message = QStringLiteral( "" ), QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); + QgsBusyIndicatorDialog( const QString& message = "", QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); ~QgsBusyIndicatorDialog(); QString message() const { return mMessage; } diff --git a/src/gui/qgscodeeditor.h b/src/gui/qgscodeeditor.h index c06e0e9ed0a8..16ddbf346e25 100644 --- a/src/gui/qgscodeeditor.h +++ b/src/gui/qgscodeeditor.h @@ -43,7 +43,7 @@ class GUI_EXPORT QgsCodeEditor : public QsciScintilla * @param margin false: Enable margin for code editor * @note added in 2.6 */ - QgsCodeEditor( QWidget *parent = nullptr, const QString& title = QLatin1String( "" ), bool folding = false, bool margin = false ); + QgsCodeEditor( QWidget *parent = nullptr, const QString& title = "", bool folding = false, bool margin = false ); ~QgsCodeEditor(); /** Set the widget title diff --git a/src/gui/qgscolorbutton.h b/src/gui/qgscolorbutton.h index d69f29fdaaa2..c8488ba5b552 100644 --- a/src/gui/qgscolorbutton.h +++ b/src/gui/qgscolorbutton.h @@ -62,7 +62,7 @@ class GUI_EXPORT QgsColorButton : public QToolButton * @param registry a color scheme registry for color swatch grids to show in the drop down menu. If not * specified, the button will use the global color scheme registry */ - QgsColorButton( QWidget *parent = nullptr, const QString& cdt = QLatin1String( "" ), QgsColorSchemeRegistry* registry = nullptr ); + QgsColorButton( QWidget *parent = nullptr, const QString& cdt = "", QgsColorSchemeRegistry* registry = nullptr ); virtual ~QgsColorButton(); diff --git a/src/gui/qgsexpressionbuilderdialog.h b/src/gui/qgsexpressionbuilderdialog.h index 8b9c5cc84bd4..0e97b6d7469c 100644 --- a/src/gui/qgsexpressionbuilderdialog.h +++ b/src/gui/qgsexpressionbuilderdialog.h @@ -28,11 +28,7 @@ class GUI_EXPORT QgsExpressionBuilderDialog : public QDialog, private Ui::QgsExp Q_OBJECT public: - - /** - * Constructor for QgsExpressionBuilderDialog. - */ - QgsExpressionBuilderDialog( QgsVectorLayer* layer, const QString& startText = QString(), QWidget* parent = nullptr, const QString& key = QStringLiteral( "generic" ), + QgsExpressionBuilderDialog( QgsVectorLayer* layer, const QString& startText = QString(), QWidget* parent = nullptr, const QString& key = "generic", const QgsExpressionContext& context = QgsExpressionContext() ); /** The builder widget that is used by the dialog */ diff --git a/src/gui/qgsexpressionbuilderwidget.h b/src/gui/qgsexpressionbuilderwidget.h index aeea83817f03..453abb7d7917 100644 --- a/src/gui/qgsexpressionbuilderwidget.h +++ b/src/gui/qgsexpressionbuilderwidget.h @@ -183,7 +183,7 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp * @param sortOrder sort ranking for item */ void registerItem( const QString& group, const QString& label, const QString& expressionText, - const QString& helpText = QLatin1String( "" ), + const QString& helpText = "", QgsExpressionItem::ItemType type = QgsExpressionItem::ExpressionNode, bool highlightedItem = false, int sortOrder = 1 ); @@ -193,17 +193,17 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp * Adds the current expression to the given collection. * By default it is saved to the collection "generic". */ - void saveToRecent( const QString& collection = QStringLiteral( "generic" ) ); + void saveToRecent( const QString& collection = "generic" ); /** * Loads the recent expressions from the given collection. * By default it is loaded from the collection "generic". */ - void loadRecent( const QString& collection = QStringLiteral( "generic" ) ); + void loadRecent( const QString& collection = "generic" ); /** Create a new file in the function editor */ - void newFunctionFile( const QString& fileName = QStringLiteral( "scratch" ) ); + void newFunctionFile( const QString& fileName = "scratch" ); /** Save the current function editor text to the given file. */ @@ -291,7 +291,7 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp * @param sortOrder sort ranking for item */ void registerItemForAllGroups( const QStringList& groups, const QString& label, const QString& expressionText, - const QString& helpText = QLatin1String( "" ), + const QString& helpText = "", QgsExpressionItem::ItemType type = QgsExpressionItem::ExpressionNode, bool highlightedItem = false, int sortOrder = 1 ); diff --git a/src/gui/qgsfieldvalidator.h b/src/gui/qgsfieldvalidator.h index a8c353e8072d..82393a67cab9 100644 --- a/src/gui/qgsfieldvalidator.h +++ b/src/gui/qgsfieldvalidator.h @@ -33,12 +33,7 @@ class GUI_EXPORT QgsFieldValidator : public QValidator Q_OBJECT public: - - /** - * Constructor for QgsFieldValidator. - */ - QgsFieldValidator( QObject *parent, const QgsField &field, const QString& defaultValue, const QString& dateFormat = QStringLiteral( "yyyy-MM-dd" ) ); - + QgsFieldValidator( QObject *parent, const QgsField &field, const QString& defaultValue, const QString& dateFormat = "yyyy-MM-dd" ); ~QgsFieldValidator(); virtual State validate( QString &, int & ) const override; diff --git a/src/gui/qgsmanageconnectionsdialog.h b/src/gui/qgsmanageconnectionsdialog.h index c533d3c33e7f..9f5bb4471145 100644 --- a/src/gui/qgsmanageconnectionsdialog.h +++ b/src/gui/qgsmanageconnectionsdialog.h @@ -47,11 +47,10 @@ class GUI_EXPORT QgsManageConnectionsDialog : public QDialog, private Ui::QgsMan Oracle, }; - /** - * Constructor for QgsManageConnectionsDialog. The mode argument must be 0 for export and 1 for import. - * The type argument must be 0 for WMS and 1 for PostGIS. - */ - QgsManageConnectionsDialog( QWidget *parent = nullptr, Mode mode = Export, Type type = WMS, const QString& fileName = QStringLiteral( "" ) ); + // constructor + // mode argument must be 0 for export and 1 for import + // type argument must be 0 for WMS and 1 for PostGIS + QgsManageConnectionsDialog( QWidget *parent = nullptr, Mode mode = Export, Type type = WMS, const QString& fileName = "" ); public slots: void doExportImport(); diff --git a/src/gui/qgsmapcanvas.h b/src/gui/qgsmapcanvas.h index 996a9a6340bf..54ae4af82f09 100644 --- a/src/gui/qgsmapcanvas.h +++ b/src/gui/qgsmapcanvas.h @@ -438,7 +438,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView void selectionChangedSlot(); //! Save the convtents of the map canvas to disk as an image - void saveAsImage( const QString& theFileName, QPixmap * QPixmap = nullptr, const QString& = QStringLiteral( "PNG" ) ); + void saveAsImage( const QString& theFileName, QPixmap * QPixmap = nullptr, const QString& = "PNG" ); //! This slot is connected to the visibility change of one or more layers void layerStateChange(); diff --git a/src/gui/qgsnewhttpconnection.h b/src/gui/qgsnewhttpconnection.h index c898961cf02d..975c6706c855 100644 --- a/src/gui/qgsnewhttpconnection.h +++ b/src/gui/qgsnewhttpconnection.h @@ -32,7 +32,7 @@ class GUI_EXPORT QgsNewHttpConnection : public QDialog, private Ui::QgsNewHttpCo public: //! Constructor - QgsNewHttpConnection( QWidget *parent = nullptr, const QString& baseKey = QStringLiteral( "/Qgis/connections-wms/" ), const QString& connName = QString::null, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); + QgsNewHttpConnection( QWidget *parent = nullptr, const QString& baseKey = "/Qgis/connections-wms/", const QString& connName = QString::null, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); //! Destructor ~QgsNewHttpConnection(); public slots: diff --git a/src/gui/qgsrasterformatsaveoptionswidget.h b/src/gui/qgsrasterformatsaveoptionswidget.h index 83a21b9ee89e..a86a903b5914 100644 --- a/src/gui/qgsrasterformatsaveoptionswidget.h +++ b/src/gui/qgsrasterformatsaveoptionswidget.h @@ -42,12 +42,9 @@ class GUI_EXPORT QgsRasterFormatSaveOptionsWidget: public QWidget, ProfileLineEdit // Profile + LineEdit }; - /** - * Constructor for QgsRasterFormatSaveOptionsWidget. - */ - QgsRasterFormatSaveOptionsWidget( QWidget* parent = nullptr, const QString& format = QStringLiteral( "GTiff" ), + QgsRasterFormatSaveOptionsWidget( QWidget* parent = nullptr, const QString& format = "GTiff", QgsRasterFormatSaveOptionsWidget::Type type = Default, - const QString& provider = QStringLiteral( "gdal" ) ); + const QString& provider = "gdal" ); ~QgsRasterFormatSaveOptionsWidget(); void setFormat( const QString& format ); diff --git a/src/gui/qgsrasterpyramidsoptionswidget.h b/src/gui/qgsrasterpyramidsoptionswidget.h index 7975cbd47761..c35a7a98f87b 100644 --- a/src/gui/qgsrasterpyramidsoptionswidget.h +++ b/src/gui/qgsrasterpyramidsoptionswidget.h @@ -32,11 +32,7 @@ class GUI_EXPORT QgsRasterPyramidsOptionsWidget: public QWidget, public: - /** - * Constructor for QgsRasterPyramidsOptionsWidget. - */ - QgsRasterPyramidsOptionsWidget( QWidget* parent = nullptr, const QString& provider = QStringLiteral( "gdal" ) ); - + QgsRasterPyramidsOptionsWidget( QWidget* parent = nullptr, const QString& provider = "gdal" ); ~QgsRasterPyramidsOptionsWidget(); QStringList configOptions() const { return mSaveOptionsWidget->options(); } diff --git a/src/gui/qgsshortcutsmanager.h b/src/gui/qgsshortcutsmanager.h index 83cdcf9e0a53..5998287b0055 100644 --- a/src/gui/qgsshortcutsmanager.h +++ b/src/gui/qgsshortcutsmanager.h @@ -43,7 +43,7 @@ class GUI_EXPORT QgsShortcutsManager : public QObject * as the default value to store settings alongside built in QGIS shortcuts, but care must be * taken to not register actions which conflict with the built in QGIS actions. */ - QgsShortcutsManager( QObject *parent = nullptr, const QString& settingsRoot = QStringLiteral( "/shortcuts/" ) ); + QgsShortcutsManager( QObject *parent = nullptr, const QString& settingsRoot = "/shortcuts/" ); /** Automatically registers all QActions and QShortcuts which are children of the * passed object. diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.h b/src/gui/symbology-ng/qgssymbolslistwidget.h index e12cc8e66c43..dd8809364014 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.h +++ b/src/gui/symbology-ng/qgssymbolslistwidget.h @@ -100,7 +100,7 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW /** Displays alpha value as transparency in mTransparencyLabel*/ void displayTransparency( double alpha ); /** Recursive function to create the group tree in the widget */ - void populateGroups( const QString& parent = QLatin1String( "" ), const QString& prepend = QLatin1String( "" ) ); + void populateGroups( const QString& parent = "", const QString& prepend = "" ); QgsSymbolWidgetContext mContext; diff --git a/src/plugins/gps_importer/qgsbabelformat.h b/src/plugins/gps_importer/qgsbabelformat.h index 986fdf8cc3d3..70df06926bd6 100644 --- a/src/plugins/gps_importer/qgsbabelformat.h +++ b/src/plugins/gps_importer/qgsbabelformat.h @@ -26,7 +26,7 @@ class QString; class QgsBabelFormat { public: - explicit QgsBabelFormat( const QString& name = QStringLiteral( "" ) ); + explicit QgsBabelFormat( const QString& name = "" ); virtual ~QgsBabelFormat() { } const QString& name() const; diff --git a/src/plugins/gps_importer/qgsgpsdevicedialog.h b/src/plugins/gps_importer/qgsgpsdevicedialog.h index 11d78bd6eaed..cc793eda4d02 100644 --- a/src/plugins/gps_importer/qgsgpsdevicedialog.h +++ b/src/plugins/gps_importer/qgsgpsdevicedialog.h @@ -29,7 +29,7 @@ class QgsGPSDeviceDialog : public QDialog, private Ui::QgsGPSDeviceDialogBase void on_pbnDeleteDevice_clicked(); void on_pbnUpdateDevice_clicked(); void on_pbnClose_clicked(); - void slotUpdateDeviceList( const QString& selection = QLatin1String( "" ) ); + void slotUpdateDeviceList( const QString& selection = "" ); void slotSelectionChanged( QListWidgetItem *current ); signals: diff --git a/src/plugins/grass/qgsgrassmapcalc.h b/src/plugins/grass/qgsgrassmapcalc.h index 9967edc7c6e7..898b3a2431f1 100644 --- a/src/plugins/grass/qgsgrassmapcalc.h +++ b/src/plugins/grass/qgsgrassmapcalc.h @@ -217,8 +217,8 @@ class QgsGrassMapcalcFunction QgsGrassMapcalcFunction(); QgsGrassMapcalcFunction( int type, QString name, int count = 2, - QString description = QStringLiteral( "" ), QString label = QStringLiteral( "" ), - QString labels = QStringLiteral( "" ), bool drawLabel = true ); + QString description = "", QString label = "", + QString labels = "", bool drawLabel = true ); ~QgsGrassMapcalcFunction(); QString name() { return mName; } @@ -329,7 +329,7 @@ class QgsGrassMapcalcObject: public QGraphicsRectItem, public QgsGrassMapcalcIte ~QgsGrassMapcalcObject(); // Set map name, constant value or function/operator - void setValue( QString val, QString lab = QStringLiteral( "" ) ); + void setValue( QString val, QString lab = "" ); // Set function void setFunction( QgsGrassMapcalcFunction f ); diff --git a/src/plugins/qgisplugin.h b/src/plugins/qgisplugin.h index 4222260e45af..15eedbfe2db6 100644 --- a/src/plugins/qgisplugin.h +++ b/src/plugins/qgisplugin.h @@ -76,10 +76,10 @@ class QgisPlugin /** * Constructor for QgisPlugin */ - QgisPlugin( QString const & name = QLatin1String( "" ), - QString const & description = QLatin1String( "" ), - QString const & category = QLatin1String( "" ), - QString const & version = QLatin1String( "" ), + QgisPlugin( QString const & name = "", + QString const & description = "", + QString const & category = "", + QString const & version = "", PLUGINTYPE type = MAPLAYER ) : mName( name ) , mDescription( description ) diff --git a/src/providers/delimitedtext/qgsdelimitedtextfile.h b/src/providers/delimitedtext/qgsdelimitedtextfile.h index 5706b579b0e3..670d825726ad 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfile.h +++ b/src/providers/delimitedtext/qgsdelimitedtextfile.h @@ -147,7 +147,7 @@ class QgsDelimitedTextFile : public QObject * @param escape The escape character used to escape quote or delim * characters. */ - void setTypeCSV( const QString& delim = QStringLiteral( "," ), const QString& quote = QStringLiteral( "\"" ), const QString& escape = QStringLiteral( "\"" ) ); + void setTypeCSV( const QString& delim = QString( "," ), const QString& quote = QString( "\"" ), const QString& escape = QString( "\"" ) ); /** Set the number of header lines to skip * @param skiplines The maximum lines to skip diff --git a/src/providers/gdal/qgsgdalprovider.h b/src/providers/gdal/qgsgdalprovider.h index 3f566e2582cb..982bf04d19b9 100644 --- a/src/providers/gdal/qgsgdalprovider.h +++ b/src/providers/gdal/qgsgdalprovider.h @@ -212,7 +212,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase bool theIncludeOutOfRange = false ) override; QString buildPyramids( const QList & theRasterPyramidList, - const QString & theResamplingMethod = QStringLiteral( "NEAREST" ), + const QString & theResamplingMethod = "NEAREST", QgsRaster::RasterPyramidsFormat theFormat = QgsRaster::PyramidsGTiff, const QStringList & theCreateOptions = QStringList() ) override; QList buildPyramidList( QList overviewList = QList() ) override; diff --git a/src/providers/gpx/gpsdata.h b/src/providers/gpx/gpsdata.h index 6c203659b99c..b4681877a9a9 100644 --- a/src/providers/gpx/gpsdata.h +++ b/src/providers/gpx/gpsdata.h @@ -181,20 +181,20 @@ class QgsGPSData /** This function tries to add a new waypoint. An iterator to the new waypoint will be returned (it will be waypointsEnd() if the waypoint couldn't be added. */ - WaypointIterator addWaypoint( double lat, double lon, const QString& name = QLatin1String( "" ), + WaypointIterator addWaypoint( double lat, double lon, const QString& name = "", double ele = -std::numeric_limits::max() ); WaypointIterator addWaypoint( const QgsWaypoint& wpt ); /** This function tries to add a new route. It returns an iterator to the new route. */ - RouteIterator addRoute( const QString& name = QLatin1String( "" ) ); + RouteIterator addRoute( const QString& name = "" ); RouteIterator addRoute( const QgsRoute& rte ); /** This function tries to add a new track. An iterator to the new track will be returned. */ - TrackIterator addTrack( const QString& name = QLatin1String( "" ) ); + TrackIterator addTrack( const QString& name = "" ); TrackIterator addTrack( const QgsTrack& trk ); diff --git a/src/providers/grass/qgsgrass.h b/src/providers/grass/qgsgrass.h index ac4ce06e6697..624ca8573843 100644 --- a/src/providers/grass/qgsgrass.h +++ b/src/providers/grass/qgsgrass.h @@ -438,7 +438,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject * @timeOut timeout */ static QString getInfo( const QString& info, const QString& gisdbase, - const QString& location, const QString& mapset = QStringLiteral( "PERMANENT" ), + const QString& location, const QString& mapset = "PERMANENT", const QString& map = QString::null, const QgsGrassObject::Type type = QgsGrassObject::None, double x = 0.0, double y = 0.0, const QgsRectangle& extent = QgsRectangle(), int sampleRows = 0, diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index dd5ca03829e8..b60aa3e09b3d 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -68,7 +68,7 @@ class QgsOgrProvider : public QgsVectorDataProvider * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset */ - explicit QgsOgrProvider( QString const & uri = QLatin1String( "" ) ); + explicit QgsOgrProvider( QString const & uri = "" ); /** * Destructor diff --git a/src/providers/postgres/qgspostgresconn.h b/src/providers/postgres/qgspostgresconn.h index 0b1b290bf6c6..c33130c97e39 100644 --- a/src/providers/postgres/qgspostgresconn.h +++ b/src/providers/postgres/qgspostgresconn.h @@ -306,7 +306,7 @@ class QgsPostgresConn : public QObject qint64 getBinaryInt( QgsPostgresResult &queryResult, int row, int col ); - QString fieldExpression( const QgsField &fld, QString expr = QStringLiteral( "%1" ) ); + QString fieldExpression( const QgsField &fld, QString expr = "%1" ); QString connInfo() const { return mConnInfo; } diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index d5d0ee07d9da..d1c46c808da1 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -72,7 +72,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider * @param uri String containing the required parameters to connect to the database * and query the table. */ - explicit QgsPostgresProvider( QString const &uri = QLatin1String( "" ) ); + explicit QgsPostgresProvider( QString const &uri = "" ); //! Destructor virtual ~QgsPostgresProvider(); diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index b59f01ced0fa..09a37d6b6fd7 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -71,7 +71,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset */ - explicit QgsSpatiaLiteProvider( QString const &uri = QLatin1String( "" ) ); + explicit QgsSpatiaLiteProvider( QString const &uri = "" ); //! Destructor virtual ~ QgsSpatiaLiteProvider(); diff --git a/src/providers/virtual/qgsvirtuallayerprovider.h b/src/providers/virtual/qgsvirtuallayerprovider.h index 812ef8f7c116..cbb23f090cca 100644 --- a/src/providers/virtual/qgsvirtuallayerprovider.h +++ b/src/providers/virtual/qgsvirtuallayerprovider.h @@ -34,7 +34,7 @@ class QgsVirtualLayerProvider: public QgsVectorDataProvider * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset */ - explicit QgsVirtualLayerProvider( QString const &uri = QLatin1String( "" ) ); + explicit QgsVirtualLayerProvider( QString const &uri = "" ); /** Destructor */ virtual ~QgsVirtualLayerProvider(); @@ -92,11 +92,11 @@ class QgsVirtualLayerProvider: public QgsVectorDataProvider struct SourceLayer { SourceLayer(): layer( nullptr ) {} - SourceLayer( QgsVectorLayer *l, const QString& n = QLatin1String( "" ) ) + SourceLayer( QgsVectorLayer *l, const QString& n = "" ) : layer( l ) , name( n ) {} - SourceLayer( const QString& p, const QString& s, const QString& n, const QString& e = QStringLiteral( "UTF-8" ) ) + SourceLayer( const QString& p, const QString& s, const QString& n, const QString& e = "UTF-8" ) : layer( nullptr ) , name( n ) , source( s ) diff --git a/src/server/qgswmsserver.h b/src/server/qgswmsserver.h index 5c3cef438912..5053531e9891 100644 --- a/src/server/qgswmsserver.h +++ b/src/server/qgswmsserver.h @@ -81,7 +81,7 @@ class QgsWmsServer: public QgsOWSServer /** Returns an XML file with the capabilities description (as described in the WMS specs) @param version WMS version (1.1.1 or 1.3.0) @param fullProjectInformation If true: add extended project information (does not validate against WMS schema)*/ - QDomDocument getCapabilities( const QString &version = QStringLiteral( "1.3.0" ), bool fullProjectInformation = false ); + QDomDocument getCapabilities( const QString &version = "1.3.0", bool fullProjectInformation = false ); QDomDocument getContext(); /** Returns the map legend as an image (or a null pointer in case of error). The caller takes ownership @@ -111,7 +111,7 @@ class QgsWmsServer: public QgsOWSServer /** Creates an xml document that describes the result of the getFeatureInfo request. @return 0 in case of success*/ - int getFeatureInfo( QDomDocument& result, const QString& version = QStringLiteral( "1.3.0" ) ); + int getFeatureInfo( QDomDocument& result, const QString& version = "1.3.0" ); /** Sets configuration parser for administration settings. Does not take ownership*/ void setAdminConfigParser( QgsWmsConfigParser* parser ) { mConfigParser = parser; } From 3ef8e6afca7c859cb9b824ccde3a662d75f24324 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 08:54:01 +1000 Subject: [PATCH 465/897] Minor doxygen improvements --- src/core/qgis.h | 38 ++++++++++++++++++-------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/src/core/qgis.h b/src/core/qgis.h index cf65599b8f93..3024ff86145e 100644 --- a/src/core/qgis.h +++ b/src/core/qgis.h @@ -42,13 +42,13 @@ class CORE_EXPORT Qgis public: // Version constants // - // Version string + //! Version string static QString QGIS_VERSION; - // Version number used for comparing versions using the "Check QGIS Version" function + //! Version number used for comparing versions using the "Check QGIS Version" function static const int QGIS_VERSION_INT; - // Release name + //! Release name static QString QGIS_RELEASE_NAME; - // The development version + //! The development version static const char* QGIS_DEV_VERSION; // Enumerations @@ -59,22 +59,20 @@ class CORE_EXPORT Qgis */ enum DataType { - /** Unknown or unspecified type */ UnknownDataType = 0, - /** Eight bit unsigned integer (quint8) */ Byte = 1, - /** Sixteen bit unsigned integer (quint16) */ UInt16 = 2, - /** Sixteen bit signed integer (qint16) */ Int16 = 3, - /** Thirty two bit unsigned integer (quint32) */ UInt32 = 4, - /** Thirty two bit signed integer (qint32) */ Int32 = 5, - /** Thirty two bit floating point (float) */ Float32 = 6, - /** Sixty four bit floating point (double) */ Float64 = 7, - /** Complex Int16 */ CInt16 = 8, - /** Complex Int32 */ CInt32 = 9, - /** Complex Float32 */ CFloat32 = 10, - /** Complex Float64 */ CFloat64 = 11, - /** Color, alpha, red, green, blue, 4 bytes the same as - QImage::Format_ARGB32 */ ARGB32 = 12, - /** Color, alpha, red, green, blue, 4 bytes the same as - QImage::Format_ARGB32_Premultiplied */ ARGB32_Premultiplied = 13 + UnknownDataType = 0, //!< Unknown or unspecified type + Byte = 1, //!< Eight bit unsigned integer (quint8) + UInt16 = 2, //!< Sixteen bit unsigned integer (quint16) + Int16 = 3, //!< Sixteen bit signed integer (qint16) + UInt32 = 4, //!< Thirty two bit unsigned integer (quint32) + Int32 = 5, //!< Thirty two bit signed integer (qint32) + Float32 = 6, //!< Thirty two bit floating point (float) + Float64 = 7, //!< Sixty four bit floating point (double) + CInt16 = 8, //!< Complex Int16 + CInt32 = 9, //!< Complex Int32 + CFloat32 = 10, //!< Complex Float32 + CFloat64 = 11, //!< Complex Float64 + ARGB32 = 12, //!< Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32 + ARGB32_Premultiplied = 13 //!< Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32_Premultiplied }; //! User defined event types From 1367fd09fc5595518b6c2a28dbddc3f28863a836 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 09:17:39 +1000 Subject: [PATCH 466/897] Prepare commit converts single line doxygen block format Flips single line doxygen comments to use the proper single line format: /*!< comment */ to //!< Comment and /** comment */ to //! Comment --- scripts/unify_includes.pl | 8 + src/analysis/interpolation/Bezier3D.h | 30 +-- .../interpolation/CloughTocherInterpolator.h | 42 ++-- .../interpolation/DualEdgeTriangulation.h | 126 +++++------ src/analysis/interpolation/HalfEdge.h | 32 +-- .../interpolation/LinTriangleInterpolator.h | 18 +- src/analysis/interpolation/Line3D.h | 20 +- src/analysis/interpolation/MathUtils.h | 54 ++--- src/analysis/interpolation/Node.h | 12 +- src/analysis/interpolation/NormVecDecorator.h | 36 ++-- src/analysis/interpolation/ParametricLine.h | 10 +- src/analysis/interpolation/Point3D.h | 22 +- src/analysis/interpolation/TriDecorator.h | 6 +- .../interpolation/TriangleInterpolator.h | 4 +- src/analysis/interpolation/Triangulation.h | 46 ++-- src/analysis/interpolation/Vector3D.h | 30 +-- src/analysis/interpolation/qgsinterpolator.h | 6 +- .../interpolation/qgstininterpolator.h | 8 +- src/analysis/openstreetmap/qgsosmdownload.h | 4 +- src/analysis/raster/qgsderivativefilter.h | 4 +- src/analysis/raster/qgsninecellfilter.h | 10 +- src/analysis/raster/qgsrastercalculator.h | 18 +- src/analysis/raster/qgsrastermatrix.h | 14 +- src/analysis/raster/qgsrelief.h | 14 +- src/analysis/vector/qgsgeometryanalyzer.h | 12 +- src/analysis/vector/qgspointsample.h | 8 +- src/analysis/vector/qgstransectsample.h | 10 +- src/analysis/vector/qgszonalstatistics.h | 10 +- .../composer/qgsattributeselectiondialog.h | 10 +- src/app/composer/qgscomposer.h | 46 ++-- src/app/composer/qgscomposerarrowwidget.h | 2 +- .../qgscomposerattributetablewidget.h | 6 +- src/app/composer/qgscomposerhtmlwidget.h | 4 +- src/app/composer/qgscomposeritemwidget.h | 20 +- .../composer/qgscomposerlegenditemdialog.h | 2 +- .../composer/qgscomposerlegendlayersdialog.h | 2 +- src/app/composer/qgscomposerlegendwidget.h | 6 +- src/app/composer/qgscomposermanager.h | 18 +- src/app/composer/qgscomposermapgridwidget.h | 12 +- src/app/composer/qgscomposermapwidget.h | 20 +- src/app/composer/qgscomposerpicturewidget.h | 16 +- src/app/composer/qgscomposerpolygonwidget.h | 2 +- src/app/composer/qgscomposerpolylinewidget.h | 2 +- src/app/composer/qgscomposerscalebarwidget.h | 4 +- src/app/composer/qgscomposershapewidget.h | 8 +- .../qgscomposertablebackgroundcolorsdialog.h | 2 +- src/app/composer/qgscompositionwidget.h | 26 +-- src/app/legend/qgsapplegendinterface.h | 4 +- src/app/nodetool/qgsmaptoolnodetool.h | 30 +-- src/app/ogr/qgsnewogrconnection.cpp | 4 +- src/app/ogr/qgsvectorlayersaveasdialog.h | 4 +- src/app/qgisapp.cpp | 4 +- src/app/qgisapp.h | 108 +++++----- src/app/qgisappinterface.h | 52 ++--- src/app/qgisappstylesheet.h | 8 +- src/app/qgsalignrasterdialog.cpp | 2 +- src/app/qgsalignrasterdialog.h | 4 +- src/app/qgsbrowserdockwidget.h | 2 +- src/app/qgsclipboard.h | 10 +- src/app/qgsdecorationgrid.h | 84 ++++---- src/app/qgsdecorationitem.h | 2 +- src/app/qgsdelattrdialog.h | 2 +- src/app/qgsdiagramproperties.h | 2 +- src/app/qgsdisplayangle.h | 2 +- src/app/qgsdxfexportdialog.h | 2 +- src/app/qgsfieldcalculator.h | 14 +- src/app/qgsfieldsproperties.h | 2 +- src/app/qgshandlebadlayers.h | 2 +- src/app/qgsidentifyresultsdialog.h | 14 +- src/app/qgsjoindialog.h | 8 +- src/app/qgslabelinggui.h | 2 +- src/app/qgslabelpropertydialog.h | 18 +- src/app/qgslayerstylingwidget.h | 2 +- src/app/qgsmaplayerstyleguiutils.h | 2 +- src/app/qgsmaptooladdcircularstring.h | 2 +- src/app/qgsmaptooladdfeature.h | 4 +- src/app/qgsmaptooladdpart.h | 4 +- src/app/qgsmaptooladdring.h | 2 +- src/app/qgsmaptoolannotation.h | 10 +- src/app/qgsmaptooldeletepart.h | 2 +- src/app/qgsmaptooldeletering.h | 2 +- src/app/qgsmaptoollabel.h | 16 +- src/app/qgsmaptoolmeasureangle.h | 16 +- src/app/qgsmaptoolmovefeature.h | 8 +- src/app/qgsmaptoolmovelabel.h | 4 +- src/app/qgsmaptooloffsetcurve.h | 28 +-- src/app/qgsmaptoolpinlabels.h | 2 +- src/app/qgsmaptoolpointsymbol.h | 2 +- src/app/qgsmaptoolreshape.h | 2 +- src/app/qgsmaptoolrotatefeature.h | 10 +- src/app/qgsmaptoolrotatelabel.h | 6 +- src/app/qgsmaptoolrotatepointsymbols.h | 16 +- src/app/qgsmaptoolshowhidelabels.h | 2 +- src/app/qgsmaptoolsimplify.h | 14 +- src/app/qgsmaptoolsplitfeatures.h | 2 +- src/app/qgsmaptoolsplitparts.h | 2 +- src/app/qgsmeasuretool.h | 2 +- src/app/qgsmergeattributesdialog.h | 16 +- src/app/qgsnewspatialitelayerdialog.h | 4 +- src/app/qgsoptions.h | 36 ++-- src/app/qgspointrotationitem.h | 14 +- src/app/qgsprojectlayergroupdialog.h | 4 +- src/app/qgsprojectproperties.h | 18 +- src/app/qgsrastercalcdialog.h | 18 +- src/app/qgsrasterlayerproperties.h | 74 +++---- src/app/qgssnappingwidget.h | 2 +- src/app/qgsstatusbarmagnifierwidget.h | 2 +- src/app/qgsstatusbarscalewidget.h | 2 +- src/app/qgstextannotationdialog.h | 2 +- src/app/qgstip.h | 12 +- src/app/qgstipfactory.h | 4 +- src/app/qgsundowidget.h | 2 +- src/app/qgsvectorlayerproperties.h | 36 ++-- src/core/auth/qgsauthcertutils.h | 38 ++-- src/core/auth/qgsauthconfig.h | 92 ++++---- src/core/auth/qgsauthcrypto.h | 10 +- src/core/auth/qgsauthmanager.h | 132 ++++++------ src/core/auth/qgsauthmethod.h | 16 +- src/core/auth/qgsauthmethodregistry.h | 26 +-- src/core/composer/qgsatlascomposition.h | 24 +-- src/core/composer/qgscomposerarrow.h | 22 +- .../qgscomposerattributetablemodelv2.h | 8 +- .../composer/qgscomposerattributetablev2.h | 30 +-- src/core/composer/qgscomposereffect.h | 2 +- src/core/composer/qgscomposerframe.h | 4 +- src/core/composer/qgscomposerhtml.h | 10 +- src/core/composer/qgscomposeritem.h | 70 +++---- src/core/composer/qgscomposeritemcommand.h | 22 +- src/core/composer/qgscomposeritemgroup.h | 6 +- src/core/composer/qgscomposerlabel.h | 22 +- src/core/composer/qgscomposerlegend.h | 22 +- src/core/composer/qgscomposerlegenditem.h | 2 +- src/core/composer/qgscomposerlegendstyle.h | 6 +- src/core/composer/qgscomposermap.h | 126 +++++------ src/core/composer/qgscomposermapgrid.h | 136 ++++++------ src/core/composer/qgscomposermapitem.h | 8 +- src/core/composer/qgscomposermapoverview.h | 12 +- src/core/composer/qgscomposermodel.h | 12 +- src/core/composer/qgscomposermousehandles.h | 60 +++--- src/core/composer/qgscomposermultiframe.h | 8 +- .../composer/qgscomposermultiframecommand.h | 2 +- src/core/composer/qgscomposernodesitem.h | 28 +-- src/core/composer/qgscomposerobject.h | 68 +++--- src/core/composer/qgscomposerpicture.h | 38 ++-- src/core/composer/qgscomposerpolygon.h | 20 +- src/core/composer/qgscomposerpolyline.h | 20 +- src/core/composer/qgscomposerscalebar.h | 66 +++--- src/core/composer/qgscomposershape.h | 16 +- src/core/composer/qgscomposertablev2.h | 84 ++++---- src/core/composer/qgscomposertexttable.h | 2 +- src/core/composer/qgscomposition.h | 154 +++++++------- .../composer/qgsgroupungroupitemscommand.h | 6 +- src/core/composer/qgsnumericscalebarstyle.h | 4 +- src/core/composer/qgspaperitem.h | 8 +- src/core/diagram/qgsdiagram.h | 6 +- src/core/dxf/qgsdxfexport.h | 4 +- src/core/dxf/qgsdxfpaintdevice.h | 4 +- src/core/effects/qgsblureffect.h | 6 +- src/core/effects/qgsgloweffect.h | 6 +- src/core/effects/qgsimageoperation.h | 14 +- src/core/effects/qgspainteffect.h | 6 +- src/core/geometry/qgsabstractgeometry.h | 4 +- src/core/geometry/qgscompoundcurve.h | 2 +- src/core/geometry/qgscurvepolygon.h | 6 +- src/core/geometry/qgsgeometry.cpp | 2 +- src/core/geometry/qgsgeometry.h | 64 +++--- src/core/geometry/qgsgeometrycollection.h | 2 +- src/core/geometry/qgsgeometryfactory.h | 16 +- src/core/geometry/qgsgeometryutils.h | 30 +-- src/core/geometry/qgsgeos.cpp | 4 +- src/core/geometry/qgsgeos.h | 2 +- src/core/geometry/qgslinestring.h | 2 +- src/core/geometry/qgsmulticurve.h | 2 +- src/core/geometry/qgsmultilinestring.h | 2 +- src/core/geometry/qgsmultipoint.h | 2 +- src/core/geometry/qgsmultipolygon.h | 2 +- src/core/geometry/qgsmultisurface.h | 2 +- src/core/geometry/qgswkbtypes.h | 2 +- src/core/gps/gmath.c | 32 +-- src/core/gps/gmath.h | 16 +- src/core/gps/info.h | 50 ++--- src/core/gps/nmeatime.h | 16 +- src/core/gps/qgsgpsconnection.h | 20 +- src/core/gps/qgsgpsconnectionregistry.h | 4 +- src/core/gps/qgsnmeaconnection.h | 6 +- src/core/gps/qgsqtlocationconnection.h | 4 +- src/core/gps/sentence.h | 98 ++++----- src/core/gps/time.c | 2 +- src/core/gps/tok.c | 2 +- src/core/gps/units.h | 8 +- src/core/layertree/qgslayertreemodel.h | 4 +- .../layertree/qgslayertreemodellegendnode.h | 18 +- src/core/layertree/qgslayertreenode.h | 14 +- src/core/pal/costcalculator.h | 6 +- src/core/pal/feature.h | 6 +- src/core/pal/labelposition.h | 16 +- src/core/pal/layer.h | 16 +- src/core/pal/pal.h | 24 +-- src/core/pal/pointset.h | 2 +- src/core/qgis.h | 20 +- src/core/qgsapplication.cpp | 4 +- src/core/qgsapplication.h | 24 +-- src/core/qgsbrowsermodel.h | 18 +- src/core/qgscolorscheme.h | 6 +- src/core/qgscoordinatereferencesystem.h | 8 +- src/core/qgscoordinatetransform.h | 6 +- src/core/qgscoordinatetransform_p.h | 4 +- src/core/qgscrscache.h | 2 +- src/core/qgsdataitem.h | 38 ++-- src/core/qgsdataprovider.h | 10 +- src/core/qgsdbfilterproxymodel.h | 4 +- src/core/qgsdiagramrenderer.h | 18 +- src/core/qgseditformconfig.h | 14 +- src/core/qgseditformconfig_p.h | 18 +- src/core/qgserror.h | 14 +- src/core/qgsexpression.h | 18 +- src/core/qgsexpressioncontext.h | 6 +- src/core/qgsfeature.h | 4 +- src/core/qgsfeaturefilterprovider.h | 4 +- src/core/qgsfeatureiterator.h | 14 +- src/core/qgsfeaturestore.h | 14 +- src/core/qgsfield.h | 6 +- src/core/qgsfields.h | 20 +- src/core/qgsgeometrycache.h | 6 +- src/core/qgsgeometryvalidator.h | 2 +- src/core/qgsgml.h | 112 +++++----- src/core/qgsgmlschema.h | 44 ++-- src/core/qgslabelingengine.h | 10 +- src/core/qgslabelsearchtree.h | 2 +- src/core/qgslayerdefinition.h | 16 +- src/core/qgslegendrenderer.h | 14 +- src/core/qgslegendsettings.h | 42 ++-- src/core/qgslogger.h | 16 +- src/core/qgsmaplayer.cpp | 8 +- src/core/qgsmaplayer.h | 86 ++++---- src/core/qgsmaplayermodel.h | 4 +- src/core/qgsmaprendererjob.h | 2 +- src/core/qgsmapsettings.h | 8 +- src/core/qgsmapunitscale.h | 12 +- src/core/qgsnetworkreplyparser.h | 6 +- src/core/qgsobjectcustomproperties.h | 2 +- src/core/qgsofflineediting.h | 8 +- src/core/qgsogcutils.h | 44 ++-- src/core/qgsowsconnection.h | 10 +- src/core/qgspalgeometry.h | 2 +- src/core/qgspallabeling.h | 34 +-- src/core/qgspluginlayer.h | 4 +- src/core/qgspluginlayerregistry.cpp | 2 +- src/core/qgspluginlayerregistry.h | 16 +- src/core/qgspoint.h | 8 +- src/core/qgspointlocator.h | 6 +- src/core/qgsproject.h | 12 +- src/core/qgsprojectproperty.h | 12 +- src/core/qgsproviderregistry.h | 30 +-- src/core/qgspythonrunner.h | 6 +- src/core/qgsrectangle.h | 8 +- src/core/qgsrelation.h | 12 +- src/core/qgsrelationmanager.h | 4 +- src/core/qgsrenderchecker.h | 2 +- src/core/qgsrendercontext.h | 36 ++-- src/core/qgsscalecalculator.h | 2 +- src/core/qgssnapper.h | 30 +-- src/core/qgssnappingconfig.h | 12 +- src/core/qgssnappingutils.h | 24 +-- src/core/qgsspatialindex.cpp | 4 +- src/core/qgsspatialindex.h | 16 +- src/core/qgssqlexpressioncompiler.h | 10 +- src/core/qgssqlstatement.h | 176 ++++++++-------- src/core/qgstextlabelfeature.h | 2 +- src/core/qgstextrenderer.h | 30 +-- src/core/qgstolerance.h | 6 +- src/core/qgstracer.cpp | 2 +- src/core/qgstransaction.h | 12 +- src/core/qgsunittypes.h | 66 +++--- src/core/qgsvectordataprovider.h | 48 ++--- src/core/qgsvectorfilewriter.h | 88 ++++---- src/core/qgsvectorlayer.cpp | 10 +- src/core/qgsvectorlayer.h | 198 +++++++++--------- src/core/qgsvectorlayerdiagramprovider.h | 2 +- src/core/qgsvectorlayereditbuffer.h | 42 ++-- src/core/qgsvectorlayerfeatureiterator.h | 14 +- src/core/qgsvectorlayerimport.h | 18 +- src/core/qgsvectorlayerjoinbuffer.h | 14 +- src/core/qgsvectorlayerrenderer.h | 6 +- src/core/qgsvectorsimplifymethod.h | 40 ++-- src/core/raster/qgsbrightnesscontrastfilter.h | 8 +- src/core/raster/qgscolorrampshader.h | 22 +- src/core/raster/qgscontrastenhancement.h | 44 ++-- .../raster/qgscontrastenhancementfunction.h | 16 +- src/core/raster/qgscubicrasterresampler.h | 2 +- src/core/raster/qgshillshaderenderer.h | 4 +- src/core/raster/qgshuesaturationfilter.h | 12 +- src/core/raster/qgsmultibandcolorrenderer.h | 6 +- src/core/raster/qgspalettedrasterrenderer.h | 12 +- src/core/raster/qgsraster.h | 4 +- src/core/raster/qgsrasterbandstats.h | 24 +-- src/core/raster/qgsrasterblock.h | 14 +- src/core/raster/qgsrasterdataprovider.h | 56 ++--- src/core/raster/qgsrasterfilewriter.h | 6 +- src/core/raster/qgsrasterhistogram.h | 22 +- src/core/raster/qgsrasteridentifyresult.h | 22 +- src/core/raster/qgsrasterinterface.h | 30 +-- src/core/raster/qgsrasteriterator.h | 2 +- src/core/raster/qgsrasterlayer.h | 92 ++++---- src/core/raster/qgsrasterlayerrenderer.h | 6 +- src/core/raster/qgsrasternuller.h | 2 +- src/core/raster/qgsrasterpipe.h | 10 +- src/core/raster/qgsrasterprojector.h | 98 ++++----- src/core/raster/qgsrasterpyramid.h | 10 +- src/core/raster/qgsrasterrenderer.h | 12 +- src/core/raster/qgsrasterresamplefilter.h | 12 +- src/core/raster/qgsrastershader.h | 18 +- src/core/raster/qgsrastershaderfunction.h | 14 +- src/core/raster/qgsrastertransparency.h | 22 +- src/core/raster/qgsrasterviewport.h | 10 +- src/core/raster/qgssinglebandgrayrenderer.h | 2 +- .../raster/qgssinglebandpseudocolorrenderer.h | 4 +- src/core/symbology-ng/qgsarrowsymbollayer.h | 72 +++---- .../qgscategorizedsymbolrenderer.h | 2 +- src/core/symbology-ng/qgscptcityarchive.h | 6 +- src/core/symbology-ng/qgsfillsymbollayer.h | 60 +++--- src/core/symbology-ng/qgsheatmaprenderer.h | 4 +- .../symbology-ng/qgsinvertedpolygonrenderer.h | 30 +-- src/core/symbology-ng/qgslinesymbollayer.h | 2 +- src/core/symbology-ng/qgsmarkersymbollayer.h | 46 ++-- .../qgspointdisplacementrenderer.h | 4 +- src/core/symbology-ng/qgsrenderer.h | 12 +- src/core/symbology-ng/qgsrendererregistry.h | 2 +- src/core/symbology-ng/qgssvgcache.h | 28 +-- src/core/symbology-ng/qgssymbol.h | 6 +- src/core/symbology-ng/qgssymbollayer.h | 14 +- .../symbology-ng/qgssymbollayerregistry.h | 6 +- src/core/symbology-ng/qgssymbollayerutils.h | 18 +- .../symbology-ng/qgssymbologyconversion.h | 2 +- .../qgsattributetablefiltermodel.h | 2 +- .../attributetable/qgsattributetablemodel.h | 6 +- src/gui/attributetable/qgsdualview.h | 4 +- src/gui/attributetable/qgsfeaturelistview.h | 2 +- src/gui/auth/qgsauthauthoritieseditor.h | 8 +- src/gui/auth/qgsauthcertificateinfo.h | 2 +- src/gui/auth/qgsauthcertificatemanager.h | 2 +- src/gui/auth/qgsauthcerttrustpolicycombobox.h | 8 +- src/gui/auth/qgsauthconfigedit.h | 8 +- src/gui/auth/qgsauthconfigeditor.h | 26 +-- src/gui/auth/qgsauthconfigidedit.h | 14 +- src/gui/auth/qgsauthconfigselect.h | 20 +- src/gui/auth/qgsautheditorwidgets.h | 14 +- src/gui/auth/qgsauthguiutils.h | 32 +-- src/gui/auth/qgsauthidentitieseditor.h | 8 +- src/gui/auth/qgsauthimportcertdialog.h | 14 +- src/gui/auth/qgsauthimportidentitydialog.h | 10 +- src/gui/auth/qgsauthmethodedit.h | 10 +- src/gui/auth/qgsauthserverseditor.h | 8 +- src/gui/auth/qgsauthsslconfigwidget.h | 62 +++--- src/gui/auth/qgsauthsslimportdialog.h | 2 +- src/gui/auth/qgsauthtrustedcasdialog.h | 8 +- .../core/qgssearchwidgetwrapper.h | 26 +-- .../editorwidgets/qgsmultiedittoolbutton.h | 6 +- .../qgslayertreeembeddedwidgetregistry.h | 6 +- src/gui/qgisinterface.h | 70 +++---- src/gui/qgsadvanceddigitizingdockwidget.h | 4 +- src/gui/qgsannotationitem.h | 40 ++-- src/gui/qgsattributeform.h | 12 +- src/gui/qgsattributeformeditorwidget.h | 6 +- src/gui/qgscollapsiblegroupbox.h | 4 +- src/gui/qgscolorbutton.h | 4 +- src/gui/qgscolorwidgets.h | 32 +-- src/gui/qgscomposerruler.h | 2 +- src/gui/qgscomposerview.h | 90 ++++---- src/gui/qgscompoundcolorwidget.h | 4 +- src/gui/qgsdatumtransformdialog.h | 2 +- src/gui/qgsdetaileditemdelegate.h | 4 +- src/gui/qgsencodingfiledialog.h | 8 +- src/gui/qgsexpressionbuilderdialog.h | 4 +- src/gui/qgsexpressionbuilderwidget.h | 4 +- src/gui/qgsextentgroupbox.h | 6 +- src/gui/qgsfieldmodel.h | 14 +- src/gui/qgsfieldproxymodel.h | 18 +- src/gui/qgsformannotationitem.h | 16 +- src/gui/qgsgeometryrubberband.h | 18 +- src/gui/qgshighlight.h | 4 +- src/gui/qgshtmlannotationitem.h | 12 +- src/gui/qgslegendinterface.h | 8 +- src/gui/qgsmapcanvas.cpp | 6 +- src/gui/qgsmapcanvas.h | 26 +-- src/gui/qgsmapcanvassnapper.h | 4 +- src/gui/qgsmaplayeractionregistry.cpp | 4 +- src/gui/qgsmaplayeractionregistry.h | 30 +-- src/gui/qgsmaplayerconfigwidgetfactory.h | 6 +- src/gui/qgsmapmouseevent.h | 4 +- src/gui/qgsmaptool.h | 10 +- src/gui/qgsmaptooladvanceddigitizing.h | 8 +- src/gui/qgsmaptoolcapture.h | 12 +- src/gui/qgsmaptooledit.h | 6 +- src/gui/qgsmaptoolidentify.h | 2 +- src/gui/qgsnewgeopackagelayerdialog.h | 2 +- src/gui/qgsnewmemorylayerdialog.h | 6 +- src/gui/qgsnewvectorlayerdialog.h | 10 +- src/gui/qgsowssourceselect.h | 2 +- src/gui/qgsprojectbadlayerguihandler.h | 4 +- src/gui/qgsprojectionselectionwidget.h | 10 +- src/gui/qgsprojectionselector.h | 6 +- src/gui/qgsrubberband.h | 6 +- src/gui/qgssearchquerybuilder.cpp | 2 +- src/gui/qgssourceselectdialog.cpp | 2 +- src/gui/qgssourceselectdialog.h | 22 +- src/gui/qgssublayersdialog.h | 12 +- src/gui/qgstextannotationitem.h | 4 +- src/gui/qgstreewidgetitem.h | 6 +- src/gui/qgsunitselectionwidget.h | 6 +- .../raster/qgsmultibandcolorrendererwidget.h | 2 +- src/gui/raster/qgsrasterhistogramwidget.h | 40 ++-- src/gui/raster/qgsrasterminmaxwidget.h | 2 +- src/gui/raster/qgsrasterrendererwidget.h | 4 +- src/gui/raster/qgsrastertransparencywidget.h | 20 +- .../qgsrendererrasterpropertieswidget.h | 6 +- ...qgssinglebandpseudocolorrendererwidget.cpp | 4 +- .../symbology-ng/qgsarrowsymbollayerwidget.h | 4 +- .../qgsgraduatedsymbolrendererwidget.h | 8 +- .../symbology-ng/qgsheatmaprendererwidget.h | 2 +- .../qgsinvertedpolygonrendererwidget.h | 6 +- src/gui/symbology-ng/qgsrendererwidget.h | 12 +- src/gui/symbology-ng/qgssvgselectorwidget.h | 2 +- src/gui/symbology-ng/qgssymbolslistwidget.h | 4 +- .../evisdatabaseconnection.h | 38 ++-- .../evisdatabaseconnectiongui.h | 16 +- .../evisdatabaselayerfieldselectiongui.h | 6 +- .../databaseconnection/evisquerydefinition.h | 62 +++--- .../eventbrowser/evisgenericeventbrowsergui.h | 62 +++--- .../eventbrowser/evisimagedisplaywidget.h | 52 ++--- src/plugins/evis/idtool/eviseventidtool.h | 8 +- .../ui/qgsgeometrycheckerresulttab.cpp | 6 +- .../ui/qgsgeometrycheckersetuptab.cpp | 16 +- .../qgsgeometrysnapperdialog.cpp | 12 +- src/plugins/georeferencer/qgsgcpcanvasitem.h | 6 +- .../qgsgeorefdescriptiondialog.h | 2 +- .../georeferencer/qgsgeorefplugingui.h | 2 +- .../georeferencer/qgsgeoreftoolmovepoint.h | 4 +- .../georeferencer/qgsgeoreftransform.h | 2 +- .../georeferencer/qgsresidualplotitem.h | 8 +- src/plugins/grass/qgsgrassmapcalc.h | 16 +- src/plugins/grass/qgsgrassmoduleinput.h | 4 +- src/plugins/grass/qgsgrassregion.cpp | 4 +- src/plugins/grass/qgsgrassregion.h | 2 +- src/plugins/heatmap/heatmapgui.h | 52 ++--- .../interpolation/qgsidwinterpolatordialog.h | 2 +- .../interpolation/qgsinterpolationdialog.h | 10 +- .../interpolation/qgsinterpolationplugin.h | 4 +- .../interpolation/qgsinterpolatordialog.h | 6 +- .../offline_editing_plugin_gui.h | 2 +- .../qgsrasterterrainanalysisdialog.h | 2 +- .../qgsrasterterrainanalysisplugin.h | 6 +- .../qgszonalstatisticsdialog.h | 6 +- .../qgszonalstatisticsplugin.h | 6 +- src/providers/db2/qgsdb2newconnection.cpp | 4 +- src/providers/db2/qgsdb2provider.h | 16 +- src/providers/db2/qgsdb2sourceselect.cpp | 6 +- src/providers/db2/qgsdb2tablemodel.h | 10 +- .../delimitedtext/qgsdelimitedtextfile.h | 4 +- src/providers/gdal/qgsgdalprovider.h | 26 +-- src/providers/gdal/qgsgdalproviderbase.h | 8 +- src/providers/gpx/gpsdata.h | 34 +-- src/providers/gpx/qgsgpxprovider.h | 6 +- src/providers/grass/qgsgrass.h | 50 ++--- src/providers/grass/qgsgrassfeatureiterator.h | 10 +- src/providers/grass/qgsgrassgislib.h | 30 +-- src/providers/grass/qgsgrassprovider.h | 26 +-- src/providers/grass/qgsgrassvector.h | 20 +- src/providers/grass/qgsgrassvectormap.h | 20 +- src/providers/grass/qgsgrassvectormaplayer.h | 12 +- src/providers/memory/qgsmemoryprovider.h | 2 +- src/providers/mssql/qgsmssqlnewconnection.cpp | 4 +- src/providers/mssql/qgsmssqlprovider.h | 22 +- src/providers/mssql/qgsmssqlsourceselect.cpp | 6 +- src/providers/mssql/qgsmssqltablemodel.h | 10 +- src/providers/ogr/qgsogrconnpool.h | 2 +- src/providers/ogr/qgsogrprovider.cpp | 12 +- src/providers/ogr/qgsogrprovider.h | 52 ++--- src/providers/oracle/qgsoracleconn.h | 4 +- src/providers/oracle/qgsoracleconnpool.h | 2 +- .../oracle/qgsoraclenewconnection.cpp | 4 +- src/providers/oracle/qgsoracleprovider.h | 16 +- .../oracle/qgsoraclesourceselect.cpp | 6 +- src/providers/oracle/qgsoracletablemodel.h | 8 +- src/providers/postgres/qgspgnewconnection.cpp | 4 +- src/providers/postgres/qgspgsourceselect.cpp | 6 +- src/providers/postgres/qgspgtablemodel.h | 8 +- src/providers/postgres/qgspostgresconn.h | 10 +- src/providers/postgres/qgspostgresconnpool.h | 2 +- src/providers/postgres/qgspostgresdataitems.h | 2 +- .../postgres/qgspostgresprovider.cpp | 2 +- src/providers/postgres/qgspostgresprovider.h | 10 +- .../spatialite/qgsspatialiteconnection.h | 22 +- .../spatialite/qgsspatialiteconnpool.h | 2 +- .../spatialite/qgsspatialitefeatureiterator.h | 2 +- .../spatialite/qgsspatialiteprovider.h | 6 +- .../spatialite/qgsspatialitesourceselect.cpp | 2 +- .../spatialite/qgsspatialitetablemodel.h | 12 +- .../virtual/qgsembeddedlayerselectdialog.h | 2 +- .../virtual/qgsvirtuallayerprovider.h | 18 +- .../virtual/qgsvirtuallayersourceselect.h | 4 +- src/providers/wcs/qgswcscapabilities.h | 20 +- src/providers/wcs/qgswcsprovider.h | 50 ++--- src/providers/wfs/qgswfscapabilities.h | 4 +- src/providers/wfs/qgswfsdatasourceuri.h | 42 ++-- src/providers/wfs/qgswfsdescribefeaturetype.h | 4 +- src/providers/wfs/qgswfsfeatureiterator.h | 46 ++-- src/providers/wfs/qgswfsprovider.h | 28 +-- src/providers/wfs/qgswfsrequest.h | 38 ++-- src/providers/wfs/qgswfsshareddata.cpp | 2 +- src/providers/wfs/qgswfsshareddata.h | 108 +++++----- src/providers/wfs/qgswfstransactionrequest.h | 4 +- src/providers/wfs/qgswfsutils.h | 18 +- src/providers/wms/qgswmscapabilities.h | 118 +++++------ src/providers/wms/qgswmsprovider.h | 20 +- src/providers/wms/qgsxyzconnection.h | 2 +- src/server/qgsaccesscontrol.cpp | 22 +- src/server/qgsaccesscontrol.h | 8 +- src/server/qgsaccesscontrolfilter.cpp | 16 +- src/server/qgsaccesscontrolfilter.h | 10 +- src/server/qgscapabilitiescache.h | 2 +- src/server/qgsconfigcache.h | 6 +- src/server/qgsconfigparserutils.h | 4 +- src/server/qgshttprequesthandler.h | 8 +- src/server/qgshttptransaction.h | 20 +- src/server/qgsinterpolationlayerbuilder.h | 2 +- src/server/qgsmaprenderer.h | 2 +- src/server/qgsmslayerbuilder.h | 2 +- src/server/qgsmslayercache.h | 18 +- src/server/qgsmsutils.h | 4 +- src/server/qgsowsserver.cpp | 4 +- src/server/qgsowsserver.h | 2 +- src/server/qgspostrequesthandler.h | 4 +- src/server/qgsremotedatasourcebuilder.h | 6 +- src/server/qgsremoteowsbuilder.h | 8 +- src/server/qgsrequesthandler.h | 36 ++-- src/server/qgssentdatasourcebuilder.h | 6 +- src/server/qgsserver.h | 8 +- src/server/qgsserverfilter.h | 4 +- src/server/qgsserverinterface.cpp | 4 +- src/server/qgsserverinterface.h | 6 +- src/server/qgsserverinterfaceimpl.cpp | 6 +- src/server/qgsserverinterfaceimpl.h | 6 +- src/server/qgsserverlogger.h | 2 +- src/server/qgsserverprojectparser.h | 30 +-- src/server/qgssldconfigparser.h | 56 ++--- src/server/qgssoaprequesthandler.h | 8 +- src/server/qgswcsserver.h | 14 +- src/server/qgswfsserver.h | 12 +- src/server/qgswmsconfigparser.h | 40 ++-- src/server/qgswmsprojectparser.h | 32 +-- src/server/qgswmsserver.h | 50 ++--- tests/src/analysis/testopenstreetmap.cpp | 2 +- tests/src/analysis/testqgsvectoranalyzer.cpp | 2 +- tests/src/core/testqgsgeometry.cpp | 8 +- tests/src/core/testqgsmaprendererjob.cpp | 2 +- tests/src/core/testqgsvectorfilewriter.cpp | 12 +- 557 files changed, 4682 insertions(+), 4674 deletions(-) diff --git a/scripts/unify_includes.pl b/scripts/unify_includes.pl index c1509aadb197..cc220b865ec5 100755 --- a/scripts/unify_includes.pl +++ b/scripts/unify_includes.pl @@ -28,6 +28,14 @@ # Also fix doxygen comments s#^(\s*)/\*[*!]\s*([^\s*].*)\s*$#$1/** \u$2\n#; +# Convert single line doxygent blocks: +# /*!< comment */ to //!< comment +# /** comment */ to //! comment +s#\/\*[!\*](?!\*)(<*)\h*(.*?)\h*\*\/\h*$#//!$1 $2#; + +# Uppercase initial character in //!< comment +s#\/\/!<\s*(.)(.*)#//!< \u$1$2#; + if( /^\s*#include/ ) { push @inc, $_ unless exists $inc{$_}; $inc{$_}=1; diff --git a/src/analysis/interpolation/Bezier3D.h b/src/analysis/interpolation/Bezier3D.h index d9a4796ace78..bc471924f617 100644 --- a/src/analysis/interpolation/Bezier3D.h +++ b/src/analysis/interpolation/Bezier3D.h @@ -27,38 +27,38 @@ class ANALYSIS_EXPORT Bezier3D: public ParametricLine protected: public: - /** Default constructor*/ + //! Default constructor Bezier3D(); - /** Constructor, par is a pointer to the parent, controlpoly a controlpolygon*/ + //! Constructor, par is a pointer to the parent, controlpoly a controlpolygon Bezier3D( ParametricLine* par, QVector* controlpoly ); - /** Destructor*/ + //! Destructor virtual ~Bezier3D(); - /** Do not use this method, since a Bezier curve does not consist of other curves*/ + //! Do not use this method, since a Bezier curve does not consist of other curves virtual void add( ParametricLine *pl ) override; - /** Calculates the first derivative and assigns it to v*/ + //! Calculates the first derivative and assigns it to v virtual void calcFirstDer( float t, Vector3D* v ) override; - /** Calculates the second derivative and assigns it to v*/ + //! Calculates the second derivative and assigns it to v virtual void calcSecDer( float t, Vector3D* v ) override; //virtual Point3D calcPoint(float t); - /** Calculates the point on the curve and assigns it to p*/ + //! Calculates the point on the curve and assigns it to p virtual void calcPoint( float t, Point3D* p ) override; - /** Changes the order of control points*/ + //! Changes the order of control points virtual void changeDirection() override; //virtual void draw(QPainter* p); //virtual bool intersects(ParametricLine* pal); - /** Do not use this method, since a Bezier curve does not consist of other curves*/ + //! Do not use this method, since a Bezier curve does not consist of other curves virtual void remove( int i ) override; - /** Returns a control point*/ + //! Returns a control point virtual const Point3D* getControlPoint( int number ) const override; - /** Returns a pointer to the control polygon*/ + //! Returns a pointer to the control polygon virtual const QVector* getControlPoly() const override; - /** Returns the degree of the curve*/ + //! Returns the degree of the curve virtual int getDegree() const override; - /** Returns the parent*/ + //! Returns the parent virtual ParametricLine* getParent() const override; - /** Sets the parent*/ + //! Sets the parent virtual void setParent( ParametricLine* par ) override; - /** Sets the control polygon*/ + //! Sets the control polygon virtual void setControlPoly( QVector* cp ) override; }; diff --git a/src/analysis/interpolation/CloughTocherInterpolator.h b/src/analysis/interpolation/CloughTocherInterpolator.h index b6884ee99fe5..7458c962c3ec 100644 --- a/src/analysis/interpolation/CloughTocherInterpolator.h +++ b/src/analysis/interpolation/CloughTocherInterpolator.h @@ -27,15 +27,15 @@ class NormVecDecorator; class ANALYSIS_EXPORT CloughTocherInterpolator : public TriangleInterpolator { protected: - /** Association with a triangulation object*/ + //! Association with a triangulation object NormVecDecorator* mTIN; - /** Tolerance of the barycentric coordinates at the borders of the triangles (to prevent errors because of very small negativ baricentric coordinates)*/ + //! Tolerance of the barycentric coordinates at the borders of the triangles (to prevent errors because of very small negativ baricentric coordinates) double mEdgeTolerance; - /** First point of the triangle in x-,y-,z-coordinates*/ + //! First point of the triangle in x-,y-,z-coordinates Point3D point1; - /** Second point of the triangle in x-,y-,z-coordinates*/ + //! Second point of the triangle in x-,y-,z-coordinates Point3D point2; - /** Third point of the triangle in x-,y-,z-coordinates*/ + //! Third point of the triangle in x-,y-,z-coordinates Point3D point3; Point3D cp1; Point3D cp2; @@ -53,39 +53,39 @@ class ANALYSIS_EXPORT CloughTocherInterpolator : public TriangleInterpolator Point3D cp14; Point3D cp15; Point3D cp16; - /** Derivative in x-direction at point1*/ + //! Derivative in x-direction at point1 double der1X; - /** Derivative in y-direction at point1*/ + //! Derivative in y-direction at point1 double der1Y; - /** Derivative in x-direction at point2*/ + //! Derivative in x-direction at point2 double der2X; - /** Derivative in y-direction at point2*/ + //! Derivative in y-direction at point2 double der2Y; - /** Derivative in x-direction at point3*/ + //! Derivative in x-direction at point3 double der3X; - /** Derivative in y-direction at point3*/ + //! Derivative in y-direction at point3 double der3Y; - /** Stores point1 of the last run*/ + //! Stores point1 of the last run Point3D lpoint1; - /** Stores point2 of the last run*/ + //! Stores point2 of the last run Point3D lpoint2; - /** Stores point3 of the last run*/ + //! Stores point3 of the last run Point3D lpoint3; - /** Finds out, in which triangle the point with the coordinates x and y is*/ + //! Finds out, in which triangle the point with the coordinates x and y is void init( double x, double y ); - /** Calculates the Bernsteinpolynomials to calculate the Beziertriangle. 'n' is three in the cubical case, 'i', 'j', 'k' are the indices of the controllpoint and 'u', 'v', 'w' are the barycentric coordinates of the point*/ + //! Calculates the Bernsteinpolynomials to calculate the Beziertriangle. 'n' is three in the cubical case, 'i', 'j', 'k' are the indices of the controllpoint and 'u', 'v', 'w' are the barycentric coordinates of the point double calcBernsteinPoly( int n, int i, int j, int k, double u, double v, double w ); public: - /** Standard constructor*/ + //! Standard constructor CloughTocherInterpolator(); - /** Constructor with a pointer to the triangulation as argument*/ + //! Constructor with a pointer to the triangulation as argument CloughTocherInterpolator( NormVecDecorator* tin ); - /** Destructor*/ + //! Destructor virtual ~CloughTocherInterpolator(); - /** Calculates the normal vector and assigns it to vec (not implemented at the moment)*/ + //! Calculates the normal vector and assigns it to vec (not implemented at the moment) virtual bool calcNormVec( double x, double y, Vector3D* result ) override; - /** Performs a linear interpolation in a triangle and assigns the x-,y- and z-coordinates to point*/ + //! Performs a linear interpolation in a triangle and assigns the x-,y- and z-coordinates to point virtual bool calcPoint( double x, double y, Point3D* result ) override; virtual void setTriangulation( NormVecDecorator* tin ); }; diff --git a/src/analysis/interpolation/DualEdgeTriangulation.h b/src/analysis/interpolation/DualEdgeTriangulation.h index c485726b34dc..6c9e6cfda432 100644 --- a/src/analysis/interpolation/DualEdgeTriangulation.h +++ b/src/analysis/interpolation/DualEdgeTriangulation.h @@ -41,137 +41,137 @@ class ANALYSIS_EXPORT DualEdgeTriangulation: public Triangulation DualEdgeTriangulation( int nop, Triangulation* decorator ); virtual ~DualEdgeTriangulation(); void setDecorator( Triangulation* d ) {mDecorator = d;} - /** Adds a line (e.g. a break-, structure- or an isoline) to the triangulation. The class takes ownership of the line object and its points*/ + //! Adds a line (e.g. a break-, structure- or an isoline) to the triangulation. The class takes ownership of the line object and its points void addLine( Line3D* line, bool breakline ) override; - /** Adds a point to the triangulation and returns the number of this point in case of success or -100 in case of failure*/ + //! Adds a point to the triangulation and returns the number of this point in case of success or -100 in case of failure int addPoint( Point3D* p ) override; - /** Performs a consistency check, remove this later*/ + //! Performs a consistency check, remove this later virtual void performConsistencyTest() override; - /** Calculates the normal at a point on the surface*/ + //! Calculates the normal at a point on the surface virtual bool calcNormal( double x, double y, Vector3D* result ) override; - /** Calculates x-, y and z-value of the point on the surface*/ + //! Calculates x-, y and z-value of the point on the surface virtual bool calcPoint( double x, double y, Point3D* result ) override; - /** Draws the points, edges and the forced lines*/ + //! Draws the points, edges and the forced lines //virtual void draw(QPainter* p, double xlowleft, double ylowleft, double xupright, double yupright, double width, double height) const; - /** Returns a pointer to the point with number i*/ + //! Returns a pointer to the point with number i virtual Point3D* getPoint( unsigned int i ) const override; - /** Returns the number of the point opposite to the triangle points p1, p2 (which have to be on a halfedge)*/ + //! Returns the number of the point opposite to the triangle points p1, p2 (which have to be on a halfedge) int getOppositePoint( int p1, int p2 ) override; - /** Finds out, in which triangle the point with coordinates x and y is and assigns the numbers of the vertices to 'n1', 'n2' and 'n3' and the vertices to 'p1', 'p2' and 'p3'*/ + //! Finds out, in which triangle the point with coordinates x and y is and assigns the numbers of the vertices to 'n1', 'n2' and 'n3' and the vertices to 'p1', 'p2' and 'p3' //! @note not available in python bindings virtual bool getTriangle( double x, double y, Point3D* p1, int* n1, Point3D* p2, int* n2, Point3D* p3, int* n3 ) override; - /** Finds out, in which triangle the point with coordinates x and y is and assigns addresses to the points at the vertices to 'p1', 'p2' and 'p3*/ + //! Finds out, in which triangle the point with coordinates x and y is and assigns addresses to the points at the vertices to 'p1', 'p2' and 'p3 virtual bool getTriangle( double x, double y, Point3D* p1, Point3D* p2, Point3D* p3 ) override; - /** Returns a pointer to a value list with the information of the triangles surrounding (counterclockwise) a point. Four integer values describe a triangle, the first three are the number of the half edges of the triangle and the fourth is -10, if the third (and most counterclockwise) edge is a breakline, and -20 otherwise. The value list has to be deleted by the code which called the method*/ + //! Returns a pointer to a value list with the information of the triangles surrounding (counterclockwise) a point. Four integer values describe a triangle, the first three are the number of the half edges of the triangle and the fourth is -10, if the third (and most counterclockwise) edge is a breakline, and -20 otherwise. The value list has to be deleted by the code which called the method QList* getSurroundingTriangles( int pointno ) override; - /** Returns the largest x-coordinate value of the bounding box*/ + //! Returns the largest x-coordinate value of the bounding box virtual double getXMax() const override { return xMax; } - /** Returns the smallest x-coordinate value of the bounding box*/ + //! Returns the smallest x-coordinate value of the bounding box virtual double getXMin() const override { return xMin; } - /** Returns the largest y-coordinate value of the bounding box*/ + //! Returns the largest y-coordinate value of the bounding box virtual double getYMax() const override { return yMax; } - /** Returns the smallest x-coordinate value of the bounding box*/ + //! Returns the smallest x-coordinate value of the bounding box virtual double getYMin() const override { return yMin; } - /** Returns the number of points*/ + //! Returns the number of points virtual int getNumberOfPoints() const override; - /** Sets the behaviour of the triangulation in case of crossing forced lines*/ + //! Sets the behaviour of the triangulation in case of crossing forced lines virtual void setForcedCrossBehaviour( Triangulation::forcedCrossBehaviour b ) override; - /** Sets the color of the normal edges*/ + //! Sets the color of the normal edges virtual void setEdgeColor( int r, int g, int b ) override; - /** Sets the color of the forced edges*/ + //! Sets the color of the forced edges virtual void setForcedEdgeColor( int r, int g, int b ) override; - /** Sets the color of the breaklines*/ + //! Sets the color of the breaklines virtual void setBreakEdgeColor( int r, int g, int b ) override; - /** Sets an interpolator object*/ + //! Sets an interpolator object void setTriangleInterpolator( TriangleInterpolator* interpolator ) override; - /** Eliminates the horizontal triangles by swapping or by insertion of new points*/ + //! Eliminates the horizontal triangles by swapping or by insertion of new points void eliminateHorizontalTriangles() override; - /** Adds points to make the triangles better shaped (algorithm of ruppert)*/ + //! Adds points to make the triangles better shaped (algorithm of ruppert) virtual void ruppertRefinement() override; - /** Returns true, if the point with coordinates x and y is inside the convex hull and false otherwise*/ + //! Returns true, if the point with coordinates x and y is inside the convex hull and false otherwise bool pointInside( double x, double y ) override; - /** Reads the dual edge structure of a taff file*/ + //! Reads the dual edge structure of a taff file //bool readFromTAFF(QString fileName); - /** Saves the dual edge structure to a taff file*/ + //! Saves the dual edge structure to a taff file //bool saveToTAFF(QString fileName) const; - /** Swaps the edge which is closest to the point with x and y coordinates (if this is possible)*/ + //! Swaps the edge which is closest to the point with x and y coordinates (if this is possible) virtual bool swapEdge( double x, double y ) override; - /** Returns a value list with the numbers of the four points, which would be affected by an edge swap. This function is e.g. needed by NormVecDecorator to know the points, for which the normals have to be recalculated. The returned ValueList has to be deleted by the code which calls the method*/ + //! Returns a value list with the numbers of the four points, which would be affected by an edge swap. This function is e.g. needed by NormVecDecorator to know the points, for which the normals have to be recalculated. The returned ValueList has to be deleted by the code which calls the method virtual QList* getPointsAroundEdge( double x, double y ) override; /** Saves the triangulation as a (line) shapefile @return true in case of success*/ virtual bool saveAsShapefile( const QString& fileName ) const override; protected: - /** X-coordinate of the upper right corner of the bounding box*/ + //! X-coordinate of the upper right corner of the bounding box double xMax; - /** X-coordinate of the lower left corner of the bounding box*/ + //! X-coordinate of the lower left corner of the bounding box double xMin; - /** Y-coordinate of the upper right corner of the bounding box*/ + //! Y-coordinate of the upper right corner of the bounding box double yMax; - /** Y-coordinate of the lower left corner of the bounding box*/ + //! Y-coordinate of the lower left corner of the bounding box double yMin; - /** Default value for the number of storable points at the beginning*/ + //! Default value for the number of storable points at the beginning const static unsigned int mDefaultStorageForPoints = 100000; - /** Stores pointers to all points in the triangulations (including the points contained in the lines)*/ + //! Stores pointers to all points in the triangulations (including the points contained in the lines) QVector mPointVector; - /** Default value for the number of storable HalfEdges at the beginning*/ + //! Default value for the number of storable HalfEdges at the beginning const static unsigned int mDefaultStorageForHalfEdges = 300006; - /** Stores pointers to the HalfEdges*/ + //! Stores pointers to the HalfEdges QVector mHalfEdge; - /** Association to an interpolator object*/ + //! Association to an interpolator object TriangleInterpolator* mTriangleInterpolator; - /** Member to store the behaviour in case of crossing forced segments*/ + //! Member to store the behaviour in case of crossing forced segments Triangulation::forcedCrossBehaviour mForcedCrossBehaviour; - /** Color to paint the normal edges*/ + //! Color to paint the normal edges QColor mEdgeColor; - /** Color to paint the forced edges*/ + //! Color to paint the forced edges QColor mForcedEdgeColor; - /** Color to paint the breaklines*/ + //! Color to paint the breaklines QColor mBreakEdgeColor; - /** Pointer to the decorator using this triangulation. It it is used directly, mDecorator equals this*/ + //! Pointer to the decorator using this triangulation. It it is used directly, mDecorator equals this Triangulation* mDecorator; - /** Inserts an edge and makes sure, everything is ok with the storage of the edge. The number of the HalfEdge is returned*/ + //! Inserts an edge and makes sure, everything is ok with the storage of the edge. The number of the HalfEdge is returned unsigned int insertEdge( int dual, int next, int point, bool mbreak, bool forced ); - /** Inserts a forced segment between the points with the numbers p1 and p2 into the triangulation and returns the number of a HalfEdge belonging to this forced edge or -100 in case of failure*/ + //! Inserts a forced segment between the points with the numbers p1 and p2 into the triangulation and returns the number of a HalfEdge belonging to this forced edge or -100 in case of failure int insertForcedSegment( int p1, int p2, bool breakline ); - /** Threshold for the leftOfTest to handle numerical instabilities*/ + //! Threshold for the leftOfTest to handle numerical instabilities //const static double leftOfTresh=0.00001; - /** Security to prevent endless loops in 'baseEdgeOfTriangle'. It there are more iteration then this number, the point will not be inserted*/ + //! Security to prevent endless loops in 'baseEdgeOfTriangle'. It there are more iteration then this number, the point will not be inserted const static int nBaseOfRuns = 300000; - /** Returns the number of an edge which points to the point with number 'point' or -1 if there is an error*/ + //! Returns the number of an edge which points to the point with number 'point' or -1 if there is an error int baseEdgeOfPoint( int point ); - /** Returns the number of a HalfEdge from a triangle in which 'point' is in. If the number -10 is returned, this means, that 'point' is outside the convex hull. If -5 is returned, then numerical problems with the leftOfTest occurred (and the value of the possible edge is stored in the variable 'mUnstableEdge'. -20 means, that the inserted point is exactly on an edge (the number is stored in the variable 'mEdgeWithPoint'). -25 means, that the point is already in the triangulation (the number of the point is stored in the member 'mTwiceInsPoint'. If -100 is returned, this means that something else went wrong*/ + //! Returns the number of a HalfEdge from a triangle in which 'point' is in. If the number -10 is returned, this means, that 'point' is outside the convex hull. If -5 is returned, then numerical problems with the leftOfTest occurred (and the value of the possible edge is stored in the variable 'mUnstableEdge'. -20 means, that the inserted point is exactly on an edge (the number is stored in the variable 'mEdgeWithPoint'). -25 means, that the point is already in the triangulation (the number of the point is stored in the member 'mTwiceInsPoint'. If -100 is returned, this means that something else went wrong int baseEdgeOfTriangle( Point3D* point ); - /** Checks, if 'edge' has to be swapped because of the empty circle criterion. If so, doSwap(...) is called.*/ + //! Checks, if 'edge' has to be swapped because of the empty circle criterion. If so, doSwap(...) is called. bool checkSwap( unsigned int edge, unsigned int recursiveDeep ); - /** Swaps 'edge' and test recursively for other swaps (delaunay criterion)*/ + //! Swaps 'edge' and test recursively for other swaps (delaunay criterion) void doSwap( unsigned int edge, unsigned int recursiveDeep ); - /** Swaps 'edge' and does no recursiv testing*/ + //! Swaps 'edge' and does no recursiv testing void doOnlySwap( unsigned int edge ); - /** Number of an edge which does not point to the virtual point. It continuously updated for a fast search*/ + //! Number of an edge which does not point to the virtual point. It continuously updated for a fast search unsigned int mEdgeInside; - /** Number of an edge on the outside of the convex hull. It is updated in method 'baseEdgeOfTriangle' to enable insertion of points outside the convex hull*/ + //! Number of an edge on the outside of the convex hull. It is updated in method 'baseEdgeOfTriangle' to enable insertion of points outside the convex hull unsigned int mEdgeOutside; - /** If an inserted point is exactly on an existing edge, 'baseEdgeOfTriangle' returns -20 and sets the variable 'mEdgeWithPoint'*/ + //! If an inserted point is exactly on an existing edge, 'baseEdgeOfTriangle' returns -20 and sets the variable 'mEdgeWithPoint' unsigned int mEdgeWithPoint; - /** If an instability occurs in 'baseEdgeOfTriangle', mUnstableEdge is set to the value of the current edge*/ + //! If an instability occurs in 'baseEdgeOfTriangle', mUnstableEdge is set to the value of the current edge unsigned int mUnstableEdge; - /** If a point has been inserted twice, its number is stored in this member*/ + //! If a point has been inserted twice, its number is stored in this member int mTwiceInsPoint; - /** Returns true, if it is possible to swap an edge, otherwise false(concave quad or edge on (or outside) the convex hull)*/ + //! Returns true, if it is possible to swap an edge, otherwise false(concave quad or edge on (or outside) the convex hull) bool swapPossible( unsigned int edge ); - /** Divides a polygon in a triangle and two polygons and calls itself recursively for these two polygons. 'poly' is a pointer to a list with the numbers of the edges of the polygon, 'free' is a pointer to a list of free halfedges, and 'mainedge' is the number of the edge, towards which the new triangle is inserted. Mainedge has to be the same as poly->begin(), otherwise the recursion does not work*/ + //! Divides a polygon in a triangle and two polygons and calls itself recursively for these two polygons. 'poly' is a pointer to a list with the numbers of the edges of the polygon, 'free' is a pointer to a list of free halfedges, and 'mainedge' is the number of the edge, towards which the new triangle is inserted. Mainedge has to be the same as poly->begin(), otherwise the recursion does not work void triangulatePolygon( QList* poly, QList* free, int mainedge ); - /** Tests, if the bounding box of the halfedge with index i intersects the specified bounding box. The main purpose for this method is the drawing of the triangulation*/ + //! Tests, if the bounding box of the halfedge with index i intersects the specified bounding box. The main purpose for this method is the drawing of the triangulation bool halfEdgeBBoxTest( int edge, double xlowleft, double ylowleft, double xupright, double yupright ) const; - /** Calculates the minimum angle, which would be present, if the specified halfedge would be swapped*/ + //! Calculates the minimum angle, which would be present, if the specified halfedge would be swapped double swapMinAngle( int edge ) const; - /** Inserts a new point on the halfedge with number 'edge'. The position can have a value from 0 to 1 (e.g. 0.5 would be in the middle). The return value is the number of the new inserted point. tin is the triangulation, which should be used to calculate the elevation of the inserted point*/ + //! Inserts a new point on the halfedge with number 'edge'. The position can have a value from 0 to 1 (e.g. 0.5 would be in the middle). The return value is the number of the new inserted point. tin is the triangulation, which should be used to calculate the elevation of the inserted point int splitHalfEdge( int edge, float position ); - /** Returns true, if a half edge is on the convex hull and false otherwise*/ + //! Returns true, if a half edge is on the convex hull and false otherwise bool edgeOnConvexHull( int edge ); - /** Function needed for the ruppert algorithm. Tests, if point is in the circle through both endpoints of edge and the endpoint of edge->dual->next->point. If so, the function calls itself recursively for edge->next and edge->next->next. Stops, if it finds a forced edge or a convex hull edge*/ + //! Function needed for the ruppert algorithm. Tests, if point is in the circle through both endpoints of edge and the endpoint of edge->dual->next->point. If so, the function calls itself recursively for edge->next and edge->next->next. Stops, if it finds a forced edge or a convex hull edge void evaluateInfluenceRegion( Point3D* point, int edge, QSet &set ); }; diff --git a/src/analysis/interpolation/HalfEdge.h b/src/analysis/interpolation/HalfEdge.h index 1d4f10967f44..17d26874778a 100644 --- a/src/analysis/interpolation/HalfEdge.h +++ b/src/analysis/interpolation/HalfEdge.h @@ -23,41 +23,41 @@ class ANALYSIS_EXPORT HalfEdge { protected: - /** Number of the dual HalfEdge*/ + //! Number of the dual HalfEdge int mDual; - /** Number of the next HalfEdge*/ + //! Number of the next HalfEdge int mNext; - /** Number of the point at which this HalfEdge points*/ + //! Number of the point at which this HalfEdge points int mPoint; - /** True, if the HalfEdge belongs to a break line, false otherwise*/ + //! True, if the HalfEdge belongs to a break line, false otherwise bool mBreak; - /** True, if the HalfEdge belongs to a constrained edge, false otherwise*/ + //! True, if the HalfEdge belongs to a constrained edge, false otherwise bool mForced; public: - /** Default constructor. Values for mDual, mNext, mPoint are set to -10 which means that they are undefined*/ + //! Default constructor. Values for mDual, mNext, mPoint are set to -10 which means that they are undefined HalfEdge(); HalfEdge( int dual, int next, int point, bool mbreak, bool forced ); ~HalfEdge(); - /** Returns the number of the dual HalfEdge*/ + //! Returns the number of the dual HalfEdge int getDual() const; - /** Returns the number of the next HalfEdge*/ + //! Returns the number of the next HalfEdge int getNext() const; - /** Returns the number of the point at which this HalfEdge points*/ + //! Returns the number of the point at which this HalfEdge points int getPoint() const; - /** Returns, whether the HalfEdge belongs to a break line or not*/ + //! Returns, whether the HalfEdge belongs to a break line or not bool getBreak() const; - /** Returns, whether the HalfEdge belongs to a constrained edge or not*/ + //! Returns, whether the HalfEdge belongs to a constrained edge or not bool getForced() const; - /** Sets the number of the dual HalfEdge*/ + //! Sets the number of the dual HalfEdge void setDual( int d ); - /** Sets the number of the next HalfEdge*/ + //! Sets the number of the next HalfEdge void setNext( int n ); - /** Sets the number of point at which this HalfEdge points*/ + //! Sets the number of point at which this HalfEdge points void setPoint( int p ); - /** Sets the break flag*/ + //! Sets the break flag void setBreak( bool b ); - /** Sets the forced flag*/ + //! Sets the forced flag void setForced( bool f ); }; diff --git a/src/analysis/interpolation/LinTriangleInterpolator.h b/src/analysis/interpolation/LinTriangleInterpolator.h index 3aededa2f5e4..75de7762533a 100644 --- a/src/analysis/interpolation/LinTriangleInterpolator.h +++ b/src/analysis/interpolation/LinTriangleInterpolator.h @@ -25,27 +25,27 @@ class ANALYSIS_EXPORT LinTriangleInterpolator : public TriangleInterpolator { public: - /** Default constructor*/ + //! Default constructor LinTriangleInterpolator(); - /** Constructor with reference to a DualEdgeTriangulation object*/ + //! Constructor with reference to a DualEdgeTriangulation object LinTriangleInterpolator( DualEdgeTriangulation* tin ); - /** Destructor*/ + //! Destructor virtual ~LinTriangleInterpolator(); - /** Calculates the normal vector and assigns it to vec*/ + //! Calculates the normal vector and assigns it to vec virtual bool calcNormVec( double x, double y, Vector3D* result ) override; - /** Performs a linear interpolation in a triangle and assigns the x-,y- and z-coordinates to point*/ + //! Performs a linear interpolation in a triangle and assigns the x-,y- and z-coordinates to point virtual bool calcPoint( double x, double y, Point3D* result ) override; - /** Returns a pointer to the current Triangulation object*/ + //! Returns a pointer to the current Triangulation object virtual DualEdgeTriangulation* getTriangulation() const; - /** Sets a Triangulation*/ + //! Sets a Triangulation virtual void setTriangulation( DualEdgeTriangulation* tin ); protected: DualEdgeTriangulation* mTIN; - /** Calculates the first derivative with respect to x for a linear surface and assigns it to vec*/ + //! Calculates the first derivative with respect to x for a linear surface and assigns it to vec virtual bool calcFirstDerX( double x, double y, Vector3D* result ); - /** Calculates the first derivative with respect to y for a linear surface and assigns it to vec*/ + //! Calculates the first derivative with respect to y for a linear surface and assigns it to vec virtual bool calcFirstDerY( double x, double y, Vector3D* result ); }; diff --git a/src/analysis/interpolation/Line3D.h b/src/analysis/interpolation/Line3D.h index 51f496235d87..f0635f86c38b 100644 --- a/src/analysis/interpolation/Line3D.h +++ b/src/analysis/interpolation/Line3D.h @@ -24,9 +24,9 @@ class ANALYSIS_EXPORT Line3D { private: - /** Copy constructor, declared private to not use it*/ + //! Copy constructor, declared private to not use it Line3D( const Line3D& ); - /** Assignment operator, declared private to not use it*/ + //! Assignment operator, declared private to not use it Line3D& operator=( const Line3D& ); protected: Node* head; @@ -38,21 +38,21 @@ class ANALYSIS_EXPORT Line3D public: Line3D(); ~Line3D(); - /** Returns true, if the Line contains no Point3D, otherwise false*/ + //! Returns true, if the Line contains no Point3D, otherwise false bool empty() const; - /** Inserts a node behind the current position and sets the current position to this new node*/ + //! Inserts a node behind the current position and sets the current position to this new node void insertPoint( Point3D* p ); - /** Removes the point behind the current position*/ + //! Removes the point behind the current position void removePoint(); - /** Gets the point at the current position*/ + //! Gets the point at the current position Point3D* getPoint() const; - /** Returns the current position*/ + //! Returns the current position unsigned int getCurrent() const; - /** Returns the size of the line (the numbero of inserted Nodes without 'head' and 'z'*/ + //! Returns the size of the line (the numbero of inserted Nodes without 'head' and 'z' unsigned int getSize() const; - /** Sets the current Node to head*/ + //! Sets the current Node to head void goToBegin(); - /** Goes to the next Node*/ + //! Goes to the next Node void goToNext(); }; diff --git a/src/analysis/interpolation/MathUtils.h b/src/analysis/interpolation/MathUtils.h index e1936b8d8024..8cab13a703a7 100644 --- a/src/analysis/interpolation/MathUtils.h +++ b/src/analysis/interpolation/MathUtils.h @@ -24,60 +24,60 @@ class Vector3D; namespace MathUtils { - /** Calculates the barycentric coordinates of a point (x,y) with respect to p1, p2, p3 and stores the three barycentric coordinates in 'result'. Thus the u-coordinate is stored in result::x, the v-coordinate in result::y and the w-coordinate in result::z. Attention: p1, p2 and p3 have to be ordered counterclockwise*/ + //! Calculates the barycentric coordinates of a point (x,y) with respect to p1, p2, p3 and stores the three barycentric coordinates in 'result'. Thus the u-coordinate is stored in result::x, the v-coordinate in result::y and the w-coordinate in result::z. Attention: p1, p2 and p3 have to be ordered counterclockwise bool ANALYSIS_EXPORT calcBarycentricCoordinates( double x, double y, Point3D* p1, Point3D* p2, Point3D* p3, Point3D* result ); bool ANALYSIS_EXPORT BarycentricToXY( double u, double v, double w, Point3D* p1, Point3D* p2, Point3D* p3, Point3D* result ); - /** Calculates the value of a Bernstein polynomial*/ + //! Calculates the value of a Bernstein polynomial double ANALYSIS_EXPORT calcBernsteinPoly( int n, int i, double t ); - /** Calculates the first derivative of a Bernstein polynomial with respect to the parameter t*/ + //! Calculates the first derivative of a Bernstein polynomial with respect to the parameter t double ANALYSIS_EXPORT cFDerBernsteinPoly( int n, int i, double t ); - /** Calculates the value of a cubic Hermite polynomial*/ + //! Calculates the value of a cubic Hermite polynomial double ANALYSIS_EXPORT calcCubicHermitePoly( int n, int i, double t ); - /** Calculates the first derivative of a cubic Hermite polynomial with respect to the parameter t*/ + //! Calculates the first derivative of a cubic Hermite polynomial with respect to the parameter t double ANALYSIS_EXPORT cFDerCubicHermitePoly( int n, int i, double t ); - /** Calculates the center of the circle passing through p1, p2 and p3. Returns true in case of success and false otherwise (e.g. all three points on a line)*/ + //! Calculates the center of the circle passing through p1, p2 and p3. Returns true in case of success and false otherwise (e.g. all three points on a line) bool ANALYSIS_EXPORT circumcenter( Point3D* p1, Point3D* p2, Point3D* p3, Point3D* result ); - /** Calculates the (2 dimensional) distance from 'thepoint' to the line defined by p1 and p2*/ + //! Calculates the (2 dimensional) distance from 'thepoint' to the line defined by p1 and p2 double ANALYSIS_EXPORT distPointFromLine( Point3D* thepoint, Point3D* p1, Point3D* p2 ); - /** Faculty function*/ + //! Faculty function int ANALYSIS_EXPORT faculty( int n ); - /** Tests, whether 'testp' is inside the circle through 'p1', 'p2' and 'p3'*/ + //! Tests, whether 'testp' is inside the circle through 'p1', 'p2' and 'p3' bool ANALYSIS_EXPORT inCircle( Point3D* testp, Point3D* p1, Point3D* p2, Point3D* p3 ); - /** Tests, whether 'point' is inside the diametral circle through 'p1' and 'p2'*/ + //! Tests, whether 'point' is inside the diametral circle through 'p1' and 'p2' bool ANALYSIS_EXPORT inDiametral( Point3D* p1, Point3D* p2, Point3D* point ); - /** Returns whether 'thepoint' is left or right of the line from 'p1' to 'p2'. Negativ values mean left and positiv values right. There may be numerical instabilities, so a threshold may be useful*/ + //! Returns whether 'thepoint' is left or right of the line from 'p1' to 'p2'. Negativ values mean left and positiv values right. There may be numerical instabilities, so a threshold may be useful double ANALYSIS_EXPORT leftOf( Point3D* thepoint, Point3D* p1, Point3D* p2 ); - /** Returns true, if line1 (p1 to p2) and line2 (p3 to p4) intersect. If the lines have an endpoint in common, false is returned*/ + //! Returns true, if line1 (p1 to p2) and line2 (p3 to p4) intersect. If the lines have an endpoint in common, false is returned bool ANALYSIS_EXPORT lineIntersection( Point3D* p1, Point3D* p2, Point3D* p3, Point3D* p4 ); - /** Returns true, if line1 (p1 to p2) and line2 (p3 to p4) intersect. If the lines have an endpoint in common, false is returned. The intersecting point is stored in 'intersection_point.*/ + //! Returns true, if line1 (p1 to p2) and line2 (p3 to p4) intersect. If the lines have an endpoint in common, false is returned. The intersecting point is stored in 'intersection_point. bool ANALYSIS_EXPORT lineIntersection( Point3D* p1, Point3D* p2, Point3D* p3, Point3D* p4, Point3D* intersection_point ); - /** Lower function*/ + //! Lower function int ANALYSIS_EXPORT lower( int n, int i ); - /** Returns the maximum of two doubles or the first argument if both are equal*/ + //! Returns the maximum of two doubles or the first argument if both are equal double ANALYSIS_EXPORT max( double x, double y ); - /** Returns the minimum of two doubles or the first argument if both are equal*/ + //! Returns the minimum of two doubles or the first argument if both are equal double ANALYSIS_EXPORT min( double x, double y ); - /** Power function for integer coefficients*/ + //! Power function for integer coefficients double ANALYSIS_EXPORT power( double a, int b );//calculates a power b - /** Returns the area of a triangle. If the points are ordered counterclockwise, the value will be positiv. If they are ordered clockwise, the value will be negativ*/ + //! Returns the area of a triangle. If the points are ordered counterclockwise, the value will be positiv. If they are ordered clockwise, the value will be negativ double ANALYSIS_EXPORT triArea( Point3D* pa, Point3D* pb, Point3D* pc ); - /** Calculates the z-component of a vector with coordinates 'x' and 'y'which is in the same tangent plane as the tangent vectors 'v1' and 'v2'. The result is assigned to 'result' */ + //! Calculates the z-component of a vector with coordinates 'x' and 'y'which is in the same tangent plane as the tangent vectors 'v1' and 'v2'. The result is assigned to 'result' bool ANALYSIS_EXPORT derVec( const Vector3D* v1, const Vector3D* v2, Vector3D* result, double x, double y ); - /** Calculates the intersection of the two vectors vec1 and vec2, which start at first(vec1) and second(vec2) end. The return value is t2(multiplication of v2 with t2 and adding to 'second' results the intersection point)*/ + //! Calculates the intersection of the two vectors vec1 and vec2, which start at first(vec1) and second(vec2) end. The return value is t2(multiplication of v2 with t2 and adding to 'second' results the intersection point) double ANALYSIS_EXPORT crossVec( Point3D* first, Vector3D* vec1, Point3D* second, Vector3D* vec2 ); - /** Assigns the vector 'result', which is normal to the vector 'v1', on the left side of v1 and has length 'length'. This method works only with two dimensions.*/ + //! Assigns the vector 'result', which is normal to the vector 'v1', on the left side of v1 and has length 'length'. This method works only with two dimensions. bool ANALYSIS_EXPORT normalLeft( Vector3D* v1, Vector3D* result, double length ); - /** Assigns the vector 'result', which is normal to the vector 'v1', on the right side of v1 and has length 'length'. The calculation is only in two dimensions*/ + //! Assigns the vector 'result', which is normal to the vector 'v1', on the right side of v1 and has length 'length'. The calculation is only in two dimensions bool ANALYSIS_EXPORT normalRight( Vector3D* v1, Vector3D* result, double length ); - /** Calculates the normal vector of the plane through the points p1, p2 and p3 and assigns the result to vec. If the points are ordered counterclockwise, the normal will have a positive z-coordinate;*/ + //! Calculates the normal vector of the plane through the points p1, p2 and p3 and assigns the result to vec. If the points are ordered counterclockwise, the normal will have a positive z-coordinate; void ANALYSIS_EXPORT normalFromPoints( Point3D* p1, Point3D* p2, Point3D* p3, Vector3D* vec ); - /** Returns true, if the point with coordinates x and y is inside (or at the edge) of the triangle p1,p2,p3 and false, if it is outside. p1, p2 and p3 have to be ordered counterclockwise*/ + //! Returns true, if the point with coordinates x and y is inside (or at the edge) of the triangle p1,p2,p3 and false, if it is outside. p1, p2 and p3 have to be ordered counterclockwise bool ANALYSIS_EXPORT pointInsideTriangle( double x, double y, Point3D* p1, Point3D* p2, Point3D* p3 ); - /** Calculates a Vector orthogonal to 'tangent' with length 1 and closest possible to result. Returns true in case of success and false otherwise*/ + //! Calculates a Vector orthogonal to 'tangent' with length 1 and closest possible to result. Returns true in case of success and false otherwise bool ANALYSIS_EXPORT normalMinDistance( Vector3D* tangent, Vector3D* target, Vector3D* result ); - /** Tests, if 'test' is in the same plane as 'p1', 'p2' and 'p3' and returns the z-difference from the plane to 'test*/ + //! Tests, if 'test' is in the same plane as 'p1', 'p2' and 'p3' and returns the z-difference from the plane to 'test double ANALYSIS_EXPORT planeTest( Point3D* test, Point3D* pt1, Point3D* pt2, Point3D* pt3 ); - /** Calculates the angle between two segments (in 2 dimension, z-values are ignored)*/ + //! Calculates the angle between two segments (in 2 dimension, z-values are ignored) double ANALYSIS_EXPORT angle( Point3D* p1, Point3D* p2, Point3D* p3, Point3D* p4 ); } diff --git a/src/analysis/interpolation/Node.h b/src/analysis/interpolation/Node.h index df9d034a20d9..0e941ebec9c7 100644 --- a/src/analysis/interpolation/Node.h +++ b/src/analysis/interpolation/Node.h @@ -24,22 +24,22 @@ class ANALYSIS_EXPORT Node { protected: - /** Pointer to the Point3D object associated with the node*/ + //! Pointer to the Point3D object associated with the node Point3D* mPoint; - /** Pointer to the next Node in the linked list*/ + //! Pointer to the next Node in the linked list Node* mNext; public: Node(); Node( const Node& n ); ~Node(); Node& operator=( const Node& n ); - /** Returns a pointer to the next element in the linked list*/ + //! Returns a pointer to the next element in the linked list Node* getNext() const; - /** Returns a pointer to the Point3D object associated with the node*/ + //! Returns a pointer to the Point3D object associated with the node Point3D* getPoint() const; - /** Sets the pointer to the next node*/ + //! Sets the pointer to the next node void setNext( Node* n ); - /** Sets a new pointer to an associated Point3D object*/ + //! Sets a new pointer to an associated Point3D object void setPoint( Point3D* p ); }; diff --git a/src/analysis/interpolation/NormVecDecorator.h b/src/analysis/interpolation/NormVecDecorator.h index efee2bb4ddd3..a0588101b971 100644 --- a/src/analysis/interpolation/NormVecDecorator.h +++ b/src/analysis/interpolation/NormVecDecorator.h @@ -29,54 +29,54 @@ class QProgressDialog; class ANALYSIS_EXPORT NormVecDecorator: public TriDecorator { public: - /** Enumeration for the state of a point. NORMAL means, that the point is not on a breakline, BREAKLINE means that the point is on a breakline (but not an endpoint of it) and ENDPOINT means, that it is an endpoint of a breakline*/ + //! Enumeration for the state of a point. NORMAL means, that the point is not on a breakline, BREAKLINE means that the point is on a breakline (but not an endpoint of it) and ENDPOINT means, that it is an endpoint of a breakline enum pointState {NORMAL, BREAKLINE, ENDPOINT}; NormVecDecorator(); NormVecDecorator( Triangulation* tin ); virtual ~NormVecDecorator(); - /** Adds a point to the triangulation*/ + //! Adds a point to the triangulation int addPoint( Point3D* p ) override; - /** Calculates the normal at a point on the surface and assigns it to 'result'. Returns true in case of success and false in case of failure*/ + //! Calculates the normal at a point on the surface and assigns it to 'result'. Returns true in case of success and false in case of failure bool calcNormal( double x, double y, Vector3D* result ) override; - /** Calculates the normal of a triangle-point for the point with coordinates x and y. This is needed, if a point is on a break line and there is no unique normal stored in 'mNormVec'. Returns false, it something went wrong and true otherwise*/ + //! Calculates the normal of a triangle-point for the point with coordinates x and y. This is needed, if a point is on a break line and there is no unique normal stored in 'mNormVec'. Returns false, it something went wrong and true otherwise bool calcNormalForPoint( double x, double y, int point, Vector3D* result ); - /** Calculates x-, y and z-value of the point on the surface and assigns it to 'result'. Returns true in case of success and flase in case of failure*/ + //! Calculates x-, y and z-value of the point on the surface and assigns it to 'result'. Returns true in case of success and flase in case of failure bool calcPoint( double x, double y, Point3D* result ) override; - /** Eliminates the horizontal triangles by swapping or by insertion of new points. If alreadyestimated is true, a re-estimation of the normals will be done*/ + //! Eliminates the horizontal triangles by swapping or by insertion of new points. If alreadyestimated is true, a re-estimation of the normals will be done virtual void eliminateHorizontalTriangles() override; - /** Estimates the first derivative a point. Return true in case of succes and false otherwise*/ + //! Estimates the first derivative a point. Return true in case of succes and false otherwise bool estimateFirstDerivative( int pointno ); - /** This method adds the functionality of estimating normals at the data points. Return true in the case of success and false otherwise*/ + //! This method adds the functionality of estimating normals at the data points. Return true in the case of success and false otherwise bool estimateFirstDerivatives( QProgressDialog* d = nullptr ); - /** Returns a pointer to the normal vector for the point with the number n*/ + //! Returns a pointer to the normal vector for the point with the number n Vector3D* getNormal( int n ) const; - /** Finds out, in which triangle a point with coordinates x and y is and assigns the triangle points to p1, p2, p3 and the estimated normals to v1, v2, v3. The vectors are normaly taken from 'mNormVec', exept if p1, p2 or p3 is a point on a breakline. In this case, the normal is calculated on-the-fly. Returns false, if something went wrong and true otherwise*/ + //! Finds out, in which triangle a point with coordinates x and y is and assigns the triangle points to p1, p2, p3 and the estimated normals to v1, v2, v3. The vectors are normaly taken from 'mNormVec', exept if p1, p2 or p3 is a point on a breakline. In this case, the normal is calculated on-the-fly. Returns false, if something went wrong and true otherwise bool getTriangle( double x, double y, Point3D* p1, Vector3D* v1, Point3D* p2, Vector3D* v2, Point3D* p3, Vector3D* v3 ); /** This function behaves similar to the one above. Additionally, the numbers of the points are returned (ptn1, ptn2, ptn3) as well as the pointStates of the triangle points (state1, state2, state3) * @note not available in Python bindings */ bool getTriangle( double x, double y, Point3D* p1, int* ptn1, Vector3D* v1, pointState* state1, Point3D* p2, int* ptn2, Vector3D* v2, pointState* state2, Point3D* p3, int* ptn3, Vector3D* v3, pointState* state3 ); - /** Returns the state of the point with the number 'pointno'*/ + //! Returns the state of the point with the number 'pointno' pointState getState( int pointno ) const; - /** Sets an interpolator*/ + //! Sets an interpolator void setTriangleInterpolator( TriangleInterpolator* inter ) override; - /** Swaps the edge which is closest to the point with x and y coordinates (if this is possible) and forces recalculation of the concerned normals (if alreadyestimated is true)*/ + //! Swaps the edge which is closest to the point with x and y coordinates (if this is possible) and forces recalculation of the concerned normals (if alreadyestimated is true) virtual bool swapEdge( double x, double y ) override; /** Saves the triangulation as a (line) shapefile @return true in case of success*/ virtual bool saveAsShapefile( const QString& fileName ) const override; protected: - /** Is true, if the normals already have been estimated*/ + //! Is true, if the normals already have been estimated bool alreadyestimated; const static unsigned int mDefaultStorageForNormals = 100000; - /** Association with an interpolator object*/ + //! Association with an interpolator object TriangleInterpolator* mInterpolator; - /** Vector that stores the normals for the points. If 'estimateFirstDerivatives()' was called and there is a null pointer, this means, that the triangle point is on a breakline*/ + //! Vector that stores the normals for the points. If 'estimateFirstDerivatives()' was called and there is a null pointer, this means, that the triangle point is on a breakline QVector* mNormVec; - /** Vector who stores, it a point is not on a breakline, if it is a normal point of the breakline or if it is an endpoint of a breakline*/ + //! Vector who stores, it a point is not on a breakline, if it is a normal point of the breakline or if it is an endpoint of a breakline QVector* mPointState; - /** Sets the state (BREAKLINE, NORMAL, ENDPOINT) of a point*/ + //! Sets the state (BREAKLINE, NORMAL, ENDPOINT) of a point void setState( int pointno, pointState s ); }; diff --git a/src/analysis/interpolation/ParametricLine.h b/src/analysis/interpolation/ParametricLine.h index 44650d4bcad7..7005eff00b35 100644 --- a/src/analysis/interpolation/ParametricLine.h +++ b/src/analysis/interpolation/ParametricLine.h @@ -28,19 +28,19 @@ class Vector3D; class ANALYSIS_EXPORT ParametricLine { protected: - /** Degree of the parametric Line*/ + //! Degree of the parametric Line int mDegree; - /** Pointer to the parent object. If there isn't one, mParent is 0*/ + //! Pointer to the parent object. If there isn't one, mParent is 0 ParametricLine* mParent; - /** MControlPoly stores the points of the control polygon*/ + //! MControlPoly stores the points of the control polygon QVector* mControlPoly; public: - /** Default constructor*/ + //! Default constructor ParametricLine(); /** Constructor, par is a pointer to the parent object, controlpoly the controlpolygon */ ParametricLine( ParametricLine* par, QVector* controlpoly ); - /** Destructor*/ + //! Destructor virtual ~ParametricLine(); virtual void add( ParametricLine* pl ) = 0; virtual void calcFirstDer( float t, Vector3D* v ) = 0; diff --git a/src/analysis/interpolation/Point3D.h b/src/analysis/interpolation/Point3D.h index 97abdc42f36e..013d4832d8ff 100644 --- a/src/analysis/interpolation/Point3D.h +++ b/src/analysis/interpolation/Point3D.h @@ -24,34 +24,34 @@ class ANALYSIS_EXPORT Point3D { protected: - /** X-coordinate*/ + //! X-coordinate double mX; - /** Y-coordinate*/ + //! Y-coordinate double mY; - /** Z-coordinate*/ + //! Z-coordinate double mZ; public: Point3D(); - /** Constructor with the x-, y- and z-coordinate as arguments*/ + //! Constructor with the x-, y- and z-coordinate as arguments Point3D( double x, double y, double z ); Point3D( const Point3D& p ); ~Point3D(); Point3D& operator=( const Point3D& p ); bool operator==( const Point3D& p ) const; bool operator!=( const Point3D& p ) const; - /** Calculates the three-dimensional distance to another point*/ + //! Calculates the three-dimensional distance to another point double dist3D( Point3D* p ) const; - /** Returns the x-coordinate of the point*/ + //! Returns the x-coordinate of the point double getX() const; - /** Returns the y-coordinate of the point*/ + //! Returns the y-coordinate of the point double getY() const; - /** Returns the z-coordinate of the point*/ + //! Returns the z-coordinate of the point double getZ() const; - /** Sets the x-coordinate of the point*/ + //! Sets the x-coordinate of the point void setX( double x ); - /** Sets the y-coordinate of the point*/ + //! Sets the y-coordinate of the point void setY( double y ); - /** Sets the z-coordinate of the point*/ + //! Sets the z-coordinate of the point void setZ( double z ); }; diff --git a/src/analysis/interpolation/TriDecorator.h b/src/analysis/interpolation/TriDecorator.h index 6c5121294afa..2c65eff99251 100644 --- a/src/analysis/interpolation/TriDecorator.h +++ b/src/analysis/interpolation/TriDecorator.h @@ -29,9 +29,9 @@ class ANALYSIS_EXPORT TriDecorator : public Triangulation virtual ~TriDecorator(); virtual void addLine( Line3D* line, bool breakline ) override; virtual int addPoint( Point3D* p ) override; - /** Adds an association to a triangulation*/ + //! Adds an association to a triangulation virtual void addTriangulation( Triangulation* t ); - /** Performs a consistency check, remove this later*/ + //! Performs a consistency check, remove this later virtual void performConsistencyTest() override; virtual bool calcNormal( double x, double y, Vector3D* result ) override; virtual bool calcPoint( double x, double y, Point3D* result ) override; @@ -56,7 +56,7 @@ class ANALYSIS_EXPORT TriDecorator : public Triangulation virtual bool swapEdge( double x, double y ) override; virtual QList* getPointsAroundEdge( double x, double y ) override; protected: - /** Association with a Triangulation object*/ + //! Association with a Triangulation object Triangulation* mTIN; }; diff --git a/src/analysis/interpolation/TriangleInterpolator.h b/src/analysis/interpolation/TriangleInterpolator.h index 4a638e99e292..4155ca29a002 100644 --- a/src/analysis/interpolation/TriangleInterpolator.h +++ b/src/analysis/interpolation/TriangleInterpolator.h @@ -26,9 +26,9 @@ class ANALYSIS_EXPORT TriangleInterpolator { public: virtual ~TriangleInterpolator() {} - /** Calculates the normal vector and assigns it to vec*/ + //! Calculates the normal vector and assigns it to vec virtual bool calcNormVec( double x, double y, Vector3D* result ) = 0; - /** Performs a linear interpolation in a triangle and assigns the x-,y- and z-coordinates to point*/ + //! Performs a linear interpolation in a triangle and assigns the x-,y- and z-coordinates to point virtual bool calcPoint( double x, double y, Point3D* result ) = 0; }; diff --git a/src/analysis/interpolation/Triangulation.h b/src/analysis/interpolation/Triangulation.h index b11191efd8aa..d6edfb19a68d 100644 --- a/src/analysis/interpolation/Triangulation.h +++ b/src/analysis/interpolation/Triangulation.h @@ -31,8 +31,8 @@ class ANALYSIS_EXPORT Triangulation //! Enumeration describing the behaviour, if two forced lines cross. enum forcedCrossBehaviour { - SnappingType_VERTICE, //!< the second inserted forced line is snapped to the closest vertice of the first inserted forced line. - DELETE_FIRST, //!< the status of the first inserted forced line is reset to that of a normal edge (so that the second inserted forced line remain and the first not) + SnappingType_VERTICE, //!< The second inserted forced line is snapped to the closest vertice of the first inserted forced line. + DELETE_FIRST, //!< The status of the first inserted forced line is reset to that of a normal edge (so that the second inserted forced line remain and the first not) INSERT_VERTICE }; virtual ~Triangulation(); @@ -55,7 +55,7 @@ class ANALYSIS_EXPORT Triangulation */ virtual bool calcNormal( double x, double y, Vector3D* result ) = 0; - /** Performs a consistency check, remove this later*/ + //! Performs a consistency check, remove this later virtual void performConsistencyTest() = 0; /** @@ -64,7 +64,7 @@ class ANALYSIS_EXPORT Triangulation */ virtual bool calcPoint( double x, double y, Point3D* result ) = 0; - /** Returns a pointer to the point with number i. Any virtual points must have the number -1*/ + //! Returns a pointer to the point with number i. Any virtual points must have the number -1 virtual Point3D* getPoint( unsigned int i ) const = 0; /** Finds out in which triangle the point with coordinates x and y is and @@ -72,25 +72,25 @@ class ANALYSIS_EXPORT Triangulation */ virtual bool getTriangle( double x, double y, Point3D* p1, int* n1, Point3D* p2, int* n2, Point3D* p3, int* n3 ) = 0; - /** Finds out, in which triangle the point with coordinates x and y is and assigns the points at the vertices to 'p1', 'p2' and 'p3*/ + //! Finds out, in which triangle the point with coordinates x and y is and assigns the points at the vertices to 'p1', 'p2' and 'p3 virtual bool getTriangle( double x, double y, Point3D* p1, Point3D* p2, Point3D* p3 ) = 0; - /** Returns the number of the point opposite to the triangle points p1, p2 (which have to be on a halfedge)*/ + //! Returns the number of the point opposite to the triangle points p1, p2 (which have to be on a halfedge) virtual int getOppositePoint( int p1, int p2 ) = 0; - /** Returns the largest x-coordinate value of the bounding box*/ + //! Returns the largest x-coordinate value of the bounding box virtual double getXMax() const = 0; - /** Returns the smallest x-coordinate value of the bounding box*/ + //! Returns the smallest x-coordinate value of the bounding box virtual double getXMin() const = 0; - /** Returns the largest y-coordinate value of the bounding box*/ + //! Returns the largest y-coordinate value of the bounding box virtual double getYMax() const = 0; - /** Returns the smallest x-coordinate value of the bounding box*/ + //! Returns the smallest x-coordinate value of the bounding box virtual double getYMin() const = 0; - /** Returns the number of points*/ + //! Returns the number of points virtual int getNumberOfPoints() const = 0; /** @@ -109,40 +109,40 @@ class ANALYSIS_EXPORT Triangulation */ virtual QList* getPointsAroundEdge( double x, double y ) = 0; - /** Draws the points, edges and the forced lines*/ + //! Draws the points, edges and the forced lines //virtual void draw(QPainter* p, double xlowleft, double ylowleft, double xupright, double yupright, double width, double height) const=0; - /** Sets the behaviour of the triangulation in case of crossing forced lines*/ + //! Sets the behaviour of the triangulation in case of crossing forced lines virtual void setForcedCrossBehaviour( Triangulation::forcedCrossBehaviour b ) = 0; - /** Sets the color of the normal edges*/ + //! Sets the color of the normal edges virtual void setEdgeColor( int r, int g, int b ) = 0; - /** Sets the color of the forced edges*/ + //! Sets the color of the forced edges virtual void setForcedEdgeColor( int r, int g, int b ) = 0; - /** Sets the color of the breaklines*/ + //! Sets the color of the breaklines virtual void setBreakEdgeColor( int r, int g, int b ) = 0; - /** Sets an interpolator object*/ + //! Sets an interpolator object virtual void setTriangleInterpolator( TriangleInterpolator* interpolator ) = 0; - /** Eliminates the horizontal triangles by swapping*/ + //! Eliminates the horizontal triangles by swapping virtual void eliminateHorizontalTriangles() = 0; - /** Adds points to make the triangles better shaped (algorithm of ruppert)*/ + //! Adds points to make the triangles better shaped (algorithm of ruppert) virtual void ruppertRefinement() = 0; - /** Returns true, if the point with coordinates x and y is inside the convex hull and false otherwise*/ + //! Returns true, if the point with coordinates x and y is inside the convex hull and false otherwise virtual bool pointInside( double x, double y ) = 0; - /** Reads the content of a taff-file*/ + //! Reads the content of a taff-file //virtual bool readFromTAFF(QString fileName)=0; - /** Saves the content to a taff file*/ + //! Saves the content to a taff file //virtual bool saveToTAFF(QString fileName) const=0; - /** Swaps the edge which is closest to the point with x and y coordinates (if this is possible)*/ + //! Swaps the edge which is closest to the point with x and y coordinates (if this is possible) virtual bool swapEdge( double x, double y ) = 0; /** diff --git a/src/analysis/interpolation/Vector3D.h b/src/analysis/interpolation/Vector3D.h index 7f3d32b83967..f4ae84416142 100644 --- a/src/analysis/interpolation/Vector3D.h +++ b/src/analysis/interpolation/Vector3D.h @@ -28,40 +28,40 @@ class ANALYSIS_EXPORT Vector3D { protected: - /** X-component of the vector*/ + //! X-component of the vector double mX; - /** Y-component of the vector*/ + //! Y-component of the vector double mY; - /** Z-component of the vector*/ + //! Z-component of the vector double mZ; public: - /** Constructor taking the three components as arguments*/ + //! Constructor taking the three components as arguments Vector3D( double x, double y, double z ); - /** Default constructor*/ + //! Default constructor Vector3D(); - /** Copy constructor*/ + //! Copy constructor Vector3D( const Vector3D& v ); - /** Destructor*/ + //! Destructor ~Vector3D(); Vector3D& operator=( const Vector3D& v ); bool operator==( const Vector3D& v ) const; bool operator!=( const Vector3D& v ) const; - /** Returns the x-component of the vector*/ + //! Returns the x-component of the vector double getX() const; - /** Returns the y-component of the vector*/ + //! Returns the y-component of the vector double getY() const; - /** Returns the z-component of the vector*/ + //! Returns the z-component of the vector double getZ() const; - /** Returns the length of the vector*/ + //! Returns the length of the vector double getLength() const; - /** Sets the x-component of the vector*/ + //! Sets the x-component of the vector void setX( double x ); - /** Sets the y-component of the vector*/ + //! Sets the y-component of the vector void setY( double y ); - /** Sets the z-component of the vector*/ + //! Sets the z-component of the vector void setZ( double z ); - /** Standardises the vector*/ + //! Standardises the vector void standardise(); }; diff --git a/src/analysis/interpolation/qgsinterpolator.h b/src/analysis/interpolation/qgsinterpolator.h index 336295d0bc61..4d3d9ab912a9 100644 --- a/src/analysis/interpolation/qgsinterpolator.h +++ b/src/analysis/interpolation/qgsinterpolator.h @@ -37,7 +37,7 @@ can be an attribute or the z-coordinates in case of 25D types*/ class ANALYSIS_EXPORT QgsInterpolator { public: - /** Describes the type of input data*/ + //! Describes the type of input data enum InputType { POINTS, @@ -45,7 +45,7 @@ class ANALYSIS_EXPORT QgsInterpolator BREAK_LINES }; - /** A layer together with the information about interpolation attribute / z-coordinate interpolation and the type (point, structure line, breakline)*/ + //! A layer together with the information about interpolation attribute / z-coordinate interpolation and the type (point, structure line, breakline) struct LayerData { QgsVectorLayer* vectorLayer; @@ -76,7 +76,7 @@ class ANALYSIS_EXPORT QgsInterpolator QVector mCachedBaseData; - /** Flag that tells if the cache already has been filled*/ + //! Flag that tells if the cache already has been filled bool mDataIsCached; //Information about the input vector layers and the attributes (or z-values) that are used for interpolation diff --git a/src/analysis/interpolation/qgstininterpolator.h b/src/analysis/interpolation/qgstininterpolator.h index be19e73aa34a..0ba1a13dd9c7 100644 --- a/src/analysis/interpolation/qgstininterpolator.h +++ b/src/analysis/interpolation/qgstininterpolator.h @@ -54,14 +54,14 @@ class ANALYSIS_EXPORT QgsTINInterpolator: public QgsInterpolator TriangleInterpolator* mTriangleInterpolator; bool mIsInitialized; bool mShowProgressDialog; - /** If true: export triangulation to shapefile after initialization*/ + //! If true: export triangulation to shapefile after initialization bool mExportTriangulationToFile; - /** File path to export the triangulation*/ + //! File path to export the triangulation QString mTriangulationFilePath; - /** Type of interpolation*/ + //! Type of interpolation TIN_INTERPOLATION mInterpolation; - /** Create dual edge triangulation*/ + //! Create dual edge triangulation void initialize(); /** Inserts the vertices of a feature into the triangulation @param f the feature diff --git a/src/analysis/openstreetmap/qgsosmdownload.h b/src/analysis/openstreetmap/qgsosmdownload.h index d45984f030c6..4b9dea23c2b9 100644 --- a/src/analysis/openstreetmap/qgsosmdownload.h +++ b/src/analysis/openstreetmap/qgsosmdownload.h @@ -82,8 +82,8 @@ class ANALYSIS_EXPORT QgsOSMDownload : public QObject bool isFinished() const; signals: - void finished(); //!< emitted when the network reply has finished (with success or with an error) - void downloadProgress( qint64, qint64 ); //!< normally the total length is not known (until we reach end) + void finished(); //!< Emitted when the network reply has finished (with success or with an error) + void downloadProgress( qint64, qint64 ); //!< Normally the total length is not known (until we reach end) private slots: void onReadyRead(); diff --git a/src/analysis/raster/qgsderivativefilter.h b/src/analysis/raster/qgsderivativefilter.h index ad3e15d2839a..796b089fb9a3 100644 --- a/src/analysis/raster/qgsderivativefilter.h +++ b/src/analysis/raster/qgsderivativefilter.h @@ -33,9 +33,9 @@ class ANALYSIS_EXPORT QgsDerivativeFilter : public QgsNineCellFilter float* x13, float* x23, float* x33 ) override = 0; protected: - /** Calculates the first order derivative in x-direction according to Horn (1981)*/ + //! Calculates the first order derivative in x-direction according to Horn (1981) float calcFirstDerX( float* x11, float* x21, float* x31, float* x12, float* x22, float* x32, float* x13, float* x23, float* x33 ); - /** Calculates the first order derivative in y-direction according to Horn (1981)*/ + //! Calculates the first order derivative in y-direction according to Horn (1981) float calcFirstDerY( float* x11, float* x21, float* x31, float* x12, float* x22, float* x32, float* x13, float* x23, float* x33 ); }; diff --git a/src/analysis/raster/qgsninecellfilter.h b/src/analysis/raster/qgsninecellfilter.h index 75639d73662b..3719bbdd45b8 100644 --- a/src/analysis/raster/qgsninecellfilter.h +++ b/src/analysis/raster/qgsninecellfilter.h @@ -31,7 +31,7 @@ the method that calculates the new value from the nine values. Everything else ( class ANALYSIS_EXPORT QgsNineCellFilter { public: - /** Constructor that takes input file, output file and output format (GDAL string)*/ + //! Constructor that takes input file, output file and output format (GDAL string) QgsNineCellFilter( const QString& inputFile, const QString& outputFile, const QString& outputFormat ); virtual ~QgsNineCellFilter(); /** Starts the calculation, reads from mInputFile and stores the result in mOutputFile @@ -62,7 +62,7 @@ class ANALYSIS_EXPORT QgsNineCellFilter //default constructor forbidden. We need input file, output file and format obligatory QgsNineCellFilter(); - /** Opens the input file and returns the dataset handle and the number of pixels in x-/y- direction*/ + //! Opens the input file and returns the dataset handle and the number of pixels in x-/y- direction GDALDatasetH openInputFile( int& nCellsX, int& nCellsY ); /** Opens the output driver and tests if it supports the creation of a new dataset @return nullptr on error and the driver handle on success*/ @@ -79,11 +79,11 @@ class ANALYSIS_EXPORT QgsNineCellFilter double mCellSizeX; double mCellSizeY; - /** The nodata value of the input layer*/ + //! The nodata value of the input layer float mInputNodataValue; - /** The nodata value of the output layer*/ + //! The nodata value of the output layer float mOutputNodataValue; - /** Scale factor for z-value if x-/y- units are different to z-units (111120 for degree->meters and 370400 for degree->feet)*/ + //! Scale factor for z-value if x-/y- units are different to z-units (111120 for degree->meters and 370400 for degree->feet) double mZFactor; }; diff --git a/src/analysis/raster/qgsrastercalculator.h b/src/analysis/raster/qgsrastercalculator.h index 9e3dfd7fbe4a..3b9b23294135 100644 --- a/src/analysis/raster/qgsrastercalculator.h +++ b/src/analysis/raster/qgsrastercalculator.h @@ -44,12 +44,12 @@ class ANALYSIS_EXPORT QgsRasterCalculator //! Result of the calculation enum Result { - Success = 0, /*!< Calculation sucessful */ - CreateOutputError = 1, /*!< Error creating output data file */ - InputLayerError = 2, /*!< Error reading input layer */ - Cancelled = 3, /*!< User cancelled calculation */ - ParserError = 4, /*!< Error parsing formula */ - MemoryError = 5, /*!< Error allocating memory for result */ + Success = 0, //!< Calculation sucessful + CreateOutputError = 1, //!< Error creating output data file + InputLayerError = 2, //!< Error reading input layer + Cancelled = 3, //!< User cancelled calculation + ParserError = 4, //!< Error parsing formula + MemoryError = 5, //!< Error allocating memory for result }; /** QgsRasterCalculator constructor. @@ -104,13 +104,13 @@ class ANALYSIS_EXPORT QgsRasterCalculator QString mOutputFile; QString mOutputFormat; - /** Output raster extent*/ + //! Output raster extent QgsRectangle mOutputRectangle; QgsCoordinateReferenceSystem mOutputCrs; - /** Number of output columns*/ + //! Number of output columns int mNumOutputColumns; - /** Number of output rows*/ + //! Number of output rows int mNumOutputRows; /***/ diff --git a/src/analysis/raster/qgsrastermatrix.h b/src/analysis/raster/qgsrastermatrix.h index 267c686fa547..81282553e02e 100644 --- a/src/analysis/raster/qgsrastermatrix.h +++ b/src/analysis/raster/qgsrastermatrix.h @@ -56,21 +56,21 @@ class ANALYSIS_EXPORT QgsRasterMatrix opLOG10, }; - /** Takes ownership of data array*/ + //! Takes ownership of data array QgsRasterMatrix(); //! @note note available in python bindings QgsRasterMatrix( int nCols, int nRows, double* data, double nodataValue ); QgsRasterMatrix( const QgsRasterMatrix& m ); ~QgsRasterMatrix(); - /** Returns true if matrix is 1x1 (=scalar number)*/ + //! Returns true if matrix is 1x1 (=scalar number) bool isNumber() const { return ( mColumns == 1 && mRows == 1 ); } double number() const { return mData[0]; } - /** Returns data array (but not ownership)*/ + //! Returns data array (but not ownership) //! @note not available in python bindings double* data() { return mData; } - /** Returns data and ownership. Sets data and nrows, ncols of this matrix to 0*/ + //! Returns data and ownership. Sets data and nrows, ncols of this matrix to 0 //! @note not available in python bindings double* takeData(); @@ -83,9 +83,9 @@ class ANALYSIS_EXPORT QgsRasterMatrix void setNodataValue( double d ) { mNodataValue = d; } QgsRasterMatrix& operator=( const QgsRasterMatrix& m ); - /** Adds another matrix to this one*/ + //! Adds another matrix to this one bool add( const QgsRasterMatrix& other ); - /** Subtracts another matrix from this one*/ + //! Subtracts another matrix from this one bool subtract( const QgsRasterMatrix& other ); bool multiply( const QgsRasterMatrix& other ); bool divide( const QgsRasterMatrix& other ); @@ -116,7 +116,7 @@ class ANALYSIS_EXPORT QgsRasterMatrix double* mData; double mNodataValue; - /** +,-,*,/,^,<,>,<=,>=,=,!=, and, or*/ + //! +,-,*,/,^,<,>,<=,>=,=,!=, and, or bool twoArgumentOperation( TwoArgOperator op, const QgsRasterMatrix& other ); double calculateTwoArgumentOp( TwoArgOperator op, double arg1, double arg2 ) const; diff --git a/src/analysis/raster/qgsrelief.h b/src/analysis/raster/qgsrelief.h index 6fe4dd3c6fc0..d6bf989c281f 100644 --- a/src/analysis/raster/qgsrelief.h +++ b/src/analysis/raster/qgsrelief.h @@ -62,7 +62,7 @@ class ANALYSIS_EXPORT QgsRelief @return true in case of success*/ QList< ReliefColor > calculateOptimizedReliefClasses(); - /** Write frequency of elevation values to file for manual inspection*/ + //! Write frequency of elevation values to file for manual inspection bool exportFrequencyDistributionToCsv( const QString& file ); private: @@ -73,9 +73,9 @@ class ANALYSIS_EXPORT QgsRelief double mCellSizeX; double mCellSizeY; - /** The nodata value of the input layer*/ + //! The nodata value of the input layer float mInputNodataValue; - /** The nodata value of the output layer*/ + //! The nodata value of the output layer float mOutputNodataValue; double mZFactor; @@ -92,7 +92,7 @@ class ANALYSIS_EXPORT QgsRelief bool processNineCellWindow( float* x1, float* x2, float* x3, float* x4, float* x5, float* x6, float* x7, float* x8, float* x9, unsigned char* red, unsigned char* green, unsigned char* blue ); - /** Opens the input file and returns the dataset handle and the number of pixels in x-/y- direction*/ + //! Opens the input file and returns the dataset handle and the number of pixels in x-/y- direction GDALDatasetH openInputFile( int& nCellsX, int& nCellsY ); /** Opens the output driver and tests if it supports the creation of a new dataset @return nullptr on error and the driver handle on success*/ @@ -101,15 +101,15 @@ class ANALYSIS_EXPORT QgsRelief @return the output dataset or nullptr in case of error*/ GDALDatasetH openOutputFile( GDALDatasetH inputDataset, GDALDriverH outputDriver ); - /** Set elevation color*/ + //! Set elevation color bool setElevationColor( double elevation, int* red, int* green, int* blue ); - /** Sets relief colors*/ + //! Sets relief colors void setDefaultReliefColors(); /** Returns class (0-255) for an elevation value @return elevation class or -1 in case of error*/ int frequencyClassForElevation( double elevation, double minElevation, double elevationClassRange ); - /** Do one iteration of class break optimisation (algorithm from Garcia and Rodriguez)*/ + //! Do one iteration of class break optimisation (algorithm from Garcia and Rodriguez) void optimiseClassBreaks( QList& breaks, double* frequencies ); /** Calculates coefficients a and b @param input data points ( elevation class / frequency ) diff --git a/src/analysis/vector/qgsgeometryanalyzer.h b/src/analysis/vector/qgsgeometryanalyzer.h index c7456fda84ec..037f2156b539 100644 --- a/src/analysis/vector/qgsgeometryanalyzer.h +++ b/src/analysis/vector/qgsgeometryanalyzer.h @@ -118,7 +118,7 @@ class ANALYSIS_EXPORT QgsGeometryAnalyzer const QString& outputFormat, int locationField1, int locationField2 = -1, int offsetField = -1, double offsetScale = 1.0, bool forceSingleGeometry = false, QgsVectorDataProvider* memoryProvider = nullptr, QProgressDialog* p = nullptr ); - /** Returns linear reference geometry as a multiline (or 0 if no match). Currently, the z-coordinates are considered to be the measures (no support for m-values in QGIS)*/ + //! Returns linear reference geometry as a multiline (or 0 if no match). Currently, the z-coordinates are considered to be the measures (no support for m-values in QGIS) QgsGeometry locateBetweenMeasures( double fromMeasure, double toMeasure, const QgsGeometry& lineGeom ); /** Returns linear reference geometry. Unlike the PostGIS function, this method always returns multipoint or 0 if no match (not geometry collection). * Currently, the z-coordinates are considered to be the measures (no support for m-values in QGIS) @@ -129,16 +129,16 @@ class ANALYSIS_EXPORT QgsGeometryAnalyzer QList simpleMeasure( QgsGeometry& geometry ); double perimeterMeasure( const QgsGeometry& geometry, QgsDistanceArea& measure ); - /** Helper function to simplify an individual feature*/ + //! Helper function to simplify an individual feature void simplifyFeature( QgsFeature& f, QgsVectorFileWriter* vfw, double tolerance ); - /** Helper function to get the cetroid of an individual feature*/ + //! Helper function to get the cetroid of an individual feature void centroidFeature( QgsFeature& f, QgsVectorFileWriter* vfw ); - /** Helper function to buffer an individual feature*/ + //! Helper function to buffer an individual feature void bufferFeature( QgsFeature& f, int nProcessedFeatures, QgsVectorFileWriter* vfw, bool dissolve, QgsGeometry& dissolveGeometry, double bufferDistance, int bufferDistanceField ); - /** Helper function to get the convex hull of feature(s)*/ + //! Helper function to get the convex hull of feature(s) void convexFeature( QgsFeature& f, int nProcessedFeatures, QgsGeometry& dissolveGeometry ); - /** Helper function to dissolve feature(s)*/ + //! Helper function to dissolve feature(s) QgsGeometry dissolveFeature( const QgsFeature& f, const QgsGeometry& dissolveInto ); //helper functions for event layer diff --git a/src/analysis/vector/qgspointsample.h b/src/analysis/vector/qgspointsample.h index e46d079b0f4c..7db3d1885715 100644 --- a/src/analysis/vector/qgspointsample.h +++ b/src/analysis/vector/qgspointsample.h @@ -42,13 +42,13 @@ class ANALYSIS_EXPORT QgsPointSample void addSamplePoints( QgsFeature& inputFeature, QgsVectorFileWriter& writer, int nPoints, double minDistance ); bool checkMinDistance( QgsPoint& pt, QgsSpatialIndex& index, double minDistance, QMap< QgsFeatureId, QgsPoint >& pointMap ); - /** Layer id of input polygon/multipolygon layer*/ + //! Layer id of input polygon/multipolygon layer QgsVectorLayer* mInputLayer; - /** Output path of result layer*/ + //! Output path of result layer QString mOutputLayer; - /** Attribute containing number of points per feature*/ + //! Attribute containing number of points per feature QString mNumberOfPointsAttribute; - /** Attribute containing minimum distance between sample points (or -1 if no min. distance constraint)*/ + //! Attribute containing minimum distance between sample points (or -1 if no min. distance constraint) QString mMinDistanceAttribute; QgsFeatureId mNCreatedPoints; //helper to find free ids }; diff --git a/src/analysis/vector/qgstransectsample.h b/src/analysis/vector/qgstransectsample.h index 8f4aaebaee33..09651ccfcc89 100644 --- a/src/analysis/vector/qgstransectsample.h +++ b/src/analysis/vector/qgstransectsample.h @@ -50,7 +50,7 @@ class ANALYSIS_EXPORT QgsTransectSample QgsGeometry findBaselineGeometry( const QVariant& strataId ); - /** Returns true if another transect is within the specified minimum distance*/ + //! Returns true if another transect is within the specified minimum distance static bool otherTransectWithinDistance( const QgsGeometry& geom, double minDistLayerUnit, double minDistance, QgsSpatialIndex& sIndex, const QMap& lineFeatureMap, QgsDistanceArea& da ); QgsVectorLayer* mStrataLayer; @@ -70,9 +70,9 @@ class ANALYSIS_EXPORT QgsTransectSample double mMinTransectLength; - /** If value is negative, the buffer distance ist set to the same value as the minimum distance*/ + //! If value is negative, the buffer distance ist set to the same value as the minimum distance double mBaselineBufferDistance; - /** If value is negative, no simplification is done to the baseline prior to create the buffer*/ + //! If value is negative, no simplification is done to the baseline prior to create the buffer double mBaselineSimplificationTolerance; /** Finds the closest points between two line segments @@ -83,7 +83,7 @@ class ANALYSIS_EXPORT QgsTransectSample @param pt2 out: closest point on secont geometry @return true in case of success*/ static bool closestSegmentPoints( const QgsGeometry& g1, const QgsGeometry& g2, double& dist, QgsPoint& pt1, QgsPoint& pt2 ); - /** Returns a copy of the multiline element closest to a point (caller takes ownership)*/ + //! Returns a copy of the multiline element closest to a point (caller takes ownership) static QgsGeometry closestMultilineElement( const QgsPoint& pt, const QgsGeometry& multiLine ); /** Returns clipped buffer line. Iteratively applies reduced tolerances if the result is not a single line @param stratumGeom stratum polygon @@ -92,7 +92,7 @@ class ANALYSIS_EXPORT QgsTransectSample @return clipped buffer line or 0 in case of error*/ QgsGeometry* clipBufferLine( const QgsGeometry& stratumGeom, QgsGeometry* clippedBaseline, double tolerance ); - /** Returns distance to buffer the baseline (takes care of units and buffer settings*/ + //! Returns distance to buffer the baseline (takes care of units and buffer settings double bufferDistance( double minDistanceFromAttribute ) const; }; diff --git a/src/analysis/vector/qgszonalstatistics.h b/src/analysis/vector/qgszonalstatistics.h index 5044708a9130..05d2d10325d8 100644 --- a/src/analysis/vector/qgszonalstatistics.h +++ b/src/analysis/vector/qgszonalstatistics.h @@ -111,25 +111,25 @@ class ANALYSIS_EXPORT QgsZonalStatistics int cellInfoForBBox( const QgsRectangle& rasterBBox, const QgsRectangle& featureBBox, double cellSizeX, double cellSizeY, int& offsetX, int& offsetY, int& nCellsX, int& nCellsY ) const; - /** Returns statistics by considering the pixels where the center point is within the polygon (fast)*/ + //! Returns statistics by considering the pixels where the center point is within the polygon (fast) void statisticsFromMiddlePointTest( void* band, const QgsGeometry& poly, int pixelOffsetX, int pixelOffsetY, int nCellsX, int nCellsY, double cellSizeX, double cellSizeY, const QgsRectangle& rasterBBox, FeatureStats& stats ); - /** Returns statistics with precise pixel - polygon intersection test (slow) */ + //! Returns statistics with precise pixel - polygon intersection test (slow) void statisticsFromPreciseIntersection( void* band, const QgsGeometry& poly, int pixelOffsetX, int pixelOffsetY, int nCellsX, int nCellsY, double cellSizeX, double cellSizeY, const QgsRectangle& rasterBBox, FeatureStats& stats ); - /** Tests whether a pixel's value should be included in the result*/ + //! Tests whether a pixel's value should be included in the result bool validPixel( float value ) const; QString getUniqueFieldName( const QString& fieldName ); QString mRasterFilePath; - /** Raster band to calculate statistics from (defaults to 1)*/ + //! Raster band to calculate statistics from (defaults to 1) int mRasterBand; QgsVectorLayer* mPolygonLayer; QString mAttributePrefix; - /** The nodata value of the input layer*/ + //! The nodata value of the input layer float mInputNodataValue; Statistics mStatistics; }; diff --git a/src/app/composer/qgsattributeselectiondialog.h b/src/app/composer/qgsattributeselectiondialog.h index 63e658082e00..767a57a6bb4c 100644 --- a/src/app/composer/qgsattributeselectiondialog.h +++ b/src/app/composer/qgsattributeselectiondialog.h @@ -36,7 +36,7 @@ class QgsComposerObject; // QgsComposerColumnAlignmentDelegate -/** A delegate for showing column alignment as a combo box*/ +//! A delegate for showing column alignment as a combo box class QgsComposerColumnAlignmentDelegate : public QItemDelegate { Q_OBJECT @@ -53,7 +53,7 @@ class QgsComposerColumnAlignmentDelegate : public QItemDelegate // QgsComposerColumnAlignmentDelegate -/** A delegate for showing column attribute source as a QgsFieldExpressionWidget*/ +//! A delegate for showing column attribute source as a QgsFieldExpressionWidget class QgsComposerColumnSourceDelegate : public QItemDelegate, private QgsExpressionContextGenerator { Q_OBJECT @@ -74,7 +74,7 @@ class QgsComposerColumnSourceDelegate : public QItemDelegate, private QgsExpress // QgsComposerColumnWidthDelegate -/** A delegate for showing column width as a spin box*/ +//! A delegate for showing column width as a spin box class QgsComposerColumnWidthDelegate : public QItemDelegate { Q_OBJECT @@ -91,7 +91,7 @@ class QgsComposerColumnWidthDelegate : public QItemDelegate // QgsComposerColumnSortOrderDelegate -/** A delegate for showing column sort order as a combo box*/ +//! A delegate for showing column sort order as a combo box class QgsComposerColumnSortOrderDelegate : public QItemDelegate { Q_OBJECT @@ -108,7 +108,7 @@ class QgsComposerColumnSortOrderDelegate : public QItemDelegate // QgsAttributeSelectionDialog -/** A dialog to select what attributes to display (in the table item), set the column properties and specify a sort order*/ +//! A dialog to select what attributes to display (in the table item), set the column properties and specify a sort order class QgsAttributeSelectionDialog: public QDialog, private Ui::QgsAttributeSelectionDialogBase { Q_OBJECT diff --git a/src/app/composer/qgscomposer.h b/src/app/composer/qgscomposer.h index 3f12a1d67203..167406ed7022 100644 --- a/src/app/composer/qgscomposer.h +++ b/src/app/composer/qgscomposer.h @@ -389,43 +389,43 @@ class QgsComposer: public QMainWindow, private Ui::QgsComposerBase //! Save window state void saveWindowState(); - /** Add a composer arrow to the item/widget map and creates a configuration widget for it*/ + //! Add a composer arrow to the item/widget map and creates a configuration widget for it void addComposerArrow( QgsComposerArrow* arrow ); - /** Add a composer polygon to the item/widget map and creates a configuration widget for it*/ + //! Add a composer polygon to the item/widget map and creates a configuration widget for it void addComposerPolygon( QgsComposerPolygon* polygon ); - /** Add a composer polyline to the item/widget map and creates a configuration widget for it*/ + //! Add a composer polyline to the item/widget map and creates a configuration widget for it void addComposerPolyline( QgsComposerPolyline* polyline ); - /** Add a composer map to the item/widget map and creates a configuration widget for it*/ + //! Add a composer map to the item/widget map and creates a configuration widget for it void addComposerMap( QgsComposerMap* map ); - /** Adds a composer label to the item/widget map and creates a configuration widget for it*/ + //! Adds a composer label to the item/widget map and creates a configuration widget for it void addComposerLabel( QgsComposerLabel* label ); - /** Adds a composer scale bar to the item/widget map and creates a configuration widget for it*/ + //! Adds a composer scale bar to the item/widget map and creates a configuration widget for it void addComposerScaleBar( QgsComposerScaleBar* scalebar ); - /** Adds a composer legend to the item/widget map and creates a configuration widget for it*/ + //! Adds a composer legend to the item/widget map and creates a configuration widget for it void addComposerLegend( QgsComposerLegend* legend ); - /** Adds a composer picture to the item/widget map and creates a configuration widget*/ + //! Adds a composer picture to the item/widget map and creates a configuration widget void addComposerPicture( QgsComposerPicture* picture ); - /** Adds a composer shape to the item/widget map and creates a configuration widget*/ + //! Adds a composer shape to the item/widget map and creates a configuration widget void addComposerShape( QgsComposerShape* shape ); - /** Adds a composer table v2 to the item/widget map and creates a configuration widget*/ + //! Adds a composer table v2 to the item/widget map and creates a configuration widget void addComposerTableV2( QgsComposerAttributeTableV2* table, QgsComposerFrame* frame ); - /** Adds composer html and creates a configuration widget*/ + //! Adds composer html and creates a configuration widget void addComposerHtmlFrame( QgsComposerHtml* html, QgsComposerFrame* frame ); - /** Removes item from the item/widget map and deletes the configuration widget. Does not delete the item itself*/ + //! Removes item from the item/widget map and deletes the configuration widget. Does not delete the item itself void deleteItem( QgsComposerItem* item ); - /** Shows the configuration widget for a composer item*/ + //! Shows the configuration widget for a composer item void showItemOptions( QgsComposerItem* i ); //XML, usually connected with QgsProject::readProject and QgsProject::writeProject @@ -463,19 +463,19 @@ class QgsComposer: public QMainWindow, private Ui::QgsComposerBase private: - /** Establishes the signal slot connections from the QgsComposerView to the composer*/ + //! Establishes the signal slot connections from the QgsComposerView to the composer void connectViewSlots(); - /** Establishes the signal slot connections from the QgsComposition to the composer*/ + //! Establishes the signal slot connections from the QgsComposition to the composer void connectCompositionSlots(); - /** Establishes other signal slot connections for the composer*/ + //! Establishes other signal slot connections for the composer void connectOtherSlots(); - /** Creates the composition widget*/ + //! Creates the composition widget void createCompositionWidget(); - /** Sets up the compositions undo/redo connections*/ + //! Sets up the compositions undo/redo connections void setupUndoView(); //! True if a composer map contains a WMS layer @@ -532,19 +532,19 @@ class QgsComposer: public QMainWindow, private Ui::QgsComposerBase QPrinter* printer(); - /** Composer title*/ + //! Composer title QString mTitle; - /** Labels in status bar which shows current mouse position*/ + //! Labels in status bar which shows current mouse position QLabel* mStatusCursorXLabel; QLabel* mStatusCursorYLabel; QLabel* mStatusCursorPageLabel; - /** Combobox in status bar which shows/adjusts current zoom level*/ + //! Combobox in status bar which shows/adjusts current zoom level QComboBox* mStatusZoomCombo; QList mStatusZoomLevelsList; - /** Label in status bar which shows messages from the composition*/ + //! Label in status bar which shows messages from the composition QLabel* mStatusCompositionLabel; - /** Label in status bar which shows atlas details*/ + //! Label in status bar which shows atlas details QLabel* mStatusAtlasLabel; //! Pointer to composer view diff --git a/src/app/composer/qgscomposerarrowwidget.h b/src/app/composer/qgscomposerarrowwidget.h index 0497de69861f..e4ae878d1df5 100644 --- a/src/app/composer/qgscomposerarrowwidget.h +++ b/src/app/composer/qgscomposerarrowwidget.h @@ -37,7 +37,7 @@ class QgsComposerArrowWidget: public QgsComposerItemBaseWidget, private Ui::QgsC QButtonGroup* mRadioButtonGroup; - /** Enables / disables the SVG line inputs*/ + //! Enables / disables the SVG line inputs void enableSvgInputElements( bool enable ); void updateLineSymbolMarker(); diff --git a/src/app/composer/qgscomposerattributetablewidget.h b/src/app/composer/qgscomposerattributetablewidget.h index e5d1431df08b..104dbbf7e663 100644 --- a/src/app/composer/qgscomposerattributetablewidget.h +++ b/src/app/composer/qgscomposerattributetablewidget.h @@ -35,7 +35,7 @@ class QgsComposerAttributeTableWidget: public QgsComposerItemBaseWidget, private QgsComposerAttributeTableV2* mComposerTable; QgsComposerFrame* mFrame; - /** Blocks / unblocks the signals of all GUI elements*/ + //! Blocks / unblocks the signals of all GUI elements void blockAllSignals( bool b ); void toggleSourceControls(); @@ -80,10 +80,10 @@ class QgsComposerAttributeTableWidget: public QgsComposerItemBaseWidget, private void on_mWrapBehaviourComboBox_currentIndexChanged( int index ); void on_mAdvancedCustomisationButton_clicked(); - /** Inserts a new maximum number of features into the spin box (without the spinbox emitting a signal)*/ + //! Inserts a new maximum number of features into the spin box (without the spinbox emitting a signal) void setMaximumNumberOfFeatures( int n ); - /** Sets the GUI elements to the values of mComposerTable*/ + //! Sets the GUI elements to the values of mComposerTable void updateGuiElements(); void atlasToggled(); diff --git a/src/app/composer/qgscomposerhtmlwidget.h b/src/app/composer/qgscomposerhtmlwidget.h index 3807e7144393..3370caa4f0d1 100644 --- a/src/app/composer/qgscomposerhtmlwidget.h +++ b/src/app/composer/qgscomposerhtmlwidget.h @@ -50,11 +50,11 @@ class QgsComposerHtmlWidget: public QgsComposerItemBaseWidget, private Ui::QgsCo void on_mEmptyFrameCheckBox_toggled( bool checked ); void on_mHideEmptyBgCheckBox_toggled( bool checked ); - /** Sets the GUI elements to the values of mHtmlItem*/ + //! Sets the GUI elements to the values of mHtmlItem void setGuiElementValues(); protected slots: - /** Initializes data defined buttons to current atlas coverage layer*/ + //! Initializes data defined buttons to current atlas coverage layer void populateDataDefinedButtons(); private: diff --git a/src/app/composer/qgscomposeritemwidget.h b/src/app/composer/qgscomposeritemwidget.h index defdec92514b..012bb252680d 100644 --- a/src/app/composer/qgscomposeritemwidget.h +++ b/src/app/composer/qgscomposeritemwidget.h @@ -56,7 +56,7 @@ class QgsComposerConfigObject: public QObject QgsComposerConfigObject( QWidget* parent, QgsComposerObject* composerObject ); ~QgsComposerConfigObject(); - /** Sets a data defined property for the item from its current data defined button settings*/ + //! Sets a data defined property for the item from its current data defined button settings void setDataDefinedProperty( const QgsDataDefinedButton *ddBtn, QgsComposerObject::DataDefinedProperty p ); /** Registers a data defined button, setting up its initial value, connections and description. @@ -68,14 +68,14 @@ class QgsComposerConfigObject: public QObject void registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, QgsDataDefinedButton::DataType type, const QString& description ); - /** Returns the current atlas coverage layer (if set)*/ + //! Returns the current atlas coverage layer (if set) QgsVectorLayer* atlasCoverageLayer() const; - /** Returns the atlas for the composition*/ + //! Returns the atlas for the composition QgsAtlasComposition *atlasComposition() const; private slots: - /** Must be called when a data defined button changes*/ + //! Must be called when a data defined button changes void updateDataDefinedProperty(); //! Updates data defined buttons to reflect current state of atlas (eg coverage layer) @@ -108,10 +108,10 @@ class QgsComposerItemBaseWidget: public QgsPanelWidget void registerDataDefinedButton( QgsDataDefinedButton* button, QgsComposerObject::DataDefinedProperty property, QgsDataDefinedButton::DataType type, const QString& description ); - /** Returns the current atlas coverage layer (if set)*/ + //! Returns the current atlas coverage layer (if set) QgsVectorLayer* atlasCoverageLayer() const; - /** Returns the atlas for the composition*/ + //! Returns the atlas for the composition QgsAtlasComposition *atlasComposition() const; private: @@ -128,12 +128,12 @@ class QgsComposerItemWidget: public QWidget, private Ui::QgsComposerItemWidgetBa QgsComposerItemWidget( QWidget* parent, QgsComposerItem* item ); ~QgsComposerItemWidget(); - /** A combination of upper/middle/lower and left/middle/right*/ + //! A combination of upper/middle/lower and left/middle/right QgsComposerItem::ItemPositionMode positionMode() const; - /** Toggles display of the background group*/ + //! Toggles display of the background group void showBackgroundGroup( bool showGroup ); - /** Toggles display of the frame group*/ + //! Toggles display of the frame group void showFrameGroup( bool showGroup ); public slots: @@ -183,7 +183,7 @@ class QgsComposerItemWidget: public QWidget, private Ui::QgsComposerItemWidgetBa void setValuesForGuiNonPositionElements(); protected slots: - /** Initializes data defined buttons to current atlas coverage layer*/ + //! Initializes data defined buttons to current atlas coverage layer void populateDataDefinedButtons(); private: diff --git a/src/app/composer/qgscomposerlegenditemdialog.h b/src/app/composer/qgscomposerlegenditemdialog.h index c0f653608f44..4e6b54e3554f 100644 --- a/src/app/composer/qgscomposerlegenditemdialog.h +++ b/src/app/composer/qgscomposerlegenditemdialog.h @@ -34,7 +34,7 @@ class QgsComposerLegendItemDialog: public QDialog, private Ui::QgsComposerLegend QgsComposerLegendItemDialog( const QStandardItem* item, QWidget* parent = nullptr ); ~QgsComposerLegendItemDialog(); - /** Returns the item text inserted by user*/ + //! Returns the item text inserted by user QString itemText() const; private: diff --git a/src/app/composer/qgscomposerlegendlayersdialog.h b/src/app/composer/qgscomposerlegendlayersdialog.h index 0a9f3e3d439c..9ead16a66f44 100644 --- a/src/app/composer/qgscomposerlegendlayersdialog.h +++ b/src/app/composer/qgscomposerlegendlayersdialog.h @@ -34,7 +34,7 @@ class QgsComposerLegendLayersDialog: public QDialog, private Ui::QgsComposerLege private: QgsComposerLegendLayersDialog(); //forbidden - /** Stores the relation between items and map layer pointers. */ + //! Stores the relation between items and map layer pointers. QMap mItemLayerMap; }; diff --git a/src/app/composer/qgscomposerlegendwidget.h b/src/app/composer/qgscomposerlegendwidget.h index 4179c0116652..b99f77af340c 100644 --- a/src/app/composer/qgscomposerlegendwidget.h +++ b/src/app/composer/qgscomposerlegendwidget.h @@ -37,7 +37,7 @@ class QgsComposerLegendWidget: public QgsComposerItemBaseWidget, private Ui::Qgs explicit QgsComposerLegendWidget( QgsComposerLegend* legend ); ~QgsComposerLegendWidget(); - /** Updates the legend layers and groups*/ + //! Updates the legend layers and groups void updateLegend(); QgsComposerLegend* legend() { return mLegend; } @@ -94,10 +94,10 @@ class QgsComposerLegendWidget: public QgsComposerItemBaseWidget, private Ui::Qgs void setCurrentNodeStyleFromAction(); private slots: - /** Sets GUI according to state of mLegend*/ + //! Sets GUI according to state of mLegend void setGuiElements(); - /** Update the enabling state of the filter by atlas button */ + //! Update the enabling state of the filter by atlas button void updateFilterLegendByAtlasButton(); void on_mItemTreeView_doubleClicked( const QModelIndex &index ); diff --git a/src/app/composer/qgscomposermanager.h b/src/app/composer/qgscomposermanager.h index a1d8d3fdb149..75e1ab5b9444 100644 --- a/src/app/composer/qgscomposermanager.h +++ b/src/app/composer/qgscomposermanager.h @@ -24,7 +24,7 @@ class QListWidgetItem; class QgsComposer; -/** Delegate for a line edit for renaming a composer. Prevents entry of duplicate composer names.*/ +//! Delegate for a line edit for renaming a composer. Prevents entry of duplicate composer names. class QgsComposerNameDelegate : public QItemDelegate { Q_OBJECT @@ -55,7 +55,7 @@ class QgsComposerManager: public QDialog, private Ui::QgsComposerManagerBase void addTemplates( const QMap& templates ); public slots: - /** Raise, unminimize and activate this window */ + //! Raise, unminimize and activate this window void activate(); private: @@ -90,24 +90,24 @@ class QgsComposerManager: public QDialog, private Ui::QgsComposerManagerBase #endif private slots: - /** Slot to update buttons state when selecting compositions */ + //! Slot to update buttons state when selecting compositions void toggleButtons(); void on_mAddButton_clicked(); - /** Slot to track combobox to use specific template path */ + //! Slot to track combobox to use specific template path void on_mTemplate_currentIndexChanged( int indx ); - /** Slot to choose path to template */ + //! Slot to choose path to template void on_mTemplatePathBtn_pressed(); - /** Slot to open default templates dir with user's system */ + //! Slot to open default templates dir with user's system void on_mTemplatesDefaultDirBtn_pressed(); - /** Slot to open user templates dir with user's system */ + //! Slot to open user templates dir with user's system void on_mTemplatesUserDirBtn_pressed(); - /** Refreshes the list of composers */ + //! Refreshes the list of composers void refreshComposers(); void remove_clicked(); void show_clicked(); - /** Duplicate composer */ + //! Duplicate composer void duplicate_clicked(); void rename_clicked(); void on_mComposerListWidget_itemChanged( QListWidgetItem * item ); diff --git a/src/app/composer/qgscomposermapgridwidget.h b/src/app/composer/qgscomposermapgridwidget.h index b4c55073160e..27b1a5ee8ae5 100644 --- a/src/app/composer/qgscomposermapgridwidget.h +++ b/src/app/composer/qgscomposermapgridwidget.h @@ -93,16 +93,16 @@ class QgsComposerMapGridWidget: public QgsComposerItemBaseWidget, private Ui::Qg protected: - /** Sets the current composer map values to the GUI elements*/ + //! Sets the current composer map values to the GUI elements virtual void updateGuiElements(); protected slots: - /** Initializes data defined buttons to current atlas coverage layer*/ + //! Initializes data defined buttons to current atlas coverage layer void populateDataDefinedButtons(); private slots: - /** Sets the GUI elements to the values of mPicture*/ + //! Sets the GUI elements to the values of mPicture void setGuiElementValues(); void updateGridLineStyleFromWidget(); @@ -114,7 +114,7 @@ class QgsComposerMapGridWidget: public QgsComposerItemBaseWidget, private Ui::Qg QgsComposerMap* mComposerMap; QgsComposerMapGrid* mComposerMapGrid; - /** Blocks / unblocks the signals of all GUI elements*/ + //! Blocks / unblocks the signals of all GUI elements void blockAllSignals( bool b ); void handleChangedFrameDisplay( QgsComposerMapGrid::BorderSide border, const QgsComposerMapGrid::DisplayMode mode ); @@ -135,10 +135,10 @@ class QgsComposerMapGridWidget: public QgsComposerItemBaseWidget, private Ui::Qg void updateGridLineSymbolMarker(); void updateGridMarkerSymbolMarker(); - /** Enables/disables grid frame related controls*/ + //! Enables/disables grid frame related controls void toggleFrameControls( bool frameEnabled, bool frameFillEnabled, bool frameSizeEnabled ); - /** Is there some predefined scales, globally or as project's options ?*/ + //! Is there some predefined scales, globally or as project's options ? bool hasPredefinedScales() const; }; diff --git a/src/app/composer/qgscomposermapwidget.h b/src/app/composer/qgscomposermapwidget.h index e89bbcc73899..4390356f5540 100644 --- a/src/app/composer/qgscomposermapwidget.h +++ b/src/app/composer/qgscomposermapwidget.h @@ -93,22 +93,22 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void addPageToToolbox( QWidget * widget, const QString& name ); - /** Sets the current composer map values to the GUI elements*/ + //! Sets the current composer map values to the GUI elements virtual void updateGuiElements(); protected slots: - /** Initializes data defined buttons to current atlas coverage layer*/ + //! Initializes data defined buttons to current atlas coverage layer void populateDataDefinedButtons(); private slots: - /** Sets the GUI elements to the values of mPicture*/ + //! Sets the GUI elements to the values of mPicture void setGuiElementValues(); - /** Enables or disables the atlas margin around feature option depending on coverage layer type*/ + //! Enables or disables the atlas margin around feature option depending on coverage layer type void atlasLayerChanged( QgsVectorLayer* layer ); - /** Enables or disables the atlas controls when composer atlas is toggled on/off*/ + //! Enables or disables the atlas controls when composer atlas is toggled on/off void compositionAtlasToggled( bool atlasEnabled ); void aboutToShowKeepLayersVisibilityPresetsMenu(); @@ -124,10 +124,10 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom private: QgsComposerMap* mComposerMap; - /** Sets extent of composer map from line edits*/ + //! Sets extent of composer map from line edits void updateComposerExtentFromGui(); - /** Blocks / unblocks the signals of all GUI elements*/ + //! Blocks / unblocks the signals of all GUI elements void blockAllSignals( bool b ); void handleChangedFrameDisplay( QgsComposerMapGrid::BorderSide border, const QgsComposerMapGrid::DisplayMode mode ); @@ -145,13 +145,13 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void initAnnotationPositionBox( QComboBox* c, QgsComposerMapGrid::AnnotationPosition pos ); void initAnnotationDirectionBox( QComboBox* c, QgsComposerMapGrid::AnnotationDirection dir ); - /** Enables or disables the atlas margin and predefined scales radio depending on the atlas coverage layer type*/ + //! Enables or disables the atlas margin and predefined scales radio depending on the atlas coverage layer type void toggleAtlasScalingOptionsByLayerType(); - /** Recalculates the bounds for an atlas map when atlas properties change*/ + //! Recalculates the bounds for an atlas map when atlas properties change void updateMapForAtlas(); - /** Is there some predefined scales, globally or as project's options ?*/ + //! Is there some predefined scales, globally or as project's options ? bool hasPredefinedScales() const; QListWidgetItem* addGridListItem( const QString& id, const QString& name ); diff --git a/src/app/composer/qgscomposerpicturewidget.h b/src/app/composer/qgscomposerpicturewidget.h index 4f6eaf4466ff..442819a5b1b1 100644 --- a/src/app/composer/qgscomposerpicturewidget.h +++ b/src/app/composer/qgscomposerpicturewidget.h @@ -34,7 +34,7 @@ class QgsComposerPictureWidget: public QgsComposerItemBaseWidget, private Ui::Qg explicit QgsComposerPictureWidget( QgsComposerPicture* picture ); ~QgsComposerPictureWidget(); - /** Add the icons of the standard directories to the preview*/ + //! Add the icons of the standard directories to the preview void addStandardDirectoriesToPreview(); public slots: @@ -53,14 +53,14 @@ class QgsComposerPictureWidget: public QgsComposerItemBaseWidget, private Ui::Qg void resizeEvent( QResizeEvent * event ) override; protected slots: - /** Initializes data defined buttons to current atlas coverage layer*/ + //! Initializes data defined buttons to current atlas coverage layer void populateDataDefinedButtons(); private slots: - /** Sets the GUI elements to the values of mPicture*/ + //! Sets the GUI elements to the values of mPicture void setGuiElementValues(); - /** Sets the picture rotation GUI control value*/ + //! Sets the picture rotation GUI control value void setPicRotationSpinValue( double r ); /** Load SVG and pixel-based image previews @@ -75,15 +75,15 @@ class QgsComposerPictureWidget: public QgsComposerItemBaseWidget, private Ui::Qg private: QgsComposerPicture* mPicture; - /** Whether the picture selection previews have been loaded */ + //! Whether the picture selection previews have been loaded bool mPreviewsLoaded; - /** Add the icons of a directory to the preview. Returns 0 in case of success*/ + //! Add the icons of a directory to the preview. Returns 0 in case of success int addDirectoryToPreview( const QString& path ); - /** Tests if a file is valid svg*/ + //! Tests if a file is valid svg bool testSvgFile( const QString& filename ) const; - /** Tests if a file is a valid pixel format*/ + //! Tests if a file is a valid pixel format bool testImageFile( const QString& filename ) const; //! Renders an svg file to a QIcon, correctly handling any SVG parameters present in the file diff --git a/src/app/composer/qgscomposerpolygonwidget.h b/src/app/composer/qgscomposerpolygonwidget.h index 96e3a362021e..83431611a3a9 100644 --- a/src/app/composer/qgscomposerpolygonwidget.h +++ b/src/app/composer/qgscomposerpolygonwidget.h @@ -41,7 +41,7 @@ class QgsComposerPolygonWidget: public QgsComposerItemBaseWidget, private Ui::Qg private slots: void on_mPolygonStyleButton_clicked(); - /** Sets the GUI elements to the currentValues of mComposerShape*/ + //! Sets the GUI elements to the currentValues of mComposerShape void setGuiElementValues(); void updateStyleFromWidget(); diff --git a/src/app/composer/qgscomposerpolylinewidget.h b/src/app/composer/qgscomposerpolylinewidget.h index b74a8b699f09..752591273469 100644 --- a/src/app/composer/qgscomposerpolylinewidget.h +++ b/src/app/composer/qgscomposerpolylinewidget.h @@ -41,7 +41,7 @@ class QgsComposerPolylineWidget: public QgsComposerItemBaseWidget, private Ui::Q private slots: void on_mLineStyleButton_clicked(); - /** Sets the GUI elements to the currentValues of mComposerShape*/ + //! Sets the GUI elements to the currentValues of mComposerShape void setGuiElementValues(); void updateStyleFromWidget(); diff --git a/src/app/composer/qgscomposerscalebarwidget.h b/src/app/composer/qgscomposerscalebarwidget.h index 7a2872da3f2c..0d1bc4945f1a 100644 --- a/src/app/composer/qgscomposerscalebarwidget.h +++ b/src/app/composer/qgscomposerscalebarwidget.h @@ -66,10 +66,10 @@ class QgsComposerScaleBarWidget: public QgsComposerItemBaseWidget, private Ui::Q QgsComposerScaleBar* mComposerScaleBar; QButtonGroup mSegmentSizeRadioGroup; - /** Enables/disables the signals of the input gui elements*/ + //! Enables/disables the signals of the input gui elements void blockMemberSignals( bool enable ); - /** Enables/disables controls based on scale bar style*/ + //! Enables/disables controls based on scale bar style void toggleStyleSpecificControls( const QString& style ); void connectUpdateSignal(); diff --git a/src/app/composer/qgscomposershapewidget.h b/src/app/composer/qgscomposershapewidget.h index 21b86ea55bac..7742d828c6b3 100644 --- a/src/app/composer/qgscomposershapewidget.h +++ b/src/app/composer/qgscomposershapewidget.h @@ -23,7 +23,7 @@ class QgsComposerShape; -/** Input widget for QgsComposerShape*/ +//! Input widget for QgsComposerShape class QgsComposerShapeWidget: public QgsComposerItemBaseWidget, private Ui::QgsComposerShapeWidgetBase { Q_OBJECT @@ -34,7 +34,7 @@ class QgsComposerShapeWidget: public QgsComposerItemBaseWidget, private Ui::QgsC private: QgsComposerShape* mComposerShape; - /** Blocks / unblocks the signal of all GUI elements*/ + //! Blocks / unblocks the signal of all GUI elements void blockAllSignals( bool block ); private slots: @@ -42,12 +42,12 @@ class QgsComposerShapeWidget: public QgsComposerItemBaseWidget, private Ui::QgsC void on_mCornerRadiusSpinBox_valueChanged( double val ); void on_mShapeStyleButton_clicked(); - /** Sets the GUI elements to the currentValues of mComposerShape*/ + //! Sets the GUI elements to the currentValues of mComposerShape void setGuiElementValues(); void updateShapeStyle(); - /** Enables or disables the rounded radius spin box based on shape type*/ + //! Enables or disables the rounded radius spin box based on shape type void toggleRadiusSpin( const QString& shapeText ); void updateSymbolFromWidget(); void cleanUpSymbolSelector( QgsPanelWidget* container ); diff --git a/src/app/composer/qgscomposertablebackgroundcolorsdialog.h b/src/app/composer/qgscomposertablebackgroundcolorsdialog.h index 54da619dbf08..575191998e52 100644 --- a/src/app/composer/qgscomposertablebackgroundcolorsdialog.h +++ b/src/app/composer/qgscomposertablebackgroundcolorsdialog.h @@ -56,7 +56,7 @@ class QgsComposerTableBackgroundColorsDialog: public QDialog, private Ui::QgsCom QMap< QgsComposerTableV2::CellStyleGroup, QgsColorButton* > mColorButtonMap; - /** Sets the GUI elements to the values of the table*/ + //! Sets the GUI elements to the values of the table void setGuiElementValues(); diff --git a/src/app/composer/qgscompositionwidget.h b/src/app/composer/qgscompositionwidget.h index 4d75ce65701d..70e9daae9e83 100644 --- a/src/app/composer/qgscompositionwidget.h +++ b/src/app/composer/qgscompositionwidget.h @@ -61,23 +61,23 @@ class QgsCompositionWidget: public QgsPanelWidget, private Ui::QgsCompositionWid void on_mOffsetYSpinBox_valueChanged( double d ); void on_mSnapToleranceSpinBox_valueChanged( int tolerance ); - /** Sets GUI elements to width/height from composition*/ + //! Sets GUI elements to width/height from composition void displayCompositionWidthHeight(); - /** Sets Print as raster checkbox value*/ + //! Sets Print as raster checkbox value void setPrintAsRasterCheckBox( bool state ); - /** Sets number of pages spin box value*/ + //! Sets number of pages spin box value void setNumberPages(); signals: - /** Is emitted when page orientation changes*/ + //! Is emitted when page orientation changes void pageOrientationChanged( const QString& orientation ); private slots: - /** Must be called when a data defined button changes*/ + //! Must be called when a data defined button changes void updateDataDefinedProperty(); - /** Initializes data defined buttons to current atlas coverage layer*/ + //! Initializes data defined buttons to current atlas coverage layer void populateDataDefinedButtons(); void variablesChanged(); @@ -94,13 +94,13 @@ class QgsCompositionWidget: public QgsPanelWidget, private Ui::QgsCompositionWid QMap mPaperMap; QgsCompositionWidget(); //default constructor is forbidden - /** Sets width/height to chosen paper format and updates paper item*/ + //! Sets width/height to chosen paper format and updates paper item void applyCurrentPaperSettings(); - /** Applies the current width and height values*/ + //! Applies the current width and height values void applyWidthHeight(); - /** Makes sure width/height values for custom paper matches the current orientation*/ + //! Makes sure width/height values for custom paper matches the current orientation void adjustOrientation(); - /** Sets GUI elements to snaping distances of composition*/ + //! Sets GUI elements to snaping distances of composition void displaySnapingSettings(); void updatePageStyle(); @@ -110,13 +110,13 @@ class QgsCompositionWidget: public QgsPanelWidget, private Ui::QgsCompositionWid double size( QDoubleSpinBox *spin ); void setSize( QDoubleSpinBox *spin, double v ); - /** Blocks / unblocks the signals of all items*/ + //! Blocks / unblocks the signals of all items void blockSignals( bool block ); - /** Sets a data defined property for the item from its current data defined button settings*/ + //! Sets a data defined property for the item from its current data defined button settings void setDataDefinedProperty( const QgsDataDefinedButton *ddBtn, QgsComposerObject::DataDefinedProperty property ); - /** Returns the data defined property corresponding to a data defined button widget*/ + //! Returns the data defined property corresponding to a data defined button widget virtual QgsComposerObject::DataDefinedProperty ddPropertyForWidget( QgsDataDefinedButton* widget ); diff --git a/src/app/legend/qgsapplegendinterface.h b/src/app/legend/qgsapplegendinterface.h index 6a2ae34ec51b..481e1c0f8c04 100644 --- a/src/app/legend/qgsapplegendinterface.h +++ b/src/app/legend/qgsapplegendinterface.h @@ -37,10 +37,10 @@ class QgsAppLegendInterface : public QgsLegendInterface public: - /** Constructor */ + //! Constructor explicit QgsAppLegendInterface( QgsLayerTreeView * layerTreeView ); - /** Destructor */ + //! Destructor ~QgsAppLegendInterface(); //! Return a string list of groups diff --git a/src/app/nodetool/qgsmaptoolnodetool.h b/src/app/nodetool/qgsmaptoolnodetool.h index 4fc3858943fe..c7c607d0628a 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.h +++ b/src/app/nodetool/qgsmaptoolnodetool.h @@ -26,7 +26,7 @@ class QgsVertexEntry; class QgsSelectedFeature; class QgsNodeEditor; -/** A maptool to move/deletes/adds vertices of line or polygon features*/ +//! A maptool to move/deletes/adds vertices of line or polygon features class QgsMapToolNodeTool: public QgsMapToolEdit { Q_OBJECT @@ -138,46 +138,46 @@ class QgsMapToolNodeTool: public QgsMapToolEdit and applies it to the map canvas*/ QgsMapCanvasSnapper mSnapper; - /** Rubber bands during node move */ + //! Rubber bands during node move QMap mMoveRubberBands; - /** Rubber band for selected feature */ + //! Rubber band for selected feature QgsGeometryRubberBand* mSelectRubberBand; - /** Vertices of features to move */ + //! Vertices of features to move QMap > > mMoveVertices; - /** Object containing selected feature and it's vertexes */ + //! Object containing selected feature and it's vertexes QgsSelectedFeature *mSelectedFeature; - /** Dock widget which allows editing vertices */ + //! Dock widget which allows editing vertices QgsNodeEditor* mNodeEditor; - /** Flag if moving of vertexes is occurring */ + //! Flag if moving of vertexes is occurring bool mMoving; - /** Flag if selection of another feature can occur */ + //! Flag if selection of another feature can occur bool mSelectAnother; - /** Feature id of another feature where user clicked */ + //! Feature id of another feature where user clicked QgsFeatureId mAnother; - /** Stored position of last press down action to count how much vertexes should be moved */ + //! Stored position of last press down action to count how much vertexes should be moved QPoint mPressCoordinates; - /** Closest vertex to click in map coordinates */ + //! Closest vertex to click in map coordinates QgsPoint mClosestMapVertex; - /** Active rubberband for selecting vertexes */ + //! Active rubberband for selecting vertexes QRubberBand *mSelectionRubberBand; - /** Rectangle defining area for selecting vertexes */ + //! Rectangle defining area for selecting vertexes QRect* mRect; - /** Flag to tell if edition points */ + //! Flag to tell if edition points bool mIsPoint; - /** Vertex to deselect on release */ + //! Vertex to deselect on release int mDeselectOnRelease; }; diff --git a/src/app/ogr/qgsnewogrconnection.cpp b/src/app/ogr/qgsnewogrconnection.cpp index a387e91015bb..dd7058c03dfb 100644 --- a/src/app/ogr/qgsnewogrconnection.cpp +++ b/src/app/ogr/qgsnewogrconnection.cpp @@ -100,7 +100,7 @@ void QgsNewOgrConnection::testConnection() } } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * void QgsNewOgrConnection::accept() { QSettings settings; @@ -140,4 +140,4 @@ void QgsNewOgrConnection::on_btnConnect_clicked() testConnection(); } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * diff --git a/src/app/ogr/qgsvectorlayersaveasdialog.h b/src/app/ogr/qgsvectorlayersaveasdialog.h index f7d71ed713e1..e809b68c7463 100644 --- a/src/app/ogr/qgsvectorlayersaveasdialog.h +++ b/src/app/ogr/qgsvectorlayersaveasdialog.h @@ -53,7 +53,7 @@ class APP_EXPORT QgsVectorLayerSaveAsDialog : public QDialog, private Ui::QgsVec QStringList layerOptions() const; long crs() const; QgsAttributeList selectedAttributes() const; - /** Return selected attributes that must be exported with their displayed values instead of their raw values. Added in QGIS 2.16 */ + //! Return selected attributes that must be exported with their displayed values instead of their raw values. Added in QGIS 2.16 QgsAttributeList attributesAsDisplayedValues() const; bool addToCanvas() const; /** Returns type of symbology export. @@ -101,7 +101,7 @@ class APP_EXPORT QgsVectorLayerSaveAsDialog : public QDialog, private Ui::QgsVec */ void setIncludeZ( bool checked ); - /** Returns creation action */ + //! Returns creation action QgsVectorFileWriter::ActionOnExistingFile creationActionOnExistingFile() const; private slots: diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 1b43237b6d99..1e5251eeb46e 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -9255,13 +9255,13 @@ void QgisApp::unregisterMapLayerPropertiesFactory( QgsMapLayerConfigWidgetFactor mMapStyleWidget->setPageFactories( mMapLayerPanelFactories ); } -/** Get a pointer to the currently selected map layer */ +//! Get a pointer to the currently selected map layer QgsMapLayer *QgisApp::activeLayer() { return mLayerTreeView ? mLayerTreeView->currentLayer() : nullptr; } -/** Set the current layer */ +//! Set the current layer bool QgisApp::setActiveLayer( QgsMapLayer *layer ) { if ( !layer ) diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index 26b15e59b467..bd2a46c24ad3 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -183,10 +183,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow */ QString crsAndFormatAdjustedLayerUri( const QString& uri, const QStringList& supportedCrs, const QStringList& supportedFormats ) const; - /** Add a 'pre-made' map layer to the project */ + //! Add a 'pre-made' map layer to the project void addMapLayer( QgsMapLayer *theMapLayer ); - /** Set the extents of the map canvas */ + //! Set the extents of the map canvas void setExtent( const QgsRectangle& theRect ); //! Remove all layers from the map and legend - reimplements same method from qgisappbase void removeAllLayers(); @@ -217,16 +217,16 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //!Overloaded version of the private function with same name that takes the imagename as a parameter void saveMapAsImage( const QString&, QPixmap * ); - /** Get the mapcanvas object from the app */ + //! Get the mapcanvas object from the app QgsMapCanvas *mapCanvas(); - /** Return the messageBar object which allows displaying unobtrusive messages to the user.*/ + //! Return the messageBar object which allows displaying unobtrusive messages to the user. QgsMessageBar *messageBar(); - /** Open the message log dock widget **/ + //! Open the message log dock widget * void openMessageLog(); - /** Adds a widget to the user input tool bar.*/ + //! Adds a widget to the user input tool bar. void addUserInputWidget( QWidget* widget ); //! Set theme (icons) @@ -278,7 +278,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow * windows which are hidden rather than deleted when closed. */ void removeWindow( QAction *action ); - /** Returns the print composers*/ + //! Returns the print composers QSet printComposers() const {return mPrintComposers;} /** Get a unique title from user for new and duplicate composers * @param acceptEmpty whether to accept empty titles (one will be generated) @@ -286,15 +286,15 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow * @return QString::null if user cancels input dialog */ bool uniqueComposerTitle( QWidget *parent, QString& composerTitle, bool acceptEmpty, const QString& currentTitle = QString() ); - /** Creates a new composer and returns a pointer to it*/ + //! Creates a new composer and returns a pointer to it QgsComposer* createNewComposer( QString title = QString() ); - /** Deletes a composer and removes entry from Set*/ + //! Deletes a composer and removes entry from Set void deleteComposer( QgsComposer *c ); /** Duplicates a composer and adds it to Set */ QgsComposer *duplicateComposer( QgsComposer *currentComposer, QString title = QString() ); - /** Overloaded function used to sort menu entries alphabetically */ + //! Overloaded function used to sort menu entries alphabetically QMenu* createPopupMenu() override; /** @@ -388,7 +388,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QAction *actionLayerSaveAs() { return mActionLayerSaveAs; } QAction *actionRemoveLayer() { return mActionRemoveLayer; } QAction *actionDuplicateLayer() { return mActionDuplicateLayer; } - /** @note added in 2.4 */ + //! @note added in 2.4 QAction *actionSetLayerScaleVisibility() { return mActionSetLayerScaleVisibility; } QAction *actionSetLayerCrs() { return mActionSetLayerCRS; } QAction *actionSetProjectCrsFromLayer() { return mActionSetProjectCRSFromLayer; } @@ -493,7 +493,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow * @returns list of layers in legend order, or empty list */ QList editableLayers( bool modified = false ) const; - /** Get timeout for timed messages: default of 5 seconds */ + //! Get timeout for timed messages: default of 5 seconds int messageTimeout(); //! emit initializationCompleted signal @@ -504,7 +504,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QList decorationItems() { return mDecorationItems; } void addDecorationItem( QgsDecorationItem *item ) { mDecorationItems.append( item ); } - /** @note added in 2.1 */ + //! @note added in 2.1 static QString normalizedMenuName( const QString & name ) { return name.normalized( QString::NormalizationForm_KD ).remove( QRegExp( "[^a-zA-Z]" ) ); } #ifdef Q_OS_WIN @@ -513,19 +513,19 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void parseVersionInfo( QNetworkReply* reply, int& latestVersion, QStringList& versionInfo ); - /** Register a new tab in the layer properties dialog */ + //! Register a new tab in the layer properties dialog void registerMapLayerPropertiesFactory( QgsMapLayerConfigWidgetFactory* factory ); - /** Unregister a previously registered tab in the layer properties dialog */ + //! Unregister a previously registered tab in the layer properties dialog void unregisterMapLayerPropertiesFactory( QgsMapLayerConfigWidgetFactory* factory ); - /** Register a new custom drop handler. */ + //! Register a new custom drop handler. void registerCustomDropHandler( QgsCustomDropHandler* handler ); - /** Unregister a previously registered custom drop handler. */ + //! Unregister a previously registered custom drop handler. void unregisterCustomDropHandler( QgsCustomDropHandler* handler ); - /** Process the list of URIs that have been dropped in QGIS */ + //! Process the list of URIs that have been dropped in QGIS void handleDropUriList( const QgsMimeDataUtils::UriList& lst ); public slots: @@ -570,7 +570,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! starts/stops editing mode of a layer bool toggleEditing( QgsMapLayer *layer, bool allowCancel = true ); - /** Save edits for active vector layer and start new transactions */ + //! Save edits for active vector layer and start new transactions void saveActiveLayerEdits(); /** Save edits of a layer @@ -588,19 +588,19 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! Save current edits for selected layer(s) and start new transaction(s) void saveEdits(); - /** Save edits for all layers and start new transactions */ + //! Save edits for all layers and start new transactions void saveAllEdits( bool verifyAction = true ); - /** Rollback current edits for selected layer(s) and start new transaction(s) */ + //! Rollback current edits for selected layer(s) and start new transaction(s) void rollbackEdits(); - /** Rollback edits for all layers and start new transactions */ + //! Rollback edits for all layers and start new transactions void rollbackAllEdits( bool verifyAction = true ); - /** Cancel edits for selected layer(s) and toggle off editing */ + //! Cancel edits for selected layer(s) and toggle off editing void cancelEdits(); - /** Cancel all edits for all layers and toggle off editing */ + //! Cancel all edits for all layers and toggle off editing void cancelAllEdits( bool verifyAction = true ); void updateUndoActions(); @@ -644,7 +644,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void copyFeatures( QgsFeatureStore & featureStore ); void loadGDALSublayers( const QString& uri, const QStringList& list ); - /** Deletes the selected attributes for the currently selected vector layer*/ + //! Deletes the selected attributes for the currently selected vector layer void deleteSelected( QgsMapLayer *layer = nullptr, QWidget *parent = nullptr, bool promptConfirmation = false ); //! project was written @@ -679,10 +679,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! Watch for QFileOpenEvent. virtual bool event( QEvent *event ) override; - /** Open a raster layer using the Raster Data Provider. */ + //! Open a raster layer using the Raster Data Provider. QgsRasterLayer *addRasterLayer( QString const & uri, QString const & baseName, QString const & providerKey ); - /** Open a plugin layer using its provider */ + //! Open a plugin layer using its provider QgsPluginLayer* addPluginLayer( const QString& uri, const QString& baseName, const QString& providerKey ); void addWfsLayer( const QString& uri, const QString& typeName ); @@ -793,12 +793,12 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow Only workds on raster layers*/ void legendLayerStretchUsingCurrentExtent(); - /** Apply the same style to selected layers or to current legend group*/ + //! Apply the same style to selected layers or to current legend group void applyStyleToGroup(); - /** Set the CRS of the current legend group*/ + //! Set the CRS of the current legend group void legendGroupSetCrs(); - /** Set the WMS data of the current legend group*/ + //! Set the WMS data of the current legend group void legendGroupSetWmsData(); //! zoom to extent of layer @@ -813,9 +813,9 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow * (stretch based on pixels values in full dataset) * Valid for non wms raster layers only. */ void fullHistogramStretch(); - /** Perform a local cumulative cut stretch */ + //! Perform a local cumulative cut stretch void localCumulativeCutStretch(); - /** Perform a full extent cumulative cut stretch */ + //! Perform a full extent cumulative cut stretch void fullCumulativeCutStretch(); /** Increase raster brightness * Valid for non wms raster layers only. */ @@ -960,9 +960,9 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void fileNewBlank(); //! As above but allows forcing without prompt and forcing blank project void fileNew( bool thePromptToSaveFlag, bool forceBlank = false ); - /** What type of project to open after launch */ + //! What type of project to open after launch void fileOpenAfterLaunch(); - /** After project read, set any auto-opened project as successful */ + //! After project read, set any auto-opened project as successful void fileOpenedOKAfterLaunch(); //! Create a new file from a template project bool fileNewFromTemplate( const QString& fileName ); @@ -1112,10 +1112,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! stop "busy" progress bar void canvasRefreshFinished(); - /** Dialog for verification of action on many edits */ + //! Dialog for verification of action on many edits bool verifyEditsActionDialog( const QString& act, const QString& upon ); - /** Update gui actions/menus when layers are modified */ + //! Update gui actions/menus when layers are modified void updateLayerModifiedActions(); //! change layer subset of current vector layer @@ -1130,10 +1130,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! change log message icon in statusbar void toggleLogMessageIcon( bool hasLogMessage ); - /** Called when some layer's editing mode was toggled on/off */ + //! Called when some layer's editing mode was toggled on/off void layerEditStateChanged(); - /** Update the label toolbar buttons */ + //! Update the label toolbar buttons void updateLabelToolButtons(); /** Activates or deactivates actions depending on the current maplayer type. @@ -1203,13 +1203,13 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void modifyAnnotation(); void reprojectAnnotations(); - /** Alerts user when labeling font for layer has not been found on system */ + //! Alerts user when labeling font for layer has not been found on system void labelingFontNotFound( QgsVectorLayer *vlayer, const QString& fontfamily ); - /** Alerts user when commit errors occurred */ + //! Alerts user when commit errors occurred void commitError( QgsVectorLayer *vlayer ); - /** Opens the labeling dialog for a layer when called from labelingFontNotFound alert */ + //! Opens the labeling dialog for a layer when called from labelingFontNotFound alert void labelingDialogFontNotFound( QAction *act ); //! shows label settings dialog (for labeling-ng) @@ -1266,10 +1266,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void writeAnnotationItemsToProject( QDomDocument& doc ); - /** Creates the composer instances in a project file and adds them to the menu*/ + //! Creates the composer instances in a project file and adds them to the menu bool loadComposersFromProject( const QDomDocument& doc ); - /** Slot to handle display of composers menu, e.g. sorting */ + //! Slot to handle display of composers menu, e.g. sorting void on_mPrintComposersMenu_aboutToShow(); bool loadAnnotationItemsFromProject( const QDomDocument& doc ); @@ -1333,10 +1333,10 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow */ void showStatisticsDockWidget(); - /** Pushes a layer error to the message bar */ + //! Pushes a layer error to the message bar void onLayerError( const QString& msg ); - /** Set the layer for the map style dock. Doesn't show the style dock */ + //! Set the layer for the map style dock. Doesn't show the style dock void setMapStyleDockLayer( QgsMapLayer *layer ); //! Handles processing of dropped mimedata @@ -1380,7 +1380,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow @note added in version 2.3*/ void composerRemoved( QgsComposerView* v ); - /** This signal is emitted when QGIS' initialization is complete */ + //! This signal is emitted when QGIS' initialization is complete void initializationCompleted(); void customCrsValidation( QgsCoordinateReferenceSystem &crs ); @@ -1415,7 +1415,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow */ bool addRasterLayer( QgsRasterLayer * theRasterLayer ); - /** Open a raster layer - this is the generic function which takes all parameters */ + //! Open a raster layer - this is the generic function which takes all parameters QgsRasterLayer* addRasterLayerPrivate( const QString & uri, const QString & baseName, const QString & providerKey, bool guiWarning, bool guiUpdate ); @@ -1439,7 +1439,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow @return empty geometry in case of error or if canceled */ QgsGeometry unionGeometries( const QgsVectorLayer* vl, QgsFeatureList& featureList, bool &canceled ); - /** Deletes all the composer objects and clears mPrintComposers*/ + //! Deletes all the composer objects and clears mPrintComposers void deletePrintComposers(); void saveAsVectorFileGeneral( QgsVectorLayer* vlayer = nullptr, bool symbologyOption = true ); @@ -1450,9 +1450,9 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow */ QgsVectorLayer * pasteToNewMemoryVector(); - /** Returns all annotation items in the canvas*/ + //! Returns all annotation items in the canvas QList annotationItems(); - /** Removes annotation items in the canvas*/ + //! Removes annotation items in the canvas void removeAnnotationItems(); //! Configure layer tree view according to the user options from QSettings @@ -1478,13 +1478,13 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void updateCrsStatusBar(); void createDecorations(); - /** Do histogram stretch for singleband gray / multiband color rasters*/ + //! Do histogram stretch for singleband gray / multiband color rasters void histogramStretch( bool visibleAreaOnly = false, QgsRaster::ContrastEnhancementLimits theLimits = QgsRaster::ContrastEnhancementMinMax ); - /** Apply raster brightness */ + //! Apply raster brightness void adjustBrightnessContrast( int delta, bool updateBrightness = true ); - /** Copy a vector style from a layer to another one, if they have the same geometry type */ + //! Copy a vector style from a layer to another one, if they have the same geometry type void duplicateVectorStyle( QgsVectorLayer* srcLayer, QgsVectorLayer* destLayer ); QgisAppStyleSheet *mStyleSheetBuilder; @@ -1695,7 +1695,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QList mRecentProjects; //! Print composers of this project, accessible by id string QSet mPrintComposers; - /** QGIS-internal vector feature clipboard */ + //! QGIS-internal vector feature clipboard QgsClipboard *mInternalClipboard; //! Flag to indicate how the project properties dialog was summoned bool mShowProjectionTab; diff --git a/src/app/qgisappinterface.h b/src/app/qgisappinterface.h index 62e773bda078..14a790a903b6 100644 --- a/src/app/qgisappinterface.h +++ b/src/app/qgisappinterface.h @@ -165,7 +165,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface #endif void openURL( const QString& url, bool useQgisDocDirectory = true ) override; - /** Return a pointer to the map canvas used by qgisapp */ + //! Return a pointer to the map canvas used by qgisapp QgsMapCanvas * mapCanvas() override; /** @@ -184,10 +184,10 @@ class APP_EXPORT QgisAppInterface : public QgisInterface QgsMessageBar * messageBar() override; - /** Open the message log dock widget **/ + //! Open the message log dock widget * void openMessageLog() override; - /** Adds a widget to the user input tool bar.*/ + //! Adds a widget to the user input tool bar. void addUserInputWidget( QWidget* widget ) override; // ### QGIS 3: return QgsComposer*, not QgsComposerView* @@ -210,56 +210,56 @@ class APP_EXPORT QgisAppInterface : public QgisInterface */ QgsComposerView* duplicateComposer( QgsComposerView* composerView, const QString& title = QString() ) override; - /** Deletes parent composer of composer view, after closing composer window */ + //! Deletes parent composer of composer view, after closing composer window void deleteComposer( QgsComposerView* composerView ) override; - /** Return changeable options built from settings and/or defaults */ + //! Return changeable options built from settings and/or defaults QMap defaultStyleSheetOptions() override; /** Generate stylesheet * @param opts generated default option values, or a changed copy of them */ void buildStyleSheet( const QMap& opts ) override; - /** Save changed default option keys/values to user settings */ + //! Save changed default option keys/values to user settings void saveStyleSheetOptions( const QMap& opts ) override; - /** Get reference font for initial qApp (may not be same as QgisApp) */ + //! Get reference font for initial qApp (may not be same as QgisApp) QFont defaultStyleSheetFont() override; - /** Add action to the plugins menu */ + //! Add action to the plugins menu void addPluginToMenu( const QString& name, QAction* action ) override; - /** Remove action from the plugins menu */ + //! Remove action from the plugins menu void removePluginMenu( const QString& name, QAction* action ) override; - /** Add action to the Database menu */ + //! Add action to the Database menu void addPluginToDatabaseMenu( const QString& name, QAction* action ) override; - /** Remove action from the Database menu */ + //! Remove action from the Database menu void removePluginDatabaseMenu( const QString& name, QAction* action ) override; - /** Add action to the Raster menu */ + //! Add action to the Raster menu void addPluginToRasterMenu( const QString& name, QAction* action ) override; - /** Remove action from the Raster menu */ + //! Remove action from the Raster menu void removePluginRasterMenu( const QString& name, QAction* action ) override; - /** Add action to the Vector menu */ + //! Add action to the Vector menu void addPluginToVectorMenu( const QString& name, QAction* action ) override; - /** Remove action from the Raster menu */ + //! Remove action from the Raster menu void removePluginVectorMenu( const QString& name, QAction* action ) override; - /** Add action to the Web menu */ + //! Add action to the Web menu void addPluginToWebMenu( const QString& name, QAction* action ) override; - /** Remove action from the Web menu */ + //! Remove action from the Web menu void removePluginWebMenu( const QString& name, QAction* action ) override; - /** Add "add layer" action to the layer menu */ + //! Add "add layer" action to the layer menu void insertAddLayerAction( QAction *action ) override; - /** Remove "add layer" action from the layer menu */ + //! Remove "add layer" action from the layer menu void removeAddLayerAction( QAction *action ) override; - /** Add a dock widget to the main window */ + //! Add a dock widget to the main window void addDockWidget( Qt::DockWidgetArea area, QDockWidget * dockwidget ) override; - /** Remove specified dock widget from main window (doesn't delete it). */ + //! Remove specified dock widget from main window (doesn't delete it). void removeDockWidget( QDockWidget * dockwidget ) override; //! return CAD dock widget @@ -282,10 +282,10 @@ class APP_EXPORT QgisAppInterface : public QgisInterface * windows which are hidden rather than deleted when closed. */ virtual void removeWindow( QAction *action ) override; - /** Register action to the shortcuts manager so its shortcut can be changed in GUI. */ + //! Register action to the shortcuts manager so its shortcut can be changed in GUI. virtual bool registerMainWindowAction( QAction* action, const QString& defaultShortcut ) override; - /** Unregister a previously registered action. (e.g. when plugin is going to be unloaded. */ + //! Unregister a previously registered action. (e.g. when plugin is going to be unloaded. virtual bool unregisterMainWindowAction( QAction* action ) override; /** Register a new tab in the vector layer properties dialog. @@ -408,9 +408,9 @@ class APP_EXPORT QgisAppInterface : public QgisInterface virtual QAction *actionAddRasterLayer() override; virtual QAction *actionAddPgLayer() override; virtual QAction *actionAddWmsLayer() override; - /** Get access to the native Add ArcGIS FeatureServer action. */ + //! Get access to the native Add ArcGIS FeatureServer action. virtual QAction *actionAddAfsLayer() override; - /** Get access to the native Add ArcGIS MapServer action. */ + //! Get access to the native Add ArcGIS MapServer action. virtual QAction *actionAddAmsLayer() override; virtual QAction *actionCopyLayerStyle() override; virtual QAction *actionPasteLayerStyle() override; @@ -500,7 +500,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface */ virtual QList editableLayers( bool modified = false ) const override; - /** Get timeout for timed messages: default of 5 seconds */ + //! Get timeout for timed messages: default of 5 seconds virtual int messageTimeout() override; signals: diff --git a/src/app/qgisappstylesheet.h b/src/app/qgisappstylesheet.h index 67f2418b23c1..fc41601c1597 100644 --- a/src/app/qgisappstylesheet.h +++ b/src/app/qgisappstylesheet.h @@ -33,7 +33,7 @@ class APP_EXPORT QgisAppStyleSheet: public QObject QgisAppStyleSheet( QObject * parent = nullptr ); ~QgisAppStyleSheet(); - /** Return changeable options built from settings and/or defaults */ + //! Return changeable options built from settings and/or defaults QMap defaultOptions(); /** Generate stylesheet @@ -42,10 +42,10 @@ class APP_EXPORT QgisAppStyleSheet: public QObject */ void buildStyleSheet( const QMap& opts ); - /** Save changed default option keys/values to user settings */ + //! Save changed default option keys/values to user settings void saveToSettings( const QMap& opts ); - /** Get reference font for initial qApp */ + //! Get reference font for initial qApp QFont defaultFont() { return mDefaultFont; } signals: @@ -55,7 +55,7 @@ class APP_EXPORT QgisAppStyleSheet: public QObject void appStyleSheetChanged( const QString& appStyleSheet ); private: - /** Set active configuration values */ + //! Set active configuration values void setActiveValues(); // qt styles diff --git a/src/app/qgsalignrasterdialog.cpp b/src/app/qgsalignrasterdialog.cpp index 14fb627beaa6..33f82bfb3294 100644 --- a/src/app/qgsalignrasterdialog.cpp +++ b/src/app/qgsalignrasterdialog.cpp @@ -55,7 +55,7 @@ static QString _rasterLayerName( const QString& filename ) -/** Helper class to report progress */ +//! Helper class to report progress struct QgsAlignRasterDialogProgress : public QgsAlignRaster::ProgressHandler { explicit QgsAlignRasterDialogProgress( QProgressBar* pb ) : mPb( pb ) {} diff --git a/src/app/qgsalignrasterdialog.h b/src/app/qgsalignrasterdialog.h index aefa9440cbd2..e6cfe9fde30d 100644 --- a/src/app/qgsalignrasterdialog.h +++ b/src/app/qgsalignrasterdialog.h @@ -21,7 +21,7 @@ class QgsAlignRaster; -/** Dialog providing user interface for QgsAlignRaster */ +//! Dialog providing user interface for QgsAlignRaster class QgsAlignRasterDialog : public QDialog, private Ui::QgsAlignRasterDialog { Q_OBJECT @@ -62,7 +62,7 @@ class QgsAlignRasterDialog : public QDialog, private Ui::QgsAlignRasterDialog class QgsMapLayerComboBox; class QCheckBox; -/** Simple dialog to display details of one layer's configuration */ +//! Simple dialog to display details of one layer's configuration class QgsAlignRasterLayerConfigDialog : public QDialog { Q_OBJECT diff --git a/src/app/qgsbrowserdockwidget.h b/src/app/qgsbrowserdockwidget.h index b2294d3dd8ff..1117410d2cc6 100644 --- a/src/app/qgsbrowserdockwidget.h +++ b/src/app/qgsbrowserdockwidget.h @@ -50,7 +50,7 @@ class QgsBrowserPropertiesWidget : public QWidget explicit QgsBrowserPropertiesWidget( QWidget* parent = nullptr ); static QgsBrowserPropertiesWidget* createWidget( QgsDataItem* item, QWidget* parent = nullptr ); virtual void setItem( QgsDataItem* item ) { Q_UNUSED( item ) } - /** Set content widget, usually item paramWidget. Takes ownership. */ + //! Set content widget, usually item paramWidget. Takes ownership. virtual void setWidget( QWidget* widget ); /** Sets whether the properties widget should display in condensed mode, ie, for display in a dock diff --git a/src/app/qgsclipboard.h b/src/app/qgsclipboard.h index acd8cbc49251..16b56fac6a70 100644 --- a/src/app/qgsclipboard.h +++ b/src/app/qgsclipboard.h @@ -57,9 +57,9 @@ class APP_EXPORT QgsClipboard : public QObject //! Available formats for copying features as text enum CopyFormat { - AttributesOnly, /*!< Tab delimited text, attributes only */ - AttributesWithWKT, /*!< Tab delimited text, with geometry in WKT format */ - GeoJSON, /*!< GeoJSON FeatureCollection format */ + AttributesOnly, //!< Tab delimited text, attributes only + AttributesWithWKT, //!< Tab delimited text, with geometry in WKT format + GeoJSON, //!< GeoJSON FeatureCollection format }; /** @@ -145,7 +145,7 @@ class APP_EXPORT QgsClipboard : public QObject void systemClipboardChanged(); signals: - /** Emitted when content changed */ + //! Emitted when content changed void changed(); private: @@ -181,7 +181,7 @@ class APP_EXPORT QgsClipboard : public QObject QgsFields mFeatureFields; QgsCoordinateReferenceSystem mCRS; - /** True when the data from the system clipboard should be read */ + //! True when the data from the system clipboard should be read bool mUseSystemClipboard; friend class TestQgisAppClipboard; diff --git a/src/app/qgsdecorationgrid.h b/src/app/qgsdecorationgrid.h index 3d6ccd3ce8b3..89eda78e2d92 100644 --- a/src/app/qgsdecorationgrid.h +++ b/src/app/qgsdecorationgrid.h @@ -59,81 +59,81 @@ class APP_EXPORT QgsDecorationGrid: public QgsDecorationItem BoundaryDirection }; - /** Sets coordinate grid style. */ + //! Sets coordinate grid style. void setGridStyle( GridStyle style ) {mGridStyle = style;} GridStyle gridStyle() const { return mGridStyle; } - /** Sets coordinate interval in x-direction for composergrid. */ + //! Sets coordinate interval in x-direction for composergrid. void setGridIntervalX( double interval ) { mGridIntervalX = interval;} double gridIntervalX() const { return mGridIntervalX; } - /** Sets coordinate interval in y-direction for composergrid. */ + //! Sets coordinate interval in y-direction for composergrid. void setGridIntervalY( double interval ) { mGridIntervalY = interval;} double gridIntervalY() const { return mGridIntervalY; } - /** Sets x-coordinate offset for composer grid */ + //! Sets x-coordinate offset for composer grid void setGridOffsetX( double offset ) { mGridOffsetX = offset; } double gridOffsetX() const { return mGridOffsetX; } - /** Sets y-coordinate offset for composer grid */ + //! Sets y-coordinate offset for composer grid void setGridOffsetY( double offset ) { mGridOffsetY = offset; } double gridOffsetY() const { return mGridOffsetY; } - /** Sets the pen to draw composer grid */ + //! Sets the pen to draw composer grid void setGridPen( const QPen& p ) { mGridPen = p; } QPen gridPen() const { return mGridPen; } - /** Sets with of grid pen */ + //! Sets with of grid pen void setGridPenWidth( double w ) { mGridPen.setWidthF( w ); } - /** Sets the color of the grid pen */ + //! Sets the color of the grid pen void setGridPenColor( const QColor& c ) { mGridPen.setColor( c ); } - /** Sets font for grid annotations */ + //! Sets font for grid annotations void setGridAnnotationFont( const QFont& f ) { mGridAnnotationFont = f; } QFont gridAnnotationFont() const { return mGridAnnotationFont; } - /** Sets coordinate precision for grid annotations */ + //! Sets coordinate precision for grid annotations void setGridAnnotationPrecision( int p ) {mGridAnnotationPrecision = p;} int gridAnnotationPrecision() const {return mGridAnnotationPrecision;} - /** Sets flag if grid annotation should be shown */ + //! Sets flag if grid annotation should be shown void setShowGridAnnotation( bool show ) {mShowGridAnnotation = show;} bool showGridAnnotation() const {return mShowGridAnnotation;} - /** Sets position of grid annotations. Possibilities are inside or outside of the map frame */ + //! Sets position of grid annotations. Possibilities are inside or outside of the map frame void setGridAnnotationPosition( GridAnnotationPosition p ) {mGridAnnotationPosition = p;} GridAnnotationPosition gridAnnotationPosition() const {return mGridAnnotationPosition;} - /** Sets distance between map frame and annotations */ + //! Sets distance between map frame and annotations void setAnnotationFrameDistance( double d ) {mAnnotationFrameDistance = d;} double annotationFrameDistance() const {return mAnnotationFrameDistance;} - /** Sets grid annotation direction. Can be horizontal, vertical, direction of axis and horizontal and vertical */ + //! Sets grid annotation direction. Can be horizontal, vertical, direction of axis and horizontal and vertical void setGridAnnotationDirection( GridAnnotationDirection d ) {mGridAnnotationDirection = d;} GridAnnotationDirection gridAnnotationDirection() const {return mGridAnnotationDirection;} - /** Sets length of the cros segments (if grid style is cross) */ + //! Sets length of the cros segments (if grid style is cross) /* void setCrossLength( double l ) {mCrossLength = l;} */ /* double crossLength() {return mCrossLength;} */ - /** Set symbol that is used to draw grid lines. Takes ownership*/ + //! Set symbol that is used to draw grid lines. Takes ownership void setLineSymbol( QgsLineSymbol* symbol ); const QgsLineSymbol* lineSymbol() const { return mLineSymbol; } - /** Set symbol that is used to draw markers. Takes ownership*/ + //! Set symbol that is used to draw markers. Takes ownership void setMarkerSymbol( QgsMarkerSymbol* symbol ); const QgsMarkerSymbol* markerSymbol() const { return mMarkerSymbol; } - /** Sets map unit type */ + //! Sets map unit type void setMapUnits( QgsUnitTypes::DistanceUnit t ) { mMapUnits = t; } QgsUnitTypes::DistanceUnit mapUnits() { return mMapUnits; } - /** Set mapUnits value */ + //! Set mapUnits value void setDirty( bool dirty = true ); bool isDirty(); - /** Computes interval that is approx. 1/5 of canvas extent */ + //! Computes interval that is approx. 1/5 of canvas extent bool getIntervalFromExtent( double* values, bool useXAxis = true ); - /** Computes interval from current raster layer */ + //! Computes interval from current raster layer bool getIntervalFromCurrentLayer( double* values ); double getDefaultInterval( bool useXAxis = true ); @@ -154,7 +154,7 @@ class APP_EXPORT QgsDecorationGrid: public QgsDecorationItem private: - /** Enum for different frame borders*/ + //! Enum for different frame borders enum Border { Left, @@ -163,31 +163,31 @@ class APP_EXPORT QgsDecorationGrid: public QgsDecorationItem Top }; - /** Line or Symbol */ + //! Line or Symbol GridStyle mGridStyle; - /** Grid line interval in x-direction (map units)*/ + //! Grid line interval in x-direction (map units) double mGridIntervalX; - /** Grid line interval in y-direction (map units)*/ + //! Grid line interval in y-direction (map units) double mGridIntervalY; - /** Grid line offset in x-direction*/ + //! Grid line offset in x-direction double mGridOffsetX; - /** Grid line offset in y-direction*/ + //! Grid line offset in y-direction double mGridOffsetY; - /** Grid line pen*/ + //! Grid line pen QPen mGridPen; - /** Font for grid line annotation*/ + //! Font for grid line annotation QFont mGridAnnotationFont; - /** Digits after the dot*/ + //! Digits after the dot int mGridAnnotationPrecision; - /** True if coordinate values should be drawn*/ + //! True if coordinate values should be drawn bool mShowGridAnnotation; - /** Annotation position inside or outside of map frame*/ + //! Annotation position inside or outside of map frame GridAnnotationPosition mGridAnnotationPosition; - /** Distance between map frame and annotation*/ + //! Distance between map frame and annotation double mAnnotationFrameDistance; - /** Annotation can be horizontal / vertical or different for axes*/ + //! Annotation can be horizontal / vertical or different for axes GridAnnotationDirection mGridAnnotationDirection; - /** The length of the cross sides for mGridStyle Cross*/ + //! The length of the cross sides for mGridStyle Cross /* double mCrossLength; */ QgsLineSymbol* mLineSymbol; @@ -213,23 +213,23 @@ class APP_EXPORT QgsDecorationGrid: public QgsDecorationItem /** Returns the grid lines for the y-coordinates. Not vertical in case of rotation @return 0 in case of success*/ int yGridLines( QList< QPair< qreal, QLineF > >& lines ) const; - /** Returns the item border of a point (in item coordinates)*/ + //! Returns the item border of a point (in item coordinates) Border borderForLineCoord( QPointF point, QPainter* p ) const; /** Draws Text. Takes care about all the composer specific issues (calculation to pixel, scaling of font and painter to work around the Qt font bug)*/ void drawText( QPainter* p, double x, double y, const QString& text, const QFont& font ) const; - /** Like the above, but with a rectangle for multiline text*/ + //! Like the above, but with a rectangle for multiline text void drawText( QPainter* p, const QRectF& rect, const QString& text, const QFont& font, Qt::AlignmentFlag halignment = Qt::AlignLeft, Qt::AlignmentFlag valignment = Qt::AlignTop ) const; - /** Returns the font width in millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE*/ + //! Returns the font width in millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE double textWidthMillimeters( const QFont& font, const QString& text ) const; - /** Returns the font height of a character in millimeters. */ + //! Returns the font height of a character in millimeters. double fontHeightCharacterMM( const QFont& font, QChar c ) const; - /** Returns the font ascent in Millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE*/ + //! Returns the font ascent in Millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE double fontAscentMillimeters( const QFont& font ) const; - /** Calculates font to from point size to pixel size*/ + //! Calculates font to from point size to pixel size double pixelFontSize( double pointSize ) const; - /** Returns a font where size is in pixel and font size is upscaled with FONT_WORKAROUND_SCALE*/ + //! Returns a font where size is in pixel and font size is upscaled with FONT_WORKAROUND_SCALE QFont scaledFontPixelSize( const QFont& font ) const; /* friend class QgsDecorationGridDialog; */ diff --git a/src/app/qgsdecorationitem.h b/src/app/qgsdecorationitem.h index 93d0dfd8d984..9e6ea80473d9 100644 --- a/src/app/qgsdecorationitem.h +++ b/src/app/qgsdecorationitem.h @@ -79,7 +79,7 @@ class APP_EXPORT QgsDecorationItem: public QObject protected: - /** True if decoration item has to be displayed*/ + //! True if decoration item has to be displayed bool mEnabled; //! Placement of the decoration diff --git a/src/app/qgsdelattrdialog.h b/src/app/qgsdelattrdialog.h index 999338e21b16..b6ddf6ecfa89 100644 --- a/src/app/qgsdelattrdialog.h +++ b/src/app/qgsdelattrdialog.h @@ -30,7 +30,7 @@ class APP_EXPORT QgsDelAttrDialog: public QDialog, private Ui::QgsDelAttrDialogB public: QgsDelAttrDialog( const QgsVectorLayer* vl ); ~QgsDelAttrDialog(); - /** Returns the selected attribute indices*/ + //! Returns the selected attribute indices QList selectedAttributes(); }; diff --git a/src/app/qgsdiagramproperties.h b/src/app/qgsdiagramproperties.h index f5c83ae5de9f..5bc297e0674e 100644 --- a/src/app/qgsdiagramproperties.h +++ b/src/app/qgsdiagramproperties.h @@ -34,7 +34,7 @@ class APP_EXPORT QgsDiagramProperties : public QWidget, private Ui::QgsDiagramPr ~QgsDiagramProperties(); - /** Adds an attribute from the list of available attributes to the assigned attributes with a random color.*/ + //! Adds an attribute from the list of available attributes to the assigned attributes with a random color. void addAttribute( QTreeWidgetItem * item ); public slots: diff --git a/src/app/qgsdisplayangle.h b/src/app/qgsdisplayangle.h index 2cf8d6cd8b75..71c2b0682b66 100644 --- a/src/app/qgsdisplayangle.h +++ b/src/app/qgsdisplayangle.h @@ -20,7 +20,7 @@ class QgsMapToolMeasureAngle; -/** A class that displays results of angle measurements with the proper unit*/ +//! A class that displays results of angle measurements with the proper unit class APP_EXPORT QgsDisplayAngle: public QDialog, private Ui::QgsDisplayAngleBase { Q_OBJECT diff --git a/src/app/qgsdxfexportdialog.h b/src/app/qgsdxfexportdialog.h index f54f933b9c33..1cb012725ed5 100644 --- a/src/app/qgsdxfexportdialog.h +++ b/src/app/qgsdxfexportdialog.h @@ -91,7 +91,7 @@ class QgsDxfExportDialog : public QDialog, private Ui::QgsDxfExportDialogBase QgsCoordinateReferenceSystem crs() const; public slots: - /** Change the selection of layers in the list */ + //! Change the selection of layers in the list void selectAll(); void unSelectAll(); diff --git a/src/app/qgsfieldcalculator.h b/src/app/qgsfieldcalculator.h index b8b4f27923c6..54936d9d6f3c 100644 --- a/src/app/qgsfieldcalculator.h +++ b/src/app/qgsfieldcalculator.h @@ -22,7 +22,7 @@ class QgsVectorLayer; -/** A dialog class that provides calculation of new fields using existing fields, values and a set of operators*/ +//! A dialog class that provides calculation of new fields using existing fields, values and a set of operators class APP_EXPORT QgsFieldCalculator: public QDialog, private Ui::QgsFieldCalculatorBase { Q_OBJECT @@ -44,23 +44,23 @@ class APP_EXPORT QgsFieldCalculator: public QDialog, private Ui::QgsFieldCalcula void on_mButtonBox_helpRequested() { QgsContextHelp::run( metaObject()->className() ); } private slots: - /** Sets the ok button enabled / disabled*/ + //! Sets the ok button enabled / disabled void setOkButtonState(); void setPrecisionMinMax(); private: //! default constructor forbidden QgsFieldCalculator(); - /** Inserts existing fields into the combo box*/ + //! Inserts existing fields into the combo box void populateFields(); - /** Inserts the types supported by the provider into the combo box*/ + //! Inserts the types supported by the provider into the combo box void populateOutputFieldTypes(); QgsVectorLayer* mVectorLayer; - /** Key: field name, Value: field index*/ + //! Key: field name, Value: field index QMap mFieldMap; - /** Create a field based on the definitions */ + //! Create a field based on the definitions inline QgsField fieldDefinition() { return QgsField( mOutputFieldNameLineEdit->text(), @@ -73,7 +73,7 @@ class APP_EXPORT QgsFieldCalculator: public QDialog, private Ui::QgsFieldCalcula ); } - /** Idx of changed attribute*/ + //! Idx of changed attribute int mAttributeId; friend class TestQgsFieldCalculator; diff --git a/src/app/qgsfieldsproperties.h b/src/app/qgsfieldsproperties.h index 71b04d3bb3c7..e0bfc4f0f8cc 100644 --- a/src/app/qgsfieldsproperties.h +++ b/src/app/qgsfieldsproperties.h @@ -196,7 +196,7 @@ class APP_EXPORT QgsFieldsProperties : public QWidget, private Ui_QgsFieldsPrope void updateExpression(); - /** Editing of layer was toggled */ + //! Editing of layer was toggled void editingToggled(); protected: diff --git a/src/app/qgshandlebadlayers.h b/src/app/qgshandlebadlayers.h index 9822688084f4..c2aeaed5643a 100644 --- a/src/app/qgshandlebadlayers.h +++ b/src/app/qgshandlebadlayers.h @@ -30,7 +30,7 @@ class APP_EXPORT QgsHandleBadLayersHandler public: QgsHandleBadLayersHandler(); - /** Implementation of the handler */ + //! Implementation of the handler virtual void handleBadLayers( const QList& layers ) override; }; diff --git a/src/app/qgsidentifyresultsdialog.h b/src/app/qgsidentifyresultsdialog.h index 52c5d718adf3..b1c88090bd10 100644 --- a/src/app/qgsidentifyresultsdialog.h +++ b/src/app/qgsidentifyresultsdialog.h @@ -84,7 +84,7 @@ class APP_EXPORT QgsIdentifyResultsWebViewItem: public QObject, public QTreeWidg QgsIdentifyResultsWebViewItem( QTreeWidget *treeWidget = nullptr ); QgsIdentifyResultsWebView *webView() { return mWebView; } void setHtml( const QString &html ); - /** @note added in 2.1 */ + //! @note added in 2.1 void setContent( const QByteArray & data, const QString & mimeType = QString(), const QUrl & baseUrl = QUrl() ); public slots: @@ -122,12 +122,12 @@ class APP_EXPORT QgsIdentifyResultsDialog: public QDialog, private Ui::QgsIdenti ~QgsIdentifyResultsDialog(); - /** Add add feature from vector layer */ + //! Add add feature from vector layer void addFeature( QgsVectorLayer * layer, const QgsFeature &f, const QMap< QString, QString > &derivedAttributes ); - /** Add add feature from other layer */ + //! Add add feature from other layer void addFeature( QgsRasterLayer * layer, const QString& label, const QMap< QString, QString > &attributes, @@ -136,13 +136,13 @@ class APP_EXPORT QgsIdentifyResultsDialog: public QDialog, private Ui::QgsIdenti const QgsFeature &feature = QgsFeature(), const QMap ¶ms = ( QMap() ) ); - /** Add feature from identify results */ + //! Add feature from identify results void addFeature( const QgsMapToolIdentify::IdentifyResult& result ); - /** Map tool was deactivated */ + //! Map tool was deactivated void deactivate(); - /** Map tool was activated */ + //! Map tool was activated void activate(); signals: @@ -156,7 +156,7 @@ class APP_EXPORT QgsIdentifyResultsDialog: public QDialog, private Ui::QgsIdenti void activateLayer( QgsMapLayer * ); public slots: - /** Remove results */ + //! Remove results void clear(); void updateViewModes(); diff --git a/src/app/qgsjoindialog.h b/src/app/qgsjoindialog.h index bf33894e05db..b80e3636c5ba 100644 --- a/src/app/qgsjoindialog.h +++ b/src/app/qgsjoindialog.h @@ -30,13 +30,13 @@ class APP_EXPORT QgsJoinDialog: public QDialog, private Ui::QgsJoinDialogBase QgsJoinDialog( QgsVectorLayer* layer, QList alreadyJoinedLayers, QWidget * parent = nullptr, Qt::WindowFlags f = 0 ); ~QgsJoinDialog(); - /** Configure the dialog for an existing join */ + //! Configure the dialog for an existing join void setJoinInfo( const QgsVectorJoinInfo& joinInfo ); - /** Returns the join info */ + //! Returns the join info QgsVectorJoinInfo joinInfo() const; - /** Returns true if user wants to create an attribute index on the join field*/ + //! Returns true if user wants to create an attribute index on the join field bool createAttributeIndex() const; private slots: @@ -45,7 +45,7 @@ class APP_EXPORT QgsJoinDialog: public QDialog, private Ui::QgsJoinDialogBase void checkDefinitionValid(); private: - /** Target layer*/ + //! Target layer QgsVectorLayer* mLayer; }; diff --git a/src/app/qgslabelinggui.h b/src/app/qgslabelinggui.h index 789c15062900..a4671b1ed212 100644 --- a/src/app/qgslabelinggui.h +++ b/src/app/qgslabelinggui.h @@ -52,7 +52,7 @@ class APP_EXPORT QgsLabelingGui : public QgsTextFormatWidget, private QgsExpress void blockInitSignals( bool block ); void syncDefinedCheckboxFrame( QgsDataDefinedButton* ddBtn, QCheckBox* chkBx, QFrame* f ); void populateDataDefinedButtons( QgsPalLayerSettings& s ); - /** Sets data defined property attribute to map */ + //! Sets data defined property attribute to map void setDataDefinedProperty( const QgsDataDefinedButton* ddBtn, QgsPalLayerSettings::DataDefinedProperties p, QgsPalLayerSettings& lyr ); private: diff --git a/src/app/qgslabelpropertydialog.h b/src/app/qgslabelpropertydialog.h index 5d202aec8b0a..2aa3279021c2 100644 --- a/src/app/qgslabelpropertydialog.h +++ b/src/app/qgslabelpropertydialog.h @@ -24,7 +24,7 @@ #include -/** A dialog to enter data defined label attributes*/ +//! A dialog to enter data defined label attributes class APP_EXPORT QgsLabelPropertyDialog: public QDialog, private Ui::QgsLabelPropertyDialogBase { Q_OBJECT @@ -32,7 +32,7 @@ class APP_EXPORT QgsLabelPropertyDialog: public QDialog, private Ui::QgsLabelPro QgsLabelPropertyDialog( const QString& layerId, const QString& providerId, int featureId, const QFont& labelFont, const QString& labelText, QWidget * parent = nullptr, Qt::WindowFlags f = 0 ); ~QgsLabelPropertyDialog(); - /** Returns properties changed by the user*/ + //! Returns properties changed by the user const QgsAttributeMap& changedProperties() const { return mChangedProperties; } signals: @@ -67,25 +67,25 @@ class APP_EXPORT QgsLabelPropertyDialog: public QDialog, private Ui::QgsLabelPro void on_mLabelTextLineEdit_textChanged( const QString& text ); private: - /** Sets activation / values to the gui elements depending on the label settings and feature values*/ + //! Sets activation / values to the gui elements depending on the label settings and feature values void init( const QString& layerId, const QString& providerId, int featureId, const QString& labelText ); void disableGuiElements(); - /** Block / unblock all input element signals*/ + //! Block / unblock all input element signals void blockElementSignals( bool block ); void setDataDefinedValues( const QgsPalLayerSettings &layerSettings, QgsVectorLayer* vlayer ); void enableDataDefinedWidgets( QgsVectorLayer* vlayer ); - /** Updates font when family or style is updated */ + //! Updates font when family or style is updated void updateFont( const QFont& font, bool block = true ); - /** Updates combobox with named styles of font */ + //! Updates combobox with named styles of font void populateFontStyleComboBox(); void fillHaliComboBox(); void fillValiComboBox(); - /** Insert changed value into mChangedProperties*/ + //! Insert changed value into mChangedProperties void insertChangedValue( QgsPalLayerSettings::DataDefinedProperties p, const QVariant& value ); QgsAttributeMap mChangedProperties; @@ -94,10 +94,10 @@ class APP_EXPORT QgsLabelPropertyDialog: public QDialog, private Ui::QgsLabelPro QFontDatabase mFontDB; - /** Label field for the current layer (or -1 if none)*/ + //! Label field for the current layer (or -1 if none) int mCurLabelField; - /** Current feature */ + //! Current feature QgsFeature mCurLabelFeat; }; diff --git a/src/app/qgslayerstylingwidget.h b/src/app/qgslayerstylingwidget.h index 1ab3332d77d6..b16d2deee28c 100644 --- a/src/app/qgslayerstylingwidget.h +++ b/src/app/qgslayerstylingwidget.h @@ -61,7 +61,7 @@ class APP_EXPORT QgsMapLayerStyleCommand : public QUndoCommand virtual void undo() override; virtual void redo() override; - /** Try to merge with other commands of this type when they are created in small time interval */ + //! Try to merge with other commands of this type when they are created in small time interval virtual bool mergeWith( const QUndoCommand* other ) override; private: diff --git a/src/app/qgsmaplayerstyleguiutils.h b/src/app/qgsmaplayerstyleguiutils.h index e9e8a8a683d4..67bd119632d9 100644 --- a/src/app/qgsmaplayerstyleguiutils.h +++ b/src/app/qgsmaplayerstyleguiutils.h @@ -23,7 +23,7 @@ class QgsMapLayer; class QAction; class QMenu; -/** Various GUI utility functions for dealing with map layer's style manager */ +//! Various GUI utility functions for dealing with map layer's style manager class QgsMapLayerStyleGuiUtils : public QObject { Q_OBJECT diff --git a/src/app/qgsmaptooladdcircularstring.h b/src/app/qgsmaptooladdcircularstring.h index d21b94176143..a9274b2af69e 100644 --- a/src/app/qgsmaptooladdcircularstring.h +++ b/src/app/qgsmaptooladdcircularstring.h @@ -44,7 +44,7 @@ class QgsMapToolAddCircularString: public QgsMapToolCapture * Completed circular strings will be added to this tool by calling its addCurve() method. * */ QgsMapToolCapture* mParentTool; - /** Circular string points (in map coordinates)*/ + //! Circular string points (in map coordinates) QgsPointSequence mPoints; //! The rubberband to show the already completed circular strings QgsGeometryRubberBand* mRubberBand; diff --git a/src/app/qgsmaptooladdfeature.h b/src/app/qgsmaptooladdfeature.h index f2cf8777d5ef..654ed4095e10 100644 --- a/src/app/qgsmaptooladdfeature.h +++ b/src/app/qgsmaptooladdfeature.h @@ -15,12 +15,12 @@ #include "qgsmaptoolcapture.h" -/** This tool adds new point/line/polygon features to already existing vector layers*/ +//! This tool adds new point/line/polygon features to already existing vector layers class APP_EXPORT QgsMapToolAddFeature : public QgsMapToolCapture { Q_OBJECT public: - /** @note mode parameter added in QGIS 2.12 */ + //! @note mode parameter added in QGIS 2.12 QgsMapToolAddFeature( QgsMapCanvas* canvas, CaptureMode mode = CaptureNone ); virtual ~QgsMapToolAddFeature(); void cadCanvasReleaseEvent( QgsMapMouseEvent * e ) override; diff --git a/src/app/qgsmaptooladdpart.h b/src/app/qgsmaptooladdpart.h index 84ee29461bef..c9af2e1923aa 100644 --- a/src/app/qgsmaptooladdpart.h +++ b/src/app/qgsmaptooladdpart.h @@ -15,7 +15,7 @@ #include "qgsmaptoolcapture.h" -/** A map tool that adds new parts to multipart features*/ +//! A map tool that adds new parts to multipart features class APP_EXPORT QgsMapToolAddPart : public QgsMapToolCapture { Q_OBJECT @@ -28,6 +28,6 @@ class APP_EXPORT QgsMapToolAddPart : public QgsMapToolCapture void activate() override; private: - /** Check if there is any feature selected */ + //! Check if there is any feature selected bool checkSelection(); }; diff --git a/src/app/qgsmaptooladdring.h b/src/app/qgsmaptooladdring.h index 35b595ebe593..8a21c8a3e605 100644 --- a/src/app/qgsmaptooladdring.h +++ b/src/app/qgsmaptooladdring.h @@ -15,7 +15,7 @@ #include "qgsmaptoolcapture.h" -/** A tool to cut holes into polygons and multipolygon features*/ +//! A tool to cut holes into polygons and multipolygon features class APP_EXPORT QgsMapToolAddRing: public QgsMapToolCapture { Q_OBJECT diff --git a/src/app/qgsmaptoolannotation.h b/src/app/qgsmaptoolannotation.h index 1cb9adc081d8..d94632e86764 100644 --- a/src/app/qgsmaptoolannotation.h +++ b/src/app/qgsmaptoolannotation.h @@ -36,18 +36,18 @@ class APP_EXPORT QgsMapToolAnnotation: public QgsMapTool void keyPressEvent( QKeyEvent* e ) override; protected: - /** Creates a new item. To be implemented by subclasses. Returns 0 by default*/ + //! Creates a new item. To be implemented by subclasses. Returns 0 by default virtual QgsAnnotationItem* createItem( QMouseEvent* e ); - /** Creates an editor widget (caller takes ownership)*/ + //! Creates an editor widget (caller takes ownership) QDialog* createItemEditor( QgsAnnotationItem* item ); private: - /** Returns the topmost annotation item at the position (or 0 if none)*/ + //! Returns the topmost annotation item at the position (or 0 if none) QgsAnnotationItem* itemAtPos( QPointF pos ); QgsAnnotationItem* selectedItem(); - /** Returns a list of all annotationitems in the canvas*/ + //! Returns a list of all annotationitems in the canvas QList annotationItems(); - /** Switches visibility states of text items*/ + //! Switches visibility states of text items void toggleTextItemVisibilities(); QgsAnnotationItem::MouseMoveAction mCurrentMoveAction; diff --git a/src/app/qgsmaptooldeletepart.h b/src/app/qgsmaptooldeletepart.h index d87feb216a43..efbe76412d16 100644 --- a/src/app/qgsmaptooldeletepart.h +++ b/src/app/qgsmaptooldeletepart.h @@ -20,7 +20,7 @@ class QgsVertexMarker; -/** Map tool to delete vertices from line/polygon features*/ +//! Map tool to delete vertices from line/polygon features class APP_EXPORT QgsMapToolDeletePart: public QgsMapToolEdit { Q_OBJECT diff --git a/src/app/qgsmaptooldeletering.h b/src/app/qgsmaptooldeletering.h index df3d9adfd4d6..9281069b1161 100644 --- a/src/app/qgsmaptooldeletering.h +++ b/src/app/qgsmaptooldeletering.h @@ -19,7 +19,7 @@ #include "qgsmaptooledit.h" class QgsVertexMarker; -/** Map tool to delete vertices from line/polygon features*/ +//! Map tool to delete vertices from line/polygon features class APP_EXPORT QgsMapToolDeleteRing : public QgsMapToolEdit { diff --git a/src/app/qgsmaptoollabel.h b/src/app/qgsmaptoollabel.h index 2ff0c3854317..c1a6677789fb 100644 --- a/src/app/qgsmaptoollabel.h +++ b/src/app/qgsmaptoollabel.h @@ -23,7 +23,7 @@ class QgsRubberBand; -/** Base class for map tools that modify label properties*/ +//! Base class for map tools that modify label properties class APP_EXPORT QgsMapToolLabel: public QgsMapTool { Q_OBJECT @@ -63,7 +63,7 @@ class APP_EXPORT QgsMapToolLabel: public QgsMapTool protected: QgsRubberBand* mLabelRubberBand; QgsRubberBand* mFeatureRubberBand; - /** Shows label fixpoint (left/bottom by default)*/ + //! Shows label fixpoint (left/bottom by default) QgsRubberBand* mFixPointRubberBand; struct LabelDetails @@ -76,7 +76,7 @@ class APP_EXPORT QgsMapToolLabel: public QgsMapTool QgsPalLayerSettings settings; }; - /** Currently dragged label position*/ + //! Currently dragged label position LabelDetails mCurrentLabel; @@ -91,10 +91,10 @@ class APP_EXPORT QgsMapToolLabel: public QgsMapTool @return true in case of success*/ bool currentLabelRotationPoint( QgsPoint& pos, bool ignoreUpsideDown = false, bool rotatingUnpinned = false ); - /** Creates label / feature / fixpoint rubber bands for the current label position*/ + //! Creates label / feature / fixpoint rubber bands for the current label position void createRubberBands(); - /** Removes label / feature / fixpoint rubber bands*/ + //! Removes label / feature / fixpoint rubber bands void deleteRubberBands(); /** Returns current label's text @@ -107,17 +107,17 @@ class APP_EXPORT QgsMapToolLabel: public QgsMapTool @return true in case of success*/ bool currentFeature( QgsFeature& f, bool fetchGeom = false ); - /** Returns the font for the current feature (considering default font and data defined properties)*/ + //! Returns the font for the current feature (considering default font and data defined properties) QFont currentLabelFont(); - /** Returns a data defined attribute column name for particular property or empty string if not defined */ + //! Returns a data defined attribute column name for particular property or empty string if not defined QString dataDefinedColumnName( QgsPalLayerSettings::DataDefinedProperties p, const QgsPalLayerSettings& labelSettings ) const; /** Returns a data defined attribute column index @return -1 if column does not exist or an expression is used instead */ int dataDefinedColumnIndex( QgsPalLayerSettings::DataDefinedProperties p, const QgsPalLayerSettings& labelSettings, const QgsVectorLayer* vlayer ) const; - /** Returns whether to preserve predefined rotation data during label pin/unpin operations*/ + //! Returns whether to preserve predefined rotation data during label pin/unpin operations bool currentLabelPreserveRotation(); /** Get data defined position of current label diff --git a/src/app/qgsmaptoolmeasureangle.h b/src/app/qgsmaptoolmeasureangle.h index 05b69034522f..2b1acd53e404 100644 --- a/src/app/qgsmaptoolmeasureangle.h +++ b/src/app/qgsmaptoolmeasureangle.h @@ -23,7 +23,7 @@ class QgsDisplayAngle; class QgsRubberBand; -/** Map tool to measure angle between two segments*/ +//! Map tool to measure angle between two segments class APP_EXPORT QgsMapToolMeasureAngle: public QgsMapTool { Q_OBJECT @@ -46,28 +46,28 @@ class APP_EXPORT QgsMapToolMeasureAngle: public QgsMapTool void deactivate() override; private: - /** Points defining the angle (three for measuring)*/ + //! Points defining the angle (three for measuring) QList mAnglePoints; QgsRubberBand* mRubberBand; QgsDisplayAngle* mResultDisplay; - /** Creates a new rubber band and deletes the old one*/ + //! Creates a new rubber band and deletes the old one void createRubberBand(); - /** Snaps point to background layers*/ + //! Snaps point to background layers QgsPoint snapPoint( QPoint p ); - /** Tool for measuring */ + //! Tool for measuring QgsDistanceArea mDa; public slots: - /** Recalculate angle if projection state changed*/ + //! Recalculate angle if projection state changed void updateSettings(); private slots: - /** Deletes the rubber band and the dialog*/ + //! Deletes the rubber band and the dialog void stopMeasuring(); - /** Configures distance area objects with ellipsoid / output crs*/ + //! Configures distance area objects with ellipsoid / output crs void configureDistanceArea(); }; diff --git a/src/app/qgsmaptoolmovefeature.h b/src/app/qgsmaptoolmovefeature.h index c30cf1497497..fd888423155e 100644 --- a/src/app/qgsmaptoolmovefeature.h +++ b/src/app/qgsmaptoolmovefeature.h @@ -18,7 +18,7 @@ #include "qgsmaptooladvanceddigitizing.h" -/** Map tool for translating feature position by mouse drag*/ +//! Map tool for translating feature position by mouse drag class APP_EXPORT QgsMapToolMoveFeature: public QgsMapToolAdvancedDigitizing { Q_OBJECT @@ -34,13 +34,13 @@ class APP_EXPORT QgsMapToolMoveFeature: public QgsMapToolAdvancedDigitizing void deactivate() override; private: - /** Start point of the move in map coordinates*/ + //! Start point of the move in map coordinates QgsPoint mStartPointMapCoords; - /** Rubberband that shows the feature being moved*/ + //! Rubberband that shows the feature being moved QgsRubberBand* mRubberBand; - /** Id of moved feature*/ + //! Id of moved feature QgsFeatureIds mMovedFeatures; QPoint mPressPos; diff --git a/src/app/qgsmaptoolmovelabel.h b/src/app/qgsmaptoolmovelabel.h index 4eddaaee10cc..464eb99c4add 100644 --- a/src/app/qgsmaptoolmovelabel.h +++ b/src/app/qgsmaptoolmovelabel.h @@ -20,7 +20,7 @@ #include "qgsmaptoollabel.h" -/** A map tool for dragging label positions*/ +//! A map tool for dragging label positions class APP_EXPORT QgsMapToolMoveLabel: public QgsMapToolLabel { Q_OBJECT @@ -37,7 +37,7 @@ class APP_EXPORT QgsMapToolMoveLabel: public QgsMapToolLabel protected: - /** Start point of the move in map coordinates*/ + //! Start point of the move in map coordinates QgsPoint mStartPointMapCoords; double mClickOffsetX; diff --git a/src/app/qgsmaptooloffsetcurve.h b/src/app/qgsmaptooloffsetcurve.h index 9f55a5a31d32..d3b685f021ba 100644 --- a/src/app/qgsmaptooloffsetcurve.h +++ b/src/app/qgsmaptooloffsetcurve.h @@ -34,30 +34,30 @@ class APP_EXPORT QgsMapToolOffsetCurve: public QgsMapToolEdit void canvasMoveEvent( QgsMapMouseEvent* e ) override; private slots: - /** Places curve offset to value entered in the spin box*/ + //! Places curve offset to value entered in the spin box void placeOffsetCurveToValue(); - /** Apply the offset either from the spin box or from the mouse event */ + //! Apply the offset either from the spin box or from the mouse event void applyOffset(); private: - /** Rubberband that shows the position of the offset curve*/ + //! Rubberband that shows the position of the offset curve QgsRubberBand* mRubberBand; - /** Geometry to manipulate*/ + //! Geometry to manipulate QgsGeometry mOriginalGeometry; - /** Geometry after manipulation*/ + //! Geometry after manipulation QgsGeometry mModifiedGeometry; - /** ID of manipulated feature*/ + //! ID of manipulated feature QgsFeatureId mModifiedFeature; - /** Layer ID of source layer*/ + //! Layer ID of source layer QString mSourceLayerId; - /** Internal flag to distinguish move from click*/ + //! Internal flag to distinguish move from click bool mGeometryModified; - /** Shows current distance value and allows numerical editing*/ + //! Shows current distance value and allows numerical editing QgsDoubleSpinBox* mDistanceWidget; - /** Marker to show the cursor was snapped to another location*/ + //! Marker to show the cursor was snapped to another location QgsVertexMarker* mSnapVertexMarker; - /** Forces geometry copy (no modification of geometry in current layer)*/ + //! Forces geometry copy (no modification of geometry in current layer) bool mForceCopy; bool mMultiPartGeometry; @@ -67,11 +67,11 @@ class APP_EXPORT QgsMapToolOffsetCurve: public QgsMapToolEdit void createDistanceWidget(); void deleteDistanceWidget(); void setOffsetForRubberBand( double offset ); - /** Creates a linestring from the polygon ring containing the snapped vertex. Caller takes ownership of the created object*/ + //! Creates a linestring from the polygon ring containing the snapped vertex. Caller takes ownership of the created object QgsGeometry linestringFromPolygon( const QgsGeometry& featureGeom, int vertex ); - /** Returns a single line from a multiline (or does nothing if geometry is already a single line). Deletes the input geometry*/ + //! Returns a single line from a multiline (or does nothing if geometry is already a single line). Deletes the input geometry QgsGeometry convertToSingleLine( const QgsGeometry& geom, int vertex, bool& isMulti ); - /** Converts offset line back to a multiline if necessary*/ + //! Converts offset line back to a multiline if necessary QgsGeometry* convertToMultiLine( QgsGeometry* geom ); }; diff --git a/src/app/qgsmaptoolpinlabels.h b/src/app/qgsmaptoolpinlabels.h index cc74ba8f5635..3a4e4120a5d9 100644 --- a/src/app/qgsmaptoolpinlabels.h +++ b/src/app/qgsmaptoolpinlabels.h @@ -23,7 +23,7 @@ class QgsRubberBand; class QgsLabelPosition; -/** A map tool for pinning (writing to attribute table) and unpinning labelpositions and rotation*/ +//! A map tool for pinning (writing to attribute table) and unpinning labelpositions and rotation class APP_EXPORT QgsMapToolPinLabels: public QgsMapToolLabel { Q_OBJECT diff --git a/src/app/qgsmaptoolpointsymbol.h b/src/app/qgsmaptoolpointsymbol.h index 360110e83b42..8ac682889656 100644 --- a/src/app/qgsmaptoolpointsymbol.h +++ b/src/app/qgsmaptoolpointsymbol.h @@ -42,7 +42,7 @@ class APP_EXPORT QgsMapToolPointSymbol: public QgsMapToolEdit QgsVectorLayer* mActiveLayer; QgsFeatureId mFeatureNumber; - /** Screen coordinate of the snaped feature*/ + //! Screen coordinate of the snaped feature QPoint mSnappedPoint; virtual void canvasPressOnFeature( QgsMapMouseEvent* e, const QgsFeature& feature, const QgsPoint& snappedPoint ) = 0; diff --git a/src/app/qgsmaptoolreshape.h b/src/app/qgsmaptoolreshape.h index 72dcc07c0455..e0d0ebc12128 100644 --- a/src/app/qgsmaptoolreshape.h +++ b/src/app/qgsmaptoolreshape.h @@ -18,7 +18,7 @@ #include "qgsmaptoolcapture.h" -/** A map tool that draws a line and splits the features cut by the line*/ +//! A map tool that draws a line and splits the features cut by the line class APP_EXPORT QgsMapToolReshape: public QgsMapToolCapture { Q_OBJECT diff --git a/src/app/qgsmaptoolrotatefeature.h b/src/app/qgsmaptoolrotatefeature.h index b20acdc63c15..19c479bb6678 100644 --- a/src/app/qgsmaptoolrotatefeature.h +++ b/src/app/qgsmaptoolrotatefeature.h @@ -61,7 +61,7 @@ class APP_EXPORT QgsAngleMagnetWidget : public QWidget }; -/** Map tool to rotate features */ +//! Map tool to rotate features class APP_EXPORT QgsMapToolRotateFeature: public QgsMapToolEdit { Q_OBJECT @@ -91,14 +91,14 @@ class APP_EXPORT QgsMapToolRotateFeature: public QgsMapToolEdit void createRotationWidget(); void deleteRotationWidget(); - /** Start point of the move in map coordinates*/ + //! Start point of the move in map coordinates QgsPoint mStartPointMapCoords; QPointF mInitialPos; - /** Rubberband that shows the feature being moved*/ + //! Rubberband that shows the feature being moved QgsRubberBand* mRubberBand; - /** Id of moved feature*/ + //! Id of moved feature QgsFeatureIds mRotatedFeatures; double mRotation; double mRotationOffset; @@ -108,7 +108,7 @@ class APP_EXPORT QgsMapToolRotateFeature: public QgsMapToolEdit bool mRotationActive; - /** Shows current angle value and allows numerical editing*/ + //! Shows current angle value and allows numerical editing QgsAngleMagnetWidget* mRotationWidget; }; diff --git a/src/app/qgsmaptoolrotatelabel.h b/src/app/qgsmaptoolrotatelabel.h index 6b5150162827..06af32172b46 100644 --- a/src/app/qgsmaptoolrotatelabel.h +++ b/src/app/qgsmaptoolrotatelabel.h @@ -36,13 +36,13 @@ class APP_EXPORT QgsMapToolRotateLabel: public QgsMapToolLabel protected: static int roundTo15Degrees( double n ); - /** Converts azimuth value to counterclockwise 0 - 360*/ + //! Converts azimuth value to counterclockwise 0 - 360 static double azimuthToCCW( double a ); QgsRubberBand* createRotationPreviewBox(); void setRotationPreviewBox( double rotation ); - /** Rotates input point counterclockwise around centerPoint*/ + //! Rotates input point counterclockwise around centerPoint QgsPoint rotatePointCounterClockwise( const QgsPoint& input, const QgsPoint& centerPoint, double degrees ); double mStartRotation; //rotation value prior to start rotating @@ -52,7 +52,7 @@ class APP_EXPORT QgsMapToolRotateLabel: public QgsMapToolLabel QgsPointRotationItem* mRotationItem; QgsRubberBand* mRotationPreviewBox; - /** True if ctrl was pressed during the last mouse move event*/ + //! True if ctrl was pressed during the last mouse move event bool mCtrlPressed; }; diff --git a/src/app/qgsmaptoolrotatepointsymbols.h b/src/app/qgsmaptoolrotatepointsymbols.h index 82d1db4b2b6e..087cccc1ca50 100644 --- a/src/app/qgsmaptoolrotatepointsymbols.h +++ b/src/app/qgsmaptoolrotatepointsymbols.h @@ -50,27 +50,27 @@ class APP_EXPORT QgsMapToolRotatePointSymbols: public QgsMapToolPointSymbol private: - /** Last azimut between mouse and edited point*/ + //! Last azimut between mouse and edited point double mCurrentMouseAzimut; - /** Last feature rotation*/ + //! Last feature rotation double mCurrentRotationFeature; bool mRotating; QSet mCurrentRotationAttributes; - /** Item that displays rotation during mouse move*/ + //! Item that displays rotation during mouse move QgsPointRotationItem* mRotationItem; - /** True if ctrl was pressed during the last mouse move event*/ + //! True if ctrl was pressed during the last mouse move event bool mCtrlPressed; //! Clone of first found marker symbol for feature with rotation attribute set QScopedPointer< QgsMarkerSymbol > mMarkerSymbol; void drawArrow( double azimut ) const; - /** Calculates the azimut between mousePos and mSnappedPoint*/ + //! Calculates the azimut between mousePos and mSnappedPoint double calculateAzimut( QPoint mousePos ); - /** Create item with the point symbol for a specific feature. This will be used to show the rotation to the user*/ + //! Create item with the point symbol for a specific feature. This will be used to show the rotation to the user void createPixmapItem( QgsMarkerSymbol *markerSymbol ); - /** Sets the rotation of the pixmap item*/ + //! Sets the rotation of the pixmap item void setPixmapItemRotation( double rotation ); - /** Rounds value to 15 degree integer (used if ctrl pressed)*/ + //! Rounds value to 15 degree integer (used if ctrl pressed) static int roundTo15Degrees( double n ); }; diff --git a/src/app/qgsmaptoolshowhidelabels.h b/src/app/qgsmaptoolshowhidelabels.h index 631c0ed55241..25cc468d8a0d 100644 --- a/src/app/qgsmaptoolshowhidelabels.h +++ b/src/app/qgsmaptoolshowhidelabels.h @@ -22,7 +22,7 @@ #include "qgsfeature.h" -/** A map tool for showing or hidding a feature's label*/ +//! A map tool for showing or hidding a feature's label class APP_EXPORT QgsMapToolShowHideLabels : public QgsMapToolLabel { Q_OBJECT diff --git a/src/app/qgsmaptoolsimplify.h b/src/app/qgsmaptoolsimplify.h index b5e1349480fb..64624b148cf0 100644 --- a/src/app/qgsmaptoolsimplify.h +++ b/src/app/qgsmaptoolsimplify.h @@ -49,7 +49,7 @@ class APP_EXPORT QgsSimplifyDialog : public QDialog, private Ui::SimplifyLineDia }; -/** Map tool to simplify line/polygon features */ +//! Map tool to simplify line/polygon features class APP_EXPORT QgsMapToolSimplify: public QgsMapToolEdit { Q_OBJECT @@ -71,12 +71,12 @@ class APP_EXPORT QgsMapToolSimplify: public QgsMapToolEdit QString statusText() const; public slots: - /** Slot to change display when slidebar is moved */ + //! Slot to change display when slidebar is moved void setTolerance( double tolerance ); void setToleranceUnits( int units ); - /** Slot to store feture after simplification */ + //! Slot to store feture after simplification void storeSimplified(); void clearSelection(); @@ -91,15 +91,15 @@ class APP_EXPORT QgsMapToolSimplify: public QgsMapToolEdit int vertexCount( const QgsGeometry& g ) const; // data - /** Dialog with slider to set correct tolerance value */ + //! Dialog with slider to set correct tolerance value QgsSimplifyDialog* mSimplifyDialog; - /** Rubber bands to draw current state of simplification */ + //! Rubber bands to draw current state of simplification QList mRubberBands; - /** Features with which we are working */ + //! Features with which we are working QList mSelectedFeatures; - /** Real value of tolerance */ + //! Real value of tolerance double mTolerance; QgsTolerance::UnitType mToleranceUnits; diff --git a/src/app/qgsmaptoolsplitfeatures.h b/src/app/qgsmaptoolsplitfeatures.h index 29e197119776..249df5a65620 100644 --- a/src/app/qgsmaptoolsplitfeatures.h +++ b/src/app/qgsmaptoolsplitfeatures.h @@ -18,7 +18,7 @@ #include "qgsmaptoolcapture.h" -/** A map tool that draws a line and splits the features cut by the line*/ +//! A map tool that draws a line and splits the features cut by the line class APP_EXPORT QgsMapToolSplitFeatures: public QgsMapToolCapture { Q_OBJECT diff --git a/src/app/qgsmaptoolsplitparts.h b/src/app/qgsmaptoolsplitparts.h index 58a2fbe17e30..6a3252189948 100644 --- a/src/app/qgsmaptoolsplitparts.h +++ b/src/app/qgsmaptoolsplitparts.h @@ -18,7 +18,7 @@ #include "qgsmaptoolcapture.h" -/** A map tool that draws a line and splits the parts cut by the line*/ +//! A map tool that draws a line and splits the parts cut by the line class QgsMapToolSplitParts: public QgsMapToolCapture { Q_OBJECT diff --git a/src/app/qgsmeasuretool.h b/src/app/qgsmeasuretool.h index 72900357bc87..ca35cb8bd065 100644 --- a/src/app/qgsmeasuretool.h +++ b/src/app/qgsmeasuretool.h @@ -105,7 +105,7 @@ class APP_EXPORT QgsMeasureTool : public QgsMapTool //@param p (pixel) coordinate QgsPoint snapPoint( QPoint p ); - /** Removes the last vertex from mRubberBand*/ + //! Removes the last vertex from mRubberBand void undo(); }; diff --git a/src/app/qgsmergeattributesdialog.h b/src/app/qgsmergeattributesdialog.h index 20e7243328c9..7e0d4f13e6dc 100644 --- a/src/app/qgsmergeattributesdialog.h +++ b/src/app/qgsmergeattributesdialog.h @@ -30,7 +30,7 @@ class QgsVectorLayer; class QComboBox; -/** A dialog to insert the merge behaviour for attributes (e.g. for the union features editing tool)*/ +//! A dialog to insert the merge behaviour for attributes (e.g. for the union features editing tool) class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeAttributesDialogBase { Q_OBJECT @@ -38,7 +38,7 @@ class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeA enum ItemDataRole { - FieldIndex = Qt::UserRole /*!< index of corresponding field in source table */ + FieldIndex = Qt::UserRole //!< Index of corresponding field in source table }; @@ -68,16 +68,16 @@ class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeA private: QgsMergeAttributesDialog(); //default constructor forbidden void createTableWidgetContents(); - /** Create new combo box with the options for featureXX / mean / min / max */ + //! Create new combo box with the options for featureXX / mean / min / max QComboBox* createMergeComboBox( QVariant::Type columnType ) const; /** Returns the table widget column index of a combo box @return the column index or -1 in case of error*/ int findComboColumn( QComboBox* c ) const; - /** Calculates the merged value of a column (depending on the selected merge behaviour) and inserts the value in the corresponding cell*/ + //! Calculates the merged value of a column (depending on the selected merge behaviour) and inserts the value in the corresponding cell void refreshMergedValue( int col ); - /** Inserts the attribute value of a specific feature into the row of merged attributes*/ + //! Inserts the attribute value of a specific feature into the row of merged attributes QVariant featureAttribute( QgsFeatureId featureId, int col ); - /** Appends the values of the features for the final value*/ + //! Appends the values of the features for the final value QVariant concatenationAttribute( int col ); /** Calculates a summary statistic for a column. Returns null if no valid numerical @@ -85,13 +85,13 @@ class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeA */ QVariant calcStatistic( int col, QgsStatisticalSummary::Statistic stat ); - /** Sets mSelectionRubberBand to a new feature*/ + //! Sets mSelectionRubberBand to a new feature void createRubberBandForFeature( QgsFeatureId featureId ); QgsFeatureList mFeatureList; QgsVectorLayer* mVectorLayer; QgsMapCanvas* mMapCanvas; - /** Item that highlights the selected feature in the merge table*/ + //! Item that highlights the selected feature in the merge table QgsRubberBand* mSelectionRubberBand; QgsFields mFields; diff --git a/src/app/qgsnewspatialitelayerdialog.h b/src/app/qgsnewspatialitelayerdialog.h index 570ec34d6ced..d1f6dacf3c04 100644 --- a/src/app/qgsnewspatialitelayerdialog.h +++ b/src/app/qgsnewspatialitelayerdialog.h @@ -52,10 +52,10 @@ class APP_EXPORT QgsNewSpatialiteLayerDialog: public QDialog, private Ui::QgsNew void on_buttonBox_rejected(); private: - /** Returns the selected geometry type*/ + //! Returns the selected geometry type QString selectedType() const; - /** Create a new database */ + //! Create a new database bool createDb(); bool apply(); diff --git a/src/app/qgsoptions.h b/src/app/qgsoptions.h index 73a48a12068e..d9b2a4794795 100644 --- a/src/app/qgsoptions.h +++ b/src/app/qgsoptions.h @@ -81,7 +81,7 @@ class APP_EXPORT QgsOptions : public QgsOptionsDialogBase, private Ui::QgsOption */ void on_mProjectOnLaunchCmbBx_currentIndexChanged( int indx ); - /** Slot to choose path to project to open after launch */ + //! Slot to choose path to project to open after launch void on_mProjectOnLaunchPushBtn_pressed(); /** @@ -91,42 +91,42 @@ class APP_EXPORT QgsOptions : public QgsOptionsDialogBase, private Ui::QgsOption */ bool newVisible(); - /** Slot to select the default font point size for app */ + //! Slot to select the default font point size for app void on_spinFontSize_valueChanged( int fontSize ); - /** Slot to set font family for app to Qt default */ + //! Slot to set font family for app to Qt default void on_mFontFamilyRadioQt_released(); - /** Slot to set font family for app to custom choice */ + //! Slot to set font family for app to custom choice void on_mFontFamilyRadioCustom_released(); - /** Slot to select custom font family choice for app */ + //! Slot to select custom font family choice for app void on_mFontFamilyComboBox_currentFontChanged( const QFont& font ); - /** Slot to set whether to use custom group boxes */ + //! Slot to set whether to use custom group boxes void on_mCustomGroupBoxChkBx_clicked( bool chkd ); void on_mProxyTypeComboBox_currentIndexChanged( int idx ); - /** Add a new URL to exclude from Proxy*/ + //! Add a new URL to exclude from Proxy void on_mAddUrlPushButton_clicked(); - /** Remove an URL to exclude from Proxy*/ + //! Remove an URL to exclude from Proxy void on_mRemoveUrlPushButton_clicked(); - /** Slot to flag restoring/delete window state settings upon restart*/ + //! Slot to flag restoring/delete window state settings upon restart void on_mRestoreDefaultWindowStateBtn_clicked(); - /** Slot to enable custom environment variables table and buttons */ + //! Slot to enable custom environment variables table and buttons void on_mCustomVariablesChkBx_toggled( bool chkd ); - /** Slot to add a custom environment variable to the app */ + //! Slot to add a custom environment variable to the app void on_mAddCustomVarBtn_clicked(); - /** Slot to remove a custom environment variable from the app */ + //! Slot to remove a custom environment variable from the app void on_mRemoveCustomVarBtn_clicked(); - /** Slot to filter out current environment variables not specific to QGIS */ + //! Slot to filter out current environment variables not specific to QGIS void on_mCurrentVariablesQGISChxBx_toggled( bool qgisSpecific ); /* Let the user add a path to the list of search paths @@ -177,16 +177,16 @@ class APP_EXPORT QgsOptions : public QgsOptionsDialogBase, private Ui::QgsOption * used in scale combobox */ void on_pbnDefaultScaleValues_clicked(); - /** Let the user load scales from file */ + //! Let the user load scales from file void on_pbnImportScales_clicked(); - /** Let the user load scales from file */ + //! Let the user load scales from file void on_pbnExportScales_clicked(); - /** Auto slot executed when the active page in the option section widget is changed */ + //! Auto slot executed when the active page in the option section widget is changed void on_mOptionsStackedWidget_currentChanged( int theIndx ); - /** A scale in the list of predefined scales changed */ + //! A scale in the list of predefined scales changed void scaleItemChanged( QListWidgetItem* changedScaleItem ); /* Load the list of drivers available in GDAL */ @@ -209,7 +209,7 @@ class APP_EXPORT QgsOptions : public QgsOptionsDialogBase, private Ui::QgsOption QgsCoordinateReferenceSystem mLayerDefaultCrs; bool mLoadedGdalDriverList; - /** Generate table row for custom environment variables */ + //! Generate table row for custom environment variables void addCustomEnvVarRow( const QString& varName, const QString& varVal, const QString& varApply = QString() ); void saveDefaultDatumTransformations(); diff --git a/src/app/qgspointrotationitem.h b/src/app/qgspointrotationitem.h index 2b83afda26c8..d8fa69bdcbd3 100644 --- a/src/app/qgspointrotationitem.h +++ b/src/app/qgspointrotationitem.h @@ -20,7 +20,7 @@ #include #include -/** An item that shows a rotated point symbol (e.g. arrow) centered to a map location together with a text displaying the rotation value*/ +//! An item that shows a rotated point symbol (e.g. arrow) centered to a map location together with a text displaying the rotation value class APP_EXPORT QgsPointRotationItem: public QgsMapCanvasItem { public: @@ -36,14 +36,14 @@ class APP_EXPORT QgsPointRotationItem: public QgsMapCanvasItem void paint( QPainter * painter ) override; - /** Sets the center point of the rotation symbol (in map coordinates)*/ + //! Sets the center point of the rotation symbol (in map coordinates) void setPointLocation( const QgsPoint& p ); /** Sets the rotation of the symbol and displays the new rotation number. Units are degrees, starting from north direction, clockwise direction*/ void setSymbolRotation( int r ) {mRotation = r;} - /** Sets rotation symbol from image (takes ownership)*/ + //! Sets rotation symbol from image (takes ownership) void setSymbol( const QImage& symbolImage ); void setOrientation( Orientation o ) { mOrientation = o; } @@ -51,13 +51,13 @@ class APP_EXPORT QgsPointRotationItem: public QgsMapCanvasItem private: QgsPointRotationItem(); - /** Converts rotation into QPainter rotation considering mOrientation*/ + //! Converts rotation into QPainter rotation considering mOrientation int painterRotation( int rotation ) const; - /** Clockwise (default) or counterclockwise*/ + //! Clockwise (default) or counterclockwise Orientation mOrientation; - /** Font to display the numerical rotation values*/ + //! Font to display the numerical rotation values QFont mFont; - /** Symboll pixmap*/ + //! Symboll pixmap QPixmap mPixmap; int mRotation; }; diff --git a/src/app/qgsprojectlayergroupdialog.h b/src/app/qgsprojectlayergroupdialog.h index 66c1e0c7e5c0..9ca1fc34216b 100644 --- a/src/app/qgsprojectlayergroupdialog.h +++ b/src/app/qgsprojectlayergroupdialog.h @@ -22,12 +22,12 @@ class QDomElement; class QgsLayerTreeGroup; -/** A dialog to select layers and groups from a qgs project*/ +//! A dialog to select layers and groups from a qgs project class APP_EXPORT QgsProjectLayerGroupDialog: public QDialog, private Ui::QgsProjectLayerGroupDialogBase { Q_OBJECT public: - /** Constructor. If a project file is given, the groups/layers are displayed directly and the file selection hidden*/ + //! Constructor. If a project file is given, the groups/layers are displayed directly and the file selection hidden QgsProjectLayerGroupDialog( QWidget * parent = nullptr, const QString& projectFile = QString(), Qt::WindowFlags f = 0 ); ~QgsProjectLayerGroupDialog(); diff --git a/src/app/qgsprojectproperties.h b/src/app/qgsprojectproperties.h index cbebec59d56e..54a086fbf66e 100644 --- a/src/app/qgsprojectproperties.h +++ b/src/app/qgsprojectproperties.h @@ -61,10 +61,10 @@ class APP_EXPORT QgsProjectProperties : public QgsOptionsDialogBase, private Ui: QString title() const; void title( QString const & title ); - /** Accessor for projection */ + //! Accessor for projection QString projectionWkt(); - /** Indicates that the projection switch is on */ + //! Indicates that the projection switch is on bool isProjected(); public slots: @@ -86,13 +86,13 @@ class APP_EXPORT QgsProjectProperties : public QgsOptionsDialogBase, private Ui: * used in scale combobox instead of global ones */ void on_pbnRemoveScale_clicked(); - /** Let the user load scales from file */ + //! Let the user load scales from file void on_pbnImportScales_clicked(); - /** Let the user load scales from file */ + //! Let the user load scales from file void on_pbnExportScales_clicked(); - /** A scale in the list of project scales changed */ + //! A scale in the list of project scales changed void scaleItemChanged( QListWidgetItem* changedScaleItem ); /*! @@ -183,10 +183,10 @@ class APP_EXPORT QgsProjectProperties : public QgsOptionsDialogBase, private Ui: //! Formats for displaying coordinates enum CoordinateFormat { - DecimalDegrees, /*!< Decimal degrees */ - DegreesMinutes, /*!< Degrees, decimal minutes */ - DegreesMinutesSeconds, /*!< Degrees, minutes, seconds */ - MapUnits, /*! Show coordinates in map units */ + DecimalDegrees, //!< Decimal degrees + DegreesMinutes, //!< Degrees, decimal minutes + DegreesMinutesSeconds, //!< Degrees, minutes, seconds + MapUnits, //! Show coordinates in map units }; QgsRelationManagerDialog *mRelationManagerDlg; diff --git a/src/app/qgsrastercalcdialog.h b/src/app/qgsrastercalcdialog.h index 3c0d47bd40a4..f2dbfcaa32a5 100644 --- a/src/app/qgsrastercalcdialog.h +++ b/src/app/qgsrastercalcdialog.h @@ -21,7 +21,7 @@ #include "ui_qgsrastercalcdialogbase.h" #include "qgsrastercalculator.h" -/** A dialog to enter a raster calculation expression*/ +//! A dialog to enter a raster calculation expression class APP_EXPORT QgsRasterCalcDialog: public QDialog, private Ui::QgsRasterCalcDialogBase { Q_OBJECT @@ -35,11 +35,11 @@ class APP_EXPORT QgsRasterCalcDialog: public QDialog, private Ui::QgsRasterCalcD QgsCoordinateReferenceSystem outputCrs() const; bool addLayerToProject() const; - /** Bounding box for output raster*/ + //! Bounding box for output raster QgsRectangle outputRectangle() const; - /** Number of pixels in x-direction*/ + //! Number of pixels in x-direction int numberOfColumns() const; - /** Number of pixels in y-direction*/ + //! Number of pixels in y-direction int numberOfRows() const; QVector rasterEntries() const; @@ -51,7 +51,7 @@ class APP_EXPORT QgsRasterCalcDialog: public QDialog, private Ui::QgsRasterCalcD void on_mCurrentLayerExtentButton_clicked(); void on_mExpressionTextEdit_textChanged(); void on_mOutputLayerLineEdit_textChanged( const QString& text ); - /** Enables ok button if calculator expression is valid and output file path exists*/ + //! Enables ok button if calculator expression is valid and output file path exists void setAcceptButtonState(); //calculator buttons @@ -83,17 +83,17 @@ class APP_EXPORT QgsRasterCalcDialog: public QDialog, private Ui::QgsRasterCalcD private: //insert available GDAL drivers that support the create() option void insertAvailableOutputFormats(); - /** Accesses the available raster layers/bands from the layer registry*/ + //! Accesses the available raster layers/bands from the layer registry void insertAvailableRasterBands(); - /** Returns true if raster calculator expression has valid syntax*/ + //! Returns true if raster calculator expression has valid syntax bool expressionValid() const; - /** Returns true if output file directory exists*/ + //! Returns true if output file directory exists bool filePathValid() const; static QString quoteBandEntry( const QString& layerName ); - /** Stores relation between driver name and extension*/ + //! Stores relation between driver name and extension QMap mDriverExtensionMap; QList mAvailableRasterBands; diff --git a/src/app/qgsrasterlayerproperties.h b/src/app/qgsrasterlayerproperties.h index 00dc6407fdd8..9ce8db5286c0 100644 --- a/src/app/qgsrasterlayerproperties.h +++ b/src/app/qgsrasterlayerproperties.h @@ -47,105 +47,105 @@ class APP_EXPORT QgsRasterLayerProperties : public QgsOptionsDialogBase, private * @param ml Map layer for which properties will be displayed */ QgsRasterLayerProperties( QgsMapLayer *lyr, QgsMapCanvas* theCanvas, QWidget *parent = nullptr, Qt::WindowFlags = QgisGui::ModalDialogFlags ); - /** \brief Destructor */ + //! \brief Destructor ~QgsRasterLayerProperties(); - /** Synchronize state with associated raster layer */ + //! Synchronize state with associated raster layer void sync(); public slots: //TODO: Verify that these all need to be public - /** \brief Applies the settings made in the dialog without closing the box */ + //! \brief Applies the settings made in the dialog without closing the box void apply(); - /** Called when cancel button is pressed */ + //! Called when cancel button is pressed void onCancel(); - /** \brief Slot to update layer display name as original is edited. */ + //! \brief Slot to update layer display name as original is edited. void on_mLayerOrigNameLineEd_textEdited( const QString& text ); - /** \brief this slot asks the rasterlayer to construct pyramids */ + //! \brief this slot asks the rasterlayer to construct pyramids void on_buttonBuildPyramids_clicked(); - /** \brief slot executed when user presses "Add Values From Display" button on the transparency page */ + //! \brief slot executed when user presses "Add Values From Display" button on the transparency page void on_pbnAddValuesFromDisplay_clicked(); - /** \brief slot executed when user presses "Add Values Manually" button on the transparency page */ + //! \brief slot executed when user presses "Add Values Manually" button on the transparency page void on_pbnAddValuesManually_clicked(); - /** \brief slot executed when user changes the layer's CRS */ + //! \brief slot executed when user changes the layer's CRS void on_mCrsSelector_crsChanged( const QgsCoordinateReferenceSystem& crs ); - /** \brief slot executed when user wishes to reset noNoDataValue and transparencyTable to default value */ + //! \brief slot executed when user wishes to reset noNoDataValue and transparencyTable to default value void on_pbnDefaultValues_clicked(); - /** \brief slot executed when user wishes to export transparency values */ + //! \brief slot executed when user wishes to export transparency values void on_pbnExportTransparentPixelValues_clicked(); - /** \brief auto slot executed when the active page in the main widget stack is changed */ + //! \brief auto slot executed when the active page in the main widget stack is changed void mOptionsStackedWidget_CurrentChanged( int indx ); - /** \brief slow executed when user wishes to import transparency values */ + //! \brief slow executed when user wishes to import transparency values void on_pbnImportTransparentPixelValues_clicked(); - /** \brief slot executed when user presses "Remove Selected Row" button on the transparency page */ + //! \brief slot executed when user presses "Remove Selected Row" button on the transparency page void on_pbnRemoveSelectedRow_clicked(); - /** \brief slot executed when the single band radio button is pressed. */ - /** \brief slot executed when the reset null value to file default icon is selected */ + //! \brief slot executed when the single band radio button is pressed. + //! \brief slot executed when the reset null value to file default icon is selected //void on_btnResetNull_clicked(); void pixelSelected( const QgsPoint& ); - /** \brief slot executed when the transparency level changes. */ + //! \brief slot executed when the transparency level changes. void sliderTransparency_valueChanged( int ); private slots: void on_mRenderTypeComboBox_currentIndexChanged( int index ); - /** Load the default style when appropriate button is pressed. */ + //! Load the default style when appropriate button is pressed. void loadDefaultStyle_clicked(); - /** Save the default style when appropriate button is pressed. */ + //! Save the default style when appropriate button is pressed. void saveDefaultStyle_clicked(); - /** Load a saved style when appropriate button is pressed. */ + //! Load a saved style when appropriate button is pressed. void loadStyle_clicked(); - /** Save a style when appriate button is pressed. */ + //! Save a style when appriate button is pressed. void saveStyleAs_clicked(); - /** Help button */ + //! Help button void on_buttonBox_helpRequested() { QgsContextHelp::run( metaObject()->className() ); } - /** Slot to reset all color rendering options to default */ + //! Slot to reset all color rendering options to default void on_mResetColorRenderingBtn_clicked(); - /** Enable or disable Build pyramids button depending on selection in pyramids list*/ + //! Enable or disable Build pyramids button depending on selection in pyramids list void toggleBuildPyramidsButton(); - /** Enable or disable saturation controls depending on choice of grayscale mode */ + //! Enable or disable saturation controls depending on choice of grayscale mode void toggleSaturationControls( int grayscaleMode ); - /** Enable or disable colorize controls depending on checkbox */ + //! Enable or disable colorize controls depending on checkbox void toggleColorizeControls( bool colorizeEnabled ); - /** Transparency cell changed */ + //! Transparency cell changed void transparencyCellTextEdited( const QString & text ); void aboutToShowStyleMenu(); - /** Make GUI reflect the layer's state */ + //! Make GUI reflect the layer's state void syncToLayer(); signals: - /** Emitted when changes to layer were saved to update legend */ + //! Emitted when changes to layer were saved to update legend void refreshLegend( const QString& layerID, bool expandItem ); private: - /** \brief A constant that signals property not used */ + //! \brief A constant that signals property not used const QString TRSTRING_NOT_SET; - /** \brief Default contrast enhancement algorithm */ + //! \brief Default contrast enhancement algorithm QString mDefaultContrastEnhancementAlgorithm; - /** \brief default standard deviation */ + //! \brief default standard deviation double mDefaultStandardDeviation; - /** \brief Default band combination */ + //! \brief Default band combination int mDefaultRedBand; int mDefaultGreenBand; int mDefaultBlueBand; - /** \brief Flag to indicate if Gray minimum maximum values are actual minimum maximum values */ + //! \brief Flag to indicate if Gray minimum maximum values are actual minimum maximum values bool mGrayMinimumMaximumEstimated; - /** \brief Flag to indicate if RGB minimum maximum values are actual minimum maximum values */ + //! \brief Flag to indicate if RGB minimum maximum values are actual minimum maximum values bool mRGBMinimumMaximumEstimated; - /** \brief Pointer to the raster layer that this property dilog changes the behaviour of. */ + //! \brief Pointer to the raster layer that this property dilog changes the behaviour of. QgsRasterLayer * mRasterLayer; /** \brief If the underlying raster layer doesn't have a provider @@ -161,7 +161,7 @@ class APP_EXPORT QgsRasterLayerProperties : public QgsOptionsDialogBase, private void setupTransparencyTable( int nBands ); - /** \brief Clear the current transparency table and populate the table with the correct types for current drawing mode and data type*/ + //! \brief Clear the current transparency table and populate the table with the correct types for current drawing mode and data type void populateTransparencyTable( QgsRasterRenderer* renderer ); void setTransparencyCell( int row, int column, double value ); diff --git a/src/app/qgssnappingwidget.h b/src/app/qgssnappingwidget.h index e1089a188832..189864f7c1a7 100644 --- a/src/app/qgssnappingwidget.h +++ b/src/app/qgssnappingwidget.h @@ -54,7 +54,7 @@ class APP_EXPORT QgsSnappingWidget : public QWidget */ QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, QWidget* parent = nullptr ); - /** Destructor */ + //! Destructor virtual ~QgsSnappingWidget(); /** diff --git a/src/app/qgsstatusbarmagnifierwidget.h b/src/app/qgsstatusbarmagnifierwidget.h index fb48d9eba662..887848939224 100644 --- a/src/app/qgsstatusbarmagnifierwidget.h +++ b/src/app/qgsstatusbarmagnifierwidget.h @@ -40,7 +40,7 @@ class APP_EXPORT QgsStatusBarMagnifierWidget : public QWidget */ QgsStatusBarMagnifierWidget( QWidget* parent = nullptr ); - /** Destructor */ + //! Destructor virtual ~QgsStatusBarMagnifierWidget(); void setDefaultFactor( double factor ); diff --git a/src/app/qgsstatusbarscalewidget.h b/src/app/qgsstatusbarscalewidget.h index 1444043ad87b..aa382b4d2a08 100644 --- a/src/app/qgsstatusbarscalewidget.h +++ b/src/app/qgsstatusbarscalewidget.h @@ -39,7 +39,7 @@ class APP_EXPORT QgsStatusBarScaleWidget : public QWidget public: explicit QgsStatusBarScaleWidget( QgsMapCanvas* canvas, QWidget *parent = 0 ); - /** Destructor */ + //! Destructor virtual ~QgsStatusBarScaleWidget(); /** diff --git a/src/app/qgstextannotationdialog.h b/src/app/qgstextannotationdialog.h index 381afbfd9d17..c673dc961ddc 100644 --- a/src/app/qgstextannotationdialog.h +++ b/src/app/qgstextannotationdialog.h @@ -36,7 +36,7 @@ class APP_EXPORT QgsTextAnnotationDialog: public QDialog, private Ui::QgsTextAnn private: QgsTextAnnotationItem* mItem; - /** Text document (a clone of the annotation items document)*/ + //! Text document (a clone of the annotation items document) QTextDocument* mTextDocument; QgsAnnotationWidget* mEmbeddedWidget; diff --git a/src/app/qgstip.h b/src/app/qgstip.h index e90e71a37b9c..c81ddbd8355d 100644 --- a/src/app/qgstip.h +++ b/src/app/qgstip.h @@ -30,24 +30,24 @@ class APP_EXPORT QgsTip { public: - /** Constructor */ + //! Constructor QgsTip() {} - /** Destructor */ + //! Destructor ~QgsTip() {} // // Accessors // - /** Get the tip title */ + //! Get the tip title QString title() {return mTitle;} - /** Get the tip content */ + //! Get the tip content QString content() {return mContent;} // // Mutators // - /** Set the tip title */ + //! Set the tip title void setTitle( const QString& theTitle ) {mTitle = theTitle;} - /** Set the tip content*/ + //! Set the tip content void setContent( const QString& theContent ) {mContent = theContent;} private: QString mTitle; diff --git a/src/app/qgstipfactory.h b/src/app/qgstipfactory.h index 41ca9417fb54..b78635a57020 100644 --- a/src/app/qgstipfactory.h +++ b/src/app/qgstipfactory.h @@ -31,9 +31,9 @@ class APP_EXPORT QgsTipFactory : public QObject { Q_OBJECT //used for tr() so we don't need to do QObject::tr() public: - /** Constructor */ + //! Constructor QgsTipFactory(); - /** Destructor */ + //! Destructor ~QgsTipFactory(); /** Get a random tip (generic or gui-centric) * @return An QgsTip containing the tip diff --git a/src/app/qgsundowidget.h b/src/app/qgsundowidget.h index f395b91d6bc0..5687bd7fc4e4 100644 --- a/src/app/qgsundowidget.h +++ b/src/app/qgsundowidget.h @@ -59,7 +59,7 @@ class APP_EXPORT QgsUndoWidget : public QgsPanelWidget */ void destroyStack(); - /** Access to dock's contents */ + //! Access to dock's contents QWidget* dockContents() { return dockWidgetContents; } public slots: diff --git a/src/app/qgsvectorlayerproperties.h b/src/app/qgsvectorlayerproperties.h index 3dc282d5a589..ebfb3018c31e 100644 --- a/src/app/qgsvectorlayerproperties.h +++ b/src/app/qgsvectorlayerproperties.h @@ -55,7 +55,7 @@ class APP_EXPORT QgsVectorLayerProperties : public QgsOptionsDialogBase, private QgsVectorLayerProperties( QgsVectorLayer *lyr = nullptr, QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); ~QgsVectorLayerProperties(); - /** Returns the display name entered in the dialog*/ + //! Returns the display name entered in the dialog QString displayName(); void setRendererDirty( bool ) {} @@ -69,26 +69,26 @@ class APP_EXPORT QgsVectorLayerProperties : public QgsOptionsDialogBase, private @return false in case of a non-existing attribute.*/ bool deleteAttribute( int attr ); - /** Adds a properties page factory to the vector layer properties dialog. */ + //! Adds a properties page factory to the vector layer properties dialog. void addPropertiesPageFactory( QgsMapLayerConfigWidgetFactory *factory ); public slots: void insertFieldOrExpression(); - /** Reset to original (vector layer) values */ + //! Reset to original (vector layer) values void syncToLayer(); - /** Get metadata about the layer in nice formatted html */ + //! Get metadata about the layer in nice formatted html QString metadata(); - /** Slot to update layer display name as original is edited */ + //! Slot to update layer display name as original is edited void on_mLayerOrigNameLineEdit_textEdited( const QString& text ); - /** Called when apply button is pressed or dialog is accepted */ + //! Called when apply button is pressed or dialog is accepted void apply(); - /** Called when cancel button is pressed */ + //! Called when cancel button is pressed void onCancel(); // @@ -115,20 +115,20 @@ class APP_EXPORT QgsVectorLayerProperties : public QgsOptionsDialogBase, private signals: - /** Emitted when changes to layer were saved to update legend */ + //! Emitted when changes to layer were saved to update legend void refreshLegend( const QString& layerID, bool expandItem ); void refreshLegend( const QString& layerID ); void toggleEditing( QgsMapLayer * ); private slots: - /** Toggle editing of layer */ + //! Toggle editing of layer void toggleEditing(); - /** Save the style based on selected format from the menu */ + //! Save the style based on selected format from the menu void saveStyleAsMenuTriggered( QAction * ); - /** Called when is possible to choice if load the style from filesystem or from db */ + //! Called when is possible to choice if load the style from filesystem or from db void loadStyleMenuTriggered( QAction * ); void aboutToShowStyleMenu(); @@ -146,7 +146,7 @@ class APP_EXPORT QgsVectorLayerProperties : public QgsOptionsDialogBase, private void saveStyleAs( StyleType styleType ); - /** When provider supports, it will list all the styles relative the layer in a dialog */ + //! When provider supports, it will list all the styles relative the layer in a dialog void showListOfStylesFromDatabase(); void updateSymbologyPage(); @@ -165,15 +165,15 @@ class APP_EXPORT QgsVectorLayerProperties : public QgsOptionsDialogBase, private QAction* mActionLoadStyle; QAction* mActionSaveStyleAs; - /** Renderer dialog which is shown*/ + //! Renderer dialog which is shown QgsRendererPropertiesDialog* mRendererDialog; - /** Labeling dialog. If apply is pressed, options are applied to vector's QgsLabel */ + //! Labeling dialog. If apply is pressed, options are applied to vector's QgsLabel QgsLabelingWidget* labelingDialog; - /** Actions dialog. If apply is pressed, the actions are stored for later use */ + //! Actions dialog. If apply is pressed, the actions are stored for later use QgsAttributeActionDialog* mActionDialog; - /** Diagram dialog. If apply is pressed, options are applied to vector's diagrams*/ + //! Diagram dialog. If apply is pressed, options are applied to vector's diagrams QgsDiagramProperties* diagramPropertiesDialog; - /** Fields dialog. If apply is pressed, options are applied to vector's diagrams*/ + //! Fields dialog. If apply is pressed, options are applied to vector's diagrams QgsFieldsProperties* mFieldsPropertiesDialog; //! List of joins of a layer at the time of creation of the dialog. Used to return joins to previous state if dialog is cancelled @@ -188,7 +188,7 @@ class APP_EXPORT QgsVectorLayerProperties : public QgsOptionsDialogBase, private void initDiagramTab(); - /** Adds a new join to mJoinTreeWidget*/ + //! Adds a new join to mJoinTreeWidget void addJoinToTreeWidget( const QgsVectorJoinInfo& join , const int insertIndex = -1 ); QgsExpressionContext mContext; diff --git a/src/core/auth/qgsauthcertutils.h b/src/core/auth/qgsauthcertutils.h index 9f50eb407297..8625c4587c8f 100644 --- a/src/core/auth/qgsauthcertutils.h +++ b/src/core/auth/qgsauthcertutils.h @@ -35,7 +35,7 @@ class QgsAuthConfigSslServer; class CORE_EXPORT QgsAuthCertUtils { public: - /** Type of CA certificate source */ + //! Type of CA certificate source enum CaCertSource { SystemRoot = 0, @@ -44,7 +44,7 @@ class CORE_EXPORT QgsAuthCertUtils Connection = 3 }; - /** Type of certificate trust policy */ + //! Type of certificate trust policy enum CertTrustPolicy { DefaultTrust = 0, @@ -53,7 +53,7 @@ class CORE_EXPORT QgsAuthCertUtils NoPolicy = 3 }; - /** Type of certificate usage */ + //! Type of certificate usage enum CertUsageType { UndeterminedUsage = 0, @@ -69,7 +69,7 @@ class CORE_EXPORT QgsAuthCertUtils CRLSigningUsage }; - /** Type of certificate key group */ + //! Type of certificate key group enum ConstraintGroup { KeyUsage = 0, @@ -77,10 +77,10 @@ class CORE_EXPORT QgsAuthCertUtils }; - /** SSL Protocol name strings per enum */ + //! SSL Protocol name strings per enum static QString getSslProtocolName( QSsl::SslProtocol protocol ); - /** Map certificate sha1 to certificate as simple cache */ + //! Map certificate sha1 to certificate as simple cache static QMap mapDigestToCerts( const QList& certs ); /** Map certificates to their oraganization. @@ -97,10 +97,10 @@ class CORE_EXPORT QgsAuthCertUtils */ static QMap< QString, QList > sslConfigsGroupedByOrg( const QList& configs ); - /** Return list of concatenated certs from a PEM or DER formatted file */ + //! Return list of concatenated certs from a PEM or DER formatted file static QList certsFromFile( const QString &certspath ); - /** Return first cert from a PEM or DER formatted file */ + //! Return first cert from a PEM or DER formatted file static QSslCertificate certFromFile( const QString &certpath ); /** Return non-encrypted key from a PEM or DER formatted file @@ -112,7 +112,7 @@ class CORE_EXPORT QgsAuthCertUtils const QString &keypass = QString(), QString *algtype = nullptr ); - /** Return list of concatenated certs from a PEM Base64 text block */ + //! Return list of concatenated certs from a PEM Base64 text block static QList certsFromString( const QString &pemtext ); /** Return list of certificate, private key and algorithm (as PEM text) from file path components @@ -150,7 +150,7 @@ class CORE_EXPORT QgsAuthCertUtils */ static QString getCaSourceName( QgsAuthCertUtils::CaCertSource source , bool single = false ); - /** Get the general name via RFC 5280 resolution */ + //! Get the general name via RFC 5280 resolution static QString resolvedCertName( const QSslCertificate& cert, bool issuer = false ); /** Get combined distinguished name for certificate @@ -163,10 +163,10 @@ class CORE_EXPORT QgsAuthCertUtils const QCA::Certificate& acert = QCA::Certificate(), bool issuer = false ); - /** Get the general name for certificate trust */ + //! Get the general name for certificate trust static QString getCertTrustName( QgsAuthCertUtils::CertTrustPolicy trust ); - /** Get string with colon delimeters every 2 characters */ + //! Get string with colon delimeters every 2 characters static QString getColonDelimited( const QString& txt ); /** Get the sha1 hash for certificate @@ -210,25 +210,25 @@ class CORE_EXPORT QgsAuthCertUtils */ static QString certificateUsageTypeString( QgsAuthCertUtils::CertUsageType usagetype ); - /** Try to determine the certificates usage types */ + //! Try to determine the certificates usage types static QList certificateUsageTypes( const QSslCertificate& cert ); - /** Get whether a certificate is an Authority */ + //! Get whether a certificate is an Authority static bool certificateIsAuthority( const QSslCertificate& cert ); - /** Get whether a certificate can sign other certificates */ + //! Get whether a certificate can sign other certificates static bool certificateIsIssuer( const QSslCertificate& cert ); - /** Get whether a certificate is an Authority or can at least sign other certificates */ + //! Get whether a certificate is an Authority or can at least sign other certificates static bool certificateIsAuthorityOrIssuer( const QSslCertificate& cert ); - /** Get whether a certificate is probably used for a SSL server */ + //! Get whether a certificate is probably used for a SSL server static bool certificateIsSslServer( const QSslCertificate& cert ); - /** Get whether a certificate is probably used for a client identity */ + //! Get whether a certificate is probably used for a client identity static bool certificateIsSslClient( const QSslCertificate& cert ); - /** Get short strings describing an SSL error */ + //! Get short strings describing an SSL error static QString sslErrorEnumString( QSslError::SslError errenum ); /** Get short strings describing SSL errors. diff --git a/src/core/auth/qgsauthconfig.h b/src/core/auth/qgsauthconfig.h index 139c5d0e35a8..1d5161c38bee 100644 --- a/src/core/auth/qgsauthconfig.h +++ b/src/core/auth/qgsauthconfig.h @@ -44,10 +44,10 @@ class CORE_EXPORT QgsAuthMethodConfig */ QgsAuthMethodConfig( const QString& method = QString(), int version = 0 ); - /** Operator used to compare configs' equality */ + //! Operator used to compare configs' equality bool operator==( const QgsAuthMethodConfig& other ) const; - /** Operator used to compare configs' inequality */ + //! Operator used to compare configs' inequality bool operator!=( const QgsAuthMethodConfig& other ) const; /** @@ -55,25 +55,25 @@ class CORE_EXPORT QgsAuthMethodConfig * @note This is set by QgsAuthManager when the config is initially stored */ const QString id() const { return mId; } - /** Set auth config ID */ + //! Set auth config ID void setId( const QString& id ) { mId = id; } - /** Get name of configuration */ + //! Get name of configuration const QString name() const { return mName; } - /** Set name of configuration */ + //! Set name of configuration void setName( const QString& name ) { mName = name; } - /** A URI to auto-select a config when connecting to a resource */ + //! A URI to auto-select a config when connecting to a resource const QString uri() const { return mUri; } void setUri( const QString& uri ) { mUri = uri; } - /** Textual key of the associated authentication method */ + //! Textual key of the associated authentication method QString method() const { return mMethod; } void setMethod( const QString& method ) { mMethod = method; } - /** Get version of the configuration */ + //! Get version of the configuration int version() const { return mVersion; } - /** Set version of the configuration */ + //! Set version of the configuration void setVersion( int version ) { mVersion = version; } /** @@ -93,7 +93,7 @@ class CORE_EXPORT QgsAuthMethodConfig */ void loadConfigString( const QString& configstr ); - /** Get extended configuration, mapped to key/value pairs of QStrings */ + //! Get extended configuration, mapped to key/value pairs of QStrings QgsStringMap configMap() const { return mConfigMap; } /** * Set extended configuration map @@ -142,7 +142,7 @@ class CORE_EXPORT QgsAuthMethodConfig */ bool hasConfig( const QString &key ) const; - /** Clear all configs */ + //! Clear all configs void clearConfigMap() { mConfigMap.clear(); } /** @@ -213,28 +213,28 @@ class CORE_EXPORT QgsPkiBundle static const QgsPkiBundle fromPkcs12Paths( const QString &bundlepath, const QString &bundlepass = QString::null ); - /** Whether the bundle, either its certificate or private key, is null */ + //! Whether the bundle, either its certificate or private key, is null bool isNull() const; - /** Whether the bundle is valid */ + //! Whether the bundle is valid bool isValid() const; - /** The sha hash of the client certificate */ + //! The sha hash of the client certificate const QString certId() const; - /** Client certificate object */ + //! Client certificate object const QSslCertificate clientCert() const { return mCert; } - /** Set client certificate object */ + //! Set client certificate object void setClientCert( const QSslCertificate &cert ); - /** Private key object */ + //! Private key object const QSslKey clientKey() const { return mCertKey; } - /** Set private key object */ + //! Set private key object void setClientKey( const QSslKey &certkey ); - /** Chain of Certificate Authorities for client certificate */ + //! Chain of Certificate Authorities for client certificate const QList caChain() const { return mCaChain; } - /** Set chain of Certificate Authorities for client certificate */ + //! Set chain of Certificate Authorities for client certificate void setCaChain( const QList &cachain ) { mCaChain = cachain; } private: @@ -260,22 +260,22 @@ class CORE_EXPORT QgsPkiConfigBundle const QSslCertificate& cert, const QSslKey& certkey ); - /** Whether the bundle is valid */ + //! Whether the bundle is valid bool isValid(); - /** Authentication method configuration */ + //! Authentication method configuration const QgsAuthMethodConfig config() const { return mConfig; } - /** Set authentication method configuration */ + //! Set authentication method configuration void setConfig( const QgsAuthMethodConfig& config ) { mConfig = config; } - /** Client certificate object */ + //! Client certificate object const QSslCertificate clientCert() const { return mCert; } - /** Set client certificate object */ + //! Set client certificate object void setClientCert( const QSslCertificate& cert ) { mCert = cert; } - /** Private key object */ + //! Private key object const QSslKey clientCertKey() const { return mCertKey; } - /** Set private key object */ + //! Set private key object void setClientCertKey( const QSslKey& certkey ) { mCertKey = certkey; } private: @@ -291,36 +291,36 @@ class CORE_EXPORT QgsPkiConfigBundle class CORE_EXPORT QgsAuthConfigSslServer { public: - /** Construct a default SSL server configuration */ + //! Construct a default SSL server configuration QgsAuthConfigSslServer(); ~QgsAuthConfigSslServer() {} - /** Server certificate object */ + //! Server certificate object const QSslCertificate sslCertificate() const { return mSslCert; } - /** Set server certificate object */ + //! Set server certificate object void setSslCertificate( const QSslCertificate& cert ) { mSslCert = cert; } - /** Server host:port string */ + //! Server host:port string const QString sslHostPort() const { return mSslHostPort; } - /** Set server host:port string */ + //! Set server host:port string void setSslHostPort( const QString& hostport ) { mSslHostPort = hostport; } - /** SSL server protocol to use in connections */ + //! SSL server protocol to use in connections QSsl::SslProtocol sslProtocol() const { return mSslProtocol; } - /** Set SSL server protocol to use in connections */ + //! Set SSL server protocol to use in connections void setSslProtocol( QSsl::SslProtocol protocol ) { mSslProtocol = protocol; } - /** SSL server errors to ignore in connections */ + //! SSL server errors to ignore in connections const QList sslIgnoredErrors() const; - /** SSL server errors (as enum list) to ignore in connections */ + //! SSL server errors (as enum list) to ignore in connections const QList sslIgnoredErrorEnums() const { return mSslIgnoredErrors; } - /** Set SSL server errors (as enum list) to ignore in connections */ + //! Set SSL server errors (as enum list) to ignore in connections void setSslIgnoredErrorEnums( const QList& errors ) { mSslIgnoredErrors = errors; } - /** SSL client's peer verify mode to use in connections */ + //! SSL client's peer verify mode to use in connections QSslSocket::PeerVerifyMode sslPeerVerifyMode() const { return mSslPeerVerifyMode; } - /** Set SSL client's peer verify mode to use in connections */ + //! Set SSL client's peer verify mode to use in connections void setSslPeerVerifyMode( QSslSocket::PeerVerifyMode mode ) { mSslPeerVerifyMode = mode; } /** Number or SSL client's peer to verify in connections @@ -332,22 +332,22 @@ class CORE_EXPORT QgsAuthConfigSslServer */ void setSslPeerVerifyDepth( int depth ) { mSslPeerVerifyDepth = depth; } - /** Version of the configuration (used for future upgrading) */ + //! Version of the configuration (used for future upgrading) int version() const { return mVersion; } - /** Set version of the configuration (used for future upgrading) */ + //! Set version of the configuration (used for future upgrading) void setVersion( int version ) { mVersion = version; } - /** Qt version when the configuration was made (SSL protocols may differ) */ + //! Qt version when the configuration was made (SSL protocols may differ) int qtVersion() const { return mQtVersion; } - /** Set Qt version when the configuration was made (SSL protocols may differ) */ + //! Set Qt version when the configuration was made (SSL protocols may differ) void setQtVersion( int version ) { mQtVersion = version; } - /** Configuration as a concatenated string */ + //! Configuration as a concatenated string const QString configString() const; - /** Load concatenated string into configuration, e.g. from auth database */ + //! Load concatenated string into configuration, e.g. from auth database void loadConfigString( const QString& config = QString() ); - /** Whether configuration is null (missing components) */ + //! Whether configuration is null (missing components) bool isNull() const; private: diff --git a/src/core/auth/qgsauthcrypto.h b/src/core/auth/qgsauthcrypto.h index cbd2c678e50d..0625804054ce 100644 --- a/src/core/auth/qgsauthcrypto.h +++ b/src/core/auth/qgsauthcrypto.h @@ -29,22 +29,22 @@ class CORE_EXPORT QgsAuthCrypto { public: - /** Whether QCA has the qca-ossl plugin, which a base run-time requirement */ + //! Whether QCA has the qca-ossl plugin, which a base run-time requirement static bool isDisabled(); - /** Encrypt data using master password */ + //! Encrypt data using master password static const QString encrypt( const QString& pass, const QString& cipheriv, const QString& text ); - /** Decrypt data using master password */ + //! Decrypt data using master password static const QString decrypt( const QString& pass, const QString& cipheriv, const QString& text ); - /** Generate SHA256 hash for master password, with iterations and salt */ + //! Generate SHA256 hash for master password, with iterations and salt static void passwordKeyHash( const QString &pass, QString *salt, QString *hash, QString *cipheriv = nullptr ); - /** Verify existing master password hash to a re-generated one */ + //! Verify existing master password hash to a re-generated one static bool verifyPasswordKeyHash( const QString& pass, const QString& salt, const QString& hash, diff --git a/src/core/auth/qgsauthmanager.h b/src/core/auth/qgsauthmanager.h index fee03683487d..0d41dd43de72 100644 --- a/src/core/auth/qgsauthmanager.h +++ b/src/core/auth/qgsauthmanager.h @@ -57,7 +57,7 @@ class CORE_EXPORT QgsAuthManager : public QObject public: - /** Message log level (mirrors that of QgsMessageLog, so it can also output there) */ + //! Message log level (mirrors that of QgsMessageLog, so it can also output there) enum MessageLevel { INFO = 0, @@ -72,22 +72,22 @@ class CORE_EXPORT QgsAuthManager : public QObject ~QgsAuthManager(); - /** Set up the application instance of the authentication database connection */ + //! Set up the application instance of the authentication database connection QSqlDatabase authDbConnection() const; - /** Name of the authentication database table that stores configs */ + //! Name of the authentication database table that stores configs const QString authDbConfigTable() const { return smAuthConfigTable; } - /** Name of the authentication database table that stores server exceptions/configs */ + //! Name of the authentication database table that stores server exceptions/configs const QString authDbServersTable() const { return smAuthServersTable; } - /** Initialize QCA, prioritize qca-ossl plugin and optionally set up the authentication database */ + //! Initialize QCA, prioritize qca-ossl plugin and optionally set up the authentication database bool init( const QString& pluginPath = QString::null ); - /** Whether QCA has the qca-ossl plugin, which a base run-time requirement */ + //! Whether QCA has the qca-ossl plugin, which a base run-time requirement bool isDisabled() const; - /** Standard message for when QCA's qca-ossl plugin is missing and system is disabled */ + //! Standard message for when QCA's qca-ossl plugin is missing and system is disabled const QString disabledMessage() const; /** The standard authentication database file in ~/.qgis3/ or defined location @@ -114,10 +114,10 @@ class CORE_EXPORT QgsAuthManager : public QObject */ bool verifyMasterPassword( const QString &compare = QString::null ); - /** Whether master password has be input and verified, i.e. authentication database is accessible */ + //! Whether master password has be input and verified, i.e. authentication database is accessible bool masterPasswordIsSet() const; - /** Verify a password hash existing in authentication database */ + //! Verify a password hash existing in authentication database bool masterPasswordHashInDb() const; /** Clear supplied master password @@ -166,16 +166,16 @@ class CORE_EXPORT QgsAuthManager : public QObject */ void setScheduledAuthDbEraseRequestEmitted( bool emitted ) { mScheduledDbEraseRequestEmitted = emitted; } - /** Simple text tag describing authentication system for message logs */ + //! Simple text tag describing authentication system for message logs QString authManTag() const { return smAuthManTag; } - /** Instantiate and register existing C++ core authentication methods from plugins */ + //! Instantiate and register existing C++ core authentication methods from plugins bool registerCoreAuthMethods(); - /** Get mapping of authentication config ids and their base configs (not decrypted data) */ + //! Get mapping of authentication config ids and their base configs (not decrypted data) QgsAuthMethodConfigsMap availableAuthMethodConfigs( const QString &dataprovider = QString() ); - /** Sync the confg/authentication method cache with what is in database */ + //! Sync the confg/authentication method cache with what is in database void updateConfigAuthMethods(); /** @@ -221,7 +221,7 @@ class CORE_EXPORT QgsAuthManager : public QObject */ QgsAuthMethod::Expansions supportedAuthMethodExpansions( const QString &authcfg ); - /** Get a unique generated 7-character string to assign to as config id */ + //! Get a unique generated 7-character string to assign to as config id const QString uniqueConfigId() const; /** @@ -236,10 +236,10 @@ class CORE_EXPORT QgsAuthManager : public QObject */ bool hasConfigId( const QString &txt ) const; - /** Return regular expression for authcfg=.{7} key/value token for authentication ids */ + //! Return regular expression for authcfg=.{7} key/value token for authentication ids QString configIdRegex() const { return smAuthCfgRegex;} - /** Get list of authentication ids from database */ + //! Get list of authentication ids from database QStringList configIds() const; /** @@ -327,28 +327,28 @@ class CORE_EXPORT QgsAuthManager : public QObject ////////////////// Generic settings /////////////////////// - /** Store an authentication setting (stored as string via QVariant( value ).toString() ) */ + //! Store an authentication setting (stored as string via QVariant( value ).toString() ) bool storeAuthSetting( const QString& key, const QVariant& value, bool encrypt = false ); - /** Get an authentication setting (retrieved as string and returned as QVariant( QString )) */ + //! Get an authentication setting (retrieved as string and returned as QVariant( QString )) QVariant getAuthSetting( const QString& key, const QVariant& defaultValue = QVariant(), bool decrypt = false ); - /** Check if an authentication setting exists */ + //! Check if an authentication setting exists bool existsAuthSetting( const QString& key ); - /** Remove an authentication setting */ + //! Remove an authentication setting bool removeAuthSetting( const QString& key ); #ifndef QT_NO_OPENSSL ////////////////// Certificate calls /////////////////////// - /** Initialize various SSL authentication caches */ + //! Initialize various SSL authentication caches bool initSslCaches(); - /** Store a certificate identity */ + //! Store a certificate identity bool storeCertIdentity( const QSslCertificate& cert, const QSslKey& key ); - /** Get a certificate identity by id (sha hash) */ + //! Get a certificate identity by id (sha hash) const QSslCertificate getCertIdentity( const QString& id ); /** Get a certificate identity bundle by id (sha hash). @@ -356,38 +356,38 @@ class CORE_EXPORT QgsAuthManager : public QObject */ const QPair getCertIdentityBundle( const QString& id ); - /** Get a certificate identity bundle by id (sha hash) returned as PEM text */ + //! Get a certificate identity bundle by id (sha hash) returned as PEM text const QStringList getCertIdentityBundleToPem( const QString& id ); - /** Get certificate identities */ + //! Get certificate identities const QList getCertIdentities(); - /** Get list of certificate identity ids from database */ + //! Get list of certificate identity ids from database QStringList getCertIdentityIds() const; - /** Check if a certificate identity exists */ + //! Check if a certificate identity exists bool existsCertIdentity( const QString& id ); - /** Remove a certificate identity */ + //! Remove a certificate identity bool removeCertIdentity( const QString& id ); - /** Store an SSL certificate custom config */ + //! Store an SSL certificate custom config bool storeSslCertCustomConfig( const QgsAuthConfigSslServer& config ); - /** Get an SSL certificate custom config by id (sha hash) and host:port */ + //! Get an SSL certificate custom config by id (sha hash) and host:port const QgsAuthConfigSslServer getSslCertCustomConfig( const QString& id, const QString &hostport ); - /** Get an SSL certificate custom config by host:port */ + //! Get an SSL certificate custom config by host:port const QgsAuthConfigSslServer getSslCertCustomConfigByHost( const QString& hostport ); - /** Get SSL certificate custom configs */ + //! Get SSL certificate custom configs const QList getSslCertCustomConfigs(); - /** Check if SSL certificate custom config exists */ + //! Check if SSL certificate custom config exists bool existsSslCertCustomConfig( const QString& id, const QString &hostport ); - /** Remove an SSL certificate custom config */ + //! Remove an SSL certificate custom config bool removeSslCertCustomConfig( const QString& id, const QString &hostport ); /** Get ignored SSL error cache, keyed with cert/connection's sha:host:port. @@ -395,44 +395,44 @@ class CORE_EXPORT QgsAuthManager : public QObject */ QHash > getIgnoredSslErrorCache() { return mIgnoredSslErrorsCache; } - /** Utility function to dump the cache for debug purposes */ + //! Utility function to dump the cache for debug purposes void dumpIgnoredSslErrorsCache_(); - /** Update ignored SSL error cache with possible ignored SSL errors, using server config */ + //! Update ignored SSL error cache with possible ignored SSL errors, using server config bool updateIgnoredSslErrorsCacheFromConfig( const QgsAuthConfigSslServer &config ); - /** Update ignored SSL error cache with possible ignored SSL errors, using sha:host:port key */ + //! Update ignored SSL error cache with possible ignored SSL errors, using sha:host:port key bool updateIgnoredSslErrorsCache( const QString &shahostport, const QList &errors ); - /** Rebuild ignoredSSL error cache */ + //! Rebuild ignoredSSL error cache bool rebuildIgnoredSslErrorCache(); - /** Store multiple certificate authorities */ + //! Store multiple certificate authorities bool storeCertAuthorities( const QList& certs ); - /** Store a certificate authority */ + //! Store a certificate authority bool storeCertAuthority( const QSslCertificate& cert ); - /** Get a certificate authority by id (sha hash) */ + //! Get a certificate authority by id (sha hash) const QSslCertificate getCertAuthority( const QString& id ); - /** Check if a certificate authority exists */ + //! Check if a certificate authority exists bool existsCertAuthority( const QSslCertificate& cert ); - /** Remove a certificate authority */ + //! Remove a certificate authority bool removeCertAuthority( const QSslCertificate& cert ); - /** Get root system certificate authorities */ + //! Get root system certificate authorities const QList getSystemRootCAs(); - /** Get extra file-based certificate authorities */ + //! Get extra file-based certificate authorities const QList getExtraFileCAs(); - /** Get database-stored certificate authorities */ + //! Get database-stored certificate authorities const QList getDatabaseCAs(); - /** Get sha1-mapped database-stored certificate authorities */ + //! Get sha1-mapped database-stored certificate authorities const QMap getMappedDatabaseCAs(); /** Get all CA certs mapped to their sha1 from cache. @@ -443,10 +443,10 @@ class CORE_EXPORT QgsAuthManager : public QObject return mCaCertsCache; } - /** Rebuild certificate authority cache */ + //! Rebuild certificate authority cache bool rebuildCaCertsCache(); - /** Store user trust value for a certificate */ + //! Store user trust value for a certificate bool storeCertTrustPolicy( const QSslCertificate& cert, QgsAuthCertUtils::CertTrustPolicy policy ); /** Get a whether certificate is trusted by user @@ -454,45 +454,45 @@ class CORE_EXPORT QgsAuthManager : public QObject */ QgsAuthCertUtils::CertTrustPolicy getCertTrustPolicy( const QSslCertificate& cert ); - /** Remove a group certificate authorities */ + //! Remove a group certificate authorities bool removeCertTrustPolicies( const QList& certs ); - /** Remove a certificate authority */ + //! Remove a certificate authority bool removeCertTrustPolicy( const QSslCertificate& cert ); - /** Get trust policy for a particular certificate */ + //! Get trust policy for a particular certificate QgsAuthCertUtils::CertTrustPolicy getCertificateTrustPolicy( const QSslCertificate& cert ); - /** Set the default certificate trust policy perferred by user */ + //! Set the default certificate trust policy perferred by user bool setDefaultCertTrustPolicy( QgsAuthCertUtils::CertTrustPolicy policy ); - /** Get the default certificate trust policy perferred by user */ + //! Get the default certificate trust policy perferred by user QgsAuthCertUtils::CertTrustPolicy defaultCertTrustPolicy(); - /** Get cache of certificate sha1s, per trust policy */ + //! Get cache of certificate sha1s, per trust policy const QMap getCertTrustCache() { return mCertTrustCache; } - /** Rebuild certificate authority cache */ + //! Rebuild certificate authority cache bool rebuildCertTrustCache(); - /** Get list of all trusted CA certificates */ + //! Get list of all trusted CA certificates const QList getTrustedCaCerts( bool includeinvalid = false ); - /** Get list of all untrusted CA certificates */ + //! Get list of all untrusted CA certificates const QList getUntrustedCaCerts( QList trustedCAs = QList() ); - /** Rebuild trusted certificate authorities cache */ + //! Rebuild trusted certificate authorities cache bool rebuildTrustedCaCertsCache(); - /** Get cache of trusted certificate authorities, ready for network connections */ + //! Get cache of trusted certificate authorities, ready for network connections const QList getTrustedCaCertsCache() { return mTrustedCaCertsCache; } - /** Get concatenated string of all trusted CA certificates */ + //! Get concatenated string of all trusted CA certificates const QByteArray getTrustedCaCertsPemText(); #endif - /** Return pointer to mutex */ + //! Return pointer to mutex QMutex *mutex() { return mMutex; } signals: @@ -511,17 +511,17 @@ class CORE_EXPORT QgsAuthManager : public QObject */ void masterPasswordVerified( bool verified ) const; - /** Emitted when a user has indicated they may want to erase the authentication db. */ + //! Emitted when a user has indicated they may want to erase the authentication db. void authDatabaseEraseRequested() const; - /** Emitted when the authentication db is significantly changed, e.g. large record removal, erased, etc. */ + //! Emitted when the authentication db is significantly changed, e.g. large record removal, erased, etc. void authDatabaseChanged() const; public slots: - /** Clear all authentication configs from authentication method caches */ + //! Clear all authentication configs from authentication method caches void clearAllCachedConfigs(); - /** Clear an authentication config from its associated authentication method cache */ + //! Clear an authentication config from its associated authentication method cache void clearCachedConfig( const QString& authcfg ); private slots: diff --git a/src/core/auth/qgsauthmethod.h b/src/core/auth/qgsauthmethod.h index f40e592140bd..7178279c96e2 100644 --- a/src/core/auth/qgsauthmethod.h +++ b/src/core/auth/qgsauthmethod.h @@ -55,16 +55,16 @@ class CORE_EXPORT QgsAuthMethod : public QObject virtual ~QgsAuthMethod() {} - /** A non-translated short name representing the auth method */ + //! A non-translated short name representing the auth method virtual QString key() const = 0; - /** A non-translated short description representing the auth method for use in debug output and About dialog */ + //! A non-translated short description representing the auth method for use in debug output and About dialog virtual QString description() const = 0; - /** Translatable display version of the 'description()' */ + //! Translatable display version of the 'description()' virtual QString displayDescription() const = 0; - /** Increment this if method is significantly updated, allow updater code to be written for previously stored authcfg */ + //! Increment this if method is significantly updated, allow updater code to be written for previously stored authcfg int version() const { return mVersion; } /** Flags that represent the update points (where authentication configurations are expanded) @@ -149,15 +149,15 @@ class CORE_EXPORT QgsAuthMethod : public QObject , mVersion( 0 ) {} - /** Tag signifying that this is an authentcation method (e.g. for use as title in message log panel output) */ + //! Tag signifying that this is an authentcation method (e.g. for use as title in message log panel output) static QString authMethodTag() { return QObject::tr( "Authentication method" ); } - /** Set the version of the auth method (useful for future upgrading) */ + //! Set the version of the auth method (useful for future upgrading) void setVersion( int version ) { mVersion = version; } - /** Set the support expansions (points in providers where the authentication is injected) of the auth method */ + //! Set the support expansions (points in providers where the authentication is injected) of the auth method void setExpansions( QgsAuthMethod::Expansions expansions ) { mExpansions = expansions; } - /** Set list of data providers this auth method supports */ + //! Set list of data providers this auth method supports void setDataProviders( const QStringList& dataproviders ) { mDataProviders = dataproviders; } QgsAuthMethod::Expansions mExpansions; diff --git a/src/core/auth/qgsauthmethodregistry.h b/src/core/auth/qgsauthmethodregistry.h index cee62da27a4d..655d0c3b8047 100644 --- a/src/core/auth/qgsauthmethodregistry.h +++ b/src/core/auth/qgsauthmethodregistry.h @@ -41,22 +41,22 @@ class CORE_EXPORT QgsAuthMethodRegistry { public: - /** Means of accessing canonical single instance */ + //! Means of accessing canonical single instance static QgsAuthMethodRegistry* instance( const QString& pluginPath = QString::null ); - /** Virtual dectructor */ + //! Virtual dectructor virtual ~QgsAuthMethodRegistry(); - /** Return path for the library of the auth method */ + //! Return path for the library of the auth method QString library( const QString & authMethodKey ) const; - /** Return list of auth method plugins found */ + //! Return list of auth method plugins found QString pluginList( bool asHtml = false ) const; - /** Return library directory where plugins are found */ + //! Return library directory where plugins are found const QDir & libraryDirectory() const; - /** Set library directory where to search for plugins */ + //! Set library directory where to search for plugins void setLibraryDirectory( const QDir & path ); /** Create an instance of the auth method @@ -94,28 +94,28 @@ class CORE_EXPORT QgsAuthMethodRegistry const QString & functionName ); #endif - /** Return the library object associated with an auth method key */ + //! Return the library object associated with an auth method key QLibrary *authMethodLibrary( const QString & authMethodKey ) const; - /** Return list of available auth methods by their keys */ + //! Return list of available auth methods by their keys QStringList authMethodList() const; - /** Return metadata of the auth method or nullptr if not found */ + //! Return metadata of the auth method or nullptr if not found const QgsAuthMethodMetadata* authMethodMetadata( const QString& authMethodKey ) const; // void registerGuis( QWidget *widget ); - /** Type for auth method metadata associative container */ + //! Type for auth method metadata associative container typedef std::map AuthMethods; private: - /** Ctor private since instance() creates it */ + //! Ctor private since instance() creates it QgsAuthMethodRegistry( const QString& pluginPath ); - /** Associative container of auth method metadata handles */ + //! Associative container of auth method metadata handles AuthMethods mAuthMethods; - /** Directory in which auth method plugins are installed */ + //! Directory in which auth method plugins are installed QDir mLibraryDirectory; }; diff --git a/src/core/composer/qgsatlascomposition.h b/src/core/composer/qgsatlascomposition.h index 3f82382080c4..5d7568d44a26 100644 --- a/src/core/composer/qgsatlascomposition.h +++ b/src/core/composer/qgsatlascomposition.h @@ -189,10 +189,10 @@ class CORE_EXPORT QgsAtlasComposition : public QObject /** Begins the rendering. Returns true if successful, false if no matching atlas features found.*/ bool beginRender(); - /** Ends the rendering. Restores original extent */ + //! Ends the rendering. Restores original extent void endRender(); - /** Returns the number of features in the coverage layer */ + //! Returns the number of features in the coverage layer int numFeatures() const; /** Prepare the atlas map for the given feature. Sets the extent and context variables @@ -207,7 +207,7 @@ class CORE_EXPORT QgsAtlasComposition : public QObject */ bool prepareForFeature( const QgsFeature *feat ); - /** Returns the current filename. Must be called after prepareForFeature() */ + //! Returns the current filename. Must be called after prepareForFeature() QString currentFilename() const; void writeXml( QDomElement& elem, QDomDocument& doc ) const; @@ -251,10 +251,10 @@ class CORE_EXPORT QgsAtlasComposition : public QObject */ int currentFeatureNumber() const { return mCurrentFeatureNo; } - /** Recalculates the bounds of an atlas driven map */ + //! Recalculates the bounds of an atlas driven map void prepareMap( QgsComposerMap* map ); - /** Returns the current atlas geometry in the given projection system (default to the coverage layer's CRS) */ + //! Returns the current atlas geometry in the given projection system (default to the coverage layer's CRS) QgsGeometry currentGeometry( const QgsCoordinateReferenceSystem& projectedTo = QgsCoordinateReferenceSystem() ) const; public slots: @@ -270,25 +270,25 @@ class CORE_EXPORT QgsAtlasComposition : public QObject void firstFeature(); signals: - /** Emitted when one of the parameters changes */ + //! Emitted when one of the parameters changes void parameterChanged(); - /** Emitted when atlas is enabled or disabled */ + //! Emitted when atlas is enabled or disabled void toggled( bool ); - /** Is emitted when the atlas has an updated status bar message for the composer window*/ + //! Is emitted when the atlas has an updated status bar message for the composer window void statusMsgChanged( const QString& message ); - /** Is emitted when the coverage layer for an atlas changes*/ + //! Is emitted when the coverage layer for an atlas changes void coverageLayerChanged( QgsVectorLayer* layer ); - /** Is emitted when atlas rendering has begun*/ + //! Is emitted when atlas rendering has begun void renderBegun(); - /** Is emitted when atlas rendering has ended*/ + //! Is emitted when atlas rendering has ended void renderEnded(); - /** Is emitted when the current atlas feature changes*/ + //! Is emitted when the current atlas feature changes void featureChanged( QgsFeature* feature ); /** Is emitted when the number of features for the atlas changes. diff --git a/src/core/composer/qgscomposerarrow.h b/src/core/composer/qgscomposerarrow.h index a42ede46a089..6ee00119857d 100644 --- a/src/core/composer/qgscomposerarrow.h +++ b/src/core/composer/qgscomposerarrow.h @@ -54,10 +54,10 @@ class CORE_EXPORT QgsComposerArrow: public QgsComposerItem ~QgsComposerArrow(); - /** Return composer item type. */ + //! Return composer item type. virtual int type() const override { return ComposerArrow; } - /** \brief Reimplementation of QCanvasItem::paint - draw on canvas */ + //! \brief Reimplementation of QCanvasItem::paint - draw on canvas void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; /** Modifies position of start and endpoint and calls QgsComposerItem::setSceneRect @@ -210,17 +210,17 @@ class CORE_EXPORT QgsComposerArrow: public QgsComposerItem QPen mPen; QBrush mBrush; - /** Width of the arrow marker in mm. May be specified by the user. The height is automatically adapted*/ + //! Width of the arrow marker in mm. May be specified by the user. The height is automatically adapted double mArrowHeadWidth; - /** Height of the arrow marker in mm. Is calculated from arrow marker width and apsect ratio of svg*/ + //! Height of the arrow marker in mm. Is calculated from arrow marker width and apsect ratio of svg double mStartArrowHeadHeight; double mStopArrowHeadHeight; - /** Path to the start marker file*/ + //! Path to the start marker file QString mStartMarkerFile; - /** Path to the end marker file*/ + //! Path to the end marker file QString mEndMarkerFile; - /** Default marker, no marker or svg marker*/ + //! Default marker, no marker or svg marker MarkerMode mMarkerMode; double mArrowHeadOutlineWidth; @@ -237,13 +237,13 @@ class CORE_EXPORT QgsComposerArrow: public QgsComposerItem * Needs to be called whenever the arrow width/height, the outline with or the endpoints are changed */ void adaptItemSceneRect(); - /** Computes the margin around the line necessary to include the markers */ + //! Computes the margin around the line necessary to include the markers double computeMarkerMargin() const; - /** Draws the default marker at the line end*/ + //! Draws the default marker at the line end void drawHardcodedMarker( QPainter* p, MarkerType type ); - /** Draws a user-defined marker (must be an svg file)*/ + //! Draws a user-defined marker (must be an svg file) void drawSVGMarker( QPainter* p, MarkerType type, const QString& markerPath ); - /** Apply default graphics settings*/ + //! Apply default graphics settings void init(); /** Creates the default line symbol * @note added in QGIS 2.5 diff --git a/src/core/composer/qgscomposerattributetablemodelv2.h b/src/core/composer/qgscomposerattributetablemodelv2.h index 75004d809f9b..f1b6a648710d 100644 --- a/src/core/composer/qgscomposerattributetablemodelv2.h +++ b/src/core/composer/qgscomposerattributetablemodelv2.h @@ -39,8 +39,8 @@ class CORE_EXPORT QgsComposerAttributeTableColumnModelV2: public QAbstractTableM */ enum ShiftDirection { - ShiftUp, /*!< shift the row/column up */ - ShiftDown /*!< shift the row/column down */ + ShiftUp, //!< Shift the row/column up + ShiftDown //!< Shift the row/column down }; /** Constructor for QgsComposerAttributeTableColumnModel. @@ -139,8 +139,8 @@ class CORE_EXPORT QgsComposerTableSortColumnsProxyModelV2: public QSortFilterPro */ enum ColumnFilterType { - ShowSortedColumns, /*!< show only sorted columns */ - ShowUnsortedColumns/*!< show only unsorted columns */ + ShowSortedColumns, //!< Show only sorted columns + ShowUnsortedColumns//!< Show only unsorted columns }; /** Constructor for QgsComposerTableSortColumnsProxyModel. diff --git a/src/core/composer/qgscomposerattributetablev2.h b/src/core/composer/qgscomposerattributetablev2.h index f975713d743d..fde6a128b340 100644 --- a/src/core/composer/qgscomposerattributetablev2.h +++ b/src/core/composer/qgscomposerattributetablev2.h @@ -61,9 +61,9 @@ class CORE_EXPORT QgsComposerAttributeTableV2: public QgsComposerTableV2 */ enum ContentSource { - LayerAttributes = 0, /*!< table shows attributes from features in a vector layer */ - AtlasFeature, /*!< table shows attributes from the current atlas feature */ - RelationChildren /*!< table shows attributes from related child features */ + LayerAttributes = 0, //!< Table shows attributes from features in a vector layer + AtlasFeature, //!< Table shows attributes from the current atlas feature + RelationChildren //!< Table shows attributes from related child features }; QgsComposerAttributeTableV2( QgsComposition* composition, bool createUndoCommands ); @@ -300,33 +300,33 @@ class CORE_EXPORT QgsComposerAttributeTableV2: public QgsComposerTableV2 private: - /** Attribute source*/ + //! Attribute source ContentSource mSource; - /** Associated vector layer*/ + //! Associated vector layer QgsVectorLayer* mVectorLayer; - /** Relation id, if in relation children mode*/ + //! Relation id, if in relation children mode QString mRelationId; - /** Current vector layer, if in atlas feature mode*/ + //! Current vector layer, if in atlas feature mode QgsVectorLayer* mCurrentAtlasLayer; - /** Associated composer map (used to display the visible features)*/ + //! Associated composer map (used to display the visible features) const QgsComposerMap* mComposerMap; - /** Maximum number of features that is displayed*/ + //! Maximum number of features that is displayed int mMaximumNumberOfFeatures; - /** True if only unique rows should be shown*/ + //! True if only unique rows should be shown bool mShowUniqueRowsOnly; - /** Shows only the features that are visible in the associated composer map (true by default)*/ + //! Shows only the features that are visible in the associated composer map (true by default) bool mShowOnlyVisibleFeatures; - /** Shows only the features that intersect the current atlas feature*/ + //! Shows only the features that intersect the current atlas feature bool mFilterToAtlasIntersection; - /** True if feature filtering enabled*/ + //! True if feature filtering enabled bool mFilterFeatures; - /** Feature filter expression*/ + //! Feature filter expression QString mFeatureFilter; QString mWrapString; @@ -348,7 +348,7 @@ class CORE_EXPORT QgsComposerAttributeTableV2: public QgsComposerTableV2 QVariant replaceWrapChar( const QVariant &variant ) const; private slots: - /** Checks if this vector layer will be removed (and sets mVectorLayer to 0 if yes) */ + //! Checks if this vector layer will be removed (and sets mVectorLayer to 0 if yes) void removeLayer( const QString& layerId ); void atlasLayerChanged( QgsVectorLayer* layer ); diff --git a/src/core/composer/qgscomposereffect.h b/src/core/composer/qgscomposereffect.h index 7b8b1fdd8fa9..d6069a6d43dd 100644 --- a/src/core/composer/qgscomposereffect.h +++ b/src/core/composer/qgscomposereffect.h @@ -35,7 +35,7 @@ class CORE_EXPORT QgsComposerEffect : public QGraphicsEffect void setCompositionMode( QPainter::CompositionMode compositionMode ); protected: - /** Called whenever source needs to be drawn */ + //! Called whenever source needs to be drawn virtual void draw( QPainter *painter ) override; private: diff --git a/src/core/composer/qgscomposerframe.h b/src/core/composer/qgscomposerframe.h index 330b6d0a0e05..323565a59f5c 100644 --- a/src/core/composer/qgscomposerframe.h +++ b/src/core/composer/qgscomposerframe.h @@ -108,9 +108,9 @@ class CORE_EXPORT QgsComposerFrame: public QgsComposerItem QgsComposerMultiFrame* mMultiFrame; QRectF mSection; - /** If true, composition will not export page if this frame is empty*/ + //! If true, composition will not export page if this frame is empty bool mHidePageIfEmpty; - /** If true, background and outside frame will not be drawn if frame is empty*/ + //! If true, background and outside frame will not be drawn if frame is empty bool mHideBackgroundIfEmpty; }; diff --git a/src/core/composer/qgscomposerhtml.h b/src/core/composer/qgscomposerhtml.h index f630c267faab..d083c6192f7a 100644 --- a/src/core/composer/qgscomposerhtml.h +++ b/src/core/composer/qgscomposerhtml.h @@ -38,8 +38,8 @@ class CORE_EXPORT QgsComposerHtml: public QgsComposerMultiFrame */ enum ContentMode { - Url, /*!< Using this mode item fetches its content via a url*/ - ManualHtml /*!< HTML content is manually set for the item*/ + Url, //!< Using this mode item fetches its content via a url + ManualHtml //!< HTML content is manually set for the item }; QgsComposerHtml( QgsComposition* c, bool createUndoCommands ); @@ -219,7 +219,7 @@ class CORE_EXPORT QgsComposerHtml: public QgsComposerMultiFrame */ void loadHtml( const bool useCache = false, const QgsExpressionContext* context = nullptr ); - /** Recalculates the frame sizes for the current viewport dimensions*/ + //! Recalculates the frame sizes for the current viewport dimensions void recalculateFrameSizes() override; void refreshExpressionContext(); @@ -264,10 +264,10 @@ class CORE_EXPORT QgsComposerHtml: public QgsComposerMultiFrame //fetches html content from a url and returns it as a string QString fetchHtml( const QUrl& url ); - /** Sets the current feature, the current layer and a list of local variable substitutions for evaluating expressions */ + //! Sets the current feature, the current layer and a list of local variable substitutions for evaluating expressions void setExpressionContext( const QgsFeature& feature, QgsVectorLayer* layer ); - /** Calculates the max width of frames in the html multiframe*/ + //! Calculates the max width of frames in the html multiframe double maxFrameWidth() const; }; diff --git a/src/core/composer/qgscomposeritem.h b/src/core/composer/qgscomposeritem.h index 934f84de0540..6a41e3be4fa9 100644 --- a/src/core/composer/qgscomposeritem.h +++ b/src/core/composer/qgscomposeritem.h @@ -64,7 +64,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec ComposerFrame }; - /** Describes the action (move or resize in different directon) to be done during mouse move*/ + //! Describes the action (move or resize in different directon) to be done during mouse move enum MouseMoveAction { MoveItem, @@ -98,10 +98,10 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec */ enum ZoomMode { - Zoom = 0, /*!< Zoom to center of content */ - ZoomRecenter, /*!< Zoom and recenter content to point */ - ZoomToPoint, /*!< Zoom while maintaining relative position of point */ - NoZoom /*!< No zoom */ + Zoom = 0, //!< Zoom to center of content + ZoomRecenter, //!< Zoom and recenter content to point + ZoomToPoint, //!< Zoom while maintaining relative position of point + NoZoom //!< No zoom }; /** Constructor @@ -118,7 +118,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec QgsComposerItem( qreal x, qreal y, qreal width, qreal height, QgsComposition* composition, bool manageZValue = true ); virtual ~QgsComposerItem(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerItem; } /** Returns whether this item has been removed from the composition. Items removed @@ -139,13 +139,13 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec */ void setIsRemoved( const bool removed ) { mRemovedFromComposition = removed; } - /** \brief Set selected, selected item should be highlighted */ + //! \brief Set selected, selected item should be highlighted virtual void setSelected( bool s ); - /** \brief Is selected */ + //! \brief Is selected virtual bool selected() const { return QGraphicsRectItem::isSelected(); } - /** Moves item in canvas coordinates*/ + //! Moves item in canvas coordinates void move( double dx, double dy ); /** Move Content of item. Does nothing per default (but implemented in composer map) @@ -216,10 +216,10 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec corresponds to 1 scene size unit*/ virtual void setSceneRect( const QRectF& rectangle ); - /** Writes parameter that are not subclass specific in document. Usually called from writeXml methods of subclasses*/ + //! Writes parameter that are not subclass specific in document. Usually called from writeXml methods of subclasses bool _writeXml( QDomElement& itemElem, QDomDocument& doc ) const; - /** Reads parameter that are not subclass specific in document. Usually called from readXml methods of subclasses*/ + //! Reads parameter that are not subclass specific in document. Usually called from readXml methods of subclasses bool _readXml( const QDomElement& itemElem, const QDomDocument& doc ); /** Whether this item has a frame or not. @@ -389,7 +389,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec */ void setEffectsEnabled( const bool effectsEnabled ); - /** Composite operations for item groups do nothing per default*/ + //! Composite operations for item groups do nothing per default virtual void addItem( QgsComposerItem* item ) { Q_UNUSED( item ); } virtual void removeItems() {} @@ -401,7 +401,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec void beginCommand( const QString& commandText, QgsComposerMergeCommand::Context c = QgsComposerMergeCommand::Unknown ); virtual void endItemCommand() { endCommand(); } - /** Finish current command and push it onto the undo stack */ + //! Finish current command and push it onto the undo stack void endCommand(); void cancelCommand(); @@ -430,7 +430,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec */ double itemRotation( const QgsComposerObject::PropertyValueType valueType = QgsComposerObject::EvaluatedValue ) const; - /** Updates item, with the possibility to do custom update for subclasses*/ + //! Updates item, with the possibility to do custom update for subclasses virtual void updateItem() { QGraphicsRectItem::update(); } /** Get item's id (which is not necessarly unique) @@ -546,52 +546,52 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec virtual void refreshDataDefinedProperty( const QgsComposerObject::DataDefinedProperty property = QgsComposerObject::AllProperties, const QgsExpressionContext* context = nullptr ) override; protected: - /** True if item has been removed from the composition*/ + //! True if item has been removed from the composition bool mRemovedFromComposition; QgsComposerItem::MouseMoveAction mCurrentMouseMoveAction; - /** Start point of the last mouse move action (in scene coordinates)*/ + //! Start point of the last mouse move action (in scene coordinates) QPointF mMouseMoveStartPos; - /** Position of the last mouse move event (in scene coordinates)*/ + //! Position of the last mouse move event (in scene coordinates) QPointF mLastMouseEventPos; - /** Rectangle used during move and resize actions*/ + //! Rectangle used during move and resize actions QGraphicsRectItem* mBoundingResizeRectangle; QGraphicsLineItem* mHAlignSnapItem; QGraphicsLineItem* mVAlignSnapItem; - /** True if item fram needs to be painted*/ + //! True if item fram needs to be painted bool mFrame; - /** True if item background needs to be painted*/ + //! True if item background needs to be painted bool mBackground; - /** Background color*/ + //! Background color QColor mBackgroundColor; - /** Frame join style*/ + //! Frame join style Qt::PenJoinStyle mFrameJoinStyle; /** True if item position and size cannot be changed with mouse move */ bool mItemPositionLocked; - /** Backup to restore item appearance if no view scale factor is available*/ + //! Backup to restore item appearance if no view scale factor is available mutable double mLastValidViewScaleFactor; - /** Item rotation in degrees, clockwise*/ + //! Item rotation in degrees, clockwise double mItemRotation; /** Temporary evaluated item rotation in degrees, clockwise. Data defined rotation may mean * this value differs from mItemRotation. */ double mEvaluatedItemRotation; - /** Composition blend mode for item*/ + //! Composition blend mode for item QPainter::CompositionMode mBlendMode; bool mEffectsEnabled; QgsComposerEffect *mEffect; - /** Item transparency*/ + //! Item transparency int mTransparency; - /** Whether item should be excluded in exports*/ + //! Whether item should be excluded in exports bool mExcludeFromExports; /** Temporary evaluated item exclusion. Data defined properties may mean @@ -599,10 +599,10 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec */ bool mEvaluatedExcludeFromExports; - /** The item's position mode */ + //! The item's position mode ItemPositionMode mLastUsedPositionMode; - /** Whether or not this item is part of a group*/ + //! Whether or not this item is part of a group bool mIsGroupMember; /** The layer that needs to be exported @@ -616,10 +616,10 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec */ virtual void drawSelectionBoxes( QPainter* p ); - /** Draw black frame around item*/ + //! Draw black frame around item virtual void drawFrame( QPainter* p ); - /** Draw background*/ + //! Draw background virtual void drawBackground( QPainter* p ); /** Returns the current (zoom level dependent) tolerance to decide if mouse position is close enough to the @@ -633,10 +633,10 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec //some utility functions - /** Return horizontal align snap item. Creates a new graphics line if 0*/ + //! Return horizontal align snap item. Creates a new graphics line if 0 QGraphicsLineItem* hAlignSnapItem(); void deleteHAlignSnapItem(); - /** Return vertical align snap item. Creates a new graphics line if 0*/ + //! Return vertical align snap item. Creates a new graphics line if 0 QGraphicsLineItem* vAlignSnapItem(); void deleteVAlignSnapItem(); void deleteAlignItems(); @@ -661,9 +661,9 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec bool shouldDrawItem() const; signals: - /** Is emitted on item rotation change*/ + //! Is emitted on item rotation change void itemRotationChanged( double newRotation ); - /** Emitted if the rectangle changes*/ + //! Emitted if the rectangle changes void sizeChanged(); /** Emitted if the item's frame style changes * @note: this function was introduced in version 2.2 diff --git a/src/core/composer/qgscomposeritemcommand.h b/src/core/composer/qgscomposeritemcommand.h index 711e33b8c569..c0675fd4188f 100644 --- a/src/core/composer/qgscomposeritemcommand.h +++ b/src/core/composer/qgscomposeritemcommand.h @@ -33,20 +33,20 @@ class CORE_EXPORT QgsComposerItemCommand: public QUndoCommand QgsComposerItemCommand( QgsComposerItem* item, const QString& text, QUndoCommand* parent = nullptr ); virtual ~QgsComposerItemCommand(); - /** Reverses the command*/ + //! Reverses the command void undo() override; - /** Replays the command*/ + //! Replays the command void redo() override; - /** Saves current item state as previous state*/ + //! Saves current item state as previous state void savePreviousState(); - /** Saves current item state as after state*/ + //! Saves current item state as after state void saveAfterState(); QDomDocument previousState() const { return mPreviousState.cloneNode().toDocument(); } QDomDocument afterState() const { return mAfterState.cloneNode().toDocument(); } - /** Returns true if previous state and after state are valid and different*/ + //! Returns true if previous state and after state are valid and different bool containsChange() const; /** Returns the target item the command applies to. @@ -55,19 +55,19 @@ class CORE_EXPORT QgsComposerItemCommand: public QUndoCommand QgsComposerItem *item() const; protected: - /** Target item of the command*/ + //! Target item of the command QgsComposerItem* mItem; - /** XML that saves the state before executing the command*/ + //! XML that saves the state before executing the command QDomDocument mPreviousState; - /** XML containing the state after executing the command*/ + //! XML containing the state after executing the command QDomDocument mAfterState; - /** Parameters for frame items*/ - /** Parent multiframe*/ + //! Parameters for frame items + //! Parent multiframe QgsComposerMultiFrame* mMultiFrame; int mFrameNumber; - /** Flag to prevent the first redo() if the command is pushed to the undo stack*/ + //! Flag to prevent the first redo() if the command is pushed to the undo stack bool mFirstRun; void saveState( QDomDocument& stateDoc ) const; diff --git a/src/core/composer/qgscomposeritemgroup.h b/src/core/composer/qgscomposeritemgroup.h index f89312edc759..50b3a2f3cee5 100644 --- a/src/core/composer/qgscomposeritemgroup.h +++ b/src/core/composer/qgscomposeritemgroup.h @@ -30,15 +30,15 @@ class CORE_EXPORT QgsComposerItemGroup: public QgsComposerItem QgsComposerItemGroup( QgsComposition* c ); ~QgsComposerItemGroup(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerItemGroup; } /** Adds an item to the group. All the group members are deleted if the group is deleted*/ void addItem( QgsComposerItem* item ) override; - /** Removes the items but does not delete them*/ + //! Removes the items but does not delete them void removeItems() override; - /** Draw outline and ev. selection handles*/ + //! Draw outline and ev. selection handles void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; /** Sets this items bound in scene coordinates such that 1 item size units corresponds to 1 scene size unit*/ diff --git a/src/core/composer/qgscomposerlabel.h b/src/core/composer/qgscomposerlabel.h index 66c18c68ef2c..01717869cb1f 100644 --- a/src/core/composer/qgscomposerlabel.h +++ b/src/core/composer/qgscomposerlabel.h @@ -35,13 +35,13 @@ class CORE_EXPORT QgsComposerLabel: public QgsComposerItem QgsComposerLabel( QgsComposition *composition ); ~QgsComposerLabel(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerLabel; } - /** \brief Reimplementation of QCanvasItem::paint*/ + //! \brief Reimplementation of QCanvasItem::paint void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; - /** Resizes the widget such that the text fits to the item. Keeps top left point*/ + //! Resizes the widget such that the text fits to the item. Keeps top left point void adjustSizeToText(); QString text() { return mText; } @@ -50,7 +50,7 @@ class CORE_EXPORT QgsComposerLabel: public QgsComposerItem int htmlState() { return mHtmlState; } void setHtmlState( int state ); - /** Returns the text as it appears on screen (with replaced data field) */ + //! Returns the text as it appears on screen (with replaced data field) QString displayText() const; QFont font() const; @@ -116,9 +116,9 @@ class CORE_EXPORT QgsComposerLabel: public QgsComposerItem */ void setMarginY( const double margin ); - /** Sets text color */ + //! Sets text color void setFontColor( const QColor& c ) { mFontColor = c; } - /** Get font color */ + //! Get font color QColor fontColor() const { return mFontColor; } /** Stores state in Dom element @@ -166,18 +166,18 @@ class CORE_EXPORT QgsComposerLabel: public QgsComposerItem double htmlUnitsToMM(); //calculate scale factor bool mHtmlLoaded; - /** Helper function to calculate x/y shift for adjustSizeToText() depending on rotation, current size and alignment*/ + //! Helper function to calculate x/y shift for adjustSizeToText() depending on rotation, current size and alignment void itemShiftAdjustSize( double newWidth, double newHeight, double& xShift, double& yShift ) const; - /** Called when the content is changed to handle HTML loading */ + //! Called when the content is changed to handle HTML loading void contentChanged(); // Font QFont mFont; - /** Horizontal margin between contents and frame (in mm)*/ + //! Horizontal margin between contents and frame (in mm) double mMarginX; - /** Vertical margin between contents and frame (in mm)*/ + //! Vertical margin between contents and frame (in mm) double mMarginY; // Font color @@ -189,7 +189,7 @@ class CORE_EXPORT QgsComposerLabel: public QgsComposerItem // Vertical Alignment Qt::AlignmentFlag mVAlignment; - /** Replaces replace '$CURRENT_DATE<(FORMAT)>' with the current date (e.g. $CURRENT_DATE(d 'June' yyyy)*/ + //! Replaces replace '$CURRENT_DATE<(FORMAT)>' with the current date (e.g. $CURRENT_DATE(d 'June' yyyy) void replaceDateText( QString& text ) const; //! Creates an encoded stylesheet url using the current font and label appearance settings diff --git a/src/core/composer/qgscomposerlegend.h b/src/core/composer/qgscomposerlegend.h index 3e7a749eb7ff..98ce51401591 100644 --- a/src/core/composer/qgscomposerlegend.h +++ b/src/core/composer/qgscomposerlegend.h @@ -60,16 +60,16 @@ class CORE_EXPORT QgsComposerLegend : public QgsComposerItem QgsComposerLegend( QgsComposition* composition ); ~QgsComposerLegend(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerLegend; } - /** \brief Reimplementation of QCanvasItem::paint*/ + //! \brief Reimplementation of QCanvasItem::paint void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; - /** Paints the legend and calculates its size. If painter is 0, only size is calculated*/ + //! Paints the legend and calculates its size. If painter is 0, only size is calculated QSizeF paintAndDetermineSize( QPainter* painter ); - /** Sets item box to the whole content*/ + //! Sets item box to the whole content void adjustBoxSize(); /** Sets whether the legend should automatically resize to fit its contents. @@ -135,17 +135,17 @@ class CORE_EXPORT QgsComposerLegend : public QgsComposerItem */ void setTitleAlignment( Qt::AlignmentFlag alignment ); - /** Returns reference to modifiable style */ + //! Returns reference to modifiable style QgsComposerLegendStyle & rstyle( QgsComposerLegendStyle::Style s ); - /** Returns style */ + //! Returns style QgsComposerLegendStyle style( QgsComposerLegendStyle::Style s ) const; void setStyle( QgsComposerLegendStyle::Style s, const QgsComposerLegendStyle& style ); QFont styleFont( QgsComposerLegendStyle::Style s ) const; - /** Set style font */ + //! Set style font void setStyleFont( QgsComposerLegendStyle::Style s, const QFont& f ); - /** Set style margin*/ + //! Set style margin void setStyleMargin( QgsComposerLegendStyle::Style s, double margin ); void setStyleMargin( QgsComposerLegendStyle::Style s, QgsComposerLegendStyle::Side side, double margin ); @@ -240,7 +240,7 @@ class CORE_EXPORT QgsComposerLegend : public QgsComposerItem void setComposerMap( const QgsComposerMap* map ); const QgsComposerMap* composerMap() const { return mComposerMap;} - /** Updates the model and all legend entries*/ + //! Updates the model and all legend entries void updateLegend(); /** Stores state in Dom node @@ -259,9 +259,9 @@ class CORE_EXPORT QgsComposerLegend : public QgsComposerItem virtual QString displayName() const override; public slots: - /** Data changed*/ + //! Data changed void synchronizeWithModel(); - /** Sets mCompositionMap to 0 if the map is deleted*/ + //! Sets mCompositionMap to 0 if the map is deleted void invalidateCurrentMap(); private slots: diff --git a/src/core/composer/qgscomposerlegenditem.h b/src/core/composer/qgscomposerlegenditem.h index 99d65376d40a..ff74c0fdfeab 100644 --- a/src/core/composer/qgscomposerlegenditem.h +++ b/src/core/composer/qgscomposerlegenditem.h @@ -88,7 +88,7 @@ class CORE_EXPORT QgsComposerSymbolItem: public QgsComposerLegendItem virtual void writeXml( QDomElement& elem, QDomDocument& doc ) const override; virtual void readXml( const QDomElement& itemElem, bool xServerAvailable = true ) override; - /** Set symbol (takes ownership)*/ + //! Set symbol (takes ownership) void setSymbol( QgsSymbol* s ); QgsSymbol* symbol() {return mSymbol;} diff --git a/src/core/composer/qgscomposerlegendstyle.h b/src/core/composer/qgscomposerlegendstyle.h index 99cb4f77d190..1e963bcb521e 100644 --- a/src/core/composer/qgscomposerlegendstyle.h +++ b/src/core/composer/qgscomposerlegendstyle.h @@ -63,13 +63,13 @@ class CORE_EXPORT QgsComposerLegendStyle void readXml( const QDomElement& elem, const QDomDocument& doc ); - /** Get name for style, used in project file */ + //! Get name for style, used in project file static QString styleName( Style s ); - /** Get style from name, used in project file */ + //! Get style from name, used in project file static Style styleFromName( const QString& styleName ); - /** Get style label, translated, used in UI */ + //! Get style label, translated, used in UI static QString styleLabel( Style s ); private: diff --git a/src/core/composer/qgscomposermap.h b/src/core/composer/qgscomposermap.h index a197d47939aa..6a8476323884 100644 --- a/src/core/composer/qgscomposermap.h +++ b/src/core/composer/qgscomposermap.h @@ -48,16 +48,16 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem Q_OBJECT public: - /** Constructor. */ + //! Constructor. QgsComposerMap( QgsComposition *composition, int x, int y, int width, int height ); - /** Constructor. Settings are read from project. */ + //! Constructor. Settings are read from project. QgsComposerMap( QgsComposition *composition ); virtual ~QgsComposerMap(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerMap; } - /** \brief Preview style */ + //! \brief Preview style enum PreviewMode { Cache = 0, // Use raster cache @@ -69,7 +69,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem */ enum AtlasScalingMode { - Fixed, /*!< The current scale of the map is used for each feature of the atlas */ + Fixed, //!< The current scale of the map is used for each feature of the atlas Predefined, /*!< A scale is chosen from the predefined scales. The smallest scale from the list of scales where the atlas feature is fully visible is chosen. @see QgsAtlasComposition::setPredefinedScales. @@ -89,23 +89,23 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem */ void draw( QPainter *painter, const QgsRectangle& extent, QSizeF size, double dpi, double* forceWidthScale = nullptr ); - /** \brief Reimplementation of QCanvasItem::paint - draw on canvas */ + //! \brief Reimplementation of QCanvasItem::paint - draw on canvas void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; - /** \brief Create cache image */ + //! \brief Create cache image void cache(); /** Return map settings that would be used for drawing of the map * @note added in 2.6 */ QgsMapSettings mapSettings( const QgsRectangle& extent, QSizeF size, int dpi ) const; - /** \brief Get identification number*/ + //! \brief Get identification number int id() const {return mId;} - /** True if a draw is already in progress*/ + //! True if a draw is already in progress bool isDrawing() const {return mDrawing;} - /** Resizes an item in x- and y direction (canvas coordinates)*/ + //! Resizes an item in x- and y direction (canvas coordinates) void resize( double dx, double dy ); /** Move content of map @@ -122,13 +122,13 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem */ virtual void zoomContent( const double factor, const QPointF point, const ZoomMode mode = QgsComposerItem::Zoom ) override; - /** Sets new scene rectangle bounds and recalculates hight and extent*/ + //! Sets new scene rectangle bounds and recalculates hight and extent void setSceneRect( const QRectF& rectangle ) override; - /** \brief Scale */ + //! \brief Scale double scale() const; - /** Sets new scale and changes only mExtent*/ + //! Sets new scale and changes only mExtent void setNewScale( double scaleDenominator, bool forceUpdate = true ); /** Sets new extent for the map. This method may change the width or height of the map @@ -168,28 +168,28 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem PreviewMode previewMode() const {return mPreviewMode;} void setPreviewMode( PreviewMode m ); - /** Getter for flag that determines if the stored layer set should be used or the current layer set of the qgis mapcanvas */ + //! Getter for flag that determines if the stored layer set should be used or the current layer set of the qgis mapcanvas bool keepLayerSet() const {return mKeepLayerSet;} - /** Setter for flag that determines if the stored layer set should be used or the current layer set of the qgis mapcanvas */ + //! Setter for flag that determines if the stored layer set should be used or the current layer set of the qgis mapcanvas void setKeepLayerSet( bool enabled ) {mKeepLayerSet = enabled;} - /** Getter for stored layer set that is used if mKeepLayerSet is true */ + //! Getter for stored layer set that is used if mKeepLayerSet is true QStringList layerSet() const {return mLayerSet;} - /** Setter for stored layer set that is used if mKeepLayerSet is true */ + //! Setter for stored layer set that is used if mKeepLayerSet is true void setLayerSet( const QStringList& layerSet ) {mLayerSet = layerSet;} - /** Stores the current layer set of the qgis mapcanvas in mLayerSet*/ + //! Stores the current layer set of the qgis mapcanvas in mLayerSet void storeCurrentLayerSet(); - /** Getter for flag that determines if current styles of layers should be overridden by previously stored styles. @note added in 2.8 */ + //! Getter for flag that determines if current styles of layers should be overridden by previously stored styles. @note added in 2.8 bool keepLayerStyles() const { return mKeepLayerStyles; } - /** Setter for flag that determines if current styles of layers should be overridden by previously stored styles. @note added in 2.8 */ + //! Setter for flag that determines if current styles of layers should be overridden by previously stored styles. @note added in 2.8 void setKeepLayerStyles( bool enabled ) { mKeepLayerStyles = enabled; } - /** Getter for stored overrides of styles for layers. @note added in 2.8 */ + //! Getter for stored overrides of styles for layers. @note added in 2.8 QMap layerStyleOverrides() const { return mLayerStyleOverrides; } - /** Setter for stored overrides of styles for layers. @note added in 2.8 */ + //! Setter for stored overrides of styles for layers. @note added in 2.8 void setLayerStyleOverrides( const QMap& overrides ); - /** Stores the current layer styles into style overrides. @note added in 2.8 */ + //! Stores the current layer styles into style overrides. @note added in 2.8 void storeCurrentLayerStyles(); /** Whether the map should follow a map theme. If true, the layers and layer styles @@ -218,13 +218,13 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem QgsRectangle extent() const {return mExtent;} - /** Sets offset values to shift image (useful for live updates when moving item content)*/ + //! Sets offset values to shift image (useful for live updates when moving item content) void setOffset( double xOffset, double yOffset ); - /** True if composer map renders a WMS layer*/ + //! True if composer map renders a WMS layer bool containsWmsLayer() const; - /** True if composer map contains layers with blend modes or flattened layers for vectors */ + //! True if composer map contains layers with blend modes or flattened layers for vectors bool containsAdvancedEffects() const; /** Stores state in Dom node @@ -269,7 +269,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem */ QgsComposerMapOverview* overview(); - /** In case of annotations, the bounding rectangle can be larger than the map item rectangle */ + //! In case of annotations, the bounding rectangle can be larger than the map item rectangle QRectF boundingRect() const override; /* reimplement setFrameOutlineWidth, so that updateBoundingRect() is called after setting the frame width */ @@ -291,13 +291,13 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem void updateItem() override; - /** Sets canvas pointer (necessary to query and draw map canvas items)*/ + //! Sets canvas pointer (necessary to query and draw map canvas items) void setMapCanvas( QGraphicsView* canvas ) { mMapCanvas = canvas; } void setDrawCanvasItems( bool b ) { mDrawCanvasItems = b; } bool drawCanvasItems() const { return mDrawCanvasItems; } - /** Returns the conversion factor map units -> mm*/ + //! Returns the conversion factor map units -> mm double mapUnitsToMM() const; /** Sets mId to a number not yet used in the composition. mId is kept if it is not in use. @@ -357,10 +357,10 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem */ void setAtlasMargin( double margin ) { mAtlasMargin = margin; } - /** Sets whether updates to the composer map are enabled. */ + //! Sets whether updates to the composer map are enabled. void setUpdatesEnabled( bool enabled ) { mUpdatesEnabled = enabled; } - /** Returns whether updates to the composer map are enabled. */ + //! Returns whether updates to the composer map are enabled. bool updatesEnabled() const { return mUpdatesEnabled; } /** Get the number of layers that this item requires for exporting as layers @@ -381,10 +381,10 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem //overridden to show "Map 1" type names virtual QString displayName() const override; - /** Returns extent that considers rotation and shift with mOffsetX / mOffsetY*/ + //! Returns extent that considers rotation and shift with mOffsetX / mOffsetY QPolygonF transformedMapPolygon() const; - /** Transforms map coordinates to item coordinates (considering rotation and move offset)*/ + //! Transforms map coordinates to item coordinates (considering rotation and move offset) QPointF mapToItemCoords( QPointF mapCoords ) const; /** Calculates the extent to request and the yShift of the top-left point in case of rotation. @@ -396,10 +396,10 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem signals: void extentChanged(); - /** Is emitted on rotation change to notify north arrow pictures*/ + //! Is emitted on rotation change to notify north arrow pictures void mapRotationChanged( double newRotation ); - /** Is emitted when the map has been prepared for atlas rendering, just before actual rendering*/ + //! Is emitted when the map has been prepared for atlas rendering, just before actual rendering void preparedForAtlas(); /** Emitted when layer style overrides are changed... a means to let @@ -410,7 +410,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem public slots: - /** Forces an update of the cached map image*/ + //! Forces an update of the cached map image void updateCachedImage(); /** Updates the cached map image if the map is set to Render mode @@ -418,7 +418,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem */ void renderModeUpdateCachedImage(); - /** Updates the bounding rect of this item. Call this function before doing any changes related to annotation out of the map rectangle */ + //! Updates the bounding rect of this item. Call this function before doing any changes related to annotation out of the map rectangle void updateBoundingRect(); virtual void refreshDataDefinedProperty( const QgsComposerObject::DataDefinedProperty property = QgsComposerObject::AllProperties, const QgsExpressionContext* context = nullptr ) override; @@ -433,7 +433,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem private: - /** Unique identifier*/ + //! Unique identifier int mId; QgsComposerMapGridStack* mGridStack; @@ -456,34 +456,34 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem // Is cache up to date bool mCacheUpdated; - /** \brief Preview style */ + //! \brief Preview style PreviewMode mPreviewMode; - /** \brief Number of layers when cache was created */ + //! \brief Number of layers when cache was created int mNumCachedLayers; - /** \brief set to true if in state of drawing. Concurrent requests to draw method are returned if set to true */ + //! \brief set to true if in state of drawing. Concurrent requests to draw method are returned if set to true bool mDrawing; - /** Offset in x direction for showing map cache image*/ + //! Offset in x direction for showing map cache image double mXOffset; - /** Offset in y direction for showing map cache image*/ + //! Offset in y direction for showing map cache image double mYOffset; - /** Map rotation*/ + //! Map rotation double mMapRotation; /** Temporary evaluated map rotation. Data defined rotation may mean this value * differs from mMapRotation*/ double mEvaluatedMapRotation; - /** Flag if layers to be displayed should be read from qgis canvas (true) or from stored list in mLayerSet (false)*/ + //! Flag if layers to be displayed should be read from qgis canvas (true) or from stored list in mLayerSet (false) bool mKeepLayerSet; - /** Stored layer list (used if layer live-link mKeepLayerSet is disabled)*/ + //! Stored layer list (used if layer live-link mKeepLayerSet is disabled) QStringList mLayerSet; bool mKeepLayerStyles; - /** Stored style names (value) to be used with particular layer IDs (key) instead of default style */ + //! Stored style names (value) to be used with particular layer IDs (key) instead of default style QMap mLayerStyleOverrides; /** Whether layers and styles should be used from a preset (preset name is stored @@ -494,53 +494,53 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem * is true. May be overridden by data-defined expression. */ QString mFollowVisibilityPresetName; - /** Whether updates to the map are enabled */ + //! Whether updates to the map are enabled bool mUpdatesEnabled; - /** Establishes signal/slot connection for update in case of layer change*/ + //! Establishes signal/slot connection for update in case of layer change void connectUpdateSlot(); - /** Removes layer ids from mLayerSet that are no longer present in the qgis main map*/ + //! Removes layer ids from mLayerSet that are no longer present in the qgis main map void syncLayerSet(); - /** Returns first map grid or creates an empty one if none*/ + //! Returns first map grid or creates an empty one if none const QgsComposerMapGrid* constFirstMapGrid() const; - /** Returns first map overview or creates an empty one if none*/ + //! Returns first map overview or creates an empty one if none const QgsComposerMapOverview* constFirstMapOverview() const; - /** Current bounding rectangle. This is used to check if notification to the graphics scene is necessary*/ + //! Current bounding rectangle. This is used to check if notification to the graphics scene is necessary QRectF mCurrentRectangle; QGraphicsView* mMapCanvas; - /** True if annotation items, rubber band, etc. from the main canvas should be displayed*/ + //! True if annotation items, rubber band, etc. from the main canvas should be displayed bool mDrawCanvasItems; /** Adjusts an extent rectangle to match the provided item width and height, so that extent * center of extent remains the same */ void adjustExtentToItemShape( double itemWidth, double itemHeight, QgsRectangle& extent ) const; - /** True if map is being controlled by an atlas*/ + //! True if map is being controlled by an atlas bool mAtlasDriven; - /** Current atlas scaling mode*/ + //! Current atlas scaling mode AtlasScalingMode mAtlasScalingMode; - /** Margin size for atlas driven extents (percentage of feature size) - when in auto scaling mode*/ + //! Margin size for atlas driven extents (percentage of feature size) - when in auto scaling mode double mAtlasMargin; void init(); - /** Resets the item tooltip to reflect current map id*/ + //! Resets the item tooltip to reflect current map id void updateToolTip(); - /** Returns a list of the layers to render for this map item*/ + //! Returns a list of the layers to render for this map item QStringList layersToRender( const QgsExpressionContext* context = nullptr ) const; - /** Returns current layer style overrides for this map item*/ + //! Returns current layer style overrides for this map item QMap layerStyleOverridesToRender( const QgsExpressionContext& context ) const; - /** Returns extent that considers mOffsetX / mOffsetY (during content move)*/ + //! Returns extent that considers mOffsetX / mOffsetY (during content move) QgsRectangle transformedExtent() const; - /** MapPolygon variant using a given extent */ + //! MapPolygon variant using a given extent void mapPolygon( const QgsRectangle& extent, QPolygonF& poly ) const; /** Scales a composer map shift (in MM) and rotates it by mRotation @@ -562,7 +562,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem SelectionBoxes }; - /** Test if a part of the copmosermap needs to be drawn, considering mCurrentExportLayer*/ + //! Test if a part of the copmosermap needs to be drawn, considering mCurrentExportLayer bool shouldDrawPart( PartType part ) const; /** Refresh the map's extents, considering data defined extent, scale and rotation diff --git a/src/core/composer/qgscomposermapgrid.h b/src/core/composer/qgscomposermapgrid.h index b65c88f86522..f08fb2020b83 100644 --- a/src/core/composer/qgscomposermapgrid.h +++ b/src/core/composer/qgscomposermapgrid.h @@ -171,9 +171,9 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem */ enum GridUnit { - MapUnit, /*!< grid units follow map units */ - MM, /*!< grid units in millimeters */ - CM /*!< grid units in centimeters */ + MapUnit, //!< Grid units follow map units + MM, //!< Grid units in millimeters + CM //!< Grid units in centimeters }; /** Grid drawing style @@ -181,52 +181,52 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem enum GridStyle { Solid = 0, - Cross, /*!< draw line crosses at intersections of grid lines */ - Markers, /*!< draw markers at intersections of grid lines */ - FrameAnnotationsOnly /*!< no grid lines over the map, only draw frame and annotations */ + Cross, //!< Draw line crosses at intersections of grid lines + Markers, //!< Draw markers at intersections of grid lines + FrameAnnotationsOnly //!< No grid lines over the map, only draw frame and annotations }; /** Display settings for grid annotations and frames */ enum DisplayMode { - ShowAll = 0, /*!< show both latitude and longitude annotations/divisions */ - LatitudeOnly, /*!< show latitude/y annotations/divisions only */ - LongitudeOnly, /*!< show longitude/x annotations/divisions only */ - HideAll /*!< no annotations */ + ShowAll = 0, //!< Show both latitude and longitude annotations/divisions + LatitudeOnly, //!< Show latitude/y annotations/divisions only + LongitudeOnly, //!< Show longitude/x annotations/divisions only + HideAll //!< No annotations }; /** Position for grid annotations */ enum AnnotationPosition { - InsideMapFrame = 0, /*!< draw annotations inside the map frame */ - OutsideMapFrame, /*!< draw annotations outside the map frame */ + InsideMapFrame = 0, //!< Draw annotations inside the map frame + OutsideMapFrame, //!< Draw annotations outside the map frame }; /** Direction of grid annotations */ enum AnnotationDirection { - Horizontal = 0, /*!< draw annotations horizontally */ - Vertical, /*!< draw annotations vertically, ascending */ - VerticalDescending, /*!< draw annotations vertically, descending */ - BoundaryDirection /*!< annotations follow the boundary direction */ + Horizontal = 0, //!< Draw annotations horizontally + Vertical, //!< Draw annotations vertically, ascending + VerticalDescending, //!< Draw annotations vertically, descending + BoundaryDirection //!< Annotations follow the boundary direction }; /** Format for displaying grid annotations */ enum AnnotationFormat { - Decimal = 0, /*!< decimal degrees, use - for S/W coordinates */ - DegreeMinute, /*!< degree/minutes, use NSEW suffix */ - DegreeMinuteSecond, /*!< degree/minutes/seconds, use NSEW suffix */ - DecimalWithSuffix, /*!< decimal degrees, use NSEW suffix */ - DegreeMinuteNoSuffix, /*!< degree/minutes, use - for S/W coordinates */ - DegreeMinutePadded, /*!< degree/minutes, with minutes using leading zeros where required */ - DegreeMinuteSecondNoSuffix, /*!< degree/minutes/seconds, use - for S/W coordinates */ - DegreeMinuteSecondPadded, /*!< degree/minutes/seconds, with minutes using leading zeros where required */ - CustomFormat /*!< custom expression-based format */ + Decimal = 0, //!< Decimal degrees, use - for S/W coordinates + DegreeMinute, //!< Degree/minutes, use NSEW suffix + DegreeMinuteSecond, //!< Degree/minutes/seconds, use NSEW suffix + DecimalWithSuffix, //!< Decimal degrees, use NSEW suffix + DegreeMinuteNoSuffix, //!< Degree/minutes, use - for S/W coordinates + DegreeMinutePadded, //!< Degree/minutes, with minutes using leading zeros where required + DegreeMinuteSecondNoSuffix, //!< Degree/minutes/seconds, use - for S/W coordinates + DegreeMinuteSecondPadded, //!< Degree/minutes/seconds, with minutes using leading zeros where required + CustomFormat //!< Custom expression-based format }; /** Border sides for annotations @@ -234,31 +234,31 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem enum BorderSide { Left, - Right, /*!< right border */ - Bottom, /*!< bottom border */ - Top /*!< top border */ + Right, //!< Right border + Bottom, //!< Bottom border + Top //!< Top border }; /** Style for grid frame */ enum FrameStyle { - NoFrame = 0, /*!< disable grid frame */ - Zebra, /*!< black/white pattern */ - InteriorTicks, /*!< tick markers drawn inside map frame */ - ExteriorTicks, /*!< tick markers drawn outside map frame */ - InteriorExteriorTicks, /*!< tick markers drawn both inside and outside the map frame */ - LineBorder /*!< simple solid line frame */ + NoFrame = 0, //!< Disable grid frame + Zebra, //!< Black/white pattern + InteriorTicks, //!< Tick markers drawn inside map frame + ExteriorTicks, //!< Tick markers drawn outside map frame + InteriorExteriorTicks, //!< Tick markers drawn both inside and outside the map frame + LineBorder //!< Simple solid line frame }; /** Flags for controlling which side of the map a frame is drawn on */ enum FrameSideFlag { - FrameLeft = 0x01, /*!< left side of map */ - FrameRight = 0x02, /*!< right side of map */ - FrameTop = 0x04, /*!< top side of map */ - FrameBottom = 0x08 /*!< bottom side of map */ + FrameLeft = 0x01, //!< Left side of map + FrameRight = 0x02, //!< Right side of map + FrameTop = 0x04, //!< Top side of map + FrameBottom = 0x08 //!< Bottom side of map }; Q_DECLARE_FLAGS( FrameSideFlags, FrameSideFlag ) @@ -266,8 +266,8 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem */ enum AnnotationCoordinate { - Longitude = 0, /*!< coordinate is a longitude value */ - Latitude /*!< coordinate is a latitude value */ + Longitude = 0, //!< Coordinate is a longitude value + Latitude //!< Coordinate is a latitude value }; /** Constructor for QgsComposerMapGrid. @@ -848,53 +848,53 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem /*True if a re-transformation of grid lines is required*/ bool mTransformDirty; - /** Solid or crosses*/ + //! Solid or crosses GridStyle mGridStyle; - /** Grid line interval in x-direction (map units)*/ + //! Grid line interval in x-direction (map units) double mGridIntervalX; - /** Grid line interval in y-direction (map units)*/ + //! Grid line interval in y-direction (map units) double mGridIntervalY; - /** Grid line offset in x-direction*/ + //! Grid line offset in x-direction double mGridOffsetX; - /** Grid line offset in y-direction*/ + //! Grid line offset in y-direction double mGridOffsetY; - /** Font for grid line annotation*/ + //! Font for grid line annotation QFont mGridAnnotationFont; - /** Font color for grid coordinates*/ + //! Font color for grid coordinates QColor mGridAnnotationFontColor; - /** Digits after the dot*/ + //! Digits after the dot int mGridAnnotationPrecision; - /** True if coordinate values should be drawn*/ + //! True if coordinate values should be drawn bool mShowGridAnnotation; - /** Annotation display mode for left map side*/ + //! Annotation display mode for left map side DisplayMode mLeftGridAnnotationDisplay; - /** Annotation display mode for right map side*/ + //! Annotation display mode for right map side DisplayMode mRightGridAnnotationDisplay; - /** Annotation display mode for top map side*/ + //! Annotation display mode for top map side DisplayMode mTopGridAnnotationDisplay; - /** Annotation display mode for bottom map side*/ + //! Annotation display mode for bottom map side DisplayMode mBottomGridAnnotationDisplay; - /** Annotation position for left map side (inside / outside)*/ + //! Annotation position for left map side (inside / outside) AnnotationPosition mLeftGridAnnotationPosition; - /** Annotation position for right map side (inside / outside)*/ + //! Annotation position for right map side (inside / outside) AnnotationPosition mRightGridAnnotationPosition; - /** Annotation position for top map side (inside / outside)*/ + //! Annotation position for top map side (inside / outside) AnnotationPosition mTopGridAnnotationPosition; - /** Annotation position for bottom map side (inside / outside)*/ + //! Annotation position for bottom map side (inside / outside) AnnotationPosition mBottomGridAnnotationPosition; - /** Distance between map frame and annotation*/ + //! Distance between map frame and annotation double mAnnotationFrameDistance; - /** Annotation direction on left side ( horizontal or vertical )*/ + //! Annotation direction on left side ( horizontal or vertical ) AnnotationDirection mLeftGridAnnotationDirection; - /** Annotation direction on right side ( horizontal or vertical )*/ + //! Annotation direction on right side ( horizontal or vertical ) AnnotationDirection mRightGridAnnotationDirection; - /** Annotation direction on top side ( horizontal or vertical )*/ + //! Annotation direction on top side ( horizontal or vertical ) AnnotationDirection mTopGridAnnotationDirection; - /** Annotation direction on bottom side ( horizontal or vertical )*/ + //! Annotation direction on bottom side ( horizontal or vertical ) AnnotationDirection mBottomGridAnnotationDirection; AnnotationFormat mGridAnnotationFormat; @@ -910,13 +910,13 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem QColor mGridFrameFillColor2; double mCrossLength; - /** Divisions for frame on left map side*/ + //! Divisions for frame on left map side DisplayMode mLeftFrameDivisions; - /** Divisions for frame on right map side*/ + //! Divisions for frame on right map side DisplayMode mRightFrameDivisions; - /** Divisions for frame on top map side*/ + //! Divisions for frame on top map side DisplayMode mTopFrameDivisions; - /** Divisions for frame on bottom map side*/ + //! Divisions for frame on bottom map side DisplayMode mBottomFrameDivisions; QgsLineSymbol* mGridLineSymbol; @@ -1004,14 +1004,14 @@ class CORE_EXPORT QgsComposerMapGrid : public QgsComposerMapItem */ BorderSide borderForLineCoord( QPointF p, const AnnotationCoordinate coordinateType ) const; - /** Get parameters for drawing grid in CRS different to map CRS*/ + //! Get parameters for drawing grid in CRS different to map CRS int crsGridParams( QgsRectangle& crsRect, QgsCoordinateTransform& inverseTransform ) const; static QList trimLinesToMap( const QPolygonF &line, const QgsRectangle &rect ); QPolygonF scalePolygon( const QPolygonF &polygon, const double scale ) const; - /** Draws grid if CRS is different to map CRS*/ + //! Draws grid if CRS is different to map CRS void drawGridCrsTransform( QgsRenderContext &context, double dotsPerMM, QList< QPair< double, QLineF > > &horizontalLines, QList< QPair< double, QLineF > > &verticalLines , bool calculateLinesOnly = false ); diff --git a/src/core/composer/qgscomposermapitem.h b/src/core/composer/qgscomposermapitem.h index 5d2d0e1760ad..d1c25afc1fce 100644 --- a/src/core/composer/qgscomposermapitem.h +++ b/src/core/composer/qgscomposermapitem.h @@ -106,16 +106,16 @@ class CORE_EXPORT QgsComposerMapItem : public QgsComposerObject protected: - /** Friendly display name*/ + //! Friendly display name QString mName; - /** Associated composer map*/ + //! Associated composer map QgsComposerMap* mComposerMap; - /** Unique id*/ + //! Unique id QString mUuid; - /** True if item is to be displayed on map*/ + //! True if item is to be displayed on map bool mEnabled; }; diff --git a/src/core/composer/qgscomposermapoverview.h b/src/core/composer/qgscomposermapoverview.h index 635dd3d9ec86..a2544400c5ff 100644 --- a/src/core/composer/qgscomposermapoverview.h +++ b/src/core/composer/qgscomposermapoverview.h @@ -250,22 +250,22 @@ class CORE_EXPORT QgsComposerMapOverview : public QgsComposerMapItem QgsComposerMapOverview(); //forbidden - /** Id of map which displays its extent rectangle into this composer map (overview map functionality). -1 if not present*/ + //! Id of map which displays its extent rectangle into this composer map (overview map functionality). -1 if not present int mFrameMapId; - /** Drawing style for overview farme*/ + //! Drawing style for overview farme QgsFillSymbol* mFrameSymbol; - /** Blend mode for overview*/ + //! Blend mode for overview QPainter::CompositionMode mBlendMode; - /** True if overview is inverted*/ + //! True if overview is inverted bool mInverted; - /** True if map is centered on overview*/ + //! True if map is centered on overview bool mCentered; - /** Creates default overview symbol*/ + //! Creates default overview symbol void createDefaultFrameSymbol(); }; diff --git a/src/core/composer/qgscomposermodel.h b/src/core/composer/qgscomposermodel.h index 1bd2da94d9d7..6d8297255247 100644 --- a/src/core/composer/qgscomposermodel.h +++ b/src/core/composer/qgscomposermodel.h @@ -54,9 +54,9 @@ class CORE_EXPORT QgsComposerModel: public QAbstractItemModel //! Columns returned by the model enum Columns { - Visibility = 0, /*!< Item visibility check box */ - LockStatus, /*!< Item lock status check box */ - ItemId, /*!< Item ID */ + Visibility = 0, //!< Item visibility check box + LockStatus, //!< Item lock status check box + ItemId, //!< Item ID }; /** Constructor @@ -255,15 +255,15 @@ class CORE_EXPORT QgsComposerModel: public QAbstractItemModel protected: - /** Maintains z-Order of items. Starts with item at position 1 (position 0 is always paper item)*/ + //! Maintains z-Order of items. Starts with item at position 1 (position 0 is always paper item) QList mItemZList; - /** Cached list of items from mItemZList which are currently in the scene*/ + //! Cached list of items from mItemZList which are currently in the scene QList mItemsInScene; private: - /** Parent composition*/ + //! Parent composition QgsComposition* mComposition; /** Returns the QgsComposerItem corresponding to a QModelIndex, if possible diff --git a/src/core/composer/qgscomposermousehandles.h b/src/core/composer/qgscomposermousehandles.h index d29fdc31ae14..a0c3a6c20949 100644 --- a/src/core/composer/qgscomposermousehandles.h +++ b/src/core/composer/qgscomposermousehandles.h @@ -34,7 +34,7 @@ class CORE_EXPORT QgsComposerMouseHandles: public QObject, public QGraphicsRectI Q_OBJECT public: - /** Describes the action (move or resize in different directon) to be done during mouse move*/ + //! Describes the action (move or resize in different directon) to be done during mouse move enum MouseAction { MoveItem, @@ -77,13 +77,13 @@ class CORE_EXPORT QgsComposerMouseHandles: public QObject, public QGraphicsRectI void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; - /** Finds out which mouse move action to choose depending on the scene cursor position*/ + //! Finds out which mouse move action to choose depending on the scene cursor position QgsComposerMouseHandles::MouseAction mouseActionForScenePos( QPointF sceneCoordPos ); - /** Returns true is user is currently dragging the handles */ + //! Returns true is user is currently dragging the handles bool isDragging() { return mIsDragging; } - /** Returns true is user is currently resizing with the handles */ + //! Returns true is user is currently resizing with the handles bool isResizing() { return mIsResizing; } protected: @@ -97,13 +97,13 @@ class CORE_EXPORT QgsComposerMouseHandles: public QObject, public QGraphicsRectI public slots: - /** Sets up listeners to sizeChanged signal for all selected items*/ + //! Sets up listeners to sizeChanged signal for all selected items void selectionChanged(); - /** Redraws handles when selected item size changes*/ + //! Redraws handles when selected item size changes void selectedItemSizeChanged(); - /** Redraws handles when selected item rotation changes*/ + //! Redraws handles when selected item rotation changes void selectedItemRotationChanged(); private: @@ -112,15 +112,15 @@ class CORE_EXPORT QgsComposerMouseHandles: public QObject, public QGraphicsRectI QGraphicsView* mGraphicsView; //reference to QGraphicsView QgsComposerMouseHandles::MouseAction mCurrentMouseMoveAction; - /** Start point of the last mouse move action (in scene coordinates)*/ + //! Start point of the last mouse move action (in scene coordinates) QPointF mMouseMoveStartPos; - /** Position of the last mouse move event (in scene coordinates)*/ + //! Position of the last mouse move event (in scene coordinates) QPointF mLastMouseEventPos; - /** Position of the mouse at beginning of move/resize (in scene coordinates)*/ + //! Position of the mouse at beginning of move/resize (in scene coordinates) QPointF mBeginMouseEventPos; - /** Position of composer handles at beginning of move/resize (in scene coordinates)*/ + //! Position of composer handles at beginning of move/resize (in scene coordinates) QPointF mBeginHandlePos; - /** Width and height of composer handles at beginning of resize*/ + //! Width and height of composer handles at beginning of resize double mBeginHandleWidth; double mBeginHandleHeight; @@ -128,62 +128,62 @@ class CORE_EXPORT QgsComposerMouseHandles: public QObject, public QGraphicsRectI double mResizeMoveX; double mResizeMoveY; - /** True if user is currently dragging items*/ + //! True if user is currently dragging items bool mIsDragging; - /** True is user is currently resizing items*/ + //! True is user is currently resizing items bool mIsResizing; - /** Align snap lines*/ + //! Align snap lines QGraphicsLineItem* mHAlignSnapItem; QGraphicsLineItem* mVAlignSnapItem; QSizeF mCursorOffset; - /** Returns the mouse handle bounds of current selection*/ + //! Returns the mouse handle bounds of current selection QRectF selectionBounds() const; - /** Returns true if all selected items have same rotation, and if so, updates passed rotation variable*/ + //! Returns true if all selected items have same rotation, and if so, updates passed rotation variable bool selectionRotation( double & rotation ) const; - /** Redraws or hides the handles based on the current selection*/ + //! Redraws or hides the handles based on the current selection void updateHandles(); - /** Draws the handles*/ + //! Draws the handles void drawHandles( QPainter* painter, double rectHandlerSize ); - /** Draw outlines for selected items*/ + //! Draw outlines for selected items void drawSelectedItemBounds( QPainter* painter ); /** Returns the current (zoom level dependent) tolerance to decide if mouse position is close enough to the item border for resizing*/ double rectHandlerBorderTolerance(); - /** Finds out the appropriate cursor for the current mouse position in the widget (e.g. move in the middle, resize at border)*/ + //! Finds out the appropriate cursor for the current mouse position in the widget (e.g. move in the middle, resize at border) Qt::CursorShape cursorForPosition( QPointF itemCoordPos ); - /** Finds out which mouse move action to choose depending on the cursor position inside the widget*/ + //! Finds out which mouse move action to choose depending on the cursor position inside the widget QgsComposerMouseHandles::MouseAction mouseActionForPosition( QPointF itemCoordPos ); - /** Handles dragging of items during mouse move*/ + //! Handles dragging of items during mouse move void dragMouseMove( QPointF currentPosition, bool lockMovement, bool preventSnap ); - /** Calculates the distance of the mouse cursor from thed edge of the mouse handles*/ + //! Calculates the distance of the mouse cursor from thed edge of the mouse handles QSizeF calcCursorEdgeOffset( QPointF cursorPos ); - /** Handles resizing of items during mouse move*/ + //! Handles resizing of items during mouse move void resizeMouseMove( QPointF currentPosition, bool lockAspect, bool fromCenter ); - /** Return horizontal align snap item. Creates a new graphics line if 0*/ + //! Return horizontal align snap item. Creates a new graphics line if 0 QGraphicsLineItem* hAlignSnapItem(); void deleteHAlignSnapItem(); - /** Return vertical align snap item. Creates a new graphics line if 0*/ + //! Return vertical align snap item. Creates a new graphics line if 0 QGraphicsLineItem* vAlignSnapItem(); void deleteVAlignSnapItem(); void deleteAlignItems(); - /** Snaps an item or point (depending on mode) originating at originalPoint to the grid or align rulers*/ + //! Snaps an item or point (depending on mode) originating at originalPoint to the grid or align rulers QPointF snapPoint( QPointF originalPoint, QgsComposerMouseHandles::SnapGuideMode mode ); - /** Snaps an item originating at unalignedX, unalignedY to the grid or align rulers*/ + //! Snaps an item originating at unalignedX, unalignedY to the grid or align rulers QPointF alignItem( double& alignX, double& alignY, double unalignedX, double unalignedY ); - /** Snaps a point to to the grid or align rulers*/ + //! Snaps a point to to the grid or align rulers QPointF alignPos( QPointF pos, double& alignX, double& alignY ); //helper functions for item align diff --git a/src/core/composer/qgscomposermultiframe.h b/src/core/composer/qgscomposermultiframe.h index dc32d321a701..6cb22a181615 100644 --- a/src/core/composer/qgscomposermultiframe.h +++ b/src/core/composer/qgscomposermultiframe.h @@ -46,9 +46,9 @@ class CORE_EXPORT QgsComposerMultiFrame: public QgsComposerObject */ enum ResizeMode { - UseExistingFrames = 0, /*!< don't automatically create new frames, just use existing frames */ - ExtendToNextPage, /*!< creates new full page frames on the following page(s) until the entire multiframe content is visible */ - RepeatOnEveryPage, /*!< repeats the same frame on every page */ + UseExistingFrames = 0, //!< Don't automatically create new frames, just use existing frames + ExtendToNextPage, //!< Creates new full page frames on the following page(s) until the entire multiframe content is visible + RepeatOnEveryPage, //!< Repeats the same frame on every page RepeatUntilFinished /*!< creates new frames with the same position and dimensions as the existing frame on the following page(s), until the entire multiframe content is visible */ }; @@ -270,7 +270,7 @@ class CORE_EXPORT QgsComposerMultiFrame: public QgsComposerObject ResizeMode mResizeMode; - /** True: creates QgsMultiFrameCommands on internal changes (e.g. changing frames )*/ + //! True: creates QgsMultiFrameCommands on internal changes (e.g. changing frames ) bool mCreateUndoCommands; protected slots: diff --git a/src/core/composer/qgscomposermultiframecommand.h b/src/core/composer/qgscomposermultiframecommand.h index 255c5065fbf7..86e01918ea22 100644 --- a/src/core/composer/qgscomposermultiframecommand.h +++ b/src/core/composer/qgscomposermultiframecommand.h @@ -41,7 +41,7 @@ class CORE_EXPORT QgsComposerMultiFrameCommand: public QUndoCommand QDomDocument previousState() const { return mPreviousState.cloneNode().toDocument(); } QDomDocument afterState() const { return mAfterState.cloneNode().toDocument(); } - /** Returns true if previous state and after state are valid and different*/ + //! Returns true if previous state and after state are valid and different bool containsChange() const; const QgsComposerMultiFrame* multiFrame() const { return mMultiFrame; } diff --git a/src/core/composer/qgscomposernodesitem.h b/src/core/composer/qgscomposernodesitem.h index 05a68034ca55..527099be9104 100644 --- a/src/core/composer/qgscomposernodesitem.h +++ b/src/core/composer/qgscomposernodesitem.h @@ -45,7 +45,7 @@ class CORE_EXPORT QgsComposerNodesItem: public QgsComposerItem */ QgsComposerNodesItem( const QString &mTagName, const QPolygonF &polygon, QgsComposition* c ); - /** Destructor */ + //! Destructor ~QgsComposerNodesItem(); /** Add a node in current shape. @@ -68,7 +68,7 @@ class CORE_EXPORT QgsComposerNodesItem: public QgsComposerItem */ bool moveNode( const int index, QPointF node ); - /** \brief Reimplementation of QCanvasItem::paint - draw on canvas */ + //! \brief Reimplementation of QCanvasItem::paint - draw on canvas void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; /** Search the nearest node in shape within a maximal area. Returns the @@ -98,7 +98,7 @@ class CORE_EXPORT QgsComposerNodesItem: public QgsComposerItem */ bool removeNode( const int index ); - /** Returns the number of nodes in the shape. */ + //! Returns the number of nodes in the shape. int nodesSize() { return mPolygon.size(); } /** Select a node. @@ -123,46 +123,46 @@ class CORE_EXPORT QgsComposerNodesItem: public QgsComposerItem protected: - /** Storage meaning for shape's nodes. */ + //! Storage meaning for shape's nodes. QPolygonF mPolygon; - /** Method called in addNode. */ + //! Method called in addNode. virtual bool _addNode( const int nodeIndex, QPointF newNode, const double radius ) = 0; - /** Method called in removeNode. */ + //! Method called in removeNode. virtual bool _removeNode( const int nodeIndex ) = 0; - /** Method called in paint. */ + //! Method called in paint. virtual void _draw( QPainter *painter ) = 0; - /** Method called in readXml. */ + //! Method called in readXml. virtual void _readXmlStyle( const QDomElement &elmt ) = 0; - /** Method called in writeXml. */ + //! Method called in writeXml. virtual void _writeXmlStyle( QDomDocument &doc, QDomElement &elmt ) const = 0; /** Rescale the current shape according to the boudning box. Useful when * the shape is resized thanks to the rubber band. */ void rescaleToFitBoundingBox(); - /** Compute an euclidian distance between 2 nodes. */ + //! Compute an euclidian distance between 2 nodes. double computeDistance( QPointF pt1, QPointF pt2 ) const; - /** Update the current scene rectangle for this item. */ + //! Update the current scene rectangle for this item. void updateSceneRect(); private: - /** This tag is used to write the XML document. */ + //! This tag is used to write the XML document. QString mTagName; - /** The index of the node currently selected. */ + //! The index of the node currently selected. int mSelectedNode; /** This tag is used to indicate if we have to draw nodes or not during * the painting. */ bool mDrawNodes; - /** Draw nodes */ + //! Draw nodes void drawNodes( QPainter *painter ) const; void drawSelectedNode( QPainter *painter ) const; }; diff --git a/src/core/composer/qgscomposerobject.h b/src/core/composer/qgscomposerobject.h index 753128acb2e0..706793352583 100644 --- a/src/core/composer/qgscomposerobject.h +++ b/src/core/composer/qgscomposerobject.h @@ -39,39 +39,39 @@ class CORE_EXPORT QgsComposerObject: public QObject, public QgsExpressionContext */ enum DataDefinedProperty { - NoProperty = 0, /*!< no property */ - AllProperties, /*!< all properties for item */ - TestProperty, /*!< dummy property with no effect on item*/ + NoProperty = 0, //!< No property + AllProperties, //!< All properties for item + TestProperty, //!< Dummy property with no effect on item //composer page properties - PresetPaperSize, /*!< preset paper size for composition */ - PaperWidth, /*!< paper width */ - PaperHeight, /*!< paper height */ - NumPages, /*!< number of pages in composition */ - PaperOrientation, /*!< paper orientation */ + PresetPaperSize, //!< Preset paper size for composition + PaperWidth, //!< Paper width + PaperHeight, //!< Paper height + NumPages, //!< Number of pages in composition + PaperOrientation, //!< Paper orientation //general composer item properties - PageNumber, /*!< page number for item placement */ - PositionX, /*!< x position on page */ - PositionY, /*!< y position on page */ - ItemWidth, /*!< width of item */ - ItemHeight, /*!< height of item */ - ItemRotation, /*!< rotation of item */ - Transparency, /*!< item transparency */ - BlendMode, /*!< item blend mode */ - ExcludeFromExports, /*!< exclude item from exports */ + PageNumber, //!< Page number for item placement + PositionX, //!< X position on page + PositionY, //!< Y position on page + ItemWidth, //!< Width of item + ItemHeight, //!< Height of item + ItemRotation, //!< Rotation of item + Transparency, //!< Item transparency + BlendMode, //!< Item blend mode + ExcludeFromExports, //!< Exclude item from exports //composer map - MapRotation, /*!< map rotation */ - MapScale, /*!< map scale */ - MapXMin, /*!< map extent x minimum */ - MapYMin, /*!< map extent y minimum */ - MapXMax, /*!< map extent x maximum */ - MapYMax, /*!< map extent y maximum */ - MapAtlasMargin, /*!< map atlas margin*/ - MapLayers, /*!< map layer set*/ - MapStylePreset, /*!< layer and style map theme */ + MapRotation, //!< Map rotation + MapScale, //!< Map scale + MapXMin, //!< Map extent x minimum + MapYMin, //!< Map extent y minimum + MapXMax, //!< Map extent x maximum + MapYMax, //!< Map extent y maximum + MapAtlasMargin, //!< Map atlas margin + MapLayers, //!< Map layer set + MapStylePreset, //!< Layer and style map theme //composer picture - PictureSource, /*!< picture source url */ + PictureSource, //!< Picture source url //html item - SourceUrl /*!< html source url */ + SourceUrl //!< Html source url }; /** Specifies whether the value returned by a function should be the original, user @@ -80,8 +80,8 @@ class CORE_EXPORT QgsComposerObject: public QObject, public QgsExpressionContext */ enum PropertyValueType { - EvaluatedValue = 0, /*!< return the current evaluated value for the property */ - OriginalValue /*!< return the original, user set value */ + EvaluatedValue = 0, //!< Return the current evaluated value for the property + OriginalValue //!< Return the original, user set value }; /** Constructor @@ -172,7 +172,7 @@ class CORE_EXPORT QgsComposerObject: public QObject, public QgsExpressionContext public slots: - /** Triggers a redraw for the item*/ + //! Triggers a redraw for the item virtual void repaint(); /** Refreshes a data defined property for the item by reevaluating the property's value @@ -189,10 +189,10 @@ class CORE_EXPORT QgsComposerObject: public QObject, public QgsExpressionContext QgsComposition* mComposition; - /** Map of data defined properties for the item to string name to use when exporting item to xml*/ + //! Map of data defined properties for the item to string name to use when exporting item to xml QMap< QgsComposerObject::DataDefinedProperty, QString > mDataDefinedNames; - /** Custom properties for object*/ + //! Custom properties for object QgsObjectCustomProperties mCustomProperties; /** Evaluate a data defined property and return the calculated value @@ -219,7 +219,7 @@ class CORE_EXPORT QgsComposerObject: public QObject, public QgsExpressionContext private: - /** Map of current data defined properties*/ + //! Map of current data defined properties //mutable since expressions in data defineds need to be preparable mutable QMap< QgsComposerObject::DataDefinedProperty, QgsDataDefined* > mDataDefinedProperties; diff --git a/src/core/composer/qgscomposerpicture.h b/src/core/composer/qgscomposerpicture.h index 17027508ec00..6016ea9e3cd0 100644 --- a/src/core/composer/qgscomposerpicture.h +++ b/src/core/composer/qgscomposerpicture.h @@ -37,11 +37,11 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem */ enum ResizeMode { - Zoom, /*!< enlarges image to fit frame while maintaining aspect ratio of picture */ - Stretch, /*!< stretches image to fit frame, ignores aspect ratio */ - Clip, /*!< draws image at original size and clips any portion which falls outside frame */ - ZoomResizeFrame, /*!< enlarges image to fit frame, then resizes frame to fit resultant image */ - FrameToImageSize /*!< sets size of frame to match original size of image without scaling */ + Zoom, //!< Enlarges image to fit frame while maintaining aspect ratio of picture + Stretch, //!< Stretches image to fit frame, ignores aspect ratio + Clip, //!< Draws image at original size and clips any portion which falls outside frame + ZoomResizeFrame, //!< Enlarges image to fit frame, then resizes frame to fit resultant image + FrameToImageSize //!< Sets size of frame to match original size of image without scaling }; /** Format of source image @@ -56,17 +56,17 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem //! Method for syncing rotation to a map's North direction enum NorthMode { - GridNorth = 0, /*!< Align to grid north */ - TrueNorth, /*!< Align to true north */ + GridNorth = 0, //!< Align to grid north + TrueNorth, //!< Align to true north }; QgsComposerPicture( QgsComposition *composition ); ~QgsComposerPicture(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerPicture; } - /** Reimplementation of QCanvasItem::paint*/ + //! Reimplementation of QCanvasItem::paint void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; /** Sets the source path of the image (may be svg or a raster format). Data defined @@ -284,19 +284,19 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem virtual void refreshDataDefinedProperty( const QgsComposerObject::DataDefinedProperty property = QgsComposerObject::AllProperties, const QgsExpressionContext *context = nullptr ) override; signals: - /** Is emitted on picture rotation change*/ + //! Is emitted on picture rotation change void pictureRotationChanged( double newRotation ); private: //default constructor is forbidden QgsComposerPicture(); - /** Calculates bounding rect for svg file (mSourcefile) such that aspect ratio is correct*/ + //! Calculates bounding rect for svg file (mSourcefile) such that aspect ratio is correct QRectF boundedSVGRect( double deviceWidth, double deviceHeight ); - /** Calculates bounding rect for image such that aspect ratio is correct*/ + //! Calculates bounding rect for image such that aspect ratio is correct QRectF boundedImageRect( double deviceWidth, double deviceHeight ); - /** Returns size of current raster or svg picture */ + //! Returns size of current raster or svg picture QSizeF pictureSize(); QImage mImage; @@ -306,9 +306,9 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem QSize mDefaultSvgSize; - /** Image rotation*/ + //! Image rotation double mPictureRotation; - /** Map that sets the rotation (or 0 if this picture uses map independent rotation)*/ + //! Map that sets the rotation (or 0 if this picture uses map independent rotation) const QgsComposerMap* mRotationMap; //! Mode used to align to North @@ -316,9 +316,9 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem //! Offset for north arrow double mNorthOffset; - /** Width of the picture (in mm)*/ + //! Width of the picture (in mm) double mPictureWidth; - /** Height of the picture (in mm)*/ + //! Height of the picture (in mm) double mPictureHeight; ResizeMode mResizeMode; @@ -332,10 +332,10 @@ class CORE_EXPORT QgsComposerPicture: public QgsComposerItem bool mLoaded; bool mLoadingSvg; - /** Loads an image file into the picture item and redraws the item*/ + //! Loads an image file into the picture item and redraws the item void loadPicture( const QString &path ); - /** Sets up the picture item and connects to relevant signals*/ + //! Sets up the picture item and connects to relevant signals void init(); /** Returns part of a raster image which will be shown, given current picture diff --git a/src/core/composer/qgscomposerpolygon.h b/src/core/composer/qgscomposerpolygon.h index e6d027447285..d4e533cfff77 100644 --- a/src/core/composer/qgscomposerpolygon.h +++ b/src/core/composer/qgscomposerpolygon.h @@ -45,24 +45,24 @@ class CORE_EXPORT QgsComposerPolygon: public QgsComposerNodesItem */ QgsComposerPolygon( const QPolygonF &polygon, QgsComposition* c ); - /** Destructor */ + //! Destructor ~QgsComposerPolygon(); - /** Overridden to return shape name */ + //! Overridden to return shape name virtual QString displayName() const override; - /** Returns the QgsSymbol used to draw the shape. */ + //! Returns the QgsSymbol used to draw the shape. QgsFillSymbol* polygonStyleSymbol() { return mPolygonStyleSymbol.data(); } - /** Set the QgsSymbol used to draw the shape. */ + //! Set the QgsSymbol used to draw the shape. void setPolygonStyleSymbol( QgsFillSymbol* symbol ); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerPolygon; } protected: - /** QgsSymbol use to draw the shape. */ + //! QgsSymbol use to draw the shape. QScopedPointer mPolygonStyleSymbol; /** Add the node newPoint at the given position according to some @@ -71,16 +71,16 @@ class CORE_EXPORT QgsComposerPolygon: public QgsComposerNodesItem bool _removeNode( const int nodeIndex ) override; - /** Draw nodes for the current shape. */ + //! Draw nodes for the current shape. void _draw( QPainter *painter ) override; - /** Read symbol in XML. */ + //! Read symbol in XML. void _readXmlStyle( const QDomElement &elmt ) override; - /** Write the symbol in an XML document. */ + //! Write the symbol in an XML document. void _writeXmlStyle( QDomDocument &doc, QDomElement &elmt ) const override; - /** Create a default symbol. */ + //! Create a default symbol. void createDefaultPolygonStyleSymbol(); }; diff --git a/src/core/composer/qgscomposerpolyline.h b/src/core/composer/qgscomposerpolyline.h index c9c03ea4abd8..ba748c868aef 100644 --- a/src/core/composer/qgscomposerpolyline.h +++ b/src/core/composer/qgscomposerpolyline.h @@ -44,24 +44,24 @@ class CORE_EXPORT QgsComposerPolyline: public QgsComposerNodesItem */ QgsComposerPolyline( const QPolygonF &polyline, QgsComposition* c ); - /** Destructor */ + //! Destructor ~QgsComposerPolyline(); - /** Overridden to return shape name */ + //! Overridden to return shape name virtual QString displayName() const override; - /** Returns the QgsSymbol used to draw the shape. */ + //! Returns the QgsSymbol used to draw the shape. QgsLineSymbol* polylineStyleSymbol() { return mPolylineStyleSymbol.data(); } - /** Set the QgsSymbol used to draw the shape. */ + //! Set the QgsSymbol used to draw the shape. void setPolylineStyleSymbol( QgsLineSymbol* symbol ); - /** Overridden to return shape type */ + //! Overridden to return shape type virtual int type() const override { return ComposerPolyline; } protected: - /** QgsSymbol use to draw the shape. */ + //! QgsSymbol use to draw the shape. QScopedPointer mPolylineStyleSymbol; /** Add the node newPoint at the given position according to some @@ -70,16 +70,16 @@ class CORE_EXPORT QgsComposerPolyline: public QgsComposerNodesItem bool _removeNode( const int nodeIndex ) override; - /** Draw nodes for the current shape. */ + //! Draw nodes for the current shape. void _draw( QPainter *painter ) override; - /** Read symbol in XML. */ + //! Read symbol in XML. void _readXmlStyle( const QDomElement &elmt ) override; - /** Write the symbol in an XML document. */ + //! Write the symbol in an XML document. void _writeXmlStyle( QDomDocument &doc, QDomElement &elmt ) const override; - /** Create a default symbol. */ + //! Create a default symbol. void createDefaultPolylineStyleSymbol(); }; diff --git a/src/core/composer/qgscomposerscalebar.h b/src/core/composer/qgscomposerscalebar.h index 4b4bf8840ce1..f22c5df93417 100644 --- a/src/core/composer/qgscomposerscalebar.h +++ b/src/core/composer/qgscomposerscalebar.h @@ -52,17 +52,17 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem */ enum SegmentSizeMode { - SegmentSizeFixed = 0, /*!< Scale bar segment size is fixed to a map unit*/ - SegmentSizeFitWidth = 1 /*!< Scale bar segment size is calculated to fit a size range*/ + SegmentSizeFixed = 0, //!< Scale bar segment size is fixed to a map unit + SegmentSizeFitWidth = 1 //!< Scale bar segment size is calculated to fit a size range }; QgsComposerScaleBar( QgsComposition* composition ); ~QgsComposerScaleBar(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerScaleBar; } - /** \brief Reimplementation of QCanvasItem::paint*/ + //! \brief Reimplementation of QCanvasItem::paint void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; //getters and setters @@ -217,7 +217,7 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem double segmentMillimeters() const {return mSegmentMillimeters;} - /** Left / Middle/ Right */ + //! Left / Middle/ Right Alignment alignment() const { return mAlignment; } void setAlignment( Alignment a ); @@ -254,16 +254,16 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem */ void setLineCapStyle( Qt::PenCapStyle style ); - /** Apply default settings*/ + //! Apply default settings void applyDefaultSettings(); - /** Apply default size (scale bar 1/5 of map item width) */ + //! Apply default size (scale bar 1/5 of map item width) void applyDefaultSize( ScaleBarUnits u = Meters ); /** Sets style by name @param styleName (untranslated) style name. Possibilities are: 'Single Box', 'Double Box', 'Line Ticks Middle', 'Line Ticks Down', 'Line Ticks Up', 'Numeric'*/ void setStyle( const QString& styleName ); - /** Returns style name*/ + //! Returns style name QString style() const; /** Returns the x - positions of the segment borders (in item coordinates) and the width @@ -272,13 +272,13 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem */ void segmentPositions( QList >& posWidthList ) const; - /** Sets box size suitable to content*/ + //! Sets box size suitable to content void adjustBoxSize(); - /** Adjusts box size and calls QgsComposerItem::update()*/ + //! Adjusts box size and calls QgsComposerItem::update() void update(); - /** Returns string of first label (important for drawing, labeling, size calculation*/ + //! Returns string of first label (important for drawing, labeling, size calculation QString firstLabelString() const; /** Stores state in Dom element @@ -293,7 +293,7 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem */ bool readXml( const QDomElement& itemElem, const QDomDocument& doc ) override; - /** Moves scalebar position to the left / right depending on alignment and change in item width*/ + //! Moves scalebar position to the left / right depending on alignment and change in item width void correctXPositionAlignment( double width, double widthAfter ); //overridden to apply minimum size @@ -301,51 +301,51 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem public slots: void updateSegmentSize(); - /** Sets mCompositionMap to 0 if the map is deleted*/ + //! Sets mCompositionMap to 0 if the map is deleted void invalidateCurrentMap(); protected: - /** Reference to composer map object*/ + //! Reference to composer map object const QgsComposerMap* mComposerMap; - /** Number of segments on right side*/ + //! Number of segments on right side int mNumSegments; - /** Number of segments on left side*/ + //! Number of segments on left side int mNumSegmentsLeft; - /** Size of a segment (in map units)*/ + //! Size of a segment (in map units) double mNumUnitsPerSegment; - /** Number of map units per scale bar units (e.g. 1000 to have km for a map with m units)*/ + //! Number of map units per scale bar units (e.g. 1000 to have km for a map with m units) double mNumMapUnitsPerScaleBarUnit; - /** Either fixed (i.e. mNumUnitsPerSegment) or try to best fit scale bar width (mMinBarWidth, mMaxBarWidth)*/ + //! Either fixed (i.e. mNumUnitsPerSegment) or try to best fit scale bar width (mMinBarWidth, mMaxBarWidth) SegmentSizeMode mSegmentSizeMode; - /** Minimum allowed bar width, when mSegmentSizeMode is FitWidth*/ + //! Minimum allowed bar width, when mSegmentSizeMode is FitWidth double mMinBarWidth; - /** Maximum allowed bar width, when mSegmentSizeMode is FitWidth*/ + //! Maximum allowed bar width, when mSegmentSizeMode is FitWidth double mMaxBarWidth; - /** Labeling of map units*/ + //! Labeling of map units QString mUnitLabeling; - /** Font*/ + //! Font QFont mFont; QColor mFontColor; - /** Outline*/ + //! Outline QPen mPen; - /** Fill*/ + //! Fill QBrush mBrush; - /** Secondary fill*/ + //! Secondary fill QBrush mBrush2; - /** Height of bars/lines*/ + //! Height of bars/lines double mHeight; - /** Scalebar style*/ + //! Scalebar style QgsScaleBarStyle* mStyle; - /** Space between bar and Text labels*/ + //! Space between bar and Text labels double mLabelBarSpace; - /** Space between content and item box*/ + //! Space between content and item box double mBoxContentSpace; - /** Width of a segment (in mm)*/ + //! Width of a segment (in mm) double mSegmentMillimeters; Alignment mAlignment; @@ -355,10 +355,10 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem Qt::PenJoinStyle mLineJoinStyle; Qt::PenCapStyle mLineCapStyle; - /** Calculates with of a segment in mm and stores it in mSegmentMillimeters*/ + //! Calculates with of a segment in mm and stores it in mSegmentMillimeters void refreshSegmentMillimeters(); - /** Returns diagonal of composer map in selected units (map units / meters / feet / nautical miles)*/ + //! Returns diagonal of composer map in selected units (map units / meters / feet / nautical miles) double mapWidth() const; }; diff --git a/src/core/composer/qgscomposershape.h b/src/core/composer/qgscomposershape.h index 0705fd0c509f..b1a24a953805 100644 --- a/src/core/composer/qgscomposershape.h +++ b/src/core/composer/qgscomposershape.h @@ -42,10 +42,10 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem QgsComposerShape( qreal x, qreal y, qreal width, qreal height, QgsComposition* composition ); ~QgsComposerShape(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerShape; } - /** \brief Reimplementation of QCanvasItem::paint - draw on canvas */ + //! \brief Reimplementation of QCanvasItem::paint - draw on canvas void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; /** Stores state in Dom element @@ -64,9 +64,9 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem QgsComposerShape::Shape shapeType() const { return mShape; } void setShapeType( QgsComposerShape::Shape s ); - /** Sets radius for rounded rectangle corners. Added in v2.1 */ + //! Sets radius for rounded rectangle corners. Added in v2.1 void setCornerRadius( double radius ); - /** Returns the radius for rounded rectangle corners*/ + //! Returns the radius for rounded rectangle corners double cornerRadius() const { return mCornerRadius; } /** Sets the QgsFillSymbol used to draw the shape. Must also call setUseSymbol( true ) to @@ -109,7 +109,7 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem void refreshSymbol(); private: - /** Ellipse, rectangle or triangle*/ + //! Ellipse, rectangle or triangle Shape mShape; double mCornerRadius; @@ -118,7 +118,7 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem QgsFillSymbol* mShapeStyleSymbol; double mMaxSymbolBleed; - /** Current bounding rectangle of shape*/ + //! Current bounding rectangle of shape QRectF mCurrentRectangle; /* draws the custom shape */ @@ -130,10 +130,10 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem /* creates the default shape symbol */ void createDefaultShapeStyleSymbol(); - /** Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point*/ + //! Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point QPointF pointOnLineWithDistance( const QPointF& startPoint, const QPointF& directionPoint, double distance ) const; - /** Updates the bounding rect of this item*/ + //! Updates the bounding rect of this item void updateBoundingRect(); }; diff --git a/src/core/composer/qgscomposertablev2.h b/src/core/composer/qgscomposertablev2.h index e2c7af551847..7c10788c7f69 100644 --- a/src/core/composer/qgscomposertablev2.h +++ b/src/core/composer/qgscomposertablev2.h @@ -97,51 +97,51 @@ class CORE_EXPORT QgsComposerTableV2: public QgsComposerMultiFrame */ enum HeaderHAlignment { - FollowColumn, /*!< header uses the same alignment as the column */ - HeaderLeft, /*!< align headers left */ - HeaderCenter, /*!< align headers to center */ - HeaderRight /*!< align headers right */ + FollowColumn, //!< Header uses the same alignment as the column + HeaderLeft, //!< Align headers left + HeaderCenter, //!< Align headers to center + HeaderRight //!< Align headers right }; /** Controls where headers are shown in the table */ enum HeaderMode { - FirstFrame = 0, /*!< header shown on first frame only */ - AllFrames, /*!< headers shown on all frames */ - NoHeaders /*!< no headers shown for table */ + FirstFrame = 0, //!< Header shown on first frame only + AllFrames, //!< Headers shown on all frames + NoHeaders //!< No headers shown for table }; /** Controls how empty tables are displayed */ enum EmptyTableMode { - HeadersOnly = 0, /*!< show header rows only */ - HideTable, /*!< hides entire table if empty */ - ShowMessage /*!< shows preset message instead of table contents*/ + HeadersOnly = 0, //!< Show header rows only + HideTable, //!< Hides entire table if empty + ShowMessage //!< Shows preset message instead of table contents }; /** Controls how long strings in the table are handled */ enum WrapBehaviour { - TruncateText = 0, /*!< text which doesn't fit inside the cell is truncated */ - WrapText /*!< text which doesn't fit inside the cell is wrapped. Note that this only applies to text in columns with a fixed width. */ + TruncateText = 0, //!< Text which doesn't fit inside the cell is truncated + WrapText //!< Text which doesn't fit inside the cell is wrapped. Note that this only applies to text in columns with a fixed width. }; /** Row or column groups for cell styling */ enum CellStyleGroup { - OddColumns, /*!< Style odd numbered columns */ - EvenColumns, /*!< Style even numbered columns */ - OddRows, /*!< Style odd numbered rows */ - EvenRows, /*!< Style even numbered rows */ - FirstColumn, /*!< Style first column only */ - LastColumn, /*!< Style last column only */ - HeaderRow, /*!< Style header row */ - FirstRow, /*!< Style first row only */ - LastRow /*!< Style last row only */ + OddColumns, //!< Style odd numbered columns + EvenColumns, //!< Style even numbered columns + OddRows, //!< Style odd numbered rows + EvenRows, //!< Style even numbered rows + FirstColumn, //!< Style first column only + LastColumn, //!< Style last column only + HeaderRow, //!< Style header row + FirstRow, //!< Style first row only + LastRow //!< Style last row only }; QgsComposerTableV2( QgsComposition* composition, bool createUndoCommands ); @@ -478,64 +478,64 @@ class CORE_EXPORT QgsComposerTableV2: public QgsComposerMultiFrame void recalculateFrameSizes() override; protected: - /** Margin between cell borders and cell text*/ + //! Margin between cell borders and cell text double mCellMargin; - /** Behaviour for empty tables*/ + //! Behaviour for empty tables EmptyTableMode mEmptyTableMode; - /** String to show in empty tables*/ + //! String to show in empty tables QString mEmptyTableMessage; - /** True if empty rows should be shown in the table*/ + //! True if empty rows should be shown in the table bool mShowEmptyRows; - /** Header font*/ + //! Header font QFont mHeaderFont; - /** Header font color*/ + //! Header font color QColor mHeaderFontColor; - /** Alignment for table headers*/ + //! Alignment for table headers HeaderHAlignment mHeaderHAlignment; - /** Header display mode*/ + //! Header display mode HeaderMode mHeaderMode; - /** Table contents font*/ + //! Table contents font QFont mContentFont; - /** Table contents font color*/ + //! Table contents font color QColor mContentFontColor; - /** True if grid should be shown*/ + //! True if grid should be shown bool mShowGrid; - /** Width of grid lines*/ + //! Width of grid lines double mGridStrokeWidth; - /** Color for grid lines*/ + //! Color for grid lines QColor mGridColor; - /** True if grid should be shown*/ + //! True if grid should be shown bool mHorizontalGrid; - /** True if grid should be shown*/ + //! True if grid should be shown bool mVerticalGrid; - /** Color for table background*/ + //! Color for table background QColor mBackgroundColor; - /** Columns to show in table*/ + //! Columns to show in table QgsComposerTableColumns mColumns; - /** Contents to show in table*/ + //! Contents to show in table QgsComposerTableContents mTableContents; - /** Map of maximum width for each column*/ + //! Map of maximum width for each column QMap mMaxColumnWidthMap; - /** Map of maximum height for each row*/ + //! Map of maximum height for each row QMap mMaxRowHeightMap; QSizeF mTableSize; @@ -641,7 +641,7 @@ class CORE_EXPORT QgsComposerTableV2: public QgsComposerMultiFrame QMap< CellStyleGroup, QString > mCellStyleNames; - /** Initializes cell style map */ + //! Initializes cell style map void initStyles(); bool textRequiresWrapping( const QString& text, double columnWidth , const QFont &font ) const; diff --git a/src/core/composer/qgscomposertexttable.h b/src/core/composer/qgscomposertexttable.h index 1931de2a73bd..e4df33df7d2b 100644 --- a/src/core/composer/qgscomposertexttable.h +++ b/src/core/composer/qgscomposertexttable.h @@ -53,7 +53,7 @@ class CORE_EXPORT QgsComposerTextTableV2 : public QgsComposerTableV2 virtual void addFrame( QgsComposerFrame* frame, bool recalcFrameSizes = true ) override; private: - /** One stringlist per row*/ + //! One stringlist per row QList< QStringList > mRowText; }; diff --git a/src/core/composer/qgscomposition.h b/src/core/composer/qgscomposition.h index becad079f816..c05cf7fec192 100644 --- a/src/core/composer/qgscomposition.h +++ b/src/core/composer/qgscomposition.h @@ -76,7 +76,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo Q_OBJECT public: - /** \brief Plot type */ + //! \brief Plot type enum PlotStyle { Preview = 0, // Use cache etc @@ -84,7 +84,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo Postscript // Fonts need different scaling! }; - /** Style to draw the snapping grid*/ + //! Style to draw the snapping grid enum GridStyle { Solid, @@ -106,7 +106,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo explicit QgsComposition( const QgsMapSettings& mapSettings ); - /** Composition atlas modes*/ + //! Composition atlas modes enum AtlasMode { AtlasOff, // Composition is not being controlled by an atlas @@ -220,9 +220,9 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ bool shouldExportPage( const int page ) const; - /** Note: added in version 2.1*/ + //! Note: added in version 2.1 void setPageStyleSymbol( QgsFillSymbol* symbol ); - /** Note: added in version 2.1*/ + //! Note: added in version 2.1 QgsFillSymbol* pageStyleSymbol() { return mPageStyleSymbol; } /** Returns the position within a page of a point in the composition @@ -251,7 +251,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo void setGridVisible( const bool b ); bool gridVisible() const {return mGridVisible;} - /** Hides / shows custom snap lines*/ + //! Hides / shows custom snap lines void setSnapLinesVisible( const bool visible ); bool snapLinesVisible() const {return mGuidesVisible;} @@ -278,7 +278,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ bool pagesVisible() const { return mPagesVisible; } - /** Removes all snap lines*/ + //! Removes all snap lines void clearSnapLines(); void setSnapGridResolution( const double r ); @@ -326,7 +326,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ bool boundingBoxesVisible() const { return mBoundingBoxesVisible; } - /** Returns pointer to undo/redo command storage*/ + //! Returns pointer to undo/redo command storage QUndoStack* undoStack() { return mUndoStack; } /** Returns the topmost composer item at a specified position. Ignores paper items. @@ -344,10 +344,10 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ QgsComposerItem* composerItemAt( QPointF position, const QgsComposerItem* belowItem, const bool ignoreLocked = false ) const; - /** Returns the page number (0-based) given a coordinate */ + //! Returns the page number (0-based) given a coordinate int pageNumberAt( QPointF position ) const; - /** Returns on which page number (0-based) is displayed an item */ + //! Returns on which page number (0-based) is displayed an item int itemPageNumber( const QgsComposerItem* ) const; /** Returns list of selected composer items @@ -428,9 +428,9 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ void setWorldFileMap( QgsComposerMap* map ); - /** Returns true if a composition should use advanced effects such as blend modes */ + //! Returns true if a composition should use advanced effects such as blend modes bool useAdvancedEffects() const {return mUseAdvancedEffects;} - /** Used to enable or disable advanced effects such as blend modes in a composition */ + //! Used to enable or disable advanced effects such as blend modes in a composition void setUseAdvancedEffects( const bool effectsEnabled ); //! Return setting of QGIS map canvas @@ -440,10 +440,10 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QgsComposition::PlotStyle plotStyle() const { return mPlotStyle; } void setPlotStyle( const QgsComposition::PlotStyle style ) { mPlotStyle = style; } - /** Writes settings to xml (paper dimension)*/ + //! Writes settings to xml (paper dimension) bool writeXml( QDomElement& composerElem, QDomDocument& doc ); - /** Reads settings from xml file*/ + //! Reads settings from xml file bool readXml( const QDomElement& compositionElem, const QDomDocument& doc ); /** Load a template document @@ -469,9 +469,9 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo void addItemsFromXml( const QDomElement& elem, const QDomDocument& doc, QMap< QgsComposerMap*, int >* mapsToRestore = nullptr, bool addUndoCommands = false, QPointF* pos = nullptr, bool pasteInPlace = false ); - /** Adds item to z list. Usually called from constructor of QgsComposerItem*/ + //! Adds item to z list. Usually called from constructor of QgsComposerItem void addItemToZList( QgsComposerItem* item ); - /** Removes item from z list. Usually called from destructor of QgsComposerItem*/ + //! Removes item from z list. Usually called from destructor of QgsComposerItem void removeItemFromZList( QgsComposerItem* item ); //functions to move selected items in hierarchy @@ -503,9 +503,9 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo void alignSelectedItemsBottom(); //functions to lock and unlock items - /** Lock the selected items*/ + //! Lock the selected items void lockSelectedItems(); - /** Unlock all items*/ + //! Unlock all items void unlockAllItems(); /** Creates a new group from a list of composer items and adds it to the composition. @@ -529,10 +529,10 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ void refreshZList(); - /** Snaps a scene coordinate point to grid*/ + //! Snaps a scene coordinate point to grid QPointF snapPointToGrid( QPointF scenePoint ) const; - /** Returns pointer to snap lines collection*/ + //! Returns pointer to snap lines collection QList< QGraphicsLineItem* >* snapLines() {return &mSnapLines;} /** Returns pointer to selection handles @@ -540,9 +540,9 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ QgsComposerMouseHandles* selectionHandles() {return mSelectionHandles;} - /** Add a custom snap line (can be horizontal or vertical)*/ + //! Add a custom snap line (can be horizontal or vertical) QGraphicsLineItem* addSnapLine(); - /** Remove custom snap line (and delete the object)*/ + //! Remove custom snap line (and delete the object) void removeSnapLine( QGraphicsLineItem* line ); /** Get nearest snap line * @note not available in python bindings @@ -556,48 +556,48 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo */ void beginCommand( QgsComposerItem* item, const QString& commandText, const QgsComposerMergeCommand::Context c = QgsComposerMergeCommand::Unknown ); - /** Saves end state of item and pushes command to the undo history*/ + //! Saves end state of item and pushes command to the undo history void endCommand(); - /** Deletes current command*/ + //! Deletes current command void cancelCommand(); void beginMultiFrameCommand( QgsComposerMultiFrame* multiFrame, const QString& text, const QgsComposerMultiFrameMergeCommand::Context c = QgsComposerMultiFrameMergeCommand::Unknown ); void endMultiFrameCommand(); - /** Deletes current multi frame command*/ + //! Deletes current multi frame command void cancelMultiFrameCommand(); - /** Adds multiframe. The object is owned by QgsComposition until removeMultiFrame is called*/ + //! Adds multiframe. The object is owned by QgsComposition until removeMultiFrame is called void addMultiFrame( QgsComposerMultiFrame* multiFrame ); - /** Removes multi frame (but does not delete it)*/ + //! Removes multi frame (but does not delete it) void removeMultiFrame( QgsComposerMultiFrame* multiFrame ); /** Adds an arrow item to the graphics scene and advises composer to create a widget for it (through signal) @note not available in python bindings*/ void addComposerArrow( QgsComposerArrow* arrow ); - /** Adds label to the graphics scene and advises composer to create a widget for it (through signal)*/ + //! Adds label to the graphics scene and advises composer to create a widget for it (through signal) void addComposerLabel( QgsComposerLabel* label ); - /** Adds map to the graphics scene and advises composer to create a widget for it (through signal)*/ + //! Adds map to the graphics scene and advises composer to create a widget for it (through signal) void addComposerMap( QgsComposerMap* map, const bool setDefaultPreviewStyle = true ); - /** Adds scale bar to the graphics scene and advises composer to create a widget for it (through signal)*/ + //! Adds scale bar to the graphics scene and advises composer to create a widget for it (through signal) void addComposerScaleBar( QgsComposerScaleBar* scaleBar ); - /** Adds legend to the graphics scene and advises composer to create a widget for it (through signal)*/ + //! Adds legend to the graphics scene and advises composer to create a widget for it (through signal) void addComposerLegend( QgsComposerLegend* legend ); - /** Adds picture to the graphics scene and advises composer to create a widget for it (through signal)*/ + //! Adds picture to the graphics scene and advises composer to create a widget for it (through signal) void addComposerPicture( QgsComposerPicture* picture ); - /** Adds a composer shape to the graphics scene and advises composer to create a widget for it (through signal)*/ + //! Adds a composer shape to the graphics scene and advises composer to create a widget for it (through signal) void addComposerShape( QgsComposerShape* shape ); - /** Adds a composer polygon and advises composer to create a widget for it (through signal)*/ + //! Adds a composer polygon and advises composer to create a widget for it (through signal) void addComposerPolygon( QgsComposerPolygon* polygon ); - /** Adds a composer polyline and advises composer to create a widget for it (through signal)*/ + //! Adds a composer polyline and advises composer to create a widget for it (through signal) void addComposerPolyline( QgsComposerPolyline* polyline ); - /** Adds composer html frame and advises composer to create a widget for it (through signal)*/ + //! Adds composer html frame and advises composer to create a widget for it (through signal) void addComposerHtmlFrame( QgsComposerHtml* html, QgsComposerFrame* frame ); - /** Adds composer tablev2 frame and advises composer to create a widget for it (through signal)*/ + //! Adds composer tablev2 frame and advises composer to create a widget for it (through signal) void addComposerTableFrame( QgsComposerAttributeTableV2* table, QgsComposerFrame* frame ); - /** Remove item from the graphics scene. Additionally to QGraphicsScene::removeItem, this function considers undo/redo command*/ + //! Remove item from the graphics scene. Additionally to QGraphicsScene::removeItem, this function considers undo/redo command void removeComposerItem( QgsComposerItem* item, const bool createCommand = true, const bool removeGroupItems = true ); - /** Convenience function to create a QgsAddRemoveItemCommand, connect its signals and push it to the undo stack*/ + //! Convenience function to create a QgsAddRemoveItemCommand, connect its signals and push it to the undo stack void pushAddRemoveCommand( QgsComposerItem* item, const QString& text, const QgsAddRemoveItemCommand::State state = QgsAddRemoveItemCommand::Added ); /** If true, prevents any mouse cursor changes by the composition or by any composer items @@ -608,9 +608,9 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo //printing - /** Prepare the printer for printing */ + //! Prepare the printer for printing void beginPrint( QPrinter& printer, const bool evaluateDDPageSize = false ); - /** Prepare the printer for printing in a PDF */ + //! Prepare the printer for printing in a PDF void beginPrintAsPDF( QPrinter& printer, const QString& file ); /** Print on a preconfigured printer @@ -800,7 +800,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QRectF compositionBounds( bool ignorePages = false, double margin = 0.0 ) const; public slots: - /** Casts object to the proper subclass type and calls corresponding itemAdded signal*/ + //! Casts object to the proper subclass type and calls corresponding itemAdded signal void sendItemAddedSignal( QgsComposerItem* item ); /** Updates the scene bounds of the composition @@ -846,7 +846,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo private: - /** Reference to map settings of QGIS main map*/ + //! Reference to map settings of QGIS main map const QgsMapSettings& mMapSettings; QgsComposition::PlotStyle mPlotStyle; @@ -855,29 +855,29 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QList< QgsPaperItem* > mPages; double mSpaceBetweenPages; //space in preview between pages - /** Drawing style for page*/ + //! Drawing style for page QgsFillSymbol* mPageStyleSymbol; void createDefaultPageStyleSymbol(); - /** List multiframe objects*/ + //! List multiframe objects QSet mMultiFrames; - /** Dpi for printout*/ + //! Dpi for printout int mPrintResolution; - /** Flag if map should be printed as a raster (via QImage). False by default*/ + //! Flag if map should be printed as a raster (via QImage). False by default bool mPrintAsRaster; - /** Flag if a world file should be generated on raster export */ + //! Flag if a world file should be generated on raster export bool mGenerateWorldFile; - /** Item ID for composer map to use for the world file generation */ + //! Item ID for composer map to use for the world file generation QString mWorldFileMapId; - /** Flag if advanced visual effects such as blend modes should be used. True by default*/ + //! Flag if advanced visual effects such as blend modes should be used. True by default bool mUseAdvancedEffects; - /** Parameters for snap to grid function*/ + //! Parameters for snap to grid function bool mSnapToGrid; bool mGridVisible; double mSnapGridResolution; @@ -886,13 +886,13 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QPen mGridPen; GridStyle mGridStyle; - /** Parameters for alignment snap*/ + //! Parameters for alignment snap bool mAlignmentSnap; bool mGuidesVisible; bool mSmartGuides; int mSnapTolerance; - /** Arbitraty snap lines (horizontal and vertical)*/ + //! Arbitraty snap lines (horizontal and vertical) QList< QGraphicsLineItem* > mSnapLines; double mResizeToContentsMarginTop; @@ -909,7 +909,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QgsComposerItemCommand* mActiveItemCommand; QgsComposerMultiFrameCommand* mActiveMultiFrameCommand; - /** The atlas composition object. It is held by the QgsComposition */ + //! The atlas composition object. It is held by the QgsComposition QgsAtlasComposition mAtlasComposition; QgsComposition::AtlasMode mAtlasMode; @@ -918,29 +918,29 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QgsComposerModel * mItemsModel; - /** Map of data defined properties for the composition to string name to use when exporting composition to xml*/ + //! Map of data defined properties for the composition to string name to use when exporting composition to xml QMap< QgsComposerObject::DataDefinedProperty, QString > mDataDefinedNames; - /** Map of current data defined properties to QgsDataDefined for the composition*/ + //! Map of current data defined properties to QgsDataDefined for the composition QMap< QgsComposerObject::DataDefinedProperty, QgsDataDefined* > mDataDefinedProperties; QgsObjectCustomProperties mCustomProperties; QgsComposition(); //default constructor is forbidden - /** Reset z-values of items based on position in z list*/ + //! Reset z-values of items based on position in z list void updateZValues( const bool addUndoCommands = true ); /** Returns the bounding rectangle of the selected items in scene coordinates @return 0 in case of success*/ int boundingRectOfSelectedItems( QRectF& bRect ); - /** Loads default composer settings*/ + //! Loads default composer settings void loadDefaults(); - /** Loads composer settings which may change, eg grid color*/ + //! Loads composer settings which may change, eg grid color void loadSettings(); - /** Calculates the item minimum position from an xml string*/ + //! Calculates the item minimum position from an xml string QPointF minPointFromXml( const QDomElement& elem ) const; void connectAddRemoveCommandSignals( QgsAddRemoveItemCommand* c ); @@ -1028,42 +1028,42 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo void paperSizeChanged(); void nPagesChanged(); - /** Is emitted when the compositions print resolution changes*/ + //! Is emitted when the compositions print resolution changes void printResolutionChanged(); - /** Is emitted when selected item changed. If 0, no item is selected*/ + //! Is emitted when selected item changed. If 0, no item is selected void selectedItemChanged( QgsComposerItem* selected ); - /** Is emitted when new composer arrow has been added to the view*/ + //! Is emitted when new composer arrow has been added to the view void composerArrowAdded( QgsComposerArrow* arrow ); - /** Is emitted when new composer polygon has been added to the view*/ + //! Is emitted when new composer polygon has been added to the view void composerPolygonAdded( QgsComposerPolygon* polygon ); - /** Is emitted when new composer polyline has been added to the view*/ + //! Is emitted when new composer polyline has been added to the view void composerPolylineAdded( QgsComposerPolyline* polyline ); - /** Is emitted when a new composer html has been added to the view*/ + //! Is emitted when a new composer html has been added to the view void composerHtmlFrameAdded( QgsComposerHtml* html, QgsComposerFrame* frame ); - /** Is emitted when a new item group has been added to the view*/ + //! Is emitted when a new item group has been added to the view void composerItemGroupAdded( QgsComposerItemGroup* group ); - /** Is emitted when new composer label has been added to the view*/ + //! Is emitted when new composer label has been added to the view void composerLabelAdded( QgsComposerLabel* label ); - /** Is emitted when new composer map has been added to the view*/ + //! Is emitted when new composer map has been added to the view void composerMapAdded( QgsComposerMap* map ); - /** Is emitted when new composer scale bar has been added*/ + //! Is emitted when new composer scale bar has been added void composerScaleBarAdded( QgsComposerScaleBar* scalebar ); - /** Is emitted when a new composer legend has been added*/ + //! Is emitted when a new composer legend has been added void composerLegendAdded( QgsComposerLegend* legend ); - /** Is emitted when a new composer picture has been added*/ + //! Is emitted when a new composer picture has been added void composerPictureAdded( QgsComposerPicture* picture ); - /** Is emitted when a new composer shape has been added*/ + //! Is emitted when a new composer shape has been added void composerShapeAdded( QgsComposerShape* shape ); - /** Is emitted when a new composer table frame has been added to the view*/ + //! Is emitted when a new composer table frame has been added to the view void composerTableFrameAdded( QgsComposerAttributeTableV2* table, QgsComposerFrame* frame ); - /** Is emitted when a composer item has been removed from the scene*/ + //! Is emitted when a composer item has been removed from the scene void itemRemoved( QgsComposerItem* ); - /** Is emitted when item in the composition must be refreshed*/ + //! Is emitted when item in the composition must be refreshed void refreshItemsTriggered(); - /** Is emitted when the composition has an updated status bar message for the composer window*/ + //! Is emitted when the composition has an updated status bar message for the composer window void statusMsgChanged( const QString& message ); /** Emitted whenever the expression variables stored in the composition have been changed. diff --git a/src/core/composer/qgsgroupungroupitemscommand.h b/src/core/composer/qgsgroupungroupitemscommand.h index 28af8d02ac12..847a0313541a 100644 --- a/src/core/composer/qgsgroupungroupitemscommand.h +++ b/src/core/composer/qgsgroupungroupitemscommand.h @@ -35,7 +35,7 @@ class CORE_EXPORT QgsGroupUngroupItemsCommand: public QObject, public QUndoComma public: - /** Command kind, and state */ + //! Command kind, and state enum State { Grouped = 0, @@ -58,9 +58,9 @@ class CORE_EXPORT QgsGroupUngroupItemsCommand: public QObject, public QUndoComma void undo() override; signals: - /** Signals addition of an item (the group) */ + //! Signals addition of an item (the group) void itemAdded( QgsComposerItem* item ); - /** Signals removal of an item (the group) */ + //! Signals removal of an item (the group) void itemRemoved( QgsComposerItem* item ); private: diff --git a/src/core/composer/qgsnumericscalebarstyle.h b/src/core/composer/qgsnumericscalebarstyle.h index 20d7327f0b9f..b915b86d8e39 100644 --- a/src/core/composer/qgsnumericscalebarstyle.h +++ b/src/core/composer/qgsnumericscalebarstyle.h @@ -37,10 +37,10 @@ class CORE_EXPORT QgsNumericScaleBarStyle: public QgsScaleBarStyle private: QgsNumericScaleBarStyle(); //forbidden - /** Returns the text for the scale bar or an empty string in case of error*/ + //! Returns the text for the scale bar or an empty string in case of error QString scaleText() const; - /** Store last width (in mm) to keep alignment to left/middle/right side*/ + //! Store last width (in mm) to keep alignment to left/middle/right side mutable double mLastScaleBarWidth; }; diff --git a/src/core/composer/qgspaperitem.h b/src/core/composer/qgspaperitem.h index 7d0f8fb1deeb..275e53acdb37 100644 --- a/src/core/composer/qgspaperitem.h +++ b/src/core/composer/qgspaperitem.h @@ -30,7 +30,7 @@ class CORE_EXPORT QgsPaperGrid: public QGraphicsRectItem QgsPaperGrid( double x, double y, double width, double height, QgsComposition* composition ); ~QgsPaperGrid(); - /** \brief Reimplementation of QCanvasItem::paint*/ + //! \brief Reimplementation of QCanvasItem::paint void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; private: @@ -48,10 +48,10 @@ class CORE_EXPORT QgsPaperItem : public QgsComposerItem QgsPaperItem( qreal x, qreal y, qreal width, qreal height, QgsComposition* composition ); ~QgsPaperItem(); - /** Return correct graphics item type. */ + //! Return correct graphics item type. virtual int type() const override { return ComposerPaper; } - /** \brief Reimplementation of QCanvasItem::paint*/ + //! \brief Reimplementation of QCanvasItem::paint void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; /** Stores state in Dom element @@ -70,7 +70,7 @@ class CORE_EXPORT QgsPaperItem : public QgsComposerItem private: QgsPaperItem(); - /** Set flags and z-value*/ + //! Set flags and z-value void initialize(); void calculatePageMargin(); diff --git a/src/core/diagram/qgsdiagram.h b/src/core/diagram/qgsdiagram.h index c53394101e06..756fb1ef504e 100644 --- a/src/core/diagram/qgsdiagram.h +++ b/src/core/diagram/qgsdiagram.h @@ -49,16 +49,16 @@ class CORE_EXPORT QgsDiagram */ QgsExpression* getExpression( const QString& expression, const QgsExpressionContext& context ); - /** Draws the diagram at the given position (in pixel coordinates)*/ + //! Draws the diagram at the given position (in pixel coordinates) virtual void renderDiagram( const QgsFeature& feature, QgsRenderContext& c, const QgsDiagramSettings& s, QPointF position ) = 0; /** * Get a descriptive name for this diagram type. */ virtual QString diagramName() const = 0; - /** Returns the size in map units the diagram will use to render.*/ + //! Returns the size in map units the diagram will use to render. virtual QSizeF diagramSize( const QgsAttributes& attributes, const QgsRenderContext& c, const QgsDiagramSettings& s ) = 0; - /** Returns the size in map units the diagram will use to render. Interpolate size*/ + //! Returns the size in map units the diagram will use to render. Interpolate size virtual QSizeF diagramSize( const QgsFeature& feature, const QgsRenderContext& c, const QgsDiagramSettings& s, const QgsDiagramInterpolationSettings& is ) = 0; /** Returns the size of the legend item for the diagram corresponding to a specified value. diff --git a/src/core/dxf/qgsdxfexport.h b/src/core/dxf/qgsdxfexport.h index 77004fd30126..4f096621925a 100644 --- a/src/core/dxf/qgsdxfexport.h +++ b/src/core/dxf/qgsdxfexport.h @@ -330,9 +330,9 @@ class CORE_EXPORT QgsDxfExport private: QList< QPair > mLayers; - /** Extent for export, only intersecting features are exported. If the extent is an empty rectangle, all features are exported*/ + //! Extent for export, only intersecting features are exported. If the extent is an empty rectangle, all features are exported QgsRectangle mExtent; - /** Scale for symbology export (used if symbols units are mm)*/ + //! Scale for symbology export (used if symbols units are mm) double mSymbologyScaleDenominator; SymbologyExport mSymbologyExport; QgsUnitTypes::DistanceUnit mMapUnits; diff --git a/src/core/dxf/qgsdxfpaintdevice.h b/src/core/dxf/qgsdxfpaintdevice.h index 2b30896d4362..08a3790df038 100644 --- a/src/core/dxf/qgsdxfpaintdevice.h +++ b/src/core/dxf/qgsdxfpaintdevice.h @@ -40,10 +40,10 @@ class CORE_EXPORT QgsDxfPaintDevice: public QPaintDevice void setDrawingSize( QSizeF size ) { mDrawingSize = size; } void setOutputSize( const QRectF& r ) { mRectangle = r; } - /** Returns scale factor for line width*/ + //! Returns scale factor for line width double widthScaleFactor() const; - /** Converts a point from device coordinates to dxf coordinates*/ + //! Converts a point from device coordinates to dxf coordinates QPointF dxfCoordinates( QPointF pt ) const; /*int height() const { return mDrawingSize.height(); } diff --git a/src/core/effects/qgsblureffect.h b/src/core/effects/qgsblureffect.h index b05094692ebc..b3d68ec206ab 100644 --- a/src/core/effects/qgsblureffect.h +++ b/src/core/effects/qgsblureffect.h @@ -34,11 +34,11 @@ class CORE_EXPORT QgsBlurEffect : public QgsPaintEffect public: - /** Available blur methods (algorithms) */ + //! Available blur methods (algorithms) enum BlurMethod { - StackBlur, /*!< stack blur, a fast but low quality blur. Valid blur level values are between 0 - 16.*/ - GaussianBlur /*!< Gaussian blur, a slower but high quality blur. Blur level values are the distance in pixels for the blur operation. */ + StackBlur, //!< Stack blur, a fast but low quality blur. Valid blur level values are between 0 - 16. + GaussianBlur //!< Gaussian blur, a slower but high quality blur. Blur level values are the distance in pixels for the blur operation. }; /** Creates a new QgsBlurEffect effect from a properties string map. diff --git a/src/core/effects/qgsgloweffect.h b/src/core/effects/qgsgloweffect.h index 779196d589be..fc238a27bf90 100644 --- a/src/core/effects/qgsgloweffect.h +++ b/src/core/effects/qgsgloweffect.h @@ -36,11 +36,11 @@ class CORE_EXPORT QgsGlowEffect : public QgsPaintEffect public: - /** Color sources for the glow */ + //! Color sources for the glow enum GlowColorType { - SingleColor, /*!< use a single color and fade the color to totally transparent */ - ColorRamp /*!< use colors from a color ramp */ + SingleColor, //!< Use a single color and fade the color to totally transparent + ColorRamp //!< Use colors from a color ramp }; QgsGlowEffect(); diff --git a/src/core/effects/qgsimageoperation.h b/src/core/effects/qgsimageoperation.h index 43752a177450..c5d94e6cb2a3 100644 --- a/src/core/effects/qgsimageoperation.h +++ b/src/core/effects/qgsimageoperation.h @@ -47,18 +47,18 @@ class CORE_EXPORT QgsImageOperation */ enum GrayscaleMode { - GrayscaleLightness, /*!< keep the lightness of the color, drops the saturation */ - GrayscaleLuminosity, /*!< grayscale by perceptual luminosity (weighted sum of color RGB components) */ - GrayscaleAverage, /*!< grayscale by taking average of color RGB components */ - GrayscaleOff /*!< no change */ + GrayscaleLightness, //!< Keep the lightness of the color, drops the saturation + GrayscaleLuminosity, //!< Grayscale by perceptual luminosity (weighted sum of color RGB components) + GrayscaleAverage, //!< Grayscale by taking average of color RGB components + GrayscaleOff //!< No change }; /** Flip operation types */ enum FlipType { - FlipHorizontal, /*!< flip the image horizontally */ - FlipVertical /*!< flip the image vertically */ + FlipHorizontal, //!< Flip the image horizontally + FlipVertical //!< Flip the image vertically }; /** Convert a QImage to a grayscale image. Alpha channel is preserved. @@ -101,7 +101,7 @@ class CORE_EXPORT QgsImageOperation */ static void overlayColor( QImage &image, const QColor& color ); - /** Struct for storing properties of a distance transform operation*/ + //! Struct for storing properties of a distance transform operation struct DistanceTransformProperties { DistanceTransformProperties() diff --git a/src/core/effects/qgspainteffect.h b/src/core/effects/qgspainteffect.h index 60674195d937..050c0985f6b2 100644 --- a/src/core/effects/qgspainteffect.h +++ b/src/core/effects/qgspainteffect.h @@ -58,9 +58,9 @@ class CORE_EXPORT QgsPaintEffect */ enum DrawMode { - Modifier, /*!< the result of the effect is not rendered, but is passed on to following effects in the stack */ - Render, /*!< the result of the effect is rendered on the destination, but does not affect subsequent effects in the stack */ - ModifyAndRender /*!< the result of the effect is both rendered and passed on to subsequent effects in the stack */ + Modifier, //!< The result of the effect is not rendered, but is passed on to following effects in the stack + Render, //!< The result of the effect is rendered on the destination, but does not affect subsequent effects in the stack + ModifyAndRender //!< The result of the effect is both rendered and passed on to subsequent effects in the stack }; QgsPaintEffect(); diff --git a/src/core/geometry/qgsabstractgeometry.h b/src/core/geometry/qgsabstractgeometry.h index 9db4b2f440d2..37636a429754 100644 --- a/src/core/geometry/qgsabstractgeometry.h +++ b/src/core/geometry/qgsabstractgeometry.h @@ -45,7 +45,7 @@ class CORE_EXPORT QgsAbstractGeometry { public: - /** Segmentation tolerance as maximum angle or maximum difference between approximation and circle*/ + //! Segmentation tolerance as maximum angle or maximum difference between approximation and circle enum SegmentationToleranceType { MaximumAngle = 0, @@ -296,7 +296,7 @@ class CORE_EXPORT QgsAbstractGeometry */ virtual double area() const { return 0.0; } - /** Returns the centroid of the geometry */ + //! Returns the centroid of the geometry virtual QgsPointV2 centroid() const; /** Returns true if the geometry is empty diff --git a/src/core/geometry/qgscompoundcurve.h b/src/core/geometry/qgscompoundcurve.h index fcc03d4de4d3..939c9145cb4e 100644 --- a/src/core/geometry/qgscompoundcurve.h +++ b/src/core/geometry/qgscompoundcurve.h @@ -101,7 +101,7 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve void sumUpArea( double& sum ) const override; - /** Appends first point if not already closed.*/ + //! Appends first point if not already closed. void close(); bool hasCurvedSegments() const override; diff --git a/src/core/geometry/qgscurvepolygon.h b/src/core/geometry/qgscurvepolygon.h index 0dc0f84cc538..79e60eff5c35 100644 --- a/src/core/geometry/qgscurvepolygon.h +++ b/src/core/geometry/qgscurvepolygon.h @@ -76,11 +76,11 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface */ virtual void setExteriorRing( QgsCurve* ring ); - /** Sets all interior rings (takes ownership)*/ + //! Sets all interior rings (takes ownership) void setInteriorRings( const QList& rings ); - /** Adds an interior ring to the geometry (takes ownership)*/ + //! Adds an interior ring to the geometry (takes ownership) virtual void addInteriorRing( QgsCurve* ring ); - /** Removes ring. Exterior ring is 0, first interior ring 1, ...*/ + //! Removes ring. Exterior ring is 0, first interior ring 1, ... bool removeInteriorRing( int nr ); virtual void draw( QPainter& p ) const override; diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index 70e70af21022..d15e8b5402a3 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -815,7 +815,7 @@ int QgsGeometry::splitGeometry( const QList& splitLine, QList& reshapeWithLine ) { if ( !d->geometry ) diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index cce70ca030ee..08c946e7dfba 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -45,19 +45,19 @@ class QPainter; class QgsPolygonV2; class QgsLineString; -/** Polyline is represented as a vector of points */ +//! Polyline is represented as a vector of points typedef QVector QgsPolyline; -/** Polygon: first item of the list is outer ring, inner rings (if any) start from second item */ +//! Polygon: first item of the list is outer ring, inner rings (if any) start from second item typedef QVector QgsPolygon; -/** A collection of QgsPoints that share a common collection of attributes */ +//! A collection of QgsPoints that share a common collection of attributes typedef QVector QgsMultiPoint; -/** A collection of QgsPolylines that share a common collection of attributes */ +//! A collection of QgsPolylines that share a common collection of attributes typedef QVector QgsMultiPolyline; -/** A collection of QgsPolygons that share a common collection of attributes */ +//! A collection of QgsPolygons that share a common collection of attributes typedef QVector QgsMultiPolygon; class QgsRectangle; @@ -81,7 +81,7 @@ class CORE_EXPORT QgsGeometry //! Constructor QgsGeometry(); - /** Copy constructor will prompt a deep copy of the object */ + //! Copy constructor will prompt a deep copy of the object QgsGeometry( const QgsGeometry & ); /** Assignments will prompt a deep copy of the object @@ -117,23 +117,23 @@ class CORE_EXPORT QgsGeometry */ bool isEmpty() const; - /** Creates a new geometry from a WKT string */ + //! Creates a new geometry from a WKT string static QgsGeometry fromWkt( const QString& wkt ); - /** Creates a new geometry from a QgsPoint object*/ + //! Creates a new geometry from a QgsPoint object static QgsGeometry fromPoint( const QgsPoint& point ); - /** Creates a new geometry from a QgsMultiPoint object */ + //! Creates a new geometry from a QgsMultiPoint object static QgsGeometry fromMultiPoint( const QgsMultiPoint& multipoint ); - /** Creates a new geometry from a QgsPolyline object */ + //! Creates a new geometry from a QgsPolyline object static QgsGeometry fromPolyline( const QgsPolyline& polyline ); - /** Creates a new geometry from a QgsMultiPolyline object*/ + //! Creates a new geometry from a QgsMultiPolyline object static QgsGeometry fromMultiPolyline( const QgsMultiPolyline& multiline ); - /** Creates a new geometry from a QgsPolygon */ + //! Creates a new geometry from a QgsPolygon static QgsGeometry fromPolygon( const QgsPolygon& polygon ); - /** Creates a new geometry from a QgsMultiPolygon */ + //! Creates a new geometry from a QgsMultiPolygon static QgsGeometry fromMultiPolygon( const QgsMultiPolygon& multipoly ); - /** Creates a new geometry from a QgsRectangle */ + //! Creates a new geometry from a QgsRectangle static QgsGeometry fromRect( const QgsRectangle& rect ); - /** Creates a new multipart geometry from a list of QgsGeometry objects*/ + //! Creates a new multipart geometry from a list of QgsGeometry objects static QgsGeometry collectGeometry( const QList< QgsGeometry >& geometries ); /** @@ -179,7 +179,7 @@ class CORE_EXPORT QgsGeometry */ QgsWkbTypes::GeometryType type() const; - /** Returns true if WKB of the geometry is of WKBMulti* type */ + //! Returns true if WKB of the geometry is of WKBMulti* type bool isMultipart() const; /** Compares the geometry with another geometry using GEOS @@ -456,16 +456,16 @@ class CORE_EXPORT QgsGeometry */ QgsGeometry makeDifference( const QgsGeometry& other ) const; - /** Returns the bounding box of this feature*/ + //! Returns the bounding box of this feature QgsRectangle boundingBox() const; - /** Test for intersection with a rectangle (uses GEOS) */ + //! Test for intersection with a rectangle (uses GEOS) bool intersects( const QgsRectangle& r ) const; - /** Test for intersection with a geometry (uses GEOS) */ + //! Test for intersection with a geometry (uses GEOS) bool intersects( const QgsGeometry& geometry ) const; - /** Test for containment of a point (uses GEOS) */ + //! Test for containment of a point (uses GEOS) bool contains( const QgsPoint* p ) const; /** Test for if geometry is contained in another (uses GEOS) @@ -558,7 +558,7 @@ class CORE_EXPORT QgsGeometry JoinStyle joinStyle = JoinStyleRound, double mitreLimit = 2.0 ) const; - /** Returns a simplified version of this geometry using a specified tolerance value */ + //! Returns a simplified version of this geometry using a specified tolerance value QgsGeometry simplify( double tolerance ) const; /** Returns the center of mass of a geometry @@ -567,10 +567,10 @@ class CORE_EXPORT QgsGeometry */ QgsGeometry centroid() const; - /** Returns a point within a geometry */ + //! Returns a point within a geometry QgsGeometry pointOnSurface() const; - /** Returns the smallest convex polygon that contains all the points in the geometry. */ + //! Returns the smallest convex polygon that contains all the points in the geometry. QgsGeometry convexHull() const; /** @@ -602,7 +602,7 @@ class CORE_EXPORT QgsGeometry */ double interpolateAngle( double distance ) const; - /** Returns a geometry representing the points shared by this geometry and other. */ + //! Returns a geometry representing the points shared by this geometry and other. QgsGeometry intersection( const QgsGeometry& geometry ) const; /** Returns a geometry representing all the points in this geometry and other (a @@ -620,13 +620,13 @@ class CORE_EXPORT QgsGeometry */ QgsGeometry mergeLines() const; - /** Returns a geometry representing the points making up this geometry that do not make up other. */ + //! Returns a geometry representing the points making up this geometry that do not make up other. QgsGeometry difference( const QgsGeometry& geometry ) const; - /** Returns a geometry representing the points making up this geometry that do not make up other. */ + //! Returns a geometry representing the points making up this geometry that do not make up other. QgsGeometry symDifference( const QgsGeometry& geometry ) const; - /** Returns an extruded version of this geometry. */ + //! Returns an extruded version of this geometry. QgsGeometry extrude( double x, double y ); /** Exports the geometry to WKT @@ -934,11 +934,11 @@ class CORE_EXPORT QgsGeometry static void convertToPolyline( const QgsPointSequence &input, QgsPolyline& output ); static void convertPolygon( const QgsPolygonV2& input, QgsPolygon& output ); - /** Try to convert the geometry to a point */ + //! Try to convert the geometry to a point QgsGeometry convertToPoint( bool destMultipart ) const; - /** Try to convert the geometry to a line */ + //! Try to convert the geometry to a line QgsGeometry convertToLine( bool destMultipart ) const; - /** Try to convert the geometry to a polygon */ + //! Try to convert the geometry to a polygon QgsGeometry convertToPolygon( bool destMultipart ) const; /** Smooths a polyline using the Chaikin algorithm @@ -972,9 +972,9 @@ class CORE_EXPORT QgsGeometry Q_DECLARE_METATYPE( QgsGeometry ) -/** Writes the geometry to stream out. QGIS version compatibility is not guaranteed. */ +//! Writes the geometry to stream out. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsGeometry& geometry ); -/** Reads a geometry from stream in into geometry. QGIS version compatibility is not guaranteed. */ +//! Reads a geometry from stream in into geometry. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsGeometry& geometry ); #endif diff --git a/src/core/geometry/qgsgeometrycollection.h b/src/core/geometry/qgsgeometrycollection.h index d644b967de77..34a79a748e50 100644 --- a/src/core/geometry/qgsgeometrycollection.h +++ b/src/core/geometry/qgsgeometrycollection.h @@ -56,7 +56,7 @@ class CORE_EXPORT QgsGeometryCollection: public QgsAbstractGeometry virtual void clear() override; virtual QgsAbstractGeometry* boundary() const override; - /** Adds a geometry and takes ownership. Returns true in case of success.*/ + //! Adds a geometry and takes ownership. Returns true in case of success. virtual bool addGeometry( QgsAbstractGeometry* g ); /** Inserts a geometry before a specified index and takes ownership. Returns true in case of success. diff --git a/src/core/geometry/qgsgeometryfactory.h b/src/core/geometry/qgsgeometryfactory.h index 22ff4313d0e9..da020f44d216 100644 --- a/src/core/geometry/qgsgeometryfactory.h +++ b/src/core/geometry/qgsgeometryfactory.h @@ -51,21 +51,21 @@ class CORE_EXPORT QgsGeometryFactory */ static QgsAbstractGeometry* geomFromWkt( const QString& text ); - /** Construct geometry from a point */ + //! Construct geometry from a point static QgsAbstractGeometry* fromPoint( const QgsPoint& point ); - /** Construct geometry from a multipoint */ + //! Construct geometry from a multipoint static QgsAbstractGeometry* fromMultiPoint( const QgsMultiPoint& multipoint ); - /** Construct geometry from a polyline */ + //! Construct geometry from a polyline static QgsAbstractGeometry* fromPolyline( const QgsPolyline& polyline ); - /** Construct geometry from a multipolyline*/ + //! Construct geometry from a multipolyline static QgsAbstractGeometry* fromMultiPolyline( const QgsMultiPolyline& multiline ); - /** Construct geometry from a polygon */ + //! Construct geometry from a polygon static QgsAbstractGeometry* fromPolygon( const QgsPolygon& polygon ); - /** Construct geometry from a multipolygon */ + //! Construct geometry from a multipolygon static QgsAbstractGeometry* fromMultiPolygon( const QgsMultiPolygon& multipoly ); - /** Construct geometry from a rectangle */ + //! Construct geometry from a rectangle static QgsAbstractGeometry* fromRect( const QgsRectangle& rect ); - /** Return empty geometry from wkb type*/ + //! Return empty geometry from wkb type static QgsAbstractGeometry* geomFromWkbType( QgsWkbTypes::Type t ); private: diff --git a/src/core/geometry/qgsgeometryutils.h b/src/core/geometry/qgsgeometryutils.h index 412b790add07..1f59e2f1ed36 100644 --- a/src/core/geometry/qgsgeometryutils.h +++ b/src/core/geometry/qgsgeometryutils.h @@ -132,24 +132,24 @@ class CORE_EXPORT QgsGeometryUtils */ static QList getSelfIntersections( const QgsAbstractGeometry* geom, int part, int ring, double tolerance ); - /** Returns < 0 if point(x/y) is left of the line x1,y1 -> x2,y2*/ + //! Returns < 0 if point(x/y) is left of the line x1,y1 -> x2,y2 static double leftOfLine( double x, double y, double x1, double y1, double x2, double y2 ); /** Returns a point a specified distance toward a second point. */ static QgsPointV2 pointOnLineWithDistance( const QgsPointV2& startPoint, const QgsPointV2& directionPoint, double distance ); - /** Returns the counter clockwise angle between a line with components dx, dy and the line with dx > 0 and dy = 0*/ + //! Returns the counter clockwise angle between a line with components dx, dy and the line with dx > 0 and dy = 0 static double ccwAngle( double dy, double dx ); - /** Returns radius and center of the circle through pt1, pt2, pt3*/ + //! Returns radius and center of the circle through pt1, pt2, pt3 static void circleCenterRadius( const QgsPointV2& pt1, const QgsPointV2& pt2, const QgsPointV2& pt3, double& radius, double& centerX, double& centerY ); - /** Returns true if circle is ordered clockwise*/ + //! Returns true if circle is ordered clockwise static bool circleClockwise( double angle1, double angle2, double angle3 ); - /** Returns true if, in a circle, angle is between angle1 and angle2*/ + //! Returns true if, in a circle, angle is between angle1 and angle2 static bool circleAngleBetween( double angle, double angle1, double angle2, bool clockwise ); /** Returns true if an angle is between angle1 and angle3 on a circle described by @@ -157,30 +157,30 @@ class CORE_EXPORT QgsGeometryUtils */ static bool angleOnCircle( double angle, double angle1, double angle2, double angle3 ); - /** Length of a circular string segment defined by pt1, pt2, pt3*/ + //! Length of a circular string segment defined by pt1, pt2, pt3 static double circleLength( double x1, double y1, double x2, double y2, double x3, double y3 ); - /** Calculates angle of a circular string part defined by pt1, pt2, pt3*/ + //! Calculates angle of a circular string part defined by pt1, pt2, pt3 static double sweepAngle( double centerX, double centerY, double x1, double y1, double x2, double y2, double x3, double y3 ); - /** Calculates midpoint on circle passing through p1 and p2, closest to given coordinate*/ + //! Calculates midpoint on circle passing through p1 and p2, closest to given coordinate static bool segmentMidPoint( const QgsPointV2& p1, const QgsPointV2& p2, QgsPointV2& result, double radius, const QgsPointV2& mousePos ); - /** Calculates the direction angle of a circle tangent (clockwise from north in radians)*/ + //! Calculates the direction angle of a circle tangent (clockwise from north in radians) static double circleTangentDirection( const QgsPointV2& tangentPoint, const QgsPointV2& cp1, const QgsPointV2& cp2, const QgsPointV2& cp3 ); /** Returns a list of points contained in a WKT string. */ static QgsPointSequence pointsFromWKT( const QString& wktCoordinateList, bool is3D, bool isMeasure ); - /** Returns a LinearRing { uint32 numPoints; Point points[numPoints]; } */ + //! Returns a LinearRing { uint32 numPoints; Point points[numPoints]; } static void pointsToWKB( QgsWkbPtr &wkb, const QgsPointSequence &points, bool is3D, bool isMeasure ); - /** Returns a WKT coordinate list */ + //! Returns a WKT coordinate list static QString pointsToWKT( const QgsPointSequence &points, int precision, bool is3D, bool isMeasure ); - /** Returns a gml::coordinates DOM element */ + //! Returns a gml::coordinates DOM element static QDomElement pointsToGML2( const QgsPointSequence &points, QDomDocument &doc, int precision, const QString& ns ); - /** Returns a gml::posList DOM element */ + //! Returns a gml::posList DOM element static QDomElement pointsToGML3( const QgsPointSequence &points, QDomDocument &doc, int precision, const QString& ns, bool is3D ); - /** Returns a geoJSON coordinates string */ + //! Returns a geoJSON coordinates string static QString pointsToJSON( const QgsPointSequence &points, int precision ); /** Ensures that an angle is in the range 0 <= angle < 2 pi. @@ -221,7 +221,7 @@ class CORE_EXPORT QgsGeometryUtils */ static double linePerpendicularAngle( double x1, double y1, double x2, double y2 ); - /** Angle between two linear segments*/ + //! Angle between two linear segments static double averageAngle( double x1, double y1, double x2, double y2, double x3, double y3 ); /** Averages two angles, correctly handling negative angles and ensuring the result is between 0 and 2 pi. diff --git a/src/core/geometry/qgsgeos.cpp b/src/core/geometry/qgsgeos.cpp index 55de0a184249..adb28f565ce9 100644 --- a/src/core/geometry/qgsgeos.cpp +++ b/src/core/geometry/qgsgeos.cpp @@ -1942,7 +1942,7 @@ double QgsGeos::lineLocatePoint( const QgsPointV2& point, QString* errorMsg ) co } -/** Extract coordinates of linestring's endpoints. Returns false on error. */ +//! Extract coordinates of linestring's endpoints. Returns false on error. static bool _linestringEndpoints( const GEOSGeometry* linestring, double& x1, double& y1, double& x2, double& y2 ) { const GEOSCoordSequence* coordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, linestring ); @@ -1964,7 +1964,7 @@ static bool _linestringEndpoints( const GEOSGeometry* linestring, double& x1, do } -/** Merge two linestrings if they meet at the given intersection point, return new geometry or null on error. */ +//! Merge two linestrings if they meet at the given intersection point, return new geometry or null on error. static GEOSGeometry* _mergeLinestrings( const GEOSGeometry* line1, const GEOSGeometry* line2, const QgsPoint& interesectionPoint ) { double x1, y1, x2, y2; diff --git a/src/core/geometry/qgsgeos.h b/src/core/geometry/qgsgeos.h index edba090eaf02..d870d8ddffab 100644 --- a/src/core/geometry/qgsgeos.h +++ b/src/core/geometry/qgsgeos.h @@ -38,7 +38,7 @@ class CORE_EXPORT QgsGeos: public QgsGeometryEngine QgsGeos( const QgsAbstractGeometry* geometry, double precision = 0 ); ~QgsGeos(); - /** Removes caches*/ + //! Removes caches void geometryChanged() override; void prepareGeometry() override; diff --git a/src/core/geometry/qgslinestring.h b/src/core/geometry/qgslinestring.h index 1485904a33bc..e487e41cf563 100644 --- a/src/core/geometry/qgslinestring.h +++ b/src/core/geometry/qgslinestring.h @@ -113,7 +113,7 @@ class CORE_EXPORT QgsLineString: public QgsCurve */ void addVertex( const QgsPointV2& pt ); - /** Closes the line string by appending the first point to the end of the line, if it is not already closed.*/ + //! Closes the line string by appending the first point to the end of the line, if it is not already closed. void close(); /** Returns the geometry converted to the more generic curve type QgsCompoundCurve diff --git a/src/core/geometry/qgsmulticurve.h b/src/core/geometry/qgsmulticurve.h index 853fce2a9aa9..dd23fb7c32b3 100644 --- a/src/core/geometry/qgsmulticurve.h +++ b/src/core/geometry/qgsmulticurve.h @@ -40,7 +40,7 @@ class CORE_EXPORT QgsMultiCurve: public QgsGeometryCollection QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; - /** Adds a geometry and takes ownership. Returns true in case of success*/ + //! Adds a geometry and takes ownership. Returns true in case of success virtual bool addGeometry( QgsAbstractGeometry* g ) override; /** Returns a copy of the multi curve, where each component curve has had its line direction reversed. diff --git a/src/core/geometry/qgsmultilinestring.h b/src/core/geometry/qgsmultilinestring.h index ddbda4d9b821..2d2b894875c7 100644 --- a/src/core/geometry/qgsmultilinestring.h +++ b/src/core/geometry/qgsmultilinestring.h @@ -40,7 +40,7 @@ class CORE_EXPORT QgsMultiLineString: public QgsMultiCurve QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; - /** Adds a geometry and takes ownership. Returns true in case of success*/ + //! Adds a geometry and takes ownership. Returns true in case of success virtual bool addGeometry( QgsAbstractGeometry* g ) override; /** Returns the geometry converted to the more generic curve type QgsMultiCurve diff --git a/src/core/geometry/qgsmultipoint.h b/src/core/geometry/qgsmultipoint.h index c3b793ad7635..f6977a3eea41 100644 --- a/src/core/geometry/qgsmultipoint.h +++ b/src/core/geometry/qgsmultipoint.h @@ -41,7 +41,7 @@ class CORE_EXPORT QgsMultiPointV2: public QgsGeometryCollection QString asJSON( int precision = 17 ) const override; - /** Adds a geometry and takes ownership. Returns true in case of success*/ + //! Adds a geometry and takes ownership. Returns true in case of success virtual bool addGeometry( QgsAbstractGeometry* g ) override; virtual QgsAbstractGeometry* boundary() const override; diff --git a/src/core/geometry/qgsmultipolygon.h b/src/core/geometry/qgsmultipolygon.h index faeda2128dfd..8aae2f52d541 100644 --- a/src/core/geometry/qgsmultipolygon.h +++ b/src/core/geometry/qgsmultipolygon.h @@ -40,7 +40,7 @@ class CORE_EXPORT QgsMultiPolygonV2: public QgsMultiSurface QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; - /** Adds a geometry and takes ownership. Returns true in case of success*/ + //! Adds a geometry and takes ownership. Returns true in case of success virtual bool addGeometry( QgsAbstractGeometry* g ) override; /** Returns the geometry converted to the more generic curve type QgsMultiSurface diff --git a/src/core/geometry/qgsmultisurface.h b/src/core/geometry/qgsmultisurface.h index 6a198b70d004..04f982a70a50 100644 --- a/src/core/geometry/qgsmultisurface.h +++ b/src/core/geometry/qgsmultisurface.h @@ -41,7 +41,7 @@ class CORE_EXPORT QgsMultiSurface: public QgsGeometryCollection QString asJSON( int precision = 17 ) const override; - /** Adds a geometry and takes ownership. Returns true in case of success*/ + //! Adds a geometry and takes ownership. Returns true in case of success virtual bool addGeometry( QgsAbstractGeometry* g ) override; virtual QgsAbstractGeometry* boundary() const override; diff --git a/src/core/geometry/qgswkbtypes.h b/src/core/geometry/qgswkbtypes.h index fd2d0df103a6..a4d4f89ccaff 100644 --- a/src/core/geometry/qgswkbtypes.h +++ b/src/core/geometry/qgswkbtypes.h @@ -455,7 +455,7 @@ class CORE_EXPORT QgsWkbTypes return Unknown; } - /** Returns the modified input geometry type according to hasZ / hasM */ + //! Returns the modified input geometry type according to hasZ / hasM static Type zmType( Type type, bool hasZ, bool hasM ) { type = flatType( type ); diff --git a/src/core/gps/gmath.c b/src/core/gps/gmath.c index ad24b9f54643..b02640350a8b 100644 --- a/src/core/gps/gmath.c +++ b/src/core/gps/gmath.c @@ -24,7 +24,7 @@ * */ -/** \file gmath.h */ +//! \file gmath.h #include "gmath.h" @@ -100,8 +100,8 @@ double nmea_meters2dop( double meters ) * \return Distance in meters */ double nmea_distance( - const nmeaPOS *from_pos, /**< From position in radians */ - const nmeaPOS *to_pos /**< To position in radians */ + const nmeaPOS *from_pos, //!< From position in radians + const nmeaPOS *to_pos //!< To position in radians ) { double dist = (( double )NMEA_EARTHRADIUS_M ) * acos( @@ -119,10 +119,10 @@ double nmea_distance( * \return Distance in meters */ double nmea_distance_ellipsoid( - const nmeaPOS *from_pos, /**< From position in radians */ - const nmeaPOS *to_pos, /**< To position in radians */ - double *from_azimuth, /**< (O) azimuth at "from" position in radians */ - double *to_azimuth /**< (O) azimuth at "to" position in radians */ + const nmeaPOS *from_pos, //!< From position in radians + const nmeaPOS *to_pos, //!< To position in radians + double *from_azimuth, //!< (O) azimuth at "from" position in radians + double *to_azimuth //!< (O) azimuth at "to" position in radians ) { /* All variables */ @@ -233,10 +233,10 @@ double nmea_distance_ellipsoid( * \brief Horizontal move of point position */ int nmea_move_horz( - const nmeaPOS *start_pos, /**< Start position in radians */ - nmeaPOS *end_pos, /**< Result position in radians */ - double azimuth, /**< Azimuth (degree) [0, 359] */ - double distance /**< Distance (km) */ + const nmeaPOS *start_pos, //!< Start position in radians + nmeaPOS *end_pos, //!< Result position in radians + double azimuth, //!< Azimuth (degree) [0, 359] + double distance //!< Distance (km) ) { nmeaPOS p1 = *start_pos; @@ -267,11 +267,11 @@ int nmea_move_horz( * http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf */ int nmea_move_horz_ellipsoid( - const nmeaPOS *start_pos, /**< Start position in radians */ - nmeaPOS *end_pos, /**< (O) Result position in radians */ - double azimuth, /**< Azimuth in radians */ - double distance, /**< Distance (km) */ - double *end_azimuth /**< (O) Azimuth at end position in radians */ + const nmeaPOS *start_pos, //!< Start position in radians + nmeaPOS *end_pos, //!< (O) Result position in radians + double azimuth, //!< Azimuth in radians + double distance, //!< Distance (km) + double *end_azimuth //!< (O) Azimuth at end position in radians ) { /* Variables */ diff --git a/src/core/gps/gmath.h b/src/core/gps/gmath.h index 2eac197624b0..dcf062e40edf 100644 --- a/src/core/gps/gmath.h +++ b/src/core/gps/gmath.h @@ -29,14 +29,14 @@ #include "info.h" -#define NMEA_PI (3.141592653589793) /**< PI value */ -#define NMEA_PI180 (NMEA_PI / 180) /**< PI division by 180 */ -#define NMEA_EARTHRADIUS_KM (6378) /**< Earth's mean radius in km */ -#define NMEA_EARTHRADIUS_M (NMEA_EARTHRADIUS_KM * 1000) /**< Earth's mean radius in m */ -#define NMEA_EARTH_SEMIMAJORAXIS_M (6378137.0) /**< Earth's semi-major axis in m according WGS84 */ -#define NMEA_EARTH_SEMIMAJORAXIS_KM (NMEA_EARTHMAJORAXIS_KM / 1000) /**< Earth's semi-major axis in km according WGS 84 */ -#define NMEA_EARTH_FLATTENING (1 / 298.257223563) /**< Earth's flattening according WGS 84 */ -#define NMEA_DOP_FACTOR (5) /**< Factor for translating DOP to meters */ +#define NMEA_PI (3.141592653589793) //!< PI value +#define NMEA_PI180 (NMEA_PI / 180) //!< PI division by 180 +#define NMEA_EARTHRADIUS_KM (6378) //!< Earth's mean radius in km +#define NMEA_EARTHRADIUS_M (NMEA_EARTHRADIUS_KM * 1000) //!< Earth's mean radius in m +#define NMEA_EARTH_SEMIMAJORAXIS_M (6378137.0) //!< Earth's semi-major axis in m according WGS84 +#define NMEA_EARTH_SEMIMAJORAXIS_KM (NMEA_EARTHMAJORAXIS_KM / 1000) //!< Earth's semi-major axis in km according WGS 84 +#define NMEA_EARTH_FLATTENING (1 / 298.257223563) //!< Earth's flattening according WGS 84 +#define NMEA_DOP_FACTOR (5) //!< Factor for translating DOP to meters #ifdef __cplusplus extern "C" diff --git a/src/core/gps/info.h b/src/core/gps/info.h index 2e4fdfbd83e6..c04d4e1b2903 100644 --- a/src/core/gps/info.h +++ b/src/core/gps/info.h @@ -24,7 +24,7 @@ * */ -/** \file */ +//! \file #ifndef NMEA_INFO_H #define NMEA_INFO_H @@ -57,8 +57,8 @@ extern "C" */ typedef struct _nmeaPOS { - double lat; /**< Latitude */ - double lon; /**< Longitude */ + double lat; //!< Latitude + double lon; //!< Longitude } nmeaPOS; @@ -69,11 +69,11 @@ extern "C" */ typedef struct _nmeaSATELLITE { - int id; /**< Satellite PRN number */ - int in_use; /**< Used in position fix */ - int elv; /**< Elevation in degrees, 90 maximum */ - int azimuth; /**< Azimuth, degrees from true north, 000 to 359 */ - int sig; /**< Signal, 00-99 dB */ + int id; //!< Satellite PRN number + int in_use; //!< Used in position fix + int elv; //!< Elevation in degrees, 90 maximum + int azimuth; //!< Azimuth, degrees from true north, 000 to 359 + int sig; //!< Signal, 00-99 dB } nmeaSATELLITE; @@ -84,9 +84,9 @@ extern "C" */ typedef struct _nmeaSATINFO { - int inuse; /**< Number of satellites in use (not those in view) */ - int inview; /**< Total number of satellites in view */ - nmeaSATELLITE sat[NMEA_MAXSAT]; /**< Satellites information */ + int inuse; //!< Number of satellites in use (not those in view) + int inview; //!< Total number of satellites in view + nmeaSATELLITE sat[NMEA_MAXSAT]; //!< Satellites information } nmeaSATINFO; @@ -98,25 +98,25 @@ extern "C" */ typedef struct _nmeaINFO { - int smask; /**< Mask specifying types of packages from which data have been obtained */ + int smask; //!< Mask specifying types of packages from which data have been obtained - nmeaTIME utc; /**< UTC of position */ + nmeaTIME utc; //!< UTC of position - int sig; /**< GPS quality indicator (0 = Invalid; 1 = Fix; 2 = Differential, 3 = Sensitive) */ - int fix; /**< Operating mode, used for navigation (1 = Fix not available; 2 = 2D; 3 = 3D) */ + int sig; //!< GPS quality indicator (0 = Invalid; 1 = Fix; 2 = Differential, 3 = Sensitive) + int fix; //!< Operating mode, used for navigation (1 = Fix not available; 2 = 2D; 3 = 3D) - double PDOP; /**< Position Dilution Of Precision */ - double HDOP; /**< Horizontal Dilution Of Precision */ - double VDOP; /**< Vertical Dilution Of Precision */ + double PDOP; //!< Position Dilution Of Precision + double HDOP; //!< Horizontal Dilution Of Precision + double VDOP; //!< Vertical Dilution Of Precision - double lat; /**< Latitude in NDEG - +/-[degree][min].[sec/60] */ - double lon; /**< Longitude in NDEG - +/-[degree][min].[sec/60] */ - double elv; /**< Antenna altitude above/below mean sea level (geoid) in meters */ - double speed; /**< Speed over the ground in kilometers/hour */ - double direction; /**< Track angle in degrees True */ - double declination; /**< Magnetic variation degrees (Easterly var. subtracts from true course) */ + double lat; //!< Latitude in NDEG - +/-[degree][min].[sec/60] + double lon; //!< Longitude in NDEG - +/-[degree][min].[sec/60] + double elv; //!< Antenna altitude above/below mean sea level (geoid) in meters + double speed; //!< Speed over the ground in kilometers/hour + double direction; //!< Track angle in degrees True + double declination; //!< Magnetic variation degrees (Easterly var. subtracts from true course) - nmeaSATINFO satinfo; /**< Satellites information */ + nmeaSATINFO satinfo; //!< Satellites information } nmeaINFO; diff --git a/src/core/gps/nmeatime.h b/src/core/gps/nmeatime.h index 14f0ae5dd570..dbd5207301e5 100644 --- a/src/core/gps/nmeatime.h +++ b/src/core/gps/nmeatime.h @@ -24,7 +24,7 @@ * */ -/** \file */ +//! \file #ifndef NMEA_TIME_H #define NMEA_TIME_H @@ -42,13 +42,13 @@ extern "C" */ typedef struct _nmeaTIME { - int year; /**< Years since 1900 */ - int mon; /**< Months since January - [0,11] */ - int day; /**< Day of the month - [1,31] */ - int hour; /**< Hours since midnight - [0,23] */ - int min; /**< Minutes after the hour - [0,59] */ - int sec; /**< Seconds after the minute - [0,59] */ - int msec; /**< Thousandths part of second - [0,999] */ + int year; //!< Years since 1900 + int mon; //!< Months since January - [0,11] + int day; //!< Day of the month - [1,31] + int hour; //!< Hours since midnight - [0,23] + int min; //!< Minutes after the hour - [0,59] + int sec; //!< Seconds after the minute - [0,59] + int msec; //!< Thousandths part of second - [0,999] } nmeaTIME; diff --git a/src/core/gps/qgsgpsconnection.h b/src/core/gps/qgsgpsconnection.h index 625520b6ac49..d333e78eb846 100644 --- a/src/core/gps/qgsgpsconnection.h +++ b/src/core/gps/qgsgpsconnection.h @@ -76,18 +76,18 @@ class CORE_EXPORT QgsGPSConnection : public QObject */ QgsGPSConnection( QIODevice* dev ); virtual ~QgsGPSConnection(); - /** Opens connection to device*/ + //! Opens connection to device bool connect(); - /** Closes connection to device*/ + //! Closes connection to device bool close(); - /** Sets the GPS source. The class takes ownership of the device class*/ + //! Sets the GPS source. The class takes ownership of the device class void setSource( QIODevice* source ); - /** Returns the status. Possible state are not connected, connected, data received*/ + //! Returns the status. Possible state are not connected, connected, data received Status status() const { return mStatus; } - /** Returns the current gps information (lat, lon, etc.)*/ + //! Returns the current gps information (lat, lon, etc.) QgsGPSInformation currentGPSInformation() const { return mLastGPSInformation; } signals: @@ -95,20 +95,20 @@ class CORE_EXPORT QgsGPSConnection : public QObject void nmeaSentenceReceived( const QString& substring ); // added to capture 'raw' data protected: - /** Data source (e.g. serial device, socket, file,...)*/ + //! Data source (e.g. serial device, socket, file,...) QIODevice* mSource; - /** Last state of the gps related variables (e.g. position, time, ...)*/ + //! Last state of the gps related variables (e.g. position, time, ...) QgsGPSInformation mLastGPSInformation; - /** Connection status*/ + //! Connection status Status mStatus; private: - /** Closes and deletes mSource*/ + //! Closes and deletes mSource void cleanupSource(); void clearLastGPSInformation(); protected slots: - /** Parse available data source content*/ + //! Parse available data source content virtual void parseData() = 0; }; diff --git a/src/core/gps/qgsgpsconnectionregistry.h b/src/core/gps/qgsgpsconnectionregistry.h index 6f8384f5842a..c9abd7e33697 100644 --- a/src/core/gps/qgsgpsconnectionregistry.h +++ b/src/core/gps/qgsgpsconnectionregistry.h @@ -32,9 +32,9 @@ class CORE_EXPORT QgsGPSConnectionRegistry static QgsGPSConnectionRegistry* instance(); ~QgsGPSConnectionRegistry(); - /** Inserts a connection into the registry. The connection is owned by the registry class until it is unregistered again*/ + //! Inserts a connection into the registry. The connection is owned by the registry class until it is unregistered again void registerConnection( QgsGPSConnection* c ); - /** Unregisters connection. The registry does no longer own the connection*/ + //! Unregisters connection. The registry does no longer own the connection void unregisterConnection( QgsGPSConnection* c ); QList< QgsGPSConnection *> connectionList() const; diff --git a/src/core/gps/qgsnmeaconnection.h b/src/core/gps/qgsnmeaconnection.h index ef8523aa8e6d..5fdbef804893 100644 --- a/src/core/gps/qgsnmeaconnection.h +++ b/src/core/gps/qgsnmeaconnection.h @@ -31,13 +31,13 @@ class CORE_EXPORT QgsNMEAConnection: public QgsGPSConnection ~QgsNMEAConnection(); protected slots: - /** Parse available data source content*/ + //! Parse available data source content void parseData() override; protected: - /** Store data from the device before it is processed*/ + //! Store data from the device before it is processed QString mStringBuffer; - /** Splits mStringBuffer into sentences and calls libnmea*/ + //! Splits mStringBuffer into sentences and calls libnmea void processStringBuffer(); //handle the different sentence type void processGGASentence( const char* data, int len ); diff --git a/src/core/gps/qgsqtlocationconnection.h b/src/core/gps/qgsqtlocationconnection.h index 5fb03002c156..13855fbf9137 100644 --- a/src/core/gps/qgsqtlocationconnection.h +++ b/src/core/gps/qgsqtlocationconnection.h @@ -47,10 +47,10 @@ class CORE_EXPORT QgsQtLocationConnection: public QgsGPSConnection ~QgsQtLocationConnection(); protected slots: - /** Needed to make QtLocation detected*/ + //! Needed to make QtLocation detected void broadcastConnectionAvailable(); - /** Parse available data source content*/ + //! Parse available data source content void parseData(); /** Called when the position updated. diff --git a/src/core/gps/sentence.h b/src/core/gps/sentence.h index 6471c3352bb1..a7e783d5a8de 100644 --- a/src/core/gps/sentence.h +++ b/src/core/gps/sentence.h @@ -8,7 +8,7 @@ * */ -/** \file */ +//! \file #ifndef NMEA_SENTENCE_H #define NMEA_SENTENCE_H @@ -25,12 +25,12 @@ extern "C" */ enum nmeaPACKTYPE { - GPNON = 0x0000, /**< Unknown packet type. */ - GPGGA = 0x0001, /**< GGA - Essential fix data which provide 3D location and accuracy data. */ - GPGSA = 0x0002, /**< GSA - GPS receiver operating mode, SVs used for navigation, and DOP values. */ - GPGSV = 0x0004, /**< GSV - Number of SVs in view, PRN numbers, elevation, azimuth & SNR values. */ - GPRMC = 0x0008, /**< RMC - Recommended Minimum Specific GPS/TRANSIT Data. */ - GPVTG = 0x0010 /**< VTG - Actual track made good and speed over ground. */ + GPNON = 0x0000, //!< Unknown packet type. + GPGGA = 0x0001, //!< GGA - Essential fix data which provide 3D location and accuracy data. + GPGSA = 0x0002, //!< GSA - GPS receiver operating mode, SVs used for navigation, and DOP values. + GPGSV = 0x0004, //!< GSV - Number of SVs in view, PRN numbers, elevation, azimuth & SNR values. + GPRMC = 0x0008, //!< RMC - Recommended Minimum Specific GPS/TRANSIT Data. + GPVTG = 0x0010 //!< VTG - Actual track made good and speed over ground. }; /** @@ -38,20 +38,20 @@ extern "C" */ typedef struct _nmeaGPGGA { - nmeaTIME utc; /**< UTC of position (just time) */ - double lat; /**< Latitude in NDEG - [degree][min].[sec/60] */ - char ns; /**< [N]orth or [S]outh */ - double lon; /**< Longitude in NDEG - [degree][min].[sec/60] */ - char ew; /**< [E]ast or [W]est */ - int sig; /**< GPS quality indicator (0 = Invalid; 1 = Fix; 2 = Differential, 3 = Sensitive) */ - int satinuse; /**< Number of satellites in use (not those in view) */ - double HDOP; /**< Horizontal dilution of precision */ - double elv; /**< Antenna altitude above/below mean sea level (geoid) */ - char elv_units; /**< [M]eters (Antenna height unit) */ - double diff; /**< Geoidal separation (Diff. between WGS-84 earth ellipsoid and mean sea level. '-' = geoid is below WGS-84 ellipsoid) */ - char diff_units; /**< [M]eters (Units of geoidal separation) */ - double dgps_age; /**< Time in seconds since last DGPS update */ - int dgps_sid; /**< DGPS station ID number */ + nmeaTIME utc; //!< UTC of position (just time) + double lat; //!< Latitude in NDEG - [degree][min].[sec/60] + char ns; //!< [N]orth or [S]outh + double lon; //!< Longitude in NDEG - [degree][min].[sec/60] + char ew; //!< [E]ast or [W]est + int sig; //!< GPS quality indicator (0 = Invalid; 1 = Fix; 2 = Differential, 3 = Sensitive) + int satinuse; //!< Number of satellites in use (not those in view) + double HDOP; //!< Horizontal dilution of precision + double elv; //!< Antenna altitude above/below mean sea level (geoid) + char elv_units; //!< [M]eters (Antenna height unit) + double diff; //!< Geoidal separation (Diff. between WGS-84 earth ellipsoid and mean sea level. '-' = geoid is below WGS-84 ellipsoid) + char diff_units; //!< [M]eters (Units of geoidal separation) + double dgps_age; //!< Time in seconds since last DGPS update + int dgps_sid; //!< DGPS station ID number } nmeaGPGGA; @@ -60,12 +60,12 @@ extern "C" */ typedef struct _nmeaGPGSA { - char fix_mode; /**< Mode (M = Manual, forced to operate in 2D or 3D; A = Automatic, 3D/2D) */ - int fix_type; /**< Type, used for navigation (1 = Fix not available; 2 = 2D; 3 = 3D) */ - int sat_prn[NMEA_MAXSAT]; /**< PRNs of satellites used in position fix (null for unused fields) */ - double PDOP; /**< Dilution of precision */ - double HDOP; /**< Horizontal dilution of precision */ - double VDOP; /**< Vertical dilution of precision */ + char fix_mode; //!< Mode (M = Manual, forced to operate in 2D or 3D; A = Automatic, 3D/2D) + int fix_type; //!< Type, used for navigation (1 = Fix not available; 2 = 2D; 3 = 3D) + int sat_prn[NMEA_MAXSAT]; //!< PRNs of satellites used in position fix (null for unused fields) + double PDOP; //!< Dilution of precision + double HDOP; //!< Horizontal dilution of precision + double VDOP; //!< Vertical dilution of precision } nmeaGPGSA; @@ -74,9 +74,9 @@ extern "C" */ typedef struct _nmeaGPGSV { - int pack_count; /**< Total number of messages of this type in this cycle */ - int pack_index; /**< Message number */ - int sat_count; /**< Total number of satellites in view */ + int pack_count; //!< Total number of messages of this type in this cycle + int pack_index; //!< Message number + int sat_count; //!< Total number of satellites in view nmeaSATELLITE sat_data[NMEA_SATINPACK]; } nmeaGPGSV; @@ -86,17 +86,17 @@ extern "C" */ typedef struct _nmeaGPRMC { - nmeaTIME utc; /**< UTC of position */ - char status; /**< Status (A = active or V = void) */ - double lat; /**< Latitude in NDEG - [degree][min].[sec/60] */ - char ns; /**< [N]orth or [S]outh */ - double lon; /**< Longitude in NDEG - [degree][min].[sec/60] */ - char ew; /**< [E]ast or [W]est */ - double speed; /**< Speed over the ground in knots */ - double direction; /**< Track angle in degrees True */ - double declination; /**< Magnetic variation degrees (Easterly var. subtracts from true course) */ - char declin_ew; /**< [E]ast or [W]est */ - char mode; /**< Mode indicator of fix type (A = autonomous, D = differential, E = estimated, N = not valid, S = simulator) */ + nmeaTIME utc; //!< UTC of position + char status; //!< Status (A = active or V = void) + double lat; //!< Latitude in NDEG - [degree][min].[sec/60] + char ns; //!< [N]orth or [S]outh + double lon; //!< Longitude in NDEG - [degree][min].[sec/60] + char ew; //!< [E]ast or [W]est + double speed; //!< Speed over the ground in knots + double direction; //!< Track angle in degrees True + double declination; //!< Magnetic variation degrees (Easterly var. subtracts from true course) + char declin_ew; //!< [E]ast or [W]est + char mode; //!< Mode indicator of fix type (A = autonomous, D = differential, E = estimated, N = not valid, S = simulator) } nmeaGPRMC; @@ -105,14 +105,14 @@ extern "C" */ typedef struct _nmeaGPVTG { - double dir; /**< True track made good (degrees) */ - char dir_t; /**< Fixed text 'T' indicates that track made good is relative to true north */ - double dec; /**< Magnetic track made good */ - char dec_m; /**< Fixed text 'M' */ - double spn; /**< Ground speed, knots */ - char spn_n; /**< Fixed text 'N' indicates that speed over ground is in knots */ - double spk; /**< Ground speed, kilometers per hour */ - char spk_k; /**< Fixed text 'K' indicates that speed over ground is in kilometers/hour */ + double dir; //!< True track made good (degrees) + char dir_t; //!< Fixed text 'T' indicates that track made good is relative to true north + double dec; //!< Magnetic track made good + char dec_m; //!< Fixed text 'M' + double spn; //!< Ground speed, knots + char spn_n; //!< Fixed text 'N' indicates that speed over ground is in knots + double spk; //!< Ground speed, kilometers per hour + char spk_k; //!< Fixed text 'K' indicates that speed over ground is in kilometers/hour } nmeaGPVTG; diff --git a/src/core/gps/time.c b/src/core/gps/time.c index 0b0b1d574668..518e0a6ae4b2 100644 --- a/src/core/gps/time.c +++ b/src/core/gps/time.c @@ -24,7 +24,7 @@ * */ -/** \file nmeatime.h */ +//! \file nmeatime.h #include "nmeatime.h" diff --git a/src/core/gps/tok.c b/src/core/gps/tok.c index 8a6d31dd3c89..ed34278ec2ad 100644 --- a/src/core/gps/tok.c +++ b/src/core/gps/tok.c @@ -24,7 +24,7 @@ * */ -/** \file tok.h */ +//! \file tok.h #include "tok.h" diff --git a/src/core/gps/units.h b/src/core/gps/units.h index 454465a14378..1f728f2b7897 100644 --- a/src/core/gps/units.h +++ b/src/core/gps/units.h @@ -33,14 +33,14 @@ * Distance units */ -#define NMEA_TUD_YARDS (1.0936) /**< Yeards, meter * NMEA_TUD_YARDS = yard */ -#define NMEA_TUD_KNOTS (1.852) /**< Knots, kilometer / NMEA_TUD_KNOTS = knot */ -#define NMEA_TUD_MILES (1.609) /**< Miles, kilometer / NMEA_TUD_MILES = mile */ +#define NMEA_TUD_YARDS (1.0936) //!< Yeards, meter * NMEA_TUD_YARDS = yard +#define NMEA_TUD_KNOTS (1.852) //!< Knots, kilometer / NMEA_TUD_KNOTS = knot +#define NMEA_TUD_MILES (1.609) //!< Miles, kilometer / NMEA_TUD_MILES = mile /* * Speed units */ -#define NMEA_TUS_MS (3.6) /**< Meters per seconds, (k/h) / NMEA_TUS_MS= (m/s) */ +#define NMEA_TUS_MS (3.6) //!< Meters per seconds, (k/h) / NMEA_TUS_MS= (m/s) #endif /* __NMEA_UNITS_H__ */ diff --git a/src/core/layertree/qgslayertreemodel.h b/src/core/layertree/qgslayertreemodel.h index 575e1875a47b..fcd4b3847a66 100644 --- a/src/core/layertree/qgslayertreemodel.h +++ b/src/core/layertree/qgslayertreemodel.h @@ -79,7 +79,7 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel ShowLegend = 0x0001, //!< Add legend nodes for layer nodes ShowRasterPreviewIcon = 0x0002, //!< Will use real preview of raster layer as icon (may be slow) ShowLegendAsTree = 0x0004, //!< For legends that support it, will show them in a tree instead of a list (needs also ShowLegend). Added in 2.8 - DeferredLegendInvalidation = 0x0008, //!< defer legend model invalidation + DeferredLegendInvalidation = 0x0008, //!< Defer legend model invalidation UseEmbeddedWidgets = 0x0010, //!< Layer nodes may optionally include extra embedded widgets (if used in QgsLayerTreeView). Added in 2.16 // behavioral flags @@ -259,7 +259,7 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel QVariant legendNodeData( QgsLayerTreeModelLegendNode* node, int role ) const; Qt::ItemFlags legendNodeFlags( QgsLayerTreeModelLegendNode* node ) const; bool legendEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; - /** Return legend node that may be embbeded in parent (i.e. its icon will be used for layer's icon). */ + //! Return legend node that may be embbeded in parent (i.e. its icon will be used for layer's icon). QgsLayerTreeModelLegendNode* legendNodeEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; QIcon legendIconEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; void legendCleanup(); diff --git a/src/core/layertree/qgslayertreemodellegendnode.h b/src/core/layertree/qgslayertreemodellegendnode.h index 138574f8ec30..69c863fd0327 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.h +++ b/src/core/layertree/qgslayertreemodellegendnode.h @@ -48,24 +48,24 @@ class CORE_EXPORT QgsLayerTreeModelLegendNode : public QObject enum LegendNodeRoles { - RuleKeyRole = Qt::UserRole, //!< rule key of the node (QString) - SymbolLegacyRuleKeyRole, //!< for QgsSymbolLegendNode only - legacy rule key (void ptr, to be cast to QgsSymbol ptr) - ParentRuleKeyRole //!< rule key of the parent legend node - for legends with tree hierarchy (QString). Added in 2.8 + RuleKeyRole = Qt::UserRole, //!< Rule key of the node (QString) + SymbolLegacyRuleKeyRole, //!< For QgsSymbolLegendNode only - legacy rule key (void ptr, to be cast to QgsSymbol ptr) + ParentRuleKeyRole //!< Rule key of the parent legend node - for legends with tree hierarchy (QString). Added in 2.8 }; - /** Return pointer to the parent layer node */ + //! Return pointer to the parent layer node QgsLayerTreeLayer* layerNode() const { return mLayerNode; } - /** Return pointer to model owning this legend node */ + //! Return pointer to model owning this legend node QgsLayerTreeModel* model() const; - /** Return item flags associated with the item. Default implementation returns Qt::ItemIsEnabled. */ + //! Return item flags associated with the item. Default implementation returns Qt::ItemIsEnabled. virtual Qt::ItemFlags flags() const; - /** Return data associated with the item. Must be implemented in derived class. */ + //! Return data associated with the item. Must be implemented in derived class. virtual QVariant data( int role ) const = 0; - /** Set some data associated with the item. Default implementation does nothing and returns false. */ + //! Set some data associated with the item. Default implementation does nothing and returns false. virtual bool setData( const QVariant& value, int role ); virtual bool isEmbeddedInParent() const { return mEmbeddedInParent; } @@ -126,7 +126,7 @@ class CORE_EXPORT QgsLayerTreeModelLegendNode : public QObject void dataChanged(); protected: - /** Construct the node with pointer to its parent layer node */ + //! Construct the node with pointer to its parent layer node explicit QgsLayerTreeModelLegendNode( QgsLayerTreeLayer* nodeL, QObject* parent = nullptr ); protected: diff --git a/src/core/layertree/qgslayertreenode.h b/src/core/layertree/qgslayertreenode.h index f8bf074a6e29..ac2f848f67cf 100644 --- a/src/core/layertree/qgslayertreenode.h +++ b/src/core/layertree/qgslayertreenode.h @@ -70,8 +70,8 @@ class CORE_EXPORT QgsLayerTreeNode : public QObject //! Enumeration of possible tree node types enum NodeType { - NodeGroup, //!< container of other groups and layers - NodeLayer //!< leaf node pointing to a layer + NodeGroup, //!< Container of other groups and layers + NodeLayer //!< Leaf node pointing to a layer }; ~QgsLayerTreeNode(); @@ -99,15 +99,15 @@ class CORE_EXPORT QgsLayerTreeNode : public QObject //! Set whether the node should be shown as expanded or collapsed in GUI void setExpanded( bool expanded ); - /** Set a custom property for the node. Properties are stored in a map and saved in project file. */ + //! Set a custom property for the node. Properties are stored in a map and saved in project file. void setCustomProperty( const QString &key, const QVariant &value ); - /** Read a custom property from layer. Properties are stored in a map and saved in project file. */ + //! Read a custom property from layer. Properties are stored in a map and saved in project file. QVariant customProperty( const QString &key, const QVariant &defaultValue = QVariant() ) const; - /** Remove a custom property from layer. Properties are stored in a map and saved in project file. */ + //! Remove a custom property from layer. Properties are stored in a map and saved in project file. void removeCustomProperty( const QString &key ); - /** Return list of keys stored in custom properties */ + //! Return list of keys stored in custom properties QStringList customProperties() const; - /** Remove a child from a node */ + //! Remove a child from a node bool takeChild( QgsLayerTreeNode *node ); signals: diff --git a/src/core/pal/costcalculator.h b/src/core/pal/costcalculator.h index 9a29b8316e80..834de08a31bc 100644 --- a/src/core/pal/costcalculator.h +++ b/src/core/pal/costcalculator.h @@ -32,15 +32,15 @@ namespace pal class CostCalculator { public: - /** Increase candidate's cost according to its collision with passed feature */ + //! Increase candidate's cost according to its collision with passed feature static void addObstacleCostPenalty( LabelPosition* lp, pal::FeaturePart *obstacle ); static void setPolygonCandidatesCost( int nblp, QList< LabelPosition* >& lPos, RTree *obstacles, double bbx[4], double bby[4] ); - /** Set cost to the smallest distance between lPos's centroid and a polygon stored in geoetry field */ + //! Set cost to the smallest distance between lPos's centroid and a polygon stored in geoetry field static void setCandidateCostFromPolygon( LabelPosition* lp, RTree *obstacles, double bbx[4], double bby[4] ); - /** Sort candidates by costs, skip the worse ones, evaluate polygon candidates */ + //! Sort candidates by costs, skip the worse ones, evaluate polygon candidates static int finalizeCandidatesCosts( Feats* feat, int max_p, RTree *obstacles, double bbx[4], double bby[4] ); /** Sorts label candidates in ascending order of cost diff --git a/src/core/pal/feature.h b/src/core/pal/feature.h index 5df362e73a44..36b181f5deb2 100644 --- a/src/core/pal/feature.h +++ b/src/core/pal/feature.h @@ -46,7 +46,7 @@ namespace pal { - /** Optional additional info about label (for curved labels) */ + //! Optional additional info about label (for curved labels) class CORE_EXPORT LabelInfo { public: @@ -251,7 +251,7 @@ namespace pal //! Get hole (inner ring) - considered as obstacle FeaturePart* getSelfObstacle( int i ) { return mHoles.at( i ); } - /** Check whether this part is connected with some other part */ + //! Check whether this part is connected with some other part bool isConnected( FeaturePart* p2 ); /** Merge other (connected) part with this one and save the result in this part (other is unchanged). @@ -279,7 +279,7 @@ namespace pal QgsLabelFeature* mLF; QList mHoles; - /** \brief read coordinates from a GEOS geom */ + //! \brief read coordinates from a GEOS geom void extractCoords( const GEOSGeometry* geom ); private: diff --git a/src/core/pal/labelposition.h b/src/core/pal/labelposition.h index 41a820d82893..7a17211f29d2 100644 --- a/src/core/pal/labelposition.h +++ b/src/core/pal/labelposition.h @@ -90,7 +90,7 @@ namespace pal double alpha, double cost, FeaturePart *feature, bool isReversed = false, Quadrant quadrant = QuadrantOver ); - /** Copy constructor */ + //! Copy constructor LabelPosition( const LabelPosition& other ); ~LabelPosition() { delete nextPart; } @@ -124,16 +124,16 @@ namespace pal */ bool isInConflict( LabelPosition *ls ); - /** Return bounding box - amin: xmin,ymin - amax: xmax,ymax */ + //! Return bounding box - amin: xmin,ymin - amax: xmax,ymax void getBoundingBox( double amin[2], double amax[2] ) const; - /** Get distance from this label to a point. If point lies inside, returns negative number. */ + //! Get distance from this label to a point. If point lies inside, returns negative number. double getDistanceToPoint( double xp, double yp ) const; - /** Returns true if this label crosses the specified line */ + //! Returns true if this label crosses the specified line bool crossesLine( PointSet* line ) const; - /** Returns true if this label crosses the boundary of the specified polygon */ + //! Returns true if this label crosses the boundary of the specified polygon bool crossesBoundary( PointSet* polygon ) const; /** Returns cost of position intersection with polygon (testing area of intersection and center). @@ -145,7 +145,7 @@ namespace pal */ bool intersectsWithPolygon( PointSet* polygon ) const; - /** Shift the label by specified offset */ + //! Shift the label by specified offset void offsetPosition( double xOffset, double yOffset ); /** \brief return id @@ -195,7 +195,7 @@ namespace pal */ bool conflictsWithObstacle() const { return mHasObstacleConflict; } - /** Make sure the cost is less than 1 */ + //! Make sure the cost is less than 1 void validateCost(); /** @@ -243,7 +243,7 @@ namespace pal FeaturePart *obstacle; } PruneCtx; - /** Check whether the candidate in ctx overlap with obstacle feat */ + //! Check whether the candidate in ctx overlap with obstacle feat static bool pruneCallback( LabelPosition *candidatePosition, void *ctx ); // for counting number of overlaps diff --git a/src/core/pal/layer.h b/src/core/pal/layer.h index b3a7105fa8d6..222990d28af1 100644 --- a/src/core/pal/layer.h +++ b/src/core/pal/layer.h @@ -82,7 +82,7 @@ namespace pal */ int featureCount() { return mHashtable.size(); } - /** Returns pointer to the associated provider */ + //! Returns pointer to the associated provider QgsAbstractLabelProvider* provider() const { return mProvider; } /** Returns the layer's name. @@ -228,7 +228,7 @@ namespace pal */ bool registerFeature( QgsLabelFeature* label ); - /** Join connected features with the same label text */ + //! Join connected features with the same label text void joinConnectedFeatures(); /** Returns the connected feature ID for a label feature ID, which is unique for all features @@ -237,17 +237,17 @@ namespace pal */ int connectedFeatureId( QgsFeatureId featureId ) const; - /** Chop layer features at the repeat distance **/ + //! Chop layer features at the repeat distance * void chopFeaturesAtRepeatDistance(); protected: QgsAbstractLabelProvider* mProvider; // not owned QString mName; - /** List of feature parts */ + //! List of feature parts QLinkedList mFeatureParts; - /** List of obstacle parts */ + //! List of obstacle parts QList mObstacleParts; Pal *pal; @@ -260,7 +260,7 @@ namespace pal bool mDisplayAll; bool mCentroidInside; - /** Optional flags used for some placement methods */ + //! Optional flags used for some placement methods QgsPalLayerSettings::Placement mArrangement; LineArrangementFlags mArrangementFlags; LabelMode mMode; @@ -297,10 +297,10 @@ namespace pal */ Layer( QgsAbstractLabelProvider* provider, const QString& name, QgsPalLayerSettings::Placement arrangement, double defaultPriority, bool active, bool toLabel, Pal *pal, bool displayAll = false ); - /** Add newly created feature part into r tree and to the list */ + //! Add newly created feature part into r tree and to the list void addFeaturePart( FeaturePart* fpart, const QString &labelText = QString() ); - /** Add newly created obstacle part into r tree and to the list */ + //! Add newly created obstacle part into r tree and to the list void addObstaclePart( FeaturePart* fpart ); }; diff --git a/src/core/pal/pal.h b/src/core/pal/pal.h index efaf8787b02c..ec79bfcaeb34 100644 --- a/src/core/pal/pal.h +++ b/src/core/pal/pal.h @@ -44,7 +44,7 @@ class QgsAbstractLabelProvider; namespace pal { - /** Get GEOS context handle to be used in all GEOS library calls with reentrant API */ + //! Get GEOS context handle to be used in all GEOS library calls with reentrant API GEOSContextHandle_t geosContext(); class Layer; @@ -53,17 +53,17 @@ namespace pal class Problem; class PointSet; - /** Search method to use */ + //! Search method to use enum SearchMethod { - CHAIN = 0, /**< is the worst but fastest method */ - POPMUSIC_TABU_CHAIN = 1, /**< is the best but slowest */ - POPMUSIC_TABU = 2, /**< is a little bit better than CHAIN but slower*/ - POPMUSIC_CHAIN = 3, /**< is slower and best than TABU, worse and faster than TABU_CHAIN */ - FALP = 4 /** only initial solution */ + CHAIN = 0, //!< Is the worst but fastest method + POPMUSIC_TABU_CHAIN = 1, //!< Is the best but slowest + POPMUSIC_TABU = 2, //!< Is a little bit better than CHAIN but slower + POPMUSIC_CHAIN = 3, //!< Is slower and best than TABU, worse and faster than TABU_CHAIN + FALP = 4 //! only initial solution }; - /** Enumeration line arrangement flags. Flags can be combined. */ + //! Enumeration line arrangement flags. Flags can be combined. enum LineArrangementFlag { FLAG_ON_LINE = 1, @@ -137,10 +137,10 @@ namespace pal typedef bool ( *FnIsCancelled )( void* ctx ); - /** Register a function that returns whether this job has been cancelled - PAL calls it during the computation */ + //! Register a function that returns whether this job has been cancelled - PAL calls it during the computation void registerCancellationCallback( FnIsCancelled fnCancelled, void* context ); - /** Check whether the job has been cancelled */ + //! Check whether the job has been cancelled inline bool isCancelled() { return fnIsCancelled ? fnIsCancelled( fnIsCancelledContext ) : false; } Problem* extractProblem( double bbox[4] ); @@ -257,9 +257,9 @@ namespace pal */ bool showPartial; - /** Callback that may be called from PAL to check whether the job has not been cancelled in meanwhile */ + //! Callback that may be called from PAL to check whether the job has not been cancelled in meanwhile FnIsCancelled fnIsCancelled; - /** Application-specific context for the cancellation check function */ + //! Application-specific context for the cancellation check function void* fnIsCancelledContext; /** diff --git a/src/core/pal/pointset.h b/src/core/pal/pointset.h index 4d7c89774664..19f1df6e96e5 100644 --- a/src/core/pal/pointset.h +++ b/src/core/pal/pointset.h @@ -122,7 +122,7 @@ namespace pal max[1] = ymax; } - /** Returns NULL if this isn't a hole. Otherwise returns pointer to parent pointset. */ + //! Returns NULL if this isn't a hole. Otherwise returns pointer to parent pointset. PointSet* getHoleOf() { return holeOf; } int getNumPoints() const { return nbPoints; } diff --git a/src/core/qgis.h b/src/core/qgis.h index 3024ff86145e..d2d45d6c607d 100644 --- a/src/core/qgis.h +++ b/src/core/qgis.h @@ -290,21 +290,21 @@ void CORE_EXPORT qgsFree( void *ptr ); extern CORE_EXPORT const QString GEOWKT; extern CORE_EXPORT const QString PROJECT_SCALES; -/** PROJ4 string that represents a geographic coord sys */ +//! PROJ4 string that represents a geographic coord sys extern CORE_EXPORT const QString GEOPROJ4; -/** Magic number for a geographic coord sys in POSTGIS SRID */ +//! Magic number for a geographic coord sys in POSTGIS SRID const long GEOSRID = 4326; -/** Magic number for a geographic coord sys in QGIS srs.db tbl_srs.srs_id */ +//! Magic number for a geographic coord sys in QGIS srs.db tbl_srs.srs_id const long GEOCRS_ID = 3452; -/** Magic number for a geographic coord sys in EpsgCrsId ID format */ +//! Magic number for a geographic coord sys in EpsgCrsId ID format const long GEO_EPSG_CRS_ID = 4326; -/** Geographic coord sys from EPSG authority */ +//! Geographic coord sys from EPSG authority extern CORE_EXPORT const QString GEO_EPSG_CRS_AUTHID; -/** The length of the string "+proj=" */ +//! The length of the string "+proj=" const int PROJ_PREFIX_LEN = 6; -/** The length of the string "+ellps=" */ +//! The length of the string "+ellps=" const int ELLPS_PREFIX_LEN = 7; -/** The length of the string "+lat_1=" */ +//! The length of the string "+lat_1=" const int LAT_PREFIX_LEN = 7; /** Magick number that determines whether a projection crsid is a system (srs.db) * or user (~/.qgis.qgis.db) defined projection. */ @@ -317,11 +317,11 @@ extern CORE_EXPORT const QString GEO_NONE; // Constants for point symbols // -/** Magic number that determines the default point size for point symbols */ +//! Magic number that determines the default point size for point symbols const double DEFAULT_POINT_SIZE = 2.0; const double DEFAULT_LINE_WIDTH = 0.26; -/** Default snapping tolerance for segments */ +//! Default snapping tolerance for segments const double DEFAULT_SEGMENT_EPSILON = 1e-8; typedef QMap QgsStringMap; diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 1502c107cc23..0fca3df2926c 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -583,13 +583,13 @@ QString QgsApplication::donorsFilePath() return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/DONORS" ); } -/** Returns the path to the sponsors file. */ +//! Returns the path to the sponsors file. QString QgsApplication::translatorsFilePath() { return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/TRANSLATORS" ); } -/** Returns the path to the licence file. */ +//! Returns the path to the licence file. QString QgsApplication::licenceFilePath() { return ABISYM( mPkgDataPath ) + QStringLiteral( "/doc/LICENSE" ); diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index cb468852a3fd..064060ae45d7 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -108,10 +108,10 @@ class CORE_EXPORT QgsApplication : public QApplication * @note this function was added in version 2.7 */ static QString developersMapFilePath(); - /** Returns the path to the sponsors file. */ + //! Returns the path to the sponsors file. static QString sponsorsFilePath(); - /** Returns the path to the donors file. */ + //! Returns the path to the donors file. static QString donorsFilePath(); /** @@ -262,7 +262,7 @@ class CORE_EXPORT QgsApplication : public QApplication //! get application icon static QString appIconPath(); - /** Constants for endian-ness */ + //! Constants for endian-ness enum endian_t { XDR = 0, // network, or big-endian, byte order @@ -308,19 +308,19 @@ class CORE_EXPORT QgsApplication : public QApplication */ static void registerOgrDrivers(); - /** Converts absolute path to path relative to target */ + //! Converts absolute path to path relative to target static QString absolutePathToRelativePath( const QString& apath, const QString& targetPath ); - /** Converts path relative to target to an absolute path */ + //! Converts path relative to target to an absolute path static QString relativePathToAbsolutePath( const QString& rpath, const QString& targetPath ); - /** Indicates whether running from build directory (not installed) */ + //! Indicates whether running from build directory (not installed) static bool isRunningFromBuildDir() { return ABISYM( mRunningFromBuildDir ); } #ifdef _MSC_VER static QString cfgIntDir() { return ABISYM( mCfgIntDir ); } #endif - /** Returns path to the source directory. Valid only when running from build directory */ + //! Returns path to the source directory. Valid only when running from build directory static QString buildSourcePath() { return ABISYM( mBuildSourcePath ); } - /** Returns path to the build output directory. Valid only when running from build directory */ + //! Returns path to the build output directory. Valid only when running from build directory static QString buildOutputPath() { return ABISYM( mBuildOutputPath ); } /** Sets the GDAL_SKIP environment variable to include the specified driver @@ -401,15 +401,15 @@ class CORE_EXPORT QgsApplication : public QApplication static QString ABISYM( mConfigPath ); - /** True when running from build directory, i.e. without 'make install' */ + //! True when running from build directory, i.e. without 'make install' static bool ABISYM( mRunningFromBuildDir ); - /** Path to the source directory. valid only when running from build directory. */ + //! Path to the source directory. valid only when running from build directory. static QString ABISYM( mBuildSourcePath ); #ifdef _MSC_VER - /** Configuration internal dir */ + //! Configuration internal dir static QString ABISYM( mCfgIntDir ); #endif - /** Path to the output directory of the build. valid only when running from build directory */ + //! Path to the output directory of the build. valid only when running from build directory static QString ABISYM( mBuildOutputPath ); /** List of gdal drivers to be skipped. Uses GDAL_SKIP to exclude them. * @see skipGdalDriver, restoreGdalDriver */ diff --git a/src/core/qgsbrowsermodel.h b/src/core/qgsbrowsermodel.h index 2a5ff0985704..3d4a2eb3d011 100644 --- a/src/core/qgsbrowsermodel.h +++ b/src/core/qgsbrowsermodel.h @@ -58,8 +58,8 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel enum ItemDataRole { - PathRole = Qt::UserRole, /*!< Item path used to access path in the tree, see QgsDataItem::mPath */ - CommentRole = Qt::UserRole + 1, /*!< Item comment */ + PathRole = Qt::UserRole, //!< Item path used to access path in the tree, see QgsDataItem::mPath + CommentRole = Qt::UserRole + 1, //!< Item comment }; // implemented methods from QAbstractItemModel for read-only access @@ -77,14 +77,14 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel by views that can display header information. */ virtual QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const override; - /** Provides the number of rows of data exposed by the model. */ + //! Provides the number of rows of data exposed by the model. virtual int rowCount( const QModelIndex &parent = QModelIndex() ) const override; /** Provides the number of columns of data exposed by the model. List models do not provide this function because it is already implemented in QAbstractListModel. */ virtual int columnCount( const QModelIndex &parent = QModelIndex() ) const override; - /** Returns the index of the item in the model specified by the given row, column and parent index. */ + //! Returns the index of the item in the model specified by the given row, column and parent index. virtual QModelIndex index( int row, int column, const QModelIndex & parent = QModelIndex() ) const override; QModelIndex findItem( QgsDataItem *item, QgsDataItem *parent = nullptr ) const; @@ -94,13 +94,13 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel */ virtual QModelIndex parent( const QModelIndex &index ) const override; - /** Returns a list of mime that can describe model indexes */ + //! Returns a list of mime that can describe model indexes virtual QStringList mimeTypes() const override; - /** Returns an object that contains serialized items of data corresponding to the list of indexes specified */ + //! Returns an object that contains serialized items of data corresponding to the list of indexes specified virtual QMimeData * mimeData( const QModelIndexList &indexes ) const override; - /** Handles the data supplied by a drag and drop operation that ended with the given action */ + //! Handles the data supplied by a drag and drop operation that ended with the given action virtual bool dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent ) override; QgsDataItem *dataItem( const QModelIndex &idx ) const; @@ -130,7 +130,7 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel void fetchMore( const QModelIndex & parent ) override; signals: - /** Emitted when item children fetch was finished */ + //! Emitted when item children fetch was finished void stateChanged( const QModelIndex & index, QgsDataItem::State oldState ); public slots: @@ -147,7 +147,7 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel void removeFavourite( const QModelIndex &index ); void updateProjectHome(); - /** Hide the given path in the browser model */ + //! Hide the given path in the browser model void hidePath( QgsDataItem *item ); protected: diff --git a/src/core/qgscolorscheme.h b/src/core/qgscolorscheme.h index b5261c8056e2..fedd159cde5d 100644 --- a/src/core/qgscolorscheme.h +++ b/src/core/qgscolorscheme.h @@ -46,9 +46,9 @@ class CORE_EXPORT QgsColorScheme */ enum SchemeFlag { - ShowInColorDialog = 0x01, /*!< show scheme in color picker dialog */ - ShowInColorButtonMenu = 0x02, /*!< show scheme in color button drop down menu */ - ShowInAllContexts = ShowInColorDialog | ShowInColorButtonMenu /*!< show scheme in all contexts */ + ShowInColorDialog = 0x01, //!< Show scheme in color picker dialog + ShowInColorButtonMenu = 0x02, //!< Show scheme in color button drop down menu + ShowInAllContexts = ShowInColorDialog | ShowInColorButtonMenu //!< Show scheme in all contexts }; Q_DECLARE_FLAGS( SchemeFlags, SchemeFlag ) diff --git a/src/core/qgscoordinatereferencesystem.h b/src/core/qgscoordinatereferencesystem.h index 330ad0e9e1c5..0be1c0217f1a 100644 --- a/src/core/qgscoordinatereferencesystem.h +++ b/src/core/qgscoordinatereferencesystem.h @@ -198,7 +198,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem EpsgCrsId //!< EPSG code }; - /** Constructs an invalid CRS object */ + //! Constructs an invalid CRS object QgsCoordinateReferenceSystem(); ~QgsCoordinateReferenceSystem(); @@ -398,7 +398,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem */ static void setupESRIWktFix(); - /** Returns whether this CRS is correctly initialized and usable */ + //! Returns whether this CRS is correctly initialized and usable bool isValid() const; /** Perform some validation on this CRS. If the CRS doesn't validate the @@ -559,7 +559,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem */ bool saveAsUserCrs( const QString& name ); - /** Returns auth id of related geographic CRS*/ + //! Returns auth id of related geographic CRS QString geographicCrsAuthId() const; /** Returns a list of recently used projections @@ -637,7 +637,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem */ void debugPrint(); - /** A string based associative array used for passing records around */ + //! A string based associative array used for passing records around typedef QMap RecordMap; /** Get a record from the srs.db or qgis.db backends, given an sql statment. * @note only handles queries that return a single record. diff --git a/src/core/qgscoordinatetransform.h b/src/core/qgscoordinatetransform.h index 0ebfb86a2c4f..f7ef285c7214 100644 --- a/src/core/qgscoordinatetransform.h +++ b/src/core/qgscoordinatetransform.h @@ -47,11 +47,11 @@ class CORE_EXPORT QgsCoordinateTransform //! Enum used to indicate the direction (forward or inverse) of the transform enum TransformDirection { - ForwardTransform, /*!< Transform from source to destination CRS. */ - ReverseTransform /*!< Transform from destination to source CRS. */ + ForwardTransform, //!< Transform from source to destination CRS. + ReverseTransform //!< Transform from destination to source CRS. }; - /** Default constructor, creates an invalid QgsCoordinateTransform. */ + //! Default constructor, creates an invalid QgsCoordinateTransform. QgsCoordinateTransform(); /** Constructs a QgsCoordinateTransform using QgsCoordinateReferenceSystem objects. diff --git a/src/core/qgscoordinatetransform_p.h b/src/core/qgscoordinatetransform_p.h index 4c98d1dfbe41..0f25b70726bc 100644 --- a/src/core/qgscoordinatetransform_p.h +++ b/src/core/qgscoordinatetransform_p.h @@ -209,7 +209,7 @@ class QgsCoordinateTransformPrivate : public QSharedData return mIsValid; } - /** Removes +nadgrids and +towgs84 from proj4 string*/ + //! Removes +nadgrids and +towgs84 from proj4 string QString stripDatumTransform( const QString& proj4 ) const { QStringList parameterSplit = proj4.split( '+', QString::SkipEmptyParts ); @@ -286,7 +286,7 @@ class QgsCoordinateTransformPrivate : public QSharedData return transformString; } - /** In certain situations, null grid shifts have to be added to src / dst proj string*/ + //! In certain situations, null grid shifts have to be added to src / dst proj string void addNullGridShifts( QString& srcProjString, QString& destProjString ) const { //if one transformation uses ntv2, the other one needs to be null grid shift diff --git a/src/core/qgscrscache.h b/src/core/qgscrscache.h index e12fbb17e924..74059fd715ae 100644 --- a/src/core/qgscrscache.h +++ b/src/core/qgscrscache.h @@ -43,7 +43,7 @@ class CORE_EXPORT QgsCoordinateTransformCache */ QgsCoordinateTransform transform( const QString& srcAuthId, const QString& destAuthId, int srcDatumTransform = -1, int destDatumTransform = -1 ); - /** Removes transformations where a changed crs is involved from the cache*/ + //! Removes transformations where a changed crs is involved from the cache void invalidateCrs( const QString& crsAuthId ); private: diff --git a/src/core/qgsdataitem.h b/src/core/qgsdataitem.h index 8e2deba7b624..3898d8d219f8 100644 --- a/src/core/qgsdataitem.h +++ b/src/core/qgsdataitem.h @@ -53,16 +53,16 @@ class CORE_EXPORT QgsAnimatedIcon : public QObject void setIconPath( const QString & iconPath ); QIcon icon() const { return mIcon; } - /** Connect listener to frameChanged() signal */ + //! Connect listener to frameChanged() signal void connectFrameChanged( const QObject * receiver, const char * method ); - /** Disconnect listener from frameChanged() signal */ + //! Disconnect listener from frameChanged() signal void disconnectFrameChanged( const QObject * receiver, const char * method ); public slots: void onFrameChanged(); signals: - /** Emitted when icon changed */ + //! Emitted when icon changed void frameChanged(); private: @@ -92,7 +92,7 @@ class CORE_EXPORT QgsDataItem : public QObject Project //! Represents a QGIS project }; - /** Create new data item. */ + //! Create new data item. QgsDataItem( QgsDataItem::Type type, QgsDataItem* parent, const QString& name, const QString& path ); virtual ~QgsDataItem(); @@ -108,7 +108,7 @@ class CORE_EXPORT QgsDataItem : public QObject { NotPopulated, //!< Children not yet created Populating, //!< Creating children in separate thread (populating or refreshing) - Populated //!< children created + Populated //!< Children created }; //! @note added in 2.8 @@ -182,7 +182,7 @@ class CORE_EXPORT QgsDataItem : public QObject NoCapabilities = 0, SetCrs = 1 << 0, //!< Can set CRS on layer or group of layers Fertile = 1 << 1, //!< Can create children. Even items without this capability may have children, but cannot create them, it means that children are created by item ancestors. - Fast = 1 << 2 //!< createChildren() is fast enough to be run in main thread when refreshing items, most root items (wms,wfs,wcs,postgres...) are considered fast because they are reading data only from QSettings + Fast = 1 << 2 //!< CreateChildren() is fast enough to be run in main thread when refreshing items, most root items (wms,wfs,wcs,postgres...) are considered fast because they are reading data only from QSettings }; Q_DECLARE_FLAGS( Capabilities, Capability ) @@ -236,7 +236,7 @@ class CORE_EXPORT QgsDataItem : public QObject // deleteLater() items anc clear the vector static void deleteLater( QVector &items ); - /** Move object and all its descendants to thread */ + //! Move object and all its descendants to thread void moveToThread( QThread * targetThread ); protected: @@ -285,7 +285,7 @@ class CORE_EXPORT QgsDataItem : public QObject // @param foreground run createChildren in foreground virtual void populate( bool foreground = false ); - /** Remove children recursively and set as not populated. This is used when refreshing collapsed items. */ + //! Remove children recursively and set as not populated. This is used when refreshing collapsed items. virtual void depopulate(); virtual void refresh(); @@ -331,7 +331,7 @@ class CORE_EXPORT QgsLayerItem : public QgsDataItem TableLayer, Database, Table, - Plugin //!< added in 2.10 + Plugin //!< Added in 2.10 }; QgsLayerItem( QgsDataItem* parent, const QString& name, const QString& path, const QString& uri, LayerType layerType, const QString& providerKey ); @@ -346,13 +346,13 @@ class CORE_EXPORT QgsLayerItem : public QgsDataItem // --- New virtual methods for layer item derived classes --- - /** Returns QgsMapLayer::LayerType */ + //! Returns QgsMapLayer::LayerType QgsMapLayer::LayerType mapLayerType() const; - /** Returns layer uri or empty string if layer cannot be created */ + //! Returns layer uri or empty string if layer cannot be created QString uri() const { return mUri; } - /** Returns provider key */ + //! Returns provider key QString providerKey() const { return mProviderKey; } /** Returns the supported CRS @@ -372,15 +372,15 @@ class CORE_EXPORT QgsLayerItem : public QgsDataItem protected: - /** The provider key */ + //! The provider key QString mProviderKey; - /** The URI */ + //! The URI QString mUri; - /** The layer type */ + //! The layer type LayerType mLayerType; - /** The list of supported CRS */ + //! The list of supported CRS QStringList mSupportedCRS; - /** The list of supported formats */ + //! The list of supported formats QStringList mSupportFormats; public: @@ -391,7 +391,7 @@ class CORE_EXPORT QgsLayerItem : public QgsDataItem static const QIcon &iconRaster(); static const QIcon &iconDefault(); - /** @return the layer name */ + //! @return the layer name virtual QString layerName() const { return name(); } }; @@ -449,7 +449,7 @@ class CORE_EXPORT QgsDirectoryItem : public QgsDataCollectionItem virtual QIcon icon() override; virtual QWidget *paramWidget() override; - /** Check if the given path is hidden from the browser model */ + //! Check if the given path is hidden from the browser model static bool hiddenPath( const QString &path ); public slots: diff --git a/src/core/qgsdataprovider.h b/src/core/qgsdataprovider.h index ba32bba08d3b..ea37a5d54cf8 100644 --- a/src/core/qgsdataprovider.h +++ b/src/core/qgsdataprovider.h @@ -307,10 +307,10 @@ class CORE_EXPORT QgsDataProvider : public QObject */ virtual void reloadData() {} - /** Time stamp of data source in the moment when data/metadata were loaded by provider */ + //! Time stamp of data source in the moment when data/metadata were loaded by provider virtual QDateTime timestamp() const { return mTimestamp; } - /** Current time stamp of data source */ + //! Current time stamp of data source virtual QDateTime dataTimestamp() const { return QDateTime(); } /** Get current status error. This error describes some principal problem @@ -427,13 +427,13 @@ class CORE_EXPORT QgsDataProvider : public QObject */ QDateTime mTimestamp; - /** \brief Error */ + //! \brief Error QgsError mError; - /** Add error message */ + //! Add error message void appendError( const QgsErrorMessage & theMessage ) { mError.append( theMessage );} - /** Set error message */ + //! Set error message void setError( const QgsError & theError ) { mError = theError;} private: diff --git a/src/core/qgsdbfilterproxymodel.h b/src/core/qgsdbfilterproxymodel.h index 539b1ead51a7..73c970e5feab 100644 --- a/src/core/qgsdbfilterproxymodel.h +++ b/src/core/qgsdbfilterproxymodel.h @@ -30,9 +30,9 @@ class CORE_EXPORT QgsDbFilterProxyModel: public QSortFilterProxyModel public: QgsDbFilterProxyModel( QObject* parent = nullptr ); ~QgsDbFilterProxyModel(); - /** Calls QSortFilterProxyModel::setFilterWildcard and triggers update*/ + //! Calls QSortFilterProxyModel::setFilterWildcard and triggers update void _setFilterWildcard( const QString& pattern ); - /** Calls QSortFilterProxyModel::setFilterRegExp and triggers update*/ + //! Calls QSortFilterProxyModel::setFilterRegExp and triggers update void _setFilterRegExp( const QString& pattern ); protected: diff --git a/src/core/qgsdiagramrenderer.h b/src/core/qgsdiagramrenderer.h index b93b67ebcb9f..63615c1a0e1c 100644 --- a/src/core/qgsdiagramrenderer.h +++ b/src/core/qgsdiagramrenderer.h @@ -390,7 +390,7 @@ class CORE_EXPORT QgsDiagramInterpolationSettings double lowerValue; double upperValue; - /** Index of the classification attribute*/ + //! Index of the classification attribute //TODO QGIS 3.0 - don't store index, store field name int classificationAttribute; @@ -415,12 +415,12 @@ class CORE_EXPORT QgsDiagramRenderer * @note added in 2.4 */ virtual QgsDiagramRenderer* clone() const = 0; - /** Returns size of the diagram for a feature in map units. Returns an invalid QSizeF in case of error*/ + //! Returns size of the diagram for a feature in map units. Returns an invalid QSizeF in case of error virtual QSizeF sizeMapUnits( const QgsFeature& feature, const QgsRenderContext& c ) const; virtual QString rendererName() const = 0; - /** Returns attribute indices needed for diagram rendering*/ + //! Returns attribute indices needed for diagram rendering virtual QList diagramAttributes() const = 0; /** Returns the set of any fields required for diagram rendering @@ -436,7 +436,7 @@ class CORE_EXPORT QgsDiagramRenderer void setDiagram( QgsDiagram* d ); QgsDiagram* diagram() const { return mDiagram; } - /** Returns list with all diagram settings in the renderer*/ + //! Returns list with all diagram settings in the renderer virtual QList diagramSettings() const = 0; virtual void readXml( const QDomElement& elem, const QgsVectorLayer* layer ) = 0; @@ -506,20 +506,20 @@ class CORE_EXPORT QgsDiagramRenderer */ virtual bool diagramSettings( const QgsFeature &feature, const QgsRenderContext& c, QgsDiagramSettings& s ) const = 0; - /** Returns size of the diagram (in painter units) or an invalid size in case of error*/ + //! Returns size of the diagram (in painter units) or an invalid size in case of error virtual QSizeF diagramSize( const QgsFeature& features, const QgsRenderContext& c ) const = 0; - /** Converts size from mm to map units*/ + //! Converts size from mm to map units void convertSizeToMapUnits( QSizeF& size, const QgsRenderContext& context ) const; - /** Returns the paint device dpi (or -1 in case of error*/ + //! Returns the paint device dpi (or -1 in case of error static int dpiPaintDevice( const QPainter* ); //read / write diagram void _readXml( const QDomElement& elem, const QgsVectorLayer* layer ); void _writeXml( QDomElement& rendererElem, QDomDocument& doc, const QgsVectorLayer* layer ) const; - /** Reference to the object that does the real diagram rendering*/ + //! Reference to the object that does the real diagram rendering QgsDiagram* mDiagram; //! Whether to show an attribute legend for the diagrams @@ -576,7 +576,7 @@ class CORE_EXPORT QgsLinearlyInterpolatedDiagramRenderer : public QgsDiagramRend QgsLinearlyInterpolatedDiagramRenderer* clone() const override; - /** Returns list with all diagram settings in the renderer*/ + //! Returns list with all diagram settings in the renderer QList diagramSettings() const override; void setDiagramSettings( const QgsDiagramSettings& s ) { mSettings = s; } diff --git a/src/core/qgseditformconfig.h b/src/core/qgseditformconfig.h index 31a284ec3dfd..e04f0f7e3065 100644 --- a/src/core/qgseditformconfig.h +++ b/src/core/qgseditformconfig.h @@ -35,7 +35,7 @@ class CORE_EXPORT QgsEditFormConfig { public: - /** The different types to layout the attribute editor. */ + //! The different types to layout the attribute editor. enum EditorLayout { GeneratedLayout = 0, //!< Autogenerate a simple tabular layout for the form @@ -125,13 +125,13 @@ class CORE_EXPORT QgsEditFormConfig */ QgsAttributeEditorContainer* invisibleRootContainer(); - /** Get the active layout style for the attribute editor for this layer */ + //! Get the active layout style for the attribute editor for this layer EditorLayout layout() const; - /** Set the active layout style for the attribute editor for this layer */ + //! Set the active layout style for the attribute editor for this layer void setLayout( EditorLayout editorLayout ); - /** Get path to the .ui form. Only meaningful with EditorLayout::UiFileLayout. */ + //! Get path to the .ui form. Only meaningful with EditorLayout::UiFileLayout. QString uiForm() const; /** @@ -351,12 +351,12 @@ class CORE_EXPORT QgsEditFormConfig */ PythonInitCodeSource initCodeSource() const; - /** Set if python code shall be used for edit form initialization and its origin */ + //! Set if python code shall be used for edit form initialization and its origin void setInitCodeSource( PythonInitCodeSource initCodeSource ); - /** Type of feature form pop-up suppression after feature creation (overrides app setting) */ + //! Type of feature form pop-up suppression after feature creation (overrides app setting) FeatureFormSuppress suppress() const; - /** Set type of feature form pop-up suppression after feature creation (overrides app setting) */ + //! Set type of feature form pop-up suppression after feature creation (overrides app setting) void setSuppress( FeatureFormSuppress s ); // Serialization diff --git a/src/core/qgseditformconfig_p.h b/src/core/qgseditformconfig_p.h index 91e050647046..6637af0ae815 100644 --- a/src/core/qgseditformconfig_p.h +++ b/src/core/qgseditformconfig_p.h @@ -59,10 +59,10 @@ class QgsEditFormConfigPrivate : public QSharedData delete mInvisibleRootContainer; } - /** The invisible root container for attribute editors in the drag and drop designer */ + //! The invisible root container for attribute editors in the drag and drop designer QgsAttributeEditorContainer* mInvisibleRootContainer; - /** This flag is set if the root container was configured by the user */ + //! This flag is set if the root container was configured by the user bool mConfiguredRootContainer; QMap< QString, QString> mConstraints; @@ -74,21 +74,21 @@ class QgsEditFormConfigPrivate : public QSharedData QMap mEditorWidgetTypes; QMap mWidgetConfigs; - /** Defines the default layout to use for the attribute editor (Drag and drop, UI File, Generated) */ + //! Defines the default layout to use for the attribute editor (Drag and drop, UI File, Generated) QgsEditFormConfig::EditorLayout mEditorLayout; - /** Init form instance */ + //! Init form instance QString mUiFormPath; - /** Name of the python form init function */ + //! Name of the python form init function QString mInitFunction; - /** Path of the python external file to be loaded */ + //! Path of the python external file to be loaded QString mInitFilePath; - /** Choose the source of the init founction */ + //! Choose the source of the init founction QgsEditFormConfig::PythonInitCodeSource mInitCodeSource; - /** Python init code provided in the dialog */ + //! Python init code provided in the dialog QString mInitCode; - /** Type of feature form suppression after feature creation */ + //! Type of feature form suppression after feature creation QgsEditFormConfig::FeatureFormSuppress mSuppressForm; QgsFields mFields; diff --git a/src/core/qgserror.h b/src/core/qgserror.h index 41ddd93fac79..a0aae0cbd5dc 100644 --- a/src/core/qgserror.h +++ b/src/core/qgserror.h @@ -29,7 +29,7 @@ class CORE_EXPORT QgsErrorMessage { public: - /** Format */ + //! Format enum Format { Text, // Plain text @@ -57,18 +57,18 @@ class CORE_EXPORT QgsErrorMessage int line() const { return mLine; } private: - /** Error messages */ + //! Error messages QString mMessage; - /** Short description */ + //! Short description QString mTag; - /** Detailed debug info */ + //! Detailed debug info QString mFile; QString mFunction; int mLine; - /** Message format */ + //! Message format Format mFormat; }; @@ -116,11 +116,11 @@ class CORE_EXPORT QgsError */ QString summary() const; - /** Clear error messages */ + //! Clear error messages void clear() { mMessageList.clear(); } private: - /** List of messages */ + //! List of messages QList mMessageList; }; diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index d81600210ea2..97b1c8b3e206 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -541,13 +541,13 @@ class CORE_EXPORT QgsExpression virtual ~Function() {} - /** The name of the function. */ + //! The name of the function. QString name() const { return mName; } - /** The number of parameters this function takes. */ + //! The number of parameters this function takes. int params() const { return mParameterList.isEmpty() ? mParams : mParameterList.count(); } - /** The mininum number of parameters this function takes. */ + //! The mininum number of parameters this function takes. int minParams() const { if ( mParameterList.isEmpty() ) @@ -567,7 +567,7 @@ class CORE_EXPORT QgsExpression */ const ParameterList& parameters() const { return mParameterList; } - /** Does this function use a geometry object. */ + //! Does this function use a geometry object. bool usesGeometry() const { return mUsesGeometry; } /** Returns a list of possible aliases for the function. These include @@ -606,7 +606,7 @@ class CORE_EXPORT QgsExpression */ QStringList groups() const { return mGroups; } - /** The help text for the function. */ + //! The help text for the function. const QString helpText() const { return mHelpText.isEmpty() ? QgsExpression::helpText( mName ) : mHelpText; } /** Returns result of evaluating the function. @@ -898,7 +898,7 @@ class CORE_EXPORT QgsExpression public: NodeList() : mHasNamedNodes( false ) {} virtual ~NodeList() { qDeleteAll( mList ); } - /** Takes ownership of the provided node */ + //! Takes ownership of the provided node void append( Node* node ) { mList.append( node ); mNameList.append( QString() ); } /** Adds a named node. Takes ownership of the provided node. @@ -920,7 +920,7 @@ class CORE_EXPORT QgsExpression //! @note added in QGIS 2.16 QStringList names() const { return mNameList; } - /** Creates a deep copy of this list. Ownership is transferred to the caller */ + //! Creates a deep copy of this list. Ownership is transferred to the caller NodeList* clone() const; virtual QString dump() const; @@ -1076,7 +1076,7 @@ class CORE_EXPORT QgsExpression : mValue( value ) {} - /** The value of the literal. */ + //! The value of the literal. inline QVariant value() const { return mValue; } virtual NodeType nodeType() const override { return ntLiteral; } @@ -1102,7 +1102,7 @@ class CORE_EXPORT QgsExpression , mIndex( -1 ) {} - /** The name of the column. */ + //! The name of the column. QString name() const { return mName; } virtual NodeType nodeType() const override { return ntColumnRef; } diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index 463bd15dce6c..02462ae71bb2 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -100,13 +100,13 @@ class CORE_EXPORT QgsExpressionContextScope , readOnly( readOnly ) {} - /** Variable name */ + //! Variable name QString name; - /** Variable value */ + //! Variable value QVariant value; - /** True if variable should not be editable by users */ + //! True if variable should not be editable by users bool readOnly; }; diff --git a/src/core/qgsfeature.h b/src/core/qgsfeature.h index 3f1239caedd3..39305aabce15 100644 --- a/src/core/qgsfeature.h +++ b/src/core/qgsfeature.h @@ -331,9 +331,9 @@ class CORE_EXPORT QgsFeature }; // class QgsFeature -/** Writes the feature to stream out. QGIS version compatibility is not guaranteed. */ +//! Writes the feature to stream out. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsFeature& feature ); -/** Reads a feature from stream in into feature. QGIS version compatibility is not guaranteed. */ +//! Reads a feature from stream in into feature. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsFeature& feature ); // key = feature id, value = changed attributes diff --git a/src/core/qgsfeaturefilterprovider.h b/src/core/qgsfeaturefilterprovider.h index 5de614457db3..66743ec80464 100644 --- a/src/core/qgsfeaturefilterprovider.h +++ b/src/core/qgsfeaturefilterprovider.h @@ -37,10 +37,10 @@ class CORE_EXPORT QgsFeatureFilterProvider { public: - /** Constructor */ + //! Constructor QgsFeatureFilterProvider() {} - /** Destructor */ + //! Destructor virtual ~QgsFeatureFilterProvider() {} /** Add additional filters to the feature request to further restrict the features returned by the request. diff --git a/src/core/qgsfeatureiterator.h b/src/core/qgsfeatureiterator.h index 36cc4761e920..2d870a236ecb 100644 --- a/src/core/qgsfeatureiterator.h +++ b/src/core/qgsfeatureiterator.h @@ -42,9 +42,9 @@ class CORE_EXPORT QgsAbstractFeatureIterator //! Status of expression compilation for filter expression requests enum CompileStatus { - NoCompilation, /*!< Expression could not be compiled or not attempt was made to compile expression */ - PartiallyCompiled, /*!< Expression was partially compiled, but extra checks need to be applied to features*/ - Compiled, /*!< Expression was fully compiled and delegated to data provider source*/ + NoCompilation, //!< Expression could not be compiled or not attempt was made to compile expression + PartiallyCompiled, //!< Expression was partially compiled, but extra checks need to be applied to features + Compiled, //!< Expression was fully compiled and delegated to data provider source }; //! base class constructor - stores the iteration parameters @@ -111,10 +111,10 @@ class CORE_EXPORT QgsAbstractFeatureIterator */ virtual bool nextFeatureFilterFids( QgsFeature & f ); - /** A copy of the feature request. */ + //! A copy of the feature request. QgsFeatureRequest mRequest; - /** Set to true, as soon as the iterator is closed. */ + //! Set to true, as soon as the iterator is closed. bool mClosed; /** @@ -129,8 +129,8 @@ class CORE_EXPORT QgsAbstractFeatureIterator //! reference counting (to allow seamless copying of QgsFeatureIterator instances) //! TODO QGIS3: make this private int refs; - void ref(); //!< add reference - void deref(); //!< remove reference, delete if refs == 0 + void ref(); //!< Add reference + void deref(); //!< Remove reference, delete if refs == 0 friend class QgsFeatureIterator; //! Number of features already fetched by iterator diff --git a/src/core/qgsfeaturestore.h b/src/core/qgsfeaturestore.h index 73729c3c2de0..640716f2557d 100644 --- a/src/core/qgsfeaturestore.h +++ b/src/core/qgsfeaturestore.h @@ -35,16 +35,16 @@ class CORE_EXPORT QgsFeatureStore //! Constructor QgsFeatureStore( const QgsFields& fields, const QgsCoordinateReferenceSystem& crs ); - /** Get fields list */ + //! Get fields list QgsFields& fields() { return mFields; } - /** Set fields. Resets feature's fields to pointer to new internal fields. */ + //! Set fields. Resets feature's fields to pointer to new internal fields. void setFields( const QgsFields & fields ); - /** Get crs */ + //! Get crs QgsCoordinateReferenceSystem crs() const { return mCrs; } - /** Set crs */ + //! Set crs void setCrs( const QgsCoordinateReferenceSystem& crs ) { mCrs = crs; } /** Add feature. Feature's fields will be set to pointer to the store fields. @@ -53,13 +53,13 @@ class CORE_EXPORT QgsFeatureStore */ void addFeature( const QgsFeature& feature ); - /** Get features list reference */ + //! Get features list reference QgsFeatureList& features() { return mFeatures; } - /** Set map of optional parameters */ + //! Set map of optional parameters void setParams( const QMap &theParams ) { mParams = theParams; } - /** Get map of optional parameters */ + //! Get map of optional parameters QMap params() const { return mParams; } private: diff --git a/src/core/qgsfield.h b/src/core/qgsfield.h index fb002c5d5d77..1e5ed1d5bc81 100644 --- a/src/core/qgsfield.h +++ b/src/core/qgsfield.h @@ -222,7 +222,7 @@ class CORE_EXPORT QgsField */ void setAlias( const QString& alias ); - /** Formats string for display*/ + //! Formats string for display QString displayString( const QVariant& v ) const; /** @@ -263,9 +263,9 @@ class CORE_EXPORT QgsField Q_DECLARE_METATYPE( QgsField ) -/** Writes the field to stream out. QGIS version compatibility is not guaranteed. */ +//! Writes the field to stream out. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsField& field ); -/** Reads a field from stream in into field. QGIS version compatibility is not guaranteed. */ +//! Reads a field from stream in into field. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsField& field ); diff --git a/src/core/qgsfields.h b/src/core/qgsfields.h index 8fc6891d1597..005ff43d6f0a 100644 --- a/src/core/qgsfields.h +++ b/src/core/qgsfields.h @@ -39,11 +39,11 @@ class CORE_EXPORT QgsFields enum FieldOrigin { - OriginUnknown, //!< it has not been specified where the field comes from - OriginProvider, //!< field comes from the underlying data provider of the vector layer (originIndex = index in provider's fields) - OriginJoin, //!< field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join) - OriginEdit, //!< field has been temporarily added in editing mode (originIndex = index in the list of added attributes) - OriginExpression //!< field is calculated from an expression + OriginUnknown, //!< It has not been specified where the field comes from + OriginProvider, //!< Field comes from the underlying data provider of the vector layer (originIndex = index in provider's fields) + OriginJoin, //!< Field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index within the join) + OriginEdit, //!< Field has been temporarily added in editing mode (originIndex = index in the list of added attributes) + OriginExpression //!< Field is calculated from an expression }; typedef struct Field @@ -63,9 +63,9 @@ class CORE_EXPORT QgsFields //! @note added in 2.6 bool operator!=( const Field& other ) const { return !( *this == other ); } - QgsField field; //!< field - FieldOrigin origin; //!< origin of the field - int originIndex; //!< index specific to the origin + QgsField field; //!< Field + FieldOrigin origin; //!< Origin of the field + int originIndex; //!< Index specific to the origin } Field; /** Constructor for an empty field container @@ -320,9 +320,9 @@ class CORE_EXPORT QgsFields Q_DECLARE_METATYPE( QgsFields ) -/** Writes the fields to stream out. QGIS version compatibility is not guaranteed. */ +//! Writes the fields to stream out. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsFields& fields ); -/** Reads fields from stream in into fields. QGIS version compatibility is not guaranteed. */ +//! Reads fields from stream in into fields. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsFields& fields ); #endif // QGSFIELDS_H diff --git a/src/core/qgsgeometrycache.h b/src/core/qgsgeometrycache.h index 4e64b3f4db48..edc27461ff27 100644 --- a/src/core/qgsgeometrycache.h +++ b/src/core/qgsgeometrycache.h @@ -40,7 +40,7 @@ class CORE_EXPORT QgsGeometryCache //! get rid of the cached geometry void removeGeometry( QgsFeatureId fid ) { mCachedGeometries.remove( fid ); } - /** Deletes the geometries in mCachedGeometries */ + //! Deletes the geometries in mCachedGeometries void deleteCachedGeometries(); void setCachedGeometriesRect( const QgsRectangle& extent ) { mCachedGeometriesRect = extent; } @@ -48,10 +48,10 @@ class CORE_EXPORT QgsGeometryCache protected: - /** Cache of the committed geometries retrieved *for the current display* */ + //! Cache of the committed geometries retrieved *for the current display* QgsGeometryMap mCachedGeometries; - /** Extent for which there are cached geometries */ + //! Extent for which there are cached geometries QgsRectangle mCachedGeometriesRect; }; diff --git a/src/core/qgsgeometryvalidator.h b/src/core/qgsgeometryvalidator.h index df4940def882..4f6c227df58a 100644 --- a/src/core/qgsgeometryvalidator.h +++ b/src/core/qgsgeometryvalidator.h @@ -34,7 +34,7 @@ class CORE_EXPORT QgsGeometryValidator : public QThread void run() override; void stop(); - /** Validate geometry and produce a list of geometry errors */ + //! Validate geometry and produce a list of geometry errors static void validateGeometry( const QgsGeometry *g, QList &errors ); signals: diff --git a/src/core/qgsgml.h b/src/core/qgsgml.h index 1a2f7f2dd22e..7e54d11b9f53 100644 --- a/src/core/qgsgml.h +++ b/src/core/qgsgml.h @@ -53,34 +53,34 @@ class CORE_EXPORT QgsGmlStreamingParser class LayerProperties { public: - /** Constructor */ + //! Constructor LayerProperties() {} - /** Layer name */ + //! Layer name QString mName; - /** Geometry attribute name */ + //! Geometry attribute name QString mGeometryAttribute; }; - /** Axis orientation logic. */ + //! Axis orientation logic. typedef enum { - /** Honour EPSG axis order only if srsName is of the form urn:ogc:def:crs:EPSG: **/ + //! Honour EPSG axis order only if srsName is of the form urn:ogc:def:crs:EPSG: * Honour_EPSG_if_urn, - /** Honour EPSG axis order */ + //! Honour EPSG axis order Honour_EPSG, - /** Ignore EPSG axis order */ + //! Ignore EPSG axis order Ignore_EPSG, } AxisOrientationLogic; - /** Constructor */ + //! Constructor QgsGmlStreamingParser( const QString& typeName, const QString& geometryAttribute, const QgsFields & fields, AxisOrientationLogic axisOrientationLogic = Honour_EPSG_if_urn, bool invertAxisOrientation = false ); - /** Constructor for a join layer, or dealing with renamed fields*/ + //! Constructor for a join layer, or dealing with renamed fields QgsGmlStreamingParser( const QList& layerProperties, const QgsFields & fields, const QMap< QString, QPair >& mapFieldNameToSrcLayerNameFieldName, @@ -102,31 +102,31 @@ class CORE_EXPORT QgsGmlStreamingParser by later calls. */ QVector getAndStealReadyFeatures(); - /** Return the EPSG code, or 0 if unknown */ + //! Return the EPSG code, or 0 if unknown int getEPSGCode() const { return mEpsg; } - /** Return the value of the srsName attribute */ + //! Return the value of the srsName attribute const QString& srsName() const { return mSrsName; } - /** Return layer bounding box */ + //! Return layer bounding box const QgsRectangle& layerExtent() const { return mLayerExtent; } - /** Return the geometry type */ + //! Return the geometry type QgsWkbTypes::Type wkbType() const { return mWkbType; } - /** Return WFS 2.0 "numberMatched" attribute, or -1 if invalid/not found */ + //! Return WFS 2.0 "numberMatched" attribute, or -1 if invalid/not found int numberMatched() const { return mNumberMatched; } - /** Return WFS 2.0 "numberReturned" or WFS 1.1 "numberOfFeatures" attribute, or -1 if invalid/not found */ + //! Return WFS 2.0 "numberReturned" or WFS 1.1 "numberOfFeatures" attribute, or -1 if invalid/not found int numberReturned() const { return mNumberReturned; } - /** Return whether the document parser is a OGC exception */ + //! Return whether the document parser is a OGC exception bool isException() const { return mIsException; } - /** Return the exception text. */ + //! Return the exception text. const QString& exceptionText() const { return mExceptionText; } - /** Return whether a "truncatedResponse" element is found */ + //! Return whether a "truncatedResponse" element is found bool isTruncatedResponse() const { return mTruncatedResponse; } private: @@ -157,7 +157,7 @@ class CORE_EXPORT QgsGmlStreamingParser ExceptionText }; - /** XML handler methods*/ + //! XML handler methods void startElement( const XML_Char* el, const XML_Char** attr ); void endElement( const XML_Char* el ); void characters( const XML_Char* chars, int len ); @@ -191,7 +191,7 @@ class CORE_EXPORT QgsGmlStreamingParser @return attribute value or an empty string if no such attribute */ QString readAttribute( const QString& attributeName, const XML_Char** attr ) const; - /** Creates a rectangle from a coordinate string. */ + //! Creates a rectangle from a coordinate string. bool createBBoxFromCoordinateString( QgsRectangle &bb, const QString& coordString ) const; /** Creates a set of points from a coordinate string. @param points list that will contain the created points @@ -221,26 +221,26 @@ class CORE_EXPORT QgsGmlStreamingParser int createMultiPointFromFragments(); int createPolygonFromFragments(); int createMultiPolygonFromFragments(); - /** Adds all the integers contained in mCurrentWKBFragmentSizes*/ + //! Adds all the integers contained in mCurrentWKBFragmentSizes int totalWKBFragmentSize() const; - /** Get safely (if empty) top from mode stack */ + //! Get safely (if empty) top from mode stack ParseMode modeStackTop() { return mParseModeStack.isEmpty() ? none : mParseModeStack.top(); } - /** Safely (if empty) pop from mode stack */ + //! Safely (if empty) pop from mode stack ParseMode modeStackPop() { return mParseModeStack.isEmpty() ? none : mParseModeStack.pop(); } - /** Expat parser */ + //! Expat parser XML_Parser mParser; - /** List of (feature, gml_id) pairs */ + //! List of (feature, gml_id) pairs QVector mFeatureList; - /** Describe the various feature types of a join layer */ + //! Describe the various feature types of a join layer QList mLayerProperties; QMap< QString, LayerProperties > mMapTypeNameToProperties; - /** Typename without namespace prefix */ + //! Typename without namespace prefix QString mTypeName; QByteArray mTypeNameBA; const char* mTypeNamePtr; @@ -249,7 +249,7 @@ class CORE_EXPORT QgsGmlStreamingParser //results are members such that handler routines are able to manipulate them - /** Name of geometry attribute*/ + //! Name of geometry attribute QString mGeometryAttribute; QByteArray mGeometryAttributeBA; const char* mGeometryAttributePtr; @@ -260,19 +260,19 @@ class CORE_EXPORT QgsGmlStreamingParser bool mIsException; QString mExceptionText; bool mTruncatedResponse; - /** Parsing depth */ + //! Parsing depth int mParseDepth; int mFeatureTupleDepth; - QString mCurrentTypename; /** Used to track the current (unprefixed) typename for wfs:Member in join layer */ - /** Keep track about the most important nested elements*/ + QString mCurrentTypename; //! Used to track the current (unprefixed) typename for wfs:Member in join layer + //! Keep track about the most important nested elements QStack mParseModeStack; - /** This contains the character data if an important element has been encountered*/ + //! This contains the character data if an important element has been encountered QString mStringCash; QgsFeature* mCurrentFeature; QVector mCurrentAttributes; //attributes of current feature QString mCurrentFeatureId; int mFeatureCount; - /** The total WKB for a feature*/ + //! The total WKB for a feature QgsWkbPtr mCurrentWKB; QgsRectangle mCurrentExtent; bool mBoundedByNullFound; @@ -283,36 +283,36 @@ class CORE_EXPORT QgsGmlStreamingParser QList< QList > mCurrentWKBFragments; QString mAttributeName; char mEndian; - /** Coordinate separator for coordinate strings. Usually "," */ + //! Coordinate separator for coordinate strings. Usually "," QString mCoordinateSeparator; - /** Tuple separator for coordinate strings. Usually " " */ + //! Tuple separator for coordinate strings. Usually " " QString mTupleSeparator; - /** Number of dimensions in pos or posList */ + //! Number of dimensions in pos or posList int mDimension; - /** Coordinates mode, coordinate or posList */ + //! Coordinates mode, coordinate or posList ParseMode mCoorMode; - /** EPSG of parsed features geometries */ + //! EPSG of parsed features geometries int mEpsg; - /** Literal srsName attribute */ + //! Literal srsName attribute QString mSrsName; - /** Layer bounding box */ + //! Layer bounding box QgsRectangle mLayerExtent; - /** GML namespace URI */ + //! GML namespace URI QString mGMLNameSpaceURI; const char* mGMLNameSpaceURIPtr; - /** Axis orientation logic */ + //! Axis orientation logic AxisOrientationLogic mAxisOrientationLogic; - /** Whether to invert axis orientation. This value is immutable, but combined with what is infered from data and mAxisOrientationLogic, is used to compute mInvertAxisOrientation */ + //! Whether to invert axis orientation. This value is immutable, but combined with what is infered from data and mAxisOrientationLogic, is used to compute mInvertAxisOrientation bool mInvertAxisOrientationRequest; - /** Whether to invert axis orientation: result of mAxisOrientationLogic, mInvertAxisOrientationRequest and what is infered from data and mAxisOrientationLogic */ + //! Whether to invert axis orientation: result of mAxisOrientationLogic, mInvertAxisOrientationRequest and what is infered from data and mAxisOrientationLogic bool mInvertAxisOrientation; - /** WFS 2.0 "numberReturned" or WFS 1.1 "numberOfFeatures" attribute, or -1 if invalid/not found */ + //! WFS 2.0 "numberReturned" or WFS 1.1 "numberOfFeatures" attribute, or -1 if invalid/not found int mNumberReturned; - /** WFS 2.0 "numberMatched" attribute, or -1 if invalid/not found */ + //! WFS 2.0 "numberMatched" attribute, or -1 if invalid/not found int mNumberMatched; - /** XML blob containing geometry */ + //! XML blob containing geometry std::string mGeometryString; - /** Whether we found a unhandled geometry element */ + //! Whether we found a unhandled geometry element bool mFoundUnhandledGeometryElement; }; @@ -356,10 +356,10 @@ class CORE_EXPORT QgsGml : public QObject */ int getFeatures( const QByteArray &data, QgsWkbTypes::Type* wkbType, QgsRectangle* extent = nullptr ); - /** Get parsed features for given type name */ + //! Get parsed features for given type name QMap featuresMap() const { return mFeatures; } - /** Get feature ids map */ + //! Get feature ids map QMap idsMap() const { return mIdMap; } /** Returns features spatial reference system @@ -370,7 +370,7 @@ class CORE_EXPORT QgsGml : public QObject void setFinished(); - /** Takes progress value and total steps and emit signals 'dataReadProgress' and 'totalStepUpdate'*/ + //! Takes progress value and total steps and emit signals 'dataReadProgress' and 'totalStepUpdate' void handleProgressEvent( qint64 progress, qint64 totalSteps ); signals: @@ -392,23 +392,23 @@ class CORE_EXPORT QgsGml : public QObject QgsGmlStreamingParser mParser; - /** Typename without namespace prefix */ + //! Typename without namespace prefix QString mTypeName; - /** True if the request is finished*/ + //! True if the request is finished bool mFinished; - /** The features of the layer, map of feature maps for each feature type*/ + //! The features of the layer, map of feature maps for each feature type //QMap &mFeatures; QMap mFeatures; //QMap > mFeatures; - /** Stores the relation between provider ids and WFS server ids*/ + //! Stores the relation between provider ids and WFS server ids //QMap &mIdMap; QMap mIdMap; //QMap > mIdMap; - /** Bounding box of the layer*/ + //! Bounding box of the layer QgsRectangle mExtent; }; diff --git a/src/core/qgsgmlschema.h b/src/core/qgsgmlschema.h index 345761f3af08..4c893da8e752 100644 --- a/src/core/qgsgmlschema.h +++ b/src/core/qgsgmlschema.h @@ -80,7 +80,7 @@ class CORE_EXPORT QgsGmlSchema : public QObject ~QgsGmlSchema(); - /** Get fields info from XSD */ + //! Get fields info from XSD bool parseXSD( const QByteArray &xml ); /** Guess GML schema from data if XSD does not exist. @@ -90,16 +90,16 @@ class CORE_EXPORT QgsGmlSchema : public QObject * @return true in case of success */ bool guessSchema( const QByteArray &data ); - /** Get list of dot separated paths to feature classes parsed from GML or XSD */ + //! Get list of dot separated paths to feature classes parsed from GML or XSD QStringList typeNames() const; - /** Get fields for type/class name parsed from GML or XSD */ + //! Get fields for type/class name parsed from GML or XSD QList fields( const QString & typeName ); - /** Get list of geometry attributes for type/class name */ + //! Get list of geometry attributes for type/class name QStringList geometryAttributes( const QString & typeName ); - /** Get error if parseXSD() or guessSchema() failed */ + //! Get error if parseXSD() or guessSchema() failed QgsError error() const { return mError; } private: @@ -115,7 +115,7 @@ class CORE_EXPORT QgsGmlSchema : public QObject geometry }; - /** XML handler methods*/ + //! XML handler methods void startElement( const XML_Char* el, const XML_Char** attr ); void endElement( const XML_Char* el ); void characters( const XML_Char* chars, int len ); @@ -140,22 +140,22 @@ class CORE_EXPORT QgsGmlSchema : public QObject @return attribute value or an empty string if no such attribute*/ QString readAttribute( const QString& attributeName, const XML_Char** attr ) const; - /** Returns pointer to main window or 0 if it does not exist*/ + //! Returns pointer to main window or 0 if it does not exist QWidget* findMainWindow() const; - /** Get dom elements by path */ + //! Get dom elements by path QList domElements( const QDomElement &element, const QString & path ); - /** Get dom element by path */ + //! Get dom element by path QDomElement domElement( const QDomElement &element, const QString & path ); - /** Filter list of elements by attribute value */ + //! Filter list of elements by attribute value QList domElements( QList &elements, const QString & attr, const QString & attrVal ); - /** Get dom element by path and attribute value */ + //! Get dom element by path and attribute value QDomElement domElement( const QDomElement &element, const QString & path, const QString & attr, const QString & attrVal ); - /** Strip namespace from element name */ + //! Strip namespace from element name QString stripNS( const QString & name ); /** Find GML base type for complex type of given name @@ -165,39 +165,39 @@ class CORE_EXPORT QgsGmlSchema : public QObject */ QString xsdComplexTypeGmlBaseType( const QDomElement &element, const QString & name ); - /** Get feature class information from complex type recursively */ + //! Get feature class information from complex type recursively bool xsdFeatureClass( const QDomElement &element, const QString & typeName, QgsGmlFeatureClass & featureClass ); - /** Get safely (if empty) top from mode stack */ + //! Get safely (if empty) top from mode stack ParseMode modeStackTop() { return mParseModeStack.isEmpty() ? none : mParseModeStack.top(); } - /** Safely (if empty) pop from mode stack */ + //! Safely (if empty) pop from mode stack ParseMode modeStackPop() { return mParseModeStack.isEmpty() ? none : mParseModeStack.pop(); } - /** Keep track about the most important nested elements*/ + //! Keep track about the most important nested elements //std::stack mParseModeStack; QStack mParseModeStack; - /** This contains the character data if an important element has been encountered*/ + //! This contains the character data if an important element has been encountered QString mStringCash; QgsFeature* mCurrentFeature; QString mCurrentFeatureId; int mFeatureCount; QString mAttributeName; - /** Coordinate separator for coordinate strings. Usually "," */ + //! Coordinate separator for coordinate strings. Usually "," QString mCoordinateSeparator; - /** Tuple separator for coordinate strings. Usually " " */ + //! Tuple separator for coordinate strings. Usually " " QString mTupleSeparator; /* Schema information guessed/parsed from GML in getSchema() */ - /** Depth level, root element is 0 */ + //! Depth level, root element is 0 int mLevel; - /** Skip all levels under this */ + //! Skip all levels under this int mSkipLevel; - /** Path to current level */ + //! Path to current level QStringList mParsePathStack; QString mCurrentFeatureName; diff --git a/src/core/qgslabelingengine.h b/src/core/qgslabelingengine.h index cd3d36e7c1fa..5e8bd6fd4c11 100644 --- a/src/core/qgslabelingengine.h +++ b/src/core/qgslabelingengine.h @@ -51,11 +51,11 @@ class CORE_EXPORT QgsAbstractLabelProvider enum Flag { - DrawLabels = 1 << 1, //!< whether the labels should be rendered - DrawAllLabels = 1 << 2, //!< whether all features will be labelled even though overlaps occur - MergeConnectedLines = 1 << 3, //!< whether adjacent lines (with the same label text) should be merged - CentroidMustBeInside = 1 << 4, //!< whether location of centroid must be inside of polygons - LabelPerFeaturePart = 1 << 6, //!< whether to label each part of multi-part features separately + DrawLabels = 1 << 1, //!< Whether the labels should be rendered + DrawAllLabels = 1 << 2, //!< Whether all features will be labelled even though overlaps occur + MergeConnectedLines = 1 << 3, //!< Whether adjacent lines (with the same label text) should be merged + CentroidMustBeInside = 1 << 4, //!< Whether location of centroid must be inside of polygons + LabelPerFeaturePart = 1 << 6, //!< Whether to label each part of multi-part features separately }; Q_DECLARE_FLAGS( Flags, Flag ) diff --git a/src/core/qgslabelsearchtree.h b/src/core/qgslabelsearchtree.h index 2b3f905bb9e1..1fb3e6f53191 100644 --- a/src/core/qgslabelsearchtree.h +++ b/src/core/qgslabelsearchtree.h @@ -36,7 +36,7 @@ class CORE_EXPORT QgsLabelSearchTree QgsLabelSearchTree(); ~QgsLabelSearchTree(); - /** Removes and deletes all the entries*/ + //! Removes and deletes all the entries void clear(); /** Returns label position(s) at a given point. QgsLabelSearchTree keeps ownership, don't delete the LabelPositions diff --git a/src/core/qgslayerdefinition.h b/src/core/qgslayerdefinition.h index bdcfae3af54e..01b46bb77b7c 100644 --- a/src/core/qgslayerdefinition.h +++ b/src/core/qgslayerdefinition.h @@ -31,13 +31,13 @@ class QgsLayerTreeNode; class CORE_EXPORT QgsLayerDefinition { public: - /** Loads the QLR at path into QGIS. New layers are added to rootGroup and the map layer registry*/ + //! Loads the QLR at path into QGIS. New layers are added to rootGroup and the map layer registry static bool loadLayerDefinition( const QString & path, QgsLayerTreeGroup* rootGroup, QString &errorMessage ); - /** Loads the QLR from the XML document. New layers are added to rootGroup and the map layer registry */ + //! Loads the QLR from the XML document. New layers are added to rootGroup and the map layer registry static bool loadLayerDefinition( QDomDocument doc, QgsLayerTreeGroup* rootGroup, QString &errorMessage ); - /** Export the selected layer tree nodes to a QLR file */ + //! Export the selected layer tree nodes to a QLR file static bool exportLayerDefinition( QString path, const QList& selectedTreeNodes, QString &errorMessage ); - /** Export the selected layer tree nodes to a QLR-XML document */ + //! Export the selected layer tree nodes to a QLR-XML document static bool exportLayerDefinition( QDomDocument doc, const QList& selectedTreeNodes, QString &errorMessage, const QString& relativeBasePath = QString::null ); /** @@ -57,16 +57,16 @@ class CORE_EXPORT QgsLayerDefinition */ DependencySorter( const QString& fileName ); - /** Get the layer nodes in an order where they can be loaded incrementally without dependency break */ + //! Get the layer nodes in an order where they can be loaded incrementally without dependency break QVector sortedLayerNodes() const { return mSortedLayerNodes; } - /** Get the layer IDs in an order where they can be loaded incrementally without dependency break */ + //! Get the layer IDs in an order where they can be loaded incrementally without dependency break QStringList sortedLayerIds() const { return mSortedLayerIds; } - /** Whether some cyclic dependency has been detected */ + //! Whether some cyclic dependency has been detected bool hasCycle() const { return mHasCycle; } - /** Whether some dependency is missing */ + //! Whether some dependency is missing bool hasMissingDependency() const { return mHasMissingDependency; } private: diff --git a/src/core/qgslegendrenderer.h b/src/core/qgslegendrenderer.h index c372f0d805c2..6c7682facd2f 100644 --- a/src/core/qgslegendrenderer.h +++ b/src/core/qgslegendrenderer.h @@ -42,16 +42,16 @@ class QgsSymbol; class CORE_EXPORT QgsLegendRenderer { public: - /** Construct legend renderer. The ownership of legend model does not change */ + //! Construct legend renderer. The ownership of legend model does not change QgsLegendRenderer( QgsLayerTreeModel* legendModel, const QgsLegendSettings& settings ); - /** Run the layout algorithm and determine the size required for legend */ + //! Run the layout algorithm and determine the size required for legend QSizeF minimumSize(); - /** Set the preferred resulting legend size. */ + //! Set the preferred resulting legend size. void setLegendSize( QSizeF s ) { mLegendSize = s; } - /** Find out preferred legend size set by the client. If null, the legend will be drawn with the minimum size */ + //! Find out preferred legend size set by the client. If null, the legend will be drawn with the minimum size QSizeF legendSize() const { return mLegendSize; } /** Draw the legend with given painter. It will occupy the area reported in legendSize(). @@ -109,10 +109,10 @@ class CORE_EXPORT QgsLegendRenderer QSizeF paintAndDetermineSize( QPainter* painter ); - /** Create list of atoms according to current layer splitting mode */ + //! Create list of atoms according to current layer splitting mode QList createAtomList( QgsLayerTreeGroup* parentGroup, bool splitLayer ); - /** Divide atoms to columns and set columns on atoms */ + //! Divide atoms to columns and set columns on atoms void setColumns( QList& atomList ); /** Draws title in the legend using the title font and the specified alignment @@ -129,7 +129,7 @@ class CORE_EXPORT QgsLegendRenderer Nucleon drawSymbolItem( QgsLayerTreeModelLegendNode* symbolItem, QPainter* painter = nullptr, QPointF point = QPointF(), double labelXOffset = 0 ); - /** Draws a layer item */ + //! Draws a layer item QSizeF drawLayerTitle( QgsLayerTreeLayer* nodeLayer, QPainter* painter = nullptr, QPointF point = QPointF() ); /** Draws a group item. diff --git a/src/core/qgslegendsettings.h b/src/core/qgslegendsettings.h index d5ac748a7234..b32bdd94a136 100644 --- a/src/core/qgslegendsettings.h +++ b/src/core/qgslegendsettings.h @@ -52,9 +52,9 @@ class CORE_EXPORT QgsLegendSettings */ void setTitleAlignment( Qt::AlignmentFlag alignment ) { mTitleAlignment = alignment; } - /** Returns reference to modifiable style */ + //! Returns reference to modifiable style QgsComposerLegendStyle & rstyle( QgsComposerLegendStyle::Style s ) { return mStyleMap[s]; } - /** Returns style */ + //! Returns style QgsComposerLegendStyle style( QgsComposerLegendStyle::Style s ) const { return mStyleMap.value( s ); } void setStyle( QgsComposerLegendStyle::Style s, const QgsComposerLegendStyle& style ) { mStyleMap[s] = style; } @@ -178,57 +178,57 @@ class CORE_EXPORT QgsLegendSettings */ void drawText( QPainter* p, const QRectF& rect, const QString& text, const QFont& font, Qt::AlignmentFlag halignment = Qt::AlignLeft, Qt::AlignmentFlag valignment = Qt::AlignTop, int flags = Qt::TextWordWrap ) const; - /** Returns a font where size is in pixel and font size is upscaled with FONT_WORKAROUND_SCALE */ + //! Returns a font where size is in pixel and font size is upscaled with FONT_WORKAROUND_SCALE QFont scaledFontPixelSize( const QFont& font ) const; - /** Calculates font to from point size to pixel size */ + //! Calculates font to from point size to pixel size double pixelFontSize( double pointSize ) const; - /** Returns the font width in millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE */ + //! Returns the font width in millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE double textWidthMillimeters( const QFont& font, const QString& text ) const; - /** Returns the font height of a character in millimeters */ + //! Returns the font height of a character in millimeters double fontHeightCharacterMM( const QFont& font, QChar c ) const; - /** Returns the font ascent in Millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE */ + //! Returns the font ascent in Millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE double fontAscentMillimeters( const QFont& font ) const; - /** Returns the font descent in Millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE */ + //! Returns the font descent in Millimeters (considers upscaling and downscaling with FONT_WORKAROUND_SCALE double fontDescentMillimeters( const QFont& font ) const; private: QString mTitle; - /** Title alignment, one of Qt::AlignLeft, Qt::AlignHCenter, Qt::AlignRight) */ + //! Title alignment, one of Qt::AlignLeft, Qt::AlignHCenter, Qt::AlignRight) Qt::AlignmentFlag mTitleAlignment; QString mWrapChar; QColor mFontColor; - /** Space between item box and contents */ + //! Space between item box and contents qreal mBoxSpace; - /** Width and height of symbol icon */ + //! Width and height of symbol icon QSizeF mSymbolSize; - /** Width and height of WMS legendGraphic pixmap */ + //! Width and height of WMS legendGraphic pixmap QSizeF mWmsLegendSize; - /** Spacing between lines when wrapped */ + //! Spacing between lines when wrapped double mLineSpacing; - /** Space between columns */ + //! Space between columns double mColumnSpace; - /** Number of legend columns */ + //! Number of legend columns int mColumnCount; - /** Allow splitting layers into multiple columns */ + //! Allow splitting layers into multiple columns bool mSplitLayer; - /** Use the same width (maximum) for all columns */ + //! Use the same width (maximum) for all columns bool mEqualColumnWidth; bool mRasterSymbolBorder; @@ -237,16 +237,16 @@ class CORE_EXPORT QgsLegendSettings QMap mStyleMap; - /** Conversion ratio between millimeters and map units - for symbols with size given in map units */ + //! Conversion ratio between millimeters and map units - for symbols with size given in map units double mMmPerMapUnit; - /** Whether to use advanced effects like transparency for symbols - may require their rasterization */ + //! Whether to use advanced effects like transparency for symbols - may require their rasterization bool mUseAdvancedEffects; - /** Denominator of map's scale */ + //! Denominator of map's scale double mMapScale; - /** DPI to be used when rendering legend */ + //! DPI to be used when rendering legend int mDpi; }; diff --git a/src/core/qgslogger.h b/src/core/qgslogger.h index 714df4954c3d..f319aa7531ac 100644 --- a/src/core/qgslogger.h +++ b/src/core/qgslogger.h @@ -62,14 +62,14 @@ class CORE_EXPORT QgsLogger @param line place in file where the message comes from*/ static void debug( const QString& msg, int debuglevel = 1, const char* file = nullptr, const char* function = nullptr, int line = -1 ); - /** Similar to the previous method, but prints a variable int-value pair*/ + //! Similar to the previous method, but prints a variable int-value pair static void debug( const QString& var, int val, int debuglevel = 1, const char* file = nullptr, const char* function = nullptr, int line = -1 ); - /** Similar to the previous method, but prints a variable double-value pair*/ + //! Similar to the previous method, but prints a variable double-value pair // @note not available in python bindings static void debug( const QString& var, double val, int debuglevel = 1, const char* file = nullptr, const char* function = nullptr, int line = -1 ); - /** Prints out a variable/value pair for types with overloaded operator<<*/ + //! Prints out a variable/value pair for types with overloaded operator<< // @note not available in python bindings template static void debug( const QString& var, T val, const char* file = nullptr, const char* function = nullptr, int line = -1, int debuglevel = 1 ) @@ -79,20 +79,20 @@ class CORE_EXPORT QgsLogger debug( var, os.str().c_str(), file, function, line, debuglevel ); } - /** Goes to qWarning*/ + //! Goes to qWarning static void warning( const QString& msg ); - /** Goes to qCritical*/ + //! Goes to qCritical static void critical( const QString& msg ); - /** Goes to qFatal*/ + //! Goes to qFatal static void fatal( const QString& msg ); /** Reads the environment variable QGIS_DEBUG and converts it to int. If QGIS_DEBUG is not set, the function returns 1 if QGISDEBUG is defined and 0 if not*/ static int debugLevel() { init(); return sDebugLevel; } - /** Logs the message passed in to the logfile defined in QGIS_LOG_FILE if any. **/ + //! Logs the message passed in to the logfile defined in QGIS_LOG_FILE if any. * static void logMessageToFile( const QString& theMessage ); /** Reads the environment variable QGIS_LOG_FILE. Returns NULL if the variable is not set, @@ -102,7 +102,7 @@ class CORE_EXPORT QgsLogger private: static void init(); - /** Current debug level */ + //! Current debug level static int sDebugLevel; static int sPrefixLength; static QString sLogFile; diff --git a/src/core/qgsmaplayer.cpp b/src/core/qgsmaplayer.cpp index 7322ba409c80..31fde2814f97 100644 --- a/src/core/qgsmaplayer.cpp +++ b/src/core/qgsmaplayer.cpp @@ -97,7 +97,7 @@ QgsMapLayer::LayerType QgsMapLayer::type() const return mLayerType; } -/** Get this layer's unique ID */ +//! Get this layer's unique ID QString QgsMapLayer::id() const { return mID; @@ -115,7 +115,7 @@ void QgsMapLayer::setName( const QString& name ) emit nameChanged(); } -/** Read property of QString layerName. */ +//! Read property of QString layerName. QString QgsMapLayer::name() const { QgsDebugMsgLevel( "returning name '" + mLayerName + '\'', 4 ); @@ -140,7 +140,7 @@ QgsRectangle QgsMapLayer::extent() const return mExtent; } -/** Write blend mode for layer */ +//! Write blend mode for layer void QgsMapLayer::setBlendMode( QPainter::CompositionMode blendMode ) { mBlendMode = blendMode; @@ -148,7 +148,7 @@ void QgsMapLayer::setBlendMode( QPainter::CompositionMode blendMode ) emit styleChanged(); } -/** Read blend mode for layer */ +//! Read blend mode for layer QPainter::CompositionMode QgsMapLayer::blendMode() const { return mBlendMode; diff --git a/src/core/qgsmaplayer.h b/src/core/qgsmaplayer.h index 5f86f5793c5f..9d4ed928d485 100644 --- a/src/core/qgsmaplayer.h +++ b/src/core/qgsmaplayer.h @@ -75,7 +75,7 @@ class CORE_EXPORT QgsMapLayer : public QObject */ QgsMapLayer::LayerType type() const; - /** Returns the layer's unique ID, which is used to access this layer from QgsMapLayerRegistry. */ + //! Returns the layer's unique ID, which is used to access this layer from QgsMapLayerRegistry. QString id() const; /** @@ -282,7 +282,7 @@ class CORE_EXPORT QgsMapLayer : public QObject */ QPainter::CompositionMode blendMode() const; - /** Returns if this layer is read only. */ + //! Returns if this layer is read only. bool readOnly() const { return isReadOnly(); } /** Synchronises with changes in the datasource @@ -294,7 +294,7 @@ class CORE_EXPORT QgsMapLayer : public QObject */ virtual QgsMapLayerRenderer* createMapRenderer( QgsRenderContext& rendererContext ) = 0; - /** Returns the extent of the layer. */ + //! Returns the extent of the layer. virtual QgsRectangle extent() const; /** Return the status of the layer. An invalid layer is one which has a bad datasource @@ -334,7 +334,7 @@ class CORE_EXPORT QgsMapLayer : public QObject */ virtual void setSubLayerVisibility( const QString& name, bool visible ); - /** Returns true if the layer can be edited. */ + //! Returns true if the layer can be edited. virtual bool isEditable() const; /** Returns true if the layer is considered a spatial layer, ie it has some form of geometry associated with it. @@ -414,10 +414,10 @@ class CORE_EXPORT QgsMapLayer : public QObject */ QgsCoordinateReferenceSystem crs() const; - /** Sets layer's spatial reference system */ + //! Sets layer's spatial reference system void setCrs( const QgsCoordinateReferenceSystem& srs, bool emitSignal = true ); - /** A convenience function to (un)capitalise the layer name */ + //! A convenience function to (un)capitalise the layer name static QString capitaliseLayerName( const QString& name ); /** Retrieve the style URI for this layer @@ -570,7 +570,7 @@ class CORE_EXPORT QgsMapLayer : public QObject */ virtual bool writeStyle( QDomNode& node, QDomDocument& doc, QString& errorMessage ) const; - /** Return pointer to layer's undo stack */ + //! Return pointer to layer's undo stack QUndoStack *undoStack(); /** Return pointer to layer's style undo stack @@ -643,7 +643,7 @@ class CORE_EXPORT QgsMapLayer : public QObject public slots: - /** Event handler for when a coordinate transform fails due to bad vertex error */ + //! Event handler for when a coordinate transform fails due to bad vertex error virtual void invalidTransformInput(); /** Sets the minimum scale denominator at which the layer will be visible. @@ -680,10 +680,10 @@ class CORE_EXPORT QgsMapLayer : public QObject */ void triggerRepaint(); - /** \brief Obtain Metadata for this layer */ + //! \brief Obtain Metadata for this layer virtual QString metadata() const; - /** Time stamp of data source in the moment when data/metadata were loaded by provider */ + //! Time stamp of data source in the moment when data/metadata were loaded by provider virtual QDateTime timestamp() const { return QDateTime() ; } /** Triggers an emission of the styleChanged() signal. @@ -712,7 +712,7 @@ class CORE_EXPORT QgsMapLayer : public QObject signals: - /** Emit a signal with status (e.g. to be caught by QgisApp and display a msg on status bar) */ + //! Emit a signal with status (e.g. to be caught by QgisApp and display a msg on status bar) void statusChanged( const QString& status ); /** @@ -722,7 +722,7 @@ class CORE_EXPORT QgsMapLayer : public QObject */ void nameChanged(); - /** Emit a signal that layer's CRS has been reset */ + //! Emit a signal that layer's CRS has been reset void crsChanged(); /** By emitting this signal the layer tells that either appearance or content have been changed @@ -730,13 +730,13 @@ class CORE_EXPORT QgsMapLayer : public QObject */ void repaintRequested(); - /** This is used to send a request that any mapcanvas using this layer update its extents */ + //! This is used to send a request that any mapcanvas using this layer update its extents void recalculateExtents() const; - /** Data of layer changed */ + //! Data of layer changed void dataChanged(); - /** Signal emitted when the blend mode is changed, through QgsMapLayer::setBlendMode() */ + //! Signal emitted when the blend mode is changed, through QgsMapLayer::setBlendMode() void blendModeChanged( QPainter::CompositionMode blendMode ); /** Signal emitted when renderer is changed. @@ -770,10 +770,10 @@ class CORE_EXPORT QgsMapLayer : public QObject void dependenciesChanged(); protected: - /** Set the extent */ + //! Set the extent virtual void setExtent( const QgsRectangle &rect ); - /** Set whether layer is valid or not - should be used in constructor. */ + //! Set whether layer is valid or not - should be used in constructor. void setValid( bool valid ); /** Called by readLayerXML(), used by children to read state specific to them from @@ -792,34 +792,34 @@ class CORE_EXPORT QgsMapLayer : public QObject @param keyStartsWith reads only properties starting with the specified string (or all if the string is empty)*/ void readCustomProperties( const QDomNode& layerNode, const QString& keyStartsWith = "" ); - /** Write custom properties to project file. */ + //! Write custom properties to project file. void writeCustomProperties( QDomNode & layerNode, QDomDocument & doc ) const; - /** Read style manager's configuration (if any). To be called by subclasses. */ + //! Read style manager's configuration (if any). To be called by subclasses. void readStyleManager( const QDomNode& layerNode ); - /** Write style manager's configuration (if exists). To be called by subclasses. */ + //! Write style manager's configuration (if exists). To be called by subclasses. void writeStyleManager( QDomNode& layerNode, QDomDocument& doc ) const; #if 0 - /** Debugging member - invoked when a connect() is made to this object */ + //! Debugging member - invoked when a connect() is made to this object void connectNotify( const char * signal ) override; #endif - /** Add error message */ + //! Add error message void appendError( const QgsErrorMessage & error ) { mError.append( error );} - /** Set error message */ + //! Set error message void setError( const QgsError & error ) { mError = error;} - /** Extent of the layer */ + //! Extent of the layer mutable QgsRectangle mExtent; - /** Indicates if the layer is valid and can be drawn */ + //! Indicates if the layer is valid and can be drawn bool mValid; - /** Data source description string, varies by layer type */ + //! Data source description string, varies by layer type QString mDataSource; - /** Name of the layer - used for display */ + //! Name of the layer - used for display QString mLayerName; /** Original name of the layer @@ -829,28 +829,28 @@ class CORE_EXPORT QgsMapLayer : public QObject QString mShortName; QString mTitle; - /** Description of the layer*/ + //! Description of the layer QString mAbstract; QString mKeywordList; - /** DataUrl of the layer*/ + //! DataUrl of the layer QString mDataUrl; QString mDataUrlFormat; - /** Attribution of the layer*/ + //! Attribution of the layer QString mAttribution; QString mAttributionUrl; - /** MetadataUrl of the layer*/ + //! MetadataUrl of the layer QString mMetadataUrl; QString mMetadataUrlType; QString mMetadataUrlFormat; - /** WMS legend*/ + //! WMS legend QString mLegendUrl; QString mLegendUrlFormat; - /** \brief Error */ + //! \brief Error QgsError mError; //! List of layers that may modify this layer on modification @@ -870,32 +870,32 @@ class CORE_EXPORT QgsMapLayer : public QObject private to make sure setCrs must be used and crsChanged() is emitted */ QgsCoordinateReferenceSystem mCRS; - /** Private copy constructor - QgsMapLayer not copyable */ + //! Private copy constructor - QgsMapLayer not copyable QgsMapLayer( QgsMapLayer const & ); - /** Private assign operator - QgsMapLayer not copyable */ + //! Private assign operator - QgsMapLayer not copyable QgsMapLayer & operator=( QgsMapLayer const & ); - /** Unique ID of this layer - used to refer to this layer in map layer registry */ + //! Unique ID of this layer - used to refer to this layer in map layer registry QString mID; - /** Type of the layer (eg. vector, raster) */ + //! Type of the layer (eg. vector, raster) QgsMapLayer::LayerType mLayerType; - /** Blend mode for the layer */ + //! Blend mode for the layer QPainter::CompositionMode mBlendMode; - /** Tag for embedding additional information */ + //! Tag for embedding additional information QString mTag; - /** Minimum scale denominator at which this layer should be displayed */ + //! Minimum scale denominator at which this layer should be displayed double mMinScale; - /** Maximum scale denominator at which this layer should be displayed */ + //! Maximum scale denominator at which this layer should be displayed double mMaxScale; - /** A flag that tells us whether to use the above vars to restrict layer visibility */ + //! A flag that tells us whether to use the above vars to restrict layer visibility bool mScaleBasedVisibility; - /** Collection of undoable operations for this layer. **/ + //! Collection of undoable operations for this layer. * QUndoStack mUndoStack; QUndoStack mUndoStackStyles; diff --git a/src/core/qgsmaplayermodel.h b/src/core/qgsmaplayermodel.h index db3de5079c8b..33badce780c9 100644 --- a/src/core/qgsmaplayermodel.h +++ b/src/core/qgsmaplayermodel.h @@ -37,8 +37,8 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel //! Item data roles enum ItemDataRole { - LayerIdRole = Qt::UserRole + 1, /*!< Stores the map layer ID */ - LayerRole, /*!< Stores pointer to the map layer itself */ + LayerIdRole = Qt::UserRole + 1, //!< Stores the map layer ID + LayerRole, //!< Stores pointer to the map layer itself }; /** diff --git a/src/core/qgsmaprendererjob.h b/src/core/qgsmaprendererjob.h index ff57843cd961..fd7ce11e4630 100644 --- a/src/core/qgsmaprendererjob.h +++ b/src/core/qgsmaprendererjob.h @@ -49,7 +49,7 @@ struct LayerRenderJob double opacity; bool cached; // if true, img already contains cached image from previous rendering QString layerId; - int renderingTime; //!< time it took to render the layer in ms (it is -1 if not rendered or still rendering) + int renderingTime; //!< Time it took to render the layer in ms (it is -1 if not rendered or still rendering) }; typedef QList LayerRenderJobs; diff --git a/src/core/qgsmapsettings.h b/src/core/qgsmapsettings.h index 06e5624caa9e..b42be6671682 100644 --- a/src/core/qgsmapsettings.h +++ b/src/core/qgsmapsettings.h @@ -284,12 +284,12 @@ class CORE_EXPORT QgsMapSettings /** Sets the segmentation tolerance applied when rendering curved geometries @param tolerance the segmentation tolerance*/ void setSegmentationTolerance( double tolerance ) { mSegmentationTolerance = tolerance; } - /** Gets the segmentation tolerance applied when rendering curved geometries*/ + //! Gets the segmentation tolerance applied when rendering curved geometries double segmentationTolerance() const { return mSegmentationTolerance; } /** Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation) @param type the segmentation tolerance typename*/ void setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType type ) { mSegmentationToleranceType = type; } - /** Gets segmentation tolerance type (maximum angle or maximum difference between curve and approximation)*/ + //! Gets segmentation tolerance type (maximum angle or maximum difference between curve and approximation) QgsAbstractGeometry::SegmentationToleranceType segmentationToleranceType() const { return mSegmentationToleranceType; } protected: @@ -324,8 +324,8 @@ class CORE_EXPORT QgsMapSettings // derived properties - bool mValid; //!< whether the actual settings are valid (set in updateDerived()) - QgsRectangle mVisibleExtent; //!< extent with some additional white space that matches the output aspect ratio + bool mValid; //!< Whether the actual settings are valid (set in updateDerived()) + QgsRectangle mVisibleExtent; //!< Extent with some additional white space that matches the output aspect ratio double mMapUnitsPerPixel; double mScale; diff --git a/src/core/qgsmapunitscale.h b/src/core/qgsmapunitscale.h index 6b0c19634772..6529d01fba07 100644 --- a/src/core/qgsmapunitscale.h +++ b/src/core/qgsmapunitscale.h @@ -47,18 +47,18 @@ class CORE_EXPORT QgsMapUnitScale , maxSizeMM( 0.0 ) {} - /** The minimum scale, or 0.0 if unset */ + //! The minimum scale, or 0.0 if unset double minScale; - /** The maximum scale, or 0.0 if unset */ + //! The maximum scale, or 0.0 if unset double maxScale; - /** Whether the minimum size in mm should be respected */ + //! Whether the minimum size in mm should be respected bool minSizeMMEnabled; - /** The minimum size in millimeters, or 0.0 if unset */ + //! The minimum size in millimeters, or 0.0 if unset double minSizeMM; - /** Whether the maximum size in mm should be respected */ + //! Whether the maximum size in mm should be respected bool maxSizeMMEnabled; - /** The maximum size in millimeters, or 0.0 if unset */ + //! The maximum size in millimeters, or 0.0 if unset double maxSizeMM; /** Computes a map units per pixel scaling factor, respecting the minimum and maximum scales diff --git a/src/core/qgsnetworkreplyparser.h b/src/core/qgsnetworkreplyparser.h index 3395370b9765..ca7cf7b1b184 100644 --- a/src/core/qgsnetworkreplyparser.h +++ b/src/core/qgsnetworkreplyparser.h @@ -56,7 +56,7 @@ class CORE_EXPORT QgsNetworkReplyParser : public QObject * @return raw header */ QByteArray rawHeader( int part, const QByteArray & headerName ) const { return mHeaders.value( part ).value( headerName ); } - /** Get headers */ + //! Get headers QList< RawHeaderMap > headers() const { return mHeaders; } /** Get part part body @@ -64,10 +64,10 @@ class CORE_EXPORT QgsNetworkReplyParser : public QObject * @return part body */ QByteArray body( int part ) const { return mBodies.value( part ); } - /** Get bodies */ + //! Get bodies QList bodies() const { return mBodies; } - /** Parsing error */ + //! Parsing error QString error() const { return mError; } /** Test if reply is multipart. diff --git a/src/core/qgsobjectcustomproperties.h b/src/core/qgsobjectcustomproperties.h index 213fbbb362c2..27782bdf2196 100644 --- a/src/core/qgsobjectcustomproperties.h +++ b/src/core/qgsobjectcustomproperties.h @@ -54,7 +54,7 @@ class CORE_EXPORT QgsObjectCustomProperties */ void readXml( const QDomNode& parentNode, const QString& keyStartsWith = QString() ); - /** Write store contents to XML */ + //! Write store contents to XML void writeXml( QDomNode& parentNode, QDomDocument& doc ) const; diff --git a/src/core/qgsofflineediting.h b/src/core/qgsofflineediting.h index 0d088cb2345d..b5dfb3b4bdb8 100644 --- a/src/core/qgsofflineediting.h +++ b/src/core/qgsofflineediting.h @@ -58,14 +58,14 @@ class CORE_EXPORT QgsOfflineEditing : public QObject */ bool convertToOfflineProject( const QString& offlineDataPath, const QString& offlineDbFile, const QStringList& layerIds, bool onlySelected = false ); - /** Return true if current project is offline */ + //! Return true if current project is offline bool isOfflineProject() const; - /** Synchronize to remote layers */ + //! Synchronize to remote layers void synchronize(); signals: - /** Emit a signal that processing has started */ + //! Emit a signal that processing has started void progressStarted(); /** Emit a signal that the next layer of numLayers has started processing @@ -85,7 +85,7 @@ class CORE_EXPORT QgsOfflineEditing : public QObject */ void progressUpdated( int progress ); - /** Emit a signal that processing of all layers has finished */ + //! Emit a signal that processing of all layers has finished void progressStopped(); /** diff --git a/src/core/qgsogcutils.h b/src/core/qgsogcutils.h index fb46c0019dfe..fa908095797e 100644 --- a/src/core/qgsogcutils.h +++ b/src/core/qgsogcutils.h @@ -65,10 +65,10 @@ class CORE_EXPORT QgsOgcUtils */ static QgsGeometry geometryFromGML( const QDomNode& geometryNode ); - /** Read rectangle from GML2 Box */ + //! Read rectangle from GML2 Box static QgsRectangle rectangleFromGMLBox( const QDomNode& boxNode ); - /** Read rectangle from GML3 Envelope */ + //! Read rectangle from GML3 Envelope static QgsRectangle rectangleFromGMLEnvelope( const QDomNode& envelopeNode ); /** Exports the geometry to GML @@ -121,10 +121,10 @@ class CORE_EXPORT QgsOgcUtils int precision = 17 ); - /** Parse XML with OGC fill into QColor */ + //! Parse XML with OGC fill into QColor static QColor colorFromOgcFill( const QDomElement& fillElement ); - /** Parse XML with OGC filter into QGIS expression */ + //! Parse XML with OGC filter into QGIS expression static QgsExpression* expressionFromOgcFilter( const QDomElement& element ); /** Creates OGC filter XML element. Supports minimum standard filter @@ -189,14 +189,14 @@ class CORE_EXPORT QgsOgcUtils class LayerProperties { public: - /** Constructor */ + //! Constructor LayerProperties() {} - /** Layer name */ + //! Layer name QString mName; - /** Geometry attribute name */ + //! Geometry attribute name QString mGeometryAttribute; - /** SRS name */ + //! SRS name QString mSRSName; }; @@ -229,17 +229,17 @@ class CORE_EXPORT QgsOgcUtils private: - /** Static method that creates geometry from GML Point */ + //! Static method that creates geometry from GML Point static QgsGeometry geometryFromGMLPoint( const QDomElement& geometryElement ); - /** Static method that creates geometry from GML LineString */ + //! Static method that creates geometry from GML LineString static QgsGeometry geometryFromGMLLineString( const QDomElement& geometryElement ); - /** Static method that creates geometry from GML Polygon */ + //! Static method that creates geometry from GML Polygon static QgsGeometry geometryFromGMLPolygon( const QDomElement& geometryElement ); - /** Static method that creates geometry from GML MultiPoint */ + //! Static method that creates geometry from GML MultiPoint static QgsGeometry geometryFromGMLMultiPoint( const QDomElement& geometryElement ); - /** Static method that creates geometry from GML MultiLineString */ + //! Static method that creates geometry from GML MultiLineString static QgsGeometry geometryFromGMLMultiLineString( const QDomElement& geometryElement ); - /** Static method that creates geometry from GML MultiPolygon */ + //! Static method that creates geometry from GML MultiPolygon static QgsGeometry geometryFromGMLMultiPolygon( const QDomElement& geometryElement ); /** Reads the \verbatim \endverbatim element and extracts the coordinates as points @param coords list where the found coordinates are appended @@ -294,7 +294,7 @@ class CORE_EXPORT QgsOgcUtils class QgsOgcUtilsExprToFilter { public: - /** Constructor */ + //! Constructor QgsOgcUtilsExprToFilter( QDomDocument& doc, QgsOgcUtils::GMLVersion gmlVersion, QgsOgcUtils::FilterVersion filterVersion, @@ -303,13 +303,13 @@ class QgsOgcUtilsExprToFilter bool honourAxisOrientation, bool invertAxisOrientation ); - /** Convert an expression to a OGC filter */ + //! Convert an expression to a OGC filter QDomElement expressionNodeToOgcFilter( const QgsExpression::Node* node ); - /** Return whether the gml: namespace is used */ + //! Return whether the gml: namespace is used bool GMLNamespaceUsed() const { return mGMLUsed; } - /** Return the error message. */ + //! Return the error message. const QString& errorMessage() const { return mErrorMessage; } private: @@ -340,7 +340,7 @@ class QgsOgcUtilsExprToFilter class QgsOgcUtilsSQLStatementToFilter { public: - /** Constructor */ + //! Constructor QgsOgcUtilsSQLStatementToFilter( QDomDocument& doc, QgsOgcUtils::GMLVersion gmlVersion, QgsOgcUtils::FilterVersion filterVersion, @@ -349,13 +349,13 @@ class QgsOgcUtilsSQLStatementToFilter bool invertAxisOrientation, const QMap< QString, QString>& mapUnprefixedTypenameToPrefixedTypename ); - /** Convert a SQL statement to a OGC filter */ + //! Convert a SQL statement to a OGC filter QDomElement toOgcFilter( const QgsSQLStatement::Node* node ); - /** Return whether the gml: namespace is used */ + //! Return whether the gml: namespace is used bool GMLNamespaceUsed() const { return mGMLUsed; } - /** Return the error message. */ + //! Return the error message. const QString& errorMessage() const { return mErrorMessage; } private: diff --git a/src/core/qgsowsconnection.h b/src/core/qgsowsconnection.h index e2aee7dcdd2e..e0231e6f80a7 100644 --- a/src/core/qgsowsconnection.h +++ b/src/core/qgsowsconnection.h @@ -45,19 +45,19 @@ class CORE_EXPORT QgsOwsConnection : public QObject //! Destructor ~QgsOwsConnection(); - /** Returns the list of connections for the specified service */ + //! Returns the list of connections for the specified service static QStringList connectionList( const QString & theService ); - /** Deletes the connection for the specified service with the specified name */ + //! Deletes the connection for the specified service with the specified name static void deleteConnection( const QString & theService, const QString & name ); - /** Retreives the selected connection for the specified service */ + //! Retreives the selected connection for the specified service static QString selectedConnection( const QString & theService ); - /** Marks the specified connection for the specified service as selected */ + //! Marks the specified connection for the specified service as selected static void setSelectedConnection( const QString & theService, const QString & name ); QString mConnName; - /** Returns the connection uri */ + //! Returns the connection uri QgsDataSourceUri uri() const; QString mConnectionInfo; diff --git a/src/core/qgspalgeometry.h b/src/core/qgspalgeometry.h index d8d3864df13e..c065341648ff 100644 --- a/src/core/qgspalgeometry.h +++ b/src/core/qgspalgeometry.h @@ -142,7 +142,7 @@ class QgsTextLabelFeature : public QgsLabelFeature QFont mDefinedFont; //! Metrics of the font for rendering QFontMetricsF* mFontMetrics; - /** Stores attribute values for data defined properties*/ + //! Stores attribute values for data defined properties QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > mDataDefinedValues; }; diff --git a/src/core/qgspallabeling.h b/src/core/qgspallabeling.h index 7230ce9475c8..3481124c25b6 100644 --- a/src/core/qgspallabeling.h +++ b/src/core/qgspallabeling.h @@ -179,14 +179,14 @@ class CORE_EXPORT QgsPalLayerSettings //TODO QGIS 3.0 - move to QgsLabelingEngine enum Placement { - AroundPoint, /**< Arranges candidates in a circle around a point (or centroid of a polygon). Applies to point or polygon layers only.*/ - OverPoint, /** Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point. Applies to point or polygon layers only.*/ - Line, /**< Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon's perimeter. Applies to line or polygon layers only. */ - Curved, /** Arranges candidates following the curvature of a line feature. Applies to line layers only.*/ - Horizontal, /**< Arranges horizontal candidates scattered throughout a polygon feature. Applies to polygon layers only.*/ - Free, /**< Arranges candidates scattered throughout a polygon feature. Candidates are rotated to respect the polygon's orientation. Applies to polygon layers only.*/ - OrderedPositionsAroundPoint, /**< Candidates are placed in predefined positions around a point. Peference is given to positions with greatest cartographic appeal, eg top right, bottom right, etc. Applies to point layers only.*/ - PerimeterCurved, /** Arranges candidates following the curvature of a polygon's boundary. Applies to polygon layers only.*/ + AroundPoint, //!< Arranges candidates in a circle around a point (or centroid of a polygon). Applies to point or polygon layers only. + OverPoint, //! Arranges candidates over a point (or centroid of a polygon), or at a preset offset from the point. Applies to point or polygon layers only. + Line, //!< Arranges candidates parallel to a generalised line representing the feature or parallel to a polygon's perimeter. Applies to line or polygon layers only. + Curved, //! Arranges candidates following the curvature of a line feature. Applies to line layers only. + Horizontal, //!< Arranges horizontal candidates scattered throughout a polygon feature. Applies to polygon layers only. + Free, //!< Arranges candidates scattered throughout a polygon feature. Candidates are rotated to respect the polygon's orientation. Applies to polygon layers only. + OrderedPositionsAroundPoint, //!< Candidates are placed in predefined positions around a point. Peference is given to positions with greatest cartographic appeal, eg top right, bottom right, etc. Applies to point layers only. + PerimeterCurved, //! Arranges candidates following the curvature of a polygon's boundary. Applies to polygon layers only. }; //! Positions for labels when using the QgsPalLabeling::OrderedPositionsAroundPoint placement mode @@ -222,7 +222,7 @@ class CORE_EXPORT QgsPalLayerSettings //LinePlacementFlags type, and replace use of pal::LineArrangementFlag enum LinePlacementFlags { - OnLine = 1, /**< Labels can be placed directly over a line feature.*/ + OnLine = 1, //!< Labels can be placed directly over a line feature. AboveLine = 2, /**< Labels can be placed above a line feature. Unless MapOrientation is also specified this mode respects the direction of the line feature, so a line from right to left labels will have labels placed placed below the line feature. */ @@ -249,16 +249,16 @@ class CORE_EXPORT QgsPalLayerSettings enum UpsideDownLabels { - Upright, /*!< upside-down labels (90 <= angle < 270) are shown upright */ - ShowDefined, /*!< show upside down when rotation is layer- or data-defined */ - ShowAll /*!< show upside down for all labels, including dynamic ones */ + Upright, //!< Upside-down labels (90 <= angle < 270) are shown upright + ShowDefined, //!< Show upside down when rotation is layer- or data-defined + ShowAll //!< Show upside down for all labels, including dynamic ones }; enum DirectionSymbols { - SymbolLeftRight, /*!< place direction symbols on left/right of label */ - SymbolAbove, /*!< place direction symbols on above label */ - SymbolBelow /*!< place direction symbols on below label */ + SymbolLeftRight, //!< Place direction symbols on left/right of label + SymbolAbove, //!< Place direction symbols on above label + SymbolBelow //!< Place direction symbols on below label }; enum MultiLineAlign @@ -287,7 +287,7 @@ class CORE_EXPORT QgsPalLayerSettings }; - /** Units used for option sizes, before being converted to rendered sizes */ + //! Units used for option sizes, before being converted to rendered sizes enum SizeUnit { Points = 0, @@ -576,7 +576,7 @@ class CORE_EXPORT QgsPalLayerSettings void setDataDefinedProperty( QgsPalLayerSettings::DataDefinedProperties p, bool active, bool useExpr, const QString& expr, const QString& field ); - /** Set a property to static instead data defined */ + //! Set a property to static instead data defined void removeDataDefinedProperty( QgsPalLayerSettings::DataDefinedProperties p ); /** Clear all data-defined properties diff --git a/src/core/qgspluginlayer.h b/src/core/qgspluginlayer.h index f57be662f82b..66a7a670204c 100644 --- a/src/core/qgspluginlayer.h +++ b/src/core/qgspluginlayer.h @@ -34,10 +34,10 @@ class CORE_EXPORT QgsPluginLayer : public QgsMapLayer public: QgsPluginLayer( const QString& layerType, const QString& layerName = QString() ); - /** Return plugin layer type (the same as used in QgsPluginLayerRegistry) */ + //! Return plugin layer type (the same as used in QgsPluginLayerRegistry) QString pluginLayerType(); - /** Set extent of the layer */ + //! Set extent of the layer void setExtent( const QgsRectangle &extent ) override; /** Set source string. This is used for example in layer tree to show tooltip. diff --git a/src/core/qgspluginlayerregistry.cpp b/src/core/qgspluginlayerregistry.cpp index cd0390ef0f8a..0e2d5708db95 100644 --- a/src/core/qgspluginlayerregistry.cpp +++ b/src/core/qgspluginlayerregistry.cpp @@ -54,7 +54,7 @@ bool QgsPluginLayerType::showLayerProperties( QgsPluginLayer *layer ) //============================================================================= -/** Static calls to enforce singleton behaviour */ +//! Static calls to enforce singleton behaviour QgsPluginLayerRegistry* QgsPluginLayerRegistry::_instance = nullptr; QgsPluginLayerRegistry* QgsPluginLayerRegistry::instance() { diff --git a/src/core/qgspluginlayerregistry.h b/src/core/qgspluginlayerregistry.h index 7fa06718ae9a..9d0a8fbf6283 100644 --- a/src/core/qgspluginlayerregistry.h +++ b/src/core/qgspluginlayerregistry.h @@ -36,7 +36,7 @@ class CORE_EXPORT QgsPluginLayerType QString name(); - /** Return new layer of this type. Return NULL on error */ + //! Return new layer of this type. Return NULL on error virtual QgsPluginLayer* createLayer(); /** Return new layer of this type, using layer URI (specific to this plugin layer type). Return NULL on error. @@ -44,7 +44,7 @@ class CORE_EXPORT QgsPluginLayerType */ virtual QgsPluginLayer* createLayer( const QString& uri ); - /** Show plugin layer properties dialog. Return false if the dialog cannot be shown. */ + //! Show plugin layer properties dialog. Return false if the dialog cannot be shown. virtual bool showLayerProperties( QgsPluginLayer* layer ); protected: @@ -60,7 +60,7 @@ class CORE_EXPORT QgsPluginLayerRegistry { public: - /** Means of accessing canonical single instance */ + //! Means of accessing canonical single instance static QgsPluginLayerRegistry* instance(); ~QgsPluginLayerRegistry(); @@ -69,13 +69,13 @@ class CORE_EXPORT QgsPluginLayerRegistry * \note added in v2.1 */ QStringList pluginLayerTypes(); - /** Add plugin layer type (take ownership) and return true on success */ + //! Add plugin layer type (take ownership) and return true on success bool addPluginLayerType( QgsPluginLayerType* pluginLayerType ); - /** Remove plugin layer type and return true on success */ + //! Remove plugin layer type and return true on success bool removePluginLayerType( const QString& typeName ); - /** Return plugin layer type metadata or NULL if doesn't exist */ + //! Return plugin layer type metadata or NULL if doesn't exist QgsPluginLayerType* pluginLayerType( const QString& typeName ); /** Return new layer if corresponding plugin has been found, else return NULL. @@ -87,12 +87,12 @@ class CORE_EXPORT QgsPluginLayerRegistry typedef QMap PluginLayerTypes; - /** Private since instance() creates it */ + //! Private since instance() creates it QgsPluginLayerRegistry(); QgsPluginLayerRegistry( const QgsPluginLayerRegistry& rh ); QgsPluginLayerRegistry& operator=( const QgsPluginLayerRegistry& rh ); - /** Pointer to canonical Singleton object */ + //! Pointer to canonical Singleton object static QgsPluginLayerRegistry* _instance; PluginLayerTypes mPluginLayerTypes; diff --git a/src/core/qgspoint.h b/src/core/qgspoint.h index 56fed3917edf..6fbf0a59db39 100644 --- a/src/core/qgspoint.h +++ b/src/core/qgspoint.h @@ -122,7 +122,7 @@ class CORE_EXPORT QgsPoint , m_y( 0.0 ) {} - /** Create a point from another point */ + //! Create a point from another point QgsPoint( const QgsPoint& p ); /** Create a point from x,y coordinates @@ -171,7 +171,7 @@ class CORE_EXPORT QgsPoint m_y = y; } - /** Sets the x and y value of the point */ + //! Sets the x and y value of the point void set( double x, double y ) { m_x = x; @@ -260,10 +260,10 @@ class CORE_EXPORT QgsPoint */ double distance( const QgsPoint& other ) const; - /** Returns the minimum distance between this point and a segment */ + //! Returns the minimum distance between this point and a segment double sqrDistToSegment( double x1, double y1, double x2, double y2, QgsPoint& minDistPoint, double epsilon = DEFAULT_SEGMENT_EPSILON ) const; - /** Calculates azimuth between this point and other one (clockwise in degree, starting from north) */ + //! Calculates azimuth between this point and other one (clockwise in degree, starting from north) double azimuth( const QgsPoint& other ) const; /** Returns a new point which correponds to this point projected by a specified distance diff --git a/src/core/qgspointlocator.h b/src/core/qgspointlocator.h index faf35b4078b1..272da0ce7ea5 100644 --- a/src/core/qgspointlocator.h +++ b/src/core/qgspointlocator.h @@ -92,7 +92,7 @@ class CORE_EXPORT QgsPointLocator : public QObject * false if the creation of index has been prematurely stopped due to the limit of features, otherwise true */ bool init( int maxFeaturesToIndex = -1 ); - /** Indicate whether the data have been already indexed */ + //! Indicate whether the data have been already indexed bool hasIndex() const; struct Match @@ -215,7 +215,7 @@ class CORE_EXPORT QgsPointLocator : public QObject void onGeometryChanged( QgsFeatureId fid, const QgsGeometry& geom ); private: - /** Storage manager */ + //! Storage manager SpatialIndex::IStorageManager* mStorage; QHash mGeoms; @@ -224,7 +224,7 @@ class CORE_EXPORT QgsPointLocator : public QObject //! flag whether the layer is currently empty (i.e. mRTree is null but it is not necessary to rebuild it) bool mIsEmptyLayer; - /** R-tree containing spatial index */ + //! R-tree containing spatial index QgsCoordinateTransform mTransform; QgsVectorLayer* mLayer; QgsRectangle* mExtent; diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index d8d06aca731c..63d6e0cdbc5b 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -282,7 +282,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera bool readBoolEntry( const QString& scope, const QString& key, bool def = false, bool* ok = nullptr ) const; - /** Remove the given key */ + //! Remove the given key bool removeEntry( const QString& scope, const QString& key ); @@ -312,10 +312,10 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ QString writePath( const QString& filename, const QString& relativeBasePath = QString::null ) const; - /** Turn filename read from the project file to an absolute path */ + //! Turn filename read from the project file to an absolute path QString readPath( QString filename ) const; - /** Return error message from previous read/write */ + //! Return error message from previous read/write QString error() const; /** Change handler for missing layers. @@ -323,7 +323,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ void setBadLayerHandler( QgsProjectBadLayerHandler* handler ); - /** Returns project file path if layer is embedded from other project file. Returns empty string if layer is not embedded*/ + //! Returns project file path if layer is embedded from other project file. Returns empty string if layer is not embedded QString layerIsEmbedded( const QString& id ) const; /** Creates a maplayer instance defined in an arbitrary project file. Caller takes ownership @@ -338,10 +338,10 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera */ QgsLayerTreeGroup* createEmbeddedGroup( const QString& groupName, const QString& projectFilePath, const QStringList &invisibleLayers ); - /** Convenience function to set topological editing */ + //! Convenience function to set topological editing void setTopologicalEditing( bool enabled ); - /** Convenience function to query topological editing status */ + //! Convenience function to query topological editing status bool topologicalEditing() const; /** Convenience function to query default distance measurement units for project. diff --git a/src/core/qgsprojectproperty.h b/src/core/qgsprojectproperty.h index 507fb324f3a9..49bf0bc519c1 100644 --- a/src/core/qgsprojectproperty.h +++ b/src/core/qgsprojectproperty.h @@ -56,10 +56,10 @@ class CORE_EXPORT QgsProperty */ virtual void dump( int tabs = 0 ) const = 0; - /** Returns true if is a QgsPropertyKey */ + //! Returns true if is a QgsPropertyKey virtual bool isKey() const = 0; - /** Returns true if is a QgsPropertyValue */ + //! Returns true if is a QgsPropertyValue virtual bool isValue() const = 0; /** Returns true if a leaf node @@ -123,10 +123,10 @@ class CORE_EXPORT QgsPropertyValue : public QgsProperty virtual ~QgsPropertyValue(); - /** Returns true if is a QgsPropertyKey */ + //! Returns true if is a QgsPropertyKey virtual bool isKey() const override { return false; } - /** Returns true if is a QgsPropertyValue */ + //! Returns true if is a QgsPropertyValue virtual bool isValue() const override { return true; } QVariant value() const override { return value_; } @@ -261,10 +261,10 @@ class CORE_EXPORT QgsPropertyKey : public QgsProperty /// Does this property not have any subkeys or values? /* virtual */ bool isEmpty() const { return mProperties.isEmpty(); } - /** Returns true if is a QgsPropertyKey */ + //! Returns true if is a QgsPropertyKey virtual bool isKey() const override { return true; } - /** Returns true if is a QgsPropertyValue */ + //! Returns true if is a QgsPropertyValue virtual bool isValue() const override { return false; } /// return keys that do not contain other keys diff --git a/src/core/qgsproviderregistry.h b/src/core/qgsproviderregistry.h index 9b9c85edd9e9..8fa00d016f1c 100644 --- a/src/core/qgsproviderregistry.h +++ b/src/core/qgsproviderregistry.h @@ -47,22 +47,22 @@ class CORE_EXPORT QgsProviderRegistry public: - /** Means of accessing canonical single instance */ + //! Means of accessing canonical single instance static QgsProviderRegistry* instance( const QString& pluginPath = QString::null ); - /** Virtual dectructor */ + //! Virtual dectructor virtual ~QgsProviderRegistry(); - /** Return path for the library of the provider */ + //! Return path for the library of the provider QString library( const QString & providerKey ) const; - /** Return list of provider plugins found */ + //! Return list of provider plugins found QString pluginList( bool asHtml = false ) const; - /** Return library directory where plugins are found */ + //! Return library directory where plugins are found const QDir & libraryDirectory() const; - /** Set library directory where to search for plugins */ + //! Set library directory where to search for plugins void setLibraryDirectory( const QDir & path ); /** Create an instance of the provider @@ -94,10 +94,10 @@ class CORE_EXPORT QgsProviderRegistry QLibrary *providerLibrary( const QString & providerKey ) const; - /** Return list of available providers by their keys */ + //! Return list of available providers by their keys QStringList providerList() const; - /** Return metadata of the provider or NULL if not found */ + //! Return metadata of the provider or NULL if not found const QgsProviderMetadata* providerMetadata( const QString& providerKey ) const; /** Return vector file filter string @@ -124,11 +124,11 @@ class CORE_EXPORT QgsProviderRegistry @note This replaces QgsRasterLayer::buildSupportedRasterFileFilter() */ virtual QString fileRasterFilters() const; - /** Return a string containing the available database drivers */ + //! Return a string containing the available database drivers virtual QString databaseDrivers() const; - /** Return a string containing the available directory drivers */ + //! Return a string containing the available directory drivers virtual QString directoryDrivers() const; - /** Return a string containing the available protocol drivers */ + //! Return a string containing the available protocol drivers virtual QString protocolDrivers() const; void registerGuis( QWidget *widget ); @@ -157,20 +157,20 @@ class CORE_EXPORT QgsProviderRegistry //QgsDataProvider * openVector( QString const & dataSource, QString const & providerKey ); - /** Type for data provider metadata associative container */ + //! Type for data provider metadata associative container typedef std::map Providers; private: - /** Ctor private since instance() creates it */ + //! Ctor private since instance() creates it QgsProviderRegistry( const QString& pluginPath ); void init(); void clean(); - /** Associative container of provider metadata handles */ + //! Associative container of provider metadata handles Providers mProviders; - /** Directory in which provider plugins are installed */ + //! Directory in which provider plugins are installed QDir mLibraryDirectory; /** File filter string for vector files diff --git a/src/core/qgspythonrunner.h b/src/core/qgspythonrunner.h index c0791c1b0b24..07fc0edd79fa 100644 --- a/src/core/qgspythonrunner.h +++ b/src/core/qgspythonrunner.h @@ -34,10 +34,10 @@ class CORE_EXPORT QgsPythonRunner (and thus is able to run commands) */ static bool isValid(); - /** Execute a python statement */ + //! Execute a python statement static bool run( const QString& command, const QString& messageOnError = QString() ); - /** Eval a python statement */ + //! Eval a python statement static bool eval( const QString& command, QString& result ); /** Assign an instance of python runner so that run() can be used. @@ -46,7 +46,7 @@ class CORE_EXPORT QgsPythonRunner static void setInstance( QgsPythonRunner* runner ); protected: - /** Protected constructor: can be instantiated only from children */ + //! Protected constructor: can be instantiated only from children QgsPythonRunner(); virtual ~QgsPythonRunner(); diff --git a/src/core/qgsrectangle.h b/src/core/qgsrectangle.h index 2e8595477ec8..34878189f3a9 100644 --- a/src/core/qgsrectangle.h +++ b/src/core/qgsrectangle.h @@ -83,7 +83,7 @@ class CORE_EXPORT QgsRectangle void scale( double scaleFactor, double centerX, double centerY ); //! Grow the rectangle by the specified amount void grow( double delta ); - /** Updates the rectangle to include the specified point */ + //! Updates the rectangle to include the specified point void include( const QgsPoint& p ); /** Get rectangle enlarged by buffer. * @note added in 2.1 */ @@ -132,7 +132,7 @@ class CORE_EXPORT QgsRectangle */ QgsRectangle & operator=( const QgsRectangle &r1 ); - /** Updates rectangle to include passed argument */ + //! Updates rectangle to include passed argument void unionRect( const QgsRectangle& rect ); /** Returns true if the rectangle has finite boundaries. Will @@ -155,9 +155,9 @@ class CORE_EXPORT QgsRectangle }; -/** Writes the list rectangle to stream out. QGIS version compatibility is not guaranteed. */ +//! Writes the list rectangle to stream out. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator<<( QDataStream& out, const QgsRectangle& rectangle ); -/** Reads a rectangle from stream in into rectangle. QGIS version compatibility is not guaranteed. */ +//! Reads a rectangle from stream in into rectangle. QGIS version compatibility is not guaranteed. CORE_EXPORT QDataStream& operator>>( QDataStream& in, QgsRectangle& rectangle ); inline QgsRectangle::~QgsRectangle() diff --git a/src/core/qgsrelation.h b/src/core/qgsrelation.h index 3cc48dcfe204..ca79a034b72c 100644 --- a/src/core/qgsrelation.h +++ b/src/core/qgsrelation.h @@ -297,17 +297,17 @@ class CORE_EXPORT QgsRelation void updateRelationStatus(); private: - /** Unique Id */ + //! Unique Id QString mRelationId; - /** Human redable name*/ + //! Human redable name QString mRelationName; - /** The child layer */ + //! The child layer QString mReferencingLayerId; - /** The child layer */ + //! The child layer QgsVectorLayer* mReferencingLayer; - /** The parent layer id */ + //! The parent layer id QString mReferencedLayerId; - /** The parent layer */ + //! The parent layer QgsVectorLayer* mReferencedLayer; /** A list of fields which define the relation. * In most cases there will be only one value, but multiple values diff --git a/src/core/qgsrelationmanager.h b/src/core/qgsrelationmanager.h index 30450c6686d3..1bbeb52f7277 100644 --- a/src/core/qgsrelationmanager.h +++ b/src/core/qgsrelationmanager.h @@ -128,7 +128,7 @@ class CORE_EXPORT QgsRelationManager : public QObject static QList discoverRelations( const QList& existingRelations, const QList& layers ); signals: - /** This signal is emitted when the relations were loaded after reading a project */ + //! This signal is emitted when the relations were loaded after reading a project void relationsLoaded(); /** @@ -143,7 +143,7 @@ class CORE_EXPORT QgsRelationManager : public QObject void layersRemoved( const QStringList& layers ); private: - /** The references */ + //! The references QMap mRelations; QgsProject* mProject; diff --git a/src/core/qgsrenderchecker.h b/src/core/qgsrenderchecker.h index aff922ad90b3..1ba6fa289803 100644 --- a/src/core/qgsrenderchecker.h +++ b/src/core/qgsrenderchecker.h @@ -70,7 +70,7 @@ class CORE_EXPORT QgsRenderChecker void setControlPathSuffix( const QString& theName ); - /** Get an md5 hash that uniquely identifies an image */ + //! Get an md5 hash that uniquely identifies an image QString imageToHash( const QString& theImageFile ); void setRenderedImage( const QString& theImageFileName ) { mRenderedImageFile = theImageFileName; } diff --git a/src/core/qgsrendercontext.h b/src/core/qgsrendercontext.h index 5c24c994a69a..a372d7143e46 100644 --- a/src/core/qgsrendercontext.h +++ b/src/core/qgsrendercontext.h @@ -145,7 +145,7 @@ class CORE_EXPORT QgsRenderContext //setters - /** Sets coordinate transformation.*/ + //! Sets coordinate transformation. void setCoordinateTransform( const QgsCoordinateTransform& t ); void setMapToPixel( const QgsMapToPixel& mtp ) {mMapToPixel = mtp;} void setExtent( const QgsRectangle& extent ) {mExtent = extent;} @@ -206,9 +206,9 @@ class CORE_EXPORT QgsRenderContext */ const QgsExpressionContext& expressionContext() const { return mExpressionContext; } - /** Returns pointer to the unsegmentized geometry*/ + //! Returns pointer to the unsegmentized geometry const QgsAbstractGeometry* geometry() const { return mGeometry; } - /** Sets pointer to original (unsegmentized) geometry*/ + //! Sets pointer to original (unsegmentized) geometry void setGeometry( const QgsAbstractGeometry* geometry ) { mGeometry = geometry; } /** Set a filter feature provider used for additional filtering of rendered features. @@ -228,60 +228,60 @@ class CORE_EXPORT QgsRenderContext /** Sets the segmentation tolerance applied when rendering curved geometries @param tolerance the segmentation tolerance*/ void setSegmentationTolerance( double tolerance ) { mSegmentationTolerance = tolerance; } - /** Gets the segmentation tolerance applied when rendering curved geometries*/ + //! Gets the segmentation tolerance applied when rendering curved geometries double segmentationTolerance() const { return mSegmentationTolerance; } /** Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation) @param type the segmentation tolerance typename*/ void setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType type ) { mSegmentationToleranceType = type; } - /** Gets segmentation tolerance type (maximum angle or maximum difference between curve and approximation)*/ + //! Gets segmentation tolerance type (maximum angle or maximum difference between curve and approximation) QgsAbstractGeometry::SegmentationToleranceType segmentationToleranceType() const { return mSegmentationToleranceType; } private: Flags mFlags; - /** Painter for rendering operations*/ + //! Painter for rendering operations QPainter* mPainter; - /** For transformation between coordinate systems. Can be invalid if on-the-fly reprojection is not used*/ + //! For transformation between coordinate systems. Can be invalid if on-the-fly reprojection is not used QgsCoordinateTransform mCoordTransform; QgsRectangle mExtent; QgsMapToPixel mMapToPixel; - /** True if the rendering has been canceled*/ + //! True if the rendering has been canceled bool mRenderingStopped; - /** Factor to scale line widths and point marker sizes*/ + //! Factor to scale line widths and point marker sizes double mScaleFactor; - /** Factor to scale rasters*/ + //! Factor to scale rasters double mRasterScaleFactor; - /** Map scale*/ + //! Map scale double mRendererScale; - /** Labeling engine (can be nullptr)*/ + //! Labeling engine (can be nullptr) QgsLabelingEngineInterface* mLabelingEngine; - /** Newer labeling engine implementation (can be nullptr) */ + //! Newer labeling engine implementation (can be nullptr) QgsLabelingEngine* mLabelingEngine2; - /** Color used for features that are marked as selected */ + //! Color used for features that are marked as selected QColor mSelectionColor; - /** Simplification object which holds the information about how to simplify the features for fast rendering */ + //! Simplification object which holds the information about how to simplify the features for fast rendering QgsVectorSimplifyMethod mVectorSimplifyMethod; - /** Expression context */ + //! Expression context QgsExpressionContext mExpressionContext; - /** Pointer to the (unsegmentized) geometry*/ + //! Pointer to the (unsegmentized) geometry const QgsAbstractGeometry* mGeometry; - /** The feature filter provider */ + //! The feature filter provider const QgsFeatureFilterProvider* mFeatureFilterProvider; double mSegmentationTolerance; diff --git a/src/core/qgsscalecalculator.h b/src/core/qgsscalecalculator.h index fd9ecb5aad8a..615b841b5b4b 100644 --- a/src/core/qgsscalecalculator.h +++ b/src/core/qgsscalecalculator.h @@ -59,7 +59,7 @@ class CORE_EXPORT QgsScaleCalculator */ void setMapUnits( QgsUnitTypes::DistanceUnit mapUnits ); - /** Returns current map units */ + //! Returns current map units QgsUnitTypes::DistanceUnit mapUnits() const; /** diff --git a/src/core/qgssnapper.h b/src/core/qgssnapper.h index 5af3a4913d64..a9927c1777cb 100644 --- a/src/core/qgssnapper.h +++ b/src/core/qgssnapper.h @@ -35,24 +35,24 @@ class QPoint; // ### QGIS 3: remove from API struct CORE_EXPORT QgsSnappingResult { - /** The coordinates of the snapping result*/ + //! The coordinates of the snapping result QgsPoint snappedVertex; /** The vertex index of snappedVertex or -1 if no such vertex number (e.g. snap to segment)*/ int snappedVertexNr; - /** The layer coordinates of the vertex before snappedVertex*/ + //! The layer coordinates of the vertex before snappedVertex QgsPoint beforeVertex; /** The index of the vertex before snappedVertex or -1 if no such vertex*/ int beforeVertexNr; - /** The layer coordinates of the vertex after snappedVertex*/ + //! The layer coordinates of the vertex after snappedVertex QgsPoint afterVertex; /** The index of the vertex after snappedVertex or -1 if no such vertex*/ int afterVertexNr; - /** Index of the snapped geometry*/ + //! Index of the snapped geometry QgsFeatureId snappedAtGeometry; - /** Layer where the snap occurred*/ + //! Layer where the snap occurred const QgsVectorLayer* layer; }; @@ -64,7 +64,7 @@ struct CORE_EXPORT QgsSnappingResult class CORE_EXPORT QgsSnapper { public: - /** Snap to vertex, to segment or both*/ + //! Snap to vertex, to segment or both enum SnappingType { SnapToVertex, @@ -75,24 +75,24 @@ class CORE_EXPORT QgsSnapper enum SnappingMode { - /** Only one snapping result is returned*/ + //! Only one snapping result is returned SnapWithOneResult, /** Several snapping results which have the same position are returned. This is useful for topological editing*/ SnapWithResultsForSamePosition, - /** All results within the given layer tolerances are returned*/ + //! All results within the given layer tolerances are returned SnapWithResultsWithinTolerances }; struct SnapLayer { - /** The layer to which snapping is applied*/ + //! The layer to which snapping is applied QgsVectorLayer* mLayer; - /** The snapping tolerances for the layers, always in source coordinate systems of the layer*/ + //! The snapping tolerances for the layers, always in source coordinate systems of the layer double mTolerance; - /** What snapping type to use (snap to segment or to vertex)*/ + //! What snapping type to use (snap to segment or to vertex) QgsSnapper::SnappingType mSnapTo; - /** What unit is used for tolerance*/ + //! What unit is used for tolerance QgsTolerance::UnitType mUnitType; }; @@ -112,16 +112,16 @@ class CORE_EXPORT QgsSnapper private: - /** Removes the snapping results that contains points in exclude list*/ + //! Removes the snapping results that contains points in exclude list void cleanResultList( QMultiMap& list, const QList& excludeList ) const; /** The map settings object contains information about the output coordinate system * of the map and about the relationship between pixel space and map space */ const QgsMapSettings& mMapSettings; - /** Snap mode to apply*/ + //! Snap mode to apply QgsSnapper::SnappingMode mSnapMode; - /** List of layers to which snapping is applied*/ + //! List of layers to which snapping is applied QList mSnapLayers; }; diff --git a/src/core/qgssnappingconfig.h b/src/core/qgssnappingconfig.h index 1143ebfcdae4..2d0bf12fe41e 100644 --- a/src/core/qgssnappingconfig.h +++ b/src/core/qgssnappingconfig.h @@ -34,9 +34,9 @@ class CORE_EXPORT QgsSnappingConfig */ enum SnappingMode { - ActiveLayer = 1, /*!< on the active layer */ - AllLayers = 2, /*!< on all vector layers */ - AdvancedConfiguration = 3, /*!< on a per layer configuration basis */ + ActiveLayer = 1, //!< On the active layer + AllLayers = 2, //!< On all vector layers + AdvancedConfiguration = 3, //!< On a per layer configuration basis }; /** @@ -44,9 +44,9 @@ class CORE_EXPORT QgsSnappingConfig */ enum SnappingType { - Vertex = 1, /*!< on vertices only */ - VertexAndSegment = 2, /*!< both on vertices and segments */ - Segment = 3, /*!< on segments only */ + Vertex = 1, //!< On vertices only + VertexAndSegment = 2, //!< Both on vertices and segments + Segment = 3, //!< On segments only }; /** \ingroup core diff --git a/src/core/qgssnappingutils.h b/src/core/qgssnappingutils.h index 72d53a3e8ab1..bc11c9248c93 100644 --- a/src/core/qgssnappingutils.h +++ b/src/core/qgssnappingutils.h @@ -53,25 +53,25 @@ class CORE_EXPORT QgsSnappingUtils : public QObject // main actions - /** Get a point locator for the given layer. If such locator does not exist, it will be created */ + //! Get a point locator for the given layer. If such locator does not exist, it will be created QgsPointLocator* locatorForLayer( QgsVectorLayer* vl ); - /** Snap to map according to the current configuration (mode). Optional filter allows discarding unwanted matches. */ + //! Snap to map according to the current configuration (mode). Optional filter allows discarding unwanted matches. QgsPointLocator::Match snapToMap( QPoint point, QgsPointLocator::MatchFilter* filter = nullptr ); QgsPointLocator::Match snapToMap( const QgsPoint& pointMap, QgsPointLocator::MatchFilter* filter = nullptr ); - /** Snap to current layer */ + //! Snap to current layer QgsPointLocator::Match snapToCurrentLayer( QPoint point, int type, QgsPointLocator::MatchFilter* filter = nullptr ); // environment setup - /** Assign current map settings to the utils - used for conversion between screen coords to map coords */ + //! Assign current map settings to the utils - used for conversion between screen coords to map coords void setMapSettings( const QgsMapSettings& settings ); QgsMapSettings mapSettings() const { return mMapSettings; } - /** Set current layer so that if mode is SnapCurrentLayer we know which layer to use */ + //! Set current layer so that if mode is SnapCurrentLayer we know which layer to use void setCurrentLayer( QgsVectorLayer* layer ); - /** The current layer used if mode is SnapCurrentLayer */ + //! The current layer used if mode is SnapCurrentLayer QgsVectorLayer* currentLayer() const { return mCurrentLayer; } @@ -80,9 +80,9 @@ class CORE_EXPORT QgsSnappingUtils : public QObject //! modes for "snap to background" enum SnapToMapMode { - SnapCurrentLayer, //!< snap just to current layer (tolerance and type from defaultSettings()) - SnapAllLayers, //!< snap to all rendered layers (tolerance and type from defaultSettings()) - SnapAdvanced, //!< snap according to the configuration set in setLayers() + SnapCurrentLayer, //!< Snap just to current layer (tolerance and type from defaultSettings()) + SnapAllLayers, //!< Snap to all rendered layers (tolerance and type from defaultSettings()) + SnapAdvanced, //!< Snap according to the configuration set in setLayers() }; enum IndexingStrategy @@ -92,9 +92,9 @@ class CORE_EXPORT QgsSnappingUtils : public QObject IndexHybrid //!< For "big" layers using IndexNeverFull, for the rest IndexAlwaysFull. Compromise between speed and memory usage. }; - /** Set a strategy for indexing geometry data - determines how fast and memory consuming the data structures will be */ + //! Set a strategy for indexing geometry data - determines how fast and memory consuming the data structures will be void setIndexingStrategy( IndexingStrategy strategy ) { mStrategy = strategy; } - /** Find out which strategy is used for indexing - by default hybrid indexing is used */ + //! Find out which strategy is used for indexing - by default hybrid indexing is used IndexingStrategy indexingStrategy() const { return mStrategy; } /** @@ -146,7 +146,7 @@ class CORE_EXPORT QgsSnappingUtils : public QObject QgsTolerance::UnitType unit; }; - /** Query layers used for snapping */ + //! Query layers used for snapping QList layers() const { return mLayers; } /** Get extra information about the instance diff --git a/src/core/qgsspatialindex.cpp b/src/core/qgsspatialindex.cpp index e5e0a3785292..7f7ccbf8f498 100644 --- a/src/core/qgsspatialindex.cpp +++ b/src/core/qgsspatialindex.cpp @@ -204,10 +204,10 @@ class QgsSpatialIndexData : public QSharedData leafCapacity, dimension, variant, indexId ); } - /** Storage manager */ + //! Storage manager SpatialIndex::IStorageManager* mStorage; - /** R-tree containing spatial index */ + //! R-tree containing spatial index SpatialIndex::ISpatialIndex* mRTree; private: diff --git a/src/core/qgsspatialindex.h b/src/core/qgsspatialindex.h index 8c6da6debb91..8a9ba9ff8abb 100644 --- a/src/core/qgsspatialindex.h +++ b/src/core/qgsspatialindex.h @@ -52,7 +52,7 @@ class CORE_EXPORT QgsSpatialIndex /* creation of spatial index */ - /** Constructor - creates R-tree */ + //! Constructor - creates R-tree QgsSpatialIndex(); /** Constructor - creates R-tree and bulk loads it with features from the iterator. @@ -62,30 +62,30 @@ class CORE_EXPORT QgsSpatialIndex */ explicit QgsSpatialIndex( const QgsFeatureIterator& fi ); - /** Copy constructor */ + //! Copy constructor QgsSpatialIndex( const QgsSpatialIndex& other ); - /** Destructor finalizes work with spatial index */ + //! Destructor finalizes work with spatial index ~QgsSpatialIndex(); - /** Implement assignment operator */ + //! Implement assignment operator QgsSpatialIndex& operator=( const QgsSpatialIndex& other ); /* operations */ - /** Add feature to index */ + //! Add feature to index bool insertFeature( const QgsFeature& f ); - /** Remove feature from index */ + //! Remove feature from index bool deleteFeature( const QgsFeature& f ); /* queries */ - /** Returns features that intersect the specified rectangle */ + //! Returns features that intersect the specified rectangle QList intersects( const QgsRectangle& rect ) const; - /** Returns nearest neighbors (their count is specified by second parameter) */ + //! Returns nearest neighbors (their count is specified by second parameter) QList nearestNeighbor( const QgsPoint& point, int neighbors ) const; /* debugging */ diff --git a/src/core/qgssqlexpressioncompiler.h b/src/core/qgssqlexpressioncompiler.h index 5a083626816e..ccf683d387c7 100644 --- a/src/core/qgssqlexpressioncompiler.h +++ b/src/core/qgssqlexpressioncompiler.h @@ -34,13 +34,13 @@ class CORE_EXPORT QgsSqlExpressionCompiler { public: - /** Possible results from expression compilation */ + //! Possible results from expression compilation enum Result { - None, /*!< No expression */ - Complete, /*!< Expression was successfully compiled and can be completely delegated to provider */ - Partial, /*!< Expression was partially compiled, but provider will return extra records and results must be double-checked using QGIS' expression engine*/ - Fail /*!< Provider cannot handle expression */ + None, //!< No expression + Complete, //!< Expression was successfully compiled and can be completely delegated to provider + Partial, //!< Expression was partially compiled, but provider will return extra records and results must be double-checked using QGIS' expression engine + Fail //!< Provider cannot handle expression }; /** Enumeration of flags for how provider handles SQL clauses diff --git a/src/core/qgssqlstatement.h b/src/core/qgssqlstatement.h index 0fdbc5532f0c..def8f3973f12 100644 --- a/src/core/qgssqlstatement.h +++ b/src/core/qgssqlstatement.h @@ -171,7 +171,7 @@ class CORE_EXPORT QgsSQLStatement class Visitor; // visitor interface is defined below - /** Node type */ + //! Node type enum NodeType { ntUnaryOperator, @@ -243,27 +243,27 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeList { public: - /** Constructor */ + //! Constructor NodeList() {} virtual ~NodeList() { qDeleteAll( mList ); } - /** Takes ownership of the provided node */ + //! Takes ownership of the provided node void append( Node* node ) { mList.append( node ); } - /** Return list */ + //! Return list QList list() { return mList; } /** Returns the number of nodes in the list. */ int count() const { return mList.count(); } - /** Accept visitor */ + //! Accept visitor void accept( Visitor& v ) const { Q_FOREACH ( Node* node, mList ) { node->accept( v ); } } - /** Creates a deep copy of this list. Ownership is transferred to the caller */ + //! Creates a deep copy of this list. Ownership is transferred to the caller NodeList* clone() const; - /** Dump list */ + //! Dump list virtual QString dump() const; protected: @@ -275,14 +275,14 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeUnaryOperator : public Node { public: - /** Constructor */ + //! Constructor NodeUnaryOperator( UnaryOperator op, Node* operand ) : mOp( op ), mOperand( operand ) {} ~NodeUnaryOperator() { delete mOperand; } - /** Operator */ + //! Operator UnaryOperator op() const { return mOp; } - /** Operand */ + //! Operand Node* operand() const { return mOperand; } virtual NodeType nodeType() const override { return ntUnaryOperator; } @@ -301,17 +301,17 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeBinaryOperator : public Node { public: - /** Constructor */ + //! Constructor NodeBinaryOperator( BinaryOperator op, Node* opLeft, Node* opRight ) : mOp( op ), mOpLeft( opLeft ), mOpRight( opRight ) {} ~NodeBinaryOperator() { delete mOpLeft; delete mOpRight; } - /** Operator */ + //! Operator BinaryOperator op() const { return mOp; } - /** Left operand */ + //! Left operand Node* opLeft() const { return mOpLeft; } - /** Right operand */ + //! Right operand Node* opRight() const { return mOpRight; } virtual NodeType nodeType() const override { return ntBinaryOperator; } @@ -320,10 +320,10 @@ class CORE_EXPORT QgsSQLStatement virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; - /** Precedence */ + //! Precedence int precedence() const; - /** Is left associative ? */ + //! Is left associative ? bool leftAssociative() const; protected: @@ -338,17 +338,17 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeInOperator : public Node { public: - /** Constructor */ + //! Constructor NodeInOperator( Node* node, NodeList* list, bool notin = false ) : mNode( node ), mList( list ), mNotIn( notin ) {} virtual ~NodeInOperator() { delete mNode; delete mList; } - /** Variable at the left of IN */ + //! Variable at the left of IN Node* node() const { return mNode; } - /** Whether this is a NOT IN operator */ + //! Whether this is a NOT IN operator bool isNotIn() const { return mNotIn; } - /** Values list */ + //! Values list NodeList* list() const { return mList; } virtual NodeType nodeType() const override { return ntInOperator; } @@ -368,20 +368,20 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeBetweenOperator : public Node { public: - /** Constructor */ + //! Constructor NodeBetweenOperator( Node* node, Node* minVal, Node* maxVal, bool notBetween = false ) : mNode( node ), mMinVal( minVal ), mMaxVal( maxVal ), mNotBetween( notBetween ) {} virtual ~NodeBetweenOperator() { delete mNode; delete mMinVal; delete mMaxVal; } - /** Variable at the left of BETWEEN */ + //! Variable at the left of BETWEEN Node* node() const { return mNode; } - /** Whether this is a NOT BETWEEN operator */ + //! Whether this is a NOT BETWEEN operator bool isNotBetween() const { return mNotBetween; } - /** Minimum bound */ + //! Minimum bound Node* minVal() const { return mMinVal; } - /** Maximum bound */ + //! Maximum bound Node* maxVal() const { return mMaxVal; } virtual NodeType nodeType() const override { return ntBetweenOperator; } @@ -402,14 +402,14 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeFunction : public Node { public: - /** Constructor */ + //! Constructor NodeFunction( const QString& name, NodeList* args ) : mName( name ), mArgs( args ) {} virtual ~NodeFunction() { delete mArgs; } - /** Return function name */ + //! Return function name QString name() const { return mName; } - /** Return arguments */ + //! Return arguments NodeList* args() const { return mArgs; } virtual NodeType nodeType() const override { return ntFunction; } @@ -429,10 +429,10 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeLiteral : public Node { public: - /** Constructor */ + //! Constructor NodeLiteral( const QVariant& value ) : mValue( value ) {} - /** The value of the literal. */ + //! The value of the literal. inline QVariant value() const { return mValue; } virtual NodeType nodeType() const override { return ntLiteral; } @@ -450,24 +450,24 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeColumnRef : public Node { public: - /** Constructor with colum name only */ + //! Constructor with colum name only NodeColumnRef( const QString& name, bool star ) : mName( name ), mDistinct( false ), mStar( star ) {} - /** Constructor with table and column name */ + //! Constructor with table and column name NodeColumnRef( const QString& tableName, const QString& name, bool star ) : mTableName( tableName ), mName( name ), mDistinct( false ), mStar( star ) {} - /** Set whether this is prefixed by DISTINCT */ + //! Set whether this is prefixed by DISTINCT void setDistinct( bool distinct = true ) { mDistinct = distinct; } - /** The name of the table. May be empty. */ + //! The name of the table. May be empty. QString tableName() const { return mTableName; } - /** The name of the column. */ + //! The name of the column. QString name() const { return mName; } - /** Whether this is the * column */ + //! Whether this is the * column bool star() const { return mStar; } - /** Whether this is prefixed by DISTINCT */ + //! Whether this is prefixed by DISTINCT bool distinct() const { return mDistinct; } virtual NodeType nodeType() const override { return ntColumnRef; } @@ -475,7 +475,7 @@ class CORE_EXPORT QgsSQLStatement virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; - /** Clone with same type return */ + //! Clone with same type return NodeColumnRef* cloneThis() const; protected: @@ -490,17 +490,17 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeSelectedColumn : public Node { public: - /** Constructor */ + //! Constructor NodeSelectedColumn( Node* node ) : mColumnNode( node ) {} virtual ~NodeSelectedColumn() { delete mColumnNode; } - /** Set alias name */ + //! Set alias name void setAlias( const QString& alias ) { mAlias = alias; } - /** Column that is refered to */ + //! Column that is refered to Node* column() const { return mColumnNode; } - /** Alias name */ + //! Alias name QString alias() const { return mAlias; } virtual NodeType nodeType() const override { return ntSelectedColumn; } @@ -508,7 +508,7 @@ class CORE_EXPORT QgsSQLStatement virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; - /** Clone with same type return */ + //! Clone with same type return NodeSelectedColumn* cloneThis() const; protected: @@ -521,14 +521,14 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeCast : public Node { public: - /** Constructor */ + //! Constructor NodeCast( Node* node, const QString& type ) : mNode( node ), mType( type ) {} virtual ~NodeCast() { delete mNode; } - /** Node that is refered to */ + //! Node that is refered to Node* node() const { return mNode; } - /** Type */ + //! Type QString type() const { return mType; } virtual NodeType nodeType() const override { return ntCast; } @@ -547,15 +547,15 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeTableDef : public Node { public: - /** Constructor with table name */ + //! Constructor with table name NodeTableDef( const QString& name ) : mName( name ) {} - /** Constructor with table name and alias */ + //! Constructor with table name and alias NodeTableDef( const QString& name, const QString& alias ) : mName( name ), mAlias( alias ) {} - /** Table name */ + //! Table name QString name() const { return mName; } - /** Table alias */ + //! Table alias QString alias() const { return mAlias; } virtual NodeType nodeType() const override { return ntTableDef; } @@ -563,7 +563,7 @@ class CORE_EXPORT QgsSQLStatement virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; - /** Clone with same type return */ + //! Clone with same type return NodeTableDef* cloneThis() const; protected: @@ -576,22 +576,22 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeJoin : public Node { public: - /** Constructor with table definition, ON expression */ + //! Constructor with table definition, ON expression NodeJoin( NodeTableDef* tabledef, Node* onExpr, JoinType type ) : mTableDef( tabledef ), mOnExpr( onExpr ), mType( type ) {} - /** Constructor with table definition and USING columns */ + //! Constructor with table definition and USING columns NodeJoin( NodeTableDef* tabledef, const QList& usingColumns, JoinType type ) : mTableDef( tabledef ), mOnExpr( nullptr ), mUsingColumns( usingColumns ), mType( type ) {} virtual ~NodeJoin() { delete mTableDef; delete mOnExpr; } - /** Table definition */ + //! Table definition NodeTableDef* tableDef() const { return mTableDef; } - /** On expression. Will be nullptr if usingColumns() is not empty */ + //! On expression. Will be nullptr if usingColumns() is not empty Node* onExpr() const { return mOnExpr; } - /** Columns referenced by USING */ + //! Columns referenced by USING QList usingColumns() const { return mUsingColumns; } - /** Join type */ + //! Join type JoinType type() const { return mType; } virtual NodeType nodeType() const override { return ntJoin; } @@ -599,7 +599,7 @@ class CORE_EXPORT QgsSQLStatement virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; - /** Clone with same type return */ + //! Clone with same type return NodeJoin* cloneThis() const; protected: @@ -614,14 +614,14 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeColumnSorted : public Node { public: - /** Constructor */ + //! Constructor NodeColumnSorted( NodeColumnRef* column, bool asc ) : mColumn( column ), mAsc( asc ) {} ~NodeColumnSorted() { delete mColumn; } - /** The name of the column. */ + //! The name of the column. NodeColumnRef* column() const { return mColumn; } - /** Whether the column is sorted in ascending order */ + //! Whether the column is sorted in ascending order bool ascending() const { return mAsc; } virtual NodeType nodeType() const override { return ntColumnSorted; } @@ -629,7 +629,7 @@ class CORE_EXPORT QgsSQLStatement virtual void accept( Visitor& v ) const override { v.visit( *this ); } virtual Node* clone() const override; - /** Clone with same type return */ + //! Clone with same type return NodeColumnSorted* cloneThis() const; protected: @@ -642,30 +642,30 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT NodeSelect : public Node { public: - /** Constructor */ + //! Constructor NodeSelect( const QList& tableList, const QList& columns, bool distinct ) : mTableList( tableList ), mColumns( columns ), mDistinct( distinct ), mWhere( nullptr ) {} virtual ~NodeSelect() { qDeleteAll( mTableList ); qDeleteAll( mColumns ); qDeleteAll( mJoins ); delete mWhere; qDeleteAll( mOrderBy ); } - /** Set joins */ + //! Set joins void setJoins( const QList& joins ) { qDeleteAll( mJoins ); mJoins = joins; } - /** Append a join */ + //! Append a join void appendJoin( NodeJoin* join ) { mJoins.append( join ); } - /** Set where clause */ + //! Set where clause void setWhere( Node* where ) { delete mWhere; mWhere = where; } - /** Set order by columns */ + //! Set order by columns void setOrderBy( const QList& orderBy ) { qDeleteAll( mOrderBy ); mOrderBy = orderBy; } - /** Return the list of tables */ + //! Return the list of tables QList tables() const { return mTableList; } - /** Return the list of columns */ + //! Return the list of columns QList columns() const { return mColumns; } - /** Return if the SELECT is DISTINCT */ + //! Return if the SELECT is DISTINCT bool distinct() const { return mDistinct; } - /** Return the list of joins */ + //! Return the list of joins QList joins() const { return mJoins; } - /** Return the where clause */ + //! Return the where clause Node* where() const { return mWhere; } - /** Return the list of order by columns */ + //! Return the list of order by columns QList orderBy() const { return mOrderBy; } virtual NodeType nodeType() const override { return ntSelect; } @@ -692,31 +692,31 @@ class CORE_EXPORT QgsSQLStatement { public: virtual ~Visitor() {} - /** Visit NodeUnaryOperator */ + //! Visit NodeUnaryOperator virtual void visit( const NodeUnaryOperator& n ) = 0; - /** Visit NodeBinaryOperator */ + //! Visit NodeBinaryOperator virtual void visit( const NodeBinaryOperator& n ) = 0; - /** Visit NodeInOperator */ + //! Visit NodeInOperator virtual void visit( const NodeInOperator& n ) = 0; - /** Visit NodeBetweenOperator */ + //! Visit NodeBetweenOperator virtual void visit( const NodeBetweenOperator& n ) = 0; - /** Visit NodeFunction */ + //! Visit NodeFunction virtual void visit( const NodeFunction& n ) = 0; - /** Visit NodeLiteral */ + //! Visit NodeLiteral virtual void visit( const NodeLiteral& n ) = 0; - /** Visit NodeColumnRef */ + //! Visit NodeColumnRef virtual void visit( const NodeColumnRef& n ) = 0; - /** Visit NodeSelectedColumn */ + //! Visit NodeSelectedColumn virtual void visit( const NodeSelectedColumn& n ) = 0; - /** Visit NodeTableDef */ + //! Visit NodeTableDef virtual void visit( const NodeTableDef& n ) = 0; - /** Visit NodeSelect */ + //! Visit NodeSelect virtual void visit( const NodeSelect& n ) = 0; - /** Visit NodeJoin */ + //! Visit NodeJoin virtual void visit( const NodeJoin& n ) = 0; - /** Visit NodeColumnSorted */ + //! Visit NodeColumnSorted virtual void visit( const NodeColumnSorted& n ) = 0; - /** Visit NodeCast */ + //! Visit NodeCast virtual void visit( const NodeCast& n ) = 0; }; @@ -725,7 +725,7 @@ class CORE_EXPORT QgsSQLStatement class CORE_EXPORT RecursiveVisitor: public QgsSQLStatement::Visitor { public: - /** Constructor */ + //! Constructor RecursiveVisitor() {} void visit( const QgsSQLStatement::NodeUnaryOperator& n ) override { n.operand()->accept( *this ); } @@ -743,7 +743,7 @@ class CORE_EXPORT QgsSQLStatement void visit( const QgsSQLStatement::NodeCast& n ) override { n.node()->accept( *this ); } }; - /** Entry function for the visitor pattern */ + //! Entry function for the visitor pattern void acceptVisitor( Visitor& v ) const; protected: diff --git a/src/core/qgstextlabelfeature.h b/src/core/qgstextlabelfeature.h index 647d4376cb18..59db97bcf0f8 100644 --- a/src/core/qgstextlabelfeature.h +++ b/src/core/qgstextlabelfeature.h @@ -61,7 +61,7 @@ class QgsTextLabelFeature : public QgsLabelFeature QFont mDefinedFont; //! Metrics of the font for rendering QFontMetricsF* mFontMetrics; - /** Stores attribute values for data defined properties*/ + //! Stores attribute values for data defined properties QMap< QgsPalLayerSettings::DataDefinedProperties, QVariant > mDataDefinedValues; }; diff --git a/src/core/qgstextrenderer.h b/src/core/qgstextrenderer.h index d36b266f18af..9c3da97b6b9f 100644 --- a/src/core/qgstextrenderer.h +++ b/src/core/qgstextrenderer.h @@ -210,29 +210,29 @@ class CORE_EXPORT QgsTextBackgroundSettings */ enum ShapeType { - ShapeRectangle = 0, /*!< rectangle */ - ShapeSquare, /*!< square - buffered sizes only*/ - ShapeEllipse, /*!< ellipse */ - ShapeCircle, /*!< circle */ - ShapeSVG /*!< SVG file */ + ShapeRectangle = 0, //!< Rectangle + ShapeSquare, //!< Square - buffered sizes only + ShapeEllipse, //!< Ellipse + ShapeCircle, //!< Circle + ShapeSVG //!< SVG file }; /** Methods for determining the background shape size. */ enum SizeType { - SizeBuffer = 0, /*!< shape size is determined by adding a buffer margin around text */ - SizeFixed, /*!< fixed size */ - SizePercent /*!< shape size is determined by percent of text size */ + SizeBuffer = 0, //!< Shape size is determined by adding a buffer margin around text + SizeFixed, //!< Fixed size + SizePercent //!< Shape size is determined by percent of text size }; /** Methods for determining the rotation of the background shape. */ enum RotationType { - RotationSync = 0, /*!< shape rotation is synced with text rotation */ - RotationOffset, /*!< shape rotation is offset from text rotation */ - RotationFixed /*!< shape rotation is a fixed angle */ + RotationSync = 0, //!< Shape rotation is synced with text rotation + RotationOffset, //!< Shape rotation is offset from text rotation + RotationFixed //!< Shape rotation is a fixed angle }; QgsTextBackgroundSettings(); @@ -605,10 +605,10 @@ class CORE_EXPORT QgsTextShadowSettings */ enum ShadowPlacement { - ShadowLowest = 0, /*!< draw shadow below all text components */ - ShadowText, /*!< draw shadow under text */ - ShadowBuffer, /*!< draw shadow under buffer */ - ShadowShape /*!< draw shadow under background shape */ + ShadowLowest = 0, //!< Draw shadow below all text components + ShadowText, //!< Draw shadow under text + ShadowBuffer, //!< Draw shadow under buffer + ShadowShape //!< Draw shadow under background shape }; QgsTextShadowSettings(); diff --git a/src/core/qgstolerance.h b/src/core/qgstolerance.h index 48d1034717a1..5091f9c4ab39 100644 --- a/src/core/qgstolerance.h +++ b/src/core/qgstolerance.h @@ -33,11 +33,11 @@ class CORE_EXPORT QgsTolerance * For map (project) units, use ProjectUnits.*/ enum UnitType { - /** Layer unit value */ + //! Layer unit value LayerUnits, - /** Pixels unit of tolerance*/ + //! Pixels unit of tolerance Pixels, - /** Map (project) units. Added in 2.8 */ + //! Map (project) units. Added in 2.8 ProjectUnits }; diff --git a/src/core/qgstracer.cpp b/src/core/qgstracer.cpp index 92578e880508..624db76a8ed1 100644 --- a/src/core/qgstracer.cpp +++ b/src/core/qgstracer.cpp @@ -87,7 +87,7 @@ double closestSegment( const QgsPolyline& pl, const QgsPoint& pt, int& vertexAft ///// -/** Simple graph structure for shortest path search */ +//! Simple graph structure for shortest path search struct QgsTracerGraph { QgsTracerGraph() : joinedVertices( 0 ) {} diff --git a/src/core/qgstransaction.h b/src/core/qgstransaction.h index 570049f4733b..4d63908a606b 100644 --- a/src/core/qgstransaction.h +++ b/src/core/qgstransaction.h @@ -51,7 +51,7 @@ class CORE_EXPORT QgsTransaction : public QObject Q_OBJECT public: - /** Creates a transaction for the specified connection string and provider */ + //! Creates a transaction for the specified connection string and provider static QgsTransaction* create( const QString& connString, const QString& providerKey ); /** Creates a transaction which includes the specified layers. Connection string @@ -60,10 +60,10 @@ class CORE_EXPORT QgsTransaction : public QObject virtual ~QgsTransaction(); - /** Add layer to the transaction. The layer must not be in edit mode.*/ + //! Add layer to the transaction. The layer must not be in edit mode. bool addLayer( const QString& layerId ); - /** Add layer to the transaction. The layer must not be in edit mode.*/ + //! Add layer to the transaction. The layer must not be in edit mode. bool addLayer( QgsVectorLayer* layer ); /** Begin transaction @@ -76,13 +76,13 @@ class CORE_EXPORT QgsTransaction : public QObject * Some providers might not honour the statement timeout. */ bool begin( QString& errorMsg, int statementTimeout = 20 ); - /** Commit transaction. */ + //! Commit transaction. bool commit( QString& errorMsg ); - /** Roll back transaction. */ + //! Roll back transaction. bool rollback( QString& errorMsg ); - /** Executes sql */ + //! Executes sql virtual bool executeSql( const QString& sql, QString& error ) = 0; /** diff --git a/src/core/qgsunittypes.h b/src/core/qgsunittypes.h index 034aa2c0acfa..00dc9a0ebc1b 100644 --- a/src/core/qgsunittypes.h +++ b/src/core/qgsunittypes.h @@ -41,61 +41,61 @@ class CORE_EXPORT QgsUnitTypes //! Units of distance enum DistanceUnit { - DistanceMeters = 0, /*!< meters */ - DistanceKilometers, /*!< kilometers */ - DistanceFeet, /*!< imperial feet */ - DistanceNauticalMiles, /*!< nautical miles */ - DistanceYards, /*!< imperial yards */ - DistanceMiles, /*!< terrestial miles */ - DistanceDegrees, /*!< degrees, for planar geographic CRS distance measurements */ - DistanceUnknownUnit, /*!< unknown distance unit */ + DistanceMeters = 0, //!< Meters + DistanceKilometers, //!< Kilometers + DistanceFeet, //!< Imperial feet + DistanceNauticalMiles, //!< Nautical miles + DistanceYards, //!< Imperial yards + DistanceMiles, //!< Terrestial miles + DistanceDegrees, //!< Degrees, for planar geographic CRS distance measurements + DistanceUnknownUnit, //!< Unknown distance unit }; /** Types of distance units */ enum DistanceUnitType { - Standard = 0, /*!< unit is a standard measurement unit */ - Geographic, /*!< unit is a geographic (eg degree based) unit */ - UnknownType, /*!< unknown unit type */ + Standard = 0, //!< Unit is a standard measurement unit + Geographic, //!< Unit is a geographic (eg degree based) unit + UnknownType, //!< Unknown unit type }; //! Units of area enum AreaUnit { - AreaSquareMeters = 0, /*!< square meters */ - AreaSquareKilometers, /*!< square kilometers */ - AreaSquareFeet, /*!< square feet */ - AreaSquareYards, /*!< square yards */ - AreaSquareMiles, /*!< square miles */ - AreaHectares, /*!< hectares */ - AreaAcres, /*!< acres */ - AreaSquareNauticalMiles, /*!< square nautical miles */ - AreaSquareDegrees, /*!< square degrees, for planar geographic CRS area measurements */ - AreaUnknownUnit, /*!< unknown areal unit */ + AreaSquareMeters = 0, //!< Square meters + AreaSquareKilometers, //!< Square kilometers + AreaSquareFeet, //!< Square feet + AreaSquareYards, //!< Square yards + AreaSquareMiles, //!< Square miles + AreaHectares, //!< Hectares + AreaAcres, //!< Acres + AreaSquareNauticalMiles, //!< Square nautical miles + AreaSquareDegrees, //!< Square degrees, for planar geographic CRS area measurements + AreaUnknownUnit, //!< Unknown areal unit }; //! Units of angles enum AngleUnit { - AngleDegrees = 0, /*!< degrees */ - AngleRadians, /*!< square kilometers */ - AngleGon, /*!< gon/gradian */ - AngleMinutesOfArc, /*!< minutes of arc */ - AngleSecondsOfArc, /*!< seconds of arc */ - AngleTurn, /*!< turn/revolutions */ - AngleUnknownUnit, /*!< unknown angle unit */ + AngleDegrees = 0, //!< Degrees + AngleRadians, //!< Square kilometers + AngleGon, //!< Gon/gradian + AngleMinutesOfArc, //!< Minutes of arc + AngleSecondsOfArc, //!< Seconds of arc + AngleTurn, //!< Turn/revolutions + AngleUnknownUnit, //!< Unknown angle unit }; //! Rendering size units enum RenderUnit { - RenderMillimeters = 0, //!< millimeters - RenderMapUnits, //!< map units - RenderPixels, //!< pixels - RenderPercentage, //!< percentage of another measurement (eg canvas size, feature size) + RenderMillimeters = 0, //!< Millimeters + RenderMapUnits, //!< Map units + RenderPixels, //!< Pixels + RenderPercentage, //!< Percentage of another measurement (eg canvas size, feature size) RenderPoints, //! points (eg for font sizes) - RenderUnknownUnit, //!< mixed or unknown units + RenderUnknownUnit, //!< Mixed or unknown units }; //! List of render units diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index c172f2486839..bb5c967ab81c 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -61,47 +61,47 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ enum Capability { - /** Provider has no capabilities */ + //! Provider has no capabilities NoCapabilities = 0, - /** Allows adding features */ + //! Allows adding features AddFeatures = 1, - /** Allows deletion of features */ + //! Allows deletion of features DeleteFeatures = 1 << 1, - /** Allows modification of attribute values */ + //! Allows modification of attribute values ChangeAttributeValues = 1 << 2, - /** Allows addition of new attributes (fields) */ + //! Allows addition of new attributes (fields) AddAttributes = 1 << 3, - /** Allows deletion of attributes (fields) */ + //! Allows deletion of attributes (fields) DeleteAttributes = 1 << 4, - /** Allows creation of spatial index */ + //! Allows creation of spatial index CreateSpatialIndex = 1 << 6, - /** Fast access to features using their ID */ + //! Fast access to features using their ID SelectAtId = 1 << 7, - /** Allows modifications of geometries */ + //! Allows modifications of geometries ChangeGeometries = 1 << 8, - /** Allows user to select encoding */ + //! Allows user to select encoding SelectEncoding = 1 << 13, - /** Can create indexes on provider's fields */ + //! Can create indexes on provider's fields CreateAttributeIndex = 1 << 12, - /** Supports simplification of geometries on provider side according to a distance tolerance */ + //! Supports simplification of geometries on provider side according to a distance tolerance SimplifyGeometries = 1 << 14, - /** Supports topological simplification of geometries on provider side according to a distance tolerance */ + //! Supports topological simplification of geometries on provider side according to a distance tolerance SimplifyGeometriesWithTopologicalValidation = 1 << 15, - /** Supports transactions*/ + //! Supports transactions TransactionSupport = 1 << 16, - /** Supports circular geometry types (circularstring, compoundcurve, curvepolygon)*/ + //! Supports circular geometry types (circularstring, compoundcurve, curvepolygon) CircularGeometries = 1 << 17, /** Supports joint updates for attributes and geometry * Providers supporting this should still define ChangeGeometries | ChangeAttributeValues */ ChangeFeatures = 1 << 18, - /** Supports renaming attributes (fields). Added in QGIS 2.16 */ + //! Supports renaming attributes (fields). Added in QGIS 2.16 RenameAttributes = 1 << 19, }; Q_DECLARE_FLAGS( Capabilities, Capability ) - /** Bitmask of all provider's editing capabilities */ + //! Bitmask of all provider's editing capabilities const static int EditingCapabilities = AddFeatures | DeleteFeatures | ChangeAttributeValues | ChangeGeometries | AddAttributes | DeleteAttributes | RenameAttributes; @@ -296,7 +296,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ virtual bool createSpatialIndex(); - /** Create an attribute index on the datasource*/ + //! Create an attribute index on the datasource virtual bool createAttributeIndex( int field ); /** Returns flags containing the supported capabilities @@ -385,7 +385,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ virtual bool doesStrictFeatureTypeCheck() const { return true;} - /** Returns a list of available encodings */ + //! Returns a list of available encodings static QStringList availableEncodings(); /** @@ -495,19 +495,19 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider mutable bool mCacheMinMaxDirty; mutable QMap mCacheMinValues, mCacheMaxValues; - /** Encoding */ + //! Encoding QTextCodec* mEncoding; - /** List of attribute indices to fetch with nextFeature calls*/ + //! List of attribute indices to fetch with nextFeature calls QgsAttributeList mAttributesToFetch; - /** The names of the providers native types*/ + //! The names of the providers native types QList< NativeType > mNativeTypes; - /** Old notation **/ + //! Old notation * QMap mOldTypeList; - /** List of errors */ + //! List of errors mutable QStringList mErrors; static QStringList smEncodings; diff --git a/src/core/qgsvectorfilewriter.h b/src/core/qgsvectorfilewriter.h index af9f44ac6f4b..0780a15f3606 100644 --- a/src/core/qgsvectorfilewriter.h +++ b/src/core/qgsvectorfilewriter.h @@ -148,7 +148,7 @@ class CORE_EXPORT QgsVectorFileWriter QString ext; QMap driverOptions; QMap layerOptions; - /** Some formats require a compulsory encoding, typically UTF-8. If no compulsory encoding, empty string */ + //! Some formats require a compulsory encoding, typically UTF-8. If no compulsory encoding, empty string QString compulsoryEncoding; }; @@ -179,10 +179,10 @@ class CORE_EXPORT QgsVectorFileWriter class CORE_EXPORT FieldValueConverter { public: - /** Constructor */ + //! Constructor FieldValueConverter(); - /** Destructor */ + //! Destructor virtual ~FieldValueConverter(); /** Return a possibly modified field definition. Default implementation will return provided field unmodified. @@ -203,16 +203,16 @@ class CORE_EXPORT QgsVectorFileWriter * @note Added in QGIS 3.0 */ enum EditionCapability { - /** Flag to indicate that a new layer can be added to the dataset */ + //! Flag to indicate that a new layer can be added to the dataset CanAddNewLayer = 1 << 0, - /** Flag to indicate that new features can be added to an existing layer */ + //! Flag to indicate that new features can be added to an existing layer CanAppendToExistingLayer = 1 << 1, - /** Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer */ + //! Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer CanAddNewFieldsToExistingLayer = 1 << 2, - /** Flag to indicate that an existing layer can be deleted */ + //! Flag to indicate that an existing layer can be deleted CanDeleteLayer = 1 << 3 }; @@ -225,16 +225,16 @@ class CORE_EXPORT QgsVectorFileWriter */ typedef enum { - /** Create or overwrite file */ + //! Create or overwrite file CreateOrOverwriteFile, - /** Create or overwrite layer */ + //! Create or overwrite layer CreateOrOverwriteLayer, - /** Append features to existing layer, but do not create new fields */ + //! Append features to existing layer, but do not create new fields AppendToLayerNoNewFields, - /** Append features to existing layer, and create new fields if needed */ + //! Append features to existing layer, and create new fields if needed AppendToLayerAddFields } ActionOnExistingFile; @@ -334,63 +334,63 @@ class CORE_EXPORT QgsVectorFileWriter class CORE_EXPORT SaveVectorOptions { public: - /** Constructor */ + //! Constructor SaveVectorOptions(); - /** Destructor */ + //! Destructor virtual ~SaveVectorOptions(); - /** OGR driver to use */ + //! OGR driver to use QString driverName; - /** Layer name. If let empty, it will be derived from the filename */ + //! Layer name. If let empty, it will be derived from the filename QString layerName; - /** Action on existing file */ + //! Action on existing file ActionOnExistingFile actionOnExistingFile; - /** Encoding to use */ + //! Encoding to use QString fileEncoding; /** Transform to reproject exported geometries with, or invalid transform * for no transformation */ QgsCoordinateTransform ct; - /** Write only selected features of layer */ + //! Write only selected features of layer bool onlySelectedFeatures; - /** List of OGR data source creation options */ + //! List of OGR data source creation options QStringList datasourceOptions; - /** List of OGR layer creation options */ + //! List of OGR layer creation options QStringList layerOptions; - /** Only write geometries */ + //! Only write geometries bool skipAttributeCreation; - /** Attributes to export (empty means all unless skipAttributeCreation is set) */ + //! Attributes to export (empty means all unless skipAttributeCreation is set) QgsAttributeList attributes; - /** Symbology to export */ + //! Symbology to export SymbologyExport symbologyExport; - /** Scale of symbology */ + //! Scale of symbology double symbologyScale; - /** If not empty, only features intersecting the extent will be saved */ + //! If not empty, only features intersecting the extent will be saved QgsRectangle filterExtent; /** Set to a valid geometry type to override the default geometry type for the layer. This parameter * allows for conversion of geometryless tables to null geometries, etc */ QgsWkbTypes::Type overrideGeometryType; - /** Set to true to force creation of multi* geometries */ + //! Set to true to force creation of multi* geometries bool forceMulti; - /** Set to true to include z dimension in output. This option is only valid if overrideGeometryType is set */ + //! Set to true to include z dimension in output. This option is only valid if overrideGeometryType is set bool includeZ; - /** Field value converter */ + //! Field value converter FieldValueConverter* fieldValueConverter; }; @@ -408,7 +408,7 @@ class CORE_EXPORT QgsVectorFileWriter QString *newFilename = nullptr, QString *errorMessage = nullptr ); - /** Create a new vector file writer */ + //! Create a new vector file writer QgsVectorFileWriter( const QString& vectorFileName, const QString& fileEncoding, const QgsFields& fields, @@ -421,7 +421,7 @@ class CORE_EXPORT QgsVectorFileWriter SymbologyExport symbologyExport = NoSymbology ); - /** Returns map with format filter string as key and OGR format key as value*/ + //! Returns map with format filter string as key and OGR format key as value static QMap< QString, QString> supportedFiltersAndFormats(); /** Returns driver list that can be used for dialogs. It contains all OGR drivers @@ -430,28 +430,28 @@ class CORE_EXPORT QgsVectorFileWriter */ static QMap< QString, QString> ogrDriverList(); - /** Returns filter string that can be used for dialogs*/ + //! Returns filter string that can be used for dialogs static QString fileFilterString(); - /** Creates a filter for an OGR driver key*/ + //! Creates a filter for an OGR driver key static QString filterForDriver( const QString& driverName ); - /** Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile*/ + //! Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile static QString convertCodecNameForEncodingOption( const QString &codecName ); - /** Checks whether there were any errors in constructor */ + //! Checks whether there were any errors in constructor WriterError hasError(); - /** Retrieves error message */ + //! Retrieves error message QString errorMessage(); - /** Add feature to the currently opened data source */ + //! Add feature to the currently opened data source bool addFeature( QgsFeature& feature, QgsFeatureRenderer* renderer = nullptr, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters ); //! @note not available in python bindings QMap attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } - /** Close opened shapefile for writing */ + //! Close opened shapefile for writing ~QgsVectorFileWriter(); /** Delete a shapefile (and its accompanying shx / dbf / prf) @@ -523,16 +523,16 @@ class CORE_EXPORT QgsVectorFileWriter QgsFields mFields; - /** Contains error value if construction was not successful */ + //! Contains error value if construction was not successful WriterError mError; QString mErrorMessage; QTextCodec *mCodec; - /** Geometry type which is being used */ + //! Geometry type which is being used QgsWkbTypes::Type mWkbType; - /** Map attribute indizes to OGR field indexes */ + //! Map attribute indizes to OGR field indexes QMap mAttrIdxToOgrIdx; SymbologyExport mSymbologyExport; @@ -541,12 +541,12 @@ class CORE_EXPORT QgsVectorFileWriter QMap< QgsSymbolLayer*, QString > mSymbolLayerTable; #endif - /** Scale for symbology export (e.g. for symbols units in map units)*/ + //! Scale for symbology export (e.g. for symbols units in map units) double mSymbologyScaleDenominator; QString mOgrDriverName; - /** Field value converter */ + //! Field value converter FieldValueConverter* mFieldValueConverter; private: @@ -597,7 +597,7 @@ class CORE_EXPORT QgsVectorFileWriter OGRFeatureH createFeature( const QgsFeature& feature ); bool writeFeature( OGRLayerH layer, OGRFeatureH feature ); - /** Writes features considering symbol level order*/ + //! Writes features considering symbol level order WriterError exportFeaturesSymbolLevels( QgsVectorLayer* layer, QgsFeatureIterator& fit, const QgsCoordinateTransform& ct, QString* errorMessage = nullptr ); double mmScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits ); double mapUnitScaleFactor( double scaleDenominator, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits ); @@ -605,7 +605,7 @@ class CORE_EXPORT QgsVectorFileWriter void startRender( QgsVectorLayer* vl ); void stopRender( QgsVectorLayer* vl ); QgsFeatureRenderer* symbologyRenderer( QgsVectorLayer* vl ) const; - /** Adds attributes needed for classification*/ + //! Adds attributes needed for classification void addRendererAttributes( QgsVectorLayer* vl, QgsAttributeList& attList ); static QMap sDriverMetadata; diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index f1b78711caed..86e173d3f117 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -638,7 +638,7 @@ class QgsVectorLayerInterruptionCheckerDuringCountSymbolFeatures: public QgsInte { public: - /** Constructor */ + //! Constructor explicit QgsVectorLayerInterruptionCheckerDuringCountSymbolFeatures( QProgressDialog* dialog ) : mDialog( dialog ) { @@ -3407,7 +3407,7 @@ QList QgsVectorLayer::getDoubleValues( const QString &fieldOrExpression, } -/** Write blend mode for features */ +//! Write blend mode for features void QgsVectorLayer::setFeatureBlendMode( QPainter::CompositionMode featureBlendMode ) { mFeatureBlendMode = featureBlendMode; @@ -3415,13 +3415,13 @@ void QgsVectorLayer::setFeatureBlendMode( QPainter::CompositionMode featureBlend emit styleChanged(); } -/** Read blend mode for layer */ +//! Read blend mode for layer QPainter::CompositionMode QgsVectorLayer::featureBlendMode() const { return mFeatureBlendMode; } -/** Write transparency for layer */ +//! Write transparency for layer void QgsVectorLayer::setLayerTransparency( int layerTransparency ) { mLayerTransparency = layerTransparency; @@ -3429,7 +3429,7 @@ void QgsVectorLayer::setLayerTransparency( int layerTransparency ) emit styleChanged(); } -/** Read transparency for layer */ +//! Read transparency for layer int QgsVectorLayer::layerTransparency() const { return mLayerTransparency; diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 3e87a374930a..08085b50fef0 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -83,15 +83,15 @@ struct CORE_EXPORT QgsVectorJoinInfo , joinFieldIndex( -1 ) {} - /** Join field in the target layer*/ + //! Join field in the target layer QString targetFieldName; - /** Source layer*/ + //! Source layer QString joinLayerId; - /** Join field in the source layer*/ + //! Join field in the source layer QString joinFieldName; - /** True if the join is cached in virtual memory*/ + //! True if the join is cached in virtual memory bool memoryCache; - /** True if the cached join attributes need to be updated*/ + //! True if the cached join attributes need to be updated bool cacheDirty; /** Cache for joined attributes to provide fast lookup (size is 0 if no memory caching) @@ -99,9 +99,9 @@ struct CORE_EXPORT QgsVectorJoinInfo */ QHash< QString, QgsAttributes> cachedAttributes; - /** Join field index in the target layer. For backward compatibility with 1.x (x>=7)*/ + //! Join field index in the target layer. For backward compatibility with 1.x (x>=7) int targetFieldIndex; - /** Join field index in the source layer. For backward compatibility with 1.x (x>=7)*/ + //! Join field index in the source layer. For backward compatibility with 1.x (x>=7) int joinFieldIndex; /** An optional prefix. If it is a Null string "{layername}_" will be used @@ -127,7 +127,7 @@ struct CORE_EXPORT QgsVectorJoinInfo QStringList* joinFieldNamesSubset() const { return joinFieldsSubset.data(); } protected: - /** Subset of fields to use from joined layer. null = use all fields*/ + //! Subset of fields to use from joined layer. null = use all fields QSharedPointer joinFieldsSubset; }; @@ -420,20 +420,20 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte //! Result of an edit operation enum EditResult { - Success = 0, /**< Edit operation was successful */ - EmptyGeometry = 1, /**< Edit operation resulted in an empty geometry */ - EditFailed = 2, /**< Edit operation failed */ - FetchFeatureFailed = 3, /**< Unable to fetch requested feature */ - InvalidLayer = 4, /**< Edit failed due to invalid layer */ + Success = 0, //!< Edit operation was successful + EmptyGeometry = 1, //!< Edit operation resulted in an empty geometry + EditFailed = 2, //!< Edit operation failed + FetchFeatureFailed = 3, //!< Unable to fetch requested feature + InvalidLayer = 4, //!< Edit failed due to invalid layer }; //! Selection behaviour enum SelectBehaviour { - SetSelection, /**< Set selection, removing any existing selection */ - AddToSelection, /**< Add selection to current selection */ - IntersectSelection, /**< Modify current selection to include only select features which match */ - RemoveFromSelection, /**< Remove from current selection */ + SetSelection, //!< Set selection, removing any existing selection + AddToSelection, //!< Add selection to current selection + IntersectSelection, //!< Modify current selection to include only select features which match + RemoveFromSelection, //!< Remove from current selection }; /** Constructor - creates a vector layer @@ -452,16 +452,16 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte QgsVectorLayer( const QString& path = QString::null, const QString& baseName = QString::null, const QString& providerLib = QString::null, bool loadDefaultStyleFlag = true ); - /** Destructor */ + //! Destructor virtual ~QgsVectorLayer(); - /** Returns the permanent storage type for this layer as a friendly name. */ + //! Returns the permanent storage type for this layer as a friendly name. QString storageType() const; - /** Capabilities for this layer in a friendly format. */ + //! Capabilities for this layer in a friendly format. QString capabilitiesString() const; - /** Returns a comment for the data in the layer */ + //! Returns a comment for the data in the layer QString dataComment() const; /** @@ -489,7 +489,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ QString displayExpression() const; - /** Returns the data provider */ + //! Returns the data provider QgsVectorDataProvider* dataProvider(); /** Returns the data provider in a const-correct manner @@ -497,10 +497,10 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ const QgsVectorDataProvider* dataProvider() const; - /** Sets the textencoding of the data provider */ + //! Sets the textencoding of the data provider void setProviderEncoding( const QString& encoding ); - /** Setup the coordinate system transformation for the layer */ + //! Setup the coordinate system transformation for the layer void setCoordinateSystem(); /** Joins another vector layer to this layer @@ -642,13 +642,13 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void modifySelection( const QgsFeatureIds& selectIds, const QgsFeatureIds &deselectIds ); - /** Select not selected features and deselect selected ones */ + //! Select not selected features and deselect selected ones void invertSelection(); - /** Select all the features */ + //! Select all the features void selectAll(); - /** Get all feature Ids */ + //! Get all feature Ids QgsFeatureIds allFeatureIds() const; /** @@ -691,7 +691,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ const QgsFeatureIds &selectedFeaturesIds() const; - /** Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned */ + //! Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned QgsRectangle boundingBoxOfSelected() const; /** Returns whether the layer contains labels which are enabled and should be drawn. @@ -706,14 +706,14 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool diagramsEnabled() const; - /** Sets diagram rendering object (takes ownership) */ + //! Sets diagram rendering object (takes ownership) void setDiagramRenderer( QgsDiagramRenderer* r ); const QgsDiagramRenderer* diagramRenderer() const { return mDiagramRenderer; } void setDiagramLayerSettings( const QgsDiagramLayerSettings& s ); const QgsDiagramLayerSettings *diagramLayerSettings() const { return mDiagramLayerSettings; } - /** Return renderer. */ + //! Return renderer. QgsFeatureRenderer* renderer() { return mRenderer; } /** Return const renderer. @@ -727,16 +727,16 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void setRenderer( QgsFeatureRenderer* r ); - /** Returns point, line or polygon */ + //! Returns point, line or polygon QgsWkbTypes::GeometryType geometryType() const; - /** Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeometry */ + //! Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeometry bool hasGeometryType() const; - /** Returns the WKBType or WKBUnknown in case of error*/ + //! Returns the WKBType or WKBUnknown in case of error QgsWkbTypes::Type wkbType() const; - /** Return the provider type for this layer */ + //! Return the provider type for this layer QString providerType() const; /** Reads vector layer specific state from project file Dom node. @@ -1088,12 +1088,12 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void setLabeling( QgsAbstractVectorLayerLabeling* labeling ); - /** Returns true if the provider is in editing mode */ + //! Returns true if the provider is in editing mode virtual bool isEditable() const override; virtual bool isSpatial() const override; - /** Returns true if the provider has been modified since the last commit */ + //! Returns true if the provider has been modified since the last commit virtual bool isModified() const; /** Snaps a point to the closest vertex if there is one within the snapping tolerance @@ -1116,7 +1116,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte QMultiMap < double, QgsSnappingResult > &snappingResults, QgsSnapper::SnappingType snap_to ); - /** Synchronises with changes in the datasource */ + //! Synchronises with changes in the datasource virtual void reload() override; /** Return new instance of QgsMapLayerRenderer that will be used for rendering of given context @@ -1124,7 +1124,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ virtual QgsMapLayerRenderer* createMapRenderer( QgsRenderContext& rendererContext ) override; - /** Return the extent of the layer */ + //! Return the extent of the layer QgsRectangle extent() const override; /** @@ -1162,7 +1162,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ inline QgsAttributeList pendingPkAttributesList() const { return pkAttributeList(); } - /** Returns list of attributes making up the primary key */ + //! Returns list of attributes making up the primary key QgsAttributeList pkAttributeList() const; /** @@ -1182,7 +1182,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool setReadOnly( bool readonly = true ); - /** Change feature's geometry */ + //! Change feature's geometry bool changeGeometry( QgsFeatureId fid, const QgsGeometry& geom ); /** @@ -1231,7 +1231,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ QString attributeAlias( int index ) const; - /** Convenience function that returns the attribute alias if defined or the field name else */ + //! Convenience function that returns the attribute alias if defined or the field name else QString attributeDisplayName( int index ) const; //! Returns a map of field name to attribute alias @@ -1256,7 +1256,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void setExcludeAttributesWfs( const QSet& att ) { mExcludeAttributesWFS = att; } - /** Delete an attribute field (but does not commit it) */ + //! Delete an attribute field (but does not commit it) bool deleteAttribute( int attr ); /** @@ -1268,10 +1268,10 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool deleteAttributes( QList attrs ); - /** Insert a copy of the given features into the layer (but does not commit it) */ + //! Insert a copy of the given features into the layer (but does not commit it) bool addFeatures( QgsFeatureList features, bool makeSelected = true ); - /** Delete a feature from the layer (but does not commit it) */ + //! Delete a feature from the layer (but does not commit it) bool deleteFeature( QgsFeatureId fid ); /** @@ -1312,10 +1312,10 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool rollBack( bool deleteBuffer = true ); - /** Get annotation form */ + //! Get annotation form QString annotationForm() const { return mAnnotationForm; } - /** Set annotation form for layer */ + //! Set annotation form for layer void setAnnotationForm( const QString& ui ); /** @@ -1338,13 +1338,13 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void beginEditCommand( const QString& text ); - /** Finish edit command and add it to undo/redo stack */ + //! Finish edit command and add it to undo/redo stack void endEditCommand(); - /** Destroy active command and reverts all changes in it */ + //! Destroy active command and reverts all changes in it void destroyEditCommand(); - /** Editing vertex markers */ + //! Editing vertex markers enum VertexMarkerType { SemiTransparentCircle, @@ -1352,13 +1352,13 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte NoMarker }; - /** Draws a vertex symbol at (screen) coordinates x, y. (Useful to assist vertex editing.) */ + //! Draws a vertex symbol at (screen) coordinates x, y. (Useful to assist vertex editing.) static void drawVertexMarker( double x, double y, QPainter& p, QgsVectorLayer::VertexMarkerType type, int vertexSize ); - /** Assembles mUpdatedFields considering provider fields, joined fields and added fields */ + //! Assembles mUpdatedFields considering provider fields, joined fields and added fields void updateFields(); - /** Caches joined attributes if required (and not already done) */ + //! Caches joined attributes if required (and not already done) // marked as const as these are just caches, and need to be created from const accessors void createJoinCaches() const; @@ -1466,19 +1466,19 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ QList< double > getDoubleValues( const QString &fieldOrExpression, bool &ok, bool selectedOnly = false, int* nullCount = nullptr ) const; - /** Set the blending mode used for rendering each feature */ + //! Set the blending mode used for rendering each feature void setFeatureBlendMode( QPainter::CompositionMode blendMode ); - /** Returns the current blending mode for features */ + //! Returns the current blending mode for features QPainter::CompositionMode featureBlendMode() const; - /** Set the transparency for the vector layer */ + //! Set the transparency for the vector layer void setLayerTransparency( int layerTransparency ); - /** Returns the current transparency for the vector layer */ + //! Returns the current transparency for the vector layer int layerTransparency() const; QString metadata() const override; - /** @note not available in python bindings */ + //! @note not available in python bindings inline QgsGeometryCache* cache() { return mCache; } /** Set the simplification settings for fast rendering of features @@ -1607,7 +1607,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ virtual void updateExtents(); - /** Check if there is a join with a layer that will be removed */ + //! Check if there is a join with a layer that will be removed void checkJoinLayerRemove( const QString& theLayerId ); /** @@ -1633,28 +1633,28 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void selectionChanged( const QgsFeatureIds& selected, const QgsFeatureIds& deselected, const bool clearAndSelect ); - /** This signal is emitted when selection was changed */ + //! This signal is emitted when selection was changed void selectionChanged(); - /** This signal is emitted when modifications has been done on layer */ + //! This signal is emitted when modifications has been done on layer void layerModified(); - /** Is emitted, when layer is checked for modifications. Use for last-minute additions */ + //! Is emitted, when layer is checked for modifications. Use for last-minute additions void beforeModifiedCheck() const; - /** Is emitted, before editing on this layer is started */ + //! Is emitted, before editing on this layer is started void beforeEditingStarted(); - /** Is emitted, when editing on this layer has started*/ + //! Is emitted, when editing on this layer has started void editingStarted(); - /** Is emitted, when edited changes successfully have been written to the data provider */ + //! Is emitted, when edited changes successfully have been written to the data provider void editingStopped(); - /** Is emitted, before changes are commited to the data provider */ + //! Is emitted, before changes are commited to the data provider void beforeCommitChanges(); - /** Is emitted, before changes are rolled back*/ + //! Is emitted, before changes are rolled back void beforeRollBack(); /** @@ -1747,26 +1747,26 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void geometryChanged( QgsFeatureId fid, const QgsGeometry& geometry ); - /** This signal is emitted, when attributes are deleted from the provider */ + //! This signal is emitted, when attributes are deleted from the provider void committedAttributesDeleted( const QString& layerId, const QgsAttributeList& deletedAttributes ); - /** This signal is emitted, when attributes are added to the provider */ + //! This signal is emitted, when attributes are added to the provider void committedAttributesAdded( const QString& layerId, const QList& addedAttributes ); - /** This signal is emitted, when features are added to the provider */ + //! This signal is emitted, when features are added to the provider void committedFeaturesAdded( const QString& layerId, const QgsFeatureList& addedFeatures ); - /** This signal is emitted, when features are deleted from the provider */ + //! This signal is emitted, when features are deleted from the provider void committedFeaturesRemoved( const QString& layerId, const QgsFeatureIds& deletedFeatureIds ); - /** This signal is emitted, when attribute value changes are saved to the provider */ + //! This signal is emitted, when attribute value changes are saved to the provider void committedAttributeValuesChanges( const QString& layerId, const QgsChangedAttributesMap& changedAttributesValues ); - /** This signal is emitted, when geometry changes are saved to the provider */ + //! This signal is emitted, when geometry changes are saved to the provider void committedGeometriesChanges( const QString& layerId, const QgsGeometryMap& changedGeometries ); - /** Emitted when the font family defined for labeling layer is not found on system */ + //! Emitted when the font family defined for labeling layer is not found on system void labelingFontNotFound( QgsVectorLayer* layer, const QString& fontfamily ); - /** Signal emitted when setFeatureBlendMode() is called */ + //! Signal emitted when setFeatureBlendMode() is called void featureBlendModeChanged( QPainter::CompositionMode blendMode ); - /** Signal emitted when setLayerTransparency() is called */ + //! Signal emitted when setLayerTransparency() is called void layerTransparencyChanged( int layerTransparency ); /** @@ -1853,7 +1853,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte void onRelationsLoaded(); protected: - /** Set the extent */ + //! Set the extent void setExtent( const QgsRectangle &rect ) override; private: // Private methods @@ -1862,10 +1862,10 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ virtual bool isReadOnly() const override; - /** Vector layers are not copyable */ + //! Vector layers are not copyable QgsVectorLayer( const QgsVectorLayer & rhs ); - /** Vector layers are not copyable */ + //! Vector layers are not copyable QgsVectorLayer & operator=( QgsVectorLayer const & rhs ); @@ -1875,7 +1875,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool setDataProvider( QString const & provider ); - /** Goes through all features and finds a free id (e.g. to give it temporarily to a not-commited feature) */ + //! Goes through all features and finds a free id (e.g. to give it temporarily to a not-commited feature) QgsFeatureId findFreeId(); /** Snaps to a geometry and adds the result to the multimap if it is within the snapping result @@ -1893,31 +1893,31 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte QMultiMap& snappingResults, QgsSnapper::SnappingType snap_to ) const; - /** Add joined attributes to a feature */ + //! Add joined attributes to a feature //void addJoinedAttributes( QgsFeature& f, bool all = false ); - /** Read labeling from SLD */ + //! Read labeling from SLD void readSldLabeling( const QDomNode& node ); private: // Private attributes QgsConditionalLayerStyles * mConditionalStyles; - /** Pointer to data provider derived from the abastract base class QgsDataProvider */ + //! Pointer to data provider derived from the abastract base class QgsDataProvider QgsVectorDataProvider *mDataProvider; - /** The preview expression used to generate a human readable preview string for features */ + //! The preview expression used to generate a human readable preview string for features QString mDisplayExpression; QString mMapTipTemplate; - /** Data provider key */ + //! Data provider key QString mProviderKey; - /** The user-defined actions that are accessed from the Identify Results dialog box */ + //! The user-defined actions that are accessed from the Identify Results dialog box QgsActionManager* mActions; - /** Flag indicating whether the layer is in read-only mode (editing disabled) or not */ + //! Flag indicating whether the layer is in read-only mode (editing disabled) or not bool mReadOnly; /** Set holding the feature IDs that are activated. Note that if a feature @@ -1926,46 +1926,46 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ QgsFeatureIds mSelectedFeatureIds; - /** Field map to commit */ + //! Field map to commit QgsFields mFields; - /** Map that stores the aliases for attributes. Key is the attribute name and value the alias for that attribute*/ + //! Map that stores the aliases for attributes. Key is the attribute name and value the alias for that attribute QgsStringMap mAttributeAliasMap; //! Map which stores default value expressions for fields QgsStringMap mDefaultExpressionMap; - /** Holds the configuration for the edit form */ + //! Holds the configuration for the edit form QgsEditFormConfig mEditFormConfig; - /** Attributes which are not published in WMS*/ + //! Attributes which are not published in WMS QSet mExcludeAttributesWMS; - /** Attributes which are not published in WFS*/ + //! Attributes which are not published in WFS QSet mExcludeAttributesWFS; - /** Geometry type as defined in enum WkbType (qgis.h) */ + //! Geometry type as defined in enum WkbType (qgis.h) QgsWkbTypes::Type mWkbType; - /** Renderer object which holds the information about how to display the features */ + //! Renderer object which holds the information about how to display the features QgsFeatureRenderer *mRenderer; - /** Simplification object which holds the information about how to simplify the features for fast rendering */ + //! Simplification object which holds the information about how to simplify the features for fast rendering QgsVectorSimplifyMethod mSimplifyMethod; - /** Labeling configuration */ + //! Labeling configuration QgsAbstractVectorLayerLabeling* mLabeling; - /** Whether 'labeling font not found' has be shown for this layer (only show once in QgsMessageBar, on first rendering) */ + //! Whether 'labeling font not found' has be shown for this layer (only show once in QgsMessageBar, on first rendering) bool mLabelFontNotFoundNotified; - /** Blend mode for features */ + //! Blend mode for features QPainter::CompositionMode mFeatureBlendMode; - /** Layer transparency */ + //! Layer transparency int mLayerTransparency; - /** Flag if the vertex markers should be drawn only for selection (true) or for all features (false) */ + //! Flag if the vertex markers should be drawn only for selection (true) or for all features (false) bool mVertexMarkerOnlyForSelection; QStringList mCommitErrors; diff --git a/src/core/qgsvectorlayerdiagramprovider.h b/src/core/qgsvectorlayerdiagramprovider.h index 8db71242163b..ea59fc52703b 100644 --- a/src/core/qgsvectorlayerdiagramprovider.h +++ b/src/core/qgsvectorlayerdiagramprovider.h @@ -39,7 +39,7 @@ class QgsDiagramLabelFeature : public QgsLabelFeature const QgsAttributes& attributes() { return mAttributes; } protected: - /** Stores attribute values for diagram rendering*/ + //! Stores attribute values for diagram rendering QgsAttributes mAttributes; }; diff --git a/src/core/qgsvectorlayereditbuffer.h b/src/core/qgsvectorlayereditbuffer.h index 31107dbf8ba2..4a9d528cfbec 100644 --- a/src/core/qgsvectorlayereditbuffer.h +++ b/src/core/qgsvectorlayereditbuffer.h @@ -38,7 +38,7 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject QgsVectorLayerEditBuffer( QgsVectorLayer* layer ); ~QgsVectorLayerEditBuffer(); - /** Returns true if the provider has been modified since the last commit */ + //! Returns true if the provider has been modified since the last commit virtual bool isModified() const; @@ -48,26 +48,26 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject */ virtual bool addFeature( QgsFeature& f ); - /** Insert a copy of the given features into the layer (but does not commit it) */ + //! Insert a copy of the given features into the layer (but does not commit it) virtual bool addFeatures( QgsFeatureList& features ); - /** Delete a feature from the layer (but does not commit it) */ + //! Delete a feature from the layer (but does not commit it) virtual bool deleteFeature( QgsFeatureId fid ); - /** Deletes a set of features from the layer (but does not commit it) */ + //! Deletes a set of features from the layer (but does not commit it) virtual bool deleteFeatures( const QgsFeatureIds& fid ); - /** Change feature's geometry */ + //! Change feature's geometry virtual bool changeGeometry( QgsFeatureId fid, const QgsGeometry &geom ); - /** Changed an attribute value (but does not commit it) */ + //! Changed an attribute value (but does not commit it) virtual bool changeAttributeValue( QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue = QVariant() ); /** Add an attribute field (but does not commit it) returns true if the field was added */ virtual bool addAttribute( const QgsField &field ); - /** Delete an attribute field (but does not commit it) */ + //! Delete an attribute field (but does not commit it) virtual bool deleteAttribute( int attr ); /** Renames an attribute field (but does not commit it) @@ -94,7 +94,7 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject */ virtual bool commitChanges( QStringList& commitErrors ); - /** Stop editing and discard the edits */ + //! Stop editing and discard the edits virtual void rollBack(); /** Returns a map of new features which are not committed. @@ -167,7 +167,7 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject void undoIndexChanged( int index ); signals: - /** This signal is emitted when modifications has been done on layer */ + //! This signal is emitted when modifications has been done on layer void layerModified(); void featureAdded( QgsFeatureId fid ); @@ -190,7 +190,7 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject */ void attributeRenamed( int idx, const QString& newName ); - /** Signals emitted after committing changes */ + //! Signals emitted after committing changes void committedAttributesDeleted( const QString& layerId, const QgsAttributeList& deletedAttributes ); void committedAttributesAdded( const QString& layerId, const QList& addedAttributes ); @@ -211,19 +211,19 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject void updateFields( QgsFields& fields ); - /** Update feature with uncommitted geometry updates */ + //! Update feature with uncommitted geometry updates void updateFeatureGeometry( QgsFeature &f ); - /** Update feature with uncommitted attribute updates */ + //! Update feature with uncommitted attribute updates void updateChangedAttributes( QgsFeature &f ); - /** Update added and changed features after addition of an attribute */ + //! Update added and changed features after addition of an attribute void handleAttributeAdded( int index ); - /** Update added and changed features after removal of an attribute */ + //! Update added and changed features after removal of an attribute void handleAttributeDeleted( int index ); - /** Updates an index in an attribute map to a new value (for updates of changed attributes) */ + //! Updates an index in an attribute map to a new value (for updates of changed attributes) void updateAttributeMapIndex( QgsAttributeMap& attrs, int index, int offset ) const; void updateLayerFields(); @@ -247,22 +247,22 @@ class CORE_EXPORT QgsVectorLayerEditBuffer : public QObject */ QgsFeatureIds mDeletedFeatureIds; - /** New features which are not committed. */ + //! New features which are not committed. QgsFeatureMap mAddedFeatures; - /** Changed attributes values which are not committed */ + //! Changed attributes values which are not committed QgsChangedAttributesMap mChangedAttributeValues; - /** Deleted attributes fields which are not committed. The list is kept sorted. */ + //! Deleted attributes fields which are not committed. The list is kept sorted. QgsAttributeList mDeletedAttributeIds; - /** Added attributes fields which are not committed */ + //! Added attributes fields which are not committed QList mAddedAttributes; - /** Renamed attributes which are not committed. */ + //! Renamed attributes which are not committed. QgsFieldNameMap mRenamedAttributes; - /** Changed geometries which are not committed. */ + //! Changed geometries which are not committed. QgsGeometryMap mChangedGeometries; friend class QgsGrassProvider; //GRASS provider totally abuses the edit buffer diff --git a/src/core/qgsvectorlayerfeatureiterator.h b/src/core/qgsvectorlayerfeatureiterator.h index 8f7666693ffd..c077bb071296 100644 --- a/src/core/qgsvectorlayerfeatureiterator.h +++ b/src/core/qgsvectorlayerfeatureiterator.h @@ -167,12 +167,12 @@ class CORE_EXPORT QgsVectorLayerFeatureIterator : public QgsAbstractFeatureItera */ struct FetchJoinInfo { - const QgsVectorJoinInfo* joinInfo;//!< cannonical source of information about the join - QgsAttributeList attributes; //!< attributes to fetch - int indexOffset; //!< at what position the joined fields start - QgsVectorLayer* joinLayer; //!< resolved pointer to the joined layer - int targetField; //!< index of field (of this layer) that drives the join - int joinField; //!< index of field (of the joined layer) must have equal value + const QgsVectorJoinInfo* joinInfo;//!< Cannonical source of information about the join + QgsAttributeList attributes; //!< Attributes to fetch + int indexOffset; //!< At what position the joined fields start + QgsVectorLayer* joinLayer; //!< Resolved pointer to the joined layer + int targetField; //!< Index of field (of this layer) that drives the join + int joinField; //!< Index of field (of the joined layer) must have equal value void addJoinedAttributesCached( QgsFeature& f, const QVariant& joinValue ) const; void addJoinedAttributesDirect( QgsFeature& f, const QVariant& joinValue ) const; @@ -206,7 +206,7 @@ class CORE_EXPORT QgsVectorLayerFeatureIterator : public QgsAbstractFeatureItera QList< int > mPreparedFields; QList< int > mFieldsToPrepare; - /** Join list sorted by dependency*/ + //! Join list sorted by dependency QList< FetchJoinInfo > mOrderedJoinInfoList; /** diff --git a/src/core/qgsvectorlayerimport.h b/src/core/qgsvectorlayerimport.h index 569f6a57fa11..4b92af4d06c7 100644 --- a/src/core/qgsvectorlayerimport.h +++ b/src/core/qgsvectorlayerimport.h @@ -50,7 +50,7 @@ class CORE_EXPORT QgsVectorLayerImport ErrInvalidProvider, ErrProviderUnsupportedFeature, ErrConnectionFailed, - ErrUserCancelled, /*!< User cancelled the import*/ + ErrUserCancelled, //!< User cancelled the import }; /** @@ -99,28 +99,28 @@ class CORE_EXPORT QgsVectorLayerImport QProgressDialog *progress = nullptr ); - /** Checks whether there were any errors */ + //! Checks whether there were any errors ImportError hasError(); - /** Retrieves error message */ + //! Retrieves error message QString errorMessage(); int errorCount() const { return mErrorCount; } - /** Add feature to the new created layer */ + //! Add feature to the new created layer bool addFeature( QgsFeature& feature ); - /** Close the new created layer */ + //! Close the new created layer ~QgsVectorLayerImport(); protected: - /** Flush the buffer writing the features to the new layer */ + //! Flush the buffer writing the features to the new layer bool flushBuffer(); - /** Create index */ + //! Create index bool createSpatialIndex(); - /** Contains error value */ + //! Contains error value ImportError mError; QString mErrorMessage; @@ -128,7 +128,7 @@ class CORE_EXPORT QgsVectorLayerImport QgsVectorDataProvider *mProvider; - /** Map attribute indexes to new field indexes */ + //! Map attribute indexes to new field indexes QMap mOldToNewAttrIdx; int mAttributeCount; diff --git a/src/core/qgsvectorlayerjoinbuffer.h b/src/core/qgsvectorlayerjoinbuffer.h index 7d1da6dbbdf5..c56868ce33ec 100644 --- a/src/core/qgsvectorlayerjoinbuffer.h +++ b/src/core/qgsvectorlayerjoinbuffer.h @@ -50,16 +50,16 @@ class CORE_EXPORT QgsVectorLayerJoinBuffer : public QObject */ void updateFields( QgsFields& fields ); - /** Calls cacheJoinLayer() for all vector joins*/ + //! Calls cacheJoinLayer() for all vector joins void createJoinCaches(); - /** Saves mVectorJoins to xml under the layer node*/ + //! Saves mVectorJoins to xml under the layer node void writeXml( QDomNode& layer_node, QDomDocument& document ) const; - /** Reads joins from project file*/ + //! Reads joins from project file void readXml( const QDomNode& layer_node ); - /** Quick way to test if there is any join at all*/ + //! Quick way to test if there is any join at all bool containsJoins() const { return !mVectorJoins.isEmpty(); } const QgsVectorJoinList& vectorJoins() const { return mVectorJoins; } @@ -96,13 +96,13 @@ class CORE_EXPORT QgsVectorLayerJoinBuffer : public QObject QgsVectorLayer* mLayer; - /** Joined vector layers*/ + //! Joined vector layers QgsVectorJoinList mVectorJoins; - /** Caches attributes of join layer in memory if QgsVectorJoinInfo.memoryCache is true (and the cache is not already there)*/ + //! Caches attributes of join layer in memory if QgsVectorJoinInfo.memoryCache is true (and the cache is not already there) void cacheJoinLayer( QgsVectorJoinInfo& joinInfo ); - /** Main mutex to protect most data members that can be modified concurrently */ + //! Main mutex to protect most data members that can be modified concurrently QMutex mMutex; }; diff --git a/src/core/qgsvectorlayerrenderer.h b/src/core/qgsvectorlayerrenderer.h index a74ef62dfef5..7ba66a09aeea 100644 --- a/src/core/qgsvectorlayerrenderer.h +++ b/src/core/qgsvectorlayerrenderer.h @@ -51,7 +51,7 @@ class QgsVectorLayerDiagramProvider; class QgsVectorLayerRendererInterruptionChecker: public QgsInterruptionChecker { public: - /** Constructor */ + //! Constructor explicit QgsVectorLayerRendererInterruptionChecker( const QgsRenderContext& context ); bool mustStop() const override; private: @@ -93,7 +93,7 @@ class QgsVectorLayerRenderer : public QgsMapLayerRenderer */ void drawRendererLevels( QgsFeatureIterator& fit ); - /** Stop version 2 renderer and selected renderer (if required) */ + //! Stop version 2 renderer and selected renderer (if required) void stopRenderer( QgsSingleSymbolRenderer* selRenderer ); @@ -103,7 +103,7 @@ class QgsVectorLayerRenderer : public QgsMapLayerRenderer QgsVectorLayerRendererInterruptionChecker mInterruptionChecker; - /** The rendered layer */ + //! The rendered layer QgsVectorLayer* mLayer; QgsFields mFields; // TODO: use fields from mSource diff --git a/src/core/qgsvectorsimplifymethod.h b/src/core/qgsvectorsimplifymethod.h index 7851eefea2c2..3dbfb2208724 100644 --- a/src/core/qgsvectorsimplifymethod.h +++ b/src/core/qgsvectorsimplifymethod.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsVectorSimplifyMethod //! construct a default object QgsVectorSimplifyMethod(); - /** Simplification flags for fast rendering of features */ + //! Simplification flags for fast rendering of features enum SimplifyHint { NoSimplification = 0, //!< No simplification can be applied @@ -38,12 +38,12 @@ class CORE_EXPORT QgsVectorSimplifyMethod }; Q_DECLARE_FLAGS( SimplifyHints, SimplifyHint ) - /** Sets the simplification hints of the vector layer managed */ + //! Sets the simplification hints of the vector layer managed void setSimplifyHints( SimplifyHints simplifyHints ) { mSimplifyHints = simplifyHints; } - /** Gets the simplification hints of the vector layer managed */ + //! Gets the simplification hints of the vector layer managed inline SimplifyHints simplifyHints() const { return mSimplifyHints; } - /** Types of local simplification algorithms that can be used */ + //! Types of local simplification algorithms that can be used enum SimplifyAlgorithm { Distance = 0, //!< The simplification uses the distance between points to remove duplicate points @@ -51,43 +51,43 @@ class CORE_EXPORT QgsVectorSimplifyMethod Visvalingam = 2, //!< The simplification gives each point in a line an importance weighting, so that least important points are removed first }; - /** Sets the local simplification algorithm of the vector layer managed */ + //! Sets the local simplification algorithm of the vector layer managed void setSimplifyAlgorithm( SimplifyAlgorithm simplifyAlgorithm ) { mSimplifyAlgorithm = simplifyAlgorithm; } - /** Gets the local simplification algorithm of the vector layer managed */ + //! Gets the local simplification algorithm of the vector layer managed inline SimplifyAlgorithm simplifyAlgorithm() const { return mSimplifyAlgorithm; } - /** Sets the tolerance of simplification in map units. Represents the maximum distance in map units between two coordinates which can be considered equal */ + //! Sets the tolerance of simplification in map units. Represents the maximum distance in map units between two coordinates which can be considered equal void setTolerance( double tolerance ) { mTolerance = tolerance; } - /** Gets the tolerance of simplification in map units. Represents the maximum distance in map units between two coordinates which can be considered equal */ + //! Gets the tolerance of simplification in map units. Represents the maximum distance in map units between two coordinates which can be considered equal inline double tolerance() const { return mTolerance; } - /** Sets the simplification threshold of the vector layer managed */ + //! Sets the simplification threshold of the vector layer managed void setThreshold( float threshold ) { mThreshold = threshold; } - /** Gets the simplification threshold of the vector layer managed */ + //! Gets the simplification threshold of the vector layer managed inline float threshold() const { return mThreshold; } - /** Sets where the simplification executes, after fetch the geometries from provider, or when supported, in provider before fetch the geometries */ + //! Sets where the simplification executes, after fetch the geometries from provider, or when supported, in provider before fetch the geometries void setForceLocalOptimization( bool localOptimization ) { mLocalOptimization = localOptimization; } - /** Gets where the simplification executes, after fetch the geometries from provider, or when supported, in provider before fetch the geometries */ + //! Gets where the simplification executes, after fetch the geometries from provider, or when supported, in provider before fetch the geometries inline bool forceLocalOptimization() const { return mLocalOptimization; } - /** Sets the maximum scale at which the layer should be simplified */ + //! Sets the maximum scale at which the layer should be simplified void setMaximumScale( float maximumScale ) { mMaximumScale = maximumScale; } - /** Gets the maximum scale at which the layer should be simplified */ + //! Gets the maximum scale at which the layer should be simplified inline float maximumScale() const { return mMaximumScale; } private: - /** Simplification hints for fast rendering of features of the vector layer managed */ + //! Simplification hints for fast rendering of features of the vector layer managed SimplifyHints mSimplifyHints; - /** Simplification algorithm */ + //! Simplification algorithm SimplifyAlgorithm mSimplifyAlgorithm; - /** Simplification tolerance, it represents the maximum distance between two coordinates which can be considered equal */ + //! Simplification tolerance, it represents the maximum distance between two coordinates which can be considered equal double mTolerance; - /** Simplification threshold */ + //! Simplification threshold float mThreshold; - /** Simplification executes after fetch the geometries from provider, otherwise it executes, when supported, in provider before fetch the geometries */ + //! Simplification executes after fetch the geometries from provider, otherwise it executes, when supported, in provider before fetch the geometries bool mLocalOptimization; - /** Maximum scale at which the layer should be simplified (Maximum scale at which generalisation should be carried out) */ + //! Maximum scale at which the layer should be simplified (Maximum scale at which generalisation should be carried out) float mMaximumScale; }; diff --git a/src/core/raster/qgsbrightnesscontrastfilter.h b/src/core/raster/qgsbrightnesscontrastfilter.h index 7a065dfb6ea2..bb6608353dad 100644 --- a/src/core/raster/qgsbrightnesscontrastfilter.h +++ b/src/core/raster/qgsbrightnesscontrastfilter.h @@ -49,17 +49,17 @@ class CORE_EXPORT QgsBrightnessContrastFilter : public QgsRasterInterface void writeXml( QDomDocument& doc, QDomElement& parentElem ) const override; - /** Sets base class members from xml. Usually called from create() methods of subclasses*/ + //! Sets base class members from xml. Usually called from create() methods of subclasses void readXml( const QDomElement& filterElem ) override; private: - /** Adjusts a color component by the specified brightness and contrast factor*/ + //! Adjusts a color component by the specified brightness and contrast factor int adjustColorComponent( int colorComponent, int alpha, int brightness, double contrastFactor ) const; - /** Current brightness coefficient value. Default: 0. Range: -255...255 */ + //! Current brightness coefficient value. Default: 0. Range: -255...255 int mBrightness; - /** Current contrast coefficient value. Default: 0. Range: -100...100 */ + //! Current contrast coefficient value. Default: 0. Range: -100...100 double mContrast; }; diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index b96a99fe85ce..0fe2fbf068f7 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -58,7 +58,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction bool operator<( const ColorRampItem& other ) const { return value < other.value; } }; - /** Supported methods for color interpolation. */ + //! Supported methods for color interpolation. enum ColorRamp_TYPE { INTERPOLATED, //!< Interpolates the color between two class breaks linearly. @@ -66,28 +66,28 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction EXACT //!< Assigns the color of the exact matching value in the color ramp item list }; - /** \brief Get the custom colormap*/ + //! \brief Get the custom colormap QList colorRampItemList() const {return mColorRampItemList.toList();} - /** \brief Get the color ramp type */ + //! \brief Get the color ramp type QgsColorRampShader::ColorRamp_TYPE colorRampType() const {return mColorRampType;} - /** \brief Get the color ramp type as a string */ + //! \brief Get the color ramp type as a string QString colorRampTypeAsQString(); - /** \brief Set custom colormap */ + //! \brief Set custom colormap void setColorRampItemList( const QList& theList ); //TODO: sort on set - /** \brief Set the color ramp type*/ + //! \brief Set the color ramp type void setColorRampType( QgsColorRampShader::ColorRamp_TYPE theColorRampType ); - /** \brief Set the color ramp type*/ + //! \brief Set the color ramp type void setColorRampType( const QString& theType ); - /** \brief Generates and new RGB value based on one input value */ + //! \brief Generates and new RGB value based on one input value bool shade( double, int*, int*, int*, int* ) override; - /** \brief Generates and new RGB value based on original RGB value */ + //! \brief Generates and new RGB value based on original RGB value bool shade( double, double, double, double, int*, int*, int*, int* ) override; void legendSymbologyItems( QList< QPair< QString, QColor > >& symbolItems ) const override; @@ -111,7 +111,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction * interpolated for values between the item values (false)*/ QVector mColorRampItemList; - /** \brief The color ramp type */ + //! \brief The color ramp type QgsColorRampShader::ColorRamp_TYPE mColorRampType; /** Look up table to speed up finding the right color. @@ -121,7 +121,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction double mLUTFactor; bool mLUTInitialized; - /** Do not render values out of range */ + //! Do not render values out of range bool mClip; }; diff --git a/src/core/raster/qgscontrastenhancement.h b/src/core/raster/qgscontrastenhancement.h index 54c60f8ec72e..70dba28d1956 100644 --- a/src/core/raster/qgscontrastenhancement.h +++ b/src/core/raster/qgscontrastenhancement.h @@ -40,7 +40,7 @@ class CORE_EXPORT QgsContrastEnhancement public: - /** \brief This enumerator describes the types of contrast enhancement algorithms that can be used. */ + //! \brief This enumerator describes the types of contrast enhancement algorithms that can be used. enum ContrastEnhancementAlgorithm { NoEnhancement, //this should be the default color scaling algorithm @@ -59,10 +59,10 @@ class CORE_EXPORT QgsContrastEnhancement * Static methods * */ - /** \brief Helper function that returns the maximum possible value for a GDAL data type */ + //! \brief Helper function that returns the maximum possible value for a GDAL data type static double maximumValuePossible( Qgis::DataType ); - /** \brief Helper function that returns the minimum possible value for a GDAL data type */ + //! \brief Helper function that returns the minimum possible value for a GDAL data type static double minimumValuePossible( Qgis::DataType ); /* @@ -70,10 +70,10 @@ class CORE_EXPORT QgsContrastEnhancement * Non-Static Inline methods * */ - /** \brief Return the maximum value for the contrast enhancement range. */ + //! \brief Return the maximum value for the contrast enhancement range. double maximumValue() const { return mMaximumValue; } - /** \brief Return the minimum value for the contrast enhancement range. */ + //! \brief Return the minimum value for the contrast enhancement range. double minimumValue() const { return mMinimumValue; } ContrastEnhancementAlgorithm contrastEnhancementAlgorithm() const { return mContrastEnhancementAlgorithm; } @@ -87,22 +87,22 @@ class CORE_EXPORT QgsContrastEnhancement * Non-Static methods * */ - /** \brief Apply the contrast enhancement to a value. Return values are 0 - 254, -1 means the pixel was clipped and should not be displayed */ + //! \brief Apply the contrast enhancement to a value. Return values are 0 - 254, -1 means the pixel was clipped and should not be displayed int enhanceContrast( double ); - /** \brief Return true if pixel is in stretable range, false if pixel is outside of range (i.e., clipped) */ + //! \brief Return true if pixel is in stretable range, false if pixel is outside of range (i.e., clipped) bool isValueInDisplayableRange( double ); - /** \brief Set the contrast enhancement algorithm */ + //! \brief Set the contrast enhancement algorithm void setContrastEnhancementAlgorithm( ContrastEnhancementAlgorithm, bool generateTable = true ); - /** \brief A public method that allows the user to set their own custom contrast enhancment function */ + //! \brief A public method that allows the user to set their own custom contrast enhancment function void setContrastEnhancementFunction( QgsContrastEnhancementFunction* ); - /** \brief Set the maximum value for the contrast enhancement range. */ + //! \brief Set the maximum value for the contrast enhancement range. void setMaximumValue( double, bool generateTable = true ); - /** \brief Return the minimum value for the contrast enhancement range. */ + //! \brief Return the minimum value for the contrast enhancement range. void setMinimumValue( double, bool generateTable = true ); void writeXml( QDomDocument& doc, QDomElement& parentElem ) const; @@ -110,39 +110,39 @@ class CORE_EXPORT QgsContrastEnhancement void readXml( const QDomElement& elem ); private: - /** \brief Current contrast enhancement algorithm */ + //! \brief Current contrast enhancement algorithm ContrastEnhancementAlgorithm mContrastEnhancementAlgorithm; - /** \brief Pointer to the contrast enhancement function */ + //! \brief Pointer to the contrast enhancement function QgsContrastEnhancementFunction* mContrastEnhancementFunction; - /** \brief Flag indicating if the lookup table needs to be regenerated */ + //! \brief Flag indicating if the lookup table needs to be regenerated bool mEnhancementDirty; - /** \brief Scalar so that values can be used as array indicies */ + //! \brief Scalar so that values can be used as array indicies double mLookupTableOffset; - /** \brief Pointer to the lookup table */ + //! \brief Pointer to the lookup table int *mLookupTable; - /** \brief User defineable minimum value for the band, used for enhanceContrasting */ + //! \brief User defineable minimum value for the band, used for enhanceContrasting double mMinimumValue; - /** \brief user defineable maximum value for the band, used for enhanceContrasting */ + //! \brief user defineable maximum value for the band, used for enhanceContrasting double mMaximumValue; - /** \brief Data type of the band */ + //! \brief Data type of the band Qgis::DataType mRasterDataType; - /** \brief Maximum range of values for a given data type */ + //! \brief Maximum range of values for a given data type double mRasterDataTypeRange; - /** \brief Method to generate a new lookup table */ + //! \brief Method to generate a new lookup table bool generateLookupTable(); - /** \brief Method to calculate the actual enhanceContrasted value(s) */ + //! \brief Method to calculate the actual enhanceContrasted value(s) int calculateContrastEnhancementValue( double ); const QgsContrastEnhancement& operator=( const QgsContrastEnhancement& ); diff --git a/src/core/raster/qgscontrastenhancementfunction.h b/src/core/raster/qgscontrastenhancementfunction.h index 25936c9886af..4221fa84361a 100644 --- a/src/core/raster/qgscontrastenhancementfunction.h +++ b/src/core/raster/qgscontrastenhancementfunction.h @@ -35,29 +35,29 @@ class CORE_EXPORT QgsContrastEnhancementFunction QgsContrastEnhancementFunction( const QgsContrastEnhancementFunction& f ); virtual ~QgsContrastEnhancementFunction() {} - /** \brief A customizable method that takes in a double and returns a int between 0 and 255 */ + //! \brief A customizable method that takes in a double and returns a int between 0 and 255 virtual int enhance( double ); - /** \brief A customicable method to indicate if the pixels is displayable */ + //! \brief A customicable method to indicate if the pixels is displayable virtual bool isValueInDisplayableRange( double ); - /** \brief Mustator for the maximum value */ + //! \brief Mustator for the maximum value void setMaximumValue( double ); - /** \brief Mutator for the minimum value */ + //! \brief Mutator for the minimum value void setMinimumValue( double ); protected: - /** \brief User defineable maximum value for the band, used for enhanceContrasting */ + //! \brief User defineable maximum value for the band, used for enhanceContrasting double mMaximumValue; - /** \brief User defineable minimum value for the band, used for enhanceContrasting */ + //! \brief User defineable minimum value for the band, used for enhanceContrasting double mMinimumValue; - /** \brief Minimum maximum range for the band, used for enhanceContrasting */ + //! \brief Minimum maximum range for the band, used for enhanceContrasting double mMinimumMaximumRange; - /** \brief Data type of the band */ + //! \brief Data type of the band Qgis::DataType mQgsRasterDataType; }; diff --git a/src/core/raster/qgscubicrasterresampler.h b/src/core/raster/qgscubicrasterresampler.h index 8b9e1bacda72..36f7001e1f7e 100644 --- a/src/core/raster/qgscubicrasterresampler.h +++ b/src/core/raster/qgscubicrasterresampler.h @@ -42,7 +42,7 @@ class CORE_EXPORT QgsCubicRasterResampler: public QgsRasterResampler double* xDerivativeMatrixAlpha, double* yDerivativeMatrixRed, double* yDerivativeMatrixGreen, double* yDerivativeMatrixBlue, double* yDerivativeMatrixAlpha ); - /** Use cubic curve interpoation at the borders of the raster*/ + //! Use cubic curve interpoation at the borders of the raster QRgb curveInterpolation( QRgb pt1, QRgb pt2, double t, double d1red, double d1green, double d1blue, double d1alpha, double d2red, double d2green, double d2blue, double d2alpha ); diff --git a/src/core/raster/qgshillshaderenderer.h b/src/core/raster/qgshillshaderenderer.h index 2c1387395c68..1501ee893704 100644 --- a/src/core/raster/qgshillshaderenderer.h +++ b/src/core/raster/qgshillshaderenderer.h @@ -123,10 +123,10 @@ class CORE_EXPORT QgsHillshadeRenderer : public QgsRasterRenderer double mLightAzimuth; bool mMultiDirectional; - /** Calculates the first order derivative in x-direction according to Horn (1981)*/ + //! Calculates the first order derivative in x-direction according to Horn (1981) double calcFirstDerX( double x11, double x21, double x31, double x12, double x22, double x32, double x13, double x23, double x33 , double cellsize ); - /** Calculates the first order derivative in y-direction according to Horn (1981)*/ + //! Calculates the first order derivative in y-direction according to Horn (1981) double calcFirstDerY( double x11, double x21, double x31, double x12, double x22, double x32, double x13, double x23, double x33 , double cellsize ); }; diff --git a/src/core/raster/qgshuesaturationfilter.h b/src/core/raster/qgshuesaturationfilter.h index 10dbdb6c9800..70224589a207 100644 --- a/src/core/raster/qgshuesaturationfilter.h +++ b/src/core/raster/qgshuesaturationfilter.h @@ -66,23 +66,23 @@ class CORE_EXPORT QgsHueSaturationFilter : public QgsRasterInterface void writeXml( QDomDocument& doc, QDomElement& parentElem ) const override; - /** Sets base class members from xml. Usually called from create() methods of subclasses*/ + //! Sets base class members from xml. Usually called from create() methods of subclasses void readXml( const QDomElement& filterElem ) override; private: - /** Process a change in saturation and update resultant HSL & RGB values*/ + //! Process a change in saturation and update resultant HSL & RGB values void processSaturation( int &r, int &g, int &b, int &h, int &s, int &l ); - /** Process a colorization and update resultant HSL & RGB values*/ + //! Process a colorization and update resultant HSL & RGB values void processColorization( int &r, int &g, int &b, int &h, int &s, int &l ); - /** Current saturation value. Range: -100 (desaturated) ... 0 (no change) ... 100 (increased)*/ + //! Current saturation value. Range: -100 (desaturated) ... 0 (no change) ... 100 (increased) int mSaturation; double mSaturationScale; - /** Current grayscale mode*/ + //! Current grayscale mode QgsHueSaturationFilter::GrayscaleMode mGrayscaleMode; - /** Colorize settings*/ + //! Colorize settings bool mColorizeOn; QColor mColorizeColor; int mColorizeH, mColorizeS; diff --git a/src/core/raster/qgsmultibandcolorrenderer.h b/src/core/raster/qgsmultibandcolorrenderer.h index b4a079a672d7..c47e2eeac95f 100644 --- a/src/core/raster/qgsmultibandcolorrenderer.h +++ b/src/core/raster/qgsmultibandcolorrenderer.h @@ -47,15 +47,15 @@ class CORE_EXPORT QgsMultiBandColorRenderer: public QgsRasterRenderer void setBlueBand( int band ) { mBlueBand = band; } const QgsContrastEnhancement* redContrastEnhancement() const { return mRedContrastEnhancement; } - /** Takes ownership*/ + //! Takes ownership void setRedContrastEnhancement( QgsContrastEnhancement* ce ); const QgsContrastEnhancement* greenContrastEnhancement() const { return mGreenContrastEnhancement; } - /** Takes ownership*/ + //! Takes ownership void setGreenContrastEnhancement( QgsContrastEnhancement* ce ); const QgsContrastEnhancement* blueContrastEnhancement() const { return mBlueContrastEnhancement; } - /** Takes ownership*/ + //! Takes ownership void setBlueContrastEnhancement( QgsContrastEnhancement* ce ); void writeXml( QDomDocument& doc, QDomElement& parentElem ) const override; diff --git a/src/core/raster/qgspalettedrasterrenderer.h b/src/core/raster/qgspalettedrasterrenderer.h index 9d6d6b2bf37e..272dc54aa28a 100644 --- a/src/core/raster/qgspalettedrasterrenderer.h +++ b/src/core/raster/qgspalettedrasterrenderer.h @@ -31,7 +31,7 @@ class QDomElement; class CORE_EXPORT QgsPalettedRasterRenderer: public QgsRasterRenderer { public: - /** Renderer owns color array*/ + //! Renderer owns color array QgsPalettedRasterRenderer( QgsRasterInterface* input, int bandNumber, QColor* colorArray, int nColors, const QVector& labels = QVector() ); QgsPalettedRasterRenderer( QgsRasterInterface* input, int bandNumber, QRgb* colorArray, int nColors, const QVector& labels = QVector() ); ~QgsPalettedRasterRenderer(); @@ -40,9 +40,9 @@ class CORE_EXPORT QgsPalettedRasterRenderer: public QgsRasterRenderer QgsRasterBlock *block( int bandNo, const QgsRectangle & extent, int width, int height, QgsRasterBlockFeedback* feedback = nullptr ) override; - /** Returns number of colors*/ + //! Returns number of colors int nColors() const { return mNColors; } - /** Returns copy of color array (caller takes ownership)*/ + //! Returns copy of color array (caller takes ownership) QColor* colors() const; /** Returns copy of rgb array (caller takes ownership) @@ -66,11 +66,11 @@ class CORE_EXPORT QgsPalettedRasterRenderer: public QgsRasterRenderer private: int mBand; - /** Color array*/ + //! Color array QRgb* mColors; - /** Number of colors*/ + //! Number of colors int mNColors; - /** Optional category labels, size of vector may be < mNColors */ + //! Optional category labels, size of vector may be < mNColors QVector mLabels; QgsPalettedRasterRenderer( const QgsPalettedRasterRenderer& ); diff --git a/src/core/raster/qgsraster.h b/src/core/raster/qgsraster.h index 7d7d75377fc0..039d9758c085 100644 --- a/src/core/raster/qgsraster.h +++ b/src/core/raster/qgsraster.h @@ -82,7 +82,7 @@ class CORE_EXPORT QgsRaster PyramidsErdas = 2 }; - /** \brief Contrast enhancement limits */ + //! \brief Contrast enhancement limits enum ContrastEnhancementLimits { ContrastEnhancementNone, @@ -91,7 +91,7 @@ class CORE_EXPORT QgsRaster ContrastEnhancementCumulativeCut }; - /** \brief This enumerator describes the different kinds of drawing we can do */ + //! \brief This enumerator describes the different kinds of drawing we can do enum DrawingStyle { UndefinedDrawingStyle, diff --git a/src/core/raster/qgsrasterbandstats.h b/src/core/raster/qgsrasterbandstats.h index 80cee43a6d31..ca93dba26640 100644 --- a/src/core/raster/qgsrasterbandstats.h +++ b/src/core/raster/qgsrasterbandstats.h @@ -61,7 +61,7 @@ class CORE_EXPORT QgsRasterBandStats bandNumber = 1; } - /** Compares region, size etc. not collected statistics */ + //! Compares region, size etc. not collected statistics bool contains( const QgsRasterBandStats &s ) const { return ( s.bandNumber == bandNumber && @@ -71,10 +71,10 @@ class CORE_EXPORT QgsRasterBandStats s.statsGathered == ( statsGathered & s.statsGathered ) ); } - /** \brief The gdal band number (starts at 1)*/ + //! \brief The gdal band number (starts at 1) int bandNumber; - /** \brief The number of not no data cells in the band. */ + //! \brief The number of not no data cells in the band. // TODO: check if no data are excluded in stats calculation qgssize elementCount; @@ -86,31 +86,31 @@ class CORE_EXPORT QgsRasterBandStats * are ignored. This does not use the gdal GetMinimum function. */ double minimumValue; - /** \brief The mean cell value for the band. NO_DATA values are excluded. */ + //! \brief The mean cell value for the band. NO_DATA values are excluded. double mean; - /** \brief The range is the distance between min & max. */ + //! \brief The range is the distance between min & max. double range; - /** \brief The standard deviation of the cell values. */ + //! \brief The standard deviation of the cell values. double stdDev; - /** \brief Collected statistics */ + //! \brief Collected statistics int statsGathered; - /** \brief The sum of all cells in the band. NO_DATA values are excluded. */ + //! \brief The sum of all cells in the band. NO_DATA values are excluded. double sum; - /** \brief The sum of the squares. Used to calculate standard deviation. */ + //! \brief The sum of the squares. Used to calculate standard deviation. double sumOfSquares; - /** \brief Number of columns used to calc statistics */ + //! \brief Number of columns used to calc statistics int width; - /** \brief Number of rows used to calc statistics */ + //! \brief Number of rows used to calc statistics int height; - /** \brief Extent used to calc statistics */ + //! \brief Extent used to calc statistics QgsRectangle extent; }; #endif diff --git a/src/core/raster/qgsrasterblock.h b/src/core/raster/qgsrasterblock.h index c4a254bd20ce..e2862ffbdf37 100644 --- a/src/core/raster/qgsrasterblock.h +++ b/src/core/raster/qgsrasterblock.h @@ -79,7 +79,7 @@ class CORE_EXPORT QgsRasterBlock */ bool isValid() const { return mValid; } - /** \brief Mark block as valid or invalid */ + //! \brief Mark block as valid or invalid void setValid( bool valid ) { mValid = valid; } /** Returns true if block is empty, i.e. its size is 0 (zero rows or cols). @@ -130,16 +130,16 @@ class CORE_EXPORT QgsRasterBlock return typeSize( mDataType ); } - /** Returns true if data type is numeric */ + //! Returns true if data type is numeric static bool typeIsNumeric( Qgis::DataType type ); - /** Returns true if data type is color */ + //! Returns true if data type is color static bool typeIsColor( Qgis::DataType type ); - /** Returns data type */ + //! Returns data type Qgis::DataType dataType() const { return mDataType; } - /** For given data type returns wider type and sets no data value */ + //! For given data type returns wider type and sets no data value static Qgis::DataType typeWithNoDataValue( Qgis::DataType dataType, double *noDataValue ); /** True if the block has no data value. @@ -322,10 +322,10 @@ class CORE_EXPORT QgsRasterBlock * @@note added in 2.3 */ void applyScaleOffset( double scale, double offset ); - /** \brief Get error */ + //! \brief Get error QgsError error() const { return mError; } - /** \brief Set error */ + //! \brief Set error void setError( const QgsError & theError ) { mError = theError;} QString toString() const; diff --git a/src/core/raster/qgsrasterdataprovider.h b/src/core/raster/qgsrasterdataprovider.h index 6560e7499dc0..c7014fbb0f2d 100644 --- a/src/core/raster/qgsrasterdataprovider.h +++ b/src/core/raster/qgsrasterdataprovider.h @@ -54,9 +54,9 @@ class CORE_EXPORT QgsImageFetcher : public QObject { Q_OBJECT public: - /** Constructor */ + //! Constructor QgsImageFetcher( QObject* parent = 0 ) : QObject( parent ) {} - /** Destructor */ + //! Destructor virtual ~QgsImageFetcher() {} /** Starts the image download @@ -67,9 +67,9 @@ class CORE_EXPORT QgsImageFetcher : public QObject /** Emitted when the download completes * @param legend The downloaded legend image */ void finish( const QImage& legend ); - /** Emitted to report progress */ + //! Emitted to report progress void progress( qint64 received, qint64 total ); - /** Emitted when an error occurs */ + //! Emitted when an error occurs void error( const QString& msg ); }; @@ -104,7 +104,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast virtual QgsRectangle extent() const override = 0; - /** Returns data type for the band specified by number */ + //! Returns data type for the band specified by number virtual Qgis::DataType dataType( int bandNo ) const override = 0; /** Returns source data type for the band specified by number, @@ -112,7 +112,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast */ virtual Qgis::DataType sourceDataType( int bandNo ) const override = 0; - /** Returns data type for the band specified by number */ + //! Returns data type for the band specified by number virtual int colorInterpretation( int theBandNo ) const { Q_UNUSED( theBandNo ); @@ -179,7 +179,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast return QStringLiteral( "Unknown" ); } } - /** Reload data (data could change) */ + //! Reload data (data could change) virtual bool reload() { return true; } virtual QString colorInterpretationName( int theBandNo ) const @@ -198,24 +198,24 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast // TODO: remove or make protected all readBlock working with void* - /** Read block of data using given extent and size. */ + //! Read block of data using given extent and size. virtual QgsRasterBlock *block( int theBandNo, const QgsRectangle &theExtent, int theWidth, int theHeight, QgsRasterBlockFeedback* feedback = nullptr ) override; - /** Return true if source band has no data value */ + //! Return true if source band has no data value virtual bool sourceHasNoDataValue( int bandNo ) const { return mSrcHasNoDataValue.value( bandNo -1 ); } - /** \brief Get source nodata value usage */ + //! \brief Get source nodata value usage virtual bool useSourceNoDataValue( int bandNo ) const { return mUseSrcNoDataValue.value( bandNo -1 ); } - /** \brief Set source nodata value usage */ + //! \brief Set source nodata value usage virtual void setUseSourceNoDataValue( int bandNo, bool use ); - /** Value representing no data value. */ + //! Value representing no data value. virtual double sourceNoDataValue( int bandNo ) const { return mSrcNoDataValue.value( bandNo -1 ); } virtual void setUserNoDataValue( int bandNo, const QgsRasterRangeList& noData ); - /** Get list of user no data value ranges */ + //! Get list of user no data value ranges virtual QgsRasterRangeList userNoDataValues( int bandNo ) const { return mUserNoDataValue.value( bandNo -1 ); } virtual QList colorTable( int bandNo ) const @@ -228,7 +228,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast return QStringList(); } - /** \brief Returns whether the provider supplies a legend graphic */ + //! \brief Returns whether the provider supplies a legend graphic virtual bool supportsLegendGraphic() const { return false; } /** \brief Returns the legend rendered as pixmap @@ -266,7 +266,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast return nullptr; } - /** \brief Create pyramid overviews */ + //! \brief Create pyramid overviews virtual QString buildPyramids( const QList & thePyramidList, const QString & theResamplingMethod = "NEAREST", QgsRaster::RasterPyramidsFormat theFormat = QgsRaster::PyramidsGTiff, @@ -289,7 +289,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast virtual QList buildPyramidList( QList overviewList = QList() ) // clazy:exclude=function-args-by-ref { Q_UNUSED( overviewList ); return QList(); } - /** \brief Returns true if raster has at least one populated histogram. */ + //! \brief Returns true if raster has at least one populated histogram. bool hasPyramids(); /** @@ -346,22 +346,22 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast */ virtual QString lastError() = 0; - /** Returns the format of the error text for the last error in this provider */ + //! Returns the format of the error text for the last error in this provider virtual QString lastErrorFormat(); - /** Returns the dpi of the output device. */ + //! Returns the dpi of the output device. int dpi() const { return mDpi; } - /** Sets the output device resolution. */ + //! Sets the output device resolution. void setDpi( int dpi ) { mDpi = dpi; } - /** Time stamp of data source in the moment when data/metadata were loaded by provider */ + //! Time stamp of data source in the moment when data/metadata were loaded by provider virtual QDateTime timestamp() const override { return mTimestamp; } - /** Current time stamp of data source */ + //! Current time stamp of data source virtual QDateTime dataTimestamp() const override { return QDateTime(); } - /** Writes into the provider datasource*/ + //! Writes into the provider datasource // TODO: add data type (may be defferent from band type) virtual bool write( void* data, int band, int width, int height, int xOffset, int yOffset ) { @@ -374,7 +374,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast return false; } - /** Creates a new dataset with mDataSourceURI */ + //! Creates a new dataset with mDataSourceURI static QgsRasterDataProvider* create( const QString &providerKey, const QString &uri, const QString& format, int nBands, @@ -389,7 +389,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast */ virtual bool setNoDataValue( int bandNo, double noDataValue ) { Q_UNUSED( bandNo ); Q_UNUSED( noDataValue ); return false; } - /** Remove dataset*/ + //! Remove dataset virtual bool remove() { return false; } /** Returns a list of pyramid resampling method name and label pairs @@ -440,10 +440,10 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast virtual void readBlock( int bandNo, QgsRectangle const & viewExtent, int width, int height, void *data, QgsRasterBlockFeedback* feedback = nullptr ) { Q_UNUSED( bandNo ); Q_UNUSED( viewExtent ); Q_UNUSED( width ); Q_UNUSED( height ); Q_UNUSED( data ); Q_UNUSED( feedback ); } - /** Returns true if user no data contains value */ + //! Returns true if user no data contains value bool userNoDataValuesContains( int bandNo, double value ) const; - /** Copy member variables from other raster data provider. Useful for implementation of clone() method in subclasses */ + //! Copy member variables from other raster data provider. Useful for implementation of clone() method in subclasses void copyBaseSettings( const QgsRasterDataProvider& other ); //! @note not available in Python bindings @@ -460,10 +460,10 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast * is available. Used internally only */ //bool hasNoDataValue ( int theBandNo ); - /** \brief Cell value representing original source no data. e.g. -9999, indexed from 0 */ + //! \brief Cell value representing original source no data. e.g. -9999, indexed from 0 QList mSrcNoDataValue; - /** \brief Source no data value exists. */ + //! \brief Source no data value exists. QList mSrcHasNoDataValue; /** \brief Use source nodata value. User can disable usage of source nodata diff --git a/src/core/raster/qgsrasterfilewriter.h b/src/core/raster/qgsrasterfilewriter.h index 98b469775abe..8e446e454ca7 100644 --- a/src/core/raster/qgsrasterfilewriter.h +++ b/src/core/raster/qgsrasterfilewriter.h @@ -133,7 +133,7 @@ class CORE_EXPORT QgsRasterFileWriter void addToVRT( const QString& filename, int band, int xSize, int ySize, int xOffset, int yOffset ); void buildPyramids( const QString& filename ); - /** Create provider and datasource for a part image (vrt mode)*/ + //! Create provider and datasource for a part image (vrt mode) QgsRasterDataProvider* createPartProvider( const QgsRectangle& extent, int nCols, int iterCols, int iterRows, int iterLeft, int iterTop, const QString& outputUrl, int fileIndex, int nBands, Qgis::DataType type, @@ -154,7 +154,7 @@ class CORE_EXPORT QgsRasterFileWriter Qgis::DataType type, const QList& destHasNoDataValueList = QList(), const QList& destNoDataValueList = QList() ); - /** Calculate nRows, geotransform and pixel size for output*/ + //! Calculate nRows, geotransform and pixel size for output void globalOutputParameters( const QgsRectangle& extent, int nCols, int& nRows, double* geoTransform, double& pixelSize ); QString partFileName( int fileIndex ); @@ -167,7 +167,7 @@ class CORE_EXPORT QgsRasterFileWriter QStringList mCreateOptions; QgsCoordinateReferenceSystem mOutputCRS; - /** False: Write one file, true: create a directory and add the files numbered*/ + //! False: Write one file, true: create a directory and add the files numbered bool mTiledMode; double mMaxTileWidth; double mMaxTileHeight; diff --git a/src/core/raster/qgsrasterhistogram.h b/src/core/raster/qgsrasterhistogram.h index 011a206b446e..474274bb6920 100644 --- a/src/core/raster/qgsrasterhistogram.h +++ b/src/core/raster/qgsrasterhistogram.h @@ -45,7 +45,7 @@ class CORE_EXPORT QgsRasterHistogram valid = false; } - /** Compares region, size etc. not histogram itself */ + //! Compares region, size etc. not histogram itself bool operator==( const QgsRasterHistogram &h ) const { return ( h.bandNumber == bandNumber && @@ -58,16 +58,16 @@ class CORE_EXPORT QgsRasterHistogram h.height == height ); } - /** \brief The gdal band number (starts at 1)*/ + //! \brief The gdal band number (starts at 1) int bandNumber; - /** \brief Number of bins (intervals,buckets) in histogram. */ + //! \brief Number of bins (intervals,buckets) in histogram. int binCount; - /** \brief The number of non NULL cells used to calculate histogram. */ + //! \brief The number of non NULL cells used to calculate histogram. int nonNullCount; - /** \brief Whether histogram includes out of range values (in first and last bin) */ + //! \brief Whether histogram includes out of range values (in first and last bin) bool includeOutOfRange; /** \brief Store the histogram for a given layer @@ -75,22 +75,22 @@ class CORE_EXPORT QgsRasterHistogram */ HistogramVector histogramVector; - /** \brief The maximum histogram value. */ + //! \brief The maximum histogram value. double maximum; - /** \brief The minimum histogram value. */ + //! \brief The minimum histogram value. double minimum; - /** \brief Number of columns used to calc histogram */ + //! \brief Number of columns used to calc histogram int width; - /** \brief Number of rows used to calc histogram */ + //! \brief Number of rows used to calc histogram int height; - /** \brief Extent used to calc histogram */ + //! \brief Extent used to calc histogram QgsRectangle extent; - /** \brief Histogram is valid */ + //! \brief Histogram is valid bool valid; }; #endif diff --git a/src/core/raster/qgsrasteridentifyresult.h b/src/core/raster/qgsrasteridentifyresult.h index 08117a4b2939..c9ca82a54198 100644 --- a/src/core/raster/qgsrasteridentifyresult.h +++ b/src/core/raster/qgsrasteridentifyresult.h @@ -43,10 +43,10 @@ class CORE_EXPORT QgsRasterIdentifyResult virtual ~QgsRasterIdentifyResult(); - /** \brief Returns true if valid */ + //! \brief Returns true if valid bool isValid() const { return mValid; } - /** \brief Get results format */ + //! \brief Get results format QgsRaster::IdentifyFormat format() const { return mFormat; } /** \brief Get results. Results are different for each format: @@ -56,34 +56,34 @@ class CORE_EXPORT QgsRasterIdentifyResult */ QMap results() const { return mResults; } - /** Set map of optional parameters */ + //! Set map of optional parameters void setParams( const QMap & theParams ) { mParams = theParams; } - /** Get map of optional parameters */ + //! Get map of optional parameters QMap params() const { return mParams; } - /** \brief Get error */ + //! \brief Get error QgsError error() const { return mError; } - /** \brief Set error */ + //! \brief Set error void setError( const QgsError & theError ) { mError = theError;} private: - /** \brief Is valid */ + //! \brief Is valid bool mValid; - /** \brief Results format */ + //! \brief Results format QgsRaster::IdentifyFormat mFormat; - /** \brief Results */ + //! \brief Results // TODO: better hierarchy (sublayer multiple feature sets)? // TODO?: results are not consistent for different formats (per band x per sublayer) QMap mResults; - /** \brief Additional params (e.g. request url used by WMS) */ + //! \brief Additional params (e.g. request url used by WMS) QMap mParams; - /** \brief Error */ + //! \brief Error QgsError mError; }; diff --git a/src/core/raster/qgsrasterinterface.h b/src/core/raster/qgsrasterinterface.h index f87161533c9d..0cfd85d98a32 100644 --- a/src/core/raster/qgsrasterinterface.h +++ b/src/core/raster/qgsrasterinterface.h @@ -96,10 +96,10 @@ class CORE_EXPORT QgsRasterInterface virtual ~QgsRasterInterface(); - /** Clone itself, create deep copy */ + //! Clone itself, create deep copy virtual QgsRasterInterface *clone() const = 0; - /** Returns a bitmask containing the supported capabilities */ + //! Returns a bitmask containing the supported capabilities virtual int capabilities() const { return QgsRasterInterface::NoCapabilities; @@ -110,7 +110,7 @@ class CORE_EXPORT QgsRasterInterface */ QString capabilitiesString() const; - /** Returns data type for the band specified by number */ + //! Returns data type for the band specified by number virtual Qgis::DataType dataType( int bandNo ) const = 0; /** Returns source data type for the band specified by number, @@ -125,18 +125,18 @@ class CORE_EXPORT QgsRasterInterface int dataTypeSize( int bandNo ) { return QgsRasterBlock::typeSize( dataType( bandNo ) ); } - /** Get number of bands */ + //! Get number of bands virtual int bandCount() const = 0; - /** Get block size */ + //! Get block size virtual int xBlockSize() const { return mInput ? mInput->xBlockSize() : 0; } virtual int yBlockSize() const { return mInput ? mInput->yBlockSize() : 0; } - /** Get raster size */ + //! Get raster size virtual int xSize() const { return mInput ? mInput->xSize() : 0; } virtual int ySize() const { return mInput ? mInput->ySize() : 0; } - /** \brief helper function to create zero padded band names */ + //! \brief helper function to create zero padded band names virtual QString generateBandName( int theBandNumber ) const { return tr( "Band" ) + QStringLiteral( " %1" ) .arg( theBandNumber, 1 + static_cast< int >( log10( static_cast< double >( bandCount() ) ) ), 10, QChar( '0' ) ); @@ -157,13 +157,13 @@ class CORE_EXPORT QgsRasterInterface * Returns true if set correctly, false if cannot use that input */ virtual bool setInput( QgsRasterInterface* input ) { mInput = input; return true; } - /** Current input */ + //! Current input virtual QgsRasterInterface * input() const { return mInput; } - /** Is on/off */ + //! Is on/off virtual bool on() const { return mOn; } - /** Set on/off */ + //! Set on/off virtual void setOn( bool on ) { mOn = on; } /** Get source / raw input, the first in pipe, usually provider. @@ -253,19 +253,19 @@ class CORE_EXPORT QgsRasterInterface const QgsRectangle & theExtent = QgsRectangle(), int theSampleSize = 0 ); - /** Write base class members to xml. */ + //! Write base class members to xml. virtual void writeXml( QDomDocument& doc, QDomElement& parentElem ) const { Q_UNUSED( doc ); Q_UNUSED( parentElem ); } - /** Sets base class members from xml. Usually called from create() methods of subclasses */ + //! Sets base class members from xml. Usually called from create() methods of subclasses virtual void readXml( const QDomElement& filterElem ) { Q_UNUSED( filterElem ); } protected: // QgsRasterInterface used as input QgsRasterInterface* mInput; - /** \brief List of cached statistics, all bands mixed */ + //! \brief List of cached statistics, all bands mixed QList mStatistics; - /** \brief List of cached histograms, all bands mixed */ + //! \brief List of cached histograms, all bands mixed QList mHistograms; // On/off state, if off, it does not do anything, replicates input @@ -282,7 +282,7 @@ class CORE_EXPORT QgsRasterInterface int theSampleSize = 0, bool theIncludeOutOfRange = false ); - /** Fill in statistics defaults if not specified */ + //! Fill in statistics defaults if not specified void initStatistics( QgsRasterBandStats &theStatistics, int theBandNo, int theStats = QgsRasterBandStats::All, const QgsRectangle & theExtent = QgsRectangle(), diff --git a/src/core/raster/qgsrasteriterator.h b/src/core/raster/qgsrasteriterator.h index 525a020e84fe..63f6586242d5 100644 --- a/src/core/raster/qgsrasteriterator.h +++ b/src/core/raster/qgsrasteriterator.h @@ -86,7 +86,7 @@ class CORE_EXPORT QgsRasterIterator int mMaximumTileWidth; int mMaximumTileHeight; - /** Remove part into and release memory*/ + //! Remove part into and release memory void removePartInfo( int bandNumber ); }; diff --git a/src/core/raster/qgsrasterlayer.h b/src/core/raster/qgsrasterlayer.h index 1723cbf94480..a1409172ebb5 100644 --- a/src/core/raster/qgsrasterlayer.h +++ b/src/core/raster/qgsrasterlayer.h @@ -136,16 +136,16 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer { Q_OBJECT public: - /** \brief Default cumulative cut lower limit */ + //! \brief Default cumulative cut lower limit static const double CUMULATIVE_CUT_LOWER; - /** \brief Default cumulative cut upper limit */ + //! \brief Default cumulative cut upper limit static const double CUMULATIVE_CUT_UPPER; - /** \brief Default sample size (number of pixels) for estimated statistics/histogram calculation */ + //! \brief Default sample size (number of pixels) for estimated statistics/histogram calculation static const double SAMPLE_SIZE; - /** \brief Constructor. Provider is not set. */ + //! \brief Constructor. Provider is not set. QgsRasterLayer(); /** \brief This is the constructor for the RasterLayer class. @@ -173,16 +173,16 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer //as the previous constructor will be called with the literal for providerKey //implicitly converted to a bool. //for QGIS 3.0, make either constructor explicit or alter the signatures - /** \brief [ data provider interface ] Constructor in provider mode */ + //! \brief [ data provider interface ] Constructor in provider mode QgsRasterLayer( const QString &uri, const QString &baseName, const QString &providerKey, bool loadDefaultStyleFlag = true ); - /** \brief The destructor */ + //! \brief The destructor ~QgsRasterLayer(); - /** \brief This enumerator describes the types of shading that can be used */ + //! \brief This enumerator describes the types of shading that can be used enum ColorShadingAlgorithm { UndefinedShader, @@ -192,7 +192,7 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer UserDefinedShader }; - /** \brief This enumerator describes the type of raster layer */ + //! \brief This enumerator describes the type of raster layer enum LayerType { GrayOrUndefined, @@ -209,41 +209,41 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer static bool isValidRasterFileName( const QString & theFileNameQString, QString &retError ); static bool isValidRasterFileName( const QString & theFileNameQString ); - /** Return time stamp for given file name */ + //! Return time stamp for given file name static QDateTime lastModified( const QString & name ); - /** [ data provider interface ] Set the data provider */ + //! [ data provider interface ] Set the data provider void setDataProvider( const QString & provider ); - /** \brief Accessor for raster layer type (which is a read only property) */ + //! \brief Accessor for raster layer type (which is a read only property) LayerType rasterType() { return mRasterType; } - /** Set raster renderer. Takes ownership of the renderer object*/ + //! Set raster renderer. Takes ownership of the renderer object void setRenderer( QgsRasterRenderer* theRenderer ); QgsRasterRenderer* renderer() const { return mPipe.renderer(); } - /** Set raster resample filter. Takes ownership of the resample filter object*/ + //! Set raster resample filter. Takes ownership of the resample filter object QgsRasterResampleFilter * resampleFilter() const { return mPipe.resampleFilter(); } QgsBrightnessContrastFilter * brightnessFilter() const { return mPipe.brightnessFilter(); } QgsHueSaturationFilter * hueSaturationFilter() const { return mPipe.hueSaturationFilter(); } - /** Get raster pipe */ + //! Get raster pipe QgsRasterPipe * pipe() { return &mPipe; } - /** \brief Accessor that returns the width of the (unclipped) raster */ + //! \brief Accessor that returns the width of the (unclipped) raster int width() const; - /** \brief Accessor that returns the height of the (unclipped) raster */ + //! \brief Accessor that returns the height of the (unclipped) raster int height() const; - /** \brief Get the number of bands in this layer */ + //! \brief Get the number of bands in this layer int bandCount() const; - /** \brief Get the name of a band given its number */ + //! \brief Get the name of a band given its number QString bandName( int theBandNoInt ) const; - /** Returns the data provider */ + //! Returns the data provider QgsRasterDataProvider* dataProvider(); /** Returns the data provider in a const-correct manner @@ -251,7 +251,7 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer */ const QgsRasterDataProvider* dataProvider() const; - /** Synchronises with changes in the datasource */ + //! Synchronises with changes in the datasource virtual void reload() override; /** Return new instance of QgsMapLayerRenderer that will be used for rendering of given context @@ -259,26 +259,26 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer */ virtual QgsMapLayerRenderer* createMapRenderer( QgsRenderContext& rendererContext ) override; - /** \brief This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap */ + //! \brief This is an overloaded version of the draw() function that is called by both draw() and thumbnailAsPixmap void draw( QPainter * theQPainter, QgsRasterViewPort * myRasterViewPort, const QgsMapToPixel* theQgsMapToPixel = nullptr ); - /** Returns a list with classification items (Text and color) */ + //! Returns a list with classification items (Text and color) QgsLegendColorList legendSymbologyItems() const; virtual bool isSpatial() const override { return true; } - /** \brief Obtain GDAL Metadata for this layer */ + //! \brief Obtain GDAL Metadata for this layer QString metadata() const override; - /** \brief Get an 100x100 pixmap of the color palette. If the layer has no palette a white pixmap will be returned */ + //! \brief Get an 100x100 pixmap of the color palette. If the layer has no palette a white pixmap will be returned QPixmap paletteAsPixmap( int theBandNumber = 1 ); - /** \brief [ data provider interface ] Which provider is being used for this Raster Layer? */ + //! \brief [ data provider interface ] Which provider is being used for this Raster Layer? QString providerType() const; - /** \brief Returns the number of raster units per each raster pixel. In a world file, this is normally the first row (without the sign) */ + //! \brief Returns the number of raster units per each raster pixel. In a world file, this is normally the first row (without the sign) double rasterUnitsPerPixelX(); double rasterUnitsPerPixelY(); @@ -296,13 +296,13 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer int theSampleSize = SAMPLE_SIZE, bool theGenerateLookupTableFlag = true ); - /** \brief Set default contrast enhancement */ + //! \brief Set default contrast enhancement void setDefaultContrastEnhancement(); - /** \brief [ data provider interface ] A wrapper function to emit a progress update signal */ + //! \brief [ data provider interface ] A wrapper function to emit a progress update signal void showProgress( int theValue ); - /** \brief Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS */ + //! \brief Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS virtual QStringList subLayers() const override; /** \brief Draws a preview of the rasterlayer into a QImage @@ -323,64 +323,64 @@ class CORE_EXPORT QgsRasterLayer : public QgsMapLayer */ virtual void setSubLayerVisibility( const QString& name, bool vis ) override; - /** Time stamp of data source in the moment when data/metadata were loaded by provider */ + //! Time stamp of data source in the moment when data/metadata were loaded by provider virtual QDateTime timestamp() const override; public slots: void showStatusMessage( const QString & theMessage ); - /** \brief receive progress signal from provider */ + //! \brief receive progress signal from provider void onProgress( int, double, const QString& ); signals: - /** \brief Signal for notifying listeners of long running processes */ + //! \brief Signal for notifying listeners of long running processes void progressUpdate( int theValue ); protected: - /** \brief Read the symbology for the current layer from the Dom node supplied */ + //! \brief Read the symbology for the current layer from the Dom node supplied bool readSymbology( const QDomNode& node, QString& errorMessage ) override; - /** \brief Read the style information for the current layer from the Dom node supplied */ + //! \brief Read the style information for the current layer from the Dom node supplied bool readStyle( const QDomNode &node, QString &errorMessage ) override; - /** \brief Reads layer specific state from project file Dom node */ + //! \brief Reads layer specific state from project file Dom node bool readXml( const QDomNode& layer_node ) override; - /** \brief Write the symbology for the layer into the docment provided */ + //! \brief Write the symbology for the layer into the docment provided bool writeSymbology( QDomNode&, QDomDocument& doc, QString& errorMessage ) const override; - /** \brief Write the style for the layer into the docment provided */ + //! \brief Write the style for the layer into the docment provided bool writeStyle( QDomNode &node, QDomDocument &doc, QString &errorMessage ) const override; - /** \brief Write layer specific state to project file Dom node */ + //! \brief Write layer specific state to project file Dom node bool writeXml( QDomNode & layer_node, QDomDocument & doc ) const override; private: - /** \brief Initialize default values */ + //! \brief Initialize default values void init(); - /** \brief Close data provider and clear related members */ + //! \brief Close data provider and clear related members void closeDataProvider(); - /** \brief Update the layer if it is outdated */ + //! \brief Update the layer if it is outdated bool update(); - /** Sets corresponding renderer for style*/ + //! Sets corresponding renderer for style void setRendererForDrawingStyle( QgsRaster::DrawingStyle theDrawingStyle ); - /** \brief Constant defining flag for XML and a constant that signals property not used */ + //! \brief Constant defining flag for XML and a constant that signals property not used const QString QSTRING_NOT_SET; const QString TRSTRING_NOT_SET; - /** Pointer to data provider */ + //! Pointer to data provider QgsRasterDataProvider* mDataProvider; - /** [ data provider interface ] Timestamp, the last modified time of the data source when the layer was created */ + //! [ data provider interface ] Timestamp, the last modified time of the data source when the layer was created QDateTime mLastModified; QgsRasterViewPort mLastViewPort; - /** [ data provider interface ] Data provider key */ + //! [ data provider interface ] Data provider key QString mProviderKey; LayerType mRasterType; diff --git a/src/core/raster/qgsrasterlayerrenderer.h b/src/core/raster/qgsrasterlayerrenderer.h index 3f992941904c..665280663437 100644 --- a/src/core/raster/qgsrasterlayerrenderer.h +++ b/src/core/raster/qgsrasterlayerrenderer.h @@ -71,9 +71,9 @@ class QgsRasterLayerRenderer : public QgsMapLayerRenderer //! when notified of new data in data provider it launches a preview draw of the raster virtual void onNewData() override; private: - QgsRasterLayerRenderer* mR; //!< parent renderer instance - int mMinimalPreviewInterval; //!< in miliseconds - QTime mLastPreview; //!< when last preview has been generated + QgsRasterLayerRenderer* mR; //!< Parent renderer instance + int mMinimalPreviewInterval; //!< In miliseconds + QTime mLastPreview; //!< When last preview has been generated }; //! feedback class for cancellation and preview generation diff --git a/src/core/raster/qgsrasternuller.h b/src/core/raster/qgsrasternuller.h index cacde254a965..e52f8a6dfc33 100644 --- a/src/core/raster/qgsrasternuller.h +++ b/src/core/raster/qgsrasternuller.h @@ -50,7 +50,7 @@ class CORE_EXPORT QgsRasterNuller : public QgsRasterInterface QgsRasterRangeList noData( int bandNo ) const { return mNoData.value( bandNo -1 ); } - /** \brief Set output no data value. */ + //! \brief Set output no data value. void setOutputNoDataValue( int bandNo, double noData ); private: diff --git a/src/core/raster/qgsrasterpipe.h b/src/core/raster/qgsrasterpipe.h index e9c2937a1ad9..bf695b1baf52 100644 --- a/src/core/raster/qgsrasterpipe.h +++ b/src/core/raster/qgsrasterpipe.h @@ -77,10 +77,10 @@ class CORE_EXPORT QgsRasterPipe */ bool set( QgsRasterInterface * theInterface ); - /** Remove and delete interface at given index if possible */ + //! Remove and delete interface at given index if possible bool remove( int idx ); - /** Remove and delete interface from pipe if possible */ + //! Remove and delete interface from pipe if possible bool remove( QgsRasterInterface * theInterface ); int size() const { return mInterfaces.size(); } @@ -91,7 +91,7 @@ class CORE_EXPORT QgsRasterPipe * Returns true on success */ bool setOn( int idx, bool on ); - /** Test if interface at index may be swithed on/off */ + //! Test if interface at index may be swithed on/off bool canSetOn( int idx, bool on ); // Getters for special types of interfaces @@ -104,7 +104,7 @@ class CORE_EXPORT QgsRasterPipe QgsRasterNuller * nuller() const; private: - /** Get known parent type_info of interface parent */ + //! Get known parent type_info of interface parent Role interfaceRole( QgsRasterInterface * iface ) const; // Interfaces in pipe, the first is always provider @@ -121,7 +121,7 @@ class CORE_EXPORT QgsRasterPipe // Check if index is in bounds bool checkBounds( int idx ) const; - /** Get known interface by role */ + //! Get known interface by role QgsRasterInterface * interface( Role role ) const; /** \brief Try to connect interfaces in pipe and to the provider at beginning. diff --git a/src/core/raster/qgsrasterprojector.h b/src/core/raster/qgsrasterprojector.h index 05b087e9ca98..a4313294dee7 100644 --- a/src/core/raster/qgsrasterprojector.h +++ b/src/core/raster/qgsrasterprojector.h @@ -55,7 +55,7 @@ class CORE_EXPORT QgsRasterProjector : public QgsRasterInterface QgsRasterProjector(); - /** \brief The destructor */ + //! \brief The destructor ~QgsRasterProjector(); QgsRasterProjector *clone() const override; @@ -64,14 +64,14 @@ class CORE_EXPORT QgsRasterProjector : public QgsRasterInterface Qgis::DataType dataType( int bandNo ) const override; - /** \brief set source and destination CRS */ + //! \brief set source and destination CRS void setCrs( const QgsCoordinateReferenceSystem & theSrcCRS, const QgsCoordinateReferenceSystem & theDestCRS, int srcDatumTransform = -1, int destDatumTransform = -1 ); - /** \brief Get source CRS */ + //! \brief Get source CRS QgsCoordinateReferenceSystem sourceCrs() const { return mSrcCRS; } - /** \brief Get destination CRS */ + //! \brief Get destination CRS QgsCoordinateReferenceSystem destinationCrs() const { return mDestCRS; } Precision precision() const { return mPrecision; } @@ -81,30 +81,30 @@ class CORE_EXPORT QgsRasterProjector : public QgsRasterInterface QgsRasterBlock *block( int bandNo, const QgsRectangle & extent, int width, int height, QgsRasterBlockFeedback* feedback = nullptr ) override; - /** Calculate destination extent and size from source extent and size */ + //! Calculate destination extent and size from source extent and size bool destExtentSize( const QgsRectangle& theSrcExtent, int theSrcXSize, int theSrcYSize, QgsRectangle& theDestExtent, int& theDestXSize, int& theDestYSize ); - /** Calculate destination extent and size from source extent and size */ + //! Calculate destination extent and size from source extent and size static bool extentSize( const QgsCoordinateTransform& ct, const QgsRectangle& theSrcExtent, int theSrcXSize, int theSrcYSize, QgsRectangle& theDestExtent, int& theDestXSize, int& theDestYSize ); private: - /** Source CRS */ + //! Source CRS QgsCoordinateReferenceSystem mSrcCRS; - /** Destination CRS */ + //! Destination CRS QgsCoordinateReferenceSystem mDestCRS; - /** Source datum transformation id (or -1 if none) */ + //! Source datum transformation id (or -1 if none) int mSrcDatumTransform; - /** Destination datum transformation id (or -1 if none) */ + //! Destination datum transformation id (or -1 if none) int mDestDatumTransform; - /** Requested precision */ + //! Requested precision Precision mPrecision; }; @@ -119,7 +119,7 @@ class CORE_EXPORT QgsRasterProjector : public QgsRasterInterface class ProjectorData { public: - /** Initialize reprojector and calculate matrix */ + //! Initialize reprojector and calculate matrix ProjectorData( const QgsRectangle &extent, int width, int height, QgsRasterInterface *input, const QgsCoordinateTransform &inverseCt, QgsRasterProjector::Precision precision ); ~ProjectorData(); @@ -137,38 +137,38 @@ class ProjectorData ProjectorData( const ProjectorData& other ); ProjectorData& operator=( const ProjectorData& other ); - /** \brief get destination point for _current_ destination position */ + //! \brief get destination point for _current_ destination position void destPointOnCPMatrix( int theRow, int theCol, double *theX, double *theY ); - /** \brief Get matrix upper left row/col indexes for destination row/col */ + //! \brief Get matrix upper left row/col indexes for destination row/col int matrixRow( int theDestRow ); int matrixCol( int theDestCol ); - /** \brief Get precise source row and column indexes for current source extent and resolution */ + //! \brief Get precise source row and column indexes for current source extent and resolution inline bool preciseSrcRowCol( int theDestRow, int theDestCol, int *theSrcRow, int *theSrcCol ); - /** \brief Get approximate source row and column indexes for current source extent and resolution */ + //! \brief Get approximate source row and column indexes for current source extent and resolution inline bool approximateSrcRowCol( int theDestRow, int theDestCol, int *theSrcRow, int *theSrcCol ); - /** \brief insert rows to matrix */ + //! \brief insert rows to matrix void insertRows( const QgsCoordinateTransform& ct ); - /** \brief insert columns to matrix */ + //! \brief insert columns to matrix void insertCols( const QgsCoordinateTransform& ct ); - /** Calculate single control point in current matrix */ + //! Calculate single control point in current matrix void calcCP( int theRow, int theCol, const QgsCoordinateTransform& ct ); - /** \brief calculate matrix row */ + //! \brief calculate matrix row bool calcRow( int theRow, const QgsCoordinateTransform& ct ); - /** \brief calculate matrix column */ + //! \brief calculate matrix column bool calcCol( int theCol, const QgsCoordinateTransform& ct ); - /** \brief calculate source extent */ + //! \brief calculate source extent void calcSrcExtent(); - /** \brief calculate minimum source width and height */ + //! \brief calculate minimum source width and height void calcSrcRowsCols(); /** \brief check error along columns @@ -179,88 +179,88 @@ class ProjectorData * returns true if within threshold */ bool checkRows( const QgsCoordinateTransform& ct ); - /** Calculate array of src helper points */ + //! Calculate array of src helper points void calcHelper( int theMatrixRow, QgsPoint *thePoints ); - /** Calc / switch helper */ + //! Calc / switch helper void nextHelper(); - /** Get mCPMatrix as string */ + //! Get mCPMatrix as string QString cpToString(); /** Use approximation (requested precision is Approximate and it is possible to calculate * an approximation matrix with a sufficient precision) */ bool mApproximate; - /** Transformation from destination CRS to source CRS */ + //! Transformation from destination CRS to source CRS QgsCoordinateTransform* mInverseCt; - /** Destination extent */ + //! Destination extent QgsRectangle mDestExtent; - /** Source extent */ + //! Source extent QgsRectangle mSrcExtent; - /** Source raster extent */ + //! Source raster extent QgsRectangle mExtent; - /** Number of destination rows */ + //! Number of destination rows int mDestRows; - /** Number of destination columns */ + //! Number of destination columns int mDestCols; - /** Destination x resolution */ + //! Destination x resolution double mDestXRes; - /** Destination y resolution */ + //! Destination y resolution double mDestYRes; - /** Number of source rows */ + //! Number of source rows int mSrcRows; - /** Number of source columns */ + //! Number of source columns int mSrcCols; - /** Source x resolution */ + //! Source x resolution double mSrcXRes; - /** Source y resolution */ + //! Source y resolution double mSrcYRes; - /** Number of destination rows per matrix row */ + //! Number of destination rows per matrix row double mDestRowsPerMatrixRow; - /** Number of destination cols per matrix col */ + //! Number of destination cols per matrix col double mDestColsPerMatrixCol; - /** Grid of source control points */ + //! Grid of source control points QList< QList > mCPMatrix; - /** Grid of source control points transformation possible indicator */ + //! Grid of source control points transformation possible indicator /* Same size as mCPMatrix */ QList< QList > mCPLegalMatrix; - /** Array of source points for each destination column on top of current CPMatrix grid row */ + //! Array of source points for each destination column on top of current CPMatrix grid row /* Warning: using QList is slow on access */ QgsPoint *pHelperTop; - /** Array of source points for each destination column on bottom of current CPMatrix grid row */ + //! Array of source points for each destination column on bottom of current CPMatrix grid row /* Warning: using QList is slow on access */ QgsPoint *pHelperBottom; - /** Current mHelperTop matrix row */ + //! Current mHelperTop matrix row int mHelperTopRow; - /** Number of mCPMatrix columns */ + //! Number of mCPMatrix columns int mCPCols; - /** Number of mCPMatrix rows */ + //! Number of mCPMatrix rows int mCPRows; - /** Maximum tolerance in destination units */ + //! Maximum tolerance in destination units double mSqrTolerance; - /** Maximum source resolution */ + //! Maximum source resolution double mMaxSrcXRes; double mMaxSrcYRes; diff --git a/src/core/raster/qgsrasterpyramid.h b/src/core/raster/qgsrasterpyramid.h index 9021075ca51f..eeacd6a41825 100644 --- a/src/core/raster/qgsrasterpyramid.h +++ b/src/core/raster/qgsrasterpyramid.h @@ -23,15 +23,15 @@ class CORE_EXPORT QgsRasterPyramid { public: - /** \brief The pyramid level as implemented in gdal (level 2 is half orignal raster size etc) */ + //! \brief The pyramid level as implemented in gdal (level 2 is half orignal raster size etc) int level; - /** \brief XDimension for this pyramid layer */ + //! \brief XDimension for this pyramid layer int xDim; - /** \brief YDimension for this pyramid layer */ + //! \brief YDimension for this pyramid layer int yDim; - /** \brief Whether the pyramid layer has been built yet */ + //! \brief Whether the pyramid layer has been built yet bool exists; - /** \brief Whether the pyramid should be built */ + //! \brief Whether the pyramid should be built bool build; QgsRasterPyramid() diff --git a/src/core/raster/qgsrasterrenderer.h b/src/core/raster/qgsrasterrenderer.h index d6ef8b9c8bb5..c32be311932a 100644 --- a/src/core/raster/qgsrasterrenderer.h +++ b/src/core/raster/qgsrasterrenderer.h @@ -81,10 +81,10 @@ class CORE_EXPORT QgsRasterRenderer : public QgsRasterInterface void setAlphaBand( int band ) { mAlphaBand = band; } int alphaBand() const { return mAlphaBand; } - /** Get symbology items if provided by renderer*/ + //! Get symbology items if provided by renderer virtual void legendSymbologyItems( QList< QPair< QString, QColor > >& symbolItems ) const { Q_UNUSED( symbolItems ); } - /** Sets base class members from xml. Usually called from create() methods of subclasses*/ + //! Sets base class members from xml. Usually called from create() methods of subclasses void readXml( const QDomElement& rendererElem ) override; /** Copies common properties like opacity / transparency data from other renderer. @@ -92,7 +92,7 @@ class CORE_EXPORT QgsRasterRenderer : public QgsRasterInterface * @note added in 2.16 */ void copyCommonProperties( const QgsRasterRenderer* other ); - /** Returns a list of band numbers used by the renderer*/ + //! Returns a list of band numbers used by the renderer virtual QList usesBands() const { return QList(); } static QString minMaxOriginName( int theOrigin ); @@ -101,14 +101,14 @@ class CORE_EXPORT QgsRasterRenderer : public QgsRasterInterface protected: - /** Write upper class info into rasterrenderer element (called by writeXml method of subclasses)*/ + //! Write upper class info into rasterrenderer element (called by writeXml method of subclasses) void _writeXml( QDomDocument& doc, QDomElement& rasterRendererElem ) const; QString mType; - /** Global alpha value (0-1)*/ + //! Global alpha value (0-1) double mOpacity; - /** Raster transparency per color or value. Overwrites global alpha value*/ + //! Raster transparency per color or value. Overwrites global alpha value QgsRasterTransparency* mRasterTransparency; /** Read alpha value from band. Is combined with value from raster transparency / global alpha value. Default: -1 (not set)*/ diff --git a/src/core/raster/qgsrasterresamplefilter.h b/src/core/raster/qgsrasterresamplefilter.h index d0b6ca44d930..6020cc95bcd9 100644 --- a/src/core/raster/qgsrasterresamplefilter.h +++ b/src/core/raster/qgsrasterresamplefilter.h @@ -43,11 +43,11 @@ class CORE_EXPORT QgsRasterResampleFilter : public QgsRasterInterface QgsRasterBlock *block( int bandNo, const QgsRectangle &extent, int width, int height, QgsRasterBlockFeedback* feedback = nullptr ) override; - /** Set resampler for zoomed in scales. Takes ownership of the object*/ + //! Set resampler for zoomed in scales. Takes ownership of the object void setZoomedInResampler( QgsRasterResampler* r ); const QgsRasterResampler* zoomedInResampler() const { return mZoomedInResampler; } - /** Set resampler for zoomed out scales. Takes ownership of the object*/ + //! Set resampler for zoomed out scales. Takes ownership of the object void setZoomedOutResampler( QgsRasterResampler* r ); const QgsRasterResampler* zoomedOutResampler() const { return mZoomedOutResampler; } @@ -56,16 +56,16 @@ class CORE_EXPORT QgsRasterResampleFilter : public QgsRasterInterface void writeXml( QDomDocument& doc, QDomElement& parentElem ) const override; - /** Sets base class members from xml. Usually called from create() methods of subclasses*/ + //! Sets base class members from xml. Usually called from create() methods of subclasses void readXml( const QDomElement& filterElem ) override; protected: - /** Resampler used if screen resolution is higher than raster resolution (zoomed in). 0 means no resampling (nearest neighbour)*/ + //! Resampler used if screen resolution is higher than raster resolution (zoomed in). 0 means no resampling (nearest neighbour) QgsRasterResampler* mZoomedInResampler; - /** Resampler used if raster resolution is higher than raster resolution (zoomed out). 0 mean no resampling (nearest neighbour)*/ + //! Resampler used if raster resolution is higher than raster resolution (zoomed out). 0 mean no resampling (nearest neighbour) QgsRasterResampler* mZoomedOutResampler; - /** Maximum boundary for oversampling (to avoid too much data traffic). Default: 2.0*/ + //! Maximum boundary for oversampling (to avoid too much data traffic). Default: 2.0 double mMaxOversampling; private: diff --git a/src/core/raster/qgsrastershader.h b/src/core/raster/qgsrastershader.h index 4d4ee3b40861..e797923a14be 100644 --- a/src/core/raster/qgsrastershader.h +++ b/src/core/raster/qgsrastershader.h @@ -39,10 +39,10 @@ class CORE_EXPORT QgsRasterShader * Non-Static Inline methods * */ - /** \brief Return the maximum value for the raster shader */ + //! \brief Return the maximum value for the raster shader double maximumValue() { return mMaximumValue; } - /** \brief Return the minimum value for the raster shader */ + //! \brief Return the minimum value for the raster shader double minimumValue() { return mMinimumValue; } QgsRasterShaderFunction* rasterShaderFunction() { return mRasterShaderFunction; } @@ -53,20 +53,20 @@ class CORE_EXPORT QgsRasterShader * Non-Static methods * */ - /** \brief generates and new RGBA value based on one input value */ + //! \brief generates and new RGBA value based on one input value bool shade( double, int*, int*, int*, int* ); - /** \brief generates and new RGBA value based on original RGBA value */ + //! \brief generates and new RGBA value based on original RGBA value bool shade( double, double, double, double, int*, int*, int*, int* ); /** \brief A public method that allows the user to set their own shader function \note Raster shader takes ownership of the shader function instance */ void setRasterShaderFunction( QgsRasterShaderFunction* ); - /** \brief Set the maximum value */ + //! \brief Set the maximum value void setMaximumValue( double ); - /** \brief Return the minimum value */ + //! \brief Return the minimum value void setMinimumValue( double ); void writeXml( QDomDocument& doc, QDomElement& parent ) const; @@ -74,13 +74,13 @@ class CORE_EXPORT QgsRasterShader void readXml( const QDomElement& elem ); private: - /** \brief User defineable minimum value for the raster shader */ + //! \brief User defineable minimum value for the raster shader double mMinimumValue; - /** \brief user defineable maximum value for the raster shader */ + //! \brief user defineable maximum value for the raster shader double mMaximumValue; - /** \brief Pointer to the shader function */ + //! \brief Pointer to the shader function QgsRasterShaderFunction* mRasterShaderFunction; QgsRasterShader( const QgsRasterShader& rh ); diff --git a/src/core/raster/qgsrastershaderfunction.h b/src/core/raster/qgsrastershaderfunction.h index e388d4a60b3f..a42896d4361c 100644 --- a/src/core/raster/qgsrastershaderfunction.h +++ b/src/core/raster/qgsrastershaderfunction.h @@ -34,16 +34,16 @@ class CORE_EXPORT QgsRasterShaderFunction QgsRasterShaderFunction( double theMinimumValue = 0.0, double theMaximumValue = 255.0 ); virtual ~QgsRasterShaderFunction() {} - /** \brief Set the maximum value */ + //! \brief Set the maximum value virtual void setMaximumValue( double ); - /** \brief Return the minimum value */ + //! \brief Return the minimum value virtual void setMinimumValue( double ); - /** \brief generates and new RGBA value based on one input value */ + //! \brief generates and new RGBA value based on one input value virtual bool shade( double, int*, int*, int*, int* ); - /** \brief generates and new RGBA value based on original RGBA value */ + //! \brief generates and new RGBA value based on original RGBA value virtual bool shade( double, double, double, double, int*, int*, int*, int* ); double minimumMaximumRange() const { return mMinimumMaximumRange; } @@ -54,13 +54,13 @@ class CORE_EXPORT QgsRasterShaderFunction virtual void legendSymbologyItems( QList< QPair< QString, QColor > >& symbolItems ) const { Q_UNUSED( symbolItems ); } protected: - /** \brief User defineable maximum value for the shading function */ + //! \brief User defineable maximum value for the shading function double mMaximumValue; - /** \brief User defineable minimum value for the shading function */ + //! \brief User defineable minimum value for the shading function double mMinimumValue; - /** \brief Minimum maximum range for the shading function */ + //! \brief Minimum maximum range for the shading function double mMinimumMaximumRange; }; #endif diff --git a/src/core/raster/qgsrastertransparency.h b/src/core/raster/qgsrastertransparency.h index 9aa54fcae453..680e09a5ab7a 100644 --- a/src/core/raster/qgsrastertransparency.h +++ b/src/core/raster/qgsrastertransparency.h @@ -53,31 +53,31 @@ class CORE_EXPORT QgsRasterTransparency // // Initializer, Accessor and mutator for transparency tables. // - /** \brief Accessor for transparentSingleValuePixelList */ + //! \brief Accessor for transparentSingleValuePixelList QList transparentSingleValuePixelList() const; - /** \brief Accessor for transparentThreeValuePixelList */ + //! \brief Accessor for transparentThreeValuePixelList QList transparentThreeValuePixelList() const; - /** \brief Reset to the transparency list to a single value */ + //! \brief Reset to the transparency list to a single value void initializeTransparentPixelList( double ); - /** \brief Reset to the transparency list to a single value */ + //! \brief Reset to the transparency list to a single value void initializeTransparentPixelList( double, double, double ); - /** \brief Mutator for transparentSingleValuePixelList */ + //! \brief Mutator for transparentSingleValuePixelList void setTransparentSingleValuePixelList( const QList& theNewList ); - /** \brief Mutator for transparentThreeValuePixelList */ + //! \brief Mutator for transparentThreeValuePixelList void setTransparentThreeValuePixelList( const QList& theNewList ); - /** \brief Returns the transparency value for a single value Pixel */ + //! \brief Returns the transparency value for a single value Pixel int alphaValue( double, int theGlobalTransparency = 255 ) const; - /** \brief Return the transparency value for a RGB Pixel */ + //! \brief Return the transparency value for a RGB Pixel int alphaValue( double, double, double, int theGlobalTransparency = 255 ) const; - /** True if there are no entries in the pixel lists except the nodata value*/ + //! True if there are no entries in the pixel lists except the nodata value bool isEmpty() const; void writeXml( QDomDocument& doc, QDomElement& parentElem ) const; @@ -85,10 +85,10 @@ class CORE_EXPORT QgsRasterTransparency void readXml( const QDomElement& elem ); private: - /** \brief The list to hold transparency values for RGB layers */ + //! \brief The list to hold transparency values for RGB layers QList mTransparentThreeValuePixelList; - /** \brief The list to hold transparency values for single value pixel layers */ + //! \brief The list to hold transparency values for single value pixel layers QList mTransparentSingleValuePixelList; }; diff --git a/src/core/raster/qgsrasterviewport.h b/src/core/raster/qgsrasterviewport.h index b34e1d7a69c2..cb85baaa6178 100644 --- a/src/core/raster/qgsrasterviewport.h +++ b/src/core/raster/qgsrasterviewport.h @@ -38,20 +38,20 @@ struct QgsRasterViewPort * of the part of the raster that is to be rendered.*/ QgsPoint mBottomRightPoint; - /** \brief Width, number of columns to be rendered */ + //! \brief Width, number of columns to be rendered int mWidth; /** \brief Distance in map units from bottom edge to top edge for the part of * the raster that is to be rendered.*/ - /** \brief Height, number of rows to be rendered */ + //! \brief Height, number of rows to be rendered int mHeight; - /** \brief Intersection of current map extent and layer extent */ + //! \brief Intersection of current map extent and layer extent QgsRectangle mDrawnExtent; - /** \brief Source coordinate system */ + //! \brief Source coordinate system QgsCoordinateReferenceSystem mSrcCRS; - /** \brief Target coordinate system */ + //! \brief Target coordinate system QgsCoordinateReferenceSystem mDestCRS; int mSrcDatumTransform; diff --git a/src/core/raster/qgssinglebandgrayrenderer.h b/src/core/raster/qgssinglebandgrayrenderer.h index 146e369ee52c..3b5d1296d092 100644 --- a/src/core/raster/qgssinglebandgrayrenderer.h +++ b/src/core/raster/qgssinglebandgrayrenderer.h @@ -46,7 +46,7 @@ class CORE_EXPORT QgsSingleBandGrayRenderer: public QgsRasterRenderer int grayBand() const { return mGrayBand; } void setGrayBand( int band ) { mGrayBand = band; } const QgsContrastEnhancement* contrastEnhancement() const { return mContrastEnhancement; } - /** Takes ownership*/ + //! Takes ownership void setContrastEnhancement( QgsContrastEnhancement* ce ); void setGradient( Gradient theGradient ) { mGradient = theGradient; } diff --git a/src/core/raster/qgssinglebandpseudocolorrenderer.h b/src/core/raster/qgssinglebandpseudocolorrenderer.h index 4764ad417ab5..59b64b292880 100644 --- a/src/core/raster/qgssinglebandpseudocolorrenderer.h +++ b/src/core/raster/qgssinglebandpseudocolorrenderer.h @@ -29,7 +29,7 @@ class QgsRasterShader; class CORE_EXPORT QgsSingleBandPseudoColorRenderer: public QgsRasterRenderer { public: - /** Note: takes ownership of QgsRasterShader*/ + //! Note: takes ownership of QgsRasterShader QgsSingleBandPseudoColorRenderer( QgsRasterInterface* input, int band, QgsRasterShader* shader ); ~QgsSingleBandPseudoColorRenderer(); QgsSingleBandPseudoColorRenderer * clone() const override; @@ -38,7 +38,7 @@ class CORE_EXPORT QgsSingleBandPseudoColorRenderer: public QgsRasterRenderer QgsRasterBlock* block( int bandNo, const QgsRectangle & extent, int width, int height, QgsRasterBlockFeedback* feedback = nullptr ) override; - /** Takes ownership of the shader*/ + //! Takes ownership of the shader void setShader( QgsRasterShader* shader ); QgsRasterShader* shader() { return mShader; } //! @note available in python as constShader diff --git a/src/core/symbology-ng/qgsarrowsymbollayer.h b/src/core/symbology-ng/qgsarrowsymbollayer.h index 0ab107f04e3e..3b3beb8b7c45 100644 --- a/src/core/symbology-ng/qgsarrowsymbollayer.h +++ b/src/core/symbology-ng/qgsarrowsymbollayer.h @@ -28,7 +28,7 @@ class CORE_EXPORT QgsArrowSymbolLayer : public QgsLineSymbolLayer { public: - /** Simple constructor */ + //! Simple constructor QgsArrowSymbolLayer(); /** @@ -45,69 +45,69 @@ class CORE_EXPORT QgsArrowSymbolLayer : public QgsLineSymbolLayer virtual bool setSubSymbol( QgsSymbol* symbol ) override; virtual QSet usedAttributes() const override; - /** Get current arrow width */ + //! Get current arrow width double arrowWidth() const { return mArrowWidth; } - /** Set the arrow width */ + //! Set the arrow width void setArrowWidth( double width ) { mArrowWidth = width; } - /** Get the unit for the arrow width */ + //! Get the unit for the arrow width QgsUnitTypes::RenderUnit arrowWidthUnit() const { return mArrowWidthUnit; } - /** Set the unit for the arrow width */ + //! Set the unit for the arrow width void setArrowWidthUnit( QgsUnitTypes::RenderUnit unit ) { mArrowWidthUnit = unit; } - /** Get the scale for the arrow width */ + //! Get the scale for the arrow width QgsMapUnitScale arrowWidthUnitScale() const { return mArrowWidthUnitScale; } - /** Set the scale for the arrow width */ + //! Set the scale for the arrow width void setArrowWidthUnitScale( const QgsMapUnitScale& scale ) { mArrowWidthUnitScale = scale; } - /** Get current arrow start width. Only meaningfull for single headed arrows */ + //! Get current arrow start width. Only meaningfull for single headed arrows double arrowStartWidth() const { return mArrowStartWidth; } - /** Set the arrow start width */ + //! Set the arrow start width void setArrowStartWidth( double width ) { mArrowStartWidth = width; } - /** Get the unit for the arrow start width */ + //! Get the unit for the arrow start width QgsUnitTypes::RenderUnit arrowStartWidthUnit() const { return mArrowStartWidthUnit; } - /** Set the unit for the arrow start width */ + //! Set the unit for the arrow start width void setArrowStartWidthUnit( QgsUnitTypes::RenderUnit unit ) { mArrowStartWidthUnit = unit; } - /** Get the scale for the arrow start width */ + //! Get the scale for the arrow start width QgsMapUnitScale arrowStartWidthUnitScale() const { return mArrowStartWidthUnitScale; } - /** Set the scale for the arrow start width */ + //! Set the scale for the arrow start width void setArrowStartWidthUnitScale( const QgsMapUnitScale& scale ) { mArrowStartWidthUnitScale = scale; } - /** Get the current arrow head length */ + //! Get the current arrow head length double headLength() const { return mHeadLength; } - /** Set the arrow head length */ + //! Set the arrow head length void setHeadLength( double length ) { mHeadLength = length; } - /** Get the unit for the head length */ + //! Get the unit for the head length QgsUnitTypes::RenderUnit headLengthUnit() const { return mHeadLengthUnit; } - /** Set the unit for the head length */ + //! Set the unit for the head length void setHeadLengthUnit( QgsUnitTypes::RenderUnit unit ) { mHeadLengthUnit = unit; } - /** Get the scale for the head length */ + //! Get the scale for the head length QgsMapUnitScale headLengthUnitScale() const { return mHeadLengthUnitScale; } - /** Set the scale for the head length */ + //! Set the scale for the head length void setHeadLengthUnitScale( const QgsMapUnitScale& scale ) { mHeadLengthUnitScale = scale; } - /** Get the current arrow head height */ + //! Get the current arrow head height double headThickness() const { return mHeadThickness; } - /** Set the arrow head height */ + //! Set the arrow head height void setHeadThickness( double thickness ) { mHeadThickness = thickness; } - /** Get the unit for the head height */ + //! Get the unit for the head height QgsUnitTypes::RenderUnit headThicknessUnit() const { return mHeadThicknessUnit; } - /** Set the unit for the head height */ + //! Set the unit for the head height void setHeadThicknessUnit( QgsUnitTypes::RenderUnit unit ) { mHeadThicknessUnit = unit; } - /** Get the scale for the head height */ + //! Get the scale for the head height QgsMapUnitScale headThicknessUnitScale() const { return mHeadThicknessUnitScale; } - /** Set the scale for the head height */ + //! Set the scale for the head height void setHeadThicknessUnitScale( const QgsMapUnitScale& scale ) { mHeadThicknessUnitScale = scale; } - /** Return whether it is a curved arrow or a straight one */ + //! Return whether it is a curved arrow or a straight one bool isCurved() const { return mIsCurved; } - /** Set whether it is a curved arrow or a straight one */ + //! Set whether it is a curved arrow or a straight one void setIsCurved( bool isCurved ) { mIsCurved = isCurved; } - /** Return whether the arrow is repeated along the line or not */ + //! Return whether the arrow is repeated along the line or not bool isRepeated() const { return mIsRepeated; } - /** Set whether the arrow is repeated along the line */ + //! Set whether the arrow is repeated along the line void setIsRepeated( bool isRepeated ) { mIsRepeated = isRepeated; } - /** Possible head types */ + //! Possible head types enum HeadType { HeadSingle, //< One single head at the end @@ -115,12 +115,12 @@ class CORE_EXPORT QgsArrowSymbolLayer : public QgsLineSymbolLayer HeadDouble //< Two heads }; - /** Get the current head type */ + //! Get the current head type HeadType headType() const { return mHeadType; } - /** Set the head type */ + //! Set the head type void setHeadType( HeadType type ) { mHeadType = type; } - /** Possible arrow types */ + //! Possible arrow types enum ArrowType { ArrowPlain, //< Regular arrow @@ -128,9 +128,9 @@ class CORE_EXPORT QgsArrowSymbolLayer : public QgsLineSymbolLayer ArrowRightHalf //< Halved arrow, only the right side of the arrow is rendered (for straight arrows) or the side toward the interior (for curved arrows) }; - /** Get the current arrow type */ + //! Get the current arrow type ArrowType arrowType() const { return mArrowType; } - /** Set the arrow type */ + //! Set the arrow type void setArrowType( ArrowType type ) { mArrowType = type; } QgsStringMap properties() const override; @@ -142,7 +142,7 @@ class CORE_EXPORT QgsArrowSymbolLayer : public QgsLineSymbolLayer virtual QColor color() const override; private: - /** Filling sub symbol */ + //! Filling sub symbol QScopedPointer mSymbol; double mArrowWidth; diff --git a/src/core/symbology-ng/qgscategorizedsymbolrenderer.h b/src/core/symbology-ng/qgscategorizedsymbolrenderer.h index 4921c92bcf6a..5a79df10cb1f 100644 --- a/src/core/symbology-ng/qgscategorizedsymbolrenderer.h +++ b/src/core/symbology-ng/qgscategorizedsymbolrenderer.h @@ -212,7 +212,7 @@ class CORE_EXPORT QgsCategorizedSymbolRenderer : public QgsFeatureRenderer private: - /** Returns calculated classification value for a feature */ + //! Returns calculated classification value for a feature QVariant valueForFeature( QgsFeature& feature, QgsRenderContext &context ) const; }; diff --git a/src/core/symbology-ng/qgscptcityarchive.h b/src/core/symbology-ng/qgscptcityarchive.h index 03c64f98b444..14639e4b49bf 100644 --- a/src/core/symbology-ng/qgscptcityarchive.h +++ b/src/core/symbology-ng/qgscptcityarchive.h @@ -351,13 +351,13 @@ class CORE_EXPORT QgsCptCityBrowserModel : public QAbstractItemModel virtual QModelIndex parent( const QModelIndex &index ) const override; - /** Returns a list of mime that can describe model indexes */ + //! Returns a list of mime that can describe model indexes /* virtual QStringList mimeTypes() const; */ - /** Returns an object that contains serialized items of data corresponding to the list of indexes specified */ + //! Returns an object that contains serialized items of data corresponding to the list of indexes specified /* virtual QMimeData * mimeData( const QModelIndexList &indexes ) const; */ - /** Handles the data supplied by a drag and drop operation that ended with the given action */ + //! Handles the data supplied by a drag and drop operation that ended with the given action /* virtual bool dropMimeData( const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent ); */ QgsCptCityDataItem *dataItem( const QModelIndex &idx ) const; diff --git a/src/core/symbology-ng/qgsfillsymbollayer.h b/src/core/symbology-ng/qgsfillsymbollayer.h index 837a32af3486..1ab62a53512a 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.h +++ b/src/core/symbology-ng/qgsfillsymbollayer.h @@ -221,11 +221,11 @@ class CORE_EXPORT QgsGradientFillSymbolLayer : public QgsFillSymbolLayer double estimateMaxBleed() const override; - /** Type of gradient, eg linear or radial*/ + //! Type of gradient, eg linear or radial GradientType gradientType() const { return mGradientType; } void setGradientType( GradientType gradientType ) { mGradientType = gradientType; } - /** Gradient color mode, controls how gradient color stops are created*/ + //! Gradient color mode, controls how gradient color stops are created GradientColorType gradientColorType() const { return mGradientColorType; } void setGradientColorType( GradientColorType gradientColorType ) { mGradientColorType = gradientColorType; } @@ -244,39 +244,39 @@ class CORE_EXPORT QgsGradientFillSymbolLayer : public QgsFillSymbolLayer */ void setColorRamp( QgsColorRamp* ramp ); - /** Color for endpoint of gradient, only used if the gradient color type is set to SimpleTwoColor*/ + //! Color for endpoint of gradient, only used if the gradient color type is set to SimpleTwoColor QColor color2() const { return mColor2; } void setColor2( const QColor& color2 ) { mColor2 = color2; } - /** Coordinate mode for gradient. Controls how the gradient stops are positioned.*/ + //! Coordinate mode for gradient. Controls how the gradient stops are positioned. GradientCoordinateMode coordinateMode() const { return mCoordinateMode; } void setCoordinateMode( GradientCoordinateMode coordinateMode ) { mCoordinateMode = coordinateMode; } - /** Gradient spread mode. Controls how the gradient behaves outside of the predefined stops*/ + //! Gradient spread mode. Controls how the gradient behaves outside of the predefined stops GradientSpread gradientSpread() const { return mGradientSpread; } void setGradientSpread( GradientSpread gradientSpread ) { mGradientSpread = gradientSpread; } - /** Starting point of gradient fill, in the range [0,0] - [1,1]*/ + //! Starting point of gradient fill, in the range [0,0] - [1,1] void setReferencePoint1( QPointF referencePoint ) { mReferencePoint1 = referencePoint; } QPointF referencePoint1() const { return mReferencePoint1; } - /** Sets the starting point of the gradient to be the feature centroid*/ + //! Sets the starting point of the gradient to be the feature centroid void setReferencePoint1IsCentroid( bool isCentroid ) { mReferencePoint1IsCentroid = isCentroid; } bool referencePoint1IsCentroid() const { return mReferencePoint1IsCentroid; } - /** End point of gradient fill, in the range [0,0] - [1,1]*/ + //! End point of gradient fill, in the range [0,0] - [1,1] void setReferencePoint2( QPointF referencePoint ) { mReferencePoint2 = referencePoint; } QPointF referencePoint2() const { return mReferencePoint2; } - /** Sets the end point of the gradient to be the feature centroid*/ + //! Sets the end point of the gradient to be the feature centroid void setReferencePoint2IsCentroid( bool isCentroid ) { mReferencePoint2IsCentroid = isCentroid; } bool referencePoint2IsCentroid() const { return mReferencePoint2IsCentroid; } - /** Offset for gradient fill*/ + //! Offset for gradient fill void setOffset( QPointF offset ) { mOffset = offset; } QPointF offset() const { return mOffset; } - /** Units for gradient fill offset*/ + //! Units for gradient fill offset void setOffsetUnit( QgsUnitTypes::RenderUnit unit ) { mOffsetUnit = unit; } QgsUnitTypes::RenderUnit offsetUnit() const { return mOffsetUnit; } @@ -314,13 +314,13 @@ class CORE_EXPORT QgsGradientFillSymbolLayer : public QgsFillSymbolLayer //helper functions for data defined symbology void applyDataDefinedSymbology( QgsSymbolRenderContext& context, const QPolygonF& points ); - /** Applies the gradient to a brush*/ + //! Applies the gradient to a brush void applyGradient( const QgsSymbolRenderContext& context, QBrush& brush, const QColor& color, const QColor& color2, GradientColorType gradientColorType, QgsColorRamp *gradientRamp, GradientType gradientType, GradientCoordinateMode coordinateMode, GradientSpread gradientSpread, QPointF referencePoint1, QPointF referencePoint2, const double angle ); - /** Rotates a reference point by a specified angle around the point (0.5, 0.5)*/ + //! Rotates a reference point by a specified angle around the point (0.5, 0.5) QPointF rotateReferencePoint( QPointF refPoint, double angle ); }; @@ -616,12 +616,12 @@ class CORE_EXPORT QgsImageFillSymbolLayer: public QgsFillSymbolLayer QBrush mBrush; double mNextAngle; // mAngle / data defined angle - /** Outline width*/ + //! Outline width double mOutlineWidth; QgsUnitTypes::RenderUnit mOutlineWidthUnit; QgsMapUnitScale mOutlineWidthMapUnitScale; - /** Custom outline*/ + //! Custom outline QgsLineSymbol* mOutline; virtual void applyDataDefinedSettings( QgsSymbolRenderContext& context ) { Q_UNUSED( context ); } @@ -789,7 +789,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer protected: - /** Path to the image file*/ + //! Path to the image file QString mImageFilePath; FillCoordinateMode mCoordinateMode; double mAlpha; @@ -806,7 +806,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer private: - /** Applies the image pattern to the brush*/ + //! Applies the image pattern to the brush void applyPattern( QBrush& brush, const QString& imageFilePath, const double width, const double alpha, const QgsSymbolRenderContext& context ); }; @@ -886,18 +886,18 @@ class CORE_EXPORT QgsSVGFillSymbolLayer: public QgsImageFillSymbolLayer QgsMapUnitScale mapUnitScale() const override; protected: - /** Width of the pattern (in output units)*/ + //! Width of the pattern (in output units) double mPatternWidth; QgsUnitTypes::RenderUnit mPatternWidthUnit; QgsMapUnitScale mPatternWidthMapUnitScale; - /** SVG data*/ + //! SVG data QByteArray mSvgData; - /** Path to the svg file (or empty if constructed directly from data)*/ + //! Path to the svg file (or empty if constructed directly from data) QString mSvgFilePath; - /** SVG view box (to keep the aspect ratio */ + //! SVG view box (to keep the aspect ratio QRectF mSvgViewBox; - /** SVG pattern image */ + //! SVG pattern image QImage* mSvgPattern; //param(fill), param(outline), param(outline-width) are going @@ -910,11 +910,11 @@ class CORE_EXPORT QgsSVGFillSymbolLayer: public QgsImageFillSymbolLayer void applyDataDefinedSettings( QgsSymbolRenderContext& context ) override; private: - /** Helper function that gets the view box from the byte array*/ + //! Helper function that gets the view box from the byte array void storeViewBox(); void setDefaultSvgParams(); //fills mSvgFillColor, mSvgOutlineColor, mSvgOutlineWidth with default values for mSvgFilePath - /** Applies the svg pattern to the brush*/ + //! Applies the svg pattern to the brush void applyPattern( QBrush& brush, const QString& svgFilePath, double patternWidth, QgsUnitTypes::RenderUnit patternWidthUnit, const QColor& svgFillColor, const QColor& svgOutlineColor, double svgOutlineWidth, QgsUnitTypes::RenderUnit svgOutlineWidthUnit, const QgsSymbolRenderContext& context, const QgsMapUnitScale& patternWidthMapUnitScale, const QgsMapUnitScale &svgOutlineWidthMapUnitScale ); }; @@ -1027,18 +1027,18 @@ class CORE_EXPORT QgsLinePatternFillSymbolLayer: public QgsImageFillSymbolLayer QSet usedAttributes() const override; protected: - /** Distance (in mm or map units) between lines*/ + //! Distance (in mm or map units) between lines double mDistance; QgsUnitTypes::RenderUnit mDistanceUnit; QgsMapUnitScale mDistanceMapUnitScale; - /** Line width (in mm or map units)*/ + //! Line width (in mm or map units) double mLineWidth; QgsUnitTypes::RenderUnit mLineWidthUnit; QgsMapUnitScale mLineWidthMapUnitScale; QColor mColor; - /** Vector line angle in degrees (0 = horizontal, counterclockwise)*/ + //! Vector line angle in degrees (0 = horizontal, counterclockwise) double mLineAngle; - /** Offset perpendicular to line direction*/ + //! Offset perpendicular to line direction double mOffset; QgsUnitTypes::RenderUnit mOffsetUnit; QgsMapUnitScale mOffsetMapUnitScale; @@ -1046,10 +1046,10 @@ class CORE_EXPORT QgsLinePatternFillSymbolLayer: public QgsImageFillSymbolLayer void applyDataDefinedSettings( QgsSymbolRenderContext& context ) override; private: - /** Applies the svg pattern to the brush*/ + //! Applies the svg pattern to the brush void applyPattern( const QgsSymbolRenderContext& context, QBrush& brush, double lineAngle, double distance, double lineWidth, const QColor& color ); - /** Fill line*/ + //! Fill line QgsLineSymbol* mFillLineSymbol; }; diff --git a/src/core/symbology-ng/qgsheatmaprenderer.h b/src/core/symbology-ng/qgsheatmaprenderer.h index 70cea65df7dd..0f80d7e442f9 100644 --- a/src/core/symbology-ng/qgsheatmaprenderer.h +++ b/src/core/symbology-ng/qgsheatmaprenderer.h @@ -166,9 +166,9 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer void setWeightExpression( const QString& expression ) { mWeightExpressionString = expression; } private: - /** Private copy constructor. @see clone() */ + //! Private copy constructor. @see clone() QgsHeatmapRenderer( const QgsHeatmapRenderer& ); - /** Private assignment operator. @see clone() */ + //! Private assignment operator. @see clone() QgsHeatmapRenderer& operator=( const QgsHeatmapRenderer& ); QVector mValues; diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h index a7e510acff2e..0c5b152274c0 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h @@ -70,9 +70,9 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer virtual QString dump() const override; - /** Proxy that will call this method on the embedded renderer. */ + //! Proxy that will call this method on the embedded renderer. virtual QSet usedAttributes() const override; - /** Proxy that will call this method on the embedded renderer. */ + //! Proxy that will call this method on the embedded renderer. virtual Capabilities capabilities() override; /** Proxy that will call this method on the embedded renderer. */ @@ -89,7 +89,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer /** Proxy that will call this method on the embedded renderer. */ virtual QgsSymbolList originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; - /** Proxy that will call this method on the embedded renderer. */ + //! Proxy that will call this method on the embedded renderer. virtual QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ) override; /** Proxy that will call this method on the embedded renderer. * @note not available in python bindings @@ -99,7 +99,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer */ virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; - /** Creates a renderer out of an XML, for loading*/ + //! Creates a renderer out of an XML, for loading static QgsFeatureRenderer* create( QDomElement& element ); virtual QDomElement save( QDomDocument& doc ) override; @@ -113,7 +113,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer virtual bool legendSymbolItemChecked( const QString& key ) override; virtual void checkLegendSymbolItem( const QString& key, bool state = true ) override; - /** @returns true if the geometries are to be preprocessed (merged with an union) before rendering.*/ + //! @returns true if the geometries are to be preprocessed (merged with an union) before rendering. bool preprocessingEnabled() const { return mPreprocessingEnabled; } /** * @param enabled enables or disables the preprocessing. @@ -130,34 +130,34 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer static QgsInvertedPolygonRenderer* convertFromRenderer( const QgsFeatureRenderer* renderer ); private: - /** Private copy constructor. @see clone() */ + //! Private copy constructor. @see clone() QgsInvertedPolygonRenderer( const QgsInvertedPolygonRenderer& ); - /** Private assignment operator. @see clone() */ + //! Private assignment operator. @see clone() QgsInvertedPolygonRenderer& operator=( const QgsInvertedPolygonRenderer& ); - /** Embedded renderer */ + //! Embedded renderer QScopedPointer mSubRenderer; - /** Structure where the reversed geometry is built during renderFeature */ + //! Structure where the reversed geometry is built during renderFeature struct CombinedFeature { QList geometries; //< list of geometries QgsFeature feature; //< one feature (for attriute-based rendering) }; typedef QVector FeatureCategoryVector; - /** Where features are stored, based on the index of their symbol category @see mSymbolCategories */ + //! Where features are stored, based on the index of their symbol category @see mSymbolCategories FeatureCategoryVector mFeaturesCategories; - /** Maps a category to an index */ + //! Maps a category to an index QMap mSymbolCategories; - /** The polygon used as exterior ring that covers the current extent */ + //! The polygon used as exterior ring that covers the current extent QgsPolygon mExtentPolygon; - /** The context used for rendering */ + //! The context used for rendering QgsRenderContext mContext; - /** Fields of each feature*/ + //! Fields of each feature QgsFields mFields; /** Class used to represent features that must be rendered @@ -178,7 +178,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer }; QList mFeatureDecorations; - /** Whether to preprocess (merge) geometries before rendering*/ + //! Whether to preprocess (merge) geometries before rendering bool mPreprocessingEnabled; }; diff --git a/src/core/symbology-ng/qgslinesymbollayer.h b/src/core/symbology-ng/qgslinesymbollayer.h index 690a73c45417..75f708916bd1 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.h +++ b/src/core/symbology-ng/qgslinesymbollayer.h @@ -128,7 +128,7 @@ class CORE_EXPORT QgsSimpleLineSymbolLayer : public QgsLineSymbolLayer QgsUnitTypes::RenderUnit mCustomDashPatternUnit; QgsMapUnitScale mCustomDashPatternMapUnitScale; - /** Vector with an even number of entries for the */ + //! Vector with an even number of entries for the QVector mCustomDashVector; bool mDrawInsidePolygon; diff --git a/src/core/symbology-ng/qgsmarkersymbollayer.h b/src/core/symbology-ng/qgsmarkersymbollayer.h index 97bab79f6f67..8cd79819f6b7 100644 --- a/src/core/symbology-ng/qgsmarkersymbollayer.h +++ b/src/core/symbology-ng/qgsmarkersymbollayer.h @@ -44,29 +44,29 @@ class CORE_EXPORT QgsSimpleMarkerSymbolLayerBase : public QgsMarkerSymbolLayer //! Marker symbol shapes enum Shape { - Square, /*!< Square */ - Diamond, /*!< Diamond */ - Pentagon, /*!< Pentagon */ - Hexagon, /*!< Hexagon */ - Triangle, /*!< Triangle */ - EquilateralTriangle, /*!< Equilateral triangle*/ - Star, /*!< Star*/ - Arrow, /*!< Arrow*/ - Circle, /*!< Circle*/ - Cross, /*!< Cross (lines only)*/ - CrossFill, /*!< Solid filled cross*/ - Cross2, /*!< Rotated cross (lines only), "x" shape*/ - Line, /*!< Vertical line*/ - ArrowHead, /*!< Right facing arrow head (unfilled, lines only)*/ - ArrowHeadFilled, /*!< Right facing filled arrow head*/ - SemiCircle, /*!< Semi circle (top half)*/ - ThirdCircle, /*!< One third circle (top left third)*/ - QuarterCircle, /*!< Quarter circle (top left quarter)*/ - QuarterSquare, /*!< Quarter square (top left quarter)*/ - HalfSquare, /*!< Half square (left half)*/ - DiagonalHalfSquare, /*!< Diagonal half square (bottom left half)*/ - RightHalfTriangle, /*!< Right half of triangle*/ - LeftHalfTriangle, /*!< Left half of triangle*/ + Square, //!< Square + Diamond, //!< Diamond + Pentagon, //!< Pentagon + Hexagon, //!< Hexagon + Triangle, //!< Triangle + EquilateralTriangle, //!< Equilateral triangle + Star, //!< Star + Arrow, //!< Arrow + Circle, //!< Circle + Cross, //!< Cross (lines only) + CrossFill, //!< Solid filled cross + Cross2, //!< Rotated cross (lines only), "x" shape + Line, //!< Vertical line + ArrowHead, //!< Right facing arrow head (unfilled, lines only) + ArrowHeadFilled, //!< Right facing filled arrow head + SemiCircle, //!< Semi circle (top half) + ThirdCircle, //!< One third circle (top left third) + QuarterCircle, //!< Quarter circle (top left quarter) + QuarterSquare, //!< Quarter square (top left quarter) + HalfSquare, //!< Half square (left half) + DiagonalHalfSquare, //!< Diagonal half square (bottom left half) + RightHalfTriangle, //!< Right half of triangle + LeftHalfTriangle, //!< Left half of triangle }; //! Returns a list of all available shape types. diff --git a/src/core/symbology-ng/qgspointdisplacementrenderer.h b/src/core/symbology-ng/qgspointdisplacementrenderer.h index 8a1e5cfade76..eef22c2b1a4f 100644 --- a/src/core/symbology-ng/qgspointdisplacementrenderer.h +++ b/src/core/symbology-ng/qgspointdisplacementrenderer.h @@ -32,8 +32,8 @@ class CORE_EXPORT QgsPointDisplacementRenderer: public QgsPointDistanceRenderer */ enum Placement { - Ring, /*!< Place points in a single ring around group*/ - ConcentricRings /*!< Place points in concentric rings around group*/ + Ring, //!< Place points in a single ring around group + ConcentricRings //!< Place points in concentric rings around group }; /** Constructor for QgsPointDisplacementRenderer. diff --git a/src/core/symbology-ng/qgsrenderer.h b/src/core/symbology-ng/qgsrenderer.h index 2aa547305c6f..881ff8324cc5 100644 --- a/src/core/symbology-ng/qgsrenderer.h +++ b/src/core/symbology-ng/qgsrenderer.h @@ -186,10 +186,10 @@ class CORE_EXPORT QgsFeatureRenderer */ enum Capability { - SymbolLevels = 1, //!< rendering with symbol levels (i.e. implements symbols(), symbolForFeature()) - MoreSymbolsPerFeature = 1 << 2, //!< may use more than one symbol to render a feature: symbolsForFeature() will return them - Filter = 1 << 3, //!< features may be filtered, i.e. some features may not be rendered (categorized, rule based ...) - ScaleDependent = 1 << 4 //!< depends on scale if feature will be rendered (rule based ) + SymbolLevels = 1, //!< Rendering with symbol levels (i.e. implements symbols(), symbolForFeature()) + MoreSymbolsPerFeature = 1 << 2, //!< May use more than one symbol to render a feature: symbolsForFeature() will return them + Filter = 1 << 3, //!< Features may be filtered, i.e. some features may not be rendered (categorized, rule based ...) + ScaleDependent = 1 << 4 //!< Depends on scale if feature will be rendered (rule based ) }; Q_DECLARE_FLAGS( Capabilities, Capability ) @@ -426,9 +426,9 @@ class CORE_EXPORT QgsFeatureRenderer bool mUsingSymbolLevels; - /** The current type of editing marker */ + //! The current type of editing marker int mCurrentVertexMarkerType; - /** The current size of editing marker */ + //! The current size of editing marker int mCurrentVertexMarkerSize; QgsPaintEffect* mPaintEffect; diff --git a/src/core/symbology-ng/qgsrendererregistry.h b/src/core/symbology-ng/qgsrendererregistry.h index d34c0f11e886..4ba5e1990676 100644 --- a/src/core/symbology-ng/qgsrendererregistry.h +++ b/src/core/symbology-ng/qgsrendererregistry.h @@ -106,7 +106,7 @@ class CORE_EXPORT QgsRendererMetadata : public QgsRendererAbstractMetadata { public: - /** Construct metadata */ + //! Construct metadata //! @note not available in python bindings QgsRendererMetadata( const QString& name, const QString& visibleName, diff --git a/src/core/symbology-ng/qgssvgcache.h b/src/core/symbology-ng/qgssvgcache.h index d5c518819568..2bfddeba4370 100644 --- a/src/core/symbology-ng/qgssvgcache.h +++ b/src/core/symbology-ng/qgssvgcache.h @@ -76,9 +76,9 @@ class CORE_EXPORT QgsSvgCacheEntry QgsSvgCacheEntry* nextEntry; QgsSvgCacheEntry* previousEntry; - /** Don't consider image, picture, last used timestamp for comparison*/ + //! Don't consider image, picture, last used timestamp for comparison bool operator==( const QgsSvgCacheEntry& other ) const; - /** Return memory usage in bytes*/ + //! Return memory usage in bytes int dataSize() const; private: @@ -172,15 +172,15 @@ class CORE_EXPORT QgsSvgCache : public QObject bool& hasOutlineWidthParam, bool& hasDefaultOutlineWidth, double& defaultOutlineWidth, bool& hasOutlineOpacityParam, bool& hasDefaultOutlineOpacity, double& defaultOutlineOpacity ) const; - /** Get image data*/ + //! Get image data QByteArray getImageData( const QString &path ) const; - /** Get SVG content*/ + //! Get SVG content const QByteArray& svgContent( const QString& file, double size, const QColor& fill, const QColor& outline, double outlineWidth, double widthScaleFactor, double rasterScaleFactor ); signals: - /** Emit a signal to be caught by qgisapp and display a msg on status bar */ + //! Emit a signal to be caught by qgisapp and display a msg on status bar void statusChanged( const QString& theStatusQString ); protected: @@ -203,11 +203,11 @@ class CORE_EXPORT QgsSvgCache : public QObject void replaceParamsAndCacheSvg( QgsSvgCacheEntry* entry ); void cacheImage( QgsSvgCacheEntry* entry ); void cachePicture( QgsSvgCacheEntry* entry, bool forceVectorOutput = false ); - /** Returns entry from cache or creates a new entry if it does not exist already*/ + //! Returns entry from cache or creates a new entry if it does not exist already QgsSvgCacheEntry* cacheEntry( const QString& file, double size, const QColor& fill, const QColor& outline, double outlineWidth, double widthScaleFactor, double rasterScaleFactor ); - /** Removes the least used items until the maximum size is under the limit*/ + //! Removes the least used items until the maximum size is under the limit void trimToMaximumSize(); //Removes entry from the ordered list (but does not delete the entry itself) @@ -217,9 +217,9 @@ class CORE_EXPORT QgsSvgCache : public QObject void downloadProgress( qint64, qint64 ); private: - /** Entry pointers accessible by file name*/ + //! Entry pointers accessible by file name QMultiHash< QString, QgsSvgCacheEntry* > mEntryLookup; - /** Estimated total size of all images, pictures and svgContent*/ + //! Estimated total size of all images, pictures and svgContent long mTotalSize; //The svg cache keeps the entries on a double connected list, moving the current entry to the front. @@ -230,7 +230,7 @@ class CORE_EXPORT QgsSvgCache : public QObject //Maximum cache size static const long mMaximumSize = 20000000; - /** Replaces parameters in elements of a dom node and calls method for all child nodes*/ + //! Replaces parameters in elements of a dom node and calls method for all child nodes void replaceElemParams( QDomElement& elem, const QColor& fill, const QColor& outline, double outlineWidth ); void containsElemParams( const QDomElement& elem, @@ -240,16 +240,16 @@ class CORE_EXPORT QgsSvgCache : public QObject bool& hasOutlineWidthParam, bool& hasDefaultOutlineWidth, double& defaultOutlineWidth, bool& hasOutlineOpacityParam, bool& hasDefaultOutlineOpacity, double& defaultOutlineOpacity ) const; - /** Calculates scaling for rendered image sizes to SVG logical sizes*/ + //! Calculates scaling for rendered image sizes to SVG logical sizes double calcSizeScaleFactor( QgsSvgCacheEntry* entry, const QDomElement& docElem, QSizeF& viewboxSize ) const; - /** Release memory and remove cache entry from mEntryLookup*/ + //! Release memory and remove cache entry from mEntryLookup void removeCacheEntry( const QString& s, QgsSvgCacheEntry* entry ); - /** For debugging*/ + //! For debugging void printEntryList(); - /** SVG content to be rendered if SVG file was not found. */ + //! SVG content to be rendered if SVG file was not found. QByteArray mMissingSvg; //! Mutex to prevent concurrent access to the class from multiple threads at once (may corrupt the entries otherwise). diff --git a/src/core/symbology-ng/qgssymbol.h b/src/core/symbology-ng/qgssymbol.h index eebca22f909d..b5c7e0f4204f 100644 --- a/src/core/symbology-ng/qgssymbol.h +++ b/src/core/symbology-ng/qgssymbol.h @@ -350,7 +350,7 @@ class CORE_EXPORT QgsSymbol SymbolType mType; QgsSymbolLayerList mLayers; - /** Symbol opacity (in the range 0 - 1)*/ + //! Symbol opacity (in the range 0 - 1) qreal mAlpha; RenderHints mRenderHints; @@ -707,9 +707,9 @@ class CORE_EXPORT QgsFillSymbol : public QgsSymbol private: void renderPolygonUsingLayer( QgsSymbolLayer* layer, const QPolygonF &points, QList *rings, QgsSymbolRenderContext &context ); - /** Calculates the bounds of a polygon including rings*/ + //! Calculates the bounds of a polygon including rings QRectF polygonBounds( const QPolygonF &points, const QList *rings ) const; - /** Translates the rings in a polygon by a set distance*/ + //! Translates the rings in a polygon by a set distance QList* translateRings( const QList *rings, double dx, double dy ) const; }; diff --git a/src/core/symbology-ng/qgssymbollayer.h b/src/core/symbology-ng/qgssymbollayer.h index 963d3f8393c4..fd2693e1a886 100644 --- a/src/core/symbology-ng/qgssymbollayer.h +++ b/src/core/symbology-ng/qgssymbollayer.h @@ -406,17 +406,17 @@ class CORE_EXPORT QgsMarkerSymbolLayer : public QgsSymbolLayer //! Symbol horizontal anchor points enum HorizontalAnchorPoint { - Left, /*!< Align to left side of symbol */ - HCenter, /*!< Align to horizontal center of symbol */ - Right, /*!< Align to right side of symbol */ + Left, //!< Align to left side of symbol + HCenter, //!< Align to horizontal center of symbol + Right, //!< Align to right side of symbol }; //! Symbol vertical anchor points enum VerticalAnchorPoint { - Top, /*!< Align to top of symbol */ - VCenter, /*!< Align to vertical center of symbol */ - Bottom, /*!< Align to bottom of symbol */ + Top, //!< Align to top of symbol + VCenter, //!< Align to vertical center of symbol + Bottom, //!< Align to bottom of symbol }; void startRender( QgsSymbolRenderContext& context ) override; @@ -754,7 +754,7 @@ class CORE_EXPORT QgsFillSymbolLayer : public QgsSymbolLayer protected: QgsFillSymbolLayer( bool locked = false ); - /** Default method to render polygon*/ + //! Default method to render polygon void _renderPolygon( QPainter* p, const QPolygonF& points, const QList* rings, QgsSymbolRenderContext& context ); double mAngle; diff --git a/src/core/symbology-ng/qgssymbollayerregistry.h b/src/core/symbology-ng/qgssymbollayerregistry.h index 3d11884da324..42ee998dd5fc 100644 --- a/src/core/symbology-ng/qgssymbollayerregistry.h +++ b/src/core/symbology-ng/qgssymbollayerregistry.h @@ -42,11 +42,11 @@ class CORE_EXPORT QgsSymbolLayerAbstractMetadata QString visibleName() const { return mVisibleName; } QgsSymbol::SymbolType type() const { return mType; } - /** Create a symbol layer of this type given the map of properties. */ + //! Create a symbol layer of this type given the map of properties. virtual QgsSymbolLayer* createSymbolLayer( const QgsStringMap& map ) = 0; - /** Create widget for symbol layer of this type. Can return NULL if there's no GUI */ + //! Create widget for symbol layer of this type. Can return NULL if there's no GUI virtual QgsSymbolLayerWidget* createSymbolLayerWidget( const QgsVectorLayer * ) { return nullptr; } - /** Create a symbol layer of this type given the map of properties. */ + //! Create a symbol layer of this type given the map of properties. virtual QgsSymbolLayer* createSymbolLayerFromSld( QDomElement & ) { return nullptr; } diff --git a/src/core/symbology-ng/qgssymbollayerutils.h b/src/core/symbology-ng/qgssymbollayerutils.h index e3e81448c0c2..743c02d4c0b8 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.h +++ b/src/core/symbology-ng/qgssymbollayerutils.h @@ -180,7 +180,7 @@ class CORE_EXPORT QgsSymbolLayerUtils //! @note customContext parameter added in 2.6 static QPixmap symbolPreviewPixmap( QgsSymbol* symbol, QSize size, QgsRenderContext* customContext = nullptr ); - /** Returns the maximum estimated bleed for the symbol */ + //! Returns the maximum estimated bleed for the symbol static double estimateMaxSymbolBleed( QgsSymbol* symbol ); /** Attempts to load a symbol from a DOM element @@ -281,7 +281,7 @@ class CORE_EXPORT QgsSymbolLayerUtils static void labelTextToSld( QDomDocument &doc, QDomElement &element, const QString& label, const QFont &font, const QColor& color = QColor(), double size = -1 ); - /** Create ogr feature style string for pen */ + //! Create ogr feature style string for pen static QString ogrFeatureStylePen( double width, double mmScaleFactor, double mapUnitsScaleFactor, const QColor& c, Qt::PenJoinStyle joinStyle = Qt::MiterJoin, Qt::PenCapStyle capStyle = Qt::FlatCap, @@ -485,19 +485,19 @@ class CORE_EXPORT QgsSymbolLayerUtils */ static double convertFromMapUnits( const QgsRenderContext& context, double sizeInMapUnits, QgsUnitTypes::RenderUnit outputUnit ); - /** Returns scale factor painter units -> pixel dimensions*/ + //! Returns scale factor painter units -> pixel dimensions static double pixelSizeScaleFactor( const QgsRenderContext& c, QgsUnitTypes::RenderUnit u, const QgsMapUnitScale& scale = QgsMapUnitScale() ); - /** Returns scale factor painter units -> map units*/ + //! Returns scale factor painter units -> map units static double mapUnitScaleFactor( const QgsRenderContext& c, QgsUnitTypes::RenderUnit u, const QgsMapUnitScale& scale = QgsMapUnitScale() ); - /** Creates a render context for a pixel based device*/ + //! Creates a render context for a pixel based device static QgsRenderContext createRenderContext( QPainter* p ); - /** Multiplies opacity of image pixel values with a (global) transparency value*/ + //! Multiplies opacity of image pixel values with a (global) transparency value static void multiplyImageOpacity( QImage* image, qreal alpha ); - /** Blurs an image in place, e.g. creating Qt-independent drop shadows */ + //! Blurs an image in place, e.g. creating Qt-independent drop shadows static void blurImageInPlace( QImage& image, QRect rect, int radius, bool alphaOnly ); /** Converts a QColor into a premultiplied ARGB QColor value using a specified alpha value @@ -505,9 +505,9 @@ class CORE_EXPORT QgsSymbolLayerUtils */ static void premultiplyColor( QColor& rgb, int alpha ); - /** Sorts the passed list in requested order*/ + //! Sorts the passed list in requested order static void sortVariantList( QList& list, Qt::SortOrder order ); - /** Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point*/ + //! Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point static QPointF pointOnLineWithDistance( QPointF startPoint, QPointF directionPoint, double distance ); //! Return a list of all available svg files diff --git a/src/core/symbology-ng/qgssymbologyconversion.h b/src/core/symbology-ng/qgssymbologyconversion.h index 7831b66be9d3..39a3bdf2b3fc 100644 --- a/src/core/symbology-ng/qgssymbologyconversion.h +++ b/src/core/symbology-ng/qgssymbologyconversion.h @@ -29,7 +29,7 @@ class CORE_EXPORT QgsSymbologyConversion { public: - /** Read old renderer definition from XML and create matching new renderer */ + //! Read old renderer definition from XML and create matching new renderer static QgsFeatureRenderer* readOldRenderer( const QDomNode& layerNode, QgsWkbTypes::GeometryType geomType ); static QString penStyle2QString( Qt::PenStyle penstyle ); diff --git a/src/gui/attributetable/qgsattributetablefiltermodel.h b/src/gui/attributetable/qgsattributetablefiltermodel.h index 5b4d4a3e9b81..37ff2886afb7 100644 --- a/src/gui/attributetable/qgsattributetablefiltermodel.h +++ b/src/gui/attributetable/qgsattributetablefiltermodel.h @@ -194,7 +194,7 @@ class GUI_EXPORT QgsAttributeTableFilterModel: public QSortFilterProxyModel, pub */ QString sortExpression() const; - /** Returns the map canvas*/ + //! Returns the map canvas QgsMapCanvas* mapCanvas() const { return mCanvas; } virtual QVariant data( const QModelIndex& index, int role ) const override; diff --git a/src/gui/attributetable/qgsattributetablemodel.h b/src/gui/attributetable/qgsattributetablemodel.h index 7296318b61b4..ed2b16f89e73 100644 --- a/src/gui/attributetable/qgsattributetablemodel.h +++ b/src/gui/attributetable/qgsattributetablemodel.h @@ -347,12 +347,12 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel QgsFeatureRequest mFeatureRequest; - /** The currently cached column */ + //! The currently cached column QgsExpression mSortCacheExpression; QgsAttributeList mSortCacheAttributes; - /** If it is set, a simple field is used for sorting, if it's -1 it's the mSortCacheExpression*/ + //! If it is set, a simple field is used for sorting, if it's -1 it's the mSortCacheExpression int mSortFieldIndex; - /** Allows caching of one value per column (used for sorting) */ + //! Allows caching of one value per column (used for sorting) QHash mSortCache; /** diff --git a/src/gui/attributetable/qgsdualview.h b/src/gui/attributetable/qgsdualview.h index 588d1eb99643..d4090a9b7dc1 100644 --- a/src/gui/attributetable/qgsdualview.h +++ b/src/gui/attributetable/qgsdualview.h @@ -312,9 +312,9 @@ class GUI_EXPORT QgsDualView : public QStackedWidget, private Ui::QgsDualViewBas */ virtual void finished(); - /** Zooms to the active feature*/ + //! Zooms to the active feature void zoomToCurrentFeature(); - /** Pans to the active feature*/ + //! Pans to the active feature void panToCurrentFeature(); private: diff --git a/src/gui/attributetable/qgsfeaturelistview.h b/src/gui/attributetable/qgsfeaturelistview.h index bf74a03e8870..d344e90f5926 100644 --- a/src/gui/attributetable/qgsfeaturelistview.h +++ b/src/gui/attributetable/qgsfeaturelistview.h @@ -179,7 +179,7 @@ class GUI_EXPORT QgsFeatureListView : public QListView QgsFeatureSelectionModel* mFeatureSelectionModel; QgsIFeatureSelectionManager* mFeatureSelectionManager; QgsFeatureListViewDelegate* mItemDelegate; - bool mEditSelectionDrag; // Is set to true when the user initiated a left button click over an edit button and still keeps pressing /**< TODO */ + bool mEditSelectionDrag; // Is set to true when the user initiated a left button click over an edit button and still keeps pressing //!< TODO int mRowAnchor; QItemSelectionModel::SelectionFlags mCtrlDragSelectionFlag; }; diff --git a/src/gui/auth/qgsauthauthoritieseditor.h b/src/gui/auth/qgsauthauthoritieseditor.h index 465a3dbb7d4e..135ffad8edc4 100644 --- a/src/gui/auth/qgsauthauthoritieseditor.h +++ b/src/gui/auth/qgsauthauthoritieseditor.h @@ -50,10 +50,10 @@ class GUI_EXPORT QgsAuthAuthoritiesEditor : public QWidget, private Ui::QgsAuthA void showCertInfo( QTreeWidgetItem *item ); - /** Pass selection change on to UI update */ + //! Pass selection change on to UI update void selectionChanged( const QItemSelection& selected, const QItemSelection& deselected ); - /** Update UI based upon current selection */ + //! Update UI based upon current selection void checkSelection(); void handleDoubleClick( QTreeWidgetItem* item, int col ); @@ -76,11 +76,11 @@ class GUI_EXPORT QgsAuthAuthoritiesEditor : public QWidget, private Ui::QgsAuthA void showTrustedCertificateAuthorities(); - /** Relay messages to widget's messagebar */ + //! Relay messages to widget's messagebar void authMessageOut( const QString& message, const QString& authtag, QgsAuthManager::MessageLevel level ); protected: - /** Overridden show event of base widget */ + //! Overridden show event of base widget void showEvent( QShowEvent *e ) override; private: diff --git a/src/gui/auth/qgsauthcertificateinfo.h b/src/gui/auth/qgsauthcertificateinfo.h index 9b725db62d10..9b41540c435a 100644 --- a/src/gui/auth/qgsauthcertificateinfo.h +++ b/src/gui/auth/qgsauthcertificateinfo.h @@ -155,7 +155,7 @@ class GUI_EXPORT QgsAuthCertInfoDialog : public QDialog const QList& connectionCAs = QList() ); ~QgsAuthCertInfoDialog(); - /** Get access to embedded info widget */ + //! Get access to embedded info widget QgsAuthCertInfo *certInfoWidget() { return mCertInfoWdgt; } /** Whether the trust cache has been rebuilt diff --git a/src/gui/auth/qgsauthcertificatemanager.h b/src/gui/auth/qgsauthcertificatemanager.h index 55b5994be0d5..c38e7a66d718 100644 --- a/src/gui/auth/qgsauthcertificatemanager.h +++ b/src/gui/auth/qgsauthcertificatemanager.h @@ -59,7 +59,7 @@ class GUI_EXPORT QgsAuthCertManager : public QDialog ~QgsAuthCertManager(); - /** Get access to embedded editors widget */ + //! Get access to embedded editors widget QgsAuthCertEditors *certEditorsWidget() { return mCertEditors; } private: diff --git a/src/gui/auth/qgsauthcerttrustpolicycombobox.h b/src/gui/auth/qgsauthcerttrustpolicycombobox.h index ff64c344328f..620bda319191 100644 --- a/src/gui/auth/qgsauthcerttrustpolicycombobox.h +++ b/src/gui/auth/qgsauthcerttrustpolicycombobox.h @@ -40,17 +40,17 @@ class GUI_EXPORT QgsAuthCertTrustPolicyComboBox : public QComboBox QgsAuthCertUtils::CertTrustPolicy defaultpolicy = QgsAuthCertUtils::DefaultTrust ); ~QgsAuthCertTrustPolicyComboBox(); - /** Get currently set trust policy */ + //! Get currently set trust policy QgsAuthCertUtils::CertTrustPolicy trustPolicy(); - /** Get trust policy for a given index of combobox */ + //! Get trust policy for a given index of combobox QgsAuthCertUtils::CertTrustPolicy trustPolicyForIndex( int indx ); public slots: - /** Set current trust policy */ + //! Set current trust policy void setTrustPolicy( QgsAuthCertUtils::CertTrustPolicy policy ); - /** Set default trust policy */ + //! Set default trust policy void setDefaultTrustPolicy( QgsAuthCertUtils::CertTrustPolicy defaultpolicy ); private slots: diff --git a/src/gui/auth/qgsauthconfigedit.h b/src/gui/auth/qgsauthconfigedit.h index d5de322f63ca..958d451c93dd 100644 --- a/src/gui/auth/qgsauthconfigedit.h +++ b/src/gui/auth/qgsauthconfigedit.h @@ -34,7 +34,7 @@ class GUI_EXPORT QgsAuthConfigEdit : public QDialog, private Ui::QgsAuthConfigEd Q_OBJECT public: - /** Type of configuration validity */ + //! Type of configuration validity enum Validity { Valid, @@ -52,14 +52,14 @@ class GUI_EXPORT QgsAuthConfigEdit : public QDialog, private Ui::QgsAuthConfigEd const QString &dataprovider = QString() ); ~QgsAuthConfigEdit(); - /** Authentication config id, updated with generated id when a new config is saved to auth database */ + //! Authentication config id, updated with generated id when a new config is saved to auth database const QString configId() const { return mAuthCfg; } signals: - /** Emit generated id when a new config is saved to auth database */ + //! Emit generated id when a new config is saved to auth database void authenticationConfigStored( const QString& authcfg ); - /** Emit current id when an existing config is updated in auth database */ + //! Emit current id when an existing config is updated in auth database void authenticationConfigUpdated( const QString& authcfg ); private slots: diff --git a/src/gui/auth/qgsauthconfigeditor.h b/src/gui/auth/qgsauthconfigeditor.h index c10510685c7d..370c36b36ae8 100644 --- a/src/gui/auth/qgsauthconfigeditor.h +++ b/src/gui/auth/qgsauthconfigeditor.h @@ -42,45 +42,45 @@ class GUI_EXPORT QgsAuthConfigEditor : public QWidget, private Ui::QgsAuthConfig explicit QgsAuthConfigEditor( QWidget *parent = nullptr, bool showUtilities = true, bool relayMessages = true ); ~QgsAuthConfigEditor(); - /** Hide the widget's title, e.g. when embedding */ + //! Hide the widget's title, e.g. when embedding void toggleTitleVisibility( bool visible ); public slots: - /** Set whether to show the widget's utilities button, e.g. when embedding */ + //! Set whether to show the widget's utilities button, e.g. when embedding void setShowUtilitiesButton( bool show = true ); - /** Set whether to relay auth manager messages to internal message bar, e.g. when embedding */ + //! Set whether to relay auth manager messages to internal message bar, e.g. when embedding void setRelayMessages( bool relay = true ); private slots: - /** Repopulate the view with table contents */ + //! Repopulate the view with table contents void refreshTableView(); - /** Sets the cached master password (and verifies it if its hash is in authentication database) */ + //! Sets the cached master password (and verifies it if its hash is in authentication database) void setMasterPassword(); - /** Clear the currently cached master password (not its hash in database) */ + //! Clear the currently cached master password (not its hash in database) void clearCachedMasterPassword(); - /** Reset the cached master password, updating its hash in authentication database and reseting all existing configs to use it */ + //! Reset the cached master password, updating its hash in authentication database and reseting all existing configs to use it void resetMasterPassword(); - /** Clear all cached authentication configs for session */ + //! Clear all cached authentication configs for session void clearCachedAuthenticationConfigs(); - /** Remove all authentication configs */ + //! Remove all authentication configs void removeAuthenticationConfigs(); - /** Completely clear out the authentication database (configs and master password) */ + //! Completely clear out the authentication database (configs and master password) void eraseAuthenticationDatabase(); - /** Relay messages to widget's messagebar */ + //! Relay messages to widget's messagebar void authMessageOut( const QString& message, const QString& authtag, QgsAuthManager::MessageLevel level ); - /** Pass selection change on to UI update */ + //! Pass selection change on to UI update void selectionChanged( const QItemSelection& selected, const QItemSelection& deselected ); - /** Update UI based upon current selection */ + //! Update UI based upon current selection void checkSelection(); void on_btnAddConfig_clicked(); diff --git a/src/gui/auth/qgsauthconfigidedit.h b/src/gui/auth/qgsauthconfigidedit.h index 5ef6ed28e927..32241d378018 100644 --- a/src/gui/auth/qgsauthconfigidedit.h +++ b/src/gui/auth/qgsauthconfigidedit.h @@ -40,27 +40,27 @@ class GUI_EXPORT QgsAuthConfigIdEdit : public QWidget, private Ui::QgsAuthConfig explicit QgsAuthConfigIdEdit( QWidget *parent = nullptr, const QString &authcfg = QString(), bool allowEmpty = true ); ~QgsAuthConfigIdEdit(); - /** The authentication configuration ID, if valid, otherwise null QString */ + //! The authentication configuration ID, if valid, otherwise null QString QString const configId(); - /** Whether to allow no ID to be set */ + //! Whether to allow no ID to be set bool allowEmptyId() { return mAllowEmpty;} - /** Validate the widget state and ID */ + //! Validate the widget state and ID bool validate(); signals: - /** Validity of the ID has changed */ + //! Validity of the ID has changed void validityChanged( bool valid ); public slots: - /** Set the authentication configuration ID, storing it, and validating the passed value */ + //! Set the authentication configuration ID, storing it, and validating the passed value void setAuthConfigId( const QString &authcfg ); - /** Set whether to allow no ID to be set */ + //! Set whether to allow no ID to be set void setAllowEmptyId( bool allowed ); - /** Clear all of the widget's editing state and contents */ + //! Clear all of the widget's editing state and contents void clear(); private slots: diff --git a/src/gui/auth/qgsauthconfigselect.h b/src/gui/auth/qgsauthconfigselect.h index f51197d37903..736266b59afa 100644 --- a/src/gui/auth/qgsauthconfigselect.h +++ b/src/gui/auth/qgsauthconfigselect.h @@ -40,27 +40,27 @@ class GUI_EXPORT QgsAuthConfigSelect : public QWidget, private Ui::QgsAuthConfig explicit QgsAuthConfigSelect( QWidget *parent = nullptr, const QString &dataprovider = QString() ); ~QgsAuthConfigSelect(); - /** Set the authentication config id for the resource */ + //! Set the authentication config id for the resource void setConfigId( const QString& authcfg ); - /** Get the authentication config id for the resource */ + //! Get the authentication config id for the resource const QString configId() const { return mAuthCfg; } - /** Set key of layer provider, if applicable */ + //! Set key of layer provider, if applicable void setDataProviderKey( const QString &key ); signals: - /** Emitted when authentication config is changed or missing */ + //! Emitted when authentication config is changed or missing void selectedConfigIdChanged( const QString& authcfg ); - /** Emitted when authentication config is removed */ + //! Emitted when authentication config is removed void selectedConfigIdRemoved( const QString& authcfg ); public slots: - /** Show a small message bar with a close button */ + //! Show a small message bar with a close button void showMessage( const QString &msg ); - /** Clear and hide small message bar */ + //! Clear and hide small message bar void clearMessage(); private slots: @@ -117,13 +117,13 @@ class GUI_EXPORT QgsAuthConfigUriEdit : public QDialog, private Ui::QgsAuthConfi const QString &dataprovider = QString() ); ~QgsAuthConfigUriEdit(); - /** Set the data source URI to parse */ + //! Set the data source URI to parse void setDataSourceUri( const QString &datauri ); - /** The returned, possibly edited data source URI */ + //! The returned, possibly edited data source URI QString dataSourceUri(); - /** Whether a string contains an authcfg ID */ + //! Whether a string contains an authcfg ID static bool hasConfigId( const QString &txt ); private slots: diff --git a/src/gui/auth/qgsautheditorwidgets.h b/src/gui/auth/qgsautheditorwidgets.h index 4fe1dd551556..7b993a9b90a5 100644 --- a/src/gui/auth/qgsautheditorwidgets.h +++ b/src/gui/auth/qgsautheditorwidgets.h @@ -68,25 +68,25 @@ class GUI_EXPORT QgsAuthEditorWidgets : public QWidget, private Ui::QgsAuthEdito void on_btnCertManager_clicked(); void on_btnAuthPlugins_clicked(); - /** Sets the cached master password (and verifies it if its hash is in authentication database) */ + //! Sets the cached master password (and verifies it if its hash is in authentication database) void setMasterPassword(); - /** Clear the currently cached master password (not its hash in database) */ + //! Clear the currently cached master password (not its hash in database) void clearCachedMasterPassword(); - /** Reset the cached master password, updating its hash in authentication database and reseting all existing configs to use it */ + //! Reset the cached master password, updating its hash in authentication database and reseting all existing configs to use it void resetMasterPassword(); - /** Clear all cached authentication configs for session */ + //! Clear all cached authentication configs for session void clearCachedAuthenticationConfigs(); - /** Remove all authentication configs */ + //! Remove all authentication configs void removeAuthenticationConfigs(); - /** Completely clear out the authentication database (configs and master password) */ + //! Completely clear out the authentication database (configs and master password) void eraseAuthenticationDatabase(); - /** Relay messages to widget's messagebar */ + //! Relay messages to widget's messagebar void authMessageOut( const QString& message, const QString& authtag, QgsAuthManager::MessageLevel level ); private: diff --git a/src/gui/auth/qgsauthguiutils.h b/src/gui/auth/qgsauthguiutils.h index 3ec09b6485d3..94c2c7d55e09 100644 --- a/src/gui/auth/qgsauthguiutils.h +++ b/src/gui/auth/qgsauthguiutils.h @@ -31,53 +31,53 @@ class GUI_EXPORT QgsAuthGuiUtils { public: - /** Green color representing valid, trusted, etc. certificate */ + //! Green color representing valid, trusted, etc. certificate static QColor greenColor(); - /** Orange color representing loaded component, but not stored in database */ + //! Orange color representing loaded component, but not stored in database static QColor orangeColor(); - /** Red color representing invalid, untrusted, etc. certificate */ + //! Red color representing invalid, untrusted, etc. certificate static QColor redColor(); - /** Yellow color representing caution regarding action */ + //! Yellow color representing caution regarding action static QColor yellowColor(); - /** Green text stylesheet representing valid, trusted, etc. certificate */ + //! Green text stylesheet representing valid, trusted, etc. certificate static QString greenTextStyleSheet( const QString& selector = "*" ); - /** Orange text stylesheet representing loaded component, but not stored in database */ + //! Orange text stylesheet representing loaded component, but not stored in database static QString orangeTextStyleSheet( const QString& selector = "*" ); - /** Red text stylesheet representing invalid, untrusted, etc. certificate */ + //! Red text stylesheet representing invalid, untrusted, etc. certificate static QString redTextStyleSheet( const QString& selector = "*" ); - /** Verify the authentication system is active, else notify user */ + //! Verify the authentication system is active, else notify user static bool isDisabled( QgsMessageBar *msgbar, int timeout = 0 ); - /** Sets the cached master password (and verifies it if its hash is in authentication database) */ + //! Sets the cached master password (and verifies it if its hash is in authentication database) static void setMasterPassword( QgsMessageBar *msgbar, int timeout = 0 ); - /** Clear the currently cached master password (not its hash in database) */ + //! Clear the currently cached master password (not its hash in database) static void clearCachedMasterPassword( QgsMessageBar *msgbar, int timeout = 0 ); - /** Reset the cached master password, updating its hash in authentication database and reseting all existing configs to use it */ + //! Reset the cached master password, updating its hash in authentication database and reseting all existing configs to use it static void resetMasterPassword( QgsMessageBar *msgbar, int timeout = 0, QWidget *parent = nullptr ); - /** Clear all cached authentication configs for session */ + //! Clear all cached authentication configs for session static void clearCachedAuthenticationConfigs( QgsMessageBar *msgbar, int timeout = 0 ); - /** Remove all authentication configs */ + //! Remove all authentication configs static void removeAuthenticationConfigs( QgsMessageBar *msgbar, int timeout = 0, QWidget *parent = nullptr ); - /** Completely clear out the authentication database (configs and master password) */ + //! Completely clear out the authentication database (configs and master password) static void eraseAuthenticationDatabase( QgsMessageBar *msgbar, int timeout = 0, QWidget *parent = nullptr ); - /** Color a widget via a stylesheet if a file path is found or not */ + //! Color a widget via a stylesheet if a file path is found or not static void fileFound( bool found, QWidget * widget ); - /** Open file dialog for auth associated widgets */ + //! Open file dialog for auth associated widgets static QString getOpenFileName( QWidget *parent, const QString& title, const QString& extfilter ); }; diff --git a/src/gui/auth/qgsauthidentitieseditor.h b/src/gui/auth/qgsauthidentitieseditor.h index 3ed92095859f..e710df9b16d3 100644 --- a/src/gui/auth/qgsauthidentitieseditor.h +++ b/src/gui/auth/qgsauthidentitieseditor.h @@ -47,10 +47,10 @@ class GUI_EXPORT QgsAuthIdentitiesEditor : public QWidget, private Ui::QgsAuthId void showCertInfo( QTreeWidgetItem *item ); - /** Pass selection change on to UI update */ + //! Pass selection change on to UI update void selectionChanged( const QItemSelection& selected, const QItemSelection& deselected ); - /** Update UI based upon current selection */ + //! Update UI based upon current selection void checkSelection(); void handleDoubleClick( QTreeWidgetItem* item, int col ); @@ -63,11 +63,11 @@ class GUI_EXPORT QgsAuthIdentitiesEditor : public QWidget, private Ui::QgsAuthId void on_btnGroupByOrg_toggled( bool checked ); - /** Relay messages to widget's messagebar */ + //! Relay messages to widget's messagebar void authMessageOut( const QString& message, const QString& authtag, QgsAuthManager::MessageLevel level ); protected: - /** Overridden show event of base widget */ + //! Overridden show event of base widget void showEvent( QShowEvent *e ) override; private: diff --git a/src/gui/auth/qgsauthimportcertdialog.h b/src/gui/auth/qgsauthimportcertdialog.h index c8de1c186f50..7ebd603d7acd 100644 --- a/src/gui/auth/qgsauthimportcertdialog.h +++ b/src/gui/auth/qgsauthimportcertdialog.h @@ -32,14 +32,14 @@ class GUI_EXPORT QgsAuthImportCertDialog : public QDialog, private Ui::QgsAuthIm Q_OBJECT public: - /** Type of filter to apply to dialog */ + //! Type of filter to apply to dialog enum CertFilter { NoFilter = 1, CaFilter = 2, }; - /** Type of inputs for certificates */ + //! Type of inputs for certificates enum CertInput { AllInputs = 1, @@ -58,19 +58,19 @@ class GUI_EXPORT QgsAuthImportCertDialog : public QDialog, private Ui::QgsAuthIm QgsAuthImportCertDialog::CertInput input = AllInputs ); ~QgsAuthImportCertDialog(); - /** Get list of certificate objects to import */ + //! Get list of certificate objects to import const QList certificatesToImport(); - /** Get the file path to a certificate to import */ + //! Get the file path to a certificate to import const QString certFileToImport(); - /** Get certificate text to import */ + //! Get certificate text to import const QString certTextToImport(); - /** Whether to allow importation of invalid certificates (so trust policy can be overridden) */ + //! Whether to allow importation of invalid certificates (so trust policy can be overridden) bool allowInvalidCerts(); - /** Defined trust policy for imported certificates */ + //! Defined trust policy for imported certificates QgsAuthCertUtils::CertTrustPolicy certTrustPolicy(); private slots: diff --git a/src/gui/auth/qgsauthimportidentitydialog.h b/src/gui/auth/qgsauthimportidentitydialog.h index 9199c2f54a6b..5ea363cac45f 100644 --- a/src/gui/auth/qgsauthimportidentitydialog.h +++ b/src/gui/auth/qgsauthimportidentitydialog.h @@ -33,20 +33,20 @@ class GUI_EXPORT QgsAuthImportIdentityDialog : public QDialog, private Ui::QgsAu Q_OBJECT public: - /** Type of identity being imported */ + //! Type of identity being imported enum IdentityType { CertIdentity = 0, }; - /** Type of bundles supported */ + //! Type of bundles supported enum BundleTypes { PkiPaths = 0, PkiPkcs12 = 1, }; - /** Type of certificate/bundle validity output */ + //! Type of certificate/bundle validity output enum Validity { Valid, @@ -63,7 +63,7 @@ class GUI_EXPORT QgsAuthImportIdentityDialog : public QDialog, private Ui::QgsAu QWidget *parent = nullptr ); ~QgsAuthImportIdentityDialog(); - /** Get identity type */ + //! Get identity type QgsAuthImportIdentityDialog::IdentityType identityType(); /** Get certificate/key bundle to be imported. @@ -71,7 +71,7 @@ class GUI_EXPORT QgsAuthImportIdentityDialog : public QDialog, private Ui::QgsAu */ const QPair certBundleToImport(); - /** Get certificate/key bundle to be imported as a PKI bundle object */ + //! Get certificate/key bundle to be imported as a PKI bundle object const QgsPkiBundle pkiBundleToImport() { return mPkiBundle; } private slots: diff --git a/src/gui/auth/qgsauthmethodedit.h b/src/gui/auth/qgsauthmethodedit.h index 73e6d764b0b6..22a0523ec610 100644 --- a/src/gui/auth/qgsauthmethodedit.h +++ b/src/gui/auth/qgsauthmethodedit.h @@ -29,14 +29,14 @@ class GUI_EXPORT QgsAuthMethodEdit : public QWidget Q_OBJECT public: - /** Validate the configuration of subclasses */ + //! Validate the configuration of subclasses virtual bool validateConfig() = 0; - /** The configuration key-vale map of subclasses */ + //! The configuration key-vale map of subclasses virtual QgsStringMap configMap() const = 0; signals: - /** Emitted when the configuration validatity changes */ + //! Emitted when the configuration validatity changes void validityChanged( bool valid ); public slots: @@ -46,10 +46,10 @@ class GUI_EXPORT QgsAuthMethodEdit : public QWidget */ virtual void loadConfig( const QgsStringMap &configmap ) = 0; - /** Clear GUI controls in subclassed widget, optionally reloading any previously loaded config map */ + //! Clear GUI controls in subclassed widget, optionally reloading any previously loaded config map virtual void resetConfig() = 0; - /** Clear GUI controls in subclassed widget */ + //! Clear GUI controls in subclassed widget virtual void clearConfig() = 0; protected: diff --git a/src/gui/auth/qgsauthserverseditor.h b/src/gui/auth/qgsauthserverseditor.h index ed4dc6f1efd0..1c410644f5eb 100644 --- a/src/gui/auth/qgsauthserverseditor.h +++ b/src/gui/auth/qgsauthserverseditor.h @@ -44,10 +44,10 @@ class GUI_EXPORT QgsAuthServersEditor : public QWidget, private Ui::QgsAuthServe void refreshSslConfigsView(); - /** Pass selection change on to UI update */ + //! Pass selection change on to UI update void selectionChanged( const QItemSelection& selected, const QItemSelection& deselected ); - /** Update UI based upon current selection */ + //! Update UI based upon current selection void checkSelection(); void handleDoubleClick( QTreeWidgetItem* item, int col ); @@ -60,11 +60,11 @@ class GUI_EXPORT QgsAuthServersEditor : public QWidget, private Ui::QgsAuthServe void on_btnGroupByOrg_toggled( bool checked ); - /** Relay messages to widget's messagebar */ + //! Relay messages to widget's messagebar void authMessageOut( const QString& message, const QString& authtag, QgsAuthManager::MessageLevel level ); protected: - /** Overridden show event of base widget */ + //! Overridden show event of base widget void showEvent( QShowEvent *e ) override; private: diff --git a/src/gui/auth/qgsauthsslconfigwidget.h b/src/gui/auth/qgsauthsslconfigwidget.h index a287263c278e..2f5a70016118 100644 --- a/src/gui/auth/qgsauthsslconfigwidget.h +++ b/src/gui/auth/qgsauthsslconfigwidget.h @@ -51,27 +51,27 @@ class GUI_EXPORT QgsAuthSslConfigWidget : public QWidget, private Ui::QgsAuthSsl const QList& connectionCAs = QList() ); ~QgsAuthSslConfigWidget(); - /** Access to the certificate's group box widget */ + //! Access to the certificate's group box widget QGroupBox *certificateGroupBox(); - /** Access to the SSL configuration's group box widget */ + //! Access to the SSL configuration's group box widget QGroupBox *sslConfigGroupBox(); - /** Get the SSL configuration */ + //! Get the SSL configuration const QgsAuthConfigSslServer sslCustomConfig(); - /** Get the SSL server certificate */ + //! Get the SSL server certificate const QSslCertificate sslCertificate(); - /** Get the host:port to associate with the server certificate */ + //! Get the host:port to associate with the server certificate const QString sslHost(); - /** Get the SSL protocl used for connections */ + //! Get the SSL protocl used for connections QSsl::SslProtocol sslProtocol(); - /** Get list of the SSL errors (as enums) to be ignored for connections */ + //! Get list of the SSL errors (as enums) to be ignored for connections const QList sslIgnoreErrorEnums(); - /** Get the client's peer verify mode for connections */ + //! Get the client's peer verify mode for connections QSslSocket::PeerVerifyMode sslPeerVerifyMode(); /** Get the client's peer verify depth for connections @@ -80,69 +80,69 @@ class GUI_EXPORT QgsAuthSslConfigWidget : public QWidget, private Ui::QgsAuthSsl int sslPeerVerifyDepth(); public slots: - /** Enable or disable the custom options widget */ + //! Enable or disable the custom options widget void enableSslCustomOptions( bool enable ); // may also load existing config, if found - /** Set SSl certificate and any associated host:port */ + //! Set SSl certificate and any associated host:port void setSslCertificate( const QSslCertificate& cert, const QString &hostport = QString() ); - /** Load an existing SSL server configuration */ + //! Load an existing SSL server configuration void loadSslCustomConfig( const QgsAuthConfigSslServer& config = QgsAuthConfigSslServer() ); - /** Save the current SSL server configuration to the authentication database */ + //! Save the current SSL server configuration to the authentication database void saveSslCertConfig(); - /** Clear the current SSL server configuration and disabled it */ + //! Clear the current SSL server configuration and disabled it void resetSslCertConfig(); - /** Set the SSL protocol to use in connections */ + //! Set the SSL protocol to use in connections void setSslProtocol( QSsl::SslProtocol protocol ); - /** Reset the SSL protocol to use in connections to the default */ + //! Reset the SSL protocol to use in connections to the default void resetSslProtocol(); - /** Add to SSL errors to ignore for the connection */ + //! Add to SSL errors to ignore for the connection void appendSslIgnoreErrors( const QList& errors ); - /** Set the SSL errors (as enums) to ignore for the connection */ + //! Set the SSL errors (as enums) to ignore for the connection void setSslIgnoreErrorEnums( const QList& errorenums ); - /** Set the SSL errors to ignore for the connection */ + //! Set the SSL errors to ignore for the connection void setSslIgnoreErrors( const QList& errors ); - /** Clear the SSL errors to ignore for the connection */ + //! Clear the SSL errors to ignore for the connection void resetSslIgnoreErrors(); - /** Set the client's peer verify mode for connections */ + //! Set the client's peer verify mode for connections void setSslPeerVerify( QSslSocket::PeerVerifyMode mode, int modedepth ); - /** Reset the client's peer verify mode for connections to default */ + //! Reset the client's peer verify mode for connections to default void resetSslPeerVerify(); - /** Set the host of the server */ + //! Set the host of the server void setSslHost( const QString& host ); - /** Set whether the config group box is checkable */ + //! Set whether the config group box is checkable void setConfigCheckable( bool checkable ); - /** Parse string for host:port */ + //! Parse string for host:port void validateHostPortText( const QString &txt ); - /** Verify if the configuration if ready to save */ + //! Verify if the configuration if ready to save bool readyToSave(); signals: - /** Emitted when the enabled state of the configuration changes */ + //! Emitted when the enabled state of the configuration changes void configEnabledChanged( bool enabled ); - /** Emitted when an certificate of same SHA hash is found in authentication database */ + //! Emitted when an certificate of same SHA hash is found in authentication database void certFoundInAuthDatabase( bool found ); - /** Emitted when the validity of the host:port changes */ + //! Emitted when the validity of the host:port changes void hostPortValidityChanged( bool valid ); - /** Emitted when the configuration can be saved changes */ + //! Emitted when the configuration can be saved changes void readyToSaveChanged( bool cansave ); private slots: @@ -199,11 +199,11 @@ class GUI_EXPORT QgsAuthSslConfigDialog : public QDialog const QString &hostport = QString() ); ~QgsAuthSslConfigDialog(); - /** Access the embedded SSL server configuration widget */ + //! Access the embedded SSL server configuration widget QgsAuthSslConfigWidget *sslCustomConfigWidget() { return mSslConfigWdgt; } public slots: - /** Overridden base dialog accept slot */ + //! Overridden base dialog accept slot void accept() override; private slots: diff --git a/src/gui/auth/qgsauthsslimportdialog.h b/src/gui/auth/qgsauthsslimportdialog.h index 5f0f5c453d63..0d27f3f41705 100644 --- a/src/gui/auth/qgsauthsslimportdialog.h +++ b/src/gui/auth/qgsauthsslimportdialog.h @@ -88,7 +88,7 @@ class GUI_EXPORT QgsAuthSslImportDialog : public QDialog, private Ui::QgsAuthSsl ~QgsAuthSslImportDialog(); public slots: - /** Overridden slot of base dialog */ + //! Overridden slot of base dialog void accept() override; private slots: diff --git a/src/gui/auth/qgsauthtrustedcasdialog.h b/src/gui/auth/qgsauthtrustedcasdialog.h index 89ceef1f0634..a83e79fcc4e6 100644 --- a/src/gui/auth/qgsauthtrustedcasdialog.h +++ b/src/gui/auth/qgsauthtrustedcasdialog.h @@ -48,10 +48,10 @@ class GUI_EXPORT QgsAuthTrustedCAsDialog : public QDialog, private Ui::QgsAuthTr void showCertInfo( QTreeWidgetItem *item ); - /** Pass selection change on to UI update */ + //! Pass selection change on to UI update void selectionChanged( const QItemSelection& selected, const QItemSelection& deselected ); - /** Update UI based upon current selection */ + //! Update UI based upon current selection void checkSelection(); void handleDoubleClick( QTreeWidgetItem* item, int col ); @@ -60,11 +60,11 @@ class GUI_EXPORT QgsAuthTrustedCAsDialog : public QDialog, private Ui::QgsAuthTr void on_btnGroupByOrg_toggled( bool checked ); - /** Relay messages to widget's messagebar */ + //! Relay messages to widget's messagebar void authMessageOut( const QString& message, const QString& authtag, QgsAuthManager::MessageLevel level ); protected: - /** Overridden widget show event */ + //! Overridden widget show event void showEvent( QShowEvent *e ) override; private: diff --git a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h index 42e5e7f1cca1..5751734e81d9 100644 --- a/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgssearchwidgetwrapper.h @@ -46,19 +46,19 @@ class GUI_EXPORT QgsSearchWidgetWrapper : public QgsWidgetWrapper //! @note added in QGIS 2.16 enum FilterFlag { - EqualTo = 1 << 1, /*!< Supports equal to */ - NotEqualTo = 1 << 2, /*!< Supports not equal to */ - GreaterThan = 1 << 3, /*!< Supports greater than */ - LessThan = 1 << 4, /*!< Supports less than */ - GreaterThanOrEqualTo = 1 << 5, /*!< Supports >= */ - LessThanOrEqualTo = 1 << 6, /*!< Supports <= */ - Between = 1 << 7, /*!< Supports searches between two values */ - CaseInsensitive = 1 << 8, /*!< Supports case insensitive searching */ - Contains = 1 << 9, /*!< Supports value "contains" searching */ - DoesNotContain = 1 << 10, /*!< Supports value does not contain searching */ - IsNull = 1 << 11, /*!< Supports searching for null values */ - IsNotBetween = 1 << 12, /*!< Supports searching for values outside of a set range */ - IsNotNull = 1 << 13, /*!< Supports searching for non-null values */ + EqualTo = 1 << 1, //!< Supports equal to + NotEqualTo = 1 << 2, //!< Supports not equal to + GreaterThan = 1 << 3, //!< Supports greater than + LessThan = 1 << 4, //!< Supports less than + GreaterThanOrEqualTo = 1 << 5, //!< Supports >= + LessThanOrEqualTo = 1 << 6, //!< Supports <= + Between = 1 << 7, //!< Supports searches between two values + CaseInsensitive = 1 << 8, //!< Supports case insensitive searching + Contains = 1 << 9, //!< Supports value "contains" searching + DoesNotContain = 1 << 10, //!< Supports value does not contain searching + IsNull = 1 << 11, //!< Supports searching for null values + IsNotBetween = 1 << 12, //!< Supports searching for values outside of a set range + IsNotNull = 1 << 13, //!< Supports searching for non-null values }; Q_DECLARE_FLAGS( FilterFlags, FilterFlag ) diff --git a/src/gui/editorwidgets/qgsmultiedittoolbutton.h b/src/gui/editorwidgets/qgsmultiedittoolbutton.h index b8e78042e34e..c8113985acc4 100644 --- a/src/gui/editorwidgets/qgsmultiedittoolbutton.h +++ b/src/gui/editorwidgets/qgsmultiedittoolbutton.h @@ -35,9 +35,9 @@ class GUI_EXPORT QgsMultiEditToolButton : public QToolButton //! Button states enum State { - Default, /*!< Default state, all features have same value for widget */ - MixedValues, /*!< Mixed state, some features have different values for the widget */ - Changed, /*!< Value for widget has changed but changes have not yet been committed */ + Default, //!< Default state, all features have same value for widget + MixedValues, //!< Mixed state, some features have different values for the widget + Changed, //!< Value for widget has changed but changes have not yet been committed }; /** Constructor for QgsMultiEditToolButton. diff --git a/src/gui/layertree/qgslayertreeembeddedwidgetregistry.h b/src/gui/layertree/qgslayertreeembeddedwidgetregistry.h index e0d5d545cbfa..f6574a81d129 100644 --- a/src/gui/layertree/qgslayertreeembeddedwidgetregistry.h +++ b/src/gui/layertree/qgslayertreeembeddedwidgetregistry.h @@ -62,15 +62,15 @@ class GUI_EXPORT QgsLayerTreeEmbeddedWidgetRegistry { public: - /** Means of accessing canonical single instance */ + //! Means of accessing canonical single instance static QgsLayerTreeEmbeddedWidgetRegistry* instance(); ~QgsLayerTreeEmbeddedWidgetRegistry(); - /** Return list of all registered providers */ + //! Return list of all registered providers QStringList providers() const; - /** Get provider object from the provider's ID */ + //! Get provider object from the provider's ID QgsLayerTreeEmbeddedWidgetProvider* provider( const QString& providerId ) const; /** Register a provider, takes ownership of the object. diff --git a/src/gui/qgisinterface.h b/src/gui/qgisinterface.h index 6cb53732617f..8f3a003ade89 100644 --- a/src/gui/qgisinterface.h +++ b/src/gui/qgisinterface.h @@ -69,13 +69,13 @@ class GUI_EXPORT QgisInterface : public QObject public: - /** Constructor */ + //! Constructor QgisInterface(); - /** Virtual destructor */ + //! Virtual destructor virtual ~QgisInterface(); - /** Get pointer to legend interface */ + //! Get pointer to legend interface virtual QgsLegendInterface* legendInterface() = 0; virtual QgsPluginManagerInterface* pluginManagerInterface() = 0; @@ -206,7 +206,7 @@ class GUI_EXPORT QgisInterface : public QObject //! @note added in 2.3 virtual void addToolBar( QToolBar* toolbar, Qt::ToolBarArea area = Qt::TopToolBarArea ) = 0; - /** Return a pointer to the map canvas */ + //! Return a pointer to the map canvas virtual QgsMapCanvas * mapCanvas() = 0; /** @@ -216,19 +216,19 @@ class GUI_EXPORT QgisInterface : public QObject */ virtual QgsLayerTreeMapCanvasBridge* layerTreeCanvasBridge() = 0; - /** Return a pointer to the main window (instance of QgisApp in case of QGIS) */ + //! Return a pointer to the main window (instance of QgisApp in case of QGIS) virtual QWidget * mainWindow() = 0; - /** Return the message bar of the main app */ + //! Return the message bar of the main app virtual QgsMessageBar * messageBar() = 0; - /** Open the message log dock widget **/ + //! Open the message log dock widget * virtual void openMessageLog() = 0; - /** Adds a widget to the user input tool bar.*/ + //! Adds a widget to the user input tool bar. virtual void addUserInputWidget( QWidget* widget ) = 0; - /** Return mainwindows / composer views of running composer instances (currently only one) */ + //! Return mainwindows / composer views of running composer instances (currently only one) virtual QList activeComposers() = 0; /** Create a new composer @@ -246,10 +246,10 @@ class GUI_EXPORT QgisInterface : public QObject */ virtual QgsComposerView* duplicateComposer( QgsComposerView* composerView, const QString& title = QString() ) = 0; - /** Deletes parent composer of composer view, after closing composer window */ + //! Deletes parent composer of composer view, after closing composer window virtual void deleteComposer( QgsComposerView* composerView ) = 0; - /** Return changeable options built from settings and/or defaults */ + //! Return changeable options built from settings and/or defaults virtual QMap defaultStyleSheetOptions() = 0; /** Generate stylesheet @@ -257,52 +257,52 @@ class GUI_EXPORT QgisInterface : public QObject */ virtual void buildStyleSheet( const QMap& opts ) = 0; - /** Save changed default option keys/values to user settings */ + //! Save changed default option keys/values to user settings virtual void saveStyleSheetOptions( const QMap& opts ) = 0; - /** Get reference font for initial qApp (may not be same as QgisApp) */ + //! Get reference font for initial qApp (may not be same as QgisApp) virtual QFont defaultStyleSheetFont() = 0; - /** Add action to the plugins menu */ + //! Add action to the plugins menu virtual void addPluginToMenu( const QString& name, QAction* action ) = 0; - /** Remove action from the plugins menu */ + //! Remove action from the plugins menu virtual void removePluginMenu( const QString& name, QAction* action ) = 0; - /** Add "add layer" action to layer menu */ + //! Add "add layer" action to layer menu virtual void insertAddLayerAction( QAction *action ) = 0; - /** Remove "add layer" action from layer menu */ + //! Remove "add layer" action from layer menu virtual void removeAddLayerAction( QAction *action ) = 0; - /** Add action to the Database menu */ + //! Add action to the Database menu virtual void addPluginToDatabaseMenu( const QString& name, QAction* action ) = 0; - /** Remove action from the Database menu */ + //! Remove action from the Database menu virtual void removePluginDatabaseMenu( const QString& name, QAction* action ) = 0; - /** Add action to the Raster menu */ + //! Add action to the Raster menu virtual void addPluginToRasterMenu( const QString& name, QAction* action ) = 0; - /** Remove action from the Raster menu */ + //! Remove action from the Raster menu virtual void removePluginRasterMenu( const QString& name, QAction* action ) = 0; - /** Add action to the Vector menu */ + //! Add action to the Vector menu virtual void addPluginToVectorMenu( const QString& name, QAction* action ) = 0; - /** Remove action from the Vector menu */ + //! Remove action from the Vector menu virtual void removePluginVectorMenu( const QString& name, QAction* action ) = 0; - /** Add action to the Web menu */ + //! Add action to the Web menu virtual void addPluginToWebMenu( const QString& name, QAction* action ) = 0; - /** Remove action from the Web menu */ + //! Remove action from the Web menu virtual void removePluginWebMenu( const QString& name, QAction* action ) = 0; - /** Add a dock widget to the main window */ + //! Add a dock widget to the main window virtual void addDockWidget( Qt::DockWidgetArea area, QDockWidget * dockwidget ) = 0; - /** Remove specified dock widget from main window (doesn't delete it). */ + //! Remove specified dock widget from main window (doesn't delete it). virtual void removeDockWidget( QDockWidget * dockwidget ) = 0; /** Advanced digitizing dock widget @@ -310,10 +310,10 @@ class GUI_EXPORT QgisInterface : public QObject */ virtual QgsAdvancedDigitizingDockWidget* cadDockWidget() = 0; - /** Open layer properties dialog */ + //! Open layer properties dialog virtual void showLayerProperties( QgsMapLayer *l ) = 0; - /** Open attribute table dialog */ + //! Open attribute table dialog virtual QDialog* showAttributeTable( QgsVectorLayer *l, const QString& filterExpression = QString() ) = 0; /** Add window to Window menu. The action title is the window title @@ -324,10 +324,10 @@ class GUI_EXPORT QgisInterface : public QObject * windows which are hidden rather than deleted when closed. */ virtual void removeWindow( QAction *action ) = 0; - /** Register action to the shortcuts manager so its shortcut can be changed in GUI */ + //! Register action to the shortcuts manager so its shortcut can be changed in GUI virtual bool registerMainWindowAction( QAction* action, const QString& defaultShortcut ) = 0; - /** Unregister a previously registered action. (e.g. when plugin is going to be unloaded) */ + //! Unregister a previously registered action. (e.g. when plugin is going to be unloaded) virtual bool unregisterMainWindowAction( QAction* action ) = 0; /** Register a new tab in the vector layer properties dialog. @@ -380,7 +380,7 @@ class GUI_EXPORT QgisInterface : public QObject virtual QMenu *viewMenu() = 0; virtual QMenu *layerMenu() = 0; virtual QMenu *newLayerMenu() = 0; - /** @note added in 2.5 */ + //! @note added in 2.5 virtual QMenu *addLayerMenu() = 0; virtual QMenu *settingsMenu() = 0; virtual QMenu *pluginMenu() = 0; @@ -489,9 +489,9 @@ class GUI_EXPORT QgisInterface : public QObject virtual QAction *actionAddRasterLayer() = 0; virtual QAction *actionAddPgLayer() = 0; virtual QAction *actionAddWmsLayer() = 0; - /** Get access to the native Add ArcGIS FeatureServer action. */ + //! Get access to the native Add ArcGIS FeatureServer action. virtual QAction *actionAddAfsLayer() = 0; - /** Get access to the native Add ArcGIS MapServer action. */ + //! Get access to the native Add ArcGIS MapServer action. virtual QAction *actionAddAmsLayer() = 0; virtual QAction *actionCopyLayerStyle() = 0; virtual QAction *actionPasteLayerStyle() = 0; @@ -579,7 +579,7 @@ class GUI_EXPORT QgisInterface : public QObject * @returns list of layers in legend order, or empty list */ virtual QList editableLayers( bool modified = false ) const = 0; - /** Get timeout for timed messages: default of 5 seconds */ + //! Get timeout for timed messages: default of 5 seconds virtual int messageTimeout() = 0; signals: diff --git a/src/gui/qgsadvanceddigitizingdockwidget.h b/src/gui/qgsadvanceddigitizingdockwidget.h index 7fbcee35bff9..96fe80270960 100644 --- a/src/gui/qgsadvanceddigitizingdockwidget.h +++ b/src/gui/qgsadvanceddigitizingdockwidget.h @@ -55,8 +55,8 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private enum CadCapacity { AbsoluteAngle = 1, //!< Azimuth - RelativeAngle = 2, //!< also for parallel and perpendicular - RelativeCoordinates = 4, //!< this corresponds to distance and relative coordinates + RelativeAngle = 2, //!< Also for parallel and perpendicular + RelativeCoordinates = 4, //!< This corresponds to distance and relative coordinates }; Q_DECLARE_FLAGS( CadCapacities, CadCapacity ) diff --git a/src/gui/qgsannotationitem.h b/src/gui/qgsannotationitem.h index 921932d71b05..22976f7b7572 100644 --- a/src/gui/qgsannotationitem.h +++ b/src/gui/qgsannotationitem.h @@ -62,7 +62,7 @@ class GUI_EXPORT QgsAnnotationItem: public QgsMapCanvasItem, public QgsAnnotatio /** Returns the mouse move behaviour for a given position @param pos the position in scene coordinates*/ QgsAnnotationItem::MouseMoveAction moveActionForPosition( QPointF pos ) const; - /** Returns suitable cursor shape for mouse move action*/ + //! Returns suitable cursor shape for mouse move action Qt::CursorShape cursorShapeForAction( MouseMoveAction moveAction ) const; //setters and getters @@ -81,7 +81,7 @@ class GUI_EXPORT QgsAnnotationItem: public QgsMapCanvasItem, public QgsAnnotatio /** Sets the CRS of the map position. @param crs the CRS to set */ virtual void setMapPositionCrs( const QgsCoordinateReferenceSystem& crs ); - /** Returns the CRS of the map position.*/ + //! Returns the CRS of the map position. QgsCoordinateReferenceSystem mapPositionCrs() const override { return mMapPositionCrs; } void setFrameSize( QSizeF size ); @@ -90,7 +90,7 @@ class GUI_EXPORT QgsAnnotationItem: public QgsMapCanvasItem, public QgsAnnotatio void setOffsetFromReferencePoint( QPointF offset ); QPointF offsetFromReferencePoint() const { return mOffsetFromReferencePoint; } - /** Set symbol that is drawn on map position. Takes ownership*/ + //! Set symbol that is drawn on map position. Takes ownership void setMarkerSymbol( QgsMarkerSymbol* symbol ); const QgsMarkerSymbol* markerSymbol() const {return mMarkerSymbol;} @@ -134,38 +134,38 @@ class GUI_EXPORT QgsAnnotationItem: public QgsMapCanvasItem, public QgsAnnotatio void paint( QPainter* painter ) override; protected: - /** True: the item stays at the same map position, False: the item stays on same screen position*/ + //! True: the item stays at the same map position, False: the item stays on same screen position bool mMapPositionFixed; - /** Map position (in case mMapPositionFixed is true)*/ + //! Map position (in case mMapPositionFixed is true) QgsPoint mMapPosition; - /** CRS of the map position */ + //! CRS of the map position QgsCoordinateReferenceSystem mMapPositionCrs; - /** Describes the shift of the item content box to the reference point*/ + //! Describes the shift of the item content box to the reference point QPointF mOffsetFromReferencePoint; - /** Size of the frame (without balloon)*/ + //! Size of the frame (without balloon) QSizeF mFrameSize; - /** Bounding rect (including item frame and balloon)*/ + //! Bounding rect (including item frame and balloon) QRectF mBoundingRect; - /** Point symbol that is to be drawn at the map reference location*/ + //! Point symbol that is to be drawn at the map reference location QgsMarkerSymbol* mMarkerSymbol; - /** Width of the frame*/ + //! Width of the frame double mFrameBorderWidth; - /** Frame / balloon color*/ + //! Frame / balloon color QColor mFrameColor; QColor mFrameBackgroundColor; - /** Segment number where the connection to the map point is attached. -1 if no balloon needed (e.g. if point is contained in frame)*/ + //! Segment number where the connection to the map point is attached. -1 if no balloon needed (e.g. if point is contained in frame) int mBalloonSegment; - /** First segment point for drawing the connection (ccw direction)*/ + //! First segment point for drawing the connection (ccw direction) QPointF mBalloonSegmentPoint1; - /** Second segment point for drawing the balloon connection (ccw direction)*/ + //! Second segment point for drawing the balloon connection (ccw direction) QPointF mBalloonSegmentPoint2; void updateBoundingRect(); - /** Check where to attach the balloon connection between frame and map point*/ + //! Check where to attach the balloon connection between frame and map point void updateBalloon(); //! Draws the annotation frame to a destination painter @@ -177,13 +177,13 @@ class GUI_EXPORT QgsAnnotationItem: public QgsMapCanvasItem, public QgsAnnotatio //! Draws selection handles around the item void drawSelectionBoxes( QPainter* p ) const; - /** Returns frame width in painter units*/ + //! Returns frame width in painter units //double scaledFrameWidth( QPainter* p) const; - /** Gets the frame line (0 is the top line, 1 right, 2 bottom, 3 left)*/ + //! Gets the frame line (0 is the top line, 1 right, 2 bottom, 3 left) QLineF segment( int index ) const; - /** Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point*/ + //! Returns a point on the line from startPoint to directionPoint that is a certain distance away from the starting point QPointF pointOnLineWithDistance( QPointF startPoint, QPointF directionPoint, double distance ) const; - /** Returns the symbol size scaled in (mapcanvas) pixels. Used for the counding rect calculation*/ + //! Returns the symbol size scaled in (mapcanvas) pixels. Used for the counding rect calculation double scaledSymbolSize() const; }; diff --git a/src/gui/qgsattributeform.h b/src/gui/qgsattributeform.h index 16b44ce09dcc..c584f327a135 100644 --- a/src/gui/qgsattributeform.h +++ b/src/gui/qgsattributeform.h @@ -42,19 +42,19 @@ class GUI_EXPORT QgsAttributeForm : public QWidget //! Form modes enum Mode { - SingleEditMode, /*!< Single edit mode, for editing a single feature */ + SingleEditMode, //!< Single edit mode, for editing a single feature AddFeatureMode, /*!< Add feature mode, for setting attributes for a new feature. In this mode the dialog will be editable even with an invalid feature and will add a new feature when the form is accepted. */ - MultiEditMode, /*!< Multi edit mode, for editing fields of multiple features at once */ - SearchMode, /*!< Form values are used for searching/filtering the layer */ + MultiEditMode, //!< Multi edit mode, for editing fields of multiple features at once + SearchMode, //!< Form values are used for searching/filtering the layer }; //! Filter types enum FilterType { - ReplaceFilter, /*!< Filter should replace any existing filter */ - FilterAnd, /*!< Filter should be combined using "AND" */ - FilterOr, /*!< Filter should be combined using "OR" */ + ReplaceFilter, //!< Filter should replace any existing filter + FilterAnd, //!< Filter should be combined using "AND" + FilterOr, //!< Filter should be combined using "OR" }; explicit QgsAttributeForm( QgsVectorLayer* vl, const QgsFeature &feature = QgsFeature(), diff --git a/src/gui/qgsattributeformeditorwidget.h b/src/gui/qgsattributeformeditorwidget.h index 51cc6b5f90a5..eeac24dcbb97 100644 --- a/src/gui/qgsattributeformeditorwidget.h +++ b/src/gui/qgsattributeformeditorwidget.h @@ -47,9 +47,9 @@ class GUI_EXPORT QgsAttributeFormEditorWidget : public QWidget //! Widget modes enum Mode { - DefaultMode, /*!< Default mode, only the editor widget is shown */ - MultiEditMode, /*!< Multi edit mode, both the editor widget and a QgsMultiEditToolButton is shown */ - SearchMode, /*!< Layer search/filter mode */ + DefaultMode, //!< Default mode, only the editor widget is shown + MultiEditMode, //!< Multi edit mode, both the editor widget and a QgsMultiEditToolButton is shown + SearchMode, //!< Layer search/filter mode }; /** Constructor for QgsAttributeFormEditorWidget. diff --git a/src/gui/qgscollapsiblegroupbox.h b/src/gui/qgscollapsiblegroupbox.h index b6f982bc95b3..2ca22f9ce007 100644 --- a/src/gui/qgscollapsiblegroupbox.h +++ b/src/gui/qgscollapsiblegroupbox.h @@ -127,7 +127,7 @@ class GUI_EXPORT QgsCollapsibleGroupBoxBasic : public QGroupBox bool scrollOnExpand() {return mScrollOnExpand;} signals: - /** Signal emitted when groupbox collapsed/expanded state is changed, and when first shown */ + //! Signal emitted when groupbox collapsed/expanded state is changed, and when first shown void collapsedStateChanged( bool collapsed ); public slots: @@ -138,7 +138,7 @@ class GUI_EXPORT QgsCollapsibleGroupBoxBasic : public QGroupBox protected: void init(); - /** Visual fixes for when group box is collapsed/expanded */ + //! Visual fixes for when group box is collapsed/expanded void collapseExpandFixes(); void showEvent( QShowEvent *event ) override; diff --git a/src/gui/qgscolorbutton.h b/src/gui/qgscolorbutton.h index c8488ba5b552..1968ec94ac51 100644 --- a/src/gui/qgscolorbutton.h +++ b/src/gui/qgscolorbutton.h @@ -52,8 +52,8 @@ class GUI_EXPORT QgsColorButton : public QToolButton */ enum Behaviour { - ShowDialog = 0, /*!< show a color picker dialog when clicked */ - SignalOnly /*!< emit colorClicked signal only, no dialog */ + ShowDialog = 0, //!< Show a color picker dialog when clicked + SignalOnly //!< Emit colorClicked signal only, no dialog }; /** Construct a new color button. diff --git a/src/gui/qgscolorwidgets.h b/src/gui/qgscolorwidgets.h index d4ffc042db41..57ca838f534b 100644 --- a/src/gui/qgscolorwidgets.h +++ b/src/gui/qgscolorwidgets.h @@ -43,14 +43,14 @@ class GUI_EXPORT QgsColorWidget : public QWidget */ enum ColorComponent { - Multiple = 0, /*!< widget alters multiple color components */ - Red, /*!< red component of color */ - Green, /*!< green component of color */ - Blue, /*!< blue component of color */ - Hue, /*!< hue component of color (based on HSV model) */ - Saturation, /*!< saturation component of color (based on HSV model) */ - Value, /*!< value component of color (based on HSV model) */ - Alpha /*!< alpha component (opacity) of color */ + Multiple = 0, //!< Widget alters multiple color components + Red, //!< Red component of color + Green, //!< Green component of color + Blue, //!< Blue component of color + Hue, //!< Hue component of color (based on HSV model) + Saturation, //!< Saturation component of color (based on HSV model) + Value, //!< Value component of color (based on HSV model) + Alpha //!< Alpha component (opacity) of color }; /** Construct a new color widget. @@ -328,10 +328,10 @@ class GUI_EXPORT QgsColorWheel : public QgsColorWidget */ void createImages( const QSizeF size ); - /** Creates the hue wheel image*/ + //! Creates the hue wheel image void createWheel(); - /** Creates the inner triangle image*/ + //! Creates the inner triangle image void createTriangle(); /** Sets the widget color based on a point in the widget @@ -446,8 +446,8 @@ class GUI_EXPORT QgsColorRampWidget : public QgsColorWidget */ enum Orientation { - Horizontal = 0, /*!< horizontal ramp */ - Vertical /*!< vertical ramp */ + Horizontal = 0, //!< Horizontal ramp + Vertical //!< Vertical ramp }; /** Construct a new color ramp widget. @@ -639,10 +639,10 @@ class GUI_EXPORT QgsColorTextWidget : public QgsColorWidget */ enum ColorTextFormat { - HexRgb = 0, /*!< \#RRGGBB in hexadecimal */ - HexRgbA, /*!< \#RRGGBBAA in hexadecimal, with alpha */ - Rgb, /*!< rgb( r, g, b ) format */ - Rgba /*!< rgba( r, g, b, a ) format, with alpha */ + HexRgb = 0, //!< \#RRGGBB in hexadecimal + HexRgbA, //!< \#RRGGBBAA in hexadecimal, with alpha + Rgb, //!< Rgb( r, g, b ) format + Rgba //!< Rgba( r, g, b, a ) format, with alpha }; QLineEdit* mLineEdit; diff --git a/src/gui/qgscomposerruler.h b/src/gui/qgscomposerruler.h index e4be28ec2a4c..ac695f2a3824 100644 --- a/src/gui/qgscomposerruler.h +++ b/src/gui/qgscomposerruler.h @@ -95,7 +95,7 @@ class GUI_EXPORT QgsComposerRuler: public QWidget void drawMarkerPos( QPainter *painter ); signals: - /** Is emitted when mouse cursor coordinates change*/ + //! Is emitted when mouse cursor coordinates change void cursorPosChanged( QPointF ); }; diff --git a/src/gui/qgscomposerview.h b/src/gui/qgscomposerview.h index afcb139b2e63..c2f3c7625937 100644 --- a/src/gui/qgscomposerview.h +++ b/src/gui/qgscomposerview.h @@ -51,7 +51,7 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView public: - /** Current tool*/ + //! Current tool enum Tool { Select = 0, // Select/Move item @@ -97,28 +97,28 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView QgsComposerView( QWidget* parent = nullptr, const char* name = nullptr, Qt::WindowFlags f = 0 ); - /** Add an item group containing the selected items*/ + //! Add an item group containing the selected items void groupItems(); - /** Ungroups the selected items*/ + //! Ungroups the selected items void ungroupItems(); - /** Cuts or copies the selected items*/ + //! Cuts or copies the selected items void copyItems( ClipboardMode mode ); - /** Pastes items from clipboard*/ + //! Pastes items from clipboard void pasteItems( PasteMode mode ); - /** Deletes selected items*/ + //! Deletes selected items void deleteSelectedItems(); - /** Selects all items*/ + //! Selects all items void selectAll(); - /** Deselects all items*/ + //! Deselects all items void selectNone(); - /** Inverts current selection*/ + //! Inverts current selection void selectInvert(); QgsComposerView::Tool currentTool() const {return mCurrentTool;} @@ -129,22 +129,22 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView */ void setComposition( QgsComposition* c ); - /** Returns the composition or 0 in case of error*/ + //! Returns the composition or 0 in case of error QgsComposition* composition(); - /** Returns the composer main window*/ + //! Returns the composer main window QMainWindow* composerWindow(); void setPaintingEnabled( bool enabled ) { mPaintingEnabled = enabled; } bool paintingEnabled() const { return mPaintingEnabled; } - /** Update rulers with current scene rect*/ + //! Update rulers with current scene rect void updateRulers(); void setHorizontalRuler( QgsComposerRuler* r ) { mHorizontalRuler = r; } void setVerticalRuler( QgsComposerRuler* r ) { mVerticalRuler = r; } - /** Set zoom level, where a zoom level of 1.0 corresponds to 100%*/ + //! Set zoom level, where a zoom level of 1.0 corresponds to 100% void setZoomLevel( double zoomLevel ); /** Scales the view in a safe way, by limiting the acceptable range @@ -188,27 +188,27 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView void scrollContentsBy( int dx, int dy ) override; private: - /** Current composer tool*/ + //! Current composer tool QgsComposerView::Tool mCurrentTool; - /** Previous composer tool*/ + //! Previous composer tool QgsComposerView::Tool mPreviousTool; - /** Rubber band item*/ + //! Rubber band item QGraphicsRectItem* mRubberBandItem; - /** Rubber band item for arrows*/ + //! Rubber band item for arrows QGraphicsLineItem* mRubberBandLineItem; - /** Item to move content*/ + //! Item to move content QgsComposerItem* mMoveContentItem; - /** Start position of content move*/ + //! Start position of content move QPointF mMoveContentStartPos; - /** Start of rubber band creation*/ + //! Start of rubber band creation QPointF mRubberBandStartPos; - /** True if user is currently selecting by marquee*/ + //! True if user is currently selecting by marquee bool mMarqueeSelect; - /** True if user is currently zooming by marquee*/ + //! True if user is currently zooming by marquee bool mMarqueeZoom; - /** True if user is currently temporarily activating the zoom tool by holding control+space*/ + //! True if user is currently temporarily activating the zoom tool by holding control+space QgsComposerView::ToolStatus mTemporaryZoomStatus; bool mPaintingEnabled; @@ -216,10 +216,10 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView QgsComposerRuler* mHorizontalRuler; QgsComposerRuler* mVerticalRuler; - /** Draw a shape on the canvas */ + //! Draw a shape on the canvas void addShape( Tool currentTool ); - /** Point based shape stuff */ + //! Point based shape stuff void addPolygonNode( QPointF scenePoint ); void movePolygonNode( QPointF scenePoint ); void displayNodes( const bool display = true ); @@ -232,14 +232,14 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView QScopedPointer mPolygonItem; QScopedPointer mPolylineItem; - /** True if user is currently panning by clicking and dragging with the pan tool*/ + //! True if user is currently panning by clicking and dragging with the pan tool bool mToolPanning; - /** True if user is currently panning by holding the middle mouse button*/ + //! True if user is currently panning by holding the middle mouse button bool mMousePanning; - /** True if user is currently panning by holding the space key*/ + //! True if user is currently panning by holding the space key bool mKeyPanning; - /** True if user is currently dragging with the move item content tool*/ + //! True if user is currently dragging with the move item content tool bool mMovingItemContent; QPoint mMouseLastXY; @@ -248,48 +248,48 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView QgsPreviewEffect* mPreviewEffect; - /** Returns the default mouse cursor for a tool*/ + //! Returns the default mouse cursor for a tool QCursor defaultCursorForTool( Tool currentTool ); - /** Zoom composition from a mouse wheel event*/ + //! Zoom composition from a mouse wheel event void wheelZoom( QWheelEvent * event ); - /** Redraws the rectangular rubber band*/ + //! Redraws the rectangular rubber band void updateRubberBandRect( QPointF & pos, const bool constrainSquare = false, const bool fromCenter = false ); - /** Redraws the linear rubber band*/ + //! Redraws the linear rubber band void updateRubberBandLine( QPointF pos, const bool constrainAngles = false ); - /** Removes the rubber band and cleans up*/ + //! Removes the rubber band and cleans up void removeRubberBand(); - /** Starts a marquee selection*/ + //! Starts a marquee selection void startMarqueeSelect( QPointF & scenePoint ); - /** Finalises a marquee selection*/ + //! Finalises a marquee selection void endMarqueeSelect( QMouseEvent* e ); - /** Starts a zoom in marquee*/ + //! Starts a zoom in marquee void startMarqueeZoom( QPointF & scenePoint ); - /** Finalises a marquee zoom*/ + //! Finalises a marquee zoom void endMarqueeZoom( QMouseEvent* e ); //void connectAddRemoveCommandSignals( QgsAddRemoveItemCommand* c ); signals: - /** Is emitted when selected item changed. If 0, no item is selected*/ + //! Is emitted when selected item changed. If 0, no item is selected void selectedItemChanged( QgsComposerItem* selected ); - /** Is emitted when a composer item has been removed from the scene*/ + //! Is emitted when a composer item has been removed from the scene void itemRemoved( QgsComposerItem* ); /** Current action (e.g. adding composer map) has been finished. The purpose of this signal is that QgsComposer may set the selection tool again*/ void actionFinished(); - /** Is emitted when mouse cursor coordinates change*/ + //! Is emitted when mouse cursor coordinates change void cursorPosChanged( QPointF ); - /** Is emitted when the view zoom changes*/ + //! Is emitted when the view zoom changes void zoomLevelChanged(); - /** Emitted before composerview is shown*/ + //! Emitted before composerview is shown void composerViewShow( QgsComposerView* ); - /** Emitted before composerview is hidden*/ + //! Emitted before composerview is hidden void composerViewHide( QgsComposerView* ); - /** Emitted when the composition is set for the view*/ + //! Emitted when the composition is set for the view void compositionSet( QgsComposition* ); }; diff --git a/src/gui/qgscompoundcolorwidget.h b/src/gui/qgscompoundcolorwidget.h index bec73418411b..d7740fa6d557 100644 --- a/src/gui/qgscompoundcolorwidget.h +++ b/src/gui/qgscompoundcolorwidget.h @@ -37,8 +37,8 @@ class GUI_EXPORT QgsCompoundColorWidget : public QgsPanelWidget, private Ui::Qgs //! Widget layout enum Layout { - LayoutDefault = 0, /*!< Use the default (rectangular) layout */ - LayoutVertical, /*!< Use a narrower, vertically stacked layout */ + LayoutDefault = 0, //!< Use the default (rectangular) layout + LayoutVertical, //!< Use a narrower, vertically stacked layout }; /** Constructor for QgsCompoundColorWidget diff --git a/src/gui/qgsdatumtransformdialog.h b/src/gui/qgsdatumtransformdialog.h index 6780859ed96d..c6ac31cd4cc0 100644 --- a/src/gui/qgsdatumtransformdialog.h +++ b/src/gui/qgsdatumtransformdialog.h @@ -48,7 +48,7 @@ class GUI_EXPORT QgsDatumTransformDialog : public QDialog, private Ui::QgsDatumT QgsDatumTransformDialog(); void updateTitle(); bool gridShiftTransformation( const QString& itemText ) const; - /** Returns false if the location of the grid shift files is known (PROJ_LIB) and the shift file is not there*/ + //! Returns false if the location of the grid shift files is known (PROJ_LIB) and the shift file is not there bool testGridShiftFileAvailability( QTreeWidgetItem* item, int col ) const; void load(); diff --git a/src/gui/qgsdetaileditemdelegate.h b/src/gui/qgsdetaileditemdelegate.h index e198df60b3dd..013f4a088fa7 100644 --- a/src/gui/qgsdetaileditemdelegate.h +++ b/src/gui/qgsdetaileditemdelegate.h @@ -37,11 +37,11 @@ class GUI_EXPORT QgsDetailedItemDelegate : public QAbstractItemDelegate public: QgsDetailedItemDelegate( QObject * parent = nullptr ); ~QgsDetailedItemDelegate(); - /** Reimplement for parent class */ + //! Reimplement for parent class void paint( QPainter * thePainter, const QStyleOptionViewItem & theOption, const QModelIndex & theIndex ) const override; - /** Reimplement for parent class */ + //! Reimplement for parent class QSize sizeHint( const QStyleOptionViewItem & theOption, const QModelIndex & theIndex ) const override; diff --git a/src/gui/qgsencodingfiledialog.h b/src/gui/qgsencodingfiledialog.h index 87fe19c4f5cb..2719649f34fd 100644 --- a/src/gui/qgsencodingfiledialog.h +++ b/src/gui/qgsencodingfiledialog.h @@ -31,11 +31,11 @@ class GUI_EXPORT QgsEncodingFileDialog: public QFileDialog const QString& caption = QString(), const QString& directory = QString(), const QString& filter = QString(), const QString& encoding = QString() ); ~QgsEncodingFileDialog(); - /** Returns a string describing the chosen encoding*/ + //! Returns a string describing the chosen encoding QString encoding() const; - /** Adds a 'Cancel All' button for the user to click */ + //! Adds a 'Cancel All' button for the user to click void addCancelAll(); - /** Returns true if the user clicked 'Cancel All' */ + //! Returns true if the user clicked 'Cancel All' bool cancelAll(); public slots: @@ -44,7 +44,7 @@ class GUI_EXPORT QgsEncodingFileDialog: public QFileDialog void pbnCancelAll_clicked(); private: - /** Box to choose the encoding type*/ + //! Box to choose the encoding type QComboBox* mEncodingComboBox; /* The button to click */ diff --git a/src/gui/qgsexpressionbuilderdialog.h b/src/gui/qgsexpressionbuilderdialog.h index 0e97b6d7469c..faf5717fe667 100644 --- a/src/gui/qgsexpressionbuilderdialog.h +++ b/src/gui/qgsexpressionbuilderdialog.h @@ -31,7 +31,7 @@ class GUI_EXPORT QgsExpressionBuilderDialog : public QDialog, private Ui::QgsExp QgsExpressionBuilderDialog( QgsVectorLayer* layer, const QString& startText = QString(), QWidget* parent = nullptr, const QString& key = "generic", const QgsExpressionContext& context = QgsExpressionContext() ); - /** The builder widget that is used by the dialog */ + //! The builder widget that is used by the dialog QgsExpressionBuilderWidget* expressionBuilder(); void setExpressionText( const QString& text ); @@ -53,7 +53,7 @@ class GUI_EXPORT QgsExpressionBuilderDialog : public QDialog, private Ui::QgsExp */ void setExpressionContext( const QgsExpressionContext& context ); - /** Sets geometry calculator used in distance/area calculations. */ + //! Sets geometry calculator used in distance/area calculations. void setGeomCalculator( const QgsDistanceArea & da ); protected: diff --git a/src/gui/qgsexpressionbuilderwidget.h b/src/gui/qgsexpressionbuilderwidget.h index 453abb7d7917..01a615ea6a8d 100644 --- a/src/gui/qgsexpressionbuilderwidget.h +++ b/src/gui/qgsexpressionbuilderwidget.h @@ -148,14 +148,14 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp */ void loadFieldsAndValues( const QMap& fieldValues ); - /** Sets geometry calculator used in distance/area calculations. */ + //! Sets geometry calculator used in distance/area calculations. void setGeomCalculator( const QgsDistanceArea & da ); /** Gets the expression string that has been set in the expression area. * @returns The expression as a string. */ QString expressionText(); - /** Sets the expression string for the widget */ + //! Sets the expression string for the widget void setExpressionText( const QString& expression ); /** Returns the expression context for the widget. The context is used for the expression diff --git a/src/gui/qgsextentgroupbox.h b/src/gui/qgsextentgroupbox.h index dd7b794af197..54835617a34e 100644 --- a/src/gui/qgsextentgroupbox.h +++ b/src/gui/qgsextentgroupbox.h @@ -44,9 +44,9 @@ class GUI_EXPORT QgsExtentGroupBox : public QgsCollapsibleGroupBox, private Ui:: enum ExtentState { - OriginalExtent, //!< layer's extent - CurrentExtent, //!< map canvas extent - UserExtent, //!< extent manually entered/modified by the user + OriginalExtent, //!< Layer's extent + CurrentExtent, //!< Map canvas extent + UserExtent, //!< Extent manually entered/modified by the user }; //! Setup original extent - should be called as part of initialization diff --git a/src/gui/qgsfieldmodel.h b/src/gui/qgsfieldmodel.h index b5b93e686605..22b7bba7d718 100644 --- a/src/gui/qgsfieldmodel.h +++ b/src/gui/qgsfieldmodel.h @@ -35,13 +35,13 @@ class GUI_EXPORT QgsFieldModel : public QAbstractItemModel public: enum FieldRoles { - FieldNameRole = Qt::UserRole + 1, /*!< return field name if index corresponds to a field */ - FieldIndexRole = Qt::UserRole + 2, /*!< return field index if index corresponds to a field */ - ExpressionRole = Qt::UserRole + 3, /*!< return field name or expression */ - IsExpressionRole = Qt::UserRole + 4, /*!< return if index corresponds to an expression */ - ExpressionValidityRole = Qt::UserRole + 5, /*!< return if expression is valid or not */ - FieldTypeRole = Qt::UserRole + 6, /*!< return the field type (if a field, return QVariant if expression) */ - FieldOriginRole = Qt::UserRole + 7, /*!< return the field origin (if a field, returns QVariant if expression) */ + FieldNameRole = Qt::UserRole + 1, //!< Return field name if index corresponds to a field + FieldIndexRole = Qt::UserRole + 2, //!< Return field index if index corresponds to a field + ExpressionRole = Qt::UserRole + 3, //!< Return field name or expression + IsExpressionRole = Qt::UserRole + 4, //!< Return if index corresponds to an expression + ExpressionValidityRole = Qt::UserRole + 5, //!< Return if expression is valid or not + FieldTypeRole = Qt::UserRole + 6, //!< Return the field type (if a field, return QVariant if expression) + FieldOriginRole = Qt::UserRole + 7, //!< Return the field origin (if a field, returns QVariant if expression) }; /** diff --git a/src/gui/qgsfieldproxymodel.h b/src/gui/qgsfieldproxymodel.h index 0b0b3e5a4a49..6c0b29e8a7b7 100644 --- a/src/gui/qgsfieldproxymodel.h +++ b/src/gui/qgsfieldproxymodel.h @@ -34,15 +34,15 @@ class GUI_EXPORT QgsFieldProxyModel : public QSortFilterProxyModel //! Field type filters enum Filter { - String = 1, /*!< String fields */ - Int = 2, /*!< Integer fields */ - LongLong = 4, /*!< Longlong fields */ - Double = 8, /*!< Double fields */ - Numeric = Int | LongLong | Double, /*!< All numeric fields */ - Date = 16, /*!< Date or datetime fields */ - Time = 32, /*!< Time fields */ - HideReadOnly = 64, /*!< Hide read-only fields */ - AllTypes = Numeric | Date | String | Time, /*!< All field types */ + String = 1, //!< String fields + Int = 2, //!< Integer fields + LongLong = 4, //!< Longlong fields + Double = 8, //!< Double fields + Numeric = Int | LongLong | Double, //!< All numeric fields + Date = 16, //!< Date or datetime fields + Time = 32, //!< Time fields + HideReadOnly = 64, //!< Hide read-only fields + AllTypes = Numeric | Date | String | Time, //!< All field types }; Q_DECLARE_FLAGS( Filters, Filter ) diff --git a/src/gui/qgsformannotationitem.h b/src/gui/qgsformannotationitem.h index 57953d78c2bb..765b3131ebed 100644 --- a/src/gui/qgsformannotationitem.h +++ b/src/gui/qgsformannotationitem.h @@ -39,10 +39,10 @@ class GUI_EXPORT QgsFormAnnotationItem: public QObject, public QgsAnnotationItem void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; QSizeF minimumFrameSize() const override; - /** Returns the optimal frame size*/ + //! Returns the optimal frame size QSizeF preferredFrameSize() const; - /** Reimplemented from QgsAnnotationItem*/ + //! Reimplemented from QgsAnnotationItem void setMapPosition( const QgsPoint& pos ) override; void setDesignerForm( const QString& uiFile ); @@ -54,21 +54,21 @@ class GUI_EXPORT QgsFormAnnotationItem: public QObject, public QgsAnnotationItem QgsVectorLayer* vectorLayer() const { return mVectorLayer; } private slots: - /** Sets a feature for the current map position and updates the dialog*/ + //! Sets a feature for the current map position and updates the dialog void setFeatureForMapPosition(); - /** Sets visibility status based on mVectorLayer visibility*/ + //! Sets visibility status based on mVectorLayer visibility void updateVisibility(); private: QGraphicsProxyWidget* mWidgetContainer; QWidget* mDesignerWidget; - /** Associated vectorlayer (or 0 if attributes are not supposed to be replaced)*/ + //! Associated vectorlayer (or 0 if attributes are not supposed to be replaced) QgsVectorLayer* mVectorLayer; - /** True if the item is related to a vector feature*/ + //! True if the item is related to a vector feature bool mHasAssociatedFeature; - /** Associated feature*/ + //! Associated feature QgsFeatureId mFeature; - /** Path to (and including) the .ui file*/ + //! Path to (and including) the .ui file QString mDesignerForm; QWidget* createDesignerWidget( const QString& filePath ); diff --git a/src/gui/qgsgeometryrubberband.h b/src/gui/qgsgeometryrubberband.h index f09e6a501ca7..67d2f3e7db5a 100644 --- a/src/gui/qgsgeometryrubberband.h +++ b/src/gui/qgsgeometryrubberband.h @@ -63,23 +63,23 @@ class GUI_EXPORT QgsGeometryRubberBand: public QgsMapCanvasItem QgsGeometryRubberBand( QgsMapCanvas* mapCanvas, QgsWkbTypes::GeometryType geomType = QgsWkbTypes::LineGeometry ); ~QgsGeometryRubberBand(); - /** Sets geometry (takes ownership). Geometry is expected to be in map coordinates */ + //! Sets geometry (takes ownership). Geometry is expected to be in map coordinates void setGeometry( QgsAbstractGeometry* geom ); - /** Returns a pointer to the geometry*/ + //! Returns a pointer to the geometry const QgsAbstractGeometry* geometry() { return mGeometry; } - /** Moves vertex to new position (in map coordinates)*/ + //! Moves vertex to new position (in map coordinates) void moveVertex( QgsVertexId id, const QgsPointV2& newPos ); - /** Sets fill color for vertex markers*/ + //! Sets fill color for vertex markers void setFillColor( const QColor& c ); - /** Sets outline color for vertex markes*/ + //! Sets outline color for vertex markes void setOutlineColor( const QColor& c ); - /** Sets outline width*/ + //! Sets outline width void setOutlineWidth( int width ); - /** Sets pen style*/ + //! Sets pen style void setLineStyle( Qt::PenStyle penStyle ); - /** Sets brush style*/ + //! Sets brush style void setBrushStyle( Qt::BrushStyle brushStyle ); - /** Sets vertex marker icon type*/ + //! Sets vertex marker icon type void setIconType( IconType iconType ) { mIconType = iconType; } protected: diff --git a/src/gui/qgshighlight.h b/src/gui/qgshighlight.h index a19846a7f359..4f8ffe60aa5c 100644 --- a/src/gui/qgshighlight.h +++ b/src/gui/qgshighlight.h @@ -67,7 +67,7 @@ class GUI_EXPORT QgsHighlight: public QgsMapCanvasItem * @note: added in version 2.3 */ void setFillColor( const QColor & fillColor ); - /** Set width. Ignored in feature mode. */ + //! Set width. Ignored in feature mode. void setWidth( int width ); /** Set line / outline buffer in millimeters. @@ -92,7 +92,7 @@ class GUI_EXPORT QgsHighlight: public QgsMapCanvasItem void init(); void setSymbol( QgsSymbol* symbol, const QgsRenderContext & context, const QColor & color, const QColor & fillColor ); double getSymbolWidth( const QgsRenderContext & context, double width, QgsUnitTypes::RenderUnit unit ); - /** Get renderer for current color mode and colors. The renderer should be freed by caller. */ + //! Get renderer for current color mode and colors. The renderer should be freed by caller. QgsFeatureRenderer * getRenderer( QgsRenderContext &context, const QColor & color, const QColor & fillColor ); void paintPoint( QPainter *p, const QgsPoint& point ); void paintLine( QPainter *p, QgsPolyline line ); diff --git a/src/gui/qgshtmlannotationitem.h b/src/gui/qgshtmlannotationitem.h index 718347bea168..760b3dcd84a0 100644 --- a/src/gui/qgshtmlannotationitem.h +++ b/src/gui/qgshtmlannotationitem.h @@ -42,7 +42,7 @@ class GUI_EXPORT QgsHtmlAnnotationItem: public QObject, public QgsAnnotationItem QSizeF minimumFrameSize() const override; - /** Reimplemented from QgsAnnotationItem*/ + //! Reimplemented from QgsAnnotationItem void setMapPosition( const QgsPoint& pos ) override; void setHTMLPage( const QString& htmlFile ); @@ -54,9 +54,9 @@ class GUI_EXPORT QgsHtmlAnnotationItem: public QObject, public QgsAnnotationItem QgsVectorLayer* vectorLayer() const { return mVectorLayer; } private slots: - /** Sets a feature for the current map position and updates the dialog*/ + //! Sets a feature for the current map position and updates the dialog void setFeatureForMapPosition(); - /** Sets visibility status based on mVectorLayer visibility*/ + //! Sets visibility status based on mVectorLayer visibility void updateVisibility(); void javascript(); @@ -64,11 +64,11 @@ class GUI_EXPORT QgsHtmlAnnotationItem: public QObject, public QgsAnnotationItem private: QGraphicsProxyWidget* mWidgetContainer; QgsWebView* mWebView; - /** Associated vectorlayer (or 0 if attributes are not supposed to be replaced)*/ + //! Associated vectorlayer (or 0 if attributes are not supposed to be replaced) QgsVectorLayer* mVectorLayer; - /** True if the item is related to a vector feature*/ + //! True if the item is related to a vector feature bool mHasAssociatedFeature; - /** Associated feature*/ + //! Associated feature QgsFeatureId mFeatureId; QgsFeature mFeature; QString mHtmlFile; diff --git a/src/gui/qgslegendinterface.h b/src/gui/qgslegendinterface.h index 8edd75c7d5c1..51cb92d3227f 100644 --- a/src/gui/qgslegendinterface.h +++ b/src/gui/qgslegendinterface.h @@ -43,10 +43,10 @@ class GUI_EXPORT QgsLegendInterface : public QObject public: - /** Constructor */ + //! Constructor QgsLegendInterface(); - /** Virtual destructor */ + //! Virtual destructor virtual ~QgsLegendInterface(); //! Return a string list of groups @@ -78,7 +78,7 @@ class GUI_EXPORT QgsLegendInterface : public QObject //! Check if a layer is visible virtual bool isLayerVisible( QgsMapLayer * ml ) = 0; - /** Add action for layers in the legend */ + //! Add action for layers in the legend virtual void addLegendLayerAction( QAction* action, QString menu, QString id, QgsMapLayer::LayerType type, bool allLayers ) = 0; @@ -87,7 +87,7 @@ class GUI_EXPORT QgsLegendInterface : public QObject */ virtual void addLegendLayerActionForLayer( QAction* action, QgsMapLayer* layer ) = 0; - /** Remove action for layers in the legend */ + //! Remove action for layers in the legend virtual bool removeLegendLayerAction( QAction* action ) = 0; //! Returns the current layer if the current item is a QgsLegendLayer. diff --git a/src/gui/qgsmapcanvas.cpp b/src/gui/qgsmapcanvas.cpp index ef3d67b7f42d..86e0a3f71360 100644 --- a/src/gui/qgsmapcanvas.cpp +++ b/src/gui/qgsmapcanvas.cpp @@ -1540,7 +1540,7 @@ void QgsMapCanvas::mouseMoveEvent( QMouseEvent * e ) -/** Sets the map tool currently being used on the canvas */ +//! Sets the map tool currently being used on the canvas void QgsMapCanvas::setMapTool( QgsMapTool* tool ) { if ( !tool ) @@ -1596,7 +1596,7 @@ void QgsMapCanvas::unsetMapTool( QgsMapTool* tool ) } } -/** Write property of QColor bgColor. */ +//! Write property of QColor bgColor. void QgsMapCanvas::setCanvasColor( const QColor & theColor ) { // background of map's pixmap @@ -1906,7 +1906,7 @@ void QgsMapCanvas::writeProject( QDomDocument & doc ) // TODO: store only units, extent, projections, dest CRS } -/** Ask user which datum transform to use*/ +//! Ask user which datum transform to use void QgsMapCanvas::getDatumTransformInfo( const QgsMapLayer* ml, const QString& srcAuthId, const QString& destAuthId ) { if ( !ml ) diff --git a/src/gui/qgsmapcanvas.h b/src/gui/qgsmapcanvas.h index 54ae4af82f09..6914e0fb7fa0 100644 --- a/src/gui/qgsmapcanvas.h +++ b/src/gui/qgsmapcanvas.h @@ -91,10 +91,10 @@ class GUI_EXPORT QgsMapCanvasLayer private: QgsMapLayer* mLayer; - /** Flag whether layer is visible */ + //! Flag whether layer is visible bool mVisible; - /** Flag whether layer is shown in overview */ + //! Flag whether layer is shown in overview bool mInOverview; }; @@ -234,10 +234,10 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView @param ids the feature ids*/ void panToFeatureIds( QgsVectorLayer* layer, const QgsFeatureIds& ids ); - /** Pan to the selected features of current (vector) layer keeping same extent. */ + //! Pan to the selected features of current (vector) layer keeping same extent. void panToSelected( QgsVectorLayer* layer = nullptr ); - /** \brief Sets the map tool currently being used on the canvas */ + //! \brief Sets the map tool currently being used on the canvas void setMapTool( QgsMapTool* mapTool ); /** \brief Unset the current map tool or last non zoom tool @@ -248,19 +248,19 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView */ void unsetMapTool( QgsMapTool* mapTool ); - /** Returns the currently active tool*/ + //! Returns the currently active tool QgsMapTool* mapTool(); - /** Write property of QColor bgColor. */ + //! Write property of QColor bgColor. void setCanvasColor( const QColor & _newVal ); - /** Read property of QColor bgColor. */ + //! Read property of QColor bgColor. QColor canvasColor() const; - /** Set color of selected vector features */ + //! Set color of selected vector features //! @note added in 2.4 void setSelectionColor( const QColor& color ); - /** Emits signal scaleChanged to update scale in main window */ + //! Emits signal scaleChanged to update scale in main window void updateScale(); //! return the map layer at position index in the layer stack @@ -431,7 +431,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView public slots: - /** Repaints the canvas map*/ + //! Repaints the canvas map void refresh(); //! Receives signal about selection change, and pass it on with layer info @@ -451,7 +451,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView //! State of render suppression flag bool renderFlag() {return mRenderFlag;} - /** A simple helper method to find out if on the fly projections are enabled or not */ + //! A simple helper method to find out if on the fly projections are enabled or not bool hasCrsTransformEnabled(); //! stop rendering (if there is any right now) @@ -527,11 +527,11 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView void renderComplete( QPainter * ); // ### QGIS 3: renamte to mapRefreshFinished() - /** Emitted when canvas finished a refresh request. */ + //! Emitted when canvas finished a refresh request. void mapCanvasRefreshed(); // ### QGIS 3: rename to mapRefreshStarted() - /** Emitted when the canvas is about to be rendered. */ + //! Emitted when the canvas is about to be rendered. void renderStarting(); //! Emitted when a new set of layers has been received diff --git a/src/gui/qgsmapcanvassnapper.h b/src/gui/qgsmapcanvassnapper.h index 794e0acb5fc9..455f006e99ee 100644 --- a/src/gui/qgsmapcanvassnapper.h +++ b/src/gui/qgsmapcanvassnapper.h @@ -72,9 +72,9 @@ class GUI_EXPORT QgsMapCanvasSnapper void setMapCanvas( QgsMapCanvas* canvas ); private: - /** Pointer to the map canvas*/ + //! Pointer to the map canvas QgsMapCanvas* mMapCanvas; - /** The object which does the snapping operations*/ + //! The object which does the snapping operations QgsSnapper* mSnapper; QgsMapCanvasSnapper( const QgsMapCanvasSnapper& rh ); diff --git a/src/gui/qgsmaplayeractionregistry.cpp b/src/gui/qgsmaplayeractionregistry.cpp index d5cab72b7b78..017223cb052e 100644 --- a/src/gui/qgsmaplayeractionregistry.cpp +++ b/src/gui/qgsmaplayeractionregistry.cpp @@ -26,7 +26,7 @@ QgsMapLayerAction::QgsMapLayerAction( const QString& name, QObject* parent, Targ { } -/** Creates a map layer action which can run only on a specific layer*/ +//! Creates a map layer action which can run only on a specific layer QgsMapLayerAction::QgsMapLayerAction( const QString& name, QObject* parent, QgsMapLayer* layer, Targets targets, const QIcon& icon ) : QAction( icon, name, parent ) , mSingleLayer( true ) @@ -37,7 +37,7 @@ QgsMapLayerAction::QgsMapLayerAction( const QString& name, QObject* parent, QgsM { } -/** Creates a map layer action which can run on a specific type of layer*/ +//! Creates a map layer action which can run on a specific type of layer QgsMapLayerAction::QgsMapLayerAction( const QString& name, QObject* parent, QgsMapLayer::LayerType layerType, Targets targets, const QIcon& icon ) : QAction( icon, name, parent ) , mSingleLayer( false ) diff --git a/src/gui/qgsmaplayeractionregistry.h b/src/gui/qgsmaplayeractionregistry.h index 574bb18c448c..90dab76835b1 100644 --- a/src/gui/qgsmaplayeractionregistry.h +++ b/src/gui/qgsmaplayeractionregistry.h @@ -55,31 +55,31 @@ class GUI_EXPORT QgsMapLayerAction : public QAction ~QgsMapLayerAction(); - /** True if action can run using the specified layer */ + //! True if action can run using the specified layer bool canRunUsingLayer( QgsMapLayer* layer ) const; - /** Triggers the action with the specified layer and list of feature. */ + //! Triggers the action with the specified layer and list of feature. void triggerForFeatures( QgsMapLayer* layer, const QList& featureList ); - /** Triggers the action with the specified layer and feature. */ + //! Triggers the action with the specified layer and feature. void triggerForFeature( QgsMapLayer* layer, const QgsFeature* feature ); - /** Triggers the action with the specified layer. */ + //! Triggers the action with the specified layer. void triggerForLayer( QgsMapLayer* layer ); - /** Define the targets of the action */ + //! Define the targets of the action void setTargets( Targets targets ) {mTargets = targets;} - /** Return availibity of action */ + //! Return availibity of action const Targets& targets() const {return mTargets;} signals: - /** Triggered when action has been run for a specific list of features */ + //! Triggered when action has been run for a specific list of features void triggeredForFeatures( QgsMapLayer* layer, const QList& featureList ); - /** Triggered when action has been run for a specific feature */ + //! Triggered when action has been run for a specific feature void triggeredForFeature( QgsMapLayer* layer, const QgsFeature& feature ); - /** Triggered when action has been run for a specific layer */ + //! Triggered when action has been run for a specific layer void triggeredForLayer( QgsMapLayer* layer ); private: @@ -113,18 +113,18 @@ class GUI_EXPORT QgsMapLayerActionRegistry : public QObject ~QgsMapLayerActionRegistry(); - /** Adds a map layer action to the registry*/ + //! Adds a map layer action to the registry void addMapLayerAction( QgsMapLayerAction * action ); - /** Returns the map layer actions which can run on the specified layer*/ + //! Returns the map layer actions which can run on the specified layer QList mapLayerActions( QgsMapLayer* layer, QgsMapLayerAction::Targets targets = QgsMapLayerAction::AllActions ); - /** Removes a map layer action from the registry*/ + //! Removes a map layer action from the registry bool removeMapLayerAction( QgsMapLayerAction *action ); - /** Sets the default action for a layer*/ + //! Sets the default action for a layer void setDefaultActionForLayer( QgsMapLayer* layer, QgsMapLayerAction* action ); - /** Returns the default action for a layer*/ + //! Returns the default action for a layer QgsMapLayerAction * defaultActionForLayer( QgsMapLayer* layer ); protected: @@ -134,7 +134,7 @@ class GUI_EXPORT QgsMapLayerActionRegistry : public QObject QList< QgsMapLayerAction* > mMapLayerActionList; signals: - /** Triggered when an action is added or removed from the registry */ + //! Triggered when an action is added or removed from the registry void changed(); private: diff --git a/src/gui/qgsmaplayerconfigwidgetfactory.h b/src/gui/qgsmaplayerconfigwidgetfactory.h index 6bcf8c3aaece..061e91de6e8d 100644 --- a/src/gui/qgsmaplayerconfigwidgetfactory.h +++ b/src/gui/qgsmaplayerconfigwidgetfactory.h @@ -31,13 +31,13 @@ class GUI_EXPORT QgsMapLayerConfigWidgetFactory { public: - /** Constructor */ + //! Constructor QgsMapLayerConfigWidgetFactory(); - /** Constructor */ + //! Constructor QgsMapLayerConfigWidgetFactory( const QString &title, const QIcon &icon ); - /** Destructor */ + //! Destructor virtual ~QgsMapLayerConfigWidgetFactory(); /** diff --git a/src/gui/qgsmapmouseevent.h b/src/gui/qgsmapmouseevent.h index a18223aa9261..08642b23acb9 100644 --- a/src/gui/qgsmapmouseevent.h +++ b/src/gui/qgsmapmouseevent.h @@ -37,8 +37,8 @@ class GUI_EXPORT QgsMapMouseEvent : public QMouseEvent enum SnappingMode { NoSnapping, - SnapProjectConfig, //!< snap according to the configuration set in the snapping settings - SnapAllLayers, //!< snap to all rendered layers (tolerance and type from defaultSettings()) + SnapProjectConfig, //!< Snap according to the configuration set in the snapping settings + SnapAllLayers, //!< Snap to all rendered layers (tolerance and type from defaultSettings()) }; /** diff --git a/src/gui/qgsmaptool.h b/src/gui/qgsmaptool.h index 0baaa6194032..e059e2333a7c 100644 --- a/src/gui/qgsmaptool.h +++ b/src/gui/qgsmaptool.h @@ -61,8 +61,8 @@ class GUI_EXPORT QgsMapTool : public QObject Transient = 1 << 1, /*!< Indicates that this map tool performs a transient (one-off) operation. If it does, the tool can be operated once and then a previous map tool automatically restored. */ - EditTool = 1 << 2, /*!< Map tool is an edit tool, which can only be used when layer is editable*/ - AllowZoomRect = 1 << 3, /*!< Allow zooming by rectangle (by holding shift and dragging) while the tool is active*/ + EditTool = 1 << 2, //!< Map tool is an edit tool, which can only be used when layer is editable + AllowZoomRect = 1 << 3, //!< Allow zooming by rectangle (by holding shift and dragging) while the tool is active }; Q_DECLARE_FLAGS( Flags, Flag ) @@ -106,17 +106,17 @@ class GUI_EXPORT QgsMapTool : public QObject * the previously used toolbutton to pop out. */ void setAction( QAction* action ); - /** Return associated action with map tool or NULL if no action is associated */ + //! Return associated action with map tool or NULL if no action is associated QAction* action(); /** Use this to associate a button to this maptool. It has the same meaning * as setAction() function except it works with a button instead of an QAction. */ void setButton( QAbstractButton* button ); - /** Return associated button with map tool or NULL if no button is associated */ + //! Return associated button with map tool or NULL if no button is associated QAbstractButton* button(); - /** Set a user defined cursor */ + //! Set a user defined cursor virtual void setCursor( const QCursor& cursor ); //! called when set as currently active map tool diff --git a/src/gui/qgsmaptooladvanceddigitizing.h b/src/gui/qgsmaptooladvanceddigitizing.h index f4d74efd358c..d5796758d5a8 100644 --- a/src/gui/qgsmaptooladvanceddigitizing.h +++ b/src/gui/qgsmaptooladvanceddigitizing.h @@ -124,10 +124,10 @@ class GUI_EXPORT QgsMapToolAdvancedDigitizing : public QgsMapToolEdit //! The capture mode in which this tool operates CaptureMode mCaptureMode; - bool mSnapOnPress; //!< snap on press - bool mSnapOnRelease; //!< snap on release - bool mSnapOnMove; //!< snap on move - bool mSnapOnDoubleClick; //!< snap on double click + bool mSnapOnPress; //!< Snap on press + bool mSnapOnRelease; //!< Snap on release + bool mSnapOnMove; //!< Snap on move + bool mSnapOnDoubleClick; //!< Snap on double click private slots: /** diff --git a/src/gui/qgsmaptoolcapture.h b/src/gui/qgsmaptoolcapture.h index 1e91e9078e59..07617bdf771b 100644 --- a/src/gui/qgsmaptoolcapture.h +++ b/src/gui/qgsmaptoolcapture.h @@ -49,7 +49,7 @@ class GUI_EXPORT QgsMapToolCapture : public QgsMapToolAdvancedDigitizing //! deactive the tool virtual void deactivate() override; - /** Adds a whole curve (e.g. circularstring) to the captured geometry. Curve must be in map CRS*/ + //! Adds a whole curve (e.g. circularstring) to the captured geometry. Curve must be in map CRS int addCurve( QgsCurve* c ); /** @@ -134,7 +134,7 @@ class GUI_EXPORT QgsMapToolCapture : public QgsMapToolAdvancedDigitizing */ int addVertex( const QgsPoint& mapPoint, const QgsPointLocator::Match &match ); - /** Removes the last vertex from mRubberBand and mCaptureList*/ + //! Removes the last vertex from mRubberBand and mCaptureList void undo(); /** @@ -190,16 +190,16 @@ class GUI_EXPORT QgsMapToolCapture : public QgsMapToolAdvancedDigitizing bool tracingAddVertex( const QgsPoint& point ); private: - /** Flag to indicate a map canvas capture operation is taking place */ + //! Flag to indicate a map canvas capture operation is taking place bool mCapturing; - /** Rubber band for polylines and polygons */ + //! Rubber band for polylines and polygons QgsRubberBand* mRubberBand; - /** Temporary rubber band for polylines and polygons. this connects the last added point to the mouse cursor position */ + //! Temporary rubber band for polylines and polygons. this connects the last added point to the mouse cursor position QgsRubberBand* mTempRubberBand; - /** List to store the points of digitised lines and polygons (in layer coordinates)*/ + //! List to store the points of digitised lines and polygons (in layer coordinates) QgsCompoundCurve mCaptureCurve; void validateGeometry(); diff --git a/src/gui/qgsmaptooledit.h b/src/gui/qgsmaptooledit.h index 098a5f13b12f..96df2e74f040 100644 --- a/src/gui/qgsmaptooledit.h +++ b/src/gui/qgsmaptooledit.h @@ -49,7 +49,7 @@ class GUI_EXPORT QgsMapToolEdit: public QgsMapTool QgsGeometryRubberBand* createGeometryRubberBand( QgsWkbTypes::GeometryType geometryType = QgsWkbTypes::LineGeometry, bool alternativeBand = false ) const; - /** Returns the current vector layer of the map canvas or 0*/ + //! Returns the current vector layer of the map canvas or 0 QgsVectorLayer* currentVectorLayer(); /** Adds vertices to other features to keep topology up to date, e.g. to neighbouring polygons. @@ -58,9 +58,9 @@ class GUI_EXPORT QgsMapToolEdit: public QgsMapTool */ int addTopologicalPoints( const QList& geom ); - /** Display a timed message bar noting the active layer is not vector. */ + //! Display a timed message bar noting the active layer is not vector. void notifyNotVectorLayer(); - /** Display a timed message bar noting the active vector layer is not editable. */ + //! Display a timed message bar noting the active vector layer is not editable. void notifyNotEditableLayer(); }; diff --git a/src/gui/qgsmaptoolidentify.h b/src/gui/qgsmaptoolidentify.h index 9a795a370464..50ee925dbc83 100644 --- a/src/gui/qgsmaptoolidentify.h +++ b/src/gui/qgsmaptoolidentify.h @@ -151,7 +151,7 @@ class GUI_EXPORT QgsMapToolIdentify : public QgsMapTool QgsIdentifyMenu* mIdentifyMenu; - /** Call the right method depending on layer type */ + //! Call the right method depending on layer type bool identifyLayer( QList *results, QgsMapLayer *layer, const QgsPoint& point, const QgsRectangle& viewExtent, double mapUnitsPerPixel, QgsMapToolIdentify::LayerType layerType = AllLayers ); bool identifyRasterLayer( QList *results, QgsRasterLayer *layer, QgsPoint point, const QgsRectangle& viewExtent, double mapUnitsPerPixel ); diff --git a/src/gui/qgsnewgeopackagelayerdialog.h b/src/gui/qgsnewgeopackagelayerdialog.h index 8bba4fb8501f..4ce0ae302e48 100644 --- a/src/gui/qgsnewgeopackagelayerdialog.h +++ b/src/gui/qgsnewgeopackagelayerdialog.h @@ -30,7 +30,7 @@ class GUI_EXPORT QgsNewGeoPackageLayerDialog: public QDialog, private Ui::QgsNew Q_OBJECT public: - /** Constructor */ + //! Constructor QgsNewGeoPackageLayerDialog( QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); ~QgsNewGeoPackageLayerDialog(); diff --git a/src/gui/qgsnewmemorylayerdialog.h b/src/gui/qgsnewmemorylayerdialog.h index ff62c8bae341..4bdab8fff331 100644 --- a/src/gui/qgsnewmemorylayerdialog.h +++ b/src/gui/qgsnewmemorylayerdialog.h @@ -41,13 +41,13 @@ class GUI_EXPORT QgsNewMemoryLayerDialog: public QDialog, private Ui::QgsNewMemo QgsNewMemoryLayerDialog( QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); ~QgsNewMemoryLayerDialog(); - /** Returns the selected geometry type*/ + //! Returns the selected geometry type QgsWkbTypes::Type selectedType() const; - /** Returns the selected crs*/ + //! Returns the selected crs QgsCoordinateReferenceSystem crs() const; - /** Returns the layer name*/ + //! Returns the layer name QString layerName() const; private: diff --git a/src/gui/qgsnewvectorlayerdialog.h b/src/gui/qgsnewvectorlayerdialog.h index 5a8530456adb..0f0a247e02e4 100644 --- a/src/gui/qgsnewvectorlayerdialog.h +++ b/src/gui/qgsnewvectorlayerdialog.h @@ -38,15 +38,15 @@ class GUI_EXPORT QgsNewVectorLayerDialog: public QDialog, private Ui::QgsNewVect QgsNewVectorLayerDialog( QWidget *parent = nullptr, Qt::WindowFlags fl = QgisGui::ModalDialogFlags ); ~QgsNewVectorLayerDialog(); - /** Returns the selected geometry type*/ + //! Returns the selected geometry type QgsWkbTypes::Type selectedType() const; - /** Appends the chosen attribute names and types to at*/ + //! Appends the chosen attribute names and types to at void attributes( QList< QPair >& at ) const; - /** Returns the file format for storage*/ + //! Returns the file format for storage QString selectedFileFormat() const; - /** Returns the file format for storage*/ + //! Returns the file format for storage QString selectedFileEncoding() const; - /** Returns the selected crs id*/ + //! Returns the selected crs id int selectedCrsId() const; protected slots: diff --git a/src/gui/qgsowssourceselect.h b/src/gui/qgsowssourceselect.h index c3898f5fa876..aefec6659bba 100644 --- a/src/gui/qgsowssourceselect.h +++ b/src/gui/qgsowssourceselect.h @@ -49,7 +49,7 @@ class GUI_EXPORT QgsOWSSourceSelect : public QDialog, public Ui::QgsOWSSourceSel Q_OBJECT public: - /** Formats supported by provider */ + //! Formats supported by provider struct SupportedFormat { QString format; diff --git a/src/gui/qgsprojectbadlayerguihandler.h b/src/gui/qgsprojectbadlayerguihandler.h index a773bb4fea82..bf3e97cd4a75 100644 --- a/src/gui/qgsprojectbadlayerguihandler.h +++ b/src/gui/qgsprojectbadlayerguihandler.h @@ -32,11 +32,11 @@ class GUI_EXPORT QgsProjectBadLayerGuiHandler : public QObject, public QgsProjec virtual void handleBadLayers( const QList& layers ) override; - /** Flag to store the Ignore button press of MessageBox used by QgsLegend */ + //! Flag to store the Ignore button press of MessageBox used by QgsLegend static bool mIgnore; protected: - /** This is used to locate files that have moved or otherwise are missing */ + //! This is used to locate files that have moved or otherwise are missing bool findMissingFile( const QString& fileFilters, QDomNode& layerNode ); /** diff --git a/src/gui/qgsprojectionselectionwidget.h b/src/gui/qgsprojectionselectionwidget.h index 32830c5966b0..25019b5d7913 100644 --- a/src/gui/qgsprojectionselectionwidget.h +++ b/src/gui/qgsprojectionselectionwidget.h @@ -41,11 +41,11 @@ class GUI_EXPORT QgsProjectionSelectionWidget : public QWidget */ enum CrsOption { - LayerCrs, /*!< optional layer CRS */ - ProjectCrs, /*!< current project CRS (if OTF reprojection enabled) */ - CurrentCrs, /*!< current user selected CRS */ - DefaultCrs, /*!< global default QGIS CRS */ - RecentCrs /*!< recently used CRS */ + LayerCrs, //!< Optional layer CRS + ProjectCrs, //!< Current project CRS (if OTF reprojection enabled) + CurrentCrs, //!< Current user selected CRS + DefaultCrs, //!< Global default QGIS CRS + RecentCrs //!< Recently used CRS }; explicit QgsProjectionSelectionWidget( QWidget *parent = nullptr ); diff --git a/src/gui/qgsprojectionselector.h b/src/gui/qgsprojectionselector.h index 5ffc59f8f954..720f9cf153c1 100644 --- a/src/gui/qgsprojectionselector.h +++ b/src/gui/qgsprojectionselector.h @@ -108,10 +108,10 @@ class GUI_EXPORT QgsProjectionSelector : public QWidget, private Ui::QgsProjecti void pushProjectionToFront(); protected: - /** Used to ensure the projection list view is actually populated */ + //! Used to ensure the projection list view is actually populated void showEvent( QShowEvent * theEvent ) override; - /** Used to manage column sizes */ + //! Used to manage column sizes void resizeEvent( QResizeEvent * theEvent ) override; private: @@ -147,7 +147,7 @@ class GUI_EXPORT QgsProjectionSelector : public QWidget, private Ui::QgsProjecti */ QString getSelectedExpression( const QString& e ); - /** Show the user a warning if the srs database could not be found */ + //! Show the user a warning if the srs database could not be found void showDBMissingWarning( const QString& theFileName ); // List view nodes for the tree view of projections //! User defined projections node diff --git a/src/gui/qgsrubberband.h b/src/gui/qgsrubberband.h index 9de42aa49fcf..38dba39a312e 100644 --- a/src/gui/qgsrubberband.h +++ b/src/gui/qgsrubberband.h @@ -33,7 +33,7 @@ class GUI_EXPORT QgsRubberBand: public QgsMapCanvasItem { public: - /** Icons */ + //! Icons enum IconType { /** @@ -247,10 +247,10 @@ class GUI_EXPORT QgsRubberBand: public QgsMapCanvasItem QBrush mBrush; QPen mPen; - /** The size of the icon for points. */ + //! The size of the icon for points. int mIconSize; - /** Icon to be shown. */ + //! Icon to be shown. IconType mIconType; /** diff --git a/src/gui/qgssearchquerybuilder.cpp b/src/gui/qgssearchquerybuilder.cpp index 905c58a2b94e..51e589479cb5 100644 --- a/src/gui/qgssearchquerybuilder.cpp +++ b/src/gui/qgssearchquerybuilder.cpp @@ -130,7 +130,7 @@ void QgsSearchQueryBuilder::getFieldValues( int limit ) mModelValues->blockSignals( true ); lstValues->setUpdatesEnabled( false ); - /** MH: keep already inserted values in a set. Querying is much faster compared to QStandardItemModel::findItems*/ + //! MH: keep already inserted values in a set. Querying is much faster compared to QStandardItemModel::findItems QSet insertedValues; while ( fit.nextFeature( feat ) && diff --git a/src/gui/qgssourceselectdialog.cpp b/src/gui/qgssourceselectdialog.cpp index 09b16433a79d..bbe33ca18692 100644 --- a/src/gui/qgssourceselectdialog.cpp +++ b/src/gui/qgssourceselectdialog.cpp @@ -43,7 +43,7 @@ class QgsSourceSelectItemDelegate : public QItemDelegate { public: - /** Constructor */ + //! Constructor QgsSourceSelectItemDelegate( QObject *parent = 0 ) : QItemDelegate( parent ) { } QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const override; }; diff --git a/src/gui/qgssourceselectdialog.h b/src/gui/qgssourceselectdialog.h index 2718fdafca7b..c5738b3da309 100644 --- a/src/gui/qgssourceselectdialog.h +++ b/src/gui/qgssourceselectdialog.h @@ -33,20 +33,20 @@ class GUI_EXPORT QgsSourceSelectDialog : public QDialog, protected Ui::QgsSource Q_OBJECT public: - /** Whether the dialog is for a map service or a feature service */ + //! Whether the dialog is for a map service or a feature service enum ServiceType { MapService, FeatureService }; - /** Constructor */ + //! Constructor QgsSourceSelectDialog( const QString& serviceName, ServiceType serviceType, QWidget* parent, Qt::WindowFlags fl ); - /** Destructor */ + //! Destructor ~QgsSourceSelectDialog(); - /** Sets the current extent and CRS. Used to select an appropriate CRS and possibly to retrieve data only in the current extent */ + //! Sets the current extent and CRS. Used to select an appropriate CRS and possibly to retrieve data only in the current extent void setCurrentExtentAndCrs( const QgsRectangle& canvasExtent, const QgsCoordinateReferenceSystem& canvasCrs ); signals: - /** Emitted when a layer is added from the dialog */ + //! Emitted when a layer is added from the dialog void addLayer( QString uri, QString typeName ); - /** Emitted when the connections for the service were changed */ + //! Emitted when the connections for the service were changed void connectionsChanged(); protected: @@ -63,20 +63,20 @@ class GUI_EXPORT QgsSourceSelectDialog : public QDialog, protected Ui::QgsSource QgsRectangle mCanvasExtent; QgsCoordinateReferenceSystem mCanvasCrs; - /** To be implemented in the child class. Called when a new connection is initiated. */ + //! To be implemented in the child class. Called when a new connection is initiated. virtual bool connectToService( const QgsOwsConnection& connection ) = 0; - /** May be implemented in child classes for services which support customized queries. */ + //! May be implemented in child classes for services which support customized queries. virtual void buildQuery( const QgsOwsConnection&, const QModelIndex& ) {} - /** To be implemented in the child class. Constructs an URI for the specified service layer. */ + //! To be implemented in the child class. Constructs an URI for the specified service layer. virtual QString getLayerURI( const QgsOwsConnection& connection, const QString& layerTitle, const QString& layerName, const QString& crs = QString(), const QString& filter = QString(), const QgsRectangle& bBox = QgsRectangle() ) const = 0; - /** Updates the UI for the list of available image encodings from the specified list. */ + //! Updates the UI for the list of available image encodings from the specified list. void populateImageEncodings( const QStringList& availableEncodings ); - /** Returns the selected image encoding. */ + //! Returns the selected image encoding. QString getSelectedImageEncoding() const; private: diff --git a/src/gui/qgssublayersdialog.h b/src/gui/qgssublayersdialog.h index 4a024c01873f..992975c7c710 100644 --- a/src/gui/qgssublayersdialog.h +++ b/src/gui/qgssublayersdialog.h @@ -41,10 +41,10 @@ class GUI_EXPORT QgsSublayersDialog : public QDialog, private Ui::QgsSublayersDi { LayerDefinition() : layerId( -1 ), count( -1 ) {} - int layerId; //!< identifier of the layer (one unique layer id may have multiple types though) - QString layerName; //!< name of the layer (not necessarily unique) - int count; //!< number of features (might be unused) - QString type; //!< extra type depending on the use (e.g. geometry type for vector sublayers) + int layerId; //!< Identifier of the layer (one unique layer id may have multiple types though) + QString layerName; //!< Name of the layer (not necessarily unique) + int count; //!< Number of features (might be unused) + QString type; //!< Extra type depending on the use (e.g. geometry type for vector sublayers) } LayerDefinition; //! List of layer definitions for the purpose of this dialog @@ -69,8 +69,8 @@ class GUI_EXPORT QgsSublayersDialog : public QDialog, private Ui::QgsSublayersDi protected: QString mName; QStringList mSelectedSubLayers; - bool mShowCount; //!< whether to show number of features in the table - bool mShowType; //!< whether to show type in the table + bool mShowCount; //!< Whether to show number of features in the table + bool mShowType; //!< Whether to show type in the table }; #endif diff --git a/src/gui/qgstextannotationitem.h b/src/gui/qgstextannotationitem.h index a30b7218923c..0f402ab9a4a7 100644 --- a/src/gui/qgstextannotationitem.h +++ b/src/gui/qgstextannotationitem.h @@ -29,9 +29,9 @@ class GUI_EXPORT QgsTextAnnotationItem: public QgsAnnotationItem QgsTextAnnotationItem( QgsMapCanvas* canvas ); ~QgsTextAnnotationItem(); - /** Returns document (caller takes ownership)*/ + //! Returns document (caller takes ownership) QTextDocument* document() const; - /** Sets document (does not take ownership)*/ + //! Sets document (does not take ownership) void setDocument( const QTextDocument* doc ); void writeXml( QDomDocument& doc ) const override; diff --git a/src/gui/qgstreewidgetitem.h b/src/gui/qgstreewidgetitem.h index 9232b7eb930e..703049193125 100644 --- a/src/gui/qgstreewidgetitem.h +++ b/src/gui/qgstreewidgetitem.h @@ -144,14 +144,14 @@ class GUI_EXPORT QgsTreeWidgetItemObject: public QObject, public QgsTreeWidgetIt */ explicit QgsTreeWidgetItemObject( int type = Type ); - /** Constructs a tree widget item of the specified type and appends it to the items in the given parent. */ + //! Constructs a tree widget item of the specified type and appends it to the items in the given parent. explicit QgsTreeWidgetItemObject( QTreeWidget * parent, int type = Type ); - /** Sets the value for the item's column and role to the given value. */ + //! Sets the value for the item's column and role to the given value. virtual void setData( int column, int role, const QVariant & value ); signals: - /** This signal is emitted when the contents of the column in the specified item has been edited by the user. */ + //! This signal is emitted when the contents of the column in the specified item has been edited by the user. void itemEdited( QTreeWidgetItem* item, int column ); }; diff --git a/src/gui/qgsunitselectionwidget.h b/src/gui/qgsunitselectionwidget.h index 3fd8ae789fd2..e752021d099a 100644 --- a/src/gui/qgsunitselectionwidget.h +++ b/src/gui/qgsunitselectionwidget.h @@ -164,7 +164,7 @@ class GUI_EXPORT QgsUnitSelectionWidget : public QWidget, private Ui::QgsUnitSel */ void setUnits( const QgsUnitTypes::RenderUnitList& units ); - /** Get the selected unit index */ + //! Get the selected unit index int getUnit() const { return mUnitCombo->currentIndex(); } /** Returns the current predefined selected unit (if applicable). @@ -184,10 +184,10 @@ class GUI_EXPORT QgsUnitSelectionWidget : public QWidget, private Ui::QgsUnitSel */ void setUnit( QgsUnitTypes::RenderUnit unit ); - /** Returns the map unit scale */ + //! Returns the map unit scale QgsMapUnitScale getMapUnitScale() const { return mMapUnitScale; } - /** Sets the map unit scale */ + //! Sets the map unit scale void setMapUnitScale( const QgsMapUnitScale& scale ) { mMapUnitScale = scale; } /** Sets the map canvas associated with the widget. This allows the widget to retrieve the current diff --git a/src/gui/raster/qgsmultibandcolorrendererwidget.h b/src/gui/raster/qgsmultibandcolorrendererwidget.h index b23f9836e90c..6c121ac0df7f 100644 --- a/src/gui/raster/qgsmultibandcolorrendererwidget.h +++ b/src/gui/raster/qgsmultibandcolorrendererwidget.h @@ -62,7 +62,7 @@ class GUI_EXPORT QgsMultiBandColorRendererWidget: public QgsRasterRendererWidget void createValidators(); void setCustomMinMaxValues( QgsMultiBandColorRenderer* r, const QgsRasterDataProvider* provider, int redBand, int GreenBand, int blueBand ); - /** Reads min/max values from contrast enhancement and fills values into the min/max line edits*/ + //! Reads min/max values from contrast enhancement and fills values into the min/max line edits void setMinMaxValue( const QgsContrastEnhancement* ce, QLineEdit* minEdit, QLineEdit* maxEdit ); QgsRasterMinMaxWidget * mMinMaxWidget; }; diff --git a/src/gui/raster/qgsrasterhistogramwidget.h b/src/gui/raster/qgsrasterhistogramwidget.h index b56bc32717b4..171685fcae72 100644 --- a/src/gui/raster/qgsrasterhistogramwidget.h +++ b/src/gui/raster/qgsrasterhistogramwidget.h @@ -45,52 +45,52 @@ class GUI_EXPORT QgsRasterHistogramWidget : public QgsMapLayerConfigWidget, priv QgsRasterHistogramWidget( QgsRasterLayer *lyr, QWidget *parent = nullptr ); ~QgsRasterHistogramWidget(); - /** Save the histogram as an image to disk */ + //! Save the histogram as an image to disk bool histoSaveAsImage( const QString& theFilename, int width = 600, int height = 600, int quality = -1 ); - /** Set the renderer widget (or just its name if there is no widget) */ + //! Set the renderer widget (or just its name if there is no widget) void setRendererWidget( const QString& name, QgsRasterRendererWidget* rendererWidget = nullptr ); - /** Activate the histogram widget */ + //! Activate the histogram widget void setActive( bool theActiveFlag ); - /** \brief Compute the histogram on demand. */ + //! \brief Compute the histogram on demand. bool computeHistogram( bool forceComputeFlag ); - /** Apply a histoActionTriggered() event. */ + //! Apply a histoActionTriggered() event. void histoAction( const QString &actionName, bool actionFlag = true ); - /** Apply a histoActionTriggered() event. */ + //! Apply a histoActionTriggered() event. void setSelectedBand( int index ); public slots: - /** \brief slot executed when user wishes to refresh raster histogramwidget */ + //! \brief slot executed when user wishes to refresh raster histogramwidget void refreshHistogram(); - /** This slot lets you save the histogram as an image to disk */ + //! This slot lets you save the histogram as an image to disk void on_mSaveAsImageButton_clicked(); void apply() override; private slots: - /** Used when the histogram band selector changes, or when tab is loaded. */ + //! Used when the histogram band selector changes, or when tab is loaded. void on_cboHistoBand_currentIndexChanged( int ); - /** Applies the selected min/max values to the renderer widget. */ + //! Applies the selected min/max values to the renderer widget. void applyHistoMin(); void applyHistoMax(); - /** Button to activate picking of the min/max value on the graph. */ + //! Button to activate picking of the min/max value on the graph. void on_btnHistoMin_toggled(); void on_btnHistoMax_toggled(); - /** Called when a selection has been made using the plot picker. */ + //! Called when a selection has been made using the plot picker. void histoPickerSelected( QPointF ); /** Called when a selection has been made using the plot picker (for qwt5 only). @note not available in python bindings */ void histoPickerSelectedQwt5( QwtDoublePoint ); - /** Various actions that are stored in btnHistoActions. */ + //! Various actions that are stored in btnHistoActions. void histoActionTriggered( QAction* ); - /** Draw the min/max markers on the histogram plot. */ + //! Draw the min/max markers on the histogram plot. void updateHistoMarkers(); - /** Button to compute the histogram, appears when no cached histogram is available. */ + //! Button to compute the histogram, appears when no cached histogram is available. void on_btnHistoCompute_clicked(); private: @@ -102,11 +102,11 @@ class GUI_EXPORT QgsRasterHistogramWidget : public QgsMapLayerConfigWidget, priv ShowRGB = 2 }; - /** \brief Pointer to the raster layer that this property dilog changes the behaviour of. */ + //! \brief Pointer to the raster layer that this property dilog changes the behaviour of. QgsRasterLayer * mRasterLayer; - /** \brief Pointer to the renderer widget, to get/set min/max. */ + //! \brief Pointer to the renderer widget, to get/set min/max. QgsRasterRendererWidget* mRendererWidget; - /** \brief Name of the renderer widget (see QgsRasterRendererRegistry). */ + //! \brief Name of the renderer widget (see QgsRasterRendererRegistry). QString mRendererName; QwtPlotPicker* mHistoPicker; @@ -122,9 +122,9 @@ class GUI_EXPORT QgsRasterHistogramWidget : public QgsMapLayerConfigWidget, priv bool mHistoDrawLines; /* bool mHistoLoadApplyAll; */ HistoShowBands mHistoShowBands; - /** \brief Returns a list of selected bands in the histogram widget- or empty if there is no selection restriction. */ + //! \brief Returns a list of selected bands in the histogram widget- or empty if there is no selection restriction. QList< int > histoSelectedBands(); - /** \brief Returns a list of selected bands in the renderer widget. */ + //! \brief Returns a list of selected bands in the renderer widget. QList< int > rendererSelectedBands(); QPair< QString, QString > rendererMinMax( int theBandNo ); }; diff --git a/src/gui/raster/qgsrasterminmaxwidget.h b/src/gui/raster/qgsrasterminmaxwidget.h index 8b96c56ddc50..b1087c9619d8 100644 --- a/src/gui/raster/qgsrasterminmaxwidget.h +++ b/src/gui/raster/qgsrasterminmaxwidget.h @@ -64,7 +64,7 @@ class GUI_EXPORT QgsRasterMinMaxWidget: public QWidget, private Ui::QgsRasterMin */ QgsRectangle extent(); - /** Return the selected sample size. */ + //! Return the selected sample size. int sampleSize() { return cboAccuracy->currentIndex() == 0 ? 250000 : 0; } // Load programmaticaly with current values diff --git a/src/gui/raster/qgsrasterrendererwidget.h b/src/gui/raster/qgsrasterrendererwidget.h index a795aa6ed84b..2ddfde592939 100644 --- a/src/gui/raster/qgsrasterrendererwidget.h +++ b/src/gui/raster/qgsrasterrendererwidget.h @@ -90,10 +90,10 @@ class GUI_EXPORT QgsRasterRendererWidget: public QWidget protected: QgsRasterLayer* mRasterLayer; - /** Returns a band name for display. First choice is color name, otherwise band number*/ + //! Returns a band name for display. First choice is color name, otherwise band number QString displayBandName( int band ) const; - /** Current extent */ + //! Current extent QgsRectangle mExtent; //! Associated map canvas diff --git a/src/gui/raster/qgsrastertransparencywidget.h b/src/gui/raster/qgsrastertransparencywidget.h index de06b834693c..600f5152d4e4 100644 --- a/src/gui/raster/qgsrastertransparencywidget.h +++ b/src/gui/raster/qgsrastertransparencywidget.h @@ -56,36 +56,36 @@ class GUI_EXPORT QgsRasterTransparencyWidget : public QgsMapLayerConfigWidget, p void pixelSelected( const QgsPoint& canvasPoint ); - /** Transparency cell changed */ + //! Transparency cell changed void transparencyCellTextEdited( const QString & text ); - /** \brief slot executed when the transparency level changes. */ + //! \brief slot executed when the transparency level changes. void sliderTransparency_valueChanged( int theValue ); - /** \brief slot executed when user presses "Add Values From Display" button on the transparency page */ + //! \brief slot executed when user presses "Add Values From Display" button on the transparency page void on_pbnAddValuesFromDisplay_clicked(); - /** \brief slot executed when user presses "Add Values Manually" button on the transparency page */ + //! \brief slot executed when user presses "Add Values Manually" button on the transparency page void on_pbnAddValuesManually_clicked(); - /** \brief slot executed when user wishes to reset noNoDataValue and transparencyTable to default value */ + //! \brief slot executed when user wishes to reset noNoDataValue and transparencyTable to default value void on_pbnDefaultValues_clicked(); - /** \brief slot executed when user wishes to export transparency values */ + //! \brief slot executed when user wishes to export transparency values void on_pbnExportTransparentPixelValues_clicked(); - /** \brief slow executed when user wishes to import transparency values */ + //! \brief slow executed when user wishes to import transparency values void on_pbnImportTransparentPixelValues_clicked(); - /** \brief slot executed when user presses "Remove Selected Row" button on the transparency page */ + //! \brief slot executed when user presses "Remove Selected Row" button on the transparency page void on_pbnRemoveSelectedRow_clicked(); private: - /** \brief A constant that signals property not used */ + //! \brief A constant that signals property not used const QString TRSTRING_NOT_SET; bool rasterIsMultiBandColor(); - /** \brief Clear the current transparency table and populate the table with the correct types for current drawing mode and data type*/ + //! \brief Clear the current transparency table and populate the table with the correct types for current drawing mode and data type void populateTransparencyTable( QgsRasterRenderer* renderer ); void setupTransparencyTable( int nBands ); diff --git a/src/gui/raster/qgsrendererrasterpropertieswidget.h b/src/gui/raster/qgsrendererrasterpropertieswidget.h index 1c59290960d3..42ce972ed13d 100644 --- a/src/gui/raster/qgsrendererrasterpropertieswidget.h +++ b/src/gui/raster/qgsrendererrasterpropertieswidget.h @@ -70,13 +70,13 @@ class GUI_EXPORT QgsRendererRasterPropertiesWidget : public QgsMapLayerConfigWid void syncToLayer( QgsRasterLayer *layer ); private slots: - /** Slot to reset all color rendering options to default */ + //! Slot to reset all color rendering options to default void on_mResetColorRenderingBtn_clicked(); - /** Enable or disable saturation controls depending on choice of grayscale mode */ + //! Enable or disable saturation controls depending on choice of grayscale mode void toggleSaturationControls( int grayscaleMode ); - /** Enable or disable colorize controls depending on checkbox */ + //! Enable or disable colorize controls depending on checkbox void toggleColorizeControls( bool colorizeEnabled ); private: void setRendererWidget( const QString& rendererName ); diff --git a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp index 437711a42c09..b1d5de8ba0cf 100644 --- a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp +++ b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp @@ -218,7 +218,7 @@ void QgsSingleBandPseudoColorRendererWidget::autoLabel() } } -/** Extract the unit out of the current labels and set the unit field. */ +//! Extract the unit out of the current labels and set the unit field. void QgsSingleBandPseudoColorRendererWidget::setUnitFromLabels() { QgsColorRampShader::ColorRamp_TYPE interpolation = static_cast< QgsColorRampShader::ColorRamp_TYPE >( mColorInterpolationComboBox->currentData().toInt() ); @@ -761,7 +761,7 @@ void QgsSingleBandPseudoColorRendererWidget::on_mColormapTreeWidget_itemDoubleCl } } -/** Update the colormap table after manual edit. */ +//! Update the colormap table after manual edit. void QgsSingleBandPseudoColorRendererWidget::mColormapTreeWidget_itemEdited( QTreeWidgetItem* item, int column ) { Q_UNUSED( item ); diff --git a/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h b/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h index f6c1f298e03b..11303e800051 100644 --- a/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h +++ b/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h @@ -39,9 +39,9 @@ class GUI_EXPORT QgsArrowSymbolLayerWidget: public QgsSymbolLayerWidget, private */ static QgsSymbolLayerWidget* create( const QgsVectorLayer* layer ) { return new QgsArrowSymbolLayerWidget( layer ); } - /** Set the symbol layer */ + //! Set the symbol layer virtual void setSymbolLayer( QgsSymbolLayer* layer ) override; - /** Get the current symbol layer */ + //! Get the current symbol layer virtual QgsSymbolLayer* symbolLayer() override; private: diff --git a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.h b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.h index 70861dacebf3..e2f95eafb7dd 100644 --- a/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.h +++ b/src/gui/symbology-ng/qgsgraduatedsymbolrendererwidget.h @@ -100,13 +100,13 @@ class GUI_EXPORT QgsGraduatedSymbolRendererWidget : public QgsRendererWidget, pr void rangesClicked( const QModelIndex & idx ); void changeCurrentValue( QStandardItem * item ); - /** Adds a class manually to the classification*/ + //! Adds a class manually to the classification void addClass(); - /** Removes currently selected classes */ + //! Removes currently selected classes void deleteClasses(); - /** Removes all classes from the classification*/ + //! Removes all classes from the classification void deleteAllClasses(); - /** Toggle the link between classes boundaries */ + //! Toggle the link between classes boundaries void toggleBoundariesLink( bool linked ); void labelFormatChanged(); diff --git a/src/gui/symbology-ng/qgsheatmaprendererwidget.h b/src/gui/symbology-ng/qgsheatmaprendererwidget.h index cce959a500ee..18cff7579923 100644 --- a/src/gui/symbology-ng/qgsheatmaprendererwidget.h +++ b/src/gui/symbology-ng/qgsheatmaprendererwidget.h @@ -43,7 +43,7 @@ class GUI_EXPORT QgsHeatmapRendererWidget : public QgsRendererWidget, private Ui */ QgsHeatmapRendererWidget( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); - /** @returns the current feature renderer */ + //! @returns the current feature renderer virtual QgsFeatureRenderer* renderer() override; virtual void setContext( const QgsSymbolWidgetContext& context ) override; diff --git a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h index 526ac40a3283..938d83f98ee7 100644 --- a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h +++ b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h @@ -45,15 +45,15 @@ class GUI_EXPORT QgsInvertedPolygonRendererWidget : public QgsRendererWidget, pr */ QgsInvertedPolygonRendererWidget( QgsVectorLayer* layer, QgsStyle* style, QgsFeatureRenderer* renderer ); - /** @returns the current feature renderer */ + //! @returns the current feature renderer virtual QgsFeatureRenderer* renderer() override; void setContext( const QgsSymbolWidgetContext& context ) override; protected: - /** The mask renderer */ + //! The mask renderer QScopedPointer mRenderer; - /** The widget used to represent the mask's embedded renderer */ + //! The widget used to represent the mask's embedded renderer QScopedPointer mEmbeddedRendererWidget; private slots: diff --git a/src/gui/symbology-ng/qgsrendererwidget.h b/src/gui/symbology-ng/qgsrendererwidget.h index aa92910d9fa4..07ef7ece5173 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.h +++ b/src/gui/symbology-ng/qgsrendererwidget.h @@ -100,17 +100,17 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget protected slots: void contextMenuViewCategories( QPoint p ); - /** Change color of selected symbols*/ + //! Change color of selected symbols void changeSymbolColor(); - /** Change opacity of selected symbols*/ + //! Change opacity of selected symbols void changeSymbolTransparency(); - /** Change units mm/map units of selected symbols*/ + //! Change units mm/map units of selected symbols void changeSymbolUnit(); - /** Change line widths of selected symbols*/ + //! Change line widths of selected symbols void changeSymbolWidth(); - /** Change marker sizes of selected symbols*/ + //! Change marker sizes of selected symbols void changeSymbolSize(); - /** Change marker angles of selected symbols*/ + //! Change marker angles of selected symbols void changeSymbolAngle(); virtual void copy() {} diff --git a/src/gui/symbology-ng/qgssvgselectorwidget.h b/src/gui/symbology-ng/qgssvgselectorwidget.h index af56928b51ff..89f3c0a203ad 100644 --- a/src/gui/symbology-ng/qgssvgselectorwidget.h +++ b/src/gui/symbology-ng/qgssvgselectorwidget.h @@ -246,7 +246,7 @@ class GUI_EXPORT QgsSvgSelectorWidget : public QWidget, private Ui::WidgetSvgSel QLayout* selectorLayout() { return this->layout(); } public slots: - /** Accepts absolute and relative paths */ + //! Accepts absolute and relative paths void setSvgPath( const QString& svgPath ); signals: diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.h b/src/gui/symbology-ng/qgssymbolslistwidget.h index dd8809364014..3e65c4255b47 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.h +++ b/src/gui/symbology-ng/qgssymbolslistwidget.h @@ -97,9 +97,9 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW void updateSymbolColor(); void updateSymbolInfo(); - /** Displays alpha value as transparency in mTransparencyLabel*/ + //! Displays alpha value as transparency in mTransparencyLabel void displayTransparency( double alpha ); - /** Recursive function to create the group tree in the widget */ + //! Recursive function to create the group tree in the widget void populateGroups( const QString& parent = "", const QString& prepend = "" ); QgsSymbolWidgetContext mContext; diff --git a/src/plugins/evis/databaseconnection/evisdatabaseconnection.h b/src/plugins/evis/databaseconnection/evisdatabaseconnection.h index bea78e35fb4c..1240323c6d23 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaseconnection.h +++ b/src/plugins/evis/databaseconnection/evisdatabaseconnection.h @@ -42,7 +42,7 @@ class eVisDatabaseConnection public: - /** \brief Enum containting the type of database supported by this class */ + //! \brief Enum containting the type of database supported by this class enum DATABASE_TYPE { UNDEFINED, @@ -53,72 +53,72 @@ class eVisDatabaseConnection QSQLITE } mDatabaseType; - /** \brief Constructor */ + //! \brief Constructor eVisDatabaseConnection( const QString&, int, const QString&, const QString&, const QString&, DATABASE_TYPE ); - /** \brief Public method that finalizes a connection to a databse */ + //! \brief Public method that finalizes a connection to a databse bool connect(); - /** \brief Public method that passes an SQL statement to the database for execution */ + //! \brief Public method that passes an SQL statement to the database for execution QSqlQuery* query( const QString& ); - /** \brief Public method for resetting the database connection parameters - equivalent to re running the constructor */ + //! \brief Public method for resetting the database connection parameters - equivalent to re running the constructor void resetConnectionParameters( const QString&, int, const QString&, const QString&, const QString&, DATABASE_TYPE ); - /** \brief Returns a list of tables in the current database */ + //! \brief Returns a list of tables in the current database QStringList tables(); - /** \brief Accessor to the database type */ + //! \brief Accessor to the database type DATABASE_TYPE databaseType() { return mDatabaseType; } - /** \brief Public method for closing the current database connection */ + //! \brief Public method for closing the current database connection void close() { mDatabase.close(); } - /** \brief Public method for requesting the last error reported by the database connect or query */ + //! \brief Public method for requesting the last error reported by the database connect or query QString lastError() { return mLastError; } - /** \brief Mutator for database type */ + //! \brief Mutator for database type void setDatabaseType( DATABASE_TYPE connectionType ) { mDatabaseType = connectionType; } protected: - /** \brief Variable used to store the query results */ + //! \brief Variable used to store the query results QSqlQuery mQuery; private: - /** \brief Host name for the database server */ + //! \brief Host name for the database server QString mHostName; - /** \brief Port number the database server is listenting to */ + //! \brief Port number the database server is listenting to int mPort; - /** \brief Database name, can also be a filename in the case of SQLite or MSAccess */ + //! \brief Database name, can also be a filename in the case of SQLite or MSAccess QString mDatabaseName; - /** \brief Username for accessing the database */ + //! \brief Username for accessing the database QString mUsername; - /** \brief Password associated with the username for accessing the database */ + //! \brief Password associated with the username for accessing the database QString mPassword; - /** \brief QString containing the last reported error message */ + //! \brief QString containing the last reported error message QString mLastError; - /** \brief The database object */ + //! \brief The database object QSqlDatabase mDatabase; - /** \brief Sets the error messages */ + //! \brief Sets the error messages void setLastError( const QString& error ) { mLastError = error; diff --git a/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h b/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h index c82fd4a4dd2d..34512fc93c5f 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h +++ b/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h @@ -49,27 +49,27 @@ class eVisDatabaseConnectionGui : public QDialog, private Ui::eVisDatabaseConnec Q_OBJECT public: - /** \brief Constructor */ + //! \brief Constructor eVisDatabaseConnectionGui( QList*, QWidget* parent = nullptr, Qt::WindowFlags fl = 0 ); - /** \brief Destructor */ + //! \brief Destructor ~eVisDatabaseConnectionGui(); private: - /** \brief Pointer to a database connection */ + //! \brief Pointer to a database connection eVisDatabaseConnection* mDatabaseConnection; - /** \brief Pointer to a temporary file which will hold the results of our query */ + //! \brief Pointer to a temporary file which will hold the results of our query QList* mTempOutputFileList; - /** \brief Pointer to another GUI component that will select which fields contain x, y coordinates */ + //! \brief Pointer to another GUI component that will select which fields contain x, y coordinates eVisDatabaseLayerFieldSelectionGui* mDatabaseLayerFieldSelector; - /** \brief Pointer to a QMap which will hold the definition of preexisting query that can be loaded from an xml file */ + //! \brief Pointer to a QMap which will hold the definition of preexisting query that can be loaded from an xml file QMap* mQueryDefinitionMap; private slots: - /** \brief Slot called after the user selects the x, y fields in the field selection gui component */ + //! \brief Slot called after the user selects the x, y fields in the field selection gui component void drawNewVectorLayer( const QString&, const QString&, const QString& ); void on_buttonBox_accepted(); @@ -83,7 +83,7 @@ class eVisDatabaseConnectionGui : public QDialog, private Ui::eVisDatabaseConnec void on_pbtnRunQuery_clicked(); signals: - /** \brief signal emitted by the drawNewVectorLayer slot */ + //! \brief signal emitted by the drawNewVectorLayer slot void drawVectorLayer( const QString&, const QString&, const QString& ); }; diff --git a/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.h b/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.h index d3edc44a5469..2f59955ca23b 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.h +++ b/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.h @@ -41,10 +41,10 @@ class eVisDatabaseLayerFieldSelectionGui : public QDialog, private Ui::eVisDatab Q_OBJECT public: - /** \brief Constructor */ + //! \brief Constructor eVisDatabaseLayerFieldSelectionGui( QWidget* parent, Qt::WindowFlags fl ); - /** \brief Public method that sets the contents of the combo boxes with the available field names */ + //! \brief Public method that sets the contents of the combo boxes with the available field names void setFieldList( QStringList* ); public slots: @@ -52,7 +52,7 @@ class eVisDatabaseLayerFieldSelectionGui : public QDialog, private Ui::eVisDatab void on_buttonBox_rejected(); signals: - /** \brief Signal emitted when the user has entered the layername, selected the field names, and pressed the accept button */ + //! \brief Signal emitted when the user has entered the layername, selected the field names, and pressed the accept button void eVisDatabaseLayerFieldsSelected( const QString&, const QString&, const QString& ); }; #endif diff --git a/src/plugins/evis/databaseconnection/evisquerydefinition.h b/src/plugins/evis/databaseconnection/evisquerydefinition.h index 6b13cd1f5a7e..35fc2fae7ce4 100644 --- a/src/plugins/evis/databaseconnection/evisquerydefinition.h +++ b/src/plugins/evis/databaseconnection/evisquerydefinition.h @@ -42,67 +42,67 @@ class eVisQueryDefinition { public: - /** \brief Constructor */ + //! \brief Constructor eVisQueryDefinition(); - /** \brief Accessor for query description */ + //! \brief Accessor for query description QString description() { return mDescription; } - /** \brief Accessor for query short description */ + //! \brief Accessor for query short description QString shortDescription() { return mShortDescription; } - /** \brief Accessor for database type */ + //! \brief Accessor for database type QString databaseType() { return mDatabaseType; } - /** \brief Accessor for database host name */ + //! \brief Accessor for database host name QString databaseHost() { return mDatabaseHost; } - /** \brief Accessor for database port */ + //! \brief Accessor for database port int databasePort() { return mDatabasePort; } - /** \brief Accessor for database name */ + //! \brief Accessor for database name QString databaseName() { return mDatabaseName; } - /** \brief Accessor for database username */ + //! \brief Accessor for database username QString databaseUsername() { return mDatabaseUsername; } - /** \brief Accessor for database password */ + //! \brief Accessor for database password QString databasePassword() { return mDatabasePassword; } - /** \brief Accessor for SQL statement */ + //! \brief Accessor for SQL statement QString sqlStatement() { return mSqlStatement; } - /** \brief Accessor for auto connection flag */ + //! \brief Accessor for auto connection flag bool autoConnect() { return mAutoConnect; } - /** \brief Mutator for query description */ + //! \brief Mutator for query description void setDescription( const QString& description ) { mDescription = description; } - /** \brief Mutator for query short description */ + //! \brief Mutator for query short description void setShortDescription( const QString& description ) { mShortDescription = description; } - /** \brief Mutator for database type */ + //! \brief Mutator for database type void setDatabaseType( const QString& type ) { mDatabaseType = type; } - /** \brief Mutator for database host name */ + //! \brief Mutator for database host name void setDatabaseHost( const QString& host ) { mDatabaseHost = host; } - /** \brief Mutator for database port */ + //! \brief Mutator for database port void setDatabasePort( int port ) { mDatabasePort = port; } - /** \brief Mutator for database name */ + //! \brief Mutator for database name void setDatabaseName( const QString& name ) { mDatabaseName = name; } - /** \brief Mutator for database username */ + //! \brief Mutator for database username void setDatabaseUsername( const QString& username ) { mDatabaseUsername = username; } - /** \brief Mutator for database password */ + //! \brief Mutator for database password void setDatabasePassword( const QString& password ) { mDatabasePassword = password; } - /** \brief Mutator for SQL statement */ + //! \brief Mutator for SQL statement void setSqlStatement( const QString& statement ) { mSqlStatement = statement; } - /** \brief Mutator for auto connection flag */ + //! \brief Mutator for auto connection flag void setAutoConnect( const QString& autoconnect ) { if ( autoconnect.startsWith( QLatin1String( "true" ), Qt::CaseInsensitive ) ) @@ -117,34 +117,34 @@ class eVisQueryDefinition private: - /** \brief Detailed description for the query */ + //! \brief Detailed description for the query QString mDescription; - /** \brief Short description for the query */ + //! \brief Short description for the query QString mShortDescription; - /** \brief The database type to which a connection should be made */ + //! \brief The database type to which a connection should be made QString mDatabaseType; - /** \brief The database host to which a connection should be made */ + //! \brief The database host to which a connection should be made QString mDatabaseHost; - /** \brief The port/socket on the database host to which a connection should be made */ + //! \brief The port/socket on the database host to which a connection should be made int mDatabasePort; - /** \brief The name, or filename, of the database to which a connection should be made */ + //! \brief The name, or filename, of the database to which a connection should be made QString mDatabaseName; - /** \brief Username for the database, if required */ + //! \brief Username for the database, if required QString mDatabaseUsername; - /** \brief Password for the username, if require */ + //! \brief Password for the username, if require QString mDatabasePassword; - /** \brief The SQL statement to execute upon successful connection to a database */ + //! \brief The SQL statement to execute upon successful connection to a database QString mSqlStatement; - /** \brief Boolean to allow for automated connection to the database when query definition is successfully loaded */ + //! \brief Boolean to allow for automated connection to the database when query definition is successfully loaded bool mAutoConnect; }; #endif diff --git a/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.h b/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.h index 432c2032a3fd..21403f61351f 100644 --- a/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.h +++ b/src/plugins/evis/eventbrowser/evisgenericeventbrowsergui.h @@ -55,13 +55,13 @@ class eVisGenericEventBrowserGui : public QDialog, private Ui::eVisGenericEventB Q_OBJECT public: - /** \brief Constructor called when button is pressed in the plugin toolbar */ + //! \brief Constructor called when button is pressed in the plugin toolbar eVisGenericEventBrowserGui( QWidget* parent, QgisInterface* interface, Qt::WindowFlags fl ); - /** \brief Constructor called when new browser is requested by the eVisEventIdTool */ + //! \brief Constructor called when new browser is requested by the eVisEventIdTool eVisGenericEventBrowserGui( QWidget* parent, QgsMapCanvas* canvas, Qt::WindowFlags fl ); - /** \Brief Destructor */ + //! \Brief Destructor ~eVisGenericEventBrowserGui(); protected: @@ -69,86 +69,86 @@ class eVisGenericEventBrowserGui : public QDialog, private Ui::eVisGenericEventB private: //Variables - /** \brief A flag to bypass some signal/slots during gui initialization */ + //! \brief A flag to bypass some signal/slots during gui initialization bool mIgnoreEvent; - /** \brief Pointer to the main configurations object */ + //! \brief Pointer to the main configurations object eVisConfiguration mConfiguration; - /** \brief Flag indicating if the browser fully initialized */ + //! \brief Flag indicating if the browser fully initialized bool mBrowserInitialized; - /** \brief Index of the attribute field name that closest 'matches' configuration of the parameter */ + //! \brief Index of the attribute field name that closest 'matches' configuration of the parameter int mDefaultCompassBearingField; - /** \brief Index of the attribute field name that closest 'matches' configuration of the parameter */ + //! \brief Index of the attribute field name that closest 'matches' configuration of the parameter int mDefaultCompassOffsetField; - /** \brief Index of the attribute field name that closest 'matches' configuration of the parameter */ + //! \brief Index of the attribute field name that closest 'matches' configuration of the parameter int mDefaultEventImagePathField; - /** \brief Pointer to the QgisInferface */ + //! \brief Pointer to the QgisInferface QgisInterface* mInterface; - /** \brief Pointer to the map canvas */ + //! \brief Pointer to the map canvas QgsMapCanvas* mCanvas; - /** \brief Pointer to the vector layer */ + //! \brief Pointer to the vector layer QgsVectorLayer* mVectorLayer; - /** \brief Pointer to the vector data provider */ + //! \brief Pointer to the vector data provider QgsVectorDataProvider* mDataProvider; - /** \brief QPixmap holding the default highlighting symbol */ + //! \brief QPixmap holding the default highlighting symbol QPixmap mHighlightSymbol; - /** \brief QPixmap holding the pointer highlighting symbol */ + //! \brief QPixmap holding the pointer highlighting symbol QPixmap mPointerSymbol; - /** \brief Compass bearing value for the current feature */ + //! \brief Compass bearing value for the current feature double mCompassBearing; - /** \brief Compass bearing offset retrieved from attribute */ + //! \brief Compass bearing offset retrieved from attribute double mCompassOffset; - /** \brief QString holding the path to the image for the current feature */ + //! \brief QString holding the path to the image for the current feature QString mEventImagePath; - /** \brief List of current select featured ids*/ + //! \brief List of current select featured ids QList mFeatureIds; - /** \brief Index of selected feature being viewed, used to access mFeatureIds */ + //! \brief Index of selected feature being viewed, used to access mFeatureIds int mCurrentFeatureIndex; - /** \brief Current feature being viewed */ + //! \brief Current feature being viewed QgsFeature mFeature; //Methods - /** \brief Applies parameters on the Options tabs and saves the configuration */ + //! \brief Applies parameters on the Options tabs and saves the configuration void accept() override; - /** \brief Modifies the Event Image Path according to the local and global settings */ + //! \brief Modifies the Event Image Path according to the local and global settings void buildEventImagePath(); - /** \brief Method that loads the image in the browser */ + //! \brief Method that loads the image in the browser void displayImage(); - /** \brief Generic method to get a feature by id. Access mLocalFeatureList when layer is of type delimitedtext otherwise calls existing methods in mDataProvider */ + //! \brief Generic method to get a feature by id. Access mLocalFeatureList when layer is of type delimitedtext otherwise calls existing methods in mDataProvider QgsFeature* featureAtId( QgsFeatureId ); - /** \brief Functionality common to both constructors */ + //! \brief Functionality common to both constructors bool initBrowser(); - /** \brief Set all of the gui objects based on the current configuration*/ + //! \brief Set all of the gui objects based on the current configuration void initOptionsTab(); - /** \brief Method called to load data into the browser */ + //! \brief Method called to load data into the browser void loadRecord(); - /** \brief Reset all gui items on the options tab to a 'system default' */ + //! \brief Reset all gui items on the options tab to a 'system default' void restoreDefaultOptions(); - /** \brief Sets the base path to the path of the data source */ + //! \brief Sets the base path to the path of the data source void setBasePathToDataSource(); private slots: @@ -176,7 +176,7 @@ class eVisGenericEventBrowserGui : public QDialog, private Ui::eVisGenericEventB void on_pbtnResetUseOnlyFilenameData_clicked(); void on_rbtnManualCompassOffset_toggled( bool ); void on_tableFileTypeAssociations_cellDoubleClicked( int, int ); - /** \brief Slot called when the map canvas is done refreshing. Draws the highlighting symbol over the current selected feature */ + //! \brief Slot called when the map canvas is done refreshing. Draws the highlighting symbol over the current selected feature void renderSymbol( QPainter* ); }; #endif diff --git a/src/plugins/evis/eventbrowser/evisimagedisplaywidget.h b/src/plugins/evis/eventbrowser/evisimagedisplaywidget.h index d7f5fab5ee03..512a1ca6ff44 100644 --- a/src/plugins/evis/eventbrowser/evisimagedisplaywidget.h +++ b/src/plugins/evis/eventbrowser/evisimagedisplaywidget.h @@ -52,26 +52,26 @@ class eVisImageDisplayWidget : public QWidget Q_OBJECT public: - /** \brief Constructor */ + //! \brief Constructor eVisImageDisplayWidget( QWidget* parent = nullptr, Qt::WindowFlags fl = 0 ); - /** \brief Destructor */ + //! \brief Destructor ~eVisImageDisplayWidget(); - /** \brief Load an image from disk and display */ + //! \brief Load an image from disk and display void displayImage( const QString& ); - /** \brief Load an image from a remote location using http and display */ + //! \brief Load an image from a remote location using http and display void displayUrlImage( const QString& ); /* * There needs to be more logic around setting the zoom steps as you could change it mid display * and end up getting not being able to zoom in or out */ - /** \brief Accessor for ZOOM_STEPS */ + //! \brief Accessor for ZOOM_STEPS int getZoomSteps() { return ZOOM_STEPS; } - /** \brief Mutator for ZOON_STEPS */ + //! \brief Mutator for ZOON_STEPS void setZoomSteps( int steps ) { ZOOM_STEPS = steps; } protected: @@ -79,64 +79,64 @@ class eVisImageDisplayWidget : public QWidget private: - /** \brief Used to hold the http request to match the correct emits with the correct result */ + //! \brief Used to hold the http request to match the correct emits with the correct result int mCurrentHttpImageRequestId; - /** \brief CUrrent Zoom level */ + //! \brief CUrrent Zoom level int mCurrentZoomStep; - /** \brief widget to display the image in */ + //! \brief widget to display the image in QScrollArea* mDisplayArea; - /** \brief Method that acually display the image in the widget */ + //! \brief Method that acually display the image in the widget void displayImage(); - /** \brief Pointer to the http buffer */ + //! \brief Pointer to the http buffer QBuffer* mHttpBuffer; // TODO: Update to QNetworkAccessManager #if QT_VERSION < 0x050000 - /** \brief Pointer to the http connection if needed */ + //! \brief Pointer to the http connection if needed QHttp* mHttpConnection; #endif - /** \brief This is a point to the actual image being displayed */ + //! \brief This is a point to the actual image being displayed QPixmap* mImage; - /** \brief Label to hold the image */ + //! \brief Label to hold the image QLabel* mImageLabel; - /** \brief Flag to indicate the success of the last load request */ + //! \brief Flag to indicate the success of the last load request bool mImageLoaded; - /** \brief Ratio if height to width or width to height for the original image, which ever is smaller */ + //! \brief Ratio if height to width or width to height for the original image, which ever is smaller double mImageSizeRatio; - /** \brief Boolean to indicate which feature the mImageSizeRation corresponds to */ + //! \brief Boolean to indicate which feature the mImageSizeRation corresponds to bool mScaleByHeight; - /** \brief Boolean to indicate which feature the mImageSizeRation corresponds to */ + //! \brief Boolean to indicate which feature the mImageSizeRation corresponds to bool mScaleByWidth; - /** \brief The increment by which the image is scaled during each scaling event */ + //! \brief The increment by which the image is scaled during each scaling event double mScaleFactor; - /** \brief The single factor by which the original image needs to be scaled to fit into current display area */ + //! \brief The single factor by which the original image needs to be scaled to fit into current display area double mScaleToFit; - /** \brief Zoom in button */ + //! \brief Zoom in button QPushButton* pbtnZoomIn; - /** \brief Zoom out button */ + //! \brief Zoom out button QPushButton* pbtnZoomOut; - /** \brief Zoom to full extent button */ + //! \brief Zoom to full extent button QPushButton* pbtnZoomFull; - /** \brief Method called to compute the various scaling parameters */ + //! \brief Method called to compute the various scaling parameters void setScalers(); - /** \brief The number of steps between the scale to fit image and full resolution */ + //! \brief The number of steps between the scale to fit image and full resolution int ZOOM_STEPS; private slots: @@ -146,7 +146,7 @@ class eVisImageDisplayWidget : public QWidget void on_pbtnZoomFull_clicked(); - /** \brief Slot called when the http request is completed */ + //! \brief Slot called when the http request is completed void displayUrlImage( int, bool ); }; #endif diff --git a/src/plugins/evis/idtool/eviseventidtool.h b/src/plugins/evis/idtool/eviseventidtool.h index b13e9b8a9f25..e050cb5adc91 100644 --- a/src/plugins/evis/idtool/eviseventidtool.h +++ b/src/plugins/evis/idtool/eviseventidtool.h @@ -48,18 +48,18 @@ class eVisEventIdTool : public QgsMapTool Q_OBJECT public: - /** \brief Constructor */ + //! \brief Constructor explicit eVisEventIdTool( QgsMapCanvas* ); - /** \brief Method to handle mouse release, i.e., select, event */ + //! \brief Method to handle mouse release, i.e., select, event void canvasReleaseEvent( QgsMapMouseEvent* ) override; private: - /** \brief Pointer to a generic event browser */ + //! \brief Pointer to a generic event browser eVisGenericEventBrowserGui* mBrowser; - /** \brief Selection routine called by the mouse release event */ + //! \brief Selection routine called by the mouse release event void select( const QgsPoint& ); }; #endif diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp index c1b1b3ad6613..8c35860ded3d 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.cpp @@ -448,7 +448,7 @@ void QgsGeometryCheckerResultTab::openAttributeTable() void QgsGeometryCheckerResultTab::fixErrors( bool prompt ) { - /** Collect errors to fix **/ + //! Collect errors to fix * QModelIndexList rows = ui.tableWidgetErrors->selectionModel()->selectedRows(); if ( rows.isEmpty() ) { @@ -473,13 +473,13 @@ void QgsGeometryCheckerResultTab::fixErrors( bool prompt ) return; } - /** Reset statistics, clear rubberbands **/ + //! Reset statistics, clear rubberbands * mStatistics = QgsGeometryCheckerFixSummaryDialog::Statistics(); qDeleteAll( mCurrentRubberBands ); mCurrentRubberBands.clear(); - /** Fix errors **/ + //! Fix errors * mCloseable = false; if ( prompt ) { diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp b/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp index fbcab8b1a2c0..5413176dc422 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.cpp @@ -169,7 +169,7 @@ void QgsGeometryCheckerSetupTab::selectOutputFile() void QgsGeometryCheckerSetupTab::runChecks() { - /** Get selected layer **/ + //! Get selected layer * QgsVectorLayer* layer = getSelectedLayer(); if ( !layer ) return; @@ -188,14 +188,14 @@ void QgsGeometryCheckerSetupTab::runChecks() } bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked(); - /** Set window busy **/ + //! Set window busy * setCursor( Qt::WaitCursor ); mRunButton->setEnabled( false ); ui.labelStatus->setText( tr( "Preparing output..." ) ); ui.labelStatus->show(); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); - /** Duplicate if necessary **/ + //! Duplicate if necessary * if ( ui.radioButtonOutputNew->isChecked() ) { // Write selected feature ids to new layer @@ -272,7 +272,7 @@ void QgsGeometryCheckerSetupTab::runChecks() } } - /** Setup checker **/ + //! Setup checker * ui.labelStatus->setText( tr( "Building spatial index..." ) ); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QgsFeaturePool* featurePool = new QgsFeaturePool( layer, selectedOnly ); @@ -292,14 +292,14 @@ void QgsGeometryCheckerSetupTab::runChecks() emit checkerStarted( checker, featurePool ); - /** Add result layer (do this after checkerStarted, otherwise warning about removing of result layer may appear) **/ + //! Add result layer (do this after checkerStarted, otherwise warning about removing of result layer may appear) * layer->setReadOnly( true ); if ( ui.radioButtonOutputNew->isChecked() ) { QgsMapLayerRegistry::instance()->addMapLayers( QList() << layer ); } - /** Run **/ + //! Run * ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole ); mRunButton->hide(); ui.progressBar->setRange( 0, 0 ); @@ -318,7 +318,7 @@ void QgsGeometryCheckerSetupTab::runChecks() ui.progressBar->setRange( 0, maxSteps ); evLoop.exec(); - /** Restore window **/ + //! Restore window * unsetCursor(); mAbortButton->setEnabled( true ); ui.buttonBox->removeButton( mAbortButton ); @@ -328,7 +328,7 @@ void QgsGeometryCheckerSetupTab::runChecks() ui.labelStatus->hide(); ui.widgetInputs->setEnabled( true ); - /** Show result **/ + //! Show result * emit checkerFinished( !futureWatcher.isCanceled() ); } diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp b/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp index f9a364e21e1d..18b5ebad12a3 100644 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp +++ b/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp @@ -183,7 +183,7 @@ void QgsGeometrySnapperDialog::selectOutputFile() void QgsGeometrySnapperDialog::run() { - /** Get layers **/ + //! Get layers * QgsVectorLayer* layer = getInputLayer(); QgsVectorLayer* referenceLayer = getReferenceLayer(); if ( !layer || !referenceLayer ) @@ -201,7 +201,7 @@ void QgsGeometrySnapperDialog::run() bool selectedOnly = checkBoxInputSelectedOnly->isChecked(); - /** Duplicate if necessary **/ + //! Duplicate if necessary * if ( radioButtonOutputNew->isChecked() ) { QString filename = lineEditOutput->text(); @@ -278,7 +278,7 @@ void QgsGeometrySnapperDialog::run() QgsMapLayerRegistry::instance()->addMapLayers( QList() << layer ); } - /** Run **/ + //! Run * QEventLoop evLoop; QFutureWatcher futureWatcher; connect( &futureWatcher, SIGNAL( finished() ), &evLoop, SLOT( quit() ) ); @@ -298,7 +298,7 @@ void QgsGeometrySnapperDialog::run() futureWatcher.setFuture( snapper.processFeatures() ); evLoop.exec(); - /** Restore window **/ + //! Restore window * unsetCursor(); buttonBox->button( QDialogButtonBox::Abort )->hide(); mRunButton->show(); @@ -307,10 +307,10 @@ void QgsGeometrySnapperDialog::run() layer->setReadOnly( false ); - /** Trigger layer repaint **/ + //! Trigger layer repaint * layer->triggerRepaint(); - /** Show errors **/ + //! Show errors * if ( !snapper.getErrors().isEmpty() ) { QMessageBox::warning( this, tr( "Errors occurred" ), tr( "

                                                                                                                                                                                    The following errors occurred:

                                                                                                                                                                                    • %1
                                                                                                                                                                                    " ).arg( snapper.getErrors().join( QStringLiteral( "
                                                                                                                                                                                  • " ) ) ) ); diff --git a/src/plugins/georeferencer/qgsgcpcanvasitem.h b/src/plugins/georeferencer/qgsgcpcanvasitem.h index 41cedef84029..b7e924621172 100644 --- a/src/plugins/georeferencer/qgsgcpcanvasitem.h +++ b/src/plugins/georeferencer/qgsgcpcanvasitem.h @@ -36,7 +36,7 @@ class QgsGCPCanvasItem : public QgsMapCanvasItem void updatePosition() override; - /** Calls prepareGeometryChange()*/ + //! Calls prepareGeometryChange() void checkBoundingRectChange(); private: @@ -52,9 +52,9 @@ class QgsGCPCanvasItem : public QgsMapCanvasItem QRectF mTextBoxRect; void drawResidualArrow( QPainter* p, const QgsRenderContext& context ); - /** Calculates scale factor for residual display*/ + //! Calculates scale factor for residual display double residualToScreenFactor() const; - /** Calculates pixel size for a font point size*/ + //! Calculates pixel size for a font point size double fontSizePainterUnits( double points, const QgsRenderContext& c ); }; diff --git a/src/plugins/georeferencer/qgsgeorefdescriptiondialog.h b/src/plugins/georeferencer/qgsgeorefdescriptiondialog.h index 8d5d0166233f..066ae1a44928 100644 --- a/src/plugins/georeferencer/qgsgeorefdescriptiondialog.h +++ b/src/plugins/georeferencer/qgsgeorefdescriptiondialog.h @@ -21,7 +21,7 @@ #include "ui_qgsgeorefdescriptiondialogbase.h" #include -/** Dialog that shows logo and description of the georef plugin*/ +//! Dialog that shows logo and description of the georef plugin class QgsGeorefDescriptionDialog: public QDialog, private Ui::QgsGeorefDescriptionDialogBase { Q_OBJECT diff --git a/src/plugins/georeferencer/qgsgeorefplugingui.h b/src/plugins/georeferencer/qgsgeorefplugingui.h index 5a67bb68f2fb..a90adf79b1a6 100644 --- a/src/plugins/georeferencer/qgsgeorefplugingui.h +++ b/src/plugins/georeferencer/qgsgeorefplugingui.h @@ -197,7 +197,7 @@ class QgsGeorefPluginGui : public QMainWindow, private Ui::QgsGeorefPluginGuiBas */ bool calculateMeanError( double& error ) const; - /** Docks / undocks this window*/ + //! Docks / undocks this window void dockThisWindow( bool dock ); QGridLayout* mCentralLayout; diff --git a/src/plugins/georeferencer/qgsgeoreftoolmovepoint.h b/src/plugins/georeferencer/qgsgeoreftoolmovepoint.h index 3c3565f79067..992745eb73e8 100644 --- a/src/plugins/georeferencer/qgsgeoreftoolmovepoint.h +++ b/src/plugins/georeferencer/qgsgeoreftoolmovepoint.h @@ -41,10 +41,10 @@ class QgsGeorefToolMovePoint : public QgsMapTool void pointReleased( QPoint p ); private: - /** Start point of the move in map coordinates*/ + //! Start point of the move in map coordinates QPoint mStartPointMapCoords; - /** Rubberband that shows the feature being moved*/ + //! Rubberband that shows the feature being moved QRubberBand *mRubberBand; }; diff --git a/src/plugins/georeferencer/qgsgeoreftransform.h b/src/plugins/georeferencer/qgsgeoreftransform.h index f99da9fd6c5c..046edbc8989f 100644 --- a/src/plugins/georeferencer/qgsgeoreftransform.h +++ b/src/plugins/georeferencer/qgsgeoreftransform.h @@ -98,7 +98,7 @@ class QgsGeorefTransform : public QgsGeorefTransformInterface //! \brief The transform parametrisation currently in use. TransformParametrisation transformParametrisation() const; - /** True for linear, Helmert, first order polynomial*/ + //! True for linear, Helmert, first order polynomial bool providesAccurateInverseTransformation() const; //! \returns whether the parameters of this transform have been initialized by \ref updateParametersFromGCPs diff --git a/src/plugins/georeferencer/qgsresidualplotitem.h b/src/plugins/georeferencer/qgsresidualplotitem.h index 74f6dae6c6a5..2d0a05030e31 100644 --- a/src/plugins/georeferencer/qgsresidualplotitem.h +++ b/src/plugins/georeferencer/qgsresidualplotitem.h @@ -30,7 +30,7 @@ class QgsResidualPlotItem: public QgsComposerItem explicit QgsResidualPlotItem( QgsComposition* c ); ~QgsResidualPlotItem(); - /** \brief Reimplementation of QCanvasItem::paint*/ + //! \brief Reimplementation of QCanvasItem::paint virtual void paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget ) override; void setGCPList( const QgsGCPList& list ) { mGCPList = list; } @@ -50,13 +50,13 @@ class QgsResidualPlotItem: public QgsComposerItem QgsGCPList mGCPList; QgsRectangle mExtent; - /** True if the scale bar units should be converted to map units. This can be done for transformation where the scaling in all directions is the same (helmert)*/ + //! True if the scale bar units should be converted to map units. This can be done for transformation where the scaling in all directions is the same (helmert) bool mConvertScaleToMapUnits; - /** Calculates maximal possible mm to pixel ratio such that the residual arrow is still inside the frame*/ + //! Calculates maximal possible mm to pixel ratio such that the residual arrow is still inside the frame double maxMMToPixelRatioForGCP( const QgsGeorefDataPoint* p, double pixelXMM, double pixelYMM ); - /** Returns distance between two points*/ + //! Returns distance between two points double dist( QPointF p1, QPointF p2 ) const; }; diff --git a/src/plugins/grass/qgsgrassmapcalc.h b/src/plugins/grass/qgsgrassmapcalc.h index 898b3a2431f1..0cbaaf29f34f 100644 --- a/src/plugins/grass/qgsgrassmapcalc.h +++ b/src/plugins/grass/qgsgrassmapcalc.h @@ -70,32 +70,32 @@ class QgsGrassMapcalc: public QMainWindow, private Ui::QgsGrassMapcalcBase, bool hasOutput( int type ) override { Q_UNUSED( type ); return true; } - /** \brief receives contentsMousePressEvent from view */ + //! \brief receives contentsMousePressEvent from view void mousePressEvent( QMouseEvent* ) override; - /** \brief receives contentsMouseReleaseEvent from view */ + //! \brief receives contentsMouseReleaseEvent from view void mouseReleaseEvent( QMouseEvent* ) override; - /** \brief receives contentsMouseMoveEvent from view */ + //! \brief receives contentsMouseMoveEvent from view void mouseMoveEvent( QMouseEvent* ) override; void keyPressEvent( QKeyEvent * e ) override; - /** Cut coordinates by current canvas extent */ + //! Cut coordinates by current canvas extent void limit( QPoint* ); - /** Grow canvas and move items */ + //! Grow canvas and move items void growCanvas( int left, int right, int top, int bottom ); - /** Grow automaticaly if an item is near border */ + //! Grow automaticaly if an item is near border void autoGrow(); void resizeCanvas( int width, int height ); - /** Show/hide options for tool */ + //! Show/hide options for tool void showOptions( int tool ); - /** Set option for selected object */ + //! Set option for selected object void setOption( void ); public slots: diff --git a/src/plugins/grass/qgsgrassmoduleinput.h b/src/plugins/grass/qgsgrassmoduleinput.h index d5989a062ef6..999e09b7457a 100644 --- a/src/plugins/grass/qgsgrassmoduleinput.h +++ b/src/plugins/grass/qgsgrassmoduleinput.h @@ -64,14 +64,14 @@ class QgsGrassModuleInputModel : public QStandardItemModel explicit QgsGrassModuleInputModel( QObject *parent = 0 ); ~QgsGrassModuleInputModel(); - /** Get singleton instance of this class. */ + //! Get singleton instance of this class. static QgsGrassModuleInputModel* instance(); QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const override; public slots: - /** Reload current mapset */ + //! Reload current mapset void reload(); void onMapsetChanged(); diff --git a/src/plugins/grass/qgsgrassregion.cpp b/src/plugins/grass/qgsgrassregion.cpp index 6af9b218fde3..3856e4e8965f 100644 --- a/src/plugins/grass/qgsgrassregion.cpp +++ b/src/plugins/grass/qgsgrassregion.cpp @@ -33,7 +33,7 @@ #include -/** Map tool which uses rubber band for changing grass region */ +//! Map tool which uses rubber band for changing grass region QgsGrassRegionEdit::QgsGrassRegionEdit( QgsMapCanvas* canvas ) : QgsMapTool( canvas ) { @@ -129,7 +129,7 @@ void QgsGrassRegionEdit::setTransform() void QgsGrassRegionEdit::transform( QgsMapCanvas *canvas, QVector &points, const QgsCoordinateTransform& coordinateTransform, QgsCoordinateTransform::TransformDirection direction ) { - /** Coordinate transform */ + //! Coordinate transform if ( canvas->hasCrsTransformEnabled() ) { //QgsDebugMsg ( "srcCrs = " + coordinateTransform->sourceCrs().toWkt() ); diff --git a/src/plugins/grass/qgsgrassregion.h b/src/plugins/grass/qgsgrassregion.h index 22121c94a63b..362fc7f6b659 100644 --- a/src/plugins/grass/qgsgrassregion.h +++ b/src/plugins/grass/qgsgrassregion.h @@ -127,7 +127,7 @@ class QgsGrassRegion: public QWidget, private Ui::QgsGrassRegionBase QgsGrassRegionEdit* mRegionEdit; }; -/** Map tool which uses rubber band for changing grass region */ +//! Map tool which uses rubber band for changing grass region class QgsGrassRegionEdit : public QgsMapTool { Q_OBJECT diff --git a/src/plugins/heatmap/heatmapgui.h b/src/plugins/heatmap/heatmapgui.h index ea125fa01af6..f87ce3e96c71 100644 --- a/src/plugins/heatmap/heatmapgui.h +++ b/src/plugins/heatmap/heatmapgui.h @@ -37,58 +37,58 @@ class HeatmapGui : public QDialog, private Ui::HeatmapGuiBase MapUnits }; - /** Returns whether to apply weighted heat */ + //! Returns whether to apply weighted heat bool weighted() const; - /** Returns whether the radius is static or based on a field */ + //! Returns whether the radius is static or based on a field bool variableRadius() const; - /** Returns the fixed radius value */ + //! Returns the fixed radius value double radius() const; - /** Return the radius unit (layer/map units) */ + //! Return the radius unit (layer/map units) int radiusUnit() const; - /** Return the selected kernel shape */ + //! Return the selected kernel shape Heatmap::KernelShape kernelShape() const; - /** Return the selected output values setting */ + //! Return the selected output values setting Heatmap::OutputValues outputValues() const; - /** Return the decay ratio */ + //! Return the decay ratio double decayRatio() const; - /** Return the attribute field for variable radius */ + //! Return the attribute field for variable radius int radiusField() const; - /** Returns the attrinute field for weighted heat */ + //! Returns the attrinute field for weighted heat int weightField() const; - /** Returns state of the add to canvas checkbox*/ + //! Returns state of the add to canvas checkbox bool addToCanvas() const; - /** Returns the output filename/path */ + //! Returns the output filename/path QString outputFilename() const; - /** Returns the GDAL Format for output raster */ + //! Returns the GDAL Format for output raster QString outputFormat() const; - /** Returns the input Vector layer */ + //! Returns the input Vector layer QgsVectorLayer* inputVectorLayer() const; - /** Returns the no of rows for the raster */ + //! Returns the no of rows for the raster int rows() const { return mRows; } - /** Returns the no of columns in the raster */ + //! Returns the no of columns in the raster int columns() const { return mColumns; } - /** Returns the cell size X value */ + //! Returns the cell size X value double cellSizeX() const { return mXcellsize; } - /** Returns the cell size Y valuue */ + //! Returns the cell size Y valuue double cellSizeY() const { return mYcellsize; } - /** Return the BBox */ + //! Return the BBox QgsRectangle bbox() const { return mBBox; } private: @@ -101,28 +101,28 @@ class HeatmapGui : public QDialog, private Ui::HeatmapGuiBase double mXcellsize, mYcellsize; int mRows, mColumns; - /** Restores control values */ + //! Restores control values void restoreSettings( bool usingLastInputLayer ); - /** Saves control values */ + //! Saves control values void saveSettings(); - /** Blocks/unblocks signals for controls */ + //! Blocks/unblocks signals for controls void blockAllSignals( bool b ); - /** Function to check wether all constrains are satisfied and enable the OK button */ + //! Function to check wether all constrains are satisfied and enable the OK button void enableOrDisableOkButton(); - /** Set the mBBox value - mainly used for updation purpose */ + //! Set the mBBox value - mainly used for updation purpose void updateBBox(); - /** Update the LineEdits cellsize and row&col values */ + //! Update the LineEdits cellsize and row&col values void updateSize(); - /** Convert layer distance value to the corresponding map units based on layer projection */ + //! Convert layer distance value to the corresponding map units based on layer projection double mapUnitsOf( double dist, const QgsCoordinateReferenceSystem& layerCrs ) const; - /** Estimate a reasonable starting value for the radius field */ + //! Estimate a reasonable starting value for the radius field double estimateRadius(); inline double max( double a, double b ) diff --git a/src/plugins/interpolation/qgsidwinterpolatordialog.h b/src/plugins/interpolation/qgsidwinterpolatordialog.h index 6e59c3cf4fc7..6866bac1912c 100644 --- a/src/plugins/interpolation/qgsidwinterpolatordialog.h +++ b/src/plugins/interpolation/qgsidwinterpolatordialog.h @@ -21,7 +21,7 @@ #include "ui_qgsidwinterpolatordialogbase.h" #include "qgsinterpolatordialog.h" -/** A class that takes the input parameter for inverse distance weighting*/ +//! A class that takes the input parameter for inverse distance weighting class QgsIDWInterpolatorDialog: public QgsInterpolatorDialog, private Ui::QgsIDWInterpolatorDialogBase { Q_OBJECT diff --git a/src/plugins/interpolation/qgsinterpolationdialog.h b/src/plugins/interpolation/qgsinterpolationdialog.h index 126f5ad18a99..2625da4c309b 100644 --- a/src/plugins/interpolation/qgsinterpolationdialog.h +++ b/src/plugins/interpolation/qgsinterpolationdialog.h @@ -56,22 +56,22 @@ class QgsInterpolationDialog: public QDialog, private Ui::QgsInterpolationDialog private: QgisInterface* mIface; - /** Dialog to get input for the current interpolation method*/ + //! Dialog to get input for the current interpolation method QgsInterpolatorDialog* mInterpolatorDialog; /** Returns the vector layer object with the given name Returns a pointer to the vector layer or 0 in case of error.*/ QgsVectorLayer* vectorLayerFromName( const QString& name ); - /** Enables or disables the Ok button depending on the availability of input layers and the output file*/ + //! Enables or disables the Ok button depending on the availability of input layers and the output file void enableOrDisableOkButton(); /** Get the current output bounding box (might be different to the compound layers bounding box because of user edits) @return the bounding box or an empty bounding box in case of error*/ QgsRectangle currentBoundingBox(); - /** Returns the compound bounding box of the inserted layers*/ + //! Returns the compound bounding box of the inserted layers QgsRectangle boundingBoxOfLayers(); - /** Inserts the compound bounding box of the input layers into the line edits for the output bounding box*/ + //! Inserts the compound bounding box of the input layers into the line edits for the output bounding box void setLayersBoundingBox(); - /** Set cellsizes according to nex bounding box and number of columns / rows */ + //! Set cellsizes according to nex bounding box and number of columns / rows void setNewCellsizeOnBoundingBoxChange(); void setNewCellsizeXOnNColumnsChange(); void setNewCellsizeYOnNRowschange(); diff --git a/src/plugins/interpolation/qgsinterpolationplugin.h b/src/plugins/interpolation/qgsinterpolationplugin.h index 4379ecbb0d2c..47a1bea8a9c0 100644 --- a/src/plugins/interpolation/qgsinterpolationplugin.h +++ b/src/plugins/interpolation/qgsinterpolationplugin.h @@ -33,9 +33,9 @@ class QgsInterpolationPlugin: public QObject, public QgisPlugin public: explicit QgsInterpolationPlugin( QgisInterface* iface ); ~QgsInterpolationPlugin(); - /** Initialize connection to GUI*/ + //! Initialize connection to GUI void initGui() override; - /** Unload the plugin and cleanup the GUI*/ + //! Unload the plugin and cleanup the GUI void unload() override; private slots: diff --git a/src/plugins/interpolation/qgsinterpolatordialog.h b/src/plugins/interpolation/qgsinterpolatordialog.h index b4b8831b63a5..ccec979b58b6 100644 --- a/src/plugins/interpolation/qgsinterpolatordialog.h +++ b/src/plugins/interpolation/qgsinterpolatordialog.h @@ -25,7 +25,7 @@ class QgsVectorLayer; class QgisInterface; -/** Abstract base class for dialogs that allow entering the options for interpolators*/ +//! Abstract base class for dialogs that allow entering the options for interpolators class QgsInterpolatorDialog: public QDialog { Q_OBJECT @@ -41,10 +41,10 @@ class QgsInterpolatorDialog: public QDialog void setInputData( const QList< QgsInterpolator::LayerData >& inputData ); protected: - /** Pointer to the running QGIS instance. This may be necessary to show interpolator properties on the map (e.g. triangulation)*/ + //! Pointer to the running QGIS instance. This may be necessary to show interpolator properties on the map (e.g. triangulation) QgisInterface* mInterface; - /** A list of input data layers, their interpolation attribute and their type (point, structure lines, breaklines)*/ + //! A list of input data layers, their interpolation attribute and their type (point, structure lines, breaklines) QList< QgsInterpolator::LayerData > mInputData; }; diff --git a/src/plugins/offline_editing/offline_editing_plugin_gui.h b/src/plugins/offline_editing/offline_editing_plugin_gui.h index db966d8040ac..9698487796b6 100644 --- a/src/plugins/offline_editing/offline_editing_plugin_gui.h +++ b/src/plugins/offline_editing/offline_editing_plugin_gui.h @@ -50,7 +50,7 @@ class QgsOfflineEditingPluginGui : public QDialog, private Ui::QgsOfflineEditing bool onlySelected() const; public slots: - /** Change the selection of layers in the list */ + //! Change the selection of layers in the list void selectAll(); void unSelectAll(); diff --git a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.h b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.h index e281c4e6ebdb..3f92f369bfca 100644 --- a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.h +++ b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisdialog.h @@ -58,7 +58,7 @@ class QgsRasterTerrainAnalysisDialog: public QDialog, private Ui::QgsRasterTerra void on_mButtonBox_accepted(); private: - /** Stores relation between driver name and extension*/ + //! Stores relation between driver name and extension QMap mDriverExtensionMap; }; diff --git a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.h b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.h index cdc42ee81bed..8cd34103aee9 100644 --- a/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.h +++ b/src/plugins/raster_terrain_analysis/qgsrasterterrainanalysisplugin.h @@ -25,7 +25,7 @@ class QgsInterface; class QAction; class QMenu; -/** A plugin for raster based terrain analysis (e.g. slope, aspect, ruggedness)*/ +//! A plugin for raster based terrain analysis (e.g. slope, aspect, ruggedness) class QgsRasterTerrainAnalysisPlugin: public QObject, public QgisPlugin { Q_OBJECT @@ -33,9 +33,9 @@ class QgsRasterTerrainAnalysisPlugin: public QObject, public QgisPlugin explicit QgsRasterTerrainAnalysisPlugin( QgisInterface* iface ); ~QgsRasterTerrainAnalysisPlugin(); - /** Initialize connection to GUI*/ + //! Initialize connection to GUI void initGui() override; - /** Unload the plugin and cleanup the GUI*/ + //! Unload the plugin and cleanup the GUI void unload() override; private slots: diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h b/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h index 4a7e5d260e13..d85d80688a20 100644 --- a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h +++ b/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h @@ -42,11 +42,11 @@ class QgsZonalStatisticsDialog: public QDialog, private Ui::QgsZonalStatisticsDi private: QgsZonalStatisticsDialog(); - /** Fills the available raster and polygon layers into the combo boxes*/ + //! Fills the available raster and polygon layers into the combo boxes void insertAvailableLayers(); - /** Propose a valid prefix for the attributes*/ + //! Propose a valid prefix for the attributes QString proposeAttributePrefix() const; - /** Check if a prefix can be used for the count, sum and mean attribute*/ + //! Check if a prefix can be used for the count, sum and mean attribute bool prefixIsValid( const QString& prefix ) const; QgisInterface* mIface; diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h b/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h index fccd58050cee..3dee4bc9a07a 100644 --- a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h +++ b/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h @@ -31,13 +31,13 @@ class QgsZonalStatisticsPlugin: public QObject, public QgisPlugin explicit QgsZonalStatisticsPlugin( QgisInterface* iface ); ~QgsZonalStatisticsPlugin(); - /** Initialize connection to GUI*/ + //! Initialize connection to GUI void initGui() override; - /** Unload the plugin and cleanup the GUI*/ + //! Unload the plugin and cleanup the GUI void unload() override; private slots: - /** Select input file, output file, format and analysis method*/ + //! Select input file, output file, format and analysis method void run(); private: diff --git a/src/providers/db2/qgsdb2newconnection.cpp b/src/providers/db2/qgsdb2newconnection.cpp index acef07d17c2a..f9250bf13597 100644 --- a/src/providers/db2/qgsdb2newconnection.cpp +++ b/src/providers/db2/qgsdb2newconnection.cpp @@ -79,7 +79,7 @@ QgsDb2NewConnection::QgsDb2NewConnection( QWidget *parent, const QString& connNa } } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * void QgsDb2NewConnection::accept() { QSettings settings; @@ -147,7 +147,7 @@ void QgsDb2NewConnection::on_cb_trustedConnection_clicked() } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * QgsDb2NewConnection::~QgsDb2NewConnection() { diff --git a/src/providers/db2/qgsdb2provider.h b/src/providers/db2/qgsdb2provider.h index 12b89af8b9a7..ad08ee661a9c 100644 --- a/src/providers/db2/qgsdb2provider.h +++ b/src/providers/db2/qgsdb2provider.h @@ -108,19 +108,19 @@ class QgsDb2Provider : public QgsVectorDataProvider */ virtual QgsVectorDataProvider::Capabilities capabilities() const override; - /** Writes a list of features to the database*/ + //! Writes a list of features to the database virtual bool addFeatures( QgsFeatureList & flist ) override; - /** Deletes a feature*/ + //! Deletes a feature virtual bool deleteFeatures( const QgsFeatureIds & id ) override; - /** Changes attribute values of existing features */ + //! Changes attribute values of existing features virtual bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ) override; - /** Changes existing geometries*/ + //! Changes existing geometries virtual bool changeGeometryValues( const QgsGeometryMap &geometry_map ) override; - /** Import a vector layer into the database */ + //! Import a vector layer into the database static QgsVectorLayerImport::ImportError createEmptyLayer( const QString& uri, const QgsFields &fields, @@ -132,14 +132,14 @@ class QgsDb2Provider : public QgsVectorDataProvider const QMap *options = nullptr ); - /** Convert a QgsField to work with DB2 */ + //! Convert a QgsField to work with DB2 static bool convertField( QgsField &field ); - /** Convert a QgsField to work with DB2 */ + //! Convert a QgsField to work with DB2 static QString qgsFieldToDb2Field( const QgsField &field ); protected: - /** Loads fields from input file to member attributeFields */ + //! Loads fields from input file to member attributeFields QVariant::Type decodeSqlType( int typeId ); void loadMetadata(); void loadFields(); diff --git a/src/providers/db2/qgsdb2sourceselect.cpp b/src/providers/db2/qgsdb2sourceselect.cpp index 0296d376cd07..af5b3877e531 100644 --- a/src/providers/db2/qgsdb2sourceselect.cpp +++ b/src/providers/db2/qgsdb2sourceselect.cpp @@ -41,7 +41,7 @@ #include #include -/** Used to create an editor for when the user tries to change the contents of a cell */ +//! Used to create an editor for when the user tries to change the contents of a cell QWidget *QgsDb2SourceSelectDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const { Q_UNUSED( option ); @@ -208,7 +208,7 @@ QgsDb2SourceSelect::QgsDb2SourceSelect( QWidget *parent, Qt::WindowFlags fl, boo cbxAllowGeometrylessTables->setDisabled( true ); } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * // Slot for adding a new connection void QgsDb2SourceSelect::on_btnNew_clicked() { @@ -285,7 +285,7 @@ void QgsDb2SourceSelect::on_btnEdit_clicked() delete nc; } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * // Remember which database is selected void QgsDb2SourceSelect::on_cmbConnections_activated( int ) diff --git a/src/providers/db2/qgsdb2tablemodel.h b/src/providers/db2/qgsdb2tablemodel.h index 23a8886f3aa1..189b3d093b7e 100644 --- a/src/providers/db2/qgsdb2tablemodel.h +++ b/src/providers/db2/qgsdb2tablemodel.h @@ -22,7 +22,7 @@ #include #include "qgis.h" -/** Layer Property structure */ +//! Layer Property structure struct QgsDb2LayerProperty { QString type; @@ -50,17 +50,17 @@ class QgsDb2TableModel : public QStandardItemModel QgsDb2TableModel(); ~QgsDb2TableModel(); - /** Adds entry for one database table to the model*/ + //! Adds entry for one database table to the model void addTableEntry( const QgsDb2LayerProperty &property ); - /** Sets an sql statement that belongs to a cell specified by a model index*/ + //! Sets an sql statement that belongs to a cell specified by a model index void setSql( const QModelIndex& index, const QString& sql ); /** Sets one or more geometry types to a row. In case of several types, additional rows are inserted. This is for tables where the type is dectected later by thread*/ void setGeometryTypesForTable( QgsDb2LayerProperty layerProperty ); - /** Returns the number of tables in the model*/ + //! Returns the number of tables in the model int tableCount() const { return mTableCount; } enum columns @@ -85,7 +85,7 @@ class QgsDb2TableModel : public QStandardItemModel static QgsWkbTypes::Type wkbTypeFromDb2( QString dbType, int dim = 2 ); private: - /** Number of tables in the model*/ + //! Number of tables in the model int mTableCount; }; #endif diff --git a/src/providers/delimitedtext/qgsdelimitedtextfile.h b/src/providers/delimitedtext/qgsdelimitedtextfile.h index 670d825726ad..26dbe0d50843 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfile.h +++ b/src/providers/delimitedtext/qgsdelimitedtextfile.h @@ -323,9 +323,9 @@ class QgsDelimitedTextFile : public QObject */ void resetDefinition(); - /** Parse reqular expression delimited fields */ + //! Parse reqular expression delimited fields Status parseRegexp( QString &buffer, QStringList &fields ); - /** Parse quote delimited fields, where quote and escape are different */ + //! Parse quote delimited fields, where quote and escape are different Status parseQuoted( QString &buffer, QStringList &fields ); /** Return the next line from the data file. If skipBlank is true then diff --git a/src/providers/gdal/qgsgdalprovider.h b/src/providers/gdal/qgsgdalprovider.h index 982bf04d19b9..3a43b5879030 100644 --- a/src/providers/gdal/qgsgdalprovider.h +++ b/src/providers/gdal/qgsgdalprovider.h @@ -67,7 +67,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase */ QgsGdalProvider( QString const & uri = QString(), bool update = false ); - /** Create invalid provider with error */ + //! Create invalid provider with error QgsGdalProvider( QString const & uri, QgsError error ); //! Destructor @@ -160,7 +160,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase QString generateBandName( int theBandNumber ) const override; - /** Reimplemented from QgsRasterDataProvider to bypass second resampling (more efficient for local file based sources)*/ + //! Reimplemented from QgsRasterDataProvider to bypass second resampling (more efficient for local file based sources) QgsRasterBlock *block( int theBandNo, const QgsRectangle &theExtent, int theWidth, int theHeight, QgsRasterBlockFeedback* feedback = nullptr ) override; void readBlock( int bandNo, int xBlock, int yBlock, void *data ) override; @@ -181,7 +181,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase */ QString metadata() override; - /** \brief Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS */ + //! \brief Returns the sublayers of this layer - Useful for providers that manage their own layers, such as WMS QStringList subLayers() const override; static QStringList subLayers( GDALDatasetH dataset ); @@ -217,21 +217,21 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase const QStringList & theCreateOptions = QStringList() ) override; QList buildPyramidList( QList overviewList = QList() ) override; - /** \brief Close data set and release related data */ + //! \brief Close data set and release related data void closeDataset(); - /** Emit a signal to notify of the progress event. */ + //! Emit a signal to notify of the progress event. void emitProgress( int theType, double theProgress, const QString &theMessage ); void emitProgressUpdate( int theProgress ); static QMap supportedMimes(); - /** Writes into the provider datasource*/ + //! Writes into the provider datasource bool write( void* data, int band, int width, int height, int xOffset, int yOffset ) override; bool setNoDataValue( int bandNo, double noDataValue ) override; - /** Remove dataset*/ + //! Remove dataset bool remove() override; QString validateCreationOptions( const QStringList& createOptions, const QString& format ) override; @@ -245,7 +245,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase // initialize CRS from wkt bool crsFromWkt( const char *wkt ); - /** Do some initialization on the dataset (e.g. handling of south-up datasets)*/ + //! Do some initialization on the dataset (e.g. handling of south-up datasets) void initBaseDataset(); /** @@ -253,7 +253,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase */ bool mValid; - /** \brief Whether this raster has overviews / pyramids or not */ + //! \brief Whether this raster has overviews / pyramids or not bool mHasPyramids; /** \brief Gdal data types used to represent data in in QGIS, @@ -276,20 +276,20 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase // List of estimated max values, index 0 for band 1 //mutable QList mMaximum; - /** \brief Pointer to the gdaldataset */ + //! \brief Pointer to the gdaldataset GDALDatasetH mGdalBaseDataset; - /** \brief Pointer to the gdaldataset (possibly warped vrt) */ + //! \brief Pointer to the gdaldataset (possibly warped vrt) GDALDatasetH mGdalDataset; - /** \brief Values for mapping pixel to world coordinates. Contents of this array are the same as the GDAL adfGeoTransform */ + //! \brief Values for mapping pixel to world coordinates. Contents of this array are the same as the GDAL adfGeoTransform double mGeoTransform[6]; QgsCoordinateReferenceSystem mCrs; QList mPyramidList; - /** \brief sublayers list saved for subsequent access */ + //! \brief sublayers list saved for subsequent access QStringList mSubLayers; }; diff --git a/src/providers/gdal/qgsgdalproviderbase.h b/src/providers/gdal/qgsgdalproviderbase.h index 2bd1e87d81ec..9595112eb962 100644 --- a/src/providers/gdal/qgsgdalproviderbase.h +++ b/src/providers/gdal/qgsgdalproviderbase.h @@ -42,16 +42,16 @@ class QgsGdalProviderBase public: QgsGdalProviderBase(); - /** \brief ensures that GDAL drivers are registered, but only once */ + //! \brief ensures that GDAL drivers are registered, but only once static void registerGdalDrivers(); - /** Wrapper function for GDALOpen to get around possible bugs in GDAL */ + //! Wrapper function for GDALOpen to get around possible bugs in GDAL static GDALDatasetH gdalOpen( const char *pszFilename, GDALAccess eAccess ); - /** Wrapper function for GDALRasterIO to get around possible bugs in GDAL */ + //! Wrapper function for GDALRasterIO to get around possible bugs in GDAL static CPLErr gdalRasterIO( GDALRasterBandH hBand, GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void * pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nPixelSpace, int nLineSpace, QgsRasterBlockFeedback* feedback = nullptr ); - /** Wrapper function for GDALRasterIO to get around possible bugs in GDAL */ + //! Wrapper function for GDALRasterIO to get around possible bugs in GDAL static int gdalGetOverviewCount( GDALRasterBandH hBand ); protected: diff --git a/src/providers/gpx/gpsdata.h b/src/providers/gpx/gpsdata.h index b4681877a9a9..ef5117d46aa0 100644 --- a/src/providers/gpx/gpsdata.h +++ b/src/providers/gpx/gpsdata.h @@ -80,7 +80,7 @@ typedef QgsGPSPoint QgsRoutepoint; typedef QgsGPSPoint QgsTrackpoint; -/** This is the waypoint class. It is a GPSPoint with an ID. */ +//! This is the waypoint class. It is a GPSPoint with an ID. class QgsWaypoint : public QgsGPSPoint { public: @@ -128,11 +128,11 @@ class QgsGPSData { public: - /** This iterator type is used to iterate over waypoints. */ + //! This iterator type is used to iterate over waypoints. typedef QList::iterator WaypointIterator; - /** This iterator type is used to iterate over routes. */ + //! This iterator type is used to iterate over routes. typedef QList::iterator RouteIterator; - /** This iterator type is used to iterate over tracks. */ + //! This iterator type is used to iterate over tracks. typedef QList::iterator TrackIterator; @@ -145,25 +145,25 @@ class QgsGPSData yourself. */ QgsRectangle getExtent() const; - /** Sets a default sensible extent. Only applies when there are no actual data. */ + //! Sets a default sensible extent. Only applies when there are no actual data. void setNoDataExtent(); - /** Returns the number of waypoints in this dataset. */ + //! Returns the number of waypoints in this dataset. int getNumberOfWaypoints() const; - /** Returns the number of waypoints in this dataset. */ + //! Returns the number of waypoints in this dataset. int getNumberOfRoutes() const; - /** Returns the number of waypoints in this dataset. */ + //! Returns the number of waypoints in this dataset. int getNumberOfTracks() const; - /** This function returns an iterator that points to the first waypoint. */ + //! This function returns an iterator that points to the first waypoint. WaypointIterator waypointsBegin(); - /** This function returns an iterator that points to the first route. */ + //! This function returns an iterator that points to the first route. RouteIterator routesBegin(); - /** This function returns an iterator that points to the first track. */ + //! This function returns an iterator that points to the first track. TrackIterator tracksBegin(); /** This function returns an iterator that points to the end of the @@ -198,13 +198,13 @@ class QgsGPSData TrackIterator addTrack( const QgsTrack& trk ); - /** This function removes the waypoints whose IDs are in the list. */ + //! This function removes the waypoints whose IDs are in the list. void removeWaypoints( const QgsFeatureIds & ids ); - /** This function removes the routes whose IDs are in the list. */ + //! This function removes the routes whose IDs are in the list. void removeRoutes( const QgsFeatureIds & ids ); - /** This function removes the tracks whose IDs are in the list. */ + //! This function removes the tracks whose IDs are in the list. void removeTracks( const QgsFeatureIds & ids ); /** This function will write the contents of this GPSData object as XML to @@ -229,7 +229,7 @@ class QgsGPSData static void releaseData( const QString& fileName ); - /** Operator<< is our friend. For debugging, not for file I/O. */ + //! Operator<< is our friend. For debugging, not for file I/O. //friend std::ostream& operator<<(std::ostream& os, const GPSData& d); protected: @@ -241,7 +241,7 @@ class QgsGPSData double xMin, xMax, yMin, yMax; - /** This is used internally to store GPS data objects (one per file). */ + //! This is used internally to store GPS data objects (one per file). typedef QMap > DataMap; /** This is the static container that maps file names to GPSData objects and @@ -308,7 +308,7 @@ class QgsGPXHandler ParsingUnknown }; - /** This is used to keep track of what kind of data we are parsing. */ + //! This is used to keep track of what kind of data we are parsing. QStack parseModes; QgsGPSData& mData; diff --git a/src/providers/gpx/qgsgpxprovider.h b/src/providers/gpx/qgsgpxprovider.h index 7535331460a2..4c74f657fce5 100644 --- a/src/providers/gpx/qgsgpxprovider.h +++ b/src/providers/gpx/qgsgpxprovider.h @@ -101,10 +101,10 @@ class QgsGPXProvider : public QgsVectorDataProvider virtual QgsRectangle extent() const override; virtual bool isValid() const override; - /** Return a provider name */ + //! Return a provider name virtual QString name() const override; - /** Return description */ + //! Return description virtual QString description() const override; virtual QgsCoordinateReferenceSystem crs() const override; @@ -115,7 +115,7 @@ class QgsGPXProvider : public QgsVectorDataProvider void changeAttributeValues( QgsGPSObject& obj, const QgsAttributeMap& attrs ); - /** Adds one feature (used by addFeatures()) */ + //! Adds one feature (used by addFeatures()) bool addFeature( QgsFeature& f ); diff --git a/src/providers/grass/qgsgrass.h b/src/providers/grass/qgsgrass.h index 624ca8573843..b67e722ebb1c 100644 --- a/src/providers/grass/qgsgrass.h +++ b/src/providers/grass/qgsgrass.h @@ -178,10 +178,10 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject QgsGrass(); - /** Get singleton instance of this class. Used as signals proxy between provider and plugin. */ + //! Get singleton instance of this class. Used as signals proxy between provider and plugin. static QgsGrass* instance(); - /** Global GRASS library lock */ + //! Global GRASS library lock static void lock(); static void unlock(); @@ -236,18 +236,18 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject */ bool isMapsetInSearchPath( const QString &mapset ); - /** Add mapset to search path of currently open mapset */ + //! Add mapset to search path of currently open mapset void addMapsetToSearchPath( const QString & mapset, QString& error ); - /** Add mapset to search path of currently open mapset */ + //! Add mapset to search path of currently open mapset void removeMapsetFromSearchPath( const QString & mapset, QString& error ); //! Error codes returned by error() enum GERROR { - OK, /*!< OK. No error. */ - WARNING, /*!< Warning, non fatal error. Should be printed by application. */ - FATAL /*!< Fatal error */ + OK, //!< OK. No error. + WARNING, //!< Warning, non fatal error. Should be printed by application. + FATAL //!< Fatal error }; //! Reset error code (to OK). Call this before a piece of code where an error is expected @@ -262,7 +262,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject //! Get initialization error static QString initError() { return mInitError; } - /** Test is current user is owner of mapset */ + //! Test is current user is owner of mapset static bool isOwner( const QString& gisdbase, const QString& location, const QString& mapset ); /** Open existing GRASS mapset. @@ -280,10 +280,10 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject */ static QString closeMapset(); - /** \brief Save current mapset to project file. */ + //! \brief Save current mapset to project file. static void saveMapset(); - /** Create new mapset in existing location */ + //! Create new mapset in existing location static void createMapset( const QString& gisdbase, const QString& location, const QString& mapset, QString& error ); @@ -498,21 +498,21 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject * @param error */ static void createVectorMap( const QgsGrassObject & object, QString &error ); - /** Create new table. Throws QgsGrass::Exception */ + //! Create new table. Throws QgsGrass::Exception static void createTable( dbDriver *driver, const QString &tableName, const QgsFields &fields ); - /** Insert row to table. Throws QgsGrass::Exception */ + //! Insert row to table. Throws QgsGrass::Exception static void insertRow( dbDriver *driver, const QString &tableName, const QgsAttributes& attributes ); - /** Returns true if object is link to external data (created by r.external) */ + //! Returns true if object is link to external data (created by r.external) static bool isExternal( const QgsGrassObject & object ); /** Adjust cell header, G_adjust_Cell_head wrapper * @throws QgsGrass::Exception */ static void adjustCellHead( struct Cell_head *cellhd, int row_flag, int col_flag ); - /** Get map of vector types / names */ + //! Get map of vector types / names static QMap vectorTypeMap(); /** Get GRASS vector type from name @@ -583,7 +583,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject static QPen regionPen(); - /** Store region pen in settings, emits regionPenChanged */ + //! Store region pen in settings, emits regionPenChanged void setRegionPen( const QPen & pen ); // Modules UI debug @@ -592,10 +592,10 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject // Switch modules UI debug void setModulesDebug( bool debug ); - /** Show warning dialog with message */ + //! Show warning dialog with message static void warning( const QString &message ); - /** Show warning dialog with exception message */ + //! Show warning dialog with exception message static void warning( QgsGrass::Exception &e ); /** Set mute mode, if set, warning() does not open dialog but prints only @@ -621,31 +621,31 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject static ModuleOutput parseModuleOutput( const QString & input, QString &text, QString &html, int &value ); public slots: - /** Close mapset and show warning if closing failed */ + //! Close mapset and show warning if closing failed bool closeMapsetWarn(); void openOptions(); - /** Read mapset search path from GRASS location */ + //! Read mapset search path from GRASS location void loadMapsetSearchPath(); void setMapsetSearchPathWatcher(); void onSearchPathFileChanged( const QString & path ); signals: - /** Signal emitted when user changed GISBASE */ + //! Signal emitted when user changed GISBASE void gisbaseChanged(); - /** Signal emitted after mapset was opened */ + //! Signal emitted after mapset was opened void mapsetChanged(); - /** Signal emitted when mapset search path changed (SEARCH_PATH file changed and it was loaded to mMapsetSearchPath) */ + //! Signal emitted when mapset search path changed (SEARCH_PATH file changed and it was loaded to mMapsetSearchPath) void mapsetSearchPathChanged(); - /** Emitted when path to modules config dir changed */ + //! Emitted when path to modules config dir changed void modulesConfigChanged(); - /** Emitted when modules debug mode changed */ + //! Emitted when modules debug mode changed void modulesDebugChanged(); /** Emitted when current region changed @@ -654,7 +654,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject */ void regionChanged(); - /** Emitted when region pen changed */ + //! Emitted when region pen changed void regionPenChanged(); /** Request from browser to open a new layer for editing, the plugin should connect diff --git a/src/providers/grass/qgsgrassfeatureiterator.h b/src/providers/grass/qgsgrassfeatureiterator.h index 297b0dd965ec..205beb9e56bb 100644 --- a/src/providers/grass/qgsgrassfeatureiterator.h +++ b/src/providers/grass/qgsgrassfeatureiterator.h @@ -37,8 +37,8 @@ class GRASS_LIB_EXPORT QgsGrassFeatureSource : public QgsAbstractFeatureSource enum Selection { - NotSelected = 0, /*!< not selected */ - Selected = 1, /*!< line/area selected */ + NotSelected = 0, //!< Not selected + Selected = 1, //!< Line/area selected Used = 2 /*!< the line was already used to create feature read in this cycle. * The codes Used must be reset to Selected if getFirstFeature() or select() is called. * Distinction between Selected and Used is used if attribute table exists, in which case @@ -110,7 +110,7 @@ class GRASS_LIB_EXPORT QgsGrassFeatureIterator : public QObject, public QgsAbstr //void lock(); //void unlock(); - /** Reset selection */ + //! Reset selection void resetSelection( bool value ); void setSelectionRect( const QgsRectangle& rect, bool useIntersect ); @@ -130,10 +130,10 @@ class GRASS_LIB_EXPORT QgsGrassFeatureIterator : public QObject, public QgsAbstr */ void setFeatureAttributes( int cat, QgsFeature *feature, const QgsAttributeList & attlist, QgsGrassVectorMap::TopoSymbol symbol ); - /** Canceled -> close when possible */ + //! Canceled -> close when possible bool mCanceled; - /** Selection array */ + //! Selection array QBitArray mSelection; // !UPDATE! // Edit mode is using mNextLid + mNextCidx diff --git a/src/providers/grass/qgsgrassgislib.h b/src/providers/grass/qgsgrassgislib.h index 59f768eb727d..bb677e30af71 100644 --- a/src/providers/grass/qgsgrassgislib.h +++ b/src/providers/grass/qgsgrassgislib.h @@ -110,20 +110,20 @@ class GRASS_LIB_EXPORT QgsGrassGisLib int G_get_ellipsoid_parameters( double *a, double *e2 ); - /** Get QGIS raster type for GRASS raster type */ + //! Get QGIS raster type for GRASS raster type Qgis::DataType qgisRasterType( RASTER_MAP_TYPE grassType ); - /** Get GRASS raster type for QGIS raster type */ + //! Get GRASS raster type for QGIS raster type RASTER_MAP_TYPE grassRasterType( Qgis::DataType qgisType ); - /** Get no data value for GRASS data type */ + //! Get no data value for GRASS data type double noDataValueForGrassType( RASTER_MAP_TYPE grassType ); /** Grass does not seem to have any function to init Cell_head, * initialization is done in G__read_Cell_head_array */ void initCellHead( struct Cell_head *cellhd ); - /** Get raster from map of opened rasters, open it if it is not yet open */ + //! Get raster from map of opened rasters, open it if it is not yet open Raster raster( QString name ); void * resolve( const char * symbol ); @@ -136,32 +136,32 @@ class GRASS_LIB_EXPORT QgsGrassGisLib void warning( QString msg ); private: - /** Pointer to canonical Singleton object */ + //! Pointer to canonical Singleton object static QgsGrassGisLib* _instance; - /** Original GRASS library handle */ + //! Original GRASS library handle QLibrary mLibrary; - /** Raster maps, key is fake file descriptor */ + //! Raster maps, key is fake file descriptor QMap mRasters; - /** Region to be used for data processing and output */ + //! Region to be used for data processing and output struct Cell_head mWindow; - /** Current region extent */ + //! Current region extent QgsRectangle mExtent; - /** Current region rows */ + //! Current region rows int mRows; - /** Current region columns */ + //! Current region columns int mColumns; - /** X resolution */ + //! X resolution double mXRes; - /** Y resolution */ + //! Y resolution double mYRes; - /** Current coordinate reference system */ + //! Current coordinate reference system QgsCoordinateReferenceSystem mCrs; QgsDistanceArea mDistanceArea; - /** Lat1, lat2 used for geodesic distance calculation */ + //! Lat1, lat2 used for geodesic distance calculation double mLat1, mLat2; }; diff --git a/src/providers/grass/qgsgrassprovider.h b/src/providers/grass/qgsgrassprovider.h index daef91fec2d3..07ce0521fa22 100644 --- a/src/providers/grass/qgsgrassprovider.h +++ b/src/providers/grass/qgsgrassprovider.h @@ -93,7 +93,7 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider // ! Key (category) field index int keyField(); - /** Restart reading features from previous select operation */ + //! Restart reading features from previous select operation void rewind(); QVariant minimumValue( int index ) const override; @@ -108,7 +108,7 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider */ void update(); - /** Load info (mNumberFeatures, mCidxFieldIndex, mCidxFieldNumCats) from map */ + //! Load info (mNumberFeatures, mCidxFieldIndex, mCidxFieldNumCats) from map void loadMapInfo(); bool isValid() const override; @@ -155,10 +155,10 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider //void startEditing( QgsVectorLayerEditBuffer* buffer ); void startEditing( QgsVectorLayer *vectorLayer ); - /** Freeze vector. */ + //! Freeze vector. void freeze(); - /** Thaw vector. */ + //! Thaw vector. void thaw(); /** Close editing. Rebuild topology, GMAP.update = false @@ -324,16 +324,16 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider /* Following functions work only until first edit operation! (category index used) */ - /** Get number of fields in category index */ + //! Get number of fields in category index int cidxGetNumFields( void ); - /** Get field number for index */ + //! Get field number for index int cidxGetFieldNumber( int idx ); - /** Get maximum category for field index */ + //! Get maximum category for field index int cidxGetMaxCat( int idx ); - /** Returns GRASS layer number */ + //! Returns GRASS layer number int grassLayer(); /** Returns GRASS layer number for given layer name or -1 if cannot @@ -346,10 +346,10 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider */ static int grassLayerType( const QString & ); - /** Return a provider name */ + //! Return a provider name QString name() const override; - /** Return description */ + //! Return description QString description() const override; // Layer type (layerType) @@ -432,10 +432,10 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider */ static char *attribute( int layerId, int cat, int column ); - /** Check if provider is outdated and update if necessary */ + //! Check if provider is outdated and update if necessary void ensureUpdated() const; - /** Check if layer is topology layer TOPO_POINT, TOPO_NODE, TOPO_LINE */ + //! Check if layer is topology layer TOPO_POINT, TOPO_NODE, TOPO_LINE bool isTopoType() const; static bool isTopoType( int layerType ); @@ -447,7 +447,7 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider // Get other edited layer, returns 0 if layer does not exist QgsGrassVectorMapLayer * otherEditLayer( int layerField ); - /** Fields used for topo layers */ + //! Fields used for topo layers QgsFields mTopoFields; //QgsFields mEditFields; diff --git a/src/providers/grass/qgsgrassvector.h b/src/providers/grass/qgsgrassvector.h index a714fe2ea25d..2596989586a5 100644 --- a/src/providers/grass/qgsgrassvector.h +++ b/src/providers/grass/qgsgrassvector.h @@ -36,19 +36,19 @@ class GRASS_LIB_EXPORT QgsGrassVectorLayer : public QObject QgsGrassObject grassObject() const { return mGrassObject; } - /** Layer number (field) */ + //! Layer number (field) int number() { return mNumber; } - /** Set number of elements of given type. */ + //! Set number of elements of given type. void setTypeCount( int type, int count ) { mTypeCounts[type] = count; } - /** Get number of elements of given type. Types may be combined by bitwise or)*/ + //! Get number of elements of given type. Types may be combined by bitwise or) int typeCount( int type ) const; - /** Get all types in the layer (combined by bitwise or)*/ + //! Get all types in the layer (combined by bitwise or) int type() const; - /** Get all types in the layer as list */ + //! Get all types in the layer as list QList types() const; QgsFields fields(); @@ -84,27 +84,27 @@ class GRASS_LIB_EXPORT QgsGrassVector : public QObject QgsGrassVector( const QgsGrassObject& grassObject, QObject *parent = 0 ); - /** Open header and read layers/types */ + //! Open header and read layers/types bool openHead(); - /** Get list of layers. The layers exist until the vector is deleted or reloaded */ + //! Get list of layers. The layers exist until the vector is deleted or reloaded QList layers() const { return mLayers; } /** Get numbers of primitives * @return type/count pairs */ QMap typeCounts() const {return mTypeCounts; } - /** Get total number of primitives of given type. Types may be combined by bitwise or) */ + //! Get total number of primitives of given type. Types may be combined by bitwise or) int typeCount( int type ) const; /** Maximum layer number (field). * @return max layer number or 0 if no layer exists */ int maxLayerNumber() const; - /** Get number of nodes */ + //! Get number of nodes int nodeCount() const { return mNodeCount; } - /** Return error message */ + //! Return error message QString error() const { return mError; } signals: diff --git a/src/providers/grass/qgsgrassvectormap.h b/src/providers/grass/qgsgrassvectormap.h index 13115c4faea7..4f707bb6502a 100644 --- a/src/providers/grass/qgsgrassvectormap.h +++ b/src/providers/grass/qgsgrassvectormap.h @@ -93,19 +93,19 @@ class GRASS_LIB_EXPORT QgsGrassVectorMap : public QObject QgsAbstractGeometry * nodeGeometry( int id ); QgsAbstractGeometry * areaGeometry( int id ); - /** Open map if not yet open. Open/close lock */ + //! Open map if not yet open. Open/close lock bool open(); - /** Close map. All iterators are closed first. Open/close lock. */ + //! Close map. All iterators are closed first. Open/close lock. void close(); - /** Open GRASS map, no open/close locking */ + //! Open GRASS map, no open/close locking bool openMap(); - /** Close GRASS map, no open/close locking */ + //! Close GRASS map, no open/close locking void closeMap(); - /** Reload layers from (reopened) map. The layers keep field/type. */ + //! Reload layers from (reopened) map. The layers keep field/type. void reloadLayers(); bool startEdit(); @@ -136,7 +136,7 @@ class GRASS_LIB_EXPORT QgsGrassVectorMap : public QObject */ bool attributesOutdated(); - /** Map descripton for debugging */ + //! Map descripton for debugging QString toString(); /** Get topology symbol code @@ -153,14 +153,14 @@ class GRASS_LIB_EXPORT QgsGrassVectorMap : public QObject * Qt::DirectConnection (non blocking) */ void cancelIterators(); - /** Close all iterators. Connected to iterators in different threads with Qt::BlockingQueuedConnection */ + //! Close all iterators. Connected to iterators in different threads with Qt::BlockingQueuedConnection void closeIterators(); - /** Emitted when data were reloaded */ + //! Emitted when data were reloaded void dataChanged(); private: - /** Close iterators, blocking */ + //! Close iterators, blocking void closeAllIterators(); QgsGrassObject mGrassObject; @@ -231,7 +231,7 @@ class GRASS_LIB_EXPORT QgsGrassVectorMapStore QgsGrassVectorMap * openMap( const QgsGrassObject & grassObject ); private: - /** Open vector maps */ + //! Open vector maps QList mMaps; // Lock open/close map diff --git a/src/providers/grass/qgsgrassvectormaplayer.h b/src/providers/grass/qgsgrassvectormaplayer.h index 4ea54fe92e23..f1ca5520746e 100644 --- a/src/providers/grass/qgsgrassvectormaplayer.h +++ b/src/providers/grass/qgsgrassvectormaplayer.h @@ -54,10 +54,10 @@ class GRASS_LIB_EXPORT QgsGrassVectorMapLayer : public QObject bool isValid() const { return mValid; } QgsGrassVectorMap *map() { return mMap; } - /** Category index index */ + //! Category index index int cidxFieldIndex(); - /** Current number of cats in cat index, changing during editing */ + //! Current number of cats in cat index, changing during editing int cidxFieldNumCats(); /** Original fields before editing started + topo field if edited. @@ -86,13 +86,13 @@ class GRASS_LIB_EXPORT QgsGrassVectorMapLayer : public QObject void addUser(); void removeUser(); - /** Load attributes from the map. Old sources are released. */ + //! Load attributes from the map. Old sources are released. void load(); - /** Clear all cached data */ + //! Clear all cached data void clear(); - /** Decrease number of users and clear if no more users */ + //! Decrease number of users and clear if no more users void close(); void startEdit(); @@ -156,7 +156,7 @@ class GRASS_LIB_EXPORT QgsGrassVectorMapLayer : public QObject void deleteColumn( const QgsField &field, QString &error ); - /** Insert records for all existing categories to the table */ + //! Insert records for all existing categories to the table void insertCats( QString &error ); // update fields to real state diff --git a/src/providers/memory/qgsmemoryprovider.h b/src/providers/memory/qgsmemoryprovider.h index 7beb40298c04..88e6adf39f5b 100644 --- a/src/providers/memory/qgsmemoryprovider.h +++ b/src/providers/memory/qgsmemoryprovider.h @@ -110,7 +110,7 @@ class QgsMemoryProvider : public QgsVectorDataProvider QString subsetString() const override; - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } diff --git a/src/providers/mssql/qgsmssqlnewconnection.cpp b/src/providers/mssql/qgsmssqlnewconnection.cpp index 1b090d9d1765..5fd8099c3a14 100644 --- a/src/providers/mssql/qgsmssqlnewconnection.cpp +++ b/src/providers/mssql/qgsmssqlnewconnection.cpp @@ -66,7 +66,7 @@ QgsMssqlNewConnection::QgsMssqlNewConnection( QWidget *parent, const QString& co } on_cb_trustedConnection_clicked(); } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * void QgsMssqlNewConnection::accept() { QSettings settings; @@ -140,7 +140,7 @@ void QgsMssqlNewConnection::on_cb_trustedConnection_clicked() } } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * QgsMssqlNewConnection::~QgsMssqlNewConnection() { diff --git a/src/providers/mssql/qgsmssqlprovider.h b/src/providers/mssql/qgsmssqlprovider.h index 982b2be960f2..916cf6fc06a4 100644 --- a/src/providers/mssql/qgsmssqlprovider.h +++ b/src/providers/mssql/qgsmssqlprovider.h @@ -91,14 +91,14 @@ class QgsMssqlProvider : public QgsVectorDataProvider */ virtual long featureCount() const override; - /** Update the extent, feature count, wkb type and srid for this layer */ + //! Update the extent, feature count, wkb type and srid for this layer void UpdateStatistics( bool estimate ) const; virtual QgsFields fields() const override; QString subsetString() const override; - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } @@ -146,10 +146,10 @@ class QgsMssqlProvider : public QgsVectorDataProvider virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } - /** Writes a list of features to the database*/ + //! Writes a list of features to the database virtual bool addFeatures( QgsFeatureList & flist ) override; - /** Deletes a feature*/ + //! Deletes a feature virtual bool deleteFeatures( const QgsFeatureIds & id ) override; /** @@ -166,10 +166,10 @@ class QgsMssqlProvider : public QgsVectorDataProvider */ virtual bool deleteAttributes( const QgsAttributeIds &attributes ) override; - /** Changes attribute values of existing features */ + //! Changes attribute values of existing features virtual bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ) override; - /** Changes existing geometries*/ + //! Changes existing geometries virtual bool changeGeometryValues( const QgsGeometryMap &geometry_map ) override; /** @@ -177,18 +177,18 @@ class QgsMssqlProvider : public QgsVectorDataProvider */ virtual bool createSpatialIndex() override; - /** Create an attribute index on the datasource*/ + //! Create an attribute index on the datasource virtual bool createAttributeIndex( int field ) override; - /** Convert a QgsField to work with MSSQL */ + //! Convert a QgsField to work with MSSQL static bool convertField( QgsField &field ); - /** Convert values to quoted values for database work **/ + //! Convert values to quoted values for database work * static QString quotedValue( const QVariant& value ); QVariant defaultValue( int fieldId ) const override; - /** Import a vector layer into the database */ + //! Import a vector layer into the database static QgsVectorLayerImport::ImportError createEmptyLayer( const QString& uri, const QgsFields &fields, @@ -203,7 +203,7 @@ class QgsMssqlProvider : public QgsVectorDataProvider virtual QgsCoordinateReferenceSystem crs() const override; protected: - /** Loads fields from input file to member attributeFields */ + //! Loads fields from input file to member attributeFields QVariant::Type DecodeSqlType( const QString& sqlTypeName ); void loadFields(); void loadMetadata(); diff --git a/src/providers/mssql/qgsmssqlsourceselect.cpp b/src/providers/mssql/qgsmssqlsourceselect.cpp index 6485d4034c7f..72154ec5d7ec 100644 --- a/src/providers/mssql/qgsmssqlsourceselect.cpp +++ b/src/providers/mssql/qgsmssqlsourceselect.cpp @@ -38,7 +38,7 @@ #include #include -/** Used to create an editor for when the user tries to change the contents of a cell */ +//! Used to create an editor for when the user tries to change the contents of a cell QWidget *QgsMssqlSourceSelectDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const { Q_UNUSED( option ); @@ -205,7 +205,7 @@ QgsMssqlSourceSelect::QgsMssqlSourceSelect( QWidget *parent, Qt::WindowFlags fl, cbxAllowGeometrylessTables->setDisabled( true ); } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * // Slot for adding a new connection void QgsMssqlSourceSelect::on_btnNew_clicked() { @@ -280,7 +280,7 @@ void QgsMssqlSourceSelect::on_btnEdit_clicked() delete nc; } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * // Remember which database is selected void QgsMssqlSourceSelect::on_cmbConnections_activated( int ) diff --git a/src/providers/mssql/qgsmssqltablemodel.h b/src/providers/mssql/qgsmssqltablemodel.h index 8bea4bc1290e..0167b29a9a46 100644 --- a/src/providers/mssql/qgsmssqltablemodel.h +++ b/src/providers/mssql/qgsmssqltablemodel.h @@ -19,7 +19,7 @@ #include "qgis.h" -/** Layer Property structure */ +//! Layer Property structure struct QgsMssqlLayerProperty { // MSSQL layer properties @@ -46,17 +46,17 @@ class QgsMssqlTableModel : public QStandardItemModel QgsMssqlTableModel(); ~QgsMssqlTableModel(); - /** Adds entry for one database table to the model*/ + //! Adds entry for one database table to the model void addTableEntry( const QgsMssqlLayerProperty &property ); - /** Sets an sql statement that belongs to a cell specified by a model index*/ + //! Sets an sql statement that belongs to a cell specified by a model index void setSql( const QModelIndex& index, const QString& sql ); /** Sets one or more geometry types to a row. In case of several types, additional rows are inserted. This is for tables where the type is dectected later by thread*/ void setGeometryTypesForTable( QgsMssqlLayerProperty layerProperty ); - /** Returns the number of tables in the model*/ + //! Returns the number of tables in the model int tableCount() const { return mTableCount; } enum columns @@ -81,7 +81,7 @@ class QgsMssqlTableModel : public QStandardItemModel static QgsWkbTypes::Type wkbTypeFromMssql( QString dbType ); private: - /** Number of tables in the model*/ + //! Number of tables in the model int mTableCount; }; diff --git a/src/providers/ogr/qgsogrconnpool.h b/src/providers/ogr/qgsogrconnpool.h index 10035951c016..0aa84563cfb2 100644 --- a/src/providers/ogr/qgsogrconnpool.h +++ b/src/providers/ogr/qgsogrconnpool.h @@ -87,7 +87,7 @@ class QgsOgrConnPoolGroup : public QObject, public QgsConnectionPoolGroup { public: diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 66fdc6dc7a20..89191a6f2053 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -1981,17 +1981,17 @@ static QString createFileFilter_( QString const &longName, QString const &glob ) QString createFilters( const QString& type ) { - /** Database drivers available*/ + //! Database drivers available static QString myDatabaseDrivers; - /** Protocol drivers available*/ + //! Protocol drivers available static QString myProtocolDrivers; - /** File filters*/ + //! File filters static QString myFileFilters; - /** Directory drivers*/ + //! Directory drivers static QString myDirectoryDrivers; - /** Extensions*/ + //! Extensions static QStringList myExtensions; - /** Wildcards*/ + //! Wildcards static QStringList myWildcards; // if we've already built the supported vector string, just return what diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index b60aa3e09b3d..22291f0700a3 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -52,7 +52,7 @@ class QgsOgrProvider : public QgsVectorDataProvider public: - /** Convert a vector layer to a vector file */ + //! Convert a vector layer to a vector file static QgsVectorLayerImport::ImportError createEmptyLayer( const QString& uri, const QgsFields &fields, @@ -98,7 +98,7 @@ class QgsOgrProvider : public QgsVectorDataProvider virtual bool supportsSubsetString() const override { return true; } - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size virtual bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; /** @@ -128,27 +128,27 @@ class QgsOgrProvider : public QgsVectorDataProvider */ virtual void updateExtents() override; - /** Writes a list of features to the file*/ + //! Writes a list of features to the file virtual bool addFeatures( QgsFeatureList & flist ) override; - /** Deletes a feature*/ + //! Deletes a feature virtual bool deleteFeatures( const QgsFeatureIds & id ) override; virtual bool addAttributes( const QList &attributes ) override; virtual bool deleteAttributes( const QgsAttributeIds &attributes ) override; virtual bool renameAttributes( const QgsFieldNameMap& renamedAttributes ) override; - /** Changes attribute values of existing features */ + //! Changes attribute values of existing features virtual bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ) override; - /** Changes existing geometries*/ + //! Changes existing geometries virtual bool changeGeometryValues( const QgsGeometryMap &geometry_map ) override; /** Tries to create a .qix index file for faster access if only a subset of the features is required @return true in case of success*/ virtual bool createSpatialIndex() override; - /** Create an attribute index on the datasource*/ + //! Create an attribute index on the datasource virtual bool createAttributeIndex( int field ) override; /** Returns a bitmask containing the supported capabilities @@ -176,11 +176,11 @@ class QgsOgrProvider : public QgsVectorDataProvider */ /* virtual */ QString fileVectorFilters() const override; - /** Return a string containing the available database drivers */ + //! Return a string containing the available database drivers QString databaseDrivers() const; - /** Return a string containing the available directory drivers */ + //! Return a string containing the available directory drivers QString protocolDrivers() const; - /** Return a string containing the available protocol drivers */ + //! Return a string containing the available protocol drivers QString directoryDrivers() const; /** Returns true if this is a valid shapefile @@ -238,10 +238,10 @@ class QgsOgrProvider : public QgsVectorDataProvider */ virtual bool doesStrictFeatureTypeCheck() const override; - /** Return OGR geometry type */ + //! Return OGR geometry type static OGRwkbGeometryType getOgrGeomType( OGRLayerH ogrLayer ); - /** Get single flatten geometry type */ + //! Get single flatten geometry type static OGRwkbGeometryType ogrWkbSingleFlatten( OGRwkbGeometryType type ); QString layerName() const { return mLayerName; } @@ -259,26 +259,26 @@ class QgsOgrProvider : public QgsVectorDataProvider */ void forceReload() override; - /** Closes and re-open the datasource */ + //! Closes and re-open the datasource void reloadData() override; protected: - /** Loads fields from input file to member attributeFields */ + //! Loads fields from input file to member attributeFields void loadFields(); - /** Find out the number of features of the whole layer */ + //! Find out the number of features of the whole layer void recalculateFeatureCount(); - /** Tell OGR, which fields to fetch in nextFeature/featureAtId (ie. which not to ignore) */ + //! Tell OGR, which fields to fetch in nextFeature/featureAtId (ie. which not to ignore) void setRelevantFields( OGRLayerH ogrLayer, bool fetchGeometry, const QgsAttributeList& fetchAttributes ); - /** Convert a QgsField to work with OGR */ + //! Convert a QgsField to work with OGR static bool convertField( QgsField &field, const QTextCodec &encoding ); - /** Clean shapefile from features which are marked as deleted */ + //! Clean shapefile from features which are marked as deleted void repack(); - /** Invalidate extent and optionnaly force its low level recomputation */ + //! Invalidate extent and optionnaly force its low level recomputation void invalidateCachedExtent( bool bForceRecomputeExtent ); enum OpenMode @@ -344,30 +344,30 @@ class QgsOgrProvider : public QgsVectorDataProvider mutable QStringList mSubLayerList; - /** Adds one feature*/ + //! Adds one feature bool addFeature( QgsFeature& f ); - /** Deletes one feature*/ + //! Deletes one feature bool deleteFeature( QgsFeatureId id ); - /** Calls OGR_L_SyncToDisk and recreates the spatial index if present*/ + //! Calls OGR_L_SyncToDisk and recreates the spatial index if present bool syncToDisc(); OGRLayerH setSubsetString( OGRLayerH layer, OGRDataSourceH ds ); friend class QgsOgrFeatureSource; - /** Whether the file is opened in write mode*/ + //! Whether the file is opened in write mode bool mWriteAccess; - /** Whether the file can potentially be opened in write mode (but not necessarily currently) */ + //! Whether the file can potentially be opened in write mode (but not necessarily currently) bool mWriteAccessPossible; - /** Whether the open mode of the datasource changes w.r.t calls to enterUpdateMode() / leaveUpdateMode() */ + //! Whether the open mode of the datasource changes w.r.t calls to enterUpdateMode() / leaveUpdateMode() bool mDynamicWriteAccess; bool mShapefileMayBeCorrupted; - /** Converts the geometry to the layer type if necessary. Takes ownership of the passed geometry */ + //! Converts the geometry to the layer type if necessary. Takes ownership of the passed geometry OGRGeometryH ConvertGeometryIfNecessary( OGRGeometryH ); int mUpdateModeStackDepth; diff --git a/src/providers/oracle/qgsoracleconn.h b/src/providers/oracle/qgsoracleconn.h index 57c4e4845e77..d1fa11d71067 100644 --- a/src/providers/oracle/qgsoracleconn.h +++ b/src/providers/oracle/qgsoracleconn.h @@ -130,10 +130,10 @@ class QgsOracleConn : public QObject void retrieveLayerTypes( QgsOracleLayerProperty &layerProperty, bool useEstimatedMetadata, bool onlyExistingTypes ); - /** Gets information about the spatial tables */ + //! Gets information about the spatial tables bool tableInfo( bool geometryTablesOnly, bool userTablesOnly, bool allowGeometrylessTables ); - /** Get primary key candidates (all int4 columns) */ + //! Get primary key candidates (all int4 columns) QStringList pkCandidates( QString ownerName, QString viewName ); static QString fieldExpression( const QgsField &fld ); diff --git a/src/providers/oracle/qgsoracleconnpool.h b/src/providers/oracle/qgsoracleconnpool.h index 60810885a9ab..46d1d8f2b6c3 100644 --- a/src/providers/oracle/qgsoracleconnpool.h +++ b/src/providers/oracle/qgsoracleconnpool.h @@ -64,7 +64,7 @@ class QgsOracleConnPoolGroup : public QObject, public QgsConnectionPoolGroup { public: diff --git a/src/providers/oracle/qgsoraclenewconnection.cpp b/src/providers/oracle/qgsoraclenewconnection.cpp index b2ad458edbaa..a850b6ef4823 100644 --- a/src/providers/oracle/qgsoraclenewconnection.cpp +++ b/src/providers/oracle/qgsoraclenewconnection.cpp @@ -81,7 +81,7 @@ QgsOracleNewConnection::QgsOracleNewConnection( QWidget *parent, const QString& txtName->setText( connName ); } } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * void QgsOracleNewConnection::accept() { QSettings settings; @@ -165,7 +165,7 @@ void QgsOracleNewConnection::on_btnConnect_clicked() } } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * QgsOracleNewConnection::~QgsOracleNewConnection() { diff --git a/src/providers/oracle/qgsoracleprovider.h b/src/providers/oracle/qgsoracleprovider.h index 1c39a328b15c..3ba0ad3a3da3 100644 --- a/src/providers/oracle/qgsoracleprovider.h +++ b/src/providers/oracle/qgsoracleprovider.h @@ -59,7 +59,7 @@ class QgsOracleProvider : public QgsVectorDataProvider public: - /** Import a vector layer into the database */ + //! Import a vector layer into the database static QgsVectorLayerImport::ImportError createEmptyLayer( const QString& uri, const QgsFields &fields, @@ -180,10 +180,10 @@ class QgsOracleProvider : public QgsVectorDataProvider QgsAttributeList pkAttributeIndexes() const override { return mPrimaryKeyAttrs; } - /** Returns the default value for field specified by @c fieldName */ + //! Returns the default value for field specified by @c fieldName QVariant defaultValue( QString fieldName, QString tableName = QString::null, QString schemaName = QString::null ); - /** Returns the default value for field specified by @c fieldId */ + //! Returns the default value for field specified by @c fieldId QVariant defaultValue( int fieldId ) const override; /** Adds a list of features @@ -231,15 +231,15 @@ class QgsOracleProvider : public QgsVectorDataProvider //! Get the table name associated with this provider instance QString getTableName(); - /** Accessor for sql where clause used to limit dataset */ + //! Accessor for sql where clause used to limit dataset QString subsetString() const override; - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } - /** Returns a bitmask containing the supported capabilities*/ + //! Returns a bitmask containing the supported capabilities QgsVectorDataProvider::Capabilities capabilities() const override; /** Return a provider name @@ -298,7 +298,7 @@ class QgsOracleProvider : public QgsVectorDataProvider */ bool loadFields(); - /** Convert a QgsField to work with Oracle */ + //! Convert a QgsField to work with Oracle static bool convertField( QgsField &field ); QgsFields mAttributeFields; //! List of fields @@ -421,7 +421,7 @@ class QgsOracleProvider : public QgsVectorDataProvider }; -/** Assorted Oracle utility functions */ +//! Assorted Oracle utility functions class QgsOracleUtils { public: diff --git a/src/providers/oracle/qgsoraclesourceselect.cpp b/src/providers/oracle/qgsoraclesourceselect.cpp index 5da2f8b37ed1..27b90538938b 100644 --- a/src/providers/oracle/qgsoraclesourceselect.cpp +++ b/src/providers/oracle/qgsoraclesourceselect.cpp @@ -38,7 +38,7 @@ email : jef at norbit dot de #include #include -/** Used to create an editor for when the user tries to change the contents of a cell */ +//! Used to create an editor for when the user tries to change the contents of a cell QWidget *QgsOracleSourceSelectDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const { Q_UNUSED( option ); @@ -256,7 +256,7 @@ QgsOracleSourceSelect::QgsOracleSourceSelect( QWidget *parent, Qt::WindowFlags f populateConnectionList(); } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * // Slot for adding a new connection void QgsOracleSourceSelect::on_btnNew_clicked() { @@ -319,7 +319,7 @@ void QgsOracleSourceSelect::on_btnEdit_clicked() delete nc; } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * // Remember which database is selected void QgsOracleSourceSelect::on_cmbConnections_currentIndexChanged( const QString & text ) diff --git a/src/providers/oracle/qgsoracletablemodel.h b/src/providers/oracle/qgsoracletablemodel.h index 79c4b014b1ad..1ace38890aa4 100644 --- a/src/providers/oracle/qgsoracletablemodel.h +++ b/src/providers/oracle/qgsoracletablemodel.h @@ -33,13 +33,13 @@ class QgsOracleTableModel : public QStandardItemModel QgsOracleTableModel(); ~QgsOracleTableModel(); - /** Adds entry for one database table to the model*/ + //! Adds entry for one database table to the model void addTableEntry( const QgsOracleLayerProperty &property ); - /** Sets an sql statement that belongs to a cell specified by a model index*/ + //! Sets an sql statement that belongs to a cell specified by a model index void setSql( const QModelIndex& index, const QString& sql ); - /** Returns the number of tables in the model*/ + //! Returns the number of tables in the model int tableCount() const { return mTableCount; } enum columns @@ -62,7 +62,7 @@ class QgsOracleTableModel : public QStandardItemModel static QIcon iconForWkbType( QgsWkbTypes::Type type ); private: - /** Number of tables in the model*/ + //! Number of tables in the model int mTableCount; }; diff --git a/src/providers/postgres/qgspgnewconnection.cpp b/src/providers/postgres/qgspgnewconnection.cpp index 8bca623385b5..4a207983a257 100644 --- a/src/providers/postgres/qgspgnewconnection.cpp +++ b/src/providers/postgres/qgspgnewconnection.cpp @@ -104,7 +104,7 @@ QgsPgNewConnection::QgsPgNewConnection( QWidget *parent, const QString& connName txtName->setText( connName ); } } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * void QgsPgNewConnection::accept() { QSettings settings; @@ -176,7 +176,7 @@ void QgsPgNewConnection::on_cb_geometryColumnsOnly_clicked() cb_publicSchemaOnly->setEnabled( true ); } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * QgsPgNewConnection::~QgsPgNewConnection() { diff --git a/src/providers/postgres/qgspgsourceselect.cpp b/src/providers/postgres/qgspgsourceselect.cpp index 527a92aee7da..c858a979a340 100644 --- a/src/providers/postgres/qgspgsourceselect.cpp +++ b/src/providers/postgres/qgspgsourceselect.cpp @@ -38,7 +38,7 @@ email : sherman at mrcc.com #include #include -/** Used to create an editor for when the user tries to change the contents of a cell */ +//! Used to create an editor for when the user tries to change the contents of a cell QWidget *QgsPgSourceSelectDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const { Q_UNUSED( option ); @@ -281,7 +281,7 @@ QgsPgSourceSelect::QgsPgSourceSelect( QWidget *parent, Qt::WindowFlags fl, bool mSearchModeLabel->setVisible( false ); mSearchTableEdit->setVisible( false ); } -/** Autoconnected SLOTS **/ +//! Autoconnected SLOTS * // Slot for adding a new connection void QgsPgSourceSelect::on_btnNew_clicked() { @@ -339,7 +339,7 @@ void QgsPgSourceSelect::on_btnEdit_clicked() delete nc; } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * // Remember which database is selected void QgsPgSourceSelect::on_cmbConnections_currentIndexChanged( const QString & text ) diff --git a/src/providers/postgres/qgspgtablemodel.h b/src/providers/postgres/qgspgtablemodel.h index 784b043b7c9c..11f9bbc9a070 100644 --- a/src/providers/postgres/qgspgtablemodel.h +++ b/src/providers/postgres/qgspgtablemodel.h @@ -33,13 +33,13 @@ class QgsPgTableModel : public QStandardItemModel QgsPgTableModel(); ~QgsPgTableModel(); - /** Adds entry for one database table to the model*/ + //! Adds entry for one database table to the model void addTableEntry( const QgsPostgresLayerProperty& property ); - /** Sets an sql statement that belongs to a cell specified by a model index*/ + //! Sets an sql statement that belongs to a cell specified by a model index void setSql( const QModelIndex& index, const QString& sql ); - /** Returns the number of tables in the model*/ + //! Returns the number of tables in the model int tableCount() const { return mTableCount; } enum columns @@ -64,7 +64,7 @@ class QgsPgTableModel : public QStandardItemModel static QIcon iconForWkbType( QgsWkbTypes::Type type ); private: - /** Number of tables in the model*/ + //! Number of tables in the model int mTableCount; }; diff --git a/src/providers/postgres/qgspostgresconn.h b/src/providers/postgres/qgspostgresconn.h index c33130c97e39..933f78e3b6a3 100644 --- a/src/providers/postgres/qgspostgresconn.h +++ b/src/providers/postgres/qgspostgresconn.h @@ -35,7 +35,7 @@ extern "C" class QgsField; -/** Spatial column types */ +//! Spatial column types enum QgsPostgresGeometryColumnType { sctNone, @@ -55,7 +55,7 @@ enum QgsPostgresPrimaryKeyType pktFidMap }; -/** Schema properties structure */ +//! Schema properties structure struct QgsPostgresSchemaProperty { QString name; @@ -63,7 +63,7 @@ struct QgsPostgresSchemaProperty QString owner; }; -/** Layer Property structure */ +//! Layer Property structure // TODO: Fill to Postgres/PostGIS specifications struct QgsPostgresLayerProperty { @@ -335,7 +335,7 @@ class QgsPostgresConn : public QObject static bool allowGeometrylessTables( const QString& theConnName ); static void deleteConnection( const QString& theConnName ); - /** A connection needs to be locked when it uses transactions, see QgsPostgresConn::{begin,commit,rollback} */ + //! A connection needs to be locked when it uses transactions, see QgsPostgresConn::{begin,commit,rollback} void lock() { mLock.lock(); } void unlock() { mLock.unlock(); } @@ -386,7 +386,7 @@ class QgsPostgresConn : public QObject static QMap sConnectionsRW; static QMap sConnectionsRO; - /** Count number of spatial columns in a given relation */ + //! Count number of spatial columns in a given relation void addColumnInfo( QgsPostgresLayerProperty& layerProperty, const QString& schemaName, const QString& viewName, bool fetchPkCandidates ); //! List of the supported layers diff --git a/src/providers/postgres/qgspostgresconnpool.h b/src/providers/postgres/qgspostgresconnpool.h index a3ae398c03e8..833441558724 100644 --- a/src/providers/postgres/qgspostgresconnpool.h +++ b/src/providers/postgres/qgspostgresconnpool.h @@ -64,7 +64,7 @@ class QgsPostgresConnPoolGroup : public QObject, public QgsConnectionPoolGroup { public: diff --git a/src/providers/postgres/qgspostgresdataitems.h b/src/providers/postgres/qgspostgresdataitems.h index 96d113838573..870e6cda7050 100644 --- a/src/providers/postgres/qgspostgresdataitems.h +++ b/src/providers/postgres/qgspostgresdataitems.h @@ -111,7 +111,7 @@ class QgsPGLayerItem : public QgsLayerItem virtual QList actions() override; - /** Returns comments of the layer */ + //! Returns comments of the layer virtual QString comments() const override; public slots: diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 2cca87a975f2..0b600accf263 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -651,7 +651,7 @@ QString QgsPostgresProvider::dataComment() const } -/** @todo XXX Perhaps this should be promoted to QgsDataProvider? */ +//! @todo XXX Perhaps this should be promoted to QgsDataProvider? QString QgsPostgresProvider::endianString() { switch ( QgsApplication::endian() ) diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index d1c46c808da1..eb90e2d770db 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -207,12 +207,12 @@ class QgsPostgresProvider : public QgsVectorDataProvider QString subsetString() const override; - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } - /** Returns a bitmask containing the supported capabilities*/ + //! Returns a bitmask containing the supported capabilities QgsVectorDataProvider::Capabilities capabilities() const override; /** The Postgres provider does its own transforms so we return @@ -330,7 +330,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider */ void setEditorWidgets(); - /** Convert a QgsField to work with PG */ + //! Convert a QgsField to work with PG static bool convertField( QgsField &field, const QMap *options = nullptr ); /** Parses the enum_range of an attribute and inserts the possible values into a stringlist @@ -362,7 +362,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider */ static QList searchLayers( const QList& layers, const QString& connectionInfo, const QString& schema, const QString& tableName ); - /** Old-style mapping of index to name for QgsPalLabeling fix */ + //! Old-style mapping of index to name for QgsPalLabeling fix QgsAttrPalIndexNameHash mAttrPalIndexName; QgsFields mAttributeFields; @@ -496,7 +496,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider }; -/** Assorted Postgres utility functions */ +//! Assorted Postgres utility functions class QgsPostgresUtils { public: diff --git a/src/providers/spatialite/qgsspatialiteconnection.h b/src/providers/spatialite/qgsspatialiteconnection.h index be6f55a938ba..7cdecef6525e 100644 --- a/src/providers/spatialite/qgsspatialiteconnection.h +++ b/src/providers/spatialite/qgsspatialiteconnection.h @@ -29,7 +29,7 @@ class QgsSpatiaLiteConnection : public QObject { Q_OBJECT public: - /** Construct a connection. Name can be either stored connection name or a path to the database file */ + //! Construct a connection. Name can be either stored connection name or a path to the database file explicit QgsSpatiaLiteConnection( const QString& name ); QString path() { return mPath; } @@ -68,13 +68,13 @@ class QgsSpatiaLiteConnection : public QObject Error fetchTables( bool loadGeometrylessTables ); - /** Return list of tables. fetchTables() function has to be called before */ + //! Return list of tables. fetchTables() function has to be called before QList tables() { return mTables; } - /** Return additional error message (if an error occurred before) */ + //! Return additional error message (if an error occurred before) QString errorMessage() { return mErrorMsg; } - /** Updates the Internal Statistics*/ + //! Updates the Internal Statistics bool updateStatistics(); protected: @@ -82,7 +82,7 @@ class QgsSpatiaLiteConnection : public QObject sqlite3 *openSpatiaLiteDb( const QString& path ); void closeSpatiaLiteDb( sqlite3 * handle ); - /** Checks if geometry_columns and spatial_ref_sys exist and have expected layout*/ + //! Checks if geometry_columns and spatial_ref_sys exist and have expected layout int checkHasMetadataTables( sqlite3* handle ); /** Inserts information about the spatial tables into mTables @@ -103,22 +103,22 @@ class QgsSpatiaLiteConnection : public QObject bool getTableInfoAbstractInterface( sqlite3 * handle, bool loadGeometrylessTables ); #endif - /** Cleaning well-formatted SQL strings*/ + //! Cleaning well-formatted SQL strings QString quotedValue( QString value ) const; - /** Checks if geometry_columns_auth table exists*/ + //! Checks if geometry_columns_auth table exists bool checkGeometryColumnsAuth( sqlite3 * handle ); - /** Checks if views_geometry_columns table exists*/ + //! Checks if views_geometry_columns table exists bool checkViewsGeometryColumns( sqlite3 * handle ); - /** Checks if virts_geometry_columns table exists*/ + //! Checks if virts_geometry_columns table exists bool checkVirtsGeometryColumns( sqlite3 * handle ); - /** Checks if this layer has been declared HIDDEN*/ + //! Checks if this layer has been declared HIDDEN bool isDeclaredHidden( sqlite3 * handle, const QString& table, const QString& geom ); - /** Checks if this layer is a RasterLite-1 datasource*/ + //! Checks if this layer is a RasterLite-1 datasource bool isRasterlite1Datasource( sqlite3 * handle, const char * table ); QString mErrorMsg; diff --git a/src/providers/spatialite/qgsspatialiteconnpool.h b/src/providers/spatialite/qgsspatialiteconnpool.h index 1266d06be022..436500eb01cf 100644 --- a/src/providers/spatialite/qgsspatialiteconnpool.h +++ b/src/providers/spatialite/qgsspatialiteconnpool.h @@ -65,7 +65,7 @@ class QgsSpatiaLiteConnPoolGroup : public QObject, public QgsConnectionPoolGroup }; -/** SpatiaLite connection pool - singleton */ +//! SpatiaLite connection pool - singleton class QgsSpatiaLiteConnPool : public QgsConnectionPool { static QgsSpatiaLiteConnPool sInstance; diff --git a/src/providers/spatialite/qgsspatialitefeatureiterator.h b/src/providers/spatialite/qgsspatialitefeatureiterator.h index f660064e9571..5b914465cf2f 100644 --- a/src/providers/spatialite/qgsspatialitefeatureiterator.h +++ b/src/providers/spatialite/qgsspatialitefeatureiterator.h @@ -94,7 +94,7 @@ class QgsSpatiaLiteFeatureIterator : public QgsAbstractFeatureIteratorFromSource */ sqlite3_stmt *sqliteStatement; - /** Geometry column index used when fetching geometry */ + //! Geometry column index used when fetching geometry int mGeomColIdx; //! Set to true, if geometry is in the requested columns diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 09a37d6b6fd7..228cb0866f8c 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -55,7 +55,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider Q_OBJECT public: - /** Import a vector layer into the database */ + //! Import a vector layer into the database static QgsVectorLayerImport::ImportError createEmptyLayer( const QString& uri, const QgsFields &fields, @@ -92,7 +92,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider virtual QString subsetString() const override; - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size virtual bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } @@ -162,7 +162,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider */ bool changeGeometryValues( const QgsGeometryMap &geometry_map ) override; - /** Returns a bitmask containing the supported capabilities*/ + //! Returns a bitmask containing the supported capabilities QgsVectorDataProvider::Capabilities capabilities() const override; /** The SpatiaLite provider does its own transforms so we return diff --git a/src/providers/spatialite/qgsspatialitesourceselect.cpp b/src/providers/spatialite/qgsspatialitesourceselect.cpp index 5f80ed6f51e8..c54723a2664e 100644 --- a/src/providers/spatialite/qgsspatialitesourceselect.cpp +++ b/src/providers/spatialite/qgsspatialitesourceselect.cpp @@ -127,7 +127,7 @@ void QgsSpatiaLiteSourceSelect::addClicked() addTables(); } -/** End Autoconnected SLOTS **/ +//! End Autoconnected SLOTS * // Remember which database is selected void QgsSpatiaLiteSourceSelect::on_cmbConnections_activated( int ) diff --git a/src/providers/spatialite/qgsspatialitetablemodel.h b/src/providers/spatialite/qgsspatialitetablemodel.h index bb4a40722fc8..495c713a7d37 100644 --- a/src/providers/spatialite/qgsspatialitetablemodel.h +++ b/src/providers/spatialite/qgsspatialitetablemodel.h @@ -28,31 +28,31 @@ class QgsSpatiaLiteTableModel: public QStandardItemModel QgsSpatiaLiteTableModel(); ~QgsSpatiaLiteTableModel(); - /** Adds entry for one database table to the model*/ + //! Adds entry for one database table to the model void addTableEntry( const QString& type, const QString& tableName, const QString& geometryColName, const QString& sql ); - /** Sets an sql statement that belongs to a cell specified by a model index*/ + //! Sets an sql statement that belongs to a cell specified by a model index void setSql( const QModelIndex& index, const QString& sql ); /** Sets one or more geometry types to a row. In case of several types, additional rows are inserted. This is for tables where the type is dectected later by thread*/ void setGeometryTypesForTable( const QString & table, const QString & attribute, const QString & type ); - /** Returns the number of tables in the model*/ + //! Returns the number of tables in the model int tableCount() const { return mTableCount; } - /** Sets the SQLite DB full path*/ + //! Sets the SQLite DB full path void setSqliteDb( const QString & dbName ) { mSqliteDb = dbName; } private: - /** Number of tables in the model*/ + //! Number of tables in the model int mTableCount; QString mSqliteDb; QIcon iconForType( QgsWkbTypes::Type type ) const; QString displayStringForType( QgsWkbTypes::Type type ) const; - /** Returns qgis wkbtype from database typename*/ + //! Returns qgis wkbtype from database typename QgsWkbTypes::Type qgisTypeFromDbType( const QString & dbType ) const; }; diff --git a/src/providers/virtual/qgsembeddedlayerselectdialog.h b/src/providers/virtual/qgsembeddedlayerselectdialog.h index b9802a8b0f8b..6187962563a8 100644 --- a/src/providers/virtual/qgsembeddedlayerselectdialog.h +++ b/src/providers/virtual/qgsembeddedlayerselectdialog.h @@ -33,7 +33,7 @@ class QgsEmbeddedLayerSelectDialog : public QDialog, private Ui::QgsEmbeddedLaye public: QgsEmbeddedLayerSelectDialog( QWidget * parent, QgsLayerTreeView* tv ); - /** Returns the list of layer ids selected */ + //! Returns the list of layer ids selected QStringList layers() const; }; diff --git a/src/providers/virtual/qgsvirtuallayerprovider.h b/src/providers/virtual/qgsvirtuallayerprovider.h index cbb23f090cca..a5426f35d9f8 100644 --- a/src/providers/virtual/qgsvirtuallayerprovider.h +++ b/src/providers/virtual/qgsvirtuallayerprovider.h @@ -36,29 +36,29 @@ class QgsVirtualLayerProvider: public QgsVectorDataProvider */ explicit QgsVirtualLayerProvider( QString const &uri = "" ); - /** Destructor */ + //! Destructor virtual ~QgsVirtualLayerProvider(); virtual QgsAbstractFeatureSource* featureSource() const override; - /** Returns the permanent storage type for this layer as a friendly name */ + //! Returns the permanent storage type for this layer as a friendly name virtual QString storageType() const override; virtual QgsCoordinateReferenceSystem crs() const override; virtual QgsFeatureIterator getFeatures( const QgsFeatureRequest& request ) const override; - /** Get the feature geometry type */ + //! Get the feature geometry type QgsWkbTypes::Type wkbType() const override; - /** Get the number of features in the layer */ + //! Get the number of features in the layer long featureCount() const override; virtual QgsRectangle extent() const override; virtual QString subsetString() const override; - /** Set the subset string used to create a subset of features in the layer (WHERE clause) */ + //! Set the subset string used to create a subset of features in the layer (WHERE clause) virtual bool setSubsetString( const QString& subset, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } @@ -67,18 +67,18 @@ class QgsVirtualLayerProvider: public QgsVectorDataProvider bool isValid() const override; - /** Returns a bitmask containing the supported capabilities*/ + //! Returns a bitmask containing the supported capabilities QgsVectorDataProvider::Capabilities capabilities() const override; - /** Return the provider name */ + //! Return the provider name QString name() const override; - /** Return description */ + //! Return description QString description() const override; QgsAttributeList pkAttributeIndexes() const override; - /** Get the list of layer ids on which this layer depends */ + //! Get the list of layer ids on which this layer depends QSet dependencies() const override; private: diff --git a/src/providers/virtual/qgsvirtuallayersourceselect.h b/src/providers/virtual/qgsvirtuallayersourceselect.h index 0032d7b7dad5..38c27a98d590 100644 --- a/src/providers/virtual/qgsvirtuallayersourceselect.h +++ b/src/providers/virtual/qgsvirtuallayersourceselect.h @@ -46,9 +46,9 @@ class QgsVirtualLayerSourceSelect : public QDialog, private Ui::QgsVirtualLayerS void onTableRowChanged( const QModelIndex& current, const QModelIndex& previous ); signals: - /** Source, name, provider */ + //! Source, name, provider void addVectorLayer( QString, QString, QString ); - /** Old_id, source, name, provider */ + //! Old_id, source, name, provider void replaceVectorLayer( QString, QString, QString, QString ); private: diff --git a/src/providers/wcs/qgswcscapabilities.h b/src/providers/wcs/qgswcscapabilities.h index edfce9a9aaa3..4b350fad34f9 100644 --- a/src/providers/wcs/qgswcscapabilities.h +++ b/src/providers/wcs/qgswcscapabilities.h @@ -34,7 +34,7 @@ class QNetworkAccessManager; class QNetworkReply; -/** CoverageSummary structure */ +//! CoverageSummary structure struct QgsWcsCoverageSummary { QgsWcsCoverageSummary() @@ -70,7 +70,7 @@ struct QgsWcsCoverageSummary bool hasSize; }; -/** Capability Property structure */ +//! Capability Property structure struct QgsWcsCapabilitiesProperty { QString version; @@ -138,13 +138,13 @@ class QgsWcsCapabilities : public QObject * \param version optional version, e.g. 1.0.0 or 1.1.0 */ QString getCapabilitiesUrl( const QString& version ) const; - /** \brief Returns the GetCoverage full url using current version */ + //! \brief Returns the GetCoverage full url using current version QString getCapabilitiesUrl() const; - /** \brief Returns the GetCoverage full full url using current version */ + //! \brief Returns the GetCoverage full full url using current version QString getDescribeCoverageUrl( QString const &identifier ) const; - /** Returns the GetCoverage base url */ + //! Returns the GetCoverage base url QString getCoverageUrl() const; //! Send request to server @@ -209,17 +209,17 @@ class QgsWcsCapabilities : public QObject * NS is ignored. Example path: domainSet.spatialDomain.RectifiedGrid */ static QDomElement domElement( const QDomElement &element, const QString &path ); - /** Get text of element specified by path */ + //! Get text of element specified by path static QString domElementText( const QDomElement &element, const QString &path ); - /** Get sub elements texts by path */ + //! Get sub elements texts by path static QStringList domElementsTexts( const QDomElement &element, const QString &path ); signals: - /** \brief emit a signal to notify of a progress event */ + //! \brief emit a signal to notify of a progress event void progressChanged( int theProgress, int theTotalSteps ); - /** \brief emit a signal to be caught by qgisapp and display a msg on status bar */ + //! \brief emit a signal to be caught by qgisapp and display a msg on status bar void statusChanged( QString const & theStatusQString ); void downloadFinished(); @@ -260,7 +260,7 @@ class QgsWcsCapabilities : public QObject */ bool retrieveServerCapabilities( const QString& preferredVersion ); - /** Retrieve the best WCS version supported by server and QGIS */ + //! Retrieve the best WCS version supported by server and QGIS bool retrieveServerCapabilities(); //! \return false if the capabilities document could not be parsed - see lastError() for more info diff --git a/src/providers/wcs/qgswcsprovider.h b/src/providers/wcs/qgswcsprovider.h index 3fb3e5580cce..91ac010a6303 100644 --- a/src/providers/wcs/qgswcsprovider.h +++ b/src/providers/wcs/qgswcsprovider.h @@ -159,7 +159,7 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase void readBlock( int theBandNo, int xBlock, int yBlock, void *block ) override; - /** Download cache */ + //! Download cache void getCache( int bandNo, QgsRectangle const & viewExtent, int width, int height, QString crs = QString(), QgsRasterBlockFeedback* feedback = nullptr ) const; virtual QgsRectangle extent() const override; @@ -207,7 +207,7 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase signals: - /** \brief emit a signal to notify of a progress event */ + //! \brief emit a signal to notify of a progress event void progressChanged( int theProgress, int theTotalSteps ); void dataChanged(); @@ -278,32 +278,32 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase */ bool mValid; - /** Server capabilities */ + //! Server capabilities QgsWcsCapabilities mCapabilities; - /** Coverage summary */ + //! Coverage summary QgsWcsCoverageSummary mCoverageSummary; - /** Spatial reference id of the layer */ + //! Spatial reference id of the layer QString mSrid; - /** Rectangle that contains the extent (bounding box) of the layer */ + //! Rectangle that contains the extent (bounding box) of the layer mutable QgsRectangle mCoverageExtent; - /** Coverage width, may be 0 if it could not be found in DescribeCoverage */ + //! Coverage width, may be 0 if it could not be found in DescribeCoverage int mWidth; - /** Coverage width, may be 0 if it could not be found in DescribeCoverage */ + //! Coverage width, may be 0 if it could not be found in DescribeCoverage int mHeight; - /** Block size */ + //! Block size int mXBlockSize; int mYBlockSize; - /** Flag if size was parsed successfully */ + //! Flag if size was parsed successfully bool mHasSize; - /** Number of bands */ + //! Number of bands int mBandCount; /** \brief Gdal data types used to represent data in in QGIS, @@ -311,13 +311,13 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase indexed from 0 */ QList mGdalDataType; - /** GDAL source data types, indexed from 0 */ + //! GDAL source data types, indexed from 0 QList mSrcGdalDataType; - /** \brief Cell value representing no data. e.g. -9999, indexed from 0 */ + //! \brief Cell value representing no data. e.g. -9999, indexed from 0 //QList mNoDataValue; - /** Color tables indexed from 0 */ + //! Color tables indexed from 0 QList< QList > mColorTables; /** @@ -336,14 +336,14 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase */ QMap mQueryableForLayer; - /** Coverage CRS used for requests in Auth */ + //! Coverage CRS used for requests in Auth // TODO: use QgsCoordinateReferenceSystem ? QString mCoverageCrs; - /** Cached data */ + //! Cached data mutable QByteArray mCachedData; - /** Name of memory file for cached data */ + //! Name of memory file for cached data QString mCachedMemFilename; #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1800 @@ -352,29 +352,29 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase mutable FILE * mCachedMemFile; #endif - /** Pointer to cached GDAL dataset */ + //! Pointer to cached GDAL dataset mutable GDALDatasetH mCachedGdalDataset; - /** Current cache error last getCache() error. */ + //! Current cache error last getCache() error. mutable QgsError mCachedError; - /** The previous parameters to draw(). */ + //! The previous parameters to draw(). mutable QgsRectangle mCachedViewExtent; mutable int mCachedViewWidth; mutable int mCachedViewHeight; - /** Maximum width and height of getmap requests */ + //! Maximum width and height of getmap requests int mMaxWidth; int mMaxHeight; - /** The error caption associated with the last WCS error. */ + //! The error caption associated with the last WCS error. QString mErrorCaption; - /** The error message associated with the last WCS error. */ + //! The error message associated with the last WCS error. QString mError; - /** The mime type of the message */ + //! The mime type of the message QString mErrorFormat; //! A QgsCoordinateTransform is used for transformation of WCS layer extents @@ -416,7 +416,7 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase }; -/** Handler for downloading of coverage data - output is written to mCachedData */ +//! Handler for downloading of coverage data - output is written to mCachedData class QgsWcsDownloadHandler : public QObject { Q_OBJECT diff --git a/src/providers/wfs/qgswfscapabilities.h b/src/providers/wfs/qgswfscapabilities.h index cb056e1fcc1a..9e3a029a72fa 100644 --- a/src/providers/wfs/qgswfscapabilities.h +++ b/src/providers/wfs/qgswfscapabilities.h @@ -21,7 +21,7 @@ #include "qgsrectangle.h" #include "qgswfsrequest.h" -/** Manages the GetCapabilities request */ +//! Manages the GetCapabilities request class QgsWfsCapabilities : public QgsWfsRequest { Q_OBJECT @@ -123,7 +123,7 @@ class QgsWfsCapabilities : public QgsWfsRequest private: Capabilities mCaps; - /** Takes element and updates the capabilities*/ + //! Takes element and updates the capabilities void parseSupportedOperations( const QDomElement& operationsElem, bool& insertCap, bool& updateCap, diff --git a/src/providers/wfs/qgswfsdatasourceuri.h b/src/providers/wfs/qgswfsdatasourceuri.h index cd934eff8dbe..1b805b00514b 100644 --- a/src/providers/wfs/qgswfsdatasourceuri.h +++ b/src/providers/wfs/qgswfsdatasourceuri.h @@ -75,67 +75,67 @@ class QgsWFSDataSourceURI explicit QgsWFSDataSourceURI( const QString& uri ); - /** Return the URI, avoiding expansion of authentication configuration, which is handled during network access */ + //! Return the URI, avoiding expansion of authentication configuration, which is handled during network access const QString uri( bool expandAuthConfig = false ) const; - /** Return base URL (with SERVICE=WFS parameter if bIncludeServiceWFS=true) */ + //! Return base URL (with SERVICE=WFS parameter if bIncludeServiceWFS=true) QUrl baseURL( bool bIncludeServiceWFS = true ) const; - /** Get WFS version. Can be auto, 1.0.0, 1.1.0 or 2.0.0. */ + //! Get WFS version. Can be auto, 1.0.0, 1.1.0 or 2.0.0. QString version() const; - /** Return user defined limit of features to download. 0=no limitation */ + //! Return user defined limit of features to download. 0=no limitation int maxNumFeatures() const; - /** Set user defined limit of features to download */ + //! Set user defined limit of features to download void setMaxNumFeatures( int maxNumFeatures ); - /** Get typename (with prefix) */ + //! Get typename (with prefix) QString typeName() const; - /** Set typename (with prefix)*/ + //! Set typename (with prefix) void setTypeName( const QString& typeName ); - /** Get SRS name (in the normalized form EPSG:xxxx) */ + //! Get SRS name (in the normalized form EPSG:xxxx) QString SRSName() const; - /** Set SRS name (in the normalized form EPSG:xxxx) */ + //! Set SRS name (in the normalized form EPSG:xxxx) void setSRSName( const QString& crsString ); - /** Set version */ + //! Set version void setVersion( const QString& versionString ); - /** Get OGC filter xml or a QGIS expression */ + //! Get OGC filter xml or a QGIS expression QString filter() const; - /** Set OGC filter xml or a QGIS expression */ + //! Set OGC filter xml or a QGIS expression void setFilter( const QString& filterIn ); - /** Get SQL query */ + //! Get SQL query QString sql() const; - /** Set SQL query */ + //! Set SQL query void setSql( const QString& sql ); - /** Returns whether GetFeature request should include the request bounding box. Defaults to false */ + //! Returns whether GetFeature request should include the request bounding box. Defaults to false bool isRestrictedToRequestBBOX() const; - /** Returns whether axis orientation should be ignored (for WFS >= 1.1). Defaults to false */ + //! Returns whether axis orientation should be ignored (for WFS >= 1.1). Defaults to false bool ignoreAxisOrientation() const; - /** Returns whether axis orientation should be inverted. Defaults to false */ + //! Returns whether axis orientation should be inverted. Defaults to false bool invertAxisOrientation() const; - /** For debug purposes. Checks that functions used in sql match functions declared by the server. Defaults to false */ + //! For debug purposes. Checks that functions used in sql match functions declared by the server. Defaults to false bool validateSqlFunctions() const; - /** Whether to hide download progress dialog in QGIS main app. Defaults to false */ + //! Whether to hide download progress dialog in QGIS main app. Defaults to false bool hideDownloadProgressDialog() const; - /** Return authorization parameters */ + //! Return authorization parameters QgsWFSAuthorization& auth() { return mAuth; } - /** Builds a derived uri from a base uri */ + //! Builds a derived uri from a base uri static QString build( const QString& uri, const QString& typeName, const QString& crsString = QString(), diff --git a/src/providers/wfs/qgswfsdescribefeaturetype.h b/src/providers/wfs/qgswfsdescribefeaturetype.h index 2a5a8f6f3c39..16e824891184 100644 --- a/src/providers/wfs/qgswfsdescribefeaturetype.h +++ b/src/providers/wfs/qgswfsdescribefeaturetype.h @@ -17,14 +17,14 @@ #include "qgswfsrequest.h" -/** Manages the DescribeFeatureType request */ +//! Manages the DescribeFeatureType request class QgsWFSDescribeFeatureType : public QgsWfsRequest { Q_OBJECT public: explicit QgsWFSDescribeFeatureType( const QString& theUri ); - /** Issue the request */ + //! Issue the request bool requestFeatureType( const QString& WFSVersion, const QString& typeName ); protected: diff --git a/src/providers/wfs/qgswfsfeatureiterator.h b/src/providers/wfs/qgswfsfeatureiterator.h index a78c63c7c71f..ff88e54dbb75 100644 --- a/src/providers/wfs/qgswfsfeatureiterator.h +++ b/src/providers/wfs/qgswfsfeatureiterator.h @@ -33,7 +33,7 @@ class QProgressDialog; typedef QPair QgsWFSFeatureGmlIdPair; -/** Utility class to issue a GetFeature resultType=hits request */ +//! Utility class to issue a GetFeature resultType=hits request class QgsWFSFeatureHitsAsyncRequest: public QgsWfsRequest { Q_OBJECT @@ -43,7 +43,7 @@ class QgsWFSFeatureHitsAsyncRequest: public QgsWfsRequest void launch( const QUrl& url ); - /** Return result of request, or -1 if not known/error */ + //! Return result of request, or -1 if not known/error int numberMatched() const { return mNumberMatched; } signals: @@ -60,12 +60,12 @@ class QgsWFSFeatureHitsAsyncRequest: public QgsWfsRequest }; -/** Utility class for QgsWFSFeatureDownloader */ +//! Utility class for QgsWFSFeatureDownloader class QgsWFSProgressDialog: public QProgressDialog { Q_OBJECT public: - /** Constructor */ + //! Constructor QgsWFSProgressDialog( const QString & labelText, const QString & cancelButtonText, int minimum, int maximum, QWidget * parent ); void resizeEvent( QResizeEvent * ev ) override; @@ -101,23 +101,23 @@ class QgsWFSFeatureDownloader: public QgsWfsRequest void run( bool serializeFeatures, int maxFeatures ); public slots: - /** To interrupt the download. Thread-safe */ + //! To interrupt the download. Thread-safe void stop(); signals: - /** Emitted when new features have been received */ + //! Emitted when new features have been received void featureReceived( QVector ); - /** Emitted when new features have been received */ + //! Emitted when new features have been received void featureReceived( int featureCount ); - /** Emitted when the download is finished (successful or not) */ + //! Emitted when the download is finished (successful or not) void endOfDownload( bool success ); - /** Used internally by the stop() method */ + //! Used internally by the stop() method void doStop(); - /** Emitted with the total accumulated number of features downloaded. */ + //! Emitted with the total accumulated number of features downloaded. void updateProgress( int totalFeatureCount ); protected: @@ -135,11 +135,11 @@ class QgsWFSFeatureDownloader: public QgsWfsRequest void pushError( const QString& errorMsg ); QString sanitizeFilter( QString filter ); - /** Mutable data shared between provider, feature sources and downloader. */ + //! Mutable data shared between provider, feature sources and downloader. QgsWFSSharedData* mShared; - /** Whether the download should stop */ + //! Whether the download should stop bool mStop; - /** Progress dialog */ + //! Progress dialog QProgressDialog* mProgressDialog; /** If the progress dialog should be shown immediately, or if it should be let to QProgressDialog logic to decide when to show it */ @@ -153,7 +153,7 @@ class QgsWFSFeatureDownloader: public QgsWfsRequest int mTotalDownloadedFeatureCount; }; -/** Downloader thread */ +//! Downloader thread class QgsWFSThreadedFeatureDownloader: public QThread { Q_OBJECT @@ -161,18 +161,18 @@ class QgsWFSThreadedFeatureDownloader: public QThread explicit QgsWFSThreadedFeatureDownloader( QgsWFSSharedData* shared ); ~QgsWFSThreadedFeatureDownloader(); - /** Return downloader object */ + //! Return downloader object QgsWFSFeatureDownloader* downloader() { return mDownloader; } - /** Stops (synchronously) the download */ + //! Stops (synchronously) the download void stop(); signals: - /** Emitted when the thread is ready */ + //! Emitted when the thread is ready void ready(); protected: - /** Inherited from QThread. Starts the download */ + //! Inherited from QThread. Starts the download void run() override; private: @@ -200,7 +200,7 @@ class QgsWFSFeatureIterator : public QObject, void setInterruptionChecker( QgsInterruptionChecker* interruptionChecker ) override; - /** Used by QgsWFSSharedData::registerToCache() */ + //! Used by QgsWFSSharedData::registerToCache() void connectSignals( QObject* downloader ); private slots: @@ -213,12 +213,12 @@ class QgsWFSFeatureIterator : public QObject, bool fetchFeature( QgsFeature& f ) override; - /** Copies feature attributes / geometry from srcFeature to dstFeature*/ + //! Copies feature attributes / geometry from srcFeature to dstFeature void copyFeature( const QgsFeature& srcFeature, QgsFeature& dstFeature ); QSharedPointer mShared; //!< Mutable data shared between provider and feature sources - /** Subset of attributes (relatives to mShared->mFields) to fetch. Only valid if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) */ + //! Subset of attributes (relatives to mShared->mFields) to fetch. Only valid if ( mRequest.flags() & QgsFeatureRequest::SubsetOfAttributes ) QgsAttributeList mSubSetAttributes; bool mDownloadFinished; @@ -244,14 +244,14 @@ class QgsWFSFeatureIterator : public QObject, bool mFetchGeometry; }; -/** Feature source */ +//! Feature source class QgsWFSFeatureSource : public QgsAbstractFeatureSource { public: explicit QgsWFSFeatureSource( const QgsWFSProvider* p ); ~QgsWFSFeatureSource(); - /** Returns features matching the request */ + //! Returns features matching the request QgsFeatureIterator getFeatures( const QgsFeatureRequest& request ) override; protected: diff --git a/src/providers/wfs/qgswfsprovider.h b/src/providers/wfs/qgswfsprovider.h index cbe7d088f872..bc9d3c9d0a40 100644 --- a/src/providers/wfs/qgswfsprovider.h +++ b/src/providers/wfs/qgswfsprovider.h @@ -80,7 +80,7 @@ class QgsWFSProvider : public QgsVectorDataProvider virtual QString subsetString() const override; - /** Mutator for sql where clause used to limit dataset size */ + //! Mutator for sql where clause used to limit dataset size virtual bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } @@ -144,7 +144,7 @@ class QgsWFSProvider : public QgsVectorDataProvider void pushErrorSlot( const QString& errorMsg ); private: - /** Mutable data shared between provider and feature sources */ + //! Mutable data shared between provider and feature sources QSharedPointer mShared; friend class QgsWFSFeatureSource; @@ -154,15 +154,15 @@ class QgsWFSProvider : public QgsVectorDataProvider //! String used to define a subset of the layer QString mSubsetString; - /** Geometry type of the features in this layer*/ + //! Geometry type of the features in this layer mutable QgsWkbTypes::Type mWKBType; - /** Flag if provider is valid*/ + //! Flag if provider is valid bool mValid; - /** Namespace URL of the server (comes from DescribeFeatureDocument)*/ + //! Namespace URL of the server (comes from DescribeFeatureDocument) QString mApplicationNamespace; - /** Server capabilities for this layer (generated from capabilities document)*/ + //! Server capabilities for this layer (generated from capabilities document) QgsVectorDataProvider::Capabilities mCapabilities; - /** Fields of this typename. Might be different from mShared->mFields in case of SELECT */ + //! Fields of this typename. Might be different from mShared->mFields in case of SELECT QgsFields mThisTypenameFields; QString mProcessSQLErrorMsg; @@ -188,20 +188,20 @@ class QgsWFSProvider : public QgsVectorDataProvider note: true does not automatically mean that the transaction succeeded*/ bool sendTransactionDocument( const QDomDocument& doc, QDomDocument& serverResponse ); - /** Creates a transaction element and adds it (normally as first element) to the document*/ + //! Creates a transaction element and adds it (normally as first element) to the document QDomElement createTransactionElement( QDomDocument& doc ) const; - /** True if the server response means success*/ + //! True if the server response means success bool transactionSuccess( const QDomDocument& serverResponse ) const; - /** Returns the inserted ids*/ + //! Returns the inserted ids QStringList insertedFeatureIds( const QDomDocument& serverResponse ) const; - /** Retrieve version and capabilities for this layer from GetCapabilities document (will be stored in mCapabilites)*/ + //! Retrieve version and capabilities for this layer from GetCapabilities document (will be stored in mCapabilites) bool getCapabilities(); - /** Records provider error*/ + //! Records provider error void handleException( const QDomDocument& serverResponse ); - /** Converts DescribeFeatureType schema geometry property type to WKBType*/ + //! Converts DescribeFeatureType schema geometry property type to WKBType QgsWkbTypes::Type geomTypeFromPropertyType( const QString& attName, const QString& propType ); - /** Convert the value to its appropriate XML representation */ + //! Convert the value to its appropriate XML representation QString convertToXML( const QVariant& value ); bool processSQL( const QString& sqlString, QString& errorMsg, QString& warningMsg ); diff --git a/src/providers/wfs/qgswfsrequest.h b/src/providers/wfs/qgswfsrequest.h index 38706909cf8a..6dfe312fcd5e 100644 --- a/src/providers/wfs/qgswfsrequest.h +++ b/src/providers/wfs/qgswfsrequest.h @@ -22,7 +22,7 @@ #include "qgswfsdatasourceuri.h" -/** Abstract base class for a WFS request. */ +//! Abstract base class for a WFS request. class QgsWfsRequest : public QObject { Q_OBJECT @@ -31,10 +31,10 @@ class QgsWfsRequest : public QObject virtual ~QgsWfsRequest(); - /** \brief proceed to sending a GET request */ + //! \brief proceed to sending a GET request bool sendGET( const QUrl& url, bool synchronous, bool forceRefresh = false, bool cache = true ); - /** \brief proceed to sending a synchronous POST request */ + //! \brief proceed to sending a synchronous POST request bool sendPOST( const QUrl& url, const QString& contentTypeHeader, const QByteArray& data ); enum ErrorCode { NoError, @@ -45,24 +45,24 @@ class QgsWfsRequest : public QObject WFSVersionNotSupported }; - /** \brief Return error code (after download/post) */ + //! \brief Return error code (after download/post) ErrorCode errorCode() const { return mErrorCode; } - /** \brief Return error message (after download/post) */ + //! \brief Return error message (after download/post) const QString& errorMessage() const { return mErrorMessage; } - /** \brief Return server response (after download/post) */ + //! \brief Return server response (after download/post) const QByteArray& response() const { return mResponse; } public slots: - /** Abort network request immediately */ + //! Abort network request immediately void abort(); signals: - /** \brief emit a signal when data arrives */ + //! \brief emit a signal when data arrives void downloadProgress( qint64, qint64 ); - /** \brief emit a signal once the download is finished */ + //! \brief emit a signal once the download is finished void downloadFinished(); protected slots: @@ -71,31 +71,31 @@ class QgsWfsRequest : public QObject void requestTimedOut( QNetworkReply* reply ); protected: - /** URI */ + //! URI QgsWFSDataSourceURI mUri; - /** The reply to the request */ + //! The reply to the request QNetworkReply *mReply; - /** The error message associated with the last error. */ + //! The error message associated with the last error. QString mErrorMessage; - /** Error code */ + //! Error code ErrorCode mErrorCode; - /** Raw response */ + //! Raw response QByteArray mResponse; - /** Whether the request is aborted. */ + //! Whether the request is aborted. bool mIsAborted; - /** Whether to force refresh (i.e. issue a network request and not use cache) */ + //! Whether to force refresh (i.e. issue a network request and not use cache) bool mForceRefresh; - /** Whether the request has timed-out */ + //! Whether the request has timed-out bool mTimedout; - /** Whether we already received bytes */ + //! Whether we already received bytes bool mGotNonEmptyResponse; protected: @@ -107,7 +107,7 @@ class QgsWfsRequest : public QObject (possibly translated, but sometimes coming from server) reason */ virtual QString errorMessageWithReason( const QString& reason ) = 0; - /** Return experiation delay in second */ + //! Return experiation delay in second virtual int defaultExpirationInSec() { return 0; } private: diff --git a/src/providers/wfs/qgswfsshareddata.cpp b/src/providers/wfs/qgswfsshareddata.cpp index 45200f1ea012..68dcba09aee4 100644 --- a/src/providers/wfs/qgswfsshareddata.cpp +++ b/src/providers/wfs/qgswfsshareddata.cpp @@ -975,7 +975,7 @@ void QgsWFSSharedData::pushError( const QString& errorMsg ) emit raiseError( errorMsg ); } -/** Called by QgsWFSFeatureDownloader::run() at the end of the download process. */ +//! Called by QgsWFSFeatureDownloader::run() at the end of the download process. void QgsWFSSharedData::endOfDownload( bool success, int featureCount, bool truncatedResponse, bool interrupted, diff --git a/src/providers/wfs/qgswfsshareddata.h b/src/providers/wfs/qgswfsshareddata.h index aecc4698b7d9..e49558817ae5 100644 --- a/src/providers/wfs/qgswfsshareddata.h +++ b/src/providers/wfs/qgswfsshareddata.h @@ -63,55 +63,55 @@ class QgsWFSSharedData : public QObject the cache. Also used by a WFS-T insert operation */ void serializeFeatures( QVector& featureList ); - /** Called by QgsWFSFeatureDownloader::run() at the end of the download process. */ + //! Called by QgsWFSFeatureDownloader::run() at the end of the download process. void endOfDownload( bool success, int featureCount, bool truncatedResponse, bool interrupted, const QString &errorMsg ); /** Used by QgsWFSProvider::reloadData(). The effect is to invalid all the caching state, so that a new request results in fresh download */ void invalidateCache(); - /** Give a feature id, find the correspond fid/gml.id. Used by WFS-T */ + //! Give a feature id, find the correspond fid/gml.id. Used by WFS-T QString findGmlId( QgsFeatureId fid ); - /** Delete from the on-disk cache the features of given fid. Used by WFS-T */ + //! Delete from the on-disk cache the features of given fid. Used by WFS-T bool deleteFeatures( const QgsFeatureIds& fidlist ); - /** Change into the on-disk cache the passed geometries. Used by WFS-T */ + //! Change into the on-disk cache the passed geometries. Used by WFS-T bool changeGeometryValues( const QgsGeometryMap &geometry_map ); - /** Change into the on-disk cache the passed attributes. Used by WFS-T */ + //! Change into the on-disk cache the passed attributes. Used by WFS-T bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ); - /** Force an update of the feature count */ + //! Force an update of the feature count void setFeatureCount( int featureCount ); - /** Return layer feature count. Might issue a GetFeature resultType=hits request */ + //! Return layer feature count. Might issue a GetFeature resultType=hits request int getFeatureCount( bool issueRequestIfNeeded = true ); - /** Return whether the feature count is exact, or approximate/transient */ + //! Return whether the feature count is exact, or approximate/transient bool isFeatureCountExact() const { return mFeatureCountExact; } - /** Return whether the server support RESULTTYPE=hits */ + //! Return whether the server support RESULTTYPE=hits bool supportsHits() const { return mCaps.supportsHits; } - /** Compute WFS filter from the sql or filter in the URI */ + //! Compute WFS filter from the sql or filter in the URI bool computeFilter( QString& errorMsg ); - /** Return extent computed from currently downloaded features */ + //! Return extent computed from currently downloaded features QgsRectangle computedExtent(); - /** Return srsName */ + //! Return srsName QString srsName() const; - /** Return whether the feature download is finished */ + //! Return whether the feature download is finished bool downloadFinished() const { return mDownloadFinished; } signals: - /** Raise error */ + //! Raise error void raiseError( const QString& errorMsg ); - /** Extent has been updated */ + //! Extent has been updated void extentUpdated(); protected: @@ -120,55 +120,55 @@ class QgsWFSSharedData : public QObject friend class QgsWFSProvider; friend class QgsWFSSingleFeatureRequest; - /** Datasource URI */ + //! Datasource URI QgsWFSDataSourceURI mURI; - /** WFS version to use. Comes from GetCapabilities response */ + //! WFS version to use. Comes from GetCapabilities response QString mWFSVersion; - /** Source CRS*/ + //! Source CRS QgsCoordinateReferenceSystem mSourceCRS; - /** Attribute fields of the layer */ + //! Attribute fields of the layer QgsFields mFields; - /** Name of geometry attribute */ + //! Name of geometry attribute QString mGeometryAttribute; - /** Layer properties */ + //! Layer properties QList< QgsOgcUtils::LayerProperties > mLayerPropertiesList; - /** Map a field name to the pair (typename, fieldname) that describes its source field */ + //! Map a field name to the pair (typename, fieldname) that describes its source field QMap< QString, QPair > mMapFieldNameToSrcLayerNameFieldName; - /** The data provider of the on-disk cache */ + //! The data provider of the on-disk cache QgsVectorDataProvider* mCacheDataProvider; - /** Current BBOX used by the downloader */ + //! Current BBOX used by the downloader QgsRectangle mRect; - /** Server-side or user-side limit of downloaded features (in a single GetFeature()). Valid if > 0 */ + //! Server-side or user-side limit of downloaded features (in a single GetFeature()). Valid if > 0 int mMaxFeatures; - /** Whether mMaxFeatures was set to a non 0 value for the purpose of paging */ + //! Whether mMaxFeatures was set to a non 0 value for the purpose of paging bool mMaxFeaturesWasSetFromDefaultForPaging; - /** Server capabilities */ + //! Server capabilities QgsWfsCapabilities::Capabilities mCaps; - /** Whether progress dialog should be hidden */ + //! Whether progress dialog should be hidden bool mHideProgressDialog; - /** SELECT DISTINCT */ + //! SELECT DISTINCT bool mDistinctSelect; - /** Bounding box for the layer as returned by GetCapabilities */ + //! Bounding box for the layer as returned by GetCapabilities QgsRectangle mCapabilityExtent; - /** If we have already issued a warning about missing feature ids */ + //! If we have already issued a warning about missing feature ids bool mHasWarnedAboutMissingFeatureId; - /** Create GML parser */ + //! Create GML parser QgsGmlStreamingParser* createParser(); /** If the server (typically MapServer WFS 1.1) honours EPSG axis order, but returns @@ -177,25 +177,25 @@ class QgsWFSSharedData : public QObject private: - /** Main mutex to protect most data members that can be modified concurrently */ + //! Main mutex to protect most data members that can be modified concurrently QMutex mMutex; - /** Mutex used specifically by registerToCache() */ + //! Mutex used specifically by registerToCache() QMutex mMutexRegisterToCache; - /** Mutex used only by serializeFeatures() */ + //! Mutex used only by serializeFeatures() QMutex mCacheWriteMutex; - /** WFS filter */ + //! WFS filter QString mWFSFilter; - /** WFS SORTBY */ + //! WFS SORTBY QString mSortBy; - /** The background feature downloader */ + //! The background feature downloader QgsWFSThreadedFeatureDownloader* mDownloader; - /** Whether the downloader has finished (or been cancelled) */ + //! Whether the downloader has finished (or been cancelled) bool mDownloadFinished; /** The generation counter. When a iterator is built or rewind, it gets the @@ -205,34 +205,34 @@ class QgsWFSSharedData : public QObject notified in live by the downloader. */ int mGenCounter; - /** Number of features of the layer */ + //! Number of features of the layer int mFeatureCount; - /** Whether mFeatureCount value is exact or approximate / in construction */ + //! Whether mFeatureCount value is exact or approximate / in construction bool mFeatureCountExact; - /** Extent computed from downloaded features */ + //! Extent computed from downloaded features QgsRectangle mComputedExtent; - /** Filename of the on-disk cache */ + //! Filename of the on-disk cache QString mCacheDbname; - /** Tablename of the on-disk cache */ + //! Tablename of the on-disk cache QString mCacheTablename; - /** Spatial index of requested cached regions */ + //! Spatial index of requested cached regions QgsSpatialIndex mCachedRegions; - /** Requested cached regions */ + //! Requested cached regions QVector< QgsFeature > mRegions; - /** Whether a GetFeature hits request has been issued to retrieve the number of features */ + //! Whether a GetFeature hits request has been issued to retrieve the number of features bool mGetFeatureHitsIssued; - /** Number of features that have been cached, or attempted to be cached */ + //! Number of features that have been cached, or attempted to be cached int mTotalFeaturesAttemptedToBeCached; - /** Whether we have already tried fetching one feature after realizing that the capabilities extent is wrong */ + //! Whether we have already tried fetching one feature after realizing that the capabilities extent is wrong bool mTryFetchingOneFeature; /** Returns the set of gmlIds that have already been downloaded and @@ -243,14 +243,14 @@ class QgsWFSSharedData : public QObject cached, so as to avoid to cache duplicates. */ QSet getExistingCachedMD5( const QVector& featureList ); - /** Create the on-disk cache and connect to it */ + //! Create the on-disk cache and connect to it bool createCache(); - /** Log error to QgsMessageLog and raise it to the provider */ + //! Log error to QgsMessageLog and raise it to the provider void pushError( const QString& errorMsg ); }; -/** Utility class to issue a GetFeature resultType=hits request */ +//! Utility class to issue a GetFeature resultType=hits request class QgsWFSFeatureHitsRequest: public QgsWfsRequest { Q_OBJECT @@ -258,7 +258,7 @@ class QgsWFSFeatureHitsRequest: public QgsWfsRequest explicit QgsWFSFeatureHitsRequest( QgsWFSDataSourceURI& uri ); ~QgsWFSFeatureHitsRequest(); - /** Return the feature count, or -1 in case of error */ + //! Return the feature count, or -1 in case of error int getFeatureCount( const QString& WFSVersion, const QString& filter ); protected: @@ -274,7 +274,7 @@ class QgsWFSSingleFeatureRequest: public QgsWfsRequest explicit QgsWFSSingleFeatureRequest( QgsWFSSharedData* shared ); ~QgsWFSSingleFeatureRequest(); - /** Return the feature extent of the single feature requested */ + //! Return the feature extent of the single feature requested QgsRectangle getExtent(); protected: diff --git a/src/providers/wfs/qgswfstransactionrequest.h b/src/providers/wfs/qgswfstransactionrequest.h index c4d847ea88b8..b2c23859e209 100644 --- a/src/providers/wfs/qgswfstransactionrequest.h +++ b/src/providers/wfs/qgswfstransactionrequest.h @@ -17,14 +17,14 @@ #include "qgswfsrequest.h" -/** Manages the Transaction requests */ +//! Manages the Transaction requests class QgsWFSTransactionRequest : public QgsWfsRequest { Q_OBJECT public: explicit QgsWFSTransactionRequest( const QString& theUri ); - /** Send the transaction document and return the server response */ + //! Send the transaction document and return the server response bool send( const QDomDocument& doc, QDomDocument& serverResponse ); protected: diff --git a/src/providers/wfs/qgswfsutils.h b/src/providers/wfs/qgswfsutils.h index 23a313788a73..fad73be0e440 100644 --- a/src/providers/wfs/qgswfsutils.h +++ b/src/providers/wfs/qgswfsutils.h @@ -27,21 +27,21 @@ class QgsWFSUtils { public: - /** Return the name of temporary directory. */ + //! Return the name of temporary directory. static QString acquireCacheDirectory(); - /** To be called when a temporary file is removed from the directory */ + //! To be called when a temporary file is removed from the directory static void releaseCacheDirectory(); - /** Initial cleanup. */ + //! Initial cleanup. static void init(); - /** Removes a possible namespace prefix from a typename*/ + //! Removes a possible namespace prefix from a typename static QString removeNamespacePrefix( const QString& tname ); - /** Returns namespace prefix (or an empty string if there is no prefix)*/ + //! Returns namespace prefix (or an empty string if there is no prefix) static QString nameSpacePrefix( const QString& tname ); - /** Return a unique identifier made from feature content */ + //! Return a unique identifier made from feature content static QString getMD5( const QgsFeature& f ); protected: @@ -54,16 +54,16 @@ class QgsWFSUtils static bool gmKeepAliveWorks; static int gmCounter; - /** Return the name of temporary directory. */ + //! Return the name of temporary directory. static QString getCacheDirectory( bool createIfNotExisting ); static QString getBaseCacheDirectory( bool createIfNotExisting ); - /** Remove (recursively) a directory. */ + //! Remove (recursively) a directory. static bool removeDir( const QString &dirName ); }; -/** For internal use of QgsWFSUtils */ +//! For internal use of QgsWFSUtils class QgsWFSUtilsKeepAlive: public QThread { Q_OBJECT diff --git a/src/providers/wms/qgswmscapabilities.h b/src/providers/wms/qgswmscapabilities.h index 00d6d36539a6..5194ff3aa184 100644 --- a/src/providers/wms/qgswmscapabilities.h +++ b/src/providers/wms/qgswmscapabilities.h @@ -32,28 +32,28 @@ class QNetworkReply; * as illustrated in Appendix E of the Web Map Service standard, version 1.3, 2004-08-02. */ -/** OnlineResource Attribute structure */ +//! OnlineResource Attribute structure // TODO: Fill to WMS specifications struct QgsWmsOnlineResourceAttribute { QString xlinkHref; }; -/** Get Property structure */ +//! Get Property structure // TODO: Fill to WMS specifications struct QgsWmsGetProperty { QgsWmsOnlineResourceAttribute onlineResource; }; -/** Post Property structure */ +//! Post Property structure // TODO: Fill to WMS specifications struct QgsWmsPostProperty { QgsWmsOnlineResourceAttribute onlineResource; }; -/** HTTP Property structure */ +//! HTTP Property structure // TODO: Fill to WMS specifications struct QgsWmsHttpProperty { @@ -61,14 +61,14 @@ struct QgsWmsHttpProperty QgsWmsPostProperty post; // can be null }; -/** DCP Type Property structure */ +//! DCP Type Property structure // TODO: Fill to WMS specifications struct QgsWmsDcpTypeProperty { QgsWmsHttpProperty http; }; -/** Operation Type structure (for GetMap and GetFeatureInfo) */ +//! Operation Type structure (for GetMap and GetFeatureInfo) // TODO: Fill to WMS specifications struct QgsWmsOperationType { @@ -77,7 +77,7 @@ struct QgsWmsOperationType QStringList allowedEncodings; }; -/** Request Property structure */ +//! Request Property structure // TODO: Fill to WMS specifications struct QgsWmsRequestProperty { @@ -90,21 +90,21 @@ struct QgsWmsRequestProperty QgsWmsOperationType getLegendGraphic; }; -/** Exception Property structure */ +//! Exception Property structure // TODO: Fill to WMS specifications struct QgsWmsExceptionProperty { QStringList format; // text formats supported. }; -/** Primary Contact Person Property structure */ +//! Primary Contact Person Property structure struct QgsWmsContactPersonPrimaryProperty { QString contactPerson; QString contactOrganization; }; -/** Contact Address Property structure */ +//! Contact Address Property structure struct QgsWmsContactAddressProperty { QString addressType; @@ -115,7 +115,7 @@ struct QgsWmsContactAddressProperty QString country; }; -/** Contact Information Property structure */ +//! Contact Information Property structure struct QgsWmsContactInformationProperty { QgsWmsContactPersonPrimaryProperty contactPersonPrimary; @@ -126,7 +126,7 @@ struct QgsWmsContactInformationProperty QString contactElectronicMailAddress; }; -/** Service Property structure */ +//! Service Property structure // TODO: Fill to WMS specifications struct QgsWmsServiceProperty { @@ -142,7 +142,7 @@ struct QgsWmsServiceProperty uint maxHeight; }; -/** Bounding Box Property structure */ +//! Bounding Box Property structure // TODO: Fill to WMS specifications struct QgsWmsBoundingBoxProperty { @@ -150,7 +150,7 @@ struct QgsWmsBoundingBoxProperty QgsRectangle box; // consumes minx, miny, maxx, maxy. }; -/** Dimension Property structure */ +//! Dimension Property structure // TODO: Fill to WMS specifications struct QgsWmsDimensionProperty { @@ -163,7 +163,7 @@ struct QgsWmsDimensionProperty bool current; }; -/** Logo URL Property structure */ +//! Logo URL Property structure // TODO: Fill to WMS specifications struct QgsWmsLogoUrlProperty { @@ -174,7 +174,7 @@ struct QgsWmsLogoUrlProperty int height; }; -/** Attribution Property structure */ +//! Attribution Property structure // TODO: Fill to WMS specifications struct QgsWmsAttributionProperty { @@ -183,7 +183,7 @@ struct QgsWmsAttributionProperty QgsWmsLogoUrlProperty logoUrl; }; -/** Legend URL Property structure */ +//! Legend URL Property structure // TODO: Fill to WMS specifications struct QgsWmsLegendUrlProperty { @@ -194,7 +194,7 @@ struct QgsWmsLegendUrlProperty int height; }; -/** StyleSheet URL Property structure */ +//! StyleSheet URL Property structure // TODO: Fill to WMS specifications struct QgsWmsStyleSheetUrlProperty { @@ -202,7 +202,7 @@ struct QgsWmsStyleSheetUrlProperty QgsWmsOnlineResourceAttribute onlineResource; }; -/** Style URL Property structure */ +//! Style URL Property structure // TODO: Fill to WMS specifications struct QgsWmsStyleUrlProperty { @@ -210,7 +210,7 @@ struct QgsWmsStyleUrlProperty QgsWmsOnlineResourceAttribute onlineResource; }; -/** Style Property structure */ +//! Style Property structure // TODO: Fill to WMS specifications struct QgsWmsStyleProperty { @@ -222,7 +222,7 @@ struct QgsWmsStyleProperty QgsWmsStyleUrlProperty styleUrl; }; -/** Authority URL Property structure */ +//! Authority URL Property structure // TODO: Fill to WMS specifications struct QgsWmsAuthorityUrlProperty { @@ -230,14 +230,14 @@ struct QgsWmsAuthorityUrlProperty QString name; // XML "NMTOKEN" type }; -/** Identifier Property structure */ +//! Identifier Property structure // TODO: Fill to WMS specifications struct QgsWmsIdentifierProperty { QString authority; }; -/** Metadata URL Property structure */ +//! Metadata URL Property structure // TODO: Fill to WMS specifications struct QgsWmsMetadataUrlProperty { @@ -246,7 +246,7 @@ struct QgsWmsMetadataUrlProperty QString type; // XML "NMTOKEN" type }; -/** Data List URL Property structure */ +//! Data List URL Property structure // TODO: Fill to WMS specifications struct QgsWmsDataListUrlProperty { @@ -254,7 +254,7 @@ struct QgsWmsDataListUrlProperty QgsWmsOnlineResourceAttribute onlineResource; }; -/** Feature List URL Property structure */ +//! Feature List URL Property structure // TODO: Fill to WMS specifications struct QgsWmsFeatureListUrlProperty { @@ -262,7 +262,7 @@ struct QgsWmsFeatureListUrlProperty QgsWmsOnlineResourceAttribute onlineResource; }; -/** Layer Property structure */ +//! Layer Property structure // TODO: Fill to WMS specifications struct QgsWmsLayerProperty { @@ -316,12 +316,12 @@ struct QgsWmtsTileMatrix QString title, abstract; QStringList keywords; double scaleDenom; - QgsPoint topLeft; //!< top-left corner of the tile matrix in map units - int tileWidth; //!< width of a tile in pixels - int tileHeight; //!< height of a tile in pixels - int matrixWidth; //!< number of tiles horizontally - int matrixHeight; //!< number of tiles vertically - double tres; //!< pixel span in map units + QgsPoint topLeft; //!< Top-left corner of the tile matrix in map units + int tileWidth; //!< Width of a tile in pixels + int tileHeight; //!< Height of a tile in pixels + int matrixWidth; //!< Number of tiles horizontally + int matrixHeight; //!< Number of tiles vertically + double tres; //!< Pixel span in map units //! Returns extent of a tile in map coordinates. //! (same function as tileBBox() but returns QRectF instead of QgsRectangle) @@ -339,12 +339,12 @@ struct QgsWmtsTileMatrix struct QgsWmtsTileMatrixSet { - QString identifier; //!< tile matrix set identifier - QString title; //!< human readable tile matrix set name - QString abstract; //!< brief description of the tile matrix set - QStringList keywords; //!< list of words/phrases to describe the dataset + QString identifier; //!< Tile matrix set identifier + QString title; //!< Human readable tile matrix set name + QString abstract; //!< Brief description of the tile matrix set + QStringList keywords; //!< List of words/phrases to describe the dataset QString crs; //!< CRS of the tile matrix set - QString wkScaleSet; //!< optional reference to a well-known scale set + QString wkScaleSet; //!< Optional reference to a well-known scale set //! available tile matrixes (key = pixel span in map units) QMap tileMatrices; @@ -394,15 +394,15 @@ struct QgsWmtsStyle */ struct QgsWmtsDimension { - QString identifier; //!< name of the dimensional axis - QString title; //!< human readable name - QString abstract; //!< brief description of the dimension - QStringList keywords; //!< list of words/phrases to describe the dataset - QString UOM; //!< units of measure of dimensional axis - QString unitSymbol; //!< symbol of the units - QString defaultValue; //!< default value to be used if value is not specified in request - bool current; //!< indicates whether temporal data are normally kept current - QStringList values; //!< available values for this dimension + QString identifier; //!< Name of the dimensional axis + QString title; //!< Human readable name + QString abstract; //!< Brief description of the dimension + QStringList keywords; //!< List of words/phrases to describe the dataset + QString UOM; //!< Units of measure of dimensional axis + QString unitSymbol; //!< Symbol of the units + QString defaultValue; //!< Default value to be used if value is not specified in request + bool current; //!< Indicates whether temporal data are normally kept current + QStringList values; //!< Available values for this dimension }; struct QgsWmtsTileLayer @@ -424,7 +424,7 @@ struct QgsWmtsTileLayer QHash getFeatureInfoURLs; }; -/** Capability Property structure */ +//! Capability Property structure // TODO: Fill to WMS specifications struct QgsWmsCapabilityProperty { @@ -441,7 +441,7 @@ struct QgsWmsCapabilityProperty QHash tileMatrixSets; }; -/** Capabilities Property structure */ +//! Capabilities Property structure // TODO: Fill to WMS specifications struct QgsWmsCapabilitiesProperty { @@ -450,7 +450,7 @@ struct QgsWmsCapabilitiesProperty QString version; }; -/** Formats supported by QImageReader */ +//! Formats supported by QImageReader struct QgsWmsSupportedFormat { QString format; @@ -536,7 +536,7 @@ struct QgsWmsAuthorization }; -/** URI that gets passed to provider */ +//! URI that gets passed to provider class QgsWmsSettings { public: @@ -607,7 +607,7 @@ class QgsWmsSettings }; -/** Keeps information about capabilities of particular URI */ +//! Keeps information about capabilities of particular URI class QgsWmsCapabilities { public: @@ -651,10 +651,10 @@ class QgsWmsCapabilities */ QHash supportedTileMatrixSets() const { return mTileMatrixSets; } - /** Find out whether to invert axis orientation when parsing/writing coordinates */ + //! Find out whether to invert axis orientation when parsing/writing coordinates bool shouldInvertAxisOrientation( const QString& ogcCrs ); - /** Find out identify capabilities */ + //! Find out identify capabilities int identifyCapabilities() const; protected: @@ -774,10 +774,10 @@ class QgsWmsCapabilitiesDownload : public QObject void abort(); signals: - /** \brief emit a signal to be caught by qgisapp and display a msg on status bar */ + //! \brief emit a signal to be caught by qgisapp and display a msg on status bar void statusChanged( QString const & theStatusQString ); - /** \brief emit a signal once the download is finished */ + //! \brief emit a signal once the download is finished void downloadFinished(); protected slots: @@ -790,16 +790,16 @@ class QgsWmsCapabilitiesDownload : public QObject QgsWmsAuthorization mAuth; - /** The reply to the capabilities request */ + //! The reply to the capabilities request QNetworkReply *mCapabilitiesReply; - /** The error message associated with the last WMS error. */ + //! The error message associated with the last WMS error. QString mError; - /** The mime type of the message */ + //! The mime type of the message QString mErrorFormat; - /** Capabilities of the WMS (raw) */ + //! Capabilities of the WMS (raw) QByteArray mHttpCapabilitiesResponse; bool mIsAborted; diff --git a/src/providers/wms/qgswmsprovider.h b/src/providers/wms/qgswmsprovider.h index cb0c5d036c00..877d6c34ea7b 100644 --- a/src/providers/wms/qgswmsprovider.h +++ b/src/providers/wms/qgswmsprovider.h @@ -176,13 +176,13 @@ class QgsWmsProvider : public QgsRasterDataProvider virtual bool hasTiles() const; #endif - /** Returns the GetMap url */ + //! Returns the GetMap url virtual QString getMapUrl() const; - /** Returns the GetFeatureInfo url */ + //! Returns the GetFeatureInfo url virtual QString getFeatureInfoUrl() const; - /** Return the GetTile url */ + //! Return the GetTile url virtual QString getTileUrl() const; /** Return the GetLegendGraphic url @@ -212,7 +212,7 @@ class QgsWmsProvider : public QgsRasterDataProvider */ QStringList subLayerStyles() const override; - /** \brief Returns whether the provider supplies a legend graphic */ + //! \brief Returns whether the provider supplies a legend graphic bool supportsLegendGraphic() const override { return true; } @@ -374,7 +374,7 @@ class QgsWmsProvider : public QgsRasterDataProvider signals: - /** \brief emit a signal to notify of a progress event */ + //! \brief emit a signal to notify of a progress event void progressChanged( int theProgress, int theTotalSteps ); void dataChanged(); @@ -460,8 +460,8 @@ class QgsWmsProvider : public QgsRasterDataProvider typedef struct TileImage { TileImage( const QRectF& r, const QImage& i ): rect( r ), img( i ) {} - QRectF rect; //!< destination rectangle for a tile (in screen coordinates) - QImage img; //!< cached tile to be drawn + QRectF rect; //!< Destination rectangle for a tile (in screen coordinates) + QImage img; //!< Cached tile to be drawn } TileImage; //! Get tiles from a different resolution to cover the missing areas void fetchOtherResTiles( QgsTileMode tileMode, const QgsRectangle& viewExtent, int imageWidth, QList& missing, double tres, int resOffset, QList &otherResTiles ); @@ -586,7 +586,7 @@ class QgsWmsProvider : public QgsRasterDataProvider }; -/** Handler for downloading of non-tiled WMS requests, the data are written to the given image */ +//! Handler for downloading of non-tiled WMS requests, the data are written to the given image class QgsWmsImageDownloadHandler : public QObject { Q_OBJECT @@ -615,7 +615,7 @@ class QgsWmsImageDownloadHandler : public QObject }; -/** Handler for tiled WMS-C/WMTS requests, the data are written to the given image */ +//! Handler for tiled WMS-C/WMTS requests, the data are written to the given image class QgsWmsTiledImageDownloadHandler : public QObject { Q_OBJECT @@ -661,7 +661,7 @@ class QgsWmsTiledImageDownloadHandler : public QObject }; -/** Class keeping simple statistics for WMS provider - per unique URI */ +//! Class keeping simple statistics for WMS provider - per unique URI class QgsWmsStatistics { public: diff --git a/src/providers/wms/qgsxyzconnection.h b/src/providers/wms/qgsxyzconnection.h index ba1882546f60..92efe8463ab0 100644 --- a/src/providers/wms/qgsxyzconnection.h +++ b/src/providers/wms/qgsxyzconnection.h @@ -26,7 +26,7 @@ struct QgsXyzConnection QString encodedUri() const; }; -/** Utility class for handling list of connections to XYZ tile layers */ +//! Utility class for handling list of connections to XYZ tile layers class QgsXyzConnectionUtils { public: diff --git a/src/server/qgsaccesscontrol.cpp b/src/server/qgsaccesscontrol.cpp index 8e13d9020a20..f8fe1480ed18 100644 --- a/src/server/qgsaccesscontrol.cpp +++ b/src/server/qgsaccesscontrol.cpp @@ -23,7 +23,7 @@ #include -/** Filter the features of the layer */ +//! Filter the features of the layer void QgsAccessControl::filterFeatures( const QgsVectorLayer* layer, QgsFeatureRequest& featureRequest ) const { QStringList expressions = QStringList(); @@ -42,13 +42,13 @@ void QgsAccessControl::filterFeatures( const QgsVectorLayer* layer, QgsFeatureRe } } -/** Clone the object */ +//! Clone the object QgsFeatureFilterProvider* QgsAccessControl::clone() const { return new QgsAccessControl( *this ); } -/** Return an additional subset string (typically SQL) filter */ +//! Return an additional subset string (typically SQL) filter QString QgsAccessControl::extraSubsetString( const QgsVectorLayer* layer ) const { QStringList sqls; @@ -64,7 +64,7 @@ QString QgsAccessControl::extraSubsetString( const QgsVectorLayer* layer ) const return sqls.isEmpty() ? QString() : QStringLiteral( "((" ).append( sqls.join( QStringLiteral( ") AND (" ) ) ).append( "))" ); } -/** Return the layer read right */ +//! Return the layer read right bool QgsAccessControl::layerReadPermission( const QgsMapLayer* layer ) const { QgsAccessControlFilterMap::const_iterator acIterator; @@ -78,7 +78,7 @@ bool QgsAccessControl::layerReadPermission( const QgsMapLayer* layer ) const return true; } -/** Return the layer insert right */ +//! Return the layer insert right bool QgsAccessControl::layerInsertPermission( const QgsVectorLayer* layer ) const { QgsAccessControlFilterMap::const_iterator acIterator; @@ -92,7 +92,7 @@ bool QgsAccessControl::layerInsertPermission( const QgsVectorLayer* layer ) cons return true; } -/** Return the layer update right */ +//! Return the layer update right bool QgsAccessControl::layerUpdatePermission( const QgsVectorLayer* layer ) const { QgsAccessControlFilterMap::const_iterator acIterator; @@ -106,7 +106,7 @@ bool QgsAccessControl::layerUpdatePermission( const QgsVectorLayer* layer ) cons return true; } -/** Return the layer delete right */ +//! Return the layer delete right bool QgsAccessControl::layerDeletePermission( const QgsVectorLayer* layer ) const { QgsAccessControlFilterMap::const_iterator acIterator; @@ -120,7 +120,7 @@ bool QgsAccessControl::layerDeletePermission( const QgsVectorLayer* layer ) cons return true; } -/** Return the authorized layer attributes */ +//! Return the authorized layer attributes QStringList QgsAccessControl::layerAttributes( const QgsVectorLayer* layer, const QStringList& attributes ) const { QStringList currentAttributes( attributes ); @@ -132,7 +132,7 @@ QStringList QgsAccessControl::layerAttributes( const QgsVectorLayer* layer, cons return currentAttributes; } -/** Are we authorized to modify the following geometry */ +//! Are we authorized to modify the following geometry bool QgsAccessControl::allowToEdit( const QgsVectorLayer* layer, const QgsFeature& feature ) const { QgsAccessControlFilterMap::const_iterator acIterator; @@ -146,7 +146,7 @@ bool QgsAccessControl::allowToEdit( const QgsVectorLayer* layer, const QgsFeatur return true; } -/** Fill the capabilities caching key */ +//! Fill the capabilities caching key bool QgsAccessControl::fillCacheKey( QStringList& cacheKey ) const { QgsAccessControlFilterMap::const_iterator acIterator; @@ -163,7 +163,7 @@ bool QgsAccessControl::fillCacheKey( QStringList& cacheKey ) const return true; } -/** Register a new access control filter */ +//! Register a new access control filter void QgsAccessControl::registerAccessControl( QgsAccessControlFilter* accessControl, int priority ) { mPluginsAccessControls->insert( priority, accessControl ); diff --git a/src/server/qgsaccesscontrol.h b/src/server/qgsaccesscontrol.h index a42a194c5efa..f039ab7b9009 100644 --- a/src/server/qgsaccesscontrol.h +++ b/src/server/qgsaccesscontrol.h @@ -35,19 +35,19 @@ class QgsAccessControlPlugin; class SERVER_EXPORT QgsAccessControl : public QgsFeatureFilterProvider { public: - /** Constructor */ + //! Constructor QgsAccessControl() { mPluginsAccessControls = new QgsAccessControlFilterMap(); } - /** Constructor */ + //! Constructor QgsAccessControl( const QgsAccessControl& copy ) { mPluginsAccessControls = new QgsAccessControlFilterMap( *copy.mPluginsAccessControls ); } - /** Destructor */ + //! Destructor ~QgsAccessControl() { delete mPluginsAccessControls; @@ -121,7 +121,7 @@ class SERVER_EXPORT QgsAccessControl : public QgsFeatureFilterProvider void registerAccessControl( QgsAccessControlFilter* accessControl, int priority = 0 ); private: - /** The AccessControl plugins registry */ + //! The AccessControl plugins registry QgsAccessControlFilterMap* mPluginsAccessControls; }; diff --git a/src/server/qgsaccesscontrolfilter.cpp b/src/server/qgsaccesscontrolfilter.cpp index f75831a2a811..386b1806beb0 100644 --- a/src/server/qgsaccesscontrolfilter.cpp +++ b/src/server/qgsaccesscontrolfilter.cpp @@ -26,18 +26,18 @@ #include -/** Constructor */ +//! Constructor QgsAccessControlFilter::QgsAccessControlFilter( const QgsServerInterface* serverInterface ): mServerInterface( serverInterface ) { } -/** Destructor */ +//! Destructor QgsAccessControlFilter::~QgsAccessControlFilter() { } -/** Return an additional layer expression filter */ +//! Return an additional layer expression filter QString QgsAccessControlFilter::layerFilterExpression( const QgsVectorLayer* layer ) const { QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default layerFilterExpression called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); @@ -45,7 +45,7 @@ QString QgsAccessControlFilter::layerFilterExpression( const QgsVectorLayer* lay return QString(); } -/** Return an additional layer subset string (typically SQL) filter */ +//! Return an additional layer subset string (typically SQL) filter QString QgsAccessControlFilter::layerFilterSubsetString( const QgsVectorLayer* layer ) const { QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default layerFilterSQL called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); @@ -53,7 +53,7 @@ QString QgsAccessControlFilter::layerFilterSubsetString( const QgsVectorLayer* l return QString(); } -/** Return the layer permissions */ +//! Return the layer permissions QgsAccessControlFilter::LayerPermissions QgsAccessControlFilter::layerPermissions( const QgsMapLayer* layer ) const { QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default layerPermissions called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); @@ -63,7 +63,7 @@ QgsAccessControlFilter::LayerPermissions QgsAccessControlFilter::layerPermission return permissions; } -/** Return the authorized layer attributes */ +//! Return the authorized layer attributes QStringList QgsAccessControlFilter::authorizedLayerAttributes( const QgsVectorLayer* layer, const QStringList& attributes ) const { Q_UNUSED( layer ); @@ -71,7 +71,7 @@ QStringList QgsAccessControlFilter::authorizedLayerAttributes( const QgsVectorLa return attributes; } -/** Are we authorized to modify the feature */ +//! Are we authorized to modify the feature bool QgsAccessControlFilter::allowToEdit( const QgsVectorLayer* layer, const QgsFeature& feature ) const { QgsMessageLog::logMessage( QStringLiteral( "QgsAccessControlFilter plugin default allowToEdit called" ), QStringLiteral( "AccessControlFilter" ), QgsMessageLog::INFO ); @@ -80,7 +80,7 @@ bool QgsAccessControlFilter::allowToEdit( const QgsVectorLayer* layer, const Qgs return true; } -/** Cache key to used to create the capabilities cache, "" for no cache */ +//! Cache key to used to create the capabilities cache, "" for no cache QString QgsAccessControlFilter::cacheKey() const { return QString(); diff --git a/src/server/qgsaccesscontrolfilter.h b/src/server/qgsaccesscontrolfilter.h index 72dfd2f56432..cb596ad17e54 100644 --- a/src/server/qgsaccesscontrolfilter.h +++ b/src/server/qgsaccesscontrolfilter.h @@ -54,10 +54,10 @@ class SERVER_EXPORT QgsAccessControlFilter * and must be passed to QgsAccessControlFilter instances. */ QgsAccessControlFilter( const QgsServerInterface* serverInterface ); - /** Destructor */ + //! Destructor virtual ~QgsAccessControlFilter(); - /** Describe the layer permission */ + //! Describe the layer permission struct LayerPermissions { bool canRead; @@ -66,7 +66,7 @@ class SERVER_EXPORT QgsAccessControlFilter bool canDelete; }; - /** Return the QgsServerInterface instance */ + //! Return the QgsServerInterface instance const QgsServerInterface* serverInterface() const { return mServerInterface; } /** Return an additional expression filter @@ -108,12 +108,12 @@ class SERVER_EXPORT QgsAccessControlFilter private: - /** The server interface */ + //! The server interface const QgsServerInterface* mServerInterface; }; -/** The registry definition */ +//! The registry definition typedef QMultiMap QgsAccessControlFilterMap; diff --git a/src/server/qgscapabilitiescache.h b/src/server/qgscapabilitiescache.h index c82217ae0068..089ce3a1fae5 100644 --- a/src/server/qgscapabilitiescache.h +++ b/src/server/qgscapabilitiescache.h @@ -57,7 +57,7 @@ class SERVER_EXPORT QgsCapabilitiesCache : public QObject QFileSystemWatcher mFileSystemWatcher; private slots: - /** Removes changed entry from this cache*/ + //! Removes changed entry from this cache void removeChangedEntry( const QString &path ); }; diff --git a/src/server/qgsconfigcache.h b/src/server/qgsconfigcache.h index e7330d216719..37cfcea41bb6 100644 --- a/src/server/qgsconfigcache.h +++ b/src/server/qgsconfigcache.h @@ -66,10 +66,10 @@ class SERVER_EXPORT QgsConfigCache : public QObject private: QgsConfigCache(); - /** Check for configuration file updates (remove entry from cache if file changes)*/ + //! Check for configuration file updates (remove entry from cache if file changes) QFileSystemWatcher mFileSystemWatcher; - /** Returns xml document for project file / sld or 0 in case of errors*/ + //! Returns xml document for project file / sld or 0 in case of errors QDomDocument* xmlDocument( const QString& filePath ); QCache mXmlDocumentCache; @@ -78,7 +78,7 @@ class SERVER_EXPORT QgsConfigCache : public QObject QCache mWCSConfigCache; private slots: - /** Removes changed entry from this cache*/ + //! Removes changed entry from this cache void removeChangedEntry( const QString& path ); }; diff --git a/src/server/qgsconfigparserutils.h b/src/server/qgsconfigparserutils.h index a213fd8ffc6b..9cb8636fd1b1 100644 --- a/src/server/qgsconfigparserutils.h +++ b/src/server/qgsconfigparserutils.h @@ -40,10 +40,10 @@ class QgsConfigParserUtils const QStringList& constrainedCrsList ); static void appendLayerBoundingBox( QDomElement& layerElem, QDomDocument& doc, const QgsRectangle& layerExtent, const QgsCoordinateReferenceSystem& layerCRS, const QString& crsText ); - /** Returns a list of supported EPSG coordinate system numbers from a layer*/ + //! Returns a list of supported EPSG coordinate system numbers from a layer static QStringList createCrsListForLayer( QgsMapLayer* theMapLayer ); - /** Returns default service capabilities from wms_metadata.xml if nothing else is defined*/ + //! Returns default service capabilities from wms_metadata.xml if nothing else is defined static void fallbackServiceCapabilities( QDomElement& parentElement, QDomDocument& doc ); static QList layerMapToList( const QMap< int, QgsMapLayer* >& layerMap, bool reverseOrder = false ); diff --git a/src/server/qgshttprequesthandler.h b/src/server/qgshttprequesthandler.h index 833fab653ff5..8aad80af8a2e 100644 --- a/src/server/qgshttprequesthandler.h +++ b/src/server/qgshttprequesthandler.h @@ -47,7 +47,7 @@ class QgsHttpRequestHandler: public QgsRequestHandler virtual void setGetFeatureResponse( QByteArray* ba ) override; virtual void endGetFeatureResponse( QByteArray* ba ) override; virtual void setGetCoverageResponse( QByteArray* ba ) override; - /** Send out HTTP headers and flush output buffer*/ + //! Send out HTTP headers and flush output buffer virtual void sendResponse() override; virtual void setDefaultHeaders() override; virtual void setHeader( const QString &name, const QString &value ) override; @@ -64,7 +64,7 @@ class QgsHttpRequestHandler: public QgsRequestHandler #ifdef HAVE_SERVER_PYTHON_PLUGINS virtual void setPluginFilters( const QgsServerFiltersMap &pluginFilters ) override; #endif - /** Return the response if capture output is activated */ + //! Return the response if capture output is activated QPair getResponse() override; protected: @@ -76,7 +76,7 @@ class QgsHttpRequestHandler: public QgsRequestHandler QString formatToMimeType( const QString& format ) const; void requestStringToParameterMap( const QString& request, QMap& parameters ); - /** Read CONTENT_LENGTH characters from stdin*/ + //! Read CONTENT_LENGTH characters from stdin QString readPostBody() const; private: @@ -89,7 +89,7 @@ class QgsHttpRequestHandler: public QgsRequestHandler static bool greenCompare( QPair c1, QPair c2 ); static bool blueCompare( QPair c1, QPair c2 ); static bool alphaCompare( QPair c1, QPair c2 ); - /** Calculates a representative color for a box (pixel weighted average)*/ + //! Calculates a representative color for a box (pixel weighted average) static QRgb boxColor( const QgsColorBox& box, int boxPixels ); // TODO: if HAVE_SERVER_PYTHON QByteArray mResponseHeader; diff --git a/src/server/qgshttptransaction.h b/src/server/qgshttptransaction.h index 9377427c154f..412a885229c2 100644 --- a/src/server/qgshttptransaction.h +++ b/src/server/qgshttptransaction.h @@ -91,12 +91,12 @@ class QgsHttpTransaction : public QObject @return true if proxy settings was applied, false else*/ static bool applyProxySettings( QHttp& http, const QString& url ); - /** Set the credentials (username and password) */ + //! Set the credentials (username and password) void setCredentials( const QString& username, const QString &password ); - /** Returns the network timeout in msec*/ + //! Returns the network timeout in msec int networkTimeout() const { return mNetworkTimeoutMsec;} - /** Sets the network timeout in milliseconds*/ + //! Sets the network timeout in milliseconds void setNetworkTimeout( int msec ) { mNetworkTimeoutMsec = msec;} @@ -118,26 +118,26 @@ class QgsHttpTransaction : public QObject void networkTimedOut(); - /** Aborts the current transaction*/ + //! Aborts the current transaction void abort(); signals: - /** Legacy code. This signal is currently not emitted and only kept for API compatibility*/ + //! Legacy code. This signal is currently not emitted and only kept for API compatibility void setProgress( int done, int total ); - /** Signal for progress update */ + //! Signal for progress update void dataReadProgress( int theProgress ); - /** Signal for adjusted number of steps*/ + //! Signal for adjusted number of steps void totalSteps( int theTotalSteps ); - /** \brief emit a signal to be caught by qgisapp and display a msg on status bar */ + //! \brief emit a signal to be caught by qgisapp and display a msg on status bar void statusChanged( const QString& theStatusQString ); private: - /** Default constructor is forbidden*/ + //! Default constructor is forbidden QgsHttpTransaction(); /** @@ -214,7 +214,7 @@ class QgsHttpTransaction : public QObject */ QString mPassword; - /** Network timeout in milliseconds*/ + //! Network timeout in milliseconds int mNetworkTimeoutMsec; }; diff --git a/src/server/qgsinterpolationlayerbuilder.h b/src/server/qgsinterpolationlayerbuilder.h index f2b3711a0aff..0912f769748d 100644 --- a/src/server/qgsinterpolationlayerbuilder.h +++ b/src/server/qgsinterpolationlayerbuilder.h @@ -22,7 +22,7 @@ class QgsVectorLayer; -/** A class that produces a rasterlayer from a vector layer with spatial interpolation*/ +//! A class that produces a rasterlayer from a vector layer with spatial interpolation class QgsInterpolationLayerBuilder: public QgsMSLayerBuilder { public: diff --git a/src/server/qgsmaprenderer.h b/src/server/qgsmaprenderer.h index 975595314848..a243e7c2a5d9 100644 --- a/src/server/qgsmaprenderer.h +++ b/src/server/qgsmaprenderer.h @@ -61,7 +61,7 @@ class SERVER_EXPORT QgsMapRenderer : public QObject public: - /** Output units for pen width and point marker width/height*/ + //! Output units for pen width and point marker width/height enum OutputUnits { Millimeters, diff --git a/src/server/qgsmslayerbuilder.h b/src/server/qgsmslayerbuilder.h index c25f2f0a5df5..98fbe97138a0 100644 --- a/src/server/qgsmslayerbuilder.h +++ b/src/server/qgsmslayerbuilder.h @@ -43,7 +43,7 @@ class QgsMSLayerBuilder @return the created layer or 0 in case of error*/ virtual QgsMapLayer* createMapLayer( const QDomElement& elem, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching = true ) const = 0; protected: - /** Tries to create a suitable layer name from a URL. */ + //! Tries to create a suitable layer name from a URL. virtual QString layerNameFromUri( const QString& uri ) const; /** Helper function that creates a new temporary file with random name under /tmp/qgis_wms_serv/ and returns the path of the file (Unix). On Windows, it is created in the current working directory diff --git a/src/server/qgsmslayercache.h b/src/server/qgsmslayercache.h index 14b7b6ee3c2b..d00775feed37 100644 --- a/src/server/qgsmslayercache.h +++ b/src/server/qgsmslayercache.h @@ -73,19 +73,19 @@ class QgsMSLayerCache: public QObject //for debugging void logCacheContents() const; - /** Expose method for use in server interface */ + //! Expose method for use in server interface void removeProjectLayers( const QString& path ); protected: - /** Protected singleton constructor*/ + //! Protected singleton constructor QgsMSLayerCache(); /** Goes through the list and removes entries and layers depending on their time stamps and the number of other layers*/ void updateEntries(); - /** Removes the cash entry with the lowest 'lastUsedTime'*/ + //! Removes the cash entry with the lowest 'lastUsedTime' void removeLeastUsedEntry(); - /** Frees memory and removes temporary files of an entry*/ + //! Frees memory and removes temporary files of an entry void freeEntryRessources( QgsMSLayerCacheEntry& entry ); private: @@ -94,21 +94,21 @@ class QgsMSLayerCache: public QObject layer names*/ QMultiHash, QgsMSLayerCacheEntry> mEntries; - /** Config files used in the cache (with reference counter)*/ + //! Config files used in the cache (with reference counter) QHash< QString, int > mConfigFiles; - /** Check for configuration file updates (remove layers from cache if configuration file changes)*/ + //! Check for configuration file updates (remove layers from cache if configuration file changes) QFileSystemWatcher mFileSystemWatcher; - /** Maximum number of layers in the cache*/ + //! Maximum number of layers in the cache int mDefaultMaxLayers; - /** Maximum number of layers in the cache, overrides DEFAULT_MAX_N_LAYERS if larger*/ + //! Maximum number of layers in the cache, overrides DEFAULT_MAX_N_LAYERS if larger int mProjectMaxLayers; private slots: - /** Removes entries from a project (e.g. if a project file has changed)*/ + //! Removes entries from a project (e.g. if a project file has changed) void removeProjectFileLayers( const QString& project ); }; diff --git a/src/server/qgsmsutils.h b/src/server/qgsmsutils.h index 9751d9979a19..326e35e87600 100644 --- a/src/server/qgsmsutils.h +++ b/src/server/qgsmsutils.h @@ -17,14 +17,14 @@ #include -/** Some utility functions that may be included from everywhere in the code*/ +//! Some utility functions that may be included from everywhere in the code namespace QgsMSUtils { /** Creates a ramdom filename for a temporary file. This function also creates the directory to store the temporary files if it does not already exist. The directory is /tmp/qgis_map_serv/ under linux or the current working directory on windows*/ QString createTempFilePath(); - /** Stores the specified text in a temporary file. Returns 0 in case of success*/ + //! Stores the specified text in a temporary file. Returns 0 in case of success int createTextFile( const QString& filePath, const QString& text ); } diff --git a/src/server/qgsowsserver.cpp b/src/server/qgsowsserver.cpp index 9cae708eee35..1524c42c4ff9 100644 --- a/src/server/qgsowsserver.cpp +++ b/src/server/qgsowsserver.cpp @@ -22,7 +22,7 @@ #include "qgsvectordataprovider.h" #ifdef HAVE_SERVER_PYTHON_PLUGINS -/** Apply filter from AccessControl */ +//! Apply filter from AccessControl void QgsOWSServer::applyAccessControlLayerFilters( QgsMapLayer* mapLayer, QHash& originalLayerFilters ) const { if ( QgsVectorLayer* layer = qobject_cast( mapLayer ) ) @@ -48,7 +48,7 @@ void QgsOWSServer::applyAccessControlLayerFilters( QgsMapLayer* mapLayer, QHash< } #endif -/** Restore layer filter as original */ +//! Restore layer filter as original void QgsOWSServer::restoreLayerFilters( const QHash& filterMap ) { QHash::const_iterator filterIt = filterMap.constBegin(); diff --git a/src/server/qgsowsserver.h b/src/server/qgsowsserver.h index cd5748f95958..7ac0fd4c5560 100644 --- a/src/server/qgsowsserver.h +++ b/src/server/qgsowsserver.h @@ -62,7 +62,7 @@ class QgsOWSServer QgsRequestHandler* mRequestHandler; QString mConfigFilePath; #ifdef HAVE_SERVER_PYTHON_PLUGINS - /** The access control helper */ + //! The access control helper const QgsAccessControl* mAccessControl; /** Apply filter strings from the access control to the layers. diff --git a/src/server/qgspostrequesthandler.h b/src/server/qgspostrequesthandler.h index 0a9a2f111956..65ddf7a56307 100644 --- a/src/server/qgspostrequesthandler.h +++ b/src/server/qgspostrequesthandler.h @@ -20,14 +20,14 @@ #include "qgshttprequesthandler.h" -/** Request handler for HTTP POST*/ +//! Request handler for HTTP POST class QgsPostRequestHandler: public QgsHttpRequestHandler { public: explicit QgsPostRequestHandler( const bool captureOutput = false ); ~QgsPostRequestHandler(); - /** Parses the input and creates a request neutral Parameter/Value map*/ + //! Parses the input and creates a request neutral Parameter/Value map void parseInput() override; }; diff --git a/src/server/qgsremotedatasourcebuilder.h b/src/server/qgsremotedatasourcebuilder.h index 466c52ce230c..f97ae721c3db 100644 --- a/src/server/qgsremotedatasourcebuilder.h +++ b/src/server/qgsremotedatasourcebuilder.h @@ -22,7 +22,7 @@ class QgsRasterLayer; class QgsVectorLayer; -/** A class that creates map layer from or tags*/ +//! A class that creates map layer from or tags class QgsRemoteDataSourceBuilder: public QgsMSLayerBuilder { public: @@ -31,9 +31,9 @@ class QgsRemoteDataSourceBuilder: public QgsMSLayerBuilder QgsMapLayer* createMapLayer( const QDomElement& elem, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching = true ) const override; private: - /** Creates a raster layer from a . This function loads the data into a temporary file and creates a rasterlayer from it. Returns a 0 pointer in case of error*/ + //! Creates a raster layer from a . This function loads the data into a temporary file and creates a rasterlayer from it. Returns a 0 pointer in case of error QgsRasterLayer* rasterLayerFromRemoteRDS( const QDomElement& remoteRDSElem, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching = true ) const; - /** Saves the vector data into a temporary file and creates a vector layer. Returns a 0 pointer in case of error*/ + //! Saves the vector data into a temporary file and creates a vector layer. Returns a 0 pointer in case of error QgsVectorLayer* vectorLayerFromRemoteVDS( const QDomElement& remoteVDSElem, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching = true ) const; /** Loads data from http or ftp diff --git a/src/server/qgsremoteowsbuilder.h b/src/server/qgsremoteowsbuilder.h index 468520618ff8..d4f5414f9e8a 100644 --- a/src/server/qgsremoteowsbuilder.h +++ b/src/server/qgsremoteowsbuilder.h @@ -24,7 +24,7 @@ class QgsRasterLayer; class QgsVectorLayer; -/** Creates QGIS maplayers from sld tags*/ +//! Creates QGIS maplayers from sld tags class QgsRemoteOWSBuilder: public QgsMSLayerBuilder { public: @@ -35,11 +35,11 @@ class QgsRemoteOWSBuilder: public QgsMSLayerBuilder private: QgsRemoteOWSBuilder(); //forbidden - /** Creates a wms layer from a complete wms url (using http get). Returns 0 in case of error*/ + //! Creates a wms layer from a complete wms url (using http get). Returns 0 in case of error QgsRasterLayer* wmsLayerFromUrl( const QString& url, const QString& layerName, QList& layersToRemove, bool allowCaching = true ) const; - /** Creates a temporary file such that the gdal library can read from wcs*/ + //! Creates a temporary file such that the gdal library can read from wcs QgsRasterLayer* wcsLayerFromUrl( const QString& url, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching = true ) const; - /** Creates sos layer by analizing server url and LayerSensorObservationConstraints*/ + //! Creates sos layer by analizing server url and LayerSensorObservationConstraints QgsVectorLayer* sosLayer( const QDomElement& remoteOWSElem, const QString& url, const QString& layerName, QList& layersToRemove, bool allowCaching = true ) const; QMap mParameterMap; diff --git a/src/server/qgsrequesthandler.h b/src/server/qgsrequesthandler.h index 72c3f690e123..ecc50eeb2e1f 100644 --- a/src/server/qgsrequesthandler.h +++ b/src/server/qgsrequesthandler.h @@ -71,7 +71,7 @@ class QgsRequestHandler //! @note not available in Python bindings virtual void setGetFeatureInfoResponse( const QDomDocument& infoDoc, const QString& infoFormat ) = 0; - /** Allow plugins to return a QgsMapServiceException*/ + //! Allow plugins to return a QgsMapServiceException virtual void setServiceException( const QgsMapServiceException& ex ) = 0; //! @note not available in Python bindings @@ -97,34 +97,34 @@ class QgsRequestHandler virtual void setDefaultHeaders() {} - /** Set an HTTP header*/ + //! Set an HTTP header virtual void setHeader( const QString &name, const QString &value ) = 0; - /** Remove an HTTP header*/ + //! Remove an HTTP header virtual int removeHeader( const QString &name ) = 0; - /** Delete all HTTP headers*/ + //! Delete all HTTP headers virtual void clearHeaders() = 0; - /** Append the bytestream to response body*/ + //! Append the bytestream to response body virtual void appendBody( const QByteArray &body ) = 0; - /** Clears the response body*/ + //! Clears the response body virtual void clearBody() = 0; - /** Return the response body*/ + //! Return the response body virtual QByteArray body() { return mBody; } - /** Set the info format string such as "text/xml"*/ + //! Set the info format string such as "text/xml" virtual void setInfoFormat( const QString &format ) = 0; - /** Check whether there is any header set or the body is not empty*/ + //! Check whether there is any header set or the body is not empty virtual bool responseReady() const = 0; - /** Send out HTTP headers and flush output buffer*/ + //! Send out HTTP headers and flush output buffer virtual void sendResponse() = 0; - /** Pointer to last raised exception*/ + //! Pointer to last raised exception virtual bool exceptionRaised() const = 0; /** Return a copy of the parsed parameters as a key-value pair, to modify @@ -133,22 +133,22 @@ class QgsRequestHandler */ QMap parameterMap() { return mParameterMap; } - /** Set a request parameter*/ + //! Set a request parameter virtual void setParameter( const QString &key, const QString &value ) = 0; - /** Remove a request parameter*/ + //! Remove a request parameter virtual int removeParameter( const QString &key ) = 0; - /** Return a request parameter*/ + //! Return a request parameter virtual QString parameter( const QString &key ) const = 0; - /** Return the requested format string*/ + //! Return the requested format string QString format() const { return mFormat; } - /** Return the mime type for the response*/ + //! Return the mime type for the response QString infoFormat() const { return mInfoFormat; } - /** Return true if the HTTP headers were already sent to the client*/ + //! Return true if the HTTP headers were already sent to the client bool headersSent() { return mHeadersSent; } #ifdef HAVE_SERVER_PYTHON_PLUGINS @@ -171,7 +171,7 @@ class QgsRequestHandler QgsServerFiltersMap mPluginFilters; #endif QByteArray mBody; // The response payload - /** This is set by the parseInput methods of the subclasses (parameter FORMAT, e.g. 'FORMAT=PNG')*/ + //! This is set by the parseInput methods of the subclasses (parameter FORMAT, e.g. 'FORMAT=PNG') QString mFormat; QString mFormatString; //format string as it is passed in the request (with base) bool mHeadersSent; diff --git a/src/server/qgssentdatasourcebuilder.h b/src/server/qgssentdatasourcebuilder.h index dcf585294c3a..9a4aeada3e60 100644 --- a/src/server/qgssentdatasourcebuilder.h +++ b/src/server/qgssentdatasourcebuilder.h @@ -23,7 +23,7 @@ class QgsVectorLayer; class QgsRasterLayer; -/** Builds maplayer from and tags*/ +//! Builds maplayer from and tags class QgsSentDataSourceBuilder: public QgsMSLayerBuilder { public: @@ -39,10 +39,10 @@ class QgsSentDataSourceBuilder: public QgsMSLayerBuilder QgsMapLayer* createMapLayer( const QDomElement& elem, const QString& layerName, QList& filesToRemove, QList& layersToRemove, bool allowCaching = true ) const override; private: - /** Creates a vector layer from a tag. Returns a 0 pointer in case of error*/ + //! Creates a vector layer from a tag. Returns a 0 pointer in case of error QgsVectorLayer* vectorLayerFromSentVDS( const QDomElement& sentVDSElem, QList& filesToRemove, QList& layersToRemove ) const; - /** Creates a raster layer from a tag. Returns a 0 pointer in case of error*/ + //! Creates a raster layer from a tag. Returns a 0 pointer in case of error QgsRasterLayer* rasterLayerFromSentRDS( const QDomElement& sentRDSElem, QList& filesToRemove, QList& layersToRemove ) const; }; diff --git a/src/server/qgsserver.h b/src/server/qgsserver.h index 11f15bf814f0..022ccc8d9130 100644 --- a/src/server/qgsserver.h +++ b/src/server/qgsserver.h @@ -77,19 +77,19 @@ class SERVER_EXPORT QgsServer QPair testQPair( QPair pair ); #endif - /** Returns a pointer to the server interface */ + //! Returns a pointer to the server interface #ifdef HAVE_SERVER_PYTHON_PLUGINS QgsServerInterfaceImpl* serverInterface() { return sServerInterface; } #endif private: - /** Server initialization */ + //! Server initialization static bool init(); void saveEnvVars(); - /** Saves environment variable into mEnvironmentVariables if defined*/ + //! Saves environment variable into mEnvironmentVariables if defined void saveEnvVar( const QString& variableName ); // All functions that where previously in the main file are now @@ -125,7 +125,7 @@ class SERVER_EXPORT QgsServer static bool sInitialised; static bool sCaptureOutput; - /** Pass important environment variables to the fcgi processes*/ + //! Pass important environment variables to the fcgi processes QHash< QString, QString > mEnvironmentVariables; }; #endif // QGSSERVER_H diff --git a/src/server/qgsserverfilter.h b/src/server/qgsserverfilter.h index 3ae33ba4b594..415937aac166 100644 --- a/src/server/qgsserverfilter.h +++ b/src/server/qgsserverfilter.h @@ -46,9 +46,9 @@ class SERVER_EXPORT QgsServerFilter * and must be passed to QgsServerFilter instances. */ QgsServerFilter( QgsServerInterface* serverInterface ); - /** Destructor */ + //! Destructor virtual ~QgsServerFilter(); - /** Return the QgsServerInterface instance*/ + //! Return the QgsServerInterface instance QgsServerInterface* serverInterface() { return mServerInterface; } /** Method called when the QgsRequestHandler is ready and populated with * parameters, just before entering the main switch for core services.*/ diff --git a/src/server/qgsserverinterface.cpp b/src/server/qgsserverinterface.cpp index f6c9cbd2b8e5..302bcfd2bc0c 100644 --- a/src/server/qgsserverinterface.cpp +++ b/src/server/qgsserverinterface.cpp @@ -18,13 +18,13 @@ #include "qgsserverinterface.h" -/** Constructor */ +//! Constructor QgsServerInterface::QgsServerInterface(): mConfigFilePath( QString() ) { } -/** Destructor */ +//! Destructor QgsServerInterface::~QgsServerInterface() { } diff --git a/src/server/qgsserverinterface.h b/src/server/qgsserverinterface.h index 228bd7a2ccaa..cc21381ba5f5 100644 --- a/src/server/qgsserverinterface.h +++ b/src/server/qgsserverinterface.h @@ -45,10 +45,10 @@ class SERVER_EXPORT QgsServerInterface public: - /** Constructor */ + //! Constructor QgsServerInterface(); - /** Destructor */ + //! Destructor virtual ~QgsServerInterface() = 0; /** @@ -102,7 +102,7 @@ class SERVER_EXPORT QgsServerInterface */ virtual void registerAccessControl( QgsAccessControlFilter* accessControl, int priority = 0 ) = 0; - /** Gets the registred access control filters */ + //! Gets the registred access control filters virtual const QgsAccessControl* accessControls() const = 0; //! Return an enrironment variable, used to pass environment variables to python diff --git a/src/server/qgsserverinterfaceimpl.cpp b/src/server/qgsserverinterfaceimpl.cpp index 0da0ee12bdbf..a90cc65135eb 100644 --- a/src/server/qgsserverinterfaceimpl.cpp +++ b/src/server/qgsserverinterfaceimpl.cpp @@ -21,7 +21,7 @@ #include "qgsconfigcache.h" #include "qgsmslayercache.h" -/** Constructor */ +//! Constructor QgsServerInterfaceImpl::QgsServerInterfaceImpl( QgsCapabilitiesCache* capCache ) : mCapabilitiesCache( capCache ) { @@ -36,7 +36,7 @@ QString QgsServerInterfaceImpl::getEnv( const QString& name ) const } -/** Destructor */ +//! Destructor QgsServerInterfaceImpl::~QgsServerInterfaceImpl() { delete mAccessControls; @@ -68,7 +68,7 @@ void QgsServerInterfaceImpl::setFilters( QgsServerFiltersMap* filters ) mFilters = *filters; } -/** Register a new access control filter */ +//! Register a new access control filter void QgsServerInterfaceImpl::registerAccessControl( QgsAccessControlFilter* accessControl, int priority ) { mAccessControls->registerAccessControl( accessControl, priority ); diff --git a/src/server/qgsserverinterfaceimpl.h b/src/server/qgsserverinterfaceimpl.h index 92e58b5bf317..a799f35563e1 100644 --- a/src/server/qgsserverinterfaceimpl.h +++ b/src/server/qgsserverinterfaceimpl.h @@ -38,10 +38,10 @@ class QgsServerInterfaceImpl : public QgsServerInterface public: - /** Constructor */ + //! Constructor explicit QgsServerInterfaceImpl( QgsCapabilitiesCache *capCache ); - /** Destructor */ + //! Destructor ~QgsServerInterfaceImpl(); void setRequestHandler( QgsRequestHandler* requestHandler ) override; @@ -51,7 +51,7 @@ class QgsServerInterfaceImpl : public QgsServerInterface QgsRequestHandler* requestHandler() override { return mRequestHandler; } void registerFilter( QgsServerFilter *filter, int priority = 0 ) override; QgsServerFiltersMap filters() override { return mFilters; } - /** Register an access control filter */ + //! Register an access control filter void registerAccessControl( QgsAccessControlFilter *accessControl, int priority = 0 ) override; /** Gets the helper over all the registered access control filters * @return the access control helper diff --git a/src/server/qgsserverlogger.h b/src/server/qgsserverlogger.h index f57d9c084a37..01031bca7a46 100644 --- a/src/server/qgsserverlogger.h +++ b/src/server/qgsserverlogger.h @@ -25,7 +25,7 @@ #include #include -/** Writes message log into server logfile*/ +//! Writes message log into server logfile class QgsServerLogger: public QObject { Q_OBJECT diff --git a/src/server/qgsserverprojectparser.h b/src/server/qgsserverprojectparser.h index 3744739e82b3..02767b563302 100644 --- a/src/server/qgsserverprojectparser.h +++ b/src/server/qgsserverprojectparser.h @@ -44,10 +44,10 @@ class SERVER_EXPORT QgsServerProjectParser const QDomDocument* xmlDocument() const { return mXMLDoc; } - /** Returns project layers by id*/ + //! Returns project layers by id void projectLayerMap( QMap& layerMap ) const; - /** Converts a (possibly relative) path to absolute*/ + //! Converts a (possibly relative) path to absolute QString convertToAbsolutePath( const QString& file ) const; /** Creates a maplayer object from element. The layer cash owns the maplayer, so don't delete it @@ -56,10 +56,10 @@ class SERVER_EXPORT QgsServerProjectParser QgsMapLayer* mapLayerFromLayerId( const QString& lId, bool useCache = true ) const; - /** Returns the layer id under a tag in the QGIS projectfile*/ + //! Returns the layer id under a tag in the QGIS projectfile QString layerIdFromLegendLayer( const QDomElement& legendLayer ) const; - /** @param considerMapExtent Take user-defined map extent instead of data-calculated extent if present in project file*/ + //! @param considerMapExtent Take user-defined map extent instead of data-calculated extent if present in project file void combineExtentAndCrsOfGroupChildren( QDomElement& groupElement, QDomDocument& doc, bool considerMapExtent = false ) const; void addLayerProjectSettings( QDomElement& layerElem, QDomDocument& doc, QgsMapLayer* currentLayer ) const; @@ -112,11 +112,11 @@ class SERVER_EXPORT QgsServerProjectParser QStringList wfsLayers() const; QStringList wcsLayers() const; - /** Add layers for vector joins */ + //! Add layers for vector joins void addJoinLayersForElement( const QDomElement& layerElem ) const; void addValueRelationLayersForLayer( const QgsVectorLayer *vl ) const; - /** Add layers which are necessary for the evaluation of the expression function 'getFeature( layer, attributField, value)'*/ + //! Add layers which are necessary for the evaluation of the expression function 'getFeature( layer, attributField, value)' void addGetFeatureLayers( const QDomElement& layerElem ) const; /** Returns the text of the element for a layer element @@ -139,32 +139,32 @@ class SERVER_EXPORT QgsServerProjectParser private: - /** Content of project file*/ + //! Content of project file QDomDocument* mXMLDoc; - /** Absolute project file path (including file name)*/ + //! Absolute project file path (including file name) QString mProjectPath; - /** List of project layer (ordered same as in the project file)*/ + //! List of project layer (ordered same as in the project file) QList mProjectLayerElements; - /** Project layer elements, accessible by layer id*/ + //! Project layer elements, accessible by layer id QHash< QString, QDomElement > mProjectLayerElementsById; - /** Project layer elements, accessible by layer name*/ + //! Project layer elements, accessible by layer name QHash< QString, QDomElement > mProjectLayerElementsByName; - /** List of all legend group elements*/ + //! List of all legend group elements QList mLegendGroupElements; - /** Names of layers and groups which should not be published*/ + //! Names of layers and groups which should not be published QSet mRestrictedLayers; bool mUseLayerIDs; QgsServerProjectParser(); //forbidden - /** Returns a complete string set with all the restricted layer names (layers/groups that are not to be published)*/ + //! Returns a complete string set with all the restricted layer names (layers/groups that are not to be published) QSet findRestrictedLayers() const; QStringList mCustomLayerOrder; @@ -174,7 +174,7 @@ class SERVER_EXPORT QgsServerProjectParser QList findLegendGroupElements() const; QList setLegendGroupElementsWithLayerTree( QgsLayerTreeGroup* layerTreeGroup, const QDomElement& legendElement ) const; - /** Adds sublayers of an embedded group to layer set*/ + //! Adds sublayers of an embedded group to layer set static void sublayersOfEmbeddedGroup( const QString& projectFilePath, const QString& groupName, QSet& layerSet ); }; diff --git a/src/server/qgssldconfigparser.h b/src/server/qgssldconfigparser.h index 552a10ee01f3..0033d2a8123e 100644 --- a/src/server/qgssldconfigparser.h +++ b/src/server/qgssldconfigparser.h @@ -40,34 +40,34 @@ class QgsSLDConfigParser : public QgsWmsConfigParser @param fullProjectInformation If true: add extended project information (does not validate against WMS schema)*/ void layersAndStylesCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& version, bool fullProjectSettings = false ) const override; - /** Returns one or possibly several maplayers for a given layer name and style. If no layers/style are found, an empty list is returned*/ + //! Returns one or possibly several maplayers for a given layer name and style. If no layers/style are found, an empty list is returned QList mapLayerFromStyle( const QString& lName, const QString& styleName, bool useCache = true ) const override; - /** Fills a layer and a style list. The two list have the same number of entries and the style and the layer at a position belong together (similar to the HTTP parameters 'Layers' and 'Styles'. Returns 0 in case of success*/ + //! Fills a layer and a style list. The two list have the same number of entries and the style and the layer at a position belong together (similar to the HTTP parameters 'Layers' and 'Styles'. Returns 0 in case of success int layersAndStyles( QStringList& layers, QStringList& styles ) const override; - /** Returns the xml fragment of a style*/ + //! Returns the xml fragment of a style QDomDocument getStyle( const QString& styleName, const QString& layerName ) const override; - /** Returns the xml fragment of layers styles*/ + //! Returns the xml fragment of layers styles QDomDocument getStyles( QStringList& layerList ) const override; - /** Returns the xml fragment of layers styles description*/ + //! Returns the xml fragment of layers styles description QDomDocument describeLayer( QStringList& layerList, const QString& hrefString ) const override; - /** Returns if output are MM or PIXEL*/ + //! Returns if output are MM or PIXEL QgsMapRenderer::OutputUnits outputUnits() const override; - /** Returns an ID-list of layers which are not queryable (comes from -> -> -> -> featureInfoLayerAliasMap() const override; QString featureInfoDocumentElement( const QString& defaultValue ) const override; @@ -76,13 +76,13 @@ class QgsSLDConfigParser : public QgsWmsConfigParser QString featureInfoSchema() const override; - /** Return feature info in format SIA2045?*/ + //! Return feature info in format SIA2045? bool featureInfoFormatSIA2045() const override; - /** Draw text annotation items from the QGIS projectfile*/ + //! Draw text annotation items from the QGIS projectfile void drawOverlays( QPainter* p, int dpi, int width, int height ) const override; - /** Load PAL engine settings from projectfile*/ + //! Load PAL engine settings from projectfile void loadLabelSettings( QgsLabelingEngineInterface* lbl ) const override; QString serviceUrl() const override; @@ -109,18 +109,18 @@ class QgsSLDConfigParser : public QgsWmsConfigParser // WMS inspire capabilities bool wmsInspireActivated() const override; - /** Adds inspire capabilities to xml document. ParentElem usually is the element*/ + //! Adds inspire capabilities to xml document. ParentElem usually is the element void inspireCapabilities( QDomElement& parentElement, QDomDocument& doc ) const override; //printing - /** Creates a print composition, usually for a GetPrint request. Replaces map and label parameters*/ + //! Creates a print composition, usually for a GetPrint request. Replaces map and label parameters QgsComposition* createPrintComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, const QMap< QString, QString >& parameterMap, QStringList& highlightLayers ) const; - /** Creates a composition from the project file (probably delegated to the fallback parser)*/ + //! Creates a composition from the project file (probably delegated to the fallback parser) QgsComposition* initComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, QList< QgsComposerMap*>& mapList, QList< QgsComposerLegend* >& legendList, QList< QgsComposerLabel* >& labelList, QList& htmlFrameList ) const override; - /** Adds print capabilities to xml document. ParentElem usually is the element*/ + //! Adds print capabilities to xml document. ParentElem usually is the element void printCapabilities( QDomElement& parentElement, QDomDocument& doc ) const override; void setScaleDenominator( double denom ) override; @@ -134,15 +134,15 @@ class QgsSLDConfigParser : public QgsWmsConfigParser private: - /** SLD as dom document*/ + //! SLD as dom document QDomDocument* mXMLDoc; - /** Map containing the WMS parameters of the request*/ + //! Map containing the WMS parameters of the request QMap mParameterMap; QString mSLDNamespace; - /** Output units (pixel or mm)*/ + //! Output units (pixel or mm) QgsMapRenderer::OutputUnits mOutputUnits; QgsWmsConfigParser *mFallbackParser; @@ -151,10 +151,10 @@ class QgsSLDConfigParser : public QgsWmsConfigParser QFont mLegendItemFont; - /** Stores pointers to layers that have to be removed after the request*/ + //! Stores pointers to layers that have to be removed after the request mutable QList mLayersToRemove; - /** Stores the temporary file objects. The class takes ownership of the objects and deletes them in the destructor*/ + //! Stores the temporary file objects. The class takes ownership of the objects and deletes them in the destructor mutable QList mFilesToRemove; /** Stores paths of files that need to be removed after each request (necessary because of contours shapefiles that @@ -164,16 +164,16 @@ class QgsSLDConfigParser : public QgsWmsConfigParser //default constructor forbidden QgsSLDConfigParser(); - /** Returns a list of all element that match the layer name. Returns an empty list if no such layer*/ + //! Returns a list of all element that match the layer name. Returns an empty list if no such layer QList findNamedLayerElements( const QString& layerName ) const; - /** Returns the node of a given or a null node in case of failure*/ + //! Returns the node of a given or a null node in case of failure QDomElement findUserStyleElement( const QDomElement& userLayerElement, const QString& styleName ) const; - /** Returns the node of a given or a null node in case of failure*/ + //! Returns the node of a given or a null node in case of failure QDomElement findNamedStyleElement( const QDomElement& layerElement, const QString& styleName ) const; - /** Creates a Renderer from a UserStyle SLD node. Returns 0 in case of error*/ + //! Creates a Renderer from a UserStyle SLD node. Returns 0 in case of error QgsFeatureRenderer* rendererFromUserStyle( const QDomElement& userStyleElement, QgsVectorLayer* vec ) const; /** Searches for a element and applies the settings to the vector layer @@ -188,7 +188,7 @@ class QgsSLDConfigParser : public QgsWmsConfigParser @return the layer or 0 if no layer could be created*/ QgsVectorLayer* contourLayerFromRaster( const QDomElement& userStyleElem, QgsRasterLayer* rasterLayer ) const; - /** Returns the dom node or a null node in case of failure*/ + //! Returns the dom node or a null node in case of failure QDomElement findUserLayerElement( const QString& layerName ) const; /** Creates a vector layer from a tag. @@ -197,7 +197,7 @@ class QgsSLDConfigParser : public QgsWmsConfigParser Delegates the work to specific methods for , or */ QgsMapLayer* mapLayerFromUserLayer( const QDomElement& userLayerElem, const QString& layerName, bool allowCaching = true ) const; - /** Reads attributes "epsg" or "proj" from layer element and sets specified CRS if present*/ + //! Reads attributes "epsg" or "proj" from layer element and sets specified CRS if present void setCrsForLayer( const QDomElement& layerElem, QgsMapLayer* ml ) const; bool useLayerIds() const override { return false; } diff --git a/src/server/qgssoaprequesthandler.h b/src/server/qgssoaprequesthandler.h index c683fb4cd157..14895c5b8572 100644 --- a/src/server/qgssoaprequesthandler.h +++ b/src/server/qgssoaprequesthandler.h @@ -22,7 +22,7 @@ class QDomElement; -/** A handler to parse requests via SOAP/HTTP POST*/ +//! A handler to parse requests via SOAP/HTTP POST class QgsSOAPRequestHandler: public QgsHttpRequestHandler { public: @@ -37,15 +37,15 @@ class QgsSOAPRequestHandler: public QgsHttpRequestHandler void setXmlResponse( const QDomDocument& doc, const QString& mimeType ) override; void setGetPrintResponse( QByteArray* ba ) override; private: - /** Parses the xml of a getMap request and fills the parameters into the map. Returns 0 in case of success*/ + //! Parses the xml of a getMap request and fills the parameters into the map. Returns 0 in case of success int parseGetMapElement( QMap& parameterMap, const QDomElement& getMapElement ) const; - /** Parses the xml of a feature info request and fills the parameters into the map. Returns 0 in case of success*/ + //! Parses the xml of a feature info request and fills the parameters into the map. Returns 0 in case of success int parseGetFeatureInfoElement( QMap& parameterMap, const QDomElement& getMapElement ) const; int parseBoundingBoxElement( QMap& parameterMap, const QDomElement& boundingBoxElement ) const; int parseOutputAttributesElement( QMap& parameterMap, const QDomElement& outputAttributesElement ) const; int setSOAPWithAttachments( QImage* img ); int setUrlToFile( QImage* img ); - /** Reads the file wms_metadata.xml and extract the OnlineResource href. Returns 0 in case of success.*/ + //! Reads the file wms_metadata.xml and extract the OnlineResource href. Returns 0 in case of success. int findOutHostAddress( QString& address ) const; }; diff --git a/src/server/qgswcsserver.h b/src/server/qgswcsserver.h index 9fc20e177944..f82fed750ce6 100644 --- a/src/server/qgswcsserver.h +++ b/src/server/qgswcsserver.h @@ -35,7 +35,7 @@ independent from any server side technology*/ class QgsWCSServer: public QgsOWSServer { public: - /** Constructor. Takes parameter map and a pointer to a renderer object (does not take ownership)*/ + //! Constructor. Takes parameter map and a pointer to a renderer object (does not take ownership) QgsWCSServer( const QString& configFilePath , QMap& parameters @@ -49,23 +49,23 @@ class QgsWCSServer: public QgsOWSServer void executeRequest() override; - /** Returns an XML file with the capabilities description (as described in the WFS specs)*/ + //! Returns an XML file with the capabilities description (as described in the WFS specs) QDomDocument getCapabilities(); - /** Returns an XML file with the describe Coverage (as described in the WCS specs)*/ + //! Returns an XML file with the describe Coverage (as described in the WCS specs) QDomDocument describeCoverage(); - /** Creates a file which is the result of the getCoverage request.*/ + //! Creates a file which is the result of the getCoverage request. QByteArray* getCoverage(); - /** Sets configuration parser for administration settings. Does not take ownership*/ + //! Sets configuration parser for administration settings. Does not take ownership void setAdminConfigParser( QgsWCSProjectParser* parser ) { mConfigParser = parser; } private: - /** Don't use the default constructor*/ + //! Don't use the default constructor QgsWCSServer(); - /** Get service address from REQUEST_URI if not specified in the configuration*/ + //! Get service address from REQUEST_URI if not specified in the configuration QString serviceUrl() const; QgsWCSProjectParser* mConfigParser; diff --git a/src/server/qgswfsserver.h b/src/server/qgswfsserver.h index ae24baeb56f2..596a17fdb82c 100644 --- a/src/server/qgswfsserver.h +++ b/src/server/qgswfsserver.h @@ -59,7 +59,7 @@ independent from any server side technology*/ class QgsWfsServer: public QgsOWSServer { public: - /** Constructor. Takes parameter map and a pointer to a renderer object (does not take ownership)*/ + //! Constructor. Takes parameter map and a pointer to a renderer object (does not take ownership) QgsWfsServer( const QString& configFilePath , QMap& parameters @@ -73,10 +73,10 @@ class QgsWfsServer: public QgsOWSServer void executeRequest() override; - /** Returns an XML file with the capabilities description (as described in the WFS specs)*/ + //! Returns an XML file with the capabilities description (as described in the WFS specs) QDomDocument getCapabilities(); - /** Returns an XML file with the describe feature type (as described in the WFS specs)*/ + //! Returns an XML file with the describe feature type (as described in the WFS specs) QDomDocument describeFeatureType(); /** Creates a document that describes the result of the getFeature request. @@ -87,14 +87,14 @@ class QgsWfsServer: public QgsOWSServer @return 0 in case of success*/ QDomDocument transaction( const QString& requestBody ); - /** Sets configuration parser for administration settings. Does not take ownership*/ + //! Sets configuration parser for administration settings. Does not take ownership void setAdminConfigParser( QgsWfsProjectParser* parser ) { mConfigParser = parser; } private: - /** Don't use the default constructor*/ + //! Don't use the default constructor QgsWfsServer(); - /** Get service address from REQUEST_URI if not specified in the configuration*/ + //! Get service address from REQUEST_URI if not specified in the configuration QString serviceUrl() const; /* The Type of Feature created */ diff --git a/src/server/qgswmsconfigparser.h b/src/server/qgswmsconfigparser.h index 6f354c7fabdb..2159f9748107 100644 --- a/src/server/qgswmsconfigparser.h +++ b/src/server/qgswmsconfigparser.h @@ -40,34 +40,34 @@ class SERVER_EXPORT QgsWmsConfigParser @param fullProjectInformation If true: add extended project information (does not validate against WMS schema)*/ virtual void layersAndStylesCapabilities( QDomElement& parentElement, QDomDocument& doc, const QString& version, bool fullProjectSettings = false ) const = 0; - /** Returns one or possibly several maplayers for a given layer name and style. If no layers/style are found, an empty list is returned*/ + //! Returns one or possibly several maplayers for a given layer name and style. If no layers/style are found, an empty list is returned virtual QList mapLayerFromStyle( const QString& lName, const QString& styleName, bool useCache = true ) const = 0; - /** Fills a layer and a style list. The two list have the same number of entries and the style and the layer at a position belong together (similar to the HTTP parameters 'Layers' and 'Styles'. Returns 0 in case of success*/ + //! Fills a layer and a style list. The two list have the same number of entries and the style and the layer at a position belong together (similar to the HTTP parameters 'Layers' and 'Styles'. Returns 0 in case of success virtual int layersAndStyles( QStringList& layers, QStringList& styles ) const = 0; - /** Returns the xml fragment of a style*/ + //! Returns the xml fragment of a style virtual QDomDocument getStyle( const QString& styleName, const QString& layerName ) const = 0; - /** Returns the xml fragment of layers styles*/ + //! Returns the xml fragment of layers styles virtual QDomDocument getStyles( QStringList& layerList ) const = 0; - /** Returns the xml fragment of layers styles description*/ + //! Returns the xml fragment of layers styles description virtual QDomDocument describeLayer( QStringList& layerList, const QString& hrefString ) const = 0; - /** Returns if output are MM or PIXEL*/ + //! Returns if output are MM or PIXEL virtual QgsMapRenderer::OutputUnits outputUnits() const = 0; - /** Returns an ID-list of layers which are not queryable (comes from -> -> -> -> featureInfoLayerAliasMap() const = 0; virtual QString featureInfoDocumentElement( const QString& defaultValue ) const = 0; @@ -76,13 +76,13 @@ class SERVER_EXPORT QgsWmsConfigParser virtual QString featureInfoSchema() const = 0; - /** Return feature info in format SIA2045?*/ + //! Return feature info in format SIA2045? virtual bool featureInfoFormatSIA2045() const = 0; - /** Draw text annotation items from the QGIS projectfile*/ + //! Draw text annotation items from the QGIS projectfile virtual void drawOverlays( QPainter* p, int dpi, int width, int height ) const = 0; - /** Load PAL engine settings from the QGIS projectfile*/ + //! Load PAL engine settings from the QGIS projectfile virtual void loadLabelSettings( QgsLabelingEngineInterface* lbl ) const = 0; virtual QString serviceUrl() const = 0; @@ -111,21 +111,21 @@ class SERVER_EXPORT QgsWmsConfigParser // WMS inspire capabilities virtual bool wmsInspireActivated() const = 0; - /** Adds inspire capabilities to xml document. ParentElem usually is the element*/ + //! Adds inspire capabilities to xml document. ParentElem usually is the element virtual void inspireCapabilities( QDomElement& parentElement, QDomDocument& doc ) const = 0; //printing - /** Creates a print composition, usually for a GetPrint request. Replaces map and label parameters*/ + //! Creates a print composition, usually for a GetPrint request. Replaces map and label parameters QgsComposition* createPrintComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, const QMap< QString, QString >& parameterMap ) const; - /** Creates a print composition, usually for a GetPrint request. Replaces map and label parameters*/ + //! Creates a print composition, usually for a GetPrint request. Replaces map and label parameters QgsComposition* createPrintComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, const QMap< QString, QString >& parameterMap, QStringList& highlightLayers ) const; - /** Creates a composition from the project file (probably delegated to the fallback parser)*/ + //! Creates a composition from the project file (probably delegated to the fallback parser) virtual QgsComposition* initComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, QList< QgsComposerMap*>& mapList, QList< QgsComposerLegend* >& legendList, QList< QgsComposerLabel* >& labelList, QList& htmlFrameList ) const = 0; - /** Adds print capabilities to xml document. ParentElem usually is the element*/ + //! Adds print capabilities to xml document. ParentElem usually is the element virtual void printCapabilities( QDomElement& parentElement, QDomDocument& doc ) const = 0; virtual void setScaleDenominator( double denom ) = 0; @@ -139,12 +139,12 @@ class SERVER_EXPORT QgsWmsConfigParser virtual bool useLayerIds() const = 0; - /** Adds highlight layers to the layer registry and to the layer set. Returns the ids of the newly created layers (for later removal)*/ + //! Adds highlight layers to the layer registry and to the layer set. Returns the ids of the newly created layers (for later removal) static QStringList addHighlightLayers( const QMap& parameterMap, QStringList& layerSet, const QString& parameterPrefix = QString() ); static void removeHighlightLayers( const QStringList& layerIds ); #if 0 - /** List of GML datasets passed outside SLD (e.g. in a SOAP request). Key of the map is the layer name*/ + //! List of GML datasets passed outside SLD (e.g. in a SOAP request). Key of the map is the layer name QMap mExternalGMLDatasets; #endif //0 diff --git a/src/server/qgswmsprojectparser.h b/src/server/qgswmsprojectparser.h index 2b4687877349..3a5d93a615eb 100644 --- a/src/server/qgswmsprojectparser.h +++ b/src/server/qgswmsprojectparser.h @@ -82,28 +82,28 @@ class SERVER_EXPORT QgsWmsProjectParser : public QgsWmsConfigParser QList< QPair< QString, QgsLayerCoordinateTransform > > layerCoordinateTransforms() const override; - /** Fills a layer and a style list. The two list have the same number of entries and the style and the layer at a position belong together (similar to the HTTP parameters 'Layers' and 'Styles'. Returns 0 in case of success*/ + //! Fills a layer and a style list. The two list have the same number of entries and the style and the layer at a position belong together (similar to the HTTP parameters 'Layers' and 'Styles'. Returns 0 in case of success int layersAndStyles( QStringList& layers, QStringList& styles ) const override; - /** Returns the xml fragment of a style*/ + //! Returns the xml fragment of a style QDomDocument getStyle( const QString& styleName, const QString& layerName ) const override; - /** Returns the xml fragment of layers styles*/ + //! Returns the xml fragment of layers styles QDomDocument getStyles( QStringList& layerList ) const override; - /** Returns the xml fragment of layers styles description*/ + //! Returns the xml fragment of layers styles description QDomDocument describeLayer( QStringList& layerList, const QString& hrefString ) const override; - /** Returns if output are MM or PIXEL*/ + //! Returns if output are MM or PIXEL QgsMapRenderer::OutputUnits outputUnits() const override; - /** True if the feature info response should contain the wkt geometry for vector features*/ + //! True if the feature info response should contain the wkt geometry for vector features bool featureInfoWithWktGeometry() const override; - /** True if the feature info wkt geometry is delivered with segmentized curve types*/ + //! True if the feature info wkt geometry is delivered with segmentized curve types bool segmentizeFeatureInfoWktGeometry() const override; - /** Returns map with layer aliases for GetFeatureInfo (or 0 pointer if not supported). Key: layer name, Value: layer alias*/ + //! Returns map with layer aliases for GetFeatureInfo (or 0 pointer if not supported). Key: layer name, Value: layer alias QHash featureInfoLayerAliasMap() const override; QString featureInfoDocumentElement( const QString& defaultValue ) const override; @@ -112,13 +112,13 @@ class SERVER_EXPORT QgsWmsProjectParser : public QgsWmsConfigParser QString featureInfoSchema() const override; - /** Return feature info in format SIA2045?*/ + //! Return feature info in format SIA2045? bool featureInfoFormatSIA2045() const override; - /** Draw text annotation items from the QGIS projectfile*/ + //! Draw text annotation items from the QGIS projectfile void drawOverlays( QPainter* p, int dpi, int width, int height ) const override; - /** Load PAL engine settings from projectfile*/ + //! Load PAL engine settings from projectfile void loadLabelSettings( QgsLabelingEngineInterface* lbl ) const override; int nLayers() const override; @@ -136,15 +136,15 @@ class SERVER_EXPORT QgsWmsProjectParser : public QgsWmsConfigParser mutable QFont mLegendLayerFont; mutable QFont mLegendItemFont; - /** Watermark text items*/ + //! Watermark text items QList< QPair< QTextDocument*, QDomElement > > mTextAnnotationItems; - /** Watermark items (content cached in QgsSVGCache)*/ + //! Watermark items (content cached in QgsSVGCache) QList< QPair< QSvgRenderer*, QDomElement > > mSvgAnnotationElems; - /** Returns an ID-list of layers which are not queryable (comes from -> -> -> -> element)*/ + //! Reads layer drawing order from the legend section of the project file and appends it to the parent elemen (usually the element) void addDrawingOrder( QDomElement& parentElem, QDomDocument& doc, const QHash &idNameMap, const QStringList &layerIDList ) const; void addLayerStyles( QgsMapLayer* currentLayer, QDomDocument& doc, QDomElement& layerElem, const QString& version ) const; @@ -166,7 +166,7 @@ class SERVER_EXPORT QgsWmsProjectParser : public QgsWmsConfigParser const QMap &layerMap, const QStringList &nonIdentifiableLayers, const QString& strHref, QgsRectangle& combinedBBox, const QString& strGroup ) const; - /** Adds layers from a legend group to list (could be embedded or a normal group)*/ + //! Adds layers from a legend group to list (could be embedded or a normal group) void addLayersFromGroup( const QDomElement& legendGroupElem, QMap< int, QgsMapLayer*>& layers, bool useCache = true ) const; QDomElement composerByName( const QString& composerName ) const; diff --git a/src/server/qgswmsserver.h b/src/server/qgswmsserver.h index 5053531e9891..5268c090a1fc 100644 --- a/src/server/qgswmsserver.h +++ b/src/server/qgswmsserver.h @@ -95,13 +95,13 @@ class QgsWmsServer: public QgsOWSServer of the image object). If an instance to existing hit test structure is passed, instead of rendering it will fill the structure with symbols that would be used for rendering */ QImage* getMap( HitTest* hitTest = nullptr ); - /** GetMap request with vector format output. This output is usually symbolized (difference to WFS GetFeature)*/ + //! GetMap request with vector format output. This output is usually symbolized (difference to WFS GetFeature) void getMapAsDxf(); - /** Returns an SLD file with the style of the requested layer. Exception is raised in case of troubles :-)*/ + //! Returns an SLD file with the style of the requested layer. Exception is raised in case of troubles :-) QDomDocument getStyle(); - /** Returns an SLD file with the styles of the requested layers. Exception is raised in case of troubles :-)*/ + //! Returns an SLD file with the styles of the requested layers. Exception is raised in case of troubles :-) QDomDocument getStyles(); - /** Returns a describeLayer file with the onlineResource of the requested layers. Exception is raised in case of troubles :-)*/ + //! Returns a describeLayer file with the onlineResource of the requested layers. Exception is raised in case of troubles :-) QDomDocument describeLayer(); /** Returns printed page as binary @@ -113,14 +113,14 @@ class QgsWmsServer: public QgsOWSServer @return 0 in case of success*/ int getFeatureInfo( QDomDocument& result, const QString& version = "1.3.0" ); - /** Sets configuration parser for administration settings. Does not take ownership*/ + //! Sets configuration parser for administration settings. Does not take ownership void setAdminConfigParser( QgsWmsConfigParser* parser ) { mConfigParser = parser; } - /** Returns the schemaExtension for WMS 1.3.0 capabilities*/ + //! Returns the schemaExtension for WMS 1.3.0 capabilities QDomDocument getSchemaExtension(); private: - /** Don't use the default constructor*/ + //! Don't use the default constructor QgsWmsServer(); /** Initializes WMS layers and configures mMapRendering. @@ -161,7 +161,7 @@ class QgsWmsServer: public QgsOWSServer const QString& version, const QString& infoFormat, QgsRectangle* featureBBox = nullptr ) const; - /** Appends feature info xml for the layer to the layer element of the dom document*/ + //! Appends feature info xml for the layer to the layer element of the dom document int featureInfoFromRasterLayer( QgsRasterLayer* layer, const QgsPoint* infoPoint, QDomDocument& infoDocument, @@ -173,12 +173,12 @@ class QgsWmsServer: public QgsOWSServer @param scaleDenominator Filter out layer if scale based visibility does not match (or use -1 if no scale restriction)*/ QStringList layerSet( const QStringList& layersList, const QStringList& stylesList, const QgsCoordinateReferenceSystem& destCRS, double scaleDenominator = -1 ) const; - /** Record which symbols would be used if the map was in the current configuration of mMapRenderer. This is useful for content-based legend*/ + //! Record which symbols would be used if the map was in the current configuration of mMapRenderer. This is useful for content-based legend void runHitTest( QPainter* painter, HitTest& hitTest ); - /** Record which symbols within one layer would be rendered with the given renderer context*/ + //! Record which symbols within one layer would be rendered with the given renderer context void runHitTestLayer( QgsVectorLayer* vl, SymbolSet& usedSymbols, QgsRenderContext& context ); - /** Read legend parameter from the request or from the first print composer in the project*/ + //! Read legend parameter from the request or from the first print composer in the project void legendParameters( double& boxSpace, double& layerSpace, double& layerTitleSpace, double& symbolSpace, double& iconLabelSpace, double& symbolWidth, double& symbolHeight, QFont& layerFont, QFont& itemFont, QColor& layerFontColor, QColor& itemFontColor ); @@ -206,23 +206,23 @@ class QgsWmsServer: public QgsOWSServer /** Tests if a filter sql string is allowed (safe) @return true in case of success, false if string seems unsafe*/ bool testFilterStringSafety( const QString& filter ) const; - /** Helper function for filter safety test. Groups stringlist to merge entries starting/ending with quotes*/ + //! Helper function for filter safety test. Groups stringlist to merge entries starting/ending with quotes static void groupStringList( QStringList& list, const QString& groupString ); /** Select vector features with ids specified in parameter SELECTED, e.g. ...&SELECTED=layer1:1,2,9;layer2:3,5,10&... @return list with layer ids where selections have been created*/ QStringList applyFeatureSelections( const QStringList& layerList ) const; - /** Clear all feature selections in the given layers*/ + //! Clear all feature selections in the given layers void clearFeatureSelections( const QStringList& layerIds ) const; - /** Applies opacity on layer/group level*/ + //! Applies opacity on layer/group level void applyOpacities( const QStringList& layerList, QList< QPair< QgsVectorLayer*, QgsFeatureRenderer*> >& vectorRenderers, QList< QPair< QgsRasterLayer*, QgsRasterRenderer* > >& rasterRenderers, QList< QPair< QgsVectorLayer*, double > >& labelTransparencies, QList< QPair< QgsVectorLayer*, double > >& labelBufferTransparencies ); - /** Restore original opacities*/ + //! Restore original opacities void restoreOpacities( QList< QPair >& vectorRenderers, QList< QPair < QgsRasterLayer*, QgsRasterRenderer* > >& rasterRenderers, QList< QPair< QgsVectorLayer*, double > >& labelTransparencies, @@ -234,19 +234,19 @@ class QgsWmsServer: public QgsOWSServer @return true if width/height values are okay*/ bool checkMaximumWidthHeight() const; - /** Get service address from REQUEST_URI if not specified in the configuration*/ + //! Get service address from REQUEST_URI if not specified in the configuration QString serviceUrl() const; - /** Add ''. Some clients need an xml declaration (though it is not strictly required)*/ + //! Add ''. Some clients need an xml declaration (though it is not strictly required) void addXmlDeclaration( QDomDocument& doc ) const; - /** Converts a feature info xml document to SIA2045 norm*/ + //! Converts a feature info xml document to SIA2045 norm void convertFeatureInfoToSIA2045( QDomDocument& doc ); - /** Cleanup temporary objects (e.g. SLD parser objects or temporary files) after request*/ + //! Cleanup temporary objects (e.g. SLD parser objects or temporary files) after request void cleanupAfterRequest(); - /** Map containing the WMS parameters*/ + //! Map containing the WMS parameters QgsMapRenderer* mMapRenderer; QgsCapabilitiesCache* mCapabilitiesCache; @@ -269,19 +269,19 @@ class QgsWmsServer: public QgsOWSServer int version, QStringList* attributes = nullptr ) const; - /** Replaces attribute value with ValueRelation or ValueRelation if defined. Otherwise returns the original value*/ + //! Replaces attribute value with ValueRelation or ValueRelation if defined. Otherwise returns the original value static QString replaceValueMapAndRelation( QgsVectorLayer* vl, int idx, const QString& attributeVal ); - /** Return the image quality to use for getMap request */ + //! Return the image quality to use for getMap request int getImageQuality() const; - /** Return precision to use for GetFeatureInfo request */ + //! Return precision to use for GetFeatureInfo request int getWMSPrecision( int defaultValue ) const; - /** Gets layer search rectangle (depending on request parameter, layer type, map and layer crs)*/ + //! Gets layer search rectangle (depending on request parameter, layer type, map and layer crs) QgsRectangle featureInfoSearchRect( QgsVectorLayer* ml, QgsMapRenderer* mr, const QgsRenderContext& rct, const QgsPoint& infoPoint ) const; - /** Reads and extracts the different options in the FORMAT_OPTIONS parameter*/ + //! Reads and extracts the different options in the FORMAT_OPTIONS parameter void readFormatOptions( QMap& formatOptions ) const; void readDxfLayerSettings( QList< QPair >& layers, const QMap& formatOptionsMap ) const; }; diff --git a/tests/src/analysis/testopenstreetmap.cpp b/tests/src/analysis/testopenstreetmap.cpp index 9a900d1a8320..a2e60a192246 100644 --- a/tests/src/analysis/testopenstreetmap.cpp +++ b/tests/src/analysis/testopenstreetmap.cpp @@ -31,7 +31,7 @@ class TestOpenStreetMap : public QObject void cleanupTestCase();// will be called after the last testfunction was executed. void init() ;// will be called before each testfunction is executed. void cleanup() ;// will be called after every testfunction. - /** Our tests proper begin here */ + //! Our tests proper begin here void download(); void importAndQueries(); private: diff --git a/tests/src/analysis/testqgsvectoranalyzer.cpp b/tests/src/analysis/testqgsvectoranalyzer.cpp index cfa309cb288b..eee865427952 100644 --- a/tests/src/analysis/testqgsvectoranalyzer.cpp +++ b/tests/src/analysis/testqgsvectoranalyzer.cpp @@ -36,7 +36,7 @@ class TestQgsVectorAnalyzer : public QObject void cleanupTestCase();// will be called after the last testfunction was executed. void init() ;// will be called before each testfunction is executed. void cleanup() ;// will be called after every testfunction. - /** Our tests proper begin here */ + //! Our tests proper begin here void singleToMulti(); void multiToSingle(); void extractNodes(); diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index 140dccd292b5..6bccf7f4ff5e 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -111,13 +111,13 @@ class TestQgsGeometry : public QObject void segmentizeCircularString(); private: - /** A helper method to do a render check to see if the geometry op is as expected */ + //! A helper method to do a render check to see if the geometry op is as expected bool renderCheck( const QString& theTestName, const QString& theComment = QLatin1String( QLatin1String( "" ) ), int mismatchCount = 0 ); - /** A helper method to dump to qdebug the geometry of a multipolygon */ + //! A helper method to dump to qdebug the geometry of a multipolygon void dumpMultiPolygon( QgsMultiPolygon &theMultiPolygon ); - /** A helper method to dump to qdebug the geometry of a polygon */ + //! A helper method to dump to qdebug the geometry of a polygon void dumpPolygon( QgsPolygon &thePolygon ); - /** A helper method to dump to qdebug the geometry of a polyline */ + //! A helper method to dump to qdebug the geometry of a polyline void dumpPolyline( QgsPolyline &thePolyline ); // Release return with delete [] diff --git a/tests/src/core/testqgsmaprendererjob.cpp b/tests/src/core/testqgsmaprendererjob.cpp index 1fe8166f48ba..d8f73dc3699a 100644 --- a/tests/src/core/testqgsmaprendererjob.cpp +++ b/tests/src/core/testqgsmaprendererjob.cpp @@ -69,7 +69,7 @@ class TestQgsMapRendererJob : public QObject void init() {} // will be called before each testfunction is executed. void cleanup() {} // will be called after every testfunction. - /** This method tests render perfomance */ + //! This method tests render perfomance void performanceTest(); /** This unit test checks if rendering of adjacent tiles (e.g. to render images for tile caches) diff --git a/tests/src/core/testqgsvectorfilewriter.cpp b/tests/src/core/testqgsvectorfilewriter.cpp index b0226bc9171c..580010e6e1de 100644 --- a/tests/src/core/testqgsvectorfilewriter.cpp +++ b/tests/src/core/testqgsvectorfilewriter.cpp @@ -67,17 +67,17 @@ class TestQgsVectorFileWriter: public QObject void cleanup() {} // will be called after every testfunction. void cleanupTestCase();// will be called after the last testfunction was executed. - /** This method tests writing a point to a shapefile */ + //! This method tests writing a point to a shapefile void createPoint(); - /** This method tests writing a polyline to a shapefile */ + //! This method tests writing a polyline to a shapefile void createLine(); - /** This method tests writing a polygon to a shapefile */ + //! This method tests writing a polygon to a shapefile void createPolygon(); - /** This method test writing multiple features to a shapefile */ + //! This method test writing multiple features to a shapefile void polygonGridTest(); - /** As above but using a projected CRS*/ + //! As above but using a projected CRS void projectedPlygonGridTest(); - /** This is a regression test ticket 1141 (broken Polish characters support since r8592) http://hub.qgis.org/issues/1141 */ + //! This is a regression test ticket 1141 (broken Polish characters support since r8592) http://hub.qgis.org/issues/1141 void regression1141(); private: From e75b572b6e08f141a927c62f710a67629a0dbe46 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 24 Oct 2016 08:27:22 +1000 Subject: [PATCH 467/897] [FEATURE] Remove dxf2shp converter plugin This functionality is available in OGR and there is no longer a need for a dedicated QGIS plugin to do this task Marked as feature for documentation + changelog reminder --- debian/copyright | 23 - debian/qgis.install | 1 - ms-windows/osgeo4w/package.cmd | 1 - ms-windows/plugins.nsh | 1 - rpm/qgis.spec.template | 3 - scripts/astyle.sh | 2 +- scripts/chkcopyrights.sh | 2 +- scripts/chkspelling.sh | 2 +- scripts/prepare-commit.sh | 2 +- scripts/sort_include.sh | 1 - scripts/verify-indentation.sh | 2 +- src/plugins/CMakeLists.txt | 1 - src/plugins/dxf2shp_converter/CMakeLists.txt | 57 - src/plugins/dxf2shp_converter/README | 27 - src/plugins/dxf2shp_converter/builder.cpp | 565 -- src/plugins/dxf2shp_converter/builder.h | 87 - .../dxf2shp_converter/dxf2shp_converter.png | Bin 805 -> 0 bytes .../dxf2shp_converter/dxf2shpconverter.cpp | 220 - .../dxf2shp_converter/dxf2shpconverter.h | 88 - .../dxf2shp_converter/dxf2shpconverter.qrc | 5 - .../dxf2shp_converter/dxf2shpconvertergui.cpp | 179 - .../dxf2shp_converter/dxf2shpconvertergui.h | 50 - .../dxf2shp_converter/dxf2shpconvertergui.ui | 158 - .../dxflib/src/dl_attributes.h | 237 - .../dxf2shp_converter/dxflib/src/dl_codes.h | 545 -- .../dxflib/src/dl_creationadapter.h | 137 - .../dxflib/src/dl_creationinterface.h | 366 -- .../dxf2shp_converter/dxflib/src/dl_dxf.cpp | 5239 ----------------- .../dxf2shp_converter/dxflib/src/dl_dxf.h | 510 -- .../dxflib/src/dl_entities.h | 1724 ------ .../dxflib/src/dl_extrusion.h | 144 - .../dxf2shp_converter/dxflib/src/dl_global.h | 38 - .../dxf2shp_converter/dxflib/src/dl_writer.h | 653 -- .../dxflib/src/dl_writer_ascii.cpp | 145 - .../dxflib/src/dl_writer_ascii.h | 74 - .../shapelib-1.2.10/LICENSE.LGPL | 483 -- .../shapelib-1.2.10/dbfopen.c | 1502 ----- .../shapelib-1.2.10/shapefil.h | 486 -- .../shapelib-1.2.10/shapelib.def | 42 - .../shapelib-1.2.10/shpopen.c | 1878 ------ .../shapelib-1.2.10/shprewind.c | 108 - 41 files changed, 5 insertions(+), 15783 deletions(-) delete mode 100644 src/plugins/dxf2shp_converter/CMakeLists.txt delete mode 100644 src/plugins/dxf2shp_converter/README delete mode 100644 src/plugins/dxf2shp_converter/builder.cpp delete mode 100644 src/plugins/dxf2shp_converter/builder.h delete mode 100644 src/plugins/dxf2shp_converter/dxf2shp_converter.png delete mode 100644 src/plugins/dxf2shp_converter/dxf2shpconverter.cpp delete mode 100644 src/plugins/dxf2shp_converter/dxf2shpconverter.h delete mode 100644 src/plugins/dxf2shp_converter/dxf2shpconverter.qrc delete mode 100644 src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp delete mode 100644 src/plugins/dxf2shp_converter/dxf2shpconvertergui.h delete mode 100644 src/plugins/dxf2shp_converter/dxf2shpconvertergui.ui delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_attributes.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_codes.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_creationadapter.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_creationinterface.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.cpp delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_extrusion.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_global.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_writer.h delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_writer_ascii.cpp delete mode 100644 src/plugins/dxf2shp_converter/dxflib/src/dl_writer_ascii.h delete mode 100644 src/plugins/dxf2shp_converter/shapelib-1.2.10/LICENSE.LGPL delete mode 100644 src/plugins/dxf2shp_converter/shapelib-1.2.10/dbfopen.c delete mode 100644 src/plugins/dxf2shp_converter/shapelib-1.2.10/shapefil.h delete mode 100644 src/plugins/dxf2shp_converter/shapelib-1.2.10/shapelib.def delete mode 100644 src/plugins/dxf2shp_converter/shapelib-1.2.10/shpopen.c delete mode 100644 src/plugins/dxf2shp_converter/shapelib-1.2.10/shprewind.c diff --git a/debian/copyright b/debian/copyright index 085800467251..8f5a7f40e2f9 100644 --- a/debian/copyright +++ b/debian/copyright @@ -320,29 +320,6 @@ Files: src/gui/symbology-ng/characterwidget.cpp Copyright: 2009, Nokia Corporation and/or its subsidiary(-ies) License: QT-Commercial or LGPL-2.1 with Digia Qt LGPL Exception 1.1 or GPL-3 -Files: src/plugins/dxf2shp_converter/builder.cpp - src/plugins/dxf2shp_converter/builder.h -Copyright: 1999, Frank Warmerdam -Comment: The code is heavily based on Christopher Michaelis' DXF to - Shapefile Converter (http://www.wanderingidea.com/content/view/12/25/), - released under GPL License - . - This code is based on two other products: - DXFLIB (http://www.ribbonsoft.com/dxflib.html) - This is a library for reading DXF files, also GPL. - SHAPELIB (http://shapelib.maptools.org/) - Used for the Shapefile functionality. -License: MIT - -Files: src/plugins/dxf2shp_converter/shapelib-1.2.10/* -Copyright: 1999, 2001-2002, Frank Warmerdam -License: MIT or LGPL-2+ - -Files: src/plugins/dxf2shp_converter/dxflib/src/* -Copyright: 2001-2013, RibbonSoft GmbH - 2001, Robert J. Campbell Jr -License: GPL-2+ or dxflib-Commercial-License - Files: src/plugins/evis/* Copyright: 2007, American Museum of Natural History License: LGPL-2+ diff --git a/debian/qgis.install b/debian/qgis.install index b4527055b62b..d3b7ed2d1667 100644 --- a/debian/qgis.install +++ b/debian/qgis.install @@ -1,6 +1,5 @@ usr/lib/qgis/plugins/libgeorefplugin.so usr/lib/qgis/plugins/libgpsimporterplugin.so -usr/lib/qgis/plugins/libdxf2shpconverterplugin.so usr/lib/qgis/plugins/libinterpolationplugin.so usr/lib/qgis/plugins/libcoordinatecaptureplugin.so usr/lib/qgis/plugins/liboracleplugin.so diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index 02957d0676da..cb198560e607 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -383,7 +383,6 @@ tar -C %OSGEO4W_ROOT% -cjf %ARCH%/release/qgis/%PACKAGENAME%/%PACKAGENAME%-%VERS "apps/%PACKAGENAME%/icons/" ^ "apps/%PACKAGENAME%/images/" ^ "apps/%PACKAGENAME%/plugins/coordinatecaptureplugin.dll" ^ - "apps/%PACKAGENAME%/plugins/dxf2shpconverterplugin.dll" ^ "apps/%PACKAGENAME%/plugins/evis.dll" ^ "apps/%PACKAGENAME%/plugins/georefplugin.dll" ^ "apps/%PACKAGENAME%/plugins/gpsimporterplugin.dll" ^ diff --git a/ms-windows/plugins.nsh b/ms-windows/plugins.nsh index f751da0d410e..ce4bc52abc24 100644 --- a/ms-windows/plugins.nsh +++ b/ms-windows/plugins.nsh @@ -9,7 +9,6 @@ WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "coordinatecaptureplugin" "true" WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "diagramoverlay" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "dxf2shpconverterplugin" "true" WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "evis" "true" WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "georefplugin" "true" WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "globeplugin" "false" diff --git a/rpm/qgis.spec.template b/rpm/qgis.spec.template index 5bb7bfa5c31c..f9dc2e35cd59 100644 --- a/rpm/qgis.spec.template +++ b/rpm/qgis.spec.template @@ -190,9 +190,6 @@ rm -rf src/core/gps/qextserialport/ rm -rf src/core/gps/qextserialport/ rm -rf "python/ext-libs/!(CMakeLists.txt|tests)" -rm -rf src/plugins/dxf2shp_converter/ -sed -i '/dxf2shp_converter/d' src/plugins/CMakeLists.txt - gzip ChangeLog diff --git a/scripts/astyle.sh b/scripts/astyle.sh index ac497689afe6..9de9aea0197a 100755 --- a/scripts/astyle.sh +++ b/scripts/astyle.sh @@ -71,7 +71,7 @@ astyleit() { for f in "$@"; do case "$f" in - src/app/gps/qwtpolar-*|src/core/gps/qextserialport/*|src/plugins/grass/qtermwidget/*|src/astyle/*|python/ext-libs/*|src/providers/spatialite/qspatialite/*|src/plugins/dxf2shp_converter/dxflib/src/*|src/plugins/globe/osgEarthQt/*|src/plugins/globe/osgEarthUtil/*|python/ext-libs/*|*/ui_*.py) + src/app/gps/qwtpolar-*|src/core/gps/qextserialport/*|src/plugins/grass/qtermwidget/*|src/astyle/*|python/ext-libs/*|src/providers/spatialite/qspatialite/*|src/plugins/globe/osgEarthQt/*|src/plugins/globe/osgEarthUtil/*|python/ext-libs/*|*/ui_*.py) echo -ne "$f skipped $elcr" continue ;; diff --git a/scripts/chkcopyrights.sh b/scripts/chkcopyrights.sh index 0b363e19b930..d54a10261b49 100755 --- a/scripts/chkcopyrights.sh +++ b/scripts/chkcopyrights.sh @@ -16,5 +16,5 @@ licensecheck -r . | - egrep -v "\/debian\/|.\/src\/plugins\/dxf2shp_converter\/dxflib|\.\/python\/ext-libs|\.\/ms-windows\/osgeo4w\/untgz\/|\.\/src\/app\/gps\/qwtpolar-|\.\/src\/app\/gps\/qwtpolar-1.0|: BSD \(3 clause\)|: GPL \(v[23] or later\)$|: LGPL \(v2 or later\)$|: MIT\/X11 \(BSD like\)$|: Apache \(v2\.0\) GPL \(v2 or later\)$|: LGPL$|: Apache \(v2\.0\)$|: zlib\/libpng$|: GPL LGPL$|GENERATED FILE" | + egrep -v "\/debian\/|\.\/python\/ext-libs|\.\/ms-windows\/osgeo4w\/untgz\/|\.\/src\/app\/gps\/qwtpolar-|\.\/src\/app\/gps\/qwtpolar-1.0|: BSD \(3 clause\)|: GPL \(v[23] or later\)$|: LGPL \(v2 or later\)$|: MIT\/X11 \(BSD like\)$|: Apache \(v2\.0\) GPL \(v2 or later\)$|: LGPL$|: Apache \(v2\.0\)$|: zlib\/libpng$|: GPL LGPL$|GENERATED FILE" | sed -e "s/:.*$//" diff --git a/scripts/chkspelling.sh b/scripts/chkspelling.sh index 7494694929a5..5b8cd79a0a71 100755 --- a/scripts/chkspelling.sh +++ b/scripts/chkspelling.sh @@ -17,6 +17,6 @@ RE=$(echo $(cut -d: -f1 scripts/spelling.dat | sed -e 's/^/\\|/;') | sed -e 's/| /|/g; s/|$//;') -EX="\.(svn-base|tmp|xpm|ts|o)|spelling\.dat|Exception_to_GPL_for_Qt.txt|sqlite3.c|qgisstyle|LexerR.py|debian/build.*|debian/.*/usr/|ms-windows/osgeo4w|ChangeLog|src/plugins/grass/qtermwidget|src/app/gps/qwtpolar-|debian/tmp|src/plugins/dxf2shp_converter/dxflib|python/ext-libs|i18n/" +EX="\.(svn-base|tmp|xpm|ts|o)|spelling\.dat|Exception_to_GPL_for_Qt.txt|sqlite3.c|qgisstyle|LexerR.py|debian/build.*|debian/.*/usr/|ms-windows/osgeo4w|ChangeLog|src/plugins/grass/qtermwidget|src/app/gps/qwtpolar-|python/ext-libs|i18n/" egrep --exclude=*.{png,svg,db,bz2,pdf,qgs,qml,api,pyc} --exclude-dir=.git --exclude-dir=debian/build* --color=always "$RE" -ir . | egrep -iv "$EX" diff --git a/scripts/prepare-commit.sh b/scripts/prepare-commit.sh index f06d9b33b2f2..22fc85bbd434 100755 --- a/scripts/prepare-commit.sh +++ b/scripts/prepare-commit.sh @@ -61,7 +61,7 @@ for f in $MODIFIED; do (( i++ )) || true case "$f" in - src/core/gps/qextserialport/*|src/plugins/dxf2shp_converter/dxflib/src/*|src/plugins/globe/osgEarthQt/*|src/plugins/globe/osgEarthUtil/*) + src/core/gps/qextserialport/*|src/plugins/globe/osgEarthQt/*|src/plugins/globe/osgEarthUtil/*) echo $f skipped continue ;; diff --git a/scripts/sort_include.sh b/scripts/sort_include.sh index 5ca6375c91db..fec7a8a39ad8 100755 --- a/scripts/sort_include.sh +++ b/scripts/sort_include.sh @@ -36,7 +36,6 @@ for file in $(find . \ ! -path "./src/astyle/*" \ ! -path "./python/ext-libs/*" \ ! -path "./src/providers/spatialite/qspatialite/*" \ - ! -path "./src/plugins/dxf2shp_converter/dxflib/src/*" \ ! -path "./src/plugins/globe/osgEarthQt/*" \ ! -path "./src/plugins/globe/osgEarthUtil/*" \ -regex "./src/\(.+/\)*.*\.\(h\|cpp\)" -type f \ diff --git a/scripts/verify-indentation.sh b/scripts/verify-indentation.sh index 02e184ec6ddd..02092bb5ef68 100755 --- a/scripts/verify-indentation.sh +++ b/scripts/verify-indentation.sh @@ -38,7 +38,7 @@ do echo "Checking $f" >>/tmp/ctest-important.log case "$f" in - src/core/gps/qextserialport/*|src/plugins/dxf2shp_converter/dxflib/src/*|src/plugins/globe/osgEarthQt/*|src/plugins/globe/osgEarthUtil/*|scripts/customwidget_template*) + src/core/gps/qextserialport/*|src/plugins/globe/osgEarthQt/*|src/plugins/globe/osgEarthUtil/*|scripts/customwidget_template*) echo "$f skipped" continue ;; diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt index fbfcec7e65c0..1259c5e1fbca 100644 --- a/src/plugins/CMakeLists.txt +++ b/src/plugins/CMakeLists.txt @@ -10,7 +10,6 @@ ADD_SUBDIRECTORY(interpolation) ADD_SUBDIRECTORY(oracle_raster) ADD_SUBDIRECTORY(raster_terrain_analysis) ADD_SUBDIRECTORY(coordinate_capture) -ADD_SUBDIRECTORY(dxf2shp_converter) ADD_SUBDIRECTORY(evis) ADD_SUBDIRECTORY(spatialquery) ADD_SUBDIRECTORY(roadgraph) diff --git a/src/plugins/dxf2shp_converter/CMakeLists.txt b/src/plugins/dxf2shp_converter/CMakeLists.txt deleted file mode 100644 index 6add09295077..000000000000 --- a/src/plugins/dxf2shp_converter/CMakeLists.txt +++ /dev/null @@ -1,57 +0,0 @@ - -######################################################## -# Files - -SET (dxf2shpconverter_SRCS - dxf2shpconverter.cpp - dxf2shpconvertergui.cpp - builder.cpp - dxflib/src/dl_dxf.cpp - dxflib/src/dl_writer_ascii.cpp - ) - -SET (dxf2shpconverter_UIS dxf2shpconvertergui.ui) - -SET (dxf2shpconverter_MOC_HDRS - dxf2shpconverter.h - dxf2shpconvertergui.h - ) - -SET (dxf2shpconverter_RCCS dxf2shpconverter.qrc) - -######################################################## -# Build - -QT5_WRAP_UI (dxf2shpconverter_UIS_H ${dxf2shpconverter_UIS}) - -QT5_WRAP_CPP (dxf2shpconverter_MOC_SRCS ${dxf2shpconverter_MOC_HDRS}) - -QT5_ADD_RESOURCES(dxf2shpconverter_RCC_SRCS ${dxf2shpconverter_RCCS}) - -ADD_LIBRARY (dxf2shpconverterplugin MODULE ${dxf2shpconverter_SRCS} ${dxf2shpconverter_MOC_SRCS} ${dxf2shpconverter_RCC_SRCS} ${dxf2shpconverter_UIS_H}) - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_BINARY_DIR} - ../../core - ../../core/geometry - ../../core/raster - ../../gui - .. -) -INCLUDE_DIRECTORIES(SYSTEM - ${PROJ_INCLUDE_DIR} -) - -TARGET_LINK_LIBRARIES(dxf2shpconverterplugin - qgis_core - qgis_gui -) - - -######################################################## -# Install - -INSTALL(TARGETS dxf2shpconverterplugin - RUNTIME DESTINATION ${QGIS_PLUGIN_DIR} - LIBRARY DESTINATION ${QGIS_PLUGIN_DIR}) - diff --git a/src/plugins/dxf2shp_converter/README b/src/plugins/dxf2shp_converter/README deleted file mode 100644 index bc53ceae3cdd..000000000000 --- a/src/plugins/dxf2shp_converter/README +++ /dev/null @@ -1,27 +0,0 @@ -/*************************************************************************** - *Copyright (C) 2008 Paolo L. Scala, Barbara Rita Barricelli, Marco Padula * - * CNR, Milan Unit (Information Technology), * - * Construction Technologies Institute.\n"; * - * * - * email : Paolo L. Scala * - * * - * This is a plugin generated from the QGIS plugin template * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ - DXF2SHP Plugin converter - -We've just developed and partially tested this plugin that converts a DXF file -into one or more vector layers in QGIS; it can also extract labels from the -DXF file and inserts the data (string, x, y, z, angle) in the dbf file of a new -point layer populated with points located where the labels should be rendered. -The purpose is to let Mapserver render them. - -The plugin uses shapelib and dxflib to convert and create the shp files. -For any suggestion or criticism, please contact us at: - -scala@itc.cnr.it -barricelli@itc.cnr.it diff --git a/src/plugins/dxf2shp_converter/builder.cpp b/src/plugins/dxf2shp_converter/builder.cpp deleted file mode 100644 index 611bfa0becc2..000000000000 --- a/src/plugins/dxf2shp_converter/builder.cpp +++ /dev/null @@ -1,565 +0,0 @@ -// The code is heavily based on Christopher Michaelis' DXF to Shapefile Converter -// (http://www.wanderingidea.com/content/view/12/25/), released under GPL License -// -// This code is based on two other products: -// DXFLIB (http://www.ribbonsoft.com/dxflib.html) -// This is a library for reading DXF files, also GPL. -// SHAPELIB (http://shapelib.maptools.org/) -// Used for the Shapefile functionality. -// It is Copyright (c) 1999, Frank Warmerdam, released under the following "MIT Style" license: -//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated -//documentation files (the "Software"), to deal in the Software without restriction, including without limitation -//the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -//and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -//LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -//IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#include "builder.h" - -#include -#include - -#include "qgslogger.h" - -Builder::Builder( const QString& theFname, - int theShapefileType, - bool theConvertText, - bool theConvertInserts ) - : fname( theFname ) - , shapefileType( theShapefileType ) - , convertText( theConvertText ) - , convertInserts( theConvertInserts ) - , ignoringBlock( false ) - , current_polyline_willclose( false ) - , store_next_vertex_for_polyline_close( false ) - , current_polyline_pointcount( 0 ) - , closePolyX( 0.0 ) - , closePolyY( 0.0 ) - , closePolyZ( 0.0 ) -{ -} - -Builder::~Builder() -{ -} - -void Builder::addBlock( const DL_BlockData& data ) -{ - Q_UNUSED( data ); - ignoringBlock = true; -} - -void Builder::endBlock() -{ - ignoringBlock = false; -} - -void Builder::addLayer( const DL_LayerData& data ) -{ - Q_UNUSED( data ); - QgsDebugMsg( QString( "Layer: %1" ).arg( data.name.c_str() ) ); -} - -void Builder::addPoint( const DL_PointData& data ) -{ - if ( shapefileType != SHPT_POINT ) - { - QgsDebugMsg( "ignoring point" ); - return; - } - - QgsDebugMsg( QString( "point (%1,%2,%3)" ).arg( data.x ).arg( data.y ).arg( data.z ) ); - - if ( ignoringBlock ) - { - QgsDebugMsg( "skipping point in block." ); - return; - } - - double x = data.x, y = data.y, z = data.z; - shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, nullptr, nullptr, 1, &x, &y, &z, nullptr ); -} - -void Builder::addLine( const DL_LineData& data ) -{ - //data.x1, data.y1, data.z1 - //data.x2, data.y2, data.z2 - - if ( shapefileType != SHPT_ARC ) - { - QgsDebugMsg( "ignoring line" ); - return; - } - - QgsDebugMsg( QString( "line %1,%2,%3 %4,%5,%6" ) - .arg( data.x1 ).arg( data.y1 ).arg( data.z1 ) - .arg( data.x2 ).arg( data.y2 ).arg( data.z2 ) ); - - if ( ignoringBlock ) - { - QgsDebugMsg( "skipping line in block." ); - return; - } - - - double xv[2] = { data.x1, data.x2 }; - double yv[2] = { data.y1, data.y2 }; - double zv[2] = { data.z1, data.z2 }; - - shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, nullptr, nullptr, 2, xv, yv, zv, nullptr ); -} - - -void Builder::addPolyline( const DL_PolylineData& data ) -{ - if ( shapefileType != SHPT_ARC && shapefileType != SHPT_POLYGON ) - { - QgsDebugMsg( "ignoring polyline" ); - return; - } - - QgsDebugMsg( "reading polyline - expecting vertices" ); - - if ( ignoringBlock ) - { - QgsDebugMsg( "skipping polyline in block" ); - return; - } - - // Add previously created polyline if not finalized yet - if ( current_polyline_pointcount > 0 ) - { - if ( current_polyline_willclose ) - { - - DL_VertexData myVertex; - - myVertex.x = closePolyX; - myVertex.y = closePolyY; - myVertex.z = closePolyZ; - - polyVertex.push_back( myVertex ); - - } - - int dim = polyVertex.size(); - QVector xv( dim ); - QVector yv( dim ); - QVector zv( dim ); - - for ( int i = 0; i < dim; i++ ) - { - xv[i] = polyVertex.at( i ).x; - yv[i] = polyVertex.at( i ).y; - zv[i] = polyVertex.at( i ).z; - } - - shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, nullptr, nullptr, dim, xv.data(), yv.data(), zv.data(), nullptr ); - - polyVertex.clear(); - - QgsDebugMsg( QString( "polyline prepared: %1" ).arg( shpObjects.size() - 1 ) ); - current_polyline_pointcount = 0; - } - - // Now that the currently-adding polyline (if any) is - // finalized, parse out the flag options - - if ( data.flags == 1 || data.flags == 32 ) - { - current_polyline_willclose = true; - store_next_vertex_for_polyline_close = true; - } - else - { - current_polyline_willclose = false; - store_next_vertex_for_polyline_close = false; - } - - current_polyline_pointcount = 0; - -} - - -void Builder::addVertex( const DL_VertexData& data ) -{ - if ( shapefileType != SHPT_ARC && shapefileType != SHPT_POLYGON ) - { - QgsDebugMsg( "ignoring vertex" ); - return; - } - - QgsDebugMsg( QString( "vertex (%1,%2,%3)" ).arg( data.x ).arg( data.y ).arg( data.z ) ); - - if ( ignoringBlock ) - { - QgsDebugMsg( "skipping vertex in block" ); - return; - } - - polyVertex << DL_VertexData( data.x, data.y, data.z ); - - current_polyline_pointcount++; - - if ( store_next_vertex_for_polyline_close ) - { - store_next_vertex_for_polyline_close = false; - closePolyX = data.x; - closePolyY = data.y; - closePolyZ = data.z; - } -} - - -void Builder::endSequence() -{ - QgsDebugMsg( "endSequence" ); -} - -void Builder::addArc( const DL_ArcData& data ) -{ - if ( shapefileType != SHPT_ARC ) - { - QgsDebugMsg( "ignoring arc" ); - return; - } - - int fromAngle = static_cast< int >( data.angle1 ) + 1; - int toAngle = static_cast< int >( data.angle2 ) + 1; - - QgsDebugMsg( QString( "arc (%1,%2,%3 r=%4 a1=%5 a2=%6)" ) - .arg( data.cx ).arg( data.cy ).arg( data.cz ) - .arg( data.radius ) - .arg( data.angle1 ).arg( data.angle2 ) ); - - if ( ignoringBlock ) - { - QgsDebugMsg( "skipping arc in block" ); - return; - } - - int i = 0; - long shpIndex = 0; - - // Approximate the arc - - double radianMeasure; - - std::vector arcPoints; - DL_PointData myPoint; - - for ( i = fromAngle; ; i++, shpIndex++ ) - { - if ( i > 360 ) - i = 0; - - if ( shpIndex > 1000 ) - break; - - radianMeasure = i * M_PI / 180.0; - - myPoint.x = data.radius * cos( radianMeasure ) + data.cx; - myPoint.y = data.radius * sin( radianMeasure ) + data.cy; - myPoint.z = data.cz; - - arcPoints.push_back( myPoint ); - - if ( i == toAngle ) - break; - } - - // Finalize - - int dim = static_cast< int >( arcPoints.size() ); - QVector xv( dim ); - QVector yv( dim ); - QVector zv( dim ); - - for ( int i = 0; i < dim; i++ ) - { - xv[i] = arcPoints[i].x; - yv[i] = arcPoints[i].y; - zv[i] = arcPoints[i].z; - - } - - shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, nullptr, nullptr, dim, xv.data(), yv.data(), zv.data(), nullptr ); - arcPoints.clear(); -} - - -void Builder::addCircle( const DL_CircleData& data ) -{ - if ( shapefileType != SHPT_ARC && shapefileType != SHPT_POLYGON ) - { - QgsDebugMsg( "ignoring circle" ); - return; - } - - QgsDebugMsg( QString( "circle (%1,%2,%3 r=%4)" ).arg( data.cx ).arg( data.cy ).arg( data.cz ).arg( data.radius ) ); - - if ( ignoringBlock ) - { - QgsDebugMsg( "skipping circle in block" ); - return; - } - - - std::vector circlePoints; - DL_PointData myPoint; - - // Approximate the circle with 360 line segments connecting points along that circle - long shpIndex = 0; - for ( double i = 0.0; i <= 2*M_PI; i += M_PI / 180.0, shpIndex++ ) - { - myPoint.x = data.radius * cos( i ) + data.cx; - myPoint.y = data.radius * sin( i ) + data.cy; - myPoint.z = data.cz; - - circlePoints.push_back( myPoint ); - } - - int dim = static_cast< int >( circlePoints.size() ); - QVector xv( dim ); - QVector yv( dim ); - QVector zv( dim ); - - for ( int i = 0; i < dim; i++ ) - { - xv[i] = circlePoints[i].x; - yv[i] = circlePoints[i].y; - zv[i] = circlePoints[i].z; - } - - shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, nullptr, nullptr, dim, xv.data(), yv.data(), zv.data(), nullptr ); - - circlePoints.clear(); -} - -void Builder::addInsert( const DL_InsertData& data ) -{ - if ( !convertInserts ) - return; - - insertObjects << DL_InsertData( - data.name, - data.ipx, data.ipy, data.ipz, - data.sx, data.sy, data.sz, - data.angle, - data.cols, data.rows, - data.colSp, data.rowSp - ); -} - -void Builder::addText( const DL_TextData &data ) -{ - if ( !convertText ) - return; - - textObjects << DL_TextData( - data.ipx, data.ipy, data.ipz, - data.apx, data.apy, data.apz, - data.height, data.xScaleFactor, data.textGenerationFlags, - data.hJustification, data.vJustification, - data.text, data.style, data.angle - ); - - QgsDebugMsg( QString( "text: %1" ).arg( data.text.c_str() ) ); -} - -void Builder::FinalizeAnyPolyline() -{ - // Save the last polyline / polygon if one exists. - if ( current_polyline_pointcount > 0 ) - { - if ( current_polyline_willclose ) - { - polyVertex << DL_VertexData( closePolyX, closePolyY, closePolyZ ); - } - - int dim = polyVertex.size(); - QVector xv( dim ); - QVector yv( dim ); - QVector zv( dim ); - - for ( int i = 0; i < dim; i++ ) - { - xv[i] = polyVertex.at( i ).x; - yv[i] = polyVertex.at( i ).y; - zv[i] = polyVertex.at( i ).z; - } - - shpObjects << SHPCreateObject( shapefileType, shpObjects.size(), 0, nullptr, nullptr, dim, xv.data(), yv.data(), zv.data(), nullptr ); - polyVertex.clear(); - - QgsDebugMsg( QString( "Finalized adding of polyline shape %1" ).arg( shpObjects.size() - 1 ) ); - current_polyline_pointcount = 0; - } -} - -void Builder::print_shpObjects() -{ - QgsDebugMsg( QString( "Number of primitives: %1" ).arg( shpObjects.size() ) ); - QgsDebugMsg( QString( "Number of text fields: %1" ).arg( textObjects.size() ) ); - QgsDebugMsg( QString( "Number of inserts fields: %1" ).arg( insertObjects.size() ) ); - - SHPHandle hSHP; - - if ( fname.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) - { - QString fn( fname.mid( fname.length() - 4 ) ); - - outputdbf = fn + ".dbf"; - outputshp = fn + ".shp"; - outputtdbf = fn + "_texts.dbf"; - outputtshp = fn + "_texts.shp"; - outputidbf = fn + "_inserts.dbf"; - outputishp = fn + "_inserts.shp"; - } - else - { - outputdbf = outputtdbf = outputidbf = fname + ".dbf"; - outputshp = outputtshp = outputishp = fname + ".shp"; - } - - DBFHandle dbffile = DBFCreate( outputdbf.toUtf8() ); - DBFAddField( dbffile, "myid", FTInteger, 10, 0 ); - - hSHP = SHPCreate( outputshp.toUtf8(), shapefileType ); - - QgsDebugMsg( "Writing to main shp file..." ); - - for ( int i = 0; i < shpObjects.size(); i++ ) - { - SHPWriteObject( hSHP, -1, shpObjects.at( i ) ); - SHPDestroyObject( shpObjects.at( i ) ); - DBFWriteIntegerAttribute( dbffile, i, 0, i ); - } - - SHPClose( hSHP ); - DBFClose( dbffile ); - - QgsDebugMsg( "Done!" ); - - if ( !textObjects.isEmpty() ) - { - SHPHandle thSHP; - - DBFHandle Tdbffile = DBFCreate( outputtdbf.toUtf8() ); - thSHP = SHPCreate( outputtshp.toUtf8(), SHPT_POINT ); - - DBFAddField( Tdbffile, "tipx", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "tipy", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "tipz", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "tapx", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "tapy", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "tapz", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "height", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "scale", FTDouble, 20, 10 ); - DBFAddField( Tdbffile, "flags", FTInteger, 10, 0 ); - DBFAddField( Tdbffile, "hjust", FTInteger, 10, 0 ); - DBFAddField( Tdbffile, "vjust", FTInteger, 10, 0 ); - DBFAddField( Tdbffile, "text", FTString, 50, 0 ); - DBFAddField( Tdbffile, "style", FTString, 50, 0 ); - DBFAddField( Tdbffile, "angle", FTDouble, 20, 10 ); - - QgsDebugMsg( "Writing Texts' shp File..." ); - - for ( int i = 0; i < textObjects.size(); i++ ) - { - SHPObject *psObject; - double x = textObjects.at( i ).ipx; - double y = textObjects.at( i ).ipy; - double z = textObjects.at( i ).ipz; - psObject = SHPCreateObject( SHPT_POINT, i, 0, nullptr, nullptr, 1, &x, &y, &z, nullptr ); - - SHPWriteObject( thSHP, -1, psObject ); - - DBFWriteDoubleAttribute( Tdbffile, i, 0, textObjects.at( i ).ipx ); - DBFWriteDoubleAttribute( Tdbffile, i, 1, textObjects.at( i ).ipy ); - DBFWriteDoubleAttribute( Tdbffile, i, 2, textObjects.at( i ).ipz ); - - DBFWriteDoubleAttribute( Tdbffile, i, 3, textObjects.at( i ).apx ); - DBFWriteDoubleAttribute( Tdbffile, i, 4, textObjects.at( i ).apy ); - DBFWriteDoubleAttribute( Tdbffile, i, 5, textObjects.at( i ).apz ); - - DBFWriteDoubleAttribute( Tdbffile, i, 6, textObjects.at( i ).height ); - DBFWriteDoubleAttribute( Tdbffile, i, 7, textObjects.at( i ).xScaleFactor ); - DBFWriteIntegerAttribute( Tdbffile, i, 8, textObjects.at( i ).textGenerationFlags ); - - DBFWriteIntegerAttribute( Tdbffile, i, 9, textObjects.at( i ).hJustification ); - DBFWriteIntegerAttribute( Tdbffile, i, 10, textObjects.at( i ).vJustification ); - - DBFWriteStringAttribute( Tdbffile, i, 11, textObjects.at( i ).text.c_str() ); - DBFWriteStringAttribute( Tdbffile, i, 12, textObjects.at( i ).style.c_str() ); - - DBFWriteDoubleAttribute( Tdbffile, i, 13, textObjects.at( i ).angle ); - - SHPDestroyObject( psObject ); - } - SHPClose( thSHP ); - DBFClose( Tdbffile ); - - QgsDebugMsg( "Done!" ); - } - - if ( !insertObjects.isEmpty() ) - { - SHPHandle ihSHP; - - DBFHandle Idbffile = DBFCreate( outputidbf.toUtf8() ); - ihSHP = SHPCreate( outputishp.toUtf8(), SHPT_POINT ); - - DBFAddField( Idbffile, "name", FTString, 200, 0 ); - DBFAddField( Idbffile, "ipx", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "ipy", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "ipz", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "sx", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "sy", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "sz", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "angle", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "cols", FTInteger, 20, 0 ); - DBFAddField( Idbffile, "rows", FTInteger, 20, 0 ); - DBFAddField( Idbffile, "colsp", FTDouble, 20, 10 ); - DBFAddField( Idbffile, "rowsp", FTDouble, 20, 10 ); - - QgsDebugMsg( "Writing Insert' shp File..." ); - - for ( int i = 0; i < insertObjects.size(); i++ ) - { - SHPObject *psObject; - double &x = insertObjects[i].ipx; - double &y = insertObjects[i].ipy; - double &z = insertObjects[i].ipz; - psObject = SHPCreateObject( SHPT_POINT, i, 0, nullptr, nullptr, 1, &x, &y, &z, nullptr ); - - SHPWriteObject( ihSHP, -1, psObject ); - - int c = 0; - DBFWriteStringAttribute( Idbffile, i, c++, insertObjects.at( i ).name.c_str() ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).ipx ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).ipy ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).ipz ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).sx ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).sy ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).sz ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).angle ); - DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects.at( i ).cols ); - DBFWriteIntegerAttribute( Idbffile, i, c++, insertObjects.at( i ).rows ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).colSp ); - DBFWriteDoubleAttribute( Idbffile, i, c++, insertObjects.at( i ).rowSp ); - - SHPDestroyObject( psObject ); - } - SHPClose( ihSHP ); - DBFClose( Idbffile ); - - QgsDebugMsg( "Done!" ); - } -} diff --git a/src/plugins/dxf2shp_converter/builder.h b/src/plugins/dxf2shp_converter/builder.h deleted file mode 100644 index b351c84f0cd0..000000000000 --- a/src/plugins/dxf2shp_converter/builder.h +++ /dev/null @@ -1,87 +0,0 @@ -// The code is heavily based on Christopher Michaelis' DXF to Shapefile Converter -// (http://www.wanderingidea.com/content/view/12/25/), released under GPL License -// -// This code is based on two other products: -// DXFLIB (http://www.ribbonsoft.com/dxflib.html) -// This is a library for reading DXF files, also GPL. -// SHAPELIB (http://shapelib.maptools.org/) -// Used for the Shapefile functionality. -// It is Copyright (c) 1999, Frank Warmerdam, released under the following "MIT Style" license: -//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated -//documentation files (the "Software"), to deal in the Software without restriction, including without limitation -//the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -//and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -//LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -//IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -#include "dxflib/src/dl_creationadapter.h" -#include "shapelib-1.2.10/shapefil.h" - -#include -#include - - -class Builder: public DL_CreationAdapter -{ - public: - Builder( const QString& theFname, int theShapefileType, bool theConvertText, bool theConvertInserts ); - ~Builder(); - - void FinalizeAnyPolyline(); - - virtual void addLayer( const DL_LayerData &data ) override; - virtual void addPoint( const DL_PointData &data ) override; - virtual void addLine( const DL_LineData &data ) override; - virtual void addInsert( const DL_InsertData &data ) override; - virtual void addPolyline( const DL_PolylineData &data ) override; - virtual void addArc( const DL_ArcData &data ) override; - virtual void addCircle( const DL_CircleData &data ) override; - virtual void addVertex( const DL_VertexData &data ) override; - virtual void addBlock( const DL_BlockData &data ) override; - virtual void endBlock() override; - virtual void endSequence() override; - virtual void addText( const DL_TextData &data ) override; - - void print_shpObjects(); - - int textObjectsSize() const { return textObjects.size(); } - int insertObjectsSize() const { return insertObjects.size(); } - QString outputShp() const { return outputshp; } - QString outputTShp() const { return outputtshp; } - QString outputIShp() const { return outputishp; } - - private: - QString fname; - int shapefileType; // SHPT_POINT, ... - bool convertText; - bool convertInserts; - - QString outputdbf; - QString outputshp; - - QString outputtdbf; - QString outputtshp; - - QString outputidbf; - QString outputishp; - - QList shpObjects; // all read objects are stored here - - QList polyVertex; - QList textObjects; - QList insertObjects; - - bool ignoringBlock; - bool current_polyline_willclose; - bool store_next_vertex_for_polyline_close; - - long current_polyline_pointcount; - - double closePolyX, closePolyY, closePolyZ; -}; diff --git a/src/plugins/dxf2shp_converter/dxf2shp_converter.png b/src/plugins/dxf2shp_converter/dxf2shp_converter.png deleted file mode 100644 index 1e6330122ab4a1f7e156efbf37370fa2d24f297a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 805 zcmV+=1KRwFP)jR4)iw6*qD6h(6@E~=7BEl_GiM6`$;6%if7>Q*X% zr8gfd7K>$IEcUAkm z6!7C>v3U8v0KXIj!4|D`+4H>PlarGle#P_oe1|b+#`pbf7={aJfSM!HTHgkqRc{Uu z`)6@JRf&Kg2t44D@B4R>@^So9T=(w)t@S?OV;F|>N%=VbF|J!tnWUhI906X}TGTmk z^<<`L$99YN?%4T4a*eRtZ|^{L z{7(-0LWcX5)M5-k-Hc_jj;oR~rC@ z_z57^q+fRZ{r%ggrlvks`!8#E&H;p@Lj*VO;(3a~`7;2FPn0mm{$8JYT~}|OU8z{WTkxeZW%Juw{ j|B}TGB9zlMx46Nd`nm`niGnON00000NkvXXu0mjfT)Jei diff --git a/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp b/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp deleted file mode 100644 index cc69f8cd2381..000000000000 --- a/src/plugins/dxf2shp_converter/dxf2shpconverter.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/*************************************************************************** - *Copyright (C) 2008 Paolo L. Scala, Barbara Rita Barricelli, Marco Padula * - * CNR, Milan Unit (Information Technology), * - * Construction Technologies Institute.\n"; * - * * - * email : Paolo L. Scala * - * * - * This is a plugin generated from the QGIS plugin template * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ - -// -// QGIS Specific includes -// - -#include -#include -#include -#include - -#include "dxf2shpconverter.h" -#include "dxf2shpconvertergui.h" - -// -// Qt4 Related Includes -// - -#include -#include -#include - -static const QString sName = QObject::tr( "Dxf2Shp Converter" ); -static const QString sDescription = QObject::tr( "Converts from dxf to shp file format" ); -static const QString sCategory = QObject::tr( "Vector" ); -static const QString sPluginVersion = QObject::tr( "Version 0.1" ); -static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = QStringLiteral( ":/dxf2shp_converter.png" ); - -////////////////////////////////////////////////////////////////////// -// -// THE FOLLOWING METHODS ARE MANDATORY FOR ALL PLUGINS -// -////////////////////////////////////////////////////////////////////// - -/** - * Constructor for the plugin. The plugin is passed a pointer - * an interface object that provides access to exposed functions in QGIS. - * @param theQGisInterface - Pointer to the QGIS interface object - */ -dxf2shpConverter::dxf2shpConverter( QgisInterface *theQgisInterface ) - : QgisPlugin( sName, sDescription, sCategory, sPluginVersion, sPluginType ) - , mQGisIface( theQgisInterface ) - , mQActionPointer( nullptr ) -{} - -dxf2shpConverter::~dxf2shpConverter() -{ - -} - -/* - * Initialize the GUI interface for the plugin - this is only called once when the plugin is - * added to the plugin registry in the QGIS application. - */ -void dxf2shpConverter::initGui() -{ - // Create the action for tool - delete mQActionPointer; - mQActionPointer = new QAction( QIcon(), QStringLiteral( "Dxf2Shp Converter" ), this ); - mQActionPointer->setObjectName( QStringLiteral( "mQActionPointer" ) ); - - // Set the icon - setCurrentTheme( QLatin1String( "" ) ); - - // Set the what's this text - mQActionPointer->setWhatsThis( tr( "Converts DXF files in Shapefile format" ) ); - - // Connect the action to the run - connect( mQActionPointer, SIGNAL( triggered() ), this, SLOT( run() ) ); - - // Add the icon to the toolbar - mQGisIface->addVectorToolBarIcon( mQActionPointer ); - mQGisIface->addPluginToVectorMenu( tr( "&Dxf2Shp" ), mQActionPointer ); - - // this is called when the icon theme is changed - connect( mQGisIface, SIGNAL( currentThemeChanged( QString ) ), this, SLOT( setCurrentTheme( QString ) ) ); -} - -//method defined in interface -void dxf2shpConverter::help() -{ - //implement me! -} - -// Slot called when the menu item is activated -// If you created more menu items / toolbar buttons in initiGui, you should -// create a separate handler for each action - this single run() method will -// not be enough -void dxf2shpConverter::run() -{ - dxf2shpConverterGui *myPluginGui = - new dxf2shpConverterGui( mQGisIface->mainWindow(), QgisGui::ModalDialogFlags ); - - myPluginGui->setAttribute( Qt::WA_DeleteOnClose ); - - connect( myPluginGui, SIGNAL( createLayer( QString, QString ) ), this, SLOT( addMyLayer( QString, QString ) ) ); - - myPluginGui->show(); -} - -// Unload the plugin by cleaning up the GUI -void dxf2shpConverter::unload() -{ - // remove the GUI - mQGisIface->removePluginVectorMenu( tr( "&Dxf2Shp" ), mQActionPointer ); - mQGisIface->removeVectorToolBarIcon( mQActionPointer ); - delete mQActionPointer; - mQActionPointer = nullptr; -} - -void dxf2shpConverter::addMyLayer( const QString& myfname, const QString& mytitle ) -{ - mQGisIface->addVectorLayer( myfname, mytitle, QStringLiteral( "ogr" ) ); -} - -//! Set icons to the current theme -void dxf2shpConverter::setCurrentTheme( const QString& theThemeName ) -{ - Q_UNUSED( theThemeName ); - QString myCurThemePath = QgsApplication::activeThemePath() + "/plugins/dxf2shp_converter.png"; - QString myDefThemePath = QgsApplication::defaultThemePath() + "/plugins/dxf2shp_converter.png"; - QString myQrcPath = QStringLiteral( ":/dxf2shp_converter.png" ); - if ( mQActionPointer ) - { - if ( QFile::exists( myCurThemePath ) ) - { - mQActionPointer->setIcon( QIcon( myCurThemePath ) ); - } - else if ( QFile::exists( myDefThemePath ) ) - { - mQActionPointer->setIcon( QIcon( myDefThemePath ) ); - } - else if ( QFile::exists( myQrcPath ) ) - { - mQActionPointer->setIcon( QIcon( myQrcPath ) ); - } - else - { - mQActionPointer->setIcon( QIcon() ); - } - } -} - -////////////////////////////////////////////////////////////////////////// -// -// -// THE FOLLOWING CODE IS AUTOGENERATED BY THE PLUGIN BUILDER SCRIPT -// YOU WOULD NORMALLY NOT NEED TO MODIFY THIS, AND YOUR PLUGIN -// MAY NOT WORK PROPERLY IF YOU MODIFY THIS INCORRECTLY -// -// -////////////////////////////////////////////////////////////////////////// - - -/** - * Required extern functions needed for every plugin - * These functions can be called prior to creating an instance - * of the plugin class - */ -// Class factory to return a new instance of the plugin class -QGISEXTERN QgisPlugin *classFactory( QgisInterface *theQgisInterfacePointer ) -{ - return new dxf2shpConverter( theQgisInterfacePointer ); -} - -// Return the name of the plugin - note that we do not user class members as -// the class may not yet be insantiated when this method is called. -QGISEXTERN QString name() -{ - return sName; -} - -// Return the description -QGISEXTERN QString description() -{ - return sDescription; -} - -// Return the category -QGISEXTERN QString category() -{ - return sCategory; -} - -// Return the type (either UI or MapLayer plugin) -QGISEXTERN int type() -{ - return sPluginType; -} - -// Return the version number for the plugin -QGISEXTERN QString version() -{ - return sPluginVersion; -} - -QGISEXTERN QString icon() -{ - return sPluginIcon; -} - -// Delete ourself -QGISEXTERN void unload( QgisPlugin *thePluginPointer ) -{ - delete thePluginPointer; -} diff --git a/src/plugins/dxf2shp_converter/dxf2shpconverter.h b/src/plugins/dxf2shp_converter/dxf2shpconverter.h deleted file mode 100644 index 67e90eedfbee..000000000000 --- a/src/plugins/dxf2shp_converter/dxf2shpconverter.h +++ /dev/null @@ -1,88 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2008 Paolo L. Scala, Barbara Rita Barricelli, Marco Padula * - * CNR, Milan Unit (Information Technology), * - * Construction Technologies Institute.\n"; * - * * - * email : Paolo L. Scala * - * * - * This is a plugin generated from the QGIS plugin template * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - * **************************************************************************/ -#ifndef dxf2shpConverter_H -#define dxf2shpConverter_H - -//QT4 includes -#include - -//QGIS includes -#include "../qgisplugin.h" - -//forward declarations -class QAction; - -class QgisInterface; - -/** - * \class dxf2shpConverter: - * \brief DXF importer plugin for QGIS - */ -class dxf2shpConverter: public QObject, public QgisPlugin -{ - Q_OBJECT - public: - - ////////////////////////////////////////////////////////////////////// - // - // MANDATORY PLUGIN METHODS FOLLOW - // - ////////////////////////////////////////////////////////////////////// - - /** - * Constructor for a plugin. The QgisInterface pointer is passed by - * QGIS when it attempts to instantiate the plugin. - * @param theInterface Pointer to the QgisInterface object. - */ - explicit dxf2shpConverter( QgisInterface *theInterface ); - //! Destructor - virtual ~dxf2shpConverter(); - - public slots: - //! init the gui - virtual void initGui() override; - //! Show the dialog box - void run(); - //! unload the plugin - void unload() override; - //! show the help document - void help(); - //! update the plugins theme when the app tells us its theme is changed - void setCurrentTheme( const QString& theThemeName ); - - void addMyLayer( const QString&, const QString& ); - - private: - - //////////////////////////////////////////////////////////////////// - // - // MANDATORY PLUGIN PROPERTY DECLARATIONS ..... - // - //////////////////////////////////////////////////////////////////// - - //! Pointer to the QGIS interface object - QgisInterface *mQGisIface; - //!pointer to the qaction for this plugin - QAction *mQActionPointer; - //////////////////////////////////////////////////////////////////// - // - // ADD YOUR OWN PROPERTY DECLARATIONS AFTER THIS POINT..... - // - //////////////////////////////////////////////////////////////////// - QString mQString; -}; - -#endif //dxf2shpConverter_H diff --git a/src/plugins/dxf2shp_converter/dxf2shpconverter.qrc b/src/plugins/dxf2shp_converter/dxf2shpconverter.qrc deleted file mode 100644 index 2680a8b200e8..000000000000 --- a/src/plugins/dxf2shp_converter/dxf2shpconverter.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - dxf2shp_converter.png - - diff --git a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp b/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp deleted file mode 100644 index 988b974ceabf..000000000000 --- a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/*************************************************************************** - *Copyright (C) 2008 Paolo L. Scala, Barbara Rita Barricelli, Marco Padula * - * CNR, Milan Unit (Information Technology), * - * Construction Technologies Institute.\n"; * - * * - * email : Paolo L. Scala * - * * - * This is a plugin generated from the QGIS plugin template * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ -#include "dxf2shpconvertergui.h" -#include "qgscontexthelp.h" - -#include "builder.h" -#include "dxflib/src/dl_dxf.h" - -//qt includes -#include -#include -#include -#include -#include - -#include "qgslogger.h" - -dxf2shpConverterGui::dxf2shpConverterGui( QWidget *parent, Qt::WindowFlags fl ): - QDialog( parent, fl ) -{ - setupUi( this ); - restoreState(); -} - -dxf2shpConverterGui::~dxf2shpConverterGui() -{ - QSettings settings; - settings.setValue( QStringLiteral( "/Plugin-DXF/geometry" ), saveGeometry() ); -} - -void dxf2shpConverterGui::on_buttonBox_accepted() -{ - QString inf = name->text(); - QString outd = dirout->text(); - - if ( inf.isEmpty() ) - { - QMessageBox::information( this, tr( "Warning" ), tr( "Please specify a file to convert." ) ); - return; - } - - if ( outd.isEmpty() ) - { - QMessageBox::information( this, tr( "Warning" ), tr( "Please specify an output file" ) ); - return; - } - - QApplication::setOverrideCursor( Qt::BusyCursor ); - - int type = SHPT_POINT; - - if ( polyline->isChecked() ) - type = SHPT_ARC; - - if ( polygon->isChecked() ) - type = SHPT_POLYGON; - - if ( point->isChecked() ) - type = SHPT_POINT; - - Builder *parser = new Builder( outd, type, convertTextCheck->isChecked(), convertInsertCheck->isChecked() ); - - DL_Dxf *dxf_Main = new DL_Dxf(); - - if ( !dxf_Main->in( inf.toStdString(), parser ) ) - { - // if file open failed - delete dxf_Main; - QgsDebugMsg( "Aborting: The input file could not be opened." ); - QApplication::restoreOverrideCursor(); - return; - } - - delete dxf_Main; - - parser->print_shpObjects(); - - emit createLayer( parser->outputShp(), QStringLiteral( "Data layer" ) ); - - if ( convertTextCheck->isChecked() && parser->textObjectsSize() > 0 ) - { - emit createLayer( parser->outputTShp(), QStringLiteral( "Text layer" ) ); - } - - if ( convertInsertCheck->isChecked() && parser->insertObjectsSize() > 0 ) - { - emit createLayer( parser->outputIShp(), QStringLiteral( "Insert layer" ) ); - } - - delete parser; - - QApplication::restoreOverrideCursor(); - - accept(); -} - -void dxf2shpConverterGui::on_buttonBox_rejected() -{ - reject(); -} - -void dxf2shpConverterGui::on_buttonBox_helpRequested() -{ - QString s = tr( "Fields description:\n" - "* Input DXF file: path to the DXF file to be converted\n" - "* Output Shp file: desired name of the shape file to be created\n" - "* Shp output file type: specifies the type of the output shape file\n" - "* Export text labels checkbox: if checked, an additional shp points layer will be created, " - "and the associated dbf table will contain information about the \"TEXT\" fields found" - " in the dxf file, and the text strings themselves\n\n" - "---\n" - "Developed by Paolo L. Scala, Barbara Rita Barricelli, Marco Padula\n" - "CNR, Milan Unit (Information Technology), Construction Technologies Institute.\n" - "For support send a mail to scala@itc.cnr.it\n" ); - - QMessageBox::information( this, QStringLiteral( "Help" ), s ); -} - -void dxf2shpConverterGui::on_btnBrowseForFile_clicked() -{ - getInputFileName(); -} - -void dxf2shpConverterGui::on_btnBrowseOutputDir_clicked() -{ - getOutputDir(); -} - -void dxf2shpConverterGui::getInputFileName() -{ - QSettings settings; - QString s = QFileDialog::getOpenFileName( this, - tr( "Choose a DXF file to open" ), - settings.value( QStringLiteral( "/Plugin-DXF/text_path" ), QDir::homePath() ).toString(), - tr( "DXF files" ) + " (*.dxf)" ); - - if ( !s.isEmpty() ) - { - name->setText( s ); - settings.setValue( QStringLiteral( "/Plugin-DXF/text_path" ), QFileInfo( s ).absolutePath() ); - } -} - -void dxf2shpConverterGui::getOutputDir() -{ - QSettings settings; - QString s = QFileDialog::getSaveFileName( this, - tr( "Choose a file name to save to" ), - settings.value( QStringLiteral( "/UI/lastShapefileDir" ), QDir::homePath() ).toString(), - tr( "Shapefile" ) + " (*.shp)" ); - - if ( !s.isEmpty() ) - { - if ( !s.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) ) - { - s += QLatin1String( ".shp" ); - } - dirout->setText( s ); - settings.setValue( QStringLiteral( "/UI/lastShapefileDir" ), QFileInfo( s ).absolutePath() ); - } -} - -void dxf2shpConverterGui::restoreState() -{ - QSettings settings; - restoreGeometry( settings.value( QStringLiteral( "/Plugin-DXF/geometry" ) ).toByteArray() ); -} diff --git a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.h b/src/plugins/dxf2shp_converter/dxf2shpconvertergui.h deleted file mode 100644 index 318b258a11da..000000000000 --- a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.h +++ /dev/null @@ -1,50 +0,0 @@ -/*************************************************************************** - *Copyright (C) 2008 Paolo L. Scala, Barbara Rita Barricelli, Marco Padula * - * CNR, Milan Unit (Information Technology), * - * Construction Technologies Institute.\n"; * - * * - * email : Paolo L. Scala * - * * - * This is a plugin generated from the QGIS plugin template * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ -#ifndef dxf2shpConverterGUI_H -#define dxf2shpConverterGUI_H - -#include -#include - -/** - @author Tim Sutton - */ -class dxf2shpConverterGui: public QDialog, private Ui::dxf2shpConverterGui -{ - Q_OBJECT - - public: - dxf2shpConverterGui( QWidget *parent = nullptr, Qt::WindowFlags fl = 0 ); - ~dxf2shpConverterGui(); - - private: - void getInputFileName(); - void getOutputFileName(); - void getOutputDir(); - - void restoreState(); - - private slots: - void on_buttonBox_accepted(); - void on_buttonBox_rejected(); - void on_buttonBox_helpRequested(); - void on_btnBrowseForFile_clicked(); - void on_btnBrowseOutputDir_clicked(); - - signals: - void createLayer( const QString&, const QString& ); -}; - -#endif diff --git a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.ui b/src/plugins/dxf2shp_converter/dxf2shpconvertergui.ui deleted file mode 100644 index e927e11bde5b..000000000000 --- a/src/plugins/dxf2shp_converter/dxf2shpconvertergui.ui +++ /dev/null @@ -1,158 +0,0 @@ - - - dxf2shpConverterGui - - - - 0 - 0 - 353 - 263 - - - - Dxf Importer - - - - - - - - - - - Input and output - - - - - - Input DXF file - - - - - - - - - - ... - - - - - - - Output file - - - - - - - - - - ... - - - - - - - Export inserts - - - - - - - Export text labels - - - - - - - - - - Output file type - - - - - - Polyline - - - - - - - Polygon - - - - - - - Point - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok - - - - - - - - - - - buttonBox - accepted() - dxf2shpConverterGui - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - dxf2shpConverterGui - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_attributes.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_attributes.h deleted file mode 100644 index 98d6720a8de9..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_attributes.h +++ /dev/null @@ -1,237 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_ATTRIBUTES_H -#define DL_ATTRIBUTES_H - -#include "dl_global.h" - -#include -#include - -#include "dl_codes.h" - -/** - * Storing and passing around attributes. Attributes - * are the layer name, color, width and line type. - * - * @author Andrew Mustun - */ -class DXFLIB_EXPORT DL_Attributes { - -public: - - /** - * Default constructor. - */ - DL_Attributes() : - layer(""), - color(0), - color24(-1), - width(0), - linetype("BYLAYER"), - linetypeScale(1.0), - handle(-1), - inPaperSpace(false) { - } - - /** - * Constructor for DXF attributes. - * - * @param layer Layer name for this entity or NULL for no layer - * (every entity should be on a named layer!). - * @param color Color number (0..256). 0 = BYBLOCK, 256 = BYLAYER. - * @param width Line thickness. Defaults to zero. -1 = BYLAYER, - * -2 = BYBLOCK, -3 = default width - * @param linetype Line type name or "BYLAYER" or "BYBLOCK". Defaults - * to "BYLAYER" - */ - DL_Attributes(const std::string& layer, - int color, int width, - const std::string& linetype, - double linetypeScale) : - layer(layer), - color(color), - color24(-1), - width(width), - linetype(linetype), - linetypeScale(linetypeScale), - handle(-1), - inPaperSpace(false) { - - } - - /** - * Constructor for DXF attributes. - * - * @param layer Layer name for this entity or NULL for no layer - * (every entity should be on a named layer!). - * @param color Color number (0..256). 0 = BYBLOCK, 256 = BYLAYER. - * @param color24 24 bit color (see DXF reference). - * @param width Line thickness. Defaults to zero. -1 = BYLAYER, - * -2 = BYBLOCK, -3 = default width - * @param linetype Line type name or "BYLAYER" or "BYBLOCK". Defaults - * to "BYLAYER" - */ - DL_Attributes(const std::string& layer, - int color, int color24, int width, - const std::string& linetype, - int handle=-1) : - layer(layer), - color(color), - color24(color24), - width(width), - linetype(linetype), - linetypeScale(1.0), - handle(handle), - inPaperSpace(false) { - } - - /** - * Sets the layer. If the given pointer points to NULL, the - * new layer name will be an empty but valid string. - */ - void setLayer(const std::string& layer) { - this->layer = layer; - } - - /** - * @return Layer name. - */ - std::string getLayer() const { - return layer; - } - - /** - * Sets the color. - * - * @see DL_Codes, dxfColors - */ - void setColor(int color) { - this->color = color; - } - - /** - * Sets the 24bit color. - * - * @see DL_Codes, dxfColors - */ - void setColor24(int color) { - this->color24 = color; - } - - /** - * @return Color. - * - * @see DL_Codes, dxfColors - */ - int getColor() const { - return color; - } - - /** - * @return 24 bit color or -1 if no 24bit color is defined. - * - * @see DL_Codes, dxfColors - */ - int getColor24() const { - return color24; - } - - /** - * Sets the width. - */ - void setWidth(int width) { - this->width = width; - } - - /** - * @return Width. - */ - int getWidth() const { - return width; - } - - /** - * Sets the line type. This can be any string and is not - * checked to be a valid line type. - */ - void setLinetype(const std::string& linetype) { - this->linetype = linetype; - } - - /** - * Sets the entity specific line type scale. - */ - void setLinetypeScale(double linetypeScale) { - this->linetypeScale = linetypeScale; - } - - double getLinetypeScale() const { - return linetypeScale; - } - - /** - * @return Line type. - */ - std::string getLinetype() const { - if (linetype.length()==0) { - return "BYLAYER"; - } else { - return linetype; - } - } - - void setHandle(int h) { - handle = h; - } - - int getHandle() const { - return handle; - } - - void setInPaperSpace(bool on) { - inPaperSpace = on; - } - - bool isInPaperSpace() { - return inPaperSpace; - } - -private: - std::string layer; - int color; - int color24; - int width; - std::string linetype; - double linetypeScale; - int handle; - - // DXF code 67 (true: entity in paper space, false: entity in model space (default): - bool inPaperSpace; -}; - -#endif - -// EOF diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_codes.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_codes.h deleted file mode 100644 index 3fa485ede167..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_codes.h +++ /dev/null @@ -1,545 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** Copyright (C) 2001 Robert J. Campbell Jr. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -/** - * Defines common DXF codes and constants. - */ - -#ifndef DXF_CODES_H -#define DXF_CODES_H - -#include "dl_global.h" - -#if defined(_MSC_VER) && _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#if defined(__OS2__)||defined(__EMX__) -#define strcasecmp(s,t) stricmp(s,t) -#endif - -#if defined(_WIN32) -#define strcasecmp(s,t) _stricmp(s,t) -#endif - - -#ifdef _WIN32 -#undef M_PI -#define M_PI 3.14159265358979323846 -#pragma warning(disable : 4800) -#endif - -#ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 -#endif - -#define DL_DXF_MAXLINE 1024 -#define DL_DXF_MAXGROUPCODE 1100 - -// used to mark invalid vectors: -//#define DL_DXF_MAXDOUBLE 1.0E+10 - -/** - * Codes for colors and DXF versions. - */ -class DXFLIB_EXPORT DL_Codes { -public: - /** - * Standard DXF colors. - */ - enum color { - black = 250, - green = 3, - red = 1, - brown = 15, - yellow = 2, - cyan = 4, - magenta = 6, - gray = 8, - blue = 5, - l_blue = 163, - l_green = 121, - l_cyan = 131, - l_red = 23, - l_magenta = 221, - l_gray = 252, - white = 7, - bylayer = 256, - byblock = 0 - }; - - /** - * Version numbers for the DXF Format. - */ - enum version { - AC1009, // R12 - AC1012, - AC1014, - AC1015 // R2000 - }; -}; - - -// Extended color palette: -// The first entry is only for direct indexing starting with [1] -// Color 1 is red (1,0,0) -const double dxfColors[][3] = { - {0,0,0}, // unused - {1,0,0}, // 1 - {1,1,0}, - {0,1,0}, - {0,1,1}, - {0,0,1}, - {1,0,1}, - {1,1,1}, // black or white - {0.5,0.5,0.5}, - {0.75,0.75,0.75}, - {1,0,0}, // 10 - {1,0.5,0.5}, - {0.65,0,0}, - {0.65,0.325,0.325}, - {0.5,0,0}, - {0.5,0.25,0.25}, - {0.3,0,0}, - {0.3,0.15,0.15}, - {0.15,0,0}, - {0.15,0.075,0.075}, - {1,0.25,0}, // 20 - {1,0.625,0.5}, - {0.65,0.1625,0}, - {0.65,0.4063,0.325}, - {0.5,0.125,0}, - {0.5,0.3125,0.25}, - {0.3,0.075,0}, - {0.3,0.1875,0.15}, - {0.15,0.0375,0}, - {0.15,0.0938,0.075}, - {1,0.5,0}, // 30 - {1,0.75,0.5}, - {0.65,0.325,0}, - {0.65,0.4875,0.325}, - {0.5,0.25,0}, - {0.5,0.375,0.25}, - {0.3,0.15,0}, - {0.3,0.225,0.15}, - {0.15,0.075,0}, - {0.15,0.1125,0.075}, - {1,0.75,0}, // 40 - {1,0.875,0.5}, - {0.65,0.4875,0}, - {0.65,0.5688,0.325}, - {0.5,0.375,0}, - {0.5,0.4375,0.25}, - {0.3,0.225,0}, - {0.3,0.2625,0.15}, - {0.15,0.1125,0}, - {0.15,0.1313,0.075}, - {1,1,0}, // 50 - {1,1,0.5}, - {0.65,0.65,0}, - {0.65,0.65,0.325}, - {0.5,0.5,0}, - {0.5,0.5,0.25}, - {0.3,0.3,0}, - {0.3,0.3,0.15}, - {0.15,0.15,0}, - {0.15,0.15,0.075}, - {0.75,1,0}, // 60 - {0.875,1,0.5}, - {0.4875,0.65,0}, - {0.5688,0.65,0.325}, - {0.375,0.5,0}, - {0.4375,0.5,0.25}, - {0.225,0.3,0}, - {0.2625,0.3,0.15}, - {0.1125,0.15,0}, - {0.1313,0.15,0.075}, - {0.5,1,0}, // 70 - {0.75,1,0.5}, - {0.325,0.65,0}, - {0.4875,0.65,0.325}, - {0.25,0.5,0}, - {0.375,0.5,0.25}, - {0.15,0.3,0}, - {0.225,0.3,0.15}, - {0.075,0.15,0}, - {0.1125,0.15,0.075}, - {0.25,1,0}, // 80 - {0.625,1,0.5}, - {0.1625,0.65,0}, - {0.4063,0.65,0.325}, - {0.125,0.5,0}, - {0.3125,0.5,0.25}, - {0.075,0.3,0}, - {0.1875,0.3,0.15}, - {0.0375,0.15,0}, - {0.0938,0.15,0.075}, - {0,1,0}, // 90 - {0.5,1,0.5}, - {0,0.65,0}, - {0.325,0.65,0.325}, - {0,0.5,0}, - {0.25,0.5,0.25}, - {0,0.3,0}, - {0.15,0.3,0.15}, - {0,0.15,0}, - {0.075,0.15,0.075}, - {0,1,0.25}, // 100 - {0.5,1,0.625}, - {0,0.65,0.1625}, - {0.325,0.65,0.4063}, - {0,0.5,0.125}, - {0.25,0.5,0.3125}, - {0,0.3,0.075}, - {0.15,0.3,0.1875}, - {0,0.15,0.0375}, - {0.075,0.15,0.0938}, - {0,1,0.5}, // 110 - {0.5,1,0.75}, - {0,0.65,0.325}, - {0.325,0.65,0.4875}, - {0,0.5,0.25}, - {0.25,0.5,0.375}, - {0,0.3,0.15}, - {0.15,0.3,0.225}, - {0,0.15,0.075}, - {0.075,0.15,0.1125}, - {0,1,0.75}, // 120 - {0.5,1,0.875}, - {0,0.65,0.4875}, - {0.325,0.65,0.5688}, - {0,0.5,0.375}, - {0.25,0.5,0.4375}, - {0,0.3,0.225}, - {0.15,0.3,0.2625}, - {0,0.15,0.1125}, - {0.075,0.15,0.1313}, - {0,1,1}, // 130 - {0.5,1,1}, - {0,0.65,0.65}, - {0.325,0.65,0.65}, - {0,0.5,0.5}, - {0.25,0.5,0.5}, - {0,0.3,0.3}, - {0.15,0.3,0.3}, - {0,0.15,0.15}, - {0.075,0.15,0.15}, - {0,0.75,1}, // 140 - {0.5,0.875,1}, - {0,0.4875,0.65}, - {0.325,0.5688,0.65}, - {0,0.375,0.5}, - {0.25,0.4375,0.5}, - {0,0.225,0.3}, - {0.15,0.2625,0.3}, - {0,0.1125,0.15}, - {0.075,0.1313,0.15}, - {0,0.5,1}, // 150 - {0.5,0.75,1}, - {0,0.325,0.65}, - {0.325,0.4875,0.65}, - {0,0.25,0.5}, - {0.25,0.375,0.5}, - {0,0.15,0.3}, - {0.15,0.225,0.3}, - {0,0.075,0.15}, - {0.075,0.1125,0.15}, - {0,0.25,1}, // 160 - {0.5,0.625,1}, - {0,0.1625,0.65}, - {0.325,0.4063,0.65}, - {0,0.125,0.5}, - {0.25,0.3125,0.5}, - {0,0.075,0.3}, - {0.15,0.1875,0.3}, - {0,0.0375,0.15}, - {0.075,0.0938,0.15}, - {0,0,1}, // 170 - {0.5,0.5,1}, - {0,0,0.65}, - {0.325,0.325,0.65}, - {0,0,0.5}, - {0.25,0.25,0.5}, - {0,0,0.3}, - {0.15,0.15,0.3}, - {0,0,0.15}, - {0.075,0.075,0.15}, - {0.25,0,1}, // 180 - {0.625,0.5,1}, - {0.1625,0,0.65}, - {0.4063,0.325,0.65}, - {0.125,0,0.5}, - {0.3125,0.25,0.5}, - {0.075,0,0.3}, - {0.1875,0.15,0.3}, - {0.0375,0,0.15}, - {0.0938,0.075,0.15}, - {0.5,0,1}, // 190 - {0.75,0.5,1}, - {0.325,0,0.65}, - {0.4875,0.325,0.65}, - {0.25,0,0.5}, - {0.375,0.25,0.5}, - {0.15,0,0.3}, - {0.225,0.15,0.3}, - {0.075,0,0.15}, - {0.1125,0.075,0.15}, - {0.75,0,1}, // 200 - {0.875,0.5,1}, - {0.4875,0,0.65}, - {0.5688,0.325,0.65}, - {0.375,0,0.5}, - {0.4375,0.25,0.5}, - {0.225,0,0.3}, - {0.2625,0.15,0.3}, - {0.1125,0,0.15}, - {0.1313,0.075,0.15}, - {1,0,1}, // 210 - {1,0.5,1}, - {0.65,0,0.65}, - {0.65,0.325,0.65}, - {0.5,0,0.5}, - {0.5,0.25,0.5}, - {0.3,0,0.3}, - {0.3,0.15,0.3}, - {0.15,0,0.15}, - {0.15,0.075,0.15}, - {1,0,0.75}, // 220 - {1,0.5,0.875}, - {0.65,0,0.4875}, - {0.65,0.325,0.5688}, - {0.5,0,0.375}, - {0.5,0.25,0.4375}, - {0.3,0,0.225}, - {0.3,0.15,0.2625}, - {0.15,0,0.1125}, - {0.15,0.075,0.1313}, - {1,0,0.5}, // 230 - {1,0.5,0.75}, - {0.65,0,0.325}, - {0.65,0.325,0.4875}, - {0.5,0,0.25}, - {0.5,0.25,0.375}, - {0.3,0,0.15}, - {0.3,0.15,0.225}, - {0.15,0,0.075}, - {0.15,0.075,0.1125}, - {1,0,0.25}, // 240 - {1,0.5,0.625}, - {0.65,0,0.1625}, - {0.65,0.325,0.4063}, - {0.5,0,0.125}, - {0.5,0.25,0.3125}, - {0.3,0,0.075}, - {0.3,0.15,0.1875}, - {0.15,0,0.0375}, - {0.15,0.075,0.0938}, - {0.33,0.33,0.33}, // 250 - {0.464,0.464,0.464}, - {0.598,0.598,0.598}, - {0.732,0.732,0.732}, - {0.866,0.866,0.866}, - {1,1,1} // 255 - } - ; - - -// AutoCAD VERSION aliases -#define DL_VERSION_R12 DL_Codes::AC1009 -#define DL_VERSION_LT2 DL_Codes::AC1009 -#define DL_VERSION_R13 DL_Codes::AC1012 // not supported yet -#define DL_VERSION_LT95 DL_Codes::AC1012 // not supported yet -#define DL_VERSION_R14 DL_Codes::AC1014 // not supported yet -#define DL_VERSION_LT97 DL_Codes::AC1014 // not supported yet -#define DL_VERSION_LT98 DL_Codes::AC1014 // not supported yet -#define DL_VERSION_2000 DL_Codes::AC1015 -#define DL_VERSION_2002 DL_Codes::AC1015 - - -// DXF Group Codes: - -// Strings -#define DL_STRGRP_START 0 -#define DL_STRGRP_END 9 - -// Coordinates -#define DL_CRDGRP_START 10 -#define DL_CRDGRP_END 19 - -// Real values -#define DL_RLGRP_START 38 -#define DL_RLGRP_END 59 - -// Short integer values -#define DL_SHOGRP_START 60 -#define DL_SHOGRP_END 79 - -// New in Release 13, -#define DL_SUBCLASS 100 - -// More coordinates -#define DL_CRD2GRP_START 210 -#define DL_CRD2GRP_END 239 - -// Extended data strings -#define DL_ESTRGRP_START 1000 -#define DL_ESTRGRP_END 1009 - -// Extended data reals -#define DL_ERLGRP_START 1010 -#define DL_ERLGRP_END 1059 - - -#define DL_Y8_COORD_CODE 28 -#define DL_Z0_COORD_CODE 30 -#define DL_Z8_COORD_CODE 38 - -#define DL_POINT_COORD_CODE 10 -#define DL_INSERT_COORD_CODE 10 - -#define DL_CRD2GRP_START 210 -#define DL_CRD2GRP_END 239 - -#define DL_THICKNESS 39 -#define DL_FIRST_REAL_CODE THICKNESS -#define DL_LAST_REAL_CODE 59 -#define DL_FIRST_INT_CODE 60 -#define DL_ATTFLAGS_CODE 70 -#define DL_PLINE_FLAGS_CODE 70 -#define DL_LAYER_FLAGS_CODE 70 -#define DL_FLD_LEN_CODE 73 // Inside ATTRIB resbuf -#define DL_LAST_INT_CODE 79 -#define DL_X_EXTRU_CODE 210 -#define DL_Y_EXTRU_CODE 220 -#define DL_Z_EXTRU_CODE 230 -#define DL_COMMENT_CODE 999 - -// Start and endpoints of a line -#define DL_LINE_START_CODE 10 // Followed by x coord -#define DL_LINE_END_CODE 11 // Followed by x coord - -// Some codes used by blocks -#define DL_BLOCK_FLAGS_CODE 70 // An int containing flags -#define DL_BLOCK_BASE_CODE 10 // Origin of block definition -#define DL_XREF_DEPENDENT 16 // If a block contains an XREF -#define DL_XREF_RESOLVED 32 // If a XREF resolved ok -#define DL_REFERENCED 64 // If a block is ref'd in DWG - -#define DL_XSCALE_CODE 41 -#define DL_YSCALE_CODE 42 -#define DL_ANGLE_CODE 50 -#define DL_INS_POINT_CODE 10 // Followed by x of ins pnt -#define DL_NAME2_CODE 3 // Second appearance of name - -// Some codes used by circle entities -#define DL_CENTER_CODE 10 // Followed by x of center -#define DL_RADIUS_CODE 40 // Followd by radius of circle - -#define DL_COND_OP_CODE -4 // Conditional op,ads_ssget - -// When using ads_buildlist you MUST use RTDXF0 instead of these -#define DL_ENTITY_TYPE_CODE 0 // Then there is LINE, 3DFACE.. -#define DL_SES_CODE 0 // Start End String Code -#define DL_FILE_SEP_CODE 0 // File separator -#define DL_SOT_CODE 0 // Start Of Table -#define DL_TEXTVAL_CODE 1 -#define DL_NAME_CODE 2 -#define DL_BLOCK_NAME_CODE 2 -#define DL_SECTION_NAME_CODE 2 -#define DL_ENT_HAND_CODE 5 // What follows is hexa string -#define DL_TXT_STYLE_CODE 7 // Inside attributes -#define DL_LAYER_NAME_CODE 8 // What follows is layer name -#define DL_FIRST_XCOORD_CODE 10 // Group code x of 1st coord -#define DL_FIRST_YCOORD_CODE 20 // Group code y of 1st coord -#define DL_FIRST_ZCOORD_CODE 30 // Group code z of 1st coord -#define DL_L_START_CODE 10 -#define DL_L_END_CODE 11 -#define DL_TXTHI_CODE 40 -#define DL_SCALE_X_CODE 41 -#define DL_SCALE_Y_CODE 42 -#define DL_SCALE_Z_CODE 43 -#define DL_BULGE_CODE 42 // Used in PLINE verts for arcs -#define DL_ROTATION_CODE 50 -#define DL_COLOUR_CODE 62 // What follows is a color int -#define DL_LTYPE_CODE 6 // What follows is a linetype - - -// Attribute flags -#define DL_ATTS_FOLLOW_CODE 66 -#define DL_ATT_TAG_CODE 2 -#define DL_ATT_VAL_CODE 1 -#define DL_ATT_FLAGS_CODE 70 // 4 1 bit flags as follows... -#define DL_ATT_INVIS_FLAG 1 -#define DL_ATT_CONST_FLAG 2 -#define DL_ATT_VERIFY_FLAG 4 // Prompt and verify -#define DL_ATT_PRESET_FLAG 8 // No prompt and no verify - -// PLINE defines -// Flags -#define DL_OPEN_PLINE 0x00 -#define DL_CLOSED_PLINE 0x01 -#define DL_POLYLINE3D 0x80 -#define DL_PFACE_MESH 0x40 -#define DL_PGON_MESH 0x10 -// Vertices follow entity, required in POLYLINES -#define DL_VERTS_FOLLOW_CODE 66 // Value should always be 1 -#define DL_VERTEX_COORD_CODE 10 - - -// LAYER flags -#define DL_FROZEN 1 -#define DL_FROZEN_BY_DEF 2 -#define DL_LOCKED 4 -#define DL_OBJECT_USED 64 // Object is ref'd in the dwg - -#define DL_BLOCK_EN_CODE -2 // Block entity definition -#define DL_E_NAME -1 // Entity name - -// Extended data codes -#define DL_EXTD_SENTINEL (-3) -#define DL_EXTD_STR 1000 -#define DL_EXTD_APP_NAME 1001 -#define DL_EXTD_CTL_STR 1002 -#define DL_EXTD_LYR_STR 1003 -#define DL_EXTD_CHUNK 1004 -#define DL_EXTD_HANDLE 1005 -#define DL_EXTD_POINT 1010 -#define DL_EXTD_POS 1011 -#define DL_EXTD_DISP 1012 -#define DL_EXTD_DIR 1013 -#define DL_EXTD_FLOAT 1040 -#define DL_EXTD_DIST 1041 -#define DL_EXTD_SCALE 1042 -#define DL_EXTD_INT16 1070 -#define DL_EXTD_INT32 1071 - -// UCS codes for use in ads_trans -#define DL_WCS_TRANS_CODE 0 -#define DL_UCS_TRANS_CODE 1 -#define DL_DCS_TRANS_CODE 2 -#define DL_PCS_TRANS_CODE 3 - -#endif - diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_creationadapter.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_creationadapter.h deleted file mode 100644 index 8694630b49f7..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_creationadapter.h +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_CREATIONADAPTER_H -#define DL_CREATIONADAPTER_H - -#include "dl_global.h" - -#include "dl_creationinterface.h" - -/** - * An abstract adapter class for receiving DXF events when a DXF file is being read. - * The methods in this class are empty. This class exists as convenience for creating - * listener objects. - * - * @author Andrew Mustun - */ -class DXFLIB_EXPORT DL_CreationAdapter : public DL_CreationInterface { -public: - DL_CreationAdapter() {} - virtual ~DL_CreationAdapter() {} - virtual void processCodeValuePair(unsigned int, const std::string&) {} - virtual void endSection() {} - virtual void addLayer(const DL_LayerData&) {} - virtual void addLinetype(const DL_LinetypeData&) {} - virtual void addLinetypeDash(double) {} - virtual void addBlock(const DL_BlockData&) {} - virtual void endBlock() {} - virtual void addTextStyle(const DL_StyleData&) {} - virtual void addPoint(const DL_PointData&) {} - virtual void addLine(const DL_LineData&) {} - virtual void addXLine(const DL_XLineData&) {} - virtual void addRay(const DL_RayData&) {} - - virtual void addArc(const DL_ArcData&) {} - virtual void addCircle(const DL_CircleData&) {} - virtual void addEllipse(const DL_EllipseData&) {} - - virtual void addPolyline(const DL_PolylineData&) {} - virtual void addVertex(const DL_VertexData&) {} - - virtual void addSpline(const DL_SplineData&) {} - virtual void addControlPoint(const DL_ControlPointData&) {} - virtual void addFitPoint(const DL_FitPointData&) {} - virtual void addKnot(const DL_KnotData&) {} - - virtual void addInsert(const DL_InsertData&) {} - - virtual void addMText(const DL_MTextData&) {} - virtual void addMTextChunk(const std::string&) {} - virtual void addText(const DL_TextData&) {} - virtual void addAttribute(const DL_AttributeData&) {} - - virtual void addDimAlign(const DL_DimensionData&, - const DL_DimAlignedData&) {} - virtual void addDimLinear(const DL_DimensionData&, - const DL_DimLinearData&) {} - virtual void addDimRadial(const DL_DimensionData&, - const DL_DimRadialData&) {} - virtual void addDimDiametric(const DL_DimensionData&, - const DL_DimDiametricData&) {} - virtual void addDimAngular(const DL_DimensionData&, - const DL_DimAngularData&) {} - virtual void addDimAngular3P(const DL_DimensionData&, - const DL_DimAngular3PData&) {} - virtual void addDimOrdinate(const DL_DimensionData&, - const DL_DimOrdinateData&) {} - virtual void addLeader(const DL_LeaderData&) {} - virtual void addLeaderVertex(const DL_LeaderVertexData&) {} - - virtual void addHatch(const DL_HatchData&) {} - - virtual void addTrace(const DL_TraceData&) {} - virtual void add3dFace(const DL_3dFaceData&) {} - virtual void addSolid(const DL_SolidData&) {} - - virtual void addImage(const DL_ImageData&) {} - virtual void linkImage(const DL_ImageDefData&) {} - virtual void addHatchLoop(const DL_HatchLoopData&) {} - virtual void addHatchEdge(const DL_HatchEdgeData&) {} - - virtual void addXRecord(const std::string&) {} - virtual void addXRecordString(int, const std::string&) {} - virtual void addXRecordReal(int, double) {} - virtual void addXRecordInt(int, int) {} - virtual void addXRecordBool(int, bool) {} - - virtual void addXDataApp(const std::string&) {} - virtual void addXDataString(int, const std::string&) {} - virtual void addXDataReal(int, double) {} - virtual void addXDataInt(int, int) {} - - virtual void addDictionary(const DL_DictionaryData&) {} - virtual void addDictionaryEntry(const DL_DictionaryEntryData&) {} - - virtual void endEntity() {} - - virtual void addComment(const std::string&) {} - - virtual void setVariableVector(const std::string&, double, double, double, int) {} - virtual void setVariableString(const std::string&, const std::string&, int) {} - virtual void setVariableInt(const std::string&, int, int) {} - virtual void setVariableDouble(const std::string&, double, int) {} -#ifdef DL_COMPAT - virtual void setVariableVector(const char*, double, double, double, int) {} - virtual void setVariableString(const char*, const char*, int) {} - virtual void setVariableInt(const char*, int, int) {} - virtual void setVariableDouble(const char*, double, int) {} - virtual void processCodeValuePair(unsigned int, char*) {} - virtual void addComment(const char*) {} - virtual void addMTextChunk(const char*) {} -#endif - virtual void endSequence() {} -}; - -#endif diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_creationinterface.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_creationinterface.h deleted file mode 100644 index a4058f6fe20c..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_creationinterface.h +++ /dev/null @@ -1,366 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_CREATIONINTERFACE_H -#define DL_CREATIONINTERFACE_H - -#include "dl_global.h" - -#include - -#include "dl_attributes.h" -#include "dl_codes.h" -#include "dl_entities.h" -#include "dl_extrusion.h" - -/** - * Abstract class (interface) for the creation of new entities. - * Inherit your class which takes care of the entities in the - * processed DXF file from this interface. - * - * Double arrays passed to your implementation contain 3 double - * values for x, y, z coordinates unless stated differently. - * - * @author Andrew Mustun - */ -class DXFLIB_EXPORT DL_CreationInterface { -public: - DL_CreationInterface() { - extrusion = new DL_Extrusion; - } - virtual ~DL_CreationInterface() { - delete extrusion; - } - - /** - * Called for every code / value tuple of the DXF file. The complete DXF file - * contents can be handled by the implemetation of this function. - */ - virtual void processCodeValuePair(unsigned int groupCode, const std::string& groupValue) = 0; - - /** - * Called when a section (entity, table entry, etc.) is finished. - */ - virtual void endSection() = 0; - - /** - * Called for every layer. - */ - virtual void addLayer(const DL_LayerData& data) = 0; - - /** - * Called for every linetype. - */ - virtual void addLinetype(const DL_LinetypeData& data) = 0; - - /** - * Called for every dash in linetype pattern - */ - virtual void addLinetypeDash(double length) = 0; - - /** - * Called for every block. Note: all entities added after this - * command go into this block until endBlock() is called. - * - * @see endBlock() - */ - virtual void addBlock(const DL_BlockData& data) = 0; - - /** Called to end the current block */ - virtual void endBlock() = 0; - - /** Called for every text style */ - virtual void addTextStyle(const DL_StyleData& data) = 0; - - /** Called for every point */ - virtual void addPoint(const DL_PointData& data) = 0; - - /** Called for every line */ - virtual void addLine(const DL_LineData& data) = 0; - - /** Called for every xline */ - virtual void addXLine(const DL_XLineData& data) = 0; - - /** Called for every ray */ - virtual void addRay(const DL_RayData& data) = 0; - - /** Called for every arc */ - virtual void addArc(const DL_ArcData& data) = 0; - - /** Called for every circle */ - virtual void addCircle(const DL_CircleData& data) = 0; - - /** Called for every ellipse */ - virtual void addEllipse(const DL_EllipseData& data) = 0; - - /** Called for every polyline start */ - virtual void addPolyline(const DL_PolylineData& data) = 0; - - /** Called for every polyline vertex */ - virtual void addVertex(const DL_VertexData& data) = 0; - - /** Called for every spline */ - virtual void addSpline(const DL_SplineData& data) = 0; - - /** Called for every spline control point */ - virtual void addControlPoint(const DL_ControlPointData& data) = 0; - - /** Called for every spline fit point */ - virtual void addFitPoint(const DL_FitPointData& data) = 0; - - /** Called for every spline knot value */ - virtual void addKnot(const DL_KnotData& data) = 0; - - /** Called for every insert. */ - virtual void addInsert(const DL_InsertData& data) = 0; - - /** Called for every trace start */ - virtual void addTrace(const DL_TraceData& data) = 0; - - /** Called for every 3dface start */ - virtual void add3dFace(const DL_3dFaceData& data) = 0; - - /** Called for every solid start */ - virtual void addSolid(const DL_SolidData& data) = 0; - - - /** Called for every Multi Text entity. */ - virtual void addMText(const DL_MTextData& data) = 0; - - /** - * Called for additional text chunks for MTEXT entities. - * The chunks come at 250 character in size each. Note that - * those chunks come before the actual MTEXT entity. - */ - virtual void addMTextChunk(const std::string& text) = 0; - - /** Called for every Text entity. */ - virtual void addText(const DL_TextData& data) = 0; - - /** Called for every Block Attribute entity. */ - virtual void addAttribute(const DL_AttributeData& data) = 0; - - /** - * Called for every aligned dimension entity. - */ - virtual void addDimAlign(const DL_DimensionData& data, - const DL_DimAlignedData& edata) = 0; - /** - * Called for every linear or rotated dimension entity. - */ - virtual void addDimLinear(const DL_DimensionData& data, - const DL_DimLinearData& edata) = 0; - - /** - * Called for every radial dimension entity. - */ - virtual void addDimRadial(const DL_DimensionData& data, - const DL_DimRadialData& edata) = 0; - - /** - * Called for every diametric dimension entity. - */ - virtual void addDimDiametric(const DL_DimensionData& data, - const DL_DimDiametricData& edata) = 0; - - /** - * Called for every angular dimension (2 lines version) entity. - */ - virtual void addDimAngular(const DL_DimensionData& data, - const DL_DimAngularData& edata) = 0; - - /** - * Called for every angular dimension (3 points version) entity. - */ - virtual void addDimAngular3P(const DL_DimensionData& data, - const DL_DimAngular3PData& edata) = 0; - - /** - * Called for every ordinate dimension entity. - */ - virtual void addDimOrdinate(const DL_DimensionData& data, - const DL_DimOrdinateData& edata) = 0; - - /** - * Called for every leader start. - */ - virtual void addLeader(const DL_LeaderData& data) = 0; - - /** - * Called for every leader vertex - */ - virtual void addLeaderVertex(const DL_LeaderVertexData& data) = 0; - - /** - * Called for every hatch entity. - */ - virtual void addHatch(const DL_HatchData& data) = 0; - - /** - * Called for every image entity. - */ - virtual void addImage(const DL_ImageData& data) = 0; - - /** - * Called for every image definition. - */ - virtual void linkImage(const DL_ImageDefData& data) = 0; - - /** - * Called for every hatch loop. - */ - virtual void addHatchLoop(const DL_HatchLoopData& data) = 0; - - /** - * Called for every hatch edge entity. - */ - virtual void addHatchEdge(const DL_HatchEdgeData& data) = 0; - - /** - * Called for every XRecord with the given handle. - */ - virtual void addXRecord(const std::string& handle) = 0; - - /** - * Called for XRecords of type string. - */ - virtual void addXRecordString(int code, const std::string& value) = 0; - - /** - * Called for XRecords of type double. - */ - virtual void addXRecordReal(int code, double value) = 0; - - /** - * Called for XRecords of type int. - */ - virtual void addXRecordInt(int code, int value) = 0; - - /** - * Called for XRecords of type bool. - */ - virtual void addXRecordBool(int code, bool value) = 0; - - /** - * Called for every beginning of an XData section of the given application. - */ - virtual void addXDataApp(const std::string& appId) = 0; - - /** - * Called for XData tuples. - */ - virtual void addXDataString(int code, const std::string& value) = 0; - - /** - * Called for XData tuples. - */ - virtual void addXDataReal(int code, double value) = 0; - - /** - * Called for XData tuples. - */ - virtual void addXDataInt(int code, int value) = 0; - - /** - * Called for dictionary objects. - */ - virtual void addDictionary(const DL_DictionaryData& data) = 0; - - /** - * Called for dictionary entries. - */ - virtual void addDictionaryEntry(const DL_DictionaryEntryData& data) = 0; - - /** - * Called after an entity has been completed. - */ - virtual void endEntity() = 0; - - /** - * Called for every comment in the DXF file (code 999). - */ - virtual void addComment(const std::string& comment) = 0; - - /** - * Called for every vector variable in the DXF file (e.g. "$EXTMIN"). - */ - virtual void setVariableVector(const std::string& key, double v1, double v2, double v3, int code) = 0; - - /** - * Called for every string variable in the DXF file (e.g. "$ACADVER"). - */ - virtual void setVariableString(const std::string& key, const std::string& value, int code) = 0; - - /** - * Called for every int variable in the DXF file (e.g. "$ACADMAINTVER"). - */ - virtual void setVariableInt(const std::string& key, int value, int code) = 0; - - /** - * Called for every double variable in the DXF file (e.g. "$DIMEXO"). - */ - virtual void setVariableDouble(const std::string& key, double value, int code) = 0; - -#ifdef DL_COMPAT - virtual void setVariableVector(const char* key, double v1, double v2, double v3, int code) = 0; - virtual void setVariableString(const char* key, const char* value, int code) = 0; - virtual void setVariableInt(const char* key, int value, int code) = 0; - virtual void setVariableDouble(const char* key, double value, int code) = 0; - virtual void processCodeValuePair(unsigned int groupCode, char* groupValue) = 0; - virtual void addComment(const char* comment) = 0; - virtual void addMTextChunk(const char* text) = 0; -#endif - - /** - * Called when a SEQEND occurs (when a POLYLINE or ATTRIB is done) - */ - virtual void endSequence() = 0; - - /** Sets the current attributes for entities. */ - void setAttributes(const DL_Attributes& attrib) { - attributes = attrib; - } - - /** @return the current attributes used for new entities. */ - DL_Attributes getAttributes() { - return attributes; - } - - /** Sets the current attributes for entities. */ - void setExtrusion(double dx, double dy, double dz, double elevation) { - extrusion->setDirection(dx, dy, dz); - extrusion->setElevation(elevation); - } - - /** @return the current attributes used for new entities. */ - DL_Extrusion* getExtrusion() { - return extrusion; - } - -protected: - DL_Attributes attributes; - DL_Extrusion *extrusion; -}; - -#endif diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.cpp b/src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.cpp deleted file mode 100644 index 549c1b1d900f..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.cpp +++ /dev/null @@ -1,5239 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#include "dl_dxf.h" - -#include -#include -#include -#include -#include - -#include "dl_attributes.h" -#include "dl_codes.h" -#include "dl_creationadapter.h" -#include "dl_writer_ascii.h" - -#include "iostream" - -/** - * Default constructor. - */ -DL_Dxf::DL_Dxf() { - version = DL_VERSION_2000; - - vertices = nullptr; - maxVertices = 0; - vertexIndex = 0; - - knots = nullptr; - maxKnots = 0; - knotIndex = 0; - - weights = nullptr; - weightIndex = 0; - - controlPoints = nullptr; - maxControlPoints = 0; - controlPointIndex = 0; - - fitPoints = nullptr; - maxFitPoints = 0; - fitPointIndex = 0; - - leaderVertices = nullptr; - maxLeaderVertices = 0; - leaderVertexIndex = 0; -} - - - -/** - * Destructor. - */ -DL_Dxf::~DL_Dxf() { - if (vertices!=nullptr) { - delete[] vertices; - } - if (knots!=nullptr) { - delete[] knots; - } - if (controlPoints!=nullptr) { - delete[] controlPoints; - } - if (fitPoints!=nullptr) { - delete[] fitPoints; - } - if (weights!=nullptr) { - delete[] weights; - } - if (leaderVertices!=nullptr) { - delete[] leaderVertices; - } -} - - - -/** - * @brief Reads the given file and calls the appropriate functions in - * the given creation interface for every entity found in the file. - * - * @param file Input - * Path and name of file to read - * @param creationInterface - * Pointer to the class which takes care of the entities in the file. - * - * @retval true If \p file could be opened. - * @retval false If \p file could not be opened. - */ -bool DL_Dxf::in(const std::string& file, DL_CreationInterface* creationInterface) { - FILE *fp; - firstCall = true; - currentObjectType = DL_UNKNOWN; - - fp = fopen(file.c_str(), "rt"); - if (fp) { - while (readDxfGroups(fp, creationInterface)) {} - fclose(fp); - return true; - } - - return false; -} - - - -/** - * Reads a DXF file from an existing stream. - * - * @param stream The string stream. - * @param creationInterface - * Pointer to the class which takes care of the entities in the file. - * - * @retval true If \p file could be opened. - * @retval false If \p file could not be opened. - */ -bool DL_Dxf::in(std::stringstream& stream, - DL_CreationInterface* creationInterface) { - - if (stream.good()) { - firstCall=true; - currentObjectType = DL_UNKNOWN; - while (readDxfGroups(stream, creationInterface)) {} - return true; - } - return false; -} - - - -/** - * @brief Reads a group couplet from a DXF file. Calls another function - * to process it. - * - * A group couplet consists of two lines that represent a single - * piece of data. An integer constant on the first line indicates - * the type of data. The value is on the next line.\n - * - * This function reads a couplet, determines the type of data, and - * passes the value to the the appropriate handler function of - * \p creationInterface.\n - * - * \p fp is advanced so that the next call to \p readDXFGroups() reads - * the next couplet in the file. - * - * @param fp Handle of input file - * @param creationInterface Handle of class which processes entities - * in the file - * - * @retval true If EOF not reached. - * @retval false If EOF reached. - */ -bool DL_Dxf::readDxfGroups(FILE *fp, DL_CreationInterface* creationInterface) { - - static int line = 1; - - // Read one group of the DXF file and strip the lines: - if (DL_Dxf::getStrippedLine(groupCodeTmp, DL_DXF_MAXLINE, fp) && - DL_Dxf::getStrippedLine(groupValue, DL_DXF_MAXLINE, fp) ) { - - groupCode = static_cast(toInt(groupCodeTmp)); - - creationInterface->processCodeValuePair(groupCode, groupValue); - line+=2; - processDXFGroup(creationInterface, groupCode, groupValue); - } - - return !feof(fp); -} - - - -/** - * Same as above but for stringstreams. - */ -bool DL_Dxf::readDxfGroups(std::stringstream& stream, - DL_CreationInterface* creationInterface) { - - static int line = 1; - - // Read one group of the DXF file and chop the lines: - if (DL_Dxf::getStrippedLine(groupCodeTmp, DL_DXF_MAXLINE, stream) && - DL_Dxf::getStrippedLine(groupValue, DL_DXF_MAXLINE, stream) ) { - - groupCode = static_cast(toInt(groupCodeTmp)); - - line+=2; - processDXFGroup(creationInterface, groupCode, groupValue); - } - return !stream.eof(); -} - - - -/** - * @brief Reads line from file & strips whitespace at start and newline - * at end. - * - * @param s Output\n - * Pointer to character array that chopped line will be returned in. - * @param size Size of \p s. (Including space for NULL.) - * @param fp Input\n - * Handle of input file. - * - * @retval true if line could be read - * @retval false if \p fp is already at end of file - * - * @todo Change function to use safer FreeBSD strl* functions - * @todo Is it a problem if line is blank (i.e., newline only)? - * Then, when function returns, (s==NULL). - */ -bool DL_Dxf::getStrippedLine(std::string& s, unsigned int size, FILE *fp) { - if (!feof(fp)) { - // The whole line in the file. Includes space for NULL. - char* wholeLine = new char[size]; - // Only the useful part of the line - char* line; - - line = fgets(wholeLine, size, fp); - - if (line!=nullptr && line[0] != '\0') { // Evaluates to fgets() retval - // line == wholeLine at this point. - // Both guaranteed to be NULL terminated. - - // Strip leading whitespace and trailing CR/LF. - stripWhiteSpace(&line); - - s = line; - assert(size > s.length()); - } - - delete[] wholeLine; // Done with wholeLine - - return true; - } else { - s = ""; - return false; - } -} - - - -/** - * Same as above but for stringstreams. - */ -bool DL_Dxf::getStrippedLine(std::string &s, unsigned int size, - std::stringstream& stream) { - - if (!stream.eof()) { - // Only the useful part of the line - char* line = new char[size+1]; - char* oriLine = line; - stream.getline(line, size); - stripWhiteSpace(&line); - s = line; - assert(size > s.length()); - delete[] oriLine; - return true; - } else { - s[0] = '\0'; - return false; - } -} - - - -/** - * @brief Strips leading whitespace and trailing Carriage Return (CR) - * and Line Feed (LF) from NULL terminated string. - * - * @param s Input and output. - * NULL terminates string. - * - * @retval true if \p s is non-NULL - * @retval false if \p s is NULL - */ -bool DL_Dxf::stripWhiteSpace(char** s) { - // last non-NULL char: - int lastChar = static_cast( strlen(*s) ) - 1; - - // Is last character CR or LF? - while ( (lastChar >= 0) && - (((*s)[lastChar] == 10) || ((*s)[lastChar] == 13) || - ((*s)[lastChar] == ' ' || ((*s)[lastChar] == '\t'))) ) { - (*s)[lastChar] = '\0'; - lastChar--; - } - - // Skip whitespace, excluding \n, at beginning of line - while ((*s)[0]==' ' || (*s)[0]=='\t') { - ++(*s); - } - - return ((*s) ? true : false); -} - - - -/** - * Processes a group (pair of group code and value). - * - * @param creationInterface Handle to class that creates entities and - * other CAD data from DXF group codes - * - * @param groupCode Constant indicating the data type of the group. - * @param groupValue The data value. - * - * @retval true if done processing current entity and new entity begun - * @retval false if not done processing current entity -*/ -bool DL_Dxf::processDXFGroup(DL_CreationInterface* creationInterface, - int groupCode, const std::string& groupValue) { - - //printf("%d\n", groupCode); - //printf("%s\n", groupValue.c_str()); - - // Init values on first call - if (firstCall) { - settingValue[0] = '\0'; - firstCall=false; - } - - // Indicates comment or dxflib version: - if (groupCode==999) { - if (!groupValue.empty()) { - if (groupValue.substr(0, 6)=="dxflib") { - libVersion = getLibVersion(groupValue.substr(7)); - } - - addComment(creationInterface, groupValue); - } - } - - // Indicates start of new entity or variable: - else if (groupCode==0 || groupCode==9) { - // If new entity is encountered, the last one is complete. - // Prepare default attributes for next entity: - std::string layer = getStringValue(8, "0"); - - int width; - // Compatibility with qcad1: - if (hasValue(39) && !hasValue(370)) { - width = getIntValue(39, -1); - } - // since autocad 2002: - else if (hasValue(370)) { - width = getIntValue(370, -1); - } - // default to BYLAYER: - else { - width = -1; - } - - int color; - color = getIntValue(62, 256); - int color24; - color24 = getIntValue(420, -1); - int handle; - handle = getIntValue(5, -1); - - std::string linetype = getStringValue(6, "BYLAYER"); - - attrib = DL_Attributes(layer, // layer - color, // color - color24, // 24 bit color - width, // width - linetype, // linetype - handle); // handle - attrib.setInPaperSpace( static_cast(getIntValue(67, 0))); - attrib.setLinetypeScale(getRealValue(48, 1.0)); - creationInterface->setAttributes(attrib); - - int elevationGroupCode=30; - if (currentObjectType==DL_ENTITY_LWPOLYLINE ) { - // see lwpolyline group codes reference - elevationGroupCode=38; - } - else { - // see polyline group codes reference - elevationGroupCode=30; - } - - creationInterface->setExtrusion(getRealValue(210, 0.0), - getRealValue(220, 0.0), - getRealValue(230, 1.0), - getRealValue(elevationGroupCode, 0.0)); - - // Add the previously parsed entity via creationInterface - switch (currentObjectType) { - case DL_SETTING: - addSetting(creationInterface); - break; - - case DL_LAYER: - addLayer(creationInterface); - break; - - case DL_LINETYPE: - addLinetype(creationInterface); - break; - - case DL_BLOCK: - addBlock(creationInterface); - break; - - case DL_ENDBLK: - endBlock(creationInterface); - break; - - case DL_STYLE: - addTextStyle(creationInterface); - break; - - case DL_ENTITY_POINT: - addPoint(creationInterface); - break; - - case DL_ENTITY_LINE: - addLine(creationInterface); - break; - - case DL_ENTITY_XLINE: - addXLine(creationInterface); - break; - - case DL_ENTITY_RAY: - addRay(creationInterface); - break; - - case DL_ENTITY_POLYLINE: - case DL_ENTITY_LWPOLYLINE: - addPolyline(creationInterface); - break; - - case DL_ENTITY_VERTEX: - addVertex(creationInterface); - break; - - case DL_ENTITY_SPLINE: - addSpline(creationInterface); - break; - - case DL_ENTITY_ARC: - addArc(creationInterface); - break; - - case DL_ENTITY_CIRCLE: - addCircle(creationInterface); - break; - - case DL_ENTITY_ELLIPSE: - addEllipse(creationInterface); - break; - - case DL_ENTITY_INSERT: - addInsert(creationInterface); - break; - - case DL_ENTITY_MTEXT: - addMText(creationInterface); - break; - - case DL_ENTITY_TEXT: - addText(creationInterface); - break; - - case DL_ENTITY_ATTRIB: - addAttribute(creationInterface); - break; - - case DL_ENTITY_DIMENSION: { - int type = (getIntValue(70, 0)&0x07); - - switch (type) { - case 0: - addDimLinear(creationInterface); - break; - - case 1: - addDimAligned(creationInterface); - break; - - case 2: - addDimAngular(creationInterface); - break; - - case 3: - addDimDiametric(creationInterface); - break; - - case 4: - addDimRadial(creationInterface); - break; - - case 5: - addDimAngular3P(creationInterface); - break; - - case 6: - addDimOrdinate(creationInterface); - break; - - default: - break; - } - } - break; - - case DL_ENTITY_LEADER: - addLeader(creationInterface); - break; - - case DL_ENTITY_HATCH: - //addHatch(creationInterface); - handleHatchData(creationInterface); - break; - - case DL_ENTITY_IMAGE: - addImage(creationInterface); - break; - - case DL_ENTITY_IMAGEDEF: - addImageDef(creationInterface); - break; - - case DL_ENTITY_TRACE: - addTrace(creationInterface); - break; - - case DL_ENTITY_3DFACE: - add3dFace(creationInterface); - break; - - case DL_ENTITY_SOLID: - addSolid(creationInterface); - break; - - case DL_ENTITY_SEQEND: - endSequence(creationInterface); - break; - - default: - break; - } - - creationInterface->endSection(); - - // reset all values (they are not persistent and only this - // way we can set defaults for omitted values) -// for (int i=0; iaddComment(comment); -} - -void DL_Dxf::addDictionary(DL_CreationInterface* creationInterface) { - creationInterface->addDictionary(DL_DictionaryData(getStringValue(5, ""))); -} - -void DL_Dxf::addDictionaryEntry(DL_CreationInterface* creationInterface) { - creationInterface->addDictionaryEntry(DL_DictionaryEntryData(getStringValue(3, ""), getStringValue(350, ""))); -} - - - -/** - * Adds a variable from the DXF file. - */ -void DL_Dxf::addSetting(DL_CreationInterface* creationInterface) { - int c = -1; - std::map::iterator it = values.begin(); - if (it!=values.end()) { - c = it->first; - } -// for (int i=0; i<=380; ++i) { -// if (values[i][0]!='\0') { -// c = i; -// break; -// } -// } - - // string - if (c>=0 && c<=9) { - creationInterface->setVariableString(settingKey, values[c], c); - #ifdef DL_COMPAT - // backwards compatibility: - creationInterface->setVariableString(settingKey.c_str(), values[c].c_str(), c); - #endif - } - // vector - else if (c>=10 && c<=39) { - if (c==10) { - creationInterface->setVariableVector( - settingKey, - getRealValue(c, 0.0), - getRealValue(c+10, 0.0), - getRealValue(c+20, 0.0), - c); - } - } - // double - else if (c>=40 && c<=59) { - creationInterface->setVariableDouble(settingKey, getRealValue(c, 0.0), c); - } - // int - else if (c>=60 && c<=99) { - creationInterface->setVariableInt(settingKey, getIntValue(c, 0), c); - } - // misc - else if (c>=0) { - creationInterface->setVariableString(settingKey, getStringValue(c, ""), c); - } -} - - - -/** - * Adds a layer that was read from the file via the creation interface. - */ -void DL_Dxf::addLayer(DL_CreationInterface* creationInterface) { - // correct some invalid attributes for layers: - attrib = creationInterface->getAttributes(); - if (attrib.getColor()==256 || attrib.getColor()==0) { - attrib.setColor(7); - } - if (attrib.getWidth()<0) { - attrib.setWidth(1); - } - - std::string linetype = attrib.getLinetype(); - std::transform(linetype.begin(), linetype.end(), linetype.begin(), ::toupper); - if (linetype=="BYLAYER" || linetype=="BYBLOCK") { - attrib.setLinetype("CONTINUOUS"); - } - - // add layer - std::string name = getStringValue(2, ""); - if (name.length()==0) { - return; - } - - creationInterface->addLayer(DL_LayerData(name, getIntValue(70, 0))); -} - -/** - * Adds a linetype that was read from the file via the creation interface. - */ -void DL_Dxf::addLinetype(DL_CreationInterface* creationInterface) { - std::string name = getStringValue(2, ""); - if (name.length()==0) { - return; - } - int numDashes = getIntValue(73, 0); - //double dashes[numDashes]; - - DL_LinetypeData d( - // name: - name, - // description: - getStringValue(3, ""), - // flags - getIntValue(70, 0), - // number of dashes: - numDashes, - // pattern length: - getRealValue(40, 0.0) - // pattern: - //dashes - ); - - if (name != "By Layer" && name != "By Block" && name != "BYLAYER" && name != "BYBLOCK") { - creationInterface->addLinetype(d); - } -} - -/** - * Handles all dashes in linetype pattern. - */ -bool DL_Dxf::handleLinetypeData(DL_CreationInterface* creationInterface) { - if (groupCode == 49) { - creationInterface->addLinetypeDash(toReal(groupValue)); - return true; - } - - return false; -} - - -/** - * Adds a block that was read from the file via the creation interface. - */ -void DL_Dxf::addBlock(DL_CreationInterface* creationInterface) { - std::string name = getStringValue(2, ""); - if (name.length()==0) { - return; - } - - DL_BlockData d( - // Name: - name, - // flags: - getIntValue(70, 0), - // base point: - getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0)); - - creationInterface->addBlock(d); -} - - - -/** - * Ends a block that was read from the file via the creation interface. - */ -void DL_Dxf::endBlock(DL_CreationInterface* creationInterface) { - creationInterface->endBlock(); -} - - - -void DL_Dxf::addTextStyle(DL_CreationInterface* creationInterface) { - std::string name = getStringValue(2, ""); - if (name.length()==0) { - return; - } - - DL_StyleData d( - // name: - name, - // flags - getIntValue(70, 0), - // fixed text height: - getRealValue(40, 0.0), - // width factor: - getRealValue(41, 0.0), - // oblique angle: - getRealValue(50, 0.0), - // text generation flags: - getIntValue(71, 0), - // last height used: - getRealValue(42, 0.0), - // primart font file: - getStringValue(3, ""), - // big font file: - getStringValue(4, "") - ); - creationInterface->addTextStyle(d); -} - - -/** - * Adds a point entity that was read from the file via the creation interface. - */ -void DL_Dxf::addPoint(DL_CreationInterface* creationInterface) { - DL_PointData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0)); - creationInterface->addPoint(d); -} - - - -/** - * Adds a line entity that was read from the file via the creation interface. - */ -void DL_Dxf::addLine(DL_CreationInterface* creationInterface) { - DL_LineData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0)); - - creationInterface->addLine(d); -} - -/** - * Adds an xline entity that was read from the file via the creation interface. - */ -void DL_Dxf::addXLine(DL_CreationInterface* creationInterface) { - DL_XLineData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0)); - - creationInterface->addXLine(d); -} - -/** - * Adds a ray entity that was read from the file via the creation interface. - */ -void DL_Dxf::addRay(DL_CreationInterface* creationInterface) { - DL_RayData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0)); - - creationInterface->addRay(d); -} - - - -/** - * Adds a polyline entity that was read from the file via the creation interface. - */ -void DL_Dxf::addPolyline(DL_CreationInterface* creationInterface) { - DL_PolylineData pd(maxVertices, getIntValue(71, 0), getIntValue(72, 0), getIntValue(70, 0)); - creationInterface->addPolyline(pd); - - maxVertices = std::min(maxVertices, vertexIndex+1); - - if (currentObjectType==DL_ENTITY_LWPOLYLINE) { - for (int i=0; iaddVertex(d); - } - creationInterface->endEntity(); - } -} - - - -/** - * Adds a polyline vertex entity that was read from the file - * via the creation interface. - */ -void DL_Dxf::addVertex(DL_CreationInterface* creationInterface) { - - // vertex defines a face of the mesh if its vertex flags group has the - // 128 bit set but not the 64 bit. 10, 20, 30 are irrelevant and set to - // 0 in this case - if ((getIntValue(70, 0)&128) && !(getIntValue(70, 0)&64)) { - return; - } - - DL_VertexData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(42, 0.0)); - - creationInterface->addVertex(d); -} - - -/** - * Adds a spline entity that was read from the file via the creation interface. - */ -void DL_Dxf::addSpline(DL_CreationInterface* creationInterface) { - DL_SplineData sd(getIntValue(71, 3), - maxKnots, - maxControlPoints, - maxFitPoints, - getIntValue(70, 4)); - - sd.tangentStartX = getRealValue(12, 0.0); - sd.tangentStartY = getRealValue(22, 0.0); - sd.tangentStartZ = getRealValue(32, 0.0); - sd.tangentEndX = getRealValue(13, 0.0); - sd.tangentEndY = getRealValue(23, 0.0); - sd.tangentEndZ = getRealValue(33, 0.0); - - creationInterface->addSpline(sd); - - int i; - for (i=0; iaddControlPoint(d); - } - for (i=0; iaddFitPoint(d); - } - for (i=0; iaddKnot(k); - } - creationInterface->endEntity(); -} - - - -/** - * Adds an arc entity that was read from the file via the creation interface. - */ -void DL_Dxf::addArc(DL_CreationInterface* creationInterface) { - DL_ArcData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(40, 0.0), - getRealValue(50, 0.0), - getRealValue(51, 0.0)); - - creationInterface->addArc(d); -} - - - -/** - * Adds a circle entity that was read from the file via the creation interface. - */ -void DL_Dxf::addCircle(DL_CreationInterface* creationInterface) { - DL_CircleData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(40, 0.0)); - - creationInterface->addCircle(d); -} - - - -/** - * Adds an ellipse entity that was read from the file via the creation interface. - */ -void DL_Dxf::addEllipse(DL_CreationInterface* creationInterface) { - DL_EllipseData d(getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0), - getRealValue(40, 1.0), - getRealValue(41, 0.0), - getRealValue(42, 2*M_PI)); - - creationInterface->addEllipse(d); -} - - - -/** - * Adds an insert entity that was read from the file via the creation interface. - */ -void DL_Dxf::addInsert(DL_CreationInterface* creationInterface) { - //printf("addInsert\n"); - //printf("code 50: %s\n", values[50]); - //printf("code 50 length: %d\n", strlen(values[50])); - //printf("code 50:\n"); - //getRealValue(50, 0.0); - - std::string name = getStringValue(2, ""); - if (name.length()==0) { - return; - } - - DL_InsertData d(name, - // insertion point - getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - // scale: - getRealValue(41, 1.0), - getRealValue(42, 1.0), - getRealValue(43, 1.0), - // angle (deg): - getRealValue(50, 0.0), - // cols / rows: - getIntValue(70, 1), - getIntValue(71, 1), - // spacing: - getRealValue(44, 0.0), - getRealValue(45, 0.0)); - - creationInterface->addInsert(d); -} - - - -/** - * Adds a trace entity (4 edge closed polyline) that was read from the file via the creation interface. - * - * @author AHM - */ -void DL_Dxf::addTrace(DL_CreationInterface* creationInterface) { - DL_TraceData td; - - for (int k = 0; k < 4; k++) { - td.x[k] = getRealValue(10 + k, 0.0); - td.y[k] = getRealValue(20 + k, 0.0); - td.z[k] = getRealValue(30 + k, 0.0); - } - creationInterface->addTrace(td); -} - - - -/** - * Adds a 3dface entity that was read from the file via the creation interface. - */ -void DL_Dxf::add3dFace(DL_CreationInterface* creationInterface) { - DL_3dFaceData td; - - for (int k = 0; k < 4; k++) { - td.x[k] = getRealValue(10 + k, 0.0); - td.y[k] = getRealValue(20 + k, 0.0); - td.z[k] = getRealValue(30 + k, 0.0); - } - creationInterface->add3dFace(td); -} - - - -/** - * Adds a solid entity (filled trace) that was read from the file via the creation interface. - * - * @author AHM - */ -void DL_Dxf::addSolid(DL_CreationInterface* creationInterface) { - DL_SolidData sd; - - for (int k = 0; k < 4; k++) { - sd.x[k] = getRealValue(10 + k, 0.0); - sd.y[k] = getRealValue(20 + k, 0.0); - sd.z[k] = getRealValue(30 + k, 0.0); - } - creationInterface->addSolid(sd); -} - - -/** - * Adds an MText entity that was read from the file via the creation interface. - */ -void DL_Dxf::addMText(DL_CreationInterface* creationInterface) { - double angle = 0.0; - - if (hasValue(50)) { - if (libVersion<=0x02000200) { - // wrong but compatible with dxflib <=2.0.2.0: - angle = getRealValue(50, 0.0); - } else { - angle = (getRealValue(50, 0.0)*2*M_PI)/360.0; - } - } else if (hasValue(11) && hasValue(21)) { - double x = getRealValue(11, 0.0); - double y = getRealValue(21, 0.0); - - if (fabs(x)<1.0e-6) { - if (y>0.0) { - angle = M_PI/2.0; - } else { - angle = M_PI/2.0*3.0; - } - } else { - angle = atan(y/x); - } - } - - DL_MTextData d( - // insertion point - getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - // X direction vector - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0), - // height - getRealValue(40, 2.5), - // width - getRealValue(41, 0.0), - // attachment point - getIntValue(71, 1), - // drawing direction - getIntValue(72, 1), - // line spacing style - getIntValue(73, 1), - // line spacing factor - getRealValue(44, 1.0), - // text - getStringValue(1, ""), - // style - getStringValue(7, ""), - // angle - angle); - creationInterface->addMText(d); -} - -/** - * Handles all XRecord data. - */ -bool DL_Dxf::handleXRecordData(DL_CreationInterface* creationInterface) { - if (groupCode==105) { - return false; - } - - if (groupCode==5) { - creationInterface->addXRecord(groupValue); - return true; - } - - if (groupCode==280) { - xRecordValues = true; - return true; - } - - if (!xRecordValues) { - return false; - } - - // string: - if (groupCode<=9 || - groupCode==100 || groupCode==102 || groupCode==105 || - (groupCode>=300 && groupCode<=369) || - (groupCode>=1000 && groupCode<=1009)) { - - creationInterface->addXRecordString(groupCode, groupValue); - return true; - } - - // int: - else if ((groupCode>=60 && groupCode<=99) || (groupCode>=160 && groupCode<=179) || (groupCode>=270 && groupCode<=289)) { - creationInterface->addXRecordInt(groupCode, toInt(groupValue)); - return true; - } - - // bool: - else if (groupCode>=290 && groupCode<=299) { - creationInterface->addXRecordBool(groupCode, toBool(groupValue)); - return true; - } - - // double: - else if ((groupCode>=10 && groupCode<=59) || (groupCode>=110 && groupCode<=149) || (groupCode>=210 && groupCode<=239)) { - creationInterface->addXRecordReal(groupCode, toReal(groupValue)); - return true; - } - - return false; -} - -/** - * Handles all dictionary data. - */ -bool DL_Dxf::handleDictionaryData(DL_CreationInterface* creationInterface) { - if (groupCode==3) { - return true; - } - - if (groupCode==5) { - creationInterface->addDictionary(DL_DictionaryData(groupValue)); - return true; - } - - if (groupCode==350) { - creationInterface->addDictionaryEntry(DL_DictionaryEntryData(getStringValue(3, ""), groupValue)); - return true; - } - return false; -} - - - -/** - * Handles XData for all object types. - */ -bool DL_Dxf::handleXData(DL_CreationInterface* creationInterface) { - if (groupCode==1001) { - creationInterface->addXDataApp(groupValue); - return true; - } - else if (groupCode>=1000 && groupCode<=1009) { - creationInterface->addXDataString(groupCode, groupValue); - return true; - } - else if (groupCode>=1010 && groupCode<=1059) { - creationInterface->addXDataReal(groupCode, toReal(groupValue)); - return true; - } - else if (groupCode>=1060 && groupCode<=1070) { - creationInterface->addXDataInt(groupCode, toInt(groupValue)); - return true; - } - else if (groupCode==1071) { - creationInterface->addXDataInt(groupCode, toInt(groupValue)); - return true; - } - - return false; -} - -/** - * Handles additional MText data. - */ -bool DL_Dxf::handleMTextData(DL_CreationInterface* creationInterface) { - // Special handling of text chunks for MTEXT entities: - if (groupCode==3) { - creationInterface->addMTextChunk(groupValue); - return true; - } - - return false; -} - - - -/** - * Handles additional polyline data. - */ -bool DL_Dxf::handleLWPolylineData(DL_CreationInterface* /*creationInterface*/) { - // Allocate LWPolyline vertices (group code 90): - if (groupCode==90) { - maxVertices = toInt(groupValue); - if (maxVertices>0) { - if (vertices!=nullptr) { - delete[] vertices; - } - vertices = new double[4*maxVertices]; - for (int i=0; i=0 && vertexIndex0) { - if (knots!=nullptr) { - delete[] knots; - } - knots = new double[maxKnots]; - for (int i=0; i0) { - if (controlPoints!=nullptr) { - delete[] controlPoints; - } - if (weights!=nullptr) { - delete[] weights; - } - controlPoints = new double[3*maxControlPoints]; - weights = new double[maxControlPoints]; - for (int i=0; i0) { - if (fitPoints!=nullptr) { - delete[] fitPoints; - } - fitPoints = new double[3*maxFitPoints]; - for (int i=0; i=0 && controlPointIndex=0 && fitPointIndex=0 && weightIndex0) { - if (leaderVertices!=nullptr) { - delete[] leaderVertices; - } - leaderVertices = new double[3*maxLeaderVertices]; - for (int i=0; i=0 && - leaderVertexIndexaddText(d); -} - - - -/** - * Adds an attrib entity that was read from the file via the creation interface. - * @todo add attrib instead of normal text - */ -void DL_Dxf::addAttribute(DL_CreationInterface* creationInterface) { - DL_AttributeData d( - // insertion point - getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - // alignment point - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0), - // height - getRealValue(40, 2.5), - // x scale - getRealValue(41, 1.0), - // generation flags - getIntValue(71, 0), - // h just - getIntValue(72, 0), - // v just - getIntValue(74, 0), - // tag - getStringValue(2, ""), - // text - getStringValue(1, ""), - // style - getStringValue(7, ""), - // angle - (getRealValue(50, 0.0)*2*M_PI)/360.0); - - creationInterface->addAttribute(d); -} - - - -/** - * @return dimension data from current values. - */ -DL_DimensionData DL_Dxf::getDimData() { - // generic dimension data: - return DL_DimensionData( - // def point - getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - // text middle point - getRealValue(11, 0.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0), - // type - getIntValue(70, 0), - // attachment point - getIntValue(71, 5), - // line sp. style - getIntValue(72, 1), - // line sp. factor - getRealValue(41, 1.0), - // text - getStringValue(1, ""), - // style - getStringValue(3, ""), - // angle - getRealValue(53, 0.0)); -} - - - -/** - * Adds a linear dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimLinear(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - // horizontal / vertical / rotated dimension: - DL_DimLinearData dl( - // definition point 1 - getRealValue(13, 0.0), - getRealValue(23, 0.0), - getRealValue(33, 0.0), - // definition point 2 - getRealValue(14, 0.0), - getRealValue(24, 0.0), - getRealValue(34, 0.0), - // angle - getRealValue(50, 0.0), - // oblique - getRealValue(52, 0.0)); - creationInterface->addDimLinear(d, dl); -} - - - -/** - * Adds an aligned dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimAligned(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - // aligned dimension: - DL_DimAlignedData da( - // extension point 1 - getRealValue(13, 0.0), - getRealValue(23, 0.0), - getRealValue(33, 0.0), - // extension point 2 - getRealValue(14, 0.0), - getRealValue(24, 0.0), - getRealValue(34, 0.0)); - creationInterface->addDimAlign(d, da); -} - - - -/** - * Adds a radial dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimRadial(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - DL_DimRadialData dr( - // definition point - getRealValue(15, 0.0), - getRealValue(25, 0.0), - getRealValue(35, 0.0), - // leader length: - getRealValue(40, 0.0)); - creationInterface->addDimRadial(d, dr); -} - - - -/** - * Adds a diametric dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimDiametric(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - // diametric dimension: - DL_DimDiametricData dr( - // definition point - getRealValue(15, 0.0), - getRealValue(25, 0.0), - getRealValue(35, 0.0), - // leader length: - getRealValue(40, 0.0)); - creationInterface->addDimDiametric(d, dr); -} - - - -/** - * Adds an angular dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimAngular(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - // angular dimension: - DL_DimAngularData da( - // definition point 1 - getRealValue(13, 0.0), - getRealValue(23, 0.0), - getRealValue(33, 0.0), - // definition point 2 - getRealValue(14, 0.0), - getRealValue(24, 0.0), - getRealValue(34, 0.0), - // definition point 3 - getRealValue(15, 0.0), - getRealValue(25, 0.0), - getRealValue(35, 0.0), - // definition point 4 - getRealValue(16, 0.0), - getRealValue(26, 0.0), - getRealValue(36, 0.0)); - creationInterface->addDimAngular(d, da); -} - - -/** - * Adds an angular dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimAngular3P(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - // angular dimension (3P): - DL_DimAngular3PData da( - // definition point 1 - getRealValue(13, 0.0), - getRealValue(23, 0.0), - getRealValue(33, 0.0), - // definition point 2 - getRealValue(14, 0.0), - getRealValue(24, 0.0), - getRealValue(34, 0.0), - // definition point 3 - getRealValue(15, 0.0), - getRealValue(25, 0.0), - getRealValue(35, 0.0)); - creationInterface->addDimAngular3P(d, da); -} - - - -/** - * Adds an ordinate dimension entity that was read from the file via the creation interface. - */ -void DL_Dxf::addDimOrdinate(DL_CreationInterface* creationInterface) { - DL_DimensionData d = getDimData(); - - // ordinate dimension: - DL_DimOrdinateData dl( - // definition point 1 - getRealValue(13, 0.0), - getRealValue(23, 0.0), - getRealValue(33, 0.0), - // definition point 2 - getRealValue(14, 0.0), - getRealValue(24, 0.0), - getRealValue(34, 0.0), - (getIntValue(70, 0)&64)==64 // true: X-type, false: Y-type - ); - creationInterface->addDimOrdinate(d, dl); -} - - - -/** - * Adds a leader entity that was read from the file via the creation interface. - */ -void DL_Dxf::addLeader(DL_CreationInterface* creationInterface) { - // leader (arrow) - DL_LeaderData le( - // arrow head flag - getIntValue(71, 1), - // leader path type - getIntValue(72, 0), - // Leader creation flag - getIntValue(73, 3), - // Hookline direction flag - getIntValue(74, 1), - // Hookline flag - getIntValue(75, 0), - // Text annotation height - getRealValue(40, 1.0), - // Text annotation width - getRealValue(41, 1.0), - // Number of vertices in leader - getIntValue(76, 0) - ); - creationInterface->addLeader(le); - - for (int i=0; iaddLeaderVertex(d); - } - creationInterface->endEntity(); -} - -/** - * Adds a hatch entity that was read from the file via the creation interface. - */ -void DL_Dxf::addHatch(DL_CreationInterface* creationInterface) { - DL_HatchData hd(getIntValue(91, 1), - getIntValue(70, 0), - getRealValue(41, 1.0), - getRealValue(52, 0.0), - getStringValue(2, "")); - - creationInterface->addHatch(hd); - - for (size_t i=0; iaddHatchLoop(DL_HatchLoopData(hatchEdges[i].size())); - for (unsigned int k=0; kaddHatchEdge(DL_HatchEdgeData(hatchEdges[i][k])); - } - } - - creationInterface->endEntity(); -} - -void DL_Dxf::addHatchLoop() { - addHatchEdge(); - hatchEdges.push_back(std::vector()); -} - -void DL_Dxf::addHatchEdge() { - if (hatchEdge.defined) { - if (hatchEdges.size()>0) { - hatchEdges.back().push_back(hatchEdge); - } - hatchEdge = DL_HatchEdgeData(); - } -} - -/** - * Handles all hatch data. - */ -bool DL_Dxf::handleHatchData(DL_CreationInterface* creationInterface) { - // New polyline loop, group code 92 - // or new loop with individual edges, group code 93 - if (groupCode==92 || groupCode==93) { - if (firstHatchLoop) { - hatchEdges.clear(); - firstHatchLoop = false; - } - if (groupCode==92 && (toInt(groupValue)&2)==2) { - addHatchLoop(); - } - if (groupCode==93) { - addHatchLoop(); - } - return true; - } - - // New hatch edge or new section / entity: add last hatch edge: - if (groupCode==72 || groupCode==0 || groupCode==78 || groupCode==98) { - // polyline boundaries use code 72 for bulge flag: - if (groupCode!=72 || (getIntValue(92, 0)&2)==0) { - addHatchEdge(); - } - - if (groupCode==0 /*|| groupCode==78*/) { - addHatch(creationInterface); - } - else { - hatchEdge.type = toInt(groupValue); - } - return true; - } - - // polyline boundary: - if ((getIntValue(92, 0)&2)==2) { - switch (groupCode) { - case 10: - hatchEdge.type = 0; - hatchEdge.vertices.push_back(std::vector()); - hatchEdge.vertices.back().push_back(toReal(groupValue)); - return true; - case 20: - if (!hatchEdge.vertices.empty()) { - hatchEdge.vertices.back().push_back(toReal(groupValue)); - hatchEdge.defined = true; - } - return true; - case 42: - if (!hatchEdge.vertices.empty()) { - hatchEdge.vertices.back().push_back(toReal(groupValue)); - hatchEdge.defined = true; - } - return true; - } - } - else { - // Line edge: - if (hatchEdge.type==1) { - switch (groupCode) { - case 10: - hatchEdge.x1 = toReal(groupValue); - return true; - case 20: - hatchEdge.y1 = toReal(groupValue); - return true; - case 11: - hatchEdge.x2 = toReal(groupValue); - return true; - case 21: - hatchEdge.y2 = toReal(groupValue); - hatchEdge.defined = true; - return true; - } - } - - // Arc edge: - if (hatchEdge.type==2) { - switch(groupCode) { - case 10: - hatchEdge.cx = toReal(groupValue); - return true; - case 20: - hatchEdge.cy = toReal(groupValue); - return true; - case 40: - hatchEdge.radius = toReal(groupValue); - return true; - case 50: - hatchEdge.angle1 = toReal(groupValue)/360.0*2*M_PI; - return true; - case 51: - hatchEdge.angle2 = toReal(groupValue)/360.0*2*M_PI; - return true; - case 73: - hatchEdge.ccw = static_cast(toInt(groupValue)); - hatchEdge.defined = true; - return true; - } - } - - // Ellipse arc edge: - if (hatchEdge.type==3) { - switch (groupCode) { - case 10: - hatchEdge.cx = toReal(groupValue); - return true; - case 20: - hatchEdge.cy = toReal(groupValue); - return true; - case 11: - hatchEdge.mx = toReal(groupValue); - return true; - case 21: - hatchEdge.my = toReal(groupValue); - return true; - case 40: - hatchEdge.ratio = toReal(groupValue); - return true; - case 50: - hatchEdge.angle1 = toReal(groupValue)/360.0*2*M_PI; - return true; - case 51: - hatchEdge.angle2 = toReal(groupValue)/360.0*2*M_PI; - return true; - case 73: - hatchEdge.ccw = static_cast(toInt(groupValue)); - hatchEdge.defined = true; - return true; - } - } - - // Spline edge: - if (hatchEdge.type==4) { - switch (groupCode) { - case 94: - hatchEdge.degree = toInt(groupValue); - return true; - case 73: - hatchEdge.rational = toBool(groupValue); - return true; - case 74: - hatchEdge.periodic = toBool(groupValue); - return true; - case 95: - hatchEdge.nKnots = toInt(groupValue); - return true; - case 96: - hatchEdge.nControl = toInt(groupValue); - return true; - case 97: - hatchEdge.nFit = toInt(groupValue); - return true; - case 40: - if (hatchEdge.knots.size() < hatchEdge.nKnots) { - hatchEdge.knots.push_back(toReal(groupValue)); - } - return true; - case 10: - if (hatchEdge.controlPoints.size() < hatchEdge.nControl) { - std::vector v; - v.push_back(toReal(groupValue)); - hatchEdge.controlPoints.push_back(v); - } - return true; - case 20: - if (!hatchEdge.controlPoints.empty() && hatchEdge.controlPoints.back().size()==1) { - hatchEdge.controlPoints.back().push_back(toReal(groupValue)); - } - hatchEdge.defined = true; - return true; - case 42: - if (hatchEdge.weights.size() < hatchEdge.nControl) { - hatchEdge.weights.push_back(toReal(groupValue)); - } - return true; - case 11: - if (hatchEdge.fitPoints.size() < hatchEdge.nFit) { - std::vector v; - v.push_back(toReal(groupValue)); - hatchEdge.fitPoints.push_back(v); - } - return true; - case 21: - if (!hatchEdge.fitPoints.empty() && hatchEdge.fitPoints.back().size()==1) { - hatchEdge.fitPoints.back().push_back(toReal(groupValue)); - } - hatchEdge.defined = true; - return true; - case 12: - hatchEdge.startTangentX = toReal(groupValue); - return true; - case 22: - hatchEdge.startTangentY = toReal(groupValue); - return true; - case 13: - hatchEdge.endTangentX = toReal(groupValue); - return true; - case 23: - hatchEdge.endTangentY = toReal(groupValue); - return true; - } - } - } - - return false; -} - - -/** - * Adds an image entity that was read from the file via the creation interface. - */ -void DL_Dxf::addImage(DL_CreationInterface* creationInterface) { - DL_ImageData id(// pass ref insead of name we don't have yet - getStringValue(340, ""), - // ins point: - getRealValue(10, 0.0), - getRealValue(20, 0.0), - getRealValue(30, 0.0), - // u vector: - getRealValue(11, 1.0), - getRealValue(21, 0.0), - getRealValue(31, 0.0), - // v vector: - getRealValue(12, 0.0), - getRealValue(22, 1.0), - getRealValue(32, 0.0), - // image size (pixel): - getIntValue(13, 1), - getIntValue(23, 1), - // brightness, contrast, fade - getIntValue(281, 50), - getIntValue(282, 50), - getIntValue(283, 0)); - - creationInterface->addImage(id); - creationInterface->endEntity(); - currentObjectType = DL_UNKNOWN; -} - - - -/** - * Adds an image definition that was read from the file via the creation interface. - */ -void DL_Dxf::addImageDef(DL_CreationInterface* creationInterface) { - DL_ImageDefData id(// handle - getStringValue(5, ""), - getStringValue(1, "")); - - creationInterface->linkImage(id); - creationInterface->endEntity(); - currentObjectType = DL_UNKNOWN; -} - - - -/** - * Ends some special entities like hatches or old style polylines. - */ -void DL_Dxf::endEntity(DL_CreationInterface* creationInterface) { - creationInterface->endEntity(); -} - - -/** - * Ends a sequence and notifies the creation interface. - */ -void DL_Dxf::endSequence(DL_CreationInterface* creationInterface) { - creationInterface->endSequence(); -} - - -/** - * Converts the given string into an int. - * ok is set to false if there was an error. - */ -//int DL_Dxf::stringToInt(const char* s, bool* ok) { -// if (ok!=NULL) { -// // check string: -// *ok = true; -// int i=0; -// bool dot = false; -// do { -// if (s[i]=='\0') { -// break; -// } else if (s[i]=='.') { -// if (dot==true) { -// //std::cerr << "two dots\n"; -// *ok = false; -// } else { -// dot = true; -// } -// } else if (s[i]<'0' || s[i]>'9') { -// //std::cerr << "NaN: '" << s[i] << "'\n"; -// *ok = false; -// } -// i++; -// } while(s[i]!='\0' && *ok==true); -// } - -// return atoi(s); -//} - - -/** - * @brief Opens the given file for writing and returns a pointer - * to the dxf writer. This pointer needs to be passed on to other - * writing functions. - * - * @param file Full path of the file to open. - * - * @return Pointer to an ascii dxf writer object. - */ -DL_WriterA* DL_Dxf::out(const char* file, DL_Codes::version version) { - char* f = new char[strlen(file)+1]; - strcpy(f, file); - this->version = version; - - DL_WriterA* dw = new DL_WriterA(f, version); - if (dw->openFailed()) { - delete dw; - delete[] f; - return nullptr; - } else { - delete[] f; - return dw; - } -} - - - -/** - * @brief Writes a DXF header to the file currently opened - * by the given DXF writer object. - */ -void DL_Dxf::writeHeader(DL_WriterA& dw) { - dw.comment("dxflib " DL_VERSION); - dw.sectionHeader(); - - dw.dxfString(9, "$ACADVER"); - switch (version) { - case DL_Codes::AC1009: - dw.dxfString(1, "AC1009"); - break; - case DL_Codes::AC1012: - dw.dxfString(1, "AC1012"); - break; - case DL_Codes::AC1014: - dw.dxfString(1, "AC1014"); - break; - case DL_Codes::AC1015: - dw.dxfString(1, "AC1015"); - break; - } - - // Newer version require that (otherwise a*cad crashes..) - if (version==DL_VERSION_2000) { - dw.dxfString(9, "$HANDSEED"); - dw.dxfHex(5, 0xFFFF); - } - - // commented out: more variables can be added after that by caller: - //dw.sectionEnd(); -} - - - - -/** - * Writes a point entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writePoint(DL_WriterA& dw, - const DL_PointData& data, - const DL_Attributes& attrib) { - dw.entity("POINT"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbPoint"); - } - dw.entityAttributes(attrib); - dw.coord(DL_POINT_COORD_CODE, data.x, data.y, data.z); -} - - - -/** - * Writes a line entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeLine(DL_WriterA& dw, - const DL_LineData& data, - const DL_Attributes& attrib) { - dw.entity("LINE"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbLine"); - } - dw.entityAttributes(attrib); - dw.coord(DL_LINE_START_CODE, data.x1, data.y1, data.z1); - dw.coord(DL_LINE_END_CODE, data.x2, data.y2, data.z2); -} - - - -/** - * Writes an x line entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeXLine(DL_WriterA& dw, - const DL_XLineData& data, - const DL_Attributes& attrib) { - dw.entity("XLINE"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbLine"); - } - dw.entityAttributes(attrib); - dw.coord(DL_LINE_START_CODE, data.bx, data.by, data.bz); - dw.coord(DL_LINE_END_CODE, data.dx, data.dy, data.dz); -} - - - -/** - * Writes a ray entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeRay(DL_WriterA& dw, - const DL_RayData& data, - const DL_Attributes& attrib) { - dw.entity("RAY"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbLine"); - } - dw.entityAttributes(attrib); - dw.coord(DL_LINE_START_CODE, data.bx, data.by, data.bz); - dw.coord(DL_LINE_END_CODE, data.dx, data.dy, data.dz); -} - - - -/** - * Writes a polyline entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - * @see writeVertex - */ -void DL_Dxf::writePolyline(DL_WriterA& dw, - const DL_PolylineData& data, - const DL_Attributes& attrib) { - if (version==DL_VERSION_2000) { - dw.entity("LWPOLYLINE"); - dw.entityAttributes(attrib); - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbPolyline"); - dw.dxfInt(90, static_cast(data.number)); - dw.dxfInt(70, data.flags); - } else { - dw.entity("POLYLINE"); - dw.entityAttributes(attrib); - polylineLayer = attrib.getLayer(); - dw.dxfInt(66, 1); - dw.dxfInt(70, data.flags); - dw.coord(DL_VERTEX_COORD_CODE, 0.0, 0.0, 0.0); - } -} - - - -/** - * Writes a single vertex of a polyline to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeVertex(DL_WriterA& dw, - const DL_VertexData& data) { - - - if (version==DL_VERSION_2000) { - dw.dxfReal(10, data.x); - dw.dxfReal(20, data.y); - dw.dxfReal(30, data.z); - if (fabs(data.bulge)>1.0e-10) { - dw.dxfReal(42, data.bulge); - } - } else { - dw.entity("VERTEX"); - //dw.entityAttributes(attrib); - dw.dxfString(8, polylineLayer); - dw.coord(DL_VERTEX_COORD_CODE, data.x, data.y, data.z); - if (fabs(data.bulge)>1.0e-10) { - dw.dxfReal(42, data.bulge); - } - } -} - - - -/** - * Writes the polyline end. Only needed for DXF R12. - */ -void DL_Dxf::writePolylineEnd(DL_WriterA& dw) { - if (version==DL_VERSION_2000) { - } else { - dw.entity("SEQEND"); - } -} - - -/** - * Writes a spline entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - * @see writeControlPoint - */ -void DL_Dxf::writeSpline(DL_WriterA& dw, - const DL_SplineData& data, - const DL_Attributes& attrib) { - - dw.entity("SPLINE"); - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbSpline"); - } - dw.dxfInt(70, data.flags); - dw.dxfInt(71, data.degree); - dw.dxfInt(72, data.nKnots); // number of knots - dw.dxfInt(73, data.nControl); // number of control points - dw.dxfInt(74, data.nFit); // number of fit points -} - - - -/** - * Writes a single control point of a spline to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeControlPoint(DL_WriterA& dw, - const DL_ControlPointData& data) { - - dw.dxfReal(10, data.x); - dw.dxfReal(20, data.y); - dw.dxfReal(30, data.z); -} - - - -/** - * Writes a single fit point of a spline to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeFitPoint(DL_WriterA& dw, - const DL_FitPointData& data) { - - dw.dxfReal(11, data.x); - dw.dxfReal(21, data.y); - dw.dxfReal(31, data.z); -} - - - -/** - * Writes a single knot of a spline to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeKnot(DL_WriterA& dw, - const DL_KnotData& data) { - - dw.dxfReal(40, data.k); -} - - - -/** - * Writes a circle entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeCircle(DL_WriterA& dw, - const DL_CircleData& data, - const DL_Attributes& attrib) { - dw.entity("CIRCLE"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbCircle"); - } - dw.entityAttributes(attrib); - dw.coord(10, data.cx, data.cy, data.cz); - dw.dxfReal(40, data.radius); -} - - - -/** - * Writes an arc entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeArc(DL_WriterA& dw, - const DL_ArcData& data, - const DL_Attributes& attrib) { - dw.entity("ARC"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbCircle"); - } - dw.coord(10, data.cx, data.cy, data.cz); - dw.dxfReal(40, data.radius); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbArc"); - } - dw.dxfReal(50, data.angle1); - dw.dxfReal(51, data.angle2); -} - - - -/** - * Writes an ellipse entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeEllipse(DL_WriterA& dw, - const DL_EllipseData& data, - const DL_Attributes& attrib) { - - if (version>DL_VERSION_R12) { - dw.entity("ELLIPSE"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbEllipse"); - } - dw.entityAttributes(attrib); - dw.coord(10, data.cx, data.cy, data.cz); - dw.coord(11, data.mx, data.my, data.mz); - dw.dxfReal(40, data.ratio); - dw.dxfReal(41, data.angle1); - dw.dxfReal(42, data.angle2); - } -} - - - -/** - * Writes a solid entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeSolid(DL_WriterA& dw, - const DL_SolidData& data, - const DL_Attributes& attrib) { - dw.entity("SOLID"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbTrace"); - } - dw.entityAttributes(attrib); - dw.coord(10, data.x[0], data.y[0], data.z[0]); - dw.coord(11, data.x[1], data.y[1], data.z[1]); - dw.coord(12, data.x[2], data.y[2], data.z[2]); - dw.coord(13, data.x[3], data.y[3], data.z[3]); - dw.dxfReal(39, data.thickness); -} - -/** - * Writes a trace entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeTrace(DL_WriterA& dw, - const DL_TraceData& data, - const DL_Attributes& attrib) { - dw.entity("TRACE"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbTrace"); - } - dw.entityAttributes(attrib); - dw.coord(10, data.x[0], data.y[0], data.z[0]); - dw.coord(11, data.x[1], data.y[1], data.z[1]); - dw.coord(12, data.x[2], data.y[2], data.z[2]); - dw.coord(13, data.x[3], data.y[3], data.z[3]); - dw.dxfReal(39, data.thickness); -} - - - -/** - * Writes a 3d face entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::write3dFace(DL_WriterA& dw, - const DL_3dFaceData& data, - const DL_Attributes& attrib) { - dw.entity("3DFACE"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbFace"); - } - dw.entityAttributes(attrib); - dw.coord(10, data.x[0], data.y[0], data.z[0]); - dw.coord(11, data.x[1], data.y[1], data.z[1]); - dw.coord(12, data.x[2], data.y[2], data.z[2]); - dw.coord(13, data.x[3], data.y[3], data.z[3]); -} - - - -/** - * Writes an insert to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeInsert(DL_WriterA& dw, - const DL_InsertData& data, - const DL_Attributes& attrib) { - - if (data.name.empty()) { - std::cerr << "DL_Dxf::writeInsert: " - << "Block name must not be empty\n"; - return; - } - - dw.entity("INSERT"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbBlockReference"); - } - dw.entityAttributes(attrib); - dw.dxfString(2, data.name); - dw.dxfReal(10, data.ipx); - dw.dxfReal(20, data.ipy); - dw.dxfReal(30, data.ipz); - if (data.sx!=1.0 || data.sy!=1.0) { - dw.dxfReal(41, data.sx); - dw.dxfReal(42, data.sy); - dw.dxfReal(43, 1.0); - } - if (data.angle!=0.0) { - dw.dxfReal(50, data.angle); - } - if (data.cols!=1 || data.rows!=1) { - dw.dxfInt(70, data.cols); - dw.dxfInt(71, data.rows); - } - if (data.colSp!=0.0 || data.rowSp!=0.0) { - dw.dxfReal(44, data.colSp); - dw.dxfReal(45, data.rowSp); - } - -} - - - -/** - * Writes a multi text entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeMText(DL_WriterA& dw, - const DL_MTextData& data, - const DL_Attributes& attrib) { - - dw.entity("MTEXT"); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbMText"); - } - dw.entityAttributes(attrib); - dw.dxfReal(10, data.ipx); - dw.dxfReal(20, data.ipy); - dw.dxfReal(30, data.ipz); - dw.dxfReal(40, data.height); - dw.dxfReal(41, data.width); - - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.drawingDirection); - - // Creare text chunks of 250 characters each: - int length = static_cast( data.text.length() ); - char chunk[251]; - int i; - for (i=250; iDL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfReal(42, data.angle); - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbAlignedDimension"); - } - - dw.dxfReal(13, edata.epx1); - dw.dxfReal(23, edata.epy1); - dw.dxfReal(33, 0.0); - - dw.dxfReal(14, edata.epx2); - dw.dxfReal(24, edata.epy2); - dw.dxfReal(34, 0.0); - - writeDimStyleOverrides(dw, data); -} - - - -/** - * Writes a linear dimension entity to the file. - * - * @param dw DXF writer - * @param data Generic dimension data for from the file - * @param data Specific linear dimension data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeDimLinear(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimLinearData& edata, - const DL_Attributes& attrib) { - - dw.entity("DIMENSION"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimension"); - } - - dw.dxfReal(10, data.dpx); - dw.dxfReal(20, data.dpy); - dw.dxfReal(30, data.dpz); - - dw.dxfReal(11, data.mpx); - dw.dxfReal(21, data.mpy); - dw.dxfReal(31, 0.0); - - dw.dxfInt(70, data.type); - if (version>DL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfReal(42, data.angle); - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbAlignedDimension"); - } - - dw.dxfReal(13, edata.dpx1); - dw.dxfReal(23, edata.dpy1); - dw.dxfReal(33, 0.0); - - dw.dxfReal(14, edata.dpx2); - dw.dxfReal(24, edata.dpy2); - dw.dxfReal(34, 0.0); - - dw.dxfReal(50, edata.angle/(2.0*M_PI)*360.0); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbRotatedDimension"); - } - - writeDimStyleOverrides(dw, data); -} - - - -/** - * Writes a radial dimension entity to the file. - * - * @param dw DXF writer - * @param data Generic dimension data for from the file - * @param data Specific radial dimension data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeDimRadial(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimRadialData& edata, - const DL_Attributes& attrib) { - - dw.entity("DIMENSION"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimension"); - } - - dw.dxfReal(10, data.dpx); - dw.dxfReal(20, data.dpy); - dw.dxfReal(30, data.dpz); - - dw.dxfReal(11, data.mpx); - dw.dxfReal(21, data.mpy); - dw.dxfReal(31, 0.0); - - dw.dxfInt(70, data.type); - if (version>DL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfReal(42, data.angle); - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbRadialDimension"); - } - - dw.dxfReal(15, edata.dpx); - dw.dxfReal(25, edata.dpy); - dw.dxfReal(35, 0.0); - - dw.dxfReal(40, edata.leader); - - writeDimStyleOverrides(dw, data); -} - - - -/** - * Writes a diametric dimension entity to the file. - * - * @param dw DXF writer - * @param data Generic dimension data for from the file - * @param data Specific diametric dimension data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeDimDiametric(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimDiametricData& edata, - const DL_Attributes& attrib) { - - dw.entity("DIMENSION"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimension"); - } - - dw.dxfReal(10, data.dpx); - dw.dxfReal(20, data.dpy); - dw.dxfReal(30, data.dpz); - - dw.dxfReal(11, data.mpx); - dw.dxfReal(21, data.mpy); - dw.dxfReal(31, 0.0); - - dw.dxfInt(70, data.type); - if (version>DL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfReal(42, data.angle); - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDiametricDimension"); - } - - dw.dxfReal(15, edata.dpx); - dw.dxfReal(25, edata.dpy); - dw.dxfReal(35, 0.0); - - dw.dxfReal(40, edata.leader); - - writeDimStyleOverrides(dw, data); -} - - - -/** - * Writes an angular dimension entity to the file. - * - * @param dw DXF writer - * @param data Generic dimension data for from the file - * @param data Specific angular dimension data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeDimAngular(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimAngularData& edata, - const DL_Attributes& attrib) { - - dw.entity("DIMENSION"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimension"); - } - - dw.dxfReal(10, data.dpx); - dw.dxfReal(20, data.dpy); - dw.dxfReal(30, data.dpz); - - dw.dxfReal(11, data.mpx); - dw.dxfReal(21, data.mpy); - dw.dxfReal(31, 0.0); - - dw.dxfInt(70, data.type); - if (version>DL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfReal(42, data.angle); - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDb2LineAngularDimension"); - } - - dw.dxfReal(13, edata.dpx1); - dw.dxfReal(23, edata.dpy1); - dw.dxfReal(33, 0.0); - - dw.dxfReal(14, edata.dpx2); - dw.dxfReal(24, edata.dpy2); - dw.dxfReal(34, 0.0); - - dw.dxfReal(15, edata.dpx3); - dw.dxfReal(25, edata.dpy3); - dw.dxfReal(35, 0.0); - - dw.dxfReal(16, edata.dpx4); - dw.dxfReal(26, edata.dpy4); - dw.dxfReal(36, 0.0); -} - - - -/** - * Writes an angular dimension entity (3 points version) to the file. - * - * @param dw DXF writer - * @param data Generic dimension data for from the file - * @param data Specific angular dimension data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeDimAngular3P(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimAngular3PData& edata, - const DL_Attributes& attrib) { - - dw.entity("DIMENSION"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimension"); - } - - dw.dxfReal(10, data.dpx); - dw.dxfReal(20, data.dpy); - dw.dxfReal(30, data.dpz); - - dw.dxfReal(11, data.mpx); - dw.dxfReal(21, data.mpy); - dw.dxfReal(31, 0.0); - - dw.dxfInt(70, data.type); - if (version>DL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfReal(42, data.angle); - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDb3PointAngularDimension"); - } - - dw.dxfReal(13, edata.dpx1); - dw.dxfReal(23, edata.dpy1); - dw.dxfReal(33, 0.0); - - dw.dxfReal(14, edata.dpx2); - dw.dxfReal(24, edata.dpy2); - dw.dxfReal(34, 0.0); - - dw.dxfReal(15, edata.dpx3); - dw.dxfReal(25, edata.dpy3); - dw.dxfReal(35, 0.0); -} - - - - -/** - * Writes an ordinate dimension entity to the file. - * - * @param dw DXF writer - * @param data Generic dimension data for from the file - * @param data Specific ordinate dimension data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeDimOrdinate(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimOrdinateData& edata, - const DL_Attributes& attrib) { - - dw.entity("DIMENSION"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - } - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimension"); - } - - dw.dxfReal(10, data.dpx); - dw.dxfReal(20, data.dpy); - dw.dxfReal(30, data.dpz); - - dw.dxfReal(11, data.mpx); - dw.dxfReal(21, data.mpy); - dw.dxfReal(31, 0.0); - - int type = data.type; - if (edata.xtype) { - type|=0x40; - } - - dw.dxfInt(70, type); - if (version>DL_VERSION_R12) { - dw.dxfInt(71, data.attachmentPoint); - dw.dxfInt(72, data.lineSpacingStyle); // opt - dw.dxfReal(41, data.lineSpacingFactor); // opt - } - - dw.dxfString(1, data.text); // opt - //dw.dxfString(3, data.style); - dw.dxfString(3, "Standard"); - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbOrdinateDimension"); - } - - dw.dxfReal(13, edata.dpx1); - dw.dxfReal(23, edata.dpy1); - dw.dxfReal(33, 0.0); - - dw.dxfReal(14, edata.dpx2); - dw.dxfReal(24, edata.dpy2); - dw.dxfReal(34, 0.0); -} - - - -/** - * Writes a leader entity to the file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - * @see writeVertex - */ -void DL_Dxf::writeLeader(DL_WriterA& dw, - const DL_LeaderData& data, - const DL_Attributes& attrib) { - if (version>DL_VERSION_R12) { - dw.entity("LEADER"); - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbLeader"); - } - dw.dxfString(3, "Standard"); - dw.dxfInt(71, data.arrowHeadFlag); - dw.dxfInt(72, data.leaderPathType); - dw.dxfInt(73, data.leaderCreationFlag); - dw.dxfInt(74, data.hooklineDirectionFlag); - dw.dxfInt(75, data.hooklineFlag); - dw.dxfReal(40, data.textAnnotationHeight); - dw.dxfReal(41, data.textAnnotationWidth); - dw.dxfInt(76, data.number); - } -} - - - -/** - * Writes a single vertex of a leader to the file. - * - * @param dw DXF writer - * @param data Entity data - */ -void DL_Dxf::writeLeaderVertex(DL_WriterA& dw, - const DL_LeaderVertexData& data) { - if (version>DL_VERSION_R12) { - dw.dxfReal(10, data.x); - dw.dxfReal(20, data.y); - } -} - - - -/** - * Writes the beginning of a hatch entity to the file. - * This must be followed by one or more writeHatchLoop() - * calls and a writeHatch2() call. - * - * @param dw DXF writer - * @param data Entity data. - * @param attrib Attributes - */ -void DL_Dxf::writeHatch1(DL_WriterA& dw, - const DL_HatchData& data, - const DL_Attributes& attrib) { - - dw.entity("HATCH"); - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbHatch"); - } - dw.dxfReal(10, 0.0); // elevation - dw.dxfReal(20, 0.0); - dw.dxfReal(30, 0.0); - dw.dxfReal(210, 0.0); // extrusion dir. - dw.dxfReal(220, 0.0); - dw.dxfReal(230, 1.0); - if (data.solid==false) { - dw.dxfString(2, data.pattern); - } else { - dw.dxfString(2, "SOLID"); - } - dw.dxfInt(70, static_cast(data.solid)); - dw.dxfInt(71, 0); // non-associative - dw.dxfInt(91, data.numLoops); -} - - - -/** - * Writes the end of a hatch entity to the file. - * - * @param dw DXF writer - * @param data Entity data. - * @param attrib Attributes - */ -void DL_Dxf::writeHatch2(DL_WriterA& dw, - const DL_HatchData& data, - const DL_Attributes& /*attrib*/) { - - dw.dxfInt(75, 0); // odd parity - dw.dxfInt(76, 1); // pattern type - if (data.solid==false) { - dw.dxfReal(52, data.angle); - dw.dxfReal(41, data.scale); - dw.dxfInt(77, 0); // not double - //dw.dxfInt(78, 0); - dw.dxfInt(78, 1); - dw.dxfReal(53, 45.0); - dw.dxfReal(43, 0.0); - dw.dxfReal(44, 0.0); - dw.dxfReal(45, -0.0883883476483184); - dw.dxfReal(46, 0.0883883476483185); - dw.dxfInt(79, 0); - } - dw.dxfInt(98, 0); - - if (version==DL_VERSION_2000) { - dw.dxfString(1001, "ACAD"); - dw.dxfReal(1010, data.originX); - dw.dxfReal(1020, data.originY); - dw.dxfInt(1030, 0.0); - } -} - - - -/** - * Writes the beginning of a hatch loop to the file. This - * must happen after writing the beginning of a hatch entity. - * - * @param dw DXF writer - * @param data Entity data. - * @param attrib Attributes - */ -void DL_Dxf::writeHatchLoop1(DL_WriterA& dw, - const DL_HatchLoopData& data) { - - dw.dxfInt(92, 1); - dw.dxfInt(93, data.numEdges); - //dw.dxfInt(97, 0); -} - - - -/** - * Writes the end of a hatch loop to the file. - * - * @param dw DXF writer - * @param data Entity data. - * @param attrib Attributes - */ -void DL_Dxf::writeHatchLoop2(DL_WriterA& dw, - const DL_HatchLoopData& /*data*/) { - - dw.dxfInt(97, 0); -} - - -/** - * Writes the beginning of a hatch entity to the file. - * - * @param dw DXF writer - * @param data Entity data. - * @param attrib Attributes - */ -void DL_Dxf::writeHatchEdge(DL_WriterA& dw, - const DL_HatchEdgeData& data) { - - if (data.type<1 || data.type>4) { - printf("WARNING: unsupported hatch edge type: %d", data.type); - } - - dw.dxfInt(72, data.type); - - switch (data.type) { - // line: - case 1: - dw.dxfReal(10, data.x1); - dw.dxfReal(20, data.y1); - dw.dxfReal(11, data.x2); - dw.dxfReal(21, data.y2); - break; - - // arc: - case 2: - dw.dxfReal(10, data.cx); - dw.dxfReal(20, data.cy); - dw.dxfReal(40, data.radius); - dw.dxfReal(50, data.angle1/(2*M_PI)*360.0); - dw.dxfReal(51, data.angle2/(2*M_PI)*360.0); - dw.dxfInt(73, static_cast(data.ccw)); - break; - - // ellipse arc: - case 3: - dw.dxfReal(10, data.cx); - dw.dxfReal(20, data.cy); - dw.dxfReal(11, data.mx); - dw.dxfReal(21, data.my); - dw.dxfReal(40, data.ratio); - dw.dxfReal(50, data.angle1/(2*M_PI)*360.0); - dw.dxfReal(51, data.angle2/(2*M_PI)*360.0); - dw.dxfInt(73, static_cast(data.ccw)); - break; - - // spline: - case 4: - dw.dxfInt(94, data.degree); - dw.dxfBool(73, data.rational); - dw.dxfBool(74, data.periodic); - dw.dxfInt(95, data.nKnots); - dw.dxfInt(96, data.nControl); - for (unsigned int i=0; i0) { - dw.dxfInt(97, data.nFit); - for (unsigned int i=0; i1.0e-4 || fabs(data.startTangentY)>1.0e-4) { - dw.dxfReal(12, data.startTangentX); - dw.dxfReal(22, data.startTangentY); - } - if (fabs(data.endTangentX)>1.0e-4 || fabs(data.endTangentY)>1.0e-4) { - dw.dxfReal(13, data.endTangentX); - dw.dxfReal(23, data.endTangentY); - } - break; - - default: - break; - } -} - - - -/** - * Writes an image entity. - * - * @return IMAGEDEF handle. Needed for the IMAGEDEF counterpart. - */ -int DL_Dxf::writeImage(DL_WriterA& dw, - const DL_ImageData& data, - const DL_Attributes& attrib) { - - /*if (data.file.empty()) { - std::cerr << "DL_Dxf::writeImage: " - << "Image file must not be empty\n"; - return; -}*/ - - dw.entity("IMAGE"); - - dw.entityAttributes(attrib); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbEntity"); - dw.dxfString(100, "AcDbRasterImage"); - dw.dxfInt(90, 0); - } - // insertion point - dw.dxfReal(10, data.ipx); - dw.dxfReal(20, data.ipy); - dw.dxfReal(30, data.ipz); - - // vector along bottom side (1 pixel long) - dw.dxfReal(11, data.ux); - dw.dxfReal(21, data.uy); - dw.dxfReal(31, data.uz); - - // vector along left side (1 pixel long) - dw.dxfReal(12, data.vx); - dw.dxfReal(22, data.vy); - dw.dxfReal(32, data.vz); - - // image size in pixel - dw.dxfReal(13, data.width); - dw.dxfReal(23, data.height); - - // handle of IMAGEDEF object - int handle = dw.incHandle(); - dw.dxfHex(340, handle); - - // flags - dw.dxfInt(70, 15); - - // clipping: - dw.dxfInt(280, 0); - - // brightness, contrast, fade - dw.dxfInt(281, data.brightness); - dw.dxfInt(282, data.contrast); - dw.dxfInt(283, data.fade); - - return handle; -} - - - -/** - * Writes an image definiition entity. - */ -void DL_Dxf::writeImageDef(DL_WriterA& dw, - int handle, - const DL_ImageData& data) { - - /*if (data.file.empty()) { - std::cerr << "DL_Dxf::writeImage: " - << "Image file must not be empty\n"; - return; -}*/ - - dw.dxfString(0, "IMAGEDEF"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, handle); - } - - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbRasterImageDef"); - dw.dxfInt(90, 0); - } - // file name: - dw.dxfString(1, data.ref); - - // image size in pixel - dw.dxfReal(10, data.width); - dw.dxfReal(20, data.height); - - dw.dxfReal(11, 1.0); - dw.dxfReal(21, 1.0); - - // loaded: - dw.dxfInt(280, 1); - // units: - dw.dxfInt(281, 0); -} - - -/** - * Writes a layer to the file. Layers are stored in the - * tables section of a DXF file. - * - * @param dw DXF writer - * @param data Entity data from the file - * @param attrib Attributes - */ -void DL_Dxf::writeLayer(DL_WriterA& dw, - const DL_LayerData& data, - const DL_Attributes& attrib) { - - if (data.name.empty()) { - std::cerr << "DL_Dxf::writeLayer: " - << "Layer name must not be empty\n"; - return; - } - - int color = attrib.getColor(); - if (color>=256) { - std::cerr << "Layer color cannot be " << color << ". Changed to 7.\n"; - color = 7; - } - - if (data.name == "0") { - dw.tableLayerEntry(0x10); - } else { - dw.tableLayerEntry(); - } - - dw.dxfString(2, data.name); - dw.dxfInt(70, data.flags); - dw.dxfInt(62, color); - if (version>=DL_VERSION_2000 && attrib.getColor24()!=-1) { - dw.dxfInt(420, attrib.getColor24()); - } - - dw.dxfString(6, (attrib.getLinetype().length()==0 ? - std::string("CONTINUOUS") : attrib.getLinetype())); - - if (version>=DL_VERSION_2000) { - // layer defpoints cannot be plotted - std::string lstr = data.name; - std::transform(lstr.begin(), lstr.end(), lstr.begin(), tolower); - if (lstr=="defpoints") { - dw.dxfInt(290, 0); - } - } - if (version>=DL_VERSION_2000 && attrib.getWidth()!=-1) { - dw.dxfInt(370, attrib.getWidth()); - } - if (version>=DL_VERSION_2000) { - dw.dxfHex(390, 0xF); - } -} - - - -/** - * Writes a line type to the file. Line types are stored in the - * tables section of a DXF file. - */ -void DL_Dxf::writeLinetype(DL_WriterA& dw, - const DL_LinetypeData& data) { - - std::string nameUpper = data.name; - std::transform(nameUpper.begin(), nameUpper.end(), nameUpper.begin(), ::toupper); - - if (data.name.empty()) { - std::cerr << "DL_Dxf::writeLinetype: " - << "Line type name must not be empty\n"; - return; - } - - // ignore BYLAYER, BYBLOCK for R12 - if (version=DL_VERSION_R13) { - dw.dxfInt(74, 0); - } - } - } -} - - - -/** - * Writes the APPID section to the DXF file. - * - * @param name Application name - */ -void DL_Dxf::writeAppid(DL_WriterA& dw, const std::string& name) { - if (name.empty()) { - std::cerr << "DL_Dxf::writeAppid: " - << "Application name must not be empty\n"; - return; - } - - std::string n = name; - std::transform(n.begin(), n.end(), n.begin(), ::toupper); - - if (n=="ACAD") { - dw.tableAppidEntry(0x12); - } else { - dw.tableAppidEntry(); - } - dw.dxfString(2, name); - dw.dxfInt(70, 0); -} - - - -/** - * Writes a block's definition (no entities) to the DXF file. - */ -void DL_Dxf::writeBlock(DL_WriterA& dw, const DL_BlockData& data) { - if (data.name.empty()) { - std::cerr << "DL_Dxf::writeBlock: " - << "Block name must not be empty\n"; - return; - } - - std::string n = data.name; - std::transform(n.begin(), n.end(), n.begin(), ::toupper); - - if (n=="*PAPER_SPACE") { - dw.sectionBlockEntry(0x1C); - } else if (n=="*MODEL_SPACE") { - dw.sectionBlockEntry(0x20); - } else if (n=="*PAPER_SPACE0") { - dw.sectionBlockEntry(0x24); - } else { - dw.sectionBlockEntry(); - } - dw.dxfString(2, data.name); - dw.dxfInt(70, 0); - dw.coord(10, data.bpx, data.bpy, data.bpz); - dw.dxfString(3, data.name); - dw.dxfString(1, ""); -} - - - -/** - * Writes a block end. - * - * @param name Block name - */ -void DL_Dxf::writeEndBlock(DL_WriterA& dw, const std::string& name) { - std::string n = name; - std::transform(n.begin(), n.end(), n.begin(), ::toupper); - - if (n=="*PAPER_SPACE") { - dw.sectionBlockEntryEnd(0x1D); - } else if (n=="*MODEL_SPACE") { - dw.sectionBlockEntryEnd(0x21); - } else if (n=="*PAPER_SPACE0") { - dw.sectionBlockEntryEnd(0x25); - } else { - dw.sectionBlockEntryEnd(); - } -} - - - -/** - * Writes a viewport section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked VPORT section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeVPort(DL_WriterA& dw) { - dw.dxfString(0, "TABLE"); - dw.dxfString(2, "VPORT"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 0x8); - } - //dw.dxfHex(330, 0); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTable"); - } - dw.dxfInt(70, 1); - dw.dxfString(0, "VPORT"); - //dw.dxfHex(5, 0x2F); - if (version==DL_VERSION_2000) { - dw.handle(); - } - //dw.dxfHex(330, 8); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbViewportTableRecord"); - } - dw.dxfString( 2, "*Active"); - dw.dxfInt( 70, 0); - dw.dxfReal( 10, 0.0); - dw.dxfReal( 20, 0.0); - dw.dxfReal( 11, 1.0); - dw.dxfReal( 21, 1.0); - dw.dxfReal( 12, 286.3055555555555); - dw.dxfReal( 22, 148.5); - dw.dxfReal( 13, 0.0); - dw.dxfReal( 23, 0.0); - dw.dxfReal( 14, 10.0); - dw.dxfReal( 24, 10.0); - dw.dxfReal( 15, 10.0); - dw.dxfReal( 25, 10.0); - dw.dxfReal( 16, 0.0); - dw.dxfReal( 26, 0.0); - dw.dxfReal( 36, 1.0); - dw.dxfReal( 17, 0.0); - dw.dxfReal( 27, 0.0); - dw.dxfReal( 37, 0.0); - dw.dxfReal( 40, 297.0); - dw.dxfReal( 41, 1.92798353909465); - dw.dxfReal( 42, 50.0); - dw.dxfReal( 43, 0.0); - dw.dxfReal( 44, 0.0); - dw.dxfReal( 50, 0.0); - dw.dxfReal( 51, 0.0); - dw.dxfInt( 71, 0); - dw.dxfInt( 72, 100); - dw.dxfInt( 73, 1); - dw.dxfInt( 74, 3); - dw.dxfInt( 75, 1); - dw.dxfInt( 76, 1); - dw.dxfInt( 77, 0); - dw.dxfInt( 78, 0); - - if (version==DL_VERSION_2000) { - dw.dxfInt(281, 0); - dw.dxfInt( 65, 1); - dw.dxfReal(110, 0.0); - dw.dxfReal(120, 0.0); - dw.dxfReal(130, 0.0); - dw.dxfReal(111, 1.0); - dw.dxfReal(121, 0.0); - dw.dxfReal(131, 0.0); - dw.dxfReal(112, 0.0); - dw.dxfReal(122, 1.0); - dw.dxfReal(132, 0.0); - dw.dxfInt( 79, 0); - dw.dxfReal(146, 0.0); - } - dw.dxfString( 0, "ENDTAB"); -} - - - -/** - * Writes a style section. This section is needed in DL_VERSION_R13. - */ -void DL_Dxf::writeStyle(DL_WriterA& dw, const DL_StyleData& style) { -// dw.dxfString( 0, "TABLE"); -// dw.dxfString( 2, "STYLE"); -// if (version==DL_VERSION_2000) { -// dw.dxfHex(5, 3); -// } - //dw.dxfHex(330, 0); -// if (version==DL_VERSION_2000) { -// dw.dxfString(100, "AcDbSymbolTable"); -// } -// dw.dxfInt( 70, 1); - dw.dxfString( 0, "STYLE"); - if (version==DL_VERSION_2000) { - if (style.name=="Standard") { - //dw.dxfHex(5, 0x11); - styleHandleStd = dw.handle(); - } - else { - dw.handle(); - } - } - //dw.dxfHex(330, 3); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbTextStyleTableRecord"); - } - dw.dxfString( 2, style.name); - dw.dxfInt( 70, style.flags); - dw.dxfReal( 40, style.fixedTextHeight); - dw.dxfReal( 41, style.widthFactor); - dw.dxfReal( 50, style.obliqueAngle); - dw.dxfInt( 71, style.textGenerationFlags); - dw.dxfReal( 42, style.lastHeightUsed); - if (version==DL_VERSION_2000) { - dw.dxfString( 3, ""); - dw.dxfString( 4, ""); - dw.dxfString(1001, "ACAD"); - //dw.dxfString(1000, style.name); - dw.dxfString(1000, style.primaryFontFile); - int xFlags = 0; - if (style.bold) { - xFlags = xFlags|0x2000000; - } - if (style.italic) { - xFlags = xFlags|0x1000000; - } - dw.dxfInt(1071, xFlags); - } - else { - dw.dxfString( 3, style.primaryFontFile); - dw.dxfString( 4, style.bigFontFile); - } - //dw.dxfString( 0, "ENDTAB"); -} - - - -/** - * Writes a view section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked VIEW section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeView(DL_WriterA& dw) { - dw.dxfString( 0, "TABLE"); - dw.dxfString( 2, "VIEW"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 6); - } - //dw.dxfHex(330, 0); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTable"); - } - dw.dxfInt( 70, 0); - dw.dxfString( 0, "ENDTAB"); -} - - - -/** - * Writes a ucs section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked UCS section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeUcs(DL_WriterA& dw) { - dw.dxfString( 0, "TABLE"); - dw.dxfString( 2, "UCS"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 7); - } - //dw.dxfHex(330, 0); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTable"); - } - dw.dxfInt( 70, 0); - dw.dxfString( 0, "ENDTAB"); -} - - - -/** - * Writes a dimstyle section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked DIMSTYLE section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeDimStyle(DL_WriterA& dw, - double dimasz, double dimexe, double dimexo, - double dimgap, double dimtxt) { - - dw.dxfString( 0, "TABLE"); - dw.dxfString( 2, "DIMSTYLE"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 0xA); - dw.dxfString(100, "AcDbSymbolTable"); - } - dw.dxfInt( 70, 1); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbDimStyleTable"); - dw.dxfInt( 71, 0); - } - - - dw.dxfString( 0, "DIMSTYLE"); - if (version==DL_VERSION_2000) { - dw.dxfHex(105, 0x27); - } - //dw.handle(105); - //dw.dxfHex(330, 0xA); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbDimStyleTableRecord"); - } - dw.dxfString( 2, "Standard"); - if (version==DL_VERSION_R12) { - dw.dxfString( 3, ""); - dw.dxfString( 4, ""); - dw.dxfString( 5, ""); - dw.dxfString( 6, ""); - dw.dxfString( 7, ""); - dw.dxfReal( 40, 1.0); - } - - dw.dxfReal( 41, dimasz); - dw.dxfReal( 42, dimexo); - dw.dxfReal( 43, 3.75); - dw.dxfReal( 44, dimexe); - if (version==DL_VERSION_R12) { - dw.dxfReal( 45, 0.0); - dw.dxfReal( 46, 0.0); - dw.dxfReal( 47, 0.0); - dw.dxfReal( 48, 0.0); - } - dw.dxfInt( 70, 0); - if (version==DL_VERSION_R12) { - dw.dxfInt( 71, 0); - dw.dxfInt( 72, 0); - } - dw.dxfInt( 73, 0); - dw.dxfInt( 74, 0); - if (version==DL_VERSION_R12) { - dw.dxfInt( 75, 0); - dw.dxfInt( 76, 0); - } - dw.dxfInt( 77, 1); - dw.dxfInt( 78, 8); - dw.dxfReal(140, dimtxt); - dw.dxfReal(141, 2.5); - if (version==DL_VERSION_R12) { - dw.dxfReal(142, 0.0); - } - dw.dxfReal(143, 0.03937007874016); - if (version==DL_VERSION_R12) { - dw.dxfReal(144, 1.0); - dw.dxfReal(145, 0.0); - dw.dxfReal(146, 1.0); - } - dw.dxfReal(147, dimgap); - if (version==DL_VERSION_R12) { - dw.dxfInt(170, 0); - } - dw.dxfInt(171, 3); - dw.dxfInt(172, 1); - if (version==DL_VERSION_R12) { - dw.dxfInt(173, 0); - dw.dxfInt(174, 0); - dw.dxfInt(175, 0); - dw.dxfInt(176, 0); - dw.dxfInt(177, 0); - dw.dxfInt(178, 0); - } - if (version==DL_VERSION_2000) { - dw.dxfInt(271, 2); - dw.dxfInt(272, 2); - dw.dxfInt(274, 3); - dw.dxfInt(278, 44); - dw.dxfInt(283, 0); - dw.dxfInt(284, 8); - dw.dxfHex(340, styleHandleStd); - //dw.dxfHex(340, 0x11); - } - // * / - dw.dxfString( 0, "ENDTAB"); -} - - - -/** - * Writes a blockrecord section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked BLOCKRECORD section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeBlockRecord(DL_WriterA& dw) { - dw.dxfString( 0, "TABLE"); - dw.dxfString( 2, "BLOCK_RECORD"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 1); - } - //dw.dxfHex(330, 0); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTable"); - } - dw.dxfInt( 70, 1); - - dw.dxfString( 0, "BLOCK_RECORD"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 0x1F); - } - //int msh = dw.handle(); - //dw.setModelSpaceHandle(msh); - //dw.dxfHex(330, 1); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbBlockTableRecord"); - } - dw.dxfString( 2, "*Model_Space"); - dw.dxfHex(340, 0x22); - - dw.dxfString( 0, "BLOCK_RECORD"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 0x1B); - } - //int psh = dw.handle(); - //dw.setPaperSpaceHandle(psh); - //dw.dxfHex(330, 1); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbBlockTableRecord"); - } - dw.dxfString( 2, "*Paper_Space"); - dw.dxfHex(340, 0x1E); - - dw.dxfString( 0, "BLOCK_RECORD"); - if (version==DL_VERSION_2000) { - dw.dxfHex(5, 0x23); - } - //int ps0h = dw.handle(); - //dw.setPaperSpace0Handle(ps0h); - //dw.dxfHex(330, 1); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbBlockTableRecord"); - } - dw.dxfString( 2, "*Paper_Space0"); - dw.dxfHex(340, 0x26); - - //dw.dxfString( 0, "ENDTAB"); -} - - - -/** - * Writes a single block record with the given name. - */ -void DL_Dxf::writeBlockRecord(DL_WriterA& dw, const std::string& name) { - dw.dxfString( 0, "BLOCK_RECORD"); - if (version==DL_VERSION_2000) { - dw.handle(); - } - //dw->dxfHex(330, 1); - if (version==DL_VERSION_2000) { - dw.dxfString(100, "AcDbSymbolTableRecord"); - dw.dxfString(100, "AcDbBlockTableRecord"); - } - dw.dxfString( 2, name); - dw.dxfHex(340, 0); -} - - - -/** - * Writes a objects section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked OBJECTS section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeObjects(DL_WriterA& dw, const std::string& appDictionaryName) { - dw.dxfString( 0, "SECTION"); - dw.dxfString( 2, "OBJECTS"); - - - dw.dxfString( 0, "DICTIONARY"); - dw.dxfHex(5, 0xC); - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(280, 0); - dw.dxfInt(281, 1); - dw.dxfString( 3, "ACAD_GROUP"); - dw.dxfHex(350, 0xD); - dw.dxfString( 3, "ACAD_LAYOUT"); - dw.dxfHex(350, 0x1A); - dw.dxfString( 3, "ACAD_MLINESTYLE"); - dw.dxfHex(350, 0x17); - dw.dxfString( 3, "ACAD_PLOTSETTINGS"); - dw.dxfHex(350, 0x19); - dw.dxfString( 3, "ACAD_PLOTSTYLENAME"); - dw.dxfHex(350, 0xE); - dw.dxfString( 3, "AcDbVariableDictionary"); - int acDbVariableDictionaryHandle = dw.handle(350); - //int acDbVariableDictionaryHandle = dw.getNextHandle(); - //dw.dxfHex(350, acDbVariableDictionaryHandle); - //dw.incHandle(); - - if (appDictionaryName.length()!=0) { - dw.dxfString( 3, appDictionaryName); - appDictionaryHandle = dw.handle(350); - //appDictionaryHandle = dw.getNextHandle(); - //dw.dxfHex(350, appDictionaryHandle); - //dw.incHandle(); - } - - dw.dxfString( 0, "DICTIONARY"); - dw.dxfHex(5, 0xD); - //dw.handle(); // D - //dw.dxfHex(330, 0xC); - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(280, 0); - dw.dxfInt(281, 1); - - - dw.dxfString( 0, "ACDBDICTIONARYWDFLT"); - dw.dxfHex(5, 0xE); - //dicId4 = dw.handle(); // E - //dw.dxfHex(330, 0xC); // C - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(281, 1); - dw.dxfString( 3, "Normal"); - dw.dxfHex(350, 0xF); - //dw.dxfHex(350, dw.getNextHandle()+5); // F - dw.dxfString(100, "AcDbDictionaryWithDefault"); - dw.dxfHex(340, 0xF); - //dw.dxfHex(340, dw.getNextHandle()+5); // F - - - dw.dxfString( 0, "ACDBPLACEHOLDER"); - dw.dxfHex(5, 0xF); - //dw.handle(); // F - //dw.dxfHex(330, dicId4); // E - - - dw.dxfString( 0, "DICTIONARY"); - //dicId3 = dw.handle(); // 17 - dw.dxfHex(5, 0x17); - //dw.dxfHex(330, 0xC); // C - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(280, 0); - dw.dxfInt(281, 1); - dw.dxfString( 3, "Standard"); - dw.dxfHex(350, 0x18); - //dw.dxfHex(350, dw.getNextHandle()+5); // 18 - - - dw.dxfString( 0, "MLINESTYLE"); - dw.dxfHex(5, 0x18); - //dw.handle(); // 18 - //dw.dxfHex(330, dicId3); // 17 - dw.dxfString(100, "AcDbMlineStyle"); - dw.dxfString( 2, "STANDARD"); - dw.dxfInt( 70, 0); - dw.dxfString( 3, ""); - dw.dxfInt( 62, 256); - dw.dxfReal( 51, 90.0); - dw.dxfReal( 52, 90.0); - dw.dxfInt( 71, 2); - dw.dxfReal( 49, 0.5); - dw.dxfInt( 62, 256); - dw.dxfString( 6, "BYLAYER"); - dw.dxfReal( 49, -0.5); - dw.dxfInt( 62, 256); - dw.dxfString( 6, "BYLAYER"); - - - dw.dxfString( 0, "DICTIONARY"); - dw.dxfHex(5, 0x19); - //dw.handle(); // 17 - //dw.dxfHex(330, 0xC); // C - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(280, 0); - dw.dxfInt(281, 1); - - - dw.dxfString( 0, "DICTIONARY"); - //dicId2 = dw.handle(); // 1A - dw.dxfHex(5, 0x1A); - //dw.dxfHex(330, 0xC); - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(281, 1); - dw.dxfString( 3, "Layout1"); - dw.dxfHex(350, 0x1E); - //dw.dxfHex(350, dw.getNextHandle()+2); // 1E - dw.dxfString( 3, "Layout2"); - dw.dxfHex(350, 0x26); - //dw.dxfHex(350, dw.getNextHandle()+4); // 26 - dw.dxfString( 3, "Model"); - dw.dxfHex(350, 0x22); - //dw.dxfHex(350, dw.getNextHandle()+5); // 22 - - - dw.dxfString( 0, "LAYOUT"); - dw.dxfHex(5, 0x1E); - //dw.handle(); // 1E - //dw.dxfHex(330, dicId2); // 1A - dw.dxfString(100, "AcDbPlotSettings"); - dw.dxfString( 1, ""); - dw.dxfString( 2, "none_device"); - dw.dxfString( 4, ""); - dw.dxfString( 6, ""); - dw.dxfReal( 40, 0.0); - dw.dxfReal( 41, 0.0); - dw.dxfReal( 42, 0.0); - dw.dxfReal( 43, 0.0); - dw.dxfReal( 44, 0.0); - dw.dxfReal( 45, 0.0); - dw.dxfReal( 46, 0.0); - dw.dxfReal( 47, 0.0); - dw.dxfReal( 48, 0.0); - dw.dxfReal( 49, 0.0); - dw.dxfReal(140, 0.0); - dw.dxfReal(141, 0.0); - dw.dxfReal(142, 1.0); - dw.dxfReal(143, 1.0); - dw.dxfInt( 70, 688); - dw.dxfInt( 72, 0); - dw.dxfInt( 73, 0); - dw.dxfInt( 74, 5); - dw.dxfString( 7, ""); - dw.dxfInt( 75, 16); - dw.dxfReal(147, 1.0); - dw.dxfReal(148, 0.0); - dw.dxfReal(149, 0.0); - dw.dxfString(100, "AcDbLayout"); - dw.dxfString( 1, "Layout1"); - dw.dxfInt( 70, 1); - dw.dxfInt( 71, 1); - dw.dxfReal( 10, 0.0); - dw.dxfReal( 20, 0.0); - dw.dxfReal( 11, 420.0); - dw.dxfReal( 21, 297.0); - dw.dxfReal( 12, 0.0); - dw.dxfReal( 22, 0.0); - dw.dxfReal( 32, 0.0); - dw.dxfReal( 14, 1.000000000000000E+20); - dw.dxfReal( 24, 1.000000000000000E+20); - dw.dxfReal( 34, 1.000000000000000E+20); - dw.dxfReal( 15, -1.000000000000000E+20); - dw.dxfReal( 25, -1.000000000000000E+20); - dw.dxfReal( 35, -1.000000000000000E+20); - dw.dxfReal(146, 0.0); - dw.dxfReal( 13, 0.0); - dw.dxfReal( 23, 0.0); - dw.dxfReal( 33, 0.0); - dw.dxfReal( 16, 1.0); - dw.dxfReal( 26, 0.0); - dw.dxfReal( 36, 0.0); - dw.dxfReal( 17, 0.0); - dw.dxfReal( 27, 1.0); - dw.dxfReal( 37, 0.0); - dw.dxfInt( 76, 0); - //dw.dxfHex(330, dw.getPaperSpaceHandle()); // 1B - dw.dxfHex(330, 0x1B); - - - dw.dxfString( 0, "LAYOUT"); - dw.dxfHex(5, 0x22); - //dw.handle(); // 22 - //dw.dxfHex(330, dicId2); // 1A - dw.dxfString(100, "AcDbPlotSettings"); - dw.dxfString( 1, ""); - dw.dxfString( 2, "none_device"); - dw.dxfString( 4, ""); - dw.dxfString( 6, ""); - dw.dxfReal( 40, 0.0); - dw.dxfReal( 41, 0.0); - dw.dxfReal( 42, 0.0); - dw.dxfReal( 43, 0.0); - dw.dxfReal( 44, 0.0); - dw.dxfReal( 45, 0.0); - dw.dxfReal( 46, 0.0); - dw.dxfReal( 47, 0.0); - dw.dxfReal( 48, 0.0); - dw.dxfReal( 49, 0.0); - dw.dxfReal(140, 0.0); - dw.dxfReal(141, 0.0); - dw.dxfReal(142, 1.0); - dw.dxfReal(143, 1.0); - dw.dxfInt( 70, 1712); - dw.dxfInt( 72, 0); - dw.dxfInt( 73, 0); - dw.dxfInt( 74, 0); - dw.dxfString( 7, ""); - dw.dxfInt( 75, 0); - dw.dxfReal(147, 1.0); - dw.dxfReal(148, 0.0); - dw.dxfReal(149, 0.0); - dw.dxfString(100, "AcDbLayout"); - dw.dxfString( 1, "Model"); - dw.dxfInt( 70, 1); - dw.dxfInt( 71, 0); - dw.dxfReal( 10, 0.0); - dw.dxfReal( 20, 0.0); - dw.dxfReal( 11, 12.0); - dw.dxfReal( 21, 9.0); - dw.dxfReal( 12, 0.0); - dw.dxfReal( 22, 0.0); - dw.dxfReal( 32, 0.0); - dw.dxfReal( 14, 0.0); - dw.dxfReal( 24, 0.0); - dw.dxfReal( 34, 0.0); - dw.dxfReal( 15, 0.0); - dw.dxfReal( 25, 0.0); - dw.dxfReal( 35, 0.0); - dw.dxfReal(146, 0.0); - dw.dxfReal( 13, 0.0); - dw.dxfReal( 23, 0.0); - dw.dxfReal( 33, 0.0); - dw.dxfReal( 16, 1.0); - dw.dxfReal( 26, 0.0); - dw.dxfReal( 36, 0.0); - dw.dxfReal( 17, 0.0); - dw.dxfReal( 27, 1.0); - dw.dxfReal( 37, 0.0); - dw.dxfInt( 76, 0); - //dw.dxfHex(330, dw.getModelSpaceHandle()); // 1F - dw.dxfHex(330, 0x1F); - - - dw.dxfString( 0, "LAYOUT"); - //dw.handle(); // 26 - dw.dxfHex(5, 0x26); - //dw.dxfHex(330, dicId2); // 1A - dw.dxfString(100, "AcDbPlotSettings"); - dw.dxfString( 1, ""); - dw.dxfString( 2, "none_device"); - dw.dxfString( 4, ""); - dw.dxfString( 6, ""); - dw.dxfReal( 40, 0.0); - dw.dxfReal( 41, 0.0); - dw.dxfReal( 42, 0.0); - dw.dxfReal( 43, 0.0); - dw.dxfReal( 44, 0.0); - dw.dxfReal( 45, 0.0); - dw.dxfReal( 46, 0.0); - dw.dxfReal( 47, 0.0); - dw.dxfReal( 48, 0.0); - dw.dxfReal( 49, 0.0); - dw.dxfReal(140, 0.0); - dw.dxfReal(141, 0.0); - dw.dxfReal(142, 1.0); - dw.dxfReal(143, 1.0); - dw.dxfInt( 70, 688); - dw.dxfInt( 72, 0); - dw.dxfInt( 73, 0); - dw.dxfInt( 74, 5); - dw.dxfString( 7, ""); - dw.dxfInt( 75, 16); - dw.dxfReal(147, 1.0); - dw.dxfReal(148, 0.0); - dw.dxfReal(149, 0.0); - dw.dxfString(100, "AcDbLayout"); - dw.dxfString( 1, "Layout2"); - dw.dxfInt( 70, 1); - dw.dxfInt( 71, 2); - dw.dxfReal( 10, 0.0); - dw.dxfReal( 20, 0.0); - dw.dxfReal( 11, 12.0); - dw.dxfReal( 21, 9.0); - dw.dxfReal( 12, 0.0); - dw.dxfReal( 22, 0.0); - dw.dxfReal( 32, 0.0); - dw.dxfReal( 14, 0.0); - dw.dxfReal( 24, 0.0); - dw.dxfReal( 34, 0.0); - dw.dxfReal( 15, 0.0); - dw.dxfReal( 25, 0.0); - dw.dxfReal( 35, 0.0); - dw.dxfReal(146, 0.0); - dw.dxfReal( 13, 0.0); - dw.dxfReal( 23, 0.0); - dw.dxfReal( 33, 0.0); - dw.dxfReal( 16, 1.0); - dw.dxfReal( 26, 0.0); - dw.dxfReal( 36, 0.0); - dw.dxfReal( 17, 0.0); - dw.dxfReal( 27, 1.0); - dw.dxfReal( 37, 0.0); - dw.dxfInt( 76, 0); - //dw.dxfHex(330, dw.getPaperSpace0Handle()); // 23 - dw.dxfHex(330, 0x23); - - dw.dxfString( 0, "DICTIONARY"); - //dw.dxfHex(5, 0x2C); - //dicId5 = - dw.dxfHex(5, acDbVariableDictionaryHandle); - //dw.handle(); // 2C - //dw.dxfHex(330, 0xC); // C - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(281, 1); - dw.dxfString( 3, "DIMASSOC"); - //dw.dxfHex(350, 0x2F); - dw.dxfHex(350, dw.getNextHandle()+1); // 2E - dw.dxfString( 3, "HIDETEXT"); - //dw.dxfHex(350, 0x2E); - dw.dxfHex(350, dw.getNextHandle()); // 2D - - - dw.dxfString( 0, "DICTIONARYVAR"); - //dw.dxfHex(5, 0x2E); - dw.handle(); // 2E - //dw.dxfHex(330, dicId5); // 2C - dw.dxfString(100, "DictionaryVariables"); - dw.dxfInt(280, 0); - dw.dxfInt( 1, 2); - - - dw.dxfString( 0, "DICTIONARYVAR"); - //dw.dxfHex(5, 0x2D); - dw.handle(); // 2D - //dw.dxfHex(330, dicId5); // 2C - dw.dxfString(100, "DictionaryVariables"); - dw.dxfInt(280, 0); - dw.dxfInt( 1, 1); -} - -void DL_Dxf::writeAppDictionary(DL_WriterA& dw) { - dw.dxfString( 0, "DICTIONARY"); - //dw.handle(); - dw.dxfHex(5, appDictionaryHandle); - dw.dxfString(100, "AcDbDictionary"); - dw.dxfInt(281, 1); -} - -int DL_Dxf::writeDictionaryEntry(DL_WriterA& dw, const std::string& name) { - dw.dxfString( 3, name); - int handle = dw.getNextHandle(); - dw.dxfHex(350, handle); - dw.incHandle(); - return handle; -} - -void DL_Dxf::writeXRecord(DL_WriterA& dw, int handle, int value) { - dw.dxfString( 0, "XRECORD"); - dw.dxfHex(5, handle); - dw.dxfHex(330, appDictionaryHandle); - dw.dxfString(100, "AcDbXrecord"); - dw.dxfInt(280, 1); - dw.dxfInt(90, value); -} - -void DL_Dxf::writeXRecord(DL_WriterA& dw, int handle, double value) { - dw.dxfString( 0, "XRECORD"); - dw.dxfHex(5, handle); - dw.dxfHex(330, appDictionaryHandle); - dw.dxfString(100, "AcDbXrecord"); - dw.dxfInt(280, 1); - dw.dxfReal(40, value); -} - -void DL_Dxf::writeXRecord(DL_WriterA& dw, int handle, bool value) { - dw.dxfString( 0, "XRECORD"); - dw.dxfHex(5, handle); - dw.dxfHex(330, appDictionaryHandle); - dw.dxfString(100, "AcDbXrecord"); - dw.dxfInt(280, 1); - dw.dxfBool(290, value); -} - -void DL_Dxf::writeXRecord(DL_WriterA& dw, int handle, const std::string& value) { - dw.dxfString( 0, "XRECORD"); - dw.dxfHex(5, handle); - dw.dxfHex(330, appDictionaryHandle); - dw.dxfString(100, "AcDbXrecord"); - dw.dxfInt(280, 1); - dw.dxfString(1000, value); -} - -/** - * Writes the end of the objects section. This section is needed in DL_VERSION_R13. - * Note that this method currently only writes a faked OBJECTS section - * to make the file readable by Aut*cad. - */ -void DL_Dxf::writeObjectsEnd(DL_WriterA& dw) { - dw.dxfString( 0, "ENDSEC"); -} - - - -/** - * Writes a comment to the DXF file. - */ -void DL_Dxf::writeComment(DL_WriterA& dw, const std::string& comment) { - dw.dxfString(999, comment); -} - - -/** - * Checks if the given variable is known by the given DXF version. - */ -bool DL_Dxf::checkVariable(const char* var, DL_Codes::version version) { - if (version>=DL_VERSION_2000) { - return true; - } else if (version==DL_VERSION_R12) { - // these are all the variables recognized by dxf r12: - if (!strcmp(var, "$ACADVER")) { - return true; - } - if (!strcmp(var, "$ACADVER")) { - return true; - } - if (!strcmp(var, "$ANGBASE")) { - return true; - } - if (!strcmp(var, "$ANGDIR")) { - return true; - } - if (!strcmp(var, "$ATTDIA")) { - return true; - } - if (!strcmp(var, "$ATTMODE")) { - return true; - } - if (!strcmp(var, "$ATTREQ")) { - return true; - } - if (!strcmp(var, "$AUNITS")) { - return true; - } - if (!strcmp(var, "$AUPREC")) { - return true; - } - if (!strcmp(var, "$AXISMODE")) { - return true; - } - if (!strcmp(var, "$AXISUNIT")) { - return true; - } - if (!strcmp(var, "$BLIPMODE")) { - return true; - } - if (!strcmp(var, "$CECOLOR")) { - return true; - } - if (!strcmp(var, "$CELTYPE")) { - return true; - } - if (!strcmp(var, "$CHAMFERA")) { - return true; - } - if (!strcmp(var, "$CHAMFERB")) { - return true; - } - if (!strcmp(var, "$CLAYER")) { - return true; - } - if (!strcmp(var, "$COORDS")) { - return true; - } - if (!strcmp(var, "$DIMALT")) { - return true; - } - if (!strcmp(var, "$DIMALTD")) { - return true; - } - if (!strcmp(var, "$DIMALTF")) { - return true; - } - if (!strcmp(var, "$DIMAPOST")) { - return true; - } - if (!strcmp(var, "$DIMASO")) { - return true; - } - if (!strcmp(var, "$DIMASZ")) { - return true; - } - if (!strcmp(var, "$DIMBLK")) { - return true; - } - if (!strcmp(var, "$DIMBLK1")) { - return true; - } - if (!strcmp(var, "$DIMBLK2")) { - return true; - } - if (!strcmp(var, "$DIMCEN")) { - return true; - } - if (!strcmp(var, "$DIMCLRD")) { - return true; - } - if (!strcmp(var, "$DIMCLRE")) { - return true; - } - if (!strcmp(var, "$DIMCLRT")) { - return true; - } - if (!strcmp(var, "$DIMDLE")) { - return true; - } - if (!strcmp(var, "$DIMDLI")) { - return true; - } - if (!strcmp(var, "$DIMEXE")) { - return true; - } - if (!strcmp(var, "$DIMEXO")) { - return true; - } - if (!strcmp(var, "$DIMGAP")) { - return true; - } - if (!strcmp(var, "$DIMLFAC")) { - return true; - } - if (!strcmp(var, "$DIMLIM")) { - return true; - } - if (!strcmp(var, "$DIMPOST")) { - return true; - } - if (!strcmp(var, "$DIMRND")) { - return true; - } - if (!strcmp(var, "$DIMSAH")) { - return true; - } - if (!strcmp(var, "$DIMSCALE")) { - return true; - } - if (!strcmp(var, "$DIMSE1")) { - return true; - } - if (!strcmp(var, "$DIMSE2")) { - return true; - } - if (!strcmp(var, "$DIMSHO")) { - return true; - } - if (!strcmp(var, "$DIMSOXD")) { - return true; - } - if (!strcmp(var, "$DIMSTYLE")) { - return true; - } - if (!strcmp(var, "$DIMTAD")) { - return true; - } - if (!strcmp(var, "$DIMTFAC")) { - return true; - } - if (!strcmp(var, "$DIMTIH")) { - return true; - } - if (!strcmp(var, "$DIMTIX")) { - return true; - } - if (!strcmp(var, "$DIMTM")) { - return true; - } - if (!strcmp(var, "$DIMTOFL")) { - return true; - } - if (!strcmp(var, "$DIMTOH")) { - return true; - } - if (!strcmp(var, "$DIMTOL")) { - return true; - } - if (!strcmp(var, "$DIMTP")) { - return true; - } - if (!strcmp(var, "$DIMTSZ")) { - return true; - } - if (!strcmp(var, "$DIMTVP")) { - return true; - } - if (!strcmp(var, "$DIMTXT")) { - return true; - } - if (!strcmp(var, "$DIMZIN")) { - return true; - } - if (!strcmp(var, "$DWGCODEPAGE")) { - return true; - } - if (!strcmp(var, "$DRAGMODE")) { - return true; - } - if (!strcmp(var, "$ELEVATION")) { - return true; - } - if (!strcmp(var, "$EXTMAX")) { - return true; - } - if (!strcmp(var, "$EXTMIN")) { - return true; - } - if (!strcmp(var, "$FILLETRAD")) { - return true; - } - if (!strcmp(var, "$FILLMODE")) { - return true; - } - if (!strcmp(var, "$HANDLING")) { - return true; - } - if (!strcmp(var, "$HANDSEED")) { - return true; - } - if (!strcmp(var, "$INSBASE")) { - return true; - } - if (!strcmp(var, "$LIMCHECK")) { - return true; - } - if (!strcmp(var, "$LIMMAX")) { - return true; - } - if (!strcmp(var, "$LIMMIN")) { - return true; - } - if (!strcmp(var, "$LTSCALE")) { - return true; - } - if (!strcmp(var, "$LUNITS")) { - return true; - } - if (!strcmp(var, "$LUPREC")) { - return true; - } - if (!strcmp(var, "$MAXACTVP")) { - return true; - } - if (!strcmp(var, "$MENU")) { - return true; - } - if (!strcmp(var, "$MIRRTEXT")) { - return true; - } - if (!strcmp(var, "$ORTHOMODE")) { - return true; - } - if (!strcmp(var, "$OSMODE")) { - return true; - } - if (!strcmp(var, "$PDMODE")) { - return true; - } - if (!strcmp(var, "$PDSIZE")) { - return true; - } - if (!strcmp(var, "$PELEVATION")) { - return true; - } - if (!strcmp(var, "$PEXTMAX")) { - return true; - } - if (!strcmp(var, "$PEXTMIN")) { - return true; - } - if (!strcmp(var, "$PLIMCHECK")) { - return true; - } - if (!strcmp(var, "$PLIMMAX")) { - return true; - } - if (!strcmp(var, "$PLIMMIN")) { - return true; - } - if (!strcmp(var, "$PLINEGEN")) { - return true; - } - if (!strcmp(var, "$PLINEWID")) { - return true; - } - if (!strcmp(var, "$PSLTSCALE")) { - return true; - } - if (!strcmp(var, "$PUCSNAME")) { - return true; - } - if (!strcmp(var, "$PUCSORG")) { - return true; - } - if (!strcmp(var, "$PUCSXDIR")) { - return true; - } - if (!strcmp(var, "$PUCSYDIR")) { - return true; - } - if (!strcmp(var, "$QTEXTMODE")) { - return true; - } - if (!strcmp(var, "$REGENMODE")) { - return true; - } - if (!strcmp(var, "$SHADEDGE")) { - return true; - } - if (!strcmp(var, "$SHADEDIF")) { - return true; - } - if (!strcmp(var, "$SKETCHINC")) { - return true; - } - if (!strcmp(var, "$SKPOLY")) { - return true; - } - if (!strcmp(var, "$SPLFRAME")) { - return true; - } - if (!strcmp(var, "$SPLINESEGS")) { - return true; - } - if (!strcmp(var, "$SPLINETYPE")) { - return true; - } - if (!strcmp(var, "$SURFTAB1")) { - return true; - } - if (!strcmp(var, "$SURFTAB2")) { - return true; - } - if (!strcmp(var, "$SURFTYPE")) { - return true; - } - if (!strcmp(var, "$SURFU")) { - return true; - } - if (!strcmp(var, "$SURFV")) { - return true; - } - if (!strcmp(var, "$TDCREATE")) { - return true; - } - if (!strcmp(var, "$TDINDWG")) { - return true; - } - if (!strcmp(var, "$TDUPDATE")) { - return true; - } - if (!strcmp(var, "$TDUSRTIMER")) { - return true; - } - if (!strcmp(var, "$TEXTSIZE")) { - return true; - } - if (!strcmp(var, "$TEXTSTYLE")) { - return true; - } - if (!strcmp(var, "$THICKNESS")) { - return true; - } - if (!strcmp(var, "$TILEMODE")) { - return true; - } - if (!strcmp(var, "$TRACEWID")) { - return true; - } - if (!strcmp(var, "$UCSNAME")) { - return true; - } - if (!strcmp(var, "$UCSORG")) { - return true; - } - if (!strcmp(var, "$UCSXDIR")) { - return true; - } - if (!strcmp(var, "$UCSYDIR")) { - return true; - } - if (!strcmp(var, "$UNITMODE")) { - return true; - } - if (!strcmp(var, "$USERI1")) { - return true; - } - if (!strcmp(var, "$USERR1")) { - return true; - } - if (!strcmp(var, "$USRTIMER")) { - return true; - } - if (!strcmp(var, "$VISRETAIN")) { - return true; - } - if (!strcmp(var, "$WORLDVIEW")) { - return true; - } - if (!strcmp(var, "$FASTZOOM")) { - return true; - } - if (!strcmp(var, "$GRIDMODE")) { - return true; - } - if (!strcmp(var, "$GRIDUNIT")) { - return true; - } - if (!strcmp(var, "$SNAPANG")) { - return true; - } - if (!strcmp(var, "$SNAPBASE")) { - return true; - } - if (!strcmp(var, "$SNAPISOPAIR")) { - return true; - } - if (!strcmp(var, "$SNAPMODE")) { - return true; - } - if (!strcmp(var, "$SNAPSTYLE")) { - return true; - } - if (!strcmp(var, "$SNAPUNIT")) { - return true; - } - if (!strcmp(var, "$VIEWCTR")) { - return true; - } - if (!strcmp(var, "$VIEWDIR")) { - return true; - } - if (!strcmp(var, "$VIEWSIZE")) { - return true; - } - return false; - } - - return false; -} - - - -/** - * @returns the library version as int (4 bytes, each byte one version number). - * e.g. if str = "2.0.2.0" getLibVersion returns 0x02000200 - */ -int DL_Dxf::getLibVersion(const std::string& str) { - size_t d[4]; - int idx = 0; - //char v[4][5]; - std::string v[4]; - int ret = 0; - - for (size_t i=0; i=2) { - d[3] = str.length(); - - v[0] = str.substr(0, d[0]); - v[1] = str.substr(d[0]+1, d[1]-d[0]-1); - v[2] = str.substr(d[1]+1, d[2]-d[1]-1); - if (idx>=3) { - v[3] = str.substr(d[2]+1, d[3]-d[2]-1); - } - else { - v[3] = "0"; - } - - ret = (atoi(v[0].c_str())<<(3*8)) + - (atoi(v[1].c_str())<<(2*8)) + - (atoi(v[2].c_str())<<(1*8)) + - (atoi(v[3].c_str())<<(0*8)); - - return ret; - } else { - std::cerr << "DL_Dxf::getLibVersion: invalid version number: " << str << "\n"; - return 0; - } -} - -/** - * Converts the given string into a double or returns the given - * default valud (def) if value is NULL or empty. - */ -//double DL_Dxf::toReal(const char* value, double def) { -// if (value!=NULL && value[0] != '\0') { -// printf("toReal: not empty: %s\n", value); -// printf("toReal: val: %f\n", atof(value)); -// printf("toReal: 0: %d\n", value[0]); -// printf("toReal: 1: %d\n", value[1]); -// printf("toReal: 2: %d\n", value[2]); -// double ret; -// if (strchr(value, ',') != NULL) { -// char* tmp = new char[strlen(value)+1]; -// strcpy(tmp, value); -// DL_WriterA::strReplace(tmp, ',', '.'); -// ret = atof(tmp); -// delete[] tmp; -// } -// else { -// ret = atof(value); -// } -// return ret; -// } else { -// return def; -// } -//} - - -/** - * Some test routines. - */ -void DL_Dxf::test() { - char* buf1; - char* buf2; - char* buf3; - char* buf4; - char* buf5; - char* buf6; - - buf1 = new char[10]; - buf2 = new char[10]; - buf3 = new char[10]; - buf4 = new char[10]; - buf5 = new char[10]; - buf6 = new char[10]; - - strcpy(buf1, " 10\n"); - strcpy(buf2, "10"); - strcpy(buf3, "10\n"); - strcpy(buf4, " 10 \n"); - strcpy(buf5, " 10 \r"); - strcpy(buf6, "\t10 \n"); - - std::cout << "1 buf1: '" << buf1 << "'\n"; - stripWhiteSpace(&buf1); - std::cout << "2 buf1: '" << buf1 << "'\n"; - //assert(!strcmp(buf1, "10")); - - std::cout << "1 buf2: '" << buf2 << "'\n"; - stripWhiteSpace(&buf2); - std::cout << "2 buf2: '" << buf2 << "'\n"; - - std::cout << "1 buf3: '" << buf3 << "'\n"; - stripWhiteSpace(&buf3); - std::cout << "2 buf3: '" << buf3 << "'\n"; - - std::cout << "1 buf4: '" << buf4 << "'\n"; - stripWhiteSpace(&buf4); - std::cout << "2 buf4: '" << buf4 << "'\n"; - - std::cout << "1 buf5: '" << buf5 << "'\n"; - stripWhiteSpace(&buf5); - std::cout << "2 buf5: '" << buf5 << "'\n"; - - std::cout << "1 buf6: '" << buf6 << "'\n"; - stripWhiteSpace(&buf6); - std::cout << "2 buf6: '" << buf6 << "'\n"; - -} - - diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.h deleted file mode 100644 index 7ddae0bfeea7..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_dxf.h +++ /dev/null @@ -1,510 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_DXF_H -#define DL_DXF_H - -#include "dl_global.h" - -#include -#include -#include -#include -#include - -#include "dl_attributes.h" -#include "dl_codes.h" -#include "dl_entities.h" -#include "dl_writer_ascii.h" - -#ifdef _WIN32 -#undef M_PI -#define M_PI 3.14159265358979323846 -#pragma warning(disable : 4800) -#endif - -#ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 -#endif - -class DL_CreationInterface; -class DL_WriterA; - - -#define DL_VERSION "3.7.5.0" - -#define DL_VERSION_MAJOR 3 -#define DL_VERSION_MINOR 7 -#define DL_VERSION_REV 5 -#define DL_VERSION_BUILD 0 - -#define DL_UNKNOWN 0 -#define DL_LAYER 10 -#define DL_BLOCK 11 -#define DL_ENDBLK 12 -#define DL_LINETYPE 13 -#define DL_STYLE 20 -#define DL_SETTING 50 -#define DL_ENTITY_POINT 100 -#define DL_ENTITY_LINE 101 -#define DL_ENTITY_POLYLINE 102 -#define DL_ENTITY_LWPOLYLINE 103 -#define DL_ENTITY_VERTEX 104 -#define DL_ENTITY_SPLINE 105 -#define DL_ENTITY_KNOT 106 -#define DL_ENTITY_CONTROLPOINT 107 -#define DL_ENTITY_ARC 108 -#define DL_ENTITY_CIRCLE 109 -#define DL_ENTITY_ELLIPSE 110 -#define DL_ENTITY_INSERT 111 -#define DL_ENTITY_TEXT 112 -#define DL_ENTITY_MTEXT 113 -#define DL_ENTITY_DIMENSION 114 -#define DL_ENTITY_LEADER 115 -#define DL_ENTITY_HATCH 116 -#define DL_ENTITY_ATTRIB 117 -#define DL_ENTITY_IMAGE 118 -#define DL_ENTITY_IMAGEDEF 119 -#define DL_ENTITY_TRACE 120 -#define DL_ENTITY_SOLID 121 -#define DL_ENTITY_3DFACE 122 -#define DL_ENTITY_XLINE 123 -#define DL_ENTITY_RAY 124 -#define DL_ENTITY_SEQEND 125 -#define DL_XRECORD 200 -#define DL_DICTIONARY 210 - - -/** - * Reading and writing of DXF files. - * - * This class can read in a DXF file and calls methods from the - * interface DL_EntityContainer to add the entities to the - * contianer provided by the user of the library. - * - * It can also be used to write DXF files to a certain extent. - * - * When saving entities, special values for colors and linetypes - * can be used: - * - * Special colors are 0 (=BYBLOCK) and 256 (=BYLAYER). - * Special linetypes are "BYLAYER" and "BYBLOCK". - * - * @author Andrew Mustun - */ -class DXFLIB_EXPORT DL_Dxf { -public: - DL_Dxf(); - ~DL_Dxf(); - - bool in(const std::string& file, - DL_CreationInterface* creationInterface); - bool readDxfGroups(FILE* fp, - DL_CreationInterface* creationInterface); - static bool getStrippedLine(std::string& s, unsigned int size, - FILE* stream); - - bool readDxfGroups(std::stringstream& stream, - DL_CreationInterface* creationInterface); - bool in(std::stringstream &stream, - DL_CreationInterface* creationInterface); - static bool getStrippedLine(std::string& s, unsigned int size, - std::stringstream& stream); - - static bool stripWhiteSpace(char** s); - - bool processDXFGroup(DL_CreationInterface* creationInterface, - int groupCode, const std::string& groupValue); - void addSetting(DL_CreationInterface* creationInterface); - void addLayer(DL_CreationInterface* creationInterface); - void addLinetype(DL_CreationInterface *creationInterface); - void addBlock(DL_CreationInterface* creationInterface); - void endBlock(DL_CreationInterface* creationInterface); - void addTextStyle(DL_CreationInterface* creationInterface); - - void addPoint(DL_CreationInterface* creationInterface); - void addLine(DL_CreationInterface* creationInterface); - void addXLine(DL_CreationInterface* creationInterface); - void addRay(DL_CreationInterface* creationInterface); - - void addPolyline(DL_CreationInterface* creationInterface); - void addVertex(DL_CreationInterface* creationInterface); - - void addSpline(DL_CreationInterface* creationInterface); - - void addArc(DL_CreationInterface* creationInterface); - void addCircle(DL_CreationInterface* creationInterface); - void addEllipse(DL_CreationInterface* creationInterface); - void addInsert(DL_CreationInterface* creationInterface); - - void addTrace(DL_CreationInterface* creationInterface); - void add3dFace(DL_CreationInterface* creationInterface); - void addSolid(DL_CreationInterface* creationInterface); - - void addMText(DL_CreationInterface* creationInterface); - void addText(DL_CreationInterface* creationInterface); - - void addAttribute(DL_CreationInterface* creationInterface); - - DL_DimensionData getDimData(); - void addDimLinear(DL_CreationInterface* creationInterface); - void addDimAligned(DL_CreationInterface* creationInterface); - void addDimRadial(DL_CreationInterface* creationInterface); - void addDimDiametric(DL_CreationInterface* creationInterface); - void addDimAngular(DL_CreationInterface* creationInterface); - void addDimAngular3P(DL_CreationInterface* creationInterface); - void addDimOrdinate(DL_CreationInterface* creationInterface); - - void addLeader(DL_CreationInterface* creationInterface); - - void addHatch(DL_CreationInterface* creationInterface); - void addHatchLoop(); - void addHatchEdge(); - bool handleHatchData(DL_CreationInterface* creationInterface); - - void addImage(DL_CreationInterface* creationInterface); - void addImageDef(DL_CreationInterface* creationInterface); - - void addComment(DL_CreationInterface* creationInterface, const std::string& comment); - - void addDictionary(DL_CreationInterface* creationInterface); - void addDictionaryEntry(DL_CreationInterface* creationInterface); - - bool handleXRecordData(DL_CreationInterface* creationInterface); - bool handleDictionaryData(DL_CreationInterface* creationInterface); - - bool handleXData(DL_CreationInterface *creationInterface); - bool handleMTextData(DL_CreationInterface* creationInterface); - bool handleLWPolylineData(DL_CreationInterface* creationInterface); - bool handleSplineData(DL_CreationInterface* creationInterface); - bool handleLeaderData(DL_CreationInterface* creationInterface); - bool handleLinetypeData(DL_CreationInterface* creationInterface); - - void endEntity(DL_CreationInterface* creationInterface); - - void endSequence(DL_CreationInterface* creationInterface); - - //int stringToInt(const char* s, bool* ok=NULL); - - DL_WriterA* out(const char* file, - DL_Codes::version version=DL_VERSION_2000); - - void writeHeader(DL_WriterA& dw); - - void writePoint(DL_WriterA& dw, - const DL_PointData& data, - const DL_Attributes& attrib); - void writeLine(DL_WriterA& dw, - const DL_LineData& data, - const DL_Attributes& attrib); - void writeXLine(DL_WriterA& dw, - const DL_XLineData& data, - const DL_Attributes& attrib); - void writeRay(DL_WriterA& dw, - const DL_RayData& data, - const DL_Attributes& attrib); - void writePolyline(DL_WriterA& dw, - const DL_PolylineData& data, - const DL_Attributes& attrib); - void writeVertex(DL_WriterA& dw, - const DL_VertexData& data); - void writePolylineEnd(DL_WriterA& dw); - void writeSpline(DL_WriterA& dw, - const DL_SplineData& data, - const DL_Attributes& attrib); - void writeControlPoint(DL_WriterA& dw, - const DL_ControlPointData& data); - void writeFitPoint(DL_WriterA& dw, - const DL_FitPointData& data); - void writeKnot(DL_WriterA& dw, - const DL_KnotData& data); - void writeCircle(DL_WriterA& dw, - const DL_CircleData& data, - const DL_Attributes& attrib); - void writeArc(DL_WriterA& dw, - const DL_ArcData& data, - const DL_Attributes& attrib); - void writeEllipse(DL_WriterA& dw, - const DL_EllipseData& data, - const DL_Attributes& attrib); - void writeSolid(DL_WriterA& dw, - const DL_SolidData& data, - const DL_Attributes& attrib); - void writeTrace(DL_WriterA& dw, - const DL_TraceData& data, - const DL_Attributes& attrib); - void write3dFace(DL_WriterA& dw, - const DL_3dFaceData& data, - const DL_Attributes& attrib); - void writeInsert(DL_WriterA& dw, - const DL_InsertData& data, - const DL_Attributes& attrib); - void writeMText(DL_WriterA& dw, - const DL_MTextData& data, - const DL_Attributes& attrib); - void writeText(DL_WriterA& dw, - const DL_TextData& data, - const DL_Attributes& attrib); - void writeAttribute(DL_WriterA& dw, - const DL_AttributeData& data, - const DL_Attributes& attrib); - void writeDimStyleOverrides(DL_WriterA& dw, - const DL_DimensionData& data); - void writeDimAligned(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimAlignedData& edata, - const DL_Attributes& attrib); - void writeDimLinear(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimLinearData& edata, - const DL_Attributes& attrib); - void writeDimRadial(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimRadialData& edata, - const DL_Attributes& attrib); - void writeDimDiametric(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimDiametricData& edata, - const DL_Attributes& attrib); - void writeDimAngular(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimAngularData& edata, - const DL_Attributes& attrib); - void writeDimAngular3P(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimAngular3PData& edata, - const DL_Attributes& attrib); - void writeDimOrdinate(DL_WriterA& dw, - const DL_DimensionData& data, - const DL_DimOrdinateData& edata, - const DL_Attributes& attrib); - void writeLeader(DL_WriterA& dw, - const DL_LeaderData& data, - const DL_Attributes& attrib); - void writeLeaderVertex(DL_WriterA& dw, - const DL_LeaderVertexData& data); - void writeHatch1(DL_WriterA& dw, - const DL_HatchData& data, - const DL_Attributes& attrib); - void writeHatch2(DL_WriterA& dw, - const DL_HatchData& data, - const DL_Attributes& attrib); - void writeHatchLoop1(DL_WriterA& dw, - const DL_HatchLoopData& data); - void writeHatchLoop2(DL_WriterA& dw, - const DL_HatchLoopData& data); - void writeHatchEdge(DL_WriterA& dw, - const DL_HatchEdgeData& data); - - int writeImage(DL_WriterA& dw, - const DL_ImageData& data, - const DL_Attributes& attrib); - - void writeImageDef(DL_WriterA& dw, int handle, - const DL_ImageData& data); - - void writeLayer(DL_WriterA& dw, - const DL_LayerData& data, - const DL_Attributes& attrib); - - void writeLinetype(DL_WriterA& dw, - const DL_LinetypeData& data); - - void writeAppid(DL_WriterA& dw, const std::string& name); - - void writeBlock(DL_WriterA& dw, - const DL_BlockData& data); - void writeEndBlock(DL_WriterA& dw, const std::string& name); - - void writeVPort(DL_WriterA& dw); - void writeStyle(DL_WriterA& dw, const DL_StyleData& style); - void writeView(DL_WriterA& dw); - void writeUcs(DL_WriterA& dw); - void writeDimStyle(DL_WriterA& dw, - double dimasz, double dimexe, double dimexo, - double dimgap, double dimtxt); - void writeBlockRecord(DL_WriterA& dw); - void writeBlockRecord(DL_WriterA& dw, const std::string& name); - void writeObjects(DL_WriterA& dw, const std::string& appDictionaryName = ""); - void writeAppDictionary(DL_WriterA& dw); - int writeDictionaryEntry(DL_WriterA& dw, const std::string& name); - void writeXRecord(DL_WriterA& dw, int handle, int value); - void writeXRecord(DL_WriterA& dw, int handle, double value); - void writeXRecord(DL_WriterA& dw, int handle, bool value); - void writeXRecord(DL_WriterA& dw, int handle, const std::string& value); - void writeObjectsEnd(DL_WriterA& dw); - - void writeComment(DL_WriterA& dw, const std::string& comment); - - /** - * Converts the given string into a double or returns the given - * default valud (def) if value is NULL or empty. - */ - //static double toReal(const char* value, double def=0.0); - - /** - * Converts the given string into an int or returns the given - * default valud (def) if value is NULL or empty. - */ -// static int toInt(const char* value, int def=0) { -// if (value!=NULL && value[0] != '\0') { -// return atoi(value); -// } - -// return def; -// } - - /** - * Converts the given string into a string or returns the given - * default valud (def) if value is NULL or empty. - */ -// static const char* toString(const char* value, const char* def="") { -// if (value!=NULL && value[0] != '\0') { -// return value; -// } else { -// return def; -// } -// } - - static bool checkVariable(const char* var, DL_Codes::version version); - - DL_Codes::version getVersion() { - return version; - } - - int getLibVersion(const std::string &str); - - static void test(); - - bool hasValue(int code) { - return values.count(code)==1; - } - - int getIntValue(int code, int def) { - if (!hasValue(code)) { - return def; - } - return toInt(values[code]); - } - - int toInt(const std::string& str) { - char* p; - return strtol(str.c_str(), &p, 10); - } - - bool toBool(const std::string& str) { - char* p; - return static_cast( strtol(str.c_str(), &p, 10) ); - } - - std::string getStringValue(int code, const std::string& def) { - if (!hasValue(code)) { - return def; - } - return values[code]; - } - - double getRealValue(int code, double def) { - if (!hasValue(code)) { - return def; - } - return toReal(values[code]); - } - - double toReal(const std::string& str) { - double ret; - // make sure the real value uses '.' not ',': - std::string str2 = str; - std::replace(str2.begin(), str2.end(), ',', '.'); - // make sure c++ expects '.' not ',': - std::istringstream istr(str2); - istr.imbue(std::locale("C")); - istr >> ret; - return ret; - } - -private: - DL_Codes::version version; - - std::string polylineLayer; - double* vertices; - int maxVertices; - int vertexIndex; - - double* knots; - int maxKnots; - int knotIndex; - - double* weights; - int weightIndex; - - double* controlPoints; - int maxControlPoints; - int controlPointIndex; - - double* fitPoints; - int maxFitPoints; - int fitPointIndex; - - double* leaderVertices; - int maxLeaderVertices; - int leaderVertexIndex; - - bool firstHatchLoop; - DL_HatchEdgeData hatchEdge; - std::vector > hatchEdges; - - std::string xRecordHandle; - bool xRecordValues; - - // Only the useful part of the group code - std::string groupCodeTmp; - // ...same as integer - unsigned int groupCode; - // Only the useful part of the group value - std::string groupValue; - // Current entity type - int currentObjectType; - // Value of the current setting - char settingValue[DL_DXF_MAXLINE+1]; - // Key of the current setting (e.g. "$ACADVER") - std::string settingKey; - // Stores the group codes - std::map values; - // First call of this method. We initialize all group values in - // the first call. - bool firstCall; - // Attributes of the current entity (layer, color, width, line type) - DL_Attributes attrib; - // library version. hex: 0x20003001 = 2.0.3.1 - int libVersion; - // app specific dictionary handle: - unsigned long appDictionaryHandle; - // handle of standard text style, referenced by dimstyle: - unsigned long styleHandleStd; -}; - -#endif - -// EOF diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h deleted file mode 100644 index 654195b46a2c..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_entities.h +++ /dev/null @@ -1,1724 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_ENTITIES_H -#define DL_ENTITIES_H - -#include "dl_global.h" -#include "qgis.h" - -#include -#include - -/** - * Layer Data. - */ -struct DXFLIB_EXPORT DL_LayerData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_LayerData(const std::string& lName, - int lFlags) { - name = lName; - flags = lFlags; - } - - /** Layer name. */ - std::string name; - /** Layer flags. (1 = frozen, 2 = frozen by default, 4 = locked) */ - int flags; -}; - - - -/** - * Block Data. - */ -struct DXFLIB_EXPORT DL_BlockData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_BlockData(const std::string& bName, - int bFlags, - double bbpx, double bbpy, double bbpz) { - name = bName; - flags = bFlags; - bpx = bbpx; - bpy = bbpy; - bpz = bbpz; - } - - /** Block name. */ - std::string name; - /** Block flags. (not used currently) */ - int flags; - /** X Coordinate of base point. */ - double bpx; - /** Y Coordinate of base point. */ - double bpy; - /** Z Coordinate of base point. */ - double bpz; -}; - - -/** - * Line Type Data. - */ -struct DXFLIB_EXPORT DL_LinetypeData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_LinetypeData( - const std::string& name, - const std::string& description, - int flags, - int numberOfDashes, - double patternLength, - double* pattern = nullptr - ) - : name(name), - description(description), - flags(flags), - numberOfDashes(numberOfDashes), - patternLength(patternLength), - pattern(pattern) - {} - - /** Linetype name */ - std::string name; - /** Linetype description */ - std::string description; - /** Linetype flags */ - int flags; - /** Number of dashes */ - int numberOfDashes; - /** Pattern length */ - double patternLength; - /** Pattern */ - double* pattern; -}; - - - -/** - * Text style data. - */ -struct DXFLIB_EXPORT DL_StyleData { - /** - * Constructor - * Parameters: see member variables. - */ - DL_StyleData( - const std::string& name, - int flags, - double fixedTextHeight, - double widthFactor, - double obliqueAngle, - int textGenerationFlags, - double lastHeightUsed, - const std::string& primaryFontFile, - const std::string& bigFontFile - ) - : name(name), - flags(flags), - fixedTextHeight(fixedTextHeight), - widthFactor(widthFactor), - obliqueAngle(obliqueAngle), - textGenerationFlags(textGenerationFlags), - lastHeightUsed(lastHeightUsed), - primaryFontFile(primaryFontFile), - bigFontFile(bigFontFile), - bold(false), - italic(false) { - } - - bool operator==(const DL_StyleData& other) { - // ignore lastHeightUsed: - return (name==other.name && - flags==other.flags && - qgsDoubleNear( fixedTextHeight, other.fixedTextHeight ) && - qgsDoubleNear( widthFactor, other.widthFactor ) && - qgsDoubleNear( obliqueAngle, other.obliqueAngle ) && - textGenerationFlags==other.textGenerationFlags && - primaryFontFile==other.primaryFontFile && - bigFontFile==other.bigFontFile); - } - - /** Style name */ - std::string name; - /** Style flags */ - int flags; - /** Fixed text height or 0 for not fixed. */ - double fixedTextHeight; - /** Width factor */ - double widthFactor; - /** Oblique angle */ - double obliqueAngle; - /** Text generation flags */ - int textGenerationFlags; - /** Last height used */ - double lastHeightUsed; - /** Primary font file name */ - std::string primaryFontFile; - /** Big font file name */ - std::string bigFontFile; - - bool bold; - bool italic; -}; - -/** - * Point Data. - */ -struct DXFLIB_EXPORT DL_PointData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_PointData(double px=0.0, double py=0.0, double pz=0.0) { - x = px; - y = py; - z = pz; - } - - /*! X Coordinate of the point. */ - double x; - /*! Y Coordinate of the point. */ - double y; - /*! Z Coordinate of the point. */ - double z; -}; - - - -/** - * Line Data. - */ -struct DXFLIB_EXPORT DL_LineData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_LineData(double lx1, double ly1, double lz1, - double lx2, double ly2, double lz2) { - x1 = lx1; - y1 = ly1; - z1 = lz1; - - x2 = lx2; - y2 = ly2; - z2 = lz2; - } - - /*! X Start coordinate of the point. */ - double x1; - /*! Y Start coordinate of the point. */ - double y1; - /*! Z Start coordinate of the point. */ - double z1; - - /*! X End coordinate of the point. */ - double x2; - /*! Y End coordinate of the point. */ - double y2; - /*! Z End coordinate of the point. */ - double z2; -}; - -/** - * XLine Data. - */ -struct DXFLIB_EXPORT DL_XLineData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_XLineData(double bx, double by, double bz, - double dx, double dy, double dz) : - bx(bx), by(by), bz(bz), - dx(dx), dy(dy), dz(dz) { - } - - /*! X base point. */ - double bx; - /*! Y base point. */ - double by; - /*! Z base point. */ - double bz; - - /*! X direction vector. */ - double dx; - /*! Y direction vector. */ - double dy; - /*! Z direction vector. */ - double dz; -}; - -/** - * Ray Data. - */ -struct DXFLIB_EXPORT DL_RayData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_RayData(double bx, double by, double bz, - double dx, double dy, double dz) : - bx(bx), by(by), bz(bz), - dx(dx), dy(dy), dz(dz) { - } - - /*! X base point. */ - double bx; - /*! Y base point. */ - double by; - /*! Z base point. */ - double bz; - - /*! X direction vector. */ - double dx; - /*! Y direction vector. */ - double dy; - /*! Z direction vector. */ - double dz; -}; - - - -/** - * Arc Data. - */ -struct DXFLIB_EXPORT DL_ArcData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_ArcData(double acx, double acy, double acz, - double aRadius, - double aAngle1, double aAngle2) { - - cx = acx; - cy = acy; - cz = acz; - radius = aRadius; - angle1 = aAngle1; - angle2 = aAngle2; - } - - /*! X Coordinate of center point. */ - double cx; - /*! Y Coordinate of center point. */ - double cy; - /*! Z Coordinate of center point. */ - double cz; - - /*! Radius of arc. */ - double radius; - /*! Startangle of arc in degrees. */ - double angle1; - /*! Endangle of arc in degrees. */ - double angle2; -}; - - - -/** - * Circle Data. - */ -struct DXFLIB_EXPORT DL_CircleData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_CircleData(double acx, double acy, double acz, - double aRadius) { - - cx = acx; - cy = acy; - cz = acz; - radius = aRadius; - } - - /*! X Coordinate of center point. */ - double cx; - /*! Y Coordinate of center point. */ - double cy; - /*! Z Coordinate of center point. */ - double cz; - - /*! Radius of arc. */ - double radius; -}; - - - -/** - * Polyline Data. - */ -struct DXFLIB_EXPORT DL_PolylineData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_PolylineData(int pNumber, int pMVerteces, int pNVerteces, int pFlags) { - number = pNumber; - m = pMVerteces; - n = pNVerteces; - flags = pFlags; - } - - /*! Number of vertices in this polyline. */ - unsigned int number; - - /*! Number of vertices in m direction if polyline is a polygon mesh. */ - unsigned int m; - - /*! Number of vertices in n direction if polyline is a polygon mesh. */ - unsigned int n; - - /*! Flags */ - int flags; -}; - - - -/** - * Vertex Data. - */ -struct DXFLIB_EXPORT DL_VertexData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_VertexData(double px=0.0, double py=0.0, double pz=0.0, - double pBulge=0.0) { - x = px; - y = py; - z = pz; - bulge = pBulge; - } - - /*! X Coordinate of the vertex. */ - double x; - /*! Y Coordinate of the vertex. */ - double y; - /*! Z Coordinate of the vertex. */ - double z; - /*! Bulge of vertex. - * (The tangent of 1/4 of the arc angle or 0 for lines) */ - double bulge; -}; - - -/** - * Trace Data / solid data / 3d face data. - */ -struct DXFLIB_EXPORT DL_TraceData { - DL_TraceData() { - thickness = 0.0; - for (int i=0; i<4; i++) { - x[i] = 0.0; - y[i] = 0.0; - z[i] = 0.0; - } - } - - /** - * Constructor. - * Parameters: see member variables. - */ - DL_TraceData(double sx1, double sy1, double sz1, - double sx2, double sy2, double sz2, - double sx3, double sy3, double sz3, - double sx4, double sy4, double sz4, - double sthickness=0.0) { - - thickness = sthickness; - - x[0] = sx1; - y[0] = sy1; - z[0] = sz1; - - x[1] = sx2; - y[1] = sy2; - z[1] = sz2; - - x[2] = sx3; - y[2] = sy3; - z[2] = sz3; - - x[3] = sx4; - y[3] = sy4; - z[3] = sz4; - } - - /*! Thickness */ - double thickness; - - /*! Points */ - double x[4]; - double y[4]; - double z[4]; -}; - - - - - -/** - * Solid Data. - */ -typedef DL_TraceData DL_SolidData; - - -/** - * 3dface Data. - */ -typedef DL_TraceData DL_3dFaceData; - - -/** - * Spline Data. - */ -struct DXFLIB_EXPORT DL_SplineData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_SplineData(int degree, - int nKnots, - int nControl, - int nFit, - int flags) : - degree(degree), - nKnots(nKnots), - nControl(nControl), - nFit(nFit), - flags(flags) { - } - - /*! Degree of the spline curve. */ - unsigned int degree; - - /*! Number of knots. */ - unsigned int nKnots; - - /*! Number of control points. */ - unsigned int nControl; - - /*! Number of fit points. */ - unsigned int nFit; - - /*! Flags */ - int flags; - - double tangentStartX; - double tangentStartY; - double tangentStartZ; - double tangentEndX; - double tangentEndY; - double tangentEndZ; -}; - - - -/** - * Spline knot data. - */ -struct DXFLIB_EXPORT DL_KnotData { - DL_KnotData() {} - /** - * Constructor. - * Parameters: see member variables. - */ - DL_KnotData(double pk) { - k = pk; - } - - /*! Knot value. */ - double k; -}; - - - -/** - * Spline control point data. - */ -struct DXFLIB_EXPORT DL_ControlPointData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_ControlPointData(double px, double py, double pz, double weight) { - x = px; - y = py; - z = pz; - w = weight; - } - - /*! X coordinate of the control point. */ - double x; - /*! Y coordinate of the control point. */ - double y; - /*! Z coordinate of the control point. */ - double z; - /*! Weight of control point. */ - double w; -}; - - - -/** - * Spline fit point data. - */ -struct DXFLIB_EXPORT DL_FitPointData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_FitPointData(double x, double y, double z) : x(x), y(y), z(z) {} - - /*! X coordinate of the fit point. */ - double x; - /*! Y coordinate of the fit point. */ - double y; - /*! Z coordinate of the fit point. */ - double z; -}; - - - -/** - * Ellipse Data. - */ -struct DXFLIB_EXPORT DL_EllipseData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_EllipseData(double cx, double cy, double cz, - double mx, double my, double mz, - double ratio, - double angle1, double angle2) - : cx(cx), - cy(cy), - cz(cz), - mx(mx), - my(my), - mz(mz), - ratio(ratio), - angle1(angle1), - angle2(angle2) { - } - - /*! X Coordinate of center point. */ - double cx; - /*! Y Coordinate of center point. */ - double cy; - /*! Z Coordinate of center point. */ - double cz; - - /*! X coordinate of the endpoint of the major axis. */ - double mx; - /*! Y coordinate of the endpoint of the major axis. */ - double my; - /*! Z coordinate of the endpoint of the major axis. */ - double mz; - - /*! Ratio of minor axis to major axis.. */ - double ratio; - /*! Startangle of ellipse in rad. */ - double angle1; - /*! Endangle of ellipse in rad. */ - double angle2; -}; - - - -/** - * Insert Data. - */ -struct DXFLIB_EXPORT DL_InsertData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_InsertData(const std::string& name, - double ipx, double ipy, double ipz, - double sx, double sy, double sz, - double angle, - int cols, int rows, - double colSp, double rowSp) : - name(name), - ipx(ipx), ipy(ipy), ipz(ipz), - sx(sx), sy(sy), sz(sz), - angle(angle), - cols(cols), rows(rows), - colSp(colSp), rowSp(rowSp) { - } - - /*! Name of the referred block. */ - std::string name; - /*! X Coordinate of insertion point. */ - double ipx; - /*! Y Coordinate of insertion point. */ - double ipy; - /*! Z Coordinate of insertion point. */ - double ipz; - /*! X Scale factor. */ - double sx; - /*! Y Scale factor. */ - double sy; - /*! Z Scale factor. */ - double sz; - /*! Rotation angle in degrees. */ - double angle; - /*! Number of columns if we insert an array of the block or 1. */ - int cols; - /*! Number of rows if we insert an array of the block or 1. */ - int rows; - /*! Values for the spacing between cols. */ - double colSp; - /*! Values for the spacing between rows. */ - double rowSp; -}; - - - -/** - * MText Data. - */ -struct DXFLIB_EXPORT DL_MTextData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_MTextData(double ipx, double ipy, double ipz, - double dirx, double diry, double dirz, - double height, double width, - int attachmentPoint, - int drawingDirection, - int lineSpacingStyle, - double lineSpacingFactor, - const std::string& text, - const std::string& style, - double angle) : - ipx(ipx), ipy(ipy), ipz(ipz), - dirx(dirx), diry(diry), dirz(dirz), - height(height), width(width), - attachmentPoint(attachmentPoint), - drawingDirection(drawingDirection), - lineSpacingStyle(lineSpacingStyle), - lineSpacingFactor(lineSpacingFactor), - text(text), - style(style), - angle(angle) { - - } - - /*! X Coordinate of insertion point. */ - double ipx; - /*! Y Coordinate of insertion point. */ - double ipy; - /*! Z Coordinate of insertion point. */ - double ipz; - /*! X Coordinate of X direction vector. */ - double dirx; - /*! Y Coordinate of X direction vector. */ - double diry; - /*! Z Coordinate of X direction vector. */ - double dirz; - /*! Text height */ - double height; - /*! Width of the text box. */ - double width; - /** - * Attachment point. - * - * 1 = Top left, 2 = Top center, 3 = Top right, - * 4 = Middle left, 5 = Middle center, 6 = Middle right, - * 7 = Bottom left, 8 = Bottom center, 9 = Bottom right - */ - int attachmentPoint; - /** - * Drawing direction. - * - * 1 = left to right, 3 = top to bottom, 5 = by style - */ - int drawingDirection; - /** - * Line spacing style. - * - * 1 = at least, 2 = exact - */ - int lineSpacingStyle; - /** - * Line spacing factor. 0.25 .. 4.0 - */ - double lineSpacingFactor; - /*! Text string. */ - std::string text; - /*! Style string. */ - std::string style; - /*! Rotation angle. */ - double angle; -}; - - - -/** - * Text Data. - */ -struct DXFLIB_EXPORT DL_TextData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_TextData(double ipx, double ipy, double ipz, - double apx, double apy, double apz, - double height, double xScaleFactor, - int textGenerationFlags, - int hJustification, - int vJustification, - const std::string& text, - const std::string& style, - double angle) - : ipx(ipx), ipy(ipy), ipz(ipz), - apx(apx), apy(apy), apz(apz), - height(height), xScaleFactor(xScaleFactor), - textGenerationFlags(textGenerationFlags), - hJustification(hJustification), - vJustification(vJustification), - text(text), - style(style), - angle(angle) { - } - - /*! X Coordinate of insertion point. */ - double ipx; - /*! Y Coordinate of insertion point. */ - double ipy; - /*! Z Coordinate of insertion point. */ - double ipz; - - /*! X Coordinate of alignment point. */ - double apx; - /*! Y Coordinate of alignment point. */ - double apy; - /*! Z Coordinate of alignment point. */ - double apz; - - /*! Text height */ - double height; - /*! Relative X scale factor. */ - double xScaleFactor; - /*! 0 = default, 2 = Backwards, 4 = Upside down */ - int textGenerationFlags; - /** - * Horizontal justification. - * - * 0 = Left (default), 1 = Center, 2 = Right, - * 3 = Aligned, 4 = Middle, 5 = Fit - * For 3, 4, 5 the vertical alignment has to be 0. - */ - int hJustification; - /** - * Vertical justification. - * - * 0 = Baseline (default), 1 = Bottom, 2 = Middle, 3= Top - */ - int vJustification; - /*! Text string. */ - std::string text; - /*! Style (font). */ - std::string style; - /*! Rotation angle of dimension text away from default orientation. */ - double angle; -}; - - -/** - * Block attribute data. - */ -struct DXFLIB_EXPORT DL_AttributeData : public DL_TextData { - DL_AttributeData(const DL_TextData& tData, const std::string& tag) - : DL_TextData(tData), tag(tag) { - - } - - /** - * Constructor. - * Parameters: see member variables. - */ - DL_AttributeData(double ipx, double ipy, double ipz, - double apx, double apy, double apz, - double height, double xScaleFactor, - int textGenerationFlags, - int hJustification, - int vJustification, - const std::string& tag, - const std::string& text, - const std::string& style, - double angle) - : DL_TextData(ipx, ipy, ipz, - apx, apy, apz, - height, xScaleFactor, - textGenerationFlags, - hJustification, - vJustification, - text, - style, - angle), - tag(tag) { - } - - /*! Tag. */ - std::string tag; -}; - - -/** - * Generic Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimensionData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimensionData(double dpx, double dpy, double dpz, - double mpx, double mpy, double mpz, - int type, - int attachmentPoint, - int lineSpacingStyle, - double lineSpacingFactor, - const std::string& text, - const std::string& style, - double angle, - double linearFactor = 1.0) : - dpx(dpx), dpy(dpy), dpz(dpz), - mpx(mpx), mpy(mpy), mpz(mpz), - type(type), - attachmentPoint(attachmentPoint), - lineSpacingStyle(lineSpacingStyle), - lineSpacingFactor(lineSpacingFactor), - text(text), - style(style), - angle(angle), - linearFactor(linearFactor) { - - } - - /*! X Coordinate of definition point. */ - double dpx; - /*! Y Coordinate of definition point. */ - double dpy; - /*! Z Coordinate of definition point. */ - double dpz; - /*! X Coordinate of middle point of the text. */ - double mpx; - /*! Y Coordinate of middle point of the text. */ - double mpy; - /*! Z Coordinate of middle point of the text. */ - double mpz; - /** - * Dimension type. - * - * 0 Rotated, horizontal, or vertical - * 1 Aligned - * 2 Angular - * 3 Diametric - * 4 Radius - * 5 Angular 3-point - * 6 Ordinate - * 64 Ordinate type. This is a bit value (bit 7) - * used only with integer value 6. If set, - * ordinate is X-type; if not set, ordinate is - * Y-type - * 128 This is a bit value (bit 8) added to the - * other group 70 values if the dimension text - * has been positioned at a user-defined - * location rather than at the default location - */ - int type; - /** - * Attachment point. - * - * 1 = Top left, 2 = Top center, 3 = Top right, - * 4 = Middle left, 5 = Middle center, 6 = Middle right, - * 7 = Bottom left, 8 = Bottom center, 9 = Bottom right, - */ - int attachmentPoint; - /** - * Line spacing style. - * - * 1 = at least, 2 = exact - */ - int lineSpacingStyle; - /** - * Line spacing factor. 0.25 .. 4.0 - */ - double lineSpacingFactor; - /** - * Text string. - * - * Text string entered explicitly by user or null - * or "<>" for the actual measurement or " " (one blank space). - * for supressing the text. - */ - std::string text; - /*! Dimension style (font name). */ - std::string style; - /** - * Rotation angle of dimension text away from - * default orientation. - */ - double angle; - /** - * Linear factor style override. - */ - double linearFactor; -}; - - - -/** - * Aligned Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimAlignedData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimAlignedData(double depx1, double depy1, double depz1, - double depx2, double depy2, double depz2) { - - epx1 = depx1; - epy1 = depy1; - epz1 = depz1; - - epx2 = depx2; - epy2 = depy2; - epz2 = depz2; - } - - /*! X Coordinate of Extension point 1. */ - double epx1; - /*! Y Coordinate of Extension point 1. */ - double epy1; - /*! Z Coordinate of Extension point 1. */ - double epz1; - - /*! X Coordinate of Extension point 2. */ - double epx2; - /*! Y Coordinate of Extension point 2. */ - double epy2; - /*! Z Coordinate of Extension point 2. */ - double epz2; -}; - - - -/** - * Linear (rotated) Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimLinearData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimLinearData(double ddpx1, double ddpy1, double ddpz1, - double ddpx2, double ddpy2, double ddpz2, - double dAngle, double dOblique) { - - dpx1 = ddpx1; - dpy1 = ddpy1; - dpz1 = ddpz1; - - dpx2 = ddpx2; - dpy2 = ddpy2; - dpz2 = ddpz2; - - angle = dAngle; - oblique = dOblique; - } - - /*! X Coordinate of Extension point 1. */ - double dpx1; - /*! Y Coordinate of Extension point 1. */ - double dpy1; - /*! Z Coordinate of Extension point 1. */ - double dpz1; - - /*! X Coordinate of Extension point 2. */ - double dpx2; - /*! Y Coordinate of Extension point 2. */ - double dpy2; - /*! Z Coordinate of Extension point 2. */ - double dpz2; - - /*! Rotation angle (angle of dimension line) in degrees. */ - double angle; - /*! Oblique angle in degrees. */ - double oblique; -}; - - - -/** - * Radial Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimRadialData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimRadialData(double ddpx, double ddpy, double ddpz, double dleader) { - dpx = ddpx; - dpy = ddpy; - dpz = ddpz; - - leader = dleader; - } - - /*! X Coordinate of definition point. */ - double dpx; - /*! Y Coordinate of definition point. */ - double dpy; - /*! Z Coordinate of definition point. */ - double dpz; - - /*! Leader length */ - double leader; -}; - - - -/** - * Diametric Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimDiametricData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimDiametricData(double ddpx, double ddpy, double ddpz, double dleader) { - dpx = ddpx; - dpy = ddpy; - dpz = ddpz; - - leader = dleader; - } - - /*! X Coordinate of definition point (DXF 15). */ - double dpx; - /*! Y Coordinate of definition point (DXF 25). */ - double dpy; - /*! Z Coordinate of definition point (DXF 35). */ - double dpz; - - /*! Leader length */ - double leader; -}; - - - -/** - * Angular Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimAngularData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimAngularData(double ddpx1, double ddpy1, double ddpz1, - double ddpx2, double ddpy2, double ddpz2, - double ddpx3, double ddpy3, double ddpz3, - double ddpx4, double ddpy4, double ddpz4) { - - dpx1 = ddpx1; - dpy1 = ddpy1; - dpz1 = ddpz1; - - dpx2 = ddpx2; - dpy2 = ddpy2; - dpz2 = ddpz2; - - dpx3 = ddpx3; - dpy3 = ddpy3; - dpz3 = ddpz3; - - dpx4 = ddpx4; - dpy4 = ddpy4; - dpz4 = ddpz4; - } - - /*! X Coordinate of definition point 1. */ - double dpx1; - /*! Y Coordinate of definition point 1. */ - double dpy1; - /*! Z Coordinate of definition point 1. */ - double dpz1; - - /*! X Coordinate of definition point 2. */ - double dpx2; - /*! Y Coordinate of definition point 2. */ - double dpy2; - /*! Z Coordinate of definition point 2. */ - double dpz2; - - /*! X Coordinate of definition point 3. */ - double dpx3; - /*! Y Coordinate of definition point 3. */ - double dpy3; - /*! Z Coordinate of definition point 3. */ - double dpz3; - - /*! X Coordinate of definition point 4. */ - double dpx4; - /*! Y Coordinate of definition point 4. */ - double dpy4; - /*! Z Coordinate of definition point 4. */ - double dpz4; -}; - - -/** - * Angular Dimension Data (3 points version). - */ -struct DXFLIB_EXPORT DL_DimAngular3PData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimAngular3PData(double ddpx1, double ddpy1, double ddpz1, - double ddpx2, double ddpy2, double ddpz2, - double ddpx3, double ddpy3, double ddpz3) { - - dpx1 = ddpx1; - dpy1 = ddpy1; - dpz1 = ddpz1; - - dpx2 = ddpx2; - dpy2 = ddpy2; - dpz2 = ddpz2; - - dpx3 = ddpx3; - dpy3 = ddpy3; - dpz3 = ddpz3; - } - - /*! X Coordinate of definition point 1. */ - double dpx1; - /*! Y Coordinate of definition point 1. */ - double dpy1; - /*! Z Coordinate of definition point 1. */ - double dpz1; - - /*! X Coordinate of definition point 2. */ - double dpx2; - /*! Y Coordinate of definition point 2. */ - double dpy2; - /*! Z Coordinate of definition point 2. */ - double dpz2; - - /*! X Coordinate of definition point 3. */ - double dpx3; - /*! Y Coordinate of definition point 3. */ - double dpy3; - /*! Z Coordinate of definition point 3. */ - double dpz3; -}; - - - -/** - * Ordinate Dimension Data. - */ -struct DXFLIB_EXPORT DL_DimOrdinateData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_DimOrdinateData(double ddpx1, double ddpy1, double ddpz1, - double ddpx2, double ddpy2, double ddpz2, - bool dxtype) { - - dpx1 = ddpx1; - dpy1 = ddpy1; - dpz1 = ddpz1; - - dpx2 = ddpx2; - dpy2 = ddpy2; - dpz2 = ddpz2; - - xtype = dxtype; - } - - /*! X Coordinate of definition point 1. */ - double dpx1; - /*! Y Coordinate of definition point 1. */ - double dpy1; - /*! Z Coordinate of definition point 1. */ - double dpz1; - - /*! X Coordinate of definition point 2. */ - double dpx2; - /*! Y Coordinate of definition point 2. */ - double dpy2; - /*! Z Coordinate of definition point 2. */ - double dpz2; - - /*! True if the dimension indicates the X-value, false for Y-value */ - bool xtype; -}; - - - -/** - * Leader (arrow). - */ -struct DXFLIB_EXPORT DL_LeaderData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_LeaderData(int lArrowHeadFlag, - int lLeaderPathType, - int lLeaderCreationFlag, - int lHooklineDirectionFlag, - int lHooklineFlag, - double lTextAnnotationHeight, - double lTextAnnotationWidth, - int lNumber) { - - arrowHeadFlag = lArrowHeadFlag; - leaderPathType = lLeaderPathType; - leaderCreationFlag = lLeaderCreationFlag; - hooklineDirectionFlag = lHooklineDirectionFlag; - hooklineFlag = lHooklineFlag; - textAnnotationHeight = lTextAnnotationHeight; - textAnnotationWidth = lTextAnnotationWidth; - number = lNumber; - } - - /*! Arrow head flag (71). */ - int arrowHeadFlag; - /*! Leader path type (72). */ - int leaderPathType; - /*! Leader creation flag (73). */ - int leaderCreationFlag; - /*! Hookline direction flag (74). */ - int hooklineDirectionFlag; - /*! Hookline flag (75) */ - int hooklineFlag; - /*! Text annotation height (40). */ - double textAnnotationHeight; - /*! Text annotation width (41) */ - double textAnnotationWidth; - /*! Number of vertices in leader (76). */ - int number; -}; - - - -/** - * Leader Vertex Data. - */ -struct DXFLIB_EXPORT DL_LeaderVertexData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_LeaderVertexData(double px=0.0, double py=0.0, double pz=0.0) { - x = px; - y = py; - z = pz; - } - - /*! X Coordinate of the vertex. */ - double x; - /*! Y Coordinate of the vertex. */ - double y; - /*! Z Coordinate of the vertex. */ - double z; -}; - - - -/** - * Hatch data. - */ -struct DXFLIB_EXPORT DL_HatchData { - /** - * Default constructor. - */ - DL_HatchData() {} - - /** - * Constructor. - * Parameters: see member variables. - */ - DL_HatchData(int numLoops, - bool solid, - double scale, - double angle, - const std::string& pattern, - double originX = 0.0, - double originY = 0.0) : - numLoops(numLoops), - solid(solid), - scale(scale), - angle(angle), - pattern(pattern), - originX(originX), - originY(originY) { - - } - - /*! Number of boundary paths (loops). */ - int numLoops; - /*! Solid fill flag (true=solid, false=pattern). */ - bool solid; - /*! Pattern scale or spacing */ - double scale; - /*! Pattern angle in degrees */ - double angle; - /*! Pattern name. */ - std::string pattern; - /*! Pattern origin */ - double originX; - double originY; -}; - - - -/** - * Hatch boundary path (loop) data. - */ -struct DXFLIB_EXPORT DL_HatchLoopData { - /** - * Default constructor. - */ - DL_HatchLoopData() {} - /** - * Constructor. - * Parameters: see member variables. - */ - DL_HatchLoopData(int hNumEdges) { - numEdges = hNumEdges; - } - - /*! Number of edges in this loop. */ - int numEdges; -}; - - - -/** - * Hatch edge data. - */ -struct DXFLIB_EXPORT DL_HatchEdgeData { - /** - * Default constructor. - */ - DL_HatchEdgeData() : defined(false), x1(0.0), y1(0.0), x2(0.0), y2(0.0) { - } - - /** - * Constructor for a line edge. - * Parameters: see member variables. - */ - DL_HatchEdgeData(double x1, double y1, - double x2, double y2) : - defined(true), - type(1), - x1(x1), - y1(y1), - x2(x2), - y2(y2) { - } - - /** - * Constructor for an arc edge. - * Parameters: see member variables. - */ - DL_HatchEdgeData(double cx, double cy, - double radius, - double angle1, double angle2, - bool ccw) : - defined(true), - type(2), - cx(cx), - cy(cy), - radius(radius), - angle1(angle1), - angle2(angle2), - ccw(ccw) { - } - - /** - * Constructor for an ellipse arc edge. - * Parameters: see member variables. - */ - DL_HatchEdgeData(double cx, double cy, - double mx, double my, - double ratio, - double angle1, double angle2, - bool ccw) : - defined(true), - type(3), - cx(cx), - cy(cy), - angle1(angle1), - angle2(angle2), - ccw(ccw), - mx(mx), - my(my), - ratio(ratio) { - } - - /** - * Constructor for a spline edge. - * Parameters: see member variables. - */ - DL_HatchEdgeData(unsigned int degree, - bool rational, - bool periodic, - unsigned int nKnots, - unsigned int nControl, - unsigned int nFit, - const std::vector& knots, - const std::vector >& controlPoints, - const std::vector >& fitPoints, - const std::vector& weights, - double startTangentX, - double startTangentY, - double endTangentX, - double endTangentY) : - defined(true), - type(4), - degree(degree), - rational(rational), - periodic(periodic), - nKnots(nKnots), - nControl(nControl), - nFit(nFit), - controlPoints(controlPoints), - knots(knots), - weights(weights), - fitPoints(fitPoints), - startTangentX(startTangentX), - startTangentY(startTangentY), - endTangentX(endTangentX), - endTangentY(endTangentY) { - } - - /** - * Set to true if this edge is fully defined. - */ - bool defined; - - /** - * Edge type. 1=line, 2=arc, 3=elliptic arc, 4=spline. - */ - int type; - - // line edges: - - /*! Start point (X). */ - double x1; - /*! Start point (Y). */ - double y1; - /*! End point (X). */ - double x2; - /*! End point (Y). */ - double y2; - - /*! Center point of arc or ellipse arc (X). */ - double cx; - /*! Center point of arc or ellipse arc (Y). */ - double cy; - /*! Arc radius. */ - double radius; - /*! Start angle of arc or ellipse arc. */ - double angle1; - /*! End angle of arc or ellipse arc. */ - double angle2; - /*! Counterclockwise flag for arc or ellipse arc. */ - bool ccw; - - /*! Major axis end point (X). */ - double mx; - /*! Major axis end point (Y). */ - double my; - /*! Axis ratio */ - double ratio; - - - /*! Spline degree */ - unsigned int degree; - bool rational; - bool periodic; - /*! Number of knots. */ - unsigned int nKnots; - /*! Number of control points. */ - unsigned int nControl; - /*! Number of fit points. */ - unsigned int nFit; - - std::vector > controlPoints; - std::vector knots; - std::vector weights; - std::vector > fitPoints; - - double startTangentX; - double startTangentY; - - double endTangentX; - double endTangentY; - - /** Polyline boundary vertices (x y [bulge])*/ - std::vector > vertices; - //bool closed; -}; - - - -/** - * Image Data. - */ -struct DXFLIB_EXPORT DL_ImageData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_ImageData(const std::string& iref, - double iipx, double iipy, double iipz, - double iux, double iuy, double iuz, - double ivx, double ivy, double ivz, - int iwidth, int iheight, - int ibrightness, int icontrast, int ifade) { - ref = iref; - ipx = iipx; - ipy = iipy; - ipz = iipz; - ux = iux; - uy = iuy; - uz = iuz; - vx = ivx; - vy = ivy; - vz = ivz; - width = iwidth; - height = iheight; - brightness = ibrightness; - contrast = icontrast; - fade = ifade; - } - - /*! Reference to the image file - (unique, used to refer to the image def object). */ - std::string ref; - /*! X Coordinate of insertion point. */ - double ipx; - /*! Y Coordinate of insertion point. */ - double ipy; - /*! Z Coordinate of insertion point. */ - double ipz; - /*! X Coordinate of u vector along bottom of image. */ - double ux; - /*! Y Coordinate of u vector along bottom of image. */ - double uy; - /*! Z Coordinate of u vector along bottom of image. */ - double uz; - /*! X Coordinate of v vector along left side of image. */ - double vx; - /*! Y Coordinate of v vector along left side of image. */ - double vy; - /*! Z Coordinate of v vector along left side of image. */ - double vz; - /*! Width of image in pixel. */ - int width; - /*! Height of image in pixel. */ - int height; - /*! Brightness (0..100, default = 50). */ - int brightness; - /*! Contrast (0..100, default = 50). */ - int contrast; - /*! Fade (0..100, default = 0). */ - int fade; -}; - - - -/** - * Image Definition Data. - */ -struct DXFLIB_EXPORT DL_ImageDefData { - /** - * Constructor. - * Parameters: see member variables. - */ - DL_ImageDefData(const std::string& iref, - const std::string& ifile) { - ref = iref; - file = ifile; - } - - /*! Reference to the image file - (unique, used to refer to the image def object). */ - std::string ref; - - /*! Image file */ - std::string file; -}; - - - -/** - * Dictionary data. - */ -struct DXFLIB_EXPORT DL_DictionaryData { - DL_DictionaryData(const std::string& handle) : handle(handle) {} - std::string handle; -}; - - - -/** - * Dictionary entry data. - */ -struct DXFLIB_EXPORT DL_DictionaryEntryData { - DL_DictionaryEntryData(const std::string& name, const std::string& handle) : - name(name), handle(handle) {} - - std::string name; - std::string handle; -}; - -#endif - -// EOF diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_extrusion.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_extrusion.h deleted file mode 100644 index c36315b7e184..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_extrusion.h +++ /dev/null @@ -1,144 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_EXTRUSION_H -#define DL_EXTRUSION_H - -#include "dl_global.h" - -#include - - -/** - * Storing and passing around attributes. Attributes - * are the layer name, color, width and line type. - * - * @author Andrew Mustun - */ -class DXFLIB_EXPORT DL_Extrusion { - -public: - - /** - * Default constructor. - */ - DL_Extrusion() { - direction = new double[3]; - setDirection(0.0, 0.0, 1.0); - setElevation(0.0); - } - - - /** - * Destructor. - */ - ~DL_Extrusion() { - delete[] direction ; - } - - - /** - * Constructor for DXF extrusion. - * - * @param direction Vector of axis along which the entity shall be extruded - * this is also the Z axis of the Entity coordinate system - * @param elevation Distance of the entities XY plane from the origin of the - * world coordinate system - */ - DL_Extrusion(double dx, double dy, double dz, double elevation) { - direction = new double[3]; - setDirection(dx, dy, dz); - setElevation(elevation); - } - - - - /** - * Sets the direction vector. - */ - void setDirection(double dx, double dy, double dz) { - direction[0]=dx; - direction[1]=dy; - direction[2]=dz; - } - - - - /** - * @return direction vector. - */ - double* getDirection() const { - return direction; - } - - - - /** - * @return direction vector. - */ - void getDirection(double dir[]) const { - dir[0]=direction[0]; - dir[1]=direction[1]; - dir[2]=direction[2]; - } - - - - /** - * Sets the elevation. - */ - void setElevation(double elevation) { - this->elevation = elevation; - } - - - - /** - * @return Elevation. - */ - double getElevation() const { - return elevation; - } - - - - /** - * Copies extrusion (deep copies) from another extrusion object. - */ - DL_Extrusion operator = (const DL_Extrusion& extru) { - setDirection(extru.direction[0], extru.direction[1], extru.direction[2]); - setElevation(extru.elevation); - - return *this; - } - - - -private: - double *direction; - double elevation; -}; - -#endif - diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_global.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_global.h deleted file mode 100644 index 8e48c592a142..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_global.h +++ /dev/null @@ -1,38 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** Copyright (C) 2001 Robert J. Campbell Jr. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#if defined(DXFLIB_DLL) -# ifdef _WIN32 -# if defined(DXFLIB_LIBRARY) -# define DXFLIB_EXPORT __declspec(dllexport) -# else -# define DXFLIB_EXPORT __declspec(dllimport) -# endif -# else -# define DXFLIB_EXPORT -# endif -#else -# define DXFLIB_EXPORT -#endif diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_writer.h b/src/plugins/dxf2shp_converter/dxflib/src/dl_writer.h deleted file mode 100644 index 723c2899edc7..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_writer.h +++ /dev/null @@ -1,653 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** Copyright (C) 2001 Robert J. Campbell Jr. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#ifndef DL_WRITER_H -#define DL_WRITER_H - -#include "dl_global.h" - -#ifndef _WIN32 -#include -#endif - -#if defined(_MSC_VER)&& _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include -#include - -#include "dl_attributes.h" -#include "dl_codes.h" - - - -/** - * Defines interface for writing low level DXF constructs to - * a file. Implementation is defined in derived classes that write - * to binary or ASCII files. - * - * Implements functions that write higher level constructs in terms of - * the low level ones. - * - * @todo Add error checking for string/entry length. - */ -class DXFLIB_EXPORT DL_Writer { -public: - /** - * @param version DXF version. Defaults to DL_VERSION_2002. - */ - DL_Writer(DL_Codes::version version) : m_handle(0x30) { - this->version = version; - modelSpaceHandle = 0; - paperSpaceHandle = 0; - paperSpace0Handle = 0; - } - - virtual ~DL_Writer() {} - - /** Generic section for section 'name'. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  name
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void section(const char* name) const { - dxfString(0, "SECTION"); - dxfString(2, name); - } - - /** - * Section HEADER - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  HEADER
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionHeader() const { - section("HEADER"); - } - - /** - * Section TABLES - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  TABLES
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionTables() const { - section("TABLES"); - } - - /** - * Section BLOCKS - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  BLOCKS
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionBlocks() const { - section("BLOCKS"); - } - - /** - * Section ENTITIES - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  ENTITIES
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionEntities() const { - section("ENTITIES"); - } - - /** - * Section CLASSES - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  CLASSES
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionClasses() const { - section("CLASSES"); - } - - /** - * Section OBJECTS - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  SECTION
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  OBJECTS
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionObjects() const { - section("OBJECTS"); - } - - /** - * End of a section. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  ENDSEC
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionEnd() const { - dxfString(0, "ENDSEC"); - } - - /** - * Generic table for table 'name' with 'num' entries: - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  TABLE
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  name
                                                                                                                                                                                    -     *  70
                                                                                                                                                                                    -     *   num
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void table(const char* name, int num, int h=0) const { - dxfString(0, "TABLE"); - dxfString(2, name); - if (version>=DL_VERSION_2000) { - if (h==0) { - handle(); - } - else { - dxfHex(5, h); - } - dxfString(100, "AcDbSymbolTable"); - } - dxfInt(70, num); - } - - /** Table for layers. - * - * @param num Number of layers in total. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  TABLE
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  LAYER
                                                                                                                                                                                    -     *   70
                                                                                                                                                                                    -     *      num
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableLayers(int num) const { - table("LAYER", num, 2); - } - - /** Table for line types. - * - * @param num Number of line types in total. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  TABLE
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  LTYPE
                                                                                                                                                                                    -     *   70
                                                                                                                                                                                    -     *      num
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableLinetypes(int num) const { - //linetypeHandle = 5; - table("LTYPE", num, 5); - } - - /** Table for application id. - * - * @param num Number of registered applications in total. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  TABLE
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  APPID
                                                                                                                                                                                    -     *   70
                                                                                                                                                                                    -     *      num
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableAppid(int num) const { - table("APPID", num, 9); - } - - /** Table for text style. - * - * @param num Number of text styles. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  TABLE
                                                                                                                                                                                    -     *   2
                                                                                                                                                                                    -     *  STYLE
                                                                                                                                                                                    -     *   70
                                                                                                                                                                                    -     *      num
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableStyle(int num) const { - table("STYLE", num, 3); - } - - /** - * End of a table. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  ENDTAB
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableEnd() const { - dxfString(0, "ENDTAB"); - } - - /** - * End of the DXF file. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  EOF
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void dxfEOF() const { - dxfString(0, "EOF"); - } - - /** - * Comment. - * - *
                                                                                                                                                                                    -     *  999
                                                                                                                                                                                    -     *  text
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void comment(const char* text) const { - dxfString(999, text); - } - - /** - * Entity. - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  entTypeName
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - * - * @return Unique handle or 0. - */ - void entity(const char* entTypeName) const { - dxfString(0, entTypeName); - if (version>=DL_VERSION_2000) { - handle(); - } - } - - /** - * Attributes of an entity. - * - *
                                                                                                                                                                                    -     *   8
                                                                                                                                                                                    -     *  layer
                                                                                                                                                                                    -     *  62
                                                                                                                                                                                    -     *  color
                                                                                                                                                                                    -     *  39
                                                                                                                                                                                    -     *  width
                                                                                                                                                                                    -     *   6
                                                                                                                                                                                    -     *  linetype
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void entityAttributes(const DL_Attributes& attrib) const { - - // layer name: - dxfString(8, attrib.getLayer()); - - // R12 doesn't accept BYLAYER values. The value has to be missing - // in that case. - if (version>=DL_VERSION_2000 || attrib.getColor()!=256) { - dxfInt(62, attrib.getColor()); - } - if (version>=DL_VERSION_2000 && attrib.getColor24()!=-1) { - dxfInt(420, attrib.getColor24()); - } - if (version>=DL_VERSION_2000) { - dxfInt(370, attrib.getWidth()); - } - if (version>=DL_VERSION_2000) { - dxfReal(48, attrib.getLinetypeScale()); - } - std::string linetype = attrib.getLinetype(); - std::transform(linetype.begin(), linetype.end(), linetype.begin(), ::toupper); - if (version>=DL_VERSION_2000 || linetype=="BYLAYER") { - dxfString(6, attrib.getLinetype()); - } - } - - /** - * Subclass. - */ - void subClass(const char* sub) const { - dxfString(100, sub); - } - - /** - * Layer (must be in the TABLES section LAYER). - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  LAYER
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableLayerEntry(unsigned long int h=0) const { - dxfString(0, "LAYER"); - if (version>=DL_VERSION_2000) { - if (h==0) { - handle(); - } else { - dxfHex(5, h); - } - dxfString(100, "AcDbSymbolTableRecord"); - dxfString(100, "AcDbLayerTableRecord"); - } - } - - /** - * Line type (must be in the TABLES section LTYPE). - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  LTYPE
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableLinetypeEntry(unsigned long int h=0) const { - dxfString(0, "LTYPE"); - if (version>=DL_VERSION_2000) { - if (h==0) { - handle(); - } else { - dxfHex(5, h); - } - //dxfHex(330, 0x5); - dxfString(100, "AcDbSymbolTableRecord"); - dxfString(100, "AcDbLinetypeTableRecord"); - } - } - - /** - * Appid (must be in the TABLES section APPID). - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  APPID
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void tableAppidEntry(unsigned long int h=0) const { - dxfString(0, "APPID"); - if (version>=DL_VERSION_2000) { - if (h==0) { - handle(); - } else { - dxfHex(5, h); - } - //dxfHex(330, 0x9); - dxfString(100, "AcDbSymbolTableRecord"); - dxfString(100, "AcDbRegAppTableRecord"); - } - } - - /** - * Block (must be in the section BLOCKS). - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  BLOCK
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionBlockEntry(unsigned long int h=0) const { - dxfString(0, "BLOCK"); - if (version>=DL_VERSION_2000) { - if (h==0) { - handle(); - } else { - dxfHex(5, h); - } - //dxfHex(330, blockHandle); - dxfString(100, "AcDbEntity"); - if (h==0x1C) { - dxfInt(67, 1); - } - dxfString(8, "0"); // TODO: Layer for block - dxfString(100, "AcDbBlockBegin"); - } - } - - /** - * End of Block (must be in the section BLOCKS). - * - *
                                                                                                                                                                                    -     *   0
                                                                                                                                                                                    -     *  ENDBLK
                                                                                                                                                                                    -     * 
                                                                                                                                                                                    - */ - void sectionBlockEntryEnd(unsigned long int h=0) const { - dxfString(0, "ENDBLK"); - if (version>=DL_VERSION_2000) { - if (h==0) { - handle(); - } else { - dxfHex(5, h); - } - //dxfHex(330, blockHandle); - dxfString(100, "AcDbEntity"); - if (h==0x1D) { - dxfInt(67, 1); - } - dxfString(8, "0"); // TODO: Layer for block - dxfString(100, "AcDbBlockEnd"); - } - } - - void color(int col=256) const { - dxfInt(62, col); - } - void linetype(const char *lt) const { - dxfString(6, lt); - } - void linetypeScale(double scale) const { - dxfReal(48, scale); - } - void lineWeight(int lw) const { - dxfInt(370, lw); - } - - void coord(int gc, double x, double y, double z=0) const { - dxfReal(gc, x); - dxfReal(gc+10, y); - dxfReal(gc+20, z); - } - - void coordTriplet(int gc, const double* value) const { - if (value) { - dxfReal(gc, *value++); - dxfReal(gc+10, *value++); - dxfReal(gc+20, *value++); - } - } - - void resetHandle() const { - m_handle = 1; - } - - /** - * Writes a unique handle and returns it. - */ - unsigned long handle(int gc=5) const { - // handle has to be hex - dxfHex(gc, m_handle); - return m_handle++; - } - - /** - * @return Next handle that will be written. - */ - unsigned long getNextHandle() const { - return m_handle; - } - - /** - * Increases handle, so that the handle returned remains available. - */ - unsigned long incHandle() const { - return m_handle++; - } - - /** - * Sets the handle of the model space. Entities refer to - * this handle. - */ - void setModelSpaceHandle(unsigned long h) { - modelSpaceHandle = h; - } - - unsigned long getModelSpaceHandle() { - return modelSpaceHandle; - } - - /** - * Sets the handle of the paper space. Some special blocks refer to - * this handle. - */ - void setPaperSpaceHandle(unsigned long h) { - paperSpaceHandle = h; - } - - unsigned long getPaperSpaceHandle() { - return paperSpaceHandle; - } - - /** - * Sets the handle of the paper space 0. Some special blocks refer to - * this handle. - */ - void setPaperSpace0Handle(unsigned long h) { - paperSpace0Handle = h; - } - - unsigned long getPaperSpace0Handle() { - return paperSpace0Handle; - } - - /** - * Must be overwritten by the implementing class to write a - * real value to the file. - * - * @param gc Group code. - * @param value The real value. - */ - virtual void dxfReal(int gc, double value) const = 0; - - /** - * Must be overwritten by the implementing class to write an - * int value to the file. - * - * @param gc Group code. - * @param value The int value. - */ - virtual void dxfInt(int gc, int value) const = 0; - - /** - * Can be overwritten by the implementing class to write a - * bool value to the file. - * - * @param gc Group code. - * @param value The bool value. - */ - virtual void dxfBool(int gc, bool value) const { - dxfInt(gc, static_cast(value)); - } - - /** - * Must be overwritten by the implementing class to write an - * int value (hex) to the file. - * - * @param gc Group code. - * @param value The int value. - */ - virtual void dxfHex(int gc, int value) const = 0; - - /** - * Must be overwritten by the implementing class to write a - * string to the file. - * - * @param gc Group code. - * @param value The string. - */ - virtual void dxfString(int gc, const char* value) const = 0; - - /** - * Must be overwritten by the implementing class to write a - * string to the file. - * - * @param gc Group code. - * @param value The string. - */ - virtual void dxfString(int gc, const std::string& value) const = 0; - -protected: - mutable unsigned long m_handle; - mutable unsigned long modelSpaceHandle; - mutable unsigned long paperSpaceHandle; - mutable unsigned long paperSpace0Handle; - - /** - * DXF version to be created. - */ - DL_Codes::version version; -private: -}; - -#endif diff --git a/src/plugins/dxf2shp_converter/dxflib/src/dl_writer_ascii.cpp b/src/plugins/dxf2shp_converter/dxflib/src/dl_writer_ascii.cpp deleted file mode 100644 index f62402a2ebfc..000000000000 --- a/src/plugins/dxf2shp_converter/dxflib/src/dl_writer_ascii.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/**************************************************************************** -** Copyright (C) 2001-2013 RibbonSoft, GmbH. All rights reserved. -** Copyright (C) 2001 Robert J. Campbell Jr. -** -** This file is part of the dxflib project. -** -** This file is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** Licensees holding valid dxflib Professional Edition licenses may use -** this file in accordance with the dxflib Commercial License -** Agreement provided with the Software. -** -** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE -** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. -** -** See http://www.ribbonsoft.com for further details. -** -** Contact info@ribbonsoft.com if any conditions of this licensing are -** not clear to you. -** -**********************************************************************/ - -#if defined(_MSC_VER) && _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include -#include - -#include "dl_writer_ascii.h" - - -/** - * Closes the output file. - */ -void DL_WriterA::close() const { - m_ofile.close(); -} - - -/** - * @retval true Opening file has failed. - * @retval false Otherwise. - */ -bool DL_WriterA::openFailed() const { - return m_ofile.fail(); -} - - - -/** - * Writes a real (double) variable to the DXF file. - * - * @param gc Group code. - * @param value Double value - */ -void DL_WriterA::dxfReal(int gc, double value) const { - char str[256]; - sprintf(str, "%.16lf", value); - - // fix for german locale: - strReplace(str, ',', '.'); - - // Cut away those zeros at the end: - bool dot = false; - int end = -1; - for (unsigned int i=0; i0 && end(strlen(str))) { - str[end] = '\0'; - } - - dxfString(gc, str); - m_ofile.flush(); -} - - - -/** - * Writes an int variable to the DXF file. - * - * @param gc Group code. - * @param value Int value - */ -void DL_WriterA::dxfInt(int gc, int value) const { - m_ofile << (gc<10 ? " " : (gc<100 ? " " : "")) << gc << "\n" << value << "\n"; -} - - - -/** - * Writes a hex int variable to the DXF file. - * - * @param gc Group code. - * @param value Int value - */ -void DL_WriterA::dxfHex(int gc, int value) const { - char str[12]; - sprintf(str, "%0X", value); - dxfString(gc, str); -} - - - -/** - * Writes a string variable to the DXF file. - * - * @param gc Group code. - * @param value String - */ -void DL_WriterA::dxfString(int gc, const char* value) const { - m_ofile << (gc<10 ? " " : (gc<100 ? " " : "")) << gc << "\n" - << value << "\n"; -} - - - -void DL_WriterA::dxfString(int gc, const std::string& value) const { - m_ofile << (gc<10 ? " " : (gc<100 ? " " : "")) << gc << "\n" - << value << "\n"; -} - - -/** - * Replaces every occurence of src with dest in the null terminated str. - */ -void DL_WriterA::strReplace(char* str, char src, char dest) { - size_t i; - for (i=0; i 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "dl_writer.h" -#include -#include - -/** - * Implements functions defined in DL_Writer for writing low - * level DXF constructs to an ASCII format DXF file. - * - * @para fname File name of the file to be created. - * @para version DXF version. Defaults to DL_VERSION_2002. - * - * @todo What if \c fname is NULL? Or \c fname can't be opened for - * another reason? - */ -class DXFLIB_EXPORT DL_WriterA : public DL_Writer { -public: - DL_WriterA(const char* fname, DL_Codes::version version=DL_VERSION_2000) - : DL_Writer(version), m_ofile(fname) {} - virtual ~DL_WriterA() {} - - bool openFailed() const; - void close() const; - void dxfReal(int gc, double value) const; - void dxfInt(int gc, int value) const; - void dxfHex(int gc, int value) const; - void dxfString(int gc, const char* value) const; - void dxfString(int gc, const std::string& value) const; - - static void strReplace(char* str, char src, char dest); - -private: - /** - * DXF file to be created. - */ - mutable std::ofstream m_ofile; - -}; - -#endif - diff --git a/src/plugins/dxf2shp_converter/shapelib-1.2.10/LICENSE.LGPL b/src/plugins/dxf2shp_converter/shapelib-1.2.10/LICENSE.LGPL deleted file mode 100644 index 0b643ac83c8b..000000000000 --- a/src/plugins/dxf2shp_converter/shapelib-1.2.10/LICENSE.LGPL +++ /dev/null @@ -1,483 +0,0 @@ - - GNU LIBRARY GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1991 Free Software Foundation, Inc. - 675 Mass Ave, Cambridge, MA 02139, USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the library GPL. It is - numbered 2 because it goes with version 2 of the ordinary GPL.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Library General Public License, applies to some -specially designated Free Software Foundation software, and to any -other libraries whose authors decide to use it. You can use it for -your libraries, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if -you distribute copies of the library, or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link a program with the library, you must provide -complete object files to the recipients so that they can relink them -with the library, after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - Our method of protecting your rights has two steps: (1) copyright -the library, and (2) offer you this license which gives you legal -permission to copy, distribute and/or modify the library. - - Also, for each distributor's protection, we want to make certain -that everyone understands that there is no warranty for this free -library. If the library is modified by someone else and passed on, we -want its recipients to know that what they have is not the original -version, so that any problems introduced by others will not reflect on -the original authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that companies distributing free -software will individually obtain patent licenses, thus in effect -transforming the program into proprietary software. To prevent this, -we have made it clear that any patent must be licensed for everyone's -free use or not licensed at all. - - Most GNU software, including some libraries, is covered by the ordinary -GNU General Public License, which was designed for utility programs. This -license, the GNU Library General Public License, applies to certain -designated libraries. This license is quite different from the ordinary -one; be sure to read it in full, and don't assume that anything in it is -the same as in the ordinary license. - - The reason we have a separate public license for some libraries is that -they blur the distinction we usually make between modifying or adding to a -program and simply using it. Linking a program with a library, without -changing the library, is in some sense simply using the library, and is -analogous to running a utility program or application program. However, in -a textual and legal sense, the linked executable is a combined work, a -derivative of the original library, and the ordinary General Public License -treats it as such. - - Because of this blurred distinction, using the ordinary General -Public License for libraries did not effectively promote software -sharing, because most developers did not use the libraries. We -concluded that weaker conditions might promote sharing better. - - However, unrestricted linking of non-free programs would deprive the -users of those programs of all benefit from the free status of the -libraries themselves. This Library General Public License is intended to -permit developers of non-free programs to use free libraries, while -preserving your freedom as a user of such programs to change the free -libraries that are incorporated in them. (We have not seen how to achieve -this as regards changes in header files, but we have achieved it as regards -changes in the actual functions of the Library.) The hope is that this -will lead to faster development of free libraries. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, while the latter only -works together with the library. - - Note that it is possible for a library to be covered by the ordinary -General Public License rather than by this special one. - - GNU LIBRARY GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library which -contains a notice placed by the copyright holder or other authorized -party saying it may be distributed under the terms of this Library -General Public License (also called "this License"). Each licensee is -addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also compile or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - c) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - d) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the source code distributed need not include anything that is normally -distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Library General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - Appendix: How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public - License along with this library; if not, write to the Free - Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - diff --git a/src/plugins/dxf2shp_converter/shapelib-1.2.10/dbfopen.c b/src/plugins/dxf2shp_converter/shapelib-1.2.10/dbfopen.c deleted file mode 100644 index c63e751f98dd..000000000000 --- a/src/plugins/dxf2shp_converter/shapelib-1.2.10/dbfopen.c +++ /dev/null @@ -1,1502 +0,0 @@ -/****************************************************************************** - * $Id: dbfopen.c,v 1.48 2003/03/10 14:51:27 warmerda Exp $ - * - * Project: Shapelib - * Purpose: Implementation of .dbf access API documented in dbf_api.html. - * Author: Frank Warmerdam, warmerdam@pobox.com - * - ****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see LICENSE.LGPL). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ****************************************************************************** - * - * $Log: dbfopen.c,v $ - * Revision 1.48 2003/03/10 14:51:27 warmerda - * DBFWrite* calls now return FALSE if they have to truncate - * - * Revision 1.47 2002/11/20 03:32:22 warmerda - * Ensure field name in DBFGetFieldIndex() is properly terminated. - * - * Revision 1.46 2002/10/09 13:10:21 warmerda - * Added check that width is positive. - * - * Revision 1.45 2002/09/29 00:00:08 warmerda - * added FTLogical and logical attribute read/write calls - * - * Revision 1.44 2002/05/07 13:46:11 warmerda - * Added DBFWriteAttributeDirectly(). - * - * Revision 1.43 2002/02/13 19:39:21 warmerda - * Fix casting issues in DBFCloneEmpty(). - * - * Revision 1.42 2002/01/15 14:36:07 warmerda - * updated email address - * - * Revision 1.41 2002/01/15 14:31:49 warmerda - * compute rather than copying nHeaderLength in DBFCloneEmpty() - * - * Revision 1.40 2002/01/09 04:32:35 warmerda - * fixed to read correct amount of header - * - * Revision 1.39 2001/12/11 22:41:03 warmerda - * improve io related error checking when reading header - * - * Revision 1.38 2001/11/28 16:07:31 warmerda - * Cleanup to avoid compiler warnings as suggested by Richard Hash. - * - * Revision 1.37 2001/07/04 05:18:09 warmerda - * do last fix properly - * - * Revision 1.36 2001/07/04 05:16:09 warmerda - * fixed fieldname comparison in DBFGetFieldIndex - * - * Revision 1.35 2001/06/22 02:10:06 warmerda - * fixed NULL shape support with help from Jim Matthews - * - * Revision 1.33 2001/05/31 19:20:13 warmerda - * added DBFGetFieldIndex() - * - * Revision 1.32 2001/05/31 18:15:40 warmerda - * Added support for NULL fields in DBF files - * - * Revision 1.31 2001/05/23 13:36:52 warmerda - * added use of SHPAPI_CALL - * - * Revision 1.30 2000/12/05 14:43:38 warmerda - * DBReadAttribute() white space trimming bug fix - * - * Revision 1.29 2000/10/05 14:36:44 warmerda - * fix bug with writing very wide numeric fields - * - * Revision 1.28 2000/09/25 14:18:07 warmerda - * Added some casts of strlen() return result to fix warnings on some - * systems, as submitted by Daniel. - * - * Revision 1.27 2000/09/25 14:15:51 warmerda - * added DBFGetNativeFieldType() - * - * Revision 1.26 2000/07/07 13:39:45 warmerda - * removed unused variables, and added system include files - * - * Revision 1.25 2000/05/29 18:19:13 warmerda - * avoid use of uchar, and adding casting fix - * - * Revision 1.24 2000/05/23 13:38:27 warmerda - * Added error checks on return results of fread() and fseek(). - * - * Revision 1.23 2000/05/23 13:25:49 warmerda - * Avoid crashing if field or record are out of range in dbfread*attribute(). - * - * Revision 1.22 1999/12/15 13:47:24 warmerda - * Added stdlib.h to ensure that atof() is prototyped. - * - * Revision 1.21 1999/12/13 17:25:46 warmerda - * Added support for upper case .DBF extension. - * - * Revision 1.20 1999/11/30 16:32:11 warmerda - * Use atof() instead of sscanf(). - * - * Revision 1.19 1999/11/05 14:12:04 warmerda - * updated license terms - * - * Revision 1.18 1999/07/27 00:53:28 warmerda - * ensure that whole old field value clear on write of string - * - * Revision 1.1 1999/07/05 18:58:07 warmerda - * New - * - * Revision 1.17 1999/06/11 19:14:12 warmerda - * Fixed some memory leaks. - * - * Revision 1.16 1999/06/11 19:04:11 warmerda - * Remoted some unused variables. - * - * Revision 1.15 1999/05/11 03:19:28 warmerda - * added new Tuple api, and improved extension handling - add from candrsn - * - * Revision 1.14 1999/05/04 15:01:48 warmerda - * Added 'F' support. - * - * Revision 1.13 1999/03/23 17:38:59 warmerda - * DBFAddField() now actually does return the new field number, or -1 if - * it fails. - * - * Revision 1.12 1999/03/06 02:54:46 warmerda - * Added logic to convert shapefile name to dbf filename in DBFOpen() - * for convenience. - * - * Revision 1.11 1998/12/31 15:30:34 warmerda - * Improved the interchangability of numeric and string attributes. Add - * white space trimming option for attributes. - * - * Revision 1.10 1998/12/03 16:36:44 warmerda - * Use r+b instead of rb+ for binary access. - * - * Revision 1.9 1998/12/03 15:34:23 warmerda - * Updated copyright message. - * - * Revision 1.8 1997/12/04 15:40:15 warmerda - * Added newline character after field definitions. - * - * Revision 1.7 1997/03/06 14:02:10 warmerda - * Ensure bUpdated is initialized. - * - * Revision 1.6 1996/02/12 04:54:41 warmerda - * Ensure that DBFWriteAttribute() returns TRUE if it succeeds. - * - * Revision 1.5 1995/10/21 03:15:12 warmerda - * Changed to use binary file access, and ensure that the - * field name field is zero filled, and limited to 10 chars. - * - * Revision 1.4 1995/08/24 18:10:42 warmerda - * Added use of SfRealloc() to avoid pre-ANSI realloc() functions such - * as on the Sun. - * - * Revision 1.3 1995/08/04 03:15:16 warmerda - * Fixed up header. - * - * Revision 1.2 1995/08/04 03:14:43 warmerda - * Added header. - */ - -static char rcsid[] = - "$Id: dbfopen.c,v 1.48 2003/03/10 14:51:27 warmerda Exp $"; - -#include "shapefil.h" - -#include -#include -#include -#include - -#ifndef FALSE -# define FALSE 0 -# define TRUE 1 -#endif - -static int nStringFieldLen = 0; -static char * pszStringField = NULL; - -/************************************************************************/ -/* SfRealloc() */ -/* */ -/* A realloc cover function that will access a NULL pointer as */ -/* a valid input. */ -/************************************************************************/ - -static void * SfRealloc( void * pMem, int nNewSize ) - -{ - if ( pMem == NULL ) - return(( void * ) malloc( nNewSize ) ); - else - return(( void * ) realloc( pMem, nNewSize ) ); -} - -/************************************************************************/ -/* DBFWriteHeader() */ -/* */ -/* This is called to write out the file header, and field */ -/* descriptions before writing any actual data records. This */ -/* also computes all the DBFDataSet field offset/size/decimals */ -/* and so forth values. */ -/************************************************************************/ - -static void DBFWriteHeader( DBFHandle psDBF ) - -{ - unsigned char abyHeader[XBASE_FLDHDR_SZ]; - int i; - - if ( !psDBF->bNoHeader ) - return; - - psDBF->bNoHeader = FALSE; - - /* -------------------------------------------------------------------- */ - /* Initialize the file header information. */ - /* -------------------------------------------------------------------- */ - for ( i = 0; i < XBASE_FLDHDR_SZ; i++ ) - abyHeader[i] = 0; - - abyHeader[0] = 0x03; /* memo field? - just copying */ - - /* date updated on close, record count preset at zero */ - - abyHeader[8] = psDBF->nHeaderLength % 256; - abyHeader[9] = psDBF->nHeaderLength / 256; - - abyHeader[10] = psDBF->nRecordLength % 256; - abyHeader[11] = psDBF->nRecordLength / 256; - - /* -------------------------------------------------------------------- */ - /* Write the initial 32 byte file header, and all the field */ - /* descriptions. */ - /* -------------------------------------------------------------------- */ - fseek( psDBF->fp, 0, 0 ); - fwrite( abyHeader, XBASE_FLDHDR_SZ, 1, psDBF->fp ); - fwrite( psDBF->pszHeader, XBASE_FLDHDR_SZ, psDBF->nFields, psDBF->fp ); - - /* -------------------------------------------------------------------- */ - /* Write out the newline character if there is room for it. */ - /* -------------------------------------------------------------------- */ - if ( psDBF->nHeaderLength > 32*psDBF->nFields + 32 ) - { - char cNewline; - - cNewline = 0x0d; - fwrite( &cNewline, 1, 1, psDBF->fp ); - } -} - -/************************************************************************/ -/* DBFFlushRecord() */ -/* */ -/* Write out the current record if there is one. */ -/************************************************************************/ - -static void DBFFlushRecord( DBFHandle psDBF ) - -{ - int nRecordOffset; - - if ( psDBF->bCurrentRecordModified && psDBF->nCurrentRecord > -1 ) - { - psDBF->bCurrentRecordModified = FALSE; - - nRecordOffset = psDBF->nRecordLength * psDBF->nCurrentRecord - + psDBF->nHeaderLength; - - fseek( psDBF->fp, nRecordOffset, 0 ); - fwrite( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp ); - } -} - -/************************************************************************/ -/* DBFOpen() */ -/* */ -/* Open a .dbf file. */ -/************************************************************************/ - -DBFHandle SHPAPI_CALL -DBFOpen( const char * pszFilename, const char * pszAccess ) - -{ - DBFHandle psDBF; - unsigned char *pabyBuf; - int nFields, nHeadLen, nRecLen, iField, i; - char *pszBasename, *pszFullname; - - /* -------------------------------------------------------------------- */ - /* We only allow the access strings "rb" and "r+". */ - /* -------------------------------------------------------------------- */ - if ( strcmp( pszAccess, "r" ) != 0 && strcmp( pszAccess, "r+" ) != 0 - && strcmp( pszAccess, "rb" ) != 0 && strcmp( pszAccess, "rb+" ) != 0 - && strcmp( pszAccess, "r+b" ) != 0 ) - return( NULL ); - - if ( strcmp( pszAccess, "r" ) == 0 ) - pszAccess = "rb"; - - if ( strcmp( pszAccess, "r+" ) == 0 ) - pszAccess = "rb+"; - - /* -------------------------------------------------------------------- */ - /* Compute the base (layer) name. If there is any extension */ - /* on the passed in filename we will strip it off. */ - /* -------------------------------------------------------------------- */ - pszBasename = ( char * ) malloc( strlen( pszFilename ) + 5 ); - strcpy( pszBasename, pszFilename ); - for ( i = strlen( pszBasename ) - 1; - i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/' - && pszBasename[i] != '\\'; - i-- ) {} - - if ( pszBasename[i] == '.' ) - pszBasename[i] = '\0'; - - pszFullname = ( char * ) malloc( strlen( pszBasename ) + 5 ); - sprintf( pszFullname, "%s.dbf", pszBasename ); - - psDBF = ( DBFHandle ) calloc( 1, sizeof( DBFInfo ) ); - psDBF->fp = fopen( pszFullname, pszAccess ); - - if ( psDBF->fp == NULL ) - { - sprintf( pszFullname, "%s.DBF", pszBasename ); - psDBF->fp = fopen( pszFullname, pszAccess ); - } - - free( pszBasename ); - free( pszFullname ); - - if ( psDBF->fp == NULL ) - { - free( psDBF ); - return( NULL ); - } - - psDBF->bNoHeader = FALSE; - psDBF->nCurrentRecord = -1; - psDBF->bCurrentRecordModified = FALSE; - - /* -------------------------------------------------------------------- */ - /* Read Table Header info */ - /* -------------------------------------------------------------------- */ - pabyBuf = ( unsigned char * ) malloc( 500 ); - if ( fread( pabyBuf, 32, 1, psDBF->fp ) != 1 ) - { - fclose( psDBF->fp ); - free( pabyBuf ); - free( psDBF ); - return NULL; - } - - psDBF->nRecords = - pabyBuf[4] + pabyBuf[5] * 256 + pabyBuf[6] * 256 * 256 + pabyBuf[7] * 256 * 256 * 256; - - psDBF->nHeaderLength = nHeadLen = pabyBuf[8] + pabyBuf[9] * 256; - psDBF->nRecordLength = nRecLen = pabyBuf[10] + pabyBuf[11] * 256; - - psDBF->nFields = nFields = ( nHeadLen - 32 ) / 32; - - psDBF->pszCurrentRecord = ( char * ) malloc( nRecLen ); - - /* -------------------------------------------------------------------- */ - /* Read in Field Definitions */ - /* -------------------------------------------------------------------- */ - - pabyBuf = psDBF->pszHeader = ( unsigned char * ) SfRealloc( pabyBuf, nHeadLen ); - - fseek( psDBF->fp, 32, 0 ); - if ( fread( pabyBuf, nHeadLen - 32, 1, psDBF->fp ) != 1 ) - { - fclose( psDBF->fp ); - free( pabyBuf ); - free( psDBF ); - return NULL; - } - - psDBF->panFieldOffset = ( int * ) malloc( sizeof( int ) * nFields ); - psDBF->panFieldSize = ( int * ) malloc( sizeof( int ) * nFields ); - psDBF->panFieldDecimals = ( int * ) malloc( sizeof( int ) * nFields ); - psDBF->pachFieldType = ( char * ) malloc( sizeof( char ) * nFields ); - - for ( iField = 0; iField < nFields; iField++ ) - { - unsigned char *pabyFInfo; - - pabyFInfo = pabyBuf + iField * 32; - - if ( pabyFInfo[11] == 'N' || pabyFInfo[11] == 'F' ) - { - psDBF->panFieldSize[iField] = pabyFInfo[16]; - psDBF->panFieldDecimals[iField] = pabyFInfo[17]; - } - else - { - psDBF->panFieldSize[iField] = pabyFInfo[16] + pabyFInfo[17] * 256; - psDBF->panFieldDecimals[iField] = 0; - } - - psDBF->pachFieldType[iField] = ( char ) pabyFInfo[11]; - if ( iField == 0 ) - psDBF->panFieldOffset[iField] = 1; - else - psDBF->panFieldOffset[iField] = - psDBF->panFieldOffset[iField-1] + psDBF->panFieldSize[iField-1]; - } - - return( psDBF ); -} - -/************************************************************************/ -/* DBFClose() */ -/************************************************************************/ - -void SHPAPI_CALL -DBFClose( DBFHandle psDBF ) -{ - /* -------------------------------------------------------------------- */ - /* Write out header if not already written. */ - /* -------------------------------------------------------------------- */ - if ( psDBF->bNoHeader ) - DBFWriteHeader( psDBF ); - - DBFFlushRecord( psDBF ); - - /* -------------------------------------------------------------------- */ - /* Update last access date, and number of records if we have */ - /* write access. */ - /* -------------------------------------------------------------------- */ - if ( psDBF->bUpdated ) - { - unsigned char abyFileHeader[32]; - - fseek( psDBF->fp, 0, 0 ); - fread( abyFileHeader, 32, 1, psDBF->fp ); - - abyFileHeader[1] = 95; /* YY */ - abyFileHeader[2] = 7; /* MM */ - abyFileHeader[3] = 26; /* DD */ - - abyFileHeader[4] = psDBF->nRecords % 256; - abyFileHeader[5] = ( psDBF->nRecords / 256 ) % 256; - abyFileHeader[6] = ( psDBF->nRecords / ( 256 * 256 ) ) % 256; - abyFileHeader[7] = ( psDBF->nRecords / ( 256 * 256 * 256 ) ) % 256; - - fseek( psDBF->fp, 0, 0 ); - fwrite( abyFileHeader, 32, 1, psDBF->fp ); - } - - /* -------------------------------------------------------------------- */ - /* Close, and free resources. */ - /* -------------------------------------------------------------------- */ - fclose( psDBF->fp ); - - if ( psDBF->panFieldOffset != NULL ) - { - free( psDBF->panFieldOffset ); - free( psDBF->panFieldSize ); - free( psDBF->panFieldDecimals ); - free( psDBF->pachFieldType ); - } - - free( psDBF->pszHeader ); - free( psDBF->pszCurrentRecord ); - - free( psDBF ); - - if ( pszStringField != NULL ) - { - free( pszStringField ); - pszStringField = NULL; - nStringFieldLen = 0; - } -} - -/************************************************************************/ -/* DBFCreate() */ -/* */ -/* Create a new .dbf file. */ -/************************************************************************/ - -DBFHandle SHPAPI_CALL -DBFCreate( const char *pszFilename ) - -{ - DBFHandle psDBF; - FILE *fp; - char *pszFullname, *pszBasename; - int i; - - /* -------------------------------------------------------------------- */ - /* Compute the base (layer) name. If there is any extension */ - /* on the passed in filename we will strip it off. */ - /* -------------------------------------------------------------------- */ - pszBasename = ( char * ) malloc( strlen( pszFilename ) + 5 ); - strcpy( pszBasename, pszFilename ); - for ( i = strlen( pszBasename ) - 1; - i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/' - && pszBasename[i] != '\\'; - i-- ) {} - - if ( pszBasename[i] == '.' ) - pszBasename[i] = '\0'; - - pszFullname = ( char * ) malloc( strlen( pszBasename ) + 5 ); - sprintf( pszFullname, "%s.dbf", pszBasename ); - free( pszBasename ); - - /* -------------------------------------------------------------------- */ - /* Create the file. */ - /* -------------------------------------------------------------------- */ - fp = fopen( pszFullname, "wb" ); - if ( fp == NULL ) - { - free( pszFullname ); - return( NULL ); - } - - fputc( 0, fp ); - fclose( fp ); - - fp = fopen( pszFullname, "rb+" ); - if ( fp == NULL ) - { - free( pszFullname ); - return( NULL ); - } - - free( pszFullname ); - - /* -------------------------------------------------------------------- */ - /* Create the info structure. */ - /* -------------------------------------------------------------------- */ - psDBF = ( DBFHandle ) malloc( sizeof( DBFInfo ) ); - - psDBF->fp = fp; - psDBF->nRecords = 0; - psDBF->nFields = 0; - psDBF->nRecordLength = 1; - psDBF->nHeaderLength = 33; - - psDBF->panFieldOffset = NULL; - psDBF->panFieldSize = NULL; - psDBF->panFieldDecimals = NULL; - psDBF->pachFieldType = NULL; - psDBF->pszHeader = NULL; - - psDBF->nCurrentRecord = -1; - psDBF->bCurrentRecordModified = FALSE; - psDBF->pszCurrentRecord = NULL; - - psDBF->bNoHeader = TRUE; - - return( psDBF ); -} - -/************************************************************************/ -/* DBFAddField() */ -/* */ -/* Add a field to a newly created .dbf file before any records */ -/* are written. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFAddField( DBFHandle psDBF, const char * pszFieldName, - DBFFieldType eType, int nWidth, int nDecimals ) - -{ - char *pszFInfo; - int i; - - /* -------------------------------------------------------------------- */ - /* Do some checking to ensure we can add records to this file. */ - /* -------------------------------------------------------------------- */ - if ( psDBF->nRecords > 0 ) - return( -1 ); - - if ( !psDBF->bNoHeader ) - return( -1 ); - - if ( eType != FTDouble && nDecimals != 0 ) - return( -1 ); - - if ( nWidth < 1 ) - return -1; - - /* -------------------------------------------------------------------- */ - /* SfRealloc all the arrays larger to hold the additional field */ - /* information. */ - /* -------------------------------------------------------------------- */ - psDBF->nFields++; - - psDBF->panFieldOffset = ( int * ) - SfRealloc( psDBF->panFieldOffset, sizeof( int ) * psDBF->nFields ); - - psDBF->panFieldSize = ( int * ) - SfRealloc( psDBF->panFieldSize, sizeof( int ) * psDBF->nFields ); - - psDBF->panFieldDecimals = ( int * ) - SfRealloc( psDBF->panFieldDecimals, sizeof( int ) * psDBF->nFields ); - - psDBF->pachFieldType = ( char * ) - SfRealloc( psDBF->pachFieldType, sizeof( char ) * psDBF->nFields ); - - /* -------------------------------------------------------------------- */ - /* Assign the new field information fields. */ - /* -------------------------------------------------------------------- */ - psDBF->panFieldOffset[psDBF->nFields-1] = psDBF->nRecordLength; - psDBF->nRecordLength += nWidth; - psDBF->panFieldSize[psDBF->nFields-1] = nWidth; - psDBF->panFieldDecimals[psDBF->nFields-1] = nDecimals; - - if ( eType == FTLogical ) - psDBF->pachFieldType[psDBF->nFields-1] = 'L'; - else if ( eType == FTString ) - psDBF->pachFieldType[psDBF->nFields-1] = 'C'; - else - psDBF->pachFieldType[psDBF->nFields-1] = 'N'; - - /* -------------------------------------------------------------------- */ - /* Extend the required header information. */ - /* -------------------------------------------------------------------- */ - psDBF->nHeaderLength += 32; - psDBF->bUpdated = FALSE; - - psDBF->pszHeader = ( char * ) SfRealloc( psDBF->pszHeader, psDBF->nFields * 32 ); - - pszFInfo = psDBF->pszHeader + 32 * ( psDBF->nFields - 1 ); - - for ( i = 0; i < 32; i++ ) - pszFInfo[i] = '\0'; - - if (( int ) strlen( pszFieldName ) < 10 ) - strncpy( pszFInfo, pszFieldName, strlen( pszFieldName ) ); - else - strncpy( pszFInfo, pszFieldName, 10 ); - - pszFInfo[11] = psDBF->pachFieldType[psDBF->nFields-1]; - - if ( eType == FTString ) - { - pszFInfo[16] = nWidth % 256; - pszFInfo[17] = nWidth / 256; - } - else - { - pszFInfo[16] = nWidth; - pszFInfo[17] = nDecimals; - } - - /* -------------------------------------------------------------------- */ - /* Make the current record buffer appropriately larger. */ - /* -------------------------------------------------------------------- */ - psDBF->pszCurrentRecord = ( char * ) SfRealloc( psDBF->pszCurrentRecord, - psDBF->nRecordLength ); - - return( psDBF->nFields - 1 ); -} - -/************************************************************************/ -/* DBFReadAttribute() */ -/* */ -/* Read one of the attribute fields of a record. */ -/************************************************************************/ - -static void *DBFReadAttribute( DBFHandle psDBF, int hEntity, int iField, - char chReqType ) - -{ - int nRecordOffset; - unsigned char *pabyRec; - void *pReturnField = NULL; - - static double dDoubleField; - - /* -------------------------------------------------------------------- */ - /* Verify selection. */ - /* -------------------------------------------------------------------- */ - if ( hEntity < 0 || hEntity >= psDBF->nRecords ) - return( NULL ); - - if ( iField < 0 || iField >= psDBF->nFields ) - return( NULL ); - - /* -------------------------------------------------------------------- */ - /* Have we read the record? */ - /* -------------------------------------------------------------------- */ - if ( psDBF->nCurrentRecord != hEntity ) - { - DBFFlushRecord( psDBF ); - - nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength; - - if ( fseek( psDBF->fp, nRecordOffset, 0 ) != 0 ) - { - fprintf( stderr, "fseek(%d) failed on DBF file.\n", - nRecordOffset ); - return NULL; - } - - if ( fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, - 1, psDBF->fp ) != 1 ) - { - fprintf( stderr, "fread(%d) failed on DBF file.\n", - psDBF->nRecordLength ); - return NULL; - } - - psDBF->nCurrentRecord = hEntity; - } - - pabyRec = ( unsigned char * ) psDBF->pszCurrentRecord; - - /* -------------------------------------------------------------------- */ - /* Ensure our field buffer is large enough to hold this buffer. */ - /* -------------------------------------------------------------------- */ - if ( psDBF->panFieldSize[iField] + 1 > nStringFieldLen ) - { - nStringFieldLen = psDBF->panFieldSize[iField] * 2 + 10; - pszStringField = ( char * ) SfRealloc( pszStringField, nStringFieldLen ); - } - - /* -------------------------------------------------------------------- */ - /* Extract the requested field. */ - /* -------------------------------------------------------------------- */ - strncpy( pszStringField, - (( const char * ) pabyRec ) + psDBF->panFieldOffset[iField], - psDBF->panFieldSize[iField] ); - pszStringField[psDBF->panFieldSize[iField]] = '\0'; - - pReturnField = pszStringField; - - /* -------------------------------------------------------------------- */ - /* Decode the field. */ - /* -------------------------------------------------------------------- */ - if ( chReqType == 'N' ) - { - dDoubleField = atof( pszStringField ); - - pReturnField = &dDoubleField; - } - - /* -------------------------------------------------------------------- */ - /* Should we trim white space off the string attribute value? */ - /* -------------------------------------------------------------------- */ -#ifdef TRIM_DBF_WHITESPACE - else - { - char *pchSrc, *pchDst; - - pchDst = pchSrc = pszStringField; - while ( *pchSrc == ' ' ) - pchSrc++; - - while ( *pchSrc != '\0' ) - *( pchDst++ ) = *( pchSrc++ ); - *pchDst = '\0'; - - while ( pchDst != pszStringField && *( --pchDst ) == ' ' ) - *pchDst = '\0'; - } -#endif - - return( pReturnField ); -} - -/************************************************************************/ -/* DBFReadIntAttribute() */ -/* */ -/* Read an integer attribute. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFReadIntegerAttribute( DBFHandle psDBF, int iRecord, int iField ) - -{ - double *pdValue; - - pdValue = ( double * ) DBFReadAttribute( psDBF, iRecord, iField, 'N' ); - - if ( pdValue == NULL ) - return 0; - else - return(( int ) *pdValue ); -} - -/************************************************************************/ -/* DBFReadDoubleAttribute() */ -/* */ -/* Read a double attribute. */ -/************************************************************************/ - -double SHPAPI_CALL -DBFReadDoubleAttribute( DBFHandle psDBF, int iRecord, int iField ) - -{ - double *pdValue; - - pdValue = ( double * ) DBFReadAttribute( psDBF, iRecord, iField, 'N' ); - - if ( pdValue == NULL ) - return 0.0; - else - return( *pdValue ); -} - -/************************************************************************/ -/* DBFReadStringAttribute() */ -/* */ -/* Read a string attribute. */ -/************************************************************************/ - -const char SHPAPI_CALL1( * ) -DBFReadStringAttribute( DBFHandle psDBF, int iRecord, int iField ) - -{ - return(( const char * ) DBFReadAttribute( psDBF, iRecord, iField, 'C' ) ); -} - -/************************************************************************/ -/* DBFReadLogicalAttribute() */ -/* */ -/* Read a logical attribute. */ -/************************************************************************/ - -const char SHPAPI_CALL1( * ) -DBFReadLogicalAttribute( DBFHandle psDBF, int iRecord, int iField ) - -{ - return(( const char * ) DBFReadAttribute( psDBF, iRecord, iField, 'L' ) ); -} - -/************************************************************************/ -/* DBFIsAttributeNULL() */ -/* */ -/* Return TRUE if value for field is NULL. */ -/* */ -/* Contributed by Jim Matthews. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFIsAttributeNULL( DBFHandle psDBF, int iRecord, int iField ) - -{ - const char *pszValue; - - pszValue = DBFReadStringAttribute( psDBF, iRecord, iField ); - - switch ( psDBF->pachFieldType[iField] ) - { - case 'N': - case 'F': - /* NULL numeric fields have value "****************" */ - return pszValue[0] == '*'; - - case 'D': - /* NULL date fields have value "00000000" */ - return strncmp( pszValue, "00000000", 8 ) == 0; - - case 'L': - /* NULL boolean fields have value "?" */ - return pszValue[0] == '?'; - - default: - /* empty string fields are considered NULL */ - return strlen( pszValue ) == 0; - } -} - -/************************************************************************/ -/* DBFGetFieldCount() */ -/* */ -/* Return the number of fields in this table. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFGetFieldCount( DBFHandle psDBF ) - -{ - return( psDBF->nFields ); -} - -/************************************************************************/ -/* DBFGetRecordCount() */ -/* */ -/* Return the number of records in this table. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFGetRecordCount( DBFHandle psDBF ) - -{ - return( psDBF->nRecords ); -} - -/************************************************************************/ -/* DBFGetFieldInfo() */ -/* */ -/* Return any requested information about the field. */ -/************************************************************************/ - -DBFFieldType SHPAPI_CALL -DBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName, - int * pnWidth, int * pnDecimals ) - -{ - if ( iField < 0 || iField >= psDBF->nFields ) - return( FTInvalid ); - - if ( pnWidth != NULL ) - *pnWidth = psDBF->panFieldSize[iField]; - - if ( pnDecimals != NULL ) - *pnDecimals = psDBF->panFieldDecimals[iField]; - - if ( pszFieldName != NULL ) - { - int i; - - strncpy( pszFieldName, ( char * ) psDBF->pszHeader + iField*32, 11 ); - pszFieldName[11] = '\0'; - for ( i = 10; i > 0 && pszFieldName[i] == ' '; i-- ) - pszFieldName[i] = '\0'; - } - - if ( psDBF->pachFieldType[iField] == 'L' ) - return( FTLogical ); - - else if ( psDBF->pachFieldType[iField] == 'N' - || psDBF->pachFieldType[iField] == 'F' - || psDBF->pachFieldType[iField] == 'D' ) - { - if ( psDBF->panFieldDecimals[iField] > 0 ) - return( FTDouble ); - else - return( FTInteger ); - } - else - { - return( FTString ); - } -} - -/************************************************************************/ -/* DBFWriteAttribute() */ -/* */ -/* Write an attribute record to the file. */ -/************************************************************************/ - -static int DBFWriteAttribute( DBFHandle psDBF, int hEntity, int iField, - void * pValue ) - -{ - int nRecordOffset, i, j, nRetResult = TRUE; - unsigned char *pabyRec; - char szSField[400], szFormat[20]; - - /* -------------------------------------------------------------------- */ - /* Is this a valid record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity < 0 || hEntity > psDBF->nRecords ) - return( FALSE ); - - if ( psDBF->bNoHeader ) - DBFWriteHeader( psDBF ); - - /* -------------------------------------------------------------------- */ - /* Is this a brand new record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity == psDBF->nRecords ) - { - DBFFlushRecord( psDBF ); - - psDBF->nRecords++; - for ( i = 0; i < psDBF->nRecordLength; i++ ) - psDBF->pszCurrentRecord[i] = ' '; - - psDBF->nCurrentRecord = hEntity; - } - - /* -------------------------------------------------------------------- */ - /* Is this an existing record, but different than the last one */ - /* we accessed? */ - /* -------------------------------------------------------------------- */ - if ( psDBF->nCurrentRecord != hEntity ) - { - DBFFlushRecord( psDBF ); - - nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength; - - fseek( psDBF->fp, nRecordOffset, 0 ); - fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp ); - - psDBF->nCurrentRecord = hEntity; - } - - pabyRec = ( unsigned char * ) psDBF->pszCurrentRecord; - - psDBF->bCurrentRecordModified = TRUE; - psDBF->bUpdated = TRUE; - - /* -------------------------------------------------------------------- */ - /* Translate NULL value to valid DBF file representation. */ - /* */ - /* Contributed by Jim Matthews. */ - /* -------------------------------------------------------------------- */ - if ( pValue == NULL ) - { - switch ( psDBF->pachFieldType[iField] ) - { - case 'N': - case 'F': - /* NULL numeric fields have value "****************" */ - memset(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), '*', - psDBF->panFieldSize[iField] ); - break; - - case 'D': - /* NULL date fields have value "00000000" */ - memset(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), '0', - psDBF->panFieldSize[iField] ); - break; - - case 'L': - /* NULL boolean fields have value "?" */ - memset(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), '?', - psDBF->panFieldSize[iField] ); - break; - - default: - /* empty string fields are considered NULL */ - memset(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), '\0', - psDBF->panFieldSize[iField] ); - break; - } - return TRUE; - } - - /* -------------------------------------------------------------------- */ - /* Assign all the record fields. */ - /* -------------------------------------------------------------------- */ - switch ( psDBF->pachFieldType[iField] ) - { - case 'D': - case 'N': - case 'F': - if ( psDBF->panFieldDecimals[iField] == 0 ) - { - int nWidth = psDBF->panFieldSize[iField]; - - if ( sizeof( szSField ) - 2 < nWidth ) - nWidth = sizeof( szSField ) - 2; - - sprintf( szFormat, "%%%dd", nWidth ); - sprintf( szSField, szFormat, ( int ) *(( double * ) pValue ) ); - if (( int )strlen( szSField ) > psDBF->panFieldSize[iField] ) - { - szSField[psDBF->panFieldSize[iField]] = '\0'; - nRetResult = FALSE; - } - - strncpy(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), - szSField, strlen( szSField ) ); - } - else - { - int nWidth = psDBF->panFieldSize[iField]; - - if ( sizeof( szSField ) - 2 < nWidth ) - nWidth = sizeof( szSField ) - 2; - - sprintf( szFormat, "%%%d.%df", - nWidth, psDBF->panFieldDecimals[iField] ); - sprintf( szSField, szFormat, *(( double * ) pValue ) ); - if (( int ) strlen( szSField ) > psDBF->panFieldSize[iField] ) - { - szSField[psDBF->panFieldSize[iField]] = '\0'; - nRetResult = FALSE; - } - strncpy(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), - szSField, strlen( szSField ) ); - } - break; - - case 'L': - if ( psDBF->panFieldSize[iField] >= 1 && - ( *( char* )pValue == 'F' || *( char* )pValue == 'T' ) ) - *( pabyRec + psDBF->panFieldOffset[iField] ) = *( char* )pValue; - break; - - default: - if (( int ) strlen(( char * ) pValue ) > psDBF->panFieldSize[iField] ) - { - j = psDBF->panFieldSize[iField]; - nRetResult = FALSE; - } - else - { - memset( pabyRec + psDBF->panFieldOffset[iField], ' ', - psDBF->panFieldSize[iField] ); - j = strlen(( char * ) pValue ); - } - - strncpy(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), - ( char * ) pValue, j ); - break; - } - - return( nRetResult ); -} - -/************************************************************************/ -/* DBFWriteAttributeDirectly() */ -/* */ -/* Write an attribute record to the file, but without any */ -/* reformatting based on type. The provided buffer is written */ -/* as is to the field position in the record. */ -/************************************************************************/ - -int DBFWriteAttributeDirectly( DBFHandle psDBF, int hEntity, int iField, - void * pValue ) - -{ - int nRecordOffset, i, j; - unsigned char *pabyRec; - - /* -------------------------------------------------------------------- */ - /* Is this a valid record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity < 0 || hEntity > psDBF->nRecords ) - return( FALSE ); - - if ( psDBF->bNoHeader ) - DBFWriteHeader( psDBF ); - - /* -------------------------------------------------------------------- */ - /* Is this a brand new record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity == psDBF->nRecords ) - { - DBFFlushRecord( psDBF ); - - psDBF->nRecords++; - for ( i = 0; i < psDBF->nRecordLength; i++ ) - psDBF->pszCurrentRecord[i] = ' '; - - psDBF->nCurrentRecord = hEntity; - } - - /* -------------------------------------------------------------------- */ - /* Is this an existing record, but different than the last one */ - /* we accessed? */ - /* -------------------------------------------------------------------- */ - if ( psDBF->nCurrentRecord != hEntity ) - { - DBFFlushRecord( psDBF ); - - nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength; - - fseek( psDBF->fp, nRecordOffset, 0 ); - fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp ); - - psDBF->nCurrentRecord = hEntity; - } - - pabyRec = ( unsigned char * ) psDBF->pszCurrentRecord; - - /* -------------------------------------------------------------------- */ - /* Assign all the record fields. */ - /* -------------------------------------------------------------------- */ - if (( int )strlen(( char * ) pValue ) > psDBF->panFieldSize[iField] ) - j = psDBF->panFieldSize[iField]; - else - { - memset( pabyRec + psDBF->panFieldOffset[iField], ' ', - psDBF->panFieldSize[iField] ); - j = strlen(( char * ) pValue ); - } - - strncpy(( char * )( pabyRec + psDBF->panFieldOffset[iField] ), - ( char * ) pValue, j ); - - psDBF->bCurrentRecordModified = TRUE; - psDBF->bUpdated = TRUE; - - return( TRUE ); -} - -/************************************************************************/ -/* DBFWriteDoubleAttribute() */ -/* */ -/* Write a double attribute. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFWriteDoubleAttribute( DBFHandle psDBF, int iRecord, int iField, - double dValue ) - -{ - return( DBFWriteAttribute( psDBF, iRecord, iField, ( void * ) &dValue ) ); -} - -/************************************************************************/ -/* DBFWriteIntegerAttribute() */ -/* */ -/* Write a integer attribute. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFWriteIntegerAttribute( DBFHandle psDBF, int iRecord, int iField, - int nValue ) - -{ - double dValue = nValue; - - return( DBFWriteAttribute( psDBF, iRecord, iField, ( void * ) &dValue ) ); -} - -/************************************************************************/ -/* DBFWriteStringAttribute() */ -/* */ -/* Write a string attribute. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFWriteStringAttribute( DBFHandle psDBF, int iRecord, int iField, - const char * pszValue ) - -{ - return( DBFWriteAttribute( psDBF, iRecord, iField, ( void * ) pszValue ) ); -} - -/************************************************************************/ -/* DBFWriteNULLAttribute() */ -/* */ -/* Write a string attribute. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFWriteNULLAttribute( DBFHandle psDBF, int iRecord, int iField ) - -{ - return( DBFWriteAttribute( psDBF, iRecord, iField, NULL ) ); -} - -/************************************************************************/ -/* DBFWriteLogicalAttribute() */ -/* */ -/* Write a logical attribute. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFWriteLogicalAttribute( DBFHandle psDBF, int iRecord, int iField, - const char lValue ) - -{ - return( DBFWriteAttribute( psDBF, iRecord, iField, ( void * )( &lValue ) ) ); -} - -/************************************************************************/ -/* DBFWriteTuple() */ -/* */ -/* Write an attribute record to the file. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFWriteTuple( DBFHandle psDBF, int hEntity, void * pRawTuple ) - -{ - int nRecordOffset, i; - unsigned char *pabyRec; - - /* -------------------------------------------------------------------- */ - /* Is this a valid record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity < 0 || hEntity > psDBF->nRecords ) - return( FALSE ); - - if ( psDBF->bNoHeader ) - DBFWriteHeader( psDBF ); - - /* -------------------------------------------------------------------- */ - /* Is this a brand new record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity == psDBF->nRecords ) - { - DBFFlushRecord( psDBF ); - - psDBF->nRecords++; - for ( i = 0; i < psDBF->nRecordLength; i++ ) - psDBF->pszCurrentRecord[i] = ' '; - - psDBF->nCurrentRecord = hEntity; - } - - /* -------------------------------------------------------------------- */ - /* Is this an existing record, but different than the last one */ - /* we accessed? */ - /* -------------------------------------------------------------------- */ - if ( psDBF->nCurrentRecord != hEntity ) - { - DBFFlushRecord( psDBF ); - - nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength; - - fseek( psDBF->fp, nRecordOffset, 0 ); - fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp ); - - psDBF->nCurrentRecord = hEntity; - } - - pabyRec = ( unsigned char * ) psDBF->pszCurrentRecord; - - memcpy( pabyRec, pRawTuple, psDBF->nRecordLength ); - - psDBF->bCurrentRecordModified = TRUE; - psDBF->bUpdated = TRUE; - - return( TRUE ); -} - -/************************************************************************/ -/* DBFReadTuple() */ -/* */ -/* Read one of the attribute fields of a record. */ -/************************************************************************/ - -const char SHPAPI_CALL1( * ) -DBFReadTuple( DBFHandle psDBF, int hEntity ) - -{ - int nRecordOffset; - unsigned char *pabyRec; - static char *pReturnTuple = NULL; - - static int nTupleLen = 0; - - /* -------------------------------------------------------------------- */ - /* Have we read the record? */ - /* -------------------------------------------------------------------- */ - if ( hEntity < 0 || hEntity >= psDBF->nRecords ) - return( NULL ); - - if ( psDBF->nCurrentRecord != hEntity ) - { - DBFFlushRecord( psDBF ); - - nRecordOffset = psDBF->nRecordLength * hEntity + psDBF->nHeaderLength; - - fseek( psDBF->fp, nRecordOffset, 0 ); - fread( psDBF->pszCurrentRecord, psDBF->nRecordLength, 1, psDBF->fp ); - - psDBF->nCurrentRecord = hEntity; - } - - pabyRec = ( unsigned char * ) psDBF->pszCurrentRecord; - - if ( nTupleLen < psDBF->nRecordLength ) - { - nTupleLen = psDBF->nRecordLength; - pReturnTuple = ( char * ) SfRealloc( pReturnTuple, psDBF->nRecordLength ); - } - - memcpy( pReturnTuple, pabyRec, psDBF->nRecordLength ); - - return( pReturnTuple ); -} - -/************************************************************************/ -/* DBFCloneEmpty() */ -/* */ -/* Read one of the attribute fields of a record. */ -/************************************************************************/ - -DBFHandle SHPAPI_CALL -DBFCloneEmpty( DBFHandle psDBF, const char * pszFilename ) -{ - DBFHandle newDBF; - - newDBF = DBFCreate( pszFilename ); - if ( newDBF == NULL ) - return ( NULL ); - - newDBF->pszHeader = ( char * ) malloc( 32 * psDBF->nFields ); - memcpy( newDBF->pszHeader, psDBF->pszHeader, 32 * psDBF->nFields ); - - newDBF->nFields = psDBF->nFields; - newDBF->nRecordLength = psDBF->nRecordLength; - newDBF->nHeaderLength = 32 * ( psDBF->nFields + 1 ); - - newDBF->panFieldOffset = ( int * ) malloc( sizeof( int ) * psDBF->nFields ); - memcpy( newDBF->panFieldOffset, psDBF->panFieldOffset, sizeof( int ) * psDBF->nFields ); - newDBF->panFieldSize = ( int * ) malloc( sizeof( int ) * psDBF->nFields ); - memcpy( newDBF->panFieldSize, psDBF->panFieldSize, sizeof( int ) * psDBF->nFields ); - newDBF->panFieldDecimals = ( int * ) malloc( sizeof( int ) * psDBF->nFields ); - memcpy( newDBF->panFieldDecimals, psDBF->panFieldDecimals, sizeof( int ) * psDBF->nFields ); - newDBF->pachFieldType = ( char * ) malloc( sizeof( int ) * psDBF->nFields ); - memcpy( newDBF->pachFieldType, psDBF->pachFieldType, sizeof( int ) * psDBF->nFields ); - - newDBF->bNoHeader = TRUE; - newDBF->bUpdated = TRUE; - - DBFWriteHeader( newDBF ); - DBFClose( newDBF ); - - newDBF = DBFOpen( pszFilename, "rb+" ); - - return ( newDBF ); -} - -/************************************************************************/ -/* DBFGetNativeFieldType() */ -/* */ -/* Return the DBase field type for the specified field. */ -/* */ -/* Value can be one of: 'C' (String), 'D' (Date), 'F' (Float), */ -/* 'N' (Numeric, with or without decimal), */ -/* 'L' (Logical), */ -/* 'M' (Memo: 10 digits .DBT block ptr) */ -/************************************************************************/ - -char SHPAPI_CALL -DBFGetNativeFieldType( DBFHandle psDBF, int iField ) - -{ - if ( iField >= 0 && iField < psDBF->nFields ) - return psDBF->pachFieldType[iField]; - - return ' '; -} - -/************************************************************************/ -/* str_to_upper() */ -/************************************************************************/ - -static void str_to_upper( char *string ) -{ - int len; - short i = -1; - - len = strlen( string ); - - while ( ++i < len ) - if ( isalpha( string[i] ) && islower( string[i] ) ) - string[i] = toupper(( int )string[i] ); -} - -/************************************************************************/ -/* DBFGetFieldIndex() */ -/* */ -/* Get the index number for a field in a .dbf file. */ -/* */ -/* Contributed by Jim Matthews. */ -/************************************************************************/ - -int SHPAPI_CALL -DBFGetFieldIndex( DBFHandle psDBF, const char *pszFieldName ) - -{ - char name[12], name1[12], name2[12]; - int i; - - strncpy( name1, pszFieldName, 11 ); - name1[11] = '\0'; - str_to_upper( name1 ); - - for ( i = 0; i < DBFGetFieldCount( psDBF ); i++ ) - { - DBFGetFieldInfo( psDBF, i, name, NULL, NULL ); - strncpy( name2, name, 11 ); - str_to_upper( name2 ); - - if ( !strncmp( name1, name2, 10 ) ) - return( i ); - } - return( -1 ); -} diff --git a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shapefil.h b/src/plugins/dxf2shp_converter/shapelib-1.2.10/shapefil.h deleted file mode 100644 index bf07768ea48c..000000000000 --- a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shapefil.h +++ /dev/null @@ -1,486 +0,0 @@ -#ifndef _SHAPEFILE_H_INCLUDED -#define _SHAPEFILE_H_INCLUDED - -/****************************************************************************** - * $Id: shapefil.h,v 1.26 2002/09/29 00:00:08 warmerda Exp $ - * - * Project: Shapelib - * Purpose: Primary include file for Shapelib. - * Author: Frank Warmerdam, warmerdam@pobox.com - * - ****************************************************************************** - * Copyright (c) 1999, Frank Warmerdam - * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see LICENSE.LGPL). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ****************************************************************************** - * - * $Log: shapefil.h,v $ - * Revision 1.26 2002/09/29 00:00:08 warmerda - * added FTLogical and logical attribute read/write calls - * - * Revision 1.25 2002/05/07 13:46:30 warmerda - * added DBFWriteAttributeDirectly(). - * - * Revision 1.24 2002/04/10 16:59:54 warmerda - * added SHPRewindObject - * - * Revision 1.23 2002/01/15 14:36:07 warmerda - * updated email address - * - * Revision 1.22 2002/01/15 14:32:00 warmerda - * try to improve SHPAPI_CALL docs - * - * Revision 1.21 2001/11/01 16:29:55 warmerda - * move pabyRec into SHPInfo for thread safety - * - * Revision 1.20 2001/07/20 13:06:02 warmerda - * fixed SHPAPI attribute for SHPTreeFindLikelyShapes - * - * Revision 1.19 2001/05/31 19:20:13 warmerda - * added DBFGetFieldIndex() - * - * Revision 1.18 2001/05/31 18:15:40 warmerda - * Added support for NULL fields in DBF files - * - * Revision 1.17 2001/05/23 13:36:52 warmerda - * added use of SHPAPI_CALL - * - * Revision 1.16 2000/09/25 14:15:59 warmerda - * added DBFGetNativeFieldType() - * - * Revision 1.15 2000/02/16 16:03:51 warmerda - * added null shape support - * - * Revision 1.14 1999/11/05 14:12:05 warmerda - * updated license terms - * - * Revision 1.13 1999/06/02 18:24:21 warmerda - * added trimming code - * - * Revision 1.12 1999/06/02 17:56:12 warmerda - * added quad'' subnode support for trees - * - * Revision 1.11 1999/05/18 19:11:11 warmerda - * Added example searching capability - * - * Revision 1.10 1999/05/18 17:49:38 warmerda - * added initial quadtree support - * - * Revision 1.9 1999/05/11 03:19:28 warmerda - * added new Tuple api, and improved extension handling - add from candrsn - * - * Revision 1.8 1999/03/23 17:22:27 warmerda - * Added extern "C" protection for C++ users of shapefil.h. - * - * Revision 1.7 1998/12/31 15:31:07 warmerda - * Added the TRIM_DBF_WHITESPACE and DISABLE_MULTIPATCH_MEASURE options. - * - * Revision 1.6 1998/12/03 15:48:15 warmerda - * Added SHPCalculateExtents(). - * - * Revision 1.5 1998/11/09 20:57:16 warmerda - * Altered SHPGetInfo() call. - * - * Revision 1.4 1998/11/09 20:19:33 warmerda - * Added 3D support, and use of SHPObject. - * - * Revision 1.3 1995/08/23 02:24:05 warmerda - * Added support for reading bounds. - * - * Revision 1.2 1995/08/04 03:17:39 warmerda - * Added header. - * - */ - -#include - -#ifdef USE_DBMALLOC -#include -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - - /************************************************************************/ - /* Configuration options. */ - /************************************************************************/ - - /* -------------------------------------------------------------------- */ - /* Should the DBFReadStringAttribute() strip leading and */ - /* trailing white space? */ - /* -------------------------------------------------------------------- */ -#define TRIM_DBF_WHITESPACE - - /* -------------------------------------------------------------------- */ - /* Should we write measure values to the Multipatch object? */ - /* Reportedly ArcView crashes if we do write it, so for now it */ - /* is disabled. */ - /* -------------------------------------------------------------------- */ -#define DISABLE_MULTIPATCH_MEASURE - - /* -------------------------------------------------------------------- */ - /* SHPAPI_CALL */ - /* */ - /* The following two macros are present to allow forcing */ - /* various calling conventions on the Shapelib API. */ - /* */ - /* To force __stdcall conventions (needed to call Shapelib */ - /* from Visual Basic and/or Dephi I believe) the makefile could */ - /* be modified to define: */ - /* */ - /* /DSHPAPI_CALL=__stdcall */ - /* */ - /* If it is desired to force export of the Shapelib API without */ - /* using the shapelib.def file, use the following definition. */ - /* */ - /* /DSHAPELIB_DLLEXPORT */ - /* */ - /* To get both at once it will be necessary to hack this */ - /* include file to define: */ - /* */ - /* #define SHPAPI_CALL __declspec(dllexport) __stdcall */ - /* #define SHPAPI_CALL1 __declspec(dllexport) * __stdcall */ - /* */ - /* The complexity of the situtation is partly caused by the */ - /* peculiar requirement of Visual C++ that __stdcall appear */ - /* after any "*"'s in the return value of a function while the */ - /* __declspec(dllexport) must appear before them. */ - /* -------------------------------------------------------------------- */ - -#ifdef SHAPELIB_DLLEXPORT -# define SHPAPI_CALL __declspec(dllexport) -# define SHPAPI_CALL1(x) __declspec(dllexport) x -#endif - -#ifndef SHPAPI_CALL -# define SHPAPI_CALL -#endif - -#ifndef SHPAPI_CALL1 -# define SHPAPI_CALL1(x) x SHPAPI_CALL -#endif - - /************************************************************************/ - /* SHP Support. */ - /************************************************************************/ - typedef struct - { - FILE *fpSHP; - FILE *fpSHX; - - int nShapeType; /* SHPT_* */ - - int nFileSize; /* SHP file */ - - int nRecords; - int nMaxRecords; - int *panRecOffset; - int *panRecSize; - - double adBoundsMin[4]; - double adBoundsMax[4]; - - int bUpdated; - - unsigned char *pabyRec; - int nBufSize; - } SHPInfo; - - typedef SHPInfo * SHPHandle; - - /* -------------------------------------------------------------------- */ - /* Shape types (nSHPType) */ - /* -------------------------------------------------------------------- */ -#define SHPT_NULL 0 -#define SHPT_POINT 1 -#define SHPT_ARC 3 -#define SHPT_POLYGON 5 -#define SHPT_MULTIPOINT 8 -#define SHPT_POINTZ 11 -#define SHPT_ARCZ 13 -#define SHPT_POLYGONZ 15 -#define SHPT_MULTIPOINTZ 18 -#define SHPT_POINTM 21 -#define SHPT_ARCM 23 -#define SHPT_POLYGONM 25 -#define SHPT_MULTIPOINTM 28 -#define SHPT_MULTIPATCH 31 - - - /* -------------------------------------------------------------------- */ - /* Part types - everything but SHPT_MULTIPATCH just uses */ - /* SHPP_RING. */ - /* -------------------------------------------------------------------- */ - -#define SHPP_TRISTRIP 0 -#define SHPP_TRIFAN 1 -#define SHPP_OUTERRING 2 -#define SHPP_INNERRING 3 -#define SHPP_FIRSTRING 4 -#define SHPP_RING 5 - - /* -------------------------------------------------------------------- */ - /* SHPObject - represents on shape (without attributes) read */ - /* from the .shp file. */ - /* -------------------------------------------------------------------- */ - typedef struct - { - int nSHPType; - - int nShapeId; /* -1 is unknown/unassigned */ - - int nParts; - int *panPartStart; - int *panPartType; - - int nVertices; - double *padfX; - double *padfY; - double *padfZ; - double *padfM; - - double dfXMin; - double dfYMin; - double dfZMin; - double dfMMin; - - double dfXMax; - double dfYMax; - double dfZMax; - double dfMMax; - } SHPObject; - - /* -------------------------------------------------------------------- */ - /* SHP API Prototypes */ - /* -------------------------------------------------------------------- */ - SHPHandle SHPAPI_CALL - SHPOpen( const char * pszShapeFile, const char * pszAccess ); - SHPHandle SHPAPI_CALL - SHPCreate( const char * pszShapeFile, int nShapeType ); - void SHPAPI_CALL - SHPGetInfo( SHPHandle hSHP, int * pnEntities, int * pnShapeType, - double * padfMinBound, double * padfMaxBound ); - - SHPObject SHPAPI_CALL1( * ) - SHPReadObject( SHPHandle hSHP, int iShape ); - int SHPAPI_CALL - SHPWriteObject( SHPHandle hSHP, int iShape, SHPObject * psObject ); - - void SHPAPI_CALL - SHPDestroyObject( SHPObject * psObject ); - void SHPAPI_CALL - SHPComputeExtents( SHPObject * psObject ); - SHPObject SHPAPI_CALL1( * ) - SHPCreateObject( int nSHPType, int nShapeId, - int nParts, int * panPartStart, int * panPartType, - int nVertices, double * padfX, double * padfY, - double * padfZ, double * padfM ); - SHPObject SHPAPI_CALL1( * ) - SHPCreateSimpleObject( int nSHPType, int nVertices, - double * padfX, double * padfY, double * padfZ ); - - int SHPAPI_CALL - SHPRewindObject( SHPHandle hSHP, SHPObject * psObject ); - - void SHPAPI_CALL - SHPClose( SHPHandle hSHP ); - - const char SHPAPI_CALL1( * ) - SHPTypeName( int nSHPType ); - const char SHPAPI_CALL1( * ) - SHPPartTypeName( int nPartType ); - - /* -------------------------------------------------------------------- */ - /* Shape quadtree indexing API. */ - /* -------------------------------------------------------------------- */ - - /* this can be two or four for binary or quad tree */ -#define MAX_SUBNODE 4 - - typedef struct shape_tree_node - { - /* region covered by this node */ - double adfBoundsMin[4]; - double adfBoundsMax[4]; - - /* list of shapes stored at this node. The papsShapeObj pointers - or the whole list can be NULL */ - int nShapeCount; - int *panShapeIds; - SHPObject **papsShapeObj; - - int nSubNodes; - struct shape_tree_node *apsSubNode[MAX_SUBNODE]; - - } SHPTreeNode; - - typedef struct - { - SHPHandle hSHP; - - int nMaxDepth; - int nDimension; - - SHPTreeNode *psRoot; - } SHPTree; - - SHPTree SHPAPI_CALL1( * ) - SHPCreateTree( SHPHandle hSHP, int nDimension, int nMaxDepth, - double *padfBoundsMin, double *padfBoundsMax ); - void SHPAPI_CALL - SHPDestroyTree( SHPTree * hTree ); - - int SHPAPI_CALL - SHPWriteTree( SHPTree *hTree, const char * pszFileName ); - SHPTree SHPAPI_CALL - SHPReadTree( const char * pszFileName ); - - int SHPAPI_CALL - SHPTreeAddObject( SHPTree * hTree, SHPObject * psObject ); - int SHPAPI_CALL - SHPTreeAddShapeId( SHPTree * hTree, SHPObject * psObject ); - int SHPAPI_CALL - SHPTreeRemoveShapeId( SHPTree * hTree, int nShapeId ); - - void SHPAPI_CALL - SHPTreeTrimExtraNodes( SHPTree * hTree ); - - int SHPAPI_CALL1( * ) - SHPTreeFindLikelyShapes( SHPTree * hTree, - double * padfBoundsMin, - double * padfBoundsMax, - int * ); - int SHPAPI_CALL - SHPCheckBoundsOverlap( double *, double *, double *, double *, int ); - - /************************************************************************/ - /* DBF Support. */ - /************************************************************************/ - typedef struct - { - FILE *fp; - - int nRecords; - - int nRecordLength; - int nHeaderLength; - int nFields; - int *panFieldOffset; - int *panFieldSize; - int *panFieldDecimals; - char *pachFieldType; - - char *pszHeader; - - int nCurrentRecord; - int bCurrentRecordModified; - char *pszCurrentRecord; - - int bNoHeader; - int bUpdated; - } DBFInfo; - - typedef DBFInfo * DBFHandle; - - typedef enum - { - FTString, - FTInteger, - FTDouble, - FTLogical, - FTInvalid - } DBFFieldType; - -#define XBASE_FLDHDR_SZ 32 - - DBFHandle SHPAPI_CALL - DBFOpen( const char * pszDBFFile, const char * pszAccess ); - DBFHandle SHPAPI_CALL - DBFCreate( const char * pszDBFFile ); - - int SHPAPI_CALL - DBFGetFieldCount( DBFHandle psDBF ); - int SHPAPI_CALL - DBFGetRecordCount( DBFHandle psDBF ); - int SHPAPI_CALL - DBFAddField( DBFHandle hDBF, const char * pszFieldName, - DBFFieldType eType, int nWidth, int nDecimals ); - - DBFFieldType SHPAPI_CALL - DBFGetFieldInfo( DBFHandle psDBF, int iField, - char * pszFieldName, int * pnWidth, int * pnDecimals ); - - int SHPAPI_CALL - DBFGetFieldIndex( DBFHandle psDBF, const char *pszFieldName ); - - int SHPAPI_CALL - DBFReadIntegerAttribute( DBFHandle hDBF, int iShape, int iField ); - double SHPAPI_CALL - DBFReadDoubleAttribute( DBFHandle hDBF, int iShape, int iField ); - const char SHPAPI_CALL1( * ) - DBFReadStringAttribute( DBFHandle hDBF, int iShape, int iField ); - const char SHPAPI_CALL1( * ) - DBFReadLogicalAttribute( DBFHandle hDBF, int iShape, int iField ); - int SHPAPI_CALL - DBFIsAttributeNULL( DBFHandle hDBF, int iShape, int iField ); - - int SHPAPI_CALL - DBFWriteIntegerAttribute( DBFHandle hDBF, int iShape, int iField, - int nFieldValue ); - int SHPAPI_CALL - DBFWriteDoubleAttribute( DBFHandle hDBF, int iShape, int iField, - double dFieldValue ); - int SHPAPI_CALL - DBFWriteStringAttribute( DBFHandle hDBF, int iShape, int iField, - const char * pszFieldValue ); - int SHPAPI_CALL - DBFWriteNULLAttribute( DBFHandle hDBF, int iShape, int iField ); - - int SHPAPI_CALL - DBFWriteLogicalAttribute( DBFHandle hDBF, int iShape, int iField, - const char lFieldValue ); - int SHPAPI_CALL - DBFWriteAttributeDirectly( DBFHandle psDBF, int hEntity, int iField, - void * pValue ); - const char SHPAPI_CALL1( * ) - DBFReadTuple( DBFHandle psDBF, int hEntity ); - int SHPAPI_CALL - DBFWriteTuple( DBFHandle psDBF, int hEntity, void * pRawTuple ); - - DBFHandle SHPAPI_CALL - DBFCloneEmpty( DBFHandle psDBF, const char * pszFileName ); - - void SHPAPI_CALL - DBFClose( DBFHandle hDBF ); - char SHPAPI_CALL - DBFGetNativeFieldType( DBFHandle hDBF, int iField ); - -#ifdef __cplusplus -} -#endif - -#endif /* ndef _SHAPEFILE_H_INCLUDED */ diff --git a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shapelib.def b/src/plugins/dxf2shp_converter/shapelib-1.2.10/shapelib.def deleted file mode 100644 index 016fecef74c6..000000000000 --- a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shapelib.def +++ /dev/null @@ -1,42 +0,0 @@ -LIBRARY shapelib -EXPORTS SHPOpen - SHPCreate - SHPGetInfo - SHPReadObject - SHPWriteObject - SHPDestroyObject - SHPComputeExtents - SHPCreateObject - SHPCreateSimpleObject - SHPClose - SHPTypeName - SHPPartTypeName - SHPCreateTree - SHPDestroyTree - SHPTreeAddShapeId - SHPTreeTrimExtraNodes - SHPTreeFindLikelyShapes - SHPCheckBoundsOverlap - DBFOpen - DBFCreate - DBFGetFieldCount - DBFGetRecordCount - DBFAddField - DBFGetFieldInfo - DBFReadIntegerAttribute - DBFReadDoubleAttribute - DBFReadStringAttribute - DBFWriteIntegerAttribute - DBFWriteDoubleAttribute - DBFWriteStringAttribute - DBFReadTuple - DBFWriteTuple - DBFCloneEmpty - DBFClose - DBFWriteNULLAttribute - DBFGetFieldIndex - DBFIsAttributeNULL - DBFWriteLogicalAttribute - DBFReadLogicalAttribute - - diff --git a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shpopen.c b/src/plugins/dxf2shp_converter/shapelib-1.2.10/shpopen.c deleted file mode 100644 index 0b1be794832b..000000000000 --- a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shpopen.c +++ /dev/null @@ -1,1878 +0,0 @@ -/****************************************************************************** - * $Id: shpopen.c,v 1.39 2002/08/26 06:46:56 warmerda Exp $ - * - * Project: Shapelib - * Purpose: Implementation of core Shapefile read/write functions. - * Author: Frank Warmerdam, warmerdam@pobox.com - * - ****************************************************************************** - * Copyright (c) 1999, 2001, Frank Warmerdam - * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see LICENSE.LGPL). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ****************************************************************************** - * - * $Log: shpopen.c,v $ - * Revision 1.39 2002/08/26 06:46:56 warmerda - * avoid c++ comments - * - * Revision 1.38 2002/05/07 16:43:39 warmerda - * Removed debugging printf. - * - * Revision 1.37 2002/04/10 17:35:22 warmerda - * fixed bug in ring reversal code - * - * Revision 1.36 2002/04/10 16:59:54 warmerda - * added SHPRewindObject - * - * Revision 1.35 2001/12/07 15:10:44 warmerda - * fix if .shx fails to open - * - * Revision 1.34 2001/11/01 16:29:55 warmerda - * move pabyRec into SHPInfo for thread safety - * - * Revision 1.33 2001/07/03 12:18:15 warmerda - * Improved cleanup if SHX not found, provied by Riccardo Cohen. - * - * Revision 1.32 2001/06/22 01:58:07 warmerda - * be more careful about establishing initial bounds in face of NULL shapes - * - * Revision 1.31 2001/05/31 19:35:29 warmerda - * added support for writing null shapes - * - * Revision 1.30 2001/05/28 12:46:29 warmerda - * Add some checking on reasonableness of record count when opening. - * - * Revision 1.29 2001/05/23 13:36:52 warmerda - * added use of SHPAPI_CALL - * - * Revision 1.28 2001/02/06 22:25:06 warmerda - * fixed memory leaks when SHPOpen() fails - * - * Revision 1.27 2000/07/18 15:21:33 warmerda - * added better enforcement of -1 for append in SHPWriteObject - * - * Revision 1.26 2000/02/16 16:03:51 warmerda - * added null shape support - * - * Revision 1.25 1999/12/15 13:47:07 warmerda - * Fixed record size settings in .shp file (was 4 words too long) - * Added stdlib.h. - * - * Revision 1.24 1999/11/05 14:12:04 warmerda - * updated license terms - * - * Revision 1.23 1999/07/27 00:53:46 warmerda - * added support for rewriting shapes - * - * Revision 1.22 1999/06/11 19:19:11 warmerda - * Cleanup pabyRec static buffer on SHPClose(). - * - * Revision 1.21 1999/06/02 14:57:56 kshih - * Remove unused variables - * - * Revision 1.20 1999/04/19 21:04:17 warmerda - * Fixed syntax error. - * - * Revision 1.19 1999/04/19 21:01:57 warmerda - * Force access string to binary in SHPOpen(). - * - * Revision 1.18 1999/04/01 18:48:07 warmerda - * Try upper case extensions if lower case doesn't work. - * - * Revision 1.17 1998/12/31 15:29:39 warmerda - * Disable writing measure values to multipatch objects if - * DISABLE_MULTIPATCH_MEASURE is defined. - * - * Revision 1.16 1998/12/16 05:14:33 warmerda - * Added support to write MULTIPATCH. Fixed reading Z coordinate of - * MULTIPATCH. Fixed record size written for all feature types. - * - * Revision 1.15 1998/12/03 16:35:29 warmerda - * r+b is proper binary access string, not rb+. - * - * Revision 1.14 1998/12/03 15:47:56 warmerda - * Fixed setting of nVertices in SHPCreateObject(). - * - * Revision 1.13 1998/12/03 15:33:54 warmerda - * Made SHPCalculateExtents() separately callable. - * - * Revision 1.12 1998/11/11 20:01:50 warmerda - * Fixed bug writing ArcM/Z, and PolygonM/Z for big endian machines. - * - * Revision 1.11 1998/11/09 20:56:44 warmerda - * Fixed up handling of file wide bounds. - * - * Revision 1.10 1998/11/09 20:18:51 warmerda - * Converted to support 3D shapefiles, and use of SHPObject. - * - * Revision 1.9 1998/02/24 15:09:05 warmerda - * Fixed memory leak. - * - * Revision 1.8 1997/12/04 15:40:29 warmerda - * Fixed byte swapping of record number, and record length fields in the - * .shp file. - * - * Revision 1.7 1995/10/21 03:15:58 warmerda - * Added support for binary file access, the magic cookie 9997 - * and tried to improve the int32 selection logic for 16bit systems. - * - * Revision 1.6 1995/09/04 04:19:41 warmerda - * Added fix for file bounds. - * - * Revision 1.5 1995/08/25 15:16:44 warmerda - * Fixed a couple of problems with big endian systems ... one with bounds - * and the other with multipart polygons. - * - * Revision 1.4 1995/08/24 18:10:17 warmerda - * Switch to use SfRealloc() to avoid problems with pre-ANSI realloc() - * functions (such as on the Sun). - * - * Revision 1.3 1995/08/23 02:23:15 warmerda - * Added support for reading bounds, and fixed up problems in setting the - * file wide bounds. - * - * Revision 1.2 1995/08/04 03:16:57 warmerda - * Added header. - * - */ - -static char rcsid[] = - "$Id: shpopen.c,v 1.39 2002/08/26 06:46:56 warmerda Exp $"; - -#include "shapefil.h" - -#include -#include -#include -#include -#include - -typedef unsigned char uchar; - -#if UINT_MAX == 65535 -typedef long int32; -#else -typedef int int32; -#endif - -#ifndef FALSE -# define FALSE 0 -# define TRUE 1 -#endif - -#define ByteCopy( a, b, c ) memcpy( b, a, c ) -#ifndef MAX -# define MIN(a,b) ((ab) ? a : b) -#endif - -static int bBigEndian; - - -/************************************************************************/ -/* SwapWord() */ -/* */ -/* Swap a 2, 4 or 8 byte word. */ -/************************************************************************/ - -static void SwapWord( int length, void * wordP ) - -{ - int i; - uchar temp; - - for ( i = 0; i < length / 2; i++ ) - { - temp = (( uchar * ) wordP )[i]; - (( uchar * )wordP )[i] = (( uchar * ) wordP )[length-i-1]; - (( uchar * ) wordP )[length-i-1] = temp; - } -} - -/************************************************************************/ -/* SfRealloc() */ -/* */ -/* A realloc cover function that will access a NULL pointer as */ -/* a valid input. */ -/************************************************************************/ - -static void * SfRealloc( void * pMem, int nNewSize ) - -{ - if ( pMem == NULL ) - return(( void * ) malloc( nNewSize ) ); - else - return(( void * ) realloc( pMem, nNewSize ) ); -} - -/************************************************************************/ -/* SHPWriteHeader() */ -/* */ -/* Write out a header for the .shp and .shx files as well as the */ -/* contents of the index (.shx) file. */ -/************************************************************************/ - -static void SHPWriteHeader( SHPHandle psSHP ) - -{ - uchar abyHeader[100]; - int i; - int32 i32; - double dValue; - int32 *panSHX; - - /* -------------------------------------------------------------------- */ - /* Prepare header block for .shp file. */ - /* -------------------------------------------------------------------- */ - for ( i = 0; i < 100; i++ ) - abyHeader[i] = 0; - - abyHeader[2] = 0x27; /* magic cookie */ - abyHeader[3] = 0x0a; - - i32 = psSHP->nFileSize / 2; /* file size */ - ByteCopy( &i32, abyHeader + 24, 4 ); - if ( !bBigEndian ) SwapWord( 4, abyHeader + 24 ); - - i32 = 1000; /* version */ - ByteCopy( &i32, abyHeader + 28, 4 ); - if ( bBigEndian ) SwapWord( 4, abyHeader + 28 ); - - i32 = psSHP->nShapeType; /* shape type */ - ByteCopy( &i32, abyHeader + 32, 4 ); - if ( bBigEndian ) SwapWord( 4, abyHeader + 32 ); - - dValue = psSHP->adBoundsMin[0]; /* set bounds */ - ByteCopy( &dValue, abyHeader + 36, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 36 ); - - dValue = psSHP->adBoundsMin[1]; - ByteCopy( &dValue, abyHeader + 44, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 44 ); - - dValue = psSHP->adBoundsMax[0]; - ByteCopy( &dValue, abyHeader + 52, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 52 ); - - dValue = psSHP->adBoundsMax[1]; - ByteCopy( &dValue, abyHeader + 60, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 60 ); - - dValue = psSHP->adBoundsMin[2]; /* z */ - ByteCopy( &dValue, abyHeader + 68, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 68 ); - - dValue = psSHP->adBoundsMax[2]; - ByteCopy( &dValue, abyHeader + 76, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 76 ); - - dValue = psSHP->adBoundsMin[3]; /* m */ - ByteCopy( &dValue, abyHeader + 84, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 84 ); - - dValue = psSHP->adBoundsMax[3]; - ByteCopy( &dValue, abyHeader + 92, 8 ); - if ( bBigEndian ) SwapWord( 8, abyHeader + 92 ); - - /* -------------------------------------------------------------------- */ - /* Write .shp file header. */ - /* -------------------------------------------------------------------- */ - fseek( psSHP->fpSHP, 0, 0 ); - fwrite( abyHeader, 100, 1, psSHP->fpSHP ); - - /* -------------------------------------------------------------------- */ - /* Prepare, and write .shx file header. */ - /* -------------------------------------------------------------------- */ - i32 = ( psSHP->nRecords * 2 * sizeof( int32 ) + 100 ) / 2; /* file size */ - ByteCopy( &i32, abyHeader + 24, 4 ); - if ( !bBigEndian ) SwapWord( 4, abyHeader + 24 ); - - fseek( psSHP->fpSHX, 0, 0 ); - fwrite( abyHeader, 100, 1, psSHP->fpSHX ); - - /* -------------------------------------------------------------------- */ - /* Write out the .shx contents. */ - /* -------------------------------------------------------------------- */ - panSHX = ( int32 * ) malloc( sizeof( int32 ) * 2 * psSHP->nRecords ); - - for ( i = 0; i < psSHP->nRecords; i++ ) - { - panSHX[i*2 ] = psSHP->panRecOffset[i] / 2; - panSHX[i*2+1] = psSHP->panRecSize[i] / 2; - if ( !bBigEndian ) SwapWord( 4, panSHX + i*2 ); - if ( !bBigEndian ) SwapWord( 4, panSHX + i*2 + 1 ); - } - - fwrite( panSHX, sizeof( int32 ) * 2, psSHP->nRecords, psSHP->fpSHX ); - - free( panSHX ); -} - -/************************************************************************/ -/* SHPOpen() */ -/* */ -/* Open the .shp and .shx files based on the basename of the */ -/* files or either file name. */ -/************************************************************************/ - -SHPHandle SHPAPI_CALL -SHPOpen( const char * pszLayer, const char * pszAccess ) - -{ - char *pszFullname, *pszBasename; - SHPHandle psSHP; - - uchar *pabyBuf; - int i; - double dValue; - - /* -------------------------------------------------------------------- */ - /* Ensure the access string is one of the legal ones. We */ - /* ensure the result string indicates binary to avoid common */ - /* problems on Windows. */ - /* -------------------------------------------------------------------- */ - if ( strcmp( pszAccess, "rb+" ) == 0 || strcmp( pszAccess, "r+b" ) == 0 - || strcmp( pszAccess, "r+" ) == 0 ) - pszAccess = "r+b"; - else - pszAccess = "rb"; - - /* -------------------------------------------------------------------- */ - /* Establish the byte order on this machine. */ - /* -------------------------------------------------------------------- */ - i = 1; - if ( *(( uchar * ) &i ) == 1 ) - bBigEndian = FALSE; - else - bBigEndian = TRUE; - - /* -------------------------------------------------------------------- */ - /* Initialize the info structure. */ - /* -------------------------------------------------------------------- */ - psSHP = ( SHPHandle ) calloc( sizeof( SHPInfo ), 1 ); - - psSHP->bUpdated = FALSE; - - /* -------------------------------------------------------------------- */ - /* Compute the base (layer) name. If there is any extension */ - /* on the passed in filename we will strip it off. */ - /* -------------------------------------------------------------------- */ - pszBasename = ( char * ) malloc( strlen( pszLayer ) + 5 ); - strcpy( pszBasename, pszLayer ); - for ( i = strlen( pszBasename ) - 1; - i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/' - && pszBasename[i] != '\\'; - i-- ) {} - - if ( pszBasename[i] == '.' ) - pszBasename[i] = '\0'; - - /* -------------------------------------------------------------------- */ - /* Open the .shp and .shx files. Note that files pulled from */ - /* a PC to Unix with upper case filenames won't work! */ - /* -------------------------------------------------------------------- */ - pszFullname = ( char * ) malloc( strlen( pszBasename ) + 5 ); - sprintf( pszFullname, "%s.shp", pszBasename ); - psSHP->fpSHP = fopen( pszFullname, pszAccess ); - if ( psSHP->fpSHP == NULL ) - { - sprintf( pszFullname, "%s.SHP", pszBasename ); - psSHP->fpSHP = fopen( pszFullname, pszAccess ); - } - - if ( psSHP->fpSHP == NULL ) - { - free( psSHP ); - free( pszBasename ); - free( pszFullname ); - return( NULL ); - } - - sprintf( pszFullname, "%s.shx", pszBasename ); - psSHP->fpSHX = fopen( pszFullname, pszAccess ); - if ( psSHP->fpSHX == NULL ) - { - sprintf( pszFullname, "%s.SHX", pszBasename ); - psSHP->fpSHX = fopen( pszFullname, pszAccess ); - } - - if ( psSHP->fpSHX == NULL ) - { - fclose( psSHP->fpSHP ); - free( psSHP ); - free( pszBasename ); - free( pszFullname ); - return( NULL ); - } - - free( pszFullname ); - free( pszBasename ); - - /* -------------------------------------------------------------------- */ - /* Read the file size from the SHP file. */ - /* -------------------------------------------------------------------- */ - pabyBuf = ( uchar * ) malloc( 100 ); - fread( pabyBuf, 100, 1, psSHP->fpSHP ); - - psSHP->nFileSize = ( pabyBuf[24] * 256 * 256 * 256 - + pabyBuf[25] * 256 * 256 - + pabyBuf[26] * 256 - + pabyBuf[27] ) * 2; - - /* -------------------------------------------------------------------- */ - /* Read SHX file Header info */ - /* -------------------------------------------------------------------- */ - fread( pabyBuf, 100, 1, psSHP->fpSHX ); - - if ( pabyBuf[0] != 0 - || pabyBuf[1] != 0 - || pabyBuf[2] != 0x27 - || ( pabyBuf[3] != 0x0a && pabyBuf[3] != 0x0d ) ) - { - fclose( psSHP->fpSHP ); - fclose( psSHP->fpSHX ); - free( psSHP ); - free( pabyBuf ); - - return( NULL ); - } - - psSHP->nRecords = pabyBuf[27] + pabyBuf[26] * 256 - + pabyBuf[25] * 256 * 256 + pabyBuf[24] * 256 * 256 * 256; - psSHP->nRecords = ( psSHP->nRecords * 2 - 100 ) / 8; - - psSHP->nShapeType = pabyBuf[32]; - - if ( psSHP->nRecords < 0 || psSHP->nRecords > 256000000 ) - { - /* this header appears to be corrupt. Give up. */ - fclose( psSHP->fpSHP ); - fclose( psSHP->fpSHX ); - free( psSHP ); - - free( pabyBuf ); - - return( NULL ); - } - - /* -------------------------------------------------------------------- */ - /* Read the bounds. */ - /* -------------------------------------------------------------------- */ - if ( bBigEndian ) SwapWord( 8, pabyBuf + 36 ); - memcpy( &dValue, pabyBuf + 36, 8 ); - psSHP->adBoundsMin[0] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 44 ); - memcpy( &dValue, pabyBuf + 44, 8 ); - psSHP->adBoundsMin[1] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 52 ); - memcpy( &dValue, pabyBuf + 52, 8 ); - psSHP->adBoundsMax[0] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 60 ); - memcpy( &dValue, pabyBuf + 60, 8 ); - psSHP->adBoundsMax[1] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 68 ); /* z */ - memcpy( &dValue, pabyBuf + 68, 8 ); - psSHP->adBoundsMin[2] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 76 ); - memcpy( &dValue, pabyBuf + 76, 8 ); - psSHP->adBoundsMax[2] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 84 ); /* z */ - memcpy( &dValue, pabyBuf + 84, 8 ); - psSHP->adBoundsMin[3] = dValue; - - if ( bBigEndian ) SwapWord( 8, pabyBuf + 92 ); - memcpy( &dValue, pabyBuf + 92, 8 ); - psSHP->adBoundsMax[3] = dValue; - - free( pabyBuf ); - - /* -------------------------------------------------------------------- */ - /* Read the .shx file to get the offsets to each record in */ - /* the .shp file. */ - /* -------------------------------------------------------------------- */ - psSHP->nMaxRecords = psSHP->nRecords; - - psSHP->panRecOffset = - ( int * ) malloc( sizeof( int ) * MAX( 1, psSHP->nMaxRecords ) ); - psSHP->panRecSize = - ( int * ) malloc( sizeof( int ) * MAX( 1, psSHP->nMaxRecords ) ); - - pabyBuf = ( uchar * ) malloc( 8 * MAX( 1, psSHP->nRecords ) ); - fread( pabyBuf, 8, psSHP->nRecords, psSHP->fpSHX ); - - for ( i = 0; i < psSHP->nRecords; i++ ) - { - int32 nOffset, nLength; - - memcpy( &nOffset, pabyBuf + i * 8, 4 ); - if ( !bBigEndian ) SwapWord( 4, &nOffset ); - - memcpy( &nLength, pabyBuf + i * 8 + 4, 4 ); - if ( !bBigEndian ) SwapWord( 4, &nLength ); - - psSHP->panRecOffset[i] = nOffset * 2; - psSHP->panRecSize[i] = nLength * 2; - } - free( pabyBuf ); - - return( psSHP ); -} - -/************************************************************************/ -/* SHPClose() */ -/* */ -/* Close the .shp and .shx files. */ -/************************************************************************/ - -void SHPAPI_CALL -SHPClose( SHPHandle psSHP ) - -{ - /* -------------------------------------------------------------------- */ - /* Update the header if we have modified anything. */ - /* -------------------------------------------------------------------- */ - if ( psSHP->bUpdated ) - { - SHPWriteHeader( psSHP ); - } - - /* -------------------------------------------------------------------- */ - /* Free all resources, and close files. */ - /* -------------------------------------------------------------------- */ - free( psSHP->panRecOffset ); - free( psSHP->panRecSize ); - - fclose( psSHP->fpSHX ); - fclose( psSHP->fpSHP ); - - if ( psSHP->pabyRec != NULL ) - { - free( psSHP->pabyRec ); - } - - free( psSHP ); -} - -/************************************************************************/ -/* SHPGetInfo() */ -/* */ -/* Fetch general information about the shape file. */ -/************************************************************************/ - -void SHPAPI_CALL -SHPGetInfo( SHPHandle psSHP, int * pnEntities, int * pnShapeType, - double * padfMinBound, double * padfMaxBound ) - -{ - int i; - - if ( pnEntities != NULL ) - *pnEntities = psSHP->nRecords; - - if ( pnShapeType != NULL ) - *pnShapeType = psSHP->nShapeType; - - for ( i = 0; i < 4; i++ ) - { - if ( padfMinBound != NULL ) - padfMinBound[i] = psSHP->adBoundsMin[i]; - if ( padfMaxBound != NULL ) - padfMaxBound[i] = psSHP->adBoundsMax[i]; - } -} - -/************************************************************************/ -/* SHPCreate() */ -/* */ -/* Create a new shape file and return a handle to the open */ -/* shape file with read/write access. */ -/************************************************************************/ - -SHPHandle SHPAPI_CALL -SHPCreate( const char * pszLayer, int nShapeType ) - -{ - char *pszBasename, *pszFullname; - int i; - FILE *fpSHP, *fpSHX; - uchar abyHeader[100]; - int32 i32; - double dValue; - - /* -------------------------------------------------------------------- */ - /* Establish the byte order on this system. */ - /* -------------------------------------------------------------------- */ - i = 1; - if ( *(( uchar * ) &i ) == 1 ) - bBigEndian = FALSE; - else - bBigEndian = TRUE; - - /* -------------------------------------------------------------------- */ - /* Compute the base (layer) name. If there is any extension */ - /* on the passed in filename we will strip it off. */ - /* -------------------------------------------------------------------- */ - pszBasename = ( char * ) malloc( strlen( pszLayer ) + 5 ); - strcpy( pszBasename, pszLayer ); - for ( i = strlen( pszBasename ) - 1; - i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/' - && pszBasename[i] != '\\'; - i-- ) {} - - if ( pszBasename[i] == '.' ) - pszBasename[i] = '\0'; - - /* -------------------------------------------------------------------- */ - /* Open the two files so we can write their headers. */ - /* -------------------------------------------------------------------- */ - pszFullname = ( char * ) malloc( strlen( pszBasename ) + 5 ); - sprintf( pszFullname, "%s.shp", pszBasename ); - fpSHP = fopen( pszFullname, "wb" ); - if ( fpSHP == NULL ) - { - free( pszBasename ); - free( pszFullname ); - return NULL; - } - - sprintf( pszFullname, "%s.shx", pszBasename ); - fpSHX = fopen( pszFullname, "wb" ); - if ( fpSHX == NULL ) - { - free( pszBasename ); - free( pszFullname ); - fclose( fpSHP ); - return( NULL ); - } - - free( pszFullname ); - free( pszBasename ); - - /* -------------------------------------------------------------------- */ - /* Prepare header block for .shp file. */ - /* -------------------------------------------------------------------- */ - for ( i = 0; i < 100; i++ ) - abyHeader[i] = 0; - - abyHeader[2] = 0x27; /* magic cookie */ - abyHeader[3] = 0x0a; - - i32 = 50; /* file size */ - ByteCopy( &i32, abyHeader + 24, 4 ); - if ( !bBigEndian ) SwapWord( 4, abyHeader + 24 ); - - i32 = 1000; /* version */ - ByteCopy( &i32, abyHeader + 28, 4 ); - if ( bBigEndian ) SwapWord( 4, abyHeader + 28 ); - - i32 = nShapeType; /* shape type */ - ByteCopy( &i32, abyHeader + 32, 4 ); - if ( bBigEndian ) SwapWord( 4, abyHeader + 32 ); - - dValue = 0.0; /* set bounds */ - ByteCopy( &dValue, abyHeader + 36, 8 ); - ByteCopy( &dValue, abyHeader + 44, 8 ); - ByteCopy( &dValue, abyHeader + 52, 8 ); - ByteCopy( &dValue, abyHeader + 60, 8 ); - - /* -------------------------------------------------------------------- */ - /* Write .shp file header. */ - /* -------------------------------------------------------------------- */ - fwrite( abyHeader, 100, 1, fpSHP ); - - /* -------------------------------------------------------------------- */ - /* Prepare, and write .shx file header. */ - /* -------------------------------------------------------------------- */ - i32 = 50; /* file size */ - ByteCopy( &i32, abyHeader + 24, 4 ); - if ( !bBigEndian ) SwapWord( 4, abyHeader + 24 ); - - fwrite( abyHeader, 100, 1, fpSHX ); - - /* -------------------------------------------------------------------- */ - /* Close the files, and then open them as regular existing files. */ - /* -------------------------------------------------------------------- */ - fclose( fpSHP ); - fclose( fpSHX ); - - return( SHPOpen( pszLayer, "r+b" ) ); -} - -/************************************************************************/ -/* _SHPSetBounds() */ -/* */ -/* Compute a bounds rectangle for a shape, and set it into the */ -/* indicated location in the record. */ -/************************************************************************/ - -static void _SHPSetBounds( uchar * pabyRec, SHPObject * psShape ) - -{ - ByteCopy( &( psShape->dfXMin ), pabyRec + 0, 8 ); - ByteCopy( &( psShape->dfYMin ), pabyRec + 8, 8 ); - ByteCopy( &( psShape->dfXMax ), pabyRec + 16, 8 ); - ByteCopy( &( psShape->dfYMax ), pabyRec + 24, 8 ); - - if ( bBigEndian ) - { - SwapWord( 8, pabyRec + 0 ); - SwapWord( 8, pabyRec + 8 ); - SwapWord( 8, pabyRec + 16 ); - SwapWord( 8, pabyRec + 24 ); - } -} - -/************************************************************************/ -/* SHPComputeExtents() */ -/* */ -/* Recompute the extents of a shape. Automatically done by */ -/* SHPCreateObject(). */ -/************************************************************************/ - -void SHPAPI_CALL -SHPComputeExtents( SHPObject * psObject ) - -{ - int i; - - /* -------------------------------------------------------------------- */ - /* Build extents for this object. */ - /* -------------------------------------------------------------------- */ - if ( psObject->nVertices > 0 ) - { - psObject->dfXMin = psObject->dfXMax = psObject->padfX[0]; - psObject->dfYMin = psObject->dfYMax = psObject->padfY[0]; - psObject->dfZMin = psObject->dfZMax = psObject->padfZ[0]; - psObject->dfMMin = psObject->dfMMax = psObject->padfM[0]; - } - - for ( i = 0; i < psObject->nVertices; i++ ) - { - psObject->dfXMin = MIN( psObject->dfXMin, psObject->padfX[i] ); - psObject->dfYMin = MIN( psObject->dfYMin, psObject->padfY[i] ); - psObject->dfZMin = MIN( psObject->dfZMin, psObject->padfZ[i] ); - psObject->dfMMin = MIN( psObject->dfMMin, psObject->padfM[i] ); - - psObject->dfXMax = MAX( psObject->dfXMax, psObject->padfX[i] ); - psObject->dfYMax = MAX( psObject->dfYMax, psObject->padfY[i] ); - psObject->dfZMax = MAX( psObject->dfZMax, psObject->padfZ[i] ); - psObject->dfMMax = MAX( psObject->dfMMax, psObject->padfM[i] ); - } -} - -/************************************************************************/ -/* SHPCreateObject() */ -/* */ -/* Create a shape object. It should be freed with */ -/* SHPDestroyObject(). */ -/************************************************************************/ - -SHPObject SHPAPI_CALL1( * ) -SHPCreateObject( int nSHPType, int nShapeId, int nParts, - int * panPartStart, int * panPartType, - int nVertices, double * padfX, double * padfY, - double * padfZ, double * padfM ) - -{ - SHPObject *psObject; - int i, bHasM, bHasZ; - - psObject = ( SHPObject * ) calloc( 1, sizeof( SHPObject ) ); - psObject->nSHPType = nSHPType; - psObject->nShapeId = nShapeId; - - /* -------------------------------------------------------------------- */ - /* Establish whether this shape type has M, and Z values. */ - /* -------------------------------------------------------------------- */ - if ( nSHPType == SHPT_ARCM - || nSHPType == SHPT_POINTM - || nSHPType == SHPT_POLYGONM - || nSHPType == SHPT_MULTIPOINTM ) - { - bHasM = TRUE; - bHasZ = FALSE; - } - else if ( nSHPType == SHPT_ARCZ - || nSHPType == SHPT_POINTZ - || nSHPType == SHPT_POLYGONZ - || nSHPType == SHPT_MULTIPOINTZ - || nSHPType == SHPT_MULTIPATCH ) - { - bHasM = TRUE; - bHasZ = TRUE; - } - else - { - bHasM = FALSE; - bHasZ = FALSE; - } - - /* -------------------------------------------------------------------- */ - /* Capture parts. Note that part type is optional, and */ - /* defaults to ring. */ - /* -------------------------------------------------------------------- */ - if ( nSHPType == SHPT_ARC || nSHPType == SHPT_POLYGON - || nSHPType == SHPT_ARCM || nSHPType == SHPT_POLYGONM - || nSHPType == SHPT_ARCZ || nSHPType == SHPT_POLYGONZ - || nSHPType == SHPT_MULTIPATCH ) - { - psObject->nParts = MAX( 1, nParts ); - - psObject->panPartStart = ( int * ) - malloc( sizeof( int ) * psObject->nParts ); - psObject->panPartType = ( int * ) - malloc( sizeof( int ) * psObject->nParts ); - - psObject->panPartStart[0] = 0; - psObject->panPartType[0] = SHPP_RING; - - for ( i = 0; i < nParts; i++ ) - { - psObject->panPartStart[i] = panPartStart[i]; - if ( panPartType != NULL ) - psObject->panPartType[i] = panPartType[i]; - else - psObject->panPartType[i] = SHPP_RING; - } - } - - /* -------------------------------------------------------------------- */ - /* Capture vertices. Note that Z and M are optional, but X and */ - /* Y are not. */ - /* -------------------------------------------------------------------- */ - if ( nVertices > 0 ) - { - psObject->padfX = ( double * ) calloc( sizeof( double ), nVertices ); - psObject->padfY = ( double * ) calloc( sizeof( double ), nVertices ); - psObject->padfZ = ( double * ) calloc( sizeof( double ), nVertices ); - psObject->padfM = ( double * ) calloc( sizeof( double ), nVertices ); - - assert( padfX != NULL ); - assert( padfY != NULL ); - - for ( i = 0; i < nVertices; i++ ) - { - psObject->padfX[i] = padfX[i]; - psObject->padfY[i] = padfY[i]; - if ( padfZ != NULL && bHasZ ) - psObject->padfZ[i] = padfZ[i]; - if ( padfM != NULL && bHasM ) - psObject->padfM[i] = padfM[i]; - } - } - - /* -------------------------------------------------------------------- */ - /* Compute the extents. */ - /* -------------------------------------------------------------------- */ - psObject->nVertices = nVertices; - SHPComputeExtents( psObject ); - - return( psObject ); -} - -/************************************************************************/ -/* SHPCreateSimpleObject() */ -/* */ -/* Create a simple (common) shape object. Destroy with */ -/* SHPDestroyObject(). */ -/************************************************************************/ - -SHPObject SHPAPI_CALL1( * ) -SHPCreateSimpleObject( int nSHPType, int nVertices, - double * padfX, double * padfY, - double * padfZ ) - -{ - return( SHPCreateObject( nSHPType, -1, 0, NULL, NULL, - nVertices, padfX, padfY, padfZ, NULL ) ); -} - -/************************************************************************/ -/* SHPWriteObject() */ -/* */ -/* Write out the vertices of a new structure. Note that it is */ -/* only possible to write vertices at the end of the file. */ -/************************************************************************/ - -int SHPAPI_CALL -SHPWriteObject( SHPHandle psSHP, int nShapeId, SHPObject * psObject ) - -{ - int nRecordOffset, i, nRecordSize; - uchar *pabyRec; - int32 i32; - - psSHP->bUpdated = TRUE; - - /* -------------------------------------------------------------------- */ - /* Ensure that shape object matches the type of the file it is */ - /* being written to. */ - /* -------------------------------------------------------------------- */ - assert( psObject->nSHPType == psSHP->nShapeType - || psObject->nSHPType == SHPT_NULL ); - - /* -------------------------------------------------------------------- */ - /* Ensure that -1 is used for appends. Either blow an */ - /* assertion, or if they are disabled, set the shapeid to -1 */ - /* for appends. */ - /* -------------------------------------------------------------------- */ - assert( nShapeId == -1 - || ( nShapeId >= 0 && nShapeId < psSHP->nRecords ) ); - - if ( nShapeId != -1 && nShapeId >= psSHP->nRecords ) - nShapeId = -1; - - /* -------------------------------------------------------------------- */ - /* Add the new entity to the in memory index. */ - /* -------------------------------------------------------------------- */ - if ( nShapeId == -1 && psSHP->nRecords + 1 > psSHP->nMaxRecords ) - { - psSHP->nMaxRecords = ( int )( psSHP->nMaxRecords * 1.3 + 100 ); - - psSHP->panRecOffset = ( int * ) - SfRealloc( psSHP->panRecOffset, sizeof( int ) * psSHP->nMaxRecords ); - psSHP->panRecSize = ( int * ) - SfRealloc( psSHP->panRecSize, sizeof( int ) * psSHP->nMaxRecords ); - } - - /* -------------------------------------------------------------------- */ - /* Initialize record. */ - /* -------------------------------------------------------------------- */ - pabyRec = ( uchar * ) malloc( psObject->nVertices * 4 * sizeof( double ) - + psObject->nParts * 8 + 128 ); - - /* -------------------------------------------------------------------- */ - /* Extract vertices for a Polygon or Arc. */ - /* -------------------------------------------------------------------- */ - if ( psObject->nSHPType == SHPT_POLYGON - || psObject->nSHPType == SHPT_POLYGONZ - || psObject->nSHPType == SHPT_POLYGONM - || psObject->nSHPType == SHPT_ARC - || psObject->nSHPType == SHPT_ARCZ - || psObject->nSHPType == SHPT_ARCM - || psObject->nSHPType == SHPT_MULTIPATCH ) - { - int32 nPoints, nParts; - int i; - - nPoints = psObject->nVertices; - nParts = psObject->nParts; - - _SHPSetBounds( pabyRec + 12, psObject ); - - if ( bBigEndian ) SwapWord( 4, &nPoints ); - if ( bBigEndian ) SwapWord( 4, &nParts ); - - ByteCopy( &nPoints, pabyRec + 40 + 8, 4 ); - ByteCopy( &nParts, pabyRec + 36 + 8, 4 ); - - nRecordSize = 52; - - /* - * Write part start positions. - */ - ByteCopy( psObject->panPartStart, pabyRec + 44 + 8, - 4 * psObject->nParts ); - for ( i = 0; i < psObject->nParts; i++ ) - { - if ( bBigEndian ) SwapWord( 4, pabyRec + 44 + 8 + 4*i ); - nRecordSize += 4; - } - - /* - * Write multipatch part types if needed. - */ - if ( psObject->nSHPType == SHPT_MULTIPATCH ) - { - memcpy( pabyRec + nRecordSize, psObject->panPartType, - 4*psObject->nParts ); - for ( i = 0; i < psObject->nParts; i++ ) - { - if ( bBigEndian ) SwapWord( 4, pabyRec + nRecordSize ); - nRecordSize += 4; - } - } - - /* - * Write the (x,y) vertex values. - */ - for ( i = 0; i < psObject->nVertices; i++ ) - { - ByteCopy( psObject->padfX + i, pabyRec + nRecordSize, 8 ); - ByteCopy( psObject->padfY + i, pabyRec + nRecordSize + 8, 8 ); - - if ( bBigEndian ) - SwapWord( 8, pabyRec + nRecordSize ); - - if ( bBigEndian ) - SwapWord( 8, pabyRec + nRecordSize + 8 ); - - nRecordSize += 2 * 8; - } - - /* - * Write the Z coordinates (if any). - */ - if ( psObject->nSHPType == SHPT_POLYGONZ - || psObject->nSHPType == SHPT_ARCZ - || psObject->nSHPType == SHPT_MULTIPATCH ) - { - ByteCopy( &( psObject->dfZMin ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - ByteCopy( &( psObject->dfZMax ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - for ( i = 0; i < psObject->nVertices; i++ ) - { - ByteCopy( psObject->padfZ + i, pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - } - } - - /* - * Write the M values, if any. - */ - if ( psObject->nSHPType == SHPT_POLYGONM - || psObject->nSHPType == SHPT_ARCM -#ifndef DISABLE_MULTIPATCH_MEASURE - || psObject->nSHPType == SHPT_MULTIPATCH -#endif - || psObject->nSHPType == SHPT_POLYGONZ - || psObject->nSHPType == SHPT_ARCZ ) - { - ByteCopy( &( psObject->dfMMin ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - ByteCopy( &( psObject->dfMMax ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - for ( i = 0; i < psObject->nVertices; i++ ) - { - ByteCopy( psObject->padfM + i, pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - } - } - } - - /* -------------------------------------------------------------------- */ - /* Extract vertices for a MultiPoint. */ - /* -------------------------------------------------------------------- */ - else if ( psObject->nSHPType == SHPT_MULTIPOINT - || psObject->nSHPType == SHPT_MULTIPOINTZ - || psObject->nSHPType == SHPT_MULTIPOINTM ) - { - int32 nPoints; - int i; - - nPoints = psObject->nVertices; - - _SHPSetBounds( pabyRec + 12, psObject ); - - if ( bBigEndian ) SwapWord( 4, &nPoints ); - ByteCopy( &nPoints, pabyRec + 44, 4 ); - - for ( i = 0; i < psObject->nVertices; i++ ) - { - ByteCopy( psObject->padfX + i, pabyRec + 48 + i*16, 8 ); - ByteCopy( psObject->padfY + i, pabyRec + 48 + i*16 + 8, 8 ); - - if ( bBigEndian ) SwapWord( 8, pabyRec + 48 + i*16 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + 48 + i*16 + 8 ); - } - - nRecordSize = 48 + 16 * psObject->nVertices; - - if ( psObject->nSHPType == SHPT_MULTIPOINTZ ) - { - ByteCopy( &( psObject->dfZMin ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - ByteCopy( &( psObject->dfZMax ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - for ( i = 0; i < psObject->nVertices; i++ ) - { - ByteCopy( psObject->padfZ + i, pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - } - } - - if ( psObject->nSHPType == SHPT_MULTIPOINTZ - || psObject->nSHPType == SHPT_MULTIPOINTM ) - { - ByteCopy( &( psObject->dfMMin ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - ByteCopy( &( psObject->dfMMax ), pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - - for ( i = 0; i < psObject->nVertices; i++ ) - { - ByteCopy( psObject->padfM + i, pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - } - } - } - - /* -------------------------------------------------------------------- */ - /* Write point. */ - /* -------------------------------------------------------------------- */ - else if ( psObject->nSHPType == SHPT_POINT - || psObject->nSHPType == SHPT_POINTZ - || psObject->nSHPType == SHPT_POINTM ) - { - ByteCopy( psObject->padfX, pabyRec + 12, 8 ); - ByteCopy( psObject->padfY, pabyRec + 20, 8 ); - - if ( bBigEndian ) SwapWord( 8, pabyRec + 12 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + 20 ); - - nRecordSize = 28; - - if ( psObject->nSHPType == SHPT_POINTZ ) - { - ByteCopy( psObject->padfZ, pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - } - - if ( psObject->nSHPType == SHPT_POINTZ - || psObject->nSHPType == SHPT_POINTM ) - { - ByteCopy( psObject->padfM, pabyRec + nRecordSize, 8 ); - if ( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize ); - nRecordSize += 8; - } - } - - /* -------------------------------------------------------------------- */ - /* Not much to do for null geometries. */ - /* -------------------------------------------------------------------- */ - else if ( psObject->nSHPType == SHPT_NULL ) - { - nRecordSize = 12; - } - - else - { - /* unknown type */ - assert( FALSE ); - } - - /* -------------------------------------------------------------------- */ - /* Establish where we are going to put this record. If we are */ - /* rewriting and existing record, and it will fit, then put it */ - /* back where the original came from. Otherwise write at the end. */ - /* -------------------------------------------------------------------- */ - if ( nShapeId == -1 || psSHP->panRecSize[nShapeId] < nRecordSize - 8 ) - { - if ( nShapeId == -1 ) - nShapeId = psSHP->nRecords++; - - psSHP->panRecOffset[nShapeId] = nRecordOffset = psSHP->nFileSize; - psSHP->panRecSize[nShapeId] = nRecordSize - 8; - psSHP->nFileSize += nRecordSize; - } - else - { - nRecordOffset = psSHP->panRecOffset[nShapeId]; - } - - /* -------------------------------------------------------------------- */ - /* Set the shape type, record number, and record size. */ - /* -------------------------------------------------------------------- */ - i32 = nShapeId + 1; /* record # */ - if ( !bBigEndian ) SwapWord( 4, &i32 ); - ByteCopy( &i32, pabyRec, 4 ); - - i32 = ( nRecordSize - 8 ) / 2; /* record size */ - if ( !bBigEndian ) SwapWord( 4, &i32 ); - ByteCopy( &i32, pabyRec + 4, 4 ); - - i32 = psObject->nSHPType; /* shape type */ - if ( bBigEndian ) SwapWord( 4, &i32 ); - ByteCopy( &i32, pabyRec + 8, 4 ); - - /* -------------------------------------------------------------------- */ - /* Write out record. */ - /* -------------------------------------------------------------------- */ - if ( fseek( psSHP->fpSHP, nRecordOffset, 0 ) != 0 - || fwrite( pabyRec, nRecordSize, 1, psSHP->fpSHP ) < 1 ) - { - printf( "Error in fseek() or fwrite().\n" ); - free( pabyRec ); - return -1; - } - - free( pabyRec ); - - /* -------------------------------------------------------------------- */ - /* Expand file wide bounds based on this shape. */ - /* -------------------------------------------------------------------- */ - if ( psSHP->adBoundsMin[0] == 0.0 - && psSHP->adBoundsMax[0] == 0.0 - && psSHP->adBoundsMin[1] == 0.0 - && psSHP->adBoundsMax[1] == 0.0 - && psObject->nSHPType != SHPT_NULL ) - { - psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = psObject->padfX[0]; - psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = psObject->padfY[0]; - psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = psObject->padfZ[0]; - psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = psObject->padfM[0]; - } - - for ( i = 0; i < psObject->nVertices; i++ ) - { - psSHP->adBoundsMin[0] = MIN( psSHP->adBoundsMin[0], psObject->padfX[i] ); - psSHP->adBoundsMin[1] = MIN( psSHP->adBoundsMin[1], psObject->padfY[i] ); - psSHP->adBoundsMin[2] = MIN( psSHP->adBoundsMin[2], psObject->padfZ[i] ); - psSHP->adBoundsMin[3] = MIN( psSHP->adBoundsMin[3], psObject->padfM[i] ); - psSHP->adBoundsMax[0] = MAX( psSHP->adBoundsMax[0], psObject->padfX[i] ); - psSHP->adBoundsMax[1] = MAX( psSHP->adBoundsMax[1], psObject->padfY[i] ); - psSHP->adBoundsMax[2] = MAX( psSHP->adBoundsMax[2], psObject->padfZ[i] ); - psSHP->adBoundsMax[3] = MAX( psSHP->adBoundsMax[3], psObject->padfM[i] ); - } - - return( nShapeId ); -} - -/************************************************************************/ -/* SHPReadObject() */ -/* */ -/* Read the vertices, parts, and other non-attribute information */ -/* for one shape. */ -/************************************************************************/ - -SHPObject SHPAPI_CALL1( * ) -SHPReadObject( SHPHandle psSHP, int hEntity ) - -{ - SHPObject *psShape; - - /* -------------------------------------------------------------------- */ - /* Validate the record/entity number. */ - /* -------------------------------------------------------------------- */ - if ( hEntity < 0 || hEntity >= psSHP->nRecords ) - return( NULL ); - - /* -------------------------------------------------------------------- */ - /* Ensure our record buffer is large enough. */ - /* -------------------------------------------------------------------- */ - if ( psSHP->panRecSize[hEntity] + 8 > psSHP->nBufSize ) - { - psSHP->nBufSize = psSHP->panRecSize[hEntity] + 8; - psSHP->pabyRec = ( uchar * ) SfRealloc( psSHP->pabyRec, psSHP->nBufSize ); - } - - /* -------------------------------------------------------------------- */ - /* Read the record. */ - /* -------------------------------------------------------------------- */ - fseek( psSHP->fpSHP, psSHP->panRecOffset[hEntity], 0 ); - fread( psSHP->pabyRec, psSHP->panRecSize[hEntity] + 8, 1, psSHP->fpSHP ); - - /* -------------------------------------------------------------------- */ - /* Allocate and minimally initialize the object. */ - /* -------------------------------------------------------------------- */ - psShape = ( SHPObject * ) calloc( 1, sizeof( SHPObject ) ); - psShape->nShapeId = hEntity; - - memcpy( &psShape->nSHPType, psSHP->pabyRec + 8, 4 ); - if ( bBigEndian ) SwapWord( 4, &( psShape->nSHPType ) ); - - /* ==================================================================== */ - /* Extract vertices for a Polygon or Arc. */ - /* ==================================================================== */ - if ( psShape->nSHPType == SHPT_POLYGON || psShape->nSHPType == SHPT_ARC - || psShape->nSHPType == SHPT_POLYGONZ - || psShape->nSHPType == SHPT_POLYGONM - || psShape->nSHPType == SHPT_ARCZ - || psShape->nSHPType == SHPT_ARCM - || psShape->nSHPType == SHPT_MULTIPATCH ) - { - int32 nPoints, nParts; - int i, nOffset; - - /* -------------------------------------------------------------------- */ - /* Get the X/Y bounds. */ - /* -------------------------------------------------------------------- */ - memcpy( &( psShape->dfXMin ), psSHP->pabyRec + 8 + 4, 8 ); - memcpy( &( psShape->dfYMin ), psSHP->pabyRec + 8 + 12, 8 ); - memcpy( &( psShape->dfXMax ), psSHP->pabyRec + 8 + 20, 8 ); - memcpy( &( psShape->dfYMax ), psSHP->pabyRec + 8 + 28, 8 ); - - if ( bBigEndian ) SwapWord( 8, &( psShape->dfXMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfYMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfXMax ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfYMax ) ); - - /* -------------------------------------------------------------------- */ - /* Extract part/point count, and build vertex and part arrays */ - /* to proper size. */ - /* -------------------------------------------------------------------- */ - memcpy( &nPoints, psSHP->pabyRec + 40 + 8, 4 ); - memcpy( &nParts, psSHP->pabyRec + 36 + 8, 4 ); - - if ( bBigEndian ) SwapWord( 4, &nPoints ); - if ( bBigEndian ) SwapWord( 4, &nParts ); - - psShape->nVertices = nPoints; - psShape->padfX = ( double * ) calloc( nPoints, sizeof( double ) ); - psShape->padfY = ( double * ) calloc( nPoints, sizeof( double ) ); - psShape->padfZ = ( double * ) calloc( nPoints, sizeof( double ) ); - psShape->padfM = ( double * ) calloc( nPoints, sizeof( double ) ); - - psShape->nParts = nParts; - psShape->panPartStart = ( int * ) calloc( nParts, sizeof( int ) ); - psShape->panPartType = ( int * ) calloc( nParts, sizeof( int ) ); - - for ( i = 0; i < nParts; i++ ) - psShape->panPartType[i] = SHPP_RING; - - /* -------------------------------------------------------------------- */ - /* Copy out the part array from the record. */ - /* -------------------------------------------------------------------- */ - memcpy( psShape->panPartStart, psSHP->pabyRec + 44 + 8, 4 * nParts ); - for ( i = 0; i < nParts; i++ ) - { - if ( bBigEndian ) SwapWord( 4, psShape->panPartStart + i ); - } - - nOffset = 44 + 8 + 4 * nParts; - - /* -------------------------------------------------------------------- */ - /* If this is a multipatch, we will also have parts types. */ - /* -------------------------------------------------------------------- */ - if ( psShape->nSHPType == SHPT_MULTIPATCH ) - { - memcpy( psShape->panPartType, psSHP->pabyRec + nOffset, 4*nParts ); - for ( i = 0; i < nParts; i++ ) - { - if ( bBigEndian ) SwapWord( 4, psShape->panPartType + i ); - } - - nOffset += 4 * nParts; - } - - /* -------------------------------------------------------------------- */ - /* Copy out the vertices from the record. */ - /* -------------------------------------------------------------------- */ - for ( i = 0; i < nPoints; i++ ) - { - memcpy( psShape->padfX + i, - psSHP->pabyRec + nOffset + i * 16, - 8 ); - - memcpy( psShape->padfY + i, - psSHP->pabyRec + nOffset + i * 16 + 8, - 8 ); - - if ( bBigEndian ) SwapWord( 8, psShape->padfX + i ); - if ( bBigEndian ) SwapWord( 8, psShape->padfY + i ); - } - - nOffset += 16 * nPoints; - - /* -------------------------------------------------------------------- */ - /* If we have a Z coordinate, collect that now. */ - /* -------------------------------------------------------------------- */ - if ( psShape->nSHPType == SHPT_POLYGONZ - || psShape->nSHPType == SHPT_ARCZ - || psShape->nSHPType == SHPT_MULTIPATCH ) - { - memcpy( &( psShape->dfZMin ), psSHP->pabyRec + nOffset, 8 ); - memcpy( &( psShape->dfZMax ), psSHP->pabyRec + nOffset + 8, 8 ); - - if ( bBigEndian ) SwapWord( 8, &( psShape->dfZMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfZMax ) ); - - for ( i = 0; i < nPoints; i++ ) - { - memcpy( psShape->padfZ + i, - psSHP->pabyRec + nOffset + 16 + i*8, 8 ); - if ( bBigEndian ) SwapWord( 8, psShape->padfZ + i ); - } - - nOffset += 16 + 8 * nPoints; - } - - /* -------------------------------------------------------------------- */ - /* If we have a M measure value, then read it now. We assume */ - /* that the measure can be present for any shape if the size is */ - /* big enough, but really it will only occur for the Z shapes */ - /* (options), and the M shapes. */ - /* -------------------------------------------------------------------- */ - if ( psSHP->panRecSize[hEntity] + 8 >= nOffset + 16 + 8*nPoints ) - { - memcpy( &( psShape->dfMMin ), psSHP->pabyRec + nOffset, 8 ); - memcpy( &( psShape->dfMMax ), psSHP->pabyRec + nOffset + 8, 8 ); - - if ( bBigEndian ) SwapWord( 8, &( psShape->dfMMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfMMax ) ); - - for ( i = 0; i < nPoints; i++ ) - { - memcpy( psShape->padfM + i, - psSHP->pabyRec + nOffset + 16 + i*8, 8 ); - if ( bBigEndian ) SwapWord( 8, psShape->padfM + i ); - } - } - - } - - /* ==================================================================== */ - /* Extract vertices for a MultiPoint. */ - /* ==================================================================== */ - else if ( psShape->nSHPType == SHPT_MULTIPOINT - || psShape->nSHPType == SHPT_MULTIPOINTM - || psShape->nSHPType == SHPT_MULTIPOINTZ ) - { - int32 nPoints; - int i, nOffset; - - memcpy( &nPoints, psSHP->pabyRec + 44, 4 ); - if ( bBigEndian ) SwapWord( 4, &nPoints ); - - psShape->nVertices = nPoints; - psShape->padfX = ( double * ) calloc( nPoints, sizeof( double ) ); - psShape->padfY = ( double * ) calloc( nPoints, sizeof( double ) ); - psShape->padfZ = ( double * ) calloc( nPoints, sizeof( double ) ); - psShape->padfM = ( double * ) calloc( nPoints, sizeof( double ) ); - - for ( i = 0; i < nPoints; i++ ) - { - memcpy( psShape->padfX + i, psSHP->pabyRec + 48 + 16 * i, 8 ); - memcpy( psShape->padfY + i, psSHP->pabyRec + 48 + 16 * i + 8, 8 ); - - if ( bBigEndian ) SwapWord( 8, psShape->padfX + i ); - if ( bBigEndian ) SwapWord( 8, psShape->padfY + i ); - } - - nOffset = 48 + 16 * nPoints; - - /* -------------------------------------------------------------------- */ - /* Get the X/Y bounds. */ - /* -------------------------------------------------------------------- */ - memcpy( &( psShape->dfXMin ), psSHP->pabyRec + 8 + 4, 8 ); - memcpy( &( psShape->dfYMin ), psSHP->pabyRec + 8 + 12, 8 ); - memcpy( &( psShape->dfXMax ), psSHP->pabyRec + 8 + 20, 8 ); - memcpy( &( psShape->dfYMax ), psSHP->pabyRec + 8 + 28, 8 ); - - if ( bBigEndian ) SwapWord( 8, &( psShape->dfXMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfYMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfXMax ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfYMax ) ); - - /* -------------------------------------------------------------------- */ - /* If we have a Z coordinate, collect that now. */ - /* -------------------------------------------------------------------- */ - if ( psShape->nSHPType == SHPT_MULTIPOINTZ ) - { - memcpy( &( psShape->dfZMin ), psSHP->pabyRec + nOffset, 8 ); - memcpy( &( psShape->dfZMax ), psSHP->pabyRec + nOffset + 8, 8 ); - - if ( bBigEndian ) SwapWord( 8, &( psShape->dfZMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfZMax ) ); - - for ( i = 0; i < nPoints; i++ ) - { - memcpy( psShape->padfZ + i, - psSHP->pabyRec + nOffset + 16 + i*8, 8 ); - if ( bBigEndian ) SwapWord( 8, psShape->padfZ + i ); - } - - nOffset += 16 + 8 * nPoints; - } - - /* -------------------------------------------------------------------- */ - /* If we have a M measure value, then read it now. We assume */ - /* that the measure can be present for any shape if the size is */ - /* big enough, but really it will only occur for the Z shapes */ - /* (options), and the M shapes. */ - /* -------------------------------------------------------------------- */ - if ( psSHP->panRecSize[hEntity] + 8 >= nOffset + 16 + 8*nPoints ) - { - memcpy( &( psShape->dfMMin ), psSHP->pabyRec + nOffset, 8 ); - memcpy( &( psShape->dfMMax ), psSHP->pabyRec + nOffset + 8, 8 ); - - if ( bBigEndian ) SwapWord( 8, &( psShape->dfMMin ) ); - if ( bBigEndian ) SwapWord( 8, &( psShape->dfMMax ) ); - - for ( i = 0; i < nPoints; i++ ) - { - memcpy( psShape->padfM + i, - psSHP->pabyRec + nOffset + 16 + i*8, 8 ); - if ( bBigEndian ) SwapWord( 8, psShape->padfM + i ); - } - } - } - - /* ==================================================================== */ - /* Extract vertices for a point. */ - /* ==================================================================== */ - else if ( psShape->nSHPType == SHPT_POINT - || psShape->nSHPType == SHPT_POINTM - || psShape->nSHPType == SHPT_POINTZ ) - { - int nOffset; - - psShape->nVertices = 1; - psShape->padfX = ( double * ) calloc( 1, sizeof( double ) ); - psShape->padfY = ( double * ) calloc( 1, sizeof( double ) ); - psShape->padfZ = ( double * ) calloc( 1, sizeof( double ) ); - psShape->padfM = ( double * ) calloc( 1, sizeof( double ) ); - - memcpy( psShape->padfX, psSHP->pabyRec + 12, 8 ); - memcpy( psShape->padfY, psSHP->pabyRec + 20, 8 ); - - if ( bBigEndian ) SwapWord( 8, psShape->padfX ); - if ( bBigEndian ) SwapWord( 8, psShape->padfY ); - - nOffset = 20 + 8; - - /* -------------------------------------------------------------------- */ - /* If we have a Z coordinate, collect that now. */ - /* -------------------------------------------------------------------- */ - if ( psShape->nSHPType == SHPT_POINTZ ) - { - memcpy( psShape->padfZ, psSHP->pabyRec + nOffset, 8 ); - - if ( bBigEndian ) SwapWord( 8, psShape->padfZ ); - - nOffset += 8; - } - - /* -------------------------------------------------------------------- */ - /* If we have a M measure value, then read it now. We assume */ - /* that the measure can be present for any shape if the size is */ - /* big enough, but really it will only occur for the Z shapes */ - /* (options), and the M shapes. */ - /* -------------------------------------------------------------------- */ - if ( psSHP->panRecSize[hEntity] + 8 >= nOffset + 8 ) - { - memcpy( psShape->padfM, psSHP->pabyRec + nOffset, 8 ); - - if ( bBigEndian ) SwapWord( 8, psShape->padfM ); - } - - /* -------------------------------------------------------------------- */ - /* Since no extents are supplied in the record, we will apply */ - /* them from the single vertex. */ - /* -------------------------------------------------------------------- */ - psShape->dfXMin = psShape->dfXMax = psShape->padfX[0]; - psShape->dfYMin = psShape->dfYMax = psShape->padfY[0]; - psShape->dfZMin = psShape->dfZMax = psShape->padfZ[0]; - psShape->dfMMin = psShape->dfMMax = psShape->padfM[0]; - } - - return( psShape ); -} - -/************************************************************************/ -/* SHPTypeName() */ -/************************************************************************/ - -const char SHPAPI_CALL1( * ) -SHPTypeName( int nSHPType ) - -{ - switch ( nSHPType ) - { - case SHPT_NULL: - return "NullShape"; - - case SHPT_POINT: - return "Point"; - - case SHPT_ARC: - return "Arc"; - - case SHPT_POLYGON: - return "Polygon"; - - case SHPT_MULTIPOINT: - return "MultiPoint"; - - case SHPT_POINTZ: - return "PointZ"; - - case SHPT_ARCZ: - return "ArcZ"; - - case SHPT_POLYGONZ: - return "PolygonZ"; - - case SHPT_MULTIPOINTZ: - return "MultiPointZ"; - - case SHPT_POINTM: - return "PointM"; - - case SHPT_ARCM: - return "ArcM"; - - case SHPT_POLYGONM: - return "PolygonM"; - - case SHPT_MULTIPOINTM: - return "MultiPointM"; - - case SHPT_MULTIPATCH: - return "MultiPatch"; - - default: - return "UnknownShapeType"; - } -} - -/************************************************************************/ -/* SHPPartTypeName() */ -/************************************************************************/ - -const char SHPAPI_CALL1( * ) -SHPPartTypeName( int nPartType ) - -{ - switch ( nPartType ) - { - case SHPP_TRISTRIP: - return "TriangleStrip"; - - case SHPP_TRIFAN: - return "TriangleFan"; - - case SHPP_OUTERRING: - return "OuterRing"; - - case SHPP_INNERRING: - return "InnerRing"; - - case SHPP_FIRSTRING: - return "FirstRing"; - - case SHPP_RING: - return "Ring"; - - default: - return "UnknownPartType"; - } -} - -/************************************************************************/ -/* SHPDestroyObject() */ -/************************************************************************/ - -void SHPAPI_CALL -SHPDestroyObject( SHPObject * psShape ) - -{ - if ( psShape == NULL ) - return; - - if ( psShape->padfX != NULL ) - free( psShape->padfX ); - if ( psShape->padfY != NULL ) - free( psShape->padfY ); - if ( psShape->padfZ != NULL ) - free( psShape->padfZ ); - if ( psShape->padfM != NULL ) - free( psShape->padfM ); - - if ( psShape->panPartStart != NULL ) - free( psShape->panPartStart ); - if ( psShape->panPartType != NULL ) - free( psShape->panPartType ); - - free( psShape ); -} - -/************************************************************************/ -/* SHPRewindObject() */ -/* */ -/* Reset the winding of polygon objects to adhere to the */ -/* specification. */ -/************************************************************************/ - -int SHPAPI_CALL -SHPRewindObject( SHPHandle hSHP, SHPObject * psObject ) - -{ - int iOpRing, bAltered = 0; - - /* -------------------------------------------------------------------- */ - /* Do nothing if this is not a polygon object. */ - /* -------------------------------------------------------------------- */ - if ( psObject->nSHPType != SHPT_POLYGON - && psObject->nSHPType != SHPT_POLYGONZ - && psObject->nSHPType != SHPT_POLYGONM ) - return 0; - - /* -------------------------------------------------------------------- */ - /* Process each of the rings. */ - /* -------------------------------------------------------------------- */ - for ( iOpRing = 0; iOpRing < psObject->nParts; iOpRing++ ) - { - int bInner, iVert, nVertCount, nVertStart, iCheckRing; - double dfSum, dfTestX, dfTestY; - - /* -------------------------------------------------------------------- */ - /* Determine if this ring is an inner ring or an outer ring */ - /* relative to all the other rings. For now we assume the */ - /* first ring is outer and all others are inner, but eventually */ - /* we need to fix this to handle multiple island polygons and */ - /* unordered sets of rings. */ - /* -------------------------------------------------------------------- */ - dfTestX = psObject->padfX[psObject->panPartStart[iOpRing]]; - dfTestY = psObject->padfY[psObject->panPartStart[iOpRing]]; - - bInner = FALSE; - for ( iCheckRing = 0; iCheckRing < psObject->nParts; iCheckRing++ ) - { - int iEdge; - - if ( iCheckRing == iOpRing ) - continue; - - nVertStart = psObject->panPartStart[iCheckRing]; - - if ( iCheckRing == psObject->nParts - 1 ) - nVertCount = psObject->nVertices - - psObject->panPartStart[iCheckRing]; - else - nVertCount = psObject->panPartStart[iCheckRing+1] - - psObject->panPartStart[iCheckRing]; - - for ( iEdge = 0; iEdge < nVertCount; iEdge++ ) - { - int iNext; - - if ( iEdge < nVertCount - 1 ) - iNext = iEdge + 1; - else - iNext = 0; - - if (( psObject->padfY[iEdge+nVertStart] < dfTestY - && psObject->padfY[iNext+nVertStart] >= dfTestY ) - || ( psObject->padfY[iNext+nVertStart] < dfTestY - && psObject->padfY[iEdge+nVertStart] >= dfTestY ) ) - { - if ( psObject->padfX[iEdge+nVertStart] - + ( dfTestY - psObject->padfY[iEdge+nVertStart] ) - / ( psObject->padfY[iNext+nVertStart] - - psObject->padfY[iEdge+nVertStart] ) - *( psObject->padfX[iNext+nVertStart] - - psObject->padfX[iEdge+nVertStart] ) < dfTestX ) - bInner = !bInner; - } - } - } - - /* -------------------------------------------------------------------- */ - /* Determine the current order of this ring so we will know if */ - /* it has to be reversed. */ - /* -------------------------------------------------------------------- */ - nVertStart = psObject->panPartStart[iOpRing]; - - if ( iOpRing == psObject->nParts - 1 ) - nVertCount = psObject->nVertices - psObject->panPartStart[iOpRing]; - else - nVertCount = psObject->panPartStart[iOpRing+1] - - psObject->panPartStart[iOpRing]; - - dfSum = 0.0; - for ( iVert = nVertStart; iVert < nVertStart + nVertCount - 1; iVert++ ) - { - dfSum += psObject->padfX[iVert] * psObject->padfY[iVert+1] - - psObject->padfY[iVert] * psObject->padfX[iVert+1]; - } - - dfSum += psObject->padfX[iVert] * psObject->padfY[nVertStart] - - psObject->padfY[iVert] * psObject->padfX[nVertStart]; - - /* -------------------------------------------------------------------- */ - /* Reverse if necessary. */ - /* -------------------------------------------------------------------- */ - if (( dfSum < 0.0 && bInner ) || ( dfSum > 0.0 && !bInner ) ) - { - int i; - - bAltered++; - for ( i = 0; i < nVertCount / 2; i++ ) - { - double dfSaved; - - /* Swap X */ - dfSaved = psObject->padfX[nVertStart+i]; - psObject->padfX[nVertStart+i] = - psObject->padfX[nVertStart+nVertCount-i-1]; - psObject->padfX[nVertStart+nVertCount-i-1] = dfSaved; - - /* Swap Y */ - dfSaved = psObject->padfY[nVertStart+i]; - psObject->padfY[nVertStart+i] = - psObject->padfY[nVertStart+nVertCount-i-1]; - psObject->padfY[nVertStart+nVertCount-i-1] = dfSaved; - - /* Swap Z */ - if ( psObject->padfZ ) - { - dfSaved = psObject->padfZ[nVertStart+i]; - psObject->padfZ[nVertStart+i] = - psObject->padfZ[nVertStart+nVertCount-i-1]; - psObject->padfZ[nVertStart+nVertCount-i-1] = dfSaved; - } - - /* Swap M */ - if ( psObject->padfM ) - { - dfSaved = psObject->padfM[nVertStart+i]; - psObject->padfM[nVertStart+i] = - psObject->padfM[nVertStart+nVertCount-i-1]; - psObject->padfM[nVertStart+nVertCount-i-1] = dfSaved; - } - } - } - } - - return bAltered; -} diff --git a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shprewind.c b/src/plugins/dxf2shp_converter/shapelib-1.2.10/shprewind.c deleted file mode 100644 index b034972fd491..000000000000 --- a/src/plugins/dxf2shp_converter/shapelib-1.2.10/shprewind.c +++ /dev/null @@ -1,108 +0,0 @@ -/****************************************************************************** - * $Id: shprewind.c,v 1.2 2002/04/10 17:23:11 warmerda Exp $ - * - * Project: Shapelib - * Purpose: Utility to validate and reset the winding order of rings in - * polygon geometries to match the ordering required by spec. - * Author: Frank Warmerdam, warmerdam@pobox.com - * - ****************************************************************************** - * Copyright (c) 2002, Frank Warmerdam - * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see LICENSE.LGPL). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - ****************************************************************************** - * - * $Log: shprewind.c,v $ - * Revision 1.2 2002/04/10 17:23:11 warmerda - * copy from source to destination now - * - * Revision 1.1 2002/04/10 16:56:36 warmerda - * New - * - */ - -#include "shapefil.h" - -int main( int argc, char ** argv ) - -{ - SHPHandle hSHP, hSHPOut; - int nShapeType, nEntities, i, nInvalidCount = 0; - double adfMinBound[4], adfMaxBound[4]; - - /* -------------------------------------------------------------------- */ - /* Display a usage message. */ - /* -------------------------------------------------------------------- */ - if ( argc != 3 ) - { - printf( "shprewind in_shp_file out_shp_file\n" ); - exit( 1 ); - } - - /* -------------------------------------------------------------------- */ - /* Open the passed shapefile. */ - /* -------------------------------------------------------------------- */ - hSHP = SHPOpen( argv[1], "rb" ); - - if ( hSHP == NULL ) - { - printf( "Unable to open:%s\n", argv[1] ); - exit( 1 ); - } - - SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound ); - - /* -------------------------------------------------------------------- */ - /* Create output shapefile. */ - /* -------------------------------------------------------------------- */ - hSHPOut = SHPCreate( argv[2], nShapeType ); - - if ( hSHPOut == NULL ) - { - printf( "Unable to create:%s\n", argv[2] ); - exit( 1 ); - } - - /* -------------------------------------------------------------------- */ - /* Skim over the list of shapes, printing all the vertices. */ - /* -------------------------------------------------------------------- */ - for ( i = 0; i < nEntities; i++ ) - { - SHPObject *psShape; - - psShape = SHPReadObject( hSHP, i ); - if ( SHPRewindObject( hSHP, psShape ) ) - nInvalidCount++; - SHPWriteObject( hSHPOut, -1, psShape ); - SHPDestroyObject( psShape ); - } - - SHPClose( hSHP ); - SHPClose( hSHPOut ); - - printf( "%d objects rewound.\n", nInvalidCount ); - - exit( 0 ); -} From b2587b7bf33376dc2f158e145322f82b341a1922 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 24 Oct 2016 08:43:44 +1000 Subject: [PATCH 468/897] [FEATURE] Remove zonal stats plugin This is now fully exposed via processing, which is the logical place for this feature to reside. One less c++ plugin is a good thing! (marked as feature so we remember to mention this in changelog!) --- debian/qgis.install | 1 - ms-windows/osgeo4w/package.cmd | 1 - ms-windows/plugins.nsh | 1 - src/plugins/CMakeLists.txt | 1 - src/plugins/zonal_statistics/CMakeLists.txt | 62 ----- .../qgszonalstatisticsdialog.cpp | 254 ------------------ .../qgszonalstatisticsdialog.h | 60 ----- .../qgszonalstatisticsdialogbase.ui | 130 --------- .../qgszonalstatisticsplugin.cpp | 123 --------- .../qgszonalstatisticsplugin.h | 48 ---- src/plugins/zonal_statistics/raster-stats.png | Bin 733 -> 0 bytes .../zonal_statistics/zonal_statistics.qrc | 6 - 12 files changed, 687 deletions(-) delete mode 100644 src/plugins/zonal_statistics/CMakeLists.txt delete mode 100644 src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp delete mode 100644 src/plugins/zonal_statistics/qgszonalstatisticsdialog.h delete mode 100644 src/plugins/zonal_statistics/qgszonalstatisticsdialogbase.ui delete mode 100644 src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp delete mode 100644 src/plugins/zonal_statistics/qgszonalstatisticsplugin.h delete mode 100644 src/plugins/zonal_statistics/raster-stats.png delete mode 100644 src/plugins/zonal_statistics/zonal_statistics.qrc diff --git a/debian/qgis.install b/debian/qgis.install index d3b7ed2d1667..0dacd3cccec2 100644 --- a/debian/qgis.install +++ b/debian/qgis.install @@ -8,7 +8,6 @@ usr/lib/qgis/plugins/librasterterrainplugin.so usr/lib/qgis/plugins/libspatialqueryplugin.so usr/lib/qgis/plugins/libofflineeditingplugin.so usr/lib/qgis/plugins/libroadgraphplugin.so -usr/lib/qgis/plugins/libzonalstatisticsplugin.so usr/lib/qgis/plugins/libheatmapplugin.so usr/lib/qgis/plugins/libtopolplugin.so usr/lib/qgis/plugins/libgeometrycheckerplugin.so diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index cb198560e607..835c506ee819 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -394,7 +394,6 @@ tar -C %OSGEO4W_ROOT% -cjf %ARCH%/release/qgis/%PACKAGENAME%/%PACKAGENAME%-%VERS "apps/%PACKAGENAME%/plugins/roadgraphplugin.dll" ^ "apps/%PACKAGENAME%/plugins/spatialqueryplugin.dll" ^ "apps/%PACKAGENAME%/plugins/topolplugin.dll" ^ - "apps/%PACKAGENAME%/plugins/zonalstatisticsplugin.dll" ^ "apps/%PACKAGENAME%/plugins/geometrycheckerplugin.dll" ^ "apps/%PACKAGENAME%/plugins/geometrysnapperplugin.dll" ^ "apps/%PACKAGENAME%/qgis_help.exe" ^ diff --git a/ms-windows/plugins.nsh b/ms-windows/plugins.nsh index ce4bc52abc24..af154aa02388 100644 --- a/ms-windows/plugins.nsh +++ b/ms-windows/plugins.nsh @@ -22,6 +22,5 @@ WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "rasterterrainplugin WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "roadgraphplugin" "true" WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "spatialqueryplugin" "true" WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "topolplugin" "true" -WriteRegStr HKEY_CURRENT_USER "Software\QGIS\QGIS3\Plugins" "zonalstatisticsplugin" "true" ############################### reg2nsis end ################################# diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt index 1259c5e1fbca..f61d1d9044a6 100644 --- a/src/plugins/CMakeLists.txt +++ b/src/plugins/CMakeLists.txt @@ -13,7 +13,6 @@ ADD_SUBDIRECTORY(coordinate_capture) ADD_SUBDIRECTORY(evis) ADD_SUBDIRECTORY(spatialquery) ADD_SUBDIRECTORY(roadgraph) -ADD_SUBDIRECTORY(zonal_statistics) ADD_SUBDIRECTORY(georeferencer) ADD_SUBDIRECTORY(gps_importer) ADD_SUBDIRECTORY(topology) diff --git a/src/plugins/zonal_statistics/CMakeLists.txt b/src/plugins/zonal_statistics/CMakeLists.txt deleted file mode 100644 index 1a511e4399b7..000000000000 --- a/src/plugins/zonal_statistics/CMakeLists.txt +++ /dev/null @@ -1,62 +0,0 @@ -######################################################## -# Files - -SET (ZONAL_STATISTICS_SRCS - qgszonalstatisticsplugin.cpp - qgszonalstatisticsdialog.cpp -) - -SET (ZONAL_STATISTICS_UIS - qgszonalstatisticsdialogbase.ui - ) - -SET (ZONAL_STATISTICS_MOC_HDRS -qgszonalstatisticsdialog.h -qgszonalstatisticsplugin.h -) - -SET (ZONAL_STATISTICS_RCCS zonal_statistics.qrc) - -######################################################## -# Build - -QT5_WRAP_UI (ZONAL_STATISTICS_UIS_H ${ZONAL_STATISTICS_UIS}) - -QT5_WRAP_CPP (ZONAL_STATISTICS_MOC_SRCS ${ZONAL_STATISTICS_MOC_HDRS}) - -QT5_ADD_RESOURCES(ZONAL_STATISTICS_RCC_SRCS ${ZONAL_STATISTICS_RCCS}) - -ADD_LIBRARY (zonalstatisticsplugin MODULE - ${ZONAL_STATISTICS_SRCS} - ${ZONAL_STATISTICS_MOC_SRCS} - ${ZONAL_STATISTICS_RCC_SRCS} - ${ZONAL_STATISTICS_UIS_H}) - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_BINARY_DIR} - ../../core - ../../core/geometry - ../../core/raster - ../../gui - ../../analysis/vector - .. - . -) -INCLUDE_DIRECTORIES(SYSTEM - ${GDAL_INCLUDE_DIR} -) - -TARGET_LINK_LIBRARIES(zonalstatisticsplugin - qgis_analysis - qgis_core - qgis_gui -) - - -######################################################## -# Install - -INSTALL(TARGETS zonalstatisticsplugin - RUNTIME DESTINATION ${QGIS_PLUGIN_DIR} - LIBRARY DESTINATION ${QGIS_PLUGIN_DIR} - ) diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp b/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp deleted file mode 100644 index 8b4baddf188d..000000000000 --- a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.cpp +++ /dev/null @@ -1,254 +0,0 @@ -/*************************************************************************** - qgszonalstatisticsdialog.h - description - ----------------------- - begin : September 1st, 2009 - copyright : (C) 2009 by Marco Hugentobler - email : marco dot hugentobler at karto dot baug dot ethz dot ch - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgszonalstatisticsdialog.h" -#include "qgsmaplayerregistry.h" -#include "qgsrasterlayer.h" -#include "qgsrasterdataprovider.h" -#include "qgsvectordataprovider.h" -#include "qgsvectorlayer.h" -#include "qgisinterface.h" - -#include -#include - -QgsZonalStatisticsDialog::QgsZonalStatisticsDialog( QgisInterface* iface ): QDialog( iface->mainWindow() ), mIface( iface ) -{ - setupUi( this ); - - QListWidgetItem* countItem = new QListWidgetItem( tr( "Count" ), mStatsListWidget ); - countItem->setFlags( countItem->flags() | Qt::ItemIsUserCheckable ); - countItem->setCheckState( Qt::Checked ); - countItem->setData( Qt::UserRole, QgsZonalStatistics::Count ); - mStatsListWidget->addItem( countItem ); - QListWidgetItem* sumItem = new QListWidgetItem( tr( "Sum" ), mStatsListWidget ); - sumItem->setFlags( sumItem->flags() | Qt::ItemIsUserCheckable ); - sumItem->setCheckState( Qt::Checked ); - sumItem->setData( Qt::UserRole, QgsZonalStatistics::Sum ); - mStatsListWidget->addItem( sumItem ); - QListWidgetItem* meanItem = new QListWidgetItem( tr( "Mean" ), mStatsListWidget ); - meanItem->setFlags( meanItem->flags() | Qt::ItemIsUserCheckable ); - meanItem->setCheckState( Qt::Checked ); - meanItem->setData( Qt::UserRole, QgsZonalStatistics::Mean ); - mStatsListWidget->addItem( meanItem ); - QListWidgetItem* medianItem = new QListWidgetItem( tr( "Median" ), mStatsListWidget ); - medianItem->setFlags( medianItem->flags() | Qt::ItemIsUserCheckable ); - medianItem->setCheckState( Qt::Unchecked ); - medianItem->setData( Qt::UserRole, QgsZonalStatistics::Median ); - mStatsListWidget->addItem( medianItem ); - QListWidgetItem* stdevItem = new QListWidgetItem( tr( "Standard deviation" ), mStatsListWidget ); - stdevItem->setFlags( stdevItem->flags() | Qt::ItemIsUserCheckable ); - stdevItem->setCheckState( Qt::Unchecked ); - stdevItem->setData( Qt::UserRole, QgsZonalStatistics::StDev ); - mStatsListWidget->addItem( stdevItem ); - QListWidgetItem* minItem = new QListWidgetItem( tr( "Minimum" ), mStatsListWidget ); - minItem->setFlags( minItem->flags() | Qt::ItemIsUserCheckable ); - minItem->setCheckState( Qt::Checked ); - minItem->setData( Qt::UserRole, QgsZonalStatistics::Min ); - mStatsListWidget->addItem( minItem ); - QListWidgetItem* maxItem = new QListWidgetItem( tr( "Maximum" ), mStatsListWidget ); - maxItem->setFlags( maxItem->flags() | Qt::ItemIsUserCheckable ); - maxItem->setCheckState( Qt::Checked ); - maxItem->setData( Qt::UserRole, QgsZonalStatistics::Max ); - mStatsListWidget->addItem( maxItem ); - QListWidgetItem* rangeItem = new QListWidgetItem( tr( "Range" ), mStatsListWidget ); - rangeItem->setFlags( rangeItem->flags() | Qt::ItemIsUserCheckable ); - rangeItem->setCheckState( Qt::Unchecked ); - rangeItem->setData( Qt::UserRole, QgsZonalStatistics::Range ); - mStatsListWidget->addItem( rangeItem ); - QListWidgetItem* minorityItem = new QListWidgetItem( tr( "Minority" ), mStatsListWidget ); - minorityItem->setFlags( minorityItem->flags() | Qt::ItemIsUserCheckable ); - minorityItem->setCheckState( Qt::Unchecked ); - minorityItem->setData( Qt::UserRole, QgsZonalStatistics::Minority ); - mStatsListWidget->addItem( minorityItem ); - QListWidgetItem* majorityItem = new QListWidgetItem( tr( "Majority" ), mStatsListWidget ); - majorityItem->setFlags( majorityItem->flags() | Qt::ItemIsUserCheckable ); - majorityItem->setCheckState( Qt::Unchecked ); - majorityItem->setData( Qt::UserRole, QgsZonalStatistics::Majority ); - mStatsListWidget->addItem( majorityItem ); - QListWidgetItem* varietyItem = new QListWidgetItem( tr( "Variety" ), mStatsListWidget ); - varietyItem->setFlags( varietyItem->flags() | Qt::ItemIsUserCheckable ); - varietyItem->setCheckState( Qt::Unchecked ); - varietyItem->setData( Qt::UserRole, QgsZonalStatistics::Variety ); - mStatsListWidget->addItem( varietyItem ); - QSettings settings; - restoreGeometry( settings.value( QStringLiteral( "Plugin-ZonalStatistics/geometry" ) ).toByteArray() ); - - insertAvailableLayers(); - mColumnPrefixLineEdit->setText( proposeAttributePrefix() ); -} - -QgsZonalStatisticsDialog::QgsZonalStatisticsDialog(): QDialog( nullptr ), mIface( nullptr ) -{ - setupUi( this ); - - QSettings settings; - restoreGeometry( settings.value( QStringLiteral( "Plugin-ZonalStatistics/geometry" ) ).toByteArray() ); -} - -QgsZonalStatisticsDialog::~QgsZonalStatisticsDialog() -{ - QSettings settings; - settings.setValue( QStringLiteral( "Plugin-ZonalStatistics/geometry" ), saveGeometry() ); -} - -void QgsZonalStatisticsDialog::insertAvailableLayers() -{ - //insert available raster layers - //enter available layers into the combo box - QMap mapLayers = QgsMapLayerRegistry::instance()->mapLayers(); - QMap::iterator layer_it = mapLayers.begin(); - - for ( ; layer_it != mapLayers.end(); ++layer_it ) - { - QgsRasterLayer* rl = dynamic_cast( layer_it.value() ); - if ( rl ) - { - QgsRasterDataProvider* rp = rl->dataProvider(); - if ( rp && rp->name() == QLatin1String( "gdal" ) ) - { - mRasterLayerComboBox->addItem( rl->name(), QVariant( rl->id() ) ); - } - } - else - { - QgsVectorLayer* vl = dynamic_cast( layer_it.value() ); - if ( vl && vl->geometryType() == QgsWkbTypes::PolygonGeometry ) - { - QgsVectorDataProvider* provider = vl->dataProvider(); - if ( provider->capabilities() & QgsVectorDataProvider::AddAttributes ) - { - mPolygonLayerComboBox->addItem( vl->name(), QVariant( vl->id() ) ); - } - } - } - } -} - -QgsRasterLayer* QgsZonalStatisticsDialog::rasterLayer() const -{ - int index = mRasterLayerComboBox->currentIndex(); - if ( index == -1 ) - { - return nullptr; - } - QString id = mRasterLayerComboBox->itemData( index ).toString(); - QgsRasterLayer* layer = dynamic_cast( QgsMapLayerRegistry::instance()->mapLayer( id ) ); - return layer; -} - -QString QgsZonalStatisticsDialog::rasterFilePath() const -{ - QgsRasterLayer* layer = rasterLayer(); - return layer ? layer->source() : QString(); -} - -int QgsZonalStatisticsDialog::rasterBand() const -{ - return mBandComboBox->currentIndex() + 1; -} - -QgsVectorLayer* QgsZonalStatisticsDialog::polygonLayer() const -{ - int index = mPolygonLayerComboBox->currentIndex(); - if ( index == -1 ) - { - return nullptr; - } - return dynamic_cast( QgsMapLayerRegistry::instance()->mapLayer( mPolygonLayerComboBox->itemData( index ).toString() ) ); -} - -QString QgsZonalStatisticsDialog::attributePrefix() const -{ - return mColumnPrefixLineEdit->text(); -} - -QgsZonalStatistics::Statistics QgsZonalStatisticsDialog::selectedStats() const -{ - QgsZonalStatistics::Statistics stats = 0; - for ( int i = 0; i < mStatsListWidget->count(); ++i ) - { - QListWidgetItem* item = mStatsListWidget->item( i ); - if ( item->checkState() == Qt::Checked ) - { - stats |= ( QgsZonalStatistics::Statistic )item->data( Qt::UserRole ).toInt(); - } - } - return stats; -} - -QString QgsZonalStatisticsDialog::proposeAttributePrefix() const -{ - if ( !polygonLayer() ) - { - return QLatin1String( "" ); - } - - QString proposedPrefix = QLatin1String( "" ); - while ( !prefixIsValid( proposedPrefix ) ) - { - proposedPrefix.prepend( '_' ); - } - return proposedPrefix; -} - -bool QgsZonalStatisticsDialog::prefixIsValid( const QString& prefix ) const -{ - QgsVectorLayer* vl = polygonLayer(); - if ( !vl ) - { - return false; - } - QgsVectorDataProvider* dp = vl->dataProvider(); - if ( !dp ) - { - return false; - } - - QString currentFieldName; - - Q_FOREACH ( const QgsField& field, dp->fields() ) - { - currentFieldName = field.name(); - if ( currentFieldName == ( prefix + "mean" ) || currentFieldName == ( prefix + "sum" ) || currentFieldName == ( prefix + "count" ) ) - { - return false; - } - } - return true; -} - -void QgsZonalStatisticsDialog::on_mRasterLayerComboBox_currentIndexChanged( int index ) -{ - Q_UNUSED( index ); - - QgsRasterLayer* layer = rasterLayer(); - if ( !layer ) - { - mBandComboBox->setEnabled( false ); - return; - } - - mBandComboBox->setEnabled( true ); - mBandComboBox->clear(); - - int bandCountInt = layer->bandCount(); - for ( int i = 1; i <= bandCountInt; ++i ) - { - mBandComboBox->addItem( layer->bandName( i ) ); - } -} diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h b/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h deleted file mode 100644 index d85d80688a20..000000000000 --- a/src/plugins/zonal_statistics/qgszonalstatisticsdialog.h +++ /dev/null @@ -1,60 +0,0 @@ -/*************************************************************************** - qgszonalstatisticsdialog.h - description - ----------------------- - begin : September 1st, 2009 - copyright : (C) 2009 by Marco Hugentobler - email : marco dot hugentobler at karto dot baug dot ethz dot ch - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGSZONALSTATISTICSDIALOG_H -#define QGSZONALSTATISTICSDIALOG_H - -#include "ui_qgszonalstatisticsdialogbase.h" -#include "qgszonalstatistics.h" - -class QgisInterface; -class QgsVectorLayer; -class QgsRasterLayer; - -class QgsZonalStatisticsDialog: public QDialog, private Ui::QgsZonalStatisticsDialogBase -{ - Q_OBJECT - public: - explicit QgsZonalStatisticsDialog( QgisInterface* iface ); - ~QgsZonalStatisticsDialog(); - - QString rasterFilePath() const; - int rasterBand() const; - QgsVectorLayer* polygonLayer() const; - QgsRasterLayer* rasterLayer() const; - - QString attributePrefix() const; - QgsZonalStatistics::Statistics selectedStats() const; - - private: - QgsZonalStatisticsDialog(); - //! Fills the available raster and polygon layers into the combo boxes - void insertAvailableLayers(); - //! Propose a valid prefix for the attributes - QString proposeAttributePrefix() const; - //! Check if a prefix can be used for the count, sum and mean attribute - bool prefixIsValid( const QString& prefix ) const; - - QgisInterface* mIface; - - private slots: - - void on_mRasterLayerComboBox_currentIndexChanged( int index ); - -}; - -#endif // QGSZONALSTATISTICSDIALOG_H diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsdialogbase.ui b/src/plugins/zonal_statistics/qgszonalstatisticsdialogbase.ui deleted file mode 100644 index 7b9398892638..000000000000 --- a/src/plugins/zonal_statistics/qgszonalstatisticsdialogbase.ui +++ /dev/null @@ -1,130 +0,0 @@ - - - QgsZonalStatisticsDialogBase - - - - 0 - 0 - 254 - 320 - - - - Zonal Statistics - - - - - - Raster layer: - - - - - - - - - - - - Band - - - - - - - - - - - - Polygon layer containing the zones: - - - - - - - - - - Output column prefix: - - - - - - - - - - - - - - Statistics to calculate: - - - - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - mRasterLayerComboBox - mBandComboBox - mPolygonLayerComboBox - mColumnPrefixLineEdit - mStatsListWidget - buttonBox - - - - - buttonBox - accepted() - QgsZonalStatisticsDialogBase - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - QgsZonalStatisticsDialogBase - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp b/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp deleted file mode 100644 index fe4f5d3c16b3..000000000000 --- a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/*************************************************************************** - qgszonalstatisticsplugin.cpp - description - ---------------------------- - begin : August 29th, 2009 - copyright : (C) 2009 by Marco Hugentobler - email : marco dot hugentobler at karto dot baug dot ethz dot ch - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgszonalstatisticsplugin.h" -#include "qgisinterface.h" -#include "qgszonalstatistics.h" -#include "qgszonalstatisticsdialog.h" -#include "qgsvectorlayer.h" -#include -#include - -static const QString name_ = QObject::tr( "Zonal statistics plugin" ); -static const QString description_ = QObject::tr( "A plugin to calculate count, sum, mean of rasters for each polygon of a vector layer" ); -static const QString category_ = QObject::tr( "Raster" ); -static const QString version_ = QObject::tr( "Version 0.1" ); -static const QString pluginIcon_ = QStringLiteral( ":/zonal_statistics/raster-stats.png" ); - -QgsZonalStatisticsPlugin::QgsZonalStatisticsPlugin( QgisInterface* iface ) - : mIface( iface ) - , mAction( nullptr ) -{ -} - -QgsZonalStatisticsPlugin::~QgsZonalStatisticsPlugin() -{ -} - -void QgsZonalStatisticsPlugin::initGui() -{ - delete mAction; - - mAction = new QAction( QIcon( ":/zonal_statistics/raster-stats.png" ), tr( "&Zonal statistics" ), nullptr ); - mAction->setObjectName( QStringLiteral( "ZonalStatistics" ) ); - QObject::connect( mAction, SIGNAL( triggered() ), this, SLOT( run() ) ); - mIface->addRasterToolBarIcon( mAction ); - mIface->addPluginToRasterMenu( tr( "&Zonal statistics" ), mAction ); -} - -void QgsZonalStatisticsPlugin::unload() -{ - mIface->removeRasterToolBarIcon( mAction ); - mIface->removePluginRasterMenu( tr( "&Zonal statistics" ), mAction ); - delete mAction; -} - -void QgsZonalStatisticsPlugin::run() -{ - QgsZonalStatisticsDialog d( mIface ); - if ( d.exec() == QDialog::Rejected ) - { - return; - } - - QString rasterFile = d.rasterFilePath(); - QgsVectorLayer* vl = d.polygonLayer(); - if ( !vl ) - { - return; - } - - QgsZonalStatistics zs( vl, rasterFile, d.attributePrefix(), d.rasterBand(), d.selectedStats() ); - QProgressDialog p( tr( "Calculating zonal statistics..." ), tr( "Abort..." ), 0, 0 ); - p.setWindowModality( Qt::WindowModal ); - zs.calculateStatistics( &p ); -} - -//global methods for the plugin manager -QGISEXTERN QgisPlugin* classFactory( QgisInterface * ifacePointer ) -{ - return new QgsZonalStatisticsPlugin( ifacePointer ); -} - -QGISEXTERN QString name() -{ - return name_; -} - -QGISEXTERN QString description() -{ - return description_; -} - -QGISEXTERN QString category() -{ - return category_; -} - -QGISEXTERN QString version() -{ - return version_; -} - -QGISEXTERN QString icon() -{ - return pluginIcon_; -} - -QGISEXTERN int type() -{ - return QgisPlugin::UI; -} - -QGISEXTERN void unload( QgisPlugin* pluginPointer ) -{ - delete pluginPointer; -} - - - diff --git a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h b/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h deleted file mode 100644 index 3dee4bc9a07a..000000000000 --- a/src/plugins/zonal_statistics/qgszonalstatisticsplugin.h +++ /dev/null @@ -1,48 +0,0 @@ -/*************************************************************************** - qgszonalstatisticsplugin.h - description - ----------------------- - begin : August 29th, 2009 - copyright : (C) 2009 by Marco Hugentobler - email : marco dot hugentobler at karto dot baug dot ethz dot ch - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGSZONALSTATISTICSPLUGIN_H -#define QGSZONALSTATISTICSPLUGIN_H - -#include "qgisplugin.h" -#include - -class QgsInterface; -class QAction; - -class QgsZonalStatisticsPlugin: public QObject, public QgisPlugin -{ - Q_OBJECT - public: - explicit QgsZonalStatisticsPlugin( QgisInterface* iface ); - ~QgsZonalStatisticsPlugin(); - - //! Initialize connection to GUI - void initGui() override; - //! Unload the plugin and cleanup the GUI - void unload() override; - - private slots: - //! Select input file, output file, format and analysis method - void run(); - - private: - QgisInterface* mIface; - QAction* mAction; -}; - -#endif // QGSZONALSTATISTICSPLUGIN_H diff --git a/src/plugins/zonal_statistics/raster-stats.png b/src/plugins/zonal_statistics/raster-stats.png deleted file mode 100644 index 1f812a74b8d98fb9a8bdcc1630e92a72b1f28cad..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 733 zcmeAS@N?(olHy`uVBq!ia0vp^5+KaM1|%Pp+x`GjEX7WqAsj$Z!;#Vf2?p zUk71ECym(^Ktah8*NBqf{Irtt#G+J&^73-M%)IR4 zKdDl;I8onN&p$n$RP|?JoPwFdVr>uFSneHy`C!J-v;A4$UN={p4+b26)|M%th zuYdpixY8x`r>~?wzwN}2HbEL9r?`(j{3n3 zJNNpf4`1B=I}1f~6gawe&2lsl^;NK1c43~W-1iBscPtOCo*8U&?or|2AmN57pEqyz z%?_R_7#P;{^5)8o>A{VH>YZ~ z`h`mM^CBve8`=(}vi{C}9Tz`!^HQbNckXSKG1u8&I9H1EM1#ijb&UJYoaGa6Gu3%t yrLaJu@A7M@1r^&G-<~%Ty_X|Ym*H!FSyGkCiCxvX - - raster-stats.png - - - From 0b35ccefa982c2933a0f4c153ea0a83713537022 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 12:14:22 +1000 Subject: [PATCH 469/897] Update qt5 build instructions for Fedora --- INSTALL | 23 ++++++++++++++++------- doc/INSTALL.html | 27 +++++++++++++++------------ doc/linux.t2t | 11 +++++++++-- 3 files changed, 40 insertions(+), 21 deletions(-) diff --git a/INSTALL b/INSTALL index bd0dfed63cf6..fa9bfd41aa6f 100644 --- a/INSTALL +++ b/INSTALL @@ -1,11 +1,9 @@ QGIS Building QGIS from source - step by step -Monday October 17, 2016 - - -Last Updated: Monday October 17, 2016 -Last Change : Monday October 17, 2016 +Tuesday October 25, 2016 +Last Updated: Tuesday October 25, 2016 +Last Change : Monday October 24, 2016 1. Introduction 2. Overview @@ -370,12 +368,21 @@ new subdirectory called `build` or `build-qt5` in it. 3.11.1. Install build dependencies ================================== + dnf install qt5-qtwebkit-devel qt5-qtlocation-devel qt5-qttools-static qt5-qtscript-devel qca-qt5-devel python3-qt5-devel python3-qscintilla-qt5-devel qscintilla-qt5-devel python3-qscintilla-devel python3-qscintilla-qt5 clang flex bison geos-devel gdal-devel sqlite-devel libspatialite-devel qt5-qtsvg-devel qt5-qtxmlpatterns-devel spatialindex-devel expat-devel proj-devel - qwt-devel gsl-devel postgresql-devel + qwt-qt5-devel gsl-devel postgresql-devel cmake python3-future gdal-python3 + python3-psycopg2 python3-PyYAML qca-qt5-ossl + + +To build QGIS server additional dependencies are required: + + + dnf install fcgi-devel + Make sure that your build directory is completely empty when you enter the following command. Do never try to "re-use" an existing Qt4 build directory. @@ -383,7 +390,9 @@ If you want to use `ccmake` or other interactive tools, run the following command in the empty build directory once before starting to use the interactive tools. - cmake -DENABLE_QT5=ON -DWITH_QWTPOLAR=OFF .. + + cmake .. + If everything went ok you can finally start to compile. (As usual append a -jX where X is the number of available cores option to make to speed up your build diff --git a/doc/INSTALL.html b/doc/INSTALL.html index 399e5378fb08..703775adb3f3 100644 --- a/doc/INSTALL.html +++ b/doc/INSTALL.html @@ -77,13 +77,13 @@

                                                                                                                                                                                    -Last Updated: Monday October 17, 2016 -Last Change : Monday October 17, 2016 +Last Updated: Tuesday October 25, 2016 +Last Change : Monday October 24, 2016

                                                                                                                                                                                    @@ -563,38 +563,41 @@

                                                                                                                                                                                    3.10.1. Install build dependencies

                                                                                                                                                                                    command in the empty build directory once before starting to use the interactive tools.

                                                                                                                                                                                    -
                                                                                                                                                                                     cmake
                                                                                                                                                                                     
                                                                                                                                                                                    - +

                                                                                                                                                                                    If everything went ok you can finally start to compile. (As usual append a -jX where X is the number of available cores option to make to speed up your build process)

                                                                                                                                                                                    -
                                                                                                                                                                                     make
                                                                                                                                                                                     
                                                                                                                                                                                    - +

                                                                                                                                                                                    3.11. On Fedora Linux

                                                                                                                                                                                    -

                                                                                                                                                                                    We assume that you have the source code of QGIS ready and created a new subdirectory called `build` or `build-qt5` in it.

                                                                                                                                                                                    -

                                                                                                                                                                                    3.11.1. Install build dependencies

                                                                                                                                                                                    -
                                                                                                                                                                                     dnf install qt5-qtwebkit-devel qt5-qtlocation-devel qt5-qttools-static
                                                                                                                                                                                     qt5-qtscript-devel qca-qt5-devel python3-qt5-devel python3-qscintilla-qt5-devel 
                                                                                                                                                                                     qscintilla-qt5-devel python3-qscintilla-devel python3-qscintilla-qt5
                                                                                                                                                                                     clang flex bison geos-devel gdal-devel sqlite-devel libspatialite-devel
                                                                                                                                                                                     qt5-qtsvg-devel qt5-qtxmlpatterns-devel spatialindex-devel expat-devel proj-devel
                                                                                                                                                                                    -qwt-devel gsl-devel postgresql-devel
                                                                                                                                                                                    +qwt-qt5-devel gsl-devel postgresql-devel cmake python3-future gdal-python3
                                                                                                                                                                                    +python3-psycopg2 python3-PyYAML qca-qt5-ossl
                                                                                                                                                                                     
                                                                                                                                                                                    - +

                                                                                                                                                                                    +

                                                                                                                                                                                    +To build QGIS server additional dependencies are required: +

                                                                                                                                                                                    +
                                                                                                                                                                                    +dnf install fcgi-devel
                                                                                                                                                                                    +
                                                                                                                                                                                    +

                                                                                                                                                                                    Make sure that your build directory is completely empty when you enter the following command. Do never try to "re-use" an existing Qt4 build directory. diff --git a/doc/linux.t2t b/doc/linux.t2t index 0ff0db24d0ff..c4443c4e107a 100644 --- a/doc/linux.t2t +++ b/doc/linux.t2t @@ -254,7 +254,14 @@ qt5-qtscript-devel qca-qt5-devel python3-qt5-devel python3-qscintilla-qt5-devel qscintilla-qt5-devel python3-qscintilla-devel python3-qscintilla-qt5 clang flex bison geos-devel gdal-devel sqlite-devel libspatialite-devel qt5-qtsvg-devel qt5-qtxmlpatterns-devel spatialindex-devel expat-devel proj-devel -qwt-devel gsl-devel postgresql-devel +qwt-qt5-devel gsl-devel postgresql-devel cmake python3-future gdal-python3 +python3-psycopg2 python3-PyYAML qca-qt5-ossl +``` + +To build QGIS server additional dependencies are required: + +``` +dnf install fcgi-devel ``` Make sure that your build directory is completely empty when you enter the @@ -264,7 +271,7 @@ command in the empty build directory once before starting to use the interactive tools. ``` -cmake -DENABLE_QT5=ON -DWITH_QWTPOLAR=OFF .. +cmake .. ``` If everything went ok you can finally start to compile. (As usual append a -jX From f195e9400f885e56625b96a6b36efd7af3a767ec Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 12:22:52 +1000 Subject: [PATCH 470/897] Make welcome page layout align with other panels + docks --- src/app/qgswelcomepage.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/app/qgswelcomepage.cpp b/src/app/qgswelcomepage.cpp index 59a9578949a1..35935a071a6d 100644 --- a/src/app/qgswelcomepage.cpp +++ b/src/app/qgswelcomepage.cpp @@ -31,18 +31,20 @@ QgsWelcomePage::QgsWelcomePage( bool skipVersionCheck, QWidget* parent ) QVBoxLayout* mainLayout = new QVBoxLayout; mainLayout->setMargin( 0 ); + mainLayout->setContentsMargins( 0, 0, 0, 0 ); setLayout( mainLayout ); QHBoxLayout* layout = new QHBoxLayout(); - layout->setMargin( 9 ); + layout->setMargin( 0 ); mainLayout->addLayout( layout ); - QWidget* recentProjctsContainer = new QWidget; - recentProjctsContainer->setLayout( new QVBoxLayout ); - recentProjctsContainer->layout()->setContentsMargins( 3, 3, 3, 0 ); + QWidget* recentProjectsContainer = new QWidget; + recentProjectsContainer->setLayout( new QVBoxLayout ); + recentProjectsContainer->layout()->setContentsMargins( 0, 0, 0, 0 ); + recentProjectsContainer->layout()->setMargin( 0 ); QLabel* recentProjectsTitle = new QLabel( QStringLiteral( "

                                                                                                                                                                                    %1

                                                                                                                                                                                    " ).arg( tr( "Recent Projects" ) ) ); - recentProjctsContainer->layout()->addWidget( recentProjectsTitle ); + recentProjectsContainer->layout()->addWidget( recentProjectsTitle ); QListView* recentProjectsListView = new QListView(); recentProjectsListView->setResizeMode( QListView::Adjust ); @@ -51,9 +53,9 @@ QgsWelcomePage::QgsWelcomePage( bool skipVersionCheck, QWidget* parent ) recentProjectsListView->setModel( mModel ); recentProjectsListView->setItemDelegate( new QgsWelcomePageItemDelegate( recentProjectsListView ) ); - recentProjctsContainer->layout()->addWidget( recentProjectsListView ); + recentProjectsContainer->layout()->addWidget( recentProjectsListView ); - layout->addWidget( recentProjctsContainer ); + layout->addWidget( recentProjectsContainer ); mVersionInformation = new QLabel; mainLayout->addWidget( mVersionInformation ); From 72e4cf7db0b8becfc3f505f0e195fb9237988b1c Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 12:30:23 +1000 Subject: [PATCH 471/897] Fix a qt warning message on startup --- src/ui/qgsmapstylingwidgetbase.ui | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/ui/qgsmapstylingwidgetbase.ui b/src/ui/qgsmapstylingwidgetbase.ui index b86a1a4a03fd..2b63d9f38f8e 100644 --- a/src/ui/qgsmapstylingwidgetbase.ui +++ b/src/ui/qgsmapstylingwidgetbase.ui @@ -203,9 +203,7 @@ - - - + From 7470b55bbd1f046cbfe4508bfd0aea8e1ce6af9e Mon Sep 17 00:00:00 2001 From: Paolo Cavallini Date: Tue, 25 Oct 2016 08:57:31 +0200 Subject: [PATCH 472/897] Enable CROP_TO_CUTLINE by default Fixes https://hub.qgis.org/issues/15750 Please backport it where appropriate. --- python/plugins/processing/algs/gdal/ClipByMask.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/gdal/ClipByMask.py b/python/plugins/processing/algs/gdal/ClipByMask.py index ed144774b2d4..0c67f717b013 100644 --- a/python/plugins/processing/algs/gdal/ClipByMask.py +++ b/python/plugins/processing/algs/gdal/ClipByMask.py @@ -87,7 +87,7 @@ def defineCharacteristics(self): self.addParameter(ParameterBoolean(self.ALPHA_BAND, self.tr('Create and output alpha band'), False)) self.addParameter(ParameterBoolean(self.CROP_TO_CUTLINE, - self.tr('Crop the extent of the target dataset to the extent of the cutline'), False)) + self.tr('Crop the extent of the target dataset to the extent of the cutline'), True)) self.addParameter(ParameterBoolean(self.KEEP_RESOLUTION, self.tr('Keep resolution of output raster'), False)) From e237963274605624f21ec5cff5f002fee0267972 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 22:29:07 +0200 Subject: [PATCH 473/897] SIP QgsVectorLayer: fix signatures for output parameter saveStyleToDatabase() and getStyleFromDatabase() should define errMsg as output parameter And loadNamedStyle() also for theResultFlag. --- doc/api_break.dox | 3 +++ python/core/qgsvectorlayer.sip | 10 +++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 10d9c788060a..e61406f6313f 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1438,6 +1438,9 @@ displayExpression instead. For the map tip use mapTipTemplate() instead.
                                                                                                                                                                                  • Removed fieldNameIndex(), use fields().lookupField() or fields().indexFromName() instead
                                                                                                                                                                                  • Renamed addAttributeAlias() to setFieldAlias()
                                                                                                                                                                                  • Renamed remAttributeAlias() to removeFieldAlias() +
                                                                                                                                                                                  • saveStyleToDatabase(): msgError argument is correctly declared as output argument +
                                                                                                                                                                                  • getStyleFromDatabase(): msgError argument is correctly declared as output argument +
                                                                                                                                                                                  • loadNamedStyle(): theResultFlag argument is correctly declared as output argument \subsection qgis_api_break_3_0_QgsVectorLayerEditBuffer QgsVectorLayerEditBuffer diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index eb99679ae4a9..125f295e8498 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -662,11 +662,11 @@ class QgsVectorLayer : QgsMapLayer * @param description * @param useAsDefault * @param uiFileContent - * @param msgError + * @param msgError (out) */ virtual void saveStyleToDatabase( const QString& name, const QString& description, bool useAsDefault, const QString& uiFileContent, - QString &msgError ); + QString &msgError /Out/ ); /** * Lists all the style in db split into related to the layer and not related to @@ -682,7 +682,7 @@ class QgsVectorLayer : QgsMapLayer /** * Will return the named style corresponding to style id provided */ - virtual QString getStyleFromDatabase( const QString& styleId, QString &msgError ); + virtual QString getStyleFromDatabase( const QString& styleId, QString &msgError /Out/ ); /** * Load a named style from file/local db/datasource db @@ -690,13 +690,13 @@ class QgsVectorLayer : QgsMapLayer * @param theResultFlag will be set to true if a named style is correctly loaded * @param loadFromLocalDb if true forces to load from local db instead of datasource one */ - virtual QString loadNamedStyle( const QString &theURI, bool &theResultFlag, bool loadFromLocalDb ); + virtual QString loadNamedStyle( const QString &theURI, bool &theResultFlag /Out/, bool loadFromLocalDb ); /** * Calls loadNamedStyle( theURI, theResultFlag, false ); * Retained for backward compatibility */ - virtual QString loadNamedStyle( const QString &theURI, bool &theResultFlag ); + virtual QString loadNamedStyle( const QString &theURI, bool &theResultFlag /Out/ ); /** Read the symbology for the current layer from the Dom node supplied. * @param node node that will contain the symbology definition for this layer. From a70d42802f2d25ce20c16fb5d354f278fcd1dbac Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 22:32:22 +0200 Subject: [PATCH 474/897] QgsVectorLayer::loadNamedStyle(): make it work with non database URI Such as OGR GPKG --- src/core/qgsvectorlayer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index f1b78711caed..7f7472432f68 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -4112,7 +4112,7 @@ QString QgsVectorLayer::loadNamedStyle( const QString &theURI, bool &theResultFl QString QgsVectorLayer::loadNamedStyle( const QString &theURI, bool &theResultFlag, bool loadFromLocalDB ) { QgsDataSourceUri dsUri( theURI ); - if ( !loadFromLocalDB && !dsUri.database().isEmpty() ) + if ( !loadFromLocalDB && mDataProvider && mDataProvider->isSaveAndLoadStyleToDBSupported() ) { QgsProviderRegistry * pReg = QgsProviderRegistry::instance(); QLibrary *myLib = pReg->providerLibrary( mProviderKey ); From 9ae156970a124992bb8d4c1767831e433e284b00 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 22:32:56 +0200 Subject: [PATCH 475/897] QgsVectorLayer::writeSymbology(): fix crash when called with invalid data provider --- src/core/qgsvectorlayer.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 7f7472432f68..173c1e60a1fe 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -1947,7 +1947,14 @@ bool QgsVectorLayer::writeSymbology( QDomNode& node, QDomDocument& doc, QString& mConditionalStyles->writeXml( node, doc ); // save expression fields - mExpressionFieldBuffer->writeXml( node, doc ); + if ( !mExpressionFieldBuffer ) + { + // can happen when saving style on a invalid layer + QgsExpressionFieldBuffer dummy; + dummy.writeXml( node, doc ); + } + else + mExpressionFieldBuffer->writeXml( node, doc ); // save readonly state node.toElement().setAttribute( QStringLiteral( "readOnly" ), mReadOnly ); From 3b77e4b395c27d3c3b384bf9c519e7d1a075b9c2 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 18 Oct 2016 22:33:23 +0200 Subject: [PATCH 476/897] [FEATURE] [OGR provider] Load/save style in database for GPKG and Spatialite --- src/providers/ogr/qgsogrprovider.cpp | 607 +++++++++++++++++++-- src/providers/ogr/qgsogrprovider.h | 3 +- tests/src/python/test_provider_ogr_gpkg.py | 143 ++++- 3 files changed, 707 insertions(+), 46 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 66fdc6dc7a20..d789f2554f5c 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -34,6 +34,7 @@ email : sherman at mrcc.com #include #include #include +#include #include #include #include @@ -64,6 +65,7 @@ static const QString TEXT_PROVIDER_DESCRIPTION = + GDALVersionInfo( "RELEASE_NAME" ) + ')'; +static OGRwkbGeometryType ogrWkbGeometryTypeFromName( const QString& typeName ); class QgsCPLErrorHandler { @@ -284,35 +286,18 @@ QgsVectorLayerImport::ImportError QgsOgrProvider::createEmptyLayer( const QStrin return QgsVectorLayerImport::NoError; } - -QgsOgrProvider::QgsOgrProvider( QString const & uri ) - : QgsVectorDataProvider( uri ) - , mFirstFieldIsFid( false ) - , ogrDataSource( nullptr ) - , mExtent( nullptr ) - , mForceRecomputeExtent( false ) - , ogrLayer( nullptr ) - , ogrOrigLayer( nullptr ) - , mLayerIndex( 0 ) - , mIsSubLayer( false ) - , mOgrGeometryTypeFilter( wkbUnknown ) - , ogrDriver( nullptr ) - , mValid( false ) - , mOGRGeomType( wkbUnknown ) - , mFeaturesCounted( -1 ) - , mWriteAccess( false ) - , mWriteAccessPossible( false ) - , mDynamicWriteAccess( false ) - , mShapefileMayBeCorrupted( false ) - , mUpdateModeStackDepth( 0 ) - , mCapabilities( 0 ) +static QString AnalyzeURI( QString const & uri, + bool& isSubLayer, + int& layerIndex, + QString& layerName, + QString& subsetString, + OGRwkbGeometryType& ogrGeometryTypeFilter ) { - QgsApplication::registerOgrDrivers(); - - QSettings settings; - CPLSetConfigOption( "SHAPE_ENCODING", settings.value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ? "" : nullptr ); - - // make connection to the data source + isSubLayer = false; + layerIndex = 0; + layerName = QString::null; + subsetString = QString::null; + ogrGeometryTypeFilter = wkbUnknown; QgsDebugMsg( "Data source uri is [" + uri + ']' ); @@ -328,14 +313,12 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) if ( !uri.contains( '|', Qt::CaseSensitive ) ) { - mFilePath = uri; - mLayerIndex = 0; - mLayerName = QString::null; + return uri; } else { QStringList theURIParts = uri.split( '|' ); - mFilePath = theURIParts.at( 0 ); + QString filePath = theURIParts.at( 0 ); for ( int i = 1 ; i < theURIParts.size(); i++ ) { @@ -347,34 +330,76 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) if ( field == QLatin1String( "layerid" ) ) { bool ok; - mLayerIndex = value.toInt( &ok ); - if ( ! ok ) + layerIndex = value.toInt( &ok ); + if ( ! ok || layerIndex < 0 ) { - mLayerIndex = -1; + layerIndex = -1; } else { - mIsSubLayer = true; + isSubLayer = true; } } else if ( field == QLatin1String( "layername" ) ) { - mLayerName = value; - mIsSubLayer = true; + layerName = value; + isSubLayer = true; } - if ( field == QLatin1String( "subset" ) ) + else if ( field == QLatin1String( "subset" ) ) { - mSubsetString = value; + subsetString = value; } - if ( field == QLatin1String( "geometrytype" ) ) + else if ( field == QLatin1String( "geometrytype" ) ) { - mOgrGeometryTypeFilter = ogrWkbGeometryTypeFromName( value ); + ogrGeometryTypeFilter = ogrWkbGeometryTypeFromName( value ); } } + + return filePath; } +} + +QgsOgrProvider::QgsOgrProvider( QString const & uri ) + : QgsVectorDataProvider( uri ) + , mFirstFieldIsFid( false ) + , ogrDataSource( nullptr ) + , mExtent( nullptr ) + , mForceRecomputeExtent( false ) + , ogrLayer( nullptr ) + , ogrOrigLayer( nullptr ) + , mLayerIndex( 0 ) + , mIsSubLayer( false ) + , mOgrGeometryTypeFilter( wkbUnknown ) + , ogrDriver( nullptr ) + , mValid( false ) + , mOGRGeomType( wkbUnknown ) + , mFeaturesCounted( -1 ) + , mWriteAccess( false ) + , mWriteAccessPossible( false ) + , mDynamicWriteAccess( false ) + , mShapefileMayBeCorrupted( false ) + , mUpdateModeStackDepth( 0 ) + , mCapabilities( 0 ) +{ + QgsApplication::registerOgrDrivers(); + + QSettings settings; + CPLSetConfigOption( "SHAPE_ENCODING", settings.value( QStringLiteral( "/qgis/ignoreShapeEncoding" ), true ).toBool() ? "" : nullptr ); + + // make connection to the data source + + QgsDebugMsg( "Data source uri is [" + uri + ']' ); + + mFilePath = AnalyzeURI( uri, + mIsSubLayer, + mLayerIndex, + mLayerName, + mSubsetString, + mOgrGeometryTypeFilter ); + open( OpenModeInitial ); setNativeTypes( QList() @@ -610,7 +635,7 @@ QString QgsOgrProvider::ogrWkbGeometryTypeName( OGRwkbGeometryType type ) const return geom; } -OGRwkbGeometryType QgsOgrProvider::ogrWkbGeometryTypeFromName( const QString& typeName ) const +static OGRwkbGeometryType ogrWkbGeometryTypeFromName( const QString& typeName ) { if ( typeName == QLatin1String( "Point" ) ) return wkbPoint; else if ( typeName == QLatin1String( "LineString" ) ) return wkbLineString; @@ -657,6 +682,12 @@ QStringList QgsOgrProvider::subLayers() const continue; } + if ( !mIsSubLayer && theLayerName == "layer_styles" ) + { + // Ignore layer_styles layer + continue; + } + QgsDebugMsg( QString( "id = %1 name = %2 layerGeomType = %3" ).arg( i ).arg( theLayerName ).arg( layerGeomType ) ); if ( wkbFlatten( layerGeomType ) != wkbUnknown ) @@ -3545,6 +3576,496 @@ bool QgsOgrProvider::leaveUpdateMode() return true; } +bool QgsOgrProvider::isSaveAndLoadStyleToDBSupported() const +{ + // We could potentially extend support for styling to other drivers + // with multiple layer support. + return ogrDriverName == "GPKG" || ogrDriverName == "SQLite"; +} + +// --------------------------------------------------------------------------- + +static +OGRDataSourceH LoadDataSourceAndLayer( const QString& uri, + OGRLayerH& hUserLayer, + QString& errCause ) +{ + hUserLayer = nullptr; + bool isSubLayer; + int layerIndex; + QString layerName; + QString subsetString; + OGRwkbGeometryType ogrGeometryType; + QString filePath = AnalyzeURI( uri, + isSubLayer, + layerIndex, + layerName, + subsetString, + ogrGeometryType ); + + OGRDataSourceH hDS = QgsOgrProviderUtils::OGROpenWrapper( TO8F( filePath ), true, nullptr ); + if ( !hDS ) + { + QgsDebugMsg( "Connection to database failed.." ); + errCause = QObject::tr( "Connection to database failed" ); + return nullptr; + } + + if ( !layerName.isEmpty() ) + { + hUserLayer = OGR_DS_GetLayerByName( hDS, TO8F( layerName ) ); + if ( !hUserLayer ) + { + errCause = QObject::tr( "Cannot find layer %1." ).arg( layerName ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return nullptr; + } + } + else + { + hUserLayer = OGR_DS_GetLayer( hDS, layerIndex ); + if ( !hUserLayer ) + { + errCause = QObject::tr( "Cannot find layer %1." ).arg( layerIndex ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return nullptr; + } + } + + return hDS; +} + + +QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QString& sldStyle, + const QString& styleName, const QString& styleDescription, + const QString& uiFileContent, bool useAsDefault, QString& errCause ) +{ + OGRLayerH hUserLayer = nullptr; + OGRDataSourceH hDS = LoadDataSourceAndLayer( uri, hUserLayer, errCause ); + if ( !hDS ) + return false; + + // check if layer_styles table already exist + OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS, "layer_styles" ); + if ( !hLayer ) + { + // if not create it + // Note: we use the same schema as in the spatialite and postgre providers + //for cross interoperability + + char** options = nullptr; + // TODO: might need change if other drivers than GPKG / SQLite + options = CSLSetNameValue( options, "FID", "id" ); + hLayer = OGR_DS_CreateLayer( hDS, "layer_styles", nullptr, wkbNone, options ); + CSLDestroy( options ); + if ( !hLayer ) + { + errCause = QObject::tr( "Unable to save layer style. It's not possible to create the destination table on the database." ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return false; + } + bool ok = true; + { + OGRFieldDefnH fld = OGR_Fld_Create( "f_table_catalog", OFTString ); + OGR_Fld_SetWidth( fld, 256 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "f_table_schema", OFTString ); + OGR_Fld_SetWidth( fld, 256 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "f_table_name", OFTString ); + OGR_Fld_SetWidth( fld, 256 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "f_geometry_column", OFTString ); + OGR_Fld_SetWidth( fld, 256 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "styleName", OFTString ); + OGR_Fld_SetWidth( fld, 30 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "styleQML", OFTString ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "styleSLD", OFTString ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "useAsDefault", OFTInteger ); +#if GDAL_VERSION_MAJOR >= 2 + OGR_Fld_SetSubType( fld, OFSTBoolean ); +#endif + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "description", OFTString ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "owner", OFTString ); + OGR_Fld_SetWidth( fld, 30 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "ui", OFTString ); + OGR_Fld_SetWidth( fld, 30 ); + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + { + OGRFieldDefnH fld = OGR_Fld_Create( "update_time", OFTDateTime ); +#if GDAL_VERSION_MAJOR >= 2 + OGR_Fld_SetDefault( fld, "CURRENT_TIMESTAMP" ); +#endif + ok &= OGR_L_CreateField( hLayer, fld, true ) == OGRERR_NONE; + OGR_Fld_Destroy( fld ); + } + if ( !ok ) + { + errCause = QObject::tr( "Unable to save layer style. It's not possible to create the destination table on the database." ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return false; + } + } + + QString realStyleName = + styleName.isEmpty() ? QString( OGR_L_GetName( hUserLayer ) ) : styleName; + + OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn( hLayer ); + + if ( useAsDefault ) + { + QString oldDefaultQuery = QString( "useAsDefault = 1 AND f_table_schema=''" + " AND f_table_name=%1" + " AND f_geometry_column=%2" ) + .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetName( hUserLayer ) ) ) ) + .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetGeometryColumn( hUserLayer ) ) ) ); + OGR_L_SetAttributeFilter( hLayer, TO8F( oldDefaultQuery ) ); + OGRFeatureH hFeature = OGR_L_GetNextFeature( hLayer ); + if ( hFeature ) + { + OGR_F_SetFieldInteger( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "useAsDefault" ), + 0 ); + bool ok = OGR_L_SetFeature( hLayer, hFeature ) == 0; + OGR_F_Destroy( hFeature ); + if ( !ok ) + { + QgsDebugMsg( "Could not unset previous useAsDefault style" ); + } + } + } + + QString checkQuery = QString( "f_table_schema=''" + " AND f_table_name=%1" + " AND f_geometry_column=%2" + " AND styleName=%3" ) + .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetName( hUserLayer ) ) ) ) + .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetGeometryColumn( hUserLayer ) ) ) ) + .arg( QgsOgrProviderUtils::quotedValue( realStyleName ) ); + OGR_L_SetAttributeFilter( hLayer, TO8F( checkQuery ) ); + OGR_L_ResetReading( hLayer ); + OGRFeatureH hFeature = OGR_L_GetNextFeature( hLayer ); + bool bNew = true; + + if ( hFeature != NULL ) + { + QSettings settings; + // Only used in tests. Do not define it for interactive implication + QVariant overwriteStyle = settings.value( "/qgis/overwriteStyle" ); + if (( !overwriteStyle.isNull() && !overwriteStyle.toBool() ) || + ( overwriteStyle.isNull() && + QMessageBox::question( nullptr, QObject::tr( "Save style in database" ), + QObject::tr( "A style named \"%1\" already exists in the database for this layer. Do you want to overwrite it?" ) + .arg( realStyleName ), + QMessageBox::Yes | QMessageBox::No ) == QMessageBox::No ) ) + { + errCause = QObject::tr( "Operation aborted" ); + OGR_F_Destroy( hFeature ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return false; + } + bNew = false; + } + else + { + hFeature = OGR_F_Create( hLayerDefn ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "f_table_catalog" ), + "" ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "f_table_schema" ), + "" ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "f_table_name" ), + OGR_L_GetName( hUserLayer ) ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "f_geometry_column" ), + OGR_L_GetGeometryColumn( hUserLayer ) ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "styleName" ), + TO8F( realStyleName ) ); + if ( !uiFileContent.isEmpty() ) + { + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "ui" ), + TO8F( uiFileContent ) ); + } + } + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "styleQML" ), + TO8F( qmlStyle ) ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "styleSLD" ), + TO8F( sldStyle ) ); + OGR_F_SetFieldInteger( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "useAsDefault" ), + useAsDefault ? 1 : 0 ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "description" ), + TO8F( styleDescription.isEmpty() ? QDateTime::currentDateTime().toString() : styleDescription ) ); + OGR_F_SetFieldString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "owner" ), + "" ); + + bool bFeatureOK; + if ( bNew ) + bFeatureOK = OGR_L_CreateFeature( hLayer, hFeature ) == OGRERR_NONE; + else + bFeatureOK = OGR_L_SetFeature( hLayer, hFeature ) == OGRERR_NONE; + + OGR_F_Destroy( hFeature ); + + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + + if ( !bFeatureOK ) + { + QgsMessageLog::logMessage( QObject::tr( "Error updating style" ) ); + errCause = QObject::tr( "Error looking for style. The query was logged" ); + return false; + } + + return true; +} + + +QGISEXTERN QString loadStyle( const QString& uri, QString& errCause ) +{ + OGRLayerH hUserLayer = nullptr; + OGRDataSourceH hDS = LoadDataSourceAndLayer( uri, hUserLayer, errCause ); + if ( !hDS ) + return ""; + + // check if layer_styles table already exist + OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS, "layer_styles" ); + if ( !hLayer ) + { + errCause = QObject::tr( "Cannot find layer_styles layer" ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return ""; + } + + QString selectQmlQuery = QString( "f_table_schema=''" + " AND f_table_name=%1" + " AND f_geometry_column=%2" + " ORDER BY CASE WHEN useAsDefault THEN 1 ELSE 2 END" + ",update_time DESC LIMIT 1" ) + .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetName( hUserLayer ) ) ) ) + .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetGeometryColumn( hUserLayer ) ) ) ); + OGR_L_SetAttributeFilter( hLayer, TO8F( selectQmlQuery ) ); + OGR_L_ResetReading( hLayer ); + OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn( hLayer ); + QString styleQML; + qlonglong moreRecentTimestamp = 0; + while ( true ) + { + OGRFeatureH hFeat = OGR_L_GetNextFeature( hLayer ); + if ( !hFeat ) + break; + if ( OGR_F_GetFieldAsInteger( hFeat, OGR_FD_GetFieldIndex( hLayerDefn, "useAsDefault" ) ) ) + { + styleQML = QString::fromUtf8( + OGR_F_GetFieldAsString( hFeat, OGR_FD_GetFieldIndex( hLayerDefn, "styleQML" ) ) ); + OGR_F_Destroy( hFeat ); + break; + } + + int year, month, day, hour, minute, second, TZ; + OGR_F_GetFieldAsDateTime( hFeat, OGR_FD_GetFieldIndex( hLayerDefn, "update_time" ), + &year, &month, &day, &hour, &minute, &second, &TZ ); + qlonglong ts = second + minute * 60 + hour * 3600 + day * 24 * 3600 + + ( qlonglong )month * 31 * 24 * 3600 + ( qlonglong )year * 12 * 31 * 24 * 3600; + if ( ts > moreRecentTimestamp ) + { + moreRecentTimestamp = ts; + styleQML = QString::fromUtf8( + OGR_F_GetFieldAsString( hFeat, OGR_FD_GetFieldIndex( hLayerDefn, "styleQML" ) ) ); + + } + OGR_F_Destroy( hFeat ); + } + + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return styleQML; +} + +QGISEXTERN int listStyles( const QString &uri, QStringList &ids, QStringList &names, + QStringList &descriptions, QString& errCause ) +{ + OGRLayerH hUserLayer = nullptr; + OGRDataSourceH hDS = LoadDataSourceAndLayer( uri, hUserLayer, errCause ); + if ( !hDS ) + return -1; + + // check if layer_styles table already exist + OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS, "layer_styles" ); + if ( !hLayer || OGR_L_GetFeatureCount( hLayer, TRUE ) == 0 ) + { + QgsMessageLog::logMessage( QObject::tr( "No styles available on DB" ) ); + errCause = QObject::tr( "No styles available on DB" ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return 0; + } + + OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn( hLayer ); + + OGR_L_ResetReading( hLayer ); + + QList listTimestamp; + QMap mapIdToStyleName; + QMap mapIdToDescription; + QMap > mapTimestampToId; + int numberOfRelatedStyles = 0; + while ( true ) + { + OGRFeatureH hFeature = OGR_L_GetNextFeature( hLayer ); + if ( !hFeature ) + break; + + QString tableName( QString::fromUtf8( + OGR_F_GetFieldAsString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "f_table_name" ) ) ) ); + QString geometryColumn( QString::fromUtf8( + OGR_F_GetFieldAsString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "f_geometry_column" ) ) ) ); + QString styleName( QString::fromUtf8( + OGR_F_GetFieldAsString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "styleName" ) ) ) ); + QString description( QString::fromUtf8( + OGR_F_GetFieldAsString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "description" ) ) ) ); + int fid = static_cast( OGR_F_GetFID( hFeature ) ); + if ( tableName == QString::fromUtf8( OGR_L_GetName( hUserLayer ) ) && + geometryColumn == QString::fromUtf8( OGR_L_GetGeometryColumn( hUserLayer ) ) ) + { + // Append first all related styles + QString id( QString( "%1" ).arg( fid ) ); + ids.append( id ); + names.append( styleName ); + descriptions.append( description ); + ++ numberOfRelatedStyles; + } + else + { + int year, month, day, hour, minute, second, TZ; + OGR_F_GetFieldAsDateTime( hFeature, OGR_FD_GetFieldIndex( hLayerDefn, "update_time" ), + &year, &month, &day, &hour, &minute, &second, &TZ ); + qlonglong ts = second + minute * 60 + hour * 3600 + day * 24 * 3600 + + ( qlonglong )month * 31 * 24 * 3600 + ( qlonglong )year * 12 * 31 * 24 * 3600; + + listTimestamp.append( ts ); + mapIdToStyleName[fid] = styleName; + mapIdToDescription[fid] = styleName; + mapTimestampToId[ts].append( fid ); + } + + OGR_F_Destroy( hFeature ); + } + + qSort( listTimestamp.begin(), listTimestamp.end() ); + // Sort from most recent to least recent + for ( int i = listTimestamp.size() - 1; i >= 0; i-- ) + { + const QList& listId = mapTimestampToId[listTimestamp[i]]; + for ( int j = 0; j < listId.size(); j++ ) + { + int fid = listId[j]; + QString id( QString( "%1" ).arg( fid ) ); + ids.append( id ); + names.append( mapIdToStyleName[fid] ); + descriptions.append( mapIdToDescription[fid] ); + } + } + + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + + return numberOfRelatedStyles; +} + +QGISEXTERN QString getStyleById( const QString& uri, QString styleId, QString& errCause ) +{ + OGRLayerH hUserLayer = nullptr; + OGRDataSourceH hDS = LoadDataSourceAndLayer( uri, hUserLayer, errCause ); + if ( !hDS ) + return ""; + + // check if layer_styles table already exist + OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS, "layer_styles" ); + if ( !hLayer ) + { + errCause = QObject::tr( "Cannot find layer_styles layer" ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return ""; + } + + bool ok; + int id = styleId.toInt( &ok ); + if ( !ok ) + { + errCause = QObject::tr( "Invalid style identifier" ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return ""; + } + + OGRFeatureH hFeature = OGR_L_GetFeature( hLayer, id ); + if ( !hFeature ) + { + errCause = QObject::tr( "No style corresponding to style identifier" ); + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + return ""; + } + + OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn( hLayer ); + QString styleQML( QString::fromUtf8( + OGR_F_GetFieldAsString( hFeature, + OGR_FD_GetFieldIndex( hLayerDefn, "styleQML" ) ) ) ); + + OGR_F_Destroy( hFeature ); + + QgsOgrProviderUtils::OGRDestroyWrapper( hDS ); + + return styleQML; +} + + // --------------------------------------------------------------------------- QGISEXTERN QgsVectorLayerImport::ImportError createEmptyLayer( diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index dd5ca03829e8..ce6c7cab25c1 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -165,6 +165,8 @@ class QgsOgrProvider : public QgsVectorDataProvider virtual bool leaveUpdateMode() override; + virtual bool isSaveAndLoadStyleToDBSupported() const override; + /** Return vector file filter string * * Returns a string suitable for a QFileDialog of vector file formats @@ -295,7 +297,6 @@ class QgsOgrProvider : public QgsVectorDataProvider private: unsigned char *getGeometryPointer( OGRFeatureH fet ); QString ogrWkbGeometryTypeName( OGRwkbGeometryType type ) const; - OGRwkbGeometryType ogrWkbGeometryTypeFromName( const QString& typeName ) const; QgsFields mAttributeFields; bool mFirstFieldIsFid; OGRDataSourceH ogrDataSource; diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index 32c89f1f4eb0..0f1201190975 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -20,10 +20,9 @@ from osgeo import gdal, ogr from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsRectangle +from qgis.PyQt.QtCore import QCoreApplication, QSettings from qgis.testing import start_app, unittest -start_app() - def GDAL_COMPUTE_VERSION(maj, min, rev): return ((maj) * 1000000 + (min) * 10000 + (rev) * 100) @@ -43,6 +42,13 @@ class TestPyQgsOGRProviderGpkg(unittest.TestCase): @classmethod def setUpClass(cls): """Run before all tests""" + + QCoreApplication.setOrganizationName("QGIS_Test") + QCoreApplication.setOrganizationDomain("TestPyQgsOGRProviderGpkg.com") + QCoreApplication.setApplicationName("TestPyQgsOGRProviderGpkg") + QSettings().clear() + start_app() + # Create test layer cls.basetestpath = tempfile.mkdtemp() @@ -51,6 +57,8 @@ def tearDownClass(cls): """Run after all tests""" shutil.rmtree(cls.basetestpath, True) + QSettings().clear() + def testSingleToMultiPolygonPromotion(self): tmpfile = os.path.join(self.basetestpath, 'testSingleToMultiPolygonPromotion.gpkg') @@ -220,6 +228,137 @@ def testSelectSubsetString(self): got = [feat for feat in vl.getFeatures()] self.assertEqual(len(got), 1) + def testStyle(self): + + # First test with invalid URI + vl = QgsVectorLayer('/idont/exist.gpkg', 'test', 'ogr') + + self.assertFalse(vl.dataProvider().isSaveAndLoadStyleToDBSupported()) + + related_count, idlist, namelist, desclist, errmsg = vl.listStylesInDatabase() + self.assertEqual(related_count, -1) + self.assertEqual(idlist, []) + self.assertEqual(namelist, []) + self.assertEqual(desclist, []) + self.assertNotEqual(errmsg, "") + + qml, errmsg = vl.getStyleFromDatabase("1") + self.assertEqual(qml, "") + self.assertNotEqual(errmsg, "") + + qml, success = vl.loadNamedStyle('/idont/exist.gpkg') + self.assertFalse(success) + + errorMsg = vl.saveStyleToDatabase("name", "description", False, "") + self.assertNotEqual(errorMsg, "") + + # Now with valid URI + tmpfile = os.path.join(self.basetestpath, 'testStyle.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbMultiPolygon) + lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) + f = ogr.Feature(lyr.GetLayerDefn()) + f['foo'] = 'bar' + lyr.CreateFeature(f) + f = None + lyr = ds.CreateLayer('test2', geom_type=ogr.wkbMultiPolygon) + lyr.CreateField(ogr.FieldDefn('foo', ogr.OFTString)) + f = ogr.Feature(lyr.GetLayerDefn()) + f['foo'] = 'bar' + lyr.CreateFeature(f) + f = None + ds = None + + vl = QgsVectorLayer('{}|layername=test'.format(tmpfile), 'test', 'ogr') + self.assertTrue(vl.isValid()) + + vl2 = QgsVectorLayer('{}|layername=test2'.format(tmpfile), 'test2', 'ogr') + self.assertTrue(vl2.isValid()) + + self.assertTrue(vl.dataProvider().isSaveAndLoadStyleToDBSupported()) + + related_count, idlist, namelist, desclist, errmsg = vl.listStylesInDatabase() + self.assertEqual(related_count, 0) + self.assertEqual(idlist, []) + self.assertEqual(namelist, []) + self.assertEqual(desclist, []) + self.assertNotEqual(errmsg, "") + + qml, errmsg = vl.getStyleFromDatabase("not_existing") + self.assertEqual(qml, "") + self.assertNotEqual(errmsg, "") + + qml, success = vl.loadNamedStyle('{}|layerid=0'.format(tmpfile)) + self.assertFalse(success) + + errorMsg = vl.saveStyleToDatabase("name", "description", False, "") + self.assertEqual(errorMsg, "") + + qml, errmsg = vl.getStyleFromDatabase("not_existing") + self.assertEqual(qml, "") + self.assertNotEqual(errmsg, "") + + related_count, idlist, namelist, desclist, errmsg = vl.listStylesInDatabase() + self.assertEqual(related_count, 1) + self.assertEqual(errmsg, "") + self.assertEqual(idlist, ['1']) + self.assertEqual(namelist, ['name']) + self.assertEqual(desclist, ['description']) + + qml, errmsg = vl.getStyleFromDatabase("100") + self.assertEqual(qml, "") + self.assertNotEqual(errmsg, "") + + qml, errmsg = vl.getStyleFromDatabase("1") + self.assertTrue(qml.startswith(' Date: Mon, 24 Oct 2016 12:27:45 +0200 Subject: [PATCH 477/897] [OGR provider] More uses of QStringLiteral / QLatin1String --- src/providers/ogr/qgsogrprovider.cpp | 51 ++++++++++++++-------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index d789f2554f5c..1cbd464dfd20 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -571,34 +571,34 @@ QString QgsOgrProvider::ogrWkbGeometryTypeName( OGRwkbGeometryType type ) const break; #if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,0) case wkbCircularString: - geom = "CircularString"; + geom = QStringLiteral( "CircularString" ); break; case wkbCompoundCurve: - geom = "CompoundCurve"; + geom = QStringLiteral( "CompoundCurve" ); break; case wkbCurvePolygon: - geom = "CurvePolygon"; + geom = QStringLiteral( "CurvePolygon" ); break; case wkbMultiCurve: - geom = "MultiCurve"; + geom = QStringLiteral( "MultiCurve" ); break; case wkbMultiSurface: - geom = "MultiSurface"; + geom = QStringLiteral( "MultiSurface" ); break; case wkbCircularStringZ: - geom = "CircularStringZ"; + geom = QStringLiteral( "CircularStringZ" ); break; case wkbCompoundCurveZ: - geom = "CompoundCurveZ"; + geom = QStringLiteral( "CompoundCurveZ" ); break; case wkbCurvePolygonZ: - geom = "CurvePolygonZ"; + geom = QStringLiteral( "CurvePolygonZ" ); break; case wkbMultiCurveZ: - geom = "MultiCurveZ"; + geom = QStringLiteral( "MultiCurveZ" ); break; case wkbMultiSurfaceZ: - geom = "MultiSurfaceZ"; + geom = QStringLiteral( "MultiSurfaceZ" ); break; #endif case wkbNone: @@ -3288,7 +3288,7 @@ OGRLayerH QgsOgrProviderUtils::setSubsetString( OGRLayerH layer, OGRDataSourceH } } QByteArray sql; - if ( subsetString.startsWith( "SELECT ", Qt::CaseInsensitive ) ) + if ( subsetString.startsWith( QLatin1String( "SELECT " ), Qt::CaseInsensitive ) ) sql = encoding->fromUnicode( subsetString ); else { @@ -3580,7 +3580,8 @@ bool QgsOgrProvider::isSaveAndLoadStyleToDBSupported() const { // We could potentially extend support for styling to other drivers // with multiple layer support. - return ogrDriverName == "GPKG" || ogrDriverName == "SQLite"; + return ogrDriverName == QLatin1String( "GPKG" ) || + ogrDriverName == QLatin1String( "SQLite" ); } // --------------------------------------------------------------------------- @@ -3753,9 +3754,9 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS if ( useAsDefault ) { - QString oldDefaultQuery = QString( "useAsDefault = 1 AND f_table_schema=''" - " AND f_table_name=%1" - " AND f_geometry_column=%2" ) + QString oldDefaultQuery = QStringLiteral( "useAsDefault = 1 AND f_table_schema=''" + " AND f_table_name=%1" + " AND f_geometry_column=%2" ) .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetName( hUserLayer ) ) ) ) .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetGeometryColumn( hUserLayer ) ) ) ); OGR_L_SetAttributeFilter( hLayer, TO8F( oldDefaultQuery ) ); @@ -3774,10 +3775,10 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS } } - QString checkQuery = QString( "f_table_schema=''" - " AND f_table_name=%1" - " AND f_geometry_column=%2" - " AND styleName=%3" ) + QString checkQuery = QStringLiteral( "f_table_schema=''" + " AND f_table_name=%1" + " AND f_geometry_column=%2" + " AND styleName=%3" ) .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetName( hUserLayer ) ) ) ) .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetGeometryColumn( hUserLayer ) ) ) ) .arg( QgsOgrProviderUtils::quotedValue( realStyleName ) ); @@ -3790,7 +3791,7 @@ QGISEXTERN bool saveStyle( const QString& uri, const QString& qmlStyle, const QS { QSettings settings; // Only used in tests. Do not define it for interactive implication - QVariant overwriteStyle = settings.value( "/qgis/overwriteStyle" ); + QVariant overwriteStyle = settings.value( QStringLiteral( "/qgis/overwriteStyle" ) ); if (( !overwriteStyle.isNull() && !overwriteStyle.toBool() ) || ( overwriteStyle.isNull() && QMessageBox::question( nullptr, QObject::tr( "Save style in database" ), @@ -3883,11 +3884,11 @@ QGISEXTERN QString loadStyle( const QString& uri, QString& errCause ) return ""; } - QString selectQmlQuery = QString( "f_table_schema=''" - " AND f_table_name=%1" - " AND f_geometry_column=%2" - " ORDER BY CASE WHEN useAsDefault THEN 1 ELSE 2 END" - ",update_time DESC LIMIT 1" ) + QString selectQmlQuery = QStringLiteral( "f_table_schema=''" + " AND f_table_name=%1" + " AND f_geometry_column=%2" + " ORDER BY CASE WHEN useAsDefault THEN 1 ELSE 2 END" + ",update_time DESC LIMIT 1" ) .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetName( hUserLayer ) ) ) ) .arg( QgsOgrProviderUtils::quotedValue( QString( OGR_L_GetGeometryColumn( hUserLayer ) ) ) ); OGR_L_SetAttributeFilter( hLayer, TO8F( selectQmlQuery ) ); From f8bae671964c5f2bca9b6bc31b7cb57bc91d4d13 Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 25 Oct 2016 11:19:44 +0200 Subject: [PATCH 478/897] Clean QgsVectorLayer: remove duplicated writeSld method --- src/core/qgsvectorlayer.cpp | 5 ----- src/core/qgsvectorlayer.h | 2 -- 2 files changed, 7 deletions(-) diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 86e173d3f117..2100bb684f6a 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -2048,11 +2048,6 @@ bool QgsVectorLayer::readSld( const QDomNode& node, QString& errorMessage ) return true; } -bool QgsVectorLayer::writeSld( QDomNode& node, QDomDocument& doc, QString& errorMessage ) const -{ - return writeSld( node, doc, errorMessage, QgsStringMap() ); -} - bool QgsVectorLayer::writeSld( QDomNode& node, QDomDocument& doc, QString& errorMessage, const QgsStringMap& props ) const { Q_UNUSED( errorMessage ); diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 08085b50fef0..ec1b3eeb32c7 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -821,8 +821,6 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ bool writeStyle( QDomNode& node, QDomDocument& doc, QString& errorMessage ) const override; - bool writeSld( QDomNode& node, QDomDocument& doc, QString& errorMessage ) const; - /** * Writes the symbology of the layer into the document provided in SLD 1.1 format * @param node the node that will have the style element added to it. From a43f8a361655e8ade14f5052fa2b30c240a24966 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 25 Oct 2016 13:43:23 +0200 Subject: [PATCH 479/897] Address snapping config UX problems See https://github.com/qgis/QGIS/pull/3617#issuecomment-255114425 --- src/app/qgisapp.cpp | 3 +-- src/app/qgssnappingwidget.cpp | 23 ++++++++++++++++++++--- src/app/qgssnappingwidget.h | 2 ++ src/core/qgsproject.cpp | 1 + 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 1e5251eeb46e..5b948cc49d35 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -823,9 +823,8 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QDialog* dialog = new QDialog( this ); dialog->setWindowTitle( tr( "Project snapping settings" ) ); QVBoxLayout* layout = new QVBoxLayout( dialog ); - QDialogButtonBox* button = new QDialogButtonBox( QDialogButtonBox::Close ); layout->addWidget( mSnappingDialogWidget ); - layout->addWidget( button ); + layout->setMargin( 0 ); mSnappingDialogContainer = dialog; } endProfile(); diff --git a/src/app/qgssnappingwidget.cpp b/src/app/qgssnappingwidget.cpp index fc4f68be46ce..39af865a095e 100644 --- a/src/app/qgssnappingwidget.cpp +++ b/src/app/qgssnappingwidget.cpp @@ -201,12 +201,15 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, mLayerTreeView = new QTreeView(); QgsSnappingLayerTreeModel* model = new QgsSnappingLayerTreeModel( mProject, this ); model->setLayerTreeModel( new QgsLayerTreeModel( QgsProject::instance()->layerTreeRoot(), model ) ); + + connect( model, &QgsSnappingLayerTreeModel::rowsInserted, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); + connect( model, &QgsSnappingLayerTreeModel::modelReset, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); + connect( model, &QgsSnappingLayerTreeModel::rowsRemoved, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); + // model->setFlags( 0 ); mLayerTreeView->setModel( model ); mLayerTreeView->resizeColumnToContents( 0 ); mLayerTreeView->header()->show(); - mLayerTreeView->header()->setSectionResizeMode( QHeaderView::ResizeToContents ); - mLayerTreeView->header()->setSectionResizeMode( QHeaderView::Interactive ); mLayerTreeView->setSelectionMode( QAbstractItemView::NoSelection ); // item delegates @@ -230,9 +233,17 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, connect( project, &QgsProject::topologicalEditingChanged, this, &QgsSnappingWidget::projectTopologicalEditingChanged ); connect( mCanvas, SIGNAL( mapUnitsChanged() ), this, SLOT( updateToleranceDecimals() ) ); + + // Slightly modify the config so the settings changed code doesn't early exit + mConfig = project->snappingConfig(); + mConfig.setEnabled( !mConfig.enabled() ); + projectSnapSettingsChanged(); + // modeChanged determines if widget are visible or not based on mode modeChanged(); updateToleranceDecimals(); + + restoreGeometry( QSettings().value( "/Windows/SnappingWidget/geometry" ).toByteArray() ); } QgsSnappingWidget::~QgsSnappingWidget() @@ -252,7 +263,7 @@ void QgsSnappingWidget::projectSnapSettingsChanged() mEnabledAction->setChecked( config.enabled() ); - if ( config.mode() == QgsSnappingConfig::AllLayers && mModeButton->defaultAction() != mActiveLayerAction ) + if ( config.mode() == QgsSnappingConfig::AllLayers && mModeButton->defaultAction() != mAllLayersAction ) { mModeButton->setDefaultAction( mAllLayersAction ); modeChanged(); @@ -351,6 +362,12 @@ void QgsSnappingWidget::enableIntersectionSnapping( bool enabled ) mProject->setSnappingConfig( mConfig ); } +void QgsSnappingWidget::onSnappingTreeLayersChanged() +{ + mLayerTreeView->resizeColumnToContents( 0 ); + QTimer::singleShot( 0, mLayerTreeView, &QTreeView::expandAll ); +} + void QgsSnappingWidget::modeButtonTriggered( QAction* action ) { if ( action != mModeButton->defaultAction() ) diff --git a/src/app/qgssnappingwidget.h b/src/app/qgssnappingwidget.h index 189864f7c1a7..33459d0085b7 100644 --- a/src/app/qgssnappingwidget.h +++ b/src/app/qgssnappingwidget.h @@ -91,6 +91,8 @@ class APP_EXPORT QgsSnappingWidget : public QWidget //! number of decimals of the tolerance spin box depends on map units void updateToleranceDecimals(); + void onSnappingTreeLayersChanged(); + private: enum DisplayMode { diff --git a/src/core/qgsproject.cpp b/src/core/qgsproject.cpp index 53ca7b0f1ede..02815f41d0a5 100644 --- a/src/core/qgsproject.cpp +++ b/src/core/qgsproject.cpp @@ -451,6 +451,7 @@ void QgsProject::clear() mEmbeddedLayers.clear(); mRelationManager->clear(); mSnappingConfig.reset(); + emit snappingConfigChanged(); mMapThemeCollection.reset( new QgsMapThemeCollection() ); emit mapThemeCollectionChanged(); From 9d0bb34010e000acea600f922ccda0dc2e72ddba Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 25 Oct 2016 13:40:10 +0200 Subject: [PATCH 480/897] [BUGFIX][QGIS Server] Do not cache invalid layer After readLayerXml, the server stored layers in cache and in registry without verifying validity. --- src/server/qgshostedrdsbuilder.cpp | 2 +- src/server/qgsserverprojectparser.cpp | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/server/qgshostedrdsbuilder.cpp b/src/server/qgshostedrdsbuilder.cpp index 23b9c3a4cb8d..86e5517d6313 100644 --- a/src/server/qgshostedrdsbuilder.cpp +++ b/src/server/qgshostedrdsbuilder.cpp @@ -61,7 +61,7 @@ QgsMapLayer* QgsHostedRDSBuilder::createMapLayer( const QDomElement& elem, { rl = qobject_cast( QgsMSLayerCache::instance()->searchLayer( uri, layerName ) ); } - if ( !rl ) + if ( !rl || !rl->isValid() ) { QgsDebugMsg( "hostedrds layer not in cache, so create and insert it" ); rl = new QgsRasterLayer( uri, layerNameFromUri( uri ) ); diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index d86a7a0c7fe8..faabfdbf1847 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -280,6 +280,10 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& layer->readLayerXml( const_cast( elem ) ); //should be changed to const in QgsMapLayer //layer->setLayerName( layerName( elem ) ); + if ( !layer->isValid() ) + { + return nullptr; + } // Insert layer in registry and cache before addValueRelationLayersForLayer if ( !QgsMapLayerRegistry::instance()->mapLayer( id ) ) QgsMapLayerRegistry::instance()->addMapLayer( layer, false, false ); From d0da880b8c55148ec0bd6d89d98a48b89f7d6932 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Tue, 25 Oct 2016 15:39:27 +0200 Subject: [PATCH 481/897] [DB Manager] Fix refresh issue when renaming GPKG table, and disable add geometry column button if already one existing --- .../db_manager/db_plugins/connector.py | 6 ++++ .../db_manager/db_plugins/gpkg/connector.py | 33 +++++++++++++++++-- .../db_manager/dlg_table_properties.py | 26 ++++++++------- 3 files changed, 51 insertions(+), 14 deletions(-) diff --git a/python/plugins/db_manager/db_plugins/connector.py b/python/plugins/db_manager/db_plugins/connector.py index 789637cbb9ba..c208566771c9 100644 --- a/python/plugins/db_manager/db_plugins/connector.py +++ b/python/plugins/db_manager/db_plugins/connector.py @@ -49,6 +49,12 @@ def publicUri(self): def hasSpatialSupport(self): return False + def canAddGeometryColumn(self, table): + return self.hasSpatialSupport() + + def canAddSpatialIndex(self, table): + return self.hasSpatialSupport() + def hasRasterSupport(self): return False diff --git a/python/plugins/db_manager/db_plugins/gpkg/connector.py b/python/plugins/db_manager/db_plugins/gpkg/connector.py index aa6c6c423a41..0d846a61e9ed 100644 --- a/python/plugins/db_manager/db_plugins/gpkg/connector.py +++ b/python/plugins/db_manager/db_plugins/gpkg/connector.py @@ -47,7 +47,11 @@ def __init__(self, uri): self.dbname = uri.database() self.has_raster = False self.mapSridToName = {} + self._opendb() + def _opendb(self): + + self.gdal_ds = None if hasattr(gdal, 'OpenEx'): # GDAL >= 2 self.gdal_ds = gdal.OpenEx(self.dbname, gdal.OF_UPDATE) @@ -216,6 +220,23 @@ def getSpatialInfo(self): def hasSpatialSupport(self): return True + # Used by DlgTableProperties + def canAddGeometryColumn(self, table): + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None: + return False + return lyr.GetGeomType() == ogr.wkbNone + + # Used by DlgTableProperties + def canAddSpatialIndex(self, table): + _, tablename = self.getSchemaTableName(table) + lyr = self.gdal_ds.GetLayerByName(tablename) + if lyr is None or lyr.GetGeometryColumn() == '': + return False + return not self.hasSpatialIndex(table, + lyr.GetGeometryColumn()) + def hasRasterSupport(self): return self.has_raster @@ -591,7 +612,12 @@ def renameTable(self, table, new_table): gdal.ErrorReset() self.gdal_ds.ExecuteSQL('ALTER TABLE %s RENAME TO %s' % (tablename, new_table)) - return gdal.GetLastErrorMsg() == '' + if gdal.GetLastErrorMsg() != '': + return False + # we need to reopen after renaming since OGR doesn't update its + # internal state + self._opendb() + return True def moveTable(self, table, new_table, new_schema=None): return self.renameTable(table, new_table) @@ -720,7 +746,10 @@ def addGeometryColumn(self, table, geom_column='geometry', geom_type='POINT', sr if sr.ImportFromEPSG(srid) == 0: geom_field_defn.SetSpatialRef(sr) - return lyr.CreateGeomField(geom_field_defn) == 0 + if lyr.CreateGeomField(geom_field_defn) != 0: + return False + self._opendb() + return True def deleteGeometryColumn(self, table, geom_column): return False # not supported diff --git a/python/plugins/db_manager/dlg_table_properties.py b/python/plugins/db_manager/dlg_table_properties.py index 852a49db7e35..c7f7dd71ef5b 100644 --- a/python/plugins/db_manager/dlg_table_properties.py +++ b/python/plugins/db_manager/dlg_table_properties.py @@ -69,6 +69,9 @@ def __init__(self, table, parent=None): self.btnAddSpatialIndex.clicked.connect(self.createSpatialIndex) self.btnDeleteIndex.clicked.connect(self.deleteIndex) + self.refresh() + + def refresh(self): self.populateViews() self.checkSupports() @@ -77,9 +80,8 @@ def checkSupports(self): self.btnEditColumn.setEnabled(allowEditColumns) self.btnDeleteColumn.setEnabled(allowEditColumns) - allowSpatial = self.db.connector.hasSpatialSupport() - self.btnAddGeometryColumn.setEnabled(allowSpatial) - self.btnAddSpatialIndex.setEnabled(allowSpatial) + self.btnAddGeometryColumn.setEnabled(self.db.connector.canAddGeometryColumn((self.table.schemaName(), self.table.name))) + self.btnAddSpatialIndex.setEnabled(self.db.connector.canAddSpatialIndex((self.table.schemaName(), self.table.name))) def populateViews(self): self.populateFields() @@ -119,7 +121,7 @@ def addColumn(self): try: # add column to table self.table.addField(fld) - self.populateViews() + self.refresh() except BaseError as e: DlgDbError.showError(e, self) return @@ -131,7 +133,7 @@ def addGeometryColumn(self): dlg = DlgAddGeometryColumn(self, self.table) if not dlg.exec_(): return - self.populateViews() + self.refresh() def editColumn(self): """ open dialog to change column info and alter table appropriately """ @@ -153,7 +155,7 @@ def editColumn(self): self.aboutToChangeTable.emit() try: fld.update(new_fld.name, new_fld.type2String(), new_fld.notNull, new_fld.default2String()) - self.populateViews() + self.refresh() except BaseError as e: DlgDbError.showError(e, self) return @@ -178,7 +180,7 @@ def deleteColumn(self): self.aboutToChangeTable.emit() try: fld.delete() - self.populateViews() + self.refresh() except BaseError as e: DlgDbError.showError(e, self) return @@ -211,7 +213,7 @@ def addConstraint(self): dlg = DlgCreateConstraint(self, self.table) if not dlg.exec_(): return - self.populateViews() + self.refresh() def deleteConstraint(self): """ delete a constraint """ @@ -233,7 +235,7 @@ def deleteConstraint(self): self.aboutToChangeTable.emit() try: constr.delete() - self.populateViews() + self.refresh() except BaseError as e: DlgDbError.showError(e, self) return @@ -274,7 +276,7 @@ def createIndex(self): dlg = DlgCreateIndex(self, self.table) if not dlg.exec_(): return - self.populateViews() + self.refresh() def createSpatialIndex(self): """ create spatial index for the geometry column """ @@ -294,7 +296,7 @@ def createSpatialIndex(self): try: self.table.createSpatialIndex() - self.populateViews() + self.refresh() except BaseError as e: DlgDbError.showError(e, self) return @@ -328,7 +330,7 @@ def deleteIndex(self): self.aboutToChangeTable.emit() try: idx.delete() - self.populateViews() + self.refresh() except BaseError as e: DlgDbError.showError(e, self) return From 323c6582c605362dfe6e6db734a40923c9fc3e21 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 25 Oct 2016 17:46:52 +0300 Subject: [PATCH 482/897] [processing] add workaround for GDAL regression with cutlines (fix #15746) --- python/plugins/processing/algs/gdal/ClipByMask.py | 3 +++ python/plugins/processing/algs/gdal/warp.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/python/plugins/processing/algs/gdal/ClipByMask.py b/python/plugins/processing/algs/gdal/ClipByMask.py index 0c67f717b013..5fc720c4f91c 100644 --- a/python/plugins/processing/algs/gdal/ClipByMask.py +++ b/python/plugins/processing/algs/gdal/ClipByMask.py @@ -193,6 +193,9 @@ def getConsoleCommands(self): arguments.append("-wo OPTIMIZE_SIZE=TRUE") + if GdalUtils.version() in [2010000, 2010100]: + arguments.append("--config GDALWARP_IGNORE_BAD_CUTLINE YES") + arguments.append(self.getParameterValue(self.INPUT)) arguments.append(out) diff --git a/python/plugins/processing/algs/gdal/warp.py b/python/plugins/processing/algs/gdal/warp.py index 5d8146525fd0..a21c0225c624 100644 --- a/python/plugins/processing/algs/gdal/warp.py +++ b/python/plugins/processing/algs/gdal/warp.py @@ -198,6 +198,9 @@ def getConsoleCommands(self): arguments.append("-wo OPTIMIZE_SIZE=TRUE") + if GdalUtils.version() in [2010000, 2010100]: + arguments.append("--config GDALWARP_IGNORE_BAD_CUTLINE YES") + arguments.append(self.getParameterValue(self.INPUT)) arguments.append(out) From 6f82740670d32d644f2eeff93c75ee1b87413d17 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 16:04:38 +1000 Subject: [PATCH 483/897] [expressions] Allow non-greedy regex by switching to QRegularExpression --- resources/function_help/json/regexp_match | 2 +- resources/function_help/json/regexp_replace | 2 +- resources/function_help/json/regexp_substr | 2 +- src/core/qgsexpression.cpp | 12 ++++++------ tests/src/core/testqgsexpression.cpp | 4 ++++ 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/resources/function_help/json/regexp_match b/resources/function_help/json/regexp_match index 90a193f84e2e..5f46cfc8d1ca 100644 --- a/resources/function_help/json/regexp_match +++ b/resources/function_help/json/regexp_match @@ -3,7 +3,7 @@ "type": "function", "description": "Returns true if any part of a string matches the supplied regular expression.", "arguments": [ {"arg":"input_string","description":"the string to test against the regular expression"}, - {"arg":"regex","description":"The regular expression to test against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."} + {"arg":"regex","description":"The regular expression to test against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character)."} ], "examples": [ { "expression":"regexp_match('QGIS ROCKS','\\\\\\\\sROCKS')", "returns":"true"}] } diff --git a/resources/function_help/json/regexp_replace b/resources/function_help/json/regexp_replace index aacce8023ca5..f480f29bb71b 100644 --- a/resources/function_help/json/regexp_replace +++ b/resources/function_help/json/regexp_replace @@ -3,7 +3,7 @@ "type": "function", "description": "Returns a string with the supplied regular expression replaced.", "arguments": [ {"arg":"input_string","description":"the string to replace matches in"}, - {"arg":"regex","description":"The regular expression to replace. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."}, + {"arg":"regex","description":"The regular expression to replace. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character)."}, {"arg":"replacement","description":"The string that will replace any matching occurrences of the supplied regular expression. Captured groups can be inserted into the replacement string using \\\\\\\\1, \\\\\\\\2, etc."} ], "examples": [ { "expression":"regexp_replace('QGIS SHOULD ROCK','\\\\\\\\sSHOULD\\\\\\\\s',' DOES ')", "returns":"'QGIS DOES ROCK'"}] diff --git a/resources/function_help/json/regexp_substr b/resources/function_help/json/regexp_substr index 58fabdb9136d..7ce1beb3f2d7 100644 --- a/resources/function_help/json/regexp_substr +++ b/resources/function_help/json/regexp_substr @@ -3,7 +3,7 @@ "type": "function", "description": "Returns the portion of a string which matches a supplied regular expression.", "arguments": [ {"arg":"input_string","description":"the string to find matches in"}, - {"arg":"regex","description":"The regular expression to match against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character). Non-greedy regular expressions are not supported."} + {"arg":"regex","description":"The regular expression to match against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character)."} ], "examples": [ { "expression":"regexp_substr('abc123','(\\\\\\\\d+)')", "returns":"'123'"}] } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index dddee79d8e3f..66129c580392 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1225,7 +1225,7 @@ static QVariant fcnRegexpReplace( const QVariantList& values, const QgsExpressio QString regexp = getStringValue( values.at( 1 ), parent ); QString after = getStringValue( values.at( 2 ), parent ); - QRegExp re( regexp ); + QRegularExpression re( regexp ); if ( !re.isValid() ) { parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) ); @@ -1239,7 +1239,7 @@ static QVariant fcnRegexpMatch( const QVariantList& values, const QgsExpressionC QString str = getStringValue( values.at( 0 ), parent ); QString regexp = getStringValue( values.at( 1 ), parent ); - QRegExp re( regexp ); + QRegularExpression re( regexp ); if ( !re.isValid() ) { parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) ); @@ -1253,7 +1253,7 @@ static QVariant fcnRegexpSubstr( const QVariantList& values, const QgsExpression QString str = getStringValue( values.at( 0 ), parent ); QString regexp = getStringValue( values.at( 1 ), parent ); - QRegExp re( regexp ); + QRegularExpression re( regexp ); if ( !re.isValid() ) { parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) ); @@ -1261,11 +1261,11 @@ static QVariant fcnRegexpSubstr( const QVariantList& values, const QgsExpression } // extract substring - ( void )re.indexIn( str ); - if ( re.captureCount() > 0 ) + QRegularExpressionMatch match = re.match( str ); + if ( match.hasMatch() ) { // return first capture - return QVariant( re.capturedTexts().at( 1 ) ); + return QVariant( match.captured( 0 ) ); } else { diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index c566ef7758a7..0d8d068c2c8b 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -822,10 +822,14 @@ class TestQgsExpression: public QObject QTest::newRow( "length" ) << "length('HeLLo')" << false << QVariant( 5 ); QTest::newRow( "replace" ) << "replace('HeLLo', 'LL', 'xx')" << false << QVariant( "Hexxo" ); QTest::newRow( "regexp_replace" ) << "regexp_replace('HeLLo','[eL]+', '-')" << false << QVariant( "H-o" ); + QTest::newRow( "regexp_replace greedy" ) << "regexp_replace('HeLLo','(?<=H).*L', '-')" << false << QVariant( "H-o" ); + QTest::newRow( "regexp_replace non greedy" ) << "regexp_replace('HeLLo','(?<=H).*?L', '-')" << false << QVariant( "H-Lo" ); + QTest::newRow( "regexp_replace cap group" ) << "regexp_replace('HeLLo','(eL)', 'x\\\\1x')" << false << QVariant( "HxeLxLo" ); QTest::newRow( "regexp_replace invalid" ) << "regexp_replace('HeLLo','[[[', '-')" << true << QVariant(); QTest::newRow( "substr" ) << "substr('HeLLo', 3,2)" << false << QVariant( "LL" ); QTest::newRow( "substr outside" ) << "substr('HeLLo', -5,2)" << false << QVariant( "" ); QTest::newRow( "regexp_substr" ) << "regexp_substr('abc123','(\\\\d+)')" << false << QVariant( "123" ); + QTest::newRow( "regexp_substr non-greedy" ) << "regexp_substr('abc123','(\\\\d+?)')" << false << QVariant( "1" ); QTest::newRow( "regexp_substr no hit" ) << "regexp_substr('abcdef','(\\\\d+)')" << false << QVariant( "" ); QTest::newRow( "regexp_substr invalid" ) << "regexp_substr('abc123','([[[')" << true << QVariant(); QTest::newRow( "strpos" ) << "strpos('Hello World','World')" << false << QVariant( 7 ); From 5798a82c8011ea7f44a1ed1d55ef0719786e8056 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 16:58:59 +1000 Subject: [PATCH 484/897] Speed up point layer rendering - don't calculate unused label obstacles Cuts render time by ~60%. Fix #15752. --- src/core/qgsvectorlayerrenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsvectorlayerrenderer.cpp b/src/core/qgsvectorlayerrenderer.cpp index fa36b2307c2f..b2838db2dd3f 100644 --- a/src/core/qgsvectorlayerrenderer.cpp +++ b/src/core/qgsvectorlayerrenderer.cpp @@ -326,7 +326,7 @@ void QgsVectorLayerRenderer::drawRenderer( QgsFeatureIterator& fit ) } } // new labeling engine - if ( mContext.labelingEngineV2() ) + if ( mContext.labelingEngineV2() && ( mLabelProvider || mDiagramProvider ) ) { QScopedPointer obstacleGeometry; QgsSymbolList symbols = mRenderer->originalSymbolsForFeature( fet, mContext ); From 49432a84683e99bdc2592e7ae808e81fa3bc40cd Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 17:14:51 +1000 Subject: [PATCH 485/897] Optimise QgsAbstractGeometry Make nCoordinates virtual, and provide shortcuts for some geometry types. The base method which calls coordinateSequence() is quite slow in certain circumstances. Speeds up rendering point layers by ~25%, also likely to speed up lots of geometry heavy operations throughout QGIS Refs #15752 --- python/core/geometry/qgsabstractgeometry.sip | 2 +- python/core/geometry/qgscurvepolygon.sip | 1 + .../core/geometry/qgsgeometrycollection.sip | 1 + python/core/geometry/qgslinestring.sip | 1 + python/core/geometry/qgsmultipoint.sip | 1 + python/core/geometry/qgspointv2.sip | 1 + src/core/geometry/qgsabstractgeometry.h | 2 +- src/core/geometry/qgscurvepolygon.cpp | 21 +++++++++++++++++++ src/core/geometry/qgscurvepolygon.h | 1 + src/core/geometry/qgsgeometrycollection.cpp | 16 ++++++++++++++ src/core/geometry/qgsgeometrycollection.h | 2 ++ src/core/geometry/qgslinestring.h | 1 + src/core/geometry/qgsmultipoint.h | 1 + src/core/geometry/qgspointv2.h | 1 + 14 files changed, 50 insertions(+), 2 deletions(-) diff --git a/python/core/geometry/qgsabstractgeometry.sip b/python/core/geometry/qgsabstractgeometry.sip index 1ec9995b471c..910487a1a768 100644 --- a/python/core/geometry/qgsabstractgeometry.sip +++ b/python/core/geometry/qgsabstractgeometry.sip @@ -248,7 +248,7 @@ class QgsAbstractGeometry /** Returns the number of nodes contained in the geometry */ - int nCoordinates() const; + virtual int nCoordinates() const; /** Returns the point corresponding to a specified vertex id */ diff --git a/python/core/geometry/qgscurvepolygon.sip b/python/core/geometry/qgscurvepolygon.sip index 3d0cb03bd6ea..dc933816d4f2 100644 --- a/python/core/geometry/qgscurvepolygon.sip +++ b/python/core/geometry/qgscurvepolygon.sip @@ -68,6 +68,7 @@ class QgsCurvePolygon: public QgsSurface virtual bool deleteVertex( QgsVertexId position ); virtual QList< QList< QList< QgsPointV2 > > > coordinateSequence() const; + virtual int nCoordinates() const; double closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const; bool nextVertex( QgsVertexId& id, QgsPointV2& vertex ) const; diff --git a/python/core/geometry/qgsgeometrycollection.sip b/python/core/geometry/qgsgeometrycollection.sip index 18d427d9b223..1847eb0cb4af 100644 --- a/python/core/geometry/qgsgeometrycollection.sip +++ b/python/core/geometry/qgsgeometrycollection.sip @@ -67,6 +67,7 @@ class QgsGeometryCollection: public QgsAbstractGeometry virtual QgsRectangle boundingBox() const; virtual QList< QList< QList< QgsPointV2 > > > coordinateSequence() const; + virtual int nCoordinates() const; virtual double closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const; bool nextVertex( QgsVertexId& id, QgsPointV2& vertex ) const; diff --git a/python/core/geometry/qgslinestring.sip b/python/core/geometry/qgslinestring.sip index e7d0467df160..25a055faaa28 100644 --- a/python/core/geometry/qgslinestring.sip +++ b/python/core/geometry/qgslinestring.sip @@ -120,6 +120,7 @@ class QgsLineString: public QgsCurve virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const /Factory/; int numPoints() const; + virtual int nCoordinates() const; void points( QList& pt ) const; void draw( QPainter& p ) const; diff --git a/python/core/geometry/qgsmultipoint.sip b/python/core/geometry/qgsmultipoint.sip index 4aaffd3c4ec8..0e86158aac16 100644 --- a/python/core/geometry/qgsmultipoint.sip +++ b/python/core/geometry/qgsmultipoint.sip @@ -16,6 +16,7 @@ class QgsMultiPointV2: public QgsGeometryCollection QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QString asJSON( int precision = 17 ) const; + virtual int nCoordinates() const; /** Adds a geometry and takes ownership. Returns true in case of success*/ virtual bool addGeometry( QgsAbstractGeometry* g /Transfer/ ); diff --git a/python/core/geometry/qgspointv2.sip b/python/core/geometry/qgspointv2.sip index e472f38db94d..2df14c504c53 100644 --- a/python/core/geometry/qgspointv2.sip +++ b/python/core/geometry/qgspointv2.sip @@ -157,6 +157,7 @@ class QgsPointV2: public QgsAbstractGeometry bool transformZ = false ); void transform( const QTransform& t ); virtual QList< QList< QList< QgsPointV2 > > > coordinateSequence() const; + virtual int nCoordinates() const; virtual QgsAbstractGeometry* boundary() const /Factory/; //low-level editing diff --git a/src/core/geometry/qgsabstractgeometry.h b/src/core/geometry/qgsabstractgeometry.h index 37636a429754..3f8d0220d15b 100644 --- a/src/core/geometry/qgsabstractgeometry.h +++ b/src/core/geometry/qgsabstractgeometry.h @@ -233,7 +233,7 @@ class CORE_EXPORT QgsAbstractGeometry /** Returns the number of nodes contained in the geometry */ - int nCoordinates() const; + virtual int nCoordinates() const; /** Returns the point corresponding to a specified vertex id */ diff --git a/src/core/geometry/qgscurvepolygon.cpp b/src/core/geometry/qgscurvepolygon.cpp index 6112a9582e99..6cc72d5c9071 100644 --- a/src/core/geometry/qgscurvepolygon.cpp +++ b/src/core/geometry/qgscurvepolygon.cpp @@ -632,6 +632,27 @@ QgsCoordinateSequence QgsCurvePolygon::coordinateSequence() const return mCoordinateSequence; } +int QgsCurvePolygon::nCoordinates() const +{ + if ( !mCoordinateSequence.isEmpty() ) + return QgsAbstractGeometry::nCoordinates(); + + int count = 0; + + if ( mExteriorRing ) + { + count += mExteriorRing->nCoordinates(); + } + + QList::const_iterator it = mInteriorRings.constBegin(); + for ( ; it != mInteriorRings.constEnd(); ++it ) + { + count += ( *it )->nCoordinates(); + } + + return count; +} + double QgsCurvePolygon::closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const { if ( !mExteriorRing ) diff --git a/src/core/geometry/qgscurvepolygon.h b/src/core/geometry/qgscurvepolygon.h index 79e60eff5c35..f96fc511b75d 100644 --- a/src/core/geometry/qgscurvepolygon.h +++ b/src/core/geometry/qgscurvepolygon.h @@ -93,6 +93,7 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface virtual bool deleteVertex( QgsVertexId position ) override; virtual QgsCoordinateSequence coordinateSequence() const override; + virtual int nCoordinates() const override; double closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const override; bool nextVertex( QgsVertexId& id, QgsPointV2& vertex ) const override; diff --git a/src/core/geometry/qgsgeometrycollection.cpp b/src/core/geometry/qgsgeometrycollection.cpp index 9a4823b9ade6..223304ab2fef 100644 --- a/src/core/geometry/qgsgeometrycollection.cpp +++ b/src/core/geometry/qgsgeometrycollection.cpp @@ -369,6 +369,22 @@ QgsCoordinateSequence QgsGeometryCollection::coordinateSequence() const return mCoordinateSequence; } +int QgsGeometryCollection::nCoordinates() const +{ + if ( !mCoordinateSequence.isEmpty() ) + return QgsAbstractGeometry::nCoordinates(); + + int count = 0; + + QVector< QgsAbstractGeometry* >::const_iterator geomIt = mGeometries.constBegin(); + for ( ; geomIt != mGeometries.constEnd(); ++geomIt ) + { + count += ( *geomIt )->nCoordinates(); + } + + return count; +} + double QgsGeometryCollection::closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const { return QgsGeometryUtils::closestSegmentFromComponents( mGeometries, QgsGeometryUtils::PART, pt, segmentPt, vertexAfter, leftOf, epsilon ); diff --git a/src/core/geometry/qgsgeometrycollection.h b/src/core/geometry/qgsgeometrycollection.h index 34a79a748e50..c3f379b2e134 100644 --- a/src/core/geometry/qgsgeometrycollection.h +++ b/src/core/geometry/qgsgeometrycollection.h @@ -91,6 +91,8 @@ class CORE_EXPORT QgsGeometryCollection: public QgsAbstractGeometry virtual QgsRectangle boundingBox() const override; virtual QgsCoordinateSequence coordinateSequence() const override; + virtual int nCoordinates() const override; + virtual double closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const override; bool nextVertex( QgsVertexId& id, QgsPointV2& vertex ) const override; diff --git a/src/core/geometry/qgslinestring.h b/src/core/geometry/qgslinestring.h index e487e41cf563..2cda7f84252d 100644 --- a/src/core/geometry/qgslinestring.h +++ b/src/core/geometry/qgslinestring.h @@ -148,6 +148,7 @@ class CORE_EXPORT QgsLineString: public QgsCurve virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const override; int numPoints() const override; + virtual int nCoordinates() const override { return mX.size(); } void points( QgsPointSequence &pt ) const override; void draw( QPainter& p ) const override; diff --git a/src/core/geometry/qgsmultipoint.h b/src/core/geometry/qgsmultipoint.h index f6977a3eea41..3211f22a5259 100644 --- a/src/core/geometry/qgsmultipoint.h +++ b/src/core/geometry/qgsmultipoint.h @@ -40,6 +40,7 @@ class CORE_EXPORT QgsMultiPointV2: public QgsGeometryCollection QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QString asJSON( int precision = 17 ) const override; + virtual int nCoordinates() const override { return mGeometries.size(); } //! Adds a geometry and takes ownership. Returns true in case of success virtual bool addGeometry( QgsAbstractGeometry* g ) override; diff --git a/src/core/geometry/qgspointv2.h b/src/core/geometry/qgspointv2.h index 2fc43db99832..b8d00622f4cc 100644 --- a/src/core/geometry/qgspointv2.h +++ b/src/core/geometry/qgspointv2.h @@ -170,6 +170,7 @@ class CORE_EXPORT QgsPointV2: public QgsAbstractGeometry bool transformZ = false ) override; void transform( const QTransform& t ) override; virtual QgsCoordinateSequence coordinateSequence() const override; + virtual int nCoordinates() const override { return 1; } virtual QgsAbstractGeometry* boundary() const override; //low-level editing From 42b9bff0933a39624095c195e93b139e3ad4fed1 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Wed, 26 Oct 2016 09:22:25 +0200 Subject: [PATCH 486/897] include qgsactionmanager.h in install (cherry picked from commit 5d7f8e9565541660d6ae080f520f38a3259173ce) --- src/core/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 020e8286d6d6..9a0a4952c88b 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -602,6 +602,7 @@ SET(QGIS_CORE_HDRS qgis.h qgsaction.h + qgsactionmanager.h qgsaggregatecalculator.h qgsannotation.h qgsattributetableconfig.h From 322edff6e490357b75e705ec0a0db4fc27f26f69 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 26 Oct 2016 10:55:10 +0200 Subject: [PATCH 487/897] Remove snapping settings from status bar --- src/app/qgisapp.cpp | 26 +---- src/app/qgsoptions.cpp | 5 - src/app/qgssnappingwidget.cpp | 68 +++++-------- src/app/qgssnappingwidget.h | 1 - src/ui/qgsoptionsbase.ui | 184 ++++++++++++++++------------------ 5 files changed, 117 insertions(+), 167 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 5b948cc49d35..e16288697117 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -2069,16 +2069,11 @@ void QgisApp::createToolBars() << mLabelToolBar; - // snapping widget as tool bar - QString simpleSnappingWidgetMode = QSettings().value( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), "toolbar" ).toString(); - if ( simpleSnappingWidgetMode != QLatin1String( "statusbar" ) ) - { - mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, mSnappingToolBar ); - mSnappingWidget->setObjectName( QStringLiteral( "mSnappingWidget" ) ); - //mSnappingWidget->setFont( myFont ); - connect( mSnappingWidget, SIGNAL( snappingConfigChanged() ), QgsProject::instance(), SIGNAL( snappingConfigChanged() ) ); - mSnappingToolBar->addWidget( mSnappingWidget ); - } + mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, mSnappingToolBar ); + mSnappingWidget->setObjectName( QStringLiteral( "mSnappingWidget" ) ); + //mSnappingWidget->setFont( myFont ); + connect( mSnappingWidget, SIGNAL( snappingConfigChanged() ), QgsProject::instance(), SIGNAL( snappingConfigChanged() ) ); + mSnappingToolBar->addWidget( mSnappingWidget ); QList toolbarMenuActions; // Set action names so that they can be used in customization @@ -2427,17 +2422,6 @@ void QgisApp::createStatusBar() mRotationLabel->setToolTip( tr( "Current clockwise map rotation in degrees" ) ); statusBar()->addPermanentWidget( mRotationLabel, 0 ); - // snapping widget - QString simpleSnappingWidgetMode = QSettings().value( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), "toolbar" ).toString(); - if ( simpleSnappingWidgetMode == QLatin1String( "statusbar" ) ) - { - mSnappingWidget = new QgsSnappingWidget( QgsProject::instance(), mMapCanvas, statusBar() ); - mSnappingWidget->setObjectName( QStringLiteral( "mSnappingWidget" ) ); - mSnappingWidget->setFont( myFont ); - connect( mSnappingWidget, SIGNAL( snappingConfigChanged() ), QgsProject::instance(), SIGNAL( snappingConfigChanged() ) ); - statusBar()->addPermanentWidget( mSnappingWidget, 0 ); - } - mRotationEdit = new QgsDoubleSpinBox( statusBar() ); mRotationEdit->setObjectName( QStringLiteral( "mRotationEdit" ) ); mRotationEdit->setClearValue( 0.0 ); diff --git a/src/app/qgsoptions.cpp b/src/app/qgsoptions.cpp index b246a59ac4f2..a387f50af4bc 100644 --- a/src/app/qgsoptions.cpp +++ b/src/app/qgsoptions.cpp @@ -915,10 +915,6 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mSnappingMainDialogComboBox->addItem( tr( "dialog" ), "dialog" ); mSnappingMainDialogComboBox->addItem( tr( "dock" ), "dock" ); mSnappingMainDialogComboBox->setCurrentIndex( mSnappingMainDialogComboBox->findData( mSettings->value( QStringLiteral( "/qgis/mainSnappingWidgetMode" ), "dialog" ).toString() ) ); - mSnappingSimplePanelComboBox->clear(); - mSnappingSimplePanelComboBox->addItem( tr( "tool bar" ), "toolbar" ); - mSnappingSimplePanelComboBox->addItem( tr( "status bar" ), "statusbar" ); - mSnappingSimplePanelComboBox->setCurrentIndex( mSnappingSimplePanelComboBox->findData( mSettings->value( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), "toolbar" ).toString() ) ); mOffsetJoinStyleComboBox->addItem( tr( "Round" ), 0 ); mOffsetJoinStyleComboBox->addItem( tr( "Mitre" ), 1 ); @@ -1191,7 +1187,6 @@ void QgsOptions::saveOptions() cmbScanZipInBrowser->currentData().toString() ); mSettings->setValue( QStringLiteral( "/qgis/ignoreShapeEncoding" ), cbxIgnoreShapeEncoding->isChecked() ); mSettings->setValue( QStringLiteral( "/qgis/mainSnappingWidgetMode" ), mSnappingMainDialogComboBox->currentData() ); - mSettings->setValue( QStringLiteral( "/qgis/simpleSnappingWidgetMode" ), mSnappingSimplePanelComboBox->currentData() ); mSettings->setValue( QStringLiteral( "/qgis/addPostgisDC" ), cbxAddPostgisDC->isChecked() ); mSettings->setValue( QStringLiteral( "/qgis/addOracleDC" ), cbxAddOracleDC->isChecked() ); diff --git a/src/app/qgssnappingwidget.cpp b/src/app/qgssnappingwidget.cpp index 39af865a095e..6e283437afde 100644 --- a/src/app/qgssnappingwidget.cpp +++ b/src/app/qgssnappingwidget.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -59,17 +58,8 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, } else { - QStatusBar *sb = qobject_cast( parent ); - if ( sb ) - { - mDisplayMode = StatusBar; - setObjectName( QStringLiteral( "SnappingOptionStatusBar" ) ); - } - else - { - mDisplayMode = Widget; - setObjectName( QStringLiteral( "SnappingOptionDialog" ) ); - } + mDisplayMode = Widget; + setObjectName( QStringLiteral( "SnappingOptionDialog" ) ); } // enable button @@ -162,7 +152,7 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, } else { - // mode = widget or status bar + // mode = widget QHBoxLayout* layout = new QHBoxLayout(); QToolButton* enabledButton = new QToolButton(); @@ -196,36 +186,28 @@ QgsSnappingWidget::QgsSnappingWidget( QgsProject* project, QgsMapCanvas* canvas, layout->setAlignment( Qt::AlignRight ); layout->setSpacing( mDisplayMode == Widget ? 3 : 0 ); - if ( mDisplayMode == Widget ) - { - mLayerTreeView = new QTreeView(); - QgsSnappingLayerTreeModel* model = new QgsSnappingLayerTreeModel( mProject, this ); - model->setLayerTreeModel( new QgsLayerTreeModel( QgsProject::instance()->layerTreeRoot(), model ) ); - - connect( model, &QgsSnappingLayerTreeModel::rowsInserted, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); - connect( model, &QgsSnappingLayerTreeModel::modelReset, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); - connect( model, &QgsSnappingLayerTreeModel::rowsRemoved, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); - - // model->setFlags( 0 ); - mLayerTreeView->setModel( model ); - mLayerTreeView->resizeColumnToContents( 0 ); - mLayerTreeView->header()->show(); - mLayerTreeView->setSelectionMode( QAbstractItemView::NoSelection ); - - // item delegates - mLayerTreeView->setEditTriggers( QAbstractItemView::AllEditTriggers ); - mLayerTreeView->setItemDelegate( new QgsSnappingLayerDelegate( mCanvas, this ) ); - - QGridLayout* topLayout = new QGridLayout(); - topLayout->addLayout( layout, 0, 0, Qt::AlignLeft | Qt::AlignTop ); - topLayout->addWidget( mLayerTreeView, 1, 0 ); - setLayout( topLayout ); - } - else - { - // mode = status bar - setLayout( layout ); - } + mLayerTreeView = new QTreeView(); + QgsSnappingLayerTreeModel* model = new QgsSnappingLayerTreeModel( mProject, this ); + model->setLayerTreeModel( new QgsLayerTreeModel( QgsProject::instance()->layerTreeRoot(), model ) ); + + connect( model, &QgsSnappingLayerTreeModel::rowsInserted, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); + connect( model, &QgsSnappingLayerTreeModel::modelReset, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); + connect( model, &QgsSnappingLayerTreeModel::rowsRemoved, this, &QgsSnappingWidget::onSnappingTreeLayersChanged ); + + // model->setFlags( 0 ); + mLayerTreeView->setModel( model ); + mLayerTreeView->resizeColumnToContents( 0 ); + mLayerTreeView->header()->show(); + mLayerTreeView->setSelectionMode( QAbstractItemView::NoSelection ); + + // item delegates + mLayerTreeView->setEditTriggers( QAbstractItemView::AllEditTriggers ); + mLayerTreeView->setItemDelegate( new QgsSnappingLayerDelegate( mCanvas, this ) ); + + QGridLayout* topLayout = new QGridLayout(); + topLayout->addLayout( layout, 0, 0, Qt::AlignLeft | Qt::AlignTop ); + topLayout->addWidget( mLayerTreeView, 1, 0 ); + setLayout( topLayout ); } // connect settings changed and map units changed to properly update the widget diff --git a/src/app/qgssnappingwidget.h b/src/app/qgssnappingwidget.h index 33459d0085b7..486cc29640af 100644 --- a/src/app/qgssnappingwidget.h +++ b/src/app/qgssnappingwidget.h @@ -97,7 +97,6 @@ class APP_EXPORT QgsSnappingWidget : public QWidget enum DisplayMode { ToolBar, - StatusBar, Widget }; DisplayMode mDisplayMode; diff --git a/src/ui/qgsoptionsbase.ui b/src/ui/qgsoptionsbase.ui index 2ac1c1a094c1..d800a0165475 100644 --- a/src/ui/qgsoptionsbase.ui +++ b/src/ui/qgsoptionsbase.ui @@ -308,7 +308,7 @@ - 13 + 8 @@ -337,8 +337,8 @@ 0 0 - 685 - 612 + 712 + 693 @@ -1023,8 +1023,8 @@ 0 0 - 671 - 869 + 601 + 877 @@ -1456,8 +1456,8 @@ 0 0 - 671 - 659 + 540 + 741 @@ -1814,8 +1814,8 @@ 0 0 - 684 - 924 + 735 + 1038 @@ -2612,8 +2612,8 @@ 0 0 - 685 - 612 + 148 + 276 @@ -2759,8 +2759,8 @@ 0 0 - 685 - 612 + 526 + 354 @@ -3102,8 +3102,8 @@ 0 0 - 685 - 612 + 639 + 668 @@ -3533,8 +3533,8 @@ 0 0 - 685 - 612 + 522 + 591 @@ -3802,8 +3802,8 @@ 0 0 - 671 - 669 + 670 + 718 @@ -4003,37 +4003,21 @@ Snapping - - - - - 0 - 0 - - - - - - - - 5 - - - 99999999.989999994635582 + + + + Display main dialog as (restart required) - - - - 5 - - - 99999999.989999994635582 + + + + Default snap mode - + @@ -4053,21 +4037,7 @@ - - - - - map units - - - - - pixels - - - - - + Qt::Horizontal @@ -4080,7 +4050,7 @@ - + Qt::Horizontal @@ -4093,7 +4063,37 @@ - + + + + + 0 + 0 + + + + + + + + 5 + + + 99999999.989999994635582 + + + + + + + 5 + + + 99999999.989999994635582 + + + + Qt::Horizontal @@ -4106,47 +4106,37 @@ - - - - Search radius for vertex edits - - - - - - - Display main dialog as (restart required) - + + + + + map units + + + + + pixels + + - - + + - Default snap mode + Search radius for vertex edits - - - - Display simplified panel in (restart required) - - + + - + Default snapping tolerance - - - - - - @@ -4360,8 +4350,8 @@ 0 0 - 685 - 612 + 457 + 382 @@ -4499,8 +4489,8 @@ 0 0 - 671 - 638 + 557 + 677 @@ -4745,8 +4735,8 @@ 0 0 - 685 - 612 + 302 + 238 @@ -4854,8 +4844,8 @@ 0 0 - 671 - 689 + 670 + 793 From 469f07c07148f4650bebdfdfe4ef2af3eb04059c Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 26 Oct 2016 10:59:46 +0200 Subject: [PATCH 488/897] Use fallback default mode for snapping with bad configuration --- src/core/qgssnappingconfig.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/qgssnappingconfig.cpp b/src/core/qgssnappingconfig.cpp index cab7a900d60a..ee9c4367bcff 100644 --- a/src/core/qgssnappingconfig.cpp +++ b/src/core/qgssnappingconfig.cpp @@ -129,16 +129,16 @@ void QgsSnappingConfig::reset() { // get defaults values. They are both used for standard and advanced configuration (per layer) bool enabled = QSettings().value( QStringLiteral( "/qgis/digitizing/default_advanced_snap_enabled" ), true ).toBool(); - SnappingMode mode = ( SnappingMode )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_mode" ), ( int )AllLayers ).toInt(); - if ( mMode == 0 ) + SnappingMode mode = static_cast( QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_mode" ), AllLayers ).toInt() ); + if ( mode == 0 ) { // backward compatibility with QGIS 2.x // could be removed in 3.4+ - mMode = AllLayers; + mode = AllLayers; } - SnappingType type = ( SnappingType )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_type" ), ( int )Vertex ).toInt(); + SnappingType type = static_cast( QSettings().value( QStringLiteral( "/qgis/digitizing/default_snap_type" ), Vertex ).toInt() ); double tolerance = QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance" ), 0 ).toDouble(); - QgsTolerance::UnitType units = ( QgsTolerance::UnitType )QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), ( int )QgsTolerance::ProjectUnits ).toInt(); + QgsTolerance::UnitType units = static_cast( QSettings().value( QStringLiteral( "/qgis/digitizing/default_snapping_tolerance_unit" ), QgsTolerance::ProjectUnits ).toInt() ); // assign main (standard) config mEnabled = enabled; From 85897885445c7383938ac89318d12a7d37024bb4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 19:20:54 +1000 Subject: [PATCH 489/897] Use QgsExpressionContextScope::addVariable instead of setVariable ...where appropriate (ie, read-only, non user set variables). It's much faster as it doesn't need to check whether the variable already exists. Results in ~10% improvement in rendering speed. Refs #15752. --- src/app/composer/qgsattributeselectiondialog.cpp | 2 +- src/app/qgsattributetabledialog.cpp | 4 ++-- src/app/qgsfieldcalculator.cpp | 4 ++-- src/app/qgsmaptoolfeatureaction.cpp | 4 ++-- src/core/composer/qgscomposerattributetablev2.cpp | 2 +- src/core/composer/qgscomposermapgrid.cpp | 8 ++++---- src/core/qgsactionmanager.cpp | 2 +- src/core/qgsconditionalstyle.cpp | 2 +- src/core/qgsexpression.cpp | 6 +++--- src/core/qgsexpressioncontext.cpp | 4 ++-- src/core/symbology-ng/qgsarrowsymbollayer.cpp | 8 ++++---- src/core/symbology-ng/qgslinesymbollayer.cpp | 8 ++++---- src/core/symbology-ng/qgspointdistancerenderer.cpp | 6 +++--- src/core/symbology-ng/qgssymbol.cpp | 10 +++++----- .../attributetable/qgsfieldconditionalformatwidget.cpp | 2 +- src/gui/symbology-ng/qgslayerpropertieswidget.cpp | 2 +- src/gui/symbology-ng/qgspointclusterrendererwidget.cpp | 8 ++++---- .../qgspointdisplacementrendererwidget.cpp | 8 ++++---- src/gui/symbology-ng/qgssymbollayerwidget.cpp | 2 +- 19 files changed, 46 insertions(+), 46 deletions(-) diff --git a/src/app/composer/qgsattributeselectiondialog.cpp b/src/app/composer/qgsattributeselectiondialog.cpp index ef6ebb65de6e..7e0885ffac02 100644 --- a/src/app/composer/qgsattributeselectiondialog.cpp +++ b/src/app/composer/qgsattributeselectiondialog.cpp @@ -105,7 +105,7 @@ QgsExpressionContext QgsComposerColumnSourceDelegate::createExpressionContext() } QgsExpressionContext expContext = mComposerObject->createExpressionContext(); - expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), 1 ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), 1, true ) ); expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) ); return expContext; } diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 98f01b7d7ef0..1549386a6cc3 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -59,7 +59,7 @@ QgsExpressionContext QgsAttributeTableDialog::createExpressionContext() const if ( mLayer ) expContext << QgsExpressionContextUtils::layerScope( mLayer ); - expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), 1 ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), 1, true ) ); expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) ); @@ -471,7 +471,7 @@ void QgsAttributeTableDialog::runFieldCalculation( QgsVectorLayer* layer, const } context.setFeature( feature ); - context.lastScope()->setVariable( QStringLiteral( "row_number" ), rownum ); + context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), rownum, true ) ); QVariant value = exp.evaluate( &context ); fld.convertCompatible( value ); diff --git a/src/app/qgsfieldcalculator.cpp b/src/app/qgsfieldcalculator.cpp index 4f223e37c79f..a443a96ca67d 100644 --- a/src/app/qgsfieldcalculator.cpp +++ b/src/app/qgsfieldcalculator.cpp @@ -44,7 +44,7 @@ QgsFieldCalculator::QgsFieldCalculator( QgsVectorLayer* vl, QWidget* parent ) << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( mVectorLayer ); - expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), 1 ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), 1, true ) ); expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) ); builder->setLayer( vl ); @@ -282,7 +282,7 @@ void QgsFieldCalculator::accept() while ( fit.nextFeature( feature ) ) { expContext.setFeature( feature ); - expContext.lastScope()->setVariable( QStringLiteral( "row_number" ), rownum ); + expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), rownum, true ) ); QVariant value = exp.evaluate( &expContext ); if ( exp.hasEvalError() ) diff --git a/src/app/qgsmaptoolfeatureaction.cpp b/src/app/qgsmaptoolfeatureaction.cpp index e3fe5bdb1fe7..b6b4de8d008d 100644 --- a/src/app/qgsmaptoolfeatureaction.cpp +++ b/src/app/qgsmaptoolfeatureaction.cpp @@ -143,8 +143,8 @@ bool QgsMapToolFeatureAction::doAction( QgsVectorLayer *layer, int x, int y ) << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::mapSettingsScope( mCanvas->mapSettings() ); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); - actionScope->setVariable( QStringLiteral( "click_x" ), point.x() ); - actionScope->setVariable( QStringLiteral( "click_y" ), point.y() ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "click_x" ), point.x(), true ) ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "click_y" ), point.y(), true ) ); context << actionScope; int actionIdx = layer->actions()->defaultAction(); diff --git a/src/core/composer/qgscomposerattributetablev2.cpp b/src/core/composer/qgscomposerattributetablev2.cpp index 1c88e4fe8530..f3c9c5626f6d 100644 --- a/src/core/composer/qgscomposerattributetablev2.cpp +++ b/src/core/composer/qgscomposerattributetablev2.cpp @@ -508,7 +508,7 @@ bool QgsComposerAttributeTableV2::getTableContents( QgsComposerTableContents &co { // Lets assume it's an expression QgsExpression* expression = new QgsExpression(( *columnIt )->attribute() ); - context.lastScope()->setVariable( QStringLiteral( "row_number" ), counter + 1 ); + context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), counter + 1, true ) ); expression->prepare( &context ); QVariant value = expression->evaluate( &context ); currentRow << value; diff --git a/src/core/composer/qgscomposermapgrid.cpp b/src/core/composer/qgscomposermapgrid.cpp index 9faebcf3b1c6..c4dbd3d43f54 100644 --- a/src/core/composer/qgscomposermapgrid.cpp +++ b/src/core/composer/qgscomposermapgrid.cpp @@ -1475,8 +1475,8 @@ QString QgsComposerMapGrid::gridAnnotationString( double value, QgsComposerMapGr } else if ( mGridAnnotationFormat == CustomFormat ) { - expressionContext.lastScope()->setVariable( QStringLiteral( "grid_number" ), value ); - expressionContext.lastScope()->setVariable( QStringLiteral( "grid_axis" ), coord == QgsComposerMapGrid::Longitude ? "x" : "y" ); + expressionContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "grid_number" ), value, true ) ); + expressionContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "grid_axis" ), coord == QgsComposerMapGrid::Longitude ? "x" : "y", true ) ); if ( !mGridAnnotationExpression.data() ) { mGridAnnotationExpression.reset( new QgsExpression( mGridAnnotationExpressionString ) ); @@ -2210,8 +2210,8 @@ QgsExpressionContext QgsComposerMapGrid::createExpressionContext() const { QgsExpressionContext context = QgsComposerObject::createExpressionContext(); context.appendScope( new QgsExpressionContextScope( tr( "Grid" ) ) ); - context.lastScope()->setVariable( QStringLiteral( "grid_number" ), 0 ); - context.lastScope()->setVariable( QStringLiteral( "grid_axis" ), "x" ); + context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "grid_number" ), 0, true ) ); + context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "grid_axis" ), "x", true ) ); context.setHighlightedVariables( QStringList() << QStringLiteral( "grid_number" ) << QStringLiteral( "grid_axis" ) ); return context; } diff --git a/src/core/qgsactionmanager.cpp b/src/core/qgsactionmanager.cpp index e9cd102f27ae..eeb7b5c978d0 100644 --- a/src/core/qgsactionmanager.cpp +++ b/src/core/qgsactionmanager.cpp @@ -67,7 +67,7 @@ void QgsActionManager::doAction( int index, const QgsFeature& feat, int defaultV { QgsExpressionContext context = createExpressionContext(); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); - actionScope->setVariable( QStringLiteral( "current_field" ), feat.attribute( defaultValueIndex ) ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "current_field" ), feat.attribute( defaultValueIndex ), true ) ); context << actionScope; doAction( index, feat, context ); } diff --git a/src/core/qgsconditionalstyle.cpp b/src/core/qgsconditionalstyle.cpp index 6053e7b996f5..7363736d9c04 100644 --- a/src/core/qgsconditionalstyle.cpp +++ b/src/core/qgsconditionalstyle.cpp @@ -195,7 +195,7 @@ void QgsConditionalStyle::setSymbol( QgsSymbol* value ) bool QgsConditionalStyle::matches( const QVariant& value, QgsExpressionContext& context ) const { QgsExpression exp( mRule ); - context.lastScope()->setVariable( QStringLiteral( "value" ), value ); + context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "value" ), value, true ) ); return exp.evaluate( &context ).toBool(); } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 66129c580392..e6a6f6a9ed48 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1297,7 +1297,7 @@ static QVariant fcnFeature( const QVariantList&, const QgsExpressionContext* con if ( !context ) return QVariant(); - return context->variable( QgsExpressionContext::EXPR_FEATURE ); + return context->feature(); } static QVariant fcnAttribute( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { @@ -4963,9 +4963,9 @@ QVariant QgsExpression::NodeColumnRef::eval( QgsExpression *parent, const QgsExp } } - if ( context && context->hasVariable( QgsExpressionContext::EXPR_FEATURE ) ) + if ( context && context->feature().isValid() ) { - QgsFeature feature = qvariant_cast( context->variable( QgsExpressionContext::EXPR_FEATURE ) ); + QgsFeature feature = context->feature(); if ( index >= 0 ) return feature.attribute( index ); else diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index 67cd7d3e769a..cd150b2fa7f6 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -196,12 +196,12 @@ void QgsExpressionContextScope::addFunction( const QString& name, QgsScopedExpre void QgsExpressionContextScope::setFeature( const QgsFeature &feature ) { - setVariable( QgsExpressionContext::EXPR_FEATURE, QVariant::fromValue( feature ) ); + addVariable( StaticVariable( QgsExpressionContext::EXPR_FEATURE, QVariant::fromValue( feature ), true ) ); } void QgsExpressionContextScope::setFields( const QgsFields &fields ) { - setVariable( QgsExpressionContext::EXPR_FIELDS, QVariant::fromValue( fields ) ); + addVariable( StaticVariable( QgsExpressionContext::EXPR_FIELDS, QVariant::fromValue( fields ), true ) ); } diff --git a/src/core/symbology-ng/qgsarrowsymbollayer.cpp b/src/core/symbology-ng/qgsarrowsymbollayer.cpp index e91f7fae2b2d..edd469984848 100644 --- a/src/core/symbology-ng/qgsarrowsymbollayer.cpp +++ b/src/core/symbology-ng/qgsarrowsymbollayer.cpp @@ -691,8 +691,8 @@ void QgsArrowSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbolRend } context.renderContext().expressionContext().appendScope( mExpressionScope.data() ); - mExpressionScope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, points.size() + 1 ); - mExpressionScope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, 1 ); + mExpressionScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, points.size() + 1, true ) ); + mExpressionScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, 1, true ) ); if ( isCurved() ) { _resolveDataDefined( context ); @@ -727,7 +727,7 @@ void QgsArrowSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbolRend { for ( int pIdx = 0; pIdx < points.size() - 1; pIdx += 2 ) { - mExpressionScope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, pIdx + 1 ); + mExpressionScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, pIdx + 1, true ) ); _resolveDataDefined( context ); if ( points.size() - pIdx >= 3 ) @@ -778,7 +778,7 @@ void QgsArrowSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbolRend // only straight arrows for ( int pIdx = 0; pIdx < points.size() - 1; pIdx++ ) { - mExpressionScope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, pIdx + 1 ); + mExpressionScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, pIdx + 1, true ) ); _resolveDataDefined( context ); // origin point diff --git a/src/core/symbology-ng/qgslinesymbollayer.cpp b/src/core/symbology-ng/qgslinesymbollayer.cpp index dcba6bdf5c36..02905773a634 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.cpp +++ b/src/core/symbology-ng/qgslinesymbollayer.cpp @@ -985,7 +985,7 @@ void QgsMarkerLineSymbolLayer::renderPolylineInterval( const QPolygonF& points, // "c" is 1 for regular point or in interval (0,1] for begin of line segment lastPt += c * diff; lengthLeft -= painterUnitInterval; - scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) ); mMarker->renderPoint( lastPt, context.feature(), rc, -1, context.selected() ); c = 1; // reset c (if wasn't 1 already) } @@ -1019,7 +1019,7 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg QgsExpressionContextScope* scope = new QgsExpressionContextScope(); context.renderContext().expressionContext().appendScope( scope ); - scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, points.size() ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_COUNT, points.size(), true ) ); double offsetAlongLine = mOffsetAlongLine; if ( hasDataDefinedProperty( QgsSymbolLayer::EXPR_OFFSET_ALONG_LINE ) ) @@ -1046,7 +1046,7 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg int pointNum = 0; while ( context.renderContext().geometry()->nextVertex( vId, vPoint ) ) { - scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) ); if (( placement == Vertex && vId.type == QgsVertexId::SegmentVertex ) || ( placement == CurvePoint && vId.type == QgsVertexId::CurveVertex ) ) @@ -1112,7 +1112,7 @@ void QgsMarkerLineSymbolLayer::renderPolylineVertex( const QPolygonF& points, Qg int pointNum = 0; for ( ; i < maxCount; ++i ) { - scope->setVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_POINT_NUM, ++pointNum, true ) ); if ( isRing && placement == Vertex && i == points.count() - 1 ) { diff --git a/src/core/symbology-ng/qgspointdistancerenderer.cpp b/src/core/symbology-ng/qgspointdistancerenderer.cpp index 4a7086e1c6d6..b90142e3fa76 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.cpp +++ b/src/core/symbology-ng/qgspointdistancerenderer.cpp @@ -449,15 +449,15 @@ QgsExpressionContextScope* QgsPointDistanceRenderer::createGroupScope( const Clu if ( groupColor.isValid() ) { - clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, QgsSymbolLayerUtils::encodeColor( groupColor ) ); + clusterScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, QgsSymbolLayerUtils::encodeColor( groupColor ), true ) ); } else { //mixed colors - clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, QVariant() ); + clusterScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, QVariant(), true ) ); } - clusterScope->setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, group.size() ); + clusterScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, group.size(), true ) ); } return clusterScope; } diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index f5ecd8a24738..f6f2f16acde3 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -696,8 +696,8 @@ void QgsSymbol::renderFeature( const QgsFeature& feature, QgsRenderContext& cont { context.expressionContext().appendScope( mSymbolRenderContext->expressionContextScope() ); QgsExpressionContextUtils::updateSymbolScope( this, mSymbolRenderContext->expressionContextScope() ); - mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT, mSymbolRenderContext->geometryPartCount() ); - mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, 1 ); + mSymbolRenderContext->expressionContextScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT, mSymbolRenderContext->geometryPartCount(), true ) ); + mSymbolRenderContext->expressionContextScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, 1, true ) ); } // Collection of markers to paint, only used for no curve types. @@ -800,7 +800,7 @@ void QgsSymbol::renderFeature( const QgsFeature& feature, QgsRenderContext& cont for ( int i = 0; i < mp.numGeometries(); ++i ) { mSymbolRenderContext->setGeometryPartNum( i + 1 ); - mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1 ); + mSymbolRenderContext->expressionContextScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1, true ) ); const QgsPointV2& point = static_cast< const QgsPointV2& >( *mp.geometryN( i ) ); const QPointF pt = _getPoint( context, point ); @@ -829,7 +829,7 @@ void QgsSymbol::renderFeature( const QgsFeature& feature, QgsRenderContext& cont for ( unsigned int i = 0; i < num; ++i ) { mSymbolRenderContext->setGeometryPartNum( i + 1 ); - mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1 ); + mSymbolRenderContext->expressionContextScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1, true ) ); context.setGeometry( geomCollection.geometryN( i ) ); const QgsCurve& curve = dynamic_cast( *geomCollection.geometryN( i ) ); @@ -887,7 +887,7 @@ void QgsSymbol::renderFeature( const QgsFeature& feature, QgsRenderContext& cont { const unsigned i = listPartIndex[idx]; mSymbolRenderContext->setGeometryPartNum( i + 1 ); - mSymbolRenderContext->expressionContextScope()->setVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1 ); + mSymbolRenderContext->expressionContextScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_NUM, i + 1, true ) ); context.setGeometry( geomCollection.geometryN( i ) ); const QgsPolygonV2& polygon = dynamic_cast( *geomCollection.geometryN( i ) ); diff --git a/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp b/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp index 81533fd7e856..989825472215 100644 --- a/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp +++ b/src/gui/attributetable/qgsfieldconditionalformatwidget.cpp @@ -78,7 +78,7 @@ void QgsFieldConditionalFormatWidget::setExpression() context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::layerScope( mLayer ); - context.lastScope()->setVariable( QStringLiteral( "value" ), 0 ); + context.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "value" ), 0, true ) ); context.setHighlightedVariables( QStringList() << QStringLiteral( "value" ) ); QgsExpressionBuilderDialog dlg( mLayer, mRuleEdit->text(), this, QStringLiteral( "generic" ), context ); diff --git a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp index 2174d2779b2f..6c862c74fe68 100644 --- a/src/gui/symbology-ng/qgslayerpropertieswidget.cpp +++ b/src/gui/symbology-ng/qgslayerpropertieswidget.cpp @@ -251,7 +251,7 @@ QgsExpressionContext QgsLayerPropertiesWidget::createExpressionContext() const { //cheat a bit - set the symbol color variable to match the symbol layer's color (when we should really be using the *symbols* //color, but that's not accessible here). 99% of the time these will be the same anyway - symbolScope->setVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, mLayer->color() ); + symbolScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, mLayer->color(), true ) ); } expContext << symbolScope; expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT, 1, true ) ); diff --git a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp index 155d9f2b2be1..9e9f471e6fd4 100644 --- a/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointclusterrendererwidget.cpp @@ -137,8 +137,8 @@ void QgsPointClusterRendererWidget::on_mRendererSettingsButton_clicked() w->setPanelTitle( tr( "Renderer settings" ) ); QgsExpressionContextScope scope; - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) ); QList< QgsExpressionContextScope > scopes = mContext.additionalExpressionContextScopes(); scopes << scope; QgsSymbolWidgetContext context = mContext; @@ -190,8 +190,8 @@ void QgsPointClusterRendererWidget::on_mCenterSymbolPushButton_clicked() QgsSymbolWidgetContext context = mContext; QgsExpressionContextScope scope; - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) ); QList< QgsExpressionContextScope > scopes = context.additionalExpressionContextScopes(); scopes << scope; context.setAdditionalExpressionContextScopes( scopes ); diff --git a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp index 6be2724573c9..7346e555e2e0 100644 --- a/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp +++ b/src/gui/symbology-ng/qgspointdisplacementrendererwidget.cpp @@ -218,8 +218,8 @@ void QgsPointDisplacementRendererWidget::on_mRendererSettingsButton_clicked() QgsSymbolWidgetContext context = mContext; QgsExpressionContextScope scope; - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) ); QList< QgsExpressionContextScope > scopes = context.additionalExpressionContextScopes(); scopes << scope; context.setAdditionalExpressionContextScopes( scopes ); @@ -366,8 +366,8 @@ void QgsPointDisplacementRendererWidget::on_mCenterSymbolPushButton_clicked() QgsSymbolWidgetContext context = mContext; QgsExpressionContextScope scope; - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "" ); - scope.setVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0 ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) ); QList< QgsExpressionContextScope > scopes = context.additionalExpressionContextScopes(); scopes << scope; context.setAdditionalExpressionContextScopes( scopes ); diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.cpp b/src/gui/symbology-ng/qgssymbollayerwidget.cpp index 2f6e9a55683d..bbabec6214b3 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.cpp +++ b/src/gui/symbology-ng/qgssymbollayerwidget.cpp @@ -77,7 +77,7 @@ QgsExpressionContext QgsSymbolLayerWidget::createExpressionContext() const { //cheat a bit - set the symbol color variable to match the symbol layer's color (when we should really be using the *symbols* //color, but that's not accessible here). 99% of the time these will be the same anyway - symbolScope->setVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, symbolLayer->color() ); + symbolScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, symbolLayer->color(), true ) ); } expContext << symbolScope; expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_GEOMETRY_PART_COUNT, 1, true ) ); From 8b74201470d98eb02871211f510a1edcaf6980fc Mon Sep 17 00:00:00 2001 From: nirvn Date: Tue, 25 Oct 2016 14:36:04 +0700 Subject: [PATCH 490/897] [FEATURE] array support for the replace() expression function --- resources/function_help/json/replace | 10 +++++--- src/core/qgsexpression.cpp | 38 +++++++++++++++++++++++++--- tests/src/core/testqgsexpression.cpp | 4 +++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/resources/function_help/json/replace b/resources/function_help/json/replace index 509b2e462619..a5d92b77fee4 100644 --- a/resources/function_help/json/replace +++ b/resources/function_help/json/replace @@ -1,10 +1,12 @@ { "name": "replace", "type": "function", - "description": "Returns a string with the the supplied string replaced.", + "description": "Returns a string with the supplied string or array of strings replaced by a string or an array of strings.", "arguments": [ {"arg":"string","description":"the input string"}, - {"arg":"before","description":"the string to replace"}, - {"arg":"after","description":"the string to use as a replacement"}], - "examples": [ { "expression":"replace('QGIS SHOULD ROCK','SHOULD','DOES')", "returns":"'QGIS DOES ROCK'"} + {"arg":"before","description":"the string or array of strings to replace"}, + {"arg":"after","description":"the string or array of strings to use as a replacement"}], + "examples": [ { "expression":"replace('QGIS SHOULD ROCK','SHOULD','DOES')", "returns":"'QGIS DOES ROCK'"}, + { "expression":"replace('QGIS ABC',array('A','B','C'),array('X','Y','Z'))", "returns":"'QGIS XYZ'"}, + { "expression":"replace('QGIS',array('Q','S'),'')", "returns":"'GI'"} ] } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index e6a6f6a9ed48..e4307700e361 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1215,9 +1215,41 @@ static QVariant fcnLength( const QVariantList& values, const QgsExpressionContex static QVariant fcnReplace( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { QString str = getStringValue( values.at( 0 ), parent ); - QString before = getStringValue( values.at( 1 ), parent ); - QString after = getStringValue( values.at( 2 ), parent ); - return QVariant( str.replace( before, after ) ); + QVariantList before; + QVariantList after; + bool isSingleReplacement = false; + + if ( values.at( 1 ).type() != QVariant::List && values.at( 2 ).type() != QVariant::StringList ) + { + before = QVariantList() << getStringValue( values.at( 1 ), parent ); + } + else + { + before = getListValue( values.at( 1 ), parent ); + } + + if ( values.at( 2 ).type() != QVariant::List && values.at( 2 ).type() != QVariant::StringList ) + { + after = QVariantList() << getStringValue( values.at( 2 ), parent ); + isSingleReplacement = true; + } + else + { + after = getListValue( values.at( 2 ), parent ); + } + + if ( !isSingleReplacement && before.length() != after.length() ) + { + parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) ); + return QVariant(); + } + + for ( int i = 0; i < before.length(); i++ ) + { + str = str.replace( before.at( i ).toString(), after.at( isSingleReplacement ? 0 : i ).toString() ); + } + + return QVariant( str ); } static QVariant fcnRegexpReplace( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 0d8d068c2c8b..01eb19d3ee11 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -821,6 +821,10 @@ class TestQgsExpression: public QObject QTest::newRow( "upper" ) << "upper('HeLLo')" << false << QVariant( "HELLO" ); QTest::newRow( "length" ) << "length('HeLLo')" << false << QVariant( 5 ); QTest::newRow( "replace" ) << "replace('HeLLo', 'LL', 'xx')" << false << QVariant( "Hexxo" ); + QTest::newRow( "replace (array replaced by array)" ) << "replace('321', array('1','2','3'), array('7','8','9'))" << false << QVariant( "987" ); + QTest::newRow( "replace (array replaced by string)" ) << "replace('12345', array('2','4'), '')" << false << QVariant( "135" ); + QTest::newRow( "replace (unbalanced array, before > after)" ) << "replace('12345', array('1','2','3'), array('6','7'))" << true << QVariant(); + QTest::newRow( "replace (unbalanced array, before < after)" ) << "replace('12345', array('1','2'), array('6','7','8'))" << true << QVariant(); QTest::newRow( "regexp_replace" ) << "regexp_replace('HeLLo','[eL]+', '-')" << false << QVariant( "H-o" ); QTest::newRow( "regexp_replace greedy" ) << "regexp_replace('HeLLo','(?<=H).*L', '-')" << false << QVariant( "H-o" ); QTest::newRow( "regexp_replace non greedy" ) << "regexp_replace('HeLLo','(?<=H).*?L', '-')" << false << QVariant( "H-Lo" ); From a042c9deccc50571452cf7c09e81a04625e45a06 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 20:46:32 +1000 Subject: [PATCH 491/897] Followup 858978, fix failing tests --- src/core/qgsexpression.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index e6a6f6a9ed48..4ba41dab4eb6 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -4963,7 +4963,7 @@ QVariant QgsExpression::NodeColumnRef::eval( QgsExpression *parent, const QgsExp } } - if ( context && context->feature().isValid() ) + if ( context && context->hasVariable( QgsExpressionContext::EXPR_FEATURE ) ) { QgsFeature feature = context->feature(); if ( index >= 0 ) From f456932514c750d4b077a9daaea5ddfbbad3f1c8 Mon Sep 17 00:00:00 2001 From: Denis Rouzaud Date: Wed, 26 Oct 2016 16:25:17 +0200 Subject: [PATCH 492/897] [Postgres] fix writing default value when primary key has varchar columns kudos to @m-kuhn to find and solve this --- src/providers/postgres/qgspostgresprovider.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 0b600accf263..5a8f3ebcb4fc 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1872,7 +1872,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) values += delim + QStringLiteral( "$%1" ).arg( defaultValues.size() + offset ); delim = ','; fieldId << idx; - defaultValues << defaultValue( idx ).toString(); + defaultValues << quotedValue( defaultValue( idx ) ); } } From 642e4a48c72fffb191ace1f77a55a386218ec413 Mon Sep 17 00:00:00 2001 From: Denis Rouzaud Date: Wed, 26 Oct 2016 17:03:06 +0200 Subject: [PATCH 493/897] Revert "[Postgres] fix writing default value when primary key has varchar columns" This reverts commit f456932514c750d4b077a9daaea5ddfbbad3f1c8. --- src/providers/postgres/qgspostgresprovider.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 5a8f3ebcb4fc..0b600accf263 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1872,7 +1872,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) values += delim + QStringLiteral( "$%1" ).arg( defaultValues.size() + offset ); delim = ','; fieldId << idx; - defaultValues << quotedValue( defaultValue( idx ) ); + defaultValues << defaultValue( idx ).toString(); } } From 3fb2d9e4e3ee75632e367644fd229e24ce9a73fb Mon Sep 17 00:00:00 2001 From: nirvn Date: Wed, 26 Oct 2016 17:41:55 +0700 Subject: [PATCH 494/897] [expression] further improve replace() to support a map argument --- resources/function_help/json/replace | 24 ++++++--- src/core/qgsexpression.cpp | 76 ++++++++++++++++++---------- tests/src/core/testqgsexpression.cpp | 1 + 3 files changed, 65 insertions(+), 36 deletions(-) diff --git a/resources/function_help/json/replace b/resources/function_help/json/replace index a5d92b77fee4..0f0ff23dab2f 100644 --- a/resources/function_help/json/replace +++ b/resources/function_help/json/replace @@ -1,12 +1,20 @@ { "name": "replace", "type": "function", - "description": "Returns a string with the supplied string or array of strings replaced by a string or an array of strings.", - "arguments": [ {"arg":"string","description":"the input string"}, - {"arg":"before","description":"the string or array of strings to replace"}, - {"arg":"after","description":"the string or array of strings to use as a replacement"}], - "examples": [ { "expression":"replace('QGIS SHOULD ROCK','SHOULD','DOES')", "returns":"'QGIS DOES ROCK'"}, - { "expression":"replace('QGIS ABC',array('A','B','C'),array('X','Y','Z'))", "returns":"'QGIS XYZ'"}, - { "expression":"replace('QGIS',array('Q','S'),'')", "returns":"'GI'"} - ] + "description": "Returns a string with the supplied string, array, or map of strings replaced.", + "variants": [ + { "variant": "String & array variant", + "variant_description": "Returns a string with the supplied string or array of strings replaced by a string or an array of strings.", + "arguments": [ {"arg":"string","description":"the input string"}, + {"arg":"before","description":"the string or array of strings to replace"}, + {"arg":"after","description":"the string or array of strings to use as a replacement"}], + "examples": [ { "expression":"replace('QGIS SHOULD ROCK','SHOULD','DOES')", "returns":"'QGIS DOES ROCK'"}, + { "expression":"replace('QGIS ABC',array('A','B','C'),array('X','Y','Z'))", "returns":"'QGIS XYZ'"}, + { "expression":"replace('QGIS',array('Q','S'),'')", "returns":"'GI'"} ] }, + { "variant": "Map variant", + "variant_description": "Returns a string with the supplied map keys replaced by paired values.", + "arguments": [ {"arg":"string","description":"the input string"}, + {"arg":"map","description":"the map containing keys and values"} ], + "examples": [ { "expression":"replace('APP SHOULD ROCK',map('APP','QGIS','SHOULD','DOES'))", "returns":"'QGIS DOES ROCK'"} ] + }] } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index e4307700e361..cd17b7777720 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1214,42 +1214,62 @@ static QVariant fcnLength( const QVariantList& values, const QgsExpressionContex static QVariant fcnReplace( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { - QString str = getStringValue( values.at( 0 ), parent ); - QVariantList before; - QVariantList after; - bool isSingleReplacement = false; - - if ( values.at( 1 ).type() != QVariant::List && values.at( 2 ).type() != QVariant::StringList ) + if ( values.count() == 2 && values.at( 1 ).type() == QVariant::Map ) { - before = QVariantList() << getStringValue( values.at( 1 ), parent ); + QString str = getStringValue( values.at( 0 ), parent ); + QVariantMap map = getMapValue( values.at( 1 ), parent ); + + for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it ) + { + str = str.replace( it.key(), it.value().toString() ); + } + + return QVariant( str ); } - else + else if ( values.count() == 3 ) { - before = getListValue( values.at( 1 ), parent ); - } + QString str = getStringValue( values.at( 0 ), parent ); + QVariantList before; + QVariantList after; + bool isSingleReplacement = false; - if ( values.at( 2 ).type() != QVariant::List && values.at( 2 ).type() != QVariant::StringList ) - { - after = QVariantList() << getStringValue( values.at( 2 ), parent ); - isSingleReplacement = true; + if ( values.at( 1 ).type() != QVariant::List && values.at( 2 ).type() != QVariant::StringList ) + { + before = QVariantList() << getStringValue( values.at( 1 ), parent ); + } + else + { + before = getListValue( values.at( 1 ), parent ); + } + + if ( values.at( 2 ).type() != QVariant::List && values.at( 2 ).type() != QVariant::StringList ) + { + after = QVariantList() << getStringValue( values.at( 2 ), parent ); + isSingleReplacement = true; + } + else + { + after = getListValue( values.at( 2 ), parent ); + } + + if ( !isSingleReplacement && before.length() != after.length() ) + { + parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) ); + return QVariant(); + } + + for ( int i = 0; i < before.length(); i++ ) + { + str = str.replace( before.at( i ).toString(), after.at( isSingleReplacement ? 0 : i ).toString() ); + } + + return QVariant( str ); } else { - after = getListValue( values.at( 2 ), parent ); - } - - if ( !isSingleReplacement && before.length() != after.length() ) - { - parent->setEvalErrorString( QObject::tr( "Invalid pair of array, length not identical" ) ); + parent->setEvalErrorString( QObject::tr( "Function replace requires 2 or 3 arguments" ) ); return QVariant(); } - - for ( int i = 0; i < before.length(); i++ ) - { - str = str.replace( before.at( i ).toString(), after.at( isSingleReplacement ? 0 : i ).toString() ); - } - - return QVariant( str ); } static QVariant fcnRegexpReplace( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { @@ -3521,7 +3541,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "char" ), 1, fcnChar, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "wordwrap" ), ParameterList() << Parameter( QStringLiteral( "text" ) ) << Parameter( QStringLiteral( "length" ) ) << Parameter( QStringLiteral( "delimiter" ), true, "" ), fcnWordwrap, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "length" ), ParameterList() << Parameter( QStringLiteral( "text" ), true, "" ), fcnLength, QStringList() << QStringLiteral( "String" ) << QStringLiteral( "GeometryGroup" ) ) - << new StaticFunction( QStringLiteral( "replace" ), 3, fcnReplace, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "replace" ), -1, fcnReplace, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "regexp_replace" ), 3, fcnRegexpReplace, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "regexp_substr" ), 2, fcnRegexpSubstr, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "substr" ), 3, fcnSubstr, QStringLiteral( "String" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 01eb19d3ee11..a35ae35a9e1d 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -825,6 +825,7 @@ class TestQgsExpression: public QObject QTest::newRow( "replace (array replaced by string)" ) << "replace('12345', array('2','4'), '')" << false << QVariant( "135" ); QTest::newRow( "replace (unbalanced array, before > after)" ) << "replace('12345', array('1','2','3'), array('6','7'))" << true << QVariant(); QTest::newRow( "replace (unbalanced array, before < after)" ) << "replace('12345', array('1','2'), array('6','7','8'))" << true << QVariant(); + QTest::newRow( "replace (map)" ) << "replace('APP SHOULD ROCK',map('APP','QGIS','SHOULD','DOES'))" << false << QVariant( "QGIS DOES ROCK" ); QTest::newRow( "regexp_replace" ) << "regexp_replace('HeLLo','[eL]+', '-')" << false << QVariant( "H-o" ); QTest::newRow( "regexp_replace greedy" ) << "regexp_replace('HeLLo','(?<=H).*L', '-')" << false << QVariant( "H-o" ); QTest::newRow( "regexp_replace non greedy" ) << "regexp_replace('HeLLo','(?<=H).*?L', '-')" << false << QVariant( "H-Lo" ); From 8a809b8700d37e54b818638ff3922425886e5a59 Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 27 Oct 2016 11:54:35 +0700 Subject: [PATCH 495/897] [map themes] fix composer signal name --- src/app/composer/qgscomposermapwidget.cpp | 8 ++++---- src/app/composer/qgscomposermapwidget.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/app/composer/qgscomposermapwidget.cpp b/src/app/composer/qgscomposermapwidget.cpp index fc6240f9b066..7f907479358d 100644 --- a/src/app/composer/qgscomposermapwidget.cpp +++ b/src/app/composer/qgscomposermapwidget.cpp @@ -67,9 +67,9 @@ QgsComposerMapWidget::QgsComposerMapWidget( QgsComposerMap* composerMap ) // follow preset combo mFollowVisibilityPresetCombo->setModel( new QStringListModel( mFollowVisibilityPresetCombo ) ); connect( mFollowVisibilityPresetCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( followVisibilityPresetSelected( int ) ) ); - connect( QgsProject::instance()->mapThemeCollection(), SIGNAL( presetsChanged() ), - this, SLOT( onPresetsChanged() ) ); - onPresetsChanged(); + connect( QgsProject::instance()->mapThemeCollection(), SIGNAL( mapThemesChanged() ), + this, SLOT( onMapThemesChanged() ) ); + onMapThemesChanged(); // keep layers from preset button QMenu* menuKeepLayers = new QMenu( this ); @@ -213,7 +213,7 @@ void QgsComposerMapWidget::keepLayersVisibilityPresetSelected() } } -void QgsComposerMapWidget::onPresetsChanged() +void QgsComposerMapWidget::onMapThemesChanged() { if ( QStringListModel* model = qobject_cast( mFollowVisibilityPresetCombo->model() ) ) { diff --git a/src/app/composer/qgscomposermapwidget.h b/src/app/composer/qgscomposermapwidget.h index 4390356f5540..7e0d8709c9bb 100644 --- a/src/app/composer/qgscomposermapwidget.h +++ b/src/app/composer/qgscomposermapwidget.h @@ -116,7 +116,7 @@ class QgsComposerMapWidget: public QgsComposerItemBaseWidget, private Ui::QgsCom void followVisibilityPresetSelected( int currentIndex ); void keepLayersVisibilityPresetSelected(); - void onPresetsChanged(); + void onMapThemesChanged(); void updateOverviewFrameStyleFromWidget(); void cleanUpOverviewFrameStyleSelector( QgsPanelWidget* container ); From e67a47b9abe40ad4b143db7a09c52ff6cd39270c Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 27 Oct 2016 11:57:38 +0200 Subject: [PATCH 496/897] [OGR provider] Do not list qgis_projects (from QgisGeoPackage plugin) as sublayer --- src/providers/ogr/qgsogrprovider.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index ac0d02fe8b41..4a7e242d48f0 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -682,9 +682,11 @@ QStringList QgsOgrProvider::subLayers() const continue; } - if ( !mIsSubLayer && theLayerName == "layer_styles" ) + if ( !mIsSubLayer && ( theLayerName == QLatin1String( "layer_styles" ) || + theLayerName == QLatin1String( "qgis_projects" ) ) ) { - // Ignore layer_styles layer + // Ignore layer_styles (coming from QGIS styling support) and + // qgis_projects (coming from http://plugins.qgis.org/plugins/QgisGeopackage/) continue; } From 472a5501689c6165fd10e54c20cf1cc3e85646d5 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 27 Oct 2016 14:28:36 +0200 Subject: [PATCH 497/897] [processing] fixed field loading in field calculator fixes #15767 Conflicts: python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py --- .../plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py index 58d5822b1071..e87cf85c3997 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py @@ -91,6 +91,7 @@ def manageGui(self): self.builder.loadRecent('fieldcalc') self.initContext() + self.updateLayer() def initContext(self): exp_context = self.builder.expressionContext() @@ -171,7 +172,8 @@ def toggleNewGroup(self, toggled): def populateFields(self): if self.layer is None: return - + + self.mExistingFieldComboBox.clear() fields = self.layer.fields() for f in fields: self.mExistingFieldComboBox.addItem(f.name()) From b58229009be3ffba7bee71707c9180237a3b2cb6 Mon Sep 17 00:00:00 2001 From: volaya Date: Thu, 27 Oct 2016 14:30:18 +0200 Subject: [PATCH 498/897] indentation fix --- .../plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py index e87cf85c3997..63b718687917 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsCalculatorDialog.py @@ -172,7 +172,7 @@ def toggleNewGroup(self, toggled): def populateFields(self): if self.layer is None: return - + self.mExistingFieldComboBox.clear() fields = self.layer.fields() for f in fields: From 984ec65fcdedcdc97d63081d943c8fa669fc4c6a Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 27 Oct 2016 15:59:57 +0200 Subject: [PATCH 499/897] [DBManager GPKG] Set appropriate icon for line layers --- python/plugins/db_manager/db_model.py | 4 +- .../db_manager/db_plugins/gpkg/connector.py | 26 +++++++++++- tests/src/python/test_db_manager_gpkg.py | 42 ++++++++++++++++++- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/python/plugins/db_manager/db_model.py b/python/plugins/db_manager/db_model.py index 2485fd3bf905..3de6f0430952 100644 --- a/python/plugins/db_manager/db_model.py +++ b/python/plugins/db_manager/db_model.py @@ -256,9 +256,9 @@ def icon(self): if geom_type is not None: if geom_type.find('POINT') != -1: return self.layerPointIcon - elif geom_type.find('LINESTRING') != -1: + elif geom_type.find('LINESTRING') != -1 or geom_type in ('CIRCULARSTRING', 'COMPOUNDCURVE', 'MULTICURVE'): return self.layerLineIcon - elif geom_type.find('POLYGON') != -1: + elif geom_type.find('POLYGON') != -1 or geom_type == 'MULTISURFACE': return self.layerPolygonIcon return self.layerUnknownIcon diff --git a/python/plugins/db_manager/db_plugins/gpkg/connector.py b/python/plugins/db_manager/db_plugins/gpkg/connector.py index 0d846a61e9ed..98fe456eafc1 100644 --- a/python/plugins/db_manager/db_plugins/gpkg/connector.py +++ b/python/plugins/db_manager/db_plugins/gpkg/connector.py @@ -300,7 +300,31 @@ def getVectorTables(self, schema=None): geomtype_flatten = ogr.GT_Flatten(geomtype) else: geomtype_flatten = geomtype - geomname = ogr.GeometryTypeToName(geomtype_flatten).upper() + if geomtype_flatten == ogr.wkbPoint: + geomname = 'POINT' + elif geomtype_flatten == ogr.wkbLineString: + geomname = 'LINESTRING' + elif geomtype_flatten == ogr.wkbPolygon: + geomname = 'POLYGON' + elif geomtype_flatten == ogr.wkbMultiPoint: + geomname = 'MULTIPOINT' + elif geomtype_flatten == ogr.wkbMultiLineString: + geomname = 'MULTILINESTRING' + elif geomtype_flatten == ogr.wkbMultiPolygon: + geomname = 'MULTIPOLYGON' + elif geomtype_flatten == ogr.wkbGeometryCollection: + geomname = 'GEOMETRYCOLLECTION' + if self.gdal2: + if geomtype_flatten == ogr.wkbCircularString: + geomname = 'CIRCULARSTRING' + elif geomtype_flatten == ogr.wkbCompoundCurve: + geomname = 'COMPOUNDCURVE' + elif geomtype_flatten == ogr.wkbCurvePolygon: + geomname = 'CURVEPOLYGON' + elif geomtype_flatten == ogr.wkbMultiCurve: + geomname = 'MULTICURVE' + elif geomtype_flatten == ogr.wkbMultiSurface: + geomname = 'MULTISURFACE' geomdim = 'XY' if hasattr(ogr, 'GT_HasZ') and ogr.GT_HasZ(lyr.GetGeomType()): geomdim += 'Z' diff --git a/tests/src/python/test_db_manager_gpkg.py b/tests/src/python/test_db_manager_gpkg.py index da86e4fc86d4..5b92ed1d39d3 100644 --- a/tests/src/python/test_db_manager_gpkg.py +++ b/tests/src/python/test_db_manager_gpkg.py @@ -127,7 +127,7 @@ def testListLayer(self): table = tables[0] self.assertEqual(table.name, 'testLayer') info = table.info() - expected_html = """

                                                                                                                                                                                    General info

                                                                                                                                                                                    Relation type: Table 
                                                                                                                                                                                    Rows: 

                                                                                                                                                                                    GeoPackage

                                                                                                                                                                                    Column: geom 
                                                                                                                                                                                    Geometry: LINE STRING 
                                                                                                                                                                                    Dimension: XY 
                                                                                                                                                                                    Spatial ref: Undefined (-1) 
                                                                                                                                                                                    Extent: 1.00000, 2.00000 - 3.00000, 4.00000 

                                                                                                                                                                                    No spatial index defined (create it)

                                                                                                                                                                                    Fields

                                                                                                                                                                                    Name Type Null Default 
                                                                                                                                                                                    fid INTEGER  
                                                                                                                                                                                    geom LINESTRING  
                                                                                                                                                                                    text_field TEXT  
                                                                                                                                                                                    """ + expected_html = """

                                                                                                                                                                                    General info

                                                                                                                                                                                    Relation type: Table 
                                                                                                                                                                                    Rows: 

                                                                                                                                                                                    GeoPackage

                                                                                                                                                                                    Column: geom 
                                                                                                                                                                                    Geometry: LINESTRING 
                                                                                                                                                                                    Dimension: XY 
                                                                                                                                                                                    Spatial ref: Undefined (-1) 
                                                                                                                                                                                    Extent: 1.00000, 2.00000 - 3.00000, 4.00000 

                                                                                                                                                                                    No spatial index defined (create it)

                                                                                                                                                                                    Fields

                                                                                                                                                                                    Name Type Null Default 
                                                                                                                                                                                    fid INTEGER  
                                                                                                                                                                                    geom LINESTRING  
                                                                                                                                                                                    text_field TEXT  
                                                                                                                                                                                    """ self.assertEqual(info.toHtml(), expected_html, info.toHtml()) connection.remove() @@ -389,5 +389,45 @@ def testNonSpatial(self): connection.remove() + def testAllGeometryTypes(self): + + connection_name = 'testAllGeometryTypes' + plugin = createDbPlugin('gpkg') + uri = QgsDataSourceUri() + + test_gpkg = os.path.join(self.basetestpath, 'testAllGeometryTypes.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(test_gpkg) + ds.CreateLayer('testPoint', geom_type=ogr.wkbPoint) + ds.CreateLayer('testLineString', geom_type=ogr.wkbLineString) + ds.CreateLayer('testPolygon', geom_type=ogr.wkbPolygon) + ds.CreateLayer('testMultiPoint', geom_type=ogr.wkbMultiPoint) + ds.CreateLayer('testMultiLineString', geom_type=ogr.wkbMultiLineString) + ds.CreateLayer('testMultiPolygon', geom_type=ogr.wkbMultiPolygon) + ds.CreateLayer('testGeometryCollection', geom_type=ogr.wkbGeometryCollection) + + if int(gdal.VersionInfo('VERSION_NUM')) >= GDAL_COMPUTE_VERSION(2, 0, 0): + ds.CreateLayer('testCircularString', geom_type=ogr.wkbCircularString) + ds.CreateLayer('testCompoundCurve', geom_type=ogr.wkbCompoundCurve) + ds.CreateLayer('testCurvePolygon', geom_type=ogr.wkbCurvePolygon) + ds.CreateLayer('testMultiCurve', geom_type=ogr.wkbMultiCurve) + ds.CreateLayer('testMultiSurface', geom_type=ogr.wkbMultiSurface) + ds = None + + uri.setDatabase(test_gpkg) + self.assertTrue(plugin.addConnection(connection_name, uri)) + + connection = createDbPlugin('gpkg', connection_name) + connection.connect() + + db = connection.database() + self.assertIsNotNone(db) + + tables = db.tables() + for i in range(len(tables)): + table = tables[i] + info = table.info() + + connection.remove() + if __name__ == '__main__': unittest.main() From 631db7b8e63a7385cbba0ea21136265b66ede4db Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 27 Oct 2016 16:57:36 +0200 Subject: [PATCH 500/897] [OGR provider] Fix declaration of types (master regression) and update more sensible values for min/max length --- src/providers/ogr/qgsogrprovider.cpp | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 4a7e242d48f0..6c18aaec6829 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -402,26 +402,27 @@ QgsOgrProvider::QgsOgrProvider( QString const & uri ) open( OpenModeInitial ); - setNativeTypes( QList() - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 1, 10 ) + QList nativeTypes; + nativeTypes + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 11 ) #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 - << QgsVectorDataProvider::NativeType( tr( "Whole number (integer 64 bit)" ), "integer64", QVariant::LongLong, 1, 10 ) + << QgsVectorDataProvider::NativeType( tr( "Whole number (integer 64 bit)" ), "integer64", QVariant::LongLong, 0, 21 ) #endif - << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double" ), QVariant::Double, 1, 20, 0, 15 ) - << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), QStringLiteral( "string" ), QVariant::String, 1, 255 ) - << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, 8, 8 ) - ); + << QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double" ), QVariant::Double, 0, 20, 0, 15 ) + << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), QStringLiteral( "string" ), QVariant::String, 0, 65535 ) + << QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, 8, 8 ); // Some drivers do not support datetime type // Please help to fill this list if ( ogrDriverName != QLatin1String( "ESRI Shapefile" ) ) { - setNativeTypes( QList() - << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1 ) - << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime ) - ); + nativeTypes + << QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1 ) + << QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime ); } + setNativeTypes( nativeTypes ); + QgsOgrConnPool::instance()->ref( dataSourceUri() ); } From 7373036edf6e9e549a0871f6f778f13b7f6902d8 Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 27 Oct 2016 13:53:58 +0700 Subject: [PATCH 501/897] [FEATURE] add string_to_array() and array_to_string() functions --- resources/function_help/json/array_to_string | 12 ++++++ resources/function_help/json/string_to_array | 12 ++++++ src/core/qgsexpression.cpp | 39 ++++++++++++++++++++ tests/src/core/testqgsexpression.cpp | 5 +++ 4 files changed, 68 insertions(+) create mode 100644 resources/function_help/json/array_to_string create mode 100644 resources/function_help/json/string_to_array diff --git a/resources/function_help/json/array_to_string b/resources/function_help/json/array_to_string new file mode 100644 index 000000000000..2fbfcb85838e --- /dev/null +++ b/resources/function_help/json/array_to_string @@ -0,0 +1,12 @@ +{ + "name": "array_to_string", + "type": "function", + "description": "Concatenates array elements into a string separated by a delimiter using and optional string for empty values.", + "arguments": [ + {"arg":"array", "description":"the input array"}, + {"arg":"delimiter","optional":true,"default":"','","description":"the string delimiter used to separate concatenated array elements"}, + {"arg":"emptyvalue","optional":true,"default":"''","description":"the optional string to use as replacement to empty values"}], + "examples": [ { "expression":"array_to_string(array('1','2','3'),',')", "returns":"'1,2,3'"}, + { "expression":"array_to_string(array('1','','3'),',','0')", "returns":"'1,0,3'"} + ] +} diff --git a/resources/function_help/json/string_to_array b/resources/function_help/json/string_to_array new file mode 100644 index 000000000000..595b60cc1cdf --- /dev/null +++ b/resources/function_help/json/string_to_array @@ -0,0 +1,12 @@ +{ + "name": "string_to_array", + "type": "function", + "description": "Splits string into an array using supplied delimiter and optional string for empty values.", + "arguments": [ + {"arg":"string", "description":"the input string"}, + {"arg":"delimiter","optional":true,"default":"','","description":"the string delimiter used to split the input string"}, + {"arg":"emptyvalue","optional":true,"default":"''","description":"the optional string to use as replacement to empty values"}], + "examples": [ { "expression":"string_to_array('1,2,3',',')", "returns":"array: '1', '2', '3'"}, + { "expression":"string_to_array('1,,3',',','0')", "returns":"array: '1', '0', '3'"} + ] +} diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 2ca74e461c89..163d2c7a98f1 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3335,6 +3335,43 @@ static QVariant fcnArrayIntersect( const QVariantList& values, const QgsExpressi return QVariant( false ); } +static QVariant fcnArrayToString( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QVariantList array = getListValue( values.at( 0 ), parent ); + QString delimiter = getStringValue( values.at( 1 ), parent ); + QString empty = getStringValue( values.at( 2 ), parent ); + + QString str; + + for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it ) + { + str += ( *it ).toString().isEmpty() == false ? ( *it ).toString() : empty; + if ( it != ( array.constEnd() - 1 ) ) + { + str += delimiter; + } + } + + return QVariant( str ); +} + +static QVariant fcnStringToArray( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QString str = getStringValue( values.at( 0 ), parent ); + QString delimiter = getStringValue( values.at( 1 ), parent ); + QString empty = getStringValue( values.at( 2 ), parent ); + + QStringList list = str.split( delimiter ); + QVariantList array; + + for ( QStringList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it ) + { + array += ( *it ).isEmpty() == false ? *it : empty; + } + + return array; +} + static QVariant fcnMap( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { QVariantMap result; @@ -3691,6 +3728,8 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "array_remove_all" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayRemoveAll, QStringLiteral( "Arrays" ) ) << new StaticFunction( QStringLiteral( "array_cat" ), -1, fcnArrayCat, QStringLiteral( "Arrays" ) ) << new StaticFunction( QStringLiteral( "array_intersect" ), ParameterList() << Parameter( QStringLiteral( "array1" ) ) << Parameter( QStringLiteral( "array2" ) ), fcnArrayIntersect, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_to_string" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "delimiter" ), true, "," ) << Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnArrayToString, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "string_to_array" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "delimiter" ), true, "," ) << Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnStringToArray, QStringLiteral( "Arrays" ) ) //functions for maps << new StaticFunction( QStringLiteral( "map" ), -1, fcnMap, QStringLiteral( "Maps" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index a35ae35a9e1d..d6f3ba252b35 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -859,6 +859,9 @@ class TestQgsExpression: public QObject QTest::newRow( "concat" ) << "concat('a', 'b', 'c', 'd')" << false << QVariant( "abcd" ); QTest::newRow( "concat function single" ) << "concat('a')" << false << QVariant( "a" ); QTest::newRow( "concat function with NULL" ) << "concat(NULL,'a','b')" << false << QVariant( "ab" ); + QTest::newRow( "array_to_string" ) << "array_to_string(array(1,2,3),',')" << false << QVariant( "1,2,3" ); + QTest::newRow( "array_to_string with custom empty value" ) << "array_to_string(array(1,'',3),',','*')" << false << QVariant( "1,*,3" ); + QTest::newRow( "array_to_string fail passing non-array" ) << "array_to_string('non-array',',')" << true << QVariant(); //fuzzy matching QTest::newRow( "levenshtein" ) << "levenshtein('kitten','sitting')" << false << QVariant( 3 ); @@ -2180,8 +2183,10 @@ class TestQgsExpression: public QObject QCOMPARE( QgsExpression( "array()" ).evaluate( &context ), QVariant( ) ); builderExpected << "hello"; QCOMPARE( QgsExpression( "array('hello')" ).evaluate( &context ), QVariant( builderExpected ) ); + QCOMPARE( QgsExpression( "string_to_array('hello',',')" ).evaluate( &context ), QVariant( builderExpected ) ); builderExpected << "world"; QCOMPARE( QgsExpression( "array('hello', 'world')" ).evaluate( &context ), QVariant( builderExpected ) ); + QCOMPARE( QgsExpression( "string_to_array('hello,world',',')" ).evaluate( &context ), QVariant( builderExpected ) ); QCOMPARE( QgsExpression( "array_length(\"strings\")" ).evaluate( &context ), QVariant( 2 ) ); From f52dfba21ed4b21a224b2a39013bf6fae101a15d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 27 Oct 2016 14:43:56 +0200 Subject: [PATCH 502/897] [expressions] Variable length arguemnt functions accept 0 params --- src/core/qgsexpressionparser.yy | 4 +++- tests/src/core/testqgsexpression.cpp | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/core/qgsexpressionparser.yy b/src/core/qgsexpressionparser.yy index 57af2a5e60e3..8f1d7335e78e 100644 --- a/src/core/qgsexpressionparser.yy +++ b/src/core/qgsexpressionparser.yy @@ -223,7 +223,9 @@ expression: exp_error(parser_ctx, "Function is not known"); YYERROR; } - if ( QgsExpression::Functions()[fnIndex]->params() != 0 ) + // 0 parameters is expected, -1 parameters means leave it to the + // implementation + if ( QgsExpression::Functions()[fnIndex]->params() > 0 ) { exp_error(parser_ctx, QString( "%1 function is called with wrong number of arguments" ).arg( QgsExpression::Functions()[fnIndex]->name() ).toLocal8Bit().constData() ); YYERROR; diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index a35ae35a9e1d..87b66047fd56 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -2177,7 +2177,7 @@ class TestQgsExpression: public QObject QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); QVariantList builderExpected; - QCOMPARE( QgsExpression( "array()" ).evaluate( &context ), QVariant( ) ); + QCOMPARE( QgsExpression( "array()" ).evaluate( &context ), QVariant( builderExpected ) ); builderExpected << "hello"; QCOMPARE( QgsExpression( "array('hello')" ).evaluate( &context ), QVariant( builderExpected ) ); builderExpected << "world"; @@ -2303,7 +2303,7 @@ class TestQgsExpression: public QObject QgsExpressionContext context = QgsExpressionContextUtils::createFeatureBasedContext( f, QgsFields() ); QVariantMap builderExpected; - QCOMPARE( QgsExpression( "map()" ).evaluate( &context ), QVariant( ) ); + QCOMPARE( QgsExpression( "map()" ).evaluate( &context ), QVariant( builderExpected ) ); builderExpected[QStringLiteral( "1" )] = "hello"; QCOMPARE( QgsExpression( "map('1', 'hello')" ).evaluate( &context ), QVariant( builderExpected ) ); builderExpected[QStringLiteral( "2" )] = "world"; From 01f3c9ae38de51e82a4a18a48488695deb51f72f Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 27 Oct 2016 14:45:13 +0200 Subject: [PATCH 503/897] [FEATURE] Add is_selected and num_selected functions * is_selected() returns if the current feature is selected * num_selected() returns the number of selected features on the current layer * is_selected(layer, feature) returns if the "feature" is selected. "feature" must be on "layer". * num_selected(layer) returns the number of selected features on "layer" --- resources/function_help/json/is_selected | 13 +++ resources/function_help/json/num_selected | 12 +++ src/core/qgsexpression.cpp | 106 ++++++++++++++++++++-- src/core/qgsexpressioncontext.cpp | 1 + src/core/qgsexpressioncontext.h | 2 +- tests/src/core/testqgsexpression.cpp | 49 ++++++++++ 6 files changed, 173 insertions(+), 10 deletions(-) create mode 100644 resources/function_help/json/is_selected create mode 100644 resources/function_help/json/num_selected diff --git a/resources/function_help/json/is_selected b/resources/function_help/json/is_selected new file mode 100644 index 000000000000..ca1e7a4344d0 --- /dev/null +++ b/resources/function_help/json/is_selected @@ -0,0 +1,13 @@ +{ + "name": "is_selected", + "type": "function", + "description": "Returns if a feature is selected. If called with no parameters checks the current feature.", + "arguments": [ + {"arg":"feature","description":"The feature which should be checked for selection"}, + {"arg":"layer","description":"The layer (or its id or name) on which the selection will be checked"} + ], + "examples": [ + { "expression":"is_selected()", "returns" : "True if the current feature is selected."}, + { "expression":"is_selected(get_feature('streets', 'name', \"street_name\"), 'streets')", "returns":"True if the current building's street is selected."} + ] +} diff --git a/resources/function_help/json/num_selected b/resources/function_help/json/num_selected new file mode 100644 index 000000000000..7c61f288bf3e --- /dev/null +++ b/resources/function_help/json/num_selected @@ -0,0 +1,12 @@ +{ + "name": "num_selected", + "type": "function", + "description": "Returns the number of selected features on a given layer. By default works on the layer on which the expression is evaluated.", + "arguments": [ + {"arg":"layer","description":"The layer (or its id or name) on which the selection will be checked"} + ], + "examples": [ + { "expression":"num_selected()", "returns":"The number of selected features on the current layer."}, + { "expression":"num_selected('streets')", "returns":"The number of selected features on the layer streets"} + ] +} diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 2ca74e461c89..46b2208b921d 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -312,14 +312,19 @@ static QgsExpression::Node* getNode( const QVariant& value, QgsExpression* paren QgsVectorLayer* getVectorLayer( const QVariant& value, QgsExpression* ) { - QString layerString = value.toString(); - QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerString ) ); //search by id first + QgsVectorLayer* vl = value.value(); if ( !vl ) { - QList layersByName = QgsMapLayerRegistry::instance()->mapLayersByName( layerString ); - if ( !layersByName.isEmpty() ) + QString layerString = value.toString(); + vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerString ) ); //search by id first + + if ( !vl ) { - vl = qobject_cast( layersByName.at( 0 ) ); + QList layersByName = QgsMapLayerRegistry::instance()->mapLayersByName( layerString ); + if ( !layersByName.isEmpty() ) + { + vl = qobject_cast( layersByName.at( 0 ) ); + } } } @@ -707,8 +712,7 @@ static QVariant fcnAggregateRelation( const QVariantList& values, const QgsExpre } // first step - find current layer - QString layerId = context->variable( QStringLiteral( "layer_id" ) ).toString(); - QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerId ) ); + QgsVectorLayer* vl = getVectorLayer( context->variable( "layer" ), parent ); if ( !vl ) { parent->setEvalErrorString( QObject::tr( "Cannot use relation aggregate function in this context" ) ); @@ -810,8 +814,7 @@ static QVariant fcnAggregateGeneric( QgsAggregateCalculator::Aggregate aggregate } // first step - find current layer - QString layerId = context->variable( QStringLiteral( "layer_id" ) ).toString(); - QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( layerId ) ); + QgsVectorLayer* vl = getVectorLayer( context->variable( "layer" ), parent ); if ( !vl ) { parent->setEvalErrorString( QObject::tr( "Cannot use aggregate function in this context" ) ); @@ -1358,6 +1361,63 @@ static QVariant fcnAttribute( const QVariantList& values, const QgsExpressionCon return feat.attribute( attr ); } + +static QVariant fcnIsSelected( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ) +{ + QgsVectorLayer* layer = nullptr; + QgsFeature feature; + + if ( values.isEmpty() ) + { + feature = context->feature(); + layer = getVectorLayer( context->variable( "layer" ), parent ); + } + else if ( values.size() == 1 ) + { + layer = getVectorLayer( context->variable( "layer" ), parent ); + feature = getFeature( values.at( 0 ), parent ); + } + else if ( values.size() == 2 ) + { + layer = getVectorLayer( values.at( 0 ), parent ); + feature = getFeature( values.at( 1 ), parent ); + } + else + { + parent->setEvalErrorString( QObject::tr( "Function `is_selected` requires no more than two parameters. %1 given." ).arg( values.length() ) ); + return QVariant(); + } + + if ( !layer || !feature.isValid() ) + { + return QVariant( QVariant::Bool ); + } + + return layer->selectedFeaturesIds().contains( feature.id() ); +} + +static QVariant fcnNumSelected( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ) +{ + QgsVectorLayer* layer = nullptr; + + if ( values.isEmpty() ) + layer = getVectorLayer( context->variable( "layer" ), parent ); + else if ( values.count() == 1 ) + layer = getVectorLayer( values.at( 0 ), parent ); + else + { + parent->setEvalErrorString( QObject::tr( "Function `num_selected` requires no more than one parameter. %1 given." ).arg( values.length() ) ); + return QVariant(); + } + + if ( !layer ) + { + return QVariant( QVariant::LongLong ); + } + + return layer->selectedFeatureCount(); +} + static QVariant fcnConcat( const QVariantList& values, const QgsExpressionContext*, QgsExpression *parent ) { QString concat; @@ -3665,10 +3725,37 @@ const QList& QgsExpression::Functions() << Parameter( QStringLiteral( "vertex" ) ), fcnAngleAtVertex, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "distance_to_vertex" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) << Parameter( QStringLiteral( "vertex" ) ), fcnDistanceToVertex, QStringLiteral( "GeometryGroup" ) ) + + + // **Record** functions + << new StaticFunction( QStringLiteral( "$id" ), 0, fcnFeatureId, QStringLiteral( "Record" ) ) << new StaticFunction( QStringLiteral( "$currentfeature" ), 0, fcnFeature, QStringLiteral( "Record" ) ) << new StaticFunction( QStringLiteral( "uuid" ), 0, fcnUuid, QStringLiteral( "Record" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "$uuid" ) ) << new StaticFunction( QStringLiteral( "get_feature" ), 3, fcnGetFeature, QStringLiteral( "Record" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "getFeature" ) ) + + << new StaticFunction( + QStringLiteral( "is_selected" ), + -1, + fcnIsSelected, + QStringLiteral( "Record" ), + QString(), + false, + QSet() + ) + + << new StaticFunction( + QStringLiteral( "num_selected" ), + -1, + fcnNumSelected, + QStringLiteral( "Record" ), + QString(), + false, + QSet() + ) + + // **General** functions + << new StaticFunction( QStringLiteral( "layer_property" ), 2, fcnGetLayerProperty, QStringLiteral( "General" ) ) << new StaticFunction( QStringLiteral( "var" ), 1, fcnGetVariable, QStringLiteral( "General" ) ) @@ -5290,6 +5377,7 @@ void QgsExpression::initVariableHelp() //layer variables gVariableHelpTexts.insert( QStringLiteral( "layer_name" ), QCoreApplication::translate( "variable_help", "Name of current layer." ) ); gVariableHelpTexts.insert( QStringLiteral( "layer_id" ), QCoreApplication::translate( "variable_help", "ID of current layer." ) ); + gVariableHelpTexts.insert( QStringLiteral( "layer" ), QCoreApplication::translate( "variable_help", "The current layer." ) ); //composition variables gVariableHelpTexts.insert( QStringLiteral( "layout_numpages" ), QCoreApplication::translate( "variable_help", "Number of pages in composition." ) ); diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index cd150b2fa7f6..c7a1cbbfd72a 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -691,6 +691,7 @@ QgsExpressionContextScope* QgsExpressionContextUtils::layerScope( const QgsMapLa scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer_name" ), layer->name(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer_id" ), layer->id(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer" ), QVariant::fromValue( const_cast( layer ) ), true ) ); const QgsVectorLayer* vLayer = dynamic_cast< const QgsVectorLayer* >( layer ); if ( vLayer ) diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index 02462ae71bb2..fa59d6a403e1 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -581,7 +581,7 @@ class CORE_EXPORT QgsExpressionContextUtils /** Creates a new scope which contains variables and functions relating to a QgsMapLayer. * For instance, layer name, id and fields. */ - static QgsExpressionContextScope* layerScope( const QgsMapLayer *layer ); + static QgsExpressionContextScope* layerScope( const QgsMapLayer* layer ); /** Sets a layer context variable. This variable will be contained within scopes retrieved via * layerScope(). diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 87b66047fd56..727aaa3fe942 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1355,6 +1355,55 @@ class TestQgsExpression: public QObject QTest::newRow( "group by expression" ) << "sum(\"col1\", \"col1\" % 2)" << false << QVariant( 16 ); } + void selection() + { + QFETCH( QgsFeatureIds, selectedFeatures ); + QFETCH( QString, expression ); + QFETCH( QVariant, result ); + QFETCH( QgsFeature, feature ); + QFETCH( QgsVectorLayer*, layer ); + + QgsExpressionContext context; + if ( layer ) + context.appendScope( QgsExpressionContextUtils::layerScope( layer ) ); + + QgsFeatureIds backupSelection = mMemoryLayer->selectedFeaturesIds(); + context.setFeature( feature ); + + mMemoryLayer->selectByIds( selectedFeatures ); + + QgsExpression exp( expression ); + QCOMPARE( exp.parserErrorString(), QString( "" ) ); + exp.prepare( &context ); + QVariant res = exp.evaluate( &context ); + QCOMPARE( res, result ); + + mMemoryLayer->selectByIds( backupSelection ); + } + + void selection_data() + { + QTest::addColumn( "expression" ); + QTest::addColumn( "selectedFeatures" ); + QTest::addColumn( "feature" ); + QTest::addColumn( "layer" ); + QTest::addColumn( "result" ); + + QgsFeature firstFeature = mMemoryLayer->getFeature( 1 ); + QgsVectorLayer* noLayer = nullptr; + + QTest::newRow( "empty selection num_selected" ) << "num_selected()" << QgsFeatureIds() << firstFeature << mMemoryLayer << QVariant( 0 ); + QTest::newRow( "empty selection is_selected" ) << "is_selected()" << QgsFeatureIds() << firstFeature << mMemoryLayer << QVariant( false ); + QTest::newRow( "two_selected" ) << "num_selected()" << ( QgsFeatureIds() << 1 << 2 ) << firstFeature << mMemoryLayer << QVariant( 2 ); + QTest::newRow( "is_selected" ) << "is_selected()" << ( QgsFeatureIds() << 1 << 2 ) << firstFeature << mMemoryLayer << QVariant( true ); + QTest::newRow( "not_selected" ) << "is_selected()" << ( QgsFeatureIds() << 4 << 2 ) << firstFeature << mMemoryLayer << QVariant( false ); + QTest::newRow( "no layer num_selected" ) << "num_selected()" << ( QgsFeatureIds() << 4 << 2 ) << QgsFeature() << noLayer << QVariant( QVariant::LongLong ); + QTest::newRow( "no layer is_selected" ) << "is_selected()" << ( QgsFeatureIds() << 4 << 2 ) << QgsFeature() << noLayer << QVariant( QVariant::Bool ); + QTest::newRow( "no layer num_selected" ) << "num_selected()" << ( QgsFeatureIds() << 4 << 2 ) << QgsFeature() << noLayer << QVariant( QVariant::LongLong ); + QTest::newRow( "is_selected with params" ) << "is_selected('test', get_feature('test', 'col1', 10))" << ( QgsFeatureIds() << 4 << 2 ) << QgsFeature() << noLayer << QVariant( QVariant::Bool ); + QTest::newRow( "num_selected with params" ) << "num_selected('test')" << ( QgsFeatureIds() << 4 << 2 ) << QgsFeature() << noLayer << QVariant( 2 ); + } + void layerAggregates() { QgsExpressionContext context; From dcad93ac045c8867d3aeceb3d1f562eb8bd2c5db Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 27 Oct 2016 17:12:54 +0200 Subject: [PATCH 504/897] Vector layer properties GUI: tweak message to be "Save in database (GeoPackage)" for GeoPackage --- src/app/qgsvectorlayerproperties.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/app/qgsvectorlayerproperties.cpp b/src/app/qgsvectorlayerproperties.cpp index a69813ed401d..c29291581772 100644 --- a/src/app/qgsvectorlayerproperties.cpp +++ b/src/app/qgsvectorlayerproperties.cpp @@ -172,7 +172,14 @@ QgsVectorLayerProperties::QgsVectorLayerProperties( this, SLOT( loadStyleMenuTriggered( QAction * ) ) ); //for saving - mSaveAsMenu->addAction( tr( "Save in database (%1)" ).arg( mLayer->providerType() ) ); + QString providerName = mLayer->providerType(); + if ( providerName == "ogr" ) + { + providerName = mLayer->dataProvider()->storageType(); + if ( providerName == "GPKG" ) + providerName = "GeoPackage"; + } + mSaveAsMenu->addAction( tr( "Save in database (%1)" ).arg( providerName ) ); } QObject::connect( mSaveAsMenu, SIGNAL( triggered( QAction * ) ), From 0f7babb682287d23bf43305f5d75a60d64ddc334 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 27 Oct 2016 14:45:13 +0200 Subject: [PATCH 505/897] Convert API break document to markdown --- doc/api_break.dox | 2438 ++++++++++++++++++++++++--------------------- 1 file changed, 1293 insertions(+), 1145 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index e61406f6313f..e146da2f70bf 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -16,9 +16,11 @@ with too big impact should be deferred to a major version release. This page tries to maintain a list with incompatible changes that happened in previous releases. -\section qgis_api_break_3_0 QGIS 3.0 +QGIS 3.0 {#qgis_api_break_3_0} +======== -\subsection qgis_api_break_3_0_moved_classes Moved Classes +Moved Classes {#qgis_api_break_3_0_moved_classes} +------------- @@ -27,7 +29,8 @@ This page tries to maintain a list with incompatible changes that happened in pr
                                                                                                                                                                                    Moved classes
                                                                                                                                                                                    QgsMapLayerProxyModelguicore
                                                                                                                                                                                    -\subsection qgis_api_break_3_0_renamed_classes Renamed Classes +Renamed Classes {#qgis_api_break_3_0_renamed_classes} +--------------- @@ -175,1363 +178,1508 @@ This page tries to maintain a list with incompatible changes that happened in pr
                                                                                                                                                                                    Renamed classes
                                                                                                                                                                                    QgsServerInterfacecapabiblitiesCachecapabilitiesCache
                                                                                                                                                                                    -\subsection qgis_api_break_3_0_removed_classes Removed Classes +Removed Classes {#qgis_api_break_3_0_removed_classes} +--------------- -
                                                                                                                                                                                      -
                                                                                                                                                                                    • QgsAttributeAction was removed, and replaced by QgsActionManager.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsAttributeEditor was removed. Use QgsEditorWidgetRegistry::create() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsColorbutton was removed. QgsColorButtonV2 has now been renamed to QgsColorButton. Hence, QgsColorButtonV2 does not exist anymore.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsColorDialog was removed, and QgsColorDialogV2 was renamed to QgsColorDialog. Hence, QgsColorButtonV2 does not exist anymore. -All the functionality from the old QgsColorDialog has been moved to the new class.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsComposerAttributeTable and associated classes (eg QgsComposerAttributeTableCompare, + +- QgsAttributeAction was removed, and replaced by QgsActionManager. +- QgsAttributeEditor was removed. Use QgsEditorWidgetRegistry::create() instead. +- QgsColorbutton was removed. QgsColorButtonV2 has now been renamed to QgsColorButton. Hence, QgsColorButtonV2 does not exist anymore. +- QgsColorDialog was removed, and QgsColorDialogV2 was renamed to QgsColorDialog. Hence, QgsColorButtonV2 does not exist anymore. +All the functionality from the old QgsColorDialog has been moved to the new class. +- QgsComposerAttributeTable and associated classes (eg QgsComposerAttributeTableCompare, QgsComposerAttributeTableColumnModel, QgsComposerTableSortColumnsProxyModel) were removed. -Use QgsComposerAttributeTableV2 instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsComposerTable was removed. Use QgsComposerAttributeTableV2 instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • ComposerTextTable was removed. Use ComposerTextTableV2 instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsCRSCache was removed. QgsCoordinateReferenceSystem now internally uses a cache for CRS creation, +Use QgsComposerAttributeTableV2 instead. +- QgsComposerTable was removed. Use QgsComposerAttributeTableV2 instead. +- ComposerTextTable was removed. Use ComposerTextTableV2 instead. +- QgsCRSCache was removed. QgsCoordinateReferenceSystem now internally uses a cache for CRS creation, so there is no longer a need for the separate cache class. Code which previously called QgsCRSCache::updateCRSCache() -should now call QgsCoordinateReferenceSystem::invalidateCache() and QgsCoordinateTransformCache::instance()->invalidateCrs( authid ).
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsHttpTransaction. This class was outdated and code should be ported to native Qt or Python implementations.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsLabel and QgsLabelAttributes. Replaced by labeling based on PAL library, see QgsLabelingEngineV2.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsLegendModel was removed. -
                                                                                                                                                                                    • QgsMapCanvasMap. It is an internal class used by map canvas.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsMapRenderer. It has been replaced by QgsMapRendererJob with subclasses and QgsMapSettings.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsPseudoColorShader. This shader has been broken for some time and was replaced by QgsSingleBandPseudoColorRenderer.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsRendererV2DataDefinedMenus was removed. Use QgsDataDefinedButton instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsLegacyHelpers.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsProviderCountCalcEvent and QgsProviderExtentCalcEvent. These classes were unused in QGIS core and unmaintained.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_global General changes - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • All setDestinationCRS() methods have been renamed to setDestinationCrs()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All destinationCRS() methods have been renamed to destinationCrs()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All readXML() and _readXML() methods have been renamed to readXml() and _readXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All writeXML() and _writeXML() methods have been renamed to writeXml() and _writeXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All setLayerID() methods have been renamed to setLayerId()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All layerID() methods have been renamed to layerId()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All setCRS() methods have been renamed to setCrs()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All srcCrs() methods have been renamed to sourceCrs()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All destCrs() methods have been renamed to destinationCrs()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All exportXML() methods have been renamed to exportXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All importXML() methods have been renamed to importXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All methods taking or returning QGis::WkbType have been changed to use QgsWkbTypes::Type
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All methods taking or returning QGis::GeometryType have been changed to use QgsWkbTypes::GeometryType
                                                                                                                                                                                    • -
                                                                                                                                                                                    - - -\subsection qgis_api_break_3_0_DataProviders Data Providers - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • Many methods in QgsDataProvider, QgsVectorDataProvider and QgsRasterDataProvider have been made const-correct. +should now call QgsCoordinateReferenceSystem::invalidateCache() and QgsCoordinateTransformCache::instance()->invalidateCrs( authid ). +- QgsHttpTransaction. This class was outdated and code should be ported to native Qt or Python implementations. +- QgsLabel and QgsLabelAttributes. Replaced by labeling based on PAL library, see QgsLabelingEngineV2. +- QgsLegendModel was removed. +- QgsMapCanvasMap. It is an internal class used by map canvas. +- QgsMapRenderer. It has been replaced by QgsMapRendererJob with subclasses and QgsMapSettings. +- QgsPseudoColorShader. This shader has been broken for some time and was replaced by QgsSingleBandPseudoColorRenderer. +- QgsRendererV2DataDefinedMenus was removed. Use QgsDataDefinedButton instead. +- QgsLegacyHelpers. +- QgsProviderCountCalcEvent and QgsProviderExtentCalcEvent. These classes were unused in QGIS core and unmaintained. + + +General changes {#qgis_api_break_3_0_global} +--------------- + + +- All setDestinationCRS() methods have been renamed to setDestinationCrs() +- All destinationCRS() methods have been renamed to destinationCrs() +- All readXML() and _readXML() methods have been renamed to readXml() and _readXml() +- All writeXML() and _writeXML() methods have been renamed to writeXml() and _writeXml() +- All setLayerID() methods have been renamed to setLayerId() +- All layerID() methods have been renamed to layerId() +- All setCRS() methods have been renamed to setCrs() +- All srcCrs() methods have been renamed to sourceCrs() +- All destCrs() methods have been renamed to destinationCrs() +- All exportXML() methods have been renamed to exportXml() +- All importXML() methods have been renamed to importXml() +- All methods taking or returning QGis::WkbType have been changed to use QgsWkbTypes::Type +- All methods taking or returning QGis::GeometryType have been changed to use QgsWkbTypes::GeometryType + + + +Data Providers {#qgis_api_break_3_0_DataProviders} +-------------- + + + - Many methods in QgsDataProvider, QgsVectorDataProvider and QgsRasterDataProvider have been made const-correct. This has no effect on PyQGIS code, but c++ code implementing third-party providers will need to update the signatures of these methods to match. Affected methods are: -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsDataProvider: crs(), extent(), isValid(), supportsSubsetString(), subsetString()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsVectorDataProvider: getFeatures(), minimumValue(), maximumValue(), uniqueValues(), enumValues(), defaultValue(), - attributeIndexes(), pkAttributeIndexes(), isSaveAndLoadStyleToDBSupported()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsRasterInterface: extent()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -
                                                                                                                                                                                    • -
                                                                                                                                                                                    • Many protected member variables have been wrapped in setter/getter methods. + + - QgsDataProvider: crs(), extent(), isValid(), supportsSubsetString(), subsetString() + - QgsVectorDataProvider: getFeatures(), minimumValue(), maximumValue(), uniqueValues(), enumValues(), defaultValue(), + attributeIndexes(), pkAttributeIndexes(), isSaveAndLoadStyleToDBSupported() + - QgsRasterInterface: extent() + + + - Many protected member variables have been wrapped in setter/getter methods. This should generally only affect 3rd party providers -
                                                                                                                                                                                        -
                                                                                                                                                                                      • mCacheMinMaxDirty: use clearMinMaxCache()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • mNativeTypes: use setNativeTypes()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • mAttrPalIndexName: overwrite palAttributeIndexNames()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_Qgis Qgis - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • The QGis class was renamed to Qgis for capitalisation consistency with other class names
                                                                                                                                                                                    • -
                                                                                                                                                                                    • permissiveToDouble() and permissiveToInt() where moved out of the QGis class and renamed to qgsPermissiveToDouble() and -qgsPermissiveToInt()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • The constants DEFAULT_IDENTIFY_RADIUS and MINIMUM_POINT_SIZE were removed
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QGis::DecimalDegrees, DegreesMinutesSeconds and DegreesDecimalMinutes have been removed, and have all been replaced -with the general Degrees unit
                                                                                                                                                                                    • -
                                                                                                                                                                                    • The distance unit types QGis::UnitType (including QGis::Meters, QGis::Feet, QGis::Degrees, QGis::NauticalMiles, + + - mCacheMinMaxDirty: use clearMinMaxCache() + - mNativeTypes: use setNativeTypes() + - mAttrPalIndexName: overwrite palAttributeIndexNames() + + + + +Qgis {#qgis_api_break_3_0_Qgis} +---- + + +- The QGis class was renamed to Qgis for capitalisation consistency with other class names +- permissiveToDouble() and permissiveToInt() where moved out of the QGis class and renamed to qgsPermissiveToDouble() and +qgsPermissiveToInt() +- The constants DEFAULT_IDENTIFY_RADIUS and MINIMUM_POINT_SIZE were removed +- QGis::DecimalDegrees, DegreesMinutesSeconds and DegreesDecimalMinutes have been removed, and have all been replaced +with the general Degrees unit +- The distance unit types QGis::UnitType (including QGis::Meters, QGis::Feet, QGis::Degrees, QGis::NauticalMiles, QGis::Kilometers, QGis::Yards, QGis::Miles and QGis::UnknownUnit have been moved to QgsUnitTypes::DistanceUnit. Some of these unit types have also been renamed - see the notes on QgsUnitTypes below. All methods which accepted -QGis::UnitType parameters have been updated to take QgsUnitTypes::DistanceUnit instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • The unit handling methods toLiteral, fromLiteral, tr, fromTr, fromUnitToUnitFactor have been removed. Their -corresponding counterparts in QgsUnitTypes should be used instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • The enum QGis::WkbType has been removed in favor of QgsWkbTypes::Type -
                                                                                                                                                                                    • The enum QGis::GeometryType has been removed in favor of QgsWkbTypes::GeometryType -
                                                                                                                                                                                    • singleType() has been removed. Use the equivalent QgsWkbTypes::singleType() instead -
                                                                                                                                                                                    • multiType() has been removed. Use the equivalent QgsWkbTypes::multiType() instead -
                                                                                                                                                                                    • flatType() has been removed. Use the equivalent QgsWkbTypes::flatType() instead -
                                                                                                                                                                                    • isSingleType() has been removed. Use the equivalent QgsWkbTypes::issingleType() instead -
                                                                                                                                                                                    • isMultiType() has been removed. Use the equivalent QgsWkbTypes::isMultiType() instead -
                                                                                                                                                                                    • wkbDimensions() has been removed. Use the equivalent QgsWkbTypes::coordDimensions() instead -
                                                                                                                                                                                    • fromOldWkbType() has been removed. This is no longer required. -
                                                                                                                                                                                    • fromNewWkbType() has been removed. This is no longer required. -
                                                                                                                                                                                    • vectorGeometryType() has been removed. Use the equivalent QgsWkbTypes::geometrydisplayString() instead. -
                                                                                                                                                                                    • featureType() has been removed. Use the equivalent QgsWkbTypes::displayString() instead. -
                                                                                                                                                                                    - - -\subsection qgis_api_break_3_0_QgisInterface QgisInterface - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • fileMenu() has been removed, use projectMenu() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • actionRemoveLayer was removed as it no longer exists.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAnnotation QgsAnnotation - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • mapPositionFixed() has been renamed to hasFixedMapPosition() -
                                                                                                                                                                                    - - -\subsection qgis_api_break_3_0_QgsActionManager QgsActionManager - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • doAction() no longer accepts a substitution map. Use expression context variables instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • The doAction() variant which takes a QgsFeature along has been removed. Use the expression context -variant instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • expandAction() has been removed. Use QgsExpression::replaceExpressionText() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setPythonExecute() was removed. Initialize QgsPythonRunner instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAdvancedDigitizingDockWidget QgsAdvancedDigitizingDockWidget - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • canvasReleaseEvent takes now QgsAdvancedDigitizingDockWidget::CaptureMode as second argument.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAtlasComposition QgsAtlasComposition - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • readXMLMapSettings() has been renamed to readXmlMapSettings()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • composerMap() and setComposerMap() were removed. Use QgsComposerMap::atlasDriven() and setAtlasDriven() -instead
                                                                                                                                                                                    • -
                                                                                                                                                                                    • fixedScale() and setFixedScale() were removed. Use QgsComposerMap::atlasScalingMode() and setAtlasScalingMode() -instead
                                                                                                                                                                                    • -
                                                                                                                                                                                    • margin() and setMargin() were removed. Use QgsComposerMap::atlasMargin() and setAtlasMargin() -instead
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setSortKeyAttributeIndex() and sortKeyAttributeIndex() were removed. Use sortKeyAttributeName() -and setSortKeyAttributeName() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • currentFeature() was removed. Use feature() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAttributeDialog QgsAttributeDialog - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • The constructor for QgsAttributeDialog has changed
                                                                                                                                                                                    • -
                                                                                                                                                                                    • dialog() was removed - just use the object directly.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setIsAddDialog() was removed. Use setMode() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAttributeForm QgsAttributeForm - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • setIsAddDialog() was removed. Use setMode() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • accept() was removed. Use save() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • reject() was removed. Use resetValues() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAuthConfigUriEdit QgsAuthConfigUriEdit - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • hasConfigID() has been renamed to hasConfigId()
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsAuthMethod QgsAuthMethod -
                                                                                                                                                                                      -
                                                                                                                                                                                    • DataSourceURI has been renamed to DataSourceUri
                                                                                                                                                                                    • -
                                                                                                                                                                                    • GenericDataSourceURI has been renamed to GenericDataSourceUri
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsQgsCachedFeatureIterator QgsCachedFeatureIterator -
                                                                                                                                                                                      -
                                                                                                                                                                                    • The constructor for QgsCachedFeatureIterator has changed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsCategorizedSymbolRendererWidget QgsCategorizedSymbolRendererWidget -
                                                                                                                                                                                      -
                                                                                                                                                                                    • sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsClipper QgsClipper - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • clippedLineWKB has been renamed to clippedLine and it's signature has been changed to return a QPolygonF
                                                                                                                                                                                    • -
                                                                                                                                                                                    +QGis::UnitType parameters have been updated to take QgsUnitTypes::DistanceUnit instead. +- The unit handling methods toLiteral, fromLiteral, tr, fromTr, fromUnitToUnitFactor have been removed. Their +corresponding counterparts in QgsUnitTypes should be used instead. +- The enum QGis::WkbType has been removed in favor of QgsWkbTypes::Type +- The enum QGis::GeometryType has been removed in favor of QgsWkbTypes::GeometryType +- singleType() has been removed. Use the equivalent QgsWkbTypes::singleType() instead +- multiType() has been removed. Use the equivalent QgsWkbTypes::multiType() instead +- flatType() has been removed. Use the equivalent QgsWkbTypes::flatType() instead +- isSingleType() has been removed. Use the equivalent QgsWkbTypes::issingleType() instead +- isMultiType() has been removed. Use the equivalent QgsWkbTypes::isMultiType() instead +- wkbDimensions() has been removed. Use the equivalent QgsWkbTypes::coordDimensions() instead +- fromOldWkbType() has been removed. This is no longer required. +- fromNewWkbType() has been removed. This is no longer required. +- vectorGeometryType() has been removed. Use the equivalent QgsWkbTypes::geometrydisplayString() instead. +- featureType() has been removed. Use the equivalent QgsWkbTypes::displayString() instead. + + + +QgisInterface {#qgis_api_break_3_0_QgisInterface} +------------- + + +- fileMenu() has been removed, use projectMenu() instead. +- actionRemoveLayer was removed as it no longer exists. + + +QgsAnnotation {#qgis_api_break_3_0_QgsAnnotation} +------------- + + +- mapPositionFixed() has been renamed to hasFixedMapPosition() + + + +QgsActionManager {#qgis_api_break_3_0_QgsActionManager} +---------------- + + +- doAction() no longer accepts a substitution map. Use expression context variables instead. +- The doAction() variant which takes a QgsFeature along has been removed. Use the expression context +variant instead. +- expandAction() has been removed. Use QgsExpression::replaceExpressionText() instead. +- setPythonExecute() was removed. Initialize QgsPythonRunner instead. + + +QgsAdvancedDigitizingDockWidget {#qgis_api_break_3_0_QgsAdvancedDigitizingDockWidget} +------------------------------- + + +- canvasReleaseEvent takes now QgsAdvancedDigitizingDockWidget::CaptureMode as second argument. + + +QgsAtlasComposition {#qgis_api_break_3_0_QgsAtlasComposition} +------------------- + + +- readXMLMapSettings() has been renamed to readXmlMapSettings() +- composerMap() and setComposerMap() were removed. Use QgsComposerMap::atlasDriven() and setAtlasDriven() +instead +- fixedScale() and setFixedScale() were removed. Use QgsComposerMap::atlasScalingMode() and setAtlasScalingMode() +instead +- margin() and setMargin() were removed. Use QgsComposerMap::atlasMargin() and setAtlasMargin() +instead +- setSortKeyAttributeIndex() and sortKeyAttributeIndex() were removed. Use sortKeyAttributeName() +and setSortKeyAttributeName() instead. +- currentFeature() was removed. Use feature() instead. + + +QgsAttributeDialog {#qgis_api_break_3_0_QgsAttributeDialog} +------------------ + + +- The constructor for QgsAttributeDialog has changed +- dialog() was removed - just use the object directly. +- setIsAddDialog() was removed. Use setMode() instead. + + +QgsAttributeForm {#qgis_api_break_3_0_QgsAttributeForm} +---------------- + + +- setIsAddDialog() was removed. Use setMode() instead. +- accept() was removed. Use save() instead. +- reject() was removed. Use resetValues() instead. + + +QgsAuthConfigUriEdit {#qgis_api_break_3_0_QgsAuthConfigUriEdit} +-------------------- -\subsection qgis_api_break_3_0_QgsColorBrewerColorRampDialog QgsColorBrewerColorRampDialog -
                                                                                                                                                                                      -
                                                                                                                                                                                    • The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited -and the new ramp can be retrieved after executing the dialog by calling ramp().
                                                                                                                                                                                    • -
                                                                                                                                                                                    • Some internal methods which were previously public or protected were made private.
                                                                                                                                                                                    • -
                                                                                                                                                                                    +- hasConfigID() has been renamed to hasConfigId() -\subsection qgis_api_break_3_0_QgsColorRampShader QgsColorRampShader -
                                                                                                                                                                                      -
                                                                                                                                                                                    • maximumColorCacheSize() and setMaximumColorCacheSize() were no longer used and are removed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    +QgsAuthMethod {#qgis_api_break_3_0_QgsAuthMethod} +------------- -\subsection qgis_api_break_3_0_QgsComposerArrow QgsComposerArrow +- DataSourceURI has been renamed to DataSourceUri +- GenericDataSourceURI has been renamed to GenericDataSourceUri -
                                                                                                                                                                                      -
                                                                                                                                                                                    • setOutlineWidth(), outlineWidth(), arrowColor() and setArrowColor() were removed. + +QgsCachedFeatureIterator {#qgis_api_break_3_0_QgsQgsCachedFeatureIterator} +------------------------ + +- The constructor for QgsCachedFeatureIterator has changed. + + +QgsCategorizedSymbolRendererWidget {#qgis_api_break_3_0_QgsCategorizedSymbolRendererWidget} +---------------------------------- + +- sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI. + + +QgsClipper {#qgis_api_break_3_0_QgsClipper} +---------- + + +- clippedLineWKB has been renamed to clippedLine and it's signature has been changed to return a QPolygonF + + +QgsColorBrewerColorRampDialog {#qgis_api_break_3_0_QgsColorBrewerColorRampDialog} +----------------------------- + + +- The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited +and the new ramp can be retrieved after executing the dialog by calling ramp(). +- Some internal methods which were previously public or protected were made private. + + +QgsColorRampShader {#qgis_api_break_3_0_QgsColorRampShader} +------------------ + + +- maximumColorCacheSize() and setMaximumColorCacheSize() were no longer used and are removed. + + +QgsComposerArrow {#qgis_api_break_3_0_QgsComposerArrow} +---------------- + + +- setOutlineWidth(), outlineWidth(), arrowColor() and setArrowColor() were removed. Use setArrowHeadOutlineWidth(), arrowHeadOutlineWidth(), arrowHeadOutlineColor(), setArrowHeadOutlineColor(), arrowHeadFillColor(), setArrowHeadFillColor(), -setLineSymbol() or lineSymbol() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    +setLineSymbol() or lineSymbol() instead. + + +QgsComposerAttributeTableV2 {#qgis_api_break_3_0_QgsComposerAttributeTableV2} +--------------------------- -\subsection qgis_api_break_3_0_QgsComposerAttributeTableV2 QgsComposerAttributeTableV2 -
                                                                                                                                                                                      -
                                                                                                                                                                                    • setDisplayAttributes() was removed. Use setDisplayedFields() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    +- setDisplayAttributes() was removed. Use setDisplayedFields() instead. -\subsection qgis_api_break_3_0_QgsComposerItem QgsComposerItem -
                                                                                                                                                                                      -
                                                                                                                                                                                    • zoomContent( int delta, double x, double y ) was removed. Use zoomContent( double, QPointF, ZoomMode ) -instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • drawText(), textWidthMillimeters(), fontHeightCharacterMM(), fontAscentMillimeters(), +QgsComposerItem {#qgis_api_break_3_0_QgsComposerItem} +--------------- + + +- zoomContent( int delta, double x, double y ) was removed. Use zoomContent( double, QPointF, ZoomMode ) +instead. +- drawText(), textWidthMillimeters(), fontHeightCharacterMM(), fontAscentMillimeters(), fontDescentMillimeters(), fontHeightMillimeters(), pixelFontSize(), scaledFontPixelSize(), drawArrowHead(), angle(), largestRotatedRectWithinBounds(), and rotate() were removed. -Use the corresponding methods in QgsComposerUtils instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • rotation() and setRotation() were removed. Use itemRotation() and setItemRotation() -instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • lockSymbolSize(), imageSizeConsideringRotation(), cornerPointOnRotatedAndScaledRect(), -sizeChangedByRotation() were removed. No replacement is offered for these methods.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerLabel QgsComposerLabel - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • setExpressionContext() has been removed. Setup the composition using an atlas and with -expression variables in the composer label item instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setSubstitutions has been removed. Use expression context variables in the composer -label item instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • margin() was removed. Use marginX() and marginY() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerLegend QgsComposerLegend - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • model() now returns the new QgsLegendModel (previously QgsLegendModelV2, see \ref qgis_api_break_3_0_renamed_classes).
                                                                                                                                                                                    • -
                                                                                                                                                                                    • modelV2() has been renamed to model().
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerLegendItem QgsComposerLegendItem - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • writeXMLChildren() has been renamed to writeXmlChildren()
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerMap QgsComposerMap - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • containsWMSLayer() has been renamed to containsWmsLayer()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • mapRenderer() has been removed. Use mapSettings() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All grid style and format enums were moved to QgsComposerMapGrid.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All grid property getters and setters were moved to QgsComposerMapGrid, -and should be accessed using QgsComposerMap::grid() or QgsComposerMap::grids().
                                                                                                                                                                                    • -
                                                                                                                                                                                    • All overview property getters and setters were moved to QgsComposerMapOverview, -and should be accessed using QgsComposerMap::overview() or QgsComposerMap::overviews().
                                                                                                                                                                                    • -
                                                                                                                                                                                    • overviewExtentChanged() was moved to QgsComposerMapOverview.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • toggleAtlasPreview(), connectMapOverviewSignals() were no longer required and are removed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setRotation() and rotation() were removed. Use setMapRotation() and mapRotation() -instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • atlasFixedScale() and setAtlasFixedScale() were removed. Use atlasScalingMode() -and setAtlasScalingMode() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerMapGrid QgsComposerMapGrid - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • The annotation position Disabled was removed. QgsComposerMapGrid::HideAll -should be used instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerMultiFrame QgsComposerMultiFrame - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • render( QPainter* p, const QRectF& renderExtent ) was removed. Use +Use the corresponding methods in QgsComposerUtils instead. +- rotation() and setRotation() were removed. Use itemRotation() and setItemRotation() +instead. +- lockSymbolSize(), imageSizeConsideringRotation(), cornerPointOnRotatedAndScaledRect(), +sizeChangedByRotation() were removed. No replacement is offered for these methods. + + +QgsComposerLabel {#qgis_api_break_3_0_QgsComposerLabel} +---------------- + + +- setExpressionContext() has been removed. Setup the composition using an atlas and with +expression variables in the composer label item instead. +- setSubstitutions has been removed. Use expression context variables in the composer +label item instead. +- margin() was removed. Use marginX() and marginY() instead. + + +QgsComposerLegend {#qgis_api_break_3_0_QgsComposerLegend} +----------------- + + +- model() now returns the new QgsLegendModel (previously QgsLegendModelV2, see \ref qgis_api_break_3_0_renamed_classes). +- modelV2() has been renamed to model(). + + +QgsComposerLegendItem {#qgis_api_break_3_0_QgsComposerLegendItem} +--------------------- + + +- writeXMLChildren() has been renamed to writeXmlChildren() + + +QgsComposerMap {#qgis_api_break_3_0_QgsComposerMap} +-------------- + + +- containsWMSLayer() has been renamed to containsWmsLayer() +- mapRenderer() has been removed. Use mapSettings() instead. +- All grid style and format enums were moved to QgsComposerMapGrid. +- All grid property getters and setters were moved to QgsComposerMapGrid, +and should be accessed using QgsComposerMap::grid() or QgsComposerMap::grids(). +- All overview property getters and setters were moved to QgsComposerMapOverview, +and should be accessed using QgsComposerMap::overview() or QgsComposerMap::overviews(). +- overviewExtentChanged() was moved to QgsComposerMapOverview. +- toggleAtlasPreview(), connectMapOverviewSignals() were no longer required and are removed. +- setRotation() and rotation() were removed. Use setMapRotation() and mapRotation() +instead. +- atlasFixedScale() and setAtlasFixedScale() were removed. Use atlasScalingMode() +and setAtlasScalingMode() instead. + + +QgsComposerMapGrid {#qgis_api_break_3_0_QgsComposerMapGrid} +------------------ + + +- The annotation position Disabled was removed. QgsComposerMapGrid::HideAll +should be used instead. + + +QgsComposerMultiFrame {#qgis_api_break_3_0_QgsComposerMultiFrame} +--------------------- + + +- render( QPainter* p, const QRectF& renderExtent ) was removed. Use render( QPainter* painter, const QRectF& renderExtent, const int frameIndex ) -instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • render( QPainter* painter, const QRectF& renderExtent, const int frameIndex ) -was made pure virtual.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerNodesItem QgsComposerNodesItem - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • _readXMLStyle() has been renamed to _readXmlStyle()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • _writeXMLStyle() has been renamed to _writeXMLStyle()
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerPicture QgsComposerPicture - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • setPictureFile() and pictureFile() were removed. Use setPicturePath() -and picturePath() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • rotation() and setRotation() were removed. Use pictureRotation() -and setPictureRotation() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • usePictureExpression() and pictureExpression() were removed. Use -QgsComposerObject::dataDefinedProperty instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setUsePictureExpression() was removed. Use -QgsComposerObject::setDataDefinedProperty() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • updatePictureExpression() was removed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerTable QgsComposerTable - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • tableWriteXML() has been renamed to tableWriteXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • tableReadXML() has been renamed to tableReadXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposerTableV2 QgsComposerTableV2 - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • rowsVisible(), rowRange(), drawHorizontalGridLines() and - drawVerticalGridLines() were removed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsComposition QgsComposition - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • addItemsFromXML() has been renamed to addItemsFromXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • Constructor with QgsMapRenderer parameter has been removed. Use the variant with QgsMapSettings parameter.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • mapRenderer() has been removed. Use mapSettings() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setSnapGridTolerance(), setAlignmentSnapTolerance(), alignmentSnapTolerance() and snapGridTolerance() -were removed. Use setSnapTolerance() and snapTolerance() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • getComposerHtmlByItem() was removed. Use QgsComposerFrame::multiFrame() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • pixelFontSize(), pointFontSize(), relativeResizeRect(), relativePosition() were removed. Use the corresponding methods in QgsComposerUtils instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • sortZList() was removed. Use refreshZList() instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • addComposerTable(), composerTableAdded() were removed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsCoordinateReferenceSystem QgsCoordinateReferenceSystem - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • QgsCoordinateReferenceSystem now uses internal caches to avoid expensive database lookups +instead. +- render( QPainter* painter, const QRectF& renderExtent, const int frameIndex ) +was made pure virtual. + + +QgsComposerNodesItem {#qgis_api_break_3_0_QgsComposerNodesItem} +-------------------- + + +- _readXMLStyle() has been renamed to _readXmlStyle() +- _writeXMLStyle() has been renamed to _writeXMLStyle() + + +QgsComposerPicture {#qgis_api_break_3_0_QgsComposerPicture} +------------------ + + +- setPictureFile() and pictureFile() were removed. Use setPicturePath() +and picturePath() instead. +- rotation() and setRotation() were removed. Use pictureRotation() +and setPictureRotation() instead. +- usePictureExpression() and pictureExpression() were removed. Use +QgsComposerObject::dataDefinedProperty instead. +- setUsePictureExpression() was removed. Use +QgsComposerObject::setDataDefinedProperty() instead. +- updatePictureExpression() was removed. + + +QgsComposerTable {#qgis_api_break_3_0_QgsComposerTable} +---------------- + + +- tableWriteXML() has been renamed to tableWriteXml() +- tableReadXML() has been renamed to tableReadXml() + + +QgsComposerTableV2 {#qgis_api_break_3_0_QgsComposerTableV2} +------------------ + + +- rowsVisible(), rowRange(), drawHorizontalGridLines() and + drawVerticalGridLines() were removed. + + +QgsComposition {#qgis_api_break_3_0_QgsComposition} +-------------- + + +- addItemsFromXML() has been renamed to addItemsFromXml() +- Constructor with QgsMapRenderer parameter has been removed. Use the variant with QgsMapSettings parameter. +- mapRenderer() has been removed. Use mapSettings() instead. +- setSnapGridTolerance(), setAlignmentSnapTolerance(), alignmentSnapTolerance() and snapGridTolerance() +were removed. Use setSnapTolerance() and snapTolerance() instead. +- getComposerHtmlByItem() was removed. Use QgsComposerFrame::multiFrame() instead. +- pixelFontSize(), pointFontSize(), relativeResizeRect(), relativePosition() were removed. Use the corresponding methods in QgsComposerUtils instead. +- sortZList() was removed. Use refreshZList() instead. +- addComposerTable(), composerTableAdded() were removed. + + +QgsCoordinateReferenceSystem {#qgis_api_break_3_0_QgsCoordinateReferenceSystem} +---------------------------- + + +- QgsCoordinateReferenceSystem now uses internal caches to avoid expensive database lookups when CRS objects are initialized. This is handled internally, but invalidateCache() must be -called if changes are made to the CRS database.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setCustomSrsValidation() has been renamed to setCustomCrsValidation()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • saveAsUserCRS() has been renamed to saveAsUserCrs()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • geographicCRSAuthId() has been renamed to geographicCrsAuthId()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • geographicFlag() was renamed to isGeographic()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • axisInverted() was renamed to hasAxisInverted()
                                                                                                                                                                                    • -
                                                                                                                                                                                    - -\subsection qgis_api_break_3_0_QgsCoordinateTransform QgsCoordinateTransform - -
                                                                                                                                                                                      -
                                                                                                                                                                                    • QgsCoordinateTransform is no longer a QObject. readXml, writeXml and initialise are all normal public members now, -not slots. The invalidTransformInput() signal has been removed.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • The extra QgsCoordinateTransform constructors (those not taking QgsCoordinateReferenceSystem arguments) have been +called if changes are made to the CRS database. +- setCustomSrsValidation() has been renamed to setCustomCrsValidation() +- saveAsUserCRS() has been renamed to saveAsUserCrs() +- geographicCRSAuthId() has been renamed to geographicCrsAuthId() +- geographicFlag() was renamed to isGeographic() +- axisInverted() was renamed to hasAxisInverted() + + +QgsCoordinateTransform {#qgis_api_break_3_0_QgsCoordinateTransform} +---------------------- + + +- QgsCoordinateTransform is no longer a QObject. readXml, writeXml and initialise are all normal public members now, +not slots. The invalidTransformInput() signal has been removed. +- The extra QgsCoordinateTransform constructors (those not taking QgsCoordinateReferenceSystem arguments) have been removed. Now, QgsCoordinateTransform must be created using an already existing source and destination -QgsCoordinateReferenceSystem object.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • QgsCoordinateTransform::clone() has been removed. Just use direct copies instead.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • sourceCrs() and destCrs() now return a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ -plugins calling these methods will need to be updated.
                                                                                                                                                                                    • -
                                                                                                                                                                                    • isInitialised() has been renamed to isValid()
                                                                                                                                                                                    • -
                                                                                                                                                                                    • theCRS parameter in setSourceCrs has been renamed to 'crs'
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setDestCRS() has been renamed to setDestinationCrs() for consistency
                                                                                                                                                                                    • -
                                                                                                                                                                                    • destCRS() has been renamed to destinationCrs() for consistency
                                                                                                                                                                                    • -
                                                                                                                                                                                    • theSource, theDest, theSourceSrsId, theDestSrsId, theSourceWkt, theDestWkt, theSourceCRSType parameters in the QgsCoordinateTransform constructors have been renamed to source, destination, sourceSrsId, destinationSrsId, sourceWkt, destinationWkt, sourceCrsType respectively
                                                                                                                                                                                    • -
                                                                                                                                                                                    • 'p' argument in transform() has been renamed to 'point', 'theRect' to 'rectangle', 'poly' to 'polygon'
                                                                                                                                                                                    • -
                                                                                                                                                                                    • setDestCRSID has been removed, use setDestinationCrs() instead
                                                                                                                                                                                    • -
                                                                                                                                                                                    • 'theNode', 'theDoc' parameters in readXML and writeXML have been renamed to 'node' and 'document' respectively
                                                                                                                                                                                    • -
                                                                                                                                                                                    • readXML() and writeXML() have been renamed to readXml() and writeXml() for consistency
                                                                                                                                                                                    • -
                                                                                                                                                                                    +QgsCoordinateReferenceSystem object. +- QgsCoordinateTransform::clone() has been removed. Just use direct copies instead. +- sourceCrs() and destCrs() now return a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ +plugins calling these methods will need to be updated. +- isInitialised() has been renamed to isValid() +- theCRS parameter in setSourceCrs has been renamed to 'crs' +- setDestCRS() has been renamed to setDestinationCrs() for consistency +- destCRS() has been renamed to destinationCrs() for consistency +- theSource, theDest, theSourceSrsId, theDestSrsId, theSourceWkt, theDestWkt, theSourceCRSType parameters in the QgsCoordinateTransform constructors have been renamed to source, destination, sourceSrsId, destinationSrsId, sourceWkt, destinationWkt, sourceCrsType respectively +- 'p' argument in transform() has been renamed to 'point', 'theRect' to 'rectangle', 'poly' to 'polygon' +- setDestCRSID has been removed, use setDestinationCrs() instead +- 'theNode', 'theDoc' parameters in readXML and writeXML have been renamed to 'node' and 'document' respectively +- readXML() and writeXML() have been renamed to readXml() and writeXml() for consistency + -\subsection qgis_api_break_3_0_QgsCoordinateTransformCache QgsCoordinateTransformCache +QgsCoordinateTransformCache {#qgis_api_break_3_0_QgsCoordinateTransformCache} +--------------------------- -
                                                                                                                                                                                      -
                                                                                                                                                                                    • transform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be returned in place of a null pointer.
                                                                                                                                                                                    • -
                                                                                                                                                                                    -\subsection qgis_api_break_3_0_QgsCptCityColorRampDialog QgsCptCityColorRampDialog +- transform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be returned in place of a null pointer. -
                                                                                                                                                                                      -
                                                                                                                                                                                    • The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited -and the new ramp can be retrieved after executing the dialog by calling ramp().
                                                                                                                                                                                    • -
                                                                                                                                                                                    • Some internal methods which were previously public or protected were made private.
                                                                                                                                                                                    • -
                                                                                                                                                                                    -\subsection qgis_api_break_3_0_QgsCptCitySelectionItem QgsCptCitySelectionItem +QgsCptCityColorRampDialog {#qgis_api_break_3_0_QgsCptCityColorRampDialog} +------------------------- -
                                                                                                                                                                                      -
                                                                                                                                                                                    • parseXML() has been renamed to parseXml()
                                                                                                                                                                                    • -
                                                                                                                                                                                    -\subsection qgis_api_break_3_0_QgsCRSCache QgsCRSCache +- The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited +and the new ramp can be retrieved after executing the dialog by calling ramp(). +- Some internal methods which were previously public or protected were made private. -
                                                                                                                                                                                      -
                                                                                                                                                                                    • QgsCRSCache has been renamed to QgsCrsCache
                                                                                                                                                                                    • -
                                                                                                                                                                                    • updateCRSCache() has been renamed to updateCrsCache
                                                                                                                                                                                    • -
                                                                                                                                                                                    -\subsection qgis_api_break_3_0_QgsCursors QgsCursors +QgsCptCitySelectionItem {#qgis_api_break_3_0_QgsCptCitySelectionItem} +----------------------- -
                                                                                                                                                                                      -
                                                                                                                                                                                    • remove old bitmap cursors pan and pan_mask. Use window system curosrs instead.
                                                                                                                                                                                    • -\subsection qgis_api_break_3_0_QgsDataDefined QgsDataDefined +- parseXML() has been renamed to parseXml() -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionParams(), setExpressionParams() and insertExpressionParam() have been removed. -QgsExpressionContext variables should be used in their place.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • prepareExpression( QgsVectorLayer* layer ) and prepareExpression( const QgsFields &fields ) -were removed. Use QgsExpressionContext variant instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • referencedColumns( QgsVectorLayer* layer ) and referencedColumns( const QgsFields& fields ) -were removed. Use QgsExpressionContext variant instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsDataDefinedButton QgsDataDefinedButton +QgsCRSCache {#qgis_api_break_3_0_QgsCRSCache} +----------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • registerGetExpressionContextCallback has been removed in favor of registerExpressionContextGenerator
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- QgsCRSCache has been renamed to QgsCrsCache +- updateCRSCache() has been renamed to updateCrsCache -\subsection qgis_api_break_3_0_QgsDataDefinedSymbolDialog QgsDataDefinedSymbolDialog -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsDataDefinedSymbolDialog was removed. Code using this dialog should be reworked to use QgsDataDefinedButton -instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsCursors {#qgis_api_break_3_0_QgsCursors} +--------- -\subsection qgis_api_break_3_0_QgsDataItem QgsDataItem -
                                                                                                                                                                                        -
                                                                                                                                                                                      • supportedCRS() has been renamed to supportedCrs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isPopulated() has been removed. Use state() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • capabilities() has been removed. Use capabilities2() instead (TODO: rename back to capabilities()).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • emitBeginInsertItems(), emitEndInsertItems(), emitBeginRemoveItems(), emitEndRemoveItems(), emitDataChanged(), emitStateChanged() have been removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- remove old bitmap cursors pan and pan_mask. Use window system curosrs instead. -\subsection qgis_api_break_3_0_QgsDatasourceUri QgsDataSourceURI +QgsDataDefined {#qgis_api_break_3_0_QgsDataDefined} +-------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsDataSourceURI has been renamed to QgsDataSourceUri
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsDataSourceURI::SSLmode has been renamed to QgsDataSourceUri::SslMode. All items of this enum have been properly CamelCased.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsDatumTransformStore QgsDatumTransformStore +- expressionParams(), setExpressionParams() and insertExpressionParam() have been removed. +QgsExpressionContext variables should be used in their place. +- prepareExpression( QgsVectorLayer* layer ) and prepareExpression( const QgsFields &fields ) +were removed. Use QgsExpressionContext variant instead. +- referencedColumns( QgsVectorLayer* layer ) and referencedColumns( const QgsFields& fields ) +were removed. Use QgsExpressionContext variant instead. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • transformation() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be returned in place of a null pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsDiagram QgsDiagram +QgsDataDefinedButton {#qgis_api_break_3_0_QgsDataDefinedButton} +-------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The deprecated getExpression( const QString& expression, const QgsFields* fields ) method has been removed. -Use the variant which accepts an expression context instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The deprecated renderDiagram( const QgsAttributes& att, QgsRenderContext& c, const QgsDiagramSettings& s, QPointF position ) method has been removed. + +- registerGetExpressionContextCallback has been removed in favor of registerExpressionContextGenerator + + + +QgsDataDefinedSymbolDialog {#qgis_api_break_3_0_QgsDataDefinedSymbolDialog} +-------------------------- + + +- QgsDataDefinedSymbolDialog was removed. Code using this dialog should be reworked to use QgsDataDefinedButton +instead. + + +QgsDataItem {#qgis_api_break_3_0_QgsDataItem} +----------- + + +- supportedCRS() has been renamed to supportedCrs() +- isPopulated() has been removed. Use state() instead. +- capabilities() has been removed. Use capabilities2() instead (TODO: rename back to capabilities()). +- emitBeginInsertItems(), emitEndInsertItems(), emitBeginRemoveItems(), emitEndRemoveItems(), emitDataChanged(), emitStateChanged() have been removed. + + +QgsDataSourceURI {#qgis_api_break_3_0_QgsDatasourceUri} +---------------- + + +- QgsDataSourceURI has been renamed to QgsDataSourceUri +- QgsDataSourceURI::SSLmode has been renamed to QgsDataSourceUri::SslMode. All items of this enum have been properly CamelCased. + + +QgsDatumTransformStore {#qgis_api_break_3_0_QgsDatumTransformStore} +---------------------- + + +- transformation() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be returned in place of a null pointer. + + +QgsDiagram {#qgis_api_break_3_0_QgsDiagram} +---------- + + +- The deprecated getExpression( const QString& expression, const QgsFields* fields ) method has been removed. +Use the variant which accepts an expression context instead. +- The deprecated renderDiagram( const QgsAttributes& att, QgsRenderContext& c, const QgsDiagramSettings& s, QPointF position ) method has been removed. Use renderDiagram( const QgsFeature& feature, QgsRenderContext& c, const QgsDiagramSettings& s, const QPointF& position ) instead. -
                                                                                                                                                                                      • The deprecated diagramSize( const QgsAttributes& attributes, const QgsRenderContext& c, const QgsDiagramSettings& s, const QgsDiagramInterpolationSettings& is ) method has been removed. +- The deprecated diagramSize( const QgsAttributes& attributes, const QgsRenderContext& c, const QgsDiagramSettings& s, const QgsDiagramInterpolationSettings& is ) method has been removed. Use diagramSize( const QgsFeature& feature, const QgsRenderContext& c, const QgsDiagramSettings& s, const QgsDiagramInterpolationSettings& is ) instead. -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsDiagramRenderer QgsDiagramRenderer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • xform, fields were no longer required and are removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsDiagramLayerSettings QgsDiagramLayerSettings - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • coordinateTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be returned in place of a null pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setCoordinateTransform() now takes a QgsCoordinateTransform object, not a pointer. Use an invalid QgsCoordinateTransform in -place of a null pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The ct member has been removed. Use coordinateTransform() and setCoordinateTransform() instead. -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsDiagramSettings QgsDiagramSettings - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The SizeType enum was removed. Use QgsUnitTypes.RenderUnit instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsDistanceArea QgsDistanceArea - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • sourceCrs() now returns a QgsCoordinateReferenceSystem instead of the crs ID.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • measure() has been removed. Use measureArea() or measureLength() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • textUnit() was removed. Use formatDistance() or formatArea() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • convertMeasurement was removed. Use QgsUnitTypes for conversion instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsDxfExport QgsDxfExport - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The writeGroup() method taking a QgsPoint argument was removed. Use the version which takes a QgsPointV2 instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The writePolyline() method taking a QgsPolyline argument was removed. Use the alternative version instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The writePolygon() method taking a QgsPolygon argument was removed. Use the version which takes a QgsRingSequence instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • writeSolid() was removed. Use writePolygon() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The signature for writeLine() has changed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • writePoint(), writeFilledCircle(), writeCircle(), writeText() and writeMText() now take QgsPointV2 arguments
                                                                                                                                                                                      • - -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsEditFormConfig QgsEditFormConfig - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • Does no longer inherit QObject
                                                                                                                                                                                      • -
                                                                                                                                                                                      • widgetType() and widgetConfig() now reflect only the user configured values. -QgsEditorWidgetRegistry::instance()->findBest() must be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • widgetType(), widgetConfig(), setWidgetType(), setWidgetConfig() and removeWidgetConfig() now only take a string as first parameter. Access by index has been removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • expression() has been renamed to constraintExpression()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setExpression() has been renamed to setConstraintExpression()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • expressionDescription() has been renamed to constraintDescription()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setExpressionDesctiption() has been renamed to setConstraintDescription()
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsExpression QgsExpression - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • prepare( const QgsFields &fields ) has been removed. Use prepare( const QgsExpressionContext *context ) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The evaluate methods which accept feature parameters have been removed. Use the version which takes a QgsExpressionContext -argument instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isValid( const QString& text, const QgsFields& fields, QString &errorMessage ) has been removed, use the QgsExpressionContext -version instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setCurrentRowNumber, currentRowNumber, scale, setScale, setSpecialColumn, unsetSpecialColumn, specialColumn, hasSpecialColumn have been -removed. Use QgsExpressionContext variables instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The replaceExpressionText version which accepts a QgsFeature argument has been removed. Use the QgsExpressionContext -version instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::Function::func has been modified to use a QgsExpressionContext argument rather than a QgsFeature.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::Function::usesgeometry() has been renamed to usesGeometry()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::Function::helptext() has been renamed to helpText()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The QgsExpression::Node::eval and prepare versions which take a QgsFeature has been removed, use the QgsExpressionContext versions instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::Interval has been removed. Use QgsInterval instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • replaceExpressionText() no longer accepts a substitution map parameter. Use expression context variables instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • helptext() has been renamed to helpText()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isValid() has been renamed to checkExpression()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • acceptVisitor() has been removed
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::referencedColumns() returns QSet instead of QStringList
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::Node::referencedColumns() returns QSet instead of QStringList
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsExpression::Function::referencedColumns() returns QSet instead of QStringList
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsFeature QgsFeature - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • geometryAndOwnership() has been removed. Use geometry() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setGeometryAndOwnership() has been removed. Use setGeometry() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The setGeometry( QgsGeometry* ) method has been removed, use setGeometry( const QgsGeometry& ) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The geometry() method now returns a copy of the geometry, not a pointer. Since QgsGeometry objects are + + +QgsDiagramRenderer {#qgis_api_break_3_0_QgsDiagramRenderer} +------------------ + + +- xform, fields were no longer required and are removed. + + +QgsDiagramLayerSettings {#qgis_api_break_3_0_QgsDiagramLayerSettings} +----------------------- + + +- coordinateTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be returned in place of a null pointer. +- setCoordinateTransform() now takes a QgsCoordinateTransform object, not a pointer. Use an invalid QgsCoordinateTransform in +place of a null pointer. +- The ct member has been removed. Use coordinateTransform() and setCoordinateTransform() instead. + + +QgsDiagramSettings {#qgis_api_break_3_0_QgsDiagramSettings} +------------------ + + +- The SizeType enum was removed. Use QgsUnitTypes.RenderUnit instead. + + +QgsDistanceArea {#qgis_api_break_3_0_QgsDistanceArea} +--------------- + + +- sourceCrs() now returns a QgsCoordinateReferenceSystem instead of the crs ID. +- measure() has been removed. Use measureArea() or measureLength() instead. +- textUnit() was removed. Use formatDistance() or formatArea() instead. +- convertMeasurement was removed. Use QgsUnitTypes for conversion instead. + + +QgsDxfExport {#qgis_api_break_3_0_QgsDxfExport} +------------ + + +- The writeGroup() method taking a QgsPoint argument was removed. Use the version which takes a QgsPointV2 instead. +- The writePolyline() method taking a QgsPolyline argument was removed. Use the alternative version instead. +- The writePolygon() method taking a QgsPolygon argument was removed. Use the version which takes a QgsRingSequence instead. +- writeSolid() was removed. Use writePolygon() instead. +- The signature for writeLine() has changed. +- writePoint(), writeFilledCircle(), writeCircle(), writeText() and writeMText() now take QgsPointV2 arguments + + + +QgsEditFormConfig {#qgis_api_break_3_0_QgsEditFormConfig} +----------------- + + +- Does no longer inherit QObject +- widgetType() and widgetConfig() now reflect only the user configured values. +QgsEditorWidgetRegistry::instance()->findBest() must be used instead. +- widgetType(), widgetConfig(), setWidgetType(), setWidgetConfig() and removeWidgetConfig() now only take a string as first parameter. Access by index has been removed. +- expression() has been renamed to constraintExpression() +- setExpression() has been renamed to setConstraintExpression() +- expressionDescription() has been renamed to constraintDescription() +- setExpressionDesctiption() has been renamed to setConstraintDescription() + + +QgsExpression {#qgis_api_break_3_0_QgsExpression} +------------- + + +- prepare( const QgsFields &fields ) has been removed. Use prepare( const QgsExpressionContext *context ) instead. +- The evaluate methods which accept feature parameters have been removed. Use the version which takes a QgsExpressionContext +argument instead. +- isValid( const QString& text, const QgsFields& fields, QString &errorMessage ) has been removed, use the QgsExpressionContext +version instead. +- setCurrentRowNumber, currentRowNumber, scale, setScale, setSpecialColumn, unsetSpecialColumn, specialColumn, hasSpecialColumn have been +removed. Use QgsExpressionContext variables instead. +- The replaceExpressionText version which accepts a QgsFeature argument has been removed. Use the QgsExpressionContext +version instead. +- QgsExpression::Function::func has been modified to use a QgsExpressionContext argument rather than a QgsFeature. +- QgsExpression::Function::usesgeometry() has been renamed to usesGeometry() +- QgsExpression::Function::helptext() has been renamed to helpText() +- The QgsExpression::Node::eval and prepare versions which take a QgsFeature has been removed, use the QgsExpressionContext versions instead. +- QgsExpression::Interval has been removed. Use QgsInterval instead. +- replaceExpressionText() no longer accepts a substitution map parameter. Use expression context variables instead. +- helptext() has been renamed to helpText() +- isValid() has been renamed to checkExpression() +- acceptVisitor() has been removed +- QgsExpression::referencedColumns() returns QSet instead of QStringList +- QgsExpression::Node::referencedColumns() returns QSet instead of QStringList +- QgsExpression::Function::referencedColumns() returns QSet instead of QStringList + + +QgsFeature {#qgis_api_break_3_0_QgsFeature} +---------- + + +- geometryAndOwnership() has been removed. Use geometry() instead. +- setGeometryAndOwnership() has been removed. Use setGeometry() instead. +- The setGeometry( QgsGeometry* ) method has been removed, use setGeometry( const QgsGeometry& ) instead. +- The geometry() method now returns a copy of the geometry, not a pointer. Since QgsGeometry objects are implicitly shared this is a low-cost copy, and avoids ownership and dangling pointer issues. Very important: Testing that a feature has a geometry is now done using the new hasGeometry() method. Any code which compares QgsFeature::geometry() to -None will need to be modified, as the method will return an empty geometry if the feature has no geometry.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The temporary constGeometry() method has been removed. Use geometry() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setFields( const QgsFields*, bool ) has been removed, use setFields( const QgsFields&, bool ) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • fields() no longer returns a pointer, but instead a QgsFields value.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsFeatureRendererV2 QgsFeatureRendererV2 - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The method capabilities() returns QgsFeatureRendererV2::Capabilities flags instead of an integer. The two are binary compatible.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • symbolForFeature( QgsFeature& feature ) has been removed. The symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) method should be used instead (previously available as symbolForFeature2 in PyQGIS bindings). symbolForFeature has been made pure virtual.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • originalSymbolForFeature( QgsFeature& feature ) has been removed. The symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) method should be used instead (previously available as originalSymbolForFeature2 in PyQGIS bindings).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • startRender( QgsRenderContext& context, const QgsVectorLayer *vlayer ) was removed. This function has had no effect since QGIS 2.4
                                                                                                                                                                                      • -
                                                                                                                                                                                      • symbols() has been removed. The symbols( QgsRenderContext& context ) method should be used instead (previously available as symbols2 in PyQGIS bindings).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • writeSld( QDomDocument& doc, const QgsVectorLayer &layer ) was removed. writeSld( QDomDocument& doc, const QgsVectorLayer &layer ) should be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • rotationField() and setRotationField() were removed. Data defined properties for QgsSymbolLayer should be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • willRenderFeature( QgsFeature& feat ) has been removed. The willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) method should be used instead (previously available as willRenderFeature2 in PyQGIS bindings).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • symbolsForFeature( QgsFeature& feat ) has been removed. The symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) method should be used instead (previously available as symbolsForFeature2 in PyQGIS bindings).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • originalSymbolsForFeature( QgsFeature& feat ) has been removed. The originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) method should be used instead (previously available as originalSymbolsForFeature2 in PyQGIS bindings).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • copyPaintEffect() was removed. copyRendererData() should be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsFields QgsFields - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • All const methods which return a field from QgsFields now return a QgsField value, not a reference.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • fieldNameIndex has been renamed to lookupField. See the API documentation for details.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsFieldExpressionWidget QgsFieldExpressionWidget - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • registerGetExpressionContextCallback has been removed in favor of registerExpressionContextGenerator
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsFieldProxyModel QgsFieldProxyModel - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • In QgsFieldProxyModel::Filter, All has been renamed to AllTypes
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsGeometry QgsGeometry - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • All QgsGeometry methods now accept geometry references instead of pointers, and return a QgsGeometry +None will need to be modified, as the method will return an empty geometry if the feature has no geometry. +- The temporary constGeometry() method has been removed. Use geometry() instead. +- setFields( const QgsFields*, bool ) has been removed, use setFields( const QgsFields&, bool ) instead. +- fields() no longer returns a pointer, but instead a QgsFields value. + + +QgsFeatureRendererV2 {#qgis_api_break_3_0_QgsFeatureRendererV2} +-------------------- + + +- The method capabilities() returns QgsFeatureRendererV2::Capabilities flags instead of an integer. The two are binary compatible. +- symbolForFeature( QgsFeature& feature ) has been removed. The symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) method should be used instead (previously available as symbolForFeature2 in PyQGIS bindings). symbolForFeature has been made pure virtual. +- originalSymbolForFeature( QgsFeature& feature ) has been removed. The symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) method should be used instead (previously available as originalSymbolForFeature2 in PyQGIS bindings). +- startRender( QgsRenderContext& context, const QgsVectorLayer *vlayer ) was removed. This function has had no effect since QGIS 2.4 +- symbols() has been removed. The symbols( QgsRenderContext& context ) method should be used instead (previously available as symbols2 in PyQGIS bindings). +- writeSld( QDomDocument& doc, const QgsVectorLayer &layer ) was removed. writeSld( QDomDocument& doc, const QgsVectorLayer &layer ) should be used instead. +- rotationField() and setRotationField() were removed. Data defined properties for QgsSymbolLayer should be used instead. +- willRenderFeature( QgsFeature& feat ) has been removed. The willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) method should be used instead (previously available as willRenderFeature2 in PyQGIS bindings). +- symbolsForFeature( QgsFeature& feat ) has been removed. The symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) method should be used instead (previously available as symbolsForFeature2 in PyQGIS bindings). +- originalSymbolsForFeature( QgsFeature& feat ) has been removed. The originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) method should be used instead (previously available as originalSymbolsForFeature2 in PyQGIS bindings). +- copyPaintEffect() was removed. copyRendererData() should be used instead. + + +QgsFields {#qgis_api_break_3_0_QgsFields} +--------- + + +- All const methods which return a field from QgsFields now return a QgsField value, not a reference. +- fieldNameIndex has been renamed to lookupField. See the API documentation for details. + + +QgsFieldExpressionWidget {#qgis_api_break_3_0_QgsFieldExpressionWidget} +------------------------ + + +- registerGetExpressionContextCallback has been removed in favor of registerExpressionContextGenerator + + +QgsFieldProxyModel {#qgis_api_break_3_0_QgsFieldProxyModel} +------------------ + + +- In QgsFieldProxyModel::Filter, All has been renamed to AllTypes + + +QgsGeometry {#qgis_api_break_3_0_QgsGeometry} +----------- + + +- All QgsGeometry methods now accept geometry references instead of pointers, and return a QgsGeometry value instead of a pointer. The biggest impact with this change is that PyQGIS code should not compare a geometry result to None, but instead either use a boolean test (`if g.buffer(10):`) or explicitly use the isEmpty() -method to determine if a geometry is valid.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPoints
                                                                                                                                                                                      • -
                                                                                                                                                                                      • int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPointsV2
                                                                                                                                                                                      • -
                                                                                                                                                                                      • static bool compare( const QgsPolyline& p1, const QgsPolyline& p2, double epsilon ) has been renamed to comparePolylines
                                                                                                                                                                                      • -
                                                                                                                                                                                      • static bool compare( const QgsPolygon& p1, const QgsPolygon& p2, double epsilon ) has been renamed to comparePolygons
                                                                                                                                                                                      • -
                                                                                                                                                                                      • static bool compare( const QgsMultiPolygon& p1, const QgsMultiPolygon& p2, double epsilon ) has been renamed to compareMultiPolygons
                                                                                                                                                                                      • -
                                                                                                                                                                                      • smoothLine and smoothPolygon are no longer public API (use smooth() instead)
                                                                                                                                                                                      • -
                                                                                                                                                                                      +method to determine if a geometry is valid. +- int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPoints +- int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPointsV2 +- static bool compare( const QgsPolyline& p1, const QgsPolyline& p2, double epsilon ) has been renamed to comparePolylines +- static bool compare( const QgsPolygon& p1, const QgsPolygon& p2, double epsilon ) has been renamed to comparePolygons +- static bool compare( const QgsMultiPolygon& p1, const QgsMultiPolygon& p2, double epsilon ) has been renamed to compareMultiPolygons +- smoothLine and smoothPolygon are no longer public API (use smooth() instead) + + +QgsGeometryAnalyzer {#qgis_api_break_3_0_QgsGeometryAnalyzer} +------------------- + -\subsection qgis_api_break_3_0_QgsGeometryAnalyzer QgsGeometryAnalyzer +- locateBetweenMeasures() and locateAlongMeasure() now take geometry references, not pointers, and return +a QgsGeometry value rather than a pointer. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • locateBetweenMeasures() and locateAlongMeasure() now take geometry references, not pointers, and return -a QgsGeometry value rather than a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsGeometrySimplifier QgsGeometrySimplifier +QgsGeometrySimplifier {#qgis_api_break_3_0_QgsGeometrySimplifier} +--------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • simplifyGeometry() has been removed and simplify() must be used instead .
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsGradientColorRampDialog QgsGradientColorRampDialog +- simplifyGeometry() has been removed and simplify() must be used instead . -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited -and the new ramp can be retrieved after executing the dialog by calling ramp().
                                                                                                                                                                                      • -
                                                                                                                                                                                      • Some internal methods which were previously public or protected were made private.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsGraduatedSymbolRenderer QgsGraduatedSymbolRenderer +QgsGradientColorRampDialog {#qgis_api_break_3_0_QgsGradientColorRampDialog} +--------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • getDataValues() has been removed - use QgsVectorLayer::getDoubleValues() instead
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsGraduatedSymbolRendererWidget QgsGraduatedSymbolRenderer -
                                                                                                                                                                                        -
                                                                                                                                                                                      • sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited +and the new ramp can be retrieved after executing the dialog by calling ramp(). +- Some internal methods which were previously public or protected were made private. -\subsection qgis_api_break_3_0_QgsGraphBuilderInterface QgsGraphBuilderInterface +QgsGraduatedSymbolRenderer {#qgis_api_break_3_0_QgsGraduatedSymbolRenderer} +-------------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ -plugins calling this method will need to be updated.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsEditorWidgetRegistry QgsEditorWidgetRegistry +- getDataValues() has been removed - use QgsVectorLayer::getDoubleValues() instead -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The signature of isFieldSupported() has been changed to return an unsigned (how good it supports the given field) -and to const-correct it.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsGroupWMSDataDialog QgsGroupWMSDataDialog +QgsGraduatedSymbolRenderer {#qgis_api_break_3_0_QgsGraduatedSymbolRendererWidget} +-------------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsGroupWMSDataDialo has been renamed to QgsGroupWmsDataDialog
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsHighlight QgsHighlight - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The QgsHighlight constructor now takes a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsJSONExporter QgsJSONExporter - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • sourceCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ -plugins calling this method will need to be updated.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsLabelingEngineInterface QgsLabelingEngineInterface - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • init(QgsMapRenderer*) has been removed. Use init(const QgsMapSettings&) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • &layer() was removed. use QgsPalLayerSettings::fromLayer() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • addDiagramLayer() was removed. Use prepareDiagramLayer() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • labelsAtPosition() was removed. Use takeResults() and methods of QgsLabelingResults instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • labelsWithinRect() was removed. Use takeResults() and methods of QgsLabelingResults.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsLayerPropertiesWidget QgsLayerPropertiesWidget - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsLayerTreeGroup QgsLayerTreeGroup - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • readChildrenFromXML() has been renamed to readChildrenFromXml()
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsLayerTreeMode QgsLayerTreeModel - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The ShowSymbology flag was removed. Use ShowLegend instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The AllowSymbologyChangeState flag was removed. Use AllowLegendChangeState instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • legendFilterByMap() was renamed to legendFilterMapSettings()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isIndexSymbologyNode() was removed. Use index2legendNode() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • layerNodeForSymbologyNode() was removed. Use index2legendNode()->parent() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • refreshLayerSymbology() was removed. Use refreshLayerLegend() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setAutoCollapseSymbologyNodes() was removed. Use setAutoCollapseLegendNodes() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • autoCollapseSymbologyNodes() was removed. Use autoCollapseLegendNodes() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - - -\subsection qgis_api_break_3_0_QgsLayerTreeNode QgsLayerTreeNode - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • readCommonXML() has been renamed to readCommonXml()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • writeCommonXML() has been renamed to writeCommonXml()
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI. -\subsection qgis_api_break_3_0_QgsLimitedRandomRampDialog QgsLimitedRandomColorRampDialog - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited -and the new ramp can be retrieved after executing the dialog by calling ramp().
                                                                                                                                                                                      • -
                                                                                                                                                                                      • Some internal methods which were previously public or protected were made private.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsMapCanvas QgsMapCanvas -
                                                                                                                                                                                        -
                                                                                                                                                                                      • rotationEnabled() and enableRotation() have been removed, since map rotation is now always supported
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The "name" parameter has been removed from constructor. Use QObject::setObjectName() to set canvas name if necessary.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • map() has been removed because QgsMapCanvasMap is not available in API anymore.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • mapRenderer() has been removed. Use directly map canvas methods to get/set configuration or mapSettings() (for reading only).
                                                                                                                                                                                      • -
                                                                                                                                                                                      • canvasPaintDevice() has been removed. Use map canvas items to draw anything on top of canvas.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • clear() has been removed. Use refresh() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setCanvasColor() and canvasColor() are not virtual methods anymore.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • updateFullExtent() has been removed. No need to call it explicitly. Full extent calculation is done in QgsMapSettings.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setDirty() and isDirty() have been removed. Use refresh() to refresh canvas content.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setWheelAction() and WheelAction enum have been removed. Custom wheel actions are not supported anymore.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • updateMap(), showError(), useImageToRender() have been removed. They did nothing since 2.4.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setProgress() signal has been removed. It was not emitted since 2.0.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapCanvasItem QgsMapCanvasItem - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • setPanningOffset() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsGraphBuilderInterface {#qgis_api_break_3_0_QgsGraphBuilderInterface} +------------------------ -\subsection qgis_api_break_3_0_QgsMapLayer QgsMapLayer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • crs() now returns a QgsCoordinateReferenceSystem object, not a reference. This change has no effect for PyQGIS code.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • createMapRenderer() has been made pure virtual.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • draw() has been removed. Use createMapRenderer() method for rendering of layers.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setLayerName() was removed, use setName() instead. The layerNameChanged() signal has been replaced by nameChanged().
                                                                                                                                                                                      • -
                                                                                                                                                                                      • toggleScaleBasedVisibility() was replaced by setScaleBasedVisibility()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • lastErrorTitle(), lastError(), cacheImage(), onCacheImageDelete(), clearCacheImage() and the signals drawingProgress(), -screenUpdateRequested() were removed. These members have had no effect for a number of QGIS 2.x releases.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • extent(), styleURI(), exportNamedStyle(), exportSldStyle(), writeXml(), metadata() were made const. This has no effect on PyQGIS code, but c++ code implementing derived layer classes will need to update the signatures of these methods to match.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The lyrname parameter in the QgsMapLayer constructor was renamed to 'name'.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The vis parameter in setSubLayerVisibility was renamed to 'visible'.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • theResultFlag parameter in loadDefaultStyle and saveDefaultStyle were renamed to resultFlag.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • theURI, theResultFlag parameters in loadNamedStyle, saveNamedStyle, saveSldStyle and loadSldStyle were renamed to uri, resultFlag.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • theURI parameter in loadNamedStyleFromDb was renamed to uri.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • theMinScale and theMaxScale parameters in setMinimumScale and setMaximumScale were renamed to scale
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The layerCrsChanged() signal was renamed to crsChanged()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • theError parameter in appendError() and setError() were renamed to 'error'.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • drawLabels() method was removed. It used old deprecated labeling. Replaced by labeling based on PAL library, see QgsLabelingEngineV2.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • readLayerXML() was renamed to readLayerXml()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • writeLayerXML() was renamed to writeLayerXml()
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapLayerRegistry QgsMapLayerRegistry - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • clearAllLayerCaches() was removed. This method has had no effect since QGIS 2.4
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapOverviewCanvas QgsMapOverviewCanvas - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • destinationSrsChanged() was renamed to destinationCrsChanged()
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapRenderer QgsMapRenderer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • transformation() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be returned instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • destinationSrsChanged() was renamed to destinationCrsChanged()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • getCompositionMode(), getBlendModeEnum() and BlendMode enum have been moved to QgsPainting utility class.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapRendererJob QgsMapRendererJob - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • reprojectToLayerExtent() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should -be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • prepareJobs() and drawLabeling() (neither available in PyQGIS) do not take QgsPalLabeling parameter anymore. All drawing of labels is done by QgsLabelingEngineV2.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • drawOldLabeling(), drawNewLabeling() were removed. The method drawLabeling() should be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapTool QgsMapTool - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • renderComplete() was removed. Map tools must not directly depend on rendering progress.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isTransient() and isEditTool() were removed. Use flags() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapToolCapture QgsMapToolCapture - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The nextPoint() method taking a QgsPoint was removed. Use the version taking a QgsPointV2 instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapToPixel QgsMapToPixel - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The constructor now uses the map center x and y, and requires both height and width in pixels and a rotation value
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setYMaximum(), setYMinimum(), setXMinimum() were removed. Use setParameters() instead
                                                                                                                                                                                      • - -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsMapToPixelGeometrySimplifier QgsMapToPixelGeometrySimplifier + +- destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ +plugins calling this method will need to be updated. + + +QgsEditorWidgetRegistry {#qgis_api_break_3_0_QgsEditorWidgetRegistry} +----------------------- + + +- The signature of isFieldSupported() has been changed to return an unsigned (how good it supports the given field) +and to const-correct it. + + +QgsGroupWMSDataDialog {#qgis_api_break_3_0_QgsGroupWMSDataDialog} +--------------------- + + +- QgsGroupWMSDataDialo has been renamed to QgsGroupWmsDataDialog + + +QgsHighlight {#qgis_api_break_3_0_QgsHighlight} +------------ + + +- The QgsHighlight constructor now takes a geometry reference, not a pointer. + + +QgsJSONExporter {#qgis_api_break_3_0_QgsJSONExporter} +--------------- + + +- sourceCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ +plugins calling this method will need to be updated. + + +QgsLabelingEngineInterface {#qgis_api_break_3_0_QgsLabelingEngineInterface} +-------------------------- + + +- init(QgsMapRenderer*) has been removed. Use init(const QgsMapSettings&) instead. +- &layer() was removed. use QgsPalLayerSettings::fromLayer() instead. +- addDiagramLayer() was removed. Use prepareDiagramLayer() instead. +- labelsAtPosition() was removed. Use takeResults() and methods of QgsLabelingResults instead. +- labelsWithinRect() was removed. Use takeResults() and methods of QgsLabelingResults. + + +QgsLayerPropertiesWidget {#qgis_api_break_3_0_QgsLayerPropertiesWidget} +------------------------ + + +- expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() + + +QgsLayerTreeGroup {#qgis_api_break_3_0_QgsLayerTreeGroup} +----------------- + + +- readChildrenFromXML() has been renamed to readChildrenFromXml() + + +QgsLayerTreeModel {#qgis_api_break_3_0_QgsLayerTreeMode} +----------------- + + +- The ShowSymbology flag was removed. Use ShowLegend instead. +- The AllowSymbologyChangeState flag was removed. Use AllowLegendChangeState instead. +- legendFilterByMap() was renamed to legendFilterMapSettings() +- isIndexSymbologyNode() was removed. Use index2legendNode() instead. +- layerNodeForSymbologyNode() was removed. Use index2legendNode()->parent() instead. +- refreshLayerSymbology() was removed. Use refreshLayerLegend() instead. +- setAutoCollapseSymbologyNodes() was removed. Use setAutoCollapseLegendNodes() instead. +- autoCollapseSymbologyNodes() was removed. Use autoCollapseLegendNodes() instead. + + + +QgsLayerTreeNode {#qgis_api_break_3_0_QgsLayerTreeNode} +---------------- + + +- readCommonXML() has been renamed to readCommonXml() +- writeCommonXML() has been renamed to writeCommonXml() + + +QgsLimitedRandomColorRampDialog {#qgis_api_break_3_0_QgsLimitedRandomRampDialog} +------------------------------- + + +- The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited +and the new ramp can be retrieved after executing the dialog by calling ramp(). +- Some internal methods which were previously public or protected were made private. + + +QgsMapCanvas {#qgis_api_break_3_0_QgsMapCanvas} +------------ + + +- rotationEnabled() and enableRotation() have been removed, since map rotation is now always supported +- The "name" parameter has been removed from constructor. Use QObject::setObjectName() to set canvas name if necessary. +- map() has been removed because QgsMapCanvasMap is not available in API anymore. +- mapRenderer() has been removed. Use directly map canvas methods to get/set configuration or mapSettings() (for reading only). +- canvasPaintDevice() has been removed. Use map canvas items to draw anything on top of canvas. +- clear() has been removed. Use refresh() instead. +- setCanvasColor() and canvasColor() are not virtual methods anymore. +- updateFullExtent() has been removed. No need to call it explicitly. Full extent calculation is done in QgsMapSettings. +- setDirty() and isDirty() have been removed. Use refresh() to refresh canvas content. +- setWheelAction() and WheelAction enum have been removed. Custom wheel actions are not supported anymore. +- updateMap(), showError(), useImageToRender() have been removed. They did nothing since 2.4. +- setProgress() signal has been removed. It was not emitted since 2.0. + + +QgsMapCanvasItem {#qgis_api_break_3_0_QgsMapCanvasItem} +---------------- + + +- setPanningOffset() was removed. + + +QgsMapLayer {#qgis_api_break_3_0_QgsMapLayer} +----------- + + +- crs() now returns a QgsCoordinateReferenceSystem object, not a reference. This change has no effect for PyQGIS code. +- createMapRenderer() has been made pure virtual. +- draw() has been removed. Use createMapRenderer() method for rendering of layers. +- setLayerName() was removed, use setName() instead. The layerNameChanged() signal has been replaced by nameChanged(). +- toggleScaleBasedVisibility() was replaced by setScaleBasedVisibility() +- lastErrorTitle(), lastError(), cacheImage(), onCacheImageDelete(), clearCacheImage() and the signals drawingProgress(), +screenUpdateRequested() were removed. These members have had no effect for a number of QGIS 2.x releases. +- extent(), styleURI(), exportNamedStyle(), exportSldStyle(), writeXml(), metadata() were made const. This has no effect on PyQGIS code, but c++ code implementing derived layer classes will need to update the signatures of these methods to match. +- The lyrname parameter in the QgsMapLayer constructor was renamed to 'name'. +- The vis parameter in setSubLayerVisibility was renamed to 'visible'. +- theResultFlag parameter in loadDefaultStyle and saveDefaultStyle were renamed to resultFlag. +- theURI, theResultFlag parameters in loadNamedStyle, saveNamedStyle, saveSldStyle and loadSldStyle were renamed to uri, resultFlag. +- theURI parameter in loadNamedStyleFromDb was renamed to uri. +- theMinScale and theMaxScale parameters in setMinimumScale and setMaximumScale were renamed to scale +- The layerCrsChanged() signal was renamed to crsChanged() +- theError parameter in appendError() and setError() were renamed to 'error'. +- drawLabels() method was removed. It used old deprecated labeling. Replaced by labeling based on PAL library, see QgsLabelingEngineV2. +- readLayerXML() was renamed to readLayerXml() +- writeLayerXML() was renamed to writeLayerXml() + + +QgsMapLayerRegistry {#qgis_api_break_3_0_QgsMapLayerRegistry} +------------------- + +- clearAllLayerCaches() was removed. This method has had no effect since QGIS 2.4 + + +QgsMapOverviewCanvas {#qgis_api_break_3_0_QgsMapOverviewCanvas} +-------------------- + +- destinationSrsChanged() was renamed to destinationCrsChanged() + + +QgsMapRenderer {#qgis_api_break_3_0_QgsMapRenderer} +-------------- + + +- transformation() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be returned instead of a null pointer if no transformation is required. +- destinationSrsChanged() was renamed to destinationCrsChanged() +- getCompositionMode(), getBlendModeEnum() and BlendMode enum have been moved to QgsPainting utility class. + + +QgsMapRendererJob {#qgis_api_break_3_0_QgsMapRendererJob} +----------------- + + +- reprojectToLayerExtent() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should +be used instead of a null pointer if no transformation is required. +- prepareJobs() and drawLabeling() (neither available in PyQGIS) do not take QgsPalLabeling parameter anymore. All drawing of labels is done by QgsLabelingEngineV2. +- drawOldLabeling(), drawNewLabeling() were removed. The method drawLabeling() should be used instead. + + +QgsMapTool {#qgis_api_break_3_0_QgsMapTool} +---------- + + +- renderComplete() was removed. Map tools must not directly depend on rendering progress. +- isTransient() and isEditTool() were removed. Use flags() instead. + + +QgsMapToolCapture {#qgis_api_break_3_0_QgsMapToolCapture} +----------------- + + +- The nextPoint() method taking a QgsPoint was removed. Use the version taking a QgsPointV2 instead. + + +QgsMapToPixel {#qgis_api_break_3_0_QgsMapToPixel} +------------- + + +- The constructor now uses the map center x and y, and requires both height and width in pixels and a rotation value +- setYMaximum(), setYMinimum(), setXMinimum() were removed. Use setParameters() instead + + + +QgsMapToPixelGeometrySimplifier {#qgis_api_break_3_0_QgsMapToPixelGeometrySimplifier} +------------------------------- The whole class has been refactored to stop using WKB and to use QgsAbstractGeometry classes. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • simplifyGeometry(), simplifyPoints(), isGeneralizableByMapBoundingBox(), _getLineString(), _getPolygon() methods have been removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The signature of the static methods _getPoint(), _getLineString() and _getPolygon() have been changed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsMapSettings QgsMapSettings +- simplifyGeometry(), simplifyPoints(), isGeneralizableByMapBoundingBox(), _getLineString(), _getPolygon() methods have been removed. +- The signature of the static methods _getPoint(), _getLineString() and _getPolygon() have been changed. + + +QgsMapSettings {#qgis_api_break_3_0_QgsMapSettings} +-------------- + + +- layerTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be returned instead of a null pointer if no transformation is required. +- destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ +plugins calling this method will need to be updated. + + +QgsMarkerSymbolLayer {#qgis_api_break_3_0_QgsMarkerSymbolLayer} +-------------------- + + +- bounds() is now pure virtual and must be implemented in all subclasses. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • layerTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be returned instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ -plugins calling this method will need to be updated.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsMarkerSymbolLayer QgsMarkerSymbolLayer +QgsMimeDataUtils {#qgis_api_break_3_0_QgsMimeDataUtils} +---------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • bounds() is now pure virtual and must be implemented in all subclasses.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsMimeDataUtils QgsMimeDataUtils +- Constructor taking QgsLayerItem argument has been removed. Use QgsDataItem::mimeUri() instead. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • Constructor taking QgsLayerItem argument has been removed. Use QgsDataItem::mimeUri() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsNetworkAccessManager QgsNetworkAccessManager +QgsNetworkAccessManager {#qgis_api_break_3_0_QgsNetworkAccessManager} +----------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • sendGet() was removed. Use get() directly.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • deleteReply() was removed. Use abort() and deleteLayer() on the reply directly.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • requestSent signal was removed. This is no longer emitted.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsOSMElement QgsOSMElement +- sendGet() was removed. Use get() directly. +- deleteReply() was removed. Use abort() and deleteLayer() on the reply directly. +- requestSent signal was removed. This is no longer emitted. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • elemID() has been renamed to elemId()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsOwsConnection QgsOwsConnection +QgsOSMElement {#qgis_api_break_3_0_QgsOSMElement} +------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • connectionInfo() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsOWSSourceSelect QgsOWSSourceSelect +- elemID() has been renamed to elemId() -
                                                                                                                                                                                        -
                                                                                                                                                                                      • selectedLayersCRSs() has been renamed selectedLayersCrses()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • populateCRS() has been renamed to populateCrs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • clearCRS() has been renamed to clearCrs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • addWMSListRow() has been renamed to addWmsListRow()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • addWMSListItem() has been renamed to addWmsListItem()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • selectedCRS() has been renamed to selectedCrs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsOWSConnection QgsOWSConnection +QgsOwsConnection {#qgis_api_break_3_0_QgsOwsConnection} +---------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsOWSConnection has been renamed QgsOwsConnection
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsNumericSortTreeWidgetItem QgsNumericSortTreeWidgetItem +- connectionInfo() was removed. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsNumericSortTreeWidgetItem has been removed and replaced with QgsTreeWidgetItem, which + +QgsOWSSourceSelect {#qgis_api_break_3_0_QgsOWSSourceSelect} +------------------ + + +- selectedLayersCRSs() has been renamed selectedLayersCrses() +- populateCRS() has been renamed to populateCrs() +- clearCRS() has been renamed to clearCrs() +- addWMSListRow() has been renamed to addWmsListRow() +- addWMSListItem() has been renamed to addWmsListItem() +- selectedCRS() has been renamed to selectedCrs() + + +QgsOWSConnection {#qgis_api_break_3_0_QgsOWSConnection} +---------------- + + +- QgsOWSConnection has been renamed QgsOwsConnection + + +QgsNumericSortTreeWidgetItem {#qgis_api_break_3_0_QgsNumericSortTreeWidgetItem} +---------------------------- + + +- QgsNumericSortTreeWidgetItem has been removed and replaced with QgsTreeWidgetItem, which has improved sort capabilities including the ability to set custom sort values for items -and for forcing certain items to always sort on top.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +and for forcing certain items to always sort on top. + + +QgsPalLabeling {#qgis_api_break_3_0_QgsPalLabeling} +-------------- -\subsection qgis_api_break_3_0_QgsPalLabeling QgsPalLabeling -
                                                                                                                                                                                        -
                                                                                                                                                                                      • init(QgsMapRenderer*) has been removed. Use init(const QgsMapSettings&) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • prepareGeometry and geometryRequiresPreparation now take geometry references, not pointers.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • layer() was removed. If direct access to QgsPalLayerSettings is necessary, use QgsPalLayerSettings::fromLayer()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • candidates() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • addDiagramLayer() was removed. Use prepareDiagramLayer() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • labelsAtPosition() was removed. Use takeResults() and methods of QgsLabelingResults instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • labelsWithinRect() was removed. Use takeResults() and methods of QgsLabelingResults instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isStoredWithProject() and setStoredWithProject() had no effect and were removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsPalLayerSettings QgsPalLayerSettings - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • ct is now a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • prepareGeometry() and geometryRequiresPreparation() now take a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsPanelWidgetStack QgsPanelWidgetStack - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • addMainPanel() has been renamed to setMainPanel()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • mainWidget() has been renamed to mainPanel()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • takeMainWidget() has been renamed to takeMainPanel()
                                                                                                                                                                                      • -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsPluginLayer QgsPluginLayer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • createMapRenderer(): default implementation (which called plugin's draw() method) has been removed. Plugin layers must implement createMapRenderer().
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- init(QgsMapRenderer*) has been removed. Use init(const QgsMapSettings&) instead. +- prepareGeometry and geometryRequiresPreparation now take geometry references, not pointers. +- layer() was removed. If direct access to QgsPalLayerSettings is necessary, use QgsPalLayerSettings::fromLayer() +- candidates() was removed. +- addDiagramLayer() was removed. Use prepareDiagramLayer() instead. +- labelsAtPosition() was removed. Use takeResults() and methods of QgsLabelingResults instead. +- labelsWithinRect() was removed. Use takeResults() and methods of QgsLabelingResults instead. +- isStoredWithProject() and setStoredWithProject() had no effect and were removed. -\subsection qgis_api_break_3_0_QgsPointDisplacementRenderer QgsPointDisplacementRenderer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The deprecated method setDisplacementGroups() has been removed. This method has had no effect since QGIS 2.4
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsPointLocator QgsPointLocator +QgsPalLayerSettings {#qgis_api_break_3_0_QgsPalLayerSettings} +------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The constructor now takes a reference rather than a pointer to a CRS. This has no effect on PyQGIS code, but c++ -plugins calling this method will need to be updated.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The destCRS parameter in the constructor has been renamed to destinationCrs.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • destCRS() has been renamed to destinationCrs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ -plugins calling this method will need to be updated.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsProject QgsProject +- ct is now a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be used instead of a null pointer if no transformation is required. +- prepareGeometry() and geometryRequiresPreparation() now take a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • visibilityPresetCollection() has been renamed to mapThemeCollection()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • title( const QString & title ) was removed. Use setTitle() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • dirty( bool b ) was removed. Use setDirty() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • clearProperties() was removed. Use clear() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRasterCalcNode QgsRasterCalcNode +QgsPanelWidgetStack {#qgis_api_break_3_0_QgsPanelWidgetStack} +------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsRasterCalcNode::calculate has been removed, use method with QgsRasterBlocks instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRasterDataProvider QgsRasterDataProvider +- addMainPanel() has been renamed to setMainPanel() +- mainWidget() has been renamed to mainPanel() +- takeMainWidget() has been renamed to takeMainPanel() -
                                                                                                                                                                                        -
                                                                                                                                                                                      • srcDataType() has been renamed to sourceDataType()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • srcHasNoDataValue() has been renamed to sourceHasNoDataValue()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • useSrcNoDataValue() has been renamed to useSourceNoDataValue()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setUseSrcNoDataValue() has been renamed to setUseSourceNoDataValue()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • srcNoDataValue() has been renamed to sourceNoDataValue()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRasterInterface QgsRasterInterface +QgsPluginLayer {#qgis_api_break_3_0_QgsPluginLayer} +-------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • srcDataType() has been renamed to sourceDataType()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • srcInput() has been renamed to sourceInput()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • block() has new "feedback" argument.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRasterLayer QgsRasterLayer +- createMapRenderer(): default implementation (which called plugin's draw() method) has been removed. Plugin layers must implement createMapRenderer(). -
                                                                                                                                                                                        -
                                                                                                                                                                                      • setDrawingStyle() was removed. Use setRendererForDrawingStyle() or setRenderer() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • previewAsPixmap() was removed. Use previewAsImage() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • updateProgress() had no effect and was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRasterProjector QgsRasterProjector +QgsPointDisplacementRenderer {#qgis_api_break_3_0_QgsPointDisplacementRenderer} +---------------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • extentSize() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRelation QgsRelation +- The deprecated method setDisplacementGroups() has been removed. This method has had no effect since QGIS 2.4 -
                                                                                                                                                                                        -
                                                                                                                                                                                      • createFromXML() has been renamed to createFromXml()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRenderChecker QgsRenderChecker +QgsPointLocator {#qgis_api_break_3_0_QgsPointLocator} +--------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • setMapRenderer() has been removed. Use setMapSettings() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • excludeAttributesWMS() and setExcludeAttributesWMS() have been renamed to excludeAttributesWms() and -setExcludeAttributesWms()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • excludeAttributesWFS() and setExcludeAttributesWFS() have been renamed to excludeAttributesWfs() and -setExcludeAttributesWfs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • editorWidgetV2() and editorWidgetV2Config() have been removed and QgsEditorWidgetRegistry::instance()->findBest() must be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setEditorWidgetV2(), setEditorWidgetV2Config() have been removed and their equivalent in editFormConfig() must be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setCheckedState() is removed. Use editFormConfig()->setWidgetConfig()` instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • valueMap(), valueRelation(), dateFormat(), widgetSize() have been removed. Use QgsEditorWidgetRegistry::instance()->findBest().config() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRenderContext QgsRenderContext +- The constructor now takes a reference rather than a pointer to a CRS. This has no effect on PyQGIS code, but c++ +plugins calling this method will need to be updated. +- The destCRS parameter in the constructor has been renamed to destinationCrs. +- destCRS() has been renamed to destinationCrs() +- destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ +plugins calling this method will need to be updated. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • coordinateTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will -be returned instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setCoordinateTransform() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRendererWidget QgsRendererWidget +QgsProject {#qgis_api_break_3_0_QgsProject} +---------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRendererRulePropsWidget QgsRendererRulePropsWidget +- visibilityPresetCollection() has been renamed to mapThemeCollection() +- title( const QString & title ) was removed. Use setTitle() instead. +- dirty( bool b ) was removed. Use setDirty() instead. +- clearProperties() was removed. Use clear() instead. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsRasterCalcNode {#qgis_api_break_3_0_QgsRasterCalcNode} +----------------- -\subsection qgis_api_break_3_0_QgsRubberBand QgsRubberBand +- QgsRasterCalcNode::calculate has been removed, use method with QgsRasterBlocks instead. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • setToGeometry() and addGeometry() now take geometry references, not pointers.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsRubberBand( QgsMapCanvas* mapCanvas, bool isPolygon ) constructor and reset( bool isPolygon) have been removed, use constructor and function with Qgis::GeometryType as argument instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRuleBasedRenderer QgsRuleBasedRenderer +QgsRasterDataProvider {#qgis_api_break_3_0_QgsRasterDataProvider} +--------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsRuleBasedRenderer.Rule checkState() and setCheckState() were removed. Use active() and setActive() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • QgsRuleBasedRenderer.Rule updateElseRules() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • startRender( QgsRenderContext& context, const QgsFields& fields ) was removed. Use startRender( QgsRenderContext& context, const QgsFields& fields, QString& filter ) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsRuleBasedRendererWidget QgsRuleBasedRendererWidget +- srcDataType() has been renamed to sourceDataType() +- srcHasNoDataValue() has been renamed to sourceHasNoDataValue() +- useSrcNoDataValue() has been renamed to useSourceNoDataValue() +- setUseSrcNoDataValue() has been renamed to setUseSourceNoDataValue() +- srcNoDataValue() has been renamed to sourceNoDataValue() -
                                                                                                                                                                                        -
                                                                                                                                                                                      • refineRuleCategoriesGui() and refineRuleRangesGui() no longer take a QModelIndexList argument.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSimpleMarkerSymbolLayer QgsSimpleMarkerSymbolLayer +QgsRasterInterface {#qgis_api_break_3_0_QgsRasterInterface} +------------------ -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The constructor variant with a string for the shape name has been removed. Use the variant which accepts a QgsSimpleMarkerSymbolLayerBase.Shape enum instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • name() and setName() have been removed. Use shape() and setShape() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • prepareShape() and preparePath() were removed. Calling these methods manually should no longer be required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSimpleMarkerSymbolLayerWidget QgsSimpleMarkerSymbolLayerWidget +- srcDataType() has been renamed to sourceDataType() +- srcInput() has been renamed to sourceInput() +- block() has new "feedback" argument. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • setName() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsRasterLayer {#qgis_api_break_3_0_QgsRasterLayer} +-------------- -\subsection qgis_api_break_3_0_QgsSingleSymbolRendererWidget QgsSingleSymbolRendererWidget -
                                                                                                                                                                                        -
                                                                                                                                                                                      • sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSnapper QgsSnapper +- setDrawingStyle() was removed. Use setRendererForDrawingStyle() or setRenderer() instead. +- previewAsPixmap() was removed. Use previewAsImage() instead. +- updateProgress() had no effect and was removed. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • Constructor variant with QgsMapRenderer has been removed. Use the variant with QgsMapSettings.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • Signature for snapPoint() has changed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSublayersDialog QgsSublayersDialog +QgsRasterProjector {#qgis_api_break_3_0_QgsRasterProjector} +------------------ -
                                                                                                                                                                                        -
                                                                                                                                                                                      • populateLayerTable() now takes a list of QgsSublayersDialog.LayerDefinition values
                                                                                                                                                                                      • -
                                                                                                                                                                                      • selectionNames() and selectionIndexes() were removed. Use selection().
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSvgCache QgsSvgCache +- extentSize() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • containsParamsV2() was removed. Use containsParamsV3() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSymbol QgsSymbol (renamed from QgsSymbolV2) +QgsRelation {#qgis_api_break_3_0_QgsRelation} +----------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The OutputUnit enum, including QgsSymbol::MM, QgsSymbol::MapUnit, QgsSymbol::Mixed, QgsSymbol::Pixel and QgsSymbol::Percentage has been moved to QgsUnitTypes + +- createFromXML() has been renamed to createFromXml() + + +QgsRenderChecker {#qgis_api_break_3_0_QgsRenderChecker} +---------------- + + +- setMapRenderer() has been removed. Use setMapSettings() instead. +- excludeAttributesWMS() and setExcludeAttributesWMS() have been renamed to excludeAttributesWms() and +setExcludeAttributesWms() +- excludeAttributesWFS() and setExcludeAttributesWFS() have been renamed to excludeAttributesWfs() and +setExcludeAttributesWfs() +- editorWidgetV2() and editorWidgetV2Config() have been removed and QgsEditorWidgetRegistry::instance()->findBest() must be used instead. +- setEditorWidgetV2(), setEditorWidgetV2Config() have been removed and their equivalent in editFormConfig() must be used instead. +- setCheckedState() is removed. Use editFormConfig()->setWidgetConfig()` instead. +- valueMap(), valueRelation(), dateFormat(), widgetSize() have been removed. Use QgsEditorWidgetRegistry::instance()->findBest().config() instead. + + +QgsRenderContext {#qgis_api_break_3_0_QgsRenderContext} +---------------- + + +- coordinateTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will +be returned instead of a null pointer if no transformation is required. +- setCoordinateTransform() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. + + +QgsRendererWidget {#qgis_api_break_3_0_QgsRendererWidget} +----------------- + + +- expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() + + +QgsRendererRulePropsWidget {#qgis_api_break_3_0_QgsRendererRulePropsWidget} +-------------------------- + + +- expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() + + + + +QgsRubberBand {#qgis_api_break_3_0_QgsRubberBand} +------------- + + +- setToGeometry() and addGeometry() now take geometry references, not pointers. +- QgsRubberBand( QgsMapCanvas* mapCanvas, bool isPolygon ) constructor and reset( bool isPolygon) have been removed, use constructor and function with Qgis::GeometryType as argument instead. + + +QgsRuleBasedRenderer {#qgis_api_break_3_0_QgsRuleBasedRenderer} +-------------------- + + +- QgsRuleBasedRenderer.Rule checkState() and setCheckState() were removed. Use active() and setActive() instead. +- QgsRuleBasedRenderer.Rule updateElseRules() was removed. +- startRender( QgsRenderContext& context, const QgsFields& fields ) was removed. Use startRender( QgsRenderContext& context, const QgsFields& fields, QString& filter ) instead. + + +QgsRuleBasedRendererWidget {#qgis_api_break_3_0_QgsRuleBasedRendererWidget} +-------------------------- + + +- refineRuleCategoriesGui() and refineRuleRangesGui() no longer take a QModelIndexList argument. + + +QgsSimpleMarkerSymbolLayer {#qgis_api_break_3_0_QgsSimpleMarkerSymbolLayer} +-------------------------- + + +- The constructor variant with a string for the shape name has been removed. Use the variant which accepts a QgsSimpleMarkerSymbolLayerBase.Shape enum instead. +- name() and setName() have been removed. Use shape() and setShape() instead. +- prepareShape() and preparePath() were removed. Calling these methods manually should no longer be required. + + +QgsSimpleMarkerSymbolLayerWidget {#qgis_api_break_3_0_QgsSimpleMarkerSymbolLayerWidget} +-------------------------------- + + +- setName() was removed. + + + +QgsSingleSymbolRendererWidget {#qgis_api_break_3_0_QgsSingleSymbolRendererWidget} +----------------------------- + +- sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI. + + +QgsSnapper {#qgis_api_break_3_0_QgsSnapper} +---------- + + +- Constructor variant with QgsMapRenderer has been removed. Use the variant with QgsMapSettings. +- Signature for snapPoint() has changed. + + +QgsSublayersDialog {#qgis_api_break_3_0_QgsSublayersDialog} +------------------ + + +- populateLayerTable() now takes a list of QgsSublayersDialog.LayerDefinition values +- selectionNames() and selectionIndexes() were removed. Use selection(). + + +QgsSvgCache {#qgis_api_break_3_0_QgsSvgCache} +----------- + + +- containsParamsV2() was removed. Use containsParamsV3() instead. + + +QgsSymbol (renamed from QgsSymbolV2) {#qgis_api_break_3_0_QgsSymbol} +------------------------------------ + + +- The OutputUnit enum, including QgsSymbol::MM, QgsSymbol::MapUnit, QgsSymbol::Mixed, QgsSymbol::Pixel and QgsSymbol::Percentage has been moved to QgsUnitTypes and renamed to RenderUnit. QgsSymbol::OutputUnitList was renamed to QgsUnitTypes::RenderUnitList. All methods which previously accepted QgsSymbol::OutputUnit -parameters or QgsSymbol::OutputUnitList parameters now take QgsUnitTypes::RenderUnit or QgsUnitTypes::RenderUnitList parameters respectively.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • startRender() now accepts a QgsFields reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • isSymbolLayerCompatible() was removed. Use QgsSymbolLayer::isCompatibleWithSymbol() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The DataDefinedSizeScale flag has been removed. This is no longer used and data defined scaling on a symbol layer level should be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The DataDefinedRotation RenderHint was renamed to DynamicRotation, as it is no longer used for -data defined rotation.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setRenderHints() and renderHints() now accept and return a QgsSymbol::RenderHints flag rather -than an integer value
                                                                                                                                                                                      • -
                                                                                                                                                                                      +parameters or QgsSymbol::OutputUnitList parameters now take QgsUnitTypes::RenderUnit or QgsUnitTypes::RenderUnitList parameters respectively. +- startRender() now accepts a QgsFields reference, not a pointer. +- isSymbolLayerCompatible() was removed. Use QgsSymbolLayer::isCompatibleWithSymbol() instead. +- The DataDefinedSizeScale flag has been removed. This is no longer used and data defined scaling on a symbol layer level should be used instead. +- The DataDefinedRotation RenderHint was renamed to DynamicRotation, as it is no longer used for +data defined rotation. +- setRenderHints() and renderHints() now accept and return a QgsSymbol::RenderHints flag rather +than an integer value + + +QgsSymbolLayer (renamed from QgsSymbolLayerV2) {#qgis_api_break_3_0_QgsSymbolLayer} +---------------------------------------------- + + +- The deprecated prepareExpressions( const QgsFields* fields, double scale = -1.0 ) method has been removed. Use +the variant which takes QgsSymbolRenderContext instead. +- The deprecated methods dataDefinedProperty( const QString& property ) and dataDefinedPropertyString() were removed. Use getDataDefinedProperty() instead. +- setDataDefinedProperty( const QString& property, const QString& expressionString ) was removed. Use setDataDefinedProperty( const QString& property, QgsDataDefined* dataDefined ) instead. +- evaluateDataDefinedProperty( const QString& property, const QgsFeature* feature ) was removed. Use the variant which takes QgsSymbolRenderContext instead. +- expression() was removed. Use getDataDefinedProperty or evaluateDataDefinedProperty instead. + + +QgsSymbolLayerWidget {#qgis_api_break_3_0_QgsSymbolLayerWidget} +-------------------- + + +- expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() + + + +QgsSymbolRenderContext (renamed from QgsSymbolV2RenderContext) {#qgis_api_break_3_0_QgsSymbolRenderContext} +-------------------------------------------------------------- + + +- The constructor now accepts a QgsFields reference, not a pointer. +- The constructor, setRenderHints() and renderHints() now accept and return a QgsSymbol::RenderHints flag rather +than an integer value +- fields() now returns a QgsFields value, not a pointer. + + +QgsSymbolLayerUtils (renamed from QgsSymbolLayerUtilsV2) {#qgis_api_break_3_0_QgsSymbolLayerUtils} +-------------------------------------------------------- + + +- encodeOutputUnit() and decodeOutputUnit() were removed. QgsUnitTypes::encodeUnit() and QgsUnitTypes::decodeRenderUnit() should be used instead. +- The signatures for wellKnownMarkerToSld() and wellKnownMarkerFromSld() were changed. + + +QgsSymbolSelectorDialog {#qgis_api_break_3_0_QgsSymbolSelectorDialog} +----------------------- -\subsection qgis_api_break_3_0_QgsSymbolLayer QgsSymbolLayer (renamed from QgsSymbolLayerV2) -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The deprecated prepareExpressions( const QgsFields* fields, double scale = -1.0 ) method has been removed. Use -the variant which takes QgsSymbolRenderContext instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The deprecated methods dataDefinedProperty( const QString& property ) and dataDefinedPropertyString() were removed. Use getDataDefinedProperty() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setDataDefinedProperty( const QString& property, const QString& expressionString ) was removed. Use setDataDefinedProperty( const QString& property, QgsDataDefined* dataDefined ) instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • evaluateDataDefinedProperty( const QString& property, const QgsFeature* feature ) was removed. Use the variant which takes QgsSymbolRenderContext instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • expression() was removed. Use getDataDefinedProperty or evaluateDataDefinedProperty instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- saveSymbol() was removed. -\subsection qgis_api_break_3_0_QgsSymbolLayerWidget QgsSymbolLayerWidget -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsSymbolSelectorWidget {#qgis_api_break_3_0_QgsSymbolSelectorWidget} +----------------------- -\subsection qgis_api_break_3_0_QgsSymbolRenderContext QgsSymbolRenderContext (renamed from QgsSymbolV2RenderContext) +- saveSymbol() was removed. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • The constructor now accepts a QgsFields reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The constructor, setRenderHints() and renderHints() now accept and return a QgsSymbol::RenderHints flag rather -than an integer value
                                                                                                                                                                                      • -
                                                                                                                                                                                      • fields() now returns a QgsFields value, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSymbolLayerUtils QgsSymbolLayerUtils (renamed from QgsSymbolLayerUtilsV2) +QgsSymbolSelectorDialog {#qgis_api_break_3_0_QgsSymbolSelectorDialog} +----------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • encodeOutputUnit() and decodeOutputUnit() were removed. QgsUnitTypes::encodeUnit() and QgsUnitTypes::decodeRenderUnit() should be used instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The signatures for wellKnownMarkerToSld() and wellKnownMarkerFromSld() were changed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSymbolSelectorDialog QgsSymbolSelectorDialog +- expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() -
                                                                                                                                                                                        -
                                                                                                                                                                                      • saveSymbol() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSymbolSelectorWidget QgsSymbolSelectorWidget +QgsSymbolsListWidget {#qgis_api_break_3_0_QgsSymbolsListWidget} +-------------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • saveSymbol() was removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSymbolSelectorDialog QgsSymbolSelectorDialog +- expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsSymbolsListWidget QgsSymbolsListWidget -
                                                                                                                                                                                        -
                                                                                                                                                                                      • expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context()
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsTolerance {#qgis_api_break_3_0_QgsTolerance} +------------ -\subsection qgis_api_break_3_0_QgsTolerance QgsTolerance +- vertexSearchRadius(), defaultTolerance(), toleranceInMapUnits() do not have variant with QgsMapRenderer anymore. Use the variants with QgsMapSettings. +- The MapUnits UnitType was removed. Use LayerUnits or ProjectUnits instead. -
                                                                                                                                                                                        -
                                                                                                                                                                                      • vertexSearchRadius(), defaultTolerance(), toleranceInMapUnits() do not have variant with QgsMapRenderer anymore. Use the variants with QgsMapSettings.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The MapUnits UnitType was removed. Use LayerUnits or ProjectUnits instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsTreeWidgetItem QgsTreeWidgetItem +QgsTreeWidgetItem {#qgis_api_break_3_0_QgsTreeWidgetItem} +----------------- -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsTreeWidgetItem is no longer a QObject and does not emit the itemEdited signal. Instead, -use QgsTreeWidgetItemObject which is an upgraded version of the original QgsTreeWidgetItem
                                                                                                                                                                                      • -
                                                                                                                                                                                      -\subsection qgis_api_break_3_0_QgsUnitTypes QgsUnitTypes +- QgsTreeWidgetItem is no longer a QObject and does not emit the itemEdited signal. Instead, +use QgsTreeWidgetItemObject which is an upgraded version of the original QgsTreeWidgetItem -
                                                                                                                                                                                        -
                                                                                                                                                                                      • All distance enumeration values were renamed to have a "Distance" prefix, including + +QgsUnitTypes {#qgis_api_break_3_0_QgsUnitTypes} +------------ + + +- All distance enumeration values were renamed to have a "Distance" prefix, including Meters (to DistanceMeters), Kilometers (to DistanceKilometers), Feet (to DistanceFeet), NauticalMiles (to DistanceNauticalMiles), Yards (to DistanceYards), Miles (to DistanceMiles), -Degrees (to DistanceDegrees) and UnknownDistanceUnit to DistanceUnknownUnit
                                                                                                                                                                                      • -
                                                                                                                                                                                      • All area enumeration values were renamed to have a "Area" prefix, including +Degrees (to DistanceDegrees) and UnknownDistanceUnit to DistanceUnknownUnit +- All area enumeration values were renamed to have a "Area" prefix, including SquareMeters (to AreaSquareMeters), SquareKilometers (to AreaSquareKilometers), SquareFeet (to AreaSquareFeet), SquareYards (to AreaSquareYards), SquareMiles (to AreaSquareMiles), Hectares (to AreaHectares), Acres (to AreaAcres), SquareNauticalMiles (to AreaSquareNauticalMiles), SquareDegrees (to AreaSquareDegrees) -and UnknownAreaUnit to AreaUnknownUnit
                                                                                                                                                                                      • -
                                                                                                                                                                                      • All angle enumeration values were renamed to have a "Angle" prefix, including +and UnknownAreaUnit to AreaUnknownUnit +- All angle enumeration values were renamed to have a "Angle" prefix, including Radians (to AngleRadians), Gon (to AngleGon), MinutesOfArc (to AngleMinutesOfArc), -SecondsOfArc (to AngleSecondsOfArc), Turn (to AngleTurn) and UnknownAngleUnit to AngleUnknownUnit
                                                                                                                                                                                      • -
                                                                                                                                                                                      +SecondsOfArc (to AngleSecondsOfArc), Turn (to AngleTurn) and UnknownAngleUnit to AngleUnknownUnit + + +QgsVector {#qgis_api_break_3_0_QgsVector} +--------- + + +- normal() was removed. Use normalized() instead. -\subsection qgis_api_break_3_0_QgsVector QgsVector -
                                                                                                                                                                                        -
                                                                                                                                                                                      • normal() was removed. Use normalized() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsVectorDataProvider {#qgis_api_break_3_0_QgsVectorDataProvider} +--------------------- -\subsection qgis_api_break_3_0_QgsVectorDataProvider QgsVectorDataProvider -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsVectorDataProvider::fields() now returns a copy, rather than a const reference. Since QgsFields +- QgsVectorDataProvider::fields() now returns a copy, rather than a const reference. Since QgsFields objects are implicitly shared, returning a copy helps simplify and make code more robust. This change -only affects third party c++ providers, and does not affect PyQGIS scripts.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The SaveAsShapefile, SelectGeometryAtId, RandomSelectGeometryAtId and SequentialSelectGeometryAtId -capabilities have been removed, as they were unused and had no effect.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • capabilities() now returns a typesafe QgsVectorDataProvider::Capabilities object, not an integer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • convertToProviderType() now takes a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • geometryType() has been renamed to wkbType() to be in line with QgsVectorLayer
                                                                                                                                                                                      • -
                                                                                                                                                                                      - - -\subsection qgis_api_break_3_0_QgsVectorLayer QgsVectorLayer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • excludeAttributesWMS() and setExcludeAttributesWMS() have been renamed to excludeAttributesWms() and -setExcludeAttributesWms()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • excludeAttributesWFS() and setExcludeAttributesWFS() have been renamed to excludeAttributesWfs() and -setExcludeAttributesWfs()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The displayField property has been separated from the mapTip. For a plain text short title use the -displayExpression instead. For the map tip use mapTipTemplate() instead.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • changeGeometry() now accepts a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The geometryChanged() signal now uses a const QgsGeometry reference.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The deprecated removePolygonIntersections has been removed.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • addTopologicalPoints() now takes a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • commitErrors() now returns an object, rather than a reference. This has no effect on PyQGIS code.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • subsetString() was made const. This has no effect on PyQGIS code, but c++ code implementing derived layer classes will need to update the signature of this method to match.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • label(), enableLabels(), hasLabelsEnabled(), drawLabels() have been removed. Replaced by labeling based on PAL library, see QgsLabelingEngineV2.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • Signal layerDeleted() has been removed. Replaced by Qt signal destroyed().
                                                                                                                                                                                      • -
                                                                                                                                                                                      • Deprecated editor widget methods and enums and structs: struct RangeData, enum FeatureFormSuppress, enum EditType, addAttributeEditorWidget(), editorWidgetV2(), editorWidgetConfig(), attributeEditorElements(), editType(), setEditType(), editorLayout(), setEditorLayout, setEditorWidgetV2Config(), setCheckedState(), editForm(), setEditForm(), featureFormSuppress(), setFeatureFormSuppress(), editFormInit(), setEditFormInit(), valueMap(), range(), dateFormat(), fieldEditable(), labelOnTop(), setFieldEditable() and setLabelOnTop(). Use editFormConfig()
                                                                                                                                                                                      • -
                                                                                                                                                                                      • select() replaced by selectByRect() -
                                                                                                                                                                                      • setSelectedFeatures() replaced by selectByIds() -
                                                                                                                                                                                      • applyNamedStyle() replaced by applyNamedStyle() -
                                                                                                                                                                                      • isReadOnly() use readOnly() -
                                                                                                                                                                                      • Signal changeAttributeValue() -
                                                                                                                                                                                      • Deleted GroupData (Use QgsEditFormConfig::GroupData) -
                                                                                                                                                                                      • Deleted TabData (Use QgsEditFormConfig::TabData) -
                                                                                                                                                                                      • Deleted EditorLayout (Use QgsEditFormConfig::EditorLayout) -
                                                                                                                                                                                      • Deleted ValueRelationData (Use QgsEditFormConfig::editorWidgetConfig) -
                                                                                                                                                                                      • Deleted attributeEditorElementFromDomElement -
                                                                                                                                                                                      • editFormConfig() returns a copy instead of direct access (Use setEditFormConfig to update) -
                                                                                                                                                                                      • Removed valueRelation(), replaced with QgsEditFormConfig::editorWidgetConfig -
                                                                                                                                                                                      • Removed fieldNameIndex(), use fields().lookupField() or fields().indexFromName() instead -
                                                                                                                                                                                      • Renamed addAttributeAlias() to setFieldAlias() -
                                                                                                                                                                                      • Renamed remAttributeAlias() to removeFieldAlias() -
                                                                                                                                                                                      • saveStyleToDatabase(): msgError argument is correctly declared as output argument -
                                                                                                                                                                                      • getStyleFromDatabase(): msgError argument is correctly declared as output argument -
                                                                                                                                                                                      • loadNamedStyle(): theResultFlag argument is correctly declared as output argument -
                                                                                                                                                                                      - -\subsection qgis_api_break_3_0_QgsVectorLayerEditBuffer QgsVectorLayerEditBuffer - -
                                                                                                                                                                                        -
                                                                                                                                                                                      • changeGeometry() now accepts a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The geometryChanged() signal now uses a const QgsGeometry reference.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The addedFeatures(), changedAttributeValues(), deletedAttributeIds(), addedAttributes(), changedGeometries() +only affects third party c++ providers, and does not affect PyQGIS scripts. +- The SaveAsShapefile, SelectGeometryAtId, RandomSelectGeometryAtId and SequentialSelectGeometryAtId +capabilities have been removed, as they were unused and had no effect. +- capabilities() now returns a typesafe QgsVectorDataProvider::Capabilities object, not an integer. +- convertToProviderType() now takes a geometry reference, not a pointer. +- geometryType() has been renamed to wkbType() to be in line with QgsVectorLayer + + + +QgsVectorLayer {#qgis_api_break_3_0_QgsVectorLayer} +-------------- + + +- excludeAttributesWMS() and setExcludeAttributesWMS() have been renamed to excludeAttributesWms() and +setExcludeAttributesWms() +- excludeAttributesWFS() and setExcludeAttributesWFS() have been renamed to excludeAttributesWfs() and +setExcludeAttributesWfs() +- The displayField property has been separated from the mapTip. For a plain text short title use the +displayExpression instead. For the map tip use mapTipTemplate() instead. +- changeGeometry() now accepts a geometry reference, not a pointer. +- The geometryChanged() signal now uses a const QgsGeometry reference. +- The deprecated removePolygonIntersections has been removed. +- addTopologicalPoints() now takes a geometry reference, not a pointer. +- commitErrors() now returns an object, rather than a reference. This has no effect on PyQGIS code. +- subsetString() was made const. This has no effect on PyQGIS code, but c++ code implementing derived layer classes will need to update the signature of this method to match. +- label(), enableLabels(), hasLabelsEnabled(), drawLabels() have been removed. Replaced by labeling based on PAL library, see QgsLabelingEngineV2. +- Signal layerDeleted() has been removed. Replaced by Qt signal destroyed(). +- Deprecated editor widget methods and enums and structs: struct RangeData, enum FeatureFormSuppress, enum EditType, addAttributeEditorWidget(), editorWidgetV2(), editorWidgetConfig(), attributeEditorElements(), editType(), setEditType(), editorLayout(), setEditorLayout, setEditorWidgetV2Config(), setCheckedState(), editForm(), setEditForm(), featureFormSuppress(), setFeatureFormSuppress(), editFormInit(), setEditFormInit(), valueMap(), range(), dateFormat(), fieldEditable(), labelOnTop(), setFieldEditable() and setLabelOnTop(). Use editFormConfig() +- select() replaced by selectByRect() +- setSelectedFeatures() replaced by selectByIds() +- applyNamedStyle() replaced by applyNamedStyle() +- isReadOnly() use readOnly() +- Signal changeAttributeValue() +- Deleted GroupData (Use QgsEditFormConfig::GroupData) +- Deleted TabData (Use QgsEditFormConfig::TabData) +- Deleted EditorLayout (Use QgsEditFormConfig::EditorLayout) +- Deleted ValueRelationData (Use QgsEditFormConfig::editorWidgetConfig) +- Deleted attributeEditorElementFromDomElement +- editFormConfig() returns a copy instead of direct access (Use setEditFormConfig to update) +- Removed valueRelation(), replaced with QgsEditFormConfig::editorWidgetConfig +- Removed fieldNameIndex(), use fields().lookupField() or fields().indexFromName() instead +- Renamed addAttributeAlias() to setFieldAlias() +- Renamed remAttributeAlias() to removeFieldAlias() +- saveStyleToDatabase(): msgError argument is correctly declared as output argument +- getStyleFromDatabase(): msgError argument is correctly declared as output argument +- loadNamedStyle(): theResultFlag argument is correctly declared as output argument + + +QgsVectorLayerEditBuffer {#qgis_api_break_3_0_QgsVectorLayerEditBuffer} +------------------------ + + +- changeGeometry() now accepts a geometry reference, not a pointer. +- The geometryChanged() signal now uses a const QgsGeometry reference. +- The addedFeatures(), changedAttributeValues(), deletedAttributeIds(), addedAttributes(), changedGeometries() and deletedFeatureIds() functions now return values, not references. This has no effect on PyQGIS code, but c++ -plugins calling these methods will need to be updated.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +plugins calling these methods will need to be updated. -\subsection qgis_api_break_3_0_QgsVectorLayerEditUtils QgsVectorLayerEditUtils -
                                                                                                                                                                                        -
                                                                                                                                                                                      • addTopologicalPoints() now accepts a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsVectorLayerEditUtils {#qgis_api_break_3_0_QgsVectorLayerEditUtils} +----------------------- -\subsection qgis_api_break_3_0_QgsVectorLayerImport QgsVectorLayerImport -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsVectorLayerImport now takes references instead of pointers to QgsCoordinateReferenceSystem objects. Since +- addTopologicalPoints() now accepts a geometry reference, not a pointer. + + +QgsVectorLayerImport {#qgis_api_break_3_0_QgsVectorLayerImport} +-------------------- + + +- QgsVectorLayerImport now takes references instead of pointers to QgsCoordinateReferenceSystem objects. Since QgsCoordinateReferenceSystem is now implicitly shared, using references to QgsCoordinateReferenceSystem rather than pointers makes for more robust, safer code. Use an invalid (default constructed) QgsCoordinateReferenceSystem -in code which previously passed a null pointer to QgsVectorLayerImport.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +in code which previously passed a null pointer to QgsVectorLayerImport. + + +QgsVectorLayerUndoCommand {#qgis_api_break_3_0_QgsVectorLayerUndoCommand} +------------------------- -\subsection qgis_api_break_3_0_QgsVectorLayerUndoCommand QgsVectorLayerUndoCommand -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsVectorLayerUndoCommandChangeGeometry constructor now accepts a geometry reference, not a pointer.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- QgsVectorLayerUndoCommandChangeGeometry constructor now accepts a geometry reference, not a pointer. -\subsection qgis_api_break_3_0_QgsVisibilityPresetCollection QgsVisibilityPresetCollection -
                                                                                                                                                                                        -
                                                                                                                                                                                      • Has been renamed to QgsMapThemeCollection
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The nested class PresetRecord has been renamed to MapThemeRecord
                                                                                                                                                                                      • -
                                                                                                                                                                                      • Various member functions have been renamed from *preset* to *mapTheme*
                                                                                                                                                                                      • -
                                                                                                                                                                                      +QgsVisibilityPresetCollection {#qgis_api_break_3_0_QgsVisibilityPresetCollection} +----------------------------- -\subsection qgis_api_break_3_0_QgsVectorFileWriter QgsVectorFileWriter -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsVectorFileWriter now takes references instead of pointers to QgsCoordinateReferenceSystem objects. Since +- Has been renamed to QgsMapThemeCollection +- The nested class PresetRecord has been renamed to MapThemeRecord +- Various member functions have been renamed from *preset* to *mapTheme* + + +QgsVectorFileWriter {#qgis_api_break_3_0_QgsVectorFileWriter} +------------------- + + +- QgsVectorFileWriter now takes references instead of pointers to QgsCoordinateReferenceSystem objects. Since QgsCoordinateReferenceSystem is now implicitly shared, using references to QgsCoordinateReferenceSystem rather than pointers makes for more robust, safer code. Use an invalid (default constructed) QgsCoordinateReferenceSystem -in code which previously passed a null pointer to QgsVectorFileWriter.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • writeAsVectorFormat() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required.
                                                                                                                                                                                      • -
                                                                                                                                                                                      +in code which previously passed a null pointer to QgsVectorFileWriter. +- writeAsVectorFormat() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. + + +QgsWMSLegendNode {#qgis_api_break_3_0_QgsWMSLegendNode} +---------------- -\subsection qgis_api_break_3_0_QgsWMSLegendNode QgsWMSLegendNode -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsWMSLegendNode has been renamed to QgsWmsLegendNode
                                                                                                                                                                                      • -
                                                                                                                                                                                      +- QgsWMSLegendNode has been renamed to QgsWmsLegendNode -\subsection qgis_api_break_3_0_QgsRenderer QgsRenderer -
                                                                                                                                                                                        -
                                                                                                                                                                                      • New virtual method bool writeSld( QDomNode& node, QDomDocument& doc, QString& errorMessage, QgsStringMap props = QgsStringMap() ) accepts an +QgsRenderer {#qgis_api_break_3_0_QgsRenderer} +----------- + + +- New virtual method bool writeSld( QDomNode& node, QDomDocument& doc, QString& errorMessage, QgsStringMap props = QgsStringMap() ) accepts an optional property map passing down layer level properties to the SLD encoders. If scale based visibility is enabled, it will contain the -scaleMinDenom and scaleMaxDenom properties.
                                                                                                                                                                                      • -
                                                                                                                                                                                      • The RotationField capabitity was removed. This is now handled using data defined rotation at a symbol layer level
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setScaleMethodToSymbol was removed. This is now handled using data defined scaling at a symbol layer level
                                                                                                                                                                                      • -
                                                                                                                                                                                      • setScaleMethodToSymbol was removed. This is now handled using data defined scaling at a symbol layer level
                                                                                                                                                                                      • -
                                                                                                                                                                                      • usedAttributes is now a const method and returns QSet instead of QStringList
                                                                                                                                                                                      • -
                                                                                                                                                                                      +scaleMinDenom and scaleMaxDenom properties. +- The RotationField capabitity was removed. This is now handled using data defined rotation at a symbol layer level +- setScaleMethodToSymbol was removed. This is now handled using data defined scaling at a symbol layer level +- setScaleMethodToSymbol was removed. This is now handled using data defined scaling at a symbol layer level +- usedAttributes is now a const method and returns QSet instead of QStringList + -\section qgis_api_break_2_4 QGIS 2.4 +QGIS 2.4 {#qgis_api_break_2_4} +======== -\subsection qgis_api_break_mtr Multi-threaded Rendering +Multi-threaded Rendering {#qgis_api_break_mtr} +------------------------ -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsMapCanvas::refresh() only schedules a map refresh (in near feature) and returns immediately - before it would do the drawing immediately +- QgsMapCanvas::refresh() only schedules a map refresh (in near feature) and returns immediately - before it would do the drawing immediately and return when the map is redrawn. A call to refresh() will have no effect if there is already a scheduled pending refresh. When map canvas does actual rendering, it will first emit renderStarting() signal, once done it will emit mapCanvasRefreshed(). The client code doing refresh() in order to later save map image should be updated to use new QgsMapRendererJob API which is better suited for such task. -
                                                                                                                                                                                      • QgsPluginLayer::draw() is now run in a background thread. It is recommended to implement newly added QgsPluginLayer::createMapRenderer() +- QgsPluginLayer::draw() is now run in a background thread. It is recommended to implement newly added QgsPluginLayer::createMapRenderer() method instead of using QgsPluginLayer::draw(). -
                                                                                                                                                                                      -\section qgis_api_break_2_6 QGIS 2.6 -\subsection qgis_api_break_legend_refactoring Legend Refactoring +QGIS 2.6 {#qgis_api_break_2_6} +======== -
                                                                                                                                                                                        -
                                                                                                                                                                                      • QgsComposerLegend::model() - not being used anymore. The model was replaced by one based on QgsLayerTreeModel class +Legend Refactoring {#qgis_api_break_legend_refactoring} +------------------ + + +- QgsComposerLegend::model() - not being used anymore. The model was replaced by one based on QgsLayerTreeModel class and is available in QgsComposerLegend::modelV2() -
                                                                                                                                                                                      + */ From f80a33be659200c1497a55c455a5521dc1e8c529 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 25 Oct 2016 18:53:36 +0200 Subject: [PATCH 506/897] [FEATURE] Expose @parent variable in aggregate functions This makes it possible to access attributes and geometry from the parent feature when in the filter of the "aggregate" expression function. With this in place aggregates can be calculated per feature. E.g. max "measurement" for each point_station per polygon_research_area. Or a default attribute value when digitizing features: aggregate(layer:='countries', aggregate:='max', expression:=\"code\", filter:=intersects( $geometry, geometry(@parent) ) ) --- python/core/qgsexpression.sip | 22 ++++++- src/core/qgsexpression.cpp | 108 +++++++++++++++++++++++++++++++--- src/core/qgsexpression.h | 29 +++++++-- src/core/qgsfeature.cpp | 13 ++++ src/core/qgsfeature.h | 2 + 5 files changed, 159 insertions(+), 15 deletions(-) diff --git a/python/core/qgsexpression.sip b/python/core/qgsexpression.sip index 0df7bff7ec7d..717d7c6a390d 100644 --- a/python/core/qgsexpression.sip +++ b/python/core/qgsexpression.sip @@ -45,14 +45,20 @@ class QgsExpression /** * Get list of columns referenced by the expression. - * @note if the returned list contains the QgsFeatureRequest::AllAttributes constant then + * + * @note If the returned list contains the QgsFeatureRequest::AllAttributes constant then * all attributes from the layer are required for evaluation of the expression. * QgsFeatureRequest::setSubsetOfAttributes automatically handles this case. * - * TODO QGIS3: Return QSet + * @see referencedAttributeIndexes() */ QSet referencedColumns() const; + /** + * Return a list of all variables which are used in this expression. + */ + QSet referencedVariables() const; + /** * Return a list of field name indexes obtained from the provided fields. * @@ -560,6 +566,11 @@ class QgsExpression */ virtual QSet referencedColumns() const = 0; + /** + * Return a list of all variables which are used in this expression. + */ + virtual QSet referencedVariables() const = 0; + /** * Abstract virtual method which returns if the geometry is required to evaluate * this expression. @@ -638,6 +649,7 @@ class QgsExpression virtual QString dump() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; }; @@ -658,6 +670,7 @@ class QgsExpression virtual QString dump() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; @@ -692,6 +705,7 @@ class QgsExpression virtual QString dump() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; }; @@ -712,6 +726,7 @@ class QgsExpression virtual QString dump() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; @@ -734,6 +749,7 @@ class QgsExpression virtual QgsExpression::Node* clone() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; }; @@ -751,6 +767,7 @@ class QgsExpression virtual QString dump() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; @@ -783,6 +800,7 @@ class QgsExpression virtual QString dump() const; virtual QSet referencedColumns() const; + virtual QSet referencedVariables() const; virtual bool needsGeometry() const; virtual QgsExpression::Node* clone() const; }; diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 1cb659779244..42a7f51d1a07 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -622,7 +622,7 @@ static QVariant fcnMin( const QVariantList& values, const QgsExpressionContext*, return QVariant( minVal ); } -static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionContext* context, QgsExpression *parent ) +static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ) { //lazy eval, so we need to evaluate nodes now @@ -677,15 +677,28 @@ static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionCon parameters.delimiter = value.toString(); } - QString cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4" ).arg( vl->id(), QString::number( static_cast< int >( aggregate ) ), subExpression, parameters.filter ); - if ( context && context->hasCachedValue( cacheKey ) ) - return context->cachedValue( cacheKey ); - QVariant result; if ( context ) { + QString cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter ); + + QgsExpression subExp( subExpression ); + if ( subExp.referencedVariables().contains( "parent" ) || subExp.referencedVariables().contains( QString() ) ) + { + cacheKey += ':' + qHash( context->feature() ); + } + + if ( context && context->hasCachedValue( cacheKey ) ) + return context->cachedValue( cacheKey ); + QgsExpressionContext subContext( *context ); + QgsExpressionContextScope* subScope = new QgsExpressionContextScope(); + subScope->setVariable( "parent", context->feature() ); + subContext.appendScope( subScope ); result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok ); + + if ( ok ) + context->setCachedValue( cacheKey, result ); } else { @@ -697,9 +710,6 @@ static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionCon return QVariant(); } - // cache value - if ( context ) - context->setCachedValue( cacheKey, result ); return result; } @@ -3991,6 +4001,14 @@ QSet QgsExpression::referencedColumns() const return d->mRootNode->referencedColumns(); } +QSet QgsExpression::referencedVariables() const +{ + if ( !d->mRootNode ) + return QSet(); + + return d->mRootNode->referencedVariables(); +} + bool QgsExpression::NodeInOperator::needsGeometry() const { bool needs = false; @@ -4303,6 +4321,16 @@ QString QgsExpression::NodeUnaryOperator::dump() const return QStringLiteral( "%1 %2" ).arg( UnaryOperatorText[mOp], mOperand->dump() ); } +QSet QgsExpression::NodeUnaryOperator::referencedColumns() const +{ + return mOperand->referencedColumns(); +} + +QSet QgsExpression::NodeUnaryOperator::referencedVariables() const +{ + return mOperand->referencedVariables(); +} + QgsExpression::Node*QgsExpression::NodeUnaryOperator::clone() const { return new NodeUnaryOperator( mOp, mOperand->clone() ); @@ -4790,6 +4818,11 @@ QSet QgsExpression::NodeBinaryOperator::referencedColumns() const return mOpLeft->referencedColumns() + mOpRight->referencedColumns(); } +QSet QgsExpression::NodeBinaryOperator::referencedVariables() const +{ + return mOpLeft->referencedVariables() + mOpRight->referencedVariables(); +} + bool QgsExpression::NodeBinaryOperator::needsGeometry() const { return mOpLeft->needsGeometry() || mOpRight->needsGeometry(); @@ -4993,6 +5026,23 @@ QSet QgsExpression::NodeFunction::referencedColumns() const return functionColumns; } +QSet QgsExpression::NodeFunction::referencedVariables() const +{ + Function* fd = Functions()[mFnIndex]; + if ( fd->name() == "var" ) + { + if ( !mArgs->list().isEmpty() ) + { + QgsExpression::NodeLiteral* var = dynamic_cast( mArgs->list().first() ); + if ( var ) + return QSet() << var->value().toString(); + } + return QSet() << QString(); + } + else + return QSet(); +} + bool QgsExpression::NodeFunction::needsGeometry() const { bool needs = Functions()[mFnIndex]->usesGeometry(); @@ -5119,6 +5169,16 @@ QString QgsExpression::NodeLiteral::dump() const } } +QSet QgsExpression::NodeLiteral::referencedColumns() const +{ + return QSet(); +} + +QSet QgsExpression::NodeLiteral::referencedVariables() const +{ + return QSet(); +} + QgsExpression::Node*QgsExpression::NodeLiteral::clone() const { return new NodeLiteral( mValue ); @@ -5177,6 +5237,16 @@ QString QgsExpression::NodeColumnRef::dump() const return QRegExp( "^[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*$" ).exactMatch( mName ) ? mName : quotedColumnRef( mName ); } +QSet QgsExpression::NodeColumnRef::referencedColumns() const +{ + return QSet() << mName; +} + +QSet QgsExpression::NodeColumnRef::referencedVariables() const +{ + return QSet(); +} + QgsExpression::Node*QgsExpression::NodeColumnRef::clone() const { return new NodeColumnRef( mName ); @@ -5253,6 +5323,20 @@ QSet QgsExpression::NodeCondition::referencedColumns() const return lst; } +QSet QgsExpression::NodeCondition::referencedVariables() const +{ + QSet lst; + Q_FOREACH ( WhenThen* cond, mConditions ) + { + lst += cond->mWhenExp->referencedVariables() + cond->mThenExp->referencedVariables(); + } + + if ( mElseExp ) + lst += mElseExp->referencedVariables(); + + return lst; +} + bool QgsExpression::NodeCondition::needsGeometry() const { Q_FOREACH ( WhenThen* cond, mConditions ) @@ -5619,6 +5703,14 @@ QSet QgsExpression::NodeInOperator::referencedColumns() const return lst; } +QSet QgsExpression::NodeInOperator::referencedVariables() const +{ + QSet lst( mNode->referencedVariables() ); + Q_FOREACH ( const Node* n, mList->list() ) + lst.unite( n->referencedVariables() ); + return lst; +} + bool QgsExpression::Function::operator==( const QgsExpression::Function& other ) const { if ( QString::compare( mName, other.mName, Qt::CaseInsensitive ) == 0 ) diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index 97b1c8b3e206..bb70cd7d5cad 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -180,11 +180,18 @@ class CORE_EXPORT QgsExpression * QgsFeatureRequest::setSubsetOfAttributes automatically handles this case. * * @see referencedAttributeIndexes() - * - * TODO QGIS3: Return QSet */ QSet referencedColumns() const; + /** + * Return a list of all variables which are used in this expression. + * If the list contains a NULL QString, there is a variable name used + * which is determined at runtime. + * + * @note Added in QGIS 3.0 + */ + QSet referencedVariables() const; + /** * Return a list of field name indexes obtained from the provided fields. * @@ -857,6 +864,11 @@ class CORE_EXPORT QgsExpression */ virtual QSet referencedColumns() const = 0; + /** + * Return a list of all variables which are used in this expression. + */ + virtual QSet referencedVariables() const = 0; + /** * Abstract virtual method which returns if the geometry is required to evaluate * this expression. @@ -953,7 +965,8 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QSet referencedColumns() const override { return mOperand->referencedColumns(); } + virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override { return mOperand->needsGeometry(); } virtual Node* clone() const override; @@ -984,6 +997,7 @@ class CORE_EXPORT QgsExpression virtual QString dump() const override; virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; @@ -1028,6 +1042,7 @@ class CORE_EXPORT QgsExpression virtual QString dump() const override; virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; @@ -1055,6 +1070,7 @@ class CORE_EXPORT QgsExpression virtual QString dump() const override; virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; @@ -1084,7 +1100,8 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QSet referencedColumns() const override { return QSet(); } + virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override { return false; } virtual Node* clone() const override; @@ -1110,7 +1127,8 @@ class CORE_EXPORT QgsExpression virtual QVariant eval( QgsExpression* parent, const QgsExpressionContext* context ) override; virtual QString dump() const override; - virtual QSet referencedColumns() const override { return QSet() << mName; } + virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override { return false; } virtual Node* clone() const override; @@ -1162,6 +1180,7 @@ class CORE_EXPORT QgsExpression virtual QString dump() const override; virtual QSet referencedColumns() const override; + virtual QSet referencedVariables() const override; virtual bool needsGeometry() const override; virtual Node* clone() const override; diff --git a/src/core/qgsfeature.cpp b/src/core/qgsfeature.cpp index 75d27482ba85..7625a094e7c6 100644 --- a/src/core/qgsfeature.cpp +++ b/src/core/qgsfeature.cpp @@ -313,3 +313,16 @@ QDataStream& operator>>( QDataStream& in, QgsFeature& feature ) feature.setValid( valid ); return in; } + +uint qHash( const QgsFeature& key, uint seed ) +{ + uint hash = seed; + Q_FOREACH ( const QVariant& attr, key.attributes() ) + { + hash ^= qHash( attr.toString() ); + } + + hash ^= qHash( key.geometry().exportToWkt() ); + + return hash; +} diff --git a/src/core/qgsfeature.h b/src/core/qgsfeature.h index 39305aabce15..d39a43f36e79 100644 --- a/src/core/qgsfeature.h +++ b/src/core/qgsfeature.h @@ -349,6 +349,8 @@ typedef QMap QgsFieldNameMap; typedef QList QgsFeatureList; +uint qHash( const QgsFeature& key, uint seed = 0 ); + Q_DECLARE_METATYPE( QgsFeature ) Q_DECLARE_METATYPE( QgsFeatureList ) From c2b84241ec474a7405f293e47d4814d9f21954be Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 25 Oct 2016 23:02:33 +0200 Subject: [PATCH 507/897] Always cache values and add fid to feature hash --- src/core/qgsexpression.cpp | 3 +-- src/core/qgsfeature.cpp | 1 + 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 42a7f51d1a07..9b2da9e53059 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -697,8 +697,7 @@ static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionCon subContext.appendScope( subScope ); result = vl->aggregate( aggregate, subExpression, parameters, &subContext, &ok ); - if ( ok ) - context->setCachedValue( cacheKey, result ); + context->setCachedValue( cacheKey, result ); } else { diff --git a/src/core/qgsfeature.cpp b/src/core/qgsfeature.cpp index 7625a094e7c6..6aa6f4da59e5 100644 --- a/src/core/qgsfeature.cpp +++ b/src/core/qgsfeature.cpp @@ -323,6 +323,7 @@ uint qHash( const QgsFeature& key, uint seed ) } hash ^= qHash( key.geometry().exportToWkt() ); + hash ^= qHash( key.id() ); return hash; } From c79cf9ae15ab2578859e34ca209261ed8c57ef87 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 25 Oct 2016 23:08:05 +0200 Subject: [PATCH 508/897] Fetch attributes and geometry for aggregate function --- src/core/qgsexpression.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 9b2da9e53059..13a548e39839 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3601,7 +3601,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "coalesce" ), -1, fcnCoalesce, QStringLiteral( "Conditionals" ), QString(), false, QSet(), false, QStringList(), true ) << new StaticFunction( QStringLiteral( "if" ), 3, fcnIf, QStringLiteral( "Conditionals" ), QString(), False, QSet(), true ) << new StaticFunction( QStringLiteral( "aggregate" ), ParameterList() << Parameter( QStringLiteral( "layer" ) ) << Parameter( QStringLiteral( "aggregate" ) ) << Parameter( QStringLiteral( "expression" ) ) - << Parameter( QStringLiteral( "filter" ), true ) << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregate, QStringLiteral( "Aggregates" ), QString(), false, QSet(), true ) + << Parameter( QStringLiteral( "filter" ), true ) << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregate, QStringLiteral( "Aggregates" ), QString(), true, QSet() << QgsFeatureRequest::AllAttributes, true ) << new StaticFunction( QStringLiteral( "relation_aggregate" ), ParameterList() << Parameter( QStringLiteral( "relation" ) ) << Parameter( QStringLiteral( "aggregate" ) ) << Parameter( QStringLiteral( "expression" ) ) << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregateRelation, QStringLiteral( "Aggregates" ), QString(), False, QSet() << QgsFeatureRequest::AllAttributes, true ) From f292fdd625cffcb004a023b21b47ade36e9d6173 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 25 Oct 2016 23:32:58 +0200 Subject: [PATCH 509/897] Add test for @parent aggregate filter --- tests/src/core/testqgsexpression.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index d51f80cdf532..134938bc588b 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1270,6 +1270,8 @@ class TestQgsExpression: public QObject QTest::newRow( "filter context" ) << "aggregate('test','sum',\"col1\", \"col1\" <= @test_var)" << false << QVariant( 13 ); QTest::newRow( "filter named" ) << "aggregate(layer:='test',aggregate:='sum',expression:=\"col1\", filter:=\"col1\" <= 10)" << false << QVariant( 13 ); QTest::newRow( "filter no matching" ) << "aggregate('test','sum',\"col1\", \"col1\" <= -10)" << false << QVariant( 0 ); + + QTest::newRow( "filter by @parent attribute" ) << "aggregate(layer:='child_layer', aggregate:='min', expression:=\"col3\", filter:=\"parent\"=attribute(@parent,'col1'))" << false << QVariant( 1 ); } void aggregate() @@ -1278,6 +1280,9 @@ class TestQgsExpression: public QObject QgsExpressionContextScope* scope = new QgsExpressionContextScope(); scope->setVariable( QStringLiteral( "test_var" ), 10 ); context << scope; + QgsFeature f; + mAggregatesLayer->getFeatures( "col1 = 4 " ).nextFeature( f ); + context.setFeature( f ); QFETCH( QString, string ); QFETCH( bool, evalError ); From adb184e43594b551dbd182057a1659c03510e4c7 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 25 Oct 2016 23:33:14 +0200 Subject: [PATCH 510/897] Add documentation for @parent aggregate filter --- resources/function_help/json/aggregate | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/resources/function_help/json/aggregate b/resources/function_help/json/aggregate index e6f9bcfad700..a8520437f748 100644 --- a/resources/function_help/json/aggregate +++ b/resources/function_help/json/aggregate @@ -6,13 +6,14 @@ {"arg":"layer", "description":"a string, representing either a layer name or layer ID"}, {"arg":"aggregate", "description":"a string corresponding to the aggregate to calculate. Valid options are:
                                                                                                                                                                                      • count
                                                                                                                                                                                      • count_distinct
                                                                                                                                                                                      • count_missing
                                                                                                                                                                                      • min
                                                                                                                                                                                      • max
                                                                                                                                                                                      • sum
                                                                                                                                                                                      • mean
                                                                                                                                                                                      • median
                                                                                                                                                                                      • stdev
                                                                                                                                                                                      • stdevsample
                                                                                                                                                                                      • range
                                                                                                                                                                                      • minority
                                                                                                                                                                                      • majority
                                                                                                                                                                                      • q1: first quartile
                                                                                                                                                                                      • q3: third quartile
                                                                                                                                                                                      • iqr: inter quartile range
                                                                                                                                                                                      • min_length: minimum string length
                                                                                                                                                                                      • max_length: maximum string length
                                                                                                                                                                                      • concatenate: join strings with a concatenator
                                                                                                                                                                                      • collect: create an aggregated multipart geometry
                                                                                                                                                                                      "}, {"arg":"calculation", "description":"sub expression or field name to aggregate"}, - {"arg":"filter", "optional":true, "description":"optional filter expression to limit the features used for calculating the aggregate"}, + {"arg":"filter", "optional":true, "description":"optional filter expression to limit the features used for calculating the aggregate. Fields and geometry are from the features on the joined layer. The source feature can be accessed with the variable @parent."}, {"arg":"concatenator", "optional":true, "description":"optional string to use to join values for 'concatenate' aggregate"} ], "examples": [ { "expression":"aggregate(layer:='rail_stations',aggregate:='sum',expression:=\"passengers\")", "returns":"sum of all values from the passengers field in the rail_stations layer"}, { "expression":"aggregate('rail_stations','sum', \"passengers\"/7)", "returns":"calculates a daily average of \"passengers\" by dividing the \"passengers\" field by 7 before summing the values"}, { "expression":"aggregate(layer:='rail_stations',calculation:='sum',expression:=\"passengers\",filter:=\"class\">3)", "returns":"sums up all values from the \"passengers\" field from features where the \"class\" attribute is greater than 3 only"}, - { "expression":"aggregate(layer:='rail_stations',calculation:='concatenate', expression:=\"name\", concatenator:=',')", "returns":"comma separated list of the name field for all features in the rail_stations layer"} + { "expression":"aggregate(layer:='rail_stations',calculation:='concatenate', expression:=\"name\", concatenator:=',')", "returns":"comma separated list of the name field for all features in the rail_stations layer"}, + { "expression":"aggregate(layer:='countries', aggregate:='max', expression:=\"code\", filter:=intersects( $geometry, geometry(@parent) ) )", "returns":"The country code of an intersecting country on the layer 'countries'"} ] } From 0b3646b2525fd7e6aeaa7ecf71b12d143cb7cb30 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 27 Oct 2016 11:33:42 +0200 Subject: [PATCH 511/897] Expression functions can dynamically report geometry and columns --- doc/api_break.dox | 12 ++- python/core/__init__.py | 12 ++- python/core/qgsexpression.sip | 34 ++++--- src/core/qgsexpression.cpp | 97 +++++++++++++++++-- src/core/qgsexpression.h | 87 ++++++++++++----- src/core/qgsexpressioncontext.cpp | 12 +++ src/core/qgsexpressioncontext.h | 11 ++- .../virtual/qgsvirtuallayersqlitemodule.cpp | 2 +- tests/src/core/testqgsexpression.cpp | 2 + 9 files changed, 219 insertions(+), 50 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index e146da2f70bf..a7888286da60 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -765,9 +765,6 @@ version instead. removed. Use QgsExpressionContext variables instead. - The replaceExpressionText version which accepts a QgsFeature argument has been removed. Use the QgsExpressionContext version instead. -- QgsExpression::Function::func has been modified to use a QgsExpressionContext argument rather than a QgsFeature. -- QgsExpression::Function::usesgeometry() has been renamed to usesGeometry() -- QgsExpression::Function::helptext() has been renamed to helpText() - The QgsExpression::Node::eval and prepare versions which take a QgsFeature has been removed, use the QgsExpressionContext versions instead. - QgsExpression::Interval has been removed. Use QgsInterval instead. - replaceExpressionText() no longer accepts a substitution map parameter. Use expression context variables instead. @@ -776,7 +773,14 @@ version instead. - acceptVisitor() has been removed - QgsExpression::referencedColumns() returns QSet instead of QStringList - QgsExpression::Node::referencedColumns() returns QSet instead of QStringList -- QgsExpression::Function::referencedColumns() returns QSet instead of QStringList + +QgsExpression::Function {#qgis_api_break_3_0_QgsExpression_Function} +----------------------- + +- `QgsExpression::Function::func` has been modified to use a `QgsExpressionContext` argument rather than a `QgsFeature`. +- `QgsExpression::Function::usesgeometry()` has been renamed to `QgsExpression::Function::usesGeometry( const NodeFunction* node )` +- `QStringList QgsExpression::Function::referencedColumns()` has been changed to `QSet QgsExpression::Function::referencedColumns( const NodeFunction* node )` +- `QgsExpression::Function::helptext()` has been renamed to `helpText()` QgsFeature {#qgis_api_break_3_0_QgsFeature} diff --git a/python/core/__init__.py b/python/core/__init__.py index 551636a43c4d..b6135fd36e85 100644 --- a/python/core/__init__.py +++ b/python/core/__init__.py @@ -69,10 +69,12 @@ def myfunc(values, *args): """ class QgsExpressionFunction(QgsExpression.Function): - def __init__(self, func, name, args, group, helptext='', usesgeometry=True, referencedColumns=QgsFeatureRequest.AllAttributes, expandargs=False): - QgsExpression.Function.__init__(self, name, args, group, helptext, usesgeometry, referencedColumns) + def __init__(self, func, name, args, group, helptext='', usesGeometry=True, referencedColumns=QgsFeatureRequest.AllAttributes, expandargs=False): + QgsExpression.Function.__init__(self, name, args, group, helptext) self.function = func self.expandargs = expandargs + self.uses_geometry = usesGeometry + self.referenced_columns = referencedColumns def func(self, values, context, parent): feature = None @@ -89,6 +91,12 @@ def func(self, values, context, parent): parent.setEvalErrorString(str(ex)) return None + def usesGeometry(self, node): + return self.uses_geometry + + def referencedColumns(self, node): + return self.referenced_columns + helptemplate = string.Template("""

                                                                                                                                                                                      $name function


                                                                                                                                                                                      $doc""") name = kwargs.get('name', function.__name__) helptext = function.__doc__ or '' diff --git a/python/core/qgsexpression.sip b/python/core/qgsexpression.sip index 717d7c6a390d..e69086ad51ef 100644 --- a/python/core/qgsexpression.sip +++ b/python/core/qgsexpression.sip @@ -306,8 +306,6 @@ class QgsExpression int params, const QString& group, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ); @@ -319,8 +317,6 @@ class QgsExpression int params, const QStringList& groups, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ); @@ -332,8 +328,6 @@ class QgsExpression const QgsExpression::ParameterList& params, const QString& group, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ); @@ -345,8 +339,6 @@ class QgsExpression const QgsExpression::ParameterList& params, const QStringList& groups, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ); @@ -366,8 +358,8 @@ class QgsExpression */ const QgsExpression::ParameterList& parameters() const; - /** Does this function use a geometry object. */ - bool usesGeometry() const; + //! Does this function use a geometry object. + virtual bool usesGeometry( const QgsExpression::NodeFunction* node ) const; /** Returns a list of possible aliases for the function. These include * other permissible names for the function, eg deprecated names. @@ -382,7 +374,15 @@ class QgsExpression */ bool lazyEval() const; - virtual QSet referencedColumns() const; + /** + * Returns a set of field names which are required for this function. + * May contain QgsFeatureRequest::AllAttributes to signal that all + * attributes are required. + * If in doubt this will return more fields than strictly required. + * + * @note Added in QGIS 3.0 + */ + virtual QSet referencedColumns( const QgsExpression::NodeFunction* node ) const; /** Returns whether the function is only available if provided by a QgsExpressionContext object. * @note added in QGIS 2.12 @@ -622,7 +622,17 @@ class QgsExpression //! @note added in QGIS 2.16 bool hasNamedNodes() const; - const QList& list(); + /** + * Get a list of all the nodes. + */ + QList list(); + + /** + * Get the node at position i in the list. + * + * @note Added in QGIS 3.0 + */ + QgsExpression::Node* at( int i ); //! Returns a list of names for nodes. Unnamed nodes will be indicated by an empty string in the list. //! @note added in QGIS 2.16 diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 13a548e39839..c45f6e68017a 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3600,8 +3600,56 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "to_interval" ), ParameterList() << Parameter( QStringLiteral( "value" ) ), fcnToInterval, QStringList() << QStringLiteral( "Conversions" ) << QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "tointerval" ) ) << new StaticFunction( QStringLiteral( "coalesce" ), -1, fcnCoalesce, QStringLiteral( "Conditionals" ), QString(), false, QSet(), false, QStringList(), true ) << new StaticFunction( QStringLiteral( "if" ), 3, fcnIf, QStringLiteral( "Conditionals" ), QString(), False, QSet(), true ) - << new StaticFunction( QStringLiteral( "aggregate" ), ParameterList() << Parameter( QStringLiteral( "layer" ) ) << Parameter( QStringLiteral( "aggregate" ) ) << Parameter( QStringLiteral( "expression" ) ) - << Parameter( QStringLiteral( "filter" ), true ) << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregate, QStringLiteral( "Aggregates" ), QString(), true, QSet() << QgsFeatureRequest::AllAttributes, true ) + + << new StaticFunction( QStringLiteral( "aggregate" ), + ParameterList() + << Parameter( QStringLiteral( "layer" ) ) + << Parameter( QStringLiteral( "aggregate" ) ) + << Parameter( QStringLiteral( "expression" ) ) + << Parameter( QStringLiteral( "filter" ), true ) + << Parameter( QStringLiteral( "concatenator" ), true ), + fcnAggregate, + QStringLiteral( "Aggregates" ), + QString(), + []( const QgsExpression::NodeFunction* node ) + { + // usesGeometry callback: return true if @parent variable is referenced + + if ( !node ) + return true; + + if ( !node->args() || node->args()->count() < 4 ) + return false; + else + { + QgsExpression::Node* filterNode = node->args()->at( 3 ); + QSet referencedVars = filterNode->referencedVariables(); + return referencedVars.contains( "parent" ) || referencedVars.contains( QString() ); + } + }, + []( const QgsExpression::NodeFunction* node ) + { + // referencedColumns callback: return AllAttributes if @parent variable is referenced + + if ( !node ) + return QSet() << QgsFeatureRequest::AllAttributes; + + if ( !node->args() || node->args()->count() < 4 ) + return QSet(); + else + { + QgsExpression::Node* filterNode = node->args()->at( 3 ); + QSet referencedVars = filterNode->referencedVariables(); + + if ( referencedVars.contains( "parent" ) || referencedVars.contains( QString() ) ) + return QSet() << QgsFeatureRequest::AllAttributes; + else + return QSet(); + } + }, + true + ) + << new StaticFunction( QStringLiteral( "relation_aggregate" ), ParameterList() << Parameter( QStringLiteral( "relation" ) ) << Parameter( QStringLiteral( "aggregate" ) ) << Parameter( QStringLiteral( "expression" ) ) << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregateRelation, QStringLiteral( "Aggregates" ), QString(), False, QSet() << QgsFeatureRequest::AllAttributes, true ) @@ -4330,14 +4378,14 @@ QSet QgsExpression::NodeUnaryOperator::referencedVariables() const return mOperand->referencedVariables(); } -QgsExpression::Node*QgsExpression::NodeUnaryOperator::clone() const +QgsExpression::Node* QgsExpression::NodeUnaryOperator::clone() const { return new NodeUnaryOperator( mOp, mOperand->clone() ); } // -QVariant QgsExpression::NodeBinaryOperator::eval( QgsExpression *parent, const QgsExpressionContext *context ) +QVariant QgsExpression::NodeBinaryOperator::eval( QgsExpression* parent, const QgsExpressionContext* context ) { QVariant vL = mOpLeft->eval( parent, context ); ENSURE_NO_EVAL_ERROR; @@ -5009,7 +5057,7 @@ QString QgsExpression::NodeFunction::dump() const QSet QgsExpression::NodeFunction::referencedColumns() const { Function* fd = Functions()[mFnIndex]; - QSet functionColumns = fd->referencedColumns(); + QSet functionColumns = fd->referencedColumns( this ); if ( !mArgs ) { @@ -5044,7 +5092,7 @@ QSet QgsExpression::NodeFunction::referencedVariables() const bool QgsExpression::NodeFunction::needsGeometry() const { - bool needs = Functions()[mFnIndex]->usesGeometry(); + bool needs = Functions()[mFnIndex]->usesGeometry( this ); if ( mArgs ) { Q_FOREACH ( Node* n, mArgs->list() ) @@ -5710,6 +5758,18 @@ QSet QgsExpression::NodeInOperator::referencedVariables() const return lst; } +bool QgsExpression::Function::usesGeometry( const QgsExpression::NodeFunction* node ) const +{ + Q_UNUSED( node ) + return true; +} + +QSet QgsExpression::Function::referencedColumns( const NodeFunction* node ) const +{ + Q_UNUSED( node ) + return QSet() << QgsFeatureRequest::AllAttributes; +} + bool QgsExpression::Function::operator==( const QgsExpression::Function& other ) const { if ( QString::compare( mName, other.mName, Qt::CaseInsensitive ) == 0 ) @@ -5717,3 +5777,28 @@ bool QgsExpression::Function::operator==( const QgsExpression::Function& other ) return false; } + +QgsExpression::StaticFunction::StaticFunction( const QString& fnname, const QgsExpression::ParameterList& params, QgsExpression::FcnEval fcn, const QString& group, const QString& helpText, std::function < bool ( const NodeFunction* node ) > usesGeometry, std::function < QSet( const NodeFunction* node ) > referencedColumns, bool lazyEval, const QStringList& aliases, bool handlesNull ) + : Function( fnname, params, group, helpText, lazyEval, handlesNull ) + , mFnc( fcn ) + , mAliases( aliases ) + , mUsesGeometryFunc( usesGeometry ) + , mReferencedColumnsFunc( referencedColumns ) +{ +} + +bool QgsExpression::StaticFunction::usesGeometry( const NodeFunction* node ) const +{ + if ( mUsesGeometryFunc ) + return mUsesGeometryFunc( node ); + else + return mUsesGeometry; +} + +QSet QgsExpression::StaticFunction::referencedColumns( const NodeFunction* node ) const +{ + if ( mReferencedColumnsFunc ) + return mReferencedColumnsFunc( node ); + else + return mReferencedColumns; +} diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index bb70cd7d5cad..eb2d8133f70c 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -23,6 +23,7 @@ #include #include #include +#include #include "qgis.h" #include "qgsunittypes.h" @@ -445,6 +446,8 @@ class CORE_EXPORT QgsExpression */ typedef QVariant( *FcnEval )( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ); + class NodeFunction; + /** \ingroup core * A abstract base class for defining QgsExpression functions. */ @@ -457,17 +460,13 @@ class CORE_EXPORT QgsExpression int params, const QString& group, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ) : mName( fnname ) , mParams( params ) - , mUsesGeometry( usesGeometry ) , mGroups( group.isEmpty() ? QStringList() : QStringList() << group ) , mHelpText( helpText ) - , mReferencedColumns( referencedColumns ) , mLazyEval( lazyEval ) , mHandlesNull( handlesNull ) , mIsContextual( isContextual ) @@ -481,17 +480,13 @@ class CORE_EXPORT QgsExpression int params, const QStringList& groups, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ) : mName( fnname ) , mParams( params ) - , mUsesGeometry( usesGeometry ) , mGroups( groups ) , mHelpText( helpText ) - , mReferencedColumns( referencedColumns ) , mLazyEval( lazyEval ) , mHandlesNull( handlesNull ) , mIsContextual( isContextual ) @@ -505,18 +500,14 @@ class CORE_EXPORT QgsExpression const ParameterList& params, const QString& group, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ) : mName( fnname ) , mParams( 0 ) , mParameterList( params ) - , mUsesGeometry( usesGeometry ) , mGroups( group.isEmpty() ? QStringList() : QStringList() << group ) , mHelpText( helpText ) - , mReferencedColumns( referencedColumns ) , mLazyEval( lazyEval ) , mHandlesNull( handlesNull ) , mIsContextual( isContextual ) @@ -529,18 +520,14 @@ class CORE_EXPORT QgsExpression const ParameterList& params, const QStringList& groups, const QString& helpText = QString(), - bool usesGeometry = false, - const QSet& referencedColumns = QSet(), bool lazyEval = false, bool handlesNull = false, bool isContextual = false ) : mName( fnname ) , mParams( 0 ) , mParameterList( params ) - , mUsesGeometry( usesGeometry ) , mGroups( groups ) , mHelpText( helpText ) - , mReferencedColumns( referencedColumns ) , mLazyEval( lazyEval ) , mHandlesNull( handlesNull ) , mIsContextual( isContextual ) @@ -575,7 +562,7 @@ class CORE_EXPORT QgsExpression const ParameterList& parameters() const { return mParameterList; } //! Does this function use a geometry object. - bool usesGeometry() const { return mUsesGeometry; } + virtual bool usesGeometry( const NodeFunction* node ) const; /** Returns a list of possible aliases for the function. These include * other permissible names for the function, eg deprecated names. @@ -589,7 +576,15 @@ class CORE_EXPORT QgsExpression * Functions are non lazy default and will be given the node return value when called **/ bool lazyEval() const { return mLazyEval; } - virtual QSet referencedColumns() const { return mReferencedColumns; } + /** + * Returns a set of field names which are required for this function. + * May contain QgsFeatureRequest::AllAttributes to signal that all + * attributes are required. + * If in doubt this will return more fields than strictly required. + * + * @note Added in QGIS 3.0 + */ + virtual QSet referencedColumns( const NodeFunction* node ) const; /** Returns whether the function is only available if provided by a QgsExpressionContext object. * @note added in QGIS 2.12 @@ -632,10 +627,8 @@ class CORE_EXPORT QgsExpression QString mName; int mParams; ParameterList mParameterList; - bool mUsesGeometry; QStringList mGroups; QString mHelpText; - QSet mReferencedColumns; bool mLazyEval; bool mHandlesNull; bool mIsContextual; //if true function is only available through an expression context @@ -661,9 +654,11 @@ class CORE_EXPORT QgsExpression bool lazyEval = false, const QStringList& aliases = QStringList(), bool handlesNull = false ) - : Function( fnname, params, group, helpText, usesGeometry, referencedColumns, lazyEval, handlesNull ) + : Function( fnname, params, group, helpText, lazyEval, handlesNull ) , mFnc( fcn ) , mAliases( aliases ) + , mUsesGeometry( usesGeometry ) + , mReferencedColumns( referencedColumns ) {} /** Static function for evaluation against a QgsExpressionContext, using a named list of parameter values. @@ -678,11 +673,35 @@ class CORE_EXPORT QgsExpression bool lazyEval = false, const QStringList& aliases = QStringList(), bool handlesNull = false ) - : Function( fnname, params, group, helpText, usesGeometry, referencedColumns, lazyEval, handlesNull ) + : Function( fnname, params, group, helpText, lazyEval, handlesNull ) , mFnc( fcn ) , mAliases( aliases ) + , mUsesGeometry( usesGeometry ) + , mReferencedColumns( referencedColumns ) {} + /** + * Static function for evaluation against a QgsExpressionContext, using a named list of parameter values. + * + * Lambda functions can be provided that will be called to determine if a geometry is used an which + * columns are referenced. + * This is only required if this cannot be determined by calling each parameter node's usesGeometry() or + * referencedColumns() method. For example, an aggregate expression requires the geometry and all columns + * if the parent variable is used. + * If a nullptr is passed as a node to these functions, they should stay on the safe side and return if they + * could potentially require a geometry or columns. + */ + StaticFunction( const QString& fnname, + const ParameterList& params, + FcnEval fcn, + const QString& group, + const QString& helpText, + std::function < bool ( const NodeFunction* node ) > usesGeometry, + std::function < QSet( const NodeFunction* node ) > referencedColumns, + bool lazyEval = false, + const QStringList& aliases = QStringList(), + bool handlesNull = false ); + /** Static function for evaluation against a QgsExpressionContext, using a named list of parameter values and list * of groups. */ @@ -696,9 +715,11 @@ class CORE_EXPORT QgsExpression bool lazyEval = false, const QStringList& aliases = QStringList(), bool handlesNull = false ) - : Function( fnname, params, groups, helpText, usesGeometry, referencedColumns, lazyEval, handlesNull ) + : Function( fnname, params, groups, helpText, lazyEval, handlesNull ) , mFnc( fcn ) , mAliases( aliases ) + , mUsesGeometry( usesGeometry ) + , mReferencedColumns( referencedColumns ) {} virtual ~StaticFunction() {} @@ -716,9 +737,17 @@ class CORE_EXPORT QgsExpression virtual QStringList aliases() const override { return mAliases; } + virtual bool usesGeometry( const QgsExpression::NodeFunction* node ) const override; + + virtual QSet referencedColumns( const QgsExpression::NodeFunction* node ) const override; + private: FcnEval mFnc; QStringList mAliases; + bool mUsesGeometry; + std::function < bool( const NodeFunction* node ) > mUsesGeometryFunc; + std::function < QSet( const NodeFunction* node ) > mReferencedColumnsFunc; + QSet mReferencedColumns; }; //! @note not available in Python bindings @@ -926,8 +955,18 @@ class CORE_EXPORT QgsExpression //! @note added in QGIS 2.16 bool hasNamedNodes() const { return mHasNamedNodes; } + /** + * Get a list of all the nodes. + */ QList list() { return mList; } + /** + * Get the node at position i in the list. + * + * @note Added in QGIS 3.0 + */ + Node* at( int i ) { return mList.at( i ); } + //! Returns a list of names for nodes. Unnamed nodes will be indicated by an empty string in the list. //! @note added in QGIS 2.16 QStringList names() const { return mNameList; } @@ -1077,7 +1116,7 @@ class CORE_EXPORT QgsExpression //! Tests whether the provided argument list is valid for the matching function static bool validateParams( int fnIndex, NodeList* args, QString& error ); - protected: + private: int mFnIndex; NodeList* mArgs; diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index c7a1cbbfd72a..bc89d42199ae 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -960,3 +960,15 @@ void QgsExpressionContextUtils::registerContextFunctions() { QgsExpression::registerFunction( new GetNamedProjectColor() ); } + +bool QgsScopedExpressionFunction::usesGeometry( const QgsExpression::NodeFunction* node ) const +{ + Q_UNUSED( node ) + return mUsesGeometry; +} + +QSet QgsScopedExpressionFunction::referencedColumns( const QgsExpression::NodeFunction* node ) const +{ + Q_UNUSED( node ) + return mReferencedColumns; +} diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index fa59d6a403e1..008e7fefbfa0 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -55,7 +55,9 @@ class CORE_EXPORT QgsScopedExpressionFunction : public QgsExpression::Function bool lazyEval = false, bool handlesNull = false, bool isContextual = true ) - : QgsExpression::Function( fnname, params, group, helpText, usesGeometry, referencedColumns, lazyEval, handlesNull, isContextual ) + : QgsExpression::Function( fnname, params, group, helpText, lazyEval, handlesNull, isContextual ) + , mUsesGeometry( usesGeometry ) + , mReferencedColumns( referencedColumns ) {} virtual ~QgsScopedExpressionFunction() {} @@ -66,6 +68,13 @@ class CORE_EXPORT QgsScopedExpressionFunction : public QgsExpression::Function */ virtual QgsScopedExpressionFunction* clone() const = 0; + virtual bool usesGeometry( const QgsExpression::NodeFunction* node ) const override; + + virtual QSet referencedColumns( const QgsExpression::NodeFunction* node ) const override; + + private: + bool mUsesGeometry; + QSet mReferencedColumns; }; diff --git a/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp b/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp index ee74d0a1bfa4..6a413b1ca9e4 100644 --- a/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp +++ b/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp @@ -851,7 +851,7 @@ void registerQgisFunctions( sqlite3* db ) // register QGIS expression functions Q_FOREACH ( QgsExpression::Function* foo, QgsExpression::Functions() ) { - if ( foo->usesGeometry() || foo->lazyEval() ) + if ( foo->usesGeometry( nullptr ) || foo->lazyEval() ) { // there is no "current" feature here, so calling functions that access "the" geometry does not make sense // also, we can't pass Node values for lazy evaluations diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 134938bc588b..234af4014b95 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1599,6 +1599,8 @@ class TestQgsExpression: public QObject QTest::newRow( "case 1" ) << "case when $area > 0 then 1 end" << true; QTest::newRow( "case 2" ) << "case when 1 then $area end" << true; QTest::newRow( "case 3" ) << "case when 1 then 0 else $area end" << true; + QTest::newRow( "aggregate with parent" ) << "aggregate(layer:='test',aggregate:='sum',expression:=\"col1\", filter:=intersects(geometry(@parent), make_point(1, 1)))" << true; + QTest::newRow( "aggregate without parent" ) << "aggregate(layer:='test',aggregate:='sum',expression:=\"col1\", filter:=\"c\" = 2)" << false; } void needs_geometry() From 17fc7dbe53367f66c0b68930b6d278e41d896b49 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 28 Oct 2016 10:26:39 +0700 Subject: [PATCH 512/897] [FEATURE] add array_distinct() function --- resources/function_help/json/array_distinct | 9 +++++++++ src/core/qgsexpression.cpp | 19 +++++++++++++++++++ tests/src/core/testqgsexpression.cpp | 2 ++ 3 files changed, 30 insertions(+) create mode 100644 resources/function_help/json/array_distinct diff --git a/resources/function_help/json/array_distinct b/resources/function_help/json/array_distinct new file mode 100644 index 000000000000..7dcf78c101d4 --- /dev/null +++ b/resources/function_help/json/array_distinct @@ -0,0 +1,9 @@ +{ + "name": "array_distinct", + "type": "function", + "description": "Returns an array containing distinct values of the given array.", + "arguments": [ + {"arg":"array","description":"an array"}], + "examples": [ { "expression":"array_distinct(array(1,2,3,2,1))", "returns":"array: 1,2,3"} + ] +} diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index c45f6e68017a..b2cd0cfdfb25 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3404,6 +3404,24 @@ static QVariant fcnArrayIntersect( const QVariantList& values, const QgsExpressi return QVariant( false ); } + +static QVariant fcnArrayDistinct( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QVariantList array = getListValue( values.at( 0 ), parent ); + + QVariantList distinct; + + for ( QVariantList::const_iterator it = array.constBegin(); it != array.constEnd(); ++it ) + { + if ( !distinct.contains( *it ) ) + { + distinct += ( *it ); + } + } + + return distinct; +} + static QVariant fcnArrayToString( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { QVariantList array = getListValue( values.at( 0 ), parent ); @@ -3872,6 +3890,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "array_remove_all" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "value" ) ), fcnArrayRemoveAll, QStringLiteral( "Arrays" ) ) << new StaticFunction( QStringLiteral( "array_cat" ), -1, fcnArrayCat, QStringLiteral( "Arrays" ) ) << new StaticFunction( QStringLiteral( "array_intersect" ), ParameterList() << Parameter( QStringLiteral( "array1" ) ) << Parameter( QStringLiteral( "array2" ) ), fcnArrayIntersect, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "array_distinct" ), 1, fcnArrayDistinct, QStringLiteral( "Arrays" ) ) << new StaticFunction( QStringLiteral( "array_to_string" ), ParameterList() << Parameter( QStringLiteral( "array" ) ) << Parameter( QStringLiteral( "delimiter" ), true, "," ) << Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnArrayToString, QStringLiteral( "Arrays" ) ) << new StaticFunction( QStringLiteral( "string_to_array" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "delimiter" ), true, "," ) << Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnStringToArray, QStringLiteral( "Arrays" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 234af4014b95..8b5fe2675369 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -862,6 +862,8 @@ class TestQgsExpression: public QObject QTest::newRow( "array_to_string" ) << "array_to_string(array(1,2,3),',')" << false << QVariant( "1,2,3" ); QTest::newRow( "array_to_string with custom empty value" ) << "array_to_string(array(1,'',3),',','*')" << false << QVariant( "1,*,3" ); QTest::newRow( "array_to_string fail passing non-array" ) << "array_to_string('non-array',',')" << true << QVariant(); + QTest::newRow( "array_unique" ) << "array_to_string(array_distinct(array('hello','world','world','hello')))" << false << QVariant( "hello,world" ); + QTest::newRow( "array_unique fail passing non-array" ) << "array_distinct('non-array')" << true << QVariant(); //fuzzy matching QTest::newRow( "levenshtein" ) << "levenshtein('kitten','sitting')" << false << QVariant( 3 ); From ada6050762c639f0861a7a2f79e63c967e3722fd Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 3 Oct 2016 12:04:03 +0800 Subject: [PATCH 513/897] Fix listing of WMTS layers in browser (fixes #15350) (cherry picked from commit 29d2bef7954d4e2b2cf21611c1398d0a7666e4c6) --- src/providers/wms/qgswmsdataitems.cpp | 33 +++++++++++++++++++-------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/providers/wms/qgswmsdataitems.cpp b/src/providers/wms/qgswmsdataitems.cpp index fe8af73ded02..e375def97f11 100644 --- a/src/providers/wms/qgswmsdataitems.cpp +++ b/src/providers/wms/qgswmsdataitems.cpp @@ -134,46 +134,61 @@ QVector QgsWMSConnectionItem::createChildren() QgsDataItem *layerItem = l.styles.size() == 1 ? this : new QgsDataCollectionItem( this, title, mPath + '/' + l.identifier ); if ( layerItem != this ) { + layerItem->setCapabilities( layerItem->capabilities2() & ~QgsDataItem::Fertile ); + layerItem->setState( QgsDataItem::Populated ); layerItem->setToolTip( title ); - addChildItem( layerItem ); + children << layerItem; } Q_FOREACH ( const QgsWmtsStyle &style, l.styles ) { QString styleName = style.title.isEmpty() ? style.identifier : style.title; if ( layerItem == this ) - styleName.prepend( title + " - " ); + styleName = title; // just one style so no need to display it QgsDataItem *styleItem = l.setLinks.size() == 1 ? layerItem : new QgsDataCollectionItem( layerItem, styleName, layerItem->path() + '/' + style.identifier ); if ( styleItem != layerItem ) { + styleItem->setCapabilities( styleItem->capabilities2() & ~QgsDataItem::Fertile ); + styleItem->setState( QgsDataItem::Populated ); styleItem->setToolTip( styleName ); - layerItem->addChildItem( styleItem ); + if ( layerItem == this ) + children << styleItem; + else + layerItem->addChildItem( styleItem ); } Q_FOREACH ( const QgsWmtsTileMatrixSetLink &setLink, l.setLinks ) { QString linkName = setLink.tileMatrixSet; if ( styleItem == layerItem ) - linkName.prepend( styleName + " - " ); + linkName = styleName; // just one link so no need to display it QgsDataItem *linkItem = l.formats.size() == 1 ? styleItem : new QgsDataCollectionItem( styleItem, linkName, styleItem->path() + '/' + setLink.tileMatrixSet ); if ( linkItem != styleItem ) { + linkItem->setCapabilities( linkItem->capabilities2() & ~QgsDataItem::Fertile ); + linkItem->setState( QgsDataItem::Populated ); linkItem->setToolTip( linkName ); - styleItem->addChildItem( linkItem ); + if ( styleItem == this ) + children << linkItem; + else + styleItem->addChildItem( linkItem ); } Q_FOREACH ( const QString& format, l.formats ) { QString name = format; if ( linkItem == styleItem ) - name.prepend( linkName + " - " ); + name = linkName; // just one format so no need to display it - QgsDataItem *layerItem = new QgsWMTSLayerItem( linkItem, name, linkItem->path() + '/' + name, uri, + QgsDataItem *tileLayerItem = new QgsWMTSLayerItem( linkItem, name, linkItem->path() + '/' + name, uri, l.identifier, format, style.identifier, setLink.tileMatrixSet, tileMatrixSets[ setLink.tileMatrixSet ].crs, title ); - layerItem->setToolTip( name ); - linkItem->addChildItem( layerItem ); + tileLayerItem->setToolTip( name ); + if ( linkItem == this ) + children << tileLayerItem; + else + linkItem->addChildItem( tileLayerItem ); } } } From f63a69b3096105e490eee713553d8a39784e6701 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 28 Oct 2016 11:13:26 +1000 Subject: [PATCH 514/897] Fix color pickers opens in dock layout when editing rules via layer properties --- src/app/qgsrulebasedlabelingwidget.cpp | 1 - src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/app/qgsrulebasedlabelingwidget.cpp b/src/app/qgsrulebasedlabelingwidget.cpp index c7aa3d84cb31..6e77a1fe15b6 100644 --- a/src/app/qgsrulebasedlabelingwidget.cpp +++ b/src/app/qgsrulebasedlabelingwidget.cpp @@ -144,7 +144,6 @@ void QgsRuleBasedLabelingWidget::editRule( const QModelIndex& index ) QgsRuleBasedLabeling::Rule* rule = mModel->ruleForIndex( index ); QgsLabelingRulePropsWidget* widget = new QgsLabelingRulePropsWidget( rule, mLayer, this, mCanvas ); - widget->setDockMode( true ); widget->setPanelTitle( tr( "Edit rule" ) ); connect( widget, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( ruleWidgetPanelAccepted( QgsPanelWidget* ) ) ); connect( widget, SIGNAL( widgetChanged() ), this, SLOT( liveUpdateRuleFromPanel() ) ); diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp index a46b36dabf2b..d4d6d9281ddd 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.cpp @@ -180,7 +180,6 @@ void QgsRuleBasedRendererWidget::editRule( const QModelIndex& index ) QgsRuleBasedRenderer::Rule* rule = mModel->ruleForIndex( index ); QgsRendererRulePropsWidget* widget = new QgsRendererRulePropsWidget( rule, mLayer, mStyle, this, mContext ); - widget->setDockMode( true ); widget->setPanelTitle( tr( "Edit rule" ) ); connect( widget, SIGNAL( panelAccepted( QgsPanelWidget* ) ), this, SLOT( ruleWidgetPanelAccepted( QgsPanelWidget* ) ) ); connect( widget, SIGNAL( widgetChanged() ), this, SLOT( liveUpdateRuleFromPanel() ) ); @@ -817,7 +816,7 @@ void QgsRendererRulePropsWidget::apply() void QgsRendererRulePropsWidget::setDockMode( bool dockMode ) { QgsPanelWidget::setDockMode( dockMode ); - mSymbolSelector->setDockMode( true ); + mSymbolSelector->setDockMode( dockMode ); } //////// From e1e3f86b9e8cc1e42756732769ef1f9b8f897b27 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 28 Oct 2016 11:14:26 +1000 Subject: [PATCH 515/897] Fix color picker does not show previous color --- src/gui/qgscolorbutton.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/gui/qgscolorbutton.cpp b/src/gui/qgscolorbutton.cpp index c1ef8c15e178..81ad68881f88 100644 --- a/src/gui/qgscolorbutton.cpp +++ b/src/gui/qgscolorbutton.cpp @@ -97,9 +97,16 @@ void QgsColorButton::showColorDialog() QgsPanelWidget* panel = QgsPanelWidget::findParentPanel( this ); if ( panel && panel->dockMode() ) { - QgsCompoundColorWidget* colorWidget = new QgsCompoundColorWidget( panel, color(), QgsCompoundColorWidget::LayoutVertical ); + QColor currentColor = color(); + QgsCompoundColorWidget* colorWidget = new QgsCompoundColorWidget( panel, currentColor, QgsCompoundColorWidget::LayoutVertical ); colorWidget->setPanelTitle( mColorDialogTitle ); colorWidget->setAllowAlpha( mAllowAlpha ); + + if ( currentColor.isValid() ) + { + colorWidget->setPreviousColor( currentColor ); + } + connect( colorWidget, SIGNAL( currentColorChanged( QColor ) ), this, SLOT( setValidTemporaryColor( QColor ) ) ); panel->openPanel( colorWidget ); return; From 79e5911e07ccdee5daec43f490b219ef804cc8c3 Mon Sep 17 00:00:00 2001 From: Paolo Cavallini Date: Fri, 28 Oct 2016 09:11:28 +0200 Subject: [PATCH 516/897] Update RegularPoints.py Fixes #15773 --- python/plugins/processing/algs/qgis/RegularPoints.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/RegularPoints.py b/python/plugins/processing/algs/qgis/RegularPoints.py index c1a1a7703a4b..ff05f329aac0 100644 --- a/python/plugins/processing/algs/qgis/RegularPoints.py +++ b/python/plugins/processing/algs/qgis/RegularPoints.py @@ -65,7 +65,7 @@ def defineCharacteristics(self): self.addParameter(ParameterExtent(self.EXTENT, self.tr('Input extent'), optional=False)) self.addParameter(ParameterNumber(self.SPACING, - self.tr('Point spacing/count'), 0.0001, 999999999.999999999, 0.0001)) + self.tr('Point spacing/count'), 100, 999999999.999999999, 100)) self.addParameter(ParameterNumber(self.INSET, self.tr('Initial inset from corner (LH side)'), 0.0, 9999.9999, 0.0)) self.addParameter(ParameterBoolean(self.RANDOMIZE, From ea2e68b8ae454d461530f8afcbe6cb2740d3033d Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 28 Oct 2016 15:53:46 +0800 Subject: [PATCH 517/897] Fix WMS identify when using "Feature" format and the layer has named CRS (cherry picked from commit 9ef91ea6294cdab762ffb2543d02473bcccbed80) --- src/providers/wms/qgswmsprovider.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/providers/wms/qgswmsprovider.cpp b/src/providers/wms/qgswmsprovider.cpp index 8806a0e5067b..c9284fa94f33 100644 --- a/src/providers/wms/qgswmsprovider.cpp +++ b/src/providers/wms/qgswmsprovider.cpp @@ -2983,7 +2983,7 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs QString crsType = result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "type" ) ).toString(); QString crsText; if ( crsType == QLatin1String( "name" ) ) - crsText = result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "name" ) ).toString(); + crsText = result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "properties" ) ).property( QStringLiteral( "name" ) ).toString(); else if ( crsType == QLatin1String( "EPSG" ) ) crsText = QStringLiteral( "%1:%2" ).arg( crsType, result.property( QStringLiteral( "crs" ) ).property( QStringLiteral( "properties" ) ).property( QStringLiteral( "code" ) ).toString() ); else @@ -3080,6 +3080,7 @@ QgsRasterIdentifyResult QgsWmsProvider::identify( const QgsPoint & thePoint, Qgs catch ( const QString &err ) { QgsDebugMsg( QString( "JSON error: %1\nResult: %2" ).arg( err, QString::fromUtf8( mIdentifyResultBodies.value( jsonPart ) ) ) ); + results.insert( results.size(), err ); // string returned for format type "feature" means error } results.insert( results.size(), qVariantFromValue( featureStoreList ) ); From 59d1d702d0b9b783493f62fd0dcc2341b5021357 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 3 Oct 2016 17:49:37 +0800 Subject: [PATCH 518/897] Fix identify tool for WMS if webkit is not available (fixes #15596) (cherry picked from commit 430694ba9a2beb5fe23d5814b63aaecdbee7a3d7) --- src/core/qgswebpage.h | 2 ++ src/core/qgswebview.h | 12 +++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/core/qgswebpage.h b/src/core/qgswebpage.h index d55e51a896ff..3a3ef7b6f5b2 100644 --- a/src/core/qgswebpage.h +++ b/src/core/qgswebpage.h @@ -183,6 +183,8 @@ class CORE_EXPORT QWebPage : public QObject signals: + void loadFinished( bool ok ); + public slots: protected: diff --git a/src/core/qgswebview.h b/src/core/qgswebview.h index 13d1740375c8..03f12e176ce8 100644 --- a/src/core/qgswebview.h +++ b/src/core/qgswebview.h @@ -66,6 +66,7 @@ class CORE_EXPORT QgsWebView : public QTextBrowser , mPage( new QWebPage( this ) ) { connect( this, SIGNAL( anchorClicked( const QUrl & ) ), this, SIGNAL( linkClicked( const QUrl & ) ) ); + connect( this, SIGNAL( pageLoadFinished( bool ) ), mPage, SIGNAL( loadFinished( bool ) ) ); } ~QgsWebView() @@ -99,8 +100,15 @@ class CORE_EXPORT QgsWebView : public QTextBrowser return new QgsWebView(); } - void setContent( const QByteArray&, const QString&, const QUrl& ) + void setContent( const QByteArray& data, const QString& contentType, const QUrl& ) { + QString text = QString::fromUtf8( data ); + if ( contentType == "text/html" ) + setHtml( text ); + else + setPlainText( text ); + + emit pageLoadFinished( true ); } void print( QPrinter* ) @@ -110,6 +118,8 @@ class CORE_EXPORT QgsWebView : public QTextBrowser signals: void linkClicked( const QUrl &link ); + void pageLoadFinished( bool ok ); + private: QWebSettings *mSettings; QWebPage *mPage; From aeeb5d95256ee51b51dfcaf7daa79fe085c5cef5 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Wed, 5 Oct 2016 09:08:21 +0800 Subject: [PATCH 519/897] Fix crash when loading WCS layers (fixes #15595) The problem is that some providers would still issue network requests in prepareJobs() - this should be ideally avoided, because it is run in main thread - all the work should be deferred to be done in worker thread. (cherry picked from commit 08f4a0f40cce21d5730653a75bdd44f175f3b0b8) --- src/core/qgsmaprenderercustompainterjob.cpp | 8 -------- src/core/qgsmaprendererparalleljob.cpp | 8 -------- src/gui/qgsmapcanvas.cpp | 11 ++++++++--- 3 files changed, 8 insertions(+), 19 deletions(-) diff --git a/src/core/qgsmaprenderercustompainterjob.cpp b/src/core/qgsmaprenderercustompainterjob.cpp index 3bde891c87ef..c50dbb786367 100644 --- a/src/core/qgsmaprenderercustompainterjob.cpp +++ b/src/core/qgsmaprenderercustompainterjob.cpp @@ -84,14 +84,6 @@ void QgsMapRendererCustomPainterJob::start() } mLayerJobs = prepareJobs( mPainter, mLabelingEngineV2 ); - // prepareJobs calls mapLayer->createMapRenderer may involve cloning a RasterDataProvider, - // whose constructor may need to download some data (i.e. WMS, AMS) and doing so runs a - // QEventLoop waiting for the network request to complete. If unluckily someone calls - // mapCanvas->refresh() while this is happening, QgsMapRendererCustomPainterJob::cancel is - // called, deleting the QgsMapRendererCustomPainterJob while this function is running. - // Hence we need to check whether the job is still active before proceeding - if ( !isActive() ) - return; QgsDebugMsg( "Rendering prepared in (seconds): " + QString( "%1" ).arg( prepareTime.elapsed() / 1000.0 ) ); diff --git a/src/core/qgsmaprendererparalleljob.cpp b/src/core/qgsmaprendererparalleljob.cpp index a9c31fa2975b..f927c3f59a7d 100644 --- a/src/core/qgsmaprendererparalleljob.cpp +++ b/src/core/qgsmaprendererparalleljob.cpp @@ -62,14 +62,6 @@ void QgsMapRendererParallelJob::start() } mLayerJobs = prepareJobs( nullptr, mLabelingEngineV2 ); - // prepareJobs calls mapLayer->createMapRenderer may involve cloning a RasterDataProvider, - // whose constructor may need to download some data (i.e. WMS, AMS) and doing so runs a - // QEventLoop waiting for the network request to complete. If unluckily someone calls - // mapCanvas->refresh() while this is happening, QgsMapRendererCustomPainterJob::cancel is - // called, deleting the QgsMapRendererCustomPainterJob while this function is running. - // Hence we need to check whether the job is still active before proceeding - if ( !isActive() ) - return; QgsDebugMsg( QString( "QThreadPool max thread count is %1" ).arg( QThreadPool::globalInstance()->maxThreadCount() ) ); diff --git a/src/gui/qgsmapcanvas.cpp b/src/gui/qgsmapcanvas.cpp index 86e0a3f71360..3f0751416f96 100644 --- a/src/gui/qgsmapcanvas.cpp +++ b/src/gui/qgsmapcanvas.cpp @@ -575,9 +575,6 @@ void QgsMapCanvas::refreshMap() stopRendering(); // if any... - // from now on we can accept refresh requests again - mRefreshScheduled = false; - //build the expression context QgsExpressionContext expressionContext; expressionContext << QgsExpressionContextUtils::globalScope() @@ -610,6 +607,14 @@ void QgsMapCanvas::refreshMap() mJob->start(); + // from now on we can accept refresh requests again + // this must be reset only after the job has been started, because + // some providers (yes, it's you WCS and AMS!) during preparation + // do network requests and start an internal event loop, which may + // end up calling refresh() and would schedule another refresh, + // deleting the one we have just started. + mRefreshScheduled = false; + mMapUpdateTimer.start(); emit renderStarting(); From ed3b0714dd8513c31ca0b5468f71057d90ceb936 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Wed, 5 Oct 2016 09:18:37 +0800 Subject: [PATCH 520/897] Cancel WCS requests just like it is done in WMS (cherry picked from commit 50258e6f01ef7dededbf057c03813ecf3442f5b9) --- src/providers/wcs/qgswcsprovider.cpp | 17 ++++++++++++++--- src/providers/wcs/qgswcsprovider.h | 2 ++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/providers/wcs/qgswcsprovider.cpp b/src/providers/wcs/qgswcsprovider.cpp index bbb4044461e7..dabd0a2b80bb 100644 --- a/src/providers/wcs/qgswcsprovider.cpp +++ b/src/providers/wcs/qgswcsprovider.cpp @@ -1653,7 +1653,18 @@ QgsWcsDownloadHandler::QgsWcsDownloadHandler( const QUrl& url, QgsWcsAuthorizati , mCachedData( cachedData ) , mWcsVersion( wcsVersion ) , mCachedError( cachedError ) + , mFeedback( feedback ) { + if ( feedback ) + { + connect( feedback, SIGNAL( cancelled() ), this, SLOT( cancelled() ), Qt::QueuedConnection ); + + // rendering could have been cancelled before we started to listen to cancelled() signal + // so let's check before doing the download and maybe quit prematurely + if ( feedback->isCancelled() ) + return; + } + QNetworkRequest request( url ); if ( !mAuth.setAuthorization( request ) ) { @@ -1676,9 +1687,6 @@ QgsWcsDownloadHandler::QgsWcsDownloadHandler( const QUrl& url, QgsWcsAuthorizati } connect( mCacheReply, SIGNAL( finished() ), this, SLOT( cacheReplyFinished() ) ); connect( mCacheReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( cacheReplyProgress( qint64, qint64 ) ) ); - - if ( feedback ) - connect( feedback, SIGNAL( cancelled() ), this, SLOT( cancelled() ), Qt::QueuedConnection ); } QgsWcsDownloadHandler::~QgsWcsDownloadHandler() @@ -1688,6 +1696,9 @@ QgsWcsDownloadHandler::~QgsWcsDownloadHandler() void QgsWcsDownloadHandler::blockingDownload() { + if ( mFeedback && mFeedback->isCancelled() ) + return; // nothing to do + mEventLoop->exec( QEventLoop::ExcludeUserInputEvents ); Q_ASSERT( !mCacheReply ); diff --git a/src/providers/wcs/qgswcsprovider.h b/src/providers/wcs/qgswcsprovider.h index 91ac010a6303..75447d0f1fc2 100644 --- a/src/providers/wcs/qgswcsprovider.h +++ b/src/providers/wcs/qgswcsprovider.h @@ -443,6 +443,8 @@ class QgsWcsDownloadHandler : public QObject QString mWcsVersion; QgsError& mCachedError; + QgsRasterBlockFeedback* mFeedback; + static int sErrors; // this should be ideally per-provider...? }; From 9ecdf61014334cf20072be5ed0ba2406774d7af3 Mon Sep 17 00:00:00 2001 From: Hugo Mercier Date: Fri, 28 Oct 2016 11:17:46 +0200 Subject: [PATCH 521/897] Don't delete QgsAttributeDialog too early. Fixes #15737 --- src/app/qgsfeatureaction.cpp | 30 +++++++++++++++++++----------- src/gui/qgsattributedialog.cpp | 5 +---- src/gui/qgsattributedialog.h | 5 ++--- 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index da2f8703c67b..c39dbd33f30e 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -102,7 +102,9 @@ bool QgsFeatureAction::viewFeatureForm( QgsHighlight *h ) QgsAttributeDialog *dialog = newDialog( true ); dialog->setHighlight( h ); - dialog->show(); // will also delete the dialog on close (show() is overridden) + // delete the dialog when it is closed + dialog->setAttribute( Qt::WA_DeleteOnClose ); + dialog->show(); return true; } @@ -112,22 +114,27 @@ bool QgsFeatureAction::editFeature( bool showModal ) if ( !mLayer ) return false; - QgsAttributeDialog *dialog = newDialog( false ); - - if ( !mFeature->isValid() ) - dialog->setMode( QgsAttributeForm::AddFeatureMode ); - if ( showModal ) { - dialog->setAttribute( Qt::WA_DeleteOnClose ); - int rv = dialog->exec(); + QScopedPointer dialog( newDialog( false ) ); + + if ( !mFeature->isValid() ) + dialog->setMode( QgsAttributeForm::AddFeatureMode ); + int rv = dialog->exec(); mFeature->setAttributes( dialog->feature()->attributes() ); return rv; } else { - dialog->show(); // will also delete the dialog on close (show() is overridden) + QgsAttributeDialog* dialog = newDialog( false ); + + if ( !mFeature->isValid() ) + dialog->setMode( QgsAttributeForm::AddFeatureMode ); + + // delete the dialog when it is closed + dialog->setAttribute( Qt::WA_DeleteOnClose ); + dialog->show(); } return true; @@ -204,6 +211,8 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo else { QgsAttributeDialog *dialog = newDialog( false ); + // delete the dialog when it is closed + dialog->setAttribute( Qt::WA_DeleteOnClose ); dialog->setMode( QgsAttributeForm::AddFeatureMode ); dialog->setEditCommandMessage( text() ); @@ -212,12 +221,11 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo if ( !showModal ) { setParent( dialog ); // keep dialog until the dialog is closed and destructed - dialog->show(); // will also delete the dialog on close (show() is overridden) + dialog->show(); mFeature = nullptr; return true; } - dialog->setAttribute( Qt::WA_DeleteOnClose ); dialog->exec(); } diff --git a/src/gui/qgsattributedialog.cpp b/src/gui/qgsattributedialog.cpp index a772ad83ae65..2aa9d6b77abf 100644 --- a/src/gui/qgsattributedialog.cpp +++ b/src/gui/qgsattributedialog.cpp @@ -69,11 +69,8 @@ void QgsAttributeDialog::accept() QDialog::accept(); } -void QgsAttributeDialog::show( bool autoDelete ) +void QgsAttributeDialog::show() { - if ( autoDelete ) - setAttribute( Qt::WA_DeleteOnClose ); - QDialog::show(); raise(); activateWindow(); diff --git a/src/gui/qgsattributedialog.h b/src/gui/qgsattributedialog.h index 83dbecead012..a5939abdc1c4 100644 --- a/src/gui/qgsattributedialog.h +++ b/src/gui/qgsattributedialog.h @@ -106,9 +106,8 @@ class GUI_EXPORT QgsAttributeDialog : public QDialog void accept() override; void reject() override; - //! Show the dialog non-blocking. Reparents this dialog to be a child of the dialog form and is deleted when - //! closed. - void show( bool autoDelete = true ); + //! Show the dialog non-blocking. Reparents this dialog to be a child of the dialog form + void show(); private: void init( QgsVectorLayer* layer, QgsFeature* feature, const QgsAttributeEditorContext& context, bool showDialogButtons ); From 800b1a6f63d0f0be73b968d3f683ee51d0a4c5d7 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 28 Oct 2016 17:56:03 +0800 Subject: [PATCH 522/897] fix indentation --- src/core/qgswebpage.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgswebpage.h b/src/core/qgswebpage.h index 3a3ef7b6f5b2..57a1d5a04381 100644 --- a/src/core/qgswebpage.h +++ b/src/core/qgswebpage.h @@ -183,7 +183,7 @@ class CORE_EXPORT QWebPage : public QObject signals: - void loadFinished( bool ok ); + void loadFinished( bool ok ); public slots: From 8e25b893573a31926d0b01a3d8eb82f328d3572d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 28 Oct 2016 11:06:21 +0200 Subject: [PATCH 523/897] Merge duplicated api doc break section titles --- doc/api_break.dox | 162 +++------------------------------------------- 1 file changed, 9 insertions(+), 153 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index a7888286da60..52df5d18ac1b 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -16,6 +16,8 @@ with too big impact should be deferred to a major version release. This page tries to maintain a list with incompatible changes that happened in previous releases. + + QGIS 3.0 {#qgis_api_break_3_0} ======== @@ -29,6 +31,7 @@ Moved Classes {#qgis_api_break_3_0_moved_classes} QgsMapLayerProxyModelguicore + Renamed Classes {#qgis_api_break_3_0_renamed_classes} --------------- @@ -178,10 +181,10 @@ Renamed Classes {#qgis_api_break_3_0_renamed_classes} QgsServerInterfacecapabiblitiesCachecapabilitiesCache + Removed Classes {#qgis_api_break_3_0_removed_classes} --------------- - - QgsAttributeAction was removed, and replaced by QgsActionManager. - QgsAttributeEditor was removed. Use QgsEditorWidgetRegistry::create() instead. - QgsColorbutton was removed. QgsColorButtonV2 has now been renamed to QgsColorButton. Hence, QgsColorButtonV2 does not exist anymore. @@ -209,7 +212,6 @@ should now call QgsCoordinateReferenceSystem::invalidateCache() and QgsCoordinat General changes {#qgis_api_break_3_0_global} --------------- - - All setDestinationCRS() methods have been renamed to setDestinationCrs() - All destinationCRS() methods have been renamed to destinationCrs() - All readXML() and _readXML() methods have been renamed to readXml() and _readXml() @@ -225,11 +227,9 @@ General changes {#qgis_api_break_3_0_global} - All methods taking or returning QGis::GeometryType have been changed to use QgsWkbTypes::GeometryType - Data Providers {#qgis_api_break_3_0_DataProviders} -------------- - - Many methods in QgsDataProvider, QgsVectorDataProvider and QgsRasterDataProvider have been made const-correct. This has no effect on PyQGIS code, but c++ code implementing third-party providers will need to update the signatures of these methods to match. Affected methods are: @@ -253,7 +253,6 @@ Data Providers {#qgis_api_break_3_0_DataProviders} Qgis {#qgis_api_break_3_0_Qgis} ---- - - The QGis class was renamed to Qgis for capitalisation consistency with other class names - permissiveToDouble() and permissiveToInt() where moved out of the QGis class and renamed to qgsPermissiveToDouble() and qgsPermissiveToInt() @@ -280,11 +279,9 @@ corresponding counterparts in QgsUnitTypes should be used instead. - featureType() has been removed. Use the equivalent QgsWkbTypes::displayString() instead. - QgisInterface {#qgis_api_break_3_0_QgisInterface} ------------- - - fileMenu() has been removed, use projectMenu() instead. - actionRemoveLayer was removed as it no longer exists. @@ -292,7 +289,6 @@ QgisInterface {#qgis_api_break_3_0_QgisInterface} QgsAnnotation {#qgis_api_break_3_0_QgsAnnotation} ------------- - - mapPositionFixed() has been renamed to hasFixedMapPosition() @@ -300,7 +296,6 @@ QgsAnnotation {#qgis_api_break_3_0_QgsAnnotation} QgsActionManager {#qgis_api_break_3_0_QgsActionManager} ---------------- - - doAction() no longer accepts a substitution map. Use expression context variables instead. - The doAction() variant which takes a QgsFeature along has been removed. Use the expression context variant instead. @@ -311,14 +306,12 @@ variant instead. QgsAdvancedDigitizingDockWidget {#qgis_api_break_3_0_QgsAdvancedDigitizingDockWidget} ------------------------------- - - canvasReleaseEvent takes now QgsAdvancedDigitizingDockWidget::CaptureMode as second argument. QgsAtlasComposition {#qgis_api_break_3_0_QgsAtlasComposition} ------------------- - - readXMLMapSettings() has been renamed to readXmlMapSettings() - composerMap() and setComposerMap() were removed. Use QgsComposerMap::atlasDriven() and setAtlasDriven() instead @@ -334,7 +327,6 @@ and setSortKeyAttributeName() instead. QgsAttributeDialog {#qgis_api_break_3_0_QgsAttributeDialog} ------------------ - - The constructor for QgsAttributeDialog has changed - dialog() was removed - just use the object directly. - setIsAddDialog() was removed. Use setMode() instead. @@ -343,7 +335,6 @@ QgsAttributeDialog {#qgis_api_break_3_0_QgsAttributeDialog} QgsAttributeForm {#qgis_api_break_3_0_QgsAttributeForm} ---------------- - - setIsAddDialog() was removed. Use setMode() instead. - accept() was removed. Use save() instead. - reject() was removed. Use resetValues() instead. @@ -352,7 +343,6 @@ QgsAttributeForm {#qgis_api_break_3_0_QgsAttributeForm} QgsAuthConfigUriEdit {#qgis_api_break_3_0_QgsAuthConfigUriEdit} -------------------- - - hasConfigID() has been renamed to hasConfigId() @@ -378,14 +368,12 @@ QgsCategorizedSymbolRendererWidget {#qgis_api_break_3_0_QgsCategorizedSym QgsClipper {#qgis_api_break_3_0_QgsClipper} ---------- - - clippedLineWKB has been renamed to clippedLine and it's signature has been changed to return a QPolygonF QgsColorBrewerColorRampDialog {#qgis_api_break_3_0_QgsColorBrewerColorRampDialog} ----------------------------- - - The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited and the new ramp can be retrieved after executing the dialog by calling ramp(). - Some internal methods which were previously public or protected were made private. @@ -394,14 +382,12 @@ and the new ramp can be retrieved after executing the dialog by calling ramp(). QgsColorRampShader {#qgis_api_break_3_0_QgsColorRampShader} ------------------ - - maximumColorCacheSize() and setMaximumColorCacheSize() were no longer used and are removed. QgsComposerArrow {#qgis_api_break_3_0_QgsComposerArrow} ---------------- - - setOutlineWidth(), outlineWidth(), arrowColor() and setArrowColor() were removed. Use setArrowHeadOutlineWidth(), arrowHeadOutlineWidth(), arrowHeadOutlineColor(), setArrowHeadOutlineColor(), arrowHeadFillColor(), setArrowHeadFillColor(), @@ -411,14 +397,12 @@ setLineSymbol() or lineSymbol() instead. QgsComposerAttributeTableV2 {#qgis_api_break_3_0_QgsComposerAttributeTableV2} --------------------------- - - setDisplayAttributes() was removed. Use setDisplayedFields() instead. QgsComposerItem {#qgis_api_break_3_0_QgsComposerItem} --------------- - - zoomContent( int delta, double x, double y ) was removed. Use zoomContent( double, QPointF, ZoomMode ) instead. - drawText(), textWidthMillimeters(), fontHeightCharacterMM(), fontAscentMillimeters(), @@ -434,7 +418,6 @@ sizeChangedByRotation() were removed. No replacement is offered for these method QgsComposerLabel {#qgis_api_break_3_0_QgsComposerLabel} ---------------- - - setExpressionContext() has been removed. Setup the composition using an atlas and with expression variables in the composer label item instead. - setSubstitutions has been removed. Use expression context variables in the composer @@ -445,7 +428,6 @@ label item instead. QgsComposerLegend {#qgis_api_break_3_0_QgsComposerLegend} ----------------- - - model() now returns the new QgsLegendModel (previously QgsLegendModelV2, see \ref qgis_api_break_3_0_renamed_classes). - modelV2() has been renamed to model(). @@ -453,14 +435,12 @@ QgsComposerLegend {#qgis_api_break_3_0_QgsComposerLegend} QgsComposerLegendItem {#qgis_api_break_3_0_QgsComposerLegendItem} --------------------- - - writeXMLChildren() has been renamed to writeXmlChildren() QgsComposerMap {#qgis_api_break_3_0_QgsComposerMap} -------------- - - containsWMSLayer() has been renamed to containsWmsLayer() - mapRenderer() has been removed. Use mapSettings() instead. - All grid style and format enums were moved to QgsComposerMapGrid. @@ -479,7 +459,6 @@ and setAtlasScalingMode() instead. QgsComposerMapGrid {#qgis_api_break_3_0_QgsComposerMapGrid} ------------------ - - The annotation position Disabled was removed. QgsComposerMapGrid::HideAll should be used instead. @@ -487,7 +466,6 @@ should be used instead. QgsComposerMultiFrame {#qgis_api_break_3_0_QgsComposerMultiFrame} --------------------- - - render( QPainter* p, const QRectF& renderExtent ) was removed. Use render( QPainter* painter, const QRectF& renderExtent, const int frameIndex ) instead. @@ -498,7 +476,6 @@ was made pure virtual. QgsComposerNodesItem {#qgis_api_break_3_0_QgsComposerNodesItem} -------------------- - - _readXMLStyle() has been renamed to _readXmlStyle() - _writeXMLStyle() has been renamed to _writeXMLStyle() @@ -506,7 +483,6 @@ QgsComposerNodesItem {#qgis_api_break_3_0_QgsComposerNodesItem} QgsComposerPicture {#qgis_api_break_3_0_QgsComposerPicture} ------------------ - - setPictureFile() and pictureFile() were removed. Use setPicturePath() and picturePath() instead. - rotation() and setRotation() were removed. Use pictureRotation() @@ -521,7 +497,6 @@ QgsComposerObject::setDataDefinedProperty() instead. QgsComposerTable {#qgis_api_break_3_0_QgsComposerTable} ---------------- - - tableWriteXML() has been renamed to tableWriteXml() - tableReadXML() has been renamed to tableReadXml() @@ -529,7 +504,6 @@ QgsComposerTable {#qgis_api_break_3_0_QgsComposerTable} QgsComposerTableV2 {#qgis_api_break_3_0_QgsComposerTableV2} ------------------ - - rowsVisible(), rowRange(), drawHorizontalGridLines() and drawVerticalGridLines() were removed. @@ -537,7 +511,6 @@ QgsComposerTableV2 {#qgis_api_break_3_0_QgsComposerTableV2} QgsComposition {#qgis_api_break_3_0_QgsComposition} -------------- - - addItemsFromXML() has been renamed to addItemsFromXml() - Constructor with QgsMapRenderer parameter has been removed. Use the variant with QgsMapSettings parameter. - mapRenderer() has been removed. Use mapSettings() instead. @@ -566,7 +539,6 @@ called if changes are made to the CRS database. QgsCoordinateTransform {#qgis_api_break_3_0_QgsCoordinateTransform} ---------------------- - - QgsCoordinateTransform is no longer a QObject. readXml, writeXml and initialise are all normal public members now, not slots. The invalidTransformInput() signal has been removed. - The extra QgsCoordinateTransform constructors (those not taking QgsCoordinateReferenceSystem arguments) have been @@ -589,7 +561,6 @@ plugins calling these methods will need to be updated. QgsCoordinateTransformCache {#qgis_api_break_3_0_QgsCoordinateTransformCache} --------------------------- - - transform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be returned in place of a null pointer. @@ -597,7 +568,6 @@ be returned in place of a null pointer. QgsCptCityColorRampDialog {#qgis_api_break_3_0_QgsCptCityColorRampDialog} ------------------------- - - The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited and the new ramp can be retrieved after executing the dialog by calling ramp(). - Some internal methods which were previously public or protected were made private. @@ -606,14 +576,12 @@ and the new ramp can be retrieved after executing the dialog by calling ramp(). QgsCptCitySelectionItem {#qgis_api_break_3_0_QgsCptCitySelectionItem} ----------------------- - - parseXML() has been renamed to parseXml() QgsCRSCache {#qgis_api_break_3_0_QgsCRSCache} ----------- - - QgsCRSCache has been renamed to QgsCrsCache - updateCRSCache() has been renamed to updateCrsCache @@ -621,13 +589,12 @@ QgsCRSCache {#qgis_api_break_3_0_QgsCRSCache} QgsCursors {#qgis_api_break_3_0_QgsCursors} --------- - - remove old bitmap cursors pan and pan_mask. Use window system curosrs instead. + QgsDataDefined {#qgis_api_break_3_0_QgsDataDefined} -------------- - - expressionParams(), setExpressionParams() and insertExpressionParam() have been removed. QgsExpressionContext variables should be used in their place. - prepareExpression( QgsVectorLayer* layer ) and prepareExpression( const QgsFields &fields ) @@ -639,7 +606,6 @@ were removed. Use QgsExpressionContext variant instead. QgsDataDefinedButton {#qgis_api_break_3_0_QgsDataDefinedButton} -------------------- - - registerGetExpressionContextCallback has been removed in favor of registerExpressionContextGenerator @@ -647,7 +613,6 @@ QgsDataDefinedButton {#qgis_api_break_3_0_QgsDataDefinedButton} QgsDataDefinedSymbolDialog {#qgis_api_break_3_0_QgsDataDefinedSymbolDialog} -------------------------- - - QgsDataDefinedSymbolDialog was removed. Code using this dialog should be reworked to use QgsDataDefinedButton instead. @@ -655,7 +620,6 @@ instead. QgsDataItem {#qgis_api_break_3_0_QgsDataItem} ----------- - - supportedCRS() has been renamed to supportedCrs() - isPopulated() has been removed. Use state() instead. - capabilities() has been removed. Use capabilities2() instead (TODO: rename back to capabilities()). @@ -665,7 +629,6 @@ QgsDataItem {#qgis_api_break_3_0_QgsDataItem} QgsDataSourceURI {#qgis_api_break_3_0_QgsDatasourceUri} ---------------- - - QgsDataSourceURI has been renamed to QgsDataSourceUri - QgsDataSourceURI::SSLmode has been renamed to QgsDataSourceUri::SslMode. All items of this enum have been properly CamelCased. @@ -673,7 +636,6 @@ QgsDataSourceURI {#qgis_api_break_3_0_QgsDatasourceUri} QgsDatumTransformStore {#qgis_api_break_3_0_QgsDatumTransformStore} ---------------------- - - transformation() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be returned in place of a null pointer. @@ -681,7 +643,6 @@ be returned in place of a null pointer. QgsDiagram {#qgis_api_break_3_0_QgsDiagram} ---------- - - The deprecated getExpression( const QString& expression, const QgsFields* fields ) method has been removed. Use the variant which accepts an expression context instead. - The deprecated renderDiagram( const QgsAttributes& att, QgsRenderContext& c, const QgsDiagramSettings& s, QPointF position ) method has been removed. @@ -693,14 +654,12 @@ Use diagramSize( const QgsFeature& feature, const QgsRenderContext& c, const Qgs QgsDiagramRenderer {#qgis_api_break_3_0_QgsDiagramRenderer} ------------------ - - xform, fields were no longer required and are removed. QgsDiagramLayerSettings {#qgis_api_break_3_0_QgsDiagramLayerSettings} ----------------------- - - coordinateTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be returned in place of a null pointer. - setCoordinateTransform() now takes a QgsCoordinateTransform object, not a pointer. Use an invalid QgsCoordinateTransform in @@ -711,14 +670,12 @@ place of a null pointer. QgsDiagramSettings {#qgis_api_break_3_0_QgsDiagramSettings} ------------------ - - The SizeType enum was removed. Use QgsUnitTypes.RenderUnit instead. QgsDistanceArea {#qgis_api_break_3_0_QgsDistanceArea} --------------- - - sourceCrs() now returns a QgsCoordinateReferenceSystem instead of the crs ID. - measure() has been removed. Use measureArea() or measureLength() instead. - textUnit() was removed. Use formatDistance() or formatArea() instead. @@ -728,7 +685,6 @@ QgsDistanceArea {#qgis_api_break_3_0_QgsDistanceArea} QgsDxfExport {#qgis_api_break_3_0_QgsDxfExport} ------------ - - The writeGroup() method taking a QgsPoint argument was removed. Use the version which takes a QgsPointV2 instead. - The writePolyline() method taking a QgsPolyline argument was removed. Use the alternative version instead. - The writePolygon() method taking a QgsPolygon argument was removed. Use the version which takes a QgsRingSequence instead. @@ -741,7 +697,6 @@ QgsDxfExport {#qgis_api_break_3_0_QgsDxfExport} QgsEditFormConfig {#qgis_api_break_3_0_QgsEditFormConfig} ----------------- - - Does no longer inherit QObject - widgetType() and widgetConfig() now reflect only the user configured values. QgsEditorWidgetRegistry::instance()->findBest() must be used instead. @@ -755,7 +710,6 @@ QgsEditorWidgetRegistry::instance()->findBest() must be used instead. QgsExpression {#qgis_api_break_3_0_QgsExpression} ------------- - - prepare( const QgsFields &fields ) has been removed. Use prepare( const QgsExpressionContext *context ) instead. - The evaluate methods which accept feature parameters have been removed. Use the version which takes a QgsExpressionContext argument instead. @@ -774,6 +728,7 @@ version instead. - QgsExpression::referencedColumns() returns QSet instead of QStringList - QgsExpression::Node::referencedColumns() returns QSet instead of QStringList + QgsExpression::Function {#qgis_api_break_3_0_QgsExpression_Function} ----------------------- @@ -786,7 +741,6 @@ QgsExpression::Function {#qgis_api_break_3_0_QgsExpression_Function} QgsFeature {#qgis_api_break_3_0_QgsFeature} ---------- - - geometryAndOwnership() has been removed. Use geometry() instead. - setGeometryAndOwnership() has been removed. Use setGeometry() instead. - The setGeometry( QgsGeometry* ) method has been removed, use setGeometry( const QgsGeometry& ) instead. @@ -802,7 +756,6 @@ None will need to be modified, as the method will return an empty geometry if th QgsFeatureRendererV2 {#qgis_api_break_3_0_QgsFeatureRendererV2} -------------------- - - The method capabilities() returns QgsFeatureRendererV2::Capabilities flags instead of an integer. The two are binary compatible. - symbolForFeature( QgsFeature& feature ) has been removed. The symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) method should be used instead (previously available as symbolForFeature2 in PyQGIS bindings). symbolForFeature has been made pure virtual. - originalSymbolForFeature( QgsFeature& feature ) has been removed. The symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) method should be used instead (previously available as originalSymbolForFeature2 in PyQGIS bindings). @@ -819,7 +772,6 @@ QgsFeatureRendererV2 {#qgis_api_break_3_0_QgsFeatureRendererV2} QgsFields {#qgis_api_break_3_0_QgsFields} --------- - - All const methods which return a field from QgsFields now return a QgsField value, not a reference. - fieldNameIndex has been renamed to lookupField. See the API documentation for details. @@ -827,21 +779,18 @@ QgsFields {#qgis_api_break_3_0_QgsFields} QgsFieldExpressionWidget {#qgis_api_break_3_0_QgsFieldExpressionWidget} ------------------------ - - registerGetExpressionContextCallback has been removed in favor of registerExpressionContextGenerator QgsFieldProxyModel {#qgis_api_break_3_0_QgsFieldProxyModel} ------------------ - - In QgsFieldProxyModel::Filter, All has been renamed to AllTypes QgsGeometry {#qgis_api_break_3_0_QgsGeometry} ----------- - - All QgsGeometry methods now accept geometry references instead of pointers, and return a QgsGeometry value instead of a pointer. The biggest impact with this change is that PyQGIS code should not compare a geometry result to None, but instead either use a boolean test (`if g.buffer(10):`) or explicitly use the isEmpty() @@ -857,7 +806,6 @@ method to determine if a geometry is valid. QgsGeometryAnalyzer {#qgis_api_break_3_0_QgsGeometryAnalyzer} ------------------- - - locateBetweenMeasures() and locateAlongMeasure() now take geometry references, not pointers, and return a QgsGeometry value rather than a pointer. @@ -865,14 +813,12 @@ a QgsGeometry value rather than a pointer. QgsGeometrySimplifier {#qgis_api_break_3_0_QgsGeometrySimplifier} --------------------- - - simplifyGeometry() has been removed and simplify() must be used instead . QgsGradientColorRampDialog {#qgis_api_break_3_0_QgsGradientColorRampDialog} --------- - - The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited and the new ramp can be retrieved after executing the dialog by calling ramp(). - Some internal methods which were previously public or protected were made private. @@ -881,7 +827,6 @@ and the new ramp can be retrieved after executing the dialog by calling ramp(). QgsGraduatedSymbolRenderer {#qgis_api_break_3_0_QgsGraduatedSymbolRenderer} -------------------------- - - getDataValues() has been removed - use QgsVectorLayer::getDoubleValues() instead @@ -891,11 +836,9 @@ QgsGraduatedSymbolRenderer {#qgis_api_break_3_0_QgsGraduatedSymbolRendere - sizeScaleFieldChanged() and scaleMethodChanged() were removed. These settings are no longer exposed in the widget's GUI. - QgsGraphBuilderInterface {#qgis_api_break_3_0_QgsGraphBuilderInterface} ------------------------ - - destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ plugins calling this method will need to be updated. @@ -903,7 +846,6 @@ plugins calling this method will need to be updated. QgsEditorWidgetRegistry {#qgis_api_break_3_0_QgsEditorWidgetRegistry} ----------------------- - - The signature of isFieldSupported() has been changed to return an unsigned (how good it supports the given field) and to const-correct it. @@ -911,21 +853,18 @@ and to const-correct it. QgsGroupWMSDataDialog {#qgis_api_break_3_0_QgsGroupWMSDataDialog} --------------------- - - QgsGroupWMSDataDialo has been renamed to QgsGroupWmsDataDialog QgsHighlight {#qgis_api_break_3_0_QgsHighlight} ------------ - - The QgsHighlight constructor now takes a geometry reference, not a pointer. QgsJSONExporter {#qgis_api_break_3_0_QgsJSONExporter} --------------- - - sourceCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ plugins calling this method will need to be updated. @@ -933,7 +872,6 @@ plugins calling this method will need to be updated. QgsLabelingEngineInterface {#qgis_api_break_3_0_QgsLabelingEngineInterface} -------------------------- - - init(QgsMapRenderer*) has been removed. Use init(const QgsMapSettings&) instead. - &layer() was removed. use QgsPalLayerSettings::fromLayer() instead. - addDiagramLayer() was removed. Use prepareDiagramLayer() instead. @@ -944,21 +882,18 @@ QgsLabelingEngineInterface {#qgis_api_break_3_0_QgsLabelingEngineInterfac QgsLayerPropertiesWidget {#qgis_api_break_3_0_QgsLayerPropertiesWidget} ------------------------ - - expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() QgsLayerTreeGroup {#qgis_api_break_3_0_QgsLayerTreeGroup} ----------------- - - readChildrenFromXML() has been renamed to readChildrenFromXml() QgsLayerTreeModel {#qgis_api_break_3_0_QgsLayerTreeMode} ----------------- - - The ShowSymbology flag was removed. Use ShowLegend instead. - The AllowSymbologyChangeState flag was removed. Use AllowLegendChangeState instead. - legendFilterByMap() was renamed to legendFilterMapSettings() @@ -969,11 +904,9 @@ QgsLayerTreeModel {#qgis_api_break_3_0_QgsLayerTreeMode} - autoCollapseSymbologyNodes() was removed. Use autoCollapseLegendNodes() instead. - QgsLayerTreeNode {#qgis_api_break_3_0_QgsLayerTreeNode} ---------------- - - readCommonXML() has been renamed to readCommonXml() - writeCommonXML() has been renamed to writeCommonXml() @@ -981,7 +914,6 @@ QgsLayerTreeNode {#qgis_api_break_3_0_QgsLayerTreeNode} QgsLimitedRandomColorRampDialog {#qgis_api_break_3_0_QgsLimitedRandomRampDialog} ------------------------------- - - The dialog no longer edits a color ramp in place. Instead, a copy of the ramp is edited and the new ramp can be retrieved after executing the dialog by calling ramp(). - Some internal methods which were previously public or protected were made private. @@ -990,7 +922,6 @@ and the new ramp can be retrieved after executing the dialog by calling ramp(). QgsMapCanvas {#qgis_api_break_3_0_QgsMapCanvas} ------------ - - rotationEnabled() and enableRotation() have been removed, since map rotation is now always supported - The "name" parameter has been removed from constructor. Use QObject::setObjectName() to set canvas name if necessary. - map() has been removed because QgsMapCanvasMap is not available in API anymore. @@ -1008,14 +939,12 @@ QgsMapCanvas {#qgis_api_break_3_0_QgsMapCanvas} QgsMapCanvasItem {#qgis_api_break_3_0_QgsMapCanvasItem} ---------------- - - setPanningOffset() was removed. QgsMapLayer {#qgis_api_break_3_0_QgsMapLayer} ----------- - - crs() now returns a QgsCoordinateReferenceSystem object, not a reference. This change has no effect for PyQGIS code. - createMapRenderer() has been made pure virtual. - draw() has been removed. Use createMapRenderer() method for rendering of layers. @@ -1052,7 +981,6 @@ QgsMapOverviewCanvas {#qgis_api_break_3_0_QgsMapOverviewCanvas} QgsMapRenderer {#qgis_api_break_3_0_QgsMapRenderer} -------------- - - transformation() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be returned instead of a null pointer if no transformation is required. - destinationSrsChanged() was renamed to destinationCrsChanged() @@ -1062,7 +990,6 @@ be returned instead of a null pointer if no transformation is required. QgsMapRendererJob {#qgis_api_break_3_0_QgsMapRendererJob} ----------------- - - reprojectToLayerExtent() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. - prepareJobs() and drawLabeling() (neither available in PyQGIS) do not take QgsPalLabeling parameter anymore. All drawing of labels is done by QgsLabelingEngineV2. @@ -1072,7 +999,6 @@ be used instead of a null pointer if no transformation is required. QgsMapTool {#qgis_api_break_3_0_QgsMapTool} ---------- - - renderComplete() was removed. Map tools must not directly depend on rendering progress. - isTransient() and isEditTool() were removed. Use flags() instead. @@ -1080,19 +1006,16 @@ QgsMapTool {#qgis_api_break_3_0_QgsMapTool} QgsMapToolCapture {#qgis_api_break_3_0_QgsMapToolCapture} ----------------- - - The nextPoint() method taking a QgsPoint was removed. Use the version taking a QgsPointV2 instead. QgsMapToPixel {#qgis_api_break_3_0_QgsMapToPixel} ------------- - - The constructor now uses the map center x and y, and requires both height and width in pixels and a rotation value - setYMaximum(), setYMinimum(), setXMinimum() were removed. Use setParameters() instead - QgsMapToPixelGeometrySimplifier {#qgis_api_break_3_0_QgsMapToPixelGeometrySimplifier} ------------------------------- @@ -1105,7 +1028,6 @@ The whole class has been refactored to stop using WKB and to use QgsAbstractGeom QgsMapSettings {#qgis_api_break_3_0_QgsMapSettings} -------------- - - layerTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be returned instead of a null pointer if no transformation is required. - destinationCrs() now returns a copy instead of a reference to the CRS. This has no effect on PyQGIS code, but c++ @@ -1115,21 +1037,18 @@ plugins calling this method will need to be updated. QgsMarkerSymbolLayer {#qgis_api_break_3_0_QgsMarkerSymbolLayer} -------------------- - - bounds() is now pure virtual and must be implemented in all subclasses. QgsMimeDataUtils {#qgis_api_break_3_0_QgsMimeDataUtils} ---------------- - - Constructor taking QgsLayerItem argument has been removed. Use QgsDataItem::mimeUri() instead. QgsNetworkAccessManager {#qgis_api_break_3_0_QgsNetworkAccessManager} ----------------------- - - sendGet() was removed. Use get() directly. - deleteReply() was removed. Use abort() and deleteLayer() on the reply directly. - requestSent signal was removed. This is no longer emitted. @@ -1138,21 +1057,18 @@ QgsNetworkAccessManager {#qgis_api_break_3_0_QgsNetworkAccessManager} QgsOSMElement {#qgis_api_break_3_0_QgsOSMElement} ------------- - - elemID() has been renamed to elemId() QgsOwsConnection {#qgis_api_break_3_0_QgsOwsConnection} ---------------- - - connectionInfo() was removed. QgsOWSSourceSelect {#qgis_api_break_3_0_QgsOWSSourceSelect} ------------------ - - selectedLayersCRSs() has been renamed selectedLayersCrses() - populateCRS() has been renamed to populateCrs() - clearCRS() has been renamed to clearCrs() @@ -1164,14 +1080,12 @@ QgsOWSSourceSelect {#qgis_api_break_3_0_QgsOWSSourceSelect} QgsOWSConnection {#qgis_api_break_3_0_QgsOWSConnection} ---------------- - - QgsOWSConnection has been renamed QgsOwsConnection QgsNumericSortTreeWidgetItem {#qgis_api_break_3_0_QgsNumericSortTreeWidgetItem} ---------------------------- - - QgsNumericSortTreeWidgetItem has been removed and replaced with QgsTreeWidgetItem, which has improved sort capabilities including the ability to set custom sort values for items and for forcing certain items to always sort on top. @@ -1180,7 +1094,6 @@ and for forcing certain items to always sort on top. QgsPalLabeling {#qgis_api_break_3_0_QgsPalLabeling} -------------- - - init(QgsMapRenderer*) has been removed. Use init(const QgsMapSettings&) instead. - prepareGeometry and geometryRequiresPreparation now take geometry references, not pointers. - layer() was removed. If direct access to QgsPalLayerSettings is necessary, use QgsPalLayerSettings::fromLayer() @@ -1194,7 +1107,6 @@ QgsPalLabeling {#qgis_api_break_3_0_QgsPalLabeling} QgsPalLayerSettings {#qgis_api_break_3_0_QgsPalLayerSettings} ------------------- - - ct is now a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be used instead of a null pointer if no transformation is required. - prepareGeometry() and geometryRequiresPreparation() now take a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. @@ -1203,7 +1115,6 @@ be used instead of a null pointer if no transformation is required. QgsPanelWidgetStack {#qgis_api_break_3_0_QgsPanelWidgetStack} ------------------- - - addMainPanel() has been renamed to setMainPanel() - mainWidget() has been renamed to mainPanel() - takeMainWidget() has been renamed to takeMainPanel() @@ -1212,21 +1123,18 @@ QgsPanelWidgetStack {#qgis_api_break_3_0_QgsPanelWidgetStack} QgsPluginLayer {#qgis_api_break_3_0_QgsPluginLayer} -------------- - - createMapRenderer(): default implementation (which called plugin's draw() method) has been removed. Plugin layers must implement createMapRenderer(). QgsPointDisplacementRenderer {#qgis_api_break_3_0_QgsPointDisplacementRenderer} ---------------------------- - - The deprecated method setDisplacementGroups() has been removed. This method has had no effect since QGIS 2.4 QgsPointLocator {#qgis_api_break_3_0_QgsPointLocator} --------------- - - The constructor now takes a reference rather than a pointer to a CRS. This has no effect on PyQGIS code, but c++ plugins calling this method will need to be updated. - The destCRS parameter in the constructor has been renamed to destinationCrs. @@ -1238,7 +1146,6 @@ plugins calling this method will need to be updated. QgsProject {#qgis_api_break_3_0_QgsProject} ---------- - - visibilityPresetCollection() has been renamed to mapThemeCollection() - title( const QString & title ) was removed. Use setTitle() instead. - dirty( bool b ) was removed. Use setDirty() instead. @@ -1248,14 +1155,12 @@ QgsProject {#qgis_api_break_3_0_QgsProject} QgsRasterCalcNode {#qgis_api_break_3_0_QgsRasterCalcNode} ----------------- - - QgsRasterCalcNode::calculate has been removed, use method with QgsRasterBlocks instead. QgsRasterDataProvider {#qgis_api_break_3_0_QgsRasterDataProvider} --------------------- - - srcDataType() has been renamed to sourceDataType() - srcHasNoDataValue() has been renamed to sourceHasNoDataValue() - useSrcNoDataValue() has been renamed to useSourceNoDataValue() @@ -1266,7 +1171,6 @@ QgsRasterDataProvider {#qgis_api_break_3_0_QgsRasterDataProvider} QgsRasterInterface {#qgis_api_break_3_0_QgsRasterInterface} ------------------ - - srcDataType() has been renamed to sourceDataType() - srcInput() has been renamed to sourceInput() - block() has new "feedback" argument. @@ -1275,7 +1179,6 @@ QgsRasterInterface {#qgis_api_break_3_0_QgsRasterInterface} QgsRasterLayer {#qgis_api_break_3_0_QgsRasterLayer} -------------- - - setDrawingStyle() was removed. Use setRendererForDrawingStyle() or setRenderer() instead. - previewAsPixmap() was removed. Use previewAsImage() instead. - updateProgress() had no effect and was removed. @@ -1284,21 +1187,18 @@ QgsRasterLayer {#qgis_api_break_3_0_QgsRasterLayer} QgsRasterProjector {#qgis_api_break_3_0_QgsRasterProjector} ------------------ - - extentSize() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. QgsRelation {#qgis_api_break_3_0_QgsRelation} ----------- - - createFromXML() has been renamed to createFromXml() QgsRenderChecker {#qgis_api_break_3_0_QgsRenderChecker} ---------------- - - setMapRenderer() has been removed. Use setMapSettings() instead. - excludeAttributesWMS() and setExcludeAttributesWMS() have been renamed to excludeAttributesWms() and setExcludeAttributesWms() @@ -1313,7 +1213,6 @@ setExcludeAttributesWfs() QgsRenderContext {#qgis_api_break_3_0_QgsRenderContext} ---------------- - - coordinateTransform() now returns a QgsCoordinateTransform object, not a pointer. An invalid QgsCoordinateTransform will be returned instead of a null pointer if no transformation is required. - setCoordinateTransform() now takes a QgsCoordinateTransform reference, not a pointer. An invalid QgsCoordinateTransform should be used instead of a null pointer if no transformation is required. @@ -1322,23 +1221,18 @@ be returned instead of a null pointer if no transformation is required. QgsRendererWidget {#qgis_api_break_3_0_QgsRendererWidget} ----------------- - - expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() QgsRendererRulePropsWidget {#qgis_api_break_3_0_QgsRendererRulePropsWidget} -------------------------- - - expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() - - QgsRubberBand {#qgis_api_break_3_0_QgsRubberBand} ------------- - - setToGeometry() and addGeometry() now take geometry references, not pointers. - QgsRubberBand( QgsMapCanvas* mapCanvas, bool isPolygon ) constructor and reset( bool isPolygon) have been removed, use constructor and function with Qgis::GeometryType as argument instead. @@ -1346,7 +1240,6 @@ QgsRubberBand {#qgis_api_break_3_0_QgsRubberBand} QgsRuleBasedRenderer {#qgis_api_break_3_0_QgsRuleBasedRenderer} -------------------- - - QgsRuleBasedRenderer.Rule checkState() and setCheckState() were removed. Use active() and setActive() instead. - QgsRuleBasedRenderer.Rule updateElseRules() was removed. - startRender( QgsRenderContext& context, const QgsFields& fields ) was removed. Use startRender( QgsRenderContext& context, const QgsFields& fields, QString& filter ) instead. @@ -1355,14 +1248,12 @@ QgsRuleBasedRenderer {#qgis_api_break_3_0_QgsRuleBasedRenderer} QgsRuleBasedRendererWidget {#qgis_api_break_3_0_QgsRuleBasedRendererWidget} -------------------------- - - refineRuleCategoriesGui() and refineRuleRangesGui() no longer take a QModelIndexList argument. QgsSimpleMarkerSymbolLayer {#qgis_api_break_3_0_QgsSimpleMarkerSymbolLayer} -------------------------- - - The constructor variant with a string for the shape name has been removed. Use the variant which accepts a QgsSimpleMarkerSymbolLayerBase.Shape enum instead. - name() and setName() have been removed. Use shape() and setShape() instead. - prepareShape() and preparePath() were removed. Calling these methods manually should no longer be required. @@ -1371,11 +1262,9 @@ QgsSimpleMarkerSymbolLayer {#qgis_api_break_3_0_QgsSimpleMarkerSymbolLaye QgsSimpleMarkerSymbolLayerWidget {#qgis_api_break_3_0_QgsSimpleMarkerSymbolLayerWidget} -------------------------------- - - setName() was removed. - QgsSingleSymbolRendererWidget {#qgis_api_break_3_0_QgsSingleSymbolRendererWidget} ----------------------------- @@ -1385,7 +1274,6 @@ QgsSingleSymbolRendererWidget {#qgis_api_break_3_0_QgsSingleSymbolRendere QgsSnapper {#qgis_api_break_3_0_QgsSnapper} ---------- - - Constructor variant with QgsMapRenderer has been removed. Use the variant with QgsMapSettings. - Signature for snapPoint() has changed. @@ -1393,7 +1281,6 @@ QgsSnapper {#qgis_api_break_3_0_QgsSnapper} QgsSublayersDialog {#qgis_api_break_3_0_QgsSublayersDialog} ------------------ - - populateLayerTable() now takes a list of QgsSublayersDialog.LayerDefinition values - selectionNames() and selectionIndexes() were removed. Use selection(). @@ -1401,14 +1288,12 @@ QgsSublayersDialog {#qgis_api_break_3_0_QgsSublayersDialog} QgsSvgCache {#qgis_api_break_3_0_QgsSvgCache} ----------- - - containsParamsV2() was removed. Use containsParamsV3() instead. QgsSymbol (renamed from QgsSymbolV2) {#qgis_api_break_3_0_QgsSymbol} ------------------------------------ - - The OutputUnit enum, including QgsSymbol::MM, QgsSymbol::MapUnit, QgsSymbol::Mixed, QgsSymbol::Pixel and QgsSymbol::Percentage has been moved to QgsUnitTypes and renamed to RenderUnit. QgsSymbol::OutputUnitList was renamed to QgsUnitTypes::RenderUnitList. All methods which previously accepted QgsSymbol::OutputUnit parameters or QgsSymbol::OutputUnitList parameters now take QgsUnitTypes::RenderUnit or QgsUnitTypes::RenderUnitList parameters respectively. @@ -1424,7 +1309,6 @@ than an integer value QgsSymbolLayer (renamed from QgsSymbolLayerV2) {#qgis_api_break_3_0_QgsSymbolLayer} ---------------------------------------------- - - The deprecated prepareExpressions( const QgsFields* fields, double scale = -1.0 ) method has been removed. Use the variant which takes QgsSymbolRenderContext instead. - The deprecated methods dataDefinedProperty( const QString& property ) and dataDefinedPropertyString() were removed. Use getDataDefinedProperty() instead. @@ -1436,15 +1320,12 @@ the variant which takes QgsSymbolRenderContext instead. QgsSymbolLayerWidget {#qgis_api_break_3_0_QgsSymbolLayerWidget} -------------------- - - expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() - QgsSymbolRenderContext (renamed from QgsSymbolV2RenderContext) {#qgis_api_break_3_0_QgsSymbolRenderContext} -------------------------------------------------------------- - - The constructor now accepts a QgsFields reference, not a pointer. - The constructor, setRenderHints() and renderHints() now accept and return a QgsSymbol::RenderHints flag rather than an integer value @@ -1454,45 +1335,32 @@ than an integer value QgsSymbolLayerUtils (renamed from QgsSymbolLayerUtilsV2) {#qgis_api_break_3_0_QgsSymbolLayerUtils} -------------------------------------------------------- - - encodeOutputUnit() and decodeOutputUnit() were removed. QgsUnitTypes::encodeUnit() and QgsUnitTypes::decodeRenderUnit() should be used instead. - The signatures for wellKnownMarkerToSld() and wellKnownMarkerFromSld() were changed. -QgsSymbolSelectorDialog {#qgis_api_break_3_0_QgsSymbolSelectorDialog} ------------------------ - - -- saveSymbol() was removed. - - QgsSymbolSelectorWidget {#qgis_api_break_3_0_QgsSymbolSelectorWidget} ----------------------- - - saveSymbol() was removed. QgsSymbolSelectorDialog {#qgis_api_break_3_0_QgsSymbolSelectorDialog} ----------------------- - +- saveSymbol() was removed. - expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() QgsSymbolsListWidget {#qgis_api_break_3_0_QgsSymbolsListWidget} -------------------- - - expressionContext(), setExpressionContext(), setMapCanvas() and mapCanvas() have been removed in favor of setContext()/context() - - QgsTolerance {#qgis_api_break_3_0_QgsTolerance} ------------ - - vertexSearchRadius(), defaultTolerance(), toleranceInMapUnits() do not have variant with QgsMapRenderer anymore. Use the variants with QgsMapSettings. - The MapUnits UnitType was removed. Use LayerUnits or ProjectUnits instead. @@ -1500,7 +1368,6 @@ QgsTolerance {#qgis_api_break_3_0_QgsTolerance} QgsTreeWidgetItem {#qgis_api_break_3_0_QgsTreeWidgetItem} ----------------- - - QgsTreeWidgetItem is no longer a QObject and does not emit the itemEdited signal. Instead, use QgsTreeWidgetItemObject which is an upgraded version of the original QgsTreeWidgetItem @@ -1508,7 +1375,6 @@ use QgsTreeWidgetItemObject which is an upgraded version of the original QgsTree QgsUnitTypes {#qgis_api_break_3_0_QgsUnitTypes} ------------ - - All distance enumeration values were renamed to have a "Distance" prefix, including Meters (to DistanceMeters), Kilometers (to DistanceKilometers), Feet (to DistanceFeet), NauticalMiles (to DistanceNauticalMiles), Yards (to DistanceYards), Miles (to DistanceMiles), @@ -1526,14 +1392,12 @@ SecondsOfArc (to AngleSecondsOfArc), Turn (to AngleTurn) and UnknownAngleUnit to QgsVector {#qgis_api_break_3_0_QgsVector} --------- - - normal() was removed. Use normalized() instead. QgsVectorDataProvider {#qgis_api_break_3_0_QgsVectorDataProvider} --------------------- - - QgsVectorDataProvider::fields() now returns a copy, rather than a const reference. Since QgsFields objects are implicitly shared, returning a copy helps simplify and make code more robust. This change only affects third party c++ providers, and does not affect PyQGIS scripts. @@ -1548,7 +1412,6 @@ capabilities have been removed, as they were unused and had no effect. QgsVectorLayer {#qgis_api_break_3_0_QgsVectorLayer} -------------- - - excludeAttributesWMS() and setExcludeAttributesWMS() have been renamed to excludeAttributesWms() and setExcludeAttributesWms() - excludeAttributesWFS() and setExcludeAttributesWFS() have been renamed to excludeAttributesWfs() and @@ -1587,7 +1450,6 @@ displayExpression instead. For the map tip use mapTipTemplate() instead. QgsVectorLayerEditBuffer {#qgis_api_break_3_0_QgsVectorLayerEditBuffer} ------------------------ - - changeGeometry() now accepts a geometry reference, not a pointer. - The geometryChanged() signal now uses a const QgsGeometry reference. - The addedFeatures(), changedAttributeValues(), deletedAttributeIds(), addedAttributes(), changedGeometries() @@ -1598,14 +1460,12 @@ plugins calling these methods will need to be updated. QgsVectorLayerEditUtils {#qgis_api_break_3_0_QgsVectorLayerEditUtils} ----------------------- - - addTopologicalPoints() now accepts a geometry reference, not a pointer. QgsVectorLayerImport {#qgis_api_break_3_0_QgsVectorLayerImport} -------------------- - - QgsVectorLayerImport now takes references instead of pointers to QgsCoordinateReferenceSystem objects. Since QgsCoordinateReferenceSystem is now implicitly shared, using references to QgsCoordinateReferenceSystem rather than pointers makes for more robust, safer code. Use an invalid (default constructed) QgsCoordinateReferenceSystem @@ -1615,14 +1475,12 @@ in code which previously passed a null pointer to QgsVectorLayerImport. QgsVectorLayerUndoCommand {#qgis_api_break_3_0_QgsVectorLayerUndoCommand} ------------------------- - - QgsVectorLayerUndoCommandChangeGeometry constructor now accepts a geometry reference, not a pointer. QgsVisibilityPresetCollection {#qgis_api_break_3_0_QgsVisibilityPresetCollection} ----------------------------- - - Has been renamed to QgsMapThemeCollection - The nested class PresetRecord has been renamed to MapThemeRecord - Various member functions have been renamed from *preset* to *mapTheme* @@ -1631,7 +1489,6 @@ QgsVisibilityPresetCollection {#qgis_api_break_3_0_QgsVisibilityPresetCol QgsVectorFileWriter {#qgis_api_break_3_0_QgsVectorFileWriter} ------------------- - - QgsVectorFileWriter now takes references instead of pointers to QgsCoordinateReferenceSystem objects. Since QgsCoordinateReferenceSystem is now implicitly shared, using references to QgsCoordinateReferenceSystem rather than pointers makes for more robust, safer code. Use an invalid (default constructed) QgsCoordinateReferenceSystem @@ -1642,14 +1499,12 @@ in code which previously passed a null pointer to QgsVectorFileWriter. QgsWMSLegendNode {#qgis_api_break_3_0_QgsWMSLegendNode} ---------------- - - QgsWMSLegendNode has been renamed to QgsWmsLegendNode QgsRenderer {#qgis_api_break_3_0_QgsRenderer} ----------- - - New virtual method bool writeSld( QDomNode& node, QDomDocument& doc, QString& errorMessage, QgsStringMap props = QgsStringMap() ) accepts an optional property map passing down layer level properties to the SLD encoders. If scale based visibility is enabled, it will contain the scaleMinDenom and scaleMaxDenom properties. @@ -1675,13 +1530,14 @@ The client code doing refresh() in order to later save map image should be updat method instead of using QgsPluginLayer::draw(). + + QGIS 2.6 {#qgis_api_break_2_6} ======== Legend Refactoring {#qgis_api_break_legend_refactoring} ------------------ - - QgsComposerLegend::model() - not being used anymore. The model was replaced by one based on QgsLayerTreeModel class and is available in QgsComposerLegend::modelV2() From 7a05a7a8c4b9184f6cad7d155b6714076b1dccd9 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 28 Oct 2016 12:30:39 +0200 Subject: [PATCH 524/897] Fix caching of aggregate values with @parent And add a test for referencedVariables --- src/core/qgsexpression.cpp | 18 +++++++++++++++--- tests/src/core/testqgsexpression.cpp | 11 +++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index b2cd0cfdfb25..2a15f91c3c2f 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -682,8 +682,8 @@ static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionCon { QString cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter ); - QgsExpression subExp( subExpression ); - if ( subExp.referencedVariables().contains( "parent" ) || subExp.referencedVariables().contains( QString() ) ) + QgsExpression filterExp( parameters.filter ); + if ( filterExp.referencedVariables().contains( "parent" ) || filterExp.referencedVariables().contains( QString() ) ) { cacheKey += ':' + qHash( context->feature() ); } @@ -5106,7 +5106,19 @@ QSet QgsExpression::NodeFunction::referencedVariables() const return QSet() << QString(); } else - return QSet(); + { + QSet functionVariables = QSet(); + + if ( !mArgs ) + return functionVariables; + + Q_FOREACH ( Node* n, mArgs->list() ) + { + functionVariables.unite( n->referencedVariables() ); + } + + return functionVariables; + } } bool QgsExpression::NodeFunction::needsGeometry() const diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 8b5fe2675369..2ca376119442 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1571,6 +1571,17 @@ class TestQgsExpression: public QObject QCOMPARE( refColsSet, expectedCols ); } + void referenced_variables() + { + QSet expectedVars; + expectedVars << QStringLiteral( "foo" ) << QStringLiteral( "bar" ) << QStringLiteral( "ppp" ) << QStringLiteral( "qqq" ) << QStringLiteral( "rrr" ); + QgsExpression exp( QStringLiteral( "CASE WHEN intersects(@bar, $geometry) THEN @ppp ELSE @qqq * @rrr END + @foo IN (1, 2, 3)" ) ); + QCOMPARE( exp.hasParserError(), false ); + QSet refVar = exp.referencedVariables(); + + QCOMPARE( refVar, expectedVars ); + } + void referenced_columns_all_attributes() { QgsExpression exp( QStringLiteral( "attribute($currentfeature,'test')" ) ); From 54f312fa7f5b1ff1de2a055bd870817b54cd62bc Mon Sep 17 00:00:00 2001 From: Richard Duivenvoorde Date: Fri, 28 Oct 2016 16:57:42 +0200 Subject: [PATCH 525/897] Temporarily hardcode plugins version in url ?qgis=3.0 If QGIS 3.0 is actually released this line should be removed. --- python/pyplugin_installer/installer_data.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python/pyplugin_installer/installer_data.py b/python/pyplugin_installer/installer_data.py index af125dcb36a6..8d0b46f29358 100644 --- a/python/pyplugin_installer/installer_data.py +++ b/python/pyplugin_installer/installer_data.py @@ -236,7 +236,10 @@ def allUnavailable(self): def urlParams(self): """ return GET parameters to be added to every request """ v = str(Qgis.QGIS_VERSION_INT) - return "?qgis=%d.%d" % (int(v[0]), int(v[1:3])) + # TODO: make this proper again after 3.0 release, by uncommenting + # the line below and removing the other return line: + #return "?qgis=%d.%d" % (int(v[0]), int(v[1:3])) + return "?qgis=3.0" # ----------------------------------------- # def setRepositoryData(self, reposName, key, value): From 74e64645e410dff89685f029ea0169eb825c7689 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 29 Oct 2016 08:05:26 +1000 Subject: [PATCH 526/897] [FEATURE][processing] New extract by expression algorithm Filters an input layer by expression --- python/plugins/processing/algs/help/qgis.yaml | 11 ++- .../algs/qgis/ExtractByExpression.py | 67 +++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 3 +- .../testdata/expected/extract_expression.gfs | 32 +++++++++ .../testdata/expected/extract_expression.gml | 29 ++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 14 +++- 6 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/ExtractByExpression.py create mode 100644 python/plugins/processing/tests/testdata/expected/extract_expression.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_expression.gml diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index bc1d4b3a2d1b..b5c0c20090f3 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -159,10 +159,15 @@ qgis:exportaddgeometrycolumns: > Depending on the geometry type of the vector layer, the attributes added to the table will be different. qgis:extractbyattribute: > - This algorithms creates new vector layer that only contain certain features from an input layer. The criteria for adding features to the resulting layer is defined based on the values of an attribute from the input layer. + This algorithms creates a new vector layer that only contains matching features from an input layer. The criteria for adding features to the resulting layer is defined based on the values of an attribute from the input layer. + +qgis:extractbyexpression: > + This algorithms creates a new vector layer that only contains matching features from an input layer. The criteria for adding features to the resulting layer is based on a QGIS expression. + + For more information about expressions see the user manual qgis:extractbylocation: > - This algorithms creates new vector layer that only contain certain features from an input layer. The criteria for adding features to the resulting layer is defined based on the spatial relationship between each feature and the features in an additional layer. + This algorithms creates a new vector layer that only contains matching features from an input layer. The criteria for adding features to the resulting layer is defined based on the spatial relationship between each feature and the features in an additional layer. qgis:extractnodes: > This algorithm takes a line or polygon layer and generates a point layer with points representing the nodes in the input lines or polygons. The attributes associated to each point are the same ones associated to the line or polygon that the point belongs to. @@ -419,7 +424,7 @@ qgis:selectbyattributesum: qgis:selectbyexpression: > This algorithms creates a selection in a vector layer. The criteria for selecting features is based on a QGIS expression. - For more information about expressions see theuser manual + For more information about expressions see the user manual qgis:selectbylocation: > diff --git a/python/plugins/processing/algs/qgis/ExtractByExpression.py b/python/plugins/processing/algs/qgis/ExtractByExpression.py new file mode 100644 index 000000000000..4779758a3ae0 --- /dev/null +++ b/python/plugins/processing/algs/qgis/ExtractByExpression.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ExtractByExpression.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +import processing +from qgis.core import QgsExpression, QgsVectorLayer, QgsFeatureRequest +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.parameters import ParameterVector +from processing.core.outputs import OutputVector +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterString +from processing.tools import dataobjects + + +class ExtractByExpression(GeoAlgorithm): + + INPUT = 'INPUT' + EXPRESSION = 'EXPRESSION' + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Extract by expression') + self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') + + self.addParameter(ParameterVector(self.INPUT, + self.tr('Input Layer'))) + self.addParameter(ParameterString(self.EXPRESSION, + self.tr("Expression"))) + self.addOutput(OutputVector(self.OUTPUT, self.tr('Extracted (expression)'))) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) + expression_string = self.getParameterValue(self.EXPRESSION) + writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.fields(), layer.wkbType(), layer.crs()) + + expression = QgsExpression(expression_string) + if not expression.hasParserError(): + req = QgsFeatureRequest().setFilterExpression(expression_string) + else: + raise GeoAlgorithmExecutionException(expression.parserErrorString()) + + for f in layer.getFeatures(req): + writer.addFeature(f) + + del writer diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 9cb4a1cab645..bf3296b2b923 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -56,6 +56,7 @@ from .RandomExtract import RandomExtract from .RandomExtractWithinSubsets import RandomExtractWithinSubsets from .ExtractByLocation import ExtractByLocation +from .ExtractByExpression import ExtractByExpression from .PointsInPolygon import PointsInPolygon from .PointsInPolygonUnique import PointsInPolygonUnique from .PointsInPolygonWeighted import PointsInPolygonWeighted @@ -231,7 +232,7 @@ def __init__(self): ReliefAuto(), ZonalStatisticsQgis(), IdwInterpolationZValue(), IdwInterpolationAttribute(), TinInterpolationZValue(), TinInterpolationAttribute(), - RemoveNullGeometry() + RemoveNullGeometry(), ExtractByExpression() ] if hasMatplotlib: diff --git a/python/plugins/processing/tests/testdata/expected/extract_expression.gfs b/python/plugins/processing/tests/testdata/expected/extract_expression.gfs new file mode 100644 index 000000000000..a62526d790e5 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_expression.gfs @@ -0,0 +1,32 @@ + + + extract_expression + extract_expression + + 3 + EPSG:4326 + + 2 + 4.00000 + 10.00000 + -3.00000 + 5.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Integer + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_expression.gml b/python/plugins/processing/tests/testdata/expected/extract_expression.gml new file mode 100644 index 000000000000..a652e20671ec --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_expression.gml @@ -0,0 +1,29 @@ + + + + + 4-3 + 105 + + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + ASDF + 0 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index ea2bc5dd3ca9..01a8e8b7757c 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1212,4 +1212,16 @@ tests: results: OUTPUT_LAYER: name: expected/remove_null_polys.gml - type: vector \ No newline at end of file + type: vector + + - algorithm: qgis:extractbyexpression + name: Extract by Expression + params: + EXPRESSION: left( "Name",1)='A' + INPUT: + name: polys.gml + type: vector + results: + OUTPUT: + name: expected/extract_expression.gml + type: vector From 121f48d654eb6dc201b0840ad3f903eb3665b923 Mon Sep 17 00:00:00 2001 From: nirvn Date: Sat, 22 Oct 2016 11:28:03 +0700 Subject: [PATCH 527/897] [processing] add import into spatialite algorithm --- python/plugins/processing/algs/help/qgis.yaml | 3 + .../processing/algs/qgis/ImportIntoPostGIS.py | 8 +- .../algs/qgis/ImportIntoSpatialite.py | 137 ++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 3 +- python/plugins/processing/tools/spatialite.py | 11 +- 5 files changed, 157 insertions(+), 5 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/ImportIntoSpatialite.py diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index bc1d4b3a2d1b..117343975daa 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -198,6 +198,9 @@ qgis:hublines: qgis:hypsometriccurves: > This algorithm computes hypsometric curves for an input Digital Elevation Model. Curves are produced as table files in an output folder specified by the user. +qgis:importintospatialite: > + This algorithms imports a vector layer into a Spatialite database, creating a new table. + qgis:importintopostgis: > This algorithms imports a vector layer into a PostGIS database, creating a new table. diff --git a/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py b/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py index ae6240bd8b0c..062211cc22f5 100644 --- a/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py +++ b/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py @@ -65,7 +65,7 @@ def defineCharacteristics(self): self.addParameter(ParameterString(self.SCHEMA, self.tr('Schema (schema name)'), 'public')) self.addParameter(ParameterString(self.TABLENAME, - self.tr('Table to import to (leave blank to use layer name)'))) + self.tr('Table to import to (leave blank to use layer name)'), optional=True)) self.addParameter(ParameterTableField(self.PRIMARY_KEY, self.tr('Primary key field'), self.INPUT, optional=True)) self.addParameter(ParameterString(self.GEOMETRY_COLUMN, @@ -100,8 +100,10 @@ def processAlgorithm(self, progress): layerUri = self.getParameterValue(self.INPUT) layer = dataobjects.getObjectFromUri(layerUri) - table = self.getParameterValue(self.TABLENAME).strip() - if table == '': + table = self.getParameterValue(self.TABLENAME) + if table: + table.strip() + if not table or table == '': table = layer.name() table = "_".join(table.split(".")[:-1]) table = table.replace(' ', '').lower()[0:62] diff --git a/python/plugins/processing/algs/qgis/ImportIntoSpatialite.py b/python/plugins/processing/algs/qgis/ImportIntoSpatialite.py new file mode 100644 index 000000000000..47bfcfd99f2a --- /dev/null +++ b/python/plugins/processing/algs/qgis/ImportIntoSpatialite.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ImportIntoSpatialite.py + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Mathieu Pellerin + Email : nirvn dot asia at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Mathieu Pellerin' +__date__ = 'October 2016' +__copyright__ = '(C) 2012, Mathieu Pellerin' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.PyQt.QtCore import QSettings +from qgis.core import QgsDataSourceUri, QgsVectorLayerImport + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.parameters import ParameterBoolean +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterSelection +from processing.core.parameters import ParameterTableField +from processing.tools import dataobjects, spatialite + + +class ImportIntoSpatialite(GeoAlgorithm): + + DATABASE = 'DATABASE' + TABLENAME = 'TABLENAME' + INPUT = 'INPUT' + OVERWRITE = 'OVERWRITE' + CREATEINDEX = 'CREATEINDEX' + GEOMETRY_COLUMN = 'GEOMETRY_COLUMN' + LOWERCASE_NAMES = 'LOWERCASE_NAMES' + DROP_STRING_LENGTH = 'DROP_STRING_LENGTH' + FORCE_SINGLEPART = 'FORCE_SINGLEPART' + PRIMARY_KEY = 'PRIMARY_KEY' + ENCODING = 'ENCODING' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Import into Spatialite') + self.group, self.i18n_group = self.trAlgorithm('Database') + self.addParameter(ParameterVector(self.INPUT, self.tr('Layer to import'))) + self.addParameter(ParameterVector(self.DATABASE, self.tr('File database'), False, False)) + self.addParameter(ParameterString(self.TABLENAME, self.tr('Table to import to (leave blank to use layer name)'), optional=True)) + self.addParameter(ParameterTableField(self.PRIMARY_KEY, self.tr('Primary key field'), self.INPUT, optional=True)) + self.addParameter(ParameterString(self.GEOMETRY_COLUMN, self.tr('Geometry column'), 'geom')) + self.addParameter(ParameterString(self.ENCODING, self.tr('Encoding'), 'UTF-8', optional=True)) + self.addParameter(ParameterBoolean(self.OVERWRITE, self.tr('Overwrite'), True)) + self.addParameter(ParameterBoolean(self.CREATEINDEX, self.tr('Create spatial index'), True)) + self.addParameter(ParameterBoolean(self.LOWERCASE_NAMES, self.tr('Convert field names to lowercase'), True)) + self.addParameter(ParameterBoolean(self.DROP_STRING_LENGTH, self.tr('Drop length constraints on character fields'), False)) + self.addParameter(ParameterBoolean(self.FORCE_SINGLEPART, self.tr('Create single-part geometries instead of multi-part'), False)) + + def processAlgorithm(self, progress): + database = self.getParameterValue(self.DATABASE) + uri = QgsDataSourceUri(database) + if uri.database() is '': + if '|layerid' in database: + database = database[:database.find('|layerid')] + uri = QgsDataSourceUri('dbname=\'%s\'' % (database)) + db = spatialite.GeoDB(uri) + + overwrite = self.getParameterValue(self.OVERWRITE) + createIndex = self.getParameterValue(self.CREATEINDEX) + convertLowerCase = self.getParameterValue(self.LOWERCASE_NAMES) + dropStringLength = self.getParameterValue(self.DROP_STRING_LENGTH) + forceSinglePart = self.getParameterValue(self.FORCE_SINGLEPART) + primaryKeyField = self.getParameterValue(self.PRIMARY_KEY) or 'id' + encoding = self.getParameterValue(self.ENCODING) + + layerUri = self.getParameterValue(self.INPUT) + layer = dataobjects.getObjectFromUri(layerUri) + + table = self.getParameterValue(self.TABLENAME) + if table: + table.strip() + if not table or table == '': + table = layer.name() + table = table.replace(' ', '').lower() + providerName = 'spatialite' + + geomColumn = self.getParameterValue(self.GEOMETRY_COLUMN) + if not geomColumn: + geomColumn = 'the_geom' + + options = {} + if overwrite: + options['overwrite'] = True + if convertLowerCase: + options['lowercaseFieldNames'] = True + geomColumn = geomColumn.lower() + if dropStringLength: + options['dropStringConstraints'] = True + if forceSinglePart: + options['forceSinglePartGeometryType'] = True + + # Clear geometry column for non-geometry tables + if not layer.hasGeometryType(): + geomColumn = None + + uri = db.uri + uri.setDataSource('', table, geomColumn, '', primaryKeyField) + + if encoding: + layer.setProviderEncoding(encoding) + + (ret, errMsg) = QgsVectorLayerImport.importLayer( + layer, + uri.uri(), + providerName, + self.crs, + False, + False, + options, + ) + if ret != 0: + raise GeoAlgorithmExecutionException( + self.tr('Error importing to Spatialite\n%s' % errMsg)) + + if geomColumn and createIndex: + db.create_spatial_index(table, geomColumn) diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 9cb4a1cab645..622e91a98b4e 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -133,6 +133,7 @@ from .PointsToPaths import PointsToPaths from .SpatialiteExecuteSQL import SpatialiteExecuteSQL from .PostGISExecuteSQL import PostGISExecuteSQL +from .ImportIntoSpatialite import ImportIntoSpatialite from .ImportIntoPostGIS import ImportIntoPostGIS from .SetVectorStyle import SetVectorStyle from .SetRasterStyle import SetRasterStyle @@ -214,7 +215,7 @@ def __init__(self): RandomPointsLayer(), RandomPointsPolygonsFixed(), RandomPointsPolygonsVariable(), RandomPointsAlongLines(), PointsToPaths(), - SpatialiteExecuteSQL(), + SpatialiteExecuteSQL(), ImportIntoSpatialite(), PostGISExecuteSQL(), ImportIntoPostGIS(), SetVectorStyle(), SetRasterStyle(), SelectByExpression(), HypsometricCurves(), diff --git a/python/plugins/processing/tools/spatialite.py b/python/plugins/processing/tools/spatialite.py index 95a75e970ab6..bb99ccfc4d3f 100644 --- a/python/plugins/processing/tools/spatialite.py +++ b/python/plugins/processing/tools/spatialite.py @@ -28,7 +28,6 @@ __revision__ = '$Format:%H$' from qgis.utils import spatialite_connect - import sqlite3 as sqlite @@ -124,3 +123,13 @@ def _exec_sql_and_commit(self, sql): except DbError: self.con.rollback() raise + + def create_spatial_index(self, table, geom_column='the_geom'): + sql = u"SELECT CreateSpatialIndex(%s, %s)" % (self._quote(table), self._quote(geom_column)) + self._exec_sql_and_commit(sql) + + def _quote(self, identifier): + """Quote identifier.""" + + # quote identifier, and double the double-quotes + return u"'%s'" % identifier.replace("'", "''") From ef34e393dc38413d213c83635301ccd63a97b3c4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 29 Oct 2016 22:06:28 +1000 Subject: [PATCH 528/897] Add method to QgsGeometry to extend the start/end of a linestring --- python/core/geometry/qgsgeometry.sip | 8 ++++++ python/core/geometry/qgslinestring.sip | 8 ++++++ src/core/geometry/qgsgeometry.cpp | 39 ++++++++++++++++++++++++++ src/core/geometry/qgsgeometry.h | 8 ++++++ src/core/geometry/qgslinestring.cpp | 26 +++++++++++++++++ src/core/geometry/qgslinestring.h | 8 ++++++ tests/src/core/testqgsgeometry.cpp | 10 +++++++ tests/src/python/test_qgsgeometry.py | 26 +++++++++++++++++ 8 files changed, 133 insertions(+) diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index ce35c94f73fa..b7a3a762c05c 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -514,6 +514,14 @@ class QgsGeometry JoinStyle joinStyle = JoinStyleRound, double mitreLimit = 2.0 ) const; + /** + * Extends a (multi)line geometry by extrapolating out the start or end of the line + * by a specified distance. Lines are extended using the bearing of the first or last + * segment in the line. + * @note added in QGIS 3.0 + */ + QgsGeometry extendLine( double startDistance, double endDistance ) const; + /** Returns a simplified version of this geometry using a specified tolerance value */ QgsGeometry simplify( double tolerance ) const; diff --git a/python/core/geometry/qgslinestring.sip b/python/core/geometry/qgslinestring.sip index 25a055faaa28..3ed4b59d31e6 100644 --- a/python/core/geometry/qgslinestring.sip +++ b/python/core/geometry/qgslinestring.sip @@ -92,6 +92,14 @@ class QgsLineString: public QgsCurve @return the converted geometry. Caller takes ownership*/ QgsAbstractGeometry* toCurveType() const /Factory/; + /** + * Extends the line geometry by extrapolating out the start or end of the line + * by a specified distance. Lines are extended using the bearing of the first or last + * segment in the line. + * @note added in QGIS 3.0 + */ + void extend( double startDistance, double endDistance ); + //reimplemented methods virtual QString geometryType() const; diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index d15e8b5402a3..8589f0c9b3c0 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -1452,6 +1452,45 @@ QgsGeometry QgsGeometry::singleSidedBuffer( double distance, int segments, Buffe } } +QgsGeometry QgsGeometry::extendLine( double startDistance, double endDistance ) const +{ + if ( !d->geometry || type() != QgsWkbTypes::LineGeometry ) + { + return QgsGeometry(); + } + + if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) ) + { + QList parts = asGeometryCollection(); + QList results; + Q_FOREACH ( const QgsGeometry& part, parts ) + { + QgsGeometry result = part.extendLine( startDistance, endDistance ); + if ( result ) + results << result; + } + if ( results.isEmpty() ) + return QgsGeometry(); + + QgsGeometry first = results.takeAt( 0 ); + Q_FOREACH ( const QgsGeometry& result, results ) + { + first.addPart( & result ); + } + return first; + } + else + { + QgsLineString* line = dynamic_cast< QgsLineString* >( d->geometry ); + if ( !line ) + return QgsGeometry(); + + QgsLineString* newLine = line->clone(); + newLine->extend( startDistance, endDistance ); + return QgsGeometry( newLine ); + } +} + QgsGeometry QgsGeometry::simplify( double tolerance ) const { if ( !d->geometry ) diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 08c946e7dfba..1854adadaa09 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -558,6 +558,14 @@ class CORE_EXPORT QgsGeometry JoinStyle joinStyle = JoinStyleRound, double mitreLimit = 2.0 ) const; + /** + * Extends a (multi)line geometry by extrapolating out the start or end of the line + * by a specified distance. Lines are extended using the bearing of the first or last + * segment in the line. + * @note added in QGIS 3.0 + */ + QgsGeometry extendLine( double startDistance, double endDistance ) const; + //! Returns a simplified version of this geometry using a specified tolerance value QgsGeometry simplify( double tolerance ) const; diff --git a/src/core/geometry/qgslinestring.cpp b/src/core/geometry/qgslinestring.cpp index a8fa9a33be6e..50211d520cfc 100644 --- a/src/core/geometry/qgslinestring.cpp +++ b/src/core/geometry/qgslinestring.cpp @@ -583,6 +583,32 @@ QgsAbstractGeometry* QgsLineString::toCurveType() const return compoundCurve; } +void QgsLineString::extend( double startDistance, double endDistance ) +{ + if ( mX.size() < 2 || mY.size() < 2 ) + return; + + // start of line + if ( startDistance > 0 ) + { + double currentLen = sqrt( qPow( mX.at( 0 ) - mX.at( 1 ), 2 ) + + qPow( mY.at( 0 ) - mY.at( 1 ), 2 ) ); + double newLen = currentLen + startDistance; + mX[ 0 ] = mX.at( 1 ) + ( mX.at( 0 ) - mX.at( 1 ) ) / currentLen * newLen; + mY[ 0 ] = mY.at( 1 ) + ( mY.at( 0 ) - mY.at( 1 ) ) / currentLen * newLen; + } + // end of line + if ( endDistance > 0 ) + { + int last = mX.size() - 1; + double currentLen = sqrt( qPow( mX.at( last ) - mX.at( last - 1 ), 2 ) + + qPow( mY.at( last ) - mY.at( last - 1 ), 2 ) ); + double newLen = currentLen + endDistance; + mX[ last ] = mX.at( last - 1 ) + ( mX.at( last ) - mX.at( last - 1 ) ) / currentLen * newLen; + mY[ last ] = mY.at( last - 1 ) + ( mY.at( last ) - mY.at( last - 1 ) ) / currentLen * newLen; + } +} + /*************************************************************************** * This class is considered CRITICAL and any change MUST be accompanied with * full unit tests. diff --git a/src/core/geometry/qgslinestring.h b/src/core/geometry/qgslinestring.h index 2cda7f84252d..489972a1631f 100644 --- a/src/core/geometry/qgslinestring.h +++ b/src/core/geometry/qgslinestring.h @@ -120,6 +120,14 @@ class CORE_EXPORT QgsLineString: public QgsCurve @return the converted geometry. Caller takes ownership*/ QgsAbstractGeometry* toCurveType() const override; + /** + * Extends the line geometry by extrapolating out the start or end of the line + * by a specified distance. Lines are extended using the bearing of the first or last + * segment in the line. + * @note added in QGIS 3.0 + */ + void extend( double startDistance, double endDistance ); + //reimplemented methods virtual QString geometryType() const override { return QStringLiteral( "LineString" ); } diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index 6bccf7f4ff5e..d170f894d3fb 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -2208,6 +2208,16 @@ void TestQgsGeometry::lineString() QCOMPARE( static_cast< QgsPointV2*>( mpBoundary->geometryN( 1 ) )->x(), 1.0 ); QCOMPARE( static_cast< QgsPointV2*>( mpBoundary->geometryN( 1 ) )->y(), 1.0 ); QCOMPARE( static_cast< QgsPointV2*>( mpBoundary->geometryN( 1 ) )->z(), 20.0 ); + + + //extend + QgsLineString extend1; + extend1.extend( 10, 10 ); //test no crash + extend1.setPoints( QList() << QgsPointV2( 0, 0 ) << QgsPointV2( 1, 0 ) << QgsPointV2( 1, 1 ) ); + extend1.extend( 1, 2 ); + QCOMPARE( extend1.pointN( 0 ), QgsPointV2( QgsWkbTypes::Point, -1, 0 ) ); + QCOMPARE( extend1.pointN( 1 ), QgsPointV2( QgsWkbTypes::Point, 1, 0 ) ); + QCOMPARE( extend1.pointN( 2 ), QgsPointV2( QgsWkbTypes::Point, 1, 3 ) ); } void TestQgsGeometry::polygon() diff --git a/tests/src/python/test_qgsgeometry.py b/tests/src/python/test_qgsgeometry.py index 11368bcdb566..de2e744757ad 100644 --- a/tests/src/python/test_qgsgeometry.py +++ b/tests/src/python/test_qgsgeometry.py @@ -3594,5 +3594,31 @@ def testAngleAtVertex(self): self.assertAlmostEqual(polygon.angleAtVertex(3), math.radians(225.0), places=3) self.assertAlmostEqual(polygon.angleAtVertex(4), math.radians(135.0), places=3) + def testExtendLine(self): + """ test QgsGeometry.extendLine """ + + empty = QgsGeometry() + self.assertFalse(empty.extendLine(1, 2)) + + # not a linestring + point = QgsGeometry.fromWkt('Point(1 2)') + self.assertFalse(point.extendLine(1, 2)) + + # linestring + linestring = QgsGeometry.fromWkt('LineString(0 0, 1 0, 1 1)') + extended = linestring.extendLine(1, 2) + exp = 'LineString(-1 0, 1 0, 1 3)' + result = extended.exportToWkt() + self.assertTrue(compareWkt(result, exp, 0.00001), + "Extend line: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result)) + + # multilinestring + multilinestring = QgsGeometry.fromWkt('MultiLineString((0 0, 1 0, 1 1),(11 11, 11 10, 10 10))') + extended = multilinestring.extendLine(1, 2) + exp = 'MultiLineString((-1 0, 1 0, 1 3),(11 12, 11 10, 8 10))' + result = extended.exportToWkt() + self.assertTrue(compareWkt(result, exp, 0.00001), + "Extend line: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result)) + if __name__ == '__main__': unittest.main() From 2b545822e7755fe3ca92c1b90db8fe260e40dc30 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 29 Oct 2016 22:24:24 +1000 Subject: [PATCH 529/897] [FEATURE] New expression function 'extend' Extends linestrings by a specified amount at the start and end of the line --- resources/function_help/json/extend | 10 ++++++++++ src/core/qgsexpression.cpp | 15 +++++++++++++++ tests/src/core/testqgsexpression.cpp | 4 ++++ 3 files changed, 29 insertions(+) create mode 100644 resources/function_help/json/extend diff --git a/resources/function_help/json/extend b/resources/function_help/json/extend new file mode 100644 index 000000000000..055862e3857b --- /dev/null +++ b/resources/function_help/json/extend @@ -0,0 +1,10 @@ +{ + "name": "extend", + "type": "function", + "description": "Extends the start and end of a linestring geometry by a specified amount. Lines are extended using the bearing of the first and last segment in the line. Distances are in the Spatial Reference System of this geometry.", + "arguments": [ {"arg":"geometry","description":"a (multi)linestring geometry"}, + {"arg":"start_distance","description":"distance to extend the start of the line"}, + {"arg":"end_distance","description":"distance to extend the end of the line."}], + "examples": [ { "expression":"geom_to_wkt(extend(geom_from_wkt('LineString(0 0, 1 0, 1 1)'),1,2))", "returns":"LineString (-1 0, 1 0, 1 3)"}] +} + diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 2a15f91c3c2f..bcb414afb047 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -2460,6 +2460,17 @@ static QVariant fcnSingleSidedBuffer( const QVariantList& values, const QgsExpre return result; } +static QVariant fcnExtend( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QgsGeometry fGeom = getGeometry( values.at( 0 ), parent ); + double distStart = getDoubleValue( values.at( 1 ), parent ); + double distEnd = getDoubleValue( values.at( 2 ), parent ); + + QgsGeometry geom = fGeom.extendLine( distStart, distEnd ); + QVariant result = !geom.isEmpty() ? QVariant::fromValue( geom ) : QVariant(); + return result; +} + static QVariant fcnTranslate( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { QgsGeometry fGeom = getGeometry( values.at( 0 ), parent ); @@ -3791,6 +3802,10 @@ const QList& QgsExpression::Functions() << Parameter( QStringLiteral( "join" ), true, QgsGeometry::JoinStyleRound ) << Parameter( QStringLiteral( "mitre_limit" ), true, 2.0 ), fcnSingleSidedBuffer, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "extend" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "start_distance" ) ) + << Parameter( QStringLiteral( "end_distance" ) ), + fcnExtend, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "centroid" ), 1, fcnCentroid, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "point_on_surface" ), 1, fcnPointOnSurface, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "reverse" ), 1, fcnReverse, QStringLiteral( "GeometryGroup" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 2ca376119442..6f9ad7c4bf28 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -699,6 +699,10 @@ class TestQgsExpression: public QObject QTest::newRow( "single_sided_buffer line" ) << "geom_to_wkt(single_sided_buffer(geom_from_wkt('LineString(0 0, 10 0)'),1,segments:=4))" << false << QVariant( "Polygon ((10 0, 0 0, 0 1, 10 1, 10 0))" ); QTest::newRow( "single_sided_buffer line mitre" ) << "geom_to_wkt(single_sided_buffer(geometry:=geom_from_wkt('LineString(0 0, 10 0)'),distance:=-1,join:=2,mitre_limit:=1))" << false << QVariant( "Polygon ((0 0, 10 0, 10 -1, 0 -1, 0 0))" ); QTest::newRow( "single_sided_buffer line bevel" ) << "geom_to_wkt(single_sided_buffer(geometry:=geom_from_wkt('LineString(0 0, 10 0, 10 10)'),distance:=1,join:=3))" << false << QVariant( "Polygon ((10 10, 10 0, 0 0, 0 1, 9 1, 9 10, 10 10))" ); + QTest::newRow( "extend not geom" ) << "extend('g', 1, 2)" << true << QVariant(); + QTest::newRow( "extend null" ) << "extend(NULL, 1, 2)" << false << QVariant(); + QTest::newRow( "extend point" ) << "extend(geom_from_wkt('POINT(1 2)'),1,2)" << false << QVariant(); + QTest::newRow( "extend line" ) << "geom_to_wkt(extend(geom_from_wkt('LineString(0 0, 1 0, 1 1)'),1,2))" << false << QVariant( "LineString (-1 0, 1 0, 1 3)" ); QTest::newRow( "start_point point" ) << "geom_to_wkt(start_point(geom_from_wkt('POINT(2 0)')))" << false << QVariant( "Point (2 0)" ); QTest::newRow( "start_point multipoint" ) << "geom_to_wkt(start_point(geom_from_wkt('MULTIPOINT((3 3), (1 1), (2 2))')))" << false << QVariant( "Point (3 3)" ); QTest::newRow( "start_point line" ) << "geom_to_wkt(start_point(geom_from_wkt('LINESTRING(4 1, 1 1, 2 2)')))" << false << QVariant( "Point (4 1)" ); From 8dab2cd4d75f4fdf6d10e0741557915e783722ca Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 29 Oct 2016 22:33:08 +1000 Subject: [PATCH 530/897] [FEATURE][processing] New algorithm to extend lines Allows extending linestrings by a set distance at the start and end of the line --- python/plugins/processing/algs/help/qgis.yaml | 3 + .../processing/algs/qgis/ExtendLines.py | 86 +++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 3 +- .../tests/testdata/expected/extend_lines.gfs | 15 ++++ .../tests/testdata/expected/extend_lines.gml | 48 +++++++++++ .../testdata/expected/extend_multilines.gfs | 15 ++++ .../testdata/expected/extend_multilines.gml | 33 +++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 27 ++++++ 8 files changed, 229 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/ExtendLines.py create mode 100644 python/plugins/processing/tests/testdata/expected/extend_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extend_lines.gml create mode 100644 python/plugins/processing/tests/testdata/expected/extend_multilines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extend_multilines.gml diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index b5c0c20090f3..9b399063e79f 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -158,6 +158,9 @@ qgis:exportaddgeometrycolumns: > Depending on the geometry type of the vector layer, the attributes added to the table will be different. +qgis:extendlines: > + This algorithms extends line geometries by a specified amount at the start and end of the line. Lines are extended using the bearing of the first and last segment in the line. + qgis:extractbyattribute: > This algorithms creates a new vector layer that only contains matching features from an input layer. The criteria for adding features to the resulting layer is defined based on the values of an attribute from the input layer. diff --git a/python/plugins/processing/algs/qgis/ExtendLines.py b/python/plugins/processing/algs/qgis/ExtendLines.py new file mode 100644 index 000000000000..b33973044add --- /dev/null +++ b/python/plugins/processing/algs/qgis/ExtendLines.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ExtendLines.py + -------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive323 + +__revision__ = '$Format:%H$' + + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.parameters import ParameterVector, ParameterNumber +from processing.core.outputs import OutputVector +from processing.tools import dataobjects, vector + + +class ExtendLines(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + OUTPUT_LAYER = 'OUTPUT_LAYER' + START_DISTANCE = 'START_DISTANCE' + END_DISTANCE = 'END_DISTANCE' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Extend lines') + self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE])) + self.addParameter(ParameterNumber(self.START_DISTANCE, + self.tr('Start distance'), default=0.0)) + self.addParameter(ParameterNumber(self.END_DISTANCE, + self.tr('End distance'), default=0.0)) + + self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Extended lines'))) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + + writer = self.getOutputFromName( + self.OUTPUT_LAYER).getVectorWriter( + layer.fields(), + layer.wkbType(), + layer.crs()) + + start_distance = self.getParameterValue(self.START_DISTANCE) + end_distance = self.getParameterValue(self.END_DISTANCE) + + features = vector.features(layer) + total = 100.0 / len(features) + + for current, input_feature in enumerate(features): + output_feature = input_feature + input_geometry = input_feature.geometry() + if input_geometry: + output_geometry = input_geometry.extendLine(start_distance, end_distance) + if not output_geometry: + raise GeoAlgorithmExecutionException( + self.tr('Error calculating extended line')) + + output_feature.setGeometry(output_geometry) + + writer.addFeature(output_feature) + progress.setPercentage(int(current * total)) + + del writer diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index bf3296b2b923..9c6a95d77b5f 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -171,6 +171,7 @@ from .TinInterpolationAttribute import TinInterpolationAttribute from .ZonalStatisticsQgis import ZonalStatisticsQgis from .RemoveNullGeometry import RemoveNullGeometry +from .ExtendLines import ExtendLines pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -232,7 +233,7 @@ def __init__(self): ReliefAuto(), ZonalStatisticsQgis(), IdwInterpolationZValue(), IdwInterpolationAttribute(), TinInterpolationZValue(), TinInterpolationAttribute(), - RemoveNullGeometry(), ExtractByExpression() + RemoveNullGeometry(), ExtractByExpression(), ExtendLines() ] if hasMatplotlib: diff --git a/python/plugins/processing/tests/testdata/expected/extend_lines.gfs b/python/plugins/processing/tests/testdata/expected/extend_lines.gfs new file mode 100644 index 000000000000..2a2f65c24007 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extend_lines.gfs @@ -0,0 +1,15 @@ + + + extend_lines + extend_lines + 2 + EPSG:4326 + + 7 + -1.10000 + 11.14142 + -3.07071 + 5.14142 + + + diff --git a/python/plugins/processing/tests/testdata/expected/extend_lines.gml b/python/plugins/processing/tests/testdata/expected/extend_lines.gml new file mode 100644 index 000000000000..89972109ce50 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extend_lines.gml @@ -0,0 +1,48 @@ + + + + + -1.1-3.070710678118655 + 11.141421356237315.141421356237309 + + + + + + 5.9,2.0 9,2 9,3 11.141421356237309,5.141421356237309 + + + + + -1.1,-1.0 1.2,-1.0 + + + + + 2.0,-0.1 2,2 3,2 3.0,3.2 + + + + + 2.9,1.0 5.2,1.0 + + + + + 6.9,-3.0 10.2,-3.0 + + + + + 5.929289321881345,-3.070710678118655 10.141421356237309,1.141421356237309 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/expected/extend_multilines.gfs b/python/plugins/processing/tests/testdata/expected/extend_multilines.gfs new file mode 100644 index 000000000000..b6f04bd2c9d1 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extend_multilines.gfs @@ -0,0 +1,15 @@ + + + extend_multilines + extend_multilines + 5 + EPSG:4326 + + 4 + -1.20000 + 5.98034 + -1.00000 + 4.13130 + + + diff --git a/python/plugins/processing/tests/testdata/expected/extend_multilines.gml b/python/plugins/processing/tests/testdata/expected/extend_multilines.gml new file mode 100644 index 000000000000..c25c6d9f411a --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extend_multilines.gml @@ -0,0 +1,33 @@ + + + + + -1.2-1 + 5.9803373870435034.131303337656388 + + + + + + -1.2,-1.0 1.4,-1.0 + + + + + 2.8,1.0 5.4,1.05.027602565068266,2.614750056493599 4.993163391936403,0.600058428279599 + + + + + + + + + 2.0,-0.2 2,2 3,2 3.0,3.42.744420970065991,4.041450058619024 5.859334643361299,4.1313033376563882.800042438915868,3.004119922970864 5.980337387043503,2.938593167493973 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 01a8e8b7757c..b3fa2f3d67de 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1225,3 +1225,30 @@ tests: OUTPUT: name: expected/extract_expression.gml type: vector + + - algorithm: qgis:extendlines + name: Extend lines + params: + END_DISTANCE: 0.2 + INPUT_LAYER: + name: lines.gml + type: vector + START_DISTANCE: 0.1 + results: + OUTPUT_LAYER: + name: expected/extend_lines.gml + type: vector + + + - algorithm: qgis:extendlines + name: Extend multilines + params: + END_DISTANCE: 0.4 + INPUT_LAYER: + name: multilines.gml + type: vector + START_DISTANCE: 0.2 + results: + OUTPUT_LAYER: + name: expected/extend_multilines.gml + type: vector From 82312e10e472fb91a5b5c0253456130dea86521e Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 30 Oct 2016 17:10:37 +1000 Subject: [PATCH 531/897] [FEATURE][processing] New algorithm to extract specific nodes This algorithm allows you to extract specific nodes from geometries. Eg you can extract the first or last node in the geometry. The algorithm accepts a comma separated list of node indices to extract, eg 0 = first node, 1 = second node, etc. Negative indices can be used to extract nodes from the end of the geometry. Eg -1 = last node, -2 = second last node. --- python/plugins/processing/algs/help/qgis.yaml | 7 + .../algs/qgis/ExtractSpecificNodes.py | 118 ++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 4 +- .../expected/extract_specific_nodes_lines.gfs | 35 +++ .../expected/extract_specific_nodes_lines.gml | 198 ++++++++++++++++ .../expected/extract_specific_nodes_polys.gfs | 51 ++++ .../expected/extract_specific_nodes_polys.gml | 217 ++++++++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 24 ++ 8 files changed, 653 insertions(+), 1 deletion(-) create mode 100644 python/plugins/processing/algs/qgis/ExtractSpecificNodes.py create mode 100644 python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gml create mode 100644 python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gml diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index 9b399063e79f..874e7e5248ac 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -177,6 +177,13 @@ qgis:extractnodes: > Additional fields are added to the nodes indicating the node index (beginning at 0), distance along original geometry and bisector angle of node for original geometry. +qgis:extractspecificnodes: > + This algorithm takes a line or polygon layer and generates a point layer with points representing specific nodes in the input lines or polygons. For instance, this algorithm can be used to extract the first or last nodes in the geometry. The attributes associated to each point are the same ones associated to the line or polygon that the point belongs to. + + The node indices parameter accepts a comma separated string specifying the indices of the nodes to extract. The first node corresponds to an index of 0, the second node has an index of 1, etc. Negative indices can be used to find nodes at the end of the geometry, eg an index of -1 corresponds to the last node, -2 corresponds to the second last node, etc. + + Additional fields are added to the nodes indicating the specific node position (eg 0, -1, etc), the original node index, distance along the original geometry and bisector angle of node for the original geometry. + qgis:fieldcalculator: > This algorithm computes a new vector layer with the same features of the input layer, but with an additional attribute. The values of this new attribute are computed from each feature using a mathematical formula, based on te properties and attributes of the feature. diff --git a/python/plugins/processing/algs/qgis/ExtractSpecificNodes.py b/python/plugins/processing/algs/qgis/ExtractSpecificNodes.py new file mode 100644 index 000000000000..d5d4057a621d --- /dev/null +++ b/python/plugins/processing/algs/qgis/ExtractSpecificNodes.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ExtractSpecificNodes.py + -------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive323 + +__revision__ = '$Format:%H$' + +import math +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.parameters import ParameterVector, ParameterString +from processing.core.outputs import OutputVector +from processing.tools import dataobjects, vector + +from qgis.core import QgsWkbTypes, QgsFeature, QgsGeometry, QgsField +from qgis.PyQt.QtCore import QVariant + + +class ExtractSpecificNodes(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + OUTPUT_LAYER = 'OUTPUT_LAYER' + NODES = 'NODES' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Extract specific nodes') + self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Input layer'), [dataobjects.TYPE_VECTOR_ANY])) + self.addParameter(ParameterString(self.NODES, + self.tr('Node indices'), default='0')) + self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Nodes'), datatype=[dataobjects.TYPE_VECTOR_POINT])) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + + fields = layer.fields() + fields.append(QgsField('node_pos', QVariant.Int)) + fields.append(QgsField('node_index', QVariant.Int)) + fields.append(QgsField('distance', QVariant.Double)) + fields.append(QgsField('angle', QVariant.Double)) + + writer = self.getOutputFromName( + self.OUTPUT_LAYER).getVectorWriter( + fields, + QgsWkbTypes.Point, + layer.crs()) + + node_indices_string = self.getParameterValue(self.NODES) + indices = [] + for node in node_indices_string.split(','): + try: + indices.append(int(node)) + except: + raise GeoAlgorithmExecutionException( + self.tr('\'{}\' is not a valid node index').format(node)) + + features = vector.features(layer) + total = 100.0 / len(features) + + for current, f in enumerate(features): + + input_geometry = f.geometry() + if not input_geometry: + writer.addFeature(f) + else: + total_nodes = input_geometry.geometry().nCoordinates() + + for node in indices: + if node < 0: + node_index = total_nodes + node + else: + node_index = node + + if node_index < 0 or node_index >= total_nodes: + continue + + distance = input_geometry.distanceToVertex(node_index) + angle = math.degrees(input_geometry.angleAtVertex(node_index)) + + output_feature = QgsFeature() + attrs = f.attributes() + attrs.append(node) + attrs.append(node_index) + attrs.append(distance) + attrs.append(angle) + output_feature.setAttributes(attrs) + + point = input_geometry.vertexAt(node_index) + output_feature.setGeometry(QgsGeometry.fromPoint(point)) + + writer.addFeature(output_feature) + + progress.setPercentage(int(current * total)) + + del writer diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 9c6a95d77b5f..43ab782dafa9 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -172,6 +172,7 @@ from .ZonalStatisticsQgis import ZonalStatisticsQgis from .RemoveNullGeometry import RemoveNullGeometry from .ExtendLines import ExtendLines +from .ExtractSpecificNodes import ExtractSpecificNodes pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -233,7 +234,8 @@ def __init__(self): ReliefAuto(), ZonalStatisticsQgis(), IdwInterpolationZValue(), IdwInterpolationAttribute(), TinInterpolationZValue(), TinInterpolationAttribute(), - RemoveNullGeometry(), ExtractByExpression(), ExtendLines() + RemoveNullGeometry(), ExtractByExpression(), ExtendLines(), + ExtractSpecificNodes() ] if hasMatplotlib: diff --git a/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gfs b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gfs new file mode 100644 index 000000000000..14ab595f5dc4 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gfs @@ -0,0 +1,35 @@ + + + extract_specific_nodes_lines + extract_specific_nodes_lines + 1 + EPSG:4326 + + 21 + -1.00000 + 11.00000 + -3.00000 + 5.00000 + + + node_pos + node_pos + Integer + + + node_index + node_index + Integer + + + distance + distance + Real + + + angle + angle + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gml b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gml new file mode 100644 index 000000000000..ae7a0d5bb767 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_lines.gml @@ -0,0 +1,198 @@ + + + + + -1-3 + 115 + + + + + + 6,2 + 0 + 0 + 0 + 90 + + + + + 11,5 + -1 + 3 + 6.82842712474619 + 45 + + + + + 9,3 + 2 + 2 + 4 + 22.5 + + + + + 9,3 + -2 + 2 + 4 + 22.5 + + + + + -1,-1 + 0 + 0 + 0 + 90 + + + + + 1,-1 + -1 + 1 + 2 + 90 + + + + + -1,-1 + -2 + 0 + 0 + 90 + + + + + 2,0 + 0 + 0 + 0 + 0 + + + + + 3,3 + -1 + 3 + 4 + 0 + + + + + 3,2 + 2 + 2 + 3 + 45 + + + + + 3,2 + -2 + 2 + 3 + 45 + + + + + 3,1 + 0 + 0 + 0 + 90 + + + + + 5,1 + -1 + 1 + 2 + 90 + + + + + 3,1 + -2 + 0 + 0 + 90 + + + + + 7,-3 + 0 + 0 + 0 + 90 + + + + + 10,-3 + -1 + 1 + 3 + 90 + + + + + 7,-3 + -2 + 0 + 0 + 90 + + + + + 6,-3 + 0 + 0 + 0 + 45 + + + + + 10,1 + -1 + 1 + 5.65685424949238 + 45 + + + + + 6,-3 + -2 + 0 + 0 + 45 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gfs b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gfs new file mode 100644 index 000000000000..275368de6d46 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gfs @@ -0,0 +1,51 @@ + + + extract_specific_nodes_polys + extract_specific_nodes_polys + 1 + EPSG:4326 + + 18 + -1.00000 + 7.00000 + -1.00000 + 5.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + node_pos + node_pos + Integer + + + node_index + node_index + Integer + + + distance + distance + Real + + + angle + angle + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gml b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gml new file mode 100644 index 000000000000..f557f1b1e796 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_specific_nodes_polys.gml @@ -0,0 +1,217 @@ + + + + + -1-1 + 75 + + + + + + -1,-1 + aaaaa + 33 + 44.123456 + 0 + 0 + 0 + 315 + + + + + -1,-1 + aaaaa + 33 + 44.123456 + -1 + 6 + 16 + 315 + + + + + 2,-1 + aaaaa + 33 + 44.123456 + 5 + 5 + 13 + 225 + + + + + 3,3 + aaaaa + 33 + 44.123456 + -5 + 2 + 8 + 135 + + + + + 5,5 + Aaaaa + -33 + 0 + 0 + 0 + 0 + 90 + + + + + 5,5 + Aaaaa + -33 + 0 + -1 + 3 + 4.82842712474619 + 90 + + + + + 2,5 + bbaaa + 0.123 + 0 + 0 + 0 + 315 + + + + + 2,5 + bbaaa + 0.123 + -1 + 4 + 4 + 315 + + + + + 2,5 + bbaaa + 0.123 + -5 + 0 + 0 + 315 + + + + + 6,1 + ASDF + 0 + 0 + 0 + 0 + 45 + + + + + 7,0 + ASDF + 0 + -1 + 9 + 25.4142135623731 + 225 + + + + + 7,0 + ASDF + 0 + 5 + 5 + 17.4142135623731 + 225 + + + + + 7,0 + ASDF + 0 + -5 + 5 + 17.4142135623731 + 225 + + + + + 120 + -100291.43213 + + + + + 3,2 + elim + 2 + 3.33 + 0 + 0 + 0 + 99.217474411461 + + + + + 3,2 + elim + 2 + 3.33 + -1 + 5 + 15.634413615168 + 99.217474411461 + + + + + 3,2 + elim + 2 + 3.33 + 5 + 5 + 15.634413615168 + 99.217474411461 + + + + + 6,1 + elim + 2 + 3.33 + -5 + 1 + 3.16227766016838 + 144.217474411461 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index b3fa2f3d67de..f4b96d6ba551 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1252,3 +1252,27 @@ tests: OUTPUT_LAYER: name: expected/extend_multilines.gml type: vector + + - algorithm: qgis:extractspecificnodes + name: Extract specific nodes lines + params: + INPUT_LAYER: + name: lines.gml + type: vector + NODES: 0,-1,2,-2 + results: + OUTPUT_LAYER: + name: expected/extract_specific_nodes_lines.gml + type: vector + + - algorithm: qgis:extractspecificnodes + name: Extract specific nodes polygons + params: + INPUT_LAYER: + name: polys.gml + type: vector + NODES: 0,-1,5,-5 + results: + OUTPUT_LAYER: + name: expected/extract_specific_nodes_polys.gml + type: vector \ No newline at end of file From bd950616ac35476aacf22d9db3b0c7b44ffccbbb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 31 Oct 2016 06:51:50 +1000 Subject: [PATCH 532/897] Rename visible "favourite" strings to "favorite", change API to use "favorite" --- doc/api_break.dox | 8 ++++++- python/core/qgsbrowsermodel.sip | 16 +++++++++++-- python/core/qgsdataitem.sip | 40 +++++++++++++++++++++++--------- src/app/qgsbrowserdockwidget.cpp | 32 ++++++++++++------------- src/app/qgsbrowserdockwidget.h | 8 +++---- src/core/qgsbrowsermodel.cpp | 22 +++++++++--------- src/core/qgsbrowsermodel.h | 18 +++++++++++--- src/core/qgsdataitem.cpp | 20 ++++++++-------- src/core/qgsdataitem.h | 35 +++++++++++++++++++++------- src/gui/qgsbrowsertreeview.cpp | 4 ++-- 10 files changed, 134 insertions(+), 69 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 52df5d18ac1b..36ec9dcd9ae1 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -61,6 +61,7 @@ Renamed Classes {#qgis_api_break_3_0_renamed_classes} QgsEditorWidgetV2QgsEditorWidget QgsEllipseSymbolLayerV2QgsEllipseSymbolLayer QgsEllipseSymbolLayerV2WidgetQgsEllipseSymbolLayerWidget +QgsFavouritesItemQgsFavoritesItem QgsFeatureRendererV2QgsFeatureRenderer QgsFillSymbolLayerV2QgsFillSymbolLayer QgsFillSymbolV2QgsFillSymbol @@ -352,6 +353,11 @@ QgsAuthMethod {#qgis_api_break_3_0_QgsAuthMethod} - DataSourceURI has been renamed to DataSourceUri - GenericDataSourceURI has been renamed to GenericDataSourceUri +QgsBrowserModel {#qgis_api_break_3_0_QgsBrowserModel} +--------------- + +- addFavouriteDirectory has been renamed to addFavoriteDirectory +- removeFavourite has been renamed to removeFavorite QgsCachedFeatureIterator {#qgis_api_break_3_0_QgsQgsCachedFeatureIterator} ------------------------ @@ -624,7 +630,7 @@ QgsDataItem {#qgis_api_break_3_0_QgsDataItem} - isPopulated() has been removed. Use state() instead. - capabilities() has been removed. Use capabilities2() instead (TODO: rename back to capabilities()). - emitBeginInsertItems(), emitEndInsertItems(), emitBeginRemoveItems(), emitEndRemoveItems(), emitDataChanged(), emitStateChanged() have been removed. - +- Favourites was renamed to Favorites QgsDataSourceURI {#qgis_api_break_3_0_QgsDatasourceUri} ---------------- diff --git a/python/core/qgsbrowsermodel.sip b/python/core/qgsbrowsermodel.sip index f22616febf51..c50012548763 100644 --- a/python/core/qgsbrowsermodel.sip +++ b/python/core/qgsbrowsermodel.sip @@ -95,8 +95,20 @@ class QgsBrowserModel : QAbstractItemModel void itemDataChanged( QgsDataItem * item ); void itemStateChanged( QgsDataItem * item, QgsDataItem::State oldState ); - void addFavouriteDirectory( const QString& favDir ); - void removeFavourite( const QModelIndex &index ); + /** + * Adds a directory to the favorites group. + * @note added in QGIS 3.0 + * @see removeFavorite() + */ + void addFavoriteDirectory( const QString& directory ); + + /** + * Removes a favorite directory from its corresponding model index. + * @note added in QGIS 3.0 + * @see addFavoriteDirectory() + */ + void removeFavorite( const QModelIndex &index ); + void updateProjectHome(); /** Hide the given path in the browser model */ diff --git a/python/core/qgsdataitem.sip b/python/core/qgsdataitem.sip index 421c50b34567..3db121ea0559 100644 --- a/python/core/qgsdataitem.sip +++ b/python/core/qgsdataitem.sip @@ -43,8 +43,8 @@ class QgsDataItem : QObject sipType = sipType_QgsErrorItem; else if (qobject_cast(sipCpp)) sipType = sipType_QgsDirectoryItem; - else if (qobject_cast(sipCpp)) - sipType = sipType_QgsFavouritesItem; + else if (qobject_cast(sipCpp)) + sipType = sipType_QgsFavoritesItem; else if (qobject_cast(sipCpp)) sipType = sipType_QgsZipItem; else if (qobject_cast(sipCpp)) @@ -61,8 +61,8 @@ class QgsDataItem : QObject Directory, Layer, Error, - Favourites, - Project //! Represents a QGIS project + Favorites, //!< Represents a favorite item + Project //!< Represents a QGIS project }; /** Create new data item. */ @@ -359,7 +359,7 @@ class QgsDirectoryItem : QgsDataCollectionItem * @param parent * @param name directory name * @param dirPath path to directory in file system - * @param path item path in the tree, it may be dirPath or dirPath with some prefix, e.g. favourites: */ + * @param path item path in the tree, it may be dirPath or dirPath with some prefix, e.g. favorites: */ QgsDirectoryItem( QgsDataItem* parent, const QString& name, const QString& dirPath, const QString& path ); ~QgsDirectoryItem(); @@ -444,22 +444,40 @@ class QgsDirectoryParamWidget : QTreeWidget void showHideColumn(); }; -/** Contains various Favourites directories */ -class QgsFavouritesItem : QgsDataCollectionItem +/** \ingroup core + * Contains various Favorites directories + * \note added in QGIS 3.0 +*/ +class QgsFavoritesItem : QgsDataCollectionItem { %TypeHeaderCode #include %End public: - QgsFavouritesItem( QgsDataItem* parent, const QString& name, const QString& path = QString() ); - ~QgsFavouritesItem(); + + /** + * Constructor for QgsFavoritesItem. Accepts a path argument specifying the file path associated with + * the item. + */ + QgsFavoritesItem( QgsDataItem* parent, const QString& name, const QString& path = QString() ); + ~QgsFavoritesItem(); QVector createChildren(); - void addDirectory( const QString& favIcon ); + /** + * Adds a new directory to the favorites group. + * @see removeDirectory() + */ + void addDirectory( const QString& directory ); + + /** + * Removes an existing directory from the favorites group. + * @see addDirectory() + */ void removeDirectory( QgsDirectoryItem *item ); - static const QIcon &iconFavourites(); + //! Icon for favorites group + static const QIcon &iconFavorites(); }; /** A zip file: contains layers, using GDAL/OGR VSIFILE mechanism */ diff --git a/src/app/qgsbrowserdockwidget.cpp b/src/app/qgsbrowserdockwidget.cpp index be5541e025b7..15092c0fa681 100644 --- a/src/app/qgsbrowserdockwidget.cpp +++ b/src/app/qgsbrowserdockwidget.cpp @@ -385,17 +385,17 @@ void QgsBrowserDockWidget::showContextMenu( QPoint pt ) { QSettings settings; QStringList favDirs = settings.value( QStringLiteral( "/browser/favourites" ) ).toStringList(); - bool inFavDirs = item->parent() && item->parent()->type() == QgsDataItem::Favourites; + bool inFavDirs = item->parent() && item->parent()->type() == QgsDataItem::Favorites; if ( item->parent() && !inFavDirs ) { - // only non-root directories can be added as favourites - menu->addAction( tr( "Add as a Favourite" ), this, SLOT( addFavourite() ) ); + // only non-root directories can be added as favorites + menu->addAction( tr( "Add as a Favorite" ), this, SLOT( addFavorite() ) ); } else if ( inFavDirs ) { - // only favourites can be removed - menu->addAction( tr( "Remove Favourite" ), this, SLOT( removeFavourite() ) ); + // only favorites can be removed + menu->addAction( tr( "Remove Favorite" ), this, SLOT( removeFavorite() ) ); } menu->addAction( tr( "Properties..." ), this, SLOT( showProperties() ) ); menu->addAction( tr( "Hide from Browser" ), this, SLOT( hideItem() ) ); @@ -410,9 +410,9 @@ void QgsBrowserDockWidget::showContextMenu( QPoint pt ) menu->addAction( tr( "Add Selected Layers" ), this, SLOT( addSelectedLayers() ) ); menu->addAction( tr( "Properties..." ), this, SLOT( showProperties() ) ); } - else if ( item->type() == QgsDataItem::Favourites ) + else if ( item->type() == QgsDataItem::Favorites ) { - menu->addAction( tr( "Add a Directory..." ), this, SLOT( addFavouriteDirectory() ) ); + menu->addAction( tr( "Add a Directory..." ), this, SLOT( addFavoriteDirectory() ) ); } @@ -434,7 +434,7 @@ void QgsBrowserDockWidget::showContextMenu( QPoint pt ) menu->popup( mBrowserView->mapToGlobal( pt ) ); } -void QgsBrowserDockWidget::addFavourite() +void QgsBrowserDockWidget::addFavorite() { QModelIndex index = mProxyModel->mapToSource( mBrowserView->currentIndex() ); QgsDataItem* item = mModel->dataItem( index ); @@ -445,26 +445,26 @@ void QgsBrowserDockWidget::addFavourite() if ( !dirItem ) return; - addFavouriteDirectory( dirItem->dirPath() ); + addFavoriteDirectory( dirItem->dirPath() ); } -void QgsBrowserDockWidget::addFavouriteDirectory() +void QgsBrowserDockWidget::addFavoriteDirectory() { - QString directory = QFileDialog::getExistingDirectory( this, tr( "Add directory to favourites" ) ); + QString directory = QFileDialog::getExistingDirectory( this, tr( "Add directory to favorites" ) ); if ( !directory.isEmpty() ) { - addFavouriteDirectory( directory ); + addFavoriteDirectory( directory ); } } -void QgsBrowserDockWidget::addFavouriteDirectory( const QString& favDir ) +void QgsBrowserDockWidget::addFavoriteDirectory( const QString& favDir ) { - mModel->addFavouriteDirectory( favDir ); + mModel->addFavoriteDirectory( favDir ); } -void QgsBrowserDockWidget::removeFavourite() +void QgsBrowserDockWidget::removeFavorite() { - mModel->removeFavourite( mProxyModel->mapToSource( mBrowserView->currentIndex() ) ); + mModel->removeFavorite( mProxyModel->mapToSource( mBrowserView->currentIndex() ) ); } void QgsBrowserDockWidget::refresh() diff --git a/src/app/qgsbrowserdockwidget.h b/src/app/qgsbrowserdockwidget.h index 1117410d2cc6..05328cedd8c5 100644 --- a/src/app/qgsbrowserdockwidget.h +++ b/src/app/qgsbrowserdockwidget.h @@ -106,15 +106,15 @@ class APP_EXPORT QgsBrowserDockWidget : public QgsDockWidget, private Ui::QgsBro public: explicit QgsBrowserDockWidget( const QString& name, QWidget *parent = nullptr ); ~QgsBrowserDockWidget(); - void addFavouriteDirectory( const QString& favDir ); + void addFavoriteDirectory( const QString& favDir ); public slots: void addLayerAtIndex( const QModelIndex& index ); void showContextMenu( QPoint ); - void addFavourite(); - void addFavouriteDirectory(); - void removeFavourite(); + void addFavorite(); + void addFavoriteDirectory(); + void removeFavorite(); void refresh(); diff --git a/src/core/qgsbrowsermodel.cpp b/src/core/qgsbrowsermodel.cpp index 1657b743e100..2b29ac91dfff 100644 --- a/src/core/qgsbrowsermodel.cpp +++ b/src/core/qgsbrowsermodel.cpp @@ -49,7 +49,7 @@ static bool cmpByDataItemName_( QgsDataItem* a, QgsDataItem* b ) QgsBrowserModel::QgsBrowserModel( QObject *parent ) : QAbstractItemModel( parent ) - , mFavourites( nullptr ) + , mFavorites( nullptr ) , mProjectHome( nullptr ) { connect( QgsProject::instance(), SIGNAL( readProject( const QDomDocument & ) ), this, SLOT( updateProjectHome() ) ); @@ -101,12 +101,12 @@ void QgsBrowserModel::addRootItems() connectItem( item ); mRootItems << item; - // add favourite directories - mFavourites = new QgsFavouritesItem( nullptr, tr( "Favourites" ) ); - if ( mFavourites ) + // add favorite directories + mFavorites = new QgsFavoritesItem( nullptr, tr( "Favorites" ) ); + if ( mFavorites ) { - connectItem( mFavourites ); - mRootItems << mFavourites; + connectItem( mFavorites ); + mRootItems << mFavorites; } // add drives @@ -530,19 +530,19 @@ void QgsBrowserModel::refresh( const QModelIndex& theIndex ) item->refresh(); } -void QgsBrowserModel::addFavouriteDirectory( const QString& favDir ) +void QgsBrowserModel::addFavoriteDirectory( const QString& directory ) { - Q_ASSERT( mFavourites ); - mFavourites->addDirectory( favDir ); + Q_ASSERT( mFavorites ); + mFavorites->addDirectory( directory ); } -void QgsBrowserModel::removeFavourite( const QModelIndex &index ) +void QgsBrowserModel::removeFavorite( const QModelIndex &index ) { QgsDirectoryItem *item = dynamic_cast( dataItem( index ) ); if ( !item ) return; - mFavourites->removeDirectory( item ); + mFavorites->removeDirectory( item ); } void QgsBrowserModel::hidePath( QgsDataItem *item ) diff --git a/src/core/qgsbrowsermodel.h b/src/core/qgsbrowsermodel.h index 3d4a2eb3d011..b514350d3aec 100644 --- a/src/core/qgsbrowsermodel.h +++ b/src/core/qgsbrowsermodel.h @@ -143,8 +143,20 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel void itemDataChanged( QgsDataItem * item ); void itemStateChanged( QgsDataItem * item, QgsDataItem::State oldState ); - void addFavouriteDirectory( const QString& favDir ); - void removeFavourite( const QModelIndex &index ); + /** + * Adds a directory to the favorites group. + * @note added in QGIS 3.0 + * @see removeFavorite() + */ + void addFavoriteDirectory( const QString& directory ); + + /** + * Removes a favorite directory from its corresponding model index. + * @note added in QGIS 3.0 + * @see addFavoriteDirectory() + */ + void removeFavorite( const QModelIndex &index ); + void updateProjectHome(); //! Hide the given path in the browser model @@ -156,7 +168,7 @@ class CORE_EXPORT QgsBrowserModel : public QAbstractItemModel void removeRootItems(); QVector mRootItems; - QgsFavouritesItem *mFavourites; + QgsFavoritesItem *mFavorites; QgsDirectoryItem *mProjectHome; }; diff --git a/src/core/qgsdataitem.cpp b/src/core/qgsdataitem.cpp index 783f6348e8d7..054a165c6359 100644 --- a/src/core/qgsdataitem.cpp +++ b/src/core/qgsdataitem.cpp @@ -182,7 +182,7 @@ const QIcon &QgsDataCollectionItem::iconDir() return icon; } -const QIcon &QgsFavouritesItem::iconFavourites() +const QIcon &QgsFavoritesItem::iconFavorites() { static QIcon icon; @@ -1100,21 +1100,21 @@ QgsErrorItem::~QgsErrorItem() { } -QgsFavouritesItem::QgsFavouritesItem( QgsDataItem* parent, const QString& name, const QString& path ) - : QgsDataCollectionItem( parent, name, QStringLiteral( "favourites:" ) ) +QgsFavoritesItem::QgsFavoritesItem( QgsDataItem* parent, const QString& name, const QString& path ) + : QgsDataCollectionItem( parent, name, QStringLiteral( "favorites:" ) ) { Q_UNUSED( path ); mCapabilities |= Fast; - mType = Favourites; + mType = Favorites; mIconName = QStringLiteral( "/mIconFavourites.png" ); populate(); } -QgsFavouritesItem::~QgsFavouritesItem() +QgsFavoritesItem::~QgsFavoritesItem() { } -QVector QgsFavouritesItem::createChildren() +QVector QgsFavoritesItem::createChildren() { QVector children; @@ -1129,7 +1129,7 @@ QVector QgsFavouritesItem::createChildren() return children; } -void QgsFavouritesItem::addDirectory( const QString& favDir ) +void QgsFavoritesItem::addDirectory( const QString& favDir ) { QSettings settings; QStringList favDirs = settings.value( QStringLiteral( "/browser/favourites" ) ).toStringList(); @@ -1146,7 +1146,7 @@ void QgsFavouritesItem::addDirectory( const QString& favDir ) } } -void QgsFavouritesItem::removeDirectory( QgsDirectoryItem *item ) +void QgsFavoritesItem::removeDirectory( QgsDirectoryItem *item ) { if ( !item ) return; @@ -1159,7 +1159,7 @@ void QgsFavouritesItem::removeDirectory( QgsDirectoryItem *item ) int idx = findItem( mChildren, item ); if ( idx < 0 ) { - QgsDebugMsg( QString( "favourites item %1 not found" ).arg( item->path() ) ); + QgsDebugMsg( QString( "favorites item %1 not found" ).arg( item->path() ) ); return; } @@ -1167,7 +1167,7 @@ void QgsFavouritesItem::removeDirectory( QgsDirectoryItem *item ) deleteChildItem( mChildren.at( idx ) ); } -QVector QgsFavouritesItem::createChildren( const QString& favDir ) +QVector QgsFavoritesItem::createChildren( const QString& favDir ) { QVector children; QString pathName = pathComponent( favDir ); diff --git a/src/core/qgsdataitem.h b/src/core/qgsdataitem.h index 3898d8d219f8..aea6f8ba3e2e 100644 --- a/src/core/qgsdataitem.h +++ b/src/core/qgsdataitem.h @@ -88,8 +88,8 @@ class CORE_EXPORT QgsDataItem : public QObject Directory, Layer, Error, - Favourites, - Project //! Represents a QGIS project + Favorites, //!< Represents a favorite item + Project //!< Represents a QGIS project }; //! Create new data item. @@ -436,7 +436,7 @@ class CORE_EXPORT QgsDirectoryItem : public QgsDataCollectionItem * @param parent * @param name directory name * @param dirPath path to directory in file system - * @param path item path in the tree, it may be dirPath or dirPath with some prefix, e.g. favourites: */ + * @param path item path in the tree, it may be dirPath or dirPath with some prefix, e.g. favorites: */ QgsDirectoryItem( QgsDataItem* parent, const QString& name, const QString& dirPath, const QString& path ); ~QgsDirectoryItem(); @@ -519,21 +519,38 @@ class CORE_EXPORT QgsDirectoryParamWidget : public QTreeWidget }; /** \ingroup core - * Contains various Favourites directories + * Contains various Favorites directories + * \note added in QGIS 3.0 */ -class CORE_EXPORT QgsFavouritesItem : public QgsDataCollectionItem +class CORE_EXPORT QgsFavoritesItem : public QgsDataCollectionItem { Q_OBJECT public: - QgsFavouritesItem( QgsDataItem* parent, const QString& name, const QString& path = QString() ); - ~QgsFavouritesItem(); + + /** + * Constructor for QgsFavoritesItem. Accepts a path argument specifying the file path associated with + * the item. + */ + QgsFavoritesItem( QgsDataItem* parent, const QString& name, const QString& path = QString() ); + + ~QgsFavoritesItem(); QVector createChildren() override; - void addDirectory( const QString& favIcon ); + /** + * Adds a new directory to the favorites group. + * @see removeDirectory() + */ + void addDirectory( const QString& directory ); + + /** + * Removes an existing directory from the favorites group. + * @see addDirectory() + */ void removeDirectory( QgsDirectoryItem *item ); - static const QIcon &iconFavourites(); + //! Icon for favorites group + static const QIcon &iconFavorites(); private: QVector createChildren( const QString& favDir ); diff --git a/src/gui/qgsbrowsertreeview.cpp b/src/gui/qgsbrowsertreeview.cpp index 208b3eeee6fe..3f3a1e2586be 100644 --- a/src/gui/qgsbrowsertreeview.cpp +++ b/src/gui/qgsbrowsertreeview.cpp @@ -91,8 +91,8 @@ void QgsBrowserTreeView::restoreState() } else { - // expand root favourites item - QModelIndex index = QgsBrowserModel::findPath( model(), QStringLiteral( "favourites:" ) ); + // expand root favorites item + QModelIndex index = QgsBrowserModel::findPath( model(), QStringLiteral( "favorites:" ) ); expand( index ); } } From d5698be69f2d5fc3e9eb02912ccfc2c358296d52 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 31 Oct 2016 09:12:39 +1000 Subject: [PATCH 533/897] Fix some processing breakage --- python/plugins/processing/gui/NumberInputPanel.py | 2 +- .../processing/modeler/ModelerParameterDefinitionDialog.py | 2 +- python/plugins/processing/tools/dataobjects.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index 92bc1f09f86a..0713be53526e 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -103,7 +103,7 @@ def showExpressionsBuilder(self): variables['%s_max' % name] = "Maximum value of %s" % desc variables['%s_avg' % name] = "Mean value of %s" % desc variables['%s_stddev' % name] = "Standard deviation of %s" % desc - for variable, desc in variables.iteritems(): + for variable, desc in variables.items(): dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 7d2a911be10b..ed1631b32653 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -179,7 +179,7 @@ def setupUi(self): if self.param is not None: self.minTextBox.setText(str(self.param.min)) self.maxTextBox.setText(str(self.param.max)) - self.horizontalLayoutDefault.addWidget(QLabel(self.tr('Default value'))) + self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 810d3a359881..6ad0318edd89 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -333,7 +333,7 @@ def exportVectorLayer(layer, supported=None): else: isASCII = True try: - str(layer.source()).decode('ascii') + str(layer.source()) except UnicodeEncodeError: isASCII = False if not os.path.splitext(layer.source())[1].lower() in supported or not isASCII: From 3caccd531dfd8317f27f6884cd058cb896ffab0c Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 31 Oct 2016 11:41:40 +1000 Subject: [PATCH 534/897] [processing] Fix handling of multiple field input in modeller --- python/plugins/processing/gui/wrappers.py | 54 ++++++++----------- .../ModelerParameterDefinitionDialog.py | 9 +++- 2 files changed, 29 insertions(+), 34 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 735cf1e40074..393bde645e88 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -755,24 +755,21 @@ class TableFieldWidgetWrapper(WidgetWrapper): def createWidget(self): self._layer = None - if self.param.multiple: - if self.dialogType == DIALOG_STANDARD: + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + if self.param.multiple: return MultipleInputPanel(options=[]) - else: - return QLineEdit() - else: - if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - widget = QComboBox() - return widget else: widget = QComboBox() - widget.setEditable(True) - fields = self.dialog.getAvailableValuesOfType(ParameterTableField, None) - if self.param.optional: - widget.addItem(self.NOT_SET, None) - for f in fields: - widget.addItem(self.dialog.resolveValueDescription(f), f) return widget + else: + widget = QComboBox() + widget.setEditable(True) + fields = self.dialog.getAvailableValuesOfType(ParameterTableField, None) + if self.param.optional: + widget.addItem(self.NOT_SET, None) + for f in fields: + widget.addItem(self.dialog.resolveValueDescription(f), f) + return widget def postInitialize(self, wrappers): for wrapper in wrappers: @@ -817,8 +814,8 @@ def getFields(self): return sorted(list(fieldNames), key=cmp_to_key(locale.strcoll)) def setValue(self, value): - if self.param.multiple: - if self.dialogType == DIALOG_STANDARD: + if self.dialogType == DIALOG_STANDARD: + if self.param.multiple: options = self.widget.options selected = [] for i, opt in enumerate(options): @@ -826,31 +823,22 @@ def setValue(self, value): selected.append(i) self.widget.setSelectedItems(selected) else: - self.widget.setText(value) - else: - if self.dialogType == DIALOG_STANDARD: self.setComboValue(value) + else: + self.setComboValue(value) def value(self): - if self.param.multiple: - if self.dialogType == DIALOG_STANDARD: + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + if self.param.multiple: return [self.widget.options[i] for i in self.widget.selectedoptions] - elif self.dialogType == DIALOG_BATCH: - return self.widget.text() else: - text = self.widget.text() - if not bool(text) and not self.param.optional: - raise InvalidParameterValue() - return text - else: - if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): if self.param.optional and self.widget.currentIndex() == 0: return None return self.widget.currentText() - else: - def validator(v): - return bool(v) or self.param.optional - return self.comboValue(validator) + else: + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) def GeometryPredicateWidgetWrapper(WidgetWrapper): diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 25e14fd04b76..d81b78384a28 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -144,6 +144,13 @@ def setupUi(self): datatypeIndex = self.param.datatype + 1 self.datatypeCombo.setCurrentIndex(datatypeIndex) + self.multipleCheck = QCheckBox() + self.multipleCheck.setText(self.tr('Accept multiple fields')) + self.multipleCheck.setChecked(False) + if self.param is not None: + self.multipleCheck.setChecked(self.param.multiple) + self.verticalLayout.addWidget(self.multipleCheck) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or isinstance(self.param, ParameterVector)): self.verticalLayout.addWidget(QLabel(self.tr('Shape type'))) @@ -269,7 +276,7 @@ def okPressed(self): return parent = self.parentCombo.itemData(self.parentCombo.currentIndex()) datatype = self.datatypeCombo.itemData(self.datatypeCombo.currentIndex()) - self.param = ParameterTableField(name, description, parent, datatype) + self.param = ParameterTableField(name, description, parent, datatype, multiple=self.multipleCheck.isChecked()) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or isinstance(self.param, ParameterRaster)): self.param = ParameterRaster( From bec379249e92be30fe66faec552b42748c2117e0 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 31 Oct 2016 10:53:13 +0700 Subject: [PATCH 535/897] [processing] sort model input parameters to avoid random ordering --- python/plugins/processing/modeler/ModelerAlgorithm.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index 321d70742e1a..15d5aafff6ec 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -276,6 +276,8 @@ def defineCharacteristics(self): for inp in list(self.inputs.values()): if inp.param not in self.parameters: self.parameters.append(inp.param) + self.parameters.sort(key=attrgetter("description")) + self.outputs = [] for alg in list(self.algs.values()): if alg.active: From b48d20220e5ef5591f3a66e78baabc6ed8852f97 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 31 Oct 2016 11:18:22 +0700 Subject: [PATCH 536/897] [processing] resurrect editing of modeler item on double-click --- python/plugins/processing/modeler/ModelerGraphicItem.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerGraphicItem.py b/python/plugins/processing/modeler/ModelerGraphicItem.py index 4c47816e2607..b0fdf6c7c1dc 100644 --- a/python/plugins/processing/modeler/ModelerGraphicItem.py +++ b/python/plugins/processing/modeler/ModelerGraphicItem.py @@ -132,8 +132,7 @@ def boundingRect(self): return rect def mouseDoubleClickEvent(self, event): - pass - #self.editElement() + self.editElement() def contextMenuEvent(self, event): if isinstance(self.element, ModelerOutput): From dd4b34ed16e0611b2e317788ed9364ef63b9d80f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 31 Oct 2016 14:37:12 +1000 Subject: [PATCH 537/897] [processing] Modeller should not be modal --- python/plugins/processing/ProcessingPlugin.py | 8 +++++--- .../plugins/processing/modeler/CreateNewModelAction.py | 8 +++++--- python/plugins/processing/modeler/EditModelAction.py | 8 +++++--- python/plugins/processing/modeler/ModelerDialog.py | 9 ++++----- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/python/plugins/processing/ProcessingPlugin.py b/python/plugins/processing/ProcessingPlugin.py index 577a38612fc5..459a52b39b6b 100644 --- a/python/plugins/processing/ProcessingPlugin.py +++ b/python/plugins/processing/ProcessingPlugin.py @@ -159,9 +159,11 @@ def openToolbox(self): def openModeler(self): dlg = ModelerDialog() - dlg.exec_() - if dlg.update: - algList.reloadProvider('model') + dlg.update_model.connect(self.updateModel) + dlg.show() + + def updateModel(self): + algList.reloadProvider('model') def openResults(self): dlg = ResultsDialog() diff --git a/python/plugins/processing/modeler/CreateNewModelAction.py b/python/plugins/processing/modeler/CreateNewModelAction.py index de2e6bd0a867..345570818f19 100644 --- a/python/plugins/processing/modeler/CreateNewModelAction.py +++ b/python/plugins/processing/modeler/CreateNewModelAction.py @@ -45,6 +45,8 @@ def getIcon(self): def execute(self): dlg = ModelerDialog() - dlg.exec_() - if dlg.update: - algList.reloadProvider('model') + dlg.update_model.connect(self.updateModel) + dlg.show() + + def updateModel(self): + algList.reloadProvider('model') diff --git a/python/plugins/processing/modeler/EditModelAction.py b/python/plugins/processing/modeler/EditModelAction.py index f89f203ebc52..b3942d068992 100644 --- a/python/plugins/processing/modeler/EditModelAction.py +++ b/python/plugins/processing/modeler/EditModelAction.py @@ -41,6 +41,8 @@ def isEnabled(self): def execute(self): dlg = ModelerDialog(self.itemData.getCopy()) - dlg.exec_() - if dlg.update: - algList.reloadProvider('model') + dlg.update_model.connect(self.updateModel) + dlg.show() + + def updateModel(self): + algList.reloadProvider('model') \ No newline at end of file diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index ad95e9ba5062..bf4abe0af996 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -31,7 +31,7 @@ import os from qgis.PyQt import uic -from qgis.PyQt.QtCore import Qt, QRectF, QMimeData, QPoint, QPointF, QSettings, QByteArray +from qgis.PyQt.QtCore import Qt, QRectF, QMimeData, QPoint, QPointF, QSettings, QByteArray, pyqtSignal from qgis.PyQt.QtWidgets import QGraphicsView, QTreeWidget, QMessageBox, QFileDialog, QTreeWidgetItem, QSizePolicy from qgis.PyQt.QtGui import QIcon, QImage, QPainter from qgis.core import QgsApplication @@ -57,6 +57,8 @@ class ModelerDialog(BASE, WIDGET): CANVAS_SIZE = 4000 + update_model = pyqtSignal() + def __init__(self, alg=None): super(ModelerDialog, self).__init__(None) self.setupUi(self) @@ -205,9 +207,6 @@ def _mimeDataAlgorithm(items): self.view.centerOn(0, 0) self.alg.setModelerView(self) self.help = None - # Indicates whether to update or not the toolbox after - # closing this dialog - self.update = False self.hasChanged = False @@ -339,7 +338,7 @@ def saveModel(self, saveAs): return fout.write(text) fout.close() - self.update = True + self.update_model.emit() self.bar.pushMessage("", "Model was correctly saved", level=QgsMessageBar.SUCCESS, duration=5) self.hasChanged = False From 24fbe1a080e567e2b01d9d1e9e7c8e005d951c7c Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 7 Oct 2016 17:34:54 +0800 Subject: [PATCH 538/897] Fix crash in node tool after deleting the whole geometry (fixes #15659) Made sure that both closestVertex() and closestSegment() return negative distance on error (e.g. with null or emtpy geometry). Also fixes snapping when dealing with layers with null/invalid geometries (cherry picked from commit c093d5188fad685c4a596ff23c27aad7d151dac2) --- python/core/geometry/qgsgeometry.sip | 2 +- src/app/nodetool/qgsmaptoolnodetool.cpp | 7 ++-- src/core/geometry/qgscircularstring.cpp | 3 ++ src/core/geometry/qgscurvepolygon.cpp | 2 +- src/core/geometry/qgsgeometry.cpp | 9 ++++-- src/core/geometry/qgsgeometry.h | 2 +- src/core/geometry/qgsgeometryutils.cpp | 1 + src/core/geometry/qgsgeometryutils.h | 8 +++-- src/core/geometry/qgslinestring.cpp | 10 ++---- src/core/qgspointlocator.cpp | 2 ++ tests/src/core/testqgsgeometry.cpp | 5 ++- tests/src/core/testqgspointlocator.cpp | 43 +++++++++++++++++++++++++ 12 files changed, 72 insertions(+), 22 deletions(-) diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index b7a3a762c05c..18a300952982 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -181,7 +181,7 @@ class QgsGeometry * @param afterVertex will be set to the vertex index of the next vertex after the closest one. Will be set to -1 if * not present. * @param sqrDist will be set to the square distance between the closest vertex and the specified point - * @returns closest point in geometry + * @returns closest point in geometry. If not found (empty geometry), returns null point nad sqrDist is negative. */ //TODO QGIS 3.0 - rename beforeVertex to previousVertex, afterVertex to nextVertex QgsPoint closestVertex( const QgsPoint& point, int& atVertex /Out/, int& beforeVertex /Out/, int& afterVertex /Out/, double& sqrDist /Out/ ) const; diff --git a/src/app/nodetool/qgsmaptoolnodetool.cpp b/src/app/nodetool/qgsmaptoolnodetool.cpp index 46efdaaed8c2..7015af367b39 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.cpp +++ b/src/app/nodetool/qgsmaptoolnodetool.cpp @@ -274,12 +274,11 @@ void QgsMapToolNodeTool::canvasPressEvent( QgsMapMouseEvent* e ) // 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 ); + double sqrDist; // will be negative on error + QgsPoint closestLayerVertex = mSelectedFeature->geometry()->closestVertex( layerCoordPoint, atVertex, beforeVertex, afterVertex, sqrDist ); mSnapper.snapToCurrentLayer( e->pos(), snapResults, QgsSnapper::SnapToVertex, tol ); - if ( dist <= tol ) + if ( sqrDist >= 0 && sqrt( sqrDist ) <= tol ) { // some vertex selected mMoving = true; diff --git a/src/core/geometry/qgscircularstring.cpp b/src/core/geometry/qgscircularstring.cpp index d28e9f131ff0..7ce639877755 100644 --- a/src/core/geometry/qgscircularstring.cpp +++ b/src/core/geometry/qgscircularstring.cpp @@ -861,6 +861,9 @@ double QgsCircularString::closestSegment( const QgsPointV2& pt, QgsPointV2& segm } } + if ( minDist == std::numeric_limits::max() ) + return -1; // error: no segments + segmentPt = minDistSegmentPoint; vertexAfter = minDistVertexAfter; vertexAfter.part = 0; diff --git a/src/core/geometry/qgscurvepolygon.cpp b/src/core/geometry/qgscurvepolygon.cpp index 6cc72d5c9071..cbae4223af69 100644 --- a/src/core/geometry/qgscurvepolygon.cpp +++ b/src/core/geometry/qgscurvepolygon.cpp @@ -657,7 +657,7 @@ double QgsCurvePolygon::closestSegment( const QgsPointV2& pt, QgsPointV2& segmen { if ( !mExteriorRing ) { - return 0.0; + return -1; } QList segmentList; segmentList.append( mExteriorRing ); diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index 8589f0c9b3c0..0a9bb0b285c0 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -369,6 +369,7 @@ QgsPoint QgsGeometry::closestVertex( const QgsPoint& point, int& atVertex, int& { if ( !d->geometry ) { + sqrDist = -1; return QgsPoint( 0, 0 ); } @@ -609,12 +610,14 @@ double QgsGeometry::closestVertexWithContext( const QgsPoint& point, int& atVert { if ( !d->geometry ) { - return 0.0; + return -1; } QgsVertexId vId; QgsPointV2 pt( point.x(), point.y() ); QgsPointV2 closestPoint = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, vId ); + if ( !vId.isValid() ) + return -1; atVertex = vertexNrFromVertexId( vId ); return QgsGeometryUtils::sqrDistance2D( closestPoint, pt ); } @@ -628,7 +631,7 @@ double QgsGeometry::closestSegmentWithContext( { if ( !d->geometry ) { - return 0; + return -1; } QgsPointV2 segmentPt; @@ -636,6 +639,8 @@ double QgsGeometry::closestSegmentWithContext( bool leftOfBool; double sqrDist = d->geometry->closestSegment( QgsPointV2( point.x(), point.y() ), segmentPt, vertexAfter, &leftOfBool, epsilon ); + if ( sqrDist < 0 ) + return -1; minDistPoint.setX( segmentPt.x() ); minDistPoint.setY( segmentPt.y() ); diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 1854adadaa09..a16e9a0543b5 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -225,7 +225,7 @@ class CORE_EXPORT QgsGeometry * @param afterVertex will be set to the vertex index of the next vertex after the closest one. Will be set to -1 if * not present. * @param sqrDist will be set to the square distance between the closest vertex and the specified point - * @returns closest point in geometry + * @returns closest point in geometry. If not found (empty geometry), returns null point nad sqrDist is negative. */ //TODO QGIS 3.0 - rename beforeVertex to previousVertex, afterVertex to nextVertex QgsPoint closestVertex( const QgsPoint& point, int& atVertex, int& beforeVertex, int& afterVertex, double& sqrDist ) const; diff --git a/src/core/geometry/qgsgeometryutils.cpp b/src/core/geometry/qgsgeometryutils.cpp index 7dcbb1d30af4..c4453c7631d5 100644 --- a/src/core/geometry/qgsgeometryutils.cpp +++ b/src/core/geometry/qgsgeometryutils.cpp @@ -65,6 +65,7 @@ QgsPointV2 QgsGeometryUtils::closestVertex( const QgsAbstractGeometry& geom, con double minDist = std::numeric_limits::max(); double currentDist = 0; QgsPointV2 minDistPoint; + id = QgsVertexId(); // set as invalid QgsVertexId vertexId; QgsPointV2 vertex; diff --git a/src/core/geometry/qgsgeometryutils.h b/src/core/geometry/qgsgeometryutils.h index 1f59e2f1ed36..ac5dd0f173e3 100644 --- a/src/core/geometry/qgsgeometryutils.h +++ b/src/core/geometry/qgsgeometryutils.h @@ -37,7 +37,8 @@ class CORE_EXPORT QgsGeometryUtils */ static QList extractLineStrings( const QgsAbstractGeometry* geom ); - /** Returns the closest vertex to a geometry for a specified point + /** Returns the closest vertex to a geometry for a specified point. + * On error null point will be returned and "id" argument will be invalid. */ static QgsPointV2 closestVertex( const QgsAbstractGeometry& geom, const QgsPointV2& pt, QgsVertexId& id ); @@ -263,7 +264,7 @@ class CORE_EXPORT QgsGeometryUtils for ( int i = 0; i < container.size(); ++i ) { sqrDist = container.at( i )->closestSegment( pt, segmentPt, vertexAfter, leftOf, epsilon ); - if ( sqrDist < minDist ) + if ( sqrDist >= 0 && sqrDist < minDist ) { minDist = sqrDist; minDistSegmentX = segmentPt.x(); @@ -293,6 +294,9 @@ class CORE_EXPORT QgsGeometryUtils } } + if ( minDist == std::numeric_limits::max() ) + return -1; // error: no segments + segmentPt.setX( minDistSegmentX ); segmentPt.setY( minDistSegmentY ); vertexAfter = minDistVertexAfter; diff --git a/src/core/geometry/qgslinestring.cpp b/src/core/geometry/qgslinestring.cpp index 50211d520cfc..d5cfcda65b20 100644 --- a/src/core/geometry/qgslinestring.cpp +++ b/src/core/geometry/qgslinestring.cpp @@ -763,16 +763,10 @@ double QgsLineString::closestSegment( const QgsPointV2& pt, QgsPointV2& segmentP double segmentPtX, segmentPtY; int size = mX.size(); - if ( size == 0 ) + if ( size == 0 || size == 1 ) { vertexAfter = QgsVertexId( 0, 0, 0 ); - return sqrDist; - } - else if ( size == 1 ) - { - segmentPt = pointN( 0 ); - vertexAfter = QgsVertexId( 0, 0, 1 ); - return QgsGeometryUtils::sqrDistance2D( pt, segmentPt ); + return -1; } for ( int i = 1; i < size; ++i ) { diff --git a/src/core/qgspointlocator.cpp b/src/core/qgspointlocator.cpp index 0022e8373a7d..7d36f149a654 100644 --- a/src/core/qgspointlocator.cpp +++ b/src/core/qgspointlocator.cpp @@ -106,6 +106,8 @@ class QgsPointLocator_VisitorNearestVertex : public IVisitor int vertexIndex, beforeVertex, afterVertex; double sqrDist; QgsPoint pt = geom->closestVertex( mSrcPoint, vertexIndex, beforeVertex, afterVertex, sqrDist ); + if ( sqrDist < 0 ) + return; // probably empty geometry QgsPointLocator::Match m( QgsPointLocator::Vertex, mLocator->mLayer, id, sqrt( sqrDist ), pt, vertexIndex ); // in range queries the filter may reject some matches diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index d170f894d3fb..ac0f1247f720 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -2047,11 +2047,10 @@ void TestQgsGeometry::lineString() //closest segment QgsLineString l35; bool leftOf = false; + p = QgsPointV2(); // reset all coords to zero ( void )l35.closestSegment( QgsPointV2( 1, 2 ), p, v, 0, 0 ); //empty line, just want no crash l35.setPoints( QgsPointSequence() << QgsPointV2( 5, 10 ) ); - QVERIFY( qgsDoubleNear( l35.closestSegment( QgsPointV2( 5, 10 ), p, v, 0, 0 ), 0 ) ); - QCOMPARE( p, QgsPointV2( 5, 10 ) ); - QCOMPARE( v, QgsVertexId( 0, 0, 1 ) ); + QVERIFY( l35.closestSegment( QgsPointV2( 5, 10 ), p, v, 0, 0 ) < 0 ); l35.setPoints( QgsPointSequence() << QgsPointV2( 5, 10 ) << QgsPointV2( 10, 10 ) ); QVERIFY( qgsDoubleNear( l35.closestSegment( QgsPointV2( 4, 11 ), p, v, &leftOf, 0 ), 2.0 ) ); QCOMPARE( p, QgsPointV2( 5, 10 ) ); diff --git a/tests/src/core/testqgspointlocator.cpp b/tests/src/core/testqgspointlocator.cpp index 15c351ac82fc..206f90c13ec0 100644 --- a/tests/src/core/testqgspointlocator.cpp +++ b/tests/src/core/testqgspointlocator.cpp @@ -23,6 +23,7 @@ #include "qgsgeometry.h" #include "qgsmaplayerregistry.h" #include "qgspointlocator.h" +#include "qgspolygon.h" struct FilterExcludePoint : public QgsPointLocator::MatchFilter @@ -261,6 +262,48 @@ class TestQgsPointLocator : public QObject QVERIFY( m2.isValid() ); QCOMPARE( m2.point(), QgsPoint( 1, 1 ) ); } + + void testNullGeometries() + { + QgsVectorLayer* vlNullGeom = new QgsVectorLayer( "Polygon", "x", "memory" ); + QgsFeature ff( 0 ); + ff.setGeometry( QgsGeometry() ); + QgsFeatureList flist; + flist << ff; + vlNullGeom->dataProvider()->addFeatures( flist ); + + QgsPointLocator loc( vlNullGeom, 0, nullptr ); + + QgsPointLocator::Match m1 = loc.nearestVertex( QgsPoint( 2, 2 ), std::numeric_limits::max() ); + QVERIFY( !m1.isValid() ); + + QgsPointLocator::Match m2 = loc.nearestEdge( QgsPoint( 2, 2 ), std::numeric_limits::max() ); + QVERIFY( !m2.isValid() ); + + delete vlNullGeom; + } + + void testEmptyGeometries() + { + QgsVectorLayer* vlEmptyGeom = new QgsVectorLayer( "Polygon", "x", "memory" ); + QgsFeature ff( 0 ); + QgsGeometry g; + g.setGeometry( new QgsPolygonV2() ); + ff.setGeometry( g ); + QgsFeatureList flist; + flist << ff; + vlEmptyGeom->dataProvider()->addFeatures( flist ); + + QgsPointLocator loc( vlEmptyGeom, 0, nullptr ); + + QgsPointLocator::Match m1 = loc.nearestVertex( QgsPoint( 2, 2 ), std::numeric_limits::max() ); + QVERIFY( !m1.isValid() ); + + QgsPointLocator::Match m2 = loc.nearestEdge( QgsPoint( 2, 2 ), std::numeric_limits::max() ); + QVERIFY( !m2.isValid() ); + + delete vlEmptyGeom; + } }; QTEST_MAIN( TestQgsPointLocator ) From a3186f80bc5e3a14b0bdca9b400bc117695e3098 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 14 Oct 2016 11:17:36 +0800 Subject: [PATCH 539/897] Fix layer tree expanded state when used expand/collapse all (fixes #15691) (cherry picked from commit de85fdd6e8fa3d4f38196376aabccce317cbf341) --- python/gui/layertree/qgslayertreeview.sip | 8 ++++ src/app/qgisapp.cpp | 4 +- src/gui/layertree/qgslayertreeview.cpp | 46 +++++++++++++++++++++++ src/gui/layertree/qgslayertreeview.h | 8 ++++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/python/gui/layertree/qgslayertreeview.sip b/python/gui/layertree/qgslayertreeview.sip index af1f53979bdd..636a27604c60 100644 --- a/python/gui/layertree/qgslayertreeview.sip +++ b/python/gui/layertree/qgslayertreeview.sip @@ -72,6 +72,14 @@ class QgsLayerTreeView : QTreeView //! Force refresh of layer symbology. Normally not needed as the changes of layer's renderer are monitored by the model void refreshLayerSymbology( const QString& layerId ); + //! Enhancement of QTreeView::expandAll() that also records expanded state in layer tree nodes + //! @note added in QGIS 2.18 + void expandAllNodes(); + + //! Enhancement of QTreeView::collapseAll() that also records expanded state in layer tree nodes + //! @note added in QGIS 2.18 + void collapseAllNodes(); + signals: //! Emitted when a current layer is changed void currentLayerChanged( QgsMapLayer* layer ); diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index e16288697117..0cb0e10abc85 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -3104,11 +3104,11 @@ void QgisApp::initLayerTreeView() QAction* actionExpandAll = new QAction( tr( "Expand All" ), this ); actionExpandAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionExpandTree.svg" ) ) ); actionExpandAll->setToolTip( tr( "Expand All" ) ); - connect( actionExpandAll, SIGNAL( triggered( bool ) ), mLayerTreeView, SLOT( expandAll() ) ); + connect( actionExpandAll, SIGNAL( triggered( bool ) ), mLayerTreeView, SLOT( expandAllNodes() ) ); QAction* actionCollapseAll = new QAction( tr( "Collapse All" ), this ); actionCollapseAll->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCollapseTree.svg" ) ) ); actionCollapseAll->setToolTip( tr( "Collapse All" ) ); - connect( actionCollapseAll, SIGNAL( triggered( bool ) ), mLayerTreeView, SLOT( collapseAll() ) ); + connect( actionCollapseAll, SIGNAL( triggered( bool ) ), mLayerTreeView, SLOT( collapseAllNodes() ) ); QWidget* spacer = new QWidget(); spacer->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); diff --git a/src/gui/layertree/qgslayertreeview.cpp b/src/gui/layertree/qgslayertreeview.cpp index 2b3a32acadba..536eca939efa 100644 --- a/src/gui/layertree/qgslayertreeview.cpp +++ b/src/gui/layertree/qgslayertreeview.cpp @@ -336,3 +336,49 @@ void QgsLayerTreeView::refreshLayerSymbology( const QString& layerId ) if ( nodeLayer ) layerTreeModel()->refreshLayerLegend( nodeLayer ); } + + +static void _expandAllLegendNodes( QgsLayerTreeLayer* nodeLayer, bool expanded, QgsLayerTreeModel* model ) +{ + // for layers we also need to find out with legend nodes contain some children and make them expanded/collapsed + // if we are collapsing, we just write out an empty list + QStringList lst; + if ( expanded ) + { + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer ) ) + { + QString parentKey = legendNode->data( QgsLayerTreeModelLegendNode::ParentRuleKeyRole ).toString(); + if ( !parentKey.isEmpty() && !lst.contains( parentKey ) ) + lst << parentKey; + } + } + nodeLayer->setCustomProperty( "expandedLegendNodes", lst ); +} + + +static void _expandAllNodes( QgsLayerTreeGroup* parent, bool expanded, QgsLayerTreeModel* model ) +{ + Q_FOREACH ( QgsLayerTreeNode* node, parent->children() ) + { + node->setExpanded( expanded ); + if ( QgsLayerTree::isGroup( node ) ) + _expandAllNodes( QgsLayerTree::toGroup( node ), expanded, model ); + else if ( QgsLayerTree::isLayer( node ) ) + _expandAllLegendNodes( QgsLayerTree::toLayer( node ), expanded, model ); + } +} + + +void QgsLayerTreeView::expandAllNodes() +{ + // unfortunately expandAll() does not emit expanded() signals + _expandAllNodes( layerTreeModel()->rootGroup(), true, layerTreeModel() ); + expandAll(); +} + +void QgsLayerTreeView::collapseAllNodes() +{ + // unfortunately collapseAll() does not emit collapsed() signals + _expandAllNodes( layerTreeModel()->rootGroup(), false, layerTreeModel() ); + collapseAll(); +} diff --git a/src/gui/layertree/qgslayertreeview.h b/src/gui/layertree/qgslayertreeview.h index e04adbdcc482..e0e5040c0b28 100644 --- a/src/gui/layertree/qgslayertreeview.h +++ b/src/gui/layertree/qgslayertreeview.h @@ -92,6 +92,14 @@ class GUI_EXPORT QgsLayerTreeView : public QTreeView //! Force refresh of layer symbology. Normally not needed as the changes of layer's renderer are monitored by the model void refreshLayerSymbology( const QString& layerId ); + //! Enhancement of QTreeView::expandAll() that also records expanded state in layer tree nodes + //! @note added in QGIS 2.18 + void expandAllNodes(); + + //! Enhancement of QTreeView::collapseAll() that also records expanded state in layer tree nodes + //! @note added in QGIS 2.18 + void collapseAllNodes(); + signals: //! Emitted when a current layer is changed void currentLayerChanged( QgsMapLayer* layer ); From fa3663907a706971bbc418a1896b48a14f572327 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 31 Oct 2016 15:22:24 +1000 Subject: [PATCH 540/897] Fix 'enable macros' button does not run open macro (fix #9523) --- src/app/qgisapp.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 0cb0e10abc85..f12eed934a7b 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -4970,8 +4970,6 @@ bool QgisApp::addProject( const QString& projectFile ) btnEnableMacros->setStyleSheet( QStringLiteral( "background-color: rgba(255, 255, 255, 0); color: black; text-decoration: underline;" ) ); btnEnableMacros->setCursor( Qt::PointingHandCursor ); btnEnableMacros->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Preferred ); - connect( btnEnableMacros, SIGNAL( clicked() ), mInfoBar, SLOT( popWidget() ) ); - connect( btnEnableMacros, SIGNAL( clicked() ), this, SLOT( enableProjectMacros() ) ); QgsMessageBarItem *macroMsg = new QgsMessageBarItem( tr( "Security warning" ), @@ -4980,6 +4978,13 @@ bool QgisApp::addProject( const QString& projectFile ) QgsMessageBar::WARNING, 0, mInfoBar ); + + connect( btnEnableMacros, &QToolButton::clicked, [this,macroMsg] + { + enableProjectMacros(); + mInfoBar->popWidget( macroMsg ); + } ); + // display the macros notification widget mInfoBar->pushItem( macroMsg ); } From 8e663309c0671f2779828a3ec26081bd59414f1e Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 31 Oct 2016 12:53:42 +0700 Subject: [PATCH 541/897] [processing] remove console error message when optional otb provider not installed --- python/plugins/processing/algs/otb/OTBAlgorithmProvider.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/python/plugins/processing/algs/otb/OTBAlgorithmProvider.py b/python/plugins/processing/algs/otb/OTBAlgorithmProvider.py index 48768ceada0d..5b33250fbbdd 100644 --- a/python/plugins/processing/algs/otb/OTBAlgorithmProvider.py +++ b/python/plugins/processing/algs/otb/OTBAlgorithmProvider.py @@ -61,8 +61,6 @@ def _loadAlgorithms(self): version = OTBUtils.getInstalledVersion(True) if version is None: - ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, - self.tr('Problem with OTB installation: OTB was not found or is not correctly installed')) return folder = OTBUtils.compatibleDescriptionPath(version) From f438542fe7a4208da9f9f9687e438178b6fa2584 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 09:43:14 +0100 Subject: [PATCH 542/897] Break oneliners --- src/core/qgsexpression.cpp | 47 ++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index bcb414afb047..864343a851ca 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -108,21 +108,36 @@ static QVariant tvl2variant( TVL v ) inline bool isIntSafe( const QVariant& v ) { - if ( v.type() == QVariant::Int ) return true; - if ( v.type() == QVariant::UInt ) return true; - if ( v.type() == QVariant::LongLong ) return true; - if ( v.type() == QVariant::ULongLong ) return true; - if ( v.type() == QVariant::Double ) return false; - if ( v.type() == QVariant::String ) { bool ok; v.toString().toInt( &ok ); return ok; } + if ( v.type() == QVariant::Int ) + return true; + if ( v.type() == QVariant::UInt ) + return true; + if ( v.type() == QVariant::LongLong ) + return true; + if ( v.type() == QVariant::ULongLong ) + return true; + if ( v.type() == QVariant::Double ) + return false; + if ( v.type() == QVariant::String ) + { + bool ok; + v.toString().toInt( &ok ); + return ok; + } return false; } inline bool isDoubleSafe( const QVariant& v ) { - if ( v.type() == QVariant::Double ) return true; - if ( v.type() == QVariant::Int ) return true; - if ( v.type() == QVariant::UInt ) return true; - if ( v.type() == QVariant::LongLong ) return true; - if ( v.type() == QVariant::ULongLong ) return true; + if ( v.type() == QVariant::Double ) + return true; + if ( v.type() == QVariant::Int ) + return true; + if ( v.type() == QVariant::UInt ) + return true; + if ( v.type() == QVariant::LongLong ) + return true; + if ( v.type() == QVariant::ULongLong ) + return true; if ( v.type() == QVariant::String ) { bool ok; @@ -135,8 +150,9 @@ inline bool isDoubleSafe( const QVariant& v ) inline bool isDateTimeSafe( const QVariant& v ) { - return v.type() == QVariant::DateTime || v.type() == QVariant::Date || - v.type() == QVariant::Time; + return v.type() == QVariant::DateTime + || v.type() == QVariant::Date + || v.type() == QVariant::Time; } inline bool isIntervalSafe( const QVariant& v ) @@ -153,7 +169,10 @@ inline bool isIntervalSafe( const QVariant& v ) return false; } -inline bool isNull( const QVariant& v ) { return v.isNull(); } +inline bool isNull( const QVariant& v ) +{ + return v.isNull(); +} /////////////////////////////////////////////// // evaluation error macros From 1b2158d854870334a34278dc1c6776fa10205880 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 09:46:09 +0100 Subject: [PATCH 543/897] Fix caching aggregate expressions with @parent usage --- src/core/qgsexpression.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 864343a851ca..8798be510d1a 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -701,8 +701,12 @@ static QVariant fcnAggregate( const QVariantList& values, const QgsExpressionCon { QString cacheKey = QStringLiteral( "aggfcn:%1:%2:%3:%4" ).arg( vl->id(), QString::number( aggregate ), subExpression, parameters.filter ); + QgsExpression subExp( subExpression ); QgsExpression filterExp( parameters.filter ); - if ( filterExp.referencedVariables().contains( "parent" ) || filterExp.referencedVariables().contains( QString() ) ) + if ( filterExp.referencedVariables().contains( "parent" ) + || filterExp.referencedVariables().contains( QString() ) + || subExp.referencedVariables().contains( "parent" ) + || subExp.referencedVariables().contains( QString() ) ) { cacheKey += ':' + qHash( context->feature() ); } From e7333f68145f27a74aacd8f75939623e37fc4510 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 12:14:23 +0100 Subject: [PATCH 544/897] [ogr] Ignore request limit if unable to compile expression Fix #15771 --- src/providers/ogr/qgsogrfeatureiterator.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index 0c97a4f48ee9..3b91834de953 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -149,6 +149,9 @@ QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool OGR_L_SetAttributeFilter( ogrLayer, nullptr ); } + if ( !mExpressionCompiled ) + mRequest.setLimit( -1 ); + //start with first feature rewind(); } From 25e983436dad4b69cf538dd9dde8ecfbdabde0cf Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 13:03:28 +0100 Subject: [PATCH 545/897] Revert "[ogr] Ignore request limit if unable to compile expression" This reverts commit e7333f68145f27a74aacd8f75939623e37fc4510. --- src/providers/ogr/qgsogrfeatureiterator.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/providers/ogr/qgsogrfeatureiterator.cpp b/src/providers/ogr/qgsogrfeatureiterator.cpp index 3b91834de953..0c97a4f48ee9 100644 --- a/src/providers/ogr/qgsogrfeatureiterator.cpp +++ b/src/providers/ogr/qgsogrfeatureiterator.cpp @@ -149,9 +149,6 @@ QgsOgrFeatureIterator::QgsOgrFeatureIterator( QgsOgrFeatureSource* source, bool OGR_L_SetAttributeFilter( ogrLayer, nullptr ); } - if ( !mExpressionCompiled ) - mRequest.setLimit( -1 ); - //start with first feature rewind(); } From 6d387650f4b41f55393acb2747466dcbcaa38645 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 14:24:34 +0100 Subject: [PATCH 546/897] More test for referencedVariables --- tests/src/core/testqgsexpression.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 6f9ad7c4bf28..59b97ff88b1e 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1578,8 +1578,14 @@ class TestQgsExpression: public QObject void referenced_variables() { QSet expectedVars; - expectedVars << QStringLiteral( "foo" ) << QStringLiteral( "bar" ) << QStringLiteral( "ppp" ) << QStringLiteral( "qqq" ) << QStringLiteral( "rrr" ); - QgsExpression exp( QStringLiteral( "CASE WHEN intersects(@bar, $geometry) THEN @ppp ELSE @qqq * @rrr END + @foo IN (1, 2, 3)" ) ); + expectedVars << QStringLiteral( "foo" ) + << QStringLiteral( "bar" ) + << QStringLiteral( "ppp" ) + << QStringLiteral( "qqq" ) + << QStringLiteral( "rrr" ) + << QStringLiteral( "sss" ) + << QStringLiteral( "ttt" ); + QgsExpression exp( QStringLiteral( "CASE WHEN intersects(@bar, $geometry) THEN @ppp ELSE @qqq * @rrr END + @foo IN (1, 2, @sss) OR @ttt" ) ); QCOMPARE( exp.hasParserError(), false ); QSet refVar = exp.referencedVariables(); From cc6b1e33912be66d8dedafacab59332546c72527 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 14:25:35 +0100 Subject: [PATCH 547/897] Fix @parent variable detection in aggregate subExpression --- src/core/qgsexpression.cpp | 43 +++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 8798be510d1a..4f339e6582d2 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3670,14 +3670,22 @@ const QList& QgsExpression::Functions() if ( !node ) return true; - if ( !node->args() || node->args()->count() < 4 ) + if ( !node->args() ) return false; - else + + QSet referencedVars; + if ( node->args()->count() > 2 ) + { + QgsExpression::Node* subExpressionNode = node->args()->at( 2 ); + referencedVars = subExpressionNode->referencedVariables(); + } + + if ( node->args()->count() > 3 ) { QgsExpression::Node* filterNode = node->args()->at( 3 ); - QSet referencedVars = filterNode->referencedVariables(); - return referencedVars.contains( "parent" ) || referencedVars.contains( QString() ); + referencedVars = filterNode->referencedVariables(); } + return referencedVars.contains( "parent" ) || referencedVars.contains( QString() ); }, []( const QgsExpression::NodeFunction* node ) { @@ -3686,18 +3694,29 @@ const QList& QgsExpression::Functions() if ( !node ) return QSet() << QgsFeatureRequest::AllAttributes; - if ( !node->args() || node->args()->count() < 4 ) + if ( !node->args() ) return QSet(); - else + + QSet referencedCols; + QSet referencedVars; + + if ( node->args()->count() > 2 ) + { + QgsExpression::Node* subExpressionNode = node->args()->at( 2 ); + referencedVars = subExpressionNode->referencedVariables(); + referencedCols = subExpressionNode->referencedColumns(); + } + if ( node->args()->count() > 3 ) { QgsExpression::Node* filterNode = node->args()->at( 3 ); - QSet referencedVars = filterNode->referencedVariables(); - - if ( referencedVars.contains( "parent" ) || referencedVars.contains( QString() ) ) - return QSet() << QgsFeatureRequest::AllAttributes; - else - return QSet(); + referencedVars = filterNode->referencedVariables(); + referencedCols.unite( filterNode->referencedColumns() ); } + + if ( referencedVars.contains( "parent" ) || referencedVars.contains( QString() ) ) + return QSet() << QgsFeatureRequest::AllAttributes; + else + return referencedCols; }, true ) From 7d2098cdf4f77e81ec2099d128e3343a2df527f8 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 15:18:56 +0100 Subject: [PATCH 548/897] Followup cc6b1e3: also respect subexp vars in presence of filter --- src/core/qgsexpression.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 4f339e6582d2..f572d22d3a8f 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -3683,7 +3683,7 @@ const QList& QgsExpression::Functions() if ( node->args()->count() > 3 ) { QgsExpression::Node* filterNode = node->args()->at( 3 ); - referencedVars = filterNode->referencedVariables(); + referencedVars.unite( filterNode->referencedVariables() ); } return referencedVars.contains( "parent" ) || referencedVars.contains( QString() ); }, From bb9c75b39443a86bd1419081d9847c35ed0e8c27 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Mon, 31 Oct 2016 17:10:58 +0100 Subject: [PATCH 549/897] [OGR provider] Make addAttributes() return the requested field type, precision and width so as to make QgsVectorLayerEditBuffer::commitChanges() API Fixes #15614 --- src/providers/ogr/qgsogrprovider.cpp | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 6c18aaec6829..550494994887 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -1348,10 +1348,12 @@ bool QgsOgrProvider::addAttributes( const QList &attributes ) bool returnvalue = true; - QMap< QString, QVariant::Type > mapFieldTypesToPatch; + QMap< QString, QgsField > mapFieldNameToOriginalField; for ( QList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter ) { + mapFieldNameToOriginalField[ iter->name()] = *iter; + OGRFieldType type; switch ( iter->type() ) @@ -1367,7 +1369,6 @@ bool QgsOgrProvider::addAttributes( const QList &attributes ) type = OFTInteger64; else { - mapFieldTypesToPatch[ iter->name()] = iter->type(); type = OFTReal; } break; @@ -1410,13 +1411,23 @@ bool QgsOgrProvider::addAttributes( const QList &attributes ) } loadFields(); - // Patch field type in case of Integer64->Real mapping so that QVariant::LongLong - // is still returned to the caller - for ( QMap< QString, QVariant::Type >::const_iterator it = mapFieldTypesToPatch.begin(); it != mapFieldTypesToPatch.end(); ++it ) + // The check in QgsVectorLayerEditBuffer::commitChanges() is questionable with + // real-world drivers that might only be able to satisfy request only partially. + // So to avoid erroring out, patch field type, width and precision to match + // what was requested. + // For example in case of Integer64->Real mapping so that QVariant::LongLong is + // still returned to the caller + // Or if a field width was specified but not strictly enforced by the driver (#15614) + for ( QMap< QString, QgsField >::const_iterator it = mapFieldNameToOriginalField.begin(); + it != mapFieldNameToOriginalField.end(); ++it ) { int idx = mAttributeFields.lookupField( it.key() ); if ( idx >= 0 ) - mAttributeFields[ idx ].setType( *it ); + { + mAttributeFields[ idx ].setType( it->type() ); + mAttributeFields[ idx ].setLength( it->length() ); + mAttributeFields[ idx ].setPrecision( it->precision() ); + } } return returnvalue; From 08218de5f414fb0c0b718ed5232b6be133de60e3 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Mon, 31 Oct 2016 19:44:34 +0100 Subject: [PATCH 550/897] [OGR provider] Use constBegin() / constEnd() --- src/providers/ogr/qgsogrprovider.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 550494994887..d2c30a2a5042 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -1350,7 +1350,7 @@ bool QgsOgrProvider::addAttributes( const QList &attributes ) QMap< QString, QgsField > mapFieldNameToOriginalField; - for ( QList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter ) + for ( QList::const_iterator iter = attributes.constBegin(); iter != attributes.constEnd(); ++iter ) { mapFieldNameToOriginalField[ iter->name()] = *iter; @@ -1418,8 +1418,8 @@ bool QgsOgrProvider::addAttributes( const QList &attributes ) // For example in case of Integer64->Real mapping so that QVariant::LongLong is // still returned to the caller // Or if a field width was specified but not strictly enforced by the driver (#15614) - for ( QMap< QString, QgsField >::const_iterator it = mapFieldNameToOriginalField.begin(); - it != mapFieldNameToOriginalField.end(); ++it ) + for ( QMap< QString, QgsField >::const_iterator it = mapFieldNameToOriginalField.constBegin(); + it != mapFieldNameToOriginalField.constEnd(); ++it ) { int idx = mAttributeFields.lookupField( it.key() ); if ( idx >= 0 ) From 70d7ce163edd1dc52dd4dbf579e2f6ff4c2a7a72 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 08:44:55 +1000 Subject: [PATCH 551/897] Describe some dependancy changes in API break docs --- doc/api_break.dox | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/doc/api_break.dox b/doc/api_break.dox index 36ec9dcd9ae1..1fb5b53c42b6 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -21,6 +21,31 @@ This page tries to maintain a list with incompatible changes that happened in pr QGIS 3.0 {#qgis_api_break_3_0} ======== +Version 3.0 brings changes to many underlying dependancies which QGIS is built upon. Any existing PyQGIS code will +need to be updated to address the changes made within these libraries. + +Python 3.0 +---------- + +QGIS 3.0 introduces a move to Python 3. This version brings many changes to both the Python language and individual Python +libraries. A good place to start learning about the changes involved, and how to port your code to Python 3, is available +in the official Python documentation: [Porting Python 2 Code to Python 3](https://docs.python.org/3/howto/pyporting.html). + +Qt 5 +---- + +QGIS 3.0 is based off version 5 of the underlying Qt libraries. Many changes and API breaks were introduced in Qt5. While +it is c++ specific, a good place to read about the major changes introduced in Qt5 is at the Qt docs: +[C++ API changes](http://doc.qt.io/qt-5/sourcebreaks.html) + + +PyQt 5 +------ + +Together with the Python and Qt version changes, the PyQt libraries which expose Qt classes to Python have also had their +version bumped to PyQt 5. The changes introduced in PyQt 5 and the steps required to upgrade existing code are summarised at: +[Differences Between PyQt4 and PyQt5](http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html) + Moved Classes {#qgis_api_break_3_0_moved_classes} ------------- From 47109d13b7d5c8f6e7e1299d18a2a5ce643883d4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 11:08:50 +1000 Subject: [PATCH 552/897] Flip some connects to new style --- doc/api_break.dox | 6 +- .../core/symbology-ng/qgscptcityarchive.sip | 6 -- src/app/qgisapp.cpp | 2 +- src/core/layertree/qgslayertreemodel.cpp | 2 +- src/core/qgsmaplayer.cpp | 2 +- src/core/qgstransactiongroup.cpp | 12 ++-- src/core/qgsvectorlayer.cpp | 67 ++++++++----------- src/core/qgsvectorlayercache.cpp | 22 +++--- src/core/qgsvectorlayereditbuffer.cpp | 2 +- src/core/qgsvectorlayerjoinbuffer.cpp | 10 +-- src/core/raster/qgsrasterlayer.cpp | 10 +-- src/core/symbology-ng/qgscptcityarchive.cpp | 53 ++++----------- src/core/symbology-ng/qgscptcityarchive.h | 6 -- src/core/symbology-ng/qgssvgcache.cpp | 2 +- 14 files changed, 75 insertions(+), 127 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 1fb5b53c42b6..3b709f16f23a 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -603,13 +603,17 @@ QgsCptCityColorRampDialog {#qgis_api_break_3_0_QgsCptCityColorRampDialog} and the new ramp can be retrieved after executing the dialog by calling ramp(). - Some internal methods which were previously public or protected were made private. +QgsCptCityDataItem {#qgis_api_break_3_0_QgsCptCityDataItem} +----------------------- + +- emitBeginInsertItems, emitEndInsertItems, emitBeginRemoveItems and emitEndRemoveItems were removed. There +should be no need to call these slots manually. QgsCptCitySelectionItem {#qgis_api_break_3_0_QgsCptCitySelectionItem} ----------------------- - parseXML() has been renamed to parseXml() - QgsCRSCache {#qgis_api_break_3_0_QgsCRSCache} ----------- diff --git a/python/core/symbology-ng/qgscptcityarchive.sip b/python/core/symbology-ng/qgscptcityarchive.sip index 9453acc425aa..ab758d032ac9 100644 --- a/python/core/symbology-ng/qgscptcityarchive.sip +++ b/python/core/symbology-ng/qgscptcityarchive.sip @@ -129,12 +129,6 @@ class QgsCptCityDataItem : QObject bool isValid(); - public slots: - void emitBeginInsertItems( QgsCptCityDataItem* parent, int first, int last ); - void emitEndInsertItems(); - void emitBeginRemoveItems( QgsCptCityDataItem* parent, int first, int last ); - void emitEndRemoveItems(); - signals: void beginInsertItems( QgsCptCityDataItem* parent, int first, int last ); void endInsertItems(); diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index f12eed934a7b..e932c78e1869 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -10249,7 +10249,7 @@ void QgisApp::layersWereAdded( const QList& theLayers ) connect( rlayer, SIGNAL( drawingProgress( int, int ) ), this, SLOT( showProgress( int, int ) ) ); // connect up any request the raster may make to update the statusbar message - connect( rlayer, SIGNAL( statusChanged( QString ) ), this, SLOT( showStatusMessage( QString ) ) ); + connect( rlayer, &QgsRasterLayer::statusChanged, this, &QgisApp::showStatusMessage ); provider = rlayer->dataProvider(); } diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index 2fc0cf86be07..27079883e650 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -837,7 +837,7 @@ void QgsLayerTreeModel::connectToLayer( QgsLayerTreeLayer* nodeLayer ) } QgsMapLayer* layer = nodeLayer->layer(); - connect( layer, SIGNAL( legendChanged() ), this, SLOT( layerLegendChanged() ), Qt::UniqueConnection ); + connect( layer, &QgsMapLayer::legendChanged, this, &QgsLayerTreeModel::layerLegendChanged, Qt::UniqueConnection ); if ( layer->type() == QgsMapLayer::VectorLayer ) { diff --git a/src/core/qgsmaplayer.cpp b/src/core/qgsmaplayer.cpp index 31fde2814f97..00dee9bd355e 100644 --- a/src/core/qgsmaplayer.cpp +++ b/src/core/qgsmaplayer.cpp @@ -1649,7 +1649,7 @@ void QgsMapLayer::setLegend( QgsMapLayerLegend* legend ) mLegend = legend; if ( mLegend ) - connect( mLegend, SIGNAL( itemsChanged() ), this, SIGNAL( legendChanged() ) ); + connect( mLegend, &QgsMapLayerLegend::itemsChanged, this, &QgsMapLayer::legendChanged ); emit legendChanged(); } diff --git a/src/core/qgstransactiongroup.cpp b/src/core/qgstransactiongroup.cpp index 94ae4700f813..486c9fc8e014 100644 --- a/src/core/qgstransactiongroup.cpp +++ b/src/core/qgstransactiongroup.cpp @@ -53,8 +53,8 @@ bool QgsTransactionGroup::addLayer( QgsVectorLayer* layer ) mLayers.insert( layer ); - connect( layer, SIGNAL( beforeEditingStarted() ), this, SLOT( onEditingStarted() ) ); - connect( layer, SIGNAL( destroyed() ), this, SLOT( onLayerDeleted() ) ); + connect( layer, &QgsVectorLayer::beforeEditingStarted, this, &QgsTransactionGroup::onEditingStarted ); + connect( layer, &QgsVectorLayer::destroyed, this, &QgsTransactionGroup::onLayerDeleted ); return true; } @@ -88,8 +88,8 @@ void QgsTransactionGroup::onEditingStarted() { mTransaction->addLayer( layer ); layer->startEditing(); - connect( layer, SIGNAL( beforeCommitChanges() ), this, SLOT( onCommitChanges() ) ); - connect( layer, SIGNAL( beforeRollBack() ), this, SLOT( onRollback() ) ); + connect( layer, &QgsVectorLayer::beforeCommitChanges, this, &QgsTransactionGroup::onCommitChanges ); + connect( layer, &QgsVectorLayer::beforeRollBack, this, &QgsTransactionGroup::onRollback ); } } @@ -160,8 +160,8 @@ void QgsTransactionGroup::disableTransaction() Q_FOREACH ( QgsVectorLayer* layer, mLayers ) { - disconnect( layer, SIGNAL( beforeCommitChanges() ), this, SLOT( onCommitChanges() ) ); - disconnect( layer, SIGNAL( beforeRollBack() ), this, SLOT( onRollback() ) ); + disconnect( layer, &QgsVectorLayer::beforeCommitChanges, this, &QgsTransactionGroup::onCommitChanges ); + disconnect( layer, &QgsVectorLayer::beforeRollBack, this, &QgsTransactionGroup::onRollback ); } } diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 8c0782feb4da..a020a4409d32 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -157,7 +157,7 @@ QgsVectorLayer::QgsVectorLayer( const QString& vectorLayerPath, connect( this, SIGNAL( selectionChanged( QgsFeatureIds, QgsFeatureIds, bool ) ), this, SIGNAL( selectionChanged() ) ); connect( this, SIGNAL( selectionChanged( QgsFeatureIds, QgsFeatureIds, bool ) ), this, SIGNAL( repaintRequested() ) ); - connect( QgsProject::instance()->relationManager(), SIGNAL( relationsLoaded() ), this, SLOT( onRelationsLoaded() ) ); + connect( QgsProject::instance()->relationManager(), &QgsRelationManager::relationsLoaded, this, &QgsVectorLayer::onRelationsLoaded ); // Default simplify drawing settings QSettings settings; @@ -1329,30 +1329,21 @@ bool QgsVectorLayer::startEditing() mEditBuffer = new QgsVectorLayerEditBuffer( this ); } // forward signals - connect( mEditBuffer, SIGNAL( layerModified() ), this, SLOT( invalidateSymbolCountedFlag() ) ); - connect( mEditBuffer, SIGNAL( layerModified() ), this, SIGNAL( layerModified() ) ); // TODO[MD]: necessary? + connect( mEditBuffer, &QgsVectorLayerEditBuffer::layerModified, this, &QgsVectorLayer::invalidateSymbolCountedFlag ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::layerModified, this, &QgsVectorLayer::layerModified ); // TODO[MD]: necessary? //connect( mEditBuffer, SIGNAL( layerModified() ), this, SLOT( triggerRepaint() ) ); // TODO[MD]: works well? - connect( mEditBuffer, SIGNAL( featureAdded( QgsFeatureId ) ), this, SIGNAL( featureAdded( QgsFeatureId ) ) ); - connect( mEditBuffer, SIGNAL( featureDeleted( QgsFeatureId ) ), this, SLOT( onFeatureDeleted( QgsFeatureId ) ) ); - connect( mEditBuffer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ) ); - connect( mEditBuffer, SIGNAL( attributeValueChanged( QgsFeatureId, int, QVariant ) ), this, SIGNAL( attributeValueChanged( QgsFeatureId, int, QVariant ) ) ); - connect( mEditBuffer, SIGNAL( attributeAdded( int ) ), this, SIGNAL( attributeAdded( int ) ) ); - connect( mEditBuffer, SIGNAL( attributeDeleted( int ) ), this, SIGNAL( attributeDeleted( int ) ) ); - - connect( mEditBuffer, SIGNAL( committedAttributesDeleted( const QString &, const QgsAttributeList & ) ), - this, SIGNAL( committedAttributesDeleted( const QString &, const QgsAttributeList & ) ) ); - - connect( mEditBuffer, SIGNAL( committedAttributesAdded( const QString &, const QList & ) ), - this, SIGNAL( committedAttributesAdded( const QString &, const QList & ) ) ); - - connect( mEditBuffer, SIGNAL( committedFeaturesAdded( QString, QgsFeatureList ) ), this, SIGNAL( committedFeaturesAdded( QString, QgsFeatureList ) ) ); - connect( mEditBuffer, SIGNAL( committedFeaturesRemoved( QString, QgsFeatureIds ) ), this, SIGNAL( committedFeaturesRemoved( QString, QgsFeatureIds ) ) ); - - connect( mEditBuffer, SIGNAL( committedAttributeValuesChanges( const QString &, const QgsChangedAttributesMap & ) ), - this, SIGNAL( committedAttributeValuesChanges( const QString &, const QgsChangedAttributesMap & ) ) ); - - connect( mEditBuffer, SIGNAL( committedGeometriesChanges( const QString &, const QgsGeometryMap & ) ), - this, SIGNAL( committedGeometriesChanges( const QString &, const QgsGeometryMap & ) ) ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::featureAdded, this, &QgsVectorLayer::featureAdded ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::featureDeleted, this, &QgsVectorLayer::onFeatureDeleted ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::geometryChanged, this, &QgsVectorLayer::geometryChanged ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::attributeValueChanged, this, &QgsVectorLayer::attributeValueChanged ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::attributeAdded, this, &QgsVectorLayer::attributeAdded ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::attributeDeleted, this, &QgsVectorLayer::attributeDeleted ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::committedAttributesDeleted, this, &QgsVectorLayer::committedAttributesDeleted ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::committedAttributesAdded, this, &QgsVectorLayer::committedAttributesAdded ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::committedFeaturesAdded, this, &QgsVectorLayer::committedFeaturesAdded ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::committedFeaturesRemoved, this, &QgsVectorLayer::committedFeaturesRemoved ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::committedAttributeValuesChanges, this, &QgsVectorLayer::committedAttributeValuesChanges ); + connect( mEditBuffer, &QgsVectorLayerEditBuffer::committedGeometriesChanges, this, &QgsVectorLayer::committedGeometriesChanges ); updateFields(); @@ -1416,7 +1407,7 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) if ( !mJoinBuffer ) { mJoinBuffer = new QgsVectorLayerJoinBuffer( this ); - connect( mJoinBuffer, SIGNAL( joinedFieldsChanged() ), this, SLOT( onJoinedFieldsChanged() ) ); + connect( mJoinBuffer, &QgsVectorLayerJoinBuffer::joinedFieldsChanged, this, &QgsVectorLayer::onJoinedFieldsChanged ); } mJoinBuffer->readXml( layer_node ); @@ -1525,7 +1516,7 @@ bool QgsVectorLayer::setDataProvider( QString const & provider ) return false; } - connect( mDataProvider, SIGNAL( raiseError( QString ) ), this, SIGNAL( raiseError( QString ) ) ); + connect( mDataProvider, &QgsVectorDataProvider::raiseError, this, &QgsVectorLayer::raiseError ); QgsDebugMsg( "Instantiated the data provider plugin" ); @@ -1537,13 +1528,13 @@ bool QgsVectorLayer::setDataProvider( QString const & provider ) } // TODO: Check if the provider has the capability to send fullExtentCalculated - connect( mDataProvider, SIGNAL( fullExtentCalculated() ), this, SLOT( updateExtents() ) ); + connect( mDataProvider, &QgsVectorDataProvider::fullExtentCalculated, this, &QgsVectorLayer::updateExtents ); // get and store the feature type mWkbType = mDataProvider->wkbType(); mJoinBuffer = new QgsVectorLayerJoinBuffer( this ); - connect( mJoinBuffer, SIGNAL( joinedFieldsChanged() ), this, SLOT( onJoinedFieldsChanged() ) ); + connect( mJoinBuffer, &QgsVectorLayerJoinBuffer::joinedFieldsChanged, this, &QgsVectorLayer::onJoinedFieldsChanged ); mExpressionFieldBuffer = new QgsExpressionFieldBuffer(); updateFields(); @@ -4165,11 +4156,11 @@ bool QgsVectorLayer::setDependencies( const QSet& oDeps ) QgsVectorLayer* lyr = static_cast( QgsMapLayerRegistry::instance()->mapLayer( dep.layerId() ) ); if ( lyr == nullptr ) continue; - disconnect( lyr, SIGNAL( featureAdded( QgsFeatureId ) ), this, SIGNAL( dataChanged() ) ); - disconnect( lyr, SIGNAL( featureDeleted( QgsFeatureId ) ), this, SIGNAL( dataChanged() ) ); - disconnect( lyr, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SIGNAL( dataChanged() ) ); - disconnect( lyr, SIGNAL( dataChanged() ), this, SIGNAL( dataChanged() ) ); - disconnect( lyr, SIGNAL( repaintRequested() ), this, SLOT( triggerRepaint() ) ); + disconnect( lyr, &QgsVectorLayer::featureAdded, this, &QgsVectorLayer::dataChanged ); + disconnect( lyr, &QgsVectorLayer::featureDeleted, this, &QgsVectorLayer::dataChanged ); + disconnect( lyr, &QgsVectorLayer::geometryChanged, this, &QgsVectorLayer::dataChanged ); + disconnect( lyr, &QgsVectorLayer::dataChanged, this, &QgsVectorLayer::dataChanged ); + disconnect( lyr, &QgsVectorLayer::repaintRequested, this, &QgsVectorLayer::triggerRepaint ); } // assign new dependencies @@ -4185,11 +4176,11 @@ bool QgsVectorLayer::setDependencies( const QSet& oDeps ) QgsVectorLayer* lyr = static_cast( QgsMapLayerRegistry::instance()->mapLayer( dep.layerId() ) ); if ( lyr == nullptr ) continue; - connect( lyr, SIGNAL( featureAdded( QgsFeatureId ) ), this, SIGNAL( dataChanged() ) ); - connect( lyr, SIGNAL( featureDeleted( QgsFeatureId ) ), this, SIGNAL( dataChanged() ) ); - connect( lyr, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SIGNAL( dataChanged() ) ); - connect( lyr, SIGNAL( dataChanged() ), this, SIGNAL( dataChanged() ) ); - connect( lyr, SIGNAL( repaintRequested() ), this, SLOT( triggerRepaint() ) ); + connect( lyr, &QgsVectorLayer::featureAdded, this, &QgsVectorLayer::dataChanged ); + connect( lyr, &QgsVectorLayer::featureDeleted, this, &QgsVectorLayer::dataChanged ); + connect( lyr, &QgsVectorLayer::geometryChanged, this, &QgsVectorLayer::dataChanged ); + connect( lyr, &QgsVectorLayer::dataChanged, this, &QgsVectorLayer::dataChanged ); + connect( lyr, &QgsVectorLayer::repaintRequested, this, &QgsVectorLayer::triggerRepaint ); } // if new layers are present, emit a data change diff --git a/src/core/qgsvectorlayercache.cpp b/src/core/qgsvectorlayercache.cpp index c46cb8e899cc..74a8ef7c6cdb 100644 --- a/src/core/qgsvectorlayercache.cpp +++ b/src/core/qgsvectorlayercache.cpp @@ -26,18 +26,18 @@ QgsVectorLayerCache::QgsVectorLayerCache( QgsVectorLayer* layer, int cacheSize, { mCache.setMaxCost( cacheSize ); - connect( mLayer, SIGNAL( featureDeleted( QgsFeatureId ) ), SLOT( featureDeleted( QgsFeatureId ) ) ); - connect( mLayer, SIGNAL( featureAdded( QgsFeatureId ) ), SLOT( onFeatureAdded( QgsFeatureId ) ) ); - connect( mLayer, SIGNAL( destroyed() ), SLOT( layerDeleted() ) ); + connect( mLayer, &QgsVectorLayer::featureDeleted, this, &QgsVectorLayerCache::featureDeleted ); + connect( mLayer, &QgsVectorLayer::featureAdded, this, &QgsVectorLayerCache::onFeatureAdded ); + connect( mLayer, &QgsVectorLayer::destroyed, this, &QgsVectorLayerCache::layerDeleted ); setCacheGeometry( true ); setCacheSubsetOfAttributes( mLayer->attributeList() ); setCacheAddedAttributes( true ); - connect( mLayer, SIGNAL( attributeDeleted( int ) ), SLOT( attributeDeleted( int ) ) ); - connect( mLayer, SIGNAL( updatedFields() ), SLOT( invalidate() ) ); - connect( mLayer, SIGNAL( dataChanged() ), SLOT( invalidate() ) ); - connect( mLayer, SIGNAL( attributeValueChanged( QgsFeatureId, int, const QVariant& ) ), SLOT( onAttributeValueChanged( QgsFeatureId, int, const QVariant& ) ) ); + connect( mLayer, &QgsVectorLayer::attributeDeleted, this, &QgsVectorLayerCache::attributeDeleted ); + connect( mLayer, &QgsVectorLayer::updatedFields, this, &QgsVectorLayerCache::invalidate ); + connect( mLayer, &QgsVectorLayer::dataChanged, this, &QgsVectorLayerCache::invalidate ); + connect( mLayer, &QgsVectorLayer::attributeValueChanged, this, &QgsVectorLayerCache::onAttributeValueChanged ); } QgsVectorLayerCache::~QgsVectorLayerCache() @@ -61,11 +61,11 @@ void QgsVectorLayerCache::setCacheGeometry( bool cacheGeometry ) mCacheGeometry = cacheGeometry && mLayer->hasGeometryType(); if ( cacheGeometry ) { - connect( mLayer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), SLOT( geometryChanged( QgsFeatureId, const QgsGeometry& ) ) ); + connect( mLayer, &QgsVectorLayer::geometryChanged, this, &QgsVectorLayerCache::geometryChanged ); } else { - disconnect( mLayer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SLOT( geometryChanged( QgsFeatureId, const QgsGeometry& ) ) ); + disconnect( mLayer, &QgsVectorLayer::geometryChanged, this, &QgsVectorLayerCache::geometryChanged ); } } @@ -124,11 +124,11 @@ void QgsVectorLayerCache::setCacheAddedAttributes( bool cacheAddedAttributes ) { if ( cacheAddedAttributes ) { - connect( mLayer, SIGNAL( attributeAdded( int ) ), SLOT( attributeAdded( int ) ) ); + connect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsVectorLayerCache::attributeAdded ); } else { - disconnect( mLayer, SIGNAL( attributeAdded( int ) ), this, SLOT( attributeAdded( int ) ) ); + disconnect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsVectorLayerCache::attributeAdded ); } } diff --git a/src/core/qgsvectorlayereditbuffer.cpp b/src/core/qgsvectorlayereditbuffer.cpp index 72c9fb8072a1..7ff4a097324b 100644 --- a/src/core/qgsvectorlayereditbuffer.cpp +++ b/src/core/qgsvectorlayereditbuffer.cpp @@ -37,7 +37,7 @@ template void mapToReversedLists( const QMap< Key, T >& map QgsVectorLayerEditBuffer::QgsVectorLayerEditBuffer( QgsVectorLayer* layer ) : L( layer ) { - connect( L->undoStack(), SIGNAL( indexChanged( int ) ), this, SLOT( undoIndexChanged( int ) ) ); // TODO[MD]: queued? + connect( L->undoStack(), &QUndoStack::indexChanged, this, &QgsVectorLayerEditBuffer::undoIndexChanged ); // TODO[MD]: queued? } QgsVectorLayerEditBuffer::~QgsVectorLayerEditBuffer() diff --git a/src/core/qgsvectorlayerjoinbuffer.cpp b/src/core/qgsvectorlayerjoinbuffer.cpp index e9b734493e88..c69d7ede161a 100644 --- a/src/core/qgsvectorlayerjoinbuffer.cpp +++ b/src/core/qgsvectorlayerjoinbuffer.cpp @@ -89,8 +89,8 @@ bool QgsVectorLayerJoinBuffer::addJoin( const QgsVectorJoinInfo& joinInfo ) // Unique connection makes sure we do not respond to one layer's update more times (in case of multiple join) if ( QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( joinInfo.joinLayerId ) ) ) { - connect( vl, SIGNAL( updatedFields() ), this, SLOT( joinedLayerUpdatedFields() ), Qt::UniqueConnection ); - connect( vl, SIGNAL( layerModified() ), this, SLOT( joinedLayerModified() ), Qt::UniqueConnection ); + connect( vl, &QgsVectorLayer::updatedFields, this, &QgsVectorLayerJoinBuffer::joinedLayerUpdatedFields, Qt::UniqueConnection ); + connect( vl, &QgsVectorLayer::layerModified, this, &QgsVectorLayerJoinBuffer::joinedLayerModified, Qt::UniqueConnection ); } emit joinedFieldsChanged(); @@ -113,7 +113,7 @@ bool QgsVectorLayerJoinBuffer::removeJoin( const QString& joinLayerId ) if ( QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( joinLayerId ) ) ) { - disconnect( vl, SIGNAL( updatedFields() ), this, SLOT( joinedLayerUpdatedFields() ) ); + disconnect( vl, &QgsVectorLayer::updatedFields, this, &QgsVectorLayerJoinBuffer::joinedLayerUpdatedFields ); } emit joinedFieldsChanged(); @@ -273,8 +273,8 @@ void QgsVectorLayerJoinBuffer::createJoinCaches() // make sure we are connected to the joined layer if ( QgsVectorLayer* vl = qobject_cast( QgsMapLayerRegistry::instance()->mapLayer( joinIt->joinLayerId ) ) ) { - connect( vl, SIGNAL( updatedFields() ), this, SLOT( joinedLayerUpdatedFields() ), Qt::UniqueConnection ); - connect( vl, SIGNAL( layerModified() ), this, SLOT( joinedLayerModified() ), Qt::UniqueConnection ); + connect( vl, &QgsVectorLayer::updatedFields, this, &QgsVectorLayerJoinBuffer::joinedLayerUpdatedFields, Qt::UniqueConnection ); + connect( vl, &QgsVectorLayer::layerModified, this, &QgsVectorLayerJoinBuffer::joinedLayerModified, Qt::UniqueConnection ); } } } diff --git a/src/core/raster/qgsrasterlayer.cpp b/src/core/raster/qgsrasterlayer.cpp index 4260760814fa..febade81ce4f 100644 --- a/src/core/raster/qgsrasterlayer.cpp +++ b/src/core/raster/qgsrasterlayer.cpp @@ -818,16 +818,10 @@ void QgsRasterLayer::setDataProvider( QString const & provider ) mLastModified = lastModified( mDataSource ); // Connect provider signals - connect( - mDataProvider, SIGNAL( progress( int, double, QString ) ), - this, SLOT( onProgress( int, double, QString ) ) - ); + connect( mDataProvider, &QgsRasterDataProvider::progress, this, &QgsRasterLayer::onProgress ); // Do a passthrough for the status bar text - connect( - mDataProvider, SIGNAL( statusChanged( QString ) ), - this, SIGNAL( statusChanged( QString ) ) - ); + connect( mDataProvider, &QgsRasterDataProvider::statusChanged, this, &QgsRasterLayer::statusChanged ); //mark the layer as valid mValid = true; diff --git a/src/core/symbology-ng/qgscptcityarchive.cpp b/src/core/symbology-ng/qgscptcityarchive.cpp index 4d90e47dcf43..342bccd4715a 100644 --- a/src/core/symbology-ng/qgscptcityarchive.cpp +++ b/src/core/symbology-ng/qgscptcityarchive.cpp @@ -508,23 +508,6 @@ QgsCptCityDataItem::~QgsCptCityDataItem() // QgsDebugMsg( "mName = " + mName + " mPath = " + mPath ); } -void QgsCptCityDataItem::emitBeginInsertItems( QgsCptCityDataItem* parent, int first, int last ) -{ - emit beginInsertItems( parent, first, last ); -} -void QgsCptCityDataItem::emitEndInsertItems() -{ - emit endInsertItems(); -} -void QgsCptCityDataItem::emitBeginRemoveItems( QgsCptCityDataItem* parent, int first, int last ) -{ - emit beginRemoveItems( parent, first, last ); -} -void QgsCptCityDataItem::emitEndRemoveItems() -{ - emit endRemoveItems(); -} - QVector QgsCptCityDataItem::createChildren() { QVector children; @@ -607,14 +590,10 @@ void QgsCptCityDataItem::addChildItem( QgsCptCityDataItem * child, bool refresh mChildren.insert( i, child ); - connect( child, SIGNAL( beginInsertItems( QgsCptCityDataItem*, int, int ) ), - this, SLOT( emitBeginInsertItems( QgsCptCityDataItem*, int, int ) ) ); - connect( child, SIGNAL( endInsertItems() ), - this, SLOT( emitEndInsertItems() ) ); - connect( child, SIGNAL( beginRemoveItems( QgsCptCityDataItem*, int, int ) ), - this, SLOT( emitBeginRemoveItems( QgsCptCityDataItem*, int, int ) ) ); - connect( child, SIGNAL( endRemoveItems() ), - this, SLOT( emitEndRemoveItems() ) ); + connect( child, &QgsCptCityDataItem::beginInsertItems, this, &QgsCptCityDataItem::beginInsertItems ); + connect( child, &QgsCptCityDataItem::endInsertItems, this, &QgsCptCityDataItem::endInsertItems ); + connect( child, &QgsCptCityDataItem::beginRemoveItems, this, &QgsCptCityDataItem::beginRemoveItems ); + connect( child, &QgsCptCityDataItem::endRemoveItems, this, &QgsCptCityDataItem::endRemoveItems ); if ( refresh ) emit endInsertItems(); @@ -638,14 +617,10 @@ QgsCptCityDataItem * QgsCptCityDataItem::removeChildItem( QgsCptCityDataItem * c emit beginRemoveItems( this, i, i ); mChildren.remove( i ); emit endRemoveItems(); - disconnect( child, SIGNAL( beginInsertItems( QgsCptCityDataItem*, int, int ) ), - this, SLOT( emitBeginInsertItems( QgsCptCityDataItem*, int, int ) ) ); - disconnect( child, SIGNAL( endInsertItems() ), - this, SLOT( emitEndInsertItems() ) ); - disconnect( child, SIGNAL( beginRemoveItems( QgsCptCityDataItem*, int, int ) ), - this, SLOT( emitBeginRemoveItems( QgsCptCityDataItem*, int, int ) ) ); - disconnect( child, SIGNAL( endRemoveItems() ), - this, SLOT( emitEndRemoveItems() ) ); + disconnect( child, &QgsCptCityDataItem::beginInsertItems, this, &QgsCptCityDataItem::beginInsertItems ); + disconnect( child, &QgsCptCityDataItem::endInsertItems, this, &QgsCptCityDataItem::endInsertItems ); + disconnect( child, &QgsCptCityDataItem::beginRemoveItems, this, &QgsCptCityDataItem::beginRemoveItems ); + disconnect( child, &QgsCptCityDataItem::endRemoveItems, this, &QgsCptCityDataItem::endRemoveItems ); child->setParent( nullptr ); return child; } @@ -1668,14 +1643,10 @@ void QgsCptCityBrowserModel::endRemoveItems() } void QgsCptCityBrowserModel::connectItem( QgsCptCityDataItem* item ) { - connect( item, SIGNAL( beginInsertItems( QgsCptCityDataItem*, int, int ) ), - this, SLOT( beginInsertItems( QgsCptCityDataItem*, int, int ) ) ); - connect( item, SIGNAL( endInsertItems() ), - this, SLOT( endInsertItems() ) ); - connect( item, SIGNAL( beginRemoveItems( QgsCptCityDataItem*, int, int ) ), - this, SLOT( beginRemoveItems( QgsCptCityDataItem*, int, int ) ) ); - connect( item, SIGNAL( endRemoveItems() ), - this, SLOT( endRemoveItems() ) ); + connect( item, &QgsCptCityDataItem::beginInsertItems, this, &QgsCptCityBrowserModel::beginInsertItems ); + connect( item, &QgsCptCityDataItem::endInsertItems, this, &QgsCptCityBrowserModel::endInsertItems ); + connect( item, &QgsCptCityDataItem::beginRemoveItems, this, &QgsCptCityBrowserModel::beginRemoveItems ); + connect( item, &QgsCptCityDataItem::endRemoveItems, this, &QgsCptCityBrowserModel::endRemoveItems ); } bool QgsCptCityBrowserModel::canFetchMore( const QModelIndex & parent ) const diff --git a/src/core/symbology-ng/qgscptcityarchive.h b/src/core/symbology-ng/qgscptcityarchive.h index 14639e4b49bf..a94e61f12bcb 100644 --- a/src/core/symbology-ng/qgscptcityarchive.h +++ b/src/core/symbology-ng/qgscptcityarchive.h @@ -188,12 +188,6 @@ class CORE_EXPORT QgsCptCityDataItem : public QObject QIcon mIcon; bool mValid; - public slots: - void emitBeginInsertItems( QgsCptCityDataItem* parent, int first, int last ); - void emitEndInsertItems(); - void emitBeginRemoveItems( QgsCptCityDataItem* parent, int first, int last ); - void emitEndRemoveItems(); - signals: void beginInsertItems( QgsCptCityDataItem* parent, int first, int last ); void endInsertItems(); diff --git a/src/core/symbology-ng/qgssvgcache.cpp b/src/core/symbology-ng/qgssvgcache.cpp index ab36f84630fe..bf16b9262a62 100644 --- a/src/core/symbology-ng/qgssvgcache.cpp +++ b/src/core/symbology-ng/qgssvgcache.cpp @@ -430,7 +430,7 @@ QByteArray QgsSvgCache::getImageData( const QString &path ) const request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); reply = QgsNetworkAccessManager::instance()->get( request ); - connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( downloadProgress( qint64, qint64 ) ) ); + connect( reply, &QNetworkReply::downloadProgress, this, &QgsSvgCache::downloadProgress ); //emit statusChanged( tr( "Downloading svg." ) ); From 6b120a86007ca6abf47138bced5c30d22db0767b Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Thu, 20 Oct 2016 16:38:27 +0800 Subject: [PATCH 553/897] Fix display of diagram legend entries (fixes #15448) To make the implementation saner, the legend node that may be embedded within parent layer node is kept separately from activeNodes. (cherry picked from commit b385ebd9ba9272516eed61e5825a603fcee969e9) --- python/core/layertree/qgslayertreemodel.sip | 10 ++- src/app/composer/qgscomposerlegendwidget.cpp | 5 +- src/app/qgsmapthemes.cpp | 6 +- src/core/layertree/qgslayertreemodel.cpp | 86 +++++++++++--------- src/core/layertree/qgslayertreemodel.h | 22 ++++- src/core/qgslegendrenderer.cpp | 3 +- src/gui/layertree/qgslayertreeview.cpp | 6 +- 7 files changed, 83 insertions(+), 55 deletions(-) diff --git a/python/core/layertree/qgslayertreemodel.sip b/python/core/layertree/qgslayertreemodel.sip index 8454f5214023..705ba3813021 100644 --- a/python/core/layertree/qgslayertreemodel.sip +++ b/python/core/layertree/qgslayertreemodel.sip @@ -92,15 +92,21 @@ class QgsLayerTreeModel : QAbstractItemModel QModelIndex legendNode2index( QgsLayerTreeModelLegendNode* legendNode ); //! Return filtered list of active legend nodes attached to a particular layer node + //! (by default it returns also legend node embedded in parent layer node (if any) unless skipNodeEmbeddedInParent is true) //! @note added in 2.6 + //! @note skipNodeEmbeddedInParent added in 2.18 //! @see layerOriginalLegendNodes() - QList layerLegendNodes( QgsLayerTreeLayer* nodeLayer ); + QList layerLegendNodes( QgsLayerTreeLayer* nodeLayer, bool skipNodeEmbeddedInParent = false ); //! Return original (unfiltered) list of legend nodes attached to a particular layer node //! @note added in 2.14 //! @see layerLegendNodes() QList layerOriginalLegendNodes( QgsLayerTreeLayer* nodeLayer ); + //! Return legend node that may be embbeded in parent (i.e. its icon will be used for layer's icon). + //! @note added in 2.18 + QgsLayerTreeModelLegendNode* legendNodeEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; + /** Searches through the layer tree to find a legend node with a matching layer ID * and rule key. * @param layerId map layer ID @@ -233,8 +239,6 @@ class QgsLayerTreeModel : QAbstractItemModel QVariant legendNodeData( QgsLayerTreeModelLegendNode* node, int role ) const; Qt::ItemFlags legendNodeFlags( QgsLayerTreeModelLegendNode* node ) const; bool legendEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; - /** Return legend node that may be embbeded in parent (i.e. its icon will be used for layer's icon). */ - QgsLayerTreeModelLegendNode* legendNodeEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; QIcon legendIconEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; void legendCleanup(); void legendInvalidateMapBasedData(); diff --git a/src/app/composer/qgscomposerlegendwidget.cpp b/src/app/composer/qgscomposerlegendwidget.cpp index 00462649b19c..92b7f489bca2 100644 --- a/src/app/composer/qgscomposerlegendwidget.cpp +++ b/src/app/composer/qgscomposerlegendwidget.cpp @@ -1006,9 +1006,8 @@ void QgsComposerLegendWidget::on_mItemTreeView_doubleClicked( const QModelIndex currentNode->setCustomProperty( QStringLiteral( "legend/title-label" ), newText ); // force update of label of the legend node with embedded icon (a bit clumsy i know) - QList nodes = model->layerLegendNodes( QgsLayerTree::toLayer( currentNode ) ); - if ( nodes.count() == 1 && nodes[0]->isEmbeddedInParent() ) - nodes[0]->setUserLabel( QString() ); + if ( QgsLayerTreeModelLegendNode* embeddedNode = model->legendNodeEmbeddedInParent( QgsLayerTree::toLayer( currentNode ) ) ) + embeddedNode->setUserLabel( QString() ); } else if ( legendNode ) { diff --git a/src/app/qgsmapthemes.cpp b/src/app/qgsmapthemes.cpp index 5408ce012f33..24bc4f0149d9 100644 --- a/src/app/qgsmapthemes.cpp +++ b/src/app/qgsmapthemes.cpp @@ -68,7 +68,7 @@ void QgsMapThemes::addPerLayerCheckedLegendSymbols( QgsMapThemeCollection::MapTh bool hasCheckableItems = false; bool someItemsUnchecked = false; QSet checkedItems; - Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer ) ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer, true ) ) { if ( legendNode->flags() & Qt::ItemIsUserCheckable ) { @@ -217,7 +217,7 @@ void QgsMapThemes::applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const { const QSet& checkedNodes = rec.perLayerCheckedLegendSymbols().value( nodeLayer->layerId() ); // some nodes are not checked - Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer ) ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer, true ) ) { Qt::CheckState shouldHaveState = checkedNodes.contains( legendNode->data( QgsLayerTreeModelLegendNode::RuleKeyRole ).toString() ) ? Qt::Checked : Qt::Unchecked; if (( legendNode->flags() & Qt::ItemIsUserCheckable ) && @@ -228,7 +228,7 @@ void QgsMapThemes::applyStateToLayerTreeGroup( QgsLayerTreeGroup* parent, const else { // all nodes should be checked - Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer ) ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer, true ) ) { if (( legendNode->flags() & Qt::ItemIsUserCheckable ) && legendNode->data( Qt::CheckStateRole ).toInt() != Qt::Checked ) diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index 27079883e650..fa3b243b7d02 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -1196,30 +1196,45 @@ void QgsLayerTreeModel::addLegendToLayer( QgsLayerTreeLayer* nodeL ) QList filteredLstNew = filterLegendNodes( lstNew ); - bool hasOnlyEmbedded = filteredLstNew.count() == 1 && filteredLstNew[0]->isEmbeddedInParent(); - Q_FOREACH ( QgsLayerTreeModelLegendNode* n, lstNew ) { n->setParent( this ); connect( n, SIGNAL( dataChanged() ), this, SLOT( legendNodeDataChanged() ) ); } - LayerLegendData data; - data.originalNodes = lstNew; - data.activeNodes = filteredLstNew; - data.tree = nullptr; + // See if we have an embedded node - if we do, we will not use it among active nodes. + // Legend node embedded in parent does not have to be the first one, + // there can be also nodes generated for embedded widgets + QgsLayerTreeModelLegendNode* embeddedNode = nullptr; + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, filteredLstNew ) + { + if ( legendNode->isEmbeddedInParent() ) + { + embeddedNode = legendNode; + filteredLstNew.removeOne( legendNode ); + break; + } + } + + LayerLegendTree* legendTree = nullptr; // maybe the legend nodes form a tree - try to create a tree structure from the list if ( testFlag( ShowLegendAsTree ) ) - tryBuildLegendTree( data ); + legendTree = tryBuildLegendTree( filteredLstNew ); - int count = data.tree ? data.tree->children[nullptr].count() : filteredLstNew.count(); + int count = legendTree ? legendTree->children[nullptr].count() : filteredLstNew.count(); - if ( ! hasOnlyEmbedded ) beginInsertRows( node2index( nodeL ), 0, count - 1 ); + if ( !filteredLstNew.isEmpty() ) beginInsertRows( node2index( nodeL ), 0, count - 1 ); + + LayerLegendData data; + data.originalNodes = lstNew; + data.activeNodes = filteredLstNew; + data.embeddedNodeInParent = embeddedNode; + data.tree = legendTree; mLegend[nodeL] = data; - if ( ! hasOnlyEmbedded ) endInsertRows(); + if ( !filteredLstNew.isEmpty() ) endInsertRows(); if ( hasStyleOverride ) ml->styleManager()->restoreOverrideStyle(); @@ -1230,11 +1245,11 @@ void QgsLayerTreeModel::addLegendToLayer( QgsLayerTreeLayer* nodeL ) } -void QgsLayerTreeModel::tryBuildLegendTree( LayerLegendData& data ) +QgsLayerTreeModel::LayerLegendTree* QgsLayerTreeModel::tryBuildLegendTree( const QList& nodes ) { // first check whether there are any legend nodes that are not top-level bool hasParentKeys = false; - Q_FOREACH ( QgsLayerTreeModelLegendNode* n, data.activeNodes ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* n, nodes ) { if ( !n->data( QgsLayerTreeModelLegendNode::ParentRuleKeyRole ).toString().isEmpty() ) { @@ -1243,30 +1258,31 @@ void QgsLayerTreeModel::tryBuildLegendTree( LayerLegendData& data ) } } if ( !hasParentKeys ) - return; // all legend nodes are top-level => stick with list representation + return nullptr; // all legend nodes are top-level => stick with list representation // make mapping from rules to nodes and do some sanity checks QHash rule2node; rule2node[QString()] = nullptr; - Q_FOREACH ( QgsLayerTreeModelLegendNode* n, data.activeNodes ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* n, nodes ) { QString ruleKey = n->data( QgsLayerTreeModelLegendNode::RuleKeyRole ).toString(); if ( ruleKey.isEmpty() ) // in tree all nodes must have key - return; + return nullptr; if ( rule2node.contains( ruleKey ) ) // and they must be unique - return; + return nullptr; rule2node[ruleKey] = n; } // create the tree structure - data.tree = new LayerLegendTree; - Q_FOREACH ( QgsLayerTreeModelLegendNode* n, data.activeNodes ) + LayerLegendTree* tree = new LayerLegendTree; + Q_FOREACH ( QgsLayerTreeModelLegendNode* n, nodes ) { QString parentRuleKey = n->data( QgsLayerTreeModelLegendNode::ParentRuleKeyRole ).toString(); QgsLayerTreeModelLegendNode* parent = rule2node.value( parentRuleKey, nullptr ); - data.tree->parents[n] = parent; - data.tree->children[parent] << n; + tree->parents[n] = parent; + tree->children[parent] << n; } + return tree; } QgsRenderContext* QgsLayerTreeModel::createTemporaryRenderContext() const @@ -1316,6 +1332,7 @@ QModelIndex QgsLayerTreeModel::legendNode2index( QgsLayerTreeModelLegendNode* le int row = data.activeNodes.indexOf( legendNode ); if ( row < 0 ) // legend node may be filtered (exists within the list of original nodes, but not in active nodes) return QModelIndex(); + return index( row, 0, parentIndex ); } @@ -1340,10 +1357,6 @@ int QgsLayerTreeModel::legendRootRowCount( QgsLayerTreeLayer* nL ) const return data.tree->children[nullptr].count(); int count = data.activeNodes.count(); - - if ( legendEmbeddedInParent( nL ) ) - count--; // one item less -- it is embedded in parent - return count; } @@ -1408,35 +1421,34 @@ Qt::ItemFlags QgsLayerTreeModel::legendNodeFlags( QgsLayerTreeModelLegendNode* n bool QgsLayerTreeModel::legendEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const { - return legendNodeEmbeddedInParent( nodeLayer ); + return mLegend[nodeLayer].embeddedNodeInParent != nullptr; } QgsLayerTreeModelLegendNode* QgsLayerTreeModel::legendNodeEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const { - // legend node embedded in parent does not have to be the first one... - // there could be extra legend nodes generated for embedded widgets - const LayerLegendData& data = mLegend[nodeLayer]; - Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, data.activeNodes ) - { - if ( legendNode->isEmbeddedInParent() ) - return legendNode; - } - return nullptr; + return mLegend[nodeLayer].embeddedNodeInParent; } QIcon QgsLayerTreeModel::legendIconEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const { - QgsLayerTreeModelLegendNode* legendNode = legendNodeEmbeddedInParent( nodeLayer ); + QgsLayerTreeModelLegendNode* legendNode = mLegend[nodeLayer].embeddedNodeInParent; if ( !legendNode ) return QIcon(); return QIcon( qvariant_cast( legendNode->data( Qt::DecorationRole ) ) ); } -QList QgsLayerTreeModel::layerLegendNodes( QgsLayerTreeLayer* nodeLayer ) +QList QgsLayerTreeModel::layerLegendNodes( QgsLayerTreeLayer* nodeLayer, bool skipNodeEmbeddedInParent ) { - return mLegend.value( nodeLayer ).activeNodes; + if ( !mLegend.contains( nodeLayer ) ) + return QList(); + + const LayerLegendData& data = mLegend[nodeLayer]; + QList lst( data.activeNodes ); + if ( !skipNodeEmbeddedInParent && data.embeddedNodeInParent ) + lst.prepend( data.embeddedNodeInParent ); + return lst; } QList QgsLayerTreeModel::layerOriginalLegendNodes( QgsLayerTreeLayer* nodeLayer ) diff --git a/src/core/layertree/qgslayertreemodel.h b/src/core/layertree/qgslayertreemodel.h index fcd4b3847a66..1522f3d224c8 100644 --- a/src/core/layertree/qgslayertreemodel.h +++ b/src/core/layertree/qgslayertreemodel.h @@ -118,15 +118,21 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel QModelIndex legendNode2index( QgsLayerTreeModelLegendNode* legendNode ); //! Return filtered list of active legend nodes attached to a particular layer node + //! (by default it returns also legend node embedded in parent layer node (if any) unless skipNodeEmbeddedInParent is true) //! @note added in 2.6 + //! @note skipNodeEmbeddedInParent added in 2.18 //! @see layerOriginalLegendNodes() - QList layerLegendNodes( QgsLayerTreeLayer* nodeLayer ); + QList layerLegendNodes( QgsLayerTreeLayer* nodeLayer, bool skipNodeEmbeddedInParent = false ); //! Return original (unfiltered) list of legend nodes attached to a particular layer node //! @note added in 2.14 //! @see layerLegendNodes() QList layerOriginalLegendNodes( QgsLayerTreeLayer* nodeLayer ); + //! Return legend node that may be embbeded in parent (i.e. its icon will be used for layer's icon). + //! @note added in 2.18 + QgsLayerTreeModelLegendNode* legendNodeEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; + /** Searches through the layer tree to find a legend node with a matching layer ID * and rule key. * @param layerId map layer ID @@ -259,8 +265,6 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel QVariant legendNodeData( QgsLayerTreeModelLegendNode* node, int role ) const; Qt::ItemFlags legendNodeFlags( QgsLayerTreeModelLegendNode* node ) const; bool legendEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; - //! Return legend node that may be embbeded in parent (i.e. its icon will be used for layer's icon). - QgsLayerTreeModelLegendNode* legendNodeEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; QIcon legendIconEmbeddedInParent( QgsLayerTreeLayer* nodeLayer ) const; void legendCleanup(); void legendInvalidateMapBasedData(); @@ -293,9 +297,19 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel //! @note not available in Python bindings struct LayerLegendData { + LayerLegendData() + : embeddedNodeInParent( nullptr ) + , tree( nullptr ) + { + } + //! Active legend nodes. May have been filtered. //! Owner of legend nodes is still originalNodes ! QList activeNodes; + //! A legend node that is not displayed separately, its icon is instead + //! shown within the layer node's item. + //! May be null. if non-null, node is owned by originalNodes ! + QgsLayerTreeModelLegendNode* embeddedNodeInParent; //! Data structure for storage of legend nodes. //! These are nodes as received from QgsMapLayerLegend QList originalNodes; @@ -304,7 +318,7 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel }; //! @note not available in Python bindings - void tryBuildLegendTree( LayerLegendData& data ); + LayerLegendTree* tryBuildLegendTree( const QList& nodes ); //! Overrides of map layers' styles: key = layer ID, value = style XML. //! This allows to show legend that is different from the current style of layers diff --git a/src/core/qgslegendrenderer.cpp b/src/core/qgslegendrenderer.cpp index 8df06f55b592..5a154629e0f8 100644 --- a/src/core/qgslegendrenderer.cpp +++ b/src/core/qgslegendrenderer.cpp @@ -593,8 +593,7 @@ QgsComposerLegendStyle::Style QgsLegendRenderer::nodeLegendStyle( QgsLayerTreeNo return QgsComposerLegendStyle::Group; else if ( QgsLayerTree::isLayer( node ) ) { - QList legendNodes = model->layerLegendNodes( QgsLayerTree::toLayer( node ) ); - if ( legendNodes.count() == 1 && legendNodes[0]->isEmbeddedInParent() ) + if ( model->legendNodeEmbeddedInParent( QgsLayerTree::toLayer( node ) ) ) return QgsComposerLegendStyle::Hidden; return QgsComposerLegendStyle::Subgroup; } diff --git a/src/gui/layertree/qgslayertreeview.cpp b/src/gui/layertree/qgslayertreeview.cpp index 536eca939efa..be815a277697 100644 --- a/src/gui/layertree/qgslayertreeview.cpp +++ b/src/gui/layertree/qgslayertreeview.cpp @@ -138,7 +138,7 @@ void QgsLayerTreeView::modelRowsInserted( const QModelIndex& index, int start, i if ( QgsMapLayer* layer = nodeLayer->layer() ) { int widgetsCount = layer->customProperty( QStringLiteral( "embeddedWidgets/count" ), 0 ).toInt(); - QList legendNodes = layerTreeModel()->layerLegendNodes( nodeLayer ); + QList legendNodes = layerTreeModel()->layerLegendNodes( nodeLayer, true ); for ( int i = 0; i < widgetsCount; ++i ) { QString providerId = layer->customProperty( QStringLiteral( "embeddedWidgets/%1/id" ).arg( i ) ).toString(); @@ -159,7 +159,7 @@ void QgsLayerTreeView::modelRowsInserted( const QModelIndex& index, int start, i if ( expandedNodeKeys.isEmpty() ) return; - Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, layerTreeModel()->layerLegendNodes( QgsLayerTree::toLayer( parentNode ) ) ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, layerTreeModel()->layerLegendNodes( QgsLayerTree::toLayer( parentNode ), true ) ) { QString ruleKey = legendNode->data( QgsLayerTreeModelLegendNode::RuleKeyRole ).toString(); if ( expandedNodeKeys.contains( ruleKey ) ) @@ -345,7 +345,7 @@ static void _expandAllLegendNodes( QgsLayerTreeLayer* nodeLayer, bool expanded, QStringList lst; if ( expanded ) { - Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer ) ) + Q_FOREACH ( QgsLayerTreeModelLegendNode* legendNode, model->layerLegendNodes( nodeLayer, true ) ) { QString parentKey = legendNode->data( QgsLayerTreeModelLegendNode::ParentRuleKeyRole ).toString(); if ( !parentKey.isEmpty() && !lst.contains( parentKey ) ) From 90e1c9366141b768a1559e35e1337858724b59e4 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Thu, 20 Oct 2016 16:50:09 +0800 Subject: [PATCH 554/897] Fix building of legend node tree if embedded widgets are used in the layer (cherry picked from commit 10cab93c3652c38db27553616f36290f7b820c48) --- src/core/layertree/qgslayertreemodel.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index fa3b243b7d02..599d85227580 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -44,13 +44,20 @@ class EmbeddedWidgetLegendNode : public QgsLayerTreeModelLegendNode EmbeddedWidgetLegendNode( QgsLayerTreeLayer* nodeL ) : QgsLayerTreeModelLegendNode( nodeL ) { + // we need a valid rule key to allow the model to build a tree out of legend nodes + // if that's possible (if there is a node without a rule key, building of tree is cancelled) + mRuleKey = QStringLiteral( "embedded-widget-" ) + QUuid::createUuid().toString(); } virtual QVariant data( int role ) const override { - Q_UNUSED( role ); + if ( role == RuleKeyRole ) + return mRuleKey; return QVariant(); } + + private: + QString mRuleKey; }; ///@endcond From 5c83b7924a908a8d211a8a6ce3890210fb2700f9 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Thu, 20 Oct 2016 22:56:11 +0800 Subject: [PATCH 555/897] Fix reordering and removal of legend nodes in composer legend (cherry picked from commit f4e1e6f6eefec74fcf61542c3c9e236c4fb3054f) --- src/app/composer/qgscomposerlegendwidget.cpp | 29 ++++++++++++++------ 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/app/composer/qgscomposerlegendwidget.cpp b/src/app/composer/qgscomposerlegendwidget.cpp index 92b7f489bca2..287715c03b8c 100644 --- a/src/app/composer/qgscomposerlegendwidget.cpp +++ b/src/app/composer/qgscomposerlegendwidget.cpp @@ -42,6 +42,23 @@ #include +static int _unfilteredLegendNodeIndex( QgsLayerTreeModelLegendNode* legendNode ) +{ + return legendNode->model()->layerOriginalLegendNodes( legendNode->layerNode() ).indexOf( legendNode ); +} + +static int _originalLegendNodeIndex( QgsLayerTreeModelLegendNode* legendNode ) +{ + // figure out index of the legend node as it comes out of the map layer legend. + // first legend nodes may be reordered, output of that is available in layerOriginalLegendNodes(). + // next the nodes may be further filtered (by scale, map content etc). + // so here we go in reverse order: 1. find index before filtering, 2. find index before reorder + int unfilteredNodeIndex = _unfilteredLegendNodeIndex( legendNode ); + QList order = QgsMapLayerLegendUtils::legendNodeOrder( legendNode->layerNode() ); + return ( unfilteredNodeIndex >= 0 && unfilteredNodeIndex < order.count() ? order[unfilteredNodeIndex] : -1 ); +} + + QgsComposerLegendWidget::QgsComposerLegendWidget( QgsComposerLegend* legend ) : QgsComposerItemBaseWidget( nullptr, legend ) , mLegend( legend ) @@ -480,7 +497,7 @@ void QgsComposerLegendWidget::on_mMoveDownToolButton_clicked() } else // legend node { - _moveLegendNode( legendNode->layerNode(), index.row(), 1 ); + _moveLegendNode( legendNode->layerNode(), _unfilteredLegendNodeIndex( legendNode ), 1 ); mItemTreeView->layerTreeModel()->refreshLayerLegend( legendNode->layerNode() ); } @@ -517,7 +534,7 @@ void QgsComposerLegendWidget::on_mMoveUpToolButton_clicked() } else // legend node { - _moveLegendNode( legendNode->layerNode(), index.row(), -1 ); + _moveLegendNode( legendNode->layerNode(), _unfilteredLegendNodeIndex( legendNode ), -1 ); mItemTreeView->layerTreeModel()->refreshLayerLegend( legendNode->layerNode() ); } @@ -688,7 +705,7 @@ void QgsComposerLegendWidget::on_mRemoveToolButton_clicked() if ( QgsLayerTreeModelLegendNode* legendNode = mItemTreeView->layerTreeModel()->index2legendNode( index ) ) { QgsLayerTreeLayer* nodeLayer = legendNode->layerNode(); - nodesWithRemoval[nodeLayer].append( index.row() ); + nodesWithRemoval[nodeLayer].append( _unfilteredLegendNodeIndex( legendNode ) ); } } Q_FOREACH ( QgsLayerTreeLayer* nodeLayer, nodesWithRemoval.keys() ) @@ -1011,11 +1028,7 @@ void QgsComposerLegendWidget::on_mItemTreeView_doubleClicked( const QModelIndex } else if ( legendNode ) { - QList order = QgsMapLayerLegendUtils::legendNodeOrder( legendNode->layerNode() ); - //find unfiltered row number - QList layerLegendNodes = model->layerOriginalLegendNodes( legendNode->layerNode() ); - int unfilteredRowIndex = layerLegendNodes.indexOf( legendNode ); - int originalIndex = ( unfilteredRowIndex >= 0 && unfilteredRowIndex < order.count() ? order[unfilteredRowIndex] : -1 ); + int originalIndex = _originalLegendNodeIndex( legendNode ); QgsMapLayerLegendUtils::setLegendNodeUserLabel( legendNode->layerNode(), originalIndex, newText ); model->refreshLayerLegend( legendNode->layerNode() ); } From b798040040ed7ab481730f72bcfeb502ca0c0f23 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Tue, 1 Nov 2016 10:12:43 +0800 Subject: [PATCH 556/897] Fixed legend renderer expected images --- .../expected_legend_diagram_attributes.png | Bin 5729 -> 4509 bytes ...xpected_legend_diagram_attributes_mask.png | Bin 2374 -> 3099 bytes .../expected_legend_diagram_size.png | Bin 14032 -> 11931 bytes .../expected_legend_diagram_size_mask.png | Bin 3467 -> 11637 bytes 4 files changed, 0 insertions(+), 0 deletions(-) diff --git a/tests/testdata/control_images/legend/expected_legend_diagram_attributes/expected_legend_diagram_attributes.png b/tests/testdata/control_images/legend/expected_legend_diagram_attributes/expected_legend_diagram_attributes.png index a4e6bbbe70bf2e9e4c72985331680d6e30e9ce71..1f46e116f5c9d1df2e1263dc9cb6cdf86c2f29d3 100644 GIT binary patch literal 4509 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 literal 5729 zcmZu#bzGCtyB{SnKtM{m6eUDNTBJsI2%{Yc(k&?=h;%ChCsN`>n3OalMNmXQO1hp23`}^F_y?@;0yYs%=&N0pH1Q{Bu50-^qP`6PHFNX-fcNqseRR7hutp;ws2T1^=^AP|O4 z4Va>Fz}QB1u(6RT{;+wLMS(^ORx*?k|LyLdaz_=Yxq$$oGY!MX;RwT3$4=UgB&4os zaS|_vy>rMOGc;^Iczw{AKc8$v)(~nCXBXc^k7@suN)|yz<{dBEdlKEeKATBQ%j-SL zIbzlwBD=JJ>zV4E8twIg!C*6qJLNq;sA(?$s#(}3*88A6xa8T|aO=Q8I(t!3k)`m} z)*h5(o=Nd&-oVO{e%CDc-FjrAeQe%L!&Z~Bh6XtcE9>m$W>Ri0S0kQ-%3WUOCg z+_&P3J3Lei2$0$fl6$Rrqj-L0CAOtSA$_Cwopj{s>2qTfleVcTj;5xjfW(`RHJ( zs%--UmHq0O9 zz~9SC@b>m54&2_}R^8a$+3A{|o?Z~o&dy#b4Ld6~K)rrVuZV4rzG~#?_{rd8DJSf` zfS_RF7^hs&YyAEi|0fqaJLR>JQuH*~w}{hjq==E;QaQO6dZ7RHZ6o3h7!R$qv^4q7 zg9i`P3;M~%bhBlKKHP$&pima5HvDG8R@d;biGJsgAF(ARCB%VSO(*WCw)zVhOmc0l zl;U{h)7~^Nmr?xL$>G+swjfuD;Usq1ls9iW{&;zLeJUzy-59S)&B`JV4i1L2?5~ZK z`>q(8h{(#aswH#SJDHlAu1{fEJ32c4mfMkno#?SPDjwo__>jYYa{}R3Sy}0Ia^Plc zYHEkyTPfMhxj21#dNO_C?sJqBAK#wJt5)XF!vZ%u+cLOKPtp3zy(5mH&$&uS&h9(q z!r~$~h)FuX-uFaS$s>KoA`U?=uJ9qGI^TyOXOhL(*w~VZv9Y(#&dxD0j{W&65iT2l z%a!{!+po&sAGa$+qoF@HId|@}B<4PlmL7FYW}v0zc9eA+yPuBL)zP7fh4Ey_JN9w4 zKE;%lO0w_-D<|*66a2Gvqaz{+Gu)k=TEUV?p8f3Z9=+I_!p4K0vTb`wUh6p9(g)$v-g`HN;mNKx+2L=Oa`}S{y$$ghe%D7%twvWl_W< zZ9<(!#C5zbe%2zE-G>H?D` zMnDloC?O%?=Srxnjl932w> zo!gC9yTM=}#cuQQef!ktG2OJVx+>5GrKF^{6p@pgbQJ#SDFiQ5NO>>m@jlnh!QtlU z-@jz5a0`p{hK7cIb0Y_bkE3P?clR$dji6eYUNbQ;lvfCveqj!|*^aQcR{@cJ&fcBY zj!;#-l9rYR)=h#nb#ueCa6rk)X}@MmxUqQq_|P&kUg78G|2sZzH~7gwT}!LIEebk* z{~uaAD`I`!)uHmbL-w0DZz8Hb((vS^HK$aPYn75I zxZNYF`E&=my0*s67{C2Xtas*kDW?-E(#VzhUOq+#B{92EGwrYf@^B7QGj*@wG$kh| zIWCT30vpVvC$~@k{P}YlX67!}`eCsViyHUxuMG{d>+9>pHZgd7P{sicclRD{KS(b0 zXqNQA0s%6cjg2jLV1*d^`QYHdfuG0{o=h91^a8-}x6V$xBit-aEX>i}{d-f$2@Zh4 zd!21|Ha2}jL!Po?smZSItFC?UshL+tC{aUhNvd7#fFE6b9fX0 zE|JPG=UVgxOl1kbZit4zeum682`&CbRW36G)lRNv(CzD$NmIEB$hz{+GJVo^cmjqk?!erfdq7ythnolNq-`braT)<@WJoObdyQbauguF+^CfD~hIYW=Q ze=K^ZbuSt}dZYq_Iaj@14B7d?@4K_05top_m!+-hUH6Ux3XP2ctPs24EltI8KW0)H z4rc~mdn*@QtrAq?(RBQ3Zf?$T{crhwP?kIU`-LefG@2S3d9Pkw`4{L`JH6F>VcmBQ zQq|7h^ou3p7_bh1ouw`yNl?ul-@fVV>L%s7fy!_Rp8H0QUo9?OE<{@A=P5_0>7v)p z^LWPTGA!>%Qh58V4&L_m@)DJHt#4=;INn_{I|2B>LS?6-q7so=aM&=`P+Qvv)WkSj z{>H|JFi%Of5|o&PB-OeU{qv`0MNJJqgb&$GvLPoYM-Dm0W9odLlTwYcWK3LBi95gns_bqA}0ce;EFoud<=Jg_g!WW_V6@K$_ z+o&1tDpNSb@%;4ogRy|qM6H*Q$H~FQhk+IKJbiFW;j+oo?*j`G;wb@<8Ys8x{8Uns z@YP({={`$bZ0vutW^Bym_k}Vy0D8s5+>)2i89JGXyb2D5g%cNV@bT$Cdc**(zsUx8 znK8MlstlqJ)Q{WP*H{24LGR0cv6GXN!(hg6_^l&V*1omg6~j5UL> zQ@1D=K0hj!=?G{JKD-0i(#YHUUQd=-G)Q8V7cX9@wudPy5_F#oyJ~~Aq#`exm zQh?-{a={W1g@XRF`g>X0We>RDXc`zAwyoARG|1zE3RDwq&m%EJ@5IH$pT(VBXJ8m| zh*4_~NnjQw1c;`lt4n;VtdTMN5UgiewCWI0Ph3(N>FE`CQd`Ex>L+Pk0hp736r<#PXi3vMNVB7k z9zaYth1~4rMRsqmSN1AlOzh6^`;g5jY(hf9lV?gwN}i`jUJ!-Q(1*pO6Hxv-w{Z!+ z8#lHWuNb*bHJZ`*y7uKN67tFm3u7j~pRjr~wyysB_pjpg!w0^M=8zLVUX;h54;mZQ z<=X5P)vkH0lI~?lcDR{Y|4Z^~UE|}ZciGuySRgxF10~%jZb|iWp5sUr1A!z83=Aya zLA1Xz0I8J7EE-XQ!H`4VAd#%2aIjUgii#O`tm3j|{paeI-bY%Oc7o(ofTd^_N(JD! zLU&Qq@V%hje?6B(CF(h&5KoPyizN;|+>C*`!`HN_&5l*Me8OO&P$*U) zcIy|3{;c@cdM{D{WjXMrmxhKW8~`DxaK%EyEDUWb9CgZ{BlhM)JR+dogqF3Qie-)W{5LIuo^3FVHlJ&&fB=>7x5k4LaNW$( zQnaYu_dWd6wy2IkAspt%|9YKE{`f!k2R&lj&Pm|EAI1jX6{{ie>ny{4|;za91moyF7A(?x^!9FOpLTL98+s>1mdOfS}$Ip zrDzx!qEM0^gpe=R*q=Mq?vrswXkEnWU=eP2SJ~K@9_T54=6s7SMjdT!82D^!Yb&%9 z*nDkYKErVn>^|*S$>U$g+*w}ZnDmY6l7lqP=n>J zqxU|b(UlbdY$IZ5I60GnFNL(cqGH7j=*c61>u^om{)h6YJ_!P@uydl$C(l?w)O|t< zqF`mk-gJ(4k&=>9$kXS#bxXZZ`4&CJhr&X$gsgS_`c6VwMM1){sG8y z-Q2K?^Gva))DSLSULt#Ydr0^IT5o=5vHMUJdEvA9w>eDyV12ZG2cT4LzatGB8zoQM zpF%CKjWO|p6Dgm6lt6Q(q@_h1PKQl@u=${p!AeL-_;`Mf%(3U)#3(rd0RbbEiJcv< zb=cXnd4x1K0U+|$I-eyRa9E@*a!&^URua`NaRw~+ald~3TA|P|55Sd`7`({%vVZ|J zxBmPYN5zB`v3XThC4MPfN}JE$4kgFLEcgBT!v?~x0!a9L2iZIWTqy8lzqlD8adB}p zbaW9nv@#x#e6a$i`)H?IWE*%)+l%uv2*kz3HQwjR=puhiY+{mO6S?^1 zTuG*TDD3oTd&5sJc)@J;^-5~l)Qz_KMZtc{5RYYA`5~sYYWEI7BVLZ~$bVnXt)_>j zc?7pgwc}fsw-vj3dr2Y0SFTi_Bp*o4fU_+_%?(1eUZxlP^Q#`4(!TZaA*L@H@bYG+ z7uK`q9ad+u(?dBY3+n8^{r`MqTqR%(P$t$2M6x{sN{$Et_9tf!1JA(4^5Rd%zE{g+Q?tFTh0!rJIfI5M?|7E z;W&N4Evv_M+;Vd4m#Gb84``I!4ZuCt&UwfVeA*Sy-U2WKRv$>&u|%EVk_WE|cM4mw^$9_#<@XF~WfAV9Z3 zZ-y!J?OV;LsHjW*^CRs>$yBx5_;NI7Xzu6F0?tlOc{yR{SwQX)aFxTg6B84St*vz_ zq9OnfkV66k0#cOnxT2I40VG($u^RCH{{HpkfSHyT5;b?jwmX=)J5JVqtBq+ZFg= zR+f8D$VNv;%gqqLH46Is`F;G6&YzA#p;{gZ05O@pJ7j7j{+5AdO35RsSN@_=2Z`zG zQg?s+3{7GP95e7X0A}0!`)OsesZC3*qjb@B&^JaOwOfO?u%s3i7K0-ryde0c*aMb- zzq4I--rc@^I|fvAhRE)w8T5nIOIiO-1&oO@5FkK7sER6sIeG1`J_1CGiw%0>0}K*& zC}8Q*DE-GEF)^ZRcJ-SX;`+AF;KUD)7vvbDfn!=ZP)6t#@LJ1g7SdguF3B6f;W0Zq z-hW3&TY=NwUFucy_1(KhetnQ3@Y9>a_YQU-s=4|3gi}*fLa@U~!157RRG2JD4-RO+ z_h_Zx%D|VVW@g4DBv39aEzM{9Pa*7WLiQQr;^U8%SCf?UZeV?#U0etzpo(r}=p!zX z?EHKlN{$Dag`f$Q`0gDWc`(?lB z^$g)w{aVp6>P5yCN85RMd6ou~I+sIF0eY>Ay8sX3K2h7s(1G>kNCd{g?s#XBizk6a zoC08cB#dXa`jJ11!H+?Nokt01Wx%A0FtV#xpKd`He3cQ;7(}wAef~WL0tm8+rE~_I za_iQuaLvL9&BA-fG7=93*V`maOt=4tHhv>>YlO$PV|{BuQ}##$UEBf=%cLg2&i_9? dRH*fWv{xzS^ZkFj#Gn}r(NNKaeNlQG@m~V?JI??B diff --git a/tests/testdata/control_images/legend/expected_legend_diagram_attributes/expected_legend_diagram_attributes_mask.png b/tests/testdata/control_images/legend/expected_legend_diagram_attributes/expected_legend_diagram_attributes_mask.png index bfd2fc9b9e0887da93f809efa59829434d6d52ca..de97cb083057fd571d4cd28dd2a395206d542a56 100644 GIT binary patch literal 3099 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 SfU*a=eE@b7Zum~$E&iW^?%}8a literal 2374 zcmeHJ`#0O!7XP-M^+-_S9Tlxs1RbjNjHwAllolmvjkhS(5L6YF(Z;KY((w*arZqLA zl4(8DOFh#z2#rTg=mQ-zWvFL~nD3pt?)_o@hI`i9XP>>+UT5vSKYM@9$vWqDMqWlk z1^@tgXD5sYsEa_!m6ine3ktW}KqVe)@9ZTFu4L(uOwc|M?Szj707%cjWnZBoL=ym{ z=bbU9y%K1P{7X*CyE^O@?jO31W2WOMmu^$}eAM!}`*Dzo9&;$p0IzU9BK35>qP>sy zVb*+gRhKammFRKb-c06vfyexzN0dORSFT;IxArgW_^w@NkRQMCd>1pxm6d#0F|pFT zMI>CGq&r~5F&z^v9kzf*xf<+I0Pd$-f%!7&4#@u-|ER%a#Z?9lMUK%jcEE@>6h>BZ z{^0;tEIN_ZsbZl8Nk~enX=s3sH~8xe$L<#sW5#@R>FMi3pipu%eK&VHN{fop-RbCX z$heoU6^bwfuVWnJK-tgL)2ZzLHtJxi=GoIE5i zCx`LzQT?6ISJcq3s-9C;Rh=2Eu+GfN>U@AL9vT~yR7|DQbsxND>VH{X&0TD5ZEcD9D5IgNxw5w4X>;R?cwu4Tn-)?H(>*Tk1QLmC zw|lO={+kZ69Z>c3>4-%)#=#+QwC+ORc61YQD&kj@ z@7t8GUcK5OI6^gec)(CkPwd*YYsZX?dPg34p7-_5k&uN|)zpX`b+0_J!Ed^%i6)D3 z>gtfVdhe&r&3d-B+IT$v7z#ycZa($!YV(bx)NKN zM=2~TyR$AB7X!-5%b8(ZxR!OioUX1egTMIm{!d>^vP#saaSEo2p$Q@GrA3 z^-?Mgj}Me@`ZV~d3pSUgG-K$ESH`Z4<0yIsg zYJPrx;C-6$T4*%7#4=W&Fi5kUodMyr+neq?#G^C@^~zAv(mI2f0V~tJmx;u_Y*mwG z(QeZ0>@2VqZy4~La^T=OFqG}>#Lr+2UIasW6crSHXlt`tTU!hG^X^78VR zFJFFMY~r88z7i2JG&J->K|z84%}2qvpIkZY*tt{JncdLPFfu-lb#tR`ZEa<;SS)cV zsqEU?+WzuW?toKJP_?p(N>)Zj1_(I*2_ZKmG}JjhzKKM0$cCv4G9cPYtSRG^l$5?; zDTtO@yjHC{9Ui{})@=)pbzOrCX4rYSW}~+ib*r%V^MhB~CY_v(50l)`j<_G?`t_(b z*xCJM=CVsmO9{K%=G)ub?fj*gncMH*2gJq4S2s6rn&iH=^pPI=F|f44kP=#k)h(6n zMySYTdmTr4bTXVI{$~W1nQVt|neaMZaX2Kwn2}B5nsh})#q!!3hD7?t1&bxEf4WfI z^3@VCD9X${znl@a_%WUf$j=j*jUVN5@ysZmfo^e;O^I)1xA}0|SMIK98N^ z;-2?YjZ?d9=2 z!MJ{U@W27cEG{kvS(fuOoOjsPcB%vzo|rILSXd~itR&KII<|Rvd1dwnDFPmzo@Ui^ zE&F*C^8&mT5Hj79MUE^Q1gSEI6OP4Zzll7VzHSGyj=p~1)&sEdpnp&9-Me=K^A4)2 zZeHp_8W?;t=#`tBtE8ZCe0r{JKQ9@nWrGdt%TfPs>E6A2!Tql-Nz>v&q453E5;b;i zP<==ENmb1VCMzQ&!vIM=Q<^y0k{Ze>y3b;nNVM?`cD*PLNSf3WXiv-QwuIEeOM zqpFp+g>_+|vad+eq`kde2?iqwla^5xsqSguL(;dAinjvCI;intE?bKGdV&$y4Ydnv z!CN5^L?W@9sFN%RZrSa#;?bDs6k%p%B^;da=WMpr?(S~F*Dpu5cXmj#FBE}ygas{| z1O+%8J}(e-FY=r73kyRd_sG}(e492!+*@)z(~)6t)HAwha6ar6qkmAP%XHwu-Tt)y q{3d8A!(5fOQg`8%%>VYjP}W(~H=5gK@CN({0nQF?n8)@3xBde5m`&;c diff --git a/tests/testdata/control_images/legend/expected_legend_diagram_size/expected_legend_diagram_size.png b/tests/testdata/control_images/legend/expected_legend_diagram_size/expected_legend_diagram_size.png index ddd22ff0545331c0bcc9a1b14a8e2656b9ca0081..822b21c48bef2852f08cf1d1d373732a8207e65c 100644 GIT binary patch literal 11931 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 diff --git a/tests/testdata/control_images/legend/expected_legend_diagram_size/expected_legend_diagram_size_mask.png b/tests/testdata/control_images/legend/expected_legend_diagram_size/expected_legend_diagram_size_mask.png index 2e819768132e7f96743d84d543b7875bd403b512..9632c102ace49358d7876369401c3edcbf85b47f 100644 GIT binary patch literal 11637 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 z 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 MH?@>MC|U;pA9jOid;kCd literal 3467 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 From 629ca8b9860fcf1f07dff554790c207995a90d99 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 21 Oct 2016 11:19:32 +0800 Subject: [PATCH 557/897] Hide import/export buttons for arcgis services as they do not work (fixes #15637) (cherry picked from commit 1c2f0de9fbea8e90c9d20036bfa1601c1d192a89) --- src/gui/qgssourceselectdialog.cpp | 23 +------------------ src/gui/qgssourceselectdialog.h | 2 -- .../arcgisrest/qgsafssourceselect.cpp | 4 ++++ .../arcgisrest/qgsamssourceselect.cpp | 4 ++++ 4 files changed, 9 insertions(+), 24 deletions(-) diff --git a/src/gui/qgssourceselectdialog.cpp b/src/gui/qgssourceselectdialog.cpp index bbe33ca18692..030793c7bb1b 100644 --- a/src/gui/qgssourceselectdialog.cpp +++ b/src/gui/qgssourceselectdialog.cpp @@ -412,28 +412,7 @@ void QgsSourceSelectDialog::on_cmbConnections_activated( int index ) QgsOwsConnection::setSelectedConnection( mServiceName, cmbConnections->currentText() ); } -void QgsSourceSelectDialog::on_btnSave_clicked() -{ - QgsManageConnectionsDialog dlg( this, QgsManageConnectionsDialog::Export, QgsManageConnectionsDialog::WFS ); - dlg.exec(); -} - -void QgsSourceSelectDialog::on_btnLoad_clicked() -{ - QString fileName = QFileDialog::getOpenFileName( this, tr( "Load connections" ), QStringLiteral( "." ), - tr( "XML files (*.xml *XML)" ) ); - if ( fileName.isEmpty() ) - { - return; - } - - QgsManageConnectionsDialog dlg( this, QgsManageConnectionsDialog::Import, QgsManageConnectionsDialog::WFS, fileName ); - dlg.exec(); - populateConnectionList(); - emit connectionsChanged(); -} - -void QgsSourceSelectDialog::treeWidgetItemDoubleClicked( const QModelIndex& index ) +void QgsSourceSelectDialog::treeWidgetItemDoubleClicked( const QModelIndex & index ) { QgsDebugMsg( "double click called" ); QgsOwsConnection connection( mServiceName, cmbConnections->currentText() ); diff --git a/src/gui/qgssourceselectdialog.h b/src/gui/qgssourceselectdialog.h index c5738b3da309..8cda87e293af 100644 --- a/src/gui/qgssourceselectdialog.h +++ b/src/gui/qgssourceselectdialog.h @@ -99,8 +99,6 @@ class GUI_EXPORT QgsSourceSelectDialog : public QDialog, protected Ui::QgsSource void changeCrsFilter(); void connectToServer(); void filterChanged( const QString &text ); - void on_btnLoad_clicked(); - void on_btnSave_clicked(); void on_cmbConnections_activated( int index ); void on_buttonBox_helpRequested() const; void treeWidgetItemDoubleClicked( const QModelIndex & index ); diff --git a/src/providers/arcgisrest/qgsafssourceselect.cpp b/src/providers/arcgisrest/qgsafssourceselect.cpp index a256fcd9f224..44380cc3fd3f 100644 --- a/src/providers/arcgisrest/qgsafssourceselect.cpp +++ b/src/providers/arcgisrest/qgsafssourceselect.cpp @@ -33,6 +33,10 @@ QgsAfsSourceSelect::QgsAfsSourceSelect( QWidget* parent, Qt::WindowFlags fl, boo { buttonBox->button( QDialogButtonBox::Close )->hide(); } + + // import/export of connections not supported yet + btnLoad->hide(); + btnSave->hide(); } bool QgsAfsSourceSelect::connectToService( const QgsOwsConnection &connection ) diff --git a/src/providers/arcgisrest/qgsamssourceselect.cpp b/src/providers/arcgisrest/qgsamssourceselect.cpp index b1dd77e24cb8..a6b0b83873ac 100644 --- a/src/providers/arcgisrest/qgsamssourceselect.cpp +++ b/src/providers/arcgisrest/qgsamssourceselect.cpp @@ -32,6 +32,10 @@ QgsAmsSourceSelect::QgsAmsSourceSelect( QWidget* parent, Qt::WindowFlags fl, boo { buttonBox->button( QDialogButtonBox::Close )->hide(); } + + // import/export of connections not supported yet + btnLoad->hide(); + btnSave->hide(); } bool QgsAmsSourceSelect::connectToService( const QgsOwsConnection &connection ) From 5e4bb00fa3e11a5dc347ddb22ed0b98965b9b03c Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 21 Oct 2016 15:10:26 +0800 Subject: [PATCH 558/897] Fix import of shapefiles to postgres - regression introduced in 5abdfcb (#3652) (cherry picked from commit a965a132c52df9308b5a58be92c04a285826485a) --- .../postgres/qgspostgresprovider.cpp | 3 +++ tests/src/python/test_provider_postgres.py | 19 +++++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 0b600accf263..417982e89f4e 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -3526,6 +3526,9 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q fldIdx = -1; // it is incremented in the for loop, i.e. restarts at 0 } } + + pkList = QStringList( primaryKey ); + pkType = QStringList( "serial" ); } else { diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 7d3c36693bc6..0935ec42f013 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -471,7 +471,9 @@ def testImportKey(self): def testKey(lyr, key, kfnames): self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.import_test') - uri = '%s table="qgis_test"."import_test" (g) key=\'%s\'' % (self.dbconn, key) + uri = '%s table="qgis_test"."import_test" (g)' % self.dbconn + if key is not None: + uri += ' key=\'%s\'' % key err = QgsVectorLayerImport.importLayer(lyr, uri, "postgres", lyr.crs()) self.assertEqual(err[0], QgsVectorLayerImport.NoError, 'unexpected import error {0}'.format(err)) @@ -479,9 +481,17 @@ def testKey(lyr, key, kfnames): self.assertTrue(olyr.isValid()) flds = lyr.fields() oflds = olyr.fields() - self.assertEquals(oflds.size(), flds.size()) - for i in range(0, oflds.size()): - self.assertEqual(oflds[i].name(), flds[i].name()) + if key is None: + # if the pkey was not given, it will create a pkey + self.assertEquals(oflds.size(), flds.size() + 1) + self.assertEquals(oflds[0].name(), kfnames[0]) + for i in range(flds.size()): + self.assertEqual(oflds[i + 1].name(), flds[i].name()) + else: + # pkey was given, no extra field generated + self.assertEquals(oflds.size(), flds.size()) + for i in range(oflds.size()): + self.assertEqual(oflds[i].name(), flds[i].name()) pks = olyr.pkAttributeList() self.assertEquals(len(pks), len(kfnames)) for i in range(0, len(kfnames)): @@ -491,6 +501,7 @@ def testKey(lyr, key, kfnames): testKey(lyr, '"f1"', ['f1']) testKey(lyr, '"f1","F2"', ['f1', 'F2']) testKey(lyr, '"f1","F2","f3"', ['f1', 'F2', 'f3']) + testKey(lyr, None, ['id']) class TestPyQgsPostgresProviderCompoundKey(unittest.TestCase, ProviderTestCase): From 4f8ee78f76e5ad720cfbd3084e540356721fee92 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 14:13:09 +1000 Subject: [PATCH 559/897] Fix some no such signal/slot warnings ... in such a way that they'll never appear again --- src/app/qgisapp.cpp | 3 --- src/gui/qgsattributeform.cpp | 51 ++++++++++++++++++------------------ 2 files changed, 25 insertions(+), 29 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index e932c78e1869..0b27a5edac0e 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -10245,9 +10245,6 @@ void QgisApp::layersWereAdded( const QList& theLayers ) QgsRasterLayer *rlayer = qobject_cast( layer ); if ( rlayer ) { - // connect up any request the raster may make to update the app progress - connect( rlayer, SIGNAL( drawingProgress( int, int ) ), this, SLOT( showProgress( int, int ) ) ); - // connect up any request the raster may make to update the statusbar message connect( rlayer, &QgsRasterLayer::statusChanged, this, &QgisApp::showStatusMessage ); diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index a6be3ed3f795..6fa90407ead9 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -75,9 +75,9 @@ QgsAttributeForm::QgsAttributeForm( QgsVectorLayer* vl, const QgsFeature &featur initPython(); setFeature( feature ); - connect( vl, SIGNAL( updatedFields() ), this, SLOT( onUpdatedFields() ) ); - connect( vl, SIGNAL( beforeAddingExpressionField( QString ) ), this, SLOT( preventFeatureRefresh() ) ); - connect( vl, SIGNAL( beforeRemovingExpressionField( int ) ), this, SLOT( preventFeatureRefresh() ) ); + connect( vl, &QgsVectorLayer::updatedFields, this, &QgsAttributeForm::onUpdatedFields ); + connect( vl, &QgsVectorLayer::beforeAddingExpressionField, this, &QgsAttributeForm::preventFeatureRefresh ); + connect( vl, &QgsVectorLayer::beforeRemovingExpressionField, this, &QgsAttributeForm::preventFeatureRefresh ); connect( vl, SIGNAL( selectionChanged() ), this, SLOT( layerSelectionChanged() ) ); // constraints management @@ -96,20 +96,20 @@ void QgsAttributeForm::hideButtonBox() // Make sure that changes are taken into account if somebody tries to figure out if there have been some if ( mMode == SingleEditMode ) - connect( mLayer, SIGNAL( beforeModifiedCheck() ), this, SLOT( save() ) ); + connect( mLayer, &QgsVectorLayer::beforeModifiedCheck, this, &QgsAttributeForm::save ); } void QgsAttributeForm::showButtonBox() { mButtonBox->show(); - disconnect( mLayer, SIGNAL( beforeModifiedCheck() ), this, SLOT( save() ) ); + disconnect( mLayer, &QgsVectorLayer::beforeModifiedCheck, this, &QgsAttributeForm::save ); } void QgsAttributeForm::disconnectButtonBox() { - disconnect( mButtonBox, SIGNAL( accepted() ), this, SLOT( accept() ) ); - disconnect( mButtonBox, SIGNAL( rejected() ), this, SLOT( resetValues() ) ); + disconnect( mButtonBox, &QDialogButtonBox::accepted, this, &QgsAttributeForm::save ); + disconnect( mButtonBox, &QDialogButtonBox::rejected, this, &QgsAttributeForm::resetValues ); } void QgsAttributeForm::addInterface( QgsAttributeFormInterface* iface ) @@ -148,11 +148,11 @@ void QgsAttributeForm::setMode( QgsAttributeForm::Mode mode ) if ( mButtonBox->isVisible() && mMode == SingleEditMode ) { - connect( mLayer, SIGNAL( beforeModifiedCheck() ), this, SLOT( save() ) ); + connect( mLayer, &QgsVectorLayer::beforeModifiedCheck, this, &QgsAttributeForm::save ); } else { - disconnect( mLayer, SIGNAL( beforeModifiedCheck() ), this, SLOT( save() ) ); + disconnect( mLayer, &QgsVectorLayer::beforeModifiedCheck, this, &QgsAttributeForm::save ); } //update all form editor widget modes to match @@ -660,7 +660,7 @@ void QgsAttributeForm::onAttributeChanged( const QVariant& value ) QLabel *msgLabel = new QLabel( tr( "Unsaved multiedit changes: apply changes or reset changes." ), mMessageBar ); msgLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); msgLabel->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed ); - connect( msgLabel, SIGNAL( linkActivated( QString ) ), this, SLOT( multiEditMessageClicked( QString ) ) ); + connect( msgLabel, &QLabel::linkActivated, this, &QgsAttributeForm::multiEditMessageClicked ); clearMultiEditMessages(); mMultiEditUnsavedMessageBarItem = new QgsMessageBarItem( msgLabel, QgsMessageBar::WARNING ); @@ -1314,7 +1314,7 @@ void QgsAttributeForm::init() mSearchButtonBox->setObjectName( QStringLiteral( "searchButtonBox" ) ); QPushButton* clearButton = new QPushButton( tr( "&Reset form" ), mSearchButtonBox ); - connect( clearButton, SIGNAL( clicked( bool ) ), this, SLOT( resetSearch() ) ); + connect( clearButton, &QPushButton::clicked, this, &QgsAttributeForm::resetSearch ); boxLayout->addWidget( clearButton ); boxLayout->addStretch( 1 ); @@ -1322,19 +1322,19 @@ void QgsAttributeForm::init() selectButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); selectButton->setText( tr( "&Select features" ) ); selectButton->setPopupMode( QToolButton::MenuButtonPopup ); - connect( selectButton, SIGNAL( clicked( bool ) ), this, SLOT( searchSetSelection() ) ); + connect( selectButton, &QToolButton::clicked, this, &QgsAttributeForm::searchSetSelection ); QMenu* selectMenu = new QMenu( selectButton ); QAction* selectAction = new QAction( tr( "Select features" ), selectMenu ); - connect( selectAction, SIGNAL( triggered( bool ) ), this, SLOT( searchSetSelection() ) ); + connect( selectAction, &QAction::triggered, this, &QgsAttributeForm::searchSetSelection ); selectMenu->addAction( selectAction ); QAction* addSelectAction = new QAction( tr( "Add to current selection" ), selectMenu ); - connect( addSelectAction, SIGNAL( triggered( bool ) ), this, SLOT( searchAddToSelection() ) ); + connect( addSelectAction, &QAction::triggered, this, &QgsAttributeForm::searchAddToSelection ); selectMenu->addAction( addSelectAction ); QAction* filterSelectAction = new QAction( tr( "Filter current selection" ), selectMenu ); - connect( filterSelectAction, SIGNAL( triggered( bool ) ), this, SLOT( searchIntersectSelection() ) ); + connect( filterSelectAction, &QAction::triggered, this, &QgsAttributeForm::searchIntersectSelection ); selectMenu->addAction( filterSelectAction ); QAction* deselectAction = new QAction( tr( "Remove from current selection" ), selectMenu ); - connect( deselectAction, SIGNAL( triggered( bool ) ), this, SLOT( searchRemoveFromSelection() ) ); + connect( deselectAction, &QAction::triggered, this, &QgsAttributeForm::searchRemoveFromSelection ); selectMenu->addAction( deselectAction ); selectButton->setMenu( selectMenu ); boxLayout->addWidget( selectButton ); @@ -1345,13 +1345,13 @@ void QgsAttributeForm::init() filterButton->setText( tr( "Filter features" ) ); filterButton->setPopupMode( QToolButton::MenuButtonPopup ); filterButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum ); - connect( filterButton, SIGNAL( clicked( bool ) ), this, SLOT( filterTriggered() ) ); + connect( filterButton, &QToolButton::clicked, this, &QgsAttributeForm::filterTriggered ); QMenu* filterMenu = new QMenu( filterButton ); QAction* filterAndAction = new QAction( tr( "Filter within (\"AND\")" ), filterMenu ); - connect( filterAndAction, SIGNAL( triggered( bool ) ), this, SLOT( filterAndTriggered() ) ); + connect( filterAndAction, &QAction::triggered, this, &QgsAttributeForm::filterAndTriggered ); filterMenu->addAction( filterAndAction ); QAction* filterOrAction = new QAction( tr( "Extend filter (\"OR\")" ), filterMenu ); - connect( filterOrAction, SIGNAL( triggered( bool ) ), this, SLOT( filterOrTriggered() ) ); + connect( filterOrAction, &QAction::triggered, this, &QgsAttributeForm::filterOrTriggered ); filterMenu->addAction( filterOrAction ); filterButton->setMenu( filterMenu ); boxLayout->addWidget( filterButton ); @@ -1359,7 +1359,7 @@ void QgsAttributeForm::init() else { QPushButton* closeButton = new QPushButton( tr( "Close" ), mSearchButtonBox ); - connect( closeButton, SIGNAL( clicked( bool ) ), this, SIGNAL( closed() ) ); + connect( closeButton, &QPushButton::clicked, this, &QgsAttributeForm::closed ); closeButton->setShortcut( Qt::Key_Escape ); boxLayout->addWidget( closeButton ); } @@ -1370,11 +1370,11 @@ void QgsAttributeForm::init() afterWidgetInit(); - connect( mButtonBox, SIGNAL( accepted() ), this, SLOT( accept() ) ); - connect( mButtonBox, SIGNAL( rejected() ), this, SLOT( resetValues() ) ); + connect( mButtonBox, &QDialogButtonBox::accepted, this, &QgsAttributeForm::save ); + connect( mButtonBox, &QDialogButtonBox::rejected, this, &QgsAttributeForm::resetValues ); - connect( mLayer, SIGNAL( editingStarted() ), this, SLOT( synchronizeEnabledState() ) ); - connect( mLayer, SIGNAL( editingStopped() ), this, SLOT( synchronizeEnabledState() ) ); + connect( mLayer, &QgsVectorLayer::editingStarted, this, &QgsAttributeForm::synchronizeEnabledState ); + connect( mLayer, &QgsVectorLayer::editingStopped, this, &QgsAttributeForm::synchronizeEnabledState ); Q_FOREACH ( QgsAttributeFormInterface* iface, mInterfaces ) { @@ -1750,8 +1750,7 @@ void QgsAttributeForm::afterWidgetInit() } connect( eww, SIGNAL( valueChanged( const QVariant& ) ), this, SLOT( onAttributeChanged( const QVariant& ) ) ); - connect( eww, SIGNAL( constraintStatusChanged( QString, QString, QString, bool ) ), - this, SLOT( onConstraintStatusChanged( QString, QString, QString, bool ) ) ); + connect( eww, &QgsEditorWidgetWrapper::constraintStatusChanged, this, &QgsAttributeForm::onConstraintStatusChanged ); } } From 667718bc89e0bf54f84d0d66d117ae7052cd5c0c Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Tue, 1 Nov 2016 08:36:21 +0100 Subject: [PATCH 560/897] [feature] Editor widget auto config for foreign keys (#3699) Automatically pick RelationReference widgets for foreign keys. --- .../qgsrelationreferencefactory.cpp | 6 +++++ .../qgsrelationreferencefactory.h | 2 ++ .../qgsrelationreferencewidgetwrapper.cpp | 5 +++- tests/src/gui/testqgseditorwidgetregistry.cpp | 27 +++++++++++++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp index 33675756f90c..24115e3ec7ac 100644 --- a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp @@ -181,3 +181,9 @@ QVariant QgsRelationReferenceFactory::sortValue( QgsVectorLayer* vl, int fieldId { return representValue( vl, fieldIdx, config, cache, value ); } + +unsigned int QgsRelationReferenceFactory::fieldScore( const QgsVectorLayer* vl, int fieldIdx ) const +{ + const QList relations = vl->referencingRelations( fieldIdx ); + return !relations.isEmpty() ? 21 /*A bit stronger than the range widget*/ : 5; +} \ No newline at end of file diff --git a/src/gui/editorwidgets/qgsrelationreferencefactory.h b/src/gui/editorwidgets/qgsrelationreferencefactory.h index 42e14e7d263a..adeb55674035 100644 --- a/src/gui/editorwidgets/qgsrelationreferencefactory.h +++ b/src/gui/editorwidgets/qgsrelationreferencefactory.h @@ -88,6 +88,8 @@ class GUI_EXPORT QgsRelationReferenceFactory : public QgsEditorWidgetFactory virtual QHash supportedWidgetTypes() override; + virtual unsigned int fieldScore( const QgsVectorLayer* vl, int fieldIdx ) const override; + private: QgsAttributeEditorContext mEditorContext; QgsMapCanvas* mCanvas; diff --git a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp index a0e0ee2d051d..6d5db05fa422 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp @@ -62,7 +62,10 @@ void QgsRelationReferenceWidgetWrapper::initWidget( QWidget* editor ) } mWidget->setAllowAddFeatures( config( QStringLiteral( "AllowAddFeatures" ), false ).toBool() ); - QgsRelation relation = QgsProject::instance()->relationManager()->relation( config( QStringLiteral( "Relation" ) ).toString() ); + const QVariant relationName = config( QStringLiteral( "Relation" ) ); + QgsRelation relation = relationName.isValid() ? + QgsProject::instance()->relationManager()->relation( relationName.toString() ) : + layer()->referencingRelations( fieldIdx() )[0]; // If this widget is already embedded by the same relation, reduce functionality const QgsAttributeEditorContext* ctx = &context(); diff --git a/tests/src/gui/testqgseditorwidgetregistry.cpp b/tests/src/gui/testqgseditorwidgetregistry.cpp index 545604beaff0..2322699188d3 100644 --- a/tests/src/gui/testqgseditorwidgetregistry.cpp +++ b/tests/src/gui/testqgseditorwidgetregistry.cpp @@ -16,6 +16,9 @@ #include "qgseditorwidgetregistry.h" #include "qgseditorwidgetautoconf.h" +#include "qgsproject.h" +#include "qgsrelationmanager.h" +#include "qgsmaplayerregistry.h" class TestQgsEditorWidgetRegistry: public QObject @@ -109,6 +112,30 @@ class TestQgsEditorWidgetRegistry: public QObject QCOMPARE( setup.config().count(), 0 ); } + void referencedLayers() + { + //build two layers + QgsVectorLayer vl1( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=name:string&field=fk:int" ), QStringLiteral( "vl1" ), QStringLiteral( "memory" ) ); + QgsVectorLayer vl2( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=col1:string" ), QStringLiteral( "vl2" ), QStringLiteral( "memory" ) ); + QgsMapLayerRegistry::instance()->addMapLayer( &vl1, false, false ); + QgsMapLayerRegistry::instance()->addMapLayer( &vl2, false, false ); + + //create a relation between them + QgsRelation relation; + relation.setRelationId( QStringLiteral( "vl1->vl2" ) ); + relation.setRelationName( QStringLiteral( "vl1->vl2" ) ); + relation.setReferencingLayer( vl1.id() ); + relation.setReferencedLayer( vl2.id() ); + relation.addFieldPair( "fk", "pk" ); + QVERIFY( relation.isValid() ); + QgsProject::instance()->relationManager()->addRelation( relation ); + + //check the guessed editor widget type for vl1.fk is RelationReference + const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( &vl1, QStringLiteral( "fk" ) ); + QCOMPARE( setup.type(), QString( "RelationReference" ) ); + QCOMPARE( setup.config(), QgsEditorWidgetConfig() ); + } + void typeFromPlugin() { const QgsVectorLayer vl( QStringLiteral( "LineString?crs=epsg:3111&field=pk:int&field=special:string" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); From 7a326b1b8d7026bc2782afc0fdc5abbaa1065370 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 1 Nov 2016 13:46:29 +0100 Subject: [PATCH 561/897] fix typos --- python/gui/qgsextentgroupbox.sip | 2 +- python/plugins/processing/algs/help/qgis.yaml | 4 ++-- src/gui/qgsextentgroupbox.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/gui/qgsextentgroupbox.sip b/python/gui/qgsextentgroupbox.sip index 1a5c6589d4d6..c2b72d0e2ae5 100644 --- a/python/gui/qgsextentgroupbox.sip +++ b/python/gui/qgsextentgroupbox.sip @@ -58,7 +58,7 @@ class QgsExtentGroupBox : QgsCollapsibleGroupBox //! set output extent to be the same as current extent (may be transformed to output CRS) void setOutputExtentFromCurrent(); - //! set output extent to custom extent (may be transformed to outut CRS) + //! set output extent to custom extent (may be transformed to output CRS) void setOutputExtentFromUser( const QgsRectangle& extent, const QgsCoordinateReferenceSystem& crs ); signals: diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index 8c5d7f7b3ada..f09998838074 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -484,9 +484,9 @@ qgis:splitlineswithlines: > This algorithm split the lines in a line layer using the lines in another line layer to define the breaking points. Intersection between geometries in both layers are considered as split points. qgis:splitvectorlayer: > - This algorithm takes a vector layer and an attribute and generates a set of vector layers in an outut folder. Each of the layers created in that folder contains all features from the input layer with the same value for the specified attribute. + This algorithm takes a vector layer and an attribute and generates a set of vector layers in an output folder. Each of the layers created in that folder contains all features from the input layer with the same value for the specified attribute. - The number of files generated is equal to the nuber of different values found for the specified attribute. + The number of files generated is equal to the nubmer of different values found for the specified attribute. qgis:statisticsbycategories: diff --git a/src/gui/qgsextentgroupbox.h b/src/gui/qgsextentgroupbox.h index 54835617a34e..306ae2ef96b6 100644 --- a/src/gui/qgsextentgroupbox.h +++ b/src/gui/qgsextentgroupbox.h @@ -84,7 +84,7 @@ class GUI_EXPORT QgsExtentGroupBox : public QgsCollapsibleGroupBox, private Ui:: //! set output extent to be the same as current extent (may be transformed to output CRS) void setOutputExtentFromCurrent(); - //! set output extent to custom extent (may be transformed to outut CRS) + //! set output extent to custom extent (may be transformed to output CRS) void setOutputExtentFromUser( const QgsRectangle& extent, const QgsCoordinateReferenceSystem& crs ); signals: From d3c7a0419329f57704a6f9b9f63970b5f7dee45a Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 1 Nov 2016 13:50:39 +0100 Subject: [PATCH 562/897] fix typo (cherry picked from commit 658cfe68c91ec24f04f8ebda307fbec7d55a412f) --- python/plugins/processing/algs/help/qgis.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index f09998838074..a718d0ca8be1 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -486,7 +486,7 @@ qgis:splitlineswithlines: > qgis:splitvectorlayer: > This algorithm takes a vector layer and an attribute and generates a set of vector layers in an output folder. Each of the layers created in that folder contains all features from the input layer with the same value for the specified attribute. - The number of files generated is equal to the nubmer of different values found for the specified attribute. + The number of files generated is equal to the number of different values found for the specified attribute. qgis:statisticsbycategories: From b679cbe0918915030b8991272eab32240070038a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 08:10:52 +1000 Subject: [PATCH 563/897] Speed up inserting features into memory layers by ~65% By avoiding an unnecessary map lookup --- src/providers/memory/qgsmemoryprovider.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/providers/memory/qgsmemoryprovider.cpp b/src/providers/memory/qgsmemoryprovider.cpp index 98b4be42adf3..f82e3367a9bd 100644 --- a/src/providers/memory/qgsmemoryprovider.cpp +++ b/src/providers/memory/qgsmemoryprovider.cpp @@ -301,15 +301,14 @@ bool QgsMemoryProvider::addFeatures( QgsFeatureList & flist ) // TODO: sanity checks of fields and geometries for ( QgsFeatureList::iterator it = flist.begin(); it != flist.end(); ++it ) { - mFeatures[mNextFeatureId] = *it; - QgsFeature& newfeat = mFeatures[mNextFeatureId]; - newfeat.setFeatureId( mNextFeatureId ); - newfeat.setValid( true ); it->setFeatureId( mNextFeatureId ); + it->setValid( true ); + + mFeatures.insert( mNextFeatureId, *it ); // update spatial index if ( mSpatialIndex ) - mSpatialIndex->insertFeature( newfeat ); + mSpatialIndex->insertFeature( *it ); mNextFeatureId++; } From fb849620e7f7927f5b9453f35fb4bd62f3244e13 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 09:38:02 +1000 Subject: [PATCH 564/897] Avoid unexpected gpkg test success with older GDAL versions --- tests/src/python/test_provider_ogr_gpkg.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index 0f1201190975..6cd4c77af14c 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -162,7 +162,7 @@ def testBug15351_commit_closeProvider_closeIter(self): def testBug15351_commit_closeIter_closeProvider(self): self.internalTestBug15351('commit_closeIter_closeProvider') - @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 1, 2)) + @unittest.skip(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 1, 2)) def testGeopackageExtentUpdate(self): ''' test http://hub.qgis.org/issues/15273 ''' tmpfile = os.path.join(self.basetestpath, 'testGeopackageExtentUpdate.gpkg') From 57a57545a038e09036afc78f2f7b86c43e265c50 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 13:42:53 +0100 Subject: [PATCH 565/897] Add test for QgsFeatureRequest.setLimit and feature variable --- tests/src/python/providertestbase.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/src/python/providertestbase.py b/tests/src/python/providertestbase.py index a10ad0bae239..a492ac1d58fa 100644 --- a/tests/src/python/providertestbase.py +++ b/tests/src/python/providertestbase.py @@ -15,7 +15,16 @@ # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' -from qgis.core import QgsRectangle, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsAbstractFeatureIterator, NULL +from qgis.core import ( + QgsRectangle, + QgsFeatureRequest, + QgsFeature, + QgsGeometry, + QgsAbstractFeatureIterator, + QgsExpressionContextScope, + QgsExpressionContext, + NULL +) from utilities import( compareWkt @@ -190,6 +199,21 @@ def runGetFeatureTests(self, provider): # geometry self.assert_query(provider, 'intersects($geometry,geom_from_wkt( \'Polygon ((-72.2 66.1, -65.2 66.1, -65.2 72.0, -72.2 72.0, -72.2 66.1))\'))', [1, 2]) + # combination of an uncompilable expression and limit + feature = next(self.vl.getFeatures('pk=4')) + context = QgsExpressionContext() + scope = QgsExpressionContextScope() + scope.setVariable('parent', feature) + context.appendScope(scope) + + request = QgsFeatureRequest() + request.setExpressionContext(context) + request.setFilterExpression('"pk" = attribute(@parent, \'pk\')') + request.setLimit(1) + + values = [f['pk'] for f in self.vl.getFeatures(request)] + self.assertEqual(values, [4]) + def testGetFeaturesUncompiled(self): self.compiled = False try: From 5e3bef77995cec25c1adedd5c882eb68ee3e004b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 09:52:03 +1000 Subject: [PATCH 566/897] Fix QgsFeatureRequest with expression not using provider fields and limit (fix #15771) --- src/core/qgsvectorlayerfeatureiterator.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/core/qgsvectorlayerfeatureiterator.cpp b/src/core/qgsvectorlayerfeatureiterator.cpp index b16c84e0a4f3..28a86426a8f8 100644 --- a/src/core/qgsvectorlayerfeatureiterator.cpp +++ b/src/core/qgsvectorlayerfeatureiterator.cpp @@ -159,6 +159,8 @@ QgsVectorLayerFeatureIterator::QgsVectorLayerFeatureIterator( QgsVectorLayerFeat if ( source->mFields.fieldOrigin( idx ) != QgsFields::OriginProvider ) { mProviderRequest.disableFilter(); + // can't limit at provider side + mProviderRequest.setLimit( -1 ); } } } From d1fd588499c3ed6ffdedb5a3c1d6a0f3f2be7f87 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 10:40:32 +1000 Subject: [PATCH 567/897] Add method to fetch constraints from a vector data provider Implemented for unique and not null constraints for postgres provider --- python/core/qgsvectordataprovider.sip | 19 ++++++++++++ src/core/qgsvectordataprovider.cpp | 6 ++++ src/core/qgsvectordataprovider.h | 19 ++++++++++++ .../postgres/qgspostgresprovider.cpp | 24 ++++++++++++++- src/providers/postgres/qgspostgresprovider.h | 2 ++ tests/src/python/test_provider_postgres.py | 29 +++++++++++++++++++ tests/testdata/provider/testdata_pg.sql | 21 ++++++++++++++ 7 files changed, 119 insertions(+), 1 deletion(-) diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 198b57c5f646..c90e9f78a220 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -55,6 +55,17 @@ class QgsVectorDataProvider : QgsDataProvider /** Bitmask of all provider's editing capabilities */ static const int EditingCapabilities; + /** + * Constraints which may be present on a field. + * @note added in QGIS 3.0 + */ + enum Constraint + { + ConstraintNotNull, //!< Field may not be null + ConstraintUnique, //!< Field must have a unique value + }; + typedef QFlags Constraints; + /** * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset @@ -230,6 +241,13 @@ class QgsVectorDataProvider : QgsDataProvider */ virtual QVariant defaultValue( int fieldId ) const; + /** + * Returns any constraints which are present at the provider for a specified + * field index. + * @note added in QGIS 3.0 + */ + virtual QgsVectorDataProvider::Constraints fieldConstraints( int fieldIndex ) const; + /** * Changes geometries of existing features * @param geometry_map A QgsGeometryMap whose index contains the feature IDs @@ -434,3 +452,4 @@ class QgsVectorDataProvider : QgsDataProvider }; QFlags operator|(QgsVectorDataProvider::Capability f1, QFlags f2); +QFlags operator|(QgsVectorDataProvider::Constraint f1, QFlags f2); diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 7387e828f85c..83baf2aee32c 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -98,6 +98,12 @@ QVariant QgsVectorDataProvider::defaultValue( int fieldId ) const return QVariant(); } +QgsVectorDataProvider::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const +{ + Q_UNUSED( fieldIndex ); + return 0; +} + bool QgsVectorDataProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) { Q_UNUSED( geometry_map ); diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index bb5c967ab81c..f6bf37ab990a 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -106,6 +106,17 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider ChangeAttributeValues | ChangeGeometries | AddAttributes | DeleteAttributes | RenameAttributes; + /** + * Constraints which may be present on a field. + * @note added in QGIS 3.0 + */ + enum Constraint + { + ConstraintNotNull = 1, //!< Field may not be null + ConstraintUnique = 1 << 1, //!< Field must have a unique value + }; + Q_DECLARE_FLAGS( Constraints, Constraint ) + /** * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset @@ -281,6 +292,13 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ virtual QVariant defaultValue( int fieldId ) const; + /** + * Returns any constraints which are present at the provider for a specified + * field index. + * @note added in QGIS 3.0 + */ + virtual Constraints fieldConstraints( int fieldIndex ) const; + /** * Changes geometries of existing features * @param geometry_map A QgsGeometryMap whose index contains the feature IDs @@ -520,6 +538,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider }; Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorDataProvider::Capabilities ) +Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorDataProvider::Constraints ) #endif diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 417982e89f4e..de298cfda3a0 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -718,6 +718,7 @@ bool QgsPostgresProvider::loadFields() QMap > fmtFieldTypeMap, descrMap, defValMap; QMap > attTypeIdMap; + QMap > notNullMap, uniqueMap; if ( result.PQnfields() > 0 ) { // Collect table oids @@ -742,9 +743,13 @@ bool QgsPostgresProvider::loadFields() QString tableoidsFilter = '(' + tableoidsList.join( QStringLiteral( "," ) ) + ')'; // Collect formatted field types - sql = "SELECT attrelid, attnum, pg_catalog.format_type(atttypid,atttypmod), pg_catalog.col_description(attrelid,attnum), pg_catalog.pg_get_expr(adbin,adrelid), atttypid" + sql = "SELECT attrelid, attnum, pg_catalog.format_type(atttypid,atttypmod), pg_catalog.col_description(attrelid,attnum), pg_catalog.pg_get_expr(adbin,adrelid), atttypid, attnotnull::int, indisunique::int" " FROM pg_attribute" " LEFT OUTER JOIN pg_attrdef ON attrelid=adrelid AND attnum=adnum" + + // find unique constraints if present. Text cast required to handle int2vector comparison. Distinct required as multiple unique constraints may exist + " LEFT OUTER JOIN ( SELECT DISTINCT indrelid, indkey, indisunique FROM pg_index WHERE indisunique ) uniq ON attrelid=indrelid AND attnum::text=indkey::text " + " WHERE attrelid IN " + tableoidsFilter; QgsPostgresResult fmtFieldTypeResult( connectionRO()->PQexec( sql ) ); for ( int i = 0; i < fmtFieldTypeResult.PQntuples(); ++i ) @@ -755,10 +760,14 @@ bool QgsPostgresProvider::loadFields() QString descr = fmtFieldTypeResult.PQgetvalue( i, 3 ); QString defVal = fmtFieldTypeResult.PQgetvalue( i, 4 ); int attType = fmtFieldTypeResult.PQgetvalue( i, 5 ).toInt(); + bool attNotNull = fmtFieldTypeResult.PQgetvalue( i, 6 ).toInt(); + bool uniqueConstraint = fmtFieldTypeResult.PQgetvalue( i, 7 ).toInt(); fmtFieldTypeMap[attrelid][attnum] = formatType; descrMap[attrelid][attnum] = descr; defValMap[attrelid][attnum] = defVal; attTypeIdMap[attrelid][attnum] = attType; + notNullMap[attrelid][attnum] = attNotNull; + uniqueMap[attrelid][attnum] = uniqueConstraint; } } } @@ -988,6 +997,14 @@ bool QgsPostgresProvider::loadFields() mAttrPalIndexName.insert( i, fieldName ); mDefaultValues.insert( mAttributeFields.size(), defValMap[tableoid][attnum] ); + + Constraints constraints = 0; + if ( notNullMap[tableoid][attnum] ) + constraints |= ConstraintNotNull; + if ( uniqueMap[tableoid][attnum] ) + constraints |= ConstraintUnique; + mFieldConstraints.insert( mAttributeFields.size(), constraints ); + mAttributeFields.append( QgsField( fieldName, fieldType, fieldTypeName, fieldSize, fieldPrec, fieldComment, fieldSubType ) ); } @@ -1719,6 +1736,11 @@ QVariant QgsPostgresProvider::defaultValue( int fieldId ) const return defVal; } +QgsVectorDataProvider::Constraints QgsPostgresProvider::fieldConstraints( int fieldIndex ) const +{ + return mFieldConstraints.value( fieldIndex, 0 ); +} + QString QgsPostgresProvider::paramValue( const QString& fieldValue, const QString &defaultValue ) const { if ( fieldValue.isNull() ) diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index eb90e2d770db..6d6b35b78b39 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -161,6 +161,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider QgsAttributeList attributeIndexes() const override; QgsAttributeList pkAttributeIndexes() const override { return mPrimaryKeyAttrs; } QVariant defaultValue( int fieldId ) const override; + Constraints fieldConstraints( int fieldIndex ) const override; /** Adds a list of features @return true in case of success and false in case of failure*/ @@ -493,6 +494,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider void setTransaction( QgsTransaction* transaction ) override; QHash mDefaultValues; + QHash mFieldConstraints; }; diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 0935ec42f013..32d0e529c4bb 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -26,6 +26,7 @@ QgsFeatureRequest, QgsFeature, QgsTransactionGroup, + QgsVectorDataProvider, NULL ) from qgis.gui import QgsEditorWidgetRegistry @@ -437,6 +438,34 @@ def testDoubleArray(self): self.assertTrue(isinstance(f.attributes()[value_idx], list)) self.assertEqual(f.attributes()[value_idx], [1.1, 2, -5.12345]) + def testNotNullConstraint(self): + vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") + self.assertTrue(vl.isValid()) + self.assertEqual(len(vl.fields()), 4) + + # test some bad field indexes + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsVectorDataProvider.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsVectorDataProvider.Constraints()) + + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsVectorDataProvider.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsVectorDataProvider.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsVectorDataProvider.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsVectorDataProvider.ConstraintNotNull) + + def testUniqueConstraint(self): + vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") + self.assertTrue(vl.isValid()) + self.assertEqual(len(vl.fields()), 4) + + # test some bad field indexes + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsVectorDataProvider.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsVectorDataProvider.Constraints()) + + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsVectorDataProvider.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsVectorDataProvider.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsVectorDataProvider.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsVectorDataProvider.ConstraintUnique) + # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): uri = 'point?field=f1:int' diff --git a/tests/testdata/provider/testdata_pg.sql b/tests/testdata/provider/testdata_pg.sql index 4c9e10b6286d..4299b2f43e31 100644 --- a/tests/testdata/provider/testdata_pg.sql +++ b/tests/testdata/provider/testdata_pg.sql @@ -458,3 +458,24 @@ CREATE TABLE qgis_test.widget_styles( INSERT INTO qgis_editor_widget_styles VALUES ('qgis_test', 'widget_styles', 'fld1', 'FooEdit', ''); + + +----------------------------- +-- Table for constraint tests +-- + +DROP TABLE IF EXISTS qgis_test.constraints; +CREATE TABLE qgis_test.constraints +( + gid serial NOT NULL PRIMARY KEY, -- implicit unique key + val int, -- unique constraint + name text NOT NULL, -- unique index + description text, + CONSTRAINT constraint_val UNIQUE (val), + CONSTRAINT constraint_val2 UNIQUE (val) -- create double unique constraint for test +); + +CREATE UNIQUE INDEX constraints_uniq + ON qgis_test.constraints + USING btree + (name COLLATE pg_catalog."default"); -- unique index From f6c1bf7f5b3d2e3277a0bf8510665f09bfccd3e8 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 11:10:14 +1000 Subject: [PATCH 568/897] Add gui for setting/exposing constraints in field properties Provider set constraints cannot be changed by users, ie if a not null constraint is set on the field at the database then QGIS users cannot clear this constraint. --- src/app/qgsattributetypedialog.cpp | 27 +++++++++++++++++++++++++++ src/app/qgsattributetypedialog.h | 16 ++++++++++++++++ src/app/qgsfieldsproperties.cpp | 6 ++++++ src/ui/qgsattributetypeedit.ui | 20 ++++++++++++++------ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 94b119292726..0c3dc55684e6 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -176,6 +176,23 @@ bool QgsAttributeTypeDialog::fieldEditable() const return isFieldEditableCheckBox->isChecked(); } +void QgsAttributeTypeDialog::setProviderConstraints( QgsVectorDataProvider::Constraints constraints ) +{ + if ( constraints & QgsVectorDataProvider::ConstraintNotNull ) + { + notNullCheckBox->setChecked( true ); + notNullCheckBox->setEnabled( false ); + notNullCheckBox->setToolTip( tr( "The provider for this layer has a NOT NULL constraint set on the field." ) ); + } + + if ( constraints & QgsVectorDataProvider::ConstraintUnique ) + { + mUniqueCheckBox->setChecked( true ); + mUniqueCheckBox->setEnabled( false ); + mUniqueCheckBox->setToolTip( tr( "The provider for this layer has a UNIQUE constraint set on the field." ) ); + } +} + void QgsAttributeTypeDialog::setNotNull( bool notNull ) { notNullCheckBox->setChecked( notNull ); @@ -201,6 +218,16 @@ bool QgsAttributeTypeDialog::notNull() const return notNullCheckBox->isChecked(); } +void QgsAttributeTypeDialog::setUnique( bool unique ) +{ + mUniqueCheckBox->setChecked( unique ); +} + +bool QgsAttributeTypeDialog::unique() const +{ + return mUniqueCheckBox->isChecked(); +} + void QgsAttributeTypeDialog::setConstraintExpression( const QString &str ) { constraintExpressionWidget->setField( str ); diff --git a/src/app/qgsattributetypedialog.h b/src/app/qgsattributetypedialog.h index 70d0df8dc82d..9dfed439affd 100644 --- a/src/app/qgsattributetypedialog.h +++ b/src/app/qgsattributetypedialog.h @@ -21,6 +21,7 @@ #include "qgseditorconfigwidget.h" #include "qgsfeature.h" +#include "qgsvectordataprovider.h" class QDialog; @@ -69,6 +70,11 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut */ bool fieldEditable() const; + /** + * Sets any provider side constraints which may affect this field's behaviour. + */ + void setProviderConstraints( QgsVectorDataProvider::Constraints constraints ); + /** * Setter for checkbox for not null */ @@ -79,6 +85,16 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut */ bool notNull() const; + /** + * Setter for unique constraint checkbox + */ + void setUnique( bool unique ); + + /** + * Getter for unique constraint checkbox state + */ + bool unique() const; + /** * Setter for constraint expression description * @param desc the expression description diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index c644370df274..8d37db34e109 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -559,6 +559,12 @@ void QgsFieldsProperties::attributeTypeDialog() attributeTypeDialog.setFieldEditable( cfg.mEditable ); attributeTypeDialog.setLabelOnTop( cfg.mLabelOnTop ); attributeTypeDialog.setNotNull( cfg.mNotNull ); + + if ( mLayer->fields().fieldOrigin( index ) == QgsFields::OriginProvider ) + { + attributeTypeDialog.setProviderConstraints( mLayer->dataProvider()->fieldConstraints( mLayer->fields().fieldOriginIndex( index ) ) ); + } + attributeTypeDialog.setConstraintExpression( cfg.mConstraint ); attributeTypeDialog.setConstraintExpressionDescription( cfg.mConstraintDescription ); attributeTypeDialog.setDefaultValueExpression( mLayer->defaultValueExpression( index ) ); diff --git a/src/ui/qgsattributetypeedit.ui b/src/ui/qgsattributetypeedit.ui index 39f5ed69282d..bae9edc17726 100644 --- a/src/ui/qgsattributetypeedit.ui +++ b/src/ui/qgsattributetypeedit.ui @@ -30,6 +30,13 @@ + + + + Unique + + + @@ -144,18 +151,18 @@ - - QgsExpressionLineEdit - QWidget -
                                                                                                                                                                                      qgsexpressionlineedit.h
                                                                                                                                                                                      - 1 -
                                                                                                                                                                                      QgsCollapsibleGroupBox QGroupBox
                                                                                                                                                                                      qgscollapsiblegroupbox.h
                                                                                                                                                                                      1
                                                                                                                                                                                      + + QgsExpressionLineEdit + QWidget +
                                                                                                                                                                                      qgsexpressionlineedit.h
                                                                                                                                                                                      + 1 +
                                                                                                                                                                                      QgsFieldExpressionWidget QWidget @@ -169,6 +176,7 @@ labelOnTopCheckBox mExpressionWidget notNullCheckBox + mUniqueCheckBox constraintExpressionWidget leConstraintExpressionDescription From 4efad04bd821da61d79f3501cd3d1b64a4587a04 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 13:42:06 +1000 Subject: [PATCH 569/897] Move constraints to QgsField --- python/core/qgsfield.sip | 28 +++++++++++++ python/core/qgsvectordataprovider.sip | 14 +------ src/app/qgsattributetypedialog.cpp | 6 +-- src/app/qgsattributetypedialog.h | 2 +- src/core/qgsfield.cpp | 16 ++++++- src/core/qgsfield.h | 29 +++++++++++++ src/core/qgsfield_p.h | 8 +++- src/core/qgsvectordataprovider.cpp | 2 +- src/core/qgsvectordataprovider.h | 15 +------ src/core/qgsvectorlayer.cpp | 16 +++++++ src/core/qgsvectorlayer.h | 8 ++++ .../postgres/qgspostgresprovider.cpp | 19 +++++---- src/providers/postgres/qgspostgresprovider.h | 3 +- tests/src/core/testqgsfield.cpp | 12 ++++++ tests/src/python/test_provider_postgres.py | 42 ++++++++++++------- 15 files changed, 162 insertions(+), 58 deletions(-) diff --git a/python/core/qgsfield.sip b/python/core/qgsfield.sip index 5ac7bd39085e..7140a63abbfd 100644 --- a/python/core/qgsfield.sip +++ b/python/core/qgsfield.sip @@ -14,6 +14,18 @@ class QgsField %End public: + + /** + * Constraints which may be present on a field. + * @note added in QGIS 3.0 + */ + enum Constraint + { + ConstraintNotNull, //!< Field may not be null + ConstraintUnique, //!< Field must have a unique value + }; + typedef QFlags Constraints; + /** Constructor. Constructs a new QgsField object. * @param name Field name * @param type Field variant type, currently supported: String / Int / Double @@ -162,6 +174,20 @@ class QgsField */ void setDefaultValueExpression( const QString& expression ); + /** + * Returns any constraints which are present for the field. + * @note added in QGIS 3.0 + * @see setConstraints() + */ + Constraints constraints() const; + + /** + * Sets constraints which are present for the field. + * @note added in QGIS 3.0 + * @see constraints() + */ + void setConstraints( Constraints constraints ); + /** Returns the alias for the field (the friendly displayed name of the field ), * or an empty string if there is no alias. * @see setAlias() @@ -254,3 +280,5 @@ class QgsField */ const QgsEditorWidgetSetup& editorWidgetSetup() const; }; // class QgsField + +QFlags operator|(QgsField::Constraint f1, QFlags f2); diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index c90e9f78a220..37a309f932e5 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -55,17 +55,6 @@ class QgsVectorDataProvider : QgsDataProvider /** Bitmask of all provider's editing capabilities */ static const int EditingCapabilities; - /** - * Constraints which may be present on a field. - * @note added in QGIS 3.0 - */ - enum Constraint - { - ConstraintNotNull, //!< Field may not be null - ConstraintUnique, //!< Field must have a unique value - }; - typedef QFlags Constraints; - /** * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset @@ -246,7 +235,7 @@ class QgsVectorDataProvider : QgsDataProvider * field index. * @note added in QGIS 3.0 */ - virtual QgsVectorDataProvider::Constraints fieldConstraints( int fieldIndex ) const; + virtual QgsField::Constraints fieldConstraints( int fieldIndex ) const; /** * Changes geometries of existing features @@ -452,4 +441,3 @@ class QgsVectorDataProvider : QgsDataProvider }; QFlags operator|(QgsVectorDataProvider::Capability f1, QFlags f2); -QFlags operator|(QgsVectorDataProvider::Constraint f1, QFlags f2); diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 0c3dc55684e6..4d40b199af3d 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -176,16 +176,16 @@ bool QgsAttributeTypeDialog::fieldEditable() const return isFieldEditableCheckBox->isChecked(); } -void QgsAttributeTypeDialog::setProviderConstraints( QgsVectorDataProvider::Constraints constraints ) +void QgsAttributeTypeDialog::setProviderConstraints( QgsField::Constraints constraints ) { - if ( constraints & QgsVectorDataProvider::ConstraintNotNull ) + if ( constraints & QgsField::ConstraintNotNull ) { notNullCheckBox->setChecked( true ); notNullCheckBox->setEnabled( false ); notNullCheckBox->setToolTip( tr( "The provider for this layer has a NOT NULL constraint set on the field." ) ); } - if ( constraints & QgsVectorDataProvider::ConstraintUnique ) + if ( constraints & QgsField::ConstraintUnique ) { mUniqueCheckBox->setChecked( true ); mUniqueCheckBox->setEnabled( false ); diff --git a/src/app/qgsattributetypedialog.h b/src/app/qgsattributetypedialog.h index 9dfed439affd..73995032f30e 100644 --- a/src/app/qgsattributetypedialog.h +++ b/src/app/qgsattributetypedialog.h @@ -73,7 +73,7 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut /** * Sets any provider side constraints which may affect this field's behaviour. */ - void setProviderConstraints( QgsVectorDataProvider::Constraints constraints ); + void setProviderConstraints( QgsField::Constraints constraints ); /** * Setter for checkbox for not null diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index ec1611ddecb7..091025962a98 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -180,6 +180,16 @@ void QgsField::setDefaultValueExpression( const QString& expression ) d->defaultValueExpression = expression; } +QgsField::Constraints QgsField::constraints() const +{ + return d->constraints; +} + +void QgsField::setConstraints( Constraints constraints ) +{ + d->constraints = constraints; +} + QString QgsField::alias() const { return d->alias; @@ -303,15 +313,16 @@ QDataStream& operator<<( QDataStream& out, const QgsField& field ) out << field.comment(); out << field.alias(); out << field.defaultValueExpression(); + out << field.constraints(); out << static_cast< quint32 >( field.subType() ); return out; } QDataStream& operator>>( QDataStream& in, QgsField& field ) { - quint32 type, subType, length, precision; + quint32 type, subType, length, precision, constraints; QString name, typeName, comment, alias, defaultValueExpression; - in >> name >> type >> typeName >> length >> precision >> comment >> alias >> defaultValueExpression >> subType; + in >> name >> type >> typeName >> length >> precision >> comment >> alias >> defaultValueExpression >> constraints >> subType; field.setName( name ); field.setType( static_cast< QVariant::Type >( type ) ); field.setTypeName( typeName ); @@ -320,6 +331,7 @@ QDataStream& operator>>( QDataStream& in, QgsField& field ) field.setComment( comment ); field.setAlias( alias ); field.setDefaultValueExpression( defaultValueExpression ); + field.setConstraints( static_cast< QgsField::Constraints>( constraints ) ); field.setSubType( static_cast< QVariant::Type >( subType ) ); return in; } diff --git a/src/core/qgsfield.h b/src/core/qgsfield.h index 1e5ed1d5bc81..6fadb60ce702 100644 --- a/src/core/qgsfield.h +++ b/src/core/qgsfield.h @@ -54,8 +54,21 @@ class CORE_EXPORT QgsField Q_PROPERTY( QString name READ name WRITE setName ) Q_PROPERTY( QString alias READ alias WRITE setAlias ) Q_PROPERTY( QString defaultValueExpression READ defaultValueExpression WRITE setDefaultValueExpression ) + Q_PROPERTY( Constraints constraints READ constraints WRITE setConstraints ) public: + + /** + * Constraints which may be present on a field. + * @note added in QGIS 3.0 + */ + enum Constraint + { + ConstraintNotNull = 1, //!< Field may not be null + ConstraintUnique = 1 << 1, //!< Field must have a unique value + }; + Q_DECLARE_FLAGS( Constraints, Constraint ) + /** Constructor. Constructs a new QgsField object. * @param name Field name * @param type Field variant type, currently supported: String / Int / Double @@ -208,6 +221,20 @@ class CORE_EXPORT QgsField */ void setDefaultValueExpression( const QString& expression ); + /** + * Returns any constraints which are present for the field. + * @note added in QGIS 3.0 + * @see setConstraints() + */ + Constraints constraints() const; + + /** + * Sets constraints which are present for the field. + * @note added in QGIS 3.0 + * @see constraints() + */ + void setConstraints( Constraints constraints ); + /** Returns the alias for the field (the friendly displayed name of the field ), * or an empty string if there is no alias. * @see setAlias() @@ -261,6 +288,8 @@ class CORE_EXPORT QgsField }; // class QgsField +Q_DECLARE_OPERATORS_FOR_FLAGS( QgsField::Constraints ) + Q_DECLARE_METATYPE( QgsField ) //! Writes the field to stream out. QGIS version compatibility is not guaranteed. diff --git a/src/core/qgsfield_p.h b/src/core/qgsfield_p.h index 7c133a8c9f1a..858c99568878 100644 --- a/src/core/qgsfield_p.h +++ b/src/core/qgsfield_p.h @@ -55,6 +55,7 @@ class QgsFieldPrivate : public QSharedData , length( len ) , precision( prec ) , comment( comment ) + , constraints( 0 ) { } @@ -69,6 +70,7 @@ class QgsFieldPrivate : public QSharedData , comment( other.comment ) , alias( other.alias ) , defaultValueExpression( other.defaultValueExpression ) + , constraints( other.constraints ) { } @@ -78,7 +80,8 @@ class QgsFieldPrivate : public QSharedData { return (( name == other.name ) && ( type == other.type ) && ( subType == other.subType ) && ( length == other.length ) && ( precision == other.precision ) - && ( alias == other.alias ) && ( defaultValueExpression == other.defaultValueExpression ) ); + && ( alias == other.alias ) && ( defaultValueExpression == other.defaultValueExpression ) + && ( constraints == other.constraints ) ); } //! Name @@ -108,6 +111,9 @@ class QgsFieldPrivate : public QSharedData //! Default value expression QString defaultValueExpression; + //! Constraints + QgsField::Constraints constraints; + QgsEditorWidgetSetup editorWidgetSetup; }; diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 83baf2aee32c..4242d680c4dc 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -98,7 +98,7 @@ QVariant QgsVectorDataProvider::defaultValue( int fieldId ) const return QVariant(); } -QgsVectorDataProvider::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const +QgsField::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const { Q_UNUSED( fieldIndex ); return 0; diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index f6bf37ab990a..57d94ee1d35f 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -106,17 +106,6 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider ChangeAttributeValues | ChangeGeometries | AddAttributes | DeleteAttributes | RenameAttributes; - /** - * Constraints which may be present on a field. - * @note added in QGIS 3.0 - */ - enum Constraint - { - ConstraintNotNull = 1, //!< Field may not be null - ConstraintUnique = 1 << 1, //!< Field must have a unique value - }; - Q_DECLARE_FLAGS( Constraints, Constraint ) - /** * Constructor of the vector provider * @param uri uniform resource locator (URI) for a dataset @@ -297,7 +286,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider * field index. * @note added in QGIS 3.0 */ - virtual Constraints fieldConstraints( int fieldIndex ) const; + virtual QgsField::Constraints fieldConstraints( int fieldIndex ) const; /** * Changes geometries of existing features @@ -538,7 +527,5 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider }; Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorDataProvider::Capabilities ) -Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorDataProvider::Constraints ) - #endif diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index a020a4409d32..9022f86a8137 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -4189,3 +4189,19 @@ bool QgsVectorLayer::setDependencies( const QSet& oDeps ) return true; } + +QgsField::Constraints QgsVectorLayer::fieldConstraints( int fieldIndex ) const +{ + if ( fieldIndex < 0 || fieldIndex >= mFields.count() ) + return 0; + + QgsField::Constraints constraints = mFields.at( fieldIndex ).constraints(); + + // make sure provider constraints are always present! + if ( mFields.fieldOrigin( fieldIndex ) == QgsFields::OriginProvider ) + { + constraints |= mDataProvider->fieldConstraints( mFields.fieldOriginIndex( fieldIndex ) ); + } + + return constraints; +} diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index ec1b3eeb32c7..a24413ef9111 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1396,6 +1396,14 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ QString defaultValueExpression( int index ) const; + /** + * Returns any constraints which are present for a specified + * field index. These constraints may be inherited from the layer's data provider + * or may be set manually on the vector layer from within QGIS. + * @note added in QGIS 3.0 + */ + QgsField::Constraints fieldConstraints( int fieldIndex ) const; + /** Calculates a list of unique values contained within an attribute in the layer. Note that * in some circumstances when unsaved changes are present for the layer then the returned list * may contain outdated values (for instance when the attribute value in a saved feature has diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index de298cfda3a0..0a74c9c9bf62 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -998,14 +998,16 @@ bool QgsPostgresProvider::loadFields() mAttrPalIndexName.insert( i, fieldName ); mDefaultValues.insert( mAttributeFields.size(), defValMap[tableoid][attnum] ); - Constraints constraints = 0; + QgsField newField = QgsField( fieldName, fieldType, fieldTypeName, fieldSize, fieldPrec, fieldComment, fieldSubType ); + + QgsField::Constraints constraints = 0; if ( notNullMap[tableoid][attnum] ) - constraints |= ConstraintNotNull; + constraints |= QgsField::ConstraintNotNull; if ( uniqueMap[tableoid][attnum] ) - constraints |= ConstraintUnique; - mFieldConstraints.insert( mAttributeFields.size(), constraints ); + constraints |= QgsField::ConstraintUnique; + newField.setConstraints( constraints ); - mAttributeFields.append( QgsField( fieldName, fieldType, fieldTypeName, fieldSize, fieldPrec, fieldComment, fieldSubType ) ); + mAttributeFields.append( newField ); } setEditorWidgets(); @@ -1736,9 +1738,12 @@ QVariant QgsPostgresProvider::defaultValue( int fieldId ) const return defVal; } -QgsVectorDataProvider::Constraints QgsPostgresProvider::fieldConstraints( int fieldIndex ) const +QgsField::Constraints QgsPostgresProvider::fieldConstraints( int fieldIndex ) const { - return mFieldConstraints.value( fieldIndex, 0 ); + if ( fieldIndex < 0 || fieldIndex >= mAttributeFields.count() ) + return 0; + + return mAttributeFields.at( fieldIndex ).constraints(); } QString QgsPostgresProvider::paramValue( const QString& fieldValue, const QString &defaultValue ) const diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index 6d6b35b78b39..6033152caf35 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -161,7 +161,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider QgsAttributeList attributeIndexes() const override; QgsAttributeList pkAttributeIndexes() const override { return mPrimaryKeyAttrs; } QVariant defaultValue( int fieldId ) const override; - Constraints fieldConstraints( int fieldIndex ) const override; + QgsField::Constraints fieldConstraints( int fieldIndex ) const override; /** Adds a list of features @return true in case of success and false in case of failure*/ @@ -494,7 +494,6 @@ class QgsPostgresProvider : public QgsVectorDataProvider void setTransaction( QgsTransaction* transaction ) override; QHash mDefaultValues; - QHash mFieldConstraints; }; diff --git a/tests/src/core/testqgsfield.cpp b/tests/src/core/testqgsfield.cpp index dc05ae74fea1..ab61324465c6 100644 --- a/tests/src/core/testqgsfield.cpp +++ b/tests/src/core/testqgsfield.cpp @@ -84,6 +84,7 @@ void TestQgsField::create() void TestQgsField::copy() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); + original.setConstraints( QgsField::ConstraintNotNull ); QgsField copy( original ); QVERIFY( copy == original ); @@ -95,6 +96,7 @@ void TestQgsField::copy() void TestQgsField::assignment() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); + original.setConstraints( QgsField::ConstraintNotNull ); QgsField copy; copy = original; QVERIFY( copy == original ); @@ -123,6 +125,8 @@ void TestQgsField::gettersSetters() QCOMPARE( field.alias(), QString( "alias" ) ); field.setDefaultValueExpression( QStringLiteral( "1+2" ) ); QCOMPARE( field.defaultValueExpression(), QString( "1+2" ) ); + field.setConstraints( QgsField::ConstraintNotNull ); + QCOMPARE( field.constraints(), QgsField::ConstraintNotNull ); } void TestQgsField::isNumeric() @@ -157,6 +161,7 @@ void TestQgsField::equality() field1.setPrecision( 2 ); field1.setTypeName( QStringLiteral( "typename1" ) ); //typename is NOT required for equality field1.setComment( QStringLiteral( "comment1" ) ); //comment is NOT required for equality + field1.setConstraints( QgsField::ConstraintNotNull ); QgsField field2; field2.setName( QStringLiteral( "name" ) ); field2.setType( QVariant::Int ); @@ -164,6 +169,7 @@ void TestQgsField::equality() field2.setPrecision( 2 ); field2.setTypeName( QStringLiteral( "typename2" ) ); //typename is NOT required for equality field2.setComment( QStringLiteral( "comment2" ) ); //comment is NOT required for equality + field2.setConstraints( QgsField::ConstraintNotNull ); QVERIFY( field1 == field2 ); QVERIFY( !( field1 != field2 ) ); @@ -192,11 +198,16 @@ void TestQgsField::equality() QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); field2.setDefaultValueExpression( QString() ); + field2.setConstraints( QgsField::ConstraintUnique ); + QVERIFY( !( field1 == field2 ) ); + QVERIFY( field1 != field2 ); + field2.setConstraints( QgsField::ConstraintNotNull ); } void TestQgsField::asVariant() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); + original.setConstraints( QgsField::ConstraintNotNull ); //convert to and from a QVariant QVariant var = QVariant::fromValue( original ); @@ -375,6 +386,7 @@ void TestQgsField::dataStream() original.setComment( QStringLiteral( "comment1" ) ); original.setAlias( QStringLiteral( "alias" ) ); original.setDefaultValueExpression( QStringLiteral( "default" ) ); + original.setConstraints( QgsField::ConstraintNotNull ); QByteArray ba; QDataStream ds( &ba, QIODevice::ReadWrite ); diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 32d0e529c4bb..b620dda1a88a 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -26,7 +26,7 @@ QgsFeatureRequest, QgsFeature, QgsTransactionGroup, - QgsVectorDataProvider, + QgsField, NULL ) from qgis.gui import QgsEditorWidgetRegistry @@ -444,13 +444,20 @@ def testNotNullConstraint(self): self.assertEqual(len(vl.fields()), 4) # test some bad field indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsVectorDataProvider.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsVectorDataProvider.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsVectorDataProvider.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsVectorDataProvider.ConstraintNotNull) - self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsVectorDataProvider.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsVectorDataProvider.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintNotNull) + + # test that constraints have been saved to fields correctly + fields = vl.fields() + self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintNotNull) + self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintNotNull) + self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintNotNull) def testUniqueConstraint(self): vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") @@ -458,13 +465,20 @@ def testUniqueConstraint(self): self.assertEqual(len(vl.fields()), 4) # test some bad field indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsVectorDataProvider.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsVectorDataProvider.Constraints()) - - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsVectorDataProvider.ConstraintUnique) - self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsVectorDataProvider.ConstraintUnique) - self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsVectorDataProvider.ConstraintUnique) - self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsVectorDataProvider.ConstraintUnique) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintUnique) + + # test that constraints have been saved to fields correctly + fields = vl.fields() + self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintUnique) + self.assertTrue(fields.at(1).constraints() & QgsField.ConstraintUnique) + self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) + self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): From bd9f672aa71a604a07b8df8211f5b9c768e5a889 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 14:44:29 +1000 Subject: [PATCH 570/897] Allow constraints to be added at a QgsVectorLayer level --- python/core/qgsvectorlayer.sip | 18 +++++++ src/core/qgsvectorlayer.cpp | 58 ++++++++++++++++++++++ src/core/qgsvectorlayer.h | 13 +++++ tests/src/python/test_provider_postgres.py | 21 ++++++++ tests/src/python/test_qgsvectorlayer.py | 57 +++++++++++++++++++++ 5 files changed, 167 insertions(+) diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index 125f295e8498..bb906db13903 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1257,6 +1257,24 @@ class QgsVectorLayer : QgsMapLayer */ QString defaultValueExpression( int index ) const; + /** + * Returns any constraints which are present for a specified + * field index. These constraints may be inherited from the layer's data provider + * or may be set manually on the vector layer from within QGIS. + * @note added in QGIS 3.0 + * @see setFieldConstraints() + */ + QgsField::Constraints fieldConstraints( int fieldIndex ) const; + + /** + * Sets the constraints for a specified field index. Any constraints inherited from the layer's + * data provider will be kept intact and cannot be cleared. Ie, calling this method only allows for new + * constraints to be added on top of the existing provider constraints. + * @note added in QGIS 3.0 + * @see fieldConstraints() + */ + void setFieldConstraints( int index, QgsField::Constraints constraints ); + /** Calculates a list of unique values contained within an attribute in the layer. Note that * in some circumstances when unsaved changes are present for the layer then the returned list * may contain outdated values (for instance when the attribute value in a saved feature has diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 9022f86a8137..6cb1d82a8baf 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -1440,6 +1440,26 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) mDefaultExpressionMap.insert( field, expression ); } } + + // constraints + mFieldConstraints.clear(); + QDomNode constraintsNode = layer_node.namedItem( "constraints" ); + if ( !constraintsNode.isNull() ) + { + QDomNodeList constraintNodeList = constraintsNode.toElement().elementsByTagName( "constraint" ); + for ( int i = 0; i < constraintNodeList.size(); ++i ) + { + QDomElement constraintElem = constraintNodeList.at( i ).toElement(); + + QString field = constraintElem.attribute( "field", QString() ); + int constraints = constraintElem.attribute( "constraints", QString( "0" ) ).toInt(); + if ( field.isEmpty() || constraints == 0 ) + continue; + + mFieldConstraints.insert( field, static_cast< QgsField::Constraints >( constraints ) ); + } + } + updateFields(); QDomNode depsNode = layer_node.namedItem( QStringLiteral( "dataDependencies" ) ); @@ -1646,6 +1666,17 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, } layer_node.appendChild( defaultsElem ); + // constraints + QDomElement constraintsElem = document.createElement( "constraints" ); + Q_FOREACH ( const QgsField& field, mFields ) + { + QDomElement constraintElem = document.createElement( "constraint" ); + constraintElem.setAttribute( "field", field.name() ); + constraintElem.setAttribute( "constraints", field.constraints() ); + constraintsElem.appendChild( constraintElem ); + } + layer_node.appendChild( constraintsElem ); + // change dependencies QDomElement dataDependenciesElement = document.createElement( QStringLiteral( "dataDependencies" ) ); Q_FOREACH ( const QgsMapLayerDependency& dep, dependencies() ) @@ -2901,6 +2932,17 @@ void QgsVectorLayer::updateFields() mFields[ index ].setDefaultValueExpression( defaultIt.value() ); } + QMap< QString, QgsField::Constraints >::const_iterator constraintIt = mFieldConstraints.constBegin(); + for ( ; constraintIt != mFieldConstraints.constEnd(); ++constraintIt ) + { + int index = mFields.lookupField( constraintIt.key() ); + if ( index < 0 ) + continue; + + // always keep provider constraints intact + mFields[ index ].setConstraints( mFields.at( index ).constraints() | constraintIt.value() ); + } + if ( oldFields != mFields ) { emit updatedFields(); @@ -4205,3 +4247,19 @@ QgsField::Constraints QgsVectorLayer::fieldConstraints( int fieldIndex ) const return constraints; } + +void QgsVectorLayer::setFieldConstraints( int index, QgsField::Constraints constraints ) +{ + if ( index < 0 || index >= mFields.count() ) + return; + + if ( constraints == 0 ) + { + mFieldConstraints.remove( mFields.at( index ).name() ); + } + else + { + mFieldConstraints.insert( mFields.at( index ).name(), constraints ); + } + updateFields(); +} diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index a24413ef9111..91a26ef17dc9 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1401,9 +1401,19 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * field index. These constraints may be inherited from the layer's data provider * or may be set manually on the vector layer from within QGIS. * @note added in QGIS 3.0 + * @see setFieldConstraints() */ QgsField::Constraints fieldConstraints( int fieldIndex ) const; + /** + * Sets the constraints for a specified field index. Any constraints inherited from the layer's + * data provider will be kept intact and cannot be cleared. Ie, calling this method only allows for new + * constraints to be added on top of the existing provider constraints. + * @note added in QGIS 3.0 + * @see fieldConstraints() + */ + void setFieldConstraints( int index, QgsField::Constraints constraints ); + /** Calculates a list of unique values contained within an attribute in the layer. Note that * in some circumstances when unsaved changes are present for the layer then the returned list * may contain outdated values (for instance when the attribute value in a saved feature has @@ -1941,6 +1951,9 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte //! Map which stores default value expressions for fields QgsStringMap mDefaultExpressionMap; + //! Map which stores constraints for fields + QMap< QString, QgsField::Constraints > mFieldConstraints; + //! Holds the configuration for the edit form QgsEditFormConfig mEditFormConfig; diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index b620dda1a88a..b92a4f18b18e 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -480,6 +480,27 @@ def testUniqueConstraint(self): self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) + def testConstraintOverwrite(self): + """ test that Postgres provider constraints can't be overwritten by vector layer method """ + vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") + self.assertTrue(vl.isValid()) + + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) + self.assertTrue(vl.fields().at(0).constraints() & QgsField.ConstraintNotNull) + + # add a constraint at the layer level + vl.setFieldConstraints(0, QgsField.ConstraintUnique) + + # should be no change at provider level + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) + + # but layer should still keep provider constraints... + self.assertTrue(vl.fields().at(0).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(vl.fieldConstraints(0) & QgsField.ConstraintNotNull) + # ...in addition to layer level constraint + self.assertTrue(vl.fields().at(0).constraints() & QgsField.ConstraintUnique) + self.assertTrue(vl.fieldConstraints(0) & QgsField.ConstraintUnique) + # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): uri = 'point?field=f1:int' diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 627ebae86475..e294edc1370d 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1773,6 +1773,63 @@ def testEvaluatingDefaultExpressions(self): layer.setDefaultValueExpression(1, 'not a valid expression') self.assertFalse(layer.defaultValue(1)) + def testGetSetConstraints(self): + """ test getting and setting field constraints """ + layer = createLayerWithOnePoint() + + self.assertFalse(layer.fieldConstraints(0)) + self.assertFalse(layer.fieldConstraints(1)) + self.assertFalse(layer.fieldConstraints(2)) + + layer.setFieldConstraints(0, QgsField.ConstraintNotNull) + self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) + self.assertFalse(layer.fieldConstraints(1)) + self.assertFalse(layer.fieldConstraints(2)) + self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) + + layer.setFieldConstraints(1, QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) + self.assertEqual(layer.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + self.assertFalse(layer.fieldConstraints(2)) + self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertEqual(layer.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + + layer.setFieldConstraints(1, QgsField.Constraints()) + self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) + self.assertFalse(layer.fieldConstraints(1)) + self.assertFalse(layer.fieldConstraints(2)) + self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertFalse(layer.fields().at(1).constraints()) + + def testSaveRestoreConstraints(self): + """ test saving and restoring constraints from xml""" + layer = createLayerWithOnePoint() + + # no constraints + doc = QDomDocument("testdoc") + elem = doc.createElement("maplayer") + self.assertTrue(layer.writeXml(elem, doc)) + + layer2 = createLayerWithOnePoint() + self.assertTrue(layer2.readXml(elem)) + self.assertFalse(layer2.fieldConstraints(0)) + self.assertFalse(layer2.fieldConstraints(1)) + + # set some constraints + layer.setFieldConstraints(0, QgsField.ConstraintNotNull) + layer.setFieldConstraints(1, QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + + doc = QDomDocument("testdoc") + elem = doc.createElement("maplayer") + self.assertTrue(layer.writeXml(elem, doc)) + + layer3 = createLayerWithOnePoint() + self.assertTrue(layer3.readXml(elem)) + self.assertEqual(layer3.fieldConstraints(0), QgsField.ConstraintNotNull) + self.assertEqual(layer3.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + self.assertEqual(layer3.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertEqual(layer3.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + def testGetFeatureLimitWithEdits(self): """ test getting features with a limit, when edits are present """ layer = createLayerWithOnePoint() From 6bbd0061f3e7cb4f739c3ec94a0711381b39119d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 15:36:19 +1000 Subject: [PATCH 571/897] Move handling of not null constraint from edit form to layer --- doc/api_break.dox | 2 +- python/core/qgseditformconfig.sip | 9 ------- src/app/qgsfieldsproperties.cpp | 26 ++++++++++++++----- src/app/qgsfieldsproperties.h | 2 +- src/core/qgseditformconfig.cpp | 17 ------------ src/core/qgseditformconfig.h | 9 ------- src/core/qgseditformconfig_p.h | 2 -- .../core/qgseditorwidgetregistry.cpp | 6 ++++- .../core/qgseditorwidgetwrapper.cpp | 4 +-- src/gui/qgsattributeform.cpp | 2 +- 10 files changed, 30 insertions(+), 49 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 3b709f16f23a..c153211f7435 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -740,7 +740,7 @@ QgsEditorWidgetRegistry::instance()->findBest() must be used instead. - setExpression() has been renamed to setConstraintExpression() - expressionDescription() has been renamed to constraintDescription() - setExpressionDesctiption() has been renamed to setConstraintDescription() - +- notNull() and setNotNull() have been removed. Use QgsVectorLayer.setFieldConstraints()/fieldConstraints(), or QgsField.constraints() instead. QgsExpression {#qgis_api_break_3_0_QgsExpression} ------------- diff --git a/python/core/qgseditformconfig.sip b/python/core/qgseditformconfig.sip index f447ba0baf2e..d59ba96d95bb 100644 --- a/python/core/qgseditformconfig.sip +++ b/python/core/qgseditformconfig.sip @@ -243,15 +243,6 @@ class QgsEditFormConfig */ void setContraintDescription( int idx, const QString& description ); - /** - * Returns if the field at fieldidx should be treated as NOT NULL value - */ - bool notNull( int fieldidx ) const; - /** - * Set if the field at fieldidx should be treated as NOT NULL value - */ - void setNotNull( int idx, bool notnull = true ); - /** * If this returns true, the widget at the given index will receive its label on the previous line * while if it returns false, the widget will receive its label on the left hand side. diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index 8d37db34e109..a585856854f7 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -558,12 +558,15 @@ void QgsFieldsProperties::attributeTypeDialog() attributeTypeDialog.setFieldEditable( cfg.mEditable ); attributeTypeDialog.setLabelOnTop( cfg.mLabelOnTop ); - attributeTypeDialog.setNotNull( cfg.mNotNull ); + attributeTypeDialog.setNotNull( cfg.mConstraints & QgsField::ConstraintNotNull ); + attributeTypeDialog.setUnique( cfg.mConstraints & QgsField::ConstraintUnique ); + QgsField::Constraints providerConstraints = 0; if ( mLayer->fields().fieldOrigin( index ) == QgsFields::OriginProvider ) { - attributeTypeDialog.setProviderConstraints( mLayer->dataProvider()->fieldConstraints( mLayer->fields().fieldOriginIndex( index ) ) ); + providerConstraints = mLayer->dataProvider()->fieldConstraints( mLayer->fields().fieldOriginIndex( index ) ); } + attributeTypeDialog.setProviderConstraints( providerConstraints ); attributeTypeDialog.setConstraintExpression( cfg.mConstraint ); attributeTypeDialog.setConstraintExpressionDescription( cfg.mConstraintDescription ); @@ -577,7 +580,17 @@ void QgsFieldsProperties::attributeTypeDialog() cfg.mEditable = attributeTypeDialog.fieldEditable(); cfg.mLabelOnTop = attributeTypeDialog.labelOnTop(); - cfg.mNotNull = attributeTypeDialog.notNull(); + + cfg.mConstraints = 0; + if ( attributeTypeDialog.notNull() && !( providerConstraints & QgsField::ConstraintNotNull ) ) + { + cfg.mConstraints |= QgsField::ConstraintNotNull; + } + if ( attributeTypeDialog.unique() && !( providerConstraints & QgsField::ConstraintUnique ) ) + { + cfg.mConstraints |= QgsField::ConstraintUnique; + } + cfg.mConstraintDescription = attributeTypeDialog.constraintExpressionDescription(); cfg.mConstraint = attributeTypeDialog.constraintExpression(); mLayer->setDefaultValueExpression( index, attributeTypeDialog.defaultValueExpression() ); @@ -962,13 +975,14 @@ void QgsFieldsProperties::apply() editFormConfig.setReadOnly( i, !cfg.mEditable ); editFormConfig.setLabelOnTop( i, cfg.mLabelOnTop ); - editFormConfig.setNotNull( i, cfg.mNotNull ); editFormConfig.setContraintDescription( i, cfg.mConstraintDescription ); editFormConfig.setConstraintExpression( i, cfg.mConstraint ); editFormConfig.setWidgetType( name, cfg.mEditorWidgetType ); editFormConfig.setWidgetConfig( name, cfg.mEditorWidgetConfig ); + mLayer->setFieldConstraints( i, cfg.mConstraints ); + if ( mFieldsList->item( i, attrWMSCol )->checkState() == Qt::Unchecked ) { excludeAttributesWMS.insert( mFieldsList->item( i, attrNameCol )->text() ); @@ -1032,7 +1046,7 @@ QgsFieldsProperties::FieldConfig::FieldConfig() : mEditable( true ) , mEditableEnabled( true ) , mLabelOnTop( false ) - , mNotNull( false ) + , mConstraints( 0 ) , mConstraintDescription( QString() ) , mButton( nullptr ) { @@ -1045,7 +1059,7 @@ QgsFieldsProperties::FieldConfig::FieldConfig( QgsVectorLayer* layer, int idx ) mEditableEnabled = layer->fields().fieldOrigin( idx ) != QgsFields::OriginJoin && layer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression; mLabelOnTop = layer->editFormConfig().labelOnTop( idx ); - mNotNull = layer->editFormConfig().notNull( idx ); + mConstraints = layer->fieldConstraints( idx ); mConstraint = layer->editFormConfig().constraintExpression( idx ); mConstraintDescription = layer->editFormConfig().constraintDescription( idx ); const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( layer, layer->fields().field( idx ).name() ); diff --git a/src/app/qgsfieldsproperties.h b/src/app/qgsfieldsproperties.h index e0bfc4f0f8cc..c830939ae8de 100644 --- a/src/app/qgsfieldsproperties.h +++ b/src/app/qgsfieldsproperties.h @@ -122,7 +122,7 @@ class APP_EXPORT QgsFieldsProperties : public QWidget, private Ui_QgsFieldsPrope bool mEditable; bool mEditableEnabled; bool mLabelOnTop; - bool mNotNull; + QgsField::Constraints mConstraints; QString mConstraint; QString mConstraintDescription; QPushButton* mButton; diff --git a/src/core/qgseditformconfig.cpp b/src/core/qgseditformconfig.cpp index 2ea90c33ca79..512b18ea7c46 100644 --- a/src/core/qgseditformconfig.cpp +++ b/src/core/qgseditformconfig.cpp @@ -220,14 +220,6 @@ void QgsEditFormConfig::setContraintDescription( int idx, const QString &descr ) } } -bool QgsEditFormConfig::notNull( int idx ) const -{ - if ( idx >= 0 && idx < d->mFields.count() ) - return d->mNotNull.value( d->mFields.at( idx ).name(), false ); - else - return false; -} - void QgsEditFormConfig::setReadOnly( int idx, bool readOnly ) { if ( idx >= 0 && idx < d->mFields.count() ) @@ -301,15 +293,6 @@ void QgsEditFormConfig::setSuppress( QgsEditFormConfig::FeatureFormSuppress s ) d->mSuppressForm = s; } -void QgsEditFormConfig::setNotNull( int idx, bool notnull ) -{ - if ( idx >= 0 && idx < d->mFields.count() ) - { - d.detach(); - d->mNotNull[ d->mFields.at( idx ).name()] = notnull; - } -} - void QgsEditFormConfig::readXml( const QDomNode& node ) { d.detach(); diff --git a/src/core/qgseditformconfig.h b/src/core/qgseditformconfig.h index e04f0f7e3065..269a171a6830 100644 --- a/src/core/qgseditformconfig.h +++ b/src/core/qgseditformconfig.h @@ -278,15 +278,6 @@ class CORE_EXPORT QgsEditFormConfig */ void setContraintDescription( int idx, const QString& description ); - /** - * Returns if the field at fieldidx should be treated as NOT NULL value - */ - bool notNull( int fieldidx ) const; - /** - * Set if the field at fieldidx should be treated as NOT NULL value - */ - void setNotNull( int idx, bool notnull = true ); - /** * If this returns true, the widget at the given index will receive its label on the previous line * while if it returns false, the widget will receive its label on the left hand side. diff --git a/src/core/qgseditformconfig_p.h b/src/core/qgseditformconfig_p.h index 6637af0ae815..e02b3a81a60a 100644 --- a/src/core/qgseditformconfig_p.h +++ b/src/core/qgseditformconfig_p.h @@ -42,7 +42,6 @@ class QgsEditFormConfigPrivate : public QSharedData , mConstraintsDescription( o.mConstraintsDescription ) , mFieldEditables( o.mFieldEditables ) , mLabelOnTop( o.mLabelOnTop ) - , mNotNull( o.mNotNull ) , mEditorWidgetTypes( o.mEditorWidgetTypes ) , mWidgetConfigs( o.mWidgetConfigs ) , mEditorLayout( o.mEditorLayout ) @@ -69,7 +68,6 @@ class QgsEditFormConfigPrivate : public QSharedData QMap< QString, QString> mConstraintsDescription; QMap< QString, bool> mFieldEditables; QMap< QString, bool> mLabelOnTop; - QMap< QString, bool> mNotNull; QMap mEditorWidgetTypes; QMap mWidgetConfigs; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index 13bf85529a82..30bc5cd865fd 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -264,6 +264,11 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle formConfig.setReadOnly( idx, ewv2CfgElem.attribute( QStringLiteral( "fieldEditable" ), QStringLiteral( "1" ) ) != QLatin1String( "1" ) ); formConfig.setLabelOnTop( idx, ewv2CfgElem.attribute( QStringLiteral( "labelOnTop" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); formConfig.setNotNull( idx, ewv2CfgElem.attribute( QStringLiteral( "notNull" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); + if ( ewv2CfgElem.attribute( QStringLiteral("notNull"), QStringLiteral("0") ) == QLatin1String( "1" ) ) + { + // upgrade from older config + vectorLayer->setFieldConstraints( idx, vectorLayer->fieldConstraints( idx ) | QgsField::ConstraintNotNull ); + } formConfig.setConstraintExpression( idx, ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ) ); formConfig.setContraintDescription( idx, ewv2CfgElem.attribute( QStringLiteral( "constraintDescription" ), QString() ) ); @@ -319,7 +324,6 @@ void QgsEditorWidgetRegistry::writeMapLayer( QgsMapLayer* mapLayer, QDomElement& QDomElement ewv2CfgElem = doc.createElement( QStringLiteral( "widgetv2config" ) ); ewv2CfgElem.setAttribute( QStringLiteral( "fieldEditable" ), !vectorLayer->editFormConfig().readOnly( idx ) ); ewv2CfgElem.setAttribute( QStringLiteral( "labelOnTop" ), vectorLayer->editFormConfig().labelOnTop( idx ) ); - ewv2CfgElem.setAttribute( QStringLiteral( "notNull" ), vectorLayer->editFormConfig().notNull( idx ) ); ewv2CfgElem.setAttribute( QStringLiteral( "constraint" ), vectorLayer->editFormConfig().constraintExpression( idx ) ); ewv2CfgElem.setAttribute( QStringLiteral( "constraintDescription" ), vectorLayer->editFormConfig().constraintDescription( idx ) ); diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 5f725bb74fc5..b55621c0823c 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -136,7 +136,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) else mValidConstraint = true; - if ( layer()->editFormConfig().notNull( mFieldIdx ) ) + if ( layer()->fieldConstraints( mFieldIdx ) & QgsField::ConstraintNotNull ) { if ( !expression.isEmpty() ) { @@ -175,4 +175,4 @@ bool QgsEditorWidgetWrapper::isInTable( const QWidget* parent ) if ( !parent ) return false; if ( qobject_cast( parent ) ) return true; return isInTable( parent->parentWidget() ); -} \ No newline at end of file +} diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 6fa90407ead9..f4069e64e6cd 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -674,7 +674,7 @@ void QgsAttributeForm::onAttributeChanged( const QVariant& value ) break; } - if ( eww->layer()->editFormConfig().notNull( eww->fieldIdx() ) ) + if ( eww->layer()->fieldConstraints( eww->fieldIdx() ) & QgsField::ConstraintNotNull ) { QLabel* buddy = mBuddyMap.value( eww->widget() ); From 21f885aa7a4c43198fa35d4855afa47a2f873a52 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 19 Oct 2016 15:57:00 +1000 Subject: [PATCH 572/897] Select all text after reset line edit to null --- src/gui/qgsfilterlineedit.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/qgsfilterlineedit.cpp b/src/gui/qgsfilterlineedit.cpp index ebe58ad40385..c1b0a6de1adf 100644 --- a/src/gui/qgsfilterlineedit.cpp +++ b/src/gui/qgsfilterlineedit.cpp @@ -104,6 +104,7 @@ void QgsFilterLineEdit::clearValue() { case ClearToNull: setText( mNullValue ); + selectAll(); break; case ClearToDefault: From 3e40f803c30fd1fe8e7785462db402587bb63563 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 14:15:16 +1000 Subject: [PATCH 573/897] Implement constraint detection for spatialite provider --- .../core/qgseditorwidgetregistry.cpp | 3 +- .../spatialite/qgsspatialiteprovider.cpp | 70 +++++++++++++++++++ .../spatialite/qgsspatialiteprovider.h | 3 + tests/src/python/test_provider_spatialite.py | 54 +++++++++++++- 4 files changed, 127 insertions(+), 3 deletions(-) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index 30bc5cd865fd..8f913c63e75f 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -263,8 +263,7 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle formConfig.setReadOnly( idx, ewv2CfgElem.attribute( QStringLiteral( "fieldEditable" ), QStringLiteral( "1" ) ) != QLatin1String( "1" ) ); formConfig.setLabelOnTop( idx, ewv2CfgElem.attribute( QStringLiteral( "labelOnTop" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); - formConfig.setNotNull( idx, ewv2CfgElem.attribute( QStringLiteral( "notNull" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); - if ( ewv2CfgElem.attribute( QStringLiteral("notNull"), QStringLiteral("0") ) == QLatin1String( "1" ) ) + if ( ewv2CfgElem.attribute( QStringLiteral( "notNull" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ) { // upgrade from older config vectorLayer->setFieldConstraints( idx, vectorLayer->fieldConstraints( idx ) | QgsField::ConstraintNotNull ); diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index b8be23e70c1e..42746a84cf5a 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -36,6 +36,7 @@ email : a.furieri@lqt.it #include #include #include +#include const QString SPATIALITE_KEY = QStringLiteral( "spatialite" ); @@ -811,6 +812,65 @@ QString QgsSpatiaLiteProvider::spatialiteVersion() return mSpatialiteVersionInfo; } +void QgsSpatiaLiteProvider::fetchConstraints() +{ + char **results; + char *errMsg = nullptr; + + // this is not particularly robust but unfortunately sqlite offers no way to check directly + // for the presence of constraints on a field (only indexes, but not all constraints are indexes) + QString sql = QStringLiteral( "SELECT sql FROM sqlite_master WHERE type='table' AND name=%1" ).arg( quotedIdentifier( mTableName ) ); + int columns = 0; + int rows = 0; + + int ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg ); + if ( ret != SQLITE_OK ) + goto error; + if ( rows < 1 ) + ; + else + { + QString sqlDef = QString::fromUtf8( results[ 1 ] ); + // extract definition + QRegularExpression re( QStringLiteral( "\\((.*)\\)" ) ); + QRegularExpressionMatch match = re.match( sqlDef ); + if ( match.hasMatch() ) + { + QString matched = match.captured( 1 ); + Q_FOREACH ( QString field, matched.split( ',' ) ) + { + field = field.trimmed(); + QString fieldName = field.left( field.indexOf( ' ' ) ); + QString definition = field.mid( field.indexOf( ' ' ) + 1 ); + QgsField::Constraints constraints = 0; + if ( definition.contains( "unique", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) + constraints |= QgsField::ConstraintUnique; + if ( definition.contains( "not null", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) + constraints |= QgsField::ConstraintNotNull; + + int fieldIdx = mAttributeFields.lookupField( fieldName ); + if ( fieldIdx >= 0 ) + { + mAttributeFields[ fieldIdx ].setConstraints( constraints ); + } + } + } + + } + sqlite3_free_table( results ); + + return; + +error: + QgsMessageLog::logMessage( tr( "SQLite error: %2\nSQL: %1" ).arg( sql, errMsg ? errMsg : tr( "unknown cause" ) ), tr( "SpatiaLite" ) ); + // unexpected error + if ( errMsg ) + { + sqlite3_free( errMsg ); + } + +} + void QgsSpatiaLiteProvider::loadFields() { int ret; @@ -866,6 +926,8 @@ void QgsSpatiaLiteProvider::loadFields() } sqlite3_free_table( results ); + // check for constraints + fetchConstraints(); // for views try to get the primary key from the meta table if ( mViewBased && mPrimaryKey.isEmpty() ) @@ -3604,6 +3666,14 @@ void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueV return; } +QgsField::Constraints QgsSpatiaLiteProvider::fieldConstraints( int fieldIndex ) const +{ + if ( fieldIndex < 0 || fieldIndex >= mAttributeFields.count() ) + return 0; + + return mAttributeFields.at( fieldIndex ).constraints(); +} + QString QgsSpatiaLiteProvider::geomParam() const { QString geometry; diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 228cb0866f8c..f81ada41abc8 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -130,6 +130,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider QVariant minimumValue( int index ) const override; QVariant maximumValue( int index ) const override; virtual void uniqueValues( int index, QList < QVariant > &uniqueValues, int limit = -1 ) const override; + QgsField::Constraints fieldConstraints( int fieldIndex ) const override; bool isValid() const override; virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } @@ -446,6 +447,8 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider int type, int nDims, int little_endian, int endian_arch ); + void fetchConstraints(); + enum GEOS_3D { GEOS_3D_POINT = -2147483647, diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index 6cf54085f350..3f6ab3d487e5 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -19,7 +19,7 @@ import shutil import tempfile -from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry +from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry, QgsField from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -135,6 +135,10 @@ def setUpClass(cls): sql = "SELECT AddGeometryColumn('test_relation_b', 'Geometry', 4326, 'POLYGON', 'XY')" cur.execute(sql) + # tables with constraints + sql = "CREATE TABLE test_constraints(id INTEGER PRIMARY KEY, num INTEGER NOT NULL, desc TEXT UNIQUE, desc2 TEXT, num2 INTEGER NOT NULL UNIQUE)" + cur.execute(sql) + cur.execute("COMMIT") con.close() @@ -382,6 +386,54 @@ def test_discover_relation(self): QgsMapLayerRegistry.instance().removeMapLayer(track.id()) QgsMapLayerRegistry.instance().removeMapLayer(artist.id()) + def testNotNullConstraint(self): + vl = QgsVectorLayer("dbname=%s table=test_constraints key='id'" % self.dbname, "test_constraints", + "spatialite") + self.assertTrue(vl.isValid()) + self.assertEqual(len(vl.fields()), 5) + + # test some bad field indexes + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(4) & QgsField.ConstraintNotNull) + + # test that constraints have been saved to fields correctly + fields = vl.fields() + self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(fields.at(1).constraints() & QgsField.ConstraintNotNull) + self.assertFalse(fields.at(2).constraints() & QgsField.ConstraintNotNull) + self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(fields.at(4).constraints() & QgsField.ConstraintNotNull) + + def testUniqueConstraint(self): + vl = QgsVectorLayer("dbname=%s table=test_constraints key='id'" % self.dbname, "test_constraints", + "spatialite") + self.assertTrue(vl.isValid()) + self.assertEqual(len(vl.fields()), 5) + + # test some bad field indexes + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(4) & QgsField.ConstraintUnique) + + # test that constraints have been saved to fields correctly + fields = vl.fields() + self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintUnique) + self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintUnique) + self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) + self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) + self.assertTrue(fields.at(4).constraints() & QgsField.ConstraintUnique) + # This test would fail. It would require turning on WAL def XXXXXtestLocking(self): From b7d0fd6f90b14dea8f6b1463436dc4f6c7a04380 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 25 Oct 2016 16:05:34 +1000 Subject: [PATCH 574/897] New class QgsVectorLayerUtils Contains static helper methods for working with vector layers. Initially only contains a method to test whether a value exists within a layer's attributes. --- python/core/core.sip | 1 + python/core/qgsvectorlayerutils.sip | 22 +++++ src/core/CMakeLists.txt | 2 + src/core/qgsvectorlayer.h | 1 + src/core/qgsvectorlayerutils.cpp | 51 ++++++++++++ src/core/qgsvectorlayerutils.h | 41 +++++++++ tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgsvectorlayerutils.py | 88 ++++++++++++++++++++ 8 files changed, 207 insertions(+) create mode 100644 python/core/qgsvectorlayerutils.sip create mode 100644 src/core/qgsvectorlayerutils.cpp create mode 100644 src/core/qgsvectorlayerutils.h create mode 100644 tests/src/python/test_qgsvectorlayerutils.py diff --git a/python/core/core.sip b/python/core/core.sip index 6418704f8d07..8693f7990808 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -148,6 +148,7 @@ %Include qgsvectorlayerimport.sip %Include qgsvectorlayerjoinbuffer.sip %Include qgsvectorlayerundocommand.sip +%Include qgsvectorlayerutils.sip %Include qgsvectorsimplifymethod.sip %Include qgscachedfeatureiterator.sip diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip new file mode 100644 index 000000000000..258fbd093ecc --- /dev/null +++ b/python/core/qgsvectorlayerutils.sip @@ -0,0 +1,22 @@ + +/** \ingroup core + * \class QgsVectorLayerUtils + * \brief Contains utility methods for working with QgsVectorLayers. + * + * \note Added in version 3.0 + */ +class QgsVectorLayerUtils +{ +%TypeHeaderCode +#include +%End + public: + + /** + * Returns true if the specified value already exists within a field. This method can be used to test for uniqueness + * of values inside a layer's attributes. An optional list of ignored feature IDs can be provided, if so, any features + * with IDs within this list are ignored when testing for existance of the value. + */ + static bool valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds = QgsFeatureIds() ); + +}; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 9a0a4952c88b..4a715e4c6cc3 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -230,6 +230,7 @@ SET(QGIS_CORE_SRCS qgsvectorlayerlabelprovider.cpp qgsvectorlayerrenderer.cpp qgsvectorlayerundocommand.cpp + qgsvectorlayerutils.cpp qgsvectorsimplifymethod.cpp qgsvirtuallayerdefinition.cpp qgsvirtuallayerdefinitionutils.cpp @@ -722,6 +723,7 @@ SET(QGIS_CORE_HDRS qgsvectorlayerlabelprovider.h qgsvectorlayerrenderer.h qgsvectorlayerundocommand.h + qgsvectorlayerutils.h qgsvectorsimplifymethod.h qgsmapthemecollection.h qgsxmlutils.h diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 91a26ef17dc9..477bcecb82ae 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -403,6 +403,7 @@ struct CORE_EXPORT QgsVectorJoinInfo * Provider to display vector data in a GRASS GIS layer. * * TODO QGIS3: Remove virtual from non-inherited methods (like isModified) + * @see QgsVectorLayerUtils() */ diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp new file mode 100644 index 000000000000..76b1abdabb2c --- /dev/null +++ b/src/core/qgsvectorlayerutils.cpp @@ -0,0 +1,51 @@ +/*************************************************************************** + qgsvectorlayerutils.cpp + ----------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgsvectorlayerutils.h" + +bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds ) +{ + if ( !layer ) + return false; + + if ( fieldIndex < 0 || fieldIndex >= layer->fields().count() ) + return false; + + QString fieldName = layer->fields().at( fieldIndex ).name(); + + // build up an optimised feature request + QgsFeatureRequest request; + request.setSubsetOfAttributes( QgsAttributeList() ); + request.setFlags( QgsFeatureRequest::NoGeometry ); + + // at most we need to check ignoreIds.size() + 1 - the feature not in ignoreIds is the one we're interested in + int limit = ignoreIds.size() + 1; + request.setLimit( limit ); + + request.setFilterExpression( QStringLiteral( "%1=%2" ).arg( QgsExpression::quotedColumnRef( fieldName ), + QgsExpression::quotedValue( value ) ) ); + + QgsFeature feat; + QgsFeatureIterator it = layer->getFeatures( request ); + while ( it.nextFeature( feat ) ) + { + if ( ignoreIds.contains( feat.id() ) ) + continue; + + return true; + } + + return false; +} diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h new file mode 100644 index 000000000000..33e2868530d4 --- /dev/null +++ b/src/core/qgsvectorlayerutils.h @@ -0,0 +1,41 @@ +/*************************************************************************** + qgsvectorlayerutils.h + --------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSVECTORLAYERUTILS_H +#define QGSVECTORLAYERUTILS_H + +#include "qgsvectorlayer.h" + +/** \ingroup core + * \class QgsVectorLayerUtils + * \brief Contains utility methods for working with QgsVectorLayers. + * + * \note Added in version 3.0 + */ + +class CORE_EXPORT QgsVectorLayerUtils +{ + public: + + /** + * Returns true if the specified value already exists within a field. This method can be used to test for uniqueness + * of values inside a layer's attributes. An optional list of ignored feature IDs can be provided, if so, any features + * with IDs within this list are ignored when testing for existance of the value. + */ + static bool valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds = QgsFeatureIds() ); + +}; + +#endif // QGSVECTORLAYERUTILS_H diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index c40a7689b025..cea9a689a55c 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -111,6 +111,7 @@ ADD_PYTHON_TEST(PyQgsVectorColorRamp test_qgsvectorcolorramp.py) ADD_PYTHON_TEST(PyQgsVectorFileWriter test_qgsvectorfilewriter.py) ADD_PYTHON_TEST(PyQgsVectorLayer test_qgsvectorlayer.py) ADD_PYTHON_TEST(PyQgsVectorLayerEditBuffer test_qgsvectorlayereditbuffer.py) +ADD_PYTHON_TEST(PyQgsVectorLayerUtils test_qgsvectorlayerutils.py) ADD_PYTHON_TEST(PyQgsZonalStatistics test_qgszonalstatistics.py) ADD_PYTHON_TEST(PyQgsMapLayerRegistry test_qgsmaplayerregistry.py) ADD_PYTHON_TEST(PyQgsVirtualLayerProvider test_provider_virtual.py) diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py new file mode 100644 index 000000000000..1190ce7f5003 --- /dev/null +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsVectorLayerUtils. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '25/10/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +import os + +from qgis.PyQt.QtCore import QVariant + +from qgis.core import (QgsVectorLayer, + QgsVectorLayerUtils, + QgsField, + QgsFields, + QgsFeature + ) +from qgis.testing import start_app, unittest +from utilities import unitTestDataPath +start_app() + + +def createLayerWithOnePoint(): + layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", + "addfeat", "memory") + pr = layer.dataProvider() + f = QgsFeature() + f.setAttributes(["test", 123]) + assert pr.addFeatures([f]) + assert layer.pendingFeatureCount() == 1 + return layer + + +class TestQgsVectorLayerUtils(unittest.TestCase): + + def test_value_exists(self): + layer = createLayerWithOnePoint() + # add some more features + f1 = QgsFeature(2) + f1.setAttributes(["test1", 124]) + f2 = QgsFeature(3) + f2.setAttributes(["test2", 125]) + f3 = QgsFeature(4) + f3.setAttributes(["test3", 126]) + f4 = QgsFeature(5) + f4.setAttributes(["test4", 127]) + layer.dataProvider().addFeatures([f1, f2, f3, f4]) + + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 0, 'test')) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 0, 'test1')) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 0, 'test4')) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 0, 'not present!')) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 1, 123)) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 1, 124)) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 1, 127)) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 1, 99)) + + # no layer + self.assertFalse(QgsVectorLayerUtils.valueExists(None, 1, 123)) + # bad field indexes + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, -1, 'test')) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 100, 'test')) + + # with ignore list + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 0, 'test1', [3, 4, 5])) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 0, 'test1', [999999])) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 0, 'test1', [2])) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 0, 'test1', [99999, 2])) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 0, 'test1', [3, 4, 5, 2])) + + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 1, 125, [2, 4, 5])) + self.assertTrue(QgsVectorLayerUtils.valueExists(layer, 1, 125, [999999])) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 1, 125, [3])) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 1, 125, [99999, 3])) + self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 1, 125, [2, 4, 5, 3])) + + +if __name__ == '__main__': + unittest.main() From 1cecf37b40d632e55ff104b2da2fea75cc56b1da Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 06:27:07 +1000 Subject: [PATCH 575/897] Enforce unique constraints in attribute form --- .../core/qgseditorwidgetwrapper.sip | 11 ++- .../core/qgseditorwidgetwrapper.cpp | 79 ++++++++++++++++--- .../core/qgseditorwidgetwrapper.h | 14 +++- src/gui/qgsattributeform.cpp | 3 +- 4 files changed, 90 insertions(+), 17 deletions(-) diff --git a/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip b/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip index 5003d16d55d2..5bdcbddd7987 100644 --- a/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip +++ b/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip @@ -104,12 +104,21 @@ class QgsEditorWidgetWrapper : QgsWidgetWrapper /** * Get the current constraint status. - * @return true if the constraint is valid or if there's not constraint, + * @return true if the constraint is valid or if there's no constraint, * false otherwise * @note added in QGIS 2.16 + * @see constraintFailureReason() */ bool isValidConstraint() const; + /** + * Returns the reason why a constraint check has failed (or an empty string + * if constraint check was successful). + * @see isValidConstraint() + * @note added in QGIS 3.0 + */ + QString constraintFailureReason() const; + signals: /** * Emit this signal, whenever the value changed. diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index b55621c0823c..3241e98d706f 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -17,6 +17,7 @@ #include "qgsvectorlayer.h" #include "qgsvectordataprovider.h" #include "qgsfields.h" +#include "qgsvectorlayerutils.h" #include @@ -108,14 +109,19 @@ void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) { bool toEmit( false ); - QString errStr( tr( "predicate is True" ) ); QString expression = layer()->editFormConfig().constraintExpression( mFieldIdx ); - QString description; + QStringList expressions, descriptions; QVariant value = ft.attribute( mFieldIdx ); + QString fieldName = ft.fields().count() > mFieldIdx ? ft.fields().field( mFieldIdx ).name() : QString(); + + mConstraintFailureReason.clear(); + + QStringList errors; if ( ! expression.isEmpty() ) { - description = layer()->editFormConfig().constraintDescription( mFieldIdx ); + expressions << expression; + descriptions << layer()->editFormConfig().constraintDescription( mFieldIdx ); QgsExpressionContext context = layer()->createExpressionContext(); context.setFeature( ft ); @@ -125,11 +131,17 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) mValidConstraint = expr.evaluate( &context ).toBool(); if ( expr.hasParserError() ) - errStr = expr.parserErrorString(); + { + errors << tr( "Parser error: %1" ).arg( expr.parserErrorString() ); + } else if ( expr.hasEvalError() ) - errStr = expr.evalErrorString(); + { + errors << tr( "Evaluation error: %1" ).arg( expr.evalErrorString() ); + } else if ( ! mValidConstraint ) - errStr = tr( "predicate is False" ); + { + errors << tr( "%1 check failed" ).arg( layer()->editFormConfig().constraintDescription( mFieldIdx ) ); + } toEmit = true; } @@ -138,30 +150,66 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) if ( layer()->fieldConstraints( mFieldIdx ) & QgsField::ConstraintNotNull ) { + descriptions << QStringLiteral( "NotNull" ); if ( !expression.isEmpty() ) { - QString fieldName = ft.fields().field( mFieldIdx ).name(); - expression = "( " + expression + " ) AND ( " + fieldName + " IS NOT NULL)"; - description = "( " + description + " ) AND NotNull"; + expressions << fieldName + " IS NOT NULL"; } else { - description = QStringLiteral( "NotNull" ); - expression = QStringLiteral( "NotNull" ); + expressions << QStringLiteral( "NotNull" ); } mValidConstraint = mValidConstraint && !value.isNull(); if ( value.isNull() ) - errStr = tr( "predicate is False" ); + { + errors << tr( "Value is NULL" ); + } + + toEmit = true; + } + + if ( layer()->fieldConstraints( mFieldIdx ) & QgsField::ConstraintUnique ) + { + descriptions << QStringLiteral( "Unique" ); + if ( !expression.isEmpty() ) + { + expressions << fieldName + " IS UNIQUE"; + } + else + { + expression = QStringLiteral( "Unique" ); + } + + bool alreadyExists = QgsVectorLayerUtils::valueExists( layer(), mFieldIdx, value, QgsFeatureIds() << ft.id() ); + mValidConstraint = mValidConstraint && !alreadyExists; + + if ( alreadyExists ) + { + errors << tr( "Value is not unique" ); + } toEmit = true; } if ( toEmit ) { + QString errStr = errors.isEmpty() ? tr( "Constraint checks passed" ) : errors.join( '\n' ); + mConstraintFailureReason = errors.join( ", " ); + QString description; + if ( descriptions.size() > 1 ) + description = "( " + descriptions.join( " ) AND ( " ) + " )"; + else if ( !descriptions.isEmpty() ) + description = descriptions.at( 0 ); + QString expressionDesc; + if ( expressions.size() > 1 ) + expressionDesc = "( " + expressions.join( " ) AND ( " ) + " )"; + else if ( !expressions.isEmpty() ) + expressionDesc = expressions.at( 0 ); + updateConstraintWidgetStatus( mValidConstraint ); - emit constraintStatusChanged( expression, description, errStr, mValidConstraint ); + emit constraintStatusChanged( expressionDesc, description, errStr, mValidConstraint ); } } @@ -170,6 +218,11 @@ bool QgsEditorWidgetWrapper::isValidConstraint() const return mValidConstraint; } +QString QgsEditorWidgetWrapper::constraintFailureReason() const +{ + return mConstraintFailureReason; +} + bool QgsEditorWidgetWrapper::isInTable( const QWidget* parent ) { if ( !parent ) return false; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h index f5894f08020e..c013c31b4ae9 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h @@ -124,12 +124,21 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper /** * Get the current constraint status. - * @return true if the constraint is valid or if there's not constraint, + * @return true if the constraint is valid or if there's no constraint, * false otherwise * @note added in QGIS 2.16 + * @see constraintFailureReason() */ bool isValidConstraint() const; + /** + * Returns the reason why a constraint check has failed (or an empty string + * if constraint check was successful). + * @see isValidConstraint() + * @note added in QGIS 3.0 + */ + QString constraintFailureReason() const; + signals: /** * Emit this signal, whenever the value changed. @@ -239,6 +248,9 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper */ bool mValidConstraint; + //! Contains the string explanation of why a constraint check failed + QString mConstraintFailureReason; + int mFieldIdx; QgsFeature mFeature; mutable QVariant mDefaultValue; // Cache default value, we don't want to retrieve different serial numbers if called repeatedly diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index f4069e64e6cd..6582131dc024 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -824,8 +824,7 @@ bool QgsAttributeForm::currentFormValidConstraints( QStringList &invalidFields, { invalidFields.append( eww->field().name() ); - QString desc = eww->layer()->editFormConfig().constraintDescription( eww->fieldIdx() ); - descriptions.append( desc ); + descriptions.append( eww->constraintFailureReason() ); valid = false; // continue to get all invalif fields } From f99ea26bdf9b17749de3257f1933451663b7602f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 08:53:08 +1000 Subject: [PATCH 576/897] Refactor constraint handling - store constraint origin in QgsField - move handling of constraint expressions to QgsField --- python/core/qgsfield.sip | 60 ++++++++++++++- python/core/qgsvectordataprovider.sip | 2 +- src/app/qgsfieldsproperties.cpp | 12 +-- src/core/qgsfield.cpp | 77 +++++++++++++++++-- src/core/qgsfield.h | 63 ++++++++++++++- src/core/qgsfield_p.h | 17 +++- src/core/qgsvectordataprovider.cpp | 7 +- src/core/qgsvectordataprovider.h | 2 +- src/core/qgsvectorlayer.cpp | 7 +- .../core/qgseditorwidgetwrapper.cpp | 4 +- src/gui/qgsattributeform.cpp | 2 +- .../postgres/qgspostgresprovider.cpp | 14 +--- src/providers/postgres/qgspostgresprovider.h | 1 - .../spatialite/qgsspatialiteprovider.cpp | 19 +---- .../spatialite/qgsspatialiteprovider.h | 1 - tests/src/core/testqgsfield.cpp | 46 ++++++++--- tests/src/python/test_provider_postgres.py | 5 ++ tests/src/python/test_provider_spatialite.py | 10 ++- tests/src/python/test_qgsvectorlayer.py | 18 +++++ 19 files changed, 302 insertions(+), 65 deletions(-) diff --git a/python/core/qgsfield.sip b/python/core/qgsfield.sip index 7140a63abbfd..91c4d01ce91d 100644 --- a/python/core/qgsfield.sip +++ b/python/core/qgsfield.sip @@ -26,6 +26,17 @@ class QgsField }; typedef QFlags Constraints; + /** + * Origin of constraints. + * @note added in QGIS 3.0 + */ + enum ConstraintOrigin + { + ConstraintOriginNotSet, //!< Constraint is not set + ConstraintOriginProvider, //!< Constraint was set at data provider + ConstraintOriginLayer, //!< Constraint was set by layer + }; + /** Constructor. Constructs a new QgsField object. * @param name Field name * @param type Field variant type, currently supported: String / Int / Double @@ -178,15 +189,60 @@ class QgsField * Returns any constraints which are present for the field. * @note added in QGIS 3.0 * @see setConstraints() + * @see constraintOrigin() */ Constraints constraints() const; /** - * Sets constraints which are present for the field. + * Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint + * is not present on this field. + * @note added in QGIS 3.0 + * @see constraints() + */ + ConstraintOrigin constraintOrigin( Constraint constraint ) const; + + /** + * Sets a constraint on the field. + * @note added in QGIS 3.0 + * @see constraints() + * @see removeConstraint() + */ + void setConstraint( Constraint constraint, ConstraintOrigin origin = ConstraintOriginLayer ); + + /** + * Removes a constraint from the field. + * @see setConstraint() + * @see constraints() + */ + void removeConstraint( Constraint constraint ); + + /** + * Returns the constraint expression for the field, if set. + * @note added in QGIS 3.0 + * @see constraints() + * @see constraintDescription() + * @see setConstraintExpression() + */ + QString constraintExpression() const; + + /** + * Returns the descriptive name for the constraint expression. + * @note added in QGIS 3.0 + * @see constraints() + * @see constraintExpression() + * @see setConstraintExpression() + */ + QString constraintDescription() const; + + /** + * Set the constraint expression for the field. An optional descriptive name for the constraint + * can also be set. Setting an empty expression will clear any existing expression constraint. * @note added in QGIS 3.0 + * @see constraintExpression() + * @see constraintDescription() * @see constraints() */ - void setConstraints( Constraints constraints ); + void setConstraintExpression( const QString& expression, const QString& description = QString() ); /** Returns the alias for the field (the friendly displayed name of the field ), * or an empty string if there is no alias. diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 37a309f932e5..8cf11d788c83 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -235,7 +235,7 @@ class QgsVectorDataProvider : QgsDataProvider * field index. * @note added in QGIS 3.0 */ - virtual QgsField::Constraints fieldConstraints( int fieldIndex ) const; + QgsField::Constraints fieldConstraints( int fieldIndex ) const; /** * Changes geometries of existing features diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index a585856854f7..a72638619cdb 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -562,10 +562,12 @@ void QgsFieldsProperties::attributeTypeDialog() attributeTypeDialog.setUnique( cfg.mConstraints & QgsField::ConstraintUnique ); QgsField::Constraints providerConstraints = 0; - if ( mLayer->fields().fieldOrigin( index ) == QgsFields::OriginProvider ) - { - providerConstraints = mLayer->dataProvider()->fieldConstraints( mLayer->fields().fieldOriginIndex( index ) ); - } + if ( mLayer->fields().at( index ).constraintOrigin( QgsField::ConstraintNotNull ) == QgsField::ConstraintOriginProvider ) + providerConstraints |= QgsField::ConstraintNotNull; + if ( mLayer->fields().at( index ).constraintOrigin( QgsField::ConstraintUnique ) == QgsField::ConstraintOriginProvider ) + providerConstraints |= QgsField::ConstraintUnique; + if ( mLayer->fields().at( index ).constraintOrigin( QgsField::ConstraintExpression ) == QgsField::ConstraintOriginProvider ) + providerConstraints |= QgsField::ConstraintExpression; attributeTypeDialog.setProviderConstraints( providerConstraints ); attributeTypeDialog.setConstraintExpression( cfg.mConstraint ); @@ -1059,7 +1061,7 @@ QgsFieldsProperties::FieldConfig::FieldConfig( QgsVectorLayer* layer, int idx ) mEditableEnabled = layer->fields().fieldOrigin( idx ) != QgsFields::OriginJoin && layer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression; mLabelOnTop = layer->editFormConfig().labelOnTop( idx ); - mConstraints = layer->fieldConstraints( idx ); + mConstraints = layer->fields().at( idx ).constraints(); mConstraint = layer->editFormConfig().constraintExpression( idx ); mConstraintDescription = layer->editFormConfig().constraintDescription( idx ); const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( layer, layer->fields().field( idx ).name() ); diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index 091025962a98..428f5e050e7a 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -185,9 +185,55 @@ QgsField::Constraints QgsField::constraints() const return d->constraints; } -void QgsField::setConstraints( Constraints constraints ) +QgsField::ConstraintOrigin QgsField::constraintOrigin( QgsField::Constraint constraint ) const { - d->constraints = constraints; + if ( !( d->constraints & constraint ) ) + return ConstraintOriginNotSet; + + return d->constraintOrigins.value( constraint, ConstraintOriginNotSet ); +} + +void QgsField::setConstraint( QgsField::Constraint constraint, QgsField::ConstraintOrigin origin ) +{ + if ( origin == ConstraintOriginNotSet ) + { + d->constraints &= ~constraint; + d->constraintOrigins.remove( constraint ); + } + else + { + d->constraints |= constraint; + d->constraintOrigins.insert( constraint, origin ); + } +} + +void QgsField::removeConstraint( QgsField::Constraint constraint ) +{ + d->constraints &= ~constraint; +} + +QString QgsField::constraintExpression() const +{ + return d->constraints & QgsField::ConstraintExpression ? d->expressionConstraint : QString(); +} + +QString QgsField::constraintDescription() const +{ + return d->expressionConstraintDescription; +} + +void QgsField::setConstraintExpression( const QString& expression, const QString& description ) +{ + if ( expression.isEmpty() ) + d->constraints &= ~QgsField::ConstraintExpression; + else + { + d->constraints |= QgsField::ConstraintExpression; + d->constraintOrigins.insert( QgsField::ConstraintExpression, QgsField::ConstraintOriginLayer ); + } + + d->expressionConstraint = expression; + d->expressionConstraintDescription = description; } QString QgsField::alias() const @@ -314,15 +360,22 @@ QDataStream& operator<<( QDataStream& out, const QgsField& field ) out << field.alias(); out << field.defaultValueExpression(); out << field.constraints(); + out << static_cast< quint32 >( field.constraintOrigin( QgsField::ConstraintNotNull ) ); + out << static_cast< quint32 >( field.constraintOrigin( QgsField::ConstraintUnique ) ); + out << static_cast< quint32 >( field.constraintOrigin( QgsField::ConstraintExpression ) ); + out << field.constraintExpression(); + out << field.constraintDescription(); out << static_cast< quint32 >( field.subType() ); return out; } QDataStream& operator>>( QDataStream& in, QgsField& field ) { - quint32 type, subType, length, precision, constraints; - QString name, typeName, comment, alias, defaultValueExpression; - in >> name >> type >> typeName >> length >> precision >> comment >> alias >> defaultValueExpression >> constraints >> subType; + quint32 type, subType, length, precision, constraints, originNotNull, originUnique, originExpression; + QString name, typeName, comment, alias, defaultValueExpression, constraintExpression, constraintDescription; + in >> name >> type >> typeName >> length >> precision >> comment >> alias + >> defaultValueExpression >> constraints >> originNotNull >> originUnique >> originExpression >> + constraintExpression >> constraintDescription >> subType; field.setName( name ); field.setType( static_cast< QVariant::Type >( type ) ); field.setTypeName( typeName ); @@ -331,7 +384,19 @@ QDataStream& operator>>( QDataStream& in, QgsField& field ) field.setComment( comment ); field.setAlias( alias ); field.setDefaultValueExpression( defaultValueExpression ); - field.setConstraints( static_cast< QgsField::Constraints>( constraints ) ); + if ( constraints & QgsField::ConstraintNotNull ) + field.setConstraint( QgsField::ConstraintNotNull, static_cast< QgsField::ConstraintOrigin>( originNotNull ) ); + else + field.removeConstraint( QgsField::ConstraintNotNull ); + if ( constraints & QgsField::ConstraintUnique ) + field.setConstraint( QgsField::ConstraintUnique, static_cast< QgsField::ConstraintOrigin>( originUnique ) ); + else + field.removeConstraint( QgsField::ConstraintUnique ); + if ( constraints & QgsField::ConstraintExpression ) + field.setConstraint( QgsField::ConstraintExpression, static_cast< QgsField::ConstraintOrigin>( originExpression ) ); + else + field.removeConstraint( QgsField::ConstraintExpression ); + field.setConstraintExpression( constraintExpression, constraintDescription ); field.setSubType( static_cast< QVariant::Type >( subType ) ); return in; } diff --git a/src/core/qgsfield.h b/src/core/qgsfield.h index 6fadb60ce702..fcb1d21f02dd 100644 --- a/src/core/qgsfield.h +++ b/src/core/qgsfield.h @@ -54,7 +54,7 @@ class CORE_EXPORT QgsField Q_PROPERTY( QString name READ name WRITE setName ) Q_PROPERTY( QString alias READ alias WRITE setAlias ) Q_PROPERTY( QString defaultValueExpression READ defaultValueExpression WRITE setDefaultValueExpression ) - Q_PROPERTY( Constraints constraints READ constraints WRITE setConstraints ) + Q_PROPERTY( Constraints constraints READ constraints ) public: @@ -66,9 +66,21 @@ class CORE_EXPORT QgsField { ConstraintNotNull = 1, //!< Field may not be null ConstraintUnique = 1 << 1, //!< Field must have a unique value + ConstraintExpression = 1 << 2, //!< Field has an expression constraint set. See constraintExpression(). }; Q_DECLARE_FLAGS( Constraints, Constraint ) + /** + * Origin of constraints. + * @note added in QGIS 3.0 + */ + enum ConstraintOrigin + { + ConstraintOriginNotSet = 0, //!< Constraint is not set + ConstraintOriginProvider, //!< Constraint was set at data provider + ConstraintOriginLayer, //!< Constraint was set by layer + }; + /** Constructor. Constructs a new QgsField object. * @param name Field name * @param type Field variant type, currently supported: String / Int / Double @@ -225,15 +237,60 @@ class CORE_EXPORT QgsField * Returns any constraints which are present for the field. * @note added in QGIS 3.0 * @see setConstraints() + * @see constraintOrigin() */ Constraints constraints() const; /** - * Sets constraints which are present for the field. + * Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint + * is not present on this field. + * @note added in QGIS 3.0 + * @see constraints() + */ + ConstraintOrigin constraintOrigin( Constraint constraint ) const; + + /** + * Sets a constraint on the field. + * @note added in QGIS 3.0 + * @see constraints() + * @see removeConstraint() + */ + void setConstraint( Constraint constraint, ConstraintOrigin origin = ConstraintOriginLayer ); + + /** + * Removes a constraint from the field. + * @see setConstraint() + * @see constraints() + */ + void removeConstraint( Constraint constraint ); + + /** + * Returns the constraint expression for the field, if set. + * @note added in QGIS 3.0 + * @see constraints() + * @see constraintDescription() + * @see setConstraintExpression() + */ + QString constraintExpression() const; + + /** + * Returns the descriptive name for the constraint expression. + * @note added in QGIS 3.0 + * @see constraints() + * @see constraintExpression() + * @see setConstraintExpression() + */ + QString constraintDescription() const; + + /** + * Set the constraint expression for the field. An optional descriptive name for the constraint + * can also be set. Setting an empty expression will clear any existing expression constraint. * @note added in QGIS 3.0 + * @see constraintExpression() + * @see constraintDescription() * @see constraints() */ - void setConstraints( Constraints constraints ); + void setConstraintExpression( const QString& expression, const QString& description = QString() ); /** Returns the alias for the field (the friendly displayed name of the field ), * or an empty string if there is no alias. diff --git a/src/core/qgsfield_p.h b/src/core/qgsfield_p.h index 858c99568878..27a2fc6b0718 100644 --- a/src/core/qgsfield_p.h +++ b/src/core/qgsfield_p.h @@ -71,6 +71,9 @@ class QgsFieldPrivate : public QSharedData , alias( other.alias ) , defaultValueExpression( other.defaultValueExpression ) , constraints( other.constraints ) + , constraintOrigins( other.constraintOrigins ) + , expressionConstraint( other.expressionConstraint ) + , expressionConstraintDescription( other.expressionConstraintDescription ) { } @@ -81,7 +84,10 @@ class QgsFieldPrivate : public QSharedData return (( name == other.name ) && ( type == other.type ) && ( subType == other.subType ) && ( length == other.length ) && ( precision == other.precision ) && ( alias == other.alias ) && ( defaultValueExpression == other.defaultValueExpression ) - && ( constraints == other.constraints ) ); + && ( constraints == other.constraints ) + && ( expressionConstraint == other.expressionConstraint ) + && ( expressionConstraintDescription == other.expressionConstraintDescription ) + && ( constraintOrigins == other.constraintOrigins ) ); } //! Name @@ -114,6 +120,15 @@ class QgsFieldPrivate : public QSharedData //! Constraints QgsField::Constraints constraints; + //! Origin of field constraints + QHash< QgsField::Constraint, QgsField::ConstraintOrigin > constraintOrigins; + + //! Expression constraint + QString expressionConstraint; + + //! Expression constraint descriptive name + QString expressionConstraintDescription; + QgsEditorWidgetSetup editorWidgetSetup; }; diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 4242d680c4dc..1fdc55d39c64 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -100,8 +100,11 @@ QVariant QgsVectorDataProvider::defaultValue( int fieldId ) const QgsField::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const { - Q_UNUSED( fieldIndex ); - return 0; + QgsFields f = fields(); + if ( fieldIndex < 0 || fieldIndex >= f.count() ) + return 0; + + return f.at( fieldIndex ).constraints(); } bool QgsVectorDataProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index 57d94ee1d35f..b237291978b5 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -286,7 +286,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider * field index. * @note added in QGIS 3.0 */ - virtual QgsField::Constraints fieldConstraints( int fieldIndex ) const; + QgsField::Constraints fieldConstraints( int fieldIndex ) const; /** * Changes geometries of existing features diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 6cb1d82a8baf..6fdb57c8c444 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -2940,7 +2940,12 @@ void QgsVectorLayer::updateFields() continue; // always keep provider constraints intact - mFields[ index ].setConstraints( mFields.at( index ).constraints() | constraintIt.value() ); + if ( !( mFields.at( index ).constraints() & QgsField::ConstraintNotNull ) && ( constraintIt.value() & QgsField::ConstraintNotNull ) ) + mFields[ index ].setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginLayer ); + if ( !( mFields.at( index ).constraints() & QgsField::ConstraintUnique ) && ( constraintIt.value() & QgsField::ConstraintUnique ) ) + mFields[ index ].setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginLayer ); + if ( !( mFields.at( index ).constraints() & QgsField::ConstraintExpression ) && ( constraintIt.value() & QgsField::ConstraintExpression ) ) + mFields[ index ].setConstraint( QgsField::ConstraintExpression, QgsField::ConstraintOriginLayer ); } if ( oldFields != mFields ) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 3241e98d706f..2ee3399f6bf9 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -148,7 +148,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) else mValidConstraint = true; - if ( layer()->fieldConstraints( mFieldIdx ) & QgsField::ConstraintNotNull ) + if ( layer()->fields().at( mFieldIdx ).constraints() & QgsField::ConstraintNotNull ) { descriptions << QStringLiteral( "NotNull" ); if ( !expression.isEmpty() ) @@ -170,7 +170,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) toEmit = true; } - if ( layer()->fieldConstraints( mFieldIdx ) & QgsField::ConstraintUnique ) + if ( layer()->fields().at( mFieldIdx ).constraints() & QgsField::ConstraintUnique ) { descriptions << QStringLiteral( "Unique" ); if ( !expression.isEmpty() ) diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 6582131dc024..45bfb2c655d4 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -674,7 +674,7 @@ void QgsAttributeForm::onAttributeChanged( const QVariant& value ) break; } - if ( eww->layer()->fieldConstraints( eww->fieldIdx() ) & QgsField::ConstraintNotNull ) + if ( eww->layer()->fields().at( eww->fieldIdx() ).constraints() & QgsField::ConstraintNotNull ) { QLabel* buddy = mBuddyMap.value( eww->widget() ); diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 0a74c9c9bf62..2f144f88d1a7 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1000,12 +1000,10 @@ bool QgsPostgresProvider::loadFields() QgsField newField = QgsField( fieldName, fieldType, fieldTypeName, fieldSize, fieldPrec, fieldComment, fieldSubType ); - QgsField::Constraints constraints = 0; if ( notNullMap[tableoid][attnum] ) - constraints |= QgsField::ConstraintNotNull; + newField.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); if ( uniqueMap[tableoid][attnum] ) - constraints |= QgsField::ConstraintUnique; - newField.setConstraints( constraints ); + newField.setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginProvider ); mAttributeFields.append( newField ); } @@ -1738,14 +1736,6 @@ QVariant QgsPostgresProvider::defaultValue( int fieldId ) const return defVal; } -QgsField::Constraints QgsPostgresProvider::fieldConstraints( int fieldIndex ) const -{ - if ( fieldIndex < 0 || fieldIndex >= mAttributeFields.count() ) - return 0; - - return mAttributeFields.at( fieldIndex ).constraints(); -} - QString QgsPostgresProvider::paramValue( const QString& fieldValue, const QString &defaultValue ) const { if ( fieldValue.isNull() ) diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index 6033152caf35..eb90e2d770db 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -161,7 +161,6 @@ class QgsPostgresProvider : public QgsVectorDataProvider QgsAttributeList attributeIndexes() const override; QgsAttributeList pkAttributeIndexes() const override { return mPrimaryKeyAttrs; } QVariant defaultValue( int fieldId ) const override; - QgsField::Constraints fieldConstraints( int fieldIndex ) const override; /** Adds a list of features @return true in case of success and false in case of failure*/ diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index 42746a84cf5a..a01992225cab 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -842,16 +842,13 @@ void QgsSpatiaLiteProvider::fetchConstraints() field = field.trimmed(); QString fieldName = field.left( field.indexOf( ' ' ) ); QString definition = field.mid( field.indexOf( ' ' ) + 1 ); - QgsField::Constraints constraints = 0; - if ( definition.contains( "unique", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) - constraints |= QgsField::ConstraintUnique; - if ( definition.contains( "not null", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) - constraints |= QgsField::ConstraintNotNull; - int fieldIdx = mAttributeFields.lookupField( fieldName ); if ( fieldIdx >= 0 ) { - mAttributeFields[ fieldIdx ].setConstraints( constraints ); + if ( definition.contains( "unique", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) + mAttributeFields[ fieldIdx ].setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginProvider ); + if ( definition.contains( "not null", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) + mAttributeFields[ fieldIdx ].setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); } } } @@ -3666,14 +3663,6 @@ void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueV return; } -QgsField::Constraints QgsSpatiaLiteProvider::fieldConstraints( int fieldIndex ) const -{ - if ( fieldIndex < 0 || fieldIndex >= mAttributeFields.count() ) - return 0; - - return mAttributeFields.at( fieldIndex ).constraints(); -} - QString QgsSpatiaLiteProvider::geomParam() const { QString geometry; diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index f81ada41abc8..94295d200172 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -130,7 +130,6 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider QVariant minimumValue( int index ) const override; QVariant maximumValue( int index ) const override; virtual void uniqueValues( int index, QList < QVariant > &uniqueValues, int limit = -1 ) const override; - QgsField::Constraints fieldConstraints( int fieldIndex ) const override; bool isValid() const override; virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } diff --git a/tests/src/core/testqgsfield.cpp b/tests/src/core/testqgsfield.cpp index ab61324465c6..8b9fda2eb726 100644 --- a/tests/src/core/testqgsfield.cpp +++ b/tests/src/core/testqgsfield.cpp @@ -84,7 +84,8 @@ void TestQgsField::create() void TestQgsField::copy() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); - original.setConstraints( QgsField::ConstraintNotNull ); + original.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + original.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); QgsField copy( original ); QVERIFY( copy == original ); @@ -96,7 +97,8 @@ void TestQgsField::copy() void TestQgsField::assignment() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); - original.setConstraints( QgsField::ConstraintNotNull ); + original.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + original.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); QgsField copy; copy = original; QVERIFY( copy == original ); @@ -125,8 +127,22 @@ void TestQgsField::gettersSetters() QCOMPARE( field.alias(), QString( "alias" ) ); field.setDefaultValueExpression( QStringLiteral( "1+2" ) ); QCOMPARE( field.defaultValueExpression(), QString( "1+2" ) ); - field.setConstraints( QgsField::ConstraintNotNull ); + field.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); QCOMPARE( field.constraints(), QgsField::ConstraintNotNull ); + QCOMPARE( field.constraintOrigin( QgsField::ConstraintNotNull ), QgsField::ConstraintOriginProvider ); + QCOMPARE( field.constraintOrigin( QgsField::ConstraintUnique ), QgsField::ConstraintOriginNotSet ); + field.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginNotSet ); + QCOMPARE( field.constraints(), 0 ); + field.setConstraint( QgsField::ConstraintUnique ); + field.setConstraint( QgsField::ConstraintNotNull ); + QCOMPARE( field.constraints(), QgsField::ConstraintUnique | QgsField::ConstraintNotNull ); + field.removeConstraint( QgsField::ConstraintNotNull ); + QCOMPARE( field.constraints(), QgsField::ConstraintUnique ); + + field.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + QCOMPARE( field.constraintExpression(), QStringLiteral( "constraint expression" ) ); + QCOMPARE( field.constraintDescription(), QStringLiteral( "description" ) ); + QCOMPARE( field.constraints(), QgsField::ConstraintUnique | QgsField::ConstraintExpression ); //setting constraint expression should add constraint } void TestQgsField::isNumeric() @@ -161,7 +177,7 @@ void TestQgsField::equality() field1.setPrecision( 2 ); field1.setTypeName( QStringLiteral( "typename1" ) ); //typename is NOT required for equality field1.setComment( QStringLiteral( "comment1" ) ); //comment is NOT required for equality - field1.setConstraints( QgsField::ConstraintNotNull ); + field1.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); QgsField field2; field2.setName( QStringLiteral( "name" ) ); field2.setType( QVariant::Int ); @@ -169,7 +185,7 @@ void TestQgsField::equality() field2.setPrecision( 2 ); field2.setTypeName( QStringLiteral( "typename2" ) ); //typename is NOT required for equality field2.setComment( QStringLiteral( "comment2" ) ); //comment is NOT required for equality - field2.setConstraints( QgsField::ConstraintNotNull ); + field2.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); QVERIFY( field1 == field2 ); QVERIFY( !( field1 != field2 ) ); @@ -198,16 +214,26 @@ void TestQgsField::equality() QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); field2.setDefaultValueExpression( QString() ); - field2.setConstraints( QgsField::ConstraintUnique ); + field2.removeConstraint( QgsField::ConstraintNotNull ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - field2.setConstraints( QgsField::ConstraintNotNull ); + field2.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginLayer ); + QVERIFY( !( field1 == field2 ) ); + QVERIFY( field1 != field2 ); + field2.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + field2.setConstraintExpression( QStringLiteral( "exp" ) ); + QVERIFY( !( field1 == field2 ) ); + QVERIFY( field1 != field2 ); + field2.setConstraintExpression( QStringLiteral( "exp" ), QStringLiteral( "desc" ) ); + QVERIFY( !( field1 == field2 ) ); + QVERIFY( field1 != field2 ); + field2.setConstraintExpression( QString(), QString() ); } void TestQgsField::asVariant() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); - original.setConstraints( QgsField::ConstraintNotNull ); + original.setConstraint( QgsField::ConstraintNotNull ); //convert to and from a QVariant QVariant var = QVariant::fromValue( original ); @@ -386,7 +412,9 @@ void TestQgsField::dataStream() original.setComment( QStringLiteral( "comment1" ) ); original.setAlias( QStringLiteral( "alias" ) ); original.setDefaultValueExpression( QStringLiteral( "default" ) ); - original.setConstraints( QgsField::ConstraintNotNull ); + original.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + original.setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginLayer ); + original.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); QByteArray ba; QDataStream ds( &ba, QIODevice::ReadWrite ); diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index b92a4f18b18e..51f4e38391a3 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -455,8 +455,10 @@ def testNotNullConstraint(self): # test that constraints have been saved to fields correctly fields = vl.fields() self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintNotNull) + self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintNotNull) self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintNotNull) + self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintNotNull) def testUniqueConstraint(self): @@ -476,8 +478,11 @@ def testUniqueConstraint(self): # test that constraints have been saved to fields correctly fields = vl.fields() self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintUnique) + self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) self.assertTrue(fields.at(1).constraints() & QgsField.ConstraintUnique) + self.assertEqual(fields.at(1).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) + self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) def testConstraintOverwrite(self): diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index 3f6ab3d487e5..12846ad35bd8 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -388,7 +388,7 @@ def test_discover_relation(self): def testNotNullConstraint(self): vl = QgsVectorLayer("dbname=%s table=test_constraints key='id'" % self.dbname, "test_constraints", - "spatialite") + "spatialite") self.assertTrue(vl.isValid()) self.assertEqual(len(vl.fields()), 5) @@ -405,14 +405,17 @@ def testNotNullConstraint(self): # test that constraints have been saved to fields correctly fields = vl.fields() self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintNotNull) + self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) self.assertTrue(fields.at(1).constraints() & QgsField.ConstraintNotNull) + self.assertEqual(fields.at(1).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) self.assertFalse(fields.at(2).constraints() & QgsField.ConstraintNotNull) self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintNotNull) self.assertTrue(fields.at(4).constraints() & QgsField.ConstraintNotNull) + self.assertEqual(fields.at(4).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) def testUniqueConstraint(self): vl = QgsVectorLayer("dbname=%s table=test_constraints key='id'" % self.dbname, "test_constraints", - "spatialite") + "spatialite") self.assertTrue(vl.isValid()) self.assertEqual(len(vl.fields()), 5) @@ -429,10 +432,13 @@ def testUniqueConstraint(self): # test that constraints have been saved to fields correctly fields = vl.fields() self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintUnique) + self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintUnique) self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) + self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) self.assertTrue(fields.at(4).constraints() & QgsField.ConstraintUnique) + self.assertEqual(fields.at(4).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) # This test would fail. It would require turning on WAL def XXXXXtestLocking(self): diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index e294edc1370d..cddfca02ad18 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1786,20 +1786,32 @@ def testGetSetConstraints(self): self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginLayer) layer.setFieldConstraints(1, QgsField.ConstraintNotNull | QgsField.ConstraintUnique) self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) self.assertEqual(layer.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) self.assertFalse(layer.fieldConstraints(2)) self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginLayer) self.assertEqual(layer.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintUnique), + QgsField.ConstraintOriginLayer) layer.setFieldConstraints(1, QgsField.Constraints()) self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginLayer) self.assertFalse(layer.fields().at(1).constraints()) + self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginNotSet) def testSaveRestoreConstraints(self): """ test saving and restoring constraints from xml""" @@ -1828,7 +1840,13 @@ def testSaveRestoreConstraints(self): self.assertEqual(layer3.fieldConstraints(0), QgsField.ConstraintNotNull) self.assertEqual(layer3.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) self.assertEqual(layer3.fields().at(0).constraints(), QgsField.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginLayer) self.assertEqual(layer3.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), + QgsField.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintUnique), + QgsField.ConstraintOriginLayer) def testGetFeatureLimitWithEdits(self): """ test getting features with a limit, when edits are present """ From 2500d75f5eb3072026a5092f3bfd90fbbc94acca Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 09:45:45 +1000 Subject: [PATCH 577/897] Move responsibility for storage of constraint expressions to QgsVectorLayer --- python/core/qgseditformconfig.sip | 46 ----------- python/core/qgsfield.sip | 1 + python/core/qgsvectorlayer.sip | 28 +++++++ src/app/qgsfieldsproperties.cpp | 7 +- src/core/qgseditformconfig.cpp | 38 --------- src/core/qgseditformconfig.h | 46 ----------- src/core/qgseditformconfig_p.h | 4 - src/core/qgsvectorlayer.cpp | 77 +++++++++++++++++++ src/core/qgsvectorlayer.h | 31 ++++++++ .../core/qgseditorwidgetregistry.cpp | 10 ++- .../core/qgseditorwidgetwrapper.cpp | 17 ++-- src/gui/qgsattributeform.cpp | 2 +- tests/src/gui/testqgsattributeform.cpp | 70 ++++++++++------- tests/src/python/test_qgsvectorlayer.py | 73 +++++++++++++++++- 14 files changed, 269 insertions(+), 181 deletions(-) diff --git a/python/core/qgseditformconfig.sip b/python/core/qgseditformconfig.sip index d59ba96d95bb..1f6987922327 100644 --- a/python/core/qgseditformconfig.sip +++ b/python/core/qgseditformconfig.sip @@ -197,52 +197,6 @@ class QgsEditFormConfig */ void setReadOnly( int idx, bool readOnly = true ); - /** - * Returns the constraint expression of a specific field - * - * @param idx The index of the field - * @return the expression - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - QString constraintExpression( int idx ) const; - - /** - * Set the constraint expression for a specific field - * - * @param idx the field index - * @param expression the constraint expression - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - void setConstraintExpression( int idx, const QString& expression ); - - /** - * Returns the constraint expression description of a specific field. - * - * @param idx The index of the field - * @return The expression description. Will be presented - * to the user in case the constraint fails. - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - QString constraintDescription( int idx ) const; - - /** - * Set the constraint expression description for a specific field. - * - * @param idx The index of the field - * @param description The description of the expression. Will be presented - * to the user in case the constraint fails. - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - void setContraintDescription( int idx, const QString& description ); - /** * If this returns true, the widget at the given index will receive its label on the previous line * while if it returns false, the widget will receive its label on the left hand side. diff --git a/python/core/qgsfield.sip b/python/core/qgsfield.sip index 91c4d01ce91d..9fb8c0af059c 100644 --- a/python/core/qgsfield.sip +++ b/python/core/qgsfield.sip @@ -23,6 +23,7 @@ class QgsField { ConstraintNotNull, //!< Field may not be null ConstraintUnique, //!< Field must have a unique value + ConstraintExpression, //!< Field has an expression constraint set. See constraintExpression(). }; typedef QFlags Constraints; diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index bb906db13903..c48d5b42134f 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1275,6 +1275,34 @@ class QgsVectorLayer : QgsMapLayer */ void setFieldConstraints( int index, QgsField::Constraints constraints ); + /** + * Returns the constraint expression for for a specified field index, if set. + * @note added in QGIS 3.0 + * @see fieldConstraints() + * @see constraintDescription() + * @see setConstraintExpression() + */ + QString constraintExpression( int index ) const; + + /** + * Returns the descriptive name for the constraint expression for a specified field index. + * @note added in QGIS 3.0 + * @see constraints() + * @see constraintExpression() + * @see setConstraintExpression() + */ + QString constraintDescription( int index ) const; + + /** + * Set the constraint expression for the specified field index. An optional descriptive name for the constraint + * can also be set. Setting an empty expression will clear any existing expression constraint. + * @note added in QGIS 3.0 + * @see constraintExpression() + * @see constraintDescription() + * @see constraints() + */ + void setConstraintExpression( int index, const QString& expression, const QString& description = QString() ); + /** Calculates a list of unique values contained within an attribute in the layer. Note that * in some circumstances when unsaved changes are present for the layer then the returned list * may contain outdated values (for instance when the attribute value in a saved feature has diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index a72638619cdb..d9732867775d 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -977,8 +977,7 @@ void QgsFieldsProperties::apply() editFormConfig.setReadOnly( i, !cfg.mEditable ); editFormConfig.setLabelOnTop( i, cfg.mLabelOnTop ); - editFormConfig.setContraintDescription( i, cfg.mConstraintDescription ); - editFormConfig.setConstraintExpression( i, cfg.mConstraint ); + mLayer->setConstraintExpression( i, cfg.mConstraint, cfg.mConstraintDescription ); editFormConfig.setWidgetType( name, cfg.mEditorWidgetType ); editFormConfig.setWidgetConfig( name, cfg.mEditorWidgetConfig ); @@ -1062,8 +1061,8 @@ QgsFieldsProperties::FieldConfig::FieldConfig( QgsVectorLayer* layer, int idx ) && layer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression; mLabelOnTop = layer->editFormConfig().labelOnTop( idx ); mConstraints = layer->fields().at( idx ).constraints(); - mConstraint = layer->editFormConfig().constraintExpression( idx ); - mConstraintDescription = layer->editFormConfig().constraintDescription( idx ); + mConstraint = layer->fields().at( idx ).constraintExpression(); + mConstraintDescription = layer->fields().at( idx ).constraintDescription(); const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( layer, layer->fields().field( idx ).name() ); mEditorWidgetType = setup.type(); mEditorWidgetConfig = setup.config(); diff --git a/src/core/qgseditformconfig.cpp b/src/core/qgseditformconfig.cpp index 512b18ea7c46..8dc518e6b023 100644 --- a/src/core/qgseditformconfig.cpp +++ b/src/core/qgseditformconfig.cpp @@ -182,44 +182,6 @@ bool QgsEditFormConfig::labelOnTop( int idx ) const return false; } -QString QgsEditFormConfig::constraintExpression( int idx ) const -{ - QString expr; - - if ( idx >= 0 && idx < d->mFields.count() ) - expr = d->mConstraints.value( d->mFields.at( idx ).name(), QString() ); - - return expr; -} - -void QgsEditFormConfig::setConstraintExpression( int idx, const QString& expression ) -{ - if ( idx >= 0 && idx < d->mFields.count() ) - { - d.detach(); - d->mConstraints[ d->mFields.at( idx ).name()] = expression; - } -} - -QString QgsEditFormConfig::constraintDescription( int idx ) const -{ - QString description; - - if ( idx >= 0 && idx < d->mFields.count() ) - description = d->mConstraintsDescription[ d->mFields.at( idx ).name()]; - - return description; -} - -void QgsEditFormConfig::setContraintDescription( int idx, const QString &descr ) -{ - if ( idx >= 0 && idx < d->mFields.count() ) - { - d.detach(); - d->mConstraintsDescription[ d->mFields.at( idx ).name()] = descr; - } -} - void QgsEditFormConfig::setReadOnly( int idx, bool readOnly ) { if ( idx >= 0 && idx < d->mFields.count() ) diff --git a/src/core/qgseditformconfig.h b/src/core/qgseditformconfig.h index 269a171a6830..2490fffb8677 100644 --- a/src/core/qgseditformconfig.h +++ b/src/core/qgseditformconfig.h @@ -232,52 +232,6 @@ class CORE_EXPORT QgsEditFormConfig */ void setReadOnly( int idx, bool readOnly = true ); - /** - * Returns the constraint expression of a specific field - * - * @param idx The index of the field - * @return the expression - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - QString constraintExpression( int idx ) const; - - /** - * Set the constraint expression for a specific field - * - * @param idx the field index - * @param expression the constraint expression - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - void setConstraintExpression( int idx, const QString& expression ); - - /** - * Returns the constraint expression description of a specific field. - * - * @param idx The index of the field - * @return The expression description. Will be presented - * to the user in case the constraint fails. - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - QString constraintDescription( int idx ) const; - - /** - * Set the constraint expression description for a specific field. - * - * @param idx The index of the field - * @param description The description of the expression. Will be presented - * to the user in case the constraint fails. - * - * @note added in QGIS 2.16 - * @note renamed in QGIS 3.0 - */ - void setContraintDescription( int idx, const QString& description ); - /** * If this returns true, the widget at the given index will receive its label on the previous line * while if it returns false, the widget will receive its label on the left hand side. diff --git a/src/core/qgseditformconfig_p.h b/src/core/qgseditformconfig_p.h index e02b3a81a60a..55a014860683 100644 --- a/src/core/qgseditformconfig_p.h +++ b/src/core/qgseditformconfig_p.h @@ -38,8 +38,6 @@ class QgsEditFormConfigPrivate : public QSharedData : QSharedData( o ) , mInvisibleRootContainer( static_cast( o.mInvisibleRootContainer->clone( nullptr ) ) ) , mConfiguredRootContainer( o.mConfiguredRootContainer ) - , mConstraints( o.mConstraints ) - , mConstraintsDescription( o.mConstraintsDescription ) , mFieldEditables( o.mFieldEditables ) , mLabelOnTop( o.mLabelOnTop ) , mEditorWidgetTypes( o.mEditorWidgetTypes ) @@ -64,8 +62,6 @@ class QgsEditFormConfigPrivate : public QSharedData //! This flag is set if the root container was configured by the user bool mConfiguredRootContainer; - QMap< QString, QString> mConstraints; - QMap< QString, QString> mConstraintsDescription; QMap< QString, bool> mFieldEditables; QMap< QString, bool> mLabelOnTop; diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 6fdb57c8c444..19ad11a81ab3 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -1459,6 +1459,24 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) mFieldConstraints.insert( field, static_cast< QgsField::Constraints >( constraints ) ); } } + mFieldConstraintExpressions.clear(); + QDomNode constraintExpressionsNode = layer_node.namedItem( "constraintExpressions" ); + if ( !constraintExpressionsNode.isNull() ) + { + QDomNodeList constraintNodeList = constraintExpressionsNode.toElement().elementsByTagName( "constraint" ); + for ( int i = 0; i < constraintNodeList.size(); ++i ) + { + QDomElement constraintElem = constraintNodeList.at( i ).toElement(); + + QString field = constraintElem.attribute( "field", QString() ); + QString exp = constraintElem.attribute( "exp", QString() ); + QString desc = constraintElem.attribute( "desc", QString() ); + if ( field.isEmpty() || exp.isEmpty() ) + continue; + + mFieldConstraintExpressions.insert( field, qMakePair( exp, desc ) ); + } + } updateFields(); @@ -1677,6 +1695,19 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, } layer_node.appendChild( constraintsElem ); + // constraint expressions + QDomElement constraintExpressionsElem = document.createElement( "constraintExpressions" ); + Q_FOREACH ( const QgsField& field, mFields ) + { + QDomElement constraintExpressionElem = document.createElement( "constraint" ); + constraintExpressionElem.setAttribute( "field", field.name() ); + constraintExpressionElem.setAttribute( "exp", field.constraintExpression() ); + constraintExpressionElem.setAttribute( "desc", field.constraintDescription() ); + constraintExpressionsElem.appendChild( constraintExpressionElem ); + } + layer_node.appendChild( constraintExpressionsElem ); + + // change dependencies QDomElement dataDependenciesElement = document.createElement( QStringLiteral( "dataDependencies" ) ); Q_FOREACH ( const QgsMapLayerDependency& dep, dependencies() ) @@ -2948,6 +2979,20 @@ void QgsVectorLayer::updateFields() mFields[ index ].setConstraint( QgsField::ConstraintExpression, QgsField::ConstraintOriginLayer ); } + QMap< QString, QPair< QString, QString > >::const_iterator constraintExpIt = mFieldConstraintExpressions.constBegin(); + for ( ; constraintExpIt != mFieldConstraintExpressions.constEnd(); ++constraintExpIt ) + { + int index = mFields.lookupField( constraintExpIt.key() ); + if ( index < 0 ) + continue; + + // always keep provider constraints intact + if ( mFields.at( index ).constraintOrigin( QgsField::ConstraintExpression ) == QgsField::ConstraintOriginProvider ) + continue; + + mFields[ index ].setConstraintExpression( constraintExpIt.value().first, constraintExpIt.value().second ); + } + if ( oldFields != mFields ) { emit updatedFields(); @@ -4268,3 +4313,35 @@ void QgsVectorLayer::setFieldConstraints( int index, QgsField::Constraints const } updateFields(); } + +QString QgsVectorLayer::constraintExpression( int index ) const +{ + if ( index < 0 || index >= mFields.count() ) + return QString(); + + return mFields.at( index ).constraintExpression(); +} + +QString QgsVectorLayer::constraintDescription( int index ) const +{ + if ( index < 0 || index >= mFields.count() ) + return QString(); + + return mFields.at( index ).constraintDescription(); +} + +void QgsVectorLayer::setConstraintExpression( int index, const QString& expression, const QString& description ) +{ + if ( index < 0 || index >= mFields.count() ) + return; + + if ( expression.isEmpty() ) + { + mFieldConstraintExpressions.remove( mFields.at( index ).name() ); + } + else + { + mFieldConstraintExpressions.insert( mFields.at( index ).name(), qMakePair( expression, description ) ); + } + updateFields(); +} diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 477bcecb82ae..9c0fc70a2bc3 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1415,6 +1415,34 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void setFieldConstraints( int index, QgsField::Constraints constraints ); + /** + * Returns the constraint expression for for a specified field index, if set. + * @note added in QGIS 3.0 + * @see fieldConstraints() + * @see constraintDescription() + * @see setConstraintExpression() + */ + QString constraintExpression( int index ) const; + + /** + * Returns the descriptive name for the constraint expression for a specified field index. + * @note added in QGIS 3.0 + * @see constraints() + * @see constraintExpression() + * @see setConstraintExpression() + */ + QString constraintDescription( int index ) const; + + /** + * Set the constraint expression for the specified field index. An optional descriptive name for the constraint + * can also be set. Setting an empty expression will clear any existing expression constraint. + * @note added in QGIS 3.0 + * @see constraintExpression() + * @see constraintDescription() + * @see constraints() + */ + void setConstraintExpression( int index, const QString& expression, const QString& description = QString() ); + /** Calculates a list of unique values contained within an attribute in the layer. Note that * in some circumstances when unsaved changes are present for the layer then the returned list * may contain outdated values (for instance when the attribute value in a saved feature has @@ -1955,6 +1983,9 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte //! Map which stores constraints for fields QMap< QString, QgsField::Constraints > mFieldConstraints; + //! Map which stores expression constraints for fields. Value is a pair of expression/description. + QMap< QString, QPair< QString, QString > > mFieldConstraintExpressions; + //! Holds the configuration for the edit form QgsEditFormConfig mEditFormConfig; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index 8f913c63e75f..2863b2fe5808 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -268,8 +268,12 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle // upgrade from older config vectorLayer->setFieldConstraints( idx, vectorLayer->fieldConstraints( idx ) | QgsField::ConstraintNotNull ); } - formConfig.setConstraintExpression( idx, ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ) ); - formConfig.setContraintDescription( idx, ewv2CfgElem.attribute( QStringLiteral( "constraintDescription" ), QString() ) ); + if ( !ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ).isEmpty() ) + { + // upgrade from older config + vectorLayer->setConstraintExpression( idx, ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ), + ewv2CfgElem.attribute( QStringLiteral( "constraintDescription" ), QString() ) ); + } formConfig.setWidgetConfig( name, cfg ); } @@ -323,8 +327,6 @@ void QgsEditorWidgetRegistry::writeMapLayer( QgsMapLayer* mapLayer, QDomElement& QDomElement ewv2CfgElem = doc.createElement( QStringLiteral( "widgetv2config" ) ); ewv2CfgElem.setAttribute( QStringLiteral( "fieldEditable" ), !vectorLayer->editFormConfig().readOnly( idx ) ); ewv2CfgElem.setAttribute( QStringLiteral( "labelOnTop" ), vectorLayer->editFormConfig().labelOnTop( idx ) ); - ewv2CfgElem.setAttribute( QStringLiteral( "constraint" ), vectorLayer->editFormConfig().constraintExpression( idx ) ); - ewv2CfgElem.setAttribute( QStringLiteral( "constraintDescription" ), vectorLayer->editFormConfig().constraintDescription( idx ) ); mWidgetFactories[widgetType]->writeConfig( vectorLayer->editFormConfig().widgetConfig( field.name() ), ewv2CfgElem, doc, vectorLayer, idx ); diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 2ee3399f6bf9..805a37a37731 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -109,10 +109,11 @@ void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) { bool toEmit( false ); - QString expression = layer()->editFormConfig().constraintExpression( mFieldIdx ); + QgsField field = layer()->fields().at( mFieldIdx ); + + QString expression = field.constraintExpression(); QStringList expressions, descriptions; QVariant value = ft.attribute( mFieldIdx ); - QString fieldName = ft.fields().count() > mFieldIdx ? ft.fields().field( mFieldIdx ).name() : QString(); mConstraintFailureReason.clear(); @@ -121,7 +122,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) if ( ! expression.isEmpty() ) { expressions << expression; - descriptions << layer()->editFormConfig().constraintDescription( mFieldIdx ); + descriptions << field.constraintDescription(); QgsExpressionContext context = layer()->createExpressionContext(); context.setFeature( ft ); @@ -140,7 +141,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) } else if ( ! mValidConstraint ) { - errors << tr( "%1 check failed" ).arg( layer()->editFormConfig().constraintDescription( mFieldIdx ) ); + errors << tr( "%1 check failed" ).arg( field.constraintDescription() ); } toEmit = true; @@ -148,12 +149,12 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) else mValidConstraint = true; - if ( layer()->fields().at( mFieldIdx ).constraints() & QgsField::ConstraintNotNull ) + if ( field.constraints() & QgsField::ConstraintNotNull ) { descriptions << QStringLiteral( "NotNull" ); if ( !expression.isEmpty() ) { - expressions << fieldName + " IS NOT NULL"; + expressions << field.name() + " IS NOT NULL"; } else { @@ -170,12 +171,12 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) toEmit = true; } - if ( layer()->fields().at( mFieldIdx ).constraints() & QgsField::ConstraintUnique ) + if ( field.constraints() & QgsField::ConstraintUnique ) { descriptions << QStringLiteral( "Unique" ); if ( !expression.isEmpty() ) { - expressions << fieldName + " IS UNIQUE"; + expressions << field.name() + " IS UNIQUE"; } else { diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 45bfb2c655d4..66c1cf659b04 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -940,7 +940,7 @@ QList QgsAttributeForm::constraintDependencies( QgsEdit if ( name != ewwName ) { // get expression and referencedColumns - QgsExpression expr = eww->layer()->editFormConfig().constraintExpression( eww->fieldIdx() ); + QgsExpression expr = eww->layer()->fields().at( eww->fieldIdx() ).constraintExpression(); Q_FOREACH ( const QString& colName, expr.referencedColumns() ) { diff --git a/tests/src/gui/testqgsattributeform.cpp b/tests/src/gui/testqgsattributeform.cpp index eb810812be41..d8d4e93d4cc0 100644 --- a/tests/src/gui/testqgsattributeform.cpp +++ b/tests/src/gui/testqgsattributeform.cpp @@ -78,14 +78,11 @@ void TestQgsAttributeForm::testFieldConstraint() form.setFeature( ft ); // testing stuff - QSignalSpy spy( &form, SIGNAL( attributeChanged( QString, QVariant ) ) ); QString validLabel = QStringLiteral( "col0*" ); QString invalidLabel = QStringLiteral( "col0*" ); // set constraint - QgsEditFormConfig config = layer->editFormConfig(); - config.setConstraintExpression( 0, QString() ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QString() ); // get wrapper QgsEditorWidgetWrapper *ww; @@ -96,8 +93,13 @@ void TestQgsAttributeForm::testFieldConstraint() QCOMPARE( label->text(), QString( "col0" ) ); // set a not null constraint - config.setConstraintExpression( 0, QStringLiteral( "col0 is not null" ) ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QStringLiteral( "col0 is not null" ) ); + // build a form for this feature + QgsAttributeForm form2( layer ); + form2.setFeature( ft ); + QSignalSpy spy( &form2, SIGNAL( attributeChanged( QString, QVariant ) ) ); + ww = qobject_cast( form2.mWidgets[0] ); + label = form2.mBuddyMap.value( ww->widget() ); // set value to 1 ww->setValue( 1 ); @@ -131,12 +133,10 @@ void TestQgsAttributeForm::testFieldMultiConstraints() ft.setAttribute( QStringLiteral( "col3" ), 3 ); // set constraints for each field - QgsEditFormConfig config = layer->editFormConfig(); - config.setConstraintExpression( 0, QString() ); - config.setConstraintExpression( 1, QString() ); - config.setConstraintExpression( 2, QString() ); - config.setConstraintExpression( 3, QString() ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QString() ); + layer->setConstraintExpression( 1, QString() ); + layer->setConstraintExpression( 2, QString() ); + layer->setConstraintExpression( 3, QString() ); // build a form for this feature QgsAttributeForm form( layer ); @@ -167,15 +167,26 @@ void TestQgsAttributeForm::testFieldMultiConstraints() QCOMPARE( label3->text(), QString( "col3" ) ); // update constraint - config.setConstraintExpression( 0, QStringLiteral( "col0 < (col1 * col2)" ) ); - config.setConstraintExpression( 1, QString() ); - config.setConstraintExpression( 2, QString() ); - config.setConstraintExpression( 3, QStringLiteral( "col0 = 2" ) ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QStringLiteral( "col0 < (col1 * col2)" ) ); + layer->setConstraintExpression( 1, QString() ); + layer->setConstraintExpression( 2, QString() ); + layer->setConstraintExpression( 3, QStringLiteral( "col0 = 2" ) ); + + QgsAttributeForm form2( layer ); + form2.setFeature( ft ); + ww0 = qobject_cast( form2.mWidgets[0] ); + ww1 = qobject_cast( form2.mWidgets[1] ); + ww2 = qobject_cast( form2.mWidgets[2] ); + ww3 = qobject_cast( form2.mWidgets[3] ); + label0 = form2.mBuddyMap.value( ww0->widget() ); + label1 = form2.mBuddyMap.value( ww1->widget() ); + label2 = form2.mBuddyMap.value( ww2->widget() ); + label3 = form2.mBuddyMap.value( ww3->widget() ); + QSignalSpy spy2( &form2, SIGNAL( attributeChanged( QString, QVariant ) ) ); // change value ww0->setValue( 2 ); // update col0 - QCOMPARE( spy.count(), 2 ); + QCOMPARE( spy2.count(), 2 ); QCOMPARE( label0->text(), QString( "col0" + inv ) ); // 2 < ( 1 + 2 ) QCOMPARE( label1->text(), QString( "col1" ) ); @@ -183,9 +194,9 @@ void TestQgsAttributeForm::testFieldMultiConstraints() QCOMPARE( label3->text(), QString( "col3" + val ) ); // 2 = 2 // change value - spy.clear(); + spy2.clear(); ww0->setValue( 1 ); // update col0 - QCOMPARE( spy.count(), 2 ); + QCOMPARE( spy2.count(), 2 ); QCOMPARE( label0->text(), QString( "col0" + val ) ); // 1 < ( 1 + 2 ) QCOMPARE( label1->text(), QString( "col1" ) ); @@ -205,9 +216,7 @@ void TestQgsAttributeForm::testOKButtonStatus() ft.setValid( true ); // set constraint - QgsEditFormConfig config = layer->editFormConfig(); - config.setConstraintExpression( 0, QString() ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QString() ); // build a form for this feature QgsAttributeForm form( layer ); @@ -235,14 +244,21 @@ void TestQgsAttributeForm::testOKButtonStatus() QCOMPARE( okButton->isEnabled(), true ); // invalid constraint and editable layer : OK button disabled - config.setConstraintExpression( 0, QStringLiteral( "col0 = 0" ) ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QStringLiteral( "col0 = 0" ) ); + QgsAttributeForm form2( layer ); + form2.setFeature( ft ); + ww = qobject_cast( form2.mWidgets[0] ); + okButton = form2.mButtonBox->button( QDialogButtonBox::Ok ); ww->setValue( 1 ); QCOMPARE( okButton->isEnabled(), false ); // valid constraint and editable layer : OK button enabled - config.setConstraintExpression( 0, QStringLiteral( "col0 = 2" ) ); - layer->setEditFormConfig( config ); + layer->setConstraintExpression( 0, QStringLiteral( "col0 = 2" ) ); + QgsAttributeForm form3( layer ); + form3.setFeature( ft ); + ww = qobject_cast( form3.mWidgets[0] ); + okButton = form3.mButtonBox->button( QDialogButtonBox::Ok ); + ww->setValue( 2 ); QCOMPARE( okButton->isEnabled(), true ); diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index cddfca02ad18..19abb8dafd10 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1840,12 +1840,79 @@ def testSaveRestoreConstraints(self): self.assertEqual(layer3.fieldConstraints(0), QgsField.ConstraintNotNull) self.assertEqual(layer3.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) self.assertEqual(layer3.fields().at(0).constraints(), QgsField.ConstraintNotNull) - self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), + self.assertEqual(layer3.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginLayer) self.assertEqual(layer3.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) - self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), + self.assertEqual(layer3.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginLayer) - self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintUnique), + self.assertEqual(layer3.fields().at(1).constraintOrigin(QgsField.ConstraintUnique), + QgsField.ConstraintOriginLayer) + + def testGetSetConstraintExpressions(self): + """ test getting and setting field constraint expressions """ + layer = createLayerWithOnePoint() + + self.assertFalse(layer.constraintExpression(0)) + self.assertFalse(layer.constraintExpression(1)) + self.assertFalse(layer.constraintExpression(2)) + + layer.setConstraintExpression(0, '1+2') + self.assertEqual(layer.constraintExpression(0), '1+2') + self.assertFalse(layer.constraintExpression(1)) + self.assertFalse(layer.constraintExpression(2)) + self.assertEqual(layer.fields().at(0).constraintExpression(), '1+2') + + layer.setConstraintExpression(1, '3+4', 'desc') + self.assertEqual(layer.constraintExpression(0), '1+2') + self.assertEqual(layer.constraintExpression(1), '3+4') + self.assertEqual(layer.constraintDescription(1), 'desc') + self.assertFalse(layer.constraintExpression(2)) + self.assertEqual(layer.fields().at(0).constraintExpression(), '1+2') + self.assertEqual(layer.fields().at(1).constraintExpression(), '3+4') + self.assertEqual(layer.fields().at(1).constraintDescription(), 'desc') + + layer.setConstraintExpression(1, None) + self.assertEqual(layer.constraintExpression(0), '1+2') + self.assertFalse(layer.constraintExpression(1)) + self.assertFalse(layer.constraintExpression(2)) + self.assertEqual(layer.fields().at(0).constraintExpression(), '1+2') + self.assertFalse(layer.fields().at(1).constraintExpression()) + + def testSaveRestoreConstraintExpressions(self): + """ test saving and restoring constraint expressions from xml""" + layer = createLayerWithOnePoint() + + # no constraints + doc = QDomDocument("testdoc") + elem = doc.createElement("maplayer") + self.assertTrue(layer.writeXml(elem, doc)) + + layer2 = createLayerWithOnePoint() + self.assertTrue(layer2.readXml(elem)) + self.assertFalse(layer2.constraintExpression(0)) + self.assertFalse(layer2.constraintExpression(1)) + + # set some constraints + layer.setConstraintExpression(0, '1+2') + layer.setConstraintExpression(1, '3+4', 'desc') + + doc = QDomDocument("testdoc") + elem = doc.createElement("maplayer") + self.assertTrue(layer.writeXml(elem, doc)) + + layer3 = createLayerWithOnePoint() + self.assertTrue(layer3.readXml(elem)) + self.assertEqual(layer3.constraintExpression(0), '1+2') + self.assertEqual(layer3.constraintExpression(1), '3+4') + self.assertEqual(layer3.constraintDescription(1), 'desc') + self.assertEqual(layer3.fields().at(0).constraintExpression(), '1+2') + self.assertEqual(layer3.fields().at(1).constraintExpression(), '3+4') + self.assertEqual(layer3.fields().at(1).constraintDescription(), 'desc') + self.assertEqual(layer3.fields().at(0).constraints(), QgsField.ConstraintExpression) + self.assertEqual(layer3.fields().at(1).constraints(), QgsField.ConstraintExpression) + self.assertEqual(layer3.fields().at(0).constraintOrigin(QgsField.ConstraintExpression), + QgsField.ConstraintOriginLayer) + self.assertEqual(layer3.fields().at(1).constraintOrigin(QgsField.ConstraintExpression), QgsField.ConstraintOriginLayer) def testGetFeatureLimitWithEdits(self): From c98d380dc1ca6e488c72679ec4dd2082d44eb70a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 10:35:07 +1000 Subject: [PATCH 578/897] Move responsibility for testing for attribute against constraints to QgsVectorLayerUtils::validateAttribute() Also clean up some strings shown to the user when a constraint check fails --- python/core/qgsvectorlayerutils.sip | 6 ++ src/core/qgsvectorlayerutils.cpp | 61 ++++++++++++++++ src/core/qgsvectorlayerutils.h | 6 ++ .../core/qgseditorwidgetwrapper.cpp | 65 +++-------------- src/gui/qgsattributeform.cpp | 5 +- tests/src/python/test_qgsvectorlayerutils.py | 70 ++++++++++++++++++- 6 files changed, 155 insertions(+), 58 deletions(-) diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip index 258fbd093ecc..bb6a6558b946 100644 --- a/python/core/qgsvectorlayerutils.sip +++ b/python/core/qgsvectorlayerutils.sip @@ -19,4 +19,10 @@ class QgsVectorLayerUtils */ static bool valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds = QgsFeatureIds() ); + /** + * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. + * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. + */ + static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors /Out/ ); + }; diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index 76b1abdabb2c..506fb36b0e98 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -49,3 +49,64 @@ bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldInd return false; } + +bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors ) +{ + if ( !layer ) + return false; + + if ( attributeIndex < 0 || attributeIndex >= layer->fields().count() ) + return false; + + QgsField field = layer->fields().at( attributeIndex ); + QVariant value = feature.attribute( attributeIndex ); + bool valid = true; + errors.clear(); + + if ( field.constraints() & QgsField::ConstraintExpression && !field.constraintExpression().isEmpty() ) + { + QgsExpressionContext context = layer->createExpressionContext(); + context.setFeature( feature ); + + QgsExpression expr( field.constraintExpression() ); + + valid = expr.evaluate( &context ).toBool(); + + if ( expr.hasParserError() ) + { + errors << QObject::tr( "parser error: %1" ).arg( expr.parserErrorString() ); + } + else if ( expr.hasEvalError() ) + { + errors << QObject::tr( "evaluation error: %1" ).arg( expr.evalErrorString() ); + } + else if ( !valid ) + { + errors << QObject::tr( "%1 check failed" ).arg( field.constraintDescription() ); + } + } + + if ( field.constraints() & QgsField::ConstraintNotNull ) + { + valid = valid && !value.isNull(); + + if ( value.isNull() ) + { + errors << QObject::tr( "value is NULL" ); + } + } + + if ( field.constraints() & QgsField::ConstraintUnique ) + { + bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() ); + valid = valid && !alreadyExists; + + if ( alreadyExists ) + { + errors << QObject::tr( "value is not unique" ); + } + } + + return valid; +} + diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h index 33e2868530d4..5d44538c4a99 100644 --- a/src/core/qgsvectorlayerutils.h +++ b/src/core/qgsvectorlayerutils.h @@ -36,6 +36,12 @@ class CORE_EXPORT QgsVectorLayerUtils */ static bool valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds = QgsFeatureIds() ); + /** + * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. + * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. + */ + static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors ); + }; #endif // QGSVECTORLAYERUTILS_H diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 805a37a37731..bd6050d4d0e1 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -113,61 +113,25 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) QString expression = field.constraintExpression(); QStringList expressions, descriptions; - QVariant value = ft.attribute( mFieldIdx ); - - mConstraintFailureReason.clear(); - - QStringList errors; if ( ! expression.isEmpty() ) { expressions << expression; descriptions << field.constraintDescription(); - - QgsExpressionContext context = layer()->createExpressionContext(); - context.setFeature( ft ); - - QgsExpression expr( expression ); - - mValidConstraint = expr.evaluate( &context ).toBool(); - - if ( expr.hasParserError() ) - { - errors << tr( "Parser error: %1" ).arg( expr.parserErrorString() ); - } - else if ( expr.hasEvalError() ) - { - errors << tr( "Evaluation error: %1" ).arg( expr.evalErrorString() ); - } - else if ( ! mValidConstraint ) - { - errors << tr( "%1 check failed" ).arg( field.constraintDescription() ); - } - toEmit = true; } - else - mValidConstraint = true; if ( field.constraints() & QgsField::ConstraintNotNull ) { - descriptions << QStringLiteral( "NotNull" ); + descriptions << QStringLiteral( "Not NULL" ); if ( !expression.isEmpty() ) { expressions << field.name() + " IS NOT NULL"; } else { - expressions << QStringLiteral( "NotNull" ); + expressions << QStringLiteral( "IS NOT NULL" ); } - - mValidConstraint = mValidConstraint && !value.isNull(); - - if ( value.isNull() ) - { - errors << tr( "Value is NULL" ); - } - toEmit = true; } @@ -180,29 +144,20 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) } else { - expression = QStringLiteral( "Unique" ); - } - - bool alreadyExists = QgsVectorLayerUtils::valueExists( layer(), mFieldIdx, value, QgsFeatureIds() << ft.id() ); - mValidConstraint = mValidConstraint && !alreadyExists; - - if ( alreadyExists ) - { - errors << tr( "Value is not unique" ); + expressions << QStringLiteral( "IS UNIQUE" ); } - toEmit = true; } + QStringList errors; + mValidConstraint = QgsVectorLayerUtils::validateAttribute( layer(), ft, mFieldIdx, errors ); + mConstraintFailureReason = errors.join( ", " ); + if ( toEmit ) { - QString errStr = errors.isEmpty() ? tr( "Constraint checks passed" ) : errors.join( '\n' ); - mConstraintFailureReason = errors.join( ", " ); - QString description; - if ( descriptions.size() > 1 ) - description = "( " + descriptions.join( " ) AND ( " ) + " )"; - else if ( !descriptions.isEmpty() ) - description = descriptions.at( 0 ); + QString errStr = errors.isEmpty() ? tr( "Constraint checks passed" ) : mConstraintFailureReason; + + QString description = descriptions.join( ", " ); QString expressionDesc; if ( expressions.size() > 1 ) expressionDesc = "( " + expressions.join( " ) AND ( " ) + " )"; diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 66c1cf659b04..e4de1ea54ebc 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -901,8 +901,9 @@ void QgsAttributeForm::onConstraintStatusChanged( const QString& constraint, if ( buddy ) { - QString tooltip = tr( "Description: " ) + description + "\n" + - tr( "Raw expression: " ) + constraint + "\n" + tr( "Constraint: " ) + err; + QString tooltip = QStringLiteral( "" ) + tr( "Constraints: " ) + QStringLiteral( "" ) + description + + QStringLiteral( "
                                                                                                                                                                                      " ) + tr( "Raw expression: " ) + QStringLiteral( "" ) + constraint + + QStringLiteral( "
                                                                                                                                                                                      " ) + tr( "Result: " ) + QStringLiteral( "" ) + err; buddy->setToolTip( tooltip ); if ( !buddy->property( "originalText" ).isValid() ) diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py index 1190ce7f5003..1336116b6f03 100644 --- a/tests/src/python/test_qgsvectorlayerutils.py +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -22,7 +22,8 @@ QgsVectorLayerUtils, QgsField, QgsFields, - QgsFeature + QgsFeature, + NULL ) from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -83,6 +84,73 @@ def test_value_exists(self): self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 1, 125, [99999, 3])) self.assertFalse(QgsVectorLayerUtils.valueExists(layer, 1, 125, [2, 4, 5, 3])) + def test_validate_attribute(self): + """ test validating attributes against constraints """ + layer = createLayerWithOnePoint() + + # field expression check + layer.setConstraintExpression(1, 'fldint>5') + + f = QgsFeature(2) + f.setAttributes(["test123", 6]) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + f.setAttributes(["test123", 2]) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertFalse(res) + self.assertEqual(len(errors), 1) + print(errors) + + # bad field expression check + layer.setConstraintExpression(1, 'fldint>') + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertFalse(res) + self.assertEqual(len(errors), 1) + print(errors) + + layer.setConstraintExpression(1, None) + + # not null constraint + f.setAttributes(["test123", NULL]) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + + layer.setFieldConstraints(1, QgsField.ConstraintNotNull) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertFalse(res) + self.assertEqual(len(errors), 1) + print(errors) + + # unique constraint + f.setAttributes(["test123", 123]) + layer.setFieldConstraints(1, QgsField.Constraints()) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + layer.setFieldConstraints(1, QgsField.ConstraintUnique) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertFalse(res) + self.assertEqual(len(errors), 1) + print(errors) + + # check - same id should be ignored when testing for uniqueness + f1 = QgsFeature(1) + f1.setAttributes(["test123", 123]) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f1, 1) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + + # test double constraint failure + layer.setConstraintExpression(1, 'fldint>5') + layer.setFieldConstraints(1, QgsField.ConstraintNotNull) + f.setAttributes(["test123", NULL]) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) + self.assertFalse(res) + self.assertEqual(len(errors), 2) + print(errors) + if __name__ == '__main__': unittest.main() From a6319a47d77bee74fc253b3430d828f2ec6c94c0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 10:59:38 +1000 Subject: [PATCH 579/897] If the layer is NOT being edited then only check layer based constraints and not any constraints enforced by the provider Because: 1. we want to keep browsing features nice and responsive. It's nice to give feedback as to whether the value checks out, but not if it's too slow to do so. Some constraints (eg unique) can be expensive to test. A user can freely remove a layer-based constraint if it proves to be too slow to test, but they are unlikely to have any control over provider-side constraints 2. the provider has already accepted the value, so presumably it doesn't violate the constraint and there's no point rechecking! --- python/core/qgsvectorlayerutils.sip | 4 +- src/core/qgsvectorlayerutils.cpp | 11 +++-- src/core/qgsvectorlayerutils.h | 4 +- .../core/qgseditorwidgetwrapper.cpp | 4 +- .../core/qgseditorwidgetwrapper.h | 4 +- src/gui/qgsattributeform.cpp | 43 +++++++------------ tests/src/python/test_qgsvectorlayerutils.py | 14 ++++++ 7 files changed, 47 insertions(+), 37 deletions(-) diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip index bb6a6558b946..413d755857bd 100644 --- a/python/core/qgsvectorlayerutils.sip +++ b/python/core/qgsvectorlayerutils.sip @@ -22,7 +22,9 @@ class QgsVectorLayerUtils /** * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. + * If the origin parameter is set then only constraints with a matching origin will be checked. */ - static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors /Out/ ); + static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors /Out/, + QgsField::ConstraintOrigin origin = QgsField::ConstraintOriginNotSet ); }; diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index 506fb36b0e98..7c3e80f140c5 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -50,7 +50,7 @@ bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldInd return false; } -bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors ) +bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, QgsField::ConstraintOrigin origin ) { if ( !layer ) return false; @@ -63,7 +63,8 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const bool valid = true; errors.clear(); - if ( field.constraints() & QgsField::ConstraintExpression && !field.constraintExpression().isEmpty() ) + if ( field.constraints() & QgsField::ConstraintExpression && !field.constraintExpression().isEmpty() + && ( origin == QgsField::ConstraintOriginNotSet || origin == field.constraintOrigin( QgsField::ConstraintExpression ) ) ) { QgsExpressionContext context = layer->createExpressionContext(); context.setFeature( feature ); @@ -86,7 +87,8 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const } } - if ( field.constraints() & QgsField::ConstraintNotNull ) + if ( field.constraints() & QgsField::ConstraintNotNull + && ( origin == QgsField::ConstraintOriginNotSet || origin == field.constraintOrigin( QgsField::ConstraintNotNull ) ) ) { valid = valid && !value.isNull(); @@ -96,7 +98,8 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const } } - if ( field.constraints() & QgsField::ConstraintUnique ) + if ( field.constraints() & QgsField::ConstraintUnique + && ( origin == QgsField::ConstraintOriginNotSet || origin == field.constraintOrigin( QgsField::ConstraintUnique ) ) ) { bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() ); valid = valid && !alreadyExists; diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h index 5d44538c4a99..070c34d50353 100644 --- a/src/core/qgsvectorlayerutils.h +++ b/src/core/qgsvectorlayerutils.h @@ -39,8 +39,10 @@ class CORE_EXPORT QgsVectorLayerUtils /** * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. + * If the origin parameter is set then only constraints with a matching origin will be checked. */ - static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors ); + static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, + QgsField::ConstraintOrigin origin = QgsField::ConstraintOriginNotSet ); }; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index bd6050d4d0e1..6c311c2e2610 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -106,7 +106,7 @@ void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid widget()->setStyleSheet( QStringLiteral( "background-color: #dd7777;" ) ); } -void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) +void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsField::ConstraintOrigin constraintOrigin ) { bool toEmit( false ); QgsField field = layer()->fields().at( mFieldIdx ); @@ -150,7 +150,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft ) } QStringList errors; - mValidConstraint = QgsVectorLayerUtils::validateAttribute( layer(), ft, mFieldIdx, errors ); + mValidConstraint = QgsVectorLayerUtils::validateAttribute( layer(), ft, mFieldIdx, errors, constraintOrigin ); mConstraintFailureReason = errors.join( ", " ); if ( toEmit ) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h index c013c31b4ae9..6c1a2d89052f 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h @@ -118,9 +118,11 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper /** * Update constraint. * @param featureContext the feature to use to evaluate the constraint + * @param constraintOrigin optional origin for constraints to check. This can be used to limit the constraints tested + * to only provider or layer based constraints. * @note added in QGIS 2.16 */ - void updateConstraint( const QgsFeature &featureContext ); + void updateConstraint( const QgsFeature &featureContext, QgsField::ConstraintOrigin constraintOrigin = QgsField::ConstraintOriginNotSet ); /** * Get the current constraint status. diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index e4de1ea54ebc..31b4188b3f0f 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -674,30 +674,6 @@ void QgsAttributeForm::onAttributeChanged( const QVariant& value ) break; } - if ( eww->layer()->fields().at( eww->fieldIdx() ).constraints() & QgsField::ConstraintNotNull ) - { - QLabel* buddy = mBuddyMap.value( eww->widget() ); - - if ( buddy ) - { - if ( !buddy->property( "originalText" ).isValid() ) - buddy->setProperty( "originalText", buddy->text() ); - - QString text = buddy->property( "originalText" ).toString(); - - if ( value.isNull() ) - { - // not good - buddy->setText( QStringLiteral( "%1" ).arg( text ) ); - } - else - { - // good - buddy->setText( QStringLiteral( "%1" ).arg( text ) ); - } - } - } - updateConstraints( eww ); // emit @@ -720,14 +696,25 @@ void QgsAttributeForm::updateConstraints( QgsEditorWidgetWrapper *eww ) QgsFeature ft; if ( currentFormFeature( ft ) ) { + // if the layer is NOT being edited then we only check layer based constraints, and not + // any constraints enforced by the provider. Because: + // 1. we want to keep browsing features nice and responsive. It's nice to give feedback as to whether + // the value checks out, but not if it's too slow to do so. Some constraints (eg unique) can be + // expensive to test. A user can freely remove a layer-based constraint if it proves to be too slow + // to test, but they are unlikely to have any control over provider-side constraints + // 2. the provider has already accepted the value, so presumably it doesn't violate the constraint + // and there's no point rechecking! + QgsField::ConstraintOrigin constraintOrigin = mLayer->isEditable() ? QgsField::ConstraintOriginNotSet + : QgsField::ConstraintOriginLayer; + // update eww constraint - eww->updateConstraint( ft ); + eww->updateConstraint( ft, constraintOrigin ); // update eww dependencies constraint QList deps = constraintDependencies( eww ); Q_FOREACH ( QgsEditorWidgetWrapper* depsEww, deps ) - depsEww->updateConstraint( ft ); + depsEww->updateConstraint( ft, constraintOrigin ); // sync ok button status synchronizeEnabledState(); @@ -914,12 +901,12 @@ void QgsAttributeForm::onConstraintStatusChanged( const QString& constraint, if ( !ok ) { // not good - buddy->setText( QStringLiteral( "%1*" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1" ).arg( text ) ); } else { // good - buddy->setText( QStringLiteral( "%1*" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1" ).arg( text ) ); } } } diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py index 1336116b6f03..bc170e3c6051 100644 --- a/tests/src/python/test_qgsvectorlayerutils.py +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -101,6 +101,10 @@ def test_validate_attribute(self): self.assertFalse(res) self.assertEqual(len(errors), 1) print(errors) + # checking only for provider constraints + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsField.ConstraintOriginProvider) + self.assertTrue(res) + self.assertEqual(len(errors), 0) # bad field expression check layer.setConstraintExpression(1, 'fldint>') @@ -123,6 +127,11 @@ def test_validate_attribute(self): self.assertEqual(len(errors), 1) print(errors) + # checking only for provider constraints + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsField.ConstraintOriginProvider) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + # unique constraint f.setAttributes(["test123", 123]) layer.setFieldConstraints(1, QgsField.Constraints()) @@ -135,6 +144,11 @@ def test_validate_attribute(self): self.assertEqual(len(errors), 1) print(errors) + # checking only for provider constraints + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsField.ConstraintOriginProvider) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + # check - same id should be ignored when testing for uniqueness f1 = QgsFeature(1) f1.setAttributes(["test123", 123]) From 961b63f292de449dc638d1b5ec0fd16b28811c1c Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 11:11:14 +1000 Subject: [PATCH 580/897] Update API break docs --- doc/api_break.dox | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index c153211f7435..22b66567c6de 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -736,10 +736,9 @@ QgsEditFormConfig {#qgis_api_break_3_0_QgsEditFormConfig} - widgetType() and widgetConfig() now reflect only the user configured values. QgsEditorWidgetRegistry::instance()->findBest() must be used instead. - widgetType(), widgetConfig(), setWidgetType(), setWidgetConfig() and removeWidgetConfig() now only take a string as first parameter. Access by index has been removed. -- expression() has been renamed to constraintExpression() -- setExpression() has been renamed to setConstraintExpression() -- expressionDescription() has been renamed to constraintDescription() -- setExpressionDesctiption() has been renamed to setConstraintDescription() +- expression(), setExpression(), expressionDescription() and setExpressionDescription() +have been removed. Use QgsVectorLayer.setConstraintExpression()/constraintExpression(), +or QgsField.constraintExpression()/QgsField.constraintDescription() instead. - notNull() and setNotNull() have been removed. Use QgsVectorLayer.setFieldConstraints()/fieldConstraints(), or QgsField.constraints() instead. QgsExpression {#qgis_api_break_3_0_QgsExpression} From 210c98bedcf0c83ae5e99a7bb7059fbcaa571743 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 26 Oct 2016 15:52:20 +1000 Subject: [PATCH 581/897] Fix failing unit test --- tests/src/gui/testqgsattributeform.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/src/gui/testqgsattributeform.cpp b/tests/src/gui/testqgsattributeform.cpp index d8d4e93d4cc0..2dd008c780bc 100644 --- a/tests/src/gui/testqgsattributeform.cpp +++ b/tests/src/gui/testqgsattributeform.cpp @@ -78,8 +78,8 @@ void TestQgsAttributeForm::testFieldConstraint() form.setFeature( ft ); // testing stuff - QString validLabel = QStringLiteral( "col0*" ); - QString invalidLabel = QStringLiteral( "col0*" ); + QString validLabel = QStringLiteral( "col0" ); + QString invalidLabel = QStringLiteral( "col0" ); // set constraint layer->setConstraintExpression( 0, QString() ); @@ -144,8 +144,8 @@ void TestQgsAttributeForm::testFieldMultiConstraints() // testing stuff QSignalSpy spy( &form, SIGNAL( attributeChanged( QString, QVariant ) ) ); - QString val = QStringLiteral( "*" ); - QString inv = QStringLiteral( "*" ); + QString val = QStringLiteral( "" ); + QString inv = QStringLiteral( "" ); // get wrappers for each widget QgsEditorWidgetWrapper *ww0, *ww1, *ww2, *ww3; From bb6fc32eec3bc5576ee0810f5e6b38f5f66a2270 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 16:25:17 +1000 Subject: [PATCH 582/897] [FEATURE] Not null constraint detection for ogr provider Implements not null constraint detection for the OGR layers, where supported for the data format by OGR. (only available for GDAL >= 2.0) --- src/providers/ogr/qgsogrprovider.cpp | 27 ++++++++++------ tests/src/python/test_provider_ogr_sqlite.py | 33 +++++++++++++++++++- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index d2c30a2a5042..56eecf9795b3 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -927,18 +927,27 @@ void QgsOgrProvider::loadFields() if ( prec > 0 ) width -= 1; - mAttributeFields.append( - QgsField( - name, - varType, + QgsField newField = QgsField( + name, + varType, #ifdef ANDROID - OGR_GetFieldTypeName( ogrType ), + OGR_GetFieldTypeName( ogrType ), #else - textEncoding()->toUnicode( OGR_GetFieldTypeName( ogrType ) ), + textEncoding()->toUnicode( OGR_GetFieldTypeName( ogrType ) ), #endif - width, prec - ) - ); + width, prec + ); + +#if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,0) + // check if field is nullable + bool nullable = OGR_Fld_IsNullable( fldDef ); + if ( !nullable ) + { + newField.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + } +#endif + + mAttributeFields.append( newField ); } } } diff --git a/tests/src/python/test_provider_ogr_sqlite.py b/tests/src/python/test_provider_ogr_sqlite.py index 582ba4b85fab..fc20dfed6d65 100644 --- a/tests/src/python/test_provider_ogr_sqlite.py +++ b/tests/src/python/test_provider_ogr_sqlite.py @@ -20,7 +20,7 @@ import glob from osgeo import gdal, ogr -from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest +from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest, QgsField from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -129,6 +129,37 @@ def testFidSupport(self): got = [(f.attribute('fid'), f.attribute('intfield')) for f in vl.dataProvider().getFeatures(QgsFeatureRequest().setFilterExpression("fid = 12"))] self.assertEqual(got, [(12, 123)]) + @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 0)) + def testNotNullConstraint(self): + """ test detection of not null constraint on OGR layer """ + + tmpfile = os.path.join(self.basetestpath, 'testNotNullConstraint.sqlite') + ds = ogr.GetDriverByName('SQLite').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, options=['FID=fid']) + lyr.CreateField(ogr.FieldDefn('field1', ogr.OFTInteger)) + fld2 = ogr.FieldDefn('field2', ogr.OFTInteger) + fld2.SetNullable(False) + lyr.CreateField(fld2) + ds = None + + vl = QgsVectorLayer('{}'.format(tmpfile), 'test', 'ogr') + self.assertTrue(vl.isValid()) + + # test some bad indexes + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + + self.assertFalse(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintNotNull) + + # test that constraints have been saved to fields correctly + fields = vl.fields() + self.assertFalse(fields.at(0).constraints() & QgsField.ConstraintNotNull) + self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintNotNull) + self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) + if __name__ == '__main__': unittest.main() From 003fe1830cdb7ee45a9b47586871da47439c6ca1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 16:29:40 +1000 Subject: [PATCH 583/897] Color a few pixels slightly differently --- src/gui/qgsattributeform.cpp | 2 +- tests/src/gui/testqgsattributeform.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 31b4188b3f0f..57910adaaf4f 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -901,7 +901,7 @@ void QgsAttributeForm::onConstraintStatusChanged( const QString& constraint, if ( !ok ) { // not good - buddy->setText( QStringLiteral( "%1" ).arg( text ) ); + buddy->setText( QStringLiteral( "%1" ).arg( text ) ); } else { diff --git a/tests/src/gui/testqgsattributeform.cpp b/tests/src/gui/testqgsattributeform.cpp index 2dd008c780bc..c8f07ada49d6 100644 --- a/tests/src/gui/testqgsattributeform.cpp +++ b/tests/src/gui/testqgsattributeform.cpp @@ -79,7 +79,7 @@ void TestQgsAttributeForm::testFieldConstraint() // testing stuff QString validLabel = QStringLiteral( "col0" ); - QString invalidLabel = QStringLiteral( "col0" ); + QString invalidLabel = QStringLiteral( "col0" ); // set constraint layer->setConstraintExpression( 0, QString() ); @@ -145,7 +145,7 @@ void TestQgsAttributeForm::testFieldMultiConstraints() // testing stuff QSignalSpy spy( &form, SIGNAL( attributeChanged( QString, QVariant ) ) ); QString val = QStringLiteral( "" ); - QString inv = QStringLiteral( "" ); + QString inv = QStringLiteral( "" ); // get wrappers for each widget QgsEditorWidgetWrapper *ww0, *ww1, *ww2, *ww3; From cb94b68d88a6c721c1c81596019265805949dda9 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 18:41:22 +1000 Subject: [PATCH 584/897] Move constraint handling to QgsFieldConstraints Avoids cluttering QgsField API --- python/core/core.sip | 1 + python/core/qgsfield.sip | 77 +--------- python/core/qgsfieldconstraints.sip | 110 +++++++++++++ python/core/qgsvectordataprovider.sip | 2 +- python/core/qgsvectorlayer.sip | 4 +- python/core/qgsvectorlayerutils.sip | 2 +- src/app/qgsattributetypedialog.cpp | 6 +- src/app/qgsattributetypedialog.h | 2 +- src/app/qgsfieldsproperties.cpp | 36 +++-- src/app/qgsfieldsproperties.h | 2 +- src/core/CMakeLists.txt | 2 + src/core/qgsfield.cpp | 88 +++-------- src/core/qgsfield.h | 81 +--------- src/core/qgsfield_p.h | 23 +-- src/core/qgsfieldconstraints.cpp | 69 +++++++++ src/core/qgsfieldconstraints.h | 145 ++++++++++++++++++ src/core/qgsvectordataprovider.cpp | 4 +- src/core/qgsvectordataprovider.h | 2 +- src/core/qgsvectorlayer.cpp | 43 +++--- src/core/qgsvectorlayer.h | 6 +- src/core/qgsvectorlayerutils.cpp | 20 +-- src/core/qgsvectorlayerutils.h | 2 +- .../core/qgseditorwidgetregistry.cpp | 2 +- .../core/qgseditorwidgetwrapper.cpp | 10 +- .../core/qgseditorwidgetwrapper.h | 2 +- src/gui/qgsattributeform.cpp | 6 +- src/providers/ogr/qgsogrprovider.cpp | 4 +- .../postgres/qgspostgresprovider.cpp | 6 +- .../spatialite/qgsspatialiteprovider.cpp | 6 +- tests/src/core/testqgsfield.cpp | 92 +++++++---- tests/src/python/test_provider_ogr_sqlite.py | 20 +-- tests/src/python/test_provider_postgres.py | 67 ++++---- tests/src/python/test_provider_spatialite.py | 62 ++++---- tests/src/python/test_qgsvectorlayer.py | 105 ++++++------- tests/src/python/test_qgsvectorlayerutils.py | 15 +- 35 files changed, 651 insertions(+), 473 deletions(-) create mode 100644 python/core/qgsfieldconstraints.sip create mode 100644 src/core/qgsfieldconstraints.cpp create mode 100644 src/core/qgsfieldconstraints.h diff --git a/python/core/core.sip b/python/core/core.sip index 8693f7990808..6adeeb3dff1d 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -56,6 +56,7 @@ %Include qgsfeaturerequest.sip %Include qgsfeedback.sip %Include qgsfield.sip +%Include qgsfieldconstraints.sip %Include qgsfields.sip %Include qgsgeometrysimplifier.sip %Include qgsgeometryvalidator.sip diff --git a/python/core/qgsfield.sip b/python/core/qgsfield.sip index 9fb8c0af059c..564860805ed4 100644 --- a/python/core/qgsfield.sip +++ b/python/core/qgsfield.sip @@ -15,29 +15,6 @@ class QgsField public: - /** - * Constraints which may be present on a field. - * @note added in QGIS 3.0 - */ - enum Constraint - { - ConstraintNotNull, //!< Field may not be null - ConstraintUnique, //!< Field must have a unique value - ConstraintExpression, //!< Field has an expression constraint set. See constraintExpression(). - }; - typedef QFlags Constraints; - - /** - * Origin of constraints. - * @note added in QGIS 3.0 - */ - enum ConstraintOrigin - { - ConstraintOriginNotSet, //!< Constraint is not set - ConstraintOriginProvider, //!< Constraint was set at data provider - ConstraintOriginLayer, //!< Constraint was set by layer - }; - /** Constructor. Constructs a new QgsField object. * @param name Field name * @param type Field variant type, currently supported: String / Int / Double @@ -187,63 +164,18 @@ class QgsField void setDefaultValueExpression( const QString& expression ); /** - * Returns any constraints which are present for the field. + * Returns constraints which are present for the field. * @note added in QGIS 3.0 * @see setConstraints() - * @see constraintOrigin() - */ - Constraints constraints() const; - - /** - * Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint - * is not present on this field. - * @note added in QGIS 3.0 - * @see constraints() - */ - ConstraintOrigin constraintOrigin( Constraint constraint ) const; - - /** - * Sets a constraint on the field. - * @note added in QGIS 3.0 - * @see constraints() - * @see removeConstraint() - */ - void setConstraint( Constraint constraint, ConstraintOrigin origin = ConstraintOriginLayer ); - - /** - * Removes a constraint from the field. - * @see setConstraint() - * @see constraints() - */ - void removeConstraint( Constraint constraint ); - - /** - * Returns the constraint expression for the field, if set. - * @note added in QGIS 3.0 - * @see constraints() - * @see constraintDescription() - * @see setConstraintExpression() - */ - QString constraintExpression() const; - - /** - * Returns the descriptive name for the constraint expression. - * @note added in QGIS 3.0 - * @see constraints() - * @see constraintExpression() - * @see setConstraintExpression() */ - QString constraintDescription() const; + const QgsFieldConstraints& constraints() const; /** - * Set the constraint expression for the field. An optional descriptive name for the constraint - * can also be set. Setting an empty expression will clear any existing expression constraint. + * Sets constraints which are present for the field. * @note added in QGIS 3.0 - * @see constraintExpression() - * @see constraintDescription() * @see constraints() */ - void setConstraintExpression( const QString& expression, const QString& description = QString() ); + void setConstraints( const QgsFieldConstraints& constraints ); /** Returns the alias for the field (the friendly displayed name of the field ), * or an empty string if there is no alias. @@ -338,4 +270,3 @@ class QgsField const QgsEditorWidgetSetup& editorWidgetSetup() const; }; // class QgsField -QFlags operator|(QgsField::Constraint f1, QFlags f2); diff --git a/python/core/qgsfieldconstraints.sip b/python/core/qgsfieldconstraints.sip new file mode 100644 index 000000000000..965f71ac9dda --- /dev/null +++ b/python/core/qgsfieldconstraints.sip @@ -0,0 +1,110 @@ +/** + * \class QgsFieldConstraints + * \ingroup core + * Stores information about constraints which may be present on a field. + * \note added in QGIS 3.0 + */ + + +class QgsFieldConstraints +{ + +%TypeHeaderCode +#include +%End + + public: + + /** + * Constraints which may be present on a field. + */ + enum Constraint + { + ConstraintNotNull, //!< Field may not be null + ConstraintUnique, //!< Field must have a unique value + ConstraintExpression, //!< Field has an expression constraint set. See constraintExpression(). + }; + typedef QFlags Constraints; + + /** + * Origin of constraints. + */ + enum ConstraintOrigin + { + ConstraintOriginNotSet, //!< Constraint is not set + ConstraintOriginProvider, //!< Constraint was set at data provider + ConstraintOriginLayer, //!< Constraint was set by layer + }; + + /** + * Strength of constraints. + */ + enum ConstraintStrength + { + ConstraintHard, //!< Constraint must be honored before feature can be accepted + ConstraintSoft, //!< User is warned if constraint is violated but feature can still be accepted + }; + + /** + * Constructor for QgsFieldConstraints. + */ + QgsFieldConstraints(); + + /** + * Returns any constraints which are present for the field. + * @see setConstraints() + * @see constraintOrigin() + */ + Constraints constraints() const; + + /** + * Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint + * is not present on this field. + * @see constraints() + */ + ConstraintOrigin constraintOrigin( Constraint constraint ) const; + + /** + * Sets a constraint on the field. + * @see constraints() + * @see removeConstraint() + */ + void setConstraint( Constraint constraint, ConstraintOrigin origin = ConstraintOriginLayer ); + + /** + * Removes a constraint from the field. + * @see setConstraint() + * @see constraints() + */ + void removeConstraint( Constraint constraint ); + + /** + * Returns the constraint expression for the field, if set. + * @see constraints() + * @see constraintDescription() + * @see setConstraintExpression() + */ + QString constraintExpression() const; + + /** + * Returns the descriptive name for the constraint expression. + * @see constraints() + * @see constraintExpression() + * @see setConstraintExpression() + */ + QString constraintDescription() const; + + /** + * Set the constraint expression for the field. An optional descriptive name for the constraint + * can also be set. Setting an empty expression will clear any existing expression constraint. + * @see constraintExpression() + * @see constraintDescription() + * @see constraints() + */ + void setConstraintExpression( const QString& expression, const QString& description = QString() ); + + bool operator==( const QgsFieldConstraints& other ) const; + +}; + +QFlags operator|(QgsFieldConstraints::Constraint f1, QFlags f2); diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 8cf11d788c83..ebbe6dccb5b7 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -235,7 +235,7 @@ class QgsVectorDataProvider : QgsDataProvider * field index. * @note added in QGIS 3.0 */ - QgsField::Constraints fieldConstraints( int fieldIndex ) const; + QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; /** * Changes geometries of existing features diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index c48d5b42134f..bf8754dcf507 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1264,7 +1264,7 @@ class QgsVectorLayer : QgsMapLayer * @note added in QGIS 3.0 * @see setFieldConstraints() */ - QgsField::Constraints fieldConstraints( int fieldIndex ) const; + QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; /** * Sets the constraints for a specified field index. Any constraints inherited from the layer's @@ -1273,7 +1273,7 @@ class QgsVectorLayer : QgsMapLayer * @note added in QGIS 3.0 * @see fieldConstraints() */ - void setFieldConstraints( int index, QgsField::Constraints constraints ); + void setFieldConstraints( int index, QgsFieldConstraints::Constraints constraints ); /** * Returns the constraint expression for for a specified field index, if set. diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip index 413d755857bd..4d897f64edfa 100644 --- a/python/core/qgsvectorlayerutils.sip +++ b/python/core/qgsvectorlayerutils.sip @@ -25,6 +25,6 @@ class QgsVectorLayerUtils * If the origin parameter is set then only constraints with a matching origin will be checked. */ static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors /Out/, - QgsField::ConstraintOrigin origin = QgsField::ConstraintOriginNotSet ); + QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); }; diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 4d40b199af3d..2857787850de 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -176,16 +176,16 @@ bool QgsAttributeTypeDialog::fieldEditable() const return isFieldEditableCheckBox->isChecked(); } -void QgsAttributeTypeDialog::setProviderConstraints( QgsField::Constraints constraints ) +void QgsAttributeTypeDialog::setProviderConstraints( QgsFieldConstraints::Constraints constraints ) { - if ( constraints & QgsField::ConstraintNotNull ) + if ( constraints & QgsFieldConstraints::ConstraintNotNull ) { notNullCheckBox->setChecked( true ); notNullCheckBox->setEnabled( false ); notNullCheckBox->setToolTip( tr( "The provider for this layer has a NOT NULL constraint set on the field." ) ); } - if ( constraints & QgsField::ConstraintUnique ) + if ( constraints & QgsFieldConstraints::ConstraintUnique ) { mUniqueCheckBox->setChecked( true ); mUniqueCheckBox->setEnabled( false ); diff --git a/src/app/qgsattributetypedialog.h b/src/app/qgsattributetypedialog.h index 73995032f30e..5a8ecce5bb93 100644 --- a/src/app/qgsattributetypedialog.h +++ b/src/app/qgsattributetypedialog.h @@ -73,7 +73,7 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut /** * Sets any provider side constraints which may affect this field's behaviour. */ - void setProviderConstraints( QgsField::Constraints constraints ); + void setProviderConstraints( QgsFieldConstraints::Constraints constraints ); /** * Setter for checkbox for not null diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index d9732867775d..9ddfc4c370df 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -558,16 +558,17 @@ void QgsFieldsProperties::attributeTypeDialog() attributeTypeDialog.setFieldEditable( cfg.mEditable ); attributeTypeDialog.setLabelOnTop( cfg.mLabelOnTop ); - attributeTypeDialog.setNotNull( cfg.mConstraints & QgsField::ConstraintNotNull ); - attributeTypeDialog.setUnique( cfg.mConstraints & QgsField::ConstraintUnique ); - - QgsField::Constraints providerConstraints = 0; - if ( mLayer->fields().at( index ).constraintOrigin( QgsField::ConstraintNotNull ) == QgsField::ConstraintOriginProvider ) - providerConstraints |= QgsField::ConstraintNotNull; - if ( mLayer->fields().at( index ).constraintOrigin( QgsField::ConstraintUnique ) == QgsField::ConstraintOriginProvider ) - providerConstraints |= QgsField::ConstraintUnique; - if ( mLayer->fields().at( index ).constraintOrigin( QgsField::ConstraintExpression ) == QgsField::ConstraintOriginProvider ) - providerConstraints |= QgsField::ConstraintExpression; + attributeTypeDialog.setNotNull( cfg.mConstraints & QgsFieldConstraints::ConstraintNotNull ); + attributeTypeDialog.setUnique( cfg.mConstraints & QgsFieldConstraints::ConstraintUnique ); + + QgsFieldConstraints constraints = mLayer->fields().at( index ).constraints(); + QgsFieldConstraints::Constraints providerConstraints = 0; + if ( constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) == QgsFieldConstraints::ConstraintOriginProvider ) + providerConstraints |= QgsFieldConstraints::ConstraintNotNull; + if ( constraints.constraintOrigin( QgsFieldConstraints::ConstraintUnique ) == QgsFieldConstraints::ConstraintOriginProvider ) + providerConstraints |= QgsFieldConstraints::ConstraintUnique; + if ( constraints.constraintOrigin( QgsFieldConstraints::ConstraintExpression ) == QgsFieldConstraints::ConstraintOriginProvider ) + providerConstraints |= QgsFieldConstraints::ConstraintExpression; attributeTypeDialog.setProviderConstraints( providerConstraints ); attributeTypeDialog.setConstraintExpression( cfg.mConstraint ); @@ -584,13 +585,13 @@ void QgsFieldsProperties::attributeTypeDialog() cfg.mLabelOnTop = attributeTypeDialog.labelOnTop(); cfg.mConstraints = 0; - if ( attributeTypeDialog.notNull() && !( providerConstraints & QgsField::ConstraintNotNull ) ) + if ( attributeTypeDialog.notNull() && !( providerConstraints & QgsFieldConstraints::ConstraintNotNull ) ) { - cfg.mConstraints |= QgsField::ConstraintNotNull; + cfg.mConstraints |= QgsFieldConstraints::ConstraintNotNull; } - if ( attributeTypeDialog.unique() && !( providerConstraints & QgsField::ConstraintUnique ) ) + if ( attributeTypeDialog.unique() && !( providerConstraints & QgsFieldConstraints::ConstraintUnique ) ) { - cfg.mConstraints |= QgsField::ConstraintUnique; + cfg.mConstraints |= QgsFieldConstraints::ConstraintUnique; } cfg.mConstraintDescription = attributeTypeDialog.constraintExpressionDescription(); @@ -1060,9 +1061,10 @@ QgsFieldsProperties::FieldConfig::FieldConfig( QgsVectorLayer* layer, int idx ) mEditableEnabled = layer->fields().fieldOrigin( idx ) != QgsFields::OriginJoin && layer->fields().fieldOrigin( idx ) != QgsFields::OriginExpression; mLabelOnTop = layer->editFormConfig().labelOnTop( idx ); - mConstraints = layer->fields().at( idx ).constraints(); - mConstraint = layer->fields().at( idx ).constraintExpression(); - mConstraintDescription = layer->fields().at( idx ).constraintDescription(); + QgsFieldConstraints constraints = layer->fields().at( idx ).constraints(); + mConstraints = constraints.constraints(); + mConstraint = constraints.constraintExpression(); + mConstraintDescription = constraints.constraintDescription(); const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( layer, layer->fields().field( idx ).name() ); mEditorWidgetType = setup.type(); mEditorWidgetConfig = setup.config(); diff --git a/src/app/qgsfieldsproperties.h b/src/app/qgsfieldsproperties.h index c830939ae8de..ac1f96dd7404 100644 --- a/src/app/qgsfieldsproperties.h +++ b/src/app/qgsfieldsproperties.h @@ -122,7 +122,7 @@ class APP_EXPORT QgsFieldsProperties : public QWidget, private Ui_QgsFieldsPrope bool mEditable; bool mEditableEnabled; bool mLabelOnTop; - QgsField::Constraints mConstraints; + QgsFieldConstraints::Constraints mConstraints; QString mConstraint; QString mConstraintDescription; QPushButton* mButton; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 4a715e4c6cc3..803bbc6dd2a4 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -123,6 +123,7 @@ SET(QGIS_CORE_SRCS qgsfeaturerequest.cpp qgsfeaturestore.cpp qgsfield.cpp + qgsfieldconstraints.cpp qgsfields.cpp qgsfontutils.cpp qgsgeometrycache.cpp @@ -459,6 +460,7 @@ SET(QGIS_CORE_MOC_HDRS qgsfeature.h qgsfeedback.h qgsfield.h + qgsfieldconstraints.h qgsgeometryvalidator.h qgsgml.h qgsgmlschema.h diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index 428f5e050e7a..3203d11b6ec9 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -180,60 +180,14 @@ void QgsField::setDefaultValueExpression( const QString& expression ) d->defaultValueExpression = expression; } -QgsField::Constraints QgsField::constraints() const +void QgsField::setConstraints( const QgsFieldConstraints& constraints ) { - return d->constraints; -} - -QgsField::ConstraintOrigin QgsField::constraintOrigin( QgsField::Constraint constraint ) const -{ - if ( !( d->constraints & constraint ) ) - return ConstraintOriginNotSet; - - return d->constraintOrigins.value( constraint, ConstraintOriginNotSet ); -} - -void QgsField::setConstraint( QgsField::Constraint constraint, QgsField::ConstraintOrigin origin ) -{ - if ( origin == ConstraintOriginNotSet ) - { - d->constraints &= ~constraint; - d->constraintOrigins.remove( constraint ); - } - else - { - d->constraints |= constraint; - d->constraintOrigins.insert( constraint, origin ); - } + d->constraints = constraints; } -void QgsField::removeConstraint( QgsField::Constraint constraint ) +const QgsFieldConstraints& QgsField::constraints() const { - d->constraints &= ~constraint; -} - -QString QgsField::constraintExpression() const -{ - return d->constraints & QgsField::ConstraintExpression ? d->expressionConstraint : QString(); -} - -QString QgsField::constraintDescription() const -{ - return d->expressionConstraintDescription; -} - -void QgsField::setConstraintExpression( const QString& expression, const QString& description ) -{ - if ( expression.isEmpty() ) - d->constraints &= ~QgsField::ConstraintExpression; - else - { - d->constraints |= QgsField::ConstraintExpression; - d->constraintOrigins.insert( QgsField::ConstraintExpression, QgsField::ConstraintOriginLayer ); - } - - d->expressionConstraint = expression; - d->expressionConstraintDescription = description; + return d->constraints; } QString QgsField::alias() const @@ -359,12 +313,12 @@ QDataStream& operator<<( QDataStream& out, const QgsField& field ) out << field.comment(); out << field.alias(); out << field.defaultValueExpression(); - out << field.constraints(); - out << static_cast< quint32 >( field.constraintOrigin( QgsField::ConstraintNotNull ) ); - out << static_cast< quint32 >( field.constraintOrigin( QgsField::ConstraintUnique ) ); - out << static_cast< quint32 >( field.constraintOrigin( QgsField::ConstraintExpression ) ); - out << field.constraintExpression(); - out << field.constraintDescription(); + out << field.constraints().constraints(); + out << static_cast< quint32 >( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) ); + out << static_cast< quint32 >( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintUnique ) ); + out << static_cast< quint32 >( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintExpression ) ); + out << field.constraints().constraintExpression(); + out << field.constraints().constraintDescription(); out << static_cast< quint32 >( field.subType() ); return out; } @@ -384,19 +338,21 @@ QDataStream& operator>>( QDataStream& in, QgsField& field ) field.setComment( comment ); field.setAlias( alias ); field.setDefaultValueExpression( defaultValueExpression ); - if ( constraints & QgsField::ConstraintNotNull ) - field.setConstraint( QgsField::ConstraintNotNull, static_cast< QgsField::ConstraintOrigin>( originNotNull ) ); + QgsFieldConstraints fieldConstraints; + if ( constraints & QgsFieldConstraints::ConstraintNotNull ) + fieldConstraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, static_cast< QgsFieldConstraints::ConstraintOrigin>( originNotNull ) ); else - field.removeConstraint( QgsField::ConstraintNotNull ); - if ( constraints & QgsField::ConstraintUnique ) - field.setConstraint( QgsField::ConstraintUnique, static_cast< QgsField::ConstraintOrigin>( originUnique ) ); + fieldConstraints.removeConstraint( QgsFieldConstraints::ConstraintNotNull ); + if ( constraints & QgsFieldConstraints::ConstraintUnique ) + fieldConstraints.setConstraint( QgsFieldConstraints::ConstraintUnique, static_cast< QgsFieldConstraints::ConstraintOrigin>( originUnique ) ); else - field.removeConstraint( QgsField::ConstraintUnique ); - if ( constraints & QgsField::ConstraintExpression ) - field.setConstraint( QgsField::ConstraintExpression, static_cast< QgsField::ConstraintOrigin>( originExpression ) ); + fieldConstraints.removeConstraint( QgsFieldConstraints::ConstraintUnique ); + if ( constraints & QgsFieldConstraints::ConstraintExpression ) + fieldConstraints.setConstraint( QgsFieldConstraints::ConstraintExpression, static_cast< QgsFieldConstraints::ConstraintOrigin>( originExpression ) ); else - field.removeConstraint( QgsField::ConstraintExpression ); - field.setConstraintExpression( constraintExpression, constraintDescription ); + fieldConstraints.removeConstraint( QgsFieldConstraints::ConstraintExpression ); + fieldConstraints.setConstraintExpression( constraintExpression, constraintDescription ); + field.setConstraints( fieldConstraints ); field.setSubType( static_cast< QVariant::Type >( subType ) ); return in; } diff --git a/src/core/qgsfield.h b/src/core/qgsfield.h index fcb1d21f02dd..4897b47090a4 100644 --- a/src/core/qgsfield.h +++ b/src/core/qgsfield.h @@ -34,6 +34,7 @@ class QgsFieldsPrivate; ****************************************************************************/ #include "qgseditorwidgetsetup.h" +#include "qgsfieldconstraints.h" /** \class QgsField * \ingroup core @@ -54,33 +55,10 @@ class CORE_EXPORT QgsField Q_PROPERTY( QString name READ name WRITE setName ) Q_PROPERTY( QString alias READ alias WRITE setAlias ) Q_PROPERTY( QString defaultValueExpression READ defaultValueExpression WRITE setDefaultValueExpression ) - Q_PROPERTY( Constraints constraints READ constraints ) + Q_PROPERTY( QgsFieldConstraints constraints READ constraints WRITE setConstraints ) public: - /** - * Constraints which may be present on a field. - * @note added in QGIS 3.0 - */ - enum Constraint - { - ConstraintNotNull = 1, //!< Field may not be null - ConstraintUnique = 1 << 1, //!< Field must have a unique value - ConstraintExpression = 1 << 2, //!< Field has an expression constraint set. See constraintExpression(). - }; - Q_DECLARE_FLAGS( Constraints, Constraint ) - - /** - * Origin of constraints. - * @note added in QGIS 3.0 - */ - enum ConstraintOrigin - { - ConstraintOriginNotSet = 0, //!< Constraint is not set - ConstraintOriginProvider, //!< Constraint was set at data provider - ConstraintOriginLayer, //!< Constraint was set by layer - }; - /** Constructor. Constructs a new QgsField object. * @param name Field name * @param type Field variant type, currently supported: String / Int / Double @@ -234,63 +212,18 @@ class CORE_EXPORT QgsField void setDefaultValueExpression( const QString& expression ); /** - * Returns any constraints which are present for the field. + * Returns constraints which are present for the field. * @note added in QGIS 3.0 * @see setConstraints() - * @see constraintOrigin() */ - Constraints constraints() const; + const QgsFieldConstraints& constraints() const; /** - * Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint - * is not present on this field. + * Sets constraints which are present for the field. * @note added in QGIS 3.0 * @see constraints() */ - ConstraintOrigin constraintOrigin( Constraint constraint ) const; - - /** - * Sets a constraint on the field. - * @note added in QGIS 3.0 - * @see constraints() - * @see removeConstraint() - */ - void setConstraint( Constraint constraint, ConstraintOrigin origin = ConstraintOriginLayer ); - - /** - * Removes a constraint from the field. - * @see setConstraint() - * @see constraints() - */ - void removeConstraint( Constraint constraint ); - - /** - * Returns the constraint expression for the field, if set. - * @note added in QGIS 3.0 - * @see constraints() - * @see constraintDescription() - * @see setConstraintExpression() - */ - QString constraintExpression() const; - - /** - * Returns the descriptive name for the constraint expression. - * @note added in QGIS 3.0 - * @see constraints() - * @see constraintExpression() - * @see setConstraintExpression() - */ - QString constraintDescription() const; - - /** - * Set the constraint expression for the field. An optional descriptive name for the constraint - * can also be set. Setting an empty expression will clear any existing expression constraint. - * @note added in QGIS 3.0 - * @see constraintExpression() - * @see constraintDescription() - * @see constraints() - */ - void setConstraintExpression( const QString& expression, const QString& description = QString() ); + void setConstraints( const QgsFieldConstraints& constraints ); /** Returns the alias for the field (the friendly displayed name of the field ), * or an empty string if there is no alias. @@ -345,8 +278,6 @@ class CORE_EXPORT QgsField }; // class QgsField -Q_DECLARE_OPERATORS_FOR_FLAGS( QgsField::Constraints ) - Q_DECLARE_METATYPE( QgsField ) //! Writes the field to stream out. QGIS version compatibility is not guaranteed. diff --git a/src/core/qgsfield_p.h b/src/core/qgsfield_p.h index 27a2fc6b0718..1f56e0bf9d64 100644 --- a/src/core/qgsfield_p.h +++ b/src/core/qgsfield_p.h @@ -27,6 +27,7 @@ // version without notice, or even be removed. // +#include "qgsfieldconstraints.h" #include #include #include @@ -55,7 +56,6 @@ class QgsFieldPrivate : public QSharedData , length( len ) , precision( prec ) , comment( comment ) - , constraints( 0 ) { } @@ -71,9 +71,6 @@ class QgsFieldPrivate : public QSharedData , alias( other.alias ) , defaultValueExpression( other.defaultValueExpression ) , constraints( other.constraints ) - , constraintOrigins( other.constraintOrigins ) - , expressionConstraint( other.expressionConstraint ) - , expressionConstraintDescription( other.expressionConstraintDescription ) { } @@ -84,10 +81,7 @@ class QgsFieldPrivate : public QSharedData return (( name == other.name ) && ( type == other.type ) && ( subType == other.subType ) && ( length == other.length ) && ( precision == other.precision ) && ( alias == other.alias ) && ( defaultValueExpression == other.defaultValueExpression ) - && ( constraints == other.constraints ) - && ( expressionConstraint == other.expressionConstraint ) - && ( expressionConstraintDescription == other.expressionConstraintDescription ) - && ( constraintOrigins == other.constraintOrigins ) ); + && ( constraints == other.constraints ) ); } //! Name @@ -117,17 +111,8 @@ class QgsFieldPrivate : public QSharedData //! Default value expression QString defaultValueExpression; - //! Constraints - QgsField::Constraints constraints; - - //! Origin of field constraints - QHash< QgsField::Constraint, QgsField::ConstraintOrigin > constraintOrigins; - - //! Expression constraint - QString expressionConstraint; - - //! Expression constraint descriptive name - QString expressionConstraintDescription; + //! Field constraints + QgsFieldConstraints constraints; QgsEditorWidgetSetup editorWidgetSetup; }; diff --git a/src/core/qgsfieldconstraints.cpp b/src/core/qgsfieldconstraints.cpp new file mode 100644 index 000000000000..7594137f39c4 --- /dev/null +++ b/src/core/qgsfieldconstraints.cpp @@ -0,0 +1,69 @@ +/*************************************************************************** + qgsfieldconstraints.cpp + ----------------------- + Date : November 2016 + Copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgsfieldconstraints.h" + + + + +QgsFieldConstraints::QgsFieldConstraints() + : mConstraints( 0 ) +{} + +QgsFieldConstraints::ConstraintOrigin QgsFieldConstraints::constraintOrigin( QgsFieldConstraints::Constraint constraint ) const +{ + if ( !( mConstraints & constraint ) ) + return ConstraintOriginNotSet; + + return mConstraintOrigins.value( constraint, ConstraintOriginNotSet ); +} + +void QgsFieldConstraints::setConstraint( QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintOrigin origin ) +{ + if ( origin == ConstraintOriginNotSet ) + { + mConstraints &= ~constraint; + mConstraintOrigins.remove( constraint ); + } + else + { + mConstraints |= constraint; + mConstraintOrigins.insert( constraint, origin ); + } +} + +QString QgsFieldConstraints::constraintExpression() const +{ + return mConstraints & QgsFieldConstraints::ConstraintExpression ? mExpressionConstraint : QString(); +} + +void QgsFieldConstraints::setConstraintExpression( const QString& expression, const QString& description ) +{ + if ( expression.isEmpty() ) + mConstraints &= ~QgsFieldConstraints::ConstraintExpression; + else + { + mConstraints |= QgsFieldConstraints::ConstraintExpression; + mConstraintOrigins.insert( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintOriginLayer ); + } + + mExpressionConstraint = expression; + mExpressionConstraintDescription = description; +} + +bool QgsFieldConstraints::operator==( const QgsFieldConstraints& other ) const +{ + return mConstraints == other.mConstraints && mConstraintOrigins == other.mConstraintOrigins + && mExpressionConstraint == other.mExpressionConstraint && mExpressionConstraintDescription == other.mExpressionConstraintDescription; +} diff --git a/src/core/qgsfieldconstraints.h b/src/core/qgsfieldconstraints.h new file mode 100644 index 000000000000..186cb0be7cb9 --- /dev/null +++ b/src/core/qgsfieldconstraints.h @@ -0,0 +1,145 @@ +/*************************************************************************** + qgsfieldconstraints.h + --------------------- + Date : November 2016 + Copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSFIELDCONSTRAINTS_H +#define QGSFIELDCONSTRAINTS_H + +#include +#include +#include + +/** + * \class QgsFieldConstraints + * \ingroup core + * Stores information about constraints which may be present on a field. + * \note added in QGIS 3.0 + */ + +class CORE_EXPORT QgsFieldConstraints +{ + Q_GADGET + + Q_PROPERTY( Constraints constraints READ constraints ) + + public: + + /** + * Constraints which may be present on a field. + */ + enum Constraint + { + ConstraintNotNull = 1, //!< Field may not be null + ConstraintUnique = 1 << 1, //!< Field must have a unique value + ConstraintExpression = 1 << 2, //!< Field has an expression constraint set. See constraintExpression(). + }; + Q_DECLARE_FLAGS( Constraints, Constraint ) + + /** + * Origin of constraints. + */ + enum ConstraintOrigin + { + ConstraintOriginNotSet = 0, //!< Constraint is not set + ConstraintOriginProvider, //!< Constraint was set at data provider + ConstraintOriginLayer, //!< Constraint was set by layer + }; + + /** + * Strength of constraints. + */ + enum ConstraintStrength + { + ConstraintHard = 0, //!< Constraint must be honored before feature can be accepted + ConstraintSoft, //!< User is warned if constraint is violated but feature can still be accepted + }; + + /** + * Constructor for QgsFieldConstraints. + */ + QgsFieldConstraints(); + + /** + * Returns any constraints which are present for the field. + * @see setConstraints() + * @see constraintOrigin() + */ + Constraints constraints() const { return mConstraints; } + + /** + * Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint + * is not present on this field. + * @see constraints() + */ + ConstraintOrigin constraintOrigin( Constraint constraint ) const; + + /** + * Sets a constraint on the field. + * @see constraints() + * @see removeConstraint() + */ + void setConstraint( Constraint constraint, ConstraintOrigin origin = ConstraintOriginLayer ); + + /** + * Removes a constraint from the field. + * @see setConstraint() + * @see constraints() + */ + void removeConstraint( Constraint constraint ) { mConstraints &= ~constraint; } + + /** + * Returns the constraint expression for the field, if set. + * @see constraints() + * @see constraintDescription() + * @see setConstraintExpression() + */ + QString constraintExpression() const; + + /** + * Returns the descriptive name for the constraint expression. + * @see constraints() + * @see constraintExpression() + * @see setConstraintExpression() + */ + QString constraintDescription() const { return mExpressionConstraintDescription; } + + /** + * Set the constraint expression for the field. An optional descriptive name for the constraint + * can also be set. Setting an empty expression will clear any existing expression constraint. + * @see constraintExpression() + * @see constraintDescription() + * @see constraints() + */ + void setConstraintExpression( const QString& expression, const QString& description = QString() ); + + bool operator==( const QgsFieldConstraints& other ) const; + + private: + + //! Constraints + Constraints mConstraints; + + //! Origin of field constraints + QHash< Constraint, ConstraintOrigin > mConstraintOrigins; + + //! Expression constraint + QString mExpressionConstraint; + + //! Expression constraint descriptive name + QString mExpressionConstraintDescription; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS( QgsFieldConstraints::Constraints ) + +#endif //QGSFIELDCONSTRAINTS_H diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 1fdc55d39c64..d84f7a1604dd 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -98,13 +98,13 @@ QVariant QgsVectorDataProvider::defaultValue( int fieldId ) const return QVariant(); } -QgsField::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const +QgsFieldConstraints::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const { QgsFields f = fields(); if ( fieldIndex < 0 || fieldIndex >= f.count() ) return 0; - return f.at( fieldIndex ).constraints(); + return f.at( fieldIndex ).constraints().constraints(); } bool QgsVectorDataProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index b237291978b5..68cb4df9c351 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -286,7 +286,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider * field index. * @note added in QGIS 3.0 */ - QgsField::Constraints fieldConstraints( int fieldIndex ) const; + QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; /** * Changes geometries of existing features diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 19ad11a81ab3..f724bae17c61 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -1456,7 +1456,7 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) if ( field.isEmpty() || constraints == 0 ) continue; - mFieldConstraints.insert( field, static_cast< QgsField::Constraints >( constraints ) ); + mFieldConstraints.insert( field, static_cast< QgsFieldConstraints::Constraints >( constraints ) ); } } mFieldConstraintExpressions.clear(); @@ -1690,7 +1690,7 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, { QDomElement constraintElem = document.createElement( "constraint" ); constraintElem.setAttribute( "field", field.name() ); - constraintElem.setAttribute( "constraints", field.constraints() ); + constraintElem.setAttribute( "constraints", field.constraints().constraints() ); constraintsElem.appendChild( constraintElem ); } layer_node.appendChild( constraintsElem ); @@ -1701,8 +1701,8 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, { QDomElement constraintExpressionElem = document.createElement( "constraint" ); constraintExpressionElem.setAttribute( "field", field.name() ); - constraintExpressionElem.setAttribute( "exp", field.constraintExpression() ); - constraintExpressionElem.setAttribute( "desc", field.constraintDescription() ); + constraintExpressionElem.setAttribute( "exp", field.constraints().constraintExpression() ); + constraintExpressionElem.setAttribute( "desc", field.constraints().constraintDescription() ); constraintExpressionsElem.appendChild( constraintExpressionElem ); } layer_node.appendChild( constraintExpressionsElem ); @@ -2963,20 +2963,24 @@ void QgsVectorLayer::updateFields() mFields[ index ].setDefaultValueExpression( defaultIt.value() ); } - QMap< QString, QgsField::Constraints >::const_iterator constraintIt = mFieldConstraints.constBegin(); + + QMap< QString, QgsFieldConstraints::Constraints >::const_iterator constraintIt = mFieldConstraints.constBegin(); for ( ; constraintIt != mFieldConstraints.constEnd(); ++constraintIt ) { int index = mFields.lookupField( constraintIt.key() ); if ( index < 0 ) continue; + QgsFieldConstraints constraints = mFields.at( index ).constraints(); + // always keep provider constraints intact - if ( !( mFields.at( index ).constraints() & QgsField::ConstraintNotNull ) && ( constraintIt.value() & QgsField::ConstraintNotNull ) ) - mFields[ index ].setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginLayer ); - if ( !( mFields.at( index ).constraints() & QgsField::ConstraintUnique ) && ( constraintIt.value() & QgsField::ConstraintUnique ) ) - mFields[ index ].setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginLayer ); - if ( !( mFields.at( index ).constraints() & QgsField::ConstraintExpression ) && ( constraintIt.value() & QgsField::ConstraintExpression ) ) - mFields[ index ].setConstraint( QgsField::ConstraintExpression, QgsField::ConstraintOriginLayer ); + if ( !( constraints.constraints() & QgsFieldConstraints::ConstraintNotNull ) && ( constraintIt.value() & QgsFieldConstraints::ConstraintNotNull ) ) + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginLayer ); + if ( !( constraints.constraints() & QgsFieldConstraints::ConstraintUnique ) && ( constraintIt.value() & QgsFieldConstraints::ConstraintUnique ) ) + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginLayer ); + if ( !( constraints.constraints() & QgsFieldConstraints::ConstraintExpression ) && ( constraintIt.value() & QgsFieldConstraints::ConstraintExpression ) ) + constraints.setConstraint( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintOriginLayer ); + mFields[ index ].setConstraints( constraints ); } QMap< QString, QPair< QString, QString > >::const_iterator constraintExpIt = mFieldConstraintExpressions.constBegin(); @@ -2986,11 +2990,14 @@ void QgsVectorLayer::updateFields() if ( index < 0 ) continue; + QgsFieldConstraints constraints = mFields.at( index ).constraints(); + // always keep provider constraints intact - if ( mFields.at( index ).constraintOrigin( QgsField::ConstraintExpression ) == QgsField::ConstraintOriginProvider ) + if ( constraints.constraintOrigin( QgsFieldConstraints::ConstraintExpression ) == QgsFieldConstraints::ConstraintOriginProvider ) continue; - mFields[ index ].setConstraintExpression( constraintExpIt.value().first, constraintExpIt.value().second ); + constraints.setConstraintExpression( constraintExpIt.value().first, constraintExpIt.value().second ); + mFields[ index ].setConstraints( constraints ); } if ( oldFields != mFields ) @@ -4282,12 +4289,12 @@ bool QgsVectorLayer::setDependencies( const QSet& oDeps ) return true; } -QgsField::Constraints QgsVectorLayer::fieldConstraints( int fieldIndex ) const +QgsFieldConstraints::Constraints QgsVectorLayer::fieldConstraints( int fieldIndex ) const { if ( fieldIndex < 0 || fieldIndex >= mFields.count() ) return 0; - QgsField::Constraints constraints = mFields.at( fieldIndex ).constraints(); + QgsFieldConstraints::Constraints constraints = mFields.at( fieldIndex ).constraints().constraints(); // make sure provider constraints are always present! if ( mFields.fieldOrigin( fieldIndex ) == QgsFields::OriginProvider ) @@ -4298,7 +4305,7 @@ QgsField::Constraints QgsVectorLayer::fieldConstraints( int fieldIndex ) const return constraints; } -void QgsVectorLayer::setFieldConstraints( int index, QgsField::Constraints constraints ) +void QgsVectorLayer::setFieldConstraints( int index, QgsFieldConstraints::Constraints constraints ) { if ( index < 0 || index >= mFields.count() ) return; @@ -4319,7 +4326,7 @@ QString QgsVectorLayer::constraintExpression( int index ) const if ( index < 0 || index >= mFields.count() ) return QString(); - return mFields.at( index ).constraintExpression(); + return mFields.at( index ).constraints().constraintExpression(); } QString QgsVectorLayer::constraintDescription( int index ) const @@ -4327,7 +4334,7 @@ QString QgsVectorLayer::constraintDescription( int index ) const if ( index < 0 || index >= mFields.count() ) return QString(); - return mFields.at( index ).constraintDescription(); + return mFields.at( index ).constraints().constraintDescription(); } void QgsVectorLayer::setConstraintExpression( int index, const QString& expression, const QString& description ) diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 9c0fc70a2bc3..7440bb343231 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1404,7 +1404,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * @note added in QGIS 3.0 * @see setFieldConstraints() */ - QgsField::Constraints fieldConstraints( int fieldIndex ) const; + QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; /** * Sets the constraints for a specified field index. Any constraints inherited from the layer's @@ -1413,7 +1413,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * @note added in QGIS 3.0 * @see fieldConstraints() */ - void setFieldConstraints( int index, QgsField::Constraints constraints ); + void setFieldConstraints( int index, QgsFieldConstraints::Constraints constraints ); /** * Returns the constraint expression for for a specified field index, if set. @@ -1981,7 +1981,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte QgsStringMap mDefaultExpressionMap; //! Map which stores constraints for fields - QMap< QString, QgsField::Constraints > mFieldConstraints; + QMap< QString, QgsFieldConstraints::Constraints > mFieldConstraints; //! Map which stores expression constraints for fields. Value is a pair of expression/description. QMap< QString, QPair< QString, QString > > mFieldConstraintExpressions; diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index 7c3e80f140c5..d92fa54c9f30 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -50,7 +50,7 @@ bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldInd return false; } -bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, QgsField::ConstraintOrigin origin ) +bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, QgsFieldConstraints::ConstraintOrigin origin ) { if ( !layer ) return false; @@ -63,13 +63,15 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const bool valid = true; errors.clear(); - if ( field.constraints() & QgsField::ConstraintExpression && !field.constraintExpression().isEmpty() - && ( origin == QgsField::ConstraintOriginNotSet || origin == field.constraintOrigin( QgsField::ConstraintExpression ) ) ) + QgsFieldConstraints constraints = field.constraints(); + + if ( constraints.constraints() & QgsFieldConstraints::ConstraintExpression && !constraints.constraintExpression().isEmpty() + && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintExpression ) ) ) { QgsExpressionContext context = layer->createExpressionContext(); context.setFeature( feature ); - QgsExpression expr( field.constraintExpression() ); + QgsExpression expr( constraints.constraintExpression() ); valid = expr.evaluate( &context ).toBool(); @@ -83,12 +85,12 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const } else if ( !valid ) { - errors << QObject::tr( "%1 check failed" ).arg( field.constraintDescription() ); + errors << QObject::tr( "%1 check failed" ).arg( constraints.constraintDescription() ); } } - if ( field.constraints() & QgsField::ConstraintNotNull - && ( origin == QgsField::ConstraintOriginNotSet || origin == field.constraintOrigin( QgsField::ConstraintNotNull ) ) ) + if ( constraints.constraints() & QgsFieldConstraints::ConstraintNotNull + && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) ) ) { valid = valid && !value.isNull(); @@ -98,8 +100,8 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const } } - if ( field.constraints() & QgsField::ConstraintUnique - && ( origin == QgsField::ConstraintOriginNotSet || origin == field.constraintOrigin( QgsField::ConstraintUnique ) ) ) + if ( constraints.constraints() & QgsFieldConstraints::ConstraintUnique + && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintUnique ) ) ) { bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() ); valid = valid && !alreadyExists; diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h index 070c34d50353..8320acee9aae 100644 --- a/src/core/qgsvectorlayerutils.h +++ b/src/core/qgsvectorlayerutils.h @@ -42,7 +42,7 @@ class CORE_EXPORT QgsVectorLayerUtils * If the origin parameter is set then only constraints with a matching origin will be checked. */ static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, - QgsField::ConstraintOrigin origin = QgsField::ConstraintOriginNotSet ); + QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); }; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index 2863b2fe5808..c646df772b99 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -266,7 +266,7 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle if ( ewv2CfgElem.attribute( QStringLiteral( "notNull" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ) { // upgrade from older config - vectorLayer->setFieldConstraints( idx, vectorLayer->fieldConstraints( idx ) | QgsField::ConstraintNotNull ); + vectorLayer->setFieldConstraints( idx, vectorLayer->fieldConstraints( idx ) | QgsFieldConstraints::ConstraintNotNull ); } if ( !ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ).isEmpty() ) { diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 6c311c2e2610..fbfe25490732 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -106,22 +106,22 @@ void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid widget()->setStyleSheet( QStringLiteral( "background-color: #dd7777;" ) ); } -void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsField::ConstraintOrigin constraintOrigin ) +void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsFieldConstraints::ConstraintOrigin constraintOrigin ) { bool toEmit( false ); QgsField field = layer()->fields().at( mFieldIdx ); - QString expression = field.constraintExpression(); + QString expression = field.constraints().constraintExpression(); QStringList expressions, descriptions; if ( ! expression.isEmpty() ) { expressions << expression; - descriptions << field.constraintDescription(); + descriptions << field.constraints().constraintDescription(); toEmit = true; } - if ( field.constraints() & QgsField::ConstraintNotNull ) + if ( field.constraints().constraints() & QgsFieldConstraints::ConstraintNotNull ) { descriptions << QStringLiteral( "Not NULL" ); if ( !expression.isEmpty() ) @@ -135,7 +135,7 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsField::C toEmit = true; } - if ( field.constraints() & QgsField::ConstraintUnique ) + if ( field.constraints().constraints() & QgsFieldConstraints::ConstraintUnique ) { descriptions << QStringLiteral( "Unique" ); if ( !expression.isEmpty() ) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h index 6c1a2d89052f..9719d4fc6042 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h @@ -122,7 +122,7 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper * to only provider or layer based constraints. * @note added in QGIS 2.16 */ - void updateConstraint( const QgsFeature &featureContext, QgsField::ConstraintOrigin constraintOrigin = QgsField::ConstraintOriginNotSet ); + void updateConstraint( const QgsFeature &featureContext, QgsFieldConstraints::ConstraintOrigin constraintOrigin = QgsFieldConstraints::ConstraintOriginNotSet ); /** * Get the current constraint status. diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 57910adaaf4f..61738ee60a9a 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -704,8 +704,8 @@ void QgsAttributeForm::updateConstraints( QgsEditorWidgetWrapper *eww ) // to test, but they are unlikely to have any control over provider-side constraints // 2. the provider has already accepted the value, so presumably it doesn't violate the constraint // and there's no point rechecking! - QgsField::ConstraintOrigin constraintOrigin = mLayer->isEditable() ? QgsField::ConstraintOriginNotSet - : QgsField::ConstraintOriginLayer; + QgsFieldConstraints::ConstraintOrigin constraintOrigin = mLayer->isEditable() ? QgsFieldConstraints::ConstraintOriginNotSet + : QgsFieldConstraints::ConstraintOriginLayer; // update eww constraint eww->updateConstraint( ft, constraintOrigin ); @@ -928,7 +928,7 @@ QList QgsAttributeForm::constraintDependencies( QgsEdit if ( name != ewwName ) { // get expression and referencedColumns - QgsExpression expr = eww->layer()->fields().at( eww->fieldIdx() ).constraintExpression(); + QgsExpression expr = eww->layer()->fields().at( eww->fieldIdx() ).constraints().constraintExpression(); Q_FOREACH ( const QString& colName, expr.referencedColumns() ) { diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 56eecf9795b3..935a8507ded3 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -943,7 +943,9 @@ void QgsOgrProvider::loadFields() bool nullable = OGR_Fld_IsNullable( fldDef ); if ( !nullable ) { - newField.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + newField.setConstraints( constraints ); } #endif diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 2f144f88d1a7..d653f29a61f9 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1000,10 +1000,12 @@ bool QgsPostgresProvider::loadFields() QgsField newField = QgsField( fieldName, fieldType, fieldTypeName, fieldSize, fieldPrec, fieldComment, fieldSubType ); + QgsFieldConstraints constraints; if ( notNullMap[tableoid][attnum] ) - newField.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); if ( uniqueMap[tableoid][attnum] ) - newField.setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + newField.setConstraints( constraints ); mAttributeFields.append( newField ); } diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index a01992225cab..dad23c26909c 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -845,10 +845,12 @@ void QgsSpatiaLiteProvider::fetchConstraints() int fieldIdx = mAttributeFields.lookupField( fieldName ); if ( fieldIdx >= 0 ) { + QgsFieldConstraints constraints = mAttributeFields.at( fieldIdx ).constraints(); if ( definition.contains( "unique", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) - mAttributeFields[ fieldIdx ].setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); if ( definition.contains( "not null", Qt::CaseInsensitive ) || definition.contains( "primary key", Qt::CaseInsensitive ) ) - mAttributeFields[ fieldIdx ].setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + mAttributeFields[ fieldIdx ].setConstraints( constraints ); } } } diff --git a/tests/src/core/testqgsfield.cpp b/tests/src/core/testqgsfield.cpp index 8b9fda2eb726..d255973d674e 100644 --- a/tests/src/core/testqgsfield.cpp +++ b/tests/src/core/testqgsfield.cpp @@ -84,8 +84,10 @@ void TestQgsField::create() void TestQgsField::copy() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); - original.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); - original.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + original.setConstraints( constraints ); QgsField copy( original ); QVERIFY( copy == original ); @@ -97,8 +99,10 @@ void TestQgsField::copy() void TestQgsField::assignment() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); - original.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); - original.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + original.setConstraints( constraints ); QgsField copy; copy = original; QVERIFY( copy == original ); @@ -127,22 +131,28 @@ void TestQgsField::gettersSetters() QCOMPARE( field.alias(), QString( "alias" ) ); field.setDefaultValueExpression( QStringLiteral( "1+2" ) ); QCOMPARE( field.defaultValueExpression(), QString( "1+2" ) ); - field.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); - QCOMPARE( field.constraints(), QgsField::ConstraintNotNull ); - QCOMPARE( field.constraintOrigin( QgsField::ConstraintNotNull ), QgsField::ConstraintOriginProvider ); - QCOMPARE( field.constraintOrigin( QgsField::ConstraintUnique ), QgsField::ConstraintOriginNotSet ); - field.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginNotSet ); - QCOMPARE( field.constraints(), 0 ); - field.setConstraint( QgsField::ConstraintUnique ); - field.setConstraint( QgsField::ConstraintNotNull ); - QCOMPARE( field.constraints(), QgsField::ConstraintUnique | QgsField::ConstraintNotNull ); - field.removeConstraint( QgsField::ConstraintNotNull ); - QCOMPARE( field.constraints(), QgsField::ConstraintUnique ); - - field.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); - QCOMPARE( field.constraintExpression(), QStringLiteral( "constraint expression" ) ); - QCOMPARE( field.constraintDescription(), QStringLiteral( "description" ) ); - QCOMPARE( field.constraints(), QgsField::ConstraintUnique | QgsField::ConstraintExpression ); //setting constraint expression should add constraint + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraints(), QgsFieldConstraints::ConstraintNotNull ); + QCOMPARE( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintNotNull ), QgsFieldConstraints::ConstraintOriginProvider ); + QCOMPARE( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintUnique ), QgsFieldConstraints::ConstraintOriginNotSet ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginNotSet ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraints(), 0 ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraints(), QgsFieldConstraints::ConstraintUnique | QgsFieldConstraints::ConstraintNotNull ); + constraints.removeConstraint( QgsFieldConstraints::ConstraintNotNull ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraints(), QgsFieldConstraints::ConstraintUnique ); + + constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraintExpression(), QStringLiteral( "constraint expression" ) ); + QCOMPARE( field.constraints().constraintDescription(), QStringLiteral( "description" ) ); + QCOMPARE( field.constraints().constraints(), QgsFieldConstraints::ConstraintUnique | QgsFieldConstraints::ConstraintExpression ); //setting constraint expression should add constraint } void TestQgsField::isNumeric() @@ -177,7 +187,9 @@ void TestQgsField::equality() field1.setPrecision( 2 ); field1.setTypeName( QStringLiteral( "typename1" ) ); //typename is NOT required for equality field1.setComment( QStringLiteral( "comment1" ) ); //comment is NOT required for equality - field1.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + field1.setConstraints( constraints ); QgsField field2; field2.setName( QStringLiteral( "name" ) ); field2.setType( QVariant::Int ); @@ -185,7 +197,9 @@ void TestQgsField::equality() field2.setPrecision( 2 ); field2.setTypeName( QStringLiteral( "typename2" ) ); //typename is NOT required for equality field2.setComment( QStringLiteral( "comment2" ) ); //comment is NOT required for equality - field2.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); + constraints = field2.constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + field2.setConstraints( constraints ); QVERIFY( field1 == field2 ); QVERIFY( !( field1 != field2 ) ); @@ -214,26 +228,38 @@ void TestQgsField::equality() QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); field2.setDefaultValueExpression( QString() ); - field2.removeConstraint( QgsField::ConstraintNotNull ); + constraints = field2.constraints(); + constraints.removeConstraint( QgsFieldConstraints::ConstraintNotNull ); + field2.setConstraints( constraints ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - field2.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginLayer ); + constraints = field2.constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginLayer ); + field2.setConstraints( constraints ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - field2.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); - field2.setConstraintExpression( QStringLiteral( "exp" ) ); + constraints = field2.constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraintExpression( QStringLiteral( "exp" ) ); + field2.setConstraints( constraints ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - field2.setConstraintExpression( QStringLiteral( "exp" ), QStringLiteral( "desc" ) ); + constraints = field2.constraints(); + constraints.setConstraintExpression( QStringLiteral( "exp" ), QStringLiteral( "desc" ) ); + field2.setConstraints( constraints ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - field2.setConstraintExpression( QString(), QString() ); + constraints = field2.constraints(); + constraints.setConstraintExpression( QString(), QString() ); + field2.setConstraints( constraints ); } void TestQgsField::asVariant() { QgsField original( QStringLiteral( "original" ), QVariant::Double, QStringLiteral( "double" ), 5, 2, QStringLiteral( "comment" ) ); - original.setConstraint( QgsField::ConstraintNotNull ); + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull ); + original.setConstraints( constraints ); //convert to and from a QVariant QVariant var = QVariant::fromValue( original ); @@ -412,9 +438,11 @@ void TestQgsField::dataStream() original.setComment( QStringLiteral( "comment1" ) ); original.setAlias( QStringLiteral( "alias" ) ); original.setDefaultValueExpression( QStringLiteral( "default" ) ); - original.setConstraint( QgsField::ConstraintNotNull, QgsField::ConstraintOriginProvider ); - original.setConstraint( QgsField::ConstraintUnique, QgsField::ConstraintOriginLayer ); - original.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + QgsFieldConstraints constraints; + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginLayer ); + constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + original.setConstraints( constraints ); QByteArray ba; QDataStream ds( &ba, QIODevice::ReadWrite ); diff --git a/tests/src/python/test_provider_ogr_sqlite.py b/tests/src/python/test_provider_ogr_sqlite.py index fc20dfed6d65..f83cf762da8c 100644 --- a/tests/src/python/test_provider_ogr_sqlite.py +++ b/tests/src/python/test_provider_ogr_sqlite.py @@ -20,7 +20,7 @@ import glob from osgeo import gdal, ogr -from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest, QgsField +from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest, QgsField, QgsFieldConstraints from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -146,19 +146,19 @@ def testNotNullConstraint(self): self.assertTrue(vl.isValid()) # test some bad indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) - self.assertFalse(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintNotNull) - self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintNotNull) # test that constraints have been saved to fields correctly fields = vl.fields() - self.assertFalse(fields.at(0).constraints() & QgsField.ConstraintNotNull) - self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintNotNull) - self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintNotNull) - self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) + self.assertFalse(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) if __name__ == '__main__': diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 51f4e38391a3..68716c6edee6 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -27,6 +27,7 @@ QgsFeature, QgsTransactionGroup, QgsField, + QgsFieldConstraints, NULL ) from qgis.gui import QgsEditorWidgetRegistry @@ -444,22 +445,22 @@ def testNotNullConstraint(self): self.assertEqual(len(vl.fields()), 4) # test some bad field indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintNotNull) - self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsFieldConstraints.ConstraintNotNull) # test that constraints have been saved to fields correctly fields = vl.fields() - self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintNotNull) - self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) - self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintNotNull) - self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintNotNull) - self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) - self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(fields.at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) + self.assertFalse(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) + self.assertFalse(fields.at(3).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) def testUniqueConstraint(self): vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") @@ -467,44 +468,44 @@ def testUniqueConstraint(self): self.assertEqual(len(vl.fields()), 4) # test some bad field indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintUnique) - self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintUnique) - self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintUnique) - self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsFieldConstraints.ConstraintUnique) # test that constraints have been saved to fields correctly fields = vl.fields() - self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintUnique) - self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) - self.assertTrue(fields.at(1).constraints() & QgsField.ConstraintUnique) - self.assertEqual(fields.at(1).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) - self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) - self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) - self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) + self.assertTrue(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertEqual(fields.at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) + self.assertTrue(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertEqual(fields.at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) + self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) + self.assertFalse(fields.at(3).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) def testConstraintOverwrite(self): """ test that Postgres provider constraints can't be overwritten by vector layer method """ vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") self.assertTrue(vl.isValid()) - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) - self.assertTrue(vl.fields().at(0).constraints() & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.fields().at(0).constraints() & QgsFieldConstraints.ConstraintNotNull) # add a constraint at the layer level - vl.setFieldConstraints(0, QgsField.ConstraintUnique) + vl.setFieldConstraints(0, QgsFieldConstraints.ConstraintUnique) # should be no change at provider level - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) # but layer should still keep provider constraints... - self.assertTrue(vl.fields().at(0).constraints() & QgsField.ConstraintNotNull) - self.assertTrue(vl.fieldConstraints(0) & QgsField.ConstraintNotNull) + self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) # ...in addition to layer level constraint - self.assertTrue(vl.fields().at(0).constraints() & QgsField.ConstraintUnique) - self.assertTrue(vl.fieldConstraints(0) & QgsField.ConstraintUnique) + self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(vl.fieldConstraints(0) & QgsFieQgsFieldConstraintsld.ConstraintUnique) # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index 12846ad35bd8..f0d38b13f6c3 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -19,7 +19,7 @@ import shutil import tempfile -from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry, QgsField +from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry, QgsField, QgsFieldConstraints from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -393,25 +393,25 @@ def testNotNullConstraint(self): self.assertEqual(len(vl.fields()), 5) # test some bad field indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintNotNull) - self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintNotNull) - self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintNotNull) - self.assertTrue(vl.dataProvider().fieldConstraints(4) & QgsField.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.dataProvider().fieldConstraints(4) & QgsFieldConstraints.ConstraintNotNull) # test that constraints have been saved to fields correctly fields = vl.fields() - self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintNotNull) - self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) - self.assertTrue(fields.at(1).constraints() & QgsField.ConstraintNotNull) - self.assertEqual(fields.at(1).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) - self.assertFalse(fields.at(2).constraints() & QgsField.ConstraintNotNull) - self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintNotNull) - self.assertTrue(fields.at(4).constraints() & QgsField.ConstraintNotNull) - self.assertEqual(fields.at(4).constraintOrigin(QgsField.ConstraintNotNull), QgsField.ConstraintOriginProvider) + self.assertTrue(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(fields.at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) + self.assertTrue(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(fields.at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) + self.assertFalse(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertFalse(fields.at(3).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(fields.at(4).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(fields.at(4).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) def testUniqueConstraint(self): vl = QgsVectorLayer("dbname=%s table=test_constraints key='id'" % self.dbname, "test_constraints", @@ -420,25 +420,25 @@ def testUniqueConstraint(self): self.assertEqual(len(vl.fields()), 5) # test some bad field indexes - self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsField.Constraints()) - self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsField.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) + self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) - self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsField.ConstraintUnique) - self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsField.ConstraintUnique) - self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsField.ConstraintUnique) - self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsField.ConstraintUnique) - self.assertTrue(vl.dataProvider().fieldConstraints(4) & QgsField.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintUnique) + self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(vl.dataProvider().fieldConstraints(4) & QgsFieldConstraints.ConstraintUnique) # test that constraints have been saved to fields correctly fields = vl.fields() - self.assertTrue(fields.at(0).constraints() & QgsField.ConstraintUnique) - self.assertEqual(fields.at(0).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) - self.assertFalse(fields.at(1).constraints() & QgsField.ConstraintUnique) - self.assertTrue(fields.at(2).constraints() & QgsField.ConstraintUnique) - self.assertEqual(fields.at(2).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) - self.assertFalse(fields.at(3).constraints() & QgsField.ConstraintUnique) - self.assertTrue(fields.at(4).constraints() & QgsField.ConstraintUnique) - self.assertEqual(fields.at(4).constraintOrigin(QgsField.ConstraintUnique), QgsField.ConstraintOriginProvider) + self.assertTrue(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertEqual(fields.at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) + self.assertFalse(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) + self.assertFalse(fields.at(3).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertTrue(fields.at(4).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) + self.assertEqual(fields.at(4).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) # This test would fail. It would require turning on WAL def XXXXXtestLocking(self): diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 19abb8dafd10..597efdee3f66 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -29,6 +29,7 @@ QgsGeometry, QgsPoint, QgsField, + QgsFieldConstraints, QgsFields, QgsMapLayerRegistry, QgsVectorJoinInfo, @@ -1781,37 +1782,37 @@ def testGetSetConstraints(self): self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) - layer.setFieldConstraints(0, QgsField.ConstraintNotNull) - self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) + layer.setFieldConstraints(0, QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) - self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) - self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginLayer) - layer.setFieldConstraints(1, QgsField.ConstraintNotNull | QgsField.ConstraintUnique) - self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) - self.assertEqual(layer.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) + self.assertEqual(layer.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer.fieldConstraints(1), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) self.assertFalse(layer.fieldConstraints(2)) - self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) - self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginLayer) - self.assertEqual(layer.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) - self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginLayer) - self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintUnique), - QgsField.ConstraintOriginLayer) - - layer.setFieldConstraints(1, QgsField.Constraints()) - self.assertEqual(layer.fieldConstraints(0), QgsField.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(1).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) + self.assertEqual(layer.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), + QgsFieldConstraints.ConstraintOriginLayer) + + layer.setFieldConstraints(1, QgsFieldConstraints.Constraints()) + self.assertEqual(layer.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) - self.assertEqual(layer.fields().at(0).constraints(), QgsField.ConstraintNotNull) - self.assertEqual(layer.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginLayer) - self.assertFalse(layer.fields().at(1).constraints()) - self.assertEqual(layer.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginNotSet) + self.assertEqual(layer.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginLayer) + self.assertFalse(layer.fields().at(1).constraints().constraints()) + self.assertEqual(layer.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginNotSet) def testSaveRestoreConstraints(self): """ test saving and restoring constraints from xml""" @@ -1828,8 +1829,8 @@ def testSaveRestoreConstraints(self): self.assertFalse(layer2.fieldConstraints(1)) # set some constraints - layer.setFieldConstraints(0, QgsField.ConstraintNotNull) - layer.setFieldConstraints(1, QgsField.ConstraintNotNull | QgsField.ConstraintUnique) + layer.setFieldConstraints(0, QgsFieldConstraints.ConstraintNotNull) + layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) doc = QDomDocument("testdoc") elem = doc.createElement("maplayer") @@ -1837,16 +1838,16 @@ def testSaveRestoreConstraints(self): layer3 = createLayerWithOnePoint() self.assertTrue(layer3.readXml(elem)) - self.assertEqual(layer3.fieldConstraints(0), QgsField.ConstraintNotNull) - self.assertEqual(layer3.fieldConstraints(1), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) - self.assertEqual(layer3.fields().at(0).constraints(), QgsField.ConstraintNotNull) - self.assertEqual(layer3.fields().at(0).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginLayer) - self.assertEqual(layer3.fields().at(1).constraints(), QgsField.ConstraintNotNull | QgsField.ConstraintUnique) - self.assertEqual(layer3.fields().at(1).constraintOrigin(QgsField.ConstraintNotNull), - QgsField.ConstraintOriginLayer) - self.assertEqual(layer3.fields().at(1).constraintOrigin(QgsField.ConstraintUnique), - QgsField.ConstraintOriginLayer) + self.assertEqual(layer3.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer3.fieldConstraints(1), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) + self.assertEqual(layer3.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) + self.assertEqual(layer3.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer3.fields().at(1).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) + self.assertEqual(layer3.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer3.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), + QgsFieldConstraints.ConstraintOriginLayer) def testGetSetConstraintExpressions(self): """ test getting and setting field constraint expressions """ @@ -1860,23 +1861,23 @@ def testGetSetConstraintExpressions(self): self.assertEqual(layer.constraintExpression(0), '1+2') self.assertFalse(layer.constraintExpression(1)) self.assertFalse(layer.constraintExpression(2)) - self.assertEqual(layer.fields().at(0).constraintExpression(), '1+2') + self.assertEqual(layer.fields().at(0).constraints().constraintExpression(), '1+2') layer.setConstraintExpression(1, '3+4', 'desc') self.assertEqual(layer.constraintExpression(0), '1+2') self.assertEqual(layer.constraintExpression(1), '3+4') self.assertEqual(layer.constraintDescription(1), 'desc') self.assertFalse(layer.constraintExpression(2)) - self.assertEqual(layer.fields().at(0).constraintExpression(), '1+2') - self.assertEqual(layer.fields().at(1).constraintExpression(), '3+4') - self.assertEqual(layer.fields().at(1).constraintDescription(), 'desc') + self.assertEqual(layer.fields().at(0).constraints().constraintExpression(), '1+2') + self.assertEqual(layer.fields().at(1).constraints().constraintExpression(), '3+4') + self.assertEqual(layer.fields().at(1).constraints().constraintDescription(), 'desc') layer.setConstraintExpression(1, None) self.assertEqual(layer.constraintExpression(0), '1+2') self.assertFalse(layer.constraintExpression(1)) self.assertFalse(layer.constraintExpression(2)) - self.assertEqual(layer.fields().at(0).constraintExpression(), '1+2') - self.assertFalse(layer.fields().at(1).constraintExpression()) + self.assertEqual(layer.fields().at(0).constraints().constraintExpression(), '1+2') + self.assertFalse(layer.fields().at(1).constraints().constraintExpression()) def testSaveRestoreConstraintExpressions(self): """ test saving and restoring constraint expressions from xml""" @@ -1905,15 +1906,15 @@ def testSaveRestoreConstraintExpressions(self): self.assertEqual(layer3.constraintExpression(0), '1+2') self.assertEqual(layer3.constraintExpression(1), '3+4') self.assertEqual(layer3.constraintDescription(1), 'desc') - self.assertEqual(layer3.fields().at(0).constraintExpression(), '1+2') - self.assertEqual(layer3.fields().at(1).constraintExpression(), '3+4') - self.assertEqual(layer3.fields().at(1).constraintDescription(), 'desc') - self.assertEqual(layer3.fields().at(0).constraints(), QgsField.ConstraintExpression) - self.assertEqual(layer3.fields().at(1).constraints(), QgsField.ConstraintExpression) - self.assertEqual(layer3.fields().at(0).constraintOrigin(QgsField.ConstraintExpression), - QgsField.ConstraintOriginLayer) - self.assertEqual(layer3.fields().at(1).constraintOrigin(QgsField.ConstraintExpression), - QgsField.ConstraintOriginLayer) + self.assertEqual(layer3.fields().at(0).constraints().constraintExpression(), '1+2') + self.assertEqual(layer3.fields().at(1).constraints().constraintExpression(), '3+4') + self.assertEqual(layer3.fields().at(1).constraints().constraintDescription(), 'desc') + self.assertEqual(layer3.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintExpression) + self.assertEqual(layer3.fields().at(1).constraints().constraints(), QgsFieldConstraints.ConstraintExpression) + self.assertEqual(layer3.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintExpression), + QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer3.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintExpression), + QgsFieldConstraints.ConstraintOriginLayer) def testGetFeatureLimitWithEdits(self): """ test getting features with a limit, when edits are present """ diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py index bc170e3c6051..03af6941a8d5 100644 --- a/tests/src/python/test_qgsvectorlayerutils.py +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -21,6 +21,7 @@ from qgis.core import (QgsVectorLayer, QgsVectorLayerUtils, QgsField, + QgsFieldConstraints, QgsFields, QgsFeature, NULL @@ -102,7 +103,7 @@ def test_validate_attribute(self): self.assertEqual(len(errors), 1) print(errors) # checking only for provider constraints - res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsField.ConstraintOriginProvider) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(res) self.assertEqual(len(errors), 0) @@ -121,31 +122,31 @@ def test_validate_attribute(self): self.assertTrue(res) self.assertEqual(len(errors), 0) - layer.setFieldConstraints(1, QgsField.ConstraintNotNull) + layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertFalse(res) self.assertEqual(len(errors), 1) print(errors) # checking only for provider constraints - res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsField.ConstraintOriginProvider) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(res) self.assertEqual(len(errors), 0) # unique constraint f.setAttributes(["test123", 123]) - layer.setFieldConstraints(1, QgsField.Constraints()) + layer.setFieldConstraints(1, QgsFieldConstraints.Constraints()) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertTrue(res) self.assertEqual(len(errors), 0) - layer.setFieldConstraints(1, QgsField.ConstraintUnique) + layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintUnique) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertFalse(res) self.assertEqual(len(errors), 1) print(errors) # checking only for provider constraints - res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsField.ConstraintOriginProvider) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(res) self.assertEqual(len(errors), 0) @@ -158,7 +159,7 @@ def test_validate_attribute(self): # test double constraint failure layer.setConstraintExpression(1, 'fldint>5') - layer.setFieldConstraints(1, QgsField.ConstraintNotNull) + layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull) f.setAttributes(["test123", NULL]) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertFalse(res) From 3a596749012a6f8b0c7e00fe9b860d85d3f71349 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 18:44:32 +1000 Subject: [PATCH 585/897] Fix some untranslatable strings --- src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index fbfe25490732..661e68909cbb 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -123,10 +123,10 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsFieldCon if ( field.constraints().constraints() & QgsFieldConstraints::ConstraintNotNull ) { - descriptions << QStringLiteral( "Not NULL" ); + descriptions << tr( "Not NULL" ); if ( !expression.isEmpty() ) { - expressions << field.name() + " IS NOT NULL"; + expressions << field.name() + QStringLiteral( " IS NOT NULL" ); } else { @@ -137,10 +137,10 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsFieldCon if ( field.constraints().constraints() & QgsFieldConstraints::ConstraintUnique ) { - descriptions << QStringLiteral( "Unique" ); + descriptions << tr( "Unique" ); if ( !expression.isEmpty() ) { - expressions << field.name() + " IS UNIQUE"; + expressions << field.name() + QStringLiteral( " IS UNIQUE" ); } else { From e3a608365f612fbc58e88255ec4f136cd609d015 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 1 Nov 2016 19:35:27 +1000 Subject: [PATCH 586/897] fix test --- tests/src/python/test_provider_postgres.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 68716c6edee6..18ee6341b38e 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -492,10 +492,10 @@ def testConstraintOverwrite(self): self.assertTrue(vl.isValid()) self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) - self.assertTrue(vl.fields().at(0).constraints() & QgsFieldConstraints.ConstraintNotNull) + self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) # add a constraint at the layer level - vl.setFieldConstraints(0, QgsFieldConstraints.ConstraintUnique) + vl.setFieldConstraint(0, QgsFieldConstraints.ConstraintUnique) # should be no change at provider level self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) @@ -505,7 +505,7 @@ def testConstraintOverwrite(self): self.assertTrue(vl.fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) # ...in addition to layer level constraint self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) - self.assertTrue(vl.fieldConstraints(0) & QgsFieQgsFieldConstraintsld.ConstraintUnique) + self.assertTrue(vl.fieldConstraints(0) & QgsFieldConstraints.ConstraintUnique) # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): From fac5bc0691101e9ef228f08d14ee1773bed92848 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 12:09:52 +1000 Subject: [PATCH 587/897] [FEATURE] Field constraints can be enforced or not Non-enforced constraints just show a warning to the user, but do not prevent committing the feature. Enforced constraints block users from comitting non compliant features. Any constraints detected by the provider are always enforced. --- python/core/qgsfieldconstraints.sip | 21 +++- python/core/qgsvectorlayer.sip | 18 ++- src/app/qgsattributetypedialog.cpp | 52 +++++++- src/app/qgsattributetypedialog.h | 30 +++++ src/app/qgsfieldsproperties.cpp | 30 ++++- src/app/qgsfieldsproperties.h | 1 + src/core/qgsfield.cpp | 16 ++- src/core/qgsfieldconstraints.cpp | 34 +++++- src/core/qgsfieldconstraints.h | 24 +++- src/core/qgsvectorlayer.cpp | 65 ++++++++-- src/core/qgsvectorlayer.h | 21 +++- .../core/qgseditorwidgetregistry.cpp | 2 +- src/ui/qgsattributetypeedit.ui | 111 +++++++++++------- tests/src/core/testqgsfield.cpp | 26 +++- tests/src/python/test_qgsvectorlayer.py | 31 ++++- 15 files changed, 406 insertions(+), 76 deletions(-) diff --git a/python/core/qgsfieldconstraints.sip b/python/core/qgsfieldconstraints.sip index 965f71ac9dda..48f125a0ec00 100644 --- a/python/core/qgsfieldconstraints.sip +++ b/python/core/qgsfieldconstraints.sip @@ -41,8 +41,9 @@ class QgsFieldConstraints */ enum ConstraintStrength { - ConstraintHard, //!< Constraint must be honored before feature can be accepted - ConstraintSoft, //!< User is warned if constraint is violated but feature can still be accepted + ConstraintStrengthNotSet, //!< Constraint is not set + ConstraintStrengthHard, //!< Constraint must be honored before feature can be accepted + ConstraintStrengthSoft, //!< User is warned if constraint is violated but feature can still be accepted }; /** @@ -64,6 +65,22 @@ class QgsFieldConstraints */ ConstraintOrigin constraintOrigin( Constraint constraint ) const; + /** + * Returns the strength of a field constraint, or ConstraintStrengthNotSet if the constraint + * is not present on this field. + * @see constraints() + * @see setConstraintStrength() + */ + ConstraintStrength constraintStrength( Constraint constraint ) const; + + /** + * Sets the strength of a constraint. Note that the strength of constraints which originate + * from a provider cannot be changed. Constraints default to ConstraintStrengthHard unless + * explicitly changed. + * @see constraintStrength() + */ + void setConstraintStrength( Constraint constraint, ConstraintStrength strength ); + /** * Sets a constraint on the field. * @see constraints() diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index bf8754dcf507..12c4b9ebadd0 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1262,18 +1262,28 @@ class QgsVectorLayer : QgsMapLayer * field index. These constraints may be inherited from the layer's data provider * or may be set manually on the vector layer from within QGIS. * @note added in QGIS 3.0 - * @see setFieldConstraints() + * @see setFieldConstraint() */ QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; /** - * Sets the constraints for a specified field index. Any constraints inherited from the layer's - * data provider will be kept intact and cannot be cleared. Ie, calling this method only allows for new + * Sets a constraint for a specified field index. Any constraints inherited from the layer's + * data provider will be kept intact and cannot be modified. Ie, calling this method only allows for new * constraints to be added on top of the existing provider constraints. * @note added in QGIS 3.0 * @see fieldConstraints() + * @see removeFieldConstraint() */ - void setFieldConstraints( int index, QgsFieldConstraints::Constraints constraints ); + void setFieldConstraint( int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthHard ); + + /** + * Removes a constraint for a specified field index. Any constraints inherited from the layer's + * data provider will be kept intact and cannot be removed. + * @note added in QGIS 3.0 + * @see fieldConstraints() + * @see setFieldConstraint() + */ + void removeFieldConstraint( int index, QgsFieldConstraints::Constraint constraint ); /** * Returns the constraint expression for for a specified field index, if set. diff --git a/src/app/qgsattributetypedialog.cpp b/src/app/qgsattributetypedialog.cpp index 2857787850de..d49507967cdd 100644 --- a/src/app/qgsattributetypedialog.cpp +++ b/src/app/qgsattributetypedialog.cpp @@ -69,7 +69,21 @@ QgsAttributeTypeDialog::QgsAttributeTypeDialog( QgsVectorLayer *vl, int fieldIdx isFieldEditableCheckBox->setEnabled( false ); } - connect( mExpressionWidget, SIGNAL( expressionChanged( QString ) ), this, SLOT( defaultExpressionChanged() ) ); + connect( mExpressionWidget, &QgsExpressionLineEdit::expressionChanged, this, &QgsAttributeTypeDialog::defaultExpressionChanged ); + connect( mUniqueCheckBox, &QCheckBox::toggled, this, [=]( bool checked ) + { + mCheckBoxEnforceUnique->setEnabled( checked ); + if ( !checked ) + mCheckBoxEnforceUnique->setChecked( false ); + } + ); + connect( notNullCheckBox, &QCheckBox::toggled, this, [=]( bool checked ) + { + mCheckBoxEnforceNotNull->setEnabled( checked ); + if ( !checked ) + mCheckBoxEnforceNotNull->setChecked( false ); + } + ); QSettings settings; restoreGeometry( settings.value( QStringLiteral( "/Windows/QgsAttributeTypeDialog/geometry" ) ).toByteArray() ); @@ -154,7 +168,7 @@ void QgsAttributeTypeDialog::setWidgetType( const QString& type ) stackedWidget->addWidget( cfgWdg ); stackedWidget->setCurrentWidget( cfgWdg ); mEditorConfigWidgets.insert( type, cfgWdg ); - connect( cfgWdg, SIGNAL( changed() ), this, SLOT( defaultExpressionChanged() ) ); + connect( cfgWdg, &QgsEditorConfigWidget::changed, this, &QgsAttributeTypeDialog::defaultExpressionChanged ); } else { @@ -183,6 +197,8 @@ void QgsAttributeTypeDialog::setProviderConstraints( QgsFieldConstraints::Constr notNullCheckBox->setChecked( true ); notNullCheckBox->setEnabled( false ); notNullCheckBox->setToolTip( tr( "The provider for this layer has a NOT NULL constraint set on the field." ) ); + mCheckBoxEnforceNotNull->setChecked( true ); + mCheckBoxEnforceNotNull->setEnabled( false ); } if ( constraints & QgsFieldConstraints::ConstraintUnique ) @@ -190,6 +206,8 @@ void QgsAttributeTypeDialog::setProviderConstraints( QgsFieldConstraints::Constr mUniqueCheckBox->setChecked( true ); mUniqueCheckBox->setEnabled( false ); mUniqueCheckBox->setToolTip( tr( "The provider for this layer has a UNIQUE constraint set on the field." ) ); + mCheckBoxEnforceUnique->setChecked( true ); + mCheckBoxEnforceUnique->setEnabled( false ); } } @@ -218,6 +236,16 @@ bool QgsAttributeTypeDialog::notNull() const return notNullCheckBox->isChecked(); } +void QgsAttributeTypeDialog::setNotNullEnforced( bool enforced ) +{ + mCheckBoxEnforceNotNull->setChecked( enforced ); +} + +bool QgsAttributeTypeDialog::notNullEnforced() const +{ + return mCheckBoxEnforceNotNull->isChecked(); +} + void QgsAttributeTypeDialog::setUnique( bool unique ) { mUniqueCheckBox->setChecked( unique ); @@ -228,11 +256,31 @@ bool QgsAttributeTypeDialog::unique() const return mUniqueCheckBox->isChecked(); } +void QgsAttributeTypeDialog::setUniqueEnforced( bool enforced ) +{ + mCheckBoxEnforceUnique->setChecked( enforced ); +} + +bool QgsAttributeTypeDialog::uniqueEnforced() const +{ + return mCheckBoxEnforceUnique->isChecked(); +} + void QgsAttributeTypeDialog::setConstraintExpression( const QString &str ) { constraintExpressionWidget->setField( str ); } +void QgsAttributeTypeDialog::setConstraintExpressionEnforced( bool enforced ) +{ + mCheckBoxEnforceExpression->setChecked( enforced ); +} + +bool QgsAttributeTypeDialog::constraintExpressionEnforced() const +{ + return mCheckBoxEnforceExpression->isChecked(); +} + QString QgsAttributeTypeDialog::defaultValueExpression() const { return mExpressionWidget->expression(); diff --git a/src/app/qgsattributetypedialog.h b/src/app/qgsattributetypedialog.h index 5a8ecce5bb93..653ade26643d 100644 --- a/src/app/qgsattributetypedialog.h +++ b/src/app/qgsattributetypedialog.h @@ -85,6 +85,16 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut */ bool notNull() const; + /** + * Sets whether the not null constraint is enforced. + */ + void setNotNullEnforced( bool enforced ); + + /** + * Returns whether the not null constraint should be enforced. + */ + bool notNullEnforced() const; + /** * Setter for unique constraint checkbox */ @@ -95,6 +105,16 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut */ bool unique() const; + /** + * Sets whether the not null constraint is enforced. + */ + void setUniqueEnforced( bool enforced ); + + /** + * Returns whether the not null constraint should be enforced. + */ + bool uniqueEnforced() const; + /** * Setter for constraint expression description * @param desc the expression description @@ -121,6 +141,16 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut */ void setConstraintExpression( const QString &str ); + /** + * Sets whether the expression constraint is enforced. + */ + void setConstraintExpressionEnforced( bool enforced ); + + /** + * Returns whether the expression constraint should be enforced. + */ + bool constraintExpressionEnforced() const; + /** * Returns the expression used for the field's default value, or * an empty string if no default value expression is set. diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index 9ddfc4c370df..88ddc58b44e4 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -559,7 +559,9 @@ void QgsFieldsProperties::attributeTypeDialog() attributeTypeDialog.setFieldEditable( cfg.mEditable ); attributeTypeDialog.setLabelOnTop( cfg.mLabelOnTop ); attributeTypeDialog.setNotNull( cfg.mConstraints & QgsFieldConstraints::ConstraintNotNull ); + attributeTypeDialog.setNotNullEnforced( cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintStrengthHard ) == QgsFieldConstraints::ConstraintStrengthHard ); attributeTypeDialog.setUnique( cfg.mConstraints & QgsFieldConstraints::ConstraintUnique ); + attributeTypeDialog.setUniqueEnforced( cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthHard ) == QgsFieldConstraints::ConstraintStrengthHard ); QgsFieldConstraints constraints = mLayer->fields().at( index ).constraints(); QgsFieldConstraints::Constraints providerConstraints = 0; @@ -573,6 +575,7 @@ void QgsFieldsProperties::attributeTypeDialog() attributeTypeDialog.setConstraintExpression( cfg.mConstraint ); attributeTypeDialog.setConstraintExpressionDescription( cfg.mConstraintDescription ); + attributeTypeDialog.setConstraintExpressionEnforced( cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthHard ) == QgsFieldConstraints::ConstraintStrengthHard ); attributeTypeDialog.setDefaultValueExpression( mLayer->defaultValueExpression( index ) ); attributeTypeDialog.setWidgetConfig( cfg.mEditorWidgetConfig ); @@ -593,6 +596,10 @@ void QgsFieldsProperties::attributeTypeDialog() { cfg.mConstraints |= QgsFieldConstraints::ConstraintUnique; } + if ( !attributeTypeDialog.constraintExpression().isEmpty() && !( providerConstraints & QgsFieldConstraints::ConstraintExpression ) ) + { + cfg.mConstraints |= QgsFieldConstraints::ConstraintExpression; + } cfg.mConstraintDescription = attributeTypeDialog.constraintExpressionDescription(); cfg.mConstraint = attributeTypeDialog.constraintExpression(); @@ -601,6 +608,13 @@ void QgsFieldsProperties::attributeTypeDialog() cfg.mEditorWidgetType = attributeTypeDialog.editorWidgetType(); cfg.mEditorWidgetConfig = attributeTypeDialog.editorWidgetConfig(); + cfg.mConstraintStrength.insert( QgsFieldConstraints::ConstraintNotNull, attributeTypeDialog.notNullEnforced() ? + QgsFieldConstraints::ConstraintStrengthHard : QgsFieldConstraints::ConstraintStrengthSoft ); + cfg.mConstraintStrength.insert( QgsFieldConstraints::ConstraintUnique, attributeTypeDialog.uniqueEnforced() ? + QgsFieldConstraints::ConstraintStrengthHard : QgsFieldConstraints::ConstraintStrengthSoft ); + cfg.mConstraintStrength.insert( QgsFieldConstraints::ConstraintExpression, attributeTypeDialog.constraintExpressionEnforced() ? + QgsFieldConstraints::ConstraintStrengthHard : QgsFieldConstraints::ConstraintStrengthSoft ); + pb->setText( attributeTypeDialog.editorWidgetText() ); setConfigForRow( row, cfg ); @@ -983,7 +997,18 @@ void QgsFieldsProperties::apply() editFormConfig.setWidgetType( name, cfg.mEditorWidgetType ); editFormConfig.setWidgetConfig( name, cfg.mEditorWidgetConfig ); - mLayer->setFieldConstraints( i, cfg.mConstraints ); + if ( cfg.mConstraints & QgsFieldConstraints::ConstraintNotNull ) + { + mLayer->setFieldConstraint( i, QgsFieldConstraints::ConstraintNotNull, cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintStrengthHard ) ); + } + if ( cfg.mConstraints & QgsFieldConstraints::ConstraintUnique ) + { + mLayer->setFieldConstraint( i, QgsFieldConstraints::ConstraintUnique, cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthHard ) ); + } + if ( cfg.mConstraints & QgsFieldConstraints::ConstraintExpression ) + { + mLayer->setFieldConstraint( i, QgsFieldConstraints::ConstraintExpression, cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthHard ) ); + } if ( mFieldsList->item( i, attrWMSCol )->checkState() == Qt::Unchecked ) { @@ -1064,6 +1089,9 @@ QgsFieldsProperties::FieldConfig::FieldConfig( QgsVectorLayer* layer, int idx ) QgsFieldConstraints constraints = layer->fields().at( idx ).constraints(); mConstraints = constraints.constraints(); mConstraint = constraints.constraintExpression(); + mConstraintStrength.insert( QgsFieldConstraints::ConstraintNotNull, constraints.constraintStrength( QgsFieldConstraints::ConstraintNotNull ) ); + mConstraintStrength.insert( QgsFieldConstraints::ConstraintUnique, constraints.constraintStrength( QgsFieldConstraints::ConstraintUnique ) ); + mConstraintStrength.insert( QgsFieldConstraints::ConstraintExpression, constraints.constraintStrength( QgsFieldConstraints::ConstraintExpression ) ); mConstraintDescription = constraints.constraintDescription(); const QgsEditorWidgetSetup setup = QgsEditorWidgetRegistry::instance()->findBest( layer, layer->fields().field( idx ).name() ); mEditorWidgetType = setup.type(); diff --git a/src/app/qgsfieldsproperties.h b/src/app/qgsfieldsproperties.h index ac1f96dd7404..5bcddab6a590 100644 --- a/src/app/qgsfieldsproperties.h +++ b/src/app/qgsfieldsproperties.h @@ -123,6 +123,7 @@ class APP_EXPORT QgsFieldsProperties : public QWidget, private Ui_QgsFieldsPrope bool mEditableEnabled; bool mLabelOnTop; QgsFieldConstraints::Constraints mConstraints; + QHash< QgsFieldConstraints::Constraint, QgsFieldConstraints::ConstraintStrength > mConstraintStrength; QString mConstraint; QString mConstraintDescription; QPushButton* mButton; diff --git a/src/core/qgsfield.cpp b/src/core/qgsfield.cpp index 3203d11b6ec9..5bba6e4905af 100644 --- a/src/core/qgsfield.cpp +++ b/src/core/qgsfield.cpp @@ -317,6 +317,9 @@ QDataStream& operator<<( QDataStream& out, const QgsField& field ) out << static_cast< quint32 >( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) ); out << static_cast< quint32 >( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintUnique ) ); out << static_cast< quint32 >( field.constraints().constraintOrigin( QgsFieldConstraints::ConstraintExpression ) ); + out << static_cast< quint32 >( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintNotNull ) ); + out << static_cast< quint32 >( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintUnique ) ); + out << static_cast< quint32 >( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintExpression ) ); out << field.constraints().constraintExpression(); out << field.constraints().constraintDescription(); out << static_cast< quint32 >( field.subType() ); @@ -325,10 +328,10 @@ QDataStream& operator<<( QDataStream& out, const QgsField& field ) QDataStream& operator>>( QDataStream& in, QgsField& field ) { - quint32 type, subType, length, precision, constraints, originNotNull, originUnique, originExpression; + quint32 type, subType, length, precision, constraints, originNotNull, originUnique, originExpression, strengthNotNull, strengthUnique, strengthExpression; QString name, typeName, comment, alias, defaultValueExpression, constraintExpression, constraintDescription; in >> name >> type >> typeName >> length >> precision >> comment >> alias - >> defaultValueExpression >> constraints >> originNotNull >> originUnique >> originExpression >> + >> defaultValueExpression >> constraints >> originNotNull >> originUnique >> originExpression >> strengthNotNull >> strengthUnique >> strengthExpression >> constraintExpression >> constraintDescription >> subType; field.setName( name ); field.setType( static_cast< QVariant::Type >( type ) ); @@ -340,15 +343,24 @@ QDataStream& operator>>( QDataStream& in, QgsField& field ) field.setDefaultValueExpression( defaultValueExpression ); QgsFieldConstraints fieldConstraints; if ( constraints & QgsFieldConstraints::ConstraintNotNull ) + { fieldConstraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, static_cast< QgsFieldConstraints::ConstraintOrigin>( originNotNull ) ); + fieldConstraints.setConstraintStrength( QgsFieldConstraints::ConstraintNotNull, static_cast< QgsFieldConstraints::ConstraintStrength>( strengthNotNull ) ); + } else fieldConstraints.removeConstraint( QgsFieldConstraints::ConstraintNotNull ); if ( constraints & QgsFieldConstraints::ConstraintUnique ) + { fieldConstraints.setConstraint( QgsFieldConstraints::ConstraintUnique, static_cast< QgsFieldConstraints::ConstraintOrigin>( originUnique ) ); + fieldConstraints.setConstraintStrength( QgsFieldConstraints::ConstraintUnique, static_cast< QgsFieldConstraints::ConstraintStrength>( strengthUnique ) ); + } else fieldConstraints.removeConstraint( QgsFieldConstraints::ConstraintUnique ); if ( constraints & QgsFieldConstraints::ConstraintExpression ) + { fieldConstraints.setConstraint( QgsFieldConstraints::ConstraintExpression, static_cast< QgsFieldConstraints::ConstraintOrigin>( originExpression ) ); + fieldConstraints.setConstraintStrength( QgsFieldConstraints::ConstraintExpression, static_cast< QgsFieldConstraints::ConstraintStrength>( strengthExpression ) ); + } else fieldConstraints.removeConstraint( QgsFieldConstraints::ConstraintExpression ); fieldConstraints.setConstraintExpression( constraintExpression, constraintDescription ); diff --git a/src/core/qgsfieldconstraints.cpp b/src/core/qgsfieldconstraints.cpp index 7594137f39c4..cde40fceb406 100644 --- a/src/core/qgsfieldconstraints.cpp +++ b/src/core/qgsfieldconstraints.cpp @@ -29,17 +29,48 @@ QgsFieldConstraints::ConstraintOrigin QgsFieldConstraints::constraintOrigin( Qgs return mConstraintOrigins.value( constraint, ConstraintOriginNotSet ); } +QgsFieldConstraints::ConstraintStrength QgsFieldConstraints::constraintStrength( QgsFieldConstraints::Constraint constraint ) const +{ + if ( !( mConstraints & constraint ) ) + return ConstraintStrengthNotSet; + + // defaults to hard strength unless explicitly set + return mConstraintStrengths.value( constraint, ConstraintStrengthHard ); +} + +void QgsFieldConstraints::setConstraintStrength( QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength ) +{ + if ( constraintOrigin( constraint ) == ConstraintOriginProvider ) + { + // cannot be overwritten + return; + } + else if ( strength == ConstraintStrengthNotSet ) + { + mConstraintStrengths.remove( constraint ); + } + else + { + mConstraintStrengths.insert( constraint, strength ); + } +} + void QgsFieldConstraints::setConstraint( QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintOrigin origin ) { if ( origin == ConstraintOriginNotSet ) { mConstraints &= ~constraint; mConstraintOrigins.remove( constraint ); + mConstraintStrengths.remove( constraint ); } else { mConstraints |= constraint; mConstraintOrigins.insert( constraint, origin ); + if ( !mConstraintStrengths.contains( constraint ) || origin == ConstraintOriginProvider ) + { + mConstraintStrengths.insert( constraint, ConstraintStrengthHard ); + } } } @@ -65,5 +96,6 @@ void QgsFieldConstraints::setConstraintExpression( const QString& expression, co bool QgsFieldConstraints::operator==( const QgsFieldConstraints& other ) const { return mConstraints == other.mConstraints && mConstraintOrigins == other.mConstraintOrigins - && mExpressionConstraint == other.mExpressionConstraint && mExpressionConstraintDescription == other.mExpressionConstraintDescription; + && mExpressionConstraint == other.mExpressionConstraint && mExpressionConstraintDescription == other.mExpressionConstraintDescription + && mConstraintStrengths == other.mConstraintStrengths; } diff --git a/src/core/qgsfieldconstraints.h b/src/core/qgsfieldconstraints.h index 186cb0be7cb9..03d92e94c5ed 100644 --- a/src/core/qgsfieldconstraints.h +++ b/src/core/qgsfieldconstraints.h @@ -61,8 +61,9 @@ class CORE_EXPORT QgsFieldConstraints */ enum ConstraintStrength { - ConstraintHard = 0, //!< Constraint must be honored before feature can be accepted - ConstraintSoft, //!< User is warned if constraint is violated but feature can still be accepted + ConstraintStrengthNotSet = 0, //!< Constraint is not set + ConstraintStrengthHard, //!< Constraint must be honored before feature can be accepted + ConstraintStrengthSoft, //!< User is warned if constraint is violated but feature can still be accepted }; /** @@ -84,6 +85,22 @@ class CORE_EXPORT QgsFieldConstraints */ ConstraintOrigin constraintOrigin( Constraint constraint ) const; + /** + * Returns the strength of a field constraint, or ConstraintStrengthNotSet if the constraint + * is not present on this field. + * @see constraints() + * @see setConstraintStrength() + */ + ConstraintStrength constraintStrength( Constraint constraint ) const; + + /** + * Sets the strength of a constraint. Note that the strength of constraints which originate + * from a provider cannot be changed. Constraints default to ConstraintStrengthHard unless + * explicitly changed. + * @see constraintStrength() + */ + void setConstraintStrength( Constraint constraint, ConstraintStrength strength ); + /** * Sets a constraint on the field. * @see constraints() @@ -133,6 +150,9 @@ class CORE_EXPORT QgsFieldConstraints //! Origin of field constraints QHash< Constraint, ConstraintOrigin > mConstraintOrigins; + //! Strength of field constraints + QHash< Constraint, ConstraintStrength > mConstraintStrengths; + //! Expression constraint QString mExpressionConstraint; diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index f724bae17c61..89bab5764b48 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -1443,6 +1443,7 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) // constraints mFieldConstraints.clear(); + mFieldConstraintStrength.clear(); QDomNode constraintsNode = layer_node.namedItem( "constraints" ); if ( !constraintsNode.isNull() ) { @@ -1457,6 +1458,14 @@ bool QgsVectorLayer::readXml( const QDomNode& layer_node ) continue; mFieldConstraints.insert( field, static_cast< QgsFieldConstraints::Constraints >( constraints ) ); + + int uniqueStrength = constraintElem.attribute( "unique_strength", QString( "1" ) ).toInt(); + int notNullStrength = constraintElem.attribute( "notnull_strength", QString( "1" ) ).toInt(); + int expStrength = constraintElem.attribute( "exp_strength", QString( "1" ) ).toInt(); + + mFieldConstraintStrength.insert( qMakePair( field, QgsFieldConstraints::ConstraintUnique ), static_cast< QgsFieldConstraints::ConstraintStrength >( uniqueStrength ) ); + mFieldConstraintStrength.insert( qMakePair( field, QgsFieldConstraints::ConstraintNotNull ), static_cast< QgsFieldConstraints::ConstraintStrength >( notNullStrength ) ); + mFieldConstraintStrength.insert( qMakePair( field, QgsFieldConstraints::ConstraintExpression ), static_cast< QgsFieldConstraints::ConstraintStrength >( expStrength ) ); } } mFieldConstraintExpressions.clear(); @@ -1691,6 +1700,9 @@ bool QgsVectorLayer::writeXml( QDomNode & layer_node, QDomElement constraintElem = document.createElement( "constraint" ); constraintElem.setAttribute( "field", field.name() ); constraintElem.setAttribute( "constraints", field.constraints().constraints() ); + constraintElem.setAttribute( "unique_strength", field.constraints().constraintStrength( QgsFieldConstraints::ConstraintUnique ) ); + constraintElem.setAttribute( "notnull_strength", field.constraints().constraintStrength( QgsFieldConstraints::ConstraintNotNull ) ); + constraintElem.setAttribute( "exp_strength", field.constraints().constraintStrength( QgsFieldConstraints::ConstraintExpression ) ); constraintsElem.appendChild( constraintElem ); } layer_node.appendChild( constraintsElem ); @@ -3000,6 +3012,23 @@ void QgsVectorLayer::updateFields() mFields[ index ].setConstraints( constraints ); } + QMap< QPair< QString, QgsFieldConstraints::Constraint >, QgsFieldConstraints::ConstraintStrength >::const_iterator constraintStrengthIt = mFieldConstraintStrength.constBegin(); + for ( ; constraintStrengthIt != mFieldConstraintStrength.constEnd(); ++constraintStrengthIt ) + { + int index = mFields.lookupField( constraintStrengthIt.key().first ); + if ( index < 0 ) + continue; + + QgsFieldConstraints constraints = mFields.at( index ).constraints(); + + // always keep provider constraints intact + if ( constraints.constraintOrigin( QgsFieldConstraints::ConstraintExpression ) == QgsFieldConstraints::ConstraintOriginProvider ) + continue; + + constraints.setConstraintStrength( constraintStrengthIt.key().second, constraintStrengthIt.value() ); + mFields[ index ].setConstraints( constraints ); + } + if ( oldFields != mFields ) { emit updatedFields(); @@ -4305,19 +4334,37 @@ QgsFieldConstraints::Constraints QgsVectorLayer::fieldConstraints( int fieldInde return constraints; } -void QgsVectorLayer::setFieldConstraints( int index, QgsFieldConstraints::Constraints constraints ) +void QgsVectorLayer::setFieldConstraint( int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength ) { if ( index < 0 || index >= mFields.count() ) return; - if ( constraints == 0 ) - { - mFieldConstraints.remove( mFields.at( index ).name() ); - } - else - { - mFieldConstraints.insert( mFields.at( index ).name(), constraints ); - } + QString name = mFields.at( index ).name(); + + // add constraint to existing constraints + QgsFieldConstraints::Constraints constraints = mFieldConstraints.value( name, 0 ); + constraints |= constraint; + mFieldConstraints.insert( name, constraints ); + + mFieldConstraintStrength.insert( qMakePair( name, constraint ), strength ); + + updateFields(); +} + +void QgsVectorLayer::removeFieldConstraint( int index, QgsFieldConstraints::Constraint constraint ) +{ + if ( index < 0 || index >= mFields.count() ) + return; + + QString name = mFields.at( index ).name(); + + // remove constraint from existing constraints + QgsFieldConstraints::Constraints constraints = mFieldConstraints.value( name, 0 ); + constraints &= ~constraint; + mFieldConstraints.insert( name, constraints ); + + mFieldConstraintStrength.remove( qMakePair( name, constraint ) ); + updateFields(); } diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 7440bb343231..3c5255de8fc1 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1402,18 +1402,28 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * field index. These constraints may be inherited from the layer's data provider * or may be set manually on the vector layer from within QGIS. * @note added in QGIS 3.0 - * @see setFieldConstraints() + * @see setFieldConstraint() */ QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; /** - * Sets the constraints for a specified field index. Any constraints inherited from the layer's - * data provider will be kept intact and cannot be cleared. Ie, calling this method only allows for new + * Sets a constraint for a specified field index. Any constraints inherited from the layer's + * data provider will be kept intact and cannot be modified. Ie, calling this method only allows for new * constraints to be added on top of the existing provider constraints. * @note added in QGIS 3.0 * @see fieldConstraints() + * @see removeFieldConstraint() */ - void setFieldConstraints( int index, QgsFieldConstraints::Constraints constraints ); + void setFieldConstraint( int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthHard ); + + /** + * Removes a constraint for a specified field index. Any constraints inherited from the layer's + * data provider will be kept intact and cannot be removed. + * @note added in QGIS 3.0 + * @see fieldConstraints() + * @see setFieldConstraint() + */ + void removeFieldConstraint( int index, QgsFieldConstraints::Constraint constraint ); /** * Returns the constraint expression for for a specified field index, if set. @@ -1983,6 +1993,9 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte //! Map which stores constraints for fields QMap< QString, QgsFieldConstraints::Constraints > mFieldConstraints; + //! Map which stores constraint strength for fields + QMap< QPair< QString, QgsFieldConstraints::Constraint >, QgsFieldConstraints::ConstraintStrength > mFieldConstraintStrength; + //! Map which stores expression constraints for fields. Value is a pair of expression/description. QMap< QString, QPair< QString, QString > > mFieldConstraintExpressions; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp index c646df772b99..9b794da3e42e 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp @@ -266,7 +266,7 @@ void QgsEditorWidgetRegistry::readMapLayer( QgsMapLayer* mapLayer, const QDomEle if ( ewv2CfgElem.attribute( QStringLiteral( "notNull" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ) { // upgrade from older config - vectorLayer->setFieldConstraints( idx, vectorLayer->fieldConstraints( idx ) | QgsFieldConstraints::ConstraintNotNull ); + vectorLayer->setFieldConstraint( idx, QgsFieldConstraints::ConstraintNotNull ); } if ( !ewv2CfgElem.attribute( QStringLiteral( "constraint" ), QString() ).isEmpty() ) { diff --git a/src/ui/qgsattributetypeedit.ui b/src/ui/qgsattributetypeedit.ui index bae9edc17726..4ffdb747d411 100644 --- a/src/ui/qgsattributetypeedit.ui +++ b/src/ui/qgsattributetypeedit.ui @@ -22,58 +22,84 @@ Constraints - - + + + + + Unique + + + + Not null - - + + + + false + + + Enforcing the unique constraint prevents committing features which do not meet the constraint. Unenforced constraints display a warning to users, but do not prevent committing the feature. + - Unique + Enforce unique constraint - - - - 0 - - - - - Constraint - - - - - - - Qt::StrongFocus - - - - + + + + Qt::StrongFocus + + - - - - 0 - - - - - Constraint description - - - - - - - + + + + Expression description + + + + + + + Optional descriptive name for expression constraint + + + + + + + false + + + Enforcing the not null constraint prevents committing features which do not meet the constraint. Unenforced constraints display a warning to users, but do not prevent committing the feature. + + + Enforce not null constraint + + + + + + + Expression + + + + + + + Enforcing the expression constraint prevents committing features which do not meet the constraint. Unenforced constraints display a warning to users, but do not prevent committing the feature. + + + Enforce expression constraint + + @@ -176,9 +202,12 @@ labelOnTopCheckBox mExpressionWidget notNullCheckBox + mCheckBoxEnforceNotNull mUniqueCheckBox + mCheckBoxEnforceUnique constraintExpressionWidget leConstraintExpressionDescription + mCheckBoxEnforceExpression diff --git a/tests/src/core/testqgsfield.cpp b/tests/src/core/testqgsfield.cpp index d255973d674e..bff356d3b3c2 100644 --- a/tests/src/core/testqgsfield.cpp +++ b/tests/src/core/testqgsfield.cpp @@ -87,6 +87,7 @@ void TestQgsField::copy() QgsFieldConstraints constraints; constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthSoft ); original.setConstraints( constraints ); QgsField copy( original ); QVERIFY( copy == original ); @@ -102,6 +103,7 @@ void TestQgsField::assignment() QgsFieldConstraints constraints; constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthSoft ); original.setConstraints( constraints ); QgsField copy; copy = original; @@ -153,6 +155,20 @@ void TestQgsField::gettersSetters() QCOMPARE( field.constraints().constraintExpression(), QStringLiteral( "constraint expression" ) ); QCOMPARE( field.constraints().constraintDescription(), QStringLiteral( "description" ) ); QCOMPARE( field.constraints().constraints(), QgsFieldConstraints::ConstraintUnique | QgsFieldConstraints::ConstraintExpression ); //setting constraint expression should add constraint + constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + + // check a constraint strength which hasn't been set + QCOMPARE( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintNotNull ), QgsFieldConstraints::ConstraintStrengthNotSet ); + // check a constraint strength which has not been explicitly set + QCOMPARE( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintUnique ), QgsFieldConstraints::ConstraintStrengthHard ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthSoft ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintUnique ), QgsFieldConstraints::ConstraintStrengthSoft ); + // try overwriting a provider constraint's strength + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthSoft ); + field.setConstraints( constraints ); + QCOMPARE( field.constraints().constraintStrength( QgsFieldConstraints::ConstraintUnique ), QgsFieldConstraints::ConstraintStrengthHard ); } void TestQgsField::isNumeric() @@ -249,9 +265,14 @@ void TestQgsField::equality() field2.setConstraints( constraints ); QVERIFY( !( field1 == field2 ) ); QVERIFY( field1 != field2 ); - constraints = field2.constraints(); - constraints.setConstraintExpression( QString(), QString() ); + constraints = QgsFieldConstraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthHard ); field2.setConstraints( constraints ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthSoft ); + field1.setConstraints( constraints ); + QVERIFY( !( field1 == field2 ) ); + QVERIFY( field1 != field2 ); } void TestQgsField::asVariant() @@ -442,6 +463,7 @@ void TestQgsField::dataStream() constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginLayer ); constraints.setConstraintExpression( QStringLiteral( "constraint expression" ), QStringLiteral( "description" ) ); + constraints.setConstraintStrength( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthSoft ); original.setConstraints( constraints ); QByteArray ba; diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 597efdee3f66..1480199911c2 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1782,37 +1782,51 @@ def testGetSetConstraints(self): self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) - layer.setFieldConstraints(0, QgsFieldConstraints.ConstraintNotNull) + layer.setFieldConstraint(0, QgsFieldConstraints.ConstraintNotNull) self.assertEqual(layer.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) self.assertEqual(layer.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) self.assertEqual(layer.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(0).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthHard) - layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintNotNull) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintUnique) self.assertEqual(layer.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) self.assertEqual(layer.fieldConstraints(1), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) self.assertFalse(layer.fieldConstraints(2)) self.assertEqual(layer.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) self.assertEqual(layer.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(0).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthHard) self.assertEqual(layer.fields().at(1).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) self.assertEqual(layer.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginLayer) self.assertEqual(layer.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(1).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthHard) + self.assertEqual(layer.fields().at(1).constraints().constraintStrength(QgsFieldConstraints.ConstraintUnique), + QgsFieldConstraints.ConstraintStrengthHard) - layer.setFieldConstraints(1, QgsFieldConstraints.Constraints()) + layer.removeFieldConstraint(1, QgsFieldConstraints.ConstraintNotNull) + layer.removeFieldConstraint(1, QgsFieldConstraints.ConstraintUnique) self.assertEqual(layer.fieldConstraints(0), QgsFieldConstraints.ConstraintNotNull) self.assertFalse(layer.fieldConstraints(1)) self.assertFalse(layer.fieldConstraints(2)) self.assertEqual(layer.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) self.assertEqual(layer.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(0).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthHard) self.assertFalse(layer.fields().at(1).constraints().constraints()) self.assertEqual(layer.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginNotSet) + self.assertEqual(layer.fields().at(1).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthNotSet) def testSaveRestoreConstraints(self): """ test saving and restoring constraints from xml""" @@ -1829,8 +1843,9 @@ def testSaveRestoreConstraints(self): self.assertFalse(layer2.fieldConstraints(1)) # set some constraints - layer.setFieldConstraints(0, QgsFieldConstraints.ConstraintNotNull) - layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) + layer.setFieldConstraint(0, QgsFieldConstraints.ConstraintNotNull) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintNotNull, QgsFieldConstraints.ConstraintStrengthSoft) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintUnique) doc = QDomDocument("testdoc") elem = doc.createElement("maplayer") @@ -1843,11 +1858,17 @@ def testSaveRestoreConstraints(self): self.assertEqual(layer3.fields().at(0).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull) self.assertEqual(layer3.fields().at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(0).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthHard) self.assertEqual(layer3.fields().at(1).constraints().constraints(), QgsFieldConstraints.ConstraintNotNull | QgsFieldConstraints.ConstraintUnique) self.assertEqual(layer3.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginLayer) self.assertEqual(layer3.fields().at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginLayer) + self.assertEqual(layer.fields().at(1).constraints().constraintStrength(QgsFieldConstraints.ConstraintNotNull), + QgsFieldConstraints.ConstraintStrengthSoft) + self.assertEqual(layer.fields().at(1).constraints().constraintStrength(QgsFieldConstraints.ConstraintUnique), + QgsFieldConstraints.ConstraintStrengthHard) def testGetSetConstraintExpressions(self): """ test getting and setting field constraint expressions """ From 3f2a7810cf4610e253a75118fed671aaed78ff66 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 13:39:07 +1000 Subject: [PATCH 588/897] Respect non-enforced constraints when editing/adding features Warnings are shown, but features can be committed. Fields which fail an unenforced constraint are now shaded in yellow to differentiate from the red failure for enforced constraints. --- python/core/qgsvectorlayerutils.sip | 3 +- .../core/qgseditorwidgetwrapper.sip | 29 ++++++++++++- .../qgsrelationreferencewidgetwrapper.sip | 14 +------ src/core/qgsvectorlayerutils.cpp | 6 ++- src/core/qgsvectorlayerutils.h | 3 +- .../core/qgseditorwidgetwrapper.cpp | 42 +++++++++++++++---- .../core/qgseditorwidgetwrapper.h | 30 +++++++++++-- .../editorwidgets/qgscolorwidgetwrapper.cpp | 2 +- src/gui/editorwidgets/qgscolorwidgetwrapper.h | 2 +- .../qgsexternalresourcewidgetwrapper.cpp | 20 ++++++--- .../qgsexternalresourcewidgetwrapper.h | 2 +- .../qgsfilenamewidgetwrapper.cpp | 18 +++++--- .../editorwidgets/qgsfilenamewidgetwrapper.h | 2 +- .../qgskeyvaluewidgetwrapper.cpp | 2 +- .../editorwidgets/qgskeyvaluewidgetwrapper.h | 2 +- .../editorwidgets/qgslistwidgetwrapper.cpp | 4 +- src/gui/editorwidgets/qgslistwidgetwrapper.h | 2 +- .../editorwidgets/qgsphotowidgetwrapper.cpp | 18 +++++--- src/gui/editorwidgets/qgsphotowidgetwrapper.h | 2 +- .../qgsrelationreferencewidgetwrapper.cpp | 20 ++++++--- .../qgsrelationreferencewidgetwrapper.h | 14 +------ .../editorwidgets/qgswebviewwidgetwrapper.cpp | 18 +++++--- .../editorwidgets/qgswebviewwidgetwrapper.h | 2 +- src/gui/qgsattributeform.cpp | 27 +++++++----- src/gui/qgsattributeform.h | 4 +- tests/src/gui/testqgsattributeform.cpp | 36 ++++++++++++++++ tests/src/python/test_qgsvectorlayerutils.py | 26 ++++++++---- 27 files changed, 255 insertions(+), 95 deletions(-) diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip index 4d897f64edfa..f5a9e5da674d 100644 --- a/python/core/qgsvectorlayerutils.sip +++ b/python/core/qgsvectorlayerutils.sip @@ -22,9 +22,10 @@ class QgsVectorLayerUtils /** * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. - * If the origin parameter is set then only constraints with a matching origin will be checked. + * If the strength or origin parameter is set then only constraints with a matching strength/origin will be checked. */ static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors /Out/, + QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); }; diff --git a/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip b/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip index 5bdcbddd7987..0cc4dba98b54 100644 --- a/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip +++ b/python/gui/editorwidgets/core/qgseditorwidgetwrapper.sip @@ -20,6 +20,18 @@ class QgsEditorWidgetWrapper : QgsWidgetWrapper %End public: + + /** + * Result of constraint checks. + * @note added in QGIS 3.0 + */ + enum ConstraintResult + { + ConstraintResultPass, //!< Widget passed constraints successfully + ConstraintResultFailHard, //!< Widget failed at least one hard (enforced) constraint + ConstraintResultFailSoft, //!< Widget failed at least one soft (non-enforced) constraint + }; + /** * Create a new widget wrapper * @@ -108,9 +120,18 @@ class QgsEditorWidgetWrapper : QgsWidgetWrapper * false otherwise * @note added in QGIS 2.16 * @see constraintFailureReason() + * @see isBlockingCommit() */ bool isValidConstraint() const; + /** + * Returns true if the widget is preventing the feature from being committed. This may be true as a result + * of attribute values failing enforced field constraints. + * @note added in QGIS 3.0 + * @see isValidConstraint() + */ + bool isBlockingCommit() const; + /** * Returns the reason why a constraint check has failed (or an empty string * if constraint check was successful). @@ -135,7 +156,7 @@ class QgsEditorWidgetWrapper : QgsWidgetWrapper * @param err the error represented as a string. Empty if none. * @param status */ - void constraintStatusChanged( const QString& constraint, const QString& err, bool status ); + void constraintStatusChanged( const QString& constraint, const QString &desc, const QString& err, ConstraintResult status ); public slots: /** @@ -214,6 +235,10 @@ class QgsEditorWidgetWrapper : QgsWidgetWrapper * * This can be overwritten in subclasses to allow individual widgets to * change the visual cue. + * + * @param status The current constraint status. + * + * @note added in QGIS 2.16 */ - virtual void updateConstraintWidgetStatus( bool contraintValid ); + virtual void updateConstraintWidgetStatus( ConstraintResult status ); }; diff --git a/python/gui/editorwidgets/qgsrelationreferencewidgetwrapper.sip b/python/gui/editorwidgets/qgsrelationreferencewidgetwrapper.sip index 2c609b32f150..081de62a3c5e 100644 --- a/python/gui/editorwidgets/qgsrelationreferencewidgetwrapper.sip +++ b/python/gui/editorwidgets/qgsrelationreferencewidgetwrapper.sip @@ -23,16 +23,6 @@ class QgsRelationReferenceWidgetWrapper : QgsEditorWidgetWrapper virtual void setEnabled( bool enabled ); protected: - /** - * This should update the widget with a visual cue if a constraint status - * changed. - * - * By default a stylesheet will be applied on the widget that changes the - * background color to red. - * - * This can be overwritten in subclasses to allow individual widgets to - * change the visual cue. - * @note added in QGIS 2.16 - */ - void updateConstraintWidgetStatus( bool constraintValid ); + + void updateConstraintWidgetStatus( ConstraintResult status ); }; diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index d92fa54c9f30..29653a98bac0 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -50,7 +50,8 @@ bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldInd return false; } -bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, QgsFieldConstraints::ConstraintOrigin origin ) +bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, + QgsFieldConstraints::ConstraintStrength strength, QgsFieldConstraints::ConstraintOrigin origin ) { if ( !layer ) return false; @@ -66,6 +67,7 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFieldConstraints constraints = field.constraints(); if ( constraints.constraints() & QgsFieldConstraints::ConstraintExpression && !constraints.constraintExpression().isEmpty() + && ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintExpression ) ) && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintExpression ) ) ) { QgsExpressionContext context = layer->createExpressionContext(); @@ -90,6 +92,7 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const } if ( constraints.constraints() & QgsFieldConstraints::ConstraintNotNull + && ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintNotNull ) ) && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) ) ) { valid = valid && !value.isNull(); @@ -101,6 +104,7 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const } if ( constraints.constraints() & QgsFieldConstraints::ConstraintUnique + && ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintUnique ) ) && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintUnique ) ) ) { bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() ); diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h index 8320acee9aae..5d2ae5984f65 100644 --- a/src/core/qgsvectorlayerutils.h +++ b/src/core/qgsvectorlayerutils.h @@ -39,9 +39,10 @@ class CORE_EXPORT QgsVectorLayerUtils /** * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. - * If the origin parameter is set then only constraints with a matching origin will be checked. + * If the strength or origin parameter is set then only constraints with a matching strength/origin will be checked. */ static bool validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, + QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); }; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index 661e68909cbb..d12381f95d2a 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -24,6 +24,7 @@ QgsEditorWidgetWrapper::QgsEditorWidgetWrapper( QgsVectorLayer* vl, int fieldIdx, QWidget* editor, QWidget* parent ) : QgsWidgetWrapper( vl, editor, parent ) , mValidConstraint( true ) + , mIsBlockingCommit( false ) , mFieldIdx( fieldIdx ) { } @@ -98,12 +99,22 @@ void QgsEditorWidgetWrapper::valueChanged() emit valueChanged( value() ); } -void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) +void QgsEditorWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult constraintResult ) { - if ( constraintValid ) - widget()->setStyleSheet( QString() ); - else - widget()->setStyleSheet( QStringLiteral( "background-color: #dd7777;" ) ); + switch ( constraintResult ) + { + case ConstraintResultPass: + widget()->setStyleSheet( QString() ); + break; + + case ConstraintResultFailHard: + widget()->setStyleSheet( QStringLiteral( "background-color: #dd7777;" ) ); + break; + + case ConstraintResultFailSoft: + widget()->setStyleSheet( QStringLiteral( "background-color: #ffd85d;" ) ); + break; + } } void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsFieldConstraints::ConstraintOrigin constraintOrigin ) @@ -150,7 +161,15 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsFieldCon } QStringList errors; - mValidConstraint = QgsVectorLayerUtils::validateAttribute( layer(), ft, mFieldIdx, errors, constraintOrigin ); + bool hardConstraintsOk = QgsVectorLayerUtils::validateAttribute( layer(), ft, mFieldIdx, errors, QgsFieldConstraints::ConstraintStrengthHard, constraintOrigin ); + + QStringList softErrors; + bool softConstraintsOk = QgsVectorLayerUtils::validateAttribute( layer(), ft, mFieldIdx, softErrors, QgsFieldConstraints::ConstraintStrengthSoft, constraintOrigin ); + errors << softErrors; + + mValidConstraint = hardConstraintsOk && softConstraintsOk; + mIsBlockingCommit = !hardConstraintsOk; + mConstraintFailureReason = errors.join( ", " ); if ( toEmit ) @@ -164,8 +183,10 @@ void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft, QgsFieldCon else if ( !expressions.isEmpty() ) expressionDesc = expressions.at( 0 ); - updateConstraintWidgetStatus( mValidConstraint ); - emit constraintStatusChanged( expressionDesc, description, errStr, mValidConstraint ); + ConstraintResult result = !hardConstraintsOk ? ConstraintResultFailHard + : ( !softConstraintsOk ? ConstraintResultFailSoft : ConstraintResultPass ); + updateConstraintWidgetStatus( result ); + emit constraintStatusChanged( expressionDesc, description, errStr, result ); } } @@ -174,6 +195,11 @@ bool QgsEditorWidgetWrapper::isValidConstraint() const return mValidConstraint; } +bool QgsEditorWidgetWrapper::isBlockingCommit() const +{ + return mIsBlockingCommit; +} + QString QgsEditorWidgetWrapper::constraintFailureReason() const { return mConstraintFailureReason; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h index 9719d4fc6042..49602e733934 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h @@ -40,6 +40,18 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper { Q_OBJECT public: + + /** + * Result of constraint checks. + * @note added in QGIS 3.0 + */ + enum ConstraintResult + { + ConstraintResultPass = 0, //!< Widget passed constraints successfully + ConstraintResultFailHard, //!< Widget failed at least one hard (enforced) constraint + ConstraintResultFailSoft, //!< Widget failed at least one soft (non-enforced) constraint + }; + /** * Create a new widget wrapper * @@ -130,9 +142,18 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper * false otherwise * @note added in QGIS 2.16 * @see constraintFailureReason() + * @see isBlockingCommit() */ bool isValidConstraint() const; + /** + * Returns true if the widget is preventing the feature from being committed. This may be true as a result + * of attribute values failing enforced field constraints. + * @note added in QGIS 3.0 + * @see isValidConstraint() + */ + bool isBlockingCommit() const; + /** * Returns the reason why a constraint check has failed (or an empty string * if constraint check was successful). @@ -157,7 +178,7 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper * @param err the error represented as a string. Empty if none. * @param status */ - void constraintStatusChanged( const QString& constraint, const QString &desc, const QString& err, bool status ); + void constraintStatusChanged( const QString& constraint, const QString &desc, const QString& err, ConstraintResult status ); public slots: /** @@ -237,11 +258,11 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper * This can be overwritten in subclasses to allow individual widgets to * change the visual cue. * - * @param constraintValid The current constraint status. + * @param status The current constraint status. * * @note added in QGIS 2.16 */ - virtual void updateConstraintWidgetStatus( bool constraintValid ); + virtual void updateConstraintWidgetStatus( ConstraintResult status ); private: @@ -250,6 +271,9 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper */ bool mValidConstraint; + //! True if widget is blocking feature commits + bool mIsBlockingCommit; + //! Contains the string explanation of why a constraint check failed QString mConstraintFailureReason; diff --git a/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp b/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp index 7b734edbba50..1533a8ce2635 100644 --- a/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgscolorwidgetwrapper.cpp @@ -80,7 +80,7 @@ void QgsColorWidgetWrapper::setValue( const QVariant& value ) mColorButton->setColor( !value.isNull() ? QColor( value.toString() ) : QColor() ); } -void QgsColorWidgetWrapper::updateConstraintWidgetStatus( bool /*constraintValid*/ ) +void QgsColorWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult /*constraintValid*/ ) { // nothing } diff --git a/src/gui/editorwidgets/qgscolorwidgetwrapper.h b/src/gui/editorwidgets/qgscolorwidgetwrapper.h index 3f2833f9beac..5a2f423f05d6 100644 --- a/src/gui/editorwidgets/qgscolorwidgetwrapper.h +++ b/src/gui/editorwidgets/qgscolorwidgetwrapper.h @@ -45,7 +45,7 @@ class GUI_EXPORT QgsColorWidgetWrapper : public QgsEditorWidgetWrapper void setValue( const QVariant& value ) override; private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; QgsColorButton* mColorButton; }; diff --git a/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp b/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp index bd92f448a0f9..ccac4d02b8da 100644 --- a/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.cpp @@ -188,13 +188,23 @@ void QgsExternalResourceWidgetWrapper::setEnabled( bool enabled ) mQgsWidget->setReadOnly( !enabled ); } -void QgsExternalResourceWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) +void QgsExternalResourceWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult status ) { if ( mLineEdit ) { - if ( constraintValid ) - mLineEdit->setStyleSheet( QString() ); - else - mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + switch ( status ) + { + case ConstraintResultPass: + mLineEdit->setStyleSheet( QString() ); + break; + + case ConstraintResultFailHard: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + break; + + case ConstraintResultFailSoft: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #ffd85d; }" ) ); + break; + } } } diff --git a/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.h b/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.h index c0314a5641f3..0ba07a328dcf 100644 --- a/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.h +++ b/src/gui/editorwidgets/qgsexternalresourcewidgetwrapper.h @@ -54,7 +54,7 @@ class GUI_EXPORT QgsExternalResourceWidgetWrapper : public QgsEditorWidgetWrappe void setEnabled( bool enabled ) override; private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; QLineEdit* mLineEdit; QLabel* mLabel; diff --git a/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp b/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp index fd94432213ba..55d8c0db5f37 100644 --- a/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsfilenamewidgetwrapper.cpp @@ -152,15 +152,23 @@ void QgsFileNameWidgetWrapper::selectFileName() mLineEdit->setText( fileName ); } -void QgsFileNameWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) +void QgsFileNameWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult status ) { if ( mLineEdit ) { - if ( constraintValid ) - mLineEdit->setStyleSheet( QString() ); - else + switch ( status ) { - mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + case ConstraintResultPass: + mLineEdit->setStyleSheet( QString() ); + break; + + case ConstraintResultFailHard: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + break; + + case ConstraintResultFailSoft: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #ffd85d; }" ) ); + break; } } } diff --git a/src/gui/editorwidgets/qgsfilenamewidgetwrapper.h b/src/gui/editorwidgets/qgsfilenamewidgetwrapper.h index 1a609781f8b9..f5d59b5ae66e 100644 --- a/src/gui/editorwidgets/qgsfilenamewidgetwrapper.h +++ b/src/gui/editorwidgets/qgsfilenamewidgetwrapper.h @@ -51,7 +51,7 @@ class GUI_EXPORT QgsFileNameWidgetWrapper : public QgsEditorWidgetWrapper void setValue( const QVariant& value ) override; private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; QLineEdit* mLineEdit; QPushButton* mPushButton; diff --git a/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.cpp b/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.cpp index 109d04077811..a10c61b87e09 100644 --- a/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.cpp @@ -72,7 +72,7 @@ void QgsKeyValueWidgetWrapper::setValue( const QVariant& value ) mWidget->setMap( value.toMap() ); } -void QgsKeyValueWidgetWrapper::updateConstraintWidgetStatus( bool /*constraintValid*/ ) +void QgsKeyValueWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult /*constraintValid*/ ) { // Nothing } diff --git a/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h b/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h index 1773437155b6..58b28bed5120 100644 --- a/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h +++ b/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h @@ -51,7 +51,7 @@ class GUI_EXPORT QgsKeyValueWidgetWrapper : public QgsEditorWidgetWrapper void onValueChanged(); private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; QgsKeyValueWidget* mWidget; }; diff --git a/src/gui/editorwidgets/qgslistwidgetwrapper.cpp b/src/gui/editorwidgets/qgslistwidgetwrapper.cpp index 48ac0bed3f13..f30e5c55edae 100644 --- a/src/gui/editorwidgets/qgslistwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgslistwidgetwrapper.cpp @@ -87,7 +87,7 @@ void QgsListWidgetWrapper::onValueChanged() emit valueChanged( value() ); } -void QgsListWidgetWrapper::updateConstraintWidgetStatus( bool /*constraintValid*/ ) +void QgsListWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult /*constraintValid*/ ) { // Nothing -} \ No newline at end of file +} diff --git a/src/gui/editorwidgets/qgslistwidgetwrapper.h b/src/gui/editorwidgets/qgslistwidgetwrapper.h index cae71b7b793e..47a745135d13 100644 --- a/src/gui/editorwidgets/qgslistwidgetwrapper.h +++ b/src/gui/editorwidgets/qgslistwidgetwrapper.h @@ -51,7 +51,7 @@ class GUI_EXPORT QgsListWidgetWrapper : public QgsEditorWidgetWrapper void onValueChanged(); private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; QgsListWidget* mWidget; }; diff --git a/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp b/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp index 75232eb3322f..fe4017ae8c83 100644 --- a/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsphotowidgetwrapper.cpp @@ -267,15 +267,23 @@ void QgsPhotoWidgetWrapper::setEnabled( bool enabled ) mButton->setEnabled( enabled ); } -void QgsPhotoWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) +void QgsPhotoWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult status ) { if ( mLineEdit ) { - if ( constraintValid ) - mLineEdit->setStyleSheet( QString() ); - else + switch ( status ) { - mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + case ConstraintResultPass: + mLineEdit->setStyleSheet( QString() ); + break; + + case ConstraintResultFailHard: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + break; + + case ConstraintResultFailSoft: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #ffd85d; }" ) ); + break; } } } diff --git a/src/gui/editorwidgets/qgsphotowidgetwrapper.h b/src/gui/editorwidgets/qgsphotowidgetwrapper.h index ce62f4bc32f7..037e460ef1fc 100644 --- a/src/gui/editorwidgets/qgsphotowidgetwrapper.h +++ b/src/gui/editorwidgets/qgsphotowidgetwrapper.h @@ -65,7 +65,7 @@ class GUI_EXPORT QgsPhotoWidgetWrapper : public QgsEditorWidgetWrapper void loadPixmap( const QString& fileName ); private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; //! This label is used as a container to display the picture QLabel* mPhotoLabel; diff --git a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp index 6d5db05fa422..de6d0761e1e6 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp @@ -143,13 +143,23 @@ void QgsRelationReferenceWidgetWrapper::foreignKeyChanged( QVariant value ) emit valueChanged( value ); } -void QgsRelationReferenceWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) +void QgsRelationReferenceWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult status ) { if ( mWidget ) { - if ( constraintValid ) - mWidget->setStyleSheet( QString() ); - else - mWidget->setStyleSheet( QStringLiteral( ".QComboBox { background-color: #dd7777; }" ) ); + switch ( status ) + { + case ConstraintResultPass: + mWidget->setStyleSheet( QString() ); + break; + + case ConstraintResultFailHard: + mWidget->setStyleSheet( QStringLiteral( ".QComboBox { background-color: #dd7777; }" ) ); + break; + + case ConstraintResultFailSoft: + mWidget->setStyleSheet( QStringLiteral( ".QComboBox { background-color: #ffd85d; }" ) ); + break; + } } } diff --git a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.h b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.h index e12c8ef16fe2..c192d56765dd 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.h +++ b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.h @@ -62,18 +62,8 @@ class GUI_EXPORT QgsRelationReferenceWidgetWrapper : public QgsEditorWidgetWrapp void foreignKeyChanged( QVariant value ); protected: - /** - * This should update the widget with a visual cue if a constraint status - * changed. - * - * By default a stylesheet will be applied on the widget that changes the - * background color to red. - * - * This can be overwritten in subclasses to allow individual widgets to - * change the visual cue. - * @note added in QGIS 2.16 - */ - void updateConstraintWidgetStatus( bool constraintValid ) override; + + void updateConstraintWidgetStatus( ConstraintResult status ) override; private: QgsRelationReferenceWidget* mWidget; diff --git a/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp b/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp index 837d618e98ea..58bcf3d74658 100644 --- a/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgswebviewwidgetwrapper.cpp @@ -190,15 +190,23 @@ void QgsWebViewWidgetWrapper::selectFileName() mLineEdit->setText( filePath ); } -void QgsWebViewWidgetWrapper::updateConstraintWidgetStatus( bool constraintValid ) +void QgsWebViewWidgetWrapper::updateConstraintWidgetStatus( ConstraintResult status ) { if ( mLineEdit ) { - if ( constraintValid ) - mLineEdit->setStyleSheet( QString() ); - else + switch ( status ) { - mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + case ConstraintResultPass: + mLineEdit->setStyleSheet( QString() ); + break; + + case ConstraintResultFailHard: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #dd7777; }" ) ); + break; + + case ConstraintResultFailSoft: + mLineEdit->setStyleSheet( QStringLiteral( "QgsFilterLineEdit { background-color: #ffd85d; }" ) ); + break; } } } diff --git a/src/gui/editorwidgets/qgswebviewwidgetwrapper.h b/src/gui/editorwidgets/qgswebviewwidgetwrapper.h index 8aae25443116..810bb24a0c63 100644 --- a/src/gui/editorwidgets/qgswebviewwidgetwrapper.h +++ b/src/gui/editorwidgets/qgswebviewwidgetwrapper.h @@ -53,7 +53,7 @@ class GUI_EXPORT QgsWebViewWidgetWrapper : public QgsEditorWidgetWrapper void selectFileName(); private: - void updateConstraintWidgetStatus( bool constraintValid ) override; + void updateConstraintWidgetStatus( ConstraintResult status ) override; //! This label is used as a container to display the picture QWebView* mWebView; diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 61738ee60a9a..9f415c5cf442 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -813,7 +813,8 @@ bool QgsAttributeForm::currentFormValidConstraints( QStringList &invalidFields, descriptions.append( eww->constraintFailureReason() ); - valid = false; // continue to get all invalif fields + if ( eww->isBlockingCommit() ) + valid = false; // continue to get all invalid fields } } } @@ -879,7 +880,7 @@ void QgsAttributeForm::onUpdatedFields() } void QgsAttributeForm::onConstraintStatusChanged( const QString& constraint, - const QString &description, const QString& err, bool ok ) + const QString &description, const QString& err, QgsEditorWidgetWrapper::ConstraintResult result ) { QgsEditorWidgetWrapper* eww = qobject_cast( sender() ); Q_ASSERT( eww ); @@ -898,15 +899,19 @@ void QgsAttributeForm::onConstraintStatusChanged( const QString& constraint, QString text = buddy->property( "originalText" ).toString(); - if ( !ok ) + switch ( result ) { - // not good - buddy->setText( QStringLiteral( "%1" ).arg( text ) ); - } - else - { - // good - buddy->setText( QStringLiteral( "%1" ).arg( text ) ); + case QgsEditorWidgetWrapper::ConstraintResultFailHard: + buddy->setText( QStringLiteral( "%1" ).arg( text ) ); + break; + + case QgsEditorWidgetWrapper::ConstraintResultFailSoft: + buddy->setText( QStringLiteral( "%1" ).arg( text ) ); + break; + + case QgsEditorWidgetWrapper::ConstraintResultPass: + buddy->setText( QStringLiteral( "%1" ).arg( text ) ); + break; } } } @@ -991,7 +996,7 @@ void QgsAttributeForm::synchronizeEnabledState() QStringList invalidFields, descriptions; bool validConstraint = currentFormValidConstraints( invalidFields, descriptions ); - if ( ! validConstraint ) + if ( ! invalidFields.isEmpty() ) displayInvalidConstraintMessage( invalidFields, descriptions ); isEditable = isEditable & validConstraint; diff --git a/src/gui/qgsattributeform.h b/src/gui/qgsattributeform.h index c584f327a135..ecf8026546d4 100644 --- a/src/gui/qgsattributeform.h +++ b/src/gui/qgsattributeform.h @@ -18,11 +18,13 @@ #include "qgsfeature.h" #include "qgsattributeeditorcontext.h" +#include "qgseditorwidgetwrapper.h" #include #include #include + class QgsAttributeFormInterface; class QgsAttributeFormEditorWidget; class QgsMessageBar; @@ -232,7 +234,7 @@ class GUI_EXPORT QgsAttributeForm : public QWidget void onAttributeDeleted( int idx ); void onUpdatedFields(); void onConstraintStatusChanged( const QString& constraint, - const QString &description, const QString& err, bool ok ); + const QString &description, const QString& err, QgsEditorWidgetWrapper::ConstraintResult result ); void preventFeatureRefresh(); void synchronizeEnabledState(); void layerSelectionChanged(); diff --git a/tests/src/gui/testqgsattributeform.cpp b/tests/src/gui/testqgsattributeform.cpp index c8f07ada49d6..88b0655bf1ff 100644 --- a/tests/src/gui/testqgsattributeform.cpp +++ b/tests/src/gui/testqgsattributeform.cpp @@ -80,6 +80,7 @@ void TestQgsAttributeForm::testFieldConstraint() // testing stuff QString validLabel = QStringLiteral( "col0" ); QString invalidLabel = QStringLiteral( "col0" ); + QString warningLabel = QStringLiteral( "col0" ); // set constraint layer->setConstraintExpression( 0, QString() ); @@ -117,6 +118,27 @@ void TestQgsAttributeForm::testFieldConstraint() ww->setValue( 1 ); QCOMPARE( spy.count(), 2 ); QCOMPARE( label->text(), validLabel ); + + // set a soft constraint + layer->setConstraintExpression( 0, QStringLiteral( "col0 is not null" ) ); + layer->setFieldConstraint( 0, QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthSoft ); + // build a form for this feature + QgsAttributeForm form3( layer ); + form3.setFeature( ft ); + ww = qobject_cast( form3.mWidgets[0] ); + label = form3.mBuddyMap.value( ww->widget() ); + + // set value to 1 + ww->setValue( 1 ); + QCOMPARE( label->text(), validLabel ); + + // set value to null + ww->setValue( QVariant() ); + QCOMPARE( label->text(), warningLabel ); + + // set value to 1 + ww->setValue( 1 ); + QCOMPARE( label->text(), validLabel ); } void TestQgsAttributeForm::testFieldMultiConstraints() @@ -267,6 +289,20 @@ void TestQgsAttributeForm::testOKButtonStatus() QCOMPARE( spy3.count(), 1 ); QCOMPARE( layer->isEditable(), false ); QCOMPARE( okButton->isEnabled(), false ); + + // set soft constraint + layer->setFieldConstraint( 0, QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthSoft ); + QgsAttributeForm form4( layer ); + form4.setFeature( ft ); + ww = qobject_cast( form4.mWidgets[0] ); + okButton = form4.mButtonBox->button( QDialogButtonBox::Ok ); + ww->setValue( 1 ); + QVERIFY( !okButton->isEnabled() ); + layer->startEditing(); + // just a soft constraint, so OK should be enabled + QVERIFY( okButton->isEnabled() ); + layer->rollBack(); + QVERIFY( !okButton->isEnabled() ); } QTEST_MAIN( TestQgsAttributeForm ) diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py index 03af6941a8d5..787bbc5e6460 100644 --- a/tests/src/python/test_qgsvectorlayerutils.py +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -103,7 +103,7 @@ def test_validate_attribute(self): self.assertEqual(len(errors), 1) print(errors) # checking only for provider constraints - res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsFieldConstraints.ConstraintOriginProvider) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, origin=QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(res) self.assertEqual(len(errors), 0) @@ -122,34 +122,45 @@ def test_validate_attribute(self): self.assertTrue(res) self.assertEqual(len(errors), 0) - layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintNotNull) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertFalse(res) self.assertEqual(len(errors), 1) print(errors) # checking only for provider constraints - res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsFieldConstraints.ConstraintOriginProvider) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, origin=QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(res) self.assertEqual(len(errors), 0) # unique constraint f.setAttributes(["test123", 123]) - layer.setFieldConstraints(1, QgsFieldConstraints.Constraints()) + layer.removeFieldConstraint(1, QgsFieldConstraints.ConstraintNotNull) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertTrue(res) self.assertEqual(len(errors), 0) - layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintUnique) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintUnique) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertFalse(res) self.assertEqual(len(errors), 1) print(errors) # checking only for provider constraints - res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, QgsFieldConstraints.ConstraintOriginProvider) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, origin=QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(res) self.assertEqual(len(errors), 0) + # checking only for soft constraints + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintUnique, QgsFieldConstraints.ConstraintStrengthHard) + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, strength=QgsFieldConstraints.ConstraintStrengthSoft) + self.assertTrue(res) + self.assertEqual(len(errors), 0) + # checking for hard constraints + res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1, + strength=QgsFieldConstraints.ConstraintStrengthHard) + self.assertFalse(res) + self.assertEqual(len(errors), 1) + # check - same id should be ignored when testing for uniqueness f1 = QgsFeature(1) f1.setAttributes(["test123", 123]) @@ -159,7 +170,8 @@ def test_validate_attribute(self): # test double constraint failure layer.setConstraintExpression(1, 'fldint>5') - layer.setFieldConstraints(1, QgsFieldConstraints.ConstraintNotNull) + layer.removeFieldConstraint(1, QgsFieldConstraints.ConstraintUnique) + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintNotNull) f.setAttributes(["test123", NULL]) res, errors = QgsVectorLayerUtils.validateAttribute(layer, f, 1) self.assertFalse(res) From 9b9a002be52a169f16e1ecbcccb93b0a4aef3780 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 14:46:24 +1000 Subject: [PATCH 589/897] Update api break docs --- doc/api_break.dox | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 22b66567c6de..f4244811bf52 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -739,7 +739,14 @@ QgsEditorWidgetRegistry::instance()->findBest() must be used instead. - expression(), setExpression(), expressionDescription() and setExpressionDescription() have been removed. Use QgsVectorLayer.setConstraintExpression()/constraintExpression(), or QgsField.constraintExpression()/QgsField.constraintDescription() instead. -- notNull() and setNotNull() have been removed. Use QgsVectorLayer.setFieldConstraints()/fieldConstraints(), or QgsField.constraints() instead. +- notNull() and setNotNull() have been removed. Use QgsVectorLayer.setFieldConstraint()/fieldConstraints(), or QgsField.constraints() instead. + +QgsEditorWidgetWrapper {#qgis_api_break_3_0_QgsEditorWidgetWrapper} +---------------------- + +- constraintStatusChanged now reports a QgsEditorWidgetWrapper::ConstraintResult instead of the previous boolean value for the constraint status +- The boolean constraintValid argument for updateConstraintWidgetStatus has been changed to a QgsEditorWidgetWrapper::ConstraintResult value + QgsExpression {#qgis_api_break_3_0_QgsExpression} ------------- From f65e770242d2e5e55167934f0a1a191726c01104 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 31 Oct 2016 08:47:08 +1000 Subject: [PATCH 590/897] [FEATURE[processing] New algorithm to compute geometry by expression This algorithm updates existing geometries (or creates new geometries) for input features by use of a QGIS expression. This allows complex geometry modifications which can utilise all the flexibility of the QGIS expression engine to manipulate and create geometries for output features. --- python/plugins/processing/algs/help/qgis.yaml | 5 + .../algs/qgis/GeometryByExpression.py | 129 ++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 3 +- .../expected/geometry_by_expression_line.gfs | 16 +++ .../expected/geometry_by_expression_line.gml | 48 +++++++ .../expected/geometry_by_expression_point.gfs | 16 +++ .../expected/geometry_by_expression_point.gml | 59 ++++++++ .../expected/geometry_by_expression_poly.gfs | 32 +++++ .../expected/geometry_by_expression_poly.gml | 58 ++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 47 ++++++- 10 files changed, 411 insertions(+), 2 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/GeometryByExpression.py create mode 100644 python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gml create mode 100644 python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gml create mode 100644 python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gml diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index a718d0ca8be1..631062dfe4a1 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -201,6 +201,11 @@ qgis:fixeddistancebuffer: > qgis:frequencyanalysis: > This algorithms generates a table with frequency analysis of the values of a selected attribute from an input vector layer +qgis:geometrybyexpression: > + This algorithm updates existing geometries (or creates new geometries) for input features by use of a QGIS expression. This allows complex geometry modifications which can utilise all the flexibility of the QGIS expression engine to manipulate and create geometries for output features. + + For help with QGIS expression functions, see the inbuilt help for specific functions which is available in the expression builder. + qgis:generatepointspixelcentroidsalongline: diff --git a/python/plugins/processing/algs/qgis/GeometryByExpression.py b/python/plugins/processing/algs/qgis/GeometryByExpression.py new file mode 100644 index 000000000000..364358ae6150 --- /dev/null +++ b/python/plugins/processing/algs/qgis/GeometryByExpression.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + GeometryByExpression.py + ----------------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive323 + +__revision__ = '$Format:%H$' + +from qgis.core import QgsWkbTypes, QgsExpression, QgsExpressionContext, QgsExpressionContextUtils, QgsGeometry + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.ProcessingLog import ProcessingLog +from processing.core.parameters import ParameterVector, ParameterSelection, ParameterBoolean, ParameterString +from processing.core.outputs import OutputVector +from processing.tools import dataobjects, vector + + +class GeometryByExpression(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + OUTPUT_LAYER = 'OUTPUT_LAYER' + OUTPUT_GEOMETRY = 'OUTPUT_GEOMETRY' + WITH_Z = 'WITH_Z' + WITH_M = 'WITH_M' + EXPRESSION = 'EXPRESSION' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Geometry by expression') + self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Input layer'))) + + self.geometry_types = [self.tr('Polygon'), + 'Line', + 'Point'] + self.addParameter(ParameterSelection( + self.OUTPUT_GEOMETRY, + self.tr('Output geometry type'), + self.geometry_types, default=0)) + self.addParameter(ParameterBoolean(self.WITH_Z, + self.tr('Output geometry has z dimension'), False)) + self.addParameter(ParameterBoolean(self.WITH_M, + self.tr('Output geometry has m values'), False)) + + self.addParameter(ParameterString(self.EXPRESSION, + self.tr("Geometry expression"), '$geometry')) + + self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Modified geometry'))) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + + geometry_type = self.getParameterValue(self.OUTPUT_GEOMETRY) + wkb_type = None + if geometry_type == 0: + wkb_type = QgsWkbTypes.Polygon + elif geometry_type == 1: + wkb_type = QgsWkbTypes.LineString + else: + wkb_type = QgsWkbTypes.Point + if self.getParameterValue(self.WITH_Z): + wkb_type = QgsWkbTypes.addZ(wkb_type) + if self.getParameterValue(self.WITH_M): + wkb_type = QgsWkbTypes.addM(wkb_type) + + writer = self.getOutputFromName( + self.OUTPUT_LAYER).getVectorWriter( + layer.fields(), + wkb_type, + layer.crs()) + + expression = QgsExpression(self.getParameterValue(self.EXPRESSION)) + if expression.hasParserError(): + raise GeoAlgorithmExecutionException(expression.parserErrorString()) + + exp_context = QgsExpressionContext() + exp_context.appendScope(QgsExpressionContextUtils.globalScope()) + exp_context.appendScope(QgsExpressionContextUtils.projectScope()) + exp_context.appendScope(QgsExpressionContextUtils.layerScope(layer)) + + if not expression.prepare(exp_context): + raise GeoAlgorithmExecutionException( + self.tr('Evaluation error: %s' % expression.evalErrorString())) + + features = vector.features(layer) + total = 100.0 / len(features) + for current, input_feature in enumerate(features): + output_feature = input_feature + + exp_context.setFeature(input_feature) + value = expression.evaluate(exp_context) + if expression.hasEvalError(): + raise GeoAlgorithmExecutionException( + self.tr('Evaluation error: %s' % expression.evalErrorString())) + + if not value: + output_feature.setGeometry(QgsGeometry()) + else: + if not isinstance(value, QgsGeometry): + raise GeoAlgorithmExecutionException( + self.tr('{} is not a geometry').format(value)) + output_feature.setGeometry(value) + + writer.addFeature(output_feature) + progress.setPercentage(int(current * total)) + + del writer diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index a765e9c77847..0bf402c0fcef 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -174,6 +174,7 @@ from .RemoveNullGeometry import RemoveNullGeometry from .ExtendLines import ExtendLines from .ExtractSpecificNodes import ExtractSpecificNodes +from .GeometryByExpression import GeometryByExpression pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -236,7 +237,7 @@ def __init__(self): IdwInterpolationZValue(), IdwInterpolationAttribute(), TinInterpolationZValue(), TinInterpolationAttribute(), RemoveNullGeometry(), ExtractByExpression(), ExtendLines(), - ExtractSpecificNodes() + ExtractSpecificNodes(), GeometryByExpression() ] if hasMatplotlib: diff --git a/python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gfs b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gfs new file mode 100644 index 000000000000..519605788520 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gfs @@ -0,0 +1,16 @@ + + + geometry_by_expression_line + geometry_by_expression_line + + 2 + EPSG:4326 + + 7 + 0.00000 + 12.00000 + -2.00000 + 6.00000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gml b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gml new file mode 100644 index 000000000000..78ad2c67f2e0 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_line.gml @@ -0,0 +1,48 @@ + + + + + 0-2 + 126 + + + + + + 7,3 10,3 10,4 12,6 + + + + + 0,0 2,0 + + + + + 3,1 3,3 4,3 4,4 + + + + + 4,2 6,2 + + + + + 8,-2 11,-2 + + + + + 7,-2 11,2 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gfs b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gfs new file mode 100644 index 000000000000..0287d6eaaad4 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gfs @@ -0,0 +1,16 @@ + + + geometry_by_expression_point + geometry_by_expression_point + + 1 + EPSG:4326 + + 9 + 1.00000 + 9.00000 + -4.00000 + 4.00000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gml b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gml new file mode 100644 index 000000000000..e3b2d8b3d24f --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_point.gml @@ -0,0 +1,59 @@ + + + + + 1-4 + 94 + + + + + + 2,2 + + + + + 4,4 + + + + + 3,3 + + + + + 6,3 + + + + + 5,2 + + + + + 1,-4 + + + + + 9,0 + + + + + 8,0 + + + + + 1,0 + + + diff --git a/python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gfs b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gfs new file mode 100644 index 000000000000..0d159c7d2bc4 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gfs @@ -0,0 +1,32 @@ + + + geometry_by_expression_poly + geometry_by_expression_poly + + 1 + EPSG:4326 + + 6 + 1.65385 + 9.00000 + 0.00000 + 6.50000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gml b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gml new file mode 100644 index 000000000000..f8064228bc58 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/geometry_by_expression_poly.gml @@ -0,0 +1,58 @@ + + + + + 1.6538461538461540 + 96.5 + + + + + + 1.653846153846154,2.115384615384615 + aaaaa + 33 + 44.123456 + + + + + 6.0,5.333333333333333 + Aaaaa + -33 + 0 + + + + + 3.5,6.5 + bbaaa + 0.123 + + + + + 9,0 + ASDF + 0 + + + + + 120 + -100291.43213 + + + + + 5.080459770114943,0.781609195402299 + elim + 2 + 3.33 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index f4b96d6ba551..e20527f5ea76 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1275,4 +1275,49 @@ tests: results: OUTPUT_LAYER: name: expected/extract_specific_nodes_polys.gml - type: vector \ No newline at end of file + type: vector + + - algorithm: qgis:geometrybyexpression + name: Geometry by expression (point) + params: + EXPRESSION: 'translate( $geometry,1,1)' + INPUT_LAYER: + name: points.gml + type: vector + OUTPUT_GEOMETRY: '0' + WITH_M: false + WITH_Z: false + results: + OUTPUT_LAYER: + name: expected/geometry_by_expression_point.gml + type: vector + + - algorithm: qgis:geometrybyexpression + name: Geometry by expression (polygon) + params: + EXPRESSION: ' translate( centroid($geometry),1,1)' + INPUT_LAYER: + name: polys.gml + type: vector + OUTPUT_GEOMETRY: '2' + WITH_M: false + WITH_Z: false + results: + OUTPUT_LAYER: + name: expected/geometry_by_expression_poly.gml + type: vector + + - algorithm: qgis:geometrybyexpression + name: Geometry by expression (line) + params: + EXPRESSION: ' translate( $geometry,1,1)' + INPUT_LAYER: + name: lines.gml + type: vector + OUTPUT_GEOMETRY: '1' + WITH_M: false + WITH_Z: false + results: + OUTPUT_LAYER: + name: expected/geometry_by_expression_line.gml + type: vector From 18fc0c6fad8fae04b2281f4c8557a0338b2297f4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 16:06:00 +1000 Subject: [PATCH 591/897] [processing] optimise multipart to singlepart algorithm - simplify code - keep z/m/curved geometries intact - might be a bit faster --- .../algs/qgis/MultipartToSingleparts.py | 71 ++++--------------- 1 file changed, 12 insertions(+), 59 deletions(-) diff --git a/python/plugins/processing/algs/qgis/MultipartToSingleparts.py b/python/plugins/processing/algs/qgis/MultipartToSingleparts.py index b64495894243..75fb0a9e8ba1 100644 --- a/python/plugins/processing/algs/qgis/MultipartToSingleparts.py +++ b/python/plugins/processing/algs/qgis/MultipartToSingleparts.py @@ -33,7 +33,6 @@ from qgis.core import QgsFeature, QgsGeometry, QgsWkbTypes from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector @@ -58,7 +57,7 @@ def defineCharacteristics(self): def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) - geomType = self.multiToSingleGeom(layer.wkbType()) + geomType = QgsWkbTypes.singleType(layer.wkbType()) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields().toList(), geomType, layer.crs()) @@ -66,66 +65,20 @@ def processAlgorithm(self, progress): features = vector.features(layer) total = 100.0 / len(features) for current, f in enumerate(features): - outFeat = QgsFeature() - attrs = f.attributes() - outFeat.setAttributes(attrs) - - inGeom = f.geometry() - if inGeom: - geometries = self.extractAsSingle(inGeom) - - for g in geometries: - outFeat.setGeometry(g) - writer.addFeature(outFeat) + input_geometry = f.geometry() + if input_geometry: + if input_geometry.isMultipart(): + for i in range(input_geometry.geometry().numGeometries()): + singlepart_geometry = QgsGeometry(input_geometry.geometry().geometryN(i).clone()) + output_feature = f + output_feature.setGeometry( singlepart_geometry ) + writer.addFeature(output_feature) + else: + writer.addFeature(f) else: #input feature with null geometry - writer.addFeature(outFeat) + writer.addFeature(f) progress.setPercentage(int(current * total)) del writer - - def multiToSingleGeom(self, wkbType): - try: - if wkbType in (QgsWkbTypes.Point, QgsWkbTypes.MultiPoint, - QgsWkbTypes.Point25D, QgsWkbTypes.MultiPoint25D): - return QgsWkbTypes.Point - elif wkbType in (QgsWkbTypes.LineString, QgsWkbTypes.MultiLineString, - QgsWkbTypes.MultiLineString25D, - QgsWkbTypes.LineString25D): - - return QgsWkbTypes.LineString - elif wkbType in (QgsWkbTypes.Polygon, QgsWkbTypes.MultiPolygon, - QgsWkbTypes.MultiPolygon25D, QgsWkbTypes.Polygon25D): - - return QgsWkbTypes.Polygon - else: - return QgsWkbTypes.Unknown - except Exception as err: - raise GeoAlgorithmExecutionException(str(err)) - - def extractAsSingle(self, geom): - multiGeom = QgsGeometry() - geometries = [] - if geom.type() == QgsWkbTypes.PointGeometry: - if geom.isMultipart(): - multiGeom = geom.asMultiPoint() - for i in multiGeom: - geometries.append(QgsGeometry().fromPoint(i)) - else: - geometries.append(geom) - elif geom.type() == QgsWkbTypes. LineGeometry: - if geom.isMultipart(): - multiGeom = geom.asMultiPolyline() - for i in multiGeom: - geometries.append(QgsGeometry().fromPolyline(i)) - else: - geometries.append(geom) - elif geom.type() == QgsWkbTypes.PolygonGeometry: - if geom.isMultipart(): - multiGeom = geom.asMultiPolygon() - for i in multiGeom: - geometries.append(QgsGeometry().fromPolygon(i)) - else: - geometries.append(geom) - return geometries From 28457ed49c764a21559e9269db7d9ab9b6a8060b Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Tue, 1 Nov 2016 15:21:04 +0100 Subject: [PATCH 592/897] Fix saving of the collapsed state for relations In the attribute form, the collapsed state of RelationReference was not loaded correctly and was interfering with the collapsed state of the relation editor. Plus, the state was saved globally for a reference. Meaning that if a reference was used (through other references) from other layers, it was sharing the same state. --- src/app/qgsattributetabledialog.cpp | 1 + .../qgsrelationreferencewidget.cpp | 1 + .../qgsrelationreferencewidgetwrapper.cpp | 1 + src/gui/qgscollapsiblegroupbox.cpp | 29 ++++++++++++------- src/gui/qgsrelationeditorwidget.cpp | 6 ++-- 5 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 1549386a6cc3..05ca1eebcdd3 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -86,6 +86,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid , mRubberBand( nullptr ) , mCurrentSearchWidgetWrapper( nullptr ) { + setObjectName( QStringLiteral( "QgsAttributeTableDialog/" ) + theLayer->id() ); setupUi( this ); Q_FOREACH ( const QgsField& field, mLayer->fields() ) diff --git a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp index 38ff106597a0..b1f323a6e355 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidget.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidget.cpp @@ -195,6 +195,7 @@ void QgsRelationReferenceWidget::setRelation( const QgsRelation& relation, bool mReferencedLayer = relation.referencedLayer(); mReferencedFieldIdx = mReferencedLayer->fields().lookupField( relation.fieldPairs().at( 0 ).second ); mReferencingFieldIdx = mReferencingLayer->fields().lookupField( relation.fieldPairs().at( 0 ).first ); + mAttributeEditorFrame->setObjectName( QStringLiteral( "referencing/" ) + relation.name() ); QgsAttributeEditorContext context( mEditorContext, relation, QgsAttributeEditorContext::Single, QgsAttributeEditorContext::Embed ); diff --git a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp index 6d5db05fa422..094eccf92fa3 100644 --- a/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencewidgetwrapper.cpp @@ -76,6 +76,7 @@ void QgsRelationReferenceWidgetWrapper::initWidget( QWidget* editor ) mWidget->setEmbedForm( false ); mWidget->setReadOnlySelector( false ); mWidget->setAllowMapIdentification( false ); + break; } ctx = ctx->parentContext(); } diff --git a/src/gui/qgscollapsiblegroupbox.cpp b/src/gui/qgscollapsiblegroupbox.cpp index 625884d64cbe..9c950dfef8fd 100644 --- a/src/gui/qgscollapsiblegroupbox.cpp +++ b/src/gui/qgscollapsiblegroupbox.cpp @@ -522,6 +522,8 @@ void QgsCollapsibleGroupBox::init() // in multiple places or used as options for different parent objects mSaveCheckedState = false; mSettingGroup = QLatin1String( "" ); // if not set, use window object name + + connect( this, &QObject::objectNameChanged, this, &QgsCollapsibleGroupBox::loadState ); } void QgsCollapsibleGroupBox::showEvent( QShowEvent * event ) @@ -547,6 +549,9 @@ void QgsCollapsibleGroupBox::showEvent( QShowEvent * event ) QString QgsCollapsibleGroupBox::saveKey() const { + if ( objectName().isEmpty() || ( mSettingGroup.isEmpty() && window()->objectName().isEmpty() ) ) + return QString(); // cannot get a valid key + // save key for load/save state // currently QgsCollapsibleGroupBox/window()/object QString saveKey = '/' + objectName(); @@ -558,9 +563,9 @@ QString QgsCollapsibleGroupBox::saveKey() const // } // if ( parent() ) // saveKey = "/" + parent()->objectName() + saveKey; - QString setgrp = mSettingGroup.isEmpty() ? window()->objectName() : mSettingGroup; + const QString setgrp = mSettingGroup.isEmpty() ? window()->objectName() : mSettingGroup; saveKey = '/' + setgrp + saveKey; - saveKey = "QgsCollapsibleGroupBox" + saveKey; + saveKey = QStringLiteral( "QgsCollapsibleGroupBox" ) + saveKey; return saveKey; } @@ -572,19 +577,21 @@ void QgsCollapsibleGroupBox::loadState() if ( !isEnabled() || ( !mSaveCollapsedState && !mSaveCheckedState ) ) return; + const QString key = saveKey(); + if ( key.isEmpty() ) + return; + setUpdatesEnabled( false ); - QString key = saveKey(); - QVariant val; if ( mSaveCheckedState ) { - val = mSettings->value( key + "/checked" ); + QVariant val = mSettings->value( key + "/checked" ); if ( ! val.isNull() ) setChecked( val.toBool() ); } if ( mSaveCollapsedState ) { - val = mSettings->value( key + "/collapsed" ); + QVariant val = mSettings->value( key + "/collapsed" ); if ( ! val.isNull() ) setCollapsed( val.toBool() ); } @@ -597,14 +604,16 @@ void QgsCollapsibleGroupBox::saveState() const if ( !mSettings ) return; - if ( !isEnabled() || ( !mSaveCollapsedState && !mSaveCheckedState ) ) + if ( !mShown || !isEnabled() || ( !mSaveCollapsedState && !mSaveCheckedState ) ) return; - QString key = saveKey(); + const QString key = saveKey(); + if ( key.isEmpty() ) + return; if ( mSaveCheckedState ) - mSettings->setValue( key + "/checked", isChecked() ); + mSettings->setValue( key + QStringLiteral( "/checked" ), isChecked() ); if ( mSaveCollapsedState ) - mSettings->setValue( key + "/collapsed", isCollapsed() ); + mSettings->setValue( key + QStringLiteral( "/collapsed" ), isCollapsed() ); } diff --git a/src/gui/qgsrelationeditorwidget.cpp b/src/gui/qgsrelationeditorwidget.cpp index ad9e52a3112b..07f96d250889 100644 --- a/src/gui/qgsrelationeditorwidget.cpp +++ b/src/gui/qgsrelationeditorwidget.cpp @@ -170,8 +170,7 @@ void QgsRelationEditorWidget::setRelationFeature( const QgsRelation& relation, c mToggleEditingButton->setEnabled( false ); } - setObjectName( mRelation.name() ); - loadState(); + setObjectName( QStringLiteral( "referenced/" ) + mRelation.name() ); // If not yet initialized, it is not (yet) visible, so we don't load it to be faster (lazy loading) // If it is already initialized, it has been set visible before and the currently shown feature is changing @@ -240,8 +239,7 @@ void QgsRelationEditorWidget::setRelations( const QgsRelation& relation, const Q mToggleEditingButton->setEnabled( false ); } - setObjectName( mRelation.name() ); - loadState(); + setObjectName( QStringLiteral( "referenced/" ) + mRelation.name() ); updateUi(); } From a7ffecd8780ab8ce89fe9f7622c23ecb92c202e7 Mon Sep 17 00:00:00 2001 From: Harrissou Sant-anna Date: Wed, 2 Nov 2016 11:22:48 +0100 Subject: [PATCH 593/897] Make collapsible the "Curve segmentation" frame in Settings --> Options --> Rendering dialog (for coherence with other frames) also fix a typo --- src/ui/qgsoptionsbase.ui | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/qgsoptionsbase.ui b/src/ui/qgsoptionsbase.ui index d800a0165475..3b5d36c6b85a 100644 --- a/src/ui/qgsoptionsbase.ui +++ b/src/ui/qgsoptionsbase.ui @@ -1997,7 +1997,7 @@ - This algorithm only is applied to simplify on local side + This algorithm is only applied to simplify on local side Simplification algorithm: @@ -2105,7 +2105,7 @@ - + Curve segmentation From 06dc501139381cf705339d24458e827142685ec7 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Wed, 2 Nov 2016 12:39:24 +0100 Subject: [PATCH 594/897] test_provider_ogr_gpkg.py: Test disabling walForSqlite3 setting --- tests/src/python/test_provider_ogr_gpkg.py | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index 6cd4c77af14c..c0cdf3bdca84 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -360,5 +360,44 @@ def testStyle(self): sublayers = vl.dataProvider().subLayers() self.assertEqual(len(sublayers), 2, sublayers) + def testDisablewalForSqlite3(self): + ''' Test disabling walForSqlite3 setting ''' + QSettings().setValue("/qgis/walForSqlite3", False) + + tmpfile = os.path.join(self.basetestpath, 'testDisablewalForSqlite3.gpkg') + ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) + lyr.CreateField(ogr.FieldDefn('attr0', ogr.OFTInteger)) + lyr.CreateField(ogr.FieldDefn('attr1', ogr.OFTInteger)) + f = ogr.Feature(lyr.GetLayerDefn()) + f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 0)')) + lyr.CreateFeature(f) + f = None + ds = None + + vl = QgsVectorLayer(u'{}'.format(tmpfile), u'test', u'ogr') + + # Test that we are using default delete mode and not WAL + ds = ogr.Open(tmpfile) + lyr = ds.ExecuteSQL('PRAGMA journal_mode') + f = lyr.GetNextFeature() + res = f.GetField(0) + ds.ReleaseResultSet(lyr) + ds = None + self.assertEqual(res, 'delete') + + self.assertTrue(vl.startEditing()) + feature = next(vl.getFeatures()) + self.assertTrue(vl.changeAttributeValue(feature.id(), 1, 1001)) + + # Commit changes + cbk = ErrorReceiver() + vl.dataProvider().raiseError.connect(cbk.receiveError) + self.assertTrue(vl.commitChanges()) + self.assertIsNone(cbk.msg) + vl = None + + QSettings().setValue("/qgis/walForSqlite3", None) + if __name__ == '__main__': unittest.main() From 2497375ee95c5eb3046a8316793adf75c4ef1768 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 8 Sep 2016 15:10:32 +0300 Subject: [PATCH 595/897] [FEATURE] save and restore color ramp used for singleband pseudocolor rendering --- src/core/raster/qgscolorrampshader.cpp | 7 +++++++ src/core/raster/qgscolorrampshader.h | 9 +++++++++ src/core/raster/qgsrastershader.cpp | 4 +++- src/core/raster/qgssinglebandpseudocolorrenderer.cpp | 1 + .../raster/qgssinglebandpseudocolorrendererwidget.cpp | 9 +++++++++ 5 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/core/raster/qgscolorrampshader.cpp b/src/core/raster/qgscolorrampshader.cpp index be9fb2c6c6f8..a6c7bdb24cad 100644 --- a/src/core/raster/qgscolorrampshader.cpp +++ b/src/core/raster/qgscolorrampshader.cpp @@ -35,6 +35,7 @@ QgsColorRampShader::QgsColorRampShader( double theMinimumValue, double theMaximu , mLUTFactor( 1.0 ) , mLUTInitialized( false ) , mClip( false ) + , mColorRampName( "" ) { QgsDebugMsgLevel( "called.", 4 ); } @@ -82,6 +83,12 @@ void QgsColorRampShader::setColorRampType( const QString& theType ) } } +void QgsColorRampShader::setColorRampName( const QString& theName ) +{ + mColorRampName = theName; +} + + bool QgsColorRampShader::shade( double theValue, int* theReturnRedValue, int* theReturnGreenValue, int* theReturnBlueValue, int *theReturnAlphaValue ) { if ( mColorRampItemList.isEmpty() ) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 0fe2fbf068f7..02730d4ebc25 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -75,6 +75,9 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Get the color ramp type as a string QString colorRampTypeAsQString(); + //! \brief Get the original color ramp name + QString colorRampName() const {return mColorRampName;} + //! \brief Set custom colormap void setColorRampItemList( const QList& theList ); //TODO: sort on set @@ -84,6 +87,9 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Set the color ramp type void setColorRampType( const QString& theType ); + //! \brief Set the source color ramp name + void setColorRampName( const QString& theName ); + //! \brief Generates and new RGB value based on one input value bool shade( double, int*, int*, int*, int* ) override; @@ -121,6 +127,9 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction double mLUTFactor; bool mLUTInitialized; + /** Colorramp name*/ + QString mColorRampName; + //! Do not render values out of range bool mClip; }; diff --git a/src/core/raster/qgsrastershader.cpp b/src/core/raster/qgsrastershader.cpp index 79b8b7853208..b843fcecef1b 100644 --- a/src/core/raster/qgsrastershader.cpp +++ b/src/core/raster/qgsrastershader.cpp @@ -143,7 +143,8 @@ void QgsRasterShader::writeXml( QDomDocument& doc, QDomElement& parent ) const if ( colorRampShader ) { QDomElement colorRampShaderElem = doc.createElement( QStringLiteral( "colorrampshader" ) ); - colorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), colorRampShader->colorRampTypeAsQString() ); + colorRampShaderElem.setAttribute( "colorRampName", colorRampShader->colorRampName() ); + colorRampShaderElem.setAttribute( "colorRampType", colorRampShader->colorRampTypeAsQString() ); colorRampShaderElem.setAttribute( QStringLiteral( "clip" ), colorRampShader->clip() ); //items QList itemList = colorRampShader->colorRampItemList(); @@ -169,6 +170,7 @@ void QgsRasterShader::readXml( const QDomElement& elem ) if ( !colorRampShaderElem.isNull() ) { QgsColorRampShader* colorRampShader = new QgsColorRampShader(); + colorRampShader->setColorRampName( colorRampShaderElem.attribute( "colorRampName", "" ) ); colorRampShader->setColorRampType( colorRampShaderElem.attribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) ) ); colorRampShader->setClip( colorRampShaderElem.attribute( QStringLiteral( "clip" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); diff --git a/src/core/raster/qgssinglebandpseudocolorrenderer.cpp b/src/core/raster/qgssinglebandpseudocolorrenderer.cpp index bcf4f0807763..b438c8fb7191 100644 --- a/src/core/raster/qgssinglebandpseudocolorrenderer.cpp +++ b/src/core/raster/qgssinglebandpseudocolorrenderer.cpp @@ -63,6 +63,7 @@ QgsSingleBandPseudoColorRenderer* QgsSingleBandPseudoColorRenderer::clone() cons { QgsColorRampShader * colorRampShader = new QgsColorRampShader( mShader->minimumValue(), mShader->maximumValue() ); + colorRampShader->setColorRampName( origColorRampShader->colorRampName() ); colorRampShader->setColorRampType( origColorRampShader->colorRampType() ); colorRampShader->setClip( origColorRampShader->clip() ); colorRampShader->setColorRampItemList( origColorRampShader->colorRampItemList() ); diff --git a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp index b1d5de8ba0cf..51a68cebeb61 100644 --- a/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp +++ b/src/gui/raster/qgssinglebandpseudocolorrendererwidget.cpp @@ -152,6 +152,7 @@ QgsRasterRenderer* QgsSingleBandPseudoColorRendererWidget::renderer() QgsColorRampShader::ColorRamp_TYPE interpolation = static_cast< QgsColorRampShader::ColorRamp_TYPE >( mColorInterpolationComboBox->currentData().toInt() ); colorRampShader->setColorRampType( interpolation ); + colorRampShader->setColorRampName( mColorRampComboBox->currentText() ); rasterShader->setRasterShaderFunction( colorRampShader ); int bandNumber = mBandComboBox->currentData().toInt(); @@ -792,6 +793,14 @@ void QgsSingleBandPseudoColorRendererWidget::setFromRenderer( const QgsRasterRen const QgsColorRampShader* colorRampShader = dynamic_cast( rasterShader->rasterShaderFunction() ); if ( colorRampShader ) { + int idx = mColorRampComboBox->findText( colorRampShader->colorRampName() ); + if ( idx == -1 ) + { + QSettings settings; + QString defaultPalette = settings.value( "/Raster/defaultPalette", "Spectral" ).toString(); + idx = mColorRampComboBox->findText( defaultPalette ); + } + mColorRampComboBox->setCurrentIndex( idx ); mColorInterpolationComboBox->setCurrentIndex( mColorInterpolationComboBox->findData( colorRampShader->colorRampType() ) ); const QList colorRampItemList = colorRampShader->colorRampItemList(); From 75b23cb55c654d073680992e082c718bcf1cc29e Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 15 Sep 2016 17:00:21 +0300 Subject: [PATCH 596/897] update Python bindings --- python/core/raster/qgscolorrampshader.sip | 10 ++++++++++ src/core/raster/qgscolorrampshader.h | 16 ++++++++++------ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/python/core/raster/qgscolorrampshader.sip b/python/core/raster/qgscolorrampshader.sip index ddad2fe1e967..77728130447d 100644 --- a/python/core/raster/qgscolorrampshader.sip +++ b/python/core/raster/qgscolorrampshader.sip @@ -40,12 +40,22 @@ class QgsColorRampShader : QgsRasterShaderFunction /** \brief Get the color ramp type */ QgsColorRampShader::ColorRamp_TYPE colorRampType() const; + /** \brief Get the original color ramp name + * @note added in QGIS 3.0 + */ + QString colorRampName() const; + /** \brief Get the color ramp type as a string */ QString colorRampTypeAsQString(); /** \brief Set custom colormap */ void setColorRampItemList( const QList& theList ); //TODO: sort on set + /** \brief Set the source color ramp name + * @note added in QGIS 3.0 + */ + void setColorRampName( const QString& theName ); + /** \brief Set the color ramp type*/ void setColorRampType( QgsColorRampShader::ColorRamp_TYPE theColorRampType ); diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 02730d4ebc25..74ccd982c241 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -72,10 +72,12 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Get the color ramp type QgsColorRampShader::ColorRamp_TYPE colorRampType() const {return mColorRampType;} - //! \brief Get the color ramp type as a string + // \brief Get the color ramp type as a string QString colorRampTypeAsQString(); - //! \brief Get the original color ramp name + /** \brief Get the original color ramp name + * @note added in QGIS 3.0 + */ QString colorRampName() const {return mColorRampName;} //! \brief Set custom colormap @@ -84,12 +86,14 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Set the color ramp type void setColorRampType( QgsColorRampShader::ColorRamp_TYPE theColorRampType ); - //! \brief Set the color ramp type - void setColorRampType( const QString& theType ); - - //! \brief Set the source color ramp name + /** \brief Set the source color ramp name + * @note added in QGIS 3.0 + */ void setColorRampName( const QString& theName ); + // \brief Set the color ramp type + void setColorRampType( const QString& theType ); + //! \brief Generates and new RGB value based on one input value bool shade( double, int*, int*, int*, int* ) override; From dac03d5ce88ac24859823c93267354f312b5c0c8 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 16 Sep 2016 09:16:13 +0300 Subject: [PATCH 597/897] use default QString() constructor instead of "" improve doxygen docs --- python/core/raster/qgscolorrampshader.sip | 2 ++ src/core/raster/qgscolorrampshader.cpp | 2 +- src/core/raster/qgscolorrampshader.h | 2 ++ src/core/raster/qgsrastershader.cpp | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/python/core/raster/qgscolorrampshader.sip b/python/core/raster/qgscolorrampshader.sip index 77728130447d..bf8a43ebd140 100644 --- a/python/core/raster/qgscolorrampshader.sip +++ b/python/core/raster/qgscolorrampshader.sip @@ -42,6 +42,7 @@ class QgsColorRampShader : QgsRasterShaderFunction /** \brief Get the original color ramp name * @note added in QGIS 3.0 + * @see setColorRampName() */ QString colorRampName() const; @@ -53,6 +54,7 @@ class QgsColorRampShader : QgsRasterShaderFunction /** \brief Set the source color ramp name * @note added in QGIS 3.0 + * @see colorRampName() */ void setColorRampName( const QString& theName ); diff --git a/src/core/raster/qgscolorrampshader.cpp b/src/core/raster/qgscolorrampshader.cpp index a6c7bdb24cad..85186deac8ae 100644 --- a/src/core/raster/qgscolorrampshader.cpp +++ b/src/core/raster/qgscolorrampshader.cpp @@ -34,8 +34,8 @@ QgsColorRampShader::QgsColorRampShader( double theMinimumValue, double theMaximu , mLUTOffset( 0.0 ) , mLUTFactor( 1.0 ) , mLUTInitialized( false ) + , mColorRampName( QString() ) , mClip( false ) - , mColorRampName( "" ) { QgsDebugMsgLevel( "called.", 4 ); } diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 74ccd982c241..22158191e21b 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -77,6 +77,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction /** \brief Get the original color ramp name * @note added in QGIS 3.0 + * @see setColorRampName() */ QString colorRampName() const {return mColorRampName;} @@ -88,6 +89,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction /** \brief Set the source color ramp name * @note added in QGIS 3.0 + * @see colorRampName() */ void setColorRampName( const QString& theName ); diff --git a/src/core/raster/qgsrastershader.cpp b/src/core/raster/qgsrastershader.cpp index b843fcecef1b..4bba4e46d07a 100644 --- a/src/core/raster/qgsrastershader.cpp +++ b/src/core/raster/qgsrastershader.cpp @@ -170,7 +170,7 @@ void QgsRasterShader::readXml( const QDomElement& elem ) if ( !colorRampShaderElem.isNull() ) { QgsColorRampShader* colorRampShader = new QgsColorRampShader(); - colorRampShader->setColorRampName( colorRampShaderElem.attribute( "colorRampName", "" ) ); + colorRampShader->setColorRampName( colorRampShaderElem.attribute( "colorRampName", QString() ) ); colorRampShader->setColorRampType( colorRampShaderElem.attribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) ) ); colorRampShader->setClip( colorRampShaderElem.attribute( QStringLiteral( "clip" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); From f7d591238099fb3e4b7977b40ce183dfcf6bd64e Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 16 Sep 2016 09:55:38 +0300 Subject: [PATCH 598/897] fix formatting --- src/core/raster/qgscolorrampshader.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 22158191e21b..26c00685a879 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -67,10 +67,10 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction }; //! \brief Get the custom colormap - QList colorRampItemList() const {return mColorRampItemList.toList();} + QList colorRampItemList() const { return mColorRampItemList.toList(); } //! \brief Get the color ramp type - QgsColorRampShader::ColorRamp_TYPE colorRampType() const {return mColorRampType;} + QgsColorRampShader::ColorRamp_TYPE colorRampType() const { return mColorRampType; } // \brief Get the color ramp type as a string QString colorRampTypeAsQString(); @@ -79,7 +79,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction * @note added in QGIS 3.0 * @see setColorRampName() */ - QString colorRampName() const {return mColorRampName;} + QString colorRampName() const { return mColorRampName; } //! \brief Set custom colormap void setColorRampItemList( const QList& theList ); //TODO: sort on set From 54dcc347ae059b200451fdf5b77057ebc04a1b58 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 19 Sep 2016 12:55:51 +0300 Subject: [PATCH 599/897] default value does not need to be explicitly set --- src/core/raster/qgsrastershader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/raster/qgsrastershader.cpp b/src/core/raster/qgsrastershader.cpp index 4bba4e46d07a..ecdbb2176d26 100644 --- a/src/core/raster/qgsrastershader.cpp +++ b/src/core/raster/qgsrastershader.cpp @@ -170,7 +170,7 @@ void QgsRasterShader::readXml( const QDomElement& elem ) if ( !colorRampShaderElem.isNull() ) { QgsColorRampShader* colorRampShader = new QgsColorRampShader(); - colorRampShader->setColorRampName( colorRampShaderElem.attribute( "colorRampName", QString() ) ); + colorRampShader->setColorRampName( colorRampShaderElem.attribute( "colorRampName" ) ); colorRampShader->setColorRampType( colorRampShaderElem.attribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) ) ); colorRampShader->setClip( colorRampShaderElem.attribute( QStringLiteral( "clip" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); From 9ae6e6ffe4320bd63bd1e5e940b7878359c275df Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 2 Nov 2016 13:54:45 +0200 Subject: [PATCH 600/897] fix typo in comment --- src/core/raster/qgscolorrampshader.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 26c00685a879..971d6362abeb 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -133,7 +133,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction double mLUTFactor; bool mLUTInitialized; - /** Colorramp name*/ + //! Color ramp name QString mColorRampName; //! Do not render values out of range From 5a2bb5d84c6030122a3205286e0bf5697b33afd1 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 2 Nov 2016 15:48:34 +0200 Subject: [PATCH 601/897] fix doxygen comments --- src/core/raster/qgscolorrampshader.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 971d6362abeb..378ced383a3f 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -75,7 +75,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction // \brief Get the color ramp type as a string QString colorRampTypeAsQString(); - /** \brief Get the original color ramp name + /** Get the original color ramp name * @note added in QGIS 3.0 * @see setColorRampName() */ @@ -87,13 +87,13 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Set the color ramp type void setColorRampType( QgsColorRampShader::ColorRamp_TYPE theColorRampType ); - /** \brief Set the source color ramp name + /** Sets the source color ramp name * @note added in QGIS 3.0 * @see colorRampName() */ void setColorRampName( const QString& theName ); - // \brief Set the color ramp type + //! \brief Set the color ramp type void setColorRampType( const QString& theType ); //! \brief Generates and new RGB value based on one input value From a3c762b218e48bc5bebee36ba1f7da1a54fa6a1d Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 2 Nov 2016 16:26:14 +0200 Subject: [PATCH 602/897] more doxygen fixes --- src/core/raster/qgscolorrampshader.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 378ced383a3f..a6a342180ad1 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -72,7 +72,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Get the color ramp type QgsColorRampShader::ColorRamp_TYPE colorRampType() const { return mColorRampType; } - // \brief Get the color ramp type as a string + //! \brief Get the color ramp type as a string QString colorRampTypeAsQString(); /** Get the original color ramp name From 2be0f013f438d2798434913f619d2db33740ac59 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 2 Nov 2016 16:31:21 +0200 Subject: [PATCH 603/897] document undocumented method --- src/core/raster/qgscolorrampshader.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index a6a342180ad1..33060066655b 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -102,6 +102,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction //! \brief Generates and new RGB value based on original RGB value bool shade( double, double, double, double, int*, int*, int*, int* ) override; + //! \brief Get symbology items if provided by renderer void legendSymbologyItems( QList< QPair< QString, QColor > >& symbolItems ) const override; /** Sets whether the shader should not render values out of range. From 963d75f471124a39131ba8a1f5f155035f9d6046 Mon Sep 17 00:00:00 2001 From: rldhont Date: Wed, 2 Nov 2016 16:29:03 +0100 Subject: [PATCH 604/897] [BUGFIX][QGIS Server] Apply filter element --- src/server/qgswfsserver.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index c7615c4c1880..dab06ea58337 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -655,6 +655,22 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format { throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), filter->parserErrorString() ); } + QgsFeatureRequest req; + req.setFlags( QgsFeatureRequest::ExactIntersect | ( mWithGeom ? QgsFeatureRequest::NoFlags : QgsFeatureRequest::NoGeometry ) ); + req.setFilterExpression( filter->expression() ); +#ifdef HAVE_SERVER_PYTHON_PLUGINS + mAccessControl->filterFeatures( layer, req ); + + QStringList attributes = QStringList(); + Q_FOREACH ( int idx, attrIndexes ) + { + attributes.append( layer->pendingFields().field( idx ).name() ); + } + req.setSubsetOfAttributes( + mAccessControl->layerAttributes( layer, attributes ), + layer->pendingFields() ); +#endif + QgsFeatureIterator fit = layer->getFeatures( req ); while ( fit.nextFeature( feature ) && ( !hasFeatureLimit || featureCounter < maxFeatures + startIndex ) ) { expressionContext.setFeature( feature ); From a44ea22880a497db920b8130f3e8afa27a8e273b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 2 Nov 2016 19:54:07 +1000 Subject: [PATCH 605/897] Small refinement to multipart to singlepart alg --- .../plugins/processing/algs/qgis/MultipartToSingleparts.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/algs/qgis/MultipartToSingleparts.py b/python/plugins/processing/algs/qgis/MultipartToSingleparts.py index 75fb0a9e8ba1..b0aaee208e19 100644 --- a/python/plugins/processing/algs/qgis/MultipartToSingleparts.py +++ b/python/plugins/processing/algs/qgis/MultipartToSingleparts.py @@ -68,13 +68,12 @@ def processAlgorithm(self, progress): input_geometry = f.geometry() if input_geometry: if input_geometry.isMultipart(): - for i in range(input_geometry.geometry().numGeometries()): - singlepart_geometry = QgsGeometry(input_geometry.geometry().geometryN(i).clone()) + for g in input_geometry.asGeometryCollection(): output_feature = f - output_feature.setGeometry( singlepart_geometry ) + output_feature.setGeometry(g) writer.addFeature(output_feature) else: - writer.addFeature(f) + writer.addFeature(f) else: #input feature with null geometry writer.addFeature(f) From 03e29d4f01fda97d10dc1719f04eb302d3742952 Mon Sep 17 00:00:00 2001 From: nirvn Date: Wed, 2 Nov 2016 16:17:10 +0700 Subject: [PATCH 606/897] [processing] optimise singlepart to multipart algorithm - keep z/m/curved geometries intact - rewrite loop to avoid the cost of nb. feature x unique values --- .../algs/qgis/SinglePartsToMultiparts.py | 107 +++++------------- 1 file changed, 28 insertions(+), 79 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py b/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py index 0be51e4ccb32..3ddbfd77aa2c 100644 --- a/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py +++ b/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py @@ -65,7 +65,7 @@ def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) fieldName = self.getParameterValue(self.FIELD) - geomType = self.singleToMultiGeom(layer.wkbType()) + geomType = QgsWkbTypes.multiType(layer.wkbType()) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields().toList(), geomType, layer.crs()) @@ -73,86 +73,35 @@ def processAlgorithm(self, progress): inFeat = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() - outGeom = QgsGeometry() index = layer.fields().lookupField(fieldName) - unique = vector.getUniqueValues(layer, index) + collection_geom = {} + collection_attrs = {} + + features = vector.features(layer) current = 0 + total = 100.0 / (len(features)) + features = vector.features(layer) - total = 100.0 / (len(features) * len(unique)) - if not len(unique) == layer.featureCount(): - for i in unique: - multi_feature = [] - first = True - features = vector.features(layer) - for inFeat in features: - atMap = inFeat.attributes() - idVar = atMap[index] - if str(idVar).strip() == str(i).strip(): - if first: - attrs = atMap - first = False - inGeom = inFeat.geometry() - vType = inGeom.type() - feature_list = self.extractAsMulti(inGeom) - multi_feature.extend(feature_list) - - current += 1 - progress.setPercentage(int(current * total)) - - outFeat.setAttributes(attrs) - outGeom = QgsGeometry(self.convertGeometry(multi_feature, - vType)) - outFeat.setGeometry(outGeom) - writer.addFeature(outFeat) - - del writer - else: - raise GeoAlgorithmExecutionException( - self.tr('At least two features must have same attribute ' - 'value! Please choose another field...')) - - def singleToMultiGeom(self, wkbType): - try: - if wkbType in (QgsWkbTypes.Point, QgsWkbTypes.MultiPoint, - QgsWkbTypes.Point25D, QgsWkbTypes.MultiPoint25D): - return QgsWkbTypes.MultiPoint - elif wkbType in (QgsWkbTypes.LineString, QgsWkbTypes.MultiLineString, - QgsWkbTypes.MultiLineString25D, - QgsWkbTypes.LineString25D): - - return QgsWkbTypes.MultiLineString - elif wkbType in (QgsWkbTypes.Polygon, QgsWkbTypes.MultiPolygon, - QgsWkbTypes.MultiPolygon25D, QgsWkbTypes.Polygon25D): - - return QgsWkbTypes.MultiPolygon - else: - return QgsWkbTypes.Unknown - except Exception: - pass - - def extractAsMulti(self, geom): - if geom.type() == QgsWkbTypes.PointGeometry: - if geom.isMultipart(): - return geom.asMultiPoint() - else: - return [geom.asPoint()] - elif geom.type() == QgsWkbTypes.LineGeometry: - if geom.isMultipart(): - return geom.asMultiPolyline() - else: - return [geom.asPolyline()] - else: - if geom.isMultipart(): - return geom.asMultiPolygon() - else: - return [geom.asPolygon()] - - def convertGeometry(self, geom_list, vType): - if vType == QgsWkbTypes.PointGeometry: - return QgsGeometry().fromMultiPoint(geom_list) - elif vType == QgsWkbTypes.LineGeometry: - return QgsGeometry().fromMultiPolyline(geom_list) - else: - return QgsGeometry().fromMultiPolygon(geom_list) + for inFeat in features: + atMap = inFeat.attributes() + idVar = atMap[index] + key = str(idVar).strip() + if not key in collection_geom: + collection_geom[key] = [] + collection_attrs[key] = atMap + + inGeom = inFeat.geometry() + vType = inGeom.type() + collection_geom[key].append(inGeom) + + current += 1 + progress.setPercentage(int(current * total)) + + for key, geoms in collection_geom.items(): + outFeat.setAttributes(collection_attrs[key]) + outFeat.setGeometry(QgsGeometry.collectGeometry(geoms)) + writer.addFeature(outFeat) + + del writer From 9cd29f39d85c95e151ad945ca63d8c9b5a60c407 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 3 Nov 2016 16:32:28 +1000 Subject: [PATCH 607/897] [processing] Fix batch panel under Qt5 --- python/plugins/processing/gui/BatchPanel.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/BatchPanel.py b/python/plugins/processing/gui/BatchPanel.py index b999d73ab81a..8db29a59cb9f 100644 --- a/python/plugins/processing/gui/BatchPanel.py +++ b/python/plugins/processing/gui/BatchPanel.py @@ -132,11 +132,11 @@ def initWidgets(self): for i in range(3): self.addRow() - self.tblParameters.horizontalHeader().setResizeMode(QHeaderView.Interactive) + self.tblParameters.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive) self.tblParameters.horizontalHeader().setDefaultSectionSize(250) self.tblParameters.horizontalHeader().setMinimumSectionSize(150) - self.tblParameters.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents) - self.tblParameters.verticalHeader().setResizeMode(QHeaderView.ResizeToContents) + self.tblParameters.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) + self.tblParameters.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) self.tblParameters.horizontalHeader().setStretchLastSection(True) def load(self): From 769c82b57964c41e0febe7d2848e0925b3e13f53 Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 3 Nov 2016 09:57:03 +0700 Subject: [PATCH 608/897] [pal] fix curved labels failure with zero-width characters (fixes 15801) --- src/core/pal/feature.cpp | 4 ++++ .../src/python/test_qgspallabeling_placement.py | 12 ++++++++++++ tests/src/python/test_qgspallabeling_tests.py | 3 ++- .../sp_label_curved_zero_width_char.png | Bin 0 -> 8497 bytes 4 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 tests/testdata/control_images/expected_pal_placement/sp_label_curved_zero_width_char/sp_label_curved_zero_width_char.png diff --git a/src/core/pal/feature.cpp b/src/core/pal/feature.cpp index 266adf1cff3c..f8918c4134b1 100644 --- a/src/core/pal/feature.cpp +++ b/src/core/pal/feature.cpp @@ -1059,6 +1059,10 @@ LabelPosition* FeaturePart::curvedPlacementAtOffset( PointSet* path_positions, d // grab the next character according to the orientation LabelInfo::CharacterInfo& ci = ( orientation > 0 ? li->char_info[i] : li->char_info[li->char_num-i-1] ); + if ( qgsDoubleNear( ci.width, 0.0 ) ) + // Certain scripts rely on zero-width character, skip those to prevent failure (see #15801) + continue; + double start_x, start_y, end_x, end_y; if ( nextCharPosition( ci.width, path_distances[index], path_positions, index, distance, start_x, start_y, end_x, end_y ) == false ) { diff --git a/tests/src/python/test_qgspallabeling_placement.py b/tests/src/python/test_qgspallabeling_placement.py index 571d2b75501b..14368ba41d72 100644 --- a/tests/src/python/test_qgspallabeling_placement.py +++ b/tests/src/python/test_qgspallabeling_placement.py @@ -433,6 +433,18 @@ def test_label_line_avoid_jaggy(self): self.removeMapLayer(self.layer) self.layer = None + def test_label_curved_zero_width_char(self): + # Test that curved label work with zero-width characters + self.layer = TestQgsPalLabeling.loadFeatureLayer('line') + self._TestMapSettings = self.cloneMapSettings(self._MapSettings) + self.lyr.placement = QgsPalLayerSettings.Curved + self.lyr.placementFlags = QgsPalLayerSettings.OnLine + self.lyr.fieldName = "'invisible​space'" + self.lyr.isExpression = True + self.checkTest() + self.removeMapLayer(self.layer) + self.layer = None + if __name__ == '__main__': # NOTE: unless PAL_SUITE env var is set all test class methods will be run # SEE: test_qgspallabeling_tests.suiteTests() to define suite diff --git a/tests/src/python/test_qgspallabeling_tests.py b/tests/src/python/test_qgspallabeling_tests.py index bdad4cbdae09..f121c752e94e 100644 --- a/tests/src/python/test_qgspallabeling_tests.py +++ b/tests/src/python/test_qgspallabeling_tests.py @@ -308,8 +308,9 @@ def test_curved_placement_below(self): self.lyr.placementFlags = QgsPalLayerSettings.BelowLine | QgsPalLayerSettings.MapOrientation self.checkTest() - # noinspection PyPep8Naming + + def suiteTests(): """ Use to define which tests are run when PAL_SUITE is set. diff --git a/tests/testdata/control_images/expected_pal_placement/sp_label_curved_zero_width_char/sp_label_curved_zero_width_char.png b/tests/testdata/control_images/expected_pal_placement/sp_label_curved_zero_width_char/sp_label_curved_zero_width_char.png new file mode 100644 index 0000000000000000000000000000000000000000..555b8a814e1a2404bb8c5eda78d8b2cbf1e094bb GIT binary patch literal 8497 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 RFkm7Gu4SlMrEx#%e*m|g03iSX literal 0 HcmV?d00001 From 434bbeabfcd39b32d1725a6d2a01fba751243069 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 26 Apr 2016 19:36:09 +0300 Subject: [PATCH 609/897] Add global python startup script support in addition to per-user scripts (fix #6297) --- src/python/qgspythonutilsimpl.cpp | 16 ++++++++++++++++ src/python/qgspythonutilsimpl.h | 3 +++ 2 files changed, 19 insertions(+) diff --git a/src/python/qgspythonutilsimpl.cpp b/src/python/qgspythonutilsimpl.cpp index 8a2b2eec98a5..930a2c9cdb26 100644 --- a/src/python/qgspythonutilsimpl.cpp +++ b/src/python/qgspythonutilsimpl.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #if (PY_VERSION_HEX < 0x03000000) @@ -209,6 +210,19 @@ bool QgsPythonUtilsImpl::checkQgisUser() return true; } +void QgsPythonUtilsImpl::doGlobalImports() +{ + QString startupPath = QStandardPaths::locate( QStandardPaths::AppDataLocation, "global_startup.py" ); + //runString( "if os.path.exists(" + startuppath + "): from global_startup import *\n" ); + if ( !startupPath.isEmpty() ) + { + runString( "import importlib.util" ); + runString( QString( "spec = importlib.util.spec_from_file_location('global_startup','%1')" ).arg( startupPath ) ); + runString( "module = importlib.util.module_from_spec(spec)" ); + runString( "spec.loader.exec_module(module)" ); + } +} + void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) { init(); @@ -224,6 +238,7 @@ void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) exitPython(); return; } + doGlobalImports(); finish(); } @@ -249,6 +264,7 @@ void QgsPythonUtilsImpl::initServerPython( QgsServerInterface* interface ) // This is the other main difference with initInterface() for desktop plugins runString( "qgis.utils.initServerInterface(" + QString::number(( unsigned long ) interface ) + ')' ); + doGlobalImports(); finish(); } diff --git a/src/python/qgspythonutilsimpl.h b/src/python/qgspythonutilsimpl.h index 348689f1ed8b..45055bc575a8 100644 --- a/src/python/qgspythonutilsimpl.h +++ b/src/python/qgspythonutilsimpl.h @@ -126,6 +126,9 @@ class QgsPythonUtilsImpl : public QgsPythonUtils //@return true if qgis.user could be imported bool checkQgisUser(); + //! import global Python code + void doGlobalImports(); + //! cleanup Python context void finish(); From 373e591a80c17010db436440b5d83f6144e1a169 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 3 Nov 2016 12:04:26 +0200 Subject: [PATCH 610/897] drop old user startup script in favour of the new system User script should be placed into $HOME/.local/share/QGIS. Additionally global scripts from /usr/local/share and /usr/share will be loaded if present --- python/user.py | 5 ----- src/python/qgspythonutilsimpl.cpp | 22 ++++++++++++++-------- src/python/qgspythonutilsimpl.h | 6 ++---- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/python/user.py b/python/user.py index 824927d8edd0..e6298af15851 100644 --- a/python/user.py +++ b/python/user.py @@ -55,14 +55,9 @@ def load_user_expressions(path): userpythonhome = os.path.join(QgsApplication.qgisSettingsDirPath(), "python") expressionspath = os.path.join(userpythonhome, "expressions") -startuppy = os.path.join(userpythonhome, "startup.py") sys.path.append(userpythonhome) -# exec startup script -if os.path.exists(startuppy): - exec(compile(open(startuppy).read(), startuppy, 'exec'), locals(), globals()) - if not os.path.exists(expressionspath): os.makedirs(expressionspath) diff --git a/src/python/qgspythonutilsimpl.cpp b/src/python/qgspythonutilsimpl.cpp index 930a2c9cdb26..32c9999c1d6b 100644 --- a/src/python/qgspythonutilsimpl.cpp +++ b/src/python/qgspythonutilsimpl.cpp @@ -210,14 +210,20 @@ bool QgsPythonUtilsImpl::checkQgisUser() return true; } -void QgsPythonUtilsImpl::doGlobalImports() +void QgsPythonUtilsImpl::doCustomImports() { - QString startupPath = QStandardPaths::locate( QStandardPaths::AppDataLocation, "global_startup.py" ); - //runString( "if os.path.exists(" + startuppath + "): from global_startup import *\n" ); - if ( !startupPath.isEmpty() ) + QStringList startupPaths = QStandardPaths::locateAll( QStandardPaths::AppDataLocation, "startup.py" ); + if ( startupPaths.isEmpty() ) { - runString( "import importlib.util" ); - runString( QString( "spec = importlib.util.spec_from_file_location('global_startup','%1')" ).arg( startupPath ) ); + return; + } + + runString( "import importlib.util" ); + + QStringList::const_iterator iter = startupPaths.constBegin(); + for ( ; iter != startupPaths.constEnd(); ++iter ) + { + runString( QString( "spec = importlib.util.spec_from_file_location('startup','%1')" ).arg( *iter ) ); runString( "module = importlib.util.module_from_spec(spec)" ); runString( "spec.loader.exec_module(module)" ); } @@ -238,7 +244,7 @@ void QgsPythonUtilsImpl::initPython( QgisInterface* interface ) exitPython(); return; } - doGlobalImports(); + doCustomImports(); finish(); } @@ -264,7 +270,7 @@ void QgsPythonUtilsImpl::initServerPython( QgsServerInterface* interface ) // This is the other main difference with initInterface() for desktop plugins runString( "qgis.utils.initServerInterface(" + QString::number(( unsigned long ) interface ) + ')' ); - doGlobalImports(); + doCustomImports(); finish(); } diff --git a/src/python/qgspythonutilsimpl.h b/src/python/qgspythonutilsimpl.h index 45055bc575a8..45a82aa2e80f 100644 --- a/src/python/qgspythonutilsimpl.h +++ b/src/python/qgspythonutilsimpl.h @@ -126,13 +126,12 @@ class QgsPythonUtilsImpl : public QgsPythonUtils //@return true if qgis.user could be imported bool checkQgisUser(); - //! import global Python code - void doGlobalImports(); + //! import custom user and global Python code (startup scripts) + void doCustomImports(); //! cleanup Python context void finish(); - void installErrorHook(); void uninstallErrorHook(); @@ -152,5 +151,4 @@ class QgsPythonUtilsImpl : public QgsPythonUtils bool mPythonEnabled; }; - #endif From 8b3c39a22043a923cae33f0111a8a2010c72c42e Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 3 Nov 2016 16:57:29 +0200 Subject: [PATCH 611/897] [processing] add missed description files for OTB 5.4.0 --- .../processing/algs/otb/CMakeLists.txt | 6 + .../algs/otb/description/5.4.0/BandMath.xml | 43 +++ .../BinaryMorphologicalOperation-closing.xml | 77 ++++ .../BinaryMorphologicalOperation-dilate.xml | 97 +++++ .../BinaryMorphologicalOperation-erode.xml | 77 ++++ .../BinaryMorphologicalOperation-opening.xml | 77 ++++ .../5.4.0/ClassificationMapRegularization.xml | 69 ++++ .../5.4.0/ColorMapping-continuous.xml | 104 ++++++ .../description/5.4.0/ColorMapping-custom.xml | 68 ++++ .../description/5.4.0/ColorMapping-image.xml | 94 +++++ .../5.4.0/ColorMapping-optimal.xml | 67 ++++ .../otb/description/5.4.0/CompareImages.xml | 81 +++++ .../5.4.0/ComputeConfusionMatrix-raster.xml | 60 +++ .../5.4.0/ComputeConfusionMatrix-vector.xml | 71 ++++ .../5.4.0/ComputeImagesStatistics.xml | 31 ++ .../ComputeOGRLayersFeaturesStatistics.xml | 30 ++ .../5.4.0/ComputePolylineFeatureFromImage.xml | 60 +++ .../description/5.4.0/ConcatenateImages.xml | 32 ++ .../5.4.0/ConcatenateVectorData.xml | 23 ++ .../5.4.0/ConnectedComponentSegmentation.xml | 72 ++++ .../algs/otb/description/5.4.0/Convert.xml | 83 +++++ .../algs/otb/description/5.4.0/DEMConvert.xml | 20 + .../otb/description/5.4.0/Despeckle-frost.xml | 64 ++++ .../description/5.4.0/Despeckle-gammamap.xml | 64 ++++ .../otb/description/5.4.0/Despeckle-kuan.xml | 64 ++++ .../otb/description/5.4.0/Despeckle-lee.xml | 64 ++++ .../5.4.0/DimensionalityReduction-ica.xml | 85 +++++ .../5.4.0/DimensionalityReduction-maf.xml | 58 +++ .../5.4.0/DimensionalityReduction-napca.xml | 85 +++++ .../5.4.0/DimensionalityReduction-pca.xml | 65 ++++ .../5.4.0/EdgeExtraction-gradient.xml | 54 +++ .../5.4.0/EdgeExtraction-sobel.xml | 54 +++ .../5.4.0/EdgeExtraction-touzi.xml | 64 ++++ .../otb/description/5.4.0/ExtractROI-fit.xml | 61 ++++ .../description/5.4.0/ExtractROI-standard.xml | 84 +++++ ...FusionOfClassifications-dempstershafer.xml | 79 ++++ ...FusionOfClassifications-majorityvoting.xml | 55 +++ ...rayScaleMorphologicalOperation-closing.xml | 77 ++++ ...GrayScaleMorphologicalOperation-dilate.xml | 77 ++++ .../GrayScaleMorphologicalOperation-erode.xml | 77 ++++ ...rayScaleMorphologicalOperation-opening.xml | 77 ++++ .../5.4.0/HaralickTextureExtraction.xml | 126 +++++++ .../5.4.0/HooverCompareSegmentation.xml | 95 +++++ .../otb/description/5.4.0/ImageClassifier.xml | 72 ++++ .../otb/description/5.4.0/ImageEnvelope.xml | 42 +++ .../5.4.0/KMeansClassification.xml | 84 +++++ .../algs/otb/description/5.4.0/KmzExport.xml | 54 +++ .../description/5.4.0/LSMSSegmentation.xml | 94 +++++ .../5.4.0/LSMSSmallRegionsMerging.xml | 58 +++ .../description/5.4.0/LSMSVectorization.xml | 47 +++ .../5.4.0/LineSegmentDetection.xml | 30 ++ .../5.4.0/LocalStatisticExtraction.xml | 51 +++ .../description/5.4.0/MeanShiftSmoothing.xml | 96 +++++ .../5.4.0/MultivariateAlterationDetector.xml | 38 ++ .../description/5.4.0/OGRLayerClassifier.xml | 48 +++ .../5.4.0/OrthoRectification-epsg.xml | 124 +++++++ .../5.4.0/OrthoRectification-fit-to-ortho.xml | 107 ++++++ .../OrthoRectification-lambert-WGS84.xml | 116 ++++++ .../5.4.0/OrthoRectification-utm.xml | 132 +++++++ .../description/5.4.0/Pansharpening-bayes.xml | 71 ++++ .../description/5.4.0/Pansharpening-lmvm.xml | 71 ++++ .../description/5.4.0/Pansharpening-rcs.xml | 51 +++ .../description/5.4.0/RadiometricIndices.xml | 131 +++++++ .../description/5.4.0/Rasterization-image.xml | 83 +++++ .../5.4.0/Rasterization-manual.xml | 146 ++++++++ .../otb/description/5.4.0/ReadImageInfo.xml | 62 ++++ .../algs/otb/description/5.4.0/Rescale.xml | 51 +++ .../5.4.0/RigidTransformResample-id.xml | 89 +++++ .../5.4.0/RigidTransformResample-rotation.xml | 99 +++++ .../RigidTransformResample-translation.xml | 109 ++++++ .../5.4.0/SFSTextureExtraction.xml | 91 +++++ .../description/5.4.0/SOMClassification.xml | 155 ++++++++ .../otb/description/5.4.0/Segmentation-cc.xml | 165 +++++++++ .../5.4.0/Segmentation-meanshift.xml | 205 +++++++++++ .../5.4.0/Segmentation-mprofiles.xml | 195 ++++++++++ .../5.4.0/Segmentation-watershed.xml | 175 +++++++++ .../description/5.4.0/Smoothing-anidif.xml | 74 ++++ .../description/5.4.0/Smoothing-gaussian.xml | 54 +++ .../otb/description/5.4.0/Smoothing-mean.xml | 54 +++ .../otb/description/5.4.0/StereoFramework.xml | 344 ++++++++++++++++++ .../otb/description/5.4.0/Superimpose.xml | 97 +++++ .../algs/otb/description/5.4.0/TileFusion.xml | 42 +++ .../5.4.0/TrainImagesClassifier-ann.xml | 268 ++++++++++++++ .../5.4.0/TrainImagesClassifier-bayes.xml | 134 +++++++ .../5.4.0/TrainImagesClassifier-boost.xml | 180 +++++++++ .../5.4.0/TrainImagesClassifier-dt.xml | 200 ++++++++++ .../5.4.0/TrainImagesClassifier-gbt.xml | 174 +++++++++ .../5.4.0/TrainImagesClassifier-knn.xml | 144 ++++++++ .../5.4.0/TrainImagesClassifier-rf.xml | 204 +++++++++++ .../5.4.0/TrainOGRLayersClassifier.xml | 48 +++ .../5.4.0/VectorDataExtractROI.xml | 40 ++ .../5.4.0/VectorDataReprojection-image.xml | 59 +++ .../5.4.0/VectorDataReprojection-user.xml | 97 +++++ .../description/5.4.0/VectorDataTransform.xml | 90 +++++ .../otb/description/5.4.0/doc/BandMath.html | 6 + .../BinaryMorphologicalOperation-closing.html | 5 + .../BinaryMorphologicalOperation-dilate.html | 5 + .../BinaryMorphologicalOperation-erode.html | 5 + .../BinaryMorphologicalOperation-opening.html | 5 + .../doc/BinaryMorphologicalOperation.html | 5 + .../description/5.4.0/doc/BlockMatching.html | 5 + .../5.4.0/doc/BundleToPerfectSensor.html | 5 + .../doc/ClassificationMapRegularization.html | 7 + .../5.4.0/doc/ColorMapping-continuous.html | 13 + .../5.4.0/doc/ColorMapping-custom.html | 13 + .../5.4.0/doc/ColorMapping-image.html | 13 + .../5.4.0/doc/ColorMapping-optimal.html | 13 + .../description/5.4.0/doc/ColorMapping.html | 13 + .../description/5.4.0/doc/CompareImages.html | 5 + .../doc/ComputeConfusionMatrix-raster.html | 5 + .../doc/ComputeConfusionMatrix-vector.html | 5 + .../5.4.0/doc/ComputeConfusionMatrix.html | 5 + .../5.4.0/doc/ComputeImagesStatistics.html | 5 + .../ComputeOGRLayersFeaturesStatistics.html | 5 + .../doc/ComputePolylineFeatureFromImage.html | 5 + .../5.4.0/doc/ConcatenateImages.html | 5 + .../5.4.0/doc/ConcatenateVectorData.html | 5 + .../doc/ConnectedComponentSegmentation.html | 5 + .../otb/description/5.4.0/doc/Convert.html | 6 + .../5.4.0/doc/ConvertCartoToGeoPoint.html | 5 + .../5.4.0/doc/ConvertSensorToGeoPoint.html | 5 + .../otb/description/5.4.0/doc/DEMConvert.html | 5 + .../5.4.0/doc/DSFuzzyModelEstimation.html | 5 + .../5.4.0/doc/Despeckle-frost.html | 5 + .../5.4.0/doc/Despeckle-gammamap.html | 5 + .../description/5.4.0/doc/Despeckle-kuan.html | 5 + .../description/5.4.0/doc/Despeckle-lee.html | 5 + .../otb/description/5.4.0/doc/Despeckle.html | 5 + .../doc/DimensionalityReduction-ica.html | 5 + .../doc/DimensionalityReduction-maf.html | 5 + .../doc/DimensionalityReduction-napca.html | 5 + .../doc/DimensionalityReduction-pca.html | 5 + .../5.4.0/doc/DimensionalityReduction.html | 5 + .../5.4.0/doc/DisparityMapToElevationMap.html | 5 + .../5.4.0/doc/DownloadSRTMTiles.html | 5 + .../5.4.0/doc/EdgeExtraction-gradient.html | 5 + .../5.4.0/doc/EdgeExtraction-sobel.html | 5 + .../5.4.0/doc/EdgeExtraction-touzi.html | 5 + .../description/5.4.0/doc/EdgeExtraction.html | 5 + .../description/5.4.0/doc/ExtractROI-fit.html | 5 + .../5.4.0/doc/ExtractROI-standard.html | 5 + .../otb/description/5.4.0/doc/ExtractROI.html | 5 + .../5.4.0/doc/FineRegistration.html | 5 + ...usionOfClassifications-dempstershafer.html | 9 + ...usionOfClassifications-majorityvoting.html | 9 + .../5.4.0/doc/FusionOfClassifications.html | 9 + .../5.4.0/doc/GeneratePlyFile.html | 5 + .../5.4.0/doc/GenerateRPCSensorModel.html | 5 + ...ayScaleMorphologicalOperation-closing.html | 5 + ...rayScaleMorphologicalOperation-dilate.html | 5 + ...GrayScaleMorphologicalOperation-erode.html | 5 + ...ayScaleMorphologicalOperation-opening.html | 5 + .../doc/GrayScaleMorphologicalOperation.html | 5 + .../5.4.0/doc/GridBasedImageResampling.html | 5 + .../5.4.0/doc/HaralickTextureExtraction.html | 5 + .../5.4.0/doc/HomologousPointsExtraction.html | 5 + .../5.4.0/doc/HooverCompareSegmentation.html | 7 + .../5.4.0/doc/HyperspectralUnmixing.html | 8 + .../5.4.0/doc/ImageClassifier.html | 16 + .../description/5.4.0/doc/ImageEnvelope.html | 5 + .../5.4.0/doc/KMeansClassification.html | 5 + .../otb/description/5.4.0/doc/KmzExport.html | 5 + .../5.4.0/doc/LSMSSegmentation.html | 5 + .../5.4.0/doc/LSMSSmallRegionsMerging.html | 5 + .../5.4.0/doc/LSMSVectorization.html | 5 + .../5.4.0/doc/LineSegmentDetection.html | 7 + .../5.4.0/doc/LocalStatisticExtraction.html | 5 + .../description/5.4.0/doc/ManageNoData.html | 5 + .../5.4.0/doc/MeanShiftSmoothing.html | 5 + .../5.4.0/doc/MultiResolutionPyramid.html | 5 + .../doc/MultivariateAlterationDetector.html | 21 ++ .../5.4.0/doc/OGRLayerClassifier.html | 5 + .../description/5.4.0/doc/OSMDownloader.html | 6 + .../5.4.0/doc/ObtainUTMZoneFromGeoPoint.html | 5 + .../5.4.0/doc/OrthoRectification-epsg.html | 7 + .../doc/OrthoRectification-fit-to-ortho.html | 7 + .../doc/OrthoRectification-lambert-WGS84.html | 7 + .../5.4.0/doc/OrthoRectification-utm.html | 7 + .../5.4.0/doc/OrthoRectification.html | 7 + .../5.4.0/doc/Pansharpening-bayes.html | 5 + .../5.4.0/doc/Pansharpening-lmvm.html | 5 + .../5.4.0/doc/Pansharpening-rcs.html | 5 + .../description/5.4.0/doc/Pansharpening.html | 5 + .../otb/description/5.4.0/doc/PixelValue.html | 6 + .../5.4.0/doc/PolygonClassStatistics.html | 12 + .../5.4.0/doc/PredictRegression.html | 5 + .../otb/description/5.4.0/doc/Quicklook.html | 7 + .../5.4.0/doc/RadiometricIndices.html | 25 ++ .../5.4.0/doc/Rasterization-image.html | 6 + .../5.4.0/doc/Rasterization-manual.html | 6 + .../description/5.4.0/doc/Rasterization.html | 6 + .../description/5.4.0/doc/ReadImageInfo.html | 5 + .../5.4.0/doc/RefineSensorModel.html | 5 + .../otb/description/5.4.0/doc/Rescale.html | 5 + .../5.4.0/doc/RigidTransformResample-id.html | 5 + .../doc/RigidTransformResample-rotation.html | 5 + .../RigidTransformResample-translation.html | 5 + .../5.4.0/doc/RigidTransformResample.html | 5 + .../description/5.4.0/doc/SARCalibration.html | 7 + .../5.4.0/doc/SARDecompositions.html | 15 + .../5.4.0/doc/SARPolarMatrixConvert.html | 32 ++ .../description/5.4.0/doc/SARPolarSynth.html | 32 ++ .../5.4.0/doc/SFSTextureExtraction.html | 5 + .../5.4.0/doc/SOMClassification.html | 5 + .../5.4.0/doc/SarRadiometricCalibration.html | 7 + .../5.4.0/doc/Segmentation-cc.html | 11 + .../5.4.0/doc/Segmentation-meanshift.html | 11 + .../5.4.0/doc/Segmentation-mprofiles.html | 11 + .../5.4.0/doc/Segmentation-watershed.html | 11 + .../description/5.4.0/doc/Segmentation.html | 11 + .../5.4.0/doc/Smoothing-anidif.html | 5 + .../5.4.0/doc/Smoothing-gaussian.html | 5 + .../description/5.4.0/doc/Smoothing-mean.html | 5 + .../otb/description/5.4.0/doc/Smoothing.html | 5 + .../otb/description/5.4.0/doc/SplitImage.html | 5 + .../5.4.0/doc/StereoFramework.html | 16 + .../doc/StereoRectificationGridGenerator.html | 5 + .../description/5.4.0/doc/Superimpose.html | 5 + .../5.4.0/doc/TestApplication.html | 5 + .../otb/description/5.4.0/doc/TileFusion.html | 5 + .../5.4.0/doc/TrainImagesClassifier-ann.html | 8 + .../doc/TrainImagesClassifier-bayes.html | 8 + .../doc/TrainImagesClassifier-boost.html | 8 + .../5.4.0/doc/TrainImagesClassifier-dt.html | 8 + .../5.4.0/doc/TrainImagesClassifier-gbt.html | 8 + .../5.4.0/doc/TrainImagesClassifier-knn.html | 8 + .../5.4.0/doc/TrainImagesClassifier-rf.html | 8 + .../5.4.0/doc/TrainImagesClassifier.html | 8 + .../5.4.0/doc/TrainOGRLayersClassifier.html | 5 + .../5.4.0/doc/TrainRegression.html | 7 + .../5.4.0/doc/VectorDataDSValidation.html | 5 + .../5.4.0/doc/VectorDataExtractROI.html | 5 + .../doc/VectorDataReprojection-image.html | 7 + .../doc/VectorDataReprojection-user.html | 7 + .../5.4.0/doc/VectorDataReprojection.html | 7 + .../5.4.0/doc/VectorDataSetField.html | 5 + .../5.4.0/doc/VectorDataTransform.html | 5 + .../5.4.0/doc/VertexComponentAnalysis.html | 5 + 238 files changed, 9311 insertions(+) create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/BandMath.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-closing.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-dilate.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-erode.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-opening.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ClassificationMapRegularization.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-continuous.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-custom.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-image.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-optimal.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/CompareImages.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-raster.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-vector.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ComputeImagesStatistics.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ComputeOGRLayersFeaturesStatistics.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ComputePolylineFeatureFromImage.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ConcatenateImages.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ConcatenateVectorData.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ConnectedComponentSegmentation.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Convert.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/DEMConvert.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Despeckle-frost.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Despeckle-gammamap.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Despeckle-kuan.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Despeckle-lee.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-ica.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-maf.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-napca.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-pca.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-gradient.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-sobel.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-touzi.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-fit.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-standard.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-dempstershafer.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-majorityvoting.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-closing.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-dilate.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-erode.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-opening.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/HaralickTextureExtraction.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/HooverCompareSegmentation.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ImageClassifier.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ImageEnvelope.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/KMeansClassification.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/KmzExport.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/LSMSSegmentation.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/LSMSSmallRegionsMerging.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/LSMSVectorization.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/LineSegmentDetection.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/LocalStatisticExtraction.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/MeanShiftSmoothing.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/MultivariateAlterationDetector.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/OGRLayerClassifier.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-epsg.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-fit-to-ortho.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-lambert-WGS84.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-utm.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-bayes.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-lmvm.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-rcs.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/RadiometricIndices.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Rasterization-image.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Rasterization-manual.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/ReadImageInfo.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Rescale.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-id.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-rotation.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-translation.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/SFSTextureExtraction.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/SOMClassification.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Segmentation-cc.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Segmentation-meanshift.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Segmentation-mprofiles.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Segmentation-watershed.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Smoothing-anidif.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Smoothing-gaussian.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Smoothing-mean.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/StereoFramework.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/Superimpose.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TileFusion.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-ann.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-bayes.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-boost.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-dt.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-gbt.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-knn.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-rf.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/TrainOGRLayersClassifier.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/VectorDataExtractROI.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-image.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-user.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/VectorDataTransform.xml create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BandMath.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-closing.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-dilate.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-erode.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-opening.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BlockMatching.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/BundleToPerfectSensor.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ClassificationMapRegularization.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-continuous.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-custom.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-image.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-optimal.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/CompareImages.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-raster.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-vector.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeImagesStatistics.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeOGRLayersFeaturesStatistics.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ComputePolylineFeatureFromImage.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateImages.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateVectorData.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ConnectedComponentSegmentation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Convert.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertCartoToGeoPoint.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertSensorToGeoPoint.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DEMConvert.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DSFuzzyModelEstimation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-frost.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-gammamap.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-kuan.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-lee.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-ica.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-maf.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-napca.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-pca.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DisparityMapToElevationMap.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/DownloadSRTMTiles.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-gradient.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-sobel.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-touzi.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-fit.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-standard.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/FineRegistration.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-dempstershafer.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-majorityvoting.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GeneratePlyFile.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GenerateRPCSensorModel.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-closing.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-dilate.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-erode.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-opening.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/GridBasedImageResampling.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/HaralickTextureExtraction.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/HomologousPointsExtraction.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/HooverCompareSegmentation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/HyperspectralUnmixing.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ImageClassifier.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ImageEnvelope.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/KMeansClassification.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/KmzExport.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSegmentation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSmallRegionsMerging.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSVectorization.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/LineSegmentDetection.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/LocalStatisticExtraction.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ManageNoData.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/MeanShiftSmoothing.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/MultiResolutionPyramid.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/MultivariateAlterationDetector.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OGRLayerClassifier.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OSMDownloader.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ObtainUTMZoneFromGeoPoint.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-epsg.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-fit-to-ortho.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-lambert-WGS84.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-utm.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-bayes.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-lmvm.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-rcs.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/PixelValue.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/PolygonClassStatistics.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/PredictRegression.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Quicklook.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/RadiometricIndices.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-image.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-manual.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/ReadImageInfo.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/RefineSensorModel.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Rescale.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-id.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-rotation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-translation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SARCalibration.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SARDecompositions.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarMatrixConvert.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarSynth.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SFSTextureExtraction.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SOMClassification.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SarRadiometricCalibration.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-cc.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-meanshift.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-mprofiles.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-watershed.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-anidif.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-gaussian.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-mean.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/SplitImage.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/StereoFramework.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/StereoRectificationGridGenerator.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/Superimpose.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TestApplication.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TileFusion.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-ann.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-bayes.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-boost.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-dt.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-gbt.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-knn.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-rf.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainOGRLayersClassifier.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/TrainRegression.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataDSValidation.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataExtractROI.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-image.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-user.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataSetField.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataTransform.html create mode 100644 python/plugins/processing/algs/otb/description/5.4.0/doc/VertexComponentAnalysis.html diff --git a/python/plugins/processing/algs/otb/CMakeLists.txt b/python/plugins/processing/algs/otb/CMakeLists.txt index dab51b54d2e8..c58a7c20df5a 100644 --- a/python/plugins/processing/algs/otb/CMakeLists.txt +++ b/python/plugins/processing/algs/otb/CMakeLists.txt @@ -3,6 +3,9 @@ FILE(GLOB HELPER_FILES helper/*.py) FILE(GLOB DESCR_FILES description/5.0.0/*.xml) FiLE(GLOB HELP_FILES description/5.0.0/doc/*.html) +FILE(GLOB DESCR_FILES description/5.4.0/*.xml) +FiLE(GLOB HELP_FILES description/5.4.0/doc/*.html) + FILE(GLOB DESCR_FILES description/5.6.0/*.xml) FiLE(GLOB HELP_FILES description/5.6.0/doc/*.html) @@ -12,5 +15,8 @@ PLUGIN_INSTALL(processing ./algs/otb/helper ${HELPER_FILES}) PLUGIN_INSTALL(processing ./algs/otb/description/5.0.0 ${DESCR_FILES}) PLUGIN_INSTALL(processing ./algs/otb/description/5.0.0/doc ${HELP_FILES}) +PLUGIN_INSTALL(processing ./algs/otb/description/5.4.0 ${DESCR_FILES}) +PLUGIN_INSTALL(processing ./algs/otb/description/5.4.0/doc ${HELP_FILES}) + PLUGIN_INSTALL(processing ./algs/otb/description/5.6.0 ${DESCR_FILES}) PLUGIN_INSTALL(processing ./algs/otb/description/5.6.0/doc ${HELP_FILES}) diff --git a/python/plugins/processing/algs/otb/description/5.4.0/BandMath.xml b/python/plugins/processing/algs/otb/description/5.4.0/BandMath.xml new file mode 100644 index 000000000000..8b42b40b3d94 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/BandMath.xml @@ -0,0 +1,43 @@ + + BandMath + otbcli_BandMath + Band Math + Miscellaneous + Perform a mathematical operation on monoband images + + ParameterMultipleInput + il + Input image list + Image list to perform computation on. + + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterString + exp + Expression + The mathematical expression to apply. +Use im1b1 for the first band, im1b2 for the second one... + + + False + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-closing.xml b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-closing.xml new file mode 100644 index 000000000000..2961f167e085 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-closing.xml @@ -0,0 +1,77 @@ + + BinaryMorphologicalOperation-closing + otbcli_BinaryMorphologicalOperation + BinaryMorphologicalOperation (closing) + Feature Extraction + Performs morphological operations on an input image channel + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + closing + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-dilate.xml b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-dilate.xml new file mode 100644 index 000000000000..23477a328fa3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-dilate.xml @@ -0,0 +1,97 @@ + + BinaryMorphologicalOperation-dilate + otbcli_BinaryMorphologicalOperation + BinaryMorphologicalOperation (dilate) + Feature Extraction + Performs morphological operations on an input image channel + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + dilate + + + 0 + False + + + ParameterNumber + filter.dilate.foreval + Foreground Value + The Foreground Value + + + 1 + False + + + ParameterNumber + filter.dilate.backval + Background Value + The Background Value + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-erode.xml b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-erode.xml new file mode 100644 index 000000000000..c25c24f0e54c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-erode.xml @@ -0,0 +1,77 @@ + + BinaryMorphologicalOperation-erode + otbcli_BinaryMorphologicalOperation + BinaryMorphologicalOperation (erode) + Feature Extraction + Performs morphological operations on an input image channel + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + erode + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-opening.xml b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-opening.xml new file mode 100644 index 000000000000..9af9fcb74cb0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/BinaryMorphologicalOperation-opening.xml @@ -0,0 +1,77 @@ + + BinaryMorphologicalOperation-opening + otbcli_BinaryMorphologicalOperation + BinaryMorphologicalOperation (opening) + Feature Extraction + Performs morphological operations on an input image channel + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + opening + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ClassificationMapRegularization.xml b/python/plugins/processing/algs/otb/description/5.4.0/ClassificationMapRegularization.xml new file mode 100644 index 000000000000..549ddcd791cb --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ClassificationMapRegularization.xml @@ -0,0 +1,69 @@ + + ClassificationMapRegularization + otbcli_ClassificationMapRegularization + Classification Map Regularization + Learning + Filters the input labeled image using Majority Voting in a ball shaped neighbordhood. + + ParameterRaster + io.in + Input classification image + The input labeled image to regularize. + False + + + OutputRaster + io.out + Output regularized image + The output regularized labeled image. + + + + ParameterNumber + ip.radius + Structuring element radius (in pixels) + The radius of the ball shaped structuring element (expressed in pixels). By default, 'ip.radius = 1 pixel'. + + + 1 + False + + + ParameterBoolean + ip.suvbool + Multiple majority: Undecided(X)/Original + Pixels with more than 1 majority class are marked as Undecided if this parameter is checked (true), or keep their Original labels otherwise (false). Please note that the Undecided value must be different from existing labels in the input labeled image. By default, 'ip.suvbool = false'. + True + True + + + ParameterNumber + ip.nodatalabel + Label for the NoData class + Label for the NoData class. Such input pixels keep their NoData label in the output image. By default, 'ip.nodatalabel = 0'. + + + 0 + False + + + ParameterNumber + ip.undecidedlabel + Label for the Undecided class + Label for the Undecided class. By default, 'ip.undecidedlabel = 0'. + + + 0 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-continuous.xml b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-continuous.xml new file mode 100644 index 000000000000..82ef3bd7a488 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-continuous.xml @@ -0,0 +1,104 @@ + + ColorMapping-continuous + otbcli_ColorMapping + ColorMapping (continuous) + Image Manipulation + Maps an input label image to 8-bits RGB using look-up tables. + + ParameterRaster + in + Input Image + Input image filename + False + + + OutputRaster + out + Output Image + Output image filename + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + op + Operation + Selection of the operation to execute (default is : label to color). + + + labeltocolor + + + 0 + False + + + ParameterSelection + method + Color mapping method + Selection of color mapping methods and their parameters. + + + continuous + + + 0 + False + + + ParameterSelection + method.continuous.lut + Look-up tables + Available look-up tables. + + + red + green + blue + grey + hot + cool + spring + summer + autumn + winter + copper + jet + hsv + overunder + relief + + + 0 + False + + + ParameterNumber + method.continuous.min + Mapping range lower value + Set the lower input value of the mapping range. + + + 0 + False + + + ParameterNumber + method.continuous.max + Mapping range higher value + Set the higher input value of the mapping range. + + + 255 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-custom.xml b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-custom.xml new file mode 100644 index 000000000000..7e9c7e0b515b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-custom.xml @@ -0,0 +1,68 @@ + + ColorMapping-custom + otbcli_ColorMapping + ColorMapping (custom) + Image Manipulation + Maps an input label image to 8-bits RGB using look-up tables. + + ParameterRaster + in + Input Image + Input image filename + False + + + OutputRaster + out + Output Image + Output image filename + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + op + Operation + Selection of the operation to execute (default is : label to color). + + + labeltocolor + + + 0 + False + + + ParameterSelection + method + Color mapping method + Selection of color mapping methods and their parameters. + + + custom + + + 0 + False + + + ParameterFile + method.custom.lut + Look-up table file + An ASCII file containing the look-up table +with one color per line +(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0) +Lines beginning with a # are ignored + + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-image.xml b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-image.xml new file mode 100644 index 000000000000..3d52f5ffa05e --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-image.xml @@ -0,0 +1,94 @@ + + ColorMapping-image + otbcli_ColorMapping + ColorMapping (image) + Image Manipulation + Maps an input label image to 8-bits RGB using look-up tables. + + ParameterRaster + in + Input Image + Input image filename + False + + + OutputRaster + out + Output Image + Output image filename + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + op + Operation + Selection of the operation to execute (default is : label to color). + + + labeltocolor + + + 0 + False + + + ParameterSelection + method + Color mapping method + Selection of color mapping methods and their parameters. + + + image + + + 0 + False + + + ParameterRaster + method.image.in + Support Image + Support image filename. For each label, the LUT is calculated from the mean pixel value in the support image, over the corresponding labeled areas. First of all, the support image is normalized with extrema rejection + False + + + ParameterNumber + method.image.nodatavalue + NoData value + NoData value for each channel of the support image, which will not be handled in the LUT estimation. If NOT checked, ALL the pixel values of the support image will be handled in the LUT estimation. + + + 0 + True + + + ParameterNumber + method.image.low + lower quantile + lower quantile for image normalization + + + 2 + True + + + ParameterNumber + method.image.up + upper quantile + upper quantile for image normalization + + + 2 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-optimal.xml b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-optimal.xml new file mode 100644 index 000000000000..473d2916c1ab --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ColorMapping-optimal.xml @@ -0,0 +1,67 @@ + + ColorMapping-optimal + otbcli_ColorMapping + ColorMapping (optimal) + Image Manipulation + Maps an input label image to 8-bits RGB using look-up tables. + + ParameterRaster + in + Input Image + Input image filename + False + + + OutputRaster + out + Output Image + Output image filename + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + op + Operation + Selection of the operation to execute (default is : label to color). + + + labeltocolor + + + 0 + False + + + ParameterSelection + method + Color mapping method + Selection of color mapping methods and their parameters. + + + optimal + + + 0 + False + + + ParameterNumber + method.optimal.background + Background label + Value of the background label + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/CompareImages.xml b/python/plugins/processing/algs/otb/description/5.4.0/CompareImages.xml new file mode 100644 index 000000000000..1ad8ea4f9ef8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/CompareImages.xml @@ -0,0 +1,81 @@ + + CompareImages + otbcli_CompareImages + Images comparaison + Miscellaneous + Estimator between 2 images. + + ParameterRaster + ref.in + Reference image + Image used as reference in the comparison + False + + + ParameterNumber + ref.channel + Reference image channel + Used channel for the reference image + + + 1 + False + + + ParameterRaster + meas.in + Measured image + Image used as measured in the comparison + False + + + ParameterNumber + meas.channel + Measured image channel + Used channel for the measured image + + + 1 + False + + + ParameterNumber + roi.startx + Start X + ROI start x position. + + + 0 + False + + + ParameterNumber + roi.starty + Start Y + ROI start y position. + + + 0 + False + + + ParameterNumber + roi.sizex + Size X + Size along x in pixels. + + + 0 + False + + + ParameterNumber + roi.sizey + Size Y + Size along y in pixels. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-raster.xml b/python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-raster.xml new file mode 100644 index 000000000000..5bf8a8210eb5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-raster.xml @@ -0,0 +1,60 @@ + + ComputeConfusionMatrix-raster + otbcli_ComputeConfusionMatrix + ComputeConfusionMatrix (raster) + Learning + Computes the confusion matrix of a classification + + ParameterRaster + in + Input Image + The input classification image. + False + + + OutputFile + out + Matrix output + Filename to store the output matrix (csv format) + + + ParameterSelection + ref + Ground truth + Choice of ground truth format + + + raster + + + 0 + False + + + ParameterRaster + ref.raster.in + Input reference image + Input image containing the ground truth labels + False + + + ParameterNumber + nodatalabel + Value for nodata pixels + Label for the NoData class. Such input pixels will be discarded from the ground truth and from the input classification map. By default, 'nodatalabel = 0'. + + + 0 + True + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-vector.xml b/python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-vector.xml new file mode 100644 index 000000000000..991e23b3f835 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ComputeConfusionMatrix-vector.xml @@ -0,0 +1,71 @@ + + ComputeConfusionMatrix-vector + otbcli_ComputeConfusionMatrix + ComputeConfusionMatrix (vector) + Learning + Computes the confusion matrix of a classification + + ParameterRaster + in + Input Image + The input classification image. + False + + + OutputFile + out + Matrix output + Filename to store the output matrix (csv format) + + + ParameterSelection + ref + Ground truth + Choice of ground truth format + + + vector + + + 0 + False + + + ParameterFile + ref.vector.in + Input reference vector data + Input vector data of the ground truth + + False + + + ParameterString + ref.vector.field + Field name + Field name containing the label values + Class + + True + + + + ParameterNumber + nodatalabel + Value for nodata pixels + Label for the NoData class. Such input pixels will be discarded from the ground truth and from the input classification map. By default, 'nodatalabel = 0'. + + + 0 + True + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ComputeImagesStatistics.xml b/python/plugins/processing/algs/otb/description/5.4.0/ComputeImagesStatistics.xml new file mode 100644 index 000000000000..b4430a982ca6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ComputeImagesStatistics.xml @@ -0,0 +1,31 @@ + + ComputeImagesStatistics + otbcli_ComputeImagesStatistics + Compute Images second order statistics + Learning + Computes global mean and standard deviation for each band from a set of images and optionally saves the results in an XML file. + + ParameterMultipleInput + il + Input images + List of input images filenames. + + False + + + ParameterNumber + bv + Background Value + Background value to ignore in statistics computation. + + + 0.0 + True + + + OutputFile + out + Output XML file + XML filename where the statistics are saved for future reuse. + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ComputeOGRLayersFeaturesStatistics.xml b/python/plugins/processing/algs/otb/description/5.4.0/ComputeOGRLayersFeaturesStatistics.xml new file mode 100644 index 000000000000..b7dd4dea07c3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ComputeOGRLayersFeaturesStatistics.xml @@ -0,0 +1,30 @@ + + ComputeOGRLayersFeaturesStatistics + otbcli_ComputeOGRLayersFeaturesStatistics + ComputeOGRLayersFeaturesStatistics + Segmentation + Compute statistics of the features in a set of OGR Layers + + ParameterVector + inshp + Name of the input shapefile + Name of the input shapefile + + False + + + OutputFile + outstats + XML file containing mean and variance of each feature. + XML file containing mean and variance of each feature. + + + ParameterString + feat + List of features to consider for statistics. + List of features to consider for statistics. + + + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ComputePolylineFeatureFromImage.xml b/python/plugins/processing/algs/otb/description/5.4.0/ComputePolylineFeatureFromImage.xml new file mode 100644 index 000000000000..2841a27ed1d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ComputePolylineFeatureFromImage.xml @@ -0,0 +1,60 @@ + + ComputePolylineFeatureFromImage + otbcli_ComputePolylineFeatureFromImage + Compute Polyline Feature From Image + Feature Extraction + This application compute for each studied polyline, contained in the input VectorData, the chosen descriptors. + + ParameterRaster + in + Input Image + An image to compute the descriptors on. + False + + + ParameterVector + vd + Vector Data + Vector data containing the polylines where the features will be computed. + + False + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterString + expr + Feature expression + The feature formula (b1 < 0.3) where b1 is the standard name of input image first band + + + False + + + + ParameterString + field + Feature name + The field name corresponding to the feature codename (NONDVI, ROADSA...) + + + False + + + + OutputVector + out + Output Vector Data + The output vector data containing polylines with a new field + + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ConcatenateImages.xml b/python/plugins/processing/algs/otb/description/5.4.0/ConcatenateImages.xml new file mode 100644 index 000000000000..4f7c9f4aa70f --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ConcatenateImages.xml @@ -0,0 +1,32 @@ + + ConcatenateImages + otbcli_ConcatenateImages + Images Concatenation + Image Manipulation + Concatenate a list of images of the same size into a single multi-channel one. + + ParameterMultipleInput + il + Input images list + The list of images to concatenate + + False + + + OutputRaster + out + Output Image + The concatenated output image + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ConcatenateVectorData.xml b/python/plugins/processing/algs/otb/description/5.4.0/ConcatenateVectorData.xml new file mode 100644 index 000000000000..6aa638a7ccf3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ConcatenateVectorData.xml @@ -0,0 +1,23 @@ + + ConcatenateVectorData + otbcli_ConcatenateVectorData + Concatenate + Vector Data Manipulation + Concatenate VectorDatas + + ParameterMultipleInput + vd + Input VectorDatas to concatenate + VectorData files to be concatenated in an unique VectorData + + False + + + OutputVector + out + Concatenated VectorData + Output conctenated VectorData + + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ConnectedComponentSegmentation.xml b/python/plugins/processing/algs/otb/description/5.4.0/ConnectedComponentSegmentation.xml new file mode 100644 index 000000000000..33b63d060d6a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ConnectedComponentSegmentation.xml @@ -0,0 +1,72 @@ + + ConnectedComponentSegmentation + otbcli_ConnectedComponentSegmentation + Connected Component Segmentation + Segmentation + Connected component segmentation and object based image filtering of the input image according to user-defined criterions. + + ParameterRaster + in + Input Image + The image to segment. + False + + + OutputVector + out + Output Shape + The segmentation shape. + + + + + ParameterString + mask + Mask expression + Mask mathematical expression (only if support image is given) + + + True + + + + ParameterString + expr + Connected Component Expression + Formula used for connected component segmentation + + + False + + + + ParameterNumber + minsize + Minimum Object Size + Min object size (area in pixel) + + + 2 + True + + + ParameterString + obia + OBIA Expression + OBIA mathematical expression + + + True + + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Convert.xml b/python/plugins/processing/algs/otb/description/5.4.0/Convert.xml new file mode 100644 index 000000000000..b5e626721b40 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Convert.xml @@ -0,0 +1,83 @@ + + Convert + otbcli_Convert + Image Conversion + Image Manipulation + Convert an image to a different format, eventually rescaling the data and/or changing the pixel type. + + ParameterRaster + in + Input image + Input image + False + + + ParameterSelection + type + Rescale type + Transfer function for the rescaling + + + none + linear + log2 + + + 0 + False + + + ParameterNumber + type.linear.gamma + Gamma correction factor + Gamma correction factor + + + 1 + True + + + ParameterRaster + mask + Input mask + The masked pixels won't be used to adapt the dynamic (the mask must have the same dimensions as the input image) + True + + + ParameterNumber + hcp.high + High Cut Quantile + Quantiles to cut from histogram high values before computing min/max rescaling (in percent, 2 by default) + + + 2 + True + + + ParameterNumber + hcp.low + Low Cut Quantile + Quantiles to cut from histogram low values before computing min/max rescaling (in percent, 2 by default) + + + 2 + True + + + OutputRaster + out + Output Image + Output image + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/DEMConvert.xml b/python/plugins/processing/algs/otb/description/5.4.0/DEMConvert.xml new file mode 100644 index 000000000000..8e017ebe1336 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/DEMConvert.xml @@ -0,0 +1,20 @@ + + DEMConvert + otbcli_DEMConvert + DEM Conversion + Image Manipulation + Converts a geo-referenced DEM image into a general raster file compatible with OTB DEM handling. + + ParameterRaster + in + Input geo-referenced DEM + Input geo-referenced DEM to convert to general raster format. + False + + + OutputFile + out + Prefix of the output files + will be used to get the prefix (name withtout extensions) of the files to write. Three files - prefix.geom, prefix.omd and prefix.ras - will be generated. + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-frost.xml b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-frost.xml new file mode 100644 index 000000000000..e7e3d54aebcf --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-frost.xml @@ -0,0 +1,64 @@ + + Despeckle-frost + otbcli_Despeckle + Despeckle (frost) + Image Filtering + Perform speckle noise reduction on SAR image. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + speckle filtering method + + + + frost + + + 0 + False + + + ParameterNumber + filter.frost.rad + Radius + Radius for frost filter + + + 1 + False + + + ParameterNumber + filter.frost.deramp + deramp + Decrease factor declaration + + + 0.1 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-gammamap.xml b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-gammamap.xml new file mode 100644 index 000000000000..25609700b661 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-gammamap.xml @@ -0,0 +1,64 @@ + + Despeckle-gammamap + otbcli_Despeckle + Despeckle (gammamap) + Image Filtering + Perform speckle noise reduction on SAR image. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + speckle filtering method + + + + gammamap + + + 0 + False + + + ParameterNumber + filter.gammamap.rad + Radius + Radius for GammaMAP filter + + + 1 + False + + + ParameterNumber + filter.gammamap.nblooks + nb looks + Nb looks for GammaMAP filter + + + 1 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-kuan.xml b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-kuan.xml new file mode 100644 index 000000000000..ac47ace38d3b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-kuan.xml @@ -0,0 +1,64 @@ + + Despeckle-kuan + otbcli_Despeckle + Despeckle (kuan) + Image Filtering + Perform speckle noise reduction on SAR image. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + speckle filtering method + + + + kuan + + + 0 + False + + + ParameterNumber + filter.kuan.rad + Radius + Radius for Kuan filter + + + 0 + False + + + ParameterNumber + filter.kuan.nblooks + nb looks + Nb looks for Kuan filter + + + 0.0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-lee.xml b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-lee.xml new file mode 100644 index 000000000000..99dad8b3254c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Despeckle-lee.xml @@ -0,0 +1,64 @@ + + Despeckle-lee + otbcli_Despeckle + Despeckle (lee) + Image Filtering + Perform speckle noise reduction on SAR image. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + speckle filtering method + + + + lee + + + 0 + False + + + ParameterNumber + filter.lee.rad + Radius + Radius for lee filter + + + 1 + False + + + ParameterNumber + filter.lee.nblooks + nb looks + Nb looks for lee filter + + + 1 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-ica.xml b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-ica.xml new file mode 100644 index 000000000000..6b4fbdfd3953 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-ica.xml @@ -0,0 +1,85 @@ + + DimensionalityReduction-ica + otbcli_DimensionalityReduction + DimensionalityReduction (ica) + Image Filtering + Perform Dimension reduction of the input image. + + ParameterRaster + in + Input Image + The input image to apply dimensionality reduction. + False + + + OutputRaster + out + Output Image + output image. Components are ordered by decreasing eigenvalues. + + + + OutputRaster + outinv + Inverse Output Image + reconstruct output image. + + + + ParameterSelection + method + Algorithm + Selection of the reduction dimension method. + + + ica + + + 0 + False + + + ParameterNumber + method.ica.iter + number of iterations + + + + 20 + True + + + ParameterNumber + method.ica.mu + Give the increment weight of W in [0, 1] + + + + 1 + True + + + ParameterNumber + nbcomp + Number of Components. + Number of relevant components kept. By default all components are kept. + + + 0 + True + + + ParameterBoolean + normalize + Normalize. + center AND reduce data before Dimensionality reduction. + True + True + + + OutputFile + outmatrix + Transformation matrix output (text format) + Filename to store the transformation matrix (csv format) + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-maf.xml b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-maf.xml new file mode 100644 index 000000000000..78b403bab5d4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-maf.xml @@ -0,0 +1,58 @@ + + DimensionalityReduction-maf + otbcli_DimensionalityReduction + DimensionalityReduction (maf) + Image Filtering + Perform Dimension reduction of the input image. + + ParameterRaster + in + Input Image + The input image to apply dimensionality reduction. + False + + + OutputRaster + out + Output Image + output image. Components are ordered by decreasing eigenvalues. + + + + ParameterSelection + method + Algorithm + Selection of the reduction dimension method. + + + maf + + + 0 + False + + + ParameterNumber + nbcomp + Number of Components. + Number of relevant components kept. By default all components are kept. + + + 0 + True + + + ParameterBoolean + normalize + Normalize. + center AND reduce data before Dimensionality reduction. + True + True + + + OutputFile + outmatrix + Transformation matrix output (text format) + Filename to store the transformation matrix (csv format) + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-napca.xml b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-napca.xml new file mode 100644 index 000000000000..6917a53ab9c4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-napca.xml @@ -0,0 +1,85 @@ + + DimensionalityReduction-napca + otbcli_DimensionalityReduction + DimensionalityReduction (napca) + Image Filtering + Perform Dimension reduction of the input image. + + ParameterRaster + in + Input Image + The input image to apply dimensionality reduction. + False + + + OutputRaster + out + Output Image + output image. Components are ordered by decreasing eigenvalues. + + + + OutputRaster + outinv + Inverse Output Image + reconstruct output image. + + + + ParameterSelection + method + Algorithm + Selection of the reduction dimension method. + + + napca + + + 0 + False + + + ParameterNumber + method.napca.radiusx + Set the x radius of the sliding window. + + + + 1 + False + + + ParameterNumber + method.napca.radiusy + Set the y radius of the sliding window. + + + + 1 + False + + + ParameterNumber + nbcomp + Number of Components. + Number of relevant components kept. By default all components are kept. + + + 0 + True + + + ParameterBoolean + normalize + Normalize. + center AND reduce data before Dimensionality reduction. + True + True + + + OutputFile + outmatrix + Transformation matrix output (text format) + Filename to store the transformation matrix (csv format) + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-pca.xml b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-pca.xml new file mode 100644 index 000000000000..c1c5439b39ca --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/DimensionalityReduction-pca.xml @@ -0,0 +1,65 @@ + + DimensionalityReduction-pca + otbcli_DimensionalityReduction + DimensionalityReduction (pca) + Image Filtering + Perform Dimension reduction of the input image. + + ParameterRaster + in + Input Image + The input image to apply dimensionality reduction. + False + + + OutputRaster + out + Output Image + output image. Components are ordered by decreasing eigenvalues. + + + + OutputRaster + outinv + Inverse Output Image + reconstruct output image. + + + + ParameterSelection + method + Algorithm + Selection of the reduction dimension method. + + + pca + + + 0 + False + + + ParameterNumber + nbcomp + Number of Components. + Number of relevant components kept. By default all components are kept. + + + 0 + True + + + ParameterBoolean + normalize + Normalize. + center AND reduce data before Dimensionality reduction. + True + True + + + OutputFile + outmatrix + Transformation matrix output (text format) + Filename to store the transformation matrix (csv format) + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-gradient.xml b/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-gradient.xml new file mode 100644 index 000000000000..6bf5b003761a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-gradient.xml @@ -0,0 +1,54 @@ + + EdgeExtraction-gradient + otbcli_EdgeExtraction + EdgeExtraction (gradient) + Feature Extraction + Computes edge features on every pixel of the input image selected channel + + ParameterRaster + in + Input Image + The input image to compute the features on. + False + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + Edge feature + Choice of edge feature + + + gradient + + + 0 + False + + + OutputRaster + out + Feature Output Image + Output image containing the edge features. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-sobel.xml b/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-sobel.xml new file mode 100644 index 000000000000..e322268eb1fa --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-sobel.xml @@ -0,0 +1,54 @@ + + EdgeExtraction-sobel + otbcli_EdgeExtraction + EdgeExtraction (sobel) + Feature Extraction + Computes edge features on every pixel of the input image selected channel + + ParameterRaster + in + Input Image + The input image to compute the features on. + False + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + Edge feature + Choice of edge feature + + + sobel + + + 0 + False + + + OutputRaster + out + Feature Output Image + Output image containing the edge features. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-touzi.xml b/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-touzi.xml new file mode 100644 index 000000000000..ea043b256958 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/EdgeExtraction-touzi.xml @@ -0,0 +1,64 @@ + + EdgeExtraction-touzi + otbcli_EdgeExtraction + EdgeExtraction (touzi) + Feature Extraction + Computes edge features on every pixel of the input image selected channel + + ParameterRaster + in + Input Image + The input image to compute the features on. + False + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + filter + Edge feature + Choice of edge feature + + + touzi + + + 0 + False + + + ParameterNumber + filter.touzi.xradius + The Radius + The Radius + + + 1 + False + + + OutputRaster + out + Feature Output Image + Output image containing the edge features. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-fit.xml b/python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-fit.xml new file mode 100644 index 000000000000..973c0a19da11 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-fit.xml @@ -0,0 +1,61 @@ + + ExtractROI-fit + otbcli_ExtractROI + ExtractROI (fit) + Image Manipulation + Extract a ROI defined by the user. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + mode + Extraction mode + + + + fit + + + 0 + False + + + ParameterRaster + mode.fit.ref + Reference image + Reference image to define the ROI + False + + + ParameterNumber + mode.fit.elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-standard.xml b/python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-standard.xml new file mode 100644 index 000000000000..e898dbf6b6cc --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ExtractROI-standard.xml @@ -0,0 +1,84 @@ + + ExtractROI-standard + otbcli_ExtractROI + ExtractROI (standard) + Image Manipulation + Extract a ROI defined by the user. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputRaster + out + Output Image + Output image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + mode + Extraction mode + + + + standard + + + 0 + False + + + ParameterNumber + startx + Start X + ROI start x position. + + + 0 + False + + + ParameterNumber + starty + Start Y + ROI start y position. + + + 0 + False + + + ParameterNumber + sizex + Size X + size along x in pixels. + + + 0 + False + + + ParameterNumber + sizey + Size Y + size along y in pixels. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-dempstershafer.xml b/python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-dempstershafer.xml new file mode 100644 index 000000000000..96d4a0cbe02c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-dempstershafer.xml @@ -0,0 +1,79 @@ + + FusionOfClassifications-dempstershafer + otbcli_FusionOfClassifications + FusionOfClassifications (dempstershafer) + Learning + Fuses several classifications maps of the same image on the basis of class labels. + + ParameterMultipleInput + il + Input classifications + List of input classification maps to fuse. Labels in each classification image must represent the same class. + + False + + + ParameterSelection + method + Fusion method + Selection of the fusion method and its parameters. + + + dempstershafer + + + 0 + False + + + ParameterMultipleInput + method.dempstershafer.cmfl + Confusion Matrices + A list of confusion matrix files (*.CSV format) to define the masses of belief and the class labels. Each file should be formatted the following way: the first line, beginning with a '#' symbol, should be a list of the class labels present in the corresponding input classification image, organized in the same order as the confusion matrix rows/columns. + + False + + + ParameterSelection + method.dempstershafer.mob + Mass of belief measurement + Type of confusion matrix measurement used to compute the masses of belief of each classifier. + + + precision + recall + accuracy + kappa + + + 0 + False + + + ParameterNumber + nodatalabel + Label for the NoData class + Label for the NoData class. Such input pixels keep their NoData label in the output image and are not handled in the fusion process. By default, 'nodatalabel = 0'. + + + 0 + False + + + ParameterNumber + undecidedlabel + Label for the Undecided class + Label for the Undecided class. Pixels with more than 1 fused class are marked as Undecided. Please note that the Undecided value must be different from existing labels in the input classifications. By default, 'undecidedlabel = 0'. + + + 0 + False + + + OutputRaster + out + The output classification image + The output classification image resulting from the fusion of the input classification images. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-majorityvoting.xml b/python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-majorityvoting.xml new file mode 100644 index 000000000000..abd3f7cb1289 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/FusionOfClassifications-majorityvoting.xml @@ -0,0 +1,55 @@ + + FusionOfClassifications-majorityvoting + otbcli_FusionOfClassifications + FusionOfClassifications (majorityvoting) + Learning + Fuses several classifications maps of the same image on the basis of class labels. + + ParameterMultipleInput + il + Input classifications + List of input classification maps to fuse. Labels in each classification image must represent the same class. + + False + + + ParameterSelection + method + Fusion method + Selection of the fusion method and its parameters. + + + majorityvoting + + + 0 + False + + + ParameterNumber + nodatalabel + Label for the NoData class + Label for the NoData class. Such input pixels keep their NoData label in the output image and are not handled in the fusion process. By default, 'nodatalabel = 0'. + + + 0 + False + + + ParameterNumber + undecidedlabel + Label for the Undecided class + Label for the Undecided class. Pixels with more than 1 fused class are marked as Undecided. Please note that the Undecided value must be different from existing labels in the input classifications. By default, 'undecidedlabel = 0'. + + + 0 + False + + + OutputRaster + out + The output classification image + The output classification image resulting from the fusion of the input classification images. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-closing.xml b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-closing.xml new file mode 100644 index 000000000000..5d5e5f146bc8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-closing.xml @@ -0,0 +1,77 @@ + + GrayScaleMorphologicalOperation-closing + otbcli_GrayScaleMorphologicalOperation + GrayScaleMorphologicalOperation (closing) + Feature Extraction + Performs morphological operations on a grayscale input image + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + closing + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-dilate.xml b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-dilate.xml new file mode 100644 index 000000000000..7302c31336de --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-dilate.xml @@ -0,0 +1,77 @@ + + GrayScaleMorphologicalOperation-dilate + otbcli_GrayScaleMorphologicalOperation + GrayScaleMorphologicalOperation (dilate) + Feature Extraction + Performs morphological operations on a grayscale input image + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + dilate + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-erode.xml b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-erode.xml new file mode 100644 index 000000000000..7da86e36fea2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-erode.xml @@ -0,0 +1,77 @@ + + GrayScaleMorphologicalOperation-erode + otbcli_GrayScaleMorphologicalOperation + GrayScaleMorphologicalOperation (erode) + Feature Extraction + Performs morphological operations on a grayscale input image + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + erode + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-opening.xml b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-opening.xml new file mode 100644 index 000000000000..e9781f67cab4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/GrayScaleMorphologicalOperation-opening.xml @@ -0,0 +1,77 @@ + + GrayScaleMorphologicalOperation-opening + otbcli_GrayScaleMorphologicalOperation + GrayScaleMorphologicalOperation (opening) + Feature Extraction + Performs morphological operations on a grayscale input image + + ParameterRaster + in + Input Image + The input image to be filtered. + False + + + OutputRaster + out + Feature Output Image + Output image containing the filtered output image. + + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + structype + Structuring Element Type + Choice of the structuring element type + + + ball + + + 0 + False + + + ParameterNumber + structype.ball.xradius + The Structuring Element Radius + The Structuring Element Radius + + + 5 + False + + + ParameterSelection + filter + Morphological Operation + Choice of the morphological operation + + + opening + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/HaralickTextureExtraction.xml b/python/plugins/processing/algs/otb/description/5.4.0/HaralickTextureExtraction.xml new file mode 100644 index 000000000000..12a02eeacf11 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/HaralickTextureExtraction.xml @@ -0,0 +1,126 @@ + + HaralickTextureExtraction + otbcli_HaralickTextureExtraction + Haralick Texture Extraction + Feature Extraction + Computes textures on every pixel of the input image selected channel + + ParameterRaster + in + Input Image + The input image to compute the features on. + False + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + parameters.xrad + X Radius + X Radius + + + 2 + False + + + ParameterNumber + parameters.yrad + Y Radius + Y Radius + + + 2 + False + + + ParameterNumber + parameters.xoff + X Offset + X Offset + + + 1 + False + + + ParameterNumber + parameters.yoff + Y Offset + Y Offset + + + 1 + False + + + ParameterNumber + parameters.min + Image Minimum + Image Minimum + + + 0 + False + + + ParameterNumber + parameters.max + Image Maximum + Image Maximum + + + 255 + False + + + ParameterNumber + parameters.nbbin + Histogram number of bin + Histogram number of bin + + + 8 + False + + + ParameterSelection + texture + Texture Set Selection + Choice of The Texture Set + + + simple + advanced + higher + + + 0 + False + + + OutputRaster + out + Output Image + Output image containing the selected texture features. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/HooverCompareSegmentation.xml b/python/plugins/processing/algs/otb/description/5.4.0/HooverCompareSegmentation.xml new file mode 100644 index 000000000000..2646745b3f7e --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/HooverCompareSegmentation.xml @@ -0,0 +1,95 @@ + + HooverCompareSegmentation + otbcli_HooverCompareSegmentation + Hoover compare segmentation + Segmentation + Compare two segmentations with Hoover metrics + + ParameterRaster + ingt + Input ground truth + A partial ground truth segmentation image. + False + + + ParameterRaster + inms + Input machine segmentation + A machine segmentation image. + False + + + ParameterNumber + bg + Background label + Label value of the background in the input segmentations + + + 0 + False + + + ParameterNumber + th + Overlapping threshold + Overlapping threshold used to find Hoover instances. + + + 0.75 + False + + + OutputRaster + outgt + Colored ground truth output + The colored ground truth output image. + + + + OutputRaster + outms + Colored machine segmentation output + The colored machine segmentation output image. + + + + ParameterNumber + rc + Correct detection score + Overall score for correct detection (RC) + + + 0.0 + False + + + ParameterNumber + rf + Over-segmentation score + Overall score for over segmentation (RF) + + + 0.0 + False + + + ParameterNumber + ra + Under-segmentation score + Overall score for under segmentation (RA) + + + 0.0 + False + + + ParameterNumber + rm + Missed detection score + Overall score for missed detection (RM) + + + 0.0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ImageClassifier.xml b/python/plugins/processing/algs/otb/description/5.4.0/ImageClassifier.xml new file mode 100644 index 000000000000..555b0eca3e43 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ImageClassifier.xml @@ -0,0 +1,72 @@ + + ImageClassifier + otbcli_ImageClassifier + Image Classification + Learning + Performs a classification of the input image according to a model file. + + ParameterRaster + in + Input Image + The input image to classify. + False + + + ParameterRaster + mask + Input Mask + The mask allows restricting classification of the input image to the area where mask pixel values are greater than 0. + True + + + ParameterFile + model + Model file + A model file (produced by TrainImagesClassifier application, maximal class label = 65535). + + False + + + ParameterFile + imstat + Statistics file + A XML file containing mean and standard deviation to center and reduce samples before classification (produced by ComputeImagesStatistics application). + + True + + + OutputRaster + out + Output Image + Output image containing class labels + + + + OutputRaster + confmap + Confidence map + Confidence map of the produced classification. The confidence index depends on the model : + - LibSVM : difference between the two highest probabilities (needs a model with probability estimates, so that classes probabilities can be computed for each sample) + - OpenCV + * Boost : sum of votes + * DecisionTree : (not supported) + * GradientBoostedTree : (not supported) + * KNearestNeighbors : number of neighbors with the same label + * NeuralNetwork : difference between the two highest responses + * NormalBayes : (not supported) + * RandomForest : Confidence (proportion of votes for the majority class). Margin (normalized difference of the votes of the 2 majority classes) is not available for now. + * SVM : distance to margin (only works for 2-class models) + + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ImageEnvelope.xml b/python/plugins/processing/algs/otb/description/5.4.0/ImageEnvelope.xml new file mode 100644 index 000000000000..937f73bbe933 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ImageEnvelope.xml @@ -0,0 +1,42 @@ + + ImageEnvelope + otbcli_ImageEnvelope + Image Envelope + Geometry + Extracts an image envelope. + + ParameterRaster + in + Input Image + Input image. + False + + + OutputVector + out + Output Vector Data + Vector data file containing the envelope + + + + + ParameterNumber + sr + Sampling Rate + Sampling rate for image edges (in pixel) + + + 0 + True + + + ParameterString + proj + Projection + Projection to be used to compute the envelope (default is WGS84) + + + True + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/KMeansClassification.xml b/python/plugins/processing/algs/otb/description/5.4.0/KMeansClassification.xml new file mode 100644 index 000000000000..9cac46c41172 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/KMeansClassification.xml @@ -0,0 +1,84 @@ + + KMeansClassification + otbcli_KMeansClassification + Unsupervised KMeans image classification + Learning + Unsupervised KMeans image classification + + ParameterRaster + in + Input Image + Input image to classify. + False + + + OutputRaster + out + Output Image + Output image containing the class indexes. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterRaster + vm + Validity Mask + Validity mask. Only non-zero pixels will be used to estimate KMeans modes. + True + + + ParameterNumber + ts + Training set size + Size of the training set (in pixels). + + + 100 + True + + + ParameterNumber + nc + Number of classes + Number of modes, which will be used to generate class membership. + + + 5 + False + + + ParameterNumber + maxit + Maximum number of iterations + Maximum number of iterations for the learning step. + + + 1000 + True + + + ParameterNumber + ct + Convergence threshold + Convergence threshold for class centroid (L2 distance, by default 0.0001). + + + 0.0001 + True + + + OutputFile + outmeans + Centroid filename + Output text file containing centroid positions + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/KmzExport.xml b/python/plugins/processing/algs/otb/description/5.4.0/KmzExport.xml new file mode 100644 index 000000000000..57469ba47a5c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/KmzExport.xml @@ -0,0 +1,54 @@ + + KmzExport + otbcli_KmzExport + Image to KMZ Export + Miscellaneous + Export the input image in a KMZ product. + + ParameterRaster + in + Input image + Input image + False + + + OutputFile + out + Output .kmz product + Output Kmz product directory (with .kmz extension) + + + ParameterNumber + tilesize + Tile Size + Size of the tiles in the kmz product, in number of pixels (default = 512). + + + 512 + True + + + ParameterRaster + logo + Image logo + Path to the image logo to add to the KMZ product. + True + + + ParameterRaster + legend + Image legend + Path to the image legend to add to the KMZ product. + True + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/LSMSSegmentation.xml b/python/plugins/processing/algs/otb/description/5.4.0/LSMSSegmentation.xml new file mode 100644 index 000000000000..2eef025b37a0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/LSMSSegmentation.xml @@ -0,0 +1,94 @@ + + LSMSSegmentation + otbcli_LSMSSegmentation + Exact Large-Scale Mean-Shift segmentation, step 2 + Segmentation + Second step of the exact Large-Scale Mean-Shift segmentation workflow. + + ParameterRaster + in + Filtered image + The filtered image (cf. Adaptive MeanShift Smoothing application). + False + + + ParameterRaster + inpos + Spatial image + The spatial image. Spatial input is the displacement map (output of the Adaptive MeanShift Smoothing application). + True + + + OutputRaster + out + Output Image + The output image. The output image is the segmentation of the filtered image. It is recommended to set the pixel type to uint32. + + + + ParameterNumber + ranger + Range radius + Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space. + + + 15 + True + + + ParameterNumber + spatialr + Spatial radius + Spatial radius of the neighborhood. + + + 5 + True + + + ParameterNumber + minsize + Minimum Region Size + Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is deleted. + + + 0 + True + + + ParameterNumber + tilesizex + Size of tiles in pixel (X-axis) + Size of tiles along the X-axis. + + + 500 + False + + + ParameterNumber + tilesizey + Size of tiles in pixel (Y-axis) + Size of tiles along the Y-axis. + + + 500 + False + + + ParameterFile + tmpdir + Directory where to write temporary files + This applications need to write temporary files for each tile. This parameter allows choosing the path where to write those files. If disabled, the current path will be used. + + True + + + ParameterBoolean + cleanup + Temporary files cleaning + If activated, the application will try to clean all temporary files it created + True + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/LSMSSmallRegionsMerging.xml b/python/plugins/processing/algs/otb/description/5.4.0/LSMSSmallRegionsMerging.xml new file mode 100644 index 000000000000..c3ccd89c0e4a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/LSMSSmallRegionsMerging.xml @@ -0,0 +1,58 @@ + + LSMSSmallRegionsMerging + otbcli_LSMSSmallRegionsMerging + Exact Large-Scale Mean-Shift segmentation, step 3 (optional) + Segmentation + Third (optional) step of the exact Large-Scale Mean-Shift segmentation workflow. + + ParameterRaster + in + Input image + The input image. + False + + + ParameterRaster + inseg + Segmented image + The segmented image input. Segmented image input is the segmentation of the input image. + False + + + OutputRaster + out + Output Image + The output image. The output image is the input image where the minimal regions have been merged. + + + + ParameterNumber + minsize + Minimum Region Size + Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is merged with the "nearest" region (radiometrically). + + + 50 + True + + + ParameterNumber + tilesizex + Size of tiles in pixel (X-axis) + Size of tiles along the X-axis. + + + 500 + False + + + ParameterNumber + tilesizey + Size of tiles in pixel (Y-axis) + Size of tiles along the Y-axis. + + + 500 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/LSMSVectorization.xml b/python/plugins/processing/algs/otb/description/5.4.0/LSMSVectorization.xml new file mode 100644 index 000000000000..8987a219f834 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/LSMSVectorization.xml @@ -0,0 +1,47 @@ + + LSMSVectorization + otbcli_LSMSVectorization + Exact Large-Scale Mean-Shift segmentation, step 4 + Segmentation + Fourth step of the exact Large-Scale Mean-Shift segmentation workflow. + + ParameterRaster + in + Input Image + The input image. + False + + + ParameterRaster + inseg + Segmented image + The segmented image input. Segmented image input is the segmentation of the input image. + False + + + OutputVector + out + Output GIS vector file + The output GIS vector file, representing the vectorized version of the segmented image where the features of the polygons are the radiometric means and variances. + + + ParameterNumber + tilesizex + Size of tiles in pixel (X-axis) + Size of tiles along the X-axis. + + + 500 + False + + + ParameterNumber + tilesizey + Size of tiles in pixel (Y-axis) + Size of tiles along the Y-axis. + + + 500 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/LineSegmentDetection.xml b/python/plugins/processing/algs/otb/description/5.4.0/LineSegmentDetection.xml new file mode 100644 index 000000000000..850f4f8a0a9f --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/LineSegmentDetection.xml @@ -0,0 +1,30 @@ + + LineSegmentDetection + otbcli_LineSegmentDetection + Line segment detection + Feature Extraction + Detect line segments in raster + + ParameterRaster + in + Input Image + Input image on which lines will be detected. + False + + + OutputVector + out + Output Detected lines + Output detected line segments (vector data). + + + + + ParameterBoolean + norescale + No rescaling in [0, 255] + By default, the input image amplitude is rescaled between [0,255]. Turn on this parameter to skip rescaling + True + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/LocalStatisticExtraction.xml b/python/plugins/processing/algs/otb/description/5.4.0/LocalStatisticExtraction.xml new file mode 100644 index 000000000000..663bd63bd3e9 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/LocalStatisticExtraction.xml @@ -0,0 +1,51 @@ + + LocalStatisticExtraction + otbcli_LocalStatisticExtraction + Local Statistic Extraction + Feature Extraction + Computes local statistical moments on every pixel in the selected channel of the input image + + ParameterRaster + in + Input Image + The input image to compute the features on. + False + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + radius + Neighborhood radius + The computational window radius. + + + 3 + False + + + OutputRaster + out + Feature Output Image + Output image containing the local statistical moments. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/MeanShiftSmoothing.xml b/python/plugins/processing/algs/otb/description/5.4.0/MeanShiftSmoothing.xml new file mode 100644 index 000000000000..22fb7dd68bf4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/MeanShiftSmoothing.xml @@ -0,0 +1,96 @@ + + MeanShiftSmoothing + otbcli_MeanShiftSmoothing + Exact Large-Scale Mean-Shift segmentation, step 1 (smoothing) + Image Filtering + Perform mean shift filtering + + ParameterRaster + in + Input Image + The input image. + False + + + OutputRaster + fout + Filtered output + The filtered output image. + + + + OutputRaster + foutpos + Spatial image + The spatial image output. Spatial image output is a displacement map (pixel position after convergence). + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + spatialr + Spatial radius + Spatial radius of the neighborhood. + + + 5 + True + + + ParameterNumber + ranger + Range radius + Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space. + + + 15 + True + + + ParameterNumber + thres + Mode convergence threshold + Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations. + + + 0.1 + True + + + ParameterNumber + maxiter + Maximum number of iterations + Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations. + + + 100 + True + + + ParameterNumber + rangeramp + Range radius coefficient + This coefficient makes dependent the ranger of the colorimetry of the filtered pixel : y = rangeramp*x+ranger. + + + 0 + True + + + ParameterBoolean + modesearch + Mode search. + If activated pixel iterative convergence is stopped if the path . Be careful, with this option, the result will slightly depend on thread number + True + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/MultivariateAlterationDetector.xml b/python/plugins/processing/algs/otb/description/5.4.0/MultivariateAlterationDetector.xml new file mode 100644 index 000000000000..3fa140a5e78d --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/MultivariateAlterationDetector.xml @@ -0,0 +1,38 @@ + + MultivariateAlterationDetector + otbcli_MultivariateAlterationDetector + Multivariate alteration detector + Feature Extraction + Multivariate Alteration Detector + + ParameterRaster + in1 + Input Image 1 + Image which describe initial state of the scene. + False + + + ParameterRaster + in2 + Input Image 2 + Image which describe scene after perturbations. + False + + + OutputRaster + out + Change Map + Image of detected changes. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/OGRLayerClassifier.xml b/python/plugins/processing/algs/otb/description/5.4.0/OGRLayerClassifier.xml new file mode 100644 index 000000000000..9e199b2d6060 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/OGRLayerClassifier.xml @@ -0,0 +1,48 @@ + + OGRLayerClassifier + otbcli_OGRLayerClassifier + OGRLayerClassifier + Segmentation + Classify an OGR layer based on a machine learning model and a list of features to consider. + + ParameterVector + inshp + Name of the input shapefile + Name of the input shapefile + + False + + + ParameterFile + instats + XML file containing mean and variance of each feature. + XML file containing mean and variance of each feature. + + False + + + OutputFile + insvm + Input model filename. + Input model filename. + + + ParameterString + feat + Features + Features to be calculated + + + False + + + ParameterString + cfield + Field containing the predicted class. + Field containing the predicted class + predicted + + False + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-epsg.xml b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-epsg.xml new file mode 100644 index 000000000000..1ca3123425f6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-epsg.xml @@ -0,0 +1,124 @@ + + OrthoRectification-epsg + otbcli_OrthoRectification + OrthoRectification (epsg) + Geometry + This application allows ortho-rectification of optical images from supported sensors. + + + ParameterRaster + io.in + Input Image + The input image to ortho-rectify + False + + + OutputRaster + io.out + Output Image + The ortho-rectified output image + + + + ParameterSelection + map + Output Cartographic Map Projection + Parameters of the output map projection to be used. + + + epsg + + + 0 + False + + + ParameterNumber + map.epsg.code + EPSG Code + See www.spatialreference.org to find which EPSG code is associated to your projection + + + 4326 + False + + + ParameterSelection + outputs.mode + Parameters estimation modes + + + + autosize + autospacing + + + 0 + False + + + ParameterNumber + outputs.default + Default pixel value + Default value to write when outside of input image. + + + 0 + True + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + bco + nn + linear + + + 0 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + opt.ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + + ParameterNumber + opt.gridspacing + Resampling grid spacing + Resampling is done according to a coordinate mapping deformation grid, whose pixel size is set by this parameter, and expressed in the coordinate system of the output image The closer to the output spacing this parameter is, the more precise will be the ortho-rectified image,but increasing this parameter will reduce processing time. + + + 4 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-fit-to-ortho.xml b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-fit-to-ortho.xml new file mode 100644 index 000000000000..5d7ce55ef3c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-fit-to-ortho.xml @@ -0,0 +1,107 @@ + + OrthoRectification-fit-to-ortho + otbcli_OrthoRectification + OrthoRectification (fit-to-ortho) + Geometry + This application allows ortho-rectification of optical images from supported sensors. + + + ParameterRaster + io.in + Input Image + The input image to ortho-rectify + False + + + OutputRaster + io.out + Output Image + The ortho-rectified output image + + + + ParameterSelection + outputs.mode + Parameters estimation modes + + + + orthofit + + + 0 + False + + + ParameterRaster + outputs.ortho + Model ortho-image + A model ortho-image that can be used to compute size, origin and spacing of the output + True + + + ParameterNumber + outputs.default + Default pixel value + Default value to write when outside of input image. + + + 0 + True + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + bco + nn + linear + + + 0 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + opt.ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + + ParameterNumber + opt.gridspacing + Resampling grid spacing + Resampling is done according to a coordinate mapping deformation grid, whose pixel size is set by this parameter, and expressed in the coordinate system of the output image The closer to the output spacing this parameter is, the more precise will be the ortho-rectified image,but increasing this parameter will reduce processing time. + + + 4 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-lambert-WGS84.xml b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-lambert-WGS84.xml new file mode 100644 index 000000000000..30f0bd09a7c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-lambert-WGS84.xml @@ -0,0 +1,116 @@ + + OrthoRectification-lambert-WGS84 + otbcli_OrthoRectification + OrthoRectification (lambert-WGS84) + Geometry + This application allows ortho-rectification of optical images from supported sensors. + + + ParameterRaster + io.in + Input Image + The input image to ortho-rectify + False + + + OutputRaster + io.out + Output Image + The ortho-rectified output image + + + + ParameterSelection + map + Output Cartographic Map Projection + Parameters of the output map projection to be used. + + + lambert2 + lambert93 + wgs + + + 0 + False + + + ParameterSelection + outputs.mode + Parameters estimation modes + + + + autosize + autospacing + + + 0 + False + + + ParameterNumber + outputs.default + Default pixel value + Default value to write when outside of input image. + + + 0 + True + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + bco + nn + linear + + + 0 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + opt.ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + + ParameterNumber + opt.gridspacing + Resampling grid spacing + Resampling is done according to a coordinate mapping deformation grid, whose pixel size is set by this parameter, and expressed in the coordinate system of the output image The closer to the output spacing this parameter is, the more precise will be the ortho-rectified image,but increasing this parameter will reduce processing time. + + + 4 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-utm.xml b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-utm.xml new file mode 100644 index 000000000000..4f9a84fe044d --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/OrthoRectification-utm.xml @@ -0,0 +1,132 @@ + + OrthoRectification-utm + otbcli_OrthoRectification + OrthoRectification (utm) + Geometry + This application allows ortho-rectification of optical images from supported sensors. + + + ParameterRaster + io.in + Input Image + The input image to ortho-rectify + False + + + OutputRaster + io.out + Output Image + The ortho-rectified output image + + + + ParameterSelection + map + Output Cartographic Map Projection + Parameters of the output map projection to be used. + + + utm + + + 0 + False + + + ParameterNumber + map.utm.zone + Zone number + The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere) + + + 31 + False + + + ParameterBoolean + map.utm.northhem + Northern Hemisphere + The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere. + True + True + + + ParameterSelection + outputs.mode + Parameters estimation modes + + + + autosize + autospacing + + + 0 + False + + + ParameterNumber + outputs.default + Default pixel value + Default value to write when outside of input image. + + + 0 + True + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + bco + nn + linear + + + 0 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + opt.ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + + ParameterNumber + opt.gridspacing + Resampling grid spacing + Resampling is done according to a coordinate mapping deformation grid, whose pixel size is set by this parameter, and expressed in the coordinate system of the output image The closer to the output spacing this parameter is, the more precise will be the ortho-rectified image,but increasing this parameter will reduce processing time. + + + 4 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-bayes.xml b/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-bayes.xml new file mode 100644 index 000000000000..9b45d08e9e73 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-bayes.xml @@ -0,0 +1,71 @@ + + Pansharpening-bayes + otbcli_Pansharpening + Pansharpening (bayes) + Geometry + Perform P+XS pansharpening + + ParameterRaster + inp + Input PAN Image + Input panchromatic image. + False + + + ParameterRaster + inxs + Input XS Image + Input XS image. + False + + + OutputRaster + out + Output image + Output image. + + + + ParameterSelection + method + Algorithm + Selection of the pan-sharpening method. + + + bayes + + + 0 + False + + + ParameterNumber + method.bayes.lambda + Weight + Set the weighting value. + + + 0.9999 + False + + + ParameterNumber + method.bayes.s + S coefficient + Set the S coefficient. + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-lmvm.xml b/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-lmvm.xml new file mode 100644 index 000000000000..fd6d171f58b9 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-lmvm.xml @@ -0,0 +1,71 @@ + + Pansharpening-lmvm + otbcli_Pansharpening + Pansharpening (lmvm) + Geometry + Perform P+XS pansharpening + + ParameterRaster + inp + Input PAN Image + Input panchromatic image. + False + + + ParameterRaster + inxs + Input XS Image + Input XS image. + False + + + OutputRaster + out + Output image + Output image. + + + + ParameterSelection + method + Algorithm + Selection of the pan-sharpening method. + + + lmvm + + + 0 + False + + + ParameterNumber + method.lmvm.radiusx + X radius + Set the x radius of the sliding window. + + + 3 + False + + + ParameterNumber + method.lmvm.radiusy + Y radius + Set the y radius of the sliding window. + + + 3 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-rcs.xml b/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-rcs.xml new file mode 100644 index 000000000000..d8b9c1bc8480 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Pansharpening-rcs.xml @@ -0,0 +1,51 @@ + + Pansharpening-rcs + otbcli_Pansharpening + Pansharpening (rcs) + Geometry + Perform P+XS pansharpening + + ParameterRaster + inp + Input PAN Image + Input panchromatic image. + False + + + ParameterRaster + inxs + Input XS Image + Input XS image. + False + + + OutputRaster + out + Output image + Output image. + + + + ParameterSelection + method + Algorithm + Selection of the pan-sharpening method. + + + rcs + + + 0 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/RadiometricIndices.xml b/python/plugins/processing/algs/otb/description/5.4.0/RadiometricIndices.xml new file mode 100644 index 000000000000..41aa91db8123 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/RadiometricIndices.xml @@ -0,0 +1,131 @@ + + RadiometricIndices + otbcli_RadiometricIndices + Radiometric Indices + Feature Extraction + Compute radiometric indices. + + ParameterRaster + in + Input Image + Input image + False + + + OutputRaster + out + Output Image + Radiometric indices output image + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + channels.blue + Blue Channel + Blue channel index + + + 1 + False + + + ParameterNumber + channels.green + Green Channel + Green channel index + + + 1 + False + + + ParameterNumber + channels.red + Red Channel + Red channel index + + + 1 + False + + + ParameterNumber + channels.nir + NIR Channel + NIR channel index + + + 1 + False + + + ParameterNumber + channels.mir + Mir Channel + Mir channel index + + + 1 + False + + + ParameterSelection + list + Available Radiometric Indices + List of available radiometric indices with their relevant channels in brackets: + Vegetation:NDVI - Normalized difference vegetation index (Red, NIR) + Vegetation:TNDVI - Transformed normalized difference vegetation index (Red, NIR) + Vegetation:RVI - Ratio vegetation index (Red, NIR) + Vegetation:SAVI - Soil adjusted vegetation index (Red, NIR) + Vegetation:TSAVI - Transformed soil adjusted vegetation index (Red, NIR) + Vegetation:MSAVI - Modified soil adjusted vegetation index (Red, NIR) + Vegetation:MSAVI2 - Modified soil adjusted vegetation index 2 (Red, NIR) + Vegetation:GEMI - Global environment monitoring index (Red, NIR) + Vegetation:IPVI - Infrared percentage vegetation index (Red, NIR) + + Water:NDWI - Normalized difference water index (Gao 1996) (NIR, MIR) + Water:NDWI2 - Normalized difference water index (Mc Feeters 1996) (Green, NIR) + Water:MNDWI - Modified normalized difference water index (Xu 2006) (Green, MIR) + Water:NDPI - Normalized difference pond index (Lacaux et al.) (MIR, Green) + Water:NDTI - Normalized difference turbidity index (Lacaux et al.) (Red, Green) + + Soil:RI - Redness index (Red, Green) + Soil:CI - Color index (Red, Green) + Soil:BI - Brightness index (Red, Green) + Soil:BI2 - Brightness index 2 (NIR, Red, Green) + + + ndvi + tndvi + rvi + savi + tsavi + msavi + msavi2 + gemi + ipvi + ndwi + ndwi2 + mndwi + ndpi + ndti + ri + ci + bi + bi2 + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Rasterization-image.xml b/python/plugins/processing/algs/otb/description/5.4.0/Rasterization-image.xml new file mode 100644 index 000000000000..b7cf4262711d --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Rasterization-image.xml @@ -0,0 +1,83 @@ + + Rasterization-image + otbcli_Rasterization + Rasterization (image) + Vector Data Manipulation + Rasterize a vector dataset. + + ParameterVector + in + Input vector dataset + The input vector dataset to be rasterized + + False + + + OutputRaster + out + Output image + An output image containing the rasterized vector dataset + + + + ParameterRaster + im + Input reference image + A reference image from which to import output grid and projection reference system information. + True + + + ParameterNumber + background + Background value + Default value for pixels not belonging to any geometry + + + 0 + False + + + ParameterSelection + mode + Rasterization mode + Choice of rasterization modes + + + binary + attribute + + + 0 + False + + + ParameterNumber + mode.binary.foreground + Foreground value + Value for pixels inside a geometry + + + 255 + False + + + ParameterString + mode.attribute.field + The attribute field to burn + Name of the attribute field to burn + DN + + False + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Rasterization-manual.xml b/python/plugins/processing/algs/otb/description/5.4.0/Rasterization-manual.xml new file mode 100644 index 000000000000..97e0d288fd3a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Rasterization-manual.xml @@ -0,0 +1,146 @@ + + Rasterization-manual + otbcli_Rasterization + Rasterization (manual) + Vector Data Manipulation + Rasterize a vector dataset. + + ParameterVector + in + Input vector dataset + The input vector dataset to be rasterized + + False + + + OutputRaster + out + Output image + An output image containing the rasterized vector dataset + + + + ParameterNumber + szx + Output size x + Output size along x axis (useless if support image is given) + + + 0 + True + + + ParameterNumber + szy + Output size y + Output size along y axis (useless if support image is given) + + + 0 + True + + + ParameterNumber + epsg + Output EPSG code + EPSG code for the output projection reference system (EPSG 4326 for WGS84, 32631 for UTM31N...,useless if support image is given) + + + 0 + True + + + ParameterNumber + orx + Output Upper-left x + Output upper-left corner x coordinate (useless if support image is given) + + + 0.0 + True + + + ParameterNumber + ory + Output Upper-left y + Output upper-left corner y coordinate (useless if support image is given) + + + 0.0 + True + + + ParameterNumber + spx + Spacing (GSD) x + Spacing (ground sampling distance) along x axis (useless if support image is given) + + + 0.0 + True + + + ParameterNumber + spy + Spacing (GSD) y + Spacing (ground sampling distance) along y axis (useless if support image is given) + + + 0.0 + True + + + ParameterNumber + background + Background value + Default value for pixels not belonging to any geometry + + + 0 + False + + + ParameterSelection + mode + Rasterization mode + Choice of rasterization modes + + + binary + attribute + + + 0 + False + + + ParameterNumber + mode.binary.foreground + Foreground value + Value for pixels inside a geometry + + + 255 + False + + + ParameterString + mode.attribute.field + The attribute field to burn + Name of the attribute field to burn + DN + + False + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/ReadImageInfo.xml b/python/plugins/processing/algs/otb/description/5.4.0/ReadImageInfo.xml new file mode 100644 index 000000000000..9ddf48cfedd7 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/ReadImageInfo.xml @@ -0,0 +1,62 @@ + + ReadImageInfo + otbcli_ReadImageInfo + Read image information + Image Manipulation + Get information about the image + + ParameterRaster + in + Input Image + Input image to analyse + False + + + ParameterBoolean + keywordlist + Display the OSSIM keywordlist + Output the OSSIM keyword list. It contains metadata information (sensor model, geometry ). Information is stored in keyword list (pairs of key/value) + True + True + + + ParameterString + gcp.ids + GCPs Id + GCPs identifier + + + False + + + + ParameterString + gcp.info + GCPs Info + GCPs Information + + + False + + + + ParameterString + gcp.imcoord + GCPs Image Coordinates + GCPs Image coordinates + + + False + + + + ParameterString + gcp.geocoord + GCPs Geographic Coordinates + GCPs Geographic Coordinates + + + False + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Rescale.xml b/python/plugins/processing/algs/otb/description/5.4.0/Rescale.xml new file mode 100644 index 000000000000..6ae441121fea --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Rescale.xml @@ -0,0 +1,51 @@ + + Rescale + otbcli_Rescale + Rescale Image + Image Manipulation + Rescale the image between two given values. + + ParameterRaster + in + Input Image + The image to scale. + False + + + OutputRaster + out + Output Image + The rescaled image filename. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + outmin + Output min value + Minimum value of the output image. + + + 0 + True + + + ParameterNumber + outmax + Output max value + Maximum value of the output image. + + + 255 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-id.xml b/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-id.xml new file mode 100644 index 000000000000..034f79e8052d --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-id.xml @@ -0,0 +1,89 @@ + + RigidTransformResample-id + otbcli_RigidTransformResample + RigidTransformResample (id) + Geometry + Resample an image with a rigid transform + + ParameterRaster + in + Input image + The input image to translate. + False + + + OutputRaster + out + Output image + The transformed output image. + + + + ParameterSelection + transform.type + Type of transformation + Type of transformation. Available transformations are spatial scaling, translation and rotation with scaling factor + + + id + + + 0 + False + + + ParameterNumber + transform.type.id.scalex + X scaling + Scaling factor between the output X spacing and the input X spacing + + + 1 + False + + + ParameterNumber + transform.type.id.scaley + Y scaling + Scaling factor between the output Y spacing and the input Y spacing + + + 1 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + nn + linear + bco + + + 2 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-rotation.xml b/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-rotation.xml new file mode 100644 index 000000000000..69130b640956 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-rotation.xml @@ -0,0 +1,99 @@ + + RigidTransformResample-rotation + otbcli_RigidTransformResample + RigidTransformResample (rotation) + Geometry + Resample an image with a rigid transform + + ParameterRaster + in + Input image + The input image to translate. + False + + + OutputRaster + out + Output image + The transformed output image. + + + + ParameterSelection + transform.type + Type of transformation + Type of transformation. Available transformations are spatial scaling, translation and rotation with scaling factor + + + rotation + + + 0 + False + + + ParameterNumber + transform.type.rotation.angle + Rotation angle + The rotation angle in degree (values between -180 and 180) + + + 0 + False + + + ParameterNumber + transform.type.rotation.scalex + X scaling + Scale factor between the X spacing of the rotated output image and the X spacing of the unrotated image + + + 1 + False + + + ParameterNumber + transform.type.rotation.scaley + Y scaling + Scale factor between the Y spacing of the rotated output image and the Y spacing of the unrotated image + + + 1 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + nn + linear + bco + + + 2 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-translation.xml b/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-translation.xml new file mode 100644 index 000000000000..f723ac8487a3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/RigidTransformResample-translation.xml @@ -0,0 +1,109 @@ + + RigidTransformResample-translation + otbcli_RigidTransformResample + RigidTransformResample (translation) + Geometry + Resample an image with a rigid transform + + ParameterRaster + in + Input image + The input image to translate. + False + + + OutputRaster + out + Output image + The transformed output image. + + + + ParameterSelection + transform.type + Type of transformation + Type of transformation. Available transformations are spatial scaling, translation and rotation with scaling factor + + + translation + + + 0 + False + + + ParameterNumber + transform.type.translation.tx + The X translation (in physical units) + The translation value along X axis (in physical units). + + + 0 + False + + + ParameterNumber + transform.type.translation.ty + The Y translation (in physical units) + The translation value along Y axis (in physical units) + + + 0 + False + + + ParameterNumber + transform.type.translation.scalex + X scaling + Scaling factor between the output X spacing and the input X spacing + + + 1 + False + + + ParameterNumber + transform.type.translation.scaley + Y scaling + Scaling factor between the output Y spacing and the input Y spacing + + + 1 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows one to define how the input image will be interpolated during resampling. + + + nn + linear + bco + + + 2 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + ram + Available RAM (Mb) + This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/SFSTextureExtraction.xml b/python/plugins/processing/algs/otb/description/5.4.0/SFSTextureExtraction.xml new file mode 100644 index 000000000000..d4c6b1e2abd0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/SFSTextureExtraction.xml @@ -0,0 +1,91 @@ + + SFSTextureExtraction + otbcli_SFSTextureExtraction + SFS Texture Extraction + Feature Extraction + Computes Structural Feature Set textures on every pixel of the input image selected channel + + ParameterRaster + in + Input Image + The input image to compute the features on. + False + + + ParameterNumber + channel + Selected Channel + The selected channel index + + + 1 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + parameters.spethre + Spectral Threshold + Spectral Threshold + + + 50 + False + + + ParameterNumber + parameters.spathre + Spatial Threshold + Spatial Threshold + + + 100 + False + + + ParameterNumber + parameters.nbdir + Number of Direction + Number of Direction + + + 20 + False + + + ParameterNumber + parameters.alpha + Alpha + Alpha + + + 1 + False + + + ParameterNumber + parameters.maxcons + Ratio Maximum Consideration Number + Ratio Maximum Consideration Number + + + 5 + False + + + OutputRaster + out + Feature Output Image + Output image containing the SFS texture features. + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/SOMClassification.xml b/python/plugins/processing/algs/otb/description/5.4.0/SOMClassification.xml new file mode 100644 index 000000000000..c6ebd5d63651 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/SOMClassification.xml @@ -0,0 +1,155 @@ + + SOMClassification + otbcli_SOMClassification + SOM Classification + Learning + SOM image classification. + + ParameterRaster + in + InputImage + Input image to classify. + False + + + OutputRaster + out + OutputImage + Output classified image (each pixel contains the index of its corresponding vector in the SOM). + + + + ParameterRaster + vm + ValidityMask + Validity mask (only pixels corresponding to a mask value greater than 0 will be used for learning) + True + + + ParameterNumber + tp + TrainingProbability + Probability for a sample to be selected in the training set + + + 1 + True + + + ParameterNumber + ts + TrainingSetSize + Maximum training set size (in pixels) + + + 0 + True + + + OutputRaster + som + SOM Map + Output image containing the Self-Organizing Map + + + + ParameterNumber + sx + SizeX + X size of the SOM map + + + 32 + True + + + ParameterNumber + sy + SizeY + Y size of the SOM map + + + 32 + True + + + ParameterNumber + nx + NeighborhoodX + X size of the initial neighborhood in the SOM map + + + 10 + True + + + ParameterNumber + ny + NeighborhoodY + Y size of the initial neighborhood in the SOM map + + + 10 + False + + + ParameterNumber + ni + NumberIteration + Number of iterations for SOM learning + + + 5 + True + + + ParameterNumber + bi + BetaInit + Initial learning coefficient + + + 1 + True + + + ParameterNumber + bf + BetaFinal + Final learning coefficient + + + 0.1 + True + + + ParameterNumber + iv + InitialValue + Maximum initial neuron weight + + + 0 + True + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-cc.xml b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-cc.xml new file mode 100644 index 000000000000..fcde12fa02fb --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-cc.xml @@ -0,0 +1,165 @@ + + Segmentation-cc + otbcli_Segmentation + Segmentation (cc) + Segmentation + Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported. + + ParameterRaster + in + Input Image + The input image to segment + False + + + ParameterSelection + filter + Segmentation algorithm + Choice of segmentation algorithm (mean-shift by default) + + + cc + + + 0 + False + + + ParameterString + filter.cc.expr + Condition + User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ) + + + False + + + + ParameterSelection + mode + Processing mode + Choice of processing mode, either raster or large-scale. + + + vector + + + 0 + False + + + OutputVector + mode.vector.out + Output vector file + The output vector file or database (name can be anything understood by OGR) + + + ParameterSelection + mode.vector.outmode + Writing mode for the output vector file + This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format. + + + ulco + ovw + ulovw + ulu + + + 0 + False + + + ParameterRaster + mode.vector.inmask + Mask Image + Only pixels whose mask value is strictly positive will be segmented. + True + + + ParameterBoolean + mode.vector.neighbor + 8-neighbor connectivity + Activate 8-Neighborhood connectivity (default is 4). + True + True + + + ParameterBoolean + mode.vector.stitch + Stitch polygons + Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel. + True + True + + + ParameterNumber + mode.vector.minsize + Minimum object size + Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization. + + + 1 + True + + + ParameterNumber + mode.vector.simplify + Simplify polygons + Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database. + + + 0.1 + True + + + ParameterString + mode.vector.layername + Layer name + Name of the layer in the vector file or database (default is Layer). + layer + + False + + + + ParameterString + mode.vector.fieldname + Geometry index field name + Name of the field holding the geometry index in the output vector file or database. + DN + + False + + + + ParameterNumber + mode.vector.tilesize + Tiles size + User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null. + + + 1024 + False + + + ParameterNumber + mode.vector.startlabel + Starting geometry index + Starting value of the geometry index field + + + 1 + False + + + ParameterString + mode.vector.ogroptions + OGR options for layer creation + A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation. + + + True + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-meanshift.xml b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-meanshift.xml new file mode 100644 index 000000000000..6ad6efcaec22 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-meanshift.xml @@ -0,0 +1,205 @@ + + Segmentation-meanshift + otbcli_Segmentation + Segmentation (meanshift) + Segmentation + Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported. + + ParameterRaster + in + Input Image + The input image to segment + False + + + ParameterSelection + filter + Segmentation algorithm + Choice of segmentation algorithm (mean-shift by default) + + + meanshift + + + 0 + False + + + ParameterNumber + filter.meanshift.spatialr + Spatial radius + Spatial radius of the neighborhood. + + + 5 + False + + + ParameterNumber + filter.meanshift.ranger + Range radius + Range radius defining the radius (expressed in radiometry unit) in the multispectral space. + + + 15 + False + + + ParameterNumber + filter.meanshift.thres + Mode convergence threshold + Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations. + + + 0.1 + False + + + ParameterNumber + filter.meanshift.maxiter + Maximum number of iterations + Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations. + + + 100 + False + + + ParameterNumber + filter.meanshift.minsize + Minimum region size + Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done. + + + 100 + False + + + ParameterSelection + mode + Processing mode + Choice of processing mode, either raster or large-scale. + + + vector + + + 0 + False + + + OutputVector + mode.vector.out + Output vector file + The output vector file or database (name can be anything understood by OGR) + + + ParameterSelection + mode.vector.outmode + Writing mode for the output vector file + This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format. + + + ulco + ovw + ulovw + ulu + + + 0 + False + + + ParameterRaster + mode.vector.inmask + Mask Image + Only pixels whose mask value is strictly positive will be segmented. + True + + + ParameterBoolean + mode.vector.neighbor + 8-neighbor connectivity + Activate 8-Neighborhood connectivity (default is 4). + True + True + + + ParameterBoolean + mode.vector.stitch + Stitch polygons + Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel. + True + True + + + ParameterNumber + mode.vector.minsize + Minimum object size + Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization. + + + 1 + True + + + ParameterNumber + mode.vector.simplify + Simplify polygons + Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database. + + + 0.1 + True + + + ParameterString + mode.vector.layername + Layer name + Name of the layer in the vector file or database (default is Layer). + layer + + False + + + + ParameterString + mode.vector.fieldname + Geometry index field name + Name of the field holding the geometry index in the output vector file or database. + DN + + False + + + + ParameterNumber + mode.vector.tilesize + Tiles size + User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null. + + + 1024 + False + + + ParameterNumber + mode.vector.startlabel + Starting geometry index + Starting value of the geometry index field + + + 1 + False + + + ParameterString + mode.vector.ogroptions + OGR options for layer creation + A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation. + + + True + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-mprofiles.xml b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-mprofiles.xml new file mode 100644 index 000000000000..24a262ab039a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-mprofiles.xml @@ -0,0 +1,195 @@ + + Segmentation-mprofiles + otbcli_Segmentation + Segmentation (mprofiles) + Segmentation + Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported. + + ParameterRaster + in + Input Image + The input image to segment + False + + + ParameterSelection + filter + Segmentation algorithm + Choice of segmentation algorithm (mean-shift by default) + + + mprofiles + + + 0 + False + + + ParameterNumber + filter.mprofiles.size + Profile Size + Size of the profiles + + + 5 + False + + + ParameterNumber + filter.mprofiles.start + Initial radius + Initial radius of the structuring element (in pixels) + + + 1 + False + + + ParameterNumber + filter.mprofiles.step + Radius step. + Radius step along the profile (in pixels) + + + 1 + False + + + ParameterNumber + filter.mprofiles.sigma + Threshold of the final decision rule + Profiles values under the threshold will be ignored. + + + 1 + False + + + ParameterSelection + mode + Processing mode + Choice of processing mode, either raster or large-scale. + + + vector + + + 0 + False + + + OutputVector + mode.vector.out + Output vector file + The output vector file or database (name can be anything understood by OGR) + + + ParameterSelection + mode.vector.outmode + Writing mode for the output vector file + This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format. + + + ulco + ovw + ulovw + ulu + + + 0 + False + + + ParameterRaster + mode.vector.inmask + Mask Image + Only pixels whose mask value is strictly positive will be segmented. + True + + + ParameterBoolean + mode.vector.neighbor + 8-neighbor connectivity + Activate 8-Neighborhood connectivity (default is 4). + True + True + + + ParameterBoolean + mode.vector.stitch + Stitch polygons + Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel. + True + True + + + ParameterNumber + mode.vector.minsize + Minimum object size + Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization. + + + 1 + True + + + ParameterNumber + mode.vector.simplify + Simplify polygons + Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database. + + + 0.1 + True + + + ParameterString + mode.vector.layername + Layer name + Name of the layer in the vector file or database (default is Layer). + layer + + False + + + + ParameterString + mode.vector.fieldname + Geometry index field name + Name of the field holding the geometry index in the output vector file or database. + DN + + False + + + + ParameterNumber + mode.vector.tilesize + Tiles size + User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null. + + + 1024 + False + + + ParameterNumber + mode.vector.startlabel + Starting geometry index + Starting value of the geometry index field + + + 1 + False + + + ParameterString + mode.vector.ogroptions + OGR options for layer creation + A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation. + + + True + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-watershed.xml b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-watershed.xml new file mode 100644 index 000000000000..f16a66c61370 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Segmentation-watershed.xml @@ -0,0 +1,175 @@ + + Segmentation-watershed + otbcli_Segmentation + Segmentation (watershed) + Segmentation + Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported. + + ParameterRaster + in + Input Image + The input image to segment + False + + + ParameterSelection + filter + Segmentation algorithm + Choice of segmentation algorithm (mean-shift by default) + + + watershed + + + 0 + False + + + ParameterNumber + filter.watershed.threshold + Depth Threshold + Depth threshold Units in percentage of the maximum depth in the image. + + + 0.01 + False + + + ParameterNumber + filter.watershed.level + Flood Level + flood level for generating the merge tree from the initial segmentation (between 0 and 1) + + + 0.1 + False + + + ParameterSelection + mode + Processing mode + Choice of processing mode, either raster or large-scale. + + + vector + + + 0 + False + + + OutputVector + mode.vector.out + Output vector file + The output vector file or database (name can be anything understood by OGR) + + + ParameterSelection + mode.vector.outmode + Writing mode for the output vector file + This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format. + + + ulco + ovw + ulovw + ulu + + + 0 + False + + + ParameterRaster + mode.vector.inmask + Mask Image + Only pixels whose mask value is strictly positive will be segmented. + True + + + ParameterBoolean + mode.vector.neighbor + 8-neighbor connectivity + Activate 8-Neighborhood connectivity (default is 4). + True + True + + + ParameterBoolean + mode.vector.stitch + Stitch polygons + Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel. + True + True + + + ParameterNumber + mode.vector.minsize + Minimum object size + Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization. + + + 1 + True + + + ParameterNumber + mode.vector.simplify + Simplify polygons + Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database. + + + 0.1 + True + + + ParameterString + mode.vector.layername + Layer name + Name of the layer in the vector file or database (default is Layer). + layer + + False + + + + ParameterString + mode.vector.fieldname + Geometry index field name + Name of the field holding the geometry index in the output vector file or database. + DN + + False + + + + ParameterNumber + mode.vector.tilesize + Tiles size + User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null. + + + 1024 + False + + + ParameterNumber + mode.vector.startlabel + Starting geometry index + Starting value of the geometry index field + + + 1 + False + + + ParameterString + mode.vector.ogroptions + OGR options for layer creation + A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation. + + + True + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-anidif.xml b/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-anidif.xml new file mode 100644 index 000000000000..84f43f070f40 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-anidif.xml @@ -0,0 +1,74 @@ + + Smoothing-anidif + otbcli_Smoothing + Smoothing (anidif) + Image Filtering + Apply a smoothing filter to an image + + ParameterRaster + in + Input Image + Input image to smooth. + False + + + OutputRaster + out + Output Image + Output smoothed image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + type + Smoothing Type + Smoothing kernel to apply + + + anidif + + + 2 + False + + + ParameterNumber + type.anidif.timestep + Time Step + Diffusion equation time step + + + 0.125 + False + + + ParameterNumber + type.anidif.nbiter + Nb Iterations + Controls the sensitivity of the conductance term + + + 10 + False + + + ParameterNumber + type.anidif.conductance + Conductance + + + + 1 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-gaussian.xml b/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-gaussian.xml new file mode 100644 index 000000000000..49f7cc1fc551 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-gaussian.xml @@ -0,0 +1,54 @@ + + Smoothing-gaussian + otbcli_Smoothing + Smoothing (gaussian) + Image Filtering + Apply a smoothing filter to an image + + ParameterRaster + in + Input Image + Input image to smooth. + False + + + OutputRaster + out + Output Image + Output smoothed image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + type + Smoothing Type + Smoothing kernel to apply + + + gaussian + + + 2 + False + + + ParameterNumber + type.gaussian.radius + Radius + Gaussian radius (in pixels) + + + 2 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-mean.xml b/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-mean.xml new file mode 100644 index 000000000000..8e010db17ede --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Smoothing-mean.xml @@ -0,0 +1,54 @@ + + Smoothing-mean + otbcli_Smoothing + Smoothing (mean) + Image Filtering + Apply a smoothing filter to an image + + ParameterRaster + in + Input Image + Input image to smooth. + False + + + OutputRaster + out + Output Image + Output smoothed image. + + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + + ParameterSelection + type + Smoothing Type + Smoothing kernel to apply + + + mean + + + 2 + False + + + ParameterNumber + type.mean.radius + Radius + Mean radius (in pixels) + + + 2 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/StereoFramework.xml b/python/plugins/processing/algs/otb/description/5.4.0/StereoFramework.xml new file mode 100644 index 000000000000..c43dc02aa5c4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/StereoFramework.xml @@ -0,0 +1,344 @@ + + StereoFramework + otbcli_StereoFramework + Stereo Framework + Stereo + Compute the ground elevation based on one or multiple stereo pair(s) + + ParameterMultipleInput + input.il + Input images list + The list of images. + + False + + + ParameterString + input.co + Couples list + List of index of couples im image list. Couples must be separated by a comma. (index start at 0). for example : 0 1,1 2 will process a first couple composed of the first and the second image in image list, then the first and the third image +. note that images are handled by pairs. if left empty couples are created from input index i.e. a first couple will be composed of the first and second image, a second couple with third and fourth image etc. (in this case image list must be even). + + + True + + + + ParameterNumber + input.channel + Image channel used for the block matching + Used channel for block matching (used for all images) + + + 1 + False + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + output.res + Output resolution + Spatial sampling distance of the output elevation : the cell size (in m) + + + 1 + False + + + ParameterNumber + output.nodata + NoData value + DSM empty cells are filled with this value (optional -32768 by default) + + + -32768 + True + + + ParameterSelection + output.fusionmethod + Method to fuse measures in each DSM cell + This parameter allows one to choose the method used to fuse elevation measurements in each output DSM cell + + + max + min + mean + acc + + + 0 + False + + + OutputRaster + output.out + Output DSM + Output elevation image + + + + ParameterSelection + output.mode + Parameters estimation modes + + + + fit + user + + + 0 + False + + + ParameterNumber + output.mode.user.ulx + Upper Left X + Cartographic X coordinate of upper-left corner (meters for cartographic projections, degrees for geographic ones) + + + 0.0 + False + + + ParameterNumber + output.mode.user.uly + Upper Left Y + Cartographic Y coordinate of the upper-left corner (meters for cartographic projections, degrees for geographic ones) + + + 0.0 + False + + + ParameterNumber + output.mode.user.sizex + Size X + Size of projected image along X (in pixels) + + + 0 + False + + + ParameterNumber + output.mode.user.sizey + Size Y + Size of projected image along Y (in pixels) + + + 0 + False + + + ParameterNumber + output.mode.user.spacingx + Pixel Size X + Size of each pixel along X axis (meters for cartographic projections, degrees for geographic ones) + + + 0.0 + False + + + ParameterNumber + output.mode.user.spacingy + Pixel Size Y + Size of each pixel along Y axis (meters for cartographic projections, degrees for geographic ones) + + + 0.0 + False + + + ParameterSelection + map + Output Cartographic Map Projection + Parameters of the output map projection to be used. + + + utm + lambert2 + lambert93 + wgs + epsg + + + 3 + False + + + ParameterNumber + map.utm.zone + Zone number + The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere) + + + 31 + False + + + ParameterBoolean + map.utm.northhem + Northern Hemisphere + The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere. + True + True + + + ParameterNumber + map.epsg.code + EPSG Code + See www.spatialreference.org to find which EPSG code is associated to your projection + + + 4326 + False + + + ParameterNumber + stereorect.fwdgridstep + Step of the displacement grid (in pixels) + Stereo-rectification displacement grid only varies slowly. Therefore, it is recommended to use a coarser grid (higher step value) in case of large images + + + 16 + True + + + ParameterNumber + stereorect.invgridssrate + Sub-sampling rate for epipolar grid inversion + Grid inversion is an heavy process that implies spline regression on control points. To avoid eating to much memory, this parameter allows one to first sub-sample the field to invert. + + + 10 + True + + + ParameterSelection + bm.metric + Block-matching metric + + + + ssdmean + ssd + ncc + lp + + + 0 + False + + + ParameterNumber + bm.metric.lp.p + p value + Value of the p parameter in Lp pseudo-norm (must be positive) + + + 1 + False + + + ParameterNumber + bm.radius + Radius of blocks for matching filter (in pixels) + The radius of blocks in Block-Matching (in pixels) + + + 2 + True + + + ParameterNumber + bm.minhoffset + Minimum altitude offset (in meters) + Minimum altitude below the selected elevation source (in meters) + + + -20 + False + + + ParameterNumber + bm.maxhoffset + Maximum altitude offset (in meters) + Maximum altitude above the selected elevation source (in meters) + + + 20 + False + + + ParameterBoolean + postproc.bij + Use bijection consistency in block matching strategy + use bijection consistency. Right to Left correlation is computed to validate Left to Right disparities. If bijection is not found pixel is rejected. + True + True + + + ParameterBoolean + postproc.med + Use median disparities filtering + disparities output can be filtered using median post filtering (disabled by default). + True + True + + + ParameterNumber + postproc.metrict + Correlation metric threshold + Use block matching metric output to discard pixels with low correlation value (disabled by default, float value) + + + 0.6 + True + + + ParameterRaster + mask.left + Input left mask + Mask for left input image + True + + + ParameterRaster + mask.right + Input right mask + Mask for right input image + True + + + ParameterNumber + mask.variancet + Discard pixels with low local variance + This parameter allows one to discard pixels whose local variance is too small (the size of the neighborhood is given by the radius parameter) + + + 50 + True + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/Superimpose.xml b/python/plugins/processing/algs/otb/description/5.4.0/Superimpose.xml new file mode 100644 index 000000000000..00453d389689 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/Superimpose.xml @@ -0,0 +1,97 @@ + + Superimpose + otbcli_Superimpose + Superimpose sensor + Geometry + Using available image metadata, project one image onto another one + + ParameterRaster + inr + Reference input + The input reference image. + False + + + ParameterRaster + inm + The image to reproject + The image to reproject into the geometry of the reference input. + False + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + lms + Spacing of the deformation field + Generate a coarser deformation field with the given spacing + + + 4 + True + + + OutputRaster + out + Output image + Output reprojected image. + + + + ParameterSelection + mode + Mode + Superimposition mode + + + default + phr + + + 0 + False + + + ParameterSelection + interpolator + Interpolation + This group of parameters allows defining how the input image will be interpolated during resampling. + + + bco + nn + linear + + + 0 + False + + + ParameterNumber + interpolator.bco.radius + Radius for bicubic interpolation + This parameter allows controling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts. + + + 2 + False + + + ParameterNumber + ram + Available RAM (Mb) + Available memory for processing (in MB) + + + 128 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TileFusion.xml b/python/plugins/processing/algs/otb/description/5.4.0/TileFusion.xml new file mode 100644 index 000000000000..b157b2caa49a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TileFusion.xml @@ -0,0 +1,42 @@ + + TileFusion + otbcli_TileFusion + Image Tile Fusion + Image Manipulation + Fusion of an image made of several tile files. + + ParameterMultipleInput + il + Input Tile Images + Input tiles to concatenate (in lexicographic order : (0,0) (1,0) (0,1) (1,1)). + + False + + + ParameterNumber + cols + Number of tile columns + Number of columns in the tile array + + + 0 + False + + + ParameterNumber + rows + Number of tile rows + Number of rows in the tile array + + + 0 + False + + + OutputRaster + out + Output Image + Output entire image + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-ann.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-ann.xml new file mode 100644 index 000000000000..0381ea96df49 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-ann.xml @@ -0,0 +1,268 @@ + + TrainImagesClassifier-ann + otbcli_TrainImagesClassifier + TrainImagesClassifier (ann) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + ann + + + 0 + False + + + ParameterSelection + classifier.ann.t + Train Method Type + Type of training method for the multilayer perceptron (MLP) neural network. + + + reg + back + + + 0 + False + + + ParameterString + classifier.ann.sizes + Number of neurons in each intermediate layer + The number of neurons in each intermediate layer (excluding input and output layers). + + + False + + + + ParameterSelection + classifier.ann.f + Neuron activation function type + Neuron activation function. + + + ident + sig + gau + + + 1 + False + + + ParameterNumber + classifier.ann.a + Alpha parameter of the activation function + Alpha parameter of the activation function (used only with sigmoid and gaussian functions). + + + 1 + False + + + ParameterNumber + classifier.ann.b + Beta parameter of the activation function + Beta parameter of the activation function (used only with sigmoid and gaussian functions). + + + 1 + False + + + ParameterNumber + classifier.ann.bpdw + Strength of the weight gradient term in the BACKPROP method + Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1. + + + 0.1 + False + + + ParameterNumber + classifier.ann.bpms + Strength of the momentum term (the difference between weights on the 2 previous iterations) + Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough. + + + 0.1 + False + + + ParameterNumber + classifier.ann.rdw + Initial value Delta_0 of update-values Delta_{ij} in RPROP method + Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1). + + + 0.1 + False + + + ParameterNumber + classifier.ann.rdwm + Update-values lower limit Delta_{min} in RPROP method + Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7). + + + 1e-07 + False + + + ParameterSelection + classifier.ann.term + Termination criteria + Termination criteria. + + + iter + eps + all + + + 2 + False + + + ParameterNumber + classifier.ann.eps + Epsilon value used in the Termination criteria + Epsilon value used in the Termination criteria. + + + 0.01 + False + + + ParameterNumber + classifier.ann.iter + Maximum number of iterations used in the Termination criteria + Maximum number of iterations used in the Termination criteria. + + + 1000 + False + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-bayes.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-bayes.xml new file mode 100644 index 000000000000..d1182d51be1b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-bayes.xml @@ -0,0 +1,134 @@ + + TrainImagesClassifier-bayes + otbcli_TrainImagesClassifier + TrainImagesClassifier (bayes) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + bayes + + + 0 + False + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-boost.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-boost.xml new file mode 100644 index 000000000000..2838d3a69ad5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-boost.xml @@ -0,0 +1,180 @@ + + TrainImagesClassifier-boost + otbcli_TrainImagesClassifier + TrainImagesClassifier (boost) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + boost + + + 0 + False + + + ParameterSelection + classifier.boost.t + Boost Type + Type of Boosting algorithm. + + + discrete + real + logit + gentle + + + 1 + False + + + ParameterNumber + classifier.boost.w + Weak count + The number of weak classifiers. + + + 100 + False + + + ParameterNumber + classifier.boost.r + Weight Trim Rate + A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality. + + + 0.95 + False + + + ParameterNumber + classifier.boost.m + Maximum depth of the tree + Maximum depth of the tree. + + + 1 + False + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-dt.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-dt.xml new file mode 100644 index 000000000000..697cf10f34ac --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-dt.xml @@ -0,0 +1,200 @@ + + TrainImagesClassifier-dt + otbcli_TrainImagesClassifier + TrainImagesClassifier (dt) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + dt + + + 0 + False + + + ParameterNumber + classifier.dt.max + Maximum depth of the tree + The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned. + + + 65535 + False + + + ParameterNumber + classifier.dt.min + Minimum number of samples in each node + If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split. + + + 10 + False + + + ParameterNumber + classifier.dt.ra + Termination criteria for regression tree + + + + 0.01 + False + + + ParameterNumber + classifier.dt.cat + Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split + Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split. + + + 10 + False + + + ParameterNumber + classifier.dt.f + K-fold cross-validations + If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds. + + + 10 + False + + + ParameterBoolean + classifier.dt.r + Set Use1seRule flag to false + If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate. + True + True + + + ParameterBoolean + classifier.dt.t + Set TruncatePrunedTree flag to false + If true, then pruned branches are physically removed from the tree. + True + True + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-gbt.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-gbt.xml new file mode 100644 index 000000000000..456efc81582d --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-gbt.xml @@ -0,0 +1,174 @@ + + TrainImagesClassifier-gbt + otbcli_TrainImagesClassifier + TrainImagesClassifier (gbt) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + gbt + + + 0 + False + + + ParameterNumber + classifier.gbt.w + Number of boosting algorithm iterations + Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes. + + + 200 + False + + + ParameterNumber + classifier.gbt.s + Regularization parameter + Regularization parameter. + + + 0.01 + False + + + ParameterNumber + classifier.gbt.p + Portion of the whole training set used for each algorithm iteration + Portion of the whole training set used for each algorithm iteration. The subset is generated randomly. + + + 0.8 + False + + + ParameterNumber + classifier.gbt.max + Maximum depth of the tree + The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned. + + + 3 + False + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-knn.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-knn.xml new file mode 100644 index 000000000000..0b6ec7b41889 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-knn.xml @@ -0,0 +1,144 @@ + + TrainImagesClassifier-knn + otbcli_TrainImagesClassifier + TrainImagesClassifier (knn) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + knn + + + 0 + False + + + ParameterNumber + classifier.knn.k + Number of Neighbors + The number of neighbors to use. + + + 32 + False + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-rf.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-rf.xml new file mode 100644 index 000000000000..437405a26e79 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainImagesClassifier-rf.xml @@ -0,0 +1,204 @@ + + TrainImagesClassifier-rf + otbcli_TrainImagesClassifier + TrainImagesClassifier (rf) + Learning + Train a classifier from multiple pairs of images and training vector data. + + ParameterMultipleInput + io.il + Input Image List + A list of input images. + + False + + + ParameterMultipleInput + io.vd + Input Vector Data List + A list of vector data to select the training samples. + + False + + + ParameterFile + io.imstat + Input XML image statistics file + Input XML file containing the mean and the standard deviation of the input images. + + True + + + OutputFile + io.confmatout + Output confusion matrix + Output file containing the confusion matrix (.csv format). + + + OutputFile + io.out + Output model + Output file containing the model estimated (.txt format). + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + + ParameterNumber + sample.mt + Maximum training sample size per class + Maximum size per class (in pixels) of the training sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available training sample list per class will be equal to the surface area of the smallest class multiplied by the training sample ratio. + + + 1000 + False + + + ParameterNumber + sample.mv + Maximum validation sample size per class + Maximum size per class (in pixels) of the validation sample list (default = 1000) (no limit = -1). If equal to -1, then the maximal size of the available validation sample list per class will be equal to the surface area of the smallest class multiplied by the validation sample ratio. + + + 1000 + False + + + ParameterNumber + sample.bm + Bound sample number by minimum + Bound the number of samples for each class by the number of available samples by the smaller class. Proportions between training and validation are respected. Default is true (=1). + + + 1 + False + + + ParameterBoolean + sample.edg + On edge pixel inclusion + Takes pixels on polygon edge into consideration when building training and validation samples. + True + True + + + ParameterNumber + sample.vtr + Training and validation sample ratio + Ratio between training and validation samples (0.0 = all training, 1.0 = all validation) (default = 0.5). + + + 0.5 + False + + + ParameterString + sample.vfn + Name of the discrimination field + Name of the field used to discriminate class labels in the input vector data files. + Class + + False + + + + ParameterSelection + classifier + Classifier to use for the training + Choice of the classifier to use for the training. + + + rf + + + 0 + False + + + ParameterNumber + classifier.rf.max + Maximum depth of the tree + The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods. + + + 5 + False + + + ParameterNumber + classifier.rf.min + Minimum number of samples in each node + If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent. + + + 10 + False + + + ParameterNumber + classifier.rf.ra + Termination Criteria for regression tree + If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split. + + + 0 + False + + + ParameterNumber + classifier.rf.cat + Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split + Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split. + + + 10 + False + + + ParameterNumber + classifier.rf.var + Size of the randomly selected subset of features at each tree node + The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features. + + + 0 + False + + + ParameterNumber + classifier.rf.nbtrees + Maximum number of trees in the forest + The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly. + + + 100 + False + + + ParameterNumber + classifier.rf.acc + Sufficient accuracy (OOB error) + Sufficient accuracy (OOB error). + + + 0.01 + False + + + ParameterNumber + rand + set user defined seed + Set specific seed. with integer value. + + + 0 + True + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/TrainOGRLayersClassifier.xml b/python/plugins/processing/algs/otb/description/5.4.0/TrainOGRLayersClassifier.xml new file mode 100644 index 000000000000..78e135a40aa8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/TrainOGRLayersClassifier.xml @@ -0,0 +1,48 @@ + + TrainOGRLayersClassifier + otbcli_TrainOGRLayersClassifier + TrainOGRLayersClassifier + Segmentation + Train a SVM classifier based on labeled geometries and a list of features to consider. + + ParameterVector + inshp + Name of the input shapefile + Name of the input shapefile + + False + + + ParameterFile + instats + XML file containing mean and variance of each feature. + XML file containing mean and variance of each feature. + + False + + + OutputFile + outsvm + Output model filename. + Output model filename. + + + ParameterString + feat + List of features to consider for classification. + List of features to consider for classification. + + + False + + + ParameterString + cfield + Field containing the class id for supervision + Field containing the class id for supervision. Only geometries with this field available will be taken into account. + class + + False + + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/VectorDataExtractROI.xml b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataExtractROI.xml new file mode 100644 index 000000000000..8efb7cca5dee --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataExtractROI.xml @@ -0,0 +1,40 @@ + + VectorDataExtractROI + otbcli_VectorDataExtractROI + VectorData Extract ROI + Vector Data Manipulation + Perform an extract ROI on the input vector data according to the input image extent + + ParameterVector + io.vd + Input Vector data + Input vector data + + False + + + ParameterRaster + io.in + Support image + Support image that specifies the extracted region + False + + + OutputVector + io.out + Output Vector data + Output extracted vector data + + + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-image.xml b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-image.xml new file mode 100644 index 000000000000..8a3948907e85 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-image.xml @@ -0,0 +1,59 @@ + + VectorDataReprojection-image + otbcli_VectorDataReprojection + VectorDataReprojection (image) + Vector Data Manipulation + Reproject a vector data using support image projection reference, or a user specified map projection + + + ParameterFile + in.vd + Input vector data + The input vector data to reproject + + False + + + ParameterRaster + in.kwl + Use image keywords list + Optional input image to fill vector data with image kwl. + True + + + OutputFile + out.vd + Output vector data + The reprojected vector data + + + ParameterSelection + out.proj + Output Projection choice + + + + image + + + 0 + False + + + ParameterRaster + out.proj.image.in + Image used to get projection map + Projection map will be found using image metadata + False + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-user.xml b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-user.xml new file mode 100644 index 000000000000..0392ba55b214 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataReprojection-user.xml @@ -0,0 +1,97 @@ + + VectorDataReprojection-user + otbcli_VectorDataReprojection + VectorDataReprojection (user) + Vector Data Manipulation + Reproject a vector data using support image projection reference, or a user specified map projection + + + ParameterFile + in.vd + Input vector data + The input vector data to reproject + + False + + + ParameterRaster + in.kwl + Use image keywords list + Optional input image to fill vector data with image kwl. + True + + + OutputFile + out.vd + Output vector data + The reprojected vector data + + + ParameterSelection + out.proj + Output Projection choice + + + + user + + + 0 + False + + + ParameterSelection + out.proj.user.map + Output Cartographic Map Projection + Parameters of the output map projection to be used. + + + utm + lambert2 + lambert93 + wgs + epsg + + + 0 + False + + + ParameterNumber + out.proj.user.map.utm.zone + Zone number + The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere) + + + 31 + False + + + ParameterBoolean + out.proj.user.map.utm.northhem + Northern Hemisphere + The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere. + True + True + + + ParameterNumber + out.proj.user.map.epsg.code + EPSG Code + See www.spatialreference.org to find which EPSG code is associated to your projection + + + 4326 + False + + + ParameterNumber + elev.default + Default elevation + This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value. + + + 0 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/VectorDataTransform.xml b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataTransform.xml new file mode 100644 index 000000000000..60f107e94a54 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/VectorDataTransform.xml @@ -0,0 +1,90 @@ + + VectorDataTransform + otbcli_VectorDataTransform + Vector Data Transformation + Vector Data Manipulation + Apply a transform to each vertex of the input VectorData + + ParameterVector + vd + Input Vector data + Input vector data to transform + + False + + + OutputVector + out + Output Vector data + Output transformed vector data + + + + + ParameterRaster + in + Support image + Image needed as a support to the vector data + False + + + ParameterNumber + transform.tx + Translation X + Translation in the X direction (in pixels) + + + 0 + False + + + ParameterNumber + transform.ty + Translation Y + Translation in the Y direction (in pixels) + + + 0 + False + + + ParameterNumber + transform.ro + Rotation Angle + Angle of the rotation to apply in degrees + + + 0 + False + + + ParameterNumber + transform.centerx + Center X + X coordinate of the rotation center (in physical units) + + + 0 + False + + + ParameterNumber + transform.centery + Center Y + Y coordinate of the rotation center (in physical units) + + + 0 + False + + + ParameterNumber + transform.scale + Scale + The scale to apply + + + 1 + False + + diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BandMath.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BandMath.html new file mode 100644 index 000000000000..c6c9657d6e99 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BandMath.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                      BandMath

                                                                                                                                                                                      Brief Description

                                                                                                                                                                                      Perform a mathematical operation on monoband images

                                                                                                                                                                                      Tags

                                                                                                                                                                                      Util

                                                                                                                                                                                      Long Description

                                                                                                                                                                                      This application performs a mathematical operation on monoband images. Mathematical formula interpretation is done via MuParser libraries http://muparser.sourceforge.net/.For MuParser version prior to v2 use 'and' and 'or' logical operators, and ternary operator 'if(; ; )'.For MuParser version superior to 2.0 uses '&&' and '||' logical operators, and C++ like ternary if-then-else operator.

                                                                                                                                                                                      Parameters

                                                                                                                                                                                      • [param] -il <string> Image list to perform computation on.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                      • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                      • [param] -exp <string> The mathematical expression to apply. +Use im1b1 for the first band, im1b2 for the second one.... Mandatory: True. Default Value: ""
                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                      Limitations

                                                                                                                                                                                      None

                                                                                                                                                                                      Authors

                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                      See Also

                                                                                                                                                                                      Example of use

                                                                                                                                                                                      • il: verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif

                                                                                                                                                                                      • out: apTvUtBandMathOutput.tif

                                                                                                                                                                                      • exp: "cos(im1b1)+im2b1*im3b1-im3b2+ndvi(im3b3, im3b4)"

                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-closing.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-closing.html new file mode 100644 index 000000000000..97a2b19d7065 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-closing.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                      BinaryMorphologicalOperation

                                                                                                                                                                                      Brief Description

                                                                                                                                                                                      Performs morphological operations on an input image channel

                                                                                                                                                                                      Tags

                                                                                                                                                                                      MorphologicalOperations,Feature Extraction

                                                                                                                                                                                      Long Description

                                                                                                                                                                                      This application performs binary morphological operations on a mono band image

                                                                                                                                                                                      Parameters

                                                                                                                                                                                      • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                      • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                      • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                      • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                        • [group] -ball
                                                                                                                                                                                          • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                          • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                        • [group] -cross
                                                                                                                                                                                          [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                          • [group] -dilate
                                                                                                                                                                                            • [param] -filter.dilate.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                            • [param] -filter.dilate.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                          • [group] -erode
                                                                                                                                                                                            • [param] -filter.erode.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                            • [param] -filter.erode.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                          • [group] -opening
                                                                                                                                                                                            • [param] -filter.opening.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                            • [param] -filter.opening.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                          • [group] -closing
                                                                                                                                                                                            • [param] -filter.closing.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"

                                                                                                                                                                                        Limitations

                                                                                                                                                                                        None

                                                                                                                                                                                        Authors

                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                        See Also

                                                                                                                                                                                        itkBinaryDilateImageFilter, itkBinaryErodeImageFilter, itkBinaryMorphologicalOpeningImageFilter and itkBinaryMorphologicalClosingImageFilter classes

                                                                                                                                                                                        Example of use

                                                                                                                                                                                        • in: qb_RoadExtract.tif

                                                                                                                                                                                        • out: opened.tif

                                                                                                                                                                                        • channel: 1

                                                                                                                                                                                        • structype.ball.xradius: 5

                                                                                                                                                                                        • structype.ball.yradius: 5

                                                                                                                                                                                        • filter: erode

                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-dilate.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-dilate.html new file mode 100644 index 000000000000..97a2b19d7065 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-dilate.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                        BinaryMorphologicalOperation

                                                                                                                                                                                        Brief Description

                                                                                                                                                                                        Performs morphological operations on an input image channel

                                                                                                                                                                                        Tags

                                                                                                                                                                                        MorphologicalOperations,Feature Extraction

                                                                                                                                                                                        Long Description

                                                                                                                                                                                        This application performs binary morphological operations on a mono band image

                                                                                                                                                                                        Parameters

                                                                                                                                                                                        • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                        • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                        • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                        • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                          • [group] -ball
                                                                                                                                                                                            • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                            • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                          • [group] -cross
                                                                                                                                                                                            [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                            • [group] -dilate
                                                                                                                                                                                              • [param] -filter.dilate.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                              • [param] -filter.dilate.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                            • [group] -erode
                                                                                                                                                                                              • [param] -filter.erode.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                              • [param] -filter.erode.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                            • [group] -opening
                                                                                                                                                                                              • [param] -filter.opening.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                              • [param] -filter.opening.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                            • [group] -closing
                                                                                                                                                                                              • [param] -filter.closing.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"

                                                                                                                                                                                          Limitations

                                                                                                                                                                                          None

                                                                                                                                                                                          Authors

                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                          See Also

                                                                                                                                                                                          itkBinaryDilateImageFilter, itkBinaryErodeImageFilter, itkBinaryMorphologicalOpeningImageFilter and itkBinaryMorphologicalClosingImageFilter classes

                                                                                                                                                                                          Example of use

                                                                                                                                                                                          • in: qb_RoadExtract.tif

                                                                                                                                                                                          • out: opened.tif

                                                                                                                                                                                          • channel: 1

                                                                                                                                                                                          • structype.ball.xradius: 5

                                                                                                                                                                                          • structype.ball.yradius: 5

                                                                                                                                                                                          • filter: erode

                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-erode.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-erode.html new file mode 100644 index 000000000000..97a2b19d7065 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-erode.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                          BinaryMorphologicalOperation

                                                                                                                                                                                          Brief Description

                                                                                                                                                                                          Performs morphological operations on an input image channel

                                                                                                                                                                                          Tags

                                                                                                                                                                                          MorphologicalOperations,Feature Extraction

                                                                                                                                                                                          Long Description

                                                                                                                                                                                          This application performs binary morphological operations on a mono band image

                                                                                                                                                                                          Parameters

                                                                                                                                                                                          • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                          • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                          • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                          • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                          • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                            • [group] -ball
                                                                                                                                                                                              • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                              • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                            • [group] -cross
                                                                                                                                                                                              [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                              • [group] -dilate
                                                                                                                                                                                                • [param] -filter.dilate.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                • [param] -filter.dilate.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                              • [group] -erode
                                                                                                                                                                                                • [param] -filter.erode.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                • [param] -filter.erode.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                              • [group] -opening
                                                                                                                                                                                                • [param] -filter.opening.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                • [param] -filter.opening.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                              • [group] -closing
                                                                                                                                                                                                • [param] -filter.closing.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"

                                                                                                                                                                                            Limitations

                                                                                                                                                                                            None

                                                                                                                                                                                            Authors

                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                            See Also

                                                                                                                                                                                            itkBinaryDilateImageFilter, itkBinaryErodeImageFilter, itkBinaryMorphologicalOpeningImageFilter and itkBinaryMorphologicalClosingImageFilter classes

                                                                                                                                                                                            Example of use

                                                                                                                                                                                            • in: qb_RoadExtract.tif

                                                                                                                                                                                            • out: opened.tif

                                                                                                                                                                                            • channel: 1

                                                                                                                                                                                            • structype.ball.xradius: 5

                                                                                                                                                                                            • structype.ball.yradius: 5

                                                                                                                                                                                            • filter: erode

                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-opening.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-opening.html new file mode 100644 index 000000000000..97a2b19d7065 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation-opening.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                            BinaryMorphologicalOperation

                                                                                                                                                                                            Brief Description

                                                                                                                                                                                            Performs morphological operations on an input image channel

                                                                                                                                                                                            Tags

                                                                                                                                                                                            MorphologicalOperations,Feature Extraction

                                                                                                                                                                                            Long Description

                                                                                                                                                                                            This application performs binary morphological operations on a mono band image

                                                                                                                                                                                            Parameters

                                                                                                                                                                                            • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                            • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                            • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                            • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                              • [group] -ball
                                                                                                                                                                                                • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                              • [group] -cross
                                                                                                                                                                                                [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                • [group] -dilate
                                                                                                                                                                                                  • [param] -filter.dilate.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                  • [param] -filter.dilate.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [group] -erode
                                                                                                                                                                                                  • [param] -filter.erode.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                  • [param] -filter.erode.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [group] -opening
                                                                                                                                                                                                  • [param] -filter.opening.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                  • [param] -filter.opening.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [group] -closing
                                                                                                                                                                                                  • [param] -filter.closing.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"

                                                                                                                                                                                              Limitations

                                                                                                                                                                                              None

                                                                                                                                                                                              Authors

                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                              See Also

                                                                                                                                                                                              itkBinaryDilateImageFilter, itkBinaryErodeImageFilter, itkBinaryMorphologicalOpeningImageFilter and itkBinaryMorphologicalClosingImageFilter classes

                                                                                                                                                                                              Example of use

                                                                                                                                                                                              • in: qb_RoadExtract.tif

                                                                                                                                                                                              • out: opened.tif

                                                                                                                                                                                              • channel: 1

                                                                                                                                                                                              • structype.ball.xradius: 5

                                                                                                                                                                                              • structype.ball.yradius: 5

                                                                                                                                                                                              • filter: erode

                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation.html new file mode 100644 index 000000000000..97a2b19d7065 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BinaryMorphologicalOperation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                              BinaryMorphologicalOperation

                                                                                                                                                                                              Brief Description

                                                                                                                                                                                              Performs morphological operations on an input image channel

                                                                                                                                                                                              Tags

                                                                                                                                                                                              MorphologicalOperations,Feature Extraction

                                                                                                                                                                                              Long Description

                                                                                                                                                                                              This application performs binary morphological operations on a mono band image

                                                                                                                                                                                              Parameters

                                                                                                                                                                                              • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                              • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                              • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                              • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                                • [group] -ball
                                                                                                                                                                                                  • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                  • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                • [group] -cross
                                                                                                                                                                                                  [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                  • [group] -dilate
                                                                                                                                                                                                    • [param] -filter.dilate.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                    • [param] -filter.dilate.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                  • [group] -erode
                                                                                                                                                                                                    • [param] -filter.erode.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                    • [param] -filter.erode.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                  • [group] -opening
                                                                                                                                                                                                    • [param] -filter.opening.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                    • [param] -filter.opening.backval <float> The Background Value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                  • [group] -closing
                                                                                                                                                                                                    • [param] -filter.closing.foreval <float> The Foreground Value. Mandatory: True. Default Value: "1"

                                                                                                                                                                                                Limitations

                                                                                                                                                                                                None

                                                                                                                                                                                                Authors

                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                See Also

                                                                                                                                                                                                itkBinaryDilateImageFilter, itkBinaryErodeImageFilter, itkBinaryMorphologicalOpeningImageFilter and itkBinaryMorphologicalClosingImageFilter classes

                                                                                                                                                                                                Example of use

                                                                                                                                                                                                • in: qb_RoadExtract.tif

                                                                                                                                                                                                • out: opened.tif

                                                                                                                                                                                                • channel: 1

                                                                                                                                                                                                • structype.ball.xradius: 5

                                                                                                                                                                                                • structype.ball.yradius: 5

                                                                                                                                                                                                • filter: erode

                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BlockMatching.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BlockMatching.html new file mode 100644 index 000000000000..4d5caf2e62c5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BlockMatching.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                BlockMatching

                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                Performs block-matching to estimate pixel-wise disparities between two images

                                                                                                                                                                                                Tags

                                                                                                                                                                                                Stereo

                                                                                                                                                                                                Long Description

                                                                                                                                                                                                This application allows one to performs block-matching to estimate pixel-wise disparities between two images. One must chose block-matching method and input masks (related to the left and right input image) of pixels for which the disparity should be investigated. Additionally, two criteria can be optionally used to disable disparity investigation for some pixel: a no-data value, and a threshold on the local variance. This allows one to speed-up computation by avoiding to investigate disparities that will not be reliable anyway. For efficiency reasons, if the optimal metric values image is desired, it will be concatenated to the output image (which will then have three bands : horizontal disparity, vertical disparity and metric value). One can split these images afterward.

                                                                                                                                                                                                Parameters

                                                                                                                                                                                                • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [param] -mask <string> This group of parameters allows determining the masking parameters to prevent disparities estimation for some pixels of the left image. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [param] -bm <string> This group of parameters allow tuning the block-matching behaviour. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                Limitations

                                                                                                                                                                                                None

                                                                                                                                                                                                Authors

                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                See Also

                                                                                                                                                                                                otbStereoRectificationGridGenerator

                                                                                                                                                                                                Example of use

                                                                                                                                                                                                • io.inleft: StereoFixed.png

                                                                                                                                                                                                • io.inright: StereoMoving.png

                                                                                                                                                                                                • bm.minhd: -10

                                                                                                                                                                                                • bm.maxhd: 10

                                                                                                                                                                                                • mask.variancet: 10

                                                                                                                                                                                                • io.out: MyDisparity.tif

                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/BundleToPerfectSensor.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/BundleToPerfectSensor.html new file mode 100644 index 000000000000..8dcdd8566369 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/BundleToPerfectSensor.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                BundleToPerfectSensor

                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                Perform P+XS pansharpening

                                                                                                                                                                                                Tags

                                                                                                                                                                                                Geometry,Pansharpening

                                                                                                                                                                                                Long Description

                                                                                                                                                                                                This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion ("default mode"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.

                                                                                                                                                                                                Parameters

                                                                                                                                                                                                • [param] -inp <string> Input panchromatic image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                • [param] -inxs <string> Input XS image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                • [param] -lms <float> Spacing of the deformation field. Default is 10 times the PAN image spacing.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                • [choice] -mode Superimposition mode default,phr. Mandatory: True. Default Value: "default"
                                                                                                                                                                                                  • [group] -default
                                                                                                                                                                                                    • [param] -elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                  • [group] -phr

                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                  None

                                                                                                                                                                                                  Authors

                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                  See Also

                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                  • inp: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                  • inxs: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                  • out: BundleToPerfectSensor.png uchar

                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ClassificationMapRegularization.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ClassificationMapRegularization.html new file mode 100644 index 000000000000..a974324ba3f4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ClassificationMapRegularization.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                  ClassificationMapRegularization

                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                  Filters the input labeled image using Majority Voting in a ball shaped neighbordhood.

                                                                                                                                                                                                  Tags

                                                                                                                                                                                                  Learning,Image Analysis

                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                  This application filters the input labeled image (with a maximal class label = 65535) using Majority Voting in a ball shaped neighbordhood. Majority Voting takes the more representative value of all the pixels identified by the ball shaped structuring element and then sets the center pixel to this majority label value. + -NoData is the label of the NOT classified pixels in the input image. These input pixels keep their NoData label in the output image. + -Pixels with more than 1 majority class are marked as Undecided if the parameter 'ip.suvbool == true', or keep their Original labels otherwise.

                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                  • [param] -io <string> This group of parameters allows setting input and output images for classification map regularization by Majority Voting.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                  • [param] -ip <string> This group allows setting parameters for classification map regularization by Majority Voting.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                  The input image must be a single band labeled image (with a maximal class label = 65535). The structuring element radius must have a minimum value equal to 1 pixel. Please note that the Undecided value must be different from existing labels in the input labeled image.

                                                                                                                                                                                                  Authors

                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                  See Also

                                                                                                                                                                                                  Documentation of the ClassificationMapRegularization application.

                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                  • io.in: clLabeledImageQB123_1.tif

                                                                                                                                                                                                  • io.out: clLabeledImageQB123_1_CMR_r2_nodl_10_undl_7.tif

                                                                                                                                                                                                  • ip.radius: 2

                                                                                                                                                                                                  • ip.suvbool: true

                                                                                                                                                                                                  • ip.nodatalabel: 10

                                                                                                                                                                                                  • ip.undecidedlabel: 7

                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-continuous.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-continuous.html new file mode 100644 index 000000000000..6ce8d15474ab --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-continuous.html @@ -0,0 +1,13 @@ + + +

                                                                                                                                                                                                  ColorMapping

                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                  Maps an input label image to 8-bits RGB using look-up tables.

                                                                                                                                                                                                  Tags

                                                                                                                                                                                                  Utilities,Image Manipulation,Image MetaData,Learning

                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                  This application allows one to map a label image to a 8-bits RGB image (in both ways) using different methods. + -The custom method allows one to use a custom look-up table. The look-up table is loaded from a text file where each line describes an entry. The typical use of this method is to colorise a classification map. + -The continuous method allows mapping a range of values in a scalar input image to a colored image using continuous look-up table, in order to enhance image interpretation. Several look-up tables can been chosen with different color ranges. +-The optimal method computes an optimal look-up table. When processing a segmentation label image (label to color), the color difference between adjacent segmented regions is maximized. When processing an unknown color image (color to label), all the present colors are mapped to a continuous label list. + - The support image method uses a color support image to associate an average color to each region.

                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                  • [param] -in <string> Input image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                  • [param] -out <string> Output image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                  • [choice] -op Selection of the operation to execute (default is : label to color). labeltocolor,colortolabel. Mandatory: True. Default Value: "labeltocolor"
                                                                                                                                                                                                    • [group] -labeltocolor
                                                                                                                                                                                                      • [group] -colortolabel
                                                                                                                                                                                                        • [param] -op.colortolabel.notfound <int32> Label to use for unknown colors.. Mandatory: False. Default Value: "404"
                                                                                                                                                                                                      [choice] -method Selection of color mapping methods and their parameters. custom,continuous,optimal,image. Mandatory: True. Default Value: "custom"
                                                                                                                                                                                                      • [group] -custom
                                                                                                                                                                                                        • [param] -method.custom.lut <string> An ASCII file containing the look-up table +with one color per line +(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0) +Lines beginning with a # are ignored. Mandatory: True. Default Value: ""
                                                                                                                                                                                                      • [group] -continuous
                                                                                                                                                                                                        • [param] -method.continuous.lut <string> Available look-up tables.. Mandatory: True. Default Value: "red"
                                                                                                                                                                                                        • [param] -method.continuous.min <float> Set the lower input value of the mapping range.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                        • [param] -method.continuous.max <float> Set the higher input value of the mapping range.. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                      • [group] -optimal
                                                                                                                                                                                                        • [param] -method.optimal.background <int32> Value of the background label. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                      • [group] -image
                                                                                                                                                                                                        • [param] -method.image.in <string> Support image filename. For each label, the LUT is calculated from the mean pixel value in the support image, over the corresponding labeled areas. First of all, the support image is normalized with extrema rejection. Mandatory: True. Default Value: ""
                                                                                                                                                                                                        • [param] -method.image.nodatavalue <float> NoData value for each channel of the support image, which will not be handled in the LUT estimation. If NOT checked, ALL the pixel values of the support image will be handled in the LUT estimation.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                        • [param] -method.image.low <int32> lower quantile for image normalization. Mandatory: False. Default Value: "2"
                                                                                                                                                                                                        • [param] -method.image.up <int32> upper quantile for image normalization. Mandatory: False. Default Value: "2"

                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                    The segmentation optimal method does not support streaming, and thus large images. The operation color to label is not implemented for the methods continuous LUT and support image LUT. + ColorMapping using support image is not threaded.

                                                                                                                                                                                                    Authors

                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                    See Also

                                                                                                                                                                                                    ImageSVMClassifier

                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                    • in: ROI_QB_MUL_1_SVN_CLASS_MULTI.png

                                                                                                                                                                                                    • method: custom

                                                                                                                                                                                                    • method.custom.lut: ROI_QB_MUL_1_SVN_CLASS_MULTI_PNG_ColorTable.txt

                                                                                                                                                                                                    • out: Colorized_ROI_QB_MUL_1_SVN_CLASS_MULTI.tif

                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-custom.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-custom.html new file mode 100644 index 000000000000..6ce8d15474ab --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-custom.html @@ -0,0 +1,13 @@ + + +

                                                                                                                                                                                                    ColorMapping

                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                    Maps an input label image to 8-bits RGB using look-up tables.

                                                                                                                                                                                                    Tags

                                                                                                                                                                                                    Utilities,Image Manipulation,Image MetaData,Learning

                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                    This application allows one to map a label image to a 8-bits RGB image (in both ways) using different methods. + -The custom method allows one to use a custom look-up table. The look-up table is loaded from a text file where each line describes an entry. The typical use of this method is to colorise a classification map. + -The continuous method allows mapping a range of values in a scalar input image to a colored image using continuous look-up table, in order to enhance image interpretation. Several look-up tables can been chosen with different color ranges. +-The optimal method computes an optimal look-up table. When processing a segmentation label image (label to color), the color difference between adjacent segmented regions is maximized. When processing an unknown color image (color to label), all the present colors are mapped to a continuous label list. + - The support image method uses a color support image to associate an average color to each region.

                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                    • [param] -in <string> Input image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                    • [param] -out <string> Output image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                    • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                    • [choice] -op Selection of the operation to execute (default is : label to color). labeltocolor,colortolabel. Mandatory: True. Default Value: "labeltocolor"
                                                                                                                                                                                                      • [group] -labeltocolor
                                                                                                                                                                                                        • [group] -colortolabel
                                                                                                                                                                                                          • [param] -op.colortolabel.notfound <int32> Label to use for unknown colors.. Mandatory: False. Default Value: "404"
                                                                                                                                                                                                        [choice] -method Selection of color mapping methods and their parameters. custom,continuous,optimal,image. Mandatory: True. Default Value: "custom"
                                                                                                                                                                                                        • [group] -custom
                                                                                                                                                                                                          • [param] -method.custom.lut <string> An ASCII file containing the look-up table +with one color per line +(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0) +Lines beginning with a # are ignored. Mandatory: True. Default Value: ""
                                                                                                                                                                                                        • [group] -continuous
                                                                                                                                                                                                          • [param] -method.continuous.lut <string> Available look-up tables.. Mandatory: True. Default Value: "red"
                                                                                                                                                                                                          • [param] -method.continuous.min <float> Set the lower input value of the mapping range.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                          • [param] -method.continuous.max <float> Set the higher input value of the mapping range.. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                        • [group] -optimal
                                                                                                                                                                                                          • [param] -method.optimal.background <int32> Value of the background label. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                        • [group] -image
                                                                                                                                                                                                          • [param] -method.image.in <string> Support image filename. For each label, the LUT is calculated from the mean pixel value in the support image, over the corresponding labeled areas. First of all, the support image is normalized with extrema rejection. Mandatory: True. Default Value: ""
                                                                                                                                                                                                          • [param] -method.image.nodatavalue <float> NoData value for each channel of the support image, which will not be handled in the LUT estimation. If NOT checked, ALL the pixel values of the support image will be handled in the LUT estimation.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                          • [param] -method.image.low <int32> lower quantile for image normalization. Mandatory: False. Default Value: "2"
                                                                                                                                                                                                          • [param] -method.image.up <int32> upper quantile for image normalization. Mandatory: False. Default Value: "2"

                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                      The segmentation optimal method does not support streaming, and thus large images. The operation color to label is not implemented for the methods continuous LUT and support image LUT. + ColorMapping using support image is not threaded.

                                                                                                                                                                                                      Authors

                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                      See Also

                                                                                                                                                                                                      ImageSVMClassifier

                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                      • in: ROI_QB_MUL_1_SVN_CLASS_MULTI.png

                                                                                                                                                                                                      • method: custom

                                                                                                                                                                                                      • method.custom.lut: ROI_QB_MUL_1_SVN_CLASS_MULTI_PNG_ColorTable.txt

                                                                                                                                                                                                      • out: Colorized_ROI_QB_MUL_1_SVN_CLASS_MULTI.tif

                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-image.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-image.html new file mode 100644 index 000000000000..6ce8d15474ab --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-image.html @@ -0,0 +1,13 @@ + + +

                                                                                                                                                                                                      ColorMapping

                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                      Maps an input label image to 8-bits RGB using look-up tables.

                                                                                                                                                                                                      Tags

                                                                                                                                                                                                      Utilities,Image Manipulation,Image MetaData,Learning

                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                      This application allows one to map a label image to a 8-bits RGB image (in both ways) using different methods. + -The custom method allows one to use a custom look-up table. The look-up table is loaded from a text file where each line describes an entry. The typical use of this method is to colorise a classification map. + -The continuous method allows mapping a range of values in a scalar input image to a colored image using continuous look-up table, in order to enhance image interpretation. Several look-up tables can been chosen with different color ranges. +-The optimal method computes an optimal look-up table. When processing a segmentation label image (label to color), the color difference between adjacent segmented regions is maximized. When processing an unknown color image (color to label), all the present colors are mapped to a continuous label list. + - The support image method uses a color support image to associate an average color to each region.

                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                      • [param] -in <string> Input image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                      • [param] -out <string> Output image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                      • [choice] -op Selection of the operation to execute (default is : label to color). labeltocolor,colortolabel. Mandatory: True. Default Value: "labeltocolor"
                                                                                                                                                                                                        • [group] -labeltocolor
                                                                                                                                                                                                          • [group] -colortolabel
                                                                                                                                                                                                            • [param] -op.colortolabel.notfound <int32> Label to use for unknown colors.. Mandatory: False. Default Value: "404"
                                                                                                                                                                                                          [choice] -method Selection of color mapping methods and their parameters. custom,continuous,optimal,image. Mandatory: True. Default Value: "custom"
                                                                                                                                                                                                          • [group] -custom
                                                                                                                                                                                                            • [param] -method.custom.lut <string> An ASCII file containing the look-up table +with one color per line +(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0) +Lines beginning with a # are ignored. Mandatory: True. Default Value: ""
                                                                                                                                                                                                          • [group] -continuous
                                                                                                                                                                                                            • [param] -method.continuous.lut <string> Available look-up tables.. Mandatory: True. Default Value: "red"
                                                                                                                                                                                                            • [param] -method.continuous.min <float> Set the lower input value of the mapping range.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                            • [param] -method.continuous.max <float> Set the higher input value of the mapping range.. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                          • [group] -optimal
                                                                                                                                                                                                            • [param] -method.optimal.background <int32> Value of the background label. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                          • [group] -image
                                                                                                                                                                                                            • [param] -method.image.in <string> Support image filename. For each label, the LUT is calculated from the mean pixel value in the support image, over the corresponding labeled areas. First of all, the support image is normalized with extrema rejection. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -method.image.nodatavalue <float> NoData value for each channel of the support image, which will not be handled in the LUT estimation. If NOT checked, ALL the pixel values of the support image will be handled in the LUT estimation.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                            • [param] -method.image.low <int32> lower quantile for image normalization. Mandatory: False. Default Value: "2"
                                                                                                                                                                                                            • [param] -method.image.up <int32> upper quantile for image normalization. Mandatory: False. Default Value: "2"

                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                        The segmentation optimal method does not support streaming, and thus large images. The operation color to label is not implemented for the methods continuous LUT and support image LUT. + ColorMapping using support image is not threaded.

                                                                                                                                                                                                        Authors

                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                        See Also

                                                                                                                                                                                                        ImageSVMClassifier

                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                        • in: ROI_QB_MUL_1_SVN_CLASS_MULTI.png

                                                                                                                                                                                                        • method: custom

                                                                                                                                                                                                        • method.custom.lut: ROI_QB_MUL_1_SVN_CLASS_MULTI_PNG_ColorTable.txt

                                                                                                                                                                                                        • out: Colorized_ROI_QB_MUL_1_SVN_CLASS_MULTI.tif

                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-optimal.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-optimal.html new file mode 100644 index 000000000000..6ce8d15474ab --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping-optimal.html @@ -0,0 +1,13 @@ + + +

                                                                                                                                                                                                        ColorMapping

                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                        Maps an input label image to 8-bits RGB using look-up tables.

                                                                                                                                                                                                        Tags

                                                                                                                                                                                                        Utilities,Image Manipulation,Image MetaData,Learning

                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                        This application allows one to map a label image to a 8-bits RGB image (in both ways) using different methods. + -The custom method allows one to use a custom look-up table. The look-up table is loaded from a text file where each line describes an entry. The typical use of this method is to colorise a classification map. + -The continuous method allows mapping a range of values in a scalar input image to a colored image using continuous look-up table, in order to enhance image interpretation. Several look-up tables can been chosen with different color ranges. +-The optimal method computes an optimal look-up table. When processing a segmentation label image (label to color), the color difference between adjacent segmented regions is maximized. When processing an unknown color image (color to label), all the present colors are mapped to a continuous label list. + - The support image method uses a color support image to associate an average color to each region.

                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                        • [param] -in <string> Input image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                        • [param] -out <string> Output image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                        • [choice] -op Selection of the operation to execute (default is : label to color). labeltocolor,colortolabel. Mandatory: True. Default Value: "labeltocolor"
                                                                                                                                                                                                          • [group] -labeltocolor
                                                                                                                                                                                                            • [group] -colortolabel
                                                                                                                                                                                                              • [param] -op.colortolabel.notfound <int32> Label to use for unknown colors.. Mandatory: False. Default Value: "404"
                                                                                                                                                                                                            [choice] -method Selection of color mapping methods and their parameters. custom,continuous,optimal,image. Mandatory: True. Default Value: "custom"
                                                                                                                                                                                                            • [group] -custom
                                                                                                                                                                                                              • [param] -method.custom.lut <string> An ASCII file containing the look-up table +with one color per line +(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0) +Lines beginning with a # are ignored. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [group] -continuous
                                                                                                                                                                                                              • [param] -method.continuous.lut <string> Available look-up tables.. Mandatory: True. Default Value: "red"
                                                                                                                                                                                                              • [param] -method.continuous.min <float> Set the lower input value of the mapping range.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [param] -method.continuous.max <float> Set the higher input value of the mapping range.. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                            • [group] -optimal
                                                                                                                                                                                                              • [param] -method.optimal.background <int32> Value of the background label. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                            • [group] -image
                                                                                                                                                                                                              • [param] -method.image.in <string> Support image filename. For each label, the LUT is calculated from the mean pixel value in the support image, over the corresponding labeled areas. First of all, the support image is normalized with extrema rejection. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -method.image.nodatavalue <float> NoData value for each channel of the support image, which will not be handled in the LUT estimation. If NOT checked, ALL the pixel values of the support image will be handled in the LUT estimation.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                              • [param] -method.image.low <int32> lower quantile for image normalization. Mandatory: False. Default Value: "2"
                                                                                                                                                                                                              • [param] -method.image.up <int32> upper quantile for image normalization. Mandatory: False. Default Value: "2"

                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                          The segmentation optimal method does not support streaming, and thus large images. The operation color to label is not implemented for the methods continuous LUT and support image LUT. + ColorMapping using support image is not threaded.

                                                                                                                                                                                                          Authors

                                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                                          See Also

                                                                                                                                                                                                          ImageSVMClassifier

                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                          • in: ROI_QB_MUL_1_SVN_CLASS_MULTI.png

                                                                                                                                                                                                          • method: custom

                                                                                                                                                                                                          • method.custom.lut: ROI_QB_MUL_1_SVN_CLASS_MULTI_PNG_ColorTable.txt

                                                                                                                                                                                                          • out: Colorized_ROI_QB_MUL_1_SVN_CLASS_MULTI.tif

                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping.html new file mode 100644 index 000000000000..6ce8d15474ab --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ColorMapping.html @@ -0,0 +1,13 @@ + + +

                                                                                                                                                                                                          ColorMapping

                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                          Maps an input label image to 8-bits RGB using look-up tables.

                                                                                                                                                                                                          Tags

                                                                                                                                                                                                          Utilities,Image Manipulation,Image MetaData,Learning

                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                          This application allows one to map a label image to a 8-bits RGB image (in both ways) using different methods. + -The custom method allows one to use a custom look-up table. The look-up table is loaded from a text file where each line describes an entry. The typical use of this method is to colorise a classification map. + -The continuous method allows mapping a range of values in a scalar input image to a colored image using continuous look-up table, in order to enhance image interpretation. Several look-up tables can been chosen with different color ranges. +-The optimal method computes an optimal look-up table. When processing a segmentation label image (label to color), the color difference between adjacent segmented regions is maximized. When processing an unknown color image (color to label), all the present colors are mapped to a continuous label list. + - The support image method uses a color support image to associate an average color to each region.

                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                          • [param] -in <string> Input image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                          • [param] -out <string> Output image filename. Mandatory: True. Default Value: ""
                                                                                                                                                                                                          • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                          • [choice] -op Selection of the operation to execute (default is : label to color). labeltocolor,colortolabel. Mandatory: True. Default Value: "labeltocolor"
                                                                                                                                                                                                            • [group] -labeltocolor
                                                                                                                                                                                                              • [group] -colortolabel
                                                                                                                                                                                                                • [param] -op.colortolabel.notfound <int32> Label to use for unknown colors.. Mandatory: False. Default Value: "404"
                                                                                                                                                                                                              [choice] -method Selection of color mapping methods and their parameters. custom,continuous,optimal,image. Mandatory: True. Default Value: "custom"
                                                                                                                                                                                                              • [group] -custom
                                                                                                                                                                                                                • [param] -method.custom.lut <string> An ASCII file containing the look-up table +with one color per line +(for instance the line '1 255 0 0' means that all pixels with label 1 will be replaced by RGB color 255 0 0) +Lines beginning with a # are ignored. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [group] -continuous
                                                                                                                                                                                                                • [param] -method.continuous.lut <string> Available look-up tables.. Mandatory: True. Default Value: "red"
                                                                                                                                                                                                                • [param] -method.continuous.min <float> Set the lower input value of the mapping range.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                • [param] -method.continuous.max <float> Set the higher input value of the mapping range.. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                              • [group] -optimal
                                                                                                                                                                                                                • [param] -method.optimal.background <int32> Value of the background label. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [group] -image
                                                                                                                                                                                                                • [param] -method.image.in <string> Support image filename. For each label, the LUT is calculated from the mean pixel value in the support image, over the corresponding labeled areas. First of all, the support image is normalized with extrema rejection. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                • [param] -method.image.nodatavalue <float> NoData value for each channel of the support image, which will not be handled in the LUT estimation. If NOT checked, ALL the pixel values of the support image will be handled in the LUT estimation.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                • [param] -method.image.low <int32> lower quantile for image normalization. Mandatory: False. Default Value: "2"
                                                                                                                                                                                                                • [param] -method.image.up <int32> upper quantile for image normalization. Mandatory: False. Default Value: "2"

                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                            The segmentation optimal method does not support streaming, and thus large images. The operation color to label is not implemented for the methods continuous LUT and support image LUT. + ColorMapping using support image is not threaded.

                                                                                                                                                                                                            Authors

                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                            See Also

                                                                                                                                                                                                            ImageSVMClassifier

                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                            • in: ROI_QB_MUL_1_SVN_CLASS_MULTI.png

                                                                                                                                                                                                            • method: custom

                                                                                                                                                                                                            • method.custom.lut: ROI_QB_MUL_1_SVN_CLASS_MULTI_PNG_ColorTable.txt

                                                                                                                                                                                                            • out: Colorized_ROI_QB_MUL_1_SVN_CLASS_MULTI.tif

                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/CompareImages.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/CompareImages.html new file mode 100644 index 000000000000..89de722c4732 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/CompareImages.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                            CompareImages

                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                            Estimator between 2 images.

                                                                                                                                                                                                            Tags

                                                                                                                                                                                                            Statistics

                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                            This application computes MSE (Mean Squared Error), MAE (Mean Absolute Error) and PSNR (Peak Signal to Noise Ratio) between the channel of two images (reference and measurement). The user has to set the used channel and can specify a ROI.

                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                            • [param] -ref <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                            • [param] -meas <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                            • [param] -roi <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                            • [param] -mse <float> Mean Squared Error value. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                            • [param] -mae <float> Mean Absolute Error value. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                            • [param] -psnr <float> Peak Signal to Noise Ratio value. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                            None

                                                                                                                                                                                                            Authors

                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                            See Also

                                                                                                                                                                                                            BandMath application, ImageStatistics

                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                            • ref.in: GomaApres.png

                                                                                                                                                                                                            • ref.channel: 1

                                                                                                                                                                                                            • meas.in: GomaAvant.png

                                                                                                                                                                                                            • meas.channel: 2

                                                                                                                                                                                                            • roi.startx: 20

                                                                                                                                                                                                            • roi.starty: 30

                                                                                                                                                                                                            • roi.sizex: 150

                                                                                                                                                                                                            • roi.sizey: 200

                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-raster.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-raster.html new file mode 100644 index 000000000000..8a6c9eed9ad3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-raster.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                            ComputeConfusionMatrix

                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                            Computes the confusion matrix of a classification

                                                                                                                                                                                                            Tags

                                                                                                                                                                                                            Learning

                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                            This application computes the confusion matrix of a classification map relatively to a ground truth. This ground truth can be given as a raster or a vector data. Only reference and produced pixels with values different from NoData are handled in the calculation of the confusion matrix. The confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the output file, the reference and produced class labels are ordered according to the rows/columns of the confusion matrix.

                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                            • [param] -in <string> The input classification image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -out <string> Filename to store the output matrix (csv format). Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -nodatalabel <int32> Label for the NoData class. Such input pixels will be discarded from the ground truth and from the input classification map. By default, 'nodatalabel = 0'.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [choice] -ref Choice of ground truth format raster,vector. Mandatory: True. Default Value: "raster"
                                                                                                                                                                                                              • [group] -raster
                                                                                                                                                                                                                • [param] -ref.raster.in <string> Input image containing the ground truth labels. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [group] -vector
                                                                                                                                                                                                                • [param] -ref.vector.in <string> Input vector data of the ground truth. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                • [param] -ref.vector.field <string> Field name containing the label values. Mandatory: False. Default Value: "Class"

                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                            None

                                                                                                                                                                                                            Authors

                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                            See Also

                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                            • in: clLabeledImageQB1.tif

                                                                                                                                                                                                            • out: ConfusionMatrix.csv

                                                                                                                                                                                                            • ref: vector

                                                                                                                                                                                                            • ref.vector.in: VectorData_QB1_bis.shp

                                                                                                                                                                                                            • ref.vector.field: Class

                                                                                                                                                                                                            • nodatalabel: 255

                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-vector.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-vector.html new file mode 100644 index 000000000000..8a6c9eed9ad3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix-vector.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                            ComputeConfusionMatrix

                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                            Computes the confusion matrix of a classification

                                                                                                                                                                                                            Tags

                                                                                                                                                                                                            Learning

                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                            This application computes the confusion matrix of a classification map relatively to a ground truth. This ground truth can be given as a raster or a vector data. Only reference and produced pixels with values different from NoData are handled in the calculation of the confusion matrix. The confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the output file, the reference and produced class labels are ordered according to the rows/columns of the confusion matrix.

                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                            • [param] -in <string> The input classification image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -out <string> Filename to store the output matrix (csv format). Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -nodatalabel <int32> Label for the NoData class. Such input pixels will be discarded from the ground truth and from the input classification map. By default, 'nodatalabel = 0'.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [choice] -ref Choice of ground truth format raster,vector. Mandatory: True. Default Value: "raster"
                                                                                                                                                                                                              • [group] -raster
                                                                                                                                                                                                                • [param] -ref.raster.in <string> Input image containing the ground truth labels. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [group] -vector
                                                                                                                                                                                                                • [param] -ref.vector.in <string> Input vector data of the ground truth. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                • [param] -ref.vector.field <string> Field name containing the label values. Mandatory: False. Default Value: "Class"

                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                            None

                                                                                                                                                                                                            Authors

                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                            See Also

                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                            • in: clLabeledImageQB1.tif

                                                                                                                                                                                                            • out: ConfusionMatrix.csv

                                                                                                                                                                                                            • ref: vector

                                                                                                                                                                                                            • ref.vector.in: VectorData_QB1_bis.shp

                                                                                                                                                                                                            • ref.vector.field: Class

                                                                                                                                                                                                            • nodatalabel: 255

                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix.html new file mode 100644 index 000000000000..8a6c9eed9ad3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeConfusionMatrix.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                            ComputeConfusionMatrix

                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                            Computes the confusion matrix of a classification

                                                                                                                                                                                                            Tags

                                                                                                                                                                                                            Learning

                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                            This application computes the confusion matrix of a classification map relatively to a ground truth. This ground truth can be given as a raster or a vector data. Only reference and produced pixels with values different from NoData are handled in the calculation of the confusion matrix. The confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the output file, the reference and produced class labels are ordered according to the rows/columns of the confusion matrix.

                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                            • [param] -in <string> The input classification image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -out <string> Filename to store the output matrix (csv format). Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -nodatalabel <int32> Label for the NoData class. Such input pixels will be discarded from the ground truth and from the input classification map. By default, 'nodatalabel = 0'.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [choice] -ref Choice of ground truth format raster,vector. Mandatory: True. Default Value: "raster"
                                                                                                                                                                                                              • [group] -raster
                                                                                                                                                                                                                • [param] -ref.raster.in <string> Input image containing the ground truth labels. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [group] -vector
                                                                                                                                                                                                                • [param] -ref.vector.in <string> Input vector data of the ground truth. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                • [param] -ref.vector.field <string> Field name containing the label values. Mandatory: False. Default Value: "Class"

                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                            None

                                                                                                                                                                                                            Authors

                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                            See Also

                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                            • in: clLabeledImageQB1.tif

                                                                                                                                                                                                            • out: ConfusionMatrix.csv

                                                                                                                                                                                                            • ref: vector

                                                                                                                                                                                                            • ref.vector.in: VectorData_QB1_bis.shp

                                                                                                                                                                                                            • ref.vector.field: Class

                                                                                                                                                                                                            • nodatalabel: 255

                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeImagesStatistics.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeImagesStatistics.html new file mode 100644 index 000000000000..05cb9575bdbb --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeImagesStatistics.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                            ComputeImagesStatistics

                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                            Computes global mean and standard deviation for each band from a set of images and optionally saves the results in an XML file.

                                                                                                                                                                                                            Tags

                                                                                                                                                                                                            Learning,Image Analysis

                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                            This application computes a global mean and standard deviation for each band of a set of images and optionally saves the results in an XML file. The output XML is intended to be used an input for the TrainImagesClassifier application to normalize samples before learning.

                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                            • [param] -il <string> List of input images filenames.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                            • [param] -bv <float> Background value to ignore in statistics computation.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                            • [param] -out <string> XML filename where the statistics are saved for future reuse.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                            Each image of the set must contain the same bands as the others (i.e. same types, in the same order).

                                                                                                                                                                                                            Authors

                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                            See Also

                                                                                                                                                                                                            Documentation of the TrainImagesClassifier application.

                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                            • il: QB_1_ortho.tif

                                                                                                                                                                                                            • out: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeOGRLayersFeaturesStatistics.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeOGRLayersFeaturesStatistics.html new file mode 100644 index 000000000000..42c4651f14e3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputeOGRLayersFeaturesStatistics.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                            ComputeOGRLayersFeaturesStatistics

                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                            Compute statistics of the features in a set of OGR Layers

                                                                                                                                                                                                            Tags

                                                                                                                                                                                                            Segmentation

                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                            Compute statistics (mean and standard deviation) of the features in a set of OGR Layers, and write them in an XML file. This XML file can then be used by the training application.

                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                            • [param] -inshp <string> Name of the input shapefile. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -outstats <string> XML file containing mean and variance of each feature.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                            • [choice] -feat List of features to consider for statistics. . Mandatory: True. Default Value: ""

                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                              Experimental. For now only shapefiles are supported.

                                                                                                                                                                                                              Authors

                                                                                                                                                                                                              David Youssefi during internship at CNES

                                                                                                                                                                                                              See Also

                                                                                                                                                                                                              OGRLayerClassifier,TrainOGRLayersClassifier

                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                              • inshp: vectorData.shp

                                                                                                                                                                                                              • outstats: results.xml

                                                                                                                                                                                                              • feat: perimeter

                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputePolylineFeatureFromImage.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputePolylineFeatureFromImage.html new file mode 100644 index 000000000000..646191e845f4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ComputePolylineFeatureFromImage.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                              ComputePolylineFeatureFromImage

                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                              This application compute for each studied polyline, contained in the input VectorData, the chosen descriptors.

                                                                                                                                                                                                              Tags

                                                                                                                                                                                                              Feature Extraction

                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                              The first step in the classifier fusion based validation is to compute, for each studied polyline, the chosen descriptors.

                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                              • [param] -in <string> An image to compute the descriptors on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -vd <string> Vector data containing the polylines where the features will be computed.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [param] -expr <string> The feature formula (b1 < 0.3) where b1 is the standard name of input image first band. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -field <string> The field name corresponding to the feature codename (NONDVI, ROADSA...). Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -out <string> The output vector data containing polylines with a new field. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                              Since it does not rely on streaming process, take care of the size of input image before launching application.

                                                                                                                                                                                                              Authors

                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                              See Also

                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                              • in: NDVI.TIF

                                                                                                                                                                                                              • vd: roads_ground_truth.shp

                                                                                                                                                                                                              • expr: "(b1 > 0.4)"

                                                                                                                                                                                                              • field: NONDVI

                                                                                                                                                                                                              • out: PolylineFeatureFromImage_LI_NONDVI_gt.shp

                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateImages.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateImages.html new file mode 100644 index 000000000000..f5d2ac5e2c28 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateImages.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                              ConcatenateImages

                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                              Concatenate a list of images of the same size into a single multi-channel one.

                                                                                                                                                                                                              Tags

                                                                                                                                                                                                              Image Manipulation,Concatenation,Multi-channel

                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                              This application performs images channels concatenation. It will walk the input image list (single or multi-channel) and generates a single multi-channel image. The channel order is the one of the list.

                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                              • [param] -il <string> The list of images to concatenate. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [param] -out <string> The concatenated output image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                              All input images must have the same size.

                                                                                                                                                                                                              Authors

                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                              See Also

                                                                                                                                                                                                              Rescale application, Convert

                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                              • il: GomaAvant.png GomaApres.png

                                                                                                                                                                                                              • out: otbConcatenateImages.tif

                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateVectorData.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateVectorData.html new file mode 100644 index 000000000000..1760c34db99c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConcatenateVectorData.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                              ConcatenateVectorData

                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                              Concatenate VectorDatas

                                                                                                                                                                                                              Tags

                                                                                                                                                                                                              Vector Data Manipulation

                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                              This application concatenates a list of VectorData to produce a unique VectorData as output.Note that the VectorDatas must be of the same type (Storing polygons only, lines only, or points only)

                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                              • [param] -vd <string> VectorData files to be concatenated in an unique VectorData. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [param] -out <string> Output conctenated VectorData. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                              None

                                                                                                                                                                                                              Authors

                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                              See Also

                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                              • vd: ToulousePoints-examples.shp ToulouseRoad-examples.shp

                                                                                                                                                                                                              • out: ConcatenatedVectorData.shp

                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ConnectedComponentSegmentation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConnectedComponentSegmentation.html new file mode 100644 index 000000000000..86198d1547a7 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConnectedComponentSegmentation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                              ConnectedComponentSegmentation

                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                              Connected component segmentation and object based image filtering of the input image according to user-defined criterions.

                                                                                                                                                                                                              Tags

                                                                                                                                                                                                              Image Analysis,Segmentation

                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                              This application allows one to perform a masking, connected components segmentation and object based image filtering. First and optionally, a mask can be built based on user-defined criterions to select pixels of the image which will be segmented. Then a connected component segmentation is performed with a user defined criterion to decide whether two neighbouring pixels belong to the same segment or not. After this segmentation step, an object based image filtering is applied using another user-defined criterion reasoning on segment properties, like shape or radiometric attributes. Criterions are mathematical expressions analysed by the MuParser library (http://muparser.sourceforge.net/). For instance, expression "((b1>80) and intensity>95)" will merge two neighbouring pixel in a single segment if their intensity is more than 95 and their value in the first image band is more than 80. See parameters documentation for a list of available attributes. The output of the object based image filtering is vectorized and can be written in shapefile or KML format. If the input image is in raw geometry, resulting polygons will be transformed to WGS84 using sensor modelling before writing, to ensure consistency with GIS software. For this purpose, a Digital Elevation Model can be provided to the application. The whole processing is done on a per-tile basis for large images, so this application can handle images of arbitrary size.

                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                              • [param] -in <string> The image to segment.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -out <string> The segmentation shape.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -mask <string> Mask mathematical expression (only if support image is given). Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -expr <string> Formula used for connected component segmentation. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -minsize <int32> Min object size (area in pixel). Mandatory: False. Default Value: "2"
                                                                                                                                                                                                              • [param] -obia <string> OBIA mathematical expression. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                              Due to the tiling scheme in case of large images, some segments can be arbitrarily split across multiple tiles.

                                                                                                                                                                                                              Authors

                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                              See Also

                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                              • in: ROI_QB_MUL_4.tif

                                                                                                                                                                                                              • mask: "((b1>80)*intensity>95)"

                                                                                                                                                                                                              • expr: "distance<10"

                                                                                                                                                                                                              • minsize: 15

                                                                                                                                                                                                              • obia: "SHAPE_Elongation>8"

                                                                                                                                                                                                              • out: ConnectedComponentSegmentation.shp

                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Convert.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Convert.html new file mode 100644 index 000000000000..d639181f4282 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Convert.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                                              Convert

                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                              Convert an image to a different format, eventually rescaling the data and/or changing the pixel type.

                                                                                                                                                                                                              Tags

                                                                                                                                                                                                              Conversion,Image Dynamic,Image Manipulation

                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                              This application performs an image pixel type conversion (short, ushort, uchar, int, uint, float and double types are handled). The output image is written in the specified format (ie. that corresponds to the given extension). + The conversion can include a rescale using the image 2 percent minimum and maximum values. The rescale can be linear or log2.

                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                              • [param] -in <string> Input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -mask <string> The masked pixels won't be used to adapt the dynamic (the mask must have the same dimensions as the input image). Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -hcp <string> Parameters to cut the histogram edges before rescaling. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                              • [param] -out <string> Output image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                              • [choice] -type Transfer function for the rescaling none,linear,log2. Mandatory: True. Default Value: "none"
                                                                                                                                                                                                                • [group] -none
                                                                                                                                                                                                                  • [group] -linear
                                                                                                                                                                                                                    • [param] -type.linear.gamma <float> Gamma correction factor. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                  • [group] -log2

                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                  None

                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                  Rescale

                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                  • out: otbConvertWithScalingOutput.png uint8

                                                                                                                                                                                                                  • type: linear

                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertCartoToGeoPoint.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertCartoToGeoPoint.html new file mode 100644 index 000000000000..7d5c59ef0e7d --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertCartoToGeoPoint.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                  ConvertCartoToGeoPoint

                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                  Convert cartographic coordinates to geographic one.

                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                  Coordinates,Geometry

                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                  This application computes the geographic coordinates from a cartographic one. User has to give the X and Y coordinate and the cartographic projection (UTM/LAMBERT/LAMBERT2/LAMBERT93/SINUS/ECKERT4/TRANSMERCATOR/MOLLWEID/SVY21).

                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                  • [param] -carto <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                  • [param] -long <float> Point longitude coordinates.. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                  • [param] -lat <float> Point latitude coordinates.. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                  • [choice] -mapproj Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                    • [group] -utm
                                                                                                                                                                                                                      • [param] -mapproj.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                      • [param] -mapproj.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                    • [group] -lambert2
                                                                                                                                                                                                                      • [group] -lambert93
                                                                                                                                                                                                                        • [group] -wgs
                                                                                                                                                                                                                          • [group] -epsg
                                                                                                                                                                                                                            • [param] -mapproj.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • carto.x: 367074.625

                                                                                                                                                                                                                        • carto.y: 4835740

                                                                                                                                                                                                                        • mapproj: utm

                                                                                                                                                                                                                        • mapproj.utm.northhem: true

                                                                                                                                                                                                                        • mapproj.utm.zone: 31

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertSensorToGeoPoint.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertSensorToGeoPoint.html new file mode 100644 index 000000000000..2f7c862990d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ConvertSensorToGeoPoint.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        ConvertSensorToGeoPoint

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Sensor to geographic coordinates conversion.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        Geometry

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        This Application converts a sensor point of an input image to a geographic point using the Forward Sensor Model of the input image.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input sensor image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -input <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                        • [param] -output <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        ConvertCartoToGeoPoint application, otbObtainUTMZoneFromGeoPoint

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                        • input.idx: 200

                                                                                                                                                                                                                        • input.idy: 200

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DEMConvert.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DEMConvert.html new file mode 100644 index 000000000000..e51b5030bbfd --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DEMConvert.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        DEMConvert

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Converts a geo-referenced DEM image into a general raster file compatible with OTB DEM handling.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        Image Manipulation

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        In order to be understood by the Orfeo ToolBox and the underlying OSSIM library, a geo-referenced Digital Elevation Model image can be converted into a general raster image, which consists in 3 files with the following extensions: .ras, .geom and .omd. Once converted, you have to place these files in a separate directory, and you can then use this directory to set the "DEM Directory" parameter of a DEM based OTB application or filter.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input geo-referenced DEM to convert to general raster format.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> will be used to get the prefix (name withtout extensions) of the files to write. Three files - prefix.geom, prefix.omd and prefix.ras - will be generated.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: QB_Toulouse_Ortho_Elev.tif

                                                                                                                                                                                                                        • out: outputDEM

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DSFuzzyModelEstimation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DSFuzzyModelEstimation.html new file mode 100644 index 000000000000..e5d507ba025b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DSFuzzyModelEstimation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        DSFuzzyModelEstimation

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Estimate feature fuzzy model parameters using 2 vector data (ground truth samples and wrong samples).

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        Feature Extraction

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        Estimate feature fuzzy model parameters using 2 vector data (ground truth samples and wrong samples).

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -psin <string> Ground truth vector data for positive samples. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -nsin <string> Ground truth vector data for negative samples. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -belsup <string> Dempster Shafer study hypothesis to compute belief. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -plasup <string> Dempster Shafer study hypothesis to compute plausibility. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -cri <string> Dempster Shafer criterion (by default (belief+plausibility)/2). Mandatory: False. Default Value: "((Belief + Plausibility)/2.)"
                                                                                                                                                                                                                        • [param] -wgt <float> Coefficient between 0 and 1 to promote undetection or false detections (default 0.5). Mandatory: False. Default Value: "0.5"
                                                                                                                                                                                                                        • [param] -initmod <string> Initialization model (xml file) to be used. If the xml initialization model is set, the descriptor list is not used (specified using the option -desclist). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -desclist <string> List of the descriptors to be used in the model (must be specified to perform an automatic initialization). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -maxnbit <int32> Maximum number of optimizer iteration (default 200). Mandatory: False. Default Value: "200"
                                                                                                                                                                                                                        • [param] -optobs <boolean> Activate the optimizer observer. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                        • [param] -out <string> Output model file name (xml file) contains the optimal model to perform information fusion.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None.

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • psin: cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_gt.shp

                                                                                                                                                                                                                        • nsin: cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_wr.shp

                                                                                                                                                                                                                        • belsup: "ROADSA"

                                                                                                                                                                                                                        • plasup: "NONDVI" "ROADSA" "NOBUIL"

                                                                                                                                                                                                                        • initmod: Dempster-Shafer/DSFuzzyModel_Init.xml

                                                                                                                                                                                                                        • maxnbit: 4

                                                                                                                                                                                                                        • optobs: true

                                                                                                                                                                                                                        • out: DSFuzzyModelEstimation.xml

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-frost.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-frost.html new file mode 100644 index 000000000000..7ec3875fb9d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-frost.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        Despeckle

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Perform speckle noise reduction on SAR image.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        SAR,Image Filtering

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        This application reduce speckle noise. Four methods are available: Lee, Frost, GammaMAP and Kuan.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [choice] -filter lee,frost,gammamap,kuan. Mandatory: True. Default Value: "lee"
                                                                                                                                                                                                                          • [group] -lee
                                                                                                                                                                                                                            • [param] -filter.lee.rad <int32> Radius for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.lee.nblooks <float> Nb looks for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -frost
                                                                                                                                                                                                                            • [param] -filter.frost.rad <int32> Radius for frost filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.frost.deramp <float> Decrease factor declaration. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                          • [group] -gammamap
                                                                                                                                                                                                                            • [param] -filter.gammamap.rad <int32> Radius for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.gammamap.nblooks <float> Nb looks for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -kuan
                                                                                                                                                                                                                            • [param] -filter.kuan.rad <int32> Radius for Kuan filter. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                            • [param] -filter.kuan.nblooks <float> Nb looks for Kuan filter. Mandatory: True. Default Value: "0.0"

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: sar.tif

                                                                                                                                                                                                                        • filter: lee

                                                                                                                                                                                                                        • filter.lee.rad: 5

                                                                                                                                                                                                                        • out: despeckle.tif

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-gammamap.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-gammamap.html new file mode 100644 index 000000000000..7ec3875fb9d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-gammamap.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        Despeckle

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Perform speckle noise reduction on SAR image.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        SAR,Image Filtering

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        This application reduce speckle noise. Four methods are available: Lee, Frost, GammaMAP and Kuan.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [choice] -filter lee,frost,gammamap,kuan. Mandatory: True. Default Value: "lee"
                                                                                                                                                                                                                          • [group] -lee
                                                                                                                                                                                                                            • [param] -filter.lee.rad <int32> Radius for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.lee.nblooks <float> Nb looks for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -frost
                                                                                                                                                                                                                            • [param] -filter.frost.rad <int32> Radius for frost filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.frost.deramp <float> Decrease factor declaration. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                          • [group] -gammamap
                                                                                                                                                                                                                            • [param] -filter.gammamap.rad <int32> Radius for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.gammamap.nblooks <float> Nb looks for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -kuan
                                                                                                                                                                                                                            • [param] -filter.kuan.rad <int32> Radius for Kuan filter. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                            • [param] -filter.kuan.nblooks <float> Nb looks for Kuan filter. Mandatory: True. Default Value: "0.0"

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: sar.tif

                                                                                                                                                                                                                        • filter: lee

                                                                                                                                                                                                                        • filter.lee.rad: 5

                                                                                                                                                                                                                        • out: despeckle.tif

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-kuan.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-kuan.html new file mode 100644 index 000000000000..7ec3875fb9d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-kuan.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        Despeckle

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Perform speckle noise reduction on SAR image.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        SAR,Image Filtering

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        This application reduce speckle noise. Four methods are available: Lee, Frost, GammaMAP and Kuan.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [choice] -filter lee,frost,gammamap,kuan. Mandatory: True. Default Value: "lee"
                                                                                                                                                                                                                          • [group] -lee
                                                                                                                                                                                                                            • [param] -filter.lee.rad <int32> Radius for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.lee.nblooks <float> Nb looks for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -frost
                                                                                                                                                                                                                            • [param] -filter.frost.rad <int32> Radius for frost filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.frost.deramp <float> Decrease factor declaration. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                          • [group] -gammamap
                                                                                                                                                                                                                            • [param] -filter.gammamap.rad <int32> Radius for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.gammamap.nblooks <float> Nb looks for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -kuan
                                                                                                                                                                                                                            • [param] -filter.kuan.rad <int32> Radius for Kuan filter. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                            • [param] -filter.kuan.nblooks <float> Nb looks for Kuan filter. Mandatory: True. Default Value: "0.0"

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: sar.tif

                                                                                                                                                                                                                        • filter: lee

                                                                                                                                                                                                                        • filter.lee.rad: 5

                                                                                                                                                                                                                        • out: despeckle.tif

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-lee.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-lee.html new file mode 100644 index 000000000000..7ec3875fb9d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle-lee.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        Despeckle

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Perform speckle noise reduction on SAR image.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        SAR,Image Filtering

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        This application reduce speckle noise. Four methods are available: Lee, Frost, GammaMAP and Kuan.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [choice] -filter lee,frost,gammamap,kuan. Mandatory: True. Default Value: "lee"
                                                                                                                                                                                                                          • [group] -lee
                                                                                                                                                                                                                            • [param] -filter.lee.rad <int32> Radius for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.lee.nblooks <float> Nb looks for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -frost
                                                                                                                                                                                                                            • [param] -filter.frost.rad <int32> Radius for frost filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.frost.deramp <float> Decrease factor declaration. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                          • [group] -gammamap
                                                                                                                                                                                                                            • [param] -filter.gammamap.rad <int32> Radius for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.gammamap.nblooks <float> Nb looks for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -kuan
                                                                                                                                                                                                                            • [param] -filter.kuan.rad <int32> Radius for Kuan filter. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                            • [param] -filter.kuan.nblooks <float> Nb looks for Kuan filter. Mandatory: True. Default Value: "0.0"

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: sar.tif

                                                                                                                                                                                                                        • filter: lee

                                                                                                                                                                                                                        • filter.lee.rad: 5

                                                                                                                                                                                                                        • out: despeckle.tif

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle.html new file mode 100644 index 000000000000..7ec3875fb9d8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Despeckle.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        Despeckle

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Perform speckle noise reduction on SAR image.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        SAR,Image Filtering

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        This application reduce speckle noise. Four methods are available: Lee, Frost, GammaMAP and Kuan.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [choice] -filter lee,frost,gammamap,kuan. Mandatory: True. Default Value: "lee"
                                                                                                                                                                                                                          • [group] -lee
                                                                                                                                                                                                                            • [param] -filter.lee.rad <int32> Radius for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.lee.nblooks <float> Nb looks for lee filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -frost
                                                                                                                                                                                                                            • [param] -filter.frost.rad <int32> Radius for frost filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.frost.deramp <float> Decrease factor declaration. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                          • [group] -gammamap
                                                                                                                                                                                                                            • [param] -filter.gammamap.rad <int32> Radius for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [param] -filter.gammamap.nblooks <float> Nb looks for GammaMAP filter. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                          • [group] -kuan
                                                                                                                                                                                                                            • [param] -filter.kuan.rad <int32> Radius for Kuan filter. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                            • [param] -filter.kuan.nblooks <float> Nb looks for Kuan filter. Mandatory: True. Default Value: "0.0"

                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                        None

                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                        • in: sar.tif

                                                                                                                                                                                                                        • filter: lee

                                                                                                                                                                                                                        • filter.lee.rad: 5

                                                                                                                                                                                                                        • out: despeckle.tif

                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-ica.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-ica.html new file mode 100644 index 000000000000..80fc079f1fc5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-ica.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                        DimensionalityReduction

                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                        Perform Dimension reduction of the input image.

                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                        Dimensionality Reduction,Image Filtering

                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                        Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file.

                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                        • [param] -in <string> The input image to apply dimensionality reduction.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                        • [param] -out <string> output image. Components are ordered by decreasing eigenvalues.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -rescale <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                        • [param] -outinv <string> reconstruct output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -nbcomp <int32> Number of relevant components kept. By default all components are kept.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                        • [param] -normalize <boolean> center AND reduce data before Dimensionality reduction.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                        • [param] -outmatrix <string> Filename to store the transformation matrix (csv format). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                        • [choice] -method Selection of the reduction dimension method. pca,napca,maf,ica. Mandatory: True. Default Value: "pca"
                                                                                                                                                                                                                          • [group] -pca
                                                                                                                                                                                                                            • [group] -napca
                                                                                                                                                                                                                              • [param] -method.napca.radiusx <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                              • [param] -method.napca.radiusy <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                            • [group] -maf
                                                                                                                                                                                                                              • [group] -ica
                                                                                                                                                                                                                                • [param] -method.ica.iter <int32> . Mandatory: False. Default Value: "20"
                                                                                                                                                                                                                                • [param] -method.ica.mu <float> . Mandatory: False. Default Value: "1"

                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                            This application does not provide the inverse transform and the transformation matrix export for the MAF.

                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                            "Kernel maximum autocorrelation factor and minimum noise fraction transformations," IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)

                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                            • in: cupriteSubHsi.tif

                                                                                                                                                                                                                            • out: FilterOutput.tif

                                                                                                                                                                                                                            • method: pca

                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-maf.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-maf.html new file mode 100644 index 000000000000..80fc079f1fc5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-maf.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                            DimensionalityReduction

                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                            Perform Dimension reduction of the input image.

                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                            Dimensionality Reduction,Image Filtering

                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                            Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file.

                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                            • [param] -in <string> The input image to apply dimensionality reduction.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                            • [param] -out <string> output image. Components are ordered by decreasing eigenvalues.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                            • [param] -rescale <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                            • [param] -outinv <string> reconstruct output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                            • [param] -nbcomp <int32> Number of relevant components kept. By default all components are kept.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                            • [param] -normalize <boolean> center AND reduce data before Dimensionality reduction.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                            • [param] -outmatrix <string> Filename to store the transformation matrix (csv format). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                            • [choice] -method Selection of the reduction dimension method. pca,napca,maf,ica. Mandatory: True. Default Value: "pca"
                                                                                                                                                                                                                              • [group] -pca
                                                                                                                                                                                                                                • [group] -napca
                                                                                                                                                                                                                                  • [param] -method.napca.radiusx <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                  • [param] -method.napca.radiusy <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                • [group] -maf
                                                                                                                                                                                                                                  • [group] -ica
                                                                                                                                                                                                                                    • [param] -method.ica.iter <int32> . Mandatory: False. Default Value: "20"
                                                                                                                                                                                                                                    • [param] -method.ica.mu <float> . Mandatory: False. Default Value: "1"

                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                This application does not provide the inverse transform and the transformation matrix export for the MAF.

                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                "Kernel maximum autocorrelation factor and minimum noise fraction transformations," IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)

                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                • in: cupriteSubHsi.tif

                                                                                                                                                                                                                                • out: FilterOutput.tif

                                                                                                                                                                                                                                • method: pca

                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-napca.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-napca.html new file mode 100644 index 000000000000..80fc079f1fc5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-napca.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                DimensionalityReduction

                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                Perform Dimension reduction of the input image.

                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                Dimensionality Reduction,Image Filtering

                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file.

                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                • [param] -in <string> The input image to apply dimensionality reduction.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                • [param] -out <string> output image. Components are ordered by decreasing eigenvalues.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                • [param] -rescale <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                • [param] -outinv <string> reconstruct output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                • [param] -nbcomp <int32> Number of relevant components kept. By default all components are kept.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                • [param] -normalize <boolean> center AND reduce data before Dimensionality reduction.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                • [param] -outmatrix <string> Filename to store the transformation matrix (csv format). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                • [choice] -method Selection of the reduction dimension method. pca,napca,maf,ica. Mandatory: True. Default Value: "pca"
                                                                                                                                                                                                                                  • [group] -pca
                                                                                                                                                                                                                                    • [group] -napca
                                                                                                                                                                                                                                      • [param] -method.napca.radiusx <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                      • [param] -method.napca.radiusy <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                    • [group] -maf
                                                                                                                                                                                                                                      • [group] -ica
                                                                                                                                                                                                                                        • [param] -method.ica.iter <int32> . Mandatory: False. Default Value: "20"
                                                                                                                                                                                                                                        • [param] -method.ica.mu <float> . Mandatory: False. Default Value: "1"

                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                    This application does not provide the inverse transform and the transformation matrix export for the MAF.

                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                    "Kernel maximum autocorrelation factor and minimum noise fraction transformations," IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)

                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                    • in: cupriteSubHsi.tif

                                                                                                                                                                                                                                    • out: FilterOutput.tif

                                                                                                                                                                                                                                    • method: pca

                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-pca.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-pca.html new file mode 100644 index 000000000000..80fc079f1fc5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction-pca.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                    DimensionalityReduction

                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                    Perform Dimension reduction of the input image.

                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                    Dimensionality Reduction,Image Filtering

                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                    Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file.

                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                    • [param] -in <string> The input image to apply dimensionality reduction.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                    • [param] -out <string> output image. Components are ordered by decreasing eigenvalues.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                    • [param] -rescale <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                    • [param] -outinv <string> reconstruct output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                    • [param] -nbcomp <int32> Number of relevant components kept. By default all components are kept.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                    • [param] -normalize <boolean> center AND reduce data before Dimensionality reduction.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                    • [param] -outmatrix <string> Filename to store the transformation matrix (csv format). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                    • [choice] -method Selection of the reduction dimension method. pca,napca,maf,ica. Mandatory: True. Default Value: "pca"
                                                                                                                                                                                                                                      • [group] -pca
                                                                                                                                                                                                                                        • [group] -napca
                                                                                                                                                                                                                                          • [param] -method.napca.radiusx <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                          • [param] -method.napca.radiusy <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                        • [group] -maf
                                                                                                                                                                                                                                          • [group] -ica
                                                                                                                                                                                                                                            • [param] -method.ica.iter <int32> . Mandatory: False. Default Value: "20"
                                                                                                                                                                                                                                            • [param] -method.ica.mu <float> . Mandatory: False. Default Value: "1"

                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                        This application does not provide the inverse transform and the transformation matrix export for the MAF.

                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                        "Kernel maximum autocorrelation factor and minimum noise fraction transformations," IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)

                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                        • in: cupriteSubHsi.tif

                                                                                                                                                                                                                                        • out: FilterOutput.tif

                                                                                                                                                                                                                                        • method: pca

                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction.html new file mode 100644 index 000000000000..80fc079f1fc5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DimensionalityReduction.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                        DimensionalityReduction

                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                        Perform Dimension reduction of the input image.

                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                        Dimensionality Reduction,Image Filtering

                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                        Performs dimensionality reduction on input image. PCA,NA-PCA,MAF,ICA methods are available. It is also possible to compute the inverse transform to reconstruct the image. It is also possible to optionnaly export the transformation matrix to a text file.

                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                        • [param] -in <string> The input image to apply dimensionality reduction.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                        • [param] -out <string> output image. Components are ordered by decreasing eigenvalues.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                        • [param] -rescale <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                        • [param] -outinv <string> reconstruct output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                        • [param] -nbcomp <int32> Number of relevant components kept. By default all components are kept.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                        • [param] -normalize <boolean> center AND reduce data before Dimensionality reduction.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                        • [param] -outmatrix <string> Filename to store the transformation matrix (csv format). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                        • [choice] -method Selection of the reduction dimension method. pca,napca,maf,ica. Mandatory: True. Default Value: "pca"
                                                                                                                                                                                                                                          • [group] -pca
                                                                                                                                                                                                                                            • [group] -napca
                                                                                                                                                                                                                                              • [param] -method.napca.radiusx <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                              • [param] -method.napca.radiusy <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                            • [group] -maf
                                                                                                                                                                                                                                              • [group] -ica
                                                                                                                                                                                                                                                • [param] -method.ica.iter <int32> . Mandatory: False. Default Value: "20"
                                                                                                                                                                                                                                                • [param] -method.ica.mu <float> . Mandatory: False. Default Value: "1"

                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                            This application does not provide the inverse transform and the transformation matrix export for the MAF.

                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                            "Kernel maximum autocorrelation factor and minimum noise fraction transformations," IEEE Transactions on Image Processing, vol. 20, no. 3, pp. 612-624, (2011)

                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                            • in: cupriteSubHsi.tif

                                                                                                                                                                                                                                            • out: FilterOutput.tif

                                                                                                                                                                                                                                            • method: pca

                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DisparityMapToElevationMap.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DisparityMapToElevationMap.html new file mode 100644 index 000000000000..303ac0e39a48 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DisparityMapToElevationMap.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                            DisparityMapToElevationMap

                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                            Projects a disparity map into a regular elevation map

                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                            Stereo

                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                            This application uses a disparity map computed from a stereo image pair to produce an elevation map on the ground area covered by the stereo pair. The needed inputs are : the disparity map, the stereo pair (in original geometry) and the epipolar deformation grids. These grids have to link the original geometry (stereo pair) and the epipolar geometry (disparity map).

                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                            • [param] -io <string> This group of parameters allows one to set input images, output images and grids.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                            • [param] -step <float> Spacing of the output elevation map (in meters). Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                            • [param] -hmin <float> Minimum elevation expected (in meters). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                            • [param] -hmax <float> Maximum elevation expected (in meters). Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                            • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                            otbStereoRectificationGridGenerator otbBlockMatching

                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                            • io.in: disparity.tif

                                                                                                                                                                                                                                            • io.left: sensor_left.tif

                                                                                                                                                                                                                                            • io.right: sensor_right.tif

                                                                                                                                                                                                                                            • io.lgrid: grid_epi_left.tif

                                                                                                                                                                                                                                            • io.rgrid: grid_epi_right.tif

                                                                                                                                                                                                                                            • io.out: dem.tif

                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/DownloadSRTMTiles.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/DownloadSRTMTiles.html new file mode 100644 index 000000000000..3c6871d7a5eb --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/DownloadSRTMTiles.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                            DownloadSRTMTiles

                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                            Download or list SRTM tiles related to a set of images

                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                            Utilities,Image Manipulation

                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                            This application allows selecting the appropriate SRTM tiles that covers a list of images. It builds a list of the required tiles. Two modes are available: the first one download those tiles from the USGS SRTM3 website (http://dds.cr.usgs.gov/srtm/version2_1/SRTM3/), the second one list those tiles in a local directory. In both cases, you need to indicate the directory in which directory tiles will be download or the location of local SRTM files.

                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                            • [param] -il <string> The list of images on which you want to determine corresponding SRTM tiles.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                            • [choice] -mode download,list. Mandatory: True. Default Value: "download"
                                                                                                                                                                                                                                              • [group] -download
                                                                                                                                                                                                                                                • [param] -mode.download.outdir <string> Directory where zipped tiles will be save. You'll need to unzip all tile files before using them in your application.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                              • [group] -list
                                                                                                                                                                                                                                                • [param] -mode.list.indir <string> Input directory where SRTM tiles can are located.. Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                            • il: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                            • mode: list

                                                                                                                                                                                                                                            • mode.list.indir: /home/user/srtm_dir/

                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-gradient.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-gradient.html new file mode 100644 index 000000000000..aa436906807a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-gradient.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                            EdgeExtraction

                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                            Computes edge features on every pixel of the input image selected channel

                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                            Edge,Feature Extraction

                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                            This application computes edge features on a mono band image

                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                            • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                            • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                            • [param] -out <string> Output image containing the edge features.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                            • [choice] -filter Choice of edge feature gradient,sobel,touzi. Mandatory: True. Default Value: "gradient"
                                                                                                                                                                                                                                              • [group] -gradient
                                                                                                                                                                                                                                                • [group] -sobel
                                                                                                                                                                                                                                                  • [group] -touzi
                                                                                                                                                                                                                                                    • [param] -filter.touzi.xradius <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                    • [param] -filter.touzi.yradius <int32> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                otb class

                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                • channel: 1

                                                                                                                                                                                                                                                • out: Edges.tif

                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-sobel.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-sobel.html new file mode 100644 index 000000000000..aa436906807a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-sobel.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                EdgeExtraction

                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                Computes edge features on every pixel of the input image selected channel

                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                Edge,Feature Extraction

                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                This application computes edge features on a mono band image

                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                • [param] -out <string> Output image containing the edge features.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                • [choice] -filter Choice of edge feature gradient,sobel,touzi. Mandatory: True. Default Value: "gradient"
                                                                                                                                                                                                                                                  • [group] -gradient
                                                                                                                                                                                                                                                    • [group] -sobel
                                                                                                                                                                                                                                                      • [group] -touzi
                                                                                                                                                                                                                                                        • [param] -filter.touzi.xradius <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                        • [param] -filter.touzi.yradius <int32> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                    None

                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                    otb class

                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                    • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                    • channel: 1

                                                                                                                                                                                                                                                    • out: Edges.tif

                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-touzi.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-touzi.html new file mode 100644 index 000000000000..aa436906807a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction-touzi.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                    EdgeExtraction

                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                    Computes edge features on every pixel of the input image selected channel

                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                    Edge,Feature Extraction

                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                    This application computes edge features on a mono band image

                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                    • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                    • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                    • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                    • [param] -out <string> Output image containing the edge features.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                    • [choice] -filter Choice of edge feature gradient,sobel,touzi. Mandatory: True. Default Value: "gradient"
                                                                                                                                                                                                                                                      • [group] -gradient
                                                                                                                                                                                                                                                        • [group] -sobel
                                                                                                                                                                                                                                                          • [group] -touzi
                                                                                                                                                                                                                                                            • [param] -filter.touzi.xradius <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                            • [param] -filter.touzi.yradius <int32> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                        otb class

                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                        • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                        • channel: 1

                                                                                                                                                                                                                                                        • out: Edges.tif

                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction.html new file mode 100644 index 000000000000..aa436906807a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/EdgeExtraction.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                        EdgeExtraction

                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                        Computes edge features on every pixel of the input image selected channel

                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                        Edge,Feature Extraction

                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                        This application computes edge features on a mono band image

                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                        • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                        • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                        • [param] -out <string> Output image containing the edge features.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                        • [choice] -filter Choice of edge feature gradient,sobel,touzi. Mandatory: True. Default Value: "gradient"
                                                                                                                                                                                                                                                          • [group] -gradient
                                                                                                                                                                                                                                                            • [group] -sobel
                                                                                                                                                                                                                                                              • [group] -touzi
                                                                                                                                                                                                                                                                • [param] -filter.touzi.xradius <int32> . Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                • [param] -filter.touzi.yradius <int32> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                            otb class

                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                            • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                            • channel: 1

                                                                                                                                                                                                                                                            • out: Edges.tif

                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-fit.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-fit.html new file mode 100644 index 000000000000..8b36b6da38c8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-fit.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                            ExtractROI

                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                            Extract a ROI defined by the user.

                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                            Image Manipulation

                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                            This application extracts a Region Of Interest with user defined size, or reference image.

                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                            • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                            • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                            • [param] -startx <int32> ROI start x position.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                            • [param] -starty <int32> ROI start y position.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                            • [param] -sizex <int32> size along x in pixels.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                            • [param] -sizey <int32> size along y in pixels.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                            • [choice] -mode standard,fit. Mandatory: True. Default Value: "standard"
                                                                                                                                                                                                                                                              • [group] -standard
                                                                                                                                                                                                                                                                • [group] -fit
                                                                                                                                                                                                                                                                  • [param] -mode.fit.ref <string> Reference image to define the ROI. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                  • [param] -mode.fit.elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                  • [param] -mode.fit.elev.dem <string> This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain only DEM files. Unexpected behaviour might occurs if other images are found in this directory.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                  • [param] -mode.fit.elev.geoid <string> Use a geoid grid to get the height above the ellipsoid in case there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles. A version of the geoid can be found on the OTB website (http://hg.orfeo-toolbox.org/OTB-Data/raw-file/404aa6e4b3e0/Input/DEM/egm96.grd).. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                  • [param] -mode.fit.elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                [choice] -cl Channels to write in the output image. . Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                • in: VegetationIndex.hd

                                                                                                                                                                                                                                                                • startx: 40

                                                                                                                                                                                                                                                                • starty: 250

                                                                                                                                                                                                                                                                • sizex: 150

                                                                                                                                                                                                                                                                • sizey: 150

                                                                                                                                                                                                                                                                • out: ExtractROI.tif

                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-standard.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-standard.html new file mode 100644 index 000000000000..8b36b6da38c8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI-standard.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                ExtractROI

                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                Extract a ROI defined by the user.

                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                Image Manipulation

                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                This application extracts a Region Of Interest with user defined size, or reference image.

                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                • [param] -startx <int32> ROI start x position.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                • [param] -starty <int32> ROI start y position.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                • [param] -sizex <int32> size along x in pixels.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                • [param] -sizey <int32> size along y in pixels.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                • [choice] -mode standard,fit. Mandatory: True. Default Value: "standard"
                                                                                                                                                                                                                                                                  • [group] -standard
                                                                                                                                                                                                                                                                    • [group] -fit
                                                                                                                                                                                                                                                                      • [param] -mode.fit.ref <string> Reference image to define the ROI. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                      • [param] -mode.fit.elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                      • [param] -mode.fit.elev.dem <string> This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain only DEM files. Unexpected behaviour might occurs if other images are found in this directory.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                      • [param] -mode.fit.elev.geoid <string> Use a geoid grid to get the height above the ellipsoid in case there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles. A version of the geoid can be found on the OTB website (http://hg.orfeo-toolbox.org/OTB-Data/raw-file/404aa6e4b3e0/Input/DEM/egm96.grd).. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                      • [param] -mode.fit.elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                    [choice] -cl Channels to write in the output image. . Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                                    None

                                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                                    • in: VegetationIndex.hd

                                                                                                                                                                                                                                                                    • startx: 40

                                                                                                                                                                                                                                                                    • starty: 250

                                                                                                                                                                                                                                                                    • sizex: 150

                                                                                                                                                                                                                                                                    • sizey: 150

                                                                                                                                                                                                                                                                    • out: ExtractROI.tif

                                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI.html new file mode 100644 index 000000000000..8b36b6da38c8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ExtractROI.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                    ExtractROI

                                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                                    Extract a ROI defined by the user.

                                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                                    Image Manipulation

                                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                                    This application extracts a Region Of Interest with user defined size, or reference image.

                                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                                    • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                    • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                    • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                    • [param] -startx <int32> ROI start x position.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                    • [param] -starty <int32> ROI start y position.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                    • [param] -sizex <int32> size along x in pixels.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                    • [param] -sizey <int32> size along y in pixels.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                    • [choice] -mode standard,fit. Mandatory: True. Default Value: "standard"
                                                                                                                                                                                                                                                                      • [group] -standard
                                                                                                                                                                                                                                                                        • [group] -fit
                                                                                                                                                                                                                                                                          • [param] -mode.fit.ref <string> Reference image to define the ROI. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                          • [param] -mode.fit.elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                          • [param] -mode.fit.elev.dem <string> This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain only DEM files. Unexpected behaviour might occurs if other images are found in this directory.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                          • [param] -mode.fit.elev.geoid <string> Use a geoid grid to get the height above the ellipsoid in case there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles. A version of the geoid can be found on the OTB website (http://hg.orfeo-toolbox.org/OTB-Data/raw-file/404aa6e4b3e0/Input/DEM/egm96.grd).. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                          • [param] -mode.fit.elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        [choice] -cl Channels to write in the output image. . Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                        • in: VegetationIndex.hd

                                                                                                                                                                                                                                                                        • startx: 40

                                                                                                                                                                                                                                                                        • starty: 250

                                                                                                                                                                                                                                                                        • sizex: 150

                                                                                                                                                                                                                                                                        • sizey: 150

                                                                                                                                                                                                                                                                        • out: ExtractROI.tif

                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/FineRegistration.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/FineRegistration.html new file mode 100644 index 000000000000..0c8330415a83 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/FineRegistration.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                        FineRegistration

                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                        Estimate disparity map between two images.

                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                        Stereo

                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                        Estimate disparity map between two images. Output image contain x offset, y offset and metric value.

                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                        • [param] -ref <string> The reference image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -sec <string> The secondary image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -out <string> The output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -erx <int32> The exploration radius along x (in pixels). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -ery <int32> The exploration radius along y (in pixels). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -mrx <int32> Radius along x (in pixels) of the metric computation window. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -mry <int32> Radius along y (in pixels) of the metric computation window. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -w <string> The image to warp after disparity estimation is completed. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -wo <string> The output warped image. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -cox <float> Coarse offset along x (in physical space) between the two images. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -coy <float> Coarse offset along y (in physical space) between the two images. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -ssrx <float> Generates a result at a coarser resolution with a given sub-sampling rate along X. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                        • [param] -ssry <float> Generates a result at a coarser resolution with a given sub-sampling rate along Y. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                        • [param] -rgsx <float> Performs a gaussian smoothing of the reference image. Parameter is gaussian sigma (in pixels) in X direction.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                        • [param] -rgsy <float> Performs a gaussian smoothing of the reference image. Parameter is gaussian sigma (in pixels) in Y direction.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                        • [param] -sgsx <float> Performs a gaussian smoothing of the secondary image. Parameter is gaussian sigma (in pixels) in X direction.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                        • [param] -sgsy <float> Performs a gaussian smoothing of the secondary image. Parameter is gaussian sigma (in pixels) in Y direction.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                        • [param] -m <string> Choose the metric used for block matching. Available metrics are cross-correlation (CC), cross-correlation with subtracted mean (CCSM), mean-square difference (MSD), mean reciprocal square difference (MRSD) and mutual information (MI). Default is cross-correlation. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -spa <float> Metric extrema location will be refined up to the given accuracy. Default is 0.01. Mandatory: False. Default Value: "0.01"
                                                                                                                                                                                                                                                                        • [param] -vmlt <float> Lower threshold to obtain a validity mask.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                        • [param] -vmut <float> Upper threshold to obtain a validity mask.. Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                        • ref: StereoFixed.png

                                                                                                                                                                                                                                                                        • sec: StereoMoving.png

                                                                                                                                                                                                                                                                        • out: FineRegistration.tif

                                                                                                                                                                                                                                                                        • erx: 2

                                                                                                                                                                                                                                                                        • ery: 2

                                                                                                                                                                                                                                                                        • mrx: 3

                                                                                                                                                                                                                                                                        • mry: 3

                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-dempstershafer.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-dempstershafer.html new file mode 100644 index 000000000000..b5b88b5fc6ff --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-dempstershafer.html @@ -0,0 +1,9 @@ + + +

                                                                                                                                                                                                                                                                        FusionOfClassifications

                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                        Fuses several classifications maps of the same image on the basis of class labels.

                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                        Learning,Image Analysis

                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                        This application allows you to fuse several classification maps and produces a single more robust classification map. Fusion is done either by mean of Majority Voting, or with the Dempster Shafer combination method on class labels. + -MAJORITY VOTING: for each pixel, the class with the highest number of votes is selected. + -DEMPSTER SHAFER: for each pixel, the class label for which the Belief Function is maximal is selected. This Belief Function is calculated by mean of the Dempster Shafer combination of Masses of Belief, and indicates the belief that each input classification map presents for each label value. Moreover, the Masses of Belief are based on the input confusion matrices of each classification map, either by using the PRECISION or RECALL rates, or the OVERALL ACCURACY, or the KAPPA coefficient. Thus, each input classification map needs to be associated with its corresponding input confusion matrix file for the Dempster Shafer fusion. +-Input pixels with the NODATA label are not handled in the fusion of classification maps. Moreover, pixels for which all the input classifiers are set to NODATA keep this value in the output fused image. +-In case of number of votes equality, the UNDECIDED label is attributed to the pixel.

                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                        • [param] -il <string> List of input classification maps to fuse. Labels in each classification image must represent the same class.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -nodatalabel <int32> Label for the NoData class. Such input pixels keep their NoData label in the output image and are not handled in the fusion process. By default, 'nodatalabel = 0'.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -undecidedlabel <int32> Label for the Undecided class. Pixels with more than 1 fused class are marked as Undecided. Please note that the Undecided value must be different from existing labels in the input classifications. By default, 'undecidedlabel = 0'.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                        • [param] -out <string> The output classification image resulting from the fusion of the input classification images.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                        • [choice] -method Selection of the fusion method and its parameters. majorityvoting,dempstershafer. Mandatory: True. Default Value: "majorityvoting"
                                                                                                                                                                                                                                                                          • [group] -majorityvoting
                                                                                                                                                                                                                                                                            • [group] -dempstershafer
                                                                                                                                                                                                                                                                              • [param] -method.dempstershafer.cmfl <string> A list of confusion matrix files (*.CSV format) to define the masses of belief and the class labels. Each file should be formatted the following way: the first line, beginning with a '#' symbol, should be a list of the class labels present in the corresponding input classification image, organized in the same order as the confusion matrix rows/columns.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                              • [param] -method.dempstershafer.mob <string> Type of confusion matrix measurement used to compute the masses of belief of each classifier.. Mandatory: True. Default Value: "precision"

                                                                                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                                                                                          None

                                                                                                                                                                                                                                                                          Authors

                                                                                                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                                                                                                          See Also

                                                                                                                                                                                                                                                                          ImageClassifier application

                                                                                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                                                                                          • il: classification1.tif classification2.tif classification3.tif

                                                                                                                                                                                                                                                                          • method: dempstershafer

                                                                                                                                                                                                                                                                          • method.dempstershafer.cmfl: classification1.csv classification2.csv classification3.csv

                                                                                                                                                                                                                                                                          • method.dempstershafer.mob: precision

                                                                                                                                                                                                                                                                          • nodatalabel: 0

                                                                                                                                                                                                                                                                          • undecidedlabel: 10

                                                                                                                                                                                                                                                                          • out: classification_fused.tif

                                                                                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-majorityvoting.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-majorityvoting.html new file mode 100644 index 000000000000..b5b88b5fc6ff --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications-majorityvoting.html @@ -0,0 +1,9 @@ + + +

                                                                                                                                                                                                                                                                          FusionOfClassifications

                                                                                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                                                                                          Fuses several classifications maps of the same image on the basis of class labels.

                                                                                                                                                                                                                                                                          Tags

                                                                                                                                                                                                                                                                          Learning,Image Analysis

                                                                                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                                                                                          This application allows you to fuse several classification maps and produces a single more robust classification map. Fusion is done either by mean of Majority Voting, or with the Dempster Shafer combination method on class labels. + -MAJORITY VOTING: for each pixel, the class with the highest number of votes is selected. + -DEMPSTER SHAFER: for each pixel, the class label for which the Belief Function is maximal is selected. This Belief Function is calculated by mean of the Dempster Shafer combination of Masses of Belief, and indicates the belief that each input classification map presents for each label value. Moreover, the Masses of Belief are based on the input confusion matrices of each classification map, either by using the PRECISION or RECALL rates, or the OVERALL ACCURACY, or the KAPPA coefficient. Thus, each input classification map needs to be associated with its corresponding input confusion matrix file for the Dempster Shafer fusion. +-Input pixels with the NODATA label are not handled in the fusion of classification maps. Moreover, pixels for which all the input classifiers are set to NODATA keep this value in the output fused image. +-In case of number of votes equality, the UNDECIDED label is attributed to the pixel.

                                                                                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                                                                                          • [param] -il <string> List of input classification maps to fuse. Labels in each classification image must represent the same class.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                          • [param] -nodatalabel <int32> Label for the NoData class. Such input pixels keep their NoData label in the output image and are not handled in the fusion process. By default, 'nodatalabel = 0'.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                          • [param] -undecidedlabel <int32> Label for the Undecided class. Pixels with more than 1 fused class are marked as Undecided. Please note that the Undecided value must be different from existing labels in the input classifications. By default, 'undecidedlabel = 0'.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                          • [param] -out <string> The output classification image resulting from the fusion of the input classification images.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                          • [choice] -method Selection of the fusion method and its parameters. majorityvoting,dempstershafer. Mandatory: True. Default Value: "majorityvoting"
                                                                                                                                                                                                                                                                            • [group] -majorityvoting
                                                                                                                                                                                                                                                                              • [group] -dempstershafer
                                                                                                                                                                                                                                                                                • [param] -method.dempstershafer.cmfl <string> A list of confusion matrix files (*.CSV format) to define the masses of belief and the class labels. Each file should be formatted the following way: the first line, beginning with a '#' symbol, should be a list of the class labels present in the corresponding input classification image, organized in the same order as the confusion matrix rows/columns.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                • [param] -method.dempstershafer.mob <string> Type of confusion matrix measurement used to compute the masses of belief of each classifier.. Mandatory: True. Default Value: "precision"

                                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                                            ImageClassifier application

                                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                                            • il: classification1.tif classification2.tif classification3.tif

                                                                                                                                                                                                                                                                            • method: dempstershafer

                                                                                                                                                                                                                                                                            • method.dempstershafer.cmfl: classification1.csv classification2.csv classification3.csv

                                                                                                                                                                                                                                                                            • method.dempstershafer.mob: precision

                                                                                                                                                                                                                                                                            • nodatalabel: 0

                                                                                                                                                                                                                                                                            • undecidedlabel: 10

                                                                                                                                                                                                                                                                            • out: classification_fused.tif

                                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications.html new file mode 100644 index 000000000000..b5b88b5fc6ff --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/FusionOfClassifications.html @@ -0,0 +1,9 @@ + + +

                                                                                                                                                                                                                                                                            FusionOfClassifications

                                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                                            Fuses several classifications maps of the same image on the basis of class labels.

                                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                                            Learning,Image Analysis

                                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                                            This application allows you to fuse several classification maps and produces a single more robust classification map. Fusion is done either by mean of Majority Voting, or with the Dempster Shafer combination method on class labels. + -MAJORITY VOTING: for each pixel, the class with the highest number of votes is selected. + -DEMPSTER SHAFER: for each pixel, the class label for which the Belief Function is maximal is selected. This Belief Function is calculated by mean of the Dempster Shafer combination of Masses of Belief, and indicates the belief that each input classification map presents for each label value. Moreover, the Masses of Belief are based on the input confusion matrices of each classification map, either by using the PRECISION or RECALL rates, or the OVERALL ACCURACY, or the KAPPA coefficient. Thus, each input classification map needs to be associated with its corresponding input confusion matrix file for the Dempster Shafer fusion. +-Input pixels with the NODATA label are not handled in the fusion of classification maps. Moreover, pixels for which all the input classifiers are set to NODATA keep this value in the output fused image. +-In case of number of votes equality, the UNDECIDED label is attributed to the pixel.

                                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                                            • [param] -il <string> List of input classification maps to fuse. Labels in each classification image must represent the same class.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                            • [param] -nodatalabel <int32> Label for the NoData class. Such input pixels keep their NoData label in the output image and are not handled in the fusion process. By default, 'nodatalabel = 0'.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                            • [param] -undecidedlabel <int32> Label for the Undecided class. Pixels with more than 1 fused class are marked as Undecided. Please note that the Undecided value must be different from existing labels in the input classifications. By default, 'undecidedlabel = 0'.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                            • [param] -out <string> The output classification image resulting from the fusion of the input classification images.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                            • [choice] -method Selection of the fusion method and its parameters. majorityvoting,dempstershafer. Mandatory: True. Default Value: "majorityvoting"
                                                                                                                                                                                                                                                                              • [group] -majorityvoting
                                                                                                                                                                                                                                                                                • [group] -dempstershafer
                                                                                                                                                                                                                                                                                  • [param] -method.dempstershafer.cmfl <string> A list of confusion matrix files (*.CSV format) to define the masses of belief and the class labels. Each file should be formatted the following way: the first line, beginning with a '#' symbol, should be a list of the class labels present in the corresponding input classification image, organized in the same order as the confusion matrix rows/columns.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                  • [param] -method.dempstershafer.mob <string> Type of confusion matrix measurement used to compute the masses of belief of each classifier.. Mandatory: True. Default Value: "precision"

                                                                                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                                                                                              None

                                                                                                                                                                                                                                                                              Authors

                                                                                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                                                                                              See Also

                                                                                                                                                                                                                                                                              ImageClassifier application

                                                                                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                                                                                              • il: classification1.tif classification2.tif classification3.tif

                                                                                                                                                                                                                                                                              • method: dempstershafer

                                                                                                                                                                                                                                                                              • method.dempstershafer.cmfl: classification1.csv classification2.csv classification3.csv

                                                                                                                                                                                                                                                                              • method.dempstershafer.mob: precision

                                                                                                                                                                                                                                                                              • nodatalabel: 0

                                                                                                                                                                                                                                                                              • undecidedlabel: 10

                                                                                                                                                                                                                                                                              • out: classification_fused.tif

                                                                                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GeneratePlyFile.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GeneratePlyFile.html new file mode 100644 index 000000000000..9cefcc9d5b87 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GeneratePlyFile.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                              GeneratePlyFile

                                                                                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                                                                                              Generate a 3D Ply file from a DEM and a color image.

                                                                                                                                                                                                                                                                              Tags

                                                                                                                                                                                                                                                                              Geometry

                                                                                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                                                                                              Generate a 3D Ply file from a DEM and a color image.

                                                                                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                                                                                              • [param] -indem <string> The input DEM. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                              • [param] -incolor <string> The input color image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                              • [param] -out <string> The output Ply file. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                              • [choice] -mode dem,3dgrid. Mandatory: True. Default Value: "dem"
                                                                                                                                                                                                                                                                                • [group] -dem
                                                                                                                                                                                                                                                                                  • [group] -3dgrid
                                                                                                                                                                                                                                                                                    [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                    • [group] -utm
                                                                                                                                                                                                                                                                                      • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                      • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                    • [group] -lambert2
                                                                                                                                                                                                                                                                                      • [group] -lambert93
                                                                                                                                                                                                                                                                                        • [group] -wgs
                                                                                                                                                                                                                                                                                          • [group] -epsg
                                                                                                                                                                                                                                                                                            • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"

                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                        • indem: image_dem.tif

                                                                                                                                                                                                                                                                                        • out: out.ply

                                                                                                                                                                                                                                                                                        • incolor: image_color.tif

                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GenerateRPCSensorModel.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GenerateRPCSensorModel.html new file mode 100644 index 000000000000..63c73dfbd0a2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GenerateRPCSensorModel.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                        GenerateRPCSensorModel

                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                        Generate a RPC sensor model from a list of Ground Control Points.

                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                        Geometry

                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                        This application generates a RPC sensor model from a list of Ground Control Points. At least 20 points are required for estimation wihtout elevation support, and 40 points for estimation with elevation support. Elevation support will be automatically deactivated if an insufficient amount of points is provided. The application can optionnaly output a file containing accuracy statistics for each point, and a vector file containing segments represening points residues. The map projection parameter allows defining a map projection in which the accuracy is evaluated.

                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                        • [param] -outgeom <string> Geom file containing the generated RPC sensor model. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                        • [param] -inpoints <string> Input file containing tie points. Points are stored in following format: col row lon lat. Line beginning with # are ignored.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                        • [param] -outstat <string> Output file containing the following info: ref_lon ref_lat elevation predicted_lon predicted_lat x_error_ref(meters) y_error_ref(meters) global_error_ref(meters) x_error(meters) y_error(meters) overall_error(meters). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                        • [param] -outvector <string> File containing segments representing residues. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                        • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                          • [group] -utm
                                                                                                                                                                                                                                                                                            • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                            • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                          • [group] -lambert2
                                                                                                                                                                                                                                                                                            • [group] -lambert93
                                                                                                                                                                                                                                                                                              • [group] -wgs
                                                                                                                                                                                                                                                                                                • [group] -epsg
                                                                                                                                                                                                                                                                                                  • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"

                                                                                                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                                                                                                              None

                                                                                                                                                                                                                                                                                              Authors

                                                                                                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                                                                                                              See Also

                                                                                                                                                                                                                                                                                              OrthoRectication,HomologousPointsExtraction,RefineSensorModel

                                                                                                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                                                                                                              • outgeom: output.geom

                                                                                                                                                                                                                                                                                              • inpoints: points.txt

                                                                                                                                                                                                                                                                                              • map: epsg

                                                                                                                                                                                                                                                                                              • map.epsg.code: 32631

                                                                                                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-closing.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-closing.html new file mode 100644 index 000000000000..e3081bbf311b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-closing.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                              GrayScaleMorphologicalOperation

                                                                                                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                                                                                                              Performs morphological operations on a grayscale input image

                                                                                                                                                                                                                                                                                              Tags

                                                                                                                                                                                                                                                                                              MorphologicalOperations,Feature Extraction

                                                                                                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                                                                                                              This application performs grayscale morphological operations on a mono band image

                                                                                                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                                                                                                              • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                              • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                              • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                              • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                                                                                                                                • [group] -ball
                                                                                                                                                                                                                                                                                                  • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                  • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                • [group] -cross
                                                                                                                                                                                                                                                                                                  [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                                                                                                                  • [group] -dilate
                                                                                                                                                                                                                                                                                                    • [group] -erode
                                                                                                                                                                                                                                                                                                      • [group] -opening
                                                                                                                                                                                                                                                                                                        • [group] -closing

                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                        itkGrayscaleDilateImageFilter, itkGrayscaleErodeImageFilter, itkGrayscaleMorphologicalOpeningImageFilter and itkGrayscaleMorphologicalClosingImageFilter classes

                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                        • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                        • out: opened.tif

                                                                                                                                                                                                                                                                                                        • channel: 1

                                                                                                                                                                                                                                                                                                        • structype.ball.xradius: 5

                                                                                                                                                                                                                                                                                                        • structype.ball.yradius: 5

                                                                                                                                                                                                                                                                                                        • filter: erode

                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-dilate.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-dilate.html new file mode 100644 index 000000000000..e3081bbf311b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-dilate.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                        GrayScaleMorphologicalOperation

                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                        Performs morphological operations on a grayscale input image

                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                        MorphologicalOperations,Feature Extraction

                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                        This application performs grayscale morphological operations on a mono band image

                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                        • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                        • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                                                                                                                                          • [group] -ball
                                                                                                                                                                                                                                                                                                            • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                            • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                          • [group] -cross
                                                                                                                                                                                                                                                                                                            [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                                                                                                                            • [group] -dilate
                                                                                                                                                                                                                                                                                                              • [group] -erode
                                                                                                                                                                                                                                                                                                                • [group] -opening
                                                                                                                                                                                                                                                                                                                  • [group] -closing

                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                  itkGrayscaleDilateImageFilter, itkGrayscaleErodeImageFilter, itkGrayscaleMorphologicalOpeningImageFilter and itkGrayscaleMorphologicalClosingImageFilter classes

                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                  • out: opened.tif

                                                                                                                                                                                                                                                                                                                  • channel: 1

                                                                                                                                                                                                                                                                                                                  • structype.ball.xradius: 5

                                                                                                                                                                                                                                                                                                                  • structype.ball.yradius: 5

                                                                                                                                                                                                                                                                                                                  • filter: erode

                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-erode.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-erode.html new file mode 100644 index 000000000000..e3081bbf311b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-erode.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                  GrayScaleMorphologicalOperation

                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                  Performs morphological operations on a grayscale input image

                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                  MorphologicalOperations,Feature Extraction

                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                  This application performs grayscale morphological operations on a mono band image

                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                  • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                  • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                  • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                  • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                                                                                                                                                    • [group] -ball
                                                                                                                                                                                                                                                                                                                      • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                      • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                    • [group] -cross
                                                                                                                                                                                                                                                                                                                      [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                                                                                                                                      • [group] -dilate
                                                                                                                                                                                                                                                                                                                        • [group] -erode
                                                                                                                                                                                                                                                                                                                          • [group] -opening
                                                                                                                                                                                                                                                                                                                            • [group] -closing

                                                                                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                                                                                            itkGrayscaleDilateImageFilter, itkGrayscaleErodeImageFilter, itkGrayscaleMorphologicalOpeningImageFilter and itkGrayscaleMorphologicalClosingImageFilter classes

                                                                                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                                                                                            • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                            • out: opened.tif

                                                                                                                                                                                                                                                                                                                            • channel: 1

                                                                                                                                                                                                                                                                                                                            • structype.ball.xradius: 5

                                                                                                                                                                                                                                                                                                                            • structype.ball.yradius: 5

                                                                                                                                                                                                                                                                                                                            • filter: erode

                                                                                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-opening.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-opening.html new file mode 100644 index 000000000000..e3081bbf311b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation-opening.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                            GrayScaleMorphologicalOperation

                                                                                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                                                                                            Performs morphological operations on a grayscale input image

                                                                                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                                                                                            MorphologicalOperations,Feature Extraction

                                                                                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                                                                                            This application performs grayscale morphological operations on a mono band image

                                                                                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                                                                                            • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                            • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                            • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                            • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                                                                                                                                                              • [group] -ball
                                                                                                                                                                                                                                                                                                                                • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                              • [group] -cross
                                                                                                                                                                                                                                                                                                                                [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                                                                                                                                                • [group] -dilate
                                                                                                                                                                                                                                                                                                                                  • [group] -erode
                                                                                                                                                                                                                                                                                                                                    • [group] -opening
                                                                                                                                                                                                                                                                                                                                      • [group] -closing

                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                      None

                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                      itkGrayscaleDilateImageFilter, itkGrayscaleErodeImageFilter, itkGrayscaleMorphologicalOpeningImageFilter and itkGrayscaleMorphologicalClosingImageFilter classes

                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                      • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                      • out: opened.tif

                                                                                                                                                                                                                                                                                                                                      • channel: 1

                                                                                                                                                                                                                                                                                                                                      • structype.ball.xradius: 5

                                                                                                                                                                                                                                                                                                                                      • structype.ball.yradius: 5

                                                                                                                                                                                                                                                                                                                                      • filter: erode

                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation.html new file mode 100644 index 000000000000..e3081bbf311b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GrayScaleMorphologicalOperation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                      GrayScaleMorphologicalOperation

                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                      Performs morphological operations on a grayscale input image

                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                      MorphologicalOperations,Feature Extraction

                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                      This application performs grayscale morphological operations on a mono band image

                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                      • [param] -in <string> The input image to be filtered.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                      • [param] -out <string> Output image containing the filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                      • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                      • [choice] -structype Choice of the structuring element type ball,cross. Mandatory: True. Default Value: "ball"
                                                                                                                                                                                                                                                                                                                                        • [group] -ball
                                                                                                                                                                                                                                                                                                                                          • [param] -structype.ball.xradius <int32> The Structuring Element X Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                          • [param] -structype.ball.yradius <int32> The Structuring Element Y Radius. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                        • [group] -cross
                                                                                                                                                                                                                                                                                                                                          [choice] -filter Choice of the morphological operation dilate,erode,opening,closing. Mandatory: True. Default Value: "dilate"
                                                                                                                                                                                                                                                                                                                                          • [group] -dilate
                                                                                                                                                                                                                                                                                                                                            • [group] -erode
                                                                                                                                                                                                                                                                                                                                              • [group] -opening
                                                                                                                                                                                                                                                                                                                                                • [group] -closing

                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                itkGrayscaleDilateImageFilter, itkGrayscaleErodeImageFilter, itkGrayscaleMorphologicalOpeningImageFilter and itkGrayscaleMorphologicalClosingImageFilter classes

                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                • out: opened.tif

                                                                                                                                                                                                                                                                                                                                                • channel: 1

                                                                                                                                                                                                                                                                                                                                                • structype.ball.xradius: 5

                                                                                                                                                                                                                                                                                                                                                • structype.ball.yradius: 5

                                                                                                                                                                                                                                                                                                                                                • filter: erode

                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/GridBasedImageResampling.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/GridBasedImageResampling.html new file mode 100644 index 000000000000..db4219381fd5 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/GridBasedImageResampling.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                GridBasedImageResampling

                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                Resamples an image according to a resampling grid

                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                Geometry

                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                This application allows performing image resampling from an input resampling grid.

                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                • [param] -grid <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Parameters of the output image. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                  • [group] -nn
                                                                                                                                                                                                                                                                                                                                                    • [group] -linear
                                                                                                                                                                                                                                                                                                                                                      • [group] -bco
                                                                                                                                                                                                                                                                                                                                                        • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                                                                                                                    None

                                                                                                                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                                                                                                                    otbStereorecificationGridGeneration

                                                                                                                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                                                                                                                    • io.in: ROI_IKO_PAN_LesHalles_sub.tif

                                                                                                                                                                                                                                                                                                                                                    • io.out: ROI_IKO_PAN_LesHalles_sub_resampled.tif uint8

                                                                                                                                                                                                                                                                                                                                                    • grid.in: ROI_IKO_PAN_LesHalles_sub_deformation_field.tif

                                                                                                                                                                                                                                                                                                                                                    • out.sizex: 256

                                                                                                                                                                                                                                                                                                                                                    • out.sizey: 256

                                                                                                                                                                                                                                                                                                                                                    • grid.type: def

                                                                                                                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/HaralickTextureExtraction.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/HaralickTextureExtraction.html new file mode 100644 index 000000000000..ef966758bb63 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/HaralickTextureExtraction.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                    HaralickTextureExtraction

                                                                                                                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                                                                                                                    Computes textures on every pixel of the input image selected channel

                                                                                                                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                                                                                                                    Textures,Feature Extraction

                                                                                                                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                                                                                                                    This application computes Haralick, advanced and higher order textures on a mono band image

                                                                                                                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                                                                                                                    • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                    • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                    • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.xrad <int32> X Radius. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.yrad <int32> Y Radius. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.xoff <int32> X Offset. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.yoff <int32> Y Offset. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.min <float> Image Minimum. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.max <float> Image Maximum. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                                                                                                                                                                    • [param] -parameters.nbbin <int32> Histogram number of bin. Mandatory: True. Default Value: "8"
                                                                                                                                                                                                                                                                                                                                                    • [param] -out <string> Output image containing the selected texture features.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                    • [choice] -texture Choice of The Texture Set simple,advanced,higher. Mandatory: True. Default Value: "simple"
                                                                                                                                                                                                                                                                                                                                                      • [group] -simple
                                                                                                                                                                                                                                                                                                                                                        • [group] -advanced
                                                                                                                                                                                                                                                                                                                                                          • [group] -higher

                                                                                                                                                                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                                                                                                                                                                          None

                                                                                                                                                                                                                                                                                                                                                          Authors

                                                                                                                                                                                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                                                                                                                                                                                          See Also

                                                                                                                                                                                                                                                                                                                                                          otbScalarImageToTexturesFilter, otbScalarImageToAdvancedTexturesFilter and otbScalarImageToHigherOrderTexturesFilter classes

                                                                                                                                                                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                                                                                                                                                                          • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                          • channel: 2

                                                                                                                                                                                                                                                                                                                                                          • parameters.xrad: 3

                                                                                                                                                                                                                                                                                                                                                          • parameters.yrad: 3

                                                                                                                                                                                                                                                                                                                                                          • texture: simple

                                                                                                                                                                                                                                                                                                                                                          • out: HaralickTextures.tif

                                                                                                                                                                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/HomologousPointsExtraction.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/HomologousPointsExtraction.html new file mode 100644 index 000000000000..39ef77e1dc46 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/HomologousPointsExtraction.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                          HomologousPointsExtraction

                                                                                                                                                                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                                                                                                                                                                          Compute homologous points between images using keypoints

                                                                                                                                                                                                                                                                                                                                                          Tags

                                                                                                                                                                                                                                                                                                                                                          Feature Extraction

                                                                                                                                                                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                                                                                                                                                                          This application allows computing homologous points between images using keypoints. SIFT or SURF keypoints can be used and the band on which keypoints are computed can be set independantly for both images. The application offers two modes : the first is the full mode where keypoints are extracted from the full extent of both images (please note that in this mode large image file are not supported). The second mode, called geobins, allows one to set-up spatial binning to get fewer points spread across the entire image. In this mode, the corresponding spatial bin in the second image is estimated using geographical transform or sensor modelling, and is padded according to the user defined precision. Last, in both modes the application can filter matches whose colocalisation in first image exceed this precision. The elevation parameters are to deal more precisely with sensor modelling in case of sensor geometry data. The outvector option allows creating a vector file with segments corresponding to the localisation error between the matches. It can be useful to assess the precision of a registration for instance. The vector file is always reprojected to EPSG:4326 to allow display in a GIS. This is done via reprojection or by applying the image sensor models.

                                                                                                                                                                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                                                                                                                                                                          • [param] -in1 <string> First input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                          • [param] -band1 <int32> Index of the band from input image 1 to use for keypoints extraction. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                          • [param] -in2 <string> Second input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                          • [param] -band2 <int32> Index of the band from input image 1 to use for keypoints extraction. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                          • [param] -threshold <float> The distance threshold for matching.. Mandatory: True. Default Value: "0.6"
                                                                                                                                                                                                                                                                                                                                                          • [param] -backmatching <boolean> If set to true, matches should be consistent in both ways.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                          • [param] -precision <float> Estimated precision of the colocalisation function in pixels. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                          • [param] -mfilter <boolean> If enabled, this option allows one to filter matches according to colocalisation from sensor or geographical information, using the given tolerancy expressed in pixels. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                          • [param] -2wgs84 <boolean> . Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                          • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                          • [param] -out <string> File containing the list of tie points. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                          • [param] -outvector <string> File containing segments representing matches . Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                          • [choice] -algorithm Choice of the detection algorithm to use surf,sift. Mandatory: True. Default Value: "surf"
                                                                                                                                                                                                                                                                                                                                                            • [group] -surf
                                                                                                                                                                                                                                                                                                                                                              • [group] -sift
                                                                                                                                                                                                                                                                                                                                                                [choice] -mode full,geobins. Mandatory: True. Default Value: "full"
                                                                                                                                                                                                                                                                                                                                                                • [group] -full
                                                                                                                                                                                                                                                                                                                                                                  • [group] -geobins
                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.geobins.binsize <int32> Radius of the spatial bin in pixels. Mandatory: True. Default Value: "256"
                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.geobins.binsizey <int32> Radius of the spatial bin in pixels (y direction). If not set, the mode.geobins.binsize value is used.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.geobins.binstep <int32> Steps between bins in pixels. Mandatory: True. Default Value: "256"
                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.geobins.binstepy <int32> Steps between bins in pixels (y direction). If not set, the mode.geobins.binstep value is used.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.geobins.margin <int32> Margin from image border to start/end bins (in pixels). Mandatory: True. Default Value: "10"

                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                Full mode does not handle large images.

                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                RefineSensorModel

                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                • in1: sensor_stereo_left.tif

                                                                                                                                                                                                                                                                                                                                                                • in2: sensor_stereo_right.tif

                                                                                                                                                                                                                                                                                                                                                                • mode: full

                                                                                                                                                                                                                                                                                                                                                                • out: homologous.txt

                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/HooverCompareSegmentation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/HooverCompareSegmentation.html new file mode 100644 index 000000000000..7fdbe9a5043f --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/HooverCompareSegmentation.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                HooverCompareSegmentation

                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                Compare two segmentations with Hoover metrics

                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                This application compares a machine segmentation (MS) with a partial ground truth segmentation (GT). The Hoover metrics are used to estimate scores for correct detection, over-segmentation, under-segmentation and missed detection. + The application can output the overall Hoover scores along with coloredimages of the MS and GT segmentation showing the state of each region (correct detection, over-segmentation, under-segmentation, missed) + The Hoover metrics are described in : Hoover et al., "An experimental comparison of range image segmentation algorithms", IEEE PAMI vol. 18, no. 7, July 1996.

                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                • [param] -ingt <string> A partial ground truth segmentation image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -inms <string> A machine segmentation image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -bg <int32> Label value of the background in the input segmentations. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                • [param] -th <float> Overlapping threshold used to find Hoover instances.. Mandatory: True. Default Value: "0.75"
                                                                                                                                                                                                                                                                                                                                                                • [param] -outgt <string> The colored ground truth output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -outms <string> The colored machine segmentation output image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -rc <float> Overall score for correct detection (RC). Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                • [param] -rf <float> Overall score for over segmentation (RF). Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                • [param] -ra <float> Overall score for under segmentation (RA). Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                • [param] -rm <float> Overall score for missed detection (RM). Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                otbHooverMatrixFilter, otbHooverInstanceFilter, otbLabelMapToAttributeImageFilter

                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                • ingt: maur_GT.tif

                                                                                                                                                                                                                                                                                                                                                                • inms: maur_labelled.tif

                                                                                                                                                                                                                                                                                                                                                                • outgt: maur_colored_GT.tif uint8

                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/HyperspectralUnmixing.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/HyperspectralUnmixing.html new file mode 100644 index 000000000000..17e18c1055e8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/HyperspectralUnmixing.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                HyperspectralUnmixing

                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                Estimate abundance maps from an hyperspectral image and a set of endmembers.

                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                Hyperspectral

                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                The application applies a linear unmixing algorithm to an hyperspectral data cube. This method supposes that the mixture between materials in the scene is macroscopic and simulates a linear mixing model of spectra. +The Linear Mixing Model (LMM) acknowledges that reflectance spectrum associated with each pixel is a linear combination of pure materials in the recovery area, commonly known as endmembers. Endmembers can be estimated using the VertexComponentAnalysis application. +The application allows one to estimate the abundance maps with several algorithms : Unconstrained Least Square (ucls), Fully Constrained Least Square (fcls), Image Space Reconstruction Algorithm (isra) and Non-negative constrained Least Square (ncls) and Minimum Dispersion Constrained Non Negative Matrix Factorization (MDMDNMF). +

                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The hyperspectral data cube to unmix. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> The output abundance map. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -ie <string> The endmembers (estimated pure pixels) to use for unmixing. Must be stored as a multispectral image, where each pixel is interpreted as an endmember. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                • [choice] -ua The algorithm to use for unmixing ucls,ncls,isra,mdmdnmf. Mandatory: False. Default Value: "ucls"
                                                                                                                                                                                                                                                                                                                                                                  • [group] -ucls
                                                                                                                                                                                                                                                                                                                                                                    • [group] -ncls
                                                                                                                                                                                                                                                                                                                                                                      • [group] -isra
                                                                                                                                                                                                                                                                                                                                                                        • [group] -mdmdnmf

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        VertexComponentAnalysis

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: cupriteSubHsi.tif

                                                                                                                                                                                                                                                                                                                                                                        • ie: cupriteEndmembers.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: HyperspectralUnmixing.tif double

                                                                                                                                                                                                                                                                                                                                                                        • ua: ucls

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ImageClassifier.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ImageClassifier.html new file mode 100644 index 000000000000..609883188384 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ImageClassifier.html @@ -0,0 +1,16 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        ImageClassifier

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Performs a classification of the input image according to a model file.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Learning

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application performs an image classification based on a model file produced by the TrainImagesClassifier application. Pixels of the output image will contain the class labels decided by the classifier (maximal class label = 65535). The input pixels can be optionally centered and reduced according to the statistics file produced by the ComputeImagesStatistics application. An optional input mask can be provided, in which case only input image pixels whose corresponding mask value is greater than 0 will be classified. The remaining of pixels will be given the label 0 in the output image.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image to classify.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -mask <string> The mask allows restricting classification of the input image to the area where mask pixel values are greater than 0.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -model <string> A model file (produced by TrainImagesClassifier application, maximal class label = 65535).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -imstat <string> A XML file containing mean and standard deviation to center and reduce samples before classification (produced by ComputeImagesStatistics application).. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output image containing class labels. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -confmap <string> Confidence map of the produced classification. The confidence index depends on the model : + - LibSVM : difference between the two highest probabilities (needs a model with probability estimates, so that classes probabilities can be computed for each sample) + - OpenCV + * Boost : sum of votes + * DecisionTree : (not supported) + * GradientBoostedTree : (not supported) + * KNearestNeighbors : number of neighbors with the same label + * NeuralNetwork : difference between the two highest responses + * NormalBayes : (not supported) + * RandomForest : Confidence (proportion of votes for the majority class). Margin (normalized difference of the votes of the 2 majority classes) is not available for now. + * SVM : distance to margin (only works for 2-class models) +. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        The input image must have the same type, order and number of bands than the images used to produce the statistics file and the SVM model file. If a statistics file was used during training by the TrainImagesClassifier, it is mandatory to use the same statistics file for classification. If an input mask is used, its size must match the input image size.

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        TrainImagesClassifier, ValidateImagesClassifier, ComputeImagesStatistics

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                        • imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                        • model: clsvmModelQB1.svm

                                                                                                                                                                                                                                                                                                                                                                        • out: clLabeledImageQB1.tif

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ImageEnvelope.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ImageEnvelope.html new file mode 100644 index 000000000000..6b0e00023b41 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ImageEnvelope.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        ImageEnvelope

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Extracts an image envelope.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Geometry

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        Build a vector data containing the polygon of the image envelope.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Vector data file containing the envelope. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -sr <int32> Sampling rate for image edges (in pixel). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -proj <string> Projection to be used to compute the envelope (default is WGS84). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: ImageEnvelope.shp

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/KMeansClassification.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/KMeansClassification.html new file mode 100644 index 000000000000..47414f7b94d3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/KMeansClassification.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        KMeansClassification

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Unsupervised KMeans image classification

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Segmentation,Learning

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        Performs unsupervised KMeans image classification.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image to classify.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output image containing the class indexes.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -vm <string> Validity mask. Only non-zero pixels will be used to estimate KMeans modes.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ts <int32> Size of the training set (in pixels).. Mandatory: False. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -nc <int32> Number of modes, which will be used to generate class membership.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -maxit <int32> Maximum number of iterations for the learning step.. Mandatory: False. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ct <float> Convergence threshold for class centroid (L2 distance, by default 0.0001).. Mandatory: False. Default Value: "0.0001"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outmeans <string> Output text file containing centroid positions. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                        • ts: 1000

                                                                                                                                                                                                                                                                                                                                                                        • nc: 5

                                                                                                                                                                                                                                                                                                                                                                        • maxit: 1000

                                                                                                                                                                                                                                                                                                                                                                        • ct: 0.0001

                                                                                                                                                                                                                                                                                                                                                                        • out: ClassificationFilterOutput.tif

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/KmzExport.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/KmzExport.html new file mode 100644 index 000000000000..98c54781ec2e --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/KmzExport.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        KmzExport

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Export the input image in a KMZ product.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        KMZ,Export

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application exports the input image in a kmz product that can be display in the Google Earth software. The user can set the size of the product size, a logo and a legend to the product. Furthemore, to obtain a product that fits the relief, a DEM can be used.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output Kmz product directory (with .kmz extension). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesize <int32> Size of the tiles in the kmz product, in number of pixels (default = 512).. Mandatory: False. Default Value: "512"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -logo <string> Path to the image logo to add to the KMZ product.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -legend <string> Path to the image legend to add to the KMZ product.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        Conversion

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: qb_RoadExtract2.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: otbKmzExport.kmz

                                                                                                                                                                                                                                                                                                                                                                        • logo: otb_big.png

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSegmentation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSegmentation.html new file mode 100644 index 000000000000..6d07dcf15518 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSegmentation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        LSMSSegmentation

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Second step of the exact Large-Scale Mean-Shift segmentation workflow.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Segmentation,LSMS

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application performs the second step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Filtered range image and spatial image should be created with the MeanShiftSmoothing application, with modesearch parameter disabled. If spatial image is not set, the application will only process the range image and spatial radius parameter will not be taken into account. This application will produce a labeled image where neighbor pixels whose range distance is below range radius (and optionally spatial distance below spatial radius) will be grouped together into the same cluster. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results. Please note that this application will generate a lot of temporary files (as many as the number of tiles), and will therefore require twice the size of the final result in term of disk space. The cleanup option (activated by default) allows removing all temporary file as soon as they are not needed anymore (if cleanup is activated, tmpdir set and tmpdir does not exists before running the application, it will be removed as well during cleanup). The tmpdir option allows defining a directory where to write the temporary files. Please also note that the output image type should be set to uint32 to ensure that there are enough labels available.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The filtered image (cf. Adaptive MeanShift Smoothing application).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inpos <string> The spatial image. Spatial input is the displacement map (output of the Adaptive MeanShift Smoothing application).. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> The output image. The output image is the segmentation of the filtered image. It is recommended to set the pixel type to uint32.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space.. Mandatory: False. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -spatialr <float> Spatial radius of the neighborhood.. Mandatory: False. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -minsize <int32> Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is deleted.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesizex <int32> Size of tiles along the X-axis.. Mandatory: True. Default Value: "500"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesizey <int32> Size of tiles along the Y-axis.. Mandatory: True. Default Value: "500"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tmpdir <string> This applications need to write temporary files for each tile. This parameter allows choosing the path where to write those files. If disabled, the current path will be used.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -cleanup <boolean> If activated, the application will try to clean all temporary files it created. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        David Youssefi

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        MeanShiftSmoothing, LSMSSmallRegionsMerging, LSMSVectorization

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: smooth.tif

                                                                                                                                                                                                                                                                                                                                                                        • inpos: position.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: segmentation.tif

                                                                                                                                                                                                                                                                                                                                                                        • ranger: 15

                                                                                                                                                                                                                                                                                                                                                                        • spatialr: 5

                                                                                                                                                                                                                                                                                                                                                                        • minsize: 0

                                                                                                                                                                                                                                                                                                                                                                        • tilesizex: 256

                                                                                                                                                                                                                                                                                                                                                                        • tilesizey: 256

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSmallRegionsMerging.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSmallRegionsMerging.html new file mode 100644 index 000000000000..b293794cb450 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSSmallRegionsMerging.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        LSMSSmallRegionsMerging

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Third (optional) step of the exact Large-Scale Mean-Shift segmentation workflow.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Segmentation,LSMS

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application performs the third step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image) and the original image, it will merge regions whose size in pixels is lower than minsize parameter with the adjacent regions with the adjacent region with closest radiometry and acceptable size. Small regions will be processed by size: first all regions of area, which is equal to 1 pixel will be merged with adjacent region, then all regions of area equal to 2 pixels, until regions of area minsize. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inseg <string> The segmented image input. Segmented image input is the segmentation of the input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> The output image. The output image is the input image where the minimal regions have been merged.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -minsize <int32> Minimum Region Size. If, after the segmentation, a region is of size lower than this criterion, the region is merged with the "nearest" region (radiometrically).. Mandatory: False. Default Value: "50"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesizex <int32> Size of tiles along the X-axis.. Mandatory: True. Default Value: "500"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesizey <int32> Size of tiles along the Y-axis.. Mandatory: True. Default Value: "500"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        David Youssefi

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        LSMSSegmentation, LSMSVectorization, MeanShiftSmoothing

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: smooth.tif

                                                                                                                                                                                                                                                                                                                                                                        • inseg: segmentation.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: merged.tif

                                                                                                                                                                                                                                                                                                                                                                        • minsize: 20

                                                                                                                                                                                                                                                                                                                                                                        • tilesizex: 256

                                                                                                                                                                                                                                                                                                                                                                        • tilesizey: 256

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSVectorization.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSVectorization.html new file mode 100644 index 000000000000..5414a039181e --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/LSMSVectorization.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        LSMSVectorization

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Fourth step of the exact Large-Scale Mean-Shift segmentation workflow.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Segmentation,LSMS

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application performs the fourth step of the exact Large-Scale Mean-Shift segmentation workflow (LSMS). Given a segmentation result (label image), that may have been processed for small regions merging or not, it will convert it to a GIS vector file containing one polygon per segment. Each polygon contains additional fields: mean and variance of each channels from input image (in parameter), segmentation image label, number of pixels in the polygon. For large images one can use the nbtilesx and nbtilesy parameters for tile-wise processing, with the guarantees of identical results.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inseg <string> The segmented image input. Segmented image input is the segmentation of the input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> The output GIS vector file, representing the vectorized version of the segmented image where the features of the polygons are the radiometric means and variances.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesizex <int32> Size of tiles along the X-axis.. Mandatory: True. Default Value: "500"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -tilesizey <int32> Size of tiles along the Y-axis.. Mandatory: True. Default Value: "500"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        This application is part of the Large-Scale Mean-Shift segmentation workflow (LSMS) and may not be suited for any other purpose.

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        David Youssefi

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        MeanShiftSmoothing, LSMSSegmentation, LSMSSmallRegionsMerging

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: avions.tif

                                                                                                                                                                                                                                                                                                                                                                        • inseg: merged.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: vector.shp

                                                                                                                                                                                                                                                                                                                                                                        • tilesizex: 256

                                                                                                                                                                                                                                                                                                                                                                        • tilesizey: 256

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/LineSegmentDetection.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/LineSegmentDetection.html new file mode 100644 index 000000000000..ca90896346a1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/LineSegmentDetection.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        LineSegmentDetection

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Detect line segments in raster

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Feature Extraction

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application detects locally straight contours in a image. It is based on Burns, Hanson, and Riseman method and use an a contrario validation approach (Desolneux, Moisan, and Morel). The algorithm was published by Rafael Gromponevon Gioi, Jérémie Jakubowicz, Jean-Michel Morel and Gregory Randall. + The given approach computes gradient and level lines of the image and detects aligned points in line support region. The application allows exporting the detected lines in a vector data.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image on which lines will be detected.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output detected line segments (vector data).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -norescale <boolean> By default, the input image amplitude is rescaled between [0,255]. Turn on this parameter to skip rescaling. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        On Line demonstration of the LSD algorithm is available here: http://www.ipol.im/pub/algo/gjmr_line_segment_detector/ +

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: QB_Suburb.png

                                                                                                                                                                                                                                                                                                                                                                        • out: LineSegmentDetection.shp

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/LocalStatisticExtraction.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/LocalStatisticExtraction.html new file mode 100644 index 000000000000..6ff7bc151aa1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/LocalStatisticExtraction.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        LocalStatisticExtraction

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Computes local statistical moments on every pixel in the selected channel of the input image

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Statistics,Feature Extraction

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application computes the 4 local statistical moments on every pixel in the selected channel of the input image, over a specified neighborhood. The output image is multi band with one statistical moment (feature) per band. Thus, the 4 output features are the Mean, the Variance, the Skewness and the Kurtosis. They are provided in this exact order in the output image.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -radius <int32> The computational window radius.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output image containing the local statistical moments.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        otbRadiometricMomentsImageFunction class

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                        • channel: 1

                                                                                                                                                                                                                                                                                                                                                                        • radius: 3

                                                                                                                                                                                                                                                                                                                                                                        • out: Statistics.tif

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ManageNoData.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ManageNoData.html new file mode 100644 index 000000000000..ab86a07b1275 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ManageNoData.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        ManageNoData

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Manage No-Data

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Conversion,Image Dynamic,Image Manipulation

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application has two modes. The first allows building a mask of no-data pixels from the no-data flags read from the image file. The second allows updating the change the no-data value of an image (pixels value and metadata). This last mode also allows replacing NaN in images with a proper no-data value. To do so, one should activate the NaN is no-data option.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -usenan <boolean> If active, the application will consider NaN as no-data values as well. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [choice] -mode Allows choosing between different no-data handling options buildmask,changevalue,apply. Mandatory: True. Default Value: "buildmask"
                                                                                                                                                                                                                                                                                                                                                                          • [group] -buildmask
                                                                                                                                                                                                                                                                                                                                                                            • [param] -mode.buildmask.inv <float> Value given in the output mask to pixels that are not no data pixels. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                            • [param] -mode.buildmask.outv <float> Value given in the output mask to pixels that are no data pixels. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [group] -changevalue
                                                                                                                                                                                                                                                                                                                                                                            • [param] -mode.changevalue.newv <float> The new no-data value. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [group] -apply
                                                                                                                                                                                                                                                                                                                                                                            • [param] -mode.apply.mask <string> Mask to be applied on input image (valid pixels have non null values). Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        BanMath

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: QB_Toulouse_Ortho_XS_nodatamask.tif uint8

                                                                                                                                                                                                                                                                                                                                                                        • mode.buildmask.inv: 255

                                                                                                                                                                                                                                                                                                                                                                        • mode.buildmask.outv: 0

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/MeanShiftSmoothing.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/MeanShiftSmoothing.html new file mode 100644 index 000000000000..491953882a83 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/MeanShiftSmoothing.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        MeanShiftSmoothing

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Perform mean shift filtering

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Image Filtering,LSMS

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application performs mean shift fitlering (multi-threaded).

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -fout <string> The filtered output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -foutpos <string> The spatial image output. Spatial image output is a displacement map (pixel position after convergence).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -spatialr <int32> Spatial radius of the neighborhood.. Mandatory: False. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multi-spectral space.. Mandatory: False. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: False. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -rangeramp <float> This coefficient makes dependent the ranger of the colorimetry of the filtered pixel : y = rangeramp*x+ranger.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -modesearch <boolean> If activated pixel iterative convergence is stopped if the path . Be careful, with this option, the result will slightly depend on thread number. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        With mode search option, the result will slightly depend on thread number.

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: maur_rgb.png

                                                                                                                                                                                                                                                                                                                                                                        • fout: MeanShift_FilterOutput.tif

                                                                                                                                                                                                                                                                                                                                                                        • foutpos: MeanShift_SpatialOutput.tif

                                                                                                                                                                                                                                                                                                                                                                        • spatialr: 16

                                                                                                                                                                                                                                                                                                                                                                        • ranger: 16

                                                                                                                                                                                                                                                                                                                                                                        • thres: 0.1

                                                                                                                                                                                                                                                                                                                                                                        • maxiter: 100

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/MultiResolutionPyramid.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/MultiResolutionPyramid.html new file mode 100644 index 000000000000..35f527bb0353 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/MultiResolutionPyramid.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        MultiResolutionPyramid

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Build a multi-resolution pyramid of the image.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Conversion,Image Manipulation,Image MultiResolution,Util

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application builds a multi-resolution pyramid of the input image. User can specified the number of levels of the pyramid and the subsampling factor. To speed up the process, you can use the fast scheme option

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> . Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> will be used to get the prefix and the extension of the images to write. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -level <int32> Number of levels in the pyramid (default is 1).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -sfactor <int32> Subsampling factor between each level of the pyramid (default is 2).. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -vfactor <float> Variance factor use in smoothing. It is multiplied by the subsampling factor of each level in the pyramid (default is 0.6).. Mandatory: True. Default Value: "0.6"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -fast <boolean> If used, this option allows one to speed-up computation by iteratively subsampling previous level of pyramid instead of processing the full input.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: multiResolutionImage.tif

                                                                                                                                                                                                                                                                                                                                                                        • level: 1

                                                                                                                                                                                                                                                                                                                                                                        • sfactor: 2

                                                                                                                                                                                                                                                                                                                                                                        • vfactor: 0.6

                                                                                                                                                                                                                                                                                                                                                                        • fast: false

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/MultivariateAlterationDetector.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/MultivariateAlterationDetector.html new file mode 100644 index 000000000000..2505ba3cba15 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/MultivariateAlterationDetector.html @@ -0,0 +1,21 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        MultivariateAlterationDetector

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Multivariate Alteration Detector

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Feature Extraction

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application detects change between two given images.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -in1 <string> Image which describe initial state of the scene.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -in2 <string> Image which describe scene after perturbations.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Image of detected changes.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                        This filter implements the Multivariate Alteration Detector, based on the following work: + A. A. Nielsen and K. Conradsen, Multivariate alteration detection (mad) in multispectral, bi-temporal image data: a new approach to change detection studies, Remote Sens. Environ., vol. 64, pp. 1-19, (1998) + + Multivariate Alteration Detector takes two images as inputs and produce a set of N change maps as a VectorImage (where N is the maximum of number of bands in first and second image) with the following properties: + - Change maps are differences of a pair of linear combinations of bands from image 1 and bands from image 2 chosen to maximize the correlation. + - Each change map is orthogonal to the others. + + This is a statistical method which can handle different modalities and even different bands and number of bands between images. + + If numbers of bands in image 1 and 2 are equal, then change maps are sorted by increasing correlation. If number of bands is different, the change maps are sorted by decreasing correlation. + + The GetV1() and GetV2() methods allow retrieving the linear combinations used to generate the Mad change maps as a vnl_matrix of double, and the GetRho() method allows retrieving the correlation associated to each Mad change maps as a vnl_vector. + + This filter has been implemented from the Matlab code kindly made available by the authors here: + http://www2.imm.dtu.dk/~aa/software.html + + Both cases (same and different number of bands) have been validated by comparing the output image to the output produced by the Matlab code, and the reference images for testing have been generated from the Matlab code using Octave.

                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                        • in1: Spot5-Gloucester-before.tif

                                                                                                                                                                                                                                                                                                                                                                        • in2: Spot5-Gloucester-after.tif

                                                                                                                                                                                                                                                                                                                                                                        • out: detectedChangeImage.tif

                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OGRLayerClassifier.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OGRLayerClassifier.html new file mode 100644 index 000000000000..9b8b14bf2ff0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OGRLayerClassifier.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                        OGRLayerClassifier

                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                        Classify an OGR layer based on a machine learning model and a list of features to consider.

                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                        Segmentation

                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                        This application will apply a trained machine learning model on the selected feature to get a classification of each geometry contained in an OGR layer. The list of feature must match the list used for training. The predicted label is written in the user defined field for each geometry.

                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                        • [param] -inshp <string> Name of the input shapefile. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -instats <string> XML file containing mean and variance of each feature.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -insvm <string> Input model filename.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -cfield <string> Field containing the predicted class. Mandatory: True. Default Value: "predicted"
                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                        • [choice] -feat Features to be calculated . Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                                                                                                                                                                                          Experimental. Only shapefiles are supported for now.

                                                                                                                                                                                                                                                                                                                                                                          Authors

                                                                                                                                                                                                                                                                                                                                                                          David Youssefi during internship at CNES

                                                                                                                                                                                                                                                                                                                                                                          See Also

                                                                                                                                                                                                                                                                                                                                                                          ComputeOGRLayersFeaturesStatistics,TrainOGRLayersClassifier

                                                                                                                                                                                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                                                                                                                                                                                          • inshp: vectorData.shp

                                                                                                                                                                                                                                                                                                                                                                          • instats: meanVar.xml

                                                                                                                                                                                                                                                                                                                                                                          • insvm: svmModel.svm

                                                                                                                                                                                                                                                                                                                                                                          • feat: perimeter

                                                                                                                                                                                                                                                                                                                                                                          • cfield: predicted

                                                                                                                                                                                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OSMDownloader.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OSMDownloader.html new file mode 100644 index 000000000000..e675bf1e6653 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OSMDownloader.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                          OSMDownloader

                                                                                                                                                                                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                                                                                                                                                                                          Generate a vector data from OSM on the input image extend

                                                                                                                                                                                                                                                                                                                                                                          Tags

                                                                                                                                                                                                                                                                                                                                                                          Image MetaData

                                                                                                                                                                                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                                                                                                                                                                                          Generate a vector data from Open Street Map data. A DEM could be use. By default, the entire layer is downloaded, an image can be use as support for the OSM data. The application can provide also available classes in layers . This application required an Internet access. Information about the OSM project : http://www.openstreetmap.fr/

                                                                                                                                                                                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                                                                                                                                                                                          • [param] -out <string> Generated output vector data path. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -support <string> Image used as support to estimate the models. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -key <string> OSM tag key to extract (highway, building...). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -value <string> OSM tag value to extract (motorway, footway...). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -printclasses <boolean> Print the key/value classes available for the bounding box of the input image + ** If not used : Note that the options OSMKey (-key) and Output (-out) become mandatory. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                                                                                                                                                                                          None

                                                                                                                                                                                                                                                                                                                                                                          Authors

                                                                                                                                                                                                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                                                                                                                                                                                                          See Also

                                                                                                                                                                                                                                                                                                                                                                          Conversion

                                                                                                                                                                                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                                                                                                                                                                                          • support: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                          • key: highway

                                                                                                                                                                                                                                                                                                                                                                          • out: apTvUtOSMDownloader.shp

                                                                                                                                                                                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ObtainUTMZoneFromGeoPoint.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ObtainUTMZoneFromGeoPoint.html new file mode 100644 index 000000000000..eb416fdd3d84 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ObtainUTMZoneFromGeoPoint.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                          ObtainUTMZoneFromGeoPoint

                                                                                                                                                                                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                                                                                                                                                                                          UTM zone determination from a geographic point.

                                                                                                                                                                                                                                                                                                                                                                          Tags

                                                                                                                                                                                                                                                                                                                                                                          Coordinates

                                                                                                                                                                                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                                                                                                                                                                                          This application returns the UTM zone of an input geographic point.

                                                                                                                                                                                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                                                                                                                                                                                          • [param] -lat <float> Latitude value of desired point.. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -lon <float> Longitude value of desired point.. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -utm <int32> UTM Zone. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                                                                                                                                                                                          None

                                                                                                                                                                                                                                                                                                                                                                          Authors

                                                                                                                                                                                                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                                                                                                                                                                                                          See Also

                                                                                                                                                                                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                                                                                                                                                                                          Obtain a UTM Zone
                                                                                                                                                                                                                                                                                                                                                                          • lat: 10.0

                                                                                                                                                                                                                                                                                                                                                                          • lon: 124.0

                                                                                                                                                                                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-epsg.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-epsg.html new file mode 100644 index 000000000000..c90885e2c5c0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-epsg.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                          OrthoRectification

                                                                                                                                                                                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                                                                                                                                                                                          This application allows ortho-rectification of optical images from supported sensors. +

                                                                                                                                                                                                                                                                                                                                                                          Tags

                                                                                                                                                                                                                                                                                                                                                                          Geometry

                                                                                                                                                                                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                                                                                                                                                                                          An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                                                                                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                                                                                                                                                                                          • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                          • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                                                                                                            • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                              • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                              • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                            • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                              • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                  • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                                                                                                                                                                                                                                                                                  [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                  • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                  • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                    • [group] -linear

                                                                                                                                                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                                                                                                                                                    Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                                                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                                                                                                                                                    Ortho-rectification chapter from the OTB Software Guide

                                                                                                                                                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                                                                                                                                                    • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                                                                                                                                                                                    • io.out: QB_Toulouse_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-fit-to-ortho.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-fit-to-ortho.html new file mode 100644 index 000000000000..c90885e2c5c0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-fit-to-ortho.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                    OrthoRectification

                                                                                                                                                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                                                                                                                                                    This application allows ortho-rectification of optical images from supported sensors. +

                                                                                                                                                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                                                                                                                                                    Geometry

                                                                                                                                                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                                                                                                                                                    An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                                                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                                                                                                                                                    • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                    • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                                                                                                                      • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                                        • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                                        • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                      • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                                        • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                          • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                            • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                                                                                                                                                                                                                                                                                            [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                            • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                            • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                              • [group] -linear

                                                                                                                                                                                                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                                                                                                                                                                                                              Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                                                                                                                                                                                                                                                                                              Authors

                                                                                                                                                                                                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                              See Also

                                                                                                                                                                                                                                                                                                                                                                                              Ortho-rectification chapter from the OTB Software Guide

                                                                                                                                                                                                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                                                                                                                                                                                                              • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                                                                                                                                                                                              • io.out: QB_Toulouse_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-lambert-WGS84.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-lambert-WGS84.html new file mode 100644 index 000000000000..c90885e2c5c0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-lambert-WGS84.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                              OrthoRectification

                                                                                                                                                                                                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                                                                                                                                                                                                              This application allows ortho-rectification of optical images from supported sensors. +

                                                                                                                                                                                                                                                                                                                                                                                              Tags

                                                                                                                                                                                                                                                                                                                                                                                              Geometry

                                                                                                                                                                                                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                                                                                                                                                                                                              An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                                                                                                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                                                                                                                                                                                                              • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                              • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                                                                                                                                • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                                                                                                                                                                                                                                                                                                      [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -linear

                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                        Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                        Ortho-rectification chapter from the OTB Software Guide

                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                        • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                                                                                                                                                                                                        • io.out: QB_Toulouse_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-utm.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-utm.html new file mode 100644 index 000000000000..c90885e2c5c0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification-utm.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                        OrthoRectification

                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                        This application allows ortho-rectification of optical images from supported sensors. +

                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                        Geometry

                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                        An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                                                                                                                                                                                                                                                                                                                [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -linear

                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                  Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                  Ortho-rectification chapter from the OTB Software Guide

                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                  • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                                                                                                                                                                                                                  • io.out: QB_Toulouse_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification.html new file mode 100644 index 000000000000..c90885e2c5c0 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/OrthoRectification.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                  OrthoRectification

                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows ortho-rectification of optical images from supported sensors. +

                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                  Geometry

                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                  An inverse sensor model is built from the input image metadata to convert geographical to raw geometry coordinates. This inverse sensor model is then combined with the chosen map projection to build a global coordinate mapping grid. Last, this grid is used to resample using the chosen interpolation algorithm. A Digital Elevation Model can be specified to account for terrain deformations. +In case of SPOT5 images, the sensor model can be approximated by an RPC model in order to speed-up computation.

                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outputs <string> This group of parameters allows one to define the grid on which the input image will be resampled.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -opt <string> This group of parameters allows optimization of processing time.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"
                                                                                                                                                                                                                                                                                                                                                                                                                          [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -interpolator.bco.radius <int32> This parameter allows one to control the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -linear

                                                                                                                                                                                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                            Supported sensors are Pleiades, SPOT5 (TIF format), Ikonos, Quickbird, Worldview2, GeoEye.

                                                                                                                                                                                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                                                                                                                                                                                            Ortho-rectification chapter from the OTB Software Guide

                                                                                                                                                                                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                            • io.in: QB_TOULOUSE_MUL_Extract_500_500.tif

                                                                                                                                                                                                                                                                                                                                                                                                                            • io.out: QB_Toulouse_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-bayes.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-bayes.html new file mode 100644 index 000000000000..dd25169010ad --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-bayes.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                            Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                            Perform P+XS pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                                                                                                                                                                                            Geometry,Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                            This application performs P+XS pansharpening. Pansharpening is a process of merging high-resolution panchromatic and lower resolution multispectral imagery to create a single high-resolution color image. Algorithms available in the applications are: RCS, bayesian fusion and Local Mean and Variance Matching(LMVM).

                                                                                                                                                                                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -inp <string> Input panchromatic image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -inxs <string> Input XS image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                            • [choice] -method Selection of the pan-sharpening method. rcs,lmvm,bayes. Mandatory: True. Default Value: "rcs"
                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -rcs
                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -lmvm
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -method.lmvm.radiusx <int32> Set the x radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -method.lmvm.radiusy <int32> Set the y radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -method.bayes.lambda <float> Set the weighting value.. Mandatory: True. Default Value: "0.9999"
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -method.bayes.s <float> Set the S coefficient.. Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                              None

                                                                                                                                                                                                                                                                                                                                                                                                                              Authors

                                                                                                                                                                                                                                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                              See Also

                                                                                                                                                                                                                                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                              • inp: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                              • inxs: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                              • out: Pansharpening.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-lmvm.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-lmvm.html new file mode 100644 index 000000000000..dd25169010ad --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-lmvm.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                              Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                              Perform P+XS pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                              Tags

                                                                                                                                                                                                                                                                                                                                                                                                                              Geometry,Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                              This application performs P+XS pansharpening. Pansharpening is a process of merging high-resolution panchromatic and lower resolution multispectral imagery to create a single high-resolution color image. Algorithms available in the applications are: RCS, bayesian fusion and Local Mean and Variance Matching(LMVM).

                                                                                                                                                                                                                                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -inp <string> Input panchromatic image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -inxs <string> Input XS image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                              • [choice] -method Selection of the pan-sharpening method. rcs,lmvm,bayes. Mandatory: True. Default Value: "rcs"
                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -rcs
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -lmvm
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -method.lmvm.radiusx <int32> Set the x radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -method.lmvm.radiusy <int32> Set the y radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -method.bayes.lambda <float> Set the weighting value.. Mandatory: True. Default Value: "0.9999"
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -method.bayes.s <float> Set the S coefficient.. Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                • inp: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                • inxs: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                • out: Pansharpening.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-rcs.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-rcs.html new file mode 100644 index 000000000000..dd25169010ad --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening-rcs.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                Perform P+XS pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                Geometry,Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                This application performs P+XS pansharpening. Pansharpening is a process of merging high-resolution panchromatic and lower resolution multispectral imagery to create a single high-resolution color image. Algorithms available in the applications are: RCS, bayesian fusion and Local Mean and Variance Matching(LMVM).

                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inp <string> Input panchromatic image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxs <string> Input XS image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -method Selection of the pan-sharpening method. rcs,lmvm,bayes. Mandatory: True. Default Value: "rcs"
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -rcs
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -lmvm
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -method.lmvm.radiusx <int32> Set the x radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -method.lmvm.radiusy <int32> Set the y radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -method.bayes.lambda <float> Set the weighting value.. Mandatory: True. Default Value: "0.9999"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -method.bayes.s <float> Set the S coefficient.. Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                  • inp: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                  • inxs: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: Pansharpening.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening.html new file mode 100644 index 000000000000..dd25169010ad --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Pansharpening.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                  Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                  Perform P+XS pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                  Geometry,Pansharpening

                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                  This application performs P+XS pansharpening. Pansharpening is a process of merging high-resolution panchromatic and lower resolution multispectral imagery to create a single high-resolution color image. Algorithms available in the applications are: RCS, bayesian fusion and Local Mean and Variance Matching(LMVM).

                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inp <string> Input panchromatic image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxs <string> Input XS image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -method Selection of the pan-sharpening method. rcs,lmvm,bayes. Mandatory: True. Default Value: "rcs"
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -rcs
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -lmvm
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -method.lmvm.radiusx <int32> Set the x radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -method.lmvm.radiusy <int32> Set the y radius of the sliding window.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -method.bayes.lambda <float> Set the weighting value.. Mandatory: True. Default Value: "0.9999"
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -method.bayes.s <float> Set the S coefficient.. Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                    None

                                                                                                                                                                                                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                    • inp: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                    • inxs: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                    • out: Pansharpening.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/PixelValue.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/PixelValue.html new file mode 100644 index 000000000000..53b7cab54fcf --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/PixelValue.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                    PixelValue

                                                                                                                                                                                                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                    Get the value of a pixel.

                                                                                                                                                                                                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                    Utilities,Coordinates,Raster

                                                                                                                                                                                                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                    Get the value of a pixel. +Pay attention, index starts at 0.

                                                                                                                                                                                                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -in <string> Input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -coordx <int32> Column index of the wanted pixel (starts at 0).. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -coordy <int32> Line index of the wanted pixel (starts at 0).. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -value <string> Pixel radiometric value. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                    • [choice] -cl Displayed channels . Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                      None

                                                                                                                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                      • in: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                      • coordx: 50

                                                                                                                                                                                                                                                                                                                                                                                                                                      • coordy: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                      • cl: Channel1

                                                                                                                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/PolygonClassStatistics.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/PolygonClassStatistics.html new file mode 100644 index 000000000000..5c21f9f73f34 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/PolygonClassStatistics.html @@ -0,0 +1,12 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                      PolygonClassStatistics

                                                                                                                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                      Computes statistics on a training polygon set.

                                                                                                                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                      Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                      The application processes a set of geometries intended for training (they should have a field giving the associated class). The geometries are analysed against a support image to compute statistics : + - number of samples per class + - number of samples per geometry +An optional raster mask can be used to discard samples. Different types of geometry are supported : polygons, lines, points. The behaviour is different for each type of geometry : + - polygon: select pixels whose center is inside the polygon + - lines : select pixels intersecting the line + - points : select closest pixel to the point +

                                                                                                                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -in <string> Support image that will be classified. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mask <string> Validity mask (only pixels corresponding to a mask value greater than 0 will be used for statistics). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -vec <string> Input geometries to analyse. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -out <string> Output file to store statistics (XML format). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -field <string> Name of the field carrying the class name in the input vectors.. Mandatory: False. Default Value: "class"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -layer <int32> Layer index to read in the input vector file.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                      None

                                                                                                                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                      • in: support_image.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                      • vec: variousVectors.sqlite

                                                                                                                                                                                                                                                                                                                                                                                                                                      • field: label

                                                                                                                                                                                                                                                                                                                                                                                                                                      • out: polygonStat.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/PredictRegression.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/PredictRegression.html new file mode 100644 index 000000000000..d86079ee3811 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/PredictRegression.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                      PredictRegression

                                                                                                                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                      Performs a prediction of the input image according to a regression model file.

                                                                                                                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                      Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                      This application predict output values from an input image, based on a regression model file produced by the TrainRegression application. Pixels of the output image will contain the predicted values fromthe regression model (single band). The input pixels can be optionally centered and reduced according to the statistics file produced by the ComputeImagesStatistics application. An optional input mask can be provided, in which case only input image pixels whose corresponding mask value is greater than 0 will be processed. The remaining of pixels will be given the value 0 in the output image.

                                                                                                                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -in <string> The input image to predict.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mask <string> The mask allow restricting classification of the input image to the area where mask pixel values are greater than 0.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -model <string> A regression model file (produced by TrainRegression application).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -imstat <string> A XML file containing mean and standard deviation to center and reduce samples before prediction (produced by ComputeImagesStatistics application). If this file containsone more band than the sample size, the last stat of last band will beapplied to expand the output predicted value. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -out <string> Output image containing predicted values. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                      The input image must contain the feature bands used for the model training (without the predicted value). If a statistics file was used during training by the TrainRegression, it is mandatory to use the same statistics file for prediction. If an input mask is used, its size must match the input image size.

                                                                                                                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                      TrainRegression, ComputeImagesStatistics

                                                                                                                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                      • in: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                      • imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                      • model: clsvmModelQB1.svm

                                                                                                                                                                                                                                                                                                                                                                                                                                      • out: clLabeledImageQB1.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Quicklook.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Quicklook.html new file mode 100644 index 000000000000..c84a0abaf342 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Quicklook.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                      Quicklook

                                                                                                                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                      Generates a subsampled version of an image extract

                                                                                                                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                      Image Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                      Generates a subsampled version of an extract of an image defined by ROIStart and ROISize. + This extract is subsampled using the ratio OR the output image Size.

                                                                                                                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -in <string> The image to read. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -out <string> The subsampled image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -rox <int32> first point of ROI in x-direction. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -roy <int32> first point of ROI in y-direction. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -rsx <int32> size of ROI in x-direction. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -rsy <int32> size of ROI in y-direction. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -sr <int32> Sampling Ratio, default is 2. Mandatory: False. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -sx <int32> quicklook size in x-direction (used if no sampling ration is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -sy <int32> quicklook size in y-direction (used if no sampling ration is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                      • [choice] -cl Selected channels . Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                        This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi). +Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.

                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                        • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: quicklookImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/RadiometricIndices.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/RadiometricIndices.html new file mode 100644 index 000000000000..9686e915d862 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/RadiometricIndices.html @@ -0,0 +1,25 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                        RadiometricIndices

                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                        Compute radiometric indices.

                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                        Radiometric Indices,Feature Extraction

                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                        This application computes radiometric indices using the relevant channels of the input image. The output is a multi band image into which each channel is one of the selected indices.

                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Radiometric indices output image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -channels <string> Channels selection. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -list List of available radiometric indices with their relevant channels in brackets: + Vegetation:NDVI - Normalized difference vegetation index (Red, NIR) + Vegetation:TNDVI - Transformed normalized difference vegetation index (Red, NIR) + Vegetation:RVI - Ratio vegetation index (Red, NIR) + Vegetation:SAVI - Soil adjusted vegetation index (Red, NIR) + Vegetation:TSAVI - Transformed soil adjusted vegetation index (Red, NIR) + Vegetation:MSAVI - Modified soil adjusted vegetation index (Red, NIR) + Vegetation:MSAVI2 - Modified soil adjusted vegetation index 2 (Red, NIR) + Vegetation:GEMI - Global environment monitoring index (Red, NIR) + Vegetation:IPVI - Infrared percentage vegetation index (Red, NIR) + + Water:NDWI - Normalized difference water index (Gao 1996) (NIR, MIR) + Water:NDWI2 - Normalized difference water index (Mc Feeters 1996) (Green, NIR) + Water:MNDWI - Modified normalized difference water index (Xu 2006) (Green, MIR) + Water:NDPI - Normalized difference pond index (Lacaux et al.) (MIR, Green) + Water:NDTI - Normalized difference turbidity index (Lacaux et al.) (Red, Green) + + Soil:RI - Redness index (Red, Green) + Soil:CI - Color index (Red, Green) + Soil:BI - Brightness index (Red, Green) + Soil:BI2 - Brightness index 2 (NIR, Red, Green) ndvi,tndvi,rvi,savi,tsavi,msavi,msavi2,gemi,ipvi,laindvilog,lairefl,laindviformo,ndwi,ndwi2,mndwi,ndpi,ndti,ri,ci,bi,bi2. Mandatory: True. Default Value: "ndvi"
                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -ndvi
                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -tndvi
                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -rvi
                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -savi
                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -tsavi
                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -msavi
                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -msavi2
                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -gemi
                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -ipvi
                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -laindvilog
                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -lairefl
                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -laindviformo
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -ndwi
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -ndwi2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -mndwi
                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -ndpi
                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -ndti
                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -ri
                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -ci
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -bi
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -bi2

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  otbVegetationIndicesFunctor, otbWaterIndicesFunctor and otbSoilIndicesFunctor classes

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • list: Vegetation:NDVI Vegetation:RVI Vegetation:IPVI

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: RadiometricIndicesImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-image.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-image.html new file mode 100644 index 000000000000..3569e88c5c6b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-image.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Rasterization

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Rasterize a vector dataset.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector Data Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows reprojecting and rasterize a vector dataset. The grid of the rasterized output can be set by using a reference image, or by setting all parmeters (origin, size, spacing) by hand. In the latter case, at least the spacing (ground sampling distance) is needed (other parameters are computed automatically). The rasterized output can also be in a different projection reference system than the input dataset. + There are two rasterize mode available in the application. The first is the binary mode: it allows rendering all pixels belonging to a geometry of the input dataset in the foreground color, while rendering the other in background color. The second one allows rendering pixels belonging to a geometry woth respect to an attribute of this geometry. The field of the attribute to render can be set by the user. In the second mode, the background value is still used for unassociated pixels.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> The input vector dataset to be rasterized. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> An output image containing the rasterized vector dataset. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -im <string> A reference image from which to import output grid and projection reference system information.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -szx <int32> Output size along x axis (useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -szy <int32> Output size along y axis (useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -epsg <int32> EPSG code for the output projection reference system (EPSG 4326 for WGS84, 32631 for UTM31N...,useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -orx <float> Output upper-left corner x coordinate (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ory <float> Output upper-left corner y coordinate (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spx <float> Spacing (ground sampling distance) along x axis (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spy <float> Spacing (ground sampling distance) along y axis (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -background <float> Default value for pixels not belonging to any geometry. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -mode Choice of rasterization modes binary,attribute. Mandatory: True. Default Value: "binary"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -binary
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mode.binary.foreground <float> Value for pixels inside a geometry. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -attribute
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mode.attribute.field <string> Name of the attribute field to burn. Mandatory: True. Default Value: "DN"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  For now, support of input dataset with multiple layers having different projection reference system is limited.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract_classification.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: rasterImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • spx: 1.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • spy: 1.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-manual.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-manual.html new file mode 100644 index 000000000000..3569e88c5c6b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization-manual.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Rasterization

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Rasterize a vector dataset.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector Data Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows reprojecting and rasterize a vector dataset. The grid of the rasterized output can be set by using a reference image, or by setting all parmeters (origin, size, spacing) by hand. In the latter case, at least the spacing (ground sampling distance) is needed (other parameters are computed automatically). The rasterized output can also be in a different projection reference system than the input dataset. + There are two rasterize mode available in the application. The first is the binary mode: it allows rendering all pixels belonging to a geometry of the input dataset in the foreground color, while rendering the other in background color. The second one allows rendering pixels belonging to a geometry woth respect to an attribute of this geometry. The field of the attribute to render can be set by the user. In the second mode, the background value is still used for unassociated pixels.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> The input vector dataset to be rasterized. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> An output image containing the rasterized vector dataset. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -im <string> A reference image from which to import output grid and projection reference system information.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -szx <int32> Output size along x axis (useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -szy <int32> Output size along y axis (useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -epsg <int32> EPSG code for the output projection reference system (EPSG 4326 for WGS84, 32631 for UTM31N...,useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -orx <float> Output upper-left corner x coordinate (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ory <float> Output upper-left corner y coordinate (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spx <float> Spacing (ground sampling distance) along x axis (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spy <float> Spacing (ground sampling distance) along y axis (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -background <float> Default value for pixels not belonging to any geometry. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -mode Choice of rasterization modes binary,attribute. Mandatory: True. Default Value: "binary"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -binary
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mode.binary.foreground <float> Value for pixels inside a geometry. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -attribute
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mode.attribute.field <string> Name of the attribute field to burn. Mandatory: True. Default Value: "DN"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  For now, support of input dataset with multiple layers having different projection reference system is limited.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract_classification.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: rasterImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • spx: 1.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • spy: 1.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization.html new file mode 100644 index 000000000000..3569e88c5c6b --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rasterization.html @@ -0,0 +1,6 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Rasterization

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Rasterize a vector dataset.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector Data Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows reprojecting and rasterize a vector dataset. The grid of the rasterized output can be set by using a reference image, or by setting all parmeters (origin, size, spacing) by hand. In the latter case, at least the spacing (ground sampling distance) is needed (other parameters are computed automatically). The rasterized output can also be in a different projection reference system than the input dataset. + There are two rasterize mode available in the application. The first is the binary mode: it allows rendering all pixels belonging to a geometry of the input dataset in the foreground color, while rendering the other in background color. The second one allows rendering pixels belonging to a geometry woth respect to an attribute of this geometry. The field of the attribute to render can be set by the user. In the second mode, the background value is still used for unassociated pixels.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> The input vector dataset to be rasterized. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> An output image containing the rasterized vector dataset. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -im <string> A reference image from which to import output grid and projection reference system information.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -szx <int32> Output size along x axis (useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -szy <int32> Output size along y axis (useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -epsg <int32> EPSG code for the output projection reference system (EPSG 4326 for WGS84, 32631 for UTM31N...,useless if support image is given). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -orx <float> Output upper-left corner x coordinate (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ory <float> Output upper-left corner y coordinate (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spx <float> Spacing (ground sampling distance) along x axis (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spy <float> Spacing (ground sampling distance) along y axis (useless if support image is given). Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -background <float> Default value for pixels not belonging to any geometry. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -mode Choice of rasterization modes binary,attribute. Mandatory: True. Default Value: "binary"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -binary
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mode.binary.foreground <float> Value for pixels inside a geometry. Mandatory: True. Default Value: "255"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -attribute
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -mode.attribute.field <string> Name of the attribute field to burn. Mandatory: True. Default Value: "DN"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  For now, support of input dataset with multiple layers having different projection reference system is limited.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract_classification.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: rasterImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • spx: 1.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • spy: 1.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/ReadImageInfo.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/ReadImageInfo.html new file mode 100644 index 000000000000..876e143d7608 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/ReadImageInfo.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ReadImageInfo

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Get information about the image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Utilities,Image Manipulation,Image MetaData

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Display information about the input image like: image size, origin, spacing, metadata, projections...

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> Input image to analyse. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -keywordlist <boolean> Output the OSSIM keyword list. It contains metadata information (sensor model, geometry ). Information is stored in keyword list (pairs of key/value). Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outkwl <string> This option allows extracting the OSSIM keywordlist of the image into a geom file.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -indexx <int32> X start index. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -indexy <int32> Y start index. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -sizex <int32> X size (in pixels). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -sizey <int32> Y size (in pixels). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spacingx <float> Pixel size along X (in physical units). Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -spacingy <float> Pixel size along Y (in physical units). Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -originx <float> Origin along X. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -originy <float> Origin along Y. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -estimatedgroundspacingx <float> Estimated ground spacing along X (in meters).. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -estimatedgroundspacingy <float> Estimated ground spacing along Y (in meters).. Mandatory: True. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -numberbands <int32> Number of bands. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -sensor <string> Sensor identifier. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -id <string> Image identifier. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -time <string> Acquisition time.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ullat <float> Lattitude of the upper left corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ullon <float> Longitude of the upper left corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -urlat <float> Lattitude of the upper right corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -urlon <float> Longitude of the upper right corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -lrlat <float> Lattitude of the lower right corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -lrlon <float> Longitude of the lower right corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -lllat <float> Lattitude of the lower left corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -lllon <float> Longitude of the lower left corner.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -town <string> Main town near center of image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -country <string> Country of the image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -rgb <string> This group of parameters provide information about the default rgb composition.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -projectionref <string> Projection Coordinate System. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -keyword <string> Image keyword list. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -gcp <string> This group of parameters provide information about all GCPs.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/RefineSensorModel.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/RefineSensorModel.html new file mode 100644 index 000000000000..868feaeff787 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/RefineSensorModel.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  RefineSensorModel

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Perform least-square fit of a sensor model to a set of tie points

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Geometry

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application reads a geom file containing a sensor model and a text file containing a list of ground control point, and performs a least-square fit of the sensor model adjustable parameters to these tie points. It produces an updated geom file as output, as well as an optional ground control points based statistics file and a vector file containing residues. The output geom file can then be used to ortho-rectify the data more accurately. Plaease note that for a proper use of the application, elevation must be correctly set (including DEM and geoid file). The map parameters allows one to choose a map projection in which the accuracy will be estimated in meters.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ingeom <string> Geom file containing the sensor model to refine. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outgeom <string> Geom file containing the refined sensor model. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inpoints <string> Input file containing tie points. Points are stored in following format: row col lon lat. Line beginning with # are ignored.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outstat <string> Output file containing the following info: ref_lon ref_lat elevation predicted_lon predicted_lat x_error_ref(meters) y_error_ref(meters) global_error_ref(meters) x_error(meters) y_error(meters) overall_error(meters). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outvector <string> File containing segments representing residues. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "utm"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OrthoRectification,HomologousPointsExtraction

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • ingeom: input.geom

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • outgeom: output.geom

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • inpoints: points.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • map: epsg

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • map.epsg.code: 32631

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Rescale.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rescale.html new file mode 100644 index 000000000000..bb606af15ef8 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Rescale.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Rescale

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Rescale the image between two given values.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Image Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        This application scales the given image pixel intensity between two given values. By default min (resp. max) value is set to 0 (resp. 255).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The image to scale.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> The rescaled image filename.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outmin <float> Minimum value of the output image.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outmax <float> Maximum value of the output image.. Mandatory: False. Default Value: "255"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: rescaledImage.png uchar

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • outmin: 0

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • outmax: 255

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-id.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-id.html new file mode 100644 index 000000000000..2b3101772c0c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-id.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        RigidTransformResample

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Resample an image with a rigid transform

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Conversion,Geometry

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -linear
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Translation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • in: qb_toulouse_sub.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • out: rigitTransformImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • transform.type: rotation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • transform.type.rotation.angle: 20

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • transform.type.rotation.scalex: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • transform.type.rotation.scaley: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-rotation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-rotation.html new file mode 100644 index 000000000000..2b3101772c0c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-rotation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            RigidTransformResample

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Resample an image with a rigid transform

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Conversion,Geometry

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -linear
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Translation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • in: qb_toulouse_sub.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • out: rigitTransformImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • transform.type: rotation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • transform.type.rotation.angle: 20

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • transform.type.rotation.scalex: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • transform.type.rotation.scaley: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-translation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-translation.html new file mode 100644 index 000000000000..2b3101772c0c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample-translation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                RigidTransformResample

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Resample an image with a rigid transform

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Conversion,Geometry

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -linear
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Translation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • in: qb_toulouse_sub.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • out: rigitTransformImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • transform.type: rotation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • transform.type.rotation.angle: 20

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • transform.type.rotation.scalex: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • transform.type.rotation.scaley: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample.html new file mode 100644 index 000000000000..2b3101772c0c --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/RigidTransformResample.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    RigidTransformResample

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Resample an image with a rigid transform

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Conversion,Geometry

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    This application performs a parametric transform on the input image. Scaling, translation and rotation with scaling factor are handled. Parameters of the transform is expressed in physical units, thus particular attention must be paid on pixel size (value, and sign). Moreover transform is expressed from input space to output space (on the contrary ITK Transforms are expressed form output space to input space).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -in <string> The input image to translate.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -out <string> The transformed output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -transform <string> This group of parameters allows setting the transformation to apply.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -ram <int32> This allows setting the maximum amount of RAM available for processing. As the writing task is time consuming, it is better to write large pieces of data, which can be achieved by increasing this parameter (pay attention to your system capabilities). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [choice] -interpolator This group of parameters allows one to define how the input image will be interpolated during resampling. nn,linear,bco. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -linear
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -interpolator.bco.radius <int32> This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Translation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • in: qb_toulouse_sub.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: rigitTransformImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • transform.type: rotation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • transform.type.rotation.angle: 20

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • transform.type.rotation.scalex: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • transform.type.rotation.scaley: 2.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SARCalibration.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARCalibration.html new file mode 100644 index 000000000000..bd06f4869601 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARCalibration.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SARCalibration

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Perform radiometric calibration of SAR images. Following sensors are supported: TerraSAR-X, Sentinel1 and Radarsat-2.Both Single Look Complex(SLC) and detected products are supported as input. +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Calibration,SAR

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically retrieved from image products.The application supports complex and non-complex images (SLC or detected products). +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input complex image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output calibrated image. This image contains the backscatter (sigmaNought) of the input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -noise <boolean> Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -lut Lookup table values are not available with all SAR products. Products that provide lookup table with metadata are: Sentinel1, Radarsat2. sigma,gamma,beta,dn. Mandatory: True. Default Value: "sigma"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -sigma
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -gamma
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -beta
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -dn

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • in: RSAT_imagery_HH.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • out: SarRadiometricCalibration.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SARDecompositions.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARDecompositions.html new file mode 100644 index 000000000000..e1a43aadade2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARDecompositions.html @@ -0,0 +1,15 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                SARDecompositions

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                From one-band complex images (each one related to an element of the Sinclair matrix), returns the selected decomposition.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                SAR

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                From one-band complex images (HH, HV, VH, VV), returns the selected decomposition. + +All the decompositions implemented are intended for the mono-static case (transmitter and receiver are co-located). +There are two kinds of decomposition : coherent ones and incoherent ones. +In the coherent case, only the Pauli decomposition is available. +In the incoherent case, there the decompositions available : Huynen, Barnes, and H-alpha-A. +User must provide three one-band complex images HH, HV or VH, and VV (mono-static case <=> HV = VH). +Incoherent decompositions consist in averaging 3x3 complex coherency/covariance matrices; the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize. +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inhh <string> Input image (HH). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inhv <string> Input image (HV). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -invh <string> Input image (VH). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -invv <string> Input image (VV). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output image. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inco <string> This group allows setting parameters related to the incoherent decompositions.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -decomp haa,barnes,huynen,pauli. Mandatory: True. Default Value: "haa"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -haa
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -barnes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -huynen
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -pauli

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Some decompositions output real images, while this application outputs complex images for general purpose. +Users should pay attention to extract the real part of the results provided by this application. +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SARPolarMatrixConvert, SARPolarSynth

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • inhh: HH.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • invh: VH.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • invv: VV.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • decomp: haa

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: HaA.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarMatrixConvert.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarMatrixConvert.html new file mode 100644 index 000000000000..6f50b0d56481 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarMatrixConvert.html @@ -0,0 +1,32 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SARPolarMatrixConvert

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        This applications allows converting classical polarimetric matrices to each other.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SAR

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        This application allows converting classical polarimetric matrices to each other. +For instance, it is possible to get the coherency matrix from the Sinclar one, or the Mueller matrix from the coherency one. +The filters used in this application never handle matrices, but images where each band is related to their elements. +As most of the time SAR polarimetry handles symetric/hermitian matrices, only the relevant elements are stored, so that the images representing them have a minimal number of bands. +For instance, the coherency matrix size is 3x3 in the monostatic case, and 4x4 in the bistatic case : it will thus be stored in a 6-band or a 10-band complex image (the diagonal and the upper elements of the matrix). + +The Sinclair matrix is a special case : it is always represented as 3 or 4 one-band complex images (for mono- or bistatic case). +The available conversions are listed below: + +--- Monostatic case --- +1 msinclairtocoherency --> Sinclair matrix to coherency matrix (input : 3 x 1 complex channel (HH, HV or VH, VV) | output : 6 complex channels) +2 msinclairtocovariance --> Sinclair matrix to covariance matrix (input : 3 x 1 complex channel (HH, HV or VH, VV) | output : 6 complex channels) +3 msinclairtocircovariance --> Sinclair matrix to circular covariance matrix (input : 3 x 1 complex channel (HH, HV or VH, VV) | output : 6 complex channels) +4 mcoherencytomueller --> Coherency matrix to Mueller matrix (input : 6 complex channels | 16 real channels) +5 mcovariancetocoherencydegree --> Covariance matrix to coherency degree (input : 6 complex channels | 3 complex channels) +6 mcovariancetocoherency --> Covariance matrix to coherency matrix (input : 6 complex channels | 6 complex channels) +7 mlinearcovariancetocircularcovariance --> Covariance matrix to circular covariance matrix (input : 6 complex channels | output : 6 complex channels) + +--- Bistatic case --- +8 bsinclairtocoherency --> Sinclair matrix to coherency matrix (input : 4 x 1 complex channel (HH, HV, VH, VV) | 10 complex channels) +9 bsinclairtocovariance --> Sinclair matrix to covariance matrix (input : 4 x 1 complex channel (HH, HV, VH, VV) | output : 10 complex channels) +10 bsinclairtocircovariance --> Sinclair matrix to circular covariance matrix (input : 4 x 1 complex channel (HH, HV, VH, VV) | output : 10 complex channels) + +--- Both cases --- +11 sinclairtomueller --> Sinclair matrix to Mueller matrix (input : 4 x 1 complex channel (HH, HV, VH, VV) | output : 16 real channels) +12 muellertomcovariance --> Mueller matrix to covariance matrix (input : 16 real channels | output : 6 complex channels) +13 muellertopoldegandpower --> Mueller matrix to polarization degree and power (input : 16 real channels | output : 4 real channels) +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inc <string> Input : multi-band complex image. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inf <string> Input : multi-band real image. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inhh <string> Input : one-band complex image (HH). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inhv <string> Input : one-band complex image (HV). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -invh <string> Input : one-band complex image (VH). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -invv <string> Input : one-band complex image (VV). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outc <string> Output Complex image.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outf <string> Output Real image.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -conv msinclairtocoherency,msinclairtocovariance,msinclairtocircovariance,mcoherencytomueller,mcovariancetocoherencydegree,mcovariancetocoherency,mlinearcovariancetocircularcovariance,muellertomcovariance,bsinclairtocoherency,bsinclairtocovariance,bsinclairtocircovariance,sinclairtomueller,muellertopoldegandpower. Mandatory: True. Default Value: "msinclairtocoherency"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -msinclairtocoherency
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -msinclairtocovariance
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -msinclairtocircovariance
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -mcoherencytomueller
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mcovariancetocoherencydegree
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -mcovariancetocoherency
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -mlinearcovariancetocircularcovariance
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -muellertomcovariance
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -bsinclairtocoherency
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -bsinclairtocovariance
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -bsinclairtocircovariance
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -sinclairtomueller
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -muellertopoldegandpower

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  SARPolarSynth, SARDecompositions

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • inhh: HH.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • invh: VH.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • invv: VV.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • conv: msinclairtocoherency

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • outc: mcoherency.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarSynth.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarSynth.html new file mode 100644 index 000000000000..3173baec19e6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SARPolarSynth.html @@ -0,0 +1,32 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  SARPolarSynth

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Gives, for each pixel, the power that would have been received by a SAR system with a basis different from the classical (H,V) one (polarimetric synthetis).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  SAR

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application gives, for each pixel, the power that would have been received by a SAR system with a basis different from the classical (H,V) one (polarimetric synthetis). +The new basis A and B are indicated through two Jones vectors, defined by the user thanks to orientation (psi) and ellipticity (khi) parameters. +These parameters are namely psii, khii, psir and khir. The suffixes (i) and (r) refer to the transmiting antenna and the receiving antenna respectively. +Orientations and ellipticities are given in degrees, and are between -90°/90° and -45°/45° respectively. + +Four polarization architectures can be processed : +1) HH_HV_VH_VV : full polarization, general bistatic case. +2) HH_HV_VV or HH_VH_VV : full polarization, monostatic case (transmitter and receiver are co-located). +3) HH_HV : dual polarization. +4) VH_VV : dual polarization. +The application takes a complex vector image as input, where each band correspond to a particular emission/reception polarization scheme. +User must comply with the band order given above, since the bands are used to build the Sinclair matrix. + +In order to determine the architecture, the application first relies on the number of bands of the input image. +1) Architecture HH_HV_VH_VV is the only one with four bands, there is no possible confusion. +2) Concerning HH_HV_VV and HH_VH_VV architectures, both correspond to a three channels image. But they are processed in the same way, as the Sinclair matrix is symetric in the monostatic case. +3) Finally, the two last architectures (dual polarizations), can't be distinguished only by the number of bands of the input image. + User must then use the parameters emissionh and emissionv to indicate the architecture of the system : emissionh=1 and emissionv=0 --> HH_HV, emissionh=0 and emissionv=1 --> VH_VV. +Note : if the architecture is HH_HV, khii and psii are automatically set to 0°/0°; if the architecture is VH_VV, khii and psii are automatically set to 0°/90°. + +It is also possible to force the calculation to co-polar or cross-polar modes. +In the co-polar case, values for psir and khir will be ignored and forced to psii and khii; same as the cross-polar mode, where khir and psir will be forced to psii+90° and -khii. + +Finally, the result of the polarimetric synthetis is expressed in the power domain, through a one-band scalar image. +Note: this application doesn't take into account the terms which do not depend on the polarization of the antennas. +The parameter gain can be used for this purpose. + +More details can be found in the OTB CookBook (SAR processing chapter).

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> Input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> Output image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -psii <float> Orientation (transmitting antenna). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -khii <float> Ellipticity (transmitting antenna). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -psir <float> Orientation (receiving antenna). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -khir <float> Ellipticity (receiving antenna). Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -emissionh <int32> This parameter is useful in determining the polarization architecture (dual polarization case).. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -emissionv <int32> This parameter is useful in determining the polarization architecture (dual polarization case).. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -mode none,co,cross. Mandatory: True. Default Value: "none"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -none
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -co
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -cross

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SARDecompositions, SARPolarMatrixConvert

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • in: sar.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • psii: 15.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • khii: 5.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • psir: -25.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • khir: 10.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: newbasis.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SFSTextureExtraction.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SFSTextureExtraction.html new file mode 100644 index 000000000000..faf6fea0fd80 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SFSTextureExtraction.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SFSTextureExtraction

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Computes Structural Feature Set textures on every pixel of the input image selected channel

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Textures,Feature Extraction

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        This application computes SFS textures on a mono band image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> The input image to compute the features on.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -channel <int32> The selected channel index. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -parameters <string> This group of parameters allows one to define SFS texture parameters. The available texture features are SFS'Length, SFS'Width, SFS'PSI, SFS'W-Mean, SFS'Ratio and SFS'SD. They are provided in this exact order in the output image.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output image containing the SFS texture features.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        otbSFSTexturesImageFilter class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • channel: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • parameters.spethre: 50.0

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • parameters.spathre: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: SFSTextures.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SOMClassification.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SOMClassification.html new file mode 100644 index 000000000000..a6fc8a522dfc --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SOMClassification.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SOMClassification

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SOM image classification.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Segmentation,Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Unsupervised Self Organizing Map image classification.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input image to classify.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output classified image (each pixel contains the index of its corresponding vector in the SOM).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -vm <string> Validity mask (only pixels corresponding to a mask value greater than 0 will be used for learning). Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -tp <float> Probability for a sample to be selected in the training set. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ts <int32> Maximum training set size (in pixels). Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -som <string> Output image containing the Self-Organizing Map. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -sx <int32> X size of the SOM map. Mandatory: False. Default Value: "32"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -sy <int32> Y size of the SOM map. Mandatory: False. Default Value: "32"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -nx <int32> X size of the initial neighborhood in the SOM map. Mandatory: False. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ny <int32> Y size of the initial neighborhood in the SOM map. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ni <int32> Number of iterations for SOM learning. Mandatory: False. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -bi <float> Initial learning coefficient. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -bf <float> Final learning coefficient. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -iv <float> Maximum initial neuron weight. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • in: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • out: SOMClassification.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • tp: 1.0

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • ts: 16384

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sx: 32

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sy: 32

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • nx: 10

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • ny: 10

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • ni: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • bi: 1.0

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • bf: 0.1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • iv: 0

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SarRadiometricCalibration.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SarRadiometricCalibration.html new file mode 100644 index 000000000000..f7375f6957b3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SarRadiometricCalibration.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        SarRadiometricCalibration

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Perform radiometric calibration of SAR images. Following sensors are supported: TerraSAR-X, Sentinel1 and Radarsat-2.Both Single Look Complex(SLC) and detected products are supported as input. +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Calibration,SAR

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This application allows computing Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically retrieved from image products.The application supports complex and non-complex images (SLC or detected products). +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -in <string> Input complex image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -out <string> Output calibrated image. This image contains the backscatter (sigmaNought) of the input image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -noise <boolean> Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -lut Lookup table values are not available with all SAR products. Products that provide lookup table with metadata are: Sentinel1, Radarsat2. sigma,gamma,beta,dn. Mandatory: True. Default Value: "sigma"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -sigma
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -gamma
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -beta
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -dn

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • in: RSAT_imagery_HH.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • out: SarRadiometricCalibration.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-cc.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-cc.html new file mode 100644 index 000000000000..b88a1efd82c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-cc.html @@ -0,0 +1,11 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. + +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. + +To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -meanshift
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -cc
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -watershed
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mprofiles
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -vector
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -raster
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. +MeanShift filter results depends on the number of threads used. +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                MeanShiftSegmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with vector mode and watershed segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: vector

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: watershed

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: raster

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: meanshift

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-meanshift.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-meanshift.html new file mode 100644 index 000000000000..b88a1efd82c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-meanshift.html @@ -0,0 +1,11 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. + +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. + +To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -meanshift
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -cc
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -watershed
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mprofiles
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -vector
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -raster
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. +MeanShift filter results depends on the number of threads used. +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                MeanShiftSegmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with vector mode and watershed segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: vector

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: watershed

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: raster

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: meanshift

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-mprofiles.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-mprofiles.html new file mode 100644 index 000000000000..b88a1efd82c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-mprofiles.html @@ -0,0 +1,11 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. + +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. + +To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -meanshift
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -cc
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -watershed
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mprofiles
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -vector
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -raster
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. +MeanShift filter results depends on the number of threads used. +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                MeanShiftSegmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with vector mode and watershed segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: vector

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: watershed

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: raster

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: meanshift

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-watershed.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-watershed.html new file mode 100644 index 000000000000..b88a1efd82c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation-watershed.html @@ -0,0 +1,11 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. + +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. + +To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -meanshift
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -cc
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -watershed
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mprofiles
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -vector
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -raster
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. +MeanShift filter results depends on the number of threads used. +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                MeanShiftSegmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with vector mode and watershed segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: vector

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: watershed

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: raster

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: meanshift

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation.html new file mode 100644 index 000000000000..b88a1efd82c1 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Segmentation.html @@ -0,0 +1,11 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Performs segmentation of an image, and output either a raster or a vector file. In vector mode, large input datasets are supported.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application allows one to perform various segmentation algorithms on a multispectral image.Available segmentation algorithms are two different versions of Mean-Shift segmentation algorithm (one being multi-threaded), simple pixel based connected components according to a user-defined criterion, and watershed from the gradient of the intensity (norm of spectral bands vector). The application has two different modes that affects the nature of its output. + +In raster mode, the output of the application is a classical image of unique labels identifying the segmented regions. The labeled output can be passed to the ColorMapping application to render regions with contrasted colours. Please note that this mode loads the whole input image into memory, and as such can not handle large images. + +To segment large data, one can use the vector mode. In this case, the output of the application is a vector file or database. The input image is split into tiles (whose size can be set using the tilesize parameter), and each tile is loaded, segmented with the chosen algorithm, vectorized, and written into the output file or database. This piece-wise behavior ensure that memory will never get overloaded, and that images of any size can be processed. There are few more options in the vector mode. The simplify option allows simplifying the geometry (i.e. remove nodes in polygons) according to a user-defined tolerance. The stitch option tries to stitch together the polygons corresponding to segmented region that may have been split by the tiling scheme.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> The input image to segment. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -filter Choice of segmentation algorithm (mean-shift by default) meanshift,cc,watershed,mprofiles. Mandatory: True. Default Value: "meanshift"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -meanshift
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.spatialr <int32> Spatial radius of the neighborhood.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.ranger <float> Range radius defining the radius (expressed in radiometry unit) in the multispectral space.. Mandatory: True. Default Value: "15"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.thres <float> Algorithm iterative scheme will stop if mean-shift vector is below this threshold or if iteration number reached maximum number of iterations.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.maxiter <int32> Algorithm iterative scheme will stop if convergence hasn't been reached after the maximum number of iterations.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.meanshift.minsize <int32> Minimum size of a region (in pixel unit) in segmentation. Smaller clusters will be merged to the neighboring cluster with the closest radiometry. If set to 0 no pruning is done.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -cc
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.cc.expr <string> User defined connection condition, written as a mathematical expression. Available variables are p(i)b(i), intensity_p(i) and distance (example of expression : distance < 10 ). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -watershed
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.threshold <float> Depth threshold Units in percentage of the maximum depth in the image.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.watershed.level <float> flood level for generating the merge tree from the initial segmentation (between 0 and 1). Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mprofiles
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.size <int32> Size of the profiles. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.start <int32> Initial radius of the structuring element (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.step <int32> Radius step along the profile (in pixels). Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -filter.mprofiles.sigma <float> Profiles values under the threshold will be ignored.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  [choice] -mode Choice of processing mode, either raster or large-scale. vector,raster. Mandatory: True. Default Value: "vector"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -vector
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.out <string> The output vector file or database (name can be anything understood by OGR). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.outmode <string> This allows one to set the writing behaviour for the output vector file. Please note that the actual behaviour depends on the file format.. Mandatory: True. Default Value: "ulco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.inmask <string> Only pixels whose mask value is strictly positive will be segmented.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.neighbor <boolean> Activate 8-Neighborhood connectivity (default is 4).. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.stitch <boolean> Scan polygons on each side of tiles and stitch polygons which connect by more than one pixel.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.minsize <int32> Objects whose size is below the minimum object size (area in pixels) will be ignored during vectorization.. Mandatory: False. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.simplify <float> Simplify polygons according to a given tolerance (in pixel). This option allows reducing the size of the output file or database.. Mandatory: False. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.layername <string> Name of the layer in the vector file or database (default is Layer).. Mandatory: True. Default Value: "layer"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.fieldname <string> Name of the field holding the geometry index in the output vector file or database.. Mandatory: True. Default Value: "DN"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.tilesize <int32> User defined tiles size for tile-based segmentation. Optimal tile size is selected according to available RAM if null.. Mandatory: True. Default Value: "1024"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.startlabel <int32> Starting value of the geometry index field. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.vector.ogroptions <string> A list of layer creation options in the form KEY=VALUE that will be passed directly to OGR without any validity checking. Options may depend on the file format, and can be found in OGR documentation.. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -raster
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -mode.raster.out <string> The output labeled image.. Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                In raster mode, the application can not handle large input images. Stitching step of vector mode might become slow with very large input images. +MeanShift filter results depends on the number of threads used. +Watershed and multiscale geodesic morphology segmentation will be performed on the amplitude of the input image.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                MeanShiftSegmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with vector mode and watershed segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: vector

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.vector.out: SegmentationVector.sqlite

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: watershed

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Example of use with raster mode and mean-shift segmentation
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode: raster

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • mode.raster.out: SegmentationRaster.tif uint16

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • filter: meanshift

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-anidif.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-anidif.html new file mode 100644 index 000000000000..c8bcf1ce16d6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-anidif.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Smoothing

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Apply a smoothing filter to an image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Image Filtering

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application applies smoothing filter to an image. Either gaussian, mean, or anisotropic diffusion are available.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> Input image to smooth.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output smoothed image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -type Smoothing kernel to apply mean,gaussian,anidif. Mandatory: True. Default Value: "anidif"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mean
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.mean.radius <int32> Mean radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -gaussian
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.gaussian.radius <float> Gaussian radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -anidif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.timestep <float> Diffusion equation time step. Mandatory: True. Default Value: "0.125"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.nbiter <int32> Controls the sensitivity of the conductance term. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.conductance <float> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using a mean filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_mean.png uchar

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: mean

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using an anisotropic diffusion filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_ani.png float

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: anidif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.timestep: 0.1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.nbiter: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.conductance: 1.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-gaussian.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-gaussian.html new file mode 100644 index 000000000000..c8bcf1ce16d6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-gaussian.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Smoothing

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Apply a smoothing filter to an image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Image Filtering

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application applies smoothing filter to an image. Either gaussian, mean, or anisotropic diffusion are available.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> Input image to smooth.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output smoothed image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -type Smoothing kernel to apply mean,gaussian,anidif. Mandatory: True. Default Value: "anidif"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mean
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.mean.radius <int32> Mean radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -gaussian
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.gaussian.radius <float> Gaussian radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -anidif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.timestep <float> Diffusion equation time step. Mandatory: True. Default Value: "0.125"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.nbiter <int32> Controls the sensitivity of the conductance term. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.conductance <float> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using a mean filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_mean.png uchar

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: mean

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using an anisotropic diffusion filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_ani.png float

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: anidif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.timestep: 0.1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.nbiter: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.conductance: 1.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-mean.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-mean.html new file mode 100644 index 000000000000..c8bcf1ce16d6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing-mean.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Smoothing

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Apply a smoothing filter to an image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Image Filtering

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application applies smoothing filter to an image. Either gaussian, mean, or anisotropic diffusion are available.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> Input image to smooth.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output smoothed image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -type Smoothing kernel to apply mean,gaussian,anidif. Mandatory: True. Default Value: "anidif"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mean
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.mean.radius <int32> Mean radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -gaussian
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.gaussian.radius <float> Gaussian radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -anidif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.timestep <float> Diffusion equation time step. Mandatory: True. Default Value: "0.125"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.nbiter <int32> Controls the sensitivity of the conductance term. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.conductance <float> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using a mean filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_mean.png uchar

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: mean

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using an anisotropic diffusion filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_ani.png float

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: anidif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.timestep: 0.1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.nbiter: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.conductance: 1.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing.html new file mode 100644 index 000000000000..c8bcf1ce16d6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Smoothing.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Smoothing

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Apply a smoothing filter to an image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Image Filtering

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application applies smoothing filter to an image. Either gaussian, mean, or anisotropic diffusion are available.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> Input image to smooth.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output smoothed image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -type Smoothing kernel to apply mean,gaussian,anidif. Mandatory: True. Default Value: "anidif"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -mean
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.mean.radius <int32> Mean radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -gaussian
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.gaussian.radius <float> Gaussian radius (in pixels). Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -anidif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.timestep <float> Diffusion equation time step. Mandatory: True. Default Value: "0.125"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.nbiter <int32> Controls the sensitivity of the conductance term. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -type.anidif.conductance <float> . Mandatory: True. Default Value: "1"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using a mean filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_mean.png uchar

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: mean

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • Image smoothing using an anisotropic diffusion filter.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: Romania_Extract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: smoothedImage_ani.png float

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type: anidif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.timestep: 0.1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.nbiter: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • type.anidif.conductance: 1.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/SplitImage.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/SplitImage.html new file mode 100644 index 000000000000..b589865061db --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/SplitImage.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                SplitImage

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Split a N multiband image into N images

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Image Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application splits a N-bands image into N mono-band images. The output images filename will be generated from the output parameter. Thus if the input image has 2 channels, and the user has set an output outimage.tif, the generated images will be outimage_0.tif and outimage_1.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -in <string> Input multiband image filename.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output filename that will be used to get the prefix and the extension of the output images to write. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • in: VegetationIndex.hd

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • out: splittedImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/StereoFramework.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/StereoFramework.html new file mode 100644 index 000000000000..157150ba4866 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/StereoFramework.html @@ -0,0 +1,16 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                StereoFramework

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Compute the ground elevation based on one or multiple stereo pair(s)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Stereo

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Compute the ground elevation with a stereo block matching algorithm between one or multiple stereo pair in sensor geometry. The output is projected in desired geographic or cartographic map projection (UTM by default). The pipeline is made of the following steps: +for each sensor pair : + - compute the epipolar displacement grids from the stereo pair (direct and inverse) + - resample the stereo pair into epipolar geometry using BCO interpolation + - create masks for each epipolar image : remove black borders and resample input masks + - compute horizontal disparities with a block matching algorithm + - refine disparities to sub-pixel precision with a dichotomy algorithm + - apply an optional median filter + - filter disparities based on the correlation score and exploration bounds + - translate disparities in sensor geometry + convert disparity to 3D Map. +Then fuse all 3D maps to produce DSM.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -input <string> This group of parameters allows one to parametrize input data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -output <string> This group of parameters allows one to choose the DSM resolution, nodata value, and projection parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -stereorect <string> This group of parameters allows one to choose direct and inverse grid subsampling. These parameters are very useful to tune time and memory consumption.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -bm <string> This group of parameters allow tuning the block-matching behavior. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -postproc <string> This group of parameters allow use optional filters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -mask <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -map Parameters of the output map projection to be used. utm,lambert2,lambert93,wgs,epsg. Mandatory: True. Default Value: "wgs"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -utm
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -map.utm.zone <int32> The zone number ranges from 1 to 60 and allows defining the transverse mercator projection (along with the hemisphere). Mandatory: True. Default Value: "31"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -map.utm.northhem <boolean> The transverse mercator projections are defined by their zone number as well as the hemisphere. Activate this parameter if your image is in the northern hemisphere.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -lambert2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -lambert93
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -wgs
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -epsg
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -map.epsg.code <int32> See www.spatialreference.org to find which EPSG code is associated to your projection. Mandatory: True. Default Value: "4326"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • input.il: sensor_stereo_left.tif sensor_stereo_right.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • elev.default: 200

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • stereorect.fwdgridstep: 8

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • stereorect.invgridssrate: 4

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • postproc.med: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • output.res: 2.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • output.out: dem.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/StereoRectificationGridGenerator.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/StereoRectificationGridGenerator.html new file mode 100644 index 000000000000..56bafc0fa3a4 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/StereoRectificationGridGenerator.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      StereoRectificationGridGenerator

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Generates two deformation fields to stereo-rectify (i.e. resample in epipolar geometry) a pair of stereo images up to the sensor model precision

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Stereo

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      This application generates a pair of deformation grid to stereo-rectify a pair of stereo images according to sensor modelling and a mean elevation hypothesis. The deformation grids can be passed to the StereoRectificationGridGenerator application for actual resampling in epipolar geometry.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -io <string> This group of parameters allows setting the input and output images.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -epi <string> Parameters of the epipolar geometry and output grids. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inverse <string> This group of parameter allows generating the inverse fields as well. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Generation of the deformation grid is not streamable, pay attention to this fact when setting the grid step.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      otbGridBasedImageResampling

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.inleft: wv2_xs_left.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.inright: wv2_xs_left.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.outleft: wv2_xs_left_epi_field.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.outright: wv2_xs_right_epi_field.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • epi.elevation.default: 400

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/Superimpose.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/Superimpose.html new file mode 100644 index 000000000000..3dc2f37a031a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/Superimpose.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Superimpose

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Using available image metadata, project one image onto another one

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Geometry,Superimposition

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      This application performs the projection of an image into the geometry of another one.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inr <string> The input reference image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inm <string> The image to reproject into the geometry of the reference input.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -lms <float> Generate a coarser deformation field with the given spacing. Mandatory: False. Default Value: "4"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -out <string> Output reprojected image.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -ram <int32> Available memory for processing (in MB). Mandatory: False. Default Value: "128"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [choice] -mode Superimposition mode default,phr. Mandatory: True. Default Value: "default"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -default
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -elev.default <float> This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average elevation value.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -phr
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          [choice] -interpolator This group of parameters allows defining how the input image will be interpolated during resampling. bco,nn,linear. Mandatory: True. Default Value: "bco"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -bco
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -interpolator.bco.radius <int32> This parameter allows controling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artefacts.. Mandatory: True. Default Value: "2"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -nn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • inr: QB_Toulouse_Ortho_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • inm: QB_Toulouse_Ortho_XS.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • out: SuperimposedXS_to_PAN.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TestApplication.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TestApplication.html new file mode 100644 index 000000000000..aac6ba570cde --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TestApplication.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            TestApplication

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            This application helps developers to test parameters types

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Test

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            The purpose of this application is to test parameters types.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -boolean <boolean> . Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -int <int32> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -float <float> . Mandatory: False. Default Value: "0.0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -string <string> . Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -filename <string> . Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -outfilename <string> . Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -directory <string> . Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -ingroup <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -outgroup <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -il <string> . Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -cin <string> . Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -cout <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [choice] -choice choice1,choice2,choice3. Mandatory: True. Default Value: "choice1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -choice1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -choice.choice1.floatchoice1 <float> . Mandatory: True. Default Value: "0.125"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -choice2
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -choice3
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -choice.choice3.floatchoice3 <float> . Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                [choice] -cl choice1,choice2. Mandatory: False. Default Value: "choice1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -choice1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -choice.choice1.floatchoice1 <float> . Mandatory: True. Default Value: "0.125"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -choice2

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • boolean: true

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • filename: myFilename.foo

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TileFusion.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TileFusion.html new file mode 100644 index 000000000000..ff003aa4becc --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TileFusion.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                TileFusion

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Fusion of an image made of several tile files.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Image Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Concatenate several tile files into a single image file.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -il <string> Input tiles to concatenate (in lexicographic order : (0,0) (1,0) (0,1) (1,1)).. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -cols <int32> Number of columns in the tile array. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -rows <int32> Number of rows in the tile array. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -out <string> Output entire image. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • il: Scene_R1C1.tif Scene_R1C2.tif Scene_R2C1.tif Scene_R2C2.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • cols: 2

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • rows: 2

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • out: EntireImage.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-ann.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-ann.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-ann.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-bayes.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-bayes.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-bayes.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-boost.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-boost.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-boost.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-dt.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-dt.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-dt.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-gbt.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-gbt.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-gbt.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-knn.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-knn.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-knn.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-rf.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-rf.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier-rf.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier.html new file mode 100644 index 000000000000..425c1e3c34e2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainImagesClassifier.html @@ -0,0 +1,8 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              TrainImagesClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Train a classifier from multiple pairs of images and training vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              This application performs a classifier training from multiple pairs of input images and training vector data. Samples are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The training vector data must contain polygons with a positive integer field representing the class label. The name of this field can be set using the "Class label field" parameter. Training and validation sample lists are built such that each class is equally represented in both lists. One parameter allows controlling the ratio between the number of samples in training and validation sets. Two parameters allow managing the size of the training and validation sets per class and per image. + Several classifier parameters can be set depending on the chosen classifier. In the validation process, the confusion matrix is organized the following way: rows = reference labels, columns = produced labels. In the header of the optional confusion matrix output file, the validation (reference) and predicted (produced) class labels are ordered according to the rows/columns of the confusion matrix. + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • [choice] -classifier Choice of the classifier to use for the training. boost,dt,gbt,ann,bayes,rf,knn. Mandatory: True. Default Value: "boost"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -boost
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.boost.t <string> Type of Boosting algorithm.. Mandatory: True. Default Value: "real"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.boost.w <int32> The number of weak classifiers.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.boost.r <float> A threshold between 0 and 1 used to save computational time. Samples with summary weight <= (1 - weight_trim_rate) do not participate in the next iteration of training. Set this parameter to 0 to turn off this functionality.. Mandatory: True. Default Value: "0.95"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.boost.m <int32> Maximum depth of the tree.. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [group] -bayes
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • io.il: QB_1_ortho.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • io.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • io.imstat: EstimateImageStatisticsQB1.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • sample.mv: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • sample.mt: 100

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • sample.vtr: 0.5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • sample.edg: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • sample.vfn: Class

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • classifier.libsvm.k: linear

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • classifier.libsvm.c: 1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • classifier.libsvm.opt: false

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • io.out: svmModelQB1.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • io.confmatout: svmConfusionMatrixQB1.csv

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainOGRLayersClassifier.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainOGRLayersClassifier.html new file mode 100644 index 000000000000..551a2cd45440 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainOGRLayersClassifier.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                TrainOGRLayersClassifier

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Train a SVM classifier based on labeled geometries and a list of features to consider.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Segmentation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                This application trains a SVM classifier based on labeled geometries and a list of features to consider for classification.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inshp <string> Name of the input shapefile. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -instats <string> XML file containing mean and variance of each feature.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outsvm <string> Output model filename.. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -cfield <string> Field containing the class id for supervision. Only geometries with this field available will be taken into account.. Mandatory: True. Default Value: "class"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • [choice] -feat List of features to consider for classification. . Mandatory: True. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Experimental. For now only shapefiles are supported. Tuning of SVM classifier is not available.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  David Youssefi during internship at CNES

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OGRLayerClassifier,ComputeOGRLayersFeaturesStatistics

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • inshp: vectorData.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • instats: meanVar.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • outsvm: svmModel.svm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • feat: perimeter

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • cfield: predicted

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainRegression.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainRegression.html new file mode 100644 index 000000000000..0e2c801d7af2 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/TrainRegression.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  TrainRegression

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Train a classifier from multiple images to perform regression.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Learning

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application trains a classifier from multiple input images or a csv file, in order to perform regression. Predictors are composed of pixel values in each band optionally centered and reduced using an XML statistics file produced by the ComputeImagesStatistics application. + The output value for each predictor is assumed to be the last band (or the last column for CSV files). Training and validation predictor lists are built such that their size is inferior to maximum bounds given by the user, and the proportion corresponds to the balance parameter. Several classifier parameters can be set depending on the chosen classifier. In the validation process, the mean square error is computed + This application is based on LibSVM and on OpenCV Machine Learning classifiers, and is compatible with OpenCV 2.3.1 and later.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -io <string> This group of parameters allows setting input and output data.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -sample <string> This group of parameters allows you to set training and validation sample lists parameters.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [choice] -classifier Choice of the classifier to use for the training. dt,gbt,ann,rf,knn. Mandatory: True. Default Value: "dt"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -dt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "65535"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.min <int32> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.ra <float> . Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.f <int32> If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K is equal to cv_folds.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.r <boolean> If true, then a pruning will be harsher. This will make a tree more compact and more resistant to the training data noise but a bit less accurate.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.dt.t <boolean> If true, then pruned branches are physically removed from the tree.. Mandatory: False. Default Value: "True"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -gbt
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.t <string> Type of loss functionused for training.. Mandatory: True. Default Value: "sqr"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.w <int32> Number "w" of boosting algorithm iterations, with w*K being the total number of trees in the GBT model, where K is the output number of classes.. Mandatory: True. Default Value: "200"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.s <float> Regularization parameter.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.p <float> Portion of the whole training set used for each algorithm iteration. The subset is generated randomly.. Mandatory: True. Default Value: "0.8"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.gbt.max <int32> The training algorithm attempts to split each node while its depth is smaller than the maximum possible depth of the tree. The actual depth may be smaller if the other termination criteria are met, and/or if the tree is pruned.. Mandatory: True. Default Value: "3"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -ann
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.t <string> Type of training method for the multilayer perceptron (MLP) neural network.. Mandatory: True. Default Value: "reg"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.sizes <string> The number of neurons in each intermediate layer (excluding input and output layers).. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.f <string> Neuron activation function.. Mandatory: True. Default Value: "sig"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.a <float> Alpha parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.b <float> Beta parameter of the activation function (used only with sigmoid and gaussian functions).. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.bpdw <float> Strength of the weight gradient term in the BACKPROP method. The recommended value is about 0.1.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.bpms <float> Strength of the momentum term (the difference between weights on the 2 previous iterations). This parameter provides some inertia to smooth the random fluctuations of the weights. It can vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.rdw <float> Initial value Delta_0 of update-values Delta_{ij} in RPROP method (default = 0.1).. Mandatory: True. Default Value: "0.1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.rdwm <float> Update-values lower limit Delta_{min} in RPROP method. It must be positive (default = 1e-7).. Mandatory: True. Default Value: "1e-07"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.term <string> Termination criteria.. Mandatory: True. Default Value: "all"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.eps <float> Epsilon value used in the Termination criteria.. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.ann.iter <int32> Maximum number of iterations used in the Termination criteria.. Mandatory: True. Default Value: "1000"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -rf
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.max <int32> The depth of the tree. A low value will likely underfit and conversely a high value will likely overfit. The optimal value can be obtained using cross validation or other suitable methods.. Mandatory: True. Default Value: "5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.min <int32> If the number of samples in a node is smaller than this parameter, then the node will not be split. A reasonable value is a small percentage of the total data e.g. 1 percent.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.ra <float> If all absolute differences between an estimated value in a node and the values of the train samples in this node are smaller than this regression accuracy parameter, then the node will not be split.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.cat <int32> Cluster possible values of a categorical variable into K <= cat clusters to find a suboptimal split.. Mandatory: True. Default Value: "10"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.var <int32> The size of the subset of features, randomly selected at each tree node, that are used to find the best split(s). If you set it to 0, then the size will be set to the square root of the total number of features.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.nbtrees <int32> The maximum number of trees in the forest. Typically, the more trees you have, the better the accuracy. However, the improvement in accuracy generally diminishes and reaches an asymptote for a certain number of trees. Also to keep in mind, increasing the number of trees increases the prediction time linearly.. Mandatory: True. Default Value: "100"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.rf.acc <float> Sufficient accuracy (OOB error).. Mandatory: True. Default Value: "0.01"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    • [group] -knn
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.knn.k <int32> The number of neighbors to use.. Mandatory: True. Default Value: "32"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      • [param] -classifier.knn.rule <string> Decision rule for regression output. Mandatory: True. Default Value: "mean"

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OpenCV documentation for machine learning http://docs.opencv.org/modules/ml/doc/ml.html

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.il: training_dataset.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.out: regression_model.txt

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.imstat: training_statistics.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • classifier: libsvm

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataDSValidation.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataDSValidation.html new file mode 100644 index 000000000000..e2cd2032ac0a --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataDSValidation.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataDSValidation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector data validation based on the fusion of features using Dempster-Shafer evidence theory framework.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Feature Extraction

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application validates or unvalidate the studied samples using the Dempster-Shafer theory.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> Input vector data to validate. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -descmod <string> Fuzzy descriptors model (xml file). Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -belsup <string> Dempster Shafer study hypothesis to compute belief. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -plasup <string> Dempster Shafer study hypothesis to compute plausibility. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -cri <string> Dempster Shafer criterion (by default (belief+plausibility)/2). Mandatory: False. Default Value: "((Belief + Plausibility)/2.)"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -thd <float> Criterion threshold (default 0.5). Mandatory: False. Default Value: "0.5"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> Output VectorData containing only the validated samples. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  http://en.wikipedia.org/wiki/Dempster-Shafer_theory

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_gt.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • belsup: cdbTvComputePolylineFeatureFromImage_LI_NOBUIL_gt.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • descmod: DSFuzzyModel.xml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: VectorDataDSValidation.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataExtractROI.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataExtractROI.html new file mode 100644 index 000000000000..5acd2390b3b6 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataExtractROI.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataExtractROI

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Perform an extract ROI on the input vector data according to the input image extent

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector Data Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application extracts the vector data features belonging to a region specified by the support image envelope. Any features intersecting the support region is copied to output. The output geometries are NOT cropped.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -io <string> Group containing input and output parameters. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.vd: qb_RoadExtract_classification.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • io.out: apTvUtVectorDataExtractROIApplicationTest.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-image.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-image.html new file mode 100644 index 000000000000..6a546974cf23 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-image.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataReprojection

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Reproject a vector data using support image projection reference, or a user specified map projection +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Geometry,Vector Data Manipulation,Coordinates

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows reprojecting a vector data using support image projection reference, or a user given map projection. + If given, image keywordlist can be added to reprojected vectordata.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.proj: image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.proj.image.in: ROI_QB_MUL_1.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.vd: reprojected_vd.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-user.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-user.html new file mode 100644 index 000000000000..6a546974cf23 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection-user.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataReprojection

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Reproject a vector data using support image projection reference, or a user specified map projection +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Geometry,Vector Data Manipulation,Coordinates

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows reprojecting a vector data using support image projection reference, or a user given map projection. + If given, image keywordlist can be added to reprojected vectordata.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.proj: image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.proj.image.in: ROI_QB_MUL_1.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.vd: reprojected_vd.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection.html new file mode 100644 index 000000000000..6a546974cf23 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataReprojection.html @@ -0,0 +1,7 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataReprojection

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Reproject a vector data using support image projection reference, or a user specified map projection +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Geometry,Vector Data Manipulation,Coordinates

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application allows reprojecting a vector data using support image projection reference, or a user given map projection. + If given, image keywordlist can be added to reprojected vectordata.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> . Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -elev <string> This group of parameters allows managing elevation values. Supported formats are SRTM, DTED or any geotiff. DownloadSRTMTiles application could be a useful tool to list/download tiles related to a product.. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in.vd: VectorData_QB1.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.proj: image

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.proj.image.in: ROI_QB_MUL_1.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out.vd: reprojected_vd.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataSetField.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataSetField.html new file mode 100644 index 000000000000..34a074002ed3 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataSetField.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataSetField

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Set a field in vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector Data Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Set a specified field to a specified value on all features of a vector data.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> Input Vector Data. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> Output Vector Data. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -fn <string> Field name. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -fv <string> Field value. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Doesn't work with KML files yet

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract_classification.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: VectorDataSetField.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • fn: Info

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • fv: Sample polygon

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataTransform.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataTransform.html new file mode 100644 index 000000000000..ad5cda0a1e68 --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VectorDataTransform.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VectorDataTransform

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Apply a transform to each vertex of the input VectorData

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Vector Data Manipulation

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  This application performs a transformation of an input vector data transforming each vertex in the vector data. The applied transformation manages translation, rotation and scale, and can be centered or not.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -vd <string> Input vector data to transform. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -out <string> Output transformed vector data. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> Image needed as a support to the vector data. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -transform <string> Group of parameters to define the transform. Mandatory: True. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • vd: qb_RoadExtract_easyClassification.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: qb_RoadExtract.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • out: VectorDataTransform.shp

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • transform.ro: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file diff --git a/python/plugins/processing/algs/otb/description/5.4.0/doc/VertexComponentAnalysis.html b/python/plugins/processing/algs/otb/description/5.4.0/doc/VertexComponentAnalysis.html new file mode 100644 index 000000000000..345c7725e11f --- /dev/null +++ b/python/plugins/processing/algs/otb/description/5.4.0/doc/VertexComponentAnalysis.html @@ -0,0 +1,5 @@ + + +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  VertexComponentAnalysis

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Brief Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Find endmembers in hyperspectral images with Vertex Component Analysis

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Tags

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Hyperspectral,Dimensionality Reduction

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Long Description

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Applies the Vertex Component Analysis to an hyperspectral image to extract endmembers

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Parameters

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -in <string> Input hyperspectral data cube. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -ne <int32> The number of endmembers to extract from the data cube. Mandatory: True. Default Value: "1"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outendm <string> The endmebers, stored in a one-line multi-spectral image, each pixel representing an endmember. Mandatory: True. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -rand <int32> Set specific seed. with integer value.. Mandatory: False. Default Value: "0"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -inxml <string> Load otb application from xml file. Mandatory: False. Default Value: ""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • [param] -outxml <string> Save otb application to xml file. Mandatory: False. Default Value: ""

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Limitations

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  None

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Authors

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  OTB-Team

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  See Also

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Example of use

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • in: cupriteSubHsi.tif

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • ne: 5

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • outendm: VertexComponentAnalysis.tif double

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \ No newline at end of file From 74f49ddd197ad05182f9e7ce59213663297f498e Mon Sep 17 00:00:00 2001 From: rldhont Date: Thu, 3 Nov 2016 17:29:27 +0100 Subject: [PATCH 612/897] [BUGFIX][QGIS Server] No flags in QgsFeatureRequest if expression needs geometry --- src/server/qgswfsserver.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index dab06ea58337..9f1765007a38 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -656,7 +656,14 @@ int QgsWfsServer::getFeature( QgsRequestHandler& request, const QString& format throw QgsMapServiceException( QStringLiteral( "RequestNotWellFormed" ), filter->parserErrorString() ); } QgsFeatureRequest req; - req.setFlags( QgsFeatureRequest::ExactIntersect | ( mWithGeom ? QgsFeatureRequest::NoFlags : QgsFeatureRequest::NoGeometry ) ); + if ( filter->needsGeometry() ) + { + req.setFlags( QgsFeatureRequest::NoFlags ); + } + else + { + req.setFlags( QgsFeatureRequest::ExactIntersect | ( mWithGeom ? QgsFeatureRequest::NoFlags : QgsFeatureRequest::NoGeometry ) ); + } req.setFilterExpression( filter->expression() ); #ifdef HAVE_SERVER_PYTHON_PLUGINS mAccessControl->filterFeatures( layer, req ); From 100667ace06aad4b3d9312b2d036ed1940c92368 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 4 Nov 2016 10:02:46 +1000 Subject: [PATCH 613/897] Fix dialogs which violate HIG (use of : at end of label) --- python/console/console_settings.ui | 58 +++++++++---------- .../ui/qgsgeometrycheckerresulttab.ui | 4 +- .../ui/qgsgeometrycheckersetuptab.ui | 28 ++++----- .../georeferencer/qgsopenrasterdialogbase.ui | 4 +- .../qgstransformtypedialogbase.ui | 2 +- src/plugins/globe/qgsglobeplugindialog.ui | 6 +- .../qgsglobevectorlayerpropertiespage.ui | 2 +- src/plugins/grass/qgsgrassnewmapsetbase.ui | 8 +-- src/ui/composer/qgscomposerhtmlwidgetbase.ui | 2 +- .../qgsvaluerelationconfigdlgbase.ui | 2 +- src/ui/qgsalignrasterdialog.ui | 2 +- src/ui/qgscharacterselectdialogbase.ui | 2 +- src/ui/qgsdecorationcopyrightdialog.ui | 2 +- src/ui/qgsdiagrampropertiesbase.ui | 4 +- src/ui/qgsfieldspropertiesbase.ui | 2 +- .../qgsinvertedpolygonrendererwidgetbase.ui | 2 +- src/ui/qgsmapunitscalewidgetbase.ui | 12 ++-- src/ui/qgsoptionsbase.ui | 10 ++-- src/ui/qgsowssourceselectbase.ui | 4 +- src/ui/qgsprojectionselectorbase.ui | 2 +- src/ui/qgsprojectpropertiesbase.ui | 2 +- src/ui/qgsrasterlayerpropertiesbase.ui | 2 +- src/ui/qgssourceselectdialogbase.ui | 2 +- src/ui/qgsvectorlayerpropertiesbase.ui | 6 +- src/ui/qgswfssourceselectbase.ui | 2 +- src/ui/raster/qgsrastertransparencywidget.ui | 2 +- src/ui/symbollayer/widget_shapeburstfill.ui | 2 +- 27 files changed, 88 insertions(+), 88 deletions(-) diff --git a/python/console/console_settings.ui b/python/console/console_settings.ui index 7fbbe9828c31..81b4aaee91ef 100644 --- a/python/console/console_settings.ui +++ b/python/console/console_settings.ui @@ -355,7 +355,7 @@ - Default: + Default @@ -369,7 +369,7 @@ - Keyword: + Keyword @@ -383,7 +383,7 @@ - Class name: + Class name @@ -397,7 +397,7 @@ - Function: + Function @@ -411,7 +411,7 @@ - Decorator: + Decorator @@ -425,7 +425,7 @@ - Comment: + Comment @@ -439,7 +439,7 @@ - Comment block: + Comment block @@ -453,7 +453,7 @@ - Cursor: + Cursor @@ -467,7 +467,7 @@ - Caretline: + Caretline @@ -481,7 +481,7 @@ - Single quote: + Single quote @@ -495,7 +495,7 @@ - Double quote: + Double quote @@ -509,7 +509,7 @@ - Triple single quote: + Triple single quote @@ -523,7 +523,7 @@ - Triple double quote: + Triple double quote @@ -537,7 +537,7 @@ - Background: + Background @@ -887,7 +887,7 @@ - Default: + Default @@ -901,7 +901,7 @@ - Keyword: + Keyword @@ -915,7 +915,7 @@ - Class name: + Class name @@ -929,7 +929,7 @@ - Function: + Function @@ -943,7 +943,7 @@ - Decorator: + Decorator @@ -957,7 +957,7 @@ - Comment: + Comment @@ -971,7 +971,7 @@ - Comment block: + Comment block @@ -985,7 +985,7 @@ - Cursor: + Cursor @@ -999,7 +999,7 @@ - Caretline: + Caretline @@ -1013,7 +1013,7 @@ - Single quote: + Single quote @@ -1027,7 +1027,7 @@ - Double quote: + Double quote @@ -1041,7 +1041,7 @@ - Triple single quote: + Triple single quote @@ -1055,7 +1055,7 @@ - Triple double quote: + Triple double quote @@ -1069,7 +1069,7 @@ - Background: + Background @@ -1083,7 +1083,7 @@ - Error: + Error diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.ui b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.ui index 9d9f896799e8..a8e45a7e6e6f 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.ui +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckerresulttab.ui @@ -155,7 +155,7 @@ - When a row is selected, move canvas to: + When a row is selected, move canvas to true @@ -385,7 +385,7 @@ - Attribute to use when merging features by attribute value: + Attribute to use when merging features by attribute value diff --git a/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.ui b/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.ui index f672cb3b9ff5..5a0eb04730f4 100644 --- a/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.ui +++ b/src/plugins/geometry_checker/ui/qgsgeometrycheckersetuptab.ui @@ -112,7 +112,7 @@ - Geometry validity: + Geometry validity true @@ -169,7 +169,7 @@ - Allowed geometry types: + Allowed geometry types true @@ -238,7 +238,7 @@ - Geometry properties: + Geometry properties true @@ -279,7 +279,7 @@ - Geometry conditions: + Geometry conditions true @@ -313,14 +313,14 @@ - Minimum angle between segments (deg): + Minimum angle between segments (deg) - Minimal segment length (map units): + Minimal segment length (map units) @@ -347,14 +347,14 @@ - Minimal polygon area (map units sqr.): + Minimal polygon area (map units sqr.) - No sliver polygons: + No sliver polygons @@ -401,7 +401,7 @@ - Maximum thinness: + Maximum thinness @@ -437,7 +437,7 @@ - Max. area (map units sqr.): + Max. area (map units sqr.) @@ -450,7 +450,7 @@ - Topology checks: + Topology checks true @@ -490,7 +490,7 @@ - Check for overlaps smaller than (map units sqr.): + Check for overlaps smaller than (map units sqr.) @@ -503,7 +503,7 @@ - Check for gaps smaller than (map units sqr.): + Check for gaps smaller than (map units sqr.) @@ -561,7 +561,7 @@ - Tolerance: + Tolerance diff --git a/src/plugins/georeferencer/qgsopenrasterdialogbase.ui b/src/plugins/georeferencer/qgsopenrasterdialogbase.ui index bdb1a1ae1870..749d7cd83f29 100644 --- a/src/plugins/georeferencer/qgsopenrasterdialogbase.ui +++ b/src/plugins/georeferencer/qgsopenrasterdialogbase.ui @@ -22,7 +22,7 @@ - Raster file: + Raster file @@ -61,7 +61,7 @@ - Save raster as: + Save raster as diff --git a/src/plugins/georeferencer/qgstransformtypedialogbase.ui b/src/plugins/georeferencer/qgstransformtypedialogbase.ui index 92c6d5636676..0bcb0a52fcb3 100644 --- a/src/plugins/georeferencer/qgstransformtypedialogbase.ui +++ b/src/plugins/georeferencer/qgstransformtypedialogbase.ui @@ -17,7 +17,7 @@ - Select transformation type: + Transformation type diff --git a/src/plugins/globe/qgsglobeplugindialog.ui b/src/plugins/globe/qgsglobeplugindialog.ui index 341e1918ea53..5454ca32fbeb 100644 --- a/src/plugins/globe/qgsglobeplugindialog.ui +++ b/src/plugins/globe/qgsglobeplugindialog.ui @@ -68,7 +68,7 @@ - Override Date / Time (UTC): + Override Date / Time (UTC) @@ -229,7 +229,7 @@ - Vertical scale: + Vertical scale @@ -602,7 +602,7 @@ - Sensitivity: + Sensitivity diff --git a/src/plugins/globe/qgsglobevectorlayerpropertiespage.ui b/src/plugins/globe/qgsglobevectorlayerpropertiespage.ui index 1bde68b9cbbc..ca201839114c 100644 --- a/src/plugins/globe/qgsglobevectorlayerpropertiespage.ui +++ b/src/plugins/globe/qgsglobevectorlayerpropertiespage.ui @@ -233,7 +233,7 @@ - Rendering mode: + Rendering mode diff --git a/src/plugins/grass/qgsgrassnewmapsetbase.ui b/src/plugins/grass/qgsgrassnewmapsetbase.ui index 1acae195d5f6..444cd976d24b 100644 --- a/src/plugins/grass/qgsgrassnewmapsetbase.ui +++ b/src/plugins/grass/qgsgrassnewmapsetbase.ui @@ -498,7 +498,7 @@ - New mapset: + New mapset @@ -613,7 +613,7 @@ - Database: + Database @@ -632,7 +632,7 @@ - Location: + Location
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  @@ -651,7 +651,7 @@ - Mapset: + Mapset
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  diff --git a/src/ui/composer/qgscomposerhtmlwidgetbase.ui b/src/ui/composer/qgscomposerhtmlwidgetbase.ui index 3c1e3096d764..e6525537cf80 100644 --- a/src/ui/composer/qgscomposerhtmlwidgetbase.ui +++ b/src/ui/composer/qgscomposerhtmlwidgetbase.ui @@ -107,7 +107,7 @@ - Source: + Source diff --git a/src/ui/editorwidgets/qgsvaluerelationconfigdlgbase.ui b/src/ui/editorwidgets/qgsvaluerelationconfigdlgbase.ui index 941b50938061..7a5fe02a59ef 100644 --- a/src/ui/editorwidgets/qgsvaluerelationconfigdlgbase.ui +++ b/src/ui/editorwidgets/qgsvaluerelationconfigdlgbase.ui @@ -17,7 +17,7 @@ - Select layer, key column and value column: + Select layer, key column and value column diff --git a/src/ui/qgsalignrasterdialog.ui b/src/ui/qgsalignrasterdialog.ui index ab10c31daa4d..41173b75de91 100644 --- a/src/ui/qgsalignrasterdialog.ui +++ b/src/ui/qgsalignrasterdialog.ui @@ -19,7 +19,7 @@ - Raster layers to align: + Raster layers to align diff --git a/src/ui/qgscharacterselectdialogbase.ui b/src/ui/qgscharacterselectdialogbase.ui index 77d4747b6b54..dd771a259c85 100644 --- a/src/ui/qgscharacterselectdialogbase.ui +++ b/src/ui/qgscharacterselectdialogbase.ui @@ -31,7 +31,7 @@ - Font: + Font
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  diff --git a/src/ui/qgsdecorationcopyrightdialog.ui b/src/ui/qgsdecorationcopyrightdialog.ui index 1601b6ec09c9..e940c0cc4e59 100644 --- a/src/ui/qgsdecorationcopyrightdialog.ui +++ b/src/ui/qgsdecorationcopyrightdialog.ui @@ -49,7 +49,7 @@ - &Enter your copyright label here: + Copyright label text txtCopyrightText diff --git a/src/ui/qgsdiagrampropertiesbase.ui b/src/ui/qgsdiagrampropertiesbase.ui index ed9231812dd9..256272312771 100644 --- a/src/ui/qgsdiagrampropertiesbase.ui +++ b/src/ui/qgsdiagrampropertiesbase.ui @@ -1037,7 +1037,7 @@ - Scale linearly between 0 and the following attribute value / diagram size: + Scale linearly between 0 and the following attribute value / diagram size true @@ -1415,7 +1415,7 @@ - Priority: + Priority diff --git a/src/ui/qgsfieldspropertiesbase.ui b/src/ui/qgsfieldspropertiesbase.ui index 3724f9b043c5..813203db0f23 100644 --- a/src/ui/qgsfieldspropertiesbase.ui +++ b/src/ui/qgsfieldspropertiesbase.ui @@ -16,7 +16,7 @@ - Attribute editor layout: + Attribute editor layout diff --git a/src/ui/qgsinvertedpolygonrendererwidgetbase.ui b/src/ui/qgsinvertedpolygonrendererwidgetbase.ui index 53c5cd7fd02f..4b2ee164b05f 100644 --- a/src/ui/qgsinvertedpolygonrendererwidgetbase.ui +++ b/src/ui/qgsinvertedpolygonrendererwidgetbase.ui @@ -19,7 +19,7 @@ - Sub renderer: + Sub renderer diff --git a/src/ui/qgsmapunitscalewidgetbase.ui b/src/ui/qgsmapunitscalewidgetbase.ui index 7dfe5ab5ab71..eb96d5e11db4 100644 --- a/src/ui/qgsmapunitscalewidgetbase.ui +++ b/src/ui/qgsmapunitscalewidgetbase.ui @@ -46,7 +46,7 @@ - Scale only within the following map unit scale range: + Scale only within the following map unit scale range true @@ -56,7 +56,7 @@ - Minimum scale: + Minimum scale @@ -70,7 +70,7 @@ - Maximum scale: + Maximum scale @@ -99,14 +99,14 @@ - Minimum size: + Minimum size - Maximum size: + Maximum size @@ -133,7 +133,7 @@ - Scale only within the following size range: + Scale only within the following size range diff --git a/src/ui/qgsoptionsbase.ui b/src/ui/qgsoptionsbase.ui index 3b5d36c6b85a..4d0adc2dcb90 100644 --- a/src/ui/qgsoptionsbase.ui +++ b/src/ui/qgsoptionsbase.ui @@ -1858,7 +1858,7 @@ - Max cores to use: + Max cores to use @@ -1942,7 +1942,7 @@ - Simplification threshold (higher values result in more simplification): + Simplification threshold (higher values result in more simplification) 2 @@ -2000,7 +2000,7 @@ This algorithm is only applied to simplify on local side - Simplification algorithm: + Simplification algorithm 2 @@ -2020,7 +2020,7 @@ - Maximum scale at which the layer should be simplified (1:1 always simplifies): + Maximum scale at which the layer should be simplified (1:1 always simplifies) 2 @@ -4781,7 +4781,7 @@ - Detected active locale on your system: + Detected active locale on your system diff --git a/src/ui/qgsowssourceselectbase.ui b/src/ui/qgsowssourceselectbase.ui index f253c184838a..3f6d329f4782 100644 --- a/src/ui/qgsowssourceselectbase.ui +++ b/src/ui/qgsowssourceselectbase.ui @@ -3,7 +3,7 @@ QgsOWSSourceSelectBase - + : 0 0 743 @@ -237,7 +237,7 @@ - Coordinate Reference System: + Coordinate Reference System diff --git a/src/ui/qgsprojectionselectorbase.ui b/src/ui/qgsprojectionselectorbase.ui index f926ac393928..c892f0a00492 100644 --- a/src/ui/qgsprojectionselectorbase.ui +++ b/src/ui/qgsprojectionselectorbase.ui @@ -39,7 +39,7 @@ - Selected CRS: + Selected CRS diff --git a/src/ui/qgsprojectpropertiesbase.ui b/src/ui/qgsprojectpropertiesbase.ui index 4b20b7a154ce..38bc06f5fdb2 100644 --- a/src/ui/qgsprojectpropertiesbase.ui +++ b/src/ui/qgsprojectpropertiesbase.ui @@ -1996,7 +1996,7 @@ - Scenario 2 - INSPIRE related fields using embedded service metadata: + Scenario 2 - INSPIRE related fields using embedded service metadata true diff --git a/src/ui/qgsrasterlayerpropertiesbase.ui b/src/ui/qgsrasterlayerpropertiesbase.ui index 0944a2ff4064..b334e0039cf6 100644 --- a/src/ui/qgsrasterlayerpropertiesbase.ui +++ b/src/ui/qgsrasterlayerpropertiesbase.ui @@ -1211,7 +1211,7 @@ Use original source no data value. - No data value: + No data value diff --git a/src/ui/qgssourceselectdialogbase.ui b/src/ui/qgssourceselectdialogbase.ui index f0f95898dee7..87bd55a73159 100644 --- a/src/ui/qgssourceselectdialogbase.ui +++ b/src/ui/qgssourceselectdialogbase.ui @@ -120,7 +120,7 @@ true - Fi&lter: + Fi&lter lineFilter diff --git a/src/ui/qgsvectorlayerpropertiesbase.ui b/src/ui/qgsvectorlayerpropertiesbase.ui index cf54f8107287..ac7254f24855 100644 --- a/src/ui/qgsvectorlayerpropertiesbase.ui +++ b/src/ui/qgsvectorlayerpropertiesbase.ui @@ -791,7 +791,7 @@ - Simplification threshold (higher values result in more simplification): + Simplification threshold (higher values result in more simplification) 2 @@ -849,7 +849,7 @@ This algorithm only is applied to simplify on local side - Simplification algorithm: + Simplification algorithm 2 @@ -869,7 +869,7 @@ - Maximum scale at which the layer should be simplified (1:1 always simplifies): + Maximum scale at which the layer should be simplified (1:1 always simplifies) 2 diff --git a/src/ui/qgswfssourceselectbase.ui b/src/ui/qgswfssourceselectbase.ui index 9c7efb4d6db4..ec506952baec 100644 --- a/src/ui/qgswfssourceselectbase.ui +++ b/src/ui/qgswfssourceselectbase.ui @@ -149,7 +149,7 @@ true - Filter: + Filter lineFilter diff --git a/src/ui/raster/qgsrastertransparencywidget.ui b/src/ui/raster/qgsrastertransparencywidget.ui index 59e131c77a1d..2c81488363bf 100644 --- a/src/ui/raster/qgsrastertransparencywidget.ui +++ b/src/ui/raster/qgsrastertransparencywidget.ui @@ -40,7 +40,7 @@ Use original source no data value. - No data value: + No data value diff --git a/src/ui/symbollayer/widget_shapeburstfill.ui b/src/ui/symbollayer/widget_shapeburstfill.ui index 3bc30a62f599..e930c5b9f9b1 100644 --- a/src/ui/symbollayer/widget_shapeburstfill.ui +++ b/src/ui/symbollayer/widget_shapeburstfill.ui @@ -126,7 +126,7 @@ - Shade to a set distance: + Shade to a set distance From 24361c5349eb31cc70145b830d875ae43dc92786 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 4 Nov 2016 11:22:28 +0800 Subject: [PATCH 614/897] Fix crash with tiled WMS (fixes #15799) (cherry picked from commit 16719b3f0f166667fdead8731a9ffe7227ab39f8) --- src/providers/wms/qgswmsprovider.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/providers/wms/qgswmsprovider.cpp b/src/providers/wms/qgswmsprovider.cpp index c9284fa94f33..679df2cdee62 100644 --- a/src/providers/wms/qgswmsprovider.cpp +++ b/src/providers/wms/qgswmsprovider.cpp @@ -512,6 +512,9 @@ static bool _fuzzyContainsRect( const QRectF& r1, const QRectF& r2 ) void QgsWmsProvider::fetchOtherResTiles( QgsTileMode tileMode, const QgsRectangle& viewExtent, int imageWidth, QList& missingRects, double tres, int resOffset, QList& otherResTiles ) { + if ( !mTileMatrixSet ) + return; // there is no tile matrix set defined for ordinary WMS (with user-specified tile size) + const QgsWmtsTileMatrix* tmOther = mTileMatrixSet->findOtherResolution( tres, resOffset ); if ( !tmOther ) return; @@ -655,6 +658,8 @@ QImage *QgsWmsProvider::draw( QgsRectangle const & viewExtent, int pixelWidth, i } else if ( mSettings.mMaxWidth != 0 && mSettings.mMaxHeight != 0 ) { + // this is an ordinary WMS server, but the user requested tiled approach + // so we will pretend it is a WMS-C server with just one tile matrix tempTm.reset( new QgsWmtsTileMatrix ); tempTm->topLeft = QgsPoint( mLayerExtent.xMinimum(), mLayerExtent.yMaximum() ); tempTm->tileWidth = mSettings.mMaxWidth; From 0dd094ca9df50db8e1299ed2d4c66013fbc46c39 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Fri, 4 Nov 2016 13:07:40 +0800 Subject: [PATCH 615/897] Remove per-pixel debug msg slowing down reprojection (fixes #15796) Even at level 5, the debug string would still be built and thrown away, and affects both debug builds and RelWithDebugInfo (used for windows -dev builds). (cherry picked from commit db0e7d57218f29dd5a6f386b8b4ce40f11a3ab59) --- src/core/raster/qgsrasterprojector.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/core/raster/qgsrasterprojector.cpp b/src/core/raster/qgsrasterprojector.cpp index 10cdad91677b..9fcbec166cba 100644 --- a/src/core/raster/qgsrasterprojector.cpp +++ b/src/core/raster/qgsrasterprojector.cpp @@ -827,7 +827,6 @@ QgsRasterBlock * QgsRasterProjector::block( int bandNo, QgsRectangle const & ex if ( !inside ) continue; // we have everything set to no data qgssize srcIndex = static_cast< qgssize >( srcRow ) * pd.srcCols() + srcCol; - QgsDebugMsgLevel( QString( "row = %1 col = %2 srcRow = %3 srcCol = %4" ).arg( i ).arg( j ).arg( srcRow ).arg( srcCol ), 5 ); // isNoData() may be slow so we check doNoData first if ( doNoData && inputBlock->isNoData( srcRow, srcCol ) ) From ea43ce0e00574f79b68da3526117ae4a151927d2 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 4 Nov 2016 09:13:38 +0100 Subject: [PATCH 616/897] Always create a main network access manager Or threaded networking - like XYZ layers - will crash in standalone apps. --- src/core/qgsapplication.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 0fca3df2926c..56c48264adcd 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -882,6 +882,9 @@ void QgsApplication::initQgis() // create map layer registry if doesn't exist QgsMapLayerRegistry::instance(); + // Make sure we have a NAM created on the main thread. + QgsNetworkAccessManager::instance(); + // initialize authentication manager and connect to database QgsAuthManager::instance()->init( pluginPath() ); } From f582849ca7d95d664fc490239031f473ba69c160 Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Fri, 4 Nov 2016 09:46:17 +0100 Subject: [PATCH 617/897] [tests] Authmanager Postgres PKI test --- tests/src/python/CMakeLists.txt | 4 +- tests/src/python/qgis_wrapped_server.py | 47 +++- ...nt.py => test_authmanager_password_ows.py} | 26 +- .../python/test_authmanager_pki_postgres.py | 237 ++++++++++++++++++ tests/src/python/utilities.py | 6 +- 5 files changed, 301 insertions(+), 19 deletions(-) rename tests/src/python/{test_authmanager_endpoint.py => test_authmanager_password_ows.py} (87%) create mode 100644 tests/src/python/test_authmanager_pki_postgres.py diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index c40a7689b025..9ab937676126 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -159,5 +159,7 @@ IF (WITH_SERVER) ADD_PYTHON_TEST(PyQgsServerAccessControl test_qgsserver_accesscontrol.py) ADD_PYTHON_TEST(PyQgsServerWFST test_qgsserver_wfst.py) ADD_PYTHON_TEST(PyQgsOfflineEditingWFS test_offline_editing_wfs.py) - ADD_PYTHON_TEST(PyQgsAuthManagerEndpointTest test_authmanager_endpoint.py) + ADD_PYTHON_TEST(PyQgsAuthManagerPasswordOWSTest test_authmanager_password_ows.py) + #ADD_PYTHON_TEST(PyQgsAuthManagerPKIOWSTest test_authmanager_pki_ows.py) + ADD_PYTHON_TEST(PyQgsAuthManagerPKIPostgresTest test_authmanager_pki_postgres.py) ENDIF (WITH_SERVER) diff --git a/tests/src/python/qgis_wrapped_server.py b/tests/src/python/qgis_wrapped_server.py index 8740aa3d6c7b..2e980a6a8469 100644 --- a/tests/src/python/qgis_wrapped_server.py +++ b/tests/src/python/qgis_wrapped_server.py @@ -3,7 +3,7 @@ QGIS Server HTTP wrapper This script launches a QGIS Server listening on port 8081 or on the port -specified on the environment variable QGIS_SERVER_PORT +specified on the environment variable QGIS_SERVER_PORT. QGIS_SERVER_HOST (defaults to 127.0.0.1) For testing purposes, HTTP Basic can be enabled by setting the following @@ -13,6 +13,21 @@ * QGIS_SERVER_USERNAME (default ="username") * QGIS_SERVER_PASSWORD (default ="password") +PKI authentication with HTTPS can be enabled with: + + * QGIS_SERVER_PKI_CERTIFICATE (server certificate) + * QGIS_SERVER_PKI_KEY (server private key) + * QGIS_SERVER_PKI_AUTHORITY (root CA) + * QGIS_SERVER_PKI_USERNAME (valid username) + + Sample run: + +QGIS_SERVER_PKI_USERNAME=Gerardus QGIS_SERVER_PORT=47547 QGIS_SERVER_HOST=localhost \ + QGIS_SERVER_PKI_KEY=/home/$USER/dev/QGIS/tests/testdata/auth_system/certs_keys/localhost_ssl_key.pem \ + QGIS_SERVER_PKI_CERTIFICATE=/home/$USER/dev/QGIS/tests/testdata/auth_system/certs_keys/localhost_ssl_cert.pem \ + QGIS_SERVER_PKI_AUTHORITY=/home/$USER/dev/QGIS/tests/testdata/auth_system/certs_keys/chains_subissuer-issuer-root_issuer2-root2.pem \ + python3 /home/$USER/dev/QGIS/tests/src/python/qgis_wrapped_server.py + .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -32,6 +47,7 @@ import os import sys import signal +import ssl import urllib.parse from http.server import BaseHTTPRequestHandler, HTTPServer from qgis.core import QgsApplication @@ -39,6 +55,21 @@ QGIS_SERVER_PORT = int(os.environ.get('QGIS_SERVER_PORT', '8081')) QGIS_SERVER_HOST = os.environ.get('QGIS_SERVER_HOST', '127.0.0.1') +# PKI authentication +QGIS_SERVER_PKI_CERTIFICATE = os.environ.get('QGIS_SERVER_PKI_CERTIFICATE') +QGIS_SERVER_PKI_KEY = os.environ.get('QGIS_SERVER_PKI_KEY') +QGIS_SERVER_PKI_AUTHORITY = os.environ.get('QGIS_SERVER_PKI_AUTHORITY') +QGIS_SERVER_PKI_USERNAME = os.environ.get('QGIS_SERVER_PKI_USERNAME') + +# Check if PKI - https is enabled +https = (QGIS_SERVER_PKI_CERTIFICATE is not None and + os.path.isfile(QGIS_SERVER_PKI_CERTIFICATE) and + QGIS_SERVER_PKI_KEY is not None and + os.path.isfile(QGIS_SERVER_PKI_KEY) and + QGIS_SERVER_PKI_AUTHORITY is not None and + os.path.isfile(QGIS_SERVER_PKI_AUTHORITY) and + QGIS_SERVER_PKI_USERNAME) + qgs_app = QgsApplication([], False) qgs_server = QgsServer() @@ -75,6 +106,8 @@ def do_GET(self): for k, v in self.headers.items(): qgs_server.putenv('HTTP_%s' % k.replace(' ', '-').replace('-', '_').replace(' ', '-').upper(), v) qgs_server.putenv('SERVER_PORT', str(self.server.server_port)) + if https: + qgs_server.putenv('HTTPS', 'ON') qgs_server.putenv('SERVER_NAME', self.server.server_name) qgs_server.putenv('REQUEST_URI', self.path) parsed_path = urllib.parse.urlparse(self.path) @@ -101,8 +134,16 @@ def do_POST(self): if __name__ == '__main__': server = HTTPServer((QGIS_SERVER_HOST, QGIS_SERVER_PORT), Handler) - print('Starting server on %s:%s, use to stop' % - (QGIS_SERVER_HOST, server.server_port), flush=True) + if https: + server.socket = ssl.wrap_socket(server.socket, + certfile=QGIS_SERVER_PKI_CERTIFICATE, + keyfile=QGIS_SERVER_PKI_KEY, + ca_certs=QGIS_SERVER_PKI_AUTHORITY, + cert_reqs=ssl.CERT_REQUIRED, + server_side=True, + ssl_version=ssl.PROTOCOL_TLSv1) + print('Starting server on %s://%s:%s, use to stop' % + ('https' if https else 'http', QGIS_SERVER_HOST, server.server_port), flush=True) def signal_handler(signal, frame): global qgs_app diff --git a/tests/src/python/test_authmanager_endpoint.py b/tests/src/python/test_authmanager_password_ows.py similarity index 87% rename from tests/src/python/test_authmanager_endpoint.py rename to tests/src/python/test_authmanager_password_ows.py index 5425e7e377db..1006ec8b7fd1 100644 --- a/tests/src/python/test_authmanager_endpoint.py +++ b/tests/src/python/test_authmanager_password_ows.py @@ -8,7 +8,7 @@ configuration to access an HTTP Basic protected endpoint. -From build dir, run: ctest -R PyQgsAuthManagerEndpointTest -V +From build dir, run: ctest -R PyQgsAuthManagerPasswordOWSTest -V .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,7 +30,6 @@ # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' -from urllib.parse import quote from shutil import rmtree from utilities import unitTestDataPath, waitServer @@ -45,11 +44,10 @@ unittest, ) - try: QGIS_SERVER_ENDPOINT_PORT = os.environ['QGIS_SERVER_ENDPOINT_PORT'] except: - QGIS_SERVER_ENDPOINT_PORT = '0' # Auto + QGIS_SERVER_ENDPOINT_PORT = '0' # Auto QGIS_AUTH_DB_DIR_PATH = tempfile.mkdtemp() @@ -74,7 +72,7 @@ def setUpClass(cls): except KeyError: pass cls.testdata_path = unitTestDataPath('qgis_server') + '/' - cls.project_path = quote(cls.testdata_path + "test_project.qgs") + cls.project_path = cls.testdata_path + "test_project.qgs" # Enable auth #os.environ['QGIS_AUTH_PASSWORD_FILE'] = QGIS_AUTH_PASSWORD_FILE authm = QgsAuthManager.instance() @@ -86,26 +84,30 @@ def setUpClass(cls): cls.auth_config.setConfig('username', cls.username) cls.auth_config.setConfig('password', cls.password) assert (authm.storeAuthenticationConfig(cls.auth_config)[0]) + cls.hostname = '127.0.0.1' + cls.protocol = 'http' os.environ['QGIS_SERVER_HTTP_BASIC_AUTH'] = '1' os.environ['QGIS_SERVER_USERNAME'] = cls.username os.environ['QGIS_SERVER_PASSWORD'] = cls.password os.environ['QGIS_SERVER_PORT'] = str(cls.port) + os.environ['QGIS_SERVER_HOST'] = cls.hostname + server_path = os.path.dirname(os.path.realpath(__file__)) + \ '/qgis_wrapped_server.py' cls.server = subprocess.Popen([sys.executable, server_path], env=os.environ, stdout=subprocess.PIPE) + line = cls.server.stdout.readline() cls.port = int(re.findall(b':(\d+)', line)[0]) assert cls.port != 0 # Wait for the server process to start - assert waitServer('http://127.0.0.1:%s' % cls.port), "Server is not responding!" + assert waitServer('%s://%s:%s' % (cls.protocol, cls.hostname, cls.port)), "Server is not responding! %s://%s:%s" % (cls.protocol, cls.hostname, cls.port) @classmethod def tearDownClass(cls): """Run after all tests""" cls.server.terminate() - cls.server.wait() rmtree(QGIS_AUTH_DB_DIR_PATH) del cls.server @@ -127,7 +129,7 @@ def _getWFSLayer(cls, type_name, layer_name=None, authcfg=None): parms = { 'srsname': 'EPSG:4326', 'typename': type_name, - 'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path), + 'url': '%s://%s:%s/?map=%s' % (cls.protocol, cls.hostname, cls.port, cls.project_path), 'version': 'auto', 'table': '', } @@ -146,12 +148,12 @@ def _getWMSLayer(cls, layers, layer_name=None, authcfg=None): layer_name = 'wms_' + layers.replace(',', '') parms = { 'crs': 'EPSG:4326', - 'url': 'http://127.0.0.1:%s/?map=%s' % (cls.port, cls.project_path), - 'format': 'image/png', + 'url': '%s://%s:%s/?map=%s' % (cls.protocol, cls.hostname, cls.port, cls.project_path), # This is needed because of a really weird implementation in QGIS Server, that # replaces _ in the the real layer name with spaces - 'layers': urllib.parse.quote(layers).replace('_', ' '), + 'layers': urllib.parse.quote(layers.replace('_', ' ')), 'styles': '', + 'version': 'auto', #'sql': '', } if authcfg is not None: @@ -173,7 +175,7 @@ def testInvalidAuthAccess(self): """ Access the HTTP Basic protected layer with no credentials """ - wfs_layer = self._getWFSLayer('testlayer_èé') + wfs_layer = self._getWFSLayer('testlayer èé') self.assertFalse(wfs_layer.isValid()) wms_layer = self._getWMSLayer('testlayer_èé') self.assertFalse(wms_layer.isValid()) diff --git a/tests/src/python/test_authmanager_pki_postgres.py b/tests/src/python/test_authmanager_pki_postgres.py new file mode 100644 index 000000000000..5b7a1b65f90f --- /dev/null +++ b/tests/src/python/test_authmanager_pki_postgres.py @@ -0,0 +1,237 @@ +# -*- coding: utf-8 -*- +""" +Tests for auth manager PKI access to postgres. + +This is an integration test for QGIS Desktop Auth Manager postgres provider that +checks if QGIS can use a stored auth manager auth configuration to access +a PKI protected postgres. + +Configuration form the environment: + + * QGIS_POSTGRES_SERVER_PORT (default: 55432) + * QGIS_POSTGRES_EXECUTABLE_PATH (default: /usr/lib/postgresql/9.4/bin) + + +From build dir, run: ctest -R PyQgsAuthManagerPKIPostgresTest -V + +or, if your postgresql path differs from the default: + +QGIS_POSTGRES_EXECUTABLE_PATH=/usr/lib/postgresql//bin \ + ctest -R PyQgsAuthManagerPKIPostgresTest -V + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +import os +import time +import signal +import stat +import subprocess +import tempfile + +from shutil import rmtree + +from utilities import unitTestDataPath +from qgis.core import ( + QgsAuthManager, + QgsAuthMethodConfig, + QgsVectorLayer, + QgsDataSourceUri, + QgsWkbTypes, +) + +from qgis.PyQt.QtNetwork import QSslCertificate + +from qgis.testing import ( + start_app, + unittest, +) + + +__author__ = 'Alessandro Pasotti' +__date__ = '25/10/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +QGIS_POSTGRES_SERVER_PORT = os.environ.get('QGIS_POSTGRES_SERVER_PORT', '55432') +QGIS_POSTGRES_EXECUTABLE_PATH = os.environ.get('QGIS_POSTGRES_EXECUTABLE_PATH', '/usr/lib/postgresql/9.4/bin') + +assert os.path.exists(QGIS_POSTGRES_EXECUTABLE_PATH) + +QGIS_AUTH_DB_DIR_PATH = tempfile.mkdtemp() + +# Postgres test path +QGIS_PG_TEST_PATH = tempfile.mkdtemp() + +os.environ['QGIS_AUTH_DB_DIR_PATH'] = QGIS_AUTH_DB_DIR_PATH + +qgis_app = start_app() + +QGIS_POSTGRES_CONF_TEMPLATE = """ +hba_file = '%(tempfolder)s/pg_hba.conf' +listen_addresses = '*' +port = %(port)s +max_connections = 100 +unix_socket_directories = '%(tempfolder)s' +ssl = true +ssl_ciphers = 'DEFAULT:!LOW:!EXP:!MD5:@STRENGTH' # allowed SSL ciphers +ssl_cert_file = '%(server_cert)s' +ssl_key_file = '%(server_key)s' +ssl_ca_file = '%(sslrootcert_path)s' +password_encryption = on +""" + +QGIS_POSTGRES_HBA_TEMPLATE = """ +hostssl all all 0.0.0.0/0 cert clientcert=1 +hostssl all all ::1/0 cert clientcert=1 +host all all 127.0.0.1/32 trust +host all all ::1/32 trust +""" + + +class TestAuthManager(unittest.TestCase): + + @classmethod + def setUpAuth(cls): + """Run before all tests and set up authentication""" + authm = QgsAuthManager.instance() + assert (authm.setMasterPassword('masterpassword', True)) + cls.pg_conf = os.path.join(cls.tempfolder, 'postgresql.conf') + cls.pg_hba = os.path.join(cls.tempfolder, 'pg_hba.conf') + # Client side + cls.sslrootcert_path = os.path.join(cls.certsdata_path, 'chains_subissuer-issuer-root_issuer2-root2.pem') + cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem') + cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem') + assert os.path.isfile(cls.sslcert) + assert os.path.isfile(cls.sslkey) + assert os.path.isfile(cls.sslrootcert_path) + os.chmod(cls.sslcert, stat.S_IRUSR) + os.chmod(cls.sslkey, stat.S_IRUSR) + os.chmod(cls.sslrootcert_path, stat.S_IRUSR) + cls.auth_config = QgsAuthMethodConfig("PKI-Paths") + cls.auth_config.setConfig('certpath', cls.sslcert) + cls.auth_config.setConfig('keypath', cls.sslkey) + cls.auth_config.setName('test_pki_auth_config') + cls.username = 'Gerardus' + cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path) + assert cls.sslrootcert is not None + authm.storeCertAuthorities(cls.sslrootcert) + authm.rebuildCaCertsCache() + authm.rebuildTrustedCaCertsCache() + authm.rebuildCertTrustCache() + assert (authm.storeAuthenticationConfig(cls.auth_config)[0]) + assert cls.auth_config.isValid() + + # Server side + cls.server_cert = os.path.join(cls.certsdata_path, 'localhost_ssl_cert.pem') + cls.server_key = os.path.join(cls.certsdata_path, 'localhost_ssl_key.pem') + cls.server_rootcert = cls.sslrootcert_path + os.chmod(cls.server_cert, stat.S_IRUSR) + os.chmod(cls.server_key, stat.S_IRUSR) + os.chmod(cls.server_rootcert, stat.S_IRUSR) + + # Place conf in the data folder + with open(cls.pg_conf, 'w+') as f: + f.write(QGIS_POSTGRES_CONF_TEMPLATE % { + 'port': cls.port, + 'tempfolder': cls.tempfolder, + 'server_cert': cls.server_cert, + 'server_key': cls.server_key, + 'sslrootcert_path': cls.sslrootcert_path, + }) + + with open(cls.pg_hba, 'w+') as f: + f.write(QGIS_POSTGRES_HBA_TEMPLATE) + + @classmethod + def setUpClass(cls): + """Run before all tests: + Creates an auth configuration""" + cls.port = QGIS_POSTGRES_SERVER_PORT + cls.dbname = 'test_pki' + cls.tempfolder = QGIS_PG_TEST_PATH + cls.certsdata_path = os.path.join(unitTestDataPath('auth_system'), 'certs_keys') + cls.hostname = 'localhost' + cls.data_path = os.path.join(cls.tempfolder, 'data') + os.mkdir(cls.data_path) + + cls.setUpAuth() + subprocess.check_call([os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'initdb'), '-D', cls.data_path]) + + cls.server = subprocess.Popen([os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'postgres'), '-D', + cls.data_path, '-c', + "config_file=%s" % cls.pg_conf], + env=os.environ, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + # Wait max 10 secs for the server to start + end = time.time() + 10 + while True: + line = cls.server.stderr.readline() + print(line) + if line.find(b"database system is ready to accept") != -1: + break + if time.time() > end: + raise Exception("Timeout connecting to postgresql") + # Create a DB + subprocess.check_call([os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'createdb'), '-h', 'localhost', '-p', cls.port, 'test_pki']) + # Inject test SQL from test path + test_sql = os.path.join(unitTestDataPath('provider'), 'testdata_pg.sql') + subprocess.check_call([os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'psql'), '-h', 'localhost', '-p', cls.port, '-f', test_sql, cls.dbname]) + # Create a role + subprocess.check_call([os.path.join(QGIS_POSTGRES_EXECUTABLE_PATH, 'psql'), '-h', 'localhost', '-p', cls.port, '-c', 'CREATE ROLE "%s" WITH SUPERUSER LOGIN' % cls.username, cls.dbname]) + + @classmethod + def tearDownClass(cls): + """Run after all tests""" + cls.server.terminate() + os.kill(cls.server.pid, signal.SIGABRT) + del cls.server + time.sleep(2) + rmtree(QGIS_AUTH_DB_DIR_PATH) + rmtree(cls.tempfolder) + + def setUp(self): + """Run before each test.""" + pass + + def tearDown(self): + """Run after each test.""" + pass + + @classmethod + def _getPostGISLayer(cls, type_name, layer_name=None, authcfg=None): + """ + PG layer factory + """ + if layer_name is None: + layer_name = 'pg_' + type_name + uri = QgsDataSourceUri() + uri.setWkbType(QgsWkbTypes.Point) + uri.setConnection("localhost", cls.port, cls.dbname, "", "", QgsDataSourceUri.SslVerifyFull, authcfg) + uri.setKeyColumn('pk') + uri.setSrid('EPSG:4326') + uri.setDataSource('qgis_test', 'someData', "geom", "", "pk") + # Note: do not expand here! + layer = QgsVectorLayer(uri.uri(False), layer_name, 'postgres') + return layer + + def testValidAuthAccess(self): + """ + Access the protected layer with valid credentials + """ + pg_layer = self._getPostGISLayer('testlayer_èé', authcfg=self.auth_config.id()) + self.assertTrue(pg_layer.isValid()) + + def testInvalidAuthAccess(self): + """ + Access the protected layer with not valid credentials + """ + pg_layer = self._getPostGISLayer('testlayer_èé') + self.assertFalse(pg_layer.isValid()) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/src/python/utilities.py b/tests/src/python/utilities.py index 5532f04474ad..20caf949f2aa 100644 --- a/tests/src/python/utilities.py +++ b/tests/src/python/utilities.py @@ -19,9 +19,9 @@ import platform import tempfile try: - from urllib2 import urlopen, HTTPError + from urllib2 import urlopen, HTTPError, URLError except ImportError: - from urllib.request import urlopen, HTTPError + from urllib.request import urlopen, HTTPError, URLError from qgis.PyQt.QtCore import QDir @@ -847,7 +847,7 @@ def waitServer(url, timeout=10): try: urlopen(url, timeout=1) return True - except HTTPError: + except (HTTPError, URLError): return True except Exception as e: if now() > end: From f587defde24595ad85a5ad08c19f915eebdd3658 Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Fri, 4 Nov 2016 09:50:34 +0100 Subject: [PATCH 618/897] [tests][bugfix] Check for result diff existance before accessing to it --- tests/src/python/test_qgsserver.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/src/python/test_qgsserver.py b/tests/src/python/test_qgsserver.py index ac046a7f3a36..826c422d3ba0 100644 --- a/tests/src/python/test_qgsserver.py +++ b/tests/src/python/test_qgsserver.py @@ -502,11 +502,13 @@ def _img_diff_error(self, response, headers, image, max_diff=10, max_size_diff=Q report, encoded_rendered_file.strip(), tempfile.gettempdir(), image ) - with open(os.path.join(tempfile.gettempdir(), image + "_result_diff.png"), "rb") as diff_file: - encoded_diff_file = base64.b64encode(diff_file.read()) - message += "\nDiff:\necho '%s' | base64 -d > %s/%s_result_diff.png" % ( - encoded_diff_file.strip(), tempfile.gettempdir(), image - ) + # If the failure is in image sizes the diff file will not exists. + if os.path.exists(os.path.join(tempfile.gettempdir(), image + "_result_diff.png")): + with open(os.path.join(tempfile.gettempdir(), image + "_result_diff.png"), "rb") as diff_file: + encoded_diff_file = base64.b64encode(diff_file.read()) + message += "\nDiff:\necho '%s' | base64 -d > %s/%s_result_diff.png" % ( + encoded_diff_file.strip(), tempfile.gettempdir(), image + ) self.assertTrue(test, message) From a0e0fcf9a971dba6a8f7d2f2e4e3fdf790ce303d Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Fri, 4 Nov 2016 12:09:57 +0100 Subject: [PATCH 619/897] [tests] WMS/WFS PKI authentication test --- tests/src/python/CMakeLists.txt | 2 +- tests/src/python/test_authmanager_pki_ows.py | 213 ++++++++++++++++++ .../certs_keys/127_0_0_1_ssl_cert.pem | 17 ++ .../certs_keys/127_0_0_1_ssl_key.pem | 15 ++ 4 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 tests/src/python/test_authmanager_pki_ows.py create mode 100644 tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_cert.pem create mode 100644 tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_key.pem diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index bc7f23935dff..ebb1705fc6b5 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -161,6 +161,6 @@ IF (WITH_SERVER) ADD_PYTHON_TEST(PyQgsServerWFST test_qgsserver_wfst.py) ADD_PYTHON_TEST(PyQgsOfflineEditingWFS test_offline_editing_wfs.py) ADD_PYTHON_TEST(PyQgsAuthManagerPasswordOWSTest test_authmanager_password_ows.py) - #ADD_PYTHON_TEST(PyQgsAuthManagerPKIOWSTest test_authmanager_pki_ows.py) + ADD_PYTHON_TEST(PyQgsAuthManagerPKIOWSTest test_authmanager_pki_ows.py) ADD_PYTHON_TEST(PyQgsAuthManagerPKIPostgresTest test_authmanager_pki_postgres.py) ENDIF (WITH_SERVER) diff --git a/tests/src/python/test_authmanager_pki_ows.py b/tests/src/python/test_authmanager_pki_ows.py new file mode 100644 index 000000000000..3ce9c40cea39 --- /dev/null +++ b/tests/src/python/test_authmanager_pki_ows.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +""" +Tests for auth manager WMS/WFS using QGIS Server through PKI +enabled qgis_wrapped_server.py. + +This is an integration test for QGIS Desktop Auth Manager WFS and WMS provider +and QGIS Server WFS/WMS that check if QGIS can use a stored auth manager auth +configuration to access an HTTP Basic protected endpoint. + + +From build dir, run: ctest -R PyQgsAuthManagerPKIOWSTest -V + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +import os +import sys +import re +import subprocess +import tempfile +import urllib +import stat + +__author__ = 'Alessandro Pasotti' +__date__ = '25/10/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +from shutil import rmtree + +from utilities import unitTestDataPath, waitServer +from qgis.core import ( + QgsAuthManager, + QgsAuthMethodConfig, + QgsVectorLayer, + QgsRasterLayer, +) + +from qgis.PyQt.QtNetwork import QSslCertificate + +from qgis.testing import ( + start_app, + unittest, +) + +try: + QGIS_SERVER_ENDPOINT_PORT = os.environ['QGIS_SERVER_ENDPOINT_PORT'] +except: + QGIS_SERVER_ENDPOINT_PORT = '0' # Auto + + +QGIS_AUTH_DB_DIR_PATH = tempfile.mkdtemp() + +os.environ['QGIS_AUTH_DB_DIR_PATH'] = QGIS_AUTH_DB_DIR_PATH + +qgis_app = start_app() + + +class TestAuthManager(unittest.TestCase): + + @classmethod + def setUpAuth(cls): + """Run before all tests and set up authentication""" + authm = QgsAuthManager.instance() + assert (authm.setMasterPassword('masterpassword', True)) + cls.sslrootcert_path = os.path.join(cls.certsdata_path, 'chains_subissuer-issuer-root_issuer2-root2.pem') + cls.sslcert = os.path.join(cls.certsdata_path, 'gerardus_cert.pem') + cls.sslkey = os.path.join(cls.certsdata_path, 'gerardus_key.pem') + assert os.path.isfile(cls.sslcert) + assert os.path.isfile(cls.sslkey) + assert os.path.isfile(cls.sslrootcert_path) + os.chmod(cls.sslcert, stat.S_IRUSR) + os.chmod(cls.sslkey, stat.S_IRUSR) + os.chmod(cls.sslrootcert_path, stat.S_IRUSR) + cls.auth_config = QgsAuthMethodConfig("PKI-Paths") + cls.auth_config.setConfig('certpath', cls.sslcert) + cls.auth_config.setConfig('keypath', cls.sslkey) + cls.auth_config.setName('test_pki_auth_config') + cls.username = 'Gerardus' + cls.sslrootcert = QSslCertificate.fromPath(cls.sslrootcert_path) + assert cls.sslrootcert is not None + authm.storeCertAuthorities(cls.sslrootcert) + authm.rebuildCaCertsCache() + authm.rebuildTrustedCaCertsCache() + assert (authm.storeAuthenticationConfig(cls.auth_config)[0]) + assert cls.auth_config.isValid() + + # cls.server_cert = os.path.join(cls.certsdata_path, 'localhost_ssl_cert.pem') + cls.server_cert = os.path.join(cls.certsdata_path, '127_0_0_1_ssl_cert.pem') + # cls.server_key = os.path.join(cls.certsdata_path, 'localhost_ssl_key.pem') + cls.server_key = os.path.join(cls.certsdata_path, '127_0_0_1_ssl_key.pem') + cls.server_rootcert = cls.sslrootcert_path + os.chmod(cls.server_cert, stat.S_IRUSR) + os.chmod(cls.server_key, stat.S_IRUSR) + os.chmod(cls.server_rootcert, stat.S_IRUSR) + + os.environ['QGIS_SERVER_HOST'] = cls.hostname + os.environ['QGIS_SERVER_PORT'] = str(cls.port) + os.environ['QGIS_SERVER_PKI_KEY'] = cls.server_key + os.environ['QGIS_SERVER_PKI_CERTIFICATE'] = cls.server_cert + os.environ['QGIS_SERVER_PKI_USERNAME'] = cls.username + os.environ['QGIS_SERVER_PKI_AUTHORITY'] = cls.server_rootcert + + @classmethod + def setUpClass(cls): + """Run before all tests: + Creates an auth configuration""" + cls.port = QGIS_SERVER_ENDPOINT_PORT + # Clean env just to be sure + env_vars = ['QUERY_STRING', 'QGIS_PROJECT_FILE'] + for ev in env_vars: + try: + del os.environ[ev] + except KeyError: + pass + cls.testdata_path = unitTestDataPath('qgis_server') + cls.certsdata_path = os.path.join(unitTestDataPath('auth_system'), 'certs_keys') + cls.project_path = os.path.join(cls.testdata_path, "test_project.qgs") + # cls.hostname = 'localhost' + cls.protocol = 'https' + cls.hostname = '127.0.0.1' + + cls.setUpAuth() + + server_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), + 'qgis_wrapped_server.py') + cls.server = subprocess.Popen([sys.executable, server_path], + env=os.environ, stdout=subprocess.PIPE) + line = cls.server.stdout.readline() + cls.port = int(re.findall(b':(\d+)', line)[0]) + assert cls.port != 0 + # Wait for the server process to start + assert waitServer('%s://%s:%s' % (cls.protocol, cls.hostname, cls.port)), "Server is not responding! %s://%s:%s" % (cls.protocol, cls.hostname, cls.port) + + @classmethod + def tearDownClass(cls): + """Run after all tests""" + cls.server.terminate() + rmtree(QGIS_AUTH_DB_DIR_PATH) + del cls.server + + def setUp(self): + """Run before each test.""" + pass + + def tearDown(self): + """Run after each test.""" + pass + + @classmethod + def _getWFSLayer(cls, type_name, layer_name=None, authcfg=None): + """ + WFS layer factory + """ + if layer_name is None: + layer_name = 'wfs_' + type_name + parms = { + 'srsname': 'EPSG:4326', + 'typename': type_name, + 'url': '%s://%s:%s/?map=%s' % (cls.protocol, cls.hostname, cls.port, cls.project_path), + 'version': 'auto', + 'table': '', + } + if authcfg is not None: + parms.update({'authcfg': authcfg}) + try: # Py2 + uri = ' '.join([("%s='%s'" % (k, v.decode('utf-8'))) for k, v in list(parms.items())]) + except AttributeError: # Py3 + uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())]) + wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS') + return wfs_layer + + @classmethod + def _getWMSLayer(cls, layers, layer_name=None, authcfg=None): + """ + WMS layer factory + """ + if layer_name is None: + layer_name = 'wms_' + layers.replace(',', '') + parms = { + 'crs': 'EPSG:4326', + 'url': '%s://%s:%s/?map=%s' % (cls.protocol, cls.hostname, cls.port, cls.project_path), + 'format': 'image/png', + # This is needed because of a really weird implementation in QGIS Server, that + # replaces _ in the the real layer name with spaces + 'layers': urllib.parse.quote(layers.replace('_', ' ')), + 'styles': '', + 'version': 'auto', + #'sql': '', + } + if authcfg is not None: + parms.update({'authcfg': authcfg}) + uri = '&'.join([("%s=%s" % (k, v.replace('=', '%3D'))) for k, v in list(parms.items())]) + wms_layer = QgsRasterLayer(uri, layer_name, 'wms') + return wms_layer + + def testValidAuthAccess(self): + """ + Access the protected layer with valid credentials + Note: cannot test invalid access in a separate test because + it would fail the subsequent (valid) calls due to cached connections + """ + wfs_layer = self._getWFSLayer('testlayer_èé', authcfg=self.auth_config.id()) + self.assertTrue(wfs_layer.isValid()) + wms_layer = self._getWMSLayer('testlayer_èé', authcfg=self.auth_config.id()) + self.assertTrue(wms_layer.isValid()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_cert.pem b/tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_cert.pem new file mode 100644 index 000000000000..de6401396267 --- /dev/null +++ b/tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_cert.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICnzCCAggCCQDJz/SWI+RkwzANBgkqhkiG9w0BAQsFADCBqDELMAkGA1UEBhMC +VVMxDzANBgNVBAgTBkFsYXNrYTESMBAGA1UEBxMJQW5jaG9yYWdlMRUwEwYDVQQK +EwxRR0lTIFRlc3QgQ0ExHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEb +MBkGA1UEAxMSUUdJUyBUZXN0IFJvb3QyIENBMSAwHgYJKoZIhvcNAQkBFhF0ZXN0 +Y2VydEBxZ2lzLm9yZzAeFw0xNjExMDQxMDM0NDVaFw0xNjEyMDQxMDM0NDVaMH8x +CzAJBgNVBAYTAkNBMQ8wDQYDVQQIDAZBbGFza2ExEjAQBgNVBAcMCUFuY2hvcmFn +ZTEVMBMGA1UECgwMUUdJUyBUZXN0IENBMRIwEAYDVQQDDAkxMjcuMC4wLjExIDAe +BgkqhkiG9w0BCQEWEXRlc3RjZXJ0QHFnaXMub3JnMIGfMA0GCSqGSIb3DQEBAQUA +A4GNADCBiQKBgQDPPRCUxvl0kcDr6tvpFJ8LuwCAP9p9SOC7Fx1JvQfLVv/Ded7x +7Tn967S57AGgVyYgA09qD68UUlGLKi2fqVIO2OsBflJ9iKyOM71UlIA7mH96+ZSZ +xYjxpHoDQ8F6856+RXHBGq8JkAxUmASCMq6a5Zcw+7C7R5/4CYHFXGFgRQIDAQAB +MA0GCSqGSIb3DQEBCwUAA4GBAClo2Omx26R7Av9dr51I23no4Kp3CBey81pAkn5w +jGE9nuPy+ndaSVV0+8+WMyPf7eZrkVOn41DsF1Z6eiIQsQ+2JQdOc3lIXwpJKXJJ +0RK1ZLLaH95II3E0U6cGatDcs/jEua26T/Th6+eg5lP+mfovUBJLerYHZW0Jsfs+ +GlzG +-----END CERTIFICATE----- diff --git a/tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_key.pem b/tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_key.pem new file mode 100644 index 000000000000..0441256f43f4 --- /dev/null +++ b/tests/testdata/auth_system/certs_keys/127_0_0_1_ssl_key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXQIBAAKBgQDPPRCUxvl0kcDr6tvpFJ8LuwCAP9p9SOC7Fx1JvQfLVv/Ded7x +7Tn967S57AGgVyYgA09qD68UUlGLKi2fqVIO2OsBflJ9iKyOM71UlIA7mH96+ZSZ +xYjxpHoDQ8F6856+RXHBGq8JkAxUmASCMq6a5Zcw+7C7R5/4CYHFXGFgRQIDAQAB +AoGBAMyNycAQZknZVEOJHmeCIzrA6k2suUzQkoIY3p/aJcdfqDSaJqVFMuifr1OU +0EYjv0359nkJ4hZ86mAi0cW2q3aVawkc32XgK7DS/QoJ6XL8ysyWEoBifdOnDBBY +wmMXgVI1SlR+6PvK12DpeoRAVS+BBlBt1J7lb36CHfl/FVxBAkEA7FZjCK12pBrT +4OZm8XPtFrAvBuFptAwDxdm58gxj2EEuO7aBF3Vs5Ha63J5JCAVEQe/PJUNyWBZx +I7420MI/qwJBAOB66sqV4fq5jT7W0DqvHOdBjQlvaRlo9ZNG+hZt/8QoRc02PaIa +aqICt2zmxT/WCuKBw8a0JvTs/GlrLi9er88CQH+0il0FBofUa0sqlNPB1Yod97tb +EHgWye8eIGkXotgXGHlxu73GWOn28jAGY+Yumlyaza8QC/hnYAl1Xj9dx3MCQFZU +bz+B7OpzubJVArfO6Jq3Rvo98nlnOCpvvXYqz5Ystst49LMG3cN4r/odtfYa5wy9 +QwGD/wdqrJgONDDbhVkCQQCnqfTgHgK7c8z+s03htgEHEGj+tNID8Brrg8y9X3QA +i4E7CnQ587WiQsq0jv5txqoksqMXGf/aQuYJEqJyELrB +-----END RSA PRIVATE KEY----- From 5984b21852dcb0323f6a14609106c9ad6620c281 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Sat, 5 Nov 2016 12:10:25 +0800 Subject: [PATCH 620/897] Add missing /Factory/ annotations to geometry classes --- python/core/geometry/qgsabstractgeometry.sip | 2 +- python/core/geometry/qgscircularstring.sip | 4 ++-- python/core/geometry/qgscompoundcurve.sip | 4 ++-- python/core/geometry/qgscurve.sip | 4 ++-- python/core/geometry/qgscurvepolygon.sip | 4 ++-- python/core/geometry/qgsgeometrycollection.sip | 4 ++-- python/core/geometry/qgsmulticurve.sip | 2 +- python/core/geometry/qgsmultilinestring.sip | 2 +- python/core/geometry/qgsmultipoint.sip | 2 +- python/core/geometry/qgsmultipolygon.sip | 2 +- python/core/geometry/qgsmultisurface.sip | 2 +- python/core/geometry/qgspolygon.sip | 4 ++-- python/core/geometry/qgssurface.sip | 2 +- 13 files changed, 19 insertions(+), 19 deletions(-) diff --git a/python/core/geometry/qgsabstractgeometry.sip b/python/core/geometry/qgsabstractgeometry.sip index 910487a1a768..179adcf559ae 100644 --- a/python/core/geometry/qgsabstractgeometry.sip +++ b/python/core/geometry/qgsabstractgeometry.sip @@ -85,7 +85,7 @@ class QgsAbstractGeometry /** Clones the geometry by performing a deep copy */ - virtual QgsAbstractGeometry* clone() const = 0; + virtual QgsAbstractGeometry* clone() const = 0 /Factory/; /** Clears the geometry, ie reset it to a null geometry */ diff --git a/python/core/geometry/qgscircularstring.sip b/python/core/geometry/qgscircularstring.sip index b24835c25337..0358616466a9 100644 --- a/python/core/geometry/qgscircularstring.sip +++ b/python/core/geometry/qgscircularstring.sip @@ -13,7 +13,7 @@ class QgsCircularString: public QgsCurve virtual QString geometryType() const; virtual int dimension() const; - virtual QgsCircularString* clone() const; + virtual QgsCircularString* clone() const /Factory/; virtual void clear(); virtual bool fromWkb( QgsConstWkbPtr wkb ); @@ -58,7 +58,7 @@ class QgsCircularString: public QgsCurve * of the curve. * @param tolerance segmentation tolerance * @param toleranceType maximum segmentation angle or maximum difference between approximation and curve*/ - virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const; + virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const /Factory/; void draw( QPainter& p ) const; void transform( const QgsCoordinateTransform& ct, QgsCoordinateTransform::TransformDirection d = QgsCoordinateTransform::ForwardTransform, diff --git a/python/core/geometry/qgscompoundcurve.sip b/python/core/geometry/qgscompoundcurve.sip index 8751cce2606e..3418bf8c2101 100644 --- a/python/core/geometry/qgscompoundcurve.sip +++ b/python/core/geometry/qgscompoundcurve.sip @@ -15,7 +15,7 @@ class QgsCompoundCurve: public QgsCurve virtual QString geometryType() const; virtual int dimension() const; - virtual QgsCompoundCurve* clone() const; + virtual QgsCompoundCurve* clone() const /Factory/; virtual void clear(); virtual bool fromWkb( QgsConstWkbPtr wkb ); @@ -38,7 +38,7 @@ class QgsCompoundCurve: public QgsCurve * of the curve. * @param tolerance segmentation tolerance * @param toleranceType maximum segmentation angle or maximum difference between approximation and curve*/ - virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const; + virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const /Factory/; /** Returns the number of curves in the geometry. */ diff --git a/python/core/geometry/qgscurve.sip b/python/core/geometry/qgscurve.sip index f403b142c739..4e36af3710ed 100644 --- a/python/core/geometry/qgscurve.sip +++ b/python/core/geometry/qgscurve.sip @@ -10,7 +10,7 @@ class QgsCurve: public QgsAbstractGeometry virtual bool operator==( const QgsCurve& other ) const = 0; virtual bool operator!=( const QgsCurve& other ) const = 0; - virtual QgsCurve* clone() const = 0; + virtual QgsCurve* clone() const = 0 /Factory/; /** Returns the starting point of the curve. * @see endPoint @@ -35,7 +35,7 @@ class QgsCurve: public QgsAbstractGeometry * @param tolerance segmentation tolerance * @param toleranceType maximum segmentation angle or maximum difference between approximation and curve */ - virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const = 0; + virtual QgsLineString* curveToLine( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const = 0 /Factory/; /** Adds a curve to a painter path. */ diff --git a/python/core/geometry/qgscurvepolygon.sip b/python/core/geometry/qgscurvepolygon.sip index dc933816d4f2..8aea54587c3e 100644 --- a/python/core/geometry/qgscurvepolygon.sip +++ b/python/core/geometry/qgscurvepolygon.sip @@ -12,7 +12,7 @@ class QgsCurvePolygon: public QgsSurface virtual QString geometryType() const; virtual int dimension() const; - virtual QgsCurvePolygon* clone() const; + virtual QgsCurvePolygon* clone() const /Factory/; void clear(); virtual bool fromWkb( QgsConstWkbPtr wkb ); @@ -28,7 +28,7 @@ class QgsCurvePolygon: public QgsSurface //surface interface virtual double area() const; virtual double perimeter() const; - QgsPolygonV2* surfaceToPolygon() const; + QgsPolygonV2* surfaceToPolygon() const /Factory/; virtual QgsAbstractGeometry* boundary() const /Factory/; diff --git a/python/core/geometry/qgsgeometrycollection.sip b/python/core/geometry/qgsgeometrycollection.sip index 1847eb0cb4af..017aec6e680a 100644 --- a/python/core/geometry/qgsgeometrycollection.sip +++ b/python/core/geometry/qgsgeometrycollection.sip @@ -10,7 +10,7 @@ class QgsGeometryCollection: public QgsAbstractGeometry //QgsGeometryCollection& operator=( const QgsGeometryCollection& c ); virtual ~QgsGeometryCollection(); - virtual QgsGeometryCollection* clone() const; + virtual QgsGeometryCollection* clone() const /Factory/; /** Returns the number of geometries within the collection. */ @@ -85,7 +85,7 @@ class QgsGeometryCollection: public QgsAbstractGeometry /** Returns a geometry without curves. Caller takes ownership * @param tolerance segmentation tolerance * @param toleranceType maximum segmentation angle or maximum difference between approximation and curve*/ - QgsAbstractGeometry* segmentize( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const; + QgsAbstractGeometry* segmentize( double tolerance = M_PI_2 / 90, SegmentationToleranceType toleranceType = MaximumAngle ) const /Factory/; /** Returns approximate rotation angle for a vertex. Usually average angle between adjacent segments. * @param vertex the vertex id diff --git a/python/core/geometry/qgsmulticurve.sip b/python/core/geometry/qgsmulticurve.sip index 9e23909534b2..ef56ab53171a 100644 --- a/python/core/geometry/qgsmulticurve.sip +++ b/python/core/geometry/qgsmulticurve.sip @@ -6,7 +6,7 @@ class QgsMultiCurve: public QgsGeometryCollection public: virtual QString geometryType() const; - virtual QgsMultiCurve* clone() const; + virtual QgsMultiCurve* clone() const /Factory/; bool fromWkt( const QString& wkt ); diff --git a/python/core/geometry/qgsmultilinestring.sip b/python/core/geometry/qgsmultilinestring.sip index 29a0843c5b29..932d61521c02 100644 --- a/python/core/geometry/qgsmultilinestring.sip +++ b/python/core/geometry/qgsmultilinestring.sip @@ -6,7 +6,7 @@ class QgsMultiLineString: public QgsMultiCurve public: virtual QString geometryType() const; - virtual QgsMultiLineString* clone() const; + virtual QgsMultiLineString* clone() const /Factory/; bool fromWkt( const QString& wkt ); diff --git a/python/core/geometry/qgsmultipoint.sip b/python/core/geometry/qgsmultipoint.sip index 0e86158aac16..3bfe6e79ff4d 100644 --- a/python/core/geometry/qgsmultipoint.sip +++ b/python/core/geometry/qgsmultipoint.sip @@ -5,7 +5,7 @@ class QgsMultiPointV2: public QgsGeometryCollection %End public: virtual QString geometryType() const; - virtual QgsMultiPointV2* clone() const; + virtual QgsMultiPointV2* clone() const /Factory/; bool fromWkt( const QString& wkt ); diff --git a/python/core/geometry/qgsmultipolygon.sip b/python/core/geometry/qgsmultipolygon.sip index b7a906381723..e56ac94ebad2 100644 --- a/python/core/geometry/qgsmultipolygon.sip +++ b/python/core/geometry/qgsmultipolygon.sip @@ -5,7 +5,7 @@ class QgsMultiPolygonV2: public QgsMultiSurface %End public: virtual QString geometryType() const; - virtual QgsMultiPolygonV2* clone() const; + virtual QgsMultiPolygonV2* clone() const /Factory/; bool fromWkt( const QString& wkt ); diff --git a/python/core/geometry/qgsmultisurface.sip b/python/core/geometry/qgsmultisurface.sip index 9c25dbfa9c82..92a3f822917e 100644 --- a/python/core/geometry/qgsmultisurface.sip +++ b/python/core/geometry/qgsmultisurface.sip @@ -5,7 +5,7 @@ class QgsMultiSurface: public QgsGeometryCollection %End public: virtual QString geometryType() const; - virtual QgsMultiSurface* clone() const; + virtual QgsMultiSurface* clone() const /Factory/; bool fromWkt( const QString& wkt ); diff --git a/python/core/geometry/qgspolygon.sip b/python/core/geometry/qgspolygon.sip index c5f6b8261a2b..dd4490820645 100644 --- a/python/core/geometry/qgspolygon.sip +++ b/python/core/geometry/qgspolygon.sip @@ -11,7 +11,7 @@ class QgsPolygonV2: public QgsCurvePolygon bool operator!=( const QgsPolygonV2& other ) const; virtual QString geometryType() const; - virtual QgsPolygonV2* clone() const; + virtual QgsPolygonV2* clone() const /Factory/; void clear(); virtual bool fromWkb( QgsConstWkbPtr wkb ); @@ -25,7 +25,7 @@ class QgsPolygonV2: public QgsCurvePolygon // inherited: QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; // inherited: QString asJSON( int precision = 17 ) const; - QgsPolygonV2* surfaceToPolygon() const; + QgsPolygonV2* surfaceToPolygon() const /Factory/; /** Returns the geometry converted to the more generic curve type QgsCurvePolygon @return the converted geometry. Caller takes ownership*/ diff --git a/python/core/geometry/qgssurface.sip b/python/core/geometry/qgssurface.sip index 3796d28c3edd..7d7a088e3c92 100644 --- a/python/core/geometry/qgssurface.sip +++ b/python/core/geometry/qgssurface.sip @@ -6,7 +6,7 @@ class QgsSurface: public QgsAbstractGeometry public: - virtual QgsPolygonV2* surfaceToPolygon() const = 0; + virtual QgsPolygonV2* surfaceToPolygon() const = 0 /Factory/; virtual QgsRectangle boundingBox() const; From 701d4440ac0ac599dad230374c48c7a6d4936aa7 Mon Sep 17 00:00:00 2001 From: Andrea Aime Date: Sun, 9 Oct 2016 11:57:38 +0200 Subject: [PATCH 621/897] Export parametric SVG parameters, will fallback symbols for the system that cannot understand them --- .../core/symbology-ng/qgssymbollayerutils.sip | 16 ++++ src/core/symbology-ng/qgsfillsymbollayer.cpp | 12 +-- .../symbology-ng/qgsmarkersymbollayer.cpp | 4 +- src/core/symbology-ng/qgssymbollayerutils.cpp | 67 ++++++++++++++- src/core/symbology-ng/qgssymbollayerutils.h | 16 ++++ .../python/test_qgssymbollayer_createsld.py | 84 +++++++++++++++++-- 6 files changed, 180 insertions(+), 19 deletions(-) diff --git a/python/core/symbology-ng/qgssymbollayerutils.sip b/python/core/symbology-ng/qgssymbollayerutils.sip index c26dbdb344fa..f43c206dde89 100644 --- a/python/core/symbology-ng/qgssymbollayerutils.sip +++ b/python/core/symbology-ng/qgssymbollayerutils.sip @@ -501,4 +501,20 @@ class QgsSymbolLayerUtils */ static void mergeScaleDependencies( int mScaleMinDenom, int mScaleMaxDenom, QgsStringMap& props ); + /** + * Encodes a reference to a parametric SVG into SLD, as a succession of parametric SVG using URL parameters, + * a fallback SVG without parameters, and a final fallback as a mark with the right colors and outline for systems + * that cannot do SVG at all + * @note added in 3.0 + */ + static void parametricSvgToSld( QDomDocument &doc, QDomElement &graphicElem, + const QString& path, + const QColor& fillColor, double size, const QColor& outlineColor, double outlineWidth ); + + /** + * Encodes a reference to a parametric SVG into a path with parameters according to the SVG Parameters spec + * @note added in 3.0 + */ + static QString getSvgParametricPath( const QString& basePath, const QColor& fillColor, const QColor& borderColor, double borderWidth ); + }; diff --git a/src/core/symbology-ng/qgsfillsymbollayer.cpp b/src/core/symbology-ng/qgsfillsymbollayer.cpp index c23ecc085495..94247410a8cf 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.cpp +++ b/src/core/symbology-ng/qgsfillsymbollayer.cpp @@ -2083,8 +2083,10 @@ void QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, cons if ( !mSvgFilePath.isEmpty() ) { - double partternWidth = QgsSymbolLayerUtils::rescaleUom( mPatternWidth, mPatternWidthUnit, props ); - QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, mSvgFilePath, QStringLiteral( "image/svg+xml" ), mColor, partternWidth ); + // encode a parametric SVG reference + double patternWidth = QgsSymbolLayerUtils::rescaleUom( mPatternWidth, mPatternWidthUnit, props ); + double outlineWidth = QgsSymbolLayerUtils::rescaleUom( mSvgOutlineWidth, mSvgOutlineWidthUnit, props ); + QgsSymbolLayerUtils::parametricSvgToSld( doc, graphicElem, mSvgFilePath, mColor, patternWidth, mSvgOutlineColor, outlineWidth ); } else { @@ -2093,12 +2095,6 @@ void QgsSVGFillSymbolLayer::toSld( QDomDocument &doc, QDomElement &element, cons symbolizerElem.appendChild( doc.createComment( QStringLiteral( "SVG from data not implemented yet" ) ) ); } - if ( mSvgOutlineColor.isValid() || mSvgOutlineWidth >= 0 ) - { - double svgOutlineWidth = QgsSymbolLayerUtils::rescaleUom( mSvgOutlineWidth, mSvgOutlineWidthUnit, props ); - QgsSymbolLayerUtils::lineToSld( doc, graphicElem, Qt::SolidLine, mSvgOutlineColor, svgOutlineWidth ); - } - // QString angleFunc; bool ok; diff --git a/src/core/symbology-ng/qgsmarkersymbollayer.cpp b/src/core/symbology-ng/qgsmarkersymbollayer.cpp index fff7ff1b5f78..a2dae580124c 100644 --- a/src/core/symbology-ng/qgsmarkersymbollayer.cpp +++ b/src/core/symbology-ng/qgsmarkersymbollayer.cpp @@ -2194,8 +2194,10 @@ void QgsSvgMarkerSymbolLayer::writeSldMarker( QDomDocument &doc, QDomElement &el QDomElement graphicElem = doc.createElement( QStringLiteral( "se:Graphic" ) ); element.appendChild( graphicElem ); + // encode a parametric SVG reference double size = QgsSymbolLayerUtils::rescaleUom( mSize, mSizeUnit, props ); - QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, mPath, QStringLiteral( "image/svg+xml" ), mColor, size ); + double outlineWidth = QgsSymbolLayerUtils::rescaleUom( mOutlineWidth, mOutlineWidthUnit, props ); + QgsSymbolLayerUtils::parametricSvgToSld( doc, graphicElem, mPath, mColor, size, mOutlineColor, outlineWidth ); // QString angleFunc; diff --git a/src/core/symbology-ng/qgssymbollayerutils.cpp b/src/core/symbology-ng/qgssymbollayerutils.cpp index af7fde79dce0..2f901a38745f 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.cpp +++ b/src/core/symbology-ng/qgssymbollayerutils.cpp @@ -68,7 +68,9 @@ QColor QgsSymbolLayerUtils::decodeColor( const QString& str ) QString QgsSymbolLayerUtils::encodeSldAlpha( int alpha ) { - return QString::number( alpha / 255.0, 'f', 2 ); + QString result; + result.sprintf( "%.2g", alpha / 255.0 ); + return result; } int QgsSymbolLayerUtils::decodeSldAlpha( const QString& str ) @@ -1953,6 +1955,69 @@ void QgsSymbolLayerUtils::externalGraphicToSld( QDomDocument &doc, QDomElement & } } +void QgsSymbolLayerUtils::parametricSvgToSld( QDomDocument &doc, QDomElement &graphicElem, + const QString& path, const QColor& fillColor, double size, const QColor& outlineColor, double outlineWidth ) +{ + // Parametric SVG paths are an extension that few systems will understand, but se:Graphic allows for fallback + // symbols, this encodes the full parametric path first, the pure shape second, and a mark with the right colors as + // a last resort for systems that cannot do SVG at all + + // encode parametric version with all coloring details (size is going to be encoded by the last fallback) + graphicElem.appendChild( doc.createComment( QStringLiteral( "Parametric SVG" ) ) ); + QString parametricPath = getSvgParametricPath( path, fillColor, outlineColor, outlineWidth ); + QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, parametricPath, QStringLiteral( "image/svg+xml" ), fillColor, -1 ); + // also encode a fallback version without parameters, in case a renderer gets confused by the parameters + graphicElem.appendChild( doc.createComment( QStringLiteral( "Plain SVG fallback, no parameters" ) ) ); + QgsSymbolLayerUtils::externalGraphicToSld( doc, graphicElem, path, QStringLiteral( "image/svg+xml" ), fillColor, -1 ); + // finally encode a simple mark with the right colors/outlines for renderers that cannot do SVG at all + graphicElem.appendChild( doc.createComment( QStringLiteral( "Well known marker fallback" ) ) ); + QgsSymbolLayerUtils::wellKnownMarkerToSld( doc, graphicElem, QStringLiteral( "square" ), fillColor, outlineColor, Qt::PenStyle::SolidLine, outlineWidth, -1 ); + + // size is encoded here, it's part of se:Graphic, not attached to the single symbol + if ( size >= 0 ) + { + QDomElement sizeElem = doc.createElement( QStringLiteral( "se:Size" ) ); + sizeElem.appendChild( doc.createTextNode( qgsDoubleToString( size ) ) ); + graphicElem.appendChild( sizeElem ); + } +} + + +QString QgsSymbolLayerUtils::getSvgParametricPath( const QString& basePath, const QColor& fillColor, const QColor& borderColor, double borderWidth ) +{ + QUrl url = QUrl(); + if ( fillColor.isValid() ) + { + url.addQueryItem( QStringLiteral( "fill" ), fillColor.name() ); + url.addQueryItem( QStringLiteral( "fill-opacity" ), encodeSldAlpha( fillColor.alpha() ) ); + } + else + { + url.addQueryItem( "fill", QStringLiteral( "#000000" ) ); + url.addQueryItem( "fill-opacity", QStringLiteral( "1" ) ); + } + if ( borderColor.isValid() ) + { + url.addQueryItem( QStringLiteral( "outline" ), borderColor.name() ); + url.addQueryItem( QStringLiteral( "outline-opacity" ), encodeSldAlpha( borderColor.alpha() ) ); + } + else + { + url.addQueryItem( QStringLiteral( "outline" ), QStringLiteral( "#000000" ) ); + url.addQueryItem( QStringLiteral( "outline-opacity" ), QStringLiteral( "1" ) ); + } + url.addQueryItem( QStringLiteral( "outline-width" ), QString::number( borderWidth ) ); + QString params = url.encodedQuery(); + if ( params.isEmpty() ) + { + return basePath; + } + else + { + return basePath + "?" + params; + } +} + bool QgsSymbolLayerUtils::externalGraphicFromSld( QDomElement &element, QString &path, QString &mime, QColor &color, double &size ) diff --git a/src/core/symbology-ng/qgssymbollayerutils.h b/src/core/symbology-ng/qgssymbollayerutils.h index 743c02d4c0b8..94db084e9fec 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.h +++ b/src/core/symbology-ng/qgssymbollayerutils.h @@ -587,6 +587,22 @@ class CORE_EXPORT QgsSymbolLayerUtils */ static void mergeScaleDependencies( int mScaleMinDenom, int mScaleMaxDenom, QgsStringMap& props ); + /** + * Encodes a reference to a parametric SVG into SLD, as a succession of parametric SVG using URL parameters, + * a fallback SVG without parameters, and a final fallback as a mark with the right colors and outline for systems + * that cannot do SVG at all + * @note added in 3.0 + */ + static void parametricSvgToSld( QDomDocument &doc, QDomElement &graphicElem, + const QString& path, + const QColor& fillColor, double size, const QColor& outlineColor, double outlineWidth ); + + /** + * Encodes a reference to a parametric SVG into a path with parameters according to the SVG Parameters spec + * @note added in 3.0 + */ + static QString getSvgParametricPath( const QString& basePath, const QColor& fillColor, const QColor& borderColor, double borderWidth ); + }; class QPolygonF; diff --git a/tests/src/python/test_qgssymbollayer_createsld.py b/tests/src/python/test_qgssymbollayer_createsld.py index 6c078968966f..f573e9121df1 100644 --- a/tests/src/python/test_qgssymbollayer_createsld.py +++ b/tests/src/python/test_qgssymbollayer_createsld.py @@ -60,9 +60,9 @@ def testSimpleMarkerRotation(self): self.assertStaticRotation(root, '50') - def assertStaticRotation(self, root, expectedValue): + def assertStaticRotation(self, root, expectedValue, index=0): # Check the rotation element is a literal, not a - rotation = root.elementsByTagName('se:Rotation').item(0) + rotation = root.elementsByTagName('se:Rotation').item(index) literal = rotation.firstChild() self.assertEqual("ogc:Literal", literal.nodeName()) self.assertEqual(expectedValue, literal.firstChild().nodeValue()) @@ -127,11 +127,21 @@ def testSimpleMarkerUnitPixels(self): def testSvgMarkerUnitDefault(self): symbol = QgsSvgMarkerSymbolLayer('symbols/star.svg', 10, 90) + symbol.setFillColor(QColor("blue")) + symbol.setOutlineWidth(1) + symbol.setOutlineColor(QColor('red')) + symbol.setPath('symbols/star.svg') symbol.setOffset(QPointF(5, 10)) dom, root = self.symbolToSld(symbol) # print("Svg marker mm: " + dom.toString()) + self.assertExternalGraphic(root, 0, + 'symbols/star.svg?fill=%230000ff&fill-opacity=1&outline=%23ff0000&outline-opacity=1&outline-width=4', 'image/svg+xml') + self.assertExternalGraphic(root, 1, + 'symbols/star.svg', 'image/svg+xml') + self.assertWellKnownMark(root, 0, 'square', '#0000ff', '#ff0000', 4) + # Check the size has been rescaled self.assertStaticSize(root, '36') @@ -141,11 +151,21 @@ def testSvgMarkerUnitDefault(self): def testSvgMarkerUnitPixels(self): symbol = QgsSvgMarkerSymbolLayer('symbols/star.svg', 10, 0) + symbol.setFillColor(QColor("blue")) + symbol.setOutlineWidth(1) + symbol.setOutlineColor(QColor('red')) + symbol.setPath('symbols/star.svg') symbol.setOffset(QPointF(5, 10)) symbol.setOutputUnit(QgsUnitTypes.RenderPixels) dom, root = self.symbolToSld(symbol) # print("Svg marker unit px: " + dom.toString()) + self.assertExternalGraphic(root, 0, + 'symbols/star.svg?fill=%230000ff&fill-opacity=1&outline=%23ff0000&outline-opacity=1&outline-width=1', 'image/svg+xml') + self.assertExternalGraphic(root, 1, + 'symbols/star.svg', 'image/svg+xml') + self.assertWellKnownMark(root, 0, 'square', '#0000ff', '#ff0000', 1) + # Check the size has not been rescaled self.assertStaticSize(root, '10') self.assertStaticDisplacement(root, 5, 10) @@ -154,7 +174,7 @@ def testFontMarkerUnitDefault(self): symbol = QgsFontMarkerSymbolLayer('sans', ',', 10, QColor('black'), 45) symbol.setOffset(QPointF(5, 10)) dom, root = self.symbolToSld(symbol) - # print "Font marker unit mm: " + dom.toString() + # print("Font marker unit mm: " + dom.toString()) # Check the size has been rescaled self.assertStaticSize(root, '36') @@ -300,32 +320,47 @@ def testSimpleFillPixels(self): def testSvgFillDefault(self): symbol = QgsSVGFillSymbolLayer('test/star.svg', 10, 45) + symbol.setSvgFillColor(QColor('blue')) symbol.setSvgOutlineWidth(3) + symbol.setSvgOutlineColor(QColor('yellow')) + symbol.subSymbol().setWidth(10) dom, root = self.symbolToSld(symbol) # print ("Svg fill mm: \n" + dom.toString()) + self.assertExternalGraphic(root, 0, + 'test/star.svg?fill=%230000ff&fill-opacity=1&outline=%23ffff00&outline-opacity=1&outline-width=11', 'image/svg+xml') + self.assertExternalGraphic(root, 1, + 'test/star.svg', 'image/svg+xml') + self.assertWellKnownMark(root, 0, 'square', '#0000ff', '#ffff00', 11) + self.assertStaticRotation(root, '45') self.assertStaticSize(root, '36') - # width of the svg outline - self.assertStrokeWidth(root, 1, 11) # width of the polygon outline - self.assertStrokeWidth(root, 3, 1) + lineSymbolizer = root.elementsByTagName('se:LineSymbolizer').item(0).toElement() + self.assertStrokeWidth(lineSymbolizer, 1, 36) def testSvgFillPixel(self): symbol = QgsSVGFillSymbolLayer('test/star.svg', 10, 45) + symbol.setSvgFillColor(QColor('blue')) symbol.setSvgOutlineWidth(3) symbol.setOutputUnit(QgsUnitTypes.RenderPixels) + symbol.subSymbol().setWidth(10) dom, root = self.symbolToSld(symbol) # print ("Svg fill px: \n" + dom.toString()) + self.assertExternalGraphic(root, 0, + 'test/star.svg?fill=%230000ff&fill-opacity=1&outline=%23000000&outline-opacity=1&outline-width=3', 'image/svg+xml') + self.assertExternalGraphic(root, 1, + 'test/star.svg', 'image/svg+xml') + self.assertWellKnownMark(root, 0, 'square', '#0000ff', '#000000', 3) + self.assertStaticRotation(root, '45') self.assertStaticSize(root, '10') - # width of the svg outline - self.assertStrokeWidth(root, 1, 3) # width of the polygon outline - self.assertStrokeWidth(root, 3, 0.26) + lineSymbolizer = root.elementsByTagName('se:LineSymbolizer').item(0).toElement() + self.assertStrokeWidth(lineSymbolizer, 1, 10) def testLineFillDefault(self): symbol = QgsLinePatternFillSymbolLayer() @@ -497,10 +532,41 @@ def assertStaticSize(self, root, expectedValue): size = root.elementsByTagName('se:Size').item(0) self.assertEqual(expectedValue, size.firstChild().nodeValue()) + def assertExternalGraphic(self, root, index, expectedLink, expectedFormat): + graphic = root.elementsByTagName('se:ExternalGraphic').item(index) + onlineResource = graphic.firstChildElement('se:OnlineResource') + self.assertEqual(expectedLink, onlineResource.attribute('xlink:href')) + format = graphic.firstChildElement('se:Format') + self.assertEqual(expectedFormat, format.firstChild().nodeValue()) + def assertStaticPerpendicularOffset(self, root, expectedValue): offset = root.elementsByTagName('se:PerpendicularOffset').item(0) self.assertEqual(expectedValue, offset.firstChild().nodeValue()) + def assertWellKnownMark(self, root, index, expectedName, expectedFill, expectedStroke, expectedStrokeWidth): + mark = root.elementsByTagName('se:Mark').item(index) + wkn = mark.firstChildElement('se:WellKnownName') + self.assertEqual(expectedName, wkn.text()) + + fill = mark.firstChildElement('se:Fill') + if expectedFill is None: + self.assertTrue(fill.isNull()) + else: + parameter = fill.firstChildElement('se:SvgParameter') + self.assertEqual('fill', parameter.attribute('name')) + self.assertEqual(expectedFill, parameter.text()) + + stroke = mark.firstChildElement('se:Stroke') + if expectedStroke is None: + self.assertTrue(stroke.isNull()) + else: + parameter = stroke.firstChildElement('se:SvgParameter') + self.assertEqual('stroke', parameter.attribute('name')) + self.assertEqual(expectedStroke, parameter.text()) + parameter = parameter.nextSiblingElement('se:SvgParameter') + self.assertEqual('stroke-width', parameter.attribute('name')) + self.assertEqual(str(expectedStrokeWidth), parameter.text()) + def symbolToSld(self, symbolLayer): dom = QDomDocument() root = dom.createElement("FakeRoot") From 022e2285225329d10b5d7791a71ce1a34126fbce Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Sat, 5 Nov 2016 12:01:43 +0100 Subject: [PATCH 622/897] Fill image with 0 in rendering thread (#3722) Calling QImage::fill( 0 ) on rendering start takes about 40% of the time required for setting up a new job. Since this is done on the main thread, the interface feels more snappy the quicker the setup process is completed. --- src/core/qgsmaprenderercustompainterjob.cpp | 3 +++ src/core/qgsmaprendererjob.cpp | 1 - src/core/qgsmaprendererparalleljob.cpp | 3 +++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/qgsmaprenderercustompainterjob.cpp b/src/core/qgsmaprenderercustompainterjob.cpp index c50dbb786367..964c5d16a327 100644 --- a/src/core/qgsmaprenderercustompainterjob.cpp +++ b/src/core/qgsmaprenderercustompainterjob.cpp @@ -244,6 +244,9 @@ void QgsMapRendererCustomPainterJob::doRender() QTime layerTime; layerTime.start(); + if ( job.img ) + job.img->fill( 0 ); + job.renderer->render(); job.renderingTime = layerTime.elapsed(); diff --git a/src/core/qgsmaprendererjob.cpp b/src/core/qgsmaprendererjob.cpp index 5654a10f78ee..90294b9f8047 100644 --- a/src/core/qgsmaprendererjob.cpp +++ b/src/core/qgsmaprendererjob.cpp @@ -286,7 +286,6 @@ LayerRenderJobs QgsMapRendererJob::prepareJobs( QPainter* painter, QgsLabelingEn layerJobs.removeLast(); continue; } - mypFlattenedImage->fill( 0 ); job.img = mypFlattenedImage; QPainter* mypPainter = new QPainter( job.img ); diff --git a/src/core/qgsmaprendererparalleljob.cpp b/src/core/qgsmaprendererparalleljob.cpp index f927c3f59a7d..48785611e824 100644 --- a/src/core/qgsmaprendererparalleljob.cpp +++ b/src/core/qgsmaprendererparalleljob.cpp @@ -215,6 +215,9 @@ void QgsMapRendererParallelJob::renderLayerStatic( LayerRenderJob& job ) if ( job.cached ) return; + if ( job.img ) + job.img->fill( 0 ); + QTime t; t.start(); QgsDebugMsgLevel( QString( "job %1 start (layer %2)" ).arg( reinterpret_cast< ulong >( &job ), 0, 16 ).arg( job.layerId ), 2 ); From e426dbc86b37d22fe55eea788e28688207707f96 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Sat, 5 Nov 2016 12:47:19 +0100 Subject: [PATCH 623/897] fix customwidgets includes path --- src/customwidgets/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/customwidgets/CMakeLists.txt b/src/customwidgets/CMakeLists.txt index 9b398f06e657..2856f08df9f0 100644 --- a/src/customwidgets/CMakeLists.txt +++ b/src/customwidgets/CMakeLists.txt @@ -105,6 +105,7 @@ INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/../gui/ ${CMAKE_CURRENT_SOURCE_DIR}/../gui/attributetable/ ${CMAKE_CURRENT_SOURCE_DIR}/../gui/editorwidgets/ + ${CMAKE_CURRENT_SOURCE_DIR}/../gui/editorwidgets/core ${CMAKE_CURRENT_BINARY_DIR}/../ui/ ) INCLUDE_DIRECTORIES(SYSTEM From 93be141af5336fa73ce50c99b57db196a7a6a6ca Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 6 Nov 2016 13:03:06 +0100 Subject: [PATCH 624/897] [processing] Fix import error in FieldsMappingPanel --- python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py index 106926ba66f3..5a190d586861 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py @@ -31,8 +31,8 @@ from collections import OrderedDict from qgis.PyQt import uic -from qgis.PyQt.QtGui import QBrush, QIcon, QSpacerItem -from qgis.PyQt.QtWidgets import QComboBox, QHeaderView, QLineEdit, QMessageBox, QSpinBox, QStyledItemDelegate +from qgis.PyQt.QtGui import QBrush, QIcon +from qgis.PyQt.QtWidgets import QComboBox, QHeaderView, QLineEdit, QSpacerItem, QMessageBox, QSpinBox, QStyledItemDelegate from qgis.PyQt.QtCore import QItemSelectionModel, QAbstractTableModel, QModelIndex, QVariant, Qt, pyqtSlot from qgis.core import QgsExpression, QgsExpressionContextUtils, QgsApplication, QgsFeature From 2d2fe8b8cc3b86c244b2dbf851552c180b8dbb07 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 6 Nov 2016 13:04:32 +0100 Subject: [PATCH 625/897] [processing] Fix BatchOutputSelectionPanel with QgsMapLayer instances --- .../processing/gui/BatchOutputSelectionPanel.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/BatchOutputSelectionPanel.py b/python/plugins/processing/gui/BatchOutputSelectionPanel.py index 964785382220..8683567cac06 100644 --- a/python/plugins/processing/gui/BatchOutputSelectionPanel.py +++ b/python/plugins/processing/gui/BatchOutputSelectionPanel.py @@ -31,6 +31,7 @@ import os import re +from qgis.core import QgsMapLayer from qgis.PyQt.QtWidgets import QWidget, QPushButton, QLineEdit, QHBoxLayout, QSizePolicy, QFileDialog from qgis.PyQt.QtCore import QSettings @@ -113,9 +114,12 @@ def showSelectionDialog(self): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): - s = str(widget.getText()) - s = os.path.basename(s) - s = os.path.splitext(s)[0] + v = widget.value() + if isinstance(v, QgsMapLayer): + s = v.name() + else: + s = os.path.basename(v) + s = os.path.splitext(s)[0] elif isinstance(param, ParameterBoolean): s = str(widget.currentIndex() == 0) elif isinstance(param, ParameterSelection): From 4a62699472b7663622c6779531de7bd3532cc2cd Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 6 Nov 2016 13:05:32 +0100 Subject: [PATCH 626/897] [processing] Fix TableWidgetWrapper in batch dialog --- python/plugins/processing/gui/wrappers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 393bde645e88..516d536a89b9 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -741,7 +741,7 @@ def value(self): except: return self.widget.getValue() elif self.dialogType == DIALOG_BATCH: - return self.widget.getText() + return self.widget.value() else: def validator(v): return bool(v) or self.param.optional From 8b8bc26ee00fb4049cfdae26af6fd80f8649529f Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Wed, 19 Oct 2016 10:25:04 +0200 Subject: [PATCH 627/897] [processing] Fix connection to postgis --- python/plugins/processing/tools/postgis.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/postgis.py b/python/plugins/processing/tools/postgis.py index 4140ac63437c..bf3a2772da3a 100644 --- a/python/plugins/processing/tools/postgis.py +++ b/python/plugins/processing/tools/postgis.py @@ -59,6 +59,9 @@ def uri_from_name(conn_name): settings.endGroup() + if hasattr(authcfg, 'isNull') and authcfg.isNull(): + authcfg = '' + if service: uri.setConnection(service, database, username, password, sslmode, authcfg) else: @@ -202,7 +205,7 @@ def __init__(self, host=None, port=None, dbname=None, user=None, for i in range(4): expandedConnInfo = self.uri.connectionInfo(True) try: - self.con = psycopg2.connect(expandedConnInfo.encode('utf-8')) + self.con = psycopg2.connect(expandedConnInfo) if err is not None: QgsCredentials.instance().put(conninfo, self.uri.username(), From 9cd39e79dd6bac0b79d3f2da9217777f60c70d66 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Wed, 19 Oct 2016 10:46:02 +0200 Subject: [PATCH 628/897] [db_manager] Fix connection to postgis --- python/plugins/db_manager/db_plugins/postgis/connector.py | 4 ++-- python/plugins/db_manager/db_plugins/postgis/plugin.py | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/python/plugins/db_manager/db_plugins/postgis/connector.py b/python/plugins/db_manager/db_plugins/postgis/connector.py index 7abe0be7d125..b2ba6b6ff106 100644 --- a/python/plugins/db_manager/db_plugins/postgis/connector.py +++ b/python/plugins/db_manager/db_plugins/postgis/connector.py @@ -64,7 +64,7 @@ def __init__(self, uri): expandedConnInfo = self._connectionInfo() try: - self.connection = psycopg2.connect(expandedConnInfo.encode('utf-8')) + self.connection = psycopg2.connect(expandedConnInfo) except self.connection_error_types() as e: err = str(e) uri = self.uri() @@ -83,7 +83,7 @@ def __init__(self, uri): newExpandedConnInfo = uri.connectionInfo(True) try: - self.connection = psycopg2.connect(newExpandedConnInfo.encode('utf-8')) + self.connection = psycopg2.connect(newExpandedConnInfo) QgsCredentials.instance().put(conninfo, username, password) except self.connection_error_types() as e: if i == 2: diff --git a/python/plugins/db_manager/db_plugins/postgis/plugin.py b/python/plugins/db_manager/db_plugins/postgis/plugin.py index 4885e3686532..110308dea565 100644 --- a/python/plugins/db_manager/db_plugins/postgis/plugin.py +++ b/python/plugins/db_manager/db_plugins/postgis/plugin.py @@ -88,6 +88,9 @@ def connect(self, parent=None): settings.endGroup() + if hasattr(authcfg, 'isNull') and authcfg.isNull(): + authcfg = '' + if service: uri.setConnection(service, database, username, password, sslmode, authcfg) else: From 01941176c59f4e3a49092e6d0e2f4c635991fe65 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 6 Nov 2016 15:21:39 +0100 Subject: [PATCH 629/897] [processing] Log gdal calls --- python/plugins/processing/algs/gdal/GdalUtils.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/algs/gdal/GdalUtils.py b/python/plugins/processing/algs/gdal/GdalUtils.py index f366d8fd075c..661336fa3e56 100644 --- a/python/plugins/processing/algs/gdal/GdalUtils.py +++ b/python/plugins/processing/algs/gdal/GdalUtils.py @@ -74,6 +74,7 @@ def runGdal(commands, progress=None): os.putenv('PATH', envval) fused_command = ' '.join([str(c) for c in commands]) + ProcessingLog.addToLog(ProcessingLog.LOG_INFO, fused_command) progress.setInfo('GDAL command:') progress.setCommand(fused_command) progress.setInfo('GDAL command output:') From a6a09d9ae212d87a5e8c906f845aac24a738ffa4 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Sun, 6 Nov 2016 15:25:11 +0100 Subject: [PATCH 630/897] [processing] Fix Ogr2OgrToPostGisList with 8798c42339 and 3472ac80d8bd --- .../algs/gdal/ogr2ogrtopostgislist.py | 64 +++++++++---------- 1 file changed, 29 insertions(+), 35 deletions(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py b/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py index 8f8e9660de46..ba963e4afeeb 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrtopostgislist.py @@ -177,36 +177,30 @@ def getConsoleCommands(self): inLayer = self.getParameterValue(self.INPUT_LAYER) ogrLayer = ogrConnectionString(inLayer)[1:-1] shapeEncoding = self.getParameterValue(self.SHAPE_ENCODING) - ssrs = str(self.getParameterValue(self.S_SRS)) - tsrs = str(self.getParameterValue(self.T_SRS)) - asrs = str(self.getParameterValue(self.A_SRS)) - schema = str(self.getParameterValue(self.SCHEMA)) - table = str(self.getParameterValue(self.TABLE)) - pk = str(self.getParameterValue(self.PK)) - pkstring = "-lco FID=" + pk + ssrs = self.getParameterValue(self.S_SRS) + tsrs = self.getParameterValue(self.T_SRS) + asrs = self.getParameterValue(self.A_SRS) + schema = self.getParameterValue(self.SCHEMA) + table = self.getParameterValue(self.TABLE) + pk = self.getParameterValue(self.PK) primary_key = self.getParameterValue(self.PRIMARY_KEY) - geocolumn = str(self.getParameterValue(self.GEOCOLUMN)) - geocolumnstring = "-lco GEOMETRY_NAME=" + geocolumn + geocolumn = self.getParameterValue(self.GEOCOLUMN) dim = self.DIMLIST[self.getParameterValue(self.DIM)] - dimstring = "-lco DIM=" + dim - simplify = str(self.getParameterValue(self.SIMPLIFY)) - segmentize = str(self.getParameterValue(self.SEGMENTIZE)) + simplify = self.getParameterValue(self.SIMPLIFY) + segmentize = self.getParameterValue(self.SEGMENTIZE) spat = self.getParameterValue(self.SPAT) clip = self.getParameterValue(self.CLIP) - where = str(self.getParameterValue(self.WHERE)) - wherestring = '-where "' + where + '"' - gt = str(self.getParameterValue(self.GT)) + where = self.getParameterValue(self.WHERE) + gt = self.getParameterValue(self.GT) overwrite = self.getParameterValue(self.OVERWRITE) append = self.getParameterValue(self.APPEND) addfields = self.getParameterValue(self.ADDFIELDS) launder = self.getParameterValue(self.LAUNDER) - launderstring = "-lco LAUNDER=NO" index = self.getParameterValue(self.INDEX) - indexstring = "-lco SPATIAL_INDEX=OFF" skipfailures = self.getParameterValue(self.SKIPFAILURES) promotetomulti = self.getParameterValue(self.PROMOTETOMULTI) precision = self.getParameterValue(self.PRECISION) - options = str(self.getParameterValue(self.OPTIONS)) + options = self.getParameterValue(self.OPTIONS) arguments = [] arguments.append('-progress') @@ -222,13 +216,13 @@ def getConsoleCommands(self): arguments.append(token) arguments.append('active_schema={}'.format(schema or 'public')) arguments.append('"') - arguments.append(dimstring) + arguments.append("-lco DIM=" + dim) arguments.append(ogrLayer) arguments.append(ogrLayerName(inLayer)) if index: - arguments.append(indexstring) + arguments.append("-lco SPATIAL_INDEX=OFF") if launder: - arguments.append(launderstring) + arguments.append("-lco LAUNDER=NO") if append: arguments.append('-append') if addfields: @@ -238,28 +232,28 @@ def getConsoleCommands(self): if len(self.GEOMTYPE[self.getParameterValue(self.GTYPE)]) > 0: arguments.append('-nlt') arguments.append(self.GEOMTYPE[self.getParameterValue(self.GTYPE)]) - if len(geocolumn) > 0: - arguments.append(geocolumnstring) - if len(pk) > 0: - arguments.append(pkstring) + if geocolumn: + arguments.append("-lco GEOMETRY_NAME=" + geocolumn) + if pk: + arguments.append("-lco FID=" + pk) elif primary_key is not None: arguments.append("-lco FID=" + primary_key) - if len(table) == 0: + if not table: table = ogrLayerName(inLayer).lower() if schema: table = '{}.{}'.format(schema, table) arguments.append('-nln') arguments.append(table) - if len(ssrs) > 0: + if ssrs: arguments.append('-s_srs') arguments.append(ssrs) - if len(tsrs) > 0: + if tsrs: arguments.append('-t_srs') arguments.append(tsrs) - if len(asrs) > 0: + if asrs: arguments.append('-a_srs') arguments.append(asrs) - if len(spat) > 0: + if spat: regionCoords = spat.split(',') arguments.append('-spat') arguments.append(regionCoords[0]) @@ -271,21 +265,21 @@ def getConsoleCommands(self): if skipfailures: arguments.append('-skipfailures') if where: - arguments.append(wherestring) - if len(simplify) > 0: + arguments.append('-where "' + where + '"') + if simplify: arguments.append('-simplify') arguments.append(simplify) - if len(segmentize) > 0: + if segmentize: arguments.append('-segmentize') arguments.append(segmentize) - if len(gt) > 0: + if gt: arguments.append('-gt') arguments.append(gt) if promotetomulti: arguments.append('-nlt PROMOTE_TO_MULTI') if precision is False: arguments.append('-lco PRECISION=NO') - if len(options) > 0: + if options: arguments.append(options) commands = [] From a8d9dea1fb6e586d712cf43d7415efe1cd701b14 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Thu, 8 Sep 2016 18:30:42 +0200 Subject: [PATCH 631/897] Add QgsExpressionContextGenerator inheritances in sip --- python/core/composer/qgscomposerobject.sip | 2 +- python/core/composer/qgscomposition.sip | 2 +- python/core/qgsproject.sip | 2 +- python/core/qgsvectorlayer.sip | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/core/composer/qgscomposerobject.sip b/python/core/composer/qgscomposerobject.sip index b03858e97bfa..1795407239c9 100644 --- a/python/core/composer/qgscomposerobject.sip +++ b/python/core/composer/qgscomposerobject.sip @@ -1,7 +1,7 @@ /** \ingroup core * A base class for objects which belong to a map composition. */ -class QgsComposerObject : QObject +class QgsComposerObject : QObject, QgsExpressionContextGenerator { %TypeHeaderCode #include diff --git a/python/core/composer/qgscomposition.sip b/python/core/composer/qgscomposition.sip index de829338c97d..8f0c9d1446ef 100644 --- a/python/core/composer/qgscomposition.sip +++ b/python/core/composer/qgscomposition.sip @@ -4,7 +4,7 @@ * them in a list in ascending z-Order. This list can be changed to lower/raise items one position * or to bring them to front/back. * */ -class QgsComposition : QGraphicsScene +class QgsComposition : QGraphicsScene, QgsExpressionContextGenerator { %TypeHeaderCode #include diff --git a/python/core/qgsproject.sip b/python/core/qgsproject.sip index 73a1f294321d..c6a4406865da 100644 --- a/python/core/qgsproject.sip +++ b/python/core/qgsproject.sip @@ -13,7 +13,7 @@ properties. */ -class QgsProject : QObject +class QgsProject : QObject, QgsExpressionContextGenerator { %TypeHeaderCode #include diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index 12c4b9ebadd0..88d9b3320dda 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -316,7 +316,7 @@ struct QgsVectorJoinInfo */ -class QgsVectorLayer : QgsMapLayer +class QgsVectorLayer : QgsMapLayer, QgsExpressionContextGenerator { %TypeHeaderCode #include "qgsvectorlayer.h" From 78236c0be1096e5c0ffbc8d8b24c844539821610 Mon Sep 17 00:00:00 2001 From: "arnaud.morvan@camptocamp.com" Date: Thu, 8 Sep 2016 18:31:51 +0200 Subject: [PATCH 632/897] Use contextGenerator in refactor fields algorithm --- .../processing/algs/qgis/FieldsMapper.py | 30 +++++++------------ .../algs/qgis/ui/FieldsMappingPanel.py | 20 +++++++++---- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/python/plugins/processing/algs/qgis/FieldsMapper.py b/python/plugins/processing/algs/qgis/FieldsMapper.py index 3f74bcac4188..bd9da22b610c 100644 --- a/python/plugins/processing/algs/qgis/FieldsMapper.py +++ b/python/plugins/processing/algs/qgis/FieldsMapper.py @@ -78,10 +78,7 @@ def processAlgorithm(self, progress): da.setEllipsoid(QgsProject.instance().readEntry( 'Measure', '/Ellipsoid', GEO_NONE)[0]) - exp_context = QgsExpressionContext() - exp_context.appendScope(QgsExpressionContextUtils.globalScope()) - exp_context.appendScope(QgsExpressionContextUtils.projectScope()) - exp_context.appendScope(QgsExpressionContextUtils.layerScope(layer)) + exp_context = layer.createExpressionContext() for field_def in mapping: fields.append(QgsField(name=field_def['name'], @@ -93,18 +90,12 @@ def processAlgorithm(self, progress): expression.setGeomCalculator(da) expression.setDistanceUnits(QgsProject.instance().distanceUnits()) expression.setAreaUnits(QgsProject.instance().areaUnits()) - + expression.prepare(exp_context) if expression.hasParserError(): raise GeoAlgorithmExecutionException( self.tr(u'Parser error in expression "{}": {}') - .format(str(field_def['expression']), - str(expression.parserErrorString()))) - expression.prepare(exp_context) - if expression.hasEvalError(): - raise GeoAlgorithmExecutionException( - self.tr(u'Evaluation error in expression "{}": {}') - .format(str(field_def['expression']), - str(expression.evalErrorString()))) + .format(unicode(expression.expression()), + unicode(expression.parserErrorString()))) expressions.append(expression) writer = output.getVectorWriter(fields, @@ -112,8 +103,7 @@ def processAlgorithm(self, progress): layer.crs()) # Create output vector layer with new attributes - error = '' - calculationSuccess = True + error_exp = None inFeat = QgsFeature() outFeat = QgsFeature() features = vector.features(layer) @@ -132,8 +122,7 @@ def processAlgorithm(self, progress): exp_context.lastScope().setVariable("row_number", rownum) value = expression.evaluate(exp_context) if expression.hasEvalError(): - calculationSuccess = False - error = expression.evalErrorString() + error_exp = expression break attrs.append(value) @@ -145,7 +134,8 @@ def processAlgorithm(self, progress): del writer - if not calculationSuccess: + if error_exp is not None: raise GeoAlgorithmExecutionException( - self.tr('An error occurred while evaluating the calculation' - ' string:\n') + error) + self.tr(u'Evaluation error in expression "{}": {}') + .format(unicode(error_exp.expression()), + unicode(error_exp.parserErrorString()))) diff --git a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py index 106926ba66f3..ad3a51c9ccf6 100644 --- a/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py +++ b/python/plugins/processing/algs/qgis/ui/FieldsMappingPanel.py @@ -35,7 +35,7 @@ from qgis.PyQt.QtWidgets import QComboBox, QHeaderView, QLineEdit, QMessageBox, QSpinBox, QStyledItemDelegate from qgis.PyQt.QtCore import QItemSelectionModel, QAbstractTableModel, QModelIndex, QVariant, Qt, pyqtSlot -from qgis.core import QgsExpression, QgsExpressionContextUtils, QgsApplication, QgsFeature +from qgis.core import QgsExpression, QgsProject, QgsApplication from qgis.gui import QgsFieldExpressionWidget from processing.gui.wrappers import WidgetWrapper, DIALOG_STANDARD, DIALOG_MODELER @@ -87,21 +87,30 @@ def testAllExpressions(self): def testExpression(self, row): self._errors[row] = None field = self._mapping[row] + exp_context = self.contextGenerator().createExpressionContext() + expression = QgsExpression(field['expression']) + expression.prepare(exp_context) if expression.hasParserError(): self._errors[row] = expression.parserErrorString() return + + # test evaluation on the first feature if self._layer is None: return - context = QgsExpressionContextUtils.createFeatureBasedContext(QgsFeature(), self._layer.fields()) for feature in self._layer.getFeatures(): - context.setFeature(feature) - expression.evaluate(context) + exp_context.setFeature(feature) + exp_context.lastScope().setVariable("row_number", 1) + expression.evaluate(exp_context) if expression.hasEvalError(): self._errors[row] = expression.evalErrorString() - return break + def contextGenerator(self): + if self._layer: + return self._layer + return QgsProject.instance() + def layer(self): return self._layer @@ -254,6 +263,7 @@ def createEditor(self, parent, option, index): elif fieldType == QgsExpression: editor = QgsFieldExpressionWidget(parent) editor.setLayer(index.model().layer()) + editor.registerExpressionContextGenerator(index.model().contextGenerator()) editor.fieldChanged.connect(self.on_expression_fieldChange) else: From eefa7115bf2f34ac052e7d977db89d533f7ea306 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 09:22:50 +1000 Subject: [PATCH 633/897] [processing] Fix invalid geometries made by densify when input geom is null --- .../processing/algs/qgis/DensifyGeometries.py | 12 +++++------- .../algs/qgis/DensifyGeometriesInterval.py | 12 +++++------- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/python/plugins/processing/algs/qgis/DensifyGeometries.py b/python/plugins/processing/algs/qgis/DensifyGeometries.py index f5b45f92db75..2ad758de22e6 100644 --- a/python/plugins/processing/algs/qgis/DensifyGeometries.py +++ b/python/plugins/processing/algs/qgis/DensifyGeometries.py @@ -72,13 +72,11 @@ def processAlgorithm(self, progress): features = vector.features(layer) total = 100.0 / len(features) for current, f in enumerate(features): - featGeometry = f.geometry() - attrs = f.attributes() - newGeometry = self.densifyGeometry(featGeometry, int(vertices), - isPolygon) - feature = QgsFeature() - feature.setGeometry(newGeometry) - feature.setAttributes(attrs) + feature = f + if feature.hasGeometry(): + new_geometry = self.densifyGeometry(feature.geometry(), int(vertices), + isPolygon) + feature.setGeometry(new_geometry) writer.addFeature(feature) progress.setPercentage(int(current * total)) diff --git a/python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py b/python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py index aaa176e3923b..42aa376bbb36 100644 --- a/python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py +++ b/python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py @@ -69,13 +69,11 @@ def processAlgorithm(self, progress): features = vector.features(layer) total = 100.0 / len(features) for current, f in enumerate(features): - featGeometry = f.geometry() - attrs = f.attributes() - newGeometry = self.densifyGeometry(featGeometry, interval, - isPolygon) - feature = QgsFeature() - feature.setGeometry(newGeometry) - feature.setAttributes(attrs) + feature = f + if feature.hasGeometry(): + new_geometry = self.densifyGeometry(feature.geometry(), interval, + isPolygon) + feature.setGeometry(new_geometry) writer.addFeature(feature) progress.setPercentage(int(current * total)) From 143c18da6feb89624817ad660128a4e23f9a26ab Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 09:23:35 +1000 Subject: [PATCH 634/897] Fix processing tests weren't actually comparing resultant features .... oops (my fault - copy/paste error) --- python/testing/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/testing/__init__.py b/python/testing/__init__.py index 15c6f26be780..7289292f75dd 100644 --- a/python/testing/__init__.py +++ b/python/testing/__init__.py @@ -78,7 +78,7 @@ def assertLayersEqual(self, layer_expected, layer_result, **kwargs): precision = 14 expected_features = sorted(layer_expected.getFeatures(request), key=lambda f: f.id()) - result_features = sorted(layer_expected.getFeatures(request), key=lambda f: f.id()) + result_features = sorted(layer_result.getFeatures(request), key=lambda f: f.id()) for feats in zip(expected_features, result_features): if feats[0].hasGeometry(): @@ -105,7 +105,7 @@ def assertLayersEqual(self, layer_expected, layer_result, **kwargs): attr_result = feats[1][field_expected.name()] field_result = [fld for fld in layer_expected.fields().toList() if fld.name() == field_expected.name()][0] try: - cmp = compare['fields'][field1.name()] + cmp = compare['fields'][field_expected.name()] except KeyError: try: cmp = compare['fields']['__all__'] From d783c732a56caeb634b50b9d63b6fe8b0b16f994 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 09:24:54 +1000 Subject: [PATCH 635/897] Fix processing tests --- .../expected/clip_lines_by_multipolygon.gml | 4 +- .../expected/clip_lines_by_multipolygon.xsd | 23 ----- .../expected/clip_lines_by_polygon.gfs | 2 + .../expected/clip_lines_by_polygon.gml | 2 +- .../expected/clip_lines_by_polygon.xsd | 23 ----- .../clip_multipolygons_by_polygons.gfs | 1 + .../clip_multipolygons_by_polygons.xsd | 43 --------- .../expected/clip_points_by_multipolygons.gfs | 3 +- .../expected/clip_points_by_multipolygons.gml | 12 +-- .../expected/clip_points_by_multipolygons.xsd | 23 ----- .../expected/clip_points_by_polygons.gfs | 3 +- .../expected/clip_points_by_polygons.gml | 12 +-- .../expected/clip_points_by_polygons.xsd | 23 ----- .../expected/clip_polys_by_multipolygon.gfs | 3 +- .../expected/clip_polys_by_multipolygon.gml | 6 +- .../expected/clip_polys_by_multipolygon.xsd | 43 --------- .../innerRingTouchesOuterRing_output.gfs | 1 + .../innerRingTouchesOuterRing_output.gml | 2 +- .../innerRingTouchesOuterRing_output.xsd | 48 ---------- .../testdata/expected/multipolys_densify.gfs | 1 + .../testdata/expected/multipolys_densify.xsd | 43 --------- .../tests/testdata/qgis_algorithm_tests.yaml | 88 ++++++++++++++++--- 22 files changed, 107 insertions(+), 302 deletions(-) delete mode 100644 python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multipolys_densify.xsd diff --git a/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.gml b/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.gml index 09acada91279..269dee7e0e4f 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.gml +++ b/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.gml @@ -18,12 +18,12 @@ - 4,1 3,1 + 4,1 3,1 - 7,2 8,2 + 7,2 8,2 diff --git a/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.xsd b/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.xsd deleted file mode 100644 index 0438e776aed9..000000000000 --- a/python/plugins/processing/tests/testdata/expected/clip_lines_by_multipolygon.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gfs b/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gfs index 3f06cc7a1b6d..2738c2815a1e 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gfs +++ b/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gfs @@ -2,6 +2,8 @@ clip_lines_by_polygon clip_lines_by_polygon + + 5 EPSG:4326 2 diff --git a/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gml b/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gml index e75f63e79167..5213e28bcd06 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gml +++ b/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.gml @@ -13,7 +13,7 @@ - 0.776536312849161,2.179050279329609 4.049720670391062,1.334357541899442 5.70391061452514,-1.991620111731844 8.572346368715085,-2.220391061452514 8.565567160553801,-3.0 + 0.776536312849161,2.179050279329609 4.049720670391062,1.334357541899442 5.70391061452514,-1.991620111731844 8.572346368715085,-2.220391061452514 8.565567160553801,-3.0 diff --git a/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.xsd b/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.xsd deleted file mode 100644 index 8bf59a08af92..000000000000 --- a/python/plugins/processing/tests/testdata/expected/clip_lines_by_polygon.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.gfs b/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.gfs index 637d994cb446..f5151e4b8f06 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.gfs +++ b/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.gfs @@ -2,6 +2,7 @@ clip_multipolygons_by_polygons clip_multipolygons_by_polygons + 6 EPSG:4326 diff --git a/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.xsd b/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.xsd deleted file mode 100644 index 26f5502d9985..000000000000 --- a/python/plugins/processing/tests/testdata/expected/clip_multipolygons_by_polygons.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gfs b/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gfs index 1557b311014c..46a68d545cde 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gfs +++ b/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gfs @@ -2,7 +2,8 @@ clip_points_by_multipolygons clip_points_by_multipolygons - 1 + + 4 EPSG:4326 6 diff --git a/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gml b/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gml index 09872f4d1b6a..01da5f25839f 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gml +++ b/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.gml @@ -13,32 +13,32 @@ - 3,3 + 3,3 - 2,2 + 2,2 - 4,1 + 4,1 - 8,-1 + 8,-1 - 7,-1 + 7,-1 - 1,1 + 1,1 diff --git a/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.xsd b/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.xsd deleted file mode 100644 index 022c175e5382..000000000000 --- a/python/plugins/processing/tests/testdata/expected/clip_points_by_multipolygons.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gfs b/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gfs index 33cfb7d09e4a..6a93432d4562 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gfs +++ b/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gfs @@ -2,7 +2,8 @@ clip_points_by_polygons clip_points_by_polygons - 1 + + 4 EPSG:4326 6 diff --git a/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gml b/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gml index 19639fe1a3fc..f236f117f01a 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gml +++ b/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.gml @@ -13,32 +13,32 @@ - 1,1 + 1,1 - 3,3 + 3,3 - 2,2 + 2,2 - 0,-1 + 0,-1 - 7,-1 + 7,-1 - 4,1 + 4,1 diff --git a/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.xsd b/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.xsd deleted file mode 100644 index 872bcf00804d..000000000000 --- a/python/plugins/processing/tests/testdata/expected/clip_points_by_polygons.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gfs b/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gfs index b7080238185e..4d91b0d4c54c 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gfs +++ b/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gfs @@ -2,7 +2,8 @@ clip_polys_by_multipolygon clip_polys_by_multipolygon - 3 + + 6 EPSG:4326 3 diff --git a/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gml b/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gml index a5c859ca85ad..18c98ff3cf11 100644 --- a/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gml +++ b/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.gml @@ -13,7 +13,7 @@ - 0,0 0,1 1,1 1,0 0,0 + 0,0 0,1 1,1 1,0 0,0 aaaaa 33 44.123456 @@ -21,7 +21,7 @@ - 2,1 2,2 3,2 4.0,1.666666666666667 4,1 2,1 + 2,1 2,2 3,2 4.0,1.666666666666667 4,1 2,1 elim 2 3.33 @@ -29,7 +29,7 @@ - 7,1 8,1 8,0 7,0 7,1 + 7,1 8,1 8,0 7,0 7,1 ASDF 0 diff --git a/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.xsd b/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.xsd deleted file mode 100644 index 4fac3a72bc4c..000000000000 --- a/python/plugins/processing/tests/testdata/expected/clip_polys_by_multipolygon.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gfs b/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gfs index 801ebe683536..d43e4f983fdf 100644 --- a/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gfs +++ b/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gfs @@ -2,6 +2,7 @@ innerRingTouchesOuterRing_output innerRingTouchesOuterRing_output + 6 EPSG:3003 diff --git a/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gml b/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gml index 3f0f11950de7..facc54fb19c9 100644 --- a/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gml +++ b/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.gml @@ -13,7 +13,7 @@ - 1756000.153752481099218,5078705.956589923240244 1754455.495129873743281,5078742.894078725017607 1754447.79750289930962,5080667.300822260789573 1755877.226238435367122,5080654.843926962465048 1756000.153752481099218,5080653.772663222625852 1756184.545023549813777,5080652.16576761752367 1757981.008284030715004,5080636.510314363986254 1757996.403537979349494,5078658.220182008109987 1756368.936294619226828,5078697.137876959517598 1756061.617509504081681,5078704.48680442944169 1756000.153752481099218,5078705.956589923240244 + 1756368.936294619226828,5078697.137876959517598 1756061.617509504081681,5078704.48680442944169 1756000.153752481099218,5078705.956589923240244 1754455.495129873743281,5078742.894078725017607 1754447.79750289930962,5080667.300822260789573 1755877.226238435367122,5080654.843926962465048 1756000.153752481099218,5080653.772663222625852 1756184.545023549813777,5080652.16576761752367 1757981.008284030715004,5080636.510314363986254 1757996.403537979349494,5078658.220182008109987 1756368.936294619226828,5078697.137876959517598 2 45333.519531 1106.347626 diff --git a/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.xsd b/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.xsd deleted file mode 100644 index 868282a51ebb..000000000000 --- a/python/plugins/processing/tests/testdata/expected/innerRingTouchesOuterRing_output.xsd +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multipolys_densify.gfs b/python/plugins/processing/tests/testdata/expected/multipolys_densify.gfs index 1666e4bff1b8..60c148365c1a 100644 --- a/python/plugins/processing/tests/testdata/expected/multipolys_densify.gfs +++ b/python/plugins/processing/tests/testdata/expected/multipolys_densify.gfs @@ -2,6 +2,7 @@ multipolys_densify multipolys_densify + 6 EPSG:4326 diff --git a/python/plugins/processing/tests/testdata/expected/multipolys_densify.xsd b/python/plugins/processing/tests/testdata/expected/multipolys_densify.xsd deleted file mode 100644 index 483620214285..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multipolys_densify.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index e20527f5ea76..7ee879f0c78e 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -132,9 +132,10 @@ tests: - name: Densify geometries algorithm: qgis:densifygeometries params: - - name: multipolys.gml - type: vector - - '4' + INPUT: + name: multipolys.gml + type: vector + VERTICES: 4 results: OUTPUT: name: expected/multipolys_densify.gml @@ -331,7 +332,7 @@ tests: name: expected/innerRingTouchesOuterRing_output.gml compare: geometry: - precision: 5 + precision: 0 - name: Dissolve with NULL geometries algorithm: qgis:dissolve @@ -597,6 +598,9 @@ tests: OUTPUT_LAYER: name: expected/line_offset_round_positive.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:offsetline name: Offset line negative @@ -612,6 +616,9 @@ tests: OUTPUT_LAYER: name: expected/line_offset_round_negative.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:offsetline name: Offset line mitre @@ -627,6 +634,9 @@ tests: OUTPUT_LAYER: name: expected/line_offset_mitre.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:offsetline name: Offset line bevel @@ -642,6 +652,9 @@ tests: OUTPUT_LAYER: name: expected/line_offset_bevel.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:offsetline name: Offset multilines @@ -657,6 +670,9 @@ tests: OUTPUT_LAYER: name: expected/multiline_offset.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:fixeddistancebuffer name: Buffer polygons using bevel @@ -708,6 +724,9 @@ tests: OUTPUT: name: expected/buffer_lines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:fixeddistancebuffer name: Buffer lines (flat) @@ -725,6 +744,9 @@ tests: OUTPUT: name: expected/buffer_lines_flat.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:fixeddistancebuffer name: Buffer lines (square) @@ -742,9 +764,12 @@ tests: OUTPUT: name: expected/buffer_lines_square.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:centroids - name: Test (qgis:centroids) + name: Centroid (lines) params: INPUT_LAYER: name: lines.gml @@ -753,9 +778,12 @@ tests: OUTPUT_LAYER: name: expected/centroid_lines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:centroids - name: Test (qgis:centroids) + name: Centroid (multilines) params: INPUT_LAYER: name: multilines.gml @@ -764,9 +792,12 @@ tests: OUTPUT_LAYER: name: expected/centroid_multilines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:centroids - name: Test (qgis:centroids) + name: Centroid (multipoints) params: INPUT_LAYER: name: multipoints.gml @@ -775,9 +806,12 @@ tests: OUTPUT_LAYER: name: expected/centroid_multipoint.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:centroids - name: Test (qgis:centroids) + name: Centroid (multipolygons) params: INPUT_LAYER: name: multipolys.gml @@ -786,9 +820,12 @@ tests: OUTPUT_LAYER: name: expected/centroid_multipolys.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:centroids - name: Test (qgis:centroids) + name: Centroid (points) params: INPUT_LAYER: name: points.gml @@ -797,9 +834,12 @@ tests: OUTPUT_LAYER: name: expected/centroid_points.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:centroids - name: Test (qgis:centroids) + name: Centroid (polygons) params: INPUT_LAYER: name: polys.gml @@ -808,6 +848,9 @@ tests: OUTPUT_LAYER: name: expected/centroid_polys.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:translategeometry name: Lines translated @@ -838,6 +881,9 @@ tests: OUTPUT_LAYER: name: expected/single_sided_buffer_line.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:singlesidedbuffer name: Single sided buffer lines (Right, mitre) @@ -854,6 +900,9 @@ tests: OUTPUT_LAYER: name: expected/single_sided_buffer_line_mitre.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:singlesidedbuffer name: Single sided buffer multiline (bevel) @@ -951,6 +1000,9 @@ tests: OUTPUT: name: expected/simplify_vis_lines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:simplifygeometries name: Simplify (grid) @@ -964,6 +1016,9 @@ tests: OUTPUT: name: expected/simplify_grid_lines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:smoothgeometry name: Smooth (lines) @@ -1238,7 +1293,9 @@ tests: OUTPUT_LAYER: name: expected/extend_lines.gml type: vector - + compare: + geometry: + precision: 7 - algorithm: qgis:extendlines name: Extend multilines @@ -1264,6 +1321,9 @@ tests: OUTPUT_LAYER: name: expected/extract_specific_nodes_lines.gml type: vector + compare: + fields: + fid: skip - algorithm: qgis:extractspecificnodes name: Extract specific nodes polygons @@ -1276,6 +1336,9 @@ tests: OUTPUT_LAYER: name: expected/extract_specific_nodes_polys.gml type: vector + compare: + fields: + fid: skip - algorithm: qgis:geometrybyexpression name: Geometry by expression (point) @@ -1306,6 +1369,9 @@ tests: OUTPUT_LAYER: name: expected/geometry_by_expression_poly.gml type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:geometrybyexpression name: Geometry by expression (line) From 54522fd590b3ad15e84303801bfde3e9c1fe3bb6 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 09:25:03 +1000 Subject: [PATCH 636/897] Fix crash when trying to render polygon with no exterior ring Should only occur with very badly corrupted layers, but we shouldn't crash in this case --- src/core/symbology-ng/qgssymbol.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index f6f2f16acde3..0023e5e917d0 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -767,6 +767,11 @@ void QgsSymbol::renderFeature( const QgsFeature& feature, QgsRenderContext& cont break; } const QgsPolygonV2& polygon = dynamic_cast( *segmentizedGeometry.geometry() ); + if ( !polygon.exteriorRing() ) + { + QgsDebugMsg( "cannot render polygon with no exterior ring" ); + break; + } _getPolygon( pts, holes, context, polygon, !tileMapRendering && clipFeaturesToExtent() ); static_cast( this )->renderPolygon( pts, ( !holes.isEmpty() ? &holes : nullptr ), &feature, context, layer, selected ); From 272cd3801801cf6f406e28a8122f3dc5e22fc703 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 10:03:15 +1000 Subject: [PATCH 637/897] Fix python deprecation warning --- python/plugins/processing/tools/general.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/general.py b/python/plugins/processing/tools/general.py index dddfa414598e..227b2aa1a824 100644 --- a/python/plugins/processing/tools/general.py +++ b/python/plugins/processing/tools/general.py @@ -90,7 +90,7 @@ def runandload(name, *args, **kwargs): def version(): pluginPath = os.path.split(os.path.dirname(__file__))[0] - cfg = configparser.SafeConfigParser() + cfg = configparser.ConfigParser() cfg.read(os.path.join(pluginPath, 'metadata.txt')) ver = cfg.get('general', 'version').split('.') return 10000 * int(ver[0]) + 100 * int(ver[1]) + int(ver[2]) From b4bca5bb98de1f3ba01c08be768f94f3ddcd3bbd Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 10:03:56 +1000 Subject: [PATCH 638/897] [processing] Don't try to force load files which don't exist --- python/plugins/processing/tools/dataobjects.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 6ad0318edd89..61f0f84212b6 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -267,7 +267,7 @@ def getObjectFromUri(uri, forceLoad=True): for table in tables: if normalizeLayerSource(table.source()) == normalizeLayerSource(uri): return table - if forceLoad: + if forceLoad and os.path.exists(uri): settings = QSettings() prjSetting = settings.value('/Projections/defaultBehaviour') settings.setValue('/Projections/defaultBehaviour', '') From 6a99017bf0657d989b960a7162cbcc29931fab91 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 10:35:15 +1000 Subject: [PATCH 639/897] [processing] Use with ... when opening files --- .../processing/algs/gdal/extractprojection.py | 26 ++-- .../processing/algs/gdal/information.py | 11 +- .../processing/algs/grass/GrassAlgorithm.py | 117 +++++++++--------- .../processing/algs/grass/GrassUtils.py | 105 ++++++++-------- .../processing/algs/grass7/Grass7Algorithm.py | 114 +++++++++-------- .../processing/algs/grass7/Grass7Utils.py | 54 ++++---- .../algs/lidar/fusion/FusionUtils.py | 7 +- .../processing/algs/otb/OTBAlgorithm.py | 4 +- .../plugins/processing/algs/otb/OTBUtils.py | 7 +- .../algs/otb/maintenance/OTBHelper.py | 18 ++- .../algs/otb/maintenance/OTBTester.py | 12 +- .../plugins/processing/algs/qgis/BarPlot.py | 5 +- .../algs/qgis/BasicStatisticsNumbers.py | 15 ++- .../algs/qgis/BasicStatisticsStrings.py | 14 +-- .../processing/algs/qgis/MeanAndStdDevPlot.py | 5 +- .../algs/qgis/NearestNeighbourAnalysis.py | 15 ++- .../processing/algs/qgis/PointsToPaths.py | 41 +++--- .../plugins/processing/algs/qgis/PolarPlot.py | 5 +- .../algs/qgis/RasterLayerHistogram.py | 5 +- .../algs/qgis/RasterLayerStatistics.py | 15 ++- .../processing/algs/qgis/UniqueValues.py | 21 ++-- .../algs/qgis/VectorLayerHistogram.py | 5 +- .../algs/qgis/VectorLayerScatterplot.py | 5 +- .../plugins/processing/algs/r/RAlgorithm.py | 10 +- python/plugins/processing/algs/r/RUtils.py | 31 +++-- .../processing/algs/saga/SagaAlgorithm212.py | 84 ++++++------- .../processing/algs/saga/SagaAlgorithm213.py | 15 ++- .../algs/saga/SagaDescriptionCreator.py | 70 +++++------ .../plugins/processing/algs/saga/SagaUtils.py | 39 +++--- .../processing/algs/saga/versioncheck.py | 53 ++++---- .../plugins/processing/core/GeoAlgorithm.py | 8 +- .../plugins/processing/core/ProcessingLog.py | 14 +-- .../plugins/processing/gui/CommanderWindow.py | 17 ++- .../plugins/processing/gui/RenderingStyles.py | 32 +++-- .../processing/modeler/ModelerDialog.py | 5 +- .../processing/script/ScriptAlgorithm.py | 21 ++-- .../expected/basic_statistics_string.html | 2 +- .../plugins/processing/tools/translation.py | 68 +++++----- 38 files changed, 523 insertions(+), 572 deletions(-) diff --git a/python/plugins/processing/algs/gdal/extractprojection.py b/python/plugins/processing/algs/gdal/extractprojection.py index 29b93ef83101..9daa2aa39a23 100644 --- a/python/plugins/processing/algs/gdal/extractprojection.py +++ b/python/plugins/processing/algs/gdal/extractprojection.py @@ -75,17 +75,15 @@ def processAlgorithm(self, progress): crs = tmp.ExportToWkt() tmp = None - prj = open(outFileName + '.prj', 'wt') - prj.write(crs) - prj.close() - - wld = open(outFileName + '.wld', 'wt') - wld.write('%0.8f\n' % geotransform[1]) - wld.write('%0.8f\n' % geotransform[4]) - wld.write('%0.8f\n' % geotransform[2]) - wld.write('%0.8f\n' % geotransform[5]) - wld.write('%0.8f\n' % (geotransform[0] + 0.5 * geotransform[1] + 0.5 - * geotransform[2])) - wld.write('%0.8f\n' % (geotransform[3] + 0.5 * geotransform[4] + 0.5 - * geotransform[5])) - wld.close() + with open(outFileName + '.prj', 'wt') as prj: + prj.write(crs) + + with open(outFileName + '.wld', 'wt') as wld: + wld.write('%0.8f\n' % geotransform[1]) + wld.write('%0.8f\n' % geotransform[4]) + wld.write('%0.8f\n' % geotransform[2]) + wld.write('%0.8f\n' % geotransform[5]) + wld.write('%0.8f\n' % (geotransform[0] + 0.5 * geotransform[1] + 0.5 + * geotransform[2])) + wld.write('%0.8f\n' % (geotransform[3] + 0.5 * geotransform[4] + 0.5 + * geotransform[5])) diff --git a/python/plugins/processing/algs/gdal/information.py b/python/plugins/processing/algs/gdal/information.py index a59e4d5e3b59..da5a1489a2d7 100644 --- a/python/plugins/processing/algs/gdal/information.py +++ b/python/plugins/processing/algs/gdal/information.py @@ -76,9 +76,8 @@ def getConsoleCommands(self): def processAlgorithm(self, progress): GdalUtils.runGdal(self.getConsoleCommands(), progress) output = self.getOutputValue(information.OUTPUT) - f = open(output, 'w') - f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ')
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -        for s in GdalUtils.getConsoleOutput()[1:]:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -            f.write(str(s))
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -        f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') - f.close() + with open(output, 'w') as f: + f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ')
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +            for s in GdalUtils.getConsoleOutput()[1:]:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +                f.write(str(s))
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +            f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') diff --git a/python/plugins/processing/algs/grass/GrassAlgorithm.py b/python/plugins/processing/algs/grass/GrassAlgorithm.py index 54a672838574..34f1be5b7e05 100644 --- a/python/plugins/processing/algs/grass/GrassAlgorithm.py +++ b/python/plugins/processing/algs/grass/GrassAlgorithm.py @@ -108,71 +108,68 @@ def getParameterDescriptions(self): descs = {} _, helpfile = self.help() try: - infile = open(helpfile) - lines = infile.readlines() - for i in range(len(lines)): - if lines[i].startswith('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  '): - for param in self.parameters: - searchLine = '' + param.name + '' - if searchLine in lines[i]: - i += 1 - descs[param.name] = (lines[i])[4:-6] - break - - infile.close() + with open(helpfile) as infile: + lines = infile.readlines() + for i in range(len(lines)): + if lines[i].startswith('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  '): + for param in self.parameters: + searchLine = '' + param.name + '' + if searchLine in lines[i]: + i += 1 + descs[param.name] = (lines[i])[4:-6] + break except Exception: pass return descs def defineCharacteristicsFromFile(self): - lines = open(self.descriptionFile) - line = lines.readline().strip('\n').strip() - self.grassName = line - line = lines.readline().strip('\n').strip() - self.name = line - self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line) - if " - " not in self.name: - self.name = self.grassName + " - " + self.name - self.i18n_name = self.grassName + " - " + self.i18n_name - line = lines.readline().strip('\n').strip() - self.group = line - self.i18n_group = QCoreApplication.translate("GrassAlgorithm", line) - hasRasterOutput = False - hasVectorInput = False - vectorOutputs = 0 - line = lines.readline().strip('\n').strip() - while line != '': - try: - line = line.strip('\n').strip() - if line.startswith('Hardcoded'): - self.hardcodedStrings.append(line[len('Hardcoded|'):]) - parameter = getParameterFromString(line) - if parameter is not None: - self.addParameter(parameter) - if isinstance(parameter, ParameterVector): - hasVectorInput = True - if isinstance(parameter, ParameterMultipleInput) \ - and parameter.datatype < 3: - hasVectorInput = True - else: - output = getOutputFromString(line) - self.addOutput(output) - if isinstance(output, OutputRaster): - hasRasterOutput = True - elif isinstance(output, OutputVector): - vectorOutputs += 1 - if isinstance(output, OutputHTML): - self.addOutput(OutputFile("rawoutput", output.description + - " (raw output)", "txt")) - line = lines.readline().strip('\n').strip() - except Exception as e: - - ProcessingLog.addToLog( - ProcessingLog.LOG_ERROR, - traceback.format_exc()) - #self.tr('Could not open GRASS algorithm: %s.\n%s' % (self.descriptionFile, line))) - raise e - lines.close() + with open(self.descriptionFile) as lines: + line = lines.readline().strip('\n').strip() + self.grassName = line + line = lines.readline().strip('\n').strip() + self.name = line + self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line) + if " - " not in self.name: + self.name = self.grassName + " - " + self.name + self.i18n_name = self.grassName + " - " + self.i18n_name + line = lines.readline().strip('\n').strip() + self.group = line + self.i18n_group = QCoreApplication.translate("GrassAlgorithm", line) + hasRasterOutput = False + hasVectorInput = False + vectorOutputs = 0 + line = lines.readline().strip('\n').strip() + while line != '': + try: + line = line.strip('\n').strip() + if line.startswith('Hardcoded'): + self.hardcodedStrings.append(line[len('Hardcoded|'):]) + parameter = getParameterFromString(line) + if parameter is not None: + self.addParameter(parameter) + if isinstance(parameter, ParameterVector): + hasVectorInput = True + if isinstance(parameter, ParameterMultipleInput) \ + and parameter.datatype < 3: + hasVectorInput = True + else: + output = getOutputFromString(line) + self.addOutput(output) + if isinstance(output, OutputRaster): + hasRasterOutput = True + elif isinstance(output, OutputVector): + vectorOutputs += 1 + if isinstance(output, OutputHTML): + self.addOutput(OutputFile("rawoutput", output.description + + " (raw output)", "txt")) + line = lines.readline().strip('\n').strip() + except Exception as e: + + ProcessingLog.addToLog( + ProcessingLog.LOG_ERROR, + traceback.format_exc()) + #self.tr('Could not open GRASS algorithm: %s.\n%s' % (self.descriptionFile, line))) + raise e self.addParameter(ParameterExtent( self.GRASS_REGION_EXTENT_PARAMETER, diff --git a/python/plugins/processing/algs/grass/GrassUtils.py b/python/plugins/processing/algs/grass/GrassUtils.py index 4673b12b2e86..191a48169a22 100644 --- a/python/plugins/processing/algs/grass/GrassUtils.py +++ b/python/plugins/processing/algs/grass/GrassUtils.py @@ -136,56 +136,53 @@ def createGrassScript(commands): encoding = locale.getpreferredencoding() # Temporary gisrc file - output = codecs.open(gisrc, 'w', encoding=encoding) - location = 'temp_location' - gisdbase = GrassUtils.grassDataFolder() - - output.write('GISDBASE: ' + gisdbase + '\n') - output.write('LOCATION_NAME: ' + location + '\n') - output.write('MAPSET: PERMANENT \n') - output.write('GRASS_GUI: text\n') - output.close() - - output = codecs.open(script, 'w', encoding=encoding) - output.write('set HOME=' + os.path.expanduser('~') + '\n') - output.write('set GISRC=' + gisrc + '\n') - output.write('set GRASS_SH=' + shell + '\\bin\\sh.exe\n') - output.write('set PATH=' + os.path.join(shell, 'bin') + ';' + os.path.join(shell, 'lib') + ';' + '%PATH%\n') - output.write('set WINGISBASE=' + folder + '\n') - output.write('set GISBASE=' + folder + '\n') - output.write('set GRASS_PROJSHARE=' + os.path.join(folder, 'share', 'proj') + '\n') - output.write('set GRASS_MESSAGE_FORMAT=gui\n') - - # Replacement code for etc/Init.bat - output.write('if "%GRASS_ADDON_PATH%"=="" set PATH=%WINGISBASE%\\bin;%WINGISBASE%\\lib;%PATH%\n') - output.write('if not "%GRASS_ADDON_PATH%"=="" set PATH=%WINGISBASE%\\bin;%WINGISBASE%\\lib;%GRASS_ADDON_PATH%;%PATH%\n') - output.write('\n') - output.write('set GRASS_VERSION=' + GrassUtils.getGrassVersion() + '\n') - output.write('if not "%LANG%"=="" goto langset\n') - output.write('FOR /F "usebackq delims==" %%i IN (`"%WINGISBASE%\\etc\\winlocale"`) DO @set LANG=%%i\n') - output.write(':langset\n') - output.write('\n') - output.write('set PATHEXT=%PATHEXT%;.PY\n') - output.write('set PYTHONPATH=%PYTHONPATH%;%WINGISBASE%\\etc\\python;%WINGISBASE%\\etc\\wxpython\\n') - output.write('\n') - output.write('g.gisenv.exe set="MAPSET=PERMANENT"\n') - output.write('g.gisenv.exe set="LOCATION=' + location + '"\n') - output.write('g.gisenv.exe set="LOCATION_NAME=' + location + '"\n') - output.write('g.gisenv.exe set="GISDBASE=' + gisdbase + '"\n') - output.write('g.gisenv.exe set="GRASS_GUI=text"\n') - for command in commands: - output.write(command + u'\n') - output.write('\n') - output.write('exit\n') - output.close() + with codecs.open(gisrc, 'w', encoding=encoding) as output: + location = 'temp_location' + gisdbase = GrassUtils.grassDataFolder() + + output.write('GISDBASE: ' + gisdbase + '\n') + output.write('LOCATION_NAME: ' + location + '\n') + output.write('MAPSET: PERMANENT \n') + output.write('GRASS_GUI: text\n') + + with codecs.open(script, 'w', encoding=encoding) as output: + output.write('set HOME=' + os.path.expanduser('~') + '\n') + output.write('set GISRC=' + gisrc + '\n') + output.write('set GRASS_SH=' + shell + '\\bin\\sh.exe\n') + output.write('set PATH=' + os.path.join(shell, 'bin') + ';' + os.path.join(shell, 'lib') + ';' + '%PATH%\n') + output.write('set WINGISBASE=' + folder + '\n') + output.write('set GISBASE=' + folder + '\n') + output.write('set GRASS_PROJSHARE=' + os.path.join(folder, 'share', 'proj') + '\n') + output.write('set GRASS_MESSAGE_FORMAT=gui\n') + + # Replacement code for etc/Init.bat + output.write('if "%GRASS_ADDON_PATH%"=="" set PATH=%WINGISBASE%\\bin;%WINGISBASE%\\lib;%PATH%\n') + output.write('if not "%GRASS_ADDON_PATH%"=="" set PATH=%WINGISBASE%\\bin;%WINGISBASE%\\lib;%GRASS_ADDON_PATH%;%PATH%\n') + output.write('\n') + output.write('set GRASS_VERSION=' + GrassUtils.getGrassVersion() + '\n') + output.write('if not "%LANG%"=="" goto langset\n') + output.write('FOR /F "usebackq delims==" %%i IN (`"%WINGISBASE%\\etc\\winlocale"`) DO @set LANG=%%i\n') + output.write(':langset\n') + output.write('\n') + output.write('set PATHEXT=%PATHEXT%;.PY\n') + output.write('set PYTHONPATH=%PYTHONPATH%;%WINGISBASE%\\etc\\python;%WINGISBASE%\\etc\\wxpython\\n') + output.write('\n') + output.write('g.gisenv.exe set="MAPSET=PERMANENT"\n') + output.write('g.gisenv.exe set="LOCATION=' + location + '"\n') + output.write('g.gisenv.exe set="LOCATION_NAME=' + location + '"\n') + output.write('g.gisenv.exe set="GISDBASE=' + gisdbase + '"\n') + output.write('g.gisenv.exe set="GRASS_GUI=text"\n') + for command in commands: + output.write(command + u'\n') + output.write('\n') + output.write('exit\n') @staticmethod def createGrassBatchJobFileFromGrassCommands(commands): - fout = codecs.open(GrassUtils.grassBatchJobFilename(), 'w', encoding='utf-8') - for command in commands: - fout.write(command + u'\n') - fout.write('exit') - fout.close() + with codecs.open(GrassUtils.grassBatchJobFilename(), 'w', encoding='utf-8') as fout: + for command in commands: + fout.write(command + u'\n') + fout.write('exit') @staticmethod def grassMapsetFolder(): @@ -213,17 +210,15 @@ def createTempMapset(): mkdir(os.path.join(folder, 'PERMANENT')) mkdir(os.path.join(folder, 'PERMANENT', '.tmp')) GrassUtils.writeGrassWindow(os.path.join(folder, 'PERMANENT', 'DEFAULT_WIND')) - outfile = codecs.open(os.path.join(folder, 'PERMANENT', 'MYNAME'), 'w', encoding='utf-8') - outfile.write( - 'QGIS GRASS interface: temporary data processing location.\n') - outfile.close() + with codecs.open(os.path.join(folder, 'PERMANENT', 'MYNAME'), 'w', encoding='utf-8') as outfile: + outfile.write( + 'QGIS GRASS interface: temporary data processing location.\n') GrassUtils.writeGrassWindow(os.path.join(folder, 'PERMANENT', 'WIND')) mkdir(os.path.join(folder, 'PERMANENT', 'dbf')) - outfile = codecs.open(os.path.join(folder, 'PERMANENT', 'VAR'), 'w', encoding='utf-8') - outfile.write('DB_DRIVER: dbf\n') - outfile.write('DB_DATABASE: $GISDBASE/$LOCATION_NAME/$MAPSET/dbf/\n') - outfile.close() + with codecs.open(os.path.join(folder, 'PERMANENT', 'VAR'), 'w', encoding='utf-8') as outfile: + outfile.write('DB_DRIVER: dbf\n') + outfile.write('DB_DATABASE: $GISDBASE/$LOCATION_NAME/$MAPSET/dbf/\n') @staticmethod def writeGrassWindow(filename): diff --git a/python/plugins/processing/algs/grass7/Grass7Algorithm.py b/python/plugins/processing/algs/grass7/Grass7Algorithm.py index 31e76a9da292..6f9a29fa5464 100644 --- a/python/plugins/processing/algs/grass7/Grass7Algorithm.py +++ b/python/plugins/processing/algs/grass7/Grass7Algorithm.py @@ -139,69 +139,67 @@ def getParameterDescriptions(self): descs = {} _, helpfile = self.help() try: - infile = open(helpfile) - lines = infile.readlines() - for i in range(len(lines)): - if lines[i].startswith('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  '): - for param in self.parameters: - searchLine = '' + param.name + '' - if searchLine in lines[i]: - i += 1 - descs[param.name] = (lines[i])[4:-6] - break - - infile.close() + with open(helpfile) as infile: + lines = infile.readlines() + for i in range(len(lines)): + if lines[i].startswith('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  '): + for param in self.parameters: + searchLine = '' + param.name + '' + if searchLine in lines[i]: + i += 1 + descs[param.name] = (lines[i])[4:-6] + break + except Exception: pass return descs def defineCharacteristicsFromFile(self): - lines = open(self.descriptionFile) - line = lines.readline().strip('\n').strip() - self.grass7Name = line - line = lines.readline().strip('\n').strip() - self.name = line - self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line) - if " - " not in self.name: - self.name = self.grass7Name + " - " + self.name - self.i18n_name = self.grass7Name + " - " + self.i18n_name - line = lines.readline().strip('\n').strip() - self.group = line - self.i18n_group = QCoreApplication.translate("GrassAlgorithm", line) - hasRasterOutput = False - hasVectorInput = False - vectorOutputs = 0 - line = lines.readline().strip('\n').strip() - while line != '': - try: - line = line.strip('\n').strip() - if line.startswith('Hardcoded'): - self.hardcodedStrings.append(line[len('Hardcoded|'):]) - parameter = getParameterFromString(line) - if parameter is not None: - self.addParameter(parameter) - if isinstance(parameter, ParameterVector): - hasVectorInput = True - if isinstance(parameter, ParameterMultipleInput) \ - and parameter.datatype < 3: - hasVectorInput = True - else: - output = getOutputFromString(line) - self.addOutput(output) - if isinstance(output, OutputRaster): - hasRasterOutput = True - elif isinstance(output, OutputVector): - vectorOutputs += 1 - if isinstance(output, OutputHTML): - self.addOutput(OutputFile("rawoutput", output.description + - " (raw output)", "txt")) - line = lines.readline().strip('\n').strip() - except Exception as e: - ProcessingLog.addToLog( - ProcessingLog.LOG_ERROR, - self.tr('Could not open GRASS GIS 7 algorithm: %s\n%s' % (self.descriptionFile, line))) - raise e - lines.close() + with open(self.descriptionFile) as lines: + line = lines.readline().strip('\n').strip() + self.grass7Name = line + line = lines.readline().strip('\n').strip() + self.name = line + self.i18n_name = QCoreApplication.translate("GrassAlgorithm", line) + if " - " not in self.name: + self.name = self.grass7Name + " - " + self.name + self.i18n_name = self.grass7Name + " - " + self.i18n_name + line = lines.readline().strip('\n').strip() + self.group = line + self.i18n_group = QCoreApplication.translate("GrassAlgorithm", line) + hasRasterOutput = False + hasVectorInput = False + vectorOutputs = 0 + line = lines.readline().strip('\n').strip() + while line != '': + try: + line = line.strip('\n').strip() + if line.startswith('Hardcoded'): + self.hardcodedStrings.append(line[len('Hardcoded|'):]) + parameter = getParameterFromString(line) + if parameter is not None: + self.addParameter(parameter) + if isinstance(parameter, ParameterVector): + hasVectorInput = True + if isinstance(parameter, ParameterMultipleInput) \ + and parameter.datatype < 3: + hasVectorInput = True + else: + output = getOutputFromString(line) + self.addOutput(output) + if isinstance(output, OutputRaster): + hasRasterOutput = True + elif isinstance(output, OutputVector): + vectorOutputs += 1 + if isinstance(output, OutputHTML): + self.addOutput(OutputFile("rawoutput", output.description + + " (raw output)", "txt")) + line = lines.readline().strip('\n').strip() + except Exception as e: + ProcessingLog.addToLog( + ProcessingLog.LOG_ERROR, + self.tr('Could not open GRASS GIS 7 algorithm: %s\n%s' % (self.descriptionFile, line))) + raise e self.addParameter(ParameterExtent( self.GRASS_REGION_EXTENT_PARAMETER, diff --git a/python/plugins/processing/algs/grass7/Grass7Utils.py b/python/plugins/processing/algs/grass7/Grass7Utils.py index 40f7676d0b96..30a9cac698e8 100644 --- a/python/plugins/processing/algs/grass7/Grass7Utils.py +++ b/python/plugins/processing/algs/grass7/Grass7Utils.py @@ -191,41 +191,37 @@ def createTempMapset(): mkdir(os.path.join(folder, 'PERMANENT')) mkdir(os.path.join(folder, 'PERMANENT', '.tmp')) Grass7Utils.writeGrass7Window(os.path.join(folder, 'PERMANENT', 'DEFAULT_WIND')) - outfile = open(os.path.join(folder, 'PERMANENT', 'MYNAME'), 'w') - outfile.write( - 'QGIS GRASS GIS 7 interface: temporary data processing location.\n') - outfile.close() + with open(os.path.join(folder, 'PERMANENT', 'MYNAME'), 'w') as outfile: + outfile.write( + 'QGIS GRASS GIS 7 interface: temporary data processing location.\n') Grass7Utils.writeGrass7Window(os.path.join(folder, 'PERMANENT', 'WIND')) mkdir(os.path.join(folder, 'PERMANENT', 'sqlite')) - outfile = open(os.path.join(folder, 'PERMANENT', 'VAR'), 'w') - outfile.write('DB_DRIVER: sqlite\n') - outfile.write('DB_DATABASE: $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db\n') - outfile.close() + with open(os.path.join(folder, 'PERMANENT', 'VAR'), 'w') as outfile: + outfile.write('DB_DRIVER: sqlite\n') + outfile.write('DB_DATABASE: $GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db\n') @staticmethod def writeGrass7Window(filename): - out = open(filename, 'w') - out.write('proj: 0\n') - out.write('zone: 0\n') - out.write('north: 1\n') - out.write('south: 0\n') - out.write('east: 1\n') - out.write('west: 0\n') - out.write('cols: 1\n') - out.write('rows: 1\n') - out.write('e-w resol: 1\n') - out.write('n-s resol: 1\n') - out.write('top: 1\n') - out.write('bottom: 0\n') - out.write('cols3: 1\n') - out.write('rows3: 1\n') - out.write('depths: 1\n') - out.write('e-w resol3: 1\n') - out.write('n-s resol3: 1\n') - out.write('t-b resol: 1\n') - - out.close() + with open(filename, 'w') as out: + out.write('proj: 0\n') + out.write('zone: 0\n') + out.write('north: 1\n') + out.write('south: 0\n') + out.write('east: 1\n') + out.write('west: 0\n') + out.write('cols: 1\n') + out.write('rows: 1\n') + out.write('e-w resol: 1\n') + out.write('n-s resol: 1\n') + out.write('top: 1\n') + out.write('bottom: 0\n') + out.write('cols3: 1\n') + out.write('rows3: 1\n') + out.write('depths: 1\n') + out.write('e-w resol3: 1\n') + out.write('n-s resol3: 1\n') + out.write('t-b resol: 1\n') @staticmethod def prepareGrass7Execution(commands): diff --git a/python/plugins/processing/algs/lidar/fusion/FusionUtils.py b/python/plugins/processing/algs/lidar/fusion/FusionUtils.py index 2e04c842eefe..66bb91464edc 100644 --- a/python/plugins/processing/algs/lidar/fusion/FusionUtils.py +++ b/python/plugins/processing/algs/lidar/fusion/FusionUtils.py @@ -54,10 +54,9 @@ def tempFileListFilepath(): @staticmethod def createFileList(files): - out = open(FusionUtils.tempFileListFilepath(), 'w') - for f in files: - out.write(f + '\n') - out.close() + with open(FusionUtils.tempFileListFilepath(), 'w') as out: + for f in files: + out.write(f + '\n') @staticmethod def runFusion(commands, progress): diff --git a/python/plugins/processing/algs/otb/OTBAlgorithm.py b/python/plugins/processing/algs/otb/OTBAlgorithm.py index fd39294f481f..237c3cbd6703 100644 --- a/python/plugins/processing/algs/otb/OTBAlgorithm.py +++ b/python/plugins/processing/algs/otb/OTBAlgorithm.py @@ -132,8 +132,8 @@ def get_list_from_node(self, myet): return all_params def defineCharacteristicsFromFile(self): - content = open(self.descriptionFile).read() - dom_model = ET.fromstring(content) + with open(self.descriptionFile) as content: + dom_model = ET.fromstring(content.read()) self.appkey = dom_model.find('key').text self.cliName = dom_model.find('exec').text diff --git a/python/plugins/processing/algs/otb/OTBUtils.py b/python/plugins/processing/algs/otb/OTBUtils.py index dca0ed151a7b..e35e405be43f 100644 --- a/python/plugins/processing/algs/otb/OTBUtils.py +++ b/python/plugins/processing/algs/otb/OTBUtils.py @@ -275,10 +275,9 @@ def remove_parameter_by_criteria(doc, criteria): def defaultWrite(available_app, original_dom_document): - fh = open("description/%s.xml" % available_app, "w") - the_root = original_dom_document - ET.ElementTree(the_root).write(fh) - fh.close() + with open("description/%s.xml" % available_app, "w") as fh: + the_root = original_dom_document + ET.ElementTree(the_root).write(fh) def defaultSplit(available_app, original_dom_document, parameter): diff --git a/python/plugins/processing/algs/otb/maintenance/OTBHelper.py b/python/plugins/processing/algs/otb/maintenance/OTBHelper.py index 7c6abd9429f0..f6f9041c30e4 100644 --- a/python/plugins/processing/algs/otb/maintenance/OTBHelper.py +++ b/python/plugins/processing/algs/otb/maintenance/OTBHelper.py @@ -661,10 +661,9 @@ def create_xml_descriptors(): if available_app in white_list and available_app not in black_list: logger.warning("There is no adaptor for %s, check white list and versions" % available_app) # TODO Remove this default code when all apps are tested... - fh = open("description/%s.xml" % available_app, "w") - the_root = get_xml_description_from_application_name(available_app) - ET.ElementTree(the_root).write(fh) - fh.close() + with open("description/%s.xml" % available_app, "w") as fh: + the_root = get_xml_description_from_application_name(available_app) + ET.ElementTree(the_root).write(fh) try: get_automatic_ut_from_xml_description(the_root) except: @@ -683,12 +682,11 @@ def create_html_description(): for available_app in otbApplication.Registry.GetAvailableApplications(): try: - fh = open("description/doc/%s.html" % available_app, "w") - app_instance = otbApplication.Registry.CreateApplication(available_app) - app_instance.UpdateParameters() - ct = describe_app(app_instance) - fh.write(ct) - fh.close() + with open("description/doc/%s.html" % available_app, "w") as fh: + app_instance = otbApplication.Registry.CreateApplication(available_app) + app_instance.UpdateParameters() + ct = describe_app(app_instance) + fh.write(ct) except Exception: logger.error(traceback.format_exc()) diff --git a/python/plugins/processing/algs/otb/maintenance/OTBTester.py b/python/plugins/processing/algs/otb/maintenance/OTBTester.py index d7954cfd9bc6..d2717838590e 100644 --- a/python/plugins/processing/algs/otb/maintenance/OTBTester.py +++ b/python/plugins/processing/algs/otb/maintenance/OTBTester.py @@ -126,7 +126,8 @@ def templatize(item): self.fail(str(e)) def add_make(self, previous_context, new_file): - input = open(new_file).read() + with open(new_file) as f: + input = f.read() output = parse(input) apps = [each for each in output if 'Command' in str(type(each))] setcommands = [each for each in apps if 'SET' in each.name.upper()] @@ -169,21 +170,24 @@ def mini_clean(item): return environment def get_apps(self, the_makefile, the_dict): - input = open(the_makefile).read() + with open(the_makefile) as f: + input = f.read() output = parse(input) apps = [each for each in output if 'Command' in str(type(each))] otb_apps = [each for each in apps if 'OTB_TEST_APPLICATION' in each.name.upper()] return otb_apps def get_tests(self, the_makefile, the_dict): - input = open(the_makefile).read() + with open(the_makefile) as f: + input = f.read() output = parse(input) apps = [each for each in output if 'Command' in str(type(each))] otb_tests = [each for each in apps if 'ADD_TEST' in each.name.upper()] return otb_tests def get_apps_with_context(self, the_makefile, the_dict): - input = open(the_makefile).read() + with open(the_makefile) as f: + input = f.read() output = parse(input) def is_a_command(item): diff --git a/python/plugins/processing/algs/qgis/BarPlot.py b/python/plugins/processing/algs/qgis/BarPlot.py index abdccfa2f445..b477670fc0db 100644 --- a/python/plugins/processing/algs/qgis/BarPlot.py +++ b/python/plugins/processing/algs/qgis/BarPlot.py @@ -77,6 +77,5 @@ def processAlgorithm(self, progress): plt.xticks(ind, values[namefieldname], rotation=45) plotFilename = output + '.png' lab.savefig(plotFilename) - f = open(output, 'w') - f.write('') - f.close() + with open(output, 'w') as f: + f.write('') diff --git a/python/plugins/processing/algs/qgis/BasicStatisticsNumbers.py b/python/plugins/processing/algs/qgis/BasicStatisticsNumbers.py index d12fadb1ba3c..803cd3748149 100644 --- a/python/plugins/processing/algs/qgis/BasicStatisticsNumbers.py +++ b/python/plugins/processing/algs/qgis/BasicStatisticsNumbers.py @@ -194,11 +194,10 @@ def processAlgorithm(self, progress): self.setOutputValue(self.IQR, iqr) def createHTML(self, outputFile, algData): - f = codecs.open(outputFile, 'w', encoding='utf-8') - f.write('\n') - f.write('\n') - for s in algData: - f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n') - f.write('\n') - f.close() + with codecs.open(outputFile, 'w', encoding='utf-8') as f: + f.write('\n') + f.write('\n') + for s in algData: + f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n') + f.write('\n') diff --git a/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py b/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py index 2d8ca9f9dc2a..149db62f506d 100644 --- a/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py +++ b/python/plugins/processing/algs/qgis/BasicStatisticsStrings.py @@ -154,11 +154,9 @@ def processAlgorithm(self, progress): self.setOutputValue(self.UNIQUE, uniqueValues) def createHTML(self, outputFile, algData): - f = codecs.open(outputFile, 'w', encoding='utf-8') - f.write('\n') - f.write('\n') - for s in algData: - f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n') - f.write('') - f.close() + with codecs.open(outputFile, 'w', encoding='utf-8') as f: + f.write('\n') + f.write('\n') + for s in algData: + f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n') + f.write('') diff --git a/python/plugins/processing/algs/qgis/MeanAndStdDevPlot.py b/python/plugins/processing/algs/qgis/MeanAndStdDevPlot.py index 003573cc5d42..43a2ca8a8e8b 100644 --- a/python/plugins/processing/algs/qgis/MeanAndStdDevPlot.py +++ b/python/plugins/processing/algs/qgis/MeanAndStdDevPlot.py @@ -83,6 +83,5 @@ def processAlgorithm(self, progress): plt.xticks(ind, values[namefieldname], rotation=45) plotFilename = output + '.png' lab.savefig(plotFilename) - f = open(output, 'w') - f.write('') - f.close() + with open(output, 'w') as f: + f.write('') diff --git a/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py b/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py index 9a869ae496e0..b396cb83d2bd 100644 --- a/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py +++ b/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py @@ -124,11 +124,10 @@ def processAlgorithm(self, progress): self.setOutputValue(self.Z_SCORE, float(data[4].split(': ')[1])) def createHTML(self, outputFile, algData): - f = codecs.open(outputFile, 'w', encoding='utf-8') - f.write('') - f.write('') - for s in algData: - f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') - f.write('') - f.close() + with codecs.open(outputFile, 'w', encoding='utf-8') as f: + f.write('') + f.write('') + for s in algData: + f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') + f.write('') diff --git a/python/plugins/processing/algs/qgis/PointsToPaths.py b/python/plugins/processing/algs/qgis/PointsToPaths.py index 04b03c22a1fa..5d4759a5dd66 100644 --- a/python/plugins/processing/algs/qgis/PointsToPaths.py +++ b/python/plugins/processing/algs/qgis/PointsToPaths.py @@ -117,26 +117,26 @@ def processAlgorithm(self, progress): fileName = os.path.join(dirName, '%s.txt' % group) - fl = open(fileName, 'w') - fl.write('angle=Azimuth\n') - fl.write('heading=Coordinate_System\n') - fl.write('dist_units=Default\n') - - line = [] - i = 0 - for node in vertices: - line.append(node[1]) - - if i == 0: - fl.write('startAt=%f;%f;90\n' % (node[1].x(), node[1].y())) - fl.write('survey=Polygonal\n') - fl.write('[data]\n') - else: - angle = line[i - 1].azimuth(line[i]) - distance = da.measureLine(line[i - 1], line[i]) - fl.write('%f;%f;90\n' % (angle, distance)) - - i += 1 + with open(fileName, 'w') as fl: + fl.write('angle=Azimuth\n') + fl.write('heading=Coordinate_System\n') + fl.write('dist_units=Default\n') + + line = [] + i = 0 + for node in vertices: + line.append(node[1]) + + if i == 0: + fl.write('startAt=%f;%f;90\n' % (node[1].x(), node[1].y())) + fl.write('survey=Polygonal\n') + fl.write('[data]\n') + else: + angle = line[i - 1].azimuth(line[i]) + distance = da.measureLine(line[i - 1], line[i]) + fl.write('%f;%f;90\n' % (angle, distance)) + + i += 1 f.setGeometry(QgsGeometry.fromPolyline(line)) writer.addFeature(f) @@ -144,4 +144,3 @@ def processAlgorithm(self, progress): progress.setPercentage(int(current * total)) del writer - fl.close() diff --git a/python/plugins/processing/algs/qgis/PolarPlot.py b/python/plugins/processing/algs/qgis/PolarPlot.py index 1f77cf60c899..85e5e7da833b 100644 --- a/python/plugins/processing/algs/qgis/PolarPlot.py +++ b/python/plugins/processing/algs/qgis/PolarPlot.py @@ -77,6 +77,5 @@ def processAlgorithm(self, progress): ax.bar(theta, radii, width=width, bottom=0.0) plotFilename = output + '.png' lab.savefig(plotFilename) - f = open(output, 'w') - f.write('') - f.close() + with open(output, 'w') as f: + f.write('') diff --git a/python/plugins/processing/algs/qgis/RasterLayerHistogram.py b/python/plugins/processing/algs/qgis/RasterLayerHistogram.py index 94a35b4771d5..4a03b6f69096 100644 --- a/python/plugins/processing/algs/qgis/RasterLayerHistogram.py +++ b/python/plugins/processing/algs/qgis/RasterLayerHistogram.py @@ -87,6 +87,5 @@ def processAlgorithm(self, progress): plotFilename = outputplot + '.png' lab.savefig(plotFilename) - f = open(outputplot, 'w') - f.write('') - f.close() + with open(outputplot, 'w') as f: + f.write('') diff --git a/python/plugins/processing/algs/qgis/RasterLayerStatistics.py b/python/plugins/processing/algs/qgis/RasterLayerStatistics.py index 77a786aac529..86502d706abb 100644 --- a/python/plugins/processing/algs/qgis/RasterLayerStatistics.py +++ b/python/plugins/processing/algs/qgis/RasterLayerStatistics.py @@ -118,11 +118,10 @@ def processAlgorithm(self, progress): self.setOutputValue(self.STD_DEV, stddev) def createHTML(self, outputFile, algData): - f = codecs.open(outputFile, 'w', encoding='utf-8') - f.write('') - f.write('') - for s in algData: - f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') - f.write('') - f.close() + with codecs.open(outputFile, 'w', encoding='utf-8') as f: + f.write('') + f.write('') + for s in algData: + f.write('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + str(s) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') + f.write('') diff --git a/python/plugins/processing/algs/qgis/UniqueValues.py b/python/plugins/processing/algs/qgis/UniqueValues.py index 45311193294e..439c8cd09175 100644 --- a/python/plugins/processing/algs/qgis/UniqueValues.py +++ b/python/plugins/processing/algs/qgis/UniqueValues.py @@ -76,14 +76,13 @@ def processAlgorithm(self, progress): values])) def createHTML(self, outputFile, algData): - f = codecs.open(outputFile, 'w', encoding='utf-8') - f.write('') - f.write('') - f.write(self.tr('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Total unique values: ') + str(len(algData)) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') - f.write(self.tr('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Unique values:

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ')) - f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    ') - for s in algData: - f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • ' + str(s) + '
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • ') - f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') - f.close() + with codecs.open(outputFile, 'w', encoding='utf-8') as f: + f.write('') + f.write('') + f.write(self.tr('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Total unique values: ') + str(len(algData)) + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') + f.write(self.tr('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Unique values:

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ')) + f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    ') + for s in algData: + f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • ' + str(s) + '
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • ') + f.write('
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ') diff --git a/python/plugins/processing/algs/qgis/VectorLayerHistogram.py b/python/plugins/processing/algs/qgis/VectorLayerHistogram.py index 82865d22a51e..91940d0341d9 100644 --- a/python/plugins/processing/algs/qgis/VectorLayerHistogram.py +++ b/python/plugins/processing/algs/qgis/VectorLayerHistogram.py @@ -70,6 +70,5 @@ def processAlgorithm(self, progress): plt.hist(values[fieldname], bins) plotFilename = output + '.png' lab.savefig(plotFilename) - f = open(output, 'w') - f.write('') - f.close() + with open(output, 'w') as f: + f.write('') diff --git a/python/plugins/processing/algs/qgis/VectorLayerScatterplot.py b/python/plugins/processing/algs/qgis/VectorLayerScatterplot.py index 8f80fd945855..396f9c2b3485 100644 --- a/python/plugins/processing/algs/qgis/VectorLayerScatterplot.py +++ b/python/plugins/processing/algs/qgis/VectorLayerScatterplot.py @@ -74,6 +74,5 @@ def processAlgorithm(self, progress): plt.xlabel(xfieldname) plotFilename = output + '.png' lab.savefig(plotFilename) - f = open(output, 'w') - f.write('') - f.close() + with open(output, 'w') as f: + f.write('') diff --git a/python/plugins/processing/algs/r/RAlgorithm.py b/python/plugins/processing/algs/r/RAlgorithm.py index 114608005f1f..240277203e72 100644 --- a/python/plugins/processing/algs/r/RAlgorithm.py +++ b/python/plugins/processing/algs/r/RAlgorithm.py @@ -203,14 +203,12 @@ def processAlgorithm(self, progress): RUtils.executeRAlgorithm(self, progress) if self.showPlots: htmlfilename = self.getOutputValue(RAlgorithm.RPLOTS) - f = open(htmlfilename, 'w') - f.write('') - f.close() + with open(htmlfilename, 'w') as f: + f.write('') if self.showConsoleOutput: htmlfilename = self.getOutputValue(RAlgorithm.R_CONSOLE_OUTPUT) - f = open(htmlfilename, 'w') - f.write(RUtils.getConsoleOutput()) - f.close() + with open(htmlfilename, 'w') as f: + f.write(RUtils.getConsoleOutput()) def getFullSetOfRCommands(self): commands = [] diff --git a/python/plugins/processing/algs/r/RUtils.py b/python/plugins/processing/algs/r/RUtils.py index 35fbe64d2a36..93f3b0b1f753 100644 --- a/python/plugins/processing/algs/r/RUtils.py +++ b/python/plugins/processing/algs/r/RUtils.py @@ -103,10 +103,9 @@ def RScriptsFolders(): @staticmethod def createRScriptFromRCommands(commands): - scriptfile = open(RUtils.getRScriptFilename(), 'w') - for command in commands: - scriptfile.write(command + '\n') - scriptfile.close() + with open(RUtils.getRScriptFilename(), 'w') as scriptfile: + for command in commands: + scriptfile.write(command + '\n') @staticmethod def getRScriptFilename(): @@ -166,18 +165,18 @@ def createConsoleOutput(): RUtils.allConsoleResults = [] add = False if os.path.exists(RUtils.getConsoleOutputFilename()): - lines = open(RUtils.getConsoleOutputFilename()) - for line in lines: - line = line.strip().strip(' ') - if line.startswith('>'): - line = line[1:].strip(' ') - if line in RUtils.verboseCommands: - add = True - else: - add = False - elif add: - RUtils.consoleResults.append('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + line + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n') - RUtils.allConsoleResults.append(line) + with open(RUtils.getConsoleOutputFilename()) as lines: + for line in lines: + line = line.strip().strip(' ') + if line.startswith('>'): + line = line[1:].strip(' ') + if line in RUtils.verboseCommands: + add = True + else: + add = False + elif add: + RUtils.consoleResults.append('

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  ' + line + '

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n') + RUtils.allConsoleResults.append(line) @staticmethod def getConsoleOutput(): diff --git a/python/plugins/processing/algs/saga/SagaAlgorithm212.py b/python/plugins/processing/algs/saga/SagaAlgorithm212.py index 03de55bf1f42..b4b8787784d3 100644 --- a/python/plugins/processing/algs/saga/SagaAlgorithm212.py +++ b/python/plugins/processing/algs/saga/SagaAlgorithm212.py @@ -85,45 +85,44 @@ def getIcon(self): return self._icon def defineCharacteristicsFromFile(self): - lines = open(self.descriptionFile) - line = lines.readline().strip('\n').strip() - self.name = line - if '|' in self.name: - tokens = self.name.split('|') - self.name = tokens[0] - #cmdname is the name of the algorithm in SAGA, that is, the name to use to call it in the console - self.cmdname = tokens[1] + with open(self.descriptionFile) as lines: + line = lines.readline().strip('\n').strip() + self.name = line + if '|' in self.name: + tokens = self.name.split('|') + self.name = tokens[0] + #cmdname is the name of the algorithm in SAGA, that is, the name to use to call it in the console + self.cmdname = tokens[1] - else: - self.cmdname = self.name - self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", str(self.name)) - #_commandLineName is the name used in processing to call the algorithm - #Most of the time will be equal to the cmdname, but in same cases, several processing algorithms - #call the same SAGA one - self._commandLineName = self.createCommandLineName(self.name) - self.name = decoratedAlgorithmName(self.name) - self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", str(self.name)) - line = lines.readline().strip('\n').strip() - self.undecoratedGroup = line - self.group = decoratedGroupName(self.undecoratedGroup) - self.i18n_group = QCoreApplication.translate("SAGAAlgorithm", self.group) - line = lines.readline().strip('\n').strip() - while line != '': - if line.startswith('Hardcoded'): - self.hardcodedStrings.append(line[len('Hardcoded|'):]) - elif line.startswith('Parameter'): - self.addParameter(getParameterFromString(line)) - elif line.startswith('AllowUnmatching'): - self.allowUnmatchingGridExtents = True - elif line.startswith('Extent'): - # An extent parameter that wraps 4 SAGA numerical parameters - self.extentParamNames = line[6:].strip().split(' ') - self.addParameter(ParameterExtent(self.OUTPUT_EXTENT, - 'Output extent')) else: - self.addOutput(getOutputFromString(line)) + self.cmdname = self.name + self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", str(self.name)) + #_commandLineName is the name used in processing to call the algorithm + #Most of the time will be equal to the cmdname, but in same cases, several processing algorithms + #call the same SAGA one + self._commandLineName = self.createCommandLineName(self.name) + self.name = decoratedAlgorithmName(self.name) + self.i18n_name = QCoreApplication.translate("SAGAAlgorithm", str(self.name)) line = lines.readline().strip('\n').strip() - lines.close() + self.undecoratedGroup = line + self.group = decoratedGroupName(self.undecoratedGroup) + self.i18n_group = QCoreApplication.translate("SAGAAlgorithm", self.group) + line = lines.readline().strip('\n').strip() + while line != '': + if line.startswith('Hardcoded'): + self.hardcodedStrings.append(line[len('Hardcoded|'):]) + elif line.startswith('Parameter'): + self.addParameter(getParameterFromString(line)) + elif line.startswith('AllowUnmatching'): + self.allowUnmatchingGridExtents = True + elif line.startswith('Extent'): + # An extent parameter that wraps 4 SAGA numerical parameters + self.extentParamNames = line[6:].strip().split(' ') + self.addParameter(ParameterExtent(self.OUTPUT_EXTENT, + 'Output extent')) + else: + self.addOutput(getOutputFromString(line)) + line = lines.readline().strip('\n').strip() def processAlgorithm(self, progress): commands = list() @@ -216,13 +215,12 @@ def processAlgorithm(self, progress): command += ' -' + param.name elif isinstance(param, ParameterFixedTable): tempTableFile = getTempFilename('txt') - f = open(tempTableFile, 'w') - f.write('\t'.join([col for col in param.cols]) + '\n') - values = param.value.split(',') - for i in range(0, len(values), 3): - s = values[i] + '\t' + values[i + 1] + '\t' + values[i + 2] + '\n' - f.write(s) - f.close() + with open(tempTableFile, 'w') as f: + f.write('\t'.join([col for col in param.cols]) + '\n') + values = param.value.split(',') + for i in range(0, len(values), 3): + s = values[i] + '\t' + values[i + 1] + '\t' + values[i + 2] + '\n' + f.write(s) command += ' -' + param.name + ' "' + tempTableFile + '"' elif isinstance(param, ParameterExtent): # 'We have to substract/add half cell size, since SAGA is diff --git a/python/plugins/processing/algs/saga/SagaAlgorithm213.py b/python/plugins/processing/algs/saga/SagaAlgorithm213.py index d93304184e0f..24da8306f9e8 100644 --- a/python/plugins/processing/algs/saga/SagaAlgorithm213.py +++ b/python/plugins/processing/algs/saga/SagaAlgorithm213.py @@ -156,14 +156,13 @@ def processAlgorithm(self, progress): command += ' -' + param.name.strip() + " false" elif isinstance(param, ParameterFixedTable): tempTableFile = getTempFilename('txt') - f = open(tempTableFile, 'w') - f.write('\t'.join([col for col in param.cols]) + '\n') - values = param.value.split(',') - for i in range(0, len(values), 3): - s = values[i] + '\t' + values[i + 1] + '\t' + values[i - + 2] + '\n' - f.write(s) - f.close() + with open(tempTableFile, 'w') as f: + f.write('\t'.join([col for col in param.cols]) + '\n') + values = param.value.split(',') + for i in range(0, len(values), 3): + s = values[i] + '\t' + values[i + 1] + '\t' + values[i + + 2] + '\n' + f.write(s) command += ' -' + param.name + ' "' + tempTableFile + '"' elif isinstance(param, ParameterExtent): # 'We have to substract/add half cell size, since SAGA is diff --git a/python/plugins/processing/algs/saga/SagaDescriptionCreator.py b/python/plugins/processing/algs/saga/SagaDescriptionCreator.py index 07ccfd5d9ba6..24417ee9f8ef 100644 --- a/python/plugins/processing/algs/saga/SagaDescriptionCreator.py +++ b/python/plugins/processing/algs/saga/SagaDescriptionCreator.py @@ -35,21 +35,19 @@ class SagaDescriptionCreator(object): def createLibraryFiles(self): - f = open('c:\\saga\\sagalibs.txt') - for lib in f: - lib = lib.strip('\n') - command = ['c:\\saga\\saga_cmd.exe', lib] - f2 = open('c:\\saga\\desc\\' + lib + '.sagalib', 'w') - subprocess.Popen( - command, - shell=True, - stdout=f2, - stdin=open(os.devnull), - stderr=subprocess.STDOUT, - universal_newlines=True, - ) - f2.close() - f.close() + with open('c:\\saga\\sagalibs.txt') as f: + for lib in f: + lib = lib.strip('\n') + command = ['c:\\saga\\saga_cmd.exe', lib] + with open('c:\\saga\\desc\\' + lib + '.sagalib', 'w') as f2: + subprocess.Popen( + command, + shell=True, + stdout=f2, + stdin=open(os.devnull), + stderr=subprocess.STDOUT, + universal_newlines=True, + ) def createLibraryMap(self): self.map = {} @@ -58,16 +56,15 @@ def createLibraryMap(self): # fix_print_with_import print(libFile) algs = [] - f = open(os.path.join('c:\\saga\\desc', libFile)) - for line in f: - line = line.strip('\n').strip(' ') - digit = line.split('\t')[0] - # fix_print_with_import - print(digit) - if digit.isdigit(): - algs.append(digit) - self.map[libFile[:-8]] = algs - f.close() + with open(os.path.join('c:\\saga\\desc', libFile)) as f: + for line in f: + line = line.strip('\n').strip(' ') + digit = line.split('\t')[0] + # fix_print_with_import + print(digit) + if digit.isdigit(): + algs.append(digit) + self.map[libFile[:-8]] = algs # fix_print_with_import print(str(self.map)) @@ -77,18 +74,17 @@ def createDescriptionFiles(self): algs = self.map[lib] for alg in algs: command = ['c:\\saga\\saga_cmd.exe', lib, alg] - f = open('c:\\saga\\desc\\' + lib + '_' + alg + '.txt', 'w') - # fix_print_with_import - print(str(command)) - subprocess.Popen( - command, - shell=True, - stdout=f, - stdin=open(os.devnull), - stderr=f, - universal_newlines=True, - ) - f.close() + with open('c:\\saga\\desc\\' + lib + '_' + alg + '.txt', 'w') as f: + # fix_print_with_import + print(str(command)) + subprocess.Popen( + command, + shell=True, + stdout=f, + stdin=open(os.devnull), + stderr=f, + universal_newlines=True, + ) def create(self): self.createLibraryMap() diff --git a/python/plugins/processing/algs/saga/SagaUtils.py b/python/plugins/processing/algs/saga/SagaUtils.py index 970bf07a07ca..5c9e54ca2444 100644 --- a/python/plugins/processing/algs/saga/SagaUtils.py +++ b/python/plugins/processing/algs/saga/SagaUtils.py @@ -85,26 +85,25 @@ def sagaDescriptionPath(): def createSagaBatchJobFileFromSagaCommands(commands): - fout = open(sagaBatchJobFilename(), 'w') - if isWindows(): - fout.write('set SAGA=' + sagaPath() + '\n') - fout.write('set SAGA_MLB=' + os.path.join(sagaPath(), 'modules') + '\n') - fout.write('PATH=%PATH%;%SAGA%;%SAGA_MLB%\n') - elif isMac(): - fout.write('export SAGA_MLB=' + os.path.join(sagaPath(), '../lib/saga') + '\n') - fout.write('export PATH=' + sagaPath() + ':$PATH\n') - else: - pass - for command in commands: - try: - # Python 2 - fout.write('saga_cmd ' + command.encode('utf8') + '\n') - except TypeError: - # Python 3 - fout.write('saga_cmd ' + command + '\n') - - fout.write('exit') - fout.close() + with open(sagaBatchJobFilename(), 'w') as fout: + if isWindows(): + fout.write('set SAGA=' + sagaPath() + '\n') + fout.write('set SAGA_MLB=' + os.path.join(sagaPath(), 'modules') + '\n') + fout.write('PATH=%PATH%;%SAGA%;%SAGA_MLB%\n') + elif isMac(): + fout.write('export SAGA_MLB=' + os.path.join(sagaPath(), '../lib/saga') + '\n') + fout.write('export PATH=' + sagaPath() + ':$PATH\n') + else: + pass + for command in commands: + try: + # Python 2 + fout.write('saga_cmd ' + command.encode('utf8') + '\n') + except TypeError: + # Python 3 + fout.write('saga_cmd ' + command + '\n') + + fout.write('exit') _installedVersion = None _installedVersionFound = False diff --git a/python/plugins/processing/algs/saga/versioncheck.py b/python/plugins/processing/algs/saga/versioncheck.py index 48c6a5ddc84f..bfd2493640a8 100644 --- a/python/plugins/processing/algs/saga/versioncheck.py +++ b/python/plugins/processing/algs/saga/versioncheck.py @@ -36,35 +36,34 @@ def getAlgParams(f): params = [] booleanparams = [] numparams = [] - lines = open(f) - line = lines.readline().strip('\n').strip() - name = line - if '|' in name: - tokens = name.split('|') - cmdname = tokens[1] - else: - cmdname = name - line = lines.readline().strip('\n').strip() - group = line - line = lines.readline().strip('\n').strip() - while line != '': - if line.startswith('Hardcoded'): - pass - elif line.startswith('AllowUnmatching'): - pass - elif line.startswith('Extent'): - extentParamNames = line[6:].strip().split(' ') - params.extend(["-" + p for p in extentParamNames]) + with open(f) as lines: + line = lines.readline().strip('\n').strip() + name = line + if '|' in name: + tokens = name.split('|') + cmdname = tokens[1] else: - tokens = line.split("|") - if tokens[0] == "ParameterBoolean": - booleanparams.append("-" + tokens[1].strip()) - elif tokens[0] == "ParameterNumber": - numparams.append("-" + tokens[1].strip()) - else: - params.append("-" + tokens[1]) + cmdname = name line = lines.readline().strip('\n').strip() - lines.close() + group = line + line = lines.readline().strip('\n').strip() + while line != '': + if line.startswith('Hardcoded'): + pass + elif line.startswith('AllowUnmatching'): + pass + elif line.startswith('Extent'): + extentParamNames = line[6:].strip().split(' ') + params.extend(["-" + p for p in extentParamNames]) + else: + tokens = line.split("|") + if tokens[0] == "ParameterBoolean": + booleanparams.append("-" + tokens[1].strip()) + elif tokens[0] == "ParameterNumber": + numparams.append("-" + tokens[1].strip()) + else: + params.append("-" + tokens[1]) + line = lines.readline().strip('\n').strip() return cmdname, group, params, booleanparams, numparams diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index 7f39d5d8e18c..c32f906bdf18 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -249,10 +249,10 @@ def runHookScript(self, filename, progress): ns = {} ns['progress'] = progress ns['alg'] = self - f = open(filename) - lines = f.readlines() - for line in lines: - script += line + with open(filename) as f: + lines = f.readlines() + for line in lines: + script += line exec(script, ns) except Exception as e: ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, diff --git a/python/plugins/processing/core/ProcessingLog.py b/python/plugins/processing/core/ProcessingLog.py index 265e3f8a1957..a3cb4b50b36a 100644 --- a/python/plugins/processing/core/ProcessingLog.py +++ b/python/plugins/processing/core/ProcessingLog.py @@ -49,10 +49,9 @@ class ProcessingLog(object): def logFilename(): logFilename = userFolder() + os.sep + 'processing.log' if not os.path.isfile(logFilename): - logfile = codecs.open(logFilename, 'w', encoding='utf-8') - logfile.write('Started logging at ' + - datetime.datetime.now().strftime(ProcessingLog.DATE_FORMAT) + '\n') - logfile.close() + with codecs.open(logFilename, 'w', encoding='utf-8') as logfile: + logfile.write('Started logging at ' + + datetime.datetime.now().strftime(ProcessingLog.DATE_FORMAT) + '\n') return logFilename @@ -67,10 +66,9 @@ def addToLog(msgtype, msg): line = msgtype + '|' + datetime.datetime.now().strftime( ProcessingLog.DATE_FORMAT) + '|' \ + msg + '\n' - logfile = codecs.open(ProcessingLog.logFilename(), 'a', - encoding='utf-8') - logfile.write(line) - logfile.close() + with codecs.open(ProcessingLog.logFilename(), 'a', + encoding='utf-8') as logfile: + logfile.write(line) algname = msg[len('Processing.runalg("'):] algname = algname[:algname.index('"')] if algname not in ProcessingLog.recentAlgs: diff --git a/python/plugins/processing/gui/CommanderWindow.py b/python/plugins/processing/gui/CommanderWindow.py index 0f82131a3875..75d857e19469 100644 --- a/python/plugins/processing/gui/CommanderWindow.py +++ b/python/plugins/processing/gui/CommanderWindow.py @@ -58,15 +58,14 @@ def commandsFolder(self): def commandsFile(self): f = os.path.join(self.commandsFolder(), 'commands.py') if not os.path.exists(f): - out = open(f, 'w') - out.write('from qgis.core import *\n') - out.write('import processing\n\n') - out.write('def removeall():\n') - out.write('\tmapreg = QgsMapLayerRegistry.instance()\n') - out.write('\tmapreg.removeAllMapLayers()\n\n') - out.write('def load(*args):\n') - out.write('\tprocessing.load(args[0])\n') - out.close() + with open(f, 'w') as out: + out.write('from qgis.core import *\n') + out.write('import processing\n\n') + out.write('def removeall():\n') + out.write('\tmapreg = QgsMapLayerRegistry.instance()\n') + out.write('\tmapreg.removeAllMapLayers()\n\n') + out.write('def load(*args):\n') + out.write('\tprocessing.load(args[0])\n') return f def algsListHasChanged(self): diff --git a/python/plugins/processing/gui/RenderingStyles.py b/python/plugins/processing/gui/RenderingStyles.py index 928b9062a6c5..5ed4f927f16c 100644 --- a/python/plugins/processing/gui/RenderingStyles.py +++ b/python/plugins/processing/gui/RenderingStyles.py @@ -47,27 +47,25 @@ def configFile(): def loadStyles(): if not os.path.isfile(RenderingStyles.configFile()): return - lines = open(RenderingStyles.configFile()) - line = lines.readline().strip('\n') - while line != '': - tokens = line.split('|') - if tokens[0] in list(RenderingStyles.styles.keys()): - RenderingStyles.styles[tokens[0]][tokens[1]] = tokens[2] - else: - alg = {} - alg[tokens[1]] = tokens[2] - RenderingStyles.styles[tokens[0]] = alg + with open(RenderingStyles.configFile()) as lines: line = lines.readline().strip('\n') - lines.close() + while line != '': + tokens = line.split('|') + if tokens[0] in list(RenderingStyles.styles.keys()): + RenderingStyles.styles[tokens[0]][tokens[1]] = tokens[2] + else: + alg = {} + alg[tokens[1]] = tokens[2] + RenderingStyles.styles[tokens[0]] = alg + line = lines.readline().strip('\n') @staticmethod def saveSettings(): - fout = open(RenderingStyles.configFile(), 'w') - for alg in list(RenderingStyles.styles.keys()): - for out in list(RenderingStyles.styles[alg].keys()): - fout.write(alg + '|' + out + '|' - + RenderingStyles.styles[alg][out] + '\n') - fout.close() + with open(RenderingStyles.configFile(), 'w') as fout: + for alg in list(RenderingStyles.styles.keys()): + for out in list(RenderingStyles.styles[alg].keys()): + fout.write(alg + '|' + out + '|' + + RenderingStyles.styles[alg][out] + '\n') @staticmethod def getStyle(algname, outputname): diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index bf4abe0af996..fe08c0c16c2b 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -324,7 +324,8 @@ def saveModel(self, saveAs): if filename: text = self.alg.toJson() try: - fout = codecs.open(filename, 'w', encoding='utf-8') + with codecs.open(filename, 'w', encoding='utf-8') as fout: + fout.write(text) except: if saveAs: QMessageBox.warning(self, self.tr('I/O error'), @@ -336,8 +337,6 @@ def saveModel(self, saveAs): "have permission to do it). Please, use " "the 'Save as...' option.")) return - fout.write(text) - fout.close() self.update_model.emit() self.bar.pushMessage("", "Model was correctly saved", level=QgsMessageBar.SUCCESS, duration=5) diff --git a/python/plugins/processing/script/ScriptAlgorithm.py b/python/plugins/processing/script/ScriptAlgorithm.py index d1153a3d1b68..ade671b44250 100644 --- a/python/plugins/processing/script/ScriptAlgorithm.py +++ b/python/plugins/processing/script/ScriptAlgorithm.py @@ -77,18 +77,17 @@ def defineCharacteristicsFromFile(self): filename = os.path.basename(self.descriptionFile) self.name = filename[:filename.rfind('.')].replace('_', ' ') self.group = self.tr('User scripts', 'ScriptAlgorithm') - lines = open(self.descriptionFile) - line = lines.readline() - while line != '': - if line.startswith('##'): - try: - self.processParameterLine(line.strip('\n')) - except: - self.error = self.tr('This script has a syntax errors.\n' - 'Problem with line: %s', 'ScriptAlgorithm') % line - self.script += line + with open(self.descriptionFile) as lines: line = lines.readline() - lines.close() + while line != '': + if line.startswith('##'): + try: + self.processParameterLine(line.strip('\n')) + except: + self.error = self.tr('This script has a syntax errors.\n' + 'Problem with line: %s', 'ScriptAlgorithm') % line + self.script += line + line = lines.readline() if self.group == self.tr('[Test scripts]', 'ScriptAlgorithm'): self.showInModeler = False self.showInToolbox = False diff --git a/python/plugins/processing/tests/testdata/expected/basic_statistics_string.html b/python/plugins/processing/tests/testdata/expected/basic_statistics_string.html index 7258899148f4..b213bb0b2379 100644 --- a/python/plugins/processing/tests/testdata/expected/basic_statistics_string.html +++ b/python/plugins/processing/tests/testdata/expected/basic_statistics_string.html @@ -1,5 +1,5 @@ - +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Analyzed layer: multipolys.gml

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Analyzed field: Bname

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Minimum length: 4.0

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  diff --git a/python/plugins/processing/tools/translation.py b/python/plugins/processing/tools/translation.py index afcae1b70660..cf103b03274d 100644 --- a/python/plugins/processing/tools/translation.py +++ b/python/plugins/processing/tools/translation.py @@ -40,43 +40,43 @@ def updateTranslations(): loadClassification() - f = open(os.path.join(os.path.dirname(__file__), '../algs/translations.py'), 'w') - f.write('''# -*- coding: utf-8 -*- + with open(os.path.join(os.path.dirname(__file__), '../algs/translations.py'), 'w') as f: + f.write('''# -*- coding: utf-8 -*- -""" -Don't edit this file manually. -Update it from QGIS console: + """ + Don't edit this file manually. + Update it from QGIS console: -from processing.tools.translation import updateTranslations -updateTranslations() -""" + from processing.tools.translation import updateTranslations + updateTranslations() + """ -from qgis.PyQt.QtCore import QCoreApplication + from qgis.PyQt.QtCore import QCoreApplication + + def translationShadow(): + ''') + groups = {} + for provider in Processing.providers: + f.write(''' + """{}""" + '''.format(provider.__class__.__name__)) + for alg in provider.algs: + display_name = alg.name + f.write(" QCoreApplication.translate(\"{}\", \"{}\")\n" + .format(alg.__class__.__name__, + display_name.replace('"', '\\"'))) + if alg.group not in groups: + groups[alg.group] = 'AlgorithmClassification' + group, subgroup = getClassificationEn(alg) + if group is not None and group not in groups: + groups[group] = 'AlgorithmClassification' + if subgroup is not None and subgroup not in groups: + groups[subgroup] = 'AlgorithmClassification' -def translationShadow(): -''') - groups = {} - for provider in Processing.providers: f.write(''' - """{}""" -'''.format(provider.__class__.__name__)) - for alg in provider.algs: - display_name = alg.name + """Groups and subgroups""" + ''') + for group, context in list(groups.items()): f.write(" QCoreApplication.translate(\"{}\", \"{}\")\n" - .format(alg.__class__.__name__, - display_name.replace('"', '\\"'))) - if alg.group not in groups: - groups[alg.group] = 'AlgorithmClassification' - group, subgroup = getClassificationEn(alg) - if group is not None and group not in groups: - groups[group] = 'AlgorithmClassification' - if subgroup is not None and subgroup not in groups: - groups[subgroup] = 'AlgorithmClassification' - - f.write(''' - """Groups and subgroups""" -''') - for group, context in list(groups.items()): - f.write(" QCoreApplication.translate(\"{}\", \"{}\")\n" - .format(context, - group.replace('"', '\\"'))) + .format(context, + group.replace('"', '\\"'))) From 0484769b7d1817b365efe706600fc9b97669651e Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 12:13:18 +1000 Subject: [PATCH 640/897] [processing] Use subprocess.DEVNULL instead of open(os.devnull) --- python/plugins/processing/algs/gdal/GdalUtils.py | 2 +- python/plugins/processing/algs/grass/GrassUtils.py | 4 ++-- python/plugins/processing/algs/grass7/Grass7Utils.py | 4 ++-- python/plugins/processing/algs/lidar/fusion/FusionUtils.py | 2 +- .../plugins/processing/algs/lidar/lastools/LAStoolsUtils.py | 2 +- python/plugins/processing/algs/otb/OTBUtils.py | 2 +- python/plugins/processing/algs/r/RUtils.py | 4 ++-- python/plugins/processing/algs/saga/SagaDescriptionCreator.py | 4 ++-- python/plugins/processing/algs/saga/SagaUtils.py | 4 ++-- python/plugins/processing/algs/saga/versioncheck.py | 2 +- python/plugins/processing/algs/taudem/TauDEMUtils.py | 2 +- 11 files changed, 16 insertions(+), 16 deletions(-) diff --git a/python/plugins/processing/algs/gdal/GdalUtils.py b/python/plugins/processing/algs/gdal/GdalUtils.py index f366d8fd075c..7e9a9f530a39 100644 --- a/python/plugins/processing/algs/gdal/GdalUtils.py +++ b/python/plugins/processing/algs/gdal/GdalUtils.py @@ -87,7 +87,7 @@ def runGdal(commands, progress=None): fused_command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ).stdout diff --git a/python/plugins/processing/algs/grass/GrassUtils.py b/python/plugins/processing/algs/grass/GrassUtils.py index 191a48169a22..1c9d58a047e2 100644 --- a/python/plugins/processing/algs/grass/GrassUtils.py +++ b/python/plugins/processing/algs/grass/GrassUtils.py @@ -277,7 +277,7 @@ def executeGrass(commands, progress, outputCommands=None): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, env=grassenv @@ -307,7 +307,7 @@ def executeGrass(commands, progress, outputCommands=None): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, env=grassenv diff --git a/python/plugins/processing/algs/grass7/Grass7Utils.py b/python/plugins/processing/algs/grass7/Grass7Utils.py index 30a9cac698e8..79c3b9ec5c6a 100644 --- a/python/plugins/processing/algs/grass7/Grass7Utils.py +++ b/python/plugins/processing/algs/grass7/Grass7Utils.py @@ -258,7 +258,7 @@ def executeGrass7(commands, progress, outputCommands=None): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, env=grassenv @@ -287,7 +287,7 @@ def executeGrass7(commands, progress, outputCommands=None): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, env=grassenv diff --git a/python/plugins/processing/algs/lidar/fusion/FusionUtils.py b/python/plugins/processing/algs/lidar/fusion/FusionUtils.py index 66bb91464edc..9fd73bff439d 100644 --- a/python/plugins/processing/algs/lidar/fusion/FusionUtils.py +++ b/python/plugins/processing/algs/lidar/fusion/FusionUtils.py @@ -68,7 +68,7 @@ def runFusion(commands, progress): commands, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=False, ).stdout diff --git a/python/plugins/processing/algs/lidar/lastools/LAStoolsUtils.py b/python/plugins/processing/algs/lidar/lastools/LAStoolsUtils.py index aec25a00798a..ac46a55e00cf 100644 --- a/python/plugins/processing/algs/lidar/lastools/LAStoolsUtils.py +++ b/python/plugins/processing/algs/lidar/lastools/LAStoolsUtils.py @@ -71,7 +71,7 @@ def runLAStools(commands, progress): loglines.append(QCoreApplication.translate("LAStoolsUtils", "LAStools command line")) loglines.append(commandline) loglines.append(QCoreApplication.translate("LAStoolsUtils", "LAStools console output")) - proc = subprocess.Popen(commandline, shell=True, stdout=subprocess.PIPE, stdin=open(os.devnull), + proc = subprocess.Popen(commandline, shell=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=False).stdout for line in iter(proc.readline, ""): loglines.append(line) diff --git a/python/plugins/processing/algs/otb/OTBUtils.py b/python/plugins/processing/algs/otb/OTBUtils.py index e35e405be43f..9ec1030aa94c 100644 --- a/python/plugins/processing/algs/otb/OTBUtils.py +++ b/python/plugins/processing/algs/otb/OTBUtils.py @@ -161,7 +161,7 @@ def executeOtb(commands, progress, addToLog=True): loglines.append(tr("OTB execution console output")) os.putenv('ITK_AUTOLOAD_PATH', otbLibPath()) fused_command = ''.join(['"%s" ' % re.sub(r'^"|"$', '', c) for c in commands]) - proc = subprocess.Popen(fused_command, shell=True, stdout=subprocess.PIPE, stdin=open(os.devnull), stderr=subprocess.STDOUT, universal_newlines=True).stdout + proc = subprocess.Popen(fused_command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True).stdout if isMac(): # This trick avoids having an uninterrupted system call exception if OTB is not installed time.sleep(1) for line in iter(proc.readline, ""): diff --git a/python/plugins/processing/algs/r/RUtils.py b/python/plugins/processing/algs/r/RUtils.py index 93f3b0b1f753..24c4c135eaef 100644 --- a/python/plugins/processing/algs/r/RUtils.py +++ b/python/plugins/processing/algs/r/RUtils.py @@ -146,7 +146,7 @@ def executeRAlgorithm(alg, progress): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ) @@ -213,7 +213,7 @@ def checkRIsInstalled(ignoreRegistrySettings=False): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ).stdout diff --git a/python/plugins/processing/algs/saga/SagaDescriptionCreator.py b/python/plugins/processing/algs/saga/SagaDescriptionCreator.py index 24417ee9f8ef..fe09b852e22e 100644 --- a/python/plugins/processing/algs/saga/SagaDescriptionCreator.py +++ b/python/plugins/processing/algs/saga/SagaDescriptionCreator.py @@ -44,7 +44,7 @@ def createLibraryFiles(self): command, shell=True, stdout=f2, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ) @@ -81,7 +81,7 @@ def createDescriptionFiles(self): command, shell=True, stdout=f, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=f, universal_newlines=True, ) diff --git a/python/plugins/processing/algs/saga/SagaUtils.py b/python/plugins/processing/algs/saga/SagaUtils.py index 5c9e54ca2444..2e141b58b6ad 100644 --- a/python/plugins/processing/algs/saga/SagaUtils.py +++ b/python/plugins/processing/algs/saga/SagaUtils.py @@ -132,7 +132,7 @@ def getSagaInstalledVersion(runSaga=False): commands, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ).stdout @@ -167,7 +167,7 @@ def executeSaga(progress): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ).stdout diff --git a/python/plugins/processing/algs/saga/versioncheck.py b/python/plugins/processing/algs/saga/versioncheck.py index bfd2493640a8..e3bf69fa6e64 100644 --- a/python/plugins/processing/algs/saga/versioncheck.py +++ b/python/plugins/processing/algs/saga/versioncheck.py @@ -82,7 +82,7 @@ def testDescriptionFile(f): command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ).stdout diff --git a/python/plugins/processing/algs/taudem/TauDEMUtils.py b/python/plugins/processing/algs/taudem/TauDEMUtils.py index c05a00b16ef9..72b4f27ade85 100644 --- a/python/plugins/processing/algs/taudem/TauDEMUtils.py +++ b/python/plugins/processing/algs/taudem/TauDEMUtils.py @@ -94,7 +94,7 @@ def executeTauDEM(command, progress): fused_command, shell=True, stdout=subprocess.PIPE, - stdin=open(os.devnull), + stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ).stdout From c3a978b9da33f69c6c5440e1166c78c89946dde4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 4 Nov 2016 17:13:59 +1000 Subject: [PATCH 641/897] [FEATURE][processing] Snap geometries to layer algorithm Port the Geometry Snapper plugin across to the analysis lib, and expose to python bindings Add a new algorithm which performs the snapping to layers --- python/analysis/analysis.sip | 1 + python/analysis/vector/qgsgeometrysnapper.sip | 43 ++ python/plugins/processing/algs/help/qgis.yaml | 3 + .../algs/qgis/QGISAlgorithmProvider.py | 3 +- .../processing/algs/qgis/SnapGeometries.py | 83 +++ .../testdata/expected/snap_lines_to_lines.gfs | 14 + .../testdata/expected/snap_lines_to_lines.gml | 48 ++ .../testdata/expected/snap_polys_to_polys.gfs | 32 + .../testdata/expected/snap_polys_to_polys.gml | 43 ++ .../tests/testdata/qgis_algorithm_tests.yaml | 30 + .../processing/tests/testdata/snap_lines.gfs | 16 + .../processing/tests/testdata/snap_lines.gml | 48 ++ .../processing/tests/testdata/snap_polys.gfs | 32 + .../processing/tests/testdata/snap_polys.gml | 43 ++ src/analysis/CMakeLists.txt | 2 + src/analysis/vector/qgsgeometrysnapper.cpp | 648 ++++++++++++++++++ src/analysis/vector/qgsgeometrysnapper.h | 183 +++++ 17 files changed, 1271 insertions(+), 1 deletion(-) create mode 100644 python/analysis/vector/qgsgeometrysnapper.sip create mode 100644 python/plugins/processing/algs/qgis/SnapGeometries.py create mode 100644 python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml create mode 100644 python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gml create mode 100644 python/plugins/processing/tests/testdata/snap_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/snap_lines.gml create mode 100644 python/plugins/processing/tests/testdata/snap_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/snap_polys.gml create mode 100644 src/analysis/vector/qgsgeometrysnapper.cpp create mode 100644 src/analysis/vector/qgsgeometrysnapper.h diff --git a/python/analysis/analysis.sip b/python/analysis/analysis.sip index ceb505617ef5..3f38bd426f65 100644 --- a/python/analysis/analysis.sip +++ b/python/analysis/analysis.sip @@ -9,6 +9,7 @@ %Import core/core.sip %Include vector/qgsgeometryanalyzer.sip +%Include vector/qgsgeometrysnapper.sip %Include vector/qgsoverlayanalyzer.sip %Include vector/qgspointsample.sip %Include vector/qgstransectsample.sip diff --git a/python/analysis/vector/qgsgeometrysnapper.sip b/python/analysis/vector/qgsgeometrysnapper.sip new file mode 100644 index 000000000000..2b3c970473ce --- /dev/null +++ b/python/analysis/vector/qgsgeometrysnapper.sip @@ -0,0 +1,43 @@ +/** + * \class QgsGeometrySnapper + * \ingroup analysis + * QgsGeometrySnapper allows a geometry to be snapped to the geometries within a + * different refence layer. Vertices in the geometries will be modified to + * match the reference layer features within a specified snap tolerance. + * \note added in QGIS 3.0 + */ + +class QgsGeometrySnapper : QObject +{ +%TypeHeaderCode +#include +%End + + public: + + /** + * Constructor for QgsGeometrySnapper. A reference layer which contains geometries to snap to must be + * set. The snap tolerance is specified in the layer units for the + * reference layer, and it is assumed that all geometries snapped using this object will have the + * same CRS as the reference layer (ie, no reprojection is performed). + */ + QgsGeometrySnapper( QgsVectorLayer* referenceLayer, double snapTolerance ); + + /** + * Snaps a geometry to the reference layer and returns the result. The geometry must be in the same + * CRS as the reference layer. + */ + QgsGeometry snapGeometry( const QgsGeometry& geometry ) const; + + /** + * Snaps a set of features to the reference layer and returns the result. This operation is + * multithreaded for performance. The featureSnapped() signal will be emitted each time a feature + * is processed. This method is not safe to call from multiple threads concurrently. + */ + QgsFeatureList snapFeatures( const QgsFeatureList& features ); + + signals: + + //! Emitted each time a feature has been processed when calling snapFeatures() + void featureSnapped(); +}; diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index 631062dfe4a1..c65e965d7667 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -481,6 +481,9 @@ qgis:smoothgeometry: > The maximum angle parameter can be used to prevent smoothing of nodes with large angles. Any node where the angle of the segments to either side is larger then this will not be smoothed. Eg setting the maximum angle to 90 degrees or lower would preserve right angles in the geometry. +qgis:snapgeometriestolayer: > + This algorithm snaps the geometries in a layer to the geometries in another layer. A tolerance is specified in layer units to control how close vertices need to be to the reference layer geometries before they are snapped. Snapping occurs to both vertices and edges, but snapping to a vertex is preferred. Vertices will be inserted or removed as required to make the geometries match the reference geometries. + qgis:snappointstogrid: > This algorithm modifies the position of points in a vector layer, so they fall in the coordinates of a grid. diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 0bf402c0fcef..1fb2006cb058 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -175,6 +175,7 @@ from .ExtendLines import ExtendLines from .ExtractSpecificNodes import ExtractSpecificNodes from .GeometryByExpression import GeometryByExpression +from .SnapGeometries import SnapGeometriesToLayer pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -237,7 +238,7 @@ def __init__(self): IdwInterpolationZValue(), IdwInterpolationAttribute(), TinInterpolationZValue(), TinInterpolationAttribute(), RemoveNullGeometry(), ExtractByExpression(), ExtendLines(), - ExtractSpecificNodes(), GeometryByExpression() + ExtractSpecificNodes(), GeometryByExpression(), SnapGeometriesToLayer() ] if hasMatplotlib: diff --git a/python/plugins/processing/algs/qgis/SnapGeometries.py b/python/plugins/processing/algs/qgis/SnapGeometries.py new file mode 100644 index 000000000000..e4f9b92bd237 --- /dev/null +++ b/python/plugins/processing/algs/qgis/SnapGeometries.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + SnapGeometries.py + ----------------- + Date : October 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" +from builtins import str + +__author__ = 'Nyall Dawson' +__date__ = 'October 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.analysis import QgsGeometrySnapper +from qgis.core import QgsFeature + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector, ParameterNumber +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.outputs import OutputVector +from processing.tools import dataobjects, vector + + +class SnapGeometriesToLayer(GeoAlgorithm): + + INPUT = 'INPUT' + REFERENCE_LAYER = 'REFERENCE_LAYER' + TOLERANCE = 'TOLERANCE' + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Snap geometries to layer') + self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + + self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'))) + self.addParameter(ParameterVector(self.REFERENCE_LAYER, self.tr('Reference layer'))) + self.addParameter(ParameterNumber(self.TOLERANCE, self.tr('Tolerance (layer units)'), 0.00000001, 9999999999, default=10.0)) + self.addOutput(OutputVector(self.OUTPUT, self.tr('Snapped geometries'))) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) + reference_layer = dataobjects.getObjectFromUri(self.getParameterValue(self.REFERENCE_LAYER)) + tolerance = self.getParameterValue(self.TOLERANCE) + + if not layer.geometryType() == reference_layer.geometryType(): + raise GeoAlgorithmExecutionException( + self.tr('Input layer and reference layer must have the same geometry type (eg both are line layers)')) + + writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( + layer.fields(), layer.wkbType(), layer.crs()) + + features = vector.features(layer) + + self.processed = 0 + self.progress = progress + self.total = 100.0 / len(features) + + snapper = QgsGeometrySnapper(reference_layer, tolerance) + snapper.featureSnapped.connect(self.featureSnapped) + snapped_features = snapper.snapFeatures(features) + for f in snapped_features: + writer.addFeature(QgsFeature(f)) + + del writer + + def featureSnapped(self): + self.processed += 1 + self.progress.setPercentage(int(self.processed * self.total)) diff --git a/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gfs b/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gfs new file mode 100644 index 000000000000..65b36fce515e --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gfs @@ -0,0 +1,14 @@ + + + snap_lines_to_lines + snap_lines_to_lines + EPSG:4326 + + 7 + -1.00000 + 11.34679 + -5.00000 + 5.28899 + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml b/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml new file mode 100644 index 000000000000..5e54d761fe6b --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml @@ -0,0 +1,48 @@ + + + + + -1-5 + 11.346788990825695.288990825688074 + + + + + + 6,2 9,2 9,3 11,5 11.346788990825686,5.288990825688074 + + + + + -1,-1 1,-1 + + + + + 2,0 2,2 2,2 3,2 3,2 + + + + + 3,-3 3,-5 + + + + + 7,-3 10,-3 + + + + + 6,-3 10,1 10.208073394495411,0.849724770642202 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gfs b/python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gfs new file mode 100644 index 000000000000..4ee6f12aa1d2 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gfs @@ -0,0 +1,32 @@ + + + snap_polys_to_polys + snap_polys_to_polys + + 3 + EPSG:4326 + + 4 + -1.00000 + 10.00000 + -3.00000 + 5.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gml b/python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gml new file mode 100644 index 000000000000..05f6544d3391 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_polys_to_polys.gml @@ -0,0 +1,43 @@ + + + + + -1-3 + 105 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.123456 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,0 7,0 + ASDF + 0 + + + + + 120 + -100291.43213 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 7ee879f0c78e..26bceff7fbe1 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1387,3 +1387,33 @@ tests: OUTPUT_LAYER: name: expected/geometry_by_expression_line.gml type: vector + + - algorithm: qgis:snapgeometriestolayer + name: Snap lines to lines + params: + INPUT: + name: snap_lines.gml + type: vector + REFERENCE_LAYER: + name: lines.gml + type: vector + TOLERANCE: 1.0 + results: + OUTPUT: + name: expected/snap_lines_to_lines.gml + type: vector + + - algorithm: qgis:snapgeometriestolayer + name: Snap polygons to polygons + params: + INPUT: + name: snap_polys.gml + type: vector + REFERENCE_LAYER: + name: polys.gml + type: vector + TOLERANCE: 1.0 + results: + OUTPUT: + name: expected/snap_polys_to_polys.gml + type: vector diff --git a/python/plugins/processing/tests/testdata/snap_lines.gfs b/python/plugins/processing/tests/testdata/snap_lines.gfs new file mode 100644 index 000000000000..654cac8c5297 --- /dev/null +++ b/python/plugins/processing/tests/testdata/snap_lines.gfs @@ -0,0 +1,16 @@ + + + snap_lines + snap_lines + + 2 + EPSG:4326 + + 7 + -1.00000 + 11.34679 + -5.00000 + 5.28899 + + + diff --git a/python/plugins/processing/tests/testdata/snap_lines.gml b/python/plugins/processing/tests/testdata/snap_lines.gml new file mode 100644 index 000000000000..cd5c809e5c4e --- /dev/null +++ b/python/plugins/processing/tests/testdata/snap_lines.gml @@ -0,0 +1,48 @@ + + + + + -1-5 + 11.346788990825695.288990825688074 + + + + + + 5.965321100917431,2.300550458715596 8.653211009174312,1.606972477064221 11.346788990825686,5.288990825688074 + + + + + -1,-1 1,-1 + + + + + 2,0 1.826605504587156,2.138715596330275 2.211493443352086,2.093215161348839 3.27743119266055,1.815045871559633 + + + + + 3,-3 3,-5 + + + + + 7,-3 10,-3 + + + + + 5.826605504587156,-2.861284403669725 7.751422018348623,-1.641605504587157 9.092339449541285,0.323532110091743 10.208073394495413,0.849724770642202 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/snap_polys.gfs b/python/plugins/processing/tests/testdata/snap_polys.gfs new file mode 100644 index 000000000000..2e6769c4cdaa --- /dev/null +++ b/python/plugins/processing/tests/testdata/snap_polys.gfs @@ -0,0 +1,32 @@ + + + snap_polys + snap_polys + + 3 + EPSG:4326 + + 4 + -1.00000 + 10.00000 + -3.00000 + 5.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/snap_polys.gml b/python/plugins/processing/tests/testdata/snap_polys.gml new file mode 100644 index 000000000000..9967eb4de0b6 --- /dev/null +++ b/python/plugins/processing/tests/testdata/snap_polys.gml @@ -0,0 +1,43 @@ + + + + + -1-3 + 105 + + + + + + -1,-1 -0.784492588369441,2.795267958950969 2.849144811858609,2.773717217787913 2.978449258836944,2.0 2.300050170012289,2.312229761192763 1.730615735461802,2.183181299885975 1.804771291422702,1.306921584337844 1.670061352901153,0.930982619199196 1.754632529218785,0.447776631639586 2,-1 -1,-1 + aaaaa + 33 + 44.123455999999997 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0.000000000000000 + + + + + 6,1 10,1 10,-3 6,-3 6,17.431014823261117,-0.247833523375142 7,-2 9.118529076396808,0.204732041049031 7.431014823261117,-0.247833523375142 + ASDF + 0 + + + + + 120 + -100291.432130000001052 + + + diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index 5da66b09cbee..bc91f54b8cd8 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -38,6 +38,7 @@ SET(QGIS_ANALYSIS_SRCS raster/qgsrastermatrix.cpp vector/mersenne-twister.cpp vector/qgsgeometryanalyzer.cpp + vector/qgsgeometrysnapper.cpp vector/qgspointsample.cpp vector/qgstransectsample.cpp vector/qgszonalstatistics.cpp @@ -52,6 +53,7 @@ SET(QGIS_ANALYSIS_SRCS SET(QGIS_ANALYSIS_MOC_HDRS openstreetmap/qgsosmdownload.h openstreetmap/qgsosmimport.h + vector/qgsgeometrysnapper.h ) INCLUDE_DIRECTORIES(SYSTEM ${SPATIALITE_INCLUDE_DIR}) diff --git a/src/analysis/vector/qgsgeometrysnapper.cpp b/src/analysis/vector/qgsgeometrysnapper.cpp new file mode 100644 index 000000000000..68473086f44c --- /dev/null +++ b/src/analysis/vector/qgsgeometrysnapper.cpp @@ -0,0 +1,648 @@ +/*************************************************************************** + * qgsgeometrysnapper.cpp * + * ------------------- * + * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * + * email : smani@sourcepole.ch * + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include +#include + +#include "qgsfeatureiterator.h" +#include "qgsgeometry.h" +#include "qgsvectorlayer.h" +#include "qgsgeometrysnapper.h" +#include "qgsvectordataprovider.h" +#include "qgsgeometryutils.h" +#include "qgsmapsettings.h" + +///@cond PRIVATE + +QgsSnapIndex::PointSnapItem::PointSnapItem( const QgsSnapIndex::CoordIdx* _idx ) + : SnapItem( QgsSnapIndex::SnapPoint ) + , idx( _idx ) +{} + +QgsPointV2 QgsSnapIndex::PointSnapItem::getSnapPoint( const QgsPointV2 &/*p*/ ) const +{ + return idx->point(); +} + +QgsSnapIndex::SegmentSnapItem::SegmentSnapItem( const QgsSnapIndex::CoordIdx* _idxFrom, const QgsSnapIndex::CoordIdx* _idxTo ) + : SnapItem( QgsSnapIndex::SnapSegment ) + , idxFrom( _idxFrom ) + , idxTo( _idxTo ) +{} + +QgsPointV2 QgsSnapIndex::SegmentSnapItem::getSnapPoint( const QgsPointV2 &p ) const +{ + return QgsGeometryUtils::projPointOnSegment( p, idxFrom->point(), idxTo->point() ); +} + +bool QgsSnapIndex::SegmentSnapItem::getIntersection( const QgsPointV2 &p1, const QgsPointV2 &p2, QgsPointV2& inter ) const +{ + const QgsPointV2& q1 = idxFrom->point(), & q2 = idxTo->point(); + QgsVector v( p2.x() - p1.x(), p2.y() - p1.y() ); + QgsVector w( q2.x() - q1.x(), q2.y() - q1.y() ); + double vl = v.length(); + double wl = w.length(); + + if ( qFuzzyIsNull( vl ) || qFuzzyIsNull( wl ) ) + { + return false; + } + v = v / vl; + w = w / wl; + + double d = v.y() * w.x() - v.x() * w.y(); + + if ( d == 0 ) + return false; + + double dx = q1.x() - p1.x(); + double dy = q1.y() - p1.y(); + double k = ( dy * w.x() - dx * w.y() ) / d; + + inter = QgsPointV2( p1.x() + v.x() * k, p1.y() + v.y() * k ); + + double lambdav = QgsVector( inter.x() - p1.x(), inter.y() - p1.y() ) * v; + if ( lambdav < 0. + 1E-8 || lambdav > vl - 1E-8 ) + return false; + + double lambdaw = QgsVector( inter.x() - q1.x(), inter.y() - q1.y() ) * w; + if ( lambdaw < 0. + 1E-8 || lambdaw >= wl - 1E-8 ) + return false; + + return true; +} + +bool QgsSnapIndex::SegmentSnapItem::getProjection( const QgsPointV2 &p, QgsPointV2 &pProj ) +{ + const QgsPointV2& s1 = idxFrom->point(); + const QgsPointV2& s2 = idxTo->point(); + double nx = s2.y() - s1.y(); + double ny = -( s2.x() - s1.x() ); + double t = ( p.x() * ny - p.y() * nx - s1.x() * ny + s1.y() * nx ) / (( s2.x() - s1.x() ) * ny - ( s2.y() - s1.y() ) * nx ); + if ( t < 0. || t > 1. ) + { + return false; + } + pProj = QgsPointV2( s1.x() + ( s2.x() - s1.x() ) * t, s1.y() + ( s2.y() - s1.y() ) * t ); + return true; +} + +/////////////////////////////////////////////////////////////////////////////// + +class Raytracer +{ + // Raytrace on an integer, unit-width 2D grid with floating point coordinates + // See http://playtechs.blogspot.ch/2007/03/raytracing-on-grid.html + public: + Raytracer( float x0, float y0, float x1, float y1 ) + : m_dx( qAbs( x1 - x0 ) ) + , m_dy( qAbs( y1 - y0 ) ) + , m_x( qFloor( x0 ) ) + , m_y( qFloor( y0 ) ) + , m_n( 1 ) + { + if ( m_dx == 0. ) + { + m_xInc = 0.; + m_error = std::numeric_limits::infinity(); + } + else if ( x1 > x0 ) + { + m_xInc = 1; + m_n += int( qFloor( x1 ) ) - m_x; + m_error = ( qFloor( x0 ) + 1 - x0 ) * m_dy; + } + else + { + m_xInc = -1; + m_n += m_x - int( qFloor( x1 ) ); + m_error = ( x0 - qFloor( x0 ) ) * m_dy; + } + if ( m_dy == 0. ) + { + m_yInc = 0.; + m_error = -std::numeric_limits::infinity(); + } + else if ( y1 > y0 ) + { + m_yInc = 1; + m_n += int( qFloor( y1 ) ) - m_y; + m_error -= ( qFloor( y0 ) + 1 - y0 ) * m_dx; + } + else + { + m_yInc = -1; + m_n += m_y - int( qFloor( y1 ) ); + m_error -= ( y0 - qFloor( y0 ) ) * m_dx; + } + } + int curCol() const { return m_x; } + int curRow() const { return m_y; } + void next() + { + if ( m_error > 0 ) + { + m_y += m_yInc; + m_error -= m_dx; + } + else if ( m_error < 0 ) + { + m_x += m_xInc; + m_error += m_dy; + } + else + { + m_x += m_xInc; + m_y += m_yInc; + m_error += m_dx; + m_error -= m_dy; + --m_n; + } + --m_n; + } + + bool isValid() const { return m_n > 0; } + + private: + float m_dx, m_dy; + int m_x, m_y; + int m_xInc, m_yInc; + float m_error; + int m_n; +}; + +/////////////////////////////////////////////////////////////////////////////// + +QgsSnapIndex::GridRow::~GridRow() +{ + Q_FOREACH ( const QgsSnapIndex::Cell& cell, mCells ) + { + qDeleteAll( cell ); + } +} + +QgsSnapIndex::Cell& QgsSnapIndex::GridRow::getCreateCell( int col ) +{ + if ( col < mColStartIdx ) + { + for ( int i = col; i < mColStartIdx; ++i ) + { + mCells.prepend( Cell() ); + } + mColStartIdx = col; + return mCells.front(); + } + else if ( col >= mColStartIdx + mCells.size() ) + { + for ( int i = mColStartIdx + mCells.size(); i <= col; ++i ) + { + mCells.append( Cell() ); + } + return mCells.back(); + } + else + { + return mCells[col - mColStartIdx]; + } +} + +const QgsSnapIndex::Cell* QgsSnapIndex::GridRow::getCell( int col ) const +{ + if ( col < mColStartIdx || col >= mColStartIdx + mCells.size() ) + { + return nullptr; + } + else + { + return &mCells[col - mColStartIdx]; + } +} + +QList QgsSnapIndex::GridRow::getSnapItems( int colStart, int colEnd ) const +{ + colStart = qMax( colStart, mColStartIdx ); + colEnd = qMin( colEnd, mColStartIdx + mCells.size() - 1 ); + + QList items; + + for ( int col = colStart; col <= colEnd; ++col ) + { + items.append( mCells[col - mColStartIdx] ); + } + return items; +} + +/////////////////////////////////////////////////////////////////////////////// + +QgsSnapIndex::QgsSnapIndex( const QgsPointV2& origin, double cellSize ) + : mOrigin( origin ) + , mCellSize( cellSize ) + , mRowsStartIdx( 0 ) +{ +} + +QgsSnapIndex::~QgsSnapIndex() +{ + qDeleteAll( mCoordIdxs ); +} + + +const QgsSnapIndex::Cell *QgsSnapIndex::getCell( int col, int row ) const +{ + if ( row < mRowsStartIdx || row >= mRowsStartIdx + mGridRows.size() ) + { + return nullptr; + } + else + { + return mGridRows[row - mRowsStartIdx].getCell( col ); + } +} + +QgsSnapIndex::Cell& QgsSnapIndex::getCreateCell( int col, int row ) +{ + if ( row < mRowsStartIdx ) + { + for ( int i = row; i < mRowsStartIdx; ++i ) + { + mGridRows.prepend( GridRow() ); + } + mRowsStartIdx = row; + return mGridRows.front().getCreateCell( col ); + } + else if ( row >= mRowsStartIdx + mGridRows.size() ) + { + for ( int i = mRowsStartIdx + mGridRows.size(); i <= row; ++i ) + { + mGridRows.append( GridRow() ); + } + return mGridRows.back().getCreateCell( col ); + } + else + { + return mGridRows[row - mRowsStartIdx].getCreateCell( col ); + } +} + +void QgsSnapIndex::addPoint( const CoordIdx* idx ) +{ + QgsPointV2 p = idx->point(); + int col = qFloor(( p.x() - mOrigin.x() ) / mCellSize ); + int row = qFloor(( p.y() - mOrigin.y() ) / mCellSize ); + getCreateCell( col, row ).append( new PointSnapItem( idx ) ); +} + +void QgsSnapIndex::addSegment( const CoordIdx* idxFrom, const CoordIdx* idxTo ) +{ + QgsPointV2 pFrom = idxFrom->point(); + QgsPointV2 pTo = idxTo->point(); + // Raytrace along the grid, get touched cells + float x0 = ( pFrom.x() - mOrigin.x() ) / mCellSize; + float y0 = ( pFrom.y() - mOrigin.y() ) / mCellSize; + float x1 = ( pTo.x() - mOrigin.x() ) / mCellSize; + float y1 = ( pTo.y() - mOrigin.y() ) / mCellSize; + + Raytracer rt( x0, y0, x1, y1 ); + for ( ; rt.isValid(); rt.next() ) + { + getCreateCell( rt.curCol(), rt.curRow() ).append( new SegmentSnapItem( idxFrom, idxTo ) ); + } +} + +void QgsSnapIndex::addGeometry( const QgsAbstractGeometry* geom ) +{ + for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart ) + { + for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing ) + { + for ( int iVert = 0, nVerts = geom->vertexCount( iPart, iRing ) - 1; iVert < nVerts; ++iVert ) + { + CoordIdx* idx = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert ) ); + CoordIdx* idx1 = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert + 1 ) ); + mCoordIdxs.append( idx ); + mCoordIdxs.append( idx1 ); + addPoint( idx ); + addSegment( idx, idx1 ); + } + } + } +} + + +QgsPointV2 QgsSnapIndex::getClosestSnapToPoint( const QgsPointV2& p, const QgsPointV2& q ) +{ + // Look for intersections on segment from the target point to the point opposite to the point reference point + // p2 = p1 + 2 * (q - p1) + QgsPointV2 p2( 2 * q.x() - p.x(), 2 * q.y() - p.y() ); + + // Raytrace along the grid, get touched cells + float x0 = ( p.x() - mOrigin.x() ) / mCellSize; + float y0 = ( p.y() - mOrigin.y() ) / mCellSize; + float x1 = ( p2.x() - mOrigin.x() ) / mCellSize; + float y1 = ( p2.y() - mOrigin.y() ) / mCellSize; + + Raytracer rt( x0, y0, x1, y1 ); + double dMin = std::numeric_limits::max(); + QgsPointV2 pMin = p; + for ( ; rt.isValid(); rt.next() ) + { + const Cell* cell = getCell( rt.curCol(), rt.curRow() ); + if ( !cell ) + { + continue; + } + Q_FOREACH ( const SnapItem* item, *cell ) + { + if ( item->type == SnapSegment ) + { + QgsPointV2 inter; + if ( static_cast( item )->getIntersection( p, p2, inter ) ) + { + double dist = QgsGeometryUtils::sqrDistance2D( q, inter ); + if ( dist < dMin ) + { + dMin = dist; + pMin = inter; + } + } + } + } + } + + return pMin; +} + +QgsSnapIndex::SnapItem* QgsSnapIndex::getSnapItem( const QgsPointV2& pos, double tol, QgsSnapIndex::PointSnapItem** pSnapPoint, QgsSnapIndex::SegmentSnapItem** pSnapSegment ) const +{ + int colStart = qFloor(( pos.x() - tol - mOrigin.x() ) / mCellSize ); + int rowStart = qFloor(( pos.y() - tol - mOrigin.y() ) / mCellSize ); + int colEnd = qFloor(( pos.x() + tol - mOrigin.x() ) / mCellSize ); + int rowEnd = qFloor(( pos.y() + tol - mOrigin.y() ) / mCellSize ); + + rowStart = qMax( rowStart, mRowsStartIdx ); + rowEnd = qMin( rowEnd, mRowsStartIdx + mGridRows.size() - 1 ); + + QList items; + for ( int row = rowStart; row <= rowEnd; ++row ) + { + items.append( mGridRows[row - mRowsStartIdx].getSnapItems( colStart, colEnd ) ); + } + + double minDistSegment = std::numeric_limits::max(); + double minDistPoint = std::numeric_limits::max(); + QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; + QgsSnapIndex::PointSnapItem* snapPoint = nullptr; + + Q_FOREACH ( QgsSnapIndex::SnapItem* item, items ) + { + if ( item->type == SnapPoint ) + { + double dist = QgsGeometryUtils::sqrDistance2D( item->getSnapPoint( pos ), pos ); + if ( dist < minDistPoint ) + { + minDistPoint = dist; + snapPoint = static_cast( item ); + } + } + else if ( item->type == SnapSegment ) + { + QgsPointV2 pProj; + if ( !static_cast( item )->getProjection( pos, pProj ) ) + { + continue; + } + double dist = QgsGeometryUtils::sqrDistance2D( pProj, pos ); + if ( dist < minDistSegment ) + { + minDistSegment = dist; + snapSegment = static_cast( item ); + } + } + } + snapPoint = minDistPoint < tol * tol ? snapPoint : nullptr; + snapSegment = minDistSegment < tol * tol ? snapSegment : nullptr; + if ( pSnapPoint ) *pSnapPoint = snapPoint; + if ( pSnapSegment ) *pSnapSegment = snapSegment; + return minDistPoint < minDistSegment ? static_cast( snapPoint ) : static_cast( snapSegment ); +} + +/// @endcond + + + + +QgsGeometrySnapper::QgsGeometrySnapper( QgsVectorLayer *referenceLayer, double snapTolerance ) + : mReferenceLayer( referenceLayer ) + , mSnapTolerance( snapTolerance ) +{ + // Build spatial index + QgsFeatureRequest req; + req.setSubsetOfAttributes( QgsAttributeList() ); + mIndex = QgsSpatialIndex( mReferenceLayer->getFeatures( req ) ); +} + +QgsFeatureList QgsGeometrySnapper::snapFeatures( const QgsFeatureList& features ) +{ + QgsFeatureList list = features; + QtConcurrent::blockingMap( list, ProcessFeatureWrapper( this ) ); + return list; +} + +void QgsGeometrySnapper::processFeature( QgsFeature& feature ) +{ + if ( !feature.geometry().isEmpty() ) + feature.setGeometry( snapGeometry( feature.geometry() ) ); +} + +QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) const +{ + // can't snap to different geometry types + if ( geometry.type() != mReferenceLayer->geometryType() ) + return geometry; + + QgsPointV2 center = QgsPointV2( geometry.geometry()->boundingBox().center() ); + + // Get potential reference features and construct snap index + QList refGeometries; + mIndexMutex.lock(); + QgsFeatureIds refFeatureIds = mIndex.intersects( geometry.boundingBox() ).toSet(); + mIndexMutex.unlock(); + + QgsFeatureRequest refFeatureRequest = QgsFeatureRequest().setFilterFids( refFeatureIds ).setSubsetOfAttributes( QgsAttributeList() ); + mReferenceLayerMutex.lock(); + QgsFeature refFeature; + QgsFeatureIterator refFeatureIt = mReferenceLayer->getFeatures( refFeatureRequest ); + + while ( refFeatureIt.nextFeature( refFeature ) ) + { + refGeometries.append( refFeature.geometry() ); + } + mReferenceLayerMutex.unlock(); + + + QgsSnapIndex refSnapIndex( center, 10 * mSnapTolerance ); + Q_FOREACH ( const QgsGeometry& geom, refGeometries ) + { + refSnapIndex.addGeometry( geom.geometry() ); + } + + // Snap geometries + QgsAbstractGeometry* subjGeom = geometry.geometry()->clone(); + QList < QList< QList > > subjPointFlags; + + // Pass 1: snap vertices of subject geometry to reference vertices + for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart ) + { + subjPointFlags.append( QList< QList >() ); + + for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing ) + { + subjPointFlags[iPart].append( QList() ); + + for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert ) + { + + QgsSnapIndex::PointSnapItem* snapPoint = nullptr; + QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; + QgsVertexId vidx( iPart, iRing, iVert ); + QgsPointV2 p = subjGeom->vertexAt( vidx ); + if ( !refSnapIndex.getSnapItem( p, mSnapTolerance, &snapPoint, &snapSegment ) ) + { + subjPointFlags[iPart][iRing].append( Unsnapped ); + } + else + { + // Prefer snapping to point + if ( snapPoint ) + { + subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) ); + subjPointFlags[iPart][iRing].append( SnappedToRefNode ); + } + else if ( snapSegment ) + { + subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) ); + subjPointFlags[iPart][iRing].append( SnappedToRefSegment ); + } + } + } + } + } + + // SnapIndex for subject feature + QgsSnapIndex* subjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); + subjSnapIndex->addGeometry( subjGeom ); + + QgsAbstractGeometry* origSubjGeom = subjGeom->clone(); + QgsSnapIndex* origSubjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); + origSubjSnapIndex->addGeometry( origSubjGeom ); + + // Pass 2: add missing vertices to subject geometry + Q_FOREACH ( const QgsGeometry& refGeom, refGeometries ) + { + for ( int iPart = 0, nParts = refGeom.geometry()->partCount(); iPart < nParts; ++iPart ) + { + for ( int iRing = 0, nRings = refGeom.geometry()->ringCount( iPart ); iRing < nRings; ++iRing ) + { + for ( int iVert = 0, nVerts = polyLineSize( refGeom.geometry(), iPart, iRing ); iVert < nVerts; ++iVert ) + { + + QgsSnapIndex::PointSnapItem* snapPoint = nullptr; + QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; + QgsPointV2 point = refGeom.geometry()->vertexAt( QgsVertexId( iPart, iRing, iVert ) ); + if ( subjSnapIndex->getSnapItem( point, mSnapTolerance, &snapPoint, &snapSegment ) ) + { + // Snap to segment, unless a subject point was already snapped to the reference point + if ( snapPoint && QgsGeometryUtils::sqrDistance2D( snapPoint->getSnapPoint( point ), point ) < 1E-16 ) + { + continue; + } + else if ( snapSegment ) + { + // Look if there is a closer reference segment, if so, ignore this point + QgsPointV2 pProj = snapSegment->getSnapPoint( point ); + QgsPointV2 closest = refSnapIndex.getClosestSnapToPoint( point, pProj ); + if ( QgsGeometryUtils::sqrDistance2D( pProj, point ) > QgsGeometryUtils::sqrDistance2D( pProj, closest ) ) + { + continue; + } + + // If we are too far away from the original geometry, do nothing + if ( !origSubjSnapIndex->getSnapItem( point, mSnapTolerance ) ) + { + continue; + } + + const QgsSnapIndex::CoordIdx* idx = snapSegment->idxFrom; + subjGeom->insertVertex( QgsVertexId( idx->vidx.part, idx->vidx.ring, idx->vidx.vertex + 1 ), point ); + subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode ); + delete subjSnapIndex; + subjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); + subjSnapIndex->addGeometry( subjGeom ); + } + } + } + } + } + } + delete subjSnapIndex; + delete origSubjSnapIndex; + + // Pass 3: remove superfluous vertices: all vertices which are snapped to a segment and not preceded or succeeded by an unsnapped vertex + for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart ) + { + for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing ) + { + bool ringIsClosed = subjGeom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ) == subjGeom->vertexAt( QgsVertexId( iPart, iRing, subjGeom->vertexCount( iPart, iRing ) - 1 ) ); + for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert ) + { + int iPrev = ( iVert - 1 + nVerts ) % nVerts; + int iNext = ( iVert + 1 ) % nVerts; + QgsPointV2 pMid = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iVert ) ); + QgsPointV2 pPrev = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iPrev ) ); + QgsPointV2 pNext = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iNext ) ); + + if ( subjPointFlags[iPart][iRing][iVert] == SnappedToRefSegment && + subjPointFlags[iPart][iRing][iPrev] != Unsnapped && + subjPointFlags[iPart][iRing][iNext] != Unsnapped && + QgsGeometryUtils::sqrDistance2D( QgsGeometryUtils::projPointOnSegment( pMid, pPrev, pNext ), pMid ) < 1E-12 ) + { + if (( ringIsClosed && nVerts > 3 ) || ( !ringIsClosed && nVerts > 2 ) ) + { + subjGeom->deleteVertex( QgsVertexId( iPart, iRing, iVert ) ); + subjPointFlags[iPart][iRing].removeAt( iVert ); + iVert -= 1; + nVerts -= 1; + } + else + { + // Don't delete vertices if this would result in a degenerate geometry + break; + } + } + } + } + } + + return QgsGeometry( subjGeom ); +} + +int QgsGeometrySnapper::polyLineSize( const QgsAbstractGeometry* geom, int iPart, int iRing ) const +{ + int nVerts = geom->vertexCount( iPart, iRing ); + QgsPointV2 front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ); + QgsPointV2 back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) ); + return back == front ? nVerts - 1 : nVerts; +} diff --git a/src/analysis/vector/qgsgeometrysnapper.h b/src/analysis/vector/qgsgeometrysnapper.h new file mode 100644 index 000000000000..828e7f4b48c3 --- /dev/null +++ b/src/analysis/vector/qgsgeometrysnapper.h @@ -0,0 +1,183 @@ +/*************************************************************************** + * qgsgeometrysnapper.h * + * ------------------- * + * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * + * email : smani@sourcepole.ch * + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGS_GEOMETRY_SNAPPER_H +#define QGS_GEOMETRY_SNAPPER_H + +#include +#include +#include +#include "qgsspatialindex.h" +#include "qgsabstractgeometry.h" +#include "qgspointv2.h" + +class QgsVectorLayer; + +/** + * \class QgsGeometrySnapper + * \ingroup analysis + * QgsGeometrySnapper allows a geometry to be snapped to the geometries within a + * different refence layer. Vertices in the geometries will be modified to + * match the reference layer features within a specified snap tolerance. + * \note added in QGIS 3.0 + */ +class ANALYSIS_EXPORT QgsGeometrySnapper : public QObject +{ + Q_OBJECT + + public: + + /** + * Constructor for QgsGeometrySnapper. A reference layer which contains geometries to snap to must be + * set. The snap tolerance is specified in the layer units for the + * reference layer, and it is assumed that all geometries snapped using this object will have the + * same CRS as the reference layer (ie, no reprojection is performed). + */ + QgsGeometrySnapper( QgsVectorLayer* referenceLayer, double snapTolerance ); + + /** + * Snaps a geometry to the reference layer and returns the result. The geometry must be in the same + * CRS as the reference layer, and must have the same type as the reference layer geometry. + */ + QgsGeometry snapGeometry( const QgsGeometry& geometry ) const; + + /** + * Snaps a set of features to the reference layer and returns the result. This operation is + * multithreaded for performance. The featureSnapped() signal will be emitted each time a feature + * is processed. This method is not safe to call from multiple threads concurrently. + */ + QgsFeatureList snapFeatures( const QgsFeatureList& features ); + + signals: + + //! Emitted each time a feature has been processed when calling snapFeatures() + void featureSnapped(); + + private: + struct ProcessFeatureWrapper + { + QgsGeometrySnapper* instance; + explicit ProcessFeatureWrapper( QgsGeometrySnapper* _instance ) : instance( _instance ) {} + void operator()( QgsFeature& feature ) { return instance->processFeature( feature ); } + }; + + enum PointFlag { SnappedToRefNode, SnappedToRefSegment, Unsnapped }; + + QgsVectorLayer* mReferenceLayer; + QgsFeatureList mInputFeatures; + + double mSnapTolerance; + + QgsSpatialIndex mIndex; + mutable QMutex mIndexMutex; + mutable QMutex mReferenceLayerMutex; + + void processFeature( QgsFeature& feature ); + + int polyLineSize( const QgsAbstractGeometry* geom, int iPart, int iRing ) const; +}; + +///@cond PRIVATE +class QgsSnapIndex +{ + public: + struct CoordIdx + { + CoordIdx( const QgsAbstractGeometry* _geom, QgsVertexId _vidx ) + : geom( _geom ) + , vidx( _vidx ) + {} + QgsPointV2 point() const { return geom->vertexAt( vidx ); } + + const QgsAbstractGeometry* geom; + QgsVertexId vidx; + }; + + enum SnapType { SnapPoint, SnapSegment }; + + class SnapItem + { + public: + virtual ~SnapItem() {} + SnapType type; + virtual QgsPointV2 getSnapPoint( const QgsPointV2& p ) const = 0; + + protected: + explicit SnapItem( SnapType _type ) : type( _type ) {} + }; + + class PointSnapItem : public QgsSnapIndex::SnapItem + { + public: + explicit PointSnapItem( const CoordIdx* _idx ); + QgsPointV2 getSnapPoint( const QgsPointV2 &/*p*/ ) const override; + const CoordIdx* idx; + }; + + class SegmentSnapItem : public QgsSnapIndex::SnapItem + { + public: + SegmentSnapItem( const CoordIdx* _idxFrom, const CoordIdx* _idxTo ); + QgsPointV2 getSnapPoint( const QgsPointV2 &p ) const override; + bool getIntersection( const QgsPointV2& p1, const QgsPointV2& p2, QgsPointV2& inter ) const; + bool getProjection( const QgsPointV2 &p, QgsPointV2 &pProj ); + const CoordIdx* idxFrom; + const CoordIdx* idxTo; + }; + + QgsSnapIndex( const QgsPointV2& origin, double cellSize ); + ~QgsSnapIndex(); + void addGeometry( const QgsAbstractGeometry *geom ); + QgsPointV2 getClosestSnapToPoint( const QgsPointV2& p, const QgsPointV2& q ); + SnapItem *getSnapItem( const QgsPointV2& pos, double tol, PointSnapItem **pSnapPoint = nullptr, SegmentSnapItem **pSnapSegment = nullptr ) const; + + private: + typedef QList Cell; + typedef QPair Segment; + + class GridRow + { + public: + GridRow() : mColStartIdx( 0 ) {} + ~GridRow(); + const Cell *getCell( int col ) const; + Cell& getCreateCell( int col ); + QList getSnapItems( int colStart, int colEnd ) const; + + private: + QList mCells; + int mColStartIdx; + }; + + QgsPointV2 mOrigin; + double mCellSize; + + QList mCoordIdxs; + QList mGridRows; + int mRowsStartIdx; + + void addPoint( const CoordIdx* idx ); + void addSegment( const CoordIdx* idxFrom, const CoordIdx* idxTo ); + const Cell* getCell( int col, int row ) const; + Cell &getCreateCell( int col, int row ); + + QgsSnapIndex( const QgsSnapIndex& rh ); + QgsSnapIndex& operator=( const QgsSnapIndex& rh ); +}; + +///@endcond + +#endif // QGS_GEOMETRY_SNAPPER_H From dae0a017617d3082b6e89f8a3e75c2c9bcd0ebf5 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 5 Nov 2016 19:38:49 +1000 Subject: [PATCH 642/897] [FEATURE][processing] Snap geometries algorithm allows snapping to other layer types, supports point/line layers Fix #14791, #15313 --- .../processing/algs/qgis/SnapGeometries.py | 5 - .../expected/snap_points_to_points.gfs | 16 + .../expected/snap_points_to_points.gml | 59 +++ .../tests/testdata/qgis_algorithm_tests.yaml | 15 + .../processing/tests/testdata/snap_points.gfs | 16 + .../processing/tests/testdata/snap_points.gml | 59 +++ src/analysis/vector/qgsgeometrysnapper.cpp | 42 +- tests/src/analysis/CMakeLists.txt | 1 + tests/src/analysis/testqgsgeometrysnapper.cpp | 391 ++++++++++++++++++ 9 files changed, 589 insertions(+), 15 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/snap_points_to_points.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/snap_points_to_points.gml create mode 100644 python/plugins/processing/tests/testdata/snap_points.gfs create mode 100644 python/plugins/processing/tests/testdata/snap_points.gml create mode 100644 tests/src/analysis/testqgsgeometrysnapper.cpp diff --git a/python/plugins/processing/algs/qgis/SnapGeometries.py b/python/plugins/processing/algs/qgis/SnapGeometries.py index e4f9b92bd237..cce7cce92d58 100644 --- a/python/plugins/processing/algs/qgis/SnapGeometries.py +++ b/python/plugins/processing/algs/qgis/SnapGeometries.py @@ -31,7 +31,6 @@ from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector, ParameterNumber -from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector @@ -57,10 +56,6 @@ def processAlgorithm(self, progress): reference_layer = dataobjects.getObjectFromUri(self.getParameterValue(self.REFERENCE_LAYER)) tolerance = self.getParameterValue(self.TOLERANCE) - if not layer.geometryType() == reference_layer.geometryType(): - raise GeoAlgorithmExecutionException( - self.tr('Input layer and reference layer must have the same geometry type (eg both are line layers)')) - writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields(), layer.wkbType(), layer.crs()) diff --git a/python/plugins/processing/tests/testdata/expected/snap_points_to_points.gfs b/python/plugins/processing/tests/testdata/expected/snap_points_to_points.gfs new file mode 100644 index 000000000000..5034e2745723 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_points_to_points.gfs @@ -0,0 +1,16 @@ + + + snap_points_to_points + snap_points_to_points + + 1 + EPSG:4326 + + 9 + 0.20114 + 7.97127 + -4.82759 + 2.74139 + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_points_to_points.gml b/python/plugins/processing/tests/testdata/expected/snap_points_to_points.gml new file mode 100644 index 000000000000..df31c25b7822 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_points_to_points.gml @@ -0,0 +1,59 @@ + + + + + 0-5 + 7.9712656784492573 + + + + + + 1,1 + + + + + 3,3 + + + + + 2,2 + + + + + 5,2 + + + + + 4,1 + + + + + 0,-5 + + + + + 7.971265678449257,0.609122006841505 + + + + + 7,-1 + + + + + 0,-1 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 26bceff7fbe1..8f7317623fe0 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1417,3 +1417,18 @@ tests: OUTPUT: name: expected/snap_polys_to_polys.gml type: vector + + - algorithm: qgis:snapgeometriestolayer + name: Snap points to points + params: + INPUT: + name: snap_points.gml + type: vector + REFERENCE_LAYER: + name: points.gml + type: vector + TOLERANCE: 1.0 + results: + OUTPUT: + name: expected/snap_points_to_points.gml + type: vector \ No newline at end of file diff --git a/python/plugins/processing/tests/testdata/snap_points.gfs b/python/plugins/processing/tests/testdata/snap_points.gfs new file mode 100644 index 000000000000..48f585965247 --- /dev/null +++ b/python/plugins/processing/tests/testdata/snap_points.gfs @@ -0,0 +1,16 @@ + + + snap_points + snap_points + + 1 + EPSG:4326 + + 9 + 0.20114 + 7.97127 + -4.82759 + 2.74139 + + + diff --git a/python/plugins/processing/tests/testdata/snap_points.gml b/python/plugins/processing/tests/testdata/snap_points.gml new file mode 100644 index 000000000000..dae89598a17e --- /dev/null +++ b/python/plugins/processing/tests/testdata/snap_points.gml @@ -0,0 +1,59 @@ + + + + + 0.2011402508551881-4.827594070695552 + 7.9712656784492572.74139110604333 + + + + + + 1,1 + + + + + 3.134093500570125,2.74139110604333 + + + + + 2,2 + + + + + 5.25860889395667,1.578563283922463 + + + + + 3.683922462941847,0.961687571265678 + + + + + 0.201140250855188,-4.827594070695552 + + + + + 7.971265678449257,0.609122006841505 + + + + + 7.181984036488029,-1.268187001140251 + + + + + 0.220296465222349,-1.210718358038768 + + + diff --git a/src/analysis/vector/qgsgeometrysnapper.cpp b/src/analysis/vector/qgsgeometrysnapper.cpp index 68473086f44c..657633463db4 100644 --- a/src/analysis/vector/qgsgeometrysnapper.cpp +++ b/src/analysis/vector/qgsgeometrysnapper.cpp @@ -24,6 +24,8 @@ #include "qgsvectordataprovider.h" #include "qgsgeometryutils.h" #include "qgsmapsettings.h" +#include "qgssurface.h" +#include "qgscurve.h" ///@cond PRIVATE @@ -328,7 +330,17 @@ void QgsSnapIndex::addGeometry( const QgsAbstractGeometry* geom ) { for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing ) { - for ( int iVert = 0, nVerts = geom->vertexCount( iPart, iRing ) - 1; iVert < nVerts; ++iVert ) + int nVerts = geom->vertexCount( iPart, iRing ); + + if ( dynamic_cast< const QgsSurface* >( geom ) ) + nVerts--; + else if ( const QgsCurve* curve = dynamic_cast< const QgsCurve* >( geom ) ) + { + if ( curve->isClosed() ) + nVerts--; + } + + for ( int iVert = 0; iVert < nVerts; ++iVert ) { CoordIdx* idx = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert ) ); CoordIdx* idx1 = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert + 1 ) ); @@ -469,16 +481,15 @@ void QgsGeometrySnapper::processFeature( QgsFeature& feature ) QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) const { - // can't snap to different geometry types - if ( geometry.type() != mReferenceLayer->geometryType() ) - return geometry; - - QgsPointV2 center = QgsPointV2( geometry.geometry()->boundingBox().center() ); + QgsPointV2 center = dynamic_cast< const QgsPointV2* >( geometry.geometry() ) ? *dynamic_cast< const QgsPointV2* >( geometry.geometry() ) : + QgsPointV2( geometry.geometry()->boundingBox().center() ); // Get potential reference features and construct snap index QList refGeometries; mIndexMutex.lock(); - QgsFeatureIds refFeatureIds = mIndex.intersects( geometry.boundingBox() ).toSet(); + QgsRectangle searchBounds = geometry.boundingBox(); + searchBounds.grow( mSnapTolerance ); + QgsFeatureIds refFeatureIds = mIndex.intersects( searchBounds ).toSet(); mIndexMutex.unlock(); QgsFeatureRequest refFeatureRequest = QgsFeatureRequest().setFilterFids( refFeatureIds ).setSubsetOfAttributes( QgsAttributeList() ); @@ -541,6 +552,10 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons } } + //nothing more to do for points + if ( dynamic_cast< const QgsPointV2* >( subjGeom ) ) + return QgsGeometry( subjGeom ); + // SnapIndex for subject feature QgsSnapIndex* subjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); subjSnapIndex->addGeometry( subjGeom ); @@ -642,7 +657,14 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons int QgsGeometrySnapper::polyLineSize( const QgsAbstractGeometry* geom, int iPart, int iRing ) const { int nVerts = geom->vertexCount( iPart, iRing ); - QgsPointV2 front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ); - QgsPointV2 back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) ); - return back == front ? nVerts - 1 : nVerts; + + if ( dynamic_cast< const QgsSurface* >( geom ) ) + { + QgsPointV2 front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ); + QgsPointV2 back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) ); + if ( front == back ) + return nVerts - 1; + } + + return nVerts; } diff --git a/tests/src/analysis/CMakeLists.txt b/tests/src/analysis/CMakeLists.txt index bb9e3cfe4df1..7bf7b76f212b 100644 --- a/tests/src/analysis/CMakeLists.txt +++ b/tests/src/analysis/CMakeLists.txt @@ -77,6 +77,7 @@ ENDMACRO (ADD_QGIS_TEST) # Tests: ADD_QGIS_TEST(analyzertest testqgsvectoranalyzer.cpp) +ADD_QGIS_TEST(geometrysnappertest testqgsgeometrysnapper.cpp) ADD_QGIS_TEST(openstreetmaptest testopenstreetmap.cpp) ADD_QGIS_TEST(zonalstatisticstest testqgszonalstatistics.cpp) ADD_QGIS_TEST(rastercalculatortest testqgsrastercalculator.cpp) diff --git a/tests/src/analysis/testqgsgeometrysnapper.cpp b/tests/src/analysis/testqgsgeometrysnapper.cpp new file mode 100644 index 000000000000..2d040405d2bc --- /dev/null +++ b/tests/src/analysis/testqgsgeometrysnapper.cpp @@ -0,0 +1,391 @@ +/*************************************************************************** + testqgsgeometrysnapper.cpp + -------------------------- +Date : November 2016 +Copyright : (C) 2016 by Nyall Dawson +Email : nyall dot dawson at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include + +//header for class being tested +#include "qgsgeometrysnapper.h" +#include "qgsgeometry.h" +#include +#include "qgsvectordataprovider.h" +#include "qgsvectorlayer.h" + + +class TestQgsGeometrySnapper : public QObject +{ + Q_OBJECT + + public: + + + private slots: + void initTestCase();// will be called before the first testfunction is executed. + void cleanupTestCase();// will be called after the last testfunction was executed. + void init() ;// will be called before each testfunction is executed. + void cleanup() ;// will be called after every testfunction. + //! Our tests proper begin here + void snapPolygonToPolygon(); + void snapPolygonToLine(); + void snapPolygonToPoint(); + void snapLineToLine(); + void snapLineToPolygon(); + void snapLineToPoint(); + void snapPointToPoint(); + void snapPointToLine(); + void snapPointToPolygon(); +}; + +void TestQgsGeometrySnapper::initTestCase() +{ + // + // Runs once before any tests are run + // + // init QGIS's paths - true means that all path will be inited from prefix + QgsApplication::init(); + QgsApplication::initQgis(); +} +void TestQgsGeometrySnapper::cleanupTestCase() +{ + QgsApplication::exitQgis(); +} +void TestQgsGeometrySnapper::init() +{ + +} +void TestQgsGeometrySnapper::cleanup() +{ + +} + +void TestQgsGeometrySnapper::snapPolygonToPolygon() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + QgsFeature ff( 0 ); + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + ff.setGeometry( refGeom ); + QgsFeatureList flist; + flist << ff; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry polygonGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1))" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( polygonGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + + QgsGeometry polygonGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom2 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 0 10, 0 0))" ) ); + + // insert new vertex + QgsGeometry polygonGeom3 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom3 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0))" ) ); + + // remove vertex + QgsGeometry polygonGeom4 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom4 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); +} + +void TestQgsGeometrySnapper::snapLineToLine() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Linestring" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + QgsFeature ff( 0 ); + + // closed linestrings + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + ff.setGeometry( refGeom ); + QgsFeatureList flist; + flist << ff; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry lineGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1)" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( lineGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + + QgsGeometry lineGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1)" ) ); + result = snapper.snapGeometry( lineGeom2 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10, 0 0)" ) ); + + // insert new vertex + QgsGeometry lineGeom3 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1)" ) ); + result = snapper.snapGeometry( lineGeom3 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0)" ) ); + + // remove vertex + QgsGeometry lineGeom4 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1)" ) ); + result = snapper.snapGeometry( lineGeom4 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + + + // unclosed linestrings + QgsGeometry lineGeom5 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom5 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); + + QgsGeometry lineGeom6 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom6 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10)" ) ); + + // insert new vertex + QgsGeometry lineGeom7 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9)" ) ); + result = snapper.snapGeometry( lineGeom7 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10)" ) ); + + // remove vertex + QgsGeometry lineGeom8 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom8 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); +} + +void TestQgsGeometrySnapper::snapLineToPolygon() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + QgsFeature ff( 0 ); + + // closed linestrings + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + ff.setGeometry( refGeom ); + QgsFeatureList flist; + flist << ff; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry lineGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1)" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( lineGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + + QgsGeometry lineGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1)" ) ); + result = snapper.snapGeometry( lineGeom2 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10, 0 0)" ) ); + + // insert new vertex + QgsGeometry lineGeom3 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1)" ) ); + result = snapper.snapGeometry( lineGeom3 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0)" ) ); + + // remove vertex + QgsGeometry lineGeom4 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1)" ) ); + result = snapper.snapGeometry( lineGeom4 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + + + // unclosed linestrings + QgsGeometry lineGeom5 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom5 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); + + QgsGeometry lineGeom6 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom6 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10)" ) ); + + // insert new vertex + QgsGeometry lineGeom7 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9)" ) ); + result = snapper.snapGeometry( lineGeom7 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10)" ) ); + + // remove vertex + QgsGeometry lineGeom8 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom8 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); +} + +void TestQgsGeometrySnapper::snapLineToPoint() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0 0)" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + QgsGeometry refGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Point(10 0)" ) ); + QgsFeature ff2( 2 ); + ff2.setGeometry( refGeom2 ); + QgsFeatureList flist; + flist << ff << ff2; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry lineGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 10 10, 0 10)" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( lineGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); + + QgsGeometry lineGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom2 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10)" ) ); + + // insert new vertex + QgsGeometry lineGeom3 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.0 0.0, 20 10, 0 10)" ) ); + result = snapper.snapGeometry( lineGeom3 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20 0, 20 10, 0 10)" ) ); +} + +void TestQgsGeometrySnapper::snapPolygonToLine() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Linestring" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + // closed linestring + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + // unclosed linestring + QgsGeometry refGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(100 0, 110 0, 110 10, 100 10)" ) ); + QgsFeature ff2( 2 ); + ff2.setGeometry( refGeom2 ); + QgsFeatureList flist; + flist << ff << ff2; + rl->dataProvider()->addFeatures( flist ); + + + // snapping to closed linestring + QgsGeometry polygonGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1))" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( polygonGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + + QgsGeometry polygonGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom2 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 0 10, 0 0))" ) ); + + // insert new vertex + QgsGeometry polygonGeom3 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom3 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0))" ) ); + + // remove vertex + QgsGeometry polygonGeom4 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom4 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + + + // snapping to unclosed linestring + QgsGeometry polygonGeom5 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 110.1 0, 109.9 10.1, 100 10, 100.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom5 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 110 10, 100 10, 100 0))" ) ); + + QgsGeometry polygonGeom6 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 110.1 0, 100 10, 100.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom6 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 100 10, 100 0))" ) ); + + // insert new vertex + QgsGeometry polygonGeom7 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 120.5 0.5, 120 10, 100 9.9, 100.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom7 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 120.5 0.5, 120 10, 110 10, 100 10, 100 0))" ) ); + + // remove vertex + QgsGeometry polygonGeom8 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 110.1 0, 109.9 10.1, 105 10, 100 10, 100.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom8 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 110 10, 100 10, 100 0))" ) ); +} + +void TestQgsGeometrySnapper::snapPolygonToPoint() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0 0)" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + QgsGeometry refGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Point(10 0)" ) ); + QgsFeature ff2( 2 ); + ff2.setGeometry( refGeom2 ); + QgsFeatureList flist; + flist << ff << ff2; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry polygonGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 10 10, 0 10, 0.1 -0.1))" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( polygonGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + + QgsGeometry polygonGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom2 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 0 10, 0 0))" ) ); + + // insert new vertex + QgsGeometry polygonGeom3 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 20.0 0.0, 20 10, 0 10, 0.1 -0.1))" ) ); + result = snapper.snapGeometry( polygonGeom3 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 20 0, 20 10, 0 10, 0 0))" ) ); +} + +void TestQgsGeometrySnapper::snapPointToPoint() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Point" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0 0)" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + QgsGeometry refGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Point(1 0)" ) ); + QgsFeature ff2( 2 ); + ff2.setGeometry( refGeom2 ); + QgsFeatureList flist; + flist << ff << ff2; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.1 -0.1)" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( pointGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); + + pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.6 -0.1)" ) ); + result = snapper.snapGeometry( pointGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (1 0)" ) ); +} + +void TestQgsGeometrySnapper::snapPointToLine() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Linestring" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + // closed linestring + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + QgsFeatureList flist; + flist << ff; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.1 -0.1)" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( pointGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); + + pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(10.6 -0.1)" ) ); + result = snapper.snapGeometry( pointGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (10 0)" ) ); +} + +void TestQgsGeometrySnapper::snapPointToPolygon() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Polygon" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + // closed linestring + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + QgsFeatureList flist; + flist << ff; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.1 -0.1)" ) ); + QgsGeometrySnapper snapper( rl, 1 ); + QgsGeometry result = snapper.snapGeometry( pointGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); + + pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(10.6 -0.1)" ) ); + result = snapper.snapGeometry( pointGeom ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (10 0)" ) ); +} + + +QTEST_MAIN( TestQgsGeometrySnapper ) +#include "testqgsgeometrysnapper.moc" From 983fe24806b47d4c8a9aa6d226685be3fb8de90f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 5 Nov 2016 20:11:15 +1000 Subject: [PATCH 643/897] Port some API from QgsPoint to QgsPointV2 --- python/core/geometry/qgspointv2.sip | 41 +++++++++++++++++++++++++++++ src/core/geometry/qgspointv2.cpp | 27 +++++++++++++++++++ src/core/geometry/qgspointv2.h | 41 +++++++++++++++++++++++++++++ tests/src/core/testqgsgeometry.cpp | 30 +++++++++++++++++++++ 4 files changed, 139 insertions(+) diff --git a/python/core/geometry/qgspointv2.sip b/python/core/geometry/qgspointv2.sip index 2df14c504c53..5c774d47214b 100644 --- a/python/core/geometry/qgspointv2.sip +++ b/python/core/geometry/qgspointv2.sip @@ -138,6 +138,47 @@ class QgsPointV2: public QgsAbstractGeometry */ QPointF toQPointF() const; + /** + * Returns the distance between this point and a specified x, y coordinate. In certain + * cases it may be more appropriate to call the faster distanceSquared() method, eg + * when comparing distances. + * @note added in QGIS 3.0 + * @see distanceSquared() + */ + double distance( double x, double y ) const; + + /** + * Returns the 2D distance between this point and another point. In certain + * cases it may be more appropriate to call the faster distanceSquared() method, eg + * when comparing distances. + * @note added in QGIS 3.0 + */ + double distance( const QgsPointV2& other ) const; + + /** + * Returns the squared distance between this point a specified x, y coordinate. Calling + * this is faster than calling distance(), and may be useful in use cases such as comparing + * distances where the extra expense of calling distance() is not required. + * @see distance() + * @note added in QGIS 3.0 + */ + double distanceSquared( double x, double y ) const; + + /** + * Returns the squared distance between this point another point. Calling + * this is faster than calling distance(), and may be useful in use cases such as comparing + * distances where the extra expense of calling distance() is not required. + * @see distance() + * @note added in QGIS 3.0 + */ + double distanceSquared( const QgsPointV2& other ) const; + + /** + * Calculates azimuth between this point and other one (clockwise in degree, starting from north) + * @note added in QGIS 3.0 + */ + double azimuth( const QgsPointV2& other ) const; + //implementation of inherited methods virtual QgsRectangle boundingBox() const; virtual QString geometryType() const; diff --git a/src/core/geometry/qgspointv2.cpp b/src/core/geometry/qgspointv2.cpp index 246ee968380d..9a2e2c768d35 100644 --- a/src/core/geometry/qgspointv2.cpp +++ b/src/core/geometry/qgspointv2.cpp @@ -439,3 +439,30 @@ QPointF QgsPointV2::toQPointF() const { return QPointF( mX, mY ); } + +double QgsPointV2::distance( double x, double y ) const +{ + return sqrt(( mX - x ) * ( mX - x ) + ( mY - y ) * ( mY - y ) ); +} + +double QgsPointV2::distance( const QgsPointV2& other ) const +{ + return sqrt(( mX - other.x() ) * ( mX - other.x() ) + ( mY - other.y() ) * ( mY - other.y() ) ); +} + +double QgsPointV2::distanceSquared( double x, double y ) const +{ + return ( mX - x ) * ( mX - x ) + ( mY - y ) * ( mY - y ); +} + +double QgsPointV2::distanceSquared( const QgsPointV2& other ) const +{ + return ( mX - other.x() ) * ( mX - other.x() ) + ( mY - other.y() ) * ( mY - other.y() ) ; +} + +double QgsPointV2::azimuth( const QgsPointV2& other ) const +{ + double dx = other.x() - mX; + double dy = other.y() - mY; + return ( atan2( dx, dy ) * 180.0 / M_PI ); +} diff --git a/src/core/geometry/qgspointv2.h b/src/core/geometry/qgspointv2.h index b8d00622f4cc..cd034a1fd5ac 100644 --- a/src/core/geometry/qgspointv2.h +++ b/src/core/geometry/qgspointv2.h @@ -151,6 +151,47 @@ class CORE_EXPORT QgsPointV2: public QgsAbstractGeometry */ QPointF toQPointF() const; + /** + * Returns the distance between this point and a specified x, y coordinate. In certain + * cases it may be more appropriate to call the faster distanceSquared() method, eg + * when comparing distances. + * @note added in QGIS 3.0 + * @see distanceSquared() + */ + double distance( double x, double y ) const; + + /** + * Returns the 2D distance between this point and another point. In certain + * cases it may be more appropriate to call the faster distanceSquared() method, eg + * when comparing distances. + * @note added in QGIS 3.0 + */ + double distance( const QgsPointV2& other ) const; + + /** + * Returns the squared distance between this point a specified x, y coordinate. Calling + * this is faster than calling distance(), and may be useful in use cases such as comparing + * distances where the extra expense of calling distance() is not required. + * @see distance() + * @note added in QGIS 3.0 + */ + double distanceSquared( double x, double y ) const; + + /** + * Returns the squared distance between this point another point. Calling + * this is faster than calling distance(), and may be useful in use cases such as comparing + * distances where the extra expense of calling distance() is not required. + * @see distance() + * @note added in QGIS 3.0 + */ + double distanceSquared( const QgsPointV2& other ) const; + + /** + * Calculates azimuth between this point and other one (clockwise in degree, starting from north) + * @note added in QGIS 3.0 + */ + double azimuth( const QgsPointV2& other ) const; + //implementation of inherited methods virtual QgsRectangle boundingBox() const override { return QgsRectangle( mX, mY, mX, mY ); } virtual QString geometryType() const override { return QStringLiteral( "Point" ); } diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index ac0f1247f720..255a4905a76e 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -792,6 +792,36 @@ void TestQgsGeometry::point() //boundary QgsPointV2 p30( 1.0, 2.0 ); QVERIFY( !p30.boundary() ); + + // distance + QCOMPARE( QgsPointV2( 1, 2 ).distance( QgsPointV2( 2, 2 ) ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( 2, 2 ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( QgsPointV2( 3, 2 ) ), 2.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( 3, 2 ), 2.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( QgsPointV2( 1, 3 ) ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( 1, 3 ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( QgsPointV2( 1, 4 ) ), 2.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distance( 1, 4 ), 2.0 ); + QCOMPARE( QgsPointV2( 1, -2 ).distance( QgsPointV2( 1, -4 ) ), 2.0 ); + QCOMPARE( QgsPointV2( 1, -2 ).distance( 1, -4 ), 2.0 ); + + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( QgsPointV2( 2, 2 ) ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( 2, 2 ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( QgsPointV2( 3, 2 ) ), 4.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( 3, 2 ), 4.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( QgsPointV2( 1, 3 ) ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( 1, 3 ), 1.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( QgsPointV2( 1, 4 ) ), 4.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).distanceSquared( 1, 4 ), 4.0 ); + QCOMPARE( QgsPointV2( 1, -2 ).distanceSquared( QgsPointV2( 1, -4 ) ), 4.0 ); + QCOMPARE( QgsPointV2( 1, -2 ).distanceSquared( 1, -4 ), 4.0 ); + + // azimuth + QCOMPARE( QgsPointV2( 1, 2 ).azimuth( QgsPointV2( 1, 2 ) ), 0.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).azimuth( QgsPointV2( 1, 3 ) ), 0.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).azimuth( QgsPointV2( 2, 2 ) ), 90.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).azimuth( QgsPointV2( 1, 0 ) ), 180.0 ); + QCOMPARE( QgsPointV2( 1, 2 ).azimuth( QgsPointV2( 0, 2 ) ), -90.0 ); } void TestQgsGeometry::lineString() From 8acc286b0f14210c70a058c16c35b5482065bf16 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 08:28:24 +1000 Subject: [PATCH 644/897] [FEATURE] Snap to layer algorithm accepts a mode parameter With a new option to prefer to snap to closest point on geometry. The old behaviour was to prefer to snap to nodes, even if a node was further from the input geometry than a segment. The new option allows you to snap geometries to the closest point, regardless of whether it's a node or segment. --- python/analysis/vector/qgsgeometrysnapper.sip | 21 ++- .../processing/algs/qgis/SnapGeometries.py | 15 ++- .../testdata/expected/snap_lines_to_lines.gml | 10 +- .../snap_point_to_lines_prefer_closest.gfs | 16 +++ .../snap_point_to_lines_prefer_closest.gml | 59 +++++++++ .../snap_point_to_lines_prefer_nodes.gfs | 16 +++ .../snap_point_to_lines_prefer_nodes.gml | 59 +++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 34 ++++- src/analysis/vector/qgsgeometrysnapper.cpp | 85 ++++++++---- src/analysis/vector/qgsgeometrysnapper.h | 35 +++-- tests/src/analysis/testqgsgeometrysnapper.cpp | 121 +++++++++++------- 11 files changed, 369 insertions(+), 102 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gml create mode 100644 python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gml diff --git a/python/analysis/vector/qgsgeometrysnapper.sip b/python/analysis/vector/qgsgeometrysnapper.sip index 2b3c970473ce..ac0b59338365 100644 --- a/python/analysis/vector/qgsgeometrysnapper.sip +++ b/python/analysis/vector/qgsgeometrysnapper.sip @@ -15,26 +15,33 @@ class QgsGeometrySnapper : QObject public: + //! Snapping modes + enum SnapMode + { + PreferNodes, //!< Prefer to snap to nodes, even when a segment may be closer than a node + PreferClosest, //!< Snap to closest point, regardless of it is a node or a segment + }; + /** * Constructor for QgsGeometrySnapper. A reference layer which contains geometries to snap to must be - * set. The snap tolerance is specified in the layer units for the - * reference layer, and it is assumed that all geometries snapped using this object will have the + * set. It is assumed that all geometries snapped using this object will have the * same CRS as the reference layer (ie, no reprojection is performed). */ - QgsGeometrySnapper( QgsVectorLayer* referenceLayer, double snapTolerance ); + QgsGeometrySnapper( QgsVectorLayer* referenceLayer ); /** * Snaps a geometry to the reference layer and returns the result. The geometry must be in the same - * CRS as the reference layer. + * CRS as the reference layer, and must have the same type as the reference layer geometry. The snap tolerance + * is specified in the layer units for the reference layer. */ - QgsGeometry snapGeometry( const QgsGeometry& geometry ) const; + QgsGeometry snapGeometry( const QgsGeometry& geometry, double snapTolerance, SnapMode mode = PreferNodes ) const; /** * Snaps a set of features to the reference layer and returns the result. This operation is * multithreaded for performance. The featureSnapped() signal will be emitted each time a feature - * is processed. This method is not safe to call from multiple threads concurrently. + * is processed. The snap tolerance is specified in the layer units for the reference layer. */ - QgsFeatureList snapFeatures( const QgsFeatureList& features ); + QgsFeatureList snapFeatures( const QgsFeatureList& features, double snapTolerance, SnapMode mode = PreferNodes ); signals: diff --git a/python/plugins/processing/algs/qgis/SnapGeometries.py b/python/plugins/processing/algs/qgis/SnapGeometries.py index cce7cce92d58..0eaf7310ec7d 100644 --- a/python/plugins/processing/algs/qgis/SnapGeometries.py +++ b/python/plugins/processing/algs/qgis/SnapGeometries.py @@ -30,7 +30,7 @@ from qgis.core import QgsFeature from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterVector, ParameterNumber +from processing.core.parameters import ParameterVector, ParameterNumber, ParameterSelection from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector @@ -41,6 +41,7 @@ class SnapGeometriesToLayer(GeoAlgorithm): REFERENCE_LAYER = 'REFERENCE_LAYER' TOLERANCE = 'TOLERANCE' OUTPUT = 'OUTPUT' + BEHAVIOUR = 'BEHAVIOUR' def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Snap geometries to layer') @@ -49,12 +50,20 @@ def defineCharacteristics(self): self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'))) self.addParameter(ParameterVector(self.REFERENCE_LAYER, self.tr('Reference layer'))) self.addParameter(ParameterNumber(self.TOLERANCE, self.tr('Tolerance (layer units)'), 0.00000001, 9999999999, default=10.0)) + + self.modes = [self.tr('Prefer aligning nodes'), + self.tr('Prefer closest point')] + self.addParameter(ParameterSelection( + self.BEHAVIOUR, + self.tr('Behaviour'), + self.modes, default=0)) self.addOutput(OutputVector(self.OUTPUT, self.tr('Snapped geometries'))) def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) reference_layer = dataobjects.getObjectFromUri(self.getParameterValue(self.REFERENCE_LAYER)) tolerance = self.getParameterValue(self.TOLERANCE) + mode = self.getParameterValue(self.BEHAVIOUR) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields(), layer.wkbType(), layer.crs()) @@ -65,9 +74,9 @@ def processAlgorithm(self, progress): self.progress = progress self.total = 100.0 / len(features) - snapper = QgsGeometrySnapper(reference_layer, tolerance) + snapper = QgsGeometrySnapper(reference_layer) snapper.featureSnapped.connect(self.featureSnapped) - snapped_features = snapper.snapFeatures(features) + snapped_features = snapper.snapFeatures(features, tolerance, mode) for f in snapped_features: writer.addFeature(QgsFeature(f)) diff --git a/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml b/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml index 5e54d761fe6b..389687b5a54d 100644 --- a/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml +++ b/python/plugins/processing/tests/testdata/expected/snap_lines_to_lines.gml @@ -7,13 +7,13 @@ -1-5 - 11.346788990825695.288990825688074 + 115 - + - 6,2 9,2 9,3 11,5 11.346788990825686,5.288990825688074 + 6,2 9,2 9,3 11,5 @@ -23,7 +23,7 @@ - 2,0 2,2 2,2 3,2 3,2 + 2,0 2,2 2,2 3,2 @@ -38,7 +38,7 @@ - 6,-3 10,1 10.208073394495411,0.849724770642202 + 6,-3 10,1 diff --git a/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gfs b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gfs new file mode 100644 index 000000000000..ea8fc5861d69 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gfs @@ -0,0 +1,16 @@ + + + snap_point_to_lines_prefer_closest + snap_point_to_lines_prefer_closest + + 1 + EPSG:4326 + + 9 + 0.20114 + 7.97127 + -4.82759 + 2.74139 + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gml b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gml new file mode 100644 index 000000000000..12d50e55a5b4 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_closest.gml @@ -0,0 +1,59 @@ + + + + + 0.201140250855188-4.827594070695552 + 7.9712656784492572.74139110604333 + + + + + + 1,1 + + + + + 3.0,2.74139110604333 + + + + + 2,2 + + + + + 5,1 + + + + + 3.683922462941847,1.0 + + + + + 0.201140250855188,-4.827594070695552 + + + + + 7.971265678449257,0.609122006841505 + + + + + 7.456898517673889,-1.543101482326111 + + + + + 0.220296465222349,-1.0 + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gfs b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gfs new file mode 100644 index 000000000000..694e5c4f225f --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gfs @@ -0,0 +1,16 @@ + + + snap_point_to_lines_prefer_nodes + snap_point_to_lines_prefer_nodes + + 1 + EPSG:4326 + + 9 + 0.20114 + 7.97127 + -4.82759 + 3.00000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gml b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gml new file mode 100644 index 000000000000..f5254b3b309a --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/snap_point_to_lines_prefer_nodes.gml @@ -0,0 +1,59 @@ + + + + + 0.201140250855188-4.827594070695552 + 7.9712656784492573 + + + + + + 1,1 + + + + + 3,3 + + + + + 2,2 + + + + + 5,1 + + + + + 3,1 + + + + + 0.201140250855188,-4.827594070695552 + + + + + 7.971265678449257,0.609122006841505 + + + + + 7.456898517673889,-1.543101482326111 + + + + + 1,-1 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 8f7317623fe0..c667aaebeecd 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1431,4 +1431,36 @@ tests: results: OUTPUT: name: expected/snap_points_to_points.gml - type: vector \ No newline at end of file + type: vector + + - algorithm: qgis:snapgeometriestolayer + name: Snap points to lines (prefer nodes) + params: + BEHAVIOUR: '0' + INPUT: + name: snap_points.gml + type: vector + REFERENCE_LAYER: + name: lines.gml + type: vector + TOLERANCE: 1.0 + results: + OUTPUT: + name: expected/snap_point_to_lines_prefer_nodes.gml + type: vector + + - algorithm: qgis:snapgeometriestolayer + name: Snap points to lines (prefer closest) + params: + BEHAVIOUR: '1' + INPUT: + name: snap_points.gml + type: vector + REFERENCE_LAYER: + name: lines.gml + type: vector + TOLERANCE: 1.0 + results: + OUTPUT: + name: expected/snap_point_to_lines_prefer_closest.gml + type: vector diff --git a/src/analysis/vector/qgsgeometrysnapper.cpp b/src/analysis/vector/qgsgeometrysnapper.cpp index 657633463db4..4c6386ac056a 100644 --- a/src/analysis/vector/qgsgeometrysnapper.cpp +++ b/src/analysis/vector/qgsgeometrysnapper.cpp @@ -347,7 +347,8 @@ void QgsSnapIndex::addGeometry( const QgsAbstractGeometry* geom ) mCoordIdxs.append( idx ); mCoordIdxs.append( idx1 ); addPoint( idx ); - addSegment( idx, idx1 ); + if ( iVert < nVerts - 1 ) + addSegment( idx, idx1 ); } } } @@ -456,9 +457,8 @@ QgsSnapIndex::SnapItem* QgsSnapIndex::getSnapItem( const QgsPointV2& pos, double -QgsGeometrySnapper::QgsGeometrySnapper( QgsVectorLayer *referenceLayer, double snapTolerance ) +QgsGeometrySnapper::QgsGeometrySnapper( QgsVectorLayer *referenceLayer ) : mReferenceLayer( referenceLayer ) - , mSnapTolerance( snapTolerance ) { // Build spatial index QgsFeatureRequest req; @@ -466,20 +466,20 @@ QgsGeometrySnapper::QgsGeometrySnapper( QgsVectorLayer *referenceLayer, double s mIndex = QgsSpatialIndex( mReferenceLayer->getFeatures( req ) ); } -QgsFeatureList QgsGeometrySnapper::snapFeatures( const QgsFeatureList& features ) +QgsFeatureList QgsGeometrySnapper::snapFeatures( const QgsFeatureList& features, double snapTolerance, SnapMode mode ) { QgsFeatureList list = features; - QtConcurrent::blockingMap( list, ProcessFeatureWrapper( this ) ); + QtConcurrent::blockingMap( list, ProcessFeatureWrapper( this, snapTolerance, mode ) ); return list; } -void QgsGeometrySnapper::processFeature( QgsFeature& feature ) +void QgsGeometrySnapper::processFeature( QgsFeature& feature, double snapTolerance, SnapMode mode ) { if ( !feature.geometry().isEmpty() ) - feature.setGeometry( snapGeometry( feature.geometry() ) ); + feature.setGeometry( snapGeometry( feature.geometry(), snapTolerance, mode ) ); } -QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) const +QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry, double snapTolerance, SnapMode mode ) const { QgsPointV2 center = dynamic_cast< const QgsPointV2* >( geometry.geometry() ) ? *dynamic_cast< const QgsPointV2* >( geometry.geometry() ) : QgsPointV2( geometry.geometry()->boundingBox().center() ); @@ -488,7 +488,7 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons QList refGeometries; mIndexMutex.lock(); QgsRectangle searchBounds = geometry.boundingBox(); - searchBounds.grow( mSnapTolerance ); + searchBounds.grow( snapTolerance ); QgsFeatureIds refFeatureIds = mIndex.intersects( searchBounds ).toSet(); mIndexMutex.unlock(); @@ -504,7 +504,7 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons mReferenceLayerMutex.unlock(); - QgsSnapIndex refSnapIndex( center, 10 * mSnapTolerance ); + QgsSnapIndex refSnapIndex( center, 10 * snapTolerance ); Q_FOREACH ( const QgsGeometry& geom, refGeometries ) { refSnapIndex.addGeometry( geom.geometry() ); @@ -530,22 +530,57 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; QgsVertexId vidx( iPart, iRing, iVert ); QgsPointV2 p = subjGeom->vertexAt( vidx ); - if ( !refSnapIndex.getSnapItem( p, mSnapTolerance, &snapPoint, &snapSegment ) ) + if ( !refSnapIndex.getSnapItem( p, snapTolerance, &snapPoint, &snapSegment ) ) { subjPointFlags[iPart][iRing].append( Unsnapped ); } else { - // Prefer snapping to point - if ( snapPoint ) + switch ( mode ) { - subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) ); - subjPointFlags[iPart][iRing].append( SnappedToRefNode ); - } - else if ( snapSegment ) - { - subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) ); - subjPointFlags[iPart][iRing].append( SnappedToRefSegment ); + case PreferNodes: + { + // Prefer snapping to point + if ( snapPoint ) + { + subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) ); + subjPointFlags[iPart][iRing].append( SnappedToRefNode ); + } + else if ( snapSegment ) + { + subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) ); + subjPointFlags[iPart][iRing].append( SnappedToRefSegment ); + } + break; + } + + case PreferClosest: + { + QgsPointV2 nodeSnap, segmentSnap; + double distanceNode = DBL_MAX; + double distanceSegment = DBL_MAX; + if ( snapPoint ) + { + nodeSnap = snapPoint->getSnapPoint( p ); + distanceNode = nodeSnap.distanceSquared( p ); + } + if ( snapSegment ) + { + segmentSnap = snapSegment->getSnapPoint( p ); + distanceSegment = segmentSnap.distanceSquared( p ); + } + if ( snapPoint && distanceNode < distanceSegment ) + { + subjGeom->moveVertex( vidx, nodeSnap ); + subjPointFlags[iPart][iRing].append( SnappedToRefNode ); + } + else if ( snapSegment ) + { + subjGeom->moveVertex( vidx, segmentSnap ); + subjPointFlags[iPart][iRing].append( SnappedToRefSegment ); + } + break; + } } } } @@ -557,11 +592,11 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons return QgsGeometry( subjGeom ); // SnapIndex for subject feature - QgsSnapIndex* subjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); + QgsSnapIndex* subjSnapIndex = new QgsSnapIndex( center, 10 * snapTolerance ); subjSnapIndex->addGeometry( subjGeom ); QgsAbstractGeometry* origSubjGeom = subjGeom->clone(); - QgsSnapIndex* origSubjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); + QgsSnapIndex* origSubjSnapIndex = new QgsSnapIndex( center, 10 * snapTolerance ); origSubjSnapIndex->addGeometry( origSubjGeom ); // Pass 2: add missing vertices to subject geometry @@ -577,7 +612,7 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons QgsSnapIndex::PointSnapItem* snapPoint = nullptr; QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; QgsPointV2 point = refGeom.geometry()->vertexAt( QgsVertexId( iPart, iRing, iVert ) ); - if ( subjSnapIndex->getSnapItem( point, mSnapTolerance, &snapPoint, &snapSegment ) ) + if ( subjSnapIndex->getSnapItem( point, snapTolerance, &snapPoint, &snapSegment ) ) { // Snap to segment, unless a subject point was already snapped to the reference point if ( snapPoint && QgsGeometryUtils::sqrDistance2D( snapPoint->getSnapPoint( point ), point ) < 1E-16 ) @@ -595,7 +630,7 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons } // If we are too far away from the original geometry, do nothing - if ( !origSubjSnapIndex->getSnapItem( point, mSnapTolerance ) ) + if ( !origSubjSnapIndex->getSnapItem( point, snapTolerance ) ) { continue; } @@ -604,7 +639,7 @@ QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry& geometry ) cons subjGeom->insertVertex( QgsVertexId( idx->vidx.part, idx->vidx.ring, idx->vidx.vertex + 1 ), point ); subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode ); delete subjSnapIndex; - subjSnapIndex = new QgsSnapIndex( center, 10 * mSnapTolerance ); + subjSnapIndex = new QgsSnapIndex( center, 10 * snapTolerance ); subjSnapIndex->addGeometry( subjGeom ); } } diff --git a/src/analysis/vector/qgsgeometrysnapper.h b/src/analysis/vector/qgsgeometrysnapper.h index 828e7f4b48c3..ad3807488b2f 100644 --- a/src/analysis/vector/qgsgeometrysnapper.h +++ b/src/analysis/vector/qgsgeometrysnapper.h @@ -40,26 +40,33 @@ class ANALYSIS_EXPORT QgsGeometrySnapper : public QObject public: + //! Snapping modes + enum SnapMode + { + PreferNodes = 0, //!< Prefer to snap to nodes, even when a segment may be closer than a node + PreferClosest, //!< Snap to closest point, regardless of it is a node or a segment + }; + /** * Constructor for QgsGeometrySnapper. A reference layer which contains geometries to snap to must be - * set. The snap tolerance is specified in the layer units for the - * reference layer, and it is assumed that all geometries snapped using this object will have the + * set. It is assumed that all geometries snapped using this object will have the * same CRS as the reference layer (ie, no reprojection is performed). */ - QgsGeometrySnapper( QgsVectorLayer* referenceLayer, double snapTolerance ); + QgsGeometrySnapper( QgsVectorLayer* referenceLayer ); /** * Snaps a geometry to the reference layer and returns the result. The geometry must be in the same - * CRS as the reference layer, and must have the same type as the reference layer geometry. + * CRS as the reference layer, and must have the same type as the reference layer geometry. The snap tolerance + * is specified in the layer units for the reference layer. */ - QgsGeometry snapGeometry( const QgsGeometry& geometry ) const; + QgsGeometry snapGeometry( const QgsGeometry& geometry, double snapTolerance, SnapMode mode = PreferNodes ) const; /** * Snaps a set of features to the reference layer and returns the result. This operation is * multithreaded for performance. The featureSnapped() signal will be emitted each time a feature - * is processed. This method is not safe to call from multiple threads concurrently. + * is processed. The snap tolerance is specified in the layer units for the reference layer. */ - QgsFeatureList snapFeatures( const QgsFeatureList& features ); + QgsFeatureList snapFeatures( const QgsFeatureList& features, double snapTolerance, SnapMode mode = PreferNodes ); signals: @@ -70,8 +77,14 @@ class ANALYSIS_EXPORT QgsGeometrySnapper : public QObject struct ProcessFeatureWrapper { QgsGeometrySnapper* instance; - explicit ProcessFeatureWrapper( QgsGeometrySnapper* _instance ) : instance( _instance ) {} - void operator()( QgsFeature& feature ) { return instance->processFeature( feature ); } + double snapTolerance; + SnapMode mode; + explicit ProcessFeatureWrapper( QgsGeometrySnapper* _instance, double snapTolerance, SnapMode mode ) + : instance( _instance ) + , snapTolerance( snapTolerance ) + , mode( mode ) + {} + void operator()( QgsFeature& feature ) { return instance->processFeature( feature, snapTolerance, mode ); } }; enum PointFlag { SnappedToRefNode, SnappedToRefSegment, Unsnapped }; @@ -79,13 +92,11 @@ class ANALYSIS_EXPORT QgsGeometrySnapper : public QObject QgsVectorLayer* mReferenceLayer; QgsFeatureList mInputFeatures; - double mSnapTolerance; - QgsSpatialIndex mIndex; mutable QMutex mIndexMutex; mutable QMutex mReferenceLayerMutex; - void processFeature( QgsFeature& feature ); + void processFeature( QgsFeature& feature, double snapTolerance, SnapMode mode ); int polyLineSize( const QgsAbstractGeometry* geom, int iPart, int iRing ) const; }; diff --git a/tests/src/analysis/testqgsgeometrysnapper.cpp b/tests/src/analysis/testqgsgeometrysnapper.cpp index 2d040405d2bc..ffb59f70d0c4 100644 --- a/tests/src/analysis/testqgsgeometrysnapper.cpp +++ b/tests/src/analysis/testqgsgeometrysnapper.cpp @@ -43,6 +43,7 @@ class TestQgsGeometrySnapper : public QObject void snapLineToPoint(); void snapPointToPoint(); void snapPointToLine(); + void snapPointToLinePreferNearest(); void snapPointToPolygon(); }; @@ -79,22 +80,22 @@ void TestQgsGeometrySnapper::snapPolygonToPolygon() rl->dataProvider()->addFeatures( flist ); QgsGeometry polygonGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1))" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( polygonGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( polygonGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); QgsGeometry polygonGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom2 ); + result = snapper.snapGeometry( polygonGeom2, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 0 10, 0 0))" ) ); // insert new vertex QgsGeometry polygonGeom3 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom3 ); + result = snapper.snapGeometry( polygonGeom3, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0))" ) ); // remove vertex QgsGeometry polygonGeom4 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom4 ); + result = snapper.snapGeometry( polygonGeom4, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); } @@ -111,42 +112,42 @@ void TestQgsGeometrySnapper::snapLineToLine() rl->dataProvider()->addFeatures( flist ); QgsGeometry lineGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1)" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( lineGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( lineGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); QgsGeometry lineGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1)" ) ); - result = snapper.snapGeometry( lineGeom2 ); + result = snapper.snapGeometry( lineGeom2, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10, 0 0)" ) ); // insert new vertex QgsGeometry lineGeom3 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1)" ) ); - result = snapper.snapGeometry( lineGeom3 ); + result = snapper.snapGeometry( lineGeom3, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0)" ) ); // remove vertex QgsGeometry lineGeom4 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1)" ) ); - result = snapper.snapGeometry( lineGeom4 ); + result = snapper.snapGeometry( lineGeom4, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); // unclosed linestrings QgsGeometry lineGeom5 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom5 ); + result = snapper.snapGeometry( lineGeom5, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); QgsGeometry lineGeom6 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom6 ); + result = snapper.snapGeometry( lineGeom6, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10)" ) ); // insert new vertex QgsGeometry lineGeom7 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9)" ) ); - result = snapper.snapGeometry( lineGeom7 ); + result = snapper.snapGeometry( lineGeom7, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10)" ) ); // remove vertex QgsGeometry lineGeom8 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom8 ); + result = snapper.snapGeometry( lineGeom8, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); } @@ -163,42 +164,42 @@ void TestQgsGeometrySnapper::snapLineToPolygon() rl->dataProvider()->addFeatures( flist ); QgsGeometry lineGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1)" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( lineGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( lineGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); QgsGeometry lineGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1)" ) ); - result = snapper.snapGeometry( lineGeom2 ); + result = snapper.snapGeometry( lineGeom2, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10, 0 0)" ) ); // insert new vertex QgsGeometry lineGeom3 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1)" ) ); - result = snapper.snapGeometry( lineGeom3 ); + result = snapper.snapGeometry( lineGeom3, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0)" ) ); // remove vertex QgsGeometry lineGeom4 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1)" ) ); - result = snapper.snapGeometry( lineGeom4 ); + result = snapper.snapGeometry( lineGeom4 , 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10, 0 0)" ) ); // unclosed linestrings QgsGeometry lineGeom5 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom5 ); + result = snapper.snapGeometry( lineGeom5, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); QgsGeometry lineGeom6 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom6 ); + result = snapper.snapGeometry( lineGeom6, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10)" ) ); // insert new vertex QgsGeometry lineGeom7 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.5 0.5, 20 10, 0 9.9)" ) ); - result = snapper.snapGeometry( lineGeom7 ); + result = snapper.snapGeometry( lineGeom7, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10)" ) ); // remove vertex QgsGeometry lineGeom8 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom8 ); + result = snapper.snapGeometry( lineGeom8, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); } @@ -217,17 +218,17 @@ void TestQgsGeometrySnapper::snapLineToPoint() rl->dataProvider()->addFeatures( flist ); QgsGeometry lineGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 10 10, 0 10)" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( lineGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( lineGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 10 10, 0 10)" ) ); QgsGeometry lineGeom2 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 10.1 0, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom2 ); + result = snapper.snapGeometry( lineGeom2, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 0 10)" ) ); // insert new vertex QgsGeometry lineGeom3 = QgsGeometry::fromWkt( QStringLiteral( "LineString(0.1 -0.1, 20.0 0.0, 20 10, 0 10)" ) ); - result = snapper.snapGeometry( lineGeom3 ); + result = snapper.snapGeometry( lineGeom3, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "LineString (0 0, 10 0, 20 0, 20 10, 0 10)" ) ); } @@ -250,42 +251,42 @@ void TestQgsGeometrySnapper::snapPolygonToLine() // snapping to closed linestring QgsGeometry polygonGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 0 10, 0.1 -0.1))" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( polygonGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( polygonGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); QgsGeometry polygonGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom2 ); + result = snapper.snapGeometry( polygonGeom2, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 0 10, 0 0))" ) ); // insert new vertex QgsGeometry polygonGeom3 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 20.5 0.5, 20 10, 0 9.9, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom3 ); + result = snapper.snapGeometry( polygonGeom3, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 20.5 0.5, 20 10, 10 10, 0 10, 0 0))" ) ); // remove vertex QgsGeometry polygonGeom4 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 9.9 10.1, 5 10, 0 10, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom4 ); + result = snapper.snapGeometry( polygonGeom4, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); // snapping to unclosed linestring QgsGeometry polygonGeom5 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 110.1 0, 109.9 10.1, 100 10, 100.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom5 ); + result = snapper.snapGeometry( polygonGeom5, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 110 10, 100 10, 100 0))" ) ); QgsGeometry polygonGeom6 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 110.1 0, 100 10, 100.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom6 ); + result = snapper.snapGeometry( polygonGeom6, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 100 10, 100 0))" ) ); // insert new vertex QgsGeometry polygonGeom7 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 120.5 0.5, 120 10, 100 9.9, 100.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom7 ); + result = snapper.snapGeometry( polygonGeom7, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 120.5 0.5, 120 10, 110 10, 100 10, 100 0))" ) ); // remove vertex QgsGeometry polygonGeom8 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((100.1 -0.1, 110.1 0, 109.9 10.1, 105 10, 100 10, 100.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom8 ); + result = snapper.snapGeometry( polygonGeom8, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((100 0, 110 0, 110 10, 100 10, 100 0))" ) ); } @@ -304,17 +305,17 @@ void TestQgsGeometrySnapper::snapPolygonToPoint() rl->dataProvider()->addFeatures( flist ); QgsGeometry polygonGeom = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 10 10, 0 10, 0.1 -0.1))" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( polygonGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( polygonGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 10 10, 0 10, 0 0))" ) ); QgsGeometry polygonGeom2 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 10.1 0, 0 10, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom2 ); + result = snapper.snapGeometry( polygonGeom2, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 0 10, 0 0))" ) ); // insert new vertex QgsGeometry polygonGeom3 = QgsGeometry::fromWkt( QStringLiteral( "Polygon((0.1 -0.1, 20.0 0.0, 20 10, 0 10, 0.1 -0.1))" ) ); - result = snapper.snapGeometry( polygonGeom3 ); + result = snapper.snapGeometry( polygonGeom3, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Polygon ((0 0, 10 0, 20 0, 20 10, 0 10, 0 0))" ) ); } @@ -333,12 +334,12 @@ void TestQgsGeometrySnapper::snapPointToPoint() rl->dataProvider()->addFeatures( flist ); QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.1 -0.1)" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( pointGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( pointGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.6 -0.1)" ) ); - result = snapper.snapGeometry( pointGeom ); + result = snapper.snapGeometry( pointGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (1 0)" ) ); } @@ -355,13 +356,35 @@ void TestQgsGeometrySnapper::snapPointToLine() rl->dataProvider()->addFeatures( flist ); QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.1 -0.1)" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( pointGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( pointGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(10.6 -0.1)" ) ); - result = snapper.snapGeometry( pointGeom ); + result = snapper.snapGeometry( pointGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (10 0)" ) ); + + pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.5 0.5)" ) ); + result = snapper.snapGeometry( pointGeom, 1 ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); +} + +void TestQgsGeometrySnapper::snapPointToLinePreferNearest() +{ + QgsVectorLayer* rl = new QgsVectorLayer( QStringLiteral( "Linestring" ), QStringLiteral( "x" ), QStringLiteral( "memory" ) ); + + // closed linestring + QgsGeometry refGeom = QgsGeometry::fromWkt( QStringLiteral( "LineString(0 0, 10 0, 10 10, 0 10, 0 0)" ) ); + QgsFeature ff( 0 ); + ff.setGeometry( refGeom ); + QgsFeatureList flist; + flist << ff; + rl->dataProvider()->addFeatures( flist ); + + QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.5 0.5)" ) ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( pointGeom, 1, QgsGeometrySnapper::PreferClosest ); + QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0.5 0)" ) ); } void TestQgsGeometrySnapper::snapPointToPolygon() @@ -377,12 +400,12 @@ void TestQgsGeometrySnapper::snapPointToPolygon() rl->dataProvider()->addFeatures( flist ); QgsGeometry pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(0.1 -0.1)" ) ); - QgsGeometrySnapper snapper( rl, 1 ); - QgsGeometry result = snapper.snapGeometry( pointGeom ); + QgsGeometrySnapper snapper( rl ); + QgsGeometry result = snapper.snapGeometry( pointGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (0 0)" ) ); pointGeom = QgsGeometry::fromWkt( QStringLiteral( "Point(10.6 -0.1)" ) ); - result = snapper.snapGeometry( pointGeom ); + result = snapper.snapGeometry( pointGeom, 1 ); QCOMPARE( result.exportToWkt(), QStringLiteral( "Point (10 0)" ) ); } From 9b667d1e8a0759a8f4d807cae98e7e4224dbf5ac Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 09:53:03 +1000 Subject: [PATCH 645/897] [FEATURE] Remove c++ geometry snapper plugin All functionality is now available through analysis lib + processing algorithm. Marked as feature for documentation + changelog flagging --- debian/qgis.install | 1 - ms-windows/osgeo4w/package.cmd | 1 - src/plugins/CMakeLists.txt | 1 - src/plugins/geometry_snapper/CMakeLists.txt | 66 --- .../icons/geometrysnapper.png | Bin 897 -> 0 bytes .../icons/geometrysnapper.svg | 257 ----------- src/plugins/geometry_snapper/pluginres.qrc | 5 - .../geometry_snapper/qgsgeometrysnapper.cpp | 263 ----------- .../geometry_snapper/qgsgeometrysnapper.h | 69 --- .../qgsgeometrysnapperdialog.cpp | 325 ------------- .../qgsgeometrysnapperdialog.h | 53 --- .../qgsgeometrysnapperplugin.cpp | 107 ----- .../qgsgeometrysnapperplugin.h | 49 -- src/plugins/geometry_snapper/qgssnapindex.cpp | 434 ------------------ src/plugins/geometry_snapper/qgssnapindex.h | 110 ----- .../ui/qgsgeometrysnapperdialog.ui | 299 ------------ 16 files changed, 2040 deletions(-) delete mode 100644 src/plugins/geometry_snapper/CMakeLists.txt delete mode 100644 src/plugins/geometry_snapper/icons/geometrysnapper.png delete mode 100644 src/plugins/geometry_snapper/icons/geometrysnapper.svg delete mode 100644 src/plugins/geometry_snapper/pluginres.qrc delete mode 100644 src/plugins/geometry_snapper/qgsgeometrysnapper.cpp delete mode 100644 src/plugins/geometry_snapper/qgsgeometrysnapper.h delete mode 100644 src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp delete mode 100644 src/plugins/geometry_snapper/qgsgeometrysnapperdialog.h delete mode 100644 src/plugins/geometry_snapper/qgsgeometrysnapperplugin.cpp delete mode 100644 src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h delete mode 100644 src/plugins/geometry_snapper/qgssnapindex.cpp delete mode 100644 src/plugins/geometry_snapper/qgssnapindex.h delete mode 100644 src/plugins/geometry_snapper/ui/qgsgeometrysnapperdialog.ui diff --git a/debian/qgis.install b/debian/qgis.install index 0dacd3cccec2..493df36c8d94 100644 --- a/debian/qgis.install +++ b/debian/qgis.install @@ -11,7 +11,6 @@ usr/lib/qgis/plugins/libroadgraphplugin.so usr/lib/qgis/plugins/libheatmapplugin.so usr/lib/qgis/plugins/libtopolplugin.so usr/lib/qgis/plugins/libgeometrycheckerplugin.so -usr/lib/qgis/plugins/libgeometrysnapperplugin.so usr/lib/qgis/qgis_help usr/share/pixmaps/ usr/share/applications/ diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index 835c506ee819..e49ce0a2b577 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -395,7 +395,6 @@ tar -C %OSGEO4W_ROOT% -cjf %ARCH%/release/qgis/%PACKAGENAME%/%PACKAGENAME%-%VERS "apps/%PACKAGENAME%/plugins/spatialqueryplugin.dll" ^ "apps/%PACKAGENAME%/plugins/topolplugin.dll" ^ "apps/%PACKAGENAME%/plugins/geometrycheckerplugin.dll" ^ - "apps/%PACKAGENAME%/plugins/geometrysnapperplugin.dll" ^ "apps/%PACKAGENAME%/qgis_help.exe" ^ "apps/%PACKAGENAME%/qtplugins/sqldrivers/qsqlspatialite.dll" ^ "apps/%PACKAGENAME%/qtplugins/designer/" ^ diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt index f61d1d9044a6..8b65054eafbc 100644 --- a/src/plugins/CMakeLists.txt +++ b/src/plugins/CMakeLists.txt @@ -19,7 +19,6 @@ ADD_SUBDIRECTORY(topology) ADD_SUBDIRECTORY(offline_editing) ADD_SUBDIRECTORY(heatmap) ADD_SUBDIRECTORY(geometry_checker) -ADD_SUBDIRECTORY(geometry_snapper) IF (GRASS_FOUND) ADD_SUBDIRECTORY(grass) diff --git a/src/plugins/geometry_snapper/CMakeLists.txt b/src/plugins/geometry_snapper/CMakeLists.txt deleted file mode 100644 index ad317cef5be7..000000000000 --- a/src/plugins/geometry_snapper/CMakeLists.txt +++ /dev/null @@ -1,66 +0,0 @@ - -######################################################## -# Files - -SET (geometrysnapper_SRCS - qgsgeometrysnapperplugin.cpp - qgsgeometrysnapperdialog.cpp - qgsgeometrysnapper.cpp - qgssnapindex.cpp -) - -SET (geometrysnapper_HDRS - qgsgeometrysnapperplugin.h - qgssnapindex.h -) - -SET (geometrysnapper_UIS - ui/qgsgeometrysnapperdialog.ui -) - -SET (geometrysnapper_MOC_HDRS - qgsgeometrysnapper.h - qgsgeometrysnapperdialog.h - qgsgeometrysnapperplugin.h -) - -SET (geometrysnapper_RCCS - pluginres.qrc -) - -######################################################## -# Build - -QT5_WRAP_UI (geometrysnapper_UIS_H ${geometrysnapper_UIS}) - -QT5_WRAP_CPP (geometrysnapper_MOC_SRCS ${geometrysnapper_MOC_HDRS}) - -QT5_ADD_RESOURCES(geometrysnapper_RCC_SRCS ${geometrysnapper_RCCS}) - -ADD_LIBRARY (geometrysnapperplugin MODULE ${geometrysnapper_HDRS} ${geometrysnapper_SRCS} ${geometrysnapper_MOC_SRCS} ${geometrysnapper_RCC_SRCS} ${geometrysnapper_UIS_H}) - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_BINARY_DIR} - ../../core - ../../core/geometry - ../../core/symbology-ng - ../../gui - .. -) -INCLUDE_DIRECTORIES(SYSTEM - ${GEOS_INCLUDE_DIR} - ${GDAL_INCLUDE_DIR} -) - -TARGET_LINK_LIBRARIES(geometrysnapperplugin - qgis_core - qgis_gui -) - -######################################################## -# Install - -INSTALL(TARGETS geometrysnapperplugin - RUNTIME DESTINATION ${QGIS_PLUGIN_DIR} - LIBRARY DESTINATION ${QGIS_PLUGIN_DIR}) - diff --git a/src/plugins/geometry_snapper/icons/geometrysnapper.png b/src/plugins/geometry_snapper/icons/geometrysnapper.png deleted file mode 100644 index 3dbfa83c0a71ac8dc9fc0237208ec78958d9fe84..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 897 zcmV-{1AhF8P)Kh7bc>tLBCZ$;&aJS2#6}uT zn&tJPN$0v{?c$9-aBj|dcz)-7&mZ`|OWl5296&8lR~#-tEBY0n9_JfZJ(qJao;!3G zJW=~Ncx05p{U8C57La>EthYE}_!@PegS-xM&qe_~2Y91hU|Ha!GA0dp;F?lrb1)5J z0oeoMxt)1UizEUnD)8nNi{+_aulIXrO^ws(bk>-r=`;+Z#xzZr+wI=m(9mGUFIfBU|`@Azu*57s2_n5;8l?O0W2kBlt>$J zKp+)tZT+*ly1L8_yH&wpaI3@Nc+Uja#3?l;s2xWb@O{Xck<|)bLYin~o*3t3uGW05>CCuT=IvH;fAQs@dg7drV_EUyoXm<+$ShQFct*{ShQm}W1 z&Qz&IHsCLS`uh4h!!RnzC!5VKDiBr%aO03y0XCbh)^4{~3|Ko?0_Y`xuInzF%~la0 zlgX3?tX5D}Rpr!my&}NU($e|>yWOrUwc#6jlhWz*9RXPYP17pcemE@vDjRpP}p#IDwWFb9~%04G@0Bc@TtHn0uEUHi{y#laPMg3LKxVo;MeZ% z?t^`Oeb0D2p3Qd(pPZb$7>~zC5{bkRAObsq7%*p&9xVZO<btmQQRlM28=y19`Hp`Us9 zci=j39{2&&MZoCl>UuvE3O(!d`L+NglgUgp8XcdWp56np74QMpVn@ya-+{{iqeW{a zZomWF2NZz3!*R^h*?D$*Q&a7hqeqS7SFgVC6)R_$1QMmde<88LPkv4NY - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - diff --git a/src/plugins/geometry_snapper/pluginres.qrc b/src/plugins/geometry_snapper/pluginres.qrc deleted file mode 100644 index 0617d2670787..000000000000 --- a/src/plugins/geometry_snapper/pluginres.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - icons/geometrysnapper.png - - diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp b/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp deleted file mode 100644 index 35253c293144..000000000000 --- a/src/plugins/geometry_snapper/qgsgeometrysnapper.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/*************************************************************************** - * qgsgeometrysnapper.cpp * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include -#include - -#include "qgsfeatureiterator.h" -#include "qgsgeometry.h" -#include "qgsvectorlayer.h" -#include "qgsgeometrysnapper.h" -#include "qgsvectordataprovider.h" -#include "qgsgeometryutils.h" -#include "qgssnapindex.h" -#include "qgsmapsettings.h" - -QgsGeometrySnapper::QgsGeometrySnapper( QgsVectorLayer *adjustLayer, QgsVectorLayer *referenceLayer, bool selectedOnly, double snapToleranceMapUnits, const QgsMapSettings *mapSettings ) - : mAdjustLayer( adjustLayer ) - , mReferenceLayer( referenceLayer ) - , mSnapToleranceMapUnits( snapToleranceMapUnits ) - , mMapSettings( mapSettings ) -{ - if ( selectedOnly ) - { - mFeatures = mAdjustLayer->selectedFeaturesIds(); - } - else - { - mFeatures = mAdjustLayer->allFeatureIds(); - } - - // Build spatial index - QgsFeature feature; - QgsFeatureRequest req; - req.setSubsetOfAttributes( QgsAttributeList() ); - mIndex = QgsSpatialIndex( mReferenceLayer->getFeatures( req ) ); -} - -QFuture QgsGeometrySnapper::processFeatures() -{ - emit progressRangeChanged( 0, mFeatures.size() ); - return QtConcurrent::map( mFeatures, ProcessFeatureWrapper( this ) ); -} - -void QgsGeometrySnapper::processFeature( QgsFeatureId id ) -{ - emit progressStep(); - // Get current feature - QgsFeature feature; - if ( !getFeature( mAdjustLayer, mAdjustLayerMutex, id, feature ) ) - { - mErrorMutex.lock(); - mErrors.append( tr( "Failed to read feature %1 of input layer." ).arg( id ) ); - mErrorMutex.unlock(); - return; - } - QgsPointV2 center = QgsPointV2( feature.geometry().geometry()->boundingBox().center() ); - - // Compute snap tolerance - double layerToMapUnits = mMapSettings->layerToMapUnits( mAdjustLayer, feature.geometry().boundingBox() ); - double snapTolerance = mSnapToleranceMapUnits / layerToMapUnits; - - - // Get potential reference features and construct snap index - QList refGeometries; - mIndexMutex.lock(); - QList refFeatureIds = mIndex.intersects( feature.geometry().boundingBox() ); - mIndexMutex.unlock(); - Q_FOREACH ( QgsFeatureId refId, refFeatureIds ) - { - QgsFeature refFeature; - if ( getFeature( mReferenceLayer, mReferenceLayerMutex, refId, refFeature ) ) - { - refGeometries.append( refFeature.geometry().geometry()->clone() ); - } - else - { - mErrorMutex.lock(); - mErrors.append( tr( "Failed to read feature %1 of input layer." ).arg( refId ) ); - mErrorMutex.unlock(); - } - } - QgsSnapIndex refSnapIndex( center, 10 * snapTolerance ); - Q_FOREACH ( const QgsAbstractGeometry* geom, refGeometries ) - { - refSnapIndex.addGeometry( geom ); - } - - // Snap geometries - QgsGeometry featureGeom = feature.geometry(); - QgsAbstractGeometry* subjGeom = featureGeom.geometry(); - QList < QList< QList > > subjPointFlags; - - // Pass 1: snap vertices of subject geometry to reference vertices - for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart ) - { - subjPointFlags.append( QList< QList >() ); - - for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing ) - { - subjPointFlags[iPart].append( QList() ); - - for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert ) - { - - QgsSnapIndex::PointSnapItem* snapPoint = nullptr; - QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; - QgsVertexId vidx( iPart, iRing, iVert ); - QgsPointV2 p = subjGeom->vertexAt( vidx ); - if ( !refSnapIndex.getSnapItem( p, snapTolerance, &snapPoint, &snapSegment ) ) - { - subjPointFlags[iPart][iRing].append( Unsnapped ); - } - else - { - // Prefer snapping to point - if ( snapPoint ) - { - subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) ); - subjPointFlags[iPart][iRing].append( SnappedToRefNode ); - } - else if ( snapSegment ) - { - subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) ); - subjPointFlags[iPart][iRing].append( SnappedToRefSegment ); - } - } - } - } - } - - // SnapIndex for subject feature - QgsSnapIndex* subjSnapIndex = new QgsSnapIndex( center, 10 * snapTolerance ); - subjSnapIndex->addGeometry( subjGeom ); - - QgsAbstractGeometry* origSubjGeom = subjGeom->clone(); - QgsSnapIndex* origSubjSnapIndex = new QgsSnapIndex( center, 10 * snapTolerance ); - origSubjSnapIndex->addGeometry( origSubjGeom ); - - // Pass 2: add missing vertices to subject geometry - Q_FOREACH ( const QgsAbstractGeometry* refGeom, refGeometries ) - { - for ( int iPart = 0, nParts = refGeom->partCount(); iPart < nParts; ++iPart ) - { - for ( int iRing = 0, nRings = refGeom->ringCount( iPart ); iRing < nRings; ++iRing ) - { - for ( int iVert = 0, nVerts = polyLineSize( refGeom, iPart, iRing ); iVert < nVerts; ++iVert ) - { - - QgsSnapIndex::PointSnapItem* snapPoint = nullptr; - QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; - QgsPointV2 point = refGeom->vertexAt( QgsVertexId( iPart, iRing, iVert ) ); - if ( subjSnapIndex->getSnapItem( point, snapTolerance, &snapPoint, &snapSegment ) ) - { - // Snap to segment, unless a subject point was already snapped to the reference point - if ( snapPoint && QgsGeometryUtils::sqrDistance2D( snapPoint->getSnapPoint( point ), point ) < 1E-16 ) - { - continue; - } - else if ( snapSegment ) - { - // Look if there is a closer reference segment, if so, ignore this point - QgsPointV2 pProj = snapSegment->getSnapPoint( point ); - QgsPointV2 closest = refSnapIndex.getClosestSnapToPoint( point, pProj ); - if ( QgsGeometryUtils::sqrDistance2D( pProj, point ) > QgsGeometryUtils::sqrDistance2D( pProj, closest ) ) - { - continue; - } - - // If we are too far away from the original geometry, do nothing - if ( !origSubjSnapIndex->getSnapItem( point, snapTolerance ) ) - { - continue; - } - - const QgsSnapIndex::CoordIdx* idx = snapSegment->idxFrom; - subjGeom->insertVertex( QgsVertexId( idx->vidx.part, idx->vidx.ring, idx->vidx.vertex + 1 ), point ); - subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode ); - delete subjSnapIndex; - subjSnapIndex = new QgsSnapIndex( center, 10 * snapTolerance ); - subjSnapIndex->addGeometry( subjGeom ); - } - } - } - } - } - } - delete subjSnapIndex; - delete origSubjSnapIndex; - - // Pass 3: remove superfluous vertices: all vertices which are snapped to a segment and not preceded or succeeded by an unsnapped vertex - for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart ) - { - for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing ) - { - bool ringIsClosed = subjGeom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ) == subjGeom->vertexAt( QgsVertexId( iPart, iRing, subjGeom->vertexCount( iPart, iRing ) - 1 ) ); - for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert ) - { - int iPrev = ( iVert - 1 + nVerts ) % nVerts; - int iNext = ( iVert + 1 ) % nVerts; - QgsPointV2 pMid = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iVert ) ); - QgsPointV2 pPrev = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iPrev ) ); - QgsPointV2 pNext = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iNext ) ); - - if ( subjPointFlags[iPart][iRing][iVert] == SnappedToRefSegment && - subjPointFlags[iPart][iRing][iPrev] != Unsnapped && - subjPointFlags[iPart][iRing][iNext] != Unsnapped && - QgsGeometryUtils::sqrDistance2D( QgsGeometryUtils::projPointOnSegment( pMid, pPrev, pNext ), pMid ) < 1E-12 ) - { - if (( ringIsClosed && nVerts > 3 ) || ( !ringIsClosed && nVerts > 2 ) ) - { - subjGeom->deleteVertex( QgsVertexId( iPart, iRing, iVert ) ); - subjPointFlags[iPart][iRing].removeAt( iVert ); - iVert -= 1; - nVerts -= 1; - } - else - { - // Don't delete vertices if this would result in a degenerate geometry - break; - } - } - } - } - } - - feature.setGeometry( QgsGeometry( featureGeom.geometry()->clone() ) ); // force refresh - QgsGeometryMap geometryMap; - geometryMap.insert( id, feature.geometry() ); - qDeleteAll( refGeometries ); - mAdjustLayerMutex.lock(); - mAdjustLayer->dataProvider()->changeGeometryValues( geometryMap ); - mAdjustLayerMutex.unlock(); -} - -bool QgsGeometrySnapper::getFeature( QgsVectorLayer *layer, QMutex &mutex, QgsFeatureId id, QgsFeature &feature ) -{ - QMutexLocker locker( &mutex ); - QgsFeatureRequest req( id ); - req.setSubsetOfAttributes( QgsAttributeList() ); - return layer->getFeatures( req ).nextFeature( feature ); -} - - -int QgsGeometrySnapper::polyLineSize( const QgsAbstractGeometry* geom, int iPart, int iRing ) const -{ - int nVerts = geom->vertexCount( iPart, iRing ); - QgsPointV2 front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ); - QgsPointV2 back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) ); - return back == front ? nVerts - 1 : nVerts; -} diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapper.h b/src/plugins/geometry_snapper/qgsgeometrysnapper.h deleted file mode 100644 index 7b11882694b4..000000000000 --- a/src/plugins/geometry_snapper/qgsgeometrysnapper.h +++ /dev/null @@ -1,69 +0,0 @@ -/*************************************************************************** - * qgsgeometrysnapper.h * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGS_GEOMETRY_SNAPPER_H -#define QGS_GEOMETRY_SNAPPER_H - -#include -#include -#include -#include "qgsspatialindex.h" - -class QgsMapSettings; -class QgsVectorLayer; -class QgsAbstractGeometry; - -class QgsGeometrySnapper : public QObject -{ - Q_OBJECT - - public: - QgsGeometrySnapper( QgsVectorLayer* adjustLayer, QgsVectorLayer* referenceLayer, bool selectedOnly, double snapToleranceMapUnits, const QgsMapSettings* mapSettings ); - QFuture processFeatures(); - const QStringList& getErrors() const { return mErrors; } - - signals: - void progressRangeChanged( int min, int max ); - void progressStep(); - - private: - struct ProcessFeatureWrapper - { - QgsGeometrySnapper* instance; - explicit ProcessFeatureWrapper( QgsGeometrySnapper* _instance ) : instance( _instance ) {} - void operator()( QgsFeatureId id ) { instance->processFeature( id ); } - }; - - enum PointFlag { SnappedToRefNode, SnappedToRefSegment, Unsnapped }; - - QgsVectorLayer* mAdjustLayer; - QgsVectorLayer* mReferenceLayer; - double mSnapToleranceMapUnits; - const QgsMapSettings* mMapSettings; - QgsFeatureIds mFeatures; - QgsSpatialIndex mIndex; - QStringList mErrors; - QMutex mErrorMutex; - QMutex mIndexMutex; - QMutex mAdjustLayerMutex; - QMutex mReferenceLayerMutex; - - void processFeature( QgsFeatureId id ); - bool getFeature( QgsVectorLayer* layer, QMutex& mutex, QgsFeatureId id, QgsFeature& feature ); - int polyLineSize( const QgsAbstractGeometry* geom, int iPart, int iRing ) const; -}; - -#endif // QGS_GEOMETRY_SNAPPER_H diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp b/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp deleted file mode 100644 index 18b5ebad12a3..000000000000 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/*************************************************************************** - * qgsgeometrysnapperdialog.cpp * - * ------------------- * - * begin : Jun 10, 2014 * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgsgeometrysnapperdialog.h" -#include "qgsgeometrysnapper.h" - -#include "qgsfeatureiterator.h" -#include "qgisinterface.h" -#include "qgsmaplayerregistry.h" -#include "qgsvectorlayer.h" -#include "qgsmapcanvas.h" -#include "qgsvectorfilewriter.h" -#include "qgsvectordataprovider.h" -#include "qgsspatialindex.h" - -#include -#include -#include -#include -#include -#include -#include - - -QgsGeometrySnapperDialog::QgsGeometrySnapperDialog( QgisInterface* iface ): - mIface( iface ) -{ - setupUi( this ); - mRunButton = buttonBox->addButton( tr( "Run" ), QDialogButtonBox::ActionRole ); - buttonBox->button( QDialogButtonBox::Abort )->hide(); - mRunButton->setEnabled( false ); - progressBar->hide(); - setFixedSize( sizeHint() ); - setWindowModality( Qt::ApplicationModal ); - - connect( mRunButton, SIGNAL( clicked() ), this, SLOT( run() ) ); - connect( comboBoxInputLayer, SIGNAL( currentIndexChanged( int ) ), this, SLOT( validateInput() ) ); - connect( comboBoxReferenceLayer, SIGNAL( currentIndexChanged( int ) ), this, SLOT( validateInput() ) ); - connect( QgsMapLayerRegistry::instance(), SIGNAL( layersAdded( QList ) ), this, SLOT( updateLayers() ) ); - connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( updateLayers() ) ); - connect( radioButtonOutputNew, SIGNAL( toggled( bool ) ), lineEditOutput, SLOT( setEnabled( bool ) ) ); - connect( radioButtonOutputNew, SIGNAL( toggled( bool ) ), pushButtonOutputBrowse, SLOT( setEnabled( bool ) ) ); - connect( buttonGroupOutput, SIGNAL( buttonClicked( int ) ), this, SLOT( validateInput() ) ); - connect( pushButtonOutputBrowse, SIGNAL( clicked() ), this, SLOT( selectOutputFile() ) ); - connect( lineEditOutput, SIGNAL( textChanged( QString ) ), this, SLOT( validateInput() ) ); - - updateLayers(); -} - -void QgsGeometrySnapperDialog::updateLayers() -{ - QString curInput = comboBoxInputLayer->currentText(); - QString curReference = comboBoxReferenceLayer->currentText(); - - comboBoxInputLayer->clear(); - comboBoxReferenceLayer->clear(); - - // Collect layers - // Don't switch current layer if dialog is visible to avoid confusing the user - QgsMapLayer* currentLayer = isVisible() ? 0 : mIface->mapCanvas()->currentLayer(); - int curInputIdx = -1; - int curReferenceIdx = -1; - int idx = 0; - Q_FOREACH ( QgsMapLayer* layer, QgsMapLayerRegistry::instance()->mapLayers() ) - { - if ( qobject_cast( layer ) ) - { - QgsWkbTypes::Type type = QgsWkbTypes::flatType( QgsWkbTypes::singleType( static_cast( layer )->wkbType() ) ); - if ( type == QgsWkbTypes::Polygon || type == QgsWkbTypes::LineString ) - { - comboBoxInputLayer->addItem( layer->name(), layer->id() ); - comboBoxReferenceLayer->addItem( layer->name(), layer->id() ); - if ( layer->name() == curInput ) - { - curInputIdx = idx; - } - else if ( curInputIdx == -1 && layer == currentLayer ) - { - curInputIdx = idx; - } - - if ( layer->name() == curReference ) - { - curReferenceIdx = idx; - } - ++idx; - } - } - } - if ( curInputIdx == -1 ) - { - curInputIdx = 0; - } - if ( curReferenceIdx == -1 ) - { - curReferenceIdx = curInputIdx + 1 >= comboBoxReferenceLayer->count() ? curInputIdx - 1 : curInputIdx + 1; - } - comboBoxInputLayer->setCurrentIndex( curInputIdx ); - comboBoxReferenceLayer->setCurrentIndex( curReferenceIdx ); -} - -QgsVectorLayer* QgsGeometrySnapperDialog::getInputLayer() -{ - int idx = comboBoxInputLayer->currentIndex(); - if ( idx < 0 ) - return nullptr; - - QString inputLayerId = comboBoxInputLayer->itemData( idx ).toString(); - return static_cast( QgsMapLayerRegistry::instance()->mapLayer( inputLayerId ) ); -} - -QgsVectorLayer* QgsGeometrySnapperDialog::getReferenceLayer() -{ - int idx = comboBoxReferenceLayer->currentIndex(); - if ( idx < 0 ) - return nullptr; - - QString inputLayerId = comboBoxReferenceLayer->itemData( idx ).toString(); - return static_cast( QgsMapLayerRegistry::instance()->mapLayer( inputLayerId ) ); -} - -void QgsGeometrySnapperDialog::validateInput() -{ - QgsVectorLayer* inLayer = getInputLayer(); - QgsVectorLayer* refLayer = getReferenceLayer(); - bool outputOk = radioButtonOuputModifyInput->isChecked() || !lineEditOutput->text().isEmpty(); - mRunButton->setEnabled( inLayer && refLayer && inLayer != refLayer && - refLayer->geometryType() == inLayer->geometryType() && outputOk ); -} - -void QgsGeometrySnapperDialog::selectOutputFile() -{ - QString filterString = QgsVectorFileWriter::filterForDriver( QStringLiteral( "ESRI Shapefile" ) ); - QMap filterFormatMap = QgsVectorFileWriter::supportedFiltersAndFormats(); - Q_FOREACH ( const QString& filter, filterFormatMap.keys() ) - { - QString driverName = filterFormatMap.value( filter ); - if ( driverName != QLatin1String( "ESRI Shapefile" ) ) // Default entry, first in list (see above) - { - filterString += ";;" + filter; - } - } - QString initialdir; - QgsVectorLayer* layer = getInputLayer(); - if ( layer ) - { - QDir dir = QFileInfo( layer->dataProvider()->dataSourceUri() ).dir(); - if ( dir.exists() ) - { - initialdir = dir.absolutePath(); - } - } - QString selectedFilter; - QString filename = QFileDialog::getSaveFileName( this, tr( "Select Output File" ), initialdir, filterString, &selectedFilter ); - if ( !filename.isEmpty() ) - { - mOutputDriverName = filterFormatMap.value( selectedFilter ); - QgsVectorFileWriter::MetaData mdata; - if ( QgsVectorFileWriter::driverMetadata( mOutputDriverName, mdata ) ) - { - if ( !filename.endsWith( QStringLiteral( ".%1" ).arg( mdata.ext ), Qt::CaseInsensitive ) ) - { - filename += QStringLiteral( ".%1" ).arg( mdata.ext ); - } - } - lineEditOutput->setText( filename ); - } -} - -void QgsGeometrySnapperDialog::run() -{ - //! Get layers * - QgsVectorLayer* layer = getInputLayer(); - QgsVectorLayer* referenceLayer = getReferenceLayer(); - if ( !layer || !referenceLayer ) - { - return; - } - - if ( radioButtonOutputNew->isChecked() && - ( layer->dataProvider()->dataSourceUri().startsWith( lineEditOutput->text() ) || - referenceLayer->dataProvider()->dataSourceUri().startsWith( lineEditOutput->text() ) ) ) - { - QMessageBox::critical( this, tr( "Invalid Output Layer" ), tr( "The chosen output layer is the same as an input layer." ) ); - return; - } - - bool selectedOnly = checkBoxInputSelectedOnly->isChecked(); - - //! Duplicate if necessary * - if ( radioButtonOutputNew->isChecked() ) - { - QString filename = lineEditOutput->text(); - - // Remove existing layer with same uri - QStringList toRemove; - Q_FOREACH ( QgsMapLayer* maplayer, QgsMapLayerRegistry::instance()->mapLayers() ) - { - if ( dynamic_cast( maplayer ) && - static_cast( maplayer )->dataProvider()->dataSourceUri().startsWith( filename ) ) - { - toRemove.append( maplayer->id() ); - } - } - if ( !toRemove.isEmpty() ) - { - QgsMapLayerRegistry::instance()->removeMapLayers( toRemove ); - } - - QString errMsg; - QgsVectorFileWriter::WriterError err = QgsVectorFileWriter::writeAsVectorFormat( layer, filename, layer->dataProvider()->encoding(), layer->crs(), mOutputDriverName, selectedOnly, &errMsg ); - if ( err != QgsVectorFileWriter::NoError ) - { - QMessageBox::critical( this, tr( "Layer Creation Failed" ), tr( "Failed to create the output layer: %1" ).arg( errMsg ) ); - return; - } - QgsVectorLayer* newlayer = new QgsVectorLayer( filename, QFileInfo( filename ).completeBaseName(), QStringLiteral( "ogr" ) ); - - if ( selectedOnly ) - { - QgsFeature feature; - - // Get features to select (only selected features were written up to this point) - QgsFeatureIds selectedFeatures = newlayer->allFeatureIds(); - - // Write non-selected feature ids - QgsFeatureList features; - QgsFeatureIterator it = layer->getFeatures(); - while ( it.nextFeature( feature ) ) - { - if ( !layer->selectedFeaturesIds().contains( feature.id() ) ) - { - features.append( feature ); - } - } - newlayer->dataProvider()->addFeatures( features ); - - // Set selected features - newlayer->selectByIds( selectedFeatures ); - } - layer = newlayer; - } - if (( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 ) - { - QMessageBox::critical( this, tr( "Non-editable Output Format" ), tr( "The output file format does not support editing features. Please select another output file format." ) ); - if ( radioButtonOutputNew->isChecked() ) - { - QString outputFileName = lineEditOutput->text(); - QFile( outputFileName ).remove(); - if ( mOutputDriverName == QLatin1String( "ESRI Shapefile" ) ) - { - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "dbf" ) ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "prj" ) ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "qpj" ) ) ).remove(); - QFile( QString( outputFileName ).replace( QRegExp( "shp$" ), QStringLiteral( "shx" ) ) ).remove(); - } - return; - } - } - - layer->setReadOnly( true ); - if ( radioButtonOutputNew->isChecked() ) - { - QgsMapLayerRegistry::instance()->addMapLayers( QList() << layer ); - } - - //! Run * - QEventLoop evLoop; - QFutureWatcher futureWatcher; - connect( &futureWatcher, SIGNAL( finished() ), &evLoop, SLOT( quit() ) ); - connect( buttonBox->button( QDialogButtonBox::Abort ), SIGNAL( clicked() ), &futureWatcher, SLOT( cancel() ) ); - - setCursor( Qt::WaitCursor ); - buttonBox->button( QDialogButtonBox::Abort )->show(); - mRunButton->hide(); - progressBar->setRange( 0, 0 ); - progressBar->setValue( 0 ); - progressBar->show(); - widgetInputs->setEnabled( false ); - - QgsGeometrySnapper snapper( layer, referenceLayer, selectedOnly, doubleSpinBoxMaxDistance->value(), &mIface->mapCanvas()->mapSettings() ); - connect( &snapper, SIGNAL( progressRangeChanged( int, int ) ), progressBar, SLOT( setRange( int, int ) ) ); - connect( &snapper, SIGNAL( progressStep() ), this, SLOT( progressStep() ) ); - futureWatcher.setFuture( snapper.processFeatures() ); - evLoop.exec(); - - //! Restore window * - unsetCursor(); - buttonBox->button( QDialogButtonBox::Abort )->hide(); - mRunButton->show(); - progressBar->hide(); - widgetInputs->setEnabled( true ); - - layer->setReadOnly( false ); - - //! Trigger layer repaint * - layer->triggerRepaint(); - - //! Show errors * - if ( !snapper.getErrors().isEmpty() ) - { - QMessageBox::warning( this, tr( "Errors occurred" ), tr( "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  The following errors occurred:

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • %1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " ).arg( snapper.getErrors().join( QStringLiteral( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • " ) ) ) ); - } - hide() ; -} - -void QgsGeometrySnapperDialog::progressStep() -{ - progressBar->setValue( progressBar->value() + 1 ); -} - diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.h b/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.h deleted file mode 100644 index fdd33efc4e63..000000000000 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperdialog.h +++ /dev/null @@ -1,53 +0,0 @@ -/*************************************************************************** - * qgsgeometrysnapperdialog.h * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGS_GEOMETRY_SNAPPER_DIALOG_H -#define QGS_GEOMETRY_SNAPPER_DIALOG_H - -#include -#include - -#include "qgsfeature.h" -#include "ui_qgsgeometrysnapperdialog.h" - -class QgisInterface; -class QgsSpatialIndex; -class QgsVectorLayer; - -class QgsGeometrySnapperDialog: public QDialog, private Ui::QgsGeometrySnapperDialog -{ - Q_OBJECT - public: - explicit QgsGeometrySnapperDialog( QgisInterface * iface ); - - private: - QgisInterface* mIface; - QAbstractButton* mRunButton; - QString mOutputDriverName; - - QgsVectorLayer* getInputLayer(); - QgsVectorLayer* getReferenceLayer(); - - private slots: - void run(); - void updateLayers(); - void validateInput(); - void selectOutputFile(); - void progressStep(); -}; - -#endif // QGS_GEOMETRY_SNAPPER_DIALOG_H - diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.cpp b/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.cpp deleted file mode 100644 index 356e11f6df76..000000000000 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/*************************************************************************** - * qgsgeometrysnapperplugin.cpp * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgsgeometrysnapperplugin.h" -#include "qgisinterface.h" - -QgsGeometrySnapperPlugin::QgsGeometrySnapperPlugin( QgisInterface* iface ) - : QgisPlugin( sName, sDescription, sCategory, sPluginVersion, sPluginType ) - , mIface( iface ) - , mDialog( nullptr ) - , mMenuAction( nullptr ) -{ -} - -void QgsGeometrySnapperPlugin::initGui() -{ - mDialog = new QgsGeometrySnapperDialog( mIface ); - mMenuAction = new QAction( QIcon( ":/geometrysnapper/icons/geometrysnapper.png" ), QApplication::translate( "QgsGeometrySnapperPlugin", "Snap geometries" ), this ); - connect( mMenuAction, SIGNAL( triggered() ), mDialog, SLOT( show() ) ); - mIface->addPluginToVectorMenu( QApplication::translate( "QgsGeometrySnapperPlugin", "G&eometry Tools" ), mMenuAction ); -} - -void QgsGeometrySnapperPlugin::unload() -{ - delete mDialog; - mDialog = nullptr; - delete mMenuAction; - mMenuAction = nullptr; - mIface->removePluginVectorMenu( QApplication::translate( "QgsGeometrySnapperPlugin", "G&eometry Tools" ), mMenuAction ); -} - - -////////////////////////////////////////////////////////////////////////// -// -// -// THE FOLLOWING CODE IS AUTOGENERATED BY THE PLUGIN BUILDER SCRIPT -// YOU WOULD NORMALLY NOT NEED TO MODIFY THIS, AND YOUR PLUGIN -// MAY NOT WORK PROPERLY IF YOU MODIFY THIS INCORRECTLY -// -// -////////////////////////////////////////////////////////////////////////// - - -/** - * Required extern functions needed for every plugin - * These functions can be called prior to creating an instance - * of the plugin class - */ -// Class factory to return a new instance of the plugin class -QGISEXTERN QgisPlugin * classFactory( QgisInterface * theQgisInterfacePointer ) -{ - return new QgsGeometrySnapperPlugin( theQgisInterfacePointer ); -} -// Return the name of the plugin - note that we do not user class members as -// the class may not yet be insantiated when this method is called. -QGISEXTERN QString name() -{ - return sName; -} - -// Return the description -QGISEXTERN QString description() -{ - return sDescription; -} - -// Return the category -QGISEXTERN QString category() -{ - return sCategory; -} - -// Return the type (either UI or MapLayer plugin) -QGISEXTERN int type() -{ - return sPluginType; -} - -// Return the version number for the plugin -QGISEXTERN QString version() -{ - return sPluginVersion; -} - -QGISEXTERN QString icon() -{ - return sPluginIcon; -} - -// Delete ourself -QGISEXTERN void unload( QgisPlugin * thePluginPointer ) -{ - delete thePluginPointer; -} diff --git a/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h b/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h deleted file mode 100644 index 611747ee0648..000000000000 --- a/src/plugins/geometry_snapper/qgsgeometrysnapperplugin.h +++ /dev/null @@ -1,49 +0,0 @@ -/*************************************************************************** - * qgsgeometrysnapperplugin.h * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGS_GEOMETRY_SNAPPER_PLUGIN_H -#define QGS_GEOMETRY_SNAPPER_PLUGIN_H - -#include "qgis.h" -#include "qgisplugin.h" -#include "qgsgeometrysnapperdialog.h" - -class QgisInterface; - -static const QString sName = QApplication::translate( "QgsGeometrySnapperPlugin", "Geometry Snapper" ); -static const QString sDescription = QApplication::translate( "QgsGeometrySnapperPlugin", "Snap geometries to a reference layer" ); -static const QString sCategory = QApplication::translate( "QgsGeometrySnapperPlugin", "Vector" ); -static const QString sPluginVersion = QApplication::translate( "QgsGeometrySnapperPlugin", "Version 0.1" ); -static const QgisPlugin::PLUGINTYPE sPluginType = QgisPlugin::UI; -static const QString sPluginIcon = QStringLiteral( ":/geometrysnapper/icons/geometrysnapper.png" ); - - -class QgsGeometrySnapperPlugin : public QObject, public QgisPlugin -{ - Q_OBJECT - - public: - explicit QgsGeometrySnapperPlugin( QgisInterface* iface ); - void initGui() override; - void unload() override; - - private: - QgisInterface* mIface; - QgsGeometrySnapperDialog* mDialog; - QAction* mMenuAction; -}; - -#endif // QGS_GEOMETRY_SNAPPER_PLUGIN_H diff --git a/src/plugins/geometry_snapper/qgssnapindex.cpp b/src/plugins/geometry_snapper/qgssnapindex.cpp deleted file mode 100644 index c0519bcff1b1..000000000000 --- a/src/plugins/geometry_snapper/qgssnapindex.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/*************************************************************************** - * qgssnapindex.cpp * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgssnapindex.h" -#include "qgsgeometryutils.h" -#include -#include - -QgsSnapIndex::PointSnapItem::PointSnapItem( const QgsSnapIndex::CoordIdx* _idx ) - : SnapItem( QgsSnapIndex::SnapPoint ) - , idx( _idx ) -{} - -QgsPointV2 QgsSnapIndex::PointSnapItem::getSnapPoint( const QgsPointV2 &/*p*/ ) const -{ - return idx->point(); -} - -/////////////////////////////////////////////////////////////////////////////// - -QgsSnapIndex::SegmentSnapItem::SegmentSnapItem( const QgsSnapIndex::CoordIdx* _idxFrom, const QgsSnapIndex::CoordIdx* _idxTo ) - : SnapItem( QgsSnapIndex::SnapSegment ) - , idxFrom( _idxFrom ) - , idxTo( _idxTo ) -{} - -QgsPointV2 QgsSnapIndex::SegmentSnapItem::getSnapPoint( const QgsPointV2 &p ) const -{ - return QgsGeometryUtils::projPointOnSegment( p, idxFrom->point(), idxTo->point() ); -} - -bool QgsSnapIndex::SegmentSnapItem::getIntersection( const QgsPointV2 &p1, const QgsPointV2 &p2, QgsPointV2& inter ) const -{ - const QgsPointV2& q1 = idxFrom->point(), & q2 = idxTo->point(); - QgsVector v( p2.x() - p1.x(), p2.y() - p1.y() ); - QgsVector w( q2.x() - q1.x(), q2.y() - q1.y() ); - double vl = v.length(); - double wl = w.length(); - - if ( qFuzzyIsNull( vl ) || qFuzzyIsNull( wl ) ) - { - return false; - } - v = v / vl; - w = w / wl; - - double d = v.y() * w.x() - v.x() * w.y(); - - if ( d == 0 ) - return false; - - double dx = q1.x() - p1.x(); - double dy = q1.y() - p1.y(); - double k = ( dy * w.x() - dx * w.y() ) / d; - - inter = QgsPointV2( p1.x() + v.x() * k, p1.y() + v.y() * k ); - - double lambdav = QgsVector( inter.x() - p1.x(), inter.y() - p1.y() ) * v; - if ( lambdav < 0. + 1E-8 || lambdav > vl - 1E-8 ) - return false; - - double lambdaw = QgsVector( inter.x() - q1.x(), inter.y() - q1.y() ) * w; - if ( lambdaw < 0. + 1E-8 || lambdaw >= wl - 1E-8 ) - return false; - - return true; -} - -bool QgsSnapIndex::SegmentSnapItem::getProjection( const QgsPointV2 &p, QgsPointV2 &pProj ) -{ - const QgsPointV2& s1 = idxFrom->point(); - const QgsPointV2& s2 = idxTo->point(); - double nx = s2.y() - s1.y(); - double ny = -( s2.x() - s1.x() ); - double t = ( p.x() * ny - p.y() * nx - s1.x() * ny + s1.y() * nx ) / (( s2.x() - s1.x() ) * ny - ( s2.y() - s1.y() ) * nx ); - if ( t < 0. || t > 1. ) - { - return false; - } - pProj = QgsPointV2( s1.x() + ( s2.x() - s1.x() ) * t, s1.y() + ( s2.y() - s1.y() ) * t ); - return true; -} - -/////////////////////////////////////////////////////////////////////////////// - -class Raytracer -{ - // Raytrace on an integer, unit-width 2D grid with floating point coordinates - // See http://playtechs.blogspot.ch/2007/03/raytracing-on-grid.html - public: - Raytracer( float x0, float y0, float x1, float y1 ) - : m_dx( qAbs( x1 - x0 ) ) - , m_dy( qAbs( y1 - y0 ) ) - , m_x( qFloor( x0 ) ) - , m_y( qFloor( y0 ) ) - , m_n( 1 ) - { - if ( m_dx == 0. ) - { - m_xInc = 0.; - m_error = std::numeric_limits::infinity(); - } - else if ( x1 > x0 ) - { - m_xInc = 1; - m_n += int( qFloor( x1 ) ) - m_x; - m_error = ( qFloor( x0 ) + 1 - x0 ) * m_dy; - } - else - { - m_xInc = -1; - m_n += m_x - int( qFloor( x1 ) ); - m_error = ( x0 - qFloor( x0 ) ) * m_dy; - } - if ( m_dy == 0. ) - { - m_yInc = 0.; - m_error = -std::numeric_limits::infinity(); - } - else if ( y1 > y0 ) - { - m_yInc = 1; - m_n += int( qFloor( y1 ) ) - m_y; - m_error -= ( qFloor( y0 ) + 1 - y0 ) * m_dx; - } - else - { - m_yInc = -1; - m_n += m_y - int( qFloor( y1 ) ); - m_error -= ( y0 - qFloor( y0 ) ) * m_dx; - } - } - int curCol() const { return m_x; } - int curRow() const { return m_y; } - void next() - { - if ( m_error > 0 ) - { - m_y += m_yInc; - m_error -= m_dx; - } - else if ( m_error < 0 ) - { - m_x += m_xInc; - m_error += m_dy; - } - else - { - m_x += m_xInc; - m_y += m_yInc; - m_error += m_dx; - m_error -= m_dy; - --m_n; - } - --m_n; - } - - bool isValid() const { return m_n > 0; } - - private: - float m_dx, m_dy; - int m_x, m_y; - int m_xInc, m_yInc; - float m_error; - int m_n; -}; - -/////////////////////////////////////////////////////////////////////////////// - -QgsSnapIndex::GridRow::~GridRow() -{ - Q_FOREACH ( const QgsSnapIndex::Cell& cell, mCells ) - { - qDeleteAll( cell ); - } -} - -QgsSnapIndex::Cell& QgsSnapIndex::GridRow::getCreateCell( int col ) -{ - if ( col < mColStartIdx ) - { - for ( int i = col; i < mColStartIdx; ++i ) - { - mCells.prepend( Cell() ); - } - mColStartIdx = col; - return mCells.front(); - } - else if ( col >= mColStartIdx + mCells.size() ) - { - for ( int i = mColStartIdx + mCells.size(); i <= col; ++i ) - { - mCells.append( Cell() ); - } - return mCells.back(); - } - else - { - return mCells[col - mColStartIdx]; - } -} - -const QgsSnapIndex::Cell* QgsSnapIndex::GridRow::getCell( int col ) const -{ - if ( col < mColStartIdx || col >= mColStartIdx + mCells.size() ) - { - return nullptr; - } - else - { - return &mCells[col - mColStartIdx]; - } -} - -QList QgsSnapIndex::GridRow::getSnapItems( int colStart, int colEnd ) const -{ - colStart = qMax( colStart, mColStartIdx ); - colEnd = qMin( colEnd, mColStartIdx + mCells.size() - 1 ); - - QList items; - - for ( int col = colStart; col <= colEnd; ++col ) - { - items.append( mCells[col - mColStartIdx] ); - } - return items; -} - -/////////////////////////////////////////////////////////////////////////////// - -QgsSnapIndex::QgsSnapIndex( const QgsPointV2& origin, double cellSize ) - : mOrigin( origin ) - , mCellSize( cellSize ) - , mRowsStartIdx( 0 ) -{ -} - -QgsSnapIndex::~QgsSnapIndex() -{ - qDeleteAll( mCoordIdxs ); -} - - -const QgsSnapIndex::Cell *QgsSnapIndex::getCell( int col, int row ) const -{ - if ( row < mRowsStartIdx || row >= mRowsStartIdx + mGridRows.size() ) - { - return nullptr; - } - else - { - return mGridRows[row - mRowsStartIdx].getCell( col ); - } -} - -QgsSnapIndex::Cell& QgsSnapIndex::getCreateCell( int col, int row ) -{ - if ( row < mRowsStartIdx ) - { - for ( int i = row; i < mRowsStartIdx; ++i ) - { - mGridRows.prepend( GridRow() ); - } - mRowsStartIdx = row; - return mGridRows.front().getCreateCell( col ); - } - else if ( row >= mRowsStartIdx + mGridRows.size() ) - { - for ( int i = mRowsStartIdx + mGridRows.size(); i <= row; ++i ) - { - mGridRows.append( GridRow() ); - } - return mGridRows.back().getCreateCell( col ); - } - else - { - return mGridRows[row - mRowsStartIdx].getCreateCell( col ); - } -} - -void QgsSnapIndex::addPoint( const CoordIdx* idx ) -{ - QgsPointV2 p = idx->point(); - int col = qFloor(( p.x() - mOrigin.x() ) / mCellSize ); - int row = qFloor(( p.y() - mOrigin.y() ) / mCellSize ); - getCreateCell( col, row ).append( new PointSnapItem( idx ) ); -} - -void QgsSnapIndex::addSegment( const CoordIdx* idxFrom, const CoordIdx* idxTo ) -{ - QgsPointV2 pFrom = idxFrom->point(); - QgsPointV2 pTo = idxTo->point(); - // Raytrace along the grid, get touched cells - float x0 = ( pFrom.x() - mOrigin.x() ) / mCellSize; - float y0 = ( pFrom.y() - mOrigin.y() ) / mCellSize; - float x1 = ( pTo.x() - mOrigin.x() ) / mCellSize; - float y1 = ( pTo.y() - mOrigin.y() ) / mCellSize; - - Raytracer rt( x0, y0, x1, y1 ); - for ( ; rt.isValid(); rt.next() ) - { - getCreateCell( rt.curCol(), rt.curRow() ).append( new SegmentSnapItem( idxFrom, idxTo ) ); - } -} - -void QgsSnapIndex::addGeometry( const QgsAbstractGeometry* geom ) -{ - for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart ) - { - for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing ) - { - for ( int iVert = 0, nVerts = geom->vertexCount( iPart, iRing ) - 1; iVert < nVerts; ++iVert ) - { - CoordIdx* idx = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert ) ); - CoordIdx* idx1 = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert + 1 ) ); - mCoordIdxs.append( idx ); - mCoordIdxs.append( idx1 ); - addPoint( idx ); - addSegment( idx, idx1 ); - } - } - } -} - - -QgsPointV2 QgsSnapIndex::getClosestSnapToPoint( const QgsPointV2& p, const QgsPointV2& q ) -{ - // Look for intersections on segment from the target point to the point opposite to the point reference point - // p2 = p1 + 2 * (q - p1) - QgsPointV2 p2( 2 * q.x() - p.x(), 2 * q.y() - p.y() ); - - // Raytrace along the grid, get touched cells - float x0 = ( p.x() - mOrigin.x() ) / mCellSize; - float y0 = ( p.y() - mOrigin.y() ) / mCellSize; - float x1 = ( p2.x() - mOrigin.x() ) / mCellSize; - float y1 = ( p2.y() - mOrigin.y() ) / mCellSize; - - Raytracer rt( x0, y0, x1, y1 ); - double dMin = std::numeric_limits::max(); - QgsPointV2 pMin = p; - for ( ; rt.isValid(); rt.next() ) - { - const Cell* cell = getCell( rt.curCol(), rt.curRow() ); - if ( !cell ) - { - continue; - } - Q_FOREACH ( const SnapItem* item, *cell ) - { - if ( item->type == SnapSegment ) - { - QgsPointV2 inter; - if ( static_cast( item )->getIntersection( p, p2, inter ) ) - { - double dist = QgsGeometryUtils::sqrDistance2D( q, inter ); - if ( dist < dMin ) - { - dMin = dist; - pMin = inter; - } - } - } - } - } - - return pMin; -} - -QgsSnapIndex::SnapItem* QgsSnapIndex::getSnapItem( const QgsPointV2& pos, double tol, QgsSnapIndex::PointSnapItem** pSnapPoint, QgsSnapIndex::SegmentSnapItem** pSnapSegment ) const -{ - int colStart = qFloor(( pos.x() - tol - mOrigin.x() ) / mCellSize ); - int rowStart = qFloor(( pos.y() - tol - mOrigin.y() ) / mCellSize ); - int colEnd = qFloor(( pos.x() + tol - mOrigin.x() ) / mCellSize ); - int rowEnd = qFloor(( pos.y() + tol - mOrigin.y() ) / mCellSize ); - - rowStart = qMax( rowStart, mRowsStartIdx ); - rowEnd = qMin( rowEnd, mRowsStartIdx + mGridRows.size() - 1 ); - - QList items; - for ( int row = rowStart; row <= rowEnd; ++row ) - { - items.append( mGridRows[row - mRowsStartIdx].getSnapItems( colStart, colEnd ) ); - } - - double minDistSegment = std::numeric_limits::max(); - double minDistPoint = std::numeric_limits::max(); - QgsSnapIndex::SegmentSnapItem* snapSegment = nullptr; - QgsSnapIndex::PointSnapItem* snapPoint = nullptr; - - Q_FOREACH ( QgsSnapIndex::SnapItem* item, items ) - { - if ( item->type == SnapPoint ) - { - double dist = QgsGeometryUtils::sqrDistance2D( item->getSnapPoint( pos ), pos ); - if ( dist < minDistPoint ) - { - minDistPoint = dist; - snapPoint = static_cast( item ); - } - } - else if ( item->type == SnapSegment ) - { - QgsPointV2 pProj; - if ( !static_cast( item )->getProjection( pos, pProj ) ) - { - continue; - } - double dist = QgsGeometryUtils::sqrDistance2D( pProj, pos ); - if ( dist < minDistSegment ) - { - minDistSegment = dist; - snapSegment = static_cast( item ); - } - } - } - snapPoint = minDistPoint < tol * tol ? snapPoint : nullptr; - snapSegment = minDistSegment < tol * tol ? snapSegment : nullptr; - if ( pSnapPoint ) *pSnapPoint = snapPoint; - if ( pSnapSegment ) *pSnapSegment = snapSegment; - return minDistPoint < minDistSegment ? static_cast( snapPoint ) : static_cast( snapSegment ); -} diff --git a/src/plugins/geometry_snapper/qgssnapindex.h b/src/plugins/geometry_snapper/qgssnapindex.h deleted file mode 100644 index 3dd800c99cd6..000000000000 --- a/src/plugins/geometry_snapper/qgssnapindex.h +++ /dev/null @@ -1,110 +0,0 @@ -/*************************************************************************** - * qgssnapindex.h * - * ------------------- * - * copyright : (C) 2014 by Sandro Mani / Sourcepole AG * - * email : smani@sourcepole.ch * - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGSSNAPINDEX_H -#define QGSSNAPINDEX_H - -#include "qgspointv2.h" -#include "qgsabstractgeometry.h" - -class QgsSnapIndex -{ - public: - struct CoordIdx - { - CoordIdx( const QgsAbstractGeometry* _geom, QgsVertexId _vidx ) - : geom( _geom ) - , vidx( _vidx ) - {} - QgsPointV2 point() const { return geom->vertexAt( vidx ); } - - const QgsAbstractGeometry* geom; - QgsVertexId vidx; - }; - - enum SnapType { SnapPoint, SnapSegment }; - - class SnapItem - { - public: - virtual ~SnapItem() {} - SnapType type; - virtual QgsPointV2 getSnapPoint( const QgsPointV2& p ) const = 0; - - protected: - explicit SnapItem( SnapType _type ) : type( _type ) {} - }; - - class PointSnapItem : public QgsSnapIndex::SnapItem - { - public: - explicit PointSnapItem( const CoordIdx* _idx ); - QgsPointV2 getSnapPoint( const QgsPointV2 &/*p*/ ) const override; - const CoordIdx* idx; - }; - - class SegmentSnapItem : public QgsSnapIndex::SnapItem - { - public: - SegmentSnapItem( const CoordIdx* _idxFrom, const CoordIdx* _idxTo ); - QgsPointV2 getSnapPoint( const QgsPointV2 &p ) const override; - bool getIntersection( const QgsPointV2& p1, const QgsPointV2& p2, QgsPointV2& inter ) const; - bool getProjection( const QgsPointV2 &p, QgsPointV2 &pProj ); - const CoordIdx* idxFrom; - const CoordIdx* idxTo; - }; - - QgsSnapIndex( const QgsPointV2& origin, double cellSize ); - ~QgsSnapIndex(); - void addGeometry( const QgsAbstractGeometry *geom ); - QgsPointV2 getClosestSnapToPoint( const QgsPointV2& p, const QgsPointV2& q ); - SnapItem *getSnapItem( const QgsPointV2& pos, double tol, PointSnapItem **pSnapPoint = nullptr, SegmentSnapItem **pSnapSegment = nullptr ) const; - - private: - typedef QList Cell; - typedef QPair Segment; - - class GridRow - { - public: - GridRow() : mColStartIdx( 0 ) {} - ~GridRow(); - const Cell *getCell( int col ) const; - Cell& getCreateCell( int col ); - QList getSnapItems( int colStart, int colEnd ) const; - - private: - QList mCells; - int mColStartIdx; - }; - - QgsPointV2 mOrigin; - double mCellSize; - - QList mCoordIdxs; - QList mGridRows; - int mRowsStartIdx; - - void addPoint( const CoordIdx* idx ); - void addSegment( const CoordIdx* idxFrom, const CoordIdx* idxTo ); - const Cell* getCell( int col, int row ) const; - Cell &getCreateCell( int col, int row ); - - QgsSnapIndex( const QgsSnapIndex& rh ); - QgsSnapIndex& operator=( const QgsSnapIndex& rh ); -}; - -#endif // QGSSNAPINDEX_H diff --git a/src/plugins/geometry_snapper/ui/qgsgeometrysnapperdialog.ui b/src/plugins/geometry_snapper/ui/qgsgeometrysnapperdialog.ui deleted file mode 100644 index 91a9e2ea07cb..000000000000 --- a/src/plugins/geometry_snapper/ui/qgsgeometrysnapperdialog.ui +++ /dev/null @@ -1,299 +0,0 @@ - - - QgsGeometrySnapperDialog - - - - 0 - 0 - 486 - 326 - - - - Geometry Snapper - - - - - - - 6 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Input vector layer - - - true - - - - 2 - - - 2 - - - 0 - - - 2 - - - 2 - - - - - - - - Only selected features - - - - - - - - - - Reference layer - - - true - - - - 2 - - - 2 - - - 0 - - - 2 - - - 2 - - - - - - - - - - - Qt::Horizontal - - - - - - - Options - - - true - - - - 2 - - - 0 - - - 2 - - - 2 - - - 2 - - - - - Maximum snapping distance (map units): - - - - - - - 6 - - - 0.000001000000000 - - - 999999999.000000000000000 - - - 1.000000000000000 - - - - - - - - - - Qt::Horizontal - - - - - - - Output vector layer - - - true - - - - 2 - - - 0 - - - 2 - - - 2 - - - 2 - - - - - &Modify input layer - - - false - - - buttonGroupOutput - - - - - - - Create new &layer - - - true - - - buttonGroupOutput - - - - - - - true - - - - - - - Browse - - - - - - - - groupBoxInputLayer - line - groupBoxTopology - groupBoxOutputLayer - line_2 - groupBoxReferenceLayer - - - - - - 24 - - - - - - - Qt::Horizontal - - - QDialogButtonBox::Abort|QDialogButtonBox::Close - - - - - - - - - buttonBox - accepted() - QgsGeometrySnapperDialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - QgsGeometrySnapperDialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - - - - From 1d245b2ef63eb62b40715d63b28b015f20df0d26 Mon Sep 17 00:00:00 2001 From: nirvn Date: Sat, 5 Nov 2016 11:21:13 +0700 Subject: [PATCH 646/897] [FEATURE] add regexp_matches() function The new function returns an array of strings captured by capturing groups in a supplied regular expression. For e.g., the following expression: regexp_matches('qgis=>rocks','(.*)=>(.*)') will return the following array: 'qgis', 'rocks'. --- resources/function_help/json/array_to_string | 2 +- resources/function_help/json/regexp_matches | 12 +++++++ resources/function_help/json/string_to_array | 2 +- src/core/qgsexpression.cpp | 35 ++++++++++++++++++++ tests/src/core/testqgsexpression.cpp | 6 ++++ 5 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 resources/function_help/json/regexp_matches diff --git a/resources/function_help/json/array_to_string b/resources/function_help/json/array_to_string index 2fbfcb85838e..dc459e59d18f 100644 --- a/resources/function_help/json/array_to_string +++ b/resources/function_help/json/array_to_string @@ -5,7 +5,7 @@ "arguments": [ {"arg":"array", "description":"the input array"}, {"arg":"delimiter","optional":true,"default":"','","description":"the string delimiter used to separate concatenated array elements"}, - {"arg":"emptyvalue","optional":true,"default":"''","description":"the optional string to use as replacement to empty values"}], + {"arg":"empty_value","optional":true,"default":"''","description":"the optional string to use as replacement for empty (zero length) matches"}], "examples": [ { "expression":"array_to_string(array('1','2','3'),',')", "returns":"'1,2,3'"}, { "expression":"array_to_string(array('1','','3'),',','0')", "returns":"'1,0,3'"} ] diff --git a/resources/function_help/json/regexp_matches b/resources/function_help/json/regexp_matches new file mode 100644 index 000000000000..7b77ecfe05b2 --- /dev/null +++ b/resources/function_help/json/regexp_matches @@ -0,0 +1,12 @@ +{ + "name": "regexp_matches", + "type": "function", + "description": "Returns an array of all strings captured by capturing groups, in the order the groups themselves appear in the supplied regular expression against a string.", + "arguments": [ + {"arg":"string", "description":"the string to capture groups from against the regular expression"}, + {"arg":"regex","description":"the regular expression used to capture groups"}, + {"arg":"empty_value","optional":true,"default":"''","description":"the optional string to use as replacement for empty (zero length) matches"}], + "examples": [ { "expression":"regexp_matches('qgis=>rocks','(.*)=>(.*)')", "returns":"array: 'qgis', 'rocks'"}, + { "expression":"regexp_matches('key=>','(.*)=>(.*)','empty value')", "returns":"array: 'key', 'empty value'"} + ] +} diff --git a/resources/function_help/json/string_to_array b/resources/function_help/json/string_to_array index 595b60cc1cdf..31e0ffbc9aba 100644 --- a/resources/function_help/json/string_to_array +++ b/resources/function_help/json/string_to_array @@ -5,7 +5,7 @@ "arguments": [ {"arg":"string", "description":"the input string"}, {"arg":"delimiter","optional":true,"default":"','","description":"the string delimiter used to split the input string"}, - {"arg":"emptyvalue","optional":true,"default":"''","description":"the optional string to use as replacement to empty values"}], + {"arg":"empty_value","optional":true,"default":"''","description":"the optional string to use as replacement for empty (zero length) matches"}], "examples": [ { "expression":"string_to_array('1,2,3',',')", "returns":"array: '1', '2', '3'"}, { "expression":"string_to_array('1,,3',',','0')", "returns":"array: '1', '0', '3'"} ] diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index f572d22d3a8f..efbfba80b29c 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1335,6 +1335,39 @@ static QVariant fcnRegexpMatch( const QVariantList& values, const QgsExpressionC return QVariant( str.contains( re ) ? 1 : 0 ); } +static QVariant fcnRegexpMatches( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QString str = getStringValue( values.at( 0 ), parent ); + QString regexp = getStringValue( values.at( 1 ), parent ); + QString empty = getStringValue( values.at( 2 ), parent ); + + QRegularExpression re( regexp ); + if ( !re.isValid() ) + { + parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) ); + return QVariant(); + } + + QRegularExpressionMatch matches = re.match( str ); + if ( matches.hasMatch() ) + { + QVariantList array; + QStringList list = matches.capturedTexts(); + + // Skip the first string to only return captured groups + for ( QStringList::const_iterator it = ++list.constBegin(); it != list.constEnd(); ++it ) + { + array += ( *it ).isEmpty() == false ? *it : empty; + } + + return QVariant( array ); + } + else + { + return QVariant(); + } +} + static QVariant fcnRegexpSubstr( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { QString str = getStringValue( values.at( 0 ), parent ); @@ -3745,6 +3778,8 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "concatenate" ), aggParams << Parameter( QStringLiteral( "concatenator" ), true ), fcnAggregateStringConcat, QStringLiteral( "Aggregates" ), QString(), False, QSet(), true ) << new StaticFunction( QStringLiteral( "regexp_match" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "regex" ) ), fcnRegexpMatch, QStringList() << QStringLiteral( "Conditionals" ) << QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "regexp_matches" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "regex" ) ) << Parameter( QStringLiteral( "emptyvalue" ), true, "" ), fcnRegexpMatches, QStringLiteral( "Arrays" ) ) + << new StaticFunction( QStringLiteral( "now" ), 0, fcnNow, QStringLiteral( "Date and Time" ), QString(), false, QSet(), false, QStringList() << QStringLiteral( "$now" ) ) << new StaticFunction( QStringLiteral( "age" ), 2, fcnAge, QStringLiteral( "Date and Time" ) ) << new StaticFunction( QStringLiteral( "year" ), 1, fcnYear, QStringLiteral( "Date and Time" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 59b97ff88b1e..e228b32442c1 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -841,6 +841,11 @@ class TestQgsExpression: public QObject QTest::newRow( "regexp_substr non-greedy" ) << "regexp_substr('abc123','(\\\\d+?)')" << false << QVariant( "1" ); QTest::newRow( "regexp_substr no hit" ) << "regexp_substr('abcdef','(\\\\d+)')" << false << QVariant( "" ); QTest::newRow( "regexp_substr invalid" ) << "regexp_substr('abc123','([[[')" << true << QVariant(); + QTest::newRow( "regexp_matches" ) << "array_get(regexp_matches('qgis=>rOcks;hello=>world','qgis=>(.*)[;$]'),0)" << false << QVariant( "rOcks" ); + QTest::newRow( "regexp_matches empty custom value" ) << "array_get(regexp_matches('qgis=>;hello=>world','qgis=>(.*)[;$]','empty'),0)" << false << QVariant( "empty" ); + QTest::newRow( "regexp_matches no match" ) << "regexp_matches('123','no()match')" << false << QVariant(); + QTest::newRow( "regexp_matches no capturing group" ) << "regexp_matches('some string','.*')" << false << QVariant( QVariantList() ); + QTest::newRow( "regexp_matches invalid" ) << "regexp_matches('invalid','(')" << true << QVariant(); QTest::newRow( "strpos" ) << "strpos('Hello World','World')" << false << QVariant( 7 ); QTest::newRow( "strpos outside" ) << "strpos('Hello World','blah')" << false << QVariant( 0 ); QTest::newRow( "left" ) << "left('Hello World',5)" << false << QVariant( "Hello" ); @@ -2266,6 +2271,7 @@ class TestQgsExpression: public QObject builderExpected << "world"; QCOMPARE( QgsExpression( "array('hello', 'world')" ).evaluate( &context ), QVariant( builderExpected ) ); QCOMPARE( QgsExpression( "string_to_array('hello,world',',')" ).evaluate( &context ), QVariant( builderExpected ) ); + QCOMPARE( QgsExpression( "regexp_matches('hello=>world','([A-Za-z]*)=>([A-Za-z]*)')" ).evaluate( &context ), QVariant( builderExpected ) ); QCOMPARE( QgsExpression( "array_length(\"strings\")" ).evaluate( &context ), QVariant( 2 ) ); From 6d8990b75d54667b1db3bac3d5578cfe084ca3e5 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 16:12:01 +1000 Subject: [PATCH 647/897] Fix coverity uninitialized variable warnings --- src/app/qgisapp.cpp | 1 + src/app/qgssnappinglayertreemodel.cpp | 1 + src/core/composer/qgscomposertablev2.cpp | 2 ++ src/core/dxf/qgsdxfexport.cpp | 2 ++ src/core/qgsexpression.cpp | 1 + src/core/qgsvectorfilewriter.cpp | 1 + 6 files changed, 8 insertions(+) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 0b27a5edac0e..c1badc292667 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -1181,6 +1181,7 @@ QgisApp::QgisApp() , mBookMarksDockWidget( nullptr ) , mSnappingWidget( nullptr ) , mSnappingDialogContainer( nullptr ) + , mSnappingDialogWidget( nullptr ) , mPluginManager( nullptr ) , mMapStylingDock( nullptr ) , mMapStyleWidget( nullptr ) diff --git a/src/app/qgssnappinglayertreemodel.cpp b/src/app/qgssnappinglayertreemodel.cpp index 21c689e2f93f..40273aedf8c9 100644 --- a/src/app/qgssnappinglayertreemodel.cpp +++ b/src/app/qgssnappinglayertreemodel.cpp @@ -141,6 +141,7 @@ QgsSnappingLayerTreeModel::QgsSnappingLayerTreeModel( QgsProject* project, QObje : QSortFilterProxyModel( parent ) , mProject( project ) , mIndividualLayerSettings( project->snappingConfig().individualLayerSettings() ) + , mLayerTreeModel( nullptr ) { connect( project, &QgsProject::snappingConfigChanged, this, &QgsSnappingLayerTreeModel::onSnappingSettingsChanged ); connect( project, &QgsProject::avoidIntersectionsListChanged, this, &QgsSnappingLayerTreeModel::onSnappingSettingsChanged ); diff --git a/src/core/composer/qgscomposertablev2.cpp b/src/core/composer/qgscomposertablev2.cpp index 8298e704212f..b537ff9309d6 100644 --- a/src/core/composer/qgscomposertablev2.cpp +++ b/src/core/composer/qgscomposertablev2.cpp @@ -93,6 +93,8 @@ QgsComposerTableV2::QgsComposerTableV2() , mShowGrid( true ) , mGridStrokeWidth( 0.5 ) , mGridColor( Qt::black ) + , mHorizontalGrid( true ) + , mVerticalGrid( true ) , mBackgroundColor( Qt::white ) , mWrapBehaviour( TruncateText ) { diff --git a/src/core/dxf/qgsdxfexport.cpp b/src/core/dxf/qgsdxfexport.cpp index d9dbd5cba5c4..8bca2ec9d9cb 100644 --- a/src/core/dxf/qgsdxfexport.cpp +++ b/src/core/dxf/qgsdxfexport.cpp @@ -373,6 +373,7 @@ QgsDxfExport::QgsDxfExport() , mSymbolLayerCounter( 0 ) , mNextHandleId( DXF_HANDSEED ) , mBlockCounter( 0 ) + , mFactor( 1 ) { } @@ -392,6 +393,7 @@ QgsDxfExport& QgsDxfExport::operator=( const QgsDxfExport & dxfExport ) mNextHandleId = 0; mBlockCounter = 0; mCrs = QgsCoordinateReferenceSystem(); + mFactor = dxfExport.mFactor; return *this; } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index efbfba80b29c..f7ee2242380a 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -5905,6 +5905,7 @@ QgsExpression::StaticFunction::StaticFunction( const QString& fnname, const QgsE : Function( fnname, params, group, helpText, lazyEval, handlesNull ) , mFnc( fcn ) , mAliases( aliases ) + , mUsesGeometry( false ) , mUsesGeometryFunc( usesGeometry ) , mReferencedColumnsFunc( referencedColumns ) { diff --git a/src/core/qgsvectorfilewriter.cpp b/src/core/qgsvectorfilewriter.cpp index d177a479b82e..ff702eaaa54b 100644 --- a/src/core/qgsvectorfilewriter.cpp +++ b/src/core/qgsvectorfilewriter.cpp @@ -2289,6 +2289,7 @@ QgsVectorFileWriter::SaveVectorOptions::SaveVectorOptions() , filterExtent( QgsRectangle() ) , overrideGeometryType( QgsWkbTypes::Unknown ) , forceMulti( false ) + , includeZ( false ) , fieldValueConverter( nullptr ) { } From 91e4b24a392c43ca16392267ca7abf7b7a5b30d0 Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Mon, 10 Oct 2016 09:34:30 +0200 Subject: [PATCH 648/897] Better reading/writting of editor widget config. Avoid saving config parameters that are not set and support not having them in the XML. --- .../core/qgseditorwidgetfactory.sip | 12 +++ .../core/qgseditorwidgetfactory.cpp | 24 ++++++ .../core/qgseditorwidgetfactory.h | 12 +++ .../qgscheckboxwidgetfactory.cpp | 8 +- .../editorwidgets/qgsdatetimeeditfactory.cpp | 16 ++-- .../qgsexternalresourcewidgetfactory.cpp | 83 +++++-------------- .../editorwidgets/qgsphotowidgetfactory.cpp | 8 +- .../editorwidgets/qgsrangewidgetfactory.cpp | 31 +++---- .../qgsrelationreferencefactory.cpp | 32 +++---- .../qgstexteditwidgetfactory.cpp | 8 +- .../qgsuniquevaluewidgetfactory.cpp | 4 +- .../qgsvaluerelationwidgetfactory.cpp | 32 +++---- .../editorwidgets/qgswebviewwidgetfactory.cpp | 8 +- 13 files changed, 140 insertions(+), 138 deletions(-) diff --git a/python/gui/editorwidgets/core/qgseditorwidgetfactory.sip b/python/gui/editorwidgets/core/qgseditorwidgetfactory.sip index 10d365fd2f81..f75fd18bf2d6 100644 --- a/python/gui/editorwidgets/core/qgseditorwidgetfactory.sip +++ b/python/gui/editorwidgets/core/qgseditorwidgetfactory.sip @@ -189,4 +189,16 @@ class QgsEditorWidgetFactory * @see supportsField( QgsVectorLayer* vl, fieldIdx ) */ virtual unsigned int fieldScore( const QgsVectorLayer* vl, int fieldIdx ) const; + + protected: + + /** + * Copy the given config element to a XML attribute. + */ + static void config2xml( const QgsEditorWidgetConfig& config, QDomElement& configElement, const QString& fieldName ); + + /** + * Copy the given XML attribute to the configuration element. + */ + static void xml2config( const QDomElement& configElement, QgsEditorWidgetConfig& config, const QString& fieldName ); }; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp b/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp index d9a8dfe82d27..8d2d584c1ad4 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp @@ -123,3 +123,27 @@ unsigned int QgsEditorWidgetFactory::fieldScore( const QgsVectorLayer* vl, int f return 5; } +void QgsEditorWidgetFactory::config2xml( const QgsEditorWidgetConfig& config, QDomElement& configElement, const QString& fieldName ) +{ + const QVariant value = config.value( fieldName ); + if ( value.isValid() ) + { + if ( value.type() == QVariant::Bool ) + { + configElement.setAttribute( fieldName, value.toBool() ? "1" : "0" ); + } + else + { + configElement.setAttribute( fieldName, value.toString() ); + } + } +} + +void QgsEditorWidgetFactory::xml2config( const QDomElement& configElement, QgsEditorWidgetConfig& config, const QString& fieldName ) +{ + const QString value = configElement.attribute( fieldName ); + if ( !value.isNull() ) + { + config.insert( fieldName, value ); + } +} \ No newline at end of file diff --git a/src/gui/editorwidgets/core/qgseditorwidgetfactory.h b/src/gui/editorwidgets/core/qgseditorwidgetfactory.h index b4ee3e21d8d5..54583540138a 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetfactory.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetfactory.h @@ -207,6 +207,18 @@ class GUI_EXPORT QgsEditorWidgetFactory */ virtual unsigned int fieldScore( const QgsVectorLayer* vl, int fieldIdx ) const; + protected: + + /** + * Copy the given config element to a XML attribute. + */ + static void config2xml( const QgsEditorWidgetConfig& config, QDomElement& configElement, const QString& fieldName ); + + /** + * Copy the given XML attribute to the configuration element. + */ + static void xml2config( const QDomElement& configElement, QgsEditorWidgetConfig& config, const QString& fieldName ); + private: QString mName; }; diff --git a/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp b/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp index 4c28516fa147..895e82e0980b 100644 --- a/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgscheckboxwidgetfactory.cpp @@ -45,8 +45,8 @@ QgsEditorWidgetConfig QgsCheckboxWidgetFactory::readConfig( const QDomElement& c QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "CheckedState" ), configElement.attribute( QStringLiteral( "CheckedState" ) ) ); - cfg.insert( QStringLiteral( "UncheckedState" ), configElement.attribute( QStringLiteral( "UncheckedState" ) ) ); + xml2config( configElement, cfg, QStringLiteral( "CheckedState" ) ); + xml2config( configElement, cfg, QStringLiteral( "UncheckedState" ) ); return cfg; } @@ -57,8 +57,8 @@ void QgsCheckboxWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "CheckedState" ), config.value( QStringLiteral( "CheckedState" ), "1" ).toString() ); - configElement.setAttribute( QStringLiteral( "UncheckedState" ), config.value( QStringLiteral( "UncheckedState" ), "0" ).toString() ); + config2xml( config, configElement, QStringLiteral( "CheckedState" ) ); + config2xml( config, configElement, QStringLiteral( "UncheckedState" ) ); } QHash QgsCheckboxWidgetFactory::supportedWidgetTypes() diff --git a/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp b/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp index 6c581c4d07b6..92fad6a6728b 100644 --- a/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp +++ b/src/gui/editorwidgets/qgsdatetimeeditfactory.cpp @@ -47,10 +47,10 @@ QgsEditorWidgetConfig QgsDateTimeEditFactory::readConfig( const QDomElement& con Q_UNUSED( fieldIdx ); QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "field_format" ), configElement.attribute( QStringLiteral( "field_format" ) ) ); - cfg.insert( QStringLiteral( "display_format" ), configElement.attribute( QStringLiteral( "display_format" ) ) ); - cfg.insert( QStringLiteral( "calendar_popup" ), configElement.attribute( QStringLiteral( "calendar_popup" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "allow_null" ), configElement.attribute( QStringLiteral( "allow_null" ) ) == QLatin1String( "1" ) ); + xml2config( configElement, cfg, QStringLiteral( "field_format" ) ); + xml2config( configElement, cfg, QStringLiteral( "display_format" ) ); + xml2config( configElement, cfg, QStringLiteral( "calendar_popup" ) ); + xml2config( configElement, cfg, QStringLiteral( "allow_null" ) ); return cfg; } @@ -61,10 +61,10 @@ void QgsDateTimeEditFactory::writeConfig( const QgsEditorWidgetConfig& config, Q Q_UNUSED( layer ); Q_UNUSED( fieldIdx ); - configElement.setAttribute( QStringLiteral( "field_format" ), config[QStringLiteral( "field_format" )].toString() ); - configElement.setAttribute( QStringLiteral( "display_format" ), config[QStringLiteral( "display_format" )].toString() ); - configElement.setAttribute( QStringLiteral( "calendar_popup" ), config[QStringLiteral( "calendar_popup" )].toBool() ); - configElement.setAttribute( QStringLiteral( "allow_null" ), config[QStringLiteral( "allow_null" )].toBool() ); + config2xml( config, configElement, QStringLiteral( "field_format" ) ); + config2xml( config, configElement, QStringLiteral( "display_format" ) ); + config2xml( config, configElement, QStringLiteral( "calendar_popup" ) ); + config2xml( config, configElement, QStringLiteral( "allow_null" ) ); } QString QgsDateTimeEditFactory::representValue( QgsVectorLayer* vl, int fieldIdx, const QgsEditorWidgetConfig& config, const QVariant& cache, const QVariant& value ) const diff --git a/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp b/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp index 3193578e915f..532471739c80 100644 --- a/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsexternalresourcewidgetfactory.cpp @@ -40,36 +40,17 @@ void QgsExternalResourceWidgetFactory::writeConfig( const QgsEditorWidgetConfig& Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "FileWidget" ), config.value( QStringLiteral( "FileWidget" ), true ).toBool() ); - configElement.setAttribute( QStringLiteral( "FileWidgetButton" ), config.value( QStringLiteral( "FileWidgetButton" ), true ).toBool() ); - - - // Non mandatory options are not saved into project file (to save some space). - if ( config.contains( QStringLiteral( "UseLink" ) ) ) - configElement.setAttribute( QStringLiteral( "UseLink" ), config.value( QStringLiteral( "UseLink" ) ).toBool() ); - - if ( config.contains( QStringLiteral( "FullUrl" ) ) ) - configElement.setAttribute( QStringLiteral( "FullUrl" ), config.value( QStringLiteral( "FullUrl" ) ).toBool() ); - - if ( config.contains( QStringLiteral( "DefaultRoot" ) ) ) - configElement.setAttribute( QStringLiteral( "DefaultRoot" ), config.value( QStringLiteral( "DefaultRoot" ) ).toString() ); - - if ( config.contains( QStringLiteral( "RelativeStorage" ) ) ) - configElement.setAttribute( QStringLiteral( "RelativeStorage" ) , config.value( QStringLiteral( "RelativeStorage" ) ).toString() ); - - if ( config.contains( QStringLiteral( "DocumentViewer" ) ) ) - configElement.setAttribute( QStringLiteral( "DocumentViewer" ), config.value( QStringLiteral( "DocumentViewer" ) ).toInt() ); - - if ( config.contains( QStringLiteral( "DocumentViewerWidth" ) ) ) - configElement.setAttribute( QStringLiteral( "DocumentViewerWidth" ), config.value( QStringLiteral( "DocumentViewerWidth" ) ).toInt() ); - - if ( config.contains( QStringLiteral( "DocumentViewerHeight" ) ) ) - configElement.setAttribute( QStringLiteral( "DocumentViewerHeight" ), config.value( QStringLiteral( "DocumentViewerHeight" ) ).toInt() ); - - if ( config.contains( QStringLiteral( "FileWidgetFilter" ) ) ) - configElement.setAttribute( QStringLiteral( "FileWidgetFilter" ), config.value( QStringLiteral( "FileWidgetFilter" ) ).toString() ); - - configElement.setAttribute( QStringLiteral( "StorageMode" ), config.value( QStringLiteral( "StorageMode" ) ).toString() ); + config2xml( config, configElement, QStringLiteral( "FileWidget" ) ); + config2xml( config, configElement, QStringLiteral( "FileWidgetButton" ) ); + config2xml( config, configElement, QStringLiteral( "UseLink" ) ); + config2xml( config, configElement, QStringLiteral( "FullUrl" ) ); + config2xml( config, configElement, QStringLiteral( "DefaultRoot" ) ); + config2xml( config, configElement, QStringLiteral( "RelativeStorage" ) ); + config2xml( config, configElement, QStringLiteral( "DocumentViewer" ) ); + config2xml( config, configElement, QStringLiteral( "DocumentViewerWidth" ) ); + config2xml( config, configElement, QStringLiteral( "DocumentViewerHeight" ) ); + config2xml( config, configElement, QStringLiteral( "FileWidgetFilter" ) ); + config2xml( config, configElement, QStringLiteral( "StorageMode" ) ); } QgsEditorWidgetConfig QgsExternalResourceWidgetFactory::readConfig( const QDomElement& configElement, QgsVectorLayer* layer, int fieldIdx ) @@ -79,42 +60,22 @@ QgsEditorWidgetConfig QgsExternalResourceWidgetFactory::readConfig( const QDomEl QgsEditorWidgetConfig cfg; - if ( configElement.hasAttribute( QStringLiteral( "FileWidgetButton" ) ) ) - cfg.insert( QStringLiteral( "FileWidgetButton" ), configElement.attribute( QStringLiteral( "FileWidgetButton" ) ) == QLatin1String( "1" ) ); - - if ( configElement.hasAttribute( QStringLiteral( "FileWidget" ) ) ) - cfg.insert( QStringLiteral( "FileWidget" ), configElement.attribute( QStringLiteral( "FileWidget" ) ) == QLatin1String( "1" ) ); - - if ( configElement.hasAttribute( QStringLiteral( "UseLink" ) ) ) - cfg.insert( QStringLiteral( "UseLink" ), configElement.attribute( QStringLiteral( "UseLink" ) ) == QLatin1String( "1" ) ); - - if ( configElement.hasAttribute( QStringLiteral( "FullUrl" ) ) ) - cfg.insert( QStringLiteral( "FullUrl" ), configElement.attribute( QStringLiteral( "FullUrl" ) ) == QLatin1String( "1" ) ); - - if ( configElement.hasAttribute( QStringLiteral( "DefaultRoot" ) ) ) - cfg.insert( QStringLiteral( "DefaultRoot" ), configElement.attribute( QStringLiteral( "DefaultRoot" ) ) ); - + xml2config( configElement, cfg, QStringLiteral( "FileWidget" ) ); + xml2config( configElement, cfg, QStringLiteral( "FileWidgetButton" ) ); + xml2config( configElement, cfg, QStringLiteral( "UseLink" ) ); + xml2config( configElement, cfg, QStringLiteral( "FullUrl" ) ); + xml2config( configElement, cfg, QStringLiteral( "DefaultRoot" ) ); if ( configElement.hasAttribute( QStringLiteral( "RelativeStorage" ) ) ) { if (( configElement.attribute( QStringLiteral( "RelativeStorage" ) ).toInt() == QgsFileWidget::RelativeDefaultPath && configElement.hasAttribute( QStringLiteral( "DefaultRoot" ) ) ) || configElement.attribute( QStringLiteral( "RelativeStorage" ) ).toInt() == QgsFileWidget::RelativeProject ) - cfg.insert( QStringLiteral( "RelativeStorage" ) , configElement.attribute( QStringLiteral( "RelativeStorage" ) ).toInt() ); + xml2config( configElement, cfg, QStringLiteral( "RelativeStorage" ) ); } - - if ( configElement.hasAttribute( QStringLiteral( "DocumentViewer" ) ) ) - cfg.insert( QStringLiteral( "DocumentViewer" ), configElement.attribute( QStringLiteral( "DocumentViewer" ) ) ); - - if ( configElement.hasAttribute( QStringLiteral( "DocumentViewerWidth" ) ) ) - cfg.insert( QStringLiteral( "DocumentViewerWidth" ), configElement.attribute( QStringLiteral( "DocumentViewerWidth" ) ) ); - - if ( configElement.hasAttribute( QStringLiteral( "DocumentViewerHeight" ) ) ) - cfg.insert( QStringLiteral( "DocumentViewerHeight" ), configElement.attribute( QStringLiteral( "DocumentViewerHeight" ) ) ); - - if ( configElement.hasAttribute( QStringLiteral( "FileWidgetFilter" ) ) ) - cfg.insert( QStringLiteral( "FileWidgetFilter" ), configElement.attribute( QStringLiteral( "FileWidgetFilter" ) ) ); - - - cfg.insert( QStringLiteral( "StorageMode" ), configElement.attribute( QStringLiteral( "StorageMode" ), QStringLiteral( "Files" ) ) ); + xml2config( configElement, cfg, QStringLiteral( "DocumentViewer" ) ); + xml2config( configElement, cfg, QStringLiteral( "DocumentViewerWidth" ) ); + xml2config( configElement, cfg, QStringLiteral( "DocumentViewerHeight" ) ); + xml2config( configElement, cfg, QStringLiteral( "FileWidgetFilter" ) ); + xml2config( configElement, cfg, QStringLiteral( "StorageMode" ) ); return cfg; } diff --git a/src/gui/editorwidgets/qgsphotowidgetfactory.cpp b/src/gui/editorwidgets/qgsphotowidgetfactory.cpp index 7fdb0840b8f3..dd3cf79cf9c0 100644 --- a/src/gui/editorwidgets/qgsphotowidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsphotowidgetfactory.cpp @@ -41,8 +41,8 @@ QgsEditorWidgetConfig QgsPhotoWidgetFactory::readConfig( const QDomElement& conf QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "Height" ), configElement.attribute( QStringLiteral( "Height" ), 0 ).toInt() ); - cfg.insert( QStringLiteral( "Width" ), configElement.attribute( QStringLiteral( "Width" ), 0 ).toInt() ); + xml2config( configElement, cfg, QStringLiteral( "Height" ) ); + xml2config( configElement, cfg, QStringLiteral( "Width" ) ); return cfg; } @@ -53,6 +53,6 @@ void QgsPhotoWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, QD Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "Height" ), config.value( QStringLiteral( "Height" ), 0 ).toString() ); - configElement.setAttribute( QStringLiteral( "Width" ), config.value( QStringLiteral( "Width" ), 0 ).toString() ); + config2xml( config, configElement, QStringLiteral( "Height" ) ); + config2xml( config, configElement, QStringLiteral( "Width" ) ); } diff --git a/src/gui/editorwidgets/qgsrangewidgetfactory.cpp b/src/gui/editorwidgets/qgsrangewidgetfactory.cpp index dce3b3b471ce..3fb8cb8cfd00 100644 --- a/src/gui/editorwidgets/qgsrangewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsrangewidgetfactory.cpp @@ -40,16 +40,12 @@ QgsEditorWidgetConfig QgsRangeWidgetFactory::readConfig( const QDomElement& conf Q_UNUSED( fieldIdx ); QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "Style" ), configElement.attribute( QStringLiteral( "Style" ) ) ); - cfg.insert( QStringLiteral( "Min" ), configElement.attribute( QStringLiteral( "Min" ) ) ); - cfg.insert( QStringLiteral( "Max" ), configElement.attribute( QStringLiteral( "Max" ) ) ); - cfg.insert( QStringLiteral( "Step" ), configElement.attribute( QStringLiteral( "Step" ) ) ); - cfg.insert( QStringLiteral( "AllowNull" ), configElement.attribute( QStringLiteral( "AllowNull" ) ) == QLatin1String( "1" ) ); - - if ( configElement.hasAttribute( QStringLiteral( "Suffix" ) ) ) - { - cfg.insert( QStringLiteral( "Suffix" ), configElement.attribute( QStringLiteral( "Suffix" ) ) ); - } + xml2config( configElement, cfg, QStringLiteral( "Style" ) ); + xml2config( configElement, cfg, QStringLiteral( "Min" ) ); + xml2config( configElement, cfg, QStringLiteral( "Max" ) ); + xml2config( configElement, cfg, QStringLiteral( "Step" ) ); + xml2config( configElement, cfg, QStringLiteral( "AllowNull" ) ); + xml2config( configElement, cfg, QStringLiteral( "Suffix" ) ); return cfg; } @@ -60,15 +56,12 @@ void QgsRangeWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, QD Q_UNUSED( layer ); Q_UNUSED( fieldIdx ); - configElement.setAttribute( QStringLiteral( "Style" ), config[QStringLiteral( "Style" )].toString() ); - configElement.setAttribute( QStringLiteral( "Min" ), config[QStringLiteral( "Min" )].toString() ); - configElement.setAttribute( QStringLiteral( "Max" ), config[QStringLiteral( "Max" )].toString() ); - configElement.setAttribute( QStringLiteral( "Step" ), config[QStringLiteral( "Step" )].toString() ); - configElement.setAttribute( QStringLiteral( "AllowNull" ), config[QStringLiteral( "AllowNull" )].toBool() ); - if ( config.contains( QStringLiteral( "Suffix" ) ) ) - { - configElement.setAttribute( QStringLiteral( "Suffix" ), config[QStringLiteral( "Suffix" )].toString() ); - } + config2xml( config, configElement, QStringLiteral( "Style" ) ); + config2xml( config, configElement, QStringLiteral( "Min" ) ); + config2xml( config, configElement, QStringLiteral( "Max" ) ); + config2xml( config, configElement, QStringLiteral( "Step" ) ); + config2xml( config, configElement, QStringLiteral( "AllowNull" ) ); + config2xml( config, configElement, QStringLiteral( "Suffix" ) ); } unsigned int QgsRangeWidgetFactory::fieldScore( const QgsVectorLayer* vl, int fieldIdx ) const diff --git a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp index 24115e3ec7ac..357b13282ea3 100644 --- a/src/gui/editorwidgets/qgsrelationreferencefactory.cpp +++ b/src/gui/editorwidgets/qgsrelationreferencefactory.cpp @@ -53,13 +53,13 @@ QgsEditorWidgetConfig QgsRelationReferenceFactory::readConfig( const QDomElement Q_UNUSED( fieldIdx ); QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "AllowNULL" ), configElement.attribute( QStringLiteral( "AllowNULL" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "OrderByValue" ), configElement.attribute( QStringLiteral( "OrderByValue" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "ShowForm" ), configElement.attribute( QStringLiteral( "ShowForm" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "Relation" ), configElement.attribute( QStringLiteral( "Relation" ) ) ); - cfg.insert( QStringLiteral( "MapIdentification" ), configElement.attribute( QStringLiteral( "MapIdentification" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "ReadOnly" ), configElement.attribute( QStringLiteral( "ReadOnly" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "AllowAddFeatures" ), configElement.attribute( QStringLiteral( "AllowAddFeatures" ) ) == QLatin1String( "1" ) ); + xml2config( configElement, cfg, QStringLiteral( "AllowNULL" ) ); + xml2config( configElement, cfg, QStringLiteral( "OrderByValue" ) ); + xml2config( configElement, cfg, QStringLiteral( "ShowForm" ) ); + xml2config( configElement, cfg, QStringLiteral( "Relation" ) ); + xml2config( configElement, cfg, QStringLiteral( "MapIdentification" ) ); + xml2config( configElement, cfg, QStringLiteral( "ReadOnly" ) ); + xml2config( configElement, cfg, QStringLiteral( "AllowAddFeatures" ) ); QDomNode filterNode = configElement.elementsByTagName( QStringLiteral( "FilterFields" ) ).at( 0 ); if ( !filterNode.isNull() ) @@ -74,7 +74,7 @@ QgsEditorWidgetConfig QgsRelationReferenceFactory::readConfig( const QDomElement } cfg.insert( QStringLiteral( "FilterFields" ), filterFields ); - cfg.insert( QStringLiteral( "ChainFilters" ), filterNode.toElement().attribute( QStringLiteral( "ChainFilters" ) ) == QLatin1String( "1" ) ); + xml2config( configElement, cfg , QStringLiteral( "ChainFilters" ) ); } return cfg; } @@ -85,13 +85,13 @@ void QgsRelationReferenceFactory::writeConfig( const QgsEditorWidgetConfig& conf Q_UNUSED( layer ); Q_UNUSED( fieldIdx ); - configElement.setAttribute( QStringLiteral( "AllowNULL" ), config[QStringLiteral( "AllowNULL" )].toBool() ); - configElement.setAttribute( QStringLiteral( "OrderByValue" ), config[QStringLiteral( "OrderByValue" )].toBool() ); - configElement.setAttribute( QStringLiteral( "ShowForm" ), config[QStringLiteral( "ShowForm" )].toBool() ); - configElement.setAttribute( QStringLiteral( "Relation" ), config[QStringLiteral( "Relation" )].toString() ); - configElement.setAttribute( QStringLiteral( "MapIdentification" ), config[QStringLiteral( "MapIdentification" )].toBool() ); - configElement.setAttribute( QStringLiteral( "ReadOnly" ), config[QStringLiteral( "ReadOnly" )].toBool() ); - configElement.setAttribute( QStringLiteral( "AllowAddFeatures" ), config[QStringLiteral( "AllowAddFeatures" )].toBool() ); + config2xml( config, configElement, QStringLiteral( "AllowNULL" ) ); + config2xml( config, configElement, QStringLiteral( "OrderByValue" ) ); + config2xml( config, configElement, QStringLiteral( "ShowForm" ) ); + config2xml( config, configElement, QStringLiteral( "Relation" ) ); + config2xml( config, configElement, QStringLiteral( "MapIdentification" ) ); + config2xml( config, configElement, QStringLiteral( "ReadOnly" ) ); + config2xml( config, configElement, QStringLiteral( "AllowAddFeatures" ) ); if ( config.contains( QStringLiteral( "FilterFields" ) ) ) { @@ -105,7 +105,7 @@ void QgsRelationReferenceFactory::writeConfig( const QgsEditorWidgetConfig& conf } configElement.appendChild( filterFields ); - filterFields.setAttribute( QStringLiteral( "ChainFilters" ), config[QStringLiteral( "ChainFilters" )].toBool() ); + config2xml( config, configElement, QStringLiteral( "ChainFilters" ) ); } } diff --git a/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp b/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp index 71b5a34f3343..66dd51a90f5a 100644 --- a/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgstexteditwidgetfactory.cpp @@ -46,8 +46,8 @@ void QgsTextEditWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "IsMultiline" ), config.value( QStringLiteral( "IsMultiline" ), false ).toBool() ); - configElement.setAttribute( QStringLiteral( "UseHtml" ), config.value( QStringLiteral( "UseHtml" ), false ).toBool() ); + config2xml( config, configElement, QStringLiteral( "IsMultiline" ) ); + config2xml( config, configElement, QStringLiteral( "UseHtml" ) ); } QgsEditorWidgetConfig QgsTextEditWidgetFactory::readConfig( const QDomElement& configElement, QgsVectorLayer* layer, int fieldIdx ) @@ -57,8 +57,8 @@ QgsEditorWidgetConfig QgsTextEditWidgetFactory::readConfig( const QDomElement& c QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "IsMultiline" ), configElement.attribute( QStringLiteral( "IsMultiline" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); - cfg.insert( QStringLiteral( "UseHtml" ), configElement.attribute( QStringLiteral( "UseHtml" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); + xml2config( configElement, cfg, QStringLiteral( "IsMultiline" ) ); + xml2config( configElement, cfg, QStringLiteral( "UseHtml" ) ); return cfg; } diff --git a/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp b/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp index 5416d8111a66..52ab3f5fcba8 100644 --- a/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsuniquevaluewidgetfactory.cpp @@ -41,7 +41,7 @@ QgsEditorWidgetConfig QgsUniqueValueWidgetFactory::readConfig( const QDomElement QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "Editable" ), configElement.attribute( QStringLiteral( "Editable" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) ); + xml2config( configElement, cfg, QStringLiteral( "Editable" ) ); return cfg; } @@ -51,5 +51,5 @@ void QgsUniqueValueWidgetFactory::writeConfig( const QgsEditorWidgetConfig& conf Q_UNUSED( doc ) Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "Editable" ), config.value( QStringLiteral( "Editable" ), false ).toBool() ); + config2xml( config, configElement, QStringLiteral( "Editable" ) ); } diff --git a/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp b/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp index 6df733d27827..faeafd452df1 100644 --- a/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationwidgetfactory.cpp @@ -52,14 +52,14 @@ QgsEditorWidgetConfig QgsValueRelationWidgetFactory::readConfig( const QDomEleme QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "Layer" ), configElement.attribute( QStringLiteral( "Layer" ) ) ); - cfg.insert( QStringLiteral( "Key" ), configElement.attribute( QStringLiteral( "Key" ) ) ); - cfg.insert( QStringLiteral( "Value" ), configElement.attribute( QStringLiteral( "Value" ) ) ); - cfg.insert( QStringLiteral( "FilterExpression" ), configElement.attribute( QStringLiteral( "FilterExpression" ) ) ); - cfg.insert( QStringLiteral( "OrderByValue" ), configElement.attribute( QStringLiteral( "OrderByValue" ) ) ); - cfg.insert( QStringLiteral( "AllowMulti" ), configElement.attribute( QStringLiteral( "AllowMulti" ) ) ); - cfg.insert( QStringLiteral( "AllowNull" ), configElement.attribute( QStringLiteral( "AllowNull" ) ) ); - cfg.insert( QStringLiteral( "UseCompleter" ), configElement.attribute( QStringLiteral( "UseCompleter" ) ) ); + xml2config( configElement, cfg, QStringLiteral( "Layer" ) ); + xml2config( configElement, cfg, QStringLiteral( "Key" ) ); + xml2config( configElement, cfg, QStringLiteral( "Value" ) ); + xml2config( configElement, cfg, QStringLiteral( "FilterExpression" ) ); + xml2config( configElement, cfg, QStringLiteral( "OrderByValue" ) ); + xml2config( configElement, cfg, QStringLiteral( "AllowMulti" ) ); + xml2config( configElement, cfg, QStringLiteral( "AllowNull" ) ); + xml2config( configElement, cfg, QStringLiteral( "UseCompleter" ) ); return cfg; } @@ -70,14 +70,14 @@ void QgsValueRelationWidgetFactory::writeConfig( const QgsEditorWidgetConfig& co Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "Layer" ), config.value( QStringLiteral( "Layer" ) ).toString() ); - configElement.setAttribute( QStringLiteral( "Key" ), config.value( QStringLiteral( "Key" ) ).toString() ); - configElement.setAttribute( QStringLiteral( "Value" ), config.value( QStringLiteral( "Value" ) ).toString() ); - configElement.setAttribute( QStringLiteral( "FilterExpression" ), config.value( QStringLiteral( "FilterExpression" ) ).toString() ); - configElement.setAttribute( QStringLiteral( "OrderByValue" ), config.value( QStringLiteral( "OrderByValue" ) ).toBool() ); - configElement.setAttribute( QStringLiteral( "AllowMulti" ), config.value( QStringLiteral( "AllowMulti" ) ).toBool() ); - configElement.setAttribute( QStringLiteral( "AllowNull" ), config.value( QStringLiteral( "AllowNull" ) ).toBool() ); - configElement.setAttribute( QStringLiteral( "UseCompleter" ), config.value( QStringLiteral( "UseCompleter" ) ).toBool() ); + config2xml( config, configElement, QStringLiteral( "Layer" ) ); + config2xml( config, configElement, QStringLiteral( "Key" ) ); + config2xml( config, configElement, QStringLiteral( "Value" ) ); + config2xml( config, configElement, QStringLiteral( "FilterExpression" ) ); + config2xml( config, configElement, QStringLiteral( "OrderByValue" ) ); + config2xml( config, configElement, QStringLiteral( "AllowMulti" ) ); + config2xml( config, configElement, QStringLiteral( "AllowNull" ) ); + config2xml( config, configElement, QStringLiteral( "UseCompleter" ) ); } QString QgsValueRelationWidgetFactory::representValue( QgsVectorLayer* vl, int fieldIdx, const QgsEditorWidgetConfig& config, const QVariant& cache, const QVariant& value ) const diff --git a/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp b/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp index 899105a6592c..702f868e8089 100644 --- a/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp +++ b/src/gui/editorwidgets/qgswebviewwidgetfactory.cpp @@ -41,8 +41,8 @@ QgsEditorWidgetConfig QgsWebViewWidgetFactory::readConfig( const QDomElement& co QgsEditorWidgetConfig cfg; - cfg.insert( QStringLiteral( "Height" ), configElement.attribute( QStringLiteral( "Height" ), 0 ).toInt() ); - cfg.insert( QStringLiteral( "Width" ), configElement.attribute( QStringLiteral( "Width" ), 0 ).toInt() ); + xml2config( configElement, cfg, QStringLiteral( "Height" ) ); + xml2config( configElement, cfg, QStringLiteral( "Width" ) ); return cfg; } @@ -53,6 +53,6 @@ void QgsWebViewWidgetFactory::writeConfig( const QgsEditorWidgetConfig& config, Q_UNUSED( layer ) Q_UNUSED( fieldIdx ) - configElement.setAttribute( QStringLiteral( "Height" ), config.value( QStringLiteral( "Height" ), 0 ).toString() ); - configElement.setAttribute( QStringLiteral( "Width" ), config.value( QStringLiteral( "Width" ), 0 ).toString() ); + config2xml( config, configElement, QStringLiteral( "Height" ) ); + config2xml( config, configElement, QStringLiteral( "Width" ) ); } From 0ca9eb0d2cc77356b0bd523f345e841e65239506 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Mon, 7 Nov 2016 12:15:23 +0100 Subject: [PATCH 649/897] debian packaging: drop trusty support --- INSTALL | 15 +++++---------- NEWS | 4 ++-- debian/changelog | 3 ++- debian/control.in | 5 +---- debian/rules | 6 +----- doc/INSTALL.html | 26 ++++++++++++++------------ doc/linux.t2t | 1 - doc/news.html | 4 ++-- 8 files changed, 27 insertions(+), 37 deletions(-) diff --git a/INSTALL b/INSTALL index fa9bfd41aa6f..3bfcba0bc992 100644 --- a/INSTALL +++ b/INSTALL @@ -1,9 +1,11 @@ QGIS Building QGIS from source - step by step -Tuesday October 25, 2016 +Monday November 07, 2016 + + +Last Updated: Monday November 07, 2016 +Last Change : Monday November 07, 2016 -Last Updated: Tuesday October 25, 2016 -Last Change : Monday October 24, 2016 1. Introduction 2. Overview @@ -179,7 +181,6 @@ Now update your local sources database: =============================== || Distribution | install command for packages | - | trusty | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | | stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | | xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | | yakkety | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | @@ -368,7 +369,6 @@ new subdirectory called `build` or `build-qt5` in it. 3.11.1. Install build dependencies ================================== - dnf install qt5-qtwebkit-devel qt5-qtlocation-devel qt5-qttools-static qt5-qtscript-devel qca-qt5-devel python3-qt5-devel python3-qscintilla-qt5-devel qscintilla-qt5-devel python3-qscintilla-devel python3-qscintilla-qt5 @@ -377,23 +377,18 @@ new subdirectory called `build` or `build-qt5` in it. qwt-qt5-devel gsl-devel postgresql-devel cmake python3-future gdal-python3 python3-psycopg2 python3-PyYAML qca-qt5-ossl - To build QGIS server additional dependencies are required: - dnf install fcgi-devel - Make sure that your build directory is completely empty when you enter the following command. Do never try to "re-use" an existing Qt4 build directory. If you want to use `ccmake` or other interactive tools, run the following command in the empty build directory once before starting to use the interactive tools. - cmake .. - If everything went ok you can finally start to compile. (As usual append a -jX where X is the number of available cores option to make to speed up your build process) diff --git a/NEWS b/NEWS index d30616765701..387cb50ddd3f 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,6 @@ QGIS News Change history for the QGIS Project -Thursday October 06, 2016 +Monday November 07, 2016 ------------------------------------------------------------------------ @@ -39,7 +39,7 @@ Thursday October 06, 2016 ------------------------------------------------------------------------ -Last Updated: Thursday October 06, 2016 +Last Updated: Monday November 07, 2016 Last Change : Wednesday July 27, 2016 diff --git a/debian/changelog b/debian/changelog index 722b5c3fdeb6..a0e7e42bcbdd 100644 --- a/debian/changelog +++ b/debian/changelog @@ -2,8 +2,9 @@ qgis (2.99.0) UNRELEASED; urgency=medium * New development version 2.999 after branch of 2.16 * move to qt5/python3/ninja + * drop trusty support (libqca-2-dev missing) - -- Jürgen E. Fischer Thu, 06 Oct 2016 13:30:42 +0200 + -- Jürgen E. Fischer Mon, 07 Nov 2016 12:14:47 +0100 qgis (2.16.0) unstable; urgency=medium diff --git a/debian/control.in b/debian/control.in index 0a85ef0728b4..86e1668b7164 100644 --- a/debian/control.in +++ b/debian/control.in @@ -13,7 +13,6 @@ Build-Depends: libexpat1-dev, libfcgi-dev, libgdal-dev (>= 1.11), -#trusty# libgsl0-dev, #sid stretch xenial yakkety# libgsl-dev, libgeos-dev (>= 3.0.0), libpq-dev, @@ -43,8 +42,7 @@ Build-Depends: locales, ca-certificates, ninja-build Build-Conflicts: libqgis-dev, qgis-dev #sid stretch xenial yakkety#Standards-Version: 3.9.7 -#trusty#Standards-Version: 3.8.4 -#trusty xenial yakkety#XS-Python-Version: current +#xenial yakkety#XS-Python-Version: current Vcs-Browser: https://github.com/qgis/QGIS/ Vcs-Git: https://github.com/qgis/QGIS.git Homepage: http://qgis.org/ @@ -202,7 +200,6 @@ Depends: libexpat1-dev, libgdal-dev (>= 1.11), libgeos-dev (>= 3.0.0), -#trusty# libgsl0-dev, #sid stretch xenial yakkety# libgsl-dev, libpq-dev, libproj-dev, diff --git a/debian/rules b/debian/rules index b1aca1250452..f036130c496d 100755 --- a/debian/rules +++ b/debian/rules @@ -36,7 +36,7 @@ endif QT_PLUGINS_DIR = usr/lib/$(DEB_BUILD_MULTIARCH)/qt5/plugins -ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"trusty stretch xenial yakkety")) +ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"stretch xenial yakkety")) DISTRIBUTION := sid endif @@ -144,10 +144,6 @@ endif ifneq (,$(findstring debug,$(DEB_BUILD_OPTIONS))) CMAKE_OPTS += -DCMAKE_BUILD_TYPE=Debug -else -ifneq (,$(findstring $(DISTRIBUTION),"trusty")) - CMAKE_OPTS += -DKEEP_GLOBE_CXX_FLAGS=TRUE -endif endif ifneq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))) diff --git a/doc/INSTALL.html b/doc/INSTALL.html index 703775adb3f3..8216371302ff 100644 --- a/doc/INSTALL.html +++ b/doc/INSTALL.html @@ -77,13 +77,13 @@

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -Last Updated: Tuesday October 25, 2016 -Last Change : Monday October 24, 2016 +Last Updated: Monday November 07, 2016 +Last Change : Monday November 07, 2016

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  @@ -312,10 +312,6 @@

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  3.3. Install build dependencies

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  install command for packages -trusty -apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui - - stretch apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui @@ -563,24 +559,29 @@

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  3.10.1. Install build dependencies

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  command in the empty build directory once before starting to use the interactive tools.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   cmake
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  If everything went ok you can finally start to compile. (As usual append a -jX where X is the number of available cores option to make to speed up your build process)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   make
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  3.11. On Fedora Linux

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  We assume that you have the source code of QGIS ready and created a new subdirectory called `build` or `build-qt5` in it.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  3.11.1. Install build dependencies

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   dnf install qt5-qtwebkit-devel qt5-qtlocation-devel qt5-qttools-static
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   qt5-qtscript-devel qca-qt5-devel python3-qt5-devel python3-qscintilla-qt5-devel 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  @@ -590,14 +591,15 @@ 

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  3.11.1. Install build dependencies

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qwt-qt5-devel gsl-devel postgresql-devel cmake python3-future gdal-python3 python3-psycopg2 python3-PyYAML qca-qt5-ossl
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  To build QGIS server additional dependencies are required:

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   dnf install fcgi-devel
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Make sure that your build directory is completely empty when you enter the following command. Do never try to "re-use" an existing Qt4 build directory. @@ -607,7 +609,7 @@

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  3.11.1. Install build dependencies

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -cmake -DENABLE_QT5=ON -DWITH_QWTPOLAR=OFF ..
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +cmake ..
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  diff --git a/doc/linux.t2t b/doc/linux.t2t index c4443c4e107a..f6d8705398ae 100644 --- a/doc/linux.t2t +++ b/doc/linux.t2t @@ -44,7 +44,6 @@ sudo apt-get update == Install build dependencies == || Distribution | install command for packages | -| trusty | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | | stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | | xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | | yakkety | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | diff --git a/doc/news.html b/doc/news.html index 524432af9cae..a2c051b7a266 100644 --- a/doc/news.html +++ b/doc/news.html @@ -77,7 +77,7 @@

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  @@ -116,7 +116,7 @@

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Thursday October 06, 2016

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  -Last Updated: Thursday October 06, 2016 +Last Updated: Monday November 07, 2016 Last Change : Wednesday July 27, 2016

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  From 8e7ae8f04dedb0226e2ffd4fecab58a3ada6627c Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Mon, 7 Nov 2016 10:29:40 +0100 Subject: [PATCH 650/897] Avoid having duplicated relations in the discovery --- src/providers/postgres/qgspostgresprovider.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index d653f29a61f9..8c35fc122bbe 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -4007,6 +4007,7 @@ QList QgsPostgresProvider::discoverRelations( const QgsVectorLayer* "ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME " "AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION " "WHERE KCU1.CONSTRAINT_SCHEMA=" + QgsPostgresConn::quotedValue( mSchemaName ) + " AND KCU1.TABLE_NAME=" + QgsPostgresConn::quotedValue( mTableName ) + + "GROUP BY RC.CONSTRAINT_NAME, KCU1.COLUMN_NAME, KCU2.CONSTRAINT_SCHEMA, KCU2.TABLE_NAME, KCU2.COLUMN_NAME, KCU1.ORDINAL_POSITION " + "ORDER BY KCU1.ORDINAL_POSITION" ); QgsPostgresResult sqlResult( connectionRO()->PQexec( sql ) ); From bc1ad2ce82196402ffa83118b7fd3c2f195a4414 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Brunner?= Date: Fri, 4 Nov 2016 12:56:44 +0100 Subject: [PATCH 651/897] Add metadata for WFS provider in layer metadata informations --- python/core/qgsvectordataprovider.sip | 6 ++++++ src/core/qgsvectordataprovider.h | 8 +++++++- src/core/qgsvectorlayer.cpp | 14 ++++++++++++++ src/providers/wfs/qgswfsprovider.cpp | 10 ++++++++++ src/providers/wfs/qgswfsprovider.h | 6 ++++++ 5 files changed, 43 insertions(+), 1 deletion(-) diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 198b57c5f646..4b40a6f02a50 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -379,6 +379,12 @@ class QgsVectorDataProvider : QgsDataProvider */ virtual QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const; + /** + * Get some metadata that will be display in the metadata tab of the layer properties. + * @return The provider metadata + */ + virtual QMap metadata() const; + signals: /** * Signals an error in this provider diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index bb5c967ab81c..b6f6b6a7c4db 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -383,7 +383,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider * Returns true if the provider is strict about the type of inserted features * (e.g. no multipolygon in a polygon layer) */ - virtual bool doesStrictFeatureTypeCheck() const { return true;} + virtual bool doesStrictFeatureTypeCheck() const { return true; } //! Returns a list of available encodings static QStringList availableEncodings(); @@ -439,6 +439,12 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ virtual QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const; + /** + * Get some metadata that will be display in the metadata tab of the layer properties. + * @return The provider metadata + */ + virtual QMap metadata() const { return QMap(); }; + signals: /** * Signals an error in this provider diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 8c0782feb4da..f210e69e79b6 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -3770,6 +3770,20 @@ QString QgsVectorLayer::metadata() const myMetadata += QLatin1String( "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " ); myMetadata += dataProvider()->description().replace( '\n', QLatin1String( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " ) ); myMetadata += QLatin1String( "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n" ); + + QMap dataProviderMetadata = mDataProvider->metadata(); + if ( !dataProviderMetadata.isEmpty() ) + { + myMetadata += "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + tr( "Provider Metadata" ) + "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n"; + myMetadata += "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n"; + QMapIterator i( dataProviderMetadata ); + while ( i.hasNext() ) + { + i.next(); + myMetadata += "\n"; + } + myMetadata += QLatin1String( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + tr( "Metadata name" ) + "" + tr( "Metadata value" ) + "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + i.key() + ":" + i.value() + "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n" ); + } } // data source diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index fb371b40fdb2..084951fd3a72 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -1100,6 +1100,16 @@ bool QgsWFSProvider::changeAttributeValues( const QgsChangedAttributesMap &attr_ } } + +QMap QgsWFSProvider::metadata() +{ + QMap result; + result[tr( "Max Features" )] = mShared->mCaps.maxFeatures == 0 ? tr( "not provided" ) : QString( mShared->mCaps.maxFeatures ); + result[tr( "Supports Paging" )] = mShared->mCaps.supportsPaging ? tr( "supported" ) : tr( "unsupported" ); + result[tr( "Supports Joins" )] = mShared->mCaps.supportsJoins ? tr( "supported" ) : tr( "unsupported" ); + return result; +} + bool QgsWFSProvider::describeFeatureType( QString& geometryAttribute, QgsFields& fields, QgsWkbTypes::Type& geomType ) { fields.clear(); diff --git a/src/providers/wfs/qgswfsprovider.h b/src/providers/wfs/qgswfsprovider.h index bc9d3c9d0a40..3b1f29be50a9 100644 --- a/src/providers/wfs/qgswfsprovider.h +++ b/src/providers/wfs/qgswfsprovider.h @@ -132,6 +132,12 @@ class QgsWFSProvider : public QgsVectorDataProvider */ virtual bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ) override; + /** + * Get some metadata description of the provider. + * @return The provider metadata + */ + virtual QMap metadata(); + public slots: /** Reloads the data from the source. Needs to be implemented by providers with data caches to synchronize with changes in the data source*/ From 1fea20de504204456d38cdcebf89e56f6dea0218 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 14:27:17 +1000 Subject: [PATCH 652/897] Split handling of literal default values from provider side default value SQL clauses QgsVectorDataProvider now has two methods: - defaultValueClause: returns SQL fragment which must be evaluated by the provider to obtain the default value, eg sequence values - defaultValue: returns the literal constant default value for a field --- python/core/qgsvectordataprovider.sip | 15 ++++++++++-- src/app/qgisapp.cpp | 6 ++--- src/app/qgsfeatureaction.cpp | 2 +- src/app/qgsidentifyresultsdialog.cpp | 2 +- src/app/qgsmergeattributesdialog.cpp | 4 ++-- src/core/qgsofflineediting.cpp | 2 +- src/core/qgsvectordataprovider.cpp | 6 +++++ src/core/qgsvectordataprovider.h | 15 ++++++++++-- src/core/qgsvectorlayereditutils.cpp | 2 +- .../core/qgseditorwidgetfactory.cpp | 2 +- .../core/qgseditorwidgetwrapper.cpp | 2 +- src/providers/mssql/qgsmssqlprovider.cpp | 13 ++++------ src/providers/mssql/qgsmssqlprovider.h | 4 ++-- .../postgres/qgspostgresprovider.cpp | 24 ++++++++++++++----- src/providers/postgres/qgspostgresprovider.h | 1 + tests/src/python/test_provider_postgres.py | 23 ++++++++++++------ .../src/python/test_qgsrelationeditwidget.py | 4 ++-- 17 files changed, 87 insertions(+), 40 deletions(-) diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 3983d5e0b34d..ec2fdb56f79b 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -226,9 +226,20 @@ class QgsVectorDataProvider : QgsDataProvider const QMap &geometry_map ); /** - * Returns the default value for field specified by @c fieldId + * Returns any literal default values which are present at the provider for a specified + * field index. + * @see defaultValueClause() + */ + virtual QVariant defaultValue( int fieldIndex ) const; + + /** + * Returns any default value clauses which are present at the provider for a specified + * field index. These clauses are usually SQL fragments which must be evaluated by the + * provider, eg sequence values. + * @see defaultValue() + * @note added in QGIS 3.0 */ - virtual QVariant defaultValue( int fieldId ) const; + virtual QString defaultValueClause( int fieldIndex ) const; /** * Returns any constraints which are present at the provider for a specified diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index c1badc292667..bb3420536d60 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -6988,7 +6988,7 @@ void QgisApp::mergeAttributesOfSelectedFeatures() QgsField fld( vl->fields().at( i ) ); bool isDefaultValue = vl->fields().fieldOrigin( i ) == QgsFields::OriginProvider && vl->dataProvider() && - vl->dataProvider()->defaultValue( vl->fields().fieldOriginIndex( i ) ) == val; + vl->dataProvider()->defaultValueClause( vl->fields().fieldOriginIndex( i ) ) == val; // convert to destination data type if ( !isDefaultValue && !fld.convertCompatible( val ) ) @@ -7167,7 +7167,7 @@ void QgisApp::mergeSelectedFeatures() QVariant val = attrs.at( i ); bool isDefaultValue = vl->fields().fieldOrigin( i ) == QgsFields::OriginProvider && vl->dataProvider() && - vl->dataProvider()->defaultValue( vl->fields().fieldOriginIndex( i ) ) == val; + vl->dataProvider()->defaultValueClause( vl->fields().fieldOriginIndex( i ) ) == val; // convert to destination data type if ( !isDefaultValue && !vl->fields().at( i ).convertCompatible( val ) ) @@ -7481,7 +7481,7 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) } else { - defVal = pasteVectorLayer->dataProvider()->defaultValue( dst ); + defVal = pasteVectorLayer->dataProvider()->defaultValueClause( dst ); } if ( defVal.isValid() && !defVal.isNull() ) diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index c39dbd33f30e..9ebf573ed6e7 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -176,7 +176,7 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo } else { - v = provider->defaultValue( idx ); + v = provider->defaultValueClause( idx ); } mFeature->setAttribute( idx, v ); diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index d8da668f3641..885064847575 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -489,7 +489,7 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat QString defVal; if ( fields.fieldOrigin( i ) == QgsFields::OriginProvider && vlayer->dataProvider() ) - defVal = vlayer->dataProvider()->defaultValue( fields.fieldOriginIndex( i ) ).toString(); + defVal = vlayer->dataProvider()->defaultValueClause( fields.fieldOriginIndex( i ) ); QString value = defVal == attrs.at( i ) ? defVal : fields.at( i ).displayString( attrs.at( i ) ); QgsTreeWidgetItem *attrItem = new QgsTreeWidgetItem( QStringList() << QString::number( i ) << value ); diff --git a/src/app/qgsmergeattributesdialog.cpp b/src/app/qgsmergeattributesdialog.cpp index de37fa0cb86e..e04b586c36d2 100644 --- a/src/app/qgsmergeattributesdialog.cpp +++ b/src/app/qgsmergeattributesdialog.cpp @@ -540,7 +540,7 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const if ( !mVectorLayer->defaultValueExpression( fieldIdx ).isEmpty() ) results[fieldIdx] = mVectorLayer->defaultValue( fieldIdx, mFeatureList.at( 0 ), &context ); else if ( mVectorLayer->dataProvider() ) - results[fieldIdx] = mVectorLayer->dataProvider()->defaultValue( fieldIdx ); + results[fieldIdx] = mVectorLayer->dataProvider()->defaultValueClause( fieldIdx ); else results[fieldIdx] = QVariant(); continue; @@ -567,7 +567,7 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const } else if ( mVectorLayer->dataProvider() ) { - results[fieldIdx] = mVectorLayer->dataProvider()->defaultValue( fieldIdx ); + results[fieldIdx] = mVectorLayer->dataProvider()->defaultValueClause( fieldIdx ); } widgetIndex++; } diff --git a/src/core/qgsofflineediting.cpp b/src/core/qgsofflineediting.cpp index 6bd50c33b0da..8cf7d115959c 100644 --- a/src/core/qgsofflineediting.cpp +++ b/src/core/qgsofflineediting.cpp @@ -793,7 +793,7 @@ void QgsOfflineEditing::applyFeaturesAdded( QgsVectorLayer* offlineLayer, QgsVec if ( !remoteLayer->defaultValueExpression( k ).isEmpty() ) newAttrs[k] = remoteLayer->defaultValue( k, f, &context ); else if ( remoteFlds.fieldOrigin( k ) == QgsFields::OriginProvider ) - newAttrs[k] = remoteLayer->dataProvider()->defaultValue( remoteFlds.fieldOriginIndex( k ) ); + newAttrs[k] = remoteLayer->dataProvider()->defaultValueClause( remoteFlds.fieldOriginIndex( k ) ); } f.setAttributes( newAttrs ); diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index d84f7a1604dd..2b50b78e2990 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -98,6 +98,12 @@ QVariant QgsVectorDataProvider::defaultValue( int fieldId ) const return QVariant(); } +QString QgsVectorDataProvider::defaultValueClause( int fieldIndex ) const +{ + Q_UNUSED( fieldIndex ); + return QString(); +} + QgsFieldConstraints::Constraints QgsVectorDataProvider::fieldConstraints( int fieldIndex ) const { QgsFields f = fields(); diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index d6b78b157baf..9126b424743d 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -277,9 +277,20 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider const QgsGeometryMap &geometry_map ); /** - * Returns the default value for field specified by @c fieldId + * Returns any literal default values which are present at the provider for a specified + * field index. + * @see defaultValueClause() + */ + virtual QVariant defaultValue( int fieldIndex ) const; + + /** + * Returns any default value clauses which are present at the provider for a specified + * field index. These clauses are usually SQL fragments which must be evaluated by the + * provider, eg sequence values. + * @see defaultValue() + * @note added in QGIS 3.0 */ - virtual QVariant defaultValue( int fieldId ) const; + virtual QString defaultValueClause( int fieldIndex ) const; /** * Returns any constraints which are present at the provider for a specified diff --git a/src/core/qgsvectorlayereditutils.cpp b/src/core/qgsvectorlayereditutils.cpp index cb4962bb53fa..8a12b9372f89 100644 --- a/src/core/qgsvectorlayereditutils.cpp +++ b/src/core/qgsvectorlayereditutils.cpp @@ -381,7 +381,7 @@ int QgsVectorLayerEditUtils::splitFeatures( const QList& splitLine, bo QgsAttributes newAttributes = feat.attributes(); Q_FOREACH ( int pkIdx, L->dataProvider()->pkAttributeIndexes() ) { - const QVariant defaultValue = L->dataProvider()->defaultValue( pkIdx ); + const QVariant defaultValue = L->dataProvider()->defaultValueClause( pkIdx ); if ( !defaultValue.isNull() ) { newAttributes[ pkIdx ] = defaultValue; diff --git a/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp b/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp index 8d2d584c1ad4..a78e0371db50 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetfactory.cpp @@ -70,7 +70,7 @@ QString QgsEditorWidgetFactory::representValue( QgsVectorLayer* vl, int fieldIdx QString defVal; if ( vl->fields().fieldOrigin( fieldIdx ) == QgsFields::OriginProvider && vl->dataProvider() ) - defVal = vl->dataProvider()->defaultValue( vl->fields().fieldOriginIndex( fieldIdx ) ).toString(); + defVal = vl->dataProvider()->defaultValueClause( vl->fields().fieldOriginIndex( fieldIdx ) ); return value == defVal ? defVal : vl->fields().at( fieldIdx ).displayString( value ); } diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp index d12381f95d2a..54de6ac85056 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.cpp @@ -44,7 +44,7 @@ QgsField QgsEditorWidgetWrapper::field() const QVariant QgsEditorWidgetWrapper::defaultValue() const { - mDefaultValue = layer()->dataProvider()->defaultValue( mFieldIdx ); + mDefaultValue = layer()->dataProvider()->defaultValueClause( mFieldIdx ); return mDefaultValue; } diff --git a/src/providers/mssql/qgsmssqlprovider.cpp b/src/providers/mssql/qgsmssqlprovider.cpp index e5fc331968dd..d0cbd1f564e6 100644 --- a/src/providers/mssql/qgsmssqlprovider.cpp +++ b/src/providers/mssql/qgsmssqlprovider.cpp @@ -433,7 +433,7 @@ void QgsMssqlProvider::loadFields() if ( !query.value( 12 ).isNull() ) { - mDefaultValues.insert( i, query.value( 12 ) ); + mDefaultValues.insert( i, query.value( 12 ).toString() ); } ++i; } @@ -501,12 +501,9 @@ QString QgsMssqlProvider::quotedValue( const QVariant& value ) } } -QVariant QgsMssqlProvider::defaultValue( int fieldId ) const +QString QgsMssqlProvider::defaultValueClause( int fieldId ) const { - if ( mDefaultValues.contains( fieldId ) ) - return mDefaultValues[fieldId]; - else - return QVariant( QString::null ); + return mDefaultValues.value( fieldId, QString() ); } QString QgsMssqlProvider::storageType() const @@ -815,7 +812,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) if ( fld.name().isEmpty() ) continue; // invalid - if ( mDefaultValues.contains( i ) && mDefaultValues[i] == attrs.at( i ) ) + if ( mDefaultValues.contains( i ) && mDefaultValues.value( i ) == attrs.at( i ).toString() ) continue; // skip fields having default values if ( !first ) @@ -886,7 +883,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) if ( fld.name().isEmpty() ) continue; // invalid - if ( mDefaultValues.contains( i ) && mDefaultValues[i] == attrs.at( i ) ) + if ( mDefaultValues.contains( i ) && mDefaultValues.value( i ) == attrs.at( i ).toString() ) continue; // skip fields having default values QVariant::Type type = fld.type(); diff --git a/src/providers/mssql/qgsmssqlprovider.h b/src/providers/mssql/qgsmssqlprovider.h index 916cf6fc06a4..e995c1c99889 100644 --- a/src/providers/mssql/qgsmssqlprovider.h +++ b/src/providers/mssql/qgsmssqlprovider.h @@ -186,7 +186,7 @@ class QgsMssqlProvider : public QgsVectorDataProvider //! Convert values to quoted values for database work * static QString quotedValue( const QVariant& value ); - QVariant defaultValue( int fieldId ) const override; + QString defaultValueClause( int fieldId ) const override; //! Import a vector layer into the database static QgsVectorLayerImport::ImportError createEmptyLayer( @@ -212,7 +212,7 @@ class QgsMssqlProvider : public QgsVectorDataProvider //! Fields QgsFields mAttributeFields; - QMap mDefaultValues; + QMap mDefaultValues; mutable QgsMssqlGeometryParser mParser; diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 8c35fc122bbe..5e8da6a94d66 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1716,15 +1716,27 @@ bool QgsPostgresProvider::isValid() const return mValid; } +QString QgsPostgresProvider::defaultValueClause( int fieldId ) const +{ + QString defVal = mDefaultValues.value( fieldId, QString() ); + + if ( !providerProperty( EvaluateDefaultValues, false ).toBool() && !defVal.isEmpty() ) + { + return defVal; + } + + return QString(); +} + QVariant QgsPostgresProvider::defaultValue( int fieldId ) const { - QVariant defVal = mDefaultValues.value( fieldId, QString::null ); + QString defVal = mDefaultValues.value( fieldId, QString() ); - if ( providerProperty( EvaluateDefaultValues, false ).toBool() && !defVal.isNull() ) + if ( providerProperty( EvaluateDefaultValues, false ).toBool() && !defVal.isEmpty() ) { QgsField fld = field( fieldId ); - QgsPostgresResult res( connectionRO()->PQexec( QStringLiteral( "SELECT %1" ).arg( defVal.toString() ) ) ); + QgsPostgresResult res( connectionRO()->PQexec( QStringLiteral( "SELECT %1" ).arg( defVal ) ) ); if ( res.result() ) return convertValue( fld.type(), fld.subType(), res.PQgetvalue( 0, 0 ) ); @@ -1735,7 +1747,7 @@ QVariant QgsPostgresProvider::defaultValue( int fieldId ) const } } - return defVal; + return QVariant(); } QString QgsPostgresProvider::paramValue( const QString& fieldValue, const QString &defaultValue ) const @@ -1891,7 +1903,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) values += delim + QStringLiteral( "$%1" ).arg( defaultValues.size() + offset ); delim = ','; fieldId << idx; - defaultValues << defaultValue( idx ).toString(); + defaultValues << defaultValueClause( idx ); } } @@ -1928,7 +1940,7 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist ) insert += delim + quotedIdentifier( fieldname ); - QString defVal = defaultValue( idx ).toString(); + QString defVal = defaultValueClause( idx ); if ( i == flist.size() ) { diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index eb90e2d770db..6245b20535d7 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -160,6 +160,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } QgsAttributeList attributeIndexes() const override; QgsAttributeList pkAttributeIndexes() const override { return mPrimaryKeyAttrs; } + QString defaultValueClause( int fieldId ) const override; QVariant defaultValue( int fieldId ) const override; /** Adds a list of features diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 18ee6341b38e..97ddb8ab3f54 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -28,6 +28,7 @@ QgsTransactionGroup, QgsField, QgsFieldConstraints, + QgsDataProvider, NULL ) from qgis.gui import QgsEditorWidgetRegistry @@ -84,9 +85,17 @@ def partiallyCompiledFilters(self): # HERE GO THE PROVIDER SPECIFIC TESTS def testDefaultValue(self): - self.assertEqual(self.provider.defaultValue(0), 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)') + self.provider.setProviderProperty(QgsDataProvider.EvaluateDefaultValues, True) + self.assertTrue(isinstance(self.provider.defaultValue(0), int)) self.assertEqual(self.provider.defaultValue(1), NULL) - self.assertEqual(self.provider.defaultValue(2), '\'qgis\'::text') + self.assertEqual(self.provider.defaultValue(2), 'qgis') + self.provider.setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) + + def testDefaultValueClause(self): + self.provider.setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) + self.assertEqual(self.provider.defaultValueClause(0), 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)') + self.assertFalse(self.provider.defaultValueClause(1)) + self.assertEqual(self.provider.defaultValueClause(2), '\'qgis\'::text') def testDateTimeTypes(self): vl = QgsVectorLayer('%s table="qgis_test"."date_times" sql=' % (self.dbconn), "testdatetimes", "postgres") @@ -248,7 +257,7 @@ def testPktMapInsert(self): vl = QgsVectorLayer('{} table="qgis_test"."{}" key="obj_id" sql='.format(self.dbconn, 'oid_serial_table'), "oid_serial", "postgres") self.assertTrue(vl.isValid()) f = QgsFeature(vl.fields()) - f['obj_id'] = vl.dataProvider().defaultValue(0) + f['obj_id'] = vl.dataProvider().defaultValueClause(0) f['name'] = 'Test' r, f = vl.dataProvider().addFeatures([f]) self.assertTrue(r) @@ -553,17 +562,17 @@ def testKey(lyr, key, kfnames): oflds = olyr.fields() if key is None: # if the pkey was not given, it will create a pkey - self.assertEquals(oflds.size(), flds.size() + 1) - self.assertEquals(oflds[0].name(), kfnames[0]) + self.assertEqual(oflds.size(), flds.size() + 1) + self.assertEqual(oflds[0].name(), kfnames[0]) for i in range(flds.size()): self.assertEqual(oflds[i + 1].name(), flds[i].name()) else: # pkey was given, no extra field generated - self.assertEquals(oflds.size(), flds.size()) + self.assertEqual(oflds.size(), flds.size()) for i in range(oflds.size()): self.assertEqual(oflds[i].name(), flds[i].name()) pks = olyr.pkAttributeList() - self.assertEquals(len(pks), len(kfnames)) + self.assertEqual(len(pks), len(kfnames)) for i in range(0, len(kfnames)): self.assertEqual(oflds[pks[i]].name(), kfnames[i]) diff --git a/tests/src/python/test_qgsrelationeditwidget.py b/tests/src/python/test_qgsrelationeditwidget.py index b6e1c84f97f5..be4877519dbc 100644 --- a/tests/src/python/test_qgsrelationeditwidget.py +++ b/tests/src/python/test_qgsrelationeditwidget.py @@ -153,7 +153,7 @@ def test_link_feature(self): wrapper = self.createWrapper(self.vl_a, '"name"=\'Douglas Adams\'') # NOQA f = QgsFeature(self.vl_b.fields()) - f.setAttributes([self.vl_b.dataProvider().defaultValue(0), 'The Hitchhiker\'s Guide to the Galaxy']) + f.setAttributes([self.vl_b.dataProvider().defaultValueClause(0), 'The Hitchhiker\'s Guide to the Galaxy']) self.vl_b.addFeature(f) def choose_linked_feature(): @@ -318,7 +318,7 @@ def addFeature(self, layer, defaultValues, defaultGeometry): if v: values.append(v) else: - values.append(layer.dataProvider().defaultValue(i)) + values.append(layer.dataProvider().defaultValueClause(i)) f = QgsFeature(layer.fields()) f.setAttributes(self.values) f.setGeometry(defaultGeometry) From 0ae610c5e3dd364385c2fd91f901e706a04101f1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 14:33:44 +1000 Subject: [PATCH 653/897] [FEATURE] Detect literal default values for spatialite provider --- .../spatialite/qgsspatialiteprovider.cpp | 46 ++++++++++++++++++- .../spatialite/qgsspatialiteprovider.h | 7 +++ tests/src/python/test_provider_spatialite.py | 14 ++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index dad23c26909c..e483b43a8d6c 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -684,6 +684,7 @@ void QgsSpatiaLiteProvider::loadFieldsAbstractInterface( gaiaVectorLayerPtr lyr mAttributeFields.clear(); mPrimaryKey.clear(); // cazzo cazzo cazzo mPrimaryKeyAttrs.clear(); + mDefaultValues.clear(); gaiaLayerAttributeFieldPtr fld = lyr->First; if ( !fld ) @@ -729,6 +730,8 @@ void QgsSpatiaLiteProvider::loadFieldsAbstractInterface( gaiaVectorLayerPtr lyr for ( int i = 1; i <= rows; i++ ) { QString name = QString::fromUtf8( results[( i * columns ) + 1] ); + insertDefaultValue( i - 1, QString::fromUtf8( results[( i * columns ) + 4] ) ); + QString pk = results[( i * columns ) + 5]; QString type = results[( i * columns ) + 2]; type = type.toLower(); @@ -870,6 +873,37 @@ void QgsSpatiaLiteProvider::fetchConstraints() } +void QgsSpatiaLiteProvider::insertDefaultValue( int fieldIndex, QString defaultVal ) +{ + if ( !defaultVal.isEmpty() ) + { + QVariant defaultVariant; + switch ( mAttributeFields.at( fieldIndex ).type() ) + { + case QVariant::LongLong: + defaultVariant = defaultVal.toLongLong(); + break; + + case QVariant::Double: + defaultVariant = defaultVal.toDouble(); + break; + + default: + { + if ( defaultVal.startsWith( '\'' ) ) + defaultVal = defaultVal.remove( 0, 1 ); + if ( defaultVal.endsWith( '\'' ) ) + defaultVal.chop( 1 ); + defaultVal.replace( "''", "'" ); + + defaultVariant = defaultVal; + break; + } + } + mDefaultValues.insert( fieldIndex, defaultVariant ); + } +} + void QgsSpatiaLiteProvider::loadFields() { int ret; @@ -884,6 +918,7 @@ void QgsSpatiaLiteProvider::loadFields() QString sql; mAttributeFields.clear(); + mDefaultValues.clear(); if ( !mIsQuery ) { @@ -921,6 +956,8 @@ void QgsSpatiaLiteProvider::loadFields() const TypeSubType fieldType = getVariantType( type ); mAttributeFields.append( QgsField( name, fieldType.first, type, 0, 0, QString(), fieldType.second ) ); } + + insertDefaultValue( i - 1, QString::fromUtf8( results[( i * columns ) + 4] ) ); } } sqlite3_free_table( results ); @@ -3820,8 +3857,10 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist ) } else if ( type == QVariant::String ) { + QString stringVal = v.toString(); + // binding a TEXT value - QByteArray ba = v.toString().toUtf8(); + QByteArray ba = stringVal.toUtf8(); sqlite3_bind_text( stmt, ++ia, ba.constData(), ba.size(), SQLITE_TRANSIENT ); } else if ( type == QVariant::StringList || type == QVariant::List ) @@ -4229,6 +4268,11 @@ QgsVectorDataProvider::Capabilities QgsSpatiaLiteProvider::capabilities() const return mEnabledCapabilities; } +QVariant QgsSpatiaLiteProvider::defaultValue( int fieldId ) const +{ + return mDefaultValues.value( fieldId, QVariant() ); +} + void QgsSpatiaLiteProvider::closeDb() { // trying to close the SQLite DB diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 94295d200172..f1dabd4e743c 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -165,6 +165,8 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider //! Returns a bitmask containing the supported capabilities QgsVectorDataProvider::Capabilities capabilities() const override; + QVariant defaultValue( int fieldId ) const override; + /** The SpatiaLite provider does its own transforms so we return * true for the following three functions to indicate that transforms * should not be handled by the QgsCoordinateTransform object. See the @@ -338,6 +340,9 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider //! Name of the geometry column in the table QString mGeometryColumn; + //! Map of field index to default value + QMap mDefaultValues; + //! Name of the SpatialIndex table QString mIndexTable; @@ -448,6 +453,8 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider void fetchConstraints(); + void insertDefaultValue( int fieldIndex, QString defaultVal ); + enum GEOS_3D { GEOS_3D_POINT = -2147483647, diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index f0d38b13f6c3..bf5fb4819a70 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -139,6 +139,10 @@ def setUpClass(cls): sql = "CREATE TABLE test_constraints(id INTEGER PRIMARY KEY, num INTEGER NOT NULL, desc TEXT UNIQUE, desc2 TEXT, num2 INTEGER NOT NULL UNIQUE)" cur.execute(sql) + # simple table with defaults + sql = "CREATE TABLE test_defaults (id INTEGER NOT NULL PRIMARY KEY, name TEXT DEFAULT 'qgis ''is good', number INTEGER DEFAULT 5, number2 REAL DEFAULT 5.7, no_default REAL)" + cur.execute(sql) + cur.execute("COMMIT") con.close() @@ -461,6 +465,16 @@ def XXXXXtestLocking(self): self.assertTrue(vl.commitChanges()) + def testDefaultValues(self): + + l = QgsVectorLayer("dbname=%s table='test_defaults' key='id'" % self.dbname, "test_defaults", "spatialite") + self.assertTrue(l.isValid()) + + self.assertEqual(l.dataProvider().defaultValue(1), "qgis 'is good") + self.assertEqual(l.dataProvider().defaultValue(2), 5) + self.assertEqual(l.dataProvider().defaultValue(3), 5.7) + self.assertFalse(l.dataProvider().defaultValue(4)) + if __name__ == '__main__': unittest.main() From b0bd61f308333381b832d8b7961dfd714e76338f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 15:10:17 +1000 Subject: [PATCH 654/897] [FEATURE] Detect default literal values from OGR layers Requires GDAL >= 2 --- src/providers/ogr/qgsogrprovider.cpp | 36 ++++++++++++++++ src/providers/ogr/qgsogrprovider.h | 7 +++ tests/src/python/test_provider_ogr_sqlite.py | 45 +++++++++++++++++++- 3 files changed, 87 insertions(+), 1 deletion(-) diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 935a8507ded3..1adc5f3efb4f 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -840,6 +840,7 @@ void QgsOgrProvider::loadFields() QgsOgrConnPool::instance()->invalidateConnections( dataSourceUri() ); //the attribute fields need to be read again when the encoding changes mAttributeFields.clear(); + mDefaultValues.clear(); if ( !ogrLayer ) return; @@ -947,6 +948,13 @@ void QgsOgrProvider::loadFields() constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); newField.setConstraints( constraints ); } + + // check if field has default value + QString defaultValue = textEncoding()->toUnicode( OGR_Fld_GetDefault( fldDef ) ); + if ( !defaultValue.isEmpty() && !OGR_Fld_IsDefaultDriverSpecific( fldDef ) ) + { + mDefaultValues.insert( i + ( mFirstFieldIsFid ? 1 : 0 ), defaultValue ); + } #endif mAttributeFields.append( newField ); @@ -1081,6 +1089,34 @@ QgsRectangle QgsOgrProvider::extent() const return mExtentRect; } +QVariant QgsOgrProvider::defaultValue( int fieldId ) const +{ + if ( fieldId < 0 || fieldId >= mAttributeFields.count() ) + return QVariant(); + + QString defaultVal = mDefaultValues.value( fieldId, QString() ); + if ( defaultVal.isEmpty() ) + return QVariant(); + + QVariant resultVar = defaultVal; + if ( defaultVal == QStringLiteral( "CURRENT_TIMESTAMP" ) ) + resultVar = QDateTime::currentDateTime(); + else if ( defaultVal == QStringLiteral( "CURRENT_DATE" ) ) + resultVar = QDate::currentDate(); + else if ( defaultVal == QStringLiteral( "CURRENT_TIME" ) ) + resultVar = QTime::currentTime(); + else if ( defaultVal.startsWith( '\'' ) ) + { + defaultVal = defaultVal.remove( 0, 1 ); + defaultVal.chop( 1 ); + defaultVal.replace( "''", "'" ); + resultVar = defaultVal; + } + + ( void )mAttributeFields.at( fieldId ).convertCompatible( resultVar ); + return resultVar; +} + void QgsOgrProvider::updateExtents() { invalidateCachedExtent( true ); diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index d4fea242a7b1..5557f7ac6c5a 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -124,6 +124,8 @@ class QgsOgrProvider : public QgsVectorDataProvider virtual QgsRectangle extent() const override; + QVariant defaultValue( int fieldId ) const override; + /** Update the extents */ virtual void updateExtents() override; @@ -297,7 +299,12 @@ class QgsOgrProvider : public QgsVectorDataProvider private: unsigned char *getGeometryPointer( OGRFeatureH fet ); QString ogrWkbGeometryTypeName( OGRwkbGeometryType type ) const; + QgsFields mAttributeFields; + + //! Map of field index to default value + QMap mDefaultValues; + bool mFirstFieldIsFid; OGRDataSourceH ogrDataSource; mutable OGREnvelope* mExtent; diff --git a/tests/src/python/test_provider_ogr_sqlite.py b/tests/src/python/test_provider_ogr_sqlite.py index f83cf762da8c..de54b2983326 100644 --- a/tests/src/python/test_provider_ogr_sqlite.py +++ b/tests/src/python/test_provider_ogr_sqlite.py @@ -20,9 +20,10 @@ import glob from osgeo import gdal, ogr -from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest, QgsField, QgsFieldConstraints +from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsFeatureRequest, QgsField, QgsFieldConstraints, NULL from qgis.testing import start_app, unittest from utilities import unitTestDataPath +from qgis.PyQt.QtCore import QDate, QTime, QDateTime start_app() @@ -160,6 +161,48 @@ def testNotNullConstraint(self): self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) + @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 0)) + def testDefaultValues(self): + """ test detection of defaults on OGR layer """ + + tmpfile = os.path.join(self.basetestpath, 'testDefaults.sqlite') + ds = ogr.GetDriverByName('SQLite').CreateDataSource(tmpfile) + lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, options=['FID=fid']) + lyr.CreateField(ogr.FieldDefn('field1', ogr.OFTInteger)) + fld2 = ogr.FieldDefn('field2', ogr.OFTInteger) + fld2.SetDefault('5') + lyr.CreateField(fld2) + fld3 = ogr.FieldDefn('field3', ogr.OFTString) + fld3.SetDefault("'some ''default'") + lyr.CreateField(fld3) + fld4 = ogr.FieldDefn('field4', ogr.OFTDate) + fld4.SetDefault("CURRENT_DATE") + lyr.CreateField(fld4) + fld5 = ogr.FieldDefn('field5', ogr.OFTTime) + fld5.SetDefault("CURRENT_TIME") + lyr.CreateField(fld5) + fld6 = ogr.FieldDefn('field6', ogr.OFTDateTime) + fld6.SetDefault("CURRENT_TIMESTAMP") + lyr.CreateField(fld6) + + ds = None + + vl = QgsVectorLayer('{}'.format(tmpfile), 'test', 'ogr') + self.assertTrue(vl.isValid()) + + # test some bad indexes + self.assertFalse(vl.dataProvider().defaultValue(-1)) + self.assertFalse(vl.dataProvider().defaultValue(1001)) + + # test default + self.assertEqual(vl.dataProvider().defaultValue(1), NULL) + self.assertEqual(vl.dataProvider().defaultValue(2), 5) + self.assertEqual(vl.dataProvider().defaultValue(3), "some 'default") + self.assertEqual(vl.dataProvider().defaultValue(4), QDate.currentDate()) + # time may pass, so we allow 1 second difference here + self.assertTrue(vl.dataProvider().defaultValue(5).secsTo(QTime.currentTime()) < 1) + self.assertTrue(vl.dataProvider().defaultValue(6).secsTo(QDateTime.currentDateTime()) < 1) + if __name__ == '__main__': unittest.main() From 94413c38fde960db4949f4ceb3d8c91ac01081a4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 15:40:05 +1000 Subject: [PATCH 655/897] Show literal defaults in add feature form --- src/app/qgsfeatureaction.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index 9ebf573ed6e7..9c7f4990b602 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -176,7 +176,17 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo } else { - v = provider->defaultValueClause( idx ); + QVariant defaultLiteral = mLayer->dataProvider()->defaultValue( idx ); + if ( defaultLiteral.isValid() ) + { + v = defaultLiteral; + } + else + { + QString defaultClause = provider->defaultValueClause( idx ); + if ( !defaultClause.isEmpty() ) + v = defaultClause; + } } mFeature->setAttribute( idx, v ); From 11405af0676ca7d66cebb6c5d1d9f7bd4d8a6dc4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 7 Nov 2016 15:40:23 +1000 Subject: [PATCH 656/897] Fix range widget wrapper not correctly respecting default allow null setting --- src/gui/editorwidgets/qgsrangewidgetwrapper.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp b/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp index 14f0112e66b2..0d584fc70601 100644 --- a/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp +++ b/src/gui/editorwidgets/qgsrangewidgetwrapper.cpp @@ -175,7 +175,7 @@ QVariant QgsRangeWidgetWrapper::value() const if ( mDoubleSpinBox ) { value = mDoubleSpinBox->value(); - if ( value == mDoubleSpinBox->minimum() && config( QStringLiteral( "AllowNull" ) ).toBool() ) + if ( value == mDoubleSpinBox->minimum() && config( QStringLiteral( "AllowNull" ), true ).toBool() ) { value = QVariant( field().type() ); } @@ -183,7 +183,7 @@ QVariant QgsRangeWidgetWrapper::value() const else if ( mIntSpinBox ) { value = mIntSpinBox->value(); - if ( value == mIntSpinBox->minimum() && config( QStringLiteral( "AllowNull" ) ).toBool() ) + if ( value == mIntSpinBox->minimum() && config( QStringLiteral( "AllowNull" ), true ).toBool() ) { value = QVariant( field().type() ); } @@ -212,7 +212,7 @@ void QgsRangeWidgetWrapper::setValue( const QVariant& value ) { if ( mDoubleSpinBox ) { - if ( value.isNull() && config( QStringLiteral( "AllowNull" ) ).toBool() ) + if ( value.isNull() && config( QStringLiteral( "AllowNull" ), true ).toBool() ) { mDoubleSpinBox->setValue( mDoubleSpinBox->minimum() ); } @@ -224,7 +224,7 @@ void QgsRangeWidgetWrapper::setValue( const QVariant& value ) if ( mIntSpinBox ) { - if ( value.isNull() && config( QStringLiteral( "AllowNull" ) ).toBool() ) + if ( value.isNull() && config( QStringLiteral( "AllowNull" ), true ).toBool() ) { mIntSpinBox->setValue( mIntSpinBox->minimum() ); } From 0fbcc4b95d310e2223a805fac4e10d726ea8f9eb Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 4 Nov 2016 15:41:04 +0700 Subject: [PATCH 657/897] [FEATURE] upgrade the substr() function - support negative start value (e.g. substr('hello',-2) returns 'lo') - support negative length value (e.g. substr('hello',3,-1) returns 'll') - length parameter now optional, defaults to end of string (e.g. substr('hello world',7) returns 'world') --- resources/function_help/json/substr | 14 +++++-- src/core/qgsexpression.cpp | 55 +++++++++++++++++++++++++--- tests/src/core/testqgsexpression.cpp | 5 ++- 3 files changed, 63 insertions(+), 11 deletions(-) diff --git a/resources/function_help/json/substr b/resources/function_help/json/substr index f474b32b353e..c07a2c900b4b 100644 --- a/resources/function_help/json/substr +++ b/resources/function_help/json/substr @@ -2,9 +2,15 @@ "name": "substr", "type": "function", "description": "Returns a part of a string.", - "arguments": [ {"arg":"input_string","description":"the full input string"}, - {"arg":"startpos","description":"integer representing start position to extract from"}, - {"arg":"length","description":"integer representing length of string to extract"} + "arguments": [ {"arg":"string","description":"the full input string"}, + {"arg":"start","description":"integer representing start position to extract from; if start is negative, the return string will begin at the end of the string minus the start value"}, + {"arg":"length","optional":true,"description":"integer representing length of string to extract; if length is negative, the return string will omit the given length of characters from the end of the string"} ], - "examples": [ { "expression":"substr('HELLO WORLD',3,5)", "returns":"'LLO W'"}] + "examples": [ { "expression":"substr('HELLO WORLD',3,5)", "returns":"'LLO W'"}, + { "expression":"substr('HELLO WORLD',6)", "returns":"'WORLD'"}, + { "expression":"substr('HELLO WORLD',-5)","returns":"'WORLD'"}, + { "expression":"substr('HELLO',3,-1)", "returns":"'LL'"}, + { "expression":"substr('HELLO WORLD',-5,2)","returns":"'WO'"}, + { "expression":"substr('HELLO WORLD',-5,-1)","returns":"'WORL'"} + ] } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index f7ee2242380a..b4c4e11b44e8 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1398,12 +1398,55 @@ static QVariant fcnUuid( const QVariantList&, const QgsExpressionContext*, QgsEx return QUuid::createUuid().toString(); } -static QVariant fcnSubstr( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +static QVariant fcnSubstr( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ) { - QString str = getStringValue( values.at( 0 ), parent ); - int from = getIntValue( values.at( 1 ), parent ); - int len = getIntValue( values.at( 2 ), parent ); - return QVariant( str.mid( from -1, len ) ); + + QgsExpression::Node* node; + + node = getNode( values.at( 0 ), parent ); + ENSURE_NO_EVAL_ERROR; + QString str = node->eval( parent, context ).toString(); + + node = getNode( values.at( 1 ), parent ); + ENSURE_NO_EVAL_ERROR; + int from = node->eval( parent, context ).toInt(); + + node = getNode( values.at( 2 ), parent ); + QVariant value = node->eval( parent, context ); + int len; + if ( value.isValid() ) + { + len = value.toInt(); + } + else + { + len = str.size(); + } + + if ( from < 0 ) + { + from = str.size() + from; + if ( from < 0 ) + { + from = 0; + } + } + else if ( from > 0 ) + { + //account for the fact that substr() starts at 1 + from -= 1; + } + + if ( len < 0 ) + { + len = str.size() + len - from; + if ( len < 0 ) + { + len = 0; + } + } + + return QVariant( str.mid( from, len ) ); } static QVariant fcnFeatureId( const QVariantList&, const QgsExpressionContext* context, QgsExpression* ) { @@ -3804,7 +3847,7 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "replace" ), -1, fcnReplace, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "regexp_replace" ), 3, fcnRegexpReplace, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "regexp_substr" ), 2, fcnRegexpSubstr, QStringLiteral( "String" ) ) - << new StaticFunction( QStringLiteral( "substr" ), 3, fcnSubstr, QStringLiteral( "String" ) ) + << new StaticFunction( QStringLiteral( "substr" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "start " ) ) << Parameter( QStringLiteral( "length" ), true ), fcnSubstr, QStringLiteral( "String" ), QString(), False, QSet(), true ) << new StaticFunction( QStringLiteral( "concat" ), -1, fcnConcat, QStringLiteral( "String" ), QString(), false, QSet(), false, QStringList(), true ) << new StaticFunction( QStringLiteral( "strpos" ), 2, fcnStrpos, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "left" ), 2, fcnLeft, QStringLiteral( "String" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index e228b32442c1..34a9e2de2d44 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -836,7 +836,10 @@ class TestQgsExpression: public QObject QTest::newRow( "regexp_replace cap group" ) << "regexp_replace('HeLLo','(eL)', 'x\\\\1x')" << false << QVariant( "HxeLxLo" ); QTest::newRow( "regexp_replace invalid" ) << "regexp_replace('HeLLo','[[[', '-')" << true << QVariant(); QTest::newRow( "substr" ) << "substr('HeLLo', 3,2)" << false << QVariant( "LL" ); - QTest::newRow( "substr outside" ) << "substr('HeLLo', -5,2)" << false << QVariant( "" ); + QTest::newRow( "substr negative start" ) << "substr('HeLLo', -4)" << false << QVariant( "eLLo" ); + QTest::newRow( "substr negative length" ) << "substr('HeLLo', 1,-3)" << false << QVariant( "He" ); + QTest::newRow( "substr positive start and negative length" ) << "substr('HeLLo', 3,-1)" << false << QVariant( "LL" ); + QTest::newRow( "substr start only" ) << "substr('HeLLo', 3)" << false << QVariant( "LLo" ); QTest::newRow( "regexp_substr" ) << "regexp_substr('abc123','(\\\\d+)')" << false << QVariant( "123" ); QTest::newRow( "regexp_substr non-greedy" ) << "regexp_substr('abc123','(\\\\d+?)')" << false << QVariant( "1" ); QTest::newRow( "regexp_substr no hit" ) << "regexp_substr('abcdef','(\\\\d+)')" << false << QVariant( "" ); From ec551618667ed0e042e845edadf455a9a4636eac Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 08:39:17 +1000 Subject: [PATCH 658/897] Avoid lazy evaluation for substr expression function Better solution is to set handlesNull to true to avoid the default null parameter = null result behaviour, and handle null values in params 1 and 2 manually --- src/core/qgsexpression.cpp | 30 ++++++++++------------------ tests/src/core/testqgsexpression.cpp | 2 ++ 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index b4c4e11b44e8..63c34acfe0f7 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1398,30 +1398,19 @@ static QVariant fcnUuid( const QVariantList&, const QgsExpressionContext*, QgsEx return QUuid::createUuid().toString(); } -static QVariant fcnSubstr( const QVariantList& values, const QgsExpressionContext* context, QgsExpression* parent ) +static QVariant fcnSubstr( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { + if ( !values.at( 0 ).isValid() || !values.at( 1 ).isValid() ) + return QVariant(); - QgsExpression::Node* node; - - node = getNode( values.at( 0 ), parent ); - ENSURE_NO_EVAL_ERROR; - QString str = node->eval( parent, context ).toString(); - - node = getNode( values.at( 1 ), parent ); - ENSURE_NO_EVAL_ERROR; - int from = node->eval( parent, context ).toInt(); + QString str = getStringValue( values.at( 0 ), parent ); + int from = getIntValue( values.at( 1 ), parent ); - node = getNode( values.at( 2 ), parent ); - QVariant value = node->eval( parent, context ); - int len; - if ( value.isValid() ) - { - len = value.toInt(); - } + int len = 0; + if ( values.at( 2 ).isValid() ) + len = getIntValue( values.at( 2 ), parent ); else - { len = str.size(); - } if ( from < 0 ) { @@ -3847,7 +3836,8 @@ const QList& QgsExpression::Functions() << new StaticFunction( QStringLiteral( "replace" ), -1, fcnReplace, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "regexp_replace" ), 3, fcnRegexpReplace, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "regexp_substr" ), 2, fcnRegexpSubstr, QStringLiteral( "String" ) ) - << new StaticFunction( QStringLiteral( "substr" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "start " ) ) << Parameter( QStringLiteral( "length" ), true ), fcnSubstr, QStringLiteral( "String" ), QString(), False, QSet(), true ) + << new StaticFunction( QStringLiteral( "substr" ), ParameterList() << Parameter( QStringLiteral( "string" ) ) << Parameter( QStringLiteral( "start " ) ) << Parameter( QStringLiteral( "length" ), true ), fcnSubstr, QStringLiteral( "String" ), QString(), + false, QSet< QString >(), false, QStringList(), true ) << new StaticFunction( QStringLiteral( "concat" ), -1, fcnConcat, QStringLiteral( "String" ), QString(), false, QSet(), false, QStringList(), true ) << new StaticFunction( QStringLiteral( "strpos" ), 2, fcnStrpos, QStringLiteral( "String" ) ) << new StaticFunction( QStringLiteral( "left" ), 2, fcnLeft, QStringLiteral( "String" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 34a9e2de2d44..3a90515f8da3 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -840,6 +840,8 @@ class TestQgsExpression: public QObject QTest::newRow( "substr negative length" ) << "substr('HeLLo', 1,-3)" << false << QVariant( "He" ); QTest::newRow( "substr positive start and negative length" ) << "substr('HeLLo', 3,-1)" << false << QVariant( "LL" ); QTest::newRow( "substr start only" ) << "substr('HeLLo', 3)" << false << QVariant( "LLo" ); + QTest::newRow( "substr null value" ) << "substr(NULL, 3,2)" << false << QVariant(); + QTest::newRow( "substr null start" ) << "substr('Hello',NULL,2)" << false << QVariant(); QTest::newRow( "regexp_substr" ) << "regexp_substr('abc123','(\\\\d+)')" << false << QVariant( "123" ); QTest::newRow( "regexp_substr non-greedy" ) << "regexp_substr('abc123','(\\\\d+?)')" << false << QVariant( "1" ); QTest::newRow( "regexp_substr no hit" ) << "regexp_substr('abcdef','(\\\\d+)')" << false << QVariant( "" ); From f8bda8dbfcd83f750f15941569cfb85ec7f235be Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 08:41:52 +1000 Subject: [PATCH 659/897] Avoid crash in testqgsexpression.cpp --- tests/src/core/testqgsexpression.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 3a90515f8da3..0086c5bae683 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -1096,6 +1096,9 @@ class TestQgsExpression: public QObject case QVariant::Time: QCOMPARE( result.toTime(), expected.toTime() ); break; + case QVariant::List: + QCOMPARE( result.toList(), expected.toList() ); + break; case QVariant::UserType: { if ( result.userType() == qMetaTypeId() ) From fd15090521a051336766d8bfad34a5cebf3e6f98 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 08:51:22 +1000 Subject: [PATCH 660/897] Update identation --- .../db_manager/db_plugins/gpkg/connector.py | 18 +++++++++--------- .../processing/modeler/EditModelAction.py | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/python/plugins/db_manager/db_plugins/gpkg/connector.py b/python/plugins/db_manager/db_plugins/gpkg/connector.py index 98fe456eafc1..a08eefcebc57 100644 --- a/python/plugins/db_manager/db_plugins/gpkg/connector.py +++ b/python/plugins/db_manager/db_plugins/gpkg/connector.py @@ -350,18 +350,18 @@ def getVectorTables(self, schema=None): if geomtype == ogr.wkbNone: item = list([Table.TableType, - lyr.GetName(), - False, # is_view + lyr.GetName(), + False, # is_view ]) else: item = list([Table.VectorType, - lyr.GetName(), - False, # is_view - lyr.GetName(), - lyr.GetGeometryColumn(), - geomname, - geomdim, - srid]) + lyr.GetName(), + False, # is_view + lyr.GetName(), + lyr.GetGeometryColumn(), + geomname, + geomdim, + srid]) items.append(item) return items diff --git a/python/plugins/processing/modeler/EditModelAction.py b/python/plugins/processing/modeler/EditModelAction.py index b3942d068992..e7693fec8ae7 100644 --- a/python/plugins/processing/modeler/EditModelAction.py +++ b/python/plugins/processing/modeler/EditModelAction.py @@ -45,4 +45,4 @@ def execute(self): dlg.show() def updateModel(self): - algList.reloadProvider('model') \ No newline at end of file + algList.reloadProvider('model') From 3b30701780c509e120532b43f49b1b14a7b0f975 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 08:52:39 +1000 Subject: [PATCH 661/897] Prepare commit ensures empty line before doxygen block --- scripts/astyle.sh | 1 + scripts/doxygen_space.pl | 29 +++++++++++++++++++++++++++++ scripts/remove_temporary_files.sh | 1 + 3 files changed, 31 insertions(+) create mode 100755 scripts/doxygen_space.pl diff --git a/scripts/astyle.sh b/scripts/astyle.sh index 9de9aea0197a..b3db9fa9877b 100755 --- a/scripts/astyle.sh +++ b/scripts/astyle.sh @@ -65,6 +65,7 @@ astyleit() { modified=$1.unify_includes_modified cp "$1" "$modified" scripts/unify_includes.pl "$modified" + scripts/doxygen_space.pl "$modified" diff "$1" "$modified" >/dev/null || mv "$modified" "$1" rm -f "$modified" } diff --git a/scripts/doxygen_space.pl b/scripts/doxygen_space.pl new file mode 100755 index 000000000000..e6df259c0d99 --- /dev/null +++ b/scripts/doxygen_space.pl @@ -0,0 +1,29 @@ +#!/usr/bin/perl -0 -i.sortinc -n +########################################################################### +# doxygen_space.pl +# --------------------- +# begin : October 2016 +# copyright : (C) 2016 by Nyall Dawson +# email : nyall dot dawson at gmail dot com +# +########################################################################### +# # +# This program is free software; you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation; either version 2 of the License, or # +# (at your option) any later version. # +# # +########################################################################### + +# adapted from scripts/sort_includes.sh + +# this is slurped in whole-file mode, as opposed to unify_incudes.pl +# which slurps in per-line mode + +use strict; +use warnings; + +# Space around doxygen start blocks (force blank line before /**) +s#(? Date: Tue, 8 Nov 2016 08:53:19 +1000 Subject: [PATCH 662/897] Add another file to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 2a91bfa058aa..c9dd91d7e983 100644 --- a/.gitignore +++ b/.gitignore @@ -66,4 +66,5 @@ tests/testdata/raster/band3_int16_noct_epsg4326.tif.aux.xml python/plugins/processing/tests/testdata/custom/grass7/float_raster.tif.aux.xml python/plugins/processing/tests/testdata/custom/grass7/raster_1class.tif.aux.xml python/plugins/processing/tests/testdata/dem.tif.aux.xml +python/plugins/processing/tests/testdata/raster.tif.aux.xml Thumb.db From 32b1603c810ad16a9caaec055c2bf5473dce2347 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 08:57:51 +1000 Subject: [PATCH 663/897] Update indentation --- .../interpolation/DualEdgeTriangulation.h | 1 + src/analysis/interpolation/NormVecDecorator.h | 2 + src/analysis/interpolation/ParametricLine.h | 1 + src/analysis/interpolation/qgsinterpolator.h | 2 + .../interpolation/qgstininterpolator.h | 1 + src/analysis/network/qgsarcproperter.h | 1 + src/analysis/network/qgsgraph.h | 2 + src/analysis/network/qgsgraphanalyzer.h | 1 + src/analysis/network/qgsgraphbuilder.h | 1 + src/analysis/network/qgsgraphbuilderintr.h | 1 + .../network/qgslinevectorlayerdirector.h | 1 + src/analysis/openstreetmap/qgsosmbase.h | 1 + src/analysis/openstreetmap/qgsosmdatabase.h | 2 + src/analysis/raster/qgsninecellfilter.h | 3 ++ src/analysis/raster/qgsrelief.h | 4 ++ src/analysis/raster/qgsruggednessfilter.h | 1 + src/analysis/raster/qgstotalcurvaturefilter.h | 1 + src/analysis/vector/qgsgeometryanalyzer.h | 2 + src/analysis/vector/qgstransectsample.h | 1 + src/app/composer/qgscomposeritemwidget.h | 1 + src/app/composer/qgscomposermanager.h | 1 + src/app/nodetool/qgsmaptoolnodetool.h | 1 + src/app/nodetool/qgsselectedfeature.h | 1 + src/app/ogr/qgsvectorlayersaveasdialog.h | 1 + src/app/qgisapp.cpp | 4 ++ src/app/qgisapp.h | 39 +++++++++++++++++++ src/app/qgisappinterface.h | 9 +++++ src/app/qgisappstylesheet.h | 1 + src/app/qgsattributetabledialog.h | 17 ++++++++ src/app/qgsattributetypedialog.h | 1 + src/app/qgsdecorationgrid.h | 3 ++ src/app/qgsdisplayangle.h | 1 + src/app/qgsmaptooladdfeature.h | 1 + src/app/qgsmaptoollabel.h | 5 +++ src/app/qgsmaptoolselectutils.h | 1 + src/app/qgsmergeattributesdialog.h | 1 + src/app/qgsoptions.h | 1 + src/app/qgspluginmetadata.h | 1 + src/app/qgsrasterlayerproperties.h | 1 + src/app/qgstipfactory.h | 4 ++ src/app/qgsversioninfo.h | 1 + src/core/auth/qgsauthconfig.h | 6 +++ src/core/auth/qgsauthmanager.h | 1 + src/core/auth/qgsauthmethod.h | 1 + src/core/auth/qgsauthmethodmetadata.h | 1 + src/core/auth/qgsauthmethodregistry.h | 2 + src/core/composer/qgsatlascomposition.h | 1 + src/core/composer/qgscomposerarrow.h | 3 ++ src/core/composer/qgscomposeritem.h | 5 +++ src/core/composer/qgscomposeritemgroup.h | 1 + src/core/composer/qgscomposerlabel.h | 4 ++ src/core/composer/qgscomposerlegend.h | 1 + src/core/composer/qgscomposerlegenditem.h | 1 + src/core/composer/qgscomposermap.h | 5 +++ src/core/composer/qgscomposerobject.h | 2 + src/core/composer/qgscomposerscalebar.h | 3 ++ src/core/composer/qgscomposershape.h | 3 ++ src/core/composer/qgscomposition.h | 2 + src/core/composer/qgsscalebarstyle.h | 1 + src/core/diagram/qgsdiagram.h | 1 + src/core/effects/qgsimageoperation.h | 3 ++ src/core/geometry/qgsabstractgeometry.h | 1 + src/core/geometry/qgscircularstring.h | 3 ++ src/core/geometry/qgscompoundcurve.h | 2 + src/core/geometry/qgscurvepolygon.h | 2 + src/core/geometry/qgsgeometryeditutils.h | 1 + src/core/geometry/qgsgeometryfactory.h | 1 + src/core/geometry/qgsgeos.h | 1 + src/core/geometry/qgsinternalgeometryengine.h | 1 + src/core/geometry/qgslinestring.h | 1 + src/core/pal/feature.h | 1 + src/core/pal/geomfunction.h | 1 + src/core/pal/labelposition.h | 2 + src/core/pal/pal.h | 1 + src/core/pal/priorityqueue.h | 2 + src/core/pal/problem.h | 4 ++ src/core/pal/rtree.hpp | 1 + src/core/pal/util.h | 1 + src/core/qgis.h | 1 + src/core/qgsaggregatecalculator.h | 1 + src/core/qgsapplication.h | 3 ++ src/core/qgsattributeeditorelement.h | 6 +++ src/core/qgsattributetableconfig.h | 1 + src/core/qgscachedfeatureiterator.h | 2 + src/core/qgsconditionalstyle.h | 1 + src/core/qgscoordinatereferencesystem.h | 9 +++++ src/core/qgscoordinatetransform.h | 1 + src/core/qgscsexception.h | 1 + src/core/qgsdatadefined.h | 1 + src/core/qgsdataitem.h | 3 ++ src/core/qgsdataprovider.h | 1 + src/core/qgseditorwidgetsetup.h | 1 + src/core/qgsexpression.h | 1 + src/core/qgsexpressioncontext.h | 2 + src/core/qgsexpressioncontextgenerator.h | 1 + src/core/qgsexpressionprivate.h | 1 + src/core/qgsfeature.h | 2 + src/core/qgsfeatureiterator.h | 1 + src/core/qgsfeaturerequest.h | 5 +++ src/core/qgsfields.h | 1 + src/core/qgsfontutils.h | 1 + src/core/qgsgeometrysimplifier.cpp | 1 + src/core/qgsgeometrysimplifier.h | 1 + src/core/qgsgml.h | 4 ++ src/core/qgslabelfeature.h | 6 +++ src/core/qgslayerdefinition.h | 1 + src/core/qgslegendsettings.h | 1 + src/core/qgsmaplayer.h | 4 ++ src/core/qgsmaplayermodel.h | 3 ++ src/core/qgsmaplayerregistry.h | 1 + src/core/qgsmaprendererjob.h | 1 + src/core/qgsmapsettings.h | 1 + src/core/qgsmultirenderchecker.h | 1 + src/core/qgsogcutils.h | 2 + src/core/qgsoptional.h | 1 + src/core/qgsoptionalexpression.h | 1 + src/core/qgsowsconnection.h | 1 + src/core/qgspointlocator.h | 1 + src/core/qgsproject.h | 2 + src/core/qgsprojectbadlayerhandler.h | 1 + src/core/qgsprojectproperty.h | 1 + src/core/qgsproviderregistry.h | 5 +++ src/core/qgsrectangle.h | 4 ++ src/core/qgsrelation.h | 3 ++ src/core/qgsrenderchecker.h | 1 + src/core/qgsrulebasedlabeling.h | 13 +++++++ src/core/qgsruntimeprofiler.h | 1 + src/core/qgsscaleutils.h | 1 + src/core/qgssnapper.h | 4 ++ src/core/qgssnappingconfig.h | 3 ++ src/core/qgssnappingutils.h | 2 + src/core/qgssqlstatement.h | 2 + src/core/qgstolerance.h | 1 + src/core/qgstransaction.h | 1 + src/core/qgstransactiongroup.h | 1 + src/core/qgsvectordataprovider.h | 4 ++ src/core/qgsvectorlayer.h | 4 ++ src/core/qgsvectorlayercache.h | 3 ++ src/core/qgsvirtuallayerdefinition.h | 1 + src/core/raster/qgscolorrampshader.h | 1 + src/core/raster/qgscontrastenhancement.cpp | 2 + src/core/raster/qgshillshaderenderer.h | 1 + src/core/raster/qgsraster.h | 17 ++++++++ src/core/raster/qgsrasterblock.h | 1 + src/core/raster/qgsrasterchecker.h | 1 + src/core/raster/qgsrasterdataprovider.h | 4 ++ src/core/raster/qgsrasterdrawer.h | 1 + src/core/raster/qgsrasterprojector.h | 1 + src/core/raster/qgsrasterpyramid.h | 1 + src/core/raster/qgsrasterrange.h | 1 + src/core/raster/qgsrasterrenderer.h | 1 + src/core/raster/qgsrasterresampler.h | 1 + src/core/raster/qgsrastershader.cpp | 1 + src/core/raster/qgsrastershaderfunction.h | 1 + src/core/raster/qgsrasterviewport.h | 3 ++ src/core/symbology-ng/qgs25drenderer.h | 2 + src/core/symbology-ng/qgsellipsesymbollayer.h | 1 + src/core/symbology-ng/qgsfillsymbollayer.h | 20 ++++++++++ src/core/symbology-ng/qgsheatmaprenderer.h | 6 +++ .../symbology-ng/qgsinvertedpolygonrenderer.h | 8 ++++ src/core/symbology-ng/qgsmarkersymbollayer.h | 4 ++ .../symbology-ng/qgspointdistancerenderer.h | 1 + src/core/symbology-ng/qgsrenderer.h | 1 + src/core/symbology-ng/qgsrendererregistry.h | 1 + src/core/symbology-ng/qgssvgcache.h | 2 + src/core/symbology-ng/qgssymbol.h | 5 +++ src/core/symbology-ng/qgssymbollayer.h | 1 + src/core/symbology-ng/qgssymbollayerutils.h | 1 + .../qgsattributetabledelegate.h | 2 + .../qgsattributetablefiltermodel.h | 4 ++ .../attributetable/qgsattributetablemodel.h | 8 ++++ .../attributetable/qgsattributetableview.h | 2 + src/gui/attributetable/qgsdualview.h | 5 +++ src/gui/attributetable/qgsfeaturelistview.h | 4 ++ .../attributetable/qgsfeatureselectionmodel.h | 3 ++ .../qgsifeatureselectionmanager.h | 1 + .../qgsorganizetablecolumnsdialog.h | 2 + .../qgsvectorlayerselectionmanager.h | 1 + src/gui/auth/qgsauthauthoritieseditor.h | 1 + src/gui/auth/qgsauthcertificateinfo.h | 1 + src/gui/auth/qgsauthcertificatemanager.h | 2 + src/gui/auth/qgsauthcerttrustpolicycombobox.h | 1 + src/gui/auth/qgsauthconfigeditor.h | 1 + src/gui/auth/qgsauthconfigidedit.h | 1 + src/gui/auth/qgsauthconfigselect.h | 2 + src/gui/auth/qgsautheditorwidgets.h | 2 + src/gui/auth/qgsauthidentitieseditor.h | 1 + src/gui/auth/qgsauthmethodedit.h | 2 + src/gui/auth/qgsauthserverseditor.h | 1 + src/gui/auth/qgsauthsslconfigwidget.h | 2 + src/gui/auth/qgsauthsslerrorsdialog.h | 1 + src/gui/auth/qgsauthsslimportdialog.h | 1 + src/gui/auth/qgsauthtrustedcasdialog.h | 1 + .../core/qgseditorconfigwidget.h | 1 + .../core/qgseditorwidgetautoconf.h | 3 ++ .../core/qgseditorwidgetfactory.h | 1 + .../core/qgseditorwidgetregistry.h | 2 + .../core/qgseditorwidgetwrapper.h | 4 ++ src/gui/editorwidgets/core/qgswidgetwrapper.h | 3 ++ .../editorwidgets/qgskeyvaluewidgetfactory.h | 1 + .../editorwidgets/qgskeyvaluewidgetwrapper.h | 1 + src/gui/editorwidgets/qgslistwidgetfactory.h | 1 + src/gui/editorwidgets/qgslistwidgetwrapper.h | 1 + .../editorwidgets/qgsrelationwidgetwrapper.h | 2 + .../qgslayertreeembeddedconfigwidget.h | 1 + .../qgslayertreeembeddedwidgetsimpl.h | 1 + src/gui/qgisinterface.h | 4 ++ src/gui/qgsadvanceddigitizingdockwidget.h | 7 ++++ src/gui/qgsattributeeditorcontext.h | 1 + src/gui/qgsattributeform.h | 2 + src/gui/qgsattributetypeloaddialog.h | 1 + src/gui/qgsbusyindicatordialog.h | 1 + src/gui/qgscodeeditor.h | 1 + src/gui/qgscodeeditorpython.h | 1 + src/gui/qgscollapsiblegroupbox.h | 4 ++ src/gui/qgscomposeritemcombobox.h | 2 + src/gui/qgscomposerview.h | 2 + src/gui/qgsdatadefinedbutton.h | 2 + src/gui/qgsdetaileditemdata.h | 1 + src/gui/qgsexpressionbuilderdialog.h | 1 + src/gui/qgsexpressionbuilderwidget.h | 3 ++ src/gui/qgsexpressionselectiondialog.h | 2 + src/gui/qgsexternalresourcewidget.h | 2 + src/gui/qgsfieldcombobox.h | 1 + src/gui/qgsfieldexpressionwidget.h | 1 + src/gui/qgsfilewidget.h | 3 ++ src/gui/qgsgenericprojectionselector.h | 2 + src/gui/qgsgeometryrubberband.h | 6 +++ src/gui/qgskeyvaluewidget.h | 2 + src/gui/qgslegendfilterbutton.h | 3 ++ src/gui/qgslistwidget.h | 2 + src/gui/qgsmapcanvas.h | 5 +++ src/gui/qgsmapcanvassnapper.h | 1 + src/gui/qgsmaplayercombobox.h | 1 + src/gui/qgsmaplayerconfigwidget.h | 1 + src/gui/qgsmaptip.h | 4 ++ src/gui/qgsmaptooladvanceddigitizing.h | 2 + src/gui/qgsmaptoolidentify.h | 1 + src/gui/qgsmaptoolidentifyfeature.h | 1 + src/gui/qgsmessagebar.h | 1 + src/gui/qgsnewnamedialog.h | 1 + src/gui/qgsoptionsdialogbase.h | 1 + src/gui/qgsorderbydialog.h | 2 + src/gui/qgsowssourceselect.h | 1 + src/gui/qgspanelwidget.h | 3 ++ src/gui/qgspanelwidgetstack.h | 1 + src/gui/qgspixmaplabel.h | 1 + src/gui/qgsprevieweffect.h | 1 + src/gui/qgsprojectionselector.h | 1 + src/gui/qgsquerybuilder.h | 1 + src/gui/qgsrelationeditorwidget.h | 3 ++ src/gui/qgsrubberband.h | 6 +++ src/gui/qgsscalerangewidget.h | 2 + src/gui/qgstablewidgetbase.h | 4 ++ src/gui/qgstablewidgetitem.h | 2 + src/gui/qgstabwidget.h | 1 + src/gui/raster/qgsrasterhistogramwidget.h | 1 + src/gui/raster/qgsrastertransparencywidget.h | 2 + .../qgsrendererrasterpropertieswidget.h | 1 + src/gui/symbology-ng/qgs25drendererwidget.h | 1 + .../symbology-ng/qgsarrowsymbollayerwidget.h | 1 + .../symbology-ng/qgsheatmaprendererwidget.h | 1 + .../qgsinvertedpolygonrendererwidget.h | 1 + .../qgsrendererpropertiesdialog.h | 2 + src/gui/symbology-ng/qgsrendererwidget.h | 4 ++ .../symbology-ng/qgsrulebasedrendererwidget.h | 2 + .../symbology-ng/qgsstyleexportimportdialog.h | 8 ++++ .../qgsstylegroupselectiondialog.h | 1 + src/gui/symbology-ng/qgssymbollayerwidget.h | 3 ++ .../symbology-ng/qgssymbolselectordialog.h | 3 ++ src/plugins/compass/qgscompassplugin.h | 6 +++ .../coordinate_capture/coordinatecapture.h | 1 + .../evisdatabaselayerfieldselectiongui.cpp | 1 + .../eventbrowser/evisimagedisplaywidget.cpp | 2 + src/plugins/gps_importer/qgsgpsplugin.h | 1 + src/plugins/grass/qgsgrassmodule.h | 1 + src/plugins/grass/qgsgrassmoduleinput.h | 1 + src/plugins/grass/qgsgrassmoduleoptions.h | 1 + src/plugins/grass/qgsgrassmoduleparam.h | 9 +++++ src/plugins/grass/qgsgrassplugin.h | 6 +++ src/plugins/heatmap/heatmapgui.h | 1 + .../interpolation/qgsinterpolationdialog.h | 1 + src/plugins/qgisplugin.h | 2 + src/plugins/roadgraph/exportdlg.h | 1 + .../roadgraph/linevectorlayersettings.h | 3 ++ src/plugins/roadgraph/linevectorlayerwidget.h | 2 + src/plugins/roadgraph/roadgraphplugin.h | 5 +++ src/plugins/roadgraph/settings.h | 4 ++ src/plugins/roadgraph/settingsdlg.h | 1 + src/plugins/roadgraph/shortestpathwidget.h | 4 ++ src/plugins/roadgraph/units.h | 2 + .../qgsgeometrycoordinatetransform.h | 3 ++ src/plugins/spatialquery/qgsmngprogressbar.h | 2 + src/plugins/spatialquery/qgsreaderfeatures.h | 2 + src/plugins/spatialquery/qgsrubberselectid.h | 2 + src/plugins/spatialquery/qgsspatialquery.h | 2 + .../spatialquery/qgsspatialquerydialog.h | 1 + .../spatialquery/qgsspatialqueryplugin.h | 1 + src/plugins/topology/checkDock.h | 14 +++++++ src/plugins/topology/dockModel.h | 7 ++++ src/plugins/topology/topolError.h | 16 ++++++++ src/plugins/topology/topolTest.h | 8 ++++ src/providers/db2/qgsdb2dataitems.h | 2 + src/providers/db2/qgsdb2featureiterator.cpp | 1 + src/providers/db2/qgsdb2newconnection.h | 1 + .../delimitedtext/qgsdelimitedtextfile.h | 12 ++++++ .../delimitedtext/qgsdelimitedtextprovider.h | 1 + src/providers/gdal/qgsgdalprovider.cpp | 4 ++ src/providers/gdal/qgsgdalprovider.h | 2 + src/providers/grass/qgsgrass.h | 4 ++ src/providers/grass/qgsgrassfeatureiterator.h | 1 + src/providers/grass/qgsgrassprovider.h | 1 + src/providers/grass/qgsgrassrasterprovider.h | 3 ++ src/providers/grass/qgsgrassvectormap.h | 2 + src/providers/oracle/qgsoracleprovider.cpp | 3 ++ src/providers/oracle/qgsoracleprovider.h | 3 ++ src/providers/ows/qgsowsprovider.h | 1 + .../postgres/qgspostgresprovider.cpp | 3 ++ src/providers/postgres/qgspostgresprovider.h | 5 +++ .../spatialite/qgsspatialiteconnection.h | 1 + .../spatialite/qgsspatialiteprovider.h | 1 + .../spatialite/qgsspatialitesourceselect.h | 1 + .../spatialite/qgsspatialitetablemodel.h | 1 + src/providers/wcs/qgswcscapabilities.h | 2 + src/providers/wcs/qgswcsprovider.h | 2 + src/providers/wfs/qgswfsconnection.h | 1 + src/providers/wfs/qgswfsfeatureiterator.h | 1 + src/providers/wfs/qgswfsprovider.h | 2 + src/providers/wfs/qgswfssourceselect.h | 1 + src/providers/wms/qgswmsprovider.cpp | 3 ++ src/providers/wms/qgswmsprovider.h | 4 ++ src/server/qgshttprequesthandler.h | 1 + src/server/qgshttptransaction.h | 1 + src/server/qgsmaprenderer.h | 2 + src/server/qgsmslayerbuilder.h | 2 + src/server/qgsmslayercache.h | 3 ++ src/server/qgsmsutils.h | 1 + src/server/qgsrequesthandler.h | 4 ++ src/server/qgsserver.h | 1 + src/server/qgsserverfilter.h | 3 ++ src/server/qgsserverinterfaceimpl.h | 1 + src/server/qgsserverplugins.h | 1 + src/server/qgssldconfigparser.h | 1 + src/server/qgswmsserver.h | 7 ++++ .../core/testqgscoordinatereferencesystem.cpp | 1 + 345 files changed, 846 insertions(+) diff --git a/src/analysis/interpolation/DualEdgeTriangulation.h b/src/analysis/interpolation/DualEdgeTriangulation.h index 6c9e6cfda432..f3c3830d4633 100644 --- a/src/analysis/interpolation/DualEdgeTriangulation.h +++ b/src/analysis/interpolation/DualEdgeTriangulation.h @@ -98,6 +98,7 @@ class ANALYSIS_EXPORT DualEdgeTriangulation: public Triangulation virtual bool swapEdge( double x, double y ) override; //! Returns a value list with the numbers of the four points, which would be affected by an edge swap. This function is e.g. needed by NormVecDecorator to know the points, for which the normals have to be recalculated. The returned ValueList has to be deleted by the code which calls the method virtual QList* getPointsAroundEdge( double x, double y ) override; + /** Saves the triangulation as a (line) shapefile @return true in case of success*/ virtual bool saveAsShapefile( const QString& fileName ) const override; diff --git a/src/analysis/interpolation/NormVecDecorator.h b/src/analysis/interpolation/NormVecDecorator.h index a0588101b971..d69dd69964b3 100644 --- a/src/analysis/interpolation/NormVecDecorator.h +++ b/src/analysis/interpolation/NormVecDecorator.h @@ -52,6 +52,7 @@ class ANALYSIS_EXPORT NormVecDecorator: public TriDecorator Vector3D* getNormal( int n ) const; //! Finds out, in which triangle a point with coordinates x and y is and assigns the triangle points to p1, p2, p3 and the estimated normals to v1, v2, v3. The vectors are normaly taken from 'mNormVec', exept if p1, p2 or p3 is a point on a breakline. In this case, the normal is calculated on-the-fly. Returns false, if something went wrong and true otherwise bool getTriangle( double x, double y, Point3D* p1, Vector3D* v1, Point3D* p2, Vector3D* v2, Point3D* p3, Vector3D* v3 ); + /** This function behaves similar to the one above. Additionally, the numbers of the points are returned (ptn1, ptn2, ptn3) as well as the pointStates of the triangle points (state1, state2, state3) * @note not available in Python bindings */ @@ -62,6 +63,7 @@ class ANALYSIS_EXPORT NormVecDecorator: public TriDecorator void setTriangleInterpolator( TriangleInterpolator* inter ) override; //! Swaps the edge which is closest to the point with x and y coordinates (if this is possible) and forces recalculation of the concerned normals (if alreadyestimated is true) virtual bool swapEdge( double x, double y ) override; + /** Saves the triangulation as a (line) shapefile @return true in case of success*/ virtual bool saveAsShapefile( const QString& fileName ) const override; diff --git a/src/analysis/interpolation/ParametricLine.h b/src/analysis/interpolation/ParametricLine.h index 7005eff00b35..1204c9a86c4d 100644 --- a/src/analysis/interpolation/ParametricLine.h +++ b/src/analysis/interpolation/ParametricLine.h @@ -37,6 +37,7 @@ class ANALYSIS_EXPORT ParametricLine public: //! Default constructor ParametricLine(); + /** Constructor, par is a pointer to the parent object, controlpoly the controlpolygon */ ParametricLine( ParametricLine* par, QVector* controlpoly ); diff --git a/src/analysis/interpolation/qgsinterpolator.h b/src/analysis/interpolation/qgsinterpolator.h index 4d3d9ab912a9..dda566490092 100644 --- a/src/analysis/interpolation/qgsinterpolator.h +++ b/src/analysis/interpolation/qgsinterpolator.h @@ -69,6 +69,7 @@ class ANALYSIS_EXPORT QgsInterpolator const QList& layerData() const { return mLayerData; } protected: + /** Caches the vertex and value data from the provider. All the vertex data will be held in virtual memory @return 0 in case of success*/ @@ -84,6 +85,7 @@ class ANALYSIS_EXPORT QgsInterpolator private: QgsInterpolator(); //forbidden + /** Helper method that adds the vertices of a geometry to the mCachedBaseData @param geom the geometry @param zCoord true if the z-coordinate of the geometry is to be interpolated diff --git a/src/analysis/interpolation/qgstininterpolator.h b/src/analysis/interpolation/qgstininterpolator.h index 0ba1a13dd9c7..9a12f75d6bc2 100644 --- a/src/analysis/interpolation/qgstininterpolator.h +++ b/src/analysis/interpolation/qgstininterpolator.h @@ -63,6 +63,7 @@ class ANALYSIS_EXPORT QgsTINInterpolator: public QgsInterpolator //! Create dual edge triangulation void initialize(); + /** Inserts the vertices of a feature into the triangulation @param f the feature @param zCoord true if the z coordinate is the interpolation attribute diff --git a/src/analysis/network/qgsarcproperter.h b/src/analysis/network/qgsarcproperter.h index 3e562f580ec0..201a88d21a66 100644 --- a/src/analysis/network/qgsarcproperter.h +++ b/src/analysis/network/qgsarcproperter.h @@ -32,6 +32,7 @@ class ANALYSIS_EXPORT QgsArcProperter { public: + /** * default constructor */ diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index 610e9c0e8b33..6790c22ce1ee 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -88,6 +88,7 @@ typedef QList< int > QgsGraphArcIdList; class ANALYSIS_EXPORT QgsGraphVertex { public: + /** * default constructor. It need for QT's container, e.g. QVector */ @@ -134,6 +135,7 @@ class ANALYSIS_EXPORT QgsGraph QgsGraph(); // begin graph constructing methods + /** * add vertex to a grap */ diff --git a/src/analysis/network/qgsgraphanalyzer.h b/src/analysis/network/qgsgraphanalyzer.h index 347a6560ab66..a35fe4697cf2 100644 --- a/src/analysis/network/qgsgraphanalyzer.h +++ b/src/analysis/network/qgsgraphanalyzer.h @@ -31,6 +31,7 @@ class QgsGraph; class ANALYSIS_EXPORT QgsGraphAnalyzer { public: + /** * solve shortest path problem using dijkstra algorithm * @param source The source graph diff --git a/src/analysis/network/qgsgraphbuilder.h b/src/analysis/network/qgsgraphbuilder.h index 1a079a511b5d..a48ecc2ecc42 100644 --- a/src/analysis/network/qgsgraphbuilder.h +++ b/src/analysis/network/qgsgraphbuilder.h @@ -36,6 +36,7 @@ class QgsGraph; class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface { public: + /** * default constructor */ diff --git a/src/analysis/network/qgsgraphbuilderintr.h b/src/analysis/network/qgsgraphbuilderintr.h index 011be8541df6..26badc27c5e7 100644 --- a/src/analysis/network/qgsgraphbuilderintr.h +++ b/src/analysis/network/qgsgraphbuilderintr.h @@ -34,6 +34,7 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface { public: + /** * QgsGraphBuilderInterface constructor * @param crs Coordinate reference system for new graph vertex diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgslinevectorlayerdirector.h index a0d083e56e49..11a1857a8031 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgslinevectorlayerdirector.h @@ -36,6 +36,7 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector Q_OBJECT public: + /** * @param myLayer source vector layer * @param directionFieldId feield contain road direction value diff --git a/src/analysis/openstreetmap/qgsosmbase.h b/src/analysis/openstreetmap/qgsosmbase.h index d4428b039425..c70cad42a508 100644 --- a/src/analysis/openstreetmap/qgsosmbase.h +++ b/src/analysis/openstreetmap/qgsosmbase.h @@ -110,6 +110,7 @@ class ANALYSIS_EXPORT QgsOSMWay : public QgsOSMElement #if 0 + /** \ingroup analysis A relation is one of the core data elements that consists of one or more tags and also an ordered list of one or more nodes and/or ways as members which is used to define logical or geographic relationships diff --git a/src/analysis/openstreetmap/qgsosmdatabase.h b/src/analysis/openstreetmap/qgsosmdatabase.h index 187fe060e7ec..d55344a3bf9f 100644 --- a/src/analysis/openstreetmap/qgsosmdatabase.h +++ b/src/analysis/openstreetmap/qgsosmdatabase.h @@ -138,6 +138,7 @@ class ANALYSIS_EXPORT QgsOSMNodeIterator // clazy:exclude=rule-of-three void close(); protected: + /** @note not available in Python bindings */ QgsOSMNodeIterator( sqlite3* handle ); @@ -163,6 +164,7 @@ class ANALYSIS_EXPORT QgsOSMWayIterator // clazy:exclude=rule-of-three void close(); protected: + /** @note not available in Python bindings */ QgsOSMWayIterator( sqlite3* handle ); diff --git a/src/analysis/raster/qgsninecellfilter.h b/src/analysis/raster/qgsninecellfilter.h index 3719bbdd45b8..03e42db770be 100644 --- a/src/analysis/raster/qgsninecellfilter.h +++ b/src/analysis/raster/qgsninecellfilter.h @@ -34,6 +34,7 @@ class ANALYSIS_EXPORT QgsNineCellFilter //! Constructor that takes input file, output file and output format (GDAL string) QgsNineCellFilter( const QString& inputFile, const QString& outputFile, const QString& outputFormat ); virtual ~QgsNineCellFilter(); + /** Starts the calculation, reads from mInputFile and stores the result in mOutputFile @param p progress dialog that receives update and that is checked for abort. 0 if no progress bar is needed. @return 0 in case of success*/ @@ -64,9 +65,11 @@ class ANALYSIS_EXPORT QgsNineCellFilter //! Opens the input file and returns the dataset handle and the number of pixels in x-/y- direction GDALDatasetH openInputFile( int& nCellsX, int& nCellsY ); + /** Opens the output driver and tests if it supports the creation of a new dataset @return nullptr on error and the driver handle on success*/ GDALDriverH openOutputDriver(); + /** Opens the output file and sets the same geotransform and CRS as the input data @return the output dataset or nullptr in case of error*/ GDALDatasetH openOutputFile( GDALDatasetH inputDataset, GDALDriverH outputDriver ); diff --git a/src/analysis/raster/qgsrelief.h b/src/analysis/raster/qgsrelief.h index d6bf989c281f..eaca801fc6fe 100644 --- a/src/analysis/raster/qgsrelief.h +++ b/src/analysis/raster/qgsrelief.h @@ -94,9 +94,11 @@ class ANALYSIS_EXPORT QgsRelief //! Opens the input file and returns the dataset handle and the number of pixels in x-/y- direction GDALDatasetH openInputFile( int& nCellsX, int& nCellsY ); + /** Opens the output driver and tests if it supports the creation of a new dataset @return nullptr on error and the driver handle on success*/ GDALDriverH openOutputDriver(); + /** Opens the output file and sets the same geotransform and CRS as the input data @return the output dataset or nullptr in case of error*/ GDALDatasetH openOutputFile( GDALDatasetH inputDataset, GDALDriverH outputDriver ); @@ -106,11 +108,13 @@ class ANALYSIS_EXPORT QgsRelief //! Sets relief colors void setDefaultReliefColors(); + /** Returns class (0-255) for an elevation value @return elevation class or -1 in case of error*/ int frequencyClassForElevation( double elevation, double minElevation, double elevationClassRange ); //! Do one iteration of class break optimisation (algorithm from Garcia and Rodriguez) void optimiseClassBreaks( QList& breaks, double* frequencies ); + /** Calculates coefficients a and b @param input data points ( elevation class / frequency ) @param a slope diff --git a/src/analysis/raster/qgsruggednessfilter.h b/src/analysis/raster/qgsruggednessfilter.h index 7719626eb243..dfe86115e7fe 100644 --- a/src/analysis/raster/qgsruggednessfilter.h +++ b/src/analysis/raster/qgsruggednessfilter.h @@ -30,6 +30,7 @@ class ANALYSIS_EXPORT QgsRuggednessFilter: public QgsNineCellFilter ~QgsRuggednessFilter(); protected: + /** Calculates output value from nine input values. The input values and the output value can be equal to the nodata value if not present or outside of the border. Must be implemented by subclasses*/ float processNineCellWindow( float* x11, float* x21, float* x31, diff --git a/src/analysis/raster/qgstotalcurvaturefilter.h b/src/analysis/raster/qgstotalcurvaturefilter.h index 7fc8f713eff6..df108ebaa48f 100644 --- a/src/analysis/raster/qgstotalcurvaturefilter.h +++ b/src/analysis/raster/qgstotalcurvaturefilter.h @@ -29,6 +29,7 @@ class ANALYSIS_EXPORT QgsTotalCurvatureFilter: public QgsNineCellFilter ~QgsTotalCurvatureFilter(); protected: + /** Calculates total curvature from nine input values. The input values and the output value can be equal to the nodata value if not present or outside of the border. Must be implemented by subclasses*/ float processNineCellWindow( float* x11, float* x21, float* x31, diff --git a/src/analysis/vector/qgsgeometryanalyzer.h b/src/analysis/vector/qgsgeometryanalyzer.h index 037f2156b539..d96e7547ef39 100644 --- a/src/analysis/vector/qgsgeometryanalyzer.h +++ b/src/analysis/vector/qgsgeometryanalyzer.h @@ -120,6 +120,7 @@ class ANALYSIS_EXPORT QgsGeometryAnalyzer //! Returns linear reference geometry as a multiline (or 0 if no match). Currently, the z-coordinates are considered to be the measures (no support for m-values in QGIS) QgsGeometry locateBetweenMeasures( double fromMeasure, double toMeasure, const QgsGeometry& lineGeom ); + /** Returns linear reference geometry. Unlike the PostGIS function, this method always returns multipoint or 0 if no match (not geometry collection). * Currently, the z-coordinates are considered to be the measures (no support for m-values in QGIS) */ @@ -144,6 +145,7 @@ class ANALYSIS_EXPORT QgsGeometryAnalyzer //helper functions for event layer void addEventLayerFeature( QgsFeature& feature, const QgsGeometry& geom, const QgsGeometry& lineGeom, QgsVectorFileWriter* fileWriter, QgsFeatureList& memoryFeatures, int offsetField = -1, double offsetScale = 1.0, bool forceSingleType = false ); + /** Create geometry offset relative to line geometry. @param geom the geometry to modify @param lineGeom the line geometry to which the feature is referenced diff --git a/src/analysis/vector/qgstransectsample.h b/src/analysis/vector/qgstransectsample.h index 09651ccfcc89..b00c01e62f8c 100644 --- a/src/analysis/vector/qgstransectsample.h +++ b/src/analysis/vector/qgstransectsample.h @@ -85,6 +85,7 @@ class ANALYSIS_EXPORT QgsTransectSample static bool closestSegmentPoints( const QgsGeometry& g1, const QgsGeometry& g2, double& dist, QgsPoint& pt1, QgsPoint& pt2 ); //! Returns a copy of the multiline element closest to a point (caller takes ownership) static QgsGeometry closestMultilineElement( const QgsPoint& pt, const QgsGeometry& multiLine ); + /** Returns clipped buffer line. Iteratively applies reduced tolerances if the result is not a single line @param stratumGeom stratum polygon @param clippedBaseline base line geometry clipped to the stratum diff --git a/src/app/composer/qgscomposeritemwidget.h b/src/app/composer/qgscomposeritemwidget.h index 012bb252680d..9df2f5e27da6 100644 --- a/src/app/composer/qgscomposeritemwidget.h +++ b/src/app/composer/qgscomposeritemwidget.h @@ -142,6 +142,7 @@ class QgsComposerItemWidget: public QWidget, private Ui::QgsComposerItemWidgetBa */ void on_mFrameColorButton_colorChanged( const QColor& newFrameColor ); void on_mBackgroundColorButton_clicked(); + /** Set the background color */ void on_mBackgroundColorButton_colorChanged( const QColor& newBackgroundColor ); diff --git a/src/app/composer/qgscomposermanager.h b/src/app/composer/qgscomposermanager.h index 75e1ab5b9444..4eb8f7a6eca5 100644 --- a/src/app/composer/qgscomposermanager.h +++ b/src/app/composer/qgscomposermanager.h @@ -59,6 +59,7 @@ class QgsComposerManager: public QDialog, private Ui::QgsComposerManagerBase void activate(); private: + /** Stores the relation between items and composer pointers. A 0 pointer for the composer means that this composer needs to be created from a default template*/ QMap mItemComposerMap; diff --git a/src/app/nodetool/qgsmaptoolnodetool.h b/src/app/nodetool/qgsmaptoolnodetool.h index c7c607d0628a..e019f79df448 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.h +++ b/src/app/nodetool/qgsmaptoolnodetool.h @@ -71,6 +71,7 @@ class QgsMapToolNodeTool: public QgsMapToolEdit void deleteNodeSelection(); private: + /** * Get the feature on the mouse click */ diff --git a/src/app/nodetool/qgsselectedfeature.h b/src/app/nodetool/qgsselectedfeature.h index e404f4a78d8a..6118df3cefd0 100644 --- a/src/app/nodetool/qgsselectedfeature.h +++ b/src/app/nodetool/qgsselectedfeature.h @@ -178,6 +178,7 @@ class QgsSelectedFeature: public QObject void beforeRollBack(); private: + /** * Deletes whole vertex map. */ diff --git a/src/app/ogr/qgsvectorlayersaveasdialog.h b/src/app/ogr/qgsvectorlayersaveasdialog.h index e809b68c7463..c586e9760208 100644 --- a/src/app/ogr/qgsvectorlayersaveasdialog.h +++ b/src/app/ogr/qgsvectorlayersaveasdialog.h @@ -56,6 +56,7 @@ class APP_EXPORT QgsVectorLayerSaveAsDialog : public QDialog, private Ui::QgsVec //! Return selected attributes that must be exported with their displayed values instead of their raw values. Added in QGIS 2.16 QgsAttributeList attributesAsDisplayedValues() const; bool addToCanvas() const; + /** Returns type of symbology export. 0: No symbology 1: Feature symbology diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index bb3420536d60..05ffeebbe70d 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -4622,8 +4622,10 @@ void QgisApp::fileOpenAfterLaunch() bool projOpenedOK = settings.value( QStringLiteral( "/qgis/projOpenedOKAtLaunch" ), QVariant( true ) ).toBool(); // notify user if last attempt at auto-opening a project failed + /** NOTE: Notification will not show if last auto-opened project failed but next project opened is from command line (minor issue) */ + /** TODO: Keep projOpenedOKAtLaunch from being reset to true after reading command line project (which happens before initialization signal) */ if ( !projOpenedOK ) @@ -6221,6 +6223,7 @@ void QgisApp::saveAsLayerDefinition() } ///@cond PRIVATE + /** Field value converter for export as vecotr layer * \note Not available in Python bindings */ @@ -7767,6 +7770,7 @@ void QgisApp::copyStyle( QgsMapLayer * sourceLayer ) mActionPasteStyle->setEnabled( true ); } } + /** \param destinationLayer The layer that the clipboard will be pasted to (defaults to the active layer on the legend) diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index bd2a46c24ad3..d8472274d5b1 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -151,6 +151,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QgisApp(); //! Destructor ~QgisApp(); + /** * Add a vector layer to the canvas, returns pointer to it */ @@ -190,6 +191,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void setExtent( const QgsRectangle& theRect ); //! Remove all layers from the map and legend - reimplements same method from qgisappbase void removeAllLayers(); + /** Open a raster or vector file; ignore other files. Used to process a commandline argument, FileOpen or Drop event. Set interactive to true if it is ok to ask the user for information (mostly for @@ -197,6 +199,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow @returns true if the file is successfully opened */ bool openLayer( const QString & fileName, bool allowInteractive = false ); + /** Open the specified project file; prompt to save previous project if necessary. Used to process a commandline argument, FileOpen or Drop event. */ @@ -211,6 +214,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow @returns false if unable to open the project */ bool addProject( const QString& projectFile ); + /** Convenience function to open either a project or a layer file. */ void openFile( const QString & fileName ); @@ -258,6 +262,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow * parent class, it will also add it to the View menu list of docks.*/ void addDockWidget( Qt::DockWidgetArea area, QDockWidget *dockwidget ); void removeDockWidget( QDockWidget* dockwidget ); + /** Add a toolbar to the main window. Overloaded from QMainWindow. * After adding the toolbar to the ui (by delegating to the QMainWindow * parent class, it will also add it to the View menu list of toolbars.*/ @@ -274,12 +279,14 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow /** Add window to Window menu. The action title is the window title * and the action should raise, unminimize and activate the window. */ void addWindow( QAction *action ); + /** Remove window from Window menu. Calling this is necessary only for * windows which are hidden rather than deleted when closed. */ void removeWindow( QAction *action ); //! Returns the print composers QSet printComposers() const {return mPrintComposers;} + /** Get a unique title from user for new and duplicate composers * @param acceptEmpty whether to accept empty titles (one will be generated) * @param currentTitle base name for initial title choice @@ -290,6 +297,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QgsComposer* createNewComposer( QString title = QString() ); //! Deletes a composer and removes entry from Set void deleteComposer( QgsComposer *c ); + /** Duplicates a composer and adds it to Set */ QgsComposer *duplicateComposer( QgsComposer *currentComposer, QString title = QString() ); @@ -453,6 +461,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QMenu *helpMenu() { return mHelpMenu; } //! Toolbars + /** Get a reference to a toolbar. Mainly intended * to be used by plugins that want to specifically add * an icon into the file toolbar for consistency e.g. @@ -606,18 +615,21 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void updateUndoActions(); //! cuts selected features on the active layer to the clipboard + /** \param layerContainingSelection The layer that the selection will be taken from (defaults to the active layer on the legend) */ void editCut( QgsMapLayer *layerContainingSelection = nullptr ); //! copies selected features on the active layer to the clipboard + /** \param layerContainingSelection The layer that the selection will be taken from (defaults to the active layer on the legend) */ void editCopy( QgsMapLayer *layerContainingSelection = nullptr ); //! copies features on the clipboard to the active layer + /** \param destinationLayer The layer that the clipboard will be pasted to (defaults to the active layer on the legend) @@ -628,12 +640,14 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! copies features on the clipboard to a new memory vector layer QgsVectorLayer *pasteAsNewMemoryVector( const QString & theLayerName = QString() ); //! copies style of the active layer to the clipboard + /** \param sourceLayer The layer where the style will be taken from (defaults to the active layer on the legend) */ void copyStyle( QgsMapLayer *sourceLayer = nullptr ); //! pastes style on the clipboard to the active layer + /** \param destinationLayer The layer that the clipboard will be pasted to (defaults to the active layer on the legend) @@ -805,10 +819,12 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void zoomToLayerExtent(); //! zoom to actual size of raster layer void zoomActualSize(); + /** Perform a local histogram stretch on the active raster layer * (stretch based on pixel values in view extent). * Valid for non wms raster layers only. */ void localHistogramStretch(); + /** Perform a full histogram stretch on the active raster layer * (stretch based on pixels values in full dataset) * Valid for non wms raster layers only. */ @@ -817,15 +833,19 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void localCumulativeCutStretch(); //! Perform a full extent cumulative cut stretch void fullCumulativeCutStretch(); + /** Increase raster brightness * Valid for non wms raster layers only. */ void increaseBrightness(); + /** Decrease raster brightness * Valid for non wms raster layers only. */ void decreaseBrightness(); + /** Increase raster contrast * Valid for non wms raster layers only. */ void increaseContrast(); + /** Decrease raster contrast * Valid for non wms raster layers only. */ void decreaseContrast(); @@ -869,6 +889,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void removeAddLayerAction( QAction *action ); //! Add an icon to the plugin toolbar int addPluginToolBarIcon( QAction *qAction ); + /** * Add a widget to the plugins toolbar. * To remove this widget again, call {@link removeToolBarIcon} @@ -882,6 +903,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void removePluginToolBarIcon( QAction *qAction ); //! Add an icon to the Raster toolbar int addRasterToolBarIcon( QAction *qAction ); + /** * Add a widget to the raster toolbar. * To remove this widget again, call {@link removeRasterToolBarIcon} @@ -895,6 +917,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void removeRasterToolBarIcon( QAction *qAction ); //! Add an icon to the Vector toolbar int addVectorToolBarIcon( QAction *qAction ); + /** * Add a widget to the vector toolbar. * To remove this widget again, call {@link removeVectorToolBarIcon} @@ -908,6 +931,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void removeVectorToolBarIcon( QAction *qAction ); //! Add an icon to the Database toolbar int addDatabaseToolBarIcon( QAction *qAction ); + /** * Add a widget to the database toolbar. * To remove this widget again, call {@link removeDatabaseToolBarIcon} @@ -921,6 +945,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void removeDatabaseToolBarIcon( QAction *qAction ); //! Add an icon to the Web toolbar int addWebToolBarIcon( QAction *qAction ); + /** * Add a widget to the web toolbar. * To remove this widget again, call {@link removeWebToolBarIcon} @@ -945,6 +970,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! Open the project file corresponding to the //! text)= of the given action. void openProject( QAction *action ); + /** Attempts to run a python script * @param filePath full path to python script * @note added in QGIS 2.7 @@ -1313,15 +1339,19 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow /** Disable any preview modes shown on the map canvas * @note added in 2.3 */ void disablePreviewMode(); + /** Enable a grayscale preview mode on the map canvas * @note added in 2.3 */ void activateGrayscalePreview(); + /** Enable a monochrome preview mode on the map canvas * @note added in 2.3 */ void activateMonoPreview(); + /** Enable a color blindness (protanope) preview mode on the map canvas * @note added in 2.3 */ void activateProtanopePreview(); + /** Enable a color blindness (deuteranope) preview mode on the map canvas * @note added in 2.3 */ void activateDeuteranopePreview(); @@ -1343,6 +1373,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void dropEventTimeout(); signals: + /** Emitted when a key is pressed and we want non widget sublasses to be able to pick up on this (e.g. maplayer) */ void keyPressed( QKeyEvent *e ); @@ -1354,6 +1385,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow knows to then check the project properties for any relevant state. */ void projectRead(); + /** Emitted when starting an entirely new project @note This is similar to projectRead(); plug-ins might want to be notified @@ -1401,15 +1433,19 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow * @returns true if any items were loaded */ bool askUserForZipItemLayers( const QString &path ); + /** This method will open a dialog so the user can select GDAL sublayers to load */ void askUserForGDALSublayers( QgsRasterLayer *layer ); + /** This method will verify if a GDAL layer contains sublayers */ bool shouldAskUserForGDALSublayers( QgsRasterLayer *layer ); + /** This method will open a dialog so the user can select OGR sublayers to load */ void askUserForOGRSublayers( QgsVectorLayer *layer ); + /** Add a raster layer to the map (passed in as a ptr). * It won't force a refresh. */ @@ -1435,6 +1471,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow // void pasteTransformations(); //! check to see if file is dirty and if so, prompt the user th save it bool saveDirty(); + /** Helper function to union several geometries together (used in function mergeSelectedFeatures) @return empty geometry in case of error or if canceled */ QgsGeometry unionGeometries( const QgsVectorLayer* vl, QgsFeatureList& featureList, bool &canceled ); @@ -1699,10 +1736,12 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QgsClipboard *mInternalClipboard; //! Flag to indicate how the project properties dialog was summoned bool mShowProjectionTab; + /** String containing supporting vector file formats Suitable for a QFileDialog file filter. Build in ctor. */ QString mVectorFileFilter; + /** String containing supporting raster file formats Suitable for a QFileDialog file filter. Build in ctor. */ diff --git a/src/app/qgisappinterface.h b/src/app/qgisappinterface.h index 14a790a903b6..df3f9cdfe26d 100644 --- a/src/app/qgisappinterface.h +++ b/src/app/qgisappinterface.h @@ -38,6 +38,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface Q_OBJECT public: + /** * Constructor. * @param qgis Pointer to the QgisApp object @@ -82,6 +83,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface //! Add an icon to the plugins toolbar int addToolBarIcon( QAction *qAction ) override; + /** * Add a widget to the plugins toolbar. * To remove this widget again, call {@link removeToolBarIcon} @@ -95,6 +97,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface void removeToolBarIcon( QAction *qAction ) override; //! Add an icon to the Raster toolbar int addRasterToolBarIcon( QAction *qAction ) override; + /** * Add a widget to the raster toolbar. * To remove this widget again, call {@link removeRasterToolBarIcon} @@ -108,6 +111,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface void removeRasterToolBarIcon( QAction *qAction ) override; //! Add an icon to the Vector toolbar int addVectorToolBarIcon( QAction *qAction ) override; + /** * Add a widget to the vector toolbar. * To remove this widget again, call {@link removeVectorToolBarIcon} @@ -121,6 +125,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface void removeVectorToolBarIcon( QAction *qAction ) override; //! Add an icon to the Database toolbar int addDatabaseToolBarIcon( QAction *qAction ) override; + /** * Add a widget to the database toolbar. * To remove this widget again, call {@link removeDatabaseToolBarIcon} @@ -134,6 +139,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface void removeDatabaseToolBarIcon( QAction *qAction ) override; //! Add an icon to the Web toolbar int addWebToolBarIcon( QAction *qAction ) override; + /** * Add a widget to the web toolbar. * To remove this widget again, call {@link removeWebToolBarIcon} @@ -194,6 +200,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface QList activeComposers() override; // ### QGIS 3: return QgsComposer*, not QgsComposerView* + /** Create a new composer * @param title window title for new composer (one will be generated if empty) * @return pointer to composer's view @@ -202,6 +209,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface QgsComposerView* createNewComposer( const QString& title = QString() ) override; // ### QGIS 3: return QgsComposer*, not QgsComposerView* + /** Duplicate an existing parent composer from composer view * @param composerView pointer to existing composer view * @param title window title for duplicated composer (one will be generated if empty) @@ -278,6 +286,7 @@ class APP_EXPORT QgisAppInterface : public QgisInterface /** Add window to Window menu. The action title is the window title * and the action should raise, unminimize and activate the window. */ virtual void addWindow( QAction *action ) override; + /** Remove window from Window menu. Calling this is necessary only for * windows which are hidden rather than deleted when closed. */ virtual void removeWindow( QAction *action ) override; diff --git a/src/app/qgisappstylesheet.h b/src/app/qgisappstylesheet.h index fc41601c1597..71eb83718542 100644 --- a/src/app/qgisappstylesheet.h +++ b/src/app/qgisappstylesheet.h @@ -49,6 +49,7 @@ class APP_EXPORT QgisAppStyleSheet: public QObject QFont defaultFont() { return mDefaultFont; } signals: + /** Signal the successful stylesheet build results * @note connect to (app|widget)->setStyleSheet or similar custom slot */ diff --git a/src/app/qgsattributetabledialog.h b/src/app/qgsattributetabledialog.h index abeea9dc05b4..ac69f7fdd687 100644 --- a/src/app/qgsattributetabledialog.h +++ b/src/app/qgsattributetabledialog.h @@ -42,6 +42,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib Q_OBJECT public: + /** * Constructor * @param theLayer layer pointer @@ -54,6 +55,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib QgsExpressionContext createExpressionContext() const override; public slots: + /** * Toggles editing mode */ @@ -68,46 +70,57 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib bool alwaysShowFilter = false ); private slots: + /** * Copies selected rows to the clipboard */ void on_mActionCopySelectedRows_triggered(); + /** * Paste features from the clipboard */ void on_mActionPasteFeatures_triggered(); + /** * Toggles editing mode */ void on_mActionToggleEditing_toggled( bool ); + /** * Saves edits */ void on_mActionSaveEdits_triggered(); + /** * Reload the data */ void on_mActionReload_triggered(); + /** * Inverts selection */ void on_mActionInvertSelection_triggered(); + /** * Clears selection */ void on_mActionRemoveSelection_triggered(); + /** * Select all */ void on_mActionSelectAll_triggered(); + /** * Zooms to selected features */ void on_mActionZoomMapToSelectedRows_triggered(); + /** * Pans to selected features */ void on_mActionPanMapToSelectedRows_triggered(); + /** * Moves selected lines to the top */ @@ -122,6 +135,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib * Opens dialog to remove attribute */ void on_mActionRemoveAttribute_triggered(); + /** * Opens field calculator dialog */ @@ -168,6 +182,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib void replaceSearchWidget( QWidget* oldw, QWidget* neww ); signals: + /** * Informs that edits should be saved * @param layer layer whose edits are to be saved @@ -175,6 +190,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib void saveEdits( QgsMapLayer *layer ); protected: + /** * Handle closing of the window * @param event unused @@ -188,6 +204,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib void keyPressEvent( QKeyEvent* event ) override; private slots: + /** * Initialize column box */ diff --git a/src/app/qgsattributetypedialog.h b/src/app/qgsattributetypedialog.h index 653ade26643d..2fcc53474f18 100644 --- a/src/app/qgsattributetypedialog.h +++ b/src/app/qgsattributetypedialog.h @@ -163,6 +163,7 @@ class APP_EXPORT QgsAttributeTypeDialog: public QDialog, private Ui::QgsAttribut void setDefaultValueExpression( const QString& expression ); private slots: + /** * Slot to handle change of index in combobox to select correct page * @param index index of value in combobox diff --git a/src/app/qgsdecorationgrid.h b/src/app/qgsdecorationgrid.h index 89eda78e2d92..692442b98db1 100644 --- a/src/app/qgsdecorationgrid.h +++ b/src/app/qgsdecorationgrid.h @@ -201,15 +201,18 @@ class APP_EXPORT QgsDecorationGrid: public QgsDecorationItem @param vLines vertical coordinate lines in item coordinates*/ void drawCoordinateAnnotations( QPainter* p, const QList< QPair< qreal, QLineF > >& hLines, const QList< QPair< qreal, QLineF > >& vLines ); void drawCoordinateAnnotation( QPainter* p, QPointF pos, const QString& annotationString ); + /** Draws a single annotation @param p drawing painter @param pos item coordinates where to draw @param rotation text rotation @param annotationText the text to draw*/ void drawAnnotation( QPainter* p, QPointF pos, int rotation, const QString& annotationText ); + /** Returns the grid lines with associated coordinate value @return 0 in case of success*/ int xGridLines( QList< QPair< qreal, QLineF > >& lines ) const; + /** Returns the grid lines for the y-coordinates. Not vertical in case of rotation @return 0 in case of success*/ int yGridLines( QList< QPair< qreal, QLineF > >& lines ) const; diff --git a/src/app/qgsdisplayangle.h b/src/app/qgsdisplayangle.h index 71c2b0682b66..f0047a4b5043 100644 --- a/src/app/qgsdisplayangle.h +++ b/src/app/qgsdisplayangle.h @@ -28,6 +28,7 @@ class APP_EXPORT QgsDisplayAngle: public QDialog, private Ui::QgsDisplayAngleBas public: QgsDisplayAngle( QgsMapToolMeasureAngle * tool = nullptr, Qt::WindowFlags f = 0 ); ~QgsDisplayAngle(); + /** Sets the measured angle value (in radians). The value is going to be converted to degrees / gon automatically if necessary*/ void setValueInRadians( double value ); diff --git a/src/app/qgsmaptooladdfeature.h b/src/app/qgsmaptooladdfeature.h index 654ed4095e10..86c944aa329d 100644 --- a/src/app/qgsmaptooladdfeature.h +++ b/src/app/qgsmaptooladdfeature.h @@ -29,6 +29,7 @@ class APP_EXPORT QgsMapToolAddFeature : public QgsMapToolCapture void activate() override; protected: + /** Check if CaptureMode match layer type. Default is true. * @note Added in 2.12 */ bool mCheckGeometryType; diff --git a/src/app/qgsmaptoollabel.h b/src/app/qgsmaptoollabel.h index c1a6677789fb..21921acdf18b 100644 --- a/src/app/qgsmaptoollabel.h +++ b/src/app/qgsmaptoollabel.h @@ -38,23 +38,28 @@ class APP_EXPORT QgsMapToolLabel: public QgsMapTool @return true if labels of layer can be moved*/ bool labelMoveable( QgsVectorLayer* vlayer, int& xCol, int& yCol ) const; bool labelMoveable( QgsVectorLayer* vlayer, const QgsPalLayerSettings& settings, int& xCol, int& yCol ) const; + /** Returns true if diagram move can be applied to a layer @param xCol out: index of the attribute for data defined x coordinate @param yCol out: index of the attribute for data defined y coordinate @return true if labels of layer can be moved*/ bool diagramMoveable( QgsVectorLayer* vlayer, int& xCol, int& yCol ) const; + /** Returns true if layer has attribute fields set up @param xCol out: index of the attribute for data defined x coordinate @param yCol out: index of the attribute for data defined y coordinate @return true if layer fields set up and exist*/ bool layerCanPin( QgsVectorLayer* vlayer, int& xCol, int& yCol ) const; + /** Returns true if layer has attribute field set up for diagrams @param showCol out: attribute column for data defined diagram showing @note added in QGIS 2.16 */ bool diagramCanShowHide( QgsVectorLayer* vlayer, int& showCol ) const; + /** Returns true if layer has attribute field set up @param showCol out: attribute column for data defined label showing*/ bool labelCanShowHide( QgsVectorLayer* vlayer, int& showCol ) const; + /** Checks if labels in a layer can be rotated @param rotationCol out: attribute column for data defined label rotation*/ bool layerIsRotatable( QgsVectorLayer *layer, int& rotationCol ) const; diff --git a/src/app/qgsmaptoolselectutils.h b/src/app/qgsmaptoolselectutils.h index b109dd679954..123a96caeba5 100644 --- a/src/app/qgsmaptoolselectutils.h +++ b/src/app/qgsmaptoolselectutils.h @@ -32,6 +32,7 @@ class QgsRubberBand; */ namespace QgsMapToolSelectUtils { + /** Calculates a list of features matching a selection geometry and flags. * @param canvas the map canvas used to get the current selected vector layer and for any required geometry transformations diff --git a/src/app/qgsmergeattributesdialog.h b/src/app/qgsmergeattributesdialog.h index 7e0d4f13e6dc..82338ee89037 100644 --- a/src/app/qgsmergeattributesdialog.h +++ b/src/app/qgsmergeattributesdialog.h @@ -70,6 +70,7 @@ class APP_EXPORT QgsMergeAttributesDialog: public QDialog, private Ui::QgsMergeA void createTableWidgetContents(); //! Create new combo box with the options for featureXX / mean / min / max QComboBox* createMergeComboBox( QVariant::Type columnType ) const; + /** Returns the table widget column index of a combo box @return the column index or -1 in case of error*/ int findComboColumn( QComboBox* c ) const; diff --git a/src/app/qgsoptions.h b/src/app/qgsoptions.h index d9b2a4794795..3f2f095cfae0 100644 --- a/src/app/qgsoptions.h +++ b/src/app/qgsoptions.h @@ -38,6 +38,7 @@ class APP_EXPORT QgsOptions : public QgsOptionsDialogBase, private Ui::QgsOption { Q_OBJECT public: + /** * Constructor * @param parent Parent widget (usually a QgisApp) diff --git a/src/app/qgspluginmetadata.h b/src/app/qgspluginmetadata.h index 14c584a3b576..4b133af49645 100644 --- a/src/app/qgspluginmetadata.h +++ b/src/app/qgspluginmetadata.h @@ -20,6 +20,7 @@ #define QGSPLUGINMETADATA_H #include class QgisPlugin; + /** * \class QgsPluginMetadata * \brief Stores information about a loaded plugin, including a pointer to diff --git a/src/app/qgsrasterlayerproperties.h b/src/app/qgsrasterlayerproperties.h index 9ce8db5286c0..42aa87ad9a53 100644 --- a/src/app/qgsrasterlayerproperties.h +++ b/src/app/qgsrasterlayerproperties.h @@ -43,6 +43,7 @@ class APP_EXPORT QgsRasterLayerProperties : public QgsOptionsDialogBase, private Q_OBJECT public: + /** \brief Constructor * @param ml Map layer for which properties will be displayed */ diff --git a/src/app/qgstipfactory.h b/src/app/qgstipfactory.h index b78635a57020..eeba72e64216 100644 --- a/src/app/qgstipfactory.h +++ b/src/app/qgstipfactory.h @@ -35,10 +35,12 @@ class APP_EXPORT QgsTipFactory : public QObject QgsTipFactory(); //! Destructor ~QgsTipFactory(); + /** Get a random tip (generic or gui-centric) * @return An QgsTip containing the tip */ QgsTip getTip(); + /** Get a specific tip (generic or gui-centric). * @param thePosition The tip returned will be based on the * number passed in as thePosition. If the @@ -47,10 +49,12 @@ class APP_EXPORT QgsTipFactory : public QObject * @return An QgsTip containing the tip */ QgsTip getTip( int thePosition ); + /** Get a random generic tip * @return An QgsTip containing the tip */ QgsTip getGenericTip(); + /** Get a random gui-centric tip * @return An QgsTip containing the tip */ diff --git a/src/app/qgsversioninfo.h b/src/app/qgsversioninfo.h index 8d1fa6070d45..cbbe085b63a6 100644 --- a/src/app/qgsversioninfo.h +++ b/src/app/qgsversioninfo.h @@ -26,6 +26,7 @@ class QgsVersionInfo : public QObject explicit QgsVersionInfo( QObject *parent = nullptr ); public slots: + /** * Connects to qgis.org and checks for new versions. */ diff --git a/src/core/auth/qgsauthconfig.h b/src/core/auth/qgsauthconfig.h index 1d5161c38bee..e95195126569 100644 --- a/src/core/auth/qgsauthconfig.h +++ b/src/core/auth/qgsauthconfig.h @@ -87,6 +87,7 @@ class CORE_EXPORT QgsAuthMethodConfig * @note This is an internal construct used by QgsAuthManager that should generally not be set by client code */ const QString configString() const; + /** * Load existing extended configuration * @param configstr Configuration string to load @@ -95,6 +96,7 @@ class CORE_EXPORT QgsAuthMethodConfig //! Get extended configuration, mapped to key/value pairs of QStrings QgsStringMap configMap() const { return mConfigMap; } + /** * Set extended configuration map * @param map Map to set @@ -108,6 +110,7 @@ class CORE_EXPORT QgsAuthMethodConfig * @param value Config value */ void setConfig( const QString &key, const QString &value ); + /** * Set a multiple config values per key in the map * @note if key exists, it is replaced @@ -183,6 +186,7 @@ typedef QHash QgsAuthMethodConfigsMap; class CORE_EXPORT QgsPkiBundle { public: + /** * Construct a bundle from existing PKI components * @param clientCert Certificate to store in bundle @@ -250,6 +254,7 @@ class CORE_EXPORT QgsPkiBundle class CORE_EXPORT QgsPkiConfigBundle { public: + /** * Construct a bundle from existing PKI components and authentication method configuration * @param config Authentication method configuration @@ -327,6 +332,7 @@ class CORE_EXPORT QgsAuthConfigSslServer * @note When set to 0 = unlimited depth */ int sslPeerVerifyDepth() const { return mSslPeerVerifyDepth; } + /** Set number or SSL client's peer to verify in connections * @note When set to 0 = unlimited depth */ diff --git a/src/core/auth/qgsauthmanager.h b/src/core/auth/qgsauthmanager.h index 0d41dd43de72..4f6463f85427 100644 --- a/src/core/auth/qgsauthmanager.h +++ b/src/core/auth/qgsauthmanager.h @@ -496,6 +496,7 @@ class CORE_EXPORT QgsAuthManager : public QObject QMutex *mutex() { return mMutex; } signals: + /** * Custom logging signal to relay to console output and QgsMessageLog * @see QgsMessageLog diff --git a/src/core/auth/qgsauthmethod.h b/src/core/auth/qgsauthmethod.h index 7178279c96e2..08cc9b3ab52a 100644 --- a/src/core/auth/qgsauthmethod.h +++ b/src/core/auth/qgsauthmethod.h @@ -139,6 +139,7 @@ class CORE_EXPORT QgsAuthMethod : public QObject virtual void updateMethodConfig( QgsAuthMethodConfig &mconfig ) = 0; protected: + /** * Construct a default authentication method * @note Non-public since this is an abstract base class diff --git a/src/core/auth/qgsauthmethodmetadata.h b/src/core/auth/qgsauthmethodmetadata.h index 647461d8a5c3..7f80a94bb3ed 100644 --- a/src/core/auth/qgsauthmethodmetadata.h +++ b/src/core/auth/qgsauthmethodmetadata.h @@ -35,6 +35,7 @@ class CORE_EXPORT QgsAuthMethodMetadata { public: + /** * Construct an authentication method metadata container * @param _key Textual key of the library plugin diff --git a/src/core/auth/qgsauthmethodregistry.h b/src/core/auth/qgsauthmethodregistry.h index 655d0c3b8047..1b6054efdb49 100644 --- a/src/core/auth/qgsauthmethodregistry.h +++ b/src/core/auth/qgsauthmethodregistry.h @@ -77,6 +77,7 @@ class CORE_EXPORT QgsAuthMethodRegistry QWidget *editWidget( const QString & authMethodKey, QWidget * parent = nullptr ); #if QT_VERSION >= 0x050000 + /** Get pointer to auth method function @param authMethodKey identificator of the auth method @param functionName name of function @@ -85,6 +86,7 @@ class CORE_EXPORT QgsAuthMethodRegistry QFunctionPointer function( const QString & authMethodKey, const QString & functionName ); #else + /** Get pointer to auth method function @param authMethodKey identificator of the auth method @param functionName name of function diff --git a/src/core/composer/qgsatlascomposition.h b/src/core/composer/qgsatlascomposition.h index 5d7568d44a26..3ce5f2871661 100644 --- a/src/core/composer/qgsatlascomposition.h +++ b/src/core/composer/qgsatlascomposition.h @@ -297,6 +297,7 @@ class CORE_EXPORT QgsAtlasComposition : public QObject void numberFeaturesChanged( int numFeatures ); private: + /** Updates the filename expression. * @returns true if expression was successfully parsed, false if expression is invalid */ diff --git a/src/core/composer/qgscomposerarrow.h b/src/core/composer/qgscomposerarrow.h index 6ee00119857d..9d2cf13d3504 100644 --- a/src/core/composer/qgscomposerarrow.h +++ b/src/core/composer/qgscomposerarrow.h @@ -226,6 +226,7 @@ class CORE_EXPORT QgsComposerArrow: public QgsComposerItem double mArrowHeadOutlineWidth; QColor mArrowHeadOutlineColor; QColor mArrowHeadFillColor; + /** Indicates QGIS version to mimic bounding box behaviour for. The line placement changed in version 2.4, so a value * of 22 is used to indicate that the line should be drawn using the older placement routine. */ @@ -245,10 +246,12 @@ class CORE_EXPORT QgsComposerArrow: public QgsComposerItem void drawSVGMarker( QPainter* p, MarkerType type, const QString& markerPath ); //! Apply default graphics settings void init(); + /** Creates the default line symbol * @note added in QGIS 2.5 */ void createDefaultLineSymbol(); + /** Draws the arrow line * @note added in QGIS 2.5 */ diff --git a/src/core/composer/qgscomposeritem.h b/src/core/composer/qgscomposeritem.h index 6a41e3be4fa9..05f4580e4321 100644 --- a/src/core/composer/qgscomposeritem.h +++ b/src/core/composer/qgscomposeritem.h @@ -94,6 +94,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec //note - must sync with QgsMapCanvas::WheelAction. //TODO - QGIS 3.0 move QgsMapCanvas::WheelAction from GUI->CORE and remove this enum + /** Modes for zooming item content */ enum ZoomMode @@ -108,6 +109,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec @param composition parent composition @param manageZValue true if the z-Value of this object should be managed by mComposition*/ QgsComposerItem( QgsComposition* composition, bool manageZValue = true ); + /** Constructor with box position and composer object @param x x coordinate of item @param y y coordinate of item @@ -578,6 +580,7 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec //! Item rotation in degrees, clockwise double mItemRotation; + /** Temporary evaluated item rotation in degrees, clockwise. Data defined rotation may mean * this value differs from mItemRotation. */ @@ -665,10 +668,12 @@ class CORE_EXPORT QgsComposerItem: public QgsComposerObject, public QGraphicsRec void itemRotationChanged( double newRotation ); //! Emitted if the rectangle changes void sizeChanged(); + /** Emitted if the item's frame style changes * @note: this function was introduced in version 2.2 */ void frameChanged(); + /** Emitted if the item's lock status changes * @note: this function was introduced in version 2.5 */ diff --git a/src/core/composer/qgscomposeritemgroup.h b/src/core/composer/qgscomposeritemgroup.h index 50b3a2f3cee5..09e3132963a3 100644 --- a/src/core/composer/qgscomposeritemgroup.h +++ b/src/core/composer/qgscomposeritemgroup.h @@ -40,6 +40,7 @@ class CORE_EXPORT QgsComposerItemGroup: public QgsComposerItem void removeItems() override; //! Draw outline and ev. selection handles void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; + /** Sets this items bound in scene coordinates such that 1 item size units corresponds to 1 scene size unit*/ void setSceneRect( const QRectF& rectangle ) override; diff --git a/src/core/composer/qgscomposerlabel.h b/src/core/composer/qgscomposerlabel.h index 01717869cb1f..300adc7ecb43 100644 --- a/src/core/composer/qgscomposerlabel.h +++ b/src/core/composer/qgscomposerlabel.h @@ -55,19 +55,23 @@ class CORE_EXPORT QgsComposerLabel: public QgsComposerItem QFont font() const; void setFont( const QFont& f ); + /** Accessor for the vertical alignment of the label * @returns Qt::AlignmentFlag */ Qt::AlignmentFlag vAlign() const { return mVAlignment; } + /** Accessor for the horizontal alignment of the label * @returns Qt::AlignmentFlag */ Qt::AlignmentFlag hAlign() const { return mHAlignment; } + /** Mutator for the horizontal alignment of the label * @param a alignment * @returns void */ void setHAlign( Qt::AlignmentFlag a ) {mHAlignment = a;} + /** Mutator for the vertical alignment of the label * @param a alignment * @returns void diff --git a/src/core/composer/qgscomposerlegend.h b/src/core/composer/qgscomposerlegend.h index 98ce51401591..8e0a2f799d41 100644 --- a/src/core/composer/qgscomposerlegend.h +++ b/src/core/composer/qgscomposerlegend.h @@ -128,6 +128,7 @@ class CORE_EXPORT QgsComposerLegend : public QgsComposerItem * @see setTitleAlignment */ Qt::AlignmentFlag titleAlignment() const; + /** Sets the alignment of the legend title * @param alignment Text alignment for drawing the legend title * @note added in 2.3 diff --git a/src/core/composer/qgscomposerlegenditem.h b/src/core/composer/qgscomposerlegenditem.h index ff74c0fdfeab..6002de3ab617 100644 --- a/src/core/composer/qgscomposerlegenditem.h +++ b/src/core/composer/qgscomposerlegenditem.h @@ -44,6 +44,7 @@ class CORE_EXPORT QgsComposerLegendItem: public QStandardItem }; virtual void writeXml( QDomElement& elem, QDomDocument& doc ) const = 0; + /** Read item content from xml @param itemElem item to read from @param xServerAvailable Read item icons if true (QIcon needs x-server)*/ diff --git a/src/core/composer/qgscomposermap.h b/src/core/composer/qgscomposermap.h index 6a8476323884..b8f5f7d8b6ec 100644 --- a/src/core/composer/qgscomposermap.h +++ b/src/core/composer/qgscomposermap.h @@ -202,13 +202,16 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem * map will use the same configuration as the map canvas uses. * @note added in 2.16 */ bool followVisibilityPreset() const { return mFollowVisibilityPreset; } + /** Sets whether the map should follow a map theme. See followVisibilityPreset() for more details. * @note added in 2.16 */ void setFollowVisibilityPreset( bool follow ) { mFollowVisibilityPreset = follow; } + /** Preset name that decides which layers and layer styles are used for map rendering. It is only * used when followVisibilityPreset() returns true. * @note added in 2.16 */ QString followVisibilityPresetName() const { return mFollowVisibilityPresetName; } + /** Sets preset name for map rendering. See followVisibilityPresetName() for more details. * @note added in 2.16 */ void setFollowVisibilityPresetName( const QString& name ) { mFollowVisibilityPresetName = name; } @@ -472,6 +475,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem //! Map rotation double mMapRotation; + /** Temporary evaluated map rotation. Data defined rotation may mean this value * differs from mMapRotation*/ double mEvaluatedMapRotation; @@ -490,6 +494,7 @@ class CORE_EXPORT QgsComposerMap : public QgsComposerItem * in mVisibilityPresetName and may be overridden by data-defined expression). * This flag has higher priority than mKeepLayerSet. */ bool mFollowVisibilityPreset; + /** Map theme name to be used for map's layers and styles in case mFollowVisibilityPreset * is true. May be overridden by data-defined expression. */ QString mFollowVisibilityPresetName; diff --git a/src/core/composer/qgscomposerobject.h b/src/core/composer/qgscomposerobject.h index 706793352583..97df132496e5 100644 --- a/src/core/composer/qgscomposerobject.h +++ b/src/core/composer/qgscomposerobject.h @@ -206,12 +206,14 @@ class CORE_EXPORT QgsComposerObject: public QObject, public QgsExpressionContext bool dataDefinedEvaluate( const QgsComposerObject::DataDefinedProperty property, QVariant &expressionValue, const QgsExpressionContext& context = QgsExpressionContext() ) const; signals: + /** Emitted when the item changes. Signifies that the item widgets must update the * gui elements. */ void itemChanged(); private slots: + /** Prepares all composer item data defined expressions using the current atlas coverage layer if set. * @note this method was added in version 2.5 */ diff --git a/src/core/composer/qgscomposerscalebar.h b/src/core/composer/qgscomposerscalebar.h index f22c5df93417..ba39365b7c4e 100644 --- a/src/core/composer/qgscomposerscalebar.h +++ b/src/core/composer/qgscomposerscalebar.h @@ -23,6 +23,7 @@ class QgsComposerMap; class QgsScaleBarStyle; + /** \ingroup core * A scale bar item that can be added to a map composition. */ @@ -232,6 +233,7 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem * @see setLineJoinStyle */ Qt::PenJoinStyle lineJoinStyle() const { return mLineJoinStyle; } + /** Sets join style used when drawing the lines in the scalebar * @param style Join style for lines * @returns nothing @@ -246,6 +248,7 @@ class CORE_EXPORT QgsComposerScaleBar: public QgsComposerItem * @see setLineCapStyle */ Qt::PenCapStyle lineCapStyle() const { return mLineCapStyle; } + /** Sets cap style used when drawing the lines in the scalebar * @param style Cap style for lines * @returns nothing diff --git a/src/core/composer/qgscomposershape.h b/src/core/composer/qgscomposershape.h index b1a24a953805..89a2de9dfb3f 100644 --- a/src/core/composer/qgscomposershape.h +++ b/src/core/composer/qgscomposershape.h @@ -73,6 +73,7 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem * enable drawing with a symbol. * Note: added in version 2.1*/ void setShapeStyleSymbol( QgsFillSymbol* symbol ); + /** Returns the QgsFillSymbol used to draw the shape. * Note: added in version 2.1*/ QgsFillSymbol* shapeStyleSymbol() { return mShapeStyleSymbol; } @@ -98,11 +99,13 @@ class CORE_EXPORT QgsComposerShape: public QgsComposerItem virtual void drawFrame( QPainter* p ) override; /* reimplement drawBackground, since it's not a rect, but a custom shape */ virtual void drawBackground( QPainter* p ) override; + /** Reimplement estimatedFrameBleed, since frames on shapes are drawn using symbology * rather than the item's pen */ virtual double estimatedFrameBleed() const override; public slots: + /** Should be called after the shape's symbol is changed. Redraws the shape and recalculates * its selection bounds. * Note: added in version 2.1*/ diff --git a/src/core/composer/qgscomposition.h b/src/core/composer/qgscomposition.h index c05cf7fec192..f75dbd503686 100644 --- a/src/core/composer/qgscomposition.h +++ b/src/core/composer/qgscomposition.h @@ -544,6 +544,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo QGraphicsLineItem* addSnapLine(); //! Remove custom snap line (and delete the object) void removeSnapLine( QGraphicsLineItem* line ); + /** Get nearest snap line * @note not available in python bindings */ @@ -570,6 +571,7 @@ class CORE_EXPORT QgsComposition : public QGraphicsScene, public QgsExpressionCo void addMultiFrame( QgsComposerMultiFrame* multiFrame ); //! Removes multi frame (but does not delete it) void removeMultiFrame( QgsComposerMultiFrame* multiFrame ); + /** Adds an arrow item to the graphics scene and advises composer to create a widget for it (through signal) @note not available in python bindings*/ void addComposerArrow( QgsComposerArrow* arrow ); diff --git a/src/core/composer/qgsscalebarstyle.h b/src/core/composer/qgsscalebarstyle.h index 56ea11a57ef7..23e4cf991ff4 100644 --- a/src/core/composer/qgsscalebarstyle.h +++ b/src/core/composer/qgsscalebarstyle.h @@ -39,6 +39,7 @@ class CORE_EXPORT QgsScaleBarStyle virtual void draw( QPainter* p, double xOffset = 0 ) const = 0; //to do by every subclass virtual void drawLabels( QPainter* p ) const; //default implementation provided virtual QRectF calculateBoxSize() const; //default implementation provided + /** * Get a name for this style. * Needs to be remiplmeented by subclasses. diff --git a/src/core/diagram/qgsdiagram.h b/src/core/diagram/qgsdiagram.h index 756fb1ef504e..8b210eb5721c 100644 --- a/src/core/diagram/qgsdiagram.h +++ b/src/core/diagram/qgsdiagram.h @@ -36,6 +36,7 @@ class CORE_EXPORT QgsDiagram { public: virtual ~QgsDiagram() { clearCache(); } + /** Returns an instance that is equivalent to this one * @note added in 2.4 */ virtual QgsDiagram* clone() const = 0; diff --git a/src/core/effects/qgsimageoperation.h b/src/core/effects/qgsimageoperation.h index c5d94e6cb2a3..4af7a36b8e5e 100644 --- a/src/core/effects/qgsimageoperation.h +++ b/src/core/effects/qgsimageoperation.h @@ -116,14 +116,17 @@ class CORE_EXPORT QgsImageOperation * on opaque pixels */ bool shadeExterior; + /** Set to true to automatically calculate the maximum distance in the * transform to use as the spread value */ bool useMaxDistance; + /** Maximum distance (in pixels) for the distance transform shading to * spread */ double spread; + /** Color ramp to use for shading the distance transform */ QgsColorRamp* ramp; diff --git a/src/core/geometry/qgsabstractgeometry.h b/src/core/geometry/qgsabstractgeometry.h index 3f8d0220d15b..a88f6de87e84 100644 --- a/src/core/geometry/qgsabstractgeometry.h +++ b/src/core/geometry/qgsabstractgeometry.h @@ -70,6 +70,7 @@ class CORE_EXPORT QgsAbstractGeometry virtual QgsRectangle boundingBox() const = 0; //mm-sql interface + /** Returns the inherent dimension of the geometry. For example, this is 0 for a point geometry, * 1 for a linestring and 2 for a polygon. */ diff --git a/src/core/geometry/qgscircularstring.h b/src/core/geometry/qgscircularstring.h index cbf52042fdee..e37fa2b39da1 100644 --- a/src/core/geometry/qgscircularstring.h +++ b/src/core/geometry/qgscircularstring.h @@ -75,10 +75,12 @@ class CORE_EXPORT QgsCircularString: public QgsCurve * @copydoc QgsCurve::startPoint() */ virtual QgsPointV2 startPoint() const override; + /** * @copydoc QgsCurve::endPoint() */ virtual QgsPointV2 endPoint() const override; + /** Returns a new line string geometry corresponding to a segmentized approximation * of the curve. * @param tolerance segmentation tolerance @@ -101,6 +103,7 @@ class CORE_EXPORT QgsCircularString: public QgsCurve virtual bool deleteVertex( QgsVertexId position ) override; double closestSegment( const QgsPointV2& pt, QgsPointV2& segmentPt, QgsVertexId& vertexAfter, bool* leftOf, double epsilon ) const override; + /** * @copydoc QgsCurve::pointAt() */ diff --git a/src/core/geometry/qgscompoundcurve.h b/src/core/geometry/qgscompoundcurve.h index 939c9145cb4e..a193a4fde145 100644 --- a/src/core/geometry/qgscompoundcurve.h +++ b/src/core/geometry/qgscompoundcurve.h @@ -58,6 +58,7 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve virtual QgsPointV2 endPoint() const override; virtual void points( QgsPointSequence &pts ) const override; virtual int numPoints() const override; + /** Returns a new line string geometry corresponding to a segmentized approximation * of the curve. * @param tolerance segmentation tolerance @@ -128,6 +129,7 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve private: QList< QgsCurve* > mCurves; + /** Turns a vertex id for the compound curve into one or more ids for the subcurves @return the index of the subcurve or -1 in case of error*/ QList< QPair > curveVertexId( QgsVertexId id ) const; diff --git a/src/core/geometry/qgscurvepolygon.h b/src/core/geometry/qgscurvepolygon.h index f96fc511b75d..9bec8122d8d0 100644 --- a/src/core/geometry/qgscurvepolygon.h +++ b/src/core/geometry/qgscurvepolygon.h @@ -61,6 +61,7 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface int numInteriorRings() const; const QgsCurve* exteriorRing() const; const QgsCurve* interiorRing( int i ) const; + /** Returns a new polygon geometry corresponding to a segmentized approximation * of the curve. * @param tolerance segmentation tolerance @@ -98,6 +99,7 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface bool nextVertex( QgsVertexId& id, QgsPointV2& vertex ) const override; bool hasCurvedSegments() const override; + /** Returns a geometry without curves. Caller takes ownership * @param tolerance segmentation tolerance * @param toleranceType maximum segmentation angle or maximum difference between approximation and curve*/ diff --git a/src/core/geometry/qgsgeometryeditutils.h b/src/core/geometry/qgsgeometryeditutils.h index 21e35823f558..36f3b9b00013 100644 --- a/src/core/geometry/qgsgeometryeditutils.h +++ b/src/core/geometry/qgsgeometryeditutils.h @@ -34,6 +34,7 @@ class QgsVectorLayer; class QgsGeometryEditUtils { public: + /** Adds interior ring (taking ownership). @return 0 in case of success (ring added), 1 problem with geometry type, 2 ring not closed, 3 ring is not valid geometry, 4 ring not disjoint with existing rings, 5 no polygon found which contained the ring*/ diff --git a/src/core/geometry/qgsgeometryfactory.h b/src/core/geometry/qgsgeometryfactory.h index da020f44d216..f3e2bcbbf740 100644 --- a/src/core/geometry/qgsgeometryfactory.h +++ b/src/core/geometry/qgsgeometryfactory.h @@ -43,6 +43,7 @@ typedef QVector QgsMultiPolygon; class CORE_EXPORT QgsGeometryFactory { public: + /** Construct geometry from a WKB string. */ static QgsAbstractGeometry* geomFromWkb( QgsConstWkbPtr wkb ); diff --git a/src/core/geometry/qgsgeos.h b/src/core/geometry/qgsgeos.h index d870d8ddffab..37dc46457c03 100644 --- a/src/core/geometry/qgsgeos.h +++ b/src/core/geometry/qgsgeos.h @@ -31,6 +31,7 @@ class QgsGeometry; class CORE_EXPORT QgsGeos: public QgsGeometryEngine { public: + /** GEOS geometry engine constructor * @param geometry The geometry * @param precision The precision of the grid to which to snap the geometry vertices. If 0, no snapping is performed. diff --git a/src/core/geometry/qgsinternalgeometryengine.h b/src/core/geometry/qgsinternalgeometryengine.h index 462df0ff297a..f6d1eff3df31 100644 --- a/src/core/geometry/qgsinternalgeometryengine.h +++ b/src/core/geometry/qgsinternalgeometryengine.h @@ -32,6 +32,7 @@ class QgsAbstractGeometry; class QgsInternalGeometryEngine { public: + /** * The caller is responsible that the geometry is available and unchanged * for the whole lifetime of this object. diff --git a/src/core/geometry/qgslinestring.h b/src/core/geometry/qgslinestring.h index 489972a1631f..25befa6dda79 100644 --- a/src/core/geometry/qgslinestring.h +++ b/src/core/geometry/qgslinestring.h @@ -149,6 +149,7 @@ class CORE_EXPORT QgsLineString: public QgsCurve virtual double length() const override; virtual QgsPointV2 startPoint() const override; virtual QgsPointV2 endPoint() const override; + /** Returns a new line string geometry corresponding to a segmentized approximation * of the curve. * @param tolerance segmentation tolerance diff --git a/src/core/pal/feature.h b/src/core/pal/feature.h index 36b181f5deb2..725d2a6892bc 100644 --- a/src/core/pal/feature.h +++ b/src/core/pal/feature.h @@ -212,6 +212,7 @@ namespace pal bool hasSameLabelFeatureAs( FeaturePart* part ) const; #if 0 + /** * \brief Print feature information * Print feature unique id, geometry type, points, and holes on screen diff --git a/src/core/pal/geomfunction.h b/src/core/pal/geomfunction.h index 2e3e8d0e8b96..c7028511adeb 100644 --- a/src/core/pal/geomfunction.h +++ b/src/core/pal/geomfunction.h @@ -35,6 +35,7 @@ namespace pal { + /** * \ingroup core * \class pal::GeomFunction diff --git a/src/core/pal/labelposition.h b/src/core/pal/labelposition.h index 7a17211f29d2..bdbe7ed13b3c 100644 --- a/src/core/pal/labelposition.h +++ b/src/core/pal/labelposition.h @@ -163,6 +163,7 @@ namespace pal void resetNumOverlaps() { nbOverlap = 0; } // called from problem.cpp, pal.cpp int getProblemFeatureId() const { return probFeat; } + /** Set problem feature ID and assigned label candidate ID. * called from pal.cpp during extraction */ void setProblemIds( int probFid, int lpId ) @@ -203,6 +204,7 @@ namespace pal * \return x coordinate */ double getX( int i = 0 ) const; + /** * \brief get the down-left y coordinate * \return y coordinate diff --git a/src/core/pal/pal.h b/src/core/pal/pal.h index ec79bfcaeb34..2cf1f96bc8d3 100644 --- a/src/core/pal/pal.h +++ b/src/core/pal/pal.h @@ -317,6 +317,7 @@ namespace pal * @return minimum # of iteration */ int getMinIt(); + /** * \brief Get the maximum # of iteration doing in POPMUSIC_TABU, POPMUSIC_CHAIN and POPMUSIC_TABU_CHAIN * @return maximum # of iteration diff --git a/src/core/pal/priorityqueue.h b/src/core/pal/priorityqueue.h index 72758617b1db..f9a36abf21c9 100644 --- a/src/core/pal/priorityqueue.h +++ b/src/core/pal/priorityqueue.h @@ -39,6 +39,7 @@ namespace pal { + /** * \ingroup core * \class pal::PriorityQueue @@ -48,6 +49,7 @@ namespace pal { public: + /** \brief Create a priority queue of max size n * \@param n max size of the queuet * \@param p external vector representing the priority diff --git a/src/core/pal/problem.h b/src/core/pal/problem.h index 2a787509cee9..86c8f18466f1 100644 --- a/src/core/pal/problem.h +++ b/src/core/pal/problem.h @@ -54,6 +54,7 @@ namespace pal typedef struct _subpart { + /** * # of features in problem */ @@ -73,10 +74,12 @@ namespace pal * wrap bw sub feat and main feat */ int *sub; + /** * sub solution */ int *sol; + /** * first feat in sub part */ @@ -192,6 +195,7 @@ namespace pal * # active candidates (remaining after reduce()) */ int nblp; + /** * # candidates (all, including) */ diff --git a/src/core/pal/rtree.hpp b/src/core/pal/rtree.hpp index 773a93d81584..b998b41699c5 100644 --- a/src/core/pal/rtree.hpp +++ b/src/core/pal/rtree.hpp @@ -363,6 +363,7 @@ namespace pal // Because there is not stream support, this is a quick and dirty file I/O helper. // Users will likely replace its usage with a Stream implementation from their favorite API. + /** \ingroup core */ class RTFileStream diff --git a/src/core/pal/util.h b/src/core/pal/util.h index e8c0151af16c..fad6e71d8ff6 100644 --- a/src/core/pal/util.h +++ b/src/core/pal/util.h @@ -82,6 +82,7 @@ namespace pal class Util { public: + /** * \brief Sort an array of pointers * \param items arays of pointers to sort diff --git a/src/core/qgis.h b/src/core/qgis.h index d2d45d6c607d..1dd9cabe755d 100644 --- a/src/core/qgis.h +++ b/src/core/qgis.h @@ -306,6 +306,7 @@ const int PROJ_PREFIX_LEN = 6; const int ELLPS_PREFIX_LEN = 7; //! The length of the string "+lat_1=" const int LAT_PREFIX_LEN = 7; + /** Magick number that determines whether a projection crsid is a system (srs.db) * or user (~/.qgis.qgis.db) defined projection. */ const int USER_CRS_START_ID = 100000; diff --git a/src/core/qgsaggregatecalculator.h b/src/core/qgsaggregatecalculator.h index 1c1f92b741c2..18df5d51bdca 100644 --- a/src/core/qgsaggregatecalculator.h +++ b/src/core/qgsaggregatecalculator.h @@ -70,6 +70,7 @@ class CORE_EXPORT QgsAggregateCalculator //! A bundle of parameters controlling aggregate calculation struct AggregateParameters { + /** Optional filter for calculating aggregate over a subset of features, or an * empty string to use all features. * @see QgsAggregateCalculator::setFilter() diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index 064060ae45d7..551610f42bc4 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -411,12 +411,15 @@ class CORE_EXPORT QgsApplication : public QApplication #endif //! Path to the output directory of the build. valid only when running from build directory static QString ABISYM( mBuildOutputPath ); + /** List of gdal drivers to be skipped. Uses GDAL_SKIP to exclude them. * @see skipGdalDriver, restoreGdalDriver */ static QStringList ABISYM( mGdalSkipList ); + /** * @note added in 2.4 */ static int ABISYM( mMaxThreads ); + /** * @note added in 2.12 */ static QString ABISYM( mAuthDbDirPath ); diff --git a/src/core/qgsattributeeditorelement.h b/src/core/qgsattributeeditorelement.h index 4c34336ba5bf..5e6535db7d19 100644 --- a/src/core/qgsattributeeditorelement.h +++ b/src/core/qgsattributeeditorelement.h @@ -117,6 +117,7 @@ class CORE_EXPORT QgsAttributeEditorElement bool mShowLabel; private: + /** * Should be implemented by subclasses to save type specific configuration. * @@ -141,6 +142,7 @@ class CORE_EXPORT QgsAttributeEditorElement class CORE_EXPORT QgsAttributeEditorContainer : public QgsAttributeEditorElement { public: + /** * Creates a new attribute editor container * @@ -254,6 +256,7 @@ class CORE_EXPORT QgsAttributeEditorContainer : public QgsAttributeEditorElement class CORE_EXPORT QgsAttributeEditorField : public QgsAttributeEditorElement { public: + /** * Creates a new attribute editor element which represents a field * @@ -289,6 +292,7 @@ class CORE_EXPORT QgsAttributeEditorField : public QgsAttributeEditorElement class CORE_EXPORT QgsAttributeEditorRelation : public QgsAttributeEditorElement { public: + /** * Creates a new element which embeds a relation. * @@ -344,6 +348,7 @@ class CORE_EXPORT QgsAttributeEditorRelation : public QgsAttributeEditorElement * @note Added in QGIS 2.18 */ bool showLinkButton() const; + /** * Determines if the "link feature" button should be shown * @@ -357,6 +362,7 @@ class CORE_EXPORT QgsAttributeEditorRelation : public QgsAttributeEditorElement * @note Added in QGIS 2.18 */ bool showUnlinkButton() const; + /** * Determines if the "unlink feature" button should be shown * diff --git a/src/core/qgsattributetableconfig.h b/src/core/qgsattributetableconfig.h index d2fb4608b5e2..32448c926070 100644 --- a/src/core/qgsattributetableconfig.h +++ b/src/core/qgsattributetableconfig.h @@ -32,6 +32,7 @@ class QgsFields; class CORE_EXPORT QgsAttributeTableConfig { public: + /** * The type of an attribute table column. */ diff --git a/src/core/qgscachedfeatureiterator.h b/src/core/qgscachedfeatureiterator.h index 1e78f984817b..5dfb365cfec6 100644 --- a/src/core/qgscachedfeatureiterator.h +++ b/src/core/qgscachedfeatureiterator.h @@ -54,6 +54,7 @@ class CORE_EXPORT QgsCachedFeatureIterator : public QgsAbstractFeatureIterator // QgsAbstractFeatureIterator interface protected: + /** * Implementation for fetching a feature. * @@ -86,6 +87,7 @@ class CORE_EXPORT QgsCachedFeatureIterator : public QgsAbstractFeatureIterator class CORE_EXPORT QgsCachedFeatureWriterIterator : public QgsAbstractFeatureIterator { public: + /** * This constructor creates a feature iterator, which queries the backend and caches retrieved features. * diff --git a/src/core/qgsconditionalstyle.h b/src/core/qgsconditionalstyle.h index d703a8d34abd..33fd56a33793 100644 --- a/src/core/qgsconditionalstyle.h +++ b/src/core/qgsconditionalstyle.h @@ -173,6 +173,7 @@ class CORE_EXPORT QgsConditionalStyle * @return True of the color set for background is valid. */ bool validBackgroundColor() const; + /** * @brief The font for the style * @return QFont for the style diff --git a/src/core/qgscoordinatereferencesystem.h b/src/core/qgscoordinatereferencesystem.h index 0be1c0217f1a..d5f7c5908f89 100644 --- a/src/core/qgscoordinatereferencesystem.h +++ b/src/core/qgscoordinatereferencesystem.h @@ -427,6 +427,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem * Internally it will use authid() for comparison. */ bool operator==( const QgsCoordinateReferenceSystem &theSrs ) const; + /** Overloaded != operator used to compare to CRS's. * * Returns opposite bool value to operator == @@ -438,6 +439,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem * @return bool True on success, False on failure */ bool readXml( const QDomNode & theNode ); + /** Stores state to the given Dom node in the given document. * @param theNode The node in which state will be restored * @param theDoc The document in which state will be stored @@ -538,6 +540,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem QgsUnitTypes::DistanceUnit mapUnits() const; // Mutators ----------------------------------- + /** Set user hint for validation */ void setValidationHint( const QString& html ); @@ -579,6 +582,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem // We don't want to expose these to the public api since they wont create // a fully valid crs. Programmers should use the createFrom* methods rather private: + /** A static helper function to find out the proj4 string for a srsid * @param theSrsId The srsid used for the lookup * @return QString The proj4 string @@ -589,10 +593,12 @@ class CORE_EXPORT QgsCoordinateReferenceSystem * @param theSrsId The internal sqlite3 srs.db primary key for this CRS */ void setInternalId( long theSrsId ); + /** Set the postgis srid * @param theSrid The postgis spatial_ref_sys key for this CRS */ void setSrid( long theSrid ); + /** Set the Description * @param theDescription A textual description of the CRS. */ @@ -624,10 +630,12 @@ class CORE_EXPORT QgsCoordinateReferenceSystem * @param theID the authority identifier for this CRS (defaults to 0) */ void setAuthId( const QString& theID ); + /** Set the projection acronym * @param theProjectionAcronym the acronym (must be a valid proj4 projection acronym) */ void setProjectionAcronym( const QString& theProjectionAcronym ); + /** Set the ellipsoid acronym * @param theEllipsoidAcronym the acronym (must be a valid proj4 ellipsoid acronym) */ @@ -639,6 +647,7 @@ class CORE_EXPORT QgsCoordinateReferenceSystem //! A string based associative array used for passing records around typedef QMap RecordMap; + /** Get a record from the srs.db or qgis.db backends, given an sql statment. * @note only handles queries that return a single record. * @note it will first try the system srs.db then the users qgis.db! diff --git a/src/core/qgscoordinatetransform.h b/src/core/qgscoordinatetransform.h index f7ef285c7214..49e8139eab26 100644 --- a/src/core/qgscoordinatetransform.h +++ b/src/core/qgscoordinatetransform.h @@ -244,6 +244,7 @@ class CORE_EXPORT QgsCoordinateTransform */ static QList< QList< int > > datumTransformations( const QgsCoordinateReferenceSystem& srcCRS, const QgsCoordinateReferenceSystem& destinationCrs ); static QString datumTransformString( int datumTransform ); + /** Gets name of source and dest geographical CRS (to show in a tooltip) @return epsgNr epsg code of the transformation (or 0 if not in epsg db)*/ static bool datumTransformCrsInfo( int datumTransform, int& epsgNr, QString& srcProjection, QString& dstProjection, QString &remarks, QString &scope, bool &preferred, bool &deprecated ); diff --git a/src/core/qgscsexception.h b/src/core/qgscsexception.h index d664b6d5705c..8e4e4562a412 100644 --- a/src/core/qgscsexception.h +++ b/src/core/qgscsexception.h @@ -18,6 +18,7 @@ #define QGSCSEXCEPTION_H #include "qgsexception.h" + /** \ingroup core * Custom exception class for Coordinate Reference System related exceptions. */ diff --git a/src/core/qgsdatadefined.h b/src/core/qgsdatadefined.h index 285fe6e2a08e..c682e154af0f 100644 --- a/src/core/qgsdatadefined.h +++ b/src/core/qgsdatadefined.h @@ -36,6 +36,7 @@ class QgsDataDefinedPrivate; class CORE_EXPORT QgsDataDefined { public: + /** * Construct a new data defined object * diff --git a/src/core/qgsdataitem.h b/src/core/qgsdataitem.h index aea6f8ba3e2e..c38e9453ec8a 100644 --- a/src/core/qgsdataitem.h +++ b/src/core/qgsdataitem.h @@ -212,6 +212,7 @@ class CORE_EXPORT QgsDataItem : public QObject /** Get item parent. QgsDataItem maintains its own items hierarchy, it does not use * QObject hierarchy. */ QgsDataItem* parent() const { return mParent; } + /** Set item parent and connect / disconnect parent to / from item signals. * It does not add itself to parents children (mChildren) */ void setParent( QgsDataItem* parent ); @@ -272,6 +273,7 @@ class CORE_EXPORT QgsDataItem : public QObject QMap mIconMap; public slots: + /** Safely delete the item: * - disconnects parent * - unsets parent (but does not remove itself) @@ -501,6 +503,7 @@ class CORE_EXPORT QgsErrorItem : public QgsDataItem // --------- + /** \ingroup core * \class QgsDirectoryParamWidget */ diff --git a/src/core/qgsdataprovider.h b/src/core/qgsdataprovider.h index ea37a5d54cf8..c690dcd285ca 100644 --- a/src/core/qgsdataprovider.h +++ b/src/core/qgsdataprovider.h @@ -422,6 +422,7 @@ class CORE_EXPORT QgsDataProvider : public QObject void dataChanged( int changed ); protected: + /** * Timestamp of data in the moment when the data were loaded by provider. */ diff --git a/src/core/qgseditorwidgetsetup.h b/src/core/qgseditorwidgetsetup.h index 40dc2933eae2..9e60b12b410d 100644 --- a/src/core/qgseditorwidgetsetup.h +++ b/src/core/qgseditorwidgetsetup.h @@ -26,6 +26,7 @@ class CORE_EXPORT QgsEditorWidgetSetup { public: + /** * Constructor */ diff --git a/src/core/qgsexpression.h b/src/core/qgsexpression.h index eb2d8133f70c..96b4cd913298 100644 --- a/src/core/qgsexpression.h +++ b/src/core/qgsexpression.h @@ -110,6 +110,7 @@ class CORE_EXPORT QgsExpression { Q_DECLARE_TR_FUNCTIONS( QgsExpression ) public: + /** * Creates a new expression based on the provided string. * The string will immediately be parsed. For optimization diff --git a/src/core/qgsexpressioncontext.h b/src/core/qgsexpressioncontext.h index 008e7fefbfa0..c2a73db13013 100644 --- a/src/core/qgsexpressioncontext.h +++ b/src/core/qgsexpressioncontext.h @@ -41,6 +41,7 @@ class QgsSymbol; class CORE_EXPORT QgsScopedExpressionFunction : public QgsExpression::Function { public: + /** * Create a new QgsScopedExpressionFunction * @@ -98,6 +99,7 @@ class CORE_EXPORT QgsExpressionContextScope */ struct StaticVariable { + /** Constructor for StaticVariable. * @param name variable name (should be unique within the QgsExpressionContextScope) * @param value intial variable value diff --git a/src/core/qgsexpressioncontextgenerator.h b/src/core/qgsexpressioncontextgenerator.h index ed1c5cdd8ef6..c84fb61ae008 100644 --- a/src/core/qgsexpressioncontextgenerator.h +++ b/src/core/qgsexpressioncontextgenerator.h @@ -36,6 +36,7 @@ class QgsExpressionContextGenerator { public: + /** * This method needs to be reimplemented in all classes which implement this interface * and return an expression context. diff --git a/src/core/qgsexpressionprivate.h b/src/core/qgsexpressionprivate.h index cda774671280..09986399712c 100644 --- a/src/core/qgsexpressionprivate.h +++ b/src/core/qgsexpressionprivate.h @@ -25,6 +25,7 @@ #include "qgsunittypes.h" ///@cond + /** * This class exists only for implicit sharing of QgsExpression * and is not part of the public API. diff --git a/src/core/qgsfeature.h b/src/core/qgsfeature.h index d39a43f36e79..ef7e71cc1941 100644 --- a/src/core/qgsfeature.h +++ b/src/core/qgsfeature.h @@ -58,6 +58,7 @@ class CORE_EXPORT QgsAttributes : public QVector QgsAttributes() : QVector() {} + /** * Create a new vector of attributes with the given size * @@ -66,6 +67,7 @@ class CORE_EXPORT QgsAttributes : public QVector QgsAttributes( int size ) : QVector( size ) {} + /** * Constructs a vector with an initial size of size elements. Each element is initialized with value. * @param size Number of elements diff --git a/src/core/qgsfeatureiterator.h b/src/core/qgsfeatureiterator.h index 2d870a236ecb..9bc11ff1d9f0 100644 --- a/src/core/qgsfeatureiterator.h +++ b/src/core/qgsfeatureiterator.h @@ -77,6 +77,7 @@ class CORE_EXPORT QgsAbstractFeatureIterator CompileStatus compileStatus() const { return mCompileStatus; } protected: + /** * If you write a feature iterator for your provider, this is the method you * need to implement!! diff --git a/src/core/qgsfeaturerequest.h b/src/core/qgsfeaturerequest.h index bba2cc1075e3..25158e7919a8 100644 --- a/src/core/qgsfeaturerequest.h +++ b/src/core/qgsfeaturerequest.h @@ -109,6 +109,7 @@ class CORE_EXPORT QgsFeatureRequest class CORE_EXPORT OrderByClause { public: + /** * Creates a new OrderByClause for a QgsFeatureRequest * @@ -118,6 +119,7 @@ class CORE_EXPORT QgsFeatureRequest * If the order is descending, by default nulls are first */ OrderByClause( const QString &expression, bool ascending = true ); + /** * Creates a new OrderByClause for a QgsFeatureRequest * @@ -177,6 +179,7 @@ class CORE_EXPORT QgsFeatureRequest class OrderBy : public QList { public: + /** * Create a new empty order by */ @@ -323,6 +326,7 @@ class CORE_EXPORT QgsFeatureRequest */ QgsFeatureRequest& addOrderBy( const QString &expression, bool ascending = true ); + /** * Adds a new OrderByClause, appending it as the least important one. * @@ -368,6 +372,7 @@ class CORE_EXPORT QgsFeatureRequest //! Set a subset of attributes that will be fetched. Empty list means that all attributes are used. //! To disable fetching attributes, reset the FetchAttributes flag (which is set by default) QgsFeatureRequest& setSubsetOfAttributes( const QgsAttributeList& attrs ); + /** * Return the subset of attributes which at least need to be fetched * @return A list of attributes to be fetched diff --git a/src/core/qgsfields.h b/src/core/qgsfields.h index 005ff43d6f0a..a4227a4a308b 100644 --- a/src/core/qgsfields.h +++ b/src/core/qgsfields.h @@ -173,6 +173,7 @@ class CORE_EXPORT QgsFields bool operator==( const QgsFields& other ) const; //! @note added in 2.6 bool operator!=( const QgsFields& other ) const { return !( *this == other ); } + /** Returns an icon corresponding to a field index, based on the field's type and source * @note added in QGIS 2.14 */ diff --git a/src/core/qgsfontutils.h b/src/core/qgsfontutils.h index c0956b98be5a..6c39c940b1d6 100644 --- a/src/core/qgsfontutils.h +++ b/src/core/qgsfontutils.h @@ -26,6 +26,7 @@ class CORE_EXPORT QgsFontUtils { public: + /** Check whether exact font is on system * @param f The font to test for match */ diff --git a/src/core/qgsgeometrysimplifier.cpp b/src/core/qgsgeometrysimplifier.cpp index 0bbb3c7407f8..bb2f430dd611 100644 --- a/src/core/qgsgeometrysimplifier.cpp +++ b/src/core/qgsgeometrysimplifier.cpp @@ -43,6 +43,7 @@ bool QgsAbstractGeometrySimplifier::isGeneralizableByDeviceBoundingBox( const QV } /***************************************************************************/ + /** * Implementation of GeometrySimplifier using the Douglas-Peucker algorithm */ diff --git a/src/core/qgsgeometrysimplifier.h b/src/core/qgsgeometrysimplifier.h index c9d68419e40d..cb891d23e27a 100644 --- a/src/core/qgsgeometrysimplifier.h +++ b/src/core/qgsgeometrysimplifier.h @@ -43,6 +43,7 @@ class CORE_EXPORT QgsAbstractGeometrySimplifier }; /***************************************************************************/ + /** \ingroup core * Implementation of GeometrySimplifier using the Douglas-Peucker algorithm * diff --git a/src/core/qgsgml.h b/src/core/qgsgml.h index 7e54d11b9f53..cc801e83ab3c 100644 --- a/src/core/qgsgml.h +++ b/src/core/qgsgml.h @@ -185,6 +185,7 @@ class CORE_EXPORT QgsGmlStreamingParser @return 0 in case of success */ int readEpsgFromAttribute( int& epsgNr, const XML_Char** attr ); + /** Reads attribute as string @param attributeName @param attr @@ -193,6 +194,7 @@ class CORE_EXPORT QgsGmlStreamingParser QString readAttribute( const QString& attributeName, const XML_Char** attr ) const; //! Creates a rectangle from a coordinate string. bool createBBoxFromCoordinateString( QgsRectangle &bb, const QString& coordString ) const; + /** Creates a set of points from a coordinate string. @param points list that will contain the created points @param coordString the text containing the coordinates @@ -212,6 +214,7 @@ class CORE_EXPORT QgsGmlStreamingParser int getPointWKB( QgsWkbPtr &wkbPtr, const QgsPoint& ) const; int getLineWKB( QgsWkbPtr &wkbPtr, const QList& lineCoordinates ) const; int getRingWKB( QgsWkbPtr &wkbPtr, const QList& ringCoordinates ) const; + /** Creates a multiline from the information in mCurrentWKBFragments and * mCurrentWKBFragmentSizes. Assign the result. The multiline is in * mCurrentWKB. The function deletes the memory in @@ -276,6 +279,7 @@ class CORE_EXPORT QgsGmlStreamingParser QgsWkbPtr mCurrentWKB; QgsRectangle mCurrentExtent; bool mBoundedByNullFound; + /** WKB intermediate storage during parsing. For points and lines, no * intermediate WKB is stored at all. For multipoints and multilines and * polygons, only one nested list is used. For multipolygons, both nested lists diff --git a/src/core/qgslabelfeature.h b/src/core/qgslabelfeature.h index c7fdeb2ff5ad..2522beb47c52 100644 --- a/src/core/qgslabelfeature.h +++ b/src/core/qgslabelfeature.h @@ -38,6 +38,7 @@ class CORE_EXPORT QgsLabelFeature //! @note not available in Python bindings struct VisualMargin { + /** Default constructor, all margins are set to 0.0 */ VisualMargin() @@ -172,6 +173,7 @@ class CORE_EXPORT QgsLabelFeature * @see setPriority */ double priority() const { return mPriority; } + /** Sets the priority for labeling the feature. * @param priority feature's priority, as a value between 0 (highest priority) * and 1 (lowest priority). Set to -1.0 to use the layer's default priority @@ -219,6 +221,7 @@ class CORE_EXPORT QgsLabelFeature * @see quadOffset */ bool hasFixedQuadrant() const { return mHasFixedQuadrant; } + /** Sets whether the quadrant for the label must be respected. This can be used * to fix the quadrant for specific features when using an "around point" placement. * @see fixedQuadrant @@ -290,16 +293,19 @@ class CORE_EXPORT QgsLabelFeature * @see setIsObstacle */ bool isObstacle() const { return mIsObstacle; } + /** Sets whether the feature will act as an obstacle for labels. * @param enabled whether feature will act as an obstacle * @see isObstacle */ void setIsObstacle( bool enabled ) { mIsObstacle = enabled; } + /** Returns the obstacle factor for the feature. The factor controls the penalty * for labels overlapping this feature. * @see setObstacleFactor */ double obstacleFactor() const { return mObstacleFactor; } + /** Sets the obstacle factor for the feature. The factor controls the penalty * for labels overlapping this feature. * @param factor larger factors ( > 1.0 ) will result in labels diff --git a/src/core/qgslayerdefinition.h b/src/core/qgslayerdefinition.h index 01b46bb77b7c..519980c2a198 100644 --- a/src/core/qgslayerdefinition.h +++ b/src/core/qgslayerdefinition.h @@ -47,6 +47,7 @@ class CORE_EXPORT QgsLayerDefinition class CORE_EXPORT DependencySorter { public: + /** Constructor * @param doc The XML document containing maplayer elements */ diff --git a/src/core/qgslegendsettings.h b/src/core/qgslegendsettings.h index b32bdd94a136..b83475745927 100644 --- a/src/core/qgslegendsettings.h +++ b/src/core/qgslegendsettings.h @@ -46,6 +46,7 @@ class CORE_EXPORT QgsLegendSettings * @see setTitleAlignment */ Qt::AlignmentFlag titleAlignment() const { return mTitleAlignment; } + /** Sets the alignment of the legend title * @param alignment Text alignment for drawing the legend title * @see titleAlignment diff --git a/src/core/qgsmaplayer.h b/src/core/qgsmaplayer.h index 9d4ed928d485..0022ad37c6e6 100644 --- a/src/core/qgsmaplayer.h +++ b/src/core/qgsmaplayer.h @@ -394,10 +394,12 @@ class CORE_EXPORT QgsMapLayer : public QObject * @see removeCustomProperty() */ void setCustomProperty( const QString& key, const QVariant& value ); + /** Read a custom property from layer. Properties are stored in a map and saved in project file. * @see setCustomProperty() */ QVariant customProperty( const QString& value, const QVariant& defaultValue = QVariant() ) const; + /** Remove a custom property from layer. Properties are stored in a map and saved in project file. * @see setCustomProperty() */ @@ -590,6 +592,7 @@ class CORE_EXPORT QgsMapLayer : public QObject * @note added in 2.6 */ void setLegend( QgsMapLayerLegend* legend ); + /** * Can be null. * @note added in 2.6 @@ -860,6 +863,7 @@ class CORE_EXPORT QgsMapLayer : public QObject bool hasDependencyCycle( const QSet& layers ) const; private: + /** * This method returns true by default but can be overwritten to specify * that a certain layer is writable. diff --git a/src/core/qgsmaplayermodel.h b/src/core/qgsmaplayermodel.h index 33badce780c9..084d07f86482 100644 --- a/src/core/qgsmaplayermodel.h +++ b/src/core/qgsmaplayermodel.h @@ -45,6 +45,7 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel * @brief QgsMapLayerModel creates a model to display layers in widgets. */ explicit QgsMapLayerModel( QObject *parent = nullptr ); + /** * @brief QgsMapLayerModel creates a model to display a specific list of layers in a widget. */ @@ -54,10 +55,12 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel * @brief setItemsCheckable defines if layers should be selectable in the widget */ void setItemsCheckable( bool checkable ); + /** * @brief checkAll changes the checkstate for all the layers */ void checkAll( Qt::CheckState checkState ); + /** * @brief layersChecked returns the list of layers which are checked (or unchecked) */ diff --git a/src/core/qgsmaplayerregistry.h b/src/core/qgsmaplayerregistry.h index 73f2a7c782db..b8854d98b086 100644 --- a/src/core/qgsmaplayerregistry.h +++ b/src/core/qgsmaplayerregistry.h @@ -346,6 +346,7 @@ class CORE_EXPORT QgsMapLayerRegistry : public QObject protected: #if 0 + /** Debugging member * invoked when a connect() is made to this object */ diff --git a/src/core/qgsmaprendererjob.h b/src/core/qgsmaprendererjob.h index fd7ce11e4630..afc0ed87c840 100644 --- a/src/core/qgsmaprendererjob.h +++ b/src/core/qgsmaprendererjob.h @@ -141,6 +141,7 @@ class CORE_EXPORT QgsMapRendererJob : public QObject const QgsMapSettings& mapSettings() const; signals: + /** * Emitted when the layers are rendered. * Rendering labels is not yet done. If the fully rendered layer including labels is required use diff --git a/src/core/qgsmapsettings.h b/src/core/qgsmapsettings.h index b42be6671682..fd7e50f89c7f 100644 --- a/src/core/qgsmapsettings.h +++ b/src/core/qgsmapsettings.h @@ -286,6 +286,7 @@ class CORE_EXPORT QgsMapSettings void setSegmentationTolerance( double tolerance ) { mSegmentationTolerance = tolerance; } //! Gets the segmentation tolerance applied when rendering curved geometries double segmentationTolerance() const { return mSegmentationTolerance; } + /** Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation) @param type the segmentation tolerance typename*/ void setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType type ) { mSegmentationToleranceType = type; } diff --git a/src/core/qgsmultirenderchecker.h b/src/core/qgsmultirenderchecker.h index 0ab28ab00880..f151aabd7540 100644 --- a/src/core/qgsmultirenderchecker.h +++ b/src/core/qgsmultirenderchecker.h @@ -130,6 +130,7 @@ class CORE_EXPORT QgsMultiRenderChecker #ifdef ENABLE_TESTS ///@cond PRIVATE + /** \ingroup core * \class QgsCompositionChecker * Renders a composition to an image and compares with an expected output diff --git a/src/core/qgsogcutils.h b/src/core/qgsogcutils.h index fa908095797e..90d0b64b0d39 100644 --- a/src/core/qgsogcutils.h +++ b/src/core/qgsogcutils.h @@ -241,11 +241,13 @@ class CORE_EXPORT QgsOgcUtils static QgsGeometry geometryFromGMLMultiLineString( const QDomElement& geometryElement ); //! Static method that creates geometry from GML MultiPolygon static QgsGeometry geometryFromGMLMultiPolygon( const QDomElement& geometryElement ); + /** Reads the \verbatim \endverbatim element and extracts the coordinates as points @param coords list where the found coordinates are appended @param elem the \verbatim \endverbatim element @return boolean for success*/ static bool readGMLCoordinates( QgsPolyline &coords, const QDomElement &elem ); + /** Reads the \verbatim \endverbatim or \verbatim \endverbatim and extracts the coordinates as points @param coords list where the found coordinates are appended diff --git a/src/core/qgsoptional.h b/src/core/qgsoptional.h index 01e711bb8d9d..d1c5ca35fa70 100644 --- a/src/core/qgsoptional.h +++ b/src/core/qgsoptional.h @@ -32,6 +32,7 @@ template class CORE_EXPORT QgsOptional { public: + /** * A QgsOptional is disabled by default if default constructed. */ diff --git a/src/core/qgsoptionalexpression.h b/src/core/qgsoptionalexpression.h index 8ae56ff951d1..50723de0dce0 100644 --- a/src/core/qgsoptionalexpression.h +++ b/src/core/qgsoptionalexpression.h @@ -34,6 +34,7 @@ class CORE_EXPORT QgsOptionalExpression : public QgsOptional { public: + /** * Construct a default optional expression. * It will be disabled and with an empty expression. diff --git a/src/core/qgsowsconnection.h b/src/core/qgsowsconnection.h index e0231e6f80a7..defa0f4d496f 100644 --- a/src/core/qgsowsconnection.h +++ b/src/core/qgsowsconnection.h @@ -35,6 +35,7 @@ class CORE_EXPORT QgsOwsConnection : public QObject Q_OBJECT public: + /** * Constructor * @param theService service name: WMS,WFS,WCS diff --git a/src/core/qgspointlocator.h b/src/core/qgspointlocator.h index 272da0ce7ea5..8b3ba9761857 100644 --- a/src/core/qgspointlocator.h +++ b/src/core/qgspointlocator.h @@ -49,6 +49,7 @@ class CORE_EXPORT QgsPointLocator : public QObject { Q_OBJECT public: + /** Construct point locator for a layer. * @arg destinationCrs if a valid QgsCoordinateReferenceSystem is passed then the locator will * do the searches on data reprojected to the given CRS diff --git a/src/core/qgsproject.h b/src/core/qgsproject.h index 63d6e0cdbc5b..f0da974457f0 100644 --- a/src/core/qgsproject.h +++ b/src/core/qgsproject.h @@ -593,6 +593,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera void mapThemeCollectionChanged(); public slots: + /** * Flag the project as dirty (modified). If this flag is set, the user will * be asked to save changes to the project before closing the current project. @@ -608,6 +609,7 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera void cleanTransactionGroups( bool force = false ); private: + /** * Create a new QgsProject. * Private since it's (still) a singleton. diff --git a/src/core/qgsprojectbadlayerhandler.h b/src/core/qgsprojectbadlayerhandler.h index 82f9d856b95e..91026468e682 100644 --- a/src/core/qgsprojectbadlayerhandler.h +++ b/src/core/qgsprojectbadlayerhandler.h @@ -24,6 +24,7 @@ class CORE_EXPORT QgsProjectBadLayerHandler { public: + /** * This method will be called whenever the project tries to load layers which * cannot be accessed. It should inform the user about this and if possible offer diff --git a/src/core/qgsprojectproperty.h b/src/core/qgsprojectproperty.h index 49bf0bc519c1..ed92904846f0 100644 --- a/src/core/qgsprojectproperty.h +++ b/src/core/qgsprojectproperty.h @@ -185,6 +185,7 @@ class CORE_EXPORT QgsPropertyValue : public QgsProperty class CORE_EXPORT QgsPropertyKey : public QgsProperty { public: + /** * Create a new QgsPropertyKey with the specified identifier. */ diff --git a/src/core/qgsproviderregistry.h b/src/core/qgsproviderregistry.h index 8fa00d016f1c..c35967ea1785 100644 --- a/src/core/qgsproviderregistry.h +++ b/src/core/qgsproviderregistry.h @@ -113,6 +113,7 @@ class CORE_EXPORT QgsProviderRegistry It'd be nice to eventually be raster/vector neutral. */ virtual QString fileVectorFilters() const; + /** Return raster file filter string Returns a string suitable for a QFileDialog of raster file formats @@ -182,20 +183,24 @@ class CORE_EXPORT QgsProviderRegistry * one time. */ QString mVectorFileFilters; + /** File filter string for raster files */ QString mRasterFileFilters; + /** Available database drivers string for vector databases * * This is a string of form: * DriverNameToShow,DriverName;DriverNameToShow,DriverName;... */ QString mDatabaseDrivers; + /** Available directory drivers string for vector databases * This is a string of form: * DriverNameToShow,DriverName;DriverNameToShow,DriverName;... */ QString mDirectoryDrivers; + /** Available protocol drivers string for vector databases * * This is a string of form: diff --git a/src/core/qgsrectangle.h b/src/core/qgsrectangle.h index 34878189f3a9..00c51acfe3af 100644 --- a/src/core/qgsrectangle.h +++ b/src/core/qgsrectangle.h @@ -85,6 +85,7 @@ class CORE_EXPORT QgsRectangle void grow( double delta ); //! Updates the rectangle to include the specified point void include( const QgsPoint& p ); + /** Get rectangle enlarged by buffer. * @note added in 2.1 */ QgsRectangle buffer( double width ); @@ -119,14 +120,17 @@ class CORE_EXPORT QgsRectangle QString toString( int thePrecision ) const; //! returns rectangle as a polygon QString asPolygon() const; + /** Comparison operator * @return True if rectangles are equal */ bool operator==( const QgsRectangle &r1 ) const; + /** Comparison operator * @return False if rectangles are equal */ bool operator!=( const QgsRectangle &r1 ) const; + /** Assignment operator * @param r1 QgsRectangle to assign from */ diff --git a/src/core/qgsrelation.h b/src/core/qgsrelation.h index ca79a034b72c..93d0d0aa385c 100644 --- a/src/core/qgsrelation.h +++ b/src/core/qgsrelation.h @@ -34,6 +34,7 @@ class QgsAttributes; class CORE_EXPORT QgsRelation { public: + /** * \ingroup core * Defines a relation between matching fields of the two involved tables of a relation. @@ -290,6 +291,7 @@ class CORE_EXPORT QgsRelation bool hasEqualDefinition( const QgsRelation& other ) const; protected: + /** * Updates the validity status of this relation. * Will be called internally whenever a member is changed. @@ -309,6 +311,7 @@ class CORE_EXPORT QgsRelation QString mReferencedLayerId; //! The parent layer QgsVectorLayer* mReferencedLayer; + /** A list of fields which define the relation. * In most cases there will be only one value, but multiple values * are supported for composited foreign keys. diff --git a/src/core/qgsrenderchecker.h b/src/core/qgsrenderchecker.h index 1ba6fa289803..187e23a522de 100644 --- a/src/core/qgsrenderchecker.h +++ b/src/core/qgsrenderchecker.h @@ -125,6 +125,7 @@ class CORE_EXPORT QgsRenderChecker * @note: make sure to call setExpectedImage and setRenderedImage first. */ bool compareImages( const QString& theTestName, unsigned int theMismatchCount = 0, const QString& theRenderedImageFile = "" ); + /** Get a list of all the anomalies. An anomaly is a rendered difference * file where there is some red pixel content (indicating a render check * mismatch), but where the output was still acceptible. If the render diff --git a/src/core/qgsrulebasedlabeling.h b/src/core/qgsrulebasedlabeling.h index addc64495005..62b3a777dd4b 100644 --- a/src/core/qgsrulebasedlabeling.h +++ b/src/core/qgsrulebasedlabeling.h @@ -96,23 +96,27 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling * @return The maximum scale denominator */ int scaleMaxDenom() const { return mScaleMaxDenom; } + /** * A filter that will check if this rule applies * @return An expression */ QString filterExpression() const { return mFilterExp; } + /** * A human readable description for this rule * * @return Description */ QString description() const { return mDescription; } + /** * Returns if this rule is active * * @return True if the rule is active */ bool active() const { return mIsActive; } + /** * Check if this rule is an ELSE rule * @@ -133,6 +137,7 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling * @param scaleMinDenom The minimum scale denominator for this rule */ void setScaleMinDenom( int scaleMinDenom ) { mScaleMinDenom = scaleMinDenom; } + /** * Set the maximum denominator for which this rule shall apply. * E.g. 100'000 if it shall be evaluated between 1:1000 and 1:100'000 @@ -140,23 +145,27 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling * @param scaleMaxDenom maximum scale denominator for this rule */ void setScaleMaxDenom( int scaleMaxDenom ) { mScaleMaxDenom = scaleMaxDenom; } + /** * Set the expression used to check if a given feature shall be rendered with this rule * * @param filterExp An expression */ void setFilterExpression( const QString& filterExp ) { mFilterExp = filterExp; initFilter(); } + /** * Set a human readable description for this rule * * @param description Description */ void setDescription( const QString& description ) { mDescription = description; } + /** * Sets if this rule is active * @param state Determines if the rule should be activated or deactivated */ void setActive( bool state ) { mIsActive = state; } + /** * Sets if this rule is an ELSE rule * @@ -175,6 +184,7 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling * @return A list of rules */ const RuleList& children() const { return mChildren; } + /** * Return all children rules of this rule * @@ -195,6 +205,7 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling * @return Parent rule */ const Rule* parent() const { return mParent; } + /** * The parent rule * @@ -244,6 +255,7 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling RegisterResult registerFeature( QgsFeature& feature, QgsRenderContext& context, RuleToProviderMap& subProviders, QgsGeometry* obstacleGeometry = nullptr ); protected: + /** * Check if a given feature shall be labelled by this rule * @@ -252,6 +264,7 @@ class CORE_EXPORT QgsRuleBasedLabeling : public QgsAbstractVectorLayerLabeling * @return True if the feature shall be rendered */ bool isFilterOK( QgsFeature& f, QgsRenderContext& context ) const; + /** * Check if this rule applies for a given scale * @param scale The scale to check. If set to 0, it will always return true. diff --git a/src/core/qgsruntimeprofiler.h b/src/core/qgsruntimeprofiler.h index d32803935f1c..6a0dd496a4eb 100644 --- a/src/core/qgsruntimeprofiler.h +++ b/src/core/qgsruntimeprofiler.h @@ -11,6 +11,7 @@ class CORE_EXPORT QgsRuntimeProfiler { public: + /** * Constructor to create a new runtime profiler. */ diff --git a/src/core/qgsscaleutils.h b/src/core/qgsscaleutils.h index 39c9ab885256..68cfee2bd14a 100644 --- a/src/core/qgsscaleutils.h +++ b/src/core/qgsscaleutils.h @@ -24,6 +24,7 @@ class CORE_EXPORT QgsScaleUtils { public: + /** Save scales to the given file * @param fileName the name of the output file * @param scales the list of scales to save diff --git a/src/core/qgssnapper.h b/src/core/qgssnapper.h index a9927c1777cb..75afc8cb61ec 100644 --- a/src/core/qgssnapper.h +++ b/src/core/qgssnapper.h @@ -37,16 +37,19 @@ struct CORE_EXPORT QgsSnappingResult { //! The coordinates of the snapping result QgsPoint snappedVertex; + /** The vertex index of snappedVertex or -1 if no such vertex number (e.g. snap to segment)*/ int snappedVertexNr; //! The layer coordinates of the vertex before snappedVertex QgsPoint beforeVertex; + /** The index of the vertex before snappedVertex or -1 if no such vertex*/ int beforeVertexNr; //! The layer coordinates of the vertex after snappedVertex QgsPoint afterVertex; + /** The index of the vertex after snappedVertex or -1 if no such vertex*/ int afterVertexNr; @@ -77,6 +80,7 @@ class CORE_EXPORT QgsSnapper { //! Only one snapping result is returned SnapWithOneResult, + /** Several snapping results which have the same position are returned. This is useful for topological editing*/ SnapWithResultsForSamePosition, diff --git a/src/core/qgssnappingconfig.h b/src/core/qgssnappingconfig.h index 2d0bf12fe41e..6dda31a5086a 100644 --- a/src/core/qgssnappingconfig.h +++ b/src/core/qgssnappingconfig.h @@ -29,6 +29,7 @@ class QgsVectorLayer; class CORE_EXPORT QgsSnappingConfig { public: + /** * SnappingMode defines on which layer the snapping is performed */ @@ -56,6 +57,7 @@ class CORE_EXPORT QgsSnappingConfig class CORE_EXPORT IndividualLayerSettings { public: + /** * @brief IndividualLayerSettings * @param enabled @@ -175,6 +177,7 @@ class CORE_EXPORT QgsSnappingConfig bool operator!= ( const QgsSnappingConfig& other ) const; public: + /** * Reads the configuration from the specified QGIS project document. * diff --git a/src/core/qgssnappingutils.h b/src/core/qgssnappingutils.h index bc11c9248c93..8cb5050ce43c 100644 --- a/src/core/qgssnappingutils.h +++ b/src/core/qgssnappingutils.h @@ -102,6 +102,7 @@ class CORE_EXPORT QgsSnappingUtils : public QObject */ struct LayerConfig { + /** * Create a new configuration for a snapping layer. @@ -165,6 +166,7 @@ class CORE_EXPORT QgsSnappingUtils : public QObject void setConfig( const QgsSnappingConfig& snappingConfig ); signals: + /** * Emitted when the snapping settings object changes. */ diff --git a/src/core/qgssqlstatement.h b/src/core/qgssqlstatement.h index def8f3973f12..3b888795a627 100644 --- a/src/core/qgssqlstatement.h +++ b/src/core/qgssqlstatement.h @@ -33,6 +33,7 @@ class CORE_EXPORT QgsSQLStatement { Q_DECLARE_TR_FUNCTIONS( QgsSQLStatement ) public: + /** * Creates a new statement based on the provided string. */ @@ -42,6 +43,7 @@ class CORE_EXPORT QgsSQLStatement * Create a copy of this statement. */ QgsSQLStatement( const QgsSQLStatement& other ); + /** * Create a copy of this statement. */ diff --git a/src/core/qgstolerance.h b/src/core/qgstolerance.h index 5091f9c4ab39..214d8e643578 100644 --- a/src/core/qgstolerance.h +++ b/src/core/qgstolerance.h @@ -29,6 +29,7 @@ class CORE_EXPORT QgsTolerance { public: + /** Type of unit of tolerance value from settings. * For map (project) units, use ProjectUnits.*/ enum UnitType diff --git a/src/core/qgstransaction.h b/src/core/qgstransaction.h index 4d63908a606b..b2f2eedb836a 100644 --- a/src/core/qgstransaction.h +++ b/src/core/qgstransaction.h @@ -91,6 +91,7 @@ class CORE_EXPORT QgsTransaction : public QObject static bool supportsTransaction( const QgsVectorLayer* layer ); signals: + /** * Emitted after a rollback */ diff --git a/src/core/qgstransactiongroup.h b/src/core/qgstransactiongroup.h index ef5cc984b0b3..b92171c64427 100644 --- a/src/core/qgstransactiongroup.h +++ b/src/core/qgstransactiongroup.h @@ -70,6 +70,7 @@ class CORE_EXPORT QgsTransactionGroup : public QObject bool isEmpty() const; signals: + /** * Will be emitted whenever there is a commit error */ diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index 9126b424743d..7cd1810d2ef1 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -56,6 +56,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider public: // If you add to this, please also add to capabilitiesString() + /** * enumeration with capabilities that providers might implement */ @@ -91,6 +92,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider TransactionSupport = 1 << 16, //! Supports circular geometry types (circularstring, compoundcurve, curvepolygon) CircularGeometries = 1 << 17, + /** Supports joint updates for attributes and geometry * Providers supporting this should still define ChangeGeometries | ChangeAttributeValues */ @@ -464,6 +466,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider virtual QMap metadata() const { return QMap(); }; signals: + /** * Signals an error in this provider * @@ -472,6 +475,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider void raiseError( const QString& msg ) const; protected: + /** * Invalidates the min/max cache. This will force the provider to recalculate the * cache the next time it is requested. diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 3c5255de8fc1..3631f7e1351f 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -122,6 +122,7 @@ struct CORE_EXPORT QgsVectorJoinInfo /** Set subset of fields to be used from joined layer. Takes ownership of the passed pointer. Null pointer tells to use all fields. @note added in 2.6 */ void setJoinFieldNamesSubset( QStringList* fieldNamesSubset ) { joinFieldsSubset = QSharedPointer( fieldNamesSubset ); } + /** Get subset of fields to be used from joined layer. All fields will be used if null is returned. @note added in 2.6 */ QStringList* joinFieldNamesSubset() const { return joinFieldsSubset.data(); } @@ -1240,6 +1241,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte * A set of attributes that are not advertised in WMS requests with QGIS server. */ const QSet& excludeAttributesWms() const { return mExcludeAttributesWMS; } + /** * A set of attributes that are not advertised in WMS requests with QGIS server. */ @@ -1614,6 +1616,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte void setEditFormConfig( const QgsEditFormConfig& editFormConfig ); public slots: + /** * Select feature by its ID * @@ -1912,6 +1915,7 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte void setExtent( const QgsRectangle &rect ) override; private: // Private methods + /** * Returns true if the provider is in read-only mode */ diff --git a/src/core/qgsvectorlayercache.h b/src/core/qgsvectorlayercache.h index cd5e48ab1e18..d7c766c63c6d 100644 --- a/src/core/qgsvectorlayercache.h +++ b/src/core/qgsvectorlayercache.h @@ -40,6 +40,7 @@ class CORE_EXPORT QgsVectorLayerCache : public QObject Q_OBJECT private: + /** * This is a wrapper class around a cached @link QgsFeature @endlink, which * will inform the cache, when it has been deleted, so indexes can be @@ -48,6 +49,7 @@ class CORE_EXPORT QgsVectorLayerCache : public QObject class QgsCachedFeature { public: + /** * Will create a new cached feature. * @@ -219,6 +221,7 @@ class CORE_EXPORT QgsVectorLayerCache : public QObject QgsVectorLayer* layer(); protected: + /** * @brief * Gets called, whenever the full list of feature ids for a certain request is known. diff --git a/src/core/qgsvirtuallayerdefinition.h b/src/core/qgsvirtuallayerdefinition.h index af04f5f05df0..709a2494a95a 100644 --- a/src/core/qgsvirtuallayerdefinition.h +++ b/src/core/qgsvirtuallayerdefinition.h @@ -29,6 +29,7 @@ email : hugo dot mercier at oslandia dot com class CORE_EXPORT QgsVirtualLayerDefinition { public: + /** \ingroup core * A SourceLayer is either a reference to a live layer in the registry * or all the parameters needed to load it (provider key, source, etc.) diff --git a/src/core/raster/qgscolorrampshader.h b/src/core/raster/qgscolorrampshader.h index 33060066655b..39e42eef48ad 100644 --- a/src/core/raster/qgscolorrampshader.h +++ b/src/core/raster/qgscolorrampshader.h @@ -117,6 +117,7 @@ class CORE_EXPORT QgsColorRampShader : public QgsRasterShaderFunction bool clip() const { return mClip; } private: + /** This vector holds the information for classification based on values. * Each item holds a value, a label and a color. The member * mDiscreteClassification holds if one color is applied for all values diff --git a/src/core/raster/qgscontrastenhancement.cpp b/src/core/raster/qgscontrastenhancement.cpp index 387b0b01a7f6..15370866d7ae 100644 --- a/src/core/raster/qgscontrastenhancement.cpp +++ b/src/core/raster/qgscontrastenhancement.cpp @@ -122,6 +122,7 @@ double QgsContrastEnhancement::maximumValuePossible( Qgis::DataType theDataType return std::numeric_limits::max(); } + /** Simple function to compute the minimum possible value for a data type. */ @@ -166,6 +167,7 @@ double QgsContrastEnhancement::minimumValuePossible( Qgis::DataType theDataType * Non-Static methods * */ + /** Public function to generate the enhanced for enhanceContrasted value for a given input. diff --git a/src/core/raster/qgshillshaderenderer.h b/src/core/raster/qgshillshaderenderer.h index 1501ee893704..be4cee42ad19 100644 --- a/src/core/raster/qgshillshaderenderer.h +++ b/src/core/raster/qgshillshaderenderer.h @@ -34,6 +34,7 @@ class QgsRasterInterface; class CORE_EXPORT QgsHillshadeRenderer : public QgsRasterRenderer { public: + /** * @brief A renderer for generating live hillshade models. * @param input The input raster interface diff --git a/src/core/raster/qgsraster.h b/src/core/raster/qgsraster.h index 039d9758c085..5fcaec31df99 100644 --- a/src/core/raster/qgsraster.h +++ b/src/core/raster/qgsraster.h @@ -32,22 +32,39 @@ class CORE_EXPORT QgsRaster enum ColorInterpretation { UndefinedColorInterpretation = 0, + /** Greyscale */ GrayIndex = 1, + /** Paletted (see associated color table) */ PaletteIndex = 2, // indexed color table + /** Red band of RGBA image */ RedBand = 3, + /** Green band of RGBA image */ GreenBand = 4, + /** Blue band of RGBA image */ BlueBand = 5, + /** Alpha (0=transparent, 255=opaque) */ AlphaBand = 6, + /** Hue band of HLS image */ HueBand = 7, + /** Saturation band of HLS image */ SaturationBand = 8, + /** Lightness band of HLS image */ LightnessBand = 9, + /** Cyan band of CMYK image */ CyanBand = 10, + /** Magenta band of CMYK image */ MagentaBand = 11, + /** Yellow band of CMYK image */ YellowBand = 12, + /** Black band of CMLY image */ BlackBand = 13, + /** Y Luminance */ YCbCr_YBand = 14, + /** Cb Chroma */ YCbCr_CbBand = 15, + /** Cr Chroma */ YCbCr_CrBand = 16, + /** Continuous palette, QGIS addition, GRASS */ ContinuousPalette = 17 }; diff --git a/src/core/raster/qgsrasterblock.h b/src/core/raster/qgsrasterblock.h index e2862ffbdf37..3256ba37c034 100644 --- a/src/core/raster/qgsrasterblock.h +++ b/src/core/raster/qgsrasterblock.h @@ -73,6 +73,7 @@ class CORE_EXPORT QgsRasterBlock // TODO: consider if use isValid() at all, isEmpty() should be sufficient // and works also if block is valid but empty - difference between valid and empty? + /** \brief Returns true if the block is valid (correctly filled with data). * An empty block may still be valid (if zero size block was requested). * If the block is not valid, error may be retrieved by error() method. diff --git a/src/core/raster/qgsrasterchecker.h b/src/core/raster/qgsrasterchecker.h index 2582311d73e0..68b44846720f 100644 --- a/src/core/raster/qgsrasterchecker.h +++ b/src/core/raster/qgsrasterchecker.h @@ -35,6 +35,7 @@ class CORE_EXPORT QgsRasterChecker ~QgsRasterChecker() {} QString report() { return mReport; } + /** * Test using renderer to generate the image to be compared. * @param theVerifiedKey verified provider key diff --git a/src/core/raster/qgsrasterdataprovider.h b/src/core/raster/qgsrasterdataprovider.h index c7014fbb0f2d..6bccd2af8647 100644 --- a/src/core/raster/qgsrasterdataprovider.h +++ b/src/core/raster/qgsrasterdataprovider.h @@ -64,6 +64,7 @@ class CORE_EXPORT QgsImageFetcher : public QObject virtual void start() = 0; signals: + /** Emitted when the download completes * @param legend The downloaded legend image */ void finish( const QImage& legend ); @@ -191,6 +192,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast * @note added in 2.3 */ virtual double bandScale( int bandNo ) const { Q_UNUSED( bandNo ); return 1.0; } + /** Read band offset for raster value * @note added in 2.3 */ @@ -417,6 +419,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast static Capability identifyFormatToCapability( QgsRaster::IdentifyFormat format ); signals: + /** Emit a signal to notify of the progress event. * Emitted theProgress is in percents (0.0-100.0) */ void progress( int theType, double theProgress, const QString& theMessage ); @@ -428,6 +431,7 @@ class CORE_EXPORT QgsRasterDataProvider : public QgsDataProvider, public QgsRast void statusChanged( const QString& ) const; protected: + /** Read block of data * @note not available in python bindings */ diff --git a/src/core/raster/qgsrasterdrawer.h b/src/core/raster/qgsrasterdrawer.h index 4abcb8e7da72..7030f5998082 100644 --- a/src/core/raster/qgsrasterdrawer.h +++ b/src/core/raster/qgsrasterdrawer.h @@ -45,6 +45,7 @@ class CORE_EXPORT QgsRasterDrawer void draw( QPainter* p, QgsRasterViewPort* viewPort, const QgsMapToPixel* theQgsMapToPixel, QgsRasterBlockFeedback* feedback = nullptr ); protected: + /** Draws raster part * @param p the painter to draw to * @param viewPort view port to draw to diff --git a/src/core/raster/qgsrasterprojector.h b/src/core/raster/qgsrasterprojector.h index a4313294dee7..26aa5bd0c93c 100644 --- a/src/core/raster/qgsrasterprojector.h +++ b/src/core/raster/qgsrasterprojector.h @@ -44,6 +44,7 @@ class QgsCoordinateTransform; class CORE_EXPORT QgsRasterProjector : public QgsRasterInterface { public: + /** Precision defines if each pixel is reprojected or approximate reprojection based * on an approximation matrix of reprojected points is used. */ diff --git a/src/core/raster/qgsrasterpyramid.h b/src/core/raster/qgsrasterpyramid.h index eeacd6a41825..544ea2badc41 100644 --- a/src/core/raster/qgsrasterpyramid.h +++ b/src/core/raster/qgsrasterpyramid.h @@ -17,6 +17,7 @@ ***************************************************************************/ #ifndef QGSRASTERPYRAMID #define QGSRASTERPYRAMID + /** \ingroup core * This struct is used to store pyramid info for the raster layer. */ diff --git a/src/core/raster/qgsrasterrange.h b/src/core/raster/qgsrasterrange.h index 7edd93a649e9..a4a837b36a09 100644 --- a/src/core/raster/qgsrasterrange.h +++ b/src/core/raster/qgsrasterrange.h @@ -31,6 +31,7 @@ typedef QList QgsRasterRangeList; class CORE_EXPORT QgsRasterRange { public: + /** \brief Constructor. */ QgsRasterRange(); diff --git a/src/core/raster/qgsrasterrenderer.h b/src/core/raster/qgsrasterrenderer.h index c32be311932a..c781f276742c 100644 --- a/src/core/raster/qgsrasterrenderer.h +++ b/src/core/raster/qgsrasterrenderer.h @@ -110,6 +110,7 @@ class CORE_EXPORT QgsRasterRenderer : public QgsRasterInterface double mOpacity; //! Raster transparency per color or value. Overwrites global alpha value QgsRasterTransparency* mRasterTransparency; + /** Read alpha value from band. Is combined with value from raster transparency / global alpha value. Default: -1 (not set)*/ int mAlphaBand; diff --git a/src/core/raster/qgsrasterresampler.h b/src/core/raster/qgsrasterresampler.h index 52963ec2d3be..b1fa05b30adc 100644 --- a/src/core/raster/qgsrasterresampler.h +++ b/src/core/raster/qgsrasterresampler.h @@ -36,6 +36,7 @@ class QgsRasterResampler * Needs to be implemented by subclasses. */ virtual QString type() const = 0; + /** * Get a deep copy of this object. * Needs to be reimplemented by subclasses. diff --git a/src/core/raster/qgsrastershader.cpp b/src/core/raster/qgsrastershader.cpp index ecdbb2176d26..933fc16924c7 100644 --- a/src/core/raster/qgsrastershader.cpp +++ b/src/core/raster/qgsrastershader.cpp @@ -56,6 +56,7 @@ bool QgsRasterShader::shade( double theValue, int* theReturnRedValue, int* theRe return false; } + /** Generates and new RGBA value based on an original RGBA value diff --git a/src/core/raster/qgsrastershaderfunction.h b/src/core/raster/qgsrastershaderfunction.h index a42896d4361c..bbf34ea29b20 100644 --- a/src/core/raster/qgsrastershaderfunction.h +++ b/src/core/raster/qgsrastershaderfunction.h @@ -19,6 +19,7 @@ email : ersts@amnh.org #ifndef QGSRASTERSHADERFUNCTION_H #define QGSRASTERSHADERFUNCTION_H + /** \ingroup core * The raster shade function applies a shader to a pixel at render time - * typically used to render grayscale images as false color. diff --git a/src/core/raster/qgsrasterviewport.h b/src/core/raster/qgsrasterviewport.h index cb85baaa6178..86ce640cc0de 100644 --- a/src/core/raster/qgsrasterviewport.h +++ b/src/core/raster/qgsrasterviewport.h @@ -31,15 +31,18 @@ struct QgsRasterViewPort { + /** \brief Coordinate (in output device coordinate system) of top left corner * of the part of the raster that is to be rendered.*/ QgsPoint mTopLeftPoint; + /** \brief Coordinate (in output device coordinate system) of bottom right corner * of the part of the raster that is to be rendered.*/ QgsPoint mBottomRightPoint; //! \brief Width, number of columns to be rendered int mWidth; + /** \brief Distance in map units from bottom edge to top edge for the part of * the raster that is to be rendered.*/ //! \brief Height, number of rows to be rendered diff --git a/src/core/symbology-ng/qgs25drenderer.h b/src/core/symbology-ng/qgs25drenderer.h index 3708cd1da943..2df00776d5c3 100644 --- a/src/core/symbology-ng/qgs25drenderer.h +++ b/src/core/symbology-ng/qgs25drenderer.h @@ -89,6 +89,7 @@ class CORE_EXPORT Qgs25DRenderer : public QgsFeatureRenderer * Get the shadow's spread distance in map units */ double shadowSpread() const; + /** * Set the shadow's spread distance in map units */ @@ -105,6 +106,7 @@ class CORE_EXPORT Qgs25DRenderer : public QgsFeatureRenderer * Is the shadow enabled */ bool shadowEnabled() const; + /** * Enable or disable the shadow */ diff --git a/src/core/symbology-ng/qgsellipsesymbollayer.h b/src/core/symbology-ng/qgsellipsesymbollayer.h index 2f9a8e9288d3..d88055d7e12c 100644 --- a/src/core/symbology-ng/qgsellipsesymbollayer.h +++ b/src/core/symbology-ng/qgsellipsesymbollayer.h @@ -60,6 +60,7 @@ class CORE_EXPORT QgsEllipseSymbolLayer: public QgsMarkerSymbolLayer /** Get outline join style. * @note added in 2.16 */ Qt::PenJoinStyle penJoinStyle() const { return mPenJoinStyle; } + /** Set outline join style. * @note added in 2.16 */ void setPenJoinStyle( Qt::PenJoinStyle style ) { mPenJoinStyle = style; } diff --git a/src/core/symbology-ng/qgsfillsymbollayer.h b/src/core/symbology-ng/qgsfillsymbollayer.h index 1ab62a53512a..dfc3e0944693 100644 --- a/src/core/symbology-ng/qgsfillsymbollayer.h +++ b/src/core/symbology-ng/qgsfillsymbollayer.h @@ -369,6 +369,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see blurRadius */ void setBlurRadius( int blurRadius ) { mBlurRadius = blurRadius; } + /** Returns the blur radius, which controls the amount of blurring applied to the fill. * @returns Integer representing the radius for fill blur. Higher values indicate a stronger blur. A 0 value indicates that blurring is disabled. * @note added in 2.3 @@ -384,6 +385,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see setMaxDistance */ void setUseWholeShape( bool useWholeShape ) { mUseWholeShape = useWholeShape; } + /** Returns whether the shapeburst fill is set to cover the entire shape. * @returns True if shapeburst fill will cover the entire shape. If false, shapeburst is drawn to a distance of maxDistance from the polygon's boundary. * @note added in 2.3 @@ -400,6 +402,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see setDistanceUnit */ void setMaxDistance( double maxDistance ) { mMaxDistance = maxDistance; } + /** Returns the maximum distance from the shape's boundary which is shaded. This parameter is only effective if useWholeShape is false. * @returns the maximum distance from the polygon's boundary which is shaded. Distance units are indicated by distanceUnit. * @note added in 2.3 @@ -416,6 +419,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see distanceUnit */ void setDistanceUnit( QgsUnitTypes::RenderUnit unit ) { mDistanceUnit = unit; } + /** Returns the unit for the maximum distance to shade inside of the shape from the polygon's boundary. * @returns distance unit for the maximum distance * @note added in 2.3 @@ -437,6 +441,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see setColorRamp */ void setColorType( ShapeburstColorType colorType ) { mColorType = colorType; } + /** Returns the color mode used for the shapeburst fill. Shapeburst can either be drawn using a QgsColorRamp color ramp * or by simply specificing a start and end color. * @returns current color mode used for the shapeburst fill @@ -455,6 +460,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see colorRamp */ void setColorRamp( QgsColorRamp* ramp ); + /** Returns the color ramp used for the shapeburst fill. The color ramp is only used if the colorType is set to ShapeburstColorType::ColorRamp * @returns a QgsColorRamp color ramp * @note added in 2.3 @@ -470,6 +476,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see color2 */ void setColor2( const QColor& color2 ) { mColor2 = color2; } + /** Returns the color used for the endpoint of the shapeburst fill. This color is only used if the colorType is set to ShapeburstColorType::SimpleTwoColor * @returns a QColor indicating the color of the endpoint of the gradient * @note added in 2.3 @@ -485,6 +492,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see ignoreRings */ void setIgnoreRings( bool ignoreRings ) { mIgnoreRings = ignoreRings; } + /** Returns whether the shapeburst fill is set to ignore polygon interior rings. * @returns True if the shapeburst fill will ignore interior rings when calculating buffered shading. * @note added in 2.3 @@ -499,6 +507,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see setOffsetUnit */ void setOffset( QPointF offset ) { mOffset = offset; } + /** Returns the offset for the shapeburst fill. * @returns a QPointF indicating the horizontal/vertical offset amount * @note added in 2.3 @@ -514,6 +523,7 @@ class CORE_EXPORT QgsShapeburstFillSymbolLayer : public QgsFillSymbolLayer * @see offsetUnit */ void setOffsetUnit( QgsUnitTypes::RenderUnit unit ) { mOffsetUnit = unit; } + /** Returns the units used for the offset of the shapeburst fill. * @returns units used for the fill offset * @note added in 2.3 @@ -665,6 +675,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see imageFilePath */ void setImageFilePath( const QString& imagePath ); + /** The path to the raster image used for the fill. * @returns path to image file * @see setImageFilePath @@ -677,6 +688,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see coordinateMode */ void setCoordinateMode( const FillCoordinateMode mode ); + /** Coordinate mode for fill. Controls how the top left corner of the image * fill is positioned relative to the feature. * @returns coordinate mode @@ -689,6 +701,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see alpha */ void setAlpha( const double alpha ); + /** The opacity for the raster image used in the fill. * @returns opacity value between 0 (fully transparent) and 1 (fully opaque) * @see setAlpha @@ -702,6 +715,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see setOffsetMapUnitScale */ void setOffset( QPointF offset ) { mOffset = offset; } + /** Returns the offset for the fill. * @returns offset for fill * @see setOffset @@ -717,6 +731,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see setOffsetMapUnitScale */ void setOffsetUnit( const QgsUnitTypes::RenderUnit unit ) { mOffsetUnit = unit; } + /** Returns the units for the fill's offset. * @returns units for offset * @see setOffsetUnit @@ -732,6 +747,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see setOffsetUnit */ void setOffsetMapUnitScale( const QgsMapUnitScale& scale ) { mOffsetMapUnitScale = scale; } + /** Returns the map unit scale for the fill's offset. * @returns map unit scale for offset * @see setOffsetMapUnitScale @@ -748,6 +764,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see setWidthMapUnitScale */ void setWidth( const double width ) { mWidth = width; } + /** Returns the width used for scaling the image used in the fill. The image's height is * scaled to maintain the image's aspect ratio. * @returns width used for scaling the image @@ -764,6 +781,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see setWidthMapUnitScale */ void setWidthUnit( const QgsUnitTypes::RenderUnit unit ) { mWidthUnit = unit; } + /** Returns the units for the image's width. * @returns units for width * @see setWidthUnit @@ -779,6 +797,7 @@ class CORE_EXPORT QgsRasterFillSymbolLayer: public QgsImageFillSymbolLayer * @see setWidthUnit */ void setWidthMapUnitScale( const QgsMapUnitScale& scale ) { mWidthMapUnitScale = scale; } + /** Returns the map unit scale for the image's width. * @returns map unit scale for width * @see setWidthMapUnitScale @@ -1241,6 +1260,7 @@ class CORE_EXPORT QgsCentroidFillSymbolLayer : public QgsFillSymbolLayer /** Sets whether a point is drawn for all parts or only on the biggest part of multi-part features. * @note added in 2.16 */ void setPointOnAllParts( bool pointOnAllParts ) { mPointOnAllParts = pointOnAllParts; } + /** Returns whether a point is drawn for all parts or only on the biggest part of multi-part features. * @note added in 2.16 */ bool pointOnAllParts() const { return mPointOnAllParts; } diff --git a/src/core/symbology-ng/qgsheatmaprenderer.h b/src/core/symbology-ng/qgsheatmaprenderer.h index 0f80d7e442f9..373c20aa858d 100644 --- a/src/core/symbology-ng/qgsheatmaprenderer.h +++ b/src/core/symbology-ng/qgsheatmaprenderer.h @@ -62,6 +62,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer * @see setColorRamp */ QgsColorRamp* colorRamp() const { return mGradientRamp; } + /** Sets the color ramp to use for shading the heatmap. * @param ramp color ramp for heatmap. Ownership of ramp is transferred to the renderer. * @see colorRamp @@ -89,6 +90,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer * @see radiusMapUnitScale */ double radius() const { return mRadius; } + /** Sets the radius for the heatmap * @param radius heatmap radius * @see radius @@ -104,6 +106,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer * @see radiusMapUnitScale */ QgsUnitTypes::RenderUnit radiusUnit() const { return mRadiusUnit; } + /** Sets the units used for the heatmap's radius * @param unit units for heatmap radius * @see radiusUnit @@ -119,6 +122,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer * @see setRadiusMapUnitScale */ const QgsMapUnitScale& radiusMapUnitScale() const { return mRadiusMapUnitScale; } + /** Sets the map unit scale used for the heatmap's radius * @param scale map unit scale for heatmap's radius * @see setRadius @@ -133,6 +137,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer * @see setMaximumValue */ double maximumValue() const { return mExplicitMax; } + /** Sets the maximum value used for shading the heatmap. * @param value maximum value for heatmap shading. Set to 0 for automatic calculation of * maximum value. @@ -146,6 +151,7 @@ class CORE_EXPORT QgsHeatmapRenderer : public QgsFeatureRenderer * @see setRenderQuality */ double renderQuality() const { return mRenderQuality; } + /** Sets the render quality used for drawing the heatmap. * @param quality render quality. A value of 1 indicates maximum quality, and increasing the * value will result in faster drawing but lower quality rendering. diff --git a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h index 0c5b152274c0..f74a099f6591 100644 --- a/src/core/symbology-ng/qgsinvertedpolygonrenderer.h +++ b/src/core/symbology-ng/qgsinvertedpolygonrenderer.h @@ -74,27 +74,34 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer virtual QSet usedAttributes() const override; //! Proxy that will call this method on the embedded renderer. virtual Capabilities capabilities() override; + /** Proxy that will call this method on the embedded renderer. */ virtual QgsSymbolList symbols( QgsRenderContext& context ) override; + /** Proxy that will call this method on the embedded renderer. */ virtual QgsSymbol* symbolForFeature( QgsFeature& feature, QgsRenderContext& context ) override; + /** Proxy that will call this method on the embedded renderer. */ virtual QgsSymbol* originalSymbolForFeature( QgsFeature& feat, QgsRenderContext& context ) override; + /** Proxy that will call this method on the embedded renderer. */ virtual QgsSymbolList symbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; + /** Proxy that will call this method on the embedded renderer. */ virtual QgsSymbolList originalSymbolsForFeature( QgsFeature& feat, QgsRenderContext& context ) override; //! Proxy that will call this method on the embedded renderer. virtual QgsLegendSymbologyList legendSymbologyItems( QSize iconSize ) override; + /** Proxy that will call this method on the embedded renderer. * @note not available in python bindings */ virtual QgsLegendSymbolList legendSymbolItems( double scaleDenominator = -1, const QString& rule = "" ) override; + /** Proxy that will call this method on the embedded renderer. */ virtual bool willRenderFeature( QgsFeature& feat, QgsRenderContext& context ) override; @@ -115,6 +122,7 @@ class CORE_EXPORT QgsInvertedPolygonRenderer : public QgsFeatureRenderer //! @returns true if the geometries are to be preprocessed (merged with an union) before rendering. bool preprocessingEnabled() const { return mPreprocessingEnabled; } + /** * @param enabled enables or disables the preprocessing. * When enabled, geometries will be merged with an union before being rendered. diff --git a/src/core/symbology-ng/qgsmarkersymbollayer.h b/src/core/symbology-ng/qgsmarkersymbollayer.h index 8cd79819f6b7..238a0585d672 100644 --- a/src/core/symbology-ng/qgsmarkersymbollayer.h +++ b/src/core/symbology-ng/qgsmarkersymbollayer.h @@ -585,6 +585,7 @@ class CORE_EXPORT QgsFontMarkerSymbolLayer : public QgsMarkerSymbolLayer /** Get outline width. * @note added in 2.16 */ double outlineWidth() const { return mOutlineWidth; } + /** Set outline width. * @note added in 2.16 */ void setOutlineWidth( double width ) { mOutlineWidth = width; } @@ -592,6 +593,7 @@ class CORE_EXPORT QgsFontMarkerSymbolLayer : public QgsMarkerSymbolLayer /** Get outline width unit. * @note added in 2.16 */ QgsUnitTypes::RenderUnit outlineWidthUnit() const { return mOutlineWidthUnit; } + /** Set outline width unit. * @note added in 2.16 */ void setOutlineWidthUnit( QgsUnitTypes::RenderUnit unit ) { mOutlineWidthUnit = unit; } @@ -599,6 +601,7 @@ class CORE_EXPORT QgsFontMarkerSymbolLayer : public QgsMarkerSymbolLayer /** Get outline width map unit scale. * @note added in 2.16 */ const QgsMapUnitScale& outlineWidthMapUnitScale() const { return mOutlineWidthMapUnitScale; } + /** Set outline width map unit scale. * @note added in 2.16 */ void setOutlineWidthMapUnitScale( const QgsMapUnitScale& scale ) { mOutlineWidthMapUnitScale = scale; } @@ -606,6 +609,7 @@ class CORE_EXPORT QgsFontMarkerSymbolLayer : public QgsMarkerSymbolLayer /** Get outline join style. * @note added in 2.16 */ Qt::PenJoinStyle penJoinStyle() const { return mPenJoinStyle; } + /** Set outline join style. * @note added in 2.16 */ void setPenJoinStyle( Qt::PenJoinStyle style ) { mPenJoinStyle = style; } diff --git a/src/core/symbology-ng/qgspointdistancerenderer.h b/src/core/symbology-ng/qgspointdistancerenderer.h index 21f34ae67d3f..558c10cd8575 100644 --- a/src/core/symbology-ng/qgspointdistancerenderer.h +++ b/src/core/symbology-ng/qgspointdistancerenderer.h @@ -39,6 +39,7 @@ class CORE_EXPORT QgsPointDistanceRenderer: public QgsFeatureRenderer //! Contains properties for a feature within a clustered group. struct GroupedFeature { + /** Constructor for GroupedFeature. * @param feature feature * @param symbol base symbol for rendering feature diff --git a/src/core/symbology-ng/qgsrenderer.h b/src/core/symbology-ng/qgsrenderer.h index 881ff8324cc5..96cd0fc2639a 100644 --- a/src/core/symbology-ng/qgsrenderer.h +++ b/src/core/symbology-ng/qgsrenderer.h @@ -439,6 +439,7 @@ class CORE_EXPORT QgsFeatureRenderer * level DataDefined size */ static void convertSymbolSizeScale( QgsSymbol * symbol, QgsSymbol::ScaleMethod method, const QString & field ); + /** @note this function is used to convert old rotations expresssions to symbol * level DataDefined angle */ diff --git a/src/core/symbology-ng/qgsrendererregistry.h b/src/core/symbology-ng/qgsrendererregistry.h index 4ba5e1990676..dd3c4c7d9e11 100644 --- a/src/core/symbology-ng/qgsrendererregistry.h +++ b/src/core/symbology-ng/qgsrendererregistry.h @@ -69,6 +69,7 @@ class CORE_EXPORT QgsRendererAbstractMetadata /** Return new instance of the renderer given the DOM element. Returns NULL on error. * Pure virtual function: must be implemented in derived classes. */ virtual QgsFeatureRenderer* createRenderer( QDomElement& elem ) = 0; + /** Return new instance of settings widget for the renderer. Returns NULL on error. * * The \a oldRenderer argument may refer to previously used renderer (or it is null). diff --git a/src/core/symbology-ng/qgssvgcache.h b/src/core/symbology-ng/qgssvgcache.h index 2bfddeba4370..eb5bea0e082b 100644 --- a/src/core/symbology-ng/qgssvgcache.h +++ b/src/core/symbology-ng/qgssvgcache.h @@ -38,6 +38,7 @@ class CORE_EXPORT QgsSvgCacheEntry { public: QgsSvgCacheEntry(); + /** Constructor. * @param file Absolute path to SVG file (relative paths are not resolved). * @param size @@ -113,6 +114,7 @@ class CORE_EXPORT QgsSvgCache : public QObject */ const QImage& svgAsImage( const QString& file, double size, const QColor& fill, const QColor& outline, double outlineWidth, double widthScaleFactor, double rasterScaleFactor, bool& fitsInCache ); + /** Get SVG as QPicture&. * @param file Absolute or relative path to SVG file. * @param size size of cached image diff --git a/src/core/symbology-ng/qgssymbol.h b/src/core/symbology-ng/qgssymbol.h index b5c7e0f4204f..7f4413af4a20 100644 --- a/src/core/symbology-ng/qgssymbol.h +++ b/src/core/symbology-ng/qgssymbol.h @@ -441,6 +441,7 @@ class CORE_EXPORT QgsSymbolRenderContext * @note added in QGIS 2.16 */ int geometryPartCount() const { return mGeometryPartCount; } + /** Sets the part count of current geometry * @note added in QGIS 2.16 */ @@ -450,6 +451,7 @@ class CORE_EXPORT QgsSymbolRenderContext * @note added in QGIS 2.16 */ int geometryPartNum() const { return mGeometryPartNum; } + /** Sets the part number of current geometry * @note added in QGIS 2.16 */ @@ -467,6 +469,7 @@ class CORE_EXPORT QgsSymbolRenderContext * @return An expression scope for details about this symbol */ QgsExpressionContextScope* expressionContextScope(); + /** * Set an expression scope for this symbol. * @@ -651,6 +654,7 @@ class CORE_EXPORT QgsMarkerSymbol : public QgsSymbol class CORE_EXPORT QgsLineSymbol : public QgsSymbol { public: + /** Create a line symbol with one symbol layer: SimpleLine with specified properties. * This is a convenience method for easier creation of line symbols. */ @@ -693,6 +697,7 @@ class CORE_EXPORT QgsLineSymbol : public QgsSymbol class CORE_EXPORT QgsFillSymbol : public QgsSymbol { public: + /** Create a fill symbol with one symbol layer: SimpleFill with specified properties. * This is a convenience method for easier creation of fill symbols. */ diff --git a/src/core/symbology-ng/qgssymbollayer.h b/src/core/symbology-ng/qgssymbollayer.h index fd2693e1a886..96f87d6d0041 100644 --- a/src/core/symbology-ng/qgssymbollayer.h +++ b/src/core/symbology-ng/qgssymbollayer.h @@ -73,6 +73,7 @@ class CORE_EXPORT QgsSymbolLayer * The fill color. */ virtual QColor color() const { return mColor; } + /** * The fill color. */ diff --git a/src/core/symbology-ng/qgssymbollayerutils.h b/src/core/symbology-ng/qgssymbollayerutils.h index 743c02d4c0b8..b0eac5da4d84 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.h +++ b/src/core/symbology-ng/qgssymbollayerutils.h @@ -287,6 +287,7 @@ class CORE_EXPORT QgsSymbolLayerUtils Qt::PenCapStyle capStyle = Qt::FlatCap, double offset = 0.0, const QVector* dashPattern = nullptr ); + /** Create ogr feature style string for brush @param fillColr fill color*/ static QString ogrFeatureStyleBrush( const QColor& fillColr ); diff --git a/src/gui/attributetable/qgsattributetabledelegate.h b/src/gui/attributetable/qgsattributetabledelegate.h index 925e85b6ba7b..c29f049e0a10 100644 --- a/src/gui/attributetable/qgsattributetabledelegate.h +++ b/src/gui/attributetable/qgsattributetabledelegate.h @@ -37,6 +37,7 @@ class GUI_EXPORT QgsAttributeTableDelegate : public QItemDelegate static const QgsAttributeTableModel* masterModel( const QAbstractItemModel* model ); public: + /** * Constructor * @param parent parent object @@ -77,6 +78,7 @@ class GUI_EXPORT QgsAttributeTableDelegate : public QItemDelegate void setFeatureSelectionModel( QgsFeatureSelectionModel* featureSelectionModel ); signals: + /** * Is emitted when an action column item is painted. * The consumer of this signal can initialize the index widget. diff --git a/src/gui/attributetable/qgsattributetablefiltermodel.h b/src/gui/attributetable/qgsattributetablefiltermodel.h index 37ff2886afb7..0930ffc8bb74 100644 --- a/src/gui/attributetable/qgsattributetablefiltermodel.h +++ b/src/gui/attributetable/qgsattributetablefiltermodel.h @@ -35,6 +35,7 @@ class GUI_EXPORT QgsAttributeTableFilterModel: public QSortFilterProxyModel, pub Q_OBJECT public: + /** * The filter mode defines how the rows should be filtered. */ @@ -217,6 +218,7 @@ class GUI_EXPORT QgsAttributeTableFilterModel: public QSortFilterProxyModel, pub void setAttributeTableConfig( const QgsAttributeTableConfig& config ); signals: + /** * Is emitted whenever the sort column is changed * @param column The sort column @@ -225,6 +227,7 @@ class GUI_EXPORT QgsAttributeTableFilterModel: public QSortFilterProxyModel, pub void sortColumnChanged( int column, Qt::SortOrder order ); protected: + /** * Returns true if the source row will be accepted * @@ -246,6 +249,7 @@ class GUI_EXPORT QgsAttributeTableFilterModel: public QSortFilterProxyModel, pub bool lessThan( const QModelIndex &left, const QModelIndex &right ) const override; public slots: + /** * Is called upon every change of the visible extents on the map canvas. * When a change is signalled, the filter is updated and invalidated if needed. diff --git a/src/gui/attributetable/qgsattributetablemodel.h b/src/gui/attributetable/qgsattributetablemodel.h index ed2b16f89e73..f0903bc911b2 100644 --- a/src/gui/attributetable/qgsattributetablemodel.h +++ b/src/gui/attributetable/qgsattributetablemodel.h @@ -57,6 +57,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel }; public: + /** * Constructor * @param layerCache A layer cache to use as backend @@ -249,6 +250,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel void setExtraColumns( int extraColumns ); public slots: + /** * Loads the layer into the model * Preferably to be called, before using this model as source for any other proxy model @@ -262,6 +264,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel void fieldConditionalStyleChanged( const QString& fieldName ); signals: + /** * Model has been changed */ @@ -272,6 +275,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel void finished(); private slots: + /** * Launched whenever the number of fields has changed */ @@ -290,6 +294,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel virtual void attributeDeleted( int idx ); protected slots: + /** * Launched when attribute value has been changed * @param fid feature id @@ -297,11 +302,13 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel * @param value new value */ virtual void attributeValueChanged( QgsFeatureId fid, int idx, const QVariant &value ); + /** * Launched when eatures have been deleted * @param fids feature ids */ virtual void featuresDeleted( const QgsFeatureIds& fids ); + /** * Launched when a feature has been added * @param fid feature id @@ -336,6 +343,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel virtual void loadAttributes(); private: + /** * Load feature fid into local cache (mFeat) * diff --git a/src/gui/attributetable/qgsattributetableview.h b/src/gui/attributetable/qgsattributetableview.h index af586fc9eec4..ffa0fc7118ff 100644 --- a/src/gui/attributetable/qgsattributetableview.h +++ b/src/gui/attributetable/qgsattributetableview.h @@ -76,6 +76,7 @@ class GUI_EXPORT QgsAttributeTableView : public QTableView void setAttributeTableConfig( const QgsAttributeTableConfig& config ); protected: + /** * Called for mouse press events on a table cell. * Disables selection change for these events. @@ -124,6 +125,7 @@ class GUI_EXPORT QgsAttributeTableView : public QTableView void closeEvent( QCloseEvent *event ) override; signals: + /** * @brief * Is emitted, in order to provide a hook to add aditional menu entries to the context menu. diff --git a/src/gui/attributetable/qgsdualview.h b/src/gui/attributetable/qgsdualview.h index d4090a9b7dc1..c5a2ad6c6c58 100644 --- a/src/gui/attributetable/qgsdualview.h +++ b/src/gui/attributetable/qgsdualview.h @@ -51,10 +51,12 @@ class GUI_EXPORT QgsDualView : public QStackedWidget, private Ui::QgsDualViewBas */ enum ViewMode { + /** * Shows the features and attributes in a table layout */ AttributeTable = 0, + /** * Show a list of the features, where one can be chosen * and the according attribute dialog will be presented @@ -190,12 +192,14 @@ class GUI_EXPORT QgsDualView : public QStackedWidget, private Ui::QgsDualViewBas QString sortExpression() const; protected: + /** * Initializes widgets which depend on the attributes of this layer */ void columnBoxInit(); public slots: + /** * @brief Set the current edit selection in the {@link AttributeEditor} mode. * @@ -231,6 +235,7 @@ class GUI_EXPORT QgsDualView : public QStackedWidget, private Ui::QgsDualViewBas void copyCellContent() const; signals: + /** * Is emitted, whenever the display expression is successfully changed * @param expression The expression that was applied diff --git a/src/gui/attributetable/qgsfeaturelistview.h b/src/gui/attributetable/qgsfeaturelistview.h index d344e90f5926..21f288e1280e 100644 --- a/src/gui/attributetable/qgsfeaturelistview.h +++ b/src/gui/attributetable/qgsfeaturelistview.h @@ -44,6 +44,7 @@ class GUI_EXPORT QgsFeatureListView : public QListView Q_OBJECT public: + /** * Creates a feature list view * @@ -68,6 +69,7 @@ class GUI_EXPORT QgsFeatureListView : public QListView * @param featureListModel The model to use */ virtual void setModel( QgsFeatureListModel* featureListModel ); + /** * Get the featureListModel used by this view * @@ -128,6 +130,7 @@ class GUI_EXPORT QgsFeatureListView : public QListView virtual void contextMenuEvent( QContextMenuEvent *event ) override; signals: + /** * Is emitted, whenever the current edit selection has been changed. * @@ -145,6 +148,7 @@ class GUI_EXPORT QgsFeatureListView : public QListView void aboutToChangeEditSelection( bool& ok ); public slots: + /** * Set the feature(s) to be edited * diff --git a/src/gui/attributetable/qgsfeatureselectionmodel.h b/src/gui/attributetable/qgsfeatureselectionmodel.h index 8c53474b6416..f530f3a61dd7 100644 --- a/src/gui/attributetable/qgsfeatureselectionmodel.h +++ b/src/gui/attributetable/qgsfeatureselectionmodel.h @@ -52,6 +52,7 @@ class GUI_EXPORT QgsFeatureSelectionModel : public QItemSelectionModel */ virtual bool isSelected( QgsFeatureId fid ); + /** * Returns the selection status of a given QModelIndex. * @@ -62,6 +63,7 @@ class GUI_EXPORT QgsFeatureSelectionModel : public QItemSelectionModel virtual bool isSelected( const QModelIndex& index ); signals: + /** * Request a repaint of a list of model indexes. * Views using this model should connect to and properly process this signal. @@ -77,6 +79,7 @@ class GUI_EXPORT QgsFeatureSelectionModel : public QItemSelectionModel void requestRepaint(); public slots: + /** * Overwritten to do NOTHING (we handle selection ourselves) * diff --git a/src/gui/attributetable/qgsifeatureselectionmanager.h b/src/gui/attributetable/qgsifeatureselectionmanager.h index fdbd19863774..028df60b5846 100644 --- a/src/gui/attributetable/qgsifeatureselectionmanager.h +++ b/src/gui/attributetable/qgsifeatureselectionmanager.h @@ -73,6 +73,7 @@ class GUI_EXPORT QgsIFeatureSelectionManager : public QObject virtual const QgsFeatureIds &selectedFeaturesIds() const = 0; signals: + /** * This signal is emitted when selection was changed * diff --git a/src/gui/attributetable/qgsorganizetablecolumnsdialog.h b/src/gui/attributetable/qgsorganizetablecolumnsdialog.h index 7944c39b570d..5d2f7f2372e9 100644 --- a/src/gui/attributetable/qgsorganizetablecolumnsdialog.h +++ b/src/gui/attributetable/qgsorganizetablecolumnsdialog.h @@ -35,6 +35,7 @@ class GUI_EXPORT QgsOrganizeTableColumnsDialog : public QDialog, private Ui::Qgs Q_OBJECT public: + /** * Constructor * @param vl The concerned vector layer @@ -54,6 +55,7 @@ class GUI_EXPORT QgsOrganizeTableColumnsDialog : public QDialog, private Ui::Qgs QgsAttributeTableConfig config() const; public slots: + /** * showAll checks all the fields to show them all in the attribute table */ diff --git a/src/gui/attributetable/qgsvectorlayerselectionmanager.h b/src/gui/attributetable/qgsvectorlayerselectionmanager.h index bcb8f8eafa1c..acccd5d2bce6 100644 --- a/src/gui/attributetable/qgsvectorlayerselectionmanager.h +++ b/src/gui/attributetable/qgsvectorlayerselectionmanager.h @@ -30,6 +30,7 @@ class GUI_EXPORT QgsVectorLayerSelectionManager : public QgsIFeatureSelectionMan public: explicit QgsVectorLayerSelectionManager( QgsVectorLayer* layer, QObject *parent = nullptr ); + /** * The number of features that are selected in this layer * diff --git a/src/gui/auth/qgsauthauthoritieseditor.h b/src/gui/auth/qgsauthauthoritieseditor.h index 135ffad8edc4..e0c4204c2020 100644 --- a/src/gui/auth/qgsauthauthoritieseditor.h +++ b/src/gui/auth/qgsauthauthoritieseditor.h @@ -36,6 +36,7 @@ class GUI_EXPORT QgsAuthAuthoritiesEditor : public QWidget, private Ui::QgsAuthA Q_OBJECT public: + /** * Widget for viewing and editing certificate authorities directly in database * @param parent Parent widget diff --git a/src/gui/auth/qgsauthcertificateinfo.h b/src/gui/auth/qgsauthcertificateinfo.h index 9b41540c435a..70d5c47349d6 100644 --- a/src/gui/auth/qgsauthcertificateinfo.h +++ b/src/gui/auth/qgsauthcertificateinfo.h @@ -142,6 +142,7 @@ class GUI_EXPORT QgsAuthCertInfoDialog : public QDialog Q_OBJECT public: + /** * Construct a dialog displaying detailed info on a certificate and its hierarchical trust chain * @param cert Certificate object diff --git a/src/gui/auth/qgsauthcertificatemanager.h b/src/gui/auth/qgsauthcertificatemanager.h index c38e7a66d718..c77be78fe3f5 100644 --- a/src/gui/auth/qgsauthcertificatemanager.h +++ b/src/gui/auth/qgsauthcertificatemanager.h @@ -31,6 +31,7 @@ class GUI_EXPORT QgsAuthCertEditors : public QWidget, private Ui::QgsAuthCertMan Q_OBJECT public: + /** * Construct a widget to contain various certificate editors * @param parent Parent widget @@ -51,6 +52,7 @@ class GUI_EXPORT QgsAuthCertManager : public QDialog Q_OBJECT public: + /** * Construct a dialog wrapper for widget to manage available certificate editors * @param parent Parent widget diff --git a/src/gui/auth/qgsauthcerttrustpolicycombobox.h b/src/gui/auth/qgsauthcerttrustpolicycombobox.h index 620bda319191..c219d749e011 100644 --- a/src/gui/auth/qgsauthcerttrustpolicycombobox.h +++ b/src/gui/auth/qgsauthcerttrustpolicycombobox.h @@ -28,6 +28,7 @@ class GUI_EXPORT QgsAuthCertTrustPolicyComboBox : public QComboBox Q_OBJECT public: + /** * Construct a combo box for defining certificate trust policy * @param parent Parent widget diff --git a/src/gui/auth/qgsauthconfigeditor.h b/src/gui/auth/qgsauthconfigeditor.h index 370c36b36ae8..edfc12238ea4 100644 --- a/src/gui/auth/qgsauthconfigeditor.h +++ b/src/gui/auth/qgsauthconfigeditor.h @@ -33,6 +33,7 @@ class GUI_EXPORT QgsAuthConfigEditor : public QWidget, private Ui::QgsAuthConfig Q_OBJECT public: + /** * Widget for editing authentication configurations directly in database * @param parent Parent widget diff --git a/src/gui/auth/qgsauthconfigidedit.h b/src/gui/auth/qgsauthconfigidedit.h index 32241d378018..03e84a4f9c48 100644 --- a/src/gui/auth/qgsauthconfigidedit.h +++ b/src/gui/auth/qgsauthconfigidedit.h @@ -31,6 +31,7 @@ class GUI_EXPORT QgsAuthConfigIdEdit : public QWidget, private Ui::QgsAuthConfig Q_OBJECT public: + /** * Widget to unlock and edit an authentication configuration ID * @param parent Parent widget diff --git a/src/gui/auth/qgsauthconfigselect.h b/src/gui/auth/qgsauthconfigselect.h index 736266b59afa..4547b30f66d3 100644 --- a/src/gui/auth/qgsauthconfigselect.h +++ b/src/gui/auth/qgsauthconfigselect.h @@ -31,6 +31,7 @@ class GUI_EXPORT QgsAuthConfigSelect : public QWidget, private Ui::QgsAuthConfig Q_OBJECT public: + /** * Create a dialog for setting an associated authentication config, either * from existing configs, or creating/removing them from auth database @@ -106,6 +107,7 @@ class GUI_EXPORT QgsAuthConfigUriEdit : public QDialog, private Ui::QgsAuthConfi Q_OBJECT public: + /** * Construct wrapper dialog for select widget to edit an authcfg in a data source URI * @param parent Parent widget diff --git a/src/gui/auth/qgsautheditorwidgets.h b/src/gui/auth/qgsautheditorwidgets.h index 7b993a9b90a5..4d574309e583 100644 --- a/src/gui/auth/qgsautheditorwidgets.h +++ b/src/gui/auth/qgsautheditorwidgets.h @@ -29,6 +29,7 @@ class GUI_EXPORT QgsAuthMethodPlugins : public QDialog, private Ui::QgsAuthMetho Q_OBJECT public: + /** * Construct a dialog for viewing available authentication method plugins * @param parent Parent widget @@ -56,6 +57,7 @@ class GUI_EXPORT QgsAuthEditorWidgets : public QWidget, private Ui::QgsAuthEdito Q_OBJECT public: + /** * Construct a widget to contain various authentication editors * @param parent Parent widget diff --git a/src/gui/auth/qgsauthidentitieseditor.h b/src/gui/auth/qgsauthidentitieseditor.h index e710df9b16d3..135875deefb1 100644 --- a/src/gui/auth/qgsauthidentitieseditor.h +++ b/src/gui/auth/qgsauthidentitieseditor.h @@ -33,6 +33,7 @@ class GUI_EXPORT QgsAuthIdentitiesEditor : public QWidget, private Ui::QgsAuthId Q_OBJECT public: + /** * Widget for editing authentication configurations directly in database * @param parent Parent widget diff --git a/src/gui/auth/qgsauthmethodedit.h b/src/gui/auth/qgsauthmethodedit.h index 22a0523ec610..f595f78006c6 100644 --- a/src/gui/auth/qgsauthmethodedit.h +++ b/src/gui/auth/qgsauthmethodedit.h @@ -40,6 +40,7 @@ class GUI_EXPORT QgsAuthMethodEdit : public QWidget void validityChanged( bool valid ); public slots: + /** * Load an existing config map into subclassed widget * @param configmap @@ -53,6 +54,7 @@ class GUI_EXPORT QgsAuthMethodEdit : public QWidget virtual void clearConfig() = 0; protected: + /** * Construct widget to edit an authentication method configuration * @note Non-public since this is an abstract base class diff --git a/src/gui/auth/qgsauthserverseditor.h b/src/gui/auth/qgsauthserverseditor.h index 1c410644f5eb..1703fef24e39 100644 --- a/src/gui/auth/qgsauthserverseditor.h +++ b/src/gui/auth/qgsauthserverseditor.h @@ -32,6 +32,7 @@ class GUI_EXPORT QgsAuthServersEditor : public QWidget, private Ui::QgsAuthServe Q_OBJECT public: + /** * Widget for editing authentication configurations directly in database * @param parent Parent Widget diff --git a/src/gui/auth/qgsauthsslconfigwidget.h b/src/gui/auth/qgsauthsslconfigwidget.h index 2f5a70016118..dfea1c8c60a8 100644 --- a/src/gui/auth/qgsauthsslconfigwidget.h +++ b/src/gui/auth/qgsauthsslconfigwidget.h @@ -38,6 +38,7 @@ class GUI_EXPORT QgsAuthSslConfigWidget : public QWidget, private Ui::QgsAuthSsl Q_OBJECT public: + /** * Construct a widget for editing an SSL server certificate configuration * @param parent Parent widget @@ -188,6 +189,7 @@ class GUI_EXPORT QgsAuthSslConfigDialog : public QDialog Q_OBJECT public: + /** * Construct wrapper dialog for the SSL config widget * @param parent Parent widget diff --git a/src/gui/auth/qgsauthsslerrorsdialog.h b/src/gui/auth/qgsauthsslerrorsdialog.h index efb91055c2e4..d36e95416167 100644 --- a/src/gui/auth/qgsauthsslerrorsdialog.h +++ b/src/gui/auth/qgsauthsslerrorsdialog.h @@ -32,6 +32,7 @@ class GUI_EXPORT QgsAuthSslErrorsDialog : public QDialog, private Ui::QgsAuthSsl { Q_OBJECT public: + /** * Construct a dialog to handle SSL errors and saving SSL server certificate exceptions * @param reply Network reply that hand error(s) diff --git a/src/gui/auth/qgsauthsslimportdialog.h b/src/gui/auth/qgsauthsslimportdialog.h index 0d27f3f41705..263ab72f38fd 100644 --- a/src/gui/auth/qgsauthsslimportdialog.h +++ b/src/gui/auth/qgsauthsslimportdialog.h @@ -80,6 +80,7 @@ class GUI_EXPORT QgsAuthSslImportDialog : public QDialog, private Ui::QgsAuthSsl { Q_OBJECT public: + /** * Construct dialog for importing certificates * @param parent diff --git a/src/gui/auth/qgsauthtrustedcasdialog.h b/src/gui/auth/qgsauthtrustedcasdialog.h index a83e79fcc4e6..081c90bb4c61 100644 --- a/src/gui/auth/qgsauthtrustedcasdialog.h +++ b/src/gui/auth/qgsauthtrustedcasdialog.h @@ -34,6 +34,7 @@ class GUI_EXPORT QgsAuthTrustedCAsDialog : public QDialog, private Ui::QgsAuthTr Q_OBJECT public: + /** * Construct a dialog that will list the trusted Certificate Authorities * @param parent Parent widget diff --git a/src/gui/editorwidgets/core/qgseditorconfigwidget.h b/src/gui/editorwidgets/core/qgseditorconfigwidget.h index 0383e1a514d0..2aa92c638e4d 100644 --- a/src/gui/editorwidgets/core/qgseditorconfigwidget.h +++ b/src/gui/editorwidgets/core/qgseditorconfigwidget.h @@ -34,6 +34,7 @@ class GUI_EXPORT QgsEditorConfigWidget : public QWidget { Q_OBJECT public: + /** * Create a new configuration widget * diff --git a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.h b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.h index c0ec973cec98..8d6dfb0e9a9c 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.h @@ -29,6 +29,7 @@ class QgsEditorWidgetSetup; class GUI_EXPORT QgsEditorWidgetAutoConfPlugin { public: + /** * Typical scores are: * * 0: no matching type found. @@ -47,6 +48,7 @@ class GUI_EXPORT QgsEditorWidgetAutoConfPlugin ///@cond PRIVATE + /** \ingroup gui * Class that allows to register plugins to pick automatically a widget type for editing fields. * This class has only one instance, owned by the QgsEditorWidgetRegistry singleton @@ -58,6 +60,7 @@ class GUI_EXPORT QgsEditorWidgetAutoConfPlugin class GUI_EXPORT QgsEditorWidgetAutoConf { public: + /** * Register the default plugins. */ diff --git a/src/gui/editorwidgets/core/qgseditorwidgetfactory.h b/src/gui/editorwidgets/core/qgseditorwidgetfactory.h index 54583540138a..ef986c59c080 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetfactory.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetfactory.h @@ -40,6 +40,7 @@ class QgsSearchWidgetWrapper; class GUI_EXPORT QgsEditorWidgetFactory { public: + /** * Constructor * diff --git a/src/gui/editorwidgets/core/qgseditorwidgetregistry.h b/src/gui/editorwidgets/core/qgseditorwidgetregistry.h index 8dd4faa05c1d..2fb04ddacdce 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetregistry.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetregistry.h @@ -41,6 +41,7 @@ class GUI_EXPORT QgsEditorWidgetRegistry : public QObject Q_OBJECT public: + /** * This class is a singleton and has therefore to be accessed with this method instead * of a constructor. @@ -181,6 +182,7 @@ class GUI_EXPORT QgsEditorWidgetRegistry : public QObject QgsEditorWidgetRegistry(); private slots: + /** * Read all the editor widget information from a map layer XML node * @param mapLayer diff --git a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h index 49602e733934..d9655eb8ae35 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgseditorwidgetwrapper.h @@ -163,6 +163,7 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper QString constraintFailureReason() const; signals: + /** * Emit this signal, whenever the value changed. * @@ -181,6 +182,7 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper void constraintStatusChanged( const QString& constraint, const QString &desc, const QString& err, ConstraintResult status ); public slots: + /** * Will be called when the feature changes * @@ -199,6 +201,7 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper virtual void setValue( const QVariant& value ) = 0; protected slots: + /** * If you emit to this slot in your implementation, an appropriate change notification * will be broadcasted. Helper for string type widgets. @@ -248,6 +251,7 @@ class GUI_EXPORT QgsEditorWidgetWrapper : public QgsWidgetWrapper void valueChanged(); protected: + /** * This should update the widget with a visual cue if a constraint status * changed. diff --git a/src/gui/editorwidgets/core/qgswidgetwrapper.h b/src/gui/editorwidgets/core/qgswidgetwrapper.h index 3cff9fa9a742..98f1c24c4b37 100644 --- a/src/gui/editorwidgets/core/qgswidgetwrapper.h +++ b/src/gui/editorwidgets/core/qgswidgetwrapper.h @@ -40,6 +40,7 @@ class GUI_EXPORT QgsWidgetWrapper : public QObject { Q_OBJECT public: + /** * Create a new widget wrapper * @@ -133,6 +134,7 @@ class GUI_EXPORT QgsWidgetWrapper : public QObject virtual bool valid() const = 0; protected: + /** * This method should create a new widget with the provided parent. This will only be called * if the form did not already provide a widget, so it is not guaranteed to be called! @@ -154,6 +156,7 @@ class GUI_EXPORT QgsWidgetWrapper : public QObject virtual void initWidget( QWidget* editor ); public slots: + /** * Is called, when the value of the widget needs to be changed. Update the widget representation * to reflect the new value. diff --git a/src/gui/editorwidgets/qgskeyvaluewidgetfactory.h b/src/gui/editorwidgets/qgskeyvaluewidgetfactory.h index b3f8ea20e712..a993066e7f07 100644 --- a/src/gui/editorwidgets/qgskeyvaluewidgetfactory.h +++ b/src/gui/editorwidgets/qgskeyvaluewidgetfactory.h @@ -26,6 +26,7 @@ class GUI_EXPORT QgsKeyValueWidgetFactory : public QgsEditorWidgetFactory { public: + /** * Constructor. */ diff --git a/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h b/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h index 58b28bed5120..c2892f75d55e 100644 --- a/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h +++ b/src/gui/editorwidgets/qgskeyvaluewidgetwrapper.h @@ -29,6 +29,7 @@ class GUI_EXPORT QgsKeyValueWidgetWrapper : public QgsEditorWidgetWrapper { Q_OBJECT public: + /** * Constructor. */ diff --git a/src/gui/editorwidgets/qgslistwidgetfactory.h b/src/gui/editorwidgets/qgslistwidgetfactory.h index 30ed0469d909..9e50c995e7c1 100644 --- a/src/gui/editorwidgets/qgslistwidgetfactory.h +++ b/src/gui/editorwidgets/qgslistwidgetfactory.h @@ -26,6 +26,7 @@ class GUI_EXPORT QgsListWidgetFactory : public QgsEditorWidgetFactory { public: + /** * Constructor. */ diff --git a/src/gui/editorwidgets/qgslistwidgetwrapper.h b/src/gui/editorwidgets/qgslistwidgetwrapper.h index 47a745135d13..132b1191ee28 100644 --- a/src/gui/editorwidgets/qgslistwidgetwrapper.h +++ b/src/gui/editorwidgets/qgslistwidgetwrapper.h @@ -29,6 +29,7 @@ class GUI_EXPORT QgsListWidgetWrapper : public QgsEditorWidgetWrapper { Q_OBJECT public: + /** * Constructor. */ diff --git a/src/gui/editorwidgets/qgsrelationwidgetwrapper.h b/src/gui/editorwidgets/qgsrelationwidgetwrapper.h index b3c2313c6cc3..6ecbcdbf76a2 100644 --- a/src/gui/editorwidgets/qgsrelationwidgetwrapper.h +++ b/src/gui/editorwidgets/qgsrelationwidgetwrapper.h @@ -54,6 +54,7 @@ class GUI_EXPORT QgsRelationWidgetWrapper : public QgsWidgetWrapper * @note Added in QGIS 2.18 */ bool showLinkButton() const; + /** * Determines if the "link feature" button should be shown * @@ -67,6 +68,7 @@ class GUI_EXPORT QgsRelationWidgetWrapper : public QgsWidgetWrapper * @note Added in QGIS 2.18 */ bool showUnlinkButton() const; + /** * Determines if the "unlink feature" button should be shown * diff --git a/src/gui/layertree/qgslayertreeembeddedconfigwidget.h b/src/gui/layertree/qgslayertreeembeddedconfigwidget.h index b9683841cf23..7b3aae233e10 100644 --- a/src/gui/layertree/qgslayertreeembeddedconfigwidget.h +++ b/src/gui/layertree/qgslayertreeembeddedconfigwidget.h @@ -29,6 +29,7 @@ class GUI_EXPORT QgsLayerTreeEmbeddedConfigWidget : public QWidget, protected Ui { Q_OBJECT public: + /** * A widget to configure layer tree embedded widgets for a particular map layer. * @param parent The parent of the widget. diff --git a/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.h b/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.h index d225035ebfc2..198a7e976649 100644 --- a/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.h +++ b/src/gui/layertree/qgslayertreeembeddedwidgetsimpl.h @@ -25,6 +25,7 @@ class QTimer; class QgsMapLayer; ///@cond PRIVATE + /** * @brief Implementation of simple transparency widget to be used in layer tree view * diff --git a/src/gui/qgisinterface.h b/src/gui/qgisinterface.h index 8f3a003ade89..32a8d4009e93 100644 --- a/src/gui/qgisinterface.h +++ b/src/gui/qgisinterface.h @@ -356,6 +356,7 @@ class GUI_EXPORT QgisInterface : public QObject virtual void unregisterCustomDropHandler( QgsCustomDropHandler* handler ) = 0; // @todo is this deprecated in favour of QgsContextHelp? + /** Open a url in the users browser. By default the QGIS doc directory is used * as the base for the URL. To open a URL that is not relative to the installed * QGIS documentation, set useQgisDocDirectory to false. @@ -583,6 +584,7 @@ class GUI_EXPORT QgisInterface : public QObject virtual int messageTimeout() = 0; signals: + /** Emitted whenever current (selected) layer changes. * The pointer to layer can be null if no layer is selected */ @@ -607,6 +609,7 @@ class GUI_EXPORT QgisInterface : public QObject * This signal is emitted when the initialization is complete */ void initializationCompleted(); + /** Emitted when a project file is successfully read * @note * This is useful for plug-ins that store properties with project files. A @@ -614,6 +617,7 @@ class GUI_EXPORT QgisInterface : public QObject * knows to then check the project properties for any relevant state. */ void projectRead(); + /** Emitted when starting an entirely new project * @note * This is similar to projectRead(); plug-ins might want to be notified diff --git a/src/gui/qgsadvanceddigitizingdockwidget.h b/src/gui/qgsadvanceddigitizingdockwidget.h index 96fe80270960..3c024a5684f5 100644 --- a/src/gui/qgsadvanceddigitizingdockwidget.h +++ b/src/gui/qgsadvanceddigitizingdockwidget.h @@ -88,6 +88,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private class GUI_EXPORT CadConstraint { public: + /** * The lock mode */ @@ -120,6 +121,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private * @return Lock mode */ LockMode lockMode() const { return mLockMode; } + /** * Is any kind of lock mode enabled */ @@ -136,6 +138,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private * Is the constraint in relative mode */ bool relative() const { return mRelative; } + /** * The value of the constraint */ @@ -215,6 +218,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasPressEvent( QgsMapMouseEvent* e ); + /** * Will react on a canvas release event * @@ -223,6 +227,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasReleaseEvent( QgsMapMouseEvent* e, AdvancedDigitizingMode mode ); + /** * Will react on a canvas move event * @@ -230,6 +235,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private * @return If the event is hidden (construction mode hides events from the maptool) */ bool canvasMoveEvent( QgsMapMouseEvent* e ); + /** * Filter key events to e.g. toggle construction mode or adapt constraints * @@ -328,6 +334,7 @@ class GUI_EXPORT QgsAdvancedDigitizingDockWidget : public QgsDockWidget, private void disable(); signals: + /** * Push a warning * diff --git a/src/gui/qgsattributeeditorcontext.h b/src/gui/qgsattributeeditorcontext.h index 6bf71315a957..778312f1e7eb 100644 --- a/src/gui/qgsattributeeditorcontext.h +++ b/src/gui/qgsattributeeditorcontext.h @@ -33,6 +33,7 @@ class GUI_EXPORT QgsAttributeEditorContext { public: + /** * Determines in which direction a relation was resolved. */ diff --git a/src/gui/qgsattributeform.h b/src/gui/qgsattributeform.h index ecf8026546d4..6e5c5fe96869 100644 --- a/src/gui/qgsattributeform.h +++ b/src/gui/qgsattributeform.h @@ -150,6 +150,7 @@ class GUI_EXPORT QgsAttributeForm : public QWidget void setMessageBar( QgsMessageBar* messageBar ); signals: + /** * Notifies about changes of attributes * @@ -191,6 +192,7 @@ class GUI_EXPORT QgsAttributeForm : public QWidget void closed(); public slots: + /** * Call this to change the content of a given attribute. Will update the editor(s) related to this field. * diff --git a/src/gui/qgsattributetypeloaddialog.h b/src/gui/qgsattributetypeloaddialog.h index cae4ac4ef608..b6cde689902d 100644 --- a/src/gui/qgsattributetypeloaddialog.h +++ b/src/gui/qgsattributetypeloaddialog.h @@ -64,6 +64,7 @@ class GUI_EXPORT QgsAttributeTypeLoadDialog: public QDialog, private Ui::QgsAttr bool insertNull(); private slots: + /** * Slot which reacts to change of selected layer to fill other two comboboxes with correct data * @param layerIndex index of layer which was selected diff --git a/src/gui/qgsbusyindicatordialog.h b/src/gui/qgsbusyindicatordialog.h index bf17c945116c..826125f79384 100644 --- a/src/gui/qgsbusyindicatordialog.h +++ b/src/gui/qgsbusyindicatordialog.h @@ -32,6 +32,7 @@ class GUI_EXPORT QgsBusyIndicatorDialog : public QDialog { Q_OBJECT public: + /** Constructor * Modal busy indicator dialog with no buttons. * @param message Text to show above busy progress indicator. diff --git a/src/gui/qgscodeeditor.h b/src/gui/qgscodeeditor.h index 16ddbf346e25..8149e8d44141 100644 --- a/src/gui/qgscodeeditor.h +++ b/src/gui/qgscodeeditor.h @@ -34,6 +34,7 @@ class GUI_EXPORT QgsCodeEditor : public QsciScintilla Q_OBJECT public: + /** * Construct a new code editor. * diff --git a/src/gui/qgscodeeditorpython.h b/src/gui/qgscodeeditorpython.h index 248322bc16e2..b59acdd5d8d9 100644 --- a/src/gui/qgscodeeditorpython.h +++ b/src/gui/qgscodeeditorpython.h @@ -30,6 +30,7 @@ class GUI_EXPORT QgsCodeEditorPython : public QgsCodeEditor Q_OBJECT public: + /** * Construct a new Python editor. * diff --git a/src/gui/qgscollapsiblegroupbox.h b/src/gui/qgscollapsiblegroupbox.h index 2ca22f9ce007..f315f57fa9b2 100644 --- a/src/gui/qgscollapsiblegroupbox.h +++ b/src/gui/qgscollapsiblegroupbox.h @@ -103,6 +103,7 @@ class GUI_EXPORT QgsCollapsibleGroupBoxBasic : public QGroupBox * Returns the current collapsed state of this group box */ bool isCollapsed() const { return mCollapsed; } + /** * Collapse or uncollapse this groupbox * @@ -202,6 +203,7 @@ class GUI_EXPORT QgsCollapsibleGroupBox : public QgsCollapsibleGroupBoxBasic //! set this to false to not save/restore collapsed state void setSaveCollapsedState( bool save ) { mSaveCollapsedState = save; } + /** Set this to true to save/restore checked state * @note only turn on mSaveCheckedState for groupboxes NOT used * in multiple places or used as options for different parent objects */ @@ -215,6 +217,7 @@ class GUI_EXPORT QgsCollapsibleGroupBox : public QgsCollapsibleGroupBoxBasic QString settingGroup() const { return mSettingGroup; } protected slots: + /** * Will load the collapsed and checked state * @@ -223,6 +226,7 @@ class GUI_EXPORT QgsCollapsibleGroupBox : public QgsCollapsibleGroupBoxBasic * * The settingGroup */ void loadState(); + /** * Will save the collapsed and checked state * diff --git a/src/gui/qgscomposeritemcombobox.h b/src/gui/qgscomposeritemcombobox.h index e2d6d08a0b78..e6a5c2b9db3d 100644 --- a/src/gui/qgscomposeritemcombobox.h +++ b/src/gui/qgscomposeritemcombobox.h @@ -33,6 +33,7 @@ class GUI_EXPORT QgsComposerItemComboBox : public QComboBox Q_OBJECT public: + /** * QgsComposerItemComboBox creates a combo box to display a list of items in a * composition. The items can optionally be filtered by type. @@ -80,6 +81,7 @@ class GUI_EXPORT QgsComposerItemComboBox : public QComboBox QgsComposerItem* currentItem() const; public slots: + /** Sets the currently selected item in the combo box. * @param item selected item */ diff --git a/src/gui/qgscomposerview.h b/src/gui/qgscomposerview.h index c2f3c7625937..fb302e5ef9ef 100644 --- a/src/gui/qgscomposerview.h +++ b/src/gui/qgscomposerview.h @@ -160,6 +160,7 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView * @see setPreviewMode */ void setPreviewModeEnabled( bool enabled ); + /** Sets the preview mode which should be used to modify the view's appearance. Preview modes are only used * if setPreviewMode is set to true. * @param mode PreviewMode to be used to draw the view @@ -276,6 +277,7 @@ class GUI_EXPORT QgsComposerView: public QGraphicsView void selectedItemChanged( QgsComposerItem* selected ); //! Is emitted when a composer item has been removed from the scene void itemRemoved( QgsComposerItem* ); + /** Current action (e.g. adding composer map) has been finished. The purpose of this signal is that QgsComposer may set the selection tool again*/ void actionFinished(); diff --git a/src/gui/qgsdatadefinedbutton.h b/src/gui/qgsdatadefinedbutton.h index 62a09f850800..06203510695c 100644 --- a/src/gui/qgsdatadefinedbutton.h +++ b/src/gui/qgsdatadefinedbutton.h @@ -295,6 +295,7 @@ class GUI_EXPORT QgsDataDefinedButton: public QToolButton static QString customDashDesc(); public slots: + /** * Set whether the current data definition or expression is to be used */ @@ -311,6 +312,7 @@ class GUI_EXPORT QgsDataDefinedButton: public QToolButton void checkCheckedWidgets( bool check ); signals: + /** * Emitted when data definition or expression is changed * @param definition The current definition or expression (empty string if inactive) diff --git a/src/gui/qgsdetaileditemdata.h b/src/gui/qgsdetaileditemdata.h index 0c68d2c2ca17..6ecffc55f523 100644 --- a/src/gui/qgsdetaileditemdata.h +++ b/src/gui/qgsdetaileditemdata.h @@ -37,6 +37,7 @@ class GUI_EXPORT QgsDetailedItemData void setCheckable( const bool theFlag ); void setChecked( const bool theFlag ); void setEnabled( bool theFlag ); + /** This is a hint to the delegate to render using * a widget rather than manually painting every * part of the list item. diff --git a/src/gui/qgsexpressionbuilderdialog.h b/src/gui/qgsexpressionbuilderdialog.h index faf5717fe667..9d48b3a557e3 100644 --- a/src/gui/qgsexpressionbuilderdialog.h +++ b/src/gui/qgsexpressionbuilderdialog.h @@ -57,6 +57,7 @@ class GUI_EXPORT QgsExpressionBuilderDialog : public QDialog, private Ui::QgsExp void setGeomCalculator( const QgsDistanceArea & da ); protected: + /** * Is called when the dialog get accepted or rejected * Used to save geometry diff --git a/src/gui/qgsexpressionbuilderwidget.h b/src/gui/qgsexpressionbuilderwidget.h index 01a615ea6a8d..10099062882b 100644 --- a/src/gui/qgsexpressionbuilderwidget.h +++ b/src/gui/qgsexpressionbuilderwidget.h @@ -72,6 +72,7 @@ class QgsExpressionItem : public QStandardItem * @return The help text. */ QString getHelpText() const { return mHelpText; } + /** Set the help text for the current item * * @note The help text can be set as a html string. @@ -124,6 +125,7 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp { Q_OBJECT public: + /** * Create a new expression builder widget with an optional parent. */ @@ -262,6 +264,7 @@ class GUI_EXPORT QgsExpressionBuilderWidget : public QWidget, private Ui::QgsExp void on_txtPython_textChanged(); signals: + /** Emitted when the user changes the expression in the widget. * Users of this widget should connect to this signal to decide if to let the user * continue. diff --git a/src/gui/qgsexpressionselectiondialog.h b/src/gui/qgsexpressionselectiondialog.h index a628e974f51b..e4eb59d3d18f 100644 --- a/src/gui/qgsexpressionselectiondialog.h +++ b/src/gui/qgsexpressionselectiondialog.h @@ -30,6 +30,7 @@ class GUI_EXPORT QgsExpressionSelectionDialog : public QDialog, private Ui::QgsE Q_OBJECT public: + /** * Creates a new selection dialog. * @param layer The layer on which the selection is to be performed. @@ -69,6 +70,7 @@ class GUI_EXPORT QgsExpressionSelectionDialog : public QDialog, private Ui::QgsE void on_mPbnClose_clicked(); protected: + /** * Implementation for closeEvent * Saves the window geometry diff --git a/src/gui/qgsexternalresourcewidget.h b/src/gui/qgsexternalresourcewidget.h index af2d5ad43fcf..090a655d0bae 100644 --- a/src/gui/qgsexternalresourcewidget.h +++ b/src/gui/qgsexternalresourcewidget.h @@ -80,6 +80,7 @@ class GUI_EXPORT QgsExternalResourceWidget : public QWidget //! returns the height of the document viewer int documentViewerHeight() const; + /** * @brief setDocumentViewerWidth set the height of the document viewer. * @param height the height. Use 0 for automatic best display. @@ -87,6 +88,7 @@ class GUI_EXPORT QgsExternalResourceWidget : public QWidget void setDocumentViewerHeight( int height ); //! returns the width of the document viewer int documentViewerWidth() const ; + /** * @brief setDocumentViewerWidth set the width of the document viewer. * @param width the width. Use 0 for automatic best display. diff --git a/src/gui/qgsfieldcombobox.h b/src/gui/qgsfieldcombobox.h index c83858edd5d6..c88bed068b24 100644 --- a/src/gui/qgsfieldcombobox.h +++ b/src/gui/qgsfieldcombobox.h @@ -37,6 +37,7 @@ class GUI_EXPORT QgsFieldComboBox : public QComboBox Q_PROPERTY( QgsFieldProxyModel::Filters filters READ filters WRITE setFilters ) public: + /** * @brief QgsFieldComboBox creates a combo box to display the fields of a layer. * The layer can be either manually given or dynamically set by connecting the signal QgsMapLayerComboBox::layerChanged to the slot setLayer. diff --git a/src/gui/qgsfieldexpressionwidget.h b/src/gui/qgsfieldexpressionwidget.h index ae3047f6c45f..e7afdb43e401 100644 --- a/src/gui/qgsfieldexpressionwidget.h +++ b/src/gui/qgsfieldexpressionwidget.h @@ -47,6 +47,7 @@ class GUI_EXPORT QgsFieldExpressionWidget : public QWidget Q_PROPERTY( QgsFieldProxyModel::Filters filters READ filters WRITE setFilters ) public: + /** * @brief QgsFieldExpressionWidget creates a widget with a combo box to display the fields and expression and a button to open the expression dialog */ diff --git a/src/gui/qgsfilewidget.h b/src/gui/qgsfilewidget.h index 04b372f03a8f..8c4694ff7d47 100644 --- a/src/gui/qgsfilewidget.h +++ b/src/gui/qgsfilewidget.h @@ -41,6 +41,7 @@ class GUI_EXPORT QgsFileWidget : public QWidget Q_PROPERTY( RelativeStorage relativeStorage READ relativeStorage WRITE setRelativeStorage ) public: + /** * @brief The StorageMode enum determines if the file picker should pick files or directories */ @@ -78,6 +79,7 @@ class GUI_EXPORT QgsFileWidget : public QWidget //! returns the open file dialog title QString dialogTitle() const; + /** * @brief setDialogTitle defines the open file dialog title * @note if not defined, the title is "Select a file" or "Select a directory" depending on the configuration. @@ -86,6 +88,7 @@ class GUI_EXPORT QgsFileWidget : public QWidget //! returns the filters used for QDialog::getOpenFileName QString filter() const; + /** * @brief setFilter sets the filter used by the model to filters. The filter is used to specify the kind of files that should be shown. * @param filter Only files that match the given filter are shown, it may be an empty string. If you want multiple filters, separate them with ';;', diff --git a/src/gui/qgsgenericprojectionselector.h b/src/gui/qgsgenericprojectionselector.h index 35ce08b561c4..a145b5c84bff 100644 --- a/src/gui/qgsgenericprojectionselector.h +++ b/src/gui/qgsgenericprojectionselector.h @@ -48,6 +48,7 @@ class GUI_EXPORT QgsGenericProjectionSelector : public QDialog, private Ui::QgsG { Q_OBJECT public: + /** * Constructor */ @@ -58,6 +59,7 @@ class GUI_EXPORT QgsGenericProjectionSelector : public QDialog, private Ui::QgsG ~QgsGenericProjectionSelector(); public slots: + /** If no parameter is passed, the message will be a generic * 'define the CRS for this layer'. */ diff --git a/src/gui/qgsgeometryrubberband.h b/src/gui/qgsgeometryrubberband.h index 67d2f3e7db5a..ee69f0906c86 100644 --- a/src/gui/qgsgeometryrubberband.h +++ b/src/gui/qgsgeometryrubberband.h @@ -34,26 +34,32 @@ class GUI_EXPORT QgsGeometryRubberBand: public QgsMapCanvasItem public: enum IconType { + /** * No icon is used */ ICON_NONE, + /** * A cross is used to highlight points (+) */ ICON_CROSS, + /** * A cross is used to highlight points (x) */ ICON_X, + /** * A box is used to highlight points (□) */ ICON_BOX, + /** * A circle is used to highlight points (○) */ ICON_CIRCLE, + /** * A full box is used to highlight points (■) */ diff --git a/src/gui/qgskeyvaluewidget.h b/src/gui/qgskeyvaluewidget.h index 3a77149f4973..f3f661877a46 100644 --- a/src/gui/qgskeyvaluewidget.h +++ b/src/gui/qgskeyvaluewidget.h @@ -21,6 +21,7 @@ #include ///@cond PRIVATE + /** @ingroup gui * Table model to edit a QVariantMap. * @note added in QGIS 3.0 @@ -61,6 +62,7 @@ class GUI_EXPORT QgsKeyValueWidget: public QgsTableWidgetBase Q_OBJECT Q_PROPERTY( QVariantMap map READ map WRITE setMap ) public: + /** * Constructor. */ diff --git a/src/gui/qgslegendfilterbutton.h b/src/gui/qgslegendfilterbutton.h index 8379a1e30427..fe2fc20c5f68 100644 --- a/src/gui/qgslegendfilterbutton.h +++ b/src/gui/qgslegendfilterbutton.h @@ -31,6 +31,7 @@ class GUI_EXPORT QgsLegendFilterButton: public QToolButton Q_OBJECT public: + /** * Construct a new filter legend button * @@ -55,6 +56,7 @@ class GUI_EXPORT QgsLegendFilterButton: public QToolButton * May be null */ QgsVectorLayer* vectorLayer() const; + /** * Sets the associated vectorLayer * May be null @@ -62,6 +64,7 @@ class GUI_EXPORT QgsLegendFilterButton: public QToolButton void setVectorLayer( QgsVectorLayer* layer ); signals: + /** * Emitted when the expression text changes */ diff --git a/src/gui/qgslistwidget.h b/src/gui/qgslistwidget.h index 10b7e25b871f..b29e1f0f11dc 100644 --- a/src/gui/qgslistwidget.h +++ b/src/gui/qgslistwidget.h @@ -21,6 +21,7 @@ #include ///@cond PRIVATE + /** @ingroup gui * Table model to edit a QVariantList. * @note added in QGIS 3.0 @@ -61,6 +62,7 @@ class GUI_EXPORT QgsListWidget: public QgsTableWidgetBase Q_OBJECT Q_PROPERTY( QVariantList list READ list WRITE setList ) public: + /** * Constructor. */ diff --git a/src/gui/qgsmapcanvas.h b/src/gui/qgsmapcanvas.h index 6914e0fb7fa0..f02e96d4be32 100644 --- a/src/gui/qgsmapcanvas.h +++ b/src/gui/qgsmapcanvas.h @@ -388,6 +388,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView * @note added in 2.8 */ QgsSnappingUtils* snappingUtils() const; + /** Assign an instance of snapping utils to the map canvas. * The instance is not owned by the canvas, so it is possible to use one instance in multiple canvases. * @@ -425,6 +426,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView /** Sets the segmentation tolerance applied when rendering curved geometries @param tolerance the segmentation tolerance*/ void setSegmentationTolerance( double tolerance ); + /** Sets segmentation tolerance type (maximum angle or maximum difference between curve and approximation) @param type the segmentation tolerance typename*/ void setSegmentationToleranceType( QgsAbstractGeometry::SegmentationToleranceType type ); @@ -496,6 +498,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView void refreshMap(); signals: + /** Emits current mouse position \note changed in 1.3 */ void xyCoordinates( const QgsPoint &p ); @@ -637,6 +640,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView QScopedPointer mCanvasProperties; #if 0 + /** Debugging member * invoked when a connect() is made to this object */ @@ -647,6 +651,7 @@ class GUI_EXPORT QgsMapCanvas : public QGraphicsView private: /// this class is non-copyable + /** @note diff --git a/src/gui/qgsmapcanvassnapper.h b/src/gui/qgsmapcanvassnapper.h index 455f006e99ee..f96f1fff5167 100644 --- a/src/gui/qgsmapcanvassnapper.h +++ b/src/gui/qgsmapcanvassnapper.h @@ -33,6 +33,7 @@ class QPoint; class GUI_EXPORT QgsMapCanvasSnapper { public: + /** Constructor @param canvas the map canvas to snap to*/ QgsMapCanvasSnapper( QgsMapCanvas* canvas ); diff --git a/src/gui/qgsmaplayercombobox.h b/src/gui/qgsmaplayercombobox.h index e005e50deec7..40ed469a3b41 100644 --- a/src/gui/qgsmaplayercombobox.h +++ b/src/gui/qgsmaplayercombobox.h @@ -34,6 +34,7 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox Q_PROPERTY( QgsMapLayerProxyModel::Filters filters READ filters WRITE setFilters ) public: + /** * @brief QgsMapLayerComboBox creates a combo box to dislpay the list of layers (currently in the registry). * The layers can be filtered and/or ordered. diff --git a/src/gui/qgsmaplayerconfigwidget.h b/src/gui/qgsmaplayerconfigwidget.h index 70ebab349204..3bba2fc58ba8 100644 --- a/src/gui/qgsmaplayerconfigwidget.h +++ b/src/gui/qgsmaplayerconfigwidget.h @@ -44,6 +44,7 @@ class GUI_EXPORT QgsMapLayerConfigWidget : public QgsPanelWidget QgsMapLayerConfigWidget( QgsMapLayer* layer, QgsMapCanvas *canvas, QWidget *parent = 0 ); public slots: + /** * @brief Called when changes to the layer need to be made. * Will be called when live update is enabled. diff --git a/src/gui/qgsmaptip.h b/src/gui/qgsmaptip.h index 23028bd4b40a..b90a58bcaa8b 100644 --- a/src/gui/qgsmaptip.h +++ b/src/gui/qgsmaptip.h @@ -50,12 +50,15 @@ class GUI_EXPORT QgsMapTip : public QWidget { Q_OBJECT public: + /** Default constructor */ QgsMapTip(); + /** Destructor */ virtual ~QgsMapTip(); + /** Show a maptip at a given point on the map canvas * @param thepLayer a qgis vector map layer pointer that will * be used to provide the attribute data for the map tip. @@ -69,6 +72,7 @@ class GUI_EXPORT QgsMapTip : public QWidget QgsPoint & theMapPosition, QPoint & thePixelPosition, QgsMapCanvas *mpMapCanvas ); + /** Clear the current maptip if it exists * @param mpMapCanvas the canvas from which the tip should be cleared. */ diff --git a/src/gui/qgsmaptooladvanceddigitizing.h b/src/gui/qgsmaptooladvanceddigitizing.h index d5796758d5a8..0fa51c7d9524 100644 --- a/src/gui/qgsmaptooladvanceddigitizing.h +++ b/src/gui/qgsmaptooladvanceddigitizing.h @@ -89,6 +89,7 @@ class GUI_EXPORT QgsMapToolAdvancedDigitizing : public QgsMapToolEdit protected: + /** * Override this method when subclassing this class. * This will receive adapted events from the cad system whenever a @@ -130,6 +131,7 @@ class GUI_EXPORT QgsMapToolAdvancedDigitizing : public QgsMapToolEdit bool mSnapOnDoubleClick; //!< Snap on double click private slots: + /** * Is to be called by the cad system whenever a point changes outside of a * mouse event. E.g. when additional constraints are toggled. diff --git a/src/gui/qgsmaptoolidentify.h b/src/gui/qgsmaptoolidentify.h index 50ee925dbc83..b93c201e1598 100644 --- a/src/gui/qgsmaptoolidentify.h +++ b/src/gui/qgsmaptoolidentify.h @@ -138,6 +138,7 @@ class GUI_EXPORT QgsMapToolIdentify : public QgsMapTool void changedRasterResults( QList& ); protected: + /** Performs the identification. To avoid beeing forced to specify IdentifyMode with a list of layers this has been made private and two publics methods are offered diff --git a/src/gui/qgsmaptoolidentifyfeature.h b/src/gui/qgsmaptoolidentifyfeature.h index 567b2c0914f1..9709e5de397b 100644 --- a/src/gui/qgsmaptoolidentifyfeature.h +++ b/src/gui/qgsmaptoolidentifyfeature.h @@ -28,6 +28,7 @@ class GUI_EXPORT QgsMapToolIdentifyFeature : public QgsMapToolIdentify Q_OBJECT public: + /** * @brief QgsMapToolIdentifyFeature is a map tool to identify a feature on a chosen layer * @param canvas the map canvas diff --git a/src/gui/qgsmessagebar.h b/src/gui/qgsmessagebar.h index 29635f7dea65..96ef80b3a507 100644 --- a/src/gui/qgsmessagebar.h +++ b/src/gui/qgsmessagebar.h @@ -101,6 +101,7 @@ class GUI_EXPORT QgsMessageBar: public QFrame void widgetRemoved( QgsMessageBarItem *item ); public slots: + /** Remove the currently displayed widget from the bar and * display the next in the stack if any or hide the bar. * @return true if the widget was removed, false otherwise diff --git a/src/gui/qgsnewnamedialog.h b/src/gui/qgsnewnamedialog.h index 44a4d9df3842..9197a95552c0 100644 --- a/src/gui/qgsnewnamedialog.h +++ b/src/gui/qgsnewnamedialog.h @@ -31,6 +31,7 @@ class GUI_EXPORT QgsNewNameDialog : public QgsDialog { Q_OBJECT public: + /** New dialog constructor. * @param source original data source name, e.g. original layer name of the layer to be copied * @param initial initial name diff --git a/src/gui/qgsoptionsdialogbase.h b/src/gui/qgsoptionsdialogbase.h index 5091e7eb426d..e7b6d040594f 100644 --- a/src/gui/qgsoptionsdialogbase.h +++ b/src/gui/qgsoptionsdialogbase.h @@ -50,6 +50,7 @@ class GUI_EXPORT QgsOptionsDialogBase : public QDialog Q_OBJECT public: + /** Constructor * @param settingsKey QSettings subgroup key for saving/restore ui states, e.g. "ProjectProperties". * @param parent parent object (owner) diff --git a/src/gui/qgsorderbydialog.h b/src/gui/qgsorderbydialog.h index 50c416e31158..a45921474b3d 100644 --- a/src/gui/qgsorderbydialog.h +++ b/src/gui/qgsorderbydialog.h @@ -35,6 +35,7 @@ class GUI_EXPORT QgsOrderByDialog : public QDialog, private Ui::OrderByDialogBas Q_OBJECT public: + /** * Create a new order by dialog. This helps building order by structures. * @@ -61,6 +62,7 @@ class GUI_EXPORT QgsOrderByDialog : public QDialog, private Ui::OrderByDialogBas void onExpressionChanged( const QString& expression ); private: + /** * Initialize a row with the given information */ diff --git a/src/gui/qgsowssourceselect.h b/src/gui/qgsowssourceselect.h index aefec6659bba..2c5c3f8b7f84 100644 --- a/src/gui/qgsowssourceselect.h +++ b/src/gui/qgsowssourceselect.h @@ -111,6 +111,7 @@ class GUI_EXPORT QgsOWSSourceSelect : public QDialog, public Ui::QgsOWSSourceSel void connectionsChanged(); protected: + /** * List of image formats (encodings) supported by provider * @return list of format/label pairs diff --git a/src/gui/qgspanelwidget.h b/src/gui/qgspanelwidget.h index c586ac12e69b..a039baa244f3 100644 --- a/src/gui/qgspanelwidget.h +++ b/src/gui/qgspanelwidget.h @@ -26,6 +26,7 @@ class GUI_EXPORT QgsPanelWidget : public QWidget { Q_OBJECT public: + /** * @brief Base class for any widget that can be shown as a inline panel * @param parent Parent widget. @@ -131,6 +132,7 @@ class GUI_EXPORT QgsPanelWidget : public QWidget void widgetChanged(); public slots: + /** * Open a panel or dialog depending on dock mode setting * If dock mode is true this method will emit the showPanel signal @@ -176,6 +178,7 @@ class GUI_EXPORT QgsPanelWidgetWrapper: public QgsPanelWidget { Q_OBJECT public: + /** * @brief Wrapper widget for existing widgets which can't have * the inheritance tree changed, e.g dialogs. diff --git a/src/gui/qgspanelwidgetstack.h b/src/gui/qgspanelwidgetstack.h index bafcefb22759..2338c1e49d9d 100644 --- a/src/gui/qgspanelwidgetstack.h +++ b/src/gui/qgspanelwidgetstack.h @@ -86,6 +86,7 @@ class GUI_EXPORT QgsPanelWidgetStack : public QWidget, private Ui::QgsRendererWi QgsPanelWidget* currentPanel(); public slots: + /** * Accept the current active widget in the stack. * diff --git a/src/gui/qgspixmaplabel.h b/src/gui/qgspixmaplabel.h index 6882e47f3dfd..06efcad0580f 100644 --- a/src/gui/qgspixmaplabel.h +++ b/src/gui/qgspixmaplabel.h @@ -28,6 +28,7 @@ class GUI_EXPORT QgsPixmapLabel : public QLabel public: explicit QgsPixmapLabel( QWidget *parent = nullptr ); + /** * Calculates the height for the given width. * diff --git a/src/gui/qgsprevieweffect.h b/src/gui/qgsprevieweffect.h index d02dbaa59491..63f88e465b25 100644 --- a/src/gui/qgsprevieweffect.h +++ b/src/gui/qgsprevieweffect.h @@ -47,6 +47,7 @@ class GUI_EXPORT QgsPreviewEffect: public QGraphicsEffect * @see mode */ void setMode( PreviewMode mode ); + /** Returns the mode used for the preview effect. * @returns PreviewMode currently used by the effect * @note added in 2.3 diff --git a/src/gui/qgsprojectionselector.h b/src/gui/qgsprojectionselector.h index 720f9cf153c1..9bbfabca8f25 100644 --- a/src/gui/qgsprojectionselector.h +++ b/src/gui/qgsprojectionselector.h @@ -115,6 +115,7 @@ class GUI_EXPORT QgsProjectionSelector : public QWidget, private Ui::QgsProjecti void resizeEvent( QResizeEvent * theEvent ) override; private: + /** * \brief converts the CRS group to a SQL expression fragment * diff --git a/src/gui/qgsquerybuilder.h b/src/gui/qgsquerybuilder.h index 9a94b72de466..375dc63c12da 100644 --- a/src/gui/qgsquerybuilder.h +++ b/src/gui/qgsquerybuilder.h @@ -40,6 +40,7 @@ class GUI_EXPORT QgsQueryBuilder : public QDialog, private Ui::QgsQueryBuilderBa { Q_OBJECT public: + /** This constructor is used when the query builder is called from the * vector layer properties dialog * @param layer existing vector layer diff --git a/src/gui/qgsrelationeditorwidget.h b/src/gui/qgsrelationeditorwidget.h index c6b6a126351b..3f4ad727ade9 100644 --- a/src/gui/qgsrelationeditorwidget.h +++ b/src/gui/qgsrelationeditorwidget.h @@ -41,6 +41,7 @@ class GUI_EXPORT QgsRelationEditorWidget : public QgsCollapsibleGroupBox Q_PROPERTY( bool showLabel READ showLabel WRITE setShowLabel ) public: + /** * @param parent parent widget */ @@ -95,6 +96,7 @@ class GUI_EXPORT QgsRelationEditorWidget : public QgsCollapsibleGroupBox * @note Added in QGIS 2.18 */ bool showLinkButton() const; + /** * Determines if the "link feature" button should be shown * @@ -108,6 +110,7 @@ class GUI_EXPORT QgsRelationEditorWidget : public QgsCollapsibleGroupBox * @note Added in QGIS 2.18 */ bool showUnlinkButton() const; + /** * Determines if the "unlink feature" button should be shown * diff --git a/src/gui/qgsrubberband.h b/src/gui/qgsrubberband.h index 38dba39a312e..3f7c845f248b 100644 --- a/src/gui/qgsrubberband.h +++ b/src/gui/qgsrubberband.h @@ -36,26 +36,32 @@ class GUI_EXPORT QgsRubberBand: public QgsMapCanvasItem //! Icons enum IconType { + /** * No icon is used */ ICON_NONE, + /** * A cross is used to highlight points (+) */ ICON_CROSS, + /** * A cross is used to highlight points (x) */ ICON_X, + /** * A box is used to highlight points (□) */ ICON_BOX, + /** * A circle is used to highlight points (○) */ ICON_CIRCLE, + /** * A full box is used to highlight points (■) */ diff --git a/src/gui/qgsscalerangewidget.h b/src/gui/qgsscalerangewidget.h index e301a4002df2..11567fdac4fd 100644 --- a/src/gui/qgsscalerangewidget.h +++ b/src/gui/qgsscalerangewidget.h @@ -34,6 +34,7 @@ class GUI_EXPORT QgsScaleRangeWidget : public QWidget ~QgsScaleRangeWidget(); //! set the map canvas which will be used for the current scale buttons + /** * @brief setMapCanvas set the map canvas which will be used for the current scale buttons * if not set, the buttons are hidden. @@ -62,6 +63,7 @@ class GUI_EXPORT QgsScaleRangeWidget : public QWidget void reloadProjectScales(); public slots: + /** * Set the minimum scale. Infinite will be handled equally to 0 internally. */ diff --git a/src/gui/qgstablewidgetbase.h b/src/gui/qgstablewidgetbase.h index bfba93298fbc..ef2b7145b482 100644 --- a/src/gui/qgstablewidgetbase.h +++ b/src/gui/qgstablewidgetbase.h @@ -32,12 +32,14 @@ class GUI_EXPORT QgsTableWidgetBase: public QWidget, public Ui::QgsTableWidgetBa { Q_OBJECT public: + /** * Constructor. */ explicit QgsTableWidgetBase( QWidget* parent ); protected: + /** * Initialise the table with the given model. * Must be called once in the child class' constructor. @@ -45,12 +47,14 @@ class GUI_EXPORT QgsTableWidgetBase: public QWidget, public Ui::QgsTableWidgetBa void init( QAbstractTableModel* model ); signals: + /** * Emitted each time a key or a value is changed. */ void valueChanged(); private slots: + /** * Called when the add button is clicked. */ diff --git a/src/gui/qgstablewidgetitem.h b/src/gui/qgstablewidgetitem.h index 7054dad8bfc5..9d4a305a6c39 100644 --- a/src/gui/qgstablewidgetitem.h +++ b/src/gui/qgstablewidgetitem.h @@ -26,6 +26,7 @@ class GUI_EXPORT QgsTableWidgetItem : public QTableWidgetItem { public: QgsTableWidgetItem(); + /** * Creates a new table widget item with the specified text. */ @@ -37,6 +38,7 @@ class GUI_EXPORT QgsTableWidgetItem : public QTableWidgetItem * By default this will be set to Qt::DisplayRole */ void setSortRole( int role ); + /** * Get the role by which the items should be sorted. * By default this will be Qt::DisplayRole diff --git a/src/gui/qgstabwidget.h b/src/gui/qgstabwidget.h index e4ce636f6c4c..b3b48504738b 100644 --- a/src/gui/qgstabwidget.h +++ b/src/gui/qgstabwidget.h @@ -29,6 +29,7 @@ class GUI_EXPORT QgsTabWidget : public QTabWidget Q_OBJECT public: + /** * Create a new QgsTabWidget with the optionally provided parent. * diff --git a/src/gui/raster/qgsrasterhistogramwidget.h b/src/gui/raster/qgsrasterhistogramwidget.h index 171685fcae72..29b021e654bc 100644 --- a/src/gui/raster/qgsrasterhistogramwidget.h +++ b/src/gui/raster/qgsrasterhistogramwidget.h @@ -82,6 +82,7 @@ class GUI_EXPORT QgsRasterHistogramWidget : public QgsMapLayerConfigWidget, priv void on_btnHistoMax_toggled(); //! Called when a selection has been made using the plot picker. void histoPickerSelected( QPointF ); + /** Called when a selection has been made using the plot picker (for qwt5 only). @note not available in python bindings */ diff --git a/src/gui/raster/qgsrastertransparencywidget.h b/src/gui/raster/qgsrastertransparencywidget.h index 600f5152d4e4..2539edfc36cb 100644 --- a/src/gui/raster/qgsrastertransparencywidget.h +++ b/src/gui/raster/qgsrastertransparencywidget.h @@ -35,6 +35,7 @@ class GUI_EXPORT QgsRasterTransparencyWidget : public QgsMapLayerConfigWidget, p { Q_OBJECT public: + /** * @brief Widget to control a layers transparency and related options */ @@ -42,6 +43,7 @@ class GUI_EXPORT QgsRasterTransparencyWidget : public QgsMapLayerConfigWidget, p ~QgsRasterTransparencyWidget(); public slots: + /** * Sync the widget state to the layer set for the widget. */ diff --git a/src/gui/raster/qgsrendererrasterpropertieswidget.h b/src/gui/raster/qgsrendererrasterpropertieswidget.h index 42ce972ed13d..ed529ccc124a 100644 --- a/src/gui/raster/qgsrendererrasterpropertieswidget.h +++ b/src/gui/raster/qgsrendererrasterpropertieswidget.h @@ -35,6 +35,7 @@ class GUI_EXPORT QgsRendererRasterPropertiesWidget : public QgsMapLayerConfigWid Q_OBJECT public: + /** * A widget to hold the renderer properties for a raster layer. * @param layer The raster layer to style diff --git a/src/gui/symbology-ng/qgs25drendererwidget.h b/src/gui/symbology-ng/qgs25drendererwidget.h index 37a5801f5ac2..5cc17b33745e 100644 --- a/src/gui/symbology-ng/qgs25drendererwidget.h +++ b/src/gui/symbology-ng/qgs25drendererwidget.h @@ -29,6 +29,7 @@ class GUI_EXPORT Qgs25DRendererWidget : public QgsRendererWidget, Ui::Qgs25DRend Q_OBJECT public: + /** Static creation method * @param layer the layer where this renderer is applied * @param style diff --git a/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h b/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h index 11303e800051..811e365bd8e5 100644 --- a/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h +++ b/src/gui/symbology-ng/qgsarrowsymbollayerwidget.h @@ -28,6 +28,7 @@ class GUI_EXPORT QgsArrowSymbolLayerWidget: public QgsSymbolLayerWidget, private Q_OBJECT public: + /** Constructor * @param layer the layer where this symbol layer is applied * @param parent the parent widget diff --git a/src/gui/symbology-ng/qgsheatmaprendererwidget.h b/src/gui/symbology-ng/qgsheatmaprendererwidget.h index 18cff7579923..9e0d6c9242c2 100644 --- a/src/gui/symbology-ng/qgsheatmaprendererwidget.h +++ b/src/gui/symbology-ng/qgsheatmaprendererwidget.h @@ -29,6 +29,7 @@ class GUI_EXPORT QgsHeatmapRendererWidget : public QgsRendererWidget, private Ui Q_OBJECT public: + /** Static creation method * @param layer the layer where this renderer is applied * @param style diff --git a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h index 938d83f98ee7..f66263fbfa5a 100644 --- a/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h +++ b/src/gui/symbology-ng/qgsinvertedpolygonrendererwidget.h @@ -31,6 +31,7 @@ class GUI_EXPORT QgsInvertedPolygonRendererWidget : public QgsRendererWidget, pr Q_OBJECT public: + /** Static creation method * @param layer the layer where this renderer is applied * @param style diff --git a/src/gui/symbology-ng/qgsrendererpropertiesdialog.h b/src/gui/symbology-ng/qgsrendererpropertiesdialog.h index 64bf2a0acf72..15818a45984b 100644 --- a/src/gui/symbology-ng/qgsrendererpropertiesdialog.h +++ b/src/gui/symbology-ng/qgsrendererpropertiesdialog.h @@ -66,6 +66,7 @@ class GUI_EXPORT QgsRendererPropertiesDialog : public QDialog, private Ui::QgsRe void setDockMode( bool dockMode ); signals: + /** * Emitted when expression context variables on the associated * vector layers have been changed. Will request the parent dialog @@ -120,6 +121,7 @@ class GUI_EXPORT QgsRendererPropertiesDialog : public QDialog, private Ui::QgsRe void syncToLayer(); protected: + /** * Connect the given slot to the value changed event for the set of widgets * Each widget is checked for type and the common type of signal is connected diff --git a/src/gui/symbology-ng/qgsrendererwidget.h b/src/gui/symbology-ng/qgsrendererwidget.h index 07ef7ece5173..f009127a36f4 100644 --- a/src/gui/symbology-ng/qgsrendererwidget.h +++ b/src/gui/symbology-ng/qgsrendererwidget.h @@ -76,6 +76,7 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget void applyChanges(); signals: + /** * Emitted when expression context variables on the associated * vector layers have been changed. Will request the parent dialog @@ -117,6 +118,7 @@ class GUI_EXPORT QgsRendererWidget : public QgsPanelWidget virtual void paste() {} private: + /** * This will be called whenever the renderer is set on a layer. * This can be overwritten in subclasses. @@ -146,6 +148,7 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD Q_OBJECT public: + /** Constructor * @param symbolList must not be empty * @param layer must not be null @@ -176,6 +179,7 @@ class GUI_EXPORT QgsDataDefinedValueDialog : public QDialog, public Ui::QgsDataD void dataDefinedChanged(); protected: + /** * Should be called in the constructor of child classes. * diff --git a/src/gui/symbology-ng/qgsrulebasedrendererwidget.h b/src/gui/symbology-ng/qgsrulebasedrendererwidget.h index efd7f21c0aca..f099616da24b 100644 --- a/src/gui/symbology-ng/qgsrulebasedrendererwidget.h +++ b/src/gui/symbology-ng/qgsrulebasedrendererwidget.h @@ -183,6 +183,7 @@ class GUI_EXPORT QgsRendererRulePropsWidget : public QgsPanelWidget, private Ui: Q_OBJECT public: + /** * Widget to edit the details of a rule based renderer rule. * @param rule The rule to edit. @@ -216,6 +217,7 @@ class GUI_EXPORT QgsRendererRulePropsWidget : public QgsPanelWidget, private Ui: * Apply any changes from the widget to the set rule. */ void apply(); + /** * Set the widget in dock mode. * @param dockMode True for dock mode. diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.h b/src/gui/symbology-ng/qgsstyleexportimportdialog.h index a9c760ddcd35..7ad6ecd27183 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.h +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.h @@ -54,6 +54,7 @@ class GUI_EXPORT QgsStyleExportImportDialog : public QDialog, private Ui::QgsSty * @param symbolNames list of symbol names */ void selectSymbols( const QStringList& symbolNames ); + /** * @brief deselectSymbols deselect symbols by name * @param symbolNames list of symbol names @@ -62,33 +63,40 @@ class GUI_EXPORT QgsStyleExportImportDialog : public QDialog, private Ui::QgsSty public slots: void doExportImport(); + /** * @brief selectByGroup open select by group dialog */ void selectByGroup(); + /** * @brief selectAll selects all symbols */ void selectAll(); + /** * @brief clearSelection deselects all symbols */ void clearSelection(); + /** * Select the symbols belonging to the given group * @param groupName the name of the group to be selected */ void selectGroup( const QString& groupName ); + /** * Deselect the symbols belonging to the given group * @param groupName the name of the group to be deselected */ void deselectGroup( const QString& groupName ); + /** * @brief selectSmartgroup selects all symbols from a smart group * @param groupName */ void selectSmartgroup( const QString& groupName ); + /** * @brief deselectSmartgroup deselects all symbols from a smart group * @param groupName diff --git a/src/gui/symbology-ng/qgsstylegroupselectiondialog.h b/src/gui/symbology-ng/qgsstylegroupselectiondialog.h index 13350b1a7966..ec370dbbc754 100644 --- a/src/gui/symbology-ng/qgsstylegroupselectiondialog.h +++ b/src/gui/symbology-ng/qgsstylegroupselectiondialog.h @@ -55,6 +55,7 @@ class GUI_EXPORT QgsStyleGroupSelectionDialog : public QDialog, private Ui::Symb void groupTreeSelectionChanged( const QItemSelection& selected, const QItemSelection& deselected ); private: + /** * @brief build group tree * @param parent diff --git a/src/gui/symbology-ng/qgssymbollayerwidget.h b/src/gui/symbology-ng/qgssymbollayerwidget.h index 02059124187f..5ee35c789f67 100644 --- a/src/gui/symbology-ng/qgssymbollayerwidget.h +++ b/src/gui/symbology-ng/qgssymbollayerwidget.h @@ -73,11 +73,13 @@ class GUI_EXPORT QgsSymbolLayerWidget : public QWidget, protected QgsExpressionC QgsMapCanvas* mMapCanvas; signals: + /** * Should be emitted whenever configuration changes happened on this symbol layer configuration. * If the subsymbol is changed, {@link symbolChanged()} should be emitted instead. */ void changed(); + /** * Should be emitted whenever the sub symbol changed on this symbol layer configuration. * Normally {@link changed()} should be preferred. @@ -528,6 +530,7 @@ class GUI_EXPORT QgsSVGFillSymbolLayerWidget : public QgsSymbolLayerWidget, priv protected: QgsSVGFillSymbolLayer* mLayer; void insertIcons(); + /** Enables or disables svg fill color, border color and border width based on whether the * svg file supports custom parameters. * @param resetValues set to true to overwrite existing layer fill color, border color and border width diff --git a/src/gui/symbology-ng/qgssymbolselectordialog.h b/src/gui/symbology-ng/qgssymbolselectordialog.h index 0a9680896e1f..65fc711fc6b0 100644 --- a/src/gui/symbology-ng/qgssymbolselectordialog.h +++ b/src/gui/symbology-ng/qgssymbolselectordialog.h @@ -86,6 +86,7 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs friend class QgsSymbolSelectorDialog; public: + /** * Symbol selector widget that can be used to select and build a symbol * @param symbol The symbol to load into the widget as a start point. @@ -165,12 +166,14 @@ class GUI_EXPORT QgsSymbolSelectorWidget: public QgsPanelWidget, private Ui::Qgs void setWidget( QWidget* widget ); signals: + /** * Emiited when a symbol is modified in the widget. */ void symbolModified(); public slots: + /** * Move the active symbol layer down. */ diff --git a/src/plugins/compass/qgscompassplugin.h b/src/plugins/compass/qgscompassplugin.h index e520c7553f71..c3f32b30894c 100644 --- a/src/plugins/compass/qgscompassplugin.h +++ b/src/plugins/compass/qgscompassplugin.h @@ -32,29 +32,35 @@ class QgsCompassPlugin: public QObject, public QgisPlugin, private Ui::QgsCompas { Q_OBJECT public: + /** * Constructor for a plugin. The QgisInterface pointer is passed by * QGIS when it attempts to instantiate the plugin. * @param qI Pointer to the QgisInterface object */ explicit QgsCompassPlugin( QgisInterface * ); + /** * Virtual function to return the name of the plugin. The name will be used when presenting a list * of installable plugins to the user */ virtual QString name(); + /** * Virtual function to return the version of the plugin. */ virtual QString version(); + /** * Virtual function to return a description of the plugins functions */ virtual QString description(); + /** * Virtual function to return a plugin category */ virtual QString category(); + /** * Return the plugin type */ diff --git a/src/plugins/coordinate_capture/coordinatecapture.h b/src/plugins/coordinate_capture/coordinatecapture.h index 52ca539d5971..b99f154374f0 100644 --- a/src/plugins/coordinate_capture/coordinatecapture.h +++ b/src/plugins/coordinate_capture/coordinatecapture.h @@ -98,6 +98,7 @@ class CoordinateCapture: public QObject, public QgisPlugin void setCRS(); //! Called when mouse clicks on the canvas. Will populate text box with coords. void mouseClicked( const QgsPoint& thePoint ); + /** Called when mouse moved over the canvas. If the tracking button is toggled, * the text box coords will be updated. */ void mouseMoved( const QgsPoint& thePoint ); diff --git a/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp b/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp index a4b50582d051..699ea8f2384b 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp +++ b/src/plugins/evis/databaseconnection/evisdatabaselayerfieldselectiongui.cpp @@ -76,6 +76,7 @@ void eVisDatabaseLayerFieldSelectionGui::setFieldList( QStringList* fieldList ) * Public and Private Slots * */ + /** * Slot called when the ok/accept button is pressed */ diff --git a/src/plugins/evis/eventbrowser/evisimagedisplaywidget.cpp b/src/plugins/evis/eventbrowser/evisimagedisplaywidget.cpp index 720e21177682..62743338260c 100644 --- a/src/plugins/evis/eventbrowser/evisimagedisplaywidget.cpp +++ b/src/plugins/evis/eventbrowser/evisimagedisplaywidget.cpp @@ -32,6 +32,7 @@ #include #include #include + /** * Constructor * @param parent - Pointer the to parent QWidget for modality @@ -238,6 +239,7 @@ void eVisImageDisplayWidget::setScalers() * Public and Private Slots * */ + /** * Slot called when a http request is complete * @param requestId - The id of the http request diff --git a/src/plugins/gps_importer/qgsgpsplugin.h b/src/plugins/gps_importer/qgsgpsplugin.h index 9fce760784a8..0defa96fad9f 100644 --- a/src/plugins/gps_importer/qgsgpsplugin.h +++ b/src/plugins/gps_importer/qgsgpsplugin.h @@ -34,6 +34,7 @@ class QgsGPSPlugin: public QObject, public QgisPlugin { Q_OBJECT public: + /** Constructor for a plugin. The QgisInterface pointer * is passed by QGIS when it attempts to instantiate the plugin. * @param qI Pointer to the QgisInterface object. diff --git a/src/plugins/grass/qgsgrassmodule.h b/src/plugins/grass/qgsgrassmodule.h index 839bdd8dc1dc..cf3a5938e921 100644 --- a/src/plugins/grass/qgsgrassmodule.h +++ b/src/plugins/grass/qgsgrassmodule.h @@ -125,6 +125,7 @@ class QgsGrassModule : public QWidget, private Ui::QgsGrassModuleBase //void mapsetChanged(); private: + /** Set progress bar or busy indicator if percent is 100 * @param percent progress to show in % * @param force to set progress for 100% */ diff --git a/src/plugins/grass/qgsgrassmoduleinput.h b/src/plugins/grass/qgsgrassmoduleinput.h index 999e09b7457a..fad2da97bf7a 100644 --- a/src/plugins/grass/qgsgrassmoduleinput.h +++ b/src/plugins/grass/qgsgrassmoduleinput.h @@ -233,6 +233,7 @@ class QgsGrassModuleInput : public QgsGrassModuleGroupBoxItem Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file diff --git a/src/plugins/grass/qgsgrassmoduleoptions.h b/src/plugins/grass/qgsgrassmoduleoptions.h index 5f8e811d682f..89a0e5ce55c1 100644 --- a/src/plugins/grass/qgsgrassmoduleoptions.h +++ b/src/plugins/grass/qgsgrassmoduleoptions.h @@ -179,6 +179,7 @@ class QgsGrassModuleStandardOptions: public QWidget, public QgsGrassModuleOption void switchAdvanced(); private: + /** Read and parse module options (--interface-description). * @param errors - list to which possible errors are added */ diff --git a/src/plugins/grass/qgsgrassmoduleparam.h b/src/plugins/grass/qgsgrassmoduleparam.h index 6c75bb3bb53b..5b9ec6d57158 100644 --- a/src/plugins/grass/qgsgrassmoduleparam.h +++ b/src/plugins/grass/qgsgrassmoduleparam.h @@ -54,6 +54,7 @@ class QgsGrassModuleCheckBox : public QCheckBox Q_OBJECT public: + /** \brief Constructor */ QgsGrassModuleCheckBox( const QString & text, QWidget * parent = 0 ); @@ -83,6 +84,7 @@ class QgsGrassModuleCheckBox : public QCheckBox class QgsGrassModuleParam { public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file @@ -172,6 +174,7 @@ class QgsGrassModuleGroupBoxItem : public QGroupBox, public QgsGrassModuleParam Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file @@ -238,6 +241,7 @@ class QgsGrassModuleOption : public QgsGrassModuleMultiParam Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file @@ -334,6 +338,7 @@ class QgsGrassModuleOption : public QgsGrassModuleMultiParam bool mUsesRegion; }; /********************** QgsGrassModuleFlag ************************/ + /** \class QgsGrassModuleFlag * \brief GRASS flag */ @@ -342,6 +347,7 @@ class QgsGrassModuleFlag : public QgsGrassModuleCheckBox, public QgsGrassModuleP Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file @@ -431,6 +437,7 @@ class QgsGrassModuleField : public QgsGrassModuleOption Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file @@ -453,6 +460,7 @@ class QgsGrassModuleVectorField : public QgsGrassModuleMultiParam Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file @@ -583,6 +591,7 @@ class QgsGrassModuleFile : public QgsGrassModuleGroupBoxItem Q_OBJECT public: + /** \brief Constructor * \param qdesc option element in QGIS module description XML file * \param gdesc GRASS module XML description file diff --git a/src/plugins/grass/qgsgrassplugin.h b/src/plugins/grass/qgsgrassplugin.h index 1fdbde5ef77c..2508a4fcc68b 100644 --- a/src/plugins/grass/qgsgrassplugin.h +++ b/src/plugins/grass/qgsgrassplugin.h @@ -45,29 +45,35 @@ class QgsGrassPlugin : public QObject, public QgisPlugin Q_OBJECT public: + /** * Constructor for a plugin. The QgisInterface pointer is passed by * QGIS when it attempts to instantiate the plugin. * @param qI Pointer to the QgisInterface object. */ explicit QgsGrassPlugin( QgisInterface * qI ); + /** * Virtual function to return the name of the plugin. The name will be used when presenting a list * of installable plugins to the user */ virtual QString name(); + /** * Virtual function to return the version of the plugin. */ virtual QString version(); + /** * Virtual function to return a description of the plugins functions */ virtual QString description(); + /** * Virtual function to return a category of the plugin */ virtual QString category(); + /** * Return the plugin type */ diff --git a/src/plugins/heatmap/heatmapgui.h b/src/plugins/heatmap/heatmapgui.h index f87ce3e96c71..0ee759e2ce75 100644 --- a/src/plugins/heatmap/heatmapgui.h +++ b/src/plugins/heatmap/heatmapgui.h @@ -19,6 +19,7 @@ #include "qgsvectorlayer.h" #include "qgscoordinatereferencesystem.h" #include "qgsgeometry.h" + /** @author Arunmozhi */ diff --git a/src/plugins/interpolation/qgsinterpolationdialog.h b/src/plugins/interpolation/qgsinterpolationdialog.h index 2625da4c309b..699e857cda66 100644 --- a/src/plugins/interpolation/qgsinterpolationdialog.h +++ b/src/plugins/interpolation/qgsinterpolationdialog.h @@ -64,6 +64,7 @@ class QgsInterpolationDialog: public QDialog, private Ui::QgsInterpolationDialog QgsVectorLayer* vectorLayerFromName( const QString& name ); //! Enables or disables the Ok button depending on the availability of input layers and the output file void enableOrDisableOkButton(); + /** Get the current output bounding box (might be different to the compound layers bounding box because of user edits) @return the bounding box or an empty bounding box in case of error*/ QgsRectangle currentBoundingBox(); diff --git a/src/plugins/qgisplugin.h b/src/plugins/qgisplugin.h index 15eedbfe2db6..0f9ae01557e7 100644 --- a/src/plugins/qgisplugin.h +++ b/src/plugins/qgisplugin.h @@ -12,6 +12,7 @@ * (at your option) any later version. * * * ***************************************************************************/ + /** QGIS - Plugin API * * \section about About QGis Plugins @@ -172,6 +173,7 @@ class QgisPlugin QString mVersion; /// UI or MAPLAYER plug-in + /** @todo Really, might be indicative that this needs to split into maplayer vs. ui plug-in vs. other kind of plug-in diff --git a/src/plugins/roadgraph/exportdlg.h b/src/plugins/roadgraph/exportdlg.h index 06cdcc36611b..cf61db3bcf2c 100644 --- a/src/plugins/roadgraph/exportdlg.h +++ b/src/plugins/roadgraph/exportdlg.h @@ -28,6 +28,7 @@ class QgsVectorLayer; /** @author Sergey Yakushev */ + /** * \class RgSettingsDlg * \brief implement of export dialog diff --git a/src/plugins/roadgraph/linevectorlayersettings.h b/src/plugins/roadgraph/linevectorlayersettings.h index a11889d359d1..aacef098aadc 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.h +++ b/src/plugins/roadgraph/linevectorlayersettings.h @@ -27,6 +27,7 @@ class QWidget; /** @author Sergey Yakushev */ + /** * \class RgSettings * \brief This class contained settings for RgLineVectorLayerDirector @@ -35,6 +36,7 @@ class QWidget; class RgLineVectorLayerSettings: public RgSettings { public: + /** * \enum DirectionType * \brief DirectionType enumeration discribe @@ -42,6 +44,7 @@ class RgLineVectorLayerSettings: public RgSettings enum DirectionType { FirstPointToLastPoint = 1, LastPointToFirstPoint = 2, Both = 3 }; public: + /** * default constructor. */ diff --git a/src/plugins/roadgraph/linevectorlayerwidget.h b/src/plugins/roadgraph/linevectorlayerwidget.h index 2313d112f416..477b88ac8b27 100644 --- a/src/plugins/roadgraph/linevectorlayerwidget.h +++ b/src/plugins/roadgraph/linevectorlayerwidget.h @@ -33,6 +33,7 @@ class QgsMapLayerComboBox; /** @author Sergey Yakushev */ + /** * \class RgLineVectorLayerSettingsWidget * \brief @@ -50,6 +51,7 @@ class RgLineVectorLayerSettingsWidget : public QWidget QgsVectorLayer * selectedLayer(); public: + /** * list of passible layers */ diff --git a/src/plugins/roadgraph/roadgraphplugin.h b/src/plugins/roadgraph/roadgraphplugin.h index aa24a327d89a..3b5dd34996b2 100644 --- a/src/plugins/roadgraph/roadgraphplugin.h +++ b/src/plugins/roadgraph/roadgraphplugin.h @@ -43,6 +43,7 @@ class RoadGraphPlugin: public QObject, public QgisPlugin { Q_OBJECT public: + /** * Constructor for a plugin. The QgisInterface pointer is passed by * QGIS when it attempts to instantiate the plugin. @@ -51,6 +52,7 @@ class RoadGraphPlugin: public QObject, public QgisPlugin explicit RoadGraphPlugin( QgisInterface * theQgisInterface ); //! Destructor virtual ~RoadGraphPlugin(); + /** * return pointer to my Interface */ @@ -96,12 +98,14 @@ class RoadGraphPlugin: public QObject, public QgisPlugin void help(); private slots: + /** * set show roads direction */ void onShowDirection(); private: + /** * set all gui elements to default status */ @@ -122,6 +126,7 @@ class RoadGraphPlugin: public QObject, public QgisPlugin // ADD YOUR OWN PROPERTY DECLARATIONS AFTER THIS POINT..... // //////////////////////////////////////////////////////////////////// + /** * on show settings */ diff --git a/src/plugins/roadgraph/settings.h b/src/plugins/roadgraph/settings.h index 6bafaf7b03d3..c02138034391 100644 --- a/src/plugins/roadgraph/settings.h +++ b/src/plugins/roadgraph/settings.h @@ -38,19 +38,23 @@ class RgSettings * write settings to the poject file */ virtual void write( QgsProject * ) = 0; + /** * read settings form project file */ virtual void read( const QgsProject * ) = 0; + /** * This function test settings and return true if setting correct */ virtual bool test() = 0; + /** * Make settings widget * use it for GUI setting */ virtual QWidget* getGui( QWidget* parent ) = 0; + /** * Load settings from widget */ diff --git a/src/plugins/roadgraph/settingsdlg.h b/src/plugins/roadgraph/settingsdlg.h index fd59b98f7c62..787d32ad6b3c 100644 --- a/src/plugins/roadgraph/settingsdlg.h +++ b/src/plugins/roadgraph/settingsdlg.h @@ -29,6 +29,7 @@ class RgSettings; /** @author Sergey Yakushev */ + /** * \class RgSettingsDlg * \brief implement of settings dialog diff --git a/src/plugins/roadgraph/shortestpathwidget.h b/src/plugins/roadgraph/shortestpathwidget.h index 16fd45e92b6b..fd66de07f565 100644 --- a/src/plugins/roadgraph/shortestpathwidget.h +++ b/src/plugins/roadgraph/shortestpathwidget.h @@ -35,6 +35,7 @@ class QgsGraph; /** @author Sergey Yakushev */ + /** * \class VrpPluginShortestPathDlg * \brief This class implement user interface for finding shortest path between two points. @@ -43,6 +44,7 @@ class RgShortestPathWidget : public QgsDockWidget { Q_OBJECT public: + /** * Standard constructor */ @@ -54,6 +56,7 @@ class RgShortestPathWidget : public QgsDockWidget ~RgShortestPathWidget(); private slots: + /** * export path */ @@ -100,6 +103,7 @@ class RgShortestPathWidget : public QgsDockWidget void helpRequested(); private: + /** * return path as a graph */ diff --git a/src/plugins/roadgraph/units.h b/src/plugins/roadgraph/units.h index 35cfd51da750..2daed469d586 100644 --- a/src/plugins/roadgraph/units.h +++ b/src/plugins/roadgraph/units.h @@ -25,6 +25,7 @@ /** @author Sergey Yakushev */ + /** * \class Unit * \brief This class provide interface to access unit name and multipler. @@ -33,6 +34,7 @@ class Unit { public: + /** * default constructor */ diff --git a/src/plugins/spatialquery/qgsgeometrycoordinatetransform.h b/src/plugins/spatialquery/qgsgeometrycoordinatetransform.h index 7c8e3011a2aa..babd112abe7b 100644 --- a/src/plugins/spatialquery/qgsgeometrycoordinatetransform.h +++ b/src/plugins/spatialquery/qgsgeometrycoordinatetransform.h @@ -29,6 +29,7 @@ class QgsGeometryCoordinateTransform { public: + /** * \brief Constructor for a Geometry Coordinate Transform. * @@ -53,11 +54,13 @@ class QgsGeometryCoordinateTransform */ void transform( QgsGeometry *geom ); private: + /** * \brief Transform the coordinates reference system of the geometry (use by transform) * \param geom Geometry */ void setGeomTransform( QgsGeometry *geom ); + /** * \brief None transform the coordinates reference system of the geometry (use by transform) * \param geom Geometry diff --git a/src/plugins/spatialquery/qgsmngprogressbar.h b/src/plugins/spatialquery/qgsmngprogressbar.h index 18dfb4c6c67f..e7d6cd5dfb7d 100644 --- a/src/plugins/spatialquery/qgsmngprogressbar.h +++ b/src/plugins/spatialquery/qgsmngprogressbar.h @@ -27,11 +27,13 @@ class MngProgressBar { public: + /** * \brief Constructor for a MngProgressBar. * \param pb Pointer to the MngProgressBar object. */ explicit MngProgressBar( QProgressBar *pb ); + /** * \brief Destructor */ diff --git a/src/plugins/spatialquery/qgsreaderfeatures.h b/src/plugins/spatialquery/qgsreaderfeatures.h index cd2f3024397c..5c3ff056e9e8 100644 --- a/src/plugins/spatialquery/qgsreaderfeatures.h +++ b/src/plugins/spatialquery/qgsreaderfeatures.h @@ -29,6 +29,7 @@ class QgsReaderFeatures { public: + /** * \brief Constructor for a Reader Features. * \param layer Pointer to the layer. @@ -44,6 +45,7 @@ class QgsReaderFeatures bool nextFeature( QgsFeature & feature ); private: + /** * \brief init Reader * \param useSelection Use or not use the features selected diff --git a/src/plugins/spatialquery/qgsrubberselectid.h b/src/plugins/spatialquery/qgsrubberselectid.h index 7497bc05f4d6..78daad81cd59 100644 --- a/src/plugins/spatialquery/qgsrubberselectid.h +++ b/src/plugins/spatialquery/qgsrubberselectid.h @@ -30,11 +30,13 @@ class QgsRubberSelectId { public: + /** * Constructor for a class RubberSelectedId. * @param mapCanvas Pointer to the iface.mapCanvas(). */ explicit QgsRubberSelectId( QgsMapCanvas* mapCanvas ); + /** * \brief Destructor */ diff --git a/src/plugins/spatialquery/qgsspatialquery.h b/src/plugins/spatialquery/qgsspatialquery.h index c70db538374b..084faa6674d1 100644 --- a/src/plugins/spatialquery/qgsspatialquery.h +++ b/src/plugins/spatialquery/qgsspatialquery.h @@ -52,6 +52,7 @@ enum Topologic_Relation class QgsSpatialQuery { public: + /** * \brief Constructor for a Spatial query. * \param pb Pointer to the MngProgressBar object. @@ -138,6 +139,7 @@ class QgsSpatialQuery */ void populateIndexResult( QgsFeatureIds &qsetIndexResult, QgsFeatureId idTarget, const QgsGeometry& geomTarget, bool ( QgsGeometryEngine::* operation )( const QgsAbstractGeometry&, QString* ) const ); + /** * \brief Populate index Result Disjoint * \param qsetIndexResult Reference to QSet contains the result query diff --git a/src/plugins/spatialquery/qgsspatialquerydialog.h b/src/plugins/spatialquery/qgsspatialquerydialog.h index d5f5e28fb316..c23337400411 100644 --- a/src/plugins/spatialquery/qgsspatialquerydialog.h +++ b/src/plugins/spatialquery/qgsspatialquerydialog.h @@ -34,6 +34,7 @@ class QgsSpatialQueryDialog : public QDialog, private Ui::QgsSpatialQueryDialogB { Q_OBJECT public: + /** * Constructor for a dialog. The QgisInterface pointer is passed by * QGIS when it attempts to instantiate the plugin. diff --git a/src/plugins/spatialquery/qgsspatialqueryplugin.h b/src/plugins/spatialquery/qgsspatialqueryplugin.h index 7047cb1a8faf..56fa515a18a8 100644 --- a/src/plugins/spatialquery/qgsspatialqueryplugin.h +++ b/src/plugins/spatialquery/qgsspatialqueryplugin.h @@ -45,6 +45,7 @@ class QgsSpatialQueryPlugin: public QObject, public QgisPlugin { Q_OBJECT public: + /** * \brief Constructor for a plugin. The QgisInterface pointer is passed by * QGIS when it attempts to instantiate the plugin. diff --git a/src/plugins/topology/checkDock.h b/src/plugins/topology/checkDock.h index 2347f5a85484..8eb37d9e5c8a 100644 --- a/src/plugins/topology/checkDock.h +++ b/src/plugins/topology/checkDock.h @@ -43,6 +43,7 @@ class checkDock : public QgsDockWidget, private Ui::checkDock Q_OBJECT public: + /** * Constructor * @param qIface pointer to QgisInterface instance that is passed to the rulesDialog @@ -52,44 +53,54 @@ class checkDock : public QgsDockWidget, private Ui::checkDock ~checkDock(); private slots: + /** * Launches the configuration dialog */ void configure(); + /** * Launches fixing routine */ void fix(); + /** * Validates the whole layer */ void validateAll(); + /** * Validates the current extent */ void validateExtent(); + /** * Validates only selected features */ void validateSelected(); + /** * toggles the visibility of rubber band error markers */ void toggleErrorMarker(); + /** * Handles error selection * @param index clicked index in the table */ void errorListClicked( const QModelIndex& index ); + /** * Deletes allocated errors' data */ void deleteErrors(); + /** * Filters all errors involving features from specified layer * @param layerId layer ID */ void parseErrorListByLayer( const QString& layerId ); + /** * Clears rubberbands when window is hidden * @param visible true if the window is visible @@ -124,16 +135,19 @@ class checkDock : public QgsDockWidget, private Ui::checkDock * @param type validation type - what features to check */ void runTests( ValidateType type ); + /** * Validates topology * @param type validation type - what features to check */ void validate( ValidateType type ); + /** * Filters all errors involving specified feature * @param featureId feature ID */ void parseErrorListByFeature( int featureId ); + /** * Deletes vertex markers */ diff --git a/src/plugins/topology/dockModel.h b/src/plugins/topology/dockModel.h index 4cdeb46f8601..4b26e9ad32ec 100644 --- a/src/plugins/topology/dockModel.h +++ b/src/plugins/topology/dockModel.h @@ -29,12 +29,14 @@ class DockModel: public QAbstractTableModel Q_OBJECT public: + /** * Constructor * @param theErrorList reference to the ErrorList where errors will be stored * @param parent parent object */ DockModel( ErrorList& theErrorList, QObject *parent ); + /** * Returns header data * @param section required section @@ -42,12 +44,14 @@ class DockModel: public QAbstractTableModel * @param role data role */ QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const override; + /** * Returns data on the given index * @param index model index * @param role data role */ virtual QVariant data( const QModelIndex &index, int role ) const override; + /** * Updates data on given index * @param index model index @@ -55,6 +59,7 @@ class DockModel: public QAbstractTableModel * @param role data role */ virtual bool setData( const QModelIndex &index, const QVariant &value, int role = Qt::EditRole ) override; + /** * Returns item flags for the index * @param index model index @@ -66,6 +71,7 @@ class DockModel: public QAbstractTableModel * @param parent parent index */ int rowCount( const QModelIndex &parent ) const override; + /** * Returns the number of columns * @param parent parent index @@ -78,6 +84,7 @@ class DockModel: public QAbstractTableModel * @param index2 end index */ void reload( const QModelIndex &index1, const QModelIndex &index2 ); + /** * Resets the model */ diff --git a/src/plugins/topology/topolError.h b/src/plugins/topology/topolError.h index 9a8b000f8aec..b5e043260dc3 100644 --- a/src/plugins/topology/topolError.h +++ b/src/plugins/topology/topolError.h @@ -33,6 +33,7 @@ class FeatureLayer : layer( nullptr ) , feature( QgsFeature() ) {} + /** * Constructor * @param theLayer layer pointer @@ -60,30 +61,37 @@ class TopolError * A dummy fix - does nothing */ bool fixDummy() { return false; } + /** * Snaps to a feature */ bool fixSnap(); + /** * Moves first feature */ bool fixMoveFirst(); + /** * Moves second feature */ bool fixMoveSecond(); + /** * Unions features to the first */ bool fixUnionFirst(); + /** * Unions features to the first */ bool fixUnionSecond(); + /** * Deletes first feature */ bool fixDeleteFirst(); + /** * Deletes second feature */ @@ -97,6 +105,7 @@ class TopolError * @param fl2 second FeatureLayer pair */ bool fixMove( const FeatureLayer &fl1, const FeatureLayer &fl2 ); + /** * Unions features to the first one * @param fl1 first FeatureLayer pair @@ -105,6 +114,7 @@ class TopolError bool fixUnion( const FeatureLayer &fl1, const FeatureLayer &fl2 ); public: + /** * Constructor * @param theBoundingBox bounding box of the two features @@ -117,27 +127,33 @@ class TopolError * Destructor */ virtual ~TopolError() {} + /** * Runs fixing function * @param fixName name of the fix */ virtual bool fix( const QString& fixName ); + /** * Returns error's name */ virtual QString name() { return mName; } + /** * Returns topology conflict */ virtual QgsGeometry conflict() const { return mConflict; } + /** * Returns bounding box of the error */ virtual QgsRectangle boundingBox() { return mBoundingBox; } + /** * Returns FeatureLayer pairs from the error */ virtual QList featurePairs() { return mFeaturePairs; } + /** * Returns the names of possible fixes */ diff --git a/src/plugins/topology/topolTest.h b/src/plugins/topology/topolTest.h index 1cd0c3a85ec6..65a334c41cbd 100644 --- a/src/plugins/topology/topolTest.h +++ b/src/plugins/topology/topolTest.h @@ -110,6 +110,7 @@ class topolTest: public QObject * Returns copy of the test map */ QMap testMap() { return mTopologyRuleMap; } + /** * Runs the test and returns all found errors * @param testName name of the test @@ -127,6 +128,7 @@ class topolTest: public QObject * @param layer2 pointer to the second layer */ ErrorList checkOverlapWithLayer( double tolerance, QgsVectorLayer* layer1, QgsVectorLayer* layer2, bool isExtent ); + /** * Checks for self-intersections in the layer * @param tolerance not used @@ -136,6 +138,7 @@ class topolTest: public QObject ErrorList checkSelfIntersections( double tolerance, QgsVectorLayer* layer1, QgsVectorLayer* layer2, bool isExtent ); #if 0 //unused and broken + /** * Checks for features that are too close * @param tolerance allowed tolerance @@ -152,6 +155,7 @@ class topolTest: public QObject * @param layer2 pointer to the second layer */ ErrorList checkSegmentLength( double tolerance, QgsVectorLayer* layer1, QgsVectorLayer* layer2, bool isExtent ); + /** * Checks for dangling lines * @param tolerance allowed tolerance @@ -159,6 +163,7 @@ class topolTest: public QObject * @param layer2 not used */ ErrorList checkDanglingLines( double tolerance, QgsVectorLayer* layer1, QgsVectorLayer* layer2, bool isExtent ); + /** * Checks for points not covered by any segment * @param tolerance not used @@ -166,6 +171,7 @@ class topolTest: public QObject * @param layer2 pointer to the second layer */ ErrorList checkPointCoveredBySegment( double tolerance, QgsVectorLayer* layer1, QgsVectorLayer* layer2, bool isExtent ); + /** * Checks for invalid geometries * @param tolerance not used @@ -248,6 +254,7 @@ class topolTest: public QObject public slots: + /** * Checks for invalid geometries * @param tolerance not used @@ -292,6 +299,7 @@ class topolTest: public QObject bool testCancelled(); signals: + /** * Informs progress dialog about current status * @param value process status diff --git a/src/providers/db2/qgsdb2dataitems.h b/src/providers/db2/qgsdb2dataitems.h index 7325cbef84d4..bad6a857b78d 100644 --- a/src/providers/db2/qgsdb2dataitems.h +++ b/src/providers/db2/qgsdb2dataitems.h @@ -75,6 +75,7 @@ class QgsDb2ConnectionItem : public QgsDataCollectionItem const QString &authcfg, QString &connInfo, QString &errorMsg ); + /** * Fetch geometry column data from server and populate Browser Panel with * schemas and layers. @@ -98,6 +99,7 @@ class QgsDb2ConnectionItem : public QgsDataCollectionItem void addGeometryColumn( QgsDb2LayerProperty ); public slots: + /** * Refresh with saved connection data. */ diff --git a/src/providers/db2/qgsdb2featureiterator.cpp b/src/providers/db2/qgsdb2featureiterator.cpp index 394e841f192d..eb36ab32677e 100644 --- a/src/providers/db2/qgsdb2featureiterator.cpp +++ b/src/providers/db2/qgsdb2featureiterator.cpp @@ -327,6 +327,7 @@ bool QgsDb2FeatureIterator::fetchFeature( QgsFeature& feature ) else { // QgsDebugMsg( QString( "Field: %1; value: %2" ).arg( attrName, v.toString() ) ); + /** * CHAR and VARCHAR fields seem to get corrupted sometimes when directly * calling feature.setAttribute(..., v) with mQuery->value(i). Workaround diff --git a/src/providers/db2/qgsdb2newconnection.h b/src/providers/db2/qgsdb2newconnection.h index 8a5d18f602b0..e5389d7796f9 100644 --- a/src/providers/db2/qgsdb2newconnection.h +++ b/src/providers/db2/qgsdb2newconnection.h @@ -38,6 +38,7 @@ class QgsDb2NewConnection : public QDialog, private Ui::QgsDb2NewConnectionBase //! Tests the connection using the parameters supplied bool testConnection(); + /** * @brief List all databases found for the given server. */ diff --git a/src/providers/delimitedtext/qgsdelimitedtextfile.h b/src/providers/delimitedtext/qgsdelimitedtextfile.h index 26dbe0d50843..d9b94ba306af 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextfile.h +++ b/src/providers/delimitedtext/qgsdelimitedtextfile.h @@ -102,6 +102,7 @@ class QgsDelimitedTextFile : public QObject * @param filename the name of the file */ void setFileName( const QString& filename ); + /** Return the filename * @return filename the name of the file */ @@ -114,6 +115,7 @@ class QgsDelimitedTextFile : public QObject * @param encoding the encoding to use for the fileName() */ void setEncoding( const QString& encoding ); + /** Return the file encoding * @return encoding The file encoding */ @@ -123,6 +125,7 @@ class QgsDelimitedTextFile : public QObject * @param url The url from which the delimiter and delimiterType items are read */ bool setFromUrl( const QString& url ); + /** Decode the parser settings from a url * @param url The url from which the delimiter and delimiterType items are read */ @@ -141,6 +144,7 @@ class QgsDelimitedTextFile : public QObject * @param regexp A string defining the regular expression */ void setTypeRegexp( const QString& regexp ); + /** Set the parser to use a character type delimiter. * @param delim The field delimiter character set * @param quote The quote character, used to define quoted fields @@ -153,6 +157,7 @@ class QgsDelimitedTextFile : public QObject * @param skiplines The maximum lines to skip */ void setSkipLines( int skiplines ); + /** Return the number of header lines to skip * @return skiplines The maximum lines to skip */ @@ -165,6 +170,7 @@ class QgsDelimitedTextFile : public QObject * @param useheaders Field names will be read if true */ void setUseHeader( bool useheader = true ); + /** Return the option for reading field names from the first record * @return useheaders Field names will be read if true */ @@ -177,6 +183,7 @@ class QgsDelimitedTextFile : public QObject * @param useheaders Empty fields will be discarded if true */ void setDiscardEmptyFields( bool discardEmptyFields = true ); + /** Return the option for discarding empty fields * @return useheaders Empty fields will be discarded if true */ @@ -189,6 +196,7 @@ class QgsDelimitedTextFile : public QObject * @param trimFields Fields will be trimmed if true */ void setTrimFields( bool trimFields = true ); + /** Return the option for trimming empty fields * @return useheaders Empty fields will be trimmed if true */ @@ -202,6 +210,7 @@ class QgsDelimitedTextFile : public QObject * @param maxFields The maximum number of fields that will be read */ void setMaxFields( int maxFields ); + /** Return the maximum number of fields that will be read * @return maxFields The maximum number of fields that will be read */ @@ -261,6 +270,7 @@ class QgsDelimitedTextFile : public QObject * @return maxRecordNumber The maximum record number */ long recordCount() { return mMaxRecordNumber; } + /** Reset the file to reread from the beginning */ Status reset(); @@ -297,11 +307,13 @@ class QgsDelimitedTextFile : public QObject void setUseWatcher( bool useWatcher ); signals: + /** Signal sent when the file is updated by another process */ void fileUpdated(); public slots: + /** Slot used by watcher to notify of file updates */ void updateFile(); diff --git a/src/providers/delimitedtext/qgsdelimitedtextprovider.h b/src/providers/delimitedtext/qgsdelimitedtextprovider.h index 1645f255be01..08830ab05ddb 100644 --- a/src/providers/delimitedtext/qgsdelimitedtextprovider.h +++ b/src/providers/delimitedtext/qgsdelimitedtextprovider.h @@ -149,6 +149,7 @@ class QgsDelimitedTextProvider : public QgsVectorDataProvider bool isValid() const override; virtual QgsCoordinateReferenceSystem crs() const override; + /** * Set the subset string used to create a subset of features in * the layer. diff --git a/src/providers/gdal/qgsgdalprovider.cpp b/src/providers/gdal/qgsgdalprovider.cpp index c5c83fbf58c6..7e9c302847f7 100644 --- a/src/providers/gdal/qgsgdalprovider.cpp +++ b/src/providers/gdal/qgsgdalprovider.cpp @@ -1934,12 +1934,14 @@ QGISEXTERN QgsGdalProvider * classFactory( const QString *uri ) { return new QgsGdalProvider( *uri ); } + /** Required key function (used to map the plugin to a data store type) */ QGISEXTERN QString providerKey() { return PROVIDER_KEY; } + /** * Required description function */ @@ -1947,6 +1949,7 @@ QGISEXTERN QString description() { return PROVIDER_DESCRIPTION; } + /** * Required isProvider function. Used to determine if this shared library * is a data provider plugin @@ -1955,6 +1958,7 @@ QGISEXTERN bool isProvider() { return true; } + /** Convenience function for readily creating file filters. diff --git a/src/providers/gdal/qgsgdalprovider.h b/src/providers/gdal/qgsgdalprovider.h index 3a43b5879030..635912fe7595 100644 --- a/src/providers/gdal/qgsgdalprovider.h +++ b/src/providers/gdal/qgsgdalprovider.h @@ -58,6 +58,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase Q_OBJECT public: + /** * Constructor for the provider. * @@ -169,6 +170,7 @@ class QgsGdalProvider : public QgsRasterDataProvider, QgsGdalProviderBase /** Read band scale for raster value * @@note added in 2.3 */ double bandScale( int bandNo ) const override; + /** Read band offset for raster value * @@note added in 2.3 */ double bandOffset( int bandNo ) const override; diff --git a/src/providers/grass/qgsgrass.h b/src/providers/grass/qgsgrass.h index b67e722ebb1c..0bea493bd6c0 100644 --- a/src/providers/grass/qgsgrass.h +++ b/src/providers/grass/qgsgrass.h @@ -99,9 +99,11 @@ class GRASS_LIB_EXPORT QgsGrassObject QString mapsetPath() const { return mGisdbase + "/" + mLocation + "/" + mMapset; } QString name() const { return mName; } void setName( const QString& name ) { mName = name; } + /** Return full name (map@mapset) * @return full name or empty string if map name is empty */ QString fullName() const; + /** Parse full name in map@mapset form and set map and mapset. If mapset is not * specified, mapset is set to the current mapset. */ void setFullName( const QString& fullName ); @@ -186,6 +188,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject static void unlock(); //! Get info about the mode + /** QgsGrass may be running in active or passive mode. * Active mode means that GISRC is set up and GISRC file is available, * in that case default GISDBASE, LOCATION and MAPSET may be read by GetDefaul*() functions. @@ -335,6 +338,7 @@ class GRASS_LIB_EXPORT QgsGrass : public QObject static void initRegion( struct Cell_head *window ); //! Set region extent static void setRegion( struct Cell_head *window, const QgsRectangle &rect ); + /** Init region, set extent, rows and cols and adjust. * Returns error if adjustment failed. */ static QString setRegion( struct Cell_head *window, const QgsRectangle &rect, int rows, int cols ); diff --git a/src/providers/grass/qgsgrassfeatureiterator.h b/src/providers/grass/qgsgrassfeatureiterator.h index 205beb9e56bb..d817326a3ac9 100644 --- a/src/providers/grass/qgsgrassfeatureiterator.h +++ b/src/providers/grass/qgsgrassfeatureiterator.h @@ -100,6 +100,7 @@ class GRASS_LIB_EXPORT QgsGrassFeatureIterator : public QObject, public QgsAbstr static QVariant nonEditableValue( int layerNumber ); public slots: + /** Cancel iterator, iterator will be closed on next occasion, probably when next getFeature() gets called. * This function can be called directly from other threads (setting bool is atomic) */ void cancel(); diff --git a/src/providers/grass/qgsgrassprovider.h b/src/providers/grass/qgsgrassprovider.h index 07ce0521fa22..575710b45ce1 100644 --- a/src/providers/grass/qgsgrassprovider.h +++ b/src/providers/grass/qgsgrassprovider.h @@ -297,6 +297,7 @@ class GRASS_LIB_EXPORT QgsGrassProvider : public QgsVectorDataProvider int findNode( double x, double y, double threshold ); // TODO is it used? + /** Read attributes from DB * @param field * @param cat diff --git a/src/providers/grass/qgsgrassrasterprovider.h b/src/providers/grass/qgsgrassrasterprovider.h index e5eb82d14b3e..8eb0e7758abe 100644 --- a/src/providers/grass/qgsgrassrasterprovider.h +++ b/src/providers/grass/qgsgrassrasterprovider.h @@ -74,6 +74,7 @@ class GRASS_LIB_EXPORT QgsGrassRasterValue QTemporaryFile mGisrcFile; QProcess *mProcess; }; + /** \brief Data provider for GRASS raster layers. @@ -88,6 +89,7 @@ class GRASS_LIB_EXPORT QgsGrassRasterProvider : public QgsRasterDataProvider Q_OBJECT public: + /** * Constructor for the provider. * @@ -216,6 +218,7 @@ class GRASS_LIB_EXPORT QgsGrassRasterProvider : public QgsRasterDataProvider void clearLastError(); // append error if it is not empty void appendIfError( const QString &error ); + /** * Flag indicating if the layer data source is a valid layer */ diff --git a/src/providers/grass/qgsgrassvectormap.h b/src/providers/grass/qgsgrassvectormap.h index 4f707bb6502a..da0328598a5e 100644 --- a/src/providers/grass/qgsgrassvectormap.h +++ b/src/providers/grass/qgsgrassvectormap.h @@ -61,6 +61,7 @@ class GRASS_LIB_EXPORT QgsGrassVectorMap : public QObject int oldNumLines() const { return mOldNumLines; } // number of instances using this map int userCount() const; + /** Get current number of lines. * @return number of lines */ int numLines(); @@ -149,6 +150,7 @@ class GRASS_LIB_EXPORT QgsGrassVectorMap : public QObject void printDebug(); signals: + /** Ask all iterators to cancel iteration when possible. Connected to iterators with * Qt::DirectConnection (non blocking) */ void cancelIterators(); diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index 3f27aa5bef75..9e9f95a199ad 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -3086,12 +3086,14 @@ QGISEXTERN QgsOracleProvider * classFactory( const QString *uri ) { return new QgsOracleProvider( *uri ); } + /** Required key function (used to map the plugin to a data store type) */ QGISEXTERN QString providerKey() { return QSqlDatabase::isDriverAvailable( "QOCISPATIAL" ) ? ORACLE_KEY : 0; } + /** * Required description function */ @@ -3099,6 +3101,7 @@ QGISEXTERN QString description() { return QSqlDatabase::isDriverAvailable( "QOCISPATIAL" ) ? ORACLE_DESCRIPTION : 0; } + /** * Required isProvider function. Used to determine if this shared library * is a data provider plugin diff --git a/src/providers/oracle/qgsoracleprovider.h b/src/providers/oracle/qgsoracleprovider.h index 3ba0ad3a3da3..e75dfa4ad91b 100644 --- a/src/providers/oracle/qgsoracleprovider.h +++ b/src/providers/oracle/qgsoracleprovider.h @@ -322,14 +322,17 @@ class QgsOracleProvider : public QgsVectorDataProvider * Name of the table with no schema */ QString mTableName; + /** * Name of the table or subquery */ QString mQuery; + /** * Owner of the table */ QString mOwnerName; + /** * SQL statement used to limit the features retrieved */ diff --git a/src/providers/ows/qgsowsprovider.h b/src/providers/ows/qgsowsprovider.h index 514404a98305..33edc25fc29b 100644 --- a/src/providers/ows/qgsowsprovider.h +++ b/src/providers/ows/qgsowsprovider.h @@ -38,6 +38,7 @@ class QgsOwsProvider : public QgsDataProvider Q_OBJECT public: + /** * Constructor for the provider. * diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 5e8da6a94d66..dfe1bc486484 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -4084,12 +4084,14 @@ QGISEXTERN QgsPostgresProvider * classFactory( const QString *uri ) { return new QgsPostgresProvider( *uri ); } + /** Required key function (used to map the plugin to a data store type) */ QGISEXTERN QString providerKey() { return POSTGRES_KEY; } + /** * Required description function */ @@ -4097,6 +4099,7 @@ QGISEXTERN QString description() { return POSTGRES_DESCRIPTION; } + /** * Required isProvider function. Used to determine if this shared library * is a data provider plugin diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index 6245b20535d7..b9130c39db38 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -277,6 +277,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider virtual QgsAttrPalIndexNameHash palAttributeIndexNames() const override; signals: + /** * This is emitted whenever the worker thread has fully calculated the * PostGIS extents for this layer, and its event has been received by this @@ -310,6 +311,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider const QgsAttributeList &fetchAttributes ); QString geomParam( int offset ) const; + /** Get parametrized primary key clause * @param offset specifies offset to use for the pk value parameter * @param alias specifies an optional alias given to the subject table @@ -386,14 +388,17 @@ class QgsPostgresProvider : public QgsVectorDataProvider * Name of the table with no schema */ QString mTableName; + /** * Name of the table or subquery */ QString mQuery; + /** * Name of the schema */ QString mSchemaName; + /** * SQL statement used to limit the features retrieved */ diff --git a/src/providers/spatialite/qgsspatialiteconnection.h b/src/providers/spatialite/qgsspatialiteconnection.h index 7cdecef6525e..c465665791ff 100644 --- a/src/providers/spatialite/qgsspatialiteconnection.h +++ b/src/providers/spatialite/qgsspatialiteconnection.h @@ -91,6 +91,7 @@ class QgsSpatiaLiteConnection : public QObject #ifdef SPATIALITE_VERSION_GE_4_0_0 // only if libspatialite version is >= 4.0.0 + /** * Inserts information about the spatial tables into mTables * please note: this method is fully based on the Abstract Interface diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index f1dabd4e743c..990634971db1 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -256,6 +256,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider QgsSqliteHandle *mHandle; signals: + /** * This is emitted whenever the worker thread has fully calculated the * extents for this layer, and its event has been received by this diff --git a/src/providers/spatialite/qgsspatialitesourceselect.h b/src/providers/spatialite/qgsspatialitesourceselect.h index 6e7690aa4cd1..151761c63c8b 100644 --- a/src/providers/spatialite/qgsspatialitesourceselect.h +++ b/src/providers/spatialite/qgsspatialitesourceselect.h @@ -65,6 +65,7 @@ class QgsSpatiaLiteSourceSelect: public QDialog, private Ui::QgsDbSourceSelectBa void dbChanged(); public slots: + /** Connects to the database using the stored connection parameters. * Once connected, available layers are displayed. */ diff --git a/src/providers/spatialite/qgsspatialitetablemodel.h b/src/providers/spatialite/qgsspatialitetablemodel.h index 495c713a7d37..47b4b8eb28b8 100644 --- a/src/providers/spatialite/qgsspatialitetablemodel.h +++ b/src/providers/spatialite/qgsspatialitetablemodel.h @@ -32,6 +32,7 @@ class QgsSpatiaLiteTableModel: public QStandardItemModel void addTableEntry( const QString& type, const QString& tableName, const QString& geometryColName, const QString& sql ); //! Sets an sql statement that belongs to a cell specified by a model index void setSql( const QModelIndex& index, const QString& sql ); + /** Sets one or more geometry types to a row. In case of several types, additional rows are inserted. This is for tables where the type is dectected later by thread*/ void setGeometryTypesForTable( const QString & table, const QString & attribute, const QString & type ); diff --git a/src/providers/wcs/qgswcscapabilities.h b/src/providers/wcs/qgswcscapabilities.h index 4b350fad34f9..b2d3306f8d58 100644 --- a/src/providers/wcs/qgswcscapabilities.h +++ b/src/providers/wcs/qgswcscapabilities.h @@ -89,6 +89,7 @@ class QgsWcsCapabilities : public QObject Q_OBJECT public: + /** * Constructor for the provider. * @@ -246,6 +247,7 @@ class QgsWcsCapabilities : public QObject QList parseInts( const QString &text ); QList parseDoubles( const QString &text ); QString crsUrnToAuthId( const QString &text ); + /** * \brief Retrieve and parse the (cached) Capabilities document from the server * diff --git a/src/providers/wcs/qgswcsprovider.h b/src/providers/wcs/qgswcsprovider.h index 75447d0f1fc2..d99e226380c9 100644 --- a/src/providers/wcs/qgswcsprovider.h +++ b/src/providers/wcs/qgswcsprovider.h @@ -106,6 +106,7 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase Q_OBJECT public: + /** * Constructor for the provider. * @@ -140,6 +141,7 @@ class QgsWcsProvider : public QgsRasterDataProvider, QgsGdalProviderBase void setCoverageCrs( QString const & crs ); // TODO: Document this better. + /** \brief Renders the layer as an image * * \return A QImage - if the attempt to retrieve data for the draw was unsuccessful, returns 0 diff --git a/src/providers/wfs/qgswfsconnection.h b/src/providers/wfs/qgswfsconnection.h index 68c41195f527..95b7c2c2d39b 100644 --- a/src/providers/wfs/qgswfsconnection.h +++ b/src/providers/wfs/qgswfsconnection.h @@ -21,6 +21,7 @@ class QgsWfsConnection : public QgsOwsConnection { public: + /** * Constructor * @param theConnName connection name diff --git a/src/providers/wfs/qgswfsfeatureiterator.h b/src/providers/wfs/qgswfsfeatureiterator.h index ff88e54dbb75..8f0a22d9d73e 100644 --- a/src/providers/wfs/qgswfsfeatureiterator.h +++ b/src/providers/wfs/qgswfsfeatureiterator.h @@ -141,6 +141,7 @@ class QgsWFSFeatureDownloader: public QgsWfsRequest bool mStop; //! Progress dialog QProgressDialog* mProgressDialog; + /** If the progress dialog should be shown immediately, or if it should be let to QProgressDialog logic to decide when to show it */ bool mProgressDialogShowImmediately; diff --git a/src/providers/wfs/qgswfsprovider.h b/src/providers/wfs/qgswfsprovider.h index 3b1f29be50a9..68f155b21aaf 100644 --- a/src/providers/wfs/qgswfsprovider.h +++ b/src/providers/wfs/qgswfsprovider.h @@ -103,6 +103,7 @@ class QgsWFSProvider : public QgsVectorDataProvider const QString processSQLWarningMsg() const { return mProcessSQLWarningMsg; } //Editing operations + /** * Adds a list of features * @return true in case of success and false in case of failure @@ -139,6 +140,7 @@ class QgsWFSProvider : public QgsVectorDataProvider virtual QMap metadata(); public slots: + /** Reloads the data from the source. Needs to be implemented by providers with data caches to synchronize with changes in the data source*/ virtual void reloadData() override; diff --git a/src/providers/wfs/qgswfssourceselect.h b/src/providers/wfs/qgswfssourceselect.h index e9c8849c6e85..7348c5b82b90 100644 --- a/src/providers/wfs/qgswfssourceselect.h +++ b/src/providers/wfs/qgswfssourceselect.h @@ -57,6 +57,7 @@ class QgsWFSSourceSelect: public QDialog, private Ui::QgsWFSSourceSelectBase private: QgsWFSSourceSelect(); //default constructor is forbidden QgsGenericProjectionSelector* mProjectionSelector; + /** Stores the available CRS for a server connections. The first string is the typename, the corresponding list stores the CRS for the typename in the form 'EPSG:XXXX'*/ diff --git a/src/providers/wms/qgswmsprovider.cpp b/src/providers/wms/qgswmsprovider.cpp index 679df2cdee62..bf6d7e4b7dd8 100644 --- a/src/providers/wms/qgswmsprovider.cpp +++ b/src/providers/wms/qgswmsprovider.cpp @@ -3499,12 +3499,14 @@ QGISEXTERN QgsWmsProvider * classFactory( const QString *uri ) { return new QgsWmsProvider( *uri ); } + /** Required key function (used to map the plugin to a data store type) */ QGISEXTERN QString providerKey() { return WMS_KEY; } + /** * Required description function */ @@ -3512,6 +3514,7 @@ QGISEXTERN QString description() { return WMS_DESCRIPTION; } + /** * Required isProvider function. Used to determine if this shared library * is a data provider plugin diff --git a/src/providers/wms/qgswmsprovider.h b/src/providers/wms/qgswmsprovider.h index 877d6c34ea7b..9a5f51ee0677 100644 --- a/src/providers/wms/qgswmsprovider.h +++ b/src/providers/wms/qgswmsprovider.h @@ -113,6 +113,7 @@ class QgsWmsProvider : public QgsRasterDataProvider Q_OBJECT public: + /** * Constructor for the provider. * @@ -148,6 +149,7 @@ class QgsWmsProvider : public QgsRasterDataProvider void setConnectionName( QString const & connName ); // TODO: Document this better. + /** \brief Renders the layer as an image * * \return A QImage - if the attempt to retrieve data for the draw was unsuccessful, returns 0 @@ -171,6 +173,7 @@ class QgsWmsProvider : public QgsRasterDataProvider bool isValid() const override; #if 0 + /** Returns true if layer has tile set profiles */ virtual bool hasTiles() const; @@ -631,6 +634,7 @@ class QgsWmsTiledImageDownloadHandler : public QObject void cancelled(); protected: + /** * \brief Relaunch tile request cloning previous request parameters and managing max repeat * diff --git a/src/server/qgshttprequesthandler.h b/src/server/qgshttprequesthandler.h index 8aad80af8a2e..a86345507b20 100644 --- a/src/server/qgshttprequesthandler.h +++ b/src/server/qgshttprequesthandler.h @@ -71,6 +71,7 @@ class QgsHttpRequestHandler: public QgsRequestHandler virtual void sendHeaders() override; virtual void sendBody() override; void setHttpResponse( QByteArray *ba, const QString &format ); + /** Converts format to official mimetype (e.g. 'jpg' to 'image/jpeg') @return mime string (or the entered string if not found)*/ QString formatToMimeType( const QString& format ) const; diff --git a/src/server/qgshttptransaction.h b/src/server/qgshttptransaction.h index 412a885229c2..c4a69cb0d7a7 100644 --- a/src/server/qgshttptransaction.h +++ b/src/server/qgshttptransaction.h @@ -43,6 +43,7 @@ class QgsHttpTransaction : public QObject Q_OBJECT public: + /** * Constructor. */ diff --git a/src/server/qgsmaprenderer.h b/src/server/qgsmaprenderer.h index a243e7c2a5d9..8743122fd4ad 100644 --- a/src/server/qgsmaprenderer.h +++ b/src/server/qgsmaprenderer.h @@ -99,6 +99,7 @@ class SERVER_EXPORT QgsMapRenderer : public QObject //! Scale denominator double scale() const { return mScale; } + /** Sets scale for scale based visibility. Normally, the scale is calculated automatically. This function is only used to force a preview scale (e.g. for print composer)*/ void setScale( double scale ) {mScale = scale;} @@ -336,6 +337,7 @@ class SERVER_EXPORT QgsMapRenderer : public QObject //! current extent to be drawn QgsRectangle mExtent; // + /** Last extent to we drew so we know if we can used layer render caching or not. Note there are no accessors for this as it is intended to internal diff --git a/src/server/qgsmslayerbuilder.h b/src/server/qgsmslayerbuilder.h index 98fbe97138a0..1b7f82b10c7f 100644 --- a/src/server/qgsmslayerbuilder.h +++ b/src/server/qgsmslayerbuilder.h @@ -45,10 +45,12 @@ class QgsMSLayerBuilder protected: //! Tries to create a suitable layer name from a URL. virtual QString layerNameFromUri( const QString& uri ) const; + /** Helper function that creates a new temporary file with random name under /tmp/qgis_wms_serv/ and returns the path of the file (Unix). On Windows, it is created in the current working directory and returns the filename only*/ QString createTempFile() const; + /** Resets the former symbology of a raster layer. This is important for single band layers (e.g. dems) coming from the cash*/ void clearRasterSymbology( QgsRasterLayer* rl ) const; diff --git a/src/server/qgsmslayercache.h b/src/server/qgsmslayercache.h index d00775feed37..2556e17f3421 100644 --- a/src/server/qgsmslayercache.h +++ b/src/server/qgsmslayercache.h @@ -62,6 +62,7 @@ class QgsMSLayerCache: public QObject @param configFile path of the config file (to invalidate entries if file changes). Can be empty (e.g. layers from sld) @param tempFiles some layers have temporary files. The cash makes sure they are removed when removing the layer from the cash*/ void insertLayer( const QString& url, const QString& layerName, QgsMapLayer* layer, const QString& configFile = QString(), const QList& tempFiles = QList() ); + /** Searches for the layer with the given url. @return a pointer to the layer or 0 if no such layer*/ QgsMapLayer* searchLayer( const QString& url, const QString& layerName, const QString& configFile = QString() ); @@ -79,6 +80,7 @@ class QgsMSLayerCache: public QObject protected: //! Protected singleton constructor QgsMSLayerCache(); + /** Goes through the list and removes entries and layers depending on their time stamps and the number of other layers*/ @@ -89,6 +91,7 @@ class QgsMSLayerCache: public QObject void freeEntryRessources( QgsMSLayerCacheEntry& entry ); private: + /** Cash entries with pair url/layer name as a key. The layer name is necessary for cases where the same url is used several time in a request. It ensures that different layer instances are created for different layer names*/ diff --git a/src/server/qgsmsutils.h b/src/server/qgsmsutils.h index 326e35e87600..c0fbc36d1549 100644 --- a/src/server/qgsmsutils.h +++ b/src/server/qgsmsutils.h @@ -20,6 +20,7 @@ //! Some utility functions that may be included from everywhere in the code namespace QgsMSUtils { + /** Creates a ramdom filename for a temporary file. This function also creates the directory to store the temporary files if it does not already exist. The directory is /tmp/qgis_map_serv/ under linux or the current working directory on windows*/ diff --git a/src/server/qgsrequesthandler.h b/src/server/qgsrequesthandler.h index ecc50eeb2e1f..445ef101cafd 100644 --- a/src/server/qgsrequesthandler.h +++ b/src/server/qgsrequesthandler.h @@ -55,6 +55,7 @@ class QgsRequestHandler , mException( nullptr ) {} virtual ~QgsRequestHandler() {} + /** Parses the input and creates a request neutral Parameter/Value map * @note not available in Python bindings */ @@ -152,6 +153,7 @@ class QgsRequestHandler bool headersSent() { return mHeadersSent; } #ifdef HAVE_SERVER_PYTHON_PLUGINS + /** Allow core services to call plugin hooks through sendResponse() * @note not available in Python bindings */ @@ -179,10 +181,12 @@ class QgsRequestHandler QString mInfoFormat; QgsMapServiceException* mException; // Stores the exception QMap mParameterMap; + /** Response headers. They can be empty, in this case headers are automatically generated from the content mFormat */ QMap mHeaders; // TODO: if HAVE_SERVER_PYTHON + /** Response output buffers, used by Python bindings to return * output instead of printing with fcgi printf */ // QByteArray mResponseHeader; diff --git a/src/server/qgsserver.h b/src/server/qgsserver.h index 022ccc8d9130..a94f8ba8e7ee 100644 --- a/src/server/qgsserver.h +++ b/src/server/qgsserver.h @@ -47,6 +47,7 @@ class SERVER_EXPORT QgsServer { public: + /** Creates the server instance * @param captureOutput set to false for stdout output (FCGI) */ diff --git a/src/server/qgsserverfilter.h b/src/server/qgsserverfilter.h index 415937aac166..e2f5f5836fc2 100644 --- a/src/server/qgsserverfilter.h +++ b/src/server/qgsserverfilter.h @@ -50,14 +50,17 @@ class SERVER_EXPORT QgsServerFilter virtual ~QgsServerFilter(); //! Return the QgsServerInterface instance QgsServerInterface* serverInterface() { return mServerInterface; } + /** Method called when the QgsRequestHandler is ready and populated with * parameters, just before entering the main switch for core services.*/ virtual void requestReady(); + /** Method called when the QgsRequestHandler processing has done and * the response is ready, just after the main switch for core services * and before final sending response to FCGI stdout. */ virtual void responseComplete(); + /** Method called when the QgsRequestHandler sends its data to FCGI stdout. * This normally occours at the end of core services processing just after * the responseComplete() plugin hook. For streaming services (like WFS on diff --git a/src/server/qgsserverinterfaceimpl.h b/src/server/qgsserverinterfaceimpl.h index a799f35563e1..68a3528c7e08 100644 --- a/src/server/qgsserverinterfaceimpl.h +++ b/src/server/qgsserverinterfaceimpl.h @@ -53,6 +53,7 @@ class QgsServerInterfaceImpl : public QgsServerInterface QgsServerFiltersMap filters() override { return mFilters; } //! Register an access control filter void registerAccessControl( QgsAccessControlFilter *accessControl, int priority = 0 ) override; + /** Gets the helper over all the registered access control filters * @return the access control helper */ diff --git a/src/server/qgsserverplugins.h b/src/server/qgsserverplugins.h index 5e81edef2588..64786d52b30e 100644 --- a/src/server/qgsserverplugins.h +++ b/src/server/qgsserverplugins.h @@ -31,6 +31,7 @@ class SERVER_EXPORT QgsServerPlugins { public: explicit QgsServerPlugins(); + /** * Initialise the python plugins * @param interface QgsServerInterface diff --git a/src/server/qgssldconfigparser.h b/src/server/qgssldconfigparser.h index 0033d2a8123e..137100ebfe0f 100644 --- a/src/server/qgssldconfigparser.h +++ b/src/server/qgssldconfigparser.h @@ -28,6 +28,7 @@ class QTemporaryFile; class QgsSLDConfigParser : public QgsWmsConfigParser { public: + /** Constructor takes a dom document as argument. The class takes ownership of the document and deletes it in the destructor @param doc SLD document @param parameterMap map containing the wms request parameters*/ diff --git a/src/server/qgswmsserver.h b/src/server/qgswmsserver.h index 5268c090a1fc..3c95ae9926e0 100644 --- a/src/server/qgswmsserver.h +++ b/src/server/qgswmsserver.h @@ -61,6 +61,7 @@ independent from any server side technology*/ class QgsWmsServer: public QgsOWSServer { public: + /** Constructor. Does _NOT_ take ownership of QgsConfigParser, QgsCapabilitiesCache and QgsMapRenderer*/ QgsWmsServer( @@ -84,6 +85,7 @@ class QgsWmsServer: public QgsOWSServer QDomDocument getCapabilities( const QString &version = "1.3.0", bool fullProjectInformation = false ); QDomDocument getContext(); + /** Returns the map legend as an image (or a null pointer in case of error). The caller takes ownership of the image object*/ QImage* getLegendGraphics(); @@ -135,19 +137,23 @@ class QgsWmsServer: public QgsOWSServer @param height image height (or -1 if height should be taken from HEIGHT wms parameter) @return 0 in case of error*/ QImage* createImage( int width = -1, int height = -1 ) const; + /** Configures mMapRenderer to the parameters HEIGHT, WIDTH, BBOX, CRS. @param paintDevice the device that is used for painting (for dpi) @return 0 in case of success*/ int configureMapRender( const QPaintDevice* paintDevice ) const; + /** Reads the layers and style lists from the parameters LAYERS and STYLES @return 0 in case of success*/ int readLayersAndStyles( QStringList& layersList, QStringList& stylesList ) const; + /** If the parameter SLD exists, mSLDParser is configured appropriately. The lists are set to the layer and style names according to the SLD @return 0 in case of success*/ int initializeSLDParser( QStringList& layersList, QStringList& stylesList ); static bool infoPointToMapCoordinates( int i, int j, QgsPoint* infoPoint, QgsMapRenderer* mapRenderer ); + /** Appends feature info xml for the layer to the layer element of the feature info dom document @param featureBBox the bounding box of the selected features in output CRS @return 0 in case of success*/ @@ -196,6 +202,7 @@ class QgsWmsServer: public QgsOWSServer void applyRequestedLayerFilters( const QStringList& layerList, QHash& originalFilters ) const; #ifdef HAVE_SERVER_PYTHON_PLUGINS + /** Apply filter strings from the access control to the layers. * @param layerList layers to filter * @param originalLayerFilters the original layers filter dictionary diff --git a/tests/src/core/testqgscoordinatereferencesystem.cpp b/tests/src/core/testqgscoordinatereferencesystem.cpp index 4b586254635a..67e6e73e3d4f 100644 --- a/tests/src/core/testqgscoordinatereferencesystem.cpp +++ b/tests/src/core/testqgscoordinatereferencesystem.cpp @@ -608,6 +608,7 @@ void TestQgsCoordinateReferenceSystem::setCustomSrsValidation() } void TestQgsCoordinateReferenceSystem::customSrsValidation() { + /** * @todo implement this test "QgsCoordinateReferenceSystem myCrs; From 02ea2d77036e929c478600172e564727598f11f3 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 09:05:47 +1000 Subject: [PATCH 664/897] Fix typos --- doc/api_break.dox | 2 +- python/analysis/raster/qgsrastercalculator.sip | 2 +- python/analysis/vector/qgsgeometrysnapper.sip | 2 +- python/core/composer/qgscomposernodesitem.sip | 2 +- python/core/qgsvectorfilewriter.sip | 2 +- python/core/symbology-ng/qgsrendererregistry.sip | 2 +- scripts/spelling.dat | 3 +++ src/analysis/raster/qgsrastercalculator.h | 2 +- src/analysis/vector/qgsgeometrysnapper.h | 2 +- src/app/qgsmaptoolsimplify.h | 2 +- src/core/composer/qgscomposernodesitem.h | 2 +- src/core/gps/qgsqtlocationconnection.cpp | 2 +- src/core/qgsvectorfilewriter.h | 2 +- src/core/symbology-ng/qgsrendererregistry.h | 2 +- .../evis/databaseconnection/evisdatabaseconnectiongui.h | 2 +- src/ui/qgsorganizetablecolumnsdialog.ui | 2 +- 16 files changed, 18 insertions(+), 15 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index f4244811bf52..939bdcbb8c6a 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -21,7 +21,7 @@ This page tries to maintain a list with incompatible changes that happened in pr QGIS 3.0 {#qgis_api_break_3_0} ======== -Version 3.0 brings changes to many underlying dependancies which QGIS is built upon. Any existing PyQGIS code will +Version 3.0 brings changes to many underlying dependencies which QGIS is built upon. Any existing PyQGIS code will need to be updated to address the changes made within these libraries. Python 3.0 diff --git a/python/analysis/raster/qgsrastercalculator.sip b/python/analysis/raster/qgsrastercalculator.sip index 6bb2f39d6682..53cf17cebac3 100644 --- a/python/analysis/raster/qgsrastercalculator.sip +++ b/python/analysis/raster/qgsrastercalculator.sip @@ -21,7 +21,7 @@ class QgsRasterCalculator //! Result of the calculation enum Result { - Success, /*!< Calculation sucessful */ + Success, /*!< Calculation successful */ CreateOutputError, /*!< Error creating output data file */ InputLayerError, /*!< Error reading input layer */ Cancelled, /*!< User cancelled calculation */ diff --git a/python/analysis/vector/qgsgeometrysnapper.sip b/python/analysis/vector/qgsgeometrysnapper.sip index ac0b59338365..e7d8e5757456 100644 --- a/python/analysis/vector/qgsgeometrysnapper.sip +++ b/python/analysis/vector/qgsgeometrysnapper.sip @@ -2,7 +2,7 @@ * \class QgsGeometrySnapper * \ingroup analysis * QgsGeometrySnapper allows a geometry to be snapped to the geometries within a - * different refence layer. Vertices in the geometries will be modified to + * different reference layer. Vertices in the geometries will be modified to * match the reference layer features within a specified snap tolerance. * \note added in QGIS 3.0 */ diff --git a/python/core/composer/qgscomposernodesitem.sip b/python/core/composer/qgscomposernodesitem.sip index 922a1a4e95a0..4b27bebada97 100644 --- a/python/core/composer/qgscomposernodesitem.sip +++ b/python/core/composer/qgscomposernodesitem.sip @@ -72,7 +72,7 @@ class QgsComposerNodesItem: QgsComposerItem */ int selectedNode(); - /** Unselect a node. + /** Deselect a node. */ void unselectNode(); diff --git a/python/core/qgsvectorfilewriter.sip b/python/core/qgsvectorfilewriter.sip index 024ca1ed376e..27825ec8c321 100644 --- a/python/core/qgsvectorfilewriter.sip +++ b/python/core/qgsvectorfilewriter.sip @@ -414,7 +414,7 @@ class QgsVectorFileWriter static QStringList defaultLayerOptions( const QString& driverName ); /** - * Return edition capabilites for an existing dataset name. + * Return edition capabilities for an existing dataset name. * @note added in QGIS 3.0 */ static EditionCapabilities editionCapabilities( const QString& datasetName ); diff --git a/python/core/symbology-ng/qgsrendererregistry.sip b/python/core/symbology-ng/qgsrendererregistry.sip index 0b27814905f1..3e4c41f28483 100644 --- a/python/core/symbology-ng/qgsrendererregistry.sip +++ b/python/core/symbology-ng/qgsrendererregistry.sip @@ -111,7 +111,7 @@ class QgsRendererRegistry //! Removes a renderer from registry. //! @param rendererName name of renderer to remove from registry - //! @returns true if renderer was sucessfully removed, or false if matching + //! @returns true if renderer was successfully removed, or false if matching //! renderer could not be found bool removeRenderer( const QString& rendererName ); diff --git a/scripts/spelling.dat b/scripts/spelling.dat index 04b07e043adc..6e7135f8fd74 100644 --- a/scripts/spelling.dat +++ b/scripts/spelling.dat @@ -192,6 +192,7 @@ extention:extension failuer:failure familar:familiar fatser:faster +feture:feature fetaures:features forse:force fortan:fortran @@ -436,6 +437,8 @@ subdirectoires:subdirectories succesful:successful succesfully:successfully sucess:success +sucessful:successful +sucessfully:successfully superceded:superseded superflous:superfluous superseeded:superseded diff --git a/src/analysis/raster/qgsrastercalculator.h b/src/analysis/raster/qgsrastercalculator.h index 3b9b23294135..27dc82696b28 100644 --- a/src/analysis/raster/qgsrastercalculator.h +++ b/src/analysis/raster/qgsrastercalculator.h @@ -44,7 +44,7 @@ class ANALYSIS_EXPORT QgsRasterCalculator //! Result of the calculation enum Result { - Success = 0, //!< Calculation sucessful + Success = 0, //!< Calculation successful CreateOutputError = 1, //!< Error creating output data file InputLayerError = 2, //!< Error reading input layer Cancelled = 3, //!< User cancelled calculation diff --git a/src/analysis/vector/qgsgeometrysnapper.h b/src/analysis/vector/qgsgeometrysnapper.h index ad3807488b2f..26926576533a 100644 --- a/src/analysis/vector/qgsgeometrysnapper.h +++ b/src/analysis/vector/qgsgeometrysnapper.h @@ -30,7 +30,7 @@ class QgsVectorLayer; * \class QgsGeometrySnapper * \ingroup analysis * QgsGeometrySnapper allows a geometry to be snapped to the geometries within a - * different refence layer. Vertices in the geometries will be modified to + * different reference layer. Vertices in the geometries will be modified to * match the reference layer features within a specified snap tolerance. * \note added in QGIS 3.0 */ diff --git a/src/app/qgsmaptoolsimplify.h b/src/app/qgsmaptoolsimplify.h index 64624b148cf0..d3b83c6382ae 100644 --- a/src/app/qgsmaptoolsimplify.h +++ b/src/app/qgsmaptoolsimplify.h @@ -76,7 +76,7 @@ class APP_EXPORT QgsMapToolSimplify: public QgsMapToolEdit void setToleranceUnits( int units ); - //! Slot to store feture after simplification + //! Slot to store feature after simplification void storeSimplified(); void clearSelection(); diff --git a/src/core/composer/qgscomposernodesitem.h b/src/core/composer/qgscomposernodesitem.h index 527099be9104..5f16b4f290be 100644 --- a/src/core/composer/qgscomposernodesitem.h +++ b/src/core/composer/qgscomposernodesitem.h @@ -111,7 +111,7 @@ class CORE_EXPORT QgsComposerNodesItem: public QgsComposerItem */ int selectedNode() { return mSelectedNode; } - /** Unselect a node. + /** Deselect a node. */ void unselectNode() { mSelectedNode = -1; } diff --git a/src/core/gps/qgsqtlocationconnection.cpp b/src/core/gps/qgsqtlocationconnection.cpp index 1d8f46e190f0..2db10191dd18 100644 --- a/src/core/gps/qgsqtlocationconnection.cpp +++ b/src/core/gps/qgsqtlocationconnection.cpp @@ -40,7 +40,7 @@ QgsQtLocationConnection::~QgsQtLocationConnection() } //Needed to make connection detectable (half HACK) -//this signals that the device has started the GPS sucessfully, +//this signals that the device has started the GPS successfully, //not that it has a fix yet. void QgsQtLocationConnection::broadcastConnectionAvailable() { diff --git a/src/core/qgsvectorfilewriter.h b/src/core/qgsvectorfilewriter.h index 0780a15f3606..4b039ac1d911 100644 --- a/src/core/qgsvectorfilewriter.h +++ b/src/core/qgsvectorfilewriter.h @@ -491,7 +491,7 @@ class CORE_EXPORT QgsVectorFileWriter static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ); /** - * Return edition capabilites for an existing dataset name. + * Return edition capabilities for an existing dataset name. * @note added in QGIS 3.0 */ static EditionCapabilities editionCapabilities( const QString& datasetName ); diff --git a/src/core/symbology-ng/qgsrendererregistry.h b/src/core/symbology-ng/qgsrendererregistry.h index dd3c4c7d9e11..72a6a41a2f26 100644 --- a/src/core/symbology-ng/qgsrendererregistry.h +++ b/src/core/symbology-ng/qgsrendererregistry.h @@ -193,7 +193,7 @@ class CORE_EXPORT QgsRendererRegistry //! Removes a renderer from registry. //! @param rendererName name of renderer to remove from registry - //! @returns true if renderer was sucessfully removed, or false if matching + //! @returns true if renderer was successfully removed, or false if matching //! renderer could not be found bool removeRenderer( const QString& rendererName ); diff --git a/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h b/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h index 34512fc93c5f..8f43a6792555 100644 --- a/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h +++ b/src/plugins/evis/databaseconnection/evisdatabaseconnectiongui.h @@ -40,7 +40,7 @@ * \class eVisDatabaseConnectionGui * \brief GUI class for database connections * This class provides the GUI component for setting up a database connection and making a sql query. -* This class effectively provides access to a wide variety of database types. Upon a sucessful query, +* This class effectively provides access to a wide variety of database types. Upon a successful query, * the results are stored in a tabdelimited file the loaded into qgis using the demlimitedtext data provider */ class eVisDatabaseConnectionGui : public QDialog, private Ui::eVisDatabaseConnectionGuiBase diff --git a/src/ui/qgsorganizetablecolumnsdialog.ui b/src/ui/qgsorganizetablecolumnsdialog.ui index 39f7b5227e72..03c13b5a53b7 100644 --- a/src/ui/qgsorganizetablecolumnsdialog.ui +++ b/src/ui/qgsorganizetablecolumnsdialog.ui @@ -44,7 +44,7 @@ - Unselect all + Deselect all From 35a29d85c008c93f718d6c7678c294ea1cc77fb2 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 09:08:09 +1000 Subject: [PATCH 665/897] Add missing API break documentation --- doc/api_break.dox | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 939bdcbb8c6a..67778e8faa7c 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1447,7 +1447,10 @@ capabilities have been removed, as they were unused and had no effect. - capabilities() now returns a typesafe QgsVectorDataProvider::Capabilities object, not an integer. - convertToProviderType() now takes a geometry reference, not a pointer. - geometryType() has been renamed to wkbType() to be in line with QgsVectorLayer - +- The behaviour of defaultValue() has changed from 2.x. In 2.x, defaultValue() would return a SQL +clause fragment which must be evaluated by the provider in order to calculate the default value. In +QGIS 3.0 defaultValue() only returns literal, constant defaultValues. A new method defaultValueClause +has been added which returns the SQL clause fragments which must be evaluated by the provider itself. QgsVectorLayer {#qgis_api_break_3_0_QgsVectorLayer} From 1a4f8f59f1b26fc88e0686b51646723a4243f9ba Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 09:30:52 +1000 Subject: [PATCH 666/897] [processing] When searching in toolbox, ignore order of words Eg, allows you to search "line merge" and find the "Merge lines" algorithm. Should make it easier for users who don't know the exact name to find algorithms. --- python/plugins/processing/gui/ProcessingToolbox.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/gui/ProcessingToolbox.py b/python/plugins/processing/gui/ProcessingToolbox.py index a691323fb6af..4280b7fb7888 100644 --- a/python/plugins/processing/gui/ProcessingToolbox.py +++ b/python/plugins/processing/gui/ProcessingToolbox.py @@ -108,7 +108,7 @@ def textChanged(self): text = self.searchBox.text().strip(' ').lower() for item in list(self.disabledProviderItems.values()): item.setHidden(True) - self._filterItem(self.algorithmTree.invisibleRootItem(), text) + self._filterItem(self.algorithmTree.invisibleRootItem(), [t for t in text.split(' ') if t]) if text: self.algorithmTree.expandAll() self.disabledWithMatchingAlgs = [] @@ -137,10 +137,15 @@ def _filterItem(self, item, text): item.setHidden(not show) return show elif isinstance(item, (TreeAlgorithmItem, TreeActionItem)): - # hide = bool(text) and (text not in item.text(0).lower()) - hide = bool(text) and not any(text in t for t in [item.text(0).lower(), item.data(0, Qt.UserRole).lower()]) + # hide if every part of text is not contained somewhere in either the item text or item user role + item_text = [item.text(0).lower(), item.data(0, Qt.UserRole).lower()] if isinstance(item, TreeAlgorithmItem): - hide = hide and (text not in item.alg.commandLineName()) + item_text.append(item.alg.commandLineName()) + + hide = bool(text) and not all( + any(part in t for t in item_text) + for part in text) + item.setHidden(hide) return not hide else: From 3550cc99a6a5e9e5ef025925c0bfc823aea44d5e Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 09:38:22 +1000 Subject: [PATCH 667/897] [processing] Allow algorithms to specify tags Tags are used while searching in the toolbox. This should help with finding algorithms when the exact name is not known, eg you could search for "envelope" or "bounds" and find the 'Polygon from Layer Extent' algorithm. At the moment it's quite hard to discover algorithms which exist when you don't know what their called and have to instead search for every possible naming variant which could exist... --- .../plugins/processing/algs/qgis/ExtentFromLayer.py | 1 + python/plugins/processing/algs/qgis/MergeLines.py | 1 + python/plugins/processing/core/GeoAlgorithm.py | 3 +++ python/plugins/processing/gui/ProcessingToolbox.py | 2 ++ python/plugins/processing/modeler/ModelerDialog.py | 11 ++++++++++- 5 files changed, 17 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/ExtentFromLayer.py b/python/plugins/processing/algs/qgis/ExtentFromLayer.py index ea8ed2587918..6238e43ea2b7 100644 --- a/python/plugins/processing/algs/qgis/ExtentFromLayer.py +++ b/python/plugins/processing/algs/qgis/ExtentFromLayer.py @@ -54,6 +54,7 @@ def getIcon(self): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Polygon from layer extent') self.group, self.i18n_group = self.trAlgorithm('Vector general tools') + self.tags = self.tr('extent,envelope,bounds,bounding,boundary,layer') self.addParameter(ParameterVector(self.INPUT_LAYER, self.tr('Input layer'))) diff --git a/python/plugins/processing/algs/qgis/MergeLines.py b/python/plugins/processing/algs/qgis/MergeLines.py index 46edf6889540..173c11a46faa 100644 --- a/python/plugins/processing/algs/qgis/MergeLines.py +++ b/python/plugins/processing/algs/qgis/MergeLines.py @@ -51,6 +51,7 @@ def getIcon(self): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Merge lines') self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + self.tags = self.tr('line,merge,join,parts') self.addParameter(ParameterVector(self.INPUT_LAYER, self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE])) diff --git a/python/plugins/processing/core/GeoAlgorithm.py b/python/plugins/processing/core/GeoAlgorithm.py index c32f906bdf18..f7bd23604902 100644 --- a/python/plugins/processing/core/GeoAlgorithm.py +++ b/python/plugins/processing/core/GeoAlgorithm.py @@ -64,6 +64,9 @@ def __init__(self): self.name, self.i18n_name = '', '' self.group, self.i18n_group = '', '' + # Tags + self.tags = '' + # The crs taken from input layers (if possible), and used when # loading output layers self.crs = None diff --git a/python/plugins/processing/gui/ProcessingToolbox.py b/python/plugins/processing/gui/ProcessingToolbox.py index 4280b7fb7888..897823a36b83 100644 --- a/python/plugins/processing/gui/ProcessingToolbox.py +++ b/python/plugins/processing/gui/ProcessingToolbox.py @@ -141,6 +141,7 @@ def _filterItem(self, item, text): item_text = [item.text(0).lower(), item.data(0, Qt.UserRole).lower()] if isinstance(item, TreeAlgorithmItem): item_text.append(item.alg.commandLineName()) + item_text.extend(item.data(0, Qt.UserRole + 1)) hide = bool(text) and not all( any(part in t for t in item_text) @@ -355,6 +356,7 @@ def __init__(self, alg): self.setToolTip(0, name) self.setText(0, name) self.setData(0, Qt.UserRole, nameEn) + self.setData(0, Qt.UserRole + 1, alg.tags.split(',')) class TreeActionItem(QTreeWidgetItem): diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index fe08c0c16c2b..5de22a596869 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -472,6 +472,7 @@ def fillAlgorithmTree(self): def fillAlgorithmTreeUsingProviders(self): self.algorithmTree.clear() text = str(self.searchBox.text()) + search_strings = text.split(' ') allAlgs = algList.algs for providerName in list(allAlgs.keys()): name = 'ACTIVATE_' + providerName.upper().replace(' ', '_') @@ -486,7 +487,15 @@ def fillAlgorithmTreeUsingProviders(self): continue if alg.commandLineName() == self.alg.commandLineName(): continue - if text == '' or text.lower() in alg.name.lower(): + + item_text = [alg.name.lower()] + item_text.extend(alg.tags.split(',')) + + show = not search_strings or all( + any(part in t for t in item_text) + for part in search_strings) + + if show: if alg.group in groups: groupItem = groups[alg.group] else: From f9bb230665c2efc9515496a4b6532d22011fa664 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 11:09:19 +1000 Subject: [PATCH 668/897] Avoid some QgsGeometry pointer use in QgsGeometry API --- python/core/geometry/qgsgeometry.sip | 4 ++-- src/core/geometry/qgsgeometry.cpp | 19 +++++++++---------- src/core/geometry/qgsgeometry.h | 4 ++-- src/core/qgsvectorlayereditutils.cpp | 10 +++------- 4 files changed, 16 insertions(+), 21 deletions(-) diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index 18a300952982..90f62a466041 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -358,7 +358,7 @@ class QgsGeometry @note available in python bindings as addPartGeometry (added in 2.2) */ // TODO QGIS 3.0 returns an enum instead of a magic constant - int addPart( const QgsGeometry *newPart /Transfer/ ) /PyName=addPartGeometry/; + int addPart( const QgsGeometry& newPart ) /PyName=addPartGeometry/; /** Translate this geometry by dx, dy @return 0 in case of success*/ @@ -388,7 +388,7 @@ class QgsGeometry @return 0 in case of success, 1 if geometry has not been split, error else*/ // TODO QGIS 3.0 returns an enum instead of a magic constant int splitGeometry( const QList& splitLine, - QList&newGeometries /Out/, + QList& newGeometries /Out/, bool topological, QList &topologyTestPoints /Out/); diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index 0a9bb0b285c0..4595014f6842 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -253,8 +253,7 @@ QgsGeometry QgsGeometry::collectGeometry( const QList< QgsGeometry >& geometries } else { - QgsGeometry part = QgsGeometry( *git ); - collected.addPart( &part ); + collected.addPart( *git ); } } return collected; @@ -731,14 +730,14 @@ int QgsGeometry::addPart( QgsAbstractGeometry* part, QgsWkbTypes::GeometryType g return QgsGeometryEditUtils::addPart( d->geometry, part ); } -int QgsGeometry::addPart( const QgsGeometry *newPart ) +int QgsGeometry::addPart( const QgsGeometry& newPart ) { - if ( !d->geometry || !newPart || !newPart->d || !newPart->d->geometry ) + if ( !d->geometry || !newPart.d || !newPart.d->geometry ) { return 1; } - return addPart( newPart->d->geometry->clone() ); + return addPart( newPart.d->geometry->clone() ); } int QgsGeometry::addPart( GEOSGeometry *newPart ) @@ -786,7 +785,7 @@ int QgsGeometry::rotate( double rotation, const QgsPoint& center ) return 0; } -int QgsGeometry::splitGeometry( const QList& splitLine, QList& newGeometries, bool topological, QList &topologyTestPoints ) +int QgsGeometry::splitGeometry( const QList& splitLine, QList& newGeometries, bool topological, QList &topologyTestPoints ) { if ( !d->geometry ) { @@ -811,7 +810,7 @@ int QgsGeometry::splitGeometry( const QList& splitLine, QList& splitLine, - QList&newGeometries, + QList& newGeometries, bool topological, QList &topologyTestPoints ); diff --git a/src/core/qgsvectorlayereditutils.cpp b/src/core/qgsvectorlayereditutils.cpp index 8a12b9372f89..5cab0b5844e6 100644 --- a/src/core/qgsvectorlayereditutils.cpp +++ b/src/core/qgsvectorlayereditutils.cpp @@ -359,9 +359,8 @@ int QgsVectorLayerEditUtils::splitFeatures( const QList& splitLine, bo { continue; } - QList newGeometries; + QList newGeometries; QList topologyTestPoints; - QgsGeometry* newGeometry = nullptr; QgsGeometry featureGeom = feat.geometry(); splitFunctionReturn = featureGeom.splitGeometry( splitLine, newGeometries, topologicalEditing, topologyTestPoints ); if ( splitFunctionReturn == 0 ) @@ -372,9 +371,8 @@ int QgsVectorLayerEditUtils::splitFeatures( const QList& splitLine, bo //insert new features for ( int i = 0; i < newGeometries.size(); ++i ) { - newGeometry = newGeometries.at( i ); QgsFeature newFeature; - newFeature.setGeometry( *newGeometry ); + newFeature.setGeometry( newGeometries.at( i ) ); //use default value where possible for primary key (e.g. autoincrement), //and use the value from the original (split) feature if not primary key @@ -492,7 +490,7 @@ int QgsVectorLayerEditUtils::splitParts( const QList& splitLine, bool QgsFeature feat; while ( fit.nextFeature( feat ) ) { - QList newGeometries; + QList newGeometries; QList topologyTestPoints; QgsGeometry featureGeom = feat.geometry(); splitFunctionReturn = featureGeom.splitGeometry( splitLine, newGeometries, topologicalEditing, topologyTestPoints ); @@ -550,8 +548,6 @@ int QgsVectorLayerEditUtils::splitParts( const QList& splitLine, bool { returnCode = splitFunctionReturn; } - - qDeleteAll( newGeometries ); } if ( numberOfSplittedParts == 0 && L->selectedFeatureCount() > 0 && returnCode == 0 ) From 6f3b0caa817b34b321ba6d0fda03e7cef0043f59 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 11:25:48 +1000 Subject: [PATCH 669/897] Add method to QgsAttributes to convert to QgsAttributeMap --- src/core/qgsfeature.cpp | 18 ++++++++++++++++++ src/core/qgsfeature.h | 8 ++++++++ tests/src/core/testqgsfeature.cpp | 23 +++++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/src/core/qgsfeature.cpp b/src/core/qgsfeature.cpp index 6aa6f4da59e5..fd9137de8c45 100644 --- a/src/core/qgsfeature.cpp +++ b/src/core/qgsfeature.cpp @@ -29,6 +29,23 @@ email : sherman at mrcc.com * See details in QEP #17 ****************************************************************************/ + +QgsAttributeMap QgsAttributes::toMap() const +{ + QgsAttributeMap map; + for ( int idx = 0; idx < count(); ++idx ) + { + QVariant v = at( idx ); + if ( v.isValid() ) + map.insert( idx, v ); + } + return map; +} + +// +// QgsFeature +// + QgsFeature::QgsFeature( QgsFeatureId id ) { d = new QgsFeaturePrivate( id ); @@ -327,3 +344,4 @@ uint qHash( const QgsFeature& key, uint seed ) return hash; } + diff --git a/src/core/qgsfeature.h b/src/core/qgsfeature.h index ef7e71cc1941..0c2d51b796ed 100644 --- a/src/core/qgsfeature.h +++ b/src/core/qgsfeature.h @@ -107,6 +107,14 @@ class CORE_EXPORT QgsAttributes : public QVector return true; } + /** + * Returns a QgsAttributeMap of the attribute values. Null values are + * excluded from the map. + * @note added in QGIS 3.0 + * @note not available in Python bindings + */ + QgsAttributeMap toMap() const; + inline bool operator!=( const QgsAttributes &v ) const { return !( *this == v ); } }; diff --git a/tests/src/core/testqgsfeature.cpp b/tests/src/core/testqgsfeature.cpp index 5536a87ec24c..5f756c9adc6f 100644 --- a/tests/src/core/testqgsfeature.cpp +++ b/tests/src/core/testqgsfeature.cpp @@ -33,6 +33,7 @@ class TestQgsFeature: public QObject void init();// will be called before each testfunction is executed. void cleanup();// will be called after every testfunction. void attributesTest(); //test QgsAttributes + void attributesToMap(); void create();//test creating a feature void copy();// test cpy destruction (double delete) void assignment(); @@ -120,6 +121,28 @@ void TestQgsFeature::attributesTest() QCOMPARE( attr7.size(), 5 ); } +void TestQgsFeature::attributesToMap() +{ + QgsAttributes attr1; + attr1 << QVariant( 5 ) << QVariant() << QVariant( "val" ); + QgsAttributeMap map1 = attr1.toMap(); + + QCOMPARE( map1.count(), 2 ); + QCOMPARE( map1.value( 0 ), QVariant( 5 ) ); + QCOMPARE( map1.value( 2 ), QVariant( "val" ) ); + + QgsAttributes attr2; + attr2 << QVariant() << QVariant( 5 ) << QVariant(); + QgsAttributeMap map2 = attr2.toMap(); + + QCOMPARE( map2.count(), 1 ); + QCOMPARE( map2.value( 1 ), QVariant( 5 ) ); + + QgsAttributes attr3; + QgsAttributeMap map3 = attr3.toMap(); + QVERIFY( map3.isEmpty() ); +} + void TestQgsFeature::create() { //test constructors From fcb6c2bb9ae17663047134d41befaac7b45eb048 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 12:35:25 +1000 Subject: [PATCH 670/897] Fix some incorrect return values from QgsFeature python bindings --- python/core/qgsfeature.sip | 4 ++++ tests/src/python/test_qgsfeature.py | 29 +++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/python/core/qgsfeature.sip b/python/core/qgsfeature.sip index 83fb397b81b9..752bc6f5de9f 100644 --- a/python/core/qgsfeature.sip +++ b/python/core/qgsfeature.sip @@ -293,6 +293,8 @@ class QgsFeature PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); sipIsErr = 1; } + + sipRes = rv; %End /** Initialize this feature with the given number of fields. Discard any previously set attribute data. @@ -412,10 +414,12 @@ class QgsFeature { PyErr_SetString(PyExc_KeyError, a0->toAscii()); sipIsErr = 1; + sipRes = false; } else { sipCpp->deleteAttribute( fieldIdx ); + sipRes = true; } %End /** Lookup attribute value from attribute name. Field map must be associated using @link setFields @endlink diff --git a/tests/src/python/test_qgsfeature.py b/tests/src/python/test_qgsfeature.py index 50327899ce4e..dd5d05a6738b 100644 --- a/tests/src/python/test_qgsfeature.py +++ b/tests/src/python/test_qgsfeature.py @@ -15,7 +15,7 @@ import qgis # NOQA import os -from qgis.core import QgsFeature, QgsGeometry, QgsPoint, QgsVectorLayer, NULL +from qgis.core import QgsFeature, QgsGeometry, QgsPoint, QgsVectorLayer, NULL, QgsFields, QgsField from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -66,13 +66,22 @@ def test_Attributes(self): assert myAttributes == myExpectedAttributes, myMessage - def test_SetAttribute(self): + def test_SetAttributes(self): feat = QgsFeature() feat.initAttributes(1) feat.setAttributes([0]) feat.setAttributes([NULL]) assert [NULL] == feat.attributes() + def test_setAttribute(self): + feat = QgsFeature() + feat.initAttributes(1) + with self.assertRaises(KeyError): + feat.setAttribute(-1, 5) + with self.assertRaises(KeyError): + feat.setAttribute(10, 5) + self.assertTrue(feat.setAttribute(0, 5)) + def test_DeleteAttribute(self): feat = QgsFeature() feat.initAttributes(3) @@ -85,6 +94,22 @@ def test_DeleteAttribute(self): myMessage = '\nExpected: %s\nGot: %s' % (str(myExpectedAttrs), str(myAttrs)) assert myAttrs == myExpectedAttrs, myMessage + def test_DeleteAttributeByName(self): + fields = QgsFields() + field1 = QgsField('my_field') + fields.append(field1) + field2 = QgsField('my_field2') + fields.append(field2) + + feat = QgsFeature(fields) + feat.initAttributes(2) + feat[0] = "text1" + feat[1] = "text2" + with self.assertRaises(KeyError): + feat.deleteAttribute('not present') + self.assertTrue(feat.deleteAttribute('my_field')) + self.assertEqual(feat.attributes(), ['text2']) + def test_SetGeometry(self): feat = QgsFeature() feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(123, 456))) From 8cd810ed2c369d03f8f3f4dbe6a238f87440a0e4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 12:48:08 +1000 Subject: [PATCH 671/897] Return false from QgsVectorLayer::addFeatures if adding features failed --- src/core/qgsvectorlayereditbuffer.cpp | 5 +- tests/src/python/test_qgsvectorlayer.py | 78 ++++++++++++++++++++++++- 2 files changed, 79 insertions(+), 4 deletions(-) diff --git a/src/core/qgsvectorlayereditbuffer.cpp b/src/core/qgsvectorlayereditbuffer.cpp index 7ff4a097324b..2d1e4f22ab44 100644 --- a/src/core/qgsvectorlayereditbuffer.cpp +++ b/src/core/qgsvectorlayereditbuffer.cpp @@ -135,13 +135,14 @@ bool QgsVectorLayerEditBuffer::addFeatures( QgsFeatureList& features ) if ( !( L->dataProvider()->capabilities() & QgsVectorDataProvider::AddFeatures ) ) return false; + bool result = true; for ( QgsFeatureList::iterator iter = features.begin(); iter != features.end(); ++iter ) { - addFeature( *iter ); + result = result && addFeature( *iter ); } L->updateExtents(); - return true; + return result; } diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 1480199911c2..90f1df330250 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -54,6 +54,12 @@ def createEmptyLayer(): return layer +def createEmptyLayerWithFields(): + layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", "addfeat", "memory") + assert layer.pendingFeatureCount() == 0 + return layer + + def createLayerWithOnePoint(): layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", "addfeat", "memory") @@ -168,8 +174,8 @@ def test_FeatureCount(self): # ADD FEATURE def test_AddFeature(self): - layer = createEmptyLayer() - feat = QgsFeature() + layer = createEmptyLayerWithFields() + feat = QgsFeature(layer.fields()) feat.setGeometry(QgsGeometry.fromPoint(QgsPoint(1, 2))) def checkAfter(): @@ -197,6 +203,12 @@ def checkBefore(): # add feature layer.startEditing() + + # try adding feature with incorrect number of fields + bad_feature = QgsFeature() + self.assertFalse(layer.addFeature(bad_feature)) + + # add good feature self.assertTrue(layer.addFeature(feat)) checkAfter() @@ -213,6 +225,68 @@ def checkBefore(): checkAfter() self.assertEqual(layer.dataProvider().featureCount(), 1) + # ADD FEATURES + + def test_AddFeatures(self): + layer = createEmptyLayerWithFields() + feat1 = QgsFeature(layer.fields()) + feat1.setGeometry(QgsGeometry.fromPoint(QgsPoint(1, 2))) + feat2 = QgsFeature(layer.fields()) + feat2.setGeometry(QgsGeometry.fromPoint(QgsPoint(11, 12))) + + def checkAfter(): + self.assertEqual(layer.pendingFeatureCount(), 2) + + # check select+nextFeature + it = layer.getFeatures() + f1 = next(it) + self.assertEqual(f1.geometry().asPoint(), QgsPoint(1, 2)) + f2 = next(it) + self.assertEqual(f2.geometry().asPoint(), QgsPoint(11, 12)) + + # check feature at id + f1_1 = next(layer.getFeatures(QgsFeatureRequest(f1.id()))) + self.assertEqual(f1_1.geometry().asPoint(), QgsPoint(1, 2)) + f2_1 = next(layer.getFeatures(QgsFeatureRequest(f2.id()))) + self.assertEqual(f2_1.geometry().asPoint(), QgsPoint(11, 12)) + + def checkBefore(): + self.assertEqual(layer.pendingFeatureCount(), 0) + + # check select+nextFeature + with self.assertRaises(StopIteration): + next(layer.getFeatures()) + + checkBefore() + + # try to add feature without editing mode + self.assertFalse(layer.addFeatures([feat1, feat2])) + + # add feature + layer.startEditing() + + # try adding feature with incorrect number of fields + bad_feature = QgsFeature() + self.assertFalse(layer.addFeatures([bad_feature])) + + # add good features + self.assertTrue(layer.addFeatures([feat1, feat2])) + + checkAfter() + self.assertEqual(layer.dataProvider().featureCount(), 0) + + # now try undo/redo + layer.undoStack().undo() + layer.undoStack().undo() + checkBefore() + layer.undoStack().redo() + layer.undoStack().redo() + checkAfter() + + self.assertTrue(layer.commitChanges()) + + checkAfter() + self.assertEqual(layer.dataProvider().featureCount(), 2) # DELETE FEATURE def test_DeleteFeature(self): From e40d64f9d5add15202cd9c76ffc1444d9cb65538 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 12:51:47 +1000 Subject: [PATCH 672/897] Make provider default value clauses exempt from unique constraint checks Otherwise the check fails when the provider has a default value clause like 'nextval(...)' even though the actual committed value will be unique. --- src/core/qgsvectorlayerutils.cpp | 19 +++++++++++++++++-- tests/src/python/test_provider_postgres.py | 15 ++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index 29653a98bac0..0ae2ab27e1cb 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -14,16 +14,31 @@ ***************************************************************************/ #include "qgsvectorlayerutils.h" +#include "qgsvectordataprovider.h" bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds ) { if ( !layer ) return false; - if ( fieldIndex < 0 || fieldIndex >= layer->fields().count() ) + QgsFields fields = layer->fields(); + + if ( fieldIndex < 0 || fieldIndex >= fields.count() ) return false; - QString fieldName = layer->fields().at( fieldIndex ).name(); + // check - if value is a provider side defaultValueClause then we exclude it from the check + if ( fields.fieldOrigin( fieldIndex ) == QgsFields::OriginProvider ) + { + int providerIdx = fields.fieldOriginIndex( fieldIndex ); + QString providerDefaultClause = layer->dataProvider()->defaultValueClause( providerIdx ); + if ( !providerDefaultClause.isEmpty() && value.toString() == providerDefaultClause ) + { + // exempt from check + return false; + } + } + + QString fieldName = fields.at( fieldIndex ).name(); // build up an optimised feature request QgsFeatureRequest request; diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 97ddb8ab3f54..d483da905e19 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -29,7 +29,8 @@ QgsField, QgsFieldConstraints, QgsDataProvider, - NULL + NULL, + QgsVectorLayerUtils ) from qgis.gui import QgsEditorWidgetRegistry from qgis.PyQt.QtCore import QSettings, QDate, QTime, QDateTime, QVariant @@ -516,6 +517,18 @@ def testConstraintOverwrite(self): self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) self.assertTrue(vl.fieldConstraints(0) & QgsFieldConstraints.ConstraintUnique) + def testVectorLayerUtilsUniqueWithProviderDefault(self): + vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") + default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' + self.assertEqual(vl.dataProvider().defaultValueClause(0), default_clause) + self.assertTrue(QgsVectorLayerUtils.valueExists(vl, 0, 4)) + + vl.startEditing() + f = QgsFeature(vl.fields()) + f.setAttribute(0, default_clause) + self.assertTrue(vl.addFeatures([f])) + self.assertFalse(QgsVectorLayerUtils.valueExists(vl, 0, default_clause)) + # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): uri = 'point?field=f1:int' From 0189609dcf22b58f2fd02dde1b7c9e1c98443606 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 8 Nov 2016 09:03:07 +0100 Subject: [PATCH 673/897] dxf export: skip nan z coordinates --- src/core/dxf/qgsdxfexport.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/dxf/qgsdxfexport.cpp b/src/core/dxf/qgsdxfexport.cpp index 8bca2ec9d9cb..7f129802f89d 100644 --- a/src/core/dxf/qgsdxfexport.cpp +++ b/src/core/dxf/qgsdxfexport.cpp @@ -428,7 +428,7 @@ void QgsDxfExport::writeGroup( int code, const QgsPointV2 &p ) { writeGroup( code + 10, p.x() ); writeGroup( code + 20, p.y() ); - if ( p.is3D() ) + if ( p.is3D() && qIsFinite( p.z() ) ) writeGroup( code + 30, p.z() ); } From aaa3117bd5cf7dc0702f3b26f91a90b4ae51a16f Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Tue, 8 Nov 2016 13:12:28 +0100 Subject: [PATCH 674/897] Multi relation removal Let the user select multiple relations and delete them. --- src/app/qgsrelationmanagerdialog.cpp | 7 +++++-- src/ui/qgsrelationmanagerdialogbase.ui | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/app/qgsrelationmanagerdialog.cpp b/src/app/qgsrelationmanagerdialog.cpp index a707c58dfdb3..083d03427fe7 100644 --- a/src/app/qgsrelationmanagerdialog.cpp +++ b/src/app/qgsrelationmanagerdialog.cpp @@ -134,8 +134,11 @@ void QgsRelationManagerDialog::on_mBtnDiscoverRelations_clicked() void QgsRelationManagerDialog::on_mBtnRemoveRelation_clicked() { - if ( mRelationsTable->currentIndex().isValid() ) - mRelationsTable->removeRow( mRelationsTable->currentItem()->row() ); + const QModelIndexList rows = mRelationsTable->selectionModel()->selectedRows(); + for ( int i = rows.size() - 1; i >= 0; --i ) + { + mRelationsTable->removeRow( rows[i].row() ); + } } QList< QgsRelation > QgsRelationManagerDialog::relations() diff --git a/src/ui/qgsrelationmanagerdialogbase.ui b/src/ui/qgsrelationmanagerdialogbase.ui index 894f5af3c94d..6268e8d50cc0 100644 --- a/src/ui/qgsrelationmanagerdialogbase.ui +++ b/src/ui/qgsrelationmanagerdialogbase.ui @@ -16,6 +16,9 @@ + + QAbstractItemView::SelectRows + true From 4234ad5c352373f7743a426846ffd736c7e2fc52 Mon Sep 17 00:00:00 2001 From: Patrick Valsecchi Date: Tue, 8 Nov 2016 13:36:23 +0100 Subject: [PATCH 675/897] Relation managment: enable the remove button when selection If nothing is selected, this button is doing nothing. --- src/app/qgsrelationmanagerdialog.cpp | 7 +++++++ src/app/qgsrelationmanagerdialog.h | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/app/qgsrelationmanagerdialog.cpp b/src/app/qgsrelationmanagerdialog.cpp index 083d03427fe7..89dd39bf7bcd 100644 --- a/src/app/qgsrelationmanagerdialog.cpp +++ b/src/app/qgsrelationmanagerdialog.cpp @@ -25,6 +25,9 @@ QgsRelationManagerDialog::QgsRelationManagerDialog( QgsRelationManager* relation , mRelationManager( relationMgr ) { setupUi( this ); + + mBtnRemoveRelation->setEnabled( false ); + connect( mRelationsTable->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QgsRelationManagerDialog::onSelectionChanged ); } QgsRelationManagerDialog::~QgsRelationManagerDialog() @@ -158,3 +161,7 @@ QList< QgsRelation > QgsRelationManagerDialog::relations() return relations; } +void QgsRelationManagerDialog::onSelectionChanged() +{ + mBtnRemoveRelation->setEnabled( mRelationsTable->selectionModel()->hasSelection() ); +} \ No newline at end of file diff --git a/src/app/qgsrelationmanagerdialog.h b/src/app/qgsrelationmanagerdialog.h index cf7ad5917f8a..48a0964afe5e 100644 --- a/src/app/qgsrelationmanagerdialog.h +++ b/src/app/qgsrelationmanagerdialog.h @@ -37,10 +37,11 @@ class APP_EXPORT QgsRelationManagerDialog : public QWidget, private Ui::QgsRelat void addRelation( const QgsRelation& rel ); QList< QgsRelation > relations(); - public slots: + private slots: void on_mBtnAddRelation_clicked(); void on_mBtnDiscoverRelations_clicked(); void on_mBtnRemoveRelation_clicked(); + void onSelectionChanged(); private: QgsRelationManager* mRelationManager; From 63e3fd37813d06d13914b41159123c9cb0a25436 Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 8 Nov 2016 20:00:47 +0100 Subject: [PATCH 676/897] [BUGFIX][QGIS Server] Revert layer order in WMS GetContext request --- src/server/qgswmsprojectparser.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/server/qgswmsprojectparser.cpp b/src/server/qgswmsprojectparser.cpp index 3e43aefcc254..ad2f47197efa 100644 --- a/src/server/qgswmsprojectparser.cpp +++ b/src/server/qgswmsprojectparser.cpp @@ -1768,7 +1768,14 @@ void QgsWmsProjectParser::addOWSLayers( QDomDocument &doc, layerElem.appendChild( metaUrlElem ); } - parentElem.appendChild( layerElem ); + if ( parentElem.hasChildNodes() ) + { + parentElem.insertBefore( layerElem, parentElem.firstChild() ); + } + else + { + parentElem.appendChild( layerElem ); + } } else { From 6cf47bef1ef8e0d273f0ed3179ec15f0cbb3f36f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Brunner?= Date: Tue, 8 Nov 2016 23:16:11 +0100 Subject: [PATCH 677/897] Apply some @m-kuhn comments (#3736) * Use QgsStringMap * Better description * Use new translated metadata methods --- python/core/qgsvectordataprovider.sip | 17 +++++++++- src/core/qgsvectordataprovider.h | 19 +++++++++-- src/core/qgsvectorlayer.cpp | 9 +++-- src/providers/wfs/qgswfsprovider.cpp | 47 +++++++++++++++++++++++---- src/providers/wfs/qgswfsprovider.h | 17 +++++++++- 5 files changed, 96 insertions(+), 13 deletions(-) diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index ec2fdb56f79b..bc2e70dec872 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -401,7 +401,22 @@ class QgsVectorDataProvider : QgsDataProvider * Get some metadata that will be display in the metadata tab of the layer properties. * @return The provider metadata */ - virtual QMap metadata() const; + virtual QVariantMap metadata() const; + + /** + * Get the translated metadata key. + * @param mdKey The metadata key + * @return The translated metadata value + */ + virtual QString translateMetadataKey( const QString& mdKey ) const; + + /** + * Get the translated metadata value. + * @param mdKey The metadata key + * @param value The metadata value + * @return The translated metadata value + */ + virtual QString translateMetadataValue( const QString& mdKey, const QVariant& value ) const; signals: /** diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index 7cd1810d2ef1..b95acfa4a541 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -460,10 +460,25 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider virtual QList discoverRelations( const QgsVectorLayer* self, const QList& layers ) const; /** - * Get some metadata that will be display in the metadata tab of the layer properties. + * Get metadata, dependent on the provider type, that will be display in the metadata tab of the layer properties. * @return The provider metadata */ - virtual QMap metadata() const { return QMap(); }; + virtual QVariantMap metadata() const { return QVariantMap(); }; + + /** + * Get the translated metadata key. + * @param mdKey The metadata key + * @return The translated metadata value + */ + virtual QString translateMetadataKey( const QString& mdKey ) const { return mdKey; }; + + /** + * Get the translated metadata value. + * @param mdKey The metadata key + * @param value The metadata value + * @return The translated metadata value + */ + virtual QString translateMetadataValue( const QString& mdKey, const QVariant& value ) const { Q_UNUSED( mdKey ); return value.toString(); }; signals: diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 869ddb4b133a..5216661b48ab 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -3890,16 +3890,19 @@ QString QgsVectorLayer::metadata() const myMetadata += dataProvider()->description().replace( '\n', QLatin1String( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " ) ); myMetadata += QLatin1String( "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n" ); - QMap dataProviderMetadata = mDataProvider->metadata(); + QVariantMap dataProviderMetadata = mDataProvider->metadata(); if ( !dataProviderMetadata.isEmpty() ) { myMetadata += "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + tr( "Provider Metadata" ) + "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n"; myMetadata += "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n"; - QMapIterator i( dataProviderMetadata ); + QMapIterator i( dataProviderMetadata ); while ( i.hasNext() ) { i.next(); - myMetadata += "\n"; + myMetadata += ""; + myMetadata += ""; + myMetadata += ""; + myMetadata += "\n"; } myMetadata += QLatin1String( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + tr( "Metadata name" ) + "" + tr( "Metadata value" ) + "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + i.key() + ":" + i.value() + "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + mDataProvider->translateMetadataKey( i.key() ) + ":" + mDataProvider->translateMetadataValue( i.key(), i.value() ) + "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  \n" ); } diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index 084951fd3a72..27c7638d388f 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -1100,16 +1100,51 @@ bool QgsWFSProvider::changeAttributeValues( const QgsChangedAttributesMap &attr_ } } - -QMap QgsWFSProvider::metadata() +QVariantMap QgsWFSProvider::metadata() const { - QMap result; - result[tr( "Max Features" )] = mShared->mCaps.maxFeatures == 0 ? tr( "not provided" ) : QString( mShared->mCaps.maxFeatures ); - result[tr( "Supports Paging" )] = mShared->mCaps.supportsPaging ? tr( "supported" ) : tr( "unsupported" ); - result[tr( "Supports Joins" )] = mShared->mCaps.supportsJoins ? tr( "supported" ) : tr( "unsupported" ); + QVariantMap result; + result["MaxFeatures"] = mShared->mCaps.maxFeatures; + result["SupportsPaging"] = mShared->mCaps.supportsPaging; + result["SupportsJoins"] = mShared->mCaps.supportsJoins; return result; } +QString QgsWFSProvider::translateMetadataKey( const QString& mdKey ) const +{ + if ( mdKey == "MaxFeatures" ) + { + return tr( "Max Features" ); + } + else if ( mdKey == "SupportsPaging" ) + { + return tr( "Supports Paging" ); + } + else if ( mdKey == "SupportsJoins" ) + { + return tr( "Supports Joins" ); + } + else + { + return mdKey; + } +}; + +QString QgsWFSProvider::translateMetadataValue( const QString& mdKey, const QVariant& value ) const +{ + if ( mdKey == "MaxFeatures" ) + { + return value.toInt() == 0 ? tr( "not provided" ) : value.toString(); + } + else if ( mdKey == "SupportsPaging" || mdKey == "SupportsJoins" ) + { + return value.toBool() ? tr( "supported" ) : tr( "unsupported" ); + } + else + { + return value.toString(); + } +}; + bool QgsWFSProvider::describeFeatureType( QString& geometryAttribute, QgsFields& fields, QgsWkbTypes::Type& geomType ) { fields.clear(); diff --git a/src/providers/wfs/qgswfsprovider.h b/src/providers/wfs/qgswfsprovider.h index 68f155b21aaf..20667cc2b609 100644 --- a/src/providers/wfs/qgswfsprovider.h +++ b/src/providers/wfs/qgswfsprovider.h @@ -137,7 +137,22 @@ class QgsWFSProvider : public QgsVectorDataProvider * Get some metadata description of the provider. * @return The provider metadata */ - virtual QMap metadata(); + virtual QVariantMap metadata() const override; + + /** + * Get the translated metadata key. + * @param mdKey The metadata key + * @return The translated metadata value + */ + virtual QString translateMetadataKey( const QString& mdKey ) const override; + + /** + * Get the translated metadata value. + * @param mdKey The metadata key + * @param value The metadata value + * @return The translated metadata value + */ + virtual QString translateMetadataValue( const QString& mdKey, const QVariant& value ) const override; public slots: From c282e2621008f49644c89acc1a4f72a48da1493b Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 27 Oct 2016 23:02:46 +0200 Subject: [PATCH 678/897] Use QPointer for storing layer pointers in expression scope --- src/core/qgsexpression.cpp | 3 ++- src/core/qgsexpressioncontext.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 63c34acfe0f7..411cf7290af0 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -331,7 +331,8 @@ static QgsExpression::Node* getNode( const QVariant& value, QgsExpression* paren QgsVectorLayer* getVectorLayer( const QVariant& value, QgsExpression* ) { - QgsVectorLayer* vl = value.value(); + QgsMapLayer* ml = value.value< QPointer >().data(); + QgsVectorLayer* vl = qobject_cast( ml ); if ( !vl ) { QString layerString = value.toString(); diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index bc89d42199ae..ca3273ea1c5e 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -691,7 +691,7 @@ QgsExpressionContextScope* QgsExpressionContextUtils::layerScope( const QgsMapLa scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer_name" ), layer->name(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer_id" ), layer->id(), true ) ); - scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer" ), QVariant::fromValue( const_cast( layer ) ), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "layer" ), QVariant::fromValue >( QPointer( const_cast( layer ) ) ), true ) ); const QgsVectorLayer* vLayer = dynamic_cast< const QgsVectorLayer* >( layer ); if ( vLayer ) From 5093ec6bc91ead1b9b2aaa3923ba98f2ef279e3a Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 27 Oct 2016 23:09:31 +0200 Subject: [PATCH 679/897] Improve num_selected and is_selected function help --- resources/function_help/json/is_selected | 14 ++++++++++++-- resources/function_help/json/num_selected | 7 ++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/resources/function_help/json/is_selected b/resources/function_help/json/is_selected index ca1e7a4344d0..68f7e9a1475c 100644 --- a/resources/function_help/json/is_selected +++ b/resources/function_help/json/is_selected @@ -3,8 +3,18 @@ "type": "function", "description": "Returns if a feature is selected. If called with no parameters checks the current feature.", "arguments": [ - {"arg":"feature","description":"The feature which should be checked for selection"}, - {"arg":"layer","description":"The layer (or its id or name) on which the selection will be checked"} + { + "arg":"feature", + "optional": true, + "default": "current feature", + "description":"The feature which should be checked for selection." + }, + { + "arg": "layer", + "optional": true, + "default": "current layer", + "description": "The layer (or its id or name) on which the selection will be checked." + } ], "examples": [ { "expression":"is_selected()", "returns" : "True if the current feature is selected."}, diff --git a/resources/function_help/json/num_selected b/resources/function_help/json/num_selected index 7c61f288bf3e..781525849e5b 100644 --- a/resources/function_help/json/num_selected +++ b/resources/function_help/json/num_selected @@ -3,7 +3,12 @@ "type": "function", "description": "Returns the number of selected features on a given layer. By default works on the layer on which the expression is evaluated.", "arguments": [ - {"arg":"layer","description":"The layer (or its id or name) on which the selection will be checked"} + { + "arg": "layer", + "optional": true, + "default": "current layer", + "description": "The layer (or its id or name) on which the selection will be checked." + } ], "examples": [ { "expression":"num_selected()", "returns":"The number of selected features on the current layer."}, From 164a85acdb42f383b955c82c00f0ac2c0c5ad2ba Mon Sep 17 00:00:00 2001 From: Hugo Mercier Date: Wed, 9 Nov 2016 16:40:43 +0100 Subject: [PATCH 680/897] [virtual] Fix encoding issue --- .../virtual/qgsvirtuallayersqlitehelper.cpp | 14 +++++++------- .../virtual/qgsvirtuallayersqlitemodule.cpp | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp b/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp index 067cf769ff45..28ec76b04aa3 100644 --- a/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp +++ b/src/providers/virtual/qgsvirtuallayersqlitehelper.cpp @@ -30,7 +30,7 @@ QgsScopedSqlite::QgsScopedSqlite( const QString& path, bool withExtension ) sqlite3_auto_extension( reinterpret_cast < void( * )() > ( qgsvlayerModuleInit ) ); } int r; - r = sqlite3_open( path.toLocal8Bit().constData(), &db_ ); + r = sqlite3_open( path.toUtf8().constData(), &db_ ); if ( withExtension ) { // reset the automatic extensions @@ -41,7 +41,7 @@ QgsScopedSqlite::QgsScopedSqlite( const QString& path, bool withExtension ) { QString err = QStringLiteral( "%1 [%2]" ).arg( sqlite3_errmsg( db_ ), path ); QgsDebugMsg( err ); - throw std::runtime_error( err.toLocal8Bit().constData() ); + throw std::runtime_error( err.toUtf8().constData() ); } // enable extended result codes sqlite3_extended_result_codes( db_, 1 ); @@ -92,12 +92,12 @@ namespace Sqlite , stmt_( nullptr ) , nBind_( 1 ) { - QByteArray ba( q.toLocal8Bit() ); + QByteArray ba( q.toUtf8() ); int r = sqlite3_prepare_v2( db, ba.constData(), ba.size(), &stmt_, nullptr ); if ( r ) { QString err = QStringLiteral( "Query preparation error on %1: %2" ).arg( q ).arg( sqlite3_errmsg( db ) ); - throw std::runtime_error( err.toLocal8Bit().constData() ); + throw std::runtime_error( err.toUtf8().constData() ); } } @@ -110,7 +110,7 @@ namespace Sqlite Query& Query::bind( const QString& str, int idx ) { - QByteArray ba( str.toLocal8Bit() ); + QByteArray ba( str.toUtf8() ); int r = sqlite3_bind_text( stmt_, idx, ba.constData(), ba.size(), SQLITE_TRANSIENT ); if ( r ) { @@ -127,11 +127,11 @@ namespace Sqlite void Query::exec( sqlite3* db, const QString& sql ) { char *errMsg = nullptr; - int r = sqlite3_exec( db, sql.toLocal8Bit().constData(), nullptr, nullptr, &errMsg ); + int r = sqlite3_exec( db, sql.toUtf8().constData(), nullptr, nullptr, &errMsg ); if ( r ) { QString err = QStringLiteral( "Query execution error on %1: %2 - %3" ).arg( sql ).arg( r ).arg( errMsg ); - throw std::runtime_error( err.toLocal8Bit().constData() ); + throw std::runtime_error( err.toUtf8().constData() ); } } diff --git a/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp b/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp index 6a413b1ca9e4..158c42a6e846 100644 --- a/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp +++ b/src/providers/virtual/qgsvirtuallayersqlitemodule.cpp @@ -57,7 +57,7 @@ void initVirtualLayerMetadata( sqlite3* db ) char *errMsg; if ( create_meta ) { - r = sqlite3_exec( db, QStringLiteral( "CREATE TABLE _meta (version INT, url TEXT); INSERT INTO _meta (version) VALUES(%1);" ).arg( VIRTUAL_LAYER_VERSION ).toLocal8Bit().constData(), nullptr, nullptr, &errMsg ); + r = sqlite3_exec( db, QStringLiteral( "CREATE TABLE _meta (version INT, url TEXT); INSERT INTO _meta (version) VALUES(%1);" ).arg( VIRTUAL_LAYER_VERSION ).toUtf8().constData(), nullptr, nullptr, &errMsg ); if ( r ) { throw std::runtime_error( errMsg ); From 45711d372ed4fe734f917d000937ca764add42b5 Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 10 Nov 2016 10:21:12 +0700 Subject: [PATCH 681/897] [processing] use algorithm description in modeler dependencies dialog --- python/plugins/processing/modeler/ModelerParametersDialog.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 183201446fc2..9c2de338da0a 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -247,7 +247,7 @@ def getAvailableDependencies(self): return opts def getDependenciesPanel(self): - return MultipleInputPanel([alg.algorithm.name for alg in self.getAvailableDependencies()]) + return MultipleInputPanel([alg.description for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced From 6b2b4c578ac45ae6f5745c240e03265c14cdfde1 Mon Sep 17 00:00:00 2001 From: nirvn Date: Tue, 8 Nov 2016 11:56:16 +0700 Subject: [PATCH 682/897] [FEATURE][expression] strpos() and regexp_match() improvements - strpos() now relies on a simple string within a string search - regexp_match() now returns pos of a matching regular expression --- resources/function_help/json/regexp_match | 4 ++-- src/core/qgsexpression.cpp | 4 ++-- tests/src/core/testqgsexpression.cpp | 3 ++- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/resources/function_help/json/regexp_match b/resources/function_help/json/regexp_match index 5f46cfc8d1ca..330010deefdd 100644 --- a/resources/function_help/json/regexp_match +++ b/resources/function_help/json/regexp_match @@ -1,9 +1,9 @@ { "name": "regexp_match", "type": "function", - "description": "Returns true if any part of a string matches the supplied regular expression.", + "description": "Return the first matching position matching a regular expression within a string, or 0 if the substring is not found.", "arguments": [ {"arg":"input_string","description":"the string to test against the regular expression"}, {"arg":"regex","description":"The regular expression to test against. Backslash characters must be double escaped (eg \"\\\\\\\\s\" to match a white space character)."} ], - "examples": [ { "expression":"regexp_match('QGIS ROCKS','\\\\\\\\sROCKS')", "returns":"true"}] + "examples": [ { "expression":"regexp_match('QGIS ROCKS','\\\\\\\\sROCKS')", "returns":"4"}] } diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 411cf7290af0..9a2037a14180 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -1333,7 +1333,7 @@ static QVariant fcnRegexpMatch( const QVariantList& values, const QgsExpressionC parent->setEvalErrorString( QObject::tr( "Invalid regular expression '%1': %2" ).arg( regexp, re.errorString() ) ); return QVariant(); } - return QVariant( str.contains( re ) ? 1 : 0 ); + return QVariant(( str.indexOf( re ) + 1 ) ); } static QVariant fcnRegexpMatches( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) @@ -1529,7 +1529,7 @@ static QVariant fcnConcat( const QVariantList& values, const QgsExpressionContex static QVariant fcnStrpos( const QVariantList& values, const QgsExpressionContext*, QgsExpression *parent ) { QString string = getStringValue( values.at( 0 ), parent ); - return string.indexOf( QRegExp( getStringValue( values.at( 1 ), parent ) ) ) + 1; + return string.indexOf( getStringValue( values.at( 1 ), parent ) ) + 1; } static QVariant fcnRight( const QVariantList& values, const QgsExpressionContext*, QgsExpression *parent ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index 0086c5bae683..ff5a62819b9b 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -852,6 +852,7 @@ class TestQgsExpression: public QObject QTest::newRow( "regexp_matches no capturing group" ) << "regexp_matches('some string','.*')" << false << QVariant( QVariantList() ); QTest::newRow( "regexp_matches invalid" ) << "regexp_matches('invalid','(')" << true << QVariant(); QTest::newRow( "strpos" ) << "strpos('Hello World','World')" << false << QVariant( 7 ); + QTest::newRow( "strpos non-regexp" ) << "strpos('Hello.World','.')" << false << QVariant( 6 ); QTest::newRow( "strpos outside" ) << "strpos('Hello World','blah')" << false << QVariant( 0 ); QTest::newRow( "left" ) << "left('Hello World',5)" << false << QVariant( "Hello" ); QTest::newRow( "right" ) << "right('Hello World', 5)" << false << QVariant( "World" ); @@ -911,7 +912,7 @@ class TestQgsExpression: public QObject QTest::newRow( "coalesce exp" ) << "coalesce(NULL, 1+1)" << false << QVariant( 2 ); QTest::newRow( "regexp match" ) << "regexp_match('abc','.b.')" << false << QVariant( 1 ); QTest::newRow( "regexp match invalid" ) << "regexp_match('abc DEF','[[[')" << true << QVariant(); - QTest::newRow( "regexp match escaped" ) << "regexp_match('abc DEF','\\\\s[A-Z]+')" << false << QVariant( 1 ); + QTest::newRow( "regexp match escaped" ) << "regexp_match('abc DEF','\\\\s[A-Z]+')" << false << QVariant( 4 ); QTest::newRow( "regexp match false" ) << "regexp_match('abc DEF','\\\\s[a-z]+')" << false << QVariant( 0 ); QTest::newRow( "if true" ) << "if(1=1, 1, 0)" << false << QVariant( 1 ); QTest::newRow( "if false" ) << "if(1=2, 1, 0)" << false << QVariant( 0 ); From 73b283c0b56a32d6578434530601d4a1710aa667 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Thu, 10 Nov 2016 13:47:50 +0100 Subject: [PATCH 683/897] update FindQCA.cmake for Arch Linux --- cmake/FindQCA.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/FindQCA.cmake b/cmake/FindQCA.cmake index c606afa883c0..612420668713 100644 --- a/cmake/FindQCA.cmake +++ b/cmake/FindQCA.cmake @@ -45,7 +45,7 @@ else(QCA_INCLUDE_DIR AND QCA_LIBRARY) "$ENV{LIB_DIR}/include" $ENV{INCLUDE} /usr/local/include - PATH_SUFFIXES QtCrypto qt5/QtCrypto Qca-qt5/QtCrypto + PATH_SUFFIXES QtCrypto qt5/QtCrypto Qca-qt5/QtCrypto qt/Qca-qt5/QtCrypto ) if(QCA_LIBRARY AND QCA_INCLUDE_DIR) From b0644ea4383f03e2a9785c5f7146a6470ceb1020 Mon Sep 17 00:00:00 2001 From: Marco Hugentobler Date: Thu, 10 Nov 2016 15:12:59 +0100 Subject: [PATCH 684/897] WMS server: add user setting if custom datasources are allowed in wms requests --- python/server/qgswmsconfigparser.sip | 2 + python/server/qgswmsprojectparser.sip | 2 + src/app/qgsprojectproperties.cpp | 4 ++ src/server/qgssldconfigparser.cpp | 21 ++++++++++ src/server/qgssldconfigparser.h | 2 + src/server/qgswmsconfigparser.h | 2 + src/server/qgswmsprojectparser.cpp | 21 ++++++++++ src/server/qgswmsprojectparser.h | 2 + src/server/qgswmsserver.cpp | 5 +++ src/ui/qgsprojectpropertiesbase.ui | 59 +++++++++++++++------------ 10 files changed, 94 insertions(+), 26 deletions(-) diff --git a/python/server/qgswmsconfigparser.sip b/python/server/qgswmsconfigparser.sip index 0d2780c48d24..f88cfdeffb10 100644 --- a/python/server/qgswmsconfigparser.sip +++ b/python/server/qgswmsconfigparser.sip @@ -123,6 +123,8 @@ class QgsWmsConfigParser virtual bool useLayerIds() const = 0; + virtual bool allowRequestDefinedDatasources() const; + private: QgsWmsConfigParser(); diff --git a/python/server/qgswmsprojectparser.sip b/python/server/qgswmsprojectparser.sip index f195e4837f29..0333dac98de4 100644 --- a/python/server/qgswmsprojectparser.sip +++ b/python/server/qgswmsprojectparser.sip @@ -111,6 +111,8 @@ class QgsWmsProjectParser : public QgsWmsConfigParser bool useLayerIds() const /*override*/ ; + bool allowRequestDefinedDatasources() const; + private: /** Returns an ID-list of layers which are not queryable (comes from -> -> readBoolEntry( QStringLiteral( "WMSAddWktGeometry" ), QStringLiteral( "/" ) ); mAddWktGeometryCheckBox->setChecked( addWktGeometry ); + bool requestDefinedSources = QgsProject::instance()->readBoolEntry( "WMSRequestDefinedDataSources", "/", false ); + mAllowRequestDefinedDataSourcesBox->setChecked( requestDefinedSources ); + bool segmentizeFeatureInfoGeometry = QgsProject::instance()->readBoolEntry( QStringLiteral( "WMSSegmentizeFeatureInfoGeometry" ), QStringLiteral( "/" ) ); mSegmentizeFeatureInfoGeometryCheckBox->setChecked( segmentizeFeatureInfoGeometry ); @@ -1077,6 +1080,7 @@ void QgsProjectProperties::apply() } QgsProject::instance()->writeEntry( QStringLiteral( "WMSAddWktGeometry" ), QStringLiteral( "/" ), mAddWktGeometryCheckBox->isChecked() ); + QgsProject::instance()->writeEntry( "WMSRequestDefinedDataSources", "/", mAllowRequestDefinedDataSourcesBox->isChecked() ); QgsProject::instance()->writeEntry( QStringLiteral( "WMSSegmentizeFeatureInfoGeometry" ), QStringLiteral( "/" ), mSegmentizeFeatureInfoGeometryCheckBox->isChecked() ); QgsProject::instance()->writeEntry( QStringLiteral( "WMSUseLayerIDs" ), QStringLiteral( "/" ), mWmsUseLayerIDs->isChecked() ); diff --git a/src/server/qgssldconfigparser.cpp b/src/server/qgssldconfigparser.cpp index 04064cba2cf7..cb441000f738 100644 --- a/src/server/qgssldconfigparser.cpp +++ b/src/server/qgssldconfigparser.cpp @@ -20,6 +20,7 @@ #include "qgsconfigparserutils.h" #include "qgslogger.h" #include "qgsmapserviceexception.h" +#include "qgsmessagelog.h" #include "qgsrasterlayer.h" #include "qgsrenderer.h" #include "qgssinglesymbolrenderer.h" @@ -1204,6 +1205,17 @@ QDomElement QgsSLDConfigParser::findUserLayerElement( const QString& layerName ) QgsMapLayer* QgsSLDConfigParser::mapLayerFromUserLayer( const QDomElement& userLayerElem, const QString& layerName, bool allowCaching ) const { + if ( !mFallbackParser ) + { + return 0; + } + + if ( !mFallbackParser->allowRequestDefinedDatasources() ) + { + QgsMessageLog::logMessage( "The project configuration does not allow datasources defined in the request", "Server", QgsMessageLog::CRITICAL ); + return 0; + } + QgsDebugMsg( "Entering." ); QgsMSLayerBuilder* layerBuilder = nullptr; QDomElement builderRootElement; @@ -1358,6 +1370,15 @@ void QgsSLDConfigParser::setCrsForLayer( const QDomElement& layerElem, QgsMapLay } } +bool QgsSLDConfigParser::allowRequestDefinedDatasources() const +{ + if ( mFallbackParser ) + { + return mFallbackParser->allowRequestDefinedDatasources(); + } + return false; +} + diff --git a/src/server/qgssldconfigparser.h b/src/server/qgssldconfigparser.h index 137100ebfe0f..3b117fff49e0 100644 --- a/src/server/qgssldconfigparser.h +++ b/src/server/qgssldconfigparser.h @@ -133,6 +133,8 @@ class QgsSLDConfigParser : public QgsWmsConfigParser void serviceCapabilities( QDomElement& parentElement, QDomDocument& doc ) const override; + bool allowRequestDefinedDatasources() const; + private: //! SLD as dom document diff --git a/src/server/qgswmsconfigparser.h b/src/server/qgswmsconfigparser.h index 2159f9748107..f10f5ea52f6a 100644 --- a/src/server/qgswmsconfigparser.h +++ b/src/server/qgswmsconfigparser.h @@ -139,6 +139,8 @@ class SERVER_EXPORT QgsWmsConfigParser virtual bool useLayerIds() const = 0; + virtual bool allowRequestDefinedDatasources() const { return false; } + //! Adds highlight layers to the layer registry and to the layer set. Returns the ids of the newly created layers (for later removal) static QStringList addHighlightLayers( const QMap& parameterMap, QStringList& layerSet, const QString& parameterPrefix = QString() ); static void removeHighlightLayers( const QStringList& layerIds ); diff --git a/src/server/qgswmsprojectparser.cpp b/src/server/qgswmsprojectparser.cpp index 3e43aefcc254..e1a472a13f45 100644 --- a/src/server/qgswmsprojectparser.cpp +++ b/src/server/qgswmsprojectparser.cpp @@ -2481,3 +2481,24 @@ QString QgsWmsProjectParser::getCapaServiceUrl( QDomDocument& doc ) const return url; } + +bool QgsWmsProjectParser::allowRequestDefinedDatasources() const +{ + if ( !mProjectParser->xmlDocument() ) + { + return false; + } + + QDomElement propertiesElem = mProjectParser->propertiesElem(); + if ( propertiesElem.isNull() ) + { + return false; + } + QDomElement dsElem = propertiesElem.firstChildElement( "WMSRequestDefinedDataSources" ); + if ( dsElem.isNull() ) + { + return false; + } + + return ( dsElem.text().compare( "true", Qt::CaseInsensitive ) == 0 ); +} diff --git a/src/server/qgswmsprojectparser.h b/src/server/qgswmsprojectparser.h index 3a5d93a615eb..bd7922caf7d1 100644 --- a/src/server/qgswmsprojectparser.h +++ b/src/server/qgswmsprojectparser.h @@ -127,6 +127,8 @@ class SERVER_EXPORT QgsWmsProjectParser : public QgsWmsConfigParser bool useLayerIds() const override { return mProjectParser->useLayerIds(); } + bool allowRequestDefinedDatasources() const; + private: QgsServerProjectParser* mProjectParser; #ifdef HAVE_SERVER_PYTHON_PLUGINS diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index ce9047ad6ee9..d3aa93463953 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -1894,6 +1894,11 @@ QImage* QgsWmsServer::initializeRendering( QStringList& layersList, QStringList& QString gml = mParameters.value( QStringLiteral( "GML" ) ); if ( !gml.isEmpty() ) { + if ( !mConfigParser->allowRequestDefinedDatasources() ) + { + QgsMessageLog::logMessage( "The project configuration does not allow datasources defined in the request", "Server", QgsMessageLog::CRITICAL ); + return 0; + } QDomDocument* gmlDoc = new QDomDocument(); if ( gmlDoc->setContent( gml, true ) ) { diff --git a/src/ui/qgsprojectpropertiesbase.ui b/src/ui/qgsprojectpropertiesbase.ui index 38bc06f5fdb2..06ce53fe8bc8 100644 --- a/src/ui/qgsprojectpropertiesbase.ui +++ b/src/ui/qgsprojectpropertiesbase.ui @@ -1238,7 +1238,7 @@
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - + @@ -1294,9 +1294,9 @@ 0 - -961 + -912 674 - 2470 + 2497 @@ -1845,7 +1845,7 @@ - + @@ -1879,7 +1879,7 @@ - + @@ -1926,7 +1926,7 @@ - + @@ -1950,7 +1950,7 @@ - + @@ -2096,13 +2096,20 @@ - + Segmentize feature info geometry + + + + Allow defining datasources in server requests + + + @@ -2359,8 +2366,8 @@ 0 0 - 694 - 779 + 141 + 54 @@ -2486,39 +2493,39 @@ - QgsCollapsibleGroupBox - QGroupBox -
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscollapsiblegroupbox.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + QgsProjectionSelector + QWidget +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgsprojectionselector.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - QgsColorButton - QToolButton -
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscolorbutton.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + QgsCollapsibleGroupBox + QGroupBox +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscollapsiblegroupbox.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - QgsColorSchemeList + QgsCodeEditorPython QWidget -
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscolorschemelist.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscodeeditorpython.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - QgsVariableEditorWidget - QWidget -
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgsvariableeditorwidget.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + QgsColorSchemeList + QTreeView +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscolorschemelist.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - QgsCodeEditorPython - QWidget -
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscodeeditorpython.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + QgsColorButton + QToolButton +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgscolorbutton.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - QgsProjectionSelector + QgsVariableEditorWidget QWidget -
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgsprojectionselector.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgsvariableeditorwidget.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  From 88587fdeb75b042113159ddd06ce5f6967e563a6 Mon Sep 17 00:00:00 2001 From: Marco Hugentobler Date: Thu, 10 Nov 2016 16:59:11 +0100 Subject: [PATCH 685/897] Add override keywords --- src/server/qgssldconfigparser.h | 2 +- src/server/qgswmsprojectparser.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/server/qgssldconfigparser.h b/src/server/qgssldconfigparser.h index 3b117fff49e0..941380a14dbf 100644 --- a/src/server/qgssldconfigparser.h +++ b/src/server/qgssldconfigparser.h @@ -133,7 +133,7 @@ class QgsSLDConfigParser : public QgsWmsConfigParser void serviceCapabilities( QDomElement& parentElement, QDomDocument& doc ) const override; - bool allowRequestDefinedDatasources() const; + bool allowRequestDefinedDatasources() const override; private: diff --git a/src/server/qgswmsprojectparser.h b/src/server/qgswmsprojectparser.h index bd7922caf7d1..b4597a74cfb9 100644 --- a/src/server/qgswmsprojectparser.h +++ b/src/server/qgswmsprojectparser.h @@ -127,7 +127,7 @@ class SERVER_EXPORT QgsWmsProjectParser : public QgsWmsConfigParser bool useLayerIds() const override { return mProjectParser->useLayerIds(); } - bool allowRequestDefinedDatasources() const; + bool allowRequestDefinedDatasources() const override; private: QgsServerProjectParser* mProjectParser; From 10648dfb0cf525da98ed30cd06bf1e444b0c3980 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 08:35:38 +1000 Subject: [PATCH 686/897] [processing] Start of tests for modeler --- .../plugins/processing/tests/CMakeLists.txt | 1 + .../plugins/processing/tests/ModelerTest.py | 67 +++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 python/plugins/processing/tests/ModelerTest.py diff --git a/python/plugins/processing/tests/CMakeLists.txt b/python/plugins/processing/tests/CMakeLists.txt index a1ac75d3617f..cc02bff82629 100644 --- a/python/plugins/processing/tests/CMakeLists.txt +++ b/python/plugins/processing/tests/CMakeLists.txt @@ -7,6 +7,7 @@ PLUGIN_INSTALL(processing tests/data ${TEST_DATA_FILES}) IF(ENABLE_TESTS) INCLUDE(UsePythonTest) ADD_PYTHON_TEST(ProcessingParametersTest ParametersTest.py) + ADD_PYTHON_TEST(ProcessingModelerTest ModelerTest.py) ADD_PYTHON_TEST(ProcessingToolsTest ToolsTest.py) ADD_PYTHON_TEST(ProcessingQgisAlgorithmsTest QgisAlgorithmsTest.py) ADD_PYTHON_TEST(ProcessingGdalAlgorithmsTest GdalAlgorithmsTest.py) diff --git a/python/plugins/processing/tests/ModelerTest.py b/python/plugins/processing/tests/ModelerTest.py new file mode 100644 index 000000000000..ad9b4b5ea873 --- /dev/null +++ b/python/plugins/processing/tests/ModelerTest.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + ModelerTest + --------------------- + Date : November 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************8 +""" + +__author__ = 'Nyall Dawson' +__date__ = 'November 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.testing import start_app, unittest + +from processing.modeler.ModelerAlgorithm import (ModelerAlgorithm, ModelerParameter) +from processing.modeler.ModelerParametersDialog import (ModelerParametersDialog) +from processing.core.parameters import (ParameterFile, + ParameterNumber, + ParameterString, + ParameterTableField) +start_app() + + +class ModelerTest(unittest.TestCase): + + def testModelerParametersDialogAvailableValuesOfType(self): + # test getAvailableValuesOfType from ModelerParametersDialog + + m = ModelerAlgorithm() + string_param_1 = ModelerParameter(ParameterString('string', 'string desc')) + m.addParameter(string_param_1) + string_param_2 = ModelerParameter(ParameterString('string2', 'string desc')) + m.addParameter(string_param_2) + num_param = ModelerParameter(ParameterNumber('number', 'number desc')) + m.addParameter(num_param) + table_field_param = ModelerParameter(ParameterTableField('field', 'field desc')) + m.addParameter(table_field_param) + file_param = ModelerParameter(ParameterFile('file', 'file desc')) + m.addParameter(file_param) + + dlg = ModelerParametersDialog(m, m) + # test single types + self.assertEqual(set(p.name for p in dlg.getAvailableValuesOfType(ParameterNumber)), + set(['number'])) + self.assertEqual(set(p.name for p in dlg.getAvailableValuesOfType(ParameterTableField)), + set(['field'])) + self.assertEqual(set(p.name for p in dlg.getAvailableValuesOfType(ParameterFile)), + set(['file'])) + + +if __name__ == '__main__': + unittest.main() From dc800dbab7d797a740f6802f5a80b4e802461224 Mon Sep 17 00:00:00 2001 From: Alvaro Huarte Date: Fri, 11 Nov 2016 00:28:27 +0100 Subject: [PATCH 687/897] Fix iteration of features --- .../algs/qgis/SinglePartsToMultiparts.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py b/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py index 3ddbfd77aa2c..23bcbde2006c 100644 --- a/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py +++ b/python/plugins/processing/algs/qgis/SinglePartsToMultiparts.py @@ -70,7 +70,6 @@ def processAlgorithm(self, progress): writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields().toList(), geomType, layer.crs()) - inFeat = QgsFeature() outFeat = QgsFeature() inGeom = QgsGeometry() @@ -80,23 +79,18 @@ def processAlgorithm(self, progress): collection_attrs = {} features = vector.features(layer) - current = 0 - total = 100.0 / (len(features)) - - features = vector.features(layer) - for inFeat in features: - atMap = inFeat.attributes() + total = 100.0 / len(features) + for current, feature in enumerate(features): + atMap = feature.attributes() idVar = atMap[index] key = str(idVar).strip() if not key in collection_geom: collection_geom[key] = [] collection_attrs[key] = atMap - inGeom = inFeat.geometry() - vType = inGeom.type() + inGeom = feature.geometry() collection_geom[key].append(inGeom) - current += 1 progress.setPercentage(int(current * total)) for key, geoms in collection_geom.items(): From a3ae0b28fc280238ec46416dfd521b35b2ca4545 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 11:02:42 +1000 Subject: [PATCH 688/897] [processing] Restore spin box widget for number inputs outside modeller This commit restores some pre 3.0 processing behaviour for number inputs. Now, if a number input is required outside of modeller than a spin box will be shown instead of a free text input. Clicking the expression builder button results in an expression which is evaluated immediately to avoid users expecting that the expression will be evaluated per feature. --- .../processing/gui/NumberInputPanel.py | 214 +++++++++++++----- python/plugins/processing/gui/wrappers.py | 6 +- .../processing/ui/widgetNumberSelector.ui | 76 +++++++ 3 files changed, 235 insertions(+), 61 deletions(-) create mode 100644 python/plugins/processing/ui/widgetNumberSelector.ui diff --git a/python/plugins/processing/gui/NumberInputPanel.py b/python/plugins/processing/gui/NumberInputPanel.py index 0713be53526e..fd742aac2a4b 100644 --- a/python/plugins/processing/gui/NumberInputPanel.py +++ b/python/plugins/processing/gui/NumberInputPanel.py @@ -28,6 +28,7 @@ __revision__ = '$Format:%H$' import os +import math from qgis.PyQt import uic from qgis.PyQt.QtCore import pyqtSignal @@ -45,16 +46,25 @@ from processing.modeler.ModelerAlgorithm import ValueFromInput, ValueFromOutput, CompoundValue pluginPath = os.path.split(os.path.dirname(__file__))[0] +NUMBER_WIDGET, NUMBER_BASE = uic.loadUiType( + os.path.join(pluginPath, 'ui', 'widgetNumberSelector.ui')) WIDGET, BASE = uic.loadUiType( os.path.join(pluginPath, 'ui', 'widgetBaseSelector.ui')) -class NumberInputPanel(BASE, WIDGET): +class ModellerNumberInputPanel(BASE, WIDGET): + """ + Number input panel for use inside the modeller - this input panel + is based off the base input panel and includes a text based line input + for entering values. This allows expressions and other non-numeric + values to be set, which are later evalauted to numbers when the model + is run. + """ hasChanged = pyqtSignal() - def __init__(self, param, modelParametersDialog=None): - super(NumberInputPanel, self).__init__(None) + def __init__(self, param, modelParametersDialog): + super(ModellerNumberInputPanel, self).__init__(None) self.setupUi(self) self.param = param @@ -66,45 +76,46 @@ def __init__(self, param, modelParametersDialog=None): def showExpressionsBuilder(self): context = self.param.expressionContext() - dlg = QgsExpressionBuilderDialog(None, self.leText.text(), self, 'generic', context) - if self.modelParametersDialog is not None: - context.popScope() - values = self.modelParametersDialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) - variables = {} - for value in values: - if isinstance(value, ValueFromInput): - name = value.name - element = self.modelParametersDialog.model.inputs[name].param - desc = element.description - else: - name = "%s_%s" % (value.alg, value.output) - alg = self.modelParametersDialog.model.algs[value.alg] - out = alg.algorithm.getOutputFromName(value.output) - desc = "Output '%s' from algorithm '%s" % (out.description, alg.description) - variables[name] = desc - values = self.modelParametersDialog.getAvailableValuesOfType(ParameterVector, OutputVector) - values.extend(self.modelParametersDialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)) - for value in values: - if isinstance(value, ValueFromInput): - name = value.name - element = self.modelParametersDialog.model.inputs[name].param - desc = element.description - else: - name = "%s_%s" % (value.alg, value.output) - alg = self.modelParametersDialog.model.algs[value.alg] - element = alg.algorithm.getOutputFromName(value.output) - desc = "Output '%s' from algorithm '%s" % (element.description, alg.description) - variables['%s_minx' % name] = "Minimum X of %s" % desc - variables['%s_miny' % name] = "Maximum X of %s" % desc - variables['%s_maxx' % name] = "Minimum Y of %s" % desc - variables['%s_maxy' % name] = "Maximum Y of %s" % desc - if isinstance(element, (ParameterRaster, OutputRaster)): - variables['%s_min' % name] = "Minimum value of %s" % desc - variables['%s_max' % name] = "Maximum value of %s" % desc - variables['%s_avg' % name] = "Mean value of %s" % desc - variables['%s_stddev' % name] = "Standard deviation of %s" % desc - for variable, desc in variables.items(): - dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) + dlg = QgsExpressionBuilderDialog(None, str(self.leText.text()), self, 'generic', context) + + context.popScope() + values = self.modelParametersDialog.getAvailableValuesOfType(ParameterNumber, OutputNumber) + variables = {} + for value in values: + if isinstance(value, ValueFromInput): + name = value.name + element = self.modelParametersDialog.model.inputs[name].param + desc = element.description + else: + name = "%s_%s" % (value.alg, value.output) + alg = self.modelParametersDialog.model.algs[value.alg] + out = alg.algorithm.getOutputFromName(value.output) + desc = "Output '%s' from algorithm '%s" % (out.description, alg.description) + variables[name] = desc + values = self.modelParametersDialog.getAvailableValuesOfType(ParameterVector, OutputVector) + values.extend(self.modelParametersDialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)) + for value in values: + if isinstance(value, ValueFromInput): + name = value.name + element = self.modelParametersDialog.model.inputs[name].param + desc = element.description + else: + name = "%s_%s" % (value.alg, value.output) + alg = self.modelParametersDialog.model.algs[value.alg] + element = alg.algorithm.getOutputFromName(value.output) + desc = "Output '%s' from algorithm '%s" % (element.description, alg.description) + variables['%s_minx' % name] = "Minimum X of %s" % desc + variables['%s_miny' % name] = "Maximum X of %s" % desc + variables['%s_maxx' % name] = "Minimum Y of %s" % desc + variables['%s_maxy' % name] = "Maximum Y of %s" % desc + if isinstance(element, (ParameterRaster, OutputRaster)): + variables['%s_min' % name] = "Minimum value of %s" % desc + variables['%s_max' % name] = "Maximum value of %s" % desc + variables['%s_avg' % name] = "Mean value of %s" % desc + variables['%s_stddev' % name] = "Standard deviation of %s" % desc + for variable, desc in variables.items(): + dlg.expressionBuilder().registerItem("Modeler", variable, "@" + variable, desc, highlightedItem=True) + dlg.setWindowTitle(self.tr('Expression based input')) if dlg.exec_() == QDialog.Accepted: exp = QgsExpression(dlg.expressionText()) @@ -112,23 +123,110 @@ def showExpressionsBuilder(self): self.setValue(dlg.expressionText()) def getValue(self): - if self.modelParametersDialog: - value = self.leText.text() - values = [] - for param in self.modelParametersDialog.model.parameters: - if isinstance(param, ParameterNumber): - if "@" + param.name in value: - values.append(ValueFromInput(param.name)) - for alg in list(self.modelParametersDialog.model.algs.values()): - for out in alg.algorithm.outputs: - if isinstance(out, OutputNumber) and "@%s_%s" % (alg.name, out.name) in value: - values.append(ValueFromOutput(alg.name, out.name)) - if values: - return CompoundValue(values, value) - else: - return value + value = self.leText.text() + values = [] + for param in self.modelParametersDialog.model.parameters: + if isinstance(param, ParameterNumber): + if "@" + param.name in value: + values.append(ValueFromInput(param.name)) + for alg in list(self.modelParametersDialog.model.algs.values()): + for out in alg.algorithm.outputs: + if isinstance(out, OutputNumber) and "@%s_%s" % (alg.name, out.name) in value: + values.append(ValueFromOutput(alg.name, out.name)) + if values: + return CompoundValue(values, value) else: - return self.leText.text() + return value def setValue(self, value): self.leText.setText(str(value)) + + +class NumberInputPanel(NUMBER_BASE, NUMBER_WIDGET): + """ + Number input panel for use outside the modeller - this input panel + contains a user friendly spin box for entering values. It also + allows expressions to be evaluated, but these expressions are evaluated + immediately after entry and are not stored anywhere. + """ + + hasChanged = pyqtSignal() + + def __init__(self, param): + super(NumberInputPanel, self).__init__(None) + self.setupUi(self) + + self.spnValue.setExpressionsEnabled(True) + + self.param = param + if self.param.isInteger: + self.spnValue.setDecimals(0) + else: + # Guess reasonable step value + if self.param.max is not None and self.param.min is not None: + try: + self.spnValue.setSingleStep(self.calculateStep(float(self.param.min), float(self.param.max))) + except: + pass + + if self.param.max is not None: + self.spnValue.setMaximum(self.param.max) + else: + self.spnValue.setMaximum(999999999) + if self.param.min is not None: + self.spnValue.setMinimum(self.param.min) + else: + self.spnValue.setMinimum(-999999999) + + # set default value + if param.default is not None: + self.setValue(param.default) + try: + self.spnValue.setClearValue(float(param.default)) + except: + pass + elif self.param.min is not None: + try: + self.setValue(float(self.param.min)) + self.spnValue.setClearValue(float(self.param.min)) + except: + pass + else: + self.setValue(0) + self.spnValue.setClearValue(0) + self.btnSelect.setFixedHeight(self.spnValue.height()) + + self.btnSelect.clicked.connect(self.showExpressionsBuilder) + self.spnValue.valueChanged.connect(lambda: self.hasChanged.emit()) + + def showExpressionsBuilder(self): + context = self.param.expressionContext() + dlg = QgsExpressionBuilderDialog(None, str(self.spnValue.value()), self, 'generic', context) + + dlg.setWindowTitle(self.tr('Expression based input')) + if dlg.exec_() == QDialog.Accepted: + exp = QgsExpression(dlg.expressionText()) + if not exp.hasParserError(): + try: + val = float(exp.evaluate(context)) + self.setValue(val) + except: + return + + def getValue(self): + return self.spnValue.value() + + def setValue(self, value): + try: + self.spnValue.setValue(float(value)) + except: + return + + def calculateStep(self, minimum, maximum): + value_range = maximum - minimum + if value_range <= 1.0: + step = value_range / 10.0 + # round to 1 significant figrue + return round(step, -int(math.floor(math.log10(step)))) + else: + return 1.0 diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 516d536a89b9..a697b1293483 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -38,7 +38,7 @@ from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant -from processing.gui.NumberInputPanel import NumberInputPanel +from processing.gui.NumberInputPanel import NumberInputPanel, ModellerNumberInputPanel from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel from processing.modeler.MultilineTextPanel import MultilineTextPanel from processing.gui.CrsSelectionPanel import CrsSelectionPanel @@ -466,9 +466,9 @@ class NumberWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - return NumberInputPanel(self.param, None) + return NumberInputPanel(self.param) else: - return NumberInputPanel(self.param, self.dialog) + return ModellerNumberInputPanel(self.param, self.dialog) def setValue(self, value): self.widget.setValue(value) diff --git a/python/plugins/processing/ui/widgetNumberSelector.ui b/python/plugins/processing/ui/widgetNumberSelector.ui new file mode 100644 index 000000000000..f2ca01cefece --- /dev/null +++ b/python/plugins/processing/ui/widgetNumberSelector.ui @@ -0,0 +1,76 @@ + + + Form + + + + 0 + 0 + 249 + 37 + + + + Form + + + + 2 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + 6 + + + -9999999999999.000000000000000 + + + 9999999999999.000000000000000 + + + + + + + + 0 + 0 + + + + ... + + + + + + + + QgsDoubleSpinBox + QDoubleSpinBox +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgis.gui
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + 1 +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + + +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  From 72118f91f907acbb3947a6b882ba04ff7cef5233 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 9 Nov 2016 13:45:08 +1000 Subject: [PATCH 689/897] [processing] When an algorithm has string parameters, also accept numeric, file and table field inputs in modeler This allows a non-string parameter to be reused as a string parameter in contexts where it makes sense. --- python/plugins/processing/gui/wrappers.py | 4 +++- .../modeler/ModelerParametersDialog.py | 16 +++++++++++----- python/plugins/processing/tests/ModelerTest.py | 4 ++++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 516d536a89b9..67a0dfb969e8 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -643,7 +643,9 @@ def createWidget(self): if self.param.default: widget.setText(self.param.default) else: - strings = self.dialog.getAvailableValuesOfType(ParameterString, OutputString) + # strings, numbers, files and table fields are all allowed input types + strings = self.dialog.getAvailableValuesOfType([ParameterString, ParameterNumber, ParameterFile, + ParameterTableField], OutputString) options = [(self.dialog.resolveValueDescription(s), s) for s in strings] if self.param.multiline: widget = MultilineTextPanel(options) diff --git a/python/plugins/processing/modeler/ModelerParametersDialog.py b/python/plugins/processing/modeler/ModelerParametersDialog.py index 9c2de338da0a..0c4df307f36f 100644 --- a/python/plugins/processing/modeler/ModelerParametersDialog.py +++ b/python/plugins/processing/modeler/ModelerParametersDialog.py @@ -261,16 +261,22 @@ def showAdvancedParametersClicked(self): self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None, dataType=None): + # upgrade paramType to list + if type(paramType) is not list: + paramType = [paramType] + values = [] inputs = self.model.inputs for i in list(inputs.values()): param = i.param - if isinstance(param, paramType): - if dataType is not None: - if param.datatype in dataType: + for t in paramType: + if isinstance(param, t): + if dataType is not None: + if param.datatype in dataType: + values.append(ValueFromInput(param.name)) + else: values.append(ValueFromInput(param.name)) - else: - values.append(ValueFromInput(param.name)) + break if outType is None: return values if self._algName is None: diff --git a/python/plugins/processing/tests/ModelerTest.py b/python/plugins/processing/tests/ModelerTest.py index ad9b4b5ea873..7b4e9a71f3a7 100644 --- a/python/plugins/processing/tests/ModelerTest.py +++ b/python/plugins/processing/tests/ModelerTest.py @@ -62,6 +62,10 @@ def testModelerParametersDialogAvailableValuesOfType(self): self.assertEqual(set(p.name for p in dlg.getAvailableValuesOfType(ParameterFile)), set(['file'])) + # test multiple types + self.assertEqual(set(p.name for p in dlg.getAvailableValuesOfType([ParameterString, ParameterNumber, ParameterFile])), + set(['string', 'string2', 'number', 'file'])) + if __name__ == '__main__': unittest.main() From 132e76a596c71e3d559deef19c36b414c01630ec Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 3 Nov 2016 16:37:00 +1000 Subject: [PATCH 690/897] [FEATURE][processing] New input type for expressions This adds a new input type for expression inputs. Expression inputs can be linked to a parent layer so that the builder shows the correct fields and layer variables. It's designed for two use cases: 1. to be used when an algorithm specifically requires an expression, eg Select by Expression and Extract by Expression. 2. to be potentially used as a replacement input instead of string or number literals in algorithms. Eg - if the simplify algorithm tolerance parameter was replaced with an expression paremeter, then this expression would be evaluated for every feature before simplifying that feature. It would allow parameters to be calculated per feature, as opposed to the current approach of calculating a parameter once before running the algorithm. It would also mean algorithms like "variable distance buffer" would no longer be needed, as a single "buffer" algorithm could then be used for either a fixed distance, field based, or expression based distance. --- .../algs/qgis/ExtractByExpression.py | 6 +- .../algs/qgis/GeometryByExpression.py | 6 +- .../algs/qgis/SelectByExpression.py | 6 +- python/plugins/processing/core/parameters.py | 49 +++++++++++++ python/plugins/processing/gui/wrappers.py | 68 +++++++++++++++++-- .../ModelerParameterDefinitionDialog.py | 29 ++++++++ 6 files changed, 151 insertions(+), 13 deletions(-) diff --git a/python/plugins/processing/algs/qgis/ExtractByExpression.py b/python/plugins/processing/algs/qgis/ExtractByExpression.py index 4779758a3ae0..6895ac51ff4e 100644 --- a/python/plugins/processing/algs/qgis/ExtractByExpression.py +++ b/python/plugins/processing/algs/qgis/ExtractByExpression.py @@ -30,7 +30,7 @@ from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterString, ParameterExpression from processing.tools import dataobjects @@ -46,8 +46,8 @@ def defineCharacteristics(self): self.addParameter(ParameterVector(self.INPUT, self.tr('Input Layer'))) - self.addParameter(ParameterString(self.EXPRESSION, - self.tr("Expression"))) + self.addParameter(ParameterExpression(self.EXPRESSION, + self.tr("Expression"), parent_layer=self.INPUT)) self.addOutput(OutputVector(self.OUTPUT, self.tr('Extracted (expression)'))) def processAlgorithm(self, progress): diff --git a/python/plugins/processing/algs/qgis/GeometryByExpression.py b/python/plugins/processing/algs/qgis/GeometryByExpression.py index 364358ae6150..be927c09e088 100644 --- a/python/plugins/processing/algs/qgis/GeometryByExpression.py +++ b/python/plugins/processing/algs/qgis/GeometryByExpression.py @@ -30,7 +30,7 @@ from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.ProcessingLog import ProcessingLog -from processing.core.parameters import ParameterVector, ParameterSelection, ParameterBoolean, ParameterString +from processing.core.parameters import ParameterVector, ParameterSelection, ParameterBoolean, ParameterExpression from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector @@ -63,8 +63,8 @@ def defineCharacteristics(self): self.addParameter(ParameterBoolean(self.WITH_M, self.tr('Output geometry has m values'), False)) - self.addParameter(ParameterString(self.EXPRESSION, - self.tr("Geometry expression"), '$geometry')) + self.addParameter(ParameterExpression(self.EXPRESSION, + self.tr("Geometry expression"), '$geometry', parent_layer=self.INPUT_LAYER)) self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Modified geometry'))) diff --git a/python/plugins/processing/algs/qgis/SelectByExpression.py b/python/plugins/processing/algs/qgis/SelectByExpression.py index 68ee980a07cd..e2e8de5f82e2 100644 --- a/python/plugins/processing/algs/qgis/SelectByExpression.py +++ b/python/plugins/processing/algs/qgis/SelectByExpression.py @@ -30,7 +30,7 @@ from processing.core.parameters import ParameterSelection from processing.core.outputs import OutputVector from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterExpression from processing.tools import dataobjects @@ -52,8 +52,8 @@ def defineCharacteristics(self): self.addParameter(ParameterVector(self.LAYERNAME, self.tr('Input Layer'))) - self.addParameter(ParameterString(self.EXPRESSION, - self.tr("Expression"))) + self.addParameter(ParameterExpression(self.EXPRESSION, + self.tr("Expression"), parent_layer=self.LAYERNAME)) self.addParameter(ParameterSelection(self.METHOD, self.tr('Modify current selection by'), self.methods, 0)) self.addOutput(OutputVector(self.RESULT, self.tr('Selected (expression)'), True)) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index c31223394477..5123299fd23c 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1210,6 +1210,55 @@ def expressionContext(self): return _expressionContext() +class ParameterExpression(Parameter): + + default_metadata = { + 'widget_wrapper': 'processing.gui.wrappers.ExpressionWidgetWrapper' + } + + NEWLINE = '\n' + ESCAPED_NEWLINE = '\\n' + + def __init__(self, name='', description='', default=None, optional=False, parent_layer=None): + Parameter.__init__(self, name, description, default, optional) + self.parent_layer = parent_layer + + def setValue(self, obj): + if not bool(obj): + if not self.optional: + return False + self.value = None + return True + + self.value = str(obj).replace( + ParameterString.ESCAPED_NEWLINE, + ParameterString.NEWLINE + ) + return True + + def getValueAsCommandLineParameter(self): + return ('"' + str(self.value.replace(ParameterExpression.NEWLINE, + ParameterExpression.ESCAPED_NEWLINE)) + '"' + if self.value is not None else str(None)) + + def getAsScriptCode(self): + param_type = '' + if self.optional: + param_type += 'optional ' + param_type += 'expression' + return '##' + self.name + '=' + param_type + self.default + + @classmethod + def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) + descName = _createDescriptiveName(name) + default = definition.strip()[len('expression') + 1:] + if default: + return ParameterExpression(name, descName, default, optional=isOptional) + else: + return ParameterExpression(name, descName, optional=isOptional) + + class ParameterTable(ParameterDataObject): default_metadata = { diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 67a0dfb969e8..f9b4bca45458 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -36,6 +36,7 @@ from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit +from qgis.gui import QgsFieldExpressionWidget from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant from processing.gui.NumberInputPanel import NumberInputPanel @@ -43,9 +44,20 @@ from processing.modeler.MultilineTextPanel import MultilineTextPanel from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.PointSelectionPanel import PointSelectionPanel -from processing.core.parameters import (ParameterBoolean, ParameterPoint, ParameterFile, - ParameterRaster, ParameterVector, ParameterNumber, ParameterString, ParameterTable, - ParameterTableField, ParameterExtent, ParameterFixedTable, ParameterCrs, _resolveLayers) +from processing.core.parameters import (ParameterBoolean, + ParameterPoint, + ParameterFile, + ParameterRaster, + ParameterVector, + ParameterNumber, + ParameterString, + ParameterExpression, + ParameterTable, + ParameterTableField, + ParameterExtent, + ParameterFixedTable, + ParameterCrs, + _resolveLayers) from processing.core.ProcessingConfig import ProcessingConfig from processing.gui.FileSelectionPanel import FileSelectionPanel from processing.core.outputs import (OutputFile, OutputRaster, OutputVector, OutputNumber, @@ -645,7 +657,7 @@ def createWidget(self): else: # strings, numbers, files and table fields are all allowed input types strings = self.dialog.getAvailableValuesOfType([ParameterString, ParameterNumber, ParameterFile, - ParameterTableField], OutputString) + ParameterTableField, ParameterExpression], OutputString) options = [(self.dialog.resolveValueDescription(s), s) for s in strings] if self.param.multiline: widget = MultilineTextPanel(options) @@ -698,6 +710,54 @@ def validator(v): return self.comboValue(validator) +class ExpressionWidgetWrapper(WidgetWrapper): + + def createWidget(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + widget = QgsFieldExpressionWidget() + if self.param.default: + widget.setExpression(self.param.default) + else: + strings = self.dialog.getAvailableValuesOfType([ParameterExpression, ParameterString, ParameterNumber], OutputString) + options = [(self.dialog.resolveValueDescription(s), s) for s in strings] + widget = QComboBox() + widget.setEditable(True) + for desc, val in options: + widget.addItem(desc, val) + widget.setEditText(self.param.default or "") + return widget + + def postInitialize(self, wrappers): + for wrapper in wrappers: + if wrapper.param.name == self.param.parent_layer: + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.setLayer(wrapper.value()) + wrapper.widgetValueHasChanged.connect(self.parentLayerChanged) + break + + def parentLayerChanged(self, wrapper): + self.setLayer(wrapper.value()) + + def setLayer(self, layer): + if isinstance(layer, str): + layer = dataobjects.getObjectFromUri(_resolveLayers(layer)) + self.widget.setLayer(layer) + + def setValue(self, value): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + self.widget.setExpression(value) + else: + self.setComboValue(value) + + def value(self): + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): + return self.widget.asExpression() + else: + def validator(v): + return bool(v) or self.param.optional + return self.comboValue(validator) + + class TableWidgetWrapper(WidgetWrapper): NOT_SELECTED = '[Not selected]' diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index d81b78384a28..08b3c51ac560 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -28,6 +28,7 @@ import math +from qgis.gui import QgsExpressionLineEdit from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtWidgets import (QDialog, QVBoxLayout, @@ -47,6 +48,7 @@ ParameterMultipleInput, ParameterNumber, ParameterString, + ParameterExpression, ParameterTableField, ParameterExtent, ParameterFile, @@ -62,6 +64,7 @@ class ModelerParameterDefinitionDialog(QDialog): PARAMETER_TABLE = 'Table' PARAMETER_VECTOR = 'Vector layer' PARAMETER_STRING = 'String' + PARAMETER_EXPRESSION = 'Expression' PARAMETER_BOOLEAN = 'Boolean' PARAMETER_TABLE_FIELD = 'Table field' PARAMETER_EXTENT = 'Extent' @@ -77,6 +80,7 @@ class ModelerParameterDefinitionDialog(QDialog): PARAMETER_NUMBER, PARAMETER_RASTER, PARAMETER_STRING, + PARAMETER_EXPRESSION, PARAMETER_TABLE, PARAMETER_TABLE_FIELD, PARAMETER_VECTOR, @@ -196,6 +200,25 @@ def setupUi(self): if default: self.defaultTextBox.setText(str(default)) self.verticalLayout.addWidget(self.defaultTextBox) + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXPRESSION or + isinstance(self.param, ParameterExpression)): + self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) + self.defaultEdit = QgsExpressionLineEdit() + if self.param is not None: + self.defaultEdit.setExpression(self.param.default) + self.verticalLayout.addWidget(self.defaultEdit) + + self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) + self.parentCombo = QComboBox() + idx = 0 + for param in list(self.alg.inputs.values()): + if isinstance(param.param, (ParameterVector, ParameterTable)): + self.parentCombo.addItem(param.param.description, param.param.name) + if self.param is not None: + if self.param.parent_layer == param.param.name: + self.parentCombo.setCurrentIndex(idx) + idx += 1 + self.verticalLayout.addWidget(self.parentCombo) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or isinstance(self.param, ParameterString)): self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) @@ -314,6 +337,12 @@ def okPressed(self): QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return + elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXPRESSION or + isinstance(self.param, ParameterExpression)): + parent = self.parentCombo.itemData(self.parentCombo.currentIndex()) + self.param = ParameterExpression(name, description, + default=str(self.defaultEdit.expression()), + parent_layer=parent) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or isinstance(self.param, ParameterString)): self.param = ParameterString(name, description, From 5625d6e9b6868de22b151313f446d1c44309017e Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 12:03:33 +1000 Subject: [PATCH 691/897] Expression parameters don't have to have parent layers --- python/plugins/processing/gui/wrappers.py | 7 +++++-- .../processing/modeler/ModelerParameterDefinitionDialog.py | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index f9b4bca45458..92491c28b438 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -36,7 +36,7 @@ from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit -from qgis.gui import QgsFieldExpressionWidget +from qgis.gui import QgsFieldExpressionWidget, QgsExpressionLineEdit from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant from processing.gui.NumberInputPanel import NumberInputPanel @@ -714,7 +714,10 @@ class ExpressionWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - widget = QgsFieldExpressionWidget() + if self.param.parent_layer: + widget = QgsFieldExpressionWidget() + else: + widget = QgsExpressionLineEdit() if self.param.default: widget.setExpression(self.param.default) else: diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 08b3c51ac560..93dc8b727d6d 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -210,7 +210,8 @@ def setupUi(self): self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() - idx = 0 + self.parentCombo.addItem(self.tr("None"), None) + idx = 1 for param in list(self.alg.inputs.values()): if isinstance(param.param, (ParameterVector, ParameterTable)): self.parentCombo.addItem(param.param.description, param.param.name) From 156fce989d29e149ce7d9d8db2975e9e032f581f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 12:59:22 +1000 Subject: [PATCH 692/897] Add unit tests for processing expression parameter --- .../processing/tests/ParametersTest.py | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index e98d424fb9fd..a73b992ec7fd 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -40,7 +40,8 @@ ParameterString, ParameterVector, ParameterTableField, - ParameterSelection) + ParameterSelection, + ParameterExpression) from processing.tools import dataobjects from processing.tests.TestData import points2 @@ -462,7 +463,30 @@ def testOptional(self): self.assertTrue(optionalParameter.setValue(None)) self.assertEqual(optionalParameter.value, None) - requiredParameter = ParameterCrs('myName', 'myDesc', default='test', optional=False) + requiredParameter = ParameterString('myName', 'myDesc', default='test', optional=False) + self.assertEqual(requiredParameter.value, 'test') + requiredParameter.setValue('check') + self.assertEqual(requiredParameter.value, 'check') + self.assertFalse(requiredParameter.setValue(None)) + self.assertEqual(requiredParameter.value, 'check') + + +class ParameterExpressionTest(unittest.TestCase): + + def testSetValue(self): + parameter = ParameterExpression('myName', 'myDescription') + self.assertTrue(parameter.setValue('\'a\' || "field"')) + self.assertEqual(parameter.value, '\'a\' || "field"') + + def testOptional(self): + optionalParameter = ParameterExpression('myName', 'myDesc', default='test', optional=True) + self.assertEqual(optionalParameter.value, 'test') + optionalParameter.setValue('check') + self.assertEqual(optionalParameter.value, 'check') + self.assertTrue(optionalParameter.setValue(None)) + self.assertEqual(optionalParameter.value, None) + + requiredParameter = ParameterExpression('myName', 'myDesc', default='test', optional=False) self.assertEqual(requiredParameter.value, 'test') requiredParameter.setValue('check') self.assertEqual(requiredParameter.value, 'check') From be2223fed38b0a2c7af26a207e5d8154adbdcdc9 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 11 Nov 2016 12:21:39 +0700 Subject: [PATCH 693/897] [processing] check for parent alg dependencies in hasDependencies() --- .../processing/modeler/ModelerAlgorithm.py | 4 +++ .../plugins/processing/tests/ModelerTest.py | 26 ++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/modeler/ModelerAlgorithm.py b/python/plugins/processing/modeler/ModelerAlgorithm.py index 15d5aafff6ec..3af5081806f3 100644 --- a/python/plugins/processing/modeler/ModelerAlgorithm.py +++ b/python/plugins/processing/modeler/ModelerAlgorithm.py @@ -360,6 +360,10 @@ def hasDependencies(self, name): elif isinstance(value, ValueFromOutput): if value.alg == name: return True + if alg.name != name: + for dep in alg.dependencies: + if (dep == name): + return True return False def getDependsOnAlgorithms(self, name): diff --git a/python/plugins/processing/tests/ModelerTest.py b/python/plugins/processing/tests/ModelerTest.py index 7b4e9a71f3a7..a76366a60a8d 100644 --- a/python/plugins/processing/tests/ModelerTest.py +++ b/python/plugins/processing/tests/ModelerTest.py @@ -27,7 +27,11 @@ from qgis.testing import start_app, unittest -from processing.modeler.ModelerAlgorithm import (ModelerAlgorithm, ModelerParameter) +from processing.modeler.ModelerAlgorithm import (Algorithm, + ModelerAlgorithm, + ModelerParameter, + ModelerOutput, + ValueFromOutput) from processing.modeler.ModelerParametersDialog import (ModelerParametersDialog) from processing.core.parameters import (ParameterFile, ParameterNumber, @@ -66,6 +70,26 @@ def testModelerParametersDialogAvailableValuesOfType(self): self.assertEqual(set(p.name for p in dlg.getAvailableValuesOfType([ParameterString, ParameterNumber, ParameterFile])), set(['string', 'string2', 'number', 'file'])) + def testModelerAlgorithmHasDependencies(self): + # test hasDependencies from ModelerAlgorithm + + m = ModelerAlgorithm() + + a = Algorithm("qgis:clip") + m.addAlgorithm(a) + a2 = Algorithm("qgis:clip") + m.addAlgorithm(a2) + + # test parent algorithm dependency + self.assertEqual(m.hasDependencies('QGISCLIP_1'), False) + a2.dependencies = ['QGISCLIP_1'] + self.assertEqual(m.hasDependencies('QGISCLIP_1'), True) + + # test output algorithm dependency + a2.dependencies = [] + a.outputs['OUTPUT'] = ModelerOutput('out') + a2.params['INPUT'] = ValueFromOutput('QGISCLIP_1', 'OUTPUT') + self.assertEqual(m.hasDependencies('QGISCLIP_1'), True) if __name__ == '__main__': unittest.main() From 35d106bf648f7e9b21a0be9286b8b3abd7b41460 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 11 Nov 2016 08:56:12 +0100 Subject: [PATCH 694/897] Fix Qt 5.7 build warnings --- src/gui/qgscolorwidgets.cpp | 6 +++--- src/gui/qgsgradientstopeditor.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gui/qgscolorwidgets.cpp b/src/gui/qgscolorwidgets.cpp index 439314f3f90a..f75d142e6a5f 100644 --- a/src/gui/qgscolorwidgets.cpp +++ b/src/gui/qgscolorwidgets.cpp @@ -409,7 +409,7 @@ void QgsColorWheel::paintEvent( QPaintEvent *event ) QPainter painter( this ); //draw a frame - QStyleOptionFrameV3 option = QStyleOptionFrameV3(); + QStyleOptionFrame option = QStyleOptionFrame(); option.initFrom( this ); option.state = this->hasFocus() ? QStyle::State_Active : QStyle::State_None; style()->drawPrimitive( QStyle::PE_Frame, &option, &painter ); @@ -774,7 +774,7 @@ void QgsColorBox::paintEvent( QPaintEvent *event ) Q_UNUSED( event ); QPainter painter( this ); - QStyleOptionFrameV3 option; + QStyleOptionFrame option; option.initFrom( this ); option.state = hasFocus() ? QStyle::State_Active : QStyle::State_None; style()->drawPrimitive( QStyle::PE_Frame, &option, &painter ); @@ -1020,7 +1020,7 @@ void QgsColorRampWidget::paintEvent( QPaintEvent *event ) if ( mShowFrame ) { //draw frame - QStyleOptionFrameV3 option; + QStyleOptionFrame option; option.initFrom( this ); option.state = hasFocus() ? QStyle::State_KeyboardFocusChange : QStyle::State_None; style()->drawPrimitive( QStyle::PE_Frame, &option, &painter ); diff --git a/src/gui/qgsgradientstopeditor.cpp b/src/gui/qgsgradientstopeditor.cpp index 2d2e4c7d84c4..3fa46cab0e52 100644 --- a/src/gui/qgsgradientstopeditor.cpp +++ b/src/gui/qgsgradientstopeditor.cpp @@ -83,7 +83,7 @@ void QgsGradientStopEditor::paintEvent( QPaintEvent *event ) rect().height() - MARGIN_BOTTOM ); //draw frame - QStyleOptionFrameV3 option; + QStyleOptionFrame option; option.initFrom( this ); option.state = hasFocus() ? QStyle::State_KeyboardFocusChange : QStyle::State_None; option.rect = frameRect; From f3d7e39abb64b051946757655cb59ba7986f85c5 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 11 Nov 2016 15:00:52 +0700 Subject: [PATCH 695/897] [processing] harmonize modeler UI behavior with QGIS - use [close without saving][cancel][save] option when closing a modeler with unsaved changes - invert mouse wheel zoom in/out to match that of QGIS' main canvas window - holding the mouse middle click and dragging will pan the modeler view --- .../processing/modeler/ModelerDialog.py | 40 +++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index 5de22a596869..2e0426dba17f 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -112,9 +112,15 @@ def _dragMoveEvent(event): def _wheelEvent(event): self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) - factor = 1.05 - if event.angleDelta().y() > 0: + + settings = QSettings() + factor = settings.value('/qgis/zoom_favor', 2.0) + if (event.modifiers() == Qt.ControlModifier): + factor = 1.0 + (factor - 1.0) / 20.0 + + if event.angleDelta().y() < 0: factor = 1 / factor + self.view.scale(factor, factor) self.repaintModel() @@ -130,6 +136,22 @@ def _mouseReleaseEvent(e): QGraphicsView.mouseReleaseEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) + def _mousePressEvent(e): + if e.button() == Qt.MidButton: + self.previousMousePos = e.pos() + else: + QGraphicsView.mousePressEvent(self.view, e) + + def _mouseMoveEvent(e): + if e.buttons() == Qt.MidButton: + offset = self.previousMousePos - e.pos() + self.previousMousePos = e.pos() + + self.view.verticalScrollBar().setValue(self.view.verticalScrollBar().value() + offset.y()) + self.view.horizontalScrollBar().setValue(self.view.horizontalScrollBar().value() + offset.x()) + else: + QGraphicsView.mouseMoveEvent(self.view, e) + self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.dragEnterEvent = _dragEnterEvent self.view.dropEvent = _dropEvent @@ -137,7 +159,8 @@ def _mouseReleaseEvent(e): self.view.wheelEvent = _wheelEvent self.view.enterEvent = _enterEvent self.view.mousePressEvent = _mousePressEvent - self.view.mouseReleaseEvent = _mouseReleaseEvent + self.view.mousePressEvent = _mousePressEvent + self.view.mouseMoveEvent = _mouseMoveEvent def _mimeDataInput(items): mimeData = QMimeData() @@ -217,11 +240,14 @@ def closeEvent(self, evt): if self.hasChanged: ret = QMessageBox.question( - self, self.tr('Unsaved changes'), - self.tr('There are unsaved changes in model. Continue?'), - QMessageBox.Yes | QMessageBox.No, QMessageBox.No) + self, self.tr('Save?'), + self.tr('There are unsaved changes in this model, do you want to keep those?'), + QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard, QMessageBox.Cancel) - if ret == QMessageBox.Yes: + if ret == QMessageBox.Save: + self.saveModel(False) + evt.accept() + elif ret == QMessageBox.Discard: evt.accept() else: evt.ignore() From 28d7ceaef5546415e2e359202fef00cbc07ed3d0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 20:12:58 +1000 Subject: [PATCH 696/897] Some fixes to processing expression parameters --- python/plugins/processing/core/parameters.py | 13 +++++++------ python/plugins/processing/gui/wrappers.py | 5 ++++- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 5123299fd23c..4e3126f9d3d8 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1251,12 +1251,13 @@ def getAsScriptCode(self): @classmethod def fromScriptCode(self, line): isOptional, name, definition = _splitParameterOptions(line) - descName = _createDescriptiveName(name) - default = definition.strip()[len('expression') + 1:] - if default: - return ParameterExpression(name, descName, default, optional=isOptional) - else: - return ParameterExpression(name, descName, optional=isOptional) + if definition.lower().strip().startswith('expression'): + descName = _createDescriptiveName(name) + default = definition.strip()[len('expression') + 1:] + if default: + return ParameterExpression(name, descName, default, optional=isOptional) + else: + return ParameterExpression(name, descName, optional=isOptional) class ParameterTable(ParameterDataObject): diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 92491c28b438..8cc56236ace3 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -754,7 +754,10 @@ def setValue(self, value): def value(self): if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): - return self.widget.asExpression() + try: + return self.widget.asExpression() + except: + return self.widget.expression() else: def validator(v): return bool(v) or self.param.optional From 054d4308596a7abac06730fef99142e40c33532c Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 11 Nov 2016 12:10:43 +0100 Subject: [PATCH 697/897] [spatialite] Don't skip default values When inserting multiple features in a single prepared statement, the spatialite provider would skip any default for individual features, even though they have been specified in the field list, resulting in missing fields. --- src/providers/spatialite/qgsspatialiteprovider.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index e483b43a8d6c..99320856cb71 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -3764,9 +3764,6 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist ) for ( int i = 0; i < attributevec.count(); ++i ) { - if ( !attributevec.at( i ).isValid() ) - continue; - if ( i >= mAttributeFields.count() ) continue; @@ -3822,8 +3819,6 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist ) for ( int i = 0; i < attributevec.count(); ++i ) { QVariant v = attributevec.at( i ); - if ( !v.isValid() ) - continue; // binding values for each attribute if ( i >= mAttributeFields.count() ) @@ -3835,7 +3830,11 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist ) QVariant::Type type = mAttributeFields.at( i ).type(); - if ( v.isNull() ) + if ( !v.isValid() ) + { + ++ia; + } + else if ( v.isNull() ) { // binding a NULL value sqlite3_bind_null( stmt, ++ia ); From 45617fb2928a9192b1bfcb2fb822b9186df6a650 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 11 Nov 2016 15:43:21 +0100 Subject: [PATCH 698/897] Fix more Qt5.7 warnings --- src/app/qgswelcomepageitemsmodel.cpp | 2 +- src/gui/qgsvariableeditorwidget.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/qgswelcomepageitemsmodel.cpp b/src/app/qgswelcomepageitemsmodel.cpp index 585f00fb75f6..680eb015a18d 100644 --- a/src/app/qgswelcomepageitemsmodel.cpp +++ b/src/app/qgswelcomepageitemsmodel.cpp @@ -39,7 +39,7 @@ void QgsWelcomePageItemDelegate::paint( QPainter* painter, const QStyleOptionVie QPixmap icon = qvariant_cast( index.data( Qt::DecorationRole ) ); QAbstractTextDocumentLayout::PaintContext ctx; - QStyleOptionViewItemV4 optionV4 = option; + QStyleOptionViewItem optionV4 = option; QColor color; if ( option.state & QStyle::State_Selected && option.state & QStyle::State_HasFocus ) diff --git a/src/gui/qgsvariableeditorwidget.cpp b/src/gui/qgsvariableeditorwidget.cpp index 38f721ee17c3..88392dc43190 100644 --- a/src/gui/qgsvariableeditorwidget.cpp +++ b/src/gui/qgsvariableeditorwidget.cpp @@ -479,7 +479,7 @@ void QgsVariableEditorTree::emitChanged() void QgsVariableEditorTree::drawRow( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { - QStyleOptionViewItemV3 opt = option; + QStyleOptionViewItem opt = option; QTreeWidgetItem* item = itemFromIndex( index ); if ( index.parent().isValid() ) { From 4981bfcf180f637726d2a5d4140561b2267a3ca5 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Fri, 11 Nov 2016 16:55:57 +0100 Subject: [PATCH 699/897] Fix memory leak --- python/core/layertree/qgslayertreenode.sip | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/core/layertree/qgslayertreenode.sip b/python/core/layertree/qgslayertreenode.sip index 0f5be693215d..7ba27fbde597 100644 --- a/python/core/layertree/qgslayertreenode.sip +++ b/python/core/layertree/qgslayertreenode.sip @@ -77,7 +77,7 @@ class QgsLayerTreeNode : QObject QList children(); //! Read layer tree from XML. Returns new instance - static QgsLayerTreeNode *readXml( QDomElement &element ); + static QgsLayerTreeNode* readXml( QDomElement& element ) /Factory/; //! Write layer tree to XML virtual void writeXml( QDomElement &parentElement ) = 0; From 4e96912c913d8812f46b30a233897bc4c58621d6 Mon Sep 17 00:00:00 2001 From: Alessandro Pasotti Date: Wed, 9 Nov 2016 15:43:09 +0100 Subject: [PATCH 700/897] [bugfix][forwardport] File downloader for identify dialog hyperlinks fixes #14703 Include C++ and Python tests Travis won: ported all test cases to Python and disabled C++ companion test (still useful locally and for debugging) For the curious: QTemporaryFile is not working as expected Moved to Qt5 new style signals Disabled C++ test and connected cancel to progress Make string comparison on SSL errors more robust --- ci/travis/linux/script.sh | 2 +- python/gui/gui.sip | 1 + python/gui/qgsfiledownloader.sip | 68 ++++++ src/app/qgsidentifyresultsdialog.cpp | 52 +++++ src/app/qgsidentifyresultsdialog.h | 7 + src/gui/CMakeLists.txt | 3 + src/gui/qgsfiledownloader.cpp | 203 ++++++++++++++++ src/gui/qgsfiledownloader.h | 117 ++++++++++ tests/src/gui/CMakeLists.txt | 2 + tests/src/gui/testqgsfiledownloader.cpp | 254 +++++++++++++++++++++ tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgsfiledownloader.py | 147 ++++++++++++ 12 files changed, 856 insertions(+), 1 deletion(-) create mode 100644 python/gui/qgsfiledownloader.sip create mode 100644 src/gui/qgsfiledownloader.cpp create mode 100644 src/gui/qgsfiledownloader.h create mode 100644 tests/src/gui/testqgsfiledownloader.cpp create mode 100644 tests/src/python/test_qgsfiledownloader.py diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 09d1ace4c24d..8c06eeb8e7d9 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -24,5 +24,5 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Set OTB application path (installed in before_install.sh script) export OTB_APPLICATION_PATH=${HOME}/OTB-5.6.0-Linux64/lib/otb/applications -xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_filedownloader|qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure diff --git a/python/gui/gui.sip b/python/gui/gui.sip index db7c97cff9e7..88c27f32972a 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -77,6 +77,7 @@ %Include qgsfieldvalidator.sip %Include qgsfiledropedit.sip %Include qgsfilewidget.sip +%Include qgsfiledownloader.sip %Include qgsfilterlineedit.sip %Include qgsfocuswatcher.sip %Include qgsformannotationitem.sip diff --git a/python/gui/qgsfiledownloader.sip b/python/gui/qgsfiledownloader.sip new file mode 100644 index 000000000000..315ea32e7505 --- /dev/null +++ b/python/gui/qgsfiledownloader.sip @@ -0,0 +1,68 @@ +/*************************************************************************** + qgsfiledownloader.sip + -------------------------------------- + Date : November 2016 + Copyright : (C) 2016 by Alessandro Pasotti + Email : elpaso at itopen dot it + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +/** \ingroup gui + * QgsFileDownloader is a utility class for downloading files. + * + * To use this class, it is necessary to pass the URL and an output file name as + * arguments to the constructor, the download will start immediately. + * The download is asynchronous and depending on the guiNotificationsEnabled + * parameter accepted by the constructor (default = true) the class will + * show a progress dialog and report all errors in a QMessageBox::warning dialog. + * If the guiNotificationsEnabled parameter is set to false, the class can still + * be used through the signals and slots mechanism. + * The object will destroy itself when the request completes, errors or is canceled. + * + * @note added in QGIS 2.18.1 + */ +class QgsFileDownloader : public QObject +{ + %TypeHeaderCode + #include + %End + public: + /** + * QgsFileDownloader + * @param url the download url + * @param outputFileName file name where the downloaded content will be stored + * @param guiNotificationsEnabled if false, the downloader will not display any progress bar or error message + */ + QgsFileDownloader(QUrl url, QString outputFileName, bool guiNotificationsEnabled = true); + + signals: + /** Emitted when the download has completed successfully */ + void downloadCompleted(); + /** Emitted always when the downloader exits */ + void downloadExited(); + /** Emitted when the download was canceled by the user */ + void downloadCanceled(); + /** Emitted when an error makes the download fail */ + void downloadError( QStringList errorMessages ); + /** Emitted when data ready to be processed */ + void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); + + public slots: + /** + * Called when a download is canceled by the user + * this slot aborts the download and deletes the object + * Never call this slot directly: this is meant to + * be managed by the signal-slot system. + */ + void onDownloadCanceled(); + + private: + ~QgsFileDownloader(); + +}; diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index 885064847575..a51ab7dd5c7d 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -42,6 +42,7 @@ #include "qgswebframe.h" #include "qgsstringutils.h" #include "qgstreewidgetitem.h" +#include "qgsfiledownloader.h" #include #include @@ -59,6 +60,11 @@ #include #include #include +#include +#include +#include +#include +#include //graph #include @@ -72,6 +78,7 @@ QgsIdentifyResultsWebView::QgsIdentifyResultsWebView( QWidget *parent ) : QgsWeb setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Minimum ); page()->setNetworkAccessManager( QgsNetworkAccessManager::instance() ); // page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); + page()->setForwardUnsupportedContent( true ); page()->setLinkDelegationPolicy( QWebPage::DontDelegateLinks ); settings()->setAttribute( QWebSettings::LocalContentCanAccessRemoteUrls, true ); settings()->setAttribute( QWebSettings::JavascriptCanOpenWindows, true ); @@ -79,6 +86,51 @@ QgsIdentifyResultsWebView::QgsIdentifyResultsWebView( QWidget *parent ) : QgsWeb #ifdef QGISDEBUG settings()->setAttribute( QWebSettings::DeveloperExtrasEnabled, true ); #endif + connect( page(), SIGNAL( downloadRequested( QNetworkRequest ) ), this, SLOT( downloadRequested( QNetworkRequest ) ) ); + connect( page(), SIGNAL( unsupportedContent( QNetworkReply* ) ), this, SLOT( unsupportedContent( QNetworkReply* ) ) ); +} + + +void QgsIdentifyResultsWebView::downloadRequested( const QNetworkRequest &request ) +{ + handleDownload( request.url() ); +} + +void QgsIdentifyResultsWebView::unsupportedContent( QNetworkReply * reply ) +{ + handleDownload( reply->url() ); +} + +void QgsIdentifyResultsWebView::handleDownload( QUrl url ) +{ + if ( ! url.isValid() ) + { + QMessageBox::warning( this, tr( "Invalid URL" ), tr( "The download URL is not valid: %1" ).arg( url.toString( ) ) ); + } + else + { + const QString DOWNLOADER_LAST_DIR_KEY( "Qgis/fileDownloaderLastDir" ); + QSettings settings; + // Try to get some information from the URL + QFileInfo info( url.toString( ) ); + QString savePath = settings.value( DOWNLOADER_LAST_DIR_KEY ).toString( ); + QString fileName = info.fileName().replace( QRegExp( "[^A-z0-9\\-_\\.]" ), "_" ); + if ( ! savePath.isEmpty() && ! fileName.isEmpty( ) ) + { + savePath = QDir::cleanPath( savePath + QDir::separator() + fileName ); + } + QString targetFile = QFileDialog::getSaveFileName( this, + tr( "Save as" ), + savePath, + info.suffix( ).isEmpty() ? QString( ) : "*." + info.suffix( ) + ); + if ( ! targetFile.isEmpty() ) + { + settings.setValue( DOWNLOADER_LAST_DIR_KEY, QFileInfo( targetFile ).dir().absolutePath( ) ); + // Start the download + new QgsFileDownloader( url, targetFile ); + } + } } void QgsIdentifyResultsWebView::print() diff --git a/src/app/qgsidentifyresultsdialog.h b/src/app/qgsidentifyresultsdialog.h index b1c88090bd10..0436ab1a000b 100644 --- a/src/app/qgsidentifyresultsdialog.h +++ b/src/app/qgsidentifyresultsdialog.h @@ -28,6 +28,9 @@ #include #include +#include +#include +#include class QCloseEvent; class QTreeWidgetItem; @@ -57,9 +60,13 @@ class APP_EXPORT QgsIdentifyResultsWebView : public QgsWebView QSize sizeHint() const override; public slots: void print(); + void downloadRequested( const QNetworkRequest &request ); + void unsupportedContent( QNetworkReply *reply ); protected: void contextMenuEvent( QContextMenuEvent* ) override; QgsWebView *createWindow( QWebPage::WebWindowType type ) override; + private: + void handleDownload( QUrl url ); }; class APP_EXPORT QgsIdentifyResultsFeatureItem: public QTreeWidgetItem diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index f2c0dc0c176a..3dceb74b66e5 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -317,6 +317,7 @@ SET(QGIS_GUI_SRCS qgsuserinputdockwidget.cpp qgsvariableeditorwidget.cpp qgsvertexmarker.cpp + qgsfiledownloader.cpp ) IF (WITH_QTWEBKIT) @@ -471,6 +472,7 @@ SET(QGIS_GUI_MOC_HDRS qgsunitselectionwidget.h qgsuserinputdockwidget.h qgsvariableeditorwidget.h + qgsfiledownloader.h raster/qgsmultibandcolorrendererwidget.h raster/qgspalettedrendererwidget.h @@ -664,6 +666,7 @@ SET(QGIS_GUI_HDRS qgsuserinputdockwidget.h qgsvectorlayertools.h qgsvertexmarker.h + qgsfiledownloader.h attributetable/qgsfeaturemodel.h diff --git a/src/gui/qgsfiledownloader.cpp b/src/gui/qgsfiledownloader.cpp new file mode 100644 index 000000000000..761d8a105600 --- /dev/null +++ b/src/gui/qgsfiledownloader.cpp @@ -0,0 +1,203 @@ +/*************************************************************************** + qgsfiledownloader.cpp + -------------------------------------- + Date : November 2016 + Copyright : (C) 2016 by Alessandro Pasotti + Email : apasotti at boundlessgeo dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgsfiledownloader.h" +#include "qgsnetworkaccessmanager.h" + +#include +#include +#include +#include +#ifndef QT_NO_OPENSSL +#include +#endif + +QgsFileDownloader::QgsFileDownloader( QUrl url, QString outputFileName, bool enableGuiNotifications ) + : mUrl( url ) + , mReply( nullptr ) + , mProgressDialog( nullptr ) + , mDownloadCanceled( false ) + , mErrors() + , mGuiNotificationsEnabled( enableGuiNotifications ) +{ + mFile.setFileName( outputFileName ); + startDownload(); +} + + +QgsFileDownloader::~QgsFileDownloader() +{ + if ( mReply ) + { + mReply->abort(); + mReply->deleteLater(); + } + if ( mProgressDialog ) + { + mProgressDialog->deleteLater(); + } +} + + +void QgsFileDownloader::startDownload() +{ + QgsNetworkAccessManager* nam = QgsNetworkAccessManager::instance(); + + QNetworkRequest request( mUrl ); + + mReply = nam->get( request ); + + connect( mReply, &QNetworkReply::readyRead, this, &QgsFileDownloader::onReadyRead ); + connect( mReply, static_cast < void ( QNetworkReply::* )( QNetworkReply::NetworkError ) > ( &QNetworkReply::error ), this, &QgsFileDownloader::onNetworkError ); + connect( mReply, &QNetworkReply::finished, this, &QgsFileDownloader::onFinished ); + connect( mReply, &QNetworkReply::downloadProgress, this, &QgsFileDownloader::onDownloadProgress ); + connect( nam, &QgsNetworkAccessManager::requestTimedOut, this, &QgsFileDownloader::onRequestTimedOut ); +#ifndef QT_NO_OPENSSL + connect( nam, &QgsNetworkAccessManager::sslErrors, this, &QgsFileDownloader::onSslErrors ); +#endif + if ( mGuiNotificationsEnabled ) + { + mProgressDialog = new QProgressDialog(); + mProgressDialog->setWindowTitle( tr( "Download" ) ); + mProgressDialog->setLabelText( tr( "Downloading %1." ).arg( mFile.fileName() ) ); + mProgressDialog->show(); + connect( mProgressDialog, &QProgressDialog::canceled, this, &QgsFileDownloader::onDownloadCanceled ); + } +} + +void QgsFileDownloader::onDownloadCanceled() +{ + mDownloadCanceled = true; + emit downloadCanceled(); + onFinished(); +} + +void QgsFileDownloader::onRequestTimedOut() +{ + error( tr( "Network request %1 timed out" ).arg( mUrl.toString() ) ); +} + +#ifndef QT_NO_OPENSSL +void QgsFileDownloader::onSslErrors( QNetworkReply *reply, const QList &errors ) +{ + Q_UNUSED( reply ); + QStringList errorMessages; + errorMessages << "SSL Errors: "; + for ( auto end = errors.size(), i = 0; i != end; ++i ) + { + errorMessages << errors[i].errorString(); + } + error( errorMessages ); +} +#endif + + +void QgsFileDownloader::error( QStringList errorMessages ) +{ + for ( auto end = errorMessages.size(), i = 0; i != end; ++i ) + { + mErrors.append( errorMessages[i] ); + } + // Show error + if ( mGuiNotificationsEnabled ) + { + QMessageBox::warning( nullptr, tr( "Download failed" ), mErrors.join( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " ) ); + } + emit downloadError( mErrors ); +} + +void QgsFileDownloader::error( QString errorMessage ) +{ + error( QStringList() << errorMessage ); +} + +void QgsFileDownloader::onReadyRead() +{ + Q_ASSERT( mReply ); + if ( ! mFile.isOpen() && ! mFile.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) + { + error( tr( "Cannot open output file: %1" ).arg( mFile.fileName() ) ); + onFinished(); + } + else + { + QByteArray data = mReply->readAll(); + mFile.write( data ); + } +} + +void QgsFileDownloader::onFinished() +{ + // when canceled + if ( ! mErrors.isEmpty() || mDownloadCanceled ) + { + mFile.close(); + mFile.remove(); + if ( mGuiNotificationsEnabled ) + mProgressDialog->hide(); + } + else + { + // download finished normally + if ( mGuiNotificationsEnabled ) + mProgressDialog->hide(); + mFile.flush(); + mFile.close(); + + // get redirection url + QVariant redirectionTarget = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute ); + if ( mReply->error() ) + { + mFile.remove(); + error( tr( "Download failed: %1." ).arg( mReply->errorString() ) ); + } + else if ( !redirectionTarget.isNull() ) + { + QUrl newUrl = mUrl.resolved( redirectionTarget.toUrl() ); + mUrl = newUrl; + mReply->deleteLater(); + mFile.open( QIODevice::WriteOnly ); + mFile.resize( 0 ); + mFile.close(); + startDownload(); + return; + } + // All done + emit downloadCompleted(); + } + emit downloadExited(); + this->deleteLater(); +} + +void QgsFileDownloader::onNetworkError( QNetworkReply::NetworkError err ) +{ + Q_ASSERT( mReply ); + error( QString( "Network error %1: %2" ).arg( err ).arg( mReply->errorString() ) ); +} + +void QgsFileDownloader::onDownloadProgress( qint64 bytesReceived, qint64 bytesTotal ) +{ + if ( mDownloadCanceled ) + { + return; + } + if ( mGuiNotificationsEnabled ) + { + mProgressDialog->setMaximum( bytesTotal ); + mProgressDialog->setValue( bytesReceived ); + } + emit downloadProgress( bytesReceived, bytesTotal ); +} + diff --git a/src/gui/qgsfiledownloader.h b/src/gui/qgsfiledownloader.h new file mode 100644 index 000000000000..ab4d6169bbf7 --- /dev/null +++ b/src/gui/qgsfiledownloader.h @@ -0,0 +1,117 @@ +/*************************************************************************** + qgsfiledownloader.h + -------------------------------------- + Date : November 2016 + Copyright : (C) 2016 by Alessandro Pasotti + Email : apasotti at boundlessgeo dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSFILEDOWNLOADER_H +#define QGSFILEDOWNLOADER_H + +#include +#include +#include +#include +#ifndef QT_NO_OPENSSL +#include +#endif + +/** \ingroup gui + * QgsFileDownloader is a utility class for downloading files. + * + * To use this class, it is necessary to pass the URL and an output file name as + * arguments to the constructor, the download will start immediately. + * The download is asynchronous and depending on the guiNotificationsEnabled + * parameter accepted by the constructor (default = true) the class will + * show a progress dialog and report all errors in a QMessageBox::warning dialog. + * If the guiNotificationsEnabled parameter is set to false, the class can still + * be used through the signals and slots mechanism. + * The object will destroy itself when the request completes, errors or is canceled. + * + * @note added in QGIS 2.18.1 + */ +class GUI_EXPORT QgsFileDownloader : public QObject +{ + Q_OBJECT + public: + + /** + * QgsFileDownloader + * @param url the download url + * @param outputFileName file name where the downloaded content will be stored + * @param guiNotificationsEnabled if false, the downloader will not display any progress bar or error message + */ + QgsFileDownloader( QUrl url, QString outputFileName, bool guiNotificationsEnabled = true ); + + signals: + //! Emitted when the download has completed successfully + void downloadCompleted(); + //! Emitted always when the downloader exits + void downloadExited(); + //! Emitted when the download was canceled by the user + void downloadCanceled(); + //! Emitted when an error makes the download fail + void downloadError( QStringList errorMessages ); + //! Emitted when data ready to be processed + void downloadProgress( qint64 bytesReceived, qint64 bytesTotal ); + + public slots: + + /** + * Called when a download is canceled by the user + * this slot aborts the download and deletes + * the object. + * Never call this slot directly: this is meant to + * be managed by the signal-slot system. + */ + void onDownloadCanceled(); + + private slots: + //! Called when the network reply data are ready + void onReadyRead(); + //! Called when the network reply has finished + void onFinished(); + //! Called on Network Error + void onNetworkError( QNetworkReply::NetworkError err ); + //! Called on data ready to be processed + void onDownloadProgress( qint64 bytesReceived, qint64 bytesTotal ); + //! Called when a network request times out + void onRequestTimedOut(); + //! Called to start the download + void startDownload(); +#ifndef QT_NO_OPENSSL + + /** + * Called on SSL network Errors + * @param reply + * @param errors + */ + void onSslErrors( QNetworkReply *reply, const QList &errors ); +#endif + private: + ~QgsFileDownloader(); + + /** + * Abort current request and show an error if the instance has GUI + * notifications enabled. + */ + void error( QStringList errorMessages ); + void error( QString errorMessage ); + QUrl mUrl; + QNetworkReply* mReply; + QFile mFile; + QProgressDialog* mProgressDialog; + bool mDownloadCanceled; + QStringList mErrors; + bool mGuiNotificationsEnabled; +}; + +#endif // QGSFILEDOWNLOADER_H diff --git a/tests/src/gui/CMakeLists.txt b/tests/src/gui/CMakeLists.txt index ee2d7a677bb0..dee5f193d8bd 100644 --- a/tests/src/gui/CMakeLists.txt +++ b/tests/src/gui/CMakeLists.txt @@ -143,3 +143,5 @@ ADD_QGIS_TEST(sqlcomposerdialog testqgssqlcomposerdialog.cpp) ADD_QGIS_TEST(editorwidgetregistrytest testqgseditorwidgetregistry.cpp) ADD_QGIS_TEST(keyvaluewidgettest testqgskeyvaluewidget.cpp) ADD_QGIS_TEST(listwidgettest testqgslistwidget.cpp) +ADD_QGIS_TEST(filedownloader testqgsfiledownloader.cpp) + diff --git a/tests/src/gui/testqgsfiledownloader.cpp b/tests/src/gui/testqgsfiledownloader.cpp new file mode 100644 index 000000000000..f6b139139e08 --- /dev/null +++ b/tests/src/gui/testqgsfiledownloader.cpp @@ -0,0 +1,254 @@ +/*************************************************************************** + testqgsfilefiledownloader.cpp + -------------------------------------- + Date : 11.8.2016 + Copyright : (C) 2016 Alessandro Pasotti + Email : apasotti at boundlessgeo dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + + +#include +#include +#include +#include +#include +#include + +#include +#include + +class TestQgsFileDownloader: public QObject +{ + Q_OBJECT + public: + TestQgsFileDownloader() + : mTempFile( nullptr ) + , mErrorMessage() + , mCanceled( false ) + , mProgress( false ) + , mError( false ) + , mCompleted( false ) + , mExited( false ) + , mFileDownloader( nullptr ) + {} + + public slots: + //! Called when the download has completed successfully + void downloadCompleted() + { + mCompleted = true; + } + //! Called when the download exits + void downloadExited() + { + mExited = true; + } + //! Called when the download was canceled by the user + void downloadCanceled() + { + mCanceled = true; + } + //! Called when an error makes the download fail + void downloadError( QStringList errorMessages ) + { + mError = true; + errorMessages.sort(); + mErrorMessage = errorMessages.join( ";" ); + } + //! Called when data ready to be processed + void downloadProgress( qint64 bytesReceived, qint64 bytesTotal ) + { + Q_UNUSED( bytesReceived ); + Q_UNUSED( bytesTotal ); + mProgress = true; + } + + private slots: + void initTestCase(); // will be called before the first testfunction is executed. + void cleanupTestCase(); // will be called after the last testfunction was executed. + void init(); // will be called before each testfunction is executed. + void cleanup(); // will be called after every testfunction. + + void testValidDownload(); + void testInValidDownload(); + void testCanceledDownload(); + void testInvalidFile(); + void testInvalidUrl(); + void testBlankUrl(); +#ifndef QT_NO_OPENSSL + void testSslError_data(); + void testSslError(); +#endif + + private: + void makeCall( QUrl url , QString fileName, bool cancel = false ); + QTemporaryFile *mTempFile; + QString mErrorMessage; + bool mCanceled; + bool mProgress; + bool mError; + bool mCompleted; + bool mExited; + QgsFileDownloader *mFileDownloader; +}; + +void TestQgsFileDownloader::makeCall( QUrl url, QString fileName, bool cancel ) +{ + QEventLoop loop; + + mFileDownloader = new QgsFileDownloader( url, fileName, false ); + connect( mFileDownloader, &QgsFileDownloader::downloadCompleted, this, &TestQgsFileDownloader::downloadCompleted ); + connect( mFileDownloader, &QgsFileDownloader::downloadCanceled, this, &TestQgsFileDownloader::downloadCanceled ); + connect( mFileDownloader, &QgsFileDownloader::downloadExited, this, &TestQgsFileDownloader::downloadExited ); + connect( mFileDownloader, &QgsFileDownloader::downloadError, this, &TestQgsFileDownloader::downloadError ); + connect( mFileDownloader, &QgsFileDownloader::downloadProgress, this, &TestQgsFileDownloader::downloadProgress ); + + connect( mFileDownloader, &QgsFileDownloader::downloadExited, &loop, &QEventLoop::quit ); + + if ( cancel ) + QTimer::singleShot( 1000, mFileDownloader, &QgsFileDownloader::onDownloadCanceled ); + + loop.exec(); + +} + +void TestQgsFileDownloader::initTestCase() +{ + QgsApplication::init(); + QgsApplication::initQgis(); + +} + +void TestQgsFileDownloader::cleanupTestCase() +{ + QgsApplication::exitQgis(); +} + +void TestQgsFileDownloader::init() +{ + mErrorMessage.clear(); + mCanceled = false; + mProgress = false; + mError = false; + mCompleted = false; + mExited = false; + mTempFile = new QTemporaryFile( ); + Q_ASSERT( mTempFile->open() ); + mTempFile->close(); +} + + + +void TestQgsFileDownloader::cleanup() +{ + delete mTempFile; +} + +void TestQgsFileDownloader::testValidDownload() +{ + QVERIFY( ! mTempFile->fileName().isEmpty() ); + makeCall( QUrl( "http://www.qgis.org" ), mTempFile->fileName() ); + QVERIFY( mExited ); + QVERIFY( mCompleted ); + QVERIFY( mProgress ); + QVERIFY( !mError ); + QVERIFY( !mCanceled ); + QVERIFY( mTempFile->size() > 0 ); +} + +void TestQgsFileDownloader::testInValidDownload() +{ + QVERIFY( ! mTempFile->fileName().isEmpty() ); + makeCall( QUrl( "http://www.doesnotexistofthatimsure.qgis" ), mTempFile->fileName() ); + QVERIFY( mExited ); + QVERIFY( !mCompleted ); + QVERIFY( mError ); + QVERIFY( !mCanceled ); + QVERIFY( mTempFile->size() == 0 ); + QCOMPARE( mErrorMessage, QString( "Network error 3: Host www.doesnotexistofthatimsure.qgis not found" ) ); +} + +void TestQgsFileDownloader::testCanceledDownload() +{ + QVERIFY( ! mTempFile->fileName().isEmpty() ); + makeCall( QUrl( "https://github.com/qgis/QGIS/archive/master.zip" ), mTempFile->fileName(), true ); + QVERIFY( mExited ); + QVERIFY( !mCompleted ); + QVERIFY( !mError ); + QVERIFY( mProgress ); + QVERIFY( mCanceled ); + QVERIFY( mTempFile->size() == 0 ); +} + +void TestQgsFileDownloader::testInvalidFile() +{ + makeCall( QUrl( "https://github.com/qgis/QGIS/archive/master.zip" ), QString() ); + QVERIFY( mExited ); + QVERIFY( !mCompleted ); + QVERIFY( mError ); + QVERIFY( !mCanceled ); + QCOMPARE( mErrorMessage, QString( "Cannot open output file: " ) ); +} + +void TestQgsFileDownloader::testInvalidUrl() +{ + QVERIFY( ! mTempFile->fileName().isEmpty() ); + makeCall( QUrl( "xyz://www" ), mTempFile->fileName() ); + QVERIFY( mExited ); + QVERIFY( !mCompleted ); + QVERIFY( mError ); + QVERIFY( !mCanceled ); + QCOMPARE( mErrorMessage, QString( "Network error 301: Protocol \"xyz\" is unknown" ) ); +} + +void TestQgsFileDownloader::testBlankUrl() +{ + QVERIFY( ! mTempFile->fileName().isEmpty() ); + makeCall( QUrl( "" ), mTempFile->fileName() ); + QVERIFY( mExited ); + QVERIFY( !mCompleted ); + QVERIFY( mError ); + QVERIFY( !mCanceled ); + QCOMPARE( mErrorMessage, QString( "Network error 301: Protocol \"\" is unknown" ) ); +} + +#ifndef QT_NO_OPENSSL +void TestQgsFileDownloader::testSslError_data() +{ + QTest::addColumn( "url" ); + QTest::addColumn( "result" ); + + QTest::newRow( "expired" ) << "https://expired.badssl.com/" + << "Network error 6: SSL handshake failed;SSL Errors: ;The certificate has expired"; + QTest::newRow( "self-signed" ) << "https://self-signed.badssl.com/" + << "Network error 6: SSL handshake failed;SSL Errors: ;The certificate is self-signed, and untrusted"; + QTest::newRow( "untrusted-root" ) << "https://untrusted-root.badssl.com/" + << "Network error 6: SSL handshake failed;No certificates could be verified;SSL Errors: ;The issuer certificate of a locally looked up certificate could not be found"; +} + +void TestQgsFileDownloader::testSslError() +{ + QFETCH( QString, url ); + QFETCH( QString, result ); + QVERIFY( ! mTempFile->fileName().isEmpty() ); + makeCall( QUrl( url ), mTempFile->fileName() ); + QCOMPARE( mErrorMessage, result ); + QVERIFY( !mCompleted ); + QVERIFY( mError ); + QVERIFY( !mCanceled ); +} + +#endif + + +QTEST_MAIN( TestQgsFileDownloader ) +#include "testqgsfiledownloader.moc" + + diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index ebb1705fc6b5..7a3ad5d080d6 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -123,6 +123,7 @@ ADD_PYTHON_TEST(PyQgsConsole test_console.py) ADD_PYTHON_TEST(PyQgsLayerDependencies test_layer_dependencies.py) ADD_PYTHON_TEST(PyQgsVersionCompare test_versioncompare.py) ADD_PYTHON_TEST(PyQgsDBManagerGpkg test_db_manager_gpkg.py) +ADD_PYTHON_TEST(PyQgsFileDownloader test_qgsfiledownloader.py) IF (NOT WIN32) ADD_PYTHON_TEST(PyQgsLogger test_qgslogger.py) diff --git a/tests/src/python/test_qgsfiledownloader.py b/tests/src/python/test_qgsfiledownloader.py new file mode 100644 index 000000000000..811b43b2f1ea --- /dev/null +++ b/tests/src/python/test_qgsfiledownloader.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +""" +Test the QgsFileDownloader class + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +from __future__ import print_function +from future import standard_library +import os +import tempfile +from functools import partial +from qgis.PyQt.QtCore import QEventLoop, QUrl, QTimer +from qgis.gui import (QgsFileDownloader,) +from qgis.testing import start_app, unittest + +standard_library.install_aliases() + +__author__ = 'Alessandro Pasotti' +__date__ = '08/11/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + + +start_app() + + +class TestQgsFileDownloader(unittest.TestCase): + + """ + This class tests the QgsFileDownloader class + """ + + def _make_download(self, url, destination, cancel=False): + self.completed_was_called = False + self.error_was_called = False + self.canceled_was_called = False + self.progress_was_called = False + self.exited_was_called = False + + loop = QEventLoop() + + downloader = QgsFileDownloader(QUrl(url), destination, False) + downloader.downloadCompleted.connect(partial(self._set_slot, 'completed')) + downloader.downloadExited.connect(partial(self._set_slot, 'exited')) + downloader.downloadCanceled.connect(partial(self._set_slot, 'canceled')) + downloader.downloadError.connect(partial(self._set_slot, 'error')) + downloader.downloadProgress.connect(partial(self._set_slot, 'progress')) + + downloader.downloadExited.connect(loop.quit) + + if cancel: + downloader.downloadProgress.connect(downloader.onDownloadCanceled) + + loop.exec_() + + def test_validDownload(self): + """Tests a valid download""" + destination = tempfile.mktemp() + self._make_download('http://www.qgis.org', destination) + self.assertTrue(self.exited_was_called) + self.assertTrue(self.completed_was_called) + self.assertTrue(self.progress_was_called) + self.assertFalse(self.canceled_was_called) + self.assertFalse(self.error_was_called) + self.assertTrue(os.path.isfile(destination)) + self.assertGreater(os.path.getsize(destination), 0) + + def test_inValidDownload(self): + """Tests an invalid download""" + destination = tempfile.mktemp() + self._make_download('http://www.doesnotexistofthatimsure.qgis', destination) + self.assertTrue(self.exited_was_called) + self.assertFalse(self.completed_was_called) + self.assertTrue(self.progress_was_called) + self.assertFalse(self.canceled_was_called) + self.assertTrue(self.error_was_called) + self.assertEqual(self.error_args[1], [u'Network error 3: Host www.doesnotexistofthatimsure.qgis not found']) + self.assertFalse(os.path.isfile(destination)) + + def test_dowloadCanceled(self): + """Tests user canceled download""" + destination = tempfile.mktemp() + self._make_download('https://github.com/qgis/QGIS/archive/master.zip', destination, True) + self.assertTrue(self.exited_was_called) + self.assertFalse(self.completed_was_called) + self.assertTrue(self.canceled_was_called) + self.assertFalse(self.error_was_called) + self.assertFalse(os.path.isfile(destination)) + + def test_InvalidUrl(self): + destination = tempfile.mktemp() + self._make_download('xyz://www', destination) + self.assertTrue(self.exited_was_called) + self.assertFalse(self.completed_was_called) + self.assertFalse(self.canceled_was_called) + self.assertTrue(self.error_was_called) + self.assertFalse(os.path.isfile(destination)) + self.assertEqual(self.error_args[1], [u"Network error 301: Protocol \"xyz\" is unknown"]) + + def test_InvalidFile(self): + self._make_download('https://github.com/qgis/QGIS/archive/master.zip', "") + self.assertTrue(self.exited_was_called) + self.assertFalse(self.completed_was_called) + self.assertFalse(self.canceled_was_called) + self.assertTrue(self.error_was_called) + self.assertEqual(self.error_args[1], [u"Cannot open output file: "]) + + def test_BlankUrl(self): + destination = tempfile.mktemp() + self._make_download('', destination) + self.assertTrue(self.exited_was_called) + self.assertFalse(self.completed_was_called) + self.assertFalse(self.canceled_was_called) + self.assertTrue(self.error_was_called) + self.assertFalse(os.path.isfile(destination)) + self.assertEqual(self.error_args[1], [u"Network error 301: Protocol \"\" is unknown"]) + + def ssl_compare(self, name, url, error): + destination = tempfile.mktemp() + self._make_download(url, destination) + msg = "Failed in %s: %s" % (name, url) + self.assertTrue(self.exited_was_called) + self.assertFalse(self.completed_was_called, msg) + self.assertFalse(self.canceled_was_called, msg) + self.assertTrue(self.error_was_called, msg) + self.assertFalse(os.path.isfile(destination), msg) + result = sorted(self.error_args[1]) + result = ';'.join(result) + self.assertTrue(result.startswith(error), msg + "expected:\n%s\nactual:\n%s\n" % (result, error)) + + def test_sslExpired(self): + self.ssl_compare("expired", "https://expired.badssl.com/", "Network error 6: SSL handshake failed;SSL Errors: ;The certificate has expired") + self.ssl_compare("self-signed", "https://self-signed.badssl.com/", "Network error 6: SSL handshake failed;SSL Errors: ;The certificate is self-signed, and untrusted") + self.ssl_compare("untrusted-root", "https://untrusted-root.badssl.com/", "Network error 6: SSL handshake failed;No certificates could be verified;") + + def _set_slot(self, *args, **kwargs): + #print('_set_slot(%s) called' % args[0]) + setattr(self, args[0] + '_was_called', True) + setattr(self, args[0] + '_args', args) + + +if __name__ == '__main__': + unittest.main() From b069e955aead612750cafd918c2a0dfdad06ca11 Mon Sep 17 00:00:00 2001 From: Harrissou Sant-anna Date: Fri, 11 Nov 2016 18:14:15 +0100 Subject: [PATCH 701/897] typo fix --- src/ui/composer/qgscomposerscalebarwidgetbase.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/composer/qgscomposerscalebarwidgetbase.ui b/src/ui/composer/qgscomposerscalebarwidgetbase.ui index 947bfac95199..2c6d2c58cdd9 100644 --- a/src/ui/composer/qgscomposerscalebarwidgetbase.ui +++ b/src/ui/composer/qgscomposerscalebarwidgetbase.ui @@ -17,7 +17,7 @@ - Barscale Options + Scalebar Options From 159fda68f2e3ac0c557a3b2e166dc24f95ad83ed Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 27 Oct 2016 20:43:10 +0300 Subject: [PATCH 702/897] [processing] add test for gdal_polygonize --- .../testdata/expected/gdal/polygonize.gfs | 21 +++ .../testdata/expected/gdal/polygonize.gml | 134 ++++++++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 46 +++--- 3 files changed, 184 insertions(+), 17 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/polygonize.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/polygonize.gml diff --git a/python/plugins/processing/tests/testdata/expected/gdal/polygonize.gfs b/python/plugins/processing/tests/testdata/expected/gdal/polygonize.gfs new file mode 100644 index 000000000000..b0c3cabf6e85 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/polygonize.gfs @@ -0,0 +1,21 @@ + + + polygonize + polygonize + + 3 + EPSG:23030 + + 40 + 270746.30402 + 270869.14438 + 4458929.13301 + 4459029.57452 + + + DN + DN + Integer + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/polygonize.gml b/python/plugins/processing/tests/testdata/expected/gdal/polygonize.gml new file mode 100644 index 000000000000..1f49b1b34c89 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/polygonize.gml @@ -0,0 +1,134 @@ + + + + + 270746.30402147234458929.133005033 + 270869.14437832154459029.574521748 + + + + + + 270746.304021472,4459029.57452175 270766.777414281,4459029.57452175 270766.777414281,4459009.4862184 270746.304021472,4459009.4862184 270746.304021472,4459029.57452175 + 826 + + + + + 270766.777414281,4459029.57452175 270797.487503493,4459029.57452175 270797.487503493,4459009.4862184 270766.777414281,4459009.4862184 270766.777414281,4459029.57452175 + 837 + + + + + 270797.487503493,4459029.57452175 270817.960896301,4459029.57452175 270817.960896301,4459009.4862184 270797.487503493,4459009.4862184 270797.487503493,4459029.57452175 + 845 + + + + + 270817.960896301,4459029.57452175 270848.670985513,4459029.57452175 270848.670985513,4459009.4862184 270817.960896301,4459009.4862184 270817.960896301,4459029.57452175 + 853 + + + + + 270848.670985513,4459029.57452175 270869.144378322,4459029.57452175 270869.144378322,4459009.4862184 270848.670985513,4459009.4862184 270848.670985513,4459029.57452175 + 861 + + + + + 270746.304021472,4459009.4862184 270766.777414281,4459009.4862184 270766.777414281,4458979.35376339 270746.304021472,4458979.35376339 270746.304021472,4459009.4862184 + 843 + + + + + 270766.777414281,4459009.4862184 270797.487503493,4459009.4862184 270797.487503493,4458979.35376339 270766.777414281,4458979.35376339 270766.777414281,4459009.4862184 + 851 + + + + + 270797.487503493,4459009.4862184 270817.960896301,4459009.4862184 270817.960896301,4458979.35376339 270797.487503493,4458979.35376339 270797.487503493,4459009.4862184 + 859 + + + + + 270817.960896301,4459009.4862184 270848.670985513,4459009.4862184 270848.670985513,4458979.35376339 270817.960896301,4458979.35376339 270817.960896301,4459009.4862184 + 866 + + + + + 270848.670985513,4459009.4862184 270869.144378322,4459009.4862184 270869.144378322,4458979.35376339 270848.670985513,4458979.35376339 270848.670985513,4459009.4862184 + 878 + + + + + 270746.304021472,4458979.35376339 270766.777414281,4458979.35376339 270766.777414281,4458959.26546005 270746.304021472,4458959.26546005 270746.304021472,4458979.35376339 + 859 + + + + + 270766.777414281,4458979.35376339 270797.487503493,4458979.35376339 270797.487503493,4458959.26546005 270766.777414281,4458959.26546005 270766.777414281,4458979.35376339 + 864 + + + + + 270797.487503493,4458979.35376339 270817.960896301,4458979.35376339 270817.960896301,4458959.26546005 270797.487503493,4458959.26546005 270797.487503493,4458979.35376339 + 872 + + + + + 270817.960896301,4458979.35376339 270848.670985513,4458979.35376339 270848.670985513,4458959.26546005 270817.960896301,4458959.26546005 270817.960896301,4458979.35376339 + 880 + + + + + 270848.670985513,4458979.35376339 270869.144378322,4458979.35376339 270869.144378322,4458959.26546005 270848.670985513,4458959.26546005 270848.670985513,4458979.35376339 + 890 + + + + + 270746.304021472,4458959.26546005 270766.777414281,4458959.26546005 270766.777414281,4458929.13300503 270746.304021472,4458929.13300503 270746.304021472,4458959.26546005 + 868 + + + + + 270766.777414281,4458959.26546005 270797.487503493,4458959.26546005 270797.487503493,4458929.13300503 270766.777414281,4458929.13300503 270766.777414281,4458959.26546005 + 873 + + + + + 270797.487503493,4458959.26546005 270817.960896301,4458959.26546005 270817.960896301,4458929.13300503 270797.487503493,4458929.13300503 270797.487503493,4458959.26546005 + 881 + + + + + 270817.960896301,4458959.26546005 270848.670985513,4458959.26546005 270848.670985513,4458929.13300503 270817.960896301,4458929.13300503 270817.960896301,4458959.26546005 + 890 + + + + + 270848.670985513,4458959.26546005 270869.144378322,4458959.26546005 270869.144378322,4458929.13300503 270848.670985513,4458929.13300503 270848.670985513,4458959.26546005 + 899 + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 50b9756f33e4..e2daf147eedd 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -27,23 +27,6 @@ tests: # hash: f1fedeb6782f9389cf43590d4c85ada9155ab61fef6dc285aaeb54d6 # type: rasterhash - - - name: GDAL ogrinfo - algorithm: gdalogr:information - params: - INPUT: - name: lines.gml - type: vector - SUMMARY_ONLY: 'True' - results: - OUTPUT: - name: expected/gdal/vector_info.html - type: regex - rules: - - 'Extent: \(-1.000000, -3.000000\) - \(11.000000, 5.000000\)' - - 'Geometry: Line String' - - 'Feature Count: [6|7]' # On some platforms returns 6 instead of 7... - - algorithm: gdalorg:rasterinfo name: GDAL gdalinfo params: @@ -60,3 +43,32 @@ tests: - 'Origin = \(270736.067325068172067,4459029.574521748349071\)' - 'Band 1 Block=16x14 Type=Float32, ColorInterp=Gray' - ' NoData Value=-32768' + + - algorithm: gdalogr:polygonize + name: GDAL polygonize + params: + FIELD: DN + INPUT: + name: raster.tif + type: raster + results: + OUTPUT: + name: expected/gdal/polygonize.gml + type: vector + + - algorithm: gdalogr:information + name: GDAL ogrinfo + params: + INPUT: + name: lines.gml + type: vector + SUMMARY_ONLY: 'True' + results: + OUTPUT: + name: expected/gdal/vector_info.html + type: regex + rules: + - 'Extent: \(-1.000000, -3.000000\) - \(11.000000, 5.000000\)' + - 'Geometry: Line String' + - 'Feature Count: [6|7]' # On some platforms returns 6 instead of 7... + From 5991eccb472d0efdb7c36ce7cfb2c48205736751 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 27 Oct 2016 21:21:52 +0300 Subject: [PATCH 703/897] [processing] simple test for ogr buffering --- .../processing/algs/gdal/ogr2ogrbuffer.py | 2 +- .../testdata/expected/gdal/buffer_lines.gfs | 16 +++++++ .../testdata/expected/gdal/buffer_lines.gml | 48 +++++++++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 14 ++++++ .../plugins/processing/tools/dataobjects.py | 9 +--- python/plugins/processing/tools/vector.py | 7 +-- 6 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gml diff --git a/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py b/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py index 475e6c2db585..e20ca5dd05e2 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py @@ -111,7 +111,7 @@ def getConsoleCommands(self): if field is not None and multi: arguments.append('-explodecollections') - if len(options) > 0: + if options is not None and len(options) > 0: arguments.append(options) commands = [] diff --git a/python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gfs b/python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gfs new file mode 100644 index 000000000000..cc2ea5004add --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gfs @@ -0,0 +1,16 @@ + + + buffer_lines + buffer_lines + + 3 + EPSG:4326 + + 7 + -2.00000 + 12.00000 + -4.00000 + 6.00000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gml b/python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gml new file mode 100644 index 000000000000..4b78ef3b7ab8 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/buffer_lines.gml @@ -0,0 +1,48 @@ + + + + + -2-4 + 126 + + + + + + 8,3 8.00137046524543,3.05233595624294 8.00547810463173,3.10452846326765 8.01231165940486,3.15643446504023 8.02185239926619,3.20791169081776 8.03407417371093,3.25881904510252 8.04894348370485,3.30901699437495 8.0664195735028,3.3583679495453 8.0864545423574,3.4067366430758 8.10899347581163,3.45399049973955 8.13397459621556,3.5 8.16132943205458,3.54463903501503 8.19098300562505,3.58778525229247 8.22285403854303,3.62932039104984 8.25685517452261,3.66913060635886 8.29289321881345,3.70710678118655 10.2928932188135,5.70710678118655 10.3308693936411,5.7431448254774 10.3706796089502,5.77714596145697 10.4122147477075,5.80901699437495 10.455360964985,5.83867056794542 10.5,5.86602540378444 10.5460095002605,5.89100652418837 10.5932633569242,5.9135454576426 10.6416320504547,5.9335804264972 10.6909830056251,5.95105651629515 10.7411809548975,5.96592582628907 10.7920883091822,5.97814760073381 10.8435655349598,5.98768834059514 10.8954715367323,5.99452189536827 10.9476640437571,5.99862953475457 11.0,6.0 11.0523359562429,5.99862953475457 11.1045284632677,5.99452189536827 11.1564344650402,5.98768834059514 11.2079116908178,5.97814760073381 11.2588190451025,5.96592582628907 11.3090169943749,5.95105651629515 11.3583679495453,5.9335804264972 11.4067366430758,5.9135454576426 11.4539904997395,5.89100652418837 11.5,5.86602540378444 11.544639035015,5.83867056794542 11.5877852522925,5.80901699437495 11.6293203910498,5.77714596145697 11.6691306063589,5.74314482547739 11.7071067811865,5.70710678118655 11.7431448254774,5.66913060635886 11.777145961457,5.62932039104984 11.8090169943749,5.58778525229247 11.8386705679454,5.54463903501503 11.8660254037844,5.5 11.8910065241884,5.45399049973955 11.9135454576426,5.4067366430758 11.9335804264972,5.3583679495453 11.9510565162952,5.30901699437495 11.9659258262891,5.25881904510252 11.9781476007338,5.20791169081776 11.9876883405951,5.15643446504023 11.9945218953683,5.10452846326766 11.9986295347546,5.05233595624295 12.0,5.0 11.9986295347546,4.94766404375706 11.9945218953683,4.89547153673235 11.9876883405951,4.84356553495977 11.9781476007338,4.79208830918224 11.9659258262891,4.74118095489748 11.9510565162952,4.69098300562506 11.9335804264972,4.6416320504547 11.9135454576426,4.5932633569242 11.8910065241884,4.54600950026046 11.8660254037844,4.5 11.8386705679454,4.45536096498498 11.809016994375,4.41221474770753 11.777145961457,4.37067960895017 11.7431448254774,4.33086939364115 11.7071067811866,4.29289321881346 10.0,2.5857864376269 10,2 9.99862953475457,1.94766404375706 9.99452189536827,1.89547153673235 9.98768834059514,1.84356553495977 9.97814760073381,1.79208830918224 9.96592582628907,1.74118095489748 9.95105651629515,1.69098300562505 9.9335804264972,1.6416320504547 9.9135454576426,1.5932633569242 9.89100652418837,1.54600950026045 9.86602540378444,1.5 9.83867056794542,1.45536096498497 9.80901699437495,1.41221474770753 9.77714596145697,1.37067960895016 9.74314482547739,1.33086939364114 9.70710678118655,1.29289321881345 9.66913060635886,1.25685517452261 9.62932039104984,1.22285403854303 9.58778525229247,1.19098300562505 9.54463903501503,1.16132943205458 9.5,1.13397459621556 9.45399049973955,1.10899347581163 9.4067366430758,1.0864545423574 9.3583679495453,1.0664195735028 9.30901699437495,1.04894348370485 9.25881904510252,1.03407417371093 9.20791169081776,1.02185239926619 9.15643446504023,1.01231165940486 9.10452846326765,1.00547810463173 9.05233595624294,1.00137046524543 9,1 6,1 5.94766404375705,1.00137046524543 5.89547153673234,1.00547810463173 5.84356553495977,1.01231165940486 5.79208830918224,1.02185239926619 5.74118095489748,1.03407417371093 5.69098300562505,1.04894348370485 5.6416320504547,1.0664195735028 5.5932633569242,1.0864545423574 5.54600950026045,1.10899347581163 5.5,1.13397459621556 5.45536096498497,1.16132943205458 5.41221474770753,1.19098300562505 5.37067960895016,1.22285403854303 5.33086939364114,1.25685517452261 5.29289321881345,1.29289321881345 5.25685517452261,1.33086939364114 5.22285403854303,1.37067960895016 5.19098300562505,1.41221474770753 5.16132943205458,1.45536096498497 5.13397459621556,1.5 5.10899347581163,1.54600950026045 5.0864545423574,1.5932633569242 5.0664195735028,1.6416320504547 5.04894348370485,1.69098300562505 5.03407417371093,1.74118095489748 5.02185239926619,1.79208830918224 5.01231165940486,1.84356553495977 5.00547810463173,1.89547153673235 5.00137046524543,1.94766404375706 5.0,2.0 5.00137046524543,2.05233595624294 5.00547810463173,2.10452846326765 5.01231165940486,2.15643446504023 5.02185239926619,2.20791169081776 5.03407417371093,2.25881904510252 5.04894348370485,2.30901699437495 5.0664195735028,2.3583679495453 5.0864545423574,2.4067366430758 5.10899347581163,2.45399049973955 5.13397459621556,2.5 5.16132943205457,2.54463903501503 5.19098300562505,2.58778525229247 5.22285403854303,2.62932039104984 5.2568551745226,2.66913060635886 5.29289321881345,2.70710678118655 5.33086939364114,2.74314482547739 5.37067960895016,2.77714596145697 5.41221474770752,2.80901699437495 5.45536096498497,2.83867056794542 5.5,2.86602540378444 5.54600950026045,2.89100652418837 5.5932633569242,2.9135454576426 5.6416320504547,2.9335804264972 5.69098300562505,2.95105651629515 5.74118095489748,2.96592582628907 5.79208830918224,2.9781476007338 5.84356553495976,2.98768834059514 5.89547153673234,2.99452189536827 5.94766404375705,2.99862953475457 6.0,3.0 8,3 + + + + + 1,0 1.05233595624295,-0.001370465245426 1.10452846326766,-0.005478104631727 1.15643446504023,-0.012311659404862 1.20791169081776,-0.021852399266195 1.25881904510252,-0.034074173710932 1.30901699437495,-0.048943483704847 1.3583679495453,-0.066419573502799 1.4067366430758,-0.0864545423574 1.45399049973955,-0.108993475811633 1.5,-0.133974596215562 1.54463903501503,-0.161329432054577 1.58778525229247,-0.190983005625053 1.62932039104984,-0.22285403854303 1.66913060635886,-0.256855174522606 1.70710678118655,-0.292893218813453 1.74314482547739,-0.330869393641142 1.77714596145697,-0.370679608950163 1.80901699437495,-0.412214747707528 1.83867056794542,-0.455360964984974 1.86602540378444,-0.5 1.89100652418837,-0.546009500260454 1.9135454576426,-0.5932633569242 1.9335804264972,-0.6416320504547 1.95105651629515,-0.690983005625053 1.96592582628907,-0.741180954897479 1.97814760073381,-0.79208830918224 1.98768834059514,-0.843565534959769 1.99452189536827,-0.895471536732346 1.99862953475457,-0.947664043757055 2.0,-1.0 1.99862953475457,-1.05233595624294 1.99452189536827,-1.10452846326765 1.98768834059514,-1.15643446504023 1.97814760073381,-1.20791169081776 1.96592582628907,-1.25881904510252 1.95105651629515,-1.30901699437495 1.9335804264972,-1.3583679495453 1.9135454576426,-1.4067366430758 1.89100652418837,-1.45399049973954 1.86602540378444,-1.5 1.83867056794543,-1.54463903501503 1.80901699437495,-1.58778525229247 1.77714596145697,-1.62932039104984 1.7431448254774,-1.66913060635886 1.70710678118655,-1.70710678118655 1.66913060635886,-1.74314482547739 1.62932039104984,-1.77714596145697 1.58778525229248,-1.80901699437495 1.54463903501503,-1.83867056794542 1.5,-1.86602540378444 1.45399049973955,-1.89100652418837 1.4067366430758,-1.9135454576426 1.3583679495453,-1.9335804264972 1.30901699437495,-1.95105651629515 1.25881904510252,-1.96592582628907 1.20791169081776,-1.9781476007338 1.15643446504024,-1.98768834059514 1.10452846326766,-1.99452189536827 1.05233595624295,-1.99862953475457 1.0,-2.0 -1,-2 -1.05233595624295,-1.99862953475457 -1.10452846326766,-1.99452189536827 -1.15643446504023,-1.98768834059514 -1.20791169081776,-1.97814760073381 -1.25881904510252,-1.96592582628907 -1.30901699437495,-1.95105651629515 -1.3583679495453,-1.9335804264972 -1.4067366430758,-1.9135454576426 -1.45399049973955,-1.89100652418837 -1.5,-1.86602540378444 -1.54463903501503,-1.83867056794542 -1.58778525229247,-1.80901699437495 -1.62932039104984,-1.77714596145697 -1.66913060635886,-1.74314482547739 -1.70710678118655,-1.70710678118655 -1.7431448254774,-1.66913060635886 -1.77714596145697,-1.62932039104984 -1.80901699437495,-1.58778525229247 -1.83867056794542,-1.54463903501503 -1.86602540378444,-1.5 -1.89100652418837,-1.45399049973955 -1.9135454576426,-1.4067366430758 -1.9335804264972,-1.3583679495453 -1.95105651629515,-1.30901699437495 -1.96592582628907,-1.25881904510252 -1.97814760073381,-1.20791169081776 -1.98768834059514,-1.15643446504023 -1.99452189536827,-1.10452846326765 -1.99862953475457,-1.05233595624294 -2.0,-1.0 -1.99862953475457,-0.947664043757057 -1.99452189536827,-0.895471536732348 -1.98768834059514,-0.84356553495977 -1.97814760073381,-0.792088309182242 -1.96592582628907,-0.74118095489748 -1.95105651629515,-0.690983005625054 -1.9335804264972,-0.641632050454701 -1.9135454576426,-0.593263356924202 -1.89100652418837,-0.546009500260455 -1.86602540378444,-0.5 -1.83867056794542,-0.455360964984975 -1.80901699437495,-0.412214747707529 -1.77714596145697,-0.370679608950164 -1.7431448254774,-0.330869393641144 -1.70710678118655,-0.292893218813454 -1.66913060635886,-0.256855174522608 -1.62932039104984,-0.222854038543031 -1.58778525229248,-0.190983005625054 -1.54463903501503,-0.161329432054578 -1.5,-0.133974596215563 -1.45399049973955,-0.108993475811634 -1.4067366430758,-0.086454542357401 -1.3583679495453,-0.0664195735028 -1.30901699437495,-0.048943483704848 -1.25881904510252,-0.034074173710933 -1.20791169081776,-0.021852399266195 -1.15643446504024,-0.012311659404863 -1.10452846326766,-0.005478104631727 -1.05233595624295,-0.001370465245426 -1.0,0.0 1,0 + + + + + 1,2 1.00137046524543,2.05233595624294 1.00547810463173,2.10452846326765 1.01231165940486,2.15643446504023 1.02185239926619,2.20791169081776 1.03407417371093,2.25881904510252 1.04894348370485,2.30901699437495 1.0664195735028,2.3583679495453 1.0864545423574,2.4067366430758 1.10899347581163,2.45399049973955 1.13397459621556,2.5 1.16132943205458,2.54463903501503 1.19098300562505,2.58778525229247 1.22285403854303,2.62932039104984 1.25685517452261,2.66913060635886 1.29289321881345,2.70710678118655 1.33086939364114,2.74314482547739 1.37067960895016,2.77714596145697 1.41221474770753,2.80901699437495 1.45536096498497,2.83867056794542 1.5,2.86602540378444 1.54600950026045,2.89100652418837 1.5932633569242,2.9135454576426 1.6416320504547,2.9335804264972 1.69098300562505,2.95105651629515 1.74118095489748,2.96592582628907 1.79208830918224,2.97814760073381 1.84356553495977,2.98768834059514 1.89547153673235,2.99452189536827 1.94766404375706,2.99862953475457 2,3 2.00137046524543,3.05233595624295 2.00547810463173,3.10452846326766 2.01231165940486,3.15643446504023 2.02185239926619,3.20791169081776 2.03407417371093,3.25881904510252 2.04894348370485,3.30901699437495 2.0664195735028,3.3583679495453 2.0864545423574,3.4067366430758 2.10899347581163,3.45399049973955 2.13397459621556,3.5 2.16132943205458,3.54463903501503 2.19098300562505,3.58778525229247 2.22285403854303,3.62932039104984 2.25685517452261,3.66913060635886 2.29289321881345,3.70710678118655 2.33086939364114,3.74314482547739 2.37067960895016,3.77714596145697 2.41221474770753,3.80901699437495 2.45536096498497,3.83867056794542 2.5,3.86602540378444 2.54600950026045,3.89100652418837 2.5932633569242,3.9135454576426 2.6416320504547,3.9335804264972 2.69098300562505,3.95105651629515 2.74118095489748,3.96592582628907 2.79208830918224,3.97814760073381 2.84356553495977,3.98768834059514 2.89547153673235,3.99452189536827 2.94766404375706,3.99862953475457 3.0,4.0 3.05233595624294,3.99862953475457 3.10452846326765,3.99452189536827 3.15643446504023,3.98768834059514 3.20791169081776,3.97814760073381 3.25881904510252,3.96592582628907 3.30901699437495,3.95105651629515 3.3583679495453,3.9335804264972 3.4067366430758,3.9135454576426 3.45399049973955,3.89100652418837 3.5,3.86602540378444 3.54463903501503,3.83867056794543 3.58778525229247,3.80901699437495 3.62932039104984,3.77714596145697 3.66913060635886,3.7431448254774 3.70710678118655,3.70710678118655 3.74314482547739,3.66913060635886 3.77714596145697,3.62932039104984 3.80901699437495,3.58778525229248 3.83867056794542,3.54463903501503 3.86602540378444,3.5 3.89100652418837,3.45399049973955 3.9135454576426,3.4067366430758 3.9335804264972,3.3583679495453 3.95105651629515,3.30901699437495 3.96592582628907,3.25881904510252 3.9781476007338,3.20791169081776 3.98768834059514,3.15643446504024 3.99452189536827,3.10452846326766 3.99862953475457,3.05233595624295 4.0,3.0 4,2 3.99862953475457,1.94766404375706 3.99452189536827,1.89547153673235 3.98768834059514,1.84356553495977 3.97814760073381,1.79208830918224 3.96592582628907,1.74118095489748 3.95105651629515,1.69098300562505 3.9335804264972,1.6416320504547 3.9135454576426,1.5932633569242 3.89100652418837,1.54600950026045 3.86602540378444,1.5 3.83867056794542,1.45536096498497 3.80901699437495,1.41221474770753 3.77714596145697,1.37067960895016 3.74314482547739,1.33086939364114 3.70710678118655,1.29289321881345 3.66913060635886,1.25685517452261 3.62932039104984,1.22285403854303 3.58778525229247,1.19098300562505 3.54463903501503,1.16132943205458 3.5,1.13397459621556 3.45399049973955,1.10899347581163 3.4067366430758,1.0864545423574 3.3583679495453,1.0664195735028 3.30901699437495,1.04894348370485 3.25881904510252,1.03407417371093 3.20791169081776,1.02185239926619 3.15643446504023,1.01231165940486 3.10452846326765,1.00547810463173 3.05233595624294,1.00137046524543 3,1 3,0 2.99862953475457,-0.052335956242945 2.99452189536827,-0.104528463267655 2.98768834059514,-0.156434465040232 2.97814760073381,-0.207911690817761 2.96592582628907,-0.258819045102522 2.95105651629515,-0.309016994374949 2.9335804264972,-0.358367949545301 2.9135454576426,-0.406736643075801 2.89100652418837,-0.453990499739548 2.86602540378444,-0.5 2.83867056794542,-0.544639035015028 2.80901699437495,-0.587785252292474 2.77714596145697,-0.629320391049838 2.74314482547739,-0.669130606358859 2.70710678118655,-0.707106781186548 2.66913060635886,-0.743144825477395 2.62932039104984,-0.777145961456971 2.58778525229247,-0.809016994374948 2.54463903501503,-0.838670567945424 2.5,-0.866025403784439 2.45399049973955,-0.891006524188368 2.4067366430758,-0.913545457642601 2.3583679495453,-0.933580426497202 2.30901699437495,-0.951056516295154 2.25881904510252,-0.965925826289068 2.20791169081776,-0.978147600733806 2.15643446504023,-0.987688340595138 2.10452846326765,-0.994521895368273 2.05233595624294,-0.998629534754574 2.0,-1.0 1.94766404375706,-0.998629534754574 1.89547153673235,-0.994521895368274 1.84356553495977,-0.987688340595138 1.79208830918224,-0.978147600733806 1.74118095489748,-0.965925826289069 1.69098300562505,-0.951056516295154 1.6416320504547,-0.933580426497203 1.5932633569242,-0.913545457642602 1.54600950026045,-0.891006524188369 1.5,-0.86602540378444 1.45536096498497,-0.838670567945425 1.41221474770753,-0.809016994374949 1.37067960895016,-0.777145961456972 1.33086939364114,-0.743144825477396 1.29289321881345,-0.707106781186549 1.25685517452261,-0.669130606358861 1.22285403854303,-0.62932039104984 1.19098300562505,-0.587785252292476 1.16132943205458,-0.54463903501503 1.13397459621556,-0.5 1.10899347581163,-0.45399049973955 1.0864545423574,-0.406736643075804 1.0664195735028,-0.358367949545304 1.04894348370485,-0.309016994374952 1.03407417371093,-0.258819045102525 1.0218523992662,-0.207911690817764 1.01231165940486,-0.156434465040235 1.00547810463173,-0.104528463267659 1.00137046524543,-0.052335956242949 1.0,-0.0 1,2 + + + + + 5,2 5.05233595624295,1.99862953475457 5.10452846326765,1.99452189536827 5.15643446504023,1.98768834059514 5.20791169081776,1.97814760073381 5.25881904510252,1.96592582628907 5.30901699437495,1.95105651629515 5.3583679495453,1.9335804264972 5.4067366430758,1.9135454576426 5.45399049973955,1.89100652418837 5.5,1.86602540378444 5.54463903501503,1.83867056794542 5.58778525229247,1.80901699437495 5.62932039104984,1.77714596145697 5.66913060635886,1.74314482547739 5.70710678118655,1.70710678118655 5.74314482547739,1.66913060635886 5.77714596145697,1.62932039104984 5.80901699437495,1.58778525229247 5.83867056794542,1.54463903501503 5.86602540378444,1.5 5.89100652418837,1.45399049973955 5.9135454576426,1.4067366430758 5.9335804264972,1.3583679495453 5.95105651629515,1.30901699437495 5.96592582628907,1.25881904510252 5.97814760073381,1.20791169081776 5.98768834059514,1.15643446504023 5.99452189536827,1.10452846326765 5.99862953475457,1.05233595624294 6.0,1.0 5.99862953475457,0.947664043757057 5.99452189536827,0.895471536732348 5.98768834059514,0.84356553495977 5.97814760073381,0.792088309182242 5.96592582628907,0.741180954897481 5.95105651629515,0.690983005625054 5.9335804264972,0.641632050454702 5.9135454576426,0.593263356924202 5.89100652418837,0.546009500260455 5.86602540378444,0.5 5.83867056794543,0.455360964984975 5.80901699437495,0.412214747707529 5.77714596145697,0.370679608950165 5.7431448254774,0.330869393641144 5.70710678118655,0.292893218813455 5.66913060635886,0.256855174522608 5.62932039104984,0.222854038543031 5.58778525229248,0.190983005625055 5.54463903501503,0.161329432054578 5.5,0.133974596215563 5.45399049973955,0.108993475811634 5.4067366430758,0.086454542357401 5.3583679495453,0.0664195735028 5.30901699437495,0.048943483704848 5.25881904510253,0.034074173710933 5.20791169081776,0.021852399266195 5.15643446504024,0.012311659404863 5.10452846326766,0.005478104631727 5.05233595624295,0.001370465245426 5.0,0.0 3,0 2.94766404375705,0.001370465245426 2.89547153673234,0.005478104631727 2.84356553495977,0.012311659404863 2.79208830918224,0.021852399266195 2.74118095489748,0.034074173710932 2.69098300562505,0.048943483704847 2.6416320504547,0.066419573502799 2.5932633569242,0.0864545423574 2.54600950026045,0.108993475811633 2.5,0.133974596215562 2.45536096498497,0.161329432054577 2.41221474770753,0.190983005625053 2.37067960895016,0.22285403854303 2.33086939364114,0.256855174522607 2.29289321881345,0.292893218813453 2.25685517452261,0.330869393641143 2.22285403854303,0.370679608950163 2.19098300562505,0.412214747707528 2.16132943205458,0.455360964984974 2.13397459621556,0.5 2.10899347581163,0.546009500260454 2.0864545423574,0.5932633569242 2.0664195735028,0.6416320504547 2.04894348370485,0.690983005625053 2.03407417371093,0.74118095489748 2.02185239926619,0.79208830918224 2.01231165940486,0.843565534959769 2.00547810463173,0.895471536732346 2.00137046524543,0.947664043757056 2.0,1.0 2.00137046524543,1.05233595624294 2.00547810463173,1.10452846326765 2.01231165940486,1.15643446504023 2.02185239926619,1.20791169081776 2.03407417371093,1.25881904510252 2.04894348370485,1.30901699437495 2.0664195735028,1.3583679495453 2.0864545423574,1.4067366430758 2.10899347581163,1.45399049973955 2.13397459621556,1.5 2.16132943205458,1.54463903501503 2.19098300562505,1.58778525229247 2.22285403854303,1.62932039104984 2.2568551745226,1.66913060635886 2.29289321881345,1.70710678118655 2.33086939364114,1.74314482547739 2.37067960895016,1.77714596145697 2.41221474770752,1.80901699437495 2.45536096498497,1.83867056794542 2.5,1.86602540378444 2.54600950026045,1.89100652418837 2.5932633569242,1.9135454576426 2.6416320504547,1.9335804264972 2.69098300562505,1.95105651629515 2.74118095489748,1.96592582628907 2.79208830918224,1.9781476007338 2.84356553495976,1.98768834059514 2.89547153673234,1.99452189536827 2.94766404375705,1.99862953475457 3.0,2.0 5,2 + + + + + 10,-2 10.0523359562429,-2.00137046524543 10.1045284632677,-2.00547810463173 10.1564344650402,-2.01231165940486 10.2079116908178,-2.02185239926619 10.2588190451025,-2.03407417371093 10.3090169943749,-2.04894348370485 10.3583679495453,-2.0664195735028 10.4067366430758,-2.0864545423574 10.4539904997395,-2.10899347581163 10.5,-2.13397459621556 10.544639035015,-2.16132943205458 10.5877852522925,-2.19098300562505 10.6293203910498,-2.22285403854303 10.6691306063589,-2.25685517452261 10.7071067811865,-2.29289321881345 10.7431448254774,-2.33086939364114 10.777145961457,-2.37067960895016 10.8090169943749,-2.41221474770753 10.8386705679454,-2.45536096498497 10.8660254037844,-2.5 10.8910065241884,-2.54600950026045 10.9135454576426,-2.5932633569242 10.9335804264972,-2.6416320504547 10.9510565162952,-2.69098300562505 10.9659258262891,-2.74118095489748 10.9781476007338,-2.79208830918224 10.9876883405951,-2.84356553495977 10.9945218953683,-2.89547153673235 10.9986295347546,-2.94766404375706 11.0,-3.0 10.9986295347546,-3.05233595624294 10.9945218953683,-3.10452846326765 10.9876883405951,-3.15643446504023 10.9781476007338,-3.20791169081776 10.9659258262891,-3.25881904510252 10.9510565162952,-3.30901699437495 10.9335804264972,-3.3583679495453 10.9135454576426,-3.4067366430758 10.8910065241884,-3.45399049973954 10.8660254037844,-3.5 10.8386705679454,-3.54463903501503 10.8090169943749,-3.58778525229247 10.777145961457,-3.62932039104984 10.7431448254774,-3.66913060635886 10.7071067811865,-3.70710678118655 10.6691306063589,-3.74314482547739 10.6293203910498,-3.77714596145697 10.5877852522925,-3.80901699437495 10.544639035015,-3.83867056794542 10.5,-3.86602540378444 10.4539904997396,-3.89100652418837 10.4067366430758,-3.9135454576426 10.3583679495453,-3.9335804264972 10.309016994375,-3.95105651629515 10.2588190451025,-3.96592582628907 10.2079116908178,-3.9781476007338 10.1564344650402,-3.98768834059514 10.1045284632677,-3.99452189536827 10.0523359562429,-3.99862953475457 10.0,-4.0 7,-4 6.94766404375705,-3.99862953475457 6.89547153673234,-3.99452189536827 6.84356553495977,-3.98768834059514 6.79208830918224,-3.97814760073381 6.74118095489748,-3.96592582628907 6.69098300562505,-3.95105651629515 6.6416320504547,-3.9335804264972 6.5932633569242,-3.9135454576426 6.54600950026045,-3.89100652418837 6.5,-3.86602540378444 6.45536096498497,-3.83867056794542 6.41221474770753,-3.80901699437495 6.37067960895016,-3.77714596145697 6.33086939364114,-3.74314482547739 6.29289321881345,-3.70710678118655 6.25685517452261,-3.66913060635886 6.22285403854303,-3.62932039104984 6.19098300562505,-3.58778525229247 6.16132943205458,-3.54463903501503 6.13397459621556,-3.5 6.10899347581163,-3.45399049973955 6.0864545423574,-3.4067366430758 6.0664195735028,-3.3583679495453 6.04894348370485,-3.30901699437495 6.03407417371093,-3.25881904510252 6.02185239926619,-3.20791169081776 6.01231165940486,-3.15643446504023 6.00547810463173,-3.10452846326765 6.00137046524543,-3.05233595624294 6.0,-3.0 6.00137046524543,-2.94766404375706 6.00547810463173,-2.89547153673235 6.01231165940486,-2.84356553495977 6.02185239926619,-2.79208830918224 6.03407417371093,-2.74118095489748 6.04894348370485,-2.69098300562505 6.0664195735028,-2.6416320504547 6.0864545423574,-2.5932633569242 6.10899347581163,-2.54600950026045 6.13397459621556,-2.5 6.16132943205457,-2.45536096498497 6.19098300562505,-2.41221474770753 6.22285403854303,-2.37067960895016 6.2568551745226,-2.33086939364114 6.29289321881345,-2.29289321881345 6.33086939364114,-2.25685517452261 6.37067960895016,-2.22285403854303 6.41221474770752,-2.19098300562505 6.45536096498497,-2.16132943205458 6.5,-2.13397459621556 6.54600950026045,-2.10899347581163 6.5932633569242,-2.0864545423574 6.6416320504547,-2.0664195735028 6.69098300562505,-2.04894348370485 6.74118095489748,-2.03407417371093 6.79208830918224,-2.0218523992662 6.84356553495976,-2.01231165940486 6.89547153673234,-2.00547810463173 6.94766404375705,-2.00137046524543 7.0,-2.0 10,-2 + + + + + 9.29289321881345,1.70710678118655 9.33086939364114,1.7431448254774 9.37067960895016,1.77714596145697 9.41221474770753,1.80901699437495 9.45536096498497,1.83867056794542 9.5,1.86602540378444 9.54600950026046,1.89100652418837 9.5932633569242,1.9135454576426 9.6416320504547,1.9335804264972 9.69098300562505,1.95105651629515 9.74118095489748,1.96592582628907 9.79208830918224,1.97814760073381 9.84356553495977,1.98768834059514 9.89547153673235,1.99452189536827 9.94766404375706,1.99862953475457 10.0,2.0 10.0523359562429,1.99862953475457 10.1045284632677,1.99452189536827 10.1564344650402,1.98768834059514 10.2079116908178,1.97814760073381 10.2588190451025,1.96592582628907 10.3090169943749,1.95105651629515 10.3583679495453,1.9335804264972 10.4067366430758,1.9135454576426 10.4539904997395,1.89100652418837 10.5,1.86602540378444 10.544639035015,1.83867056794542 10.5877852522925,1.80901699437495 10.6293203910498,1.77714596145697 10.6691306063589,1.74314482547739 10.7071067811865,1.70710678118655 10.7431448254774,1.66913060635886 10.777145961457,1.62932039104984 10.8090169943749,1.58778525229247 10.8386705679454,1.54463903501503 10.8660254037844,1.5 10.8910065241884,1.45399049973955 10.9135454576426,1.4067366430758 10.9335804264972,1.3583679495453 10.9510565162952,1.30901699437495 10.9659258262891,1.25881904510252 10.9781476007338,1.20791169081776 10.9876883405951,1.15643446504023 10.9945218953683,1.10452846326766 10.9986295347546,1.05233595624295 11.0,1.0 10.9986295347546,0.947664043757059 10.9945218953683,0.895471536732349 10.9876883405951,0.843565534959772 10.9781476007338,0.792088309182244 10.9659258262891,0.741180954897483 10.9510565162952,0.690983005625056 10.9335804264972,0.641632050454703 10.9135454576426,0.593263356924203 10.8910065241884,0.546009500260457 10.8660254037844,0.5 10.8386705679454,0.455360964984977 10.809016994375,0.412214747707531 10.777145961457,0.370679608950166 10.7431448254774,0.330869393641145 10.7071067811866,0.292893218813456 6.70710678118655,-3.70710678118655 6.66913060635886,-3.7431448254774 6.62932039104984,-3.77714596145697 6.58778525229247,-3.80901699437495 6.54463903501503,-3.83867056794542 6.5,-3.86602540378444 6.45399049973955,-3.89100652418837 6.4067366430758,-3.9135454576426 6.3583679495453,-3.9335804264972 6.30901699437495,-3.95105651629515 6.25881904510252,-3.96592582628907 6.20791169081776,-3.97814760073381 6.15643446504023,-3.98768834059514 6.10452846326765,-3.99452189536827 6.05233595624294,-3.99862953475457 6.0,-4.0 5.94766404375706,-3.99862953475457 5.89547153673235,-3.99452189536827 5.84356553495977,-3.98768834059514 5.79208830918224,-3.97814760073381 5.74118095489748,-3.96592582628907 5.69098300562505,-3.95105651629515 5.6416320504547,-3.9335804264972 5.5932633569242,-3.9135454576426 5.54600950026045,-3.89100652418837 5.5,-3.86602540378444 5.45536096498497,-3.83867056794542 5.41221474770753,-3.80901699437495 5.37067960895016,-3.77714596145697 5.33086939364114,-3.74314482547739 5.29289321881345,-3.70710678118655 5.25685517452261,-3.66913060635886 5.22285403854303,-3.62932039104984 5.19098300562505,-3.58778525229247 5.16132943205458,-3.54463903501503 5.13397459621556,-3.5 5.10899347581163,-3.45399049973955 5.0864545423574,-3.4067366430758 5.0664195735028,-3.3583679495453 5.04894348370485,-3.30901699437495 5.03407417371093,-3.25881904510252 5.0218523992662,-3.20791169081776 5.01231165940486,-3.15643446504023 5.00547810463173,-3.10452846326766 5.00137046524543,-3.05233595624295 5.0,-3.0 5.00137046524543,-2.94766404375706 5.00547810463173,-2.89547153673235 5.01231165940486,-2.84356553495977 5.02185239926619,-2.79208830918224 5.03407417371093,-2.74118095489748 5.04894348370485,-2.69098300562506 5.0664195735028,-2.6416320504547 5.0864545423574,-2.5932633569242 5.10899347581163,-2.54600950026046 5.13397459621556,-2.5 5.16132943205457,-2.45536096498498 5.19098300562505,-2.41221474770753 5.22285403854303,-2.37067960895017 5.2568551745226,-2.33086939364115 5.29289321881345,-2.29289321881346 9.29289321881345,1.70710678118655 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index e2daf147eedd..30578c4b7e2e 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -72,3 +72,17 @@ tests: - 'Geometry: Line String' - 'Feature Count: [6|7]' # On some platforms returns 6 instead of 7... + - algorithm: gdalogr:buffervectors + name: OGR buffer lines + params: + DISSOLVEALL: false + DISTANCE: '1' + GEOMETRY: geometry + INPUT_LAYER: + name: lines.gml + type: vector + MULTI: false + results: + OUTPUT_LAYER: + name: expected/gdal/buffer_lines.gml + type: vector diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 61f0f84212b6..feea4c7699ad 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -331,12 +331,7 @@ def exportVectorLayer(layer, supported=None): del writer return output else: - isASCII = True - try: - str(layer.source()) - except UnicodeEncodeError: - isASCII = False - if not os.path.splitext(layer.source())[1].lower() in supported or not isASCII: + if not os.path.splitext(layer.source())[1].lower() in supported: writer = QgsVectorFileWriter( output, systemEncoding, layer.fields(), layer.wkbType(), @@ -347,7 +342,7 @@ def exportVectorLayer(layer, supported=None): del writer return output else: - return str(layer.source()) + return layer.source() def exportRasterLayer(layer): diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 2d2ac2067290..34f68d696095 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -538,7 +538,6 @@ def ogrConnectionString(uri): return '"' + ogrstr + '"' -# # The uri parameter is an URI from any QGIS provider, # so could have different formats. # Example formats: @@ -623,7 +622,7 @@ def __init__(self, destination, encoding, fields, geometryType, if encoding is None: settings = QSettings() - encoding = settings.value('/Processing/encoding', 'System', type=str) + encoding = settings.value('/Processing/encoding', 'System', str) if self.destination.startswith(self.MEMORY_LAYER_PREFIX): self.isNotFileBased = True @@ -650,8 +649,6 @@ def __init__(self, destination, encoding, fields, geometryType, QgsCredentials.instance().put(connInfo, user, passwd) else: raise GeoAlgorithmExecutionException("Couldn't connect to database") - # fix_print_with_import - print(uri.uri()) try: db = postgis.GeoDB(host=uri.host(), port=int(uri.port()), dbname=uri.database(), user=user, passwd=passwd) @@ -682,8 +679,6 @@ def _runSQL(sql): elif self.destination.startswith(self.SPATIALITE_LAYER_PREFIX): self.isNotFileBased = True uri = QgsDataSourceUri(self.destination[len(self.SPATIALITE_LAYER_PREFIX):]) - # fix_print_with_import - print(uri.uri()) try: db = spatialite.GeoDB(uri=uri) except spatialite.DbError as e: From a6bd9f020706fa99ee5bb863b5894a2dcb4682ab Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 10:25:59 +0200 Subject: [PATCH 704/897] Revert "Fix extraction of ogr LayerName from multi-layer dataset URIs" This reverts commit 6c5364186dd8d45ac51e5bd1a72c6a542f032cb1. As it breaks all OGR geoprocessing algoroithms. --- python/plugins/processing/tests/ToolsTest.py | 56 -------------------- python/plugins/processing/tools/vector.py | 51 +++++------------- 2 files changed, 12 insertions(+), 95 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index dd9549691069..a738c3e9bfa8 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -31,72 +31,17 @@ from qgis.core import (QgsVectorLayer, QgsFeatureRequest) from processing.core.ProcessingConfig import ProcessingConfig -import os.path -import errno -import shutil - -dataFolder = os.path.join(os.path.dirname(__file__), '../../../../tests/testdata/') -tmpBaseFolder = os.path.join(os.sep, 'tmp', 'qgis_test', str(os.getpid())) - - -def mkDirP(path): - try: - os.makedirs(path) - except OSError as exc: - if exc.errno == errno.EEXIST and os.path.isdir(path): - pass - else: - raise - start_app() class VectorTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - mkDirP(tmpBaseFolder) - - @classmethod - def tearDownClass(cls): - shutil.rmtree(tmpBaseFolder) - pass - - # See http://hub.qgis.org/issues/15698 - def test_ogrLayerName(self): - tmpdir = os.path.join(tmpBaseFolder, 'ogrLayerName') - os.mkdir(tmpdir) - - def linkTestfile(f, t): - os.link(os.path.join(dataFolder, f), os.path.join(tmpdir, t)) - # URI from OGR provider - linkTestfile('geom_data.csv', 'a.csv') - name = vector.ogrLayerName(tmpdir) - self.assertEqual(name, 'a') - # URI from OGR provider - linkTestfile('wkt_data.csv', 'b.csv') - name = vector.ogrLayerName(tmpdir + '|layerid=0') - self.assertEqual(name, 'a') - name = vector.ogrLayerName(tmpdir + '|layerid=1') - self.assertEqual(name, 'b') - # URI from OGR provider - name = vector.ogrLayerName(tmpdir + '|layerid=2') - self.assertEqual(name, 'invalid-layerid') - # URI from OGR provider - name = vector.ogrLayerName(tmpdir + '|layername=f') - self.assertEqual(name, 'f') # layername takes precedence - # URI from OGR provider - name = vector.ogrLayerName(tmpdir + '|layerid=0|layername=f2') - self.assertEqual(name, 'f2') # layername takes precedence - # URI from OGR provider - name = vector.ogrLayerName(tmpdir + '|layername=f2|layerid=0') - self.assertEqual(name, 'f2') # layername takes precedence # URI from Sqlite provider name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=') @@ -105,7 +50,6 @@ def linkTestfile(f, t): # URI from PostgreSQL provider name = vector.ogrLayerName('port=5493 sslmode=disable key=\'edge_id\' srid=0 type=LineString table="city_data"."edge" (geom) sql=') self.assertEqual(name, 'city_data.edge') - def testFeatures(self): ProcessingConfig.initialize() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 34f68d696095..2b230bbe80e7 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -41,8 +41,6 @@ import psycopg2 -from osgeo import ogr - from qgis.PyQt.QtCore import QVariant, QSettings from qgis.core import (Qgis, QgsFields, QgsField, QgsGeometry, QgsRectangle, QgsWkbTypes, QgsSpatialIndex, QgsMapLayerRegistry, QgsMapLayer, QgsVectorLayer, @@ -558,46 +556,21 @@ def ogrConnectionString(uri): # /tmp/x.gdb|layername=thelayer # def ogrLayerName(uri): - - # handle URIs of database providers - if ' table=' in uri: - # Matches table="schema"."table" - re_table_schema = re.compile(' table="([^"]*)"\."([^"]*)"') - r = re_table_schema.search(uri) - if r: - return r.groups()[0] + '.' + r.groups()[1] - # Matches table="table" - re_table = re.compile(' table="([^"]*)"') - r = re_table.search(uri) - if r: - return r.groups()[0] - - # handle URIs of OGR provider with explicit layername - if 'layername' in uri: - regex = re.compile('(layername=)([^|]*)') + if 'host' in uri: + regex = re.compile('(table=")(.+?)(\.)(.+?)"') + r = regex.search(uri) + return '"' + r.groups()[1] + '.' + r.groups()[3] + '"' + elif 'dbname' in uri: + regex = re.compile('(table=")(.+?)"') r = regex.search(uri) return r.groups()[1] + elif 'layername' in uri: + regex = re.compile('(layername=)(.*)') + r = regex.search(uri) + return r.groups()[1] + else: + return os.path.basename(os.path.splitext(uri)[0]) - fields = uri.split('|') - ogruri = fields[0] - fields = fields[1:] - layerid = 0 - for f in fields: - if f.startswith('layername='): - # Name encoded in uri, nothing more needed - return f.split('=')[1] - if f.startswith('layerid='): - layerid = int(f.split('=')[1]) - # Last layerid= takes precedence, to allow of layername to - # take precedence - ds = ogr.Open(ogruri) - if not ds: - return "invalid-uri" - ly = ds.GetLayer(layerid) - if not ly: - return "invalid-layerid" - name = ly.GetName() - return name class VectorWriter(object): From 31a6189a9cf7306c0cf302576f385c05636cba95 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 11:29:18 +0200 Subject: [PATCH 705/897] [processing] add test for OGR polygon buffering --- .../testdata/expected/gdal/buffer_polys.gfs | 32 ++++++++++ .../testdata/expected/gdal/buffer_polys.gml | 58 +++++++++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 14 +++++ 3 files changed, 104 insertions(+) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gml diff --git a/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gfs b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gfs new file mode 100644 index 000000000000..96b8f2bc468c --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gfs @@ -0,0 +1,32 @@ + + + buffer_polys + buffer_polys + + 3 + EPSG:4326 + + 6 + -1.50000 + 10.50000 + -3.50000 + 6.50000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gml b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gml new file mode 100644 index 000000000000..dc5a14582c94 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys.gml @@ -0,0 +1,58 @@ + + + + + -1.5-3.5 + 10.56.5 + + + + + + -1.0,-1.5 -1.02616797812147,-1.49931476737729 -1.05226423163383,-1.49726094768414 -1.07821723252012,-1.49384417029757 -1.10395584540888,-1.4890738003669 -1.12940952255126,-1.48296291314453 -1.15450849718748,-1.47552825814758 -1.17918397477265,-1.4667902132486 -1.2033683215379,-1.4567727288213 -1.22699524986978,-1.44550326209418 -1.25,-1.43301270189222 -1.27231951750752,-1.41933528397271 -1.29389262614624,-1.40450849718747 -1.31466019552492,-1.38857298072848 -1.33456530317943,-1.3715724127387 -1.35355339059327,-1.35355339059327 -1.3715724127387,-1.33456530317943 -1.38857298072849,-1.31466019552492 -1.40450849718747,-1.29389262614624 -1.41933528397271,-1.27231951750751 -1.43301270189222,-1.25 -1.44550326209418,-1.22699524986977 -1.4567727288213,-1.2033683215379 -1.4667902132486,-1.17918397477265 -1.47552825814758,-1.15450849718747 -1.48296291314453,-1.12940952255126 -1.4890738003669,-1.10395584540888 -1.49384417029757,-1.07821723252012 -1.49726094768414,-1.05226423163383 -1.49931476737729,-1.02616797812147 -1.5,-1.0 -1.5,3.0 -1.49931476737729,3.02616797812147 -1.49726094768414,3.05226423163383 -1.49384417029757,3.07821723252012 -1.4890738003669,3.10395584540888 -1.48296291314453,3.12940952255126 -1.47552825814758,3.15450849718747 -1.4667902132486,3.17918397477265 -1.4567727288213,3.2033683215379 -1.44550326209418,3.22699524986977 -1.43301270189222,3.25 -1.41933528397271,3.27231951750751 -1.40450849718747,3.29389262614624 -1.38857298072849,3.31466019552492 -1.3715724127387,3.33456530317943 -1.35355339059327,3.35355339059327 -1.33456530317943,3.3715724127387 -1.31466019552492,3.38857298072849 -1.29389262614624,3.40450849718747 -1.27231951750751,3.41933528397271 -1.25,3.43301270189222 -1.22699524986977,3.44550326209418 -1.2033683215379,3.4567727288213 -1.17918397477265,3.4667902132486 -1.15450849718747,3.47552825814758 -1.12940952255126,3.48296291314453 -1.10395584540888,3.4890738003669 -1.07821723252012,3.49384417029757 -1.05226423163383,3.49726094768414 -1.02616797812147,3.49931476737729 -1.0,3.5 3.0,3.5 3.02616797812147,3.49931476737729 3.05226423163383,3.49726094768414 3.07821723252012,3.49384417029757 3.10395584540888,3.4890738003669 3.12940952255126,3.48296291314453 3.15450849718747,3.47552825814758 3.17918397477265,3.4667902132486 3.2033683215379,3.4567727288213 3.22699524986977,3.44550326209418 3.25,3.43301270189222 3.27231951750751,3.41933528397271 3.29389262614624,3.40450849718747 3.31466019552492,3.38857298072849 3.33456530317943,3.3715724127387 3.35355339059327,3.35355339059327 3.3715724127387,3.33456530317943 3.38857298072849,3.31466019552492 3.40450849718747,3.29389262614624 3.41933528397271,3.27231951750751 3.43301270189222,3.25 3.44550326209418,3.22699524986977 3.4567727288213,3.2033683215379 3.4667902132486,3.17918397477265 3.47552825814758,3.15450849718747 3.48296291314453,3.12940952255126 3.4890738003669,3.10395584540888 3.49384417029757,3.07821723252012 3.49726094768414,3.05226423163383 3.49931476737729,3.02616797812147 3.5,3.0 3.5,2.0 3.49931476737729,1.97383202187853 3.49726094768414,1.94773576836617 3.49384417029757,1.92178276747988 3.4890738003669,1.89604415459112 3.48296291314453,1.87059047744874 3.47552825814758,1.84549150281253 3.4667902132486,1.82081602522735 3.4567727288213,1.7966316784621 3.44550326209418,1.77300475013023 3.43301270189222,1.75 3.41933528397271,1.72768048249249 3.40450849718747,1.70610737385376 3.38857298072849,1.68533980447508 3.3715724127387,1.66543469682057 3.35355339059327,1.64644660940673 3.33456530317943,1.6284275872613 3.31466019552492,1.61142701927151 3.29389262614624,1.59549150281253 3.27231951750751,1.58066471602729 3.25,1.56698729810778 3.22699524986977,1.55449673790582 3.2033683215379,1.5432272711787 3.17918397477265,1.5332097867514 3.15450849718747,1.52447174185242 3.12940952255126,1.51703708685547 3.10395584540888,1.5109261996331 3.07821723252012,1.50615582970243 3.05226423163383,1.50273905231586 3.02616797812147,1.50068523262271 3.0,1.5 2.5,1.5 2.5,-1.0 2.49931476737729,-1.02616797812147 2.49726094768414,-1.05226423163383 2.49384417029757,-1.07821723252012 2.4890738003669,-1.10395584540888 2.48296291314453,-1.12940952255126 2.47552825814758,-1.15450849718747 2.4667902132486,-1.17918397477265 2.4567727288213,-1.2033683215379 2.44550326209418,-1.22699524986977 2.43301270189222,-1.25 2.41933528397271,-1.27231951750751 2.40450849718747,-1.29389262614624 2.38857298072849,-1.31466019552492 2.3715724127387,-1.33456530317943 2.35355339059327,-1.35355339059327 2.33456530317943,-1.3715724127387 2.31466019552492,-1.38857298072849 2.29389262614624,-1.40450849718747 2.27231951750751,-1.41933528397271 2.25,-1.43301270189222 2.22699524986977,-1.44550326209418 2.2033683215379,-1.4567727288213 2.17918397477265,-1.4667902132486 2.15450849718747,-1.47552825814758 2.12940952255126,-1.48296291314453 2.10395584540888,-1.4890738003669 2.07821723252012,-1.49384417029757 2.05226423163383,-1.49726094768414 2.02616797812147,-1.49931476737729 2.0,-1.5 -1.0,-1.5 + aaaaa + 33 + 44.123455999999997 + + + + + 4.64644660940673,5.35355339059327 4.66543469682057,5.3715724127387 4.68533980447508,5.38857298072849 4.70610737385376,5.40450849718747 4.72768048249249,5.41933528397271 4.75,5.43301270189222 4.77300475013023,5.44550326209418 4.7966316784621,5.4567727288213 4.82081602522735,5.4667902132486 4.84549150281253,5.47552825814758 4.87059047744874,5.48296291314453 4.89604415459112,5.4890738003669 4.92178276747988,5.49384417029757 4.94773576836617,5.49726094768414 4.97383202187853,5.49931476737729 5.0,5.5 5.02616797812147,5.49931476737729 5.05226423163383,5.49726094768414 5.07821723252012,5.49384417029757 5.10395584540888,5.4890738003669 5.12940952255126,5.48296291314453 5.15450849718747,5.47552825814758 5.17918397477265,5.4667902132486 5.2033683215379,5.4567727288213 5.22699524986977,5.44550326209418 5.25,5.43301270189222 5.27231951750751,5.41933528397271 5.29389262614624,5.40450849718747 5.31466019552492,5.38857298072849 5.33456530317943,5.3715724127387 5.35355339059327,5.35355339059327 6.35355339059327,4.35355339059327 6.3715724127387,4.33456530317943 6.38857298072849,4.31466019552492 6.40450849718747,4.29389262614624 6.41933528397271,4.27231951750751 6.43301270189222,4.25 6.44550326209418,4.22699524986977 6.4567727288213,4.2033683215379 6.4667902132486,4.17918397477265 6.47552825814758,4.15450849718747 6.48296291314453,4.12940952255126 6.4890738003669,4.10395584540888 6.49384417029757,4.07821723252012 6.49726094768414,4.05226423163383 6.49931476737729,4.02616797812147 6.5,4.0 6.49931476737729,3.97383202187853 6.49726094768414,3.94773576836617 6.49384417029757,3.92178276747988 6.4890738003669,3.89604415459112 6.48296291314453,3.87059047744874 6.47552825814758,3.84549150281253 6.4667902132486,3.82081602522735 6.4567727288213,3.7966316784621 6.44550326209418,3.77300475013023 6.43301270189222,3.75 6.41933528397271,3.72768048249249 6.40450849718747,3.70610737385376 6.38857298072849,3.68533980447508 6.3715724127387,3.66543469682057 6.35355339059327,3.64644660940673 6.33456530317943,3.6284275872613 6.31466019552492,3.61142701927151 6.29389262614624,3.59549150281253 6.27231951750751,3.58066471602729 6.25,3.56698729810778 6.22699524986977,3.55449673790582 6.2033683215379,3.5432272711787 6.17918397477265,3.5332097867514 6.15450849718747,3.52447174185242 6.12940952255126,3.51703708685547 6.10395584540888,3.5109261996331 6.07821723252012,3.50615582970243 6.05226423163383,3.50273905231586 6.02616797812147,3.50068523262271 6.0,3.5 4.0,3.5 3.97383202187852,3.50068523262271 3.94773576836617,3.50273905231586 3.92178276747988,3.50615582970243 3.89604415459112,3.5109261996331 3.87059047744874,3.51703708685547 3.84549150281252,3.52447174185242 3.82081602522735,3.5332097867514 3.7966316784621,3.5432272711787 3.77300475013022,3.55449673790582 3.75,3.56698729810778 3.72768048249248,3.58066471602729 3.70610737385376,3.59549150281253 3.68533980447508,3.61142701927152 3.66543469682057,3.6284275872613 3.64644660940672,3.64644660940673 3.6284275872613,3.66543469682057 3.61142701927151,3.68533980447508 3.59549150281253,3.70610737385377 3.58066471602729,3.72768048249249 3.56698729810778,3.75 3.55449673790581,3.77300475013023 3.5432272711787,3.7966316784621 3.5332097867514,3.82081602522735 3.52447174185242,3.84549150281253 3.51703708685547,3.87059047744874 3.5109261996331,3.89604415459112 3.50615582970243,3.92178276747989 3.50273905231586,3.94773576836617 3.50068523262271,3.97383202187853 3.5,4.0 3.50068523262271,4.02616797812147 3.50273905231586,4.05226423163383 3.50615582970243,4.07821723252012 3.5109261996331,4.10395584540888 3.51703708685547,4.12940952255126 3.52447174185242,4.15450849718747 3.5332097867514,4.17918397477265 3.5432272711787,4.2033683215379 3.55449673790582,4.22699524986977 3.56698729810778,4.25 3.58066471602729,4.27231951750751 3.59549150281253,4.29389262614624 3.61142701927151,4.31466019552492 3.6284275872613,4.33456530317943 3.64644660940673,4.35355339059327 4.64644660940673,5.35355339059327 + Aaaaa + -33 + 0.000000000000000 + + + + + 2.0,4.5 1.97383202187853,4.50068523262271 1.94773576836617,4.50273905231586 1.92178276747988,4.50615582970243 1.89604415459112,4.5109261996331 1.87059047744874,4.51703708685547 1.84549150281252,4.52447174185242 1.82081602522735,4.5332097867514 1.7966316784621,4.5432272711787 1.77300475013022,4.55449673790582 1.75,4.56698729810778 1.72768048249248,4.58066471602729 1.70610737385376,4.59549150281253 1.68533980447508,4.61142701927152 1.66543469682057,4.6284275872613 1.64644660940673,4.64644660940673 1.6284275872613,4.66543469682057 1.61142701927151,4.68533980447508 1.59549150281253,4.70610737385376 1.58066471602729,4.72768048249249 1.56698729810778,4.75 1.55449673790582,4.77300475013023 1.5432272711787,4.7966316784621 1.5332097867514,4.82081602522735 1.52447174185242,4.84549150281253 1.51703708685547,4.87059047744874 1.5109261996331,4.89604415459112 1.50615582970243,4.92178276747988 1.50273905231586,4.94773576836617 1.50068523262271,4.97383202187853 1.5,5.0 1.5,6.0 1.50068523262271,6.02616797812147 1.50273905231586,6.05226423163383 1.50615582970243,6.07821723252012 1.5109261996331,6.10395584540888 1.51703708685547,6.12940952255126 1.52447174185242,6.15450849718747 1.5332097867514,6.17918397477265 1.5432272711787,6.2033683215379 1.55449673790582,6.22699524986977 1.56698729810778,6.25 1.58066471602729,6.27231951750751 1.59549150281253,6.29389262614624 1.61142701927151,6.31466019552492 1.6284275872613,6.33456530317943 1.64644660940673,6.35355339059327 1.66543469682057,6.3715724127387 1.68533980447508,6.38857298072849 1.70610737385376,6.40450849718747 1.72768048249249,6.41933528397271 1.75,6.43301270189222 1.77300475013023,6.44550326209418 1.7966316784621,6.4567727288213 1.82081602522735,6.4667902132486 1.84549150281253,6.47552825814758 1.87059047744874,6.48296291314453 1.89604415459112,6.4890738003669 1.92178276747988,6.49384417029757 1.94773576836617,6.49726094768414 1.97383202187853,6.49931476737729 2.0,6.5 3.0,6.5 3.02616797812147,6.49931476737729 3.05226423163383,6.49726094768414 3.07821723252012,6.49384417029757 3.10395584540888,6.4890738003669 3.12940952255126,6.48296291314453 3.15450849718747,6.47552825814758 3.17918397477265,6.4667902132486 3.2033683215379,6.4567727288213 3.22699524986977,6.44550326209418 3.25,6.43301270189222 3.27231951750751,6.41933528397271 3.29389262614624,6.40450849718747 3.31466019552492,6.38857298072849 3.33456530317943,6.3715724127387 3.35355339059327,6.35355339059327 3.3715724127387,6.33456530317943 3.38857298072849,6.31466019552492 3.40450849718747,6.29389262614624 3.41933528397271,6.27231951750751 3.43301270189222,6.25 3.44550326209418,6.22699524986977 3.4567727288213,6.2033683215379 3.4667902132486,6.17918397477265 3.47552825814758,6.15450849718747 3.48296291314453,6.12940952255126 3.4890738003669,6.10395584540888 3.49384417029757,6.07821723252012 3.49726094768414,6.05226423163383 3.49931476737729,6.02616797812147 3.5,6.0 3.5,5.0 3.49931476737729,4.97383202187853 3.49726094768414,4.94773576836617 3.49384417029757,4.92178276747988 3.4890738003669,4.89604415459112 3.48296291314453,4.87059047744874 3.47552825814758,4.84549150281253 3.4667902132486,4.82081602522735 3.4567727288213,4.7966316784621 3.44550326209418,4.77300475013023 3.43301270189222,4.75 3.41933528397271,4.72768048249249 3.40450849718747,4.70610737385376 3.38857298072849,4.68533980447508 3.3715724127387,4.66543469682057 3.35355339059327,4.64644660940673 3.33456530317943,4.6284275872613 3.31466019552492,4.61142701927151 3.29389262614624,4.59549150281253 3.27231951750751,4.58066471602729 3.25,4.56698729810778 3.22699524986977,4.55449673790582 3.2033683215379,4.5432272711787 3.17918397477265,4.5332097867514 3.15450849718747,4.52447174185242 3.12940952255126,4.51703708685547 3.10395584540888,4.5109261996331 3.07821723252012,4.50615582970243 3.05226423163383,4.50273905231586 3.02616797812147,4.50068523262271 3.0,4.5 2.0,4.5 + bbaaa + 0.123000000000000 + + + + + 5.5,1.0 5.50068523262271,1.02616797812147 5.50273905231586,1.05226423163383 5.50615582970243,1.07821723252012 5.5109261996331,1.10395584540888 5.51703708685547,1.12940952255126 5.52447174185242,1.15450849718747 5.5332097867514,1.17918397477265 5.5432272711787,1.2033683215379 5.55449673790582,1.22699524986977 5.56698729810778,1.25 5.58066471602729,1.27231951750751 5.59549150281253,1.29389262614624 5.61142701927151,1.31466019552492 5.6284275872613,1.33456530317943 5.64644660940673,1.35355339059327 5.66543469682057,1.3715724127387 5.68533980447508,1.38857298072849 5.70610737385376,1.40450849718747 5.72768048249249,1.41933528397271 5.75,1.43301270189222 5.77300475013023,1.44550326209418 5.7966316784621,1.4567727288213 5.82081602522735,1.4667902132486 5.84549150281253,1.47552825814758 5.87059047744874,1.48296291314453 5.89604415459112,1.4890738003669 5.92178276747988,1.49384417029757 5.94773576836617,1.49726094768414 5.97383202187853,1.49931476737729 6.0,1.5 10.0,1.5 10.0261679781215,1.49931476737729 10.0522642316338,1.49726094768414 10.0782172325201,1.49384417029757 10.1039558454089,1.4890738003669 10.1294095225513,1.48296291314453 10.1545084971875,1.47552825814758 10.1791839747727,1.4667902132486 10.2033683215379,1.4567727288213 10.2269952498698,1.44550326209418 10.25,1.43301270189222 10.2723195175075,1.41933528397271 10.2938926261462,1.40450849718747 10.3146601955249,1.38857298072849 10.3345653031794,1.3715724127387 10.3535533905933,1.35355339059327 10.3715724127387,1.33456530317943 10.3885729807285,1.31466019552492 10.4045084971875,1.29389262614624 10.4193352839727,1.27231951750751 10.4330127018922,1.25 10.4455032620942,1.22699524986977 10.4567727288213,1.2033683215379 10.4667902132486,1.17918397477265 10.4755282581476,1.15450849718747 10.4829629131445,1.12940952255126 10.4890738003669,1.10395584540888 10.4938441702976,1.07821723252012 10.4972609476841,1.05226423163383 10.4993147673773,1.02616797812147 10.5,1.0 10.5,-3.0 10.4993147673773,-3.02616797812147 10.4972609476841,-3.05226423163383 10.4938441702976,-3.07821723252012 10.4890738003669,-3.10395584540888 10.4829629131445,-3.12940952255126 10.4755282581476,-3.15450849718747 10.4667902132486,-3.17918397477265 10.4567727288213,-3.2033683215379 10.4455032620942,-3.22699524986977 10.4330127018922,-3.25 10.4193352839727,-3.27231951750751 10.4045084971875,-3.29389262614624 10.3885729807285,-3.31466019552492 10.3715724127387,-3.33456530317943 10.3535533905933,-3.35355339059327 10.3345653031794,-3.3715724127387 10.3146601955249,-3.38857298072849 10.2938926261462,-3.40450849718747 10.2723195175075,-3.41933528397271 10.25,-3.43301270189222 10.2269952498698,-3.44550326209418 10.2033683215379,-3.4567727288213 10.1791839747727,-3.4667902132486 10.1545084971875,-3.47552825814758 10.1294095225513,-3.48296291314453 10.1039558454089,-3.4890738003669 10.0782172325201,-3.49384417029757 10.0522642316338,-3.49726094768414 10.0261679781215,-3.49931476737729 10.0,-3.5 6.0,-3.5 5.97383202187853,-3.49931476737729 5.94773576836617,-3.49726094768414 5.92178276747988,-3.49384417029757 5.89604415459112,-3.4890738003669 5.87059047744874,-3.48296291314453 5.84549150281252,-3.47552825814758 5.82081602522735,-3.4667902132486 5.7966316784621,-3.4567727288213 5.77300475013022,-3.44550326209418 5.75,-3.43301270189222 5.72768048249248,-3.41933528397271 5.70610737385376,-3.40450849718747 5.68533980447508,-3.38857298072848 5.66543469682057,-3.3715724127387 5.64644660940673,-3.35355339059327 5.6284275872613,-3.33456530317943 5.61142701927151,-3.31466019552492 5.59549150281253,-3.29389262614624 5.58066471602729,-3.27231951750751 5.56698729810778,-3.25 5.55449673790582,-3.22699524986977 5.5432272711787,-3.2033683215379 5.5332097867514,-3.17918397477265 5.52447174185242,-3.15450849718747 5.51703708685547,-3.12940952255126 5.5109261996331,-3.10395584540888 5.50615582970243,-3.07821723252012 5.50273905231586,-3.05226423163383 5.50068523262271,-3.02616797812147 5.5,-3.0 5.5,1.07.5,-0.5 7.5,-1.5 8.5,-1.5 8.5,-0.5 7.5,-0.5 + ASDF + 0 + + + + + 120 + -100291.432130000001052 + + + + + 3.0,2.5 3.02679969746181,2.49928125962823 3.05352234682556,2.49712710486382 3.08009112150348,2.49354372881875 3.10642963729163,2.48854143356114 3.13246217197148,2.4821346004972 3.15811388300842,2.47434164902526 6.15811388300842,1.47434164902526 6.18257509509854,1.46547431148213 6.20654190801939,1.4553465056764 6.22994942150409,1.44398565691916 6.25273424982517,1.43142252950595 6.27483469343818,1.41769114340951 6.2961909060593,1.40282868215629 6.31674505672436,1.38687539213638 6.33644148639068,1.3698744736194 6.35522685865737,1.35187196377151 6.37305030419617,1.33291661199036 6.38986355850167,1.31305974789554 6.40562109258778,1.29235514233188 6.42028023627676,1.27085886176227 6.43380129374668,1.24862911644397 6.44614765102466,1.22572610279978 6.45728587513466,1.20221184041082 6.46718580463135,1.17815000407229 6.47582063127501,1.15360575136711 6.4831669726261,1.12864554622423 6.48920493536315,1.10333697893946 6.49391816915229,1.07774858314624 6.49729391092269,1.05194965023186 6.49932301942798,1.02601004170175 6.5,1.0 6.5,-3.0 6.49931985147427,-3.02607078678739 6.49728125630515,-3.05207064554598 6.49388976068263,-3.07792884121337 6.4891545914897,-3.1035750241349 6.48308863119975,-3.12893942145656 6.47570838282857,-3.15395302694858 6.46703392503635,-3.17854778874335 6.45708885750182,-3.20265679447697 6.44590023671705,-3.22621445333063 6.43349850237779,-3.24915667447656 6.41991739456932,-3.2714210414432 6.40519386197348,-3.29294698192508 6.38936796134622,-3.31367593257547 6.37248274853944,-3.33355149833347 6.35458416136355,-3.35251960585208 6.33572089460927,-3.37052865060984 6.31594426756888,-3.3875296373058 6.2953080844173,-3.40347631315578 6.2738684878327,-3.41832529372754 6.25168380625513,-3.43203618097207 6.22881439519847,-3.4445716731304 6.20532247304756,-3.45589766621648 6.18127195178728,-3.46598334680032 6.15672826312394,-3.4748012758388 6.13175818047219,-3.48232746332617 6.10642963729163,-3.48854143356114 6.08081154226748,-3.49342628085293 6.05497359183799,-3.4969687155148 6.02898608057873,-3.49915910001991 6.00291970995958,-3.49999147522108 5.97684539599473,-3.49946357656326 5.95083407630899,-3.49757684024441 5.92495651714532,-3.49433639930824 5.89928312083856,-3.48975106967926 5.87388373427931,-3.48383332617821 5.84882745888886,-3.47659926858316 5.82418246262228,-3.46806857782854 5.80001579451109,-3.45826446246133 5.77639320225002,-3.44721359549996 1.77639320225002,-1.44721359549996 1.75313710128354,-1.43480881918069 1.73056700733767,-1.42119575314219 1.70874564042008,-1.40641222671776 1.68773363990178,-1.39049932183169 1.66758939600645,-1.37350125883676 1.6483688875499,-1.35546527363036 1.6301255263806,-1.33644148639068 1.61291000895357,-1.31648276229785 1.59677017545007,-1.29564456462691 1.58175087683455,-1.273984800621 1.56789385021836,-1.251563660573 1.55523760287657,-1.22844345056276 1.54381730524012,-1.20468841931485 1.53366469316076,-1.18036457965784 1.52480797972032,-1.15553952508131 1.51727177682944,-1.13028224190038 1.5110770268335,-1.10466291754977 1.50624094431604,-1.07875274553995 1.5027769682611,-1.05262372761763 1.50069472470769,-1.02634847368017 1.5,-1.0 1.5,2.0 1.50068523262271,2.02616797812147 1.50273905231586,2.05226423163383 1.50615582970243,2.07821723252012 1.5109261996331,2.10395584540888 1.51703708685547,2.12940952255126 1.52447174185242,2.15450849718747 1.5332097867514,2.17918397477265 1.5432272711787,2.2033683215379 1.55449673790582,2.22699524986977 1.56698729810778,2.25 1.58066471602729,2.27231951750751 1.59549150281253,2.29389262614624 1.61142701927151,2.31466019552492 1.6284275872613,2.33456530317943 1.64644660940673,2.35355339059327 1.66543469682057,2.3715724127387 1.68533980447508,2.38857298072849 1.70610737385376,2.40450849718747 1.72768048249249,2.41933528397271 1.75,2.43301270189222 1.77300475013023,2.44550326209418 1.7966316784621,2.4567727288213 1.82081602522735,2.4667902132486 1.84549150281253,2.47552825814758 1.87059047744874,2.48296291314453 1.89604415459112,2.4890738003669 1.92178276747988,2.49384417029757 1.94773576836617,2.49726094768414 1.97383202187853,2.49931476737729 2.0,2.5 3.0,2.5 + elim + 2 + 3.330000000000000 + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 30578c4b7e2e..f6686891534e 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -86,3 +86,17 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_lines.gml type: vector + - algorithm: gdalogr:buffervectors + name: OGR basic polygon buffer + params: + DISSOLVEALL: false + DISTANCE: '0.5' + GEOMETRY: geometry + INPUT_LAYER: + name: polys.gml + type: vector + MULTI: false + results: + OUTPUT_LAYER: + name: expected/gdal/buffer_polys.gml + type: vector From 23de13c03f39e67e4451aa9a4bbeb087c995b0f4 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 11:35:59 +0200 Subject: [PATCH 706/897] [processing] add test for OGR buffer with dissolve --- .../expected/gdal/buffer_polys_dissolve.gfs | 32 +++++++++++++++++++ .../expected/gdal/buffer_polys_dissolve.gml | 22 +++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 16 ++++++++++ 3 files changed, 70 insertions(+) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gml diff --git a/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gfs b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gfs new file mode 100644 index 000000000000..14ad992ba476 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gfs @@ -0,0 +1,32 @@ + + + buffer_polys_dissolve + buffer_polys_dissolve + + 6 + EPSG:4326 + + 1 + -1.50000 + 10.50000 + -3.50000 + 6.50000 + + + name + name + String + 4 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gml b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gml new file mode 100644 index 000000000000..095fb6cf0247 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/buffer_polys_dissolve.gml @@ -0,0 +1,22 @@ + + + + + -1.5-3.5 + 10.56.5 + + + + + + 2.0,4.5 1.97383202187853,4.50068523262271 1.94773576836617,4.50273905231586 1.92178276747988,4.50615582970243 1.89604415459112,4.5109261996331 1.87059047744874,4.51703708685547 1.84549150281252,4.52447174185242 1.82081602522735,4.5332097867514 1.7966316784621,4.5432272711787 1.77300475013022,4.55449673790582 1.75,4.56698729810778 1.72768048249248,4.58066471602729 1.70610737385376,4.59549150281253 1.68533980447508,4.61142701927152 1.66543469682057,4.6284275872613 1.64644660940673,4.64644660940673 1.6284275872613,4.66543469682057 1.61142701927151,4.68533980447508 1.59549150281253,4.70610737385376 1.58066471602729,4.72768048249249 1.56698729810778,4.75 1.55449673790582,4.77300475013023 1.5432272711787,4.7966316784621 1.5332097867514,4.82081602522735 1.52447174185242,4.84549150281253 1.51703708685547,4.87059047744874 1.5109261996331,4.89604415459112 1.50615582970243,4.92178276747988 1.50273905231586,4.94773576836617 1.50068523262271,4.97383202187853 1.5,5.0 1.5,6.0 1.50068523262271,6.02616797812147 1.50273905231586,6.05226423163383 1.50615582970243,6.07821723252012 1.5109261996331,6.10395584540888 1.51703708685547,6.12940952255126 1.52447174185242,6.15450849718747 1.5332097867514,6.17918397477265 1.5432272711787,6.2033683215379 1.55449673790582,6.22699524986977 1.56698729810778,6.25 1.58066471602729,6.27231951750751 1.59549150281253,6.29389262614624 1.61142701927151,6.31466019552492 1.6284275872613,6.33456530317943 1.64644660940673,6.35355339059327 1.66543469682057,6.3715724127387 1.68533980447508,6.38857298072849 1.70610737385376,6.40450849718747 1.72768048249249,6.41933528397271 1.75,6.43301270189222 1.77300475013023,6.44550326209418 1.7966316784621,6.4567727288213 1.82081602522735,6.4667902132486 1.84549150281253,6.47552825814758 1.87059047744874,6.48296291314453 1.89604415459112,6.4890738003669 1.92178276747988,6.49384417029757 1.94773576836617,6.49726094768414 1.97383202187853,6.49931476737729 2.0,6.5 3.0,6.5 3.02616797812147,6.49931476737729 3.05226423163383,6.49726094768414 3.07821723252012,6.49384417029757 3.10395584540888,6.4890738003669 3.12940952255126,6.48296291314453 3.15450849718747,6.47552825814758 3.17918397477265,6.4667902132486 3.2033683215379,6.4567727288213 3.22699524986977,6.44550326209418 3.25,6.43301270189222 3.27231951750751,6.41933528397271 3.29389262614624,6.40450849718747 3.31466019552492,6.38857298072849 3.33456530317943,6.3715724127387 3.35355339059327,6.35355339059327 3.3715724127387,6.33456530317943 3.38857298072849,6.31466019552492 3.40450849718747,6.29389262614624 3.41933528397271,6.27231951750751 3.43301270189222,6.25 3.44550326209418,6.22699524986977 3.4567727288213,6.2033683215379 3.4667902132486,6.17918397477265 3.47552825814758,6.15450849718747 3.48296291314453,6.12940952255126 3.4890738003669,6.10395584540888 3.49384417029757,6.07821723252012 3.49726094768414,6.05226423163383 3.49931476737729,6.02616797812147 3.5,6.0 3.5,5.0 3.49931476737729,4.97383202187853 3.49726094768414,4.94773576836617 3.49384417029757,4.92178276747988 3.4890738003669,4.89604415459112 3.48296291314453,4.87059047744874 3.47552825814758,4.84549150281253 3.4667902132486,4.82081602522735 3.4567727288213,4.7966316784621 3.44550326209418,4.77300475013023 3.43301270189222,4.75 3.41933528397271,4.72768048249249 3.40450849718747,4.70610737385376 3.38857298072849,4.68533980447508 3.3715724127387,4.66543469682057 3.35355339059327,4.64644660940673 3.33456530317943,4.6284275872613 3.31466019552492,4.61142701927151 3.29389262614624,4.59549150281253 3.27231951750751,4.58066471602729 3.25,4.56698729810778 3.22699524986977,4.55449673790582 3.2033683215379,4.5432272711787 3.17918397477265,4.5332097867514 3.15450849718747,4.52447174185242 3.12940952255126,4.51703708685547 3.10395584540888,4.5109261996331 3.07821723252012,4.50615582970243 3.05226423163383,4.50273905231586 3.02616797812147,4.50068523262271 3.0,4.5 2.0,4.56.08113883008419,1.5 10.0,1.5 10.0261679781215,1.49931476737729 10.0522642316338,1.49726094768414 10.0782172325201,1.49384417029757 10.1039558454089,1.4890738003669 10.1294095225513,1.48296291314453 10.1545084971875,1.47552825814758 10.1791839747727,1.4667902132486 10.2033683215379,1.4567727288213 10.2269952498698,1.44550326209418 10.25,1.43301270189222 10.2723195175075,1.41933528397271 10.2938926261462,1.40450849718747 10.3146601955249,1.38857298072849 10.3345653031794,1.3715724127387 10.3535533905933,1.35355339059327 10.3715724127387,1.33456530317943 10.3885729807285,1.31466019552492 10.4045084971875,1.29389262614624 10.4193352839727,1.27231951750751 10.4330127018922,1.25 10.4455032620942,1.22699524986977 10.4567727288213,1.2033683215379 10.4667902132486,1.17918397477265 10.4755282581476,1.15450849718747 10.4829629131445,1.12940952255126 10.4890738003669,1.10395584540888 10.4938441702976,1.07821723252012 10.4972609476841,1.05226423163383 10.4993147673773,1.02616797812147 10.5,1.0 10.5,-3.0 10.4993147673773,-3.02616797812147 10.4972609476841,-3.05226423163383 10.4938441702976,-3.07821723252012 10.4890738003669,-3.10395584540888 10.4829629131445,-3.12940952255126 10.4755282581476,-3.15450849718747 10.4667902132486,-3.17918397477265 10.4567727288213,-3.2033683215379 10.4455032620942,-3.22699524986977 10.4330127018922,-3.25 10.4193352839727,-3.27231951750751 10.4045084971875,-3.29389262614624 10.3885729807285,-3.31466019552492 10.3715724127387,-3.33456530317943 10.3535533905933,-3.35355339059327 10.3345653031794,-3.3715724127387 10.3146601955249,-3.38857298072849 10.2938926261462,-3.40450849718747 10.2723195175075,-3.41933528397271 10.25,-3.43301270189222 10.2269952498698,-3.44550326209418 10.2033683215379,-3.4567727288213 10.1791839747727,-3.4667902132486 10.1545084971875,-3.47552825814758 10.1294095225513,-3.48296291314453 10.1039558454089,-3.4890738003669 10.0782172325201,-3.49384417029757 10.0522642316338,-3.49726094768414 10.0261679781215,-3.49931476737729 10.0,-3.5 6.0,-3.5 5.98861328689307,-3.49970182842365 5.97684539599473,-3.49946357656326 5.97533725589921,-3.4993541833173 5.97383202187853,-3.49931476737729 5.96251823694463,-3.49842435319234 5.95083407630899,-3.49757684024441 5.94928528203419,-3.49738289705456 5.94773576836617,-3.49726094768414 5.9365259930818,-3.49578515277056 5.92495651714532,-3.49433639930824 5.9233719137338,-3.49405338537093 5.92178276747988,-3.49384417029757 5.91070752419031,-3.49179149528389 5.89928312083856,-3.48975106967926 5.89766791313086,-3.48937474622386 5.89604415459112,-3.4890738003669 5.88513332451513,-3.48645434182173 5.87388373427931,-3.48383332617821 5.87224347033073,-3.48335976162441 5.87059047744874,-3.48296291314453 5.85987322117231,-3.47978831720649 5.84882745888886,-3.47659926858316 5.84716801174553,-3.47602486271796 5.84549150281252,-3.47552825814758 5.8349961834824,-3.47181167064814 5.82418246262228,-3.46806857782854 5.8225100105145,-3.46739008490037 5.82081602522735,-3.4667902132486 5.81057013464642,-3.46254622641139 5.80001579451109,-3.45826446246133 5.79833679952825,-3.45747901309239 5.7966316784621,-3.4567727288213 5.78666176627805,-3.45201732464636 5.77639320225002,-3.44721359549996 1.88196601125011,-1.5 -1.0,-1.5 -1.02616797812147,-1.49931476737729 -1.05226423163383,-1.49726094768414 -1.07821723252012,-1.49384417029757 -1.10395584540888,-1.4890738003669 -1.12940952255126,-1.48296291314453 -1.15450849718748,-1.47552825814758 -1.17918397477265,-1.4667902132486 -1.2033683215379,-1.4567727288213 -1.22699524986978,-1.44550326209418 -1.25,-1.43301270189222 -1.27231951750752,-1.41933528397271 -1.29389262614624,-1.40450849718747 -1.31466019552492,-1.38857298072848 -1.33456530317943,-1.3715724127387 -1.35355339059327,-1.35355339059327 -1.3715724127387,-1.33456530317943 -1.38857298072849,-1.31466019552492 -1.40450849718747,-1.29389262614624 -1.41933528397271,-1.27231951750751 -1.43301270189222,-1.25 -1.44550326209418,-1.22699524986977 -1.4567727288213,-1.2033683215379 -1.4667902132486,-1.17918397477265 -1.47552825814758,-1.15450849718747 -1.48296291314453,-1.12940952255126 -1.4890738003669,-1.10395584540888 -1.49384417029757,-1.07821723252012 -1.49726094768414,-1.05226423163383 -1.49931476737729,-1.02616797812147 -1.5,-1.0 -1.5,3.0 -1.49931476737729,3.02616797812147 -1.49726094768414,3.05226423163383 -1.49384417029757,3.07821723252012 -1.4890738003669,3.10395584540888 -1.48296291314453,3.12940952255126 -1.47552825814758,3.15450849718747 -1.4667902132486,3.17918397477265 -1.4567727288213,3.2033683215379 -1.44550326209418,3.22699524986977 -1.43301270189222,3.25 -1.41933528397271,3.27231951750751 -1.40450849718747,3.29389262614624 -1.38857298072849,3.31466019552492 -1.3715724127387,3.33456530317943 -1.35355339059327,3.35355339059327 -1.33456530317943,3.3715724127387 -1.31466019552492,3.38857298072849 -1.29389262614624,3.40450849718747 -1.27231951750751,3.41933528397271 -1.25,3.43301270189222 -1.22699524986977,3.44550326209418 -1.2033683215379,3.4567727288213 -1.17918397477265,3.4667902132486 -1.15450849718747,3.47552825814758 -1.12940952255126,3.48296291314453 -1.10395584540888,3.4890738003669 -1.07821723252012,3.49384417029757 -1.05226423163383,3.49726094768414 -1.02616797812147,3.49931476737729 -1.0,3.5 3.0,3.5 3.02616797812147,3.49931476737729 3.05226423163383,3.49726094768414 3.07821723252012,3.49384417029757 3.10395584540888,3.4890738003669 3.12940952255126,3.48296291314453 3.15450849718747,3.47552825814758 3.17918397477265,3.4667902132486 3.2033683215379,3.4567727288213 3.22699524986977,3.44550326209418 3.25,3.43301270189222 3.27231951750751,3.41933528397271 3.29389262614624,3.40450849718747 3.31466019552492,3.38857298072849 3.33456530317943,3.3715724127387 3.35355339059327,3.35355339059327 3.3715724127387,3.33456530317943 3.38857298072849,3.31466019552492 3.40450849718747,3.29389262614624 3.41933528397271,3.27231951750751 3.43301270189222,3.25 3.44550326209418,3.22699524986977 3.4567727288213,3.2033683215379 3.4667902132486,3.17918397477265 3.47552825814758,3.15450849718747 3.48296291314453,3.12940952255126 3.4890738003669,3.10395584540888 3.49384417029757,3.07821723252012 3.49726094768414,3.05226423163383 3.49931476737729,3.02616797812147 3.5,3.0 3.5,2.36037961002806 6.08113883008419,1.57.5,-0.5 7.5,-1.5 8.5,-1.5 8.5,-0.5 7.5,-0.54.64644660940673,5.35355339059327 4.66543469682057,5.3715724127387 4.68533980447508,5.38857298072849 4.70610737385376,5.40450849718747 4.72768048249249,5.41933528397271 4.75,5.43301270189222 4.77300475013023,5.44550326209418 4.7966316784621,5.4567727288213 4.82081602522735,5.4667902132486 4.84549150281253,5.47552825814758 4.87059047744874,5.48296291314453 4.89604415459112,5.4890738003669 4.92178276747988,5.49384417029757 4.94773576836617,5.49726094768414 4.97383202187853,5.49931476737729 5.0,5.5 5.02616797812147,5.49931476737729 5.05226423163383,5.49726094768414 5.07821723252012,5.49384417029757 5.10395584540888,5.4890738003669 5.12940952255126,5.48296291314453 5.15450849718747,5.47552825814758 5.17918397477265,5.4667902132486 5.2033683215379,5.4567727288213 5.22699524986977,5.44550326209418 5.25,5.43301270189222 5.27231951750751,5.41933528397271 5.29389262614624,5.40450849718747 5.31466019552492,5.38857298072849 5.33456530317943,5.3715724127387 5.35355339059327,5.35355339059327 6.35355339059327,4.35355339059327 6.3715724127387,4.33456530317943 6.38857298072849,4.31466019552492 6.40450849718747,4.29389262614624 6.41933528397271,4.27231951750751 6.43301270189222,4.25 6.44550326209418,4.22699524986977 6.4567727288213,4.2033683215379 6.4667902132486,4.17918397477265 6.47552825814758,4.15450849718747 6.48296291314453,4.12940952255126 6.4890738003669,4.10395584540888 6.49384417029757,4.07821723252012 6.49726094768414,4.05226423163383 6.49931476737729,4.02616797812147 6.5,4.0 6.49931476737729,3.97383202187853 6.49726094768414,3.94773576836617 6.49384417029757,3.92178276747988 6.4890738003669,3.89604415459112 6.48296291314453,3.87059047744874 6.47552825814758,3.84549150281253 6.4667902132486,3.82081602522735 6.4567727288213,3.7966316784621 6.44550326209418,3.77300475013023 6.43301270189222,3.75 6.41933528397271,3.72768048249249 6.40450849718747,3.70610737385376 6.38857298072849,3.68533980447508 6.3715724127387,3.66543469682057 6.35355339059327,3.64644660940673 6.33456530317943,3.6284275872613 6.31466019552492,3.61142701927151 6.29389262614624,3.59549150281253 6.27231951750751,3.58066471602729 6.25,3.56698729810778 6.22699524986977,3.55449673790582 6.2033683215379,3.5432272711787 6.17918397477265,3.5332097867514 6.15450849718747,3.52447174185242 6.12940952255126,3.51703708685547 6.10395584540888,3.5109261996331 6.07821723252012,3.50615582970243 6.05226423163383,3.50273905231586 6.02616797812147,3.50068523262271 6.0,3.5 4.0,3.5 3.97383202187852,3.50068523262271 3.94773576836617,3.50273905231586 3.92178276747988,3.50615582970243 3.89604415459112,3.5109261996331 3.87059047744874,3.51703708685547 3.84549150281252,3.52447174185242 3.82081602522735,3.5332097867514 3.7966316784621,3.5432272711787 3.77300475013022,3.55449673790582 3.75,3.56698729810778 3.72768048249248,3.58066471602729 3.70610737385376,3.59549150281253 3.68533980447508,3.61142701927152 3.66543469682057,3.6284275872613 3.64644660940672,3.64644660940673 3.6284275872613,3.66543469682057 3.61142701927151,3.68533980447508 3.59549150281253,3.70610737385377 3.58066471602729,3.72768048249249 3.56698729810778,3.75 3.55449673790581,3.77300475013023 3.5432272711787,3.7966316784621 3.5332097867514,3.82081602522735 3.52447174185242,3.84549150281253 3.51703708685547,3.87059047744874 3.5109261996331,3.89604415459112 3.50615582970243,3.92178276747989 3.50273905231586,3.94773576836617 3.50068523262271,3.97383202187853 3.5,4.0 3.50068523262271,4.02616797812147 3.50273905231586,4.05226423163383 3.50615582970243,4.07821723252012 3.5109261996331,4.10395584540888 3.51703708685547,4.12940952255126 3.52447174185242,4.15450849718747 3.5332097867514,4.17918397477265 3.5432272711787,4.2033683215379 3.55449673790582,4.22699524986977 3.56698729810778,4.25 3.58066471602729,4.27231951750751 3.59549150281253,4.29389262614624 3.61142701927151,4.31466019552492 3.6284275872613,4.33456530317943 3.64644660940673,4.35355339059327 4.64644660940673,5.35355339059327 + elim + 2 + 3.330000000000000 + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index f6686891534e..8e67f94f61b4 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -86,6 +86,7 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_lines.gml type: vector + - algorithm: gdalogr:buffervectors name: OGR basic polygon buffer params: @@ -100,3 +101,18 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_polys.gml type: vector + + - algorithm: gdalogr:buffervectors + name: OGR polygon buffer with dissolve + params: + DISSOLVEALL: true + DISTANCE: '0.5' + GEOMETRY: geometry + INPUT_LAYER: + name: polys.gml + type: vector + MULTI: false + results: + OUTPUT_LAYER: + name: expected/gdal/buffer_polys_dissolve.gml + type: vector From 52e29b93b887446ca11f3cc40bb931c7f2b4677a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 11:53:30 +0200 Subject: [PATCH 707/897] [processing] fix deprecation warnings in GDAL test --- .../plugins/processing/tests/GdalAlgorithmsTest.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/tests/GdalAlgorithmsTest.py b/python/plugins/processing/tests/GdalAlgorithmsTest.py index 57f6f13c276c..0b1f1f2e2370 100644 --- a/python/plugins/processing/tests/GdalAlgorithmsTest.py +++ b/python/plugins/processing/tests/GdalAlgorithmsTest.py @@ -74,31 +74,31 @@ def test_getConnectionString(self): cs = obj.getConnectionString() # NOTE: defaults are debatable, see # https://github.com/qgis/QGIS/pull/3607#issuecomment-253971020 - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "host=localhost port=5432 active_schema=public") obj.setParameterValue('HOST', 'remote') - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "host=remote port=5432 active_schema=public") obj.setParameterValue('HOST', '') - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "port=5432 active_schema=public") obj.setParameterValue('PORT', '5555') - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "port=5555 active_schema=public") obj.setParameterValue('PORT', '') - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "active_schema=public") obj.setParameterValue('USER', 'usr') - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "active_schema=public user=usr") obj.setParameterValue('PASSWORD', 'pwd') - self.assertEquals(obj.getConnectionString(), + self.assertEqual(obj.getConnectionString(), "password=pwd active_schema=public user=usr") From d08c02dbd0e52fbbf1a88f8225b637e2b3a594cd Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 12:33:42 +0200 Subject: [PATCH 708/897] [processing] disable polygonize test, as it is not stable --- python/plugins/processing/tests/ToolsTest.py | 14 ------------ .../tests/testdata/gdal_algorithm_tests.yaml | 22 +++++++++---------- 2 files changed, 11 insertions(+), 25 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index a738c3e9bfa8..55e2de437b9b 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -36,20 +36,6 @@ class VectorTest(unittest.TestCase): - # URI from OGR provider - # URI from OGR provider - # URI from OGR provider - # URI from OGR provider - # URI from OGR provider - # URI from OGR provider - - # URI from Sqlite provider - name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=') - self.assertEqual(name, 't') - - # URI from PostgreSQL provider - name = vector.ogrLayerName('port=5493 sslmode=disable key=\'edge_id\' srid=0 type=LineString table="city_data"."edge" (geom) sql=') - self.assertEqual(name, 'city_data.edge') def testFeatures(self): ProcessingConfig.initialize() diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 8e67f94f61b4..499ed9349a6f 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -44,17 +44,17 @@ tests: - 'Band 1 Block=16x14 Type=Float32, ColorInterp=Gray' - ' NoData Value=-32768' - - algorithm: gdalogr:polygonize - name: GDAL polygonize - params: - FIELD: DN - INPUT: - name: raster.tif - type: raster - results: - OUTPUT: - name: expected/gdal/polygonize.gml - type: vector +# - algorithm: gdalogr:polygonize +# name: GDAL polygonize +# params: +# FIELD: DN +# INPUT: +# name: raster.tif +# type: raster +# results: +# OUTPUT: +# name: expected/gdal/polygonize.gml +# type: vector - algorithm: gdalogr:information name: GDAL ogrinfo From 397df659089e8d4f5d0c1f70700c7beacc47d6cc Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 13:41:14 +0200 Subject: [PATCH 709/897] [processing] add test for points along lines --- .../expected/gdal/points_along_lines.gfs | 16 +++++++ .../expected/gdal/points_along_lines.gml | 48 +++++++++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 12 +++++ 3 files changed, 76 insertions(+) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gml diff --git a/python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gfs b/python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gfs new file mode 100644 index 000000000000..4e10a8bc683c --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gfs @@ -0,0 +1,16 @@ + + + points_along_lines + points_along_lines + + 1 + EPSG:4326 + + 7 + -0.50000 + 7.75000 + -3.00000 + 2.00000 + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gml b/python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gml new file mode 100644 index 000000000000..9db8ce13ae8c --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/points_along_lines.gml @@ -0,0 +1,48 @@ + + + + + -0.5-3 + 7.752 + + + + + + 7.70710678118655,2.0 + + + + + -0.5,-1.0 + + + + + 2,1 + + + + + 3.5,1.0 + + + + + 7.75,-3.0 + + + + + 7,-2 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 499ed9349a6f..63e092c29e1d 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -116,3 +116,15 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_polys_dissolve.gml type: vector + - algorithm: gdalogr:createpointsalonglines + name: OGR points along lines + params: + DISTANCE: 0.25 + GEOMETRY: geometry + INPUT_LAYER: + name: lines.gml + type: vector + results: + OUTPUT_LAYER: + name: expected/gdal/points_along_lines.gml + type: vector From 02ed0aa628ac19c4f8ad754fbbc9c4ee28229750 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 14:13:41 +0200 Subject: [PATCH 710/897] [processing] fix OGR offset curve and one-side buffer --- .../processing/algs/gdal/offsetcurve.py | 18 ++++++++---------- .../processing/algs/gdal/onesidebuffer.py | 9 ++++++--- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/python/plugins/processing/algs/gdal/offsetcurve.py b/python/plugins/processing/algs/gdal/offsetcurve.py index 5317822605cf..03318053f992 100644 --- a/python/plugins/processing/algs/gdal/offsetcurve.py +++ b/python/plugins/processing/algs/gdal/offsetcurve.py @@ -27,6 +27,7 @@ from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterTableField from processing.core.parameters import ParameterSelection @@ -46,8 +47,6 @@ class OffsetCurve(GdalAlgorithm): INPUT_LAYER = 'INPUT_LAYER' GEOMETRY = 'GEOMETRY' RADIUS = 'RADIUS' - LEFTRIGHT = 'LEFTRIGHT' - LEFTRIGHTLIST = ['Right', 'Left'] DISSOLVEALL = 'DISSOLVEALL' FIELD = 'FIELD' MULTI = 'MULTI' @@ -62,10 +61,10 @@ def defineCharacteristics(self): self.addParameter(ParameterString(self.GEOMETRY, self.tr('Geometry column name ("geometry" for Shapefiles, may be different for other formats)'), 'geometry', optional=False)) - self.addParameter(ParameterString(self.RADIUS, - self.tr('Offset distance'), '1000', optional=False)) - self.addParameter(ParameterSelection(self.LEFTRIGHT, - self.tr('Offset side'), self.LEFTRIGHTLIST, 0)) + self.addParameter(ParameterNumber(self.RADIUS, + self.tr('Offset distance (positive value for left-sided and negative - for right-sided)'), + 0.0, 99999999.999999, 1000.0, + optional=False)) self.addParameter(ParameterBoolean(self.DISSOLVEALL, self.tr('Dissolve all results'), False)) self.addParameter(ParameterTableField(self.FIELD, @@ -82,7 +81,6 @@ def getConsoleCommands(self): inLayer = self.getParameterValue(self.INPUT_LAYER) geometry = self.getParameterValue(self.GEOMETRY) distance = self.getParameterValue(self.RADIUS) - leftright = self.getParameterValue(self.LEFTRIGHT) dissolveall = self.getParameterValue(self.DISSOLVEALL) field = self.getParameterValue(self.FIELD) multi = self.getParameterValue(self.MULTI) @@ -106,9 +104,9 @@ def getConsoleCommands(self): arguments.append('-sql') if dissolveall or field is not None: - sql = "SELECT ST_Union(ST_OffsetCurve({}, {}, {})) * FROM '{}'".format(geometry, distance, leftright, layername) + sql = "SELECT ST_Union(ST_OffsetCurve({}, {})) * FROM '{}'".format(geometry, distance, layername) else: - sql = "SELECT ST_OffsetCurve({}, {}, {}), * FROM '{}'".format(geometry, distance, leftright, layername) + sql = "SELECT ST_OffsetCurve({}, {}), * FROM '{}'".format(geometry, distance, layername) if field is not None: sql = '"{} GROUP BY {}"'.format(sql, field) @@ -118,7 +116,7 @@ def getConsoleCommands(self): if field is not None and multi: arguments.append('-explodecollections') - if len(options) > 0: + if options is not None and len(options.strip()) > 0: arguments.append(options) commands = [] diff --git a/python/plugins/processing/algs/gdal/onesidebuffer.py b/python/plugins/processing/algs/gdal/onesidebuffer.py index 65b3a870a004..29fc7f730dae 100644 --- a/python/plugins/processing/algs/gdal/onesidebuffer.py +++ b/python/plugins/processing/algs/gdal/onesidebuffer.py @@ -27,6 +27,7 @@ from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterTableField from processing.core.parameters import ParameterSelection @@ -62,8 +63,10 @@ def defineCharacteristics(self): self.addParameter(ParameterString(self.GEOMETRY, self.tr('Geometry column name ("geometry" for Shapefiles, may be different for other formats)'), 'geometry', optional=False)) - self.addParameter(ParameterString(self.RADIUS, - self.tr('Buffer distance'), '1000', optional=False)) + self.addParameter(ParameterNumber(self.RADIUS, + self.tr('Buffer distance'), + 0.0, 99999999.999999, 1000.0, + optional=False)) self.addParameter(ParameterSelection(self.LEFTRIGHT, self.tr('Buffer side'), self.LEFTRIGHTLIST, 0)) self.addParameter(ParameterBoolean(self.DISSOLVEALL, @@ -118,7 +121,7 @@ def getConsoleCommands(self): if field is not None and multi: arguments.append('-explodecollections') - if len(options) > 0: + if options is not None and len(options.strip()) > 0: arguments.append(options) commands = [] From 32094e93d0dccd4144912ff353aa90e2656b5687 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 14:25:19 +0200 Subject: [PATCH 711/897] [processing] add test for OGR offset lines --- .../testdata/expected/gdal/offset_lines.gfs | 16 +++++++ .../testdata/expected/gdal/offset_lines.gml | 48 +++++++++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 15 ++++++ 3 files changed, 79 insertions(+) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gml diff --git a/python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gfs b/python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gfs new file mode 100644 index 000000000000..604f07a462ed --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gfs @@ -0,0 +1,16 @@ + + + offset_lines + offset_lines + + 2 + EPSG:4326 + + 7 + -1.00000 + 11.35355 + -3.50000 + 4.64645 + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gml b/python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gml new file mode 100644 index 000000000000..b5dfd6140edf --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/offset_lines.gml @@ -0,0 +1,48 @@ + + + + + -1-3.5 + 11.353553390593274.646446609406726 + + + + + + 11.3535533905933,4.64644660940673 9.5,2.79289321881345 9.5,2.0 9.4975923633361,1.95099142983522 9.49039264020162,1.90245483899194 9.4784701678661,1.85485766137277 9.46193976625564,1.80865828381746 9.44096063217418,1.764301631587 9.41573480615127,1.7222148834902 9.38650522668137,1.68280335791818 9.35355339059327,1.64644660940673 9.31719664208182,1.61349477331863 9.2777851165098,1.58426519384873 9.235698368413,1.55903936782582 9.19134171618255,1.53806023374436 9.14514233862723,1.5215298321339 9.09754516100806,1.50960735979838 9.04900857016478,1.5024076366639 9.0,1.5 6.0,1.5 + + + + + 1.0,-1.5 -1.0,-1.5 + + + + + 3.5,3.0 3.5,2.0 3.4975923633361,1.95099142983522 3.49039264020162,1.90245483899194 3.4784701678661,1.85485766137277 3.46193976625564,1.80865828381746 3.44096063217418,1.764301631587 3.41573480615127,1.7222148834902 3.38650522668137,1.68280335791818 3.35355339059327,1.64644660940673 3.31719664208182,1.61349477331863 3.2777851165098,1.58426519384873 3.235698368413,1.55903936782582 3.19134171618254,1.53806023374436 3.14514233862723,1.5215298321339 3.09754516100806,1.50960735979838 3.04900857016478,1.5024076366639 3.0,1.5 2.5,1.5 2.5,0.0 + + + + + 5.0,0.5 3.0,0.5 + + + + + 10.0,-3.5 7.0,-3.5 + + + + + 10.3535533905933,0.646446609406726 6.35355339059327,-3.35355339059327 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 63e092c29e1d..a160c3cdb1f8 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -128,3 +128,18 @@ tests: OUTPUT_LAYER: name: expected/gdal/points_along_lines.gml type: vector + + - algorithm: gdalogr:offsetlinesforlines + name: OGR offset lines for lines (right-handed) + params: + DISSOLVEALL: false + GEOMETRY: geometry + INPUT_LAYER: + name: lines.gml + type: vector + MULTI: false + RADIUS: -0.5 + results: + OUTPUT_LAYER: + name: expected/gdal/offset_lines.gml + type: vector From d239a97c4133a508da6bf483627f7cdb380feafa Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 14:32:05 +0200 Subject: [PATCH 712/897] [processing] test for OGR one-side buffer --- .../expected/gdal/one_side_buffer.gfs | 16 +++++++ .../expected/gdal/one_side_buffer.gml | 48 +++++++++++++++++++ .../tests/testdata/gdal_algorithm_tests.yaml | 16 +++++++ 3 files changed, 80 insertions(+) create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gml diff --git a/python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gfs b/python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gfs new file mode 100644 index 000000000000..1022f4ed2f0b --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gfs @@ -0,0 +1,16 @@ + + + one_side_buffer + one_side_buffer + + 3 + EPSG:4326 + + 7 + -1.00000 + 11.00000 + -3.00000 + 5.35355 + + + diff --git a/python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gml b/python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gml new file mode 100644 index 000000000000..db5ee63e13b7 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/gdal/one_side_buffer.gml @@ -0,0 +1,48 @@ + + + + + -1-3 + 115.353553390593274 + + + + + + 11,5 9,3 9,2 6,2 6.0,2.5 8.5,2.5 8.5,3.0 8.5024076366639,3.04900857016478 8.50960735979838,3.09754516100806 8.5215298321339,3.14514233862723 8.53806023374436,3.19134171618255 8.55903936782582,3.235698368413 8.58426519384873,3.2777851165098 8.61349477331863,3.31719664208182 8.64644660940673,3.35355339059327 10.6464466094067,5.35355339059327 11,5 + + + + + 1,-1 -1,-1 -1.0,-0.5 1.0,-0.5 1,-1 + + + + + 3,3 3,2 2,2 2,0 1.5,0.0 1.5,2.0 1.5024076366639,2.04900857016478 1.50960735979838,2.09754516100806 1.5215298321339,2.14514233862723 1.53806023374436,2.19134171618254 1.55903936782582,2.235698368413 1.58426519384873,2.2777851165098 1.61349477331863,2.31719664208182 1.64644660940673,2.35355339059327 1.68280335791818,2.38650522668137 1.7222148834902,2.41573480615127 1.764301631587,2.44096063217418 1.80865828381746,2.46193976625564 1.85485766137277,2.4784701678661 1.90245483899194,2.49039264020162 1.95099142983522,2.4975923633361 2.0,2.5 2.5,2.5 2.5,3.0 3,3 + + + + + 5,1 3,1 3.0,1.5 5.0,1.5 5,1 + + + + + 10,-3 7,-3 7.0,-2.5 10.0,-2.5 10,-3 + + + + + 10,1 6,-3 5.64644660940673,-2.64644660940673 9.64644660940673,1.35355339059327 10,1 + + + + + + + diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index a160c3cdb1f8..1b0d23ba39b7 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -143,3 +143,19 @@ tests: OUTPUT_LAYER: name: expected/gdal/offset_lines.gml type: vector + + - algorithm: gdalogr:singlesidedbufferforlines + name: OGR one-side buffer for lines (left-handed) + params: + DISSOLVEALL: false + GEOMETRY: geometry + INPUT_LAYER: + name: lines.gml + type: vector + LEFTRIGHT: '1' + MULTI: false + RADIUS: 0.5 + results: + OUTPUT_LAYER: + name: expected/gdal/one_side_buffer.gml + type: vector From a8feec8d3c1f0e7f49797ad82822fab54d74e0e8 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 14:44:32 +0200 Subject: [PATCH 713/897] [processing] friendly names for some QGIS tests --- .../tests/testdata/qgis_algorithm_tests.yaml | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index c667aaebeecd..ce3afa7fa6cd 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -38,7 +38,6 @@ tests: name: expected/clip_lines_by_polygon.gml type: vector - - algorithm: qgis:clip name: Clip lines by multipolygon params: @@ -109,7 +108,6 @@ tests: name: expected/clip_points_by_multipolygons.gml type: vector - # These datasets should produce a geometry collection and not a polygon only # dataset. If the algorithm is fixed, a new test should be introduced to # check this behavior. @@ -152,7 +150,7 @@ tests: type: vector - algorithm: qgis:basicstatisticsfornumericfields - name: Test (qgis:basicstatisticsfornumericfields) + name: Basic statistics for numeric fields params: - name: multipolys.gml type: vector @@ -182,7 +180,7 @@ tests: - 'Interquartile Range \(IQR\): 0.123' - algorithm: qgis:basicstatisticsfortextfields - name: Test (qgis:basicstatisticsfortextfields) + name: Basic statistics for text fields params: - name: multipolys.gml type: vector @@ -865,7 +863,6 @@ tests: name: expected/lines_translated.gml type: vector - - algorithm: qgis:singlesidedbuffer name: Single sided buffer lines (left, round) params: @@ -932,7 +929,7 @@ tests: type: vector - algorithm: qgis:extractnodes - name: Test (qgis:extractnodes) + name: Extract nodes from polygons params: INPUT: name: polys.gml @@ -943,7 +940,7 @@ tests: type: vector - algorithm: qgis:extractnodes - name: Test (qgis:extractnodes) + name: Extract nodes from multilines params: INPUT: name: multilines.gml @@ -954,7 +951,7 @@ tests: type: vector - algorithm: qgis:extractnodes - name: Test (qgis:extractnodes) + name: Extract nodes from lines params: INPUT: name: lines.gml @@ -1138,7 +1135,7 @@ tests: type: rasterhash - algorithm: qgis:lineintersections - name: Line Intersection + name: Line intersection params: INPUT_A: name: lines.gml @@ -1296,7 +1293,6 @@ tests: compare: geometry: precision: 7 - - algorithm: qgis:extendlines name: Extend multilines params: From 256efcc0347169171cbf5d654175001d4ea54a03 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 14:50:58 +0200 Subject: [PATCH 714/897] [processing] remove unnecessary schemas from test data --- .../expected/PolygonDissolveTest_output.xsd | 23 --------- .../testdata/expected/autoincrement_field.xsd | 30 ------------ .../tests/testdata/expected/buffer_lines.xsd | 23 --------- .../testdata/expected/buffer_lines_flat.xsd | 23 --------- .../testdata/expected/buffer_lines_square.xsd | 23 --------- .../tests/testdata/expected/buffer_polys.xsd | 43 ----------------- .../testdata/expected/buffer_polys_bevel.xsd | 43 ----------------- .../expected/buffer_polys_dissolve.xsd | 43 ----------------- .../testdata/expected/buffer_polys_mitre.xsd | 43 ----------------- .../testdata/expected/dissolve_field.xsd | 43 ----------------- .../testdata/expected/dissolve_two_fields.xsd | 43 ----------------- .../expected/eliminate_largest_area.xsd | 43 ----------------- .../expected/eliminate_smallest_area.xsd | 43 ----------------- .../testdata/expected/line_offset_bevel.xsd | 23 --------- .../testdata/expected/line_offset_mitre.xsd | 23 --------- .../expected/line_offset_round_negative.xsd | 23 --------- .../expected/line_offset_round_positive.xsd | 23 --------- .../testdata/expected/lines_boundary.xsd | 23 --------- .../tests/testdata/expected/lines_bounds.xsd | 23 --------- .../expected/lines_split_with_lines.xsd | 23 --------- .../expected/lines_split_with_same_lines.xsd | 23 --------- .../tests/testdata/expected/merge_lines.xsd | 23 --------- .../testdata/expected/multi_to_single.xsd | 23 --------- .../testdata/expected/multiline_boundary.xsd | 23 --------- .../testdata/expected/multiline_bounds.xsd | 23 --------- .../testdata/expected/multiline_offset.xsd | 23 --------- .../testdata/expected/multipoint_bounds.xsd | 30 ------------ .../testdata/expected/multipoint_delaunay.xsd | 47 ------------------- .../testdata/expected/multipoly_boundary.xsd | 43 ----------------- .../testdata/expected/multipoly_bounds.xsd | 43 ----------------- .../expected/nullGeometryDissolve_output.xsd | 23 --------- .../tests/testdata/expected/point_bounds.xsd | 23 --------- .../tests/testdata/expected/point_on_line.xsd | 23 --------- .../testdata/expected/point_on_multipoint.xsd | 30 ------------ .../tests/testdata/expected/point_on_poly.xsd | 43 ----------------- .../tests/testdata/expected/poly_boundary.xsd | 43 ----------------- .../tests/testdata/expected/poly_bounds.xsd | 43 ----------------- .../testdata/expected/polys_centroid.xsd | 43 ----------------- .../testdata/expected/polys_deleteholes.xsd | 43 ----------------- .../testdata/expected/polys_to_lines.xsd | 43 ----------------- .../expected/rectanglesovalsdiamondsfixed.xsd | 23 --------- 41 files changed, 1308 deletions(-) delete mode 100644 python/plugins/processing/tests/testdata/expected/PolygonDissolveTest_output.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/autoincrement_field.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_lines.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_lines_flat.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_lines_square.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_polys.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_polys_bevel.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_polys_dissolve.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/buffer_polys_mitre.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/dissolve_field.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/dissolve_two_fields.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/eliminate_largest_area.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/eliminate_smallest_area.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/line_offset_bevel.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/line_offset_mitre.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/line_offset_round_negative.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/line_offset_round_positive.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/lines_boundary.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/lines_bounds.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/lines_split_with_lines.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/lines_split_with_same_lines.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/merge_lines.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multi_to_single.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multiline_boundary.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multiline_bounds.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multiline_offset.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multipoint_bounds.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multipoly_boundary.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/multipoly_bounds.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/nullGeometryDissolve_output.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/point_bounds.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/point_on_line.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/point_on_multipoint.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/point_on_poly.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/poly_boundary.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/poly_bounds.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/polys_centroid.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/polys_deleteholes.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/polys_to_lines.xsd delete mode 100644 python/plugins/processing/tests/testdata/expected/rectanglesovalsdiamondsfixed.xsd diff --git a/python/plugins/processing/tests/testdata/expected/PolygonDissolveTest_output.xsd b/python/plugins/processing/tests/testdata/expected/PolygonDissolveTest_output.xsd deleted file mode 100644 index dd4ebff371a8..000000000000 --- a/python/plugins/processing/tests/testdata/expected/PolygonDissolveTest_output.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/autoincrement_field.xsd b/python/plugins/processing/tests/testdata/expected/autoincrement_field.xsd deleted file mode 100644 index d6770f6e5624..000000000000 --- a/python/plugins/processing/tests/testdata/expected/autoincrement_field.xsd +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_lines.xsd b/python/plugins/processing/tests/testdata/expected/buffer_lines.xsd deleted file mode 100644 index d280fc135bf9..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_lines.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_lines_flat.xsd b/python/plugins/processing/tests/testdata/expected/buffer_lines_flat.xsd deleted file mode 100644 index db988763fdb6..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_lines_flat.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_lines_square.xsd b/python/plugins/processing/tests/testdata/expected/buffer_lines_square.xsd deleted file mode 100644 index 8cf8916b9f85..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_lines_square.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_polys.xsd b/python/plugins/processing/tests/testdata/expected/buffer_polys.xsd deleted file mode 100644 index 63d0eaed8467..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_polys.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_polys_bevel.xsd b/python/plugins/processing/tests/testdata/expected/buffer_polys_bevel.xsd deleted file mode 100644 index 8ddec54df9d5..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_polys_bevel.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_polys_dissolve.xsd b/python/plugins/processing/tests/testdata/expected/buffer_polys_dissolve.xsd deleted file mode 100644 index 1281df9b2889..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_polys_dissolve.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/buffer_polys_mitre.xsd b/python/plugins/processing/tests/testdata/expected/buffer_polys_mitre.xsd deleted file mode 100644 index ac4766633974..000000000000 --- a/python/plugins/processing/tests/testdata/expected/buffer_polys_mitre.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/dissolve_field.xsd b/python/plugins/processing/tests/testdata/expected/dissolve_field.xsd deleted file mode 100644 index 0a1ca1e35776..000000000000 --- a/python/plugins/processing/tests/testdata/expected/dissolve_field.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/dissolve_two_fields.xsd b/python/plugins/processing/tests/testdata/expected/dissolve_two_fields.xsd deleted file mode 100644 index 61fcdc5bfbae..000000000000 --- a/python/plugins/processing/tests/testdata/expected/dissolve_two_fields.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/eliminate_largest_area.xsd b/python/plugins/processing/tests/testdata/expected/eliminate_largest_area.xsd deleted file mode 100644 index d1c19fff7785..000000000000 --- a/python/plugins/processing/tests/testdata/expected/eliminate_largest_area.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/eliminate_smallest_area.xsd b/python/plugins/processing/tests/testdata/expected/eliminate_smallest_area.xsd deleted file mode 100644 index 1046cc7df8df..000000000000 --- a/python/plugins/processing/tests/testdata/expected/eliminate_smallest_area.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/line_offset_bevel.xsd b/python/plugins/processing/tests/testdata/expected/line_offset_bevel.xsd deleted file mode 100644 index 1d7cd80674f3..000000000000 --- a/python/plugins/processing/tests/testdata/expected/line_offset_bevel.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/line_offset_mitre.xsd b/python/plugins/processing/tests/testdata/expected/line_offset_mitre.xsd deleted file mode 100644 index 44e4f124d04a..000000000000 --- a/python/plugins/processing/tests/testdata/expected/line_offset_mitre.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/line_offset_round_negative.xsd b/python/plugins/processing/tests/testdata/expected/line_offset_round_negative.xsd deleted file mode 100644 index b068b06d65a5..000000000000 --- a/python/plugins/processing/tests/testdata/expected/line_offset_round_negative.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/line_offset_round_positive.xsd b/python/plugins/processing/tests/testdata/expected/line_offset_round_positive.xsd deleted file mode 100644 index 909c4aee8a18..000000000000 --- a/python/plugins/processing/tests/testdata/expected/line_offset_round_positive.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/lines_boundary.xsd b/python/plugins/processing/tests/testdata/expected/lines_boundary.xsd deleted file mode 100644 index 44b50cae613d..000000000000 --- a/python/plugins/processing/tests/testdata/expected/lines_boundary.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/lines_bounds.xsd b/python/plugins/processing/tests/testdata/expected/lines_bounds.xsd deleted file mode 100644 index 8db5a1f71a0a..000000000000 --- a/python/plugins/processing/tests/testdata/expected/lines_bounds.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/lines_split_with_lines.xsd b/python/plugins/processing/tests/testdata/expected/lines_split_with_lines.xsd deleted file mode 100644 index e28d72899056..000000000000 --- a/python/plugins/processing/tests/testdata/expected/lines_split_with_lines.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/lines_split_with_same_lines.xsd b/python/plugins/processing/tests/testdata/expected/lines_split_with_same_lines.xsd deleted file mode 100644 index 9606a9d287c3..000000000000 --- a/python/plugins/processing/tests/testdata/expected/lines_split_with_same_lines.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/merge_lines.xsd b/python/plugins/processing/tests/testdata/expected/merge_lines.xsd deleted file mode 100644 index c3cbd1491c92..000000000000 --- a/python/plugins/processing/tests/testdata/expected/merge_lines.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multi_to_single.xsd b/python/plugins/processing/tests/testdata/expected/multi_to_single.xsd deleted file mode 100644 index e5c9e7d5d950..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multi_to_single.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multiline_boundary.xsd b/python/plugins/processing/tests/testdata/expected/multiline_boundary.xsd deleted file mode 100644 index aa8a6ff48c4c..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multiline_boundary.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multiline_bounds.xsd b/python/plugins/processing/tests/testdata/expected/multiline_bounds.xsd deleted file mode 100644 index 93d7a1e03a57..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multiline_bounds.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multiline_offset.xsd b/python/plugins/processing/tests/testdata/expected/multiline_offset.xsd deleted file mode 100644 index 2593e94bf46a..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multiline_offset.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multipoint_bounds.xsd b/python/plugins/processing/tests/testdata/expected/multipoint_bounds.xsd deleted file mode 100644 index 3aca84472297..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multipoint_bounds.xsd +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd b/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd deleted file mode 100644 index 498417068abd..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multipoint_delaunay.xsd +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multipoly_boundary.xsd b/python/plugins/processing/tests/testdata/expected/multipoly_boundary.xsd deleted file mode 100644 index 8563aa7d84f5..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multipoly_boundary.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/multipoly_bounds.xsd b/python/plugins/processing/tests/testdata/expected/multipoly_bounds.xsd deleted file mode 100644 index f44a5816f91f..000000000000 --- a/python/plugins/processing/tests/testdata/expected/multipoly_bounds.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/nullGeometryDissolve_output.xsd b/python/plugins/processing/tests/testdata/expected/nullGeometryDissolve_output.xsd deleted file mode 100644 index ca10fbbe8f1e..000000000000 --- a/python/plugins/processing/tests/testdata/expected/nullGeometryDissolve_output.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/point_bounds.xsd b/python/plugins/processing/tests/testdata/expected/point_bounds.xsd deleted file mode 100644 index a73e5510b28c..000000000000 --- a/python/plugins/processing/tests/testdata/expected/point_bounds.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/point_on_line.xsd b/python/plugins/processing/tests/testdata/expected/point_on_line.xsd deleted file mode 100644 index fab0ad2ce893..000000000000 --- a/python/plugins/processing/tests/testdata/expected/point_on_line.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/point_on_multipoint.xsd b/python/plugins/processing/tests/testdata/expected/point_on_multipoint.xsd deleted file mode 100644 index a51301c1aadd..000000000000 --- a/python/plugins/processing/tests/testdata/expected/point_on_multipoint.xsd +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/point_on_poly.xsd b/python/plugins/processing/tests/testdata/expected/point_on_poly.xsd deleted file mode 100644 index f3d746e9086a..000000000000 --- a/python/plugins/processing/tests/testdata/expected/point_on_poly.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/poly_boundary.xsd b/python/plugins/processing/tests/testdata/expected/poly_boundary.xsd deleted file mode 100644 index d698297f70af..000000000000 --- a/python/plugins/processing/tests/testdata/expected/poly_boundary.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/poly_bounds.xsd b/python/plugins/processing/tests/testdata/expected/poly_bounds.xsd deleted file mode 100644 index d2576f484873..000000000000 --- a/python/plugins/processing/tests/testdata/expected/poly_bounds.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/polys_centroid.xsd b/python/plugins/processing/tests/testdata/expected/polys_centroid.xsd deleted file mode 100644 index dbf3fda59845..000000000000 --- a/python/plugins/processing/tests/testdata/expected/polys_centroid.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/polys_deleteholes.xsd b/python/plugins/processing/tests/testdata/expected/polys_deleteholes.xsd deleted file mode 100644 index 30f3028a46c6..000000000000 --- a/python/plugins/processing/tests/testdata/expected/polys_deleteholes.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/polys_to_lines.xsd b/python/plugins/processing/tests/testdata/expected/polys_to_lines.xsd deleted file mode 100644 index 5c1789371a7c..000000000000 --- a/python/plugins/processing/tests/testdata/expected/polys_to_lines.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/python/plugins/processing/tests/testdata/expected/rectanglesovalsdiamondsfixed.xsd b/python/plugins/processing/tests/testdata/expected/rectanglesovalsdiamondsfixed.xsd deleted file mode 100644 index f28e362a2371..000000000000 --- a/python/plugins/processing/tests/testdata/expected/rectanglesovalsdiamondsfixed.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - From e1ee477c40a7797ea8d233d7151b4eda0ed36f2a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 17:57:39 +0200 Subject: [PATCH 715/897] [processing] use numeric parameter for buffer distance --- python/plugins/processing/algs/gdal/ogr2ogrbuffer.py | 9 ++++++--- .../processing/tests/testdata/gdal_algorithm_tests.yaml | 6 +++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py b/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py index e20ca5dd05e2..d33f52dddf68 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py @@ -27,6 +27,7 @@ from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterString +from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterTableField from processing.core.outputs import OutputVector @@ -59,8 +60,10 @@ def defineCharacteristics(self): self.addParameter(ParameterString(self.GEOMETRY, self.tr('Geometry column name ("geometry" for Shapefiles, may be different for other formats)'), 'geometry', optional=False)) - self.addParameter(ParameterString(self.DISTANCE, - self.tr('Buffer distance'), '1000', optional=False)) + self.addParameter(ParameterNumber(self.DISTANCE, + self.tr('Buffer distance'), + 0.0, 99999999.999999, 1000.0, + optional=False)) self.addParameter(ParameterBoolean(self.DISSOLVEALL, self.tr('Dissolve all results'), False)) self.addParameter(ParameterTableField(self.FIELD, @@ -124,4 +127,4 @@ def getConsoleCommands(self): return commands def commandName(self): - return "ogr2ogr" + return 'ogr2ogr' diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 1b0d23ba39b7..32bbd8ab5845 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -76,7 +76,7 @@ tests: name: OGR buffer lines params: DISSOLVEALL: false - DISTANCE: '1' + DISTANCE: 1.0 GEOMETRY: geometry INPUT_LAYER: name: lines.gml @@ -91,7 +91,7 @@ tests: name: OGR basic polygon buffer params: DISSOLVEALL: false - DISTANCE: '0.5' + DISTANCE: 0.5 GEOMETRY: geometry INPUT_LAYER: name: polys.gml @@ -106,7 +106,7 @@ tests: name: OGR polygon buffer with dissolve params: DISSOLVEALL: true - DISTANCE: '0.5' + DISTANCE: 0.5 GEOMETRY: geometry INPUT_LAYER: name: polys.gml From 652addb5074e8f889707fa7172b14ac3cbf7b475 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 1 Nov 2016 20:16:41 +0200 Subject: [PATCH 716/897] [processing] don't pass layer name when '-sql' parameter is used --- python/plugins/processing/algs/gdal/offsetcurve.py | 1 - python/plugins/processing/algs/gdal/ogr2ogrbuffer.py | 1 - python/plugins/processing/algs/gdal/ogr2ogrpointsonlines.py | 1 - python/plugins/processing/algs/gdal/onesidebuffer.py | 1 - 4 files changed, 4 deletions(-) diff --git a/python/plugins/processing/algs/gdal/offsetcurve.py b/python/plugins/processing/algs/gdal/offsetcurve.py index 03318053f992..83fd4b32a160 100644 --- a/python/plugins/processing/algs/gdal/offsetcurve.py +++ b/python/plugins/processing/algs/gdal/offsetcurve.py @@ -98,7 +98,6 @@ def getConsoleCommands(self): arguments = [] arguments.append(output) arguments.append(ogrLayer) - arguments.append(layername) arguments.append('-dialect') arguments.append('sqlite') arguments.append('-sql') diff --git a/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py b/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py index d33f52dddf68..9c45e91ac818 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrbuffer.py @@ -96,7 +96,6 @@ def getConsoleCommands(self): arguments = [] arguments.append(output) arguments.append(ogrLayer) - arguments.append(ogrLayerName(inLayer)) arguments.append('-dialect') arguments.append('sqlite') arguments.append('-sql') diff --git a/python/plugins/processing/algs/gdal/ogr2ogrpointsonlines.py b/python/plugins/processing/algs/gdal/ogr2ogrpointsonlines.py index 47eed0366572..d99efc20ecd4 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrpointsonlines.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrpointsonlines.py @@ -80,7 +80,6 @@ def getConsoleCommands(self): arguments = [] arguments.append(output) arguments.append(ogrLayer) - arguments.append(ogrLayerName(inLayer)) arguments.append('-dialect sqlite -sql "SELECT ST_Line_Interpolate_Point(') arguments.append(geometry) diff --git a/python/plugins/processing/algs/gdal/onesidebuffer.py b/python/plugins/processing/algs/gdal/onesidebuffer.py index 29fc7f730dae..f9a9f4436262 100644 --- a/python/plugins/processing/algs/gdal/onesidebuffer.py +++ b/python/plugins/processing/algs/gdal/onesidebuffer.py @@ -103,7 +103,6 @@ def getConsoleCommands(self): arguments = [] arguments.append(output) arguments.append(ogrLayer) - arguments.append(layername) arguments.append('-dialect') arguments.append('sqlite') arguments.append('-sql') From 85d1fd720b08e782d31b7b0625ba603cb9c39a8f Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 2 Nov 2016 12:53:16 +0200 Subject: [PATCH 717/897] [processing] cleanup test data --- python/plugins/processing/__init__.py | 1 - .../processing/algs/grass/GrassUtils.py | 2 +- .../processing/algs/grass7/Grass7Utils.py | 2 +- .../plugins/processing/tests/CMakeLists.txt | 4 +- .../processing/tests/ParametersTest.py | 4 +- python/plugins/processing/tests/TestData.py | 47 +-- python/plugins/processing/tests/ToolsTest.py | 52 +-- .../plugins/processing/tests/data/lines.dbf | Bin 223 -> 0 bytes .../plugins/processing/tests/data/lines.prj | 1 - .../plugins/processing/tests/data/lines.qpj | 1 - .../plugins/processing/tests/data/lines.shp | Bin 716 -> 0 bytes .../plugins/processing/tests/data/lines.shx | Bin 124 -> 0 bytes .../plugins/processing/tests/data/points.dbf | Bin 610 -> 0 bytes .../plugins/processing/tests/data/points.prj | 1 - .../plugins/processing/tests/data/points.qpj | 1 - .../plugins/processing/tests/data/points.shp | Bin 436 -> 0 bytes .../plugins/processing/tests/data/points.shx | Bin 196 -> 0 bytes .../plugins/processing/tests/data/points2.dbf | Bin 938 -> 0 bytes .../plugins/processing/tests/data/points2.prj | 1 - .../plugins/processing/tests/data/points2.qpj | 1 - .../plugins/processing/tests/data/points2.shp | Bin 324 -> 0 bytes .../plugins/processing/tests/data/points2.shx | Bin 164 -> 0 bytes .../processing/tests/data/polygons.dbf | Bin 210 -> 0 bytes .../processing/tests/data/polygons.geojson | 10 - .../processing/tests/data/polygons.prj | 1 - .../processing/tests/data/polygons.qpj | 1 - .../processing/tests/data/polygons.shp | Bin 532 -> 0 bytes .../processing/tests/data/polygons.shx | Bin 116 -> 0 bytes .../processing/tests/data/polygons2.dbf | Bin 302 -> 0 bytes .../processing/tests/data/polygons2.prj | 1 - .../processing/tests/data/polygons2.qpj | 1 - .../processing/tests/data/polygons2.shp | Bin 484 -> 0 bytes .../processing/tests/data/polygons2.shx | Bin 116 -> 0 bytes .../plugins/processing/tests/data/project.qgs | 356 ------------------ .../plugins/processing/tests/data/union.dbf | Bin 938 -> 0 bytes .../plugins/processing/tests/data/union.prj | 1 - .../plugins/processing/tests/data/union.qpj | 1 - .../plugins/processing/tests/data/union.shp | Bin 2120 -> 0 bytes .../plugins/processing/tests/data/union.shx | Bin 164 -> 0 bytes .../processing/tests/testdata/points.gfs | 10 + .../processing/tests/testdata/points.gml | 20 +- .../tests/{data => testdata}/table.dbf | Bin 42 files changed, 64 insertions(+), 456 deletions(-) delete mode 100644 python/plugins/processing/tests/data/lines.dbf delete mode 100644 python/plugins/processing/tests/data/lines.prj delete mode 100644 python/plugins/processing/tests/data/lines.qpj delete mode 100644 python/plugins/processing/tests/data/lines.shp delete mode 100644 python/plugins/processing/tests/data/lines.shx delete mode 100644 python/plugins/processing/tests/data/points.dbf delete mode 100644 python/plugins/processing/tests/data/points.prj delete mode 100644 python/plugins/processing/tests/data/points.qpj delete mode 100644 python/plugins/processing/tests/data/points.shp delete mode 100644 python/plugins/processing/tests/data/points.shx delete mode 100644 python/plugins/processing/tests/data/points2.dbf delete mode 100644 python/plugins/processing/tests/data/points2.prj delete mode 100644 python/plugins/processing/tests/data/points2.qpj delete mode 100644 python/plugins/processing/tests/data/points2.shp delete mode 100644 python/plugins/processing/tests/data/points2.shx delete mode 100644 python/plugins/processing/tests/data/polygons.dbf delete mode 100644 python/plugins/processing/tests/data/polygons.geojson delete mode 100644 python/plugins/processing/tests/data/polygons.prj delete mode 100644 python/plugins/processing/tests/data/polygons.qpj delete mode 100644 python/plugins/processing/tests/data/polygons.shp delete mode 100644 python/plugins/processing/tests/data/polygons.shx delete mode 100644 python/plugins/processing/tests/data/polygons2.dbf delete mode 100644 python/plugins/processing/tests/data/polygons2.prj delete mode 100644 python/plugins/processing/tests/data/polygons2.qpj delete mode 100644 python/plugins/processing/tests/data/polygons2.shp delete mode 100644 python/plugins/processing/tests/data/polygons2.shx delete mode 100644 python/plugins/processing/tests/data/project.qgs delete mode 100644 python/plugins/processing/tests/data/union.dbf delete mode 100644 python/plugins/processing/tests/data/union.prj delete mode 100644 python/plugins/processing/tests/data/union.qpj delete mode 100644 python/plugins/processing/tests/data/union.shp delete mode 100644 python/plugins/processing/tests/data/union.shx rename python/plugins/processing/tests/{data => testdata}/table.dbf (100%) diff --git a/python/plugins/processing/__init__.py b/python/plugins/processing/__init__.py index 358842c79c0f..0b817d3f7f48 100644 --- a/python/plugins/processing/__init__.py +++ b/python/plugins/processing/__init__.py @@ -30,7 +30,6 @@ from processing.tools.vector import * # NOQA from processing.tools.raster import * # NOQA from processing.tools.system import * # NOQA -from processing.tests.TestData import loadTestData # NOQA def classFactory(iface): diff --git a/python/plugins/processing/algs/grass/GrassUtils.py b/python/plugins/processing/algs/grass/GrassUtils.py index 1c9d58a047e2..903a569569b9 100644 --- a/python/plugins/processing/algs/grass/GrassUtils.py +++ b/python/plugins/processing/algs/grass/GrassUtils.py @@ -383,7 +383,7 @@ def checkGrassIsInstalled(ignorePreviousState=False): points(), False, False, - '270778.60198,270855.745301,4458921.97814,4458983.8488', + 'None', -1, 0.0001, 0, diff --git a/python/plugins/processing/algs/grass7/Grass7Utils.py b/python/plugins/processing/algs/grass7/Grass7Utils.py index 79c3b9ec5c6a..ea7d7a3f8418 100644 --- a/python/plugins/processing/algs/grass7/Grass7Utils.py +++ b/python/plugins/processing/algs/grass7/Grass7Utils.py @@ -363,7 +363,7 @@ def checkGrass7IsInstalled(ignorePreviousState=False): points(), False, False, - '270778.60198,270855.745301,4458921.97814,4458983.8488', + 'None', -1, 0.0001, 0, diff --git a/python/plugins/processing/tests/CMakeLists.txt b/python/plugins/processing/tests/CMakeLists.txt index cc02bff82629..09fb9f4fa3f9 100644 --- a/python/plugins/processing/tests/CMakeLists.txt +++ b/python/plugins/processing/tests/CMakeLists.txt @@ -1,8 +1,8 @@ FILE(GLOB PY_FILES *.py) -FILE(GLOB TEST_DATA_FILES data/*) +FILE(GLOB TEST_DATA_FILES testdata/points.* testdata/table.dbf) PLUGIN_INSTALL(processing tests ${PY_FILES}) -PLUGIN_INSTALL(processing tests/data ${TEST_DATA_FILES}) +PLUGIN_INSTALL(processing tests/testdata ${TEST_DATA_FILES}) IF(ENABLE_TESTS) INCLUDE(UsePythonTest) diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index a73b992ec7fd..b40a40aca857 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -43,7 +43,7 @@ ParameterSelection, ParameterExpression) from processing.tools import dataobjects -from processing.tests.TestData import points2 +from processing.tests.TestData import points from qgis.core import (QgsRasterLayer, QgsVectorLayer) @@ -498,7 +498,7 @@ class ParameterTableFieldTest(unittest.TestCase): def testOptional(self): parent_name = 'test_parent_layer' - test_data = points2() + test_data = points() test_layer = QgsVectorLayer(test_data, parent_name, 'ogr') parent = ParameterVector(parent_name, parent_name) parent.setValue(test_layer) diff --git a/python/plugins/processing/tests/TestData.py b/python/plugins/processing/tests/TestData.py index 9e3963d0058c..a0d34da7a9d1 100644 --- a/python/plugins/processing/tests/TestData.py +++ b/python/plugins/processing/tests/TestData.py @@ -26,54 +26,13 @@ __revision__ = '$Format:%H$' import os.path -from processing.tools import dataobjects -dataFolder = os.path.join(os.path.dirname(__file__), 'data') +testDataPath = os.path.join(os.path.dirname(__file__), 'testdata') def table(): - return os.path.join(dataFolder, 'table.dbf') + return os.path.join(testDataPath, 'table.dbf') def points(): - return os.path.join(dataFolder, 'points.shp') - - -def points2(): - return os.path.join(dataFolder, 'points2.shp') - - -def raster(): - return os.path.join(dataFolder, 'raster.tif') - - -def lines(): - return os.path.join(dataFolder, 'lines.shp') - - -def polygons(): - return os.path.join(dataFolder, 'polygons.shp') - - -def polygons2(): - return os.path.join(dataFolder, 'polygons2.shp') - - -def polygonsGeoJson(): - return os.path.join(dataFolder, 'polygons.geojson') - - -def union(): - return os.path.join(dataFolder, 'union.shp') - - -def loadTestData(): - dataobjects.load(points(), 'points') - dataobjects.load(points2(), 'points2') - dataobjects.load(polygons(), 'polygons') - dataobjects.load(polygons2(), 'polygons2') - dataobjects.load(polygonsGeoJson(), 'polygonsGeoJson') - dataobjects.load(lines(), 'lines') - dataobjects.load(raster(), 'raster') - dataobjects.load(table(), 'table') - dataobjects.load(union(), 'union') + return os.path.join(testDataPath, 'points.gml') diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index 55e2de437b9b..46bde7e57ff0 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -26,7 +26,7 @@ __revision__ = '$Format:%H$' from qgis.testing import start_app, unittest -from processing.tests.TestData import points2 +from processing.tests.TestData import points from processing.tools import vector from qgis.core import (QgsVectorLayer, QgsFeatureRequest) from processing.core.ProcessingConfig import ProcessingConfig @@ -39,13 +39,13 @@ class VectorTest(unittest.TestCase): def testFeatures(self): ProcessingConfig.initialize() - test_data = points2() + test_data = points() test_layer = QgsVectorLayer(test_data, 'test', 'ogr') # test with all features features = vector.features(test_layer) - self.assertEqual(len(features), 8) - self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7])) + self.assertEqual(len(features), 9) + self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8])) # test with selected features previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) @@ -59,15 +59,15 @@ def testFeatures(self): ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False) test_layer.selectByIds([2, 4, 6]) features = vector.features(test_layer) - self.assertEqual(len(features), 8) - self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7])) + self.assertEqual(len(features), 9) + self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8])) # using selected features, but no selection ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True) test_layer.removeSelection() features = vector.features(test_layer) - self.assertEqual(len(features), 8) - self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7])) + self.assertEqual(len(features), 9) + self.assertEqual(set([f.id() for f in features]), set([0, 1, 2, 3, 4, 5, 6, 7, 8])) # test that feature request is honored ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, False) @@ -87,54 +87,54 @@ def testFeatures(self): def testValues(self): ProcessingConfig.initialize() - test_data = points2() + test_data = points() test_layer = QgsVectorLayer(test_data, 'test', 'ogr') # field by index - res = vector.values(test_layer, 0) - self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) + res = vector.values(test_layer, 1) + self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9]) # field by name res = vector.values(test_layer, 'id') - self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) + self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9]) # two fields - res = vector.values(test_layer, 0, 3) - self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) - self.assertEqual(res[3], [2, 1, 0, 2, 1, 0, 0, 0]) + res = vector.values(test_layer, 1, 2) + self.assertEqual(res[1], [1, 2, 3, 4, 5, 6, 7, 8, 9]) + self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0]) # two fields by name - res = vector.values(test_layer, 'id', 'id_2') - self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) - self.assertEqual(res['id_2'], [2, 1, 0, 2, 1, 0, 0, 0]) + res = vector.values(test_layer, 'id', 'id2') + self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9]) + self.assertEqual(res['id2'], [2, 1, 0, 2, 1, 0, 0, 0, 0]) # two fields by name and index - res = vector.values(test_layer, 'id', 3) - self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) - self.assertEqual(res[3], [2, 1, 0, 2, 1, 0, 0, 0]) + res = vector.values(test_layer, 'id', 2) + self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8, 9]) + self.assertEqual(res[2], [2, 1, 0, 2, 1, 0, 0, 0, 0]) # test with selected features previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True) test_layer.selectByIds([2, 4, 6]) - res = vector.values(test_layer, 0) - self.assertEqual(set(res[0]), set([5, 7, 3])) + res = vector.values(test_layer, 1) + self.assertEqual(set(res[1]), set([5, 7, 3])) ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value) def testUniqueValues(self): ProcessingConfig.initialize() - test_data = points2() + test_data = points() test_layer = QgsVectorLayer(test_data, 'test', 'ogr') # field by index - v = vector.uniqueValues(test_layer, 3) + v = vector.uniqueValues(test_layer, 2) self.assertEqual(len(v), len(set(v))) self.assertEqual(set(v), set([2, 1, 0])) # field by name - v = vector.uniqueValues(test_layer, 'id_2') + v = vector.uniqueValues(test_layer, 'id2') self.assertEqual(len(v), len(set(v))) self.assertEqual(set(v), set([2, 1, 0])) diff --git a/python/plugins/processing/tests/data/lines.dbf b/python/plugins/processing/tests/data/lines.dbf deleted file mode 100644 index c562bb2a0fc44a136defa4afa8b14e99da5ba840..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 223 zcmZSPWfo^WP@ diff --git a/python/plugins/processing/tests/data/lines.prj b/python/plugins/processing/tests/data/lines.prj deleted file mode 100644 index c048a47c177c..000000000000 --- a/python/plugins/processing/tests/data/lines.prj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50_UTM_zone_30N",GEOGCS["GCS_European_1950",DATUM["D_European_1950",SPHEROID["International_1924",6378388,297]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]] \ No newline at end of file diff --git a/python/plugins/processing/tests/data/lines.qpj b/python/plugins/processing/tests/data/lines.qpj deleted file mode 100644 index 9be6fb54cf31..000000000000 --- a/python/plugins/processing/tests/data/lines.qpj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50 / UTM zone 30N",GEOGCS["ED50",DATUM["European_Datum_1950",SPHEROID["International 1924",6378388,297,AUTHORITY["EPSG","7022"]],TOWGS84[-87,-98,-121,0,0,0,0],AUTHORITY["EPSG","6230"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4230"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","23030"]] diff --git a/python/plugins/processing/tests/data/lines.shp b/python/plugins/processing/tests/data/lines.shp deleted file mode 100644 index 77ab7ca7e5095a489c27b2a5dd5cef835e1d19e4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 716 zcmZQzQ0HR63K-K~Ff%X!5rgwFu|?0@1RSgX#`a}01v-ZIcJA`(5OAC`)ziNg$j7Q3 zRge+L^#GYAbg}AGXS;x7f!mFSVxZoX=?;=dfqa-*AcbsDy)d;fIhfja2AQWSfqK>4 zE`{v|>V4V%`eHedZ!MY8HxtPJ_8{wQDUjb+9PU3C$UkfR`3=afZ`Y3V%?9#eb_1

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  JI%XWUUeOT| diff --git a/python/plugins/processing/tests/data/points.dbf b/python/plugins/processing/tests/data/points.dbf deleted file mode 100644 index dc2d949c8396c0b2baace8401a287634559b796b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 610 zcmZY6u?~Vj3fOw=dw%>_(;YPo^jwcoWln&sJU zLqs1s4BzFtUJz@>-5ST==HB*Ack55XY07U`|6s^J+9^%vF=OxNh2Vm)9LI$K(X+sE z2s?Jxy}$|&=h<8Lo?Qu7a%r9FTftRaS*Q92xWK_WRWHItj@GGq2`+K6PQ9astGTvL e^%eYA5uO|ZM5?b~AmSDS(e*G8@r!}X_4Z$wYcTTw diff --git a/python/plugins/processing/tests/data/points.prj b/python/plugins/processing/tests/data/points.prj deleted file mode 100644 index c048a47c177c..000000000000 --- a/python/plugins/processing/tests/data/points.prj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50_UTM_zone_30N",GEOGCS["GCS_European_1950",DATUM["D_European_1950",SPHEROID["International_1924",6378388,297]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]] \ No newline at end of file diff --git a/python/plugins/processing/tests/data/points.qpj b/python/plugins/processing/tests/data/points.qpj deleted file mode 100644 index 9be6fb54cf31..000000000000 --- a/python/plugins/processing/tests/data/points.qpj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50 / UTM zone 30N",GEOGCS["ED50",DATUM["European_Datum_1950",SPHEROID["International 1924",6378388,297,AUTHORITY["EPSG","7022"]],TOWGS84[-87,-98,-121,0,0,0,0],AUTHORITY["EPSG","6230"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4230"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","23030"]] diff --git a/python/plugins/processing/tests/data/points.shp b/python/plugins/processing/tests/data/points.shp deleted file mode 100644 index 5fd2897598f847a08e99adca158ba9059b9865a7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 436 zcmZQzQ0HR64sN|*W?*0h%H4^|&3M%&;K+YvW?dFjprf6e!Ed<^0mnV3g1%J(`Pj9i zh=Ppa0ug5n=FGp>F5vjiAoCPdFB44euc}444N%VCGih-y#9W{YAo|_~=G?yvl!Lhe zD9!?tgSjW;l$LQmL?0_m?onyziYY*S|ErWvS3u<0U~Ihqz?d&=v}w~ diff --git a/python/plugins/processing/tests/data/points.shx b/python/plugins/processing/tests/data/points.shx deleted file mode 100644 index 0cae4ee52f02e610d57e428a35571b39f7c90940..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 196 zcmZQzQ0HR64w7ClGcYg$aOA%-vo4D%(9zD#;I~|dfa9K1LEkEYeC*m$ oM2&zvkUb7i+7C*{K+)rp!5_dy$DKgfYSS*^cfHh0D>VEF#rGn diff --git a/python/plugins/processing/tests/data/points2.dbf b/python/plugins/processing/tests/data/points2.dbf deleted file mode 100644 index b8b06163cd46d67a977b4dab1377e0b7535a4b7d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 938 zcmZSPWtQMzU|@L25D6qPfu{>x%n!ukf^#8^0Dqszc)w8Jct-}Xyf7Q80g+v7f zm@60<5E|eL5y})007(ZvgAv9dG@u)tgfJDzGKNdzbuq#p2o_u?ih(eW30&Gp&j?3Q z0G)zxC&KM;omhjy6fTX|V1#i9E8sez2BQXr8C)8#!H57ru;4mjzDJ?W;nGw#*n&m| GO923Vr&@Uc diff --git a/python/plugins/processing/tests/data/points2.prj b/python/plugins/processing/tests/data/points2.prj deleted file mode 100644 index c048a47c177c..000000000000 --- a/python/plugins/processing/tests/data/points2.prj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50_UTM_zone_30N",GEOGCS["GCS_European_1950",DATUM["D_European_1950",SPHEROID["International_1924",6378388,297]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]] \ No newline at end of file diff --git a/python/plugins/processing/tests/data/points2.qpj b/python/plugins/processing/tests/data/points2.qpj deleted file mode 100644 index 9be6fb54cf31..000000000000 --- a/python/plugins/processing/tests/data/points2.qpj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50 / UTM zone 30N",GEOGCS["ED50",DATUM["European_Datum_1950",SPHEROID["International 1924",6378388,297,AUTHORITY["EPSG","7022"]],TOWGS84[-87,-98,-121,0,0,0,0],AUTHORITY["EPSG","6230"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4230"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","23030"]] diff --git a/python/plugins/processing/tests/data/points2.shp b/python/plugins/processing/tests/data/points2.shp deleted file mode 100644 index c27dfc60411a1c23baa2d203752ba88bac050a9c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 324 zcmZQzQ0HR64i>#&W?*0h%K0DUzxAd~z;Q+KOpz?6Ku0^?=!Iq-0*($6^EE4heC*m$ zL_x-Ife0z{<$+&-W;GW6waSI)WrE55QB?F+Y!`6kvvOWs29X200HP1(h6mT}rx!xx zSYUEjR|&|T2kL{l4=BzGlXLs1GV481?!p244>p$zAhaJ7X?T4(5LVS-Cvp diff --git a/python/plugins/processing/tests/data/points2.shx b/python/plugins/processing/tests/data/points2.shx deleted file mode 100644 index 381609668f6214da68c406645a515199701ae304..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 164 zcmZQzQ0HR64uW1VGcYg$<@^uw-+I#~;JBiArbrf3prajc^g^=^0Y?Xk`I?nLK6dRW dqDDX-$Q}nM?FXe}pmY|Lu7J{QPX*lM{$RAmGj4qvb%gD+)CC=K$rxUQ`IJ0`g&MH>Kt!`2fQ^QBCo(JTg=J4F@3zUE2{NrmnkYBXEKk5{c-7vTK=k8$z$?yNu(NPAJ|Mw@M J8su+u`vES=s5Srq diff --git a/python/plugins/processing/tests/data/polygons.shx b/python/plugins/processing/tests/data/polygons.shx deleted file mode 100644 index b5781ef074d2f9da9d328d04d2ef4edf6f61f46a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 116 zcmZQzQ0HR64y;}Grh=IO;`z^Gjt4bmRxG zQAQvy0GnA=*Oxr?2byJnrdF;5XckBzJ5;OKoH*8bKzm_wx2m+wG}{FnJN`Cxij6EfWxDfZVyE za$3*X$k!lX26!wir=VQ$e{QIxL@42J^Y?th?gfVs7K MhfaJckdN*j0QRAc;Q#;t diff --git a/python/plugins/processing/tests/data/polygons2.shx b/python/plugins/processing/tests/data/polygons2.shx deleted file mode 100644 index 727123de23084cfe2436943c7ddafc939ea17fb6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 116 zcmZQzQ0HR64y;}&g$k6k;8 Os1cAC0K{!ToB;rD5Dtt0 diff --git a/python/plugins/processing/tests/data/project.qgs b/python/plugins/processing/tests/data/project.qgs deleted file mode 100644 index af852743cbc6..000000000000 --- a/python/plugins/processing/tests/data/project.qgs +++ /dev/null @@ -1,356 +0,0 @@ - - - - - degrees - - -5.696740 - 40.246875 - -5.694684 - 40.248640 - - 1 - - - +proj=longlat +datum=WGS84 +no_defs - 3452 - 4326 - EPSG:4326 - WGS 84 - longlat - WGS84 - true - - - - - - - - - - - - - - - - - - - - lines20130323011923044 - ./lines.shp - - - lines - - - +proj=utm +zone=30 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs - 1976 - 23030 - EPSG:23030 - ED50 / UTM zone 30N - utm - intl - false - - - 255 - ogr - - - - - - - - - - - - - - - - - - - - - - - - ID - - - - .. - - .. - generatedlayout - - - - - - points20130323011923066 - ./points.shp - - - points - - - +proj=utm +zone=30 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs - 1976 - 23030 - EPSG:23030 - ED50 / UTM zone 30N - utm - intl - false - - - 255 - ogr - - - - - - - - - - - - - - - - - - - - - - ID - - - - .. - - .. - generatedlayout - - - - - - polygons20130323011923079 - ./polygons.shp - - - polygons - - - +proj=utm +zone=30 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs - 1976 - 23030 - EPSG:23030 - ED50 / UTM zone 30N - utm - intl - false - - - 255 - ogr - - - - - - - - - - - - - - - - - - - - - ID - - - - .. - - .. - generatedlayout - - - - - - polygons220130323011923092 - ./polygons2.shp - - - polygons2 - - - +proj=utm +zone=30 +ellps=intl +towgs84=-87,-98,-121,0,0,0,0 +units=m +no_defs - 1976 - 23030 - EPSG:23030 - ED50 / UTM zone 30N - utm - intl - false - - - 255 - ogr - - - - - - - - - - - - - - - - - - - - - ID - - - - .. - - .. - generatedlayout - - - - - - - - EPSG:4326 - 1 - - - false - - - 0 - 255 - 255 - 255 - 255 - 255 - 255 - - - 2 - true - - - diff --git a/python/plugins/processing/tests/data/union.dbf b/python/plugins/processing/tests/data/union.dbf deleted file mode 100644 index b8b06163cd46d67a977b4dab1377e0b7535a4b7d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 938 zcmZSPWtQMzU|@L25D6qPfu{>x%n!ukf^#8^0Dqszc)w8Jct-}Xyf7Q80g+v7f zm@60<5E|eL5y})007(ZvgAv9dG@u)tgfJDzGKNdzbuq#p2o_u?ih(eW30&Gp&j?3Q z0G)zxC&KM;omhjy6fTX|V1#i9E8sez2BQXr8C)8#!H57ru;4mjzDJ?W;nGw#*n&m| GO923Vr&@Uc diff --git a/python/plugins/processing/tests/data/union.prj b/python/plugins/processing/tests/data/union.prj deleted file mode 100644 index c048a47c177c..000000000000 --- a/python/plugins/processing/tests/data/union.prj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50_UTM_zone_30N",GEOGCS["GCS_European_1950",DATUM["D_European_1950",SPHEROID["International_1924",6378388,297]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["Meter",1]] \ No newline at end of file diff --git a/python/plugins/processing/tests/data/union.qpj b/python/plugins/processing/tests/data/union.qpj deleted file mode 100644 index 9be6fb54cf31..000000000000 --- a/python/plugins/processing/tests/data/union.qpj +++ /dev/null @@ -1 +0,0 @@ -PROJCS["ED50 / UTM zone 30N",GEOGCS["ED50",DATUM["European_Datum_1950",SPHEROID["International 1924",6378388,297,AUTHORITY["EPSG","7022"]],TOWGS84[-87,-98,-121,0,0,0,0],AUTHORITY["EPSG","6230"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4230"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-3],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","23030"]] diff --git a/python/plugins/processing/tests/data/union.shp b/python/plugins/processing/tests/data/union.shp deleted file mode 100644 index d0e0dc472c298b8e750d4b3a60d3abc27a299a35..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2120 zcmZuyeN4=87{4NlWhI?v3Kdq#7)lrA#?D15jY?S(sk!bti4<3jEvH&#lVwV~vAHN+ zB`j8dq%q!YO1|j!(bb1nq?*5sb`jIzS_mQ@^s(K zE0E)#JPO_mJ?9!$xn9yi{?;{TUJLY`tG_TPBmnWue~y+>e3=h09C5M;_iRITTPu9E z)$7yAHnKA^v<$vor&?2q1H#Qjx+qJ`4`CZ*X;6~xMUn4zZ#&zVB@g^oL4H$vSws5r z&+d69$YF!p&O*D`KG}t)e8?{cey&J`o^uCUb8~_q8$HTL2@7L$djDYZ0m$Es z{*L*tJqsX9Jb;SMDsri=>=E1U2G}xZuf}q5EFxek4t!?ls`z2L$8SFAwywcF)_cypYJf~Vbitu7?$e*% zeArrz0o~cqDetNpiy*V@y0Q6VKdp?vvi2vrv8Qr4dSdE*Z1zV{S`T@;&g! zHOjt9dz46HbBp+q?`Yxk3-4o*JF?H@lLu_X&kP*;$leV{S(oZ`4)e)2a-QTH$2qKi zIYa;W68>^tC7<%%$$Kg9t*n1;iSLJA;Qg7^kwJXRd6aLqeA6X9*)Qgdcah{<+Jiz` zCpO~KR&YAE5!m={$vsAMXRUs`RW2m=Ge6@K98xl@}A1MlXEHOK<)tEKfEL44v{-X?jX4n&g$k6k;8 xs1cAC0mOYkoB_nYfVhZ(fw2HcCjjXyK-zK_W-5.00000 3.00000 + + id + id + Integer + + + id2 + id2 + Integer + diff --git a/python/plugins/processing/tests/testdata/points.gml b/python/plugins/processing/tests/testdata/points.gml index 9be17bfadca1..b38e58604810 100644 --- a/python/plugins/processing/tests/testdata/points.gml +++ b/python/plugins/processing/tests/testdata/points.gml @@ -10,50 +10,68 @@ 83 - + 1,1 + 1 + 2 3,3 + 2 + 1 2,2 + 3 + 0 5,2 + 4 + 2 4,1 + 5 + 1 0,-5 + 6 + 0 8,-1 + 7 + 0 7,-1 + 8 + 0 0,-1 + 9 + 0 diff --git a/python/plugins/processing/tests/data/table.dbf b/python/plugins/processing/tests/testdata/table.dbf similarity index 100% rename from python/plugins/processing/tests/data/table.dbf rename to python/plugins/processing/tests/testdata/table.dbf From b6d5f35be2ce6c33c2131495bd31f210bda1411a Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 10 Nov 2016 12:08:15 +0200 Subject: [PATCH 718/897] [processing] cleanup OGR dissolve algorithm code Avoid double extensions when creating temp files --- .../processing/algs/gdal/GdalAlgorithm.py | 1 - .../processing/algs/gdal/ogr2ogrdissolve.py | 68 ++++++++++--------- .../plugins/processing/tools/dataobjects.py | 2 +- 3 files changed, 37 insertions(+), 34 deletions(-) diff --git a/python/plugins/processing/algs/gdal/GdalAlgorithm.py b/python/plugins/processing/algs/gdal/GdalAlgorithm.py index 5cbcad690e07..5df8012983fa 100644 --- a/python/plugins/processing/algs/gdal/GdalAlgorithm.py +++ b/python/plugins/processing/algs/gdal/GdalAlgorithm.py @@ -74,7 +74,6 @@ def processAlgorithm(self, progress): def shortHelp(self): return self._formatHelp('''This algorithm is based on the GDAL %s module. - For more info, see the module help ''' % (self.commandName(), self.commandName())) diff --git a/python/plugins/processing/algs/gdal/ogr2ogrdissolve.py b/python/plugins/processing/algs/gdal/ogr2ogrdissolve.py index 191a68866000..6677387e3d7b 100644 --- a/python/plugins/processing/algs/gdal/ogr2ogrdissolve.py +++ b/python/plugins/processing/algs/gdal/ogr2ogrdissolve.py @@ -85,52 +85,56 @@ def defineCharacteristics(self): def getConsoleCommands(self): inLayer = self.getParameterValue(self.INPUT_LAYER) - ogrLayer = ogrConnectionString(inLayer)[1:-1] - layername = "'" + ogrLayerName(inLayer) + "'" - geometry = str(self.getParameterValue(self.GEOMETRY)) - field = str(self.getParameterValue(self.FIELD)) - statsatt = str(self.getParameterValue(self.STATSATT)) - stats = self.getParameterValue(self.STATS) - area = self.getParameterValue(self.AREA) + geometry = self.getParameterValue(self.GEOMETRY) + field = self.getParameterValue(self.FIELD) multi = self.getParameterValue(self.MULTI) - count = self.getParameterValue(self.COUNT) fields = self.getParameterValue(self.FIELDS) - querystart = '-dialect sqlite -sql "SELECT ST_Union(' + geometry + ')' - queryend = ' FROM ' + layername + ' GROUP BY ' + field + '"' - if fields: - queryfields = ",*" - else: - queryfields = "," + field - if count: - querycount = ", COUNT(" + geometry + ") AS count" - else: - querycount = "" - if stats: - querystats = ", SUM(" + statsatt + ") AS sum_diss, MIN(" + statsatt + ") AS min_diss, MAX(" + statsatt + ") AS max_diss, AVG(" + statsatt + ") AS avg_diss" - else: - querystats = "" - if area: - queryarea = ", SUM(ST_area(" + geometry + ")) AS area_diss, ST_perimeter(ST_union(" + geometry + ")) AS peri_diss" - else: - queryarea = "" + count = self.getParameterValue(self.COUNT) + area = self.getParameterValue(self.AREA) + stats = self.getParameterValue(self.STATS) + statsatt = self.getParameterValue(self.STATSATT) + options = self.getParameterValue(self.OPTIONS) + + ogrLayer = ogrConnectionString(inLayer)[1:-1] + layername = ogrLayerName(inLayer) - query = querystart + queryfields + querycount + querystats + queryarea + queryend output = self.getOutputFromName(self.OUTPUT_LAYER) outFile = output.value output = ogrConnectionString(outFile) - options = str(self.getParameterValue(self.OPTIONS)) arguments = [] arguments.append(output) arguments.append(ogrLayer) - arguments.append(ogrLayerName(inLayer)) - arguments.append(query) + arguments.append('-dialect') + arguments.append('sqlite') + arguments.append('-sql') + + sql = "SELECT ST_Union('{}')".format(geometry) + + sqlOpts = '' + if fields: + sqlOpts += ',*' + else: + sqlOpts += ',{}'.format(field) + + if count: + sqlOpts += ", COUNT('{}') AS count".format(geometry) + + if stats: + sqlOpts += ", SUM('{0}') AS sum_diss, MIN('{0}') AS min_diss, MAX('{0}') AS max_diss, AVG('{0}') AS avg_diss".format(statsatt) + + if area: + sqlOpts += ", SUM(ST_Area('{0}')) AS area_diss, ST_Perimeter(ST_Union('{0}')) AS peri_diss".format(geometry) + + sql = '{}{} FROM {} GROUP BY {}'.format(sql, sqlOpts, layername, field) + + arguments.append(sql) if not multi: arguments.append('-explodecollections') - if len(options) > 0: + if options is not None and len(options) > 0: arguments.append(options) commands = [] @@ -143,4 +147,4 @@ def getConsoleCommands(self): return commands def commandName(self): - return "ogr2ogr" + return 'ogr2ogr' diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index feea4c7699ad..1c4db8c5790d 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -315,7 +315,7 @@ def exportVectorLayer(layer, supported=None): basename = removeInvalidChars(os.path.basename(layer.source())) if basename: if not basename.endswith("shp"): - basename = basename + ".shp" + basename = os.path.splitext(basename)[0] + ".shp" output = getTempFilenameInTempFolder(basename) else: output = getTempFilename("shp") From dff239c2416de5532d89b03be739a76937965ab5 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 10 Nov 2016 14:16:21 +0200 Subject: [PATCH 719/897] [processing] improve temp file names generation --- python/plugins/processing/tools/system.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/python/plugins/processing/tools/system.py b/python/plugins/processing/tools/system.py index 273e377301a7..7c6ad7e81a19 100644 --- a/python/plugins/processing/tools/system.py +++ b/python/plugins/processing/tools/system.py @@ -31,6 +31,7 @@ import time import sys import uuid +import math from qgis.PyQt.QtCore import QDir from qgis.core import QgsApplication @@ -81,13 +82,14 @@ def setTempOutput(out, alg): def getTempFilename(ext=None): - path = tempFolder() + tmpPath = tempFolder() + t = time.time() + m = math.floor(t) + uid = '{:8x}{:05x}'.format(m, int((t - m) * 1000000)) if ext is None: - filename = path + os.sep + str(time.time()) \ - + str(getNumExportedLayers()) + filename = os.path.join(tmpPath, '{}{}'.format(uid, getNumExportedLayers())) else: - filename = path + os.sep + str(time.time()) \ - + str(getNumExportedLayers()) + '.' + ext + filename = os.path.join(tmpPath, '{}{}.{}'.format(uid, getNumExportedLayers(), ext)) return filename From 426c5bef476896f44bdad7598d10a7478bfa2c85 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 11 Nov 2016 10:41:21 +0200 Subject: [PATCH 720/897] [processing] compare only geometry in tests --- .../tests/testdata/gdal_algorithm_tests.yaml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 32bbd8ab5845..70910cdd2f07 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -86,6 +86,9 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_lines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: gdalogr:buffervectors name: OGR basic polygon buffer @@ -101,6 +104,9 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_polys.gml type: vector + compare: + geometry: + precision: 7 - algorithm: gdalogr:buffervectors name: OGR polygon buffer with dissolve @@ -116,6 +122,10 @@ tests: OUTPUT_LAYER: name: expected/gdal/buffer_polys_dissolve.gml type: vector + compare: + geometry: + precision: 7 + - algorithm: gdalogr:createpointsalonglines name: OGR points along lines params: @@ -159,3 +169,6 @@ tests: OUTPUT_LAYER: name: expected/gdal/one_side_buffer.gml type: vector + compare: + geometry: + precision: 7 From 2287230f0fe49d1401594bb2d9f710a39dced707 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 11 Nov 2016 16:03:25 +0200 Subject: [PATCH 721/897] [processing] fix parameter definition in offset curve algorithm --- python/plugins/processing/algs/gdal/offsetcurve.py | 2 +- .../processing/tests/testdata/gdal_algorithm_tests.yaml | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/gdal/offsetcurve.py b/python/plugins/processing/algs/gdal/offsetcurve.py index 83fd4b32a160..9e0404600eae 100644 --- a/python/plugins/processing/algs/gdal/offsetcurve.py +++ b/python/plugins/processing/algs/gdal/offsetcurve.py @@ -63,7 +63,7 @@ def defineCharacteristics(self): 'geometry', optional=False)) self.addParameter(ParameterNumber(self.RADIUS, self.tr('Offset distance (positive value for left-sided and negative - for right-sided)'), - 0.0, 99999999.999999, 1000.0, + -99999999.999999, 99999999.999999, 1000.0, optional=False)) self.addParameter(ParameterBoolean(self.DISSOLVEALL, self.tr('Dissolve all results'), False)) diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 70910cdd2f07..2e2a07aa669f 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -153,6 +153,9 @@ tests: OUTPUT_LAYER: name: expected/gdal/offset_lines.gml type: vector + compare: + geometry: + precision: 7 - algorithm: gdalogr:singlesidedbufferforlines name: OGR one-side buffer for lines (left-handed) From 75bd622ccc582f0d81ea80206e1049c6afee4104 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 11 Nov 2016 17:25:45 +0200 Subject: [PATCH 722/897] [processing] restore and fix extraction of OGR layer names --- python/plugins/processing/tests/ToolsTest.py | 62 +++++++++++++++++- python/plugins/processing/tools/vector.py | 67 +++++++++++--------- 2 files changed, 96 insertions(+), 33 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index 46bde7e57ff0..2f3e6ddf31f2 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -25,17 +25,33 @@ __revision__ = '$Format:%H$' -from qgis.testing import start_app, unittest -from processing.tests.TestData import points -from processing.tools import vector +import os +import shutil +import tempfile + from qgis.core import (QgsVectorLayer, QgsFeatureRequest) +from qgis.testing import start_app, unittest + from processing.core.ProcessingConfig import ProcessingConfig +from processing.tests.TestData import testDataPath, points +from processing.tools import vector + +testDataPath = os.path.join(os.path.dirname(__file__), 'testdata') start_app() class VectorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cleanup_paths = [] + + @classmethod + def tearDownClass(cls): + for path in cls.cleanup_paths: + shutil.rmtree(path) + def testFeatures(self): ProcessingConfig.initialize() @@ -148,6 +164,46 @@ def testUniqueValues(self): ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value) + def testOgrLayerNameExtraction(self): + outdir = tempfile.mkdtemp() + self.cleanup_paths.append(outdir) + + def _copyFile(dst): + shutil.copyfile(os.path.join(testDataPath, 'custom', 'grass7', 'weighted.csv'), dst) + + # OGR provider - single layer + _copyFile(os.path.join(outdir, 'a.csv')) + name = vector.ogrLayerName(outdir) + self.assertEqual(name, 'a') + + # OGR provider - multiple layers + _copyFile(os.path.join(outdir, 'b.csv')) + name = vector.ogrLayerName(outdir + '|layerid=0') + self.assertEqual(name, 'b') + name = vector.ogrLayerName(outdir + '|layerid=1') + self.assertEqual(name, 'a') + + name = vector.ogrLayerName(outdir + '|layerid=2') + self.assertIsNone(name) + + # OGR provider - layername takes precedence + name = vector.ogrLayerName(outdir + '|layername=f') + self.assertEqual(name, 'f') + + name = vector.ogrLayerName(outdir + '|layerid=0|layername=f') + self.assertEqual(name, 'f') + + name = vector.ogrLayerName(outdir + '|layername=f|layerid=0') + self.assertEqual(name, 'f') + + # SQLiite provider + name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=') + self.assertEqual(name, 't') + + # PostgreSQL provider + name = vector.ogrLayerName('port=5493 sslmode=disable key=\'edge_id\' srid=0 type=LineString table="city_data"."edge" (geom) sql=') + self.assertEqual(name, 'city_data.edge') + if __name__ == '__main__': unittest.main() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 2b230bbe80e7..bf247091e0f2 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -40,6 +40,7 @@ import io import psycopg2 +from osgeo import ogr from qgis.PyQt.QtCore import QVariant, QSettings from qgis.core import (Qgis, QgsFields, QgsField, QgsGeometry, QgsRectangle, QgsWkbTypes, @@ -536,41 +537,47 @@ def ogrConnectionString(uri): return '"' + ogrstr + '"' -# The uri parameter is an URI from any QGIS provider, -# so could have different formats. -# Example formats: -# -# -- PostgreSQL provider -# port=5493 sslmode=disable key='edge_id' srid=0 type=LineString table="city_data"."edge" (geom) sql= -# -# -- Spatialite provider -# dbname='/tmp/x.sqlite' table="t" (geometry) sql=' -# -# -- OGR provider (single-layer directory) -# /tmp/x.gdb -# -# -- OGR provider (multi-layer directory) -# /tmp/x.gdb|layerid=1 -# -# -- OGR provider (multi-layer directory) -# /tmp/x.gdb|layername=thelayer -# def ogrLayerName(uri): - if 'host' in uri: - regex = re.compile('(table=")(.+?)(\.)(.+?)"') - r = regex.search(uri) - return '"' + r.groups()[1] + '.' + r.groups()[3] + '"' - elif 'dbname' in uri: - regex = re.compile('(table=")(.+?)"') - r = regex.search(uri) - return r.groups()[1] + if os.path.isfile(uri): + return os.path.basename(os.path.splitext(uri)[0]) + + if ' table=' in uri: + # table="schema"."table" + re_table_schema = re.compile(' table="([^"]*)"\."([^"]*)"') + r = re_table_schema.search(uri) + if r: + return r.groups()[0] + '.' + r.groups()[1] + # table="table" + re_table = re.compile(' table="([^"]*)"') + r = re_table.search(uri) + if r: + return r.groups()[0] elif 'layername' in uri: - regex = re.compile('(layername=)(.*)') + regex = re.compile('(layername=)([^|]*)') r = regex.search(uri) return r.groups()[1] - else: - return os.path.basename(os.path.splitext(uri)[0]) + fields = uri.split('|') + basePath = fields[0] + fields = fields[1:] + layerid = 0 + for f in fields: + if f.startswith('layername='): + return f.split('=')[1] + if f.startswith('layerid='): + layerid = int(f.split('=')[1]) + + ds = ogr.Open(basePath) + if not ds: + return None + + ly = ds.GetLayer(layerid) + if not ly: + return None + + name = ly.GetName() + ds = None + return name class VectorWriter(object): From fcc96de8a794237202c780063aa66452724f9c94 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 11 Nov 2016 17:28:13 +0200 Subject: [PATCH 723/897] [processing] fix indentation --- .../plugins/processing/tests/GdalAlgorithmsTest.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/tests/GdalAlgorithmsTest.py b/python/plugins/processing/tests/GdalAlgorithmsTest.py index 0b1f1f2e2370..1a6563eeb3c3 100644 --- a/python/plugins/processing/tests/GdalAlgorithmsTest.py +++ b/python/plugins/processing/tests/GdalAlgorithmsTest.py @@ -75,31 +75,31 @@ def test_getConnectionString(self): # NOTE: defaults are debatable, see # https://github.com/qgis/QGIS/pull/3607#issuecomment-253971020 self.assertEqual(obj.getConnectionString(), - "host=localhost port=5432 active_schema=public") + "host=localhost port=5432 active_schema=public") obj.setParameterValue('HOST', 'remote') self.assertEqual(obj.getConnectionString(), - "host=remote port=5432 active_schema=public") + "host=remote port=5432 active_schema=public") obj.setParameterValue('HOST', '') self.assertEqual(obj.getConnectionString(), - "port=5432 active_schema=public") + "port=5432 active_schema=public") obj.setParameterValue('PORT', '5555') self.assertEqual(obj.getConnectionString(), - "port=5555 active_schema=public") + "port=5555 active_schema=public") obj.setParameterValue('PORT', '') self.assertEqual(obj.getConnectionString(), - "active_schema=public") + "active_schema=public") obj.setParameterValue('USER', 'usr') self.assertEqual(obj.getConnectionString(), - "active_schema=public user=usr") + "active_schema=public user=usr") obj.setParameterValue('PASSWORD', 'pwd') self.assertEqual(obj.getConnectionString(), - "password=pwd active_schema=public user=usr") + "password=pwd active_schema=public user=usr") if __name__ == '__main__': From af16bbf5321eacc14bc3414c9f5a4c3c082a4f62 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 11 Nov 2016 17:31:12 +0200 Subject: [PATCH 724/897] [processing] don't print Processing version --- python/plugins/processing/tests/AlgorithmsTestBase.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/plugins/processing/tests/AlgorithmsTestBase.py b/python/plugins/processing/tests/AlgorithmsTestBase.py index 194049415a17..73f4fae66fb2 100644 --- a/python/plugins/processing/tests/AlgorithmsTestBase.py +++ b/python/plugins/processing/tests/AlgorithmsTestBase.py @@ -75,7 +75,6 @@ def test_algorithms(self): This is the main test function. All others will be executed based on the definitions in testdata/algorithm_tests.yaml """ ver = processing.version() - print("Processing {}.{}.{}".format(ver / 10000, ver / 100 % 100, ver % 100)) with open(os.path.join(processingTestDataPath(), self.test_definition_file()), 'r') as stream: algorithm_tests = yaml.load(stream) From 0589566e4b1f19e6adff248e7e7428b3567fa643 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 11 Nov 2016 17:41:13 +0200 Subject: [PATCH 725/897] [processing] mark buffer lines test as expected failure This test failed as result and expected WKT geometries differ only because of 0 vs. -0 in one coordinates pair --- .../plugins/processing/tests/testdata/gdal_algorithm_tests.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml index 2e2a07aa669f..46eb3e43782e 100644 --- a/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/gdal_algorithm_tests.yaml @@ -89,6 +89,8 @@ tests: compare: geometry: precision: 7 + expectedFailure: + - int(1) - algorithm: gdalogr:buffervectors name: OGR basic polygon buffer From d81533e05a79930839c0bcac26394b822dd02f0f Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Sat, 12 Nov 2016 13:31:11 +0200 Subject: [PATCH 726/897] fix failing test --- python/plugins/processing/tests/ToolsTest.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index 2f3e6ddf31f2..12496b4c184f 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -179,9 +179,9 @@ def _copyFile(dst): # OGR provider - multiple layers _copyFile(os.path.join(outdir, 'b.csv')) name = vector.ogrLayerName(outdir + '|layerid=0') - self.assertEqual(name, 'b') - name = vector.ogrLayerName(outdir + '|layerid=1') self.assertEqual(name, 'a') + name = vector.ogrLayerName(outdir + '|layerid=1') + self.assertEqual(name, 'b') name = vector.ogrLayerName(outdir + '|layerid=2') self.assertIsNone(name) From fbc12a8a8110be7b0750ce1cde6241592f947a65 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 19:44:59 +1000 Subject: [PATCH 727/897] Allow showing 'not set' in QgsProjectionSelectionWidget --- python/gui/qgsprojectionselectionwidget.sip | 25 +++- src/gui/qgsprojectionselectionwidget.cpp | 84 +++++++++++- src/gui/qgsprojectionselectionwidget.h | 28 +++- tests/src/python/CMakeLists.txt | 1 + .../test_qgsprojectionselectionwidget.py | 122 ++++++++++++++++++ 5 files changed, 254 insertions(+), 6 deletions(-) create mode 100644 tests/src/python/test_qgsprojectionselectionwidget.py diff --git a/python/gui/qgsprojectionselectionwidget.sip b/python/gui/qgsprojectionselectionwidget.sip index d8b86d033287..8af369d526f2 100644 --- a/python/gui/qgsprojectionselectionwidget.sip +++ b/python/gui/qgsprojectionselectionwidget.sip @@ -20,7 +20,8 @@ class QgsProjectionSelectionWidget : QWidget ProjectCrs, /*!< current project CRS (if OTF reprojection enabled) */ CurrentCrs, /*!< current user selected CRS */ DefaultCrs, /*!< global default QGIS CRS */ - RecentCrs /*!< recently used CRS */ + RecentCrs, //!< Recently used CRS + CrsNotSet, //!< Not set (hidden by default) }; explicit QgsProjectionSelectionWidget( QWidget *parent /TransferThis/ = 0 ); @@ -39,15 +40,37 @@ class QgsProjectionSelectionWidget : QWidget /** Sets whether a predefined CRS option should be shown in the widget. * @param option CRS option to show/hide * @param visible whether the option should be shown + * @see optionVisible() */ void setOptionVisible( const CrsOption option, const bool visible ); + + /** + * Returns whether the specified CRS option is visible in the widget. + * @note added in QGIS 3.0 + * @see setOptionVisible() + */ + bool optionVisible( CrsOption option ) const; + + /** + * Sets the text to show for the not set option. Note that this option is not shown + * by default and must be set visible by calling setOptionVisible(). + * @note added in QGIS 3.0 + */ + void setNotSetText( const QString& text ); + signals: /** Emitted when the selected CRS is changed */ void crsChanged( const QgsCoordinateReferenceSystem& ); + /** + * Emitted when the not set option is selected. + * @note added in QGIS 3.0 + */ + void cleared(); + public slots: /** Sets the current CRS for the widget diff --git a/src/gui/qgsprojectionselectionwidget.cpp b/src/gui/qgsprojectionselectionwidget.cpp index 3e28f0655ef9..ae6f2991dde6 100644 --- a/src/gui/qgsprojectionselectionwidget.cpp +++ b/src/gui/qgsprojectionselectionwidget.cpp @@ -88,6 +88,8 @@ QgsCoordinateReferenceSystem QgsProjectionSelectionWidget::crs() const QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromSrsId( srsid ); return crs; } + case QgsProjectionSelectionWidget::CrsNotSet: + return QgsCoordinateReferenceSystem(); } return mCrs; } @@ -117,18 +119,55 @@ void QgsProjectionSelectionWidget::setOptionVisible( const QgsProjectionSelectio return; } case QgsProjectionSelectionWidget::CurrentCrs: + { + addCurrentCrsOption(); + return; + } case QgsProjectionSelectionWidget::RecentCrs: - //current/recently used CRS option cannot be readded + //recently used CRS option cannot be readded + return; + case QgsProjectionSelectionWidget::CrsNotSet: + { + addNotSetOption(); + + if ( optionVisible( CurrentCrs ) && !mCrs.isValid() ) + { + // hide invalid option if not set option is shown + setOptionVisible( CurrentCrs, false ); + } + return; + } } } else if ( !visible && optionIndex >= 0 ) { //remove CRS option mCrsComboBox->removeItem( optionIndex ); + + if ( option == CrsNotSet ) + { + setOptionVisible( CurrentCrs, true ); + } + } +} + +void QgsProjectionSelectionWidget::setNotSetText( const QString& text ) +{ + mNotSetText = text; + int optionIndex = mCrsComboBox->findData( CrsNotSet ); + if ( optionIndex >= 0 ) + { + mCrsComboBox->setItemText( optionIndex, mNotSetText ); } } +bool QgsProjectionSelectionWidget::optionVisible( QgsProjectionSelectionWidget::CrsOption option ) const +{ + int optionIndex = mCrsComboBox->findData( option ); + return optionIndex >= 0; +} + void QgsProjectionSelectionWidget::selectCrs() { //find out crs id of current proj4 string @@ -152,6 +191,13 @@ void QgsProjectionSelectionWidget::selectCrs() } } +void QgsProjectionSelectionWidget::addNotSetOption() +{ + mCrsComboBox->insertItem( 0, mNotSetText, QgsProjectionSelectionWidget::CrsNotSet ); + if ( !mCrs.isValid() ) + whileBlocking( mCrsComboBox )->setCurrentIndex( 0 ); +} + void QgsProjectionSelectionWidget::comboIndexChanged( int idx ) { switch (( CrsOption )mCrsComboBox->itemData( idx ).toInt() ) @@ -175,6 +221,9 @@ void QgsProjectionSelectionWidget::comboIndexChanged( int idx ) emit crsChanged( crs ); return; } + case QgsProjectionSelectionWidget::CrsNotSet: + emit cleared(); + return; } } @@ -182,16 +231,28 @@ void QgsProjectionSelectionWidget::setCrs( const QgsCoordinateReferenceSystem& c { if ( crs.isValid() ) { + if ( !optionVisible( QgsProjectionSelectionWidget::CurrentCrs ) ) + setOptionVisible( QgsProjectionSelectionWidget::CurrentCrs, true ); mCrsComboBox->setItemText( mCrsComboBox->findData( QgsProjectionSelectionWidget::CurrentCrs ), - tr( "Selected CRS (%1, %2)" ).arg( crs.authid(), crs.description() ) ); + currentCrsOptionText( crs ) ); mCrsComboBox->blockSignals( true ); mCrsComboBox->setCurrentIndex( mCrsComboBox->findData( QgsProjectionSelectionWidget::CurrentCrs ) ); mCrsComboBox->blockSignals( false ); } else { - mCrsComboBox->setItemText( mCrsComboBox->findData( QgsProjectionSelectionWidget::CurrentCrs ), - tr( "invalid projection" ) ); + int crsNotSetIndex = mCrsComboBox->findData( QgsProjectionSelectionWidget::CrsNotSet ); + if ( crsNotSetIndex >= 0 ) + { + mCrsComboBox->blockSignals( true ); + mCrsComboBox->setCurrentIndex( crsNotSetIndex ); + mCrsComboBox->blockSignals( false ); + } + else + { + mCrsComboBox->setItemText( mCrsComboBox->findData( QgsProjectionSelectionWidget::CurrentCrs ), + currentCrsOptionText( crs ) ); + } } mCrs = crs; } @@ -233,6 +294,21 @@ void QgsProjectionSelectionWidget::addDefaultCrsOption() mCrsComboBox->addItem( tr( "Default CRS (%1 - %2)" ).arg( mDefaultCrs.authid(), mDefaultCrs.description() ), QgsProjectionSelectionWidget::DefaultCrs ); } +void QgsProjectionSelectionWidget::addCurrentCrsOption() +{ + int index = optionVisible( CrsNotSet ) ? 1 : 0; + mCrsComboBox->insertItem( index, currentCrsOptionText( mCrs ), QgsProjectionSelectionWidget::CurrentCrs ); + +} + +QString QgsProjectionSelectionWidget::currentCrsOptionText( const QgsCoordinateReferenceSystem& crs ) const +{ + if ( crs.isValid() ) + return tr( "Selected CRS (%1, %2)" ).arg( crs.authid(), crs.description() ); + else + return tr( "invalid projection" ); +} + void QgsProjectionSelectionWidget::addRecentCrs() { QStringList recentProjections = QgsCoordinateReferenceSystem::recentProjections(); diff --git a/src/gui/qgsprojectionselectionwidget.h b/src/gui/qgsprojectionselectionwidget.h index 25019b5d7913..8680db18259c 100644 --- a/src/gui/qgsprojectionselectionwidget.h +++ b/src/gui/qgsprojectionselectionwidget.h @@ -45,7 +45,8 @@ class GUI_EXPORT QgsProjectionSelectionWidget : public QWidget ProjectCrs, //!< Current project CRS (if OTF reprojection enabled) CurrentCrs, //!< Current user selected CRS DefaultCrs, //!< Global default QGIS CRS - RecentCrs //!< Recently used CRS + RecentCrs, //!< Recently used CRS + CrsNotSet, //!< Not set (hidden by default) }; explicit QgsProjectionSelectionWidget( QWidget *parent = nullptr ); @@ -64,15 +65,36 @@ class GUI_EXPORT QgsProjectionSelectionWidget : public QWidget /** Sets whether a predefined CRS option should be shown in the widget. * @param option CRS option to show/hide * @param visible whether the option should be shown + * @see optionVisible() */ void setOptionVisible( const CrsOption option, const bool visible ); + /** + * Returns whether the specified CRS option is visible in the widget. + * @note added in QGIS 3.0 + * @see setOptionVisible() + */ + bool optionVisible( CrsOption option ) const; + + /** + * Sets the text to show for the not set option. Note that this option is not shown + * by default and must be set visible by calling setOptionVisible(). + * @note added in QGIS 3.0 + */ + void setNotSetText( const QString& text ); + signals: /** Emitted when the selected CRS is changed */ void crsChanged( const QgsCoordinateReferenceSystem& ); + /** + * Emitted when the not set option is selected. + * @note added in QGIS 3.0 + */ + void cleared(); + public slots: /** Sets the current CRS for the widget @@ -99,9 +121,13 @@ class GUI_EXPORT QgsProjectionSelectionWidget : public QWidget QComboBox* mCrsComboBox; QToolButton* mButton; QgsGenericProjectionSelector* mDialog; + QString mNotSetText; + void addNotSetOption(); void addProjectCrsOption(); void addDefaultCrsOption(); + void addCurrentCrsOption(); + QString currentCrsOptionText( const QgsCoordinateReferenceSystem& crs ) const; void addRecentCrs(); bool crsIsShown( const long srsid ) const; diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 7a3ad5d080d6..918a8a2da08b 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -74,6 +74,7 @@ ADD_PYTHON_TEST(PyQgsPanelWidgetStack test_qgspanelwidgetstack.py) ADD_PYTHON_TEST(PyQgsPoint test_qgspoint.py) ADD_PYTHON_TEST(PyQgsPointClusterRenderer test_qgspointclusterrenderer.py) ADD_PYTHON_TEST(PyQgsPointDisplacementRenderer test_qgspointdisplacementrenderer.py) +ADD_PYTHON_TEST(PyQgsProjectionSelectionWidget test_qgsprojectionselectionwidget.py) ADD_PYTHON_TEST(PyQgsRangeWidgets test_qgsrangewidgets.py) ADD_PYTHON_TEST(PyQgsRasterFileWriter test_qgsrasterfilewriter.py) ADD_PYTHON_TEST(PyQgsRasterLayer test_qgsrasterlayer.py) diff --git a/tests/src/python/test_qgsprojectionselectionwidget.py b/tests/src/python/test_qgsprojectionselectionwidget.py new file mode 100644 index 000000000000..1095342d4f1e --- /dev/null +++ b/tests/src/python/test_qgsprojectionselectionwidget.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsProjectionSelectionWidget. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '12/11/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +from qgis.gui import QgsProjectionSelectionWidget +from qgis.core import QgsCoordinateReferenceSystem, QgsProject +from qgis.testing import start_app, unittest +from qgis.PyQt.QtGui import QColor +start_app() + + +class TestQgsProjectionSelectionWidget(unittest.TestCase): + + def testShowingHiding(self): + """ test showing and hiding options """ + w = QgsProjectionSelectionWidget() + + # layer crs + w.setOptionVisible(QgsProjectionSelectionWidget.LayerCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.LayerCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.LayerCrs, True) + # should still be hidden, because layer crs not set + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.LayerCrs)) + w.setLayerCrs(QgsCoordinateReferenceSystem('EPSG:3111')) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.LayerCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.LayerCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.LayerCrs)) + + # project crs + w.setOptionVisible(QgsProjectionSelectionWidget.ProjectCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.ProjectCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.ProjectCrs, True) + # should still be hidden, because project crs was not set + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.ProjectCrs)) + QgsProject.instance().setCrs(QgsCoordinateReferenceSystem('EPSG:3113')) + w = QgsProjectionSelectionWidget() + w.setOptionVisible(QgsProjectionSelectionWidget.ProjectCrs, True) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.ProjectCrs)) + # should still be hidden, because otf reprojection not active + QgsProject.instance().writeEntry("SpatialRefSys", "/ProjectionsEnabled", 1) + w = QgsProjectionSelectionWidget() + w.setOptionVisible(QgsProjectionSelectionWidget.ProjectCrs, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.ProjectCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.ProjectCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.ProjectCrs)) + + # default crs + w.setOptionVisible(QgsProjectionSelectionWidget.DefaultCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.DefaultCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.DefaultCrs, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.DefaultCrs)) + + # current crs + w = QgsProjectionSelectionWidget() + w.setOptionVisible(QgsProjectionSelectionWidget.CurrentCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.CurrentCrs, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + + w = QgsProjectionSelectionWidget() + w.setCrs(QgsCoordinateReferenceSystem('EPSG:3111')) + w.setOptionVisible(QgsProjectionSelectionWidget.CurrentCrs, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + w.setOptionVisible(QgsProjectionSelectionWidget.CurrentCrs, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + + # not set + w = QgsProjectionSelectionWidget() + w.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + w.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + w.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + + def testShowingNotSetOption(self): + """ test showing the not set option """ + + w = QgsProjectionSelectionWidget() + # start with an invalid CRS + w.setCrs(QgsCoordinateReferenceSystem()) + # add the not-set option + w.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + # current crs (which would show "invalid") should be hidden + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + # hide not-set option + w.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, False) + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + # and now current crs option ('invalid') should be reshown + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + + # repeat with a slightly different workflow + w = QgsProjectionSelectionWidget() + # start with an invalid CRS + w.setCrs(QgsCoordinateReferenceSystem()) + # add the not-set option + w.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + # current crs (which would show "invalid") should be hidden + self.assertFalse(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + # now set a current crs + w.setCrs(QgsCoordinateReferenceSystem('EPSG:3111')) + # both current and not set options should be shown + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CurrentCrs)) + self.assertTrue(w.optionVisible(QgsProjectionSelectionWidget.CrsNotSet)) + + +if __name__ == '__main__': + unittest.main() From 3ef7b3b7eb2f6a56ec729ef256c5594949690d52 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 19:46:42 +1000 Subject: [PATCH 728/897] [processing] Use standard QGIS projection selection widget for CRS params --- python/plugins/processing/algs/gdal/warp.py | 3 +- .../processing/algs/qgis/ReprojectLayer.py | 9 +++ .../processing/gui/CrsSelectionPanel.py | 76 ------------------- python/plugins/processing/gui/wrappers.py | 26 ++++--- .../ModelerParameterDefinitionDialog.py | 14 ++-- 5 files changed, 36 insertions(+), 92 deletions(-) delete mode 100644 python/plugins/processing/gui/CrsSelectionPanel.py diff --git a/python/plugins/processing/algs/gdal/warp.py b/python/plugins/processing/algs/gdal/warp.py index a21c0225c624..f38b39fbeb56 100644 --- a/python/plugins/processing/algs/gdal/warp.py +++ b/python/plugins/processing/algs/gdal/warp.py @@ -75,11 +75,12 @@ def getIcon(self): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Warp (reproject)') self.group, self.i18n_group = self.trAlgorithm('[GDAL] Projections') + self.tags = self.tr('transform,reproject,crs,srs') self.addParameter(ParameterRaster(self.INPUT, self.tr('Input layer'), False)) self.addParameter(ParameterCrs(self.SOURCE_SRS, self.tr('Source SRS'), '', optional=True)) self.addParameter(ParameterCrs(self.DEST_SRS, - self.tr('Destination SRS'), '')) + self.tr('Destination SRS'), 'EPSG:4326')) self.addParameter(ParameterString(self.NO_DATA, self.tr("Nodata value, leave blank to take the nodata value from input"), '', optional=True)) diff --git a/python/plugins/processing/algs/qgis/ReprojectLayer.py b/python/plugins/processing/algs/qgis/ReprojectLayer.py index e14ee6f16e4e..c10affda74a1 100644 --- a/python/plugins/processing/algs/qgis/ReprojectLayer.py +++ b/python/plugins/processing/algs/qgis/ReprojectLayer.py @@ -25,12 +25,17 @@ __revision__ = '$Format:%H$' +import os + from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsFeature from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterCrs from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector +from qgis.PyQt.QtGui import QIcon + +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] class ReprojectLayer(GeoAlgorithm): @@ -39,9 +44,13 @@ class ReprojectLayer(GeoAlgorithm): TARGET_CRS = 'TARGET_CRS' OUTPUT = 'OUTPUT' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'warp.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Reproject layer') self.group, self.i18n_group = self.trAlgorithm('Vector general tools') + self.tags = self.tr('transform,reproject,crs,srs,warp') self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'))) diff --git a/python/plugins/processing/gui/CrsSelectionPanel.py b/python/plugins/processing/gui/CrsSelectionPanel.py deleted file mode 100644 index 854c30d08ee4..000000000000 --- a/python/plugins/processing/gui/CrsSelectionPanel.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - CrsSelectionPanel.py - --------------------- - Date : August 2012 - Copyright : (C) 2012 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Victor Olaya' -__date__ = 'August 2012' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -import os - -from qgis.PyQt import uic - -from qgis.core import QgsCoordinateReferenceSystem -from qgis.gui import QgsGenericProjectionSelector - -pluginPath = os.path.split(os.path.dirname(__file__))[0] -WIDGET, BASE = uic.loadUiType( - os.path.join(pluginPath, 'ui', 'widgetBaseSelector.ui')) - - -class CrsSelectionPanel(BASE, WIDGET): - - def __init__(self, default='EPSG:4326'): - super(CrsSelectionPanel, self).__init__(None) - self.setupUi(self) - - self.leText.setEnabled(False) - - self.btnSelect.clicked.connect(self.browseCRS) - - # TODO: Default should be removed - self.crs = default - self.updateText() - - def setAuthId(self, authid): - self.crs = authid - self.updateText() - - def browseCRS(self): - selector = QgsGenericProjectionSelector() - selector.setSelectedAuthId(self.crs) - if selector.exec_(): - authId = selector.selectedAuthId() - if authId.upper().startswith("EPSG:"): - self.crs = authId - else: - proj = QgsCoordinateReferenceSystem() - proj.createFromSrsId(selector.selectedCrsId()) - self.crs = proj.toProj4() - self.updateText() - - def updateText(self): - if self.crs is not None: - self.leText.setText(self.crs) - - def getValue(self): - return self.crs diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 8cc56236ace3..bc38a2329a67 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -36,13 +36,12 @@ from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit -from qgis.gui import QgsFieldExpressionWidget, QgsExpressionLineEdit +from qgis.gui import QgsFieldExpressionWidget, QgsExpressionLineEdit, QgsProjectionSelectionWidget from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant from processing.gui.NumberInputPanel import NumberInputPanel from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel from processing.modeler.MultilineTextPanel import MultilineTextPanel -from processing.gui.CrsSelectionPanel import CrsSelectionPanel from processing.gui.PointSelectionPanel import PointSelectionPanel from processing.core.parameters import (ParameterBoolean, ParameterPoint, @@ -222,23 +221,32 @@ def createWidget(self): widget.setEditText(self.param.default) return widget else: - return CrsSelectionPanel() + + widget = QgsProjectionSelectionWidget() + if self.param.optional: + widget.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) + + if self.param.default: + crs = QgsCoordinateReferenceSystem(self.param.default) + widget.setCrs(crs) + + return widget def setValue(self, value): if self.dialogType == DIALOG_MODELER: self.setComboValue(value) else: - if isinstance(value, str): # authId - self.widget.crs = value - else: - self.widget.crs = QgsCoordinateReferenceSystem(value).authid() - self.widget.updateText() + self.widget.setCrs(QgsCoordinateReferenceSystem(value)) def value(self): if self.dialogType == DIALOG_MODELER: return self.comboValue() else: - return self.widget.getValue() + crs = self.widget.crs() + if crs.isValid(): + return self.widget.crs().authid() + else: + return None class ExtentWidgetWrapper(WidgetWrapper): diff --git a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py index 93dc8b727d6d..898970180359 100644 --- a/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py +++ b/python/plugins/processing/modeler/ModelerParameterDefinitionDialog.py @@ -28,7 +28,8 @@ import math -from qgis.gui import QgsExpressionLineEdit +from qgis.gui import QgsExpressionLineEdit, QgsProjectionSelectionWidget +from qgis.core import QgsCoordinateReferenceSystem from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtWidgets import (QDialog, QVBoxLayout, @@ -54,7 +55,6 @@ ParameterFile, ParameterPoint, ParameterCrs) -from processing.gui.CrsSelectionPanel import CrsSelectionPanel class ModelerParameterDefinitionDialog(QDialog): @@ -247,10 +247,12 @@ def setupUi(self): elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or isinstance(self.param, ParameterCrs)): self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) - self.defaultTextBox = CrsSelectionPanel('EPSG:4326') + self.selector = QgsProjectionSelectionWidget() if self.param is not None: - self.defaultTextBox.setAuthId(self.param.default) - self.verticalLayout.addWidget(self.defaultTextBox) + self.selector.setCrs(QgsCoordinateReferenceSystem(self.param.default)) + else: + self.selector.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) + self.verticalLayout.addWidget(self.selector) self.verticalLayout.addSpacing(20) self.requiredCheck = QCheckBox() @@ -361,7 +363,7 @@ def okPressed(self): str(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or isinstance(self.param, ParameterCrs)): - self.param = ParameterCrs(name, description, self.defaultTextBox.getValue()) + self.param = ParameterCrs(name, description, default=self.selector.crs().authid()) self.param.optional = not self.requiredCheck.isChecked() self.close() From f24cda44025eca0f0c9f8e270fcdefd60f8e7979 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 13 Nov 2016 18:44:08 +1000 Subject: [PATCH 729/897] [processing] Add unit tests for retrieving param from script code And fix number param retrieving from script code --- python/plugins/processing/core/parameters.py | 10 +- .../processing/tests/ParametersTest.py | 127 +++++++++++++++++- 2 files changed, 134 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 4e3126f9d3d8..63e4791d7cb6 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -863,14 +863,20 @@ def getAsScriptCode(self): if self.optional: param_type += 'optional ' param_type += 'number' - return '##' + self.name + '=' + param_type + str(self.default) + code = '##' + self.name + '=' + param_type + if self.default: + code += str(self.default) + return code @classmethod def fromScriptCode(self, line): + isOptional, name, definition = _splitParameterOptions(line) descName = _createDescriptiveName(name) if definition.lower().strip().startswith('number'): - default = definition.strip()[len('number') + 1:] or None + default = definition.strip()[len('number'):] or None + if default == 'None': + default = None return ParameterNumber(name, descName, default=default, optional=isOptional) def _evaluate(self, value): diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index a73b992ec7fd..fadcc0aad31d 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -41,7 +41,8 @@ ParameterVector, ParameterTableField, ParameterSelection, - ParameterExpression) + ParameterExpression, + getParameterFromString) from processing.tools import dataobjects from processing.tests.TestData import points2 @@ -96,6 +97,19 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, True) + def testScriptCode(self): + parameter = ParameterBoolean('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterBoolean)) + self.assertFalse(result.optional) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterBoolean)) + self.assertTrue(result.optional) + class ParameterCRSTest(unittest.TestCase): @@ -119,6 +133,18 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, 'EPSG:12003') + def testScriptCode(self): + parameter = ParameterCrs('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterCrs)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterCrs)) + self.assertTrue(result.optional) + class ParameterDataObjectTest(unittest.TestCase): @@ -161,6 +187,18 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, '1,2,3,4') + def testScriptCode(self): + parameter = ParameterExtent('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterExtent)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterExtent)) + self.assertTrue(result.optional) + class ParameterPointTest(unittest.TestCase): @@ -191,6 +229,18 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, '1,2') + def testScriptCode(self): + parameter = ParameterPoint('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterPoint)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterPoint)) + self.assertTrue(result.optional) + class ParameterSelectionTest(unittest.TestCase): @@ -283,6 +333,18 @@ def testGetValueAsCommandLineParameter(self): parameter.setValue('myFile.png') self.assertEqual(parameter.getValueAsCommandLineParameter(), '"myFile.png"') + def testScriptCode(self): + parameter = ParameterFile('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterFile)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterFile)) + self.assertTrue(result.optional) + class TestParameterFixedTable(unittest.TestCase): @@ -393,6 +455,18 @@ def testGetAsStringWhenVector(self): # TODO With Layer Name, instead of Layer object + def testScriptCode(self): + parameter = ParameterMultipleInput('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterMultipleInput)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterMultipleInput)) + self.assertTrue(result.optional) + class ParameterNumberTest(unittest.TestCase): @@ -447,6 +521,18 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, 5) + def testScriptCode(self): + parameter = ParameterNumber('myName', 'myDescription') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterNumber)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterNumber)) + self.assertTrue(result.optional) + class ParameterStringTest(unittest.TestCase): @@ -470,6 +556,18 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, 'check') + def testScriptCode(self): + parameter = ParameterString('myName', 'myDescription', default='test') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterString)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterString)) + self.assertTrue(result.optional) + class ParameterExpressionTest(unittest.TestCase): @@ -493,6 +591,18 @@ def testOptional(self): self.assertFalse(requiredParameter.setValue(None)) self.assertEqual(requiredParameter.value, 'check') + def testScriptCode(self): + parameter = ParameterExpression('myName', 'myDescription', default='test') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterExpression)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterExpression)) + self.assertTrue(result.optional) + class ParameterTableFieldTest(unittest.TestCase): @@ -505,6 +615,21 @@ def testOptional(self): parameter = ParameterTableField( 'myName', 'myDesc', parent_name, optional=True) + def testScriptCode(self): + parent_name = 'test_parent_layer' + test_data = points2() + test_layer = QgsVectorLayer(test_data, parent_name, 'ogr') + parameter = ParameterTableField( + 'myName', 'myDesc', parent_name) + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterTableField)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterTableField)) + self.assertTrue(result.optional) if __name__ == '__main__': unittest.main() From dbf6107b14347f2619e557f433de65bfbfee6bcf Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sun, 13 Nov 2016 19:05:28 +1000 Subject: [PATCH 730/897] [processing] Add button for projection selection dialog to Crs parameters in algorithm settings in modeler This makes it easier to pick static CRSes for the parameter, and also makes it obvious to users that they can use a fixed CRS parameter in their model (as opposed to one taken from a layer or input) --- python/plugins/processing/gui/wrappers.py | 68 ++++++++++++++++------- 1 file changed, 47 insertions(+), 21 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index bc38a2329a67..fe32b342a3d0 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -34,9 +34,9 @@ import os from functools import cmp_to_key -from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer -from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit -from qgis.gui import QgsFieldExpressionWidget, QgsExpressionLineEdit, QgsProjectionSelectionWidget +from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer, QgsApplication +from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit, QWidget, QHBoxLayout, QToolButton +from qgis.gui import QgsFieldExpressionWidget, QgsExpressionLineEdit, QgsProjectionSelectionWidget, QgsGenericProjectionSelector from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant from processing.gui.NumberInputPanel import NumberInputPanel @@ -107,14 +107,16 @@ def __init__(self, param, dialog, row=0, col=0): if param.default is not None: self.setValue(param.default) - def comboValue(self, validator=None): - idx = self.widget.findText(self.widget.currentText()) + def comboValue(self, validator=None, combobox=None): + if not combobox: + combobox = self.widget + idx = combobox.findText(combobox.currentText()) if idx < 0: - v = self.widget.currentText().strip() + v = combobox.currentText().strip() if validator is not None and not validator(v): raise InvalidParameterValue() return v - return self.widget.itemData(self.widget.currentIndex()) + return combobox.itemData(combobox.currentIndex()) def createWidget(self): pass @@ -122,21 +124,23 @@ def createWidget(self): def setValue(self, value): pass - def setComboValue(self, value): + def setComboValue(self, value, combobox=None): + if not combobox: + combobox = self.widget if isinstance(value, list): value = value[0] - values = [self.widget.itemData(i) for i in range(self.widget.count())] + values = [combobox.itemData(i) for i in range(combobox.count())] try: idx = values.index(value) - self.widget.setCurrentIndex(idx) + combobox.setCurrentIndex(idx) return except ValueError: pass - if self.widget.isEditable(): + if combobox.isEditable(): if value is not None: - self.widget.setEditText(str(value)) + combobox.setEditText(str(value)) else: - self.widget.setCurrentIndex(0) + combobox.setCurrentIndex(0) def value(self): pass @@ -206,19 +210,32 @@ class CrsWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType == DIALOG_MODELER: - widget = QComboBox() - widget.setEditable(True) + self.combo = QComboBox() + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(1) + layout.addWidget(self.combo) + btn = QToolButton() + btn.setIcon(QgsApplication.getThemeIcon("mActionSetProjection.svg")) + btn.setToolTip(self.tr("Select CRS")) + btn.clicked.connect(self.selectProjection) + layout.addWidget(btn) + + widget.setLayout(layout) + self.combo.setEditable(True) crss = self.dialog.getAvailableValuesOfType(ParameterCrs) for crs in crss: - widget.addItem(self.dialog.resolveValueDescription(crs), crs) + self.combo.addItem(self.dialog.resolveValueDescription(crs), crs) raster = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) vector = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) for r in raster: - widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(r), r) + self.combo.addItem("Crs of layer " + self.dialog.resolveValueDescription(r), r) for v in vector: - widget.addItem("Crs of layer " + self.dialog.resolveValueDescription(v), v) + self.combo.addItem("Crs of layer " + self.dialog.resolveValueDescription(v), v) if not self.param.default: - widget.setEditText(self.param.default) + self.combo.setEditText(self.param.default) return widget else: @@ -232,15 +249,24 @@ def createWidget(self): return widget + def selectProjection(self): + dialog = QgsGenericProjectionSelector(self.widget) + current_crs = QgsCoordinateReferenceSystem(self.combo.currentText()) + if current_crs.isValid(): + dialog.setSelectedCrsId(current_crs.srsid()) + + if dialog.exec_(): + self.setValue(dialog.selectedAuthId()) + def setValue(self, value): if self.dialogType == DIALOG_MODELER: - self.setComboValue(value) + self.setComboValue(value, self.combo) else: self.widget.setCrs(QgsCoordinateReferenceSystem(value)) def value(self): if self.dialogType == DIALOG_MODELER: - return self.comboValue() + return self.comboValue(combobox=self.combo) else: crs = self.widget.crs() if crs.isValid(): From d729951dcd13ed38d71ab2b850d1673bd794a569 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Sun, 13 Nov 2016 23:43:38 +0800 Subject: [PATCH 731/897] Remove caching of WKB from QgsGeometry (was kept just for compatibility) Also improves the API to export/import WKB as QByteArray --- doc/api_break.dox | 8 ++ python/core/geometry/qgsabstractgeometry.sip | 13 +-- python/core/geometry/qgscircularstring.sip | 5 +- python/core/geometry/qgscompoundcurve.sip | 5 +- python/core/geometry/qgscurvepolygon.sip | 5 +- python/core/geometry/qgsgeometry.sip | 30 ++---- .../core/geometry/qgsgeometrycollection.sip | 5 +- python/core/geometry/qgslinestring.sip | 5 +- python/core/geometry/qgspointv2.sip | 5 +- python/core/geometry/qgspolygon.sip | 5 +- .../algs/qgis/scripts/Fill_holes.py | 2 +- .../interpolation/qgsinterpolator.cpp | 3 +- .../interpolation/qgstininterpolator.cpp | 3 +- src/analysis/openstreetmap/qgsosmdatabase.cpp | 8 +- src/analysis/vector/qgsgeometryanalyzer.cpp | 6 +- src/core/geometry/qgsabstractgeometry.h | 13 +-- src/core/geometry/qgscircularstring.cpp | 20 ++-- src/core/geometry/qgscircularstring.h | 5 +- src/core/geometry/qgscompoundcurve.cpp | 36 +++---- src/core/geometry/qgscompoundcurve.h | 5 +- src/core/geometry/qgscurvepolygon.cpp | 48 ++++----- src/core/geometry/qgscurvepolygon.h | 5 +- src/core/geometry/qgsgeometry.cpp | 101 ++++-------------- src/core/geometry/qgsgeometry.h | 20 ++-- src/core/geometry/qgsgeometrycollection.cpp | 39 +++---- src/core/geometry/qgsgeometrycollection.h | 5 +- src/core/geometry/qgsgeometryfactory.cpp | 4 +- src/core/geometry/qgsgeometryfactory.h | 3 +- src/core/geometry/qgslinestring.cpp | 20 ++-- src/core/geometry/qgslinestring.h | 5 +- src/core/geometry/qgspointv2.cpp | 22 ++-- src/core/geometry/qgspointv2.h | 5 +- src/core/geometry/qgspolygon.cpp | 26 ++--- src/core/geometry/qgspolygon.h | 5 +- src/core/geometry/qgswkbptr.cpp | 15 +++ src/core/geometry/qgswkbptr.h | 10 ++ src/core/qgsogcutils.cpp | 5 +- src/core/qgspointlocator.cpp | 6 +- src/core/qgsvectorfilewriter.cpp | 6 +- src/providers/db2/qgsdb2provider.cpp | 4 +- src/providers/gpx/qgsgpxprovider.cpp | 3 +- src/providers/mssql/qgsmssqlprovider.cpp | 4 +- src/providers/ogr/qgsogrprovider.cpp | 15 +-- .../postgres/qgspostgresprovider.cpp | 7 +- .../spatialite/qgsspatialiteprovider.cpp | 8 +- src/providers/virtual/qgsvirtuallayerblob.cpp | 8 +- src/providers/wfs/qgswfsfeatureiterator.cpp | 7 +- src/providers/wfs/qgswfsshareddata.cpp | 12 +-- src/providers/wfs/qgswfsutils.cpp | 4 +- tests/src/core/testqgsfeature.cpp | 20 ++-- tests/src/core/testqgsgeometry.cpp | 100 +++++++---------- tests/src/python/test_provider_ogr_gpkg.py | 4 +- tests/src/python/test_qgsgeometry.py | 6 +- 53 files changed, 305 insertions(+), 434 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 67778e8faa7c..d5935f7ee1c1 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -318,6 +318,13 @@ QgsAnnotation {#qgis_api_break_3_0_QgsAnnotation} - mapPositionFixed() has been renamed to hasFixedMapPosition() +QgsAbstractGeometry {#qgis_api_break_3_0_QgsAbstractGeometry} +------------------- + +- asWkb() returns QByteArray instead of new raw pointer +- wkbSize() has been removed, use asWkb() to get length of returned QByteArray +- fromWkb() gets the WKB pointer passed by reference instead of value, so that caller may to find out where the parsing ended + QgsActionManager {#qgis_api_break_3_0_QgsActionManager} ---------------- @@ -836,6 +843,7 @@ QgsGeometry {#qgis_api_break_3_0_QgsGeometry} value instead of a pointer. The biggest impact with this change is that PyQGIS code should not compare a geometry result to None, but instead either use a boolean test (`if g.buffer(10):`) or explicitly use the isEmpty() method to determine if a geometry is valid. +- wkbSize() and asWkb() has been replaced by exportToWkb(). WKB representation is no longer cached within QgsGeometry - int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPoints - int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPointsV2 - static bool compare( const QgsPolyline& p1, const QgsPolyline& p2, double epsilon ) has been renamed to comparePolylines diff --git a/python/core/geometry/qgsabstractgeometry.sip b/python/core/geometry/qgsabstractgeometry.sip index 179adcf559ae..a48605dc5f8d 100644 --- a/python/core/geometry/qgsabstractgeometry.sip +++ b/python/core/geometry/qgsabstractgeometry.sip @@ -140,9 +140,10 @@ class QgsAbstractGeometry //import /** Sets the geometry from a WKB string. + * After successful read the wkb argument will be at the position where the reading has stopped. * @see fromWkt */ - virtual bool fromWkb( QgsConstWkbPtr wkb ) = 0; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) = 0; /** Sets the geometry from a WKT string. * @see fromWkb @@ -151,20 +152,14 @@ class QgsAbstractGeometry //export - /** Returns the size of the WKB representation of the geometry. - * @see asWkb - */ - virtual int wkbSize() const = 0; - /** Returns a WKB representation of the geometry. - * @param binarySize will be set to the size of the returned WKB string - * @see wkbSize * @see asWkt * @see asGML2 * @see asGML3 * @see asJSON + * @note added in 3.0 */ - virtual unsigned char* asWkb( int& binarySize ) const = 0; + virtual QByteArray asWkb() const = 0; /** Returns a WKT representation of the geometry. * @param precision number of decimal places for coordinates diff --git a/python/core/geometry/qgscircularstring.sip b/python/core/geometry/qgscircularstring.sip index 0358616466a9..dcba282e8e04 100644 --- a/python/core/geometry/qgscircularstring.sip +++ b/python/core/geometry/qgscircularstring.sip @@ -16,11 +16,10 @@ class QgsCircularString: public QgsCurve virtual QgsCircularString* clone() const /Factory/; virtual void clear(); - virtual bool fromWkb( QgsConstWkbPtr wkb ); + virtual bool fromWkb( QgsConstWkbPtr& wkb ); virtual bool fromWkt( const QString& wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; QString asWkt( int precision = 17 ) const; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/core/geometry/qgscompoundcurve.sip b/python/core/geometry/qgscompoundcurve.sip index 3418bf8c2101..4b73c7580cd8 100644 --- a/python/core/geometry/qgscompoundcurve.sip +++ b/python/core/geometry/qgscompoundcurve.sip @@ -18,11 +18,10 @@ class QgsCompoundCurve: public QgsCurve virtual QgsCompoundCurve* clone() const /Factory/; virtual void clear(); - virtual bool fromWkb( QgsConstWkbPtr wkb ); + virtual bool fromWkb( QgsConstWkbPtr& wkb ); virtual bool fromWkt( const QString& wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; QString asWkt( int precision = 17 ) const; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/core/geometry/qgscurvepolygon.sip b/python/core/geometry/qgscurvepolygon.sip index 8aea54587c3e..1ae09a87d190 100644 --- a/python/core/geometry/qgscurvepolygon.sip +++ b/python/core/geometry/qgscurvepolygon.sip @@ -15,11 +15,10 @@ class QgsCurvePolygon: public QgsSurface virtual QgsCurvePolygon* clone() const /Factory/; void clear(); - virtual bool fromWkb( QgsConstWkbPtr wkb ); + virtual bool fromWkb( QgsConstWkbPtr& wkb ); virtual bool fromWkt( const QString& wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; QString asWkt( int precision = 17 ) const; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index 90f62a466041..588b7f767b14 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -93,30 +93,15 @@ class QgsGeometry /** Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length. This class will take ownership of the buffer. + @note not available in python bindings */ - void fromWkb( unsigned char * wkb /Array/, int length /ArraySize/ ); -%MethodCode - // create copy of Python's string and pass it to fromWkb() - unsigned char * copy = new unsigned char[a1]; - memcpy(copy, a0, a1); - sipCpp->fromWkb(copy, a1); -%End + // void fromWkb( unsigned char *wkb, int length ); /** - Returns the buffer containing this geometry in WKB format. - You may wish to use in conjunction with wkbSize(). - @see wkbSize + * Set the geometry, feeding in the buffer containing OGC Well-Known Binary + * @note added in 3.0 */ - SIP_PYOBJECT asWkb(); -%MethodCode - sipRes = PyBytes_FromStringAndSize((const char *)sipCpp->asWkb(), sipCpp->wkbSize()); -%End - - /** - * Returns the size of the WKB in asWkb(). - * @see asWkb - */ - int wkbSize() const; + void fromWkb( const QByteArray& wkb ); /** Returns a geos geometry. QgsGeometry retains ownership of the geometry, so the returned object should not be deleted. * @param precision The precision of the grid to which to snap the geometry vertices. If 0, no snapping is performed. @@ -593,6 +578,11 @@ class QgsGeometry /** Returns an extruded version of this geometry. */ QgsGeometry extrude( double x, double y ); + /** Export the geometry to WKB + * @note added in 3.0 + */ + QByteArray exportToWkb() const; + /** Exports the geometry to WKT * @note precision parameter added in 2.4 * @return true in case of success and false else diff --git a/python/core/geometry/qgsgeometrycollection.sip b/python/core/geometry/qgsgeometrycollection.sip index 017aec6e680a..ae613cb9562d 100644 --- a/python/core/geometry/qgsgeometrycollection.sip +++ b/python/core/geometry/qgsgeometrycollection.sip @@ -55,10 +55,9 @@ class QgsGeometryCollection: public QgsAbstractGeometry virtual void draw( QPainter& p ) const; - bool fromWkb( QgsConstWkbPtr wkb ); + bool fromWkb( QgsConstWkbPtr& wkb ); virtual bool fromWkt( const QString& wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; QString asWkt( int precision = 17 ) const; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/core/geometry/qgslinestring.sip b/python/core/geometry/qgslinestring.sip index 3ed4b59d31e6..c2b817644091 100644 --- a/python/core/geometry/qgslinestring.sip +++ b/python/core/geometry/qgslinestring.sip @@ -107,11 +107,10 @@ class QgsLineString: public QgsCurve virtual QgsLineString* clone() const /Factory/; virtual void clear(); - virtual bool fromWkb( QgsConstWkbPtr wkb ); + virtual bool fromWkb( QgsConstWkbPtr& wkb ); virtual bool fromWkt( const QString& wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; QString asWkt( int precision = 17 ) const; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/core/geometry/qgspointv2.sip b/python/core/geometry/qgspointv2.sip index 5c774d47214b..58492d489df9 100644 --- a/python/core/geometry/qgspointv2.sip +++ b/python/core/geometry/qgspointv2.sip @@ -185,10 +185,9 @@ class QgsPointV2: public QgsAbstractGeometry virtual int dimension() const; virtual QgsPointV2* clone() const /Factory/; void clear(); - virtual bool fromWkb( QgsConstWkbPtr wkb ); + virtual bool fromWkb( QgsConstWkbPtr& wkb ); virtual bool fromWkt( const QString& wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; QString asWkt( int precision = 17 ) const; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/core/geometry/qgspolygon.sip b/python/core/geometry/qgspolygon.sip index dd4490820645..3f94285c06e7 100644 --- a/python/core/geometry/qgspolygon.sip +++ b/python/core/geometry/qgspolygon.sip @@ -14,12 +14,11 @@ class QgsPolygonV2: public QgsCurvePolygon virtual QgsPolygonV2* clone() const /Factory/; void clear(); - virtual bool fromWkb( QgsConstWkbPtr wkb ); + virtual bool fromWkb( QgsConstWkbPtr& wkb ); // inherited: bool fromWkt( const QString &wkt ); - int wkbSize() const; - unsigned char* asWkb( int& binarySize ) const; + QByteArray asWkb() const; // inherited: QString asWkt( int precision = 17 ) const; // inherited: QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; // inherited: QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/python/plugins/processing/algs/qgis/scripts/Fill_holes.py b/python/plugins/processing/algs/qgis/scripts/Fill_holes.py index b66fe155336d..44bbeb84585a 100644 --- a/python/plugins/processing/algs/qgis/scripts/Fill_holes.py +++ b/python/plugins/processing/algs/qgis/scripts/Fill_holes.py @@ -25,7 +25,7 @@ progress.setPercentage(int(100 * l / n)) l += 1 - g = loads(feat.geometry().asWkb()) + g = loads(feat.geometry().exportToWkb()) if g.geom_type == 'MultiPolygon': resg = [Polygon(p.exterior, diff --git a/src/analysis/interpolation/qgsinterpolator.cpp b/src/analysis/interpolation/qgsinterpolator.cpp index 7988afc73ce4..d11ac682ffb3 100644 --- a/src/analysis/interpolation/qgsinterpolator.cpp +++ b/src/analysis/interpolation/qgsinterpolator.cpp @@ -109,7 +109,8 @@ int QgsInterpolator::addVerticesToCache( const QgsGeometry& geom, bool zCoord, d return 1; bool hasZValue = false; - QgsConstWkbPtr currentWkbPtr( geom.asWkb(), geom.wkbSize() ); + QByteArray wkb( geom.exportToWkb() ); + QgsConstWkbPtr currentWkbPtr( wkb ); currentWkbPtr.readHeader(); vertexData theVertex; //the current vertex diff --git a/src/analysis/interpolation/qgstininterpolator.cpp b/src/analysis/interpolation/qgstininterpolator.cpp index 55c7e04ebb8c..3f996d68db1e 100644 --- a/src/analysis/interpolation/qgstininterpolator.cpp +++ b/src/analysis/interpolation/qgstininterpolator.cpp @@ -201,7 +201,8 @@ int QgsTINInterpolator::insertData( QgsFeature* f, bool zCoord, int attr, InputT //parse WKB. It is ugly, but we cannot use the methods with QgsPoint because they don't contain z-values for 25D types bool hasZValue = false; double x, y, z; - QgsConstWkbPtr currentWkbPtr( g.asWkb(), g.wkbSize() ); + QByteArray wkb( g.exportToWkb() ); + QgsConstWkbPtr currentWkbPtr( wkb ); currentWkbPtr.readHeader(); //maybe a structure or break line Line3D* line = nullptr; diff --git a/src/analysis/openstreetmap/qgsosmdatabase.cpp b/src/analysis/openstreetmap/qgsosmdatabase.cpp index 8eb2a04fe43c..2af9912c962a 100644 --- a/src/analysis/openstreetmap/qgsosmdatabase.cpp +++ b/src/analysis/openstreetmap/qgsosmdatabase.cpp @@ -423,7 +423,8 @@ void QgsOSMDatabase::exportSpatiaLiteNodes( const QString& tableName, const QStr sqlite3_bind_null( stmtInsert, ++col ); } - sqlite3_bind_blob( stmtInsert, ++col, geom.asWkb(), ( int ) geom.wkbSize(), SQLITE_STATIC ); + QByteArray wkb( geom.exportToWkb() ); + sqlite3_bind_blob( stmtInsert, ++col, wkb.constData(), wkb.length(), SQLITE_STATIC ); int insertRes = sqlite3_step( stmtInsert ); if ( insertRes != SQLITE_DONE ) @@ -504,7 +505,10 @@ void QgsOSMDatabase::exportSpatiaLiteWays( bool closed, const QString& tableName } if ( !geom.isEmpty() ) - sqlite3_bind_blob( stmtInsert, ++col, geom.asWkb(), ( int ) geom.wkbSize(), SQLITE_STATIC ); + { + QByteArray wkb( geom.exportToWkb() ); + sqlite3_bind_blob( stmtInsert, ++col, wkb.constData(), wkb.length(), SQLITE_STATIC ); + } else sqlite3_bind_null( stmtInsert, ++col ); diff --git a/src/analysis/vector/qgsgeometryanalyzer.cpp b/src/analysis/vector/qgsgeometryanalyzer.cpp index 2fc8aad7b6e8..44abaef62b21 100644 --- a/src/analysis/vector/qgsgeometryanalyzer.cpp +++ b/src/analysis/vector/qgsgeometryanalyzer.cpp @@ -1153,7 +1153,8 @@ QgsGeometry QgsGeometryAnalyzer::locateBetweenMeasures( double fromMeasure, doub QgsMultiPolyline resultGeom; //need to go with WKB and z coordinate until QgsGeometry supports M values - QgsConstWkbPtr wkbPtr( lineGeom.asWkb(), lineGeom.wkbSize() ); + QByteArray wkb( lineGeom.exportToWkb() ); + QgsConstWkbPtr wkbPtr( wkb ); wkbPtr.readHeader(); QgsWkbTypes::Type wkbType = lineGeom.wkbType(); @@ -1194,7 +1195,8 @@ QgsGeometry QgsGeometryAnalyzer::locateAlongMeasure( double measure, const QgsGe QgsMultiPoint resultGeom; //need to go with WKB and z coordinate until QgsGeometry supports M values - QgsConstWkbPtr wkbPtr( lineGeom.asWkb(), lineGeom.wkbSize() ); + QByteArray wkb( lineGeom.exportToWkb() ); + QgsConstWkbPtr wkbPtr( wkb ); QgsWkbTypes::Type wkbType = lineGeom.wkbType(); if ( wkbType != QgsWkbTypes::LineString25D && wkbType != QgsWkbTypes::MultiLineString25D ) diff --git a/src/core/geometry/qgsabstractgeometry.h b/src/core/geometry/qgsabstractgeometry.h index a88f6de87e84..599ba07ce570 100644 --- a/src/core/geometry/qgsabstractgeometry.h +++ b/src/core/geometry/qgsabstractgeometry.h @@ -125,9 +125,10 @@ class CORE_EXPORT QgsAbstractGeometry //import /** Sets the geometry from a WKB string. + * After successful read the wkb argument will be at the position where the reading has stopped. * @see fromWkt */ - virtual bool fromWkb( QgsConstWkbPtr wkb ) = 0; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) = 0; /** Sets the geometry from a WKT string. * @see fromWkb @@ -136,20 +137,14 @@ class CORE_EXPORT QgsAbstractGeometry //export - /** Returns the size of the WKB representation of the geometry. - * @see asWkb - */ - virtual int wkbSize() const = 0; - /** Returns a WKB representation of the geometry. - * @param binarySize will be set to the size of the returned WKB string - * @see wkbSize * @see asWkt * @see asGML2 * @see asGML3 * @see asJSON + * @note added in 3.0 */ - virtual unsigned char* asWkb( int& binarySize ) const = 0; + virtual QByteArray asWkb() const = 0; /** Returns a WKT representation of the geometry. * @param precision number of decimal places for coordinates diff --git a/src/core/geometry/qgscircularstring.cpp b/src/core/geometry/qgscircularstring.cpp index 7ce639877755..035018b77202 100644 --- a/src/core/geometry/qgscircularstring.cpp +++ b/src/core/geometry/qgscircularstring.cpp @@ -207,7 +207,7 @@ QgsPointSequence QgsCircularString::compassPointsOnSegment( double p1Angle, doub return pointList; } -bool QgsCircularString::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsCircularString::fromWkb( QgsConstWkbPtr& wkbPtr ) { if ( !wkbPtr ) return false; @@ -260,24 +260,20 @@ bool QgsCircularString::fromWkt( const QString& wkt ) return true; } -int QgsCircularString::wkbSize() const +QByteArray QgsCircularString::asWkb() const { - int size = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); - size += numPoints() * ( 2 + is3D() + isMeasure() ) * sizeof( double ); - return size; -} + int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + binarySize += numPoints() * ( 2 + is3D() + isMeasure() ) * sizeof( double ); -unsigned char* QgsCircularString::asWkb( int& binarySize ) const -{ - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkb( geomPtr, binarySize ); + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkb( wkbArray ); wkb << static_cast( QgsApplication::endian() ); wkb << static_cast( wkbType() ); QgsPointSequence pts; points( pts ); QgsGeometryUtils::pointsToWKB( wkb, pts, is3D(), isMeasure() ); - return geomPtr; + return wkbArray; } QString QgsCircularString::asWkt( int precision ) const diff --git a/src/core/geometry/qgscircularstring.h b/src/core/geometry/qgscircularstring.h index e37fa2b39da1..521d9016a136 100644 --- a/src/core/geometry/qgscircularstring.h +++ b/src/core/geometry/qgscircularstring.h @@ -41,11 +41,10 @@ class CORE_EXPORT QgsCircularString: public QgsCurve virtual QgsCircularString* clone() const override; virtual void clear() override; - virtual bool fromWkb( QgsConstWkbPtr wkb ) override; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) override; virtual bool fromWkt( const QString& wkt ) override; - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; QString asWkt( int precision = 17 ) const override; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; diff --git a/src/core/geometry/qgscompoundcurve.cpp b/src/core/geometry/qgscompoundcurve.cpp index 5e6f26734ddf..668617fb28e7 100644 --- a/src/core/geometry/qgscompoundcurve.cpp +++ b/src/core/geometry/qgscompoundcurve.cpp @@ -101,7 +101,7 @@ QgsRectangle QgsCompoundCurve::calculateBoundingBox() const return bbox; } -bool QgsCompoundCurve::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsCompoundCurve::fromWkb( QgsConstWkbPtr& wkbPtr ) { clear(); if ( !wkbPtr ) @@ -119,7 +119,6 @@ bool QgsCompoundCurve::fromWkb( QgsConstWkbPtr wkbPtr ) int nCurves; wkbPtr >> nCurves; QgsCurve* currentCurve = nullptr; - int currentCurveSize = 0; for ( int i = 0; i < nCurves; ++i ) { QgsWkbTypes::Type curveType = wkbPtr.readHeader(); @@ -136,10 +135,8 @@ bool QgsCompoundCurve::fromWkb( QgsConstWkbPtr wkbPtr ) { return false; } - currentCurve->fromWkb( wkbPtr ); - currentCurveSize = currentCurve->wkbSize(); + currentCurve->fromWkb( wkbPtr ); // also updates wkbPtr mCurves.append( currentCurve ); - wkbPtr += currentCurveSize; } return true; } @@ -195,33 +192,28 @@ bool QgsCompoundCurve::fromWkt( const QString& wkt ) return true; } -int QgsCompoundCurve::wkbSize() const +QByteArray QgsCompoundCurve::asWkb() const { - int size = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + QList wkbForCurves; Q_FOREACH ( const QgsCurve *curve, mCurves ) { - size += curve->wkbSize(); + QByteArray wkbForCurve = curve->asWkb(); + binarySize += wkbForCurve.length(); + wkbForCurves << wkbForCurve; } - return size; -} -unsigned char* QgsCompoundCurve::asWkb( int& binarySize ) const -{ - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkb( geomPtr, binarySize ); + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkb( wkbArray ); wkb << static_cast( QgsApplication::endian() ); wkb << static_cast( wkbType() ); wkb << static_cast( mCurves.size() ); - Q_FOREACH ( const QgsCurve* curve, mCurves ) + Q_FOREACH ( const QByteArray& wkbForCurve, wkbForCurves ) { - int curveWkbLen = 0; - unsigned char* curveWkb = curve->asWkb( curveWkbLen ); - memcpy( wkb, curveWkb, curveWkbLen ); - wkb += curveWkbLen; - delete[] curveWkb; + wkb << wkbForCurve; } - return geomPtr; + return wkbArray; } QString QgsCompoundCurve::asWkt( int precision ) const diff --git a/src/core/geometry/qgscompoundcurve.h b/src/core/geometry/qgscompoundcurve.h index a193a4fde145..a2f0ac15e1a1 100644 --- a/src/core/geometry/qgscompoundcurve.h +++ b/src/core/geometry/qgscompoundcurve.h @@ -42,11 +42,10 @@ class CORE_EXPORT QgsCompoundCurve: public QgsCurve virtual QgsCompoundCurve* clone() const override; virtual void clear() override; - virtual bool fromWkb( QgsConstWkbPtr wkb ) override; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) override; virtual bool fromWkt( const QString& wkt ) override; - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; QString asWkt( int precision = 17 ) const override; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; diff --git a/src/core/geometry/qgscurvepolygon.cpp b/src/core/geometry/qgscurvepolygon.cpp index cbae4223af69..60e335ab3bf0 100644 --- a/src/core/geometry/qgscurvepolygon.cpp +++ b/src/core/geometry/qgscurvepolygon.cpp @@ -88,7 +88,7 @@ void QgsCurvePolygon::clear() } -bool QgsCurvePolygon::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsCurvePolygon::fromWkb( QgsConstWkbPtr& wkbPtr ) { clear(); if ( !wkbPtr ) @@ -106,7 +106,6 @@ bool QgsCurvePolygon::fromWkb( QgsConstWkbPtr wkbPtr ) int nRings; wkbPtr >> nRings; QgsCurve* currentCurve = nullptr; - int currentCurveSize = 0; for ( int i = 0; i < nRings; ++i ) { QgsWkbTypes::Type curveType = wkbPtr.readHeader(); @@ -128,8 +127,7 @@ bool QgsCurvePolygon::fromWkb( QgsConstWkbPtr wkbPtr ) { return false; } - currentCurve->fromWkb( wkbPtr ); - currentCurveSize = currentCurve->wkbSize(); + currentCurve->fromWkb( wkbPtr ); // also updates wkbPtr if ( i == 0 ) { mExteriorRing = currentCurve; @@ -138,7 +136,6 @@ bool QgsCurvePolygon::fromWkb( QgsConstWkbPtr wkbPtr ) { mInteriorRings.append( currentCurve ); } - wkbPtr += currentCurveSize; } return true; @@ -222,43 +219,34 @@ QgsRectangle QgsCurvePolygon::calculateBoundingBox() const return QgsRectangle(); } -int QgsCurvePolygon::wkbSize() const +QByteArray QgsCurvePolygon::asWkb() const { - int size = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + QList wkbForRings; if ( mExteriorRing ) { - size += mExteriorRing->wkbSize(); + QByteArray wkb( mExteriorRing->asWkb() ); + binarySize += wkb.length(); + wkbForRings << wkb; } Q_FOREACH ( const QgsCurve* curve, mInteriorRings ) { - size += curve->wkbSize(); + QByteArray wkb( curve->asWkb() ); + binarySize += wkb.length(); + wkbForRings << wkb; } - return size; -} -unsigned char* QgsCurvePolygon::asWkb( int& binarySize ) const -{ - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkbPtr( geomPtr, binarySize ); + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkbPtr( wkbArray ); wkbPtr << static_cast( QgsApplication::endian() ); wkbPtr << static_cast( wkbType() ); - wkbPtr << static_cast(( nullptr != mExteriorRing ) + mInteriorRings.size() ); - if ( mExteriorRing ) - { - int curveWkbLen = 0; - unsigned char *ringWkb = mExteriorRing->asWkb( curveWkbLen ); - memcpy( wkbPtr, ringWkb, curveWkbLen ); - wkbPtr += curveWkbLen; - } - Q_FOREACH ( const QgsCurve* curve, mInteriorRings ) + wkbPtr << static_cast( wkbForRings.count() ); + Q_FOREACH ( const QByteArray& wkb, wkbForRings ) { - int curveWkbLen = 0; - unsigned char *ringWkb = curve->asWkb( curveWkbLen ); - memcpy( wkbPtr, ringWkb, curveWkbLen ); - wkbPtr += curveWkbLen; + wkbPtr << wkb; } - return geomPtr; + return wkbArray; } QString QgsCurvePolygon::asWkt( int precision ) const diff --git a/src/core/geometry/qgscurvepolygon.h b/src/core/geometry/qgscurvepolygon.h index 9bec8122d8d0..bf921213f41c 100644 --- a/src/core/geometry/qgscurvepolygon.h +++ b/src/core/geometry/qgscurvepolygon.h @@ -41,11 +41,10 @@ class CORE_EXPORT QgsCurvePolygon: public QgsSurface virtual QgsCurvePolygon* clone() const override; void clear() override; - virtual bool fromWkb( QgsConstWkbPtr wkb ) override; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) override; virtual bool fromWkt( const QString& wkt ) override; - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; QString asWkt( int precision = 17 ) const override; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index 4595014f6842..91f8f582bfe1 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -54,12 +54,10 @@ email : morb at ozemail dot com dot au struct QgsGeometryPrivate { - QgsGeometryPrivate(): ref( 1 ), geometry( nullptr ), mWkb( nullptr ), mWkbSize( 0 ), mGeos( nullptr ) {} - ~QgsGeometryPrivate() { delete geometry; delete[] mWkb; GEOSGeom_destroy_r( QgsGeos::getGEOSHandler(), mGeos ); } + QgsGeometryPrivate(): ref( 1 ), geometry( nullptr ), mGeos( nullptr ) {} + ~QgsGeometryPrivate() { delete geometry; GEOSGeom_destroy_r( QgsGeos::getGEOSHandler(), mGeos ); } QAtomicInt ref; QgsAbstractGeometry* geometry; - mutable const unsigned char* mWkb; //store wkb pointer for backward compatibility - mutable int mWkbSize; mutable GEOSGeometry* mGeos; }; @@ -114,18 +112,6 @@ void QgsGeometry::detach( bool cloneGeom ) } } -void QgsGeometry::removeWkbGeos() -{ - delete[] d->mWkb; - d->mWkb = nullptr; - d->mWkbSize = 0; - if ( d->mGeos ) - { - GEOSGeom_destroy_r( QgsGeos::getGEOSHandler(), d->mGeos ); - d->mGeos = nullptr; - } -} - QgsAbstractGeometry* QgsGeometry::geometry() const { return d->geometry; @@ -144,7 +130,6 @@ void QgsGeometry::setGeometry( QgsAbstractGeometry* geometry ) delete d->geometry; d->geometry = nullptr; } - removeWkbGeos(); d->geometry = geometry; } @@ -266,48 +251,22 @@ void QgsGeometry::fromWkb( unsigned char *wkb, int length ) if ( d->geometry ) { delete d->geometry; - removeWkbGeos(); - } - d->geometry = QgsGeometryFactory::geomFromWkb( QgsConstWkbPtr( wkb, length ) ); - if ( d->geometry ) - { - d->mWkb = wkb; - d->mWkbSize = length; - } - else - { - delete [] wkb; - d->mWkb = nullptr; - d->mWkbSize = 0; - } -} - -const unsigned char *QgsGeometry::asWkb() const -{ - if ( !d->geometry ) - { - return nullptr; - } - - if ( !d->mWkb ) - { - d->mWkb = d->geometry->asWkb( d->mWkbSize ); } - return d->mWkb; + QgsConstWkbPtr ptr( wkb, length ); + d->geometry = QgsGeometryFactory::geomFromWkb( ptr ); + delete [] wkb; } -int QgsGeometry::wkbSize() const +void QgsGeometry::fromWkb( const QByteArray &wkb ) { - if ( !d->geometry ) - { - return 0; - } + detach( false ); - if ( !d->mWkb ) + if ( d->geometry ) { - d->mWkb = d->geometry->asWkb( d->mWkbSize ); + delete d->geometry; } - return d->mWkbSize; + QgsConstWkbPtr ptr( wkb ); + d->geometry = QgsGeometryFactory::geomFromWkb( ptr ); } const GEOSGeometry* QgsGeometry::asGeos( double precision ) const @@ -480,7 +439,6 @@ bool QgsGeometry::moveVertex( double x, double y, int atVertex ) detach( true ); - removeWkbGeos(); return d->geometry->moveVertex( id, QgsPointV2( x, y ) ); } @@ -499,7 +457,6 @@ bool QgsGeometry::moveVertex( const QgsPointV2& p, int atVertex ) detach( true ); - removeWkbGeos(); return d->geometry->moveVertex( id, p ); } @@ -514,7 +471,6 @@ bool QgsGeometry::deleteVertex( int atVertex ) if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint ) { detach( true ); - removeWkbGeos(); //delete geometry instead of point return static_cast< QgsGeometryCollection* >( d->geometry )->removeGeometry( atVertex ); } @@ -524,7 +480,6 @@ bool QgsGeometry::deleteVertex( int atVertex ) { detach( false ); delete d->geometry; - removeWkbGeos(); d->geometry = nullptr; return true; } @@ -537,7 +492,6 @@ bool QgsGeometry::deleteVertex( int atVertex ) detach( true ); - removeWkbGeos(); return d->geometry->deleteVertex( id ); } @@ -552,7 +506,6 @@ bool QgsGeometry::insertVertex( double x, double y, int beforeVertex ) if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint ) { detach( true ); - removeWkbGeos(); //insert geometry instead of point return static_cast< QgsGeometryCollection* >( d->geometry )->insertGeometry( new QgsPointV2( x, y ), beforeVertex ); } @@ -565,8 +518,6 @@ bool QgsGeometry::insertVertex( double x, double y, int beforeVertex ) detach( true ); - removeWkbGeos(); - return d->geometry->insertVertex( id, QgsPointV2( x, y ) ); } @@ -655,7 +606,6 @@ int QgsGeometry::addRing( const QList &ring ) { detach( true ); - removeWkbGeos(); QgsLineString* ringLine = new QgsLineString(); QgsPointSequence ringPoints; convertPointList( ring, ringPoints ); @@ -673,7 +623,6 @@ int QgsGeometry::addRing( QgsCurve* ring ) detach( true ); - removeWkbGeos(); return QgsGeometryEditUtils::addRing( d->geometry, ring ); } @@ -723,7 +672,6 @@ int QgsGeometry::addPart( QgsAbstractGeometry* part, QgsWkbTypes::GeometryType g else { detach( true ); - removeWkbGeos(); } convertToMultiType(); @@ -750,7 +698,6 @@ int QgsGeometry::addPart( GEOSGeometry *newPart ) detach( true ); QgsAbstractGeometry* geom = QgsGeos::fromGeos( newPart ); - removeWkbGeos(); return QgsGeometryEditUtils::addPart( d->geometry, geom ); } @@ -764,7 +711,6 @@ int QgsGeometry::translate( double dx, double dy ) detach( true ); d->geometry->transform( QTransform::fromTranslate( dx, dy ) ); - removeWkbGeos(); return 0; } @@ -781,7 +727,6 @@ int QgsGeometry::rotate( double rotation, const QgsPoint& center ) t.rotate( -rotation ); t.translate( -center.x(), -center.y() ); d->geometry->transform( t ); - removeWkbGeos(); return 0; } @@ -815,7 +760,6 @@ int QgsGeometry::splitGeometry( const QList& splitLine, QList& reshapeWithLine ) detach( false ); delete d->geometry; d->geometry = geom; - removeWkbGeos(); return 0; } return errorCode; @@ -865,7 +808,6 @@ int QgsGeometry::makeDifference( const QgsGeometry* other ) delete d->geometry; d->geometry = diffGeom; - removeWkbGeos(); return 0; } @@ -1060,7 +1002,6 @@ bool QgsGeometry::convertToMultiType() detach( true ); multiGeom->addGeometry( d->geometry ); d->geometry = multiGeom; - removeWkbGeos(); return true; } @@ -1084,7 +1025,6 @@ bool QgsGeometry::convertToSingleType() detach( false ); d->geometry = firstPart; - removeWkbGeos(); return true; } @@ -1740,6 +1680,11 @@ QgsGeometry QgsGeometry::extrude( double x, double y ) return engine.extrude( x, y ); } +QByteArray QgsGeometry::exportToWkb() const +{ + return d->geometry ? d->geometry->asWkb() : QByteArray(); +} + QList QgsGeometry::asGeometryCollection() const { QList geometryList; @@ -1810,7 +1755,6 @@ bool QgsGeometry::deleteRing( int ringNum, int partNum ) detach( true ); bool ok = QgsGeometryEditUtils::deleteRing( d->geometry, ringNum, partNum ); - removeWkbGeos(); return ok; } @@ -1829,7 +1773,6 @@ bool QgsGeometry::deletePart( int partNum ) detach( true ); bool ok = QgsGeometryEditUtils::deletePart( d->geometry, partNum ); - removeWkbGeos(); return ok; } @@ -1845,7 +1788,6 @@ int QgsGeometry::avoidIntersections( const QHashgeometry = diffGeom; - removeWkbGeos(); } return 0; } @@ -1917,7 +1859,6 @@ void QgsGeometry::convertToStraightSegment() detach( false ); d->geometry = straightGeom; - removeWkbGeos(); } bool QgsGeometry::requiresConversionToStraightSegments() const @@ -1939,7 +1880,6 @@ int QgsGeometry::transform( const QgsCoordinateTransform& ct ) detach(); d->geometry->transform( ct ); - removeWkbGeos(); return 0; } @@ -1952,7 +1892,6 @@ int QgsGeometry::transform( const QTransform& ct ) detach(); d->geometry->transform( ct ); - removeWkbGeos(); return 0; } @@ -1962,7 +1901,6 @@ void QgsGeometry::mapToPixel( const QgsMapToPixel& mtp ) { detach(); d->geometry->transform( mtp.transform() ); - removeWkbGeos(); } } @@ -2679,8 +2617,7 @@ QgsGeometryEngine* QgsGeometry::createGeometryEngine( const QgsAbstractGeometry* QDataStream& operator<<( QDataStream& out, const QgsGeometry& geometry ) { - QByteArray byteArray = QByteArray::fromRawData( reinterpret_cast< const char * >( geometry.asWkb() ), geometry.wkbSize() ); // does not copy data and does not take ownership - out << byteArray; + out << geometry.exportToWkb(); return out; } @@ -2694,8 +2631,6 @@ QDataStream& operator>>( QDataStream& in, QgsGeometry& geometry ) return in; } - char *data = new char[byteArray.size()]; - memcpy( data, byteArray.data(), byteArray.size() ); - geometry.fromWkb( reinterpret_cast< unsigned char* >( data ), byteArray.size() ); + geometry.fromWkb( byteArray ); return in; } diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 581edb138105..8568cae8fef5 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -146,21 +146,15 @@ class CORE_EXPORT QgsGeometry /** Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length. This class will take ownership of the buffer. + @note not available in python bindings */ void fromWkb( unsigned char *wkb, int length ); /** - Returns the buffer containing this geometry in WKB format. - You may wish to use in conjunction with wkbSize(). - @see wkbSize + * Set the geometry, feeding in the buffer containing OGC Well-Known Binary + * @note added in 3.0 */ - const unsigned char* asWkb() const; - - /** - * Returns the size of the WKB in asWkb(). - * @see asWkb - */ - int wkbSize() const; + void fromWkb( const QByteArray& wkb ); /** Returns a geos geometry. QgsGeometry retains ownership of the geometry, so the returned object should not be deleted. * @param precision The precision of the grid to which to snap the geometry vertices. If 0, no snapping is performed. @@ -637,6 +631,11 @@ class CORE_EXPORT QgsGeometry //! Returns an extruded version of this geometry. QgsGeometry extrude( double x, double y ); + /** Export the geometry to WKB + * @note added in 3.0 + */ + QByteArray exportToWkb() const; + /** Exports the geometry to WKT * @note precision parameter added in 2.4 * @return true in case of success and false else @@ -937,7 +936,6 @@ class CORE_EXPORT QgsGeometry QgsGeometryPrivate* d; //implicitely shared data pointer void detach( bool cloneGeom = true ); //make sure mGeometry only referenced from this instance - void removeWkbGeos(); static void convertToPolyline( const QgsPointSequence &input, QgsPolyline& output ); static void convertPolygon( const QgsPolygonV2& input, QgsPolygon& output ); diff --git a/src/core/geometry/qgsgeometrycollection.cpp b/src/core/geometry/qgsgeometrycollection.cpp index 223304ab2fef..8eea134f17b7 100644 --- a/src/core/geometry/qgsgeometrycollection.cpp +++ b/src/core/geometry/qgsgeometrycollection.cpp @@ -185,7 +185,7 @@ void QgsGeometryCollection::draw( QPainter& p ) const } } -bool QgsGeometryCollection::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsGeometryCollection::fromWkb( QgsConstWkbPtr& wkbPtr ) { if ( !wkbPtr ) { @@ -201,7 +201,7 @@ bool QgsGeometryCollection::fromWkb( QgsConstWkbPtr wkbPtr ) mGeometries.clear(); for ( int i = 0; i < nGeometries; ++i ) { - QgsAbstractGeometry* geom = QgsGeometryFactory::geomFromWkb( wkbPtr ); + QgsAbstractGeometry* geom = QgsGeometryFactory::geomFromWkb( wkbPtr ); // also updates wkbPtr if ( geom ) { if ( !addGeometry( geom ) ) @@ -210,7 +210,6 @@ bool QgsGeometryCollection::fromWkb( QgsConstWkbPtr wkbPtr ) mGeometries = geometryListBackup; return false; } - wkbPtr += geom->wkbSize(); } } qDeleteAll( geometryListBackup ); @@ -230,39 +229,31 @@ bool QgsGeometryCollection::fromWkt( const QString& wkt ) << new QgsMultiCurve << new QgsMultiSurface, QStringLiteral( "GeometryCollection" ) ); } -int QgsGeometryCollection::wkbSize() const +QByteArray QgsGeometryCollection::asWkb() const { - int size = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + QList wkbForGeometries; Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) { if ( geom ) { - size += geom->wkbSize(); + QByteArray wkb( geom->asWkb() ); + binarySize += wkb.length(); + wkbForGeometries << wkb; } } - return size; -} -unsigned char* QgsGeometryCollection::asWkb( int& binarySize ) const -{ - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkb( geomPtr, binarySize ); + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkb( wkbArray ); wkb << static_cast( QgsApplication::endian() ); wkb << static_cast( wkbType() ); - wkb << static_cast( mGeometries.size() ); - Q_FOREACH ( const QgsAbstractGeometry *geom, mGeometries ) + wkb << static_cast( wkbForGeometries.count() ); + Q_FOREACH ( const QByteArray& wkbForGeometry, wkbForGeometries ) { - int geomWkbLen = 0; - if ( geom ) - { - unsigned char* geomWkb = geom->asWkb( geomWkbLen ); - memcpy( wkb, geomWkb, geomWkbLen ); - wkb += geomWkbLen; - delete[] geomWkb; - } + wkb << wkbForGeometry; } - return geomPtr; + return wkbArray; } QString QgsGeometryCollection::asWkt( int precision ) const diff --git a/src/core/geometry/qgsgeometrycollection.h b/src/core/geometry/qgsgeometrycollection.h index c3f379b2e134..05e09497c2cb 100644 --- a/src/core/geometry/qgsgeometrycollection.h +++ b/src/core/geometry/qgsgeometrycollection.h @@ -79,10 +79,9 @@ class CORE_EXPORT QgsGeometryCollection: public QgsAbstractGeometry #endif virtual void draw( QPainter& p ) const override; - bool fromWkb( QgsConstWkbPtr wkb ) override; + bool fromWkb( QgsConstWkbPtr& wkb ) override; virtual bool fromWkt( const QString& wkt ) override; - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; QString asWkt( int precision = 17 ) const override; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; diff --git a/src/core/geometry/qgsgeometryfactory.cpp b/src/core/geometry/qgsgeometryfactory.cpp index 07c7aea8352f..405e631072a0 100644 --- a/src/core/geometry/qgsgeometryfactory.cpp +++ b/src/core/geometry/qgsgeometryfactory.cpp @@ -30,7 +30,7 @@ #include "qgswkbtypes.h" #include "qgslogger.h" -QgsAbstractGeometry* QgsGeometryFactory::geomFromWkb( QgsConstWkbPtr wkbPtr ) +QgsAbstractGeometry* QgsGeometryFactory::geomFromWkb( QgsConstWkbPtr& wkbPtr ) { if ( !wkbPtr ) return nullptr; @@ -57,7 +57,7 @@ QgsAbstractGeometry* QgsGeometryFactory::geomFromWkb( QgsConstWkbPtr wkbPtr ) { try { - geom->fromWkb( wkbPtr ); + geom->fromWkb( wkbPtr ); // also updates wkbPtr } catch ( const QgsWkbException &e ) { diff --git a/src/core/geometry/qgsgeometryfactory.h b/src/core/geometry/qgsgeometryfactory.h index f3e2bcbbf740..ea8498dc2de7 100644 --- a/src/core/geometry/qgsgeometryfactory.h +++ b/src/core/geometry/qgsgeometryfactory.h @@ -45,8 +45,9 @@ class CORE_EXPORT QgsGeometryFactory public: /** Construct geometry from a WKB string. + * Updates position of the passed WKB pointer. */ - static QgsAbstractGeometry* geomFromWkb( QgsConstWkbPtr wkb ); + static QgsAbstractGeometry* geomFromWkb( QgsConstWkbPtr& wkb ); /** Construct geometry from a WKT string. */ diff --git a/src/core/geometry/qgslinestring.cpp b/src/core/geometry/qgslinestring.cpp index d5cfcda65b20..85287245cb6e 100644 --- a/src/core/geometry/qgslinestring.cpp +++ b/src/core/geometry/qgslinestring.cpp @@ -91,7 +91,7 @@ void QgsLineString::clear() clearCache(); } -bool QgsLineString::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsLineString::fromWkb( QgsConstWkbPtr& wkbPtr ) { if ( !wkbPtr ) { @@ -158,24 +158,20 @@ bool QgsLineString::fromWkt( const QString& wkt ) return true; } -int QgsLineString::wkbSize() const +QByteArray QgsLineString::asWkb() const { - int size = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); - size += numPoints() * ( 2 + is3D() + isMeasure() ) * sizeof( double ); - return size; -} + int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + binarySize += numPoints() * ( 2 + is3D() + isMeasure() ) * sizeof( double ); -unsigned char* QgsLineString::asWkb( int& binarySize ) const -{ - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkb( geomPtr, binarySize ); + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkb( wkbArray ); wkb << static_cast( QgsApplication::endian() ); wkb << static_cast( wkbType() ); QgsPointSequence pts; points( pts ); QgsGeometryUtils::pointsToWKB( wkb, pts, is3D(), isMeasure() ); - return geomPtr; + return wkbArray; } /*************************************************************************** diff --git a/src/core/geometry/qgslinestring.h b/src/core/geometry/qgslinestring.h index 25befa6dda79..9c1ae8f0a6be 100644 --- a/src/core/geometry/qgslinestring.h +++ b/src/core/geometry/qgslinestring.h @@ -135,11 +135,10 @@ class CORE_EXPORT QgsLineString: public QgsCurve virtual QgsLineString* clone() const override; virtual void clear() override; - virtual bool fromWkb( QgsConstWkbPtr wkb ) override; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) override; virtual bool fromWkt( const QString& wkt ) override; - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; QString asWkt( int precision = 17 ) const override; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; diff --git a/src/core/geometry/qgspointv2.cpp b/src/core/geometry/qgspointv2.cpp index 9a2e2c768d35..15cb5194fcbf 100644 --- a/src/core/geometry/qgspointv2.cpp +++ b/src/core/geometry/qgspointv2.cpp @@ -96,7 +96,7 @@ QgsPointV2 *QgsPointV2::clone() const return new QgsPointV2( *this ); } -bool QgsPointV2::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsPointV2::fromWkb( QgsConstWkbPtr& wkbPtr ) { QgsWkbTypes::Type type = wkbPtr.readHeader(); if ( QgsWkbTypes::flatType( type ) != QgsWkbTypes::Point ) @@ -165,24 +165,20 @@ bool QgsPointV2::fromWkt( const QString& wkt ) return true; } -int QgsPointV2::wkbSize() const -{ - int size = sizeof( char ) + sizeof( quint32 ); - size += ( 2 + is3D() + isMeasure() ) * sizeof( double ); - return size; -} - /*************************************************************************** * This class is considered CRITICAL and any change MUST be accompanied with * full unit tests. * See details in QEP #17 ****************************************************************************/ -unsigned char* QgsPointV2::asWkb( int& binarySize ) const +QByteArray QgsPointV2::asWkb() const { - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkb( geomPtr, binarySize ); + int binarySize = sizeof( char ) + sizeof( quint32 ); + binarySize += ( 2 + is3D() + isMeasure() ) * sizeof( double ); + + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkb( wkbArray ); wkb << static_cast( QgsApplication::endian() ); wkb << static_cast( wkbType() ); wkb << mX << mY; @@ -194,7 +190,7 @@ unsigned char* QgsPointV2::asWkb( int& binarySize ) const { wkb << mM; } - return geomPtr; + return wkbArray; } QString QgsPointV2::asWkt( int precision ) const diff --git a/src/core/geometry/qgspointv2.h b/src/core/geometry/qgspointv2.h index cd034a1fd5ac..8cb95b65190f 100644 --- a/src/core/geometry/qgspointv2.h +++ b/src/core/geometry/qgspointv2.h @@ -198,10 +198,9 @@ class CORE_EXPORT QgsPointV2: public QgsAbstractGeometry virtual int dimension() const override { return 0; } virtual QgsPointV2* clone() const override; void clear() override; - virtual bool fromWkb( QgsConstWkbPtr wkb ) override; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) override; virtual bool fromWkt( const QString& wkt ) override; - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; QString asWkt( int precision = 17 ) const override; QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const override; diff --git a/src/core/geometry/qgspolygon.cpp b/src/core/geometry/qgspolygon.cpp index cf3ba723ecc7..9f3f25d82916 100644 --- a/src/core/geometry/qgspolygon.cpp +++ b/src/core/geometry/qgspolygon.cpp @@ -77,7 +77,7 @@ void QgsPolygonV2::clear() mWkbType = QgsWkbTypes::Polygon; } -bool QgsPolygonV2::fromWkb( QgsConstWkbPtr wkbPtr ) +bool QgsPolygonV2::fromWkb( QgsConstWkbPtr& wkbPtr ) { clear(); if ( !wkbPtr ) @@ -136,27 +136,23 @@ bool QgsPolygonV2::fromWkb( QgsConstWkbPtr wkbPtr ) return true; } -int QgsPolygonV2::wkbSize() const +QByteArray QgsPolygonV2::asWkb() const { - int size = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + int binarySize = sizeof( char ) + sizeof( quint32 ) + sizeof( quint32 ); + + // Endianness and WkbType is not stored for LinearRings if ( mExteriorRing ) { - // Endianness and WkbType is not stored for LinearRings - size += mExteriorRing->wkbSize() - ( sizeof( char ) + sizeof( quint32 ) ); + binarySize += sizeof( quint32 ) + mExteriorRing->numPoints() * ( 2 + mExteriorRing->is3D() + mExteriorRing->isMeasure() ) * sizeof( double ); } Q_FOREACH ( const QgsCurve* curve, mInteriorRings ) { - // Endianness and WkbType is not stored for LinearRings - size += curve->wkbSize() - ( sizeof( char ) + sizeof( quint32 ) ); + binarySize += sizeof( quint32 ) + curve->numPoints() * ( 2 + curve->is3D() + curve->isMeasure() ) * sizeof( double ); } - return size; -} -unsigned char* QgsPolygonV2::asWkb( int& binarySize ) const -{ - binarySize = wkbSize(); - unsigned char* geomPtr = new unsigned char[binarySize]; - QgsWkbPtr wkb( geomPtr, binarySize ); + QByteArray wkbArray; + wkbArray.resize( binarySize ); + QgsWkbPtr wkb( wkbArray ); wkb << static_cast( QgsApplication::endian() ); wkb << static_cast( wkbType() ); wkb << static_cast(( nullptr != mExteriorRing ) + mInteriorRings.size() ); @@ -173,7 +169,7 @@ unsigned char* QgsPolygonV2::asWkb( int& binarySize ) const QgsGeometryUtils::pointsToWKB( wkb, pts, curve->is3D(), curve->isMeasure() ); } - return geomPtr; + return wkbArray; } void QgsPolygonV2::addInteriorRing( QgsCurve* ring ) diff --git a/src/core/geometry/qgspolygon.h b/src/core/geometry/qgspolygon.h index a1ce6dfe1add..6bbff312c4ff 100644 --- a/src/core/geometry/qgspolygon.h +++ b/src/core/geometry/qgspolygon.h @@ -38,12 +38,11 @@ class CORE_EXPORT QgsPolygonV2: public QgsCurvePolygon virtual QgsPolygonV2* clone() const override; void clear() override; - virtual bool fromWkb( QgsConstWkbPtr wkb ) override; + virtual bool fromWkb( QgsConstWkbPtr& wkb ) override; // inherited: bool fromWkt( const QString &wkt ); - int wkbSize() const override; - unsigned char* asWkb( int& binarySize ) const override; + QByteArray asWkb() const override; // inherited: QString asWkt( int precision = 17 ) const; // inherited: QDomElement asGML2( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; // inherited: QDomElement asGML3( QDomDocument& doc, int precision = 17, const QString& ns = "gml" ) const; diff --git a/src/core/geometry/qgswkbptr.cpp b/src/core/geometry/qgswkbptr.cpp index d91b278a115f..85cf582e1331 100644 --- a/src/core/geometry/qgswkbptr.cpp +++ b/src/core/geometry/qgswkbptr.cpp @@ -14,6 +14,13 @@ ***************************************************************************/ #include "qgswkbptr.h" +QgsWkbPtr::QgsWkbPtr( QByteArray &wkb ) +{ + mP = reinterpret_cast( wkb.data() ); + mStart = mP; + mEnd = mP + wkb.length(); +} + QgsWkbPtr::QgsWkbPtr( unsigned char *p, int size ) { mP = p; @@ -27,6 +34,14 @@ void QgsWkbPtr::verifyBound( int size ) const throw QgsWkbException( QStringLiteral( "wkb access out of bounds" ) ); } +QgsConstWkbPtr::QgsConstWkbPtr( const QByteArray &wkb ) +{ + mP = reinterpret_cast< unsigned char * >( const_cast( wkb.constData() ) ); + mEnd = mP + wkb.length(); + mEndianSwap = false; + mWkbType = QgsWkbTypes::Unknown; +} + QgsConstWkbPtr::QgsConstWkbPtr( const unsigned char *p, int size ) { mP = const_cast< unsigned char * >( p ); diff --git a/src/core/geometry/qgswkbptr.h b/src/core/geometry/qgswkbptr.h index ee31677cffdf..b1da1197ca0d 100644 --- a/src/core/geometry/qgswkbptr.h +++ b/src/core/geometry/qgswkbptr.h @@ -58,7 +58,15 @@ class CORE_EXPORT QgsWkbPtr mP += sizeof v; } + void write( const QByteArray& data ) const + { + verifyBound( data.length() ); + memcpy( mP, data.constData(), data.length() ); + mP += data.length(); + } + public: + QgsWkbPtr( QByteArray& wkb ); QgsWkbPtr( unsigned char *p, int size ); inline const QgsWkbPtr &operator>>( double &v ) const { read( v ); return *this; } @@ -74,6 +82,7 @@ class CORE_EXPORT QgsWkbPtr inline QgsWkbPtr &operator<<( const unsigned int &v ) { write( v ); return *this; } inline QgsWkbPtr &operator<<( const char &v ) { write( v ); return *this; } inline QgsWkbPtr &operator<<( const QgsWkbTypes::Type &v ) { write( v ); return *this; } + inline QgsWkbPtr &operator<<( const QByteArray &data ) { write( data ); return *this; } inline void operator+=( int n ) { verifyBound( n ); mP += n; } @@ -110,6 +119,7 @@ class CORE_EXPORT QgsConstWkbPtr } public: + explicit QgsConstWkbPtr( const QByteArray& wkb ); QgsConstWkbPtr( const unsigned char *p, int size ); QgsWkbTypes::Type readHeader() const; diff --git a/src/core/qgsogcutils.cpp b/src/core/qgsogcutils.cpp index 6918fc5b5b21..26b2f7688e39 100644 --- a/src/core/qgsogcutils.cpp +++ b/src/core/qgsogcutils.cpp @@ -1132,7 +1132,7 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen const QString& gmlIdBase, int precision ) { - if ( !geometry || !geometry->asWkb() ) + if ( !geometry ) return QDomElement(); // coordinate separator @@ -1144,7 +1144,8 @@ QDomElement QgsOgcUtils::geometryToGML( const QgsGeometry* geometry, QDomDocumen bool hasZValue = false; - QgsConstWkbPtr wkbPtr( geometry->asWkb(), geometry->wkbSize() ); + QByteArray wkb( geometry->exportToWkb() ); + QgsConstWkbPtr wkbPtr( wkb ); try { wkbPtr.readHeader(); diff --git a/src/core/qgspointlocator.cpp b/src/core/qgspointlocator.cpp index 7d36f149a654..902131a2d103 100644 --- a/src/core/qgspointlocator.cpp +++ b/src/core/qgspointlocator.cpp @@ -325,13 +325,13 @@ static QgsPointLocator::MatchList _geometrySegmentsInRect( QgsGeometry *geom, co // we need iterator for segments... QgsPointLocator::MatchList lst; - unsigned char* wkb = const_cast( geom->asWkb() ); // we're not changing wkb, just need non-const for QgsWkbPtr - if ( !wkb ) + QByteArray wkb( geom->exportToWkb() ); + if ( wkb.isEmpty() ) return lst; _CohenSutherland cs( rect ); - QgsConstWkbPtr wkbPtr( wkb, geom->wkbSize() ); + QgsConstWkbPtr wkbPtr( wkb ); wkbPtr.readHeader(); QgsWkbTypes::Type wkbType = geom->wkbType(); diff --git a/src/core/qgsvectorfilewriter.cpp b/src/core/qgsvectorfilewriter.cpp index ff702eaaa54b..9aeed83a67d7 100644 --- a/src/core/qgsvectorfilewriter.cpp +++ b/src/core/qgsvectorfilewriter.cpp @@ -2117,7 +2117,8 @@ OGRFeatureH QgsVectorFileWriter::createFeature( const QgsFeature& feature ) return nullptr; } - OGRErr err = OGR_G_ImportFromWkb( mGeom2, const_cast( geom.asWkb() ), static_cast< int >( geom.wkbSize() ) ); + QByteArray wkb( geom.exportToWkb() ); + OGRErr err = OGR_G_ImportFromWkb( mGeom2, reinterpret_cast( const_cast( wkb.constData() ) ), wkb.length() ); if ( err != OGRERR_NONE ) { mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" ) @@ -2133,7 +2134,8 @@ OGRFeatureH QgsVectorFileWriter::createFeature( const QgsFeature& feature ) } else // wkb type matches { - OGRErr err = OGR_G_ImportFromWkb( mGeom, const_cast( geom.asWkb() ), static_cast< int >( geom.wkbSize() ) ); + QByteArray wkb( geom.exportToWkb() ); + OGRErr err = OGR_G_ImportFromWkb( mGeom, reinterpret_cast( const_cast( wkb.constData() ) ), wkb.length() ); if ( err != OGRERR_NONE ) { mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" ) diff --git a/src/providers/db2/qgsdb2provider.cpp b/src/providers/db2/qgsdb2provider.cpp index 03a89e1ed983..0e8ee12b4efd 100644 --- a/src/providers/db2/qgsdb2provider.cpp +++ b/src/providers/db2/qgsdb2provider.cpp @@ -1083,7 +1083,7 @@ bool QgsDb2Provider::addFeatures( QgsFeatureList & flist ) { QgsGeometry geom = it->geometry(); - QByteArray bytea = QByteArray(( char* )geom.asWkb(), ( int ) geom.wkbSize() ); + QByteArray bytea = geom.exportToWkb(); query.bindValue( bindIdx, bytea, QSql::In | QSql::Binary ); } @@ -1217,7 +1217,7 @@ bool QgsDb2Provider::changeGeometryValues( const QgsGeometryMap &geometry_map ) } // add geometry param - QByteArray bytea = QByteArray(( char* )it->asWkb(), ( int ) it->wkbSize() ); + QByteArray bytea = it->exportToWkb(); query.addBindValue( bytea, QSql::In | QSql::Binary ); if ( !query.exec() ) diff --git a/src/providers/gpx/qgsgpxprovider.cpp b/src/providers/gpx/qgsgpxprovider.cpp index 417910b7d933..af8a3e5f0fd2 100644 --- a/src/providers/gpx/qgsgpxprovider.cpp +++ b/src/providers/gpx/qgsgpxprovider.cpp @@ -213,7 +213,8 @@ bool QgsGPXProvider::addFeatures( QgsFeatureList & flist ) bool QgsGPXProvider::addFeature( QgsFeature& f ) { - const unsigned char* geo = f.geometry().asWkb(); + QByteArray wkb( f.geometry().exportToWkb() ); + const char* geo = wkb.constData(); QgsWkbTypes::Type wkbType = f.geometry().wkbType(); bool success = false; QgsGPSObject* obj = nullptr; diff --git a/src/providers/mssql/qgsmssqlprovider.cpp b/src/providers/mssql/qgsmssqlprovider.cpp index d0cbd1f564e6..afce499d4256 100644 --- a/src/providers/mssql/qgsmssqlprovider.cpp +++ b/src/providers/mssql/qgsmssqlprovider.cpp @@ -936,7 +936,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList & flist ) QgsGeometry geom = it->geometry(); if ( mUseWkb ) { - QByteArray bytea = QByteArray(( char* )geom.asWkb(), ( int ) geom.wkbSize() ); + QByteArray bytea = geom.exportToWkb(); query.addBindValue( bytea, QSql::In | QSql::Binary ); } else @@ -1255,7 +1255,7 @@ bool QgsMssqlProvider::changeGeometryValues( const QgsGeometryMap &geometry_map // add geometry param if ( mUseWkb ) { - QByteArray bytea = QByteArray(( char* )it->asWkb(), ( int ) it->wkbSize() ); + QByteArray bytea = it->exportToWkb(); query.addBindValue( bytea, QSql::In | QSql::Binary ); } else diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index 1adc5f3efb4f..efb7ae13d93b 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -1204,14 +1204,14 @@ bool QgsOgrProvider::addFeature( QgsFeature& f ) OGRFeatureDefnH fdef = OGR_L_GetLayerDefn( ogrLayer ); OGRFeatureH feature = OGR_F_Create( fdef ); - if ( f.hasGeometry() && f.geometry().wkbSize() > 0 ) + if ( f.hasGeometry() ) { - const unsigned char* wkb = f.geometry().asWkb(); + QByteArray wkb( f.geometry().exportToWkb() ); OGRGeometryH geom = nullptr; - if ( wkb ) + if ( !wkb.isEmpty() ) { - if ( OGR_G_CreateFromWkb( const_cast( wkb ), nullptr, &geom, f.geometry().wkbSize() ) != OGRERR_NONE ) + if ( OGR_G_CreateFromWkb( reinterpret_cast( const_cast( wkb.constData() ) ), nullptr, &geom, wkb.length() ) != OGRERR_NONE ) { pushError( tr( "OGR error creating wkb for feature %1: %2" ).arg( f.id() ).arg( CPLGetLastErrorMsg() ) ); return false; @@ -1733,15 +1733,16 @@ bool QgsOgrProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) } OGRGeometryH theNewGeometry = nullptr; + QByteArray wkb = it->exportToWkb(); // We might receive null geometries. It is ok, but don't go through the // OGR_G_CreateFromWkb() route then - if ( it->wkbSize() != 0 ) + if ( !wkb.isEmpty() ) { //create an OGRGeometry - if ( OGR_G_CreateFromWkb( const_cast( it->asWkb() ), + if ( OGR_G_CreateFromWkb( reinterpret_cast( const_cast( wkb.constData() ) ), OGR_L_GetSpatialRef( ogrLayer ), &theNewGeometry, - it->wkbSize() ) != OGRERR_NONE ) + wkb.length() ) != OGRERR_NONE ) { pushError( tr( "OGR error creating geometry for feature %1: %2" ).arg( it.key() ).arg( CPLGetLastErrorMsg() ) ); OGR_G_DestroyGeometry( theNewGeometry ); diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index dfe1bc486484..c4ce906cdd9b 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -2498,10 +2498,11 @@ void QgsPostgresProvider::appendGeomParam( const QgsGeometry& geom, QStringList QString param; QScopedPointer convertedGeom( convertToProviderType( geom ) ); - const unsigned char *buf = convertedGeom ? convertedGeom->asWkb() : geom.asWkb(); - size_t wkbSize = convertedGeom ? convertedGeom->wkbSize() : geom.wkbSize(); + QByteArray wkb( convertedGeom ? convertedGeom->exportToWkb() : geom.exportToWkb() ); + const char *buf = wkb.constData(); + int wkbSize = wkb.length(); - for ( size_t i = 0; i < wkbSize; ++i ) + for ( int i = 0; i < wkbSize; ++i ) { if ( connectionRO()->useWkbHex() ) param += QStringLiteral( "%1" ).arg(( int ) buf[i], 2, 16, QChar( '0' ) ); diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index 99320856cb71..a06b3562cd7f 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -3806,8 +3806,9 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist ) { unsigned char *wkb = nullptr; int wkb_size; - convertFromGeosWKB( feature->geometry().asWkb(), - feature->geometry().wkbSize(), + QByteArray featureWkb = feature->geometry().exportToWkb(); + convertFromGeosWKB( reinterpret_cast( featureWkb.constData() ), + featureWkb.length(), &wkb, &wkb_size, nDims ); if ( !wkb ) sqlite3_bind_null( stmt, ++ia ); @@ -4216,7 +4217,8 @@ bool QgsSpatiaLiteProvider::changeGeometryValues( const QgsGeometryMap &geometry // binding GEOMETRY to Prepared Statement unsigned char *wkb = nullptr; int wkb_size; - convertFromGeosWKB( iter->asWkb(), iter->wkbSize(), &wkb, &wkb_size, nDims ); + QByteArray iterWkb = iter->exportToWkb(); + convertFromGeosWKB( reinterpret_cast( iterWkb.constData() ), iterWkb.length(), &wkb, &wkb_size, nDims ); if ( !wkb ) sqlite3_bind_null( stmt, 1 ); else diff --git a/src/providers/virtual/qgsvirtuallayerblob.cpp b/src/providers/virtual/qgsvirtuallayerblob.cpp index bb6028ed8f5e..db433c914302 100644 --- a/src/providers/virtual/qgsvirtuallayerblob.cpp +++ b/src/providers/virtual/qgsvirtuallayerblob.cpp @@ -78,7 +78,9 @@ void qgsGeometryToSpatialiteBlob( const QgsGeometry &geom, int32_t srid, char *& { const int header_len = SpatialiteBlobHeader::length; - const int wkb_size = geom.wkbSize(); + QByteArray wkb( geom.exportToWkb() ); + + const int wkb_size = wkb.length(); size = header_len + wkb_size; blob = new char[size]; @@ -104,9 +106,7 @@ void qgsGeometryToSpatialiteBlob( const QgsGeometry &geom, int32_t srid, char *& // blob geometry = header + wkb[1:] + 'end' // copy wkb - const unsigned char* wkb = geom.asWkb(); - - memcpy( p, wkb + 1, wkb_size - 1 ); + memcpy( p, wkb.constData() + 1, wkb_size - 1 ); p += wkb_size - 1; // end marker diff --git a/src/providers/wfs/qgswfsfeatureiterator.cpp b/src/providers/wfs/qgswfsfeatureiterator.cpp index b35387c6f8f9..331d1636ff11 100644 --- a/src/providers/wfs/qgswfsfeatureiterator.cpp +++ b/src/providers/wfs/qgswfsfeatureiterator.cpp @@ -1167,13 +1167,8 @@ void QgsWFSFeatureIterator::copyFeature( const QgsFeature& srcFeature, QgsFeatur QgsGeometry geometry = srcFeature.geometry(); if ( !mShared->mGeometryAttribute.isEmpty() && !geometry.isEmpty() ) { - const unsigned char *geom = geometry.asWkb(); - int geomSize = geometry.wkbSize(); - unsigned char* copiedGeom = new unsigned char[geomSize]; - memcpy( copiedGeom, geom, geomSize ); - QgsGeometry g; - g.fromWkb( copiedGeom, geomSize ); + g.fromWkb( geometry.exportToWkb() ); dstFeature.setGeometry( g ); } else diff --git a/src/providers/wfs/qgswfsshareddata.cpp b/src/providers/wfs/qgswfsshareddata.cpp index 68dcba09aee4..4c9f159f9a5f 100644 --- a/src/providers/wfs/qgswfsshareddata.cpp +++ b/src/providers/wfs/qgswfsshareddata.cpp @@ -734,13 +734,11 @@ bool QgsWFSSharedData::changeGeometryValues( const QgsGeometryMap &geometry_map QgsChangedAttributesMap newChangedAttrMap; for ( QgsGeometryMap::const_iterator iter = geometry_map.constBegin(); iter != geometry_map.constEnd(); ++iter ) { - const unsigned char *geom = iter->asWkb(); - int geomSize = iter->wkbSize(); - if ( geomSize ) + QByteArray wkb = iter->exportToWkb(); + if ( !wkb.isEmpty() ) { QgsAttributeMap newAttrMap; - QByteArray array(( const char* )geom, geomSize ); - newAttrMap[idx] = QString( array.toHex().data() ); + newAttrMap[idx] = QString( wkb.toHex().data() ); newChangedAttrMap[ iter.key()] = newAttrMap; QgsGeometry polyBoudingBox = QgsGeometry::fromRect( iter.value().boundingBox() ); @@ -872,9 +870,7 @@ void QgsWFSSharedData::serializeFeatures( QVector& featu QgsGeometry geometry = gmlFeature.geometry(); if ( !mGeometryAttribute.isEmpty() && !geometry.isEmpty() ) { - const unsigned char *geom = geometry.asWkb(); - int geomSize = geometry.wkbSize(); - QByteArray array(( const char* )geom, geomSize ); + QByteArray array( geometry.exportToWkb() ); cachedFeature.setAttribute( hexwkbGeomIdx, QVariant( QString( array.toHex().data() ) ) ); diff --git a/src/providers/wfs/qgswfsutils.cpp b/src/providers/wfs/qgswfsutils.cpp index 728840823a81..bf2067aa16d5 100644 --- a/src/providers/wfs/qgswfsutils.cpp +++ b/src/providers/wfs/qgswfsutils.cpp @@ -359,9 +359,7 @@ QString QgsWFSUtils::getMD5( const QgsFeature& f ) QgsGeometry geometry = f.geometry(); if ( !geometry.isEmpty() ) { - const unsigned char *geom = geometry.asWkb(); - int geomSize = geometry.wkbSize(); - hash.addData( QByteArray(( const char* )geom, geomSize ) ); + hash.addData( geometry.exportToWkb() ); } return hash.result().toHex(); diff --git a/tests/src/core/testqgsfeature.cpp b/tests/src/core/testqgsfeature.cpp index 5f756c9adc6f..3d7efcd96e76 100644 --- a/tests/src/core/testqgsfeature.cpp +++ b/tests/src/core/testqgsfeature.cpp @@ -275,14 +275,14 @@ void TestQgsFeature::geometry() feature.setGeometry( QgsGeometry( mGeometry2 ) ); QVERIFY( feature.hasGeometry() ); feature.setGeometry( QgsGeometry( mGeometry ) ); - QCOMPARE( *feature.geometry().asWkb(), *mGeometry.asWkb() ); + QCOMPARE( feature.geometry().exportToWkb(), mGeometry.exportToWkb() ); //test implicit sharing detachment QgsFeature copy( feature ); - QCOMPARE( *copy.geometry().asWkb(), *feature.geometry().asWkb() ); + QCOMPARE( copy.geometry().exportToWkb(), feature.geometry().exportToWkb() ); copy.clearGeometry(); QVERIFY( ! copy.hasGeometry() ); - QCOMPARE( *feature.geometry().asWkb(), *mGeometry.asWkb() ); + QCOMPARE( feature.geometry().exportToWkb(), mGeometry.exportToWkb() ); //test no crash when setting an empty geometry and triggering a detach QgsFeature emptyGeomFeature; @@ -294,18 +294,18 @@ void TestQgsFeature::geometry() //setGeometry //always start with a copy so that we can test implicit sharing detachment is working copy = feature; - QCOMPARE( *copy.geometry().asWkb(), *mGeometry.asWkb() ); + QCOMPARE( copy.geometry().exportToWkb(), mGeometry.exportToWkb() ); copy.setGeometry( QgsGeometry( mGeometry2 ) ); - QCOMPARE( *copy.geometry().asWkb(), *mGeometry2.asWkb() ); - QCOMPARE( *feature.geometry().asWkb(), *mGeometry.asWkb() ); + QCOMPARE( copy.geometry().exportToWkb(), mGeometry2.exportToWkb() ); + QCOMPARE( feature.geometry().exportToWkb(), mGeometry.exportToWkb() ); //setGeometry using reference copy = feature; - QCOMPARE( *copy.geometry().asWkb(), *mGeometry.asWkb() ); + QCOMPARE( copy.geometry().exportToWkb(), mGeometry.exportToWkb() ); QgsGeometry geomByRef( mGeometry2 ); copy.setGeometry( geomByRef ); - QCOMPARE( *copy.geometry().asWkb(), *geomByRef.asWkb() ); - QCOMPARE( *feature.geometry().asWkb(), *mGeometry.asWkb() ); + QCOMPARE( copy.geometry().exportToWkb(), geomByRef.exportToWkb() ); + QCOMPARE( feature.geometry().exportToWkb(), mGeometry.exportToWkb() ); //clearGeometry QgsFeature geomFeature; @@ -501,7 +501,7 @@ void TestQgsFeature::dataStream() QCOMPARE( resultFeature.id(), originalFeature.id() ); QCOMPARE( resultFeature.attributes(), originalFeature.attributes() ); - QCOMPARE( *resultFeature.geometry().asWkb(), *originalFeature.geometry().asWkb() ); + QCOMPARE( resultFeature.geometry().exportToWkb(), originalFeature.geometry().exportToWkb() ); QCOMPARE( resultFeature.isValid(), originalFeature.isValid() ); //also test with feature empty geometry diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index 255a4905a76e..a79697146cbf 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -547,25 +547,22 @@ void TestQgsGeometry::point() //to/from WKB QgsPointV2 p12( QgsWkbTypes::PointZM, 1.0, 2.0, 3.0, -4.0 ); - int size = 0; - unsigned char* wkb = p12.asWkb( size ); - QCOMPARE( size, p12.wkbSize() ); + QByteArray wkb12 = p12.asWkb(); QgsPointV2 p13; - p13.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + QgsConstWkbPtr wkb12ptr( wkb12 ); + p13.fromWkb( wkb12ptr ); QVERIFY( p13 == p12 ); //bad WKB - check for no crash p13 = QgsPointV2( 1, 2 ); - QVERIFY( !p13.fromWkb( QgsConstWkbPtr( nullptr, 0 ) ) ); + QgsConstWkbPtr nullPtr( nullptr, 0 ); + QVERIFY( !p13.fromWkb( nullPtr ) ); QCOMPARE( p13.wkbType(), QgsWkbTypes::Point ); QgsLineString line; p13 = QgsPointV2( 1, 2 ); - wkb = line.asWkb( size ); - QVERIFY( !p13.fromWkb( QgsConstWkbPtr( wkb, size ) ) ); - delete[] wkb; - wkb = 0; + QByteArray wkbLine = line.asWkb(); + QgsConstWkbPtr wkbLinePtr( wkbLine ); + QVERIFY( !p13.fromWkb( wkbLinePtr ) ); QCOMPARE( p13.wkbType(), QgsWkbTypes::Point ); //to/from WKT @@ -1390,13 +1387,10 @@ void TestQgsGeometry::lineString() << QgsPointV2( QgsWkbTypes::PointZM, 11, 2, 11, 14 ) << QgsPointV2( QgsWkbTypes::PointZM, 11, 22, 21, 24 ) << QgsPointV2( QgsWkbTypes::PointZM, 1, 22, 31, 34 ) ); - int size = 0; - unsigned char* wkb = l15.asWkb( size ); - QCOMPARE( size, l15.wkbSize() ); + QByteArray wkb15 = l15.asWkb(); QgsLineString l16; - l16.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + QgsConstWkbPtr wkb15ptr( wkb15 ); + l16.fromWkb( wkb15ptr ); QCOMPARE( l16.numPoints(), 4 ); QCOMPARE( l16.vertexCount(), 4 ); QCOMPARE( l16.nCoordinates(), 4 ); @@ -1412,13 +1406,13 @@ void TestQgsGeometry::lineString() //bad WKB - check for no crash l16.clear(); - QVERIFY( !l16.fromWkb( QgsConstWkbPtr( nullptr, 0 ) ) ); + QgsConstWkbPtr nullPtr( nullptr, 0 ); + QVERIFY( !l16.fromWkb( nullPtr ) ); QCOMPARE( l16.wkbType(), QgsWkbTypes::LineString ); QgsPointV2 point( 1, 2 ); - wkb = point.asWkb( size ) ; - QVERIFY( !l16.fromWkb( QgsConstWkbPtr( wkb, size ) ) ); - delete[] wkb; - wkb = 0; + QByteArray wkb16 = point.asWkb(); + QgsConstWkbPtr wkb16ptr( wkb16 ); + QVERIFY( !l16.fromWkb( wkb16ptr ) ); QCOMPARE( l16.wkbType(), QgsWkbTypes::LineString ); //to/from WKT @@ -2147,10 +2141,9 @@ void TestQgsGeometry::lineString() l37.clear(); QVERIFY( l37.boundingBox().isNull() ); l37.setPoints( QgsPointSequence() << QgsPointV2( 5, 10 ) << QgsPointV2( 10, 15 ) ); - wkb = toAppend->asWkb( size ); - l37.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + QByteArray wkbToAppend = toAppend->asWkb(); + QgsConstWkbPtr wkbToAppendPtr( wkbToAppend ); + l37.fromWkb( wkbToAppendPtr ); QCOMPARE( l37.boundingBox(), QgsRectangle( 1, 0, 4, 2 ) ); l37.fromWkt( QStringLiteral( "LineString( 1 5, 3 4, 6 3 )" ) ); QCOMPARE( l37.boundingBox(), QgsRectangle( 1, 3, 6, 5 ) ); @@ -2786,13 +2779,10 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::Point, 1, 9 ) << QgsPointV2( QgsWkbTypes::Point, 9, 9 ) << QgsPointV2( QgsWkbTypes::Point, 9, 1 ) << QgsPointV2( QgsWkbTypes::Point, 1, 1 ) ); p16.addInteriorRing( ring ); - int size = 0; - unsigned char* wkb = p16.asWkb( size ); - QCOMPARE( size, p16.wkbSize() ); + QByteArray wkb16 = p16.asWkb(); QgsPolygonV2 p17; - p17.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + QgsConstWkbPtr wkb16ptr( wkb16 ); + p17.fromWkb( wkb16ptr ); QCOMPARE( p16, p17 ); //PolygonZ p16.clear(); @@ -2807,12 +2797,9 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::PointZ, 1, 9, 2 ) << QgsPointV2( QgsWkbTypes::PointZ, 9, 9, 3 ) << QgsPointV2( QgsWkbTypes::PointZ, 9, 1, 4 ) << QgsPointV2( QgsWkbTypes::PointZ, 1, 1, 1 ) ); p16.addInteriorRing( ring ); - size = 0; - wkb = p16.asWkb( size ); - QCOMPARE( size, p16.wkbSize() ); - p17.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + wkb16 = p16.asWkb(); + QgsConstWkbPtr wkb16ptr2( wkb16 ); + p17.fromWkb( wkb16ptr2 ); QCOMPARE( p16, p17 ); //PolygonM p16.clear(); @@ -2827,12 +2814,9 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::PointM, 1, 9, 0, 2 ) << QgsPointV2( QgsWkbTypes::PointM, 9, 9, 0, 3 ) << QgsPointV2( QgsWkbTypes::PointM, 9, 1, 0, 4 ) << QgsPointV2( QgsWkbTypes::PointM, 1, 1, 0, 1 ) ); p16.addInteriorRing( ring ); - size = 0; - wkb = p16.asWkb( size ); - QCOMPARE( size, p16.wkbSize() ); - p17.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + wkb16 = p16.asWkb(); + QgsConstWkbPtr wkb16ptr3( wkb16 ); + p17.fromWkb( wkb16ptr3 ); QCOMPARE( p16, p17 ); //PolygonZM p16.clear(); @@ -2847,12 +2831,9 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::PointZM, 1, 9, 2, 3 ) << QgsPointV2( QgsWkbTypes::PointZM, 9, 9, 3, 6 ) << QgsPointV2( QgsWkbTypes::PointZM, 9, 1, 4, 4 ) << QgsPointV2( QgsWkbTypes::PointZM, 1, 1, 1, 7 ) ); p16.addInteriorRing( ring ); - size = 0; - wkb = p16.asWkb( size ); - QCOMPARE( size, p16.wkbSize() ); - p17.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + wkb16 = p16.asWkb(); + QgsConstWkbPtr wkb16ptr4( wkb16 ); + p17.fromWkb( wkb16ptr4 ); QCOMPARE( p16, p17 ); //Polygon25D p16.clear(); @@ -2867,24 +2848,21 @@ void TestQgsGeometry::polygon() << QgsPointV2( QgsWkbTypes::Point25D, 1, 9, 2 ) << QgsPointV2( QgsWkbTypes::Point25D, 9, 9, 3 ) << QgsPointV2( QgsWkbTypes::Point25D, 9, 1, 4 ) << QgsPointV2( QgsWkbTypes::Point25D, 1, 1, 1 ) ); p16.addInteriorRing( ring ); - size = 0; - wkb = p16.asWkb( size ); - QCOMPARE( size, p16.wkbSize() ); + wkb16 = p16.asWkb(); p17.clear(); - p17.fromWkb( QgsConstWkbPtr( wkb, size ) ); - delete[] wkb; - wkb = 0; + QgsConstWkbPtr wkb16ptr5( wkb16 ); + p17.fromWkb( wkb16ptr5 ); QCOMPARE( p16, p17 ); //bad WKB - check for no crash p17.clear(); - QVERIFY( !p17.fromWkb( QgsConstWkbPtr( nullptr, 0 ) ) ); + QgsConstWkbPtr nullPtr( nullptr, 0 ); + QVERIFY( !p17.fromWkb( nullPtr ) ); QCOMPARE( p17.wkbType(), QgsWkbTypes::Polygon ); QgsPointV2 point( 1, 2 ); - wkb = point.asWkb( size ) ; - QVERIFY( !p17.fromWkb( QgsConstWkbPtr( wkb, size ) ) ); - delete[] wkb; - wkb = 0; + QByteArray wkbPoint = point.asWkb(); + QgsConstWkbPtr wkbPointPtr( wkbPoint ); + QVERIFY( !p17.fromWkb( wkbPointPtr ) ); QCOMPARE( p17.wkbType(), QgsWkbTypes::Polygon ); //to/from WKT diff --git a/tests/src/python/test_provider_ogr_gpkg.py b/tests/src/python/test_provider_ogr_gpkg.py index c0cdf3bdca84..64c15f6e3aee 100644 --- a/tests/src/python/test_provider_ogr_gpkg.py +++ b/tests/src/python/test_provider_ogr_gpkg.py @@ -74,7 +74,7 @@ def testSingleToMultiPolygonPromotion(self): got_geom = got.geometry() reference = QgsGeometry.fromWkt('MultiPolygon (((0 0, 0 1, 1 1, 0 0)))') # The geometries must be binarily identical - self.assertEqual(got_geom.asWkb(), reference.asWkb(), 'Expected {}, got {}'.format(reference.exportToWkt(), got_geom.exportToWkt())) + self.assertEqual(got_geom.exportToWkb(), reference.exportToWkb(), 'Expected {}, got {}'.format(reference.exportToWkt(), got_geom.exportToWkt())) @unittest.expectedFailure(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(2, 0, 0)) def testCurveGeometryType(self): @@ -93,7 +93,7 @@ def testCurveGeometryType(self): got_geom = got.geometry() reference = QgsGeometry.fromWkt('CurvePolygon (((0 0, 0 1, 1 1, 0 0)))') # The geometries must be binarily identical - self.assertEqual(got_geom.asWkb(), reference.asWkb(), 'Expected {}, got {}'.format(reference.exportToWkt(), got_geom.exportToWkt())) + self.assertEqual(got_geom.exportToWkb(), reference.exportToWkb(), 'Expected {}, got {}'.format(reference.exportToWkt(), got_geom.exportToWkt())) def internalTestBug15351(self, orderClosing): diff --git a/tests/src/python/test_qgsgeometry.py b/tests/src/python/test_qgsgeometry.py index de2e744757ad..9b2c4843b93b 100644 --- a/tests/src/python/test_qgsgeometry.py +++ b/tests/src/python/test_qgsgeometry.py @@ -3394,7 +3394,7 @@ def testMisc(self): # Test that importing an invalid WKB (a MultiPolygon with a CurvePolygon) fails geom = QgsGeometry.fromWkt('MultiSurface(((0 0,0 1,1 1,0 0)), CurvePolygon ((0 0,0 1,1 1,0 0)))') - wkb = geom.asWkb() + wkb = geom.exportToWkb() wkb = bytearray(wkb) if wkb[1] == QgsWkbTypes.MultiSurface: wkb[1] = QgsWkbTypes.MultiPolygon @@ -3434,10 +3434,10 @@ def testMisc(self): wkt += ")" geom = QgsGeometry.fromWkt(wkt) assert geom is not None - wkb1 = geom.asWkb() + wkb1 = geom.exportToWkb() geom = QgsGeometry() geom.fromWkb(wkb1) - wkb2 = geom.asWkb() + wkb2 = geom.exportToWkb() self.assertEqual(wkb1, wkb2) def testMergeLines(self): From 9872b4848d052e3ff64f2558a9668614ea487307 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 14 Nov 2016 00:53:23 +0800 Subject: [PATCH 732/897] Remove caching of GEOS representation within QgsGeometry (legacy) --- doc/api_break.dox | 1 + python/core/geometry/qgsgeometry.sip | 6 +-- src/analysis/vector/qgsgeometryanalyzer.cpp | 4 +- src/analysis/vector/qgszonalstatistics.cpp | 6 ++- src/app/qgsmaptooloffsetcurve.cpp | 3 +- src/core/geometry/qgsgeometry.cpp | 15 +++----- src/core/geometry/qgsgeometry.h | 6 +-- src/core/geometry/qgswkbptr.h | 3 ++ src/core/qgsgeometryvalidator.cpp | 6 ++- src/core/qgslabelfeature.cpp | 12 ++++-- src/core/qgslabelfeature.h | 3 ++ src/core/qgspallabeling.cpp | 31 ++++++---------- src/core/qgstracer.cpp | 4 +- src/core/qgsvectorlayerdiagramprovider.cpp | 22 ++++------- src/plugins/topology/topolTest.cpp | 41 ++++++++++++++------- 15 files changed, 89 insertions(+), 74 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index d5935f7ee1c1..c5d2a06be28c 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -844,6 +844,7 @@ value instead of a pointer. The biggest impact with this change is that PyQGIS c result to None, but instead either use a boolean test (`if g.buffer(10):`) or explicitly use the isEmpty() method to determine if a geometry is valid. - wkbSize() and asWkb() has been replaced by exportToWkb(). WKB representation is no longer cached within QgsGeometry +- asGeos() has been replaced by exportToGeos(). GEOS representation is no longer cached within QgsGeometry - int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPoints - int addPart( const QList &points, QgsWkbTypes::GeometryType geomType ) has been renamed to addPointsV2 - static bool compare( const QgsPolyline& p1, const QgsPolyline& p2, double epsilon ) has been renamed to comparePolylines diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index 588b7f767b14..1db6117ff62a 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -103,12 +103,12 @@ class QgsGeometry */ void fromWkb( const QByteArray& wkb ); - /** Returns a geos geometry. QgsGeometry retains ownership of the geometry, so the returned object should not be deleted. + /** Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destroy_r) * @param precision The precision of the grid to which to snap the geometry vertices. If 0, no snapping is performed. - * @note this method was added in version 1.1 + * @note added in version 3.0 * @note not available in python bindings */ - // const GEOSGeometry* asGeos( double precision = 0 ) const; + // GEOSGeometry* exportToGeos( double precision = 0 ) const; /** Returns type of the geometry as a WKB type (point / linestring / polygon etc.) * @see type diff --git a/src/analysis/vector/qgsgeometryanalyzer.cpp b/src/analysis/vector/qgsgeometryanalyzer.cpp index 44abaef62b21..b356de2592d5 100644 --- a/src/analysis/vector/qgsgeometryanalyzer.cpp +++ b/src/analysis/vector/qgsgeometryanalyzer.cpp @@ -1063,7 +1063,9 @@ QgsGeometry QgsGeometryAnalyzer::createOffsetGeometry( const QgsGeometry& geom, { if ( geom.type() == QgsWkbTypes::LineGeometry ) { - GEOSGeometry* offsetGeom = GEOSOffsetCurve_r( geosctxt, ( *inputGeomIt ).asGeos(), -offset, 8 /*quadSegments*/, 0 /*joinStyle*/, 5.0 /*mitreLimit*/ ); + GEOSGeometry* inputGeomItGeos = inputGeomIt->exportToGeos(); + GEOSGeometry* offsetGeom = GEOSOffsetCurve_r( geosctxt, inputGeomItGeos, -offset, 8 /*quadSegments*/, 0 /*joinStyle*/, 5.0 /*mitreLimit*/ ); + GEOSGeom_destroy_r( geosctxt, inputGeomItGeos ); if ( !offsetGeom || !GEOSisValid_r( geosctxt, offsetGeom ) ) { return QgsGeometry(); diff --git a/src/analysis/vector/qgszonalstatistics.cpp b/src/analysis/vector/qgszonalstatistics.cpp index 489d4689b007..0fd2df0cb28e 100644 --- a/src/analysis/vector/qgszonalstatistics.cpp +++ b/src/analysis/vector/qgszonalstatistics.cpp @@ -419,16 +419,17 @@ void QgsZonalStatistics::statisticsFromMiddlePointTest( void* band, const QgsGeo cellCenterY = rasterBBox.yMaximum() - pixelOffsetY * cellSizeY - cellSizeY / 2; stats.reset(); - const GEOSGeometry* polyGeos = poly.asGeos(); + GEOSGeometry* polyGeos = poly.exportToGeos(); if ( !polyGeos ) { return; } GEOSContextHandle_t geosctxt = QgsGeometry::getGEOSHandler(); - const GEOSPreparedGeometry* polyGeosPrepared = GEOSPrepare_r( geosctxt, poly.asGeos() ); + const GEOSPreparedGeometry* polyGeosPrepared = GEOSPrepare_r( geosctxt, polyGeos ); if ( !polyGeosPrepared ) { + GEOSGeom_destroy_r( geosctxt, polyGeos ); return; } @@ -464,6 +465,7 @@ void QgsZonalStatistics::statisticsFromMiddlePointTest( void* band, const QgsGeo GEOSGeom_destroy_r( geosctxt, currentCellCenter ); CPLFree( scanLine ); GEOSPreparedGeom_destroy_r( geosctxt, polyGeosPrepared ); + GEOSGeom_destroy_r( geosctxt, polyGeos ); } void QgsZonalStatistics::statisticsFromPreciseIntersection( void* band, const QgsGeometry& poly, int pixelOffsetX, diff --git a/src/app/qgsmaptooloffsetcurve.cpp b/src/app/qgsmaptooloffsetcurve.cpp index bebc5284530b..8b600036141b 100644 --- a/src/app/qgsmaptooloffsetcurve.cpp +++ b/src/app/qgsmaptooloffsetcurve.cpp @@ -368,7 +368,7 @@ void QgsMapToolOffsetCurve::setOffsetForRubberBand( double offset ) } QgsGeometry geomCopy( mOriginalGeometry ); - const GEOSGeometry* geosGeom = geomCopy.asGeos(); + GEOSGeometry* geosGeom = geomCopy.exportToGeos(); if ( geosGeom ) { QSettings s; @@ -377,6 +377,7 @@ void QgsMapToolOffsetCurve::setOffsetForRubberBand( double offset ) double mitreLimit = s.value( QStringLiteral( "/qgis/digitizing/offset_miter_limit" ), 5.0 ).toDouble(); GEOSGeometry* offsetGeom = GEOSOffsetCurve_r( QgsGeometry::getGEOSHandler(), geosGeom, offset, quadSegments, joinStyle, mitreLimit ); + GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), geosGeom ); if ( !offsetGeom ) { deleteRubberBandAndGeometry(); diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index 91f8f582bfe1..c2126a6d64a5 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -54,11 +54,10 @@ email : morb at ozemail dot com dot au struct QgsGeometryPrivate { - QgsGeometryPrivate(): ref( 1 ), geometry( nullptr ), mGeos( nullptr ) {} - ~QgsGeometryPrivate() { delete geometry; GEOSGeom_destroy_r( QgsGeos::getGEOSHandler(), mGeos ); } + QgsGeometryPrivate(): ref( 1 ), geometry( nullptr ) {} + ~QgsGeometryPrivate() { delete geometry; } QAtomicInt ref; QgsAbstractGeometry* geometry; - mutable GEOSGeometry* mGeos; }; QgsGeometry::QgsGeometry(): d( new QgsGeometryPrivate() ) @@ -269,18 +268,14 @@ void QgsGeometry::fromWkb( const QByteArray &wkb ) d->geometry = QgsGeometryFactory::geomFromWkb( ptr ); } -const GEOSGeometry* QgsGeometry::asGeos( double precision ) const +GEOSGeometry* QgsGeometry::exportToGeos( double precision ) const { if ( !d->geometry ) { return nullptr; } - if ( !d->mGeos ) - { - d->mGeos = QgsGeos::asGeos( d->geometry, precision ); - } - return d->mGeos; + return QgsGeos::asGeos( d->geometry, precision ); } @@ -320,7 +315,7 @@ void QgsGeometry::fromGeos( GEOSGeometry *geos ) detach( false ); delete d->geometry; d->geometry = QgsGeos::fromGeos( geos ); - d->mGeos = geos; + GEOSGeom_destroy_r( QgsGeos::getGEOSHandler(), geos ); } QgsPoint QgsGeometry::closestVertex( const QgsPoint& point, int& atVertex, int& beforeVertex, int& afterVertex, double& sqrDist ) const diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 8568cae8fef5..2de8aedd9021 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -156,12 +156,12 @@ class CORE_EXPORT QgsGeometry */ void fromWkb( const QByteArray& wkb ); - /** Returns a geos geometry. QgsGeometry retains ownership of the geometry, so the returned object should not be deleted. + /** Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destroy_r) * @param precision The precision of the grid to which to snap the geometry vertices. If 0, no snapping is performed. - * @note this method was added in version 1.1 + * @note added in 3.0 * @note not available in python bindings */ - const GEOSGeometry* asGeos( double precision = 0 ) const; + GEOSGeometry* exportToGeos( double precision = 0 ) const; /** Returns type of the geometry as a WKB type (point / linestring / polygon etc.) * @see type diff --git a/src/core/geometry/qgswkbptr.h b/src/core/geometry/qgswkbptr.h index b1da1197ca0d..7a62e3ba750b 100644 --- a/src/core/geometry/qgswkbptr.h +++ b/src/core/geometry/qgswkbptr.h @@ -66,6 +66,7 @@ class CORE_EXPORT QgsWkbPtr } public: + //! Construct WKB pointer from QByteArray QgsWkbPtr( QByteArray& wkb ); QgsWkbPtr( unsigned char *p, int size ); @@ -82,6 +83,7 @@ class CORE_EXPORT QgsWkbPtr inline QgsWkbPtr &operator<<( const unsigned int &v ) { write( v ); return *this; } inline QgsWkbPtr &operator<<( const char &v ) { write( v ); return *this; } inline QgsWkbPtr &operator<<( const QgsWkbTypes::Type &v ) { write( v ); return *this; } + //! Append data from a byte array inline QgsWkbPtr &operator<<( const QByteArray &data ) { write( data ); return *this; } inline void operator+=( int n ) { verifyBound( n ); mP += n; } @@ -119,6 +121,7 @@ class CORE_EXPORT QgsConstWkbPtr } public: + //! Construct WKB pointer from QByteArray explicit QgsConstWkbPtr( const QByteArray& wkb ); QgsConstWkbPtr( const unsigned char *p, int size ); QgsWkbTypes::Type readHeader() const; diff --git a/src/core/qgsgeometryvalidator.cpp b/src/core/qgsgeometryvalidator.cpp index 571dee051071..e082d13a396f 100644 --- a/src/core/qgsgeometryvalidator.cpp +++ b/src/core/qgsgeometryvalidator.cpp @@ -220,7 +220,7 @@ void QgsGeometryValidator::run() if ( settings.value( QStringLiteral( "/qgis/digitizing/validate_geometries" ), 1 ).toInt() == 2 ) { char *r = nullptr; - const GEOSGeometry *g0 = mG.asGeos(); + GEOSGeometry *g0 = mG.exportToGeos(); GEOSContextHandle_t handle = QgsGeometry::getGEOSHandler(); if ( !g0 ) { @@ -229,7 +229,9 @@ void QgsGeometryValidator::run() else { GEOSGeometry *g1 = nullptr; - if ( GEOSisValidDetail_r( handle, g0, GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE, &r, &g1 ) != 1 ) + char res = GEOSisValidDetail_r( handle, g0, GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE, &r, &g1 ); + GEOSGeom_destroy_r( handle, g0 ); + if ( res != 1 ) { if ( g1 ) { diff --git a/src/core/qgslabelfeature.cpp b/src/core/qgslabelfeature.cpp index be5c66d7c921..51f30b900d7d 100644 --- a/src/core/qgslabelfeature.cpp +++ b/src/core/qgslabelfeature.cpp @@ -35,6 +35,7 @@ QgsLabelFeature::QgsLabelFeature( QgsFeatureId id, GEOSGeometry* geometry, QSize , mIsObstacle( false ) , mObstacleFactor( 1 ) , mInfo( nullptr ) + , mPermissibleZoneGeos( nullptr ) , mPermissibleZoneGeosPrepared( nullptr ) { } @@ -48,7 +49,10 @@ QgsLabelFeature::~QgsLabelFeature() GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), mObstacleGeometry ); if ( mPermissibleZoneGeosPrepared ) + { GEOSPreparedGeom_destroy_r( QgsGeometry::getGEOSHandler(), mPermissibleZoneGeosPrepared ); + GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), mPermissibleZoneGeos ); + } delete mInfo; } @@ -68,15 +72,17 @@ void QgsLabelFeature::setPermissibleZone( const QgsGeometry &geometry ) if ( mPermissibleZoneGeosPrepared ) { GEOSPreparedGeom_destroy_r( QgsGeometry::getGEOSHandler(), mPermissibleZoneGeosPrepared ); + GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), mPermissibleZoneGeos ); mPermissibleZoneGeosPrepared = nullptr; + mPermissibleZoneGeos = nullptr; } if ( mPermissibleZone.isEmpty() ) return; - const GEOSGeometry* zoneGeos = mPermissibleZone.asGeos(); - if ( !zoneGeos ) + mPermissibleZoneGeos = mPermissibleZone.exportToGeos(); + if ( !mPermissibleZoneGeos ) return; - mPermissibleZoneGeosPrepared = GEOSPrepare_r( QgsGeometry::getGEOSHandler(), zoneGeos ); + mPermissibleZoneGeosPrepared = GEOSPrepare_r( QgsGeometry::getGEOSHandler(), mPermissibleZoneGeos ); } diff --git a/src/core/qgslabelfeature.h b/src/core/qgslabelfeature.h index 2522beb47c52..d9442b36d323 100644 --- a/src/core/qgslabelfeature.h +++ b/src/core/qgslabelfeature.h @@ -394,6 +394,9 @@ class CORE_EXPORT QgsLabelFeature private: + //! GEOS geometry on which mPermissibleZoneGeosPrepared is based on + GEOSGeometry* mPermissibleZoneGeos; + // TODO - not required when QgsGeometry caches geos preparedness const GEOSPreparedGeometry* mPermissibleZoneGeosPrepared; diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index c453c7490331..15009c2e0fa0 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -1851,7 +1851,7 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont geom = QgsGeometry( geom.geometry()->boundary() ); } - const GEOSGeometry* geos_geom = nullptr; + GEOSGeometry* geos_geom_clone = nullptr; if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, ct, doClip ? &extentGeom : nullptr ) ) { geom = QgsPalLabeling::prepareGeometry( geom, context, ct, doClip ? &extentGeom : nullptr ); @@ -1859,9 +1859,8 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont if ( geom.isEmpty() ) return; } - geos_geom = geom.asGeos(); + geos_geom_clone = geom.exportToGeos(); - const GEOSGeometry* geosObstacleGeom = nullptr; QScopedPointer scopedObstacleGeom; if ( isObstacle ) { @@ -1870,16 +1869,12 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont scopedObstacleGeom.reset( new QgsGeometry( QgsPalLabeling::prepareGeometry( *obstacleGeometry, context, ct, doClip ? &extentGeom : nullptr ) ) ); obstacleGeometry = scopedObstacleGeom.data(); } - if ( obstacleGeometry ) - { - geosObstacleGeom = obstacleGeometry->asGeos(); - } } if ( minFeatureSize > 0 && !checkMinimumSizeMM( context, geom, minFeatureSize ) ) return; - if ( !geos_geom ) + if ( !geos_geom_clone ) return; // invalid geometry // likelihood exists label will be registered with PAL and may be drawn @@ -1907,11 +1902,10 @@ void QgsPalLayerSettings::registerFeature( QgsFeature& f, QgsRenderContext &cont } } - GEOSGeometry* geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom ); GEOSGeometry* geosObstacleGeomClone = nullptr; - if ( geosObstacleGeom ) + if ( obstacleGeometry ) { - geosObstacleGeomClone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geosObstacleGeom ); + geosObstacleGeomClone = obstacleGeometry->exportToGeos(); } @@ -2384,21 +2378,18 @@ void QgsPalLayerSettings::registerObstacleFeature( QgsFeature& f, QgsRenderConte geom = simplifier.simplify( geom ); } - const GEOSGeometry* geos_geom = nullptr; + GEOSGeometry* geos_geom_clone = nullptr; QScopedPointer scopedPreparedGeom; if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, ct, &extentGeom ) ) { geom = QgsPalLabeling::prepareGeometry( geom, context, ct, &extentGeom ); } - geos_geom = geom.asGeos(); + geos_geom_clone = geom.exportToGeos(); - if ( !geos_geom ) + if ( !geos_geom_clone ) return; // invalid geometry - GEOSGeometry* geos_geom_clone; - geos_geom_clone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom ); - // feature to the layer *obstacleFeature = new QgsLabelFeature( f.id(), geos_geom_clone, QSizeF( 0, 0 ) ); ( *obstacleFeature )->setIsObstacle( true ); @@ -3416,8 +3407,10 @@ QgsGeometry QgsPalLabeling::prepareGeometry( const QgsGeometry& geometry, QgsRen } } - if ( !geom.asGeos() ) - return QgsGeometry(); // there is something really wrong with the geometry + // MD: exporting geometry to GEOS just to see if the geometry is wrong...? + // if still needed, we could have a more specific test here + //if ( !geom.asGeos() ) + // return QgsGeometry(); // there is something really wrong with the geometry // fix invalid polygons if ( geom.type() == QgsWkbTypes::PolygonGeometry && !geom.isGeosValid() ) diff --git a/src/core/qgstracer.cpp b/src/core/qgstracer.cpp index 624db76a8ed1..ce1a1db12401 100644 --- a/src/core/qgstracer.cpp +++ b/src/core/qgstracer.cpp @@ -533,7 +533,9 @@ bool QgsTracer::initGraph() { t2a.start(); // GEOSNode_r may throw an exception - GEOSGeometry* allNoded = GEOSNode_r( QgsGeometry::getGEOSHandler(), allGeom.asGeos() ); + GEOSGeometry* allGeomGeos = allGeom.exportToGeos(); + GEOSGeometry* allNoded = GEOSNode_r( QgsGeometry::getGEOSHandler(), allGeomGeos ); + GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), allGeomGeos ); timeNodingCall = t2a.elapsed(); QgsGeometry* noded = new QgsGeometry; diff --git a/src/core/qgsvectorlayerdiagramprovider.cpp b/src/core/qgsvectorlayerdiagramprovider.cpp index 6e9ada148c89..919acaa71f93 100644 --- a/src/core/qgsvectorlayerdiagramprovider.cpp +++ b/src/core/qgsvectorlayerdiagramprovider.cpp @@ -224,7 +224,7 @@ QgsLabelFeature* QgsVectorLayerDiagramProvider::registerDiagram( QgsFeature& fea extentGeom.rotate( -mapSettings.rotation(), mapSettings.visibleExtent().center() ); } - const GEOSGeometry* geos_geom = nullptr; + GEOSGeometry* geomCopy = nullptr; QScopedPointer scopedPreparedGeom; if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, mSettings.coordinateTransform(), &extentGeom ) ) { @@ -232,36 +232,28 @@ QgsLabelFeature* QgsVectorLayerDiagramProvider::registerDiagram( QgsFeature& fea QgsGeometry* preparedGeom = scopedPreparedGeom.data(); if ( preparedGeom->isEmpty() ) return nullptr; - geos_geom = preparedGeom->asGeos(); + geomCopy = preparedGeom->exportToGeos(); } else { - geos_geom = geom.asGeos(); + geomCopy = geom.exportToGeos(); } - if ( !geos_geom ) + if ( !geomCopy ) return nullptr; // invalid geometry - GEOSGeometry* geomCopy = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom ); - - const GEOSGeometry* geosObstacleGeom = nullptr; + GEOSGeometry* geosObstacleGeomClone = nullptr; QScopedPointer scopedObstacleGeom; if ( mSettings.isObstacle() && obstacleGeometry && QgsPalLabeling::geometryRequiresPreparation( *obstacleGeometry, context, mSettings.coordinateTransform(), &extentGeom ) ) { QgsGeometry preparedObstacleGeom = QgsPalLabeling::prepareGeometry( *obstacleGeometry, context, mSettings.coordinateTransform(), &extentGeom ); - geosObstacleGeom = preparedObstacleGeom.asGeos(); + geosObstacleGeomClone = preparedObstacleGeom.exportToGeos(); } else if ( mSettings.isObstacle() && obstacleGeometry ) { - geosObstacleGeom = obstacleGeometry->asGeos(); - } - GEOSGeometry* geosObstacleGeomClone = nullptr; - if ( geosObstacleGeom ) - { - geosObstacleGeomClone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geosObstacleGeom ); + geosObstacleGeomClone = obstacleGeometry->exportToGeos(); } - double diagramWidth = 0; double diagramHeight = 0; if ( dr ) diff --git a/src/plugins/topology/topolTest.cpp b/src/plugins/topology/topolTest.cpp index 61a39c3d56e9..cb7f8980e107 100644 --- a/src/plugins/topology/topolTest.cpp +++ b/src/plugins/topology/topolTest.cpp @@ -31,6 +31,17 @@ #include #include +static bool _canExportToGeos( const QgsGeometry& geom ) +{ + GEOSGeometry* geosGeom = geom.exportToGeos(); + if ( geosGeom ) + { + GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), geosGeom ); + return true; + } + return false; +} + topolTest::topolTest( QgisInterface* qgsIface ) { theQgsInterface = qgsIface; @@ -266,7 +277,7 @@ ErrorList topolTest::checkDanglingLines( double tolerance, QgsVectorLayer* layer continue; } - if ( !g1.asGeos() ) + if ( !_canExportToGeos( g1 ) ) { QgsMessageLog::logMessage( tr( "Failed to import first geometry into GEOS in dangling line test." ), tr( "Topology plugin" ) ); continue; @@ -395,7 +406,7 @@ ErrorList topolTest::checkDuplicates( double tolerance, QgsVectorLayer *layer1, continue; } - if ( !g2.asGeos() ) + if ( !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in duplicate geometry test." ), tr( "Topology plugin" ) ); continue; @@ -514,7 +525,7 @@ ErrorList topolTest::checkOverlaps( double tolerance, QgsVectorLayer *layer1, Qg continue; } - if ( !g2.asGeos() ) + if ( !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Failed to import second geometry into GEOS in overlaps test." ), tr( "Topology plugin" ) ); continue; @@ -609,7 +620,7 @@ ErrorList topolTest::checkGaps( double tolerance, QgsVectorLayer *layer1, QgsVec continue; } - if ( !g1.asGeos() ) + if ( !_canExportToGeos( g1 ) ) { continue; } @@ -629,13 +640,13 @@ ErrorList topolTest::checkGaps( double tolerance, QgsVectorLayer *layer1, QgsVec QgsGeometry polyGeom = QgsGeometry::fromPolygon( polygon ); - geomList.push_back( GEOSGeom_clone_r( geosctxt, polyGeom.asGeos() ) ); + geomList.push_back( polyGeom.exportToGeos() ); } } else { - geomList.push_back( GEOSGeom_clone_r( geosctxt, g1.asGeos() ) ); + geomList.push_back( g1.exportToGeos() ); } } @@ -753,7 +764,7 @@ ErrorList topolTest::checkPseudos( double tolerance, QgsVectorLayer *layer1, Qgs continue; } - if ( !g1.asGeos() ) + if ( !_canExportToGeos( g1 ) ) { QgsMessageLog::logMessage( tr( "Failed to import first geometry into GEOS in pseudo line test." ), tr( "Topology plugin" ) ); continue; @@ -853,10 +864,11 @@ ErrorList topolTest::checkValid( double tolerance, QgsVectorLayer* layer1, QgsVe continue; } - if ( !g.asGeos() ) + GEOSGeometry* gGeos = g.exportToGeos(); + if ( !gGeos ) continue; - if ( !GEOSisValid_r( QgsGeometry::getGEOSHandler(), g.asGeos() ) ) + if ( !GEOSisValid_r( QgsGeometry::getGEOSHandler(), gGeos ) ) { QgsRectangle r = g.boundingBox(); QList fls; @@ -865,6 +877,7 @@ ErrorList topolTest::checkValid( double tolerance, QgsVectorLayer* layer1, QgsVe TopolErrorValid* err = new TopolErrorValid( r, g, fls ); errorList << err; } + GEOSGeom_destroy_r( QgsGeometry::getGEOSHandler(), gGeos ); } return errorList; @@ -1234,7 +1247,7 @@ ErrorList topolTest::checkPointCoveredByLineEnds( double tolerance, QgsVectorLay { QgsFeature& f = mFeatureMap2[*cit].feature; QgsGeometry g2 = f.geometry(); - if ( g2.isEmpty() || !g2.asGeos() ) + if ( g2.isEmpty() || !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Second geometry missing or GEOS import failed." ), tr( "Topology plugin" ) ); continue; @@ -1320,7 +1333,7 @@ ErrorList topolTest::checkyLineEndsCoveredByPoints( double tolerance, QgsVectorL { QgsFeature& f = mFeatureMap2[*cit].feature; QgsGeometry g2 = f.geometry(); - if ( g2.isEmpty() || !g2.asGeos() ) + if ( g2.isEmpty() || !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Second geometry missing or GEOS import failed." ), tr( "Topology plugin" ) ); continue; @@ -1410,7 +1423,7 @@ ErrorList topolTest::checkPointInPolygon( double tolerance, QgsVectorLayer *laye { QgsFeature& f = mFeatureMap2[*cit].feature; QgsGeometry g2 = f.geometry(); - if ( g2.isEmpty() || !g2.asGeos() ) + if ( g2.isEmpty() || !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Second geometry missing or GEOS import failed." ), tr( "Topology plugin" ) ); continue; @@ -1484,7 +1497,7 @@ ErrorList topolTest::checkPolygonContainsPoint( double tolerance, QgsVectorLayer { QgsFeature& f = mFeatureMap2[*cit].feature; QgsGeometry g2 = f.geometry(); - if ( g2.isEmpty() || !g2.asGeos() ) + if ( g2.isEmpty() || !_canExportToGeos( g2 ) ) { QgsMessageLog::logMessage( tr( "Second geometry missing or GEOS import failed." ), tr( "Topology plugin" ) ); continue; @@ -1529,7 +1542,7 @@ ErrorList topolTest::checkMultipart( double tolerance, QgsVectorLayer *layer1, Q QgsMessageLog::logMessage( tr( "Missing geometry in multipart check." ), tr( "Topology plugin" ) ); continue; } - if ( !g.asGeos() ) + if ( !_canExportToGeos( g ) ) continue; if ( g.isMultipart() ) { From 514d4439bd7428d1889aa9a21832da79e2f442d4 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 14 Nov 2016 13:05:07 +0800 Subject: [PATCH 733/897] Fix oracle provider and remove dead code --- src/core/qgspallabeling.cpp | 5 ----- src/providers/oracle/qgsoraclefeatureiterator.cpp | 15 ++++----------- src/providers/oracle/qgsoracleprovider.cpp | 8 ++++---- 3 files changed, 8 insertions(+), 20 deletions(-) diff --git a/src/core/qgspallabeling.cpp b/src/core/qgspallabeling.cpp index 15009c2e0fa0..497a6bbda534 100644 --- a/src/core/qgspallabeling.cpp +++ b/src/core/qgspallabeling.cpp @@ -3407,11 +3407,6 @@ QgsGeometry QgsPalLabeling::prepareGeometry( const QgsGeometry& geometry, QgsRen } } - // MD: exporting geometry to GEOS just to see if the geometry is wrong...? - // if still needed, we could have a more specific test here - //if ( !geom.asGeos() ) - // return QgsGeometry(); // there is something really wrong with the geometry - // fix invalid polygons if ( geom.type() == QgsWkbTypes::PolygonGeometry && !geom.isGeosValid() ) { diff --git a/src/providers/oracle/qgsoraclefeatureiterator.cpp b/src/providers/oracle/qgsoraclefeatureiterator.cpp index 2190c7ee5c49..41f7ae9f952e 100644 --- a/src/providers/oracle/qgsoraclefeatureiterator.cpp +++ b/src/providers/oracle/qgsoraclefeatureiterator.cpp @@ -270,11 +270,8 @@ bool QgsOracleFeatureIterator::fetchFeature( QgsFeature& feature ) QByteArray *ba = static_cast( mQry.value( col++ ).data() ); if ( ba->size() > 0 ) { - unsigned char *copy = new unsigned char[ba->size()]; - memcpy( copy, ba->constData(), ba->size() ); - QgsGeometry g; - g.fromWkb( copy, ba->size() ); + g.fromWkb( *ba ); feature.setGeometry( g ); } else @@ -381,13 +378,9 @@ bool QgsOracleFeatureIterator::fetchFeature( QgsFeature& feature ) QByteArray *ba = static_cast( v.data() ); if ( ba->size() > 0 ) { - unsigned char *copy = new unsigned char[ba->size()]; - memcpy( copy, ba->constData(), ba->size() ); - - QgsGeometry *g = new QgsGeometry(); - g->fromWkb( copy, ba->size() ); - v = g->exportToWkt(); - delete g; + QgsGeometry g; + g.fromWkb( *ba ); + v = g.exportToWkt(); } else { diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index 9e9f95a199ad..e4d2a449f9e6 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -1856,8 +1856,10 @@ void QgsOracleProvider::appendGeomParam( const QgsGeometry& geom, QSqlQuery &qry { QOCISpatialGeometry g; + QByteArray wkb = geom.exportToWkb(); + wkbPtr ptr; - ptr.ucPtr = !geom.isEmpty() ? ( unsigned char * ) geom.asWkb() : 0; + ptr.ucPtr = !geom.isEmpty() ? reinterpret_cast< unsigned char * >( const_cast( wkb.constData() ) ) : 0; g.isNull = !ptr.ucPtr; g.gtype = -1; g.srid = mSrid < 1 ? -1 : mSrid; @@ -2274,10 +2276,8 @@ QgsRectangle QgsOracleProvider::extent() const if ( ok && qry.next() ) { QByteArray *ba = static_cast( qry.value( 0 ).data() ); - unsigned char *copy = new unsigned char[ba->size()]; - memcpy( copy, ba->constData(), ba->size() ); QgsGeometry g; - g.fromWkb( copy, ba->size() ); // take ownership + g.fromWkb( *ba ); mLayerExtent = g.boundingBox(); QgsDebugMsg( "extent: " + mLayerExtent.toString() ); } From 1d3f1f07e8b8d7f73aea83d439bde9b20dedd385 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 10 Nov 2016 14:56:11 +1000 Subject: [PATCH 734/897] Fix QgsGeometryUtils::sqrDistToLine returns bad values (eg nan values) --- src/core/geometry/qgsgeometryutils.cpp | 39 +++++++++++++------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/src/core/geometry/qgsgeometryutils.cpp b/src/core/geometry/qgsgeometryutils.cpp index c4453c7631d5..83a81435c0a0 100644 --- a/src/core/geometry/qgsgeometryutils.cpp +++ b/src/core/geometry/qgsgeometryutils.cpp @@ -248,30 +248,31 @@ double QgsGeometryUtils::sqrDistance2D( const QgsPointV2& pt1, const QgsPointV2& double QgsGeometryUtils::sqrDistToLine( double ptX, double ptY, double x1, double y1, double x2, double y2, double& minDistX, double& minDistY, double epsilon ) { - //normal vector - double nx = y2 - y1; - double ny = -( x2 - x1 ); + minDistX = x1; + minDistY = y1; - double t; - t = ( ptX * ny - ptY * nx - x1 * ny + y1 * nx ) / (( x2 - x1 ) * ny - ( y2 - y1 ) * nx ); + double dx = x2 - x1; + double dy = y2 - y1; - if ( t < 0.0 ) + if ( !qgsDoubleNear( dx, 0.0 ) || !qgsDoubleNear( dy, 0.0 ) ) { - minDistX = x1; - minDistY = y1; - } - else if ( t > 1.0 ) - { - minDistX = x2; - minDistY = y2; - } - else - { - minDistX = x1 + t * ( x2 - x1 ); - minDistY = y1 + t * ( y2 - y1 ); + double t = (( ptX - x1 ) * dx + ( ptY - y1 ) * dy ) / ( dx * dx + dy * dy ); + if ( t > 1 ) + { + minDistX = x2; + minDistY = y2; + } + else if ( t > 0 ) + { + minDistX += dx * t ; + minDistY += dy * t ; + } } - double dist = ( minDistX - ptX ) * ( minDistX - ptX ) + ( minDistY - ptY ) * ( minDistY - ptY ); + dx = ptX - minDistX; + dy = ptY - minDistY; + + double dist = dx * dx + dy * dy; //prevent rounding errors if the point is directly on the segment if ( qgsDoubleNear( dist, 0.0, epsilon ) ) From d5c307eb050553959bd40bd57b1564c096564d7b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 10 Nov 2016 15:58:18 +1000 Subject: [PATCH 735/897] Add method to find distance from a point to a poylgon's boundary --- python/core/geometry/qgspolygon.sip | 8 +++++++ src/core/geometry/qgspolygon.cpp | 34 +++++++++++++++++++++++++++++ src/core/geometry/qgspolygon.h | 8 +++++++ tests/src/core/testqgsgeometry.cpp | 23 +++++++++++++++++++ 4 files changed, 73 insertions(+) diff --git a/python/core/geometry/qgspolygon.sip b/python/core/geometry/qgspolygon.sip index 3f94285c06e7..b91837510319 100644 --- a/python/core/geometry/qgspolygon.sip +++ b/python/core/geometry/qgspolygon.sip @@ -35,4 +35,12 @@ class QgsPolygonV2: public QgsCurvePolygon virtual void setExteriorRing( QgsCurve* ring /Transfer/ ); virtual QgsAbstractGeometry* boundary() const /Factory/; + + /** + * Returns the distance from a point to the boundary of the polygon (either the + * exterior ring or any closer interior rings). The returned distance will be + * negative if the point lies outside the polygon. + * @note added in QGIS 3.0 + */ + double pointDistanceToBoundary( double x, double y ) const; }; diff --git a/src/core/geometry/qgspolygon.cpp b/src/core/geometry/qgspolygon.cpp index 9f3f25d82916..816f396e1a6b 100644 --- a/src/core/geometry/qgspolygon.cpp +++ b/src/core/geometry/qgspolygon.cpp @@ -261,6 +261,40 @@ QgsAbstractGeometry* QgsPolygonV2::boundary() const } } +double QgsPolygonV2::pointDistanceToBoundary( double x, double y ) const +{ + if ( !mExteriorRing ) + return std::numeric_limits< double >::quiet_NaN(); + + bool inside = false; + double minimumDistance = DBL_MAX; + double minDistX = 0.0; + double minDistY = 0.0; + + int numRings = mInteriorRings.size() + 1; + for ( int ringIndex = 0; ringIndex < numRings; ++ringIndex ) + { + const QgsLineString* ring = static_cast< const QgsLineString* >( ringIndex == 0 ? mExteriorRing : mInteriorRings.at( ringIndex - 1 ) ); + + int len = ring->numPoints() - 1; //assume closed + for ( int i = 0, j = len - 1; i < len; j = i++ ) + { + double aX = ring->xAt( i ); + double aY = ring->yAt( i ); + double bX = ring->xAt( j ); + double bY = ring->yAt( j ); + + if ((( aY > y ) != ( bY > y ) ) && + ( x < ( bX - aX ) * ( y - aY ) / ( bY - aY ) + aX ) ) + inside = !inside; + + minimumDistance = qMin( minimumDistance, QgsGeometryUtils::sqrDistToLine( x, y, aX, aY, bX, bY, minDistX, minDistY, 4 * DBL_EPSILON ) ); + } + } + + return ( inside ? 1 : -1 ) * sqrt( minimumDistance ); +} + QgsPolygonV2* QgsPolygonV2::surfaceToPolygon() const { return clone(); diff --git a/src/core/geometry/qgspolygon.h b/src/core/geometry/qgspolygon.h index 6bbff312c4ff..630284cb182e 100644 --- a/src/core/geometry/qgspolygon.h +++ b/src/core/geometry/qgspolygon.h @@ -60,5 +60,13 @@ class CORE_EXPORT QgsPolygonV2: public QgsCurvePolygon virtual QgsAbstractGeometry* boundary() const override; + /** + * Returns the distance from a point to the boundary of the polygon (either the + * exterior ring or any closer interior rings). The returned distance will be + * negative if the point lies outside the polygon. + * @note added in QGIS 3.0 + */ + double pointDistanceToBoundary( double x, double y ) const; + }; #endif // QGSPOLYGONV2_H diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index a79697146cbf..fb9cf15e549b 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -3026,6 +3026,29 @@ void TestQgsGeometry::polygon() QCOMPARE( lineBoundary->zAt( 3 ), 10.0 ); delete boundary; + // point distance to boundary + + QgsLineString pd1; + pd1.setPoints( QList() << QgsPointV2( 0, 0 ) << QgsPointV2( 1, 0 ) << QgsPointV2( 1, 1 ) << QgsPointV2( 0, 1 ) << QgsPointV2( 0, 0 ) ); + QgsPolygonV2 pd; + // no meaning, but let's not crash + ( void )pd.pointDistanceToBoundary( 0, 0 ); + + pd.setExteriorRing( pd1.clone() ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0, 0.5 ), 0.0, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0.1, 0.5 ), 0.1, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( -0.1, 0.5 ), -0.1, 0.0000000001 ); + // with a ring + QgsLineString pdRing1; + pdRing1.setPoints( QList() << QgsPointV2( 0.1, 0.1 ) << QgsPointV2( 0.2, 0.1 ) << QgsPointV2( 0.2, 0.6 ) << QgsPointV2( 0.1, 0.6 ) << QgsPointV2( 0.1, 0.1 ) ); + pd.setInteriorRings( QList< QgsCurve* >() << pdRing1.clone() ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0, 0.5 ), 0.0, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0.1, 0.5 ), 0.0, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0.01, 0.5 ), 0.01, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0.08, 0.5 ), 0.02, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( 0.12, 0.5 ), -0.02, 0.0000000001 ); + QGSCOMPARENEAR( pd.pointDistanceToBoundary( -0.1, 0.5 ), -0.1, 0.0000000001 ); + } void TestQgsGeometry::multiPoint() From d6f09c012e71cb827c2e4408783f724638094cec Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 10 Nov 2016 17:06:15 +1000 Subject: [PATCH 736/897] [FEATURE] Add method to calculate pole of inaccessibility for polygons Implements a method in QgsGeometry and a processing algorithm to calculate the pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface. This function uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative approach guaranteed to find the true pole of inaccessibility within a specified tolerance. More precise tolerances require more iterations and will take longer to calculate. --- python/core/geometry/qgsgeometry.sip | 26 ++- python/plugins/processing/algs/help/qgis.yaml | 3 + .../processing/algs/qgis/PointOnSurface.py | 3 + .../algs/qgis/PoleOfInaccessibility.py | 91 +++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 4 +- .../expected/pole_inaccessibility_polys.gfs | 32 ++++ .../expected/pole_inaccessibility_polys.gml | 58 +++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 12 ++ src/core/geometry/qgsgeometry.cpp | 7 + src/core/geometry/qgsgeometry.h | 26 ++- .../geometry/qgsinternalgeometryengine.cpp | 149 +++++++++++++++++- src/core/geometry/qgsinternalgeometryengine.h | 12 +- tests/src/core/testqgsgeometry.cpp | 122 ++++++++++++++ 13 files changed, 538 insertions(+), 7 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/PoleOfInaccessibility.py create mode 100644 python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index 1db6117ff62a..2120052547b4 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -510,15 +510,37 @@ class QgsGeometry /** Returns a simplified version of this geometry using a specified tolerance value */ QgsGeometry simplify( double tolerance ) const; - /** Returns the center of mass of a geometry + /** + * Returns the center of mass of a geometry. * @note for line based geometries, the center point of the line is returned, * and for point based geometries, the point itself is returned + * @see pointOnSurface() + * @see poleOfInaccessibility() */ QgsGeometry centroid() const; - /** Returns a point within a geometry */ + /** + * Returns a point guaranteed to lie on the surface of a geometry. While the centroid() + * of a geometry may be located outside of the geometry itself (eg for concave shapes), + * the point on surface will always be inside the geometry. + * @see centroid() + * @see poleOfInaccessibility() + */ QgsGeometry pointOnSurface() const; + /** + * Calculates the approximate pole of inaccessibility for a surface, which is the + * most distant internal point from the boundary of the surface. This function + * uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative + * approach guaranteed to find the true pole of inaccessibility within a specified + * tolerance. More precise tolerances require more iterations and will take longer + * to calculate. + * @see centroid() + * @see pointOnSurface() + * @note added in QGIS 3.0 + */ + QgsGeometry poleOfInaccessibility( double precision ) const; + /** Returns the smallest convex polygon that contains all the points in the geometry. */ QgsGeometry convexHull() const; diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index c65e965d7667..e1c0d7aba827 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -337,6 +337,9 @@ qgis:polarplot: > Two fields must be entered as parameters: one that define the category each feature two (to group features) and another one with the variable to plot (this has to be a numeric one) +qgis:poleofinaccessibility: > + This algorithm calculates the pole of inaccessibility for a polygon layer, which is the most distant internal point from the boundary of the surface. This algorithm uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative approach guaranteed to find the true pole of inaccessibility within a specified tolerance (in layer units). More precise tolerances require more iterations and will take longer to calculate. + qgis:polygoncentroids: > This algorithm creates a new point layer, with points representing the centroid of polygons of an input layer. diff --git a/python/plugins/processing/algs/qgis/PointOnSurface.py b/python/plugins/processing/algs/qgis/PointOnSurface.py index 4a814412f760..0a10d70a06df 100644 --- a/python/plugins/processing/algs/qgis/PointOnSurface.py +++ b/python/plugins/processing/algs/qgis/PointOnSurface.py @@ -45,6 +45,9 @@ class PointOnSurface(GeoAlgorithm): INPUT_LAYER = 'INPUT_LAYER' OUTPUT_LAYER = 'OUTPUT_LAYER' + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'centroids.png')) + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Point on surface') self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') diff --git a/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py b/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py new file mode 100644 index 000000000000..d491b65d38e9 --- /dev/null +++ b/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + PoleOfInaccessibility.py + ------------------------ + Date : November 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'November 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive323 + +__revision__ = '$Format:%H$' + +import os + +from qgis.core import QgsGeometry, QgsWkbTypes + +from qgis.PyQt.QtGui import QIcon + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException +from processing.core.parameters import ParameterVector, ParameterNumber +from processing.core.outputs import OutputVector +from processing.tools import dataobjects, vector + +pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] + + +class PoleOfInaccessibility(GeoAlgorithm): + + INPUT_LAYER = 'INPUT_LAYER' + TOLERANCE = 'TOLERANCE' + OUTPUT_LAYER = 'OUTPUT_LAYER' + + def getIcon(self): + return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'centroids.png')) + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Pole of Inaccessibility') + self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + + self.addParameter(ParameterVector(self.INPUT_LAYER, + self.tr('Input layer'), + [dataobjects.TYPE_VECTOR_POLYGON])) + self.addParameter(ParameterNumber(self.TOLERANCE, + self.tr('Tolerance (layer units)'), default=1.0, minValue=0.0)) + self.addOutput(OutputVector(self.OUTPUT_LAYER, self.tr('Point'), datatype=[dataobjects.TYPE_VECTOR_POINT])) + + def processAlgorithm(self, progress): + layer = dataobjects.getObjectFromUri( + self.getParameterValue(self.INPUT_LAYER)) + tolerance = self.getParameterValue(self.TOLERANCE) + + writer = self.getOutputFromName( + self.OUTPUT_LAYER).getVectorWriter( + layer.fields(), + QgsWkbTypes.Point, + layer.crs()) + + features = vector.features(layer) + total = 100.0 / len(features) + + for current, input_feature in enumerate(features): + output_feature = input_feature + input_geometry = input_feature.geometry() + if input_geometry: + output_geometry = input_geometry.poleOfInaccessibility(tolerance) + if not output_geometry: + raise GeoAlgorithmExecutionException( + self.tr('Error calculating pole of inaccessibility')) + + output_feature.setGeometry(output_geometry) + + writer.addFeature(output_feature) + progress.setPercentage(int(current * total)) + + del writer diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 1fb2006cb058..cfb5b5a38e3e 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -176,6 +176,7 @@ from .ExtractSpecificNodes import ExtractSpecificNodes from .GeometryByExpression import GeometryByExpression from .SnapGeometries import SnapGeometriesToLayer +from .PoleOfInaccessibility import PoleOfInaccessibility pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -238,7 +239,8 @@ def __init__(self): IdwInterpolationZValue(), IdwInterpolationAttribute(), TinInterpolationZValue(), TinInterpolationAttribute(), RemoveNullGeometry(), ExtractByExpression(), ExtendLines(), - ExtractSpecificNodes(), GeometryByExpression(), SnapGeometriesToLayer() + ExtractSpecificNodes(), GeometryByExpression(), SnapGeometriesToLayer(), + PoleOfInaccessibility() ] if hasMatplotlib: diff --git a/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gfs b/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gfs new file mode 100644 index 000000000000..4010a6d66fbf --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gfs @@ -0,0 +1,32 @@ + + + pole_inaccessibility_polys + pole_inaccessibility_polys + + 1 + EPSG:4326 + + 6 + 0.50000 + 6.58578 + -2.41422 + 5.50000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml b/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml new file mode 100644 index 000000000000..63040c79ea9c --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml @@ -0,0 +1,58 @@ + + + + + 0.5-2.414215087890625 + 6.5857849121093755.5 + + + + + + 0.5,0.5 + aaaaa + 33 + 44.123456 + + + + + 4.999996185302734,4.414211273193359 + Aaaaa + -33 + 0 + + + + + 2.5,5.5 + bbaaa + 0.123 + + + + + 6.585784912109375,-2.414215087890625 + ASDF + 0 + + + + + 120 + -100291.43213 + + + + + 4.289703369140625,-0.232696533203125 + elim + 2 + 3.33 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index c667aaebeecd..8318e165b703 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1464,3 +1464,15 @@ tests: OUTPUT: name: expected/snap_point_to_lines_prefer_closest.gml type: vector + + - algorithm: qgis:poleofinaccessibility + name: Pole of inaccessibility (polygons) + params: + INPUT_LAYER: + name: polys.gml + type: vector + TOLERANCE: 1.0e-05 + results: + OUTPUT_LAYER: + name: expected/pole_inaccessibility_polys.gml + type: vector diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index c2126a6d64a5..b4b187f1c42c 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -1480,6 +1480,13 @@ QgsGeometry QgsGeometry::pointOnSurface() const return QgsGeometry( pt.clone() ); } +QgsGeometry QgsGeometry::poleOfInaccessibility( double precision ) const +{ + QgsInternalGeometryEngine engine( *this ); + + return engine.poleOfInaccessibility( precision ); +} + QgsGeometry QgsGeometry::convexHull() const { if ( !d->geometry ) diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 2de8aedd9021..4e3f86c2b8f4 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -563,15 +563,37 @@ class CORE_EXPORT QgsGeometry //! Returns a simplified version of this geometry using a specified tolerance value QgsGeometry simplify( double tolerance ) const; - /** Returns the center of mass of a geometry + /** + * Returns the center of mass of a geometry. * @note for line based geometries, the center point of the line is returned, * and for point based geometries, the point itself is returned + * @see pointOnSurface() + * @see poleOfInaccessibility() */ QgsGeometry centroid() const; - //! Returns a point within a geometry + /** + * Returns a point guaranteed to lie on the surface of a geometry. While the centroid() + * of a geometry may be located outside of the geometry itself (eg for concave shapes), + * the point on surface will always be inside the geometry. + * @see centroid() + * @see poleOfInaccessibility() + */ QgsGeometry pointOnSurface() const; + /** + * Calculates the approximate pole of inaccessibility for a surface, which is the + * most distant internal point from the boundary of the surface. This function + * uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative + * approach guaranteed to find the true pole of inaccessibility within a specified + * tolerance. More precise tolerances require more iterations and will take longer + * to calculate. + * @see centroid() + * @see pointOnSurface() + * @note added in QGIS 3.0 + */ + QgsGeometry poleOfInaccessibility( double precision ) const; + //! Returns the smallest convex polygon that contains all the points in the geometry. QgsGeometry convexHull() const; diff --git a/src/core/geometry/qgsinternalgeometryengine.cpp b/src/core/geometry/qgsinternalgeometryengine.cpp index 811e3778d9b6..8d17151b2683 100644 --- a/src/core/geometry/qgsinternalgeometryengine.cpp +++ b/src/core/geometry/qgsinternalgeometryengine.cpp @@ -21,8 +21,11 @@ #include "qgspolygon.h" #include "qgsmulticurve.h" #include "qgsgeometry.h" +#include "qgsgeometryutils.h" + #include +#include QgsInternalGeometryEngine::QgsInternalGeometryEngine( const QgsGeometry& geometry ) : mGeometry( geometry.geometry() ) @@ -36,7 +39,7 @@ QgsInternalGeometryEngine::QgsInternalGeometryEngine( const QgsGeometry& geometr * See details in QEP #17 ****************************************************************************/ -QgsGeometry QgsInternalGeometryEngine::extrude( double x, double y ) +QgsGeometry QgsInternalGeometryEngine::extrude( double x, double y ) const { QList linesToProcess; @@ -87,3 +90,147 @@ QgsGeometry QgsInternalGeometryEngine::extrude( double x, double y ) return QgsGeometry(); } + + + +// polylabel implementation +// ported from the original Javascript implementation developed by Vladimir Agafonkin +// originally licensed under the ISC License + +class Cell +{ + public: + Cell( double x, double y, double h, const QgsPolygonV2* polygon ) + : x( x ) + , y( y ) + , h( h ) + , d( polygon->pointDistanceToBoundary( x, y ) ) + , max( d + h * M_SQRT2 ) + {} + + //! Cell center x + double x; + //! Cell center y + double y; + //! Half the cell size + double h; + //! Distance from cell center to polygon + double d; + //! Maximum distance to polygon within a cell + double max; +}; + +struct GreaterThanByMax +{ + bool operator()( const Cell* lhs, const Cell* rhs ) + { + return rhs->max > lhs->max; + } +}; + +Cell* getCentroidCell( const QgsPolygonV2* polygon ) +{ + double area = 0; + double x = 0; + double y = 0; + + const QgsLineString* exterior = static_cast< const QgsLineString*>( polygon->exteriorRing() ); + int len = exterior->numPoints() - 1; //assume closed + for ( int i = 0, j = len - 1; i < len; j = i++ ) + { + double aX = exterior->xAt( i ); + double aY = exterior->yAt( i ); + double bX = exterior->xAt( j ); + double bY = exterior->yAt( j ); + double f = aX * bY - bX * aY; + x += ( aX + bX ) * f; + y += ( aY + bY ) * f; + area += f * 3; + } + if ( area == 0 ) + return new Cell( exterior->xAt( 0 ), exterior->yAt( 0 ), 0, polygon ); + else + return new Cell( x / area, y / area, 0.0, polygon ); +} + + +QgsGeometry QgsInternalGeometryEngine::poleOfInaccessibility( double precision ) const +{ + if ( !mGeometry || mGeometry->isEmpty() ) + return QgsGeometry(); + + if ( precision <= 0 ) + return QgsGeometry(); + + const QgsSurface* surface = dynamic_cast< const QgsSurface* >( mGeometry ); + if ( !surface ) + return QgsGeometry(); + + QScopedPointer< QgsPolygonV2 > segmentizedPoly; + const QgsPolygonV2* polygon = dynamic_cast< const QgsPolygonV2* >( mGeometry ); + if ( !polygon ) + { + segmentizedPoly.reset( static_cast< QgsPolygonV2*>( surface->segmentize() ) ); + polygon = segmentizedPoly.data(); + } + + // start with the bounding box + QgsRectangle bounds = polygon->boundingBox(); + + // initial parameters + double cellSize = qMin( bounds.width(), bounds.height() ); + + if ( qgsDoubleNear( cellSize, 0.0 ) ) + return QgsGeometry( new QgsPointV2( bounds.xMinimum(), bounds.yMinimum() ) ); + + double h = cellSize / 2.0; + std::priority_queue< Cell*, std::vector, GreaterThanByMax > cellQueue; + + // cover polygon with initial cells + for ( double x = bounds.xMinimum(); x < bounds.xMaximum(); x += cellSize ) + { + for ( double y = bounds.yMinimum(); y < bounds.yMaximum(); y += cellSize ) + { + cellQueue.push( new Cell( x + h, y + h, h, polygon ) ); + } + } + + // take centroid as the first best guess + QScopedPointer< Cell > bestCell( getCentroidCell( polygon ) ); + + // special case for rectangular polygons + QScopedPointer< Cell > bboxCell( new Cell( bounds.xMinimum() + bounds.width() / 2.0, + bounds.yMinimum() + bounds.height() / 2.0, + 0, polygon ) ); + if ( bboxCell->d > bestCell->d ) + { + bestCell.reset( bboxCell.take() ); + } + + while ( cellQueue.size() > 0 ) + { + // pick the most promising cell from the queue + QScopedPointer< Cell > cell( cellQueue.top() ); + cellQueue.pop(); + Cell* currentCell = cell.data(); + + // update the best cell if we found a better one + if ( currentCell->d > bestCell->d ) + { + bestCell.reset( cell.take() ); + } + + // do not drill down further if there's no chance of a better solution + if ( currentCell->max - bestCell->d <= precision ) + continue; + + // split the cell into four cells + h = currentCell->h / 2.0; + cellQueue.push( new Cell( currentCell->x - h, currentCell->y - h, h, polygon ) ); + cellQueue.push( new Cell( currentCell->x + h, currentCell->y - h, h, polygon ) ); + cellQueue.push( new Cell( currentCell->x - h, currentCell->y + h, h, polygon ) ); + cellQueue.push( new Cell( currentCell->x + h, currentCell->y + h, h, polygon ) ); + } + + return QgsGeometry( new QgsPointV2( bestCell->x, bestCell->y ) ); +} diff --git a/src/core/geometry/qgsinternalgeometryengine.h b/src/core/geometry/qgsinternalgeometryengine.h index f6d1eff3df31..636d42a1fd1d 100644 --- a/src/core/geometry/qgsinternalgeometryengine.h +++ b/src/core/geometry/qgsinternalgeometryengine.h @@ -48,7 +48,17 @@ class QgsInternalGeometryEngine * @param y offset in y direction * @return an extruded polygon */ - QgsGeometry extrude( double x, double y ); + QgsGeometry extrude( double x, double y ) const; + + /** + * Calculates the approximate pole of inaccessibility for a surface, which is the + * most distant internal point from the boundary of the surface. This function + * uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative + * approach guaranteed to find the true pole of inaccessibility within a specified + * tolerance. More precise tolerances require more iterations and will take longer + * to calculate. + */ + QgsGeometry poleOfInaccessibility( double precision ) const; private: const QgsAbstractGeometry* mGeometry; diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index fb9cf15e549b..9027bf6cb6c8 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -109,6 +109,7 @@ class TestQgsGeometry : public QObject void wkbInOut(); void segmentizeCircularString(); + void poleOfInaccessibility(); private: //! A helper method to do a render check to see if the geometry op is as expected @@ -3880,5 +3881,126 @@ void TestQgsGeometry::segmentizeCircularString() QVERIFY( points.contains( QgsPointV2( 0.5, 0.5 ) ) ); } +void TestQgsGeometry::poleOfInaccessibility() +{ + QString poly1Wkt( "Polygon ((3116 3071, 3394 3431, 3563 3362, 3611 3205, 3599 3181, 3477 3281, 3449 3160, 3570 3127, 3354 3116," + " 3436 3008, 3158 2907, 2831 2438, 3269 2916, 3438 2885, 3295 2799, 3407 2772, 3278 2629, 3411 2689, 3329 2611," + " 3360 2531, 3603 2800, 3598 2501, 3317 2429, 3329 2401, 3170 2340, 3142 2291, 3524 2403, 3598 2233, 3460 2117," + " 3590 1931, 3364 1753, 3597 1875, 3639 1835, 3660 1733, 3600 1771, 3538 1694, 3661 1732, 3359 1554, 3334 1554," + " 3341 1588, 3317 1588, 3305 1644, 3286 1656, 3115 1255, 3072 1252, 3078 1335, 3046 1355, 2984 1234, 2983 1409," + " 2876 1222, 2525 1161, 2488 787, 2162 913, 2079 661, 2270 380, 2188 823, 2510 592, 2659 992, 2911 1118, 2943 938," + " 2957 1097, 3092 1002, 3006 1097, 3233 1282, 3325 1291, 3296 1116, 3333 1115, 3391 1333, 3434 1274, 3413 1326," + " 3449 1327, 3473 1408, 3490 1430, 3526 1434, 3198 -112, 3263 -87, 3289 -128, 4224 -128, 4224 -128, 3474 -128," + " 3475 -116, 3486 -120, 3458 -49, 3523 -78, 3513 -128, 3509 -119, 3509 -128, 3717 -128, 3705 -60, 3735 -16," + " 3714 38, 3758 88, 3825 47, 3812 -11, 3859 -51, 3871 49, 3760 149, 3636 -74, 3510 126, 3501 245, 3504 270," + " 3511 284, 3582 16, 3631 19, 3569 125, 3570 193, 3610 212, 3583 119, 3655 29, 3738 170, 3561 466, 3826 549," + " 3527 604, 3609 833, 3681 798, 3956 1127, 3917 964, 4043 850, 4049 1096, 4193 1052, 4191 1078, 4208 1106," + " 4222 1110, 4224 1109, 4224 1144, 4202 1158, 4177 1161, 4182 1181, 4075 1201, 4141 1275, 4215 1215, 4221 1223," + " 4219 1231, 4224 1243, 4224 1257, 4224 1262, 4224 1345, 4224 1339, 4224 1328, 4215 1335, 4203 1355, 4215 1369," + " 4224 1363, 4215 1377, 4208 1387, 4217 1401, 4224 1403, 4224 1520, 4219 1535, 4221 1544, 4199 1593, 4223 1595," + " 4206 1626, 4214 1648, 4224 1645, 4224 1640, 4224 2108, 4220 2125, 4224 2125, 4224 2143, 4205 2141, 4180 2159," + " 4201 2182, 4163 2189, 4176 2229, 4199 2211, 4210 2218, 4212 2210, 4223 2214, 4224 2207, 4224 2216, 4217 2225," + " 4221 2233, 4203 2227, 4209 2248, 4185 2240, 4198 2276, 4144 2218, 4091 2343, 4119 2332, 4121 2347, 4155 2337," + " 4180 2355, 4200 2342, 4201 2354, 4213 2352, 4224 2348, 4224 2356, 4207 2361, 4184 2358, 4176 2367, 4106 2355," + " 3983 2765, 4050 3151, 4139 2720, 4209 2589, 4211 2600, 4219 2599, 4224 2592, 4224 2574, 4223 2566, 4224 2562," + " 4224 2553, 4224 2552, 4224 -128, 4224 4224, 4205 4224, 4015 3513, 3993 3494, 3873 3533, 3887 3539, 3923 3524," + " 3950 3529, 4018 3572, 3987 3633, 3983 3571, 3955 3583, 3936 3547, 3882 3539, 3913 3557, 3920 3598, 3901 3596," + " 3923 3631, 3914 3628, 3919 3647, 3922 3656, 3917 3666, 3523 3438, 3631 3564, 3527 3597, 3718 3655, 3578 3672," + " 3660 3867, 3543 3628, 3416 3725, 3487 3503, 3274 3583, 3271 3644, 3197 3671, 3210 3775, 3184 3788, 3181 3672," + " 3306 3521, 3292 3508, 3229 3565, 3219 3564, 3216 3574, 3192 3578, 3297 3444, 3089 3395, 3029 3028, 2973 3133," + " 2529 2945, 2538 2811, 2461 2901, 2170 2839, 2121 2797, 2156 2733, 2105 2709, 2096 2695, 2114 2621, 2102 2693," + " 2168 2738, 2167 2778, 2447 2765, 2441 2866, 2527 2793, 2670 2938, 2626 2651, 2688 2623, 2740 2922, 3084 2960," + " 3116 3071),(4016 1878, 4029 1859, 4008 1839, 4006 1863, 4016 1878),(3315 1339, 3331 1324, 3290 1293, 3305 1315," + " 3315 1339),(4136 3071, 4136 3080, 4143 3020, 4137 3036, 4136 3071),(4218 3073, 4183 3114, 4117 3157, 4159 3147," + " 4218 3073),(3912 3542, 3934 3536, 3955 3536, 3937 3527, 3900 3540, 3912 3542),(4050 3172, 4043 3210, 4085 3209," + " 4090 3179, 4050 3172),(4151 2998, 4158 2977, 4159 2946, 4147 2988, 4151 2998),(2920 3005, 2935 2994, 2864 2973," + " 2905 3016, 2920 3005),(3571 2424, 3545 2469, 3608 2480, 3596 2434, 3571 2424),(4095 1229, 4073 1234, 4076 1293," + " 4121 1285, 4095 1229),(4173 1536, 4153 1576, 4166 1585, 4198 1571, 4188 1532, 4213 1535, 4224 1512, 4224 1511," + " 4209 1511, 4198 1506, 4190 1517, 4194 1509, 4192 1499, 4200 1496, 4202 1504, 4224 1510, 4224 1488, 4215 1486," + " 4216 1478, 4224 1472, 4224 1464, 4207 1458, 4193 1464, 4173 1536),(3934 1537, 3968 1630, 3960 1666, 3968 1673," + " 3975 1562, 3934 1537),(4182 1653, 4196 1624, 4166 1614, 4157 1674, 4216 1671, 4182 1653),(4200 1619, 4196 1620," + " 4200 1632, 4195 1642, 4207 1648, 4200 1619),(4026 1835, 4025 1830, 4016 1808, 4007 1836, 4026 1835),(4199 1384," + " 4182 1389, 4206 1412, 4216 1401, 4199 1384),(3926 1251, 3969 1206, 3913 1149, 3878 1173, 3876 1229, 3926 1251)," + " (3926 1354, 3958 1389, 3997 1384, 3991 1352, 3960 1322, 3955 1299, 3926 1354),(3964 1319, 3974 1329, 3984 1285," + " 3963 1301, 3964 1319),(3687 959, 3696 903, 3678 885, 3665 930, 3687 959),(3452 79, 3437 124, 3456 149, 3476 141," + " 3452 79),(3751 927, 3738 906, 3719 942, 3739 929, 3751 927))" ); + + QString poly2Wkt( "Polygon ((-128 4224, -128 2734, -11 2643, -101 2919, 120 2654, 19 2846, 217 2897, -13 2873, -79 2998, -106 2989," + " -128 3002, -128 4224, -128 4224, 1249 4224, 1247 4199, 1231 4132, 909 3902, 775 3278, 509 2903, 470 2603, 663 2311," + " 889 2134, 989 2146, 534 2585, 575 2880, 833 3112, 833 3037, 1025 2977, 834 3096, 946 3217, 923 3153, 971 3094," + " 997 3103, 1166 3423, 1198 3329, 1233 3367, 1270 3327, 1274 3354, 1290 3360, 1321 3322, 1331 3318, 1343 3325," + " 1310 3073, 1363 3093, 1413 3186, 1325 3398, 1458 3364, 1493 3426, 1526 3394, 1588 3465, 1417 3824, 1458 3825," + " 1522 3849, 1729 3488, 2018 3223, 1908 3291, 1924 3238, 1899 3187, 1913 3150, 2070 3041, 2102 3063, 2112 3053," + " 2168 3085, 2101 2994, 2265 2863, 1890 2593, 2106 2713, 2130 2706, 2108 2678, 2117 2647, 2105 2636, 2099 2604," + " 2094 2591, 2088 2575, 2088 2564, 2249 2751, 2441 2618, 2689 1728, 2681 2323, 2776 1685, 2711 1708, 2673 1680," + " 2675 1639, 2810 1522, 2765 1535, 2734 1510, 2850 1332, 2863 1186, 2847 1025, 2832 985, 2739 1025, 2850 1090," + " 2859 1174, 2853 1235, 2827 1235, 2839 1279, 2811 1286, 2751 1272, 2851 1160, 2788 1159, 2724 1204, 2713 1198," + " 2708 1213, 2699 1221, 2724 1179, 2797 1145, 2785 1123, 2848 1143, 2821 1092, 2284 980, 2288 963, 2264 962," + " 2261 948, 2247 958, 2194 947, 2120 900, 2047 809, 2434 923, 2450 817, 2528 737, 2527 667, 2641 544, 2641 460," + " 2710 452, 2687 447, 2681 435, 2693 330, 2772 327, 2766 291, 2779 245, 2769 219, 2771 198, 2816 219, 2781 342," + " 2612 647, 2903 188, 2803 539, 2950 206, 2927 342, 3123 339, 3092 300, 3073 175, 3082 160, 3412 -103, 4224 -128," + " 4032 167, 3572 63, 3554 109, 3606 211, 3604 232, 3454 124, 3332 345, 3237 212, 3181 415, 2953 364, 2761 692," + " 2819 788, 2997 769, 2997 626, 3199 659, 3155 730, 2929 805, 2908 841, 3218 717, 3276 744, 3246 723, 3270 658," + " 4223 473, 4224 589, 3906 681, 3818 677, 3915 686, 4224 592, 4224 4224, -128 4224, -128 4224),(2049 3181," + " 2224 3084, 2204 3040, 2169 3036, 2174 3084, 2155 3102, 2126 3123, 2109 3127, 2103 3102, 2049 3181),(1578 3811," + " 1567 3883, 1675 3768, 1658 3712, 1659 3751, 1578 3811),(2304 2930, 2335 2918, 2287 2880, 2279 2926, 2304 2930)," + " (2316 2895, 2317 2895, 2316 2901, 2331 2901, 2332 2889, 2316 2895),(2304 2850, 2335 2861, 2344 2910, 2357 2828," + " 2304 2850),(1714 3583, 1725 3638, 1682 3717, 1797 3564, 1714 3583),(1537 3873, 1456 3827, 1405 3876, 1461 3898," + " 1537 3873),(2547 2560, 2375 2815, 2384 2825, 2470 2722, 2685 2336, 2648 2310, 2547 2560),(2107 3073, 2107 3098," + " 2144 3086, 2122 3073, 2113 3059, 2107 3073),(2117 3120, 2156 3099, 2164 3083, 2106 3103, 2117 3120),(2303 2981," + " 2226 3010, 2232 3064, 2286 3012, 2344 2928, 2303 2981),(2304 2858, 2291 2864, 2303 2885, 2324 2870, 2304 2858)," + " (2175 3002, 2179 2983, 2152 2991, 2175 3002, 2175 3002),(2175 3022, 2150 3017, 2144 3048, 2159 3031, 2184 3030," + " 2175 3022),(2265 2953, 2270 2950, 2262 2950, 2254 2963, 2253 2979, 2265 2953),(2229 2928, 2250 2928, 2241 2922," + " 2239 2914, 2224 2900, 2237 2914, 2229 2928),(2531 2473, 2520 2466, 2521 2474, 2511 2503, 2531 2473),(2547 2526," + " 2529 2519, 2528 2541, 2544 2538, 2547 2526),(2559 646, 2513 810, 2463 835, 2462 930, 2746 731, 2559 646),(3840 653," + " 3809 641, 3718 689, 3547 733, 3553 712, 3440 780, 3840 653),(3327 741, 3242 750, 3195 745, 3180 758, 3326 764," + " 3440 742, 3327 741),(3282 702, 3265 699, 3273 721, 3290 714, 3282 702),(3762 662, 3783 654, 3786 638, 3742 653," + " 3762 662),(3071 703, 3082 741, 3079 655, 3064 657, 3071 703),(3881 637, 3904 647, 3914 626, 3861 638, 3881 637))" ); + + QgsGeometry poly1 = QgsGeometry::fromWkt( poly1Wkt ); + QgsGeometry poly2 = QgsGeometry::fromWkt( poly2Wkt ); + + QgsPoint point = poly1.poleOfInaccessibility( 1 ).asPoint(); + QGSCOMPARENEAR( point.x(), 3867.37, 0.01 ); + QGSCOMPARENEAR( point.y(), 2126.45, 0.01 ); + + point = poly1.poleOfInaccessibility( 50 ).asPoint(); + QGSCOMPARENEAR( point.x(), 3855.33, 0.01 ); + QGSCOMPARENEAR( point.y(), 2117.55, 0.01 ); + + point = poly2.poleOfInaccessibility( 1 ).asPoint(); + QGSCOMPARENEAR( point.x(), 3263.50, 0.01 ); + QGSCOMPARENEAR( point.y(), 3263.50, 0.01 ); + + //test degenerate polygons + QgsGeometry degen1 = QgsGeometry::fromWkt( "Polygon(( 0 0, 1 0, 2 0, 0 0 ))" ); + point = degen1.poleOfInaccessibility( 1 ).asPoint(); + QGSCOMPARENEAR( point.x(), 0, 0.01 ); + QGSCOMPARENEAR( point.y(), 0, 0.01 ); + + QgsGeometry degen2 = QgsGeometry::fromWkt( "Polygon(( 0 0, 1 0, 1 1 , 1 0, 0 0 ))" ); + point = degen2.poleOfInaccessibility( 1 ).asPoint(); + QGSCOMPARENEAR( point.x(), 0, 0.01 ); + QGSCOMPARENEAR( point.y(), 0, 0.01 ); + + //empty geometry + QVERIFY( QgsGeometry().poleOfInaccessibility( 1 ).isEmpty() ); + + // not a polygon + QgsGeometry lineString = QgsGeometry::fromWkt( "LineString(1 0, 2 2 )" ); + QVERIFY( lineString.poleOfInaccessibility( 1 ).isEmpty() ); + + // invalid threshold + QVERIFY( poly1.poleOfInaccessibility( -1 ).isEmpty() ); + QVERIFY( poly1.poleOfInaccessibility( 0 ).isEmpty() ); + + // curved geometry + QgsGeometry curved = QgsGeometry::fromWkt( "CurvePolygon( CompoundCurve( CircularString(-0.44 0.35, 0.51 0.34, 0.56 0.21, 0.11 -0.33, 0.15 -0.35," + "-0.93 -0.30, -1.02 -0.22, -0.49 0.01, -0.23 -0.04),(-0.23 -0.04, -0.44, 0.35)))" ); + point = curved.poleOfInaccessibility( 0.01 ).asPoint(); + QGSCOMPARENEAR( point.x(), -0.4324, 0.0001 ); + QGSCOMPARENEAR( point.y(), -0.2434, 0.0001 ); +} + QTEST_MAIN( TestQgsGeometry ) #include "testqgsgeometry.moc" From b44093914b09dee0fa02f9b25cded93c3d623df2 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 10 Nov 2016 20:53:47 +1000 Subject: [PATCH 737/897] Fix test failure, report distance from pole --- python/core/geometry/qgsgeometry.sip | 3 ++- python/plugins/processing/algs/help/qgis.yaml | 2 ++ .../algs/qgis/PoleOfInaccessibility.py | 17 ++++++++++++++--- .../expected/pole_inaccessibility_polys.gml | 5 +++++ src/core/geometry/qgsgeometry.cpp | 4 ++-- src/core/geometry/qgsgeometry.h | 3 ++- src/core/geometry/qgsinternalgeometryengine.cpp | 10 +++++++++- src/core/geometry/qgsinternalgeometryengine.h | 3 ++- tests/src/core/testqgsgeometry.cpp | 4 +++- 9 files changed, 41 insertions(+), 10 deletions(-) diff --git a/python/core/geometry/qgsgeometry.sip b/python/core/geometry/qgsgeometry.sip index 2120052547b4..2fe77f34ceed 100644 --- a/python/core/geometry/qgsgeometry.sip +++ b/python/core/geometry/qgsgeometry.sip @@ -535,11 +535,12 @@ class QgsGeometry * approach guaranteed to find the true pole of inaccessibility within a specified * tolerance. More precise tolerances require more iterations and will take longer * to calculate. + * Optionally, the distance to the polygon boundary from the pole can be stored. * @see centroid() * @see pointOnSurface() * @note added in QGIS 3.0 */ - QgsGeometry poleOfInaccessibility( double precision ) const; + QgsGeometry poleOfInaccessibility( double precision, double* distanceToBoundary /Out/ = nullptr ) const; /** Returns the smallest convex polygon that contains all the points in the geometry. */ QgsGeometry convexHull() const; diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index e1c0d7aba827..fab282a91739 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -340,6 +340,8 @@ qgis:polarplot: > qgis:poleofinaccessibility: > This algorithm calculates the pole of inaccessibility for a polygon layer, which is the most distant internal point from the boundary of the surface. This algorithm uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative approach guaranteed to find the true pole of inaccessibility within a specified tolerance (in layer units). More precise tolerances require more iterations and will take longer to calculate. + The distance from the calculated pole to the polygon boundary will be stored as a new attribute in the output layer. + qgis:polygoncentroids: > This algorithm creates a new point layer, with points representing the centroid of polygons of an input layer. diff --git a/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py b/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py index d491b65d38e9..cad2c55d5d99 100644 --- a/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py +++ b/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py @@ -27,8 +27,9 @@ import os -from qgis.core import QgsGeometry, QgsWkbTypes +from qgis.core import QgsGeometry, QgsWkbTypes, QgsField, NULL +from qgis.PyQt.QtCore import QVariant from qgis.PyQt.QtGui import QIcon from processing.core.GeoAlgorithm import GeoAlgorithm @@ -65,9 +66,12 @@ def processAlgorithm(self, progress): self.getParameterValue(self.INPUT_LAYER)) tolerance = self.getParameterValue(self.TOLERANCE) + fields = layer.fields() + fields.append(QgsField('dist_pole', QVariant.Double)) + writer = self.getOutputFromName( self.OUTPUT_LAYER).getVectorWriter( - layer.fields(), + fields, QgsWkbTypes.Point, layer.crs()) @@ -78,12 +82,19 @@ def processAlgorithm(self, progress): output_feature = input_feature input_geometry = input_feature.geometry() if input_geometry: - output_geometry = input_geometry.poleOfInaccessibility(tolerance) + output_geometry, distance = input_geometry.poleOfInaccessibility(tolerance) if not output_geometry: raise GeoAlgorithmExecutionException( self.tr('Error calculating pole of inaccessibility')) + attrs = input_feature.attributes() + attrs.append(distance) + output_feature.setAttributes(attrs) output_feature.setGeometry(output_geometry) + else: + attrs = input_feature.attributes() + attrs.append(NULL) + output_feature.setAttributes(attrs) writer.addFeature(output_feature) progress.setPercentage(int(current * total)) diff --git a/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml b/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml index 63040c79ea9c..172bfe405437 100644 --- a/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml +++ b/python/plugins/processing/tests/testdata/expected/pole_inaccessibility_polys.gml @@ -17,6 +17,7 @@ aaaaa 33 44.123456 + 1.5 @@ -25,6 +26,7 @@ Aaaaa -33 0 + 0.414211273193359 @@ -32,6 +34,7 @@ 2.5,5.5 bbaaa 0.123 + 0.5 @@ -39,6 +42,7 @@ 6.585784912109375,-2.414215087890625 ASDF 0 + 0.585784912109375 @@ -53,6 +57,7 @@ elim 2 3.33 + 1.71028189541736 diff --git a/src/core/geometry/qgsgeometry.cpp b/src/core/geometry/qgsgeometry.cpp index b4b187f1c42c..ff672118b2cd 100644 --- a/src/core/geometry/qgsgeometry.cpp +++ b/src/core/geometry/qgsgeometry.cpp @@ -1480,11 +1480,11 @@ QgsGeometry QgsGeometry::pointOnSurface() const return QgsGeometry( pt.clone() ); } -QgsGeometry QgsGeometry::poleOfInaccessibility( double precision ) const +QgsGeometry QgsGeometry::poleOfInaccessibility( double precision, double* distanceToBoundary ) const { QgsInternalGeometryEngine engine( *this ); - return engine.poleOfInaccessibility( precision ); + return engine.poleOfInaccessibility( precision, distanceToBoundary ); } QgsGeometry QgsGeometry::convexHull() const diff --git a/src/core/geometry/qgsgeometry.h b/src/core/geometry/qgsgeometry.h index 4e3f86c2b8f4..21e9d2774403 100644 --- a/src/core/geometry/qgsgeometry.h +++ b/src/core/geometry/qgsgeometry.h @@ -588,11 +588,12 @@ class CORE_EXPORT QgsGeometry * approach guaranteed to find the true pole of inaccessibility within a specified * tolerance. More precise tolerances require more iterations and will take longer * to calculate. + * Optionally, the distance to the polygon boundary from the pole can be stored. * @see centroid() * @see pointOnSurface() * @note added in QGIS 3.0 */ - QgsGeometry poleOfInaccessibility( double precision ) const; + QgsGeometry poleOfInaccessibility( double precision, double* distanceToBoundary = nullptr ) const; //! Returns the smallest convex polygon that contains all the points in the geometry. QgsGeometry convexHull() const; diff --git a/src/core/geometry/qgsinternalgeometryengine.cpp b/src/core/geometry/qgsinternalgeometryengine.cpp index 8d17151b2683..d9d9b236b297 100644 --- a/src/core/geometry/qgsinternalgeometryengine.cpp +++ b/src/core/geometry/qgsinternalgeometryengine.cpp @@ -97,6 +97,7 @@ QgsGeometry QgsInternalGeometryEngine::extrude( double x, double y ) const // ported from the original Javascript implementation developed by Vladimir Agafonkin // originally licensed under the ISC License +/// @cond PRIVATE class Cell { public: @@ -153,9 +154,13 @@ Cell* getCentroidCell( const QgsPolygonV2* polygon ) return new Cell( x / area, y / area, 0.0, polygon ); } +///@endcond -QgsGeometry QgsInternalGeometryEngine::poleOfInaccessibility( double precision ) const +QgsGeometry QgsInternalGeometryEngine::poleOfInaccessibility( double precision , double* distanceFromBoundary ) const { + if ( distanceFromBoundary ) + *distanceFromBoundary = DBL_MAX; + if ( !mGeometry || mGeometry->isEmpty() ) return QgsGeometry(); @@ -232,5 +237,8 @@ QgsGeometry QgsInternalGeometryEngine::poleOfInaccessibility( double precision ) cellQueue.push( new Cell( currentCell->x + h, currentCell->y + h, h, polygon ) ); } + if ( distanceFromBoundary ) + *distanceFromBoundary = bestCell->d; + return QgsGeometry( new QgsPointV2( bestCell->x, bestCell->y ) ); } diff --git a/src/core/geometry/qgsinternalgeometryengine.h b/src/core/geometry/qgsinternalgeometryengine.h index 636d42a1fd1d..c400e259265a 100644 --- a/src/core/geometry/qgsinternalgeometryengine.h +++ b/src/core/geometry/qgsinternalgeometryengine.h @@ -57,8 +57,9 @@ class QgsInternalGeometryEngine * approach guaranteed to find the true pole of inaccessibility within a specified * tolerance. More precise tolerances require more iterations and will take longer * to calculate. + * Optionally, the distance to the polygon boundary from the pole can be stored. */ - QgsGeometry poleOfInaccessibility( double precision ) const; + QgsGeometry poleOfInaccessibility( double precision, double* distanceFromBoundary = nullptr ) const; private: const QgsAbstractGeometry* mGeometry; diff --git a/tests/src/core/testqgsgeometry.cpp b/tests/src/core/testqgsgeometry.cpp index 9027bf6cb6c8..3fbc122db410 100644 --- a/tests/src/core/testqgsgeometry.cpp +++ b/tests/src/core/testqgsgeometry.cpp @@ -3960,9 +3960,11 @@ void TestQgsGeometry::poleOfInaccessibility() QgsGeometry poly1 = QgsGeometry::fromWkt( poly1Wkt ); QgsGeometry poly2 = QgsGeometry::fromWkt( poly2Wkt ); - QgsPoint point = poly1.poleOfInaccessibility( 1 ).asPoint(); + double distance; + QgsPoint point = poly1.poleOfInaccessibility( 1 , &distance ).asPoint(); QGSCOMPARENEAR( point.x(), 3867.37, 0.01 ); QGSCOMPARENEAR( point.y(), 2126.45, 0.01 ); + QGSCOMPARENEAR( distance, 289.51, 0.01 ); point = poly1.poleOfInaccessibility( 50 ).asPoint(); QGSCOMPARENEAR( point.x(), 3855.33, 0.01 ); From 880647e50ecaf5964392f0ebdb01eb2c02f3e1e1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 10 Nov 2016 21:58:51 +1000 Subject: [PATCH 738/897] Add some tags to algorithm --- python/plugins/processing/algs/qgis/PoleOfInaccessibility.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py b/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py index cad2c55d5d99..ae1f45a577c5 100644 --- a/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py +++ b/python/plugins/processing/algs/qgis/PoleOfInaccessibility.py @@ -53,6 +53,7 @@ def getIcon(self): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Pole of Inaccessibility') self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + self.tags = self.tr('furthest,point,distant,extreme,maximum,centroid,center,centre') self.addParameter(ParameterVector(self.INPUT_LAYER, self.tr('Input layer'), From 1f81a7c4fc2279f895a91dd3e694730c1bd02704 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 11 Nov 2016 07:41:03 +1000 Subject: [PATCH 739/897] [FEATURE] pole_of_inaccessibility expression function Exposes calculation of pole of inaccessiblity to expression engine --- resources/function_help/json/pole_of_inaccessibility | 8 ++++++++ src/core/qgsexpression.cpp | 12 ++++++++++++ tests/src/core/testqgsexpression.cpp | 5 +++++ 3 files changed, 25 insertions(+) create mode 100644 resources/function_help/json/pole_of_inaccessibility diff --git a/resources/function_help/json/pole_of_inaccessibility b/resources/function_help/json/pole_of_inaccessibility new file mode 100644 index 000000000000..0a697cba4e8c --- /dev/null +++ b/resources/function_help/json/pole_of_inaccessibility @@ -0,0 +1,8 @@ +{ + "name": "pole_of_inaccessibility", + "type": "function", + "description": "Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal point from the boundary of the surface. This function uses the 'polylabel' algorithm (Vladimir Agafonkin, 2016), which is an iterative approach guaranteed to find the true pole of inaccessibility within a specified tolerance. More precise tolerances require more iterations and will take longer to calculate.", + "arguments": [ {"arg":"geometry","description":"a geometry"}, + {"arg":"tolerance","description":"maximum distance between the returned point and the true pole location"}], + "examples": [ { "expression":"geom_to_wkt(pole_of_inaccessibility( geom_from_wkt('POLYGON((0 1,0 9,3 10,3 3, 10 3, 10 1, 0 1))'), 0.1))", "returns":"Point(1.55, 1.55)"}] +} diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 9a2037a14180..94bc8ff2d5bd 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -2582,6 +2582,16 @@ static QVariant fcnPointOnSurface( const QVariantList& values, const QgsExpressi QVariant result = !geom.isEmpty() ? QVariant::fromValue( geom ) : QVariant(); return result; } + +static QVariant fcnPoleOfInaccessibility( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QgsGeometry fGeom = getGeometry( values.at( 0 ), parent ); + double tolerance = getDoubleValue( values.at( 1 ), parent ); + QgsGeometry geom = fGeom.poleOfInaccessibility( tolerance ); + QVariant result = !geom.isEmpty() ? QVariant::fromValue( geom ) : QVariant(); + return result; +} + static QVariant fcnConvexHull( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) { QgsGeometry fGeom = getGeometry( values.at( 0 ), parent ); @@ -3919,6 +3929,8 @@ const QList& QgsExpression::Functions() fcnExtend, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "centroid" ), 1, fcnCentroid, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "point_on_surface" ), 1, fcnPointOnSurface, QStringLiteral( "GeometryGroup" ) ) + << new StaticFunction( QStringLiteral( "pole_of_inaccessibility" ), ParameterList() << Parameter( QStringLiteral( "geometry" ) ) + << Parameter( QStringLiteral( "tolerance" ) ), fcnPoleOfInaccessibility, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "reverse" ), 1, fcnReverse, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "exterior_ring" ), 1, fcnExteriorRing, QStringLiteral( "GeometryGroup" ) ) << new StaticFunction( QStringLiteral( "interior_ring_n" ), 2, fcnInteriorRingN, QStringLiteral( "GeometryGroup" ) ) diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index ff5a62819b9b..b0ba3c7aa0fd 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -733,6 +733,11 @@ class TestQgsExpression: public QObject QTest::newRow( "point on surface line" ) << "geom_to_wkt(point_on_surface( geomFromWKT('LINESTRING (-1 2, 9 12)') ))" << false << QVariant( "Point (-1 2)" ); QTest::newRow( "point on surface not geom" ) << "point_on_surface('g')" << true << QVariant(); QTest::newRow( "point on surface null" ) << "point_on_surface(NULL)" << false << QVariant(); + QTest::newRow( "pole_of_inaccessibility polygon" ) << "round(x(pole_of_inaccessibility( geomFromWKT('POLYGON((0 1,0 9,3 10,3 3, 10 3, 10 1, 0 1))'), 0.1))*100)" << false << QVariant( 155 ); + QTest::newRow( "pole_of_inaccessibility polygon" ) << "round(y(pole_of_inaccessibility( geomFromWKT('POLYGON((0 1,0 9,3 10,3 3, 10 3, 10 1, 0 1))'), 0.1))*100)" << false << QVariant( 255 ); + QTest::newRow( "pole_of_inaccessibility not poly" ) << "geom_to_wkt(pole_of_inaccessibility( geomFromWKT('POINT (1.5 0.5)'), 0.1 ))" << false << QVariant(); + QTest::newRow( "pole_of_inaccessibility not geom" ) << "pole_of_inaccessibility('g',0.1)" << true << QVariant(); + QTest::newRow( "pole_of_inaccessibility null" ) << "pole_of_inaccessibility(NULL,0.1)" << false << QVariant(); QTest::newRow( "is_closed not geom" ) << "is_closed('g')" << true << QVariant(); QTest::newRow( "is_closed null" ) << "is_closed(NULL)" << false << QVariant(); QTest::newRow( "is_closed point" ) << "is_closed(geom_from_wkt('POINT(1 2)'))" << false << QVariant(); From 798bc09130395659aee7f1f777c2b4378e2b51df Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 14 Nov 2016 15:36:58 +0800 Subject: [PATCH 740/897] Fix conversion from WKB to string in postgres provider (follow up d729951) --- src/providers/postgres/qgspostgresprovider.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index c4ce906cdd9b..b5ae64f944b2 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -2499,7 +2499,7 @@ void QgsPostgresProvider::appendGeomParam( const QgsGeometry& geom, QStringList QScopedPointer convertedGeom( convertToProviderType( geom ) ); QByteArray wkb( convertedGeom ? convertedGeom->exportToWkb() : geom.exportToWkb() ); - const char *buf = wkb.constData(); + const unsigned char *buf = reinterpret_cast< const unsigned char * >( wkb.constData() ); int wkbSize = wkb.length(); for ( int i = 0; i < wkbSize; ++i ) From 7ae6269932f924eb786e351d119860794387ba89 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 14 Nov 2016 10:53:46 +0100 Subject: [PATCH 741/897] [BUGFIX][QGIS Server] Transform feature collections bbox to ESPG:4326 --- src/server/qgswfsserver.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index 9f1765007a38..4a46717aaa6f 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -1216,6 +1216,22 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f QString fcString; if ( format == QLatin1String( "GeoJSON" ) ) { + if ( crs.isValid() ) + { + QgsGeometry* exportGeom = QgsGeometry::fromRect( *rect ); + QgsCoordinateTransform transform; + transform.setSourceCrs( crs ); + transform.setDestCRS( QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) ); + try + { + if ( exportGeom->transform( transform ) == 0 ) + rect = new QgsRectangle( exportGeom->boundingBox() ); + } + catch ( QgsCsException &cse ) + { + Q_UNUSED( cse ); + } + } fcString = QStringLiteral( "{\"type\": \"FeatureCollection\",\n" ); fcString += " \"bbox\": [ " + qgsDoubleToString( rect->xMinimum(), prec ) + ", " + qgsDoubleToString( rect->yMinimum(), prec ) + ", " + qgsDoubleToString( rect->xMaximum(), prec ) + ", " + qgsDoubleToString( rect->yMaximum(), prec ) + "],\n"; fcString += QLatin1String( " \"features\": [\n" ); From 7299e6b8ba21b7e4839233ecff5397dafa677a3a Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 14 Nov 2016 10:55:26 +0100 Subject: [PATCH 742/897] Fix typo --- src/server/qgswfsserver.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index 4a46717aaa6f..00451854ac4b 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -1225,7 +1225,7 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f try { if ( exportGeom->transform( transform ) == 0 ) - rect = new QgsRectangle( exportGeom->boundingBox() ); + rect = new QgsRectangle( exportGeom->boundingBox() ); } catch ( QgsCsException &cse ) { From 968e02d6fe38b024855ef75852eb033b4ad9ecbd Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 14 Nov 2016 19:53:18 +0800 Subject: [PATCH 743/897] Propagate layer/group name changes in the layer tree (fixes #15844) --- python/core/layertree/qgslayertreelayer.sip | 10 ++++ python/core/layertree/qgslayertreenode.sip | 10 ++++ src/core/layertree/qgslayertreegroup.cpp | 14 +++++ src/core/layertree/qgslayertreegroup.h | 4 +- src/core/layertree/qgslayertreelayer.cpp | 26 +++++++++ src/core/layertree/qgslayertreelayer.h | 10 ++++ src/core/layertree/qgslayertreemodel.cpp | 11 +++- src/core/layertree/qgslayertreemodel.h | 1 + src/core/layertree/qgslayertreenode.cpp | 1 + src/core/layertree/qgslayertreenode.h | 10 ++++ tests/src/core/testqgslayertree.cpp | 62 +++++++++++++++++++++ 11 files changed, 156 insertions(+), 3 deletions(-) diff --git a/python/core/layertree/qgslayertreelayer.sip b/python/core/layertree/qgslayertreelayer.sip index 2d52aa58966a..2c3994733571 100644 --- a/python/core/layertree/qgslayertreelayer.sip +++ b/python/core/layertree/qgslayertreelayer.sip @@ -31,6 +31,13 @@ class QgsLayerTreeLayer : QgsLayerTreeNode QgsMapLayer* layer() const; + //! Get layer's name + //! @note added in 3.0 + QString name() const; + //! Set layer's name + //! @note added in 3.0 + void setName( const QString& n ); + QString layerName() const; void setLayerName( const QString& n ); @@ -47,6 +54,9 @@ class QgsLayerTreeLayer : QgsLayerTreeNode protected slots: void registryLayersAdded( const QList& layers ); void registryLayersWillBeRemoved( const QStringList& layerIds ); + //! Emits a nameChanged() signal if layer's name has changed + //! @note added in 3.0 + void layerNameChanged(); signals: //! emitted when a previously unavailable layer got loaded diff --git a/python/core/layertree/qgslayertreenode.sip b/python/core/layertree/qgslayertreenode.sip index 7ba27fbde597..dd8bc08956ae 100644 --- a/python/core/layertree/qgslayertreenode.sip +++ b/python/core/layertree/qgslayertreenode.sip @@ -76,6 +76,13 @@ class QgsLayerTreeNode : QObject //! Get list of children of the node. Children are owned by the parent QList children(); + //! Return name of the node + //! @note added in 3.0 + virtual QString name() const = 0; + //! Set name of the node. Emits nameChanged signal. + //! @note added in 3.0 + virtual void setName( const QString& name ) = 0; + //! Read layer tree from XML. Returns new instance static QgsLayerTreeNode* readXml( QDomElement& element ) /Factory/; //! Write layer tree to XML @@ -119,6 +126,9 @@ class QgsLayerTreeNode : QObject void customPropertyChanged( QgsLayerTreeNode *node, const QString& key ); //! Emitted when the collapsed/expanded state of a node within the tree has been changed void expandedChanged( QgsLayerTreeNode *node, bool expanded ); + //! Emitted when the name of the node is changed + //! @note added in 3.0 + void nameChanged( QgsLayerTreeNode* node, QString name ); protected: diff --git a/src/core/layertree/qgslayertreegroup.cpp b/src/core/layertree/qgslayertreegroup.cpp index 71d194029e23..04a2e372c302 100644 --- a/src/core/layertree/qgslayertreegroup.cpp +++ b/src/core/layertree/qgslayertreegroup.cpp @@ -46,6 +46,20 @@ QgsLayerTreeGroup::QgsLayerTreeGroup( const QgsLayerTreeGroup& other ) connect( this, SIGNAL( visibilityChanged( QgsLayerTreeNode*, Qt::CheckState ) ), this, SLOT( nodeVisibilityChanged( QgsLayerTreeNode* ) ) ); } +QString QgsLayerTreeGroup::name() const +{ + return mName; +} + +void QgsLayerTreeGroup::setName( const QString& n ) +{ + if ( mName == n ) + return; + + mName = n; + emit nameChanged( this, n ); +} + QgsLayerTreeGroup* QgsLayerTreeGroup::insertGroup( int index, const QString& name ) { diff --git a/src/core/layertree/qgslayertreegroup.h b/src/core/layertree/qgslayertreegroup.h index ed82ad44be25..b8b47cb7e0d0 100644 --- a/src/core/layertree/qgslayertreegroup.h +++ b/src/core/layertree/qgslayertreegroup.h @@ -36,9 +36,9 @@ class CORE_EXPORT QgsLayerTreeGroup : public QgsLayerTreeNode QgsLayerTreeGroup( const QgsLayerTreeGroup& other ); //! Get group's name - QString name() const { return mName; } + QString name() const override; //! Set group's name - void setName( const QString& n ) { mName = n; } + void setName( const QString& n ) override; //! Insert a new group node with given name at specified position. Newly created node is owned by this group. QgsLayerTreeGroup* insertGroup( int index, const QString& name ); diff --git a/src/core/layertree/qgslayertreelayer.cpp b/src/core/layertree/qgslayertreelayer.cpp index 4900006f13f5..b7ef0457c927 100644 --- a/src/core/layertree/qgslayertreelayer.cpp +++ b/src/core/layertree/qgslayertreelayer.cpp @@ -58,6 +58,7 @@ void QgsLayerTreeLayer::attachToLayer() { mLayer = l; mLayerName = l->name(); + connect( l, SIGNAL( nameChanged() ), this, SLOT( layerNameChanged() ) ); // make sure we are notified if the layer is removed connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( registryLayersWillBeRemoved( QStringList ) ) ); } @@ -70,6 +71,15 @@ void QgsLayerTreeLayer::attachToLayer() } } +QString QgsLayerTreeLayer::name() const +{ + return layerName(); +} + +void QgsLayerTreeLayer::setName( const QString& n ) +{ + setLayerName( n ); +} QString QgsLayerTreeLayer::layerName() const { @@ -79,9 +89,19 @@ QString QgsLayerTreeLayer::layerName() const void QgsLayerTreeLayer::setLayerName( const QString& n ) { if ( mLayer ) + { + if ( mLayer->name() == n ) + return; mLayer->setName( n ); + // no need to emit signal: we will be notified from layer's nameChanged() signal + } else + { + if ( mLayerName == n ) + return; mLayerName = n; + emit nameChanged( this, n ); + } } void QgsLayerTreeLayer::setVisible( Qt::CheckState state ) @@ -170,3 +190,9 @@ void QgsLayerTreeLayer::registryLayersWillBeRemoved( const QStringList& layerIds mLayer = nullptr; } } + +void QgsLayerTreeLayer::layerNameChanged() +{ + Q_ASSERT( mLayer ); + emit nameChanged( this, mLayer->name() ); +} diff --git a/src/core/layertree/qgslayertreelayer.h b/src/core/layertree/qgslayertreelayer.h index 6afc51e0afc9..7b94d4ba5097 100644 --- a/src/core/layertree/qgslayertreelayer.h +++ b/src/core/layertree/qgslayertreelayer.h @@ -51,6 +51,13 @@ class CORE_EXPORT QgsLayerTreeLayer : public QgsLayerTreeNode QgsMapLayer* layer() const { return mLayer; } + //! Get layer's name + //! @note added in 3.0 + QString name() const override; + //! Set layer's name + //! @note added in 3.0 + void setName( const QString& n ) override; + QString layerName() const; void setLayerName( const QString& n ); @@ -67,6 +74,9 @@ class CORE_EXPORT QgsLayerTreeLayer : public QgsLayerTreeNode protected slots: void registryLayersAdded( const QList& layers ); void registryLayersWillBeRemoved( const QStringList& layerIds ); + //! Emits a nameChanged() signal if layer's name has changed + //! @note added in 3.0 + void layerNameChanged(); signals: //! emitted when a previously unavailable layer got loaded diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index 599d85227580..3314912f7714 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -742,6 +742,15 @@ void QgsLayerTreeModel::nodeVisibilityChanged( QgsLayerTreeNode* node ) emit dataChanged( index, index ); } +void QgsLayerTreeModel::nodeNameChanged( QgsLayerTreeNode* node, const QString& name ) +{ + Q_UNUSED( name ); + Q_ASSERT( node ); + + QModelIndex index = node2index( node ); + emit dataChanged( index, index ); +} + void QgsLayerTreeModel::nodeCustomPropertyChanged( QgsLayerTreeNode* node, const QString& key ) { @@ -854,7 +863,6 @@ void QgsLayerTreeModel::connectToLayer( QgsLayerTreeLayer* nodeLayer ) connect( layer, SIGNAL( editingStarted() ), this, SLOT( layerNeedsUpdate() ), Qt::UniqueConnection ); connect( layer, SIGNAL( editingStopped() ), this, SLOT( layerNeedsUpdate() ), Qt::UniqueConnection ); connect( layer, SIGNAL( layerModified() ), this, SLOT( layerNeedsUpdate() ), Qt::UniqueConnection ); - connect( layer, SIGNAL( nameChanged() ), this, SLOT( layerNeedsUpdate() ), Qt::UniqueConnection ); } } @@ -927,6 +935,7 @@ void QgsLayerTreeModel::connectToRootNode() connect( mRootNode, SIGNAL( willRemoveChildren( QgsLayerTreeNode*, int, int ) ), this, SLOT( nodeWillRemoveChildren( QgsLayerTreeNode*, int, int ) ) ); connect( mRootNode, SIGNAL( removedChildren( QgsLayerTreeNode*, int, int ) ), this, SLOT( nodeRemovedChildren() ) ); connect( mRootNode, SIGNAL( visibilityChanged( QgsLayerTreeNode*, Qt::CheckState ) ), this, SLOT( nodeVisibilityChanged( QgsLayerTreeNode* ) ) ); + connect( mRootNode, SIGNAL( nameChanged( QgsLayerTreeNode*, QString ) ), this, SLOT( nodeNameChanged( QgsLayerTreeNode*, QString ) ) ); connect( mRootNode, SIGNAL( customPropertyChanged( QgsLayerTreeNode*, QString ) ), this, SLOT( nodeCustomPropertyChanged( QgsLayerTreeNode*, QString ) ) ); diff --git a/src/core/layertree/qgslayertreemodel.h b/src/core/layertree/qgslayertreemodel.h index 1522f3d224c8..8905628a0d97 100644 --- a/src/core/layertree/qgslayertreemodel.h +++ b/src/core/layertree/qgslayertreemodel.h @@ -216,6 +216,7 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel void nodeRemovedChildren(); void nodeVisibilityChanged( QgsLayerTreeNode* node ); + void nodeNameChanged( QgsLayerTreeNode* node, const QString& name ); void nodeCustomPropertyChanged( QgsLayerTreeNode* node, const QString& key ); diff --git a/src/core/layertree/qgslayertreenode.cpp b/src/core/layertree/qgslayertreenode.cpp index 9ffd0de7143a..f1ef54fb46d4 100644 --- a/src/core/layertree/qgslayertreenode.cpp +++ b/src/core/layertree/qgslayertreenode.cpp @@ -136,6 +136,7 @@ void QgsLayerTreeNode::insertChildrenPrivate( int index, QList children() { return mChildren; } + //! Return name of the node + //! @note added in 3.0 + virtual QString name() const = 0; + //! Set name of the node. Emits nameChanged signal. + //! @note added in 3.0 + virtual void setName( const QString& name ) = 0; + //! Read layer tree from XML. Returns new instance static QgsLayerTreeNode *readXml( QDomElement &element ); //! Write layer tree to XML @@ -126,6 +133,9 @@ class CORE_EXPORT QgsLayerTreeNode : public QObject void customPropertyChanged( QgsLayerTreeNode *node, const QString& key ); //! Emitted when the collapsed/expanded state of a node within the tree has been changed void expandedChanged( QgsLayerTreeNode *node, bool expanded ); + //! Emitted when the name of the node is changed + //! @note added in 3.0 + void nameChanged( QgsLayerTreeNode* node, QString name ); protected: diff --git a/tests/src/core/testqgslayertree.cpp b/tests/src/core/testqgslayertree.cpp index 498f23b89f5c..7f21b94b24a6 100644 --- a/tests/src/core/testqgslayertree.cpp +++ b/tests/src/core/testqgslayertree.cpp @@ -35,6 +35,8 @@ class TestQgsLayerTree : public QObject private slots: void initTestCase(); void cleanupTestCase(); + void testGroupNameChanged(); + void testLayerNameChanged(); void testCheckStateParentToChild(); void testCheckStateChildToParent(); void testCheckStateMutuallyExclusive(); @@ -80,6 +82,66 @@ void TestQgsLayerTree::cleanupTestCase() QgsApplication::exitQgis(); } +void TestQgsLayerTree::testGroupNameChanged() +{ + QgsLayerTreeNode* secondGroup = mRoot->children()[1]; + + QSignalSpy spy( mRoot, SIGNAL( nameChanged( QgsLayerTreeNode*, QString ) ) ); + secondGroup->setName( "grp2+" ); + + QCOMPARE( secondGroup->name(), QString( "grp2+" ) ); + + QCOMPARE( spy.count(), 1 ); + QList arguments = spy.takeFirst(); + QCOMPARE( arguments.at( 0 ).value(), secondGroup ); + QCOMPARE( arguments.at( 1 ).toString(), QString( "grp2+" ) ); + + secondGroup->setName( "grp2" ); + QCOMPARE( secondGroup->name(), QString( "grp2" ) ); +} + +void TestQgsLayerTree::testLayerNameChanged() +{ + QgsVectorLayer* vl = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer" ), QStringLiteral( "vl" ), QStringLiteral( "memory" ) ); + QVERIFY( vl->isValid() ); + + QgsLayerTreeLayer* n = new QgsLayerTreeLayer( vl->id(), vl->name() ); + mRoot->addChildNode( n ); + + QSignalSpy spy( mRoot, SIGNAL( nameChanged( QgsLayerTreeNode*, QString ) ) ); + + QCOMPARE( n->name(), QString( "vl" ) ); + n->setName( "changed 1" ); + + QCOMPARE( n->name(), QString( "changed 1" ) ); + QCOMPARE( spy.count(), 1 ); + QList arguments = spy.takeFirst(); + QCOMPARE( arguments.at( 0 ).value(), n ); + QCOMPARE( arguments.at( 1 ).toString(), QString( "changed 1" ) ); + + QgsMapLayerRegistry::instance()->addMapLayers( QList() << vl ); + + // set name via map layer + vl->setName( "changed 2" ); + QCOMPARE( n->name(), QString( "changed 2" ) ); + QCOMPARE( spy.count(), 1 ); + arguments = spy.takeFirst(); + QCOMPARE( arguments.at( 0 ).value(), n ); + QCOMPARE( arguments.at( 1 ).toString(), QString( "changed 2" ) ); + + // set name via layer tree + n->setName( "changed 3" ); + QCOMPARE( n->name(), QString( "changed 3" ) ); + QCOMPARE( spy.count(), 1 ); + arguments = spy.takeFirst(); + QCOMPARE( arguments.at( 0 ).value(), n ); + QCOMPARE( arguments.at( 1 ).toString(), QString( "changed 3" ) ); + + QgsMapLayerRegistry::instance()->removeMapLayers( QList() << vl ); + + mRoot->removeChildNode( n ); +} + void TestQgsLayerTree::testCheckStateParentToChild() { mRoot->setVisible( Qt::Unchecked ); From b13b4f942d113cae2281b544029bcfcbc09b1473 Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 14 Nov 2016 14:24:18 +0100 Subject: [PATCH 744/897] Fix QGIS Server build error --- src/server/qgswfsserver.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index 00451854ac4b..8ef6d3caf35f 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -1218,16 +1218,16 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f { if ( crs.isValid() ) { - QgsGeometry* exportGeom = QgsGeometry::fromRect( *rect ); + QgsGeometry exportGeom = QgsGeometry::fromRect( *rect ); QgsCoordinateTransform transform; transform.setSourceCrs( crs ); - transform.setDestCRS( QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) ); + transform.setDestinationCRS( QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) ); try { - if ( exportGeom->transform( transform ) == 0 ) - rect = new QgsRectangle( exportGeom->boundingBox() ); + if ( exportGeom.transform( transform ) == 0 ) + rect = new QgsRectangle( exportGeom.boundingBox() ); } - catch ( QgsCsException &cse ) + catch ( QgsException &cse ) { Q_UNUSED( cse ); } From 9ad365e2aa1cda696ad2d03242b9f8ea7c62d64f Mon Sep 17 00:00:00 2001 From: rldhont Date: Mon, 14 Nov 2016 14:38:19 +0100 Subject: [PATCH 745/897] Fix setDestinationCRS --- src/server/qgswfsserver.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgswfsserver.cpp b/src/server/qgswfsserver.cpp index 8ef6d3caf35f..56477c5692e4 100644 --- a/src/server/qgswfsserver.cpp +++ b/src/server/qgswfsserver.cpp @@ -1221,7 +1221,7 @@ void QgsWfsServer::startGetFeature( QgsRequestHandler& request, const QString& f QgsGeometry exportGeom = QgsGeometry::fromRect( *rect ); QgsCoordinateTransform transform; transform.setSourceCrs( crs ); - transform.setDestinationCRS( QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) ); + transform.setDestinationCrs( QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem::EpsgCrsId ) ); try { if ( exportGeom.transform( transform ) == 0 ) From 9afd6b0a2ea9e39c1f63c3d5d7432b9d79577dbc Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 14 Nov 2016 15:39:17 +0200 Subject: [PATCH 746/897] [processing] fix test --- python/plugins/processing/tests/ParametersTest.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index f3122a034ae7..c98007bef92b 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -617,7 +617,7 @@ def testOptional(self): def testScriptCode(self): parent_name = 'test_parent_layer' - test_data = points2() + test_data = points() test_layer = QgsVectorLayer(test_data, parent_name, 'ogr') parameter = ParameterTableField( 'myName', 'myDesc', parent_name) From 9950b085d4c59ad432f15d4c1e3cdb4ef8bede5f Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 14 Nov 2016 23:39:58 +0800 Subject: [PATCH 747/897] Fix missing docs and sip coverage (followup 968e02d6) --- python/core/layertree/qgslayertreemodel.sip | 3 +++ src/core/layertree/qgslayertreemodel.h | 2 ++ 2 files changed, 5 insertions(+) diff --git a/python/core/layertree/qgslayertreemodel.sip b/python/core/layertree/qgslayertreemodel.sip index 705ba3813021..7f8ac99b1bc6 100644 --- a/python/core/layertree/qgslayertreemodel.sip +++ b/python/core/layertree/qgslayertreemodel.sip @@ -190,6 +190,9 @@ class QgsLayerTreeModel : QAbstractItemModel void nodeRemovedChildren(); void nodeVisibilityChanged( QgsLayerTreeNode* node ); + //! Updates model when node's name has changed + //! @note added in 3.0 + void nodeNameChanged( QgsLayerTreeNode* node, const QString& name ); void nodeCustomPropertyChanged( QgsLayerTreeNode* node, const QString& key ); diff --git a/src/core/layertree/qgslayertreemodel.h b/src/core/layertree/qgslayertreemodel.h index 8905628a0d97..330f7d4f8a22 100644 --- a/src/core/layertree/qgslayertreemodel.h +++ b/src/core/layertree/qgslayertreemodel.h @@ -216,6 +216,8 @@ class CORE_EXPORT QgsLayerTreeModel : public QAbstractItemModel void nodeRemovedChildren(); void nodeVisibilityChanged( QgsLayerTreeNode* node ); + //! Updates model when node's name has changed + //! @note added in 3.0 void nodeNameChanged( QgsLayerTreeNode* node, const QString& name ); void nodeCustomPropertyChanged( QgsLayerTreeNode* node, const QString& key ); From 645514a23b266a3af9446dbd56adf69477e8541c Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Tue, 15 Nov 2016 00:56:22 +0800 Subject: [PATCH 748/897] Remove setLayerName(), layerName() from QgsLayerTreeLayer (replaced by setName(), name() overridden from the parent) --- doc/api_break.dox | 6 ++++++ python/core/layertree/qgslayertreelayer.sip | 3 --- src/app/composer/qgscomposerlegendwidget.cpp | 2 +- src/app/qgsprojectlayergroupdialog.cpp | 2 +- src/core/layertree/qgslayertreelayer.cpp | 16 +++------------- src/core/layertree/qgslayertreelayer.h | 3 --- src/core/layertree/qgslayertreemodel.cpp | 4 ++-- .../layertree/qgslayertreemodellegendnode.cpp | 2 +- src/core/layertree/qgslayertreeutils.cpp | 2 +- 9 files changed, 15 insertions(+), 25 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index c5d2a06be28c..b61e5aa78808 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -941,6 +941,12 @@ QgsLayerTreeGroup {#qgis_api_break_3_0_QgsLayerTreeGroup} - readChildrenFromXML() has been renamed to readChildrenFromXml() +QgsLayerTreeLayer {#qgis_api_break_3_0_QgsLayerTreeLayer} +----------------- + +- setLayerName(), layerName() were renamed to setName(), name() + + QgsLayerTreeModel {#qgis_api_break_3_0_QgsLayerTreeMode} ----------------- diff --git a/python/core/layertree/qgslayertreelayer.sip b/python/core/layertree/qgslayertreelayer.sip index 2c3994733571..a961dc99eb66 100644 --- a/python/core/layertree/qgslayertreelayer.sip +++ b/python/core/layertree/qgslayertreelayer.sip @@ -38,9 +38,6 @@ class QgsLayerTreeLayer : QgsLayerTreeNode //! @note added in 3.0 void setName( const QString& n ); - QString layerName() const; - void setLayerName( const QString& n ); - Qt::CheckState isVisible() const; void setVisible( Qt::CheckState visible ); diff --git a/src/app/composer/qgscomposerlegendwidget.cpp b/src/app/composer/qgscomposerlegendwidget.cpp index 287715c03b8c..36e1b38e8bc6 100644 --- a/src/app/composer/qgscomposerlegendwidget.cpp +++ b/src/app/composer/qgscomposerlegendwidget.cpp @@ -996,7 +996,7 @@ void QgsComposerLegendWidget::on_mItemTreeView_doubleClicked( const QModelIndex } else if ( QgsLayerTree::isLayer( currentNode ) ) { - currentText = QgsLayerTree::toLayer( currentNode )->layerName(); + currentText = QgsLayerTree::toLayer( currentNode )->name(); QVariant v = currentNode->customProperty( QStringLiteral( "legend/title-label" ) ); if ( !v.isNull() ) currentText = v.toString(); diff --git a/src/app/qgsprojectlayergroupdialog.cpp b/src/app/qgsprojectlayergroupdialog.cpp index efa4c922ed0d..63dbcfec0508 100644 --- a/src/app/qgsprojectlayergroupdialog.cpp +++ b/src/app/qgsprojectlayergroupdialog.cpp @@ -92,7 +92,7 @@ QStringList QgsProjectLayerGroupDialog::selectedLayerNames() const { QgsLayerTreeNode* node = model->index2node( index ); if ( QgsLayerTree::isLayer( node ) ) - layerNames << QgsLayerTree::toLayer( node )->layerName(); + layerNames << QgsLayerTree::toLayer( node )->name(); } return layerNames; } diff --git a/src/core/layertree/qgslayertreelayer.cpp b/src/core/layertree/qgslayertreelayer.cpp index b7ef0457c927..3274655f61a3 100644 --- a/src/core/layertree/qgslayertreelayer.cpp +++ b/src/core/layertree/qgslayertreelayer.cpp @@ -72,21 +72,11 @@ void QgsLayerTreeLayer::attachToLayer() } QString QgsLayerTreeLayer::name() const -{ - return layerName(); -} - -void QgsLayerTreeLayer::setName( const QString& n ) -{ - setLayerName( n ); -} - -QString QgsLayerTreeLayer::layerName() const { return mLayer ? mLayer->name() : mLayerName; } -void QgsLayerTreeLayer::setLayerName( const QString& n ) +void QgsLayerTreeLayer::setName( const QString& n ) { if ( mLayer ) { @@ -144,7 +134,7 @@ void QgsLayerTreeLayer::writeXml( QDomElement& parentElement ) QDomDocument doc = parentElement.ownerDocument(); QDomElement elem = doc.createElement( QStringLiteral( "layer-tree-layer" ) ); elem.setAttribute( QStringLiteral( "id" ), mLayerId ); - elem.setAttribute( QStringLiteral( "name" ), layerName() ); + elem.setAttribute( QStringLiteral( "name" ), name() ); elem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( mVisible ) ); elem.setAttribute( QStringLiteral( "expanded" ), mExpanded ? "1" : "0" ); @@ -155,7 +145,7 @@ void QgsLayerTreeLayer::writeXml( QDomElement& parentElement ) QString QgsLayerTreeLayer::dump() const { - return QStringLiteral( "LAYER: %1 visible=%2 expanded=%3 id=%4\n" ).arg( layerName() ).arg( mVisible ).arg( mExpanded ).arg( layerId() ); + return QStringLiteral( "LAYER: %1 visible=%2 expanded=%3 id=%4\n" ).arg( name() ).arg( mVisible ).arg( mExpanded ).arg( layerId() ); } QgsLayerTreeLayer* QgsLayerTreeLayer::clone() const diff --git a/src/core/layertree/qgslayertreelayer.h b/src/core/layertree/qgslayertreelayer.h index 7b94d4ba5097..d90371756808 100644 --- a/src/core/layertree/qgslayertreelayer.h +++ b/src/core/layertree/qgslayertreelayer.h @@ -58,9 +58,6 @@ class CORE_EXPORT QgsLayerTreeLayer : public QgsLayerTreeNode //! @note added in 3.0 void setName( const QString& n ) override; - QString layerName() const; - void setLayerName( const QString& n ); - Qt::CheckState isVisible() const { return mVisible; } void setVisible( Qt::CheckState visible ); diff --git a/src/core/layertree/qgslayertreemodel.cpp b/src/core/layertree/qgslayertreemodel.cpp index 3314912f7714..ee7988f1a9b3 100644 --- a/src/core/layertree/qgslayertreemodel.cpp +++ b/src/core/layertree/qgslayertreemodel.cpp @@ -198,7 +198,7 @@ QVariant QgsLayerTreeModel::data( const QModelIndex &index, int role ) const if ( QgsLayerTree::isLayer( node ) ) { QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node ); - QString name = nodeLayer->layerName(); + QString name = nodeLayer->name(); if ( nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ), 0 ).toInt() && role == Qt::DisplayRole ) { QgsVectorLayer* vlayer = qobject_cast( nodeLayer->layer() ); @@ -417,7 +417,7 @@ bool QgsLayerTreeModel::setData( const QModelIndex& index, const QVariant& value if ( QgsLayerTree::isLayer( node ) ) { QgsLayerTreeLayer* layer = QgsLayerTree::toLayer( node ); - layer->setLayerName( value.toString() ); + layer->setName( value.toString() ); emit dataChanged( index, index ); } else if ( QgsLayerTree::isGroup( node ) ) diff --git a/src/core/layertree/qgslayertreemodellegendnode.cpp b/src/core/layertree/qgslayertreemodellegendnode.cpp index e4d687823404..93ca467c6678 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.cpp +++ b/src/core/layertree/qgslayertreemodellegendnode.cpp @@ -457,7 +457,7 @@ void QgsSymbolLegendNode::updateLabel() if ( mEmbeddedInParent ) { - QString layerName = mLayerNode->layerName(); + QString layerName = mLayerNode->name(); if ( !mLayerNode->customProperty( QStringLiteral( "legend/title-label" ) ).isNull() ) layerName = mLayerNode->customProperty( QStringLiteral( "legend/title-label" ) ).toString(); diff --git a/src/core/layertree/qgslayertreeutils.cpp b/src/core/layertree/qgslayertreeutils.cpp index 935beaeb2c44..78319e46625a 100644 --- a/src/core/layertree/qgslayertreeutils.cpp +++ b/src/core/layertree/qgslayertreeutils.cpp @@ -113,7 +113,7 @@ static QDomElement _writeOldLegendLayer( QDomDocument& doc, QgsLayerTreeLayer* n layerElem.setAttribute( QStringLiteral( "drawingOrder" ), drawingOrder ); layerElem.setAttribute( QStringLiteral( "open" ), nodeLayer->isExpanded() ? "true" : "false" ); layerElem.setAttribute( QStringLiteral( "checked" ), QgsLayerTreeUtils::checkStateToXml( nodeLayer->isVisible() ) ); - layerElem.setAttribute( QStringLiteral( "name" ), nodeLayer->layerName() ); + layerElem.setAttribute( QStringLiteral( "name" ), nodeLayer->name() ); layerElem.setAttribute( QStringLiteral( "showFeatureCount" ), nodeLayer->customProperty( QStringLiteral( "showFeatureCount" ) ).toInt() ); QDomElement fileGroupElem = doc.createElement( QStringLiteral( "filegroup" ) ); From 8898c949ef54e64d6776c1e1685e99669253a945 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Tue, 15 Nov 2016 01:16:31 +0800 Subject: [PATCH 749/897] Fix build --- src/server/qgswmsserver.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index d3aa93463953..8a29d28fb96c 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -819,7 +819,7 @@ QImage* QgsWmsServer::getLegendGraphics() layerNameMap.insert( layerId, ml->name() ); // set layer name with layer's title to have it in legend if ( !ml->title().isEmpty() ) - layer->setLayerName( ml->title() ); + layer->setName( ml->title() ); // set show feature count if ( showFeatureCount ) layer->setCustomProperty( QStringLiteral( "showFeatureCount" ), showFeatureCount ); From dd68d815668f773ee68d752417f5d953c393e36e Mon Sep 17 00:00:00 2001 From: Werner Macho Date: Mon, 14 Nov 2016 20:54:19 +0100 Subject: [PATCH 750/897] Update tsstat.pl just a small intendation fix --- scripts/tsstat.pl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/tsstat.pl b/scripts/tsstat.pl index 7ccf7e4502df..6ded0e195434 100755 --- a/scripts/tsstat.pl +++ b/scripts/tsstat.pl @@ -84,7 +84,7 @@ 'ta' => '', 'te' => '', 'th' => 'Man Chao', - 'tl' => 'Kathrina Gregana', + 'tl' => 'Kathrina Gregana', 'tr' => 'Osman Yalçın YILMAZ, Omur Saygin', 'uk' => 'Alexander Bruy', 'vi' => 'Phùng Văn Doanh, Bùi Hữu Mạnh, Nguyễn Văn Thanh, Nguyễn Hữu Phúc, Cao Minh Tu', From 85c8c97d5f40dcd855d7e937d1715567a91847eb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 12:12:43 +1000 Subject: [PATCH 751/897] Allow empty field name ('not set' option) in QgsFieldModel, QgsFieldComboBox --- python/gui/qgsfieldcombobox.sip | 14 ++ python/gui/qgsfieldmodel.sip | 65 ++++++- src/gui/qgsfieldcombobox.cpp | 10 ++ src/gui/qgsfieldcombobox.h | 15 ++ src/gui/qgsfieldmodel.cpp | 100 ++++++++--- src/gui/qgsfieldmodel.h | 75 ++++++++- src/gui/qgsfieldproxymodel.cpp | 6 + tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgsfieldmodel.py | 225 +++++++++++++++++++++++++ 9 files changed, 468 insertions(+), 43 deletions(-) create mode 100644 tests/src/python/test_qgsfieldmodel.py diff --git a/python/gui/qgsfieldcombobox.sip b/python/gui/qgsfieldcombobox.sip index b967b37d22db..57c26f089fbd 100644 --- a/python/gui/qgsfieldcombobox.sip +++ b/python/gui/qgsfieldcombobox.sip @@ -25,6 +25,20 @@ class QgsFieldComboBox : QComboBox //! currently used filter on list of fields QgsFieldProxyModel::Filters filters() const; + /** + * Sets whether an optional empty field ("not set") option is shown in the combo box. + * @see allowEmptyFieldName() + * @note added in QGIS 3.0 + */ + void setAllowEmptyFieldName( bool allowEmpty ); + + /** + * Returns true if the combo box allows the empty field ("not set") choice. + * @see setAllowEmptyFieldName() + * @note added in QGIS 3.0 + */ + bool allowEmptyFieldName() const; + //! return the currently selected field QString currentField() const; diff --git a/python/gui/qgsfieldmodel.sip b/python/gui/qgsfieldmodel.sip index f489a8b8630e..6f5ce5c1d462 100644 --- a/python/gui/qgsfieldmodel.sip +++ b/python/gui/qgsfieldmodel.sip @@ -12,6 +12,8 @@ class QgsFieldModel : QAbstractItemModel %End public: + + //! Roles utilised by the model enum FieldRoles { FieldNameRole, /*!< return field name if index corresponds to a field */ @@ -21,38 +23,85 @@ class QgsFieldModel : QAbstractItemModel ExpressionValidityRole, /*!< return if expression is valid or not */ FieldTypeRole, /*!< return the field type (if a field, return QVariant if expression) */ FieldOriginRole, /*!< return the field origin (if a field, returns QVariant if expression) */ + IsEmptyRole, //!< Return if the index corresponds to the empty value }; /** - * @brief QgsFieldModel creates a model to display the fields of a given layer + * Constructor for QgsFieldModel - creates a model to display the fields of a given layer. */ explicit QgsFieldModel( QObject *parent /TransferThis/ = 0 ); - //! return the index corresponding to a given fieldName + /** + * Returns the index corresponding to a given fieldName. + */ QModelIndex indexFromName( const QString &fieldName ); - //! returns the currently used layer + /** + * Sets whether custom expressions are accepted and displayed in the model. + * @see allowExpression() + * @see setExpression() + */ void setAllowExpression( bool allowExpression ); + + /** + * Returns true if the model allows custom expressions to be created and displayed. + * @see setAllowExpression() + */ bool allowExpression(); - bool isField( const QString& expression ); + /** + * Sets whether an optional empty field ("not set") option is present in the model. + * @see allowEmptyFieldName() + * @note added in QGIS 3.0 + */ + void setAllowEmptyFieldName( bool allowEmpty ); + + /** + * Returns true if the model allows the empty field ("not set") choice. + * @see setAllowEmptyFieldName() + * @note added in QGIS 3.0 + */ + bool allowEmptyFieldName() const; /** - * @brief setExpression sets a single expression to be added after the fields at the end of the model + * Returns true if a string represents a field reference, or false if it is an + * expression consisting of more than direct field reference. + */ + bool isField( const QString& expression ) const; + + /** + * Sets a single expression to be added after the fields at the end of the model. + * @see setAllowExpression() + * @see allowExpression() + * @see removeExpression() */ void setExpression( const QString &expression ); - //! remove expressions from the model + /** + * Removes any custom expression from the model. + * @see setExpression() + * @see allowExpression() + */ void removeExpression(); - //! returns the currently used layer + /** + * Returns the layer associated with the model. + * @see setLayer() + */ QgsVectorLayer* layer(); public slots: - //! set the layer of whch fields are displayed + /** + * Set the layer from which fields are displayed. + * @see layer() + */ void setLayer( QgsVectorLayer *layer ); protected slots: + + /** + * Called when the model must be updated. + */ virtual void updateModel(); // QAbstractItemModel interface diff --git a/src/gui/qgsfieldcombobox.cpp b/src/gui/qgsfieldcombobox.cpp index 14d21e355b6a..79f635f54c19 100644 --- a/src/gui/qgsfieldcombobox.cpp +++ b/src/gui/qgsfieldcombobox.cpp @@ -33,6 +33,16 @@ void QgsFieldComboBox::setFilters( QgsFieldProxyModel::Filters filters ) mFieldProxyModel->setFilters( filters ); } +void QgsFieldComboBox::setAllowEmptyFieldName( bool allowEmpty ) +{ + mFieldProxyModel->sourceFieldModel()->setAllowEmptyFieldName( allowEmpty ); +} + +bool QgsFieldComboBox::allowEmptyFieldName() const +{ + return mFieldProxyModel->sourceFieldModel()->allowEmptyFieldName(); +} + void QgsFieldComboBox::setLayer( QgsMapLayer *layer ) { QgsVectorLayer* vl = dynamic_cast( layer ); diff --git a/src/gui/qgsfieldcombobox.h b/src/gui/qgsfieldcombobox.h index c88bed068b24..804309116ce6 100644 --- a/src/gui/qgsfieldcombobox.h +++ b/src/gui/qgsfieldcombobox.h @@ -35,6 +35,7 @@ class GUI_EXPORT QgsFieldComboBox : public QComboBox Q_OBJECT Q_FLAGS( QgsFieldProxyModel::Filters ) Q_PROPERTY( QgsFieldProxyModel::Filters filters READ filters WRITE setFilters ) + Q_PROPERTY( bool allowEmptyFieldName READ allowEmptyFieldName WRITE setAllowEmptyFieldName ) public: @@ -50,6 +51,20 @@ class GUI_EXPORT QgsFieldComboBox : public QComboBox //! currently used filter on list of fields QgsFieldProxyModel::Filters filters() const { return mFieldProxyModel->filters(); } + /** + * Sets whether an optional empty field ("not set") option is shown in the combo box. + * @see allowEmptyFieldName() + * @note added in QGIS 3.0 + */ + void setAllowEmptyFieldName( bool allowEmpty ); + + /** + * Returns true if the combo box allows the empty field ("not set") choice. + * @see setAllowEmptyFieldName() + * @note added in QGIS 3.0 + */ + bool allowEmptyFieldName() const; + //! return the currently selected field QString currentField() const; diff --git a/src/gui/qgsfieldmodel.cpp b/src/gui/qgsfieldmodel.cpp index 6623689de06b..2fb479dafbd4 100644 --- a/src/gui/qgsfieldmodel.cpp +++ b/src/gui/qgsfieldmodel.cpp @@ -27,6 +27,7 @@ QgsFieldModel::QgsFieldModel( QObject *parent ) : QAbstractItemModel( parent ) , mLayer( nullptr ) , mAllowExpression( false ) + , mAllowEmpty( false ) { } @@ -44,11 +45,20 @@ QModelIndex QgsFieldModel::indexFromName( const QString &fieldName ) fldName = fieldNameWithAlias; } + if ( mAllowEmpty && fieldName.isEmpty() ) + return index( 0, 0 ); + int r = mFields.indexFromName( fldName ); - QModelIndex idx = index( r, 0 ); - if ( idx.isValid() ) + if ( r >= 0 ) { - return idx; + if ( mAllowEmpty ) + r++; + + QModelIndex idx = index( r, 0 ); + if ( idx.isValid() ) + { + return idx; + } } if ( mAllowExpression ) @@ -56,14 +66,14 @@ QModelIndex QgsFieldModel::indexFromName( const QString &fieldName ) int exprIdx = mExpression.indexOf( fldName ); if ( exprIdx != -1 ) { - return index( mFields.count() + exprIdx, 0 ); + return index(( mAllowEmpty ? 1 : 0 ) + mFields.count() + exprIdx, 0 ); } } return QModelIndex(); } -bool QgsFieldModel::isField( const QString& expression ) +bool QgsFieldModel::isField( const QString& expression ) const { int index = mFields.indexFromName( expression ); return index >= 0; @@ -96,6 +106,7 @@ void QgsFieldModel::layerDeleted() void QgsFieldModel::updateModel() { + int offset = mAllowEmpty ? 1 : 0; if ( mLayer ) { QgsFields newFields = mLayer->fields(); @@ -112,7 +123,7 @@ void QgsFieldModel::updateModel() if ( mFields.toList() == tmpNewFields.toList() ) { // the only change is a new field at the end - beginInsertRows( QModelIndex(), mFields.count(), mFields.count() ); + beginInsertRows( QModelIndex(), mFields.count() + offset, mFields.count() + offset ); mFields = newFields; endInsertRows(); return; @@ -126,7 +137,7 @@ void QgsFieldModel::updateModel() if ( tmpOldFields.toList() == newFields.toList() ) { // the only change is a field removed at the end - beginRemoveRows( QModelIndex(), mFields.count() - 1, mFields.count() - 1 ); + beginRemoveRows( QModelIndex(), mFields.count() - 1 + offset, mFields.count() - 1 + offset ); mFields = newFields; endRemoveRows(); return; @@ -142,7 +153,7 @@ void QgsFieldModel::updateModel() break; // the change is more complex - go with general case // the only change is a field removed at index i - beginRemoveRows( QModelIndex(), i, i ); + beginRemoveRows( QModelIndex(), i + offset, i + offset ); mFields = newFields; endRemoveRows(); return; @@ -156,7 +167,7 @@ void QgsFieldModel::updateModel() endResetModel(); } else - emit dataChanged( index( 0, 0 ), index( rowCount(), 0 ) ); + emit dataChanged( index( 0 + offset, 0 ), index( rowCount(), 0 ) ); } else { @@ -183,6 +194,26 @@ void QgsFieldModel::setAllowExpression( bool allowExpression ) } } +void QgsFieldModel::setAllowEmptyFieldName( bool allowEmpty ) +{ + if ( allowEmpty == mAllowEmpty ) + return; + + if ( allowEmpty ) + { + beginInsertRows( QModelIndex(), 0, 0 ); + mAllowEmpty = true; + endInsertRows(); + } + else + { + beginRemoveRows( QModelIndex(), 0, 0 ); + mAllowEmpty = false; + endRemoveRows(); + } +} + + void QgsFieldModel::setExpression( const QString &expression ) { if ( !mAllowExpression ) @@ -229,7 +260,7 @@ int QgsFieldModel::rowCount( const QModelIndex &parent ) const return 0; } - return mAllowExpression ? mFields.count() + mExpression.count() : mFields.count(); + return ( mAllowEmpty ? 1 : 0 ) + ( mAllowExpression ? mFields.count() + mExpression.count() : mFields.count() ); } int QgsFieldModel::columnCount( const QModelIndex &parent ) const @@ -244,16 +275,20 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const return QVariant(); int exprIdx = index.row() - mFields.count(); + if ( mAllowEmpty ) + exprIdx--; + bool isEmpty = mAllowEmpty && index.row() == 0; + int fieldOffset = mAllowEmpty ? 1 : 0; switch ( role ) { case FieldNameRole: { - if ( exprIdx >= 0 ) + if ( isEmpty || exprIdx >= 0 ) { return ""; } - QgsField field = mFields.at( index.row() ); + QgsField field = mFields.at( index.row() - fieldOffset ); return field.name(); } @@ -263,20 +298,24 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const { return mExpression.at( exprIdx ); } + else if ( isEmpty ) + { + return QVariant(); + } else { - QgsField field = mFields.at( index.row() ); + QgsField field = mFields.at( index.row() - fieldOffset ); return field.name(); } } case FieldIndexRole: { - if ( exprIdx >= 0 ) + if ( isEmpty || exprIdx >= 0 ) { return QVariant(); } - return index.row(); + return index.row() - fieldOffset; } case IsExpressionRole: @@ -301,9 +340,9 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const case FieldTypeRole: { - if ( exprIdx < 0 ) + if ( exprIdx < 0 && !isEmpty ) { - QgsField field = mFields.at( index.row() ); + QgsField field = mFields.at( index.row() - fieldOffset ); return static_cast< int >( field.type() ); } return QVariant(); @@ -311,27 +350,36 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const case FieldOriginRole: { - if ( exprIdx < 0 ) + if ( exprIdx < 0 && !isEmpty ) { - return static_cast< int >( mFields.fieldOrigin( index.row() ) ); + return static_cast< int >( mFields.fieldOrigin( index.row() - fieldOffset ) ); } return QVariant(); } + case IsEmptyRole: + { + return isEmpty; + } + case Qt::DisplayRole: case Qt::EditRole: { - if ( exprIdx >= 0 ) + if ( isEmpty ) + { + return QVariant(); + } + else if ( exprIdx >= 0 ) { return mExpression.at( exprIdx ); } else if ( role == Qt::EditRole ) { - return mFields.at( index.row() ).name(); + return mFields.at( index.row() - fieldOffset ).name(); } else if ( mLayer ) { - return mLayer->attributeDisplayName( index.row() ); + return mLayer->attributeDisplayName( index.row() - fieldOffset ); } else return QVariant(); @@ -339,7 +387,7 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const case Qt::ForegroundRole: { - if ( exprIdx >= 0 ) + if ( !isEmpty && exprIdx >= 0 ) { // if expression, test validity QgsExpression exp( mExpression.at( exprIdx ) ); @@ -358,7 +406,7 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const case Qt::FontRole: { - if ( exprIdx >= 0 ) + if ( !isEmpty && exprIdx >= 0 ) { // if the line is an expression, set it as italic QFont font = QFont(); @@ -370,9 +418,9 @@ QVariant QgsFieldModel::data( const QModelIndex &index, int role ) const case Qt::DecorationRole: { - if ( exprIdx < 0 ) + if ( !isEmpty && exprIdx < 0 ) { - return mFields.iconForField( index.row() ); + return mFields.iconForField( index.row() - fieldOffset ); } return QIcon(); } diff --git a/src/gui/qgsfieldmodel.h b/src/gui/qgsfieldmodel.h index 22b7bba7d718..73260dbdff12 100644 --- a/src/gui/qgsfieldmodel.h +++ b/src/gui/qgsfieldmodel.h @@ -23,7 +23,8 @@ class QgsVectorLayer; -/** \ingroup gui +/** + * \ingroup gui * @brief The QgsFieldModel class is a model to display the list of fields of a layer in widgets. * If allowed, expressions might be added to the end of the model. * It can be associated with a QgsMapLayerModel to dynamically display a layer and its fields. @@ -32,7 +33,14 @@ class QgsVectorLayer; class GUI_EXPORT QgsFieldModel : public QAbstractItemModel { Q_OBJECT + + Q_PROPERTY( bool allowExpression READ allowExpression WRITE setAllowExpression ) + Q_PROPERTY( bool allowEmptyFieldName READ allowEmptyFieldName WRITE setAllowEmptyFieldName ) + Q_PROPERTY( QgsVectorLayer* layer READ layer WRITE setLayer ) + public: + + //! Roles utilised by the model enum FieldRoles { FieldNameRole = Qt::UserRole + 1, //!< Return field name if index corresponds to a field @@ -42,31 +50,71 @@ class GUI_EXPORT QgsFieldModel : public QAbstractItemModel ExpressionValidityRole = Qt::UserRole + 5, //!< Return if expression is valid or not FieldTypeRole = Qt::UserRole + 6, //!< Return the field type (if a field, return QVariant if expression) FieldOriginRole = Qt::UserRole + 7, //!< Return the field origin (if a field, returns QVariant if expression) + IsEmptyRole = Qt::UserRole + 8, //!< Return if the index corresponds to the empty value }; /** - * @brief QgsFieldModel creates a model to display the fields of a given layer + * Constructor for QgsFieldModel - creates a model to display the fields of a given layer. */ explicit QgsFieldModel( QObject *parent = nullptr ); - //! return the index corresponding to a given fieldName + /** + * Returns the index corresponding to a given fieldName. + */ QModelIndex indexFromName( const QString &fieldName ); - //! returns the currently used layer + /** + * Sets whether custom expressions are accepted and displayed in the model. + * @see allowExpression() + * @see setExpression() + */ void setAllowExpression( bool allowExpression ); + + /** + * Returns true if the model allows custom expressions to be created and displayed. + * @see setAllowExpression() + */ bool allowExpression() { return mAllowExpression; } - bool isField( const QString& expression ); + /** + * Sets whether an optional empty field ("not set") option is present in the model. + * @see allowEmptyFieldName() + * @note added in QGIS 3.0 + */ + void setAllowEmptyFieldName( bool allowEmpty ); + + /** + * Returns true if the model allows the empty field ("not set") choice. + * @see setAllowEmptyFieldName() + * @note added in QGIS 3.0 + */ + bool allowEmptyFieldName() const { return mAllowEmpty; } + + /** + * Returns true if a string represents a field reference, or false if it is an + * expression consisting of more than direct field reference. + */ + bool isField( const QString& expression ) const; /** - * @brief setExpression sets a single expression to be added after the fields at the end of the model + * Sets a single expression to be added after the fields at the end of the model. + * @see setAllowExpression() + * @see allowExpression() + * @see removeExpression() */ void setExpression( const QString &expression ); - //! remove expressions from the model + /** + * Removes any custom expression from the model. + * @see setExpression() + * @see allowExpression() + */ void removeExpression(); - //! returns the currently used layer + /** + * Returns the layer associated with the model. + * @see setLayer() + */ QgsVectorLayer* layer() { return mLayer; } // QAbstractItemModel interface @@ -77,10 +125,18 @@ class GUI_EXPORT QgsFieldModel : public QAbstractItemModel QVariant data( const QModelIndex &index, int role ) const override; public slots: - //! set the layer of whch fields are displayed + + /** + * Set the layer from which fields are displayed. + * @see layer() + */ void setLayer( QgsVectorLayer *layer ); protected slots: + + /** + * Called when the model must be updated. + */ virtual void updateModel(); private slots: @@ -92,6 +148,7 @@ class GUI_EXPORT QgsFieldModel : public QAbstractItemModel QgsVectorLayer* mLayer; bool mAllowExpression; + bool mAllowEmpty; private: void fetchFeature(); diff --git a/src/gui/qgsfieldproxymodel.cpp b/src/gui/qgsfieldproxymodel.cpp index c74843cd5718..5f4514ac0cec 100644 --- a/src/gui/qgsfieldproxymodel.cpp +++ b/src/gui/qgsfieldproxymodel.cpp @@ -93,6 +93,12 @@ bool QgsFieldProxyModel::filterAcceptsRow( int source_row, const QModelIndex &so bool QgsFieldProxyModel::lessThan( const QModelIndex &left, const QModelIndex &right ) const { + // empty field is always first + if ( sourceModel()->data( left, QgsFieldModel::IsEmptyRole ).toBool() ) + return true; + else if ( sourceModel()->data( right, QgsFieldModel::IsEmptyRole ).toBool() ) + return false; + // order is field order, then expressions bool lok, rok; int leftId = sourceModel()->data( left, QgsFieldModel::FieldIndexRole ).toInt( &lok ); diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 918a8a2da08b..6f0135584271 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -47,6 +47,7 @@ ADD_PYTHON_TEST(PyQgsFeature test_qgsfeature.py) ADD_PYTHON_TEST(PyQgsProject test_qgsproject.py) ADD_PYTHON_TEST(PyQgsFeatureIterator test_qgsfeatureiterator.py) ADD_PYTHON_TEST(PyQgsField test_qgsfield.py) +ADD_PYTHON_TEST(PyQgsFieldModel test_qgsfieldmodel.py) ADD_PYTHON_TEST(PyQgsFilterLineEdit test_qgsfilterlineedit.py) ADD_PYTHON_TEST(PyQgsFontUtils test_qgsfontutils.py) ADD_PYTHON_TEST(PyQgsGeometryAvoidIntersections test_qgsgeometry_avoid_intersections.py) diff --git a/tests/src/python/test_qgsfieldmodel.py b/tests/src/python/test_qgsfieldmodel.py new file mode 100644 index 000000000000..3a454eea4018 --- /dev/null +++ b/tests/src/python/test_qgsfieldmodel.py @@ -0,0 +1,225 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsFieldModel + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '14/11/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +from qgis.core import QgsField, QgsFields, QgsVectorLayer +from qgis.gui import QgsFieldModel +from qgis.PyQt.QtCore import QVariant, Qt + +from qgis.testing import start_app, unittest + +start_app() + + +def create_layer(): + layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", + "addfeat", "memory") + assert layer.isValid() + return layer + + +def create_model(): + l = create_layer() + m = QgsFieldModel() + m.setLayer(l) + return l, m + + +class TestQgsFieldModel(unittest.TestCase): + + def testGettersSetters(self): + """ test model getters/setters """ + l = create_layer() + m = QgsFieldModel() + + self.assertFalse(m.layer()) + m.setLayer(l) + self.assertEqual(m.layer(), l) + + m.setAllowExpression(True) + self.assertTrue(m.allowExpression()) + m.setAllowExpression(False) + self.assertFalse(m.allowExpression()) + + m.setAllowEmptyFieldName(True) + self.assertTrue(m.allowEmptyFieldName()) + m.setAllowEmptyFieldName(False) + self.assertFalse(m.allowEmptyFieldName()) + + def testIndexFromName(self): + l, m = create_model() + i = m.indexFromName('fldtxt') + self.assertTrue(i.isValid()) + self.assertEqual(i.row(), 0) + i = m.indexFromName('fldint') + self.assertTrue(i.isValid()) + self.assertEqual(i.row(), 1) + i = m.indexFromName('not a field') + self.assertFalse(i.isValid()) + + # try with expression + m.setAllowExpression(True) + i = m.indexFromName('not a field') + # still not valid - needs expression set first + self.assertFalse(i.isValid()) + m.setExpression('not a field') + i = m.indexFromName('not a field') + self.assertTrue(i.isValid()) + self.assertEqual(i.row(), 2) + + # try with null + i = m.indexFromName(None) + self.assertFalse(i.isValid()) + m.setAllowEmptyFieldName(True) + i = m.indexFromName(None) + self.assertTrue(i.isValid()) + self.assertEqual(i.row(), 0) + # when null is shown, all other rows should be offset + self.assertEqual(m.indexFromName('fldtxt').row(), 1) + self.assertEqual(m.indexFromName('fldint').row(), 2) + self.assertEqual(m.indexFromName('not a field').row(), 3) + + def testIsField(self): + l, m = create_model() + self.assertTrue(m.isField('fldtxt')) + self.assertTrue(m.isField('fldint')) + self.assertFalse(m.isField(None)) + self.assertFalse(m.isField('an expression')) + + def testRowCount(self): + l, m = create_model() + self.assertEqual(m.rowCount(), 2) + m.setAllowEmptyFieldName(True) + self.assertEqual(m.rowCount(), 3) + m.setAllowExpression(True) + m.setExpression('not a field') + self.assertEqual(m.rowCount(), 4) + m.setExpression('not a field') + self.assertEqual(m.rowCount(), 4) + m.setExpression('not a field 2') + self.assertEqual(m.rowCount(), 4) + m.removeExpression() + self.assertEqual(m.rowCount(), 3) + + def testFieldNameRole(self): + l, m = create_model() + self.assertEqual(m.data(m.indexFromName('fldtxt'), QgsFieldModel.FieldNameRole), 'fldtxt') + self.assertEqual(m.data(m.indexFromName('fldint'), QgsFieldModel.FieldNameRole), 'fldint') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldNameRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldNameRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldNameRole)) + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldNameRole)) + + def testExpressionRole(self): + l, m = create_model() + self.assertEqual(m.data(m.indexFromName('fldtxt'), QgsFieldModel.ExpressionRole), 'fldtxt') + self.assertEqual(m.data(m.indexFromName('fldint'), QgsFieldModel.ExpressionRole), 'fldint') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.ExpressionRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.ExpressionRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertEqual(m.data(m.indexFromName('an expression'), QgsFieldModel.ExpressionRole), 'an expression') + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.ExpressionRole)) + + def testFieldIndexRole(self): + l, m = create_model() + self.assertEqual(m.data(m.indexFromName('fldtxt'), QgsFieldModel.FieldIndexRole), 0) + self.assertEqual(m.data(m.indexFromName('fldint'), QgsFieldModel.FieldIndexRole), 1) + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldIndexRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldIndexRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldIndexRole)) + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldIndexRole)) + + def testIsExpressionRole(self): + l, m = create_model() + self.assertFalse(m.data(m.indexFromName('fldtxt'), QgsFieldModel.IsExpressionRole)) + self.assertFalse(m.data(m.indexFromName('fldint'), QgsFieldModel.IsExpressionRole)) + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.IsExpressionRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.IsExpressionRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertTrue(m.data(m.indexFromName('an expression'), QgsFieldModel.IsExpressionRole)) + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.IsExpressionRole)) + + def testExpressionValidityRole(self): + l, m = create_model() + self.assertTrue(m.data(m.indexFromName('fldtxt'), QgsFieldModel.ExpressionValidityRole)) + self.assertTrue(m.data(m.indexFromName('fldint'), QgsFieldModel.ExpressionValidityRole)) + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.ExpressionValidityRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.ExpressionValidityRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.ExpressionValidityRole)) + m.setAllowEmptyFieldName(True) + self.assertTrue(m.data(m.indexFromName(None), QgsFieldModel.ExpressionValidityRole)) + + def testFieldTypeRole(self): + l, m = create_model() + self.assertEqual(m.data(m.indexFromName('fldtxt'), QgsFieldModel.FieldTypeRole), QVariant.String) + self.assertEqual(m.data(m.indexFromName('fldint'), QgsFieldModel.FieldTypeRole), QVariant.Int) + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldTypeRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldTypeRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldTypeRole)) + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldTypeRole)) + + def testFieldOriginRole(self): + l, m = create_model() + self.assertEqual(m.data(m.indexFromName('fldtxt'), QgsFieldModel.FieldOriginRole), QgsFields.OriginProvider) + self.assertEqual(m.data(m.indexFromName('fldint'), QgsFieldModel.FieldOriginRole), QgsFields.OriginProvider) + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldOriginRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldOriginRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.FieldOriginRole)) + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.FieldOriginRole)) + + def testIsEmptyRole(self): + l, m = create_model() + self.assertFalse(m.data(m.indexFromName('fldtxt'), QgsFieldModel.IsEmptyRole), QgsFields.OriginProvider) + self.assertFalse(m.data(m.indexFromName('fldint'), QgsFieldModel.IsEmptyRole), QgsFields.OriginProvider) + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.IsEmptyRole)) + self.assertFalse(m.data(m.indexFromName(None), QgsFieldModel.IsEmptyRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertFalse(m.data(m.indexFromName('an expression'), QgsFieldModel.IsEmptyRole)) + m.setAllowEmptyFieldName(True) + self.assertTrue(m.data(m.indexFromName(None), QgsFieldModel.IsEmptyRole)) + + def testDisplayRole(self): + l, m = create_model() + self.assertEqual(m.data(m.indexFromName('fldtxt'), Qt.DisplayRole), 'fldtxt') + self.assertEqual(m.data(m.indexFromName('fldint'), Qt.DisplayRole), 'fldint') + self.assertFalse(m.data(m.indexFromName('an expression'), Qt.DisplayRole)) + self.assertFalse(m.data(m.indexFromName(None), Qt.DisplayRole)) + m.setAllowExpression(True) + m.setExpression('an expression') + self.assertEqual(m.data(m.indexFromName('an expression'), Qt.DisplayRole), 'an expression') + m.setAllowEmptyFieldName(True) + self.assertFalse(m.data(m.indexFromName(None), Qt.DisplayRole)) + +if __name__ == '__main__': + unittest.main() From d3f5314bf5d4d358cd9952da4d651dbf1824b9f6 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 12:36:12 +1000 Subject: [PATCH 752/897] [processing] Use standard field combo box for field choices --- python/plugins/processing/gui/wrappers.py | 30 +++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index fe32b342a3d0..9a67b6dee080 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -36,7 +36,12 @@ from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer, QgsApplication from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit, QWidget, QHBoxLayout, QToolButton -from qgis.gui import QgsFieldExpressionWidget, QgsExpressionLineEdit, QgsProjectionSelectionWidget, QgsGenericProjectionSelector +from qgis.gui import (QgsFieldExpressionWidget, + QgsExpressionLineEdit, + QgsProjectionSelectionWidget, + QgsGenericProjectionSelector, + QgsFieldComboBox, + QgsFieldProxyModel) from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant from processing.gui.NumberInputPanel import NumberInputPanel @@ -861,7 +866,13 @@ def createWidget(self): if self.param.multiple: return MultipleInputPanel(options=[]) else: - widget = QComboBox() + widget = QgsFieldComboBox() + widget.setAllowEmptyFieldName(self.param.optional) + if self.param.datatype == ParameterTableField.DATA_TYPE_NUMBER: + widget.setFilters(QgsFieldProxyModel.Numeric) + elif self.param.datatype == ParameterTableField.DATA_TYPE_STRING: + widget.setFilters(QgsFieldProxyModel.String) + return widget else: widget = QComboBox() @@ -894,10 +905,8 @@ def refreshItems(self): if self.param.multiple: self.widget.updateForOptions(self.getFields()) else: - self.widget.clear() - if self.param.optional: - self.widget.addItem(self.tr(self.NOT_SET)) - self.widget.addItems(self.getFields()) + self.widget.setLayer(self._layer) + self.widget.setCurrentIndex(0) def getFields(self): if self._layer is None: @@ -916,7 +925,7 @@ def getFields(self): return sorted(list(fieldNames), key=cmp_to_key(locale.strcoll)) def setValue(self, value): - if self.dialogType == DIALOG_STANDARD: + if self.dialogType in (DIALOG_STANDARD, DIALOG_BATCH): if self.param.multiple: options = self.widget.options selected = [] @@ -925,7 +934,7 @@ def setValue(self, value): selected.append(i) self.widget.setSelectedItems(selected) else: - self.setComboValue(value) + self.widget.setField(value) else: self.setComboValue(value) @@ -934,9 +943,10 @@ def value(self): if self.param.multiple: return [self.widget.options[i] for i in self.widget.selectedoptions] else: - if self.param.optional and self.widget.currentIndex() == 0: + f = self.widget.field() + if self.param.optional and not f: return None - return self.widget.currentText() + return f else: def validator(v): return bool(v) or self.param.optional From 4a5faa083f1e737edb7ee680c9d1f841fdb369c9 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 15:20:24 +1000 Subject: [PATCH 753/897] Remove duplicate selectionChanged signal from QgsVectorLayer If you don't want the extra info, just don't capture it... --- doc/api_break.dox | 2 +- python/core/qgsvectorlayer.sip | 3 --- src/app/qgsattributetabledialog.cpp | 2 +- src/app/qgsstatisticalsummarydockwidget.cpp | 6 ++--- src/core/qgsvectorlayer.cpp | 3 +-- src/core/qgsvectorlayer.h | 3 --- .../qgsattributetablefiltermodel.cpp | 2 +- .../qgsvectorlayerselectionmanager.cpp | 2 +- src/gui/qgsattributeform.cpp | 2 +- src/gui/qgsmapcanvas.cpp | 4 ++-- src/plugins/grass/qgsgrassmoduleparam.cpp | 3 +-- .../spatialquery/qgsspatialquerydialog.cpp | 24 +++++++++---------- 12 files changed, 24 insertions(+), 32 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index b61e5aa78808..0667a0f0ba03 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1504,7 +1504,7 @@ displayExpression instead. For the map tip use mapTipTemplate() instead. - saveStyleToDatabase(): msgError argument is correctly declared as output argument - getStyleFromDatabase(): msgError argument is correctly declared as output argument - loadNamedStyle(): theResultFlag argument is correctly declared as output argument - +- The duplicate selectionChanged() signal was removed. Use selectionChanged( const QgsFeatureIds&, const QgsFeatureIds&, const bool ) instead. QgsVectorLayerEditBuffer {#qgis_api_break_3_0_QgsVectorLayerEditBuffer} ------------------------ diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index 88d9b3320dda..6957294a7a8e 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1548,9 +1548,6 @@ class QgsVectorLayer : QgsMapLayer, QgsExpressionContextGenerator */ void selectionChanged( const QgsFeatureIds& selected, const QgsFeatureIds& deselected, const bool clearAndSelect ); - /** This signal is emitted when selection was changed */ - void selectionChanged(); - /** This signal is emitted when modifications has been done on layer */ void layerModified(); diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 05ca1eebcdd3..230075602dea 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -181,7 +181,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid connect( mLayer, SIGNAL( editingStarted() ), this, SLOT( editingToggled() ) ); connect( mLayer, SIGNAL( editingStopped() ), this, SLOT( editingToggled() ) ); connect( mLayer, SIGNAL( destroyed() ), this, SLOT( close() ) ); - connect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( updateTitle() ) ); + connect( mLayer, &QgsVectorLayer::selectionChanged, this, &QgsAttributeTableDialog::updateTitle ); connect( mLayer, SIGNAL( featureAdded( QgsFeatureId ) ), this, SLOT( updateTitle() ) ); connect( mLayer, SIGNAL( featuresDeleted( QgsFeatureIds ) ), this, SLOT( updateTitle() ) ); connect( mLayer, SIGNAL( attributeAdded( int ) ), this, SLOT( columnBoxInit() ) ); diff --git a/src/app/qgsstatisticalsummarydockwidget.cpp b/src/app/qgsstatisticalsummarydockwidget.cpp index 81bb31dafb05..13cb91ddacd0 100644 --- a/src/app/qgsstatisticalsummarydockwidget.cpp +++ b/src/app/qgsstatisticalsummarydockwidget.cpp @@ -251,14 +251,14 @@ void QgsStatisticalSummaryDockWidget::layerChanged( QgsMapLayer *layer ) QgsVectorLayer* newLayer = dynamic_cast< QgsVectorLayer* >( layer ); if ( mLayer && mLayer != newLayer ) { - disconnect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( layerSelectionChanged() ) ); + disconnect( mLayer, &QgsVectorLayer::selectionChanged, this, &QgsStatisticalSummaryDockWidget::layerSelectionChanged ); } mLayer = newLayer; if ( mLayer ) { - connect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( layerSelectionChanged() ) ); + connect( mLayer, &QgsVectorLayer::selectionChanged, this, &QgsStatisticalSummaryDockWidget::layerSelectionChanged ); } mFieldExpressionWidget->setLayer( mLayer ); @@ -294,7 +294,7 @@ void QgsStatisticalSummaryDockWidget::layersRemoved( const QStringList& layers ) { if ( mLayer && layers.contains( mLayer->id() ) ) { - disconnect( mLayer, SIGNAL( selectionChanged() ), this, SLOT( layerSelectionChanged() ) ); + disconnect( mLayer, &QgsVectorLayer::selectionChanged, this, &QgsStatisticalSummaryDockWidget::layerSelectionChanged ); mLayer = nullptr; } } diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 5216661b48ab..ad7af11e3e68 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -155,8 +155,7 @@ QgsVectorLayer::QgsVectorLayer( const QString& vectorLayerPath, setDataSource( vectorLayerPath, baseName, providerKey, loadDefaultStyleFlag ); } - connect( this, SIGNAL( selectionChanged( QgsFeatureIds, QgsFeatureIds, bool ) ), this, SIGNAL( selectionChanged() ) ); - connect( this, SIGNAL( selectionChanged( QgsFeatureIds, QgsFeatureIds, bool ) ), this, SIGNAL( repaintRequested() ) ); + connect( this, &QgsVectorLayer::selectionChanged, this, &QgsVectorLayer::repaintRequested ); connect( QgsProject::instance()->relationManager(), &QgsRelationManager::relationsLoaded, this, &QgsVectorLayer::onRelationsLoaded ); // Default simplify drawing settings diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index 3631f7e1351f..da3955d991c0 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -1691,9 +1691,6 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void selectionChanged( const QgsFeatureIds& selected, const QgsFeatureIds& deselected, const bool clearAndSelect ); - //! This signal is emitted when selection was changed - void selectionChanged(); - //! This signal is emitted when modifications has been done on layer void layerModified(); diff --git a/src/gui/attributetable/qgsattributetablefiltermodel.cpp b/src/gui/attributetable/qgsattributetablefiltermodel.cpp index 84f53b024829..ba977d482635 100644 --- a/src/gui/attributetable/qgsattributetablefiltermodel.cpp +++ b/src/gui/attributetable/qgsattributetablefiltermodel.cpp @@ -38,7 +38,7 @@ QgsAttributeTableFilterModel::QgsAttributeTableFilterModel( QgsMapCanvas* canvas setSourceModel( sourceModel ); setDynamicSortFilter( true ); setSortRole( QgsAttributeTableModel::SortRole ); - connect( layer(), SIGNAL( selectionChanged() ), SLOT( selectionChanged() ) ); + connect( layer(), &QgsVectorLayer::selectionChanged, this, &QgsAttributeTableFilterModel::selectionChanged ); } bool QgsAttributeTableFilterModel::lessThan( const QModelIndex &left, const QModelIndex &right ) const diff --git a/src/gui/attributetable/qgsvectorlayerselectionmanager.cpp b/src/gui/attributetable/qgsvectorlayerselectionmanager.cpp index 651dba316b09..bf013d700844 100644 --- a/src/gui/attributetable/qgsvectorlayerselectionmanager.cpp +++ b/src/gui/attributetable/qgsvectorlayerselectionmanager.cpp @@ -21,7 +21,7 @@ QgsVectorLayerSelectionManager::QgsVectorLayerSelectionManager( QgsVectorLayer* : QgsIFeatureSelectionManager( parent ) , mLayer( layer ) { - connect( mLayer, SIGNAL( selectionChanged( QgsFeatureIds, QgsFeatureIds, bool ) ), this, SIGNAL( selectionChanged( QgsFeatureIds, QgsFeatureIds, bool ) ) ); + connect( mLayer, &QgsVectorLayer::selectionChanged, this, &QgsVectorLayerSelectionManager::selectionChanged ); } int QgsVectorLayerSelectionManager::selectedFeatureCount() diff --git a/src/gui/qgsattributeform.cpp b/src/gui/qgsattributeform.cpp index 9f415c5cf442..fac6533e901c 100644 --- a/src/gui/qgsattributeform.cpp +++ b/src/gui/qgsattributeform.cpp @@ -78,7 +78,7 @@ QgsAttributeForm::QgsAttributeForm( QgsVectorLayer* vl, const QgsFeature &featur connect( vl, &QgsVectorLayer::updatedFields, this, &QgsAttributeForm::onUpdatedFields ); connect( vl, &QgsVectorLayer::beforeAddingExpressionField, this, &QgsAttributeForm::preventFeatureRefresh ); connect( vl, &QgsVectorLayer::beforeRemovingExpressionField, this, &QgsAttributeForm::preventFeatureRefresh ); - connect( vl, SIGNAL( selectionChanged() ), this, SLOT( layerSelectionChanged() ) ); + connect( vl, &QgsVectorLayer::selectionChanged, this, &QgsAttributeForm::layerSelectionChanged ); // constraints management updateAllConstraints(); diff --git a/src/gui/qgsmapcanvas.cpp b/src/gui/qgsmapcanvas.cpp index 3f0751416f96..2838a5ecd010 100644 --- a/src/gui/qgsmapcanvas.cpp +++ b/src/gui/qgsmapcanvas.cpp @@ -336,7 +336,7 @@ void QgsMapCanvas::setLayerSet( QList &layers ) QgsVectorLayer *isVectLyr = qobject_cast( currentLayer ); if ( isVectLyr ) { - disconnect( currentLayer, SIGNAL( selectionChanged() ), this, SLOT( selectionChangedSlot() ) ); + disconnect( isVectLyr, &QgsVectorLayer::selectionChanged, this, &QgsMapCanvas::selectionChangedSlot ); } } @@ -354,7 +354,7 @@ void QgsMapCanvas::setLayerSet( QList &layers ) QgsVectorLayer *isVectLyr = qobject_cast( currentLayer ); if ( isVectLyr ) { - connect( currentLayer, SIGNAL( selectionChanged() ), this, SLOT( selectionChangedSlot() ) ); + connect( isVectLyr, &QgsVectorLayer::selectionChanged, this, &QgsMapCanvas::selectionChangedSlot ); } } diff --git a/src/plugins/grass/qgsgrassmoduleparam.cpp b/src/plugins/grass/qgsgrassmoduleparam.cpp index 5c74c741c635..0e35a0a36727 100644 --- a/src/plugins/grass/qgsgrassmoduleparam.cpp +++ b/src/plugins/grass/qgsgrassmoduleparam.cpp @@ -1388,8 +1388,7 @@ void QgsGrassModuleSelection::onModeChanged() if ( vectorLayer ) { onLayerSelectionChanged(); - connect( vectorLayer, SIGNAL( selectionChanged( const QgsFeatureIds, const QgsFeatureIds, const bool ) ), - SLOT( onLayerSelectionChanged() ) ); + connect( vectorLayer, &QgsVectorLayer::selectionChanged, this, &QgsGrassModuleSelection::onLayerSelectionChanged ); } } } diff --git a/src/plugins/spatialquery/qgsspatialquerydialog.cpp b/src/plugins/spatialquery/qgsspatialquerydialog.cpp index 12a4ed61ef69..5d32556d52bc 100644 --- a/src/plugins/spatialquery/qgsspatialquerydialog.cpp +++ b/src/plugins/spatialquery/qgsspatialquerydialog.cpp @@ -125,23 +125,23 @@ void QgsSpatialQueryDialog::setLayer( bool isTarget, int index ) { if ( mLayerTarget ) { - disconnect( mLayerTarget, SIGNAL( selectionChanged() ), - this, SLOT( signal_layerTarget_selectionFeaturesChanged() ) ); + disconnect( mLayerTarget, &QgsVectorLayer::selectionChanged, + this, &QgsSpatialQueryDialog::signal_layerTarget_selectionFeaturesChanged ); } mLayerTarget = getLayerFromCombobox( isTarget, index ); - connect( mLayerTarget, SIGNAL( selectionChanged() ), - this, SLOT( signal_layerTarget_selectionFeaturesChanged() ) ); + connect( mLayerTarget, &QgsVectorLayer::selectionChanged, + this, &QgsSpatialQueryDialog::signal_layerTarget_selectionFeaturesChanged ); } else { if ( mLayerReference ) { - disconnect( mLayerReference, SIGNAL( selectionChanged() ), - this, SLOT( signal_layerReference_selectionFeaturesChanged() ) ); + disconnect( mLayerReference, &QgsVectorLayer::selectionChanged, + this, &QgsSpatialQueryDialog::signal_layerReference_selectionFeaturesChanged ); } mLayerReference = getLayerFromCombobox( isTarget, index ); - connect( mLayerReference, SIGNAL( selectionChanged() ), - this, SLOT( signal_layerReference_selectionFeaturesChanged() ) ); + connect( mLayerReference, &QgsVectorLayer::selectionChanged, + this, &QgsSpatialQueryDialog::signal_layerReference_selectionFeaturesChanged ); } } // void QgsSpatialQueryDialog::setLayer(bool isTarget, int index) @@ -369,14 +369,14 @@ void QgsSpatialQueryDialog::disconnectAll() if ( mLayerTarget ) { - disconnect( mLayerTarget, SIGNAL( selectionChanged() ), - this, SLOT( signal_layerTarget_selectionFeaturesChanged() ) ); + disconnect( mLayerTarget, &QgsVectorLayer::selectionChanged, + this, &QgsSpatialQueryDialog::signal_layerTarget_selectionFeaturesChanged ); } if ( mLayerReference ) { - disconnect( mLayerReference, SIGNAL( selectionChanged() ), - this, SLOT( signal_layerReference_selectionFeaturesChanged() ) ); + disconnect( mLayerReference, &QgsVectorLayer::selectionChanged, + this, &QgsSpatialQueryDialog::signal_layerReference_selectionFeaturesChanged ); } } // QgsSpatialQueryDialog::disconnectAll() From 5d78d60bf3fac2fa2401107e6ba15cdf8ead4ce0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 15:29:00 +1000 Subject: [PATCH 754/897] Remove duplicate QgsDataProvider::dataChanged( int ) signal Was not needed and not emitted anywhere --- doc/api_break.dox | 6 ++++++ python/core/qgsdataprovider.sip | 6 ------ src/app/qgisapp.cpp | 4 ++-- src/browser/qgsbrowser.cpp | 4 ++-- src/core/qgsdataprovider.h | 6 ------ src/core/qgspointlocator.cpp | 2 +- src/core/qgstransaction.cpp | 2 +- src/core/qgsvectorlayer.cpp | 4 ++-- 8 files changed, 14 insertions(+), 20 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 0667a0f0ba03..3a9223bac0c7 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -668,6 +668,12 @@ QgsDataItem {#qgis_api_break_3_0_QgsDataItem} - emitBeginInsertItems(), emitEndInsertItems(), emitBeginRemoveItems(), emitEndRemoveItems(), emitDataChanged(), emitStateChanged() have been removed. - Favourites was renamed to Favorites +QgsDataProvider {#qgis_api_break_3_0_QgsDataProvider} +--------------- + +- The duplicate (and unused) dataChanged( int ) signal was removed. Use dataChanged() instead. + + QgsDataSourceURI {#qgis_api_break_3_0_QgsDatasourceUri} ---------------- diff --git a/python/core/qgsdataprovider.sip b/python/core/qgsdataprovider.sip index c9423f04510a..9a30fb14f234 100644 --- a/python/core/qgsdataprovider.sip +++ b/python/core/qgsdataprovider.sip @@ -326,12 +326,6 @@ class QgsDataProvider : QObject */ void dataChanged(); - /** - * This is emitted whenever data or metadata (e.g. color table, extent) has changed - * @param changed binary combination of changes - */ - void dataChanged( int changed ); - protected: /** Add error message */ diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 05ffeebbe70d..56931e374a3c 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -10258,8 +10258,8 @@ void QgisApp::layersWereAdded( const QList& theLayers ) if ( provider ) { - connect( provider, SIGNAL( dataChanged() ), layer, SLOT( triggerRepaint() ) ); - connect( provider, SIGNAL( dataChanged() ), mMapCanvas, SLOT( refresh() ) ); + connect( provider, &QgsDataProvider::dataChanged, layer, &QgsMapLayer::triggerRepaint ); + connect( provider, &QgsDataProvider::dataChanged, mMapCanvas, &QgsMapCanvas::refresh ); } } } diff --git a/src/browser/qgsbrowser.cpp b/src/browser/qgsbrowser.cpp index e62ab99822d7..d6a399c395dc 100644 --- a/src/browser/qgsbrowser.cpp +++ b/src/browser/qgsbrowser.cpp @@ -442,8 +442,8 @@ void QgsBrowser::updateCurrentTab() QgsRasterLayer *rlayer = qobject_cast< QgsRasterLayer * >( mLayer ); if ( rlayer ) { - connect( rlayer->dataProvider(), SIGNAL( dataChanged() ), rlayer, SLOT( triggerRepaint() ) ); - connect( rlayer->dataProvider(), SIGNAL( dataChanged() ), mapCanvas, SLOT( refresh() ) ); + connect( rlayer->dataProvider(), &QgsRasterDataProvider::dataChanged, rlayer, &QgsRasterLayer::triggerRepaint ); + connect( rlayer->dataProvider(), &QgsRasterDataProvider::dataChanged, mapCanvas, &QgsMapCanvas::refresh ); } } mDirtyPreview = false; diff --git a/src/core/qgsdataprovider.h b/src/core/qgsdataprovider.h index c690dcd285ca..a7fe47ea8271 100644 --- a/src/core/qgsdataprovider.h +++ b/src/core/qgsdataprovider.h @@ -415,12 +415,6 @@ class CORE_EXPORT QgsDataProvider : public QObject */ void dataChanged(); - /** - * This is emitted whenever data or metadata (e.g. color table, extent) has changed - * @param changed binary combination of changes - */ - void dataChanged( int changed ); - protected: /** diff --git a/src/core/qgspointlocator.cpp b/src/core/qgspointlocator.cpp index 902131a2d103..9264cd108f0c 100644 --- a/src/core/qgspointlocator.cpp +++ b/src/core/qgspointlocator.cpp @@ -631,7 +631,7 @@ QgsPointLocator::QgsPointLocator( QgsVectorLayer* layer, const QgsCoordinateRefe connect( mLayer, SIGNAL( featureAdded( QgsFeatureId ) ), this, SLOT( onFeatureAdded( QgsFeatureId ) ) ); connect( mLayer, SIGNAL( featureDeleted( QgsFeatureId ) ), this, SLOT( onFeatureDeleted( QgsFeatureId ) ) ); connect( mLayer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry& ) ), this, SLOT( onGeometryChanged( QgsFeatureId, const QgsGeometry& ) ) ); - connect( mLayer, SIGNAL( dataChanged() ), this, SLOT( destroyIndex() ) ); + connect( mLayer, &QgsVectorLayer::dataChanged, this, &QgsPointLocator::destroyIndex ); } diff --git a/src/core/qgstransaction.cpp b/src/core/qgstransaction.cpp index 418d90702ff4..ec8d34adae08 100644 --- a/src/core/qgstransaction.cpp +++ b/src/core/qgstransaction.cpp @@ -112,7 +112,7 @@ bool QgsTransaction::addLayer( QgsVectorLayer* layer ) return false; } - connect( this, SIGNAL( afterRollback() ), layer->dataProvider(), SIGNAL( dataChanged() ) ); + connect( this, &QgsTransaction::afterRollback, layer->dataProvider(), &QgsVectorDataProvider::dataChanged ); connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( onLayersDeleted( QStringList ) ) ); mLayers.insert( layer ); diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index ad7af11e3e68..80d9cf91b5c7 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -1628,8 +1628,8 @@ bool QgsVectorLayer::setDataProvider( QString const & provider ) mDataSource.chop( 10 ); } - connect( mDataProvider, SIGNAL( dataChanged() ), this, SIGNAL( dataChanged() ) ); - connect( mDataProvider, SIGNAL( dataChanged() ), this, SLOT( removeSelection() ) ); + connect( mDataProvider, &QgsVectorDataProvider::dataChanged, this, &QgsVectorLayer::dataChanged ); + connect( mDataProvider, &QgsVectorDataProvider::dataChanged, this, &QgsVectorLayer::removeSelection ); return true; } // QgsVectorLayer:: setDataProvider From 29d33b47fe050f1004cc8a5d8474018dd84ce72d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 15 Nov 2016 09:27:14 +1000 Subject: [PATCH 755/897] [processing] Polygons to line fixes - Maintain Z/M values - Handle curved geometries without segmentizing - Retain null geometries --- .../processing/algs/qgis/LinesToPolygons.py | 1 + .../processing/algs/qgis/PolygonsToLines.py | 34 +++++-------------- .../testdata/expected/polys_to_lines.gml | 7 ++++ 3 files changed, 16 insertions(+), 26 deletions(-) diff --git a/python/plugins/processing/algs/qgis/LinesToPolygons.py b/python/plugins/processing/algs/qgis/LinesToPolygons.py index ada0edd7fd6d..7c0331acfb3d 100644 --- a/python/plugins/processing/algs/qgis/LinesToPolygons.py +++ b/python/plugins/processing/algs/qgis/LinesToPolygons.py @@ -50,6 +50,7 @@ def getIcon(self): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Lines to polygons') self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + self.tags = self.tr('line,polygon,convert') self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'), diff --git a/python/plugins/processing/algs/qgis/PolygonsToLines.py b/python/plugins/processing/algs/qgis/PolygonsToLines.py index b5472839f291..45eb45110f53 100644 --- a/python/plugins/processing/algs/qgis/PolygonsToLines.py +++ b/python/plugins/processing/algs/qgis/PolygonsToLines.py @@ -50,6 +50,7 @@ def getIcon(self): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Polygons to lines') self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools') + self.tags = self.tr('line,polygon,convert') self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'), [dataobjects.TYPE_VECTOR_POLYGON])) @@ -62,36 +63,17 @@ def processAlgorithm(self, progress): writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.fields().toList(), QgsWkbTypes.LineString, layer.crs()) - outFeat = QgsFeature() - inGeom = QgsGeometry() - outGeom = QgsGeometry() - features = vector.features(layer) total = 100.0 / len(features) for current, f in enumerate(features): - inGeom = f.geometry() - attrs = f.attributes() - lineList = self.extractAsLine(inGeom) - outFeat.setAttributes(attrs) - for h in lineList: - outFeat.setGeometry(outGeom.fromPolyline(h)) - writer.addFeature(outFeat) + if f.hasGeometry(): + lines = QgsGeometry(f.geometry().geometry().boundary()).asGeometryCollection() + for line in lines: + f.setGeometry(line) + writer.addFeature(f) + else: + writer.addFeature(f) progress.setPercentage(int(current * total)) del writer - - def extractAsLine(self, geom): - multiGeom = QgsGeometry() - lines = [] - if geom and geom.type() == QgsWkbTypes.PolygonGeometry: - if geom.isMultipart(): - multiGeom = geom.asMultiPolygon() - for i in multiGeom: - lines.extend(i) - else: - multiGeom = geom.asPolygon() - lines = multiGeom - return lines - else: - return [] diff --git a/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml b/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml index e68960925b45..ce07984e3fe1 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml +++ b/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml @@ -37,4 +37,11 @@ -0.123 + + + Test + 3 + 0 + + From d237e27d7e21b4b7129175d86aaf3552e7c9fe92 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 15 Nov 2016 10:15:43 +1000 Subject: [PATCH 756/897] Followup 29d33b4 --- .../processing/tests/testdata/expected/polys_to_lines.gfs | 3 ++- .../processing/tests/testdata/expected/polys_to_lines.gml | 6 +++--- .../processing/tests/testdata/qgis_algorithm_tests.yaml | 3 +++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/python/plugins/processing/tests/testdata/expected/polys_to_lines.gfs b/python/plugins/processing/tests/testdata/expected/polys_to_lines.gfs index 1aa78269eb0f..ea3e274285e0 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_to_lines.gfs +++ b/python/plugins/processing/tests/testdata/expected/polys_to_lines.gfs @@ -2,10 +2,11 @@ polys_to_lines polys_to_lines + 2 EPSG:4326 - 4 + 5 0.00000 9.00000 -1.00000 diff --git a/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml b/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml index ce07984e3fe1..6fb2f5867f51 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml +++ b/python/plugins/processing/tests/testdata/expected/polys_to_lines.gml @@ -25,12 +25,12 @@ - + 7,6 7,5 7,4 8,4 9,5 9,6 7,6 - + 0,0 0,1 1,1 1,0 0,0 Test 2 @@ -38,7 +38,7 @@ - + Test 3 0 diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 2ad81d07163d..5c7d77613a70 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -148,6 +148,9 @@ tests: OUTPUT: name: expected/polys_to_lines.gml type: vector + compare: + fields: + fid: skip - algorithm: qgis:basicstatisticsfornumericfields name: Basic statistics for numeric fields From 8908eea43bb0cce524f21732f14a8a5e924d2227 Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Tue, 15 Nov 2016 09:51:12 +0800 Subject: [PATCH 757/897] Fix rubber band in node tool not getting updated correctly --- src/app/nodetool/qgsmaptoolnodetool.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/nodetool/qgsmaptoolnodetool.cpp b/src/app/nodetool/qgsmaptoolnodetool.cpp index 7015af367b39..d8a3da8cde59 100644 --- a/src/app/nodetool/qgsmaptoolnodetool.cpp +++ b/src/app/nodetool/qgsmaptoolnodetool.cpp @@ -252,7 +252,7 @@ void QgsMapToolNodeTool::canvasPressEvent( QgsMapMouseEvent* e ) } connect( QgisApp::instance()->layerTreeView(), SIGNAL( currentLayerChanged( QgsMapLayer* ) ), this, SLOT( currentLayerChanged( QgsMapLayer* ) ) ); connect( mSelectedFeature, SIGNAL( destroyed() ), this, SLOT( selectedFeatureDestroyed() ) ); - connect( vlayer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry & ) ), this, SLOT( geometryChanged( QgsFeatureId, QgsGeometry & ) ) ); + connect( vlayer, SIGNAL( geometryChanged( QgsFeatureId, const QgsGeometry & ) ), this, SLOT( geometryChanged( QgsFeatureId, const QgsGeometry & ) ) ); connect( vlayer, SIGNAL( editingStopped() ), this, SLOT( editingToggled() ) ); mIsPoint = vlayer->geometryType() == QgsWkbTypes::PointGeometry; mNodeEditor = new QgsNodeEditor( vlayer, mSelectedFeature, mCanvas ); From c87839f0549f21af0b96e5d2d096ff8ffa346b75 Mon Sep 17 00:00:00 2001 From: nirvn Date: Tue, 15 Nov 2016 09:07:58 +0700 Subject: [PATCH 758/897] [processing] fix ExtentSelectionPanel's getValue() --- python/plugins/processing/gui/AlgorithmDialog.py | 2 +- python/plugins/processing/gui/ExtentSelectionPanel.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/gui/AlgorithmDialog.py b/python/plugins/processing/gui/AlgorithmDialog.py index 89f2d34900bc..052b6e2cdfa8 100644 --- a/python/plugins/processing/gui/AlgorithmDialog.py +++ b/python/plugins/processing/gui/AlgorithmDialog.py @@ -211,7 +211,7 @@ def accept(self): self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: - self.buttonBox.accepted.connect(lambda: + self.buttonBox.accepted.connect(lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) diff --git a/python/plugins/processing/gui/ExtentSelectionPanel.py b/python/plugins/processing/gui/ExtentSelectionPanel.py index 408d88c7eed3..6ec0d34208a7 100644 --- a/python/plugins/processing/gui/ExtentSelectionPanel.py +++ b/python/plugins/processing/gui/ExtentSelectionPanel.py @@ -153,7 +153,7 @@ def setValueFromRect(self, r): self.dialog.activateWindow() def getValue(self): - if str(self.leText.text()).strip() == '': + if str(self.leText.text()).strip() != '': return str(self.leText.text()) else: return None From 4a4ffa4c1b68604b7f9240891574f796c4dc0cc7 Mon Sep 17 00:00:00 2001 From: nirvn Date: Tue, 15 Nov 2016 09:16:11 +0700 Subject: [PATCH 759/897] [processing] fix grass/grass7 installation check --- python/plugins/processing/algs/grass/GrassUtils.py | 2 +- python/plugins/processing/algs/grass7/Grass7Utils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/grass/GrassUtils.py b/python/plugins/processing/algs/grass/GrassUtils.py index 903a569569b9..4324e7f4d0df 100644 --- a/python/plugins/processing/algs/grass/GrassUtils.py +++ b/python/plugins/processing/algs/grass/GrassUtils.py @@ -383,7 +383,7 @@ def checkGrassIsInstalled(ignorePreviousState=False): points(), False, False, - 'None', + None, -1, 0.0001, 0, diff --git a/python/plugins/processing/algs/grass7/Grass7Utils.py b/python/plugins/processing/algs/grass7/Grass7Utils.py index ea7d7a3f8418..45d84a884a79 100644 --- a/python/plugins/processing/algs/grass7/Grass7Utils.py +++ b/python/plugins/processing/algs/grass7/Grass7Utils.py @@ -363,7 +363,7 @@ def checkGrass7IsInstalled(ignorePreviousState=False): points(), False, False, - 'None', + None, -1, 0.0001, 0, From 38a4aac97117d81d11beb96f7b15fe25ff1ea6d4 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 12:25:57 +1000 Subject: [PATCH 760/897] Fix test for request size vs cache size On behalf of Faunalia, sponsored by ENEL --- src/core/qgsvectorlayercache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/qgsvectorlayercache.cpp b/src/core/qgsvectorlayercache.cpp index 74a8ef7c6cdb..dd8e74ec70be 100644 --- a/src/core/qgsvectorlayercache.cpp +++ b/src/core/qgsvectorlayercache.cpp @@ -174,7 +174,7 @@ QgsVectorLayer* QgsVectorLayerCache::layer() void QgsVectorLayerCache::requestCompleted( const QgsFeatureRequest& featureRequest, const QgsFeatureIds& fids ) { // If a request is too large for the cache don't notify to prevent from indexing incomplete requests - if ( fids.count() < mCache.size() ) + if ( fids.count() <= mCache.size() ) { Q_FOREACH ( QgsAbstractCacheIndex* idx, mCacheIndices ) { From afd5d1e9344f41a40f882fb204810f8e650813c0 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 12:28:00 +1000 Subject: [PATCH 761/897] Recognise that a cache can be filled using a FilterNone request On behalf of Faunalia, sponsored by ENEL --- python/core/qgsvectorlayercache.sip | 9 ++++ src/core/qgsvectorlayercache.cpp | 4 ++ src/core/qgsvectorlayercache.h | 9 ++++ tests/src/core/testqgsvectorlayercache.cpp | 48 ++++++++++++++++++++++ 4 files changed, 70 insertions(+) diff --git a/python/core/qgsvectorlayercache.sip b/python/core/qgsvectorlayercache.sip index 99a3fd196b66..3fe37c87f077 100644 --- a/python/core/qgsvectorlayercache.sip +++ b/python/core/qgsvectorlayercache.sip @@ -65,9 +65,18 @@ class QgsVectorLayerCache : QObject * be used for slow data sources, be aware, that the call to this method might take a long time. * * @param fullCache True: enable full caching, False: disable full caching + * @see hasFullCache() */ void setFullCache( bool fullCache ); + /** Returns true if the cache is complete, ie it contains all features. This may happen as + * a result of a call to setFullCache() or by through a feature request which resulted in + * all available features being cached. + * @see setFullCache() + * @note added in QGIS 3.0 + */ + bool hasFullCache() const; + /** * @brief * Adds a {@link QgsAbstractCacheIndex} to this cache. Cache indices know about features present diff --git a/src/core/qgsvectorlayercache.cpp b/src/core/qgsvectorlayercache.cpp index dd8e74ec70be..ffb067a4865e 100644 --- a/src/core/qgsvectorlayercache.cpp +++ b/src/core/qgsvectorlayercache.cpp @@ -180,6 +180,10 @@ void QgsVectorLayerCache::requestCompleted( const QgsFeatureRequest& featureRequ { idx->requestCompleted( featureRequest, fids ); } + if ( featureRequest.filterType() == QgsFeatureRequest::FilterNone ) + { + mFullCache = true; + } } } diff --git a/src/core/qgsvectorlayercache.h b/src/core/qgsvectorlayercache.h index d7c766c63c6d..c06127e118da 100644 --- a/src/core/qgsvectorlayercache.h +++ b/src/core/qgsvectorlayercache.h @@ -133,9 +133,18 @@ class CORE_EXPORT QgsVectorLayerCache : public QObject * be used for slow data sources, be aware, that the call to this method might take a long time. * * @param fullCache True: enable full caching, False: disable full caching + * @see hasFullCache() */ void setFullCache( bool fullCache ); + /** Returns true if the cache is complete, ie it contains all features. This may happen as + * a result of a call to setFullCache() or by through a feature request which resulted in + * all available features being cached. + * @see setFullCache() + * @note added in QGIS 3.0 + */ + bool hasFullCache() const { return mFullCache; } + /** * @brief * Adds a {@link QgsAbstractCacheIndex} to this cache. Cache indices know about features present diff --git a/tests/src/core/testqgsvectorlayercache.cpp b/tests/src/core/testqgsvectorlayercache.cpp index 5cd564feb8a2..f5d68ed258e9 100644 --- a/tests/src/core/testqgsvectorlayercache.cpp +++ b/tests/src/core/testqgsvectorlayercache.cpp @@ -52,6 +52,8 @@ class TestVectorLayerCache : public QObject void testCacheAttrActions(); // Test attribute add/ attribute delete void testFeatureActions(); // Test adding/removing features works void testSubsetRequest(); + void testFullCache(); + void testFullCacheThroughRequest(); void onCommittedFeaturesAdded( const QString&, const QgsFeatureList& ); @@ -219,6 +221,52 @@ void TestVectorLayerCache::testSubsetRequest() QVERIFY( a == f.attribute( 3 ) ); } +void TestVectorLayerCache::testFullCache() +{ + // cache is too small to fit all features + QgsVectorLayerCache cache( mPointsLayer, 2 ); + QVERIFY( !cache.hasFullCache() ); + QVERIFY( cache.cacheSize() < mPointsLayer->featureCount() ); + // but we set it to full cache + cache.setFullCache( true ); + // so now it should have sufficient size for all features + QVERIFY( cache.cacheSize() >= mPointsLayer->featureCount() ); + QVERIFY( cache.hasFullCache() ); + + // double check that everything is indeed in the cache + QgsFeatureIterator it = mPointsLayer->getFeatures(); + QgsFeature f; + while ( it.nextFeature( f ) ) + { + QVERIFY( cache.isFidCached( f.id() ) ); + } +} + +void TestVectorLayerCache::testFullCacheThroughRequest() +{ + // make sure cache is sufficient size for all features + QgsVectorLayerCache cache( mPointsLayer, mPointsLayer->featureCount() * 2 ); + QVERIFY( !cache.hasFullCache() ); + + // now request all features from cache + QgsFeatureIterator it = cache.getFeatures( QgsFeatureRequest() ); + QgsFeature f; + while ( it.nextFeature( f ) ) + { + // suck in all features + } + + // cache should now contain all features + it = mPointsLayer->getFeatures(); + while ( it.nextFeature( f ) ) + { + QVERIFY( cache.isFidCached( f.id() ) ); + } + + // so it should be a full cache! + QVERIFY( cache.hasFullCache() ); +} + void TestVectorLayerCache::onCommittedFeaturesAdded( const QString& layerId, const QgsFeatureList& features ) { Q_UNUSED( layerId ) From 5e3d8fe0b6ee3e1fe16deceb7af24b89e15dbf93 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 13:16:54 +1000 Subject: [PATCH 762/897] Use cached feature iterator if cache has all needed features Previously a cached feature iterator would only be returned if cache was either full or used a cache index On behalf of Faunalia, sponsored by ENEL --- src/core/qgsvectorlayercache.cpp | 59 ++++++++++++++++---- src/core/qgsvectorlayercache.h | 11 ++++ tests/src/core/testqgsvectorlayercache.cpp | 62 ++++++++++++++++++++++ 3 files changed, 123 insertions(+), 9 deletions(-) diff --git a/src/core/qgsvectorlayercache.cpp b/src/core/qgsvectorlayercache.cpp index ffb067a4865e..47e4f59db140 100644 --- a/src/core/qgsvectorlayercache.cpp +++ b/src/core/qgsvectorlayercache.cpp @@ -270,6 +270,54 @@ void QgsVectorLayerCache::invalidate() emit invalidated(); } +bool QgsVectorLayerCache::canUseCacheForRequest( const QgsFeatureRequest &featureRequest, QgsFeatureIterator& it ) +{ + // check first for available indices + Q_FOREACH ( QgsAbstractCacheIndex *idx, mCacheIndices ) + { + if ( idx->getCacheIterator( it, featureRequest ) ) + { + return true; + } + } + + // no indexes available, but maybe we have already cached all required features anyway? + switch ( featureRequest.filterType() ) + { + case QgsFeatureRequest::FilterFid: + { + if ( mCache.contains( featureRequest.filterFid() ) ) + { + it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) ); + return true; + } + break; + } + case QgsFeatureRequest::FilterFids: + { + if ( mCache.keys().toSet().contains( featureRequest.filterFids() ) ) + { + it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) ); + return true; + } + break; + } + case QgsFeatureRequest::FilterNone: + case QgsFeatureRequest::FilterRect: + case QgsFeatureRequest::FilterExpression: + { + if ( mFullCache ) + { + it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) ); + return true; + } + break; + } + + } + return false; +} + QgsFeatureIterator QgsVectorLayerCache::getFeatures( const QgsFeatureRequest &featureRequest ) { QgsFeatureIterator it; @@ -285,15 +333,8 @@ QgsFeatureIterator QgsVectorLayerCache::getFeatures( const QgsFeatureRequest &fe } else { - // Check if an index is able to deliver the requested features - Q_FOREACH ( QgsAbstractCacheIndex *idx, mCacheIndices ) - { - if ( idx->getCacheIterator( it, featureRequest ) ) - { - requiresWriterIt = false; - break; - } - } + // may still be able to satisfy request using cache + requiresWriterIt = !canUseCacheForRequest( featureRequest, it ); } } else diff --git a/src/core/qgsvectorlayercache.h b/src/core/qgsvectorlayercache.h index c06127e118da..48f4808c729e 100644 --- a/src/core/qgsvectorlayercache.h +++ b/src/core/qgsvectorlayercache.h @@ -338,5 +338,16 @@ class CORE_EXPORT QgsVectorLayerCache : public QObject friend class QgsCachedFeatureIterator; friend class QgsCachedFeatureWriterIterator; friend class QgsCachedFeature; + + /** Returns true if the cache contains all the features required for a specified request. + * @param featureRequest feature request + * @param it will be set to iterator for matching features + * @returns true if cache can satisfy request + * @note this method only checks for available features, not whether the cache + * contains required attributes or geometry. For that, use checkInformationCovered() + */ + bool canUseCacheForRequest( const QgsFeatureRequest& featureRequest, QgsFeatureIterator& it ); + + friend class TestVectorLayerCache; }; #endif // QgsVectorLayerCache_H diff --git a/tests/src/core/testqgsvectorlayercache.cpp b/tests/src/core/testqgsvectorlayercache.cpp index f5d68ed258e9..5687e9914952 100644 --- a/tests/src/core/testqgsvectorlayercache.cpp +++ b/tests/src/core/testqgsvectorlayercache.cpp @@ -54,6 +54,7 @@ class TestVectorLayerCache : public QObject void testSubsetRequest(); void testFullCache(); void testFullCacheThroughRequest(); + void testCanUseCacheForRequest(); void onCommittedFeaturesAdded( const QString&, const QgsFeatureList& ); @@ -267,6 +268,67 @@ void TestVectorLayerCache::testFullCacheThroughRequest() QVERIFY( cache.hasFullCache() ); } +void TestVectorLayerCache::testCanUseCacheForRequest() +{ + //first get some feature ids from layer + QgsFeature f; + QgsFeatureIterator it = mPointsLayer->getFeatures(); + it.nextFeature( f ); + QgsFeatureId id1 = f.id(); + it.nextFeature( f ); + QgsFeatureId id2 = f.id(); + + QgsVectorLayerCache cache( mPointsLayer, 10 ); + // initially nothing in cache, so can't use it to fulfill the request + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id1 ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id2 ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFids( QgsFeatureIds() << id1 << id2 ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterRect( QgsRectangle( 1, 2, 3, 4 ) ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterExpression( "$x<5" ), it ) ); + + // get just the first feature into the cache + it = cache.getFeatures( QgsFeatureRequest().setFilterFid( id1 ) ); + while ( it.nextFeature( f ) ) { } + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id1 ), it ) ); + //verify that the returned iterator was correct + QVERIFY( it.nextFeature( f ) ); + QCOMPARE( f.id(), id1 ); + QVERIFY( !it.nextFeature( f ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id2 ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFids( QgsFeatureIds() << id1 << id2 ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterRect( QgsRectangle( 1, 2, 3, 4 ) ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterExpression( "$x<5" ), it ) ); + + // get feature 2 into cache + it = cache.getFeatures( QgsFeatureRequest().setFilterFid( id2 ) ); + while ( it.nextFeature( f ) ) { } + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id1 ), it ) ); + QVERIFY( it.nextFeature( f ) ); + QCOMPARE( f.id(), id1 ); + QVERIFY( !it.nextFeature( f ) ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id2 ), it ) ); + QVERIFY( it.nextFeature( f ) ); + QCOMPARE( f.id(), id2 ); + QVERIFY( !it.nextFeature( f ) ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFids( QgsFeatureIds() << id1 << id2 ), it ) ); + QVERIFY( it.nextFeature( f ) ); + QgsFeatureIds result; + result << f.id(); + QVERIFY( it.nextFeature( f ) ); + result << f.id(); + QCOMPARE( result, QgsFeatureIds() << id1 << id2 ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterRect( QgsRectangle( 1, 2, 3, 4 ) ), it ) ); + QVERIFY( !cache.canUseCacheForRequest( QgsFeatureRequest().setFilterExpression( "$x<5" ), it ) ); + + // can only use rect/expression requests if cache has everything + cache.setFullCache( true ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id1 ), it ) ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id2 ), it ) ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFids( QgsFeatureIds() << id1 << id2 ), it ) ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterRect( QgsRectangle( 1, 2, 3, 4 ) ), it ) ); + QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterExpression( "$x<5" ), it ) ); +} + void TestVectorLayerCache::onCommittedFeaturesAdded( const QString& layerId, const QgsFeatureList& features ) { Q_UNUSED( layerId ) From 08eaeaab4ab6ae372514f1306ccd086d783df678 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 13:18:56 +1000 Subject: [PATCH 763/897] Increase maximum number of cached features On behalf of Faunalia, sponsored by ENEL --- src/ui/qgsoptionsbase.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/qgsoptionsbase.ui b/src/ui/qgsoptionsbase.ui index 4d0adc2dcb90..e54553310ed9 100644 --- a/src/ui/qgsoptionsbase.ui +++ b/src/ui/qgsoptionsbase.ui @@ -1530,7 +1530,7 @@ 0 - 100000 + 10000000 1000 From b0801f34c967d329d2045c7bdb0cd4622f8c1a13 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 14:32:56 +1000 Subject: [PATCH 764/897] Avoid warning noise during attribute table load On behalf of Faunalia, sponsored by ENEL --- src/gui/attributetable/qgsdualview.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/gui/attributetable/qgsdualview.cpp b/src/gui/attributetable/qgsdualview.cpp index c5e244230a18..0f91c34afd13 100644 --- a/src/gui/attributetable/qgsdualview.cpp +++ b/src/gui/attributetable/qgsdualview.cpp @@ -706,9 +706,7 @@ void QgsDualView::progress( int i, bool& cancel ) mProgressDlg->show(); } - mProgressDlg->setValue( i ); mProgressDlg->setLabelText( tr( "%1 features loaded." ).arg( i ) ); - QCoreApplication::processEvents(); cancel = mProgressDlg && mProgressDlg->wasCanceled(); From 53460232bb8e5a4a7f536e16e8aad6400269ecfd Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 14:33:41 +1000 Subject: [PATCH 765/897] Don't query list of visible features when showing selected features On behalf of Faunalia, sponsored by ENEL --- src/gui/attributetable/qgsattributetablefiltermodel.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/gui/attributetable/qgsattributetablefiltermodel.cpp b/src/gui/attributetable/qgsattributetablefiltermodel.cpp index ba977d482635..1acf28e730ee 100644 --- a/src/gui/attributetable/qgsattributetablefiltermodel.cpp +++ b/src/gui/attributetable/qgsattributetablefiltermodel.cpp @@ -294,11 +294,6 @@ void QgsAttributeTableFilterModel::setFilterMode( FilterMode filterMode ) disconnect( mCanvas, SIGNAL( extentsChanged() ), this, SLOT( extentsChanged() ) ); } - if ( filterMode == ShowSelected ) - { - generateListOfVisibleFeatures(); - } - mFilterMode = filterMode; invalidateFilter(); } @@ -359,7 +354,6 @@ void QgsAttributeTableFilterModel::selectionChanged() { if ( ShowSelected == mFilterMode ) { - generateListOfVisibleFeatures(); invalidateFilter(); } else if ( mSelectedOnTop ) From b5c1d0f24e2187a3a32c1f734df9b2e451d77b65 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 10 Aug 2016 14:59:54 +1000 Subject: [PATCH 766/897] QgsCacheIndexFeatureId can also handle non-FilterFid requests in certain circumstances On behalf of Faunalia, sponsored by ENEL --- python/core/qgscacheindexfeatureid.sip | 34 ---------------------- python/core/qgsvectorlayercache.sip | 9 +++++- src/core/qgscacheindex.h | 4 +-- src/core/qgscacheindexfeatureid.cpp | 32 +++++++++++++++++--- src/core/qgscacheindexfeatureid.h | 34 ---------------------- src/core/qgsvectorlayercache.cpp | 2 +- src/core/qgsvectorlayercache.h | 9 +++++- tests/src/core/testqgsvectorlayercache.cpp | 2 ++ 8 files changed, 49 insertions(+), 77 deletions(-) diff --git a/python/core/qgscacheindexfeatureid.sip b/python/core/qgscacheindexfeatureid.sip index b6c7bd16f598..2fc8aec22569 100644 --- a/python/core/qgscacheindexfeatureid.sip +++ b/python/core/qgscacheindexfeatureid.sip @@ -6,42 +6,8 @@ class QgsCacheIndexFeatureId : QgsAbstractCacheIndex public: QgsCacheIndexFeatureId( QgsVectorLayerCache* ); - /** - * Is called, whenever a feature is removed from the cache. You should update your indexes, so - * they become invalid in case this feature was required to successfuly answer a request. - */ virtual void flushFeature( const QgsFeatureId fid ); - - /** - * Sometimes, the whole cache changes its state and its easier to just withdraw everything. - * In this case, this method is issued. Be sure to clear all cache information in here. - */ virtual void flush(); - - /** - * @brief - * Implement this method to update the the indices, in case you need information contained by the request - * to properly index. (E.g. spatial index) - * Does nothing by default - * - * @param featureRequest The feature request that was answered - * @param fids The feature ids that have been returned - */ virtual void requestCompleted( const QgsFeatureRequest& featureRequest, const QgsFeatureIds& fids ); - - /** - * Is called, when a feature request is issued on a cached layer. - * If this cache index is able to completely answer the feature request, it will return true - * and write the list of feature ids of cached features to cachedFeatures. If it is not able - * it will return false and the cachedFeatures state is undefined. - * - * @param featureIterator A reference to a {@link QgsFeatureIterator}. A valid featureIterator will - * be assigned in case this index is able to answer the request and the return - * value is true. - * @param featureRequest The feature request, for which this index is queried. - * - * @return True, if this index holds the information to answer the request. - * - */ virtual bool getCacheIterator( QgsFeatureIterator& featureIterator, const QgsFeatureRequest& featureRequest ); }; diff --git a/python/core/qgsvectorlayercache.sip b/python/core/qgsvectorlayercache.sip index 3fe37c87f077..6ece7982510a 100644 --- a/python/core/qgsvectorlayercache.sip +++ b/python/core/qgsvectorlayercache.sip @@ -123,8 +123,15 @@ class QgsVectorLayerCache : QObject * Check if a certain feature id is cached. * @param fid The feature id to look for * @return True if this id is in the cache + * @see cachedFeatureIds() */ - bool isFidCached( const QgsFeatureId fid ); + bool isFidCached( const QgsFeatureId fid ) const; + + /** Returns the set of feature IDs for features which are cached. + * @note added in QGIS 3.0 + * @see isFidCached() + */ + QgsFeatureIds cachedFeatureIds() const; /** * Gets the feature at the given feature id. Considers the changed, added, deleted and permanent features diff --git a/src/core/qgscacheindex.h b/src/core/qgscacheindex.h index 80bd359159a6..836b7f5a9946 100644 --- a/src/core/qgscacheindex.h +++ b/src/core/qgscacheindex.h @@ -58,8 +58,8 @@ class CORE_EXPORT QgsAbstractCacheIndex /** * Is called, when a feature request is issued on a cached layer. * If this cache index is able to completely answer the feature request, it will return true - * and write the list of feature ids of cached features to cachedFeatures. If it is not able - * it will return false and the cachedFeatures state is undefined. + * and set the iterator to a valid iterator over the cached features. If it is not able + * it will return false. * * @param featureIterator A reference to a {@link QgsFeatureIterator}. A valid featureIterator will * be assigned in case this index is able to answer the request and the return diff --git a/src/core/qgscacheindexfeatureid.cpp b/src/core/qgscacheindexfeatureid.cpp index 496171ae857e..9c9163449223 100644 --- a/src/core/qgscacheindexfeatureid.cpp +++ b/src/core/qgscacheindexfeatureid.cpp @@ -42,12 +42,36 @@ void QgsCacheIndexFeatureId::requestCompleted( const QgsFeatureRequest& featureR bool QgsCacheIndexFeatureId::getCacheIterator( QgsFeatureIterator &featureIterator, const QgsFeatureRequest &featureRequest ) { - if ( featureRequest.filterType() == QgsFeatureRequest::FilterFid ) + switch ( featureRequest.filterType() ) { - if ( C->isFidCached( featureRequest.filterFid() ) ) + case QgsFeatureRequest::FilterFid: { - featureIterator = QgsFeatureIterator( new QgsCachedFeatureIterator( C, featureRequest ) ); - return true; + if ( C->isFidCached( featureRequest.filterFid() ) ) + { + featureIterator = QgsFeatureIterator( new QgsCachedFeatureIterator( C, featureRequest ) ); + return true; + } + break; + } + case QgsFeatureRequest::FilterFids: + { + if ( C->cachedFeatureIds().contains( featureRequest.filterFids() ) ) + { + featureIterator = QgsFeatureIterator( new QgsCachedFeatureIterator( C, featureRequest ) ); + return true; + } + break; + } + case QgsFeatureRequest::FilterNone: + case QgsFeatureRequest::FilterRect: + case QgsFeatureRequest::FilterExpression: + { + if ( C->hasFullCache() ) + { + featureIterator = QgsFeatureIterator( new QgsCachedFeatureIterator( C, featureRequest ) ); + return true; + } + break; } } diff --git a/src/core/qgscacheindexfeatureid.h b/src/core/qgscacheindexfeatureid.h index 29ab923db321..25a7483cacf2 100644 --- a/src/core/qgscacheindexfeatureid.h +++ b/src/core/qgscacheindexfeatureid.h @@ -28,43 +28,9 @@ class CORE_EXPORT QgsCacheIndexFeatureId : public QgsAbstractCacheIndex public: QgsCacheIndexFeatureId( QgsVectorLayerCache* ); - /** - * Is called, whenever a feature is removed from the cache. You should update your indexes, so - * they become invalid in case this feature was required to successfuly answer a request. - */ virtual void flushFeature( const QgsFeatureId fid ) override; - - /** - * Sometimes, the whole cache changes its state and its easier to just withdraw everything. - * In this case, this method is issued. Be sure to clear all cache information in here. - */ virtual void flush() override; - - /** - * @brief - * Implement this method to update the the indices, in case you need information contained by the request - * to properly index. (E.g. spatial index) - * Does nothing by default - * - * @param featureRequest The feature request that was answered - * @param fids The feature ids that have been returned - */ virtual void requestCompleted( const QgsFeatureRequest& featureRequest, const QgsFeatureIds& fids ) override; - - /** - * Is called, when a feature request is issued on a cached layer. - * If this cache index is able to completely answer the feature request, it will return true - * and write the list of feature ids of cached features to cachedFeatures. If it is not able - * it will return false and the cachedFeatures state is undefined. - * - * @param featureIterator A reference to a {@link QgsFeatureIterator}. A valid featureIterator will - * be assigned in case this index is able to answer the request and the return - * value is true. - * @param featureRequest The feature request, for which this index is queried. - * - * @return True, if this index holds the information to answer the request. - * - */ virtual bool getCacheIterator( QgsFeatureIterator& featureIterator, const QgsFeatureRequest& featureRequest ) override; private: diff --git a/src/core/qgsvectorlayercache.cpp b/src/core/qgsvectorlayercache.cpp index 47e4f59db140..9d175f57cd50 100644 --- a/src/core/qgsvectorlayercache.cpp +++ b/src/core/qgsvectorlayercache.cpp @@ -364,7 +364,7 @@ QgsFeatureIterator QgsVectorLayerCache::getFeatures( const QgsFeatureRequest &fe return it; } -bool QgsVectorLayerCache::isFidCached( const QgsFeatureId fid ) +bool QgsVectorLayerCache::isFidCached( const QgsFeatureId fid ) const { return mCache.contains( fid ); } diff --git a/src/core/qgsvectorlayercache.h b/src/core/qgsvectorlayercache.h index 48f4808c729e..5287da411191 100644 --- a/src/core/qgsvectorlayercache.h +++ b/src/core/qgsvectorlayercache.h @@ -205,8 +205,15 @@ class CORE_EXPORT QgsVectorLayerCache : public QObject * Check if a certain feature id is cached. * @param fid The feature id to look for * @return True if this id is in the cache + * @see cachedFeatureIds() */ - bool isFidCached( const QgsFeatureId fid ); + bool isFidCached( const QgsFeatureId fid ) const; + + /** Returns the set of feature IDs for features which are cached. + * @note added in QGIS 3.0 + * @see isFidCached() + */ + QgsFeatureIds cachedFeatureIds() const { return mCache.keys().toSet(); } /** * Gets the feature at the given feature id. Considers the changed, added, deleted and permanent features diff --git a/tests/src/core/testqgsvectorlayercache.cpp b/tests/src/core/testqgsvectorlayercache.cpp index 5687e9914952..1cdf83eb4649 100644 --- a/tests/src/core/testqgsvectorlayercache.cpp +++ b/tests/src/core/testqgsvectorlayercache.cpp @@ -289,6 +289,7 @@ void TestVectorLayerCache::testCanUseCacheForRequest() // get just the first feature into the cache it = cache.getFeatures( QgsFeatureRequest().setFilterFid( id1 ) ); while ( it.nextFeature( f ) ) { } + QCOMPARE( cache.cachedFeatureIds(), QgsFeatureIds() << id1 ); QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id1 ), it ) ); //verify that the returned iterator was correct QVERIFY( it.nextFeature( f ) ); @@ -302,6 +303,7 @@ void TestVectorLayerCache::testCanUseCacheForRequest() // get feature 2 into cache it = cache.getFeatures( QgsFeatureRequest().setFilterFid( id2 ) ); while ( it.nextFeature( f ) ) { } + QCOMPARE( cache.cachedFeatureIds(), QgsFeatureIds() << id1 << id2 ); QVERIFY( cache.canUseCacheForRequest( QgsFeatureRequest().setFilterFid( id1 ), it ) ); QVERIFY( it.nextFeature( f ) ); QCOMPARE( f.id(), id1 ); From 8f8624a333aa21d682d3df1134b460b619d28d93 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 15 Nov 2016 12:59:12 +1000 Subject: [PATCH 767/897] Improve test debugging --- tests/src/gui/testqgsdualview.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/src/gui/testqgsdualview.cpp b/tests/src/gui/testqgsdualview.cpp index 5c84e09848a0..fa671cadb55c 100644 --- a/tests/src/gui/testqgsdualview.cpp +++ b/tests/src/gui/testqgsdualview.cpp @@ -136,12 +136,12 @@ void TestQgsDualView::testSelectAll() // Only show parts of the canvas, so only one selected feature is visible mCanvas->setExtent( QgsRectangle( -139, 23, -100, 48 ) ); mDualView->mTableView->selectAll(); - QVERIFY( mPointsLayer->selectedFeatureCount() == 10 ); + QCOMPARE( mPointsLayer->selectedFeatureCount(), 10 ); mPointsLayer->selectByIds( QgsFeatureIds() ); mCanvas->setExtent( QgsRectangle( -110, 40, -100, 48 ) ); mDualView->mTableView->selectAll(); - QVERIFY( mPointsLayer->selectedFeatureCount() == 1 ); + QCOMPARE( mPointsLayer->selectedFeatureCount(), 1 ); } void TestQgsDualView::testSort() From 9ddf78e39f72482c5655f8fee14dc9b5f12d100f Mon Sep 17 00:00:00 2001 From: Richard Duivenvoorde Date: Tue, 15 Nov 2016 10:15:21 +0100 Subject: [PATCH 768/897] minimal textual fix --- src/ui/qgisapp.ui | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/qgisapp.ui b/src/ui/qgisapp.ui index 45fc44713f26..86a9c1b33d2d 100644 --- a/src/ui/qgisapp.ui +++ b/src/ui/qgisapp.ui @@ -1963,7 +1963,7 @@ Acts on all editable layers :/images/themes/default/mActionShowPinnedLabels.svg:/images/themes/default/mActionShowPinnedLabels.svg - Highlight Pinned Labels And DIagrams + Highlight Pinned Labels And Diagrams Highlight Pinned Labels And Diagrams From a373f95707fb2bf52694fc7a4ae34bda81099f26 Mon Sep 17 00:00:00 2001 From: Denis Rouzaud Date: Tue, 1 Nov 2016 16:03:05 +0100 Subject: [PATCH 769/897] [FEATURE] add functionnality to copy/move feature to move feature map tool --- images/images.qrc | 3 + images/themes/default/mActionMoveFeature.png | Bin 1290 -> 0 bytes .../themes/default/mActionMoveFeatureCopy.svg | 1159 ++++++++++++++++ .../default/mActionMoveFeatureCopyLine.svg | 1205 +++++++++++++++++ .../default/mActionMoveFeatureCopyPoint.svg | 729 ++++++++++ python/core/core.sip | 2 + .../qgstrackedvectorlayertools.sip | 1 + python/{gui => core}/qgsvectorlayertools.sip | 18 +- python/gui/gui.sip | 2 - python/testing/mocked.py | 1 - src/app/qgisapp.cpp | 42 +- src/app/qgisapp.h | 4 + src/app/qgsguivectorlayertools.cpp | 13 +- src/app/qgsguivectorlayertools.h | 3 +- src/app/qgsmaptoolmovefeature.cpp | 62 +- src/app/qgsmaptoolmovefeature.h | 11 +- src/core/CMakeLists.txt | 4 + .../qgstrackedvectorlayertools.cpp | 7 +- .../qgstrackedvectorlayertools.h | 4 +- src/core/qgsvectorlayertools.cpp | 107 ++ src/{gui => core}/qgsvectorlayertools.h | 25 +- src/gui/CMakeLists.txt | 3 - src/ui/qgisapp.ui | 18 +- tests/src/python/CMakeLists.txt | 1 + .../src/python/test_qgsrelationeditwidget.py | 6 +- tests/src/python/test_qgsvectorlayertools.py | 76 ++ 26 files changed, 3466 insertions(+), 40 deletions(-) delete mode 100644 images/themes/default/mActionMoveFeature.png create mode 100644 images/themes/default/mActionMoveFeatureCopy.svg create mode 100644 images/themes/default/mActionMoveFeatureCopyLine.svg create mode 100644 images/themes/default/mActionMoveFeatureCopyPoint.svg rename python/{gui => core}/qgstrackedvectorlayertools.sip (92%) rename python/{gui => core}/qgsvectorlayertools.sip (71%) rename src/{gui => core}/qgstrackedvectorlayertools.cpp (90%) rename src/{gui => core}/qgstrackedvectorlayertools.h (89%) create mode 100644 src/core/qgsvectorlayertools.cpp rename src/{gui => core}/qgsvectorlayertools.h (80%) create mode 100644 tests/src/python/test_qgsvectorlayertools.py diff --git a/images/images.qrc b/images/images.qrc index c1f9ec460971..752e9d61041d 100644 --- a/images/images.qrc +++ b/images/images.qrc @@ -583,6 +583,9 @@ themes/default/mIconSnappingSegment.svg themes/default/mIconTopologicalEditing.svg themes/default/mIconSnappingIntersection.svg + themes/default/mActionMoveFeatureCopy.svg + themes/default/mActionMoveFeatureCopyLine.svg + themes/default/mActionMoveFeatureCopyPoint.svg qgis_tips/symbol_levels.png diff --git a/images/themes/default/mActionMoveFeature.png b/images/themes/default/mActionMoveFeature.png deleted file mode 100644 index 9fdea5d223475aa864e0a01439502e18f2dc20db..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1290 zcmV+l1@-!gP)EFeK{X>?&AM{;3vWpeCJAm0E002p*dSad^jWnpw_ zZ*Cw|X>DZyGB7bQEig1KGBDgUI&lC108(^CSad^gaCvfRXJ~W)Lqi}zbaZlQVs&(B zZ*DD9Xkl_?L2PMjWguvDbZ|N^FJp3LVRUJBWn*t`ZEtRKE^l&YFKlUJWo~n2b1!0f zEpuTnGcGVMUV~b^000BENklK)pm!k3V z&=<8}V+d7`r9Cc+ux z>C*tt1Ly?M2Vf9DG9F7zG#MOvHhR4GuIo8;5ZWplv^dd13J{S3YGZ1Q zF<=?v<*(P#;^E{h~6SiN8_$YWE28^*LZYf*V6;G3G2{tkmwmX87F~*wDgI4kI z(9WQ3iG~6>uNik(wN56d7OHI-EG`!eV4$Sh^oHR1wMA8e + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mActionMoveFeatureCopyLine.svg b/images/themes/default/mActionMoveFeatureCopyLine.svg new file mode 100644 index 000000000000..478c080854bc --- /dev/null +++ b/images/themes/default/mActionMoveFeatureCopyLine.svg @@ -0,0 +1,1205 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mActionMoveFeatureCopyPoint.svg b/images/themes/default/mActionMoveFeatureCopyPoint.svg new file mode 100644 index 000000000000..619ad333390a --- /dev/null +++ b/images/themes/default/mActionMoveFeatureCopyPoint.svg @@ -0,0 +1,729 @@ + + + + + ring fill + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + ring fill + 2014-02-04 + + + Robert Szczepanek + + + + + + + + + + ring fill + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + + + diff --git a/python/core/core.sip b/python/core/core.sip index 6adeeb3dff1d..cc14357c1b42 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -139,6 +139,7 @@ %Include qgstextrenderer.sip %Include qgstolerance.sip %Include qgstracer.sip +%Include qgstrackedvectorlayertools.sip %Include qgsunittypes.sip %Include qgsvectordataprovider.sip %Include qgsvectorfilewriter.sip @@ -148,6 +149,7 @@ %Include qgsvectorlayereditpassthrough.sip %Include qgsvectorlayerimport.sip %Include qgsvectorlayerjoinbuffer.sip +%Include qgsvectorlayertools.sip %Include qgsvectorlayerundocommand.sip %Include qgsvectorlayerutils.sip %Include qgsvectorsimplifymethod.sip diff --git a/python/gui/qgstrackedvectorlayertools.sip b/python/core/qgstrackedvectorlayertools.sip similarity index 92% rename from python/gui/qgstrackedvectorlayertools.sip rename to python/core/qgstrackedvectorlayertools.sip index 6efd5f519b8d..7b7ba477d694 100644 --- a/python/gui/qgstrackedvectorlayertools.sip +++ b/python/core/qgstrackedvectorlayertools.sip @@ -25,6 +25,7 @@ class QgsTrackedVectorLayerTools : QgsVectorLayerTools bool startEditing( QgsVectorLayer* layer ) const ; bool stopEditing( QgsVectorLayer* layer, bool allowCancel ) const ; bool saveEdits( QgsVectorLayer* layer ) const ; + bool copyMoveFeatures( QgsVectorLayer* layer, QgsFeatureRequest &request, double dx = 0, double dy = 0, QString *errorMsg = nullptr ) const; /** * Set the vector layer tools that will be used to interact with the data diff --git a/python/gui/qgsvectorlayertools.sip b/python/core/qgsvectorlayertools.sip similarity index 71% rename from python/gui/qgsvectorlayertools.sip rename to python/core/qgsvectorlayertools.sip index bd65f42011a8..fcc2c8b90a1f 100644 --- a/python/gui/qgsvectorlayertools.sip +++ b/python/core/qgsvectorlayertools.sip @@ -1,9 +1,12 @@ -class QgsVectorLayerTools +class QgsVectorLayerTools : QObject { %TypeHeaderCode #include %End public: + QgsVectorLayerTools(); + + virtual ~QgsVectorLayerTools(); /** * This method should/will be called, whenever a new feature will be added to the layer @@ -45,4 +48,17 @@ class QgsVectorLayerTools */ virtual bool saveEdits( QgsVectorLayer* layer ) const = 0; + /** + * Copy and move features with defined translation. + * + * @param layer The layer + * @param request The request for the features to be moved. It will be assigned to a new feature request with the newly copied features. + * @param dx The translation on x + * @param dy The translation on y + * @param errorMsg If given, it will contain the error message + * @return True if all features could be copied. + * + * TODO QGIS 3: remove const qualifier + */ + virtual bool copyMoveFeatures( QgsVectorLayer* layer, QgsFeatureRequest &request /In,Out/, double dx = 0, double dy = 0, QString* errorMsg /Out/ = nullptr ) const; }; diff --git a/python/gui/gui.sip b/python/gui/gui.sip index 88c27f32972a..3587c165310f 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -165,12 +165,10 @@ %Include qgstextannotationitem.sip %Include qgstextformatwidget.sip %Include qgstextpreview.sip -%Include qgstrackedvectorlayertools.sip %Include qgstreewidgetitem.sip %Include qgsunitselectionwidget.sip %Include qgsuserinputdockwidget.sip %Include qgsvariableeditorwidget.sip -%Include qgsvectorlayertools.sip %Include qgsvertexmarker.sip %Include attributetable/qgsattributetabledelegate.sip diff --git a/python/testing/mocked.py b/python/testing/mocked.py index 1445c7f9dba8..312506dc13e8 100644 --- a/python/testing/mocked.py +++ b/python/testing/mocked.py @@ -61,7 +61,6 @@ def get_iface(): canvas = QgsMapCanvas(my_iface.mainWindow()) canvas.resize(QSize(400, 400)) - my_iface.mapCanvas.return_value = canvas return my_iface diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 56931e374a3c..6644b8e7c484 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -1248,6 +1248,7 @@ QgisApp::~QgisApp() delete mMapTools.mMeasureArea; delete mMapTools.mMeasureDist; delete mMapTools.mMoveFeature; + delete mMapTools.mMoveFeatureCopy; delete mMapTools.mMoveLabel; delete mMapTools.mNodeTool; delete mMapTools.mOffsetCurve; @@ -1584,6 +1585,7 @@ void QgisApp::createActions() connect( mActionCircularStringCurvePoint, SIGNAL( triggered() ), this, SLOT( circularStringCurvePoint() ) ); connect( mActionCircularStringRadius, SIGNAL( triggered() ), this, SLOT( circularStringRadius() ) ); connect( mActionMoveFeature, SIGNAL( triggered() ), this, SLOT( moveFeature() ) ); + connect( mActionMoveFeatureCopy, &QAction::triggered, this, &QgisApp::moveFeatureCopy ); connect( mActionRotateFeature, SIGNAL( triggered() ), this, SLOT( rotateFeature() ) ); connect( mActionReshapeFeatures, SIGNAL( triggered() ), this, SLOT( reshapeFeatures() ) ); @@ -1876,6 +1878,7 @@ void QgisApp::createActionGroups() mMapToolGroup->addAction( mActionCircularStringCurvePoint ); mMapToolGroup->addAction( mActionCircularStringRadius ); mMapToolGroup->addAction( mActionMoveFeature ); + mMapToolGroup->addAction( mActionMoveFeatureCopy ); mMapToolGroup->addAction( mActionRotateFeature ); mMapToolGroup->addAction( mActionOffsetCurve ); mMapToolGroup->addAction( mActionReshapeFeatures ); @@ -2328,6 +2331,25 @@ void QgisApp::createToolBars() layout->itemAt( i )->setAlignment( Qt::AlignLeft ); } + // move feature tool button + QToolButton* moveFeatureButton = new QToolButton( mDigitizeToolBar ); + moveFeatureButton->setPopupMode( QToolButton::MenuButtonPopup ); + moveFeatureButton->addAction( mActionMoveFeature ); + moveFeatureButton->addAction( mActionMoveFeatureCopy ); + QAction* defAction = mActionMoveFeature; + switch ( settings.value( QStringLiteral( "/UI/defaultMoveTool" ), 0 ).toInt() ) + { + case 0: + defAction = mActionMoveFeature; + break; + case 1: + defAction = mActionMoveFeatureCopy; + break; + }; + moveFeatureButton->setDefaultAction( defAction ); + connect( moveFeatureButton, SIGNAL( triggered( QAction * ) ), this, SLOT( toolButtonActionTriggered( QAction * ) ) ); + mDigitizeToolBar->insertWidget( mActionNodeTool, moveFeatureButton ); + //circular string digitize tool button QToolButton* tbAddCircularString = new QToolButton( mDigitizeToolBar ); tbAddCircularString->setPopupMode( QToolButton::MenuButtonPopup ); @@ -2617,6 +2639,7 @@ void QgisApp::setTheme( const QString& theThemeName ) mActionPasteFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionEditPaste.svg" ) ) ); mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePoint.svg" ) ) ); mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeaturePoint.svg" ) ) ); + mActionMoveFeatureCopy->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeatureCopyPoint.svg" ) ) ); mActionRotateFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionRotateFeature.svg" ) ) ); mActionReshapeFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionReshape.svg" ) ) ); mActionSplitFeatures->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionSplitFeatures.svg" ) ) ); @@ -2855,8 +2878,10 @@ void QgisApp::createCanvasTools() mMapTools.mCircularStringCurvePoint->setAction( mActionCircularStringCurvePoint ); mMapTools.mCircularStringRadius = new QgsMapToolCircularStringRadius( dynamic_cast( mMapTools.mAddFeature ), mMapCanvas ); mMapTools.mCircularStringRadius->setAction( mActionCircularStringRadius ); - mMapTools.mMoveFeature = new QgsMapToolMoveFeature( mMapCanvas ); + mMapTools.mMoveFeature = new QgsMapToolMoveFeature( mMapCanvas, QgsMapToolMoveFeature::Move ); mMapTools.mMoveFeature->setAction( mActionMoveFeature ); + mMapTools.mMoveFeatureCopy = new QgsMapToolMoveFeature( mMapCanvas, QgsMapToolMoveFeature::CopyMove ); + mMapTools.mMoveFeatureCopy->setAction( mActionMoveFeatureCopy ); mMapTools.mRotateFeature = new QgsMapToolRotateFeature( mMapCanvas ); mMapTools.mRotateFeature->setAction( mActionRotateFeature ); mMapTools.mOffsetCurve = new QgsMapToolOffsetCurve( mMapCanvas ); @@ -6485,6 +6510,11 @@ void QgisApp::moveFeature() mMapCanvas->setMapTool( mMapTools.mMoveFeature ); } +void QgisApp::moveFeatureCopy() +{ + mMapCanvas->setMapTool( mMapTools.mMoveFeatureCopy ); +} + void QgisApp::offsetCurve() { mMapCanvas->setMapTool( mMapTools.mOffsetCurve ); @@ -10526,6 +10556,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) mActionCircularStringCurvePoint->setEnabled( false ); mActionCircularStringRadius->setEnabled( false ); mActionMoveFeature->setEnabled( false ); + mActionMoveFeatureCopy->setEnabled( false ); mActionRotateFeature->setEnabled( false ); mActionOffsetCurve->setEnabled( false ); mActionNodeTool->setEnabled( false ); @@ -10680,6 +10711,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) mActionAddPart->setEnabled( isEditable && canChangeGeometry ); mActionDeletePart->setEnabled( isEditable && canChangeGeometry ); mActionMoveFeature->setEnabled( isEditable && canChangeGeometry ); + mActionMoveFeatureCopy->setEnabled( isEditable && canChangeGeometry ); mActionRotateFeature->setEnabled( isEditable && canChangeGeometry ); mActionNodeTool->setEnabled( isEditable && canChangeGeometry ); @@ -10690,6 +10722,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) { mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePoint.svg" ) ) ); mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeaturePoint.svg" ) ) ); + mActionMoveFeatureCopy->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeatureCopyPoint.svg" ) ) ); mActionAddRing->setEnabled( false ); mActionFillRing->setEnabled( false ); @@ -10718,6 +10751,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) { mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCaptureLine.svg" ) ) ); mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeatureLine.svg" ) ) ); + mActionMoveFeatureCopy->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeatureCopyLine.svg" ) ) ); mActionReshapeFeatures->setEnabled( isEditable && canChangeGeometry ); mActionSplitFeatures->setEnabled( isEditable && canAddFeatures ); @@ -10733,6 +10767,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) { mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionCapturePolygon.svg" ) ) ); mActionMoveFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeature.svg" ) ) ); + mActionMoveFeatureCopy->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionMoveFeatureCopy.svg" ) ) ); mActionAddRing->setEnabled( isEditable && canChangeGeometry ); mActionFillRing->setEnabled( isEditable && canChangeGeometry ); @@ -10819,6 +10854,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) mActionAddPart->setEnabled( false ); mActionNodeTool->setEnabled( false ); mActionMoveFeature->setEnabled( false ); + mActionMoveFeatureCopy->setEnabled( false ); mActionRotateFeature->setEnabled( false ); mActionOffsetCurve->setEnabled( false ); mActionCopyFeatures->setEnabled( false ); @@ -11846,6 +11882,10 @@ void QgisApp::toolButtonActionTriggered( QAction *action ) settings.setValue( QStringLiteral( "/UI/defaultMapService" ), 0 ); else if ( action == mActionAddAmsLayer ) settings.setValue( QStringLiteral( "/UI/defaultMapService" ), 1 ); + else if ( action == mActionMoveFeature ) + settings.setValue( QStringLiteral( "/UI/defaultMoveTool" ), 0 ); + else if ( action == mActionMoveFeatureCopy ) + settings.setValue( QStringLiteral( "/UI/defaultMoveTool" ), 1 ); bt->setDefaultAction( action ); } diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index d8472274d5b1..cbf2a7a393d4 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -331,6 +331,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QAction *actionDeleteSelected() { return mActionDeleteSelected; } QAction *actionAddFeature() { return mActionAddFeature; } QAction *actionMoveFeature() { return mActionMoveFeature; } + QAction *actionMoveFeatureCopy() { return mActionMoveFeatureCopy; } QAction *actionRotateFeature() { return mActionRotateFeature;} QAction *actionSplitFeatures() { return mActionSplitFeatures; } QAction *actionSplitParts() { return mActionSplitParts; } @@ -1068,6 +1069,8 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void circularStringRadius(); //! activates the move feature tool void moveFeature(); + //! activates the copy and move feature tool + void moveFeatureCopy(); //! activates the offset curve tool void offsetCurve(); //! activates the reshape features tool @@ -1634,6 +1637,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow QgsMapTool *mCircularStringCurvePoint; QgsMapTool *mCircularStringRadius; QgsMapTool *mMoveFeature; + QgsMapTool *mMoveFeatureCopy; QgsMapTool *mOffsetCurve; QgsMapTool *mReshapeFeatures; QgsMapTool *mSplitFeatures; diff --git a/src/app/qgsguivectorlayertools.cpp b/src/app/qgsguivectorlayertools.cpp index bcca09eacd84..1bb4d33c5acb 100644 --- a/src/app/qgsguivectorlayertools.cpp +++ b/src/app/qgsguivectorlayertools.cpp @@ -17,19 +17,21 @@ #include #include "qgsguivectorlayertools.h" -#include "qgsvectorlayer.h" -#include "qgsvectordataprovider.h" -#include "qgsmessagebar.h" + #include "qgisapp.h" #include "qgsapplication.h" -#include "qgsmessageviewer.h" #include "qgsfeatureaction.h" +#include "qgslogger.h" #include "qgsmapcanvas.h" +#include "qgsmessagebar.h" #include "qgsmessagebaritem.h" +#include "qgsmessageviewer.h" +#include "qgsvectordataprovider.h" +#include "qgsvectorlayer.h" QgsGuiVectorLayerTools::QgsGuiVectorLayerTools() - : QObject( nullptr ) + : QgsVectorLayerTools() {} bool QgsGuiVectorLayerTools::addFeature( QgsVectorLayer* layer, const QgsAttributeMap& defaultValues, const QgsGeometry& defaultGeometry, QgsFeature* feat ) const @@ -95,7 +97,6 @@ bool QgsGuiVectorLayerTools::saveEdits( QgsVectorLayer* layer ) const return res; } - bool QgsGuiVectorLayerTools::stopEditing( QgsVectorLayer* layer, bool allowCancel ) const { bool res = true; diff --git a/src/app/qgsguivectorlayertools.h b/src/app/qgsguivectorlayertools.h index da90b64b82db..ecc57ce7664c 100644 --- a/src/app/qgsguivectorlayertools.h +++ b/src/app/qgsguivectorlayertools.h @@ -23,7 +23,7 @@ * or a feature is added. */ -class QgsGuiVectorLayerTools : public QObject, public QgsVectorLayerTools +class QgsGuiVectorLayerTools : public QgsVectorLayerTools { Q_OBJECT @@ -73,6 +73,7 @@ class QgsGuiVectorLayerTools : public QObject, public QgsVectorLayerTools private: void commitError( QgsVectorLayer* vlayer ) const; + }; #endif // QGSGUIVECTORLAYERTOOLS_H diff --git a/src/app/qgsmaptoolmovefeature.cpp b/src/app/qgsmaptoolmovefeature.cpp index e4d43d0e60ec..77dfa8a73fc1 100644 --- a/src/app/qgsmaptoolmovefeature.cpp +++ b/src/app/qgsmaptoolmovefeature.cpp @@ -13,27 +13,39 @@ * * ***************************************************************************/ -#include "qgsmaptoolmovefeature.h" +#include "qgisapp.h" +#include "qgsadvanceddigitizingdockwidget.h" #include "qgsfeatureiterator.h" #include "qgsgeometry.h" #include "qgslogger.h" #include "qgsmapcanvas.h" +#include "qgsmaptoolmovefeature.h" #include "qgsrubberband.h" -#include "qgsvectorlayer.h" #include "qgstolerance.h" -#include "qgisapp.h" -#include "qgsadvanceddigitizingdockwidget.h" +#include "qgsvectorlayer.h" +#include "qgsvectorlayertools.h" + #include #include #include -QgsMapToolMoveFeature::QgsMapToolMoveFeature( QgsMapCanvas* canvas ) + +QgsMapToolMoveFeature::QgsMapToolMoveFeature( QgsMapCanvas* canvas , MoveMode mode ) : QgsMapToolAdvancedDigitizing( canvas, QgisApp::instance()->cadDockWidget() ) , mRubberBand( nullptr ) + , mMode( mode ) { mToolName = tr( "Move feature" ); - mCaptureMode = QgsMapToolAdvancedDigitizing::CaptureSegment; + switch ( mode ) + { + case Move: + mCaptureMode = QgsMapToolAdvancedDigitizing::CaptureSegment; + break; + case CopyMove: + mCaptureMode = QgsMapToolAdvancedDigitizing::CaptureLine; // we copy/move several times + break; + } } QgsMapToolMoveFeature::~QgsMapToolMoveFeature() @@ -138,12 +150,12 @@ void QgsMapToolMoveFeature::cadCanvasReleaseEvent( QgsMapMouseEvent* e ) } else { - delete mRubberBand; - mRubberBand = nullptr; - + // copy and move mode if ( e->button() != Qt::LeftButton ) { cadDockWidget()->clear(); + delete mRubberBand; + mRubberBand = nullptr; return; } @@ -152,13 +164,35 @@ void QgsMapToolMoveFeature::cadCanvasReleaseEvent( QgsMapMouseEvent* e ) double dx = stopPointLayerCoords.x() - startPointLayerCoords.x(); double dy = stopPointLayerCoords.y() - startPointLayerCoords.y(); - vlayer->beginEditCommand( tr( "Feature moved" ) ); - Q_FOREACH ( QgsFeatureId id, mMovedFeatures ) + + + vlayer->beginEditCommand( mMode == Move ? tr( "Feature moved" ) : tr( "Feature copied and moved" ) ); + + + switch ( mMode ) { - vlayer->translateFeature( id, dx, dy ); + case Move: + Q_FOREACH ( QgsFeatureId id, mMovedFeatures ) + { + vlayer->translateFeature( id, dx, dy ); + } + delete mRubberBand; + mRubberBand = nullptr; + break; + + case CopyMove: + QgsFeatureRequest request; + request.setFilterFids( mMovedFeatures ); + QString* errorMsg = new QString(); + if ( !QgisApp::instance()->vectorLayerTools()->copyMoveFeatures( vlayer, request, dx, dy, errorMsg ) ) + { + emit messageEmitted( *errorMsg, QgsMessageBar::CRITICAL ); + delete mRubberBand; + mRubberBand = nullptr; + } + break; } - delete mRubberBand; - mRubberBand = nullptr; + vlayer->endEditCommand(); vlayer->triggerRepaint(); } diff --git a/src/app/qgsmaptoolmovefeature.h b/src/app/qgsmaptoolmovefeature.h index fd888423155e..eda9c22712ef 100644 --- a/src/app/qgsmaptoolmovefeature.h +++ b/src/app/qgsmaptoolmovefeature.h @@ -23,7 +23,14 @@ class APP_EXPORT QgsMapToolMoveFeature: public QgsMapToolAdvancedDigitizing { Q_OBJECT public: - QgsMapToolMoveFeature( QgsMapCanvas* canvas ); + //! Mode for moving features + enum MoveMode + { + Move, //!< Move feature + CopyMove //!< Copy and move feature + }; + + QgsMapToolMoveFeature( QgsMapCanvas* canvas, MoveMode mode = Move ); virtual ~QgsMapToolMoveFeature(); virtual void cadCanvasMoveEvent( QgsMapMouseEvent* e ) override; @@ -45,6 +52,8 @@ class APP_EXPORT QgsMapToolMoveFeature: public QgsMapToolAdvancedDigitizing QPoint mPressPos; + MoveMode mMode; + }; #endif diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 803bbc6dd2a4..ca808a861bcf 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -213,6 +213,7 @@ SET(QGIS_CORE_SRCS qgstextrenderer.cpp qgstolerance.cpp qgstracer.cpp + qgstrackedvectorlayertools.cpp qgstransaction.cpp qgstransactiongroup.cpp qgsunittypes.cpp @@ -230,6 +231,7 @@ SET(QGIS_CORE_SRCS qgsvectorlayerlabeling.cpp qgsvectorlayerlabelprovider.cpp qgsvectorlayerrenderer.cpp + qgsvectorlayertools.cpp qgsvectorlayerundocommand.cpp qgsvectorlayerutils.cpp qgsvectorsimplifymethod.cpp @@ -491,6 +493,7 @@ SET(QGIS_CORE_MOC_HDRS qgsrunprocess.h qgssnappingutils.h qgstracer.h + qgstrackedvectorlayertools.h qgstransaction.h qgstransactiongroup.h qgsunittypes.h @@ -500,6 +503,7 @@ SET(QGIS_CORE_MOC_HDRS qgsvectorlayereditpassthrough.h qgsvectorlayer.h qgsvectorlayerjoinbuffer.h + qgsvectorlayertools.h qgsmapthemecollection.h qgswebpage.h qgswebview.h diff --git a/src/gui/qgstrackedvectorlayertools.cpp b/src/core/qgstrackedvectorlayertools.cpp similarity index 90% rename from src/gui/qgstrackedvectorlayertools.cpp rename to src/core/qgstrackedvectorlayertools.cpp index a09687d1e2d0..b29bad54c2f5 100644 --- a/src/gui/qgstrackedvectorlayertools.cpp +++ b/src/core/qgstrackedvectorlayertools.cpp @@ -17,7 +17,7 @@ #include "qgsvectorlayer.h" QgsTrackedVectorLayerTools::QgsTrackedVectorLayerTools() - : mBackend( nullptr ) + : mBackend() { } @@ -57,6 +57,11 @@ bool QgsTrackedVectorLayerTools::saveEdits( QgsVectorLayer* layer ) const return mBackend->saveEdits( layer ); } +bool QgsTrackedVectorLayerTools::copyMoveFeatures( QgsVectorLayer* layer, QgsFeatureRequest& request, double dx, double dy, QString* errorMsg ) const +{ + return mBackend->copyMoveFeatures( layer, request, dx, dy, errorMsg ); +} + void QgsTrackedVectorLayerTools::setVectorLayerTools( const QgsVectorLayerTools* tools ) { mBackend = tools; diff --git a/src/gui/qgstrackedvectorlayertools.h b/src/core/qgstrackedvectorlayertools.h similarity index 89% rename from src/gui/qgstrackedvectorlayertools.h rename to src/core/qgstrackedvectorlayertools.h index d7894e796783..32ef3a782671 100644 --- a/src/gui/qgstrackedvectorlayertools.h +++ b/src/core/qgstrackedvectorlayertools.h @@ -21,8 +21,9 @@ /** \ingroup gui * \class QgsTrackedVectorLayerTools */ -class GUI_EXPORT QgsTrackedVectorLayerTools : public QgsVectorLayerTools +class CORE_EXPORT QgsTrackedVectorLayerTools : public QgsVectorLayerTools { + Q_OBJECT public: QgsTrackedVectorLayerTools(); @@ -30,6 +31,7 @@ class GUI_EXPORT QgsTrackedVectorLayerTools : public QgsVectorLayerTools bool startEditing( QgsVectorLayer* layer ) const override; bool stopEditing( QgsVectorLayer* layer, bool allowCancel ) const override; bool saveEdits( QgsVectorLayer* layer ) const override; + bool copyMoveFeatures( QgsVectorLayer* layer, QgsFeatureRequest &request, double dx = 0, double dy = 0, QString *errorMsg = nullptr ) const override; /** * Set the vector layer tools that will be used to interact with the data diff --git a/src/core/qgsvectorlayertools.cpp b/src/core/qgsvectorlayertools.cpp new file mode 100644 index 000000000000..3ca7efb5e5f4 --- /dev/null +++ b/src/core/qgsvectorlayertools.cpp @@ -0,0 +1,107 @@ +/*************************************************************************** + qgsvectorlayertools.cpp + --------------------- + begin : 09.11.2016 + copyright : (C) 2016 by Denis Rouzaud + email : denis.rouzaud@gmail.com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + + +#include "qgsvectorlayer.h" +#include "qgsvectorlayertools.h" +#include "qgsfeaturerequest.h" +#include "qgslogger.h" + + +QgsVectorLayerTools::QgsVectorLayerTools() + : QObject( nullptr ) +{} + + +QgsVectorLayerTools::~QgsVectorLayerTools() +{} + + +bool QgsVectorLayerTools::copyMoveFeatures( QgsVectorLayer* layer, QgsFeatureRequest& request, double dx, double dy, QString* errorMsg ) const +{ + bool res = false; + if ( !layer || !layer->isEditable() ) + { + return false; + } + + QgsFeatureIterator fi = layer->getFeatures( request ); + QgsFeature f; + QgsAttributeList pkAttrList = layer->pkAttributeList(); + + int browsedFeatureCount = 0; + int couldNotWriteCount = 0; + int noGeometryCount = 0; + + QgsFeatureIds fidList; + + while ( fi.nextFeature( f ) ) + { + browsedFeatureCount++; + // remove pkey values + Q_FOREACH ( auto idx, pkAttrList ) + { + f.setAttribute( idx, QVariant() ); + } + // translate + if ( f.hasGeometry() ) + { + QgsGeometry geom = f.geometry(); + geom.translate( dx, dy ); + f.setGeometry( geom ); +#ifdef QGISDEBUG + const QgsFeatureId fid = f.id(); +#endif + // paste feature + if ( !layer->addFeature( f, false ) ) + { + couldNotWriteCount++; + QgsDebugMsg( QString( "Could not add new feature. Original copied feature id: %1" ).arg( fid ) ); + } + else + { + fidList.insert( f.id() ); + } + } + else + { + noGeometryCount++; + } + } + + request = QgsFeatureRequest(); + request.setFilterFids( fidList ); + + if ( !couldNotWriteCount && !noGeometryCount ) + { + res = true; + } + else if ( errorMsg ) + { + errorMsg = new QString( QString( tr( "Only %1 out of %2 features were copied." ) ) + .arg( browsedFeatureCount - couldNotWriteCount - noGeometryCount, browsedFeatureCount ) ); + if ( noGeometryCount ) + { + errorMsg->append( " " ); + errorMsg->append( tr( "Some features have no geometry." ) ); + } + if ( couldNotWriteCount ) + { + errorMsg->append( " " ); + errorMsg->append( tr( "Some could not be created on the layer." ) ); + } + } + return res; +} diff --git a/src/gui/qgsvectorlayertools.h b/src/core/qgsvectorlayertools.h similarity index 80% rename from src/gui/qgsvectorlayertools.h rename to src/core/qgsvectorlayertools.h index 468f1d8ec427..6a9dab28eec7 100644 --- a/src/gui/qgsvectorlayertools.h +++ b/src/core/qgsvectorlayertools.h @@ -16,9 +16,12 @@ #ifndef QGSVECTORLAYERTOOLS_H #define QGSVECTORLAYERTOOLS_H +#include + #include "qgsfeature.h" #include "qgsgeometry.h" +class QgsFeatureRequest; class QgsVectorLayer; /** \ingroup gui @@ -30,12 +33,14 @@ class QgsVectorLayer; * in your application. * */ -class GUI_EXPORT QgsVectorLayerTools +class CORE_EXPORT QgsVectorLayerTools : public QObject { + Q_OBJECT + public: - QgsVectorLayerTools() {} + QgsVectorLayerTools(); - virtual ~QgsVectorLayerTools() {} + virtual ~QgsVectorLayerTools(); /** * This method should/will be called, whenever a new feature will be added to the layer @@ -85,6 +90,20 @@ class GUI_EXPORT QgsVectorLayerTools */ virtual bool saveEdits( QgsVectorLayer* layer ) const = 0; + /** + * Copy and move features with defined translation. + * + * @param layer The layer + * @param request The request for the features to be moved. It will be assigned to a new feature request with the newly copied features. + * @param dx The translation on x + * @param dy The translation on y + * @param errorMsg If given, it will contain the error message + * @return True if all features could be copied. + * + * TODO QGIS 3: remove const qualifier + */ + virtual bool copyMoveFeatures( QgsVectorLayer* layer, QgsFeatureRequest &request, double dx = 0, double dy = 0, QString *errorMsg = nullptr ) const; + }; #endif // QGSVECTORLAYERTOOLS_H diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index 3dceb74b66e5..fe02b7cade1a 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -311,7 +311,6 @@ SET(QGIS_GUI_SRCS qgstextannotationitem.cpp qgstextformatwidget.cpp qgstextpreview.cpp - qgstrackedvectorlayertools.cpp qgstreewidgetitem.cpp qgsunitselectionwidget.cpp qgsuserinputdockwidget.cpp @@ -662,9 +661,7 @@ SET(QGIS_GUI_HDRS qgssvgannotationitem.h qgstablewidgetitem.h qgstextannotationitem.h - qgstrackedvectorlayertools.h qgsuserinputdockwidget.h - qgsvectorlayertools.h qgsvertexmarker.h qgsfiledownloader.h diff --git a/src/ui/qgisapp.ui b/src/ui/qgisapp.ui index 86a9c1b33d2d..f69671d8bf47 100644 --- a/src/ui/qgisapp.ui +++ b/src/ui/qgisapp.ui @@ -17,7 +17,7 @@ 0 0 1018 - 28 + 22 @@ -369,7 +369,6 @@ - @@ -2564,6 +2563,21 @@ Acts on currently active editable layer F3 + + + true + + + + :/images/themes/default/mActionMoveFeatureCopy.svg:/images/themes/default/mActionMoveFeatureCopy.svg + + + Copy and Move Feature(s) + + + Copy and Move Feature(s) + + diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 6f0135584271..3ee40185163e 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -143,6 +143,7 @@ ENDIF (WITH_DESKTOP) IF (ENABLE_PGTEST) ADD_PYTHON_TEST(PyQgsPostgresProvider test_provider_postgres.py) ADD_PYTHON_TEST(PyQgsRelationEditWidget test_qgsrelationeditwidget.py) + ADD_PYTHON_TEST(PyQgsVectorLayerTools test_qgsvectorlayertools.py) ENDIF (ENABLE_PGTEST) IF (ENABLE_MSSQLTEST) diff --git a/tests/src/python/test_qgsrelationeditwidget.py b/tests/src/python/test_qgsrelationeditwidget.py index be4877519dbc..d184500b4f8a 100644 --- a/tests/src/python/test_qgsrelationeditwidget.py +++ b/tests/src/python/test_qgsrelationeditwidget.py @@ -23,14 +23,14 @@ QgsRelation, QgsMapLayerRegistry, QgsTransaction, - QgsFeatureRequest + QgsFeatureRequest, + QgsVectorLayerTools ) from qgis.gui import ( QgsEditorWidgetRegistry, QgsRelationWidgetWrapper, - QgsAttributeEditorContext, - QgsVectorLayerTools + QgsAttributeEditorContext ) from qgis.PyQt.QtCore import QTimer diff --git a/tests/src/python/test_qgsvectorlayertools.py b/tests/src/python/test_qgsvectorlayertools.py new file mode 100644 index 000000000000..2fcd4612897c --- /dev/null +++ b/tests/src/python/test_qgsvectorlayertools.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit test utils for provider tests. + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" + +from builtins import str +from builtins import object +__author__ = 'Denis Rouzaud' +__date__ = '2016-11-07' +__copyright__ = 'Copyright 2015, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +from qgis.core import QgsFeatureRequest, QgsVectorLayer, QgsMapLayerRegistry, QgsVectorLayerTools +from qgis.testing import start_app, unittest + +import os + +start_app() + + +class SubQgsVectorLayerTools(QgsVectorLayerTools): + + def __init__(self): + super().__init__() + + def addFeature(self, layer): + pass + + def startEditing(self, layer): + pass + + def stopEditing(self, layer): + pass + + def saveEdits(self, layer): + pass + + +class TestQgsVectorLayerTools(unittest.TestCase): + + @classmethod + def setUpClass(cls): + """ + Setup the involved layers and relations for a n:m relation + :return: + """ + cls.dbconn = 'service=\'qgis_test\'' + if 'QGIS_PGTEST_DB' in os.environ: + cls.dbconn = os.environ['QGIS_PGTEST_DB'] + # Create test layer + cls.vl = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."someData" (geom) sql=', 'layer', 'postgres') + + QgsMapLayerRegistry.instance().addMapLayer(cls.vl) + + cls.vltools = SubQgsVectorLayerTools() + + def testCopyMoveFeature(self): + """ Test copy and move features""" + rqst = QgsFeatureRequest() + rqst.setFilterFid(4) + self.vl.startEditing() + (ok, rqst, msg) = self.vltools.copyMoveFeatures(self.vl, rqst, -0.1, 0.2) + self.assertTrue(ok) + for f in self.vl.getFeatures(rqst): + geom = f.geometry() + self.assertAlmostEqual(geom.asPoint().x(), -65.42) + self.assertAlmostEqual(geom.asPoint().y(), 78.5) + + +if __name__ == '__main__': + unittest.main() From 6bfd0fd79ee99e4bc639f972afbbb8a2d20f0de3 Mon Sep 17 00:00:00 2001 From: aroche Date: Tue, 15 Nov 2016 10:23:57 +0100 Subject: [PATCH 770/897] fix exception when selecting string function just a typo causing an exception when selecting a string function in query builder dialog --- python/plugins/db_manager/dlg_query_builder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/db_manager/dlg_query_builder.py b/python/plugins/db_manager/dlg_query_builder.py index 6acd2b4f62c8..827dd4c43c2c 100644 --- a/python/plugins/db_manager/dlg_query_builder.py +++ b/python/plugins/db_manager/dlg_query_builder.py @@ -163,7 +163,7 @@ def add_functions(self): self.ui.functions.setCurrentIndex(0) def add_stringfct(self): - if self.ui.stringFct.currentIndex() <= 0: + if self.ui.stringfct.currentIndex() <= 0: return ag = self.ui.stringfct.currentText() From e9c4090e43694ec1a53e6ae5758c562a22f85a5d Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Tue, 15 Nov 2016 18:00:17 +0100 Subject: [PATCH 771/897] fix build of qspatialite and ocispatial sql drivers --- src/providers/oracle/ocispatial/qsqlcachedresult_p.h | 4 ++-- src/providers/spatialite/qspatialite/qsqlcachedresult_p.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/providers/oracle/ocispatial/qsqlcachedresult_p.h b/src/providers/oracle/ocispatial/qsqlcachedresult_p.h index 2286e2c524c8..9e5df5aad46d 100644 --- a/src/providers/oracle/ocispatial/qsqlcachedresult_p.h +++ b/src/providers/oracle/ocispatial/qsqlcachedresult_p.h @@ -65,12 +65,12 @@ class QSqlCachedResultPrivate; class Q_SQL_EXPORT QSqlCachedResult: public QSqlResult { public: - virtual ~QSqlCachedResult(); + virtual ~QSqlCachedResult() {} typedef QVector ValueCache; protected: - QSqlCachedResult( const QSqlDriver * db ); + QSqlCachedResult( const QSqlDriver * db ) : QSqlResult(db) {} void init( int colCount ); void cleanup(); diff --git a/src/providers/spatialite/qspatialite/qsqlcachedresult_p.h b/src/providers/spatialite/qspatialite/qsqlcachedresult_p.h index 2286e2c524c8..9e5df5aad46d 100644 --- a/src/providers/spatialite/qspatialite/qsqlcachedresult_p.h +++ b/src/providers/spatialite/qspatialite/qsqlcachedresult_p.h @@ -65,12 +65,12 @@ class QSqlCachedResultPrivate; class Q_SQL_EXPORT QSqlCachedResult: public QSqlResult { public: - virtual ~QSqlCachedResult(); + virtual ~QSqlCachedResult() {} typedef QVector ValueCache; protected: - QSqlCachedResult( const QSqlDriver * db ); + QSqlCachedResult( const QSqlDriver * db ) : QSqlResult(db) {} void init( int colCount ); void cleanup(); From 1d538a674562e3b63bf3ac225798b1769382fe35 Mon Sep 17 00:00:00 2001 From: Werner Macho Date: Tue, 15 Nov 2016 20:33:47 +0100 Subject: [PATCH 772/897] Add Translator Add new italian translator --- scripts/tsstat.pl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/tsstat.pl b/scripts/tsstat.pl index 6ded0e195434..d70021e15ba5 100755 --- a/scripts/tsstat.pl +++ b/scripts/tsstat.pl @@ -56,7 +56,7 @@ 'hr' => 'Zoran Jankovic', 'is' => 'Ásta Kristín Óladóttir, Thordur Ivarsson', 'id' => 'Emir Hartato, Muhammad Iqnaul Haq Siregar, Trias Aditya, Januar V. Simarmata, I Made Anombawa', - 'it' => 'Roberto Angeletti, Michele Beneventi, Marco Braida, Stefano Campus, Luca Casagrande, Paolo Cavallini, Giuliano Curti, Luca Delucchi, Alessandro Fanna, Michele Ferretti, Matteo Ghetta, Anne Gishla, Maurizio Napolitano, Flavio Rigolon', + 'it' => 'Marco Grisolia, Roberto Angeletti, Michele Beneventi, Marco Braida, Stefano Campus, Luca Casagrande, Paolo Cavallini, Giuliano Curti, Luca Delucchi, Alessandro Fanna, Michele Ferretti, Matteo Ghetta, Anne Gishla, Maurizio Napolitano, Flavio Rigolon', 'ja' => 'BABA Yoshihiko, Yoichi Kayama, Minoru Akagi, Takayuki Nuimura, Takayuki Mizutani, Norihiro Yamate', 'ka' => 'Shota Murtskhvaladze, George Machitidze', 'km' => 'Khoem Sokhem', From 87d2ac3525f706759e646dba14919be529d53d9d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 10:21:29 +1000 Subject: [PATCH 773/897] Add @map_extent variable containing geometry of current map extent ...Because I've seen a lot of ugly workarounds to recreate this extent using wkt/buffers/etc --- src/core/composer/qgscomposermap.cpp | 1 + src/core/qgsexpression.cpp | 1 + src/core/qgsexpressioncontext.cpp | 2 ++ 3 files changed, 4 insertions(+) diff --git a/src/core/composer/qgscomposermap.cpp b/src/core/composer/qgscomposermap.cpp index 4f2bcc46dcb9..f76ef04a2ba8 100644 --- a/src/core/composer/qgscomposermap.cpp +++ b/src/core/composer/qgscomposermap.cpp @@ -1820,6 +1820,7 @@ QgsExpressionContext QgsComposerMap::createExpressionContext() const scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_scale" ), scale(), true ) ); QgsRectangle extent( *currentMapExtent() ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent" ), QVariant::fromValue( QgsGeometry::fromRect( extent ) ), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_width" ), extent.width(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_height" ), extent.height(), true ) ); QgsGeometry centerPoint = QgsGeometry::fromPoint( extent.center() ); diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index 94bc8ff2d5bd..fc183e5c34cd 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -5746,6 +5746,7 @@ void QgsExpression::initVariableHelp() gVariableHelpTexts.insert( QStringLiteral( "map_id" ), QCoreApplication::translate( "variable_help", "ID of current map destination. This will be 'canvas' for canvas renders, and the item ID for composer map renders." ) ); gVariableHelpTexts.insert( QStringLiteral( "map_rotation" ), QCoreApplication::translate( "variable_help", "Current rotation of map." ) ); gVariableHelpTexts.insert( QStringLiteral( "map_scale" ), QCoreApplication::translate( "variable_help", "Current scale of map." ) ); + gVariableHelpTexts.insert( QStringLiteral( "map_extent" ), QCoreApplication::translate( "variable_help", "Geometry representing the current extent of the map." ) ); gVariableHelpTexts.insert( QStringLiteral( "map_extent_center" ), QCoreApplication::translate( "variable_help", "Center of map." ) ); gVariableHelpTexts.insert( QStringLiteral( "map_extent_width" ), QCoreApplication::translate( "variable_help", "Width of map." ) ); gVariableHelpTexts.insert( QStringLiteral( "map_extent_height" ), QCoreApplication::translate( "variable_help", "Height of map." ) ); diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index ca3273ea1c5e..4e91e08ba05d 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -752,6 +752,8 @@ QgsExpressionContextScope* QgsExpressionContextUtils::mapSettingsScope( const Qg scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_id" ), "canvas", true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_rotation" ), mapSettings.rotation(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_scale" ), mapSettings.scale(), true ) ); + QgsGeometry extent = QgsGeometry::fromRect( mapSettings.visibleExtent() ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent" ), QVariant::fromValue( extent ), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_width" ), mapSettings.visibleExtent().width(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "map_extent_height" ), mapSettings.visibleExtent().height(), true ) ); QgsGeometry centerPoint = QgsGeometry::fromPoint( mapSettings.visibleExtent().center() ); From 5e487cfea49f45bc696e116a5568f0c25c424d2d Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 7 Nov 2016 08:41:33 +0700 Subject: [PATCH 774/897] [FEATURE] Style management re-work and upgrade - A new favorite grouping system was added, which the symbols list widget defaults to - The selected tag / smartgroup in the symbols list widget now persists when switching layers (and across sessions) - The symbols list widget will update the tag / smartgroup combo box when users add / rename / remove categories - Users can now directly tag, as well as add to favorites, symbols while saving those to the style database - To streamline style management, groups have been removed and fully replaced by tags - Tags have been integrated into the import/export user interface --- doc/api_break.dox | 5 + python/core/symbology-ng/qgsstyle.sip | 200 ++++--- python/gui/gui.sip | 1 + .../qgsstyleexportimportdialog.sip | 12 +- .../qgsstylegroupselectiondialog.sip | 8 +- .../symbology-ng/qgsstylemanagerdialog.sip | 21 +- .../gui/symbology-ng/qgsstylesavedialog.sip | 22 + .../gui/symbology-ng/qgssymbolslistwidget.sip | 3 +- resources/symbology-ng-style.db | Bin 98304 -> 118784 bytes resources/symbology-ng-style.xml | 2 +- scripts/symbol_xml2db.py | 51 +- src/core/symbology-ng/qgsstyle.cpp | 342 ++++++------ src/core/symbology-ng/qgsstyle.h | 243 +++++---- src/gui/CMakeLists.txt | 2 + .../qgssmartgroupeditordialog.cpp | 4 +- .../qgsstyleexportimportdialog.cpp | 82 ++- .../symbology-ng/qgsstyleexportimportdialog.h | 14 +- .../qgsstylegroupselectiondialog.cpp | 55 +- .../qgsstylegroupselectiondialog.h | 10 +- .../symbology-ng/qgsstylemanagerdialog.cpp | 497 +++++++++--------- src/gui/symbology-ng/qgsstylemanagerdialog.h | 21 +- src/gui/symbology-ng/qgsstylesavedialog.cpp | 56 ++ src/gui/symbology-ng/qgsstylesavedialog.h | 57 ++ src/gui/symbology-ng/qgssymbolslistwidget.cpp | 146 ++--- src/gui/symbology-ng/qgssymbolslistwidget.h | 7 +- src/ui/qgsstyleexportimportdialogbase.ui | 30 +- src/ui/qgsstylemanagerdialogbase.ui | 56 +- src/ui/qgsstylesavedialog.ui | 126 +++++ src/ui/symbollayer/widget_symbolslist.ui | 10 +- tests/src/core/testqgsstyle.cpp | 32 +- 30 files changed, 1186 insertions(+), 929 deletions(-) create mode 100644 python/gui/symbology-ng/qgsstylesavedialog.sip create mode 100644 src/gui/symbology-ng/qgsstylesavedialog.cpp create mode 100644 src/gui/symbology-ng/qgsstylesavedialog.h create mode 100644 src/ui/qgsstylesavedialog.ui diff --git a/doc/api_break.dox b/doc/api_break.dox index 3a9223bac0c7..3a0be4484f10 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1352,6 +1352,11 @@ QgsSvgCache {#qgis_api_break_3_0_QgsSvgCache} - containsParamsV2() was removed. Use containsParamsV3() instead. +QgsStyle (renamed from QgsStyleV2) {#qgis_api_break_3_0_QgsStyle} +---------------------------------- +- All group functions have been removed: group(), addGroup(), groupId(), groupName(), groupNames(), groupIds(), symbolsOfGroup(), getGroupRemoveQuery() +- The StyleEntity::GroupEntity has been removed +- The SymgroupTable enum has been removed QgsSymbol (renamed from QgsSymbolV2) {#qgis_api_break_3_0_QgsSymbol} ------------------------------------ diff --git a/python/core/symbology-ng/qgsstyle.sip b/python/core/symbology-ng/qgsstyle.sip index 32395591bee2..f3f70d606d2a 100644 --- a/python/core/symbology-ng/qgsstyle.sip +++ b/python/core/symbology-ng/qgsstyle.sip @@ -8,15 +8,16 @@ class QgsStyle : QObject QgsStyle(); ~QgsStyle(); - //! Enum for Entities involved in a style - /*! - The enumerator is used for identifying the entity being operated on when generic - database functions are being run. - \sa group(), rename(), remove(), symbolsOfGroup(), symbolsWithTag(), symbolsOfSmartgroup() + /** Enum for Entities involved in a style + /* + * The enumerator is used for identifying the entity being operated on when generic + * database functions are being run. + * \sa group(), rename(), remove(), symbolsOfGroup(), symbolsWithTag(), symbolsOfSmartgroup() */ - enum StyleEntity { SymbolEntity, GroupEntity, TagEntity, ColorrampEntity, SmartgroupEntity }; + enum StyleEntity { SymbolEntity, TagEntity, ColorrampEntity, SmartgroupEntity }; /** Adds a color ramp to the style. Calling this method takes the ramp's ownership. + * * \note Adding a color ramp with the name of existing one replaces it. * \param name is the name of the color ramp being added or updated * \param colorRamp is the color ramp. Ownership is transferred. @@ -25,24 +26,16 @@ class QgsStyle : QObject */ bool addColorRamp( const QString& name, QgsColorRamp* colorRamp /Transfer/, bool update = false ); - //! adds a new group and returns the group's id - /*! - * \param groupName the name of the new group as QString - * \param parent is the id of the parent group when a subgrouo is to be created. By default it is 0 indicating it is not a sub-group - * \return returns an int, which is the DB id of the new group created, 0 if the group couldn't be created - */ - int addGroup( const QString& groupName, int parent = 0 ); - - //! adds new smartgroup to the database and returns the id - /*! + /** Adds new smartgroup to the database and returns the id + * * \param name is the name of the new Smart Group to be added * \param op is the operator between the conditions; AND/OR as QString * \param conditions are the smart group conditions */ int addSmartgroup( const QString& name, const QString& op, QMultiMap conditions ); - //! add symbol to style. takes symbol's ownership - /*! + /** Adds symbol to style and takes symbol's ownership + * * \note Adding a symbol with the name of existing one replaces it. * \param name is the name of the symbol being added or updated * \param symbol is the Vector symbol @@ -51,22 +44,19 @@ class QgsStyle : QObject */ bool addSymbol( const QString& name, QgsSymbol* symbol /Transfer/, bool update = false ); - //! adds a new tag and returns the tag's id - /*! + /** Adds a new tag and returns the tag's id + * * \param tagName the name of the new tag to be created * \return returns an int, which is the DB id of the new tag created, 0 if the tag couldn't be created */ int addTag( const QString& tagName ); /** Returns a list of all tags in the style database - * @note added in QGIS 2.16 - * @see addTag() + * @note added in QGIS 2.16 + * @see addTag() */ QStringList tags() const; - //! return a map of groupid and names for the given parent group - QMap childGroupNames( const QString& parent = "" ); - //! remove all contents of the style void clear(); @@ -75,24 +65,25 @@ class QgsStyle : QObject */ QgsColorRamp* colorRamp( const QString& name ) const /Factory/; - //! return count of color ramps + //! Returns count of color ramps int colorRampCount(); - //! return a list of names of color ramps + //! Returns a list of names of color ramps QStringList colorRampNames(); - //! return a const pointer to a symbol (doesn't create new instance) + //! Returns a const pointer to a symbol (doesn't create new instance) const QgsColorRamp* colorRampRef( const QString& name ) const; - //! return the id in the style database for the given colorramp name - //! returns 0 if not found + /** Returns the id in the style database for the given colorramp name + * returns 0 if not found + */ int colorrampId( const QString& name ); - //! return default application-wide style + //! Returns default application-wide style static QgsStyle* defaultStyle(); - //! tags the symbol with the tags in the list - /*! + /** Tags the symbol with the tags in the list + * * Applies the given tags to the given symbol or colorramp * \param type is either SymbolEntity or ColorrampEntity * \param symbol is the name of the symbol or colorramp as QString @@ -101,8 +92,8 @@ class QgsStyle : QObject */ bool tagSymbol( StyleEntity type, const QString& symbol, const QStringList& tags ); - //! detags the symbol with the given list - /*! + /** Detags the symbol with the given list + * * Removes the given tags for the specified symbol or colorramp * \param type is either SymbolEntity or ColorrampEntity * \param symbol is the name of the symbol or colorramp @@ -110,85 +101,89 @@ class QgsStyle : QObject * \return returns the success state of the operation */ bool detagSymbol( StyleEntity type, QString symbol, QStringList tags ); + /** Clears the symbol from all attached tags + * + * Removes all tags for the specified symbol or colorramp + * \param type is either SymbolEntity or ColorrampEntity + * \param symbol is the name of the symbol or colorramp + * \return returns the success state of the operation + */ + bool detagSymbol( StyleEntity type, QString symbol ); - //! remove symbol from style (and delete it) + //! Removes symbol from style (and delete it) bool removeSymbol( const QString& name ); - //! change symbol's name + //! Changes symbol's name bool renameSymbol( const QString& oldName, const QString& newName ); - //! return a NEW copy of symbol + //! Returns a NEW copy of symbol QgsSymbol* symbol( const QString& name ) /Factory/; - //! return a const pointer to a symbol (doesn't create new instance) + //! Returns a const pointer to a symbol (doesn't create new instance) const QgsSymbol* symbolRef( const QString& name ) const; - //! return count of symbols in style + //! Returns count of symbols in style int symbolCount(); - //! return a list of names of symbols + //! Returns a list of names of symbols QStringList symbolNames(); - //! return the id in the style database for the given symbol name - //! returns 0 if not found + /** Returns the id in the style database for the given symbol name + * returns 0 if not found + */ int symbolId( const QString& name ); - //! return the DB id for the given group name - int groupId( const QString& group ); - //! return the group name for the given DB id - QString groupName( int groupId ) const; - //! return the DB id for the given tag name + //! Returns the DB id for the given tag name int tagId( const QString& tag ); - //! return the DB id for the given smartgroup name + //! Returns the DB id for the given smartgroup name int smartgroupId( const QString& smartgroup ); - //! return the all the groups in the style - QStringList groupNames(); - - //! return the ids of all the groups in the style - QList groupIds() const; - - //! returns the symbolnames of a given groupid - /*! + /** Returns the symbol names which are flagged as favorite + * * \param type is either SymbolEntity or ColorampEntity - * \param groupid is id of the group to which the symbols belong to, as int - * \return A QStringList of the symbol or colorramp names for the given group id + * \return A QStringList of the symbol or colorramp names flagged as favorite */ - QStringList symbolsOfGroup( StyleEntity type, int groupid ); + QStringList symbolsOfFavorite( StyleEntity type ); - //! returns the symbol names with which have the given tag - /*! + /** Returns the symbol names with which have the given tag + * * \param type is either SymbolEntity or ColorampEntity * \param tagid is id of the tag which has been applied over the symbol as int * \return A QStringList of the symbol or colorramp names for the given tag id */ QStringList symbolsWithTag( StyleEntity type, int tagid ); - //! applies the specified group to the symbol or colorramp specified by StyleEntity - /*! + /** Adds the specified symbol to favorites + * + * \param type is either SymbolEntity of ColorrampEntity + * \param name is the name of the symbol or coloramp whose is to be added to favorites + * \return returns the success state as bool + */ + bool addFavorite( StyleEntity type, const QString& name ); + /** Removes the specified symbol from favorites + * * \param type is either SymbolEntity of ColorrampEntity - * \param name is the name of the symbol or coloramp whose group is to be set - * \param groupid is the id of the group to which the entity is assigned + * \param name is the name of the symbol or coloramp whose is to be removed from favorites * \return returns the success state as bool */ - bool group( StyleEntity type, const QString& name, int groupid ); + bool removeFavorite( StyleEntity type, const QString& name ); - //! rename the given entity with the specified id - /*! + /** Renames the given entity with the specified id + * * \param type is any of the style entites. Refer enum StyleEntity. * \param id is the DB id of the entity which is to be renamed * \param newName is the new name of the entity */ void rename( StyleEntity type, int id, const QString& newName ); - //! remove the specified entity from the db - /*! + /** Removes the specified entity from the db + * * \param type is any of the style entites. Refer enum StyleEntity. * \param id is the DB id of the entity to be removed */ void remove( StyleEntity type, int id ); - //! add the symbol to the DB with the tags - /*! + /** Adds the symbol to the DB with the tags + * * \param name is the name of the symbol as QString * \param symbol is the pointer to the new QgsSymbol being saved * \param groupid is the id of the group to which the symbol belongs. Pass 0 if it doesn't belong to any group or not known. @@ -197,8 +192,8 @@ class QgsStyle : QObject */ bool saveSymbol( const QString& name, QgsSymbol* symbol /Transfer/, int groupid, const QStringList& tags ); - //! add the colorramp to the DB - /*! + /** Adds the colorramp to the DB + * * \param name is the name of the colorramp as QString * \param ramp is the pointer to the new QgsColorRamp being saved * \param groupid is the id of the group to which the Color Ramp belongs. Pass 0 if it doesn't belong to any group or not known. @@ -207,54 +202,54 @@ class QgsStyle : QObject */ bool saveColorRamp( const QString& name, QgsColorRamp* ramp, int groupid, const QStringList& tags ); - //! remove color ramp from style (and delete it) + //! Removes color ramp from style (and delete it) bool removeColorRamp( const QString& name ); - //! change ramp's name + //! Changes ramp's name bool renameColorRamp( const QString& oldName, const QString& newName ); - //! load a file into the style + //! Loads a file into the style bool load( const QString& filename ); - //! save style into a file (will use current filename if empty string is passed) + //! Saves style into a file (will use current filename if empty string is passed) bool save( QString filename = QString() ); - //! return last error from load/save operation + //! Returns last error from load/save operation QString errorString(); - //! return current file name of the style + //! Returns current file name of the style QString fileName(); - //! return the names of the symbols which have a matching 'substring' in its defintion - /*! + /** Returns the names of the symbols which have a matching 'substring' in its defintion + * * \param type is either SymbolEntity or ColorrampEntity * \param qword is the query string to search the symbols or colorramps. * \return A QStringList of the matched symbols or colorramps * */ QStringList findSymbols( StyleEntity type, const QString& qword ); - //! return the tags associated with the symbol - /*! + /** Returns the tags associated with the symbol + * * \param type is either SymbolEntity or ColorrampEntity * \param symbol is the name of the symbol or color ramp * \return A QStringList of the tags that have been applied to that symbol/colorramp */ QStringList tagsOfSymbol( StyleEntity type, const QString& symbol ); - //! returns the smart groups map with id as key and name as value + //! Returns the smart groups map with id as key and name as value QMap smartgroupsListMap(); - //! returns the smart groups list + //! Returns the smart groups list QStringList smartgroupNames(); - //! returns the QgsSmartConditionMap for the given id + //! Returns the QgsSmartConditionMap for the given id QMultiMap smartgroup( int id ); - //! returns the operator for the smartgroup + //! Returns the operator for the smartgroup //clumsy implementation TODO create a class for smartgroups QString smartgroupOperator( int id ); - //! returns the symbols for the smartgroup + //! Returns the symbols for the smartgroup QStringList symbolsOfSmartgroup( StyleEntity type, int id ); //! Exports the style as a XML file @@ -264,29 +259,30 @@ class QgsStyle : QObject bool importXml( const QString& filename ); signals: + //! Is emitted every time a new symbol has been added to the database void symbolSaved( const QString& name, QgsSymbol* symbol ); + //! Is emitted every time a tag or smartgroup has been added, removed, or renamed + void groupsModified(); protected: - //! convenience function to open the DB and return a sqlite3 object + //! Convenience function to open the DB and return a sqlite3 object bool openDB( const QString& filename ); - //! convenience function that would run queries which don't generate return values - //! \param query query to run - //! \param freeQuery release query memory - //! \return success true on success + /** Convenience function that would run queries which don't generate return values + * \param query query to run + * \param freeQuery release query memory + * \return success true on success + */ bool runEmptyQuery( char* query, bool freeQuery = true ); - //! prepares the complex query for removing a group, so that the children are not abandoned - char* getGroupRemoveQuery( int id ); - - //! gets the id from the table for the given name from the database, 0 if not found + //! Gets the id from the table for the given name from the database, 0 if not found int getId( const QString& table, const QString& name ); - //! gets the name from the table for the given id from the database, empty if not found + //! Gets the name from the table for the given id from the database, empty if not found QString getName( const QString& table, int id ) const; - //! updates the properties of an existing symbol/colorramp - /*! + /** Updates the properties of an existing symbol/colorramp + * * \note This should not be called separately, only called through addSymbol or addColorRamp * \param type is either SymbolEntity or ColorrampEntity * \param name is the name of an existing symbol or a color ramp diff --git a/python/gui/gui.sip b/python/gui/gui.sip index 3587c165310f..4396df54e716 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -247,6 +247,7 @@ %Include symbology-ng/qgsstyleexportimportdialog.sip %Include symbology-ng/qgsstylegroupselectiondialog.sip %Include symbology-ng/qgsstylemanagerdialog.sip +%Include symbology-ng/qgsstylesavedialog.sip %Include symbology-ng/qgssvgselectorwidget.sip %Include symbology-ng/qgssymbollayerwidget.sip %Include symbology-ng/qgssymbollevelsdialog.sip diff --git a/python/gui/symbology-ng/qgsstyleexportimportdialog.sip b/python/gui/symbology-ng/qgsstyleexportimportdialog.sip index 678403050e9a..85ed24242a83 100644 --- a/python/gui/symbology-ng/qgsstyleexportimportdialog.sip +++ b/python/gui/symbology-ng/qgsstyleexportimportdialog.sip @@ -41,15 +41,15 @@ class QgsStyleExportImportDialog : QDialog */ void clearSelection(); /** - * Select the symbols belonging to the given group - * @param groupName the name of the group to be selected + * Select the symbols belonging to the given tag + * @param tagName the name of the tag to be selected */ - void selectGroup( const QString& groupName ); + void selectTag( const QString& tagName ); /** - * Deselect the symbols belonging to the given group - * @param groupName the name of the group to be deselected + * Deselect the symbols belonging to the given tag + * @param tagName the name of the tag to be deselected */ - void deselectGroup( const QString& groupName ); + void deselectTag( const QString& tagName ); /** * @brief selectSmartgroup selects all symbols from a smart group * @param groupName diff --git a/python/gui/symbology-ng/qgsstylegroupselectiondialog.sip b/python/gui/symbology-ng/qgsstylegroupselectiondialog.sip index 0579ebb6dbf3..8e4f99e818de 100644 --- a/python/gui/symbology-ng/qgsstylegroupselectiondialog.sip +++ b/python/gui/symbology-ng/qgsstylegroupselectiondialog.sip @@ -28,10 +28,10 @@ class QgsStyleGroupSelectionDialog : public QDialog, private Ui::SymbolsGroupSel void setBold( QStandardItem *item ); signals: - //! group with groupName has been selected - void groupSelected( const QString& groupName ); - //! group with groupName has been deselected - void groupDeselected( const QString& groupName ); + //! tag with tagName has been selected + void tagSelected( const QString& tagName ); + //! tag with tagName has been deselected + void tagDeselected( const QString& tagName ); //! smartgroup with groupName has been selected void smartgroupSelected( const QString& groupName ); //! smart group with groupName has been deselected diff --git a/python/gui/symbology-ng/qgsstylemanagerdialog.sip b/python/gui/symbology-ng/qgsstylemanagerdialog.sip index 012907dbf67b..dd0739d46a14 100644 --- a/python/gui/symbology-ng/qgsstylemanagerdialog.sip +++ b/python/gui/symbology-ng/qgsstylemanagerdialog.sip @@ -37,8 +37,8 @@ class QgsStyleManagerDialog : QDialog void addGroup(); void removeGroup(); - //! carryout symbol grouping using check boxes - void groupSymbolsAction(); + //! carry out symbol tagging using check boxes + void tagSymbolsAction(); //! edit the selected smart group void editSmartgroupAction(); @@ -49,9 +49,6 @@ class QgsStyleManagerDialog : QDialog //! filter the symbols based on input search term void filterSymbols( const QString& ); - //! Listen to tag changes - void tagsChanged(); - //! Perform symbol specific tasks when selected void symbolSelected( const QModelIndex& ); @@ -66,7 +63,14 @@ class QgsStyleManagerDialog : QDialog protected slots: bool addColorRamp( QAction* action ); - void groupSelectedSymbols(); + //! Add selected symbols to favorites + void addFavoriteSelectedSymbols(); + //! Remove selected symbols from favorites + void removeFavoriteSelectedSymbols(); + //! Tag selected symbols using menu item selection + void tagSelectedSymbols(); + //! Remove all tags from selected symbols + void detagSelectedSymbols(); protected: @@ -75,8 +79,6 @@ class QgsStyleManagerDialog : QDialog //! populate the groups void populateGroups(); - //! build the groups tree - void buildGroupTree( QStandardItem* &parent ); //! to set symbols checked when in editing mode void setSymbolsChecked( const QStringList& ); @@ -107,9 +109,6 @@ class QgsStyleManagerDialog : QDialog //! Enables or diables the groupTree items for grouping mode void enableItemsForGroupingMode( bool ); - //! Event filter to capture tagsLineEdit out of focus - bool eventFilter( QObject*, QEvent* ); - //! sets the text of the item with bold font void setBold( QStandardItem* ); }; diff --git a/python/gui/symbology-ng/qgsstylesavedialog.sip b/python/gui/symbology-ng/qgsstylesavedialog.sip new file mode 100644 index 000000000000..f73521ed223a --- /dev/null +++ b/python/gui/symbology-ng/qgsstylesavedialog.sip @@ -0,0 +1,22 @@ +class QgsStyleSaveDialog : QDialog +{ +%TypeHeaderCode +#include +%End + + public: + /** Constructor for QgsSymbolSaveDialog + * @param parent parent widget + * @param type the QgsStyle entity type being saved + */ + QgsStyleSaveDialog( QWidget* parent /TransferThis/ = NULL, QgsStyle::StyleEntity type = QgsStyle::SymbolEntity ); + + //! returns the text value of the name element + QString name() const; + + //! returns the text value of the tags element + QString tags() const; + + //! returns whether the favorite element is checked + bool isFavorite() const; +}; diff --git a/python/gui/symbology-ng/qgssymbolslistwidget.sip b/python/gui/symbology-ng/qgssymbolslistwidget.sip index 7bf1f727fe85..d7a7051a9398 100644 --- a/python/gui/symbology-ng/qgssymbolslistwidget.sip +++ b/python/gui/symbology-ng/qgssymbolslistwidget.sip @@ -37,8 +37,9 @@ class QgsSymbolsListWidget : QWidget void on_mSymbolUnitWidget_changed(); void on_mTransparencySlider_valueChanged( int value ); + //! Pupulates the groups combo box with available tags and smartgroups + void populateGroups(); void on_groupsCombo_currentIndexChanged( int index ); - void on_groupsCombo_editTextChanged( const QString &text ); void openStyleManager(); void clipFeaturesToggled( bool checked ); diff --git a/resources/symbology-ng-style.db b/resources/symbology-ng-style.db index 4807ad6169908372f0a2707e49f2475cd686fbed..6a62979ba86b7e608d0a74004b16482920f67442 100644 GIT binary patch delta 2345 zcmcIleNa@_6~E`+_jcd1yn7b~5fE7sH$FR`GsT1}g3jJDczYKMu*q$W*+jkab?w0A{POaJI!eKYqr zXU{!*&hPxrdArTcrshNDd3m|nTU}-LE!DM^#V-3IWJ3VRVYefMGOa%7gkQwxMA#!fcmzetRKU+`ouAsl!YQQj6L8;B zN6dj?VX!Ba58)zhOYyg>Yb66dnC! z*gx1U_E+{1d!Jore_&VGMfPiUmYrrN*@?+a?EY8C?&%BV7X#xYOpBHf5Glcbu7s&} z2~%cB@C%Y)3zWd7NT5uD?kmC9OTg+S;G_6ROw{8M`<&fm@3Av%koB{Jtefp)yV!PC z&hptBmc$~NKO^+-^g11(gY;Fp@*r)eEp!Jhqw8rpjiX_78ug(_zpdZYNA=(7=k=fK z1Ntla5A;sGRj=1;^euXUzD{4IFV*8Gb;OI52O{2b6;r})Nj@laT#!j&4~HRR)1RK< z9c4&}gkb7zAdH?z?4Rs!>_he^soh)b6#WbRGdsbKvO~;6udtWdi>yJmQ^pEd9?N2> zY%z;vGwFF2zN*2n!Ab6a98w^v1oyr_EOekDQJ{iBH1J4ZF4(Bmt_z>;im?>{1rF55u7sl$y6 z8(}B*$lS9;=<*vd?yM{Xj@@0Vg=|LF^XC0zv+(oJB|IX}$sa_|<~b#E#Z%AhB;1|n zbf+oqm~ftRe6GkzZXtaAVyAmouE=-nBJNVv3KUr`s&29lsOI9;|1i{avQ%$stY z++L#cd#fxD6Udy;7Bms@aZV!kT+$(!JGvD<(4Wn7`lx8y*h(HU+JLMh=6z&?Wb`EA z-zs(TuU47eF>AyoR|<&z+fy;WA)WSit8{vjOCUgWxXXcG+8)OfdNO#zYr&#pVHEJj zA7=90GABROJ%tzM&f@mkIijFKviA0!fvjiDdq{??l0^7mgOfMsQQ3Qj_-1pX6r$0| z$M*P)b6+D0n|4brr0?roRWg^WQ7WKN6&*mchTlgAqzK;?gWXwJoatPNdD>nl zPw4iaNG4+2&k`}PHwW{~$7{CkB<|m;W^*^PUNd(;T3Y`e!vEOy7!f%IDdOfnIhf3D z=Xg_95&uI2*{%jDNPUOw1O9I6BDwwdg?RlbEQSuR##&c=un7gen#YU!`{W>)n40-1 z;e|=3Mc)%^F=zMe(kR95Qj^aY$a=xtt}aJk$R=-c$FQUpz0kWEF2Ed7N@!d z-$90~_#^Sl_foJJ`Mm@4{0mNxJs7e@&ZXT%oVl zl_k~N?8Vz^DvDQzF9^3!{K5vKPeg^>j?-;>j2BP`*~WwYa>R7srK& z)|+*hCuYnL_R&$o9hv@o_y*-2RkL{W3Z0LnQ9jz|=PAsGAY-fqZ1C`B$R?6S)oG$Wj^wG$`N$$5i8}4Z;X*TeLuKOGlyhf~&Z8p|`lF&H}3+MH`vE&_;|A3plWGN`*9R z3;|?fUj-aUKWW`&c^MqCp#;!7zL97`0f(8kV{28JH;?grH1uLVQsC=lErRZTM2u}t z=mOstH!YDhUy9Rq6ubC4oxw)tOn3u~<3X?%8z%!G3&&6tkLUrt#kbO$?~|fk(?ZOe zdQjO*YH4^emrVi1Feylh7mRs|D zk}cty#dJh{NvS0pu>+zdeKQzFCOk=ut*gO9j6nxvNjuqV4=saf&{GF;K_Zb)pBg!_ zAW>ihRzf`(N)3ETjIJuEfPN(c6b-8k`Fu}h6OlGB9@N2Z8QJ8GY-xZ7X}hHTFPLHW Ae*gdg delta 3047 zcmai03shBA8s7i@d0bFHR3Jd)sv!76u7J-(9ukNoiVBq!klhGI5CJnQ#ciw^C(H5N zEgo|@sXa!`NjaWmE1{B__B6|uHjX`JYEtPjHR;T1Y;yi{4!Blp&02HT+TYoCpS}Ob z_doVsvm8$5|lZH zU|KT4)FguZbb>q52y!P7oJGkvy0)xCU3@ zGx!ir!>iB^FThsNpcPhzLIXSq zb$$*vP-Gq@-@I6k^RW3WYG@kozMQVB!gF0gElRw=PChs&P*k=D7vswonF zLTfru|4S(hk?wB_A64j}r@+z%Ga*W*FQ~!k>;v*p0M>X`Q7DI`RT!tX343?Y0GG0 zJOJPbgCmA8!7M(J%Qw3rAb2^0V=#|>&X#M!E6dK=s^aAO3-)A)?EbSoi8VuC%XY}n zJ!7HF6qi~ou`>12JpGeN5O1b_I0W?X5+IxSE0&dCC+ewlAjX_~u>mxZVZL_mE!scP zIUM?7CYZ;+$s{I6`8N9Z;{`ScR7C}bn9SwL8@AHnGXHaXGE9og_QWkud}VWB6*!Z_ zp1s?gdBrj$*)%>sOYc;A`@rn}PZr6xoTfC(VN`ZGhL{L4{<om@98+6^U^*F@;6$d2L6;#8fLcEY zW^&(-RE{4QVkCw>6A?pp92n-B-|TH@vhC2XN5E<;XRSuYWcD9ND0dN*^`@YHC)C)= z$H?$+%GBG1@FG&3FshLY3{1#l7c}vv{#24S|(eHui|20cJsng%_v z3H$?LA%zPT8e$gc85xew3{^XYn6(R6_cTF~-aQ+lRCgMrf|@W1CKKr%M`t&KZbNi{ zx;_E2h;$NooWXHeKn`*chFAqkr9!6l$^TaIsC5e=*Oq^`giS+a`_>?(-2)e}e+c@h zQDrd5K%XH-!GKM3lF0TwVXnnX8|%G|PWV)A0eH9-zp*r|UglV{h`}O5%!BZ@$Yg3( zFU7eYsHv)6+Sd=&wK90bJ~oAp-J_anskiiZdSeQM6eu>taB#Kdjt*eaFFmGSu7*=~ z|GeGVW7R&(ryB&+{oY;&7U`aQAVLjlh0Bg8&hi-_!SXdRP3@_I!)SYcD>=JXK>?>= z9c6IT5U+rG^fAbBO5zLR5=yL|dtN`^;DjPi_gn7FW~!+xiDD-xRcVl?%;oSK%AItb ze$CYDH$b`iY#Aib(qxB@P6nNZXb08#G!$A&4=^}jh~1!;tfwYxMT-w-d^o&9mCmhX z=>fIjx9|zrC0fV$7Ff&bG*O}Iwt;lo;x4}~u(Bh)z_ zYT;f1&v5HHo#7NsE#p_(azN)w2&GL8WYj6y7VXhH)RPVl|pr6tXsaAlcL!>neF5 zf2Ho(1A|o4URcp5sDtsV@E+^X#BLR|8w&f@NyIi-ZHrKiFM!^+t}Ml8n9{@^HEJi! zvYA*YJ@0zV8`|3rFJ}9$7?7WBUZ_83UA?8gid(l>nGD|)BRB4M=|`I(M8<6jl>_#s z$S3zcY>wS`6!eyR!EILWoeoxT?=oTc9cbT$vU>0D?RcA2yS~J}JCVs{TLZz&1y1se^~;{{cPeQ>4*0(z - + diff --git a/scripts/symbol_xml2db.py b/scripts/symbol_xml2db.py index 9cf7102df11c..8d220715b244 100644 --- a/scripts/symbol_xml2db.py +++ b/scripts/symbol_xml2db.py @@ -32,13 +32,13 @@ "id INTEGER PRIMARY KEY,"\ "name TEXT UNIQUE,"\ "xml TEXT,"\ - "groupid INTEGER)" + "favorite INTEGER)" _colorramp = "CREATE TABLE colorramp("\ "id INTEGER PRIMARY KEY,"\ "name TEXT UNIQUE,"\ "xml TEXT,"\ - "groupid INTEGER)" + "favorite INTEGER)" _tag = "CREATE TABLE tag("\ "id INTEGER PRIMARY KEY,"\ @@ -48,57 +48,60 @@ "tag_id INTEGER NOT NULL,"\ "symbol_id INTEGER)" -_symgroup = "CREATE TABLE symgroup("\ - "id INTEGER PRIMARY KEY,"\ - "name TEXT,"\ - "parent INTEGER)" +_ctagmap = "CREATE TABLE ctagmap("\ + "tag_id INTEGER NOT NULL,"\ + "colorramp_id INTEGER)" _smartgroup = "CREATE TABLE smartgroup("\ "id INTEGER PRIMARY KEY,"\ "name TEXT,"\ "xml TEXT)" -_ctagmap = "CREATE TABLE ctagmap("\ - "tag_id INTEGER NOT NULL,"\ - "colorramp_id INTEGER)" - -create_tables = [ _symbol, _colorramp, _tag, _tagmap, _ctagmap, _symgroup, _smartgroup ] +create_tables = [_symbol, _colorramp, _tag, _tagmap, _ctagmap, _smartgroup] # Create the DB with required Schema -conn = sqlite3.connect( dbfile ) +conn = sqlite3.connect(dbfile) c = conn.cursor() print "Creating tables in the Database\n" for table in create_tables: try: - c.execute( table ) + c.execute(table) print table except sqlite3.OperationalError as e: pass conn.commit() # parse the XML file & write symbol into DB -dom = parse( xmlfile ) -symbols = dom.getElementsByTagName( "symbol" ) +dom = parse(xmlfile) +symbols = dom.getElementsByTagName("symbol") for symbol in symbols: - symbol_name = symbol.getAttribute( "name" ) + symbol_name = symbol.getAttribute("name") + symbol_favorite = symbol.getAttribute("favorite") + if not symbol_favorite: + symbol_favorite = 0 + if '@' in symbol_name: parts = symbol_name.split('@') parent_name = parts[1] layerno = int(parts[2]) - c.execute( "SELECT xml FROM symbol WHERE name=(?)", (parent_name,) ) - symdom = parseString( c.fetchone()[0] ).getElementsByTagName( 'symbol' )[0] - symdom.getElementsByTagName( "layer" )[ layerno ].appendChild( symbol ) - c.execute( "UPDATE symbol SET xml=? WHERE name=?", ( symdom.toxml(), parent_name )) + c.execute("SELECT xml FROM symbol WHERE name=(?)", (parent_name,)) + symdom = parseString(c.fetchone()[0]).getElementsByTagName('symbol')[0] + symdom.getElementsByTagName("layer")[layerno].appendChild(symbol) + c.execute("UPDATE symbol SET xml=? WHERE name=?", (symdom.toxml(), parent_name)) else: - c.execute( "INSERT INTO symbol VALUES (?,?,?,?)", ( None, symbol_name, symbol.toxml(), 0 ) ) + c.execute("INSERT INTO symbol VALUES (?,?,?,?)", (None, symbol_name, symbol.toxml(), symbol_favorite)) conn.commit() # ColorRamps -colorramps = dom.getElementsByTagName( "colorramp" ) +colorramps = dom.getElementsByTagName("colorramp") for ramp in colorramps: - ramp_name = ramp.getAttribute( "name" ) - c.execute( "INSERT INTO colorramp VALUES (?,?,?,?)", ( None, ramp_name, ramp.toxml(), 0 ) ) + ramp_name = ramp.getAttribute("name") + symbol_favorite = symbol.getAttribute("favorite") + if not symbol_favorite: + symbol_favorite = 0 + + c.execute("INSERT INTO colorramp VALUES (?,?,?,?)", (None, ramp_name, ramp.toxml(), symbol_favorite)) conn.commit() # Finally close the sqlite cursor diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index 4410974001dc..cc7d03b377eb 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -96,13 +97,13 @@ bool QgsStyle::addSymbol( const QString& name, QgsSymbol* symbol, bool update ) { mSymbols.insert( name, symbol ); if ( update ) - saveSymbol( name, symbol, 0, QStringList() ); + saveSymbol( name, symbol, false, QStringList() ); } return true; } -bool QgsStyle::saveSymbol( const QString& name, QgsSymbol* symbol, int groupid, const QStringList& tags ) +bool QgsStyle::saveSymbol( const QString& name, QgsSymbol* symbol, bool favorite, const QStringList& tags ) { // TODO add support for groups QDomDocument doc( QStringLiteral( "dummy" ) ); @@ -118,7 +119,7 @@ bool QgsStyle::saveSymbol( const QString& name, QgsSymbol* symbol, int groupid, stream.setCodec( "UTF-8" ); symEl.save( stream, 4 ); char *query = sqlite3_mprintf( "INSERT INTO symbol VALUES (NULL, '%q', '%q', %d);", - name.toUtf8().constData(), xmlArray.constData(), groupid ); + name.toUtf8().constData(), xmlArray.constData(), ( favorite ? 1 : 0 ) ); if ( !runEmptyQuery( query ) ) { @@ -207,11 +208,12 @@ bool QgsStyle::addColorRamp( const QString& name, QgsColorRamp* colorRamp, bool return true; } -bool QgsStyle::saveColorRamp( const QString& name, QgsColorRamp* ramp, int groupid, const QStringList& tags ) +bool QgsStyle::saveColorRamp( const QString& name, QgsColorRamp* ramp, bool favorite, const QStringList& tags ) { // insert it into the database QDomDocument doc( QStringLiteral( "dummy" ) ); QDomElement rampEl = QgsSymbolLayerUtils::saveColorRamp( name, ramp, doc ); + if ( rampEl.isNull() ) { QgsDebugMsg( "Couldn't convert color ramp to valid XML!" ); @@ -223,8 +225,7 @@ bool QgsStyle::saveColorRamp( const QString& name, QgsColorRamp* ramp, int group stream.setCodec( "UTF-8" ); rampEl.save( stream, 4 ); char *query = sqlite3_mprintf( "INSERT INTO colorramp VALUES (NULL, '%q', '%q', %d);", - name.toUtf8().constData(), xmlArray.constData(), groupid ); - + name.toUtf8().constData(), xmlArray.constData(), ( favorite ? 1 : 0 ) ); if ( !runEmptyQuery( query ) ) { QgsDebugMsg( "Couldn't insert colorramp into the database!" ); @@ -301,8 +302,8 @@ bool QgsStyle::load( const QString& filename ) } // Make sure there are no Null fields in parenting symbols ang groups - char *query = sqlite3_mprintf( "UPDATE symbol SET groupid=0 WHERE groupid IS NULL;" - "UPDATE colorramp SET groupid=0 WHERE groupid IS NULL;" + char *query = sqlite3_mprintf( "UPDATE symbol SET favorite=0 WHERE favorite IS NULL;" + "UPDATE colorramp SET favorite=0 WHERE favorite IS NULL;" "UPDATE symgroup SET parent=0 WHERE parent IS NULL;" ); runEmptyQuery( query ); @@ -460,97 +461,22 @@ bool QgsStyle::renameColorRamp( const QString& oldName, const QString& newName ) return true; } -QStringList QgsStyle::groupNames() -{ - QStringList groupNames; - sqlite3_stmt *ppStmt; - const char *query = "SELECT * FROM symgroup"; - int nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); - while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) - { - groupNames << QString::fromUtf8( reinterpret_cast< const char * >( sqlite3_column_text( ppStmt, SymgroupName ) ) ); - } - sqlite3_finalize( ppStmt ); - return groupNames; -} - -QList QgsStyle::groupIds() const +QStringList QgsStyle::symbolsOfFavorite( StyleEntity type ) const { - QList groupIds; - sqlite3_stmt *ppStmt; - const char *query = "SELECT * FROM symgroup"; - int nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); - while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) - { - groupIds << QString::fromUtf8( reinterpret_cast< const char * >( sqlite3_column_text( ppStmt, SymgroupId ) ) ).toInt(); - } - sqlite3_finalize( ppStmt ); - return groupIds; -} - -QgsSymbolGroupMap QgsStyle::childGroupNames( const QString& parent ) -{ - // get the name list from the sqlite database and return as a QStringList if ( !mCurrentDB ) { - QgsDebugMsg( "Cannot open database for listing groups" ); - return QgsSymbolGroupMap(); - } - - char *query = nullptr; - int nError; - sqlite3_stmt *ppStmt; - - // decide the query to be run based on parent group - if ( parent == QLatin1String( "" ) || parent == QString() ) - { - query = sqlite3_mprintf( "SELECT * FROM symgroup WHERE parent=0" ); - } - else - { - char *subquery = sqlite3_mprintf( "SELECT * FROM symgroup WHERE name='%q'", parent.toUtf8().constData() ); - nError = sqlite3_prepare_v2( mCurrentDB, subquery, -1, &ppStmt, nullptr ); - if ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) - { - query = sqlite3_mprintf( "SELECT * FROM symgroup WHERE parent=%d", sqlite3_column_int( ppStmt, SymgroupId ) ); - } - sqlite3_finalize( ppStmt ); - } - - if ( !query ) - return QgsSymbolGroupMap(); - - QgsSymbolGroupMap groupNames; - - // Now run the query and retrieve the group names - nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); - while ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) - { - QString group = QString::fromUtf8( reinterpret_cast< const char * >( sqlite3_column_text( ppStmt, SymgroupName ) ) ); - groupNames.insert( sqlite3_column_int( ppStmt, SymgroupId ), group ); - } - - sqlite3_finalize( ppStmt ); - - return groupNames; -} - -QStringList QgsStyle::symbolsOfGroup( StyleEntity type, int groupid ) -{ - if ( !mCurrentDB ) - { - QgsDebugMsg( QString( "Cannot Open database for getting group symbols of groupid: %1" ).arg( groupid ) ); + QgsDebugMsg( QString( "Cannot Open database for getting favorite symbols" ) ); return QStringList(); } char *query; if ( type == SymbolEntity ) { - query = sqlite3_mprintf( "SELECT name FROM symbol WHERE groupid=%d", groupid ); + query = sqlite3_mprintf( "SELECT name FROM symbol WHERE favorite=1" ); } else if ( type == ColorrampEntity ) { - query = sqlite3_mprintf( "SELECT name FROM colorramp WHERE groupid=%d", groupid ); + query = sqlite3_mprintf( "SELECT name FROM colorramp WHERE favorite=1" ); } else { @@ -572,7 +498,7 @@ QStringList QgsStyle::symbolsOfGroup( StyleEntity type, int groupid ) return symbols; } -QStringList QgsStyle::symbolsWithTag( StyleEntity type, int tagid ) +QStringList QgsStyle::symbolsWithTag( StyleEntity type, int tagid ) const { if ( !mCurrentDB ) { @@ -587,7 +513,7 @@ QStringList QgsStyle::symbolsWithTag( StyleEntity type, int tagid ) } else if ( type == ColorrampEntity ) { - subquery = sqlite3_mprintf( "SELECT symbol_id FROM ctagmap WHERE tag_id=%d", tagid ); + subquery = sqlite3_mprintf( "SELECT colorramp_id FROM ctagmap WHERE tag_id=%d", tagid ); } else { @@ -598,15 +524,15 @@ QStringList QgsStyle::symbolsWithTag( StyleEntity type, int tagid ) sqlite3_stmt *ppStmt; int nErr = sqlite3_prepare_v2( mCurrentDB, subquery, -1, &ppStmt, nullptr ); - // get the symbol <-> tag connection from table 'tagmap' + // get the symbol <-> tag connection from table 'tagmap'/'ctagmap' QStringList symbols; while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) { - int symbolId = sqlite3_column_int( ppStmt, 0 ); + int id = sqlite3_column_int( ppStmt, 0 ); char *query = type == SymbolEntity - ? sqlite3_mprintf( "SELECT name FROM symbol WHERE id=%d", symbolId ) - : sqlite3_mprintf( "SELECT name FROM colorramp WHERE id=%d", symbolId ); + ? sqlite3_mprintf( "SELECT name FROM symbol WHERE id=%d", id ) + : sqlite3_mprintf( "SELECT name FROM colorramp WHERE id=%d", id ); sqlite3_stmt *ppStmt2; int sErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt2, nullptr ); @@ -621,23 +547,6 @@ QStringList QgsStyle::symbolsWithTag( StyleEntity type, int tagid ) return symbols; } -int QgsStyle::addGroup( const QString& groupName, int parentid ) -{ - if ( !mCurrentDB ) - return 0; - - char *query = sqlite3_mprintf( "INSERT INTO symgroup VALUES (NULL, '%q', %d)", groupName.toUtf8().constData(), parentid ); - - sqlite3_stmt *ppStmt; - int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); - if ( nErr == SQLITE_OK ) - ( void )sqlite3_step( ppStmt ); - - sqlite3_finalize( ppStmt ); - - return static_cast< int >( sqlite3_last_insert_rowid( mCurrentDB ) ); -} - int QgsStyle::addTag( const QString& tagname ) { if ( !mCurrentDB ) @@ -650,6 +559,11 @@ int QgsStyle::addTag( const QString& tagname ) ( void )sqlite3_step( ppStmt ); sqlite3_finalize( ppStmt ); + QSettings settings; + settings.setValue( QStringLiteral( "qgis/symbolsListGroupsIndex" ), 0 ); + + emit groupsModified(); + return static_cast< int >( sqlite3_last_insert_rowid( mCurrentDB ) ); } @@ -676,69 +590,60 @@ QStringList QgsStyle::tags() const void QgsStyle::rename( StyleEntity type, int id, const QString& newName ) { + bool groupRenamed = false; char *query; switch ( type ) { case SymbolEntity: query = sqlite3_mprintf( "UPDATE symbol SET name='%q' WHERE id=%d", newName.toUtf8().constData(), id ); break; - case GroupEntity: - query = sqlite3_mprintf( "UPDATE symgroup SET name='%q' WHERE id=%d", newName.toUtf8().constData(), id ); + case ColorrampEntity: + query = sqlite3_mprintf( "UPDATE colorramp SET name='%q' WHERE id=%d", newName.toUtf8().constData(), id ); break; case TagEntity: query = sqlite3_mprintf( "UPDATE tag SET name='%q' WHERE id=%d", newName.toUtf8().constData(), id ); - break; - case ColorrampEntity: - query = sqlite3_mprintf( "UPDATE colorramp SET name='%q' WHERE id=%d", newName.toUtf8().constData(), id ); + groupRenamed = true; break; case SmartgroupEntity: query = sqlite3_mprintf( "UPDATE smartgroup SET name='%q' WHERE id=%d", newName.toUtf8().constData(), id ); + groupRenamed = true; break; default: QgsDebugMsg( "Invalid Style Entity indicated" ); return; } if ( !runEmptyQuery( query ) ) + { mErrorString = QStringLiteral( "Could not rename!" ); -} - -char* QgsStyle::getGroupRemoveQuery( int id ) -{ - char *query = sqlite3_mprintf( "SELECT parent FROM symgroup WHERE id=%d", id ); - - sqlite3_stmt *ppStmt; - int err = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); - - int parentid = 0; - if ( err == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) - parentid = sqlite3_column_int( ppStmt, 0 ); - - sqlite3_finalize( ppStmt ); - - return sqlite3_mprintf( "UPDATE symbol SET groupid=%d WHERE groupid=%d;" - "UPDATE symgroup SET parent=%d WHERE parent=%d;" - "DELETE FROM symgroup WHERE id=%d", parentid, id, parentid, id, id ); + } + else + { + if ( groupRenamed ) + { + emit groupsModified(); + } + } } void QgsStyle::remove( StyleEntity type, int id ) { + bool groupRemoved = false; char *query; switch ( type ) { case SymbolEntity: query = sqlite3_mprintf( "DELETE FROM symbol WHERE id=%d; DELETE FROM tagmap WHERE symbol_id=%d", id, id ); break; - case GroupEntity: - query = getGroupRemoveQuery( id ); + case ColorrampEntity: + query = sqlite3_mprintf( "DELETE FROM colorramp WHERE id=%d", id ); break; case TagEntity: query = sqlite3_mprintf( "DELETE FROM tag WHERE id=%d; DELETE FROM tagmap WHERE tag_id=%d", id, id ); - break; - case ColorrampEntity: - query = sqlite3_mprintf( "DELETE FROM colorramp WHERE id=%d", id ); + groupRemoved = true; break; case SmartgroupEntity: query = sqlite3_mprintf( "DELETE FROM smartgroup WHERE id=%d", id ); + groupRemoved = true; break; default: QgsDebugMsg( "Invalid Style Entity indicated" ); @@ -749,6 +654,16 @@ void QgsStyle::remove( StyleEntity type, int id ) { QgsDebugMsg( "Could not delete entity!" ); } + else + { + if ( groupRemoved ) + { + QSettings settings; + settings.setValue( QStringLiteral( "qgis/symbolsListGroupsIndex" ), 0 ); + + emit groupsModified(); + } + } } bool QgsStyle::runEmptyQuery( char *query, bool freeQuery ) @@ -772,17 +687,38 @@ bool QgsStyle::runEmptyQuery( char *query, bool freeQuery ) return zErr == SQLITE_OK; } -bool QgsStyle::group( StyleEntity type, const QString& name, int groupid ) +bool QgsStyle::addFavorite( StyleEntity type, const QString& name ) +{ + char *query; + + switch ( type ) + { + case SymbolEntity: + query = sqlite3_mprintf( "UPDATE symbol SET favorite=1 WHERE name='%q'", name.toUtf8().constData() ); + break; + case ColorrampEntity: + query = sqlite3_mprintf( "UPDATE colorramp SET favorite=1 WHERE name='%q'", name.toUtf8().constData() ); + break; + + default: + QgsDebugMsg( "Wrong entity value. cannot apply group" ); + return false; + } + + return runEmptyQuery( query ); +} + +bool QgsStyle::removeFavorite( StyleEntity type, const QString& name ) { char *query; switch ( type ) { case SymbolEntity: - query = sqlite3_mprintf( "UPDATE symbol SET groupid=%d WHERE name='%q'", groupid, name.toUtf8().constData() ); + query = sqlite3_mprintf( "UPDATE symbol SET favorite=0 WHERE name='%q'", name.toUtf8().constData() ); break; case ColorrampEntity: - query = sqlite3_mprintf( "UPDATE colorramp SET groupid=%d WHERE name='%q'", groupid, name.toUtf8().constData() ); + query = sqlite3_mprintf( "UPDATE colorramp SET favorite=0 WHERE name='%q'", name.toUtf8().constData() ); break; default: @@ -882,37 +818,41 @@ bool QgsStyle::tagSymbol( StyleEntity type, const QString& symbol, const QString return false; } - - Q_FOREACH ( const QString &tag, tags ) + QString tag; + Q_FOREACH ( const QString &t, tags ) { - // sql: gets the id of the tag if present or insert the tag and get the id of the tag - char *query = sqlite3_mprintf( "SELECT id FROM tag WHERE name='%q'", tag.toUtf8().constData() ); + tag = t.trimmed(); + if ( tag != "" ) + { + // sql: gets the id of the tag if present or insert the tag and get the id of the tag + char *query = sqlite3_mprintf( "SELECT id FROM tag WHERE LOWER(name)='%q'", tag.toUtf8().toLower().constData() ); - sqlite3_stmt *ppStmt; - int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); + sqlite3_stmt *ppStmt; + int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); - int tagid; - if ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) - { - tagid = sqlite3_column_int( ppStmt, 0 ); - } - else - { - tagid = addTag( tag ); - } + int tagid; + if ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) + { + tagid = sqlite3_column_int( ppStmt, 0 ); + } + else + { + tagid = addTag( tag ); + } - sqlite3_finalize( ppStmt ); + sqlite3_finalize( ppStmt ); - // Now map the tag to the symbol - query = type == SymbolEntity - ? sqlite3_mprintf( "INSERT INTO tagmap VALUES (%d,%d)", tagid, symbolid ) - : sqlite3_mprintf( "INSERT INTO ctagmap VALUES (%d,%d)", tagid, symbolid ); + // Now map the tag to the symbol + query = type == SymbolEntity + ? sqlite3_mprintf( "INSERT INTO tagmap VALUES (%d,%d)", tagid, symbolid ) + : sqlite3_mprintf( "INSERT INTO ctagmap VALUES (%d,%d)", tagid, symbolid ); - char *zErr = nullptr; - nErr = sqlite3_exec( mCurrentDB, query, nullptr, nullptr, &zErr ); - if ( nErr ) - { - QgsDebugMsg( zErr ); + char *zErr = nullptr; + nErr = sqlite3_exec( mCurrentDB, query, nullptr, nullptr, &zErr ); + if ( nErr ) + { + QgsDebugMsg( zErr ); + } } } @@ -977,6 +917,45 @@ bool QgsStyle::detagSymbol( StyleEntity type, const QString& symbol, const QStri return true; } +bool QgsStyle::detagSymbol( StyleEntity type, const QString& symbol ) +{ + if ( !mCurrentDB ) + { + QgsDebugMsg( "Sorry! Cannot open database for detgging." ); + return false; + } + + char *query = type == SymbolEntity + ? sqlite3_mprintf( "SELECT id FROM symbol WHERE name='%q'", symbol.toUtf8().constData() ) + : sqlite3_mprintf( "SELECT id FROM colorramp WHERE name='%q'", symbol.toUtf8().constData() ); + sqlite3_stmt *ppStmt; + int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); + + int symbolid = 0; + if ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) + { + symbolid = sqlite3_column_int( ppStmt, 0 ); + } + else + { + sqlite3_finalize( ppStmt ); + return false; + } + + sqlite3_finalize( ppStmt ); + + // remove all tags + query = type == SymbolEntity + ? sqlite3_mprintf( "DELETE FROM tagmap WHERE symbol_id=%d", symbolid ) + : sqlite3_mprintf( "DELETE FROM ctagmap WHERE colorramp_id=%d", symbolid ); + runEmptyQuery( query ); + + // TODO Perform tag cleanup + // check the number of entries for a given tag in the tagmap + // if the count is 0, then remove( TagEntity, tagid ) + return true; +} + QStringList QgsStyle::tagsOfSymbol( StyleEntity type, const QString& symbol ) { if ( !mCurrentDB ) @@ -1018,7 +997,7 @@ QStringList QgsStyle::tagsOfSymbol( StyleEntity type, const QString& symbol ) int QgsStyle::getId( const QString& table, const QString& name ) { - char *query = sqlite3_mprintf( "SELECT id FROM %q WHERE name='%q'", table.toUtf8().constData(), name.toUtf8().constData() ); + char *query = sqlite3_mprintf( "SELECT id FROM %q WHERE LOWER(name)='%q'", table.toUtf8().constData(), name.toUtf8().toLower().constData() ); sqlite3_stmt *ppStmt; int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); @@ -1062,16 +1041,6 @@ int QgsStyle::colorrampId( const QString& name ) return getId( QStringLiteral( "colorramp" ), name ); } -int QgsStyle::groupId( const QString& name ) -{ - return getId( QStringLiteral( "symgroup" ), name ); -} - -QString QgsStyle::groupName( int groupId ) const -{ - return getName( QStringLiteral( "symgroup" ), groupId ); -} - int QgsStyle::tagId( const QString& name ) { return getId( QStringLiteral( "tag" ), name ); @@ -1113,6 +1082,10 @@ int QgsStyle::addSmartgroup( const QString& name, const QString& op, const QgsSm if ( runEmptyQuery( query ) ) { + QSettings settings; + settings.setValue( QStringLiteral( "qgis/symbolsListGroupsIndex" ), 0 ); + + emit groupsModified(); return static_cast< int >( sqlite3_last_insert_rowid( mCurrentDB ) ); } else @@ -1211,12 +1184,6 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) { resultNames = symbolsWithTag( type, tagId( param ) ); } - else if ( constraint == QLatin1String( "group" ) ) - { - // XXX Validating group id might be a good idea here - resultNames = symbolsOfGroup( type, groupId( param ) ); - - } else if ( constraint == QLatin1String( "name" ) ) { if ( type == SymbolEntity ) @@ -1237,15 +1204,6 @@ QStringList QgsStyle::symbolsOfSmartgroup( StyleEntity type, int id ) resultNames.removeAll( name ); } } - else if ( constraint == QLatin1String( "!group" ) ) - { - resultNames = type == SymbolEntity ? symbolNames() : colorRampNames(); - QStringList unwanted = symbolsOfGroup( type, groupId( param ) ); - Q_FOREACH ( const QString& name, unwanted ) - { - resultNames.removeAll( name ); - } - } else if ( constraint == QLatin1String( "!name" ) ) { QStringList all = type == SymbolEntity ? symbolNames() : colorRampNames(); diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index 6c0edcf32629..9e415b00069a 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -41,8 +41,6 @@ typedef QMap QgsSymbolGroupMap; * The supported constraints are: * tag -> symbol has the tag matching the parameter * !tag -> symbol doesnot have the tag matching the parameter - * group -> symbol belongs to group specified by the parameter - * !group -> symbol doesn't belong to the group specified by the parameter * name -> symbol has a part of its name matching the parameter * !name -> symbol doesn't have any part of the name matching the parameter * @@ -56,11 +54,10 @@ typedef QMap QgsSymbolGroupMap; typedef QMultiMap QgsSmartConditionMap; // enumerators representing sqlite DB columns -enum SymbolTable { SymbolId, SymbolName, SymbolXML, SymbolGroupId }; -enum SymgroupTable { SymgroupId, SymgroupName, SymgroupParent }; +enum SymbolTable { SymbolId, SymbolName, SymbolXML, SymbolFavoriteId }; enum TagTable { TagId, TagName }; enum TagmapTable { TagmapTagId, TagmapSymbolId }; -enum ColorrampTable { ColorrampId, ColorrampName, ColorrampXML, ColorrampGroupId }; +enum ColorrampTable { ColorrampId, ColorrampName, ColorrampXML, ColorrampFavoriteId }; enum SmartgroupTable { SmartgroupId, SmartgroupName, SmartgroupXML }; /** \ingroup core @@ -74,13 +71,23 @@ class CORE_EXPORT QgsStyle : public QObject QgsStyle(); ~QgsStyle(); - //! Enum for Entities involved in a style - /*! - The enumerator is used for identifying the entity being operated on when generic - database functions are being run. - \sa group(), rename(), remove(), symbolsOfGroup(), symbolsWithTag(), symbolsOfSmartgroup() + /** Enum for Entities involved in a style + * + * The enumerator is used for identifying the entity being operated on when generic + * database functions are being run. + * \sa rename(), remove(), symbolsOfFavorite(), symbolsWithTag(), symbolsOfSmartgroup() */ - enum StyleEntity { SymbolEntity, GroupEntity, TagEntity, ColorrampEntity, SmartgroupEntity }; + enum StyleEntity { SymbolEntity, TagEntity, ColorrampEntity, SmartgroupEntity }; + + /** Adds a symbol to style and takes symbol's ownership + * + * \note Adding a symbol with the name of existing one replaces it. + * \param name is the name of the symbol being added or updated + * \param symbol is the Vector symbol + * \param update set to true when the style DB has to be updated, by default it is false + * \return success status of the operation + */ + bool addSymbol( const QString& name, QgsSymbol* symbol, bool update = false ); /** Adds a color ramp to the style. Calling this method takes the ramp's ownership. * \note Adding a color ramp with the name of existing one replaces it. @@ -91,49 +98,29 @@ class CORE_EXPORT QgsStyle : public QObject */ bool addColorRamp( const QString& name, QgsColorRamp* colorRamp, bool update = false ); - //! adds a new group and returns the group's id - /*! - * \param groupName the name of the new group as QString - * \param parent is the id of the parent group when a subgrouo is to be created. By default it is 0 indicating it is not a sub-group - * \return returns an int, which is the DB id of the new group created, 0 if the group couldn't be created + /** Adds a new tag and returns the tag's id + * + * \param tagName the name of the new tag to be created + * \return returns an int, which is the DB id of the new tag created, 0 if the tag couldn't be created */ - int addGroup( const QString& groupName, int parent = 0 ); + int addTag( const QString& tagName ); - //! adds new smartgroup to the database and returns the id - /*! + /** Adds a new smartgroup to the database and returns the id + * * \param name is the name of the new Smart Group to be added * \param op is the operator between the conditions; AND/OR as QString * \param conditions are the smart group conditions */ int addSmartgroup( const QString& name, const QString& op, const QgsSmartConditionMap& conditions ); - //! add symbol to style. takes symbol's ownership - /*! - * \note Adding a symbol with the name of existing one replaces it. - * \param name is the name of the symbol being added or updated - * \param symbol is the Vector symbol - * \param update set to true when the style DB has to be updated, by default it is false - * \return success status of the operation - */ - bool addSymbol( const QString& name, QgsSymbol* symbol, bool update = false ); - - //! adds a new tag and returns the tag's id - /*! - * \param tagName the name of the new tag to be created - * \return returns an int, which is the DB id of the new tag created, 0 if the tag couldn't be created - */ - int addTag( const QString& tagName ); - /** Returns a list of all tags in the style database + * * @note added in QGIS 2.16 * @see addTag() */ QStringList tags() const; - //! return a map of groupid and names for the given parent group - QgsSymbolGroupMap childGroupNames( const QString& parent = "" ); - - //! remove all contents of the style + //! Removes all contents of the style void clear(); /** Returns a new copy of the specified color ramp. The caller @@ -141,24 +128,25 @@ class CORE_EXPORT QgsStyle : public QObject */ QgsColorRamp* colorRamp( const QString& name ) const; - //! return count of color ramps + //! Returns count of color ramps int colorRampCount(); - //! return a list of names of color ramps + //! Returns a list of names of color ramps QStringList colorRampNames(); - //! return a const pointer to a symbol (doesn't create new instance) + //! Returns a const pointer to a symbol (doesn't create new instance) const QgsColorRamp* colorRampRef( const QString& name ) const; - //! return the id in the style database for the given colorramp name - //! returns 0 if not found + /** Returns the id in the style database for the given colorramp name + * returns 0 if not found + */ int colorrampId( const QString& name ); - //! return default application-wide style + //! Returns default application-wide style static QgsStyle* defaultStyle(); - //! tags the symbol with the tags in the list - /*! + /** Tags the symbol with the tags in the list + * * Applies the given tags to the given symbol or colorramp * \param type is either SymbolEntity or ColorrampEntity * \param symbol is the name of the symbol or colorramp as QString @@ -167,8 +155,8 @@ class CORE_EXPORT QgsStyle : public QObject */ bool tagSymbol( StyleEntity type, const QString& symbol, const QStringList& tags ); - //! detags the symbol with the given list - /*! + /** Detags the symbol with the given list + * * Removes the given tags for the specified symbol or colorramp * \param type is either SymbolEntity or ColorrampEntity * \param symbol is the name of the symbol or colorramp @@ -177,150 +165,157 @@ class CORE_EXPORT QgsStyle : public QObject */ bool detagSymbol( StyleEntity type, const QString& symbol, const QStringList& tags ); - //! remove symbol from style (and delete it) + /** Clears the symbol from all attached tags + * + * Removes all tags for the specified symbol or colorramp + * \param type is either SymbolEntity or ColorrampEntity + * \param symbol is the name of the symbol or colorramp + * \return returns the success state of the operation + */ + bool detagSymbol( StyleEntity type, const QString& symbol ); + + //! Removes symbol from style (and delete it) bool removeSymbol( const QString& name ); - //! change symbol's name + //! Changessymbol's name bool renameSymbol( const QString& oldName, const QString& newName ); - //! return a NEW copy of symbol + //! Returns a NEW copy of symbol QgsSymbol* symbol( const QString& name ); - //! return a const pointer to a symbol (doesn't create new instance) + //! Returns a const pointer to a symbol (doesn't create new instance) const QgsSymbol* symbolRef( const QString& name ) const; - //! return count of symbols in style + //! Returns count of symbols in style int symbolCount(); - //! return a list of names of symbols + //! Returns a list of names of symbols QStringList symbolNames(); - //! return the id in the style database for the given symbol name - //! returns 0 if not found + /** Returns the id in the style database for the given symbol name + * returns 0 if not found + */ int symbolId( const QString& name ); - //! return the DB id for the given group name - int groupId( const QString& group ); - //! return the group name for the given DB id - QString groupName( int groupId ) const; - //! return the DB id for the given tag name + //! Returns the DB id for the given tag name int tagId( const QString& tag ); - //! return the DB id for the given smartgroup name + //! Returns the DB id for the given smartgroup name int smartgroupId( const QString& smartgroup ); - //! return the all the groups in the style - QStringList groupNames(); - - //! return the ids of all the groups in the style - QList groupIds() const; - - //! returns the symbolnames of a given groupid - /*! + /** Returns the symbol names which are flagged as favorite + * * \param type is either SymbolEntity or ColorampEntity - * \param groupid is id of the group to which the symbols belong to, as int - * \return A QStringList of the symbol or colorramp names for the given group id + * \return A QStringList of the symbol or colorramp names flagged as favorite */ - QStringList symbolsOfGroup( StyleEntity type, int groupid ); + QStringList symbolsOfFavorite( StyleEntity type ) const; - //! returns the symbol names with which have the given tag - /*! + /** Returns the symbol names with which have the given tag + * * \param type is either SymbolEntity or ColorampEntity * \param tagid is id of the tag which has been applied over the symbol as int * \return A QStringList of the symbol or colorramp names for the given tag id */ - QStringList symbolsWithTag( StyleEntity type, int tagid ); + QStringList symbolsWithTag( StyleEntity type, int tagid ) const; + + /** Adds the specified symbol to favorites + * + * \param type is either SymbolEntity of ColorrampEntity + * \param name is the name of the symbol or coloramp whose is to be added to favorites + * \return returns the success state as bool + */ + bool addFavorite( StyleEntity type, const QString& name ); - //! applies the specified group to the symbol or colorramp specified by StyleEntity - /*! + /** Removes the specified symbol from favorites + * * \param type is either SymbolEntity of ColorrampEntity - * \param name is the name of the symbol or coloramp whose group is to be set - * \param groupid is the id of the group to which the entity is assigned + * \param name is the name of the symbol or coloramp whose is to be removed from favorites * \return returns the success state as bool */ - bool group( StyleEntity type, const QString& name, int groupid ); + bool removeFavorite( StyleEntity type, const QString& name ); - //! rename the given entity with the specified id - /*! + /** Renames the given entity with the specified id + * * \param type is any of the style entites. Refer enum StyleEntity. * \param id is the DB id of the entity which is to be renamed * \param newName is the new name of the entity */ void rename( StyleEntity type, int id, const QString& newName ); - //! remove the specified entity from the db - /*! + /** Removes the specified entity from the db + * * \param type is any of the style entites. Refer enum StyleEntity. * \param id is the DB id of the entity to be removed */ void remove( StyleEntity type, int id ); - //! add the symbol to the DB with the tags - /*! + /** Adds the symbol to the DB with the tags + * * \param name is the name of the symbol as QString * \param symbol is the pointer to the new QgsSymbol being saved - * \param groupid is the id of the group to which the symbol belongs. Pass 0 if it doesn't belong to any group or not known. + * \param favorite is a boolean value to specify whether the symbol should be added to favorites * \param tags is a list of tags that are associated with the symbol as a QStringList. * \return returns the success state of the save operation */ - bool saveSymbol( const QString& name, QgsSymbol* symbol, int groupid, const QStringList& tags ); + bool saveSymbol( const QString& name, QgsSymbol* symbol, bool favorite, const QStringList& tags ); - //! add the colorramp to the DB - /*! + /** Adds the colorramp to the DB + * * \param name is the name of the colorramp as QString * \param ramp is the pointer to the new QgsColorRamp being saved - * \param groupid is the id of the group to which the Color Ramp belongs. Pass 0 if it doesn't belong to any group or not known. + * \param favorite is a boolean value to specify whether the colorramp should be added to favorites * \param tags is a list of tags that are associated with the color ramp as a QStringList. * \return returns the success state of the save operation */ - bool saveColorRamp( const QString& name, QgsColorRamp* ramp, int groupid, const QStringList& tags ); + bool saveColorRamp( const QString& name, QgsColorRamp* ramp, bool favorite, const QStringList& tags ); - //! remove color ramp from style (and delete it) + //! Removes color ramp from style (and delete it) bool removeColorRamp( const QString& name ); - //! change ramp's name + //! Changes ramp's name bool renameColorRamp( const QString& oldName, const QString& newName ); - //! load a file into the style + //! Loads a file into the style bool load( const QString& filename ); - //! save style into a file (will use current filename if empty string is passed) + //! Saves style into a file (will use current filename if empty string is passed) bool save( QString filename = QString() ); - //! return last error from load/save operation + //! Returns last error from load/save operation QString errorString() { return mErrorString; } - //! return current file name of the style + //! Returns current file name of the style QString fileName() { return mFileName; } - //! return the names of the symbols which have a matching 'substring' in its defintion - /*! + /** Returns the names of the symbols which have a matching 'substring' in its defintion + * * \param type is either SymbolEntity or ColorrampEntity * \param qword is the query string to search the symbols or colorramps. * \return A QStringList of the matched symbols or colorramps * */ QStringList findSymbols( StyleEntity type, const QString& qword ); - //! return the tags associated with the symbol - /*! + /** Returns the tags associated with the symbol + * * \param type is either SymbolEntity or ColorrampEntity * \param symbol is the name of the symbol or color ramp * \return A QStringList of the tags that have been applied to that symbol/colorramp */ QStringList tagsOfSymbol( StyleEntity type, const QString& symbol ); - //! returns the smart groups map with id as key and name as value + //! Returns the smart groups map with id as key and name as value QgsSymbolGroupMap smartgroupsListMap(); - //! returns the smart groups list + //! Returns the smart groups list QStringList smartgroupNames(); - //! returns the QgsSmartConditionMap for the given id + //! Returns the QgsSmartConditionMap for the given id QgsSmartConditionMap smartgroup( int id ); - //! returns the operator for the smartgroup - //clumsy implementation TODO create a class for smartgroups + /** Returns the operator for the smartgroup + * clumsy implementation TODO create a class for smartgroups + */ QString smartgroupOperator( int id ); - //! returns the symbols for the smartgroup + //! Returns the symbols for the smartgroup QStringList symbolsOfSmartgroup( StyleEntity type, int id ); //! Exports the style as a XML file @@ -330,7 +325,10 @@ class CORE_EXPORT QgsStyle : public QObject bool importXml( const QString& filename ); signals: + //! Is emitted every time a new symbol has been added to the database void symbolSaved( const QString& name, QgsSymbol* symbol ); + //! Is emitted every time a tag or smartgroup has been added, removed, or renamed + void groupsModified(); protected: @@ -344,26 +342,25 @@ class CORE_EXPORT QgsStyle : public QObject static QgsStyle* mDefaultStyle; - //! convenience function to open the DB and return a sqlite3 object + //! Convenience function to open the DB and return a sqlite3 object bool openDB( const QString& filename ); - //! convenience function that would run queries which don't generate return values - //! \param query query to run - //! \param freeQuery release query memory - //! \return success true on success + /** Convenience function that would run queries which don't generate return values + * + * \param query query to run + * \param freeQuery release query memory + * \return success true on success + */ bool runEmptyQuery( char* query, bool freeQuery = true ); - //! prepares the complex query for removing a group, so that the children are not abandoned - char* getGroupRemoveQuery( int id ); - - //! gets the id from the table for the given name from the database, 0 if not found + //! Gets the id from the table for the given name from the database, 0 if not found int getId( const QString& table, const QString& name ); - //! gets the name from the table for the given id from the database, empty if not found + //! Gets the name from the table for the given id from the database, empty if not found QString getName( const QString& table, int id ) const; - //! updates the properties of an existing symbol/colorramp - /*! + /** Updates the properties of an existing symbol/colorramp + * * \note This should not be called separately, only called through addSymbol or addColorRamp * \param type is either SymbolEntity or ColorrampEntity * \param name is the name of an existing symbol or a color ramp diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index fe02b7cade1a..4f91772b43c1 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -38,6 +38,7 @@ SET(QGIS_GUI_SRCS symbology-ng/qgsstyleexportimportdialog.cpp symbology-ng/qgsstylegroupselectiondialog.cpp symbology-ng/qgsstylemanagerdialog.cpp + symbology-ng/qgsstylesavedialog.cpp symbology-ng/qgssvgselectorwidget.cpp symbology-ng/qgssymbollayerwidget.cpp symbology-ng/qgssymbollevelsdialog.cpp @@ -511,6 +512,7 @@ SET(QGIS_GUI_MOC_HDRS symbology-ng/qgsstyleexportimportdialog.h symbology-ng/qgsstylegroupselectiondialog.h symbology-ng/qgsstylemanagerdialog.h + symbology-ng/qgsstylesavedialog.h symbology-ng/qgssvgselectorwidget.h symbology-ng/qgssymbollayerwidget.h symbology-ng/qgssymbollevelsdialog.h diff --git a/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp b/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp index 7f60c0d5ac48..55a895c47887 100644 --- a/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp +++ b/src/gui/symbology-ng/qgssmartgroupeditordialog.cpp @@ -31,10 +31,8 @@ QgsSmartGroupCondition::QgsSmartGroupCondition( int id, QWidget* parent ) : QWid mConditionId = id; mCondCombo->addItem( tr( "has the tag" ), QVariant( "tag" ) ); - mCondCombo->addItem( tr( "is a member of group" ), QVariant( "group" ) ); mCondCombo->addItem( tr( "has a part of name matching" ), QVariant( "name" ) ); mCondCombo->addItem( tr( "does NOT have the tag" ), QVariant( "!tag" ) ); - mCondCombo->addItem( tr( "is NOT a member of group" ), QVariant( "!group" ) ); mCondCombo->addItem( tr( "has NO part of name matching" ), QVariant( "!name" ) ); mRemoveBtn->setIcon( QIcon( QgsApplication::iconPath( "symbologyRemove.svg" ) ) ); @@ -159,7 +157,7 @@ QString QgsSmartGroupEditorDialog::conditionOperator() void QgsSmartGroupEditorDialog::setConditionMap( const QgsSmartConditionMap& map ) { QStringList constraints; - constraints << QStringLiteral( "tag" ) << QStringLiteral( "group" ) << QStringLiteral( "name" ) << QStringLiteral( "!tag" ) << QStringLiteral( "!group" ) << QStringLiteral( "!name" ); + constraints << QStringLiteral( "tag" ) << QStringLiteral( "name" ) << QStringLiteral( "!tag" ) << QStringLiteral( "!name" ); // clear any defaults Q_FOREACH ( int id, mConditionMap.keys() ) diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp index eb2792cc30fc..8e3a96127aeb 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp @@ -35,7 +35,7 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget *parent, Mode mode ) : QDialog( parent ) , mDialogMode( mode ) - , mQgisStyle( style ) + , mStyle( style ) { setupUi( this ); @@ -73,12 +73,7 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget importTypeCombo->addItem( tr( "URL specified below" ), QVariant( "url" ) ); connect( importTypeCombo, SIGNAL( currentIndexChanged( int ) ), this, SLOT( importTypeChanged( int ) ) ); - QStringList groups = mQgisStyle->groupNames(); - groupCombo->addItem( QStringLiteral( "imported" ), QVariant( "new" ) ); - Q_FOREACH ( const QString& gName, groups ) - { - groupCombo->addItem( gName ); - } + mSymbolTags->setText( "imported" ); btnBrowse->setText( QStringLiteral( "Browse" ) ); connect( btnBrowse, SIGNAL( clicked() ), this, SLOT( browse() ) ); @@ -96,14 +91,17 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget locationLabel->setHidden( true ); locationLineEdit->setHidden( true ); + mFavorite->setHidden( true ); + pb = new QPushButton( tr( "Select by group" ) ); buttonBox->addButton( pb, QDialogButtonBox::ActionRole ); connect( pb, SIGNAL( clicked() ), this, SLOT( selectByGroup() ) ); - groupLabel->setHidden( true ); - groupCombo->setHidden( true ); + tagLabel->setHidden( true ); + mSymbolTags->setHidden( true ); + tagHintLabel->setHidden( true ); buttonBox->button( QDialogButtonBox::Ok )->setText( tr( "Export" ) ); - if ( !populateStyles( mQgisStyle ) ) + if ( !populateStyles( mStyle ) ) { QApplication::postEvent( this, new QCloseEvent() ); } @@ -142,7 +140,7 @@ void QgsStyleExportImportDialog::doExportImport() mFileName = fileName; - moveStyles( &selection, mQgisStyle, mTempStyle ); + moveStyles( &selection, mStyle, mTempStyle ); if ( !mTempStyle->exportXml( mFileName ) ) { QMessageBox::warning( this, tr( "Export/import error" ), @@ -153,7 +151,7 @@ void QgsStyleExportImportDialog::doExportImport() } else // import { - moveStyles( &selection, mTempStyle, mQgisStyle ); + moveStyles( &selection, mTempStyle, mStyle ); // clear model QStandardItemModel* model = qobject_cast( listItems->model() ); @@ -222,26 +220,13 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl bool isSymbol = true; bool prompt = true; bool overwrite = true; - int groupid = 0; + QStringList tags; // get the groupid when going for import if ( mDialogMode == Import ) { // get the name the user entered - QString name = groupCombo->currentText(); - if ( name.isEmpty() ) - { - // import to "ungrouped" - groupid = 0; - } - else if ( dst->groupNames().contains( name ) ) - { - groupid = dst->groupId( name ); - } - else - { - groupid = dst->addGroup( name ); - } + tags = mSymbolTags->text().split( ',' ); } for ( int i = 0; i < selection->size(); ++i ) @@ -272,7 +257,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl case QMessageBox::Yes: dst->addSymbol( symbolName, symbol ); if ( mDialogMode == Import ) - dst->saveSymbol( symbolName, symbol, groupid, QStringList() ); + dst->saveSymbol( symbolName, symbol, mFavorite->isChecked(), tags ); continue; case QMessageBox::YesToAll: prompt = false; @@ -289,7 +274,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl { dst->addSymbol( symbolName, symbol ); if ( mDialogMode == Import ) - dst->saveSymbol( symbolName, symbol, groupid, QStringList() ); + dst->saveSymbol( symbolName, symbol, mFavorite->isChecked(), tags ); } else if ( dst->symbolNames().contains( symbolName ) && !overwrite ) { @@ -299,7 +284,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl { dst->addSymbol( symbolName, symbol ); if ( mDialogMode == Import ) - dst->saveSymbol( symbolName, symbol, groupid, QStringList() ); + dst->saveSymbol( symbolName, symbol, mFavorite->isChecked(), tags ); } } else @@ -319,7 +304,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl case QMessageBox::Yes: dst->addColorRamp( symbolName, ramp ); if ( mDialogMode == Import ) - dst->saveColorRamp( symbolName, ramp, groupid, QStringList() ); + dst->saveColorRamp( symbolName, ramp, mFavorite->isChecked(), tags ); continue; case QMessageBox::YesToAll: prompt = false; @@ -336,7 +321,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl { dst->addColorRamp( symbolName, ramp ); if ( mDialogMode == Import ) - dst->saveColorRamp( symbolName, ramp, groupid, QStringList() ); + dst->saveColorRamp( symbolName, ramp, mFavorite->isChecked(), tags ); } else if ( dst->colorRampNames().contains( symbolName ) && !overwrite ) { @@ -346,7 +331,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl { dst->addColorRamp( symbolName, ramp ); if ( mDialogMode == Import ) - dst->saveColorRamp( symbolName, ramp, groupid, QStringList() ); + dst->saveColorRamp( symbolName, ramp, mFavorite->isChecked() , tags ); } } } @@ -394,36 +379,31 @@ void QgsStyleExportImportDialog::deselectSymbols( const QStringList& symbolNames } } -void QgsStyleExportImportDialog::selectGroup( const QString& groupName ) +void QgsStyleExportImportDialog::selectTag( const QString& tagName ) { - QStringList symbolNames = mQgisStyle->symbolsOfGroup( QgsStyle::SymbolEntity, mQgisStyle->groupId( groupName ) ); - selectSymbols( symbolNames ); - symbolNames = mQgisStyle->symbolsOfGroup( QgsStyle::ColorrampEntity, mQgisStyle->groupId( groupName ) ); + QStringList symbolNames = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( tagName ) ); selectSymbols( symbolNames ); } - -void QgsStyleExportImportDialog::deselectGroup( const QString& groupName ) +void QgsStyleExportImportDialog::deselectTag( const QString& tagName ) { - QStringList symbolNames = mQgisStyle->symbolsOfGroup( QgsStyle::SymbolEntity, mQgisStyle->groupId( groupName ) ); - deselectSymbols( symbolNames ); - symbolNames = mQgisStyle->symbolsOfGroup( QgsStyle::ColorrampEntity, mQgisStyle->groupId( groupName ) ); + QStringList symbolNames = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, mStyle->tagId( tagName ) ); deselectSymbols( symbolNames ); } void QgsStyleExportImportDialog::selectSmartgroup( const QString& groupName ) { - QStringList symbolNames = mQgisStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mQgisStyle->smartgroupId( groupName ) ); + QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) ); selectSymbols( symbolNames ); - symbolNames = mQgisStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mQgisStyle->smartgroupId( groupName ) ); + symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) ); selectSymbols( symbolNames ); } void QgsStyleExportImportDialog::deselectSmartgroup( const QString& groupName ) { - QStringList symbolNames = mQgisStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mQgisStyle->smartgroupId( groupName ) ); + QStringList symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, mStyle->smartgroupId( groupName ) ); deselectSymbols( symbolNames ); - symbolNames = mQgisStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mQgisStyle->smartgroupId( groupName ) ); + symbolNames = mStyle->symbolsOfSmartgroup( QgsStyle::ColorrampEntity, mStyle->smartgroupId( groupName ) ); deselectSymbols( symbolNames ); } @@ -431,10 +411,10 @@ void QgsStyleExportImportDialog::selectByGroup() { if ( ! mGroupSelectionDlg ) { - mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mQgisStyle, this ); + mGroupSelectionDlg = new QgsStyleGroupSelectionDialog( mStyle, this ); mGroupSelectionDlg->setWindowTitle( tr( "Select symbols by group" ) ); - connect( mGroupSelectionDlg, SIGNAL( groupSelected( const QString ) ), this, SLOT( selectGroup( const QString ) ) ); - connect( mGroupSelectionDlg, SIGNAL( groupDeselected( const QString ) ), this, SLOT( deselectGroup( const QString ) ) ); + connect( mGroupSelectionDlg, SIGNAL( tagSelected( const QString ) ), this, SLOT( selectTag( const QString ) ) ); + connect( mGroupSelectionDlg, SIGNAL( tagDeselected( const QString ) ), this, SLOT( deselectTag( const QString ) ) ); connect( mGroupSelectionDlg, SIGNAL( allSelected() ), this, SLOT( selectAll() ) ); connect( mGroupSelectionDlg, SIGNAL( allDeselected() ), this, SLOT( clearSelection() ) ); connect( mGroupSelectionDlg, SIGNAL( smartgroupSelected( const QString ) ), this, SLOT( selectSmartgroup( const QString ) ) ); @@ -481,8 +461,8 @@ void QgsStyleExportImportDialog::browse() return; } QFileInfo pathInfo( mFileName ); - QString groupName = pathInfo.fileName().remove( QStringLiteral( ".xml" ) ); - groupCombo->setItemText( 0, groupName ); + QString tag = pathInfo.fileName().remove( QStringLiteral( ".xml" ) ); + mSymbolTags->setText( tag ); locationLineEdit->setText( mFileName ); populateStyles( mTempStyle ); } diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.h b/src/gui/symbology-ng/qgsstyleexportimportdialog.h index 7ad6ecd27183..007e35123c98 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.h +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.h @@ -80,16 +80,16 @@ class GUI_EXPORT QgsStyleExportImportDialog : public QDialog, private Ui::QgsSty void clearSelection(); /** - * Select the symbols belonging to the given group - * @param groupName the name of the group to be selected + * Select the symbols belonging to the given tag + * @param tagName the name of the group to be selected */ - void selectGroup( const QString& groupName ); + void selectTag( const QString& tagName ); /** - * Deselect the symbols belonging to the given group - * @param groupName the name of the group to be deselected + * Deselect the symbols belonging to the given tag + * @param tagName the name of the group to be deselected */ - void deselectGroup( const QString& groupName ); + void deselectTag( const QString& tagName ); /** * @brief selectSmartgroup selects all symbols from a smart group @@ -127,7 +127,7 @@ class GUI_EXPORT QgsStyleExportImportDialog : public QDialog, private Ui::QgsSty QString mFileName; Mode mDialogMode; - QgsStyle* mQgisStyle; + QgsStyle* mStyle; QgsStyle* mTempStyle; }; diff --git a/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp b/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp index 2b8a95d2281c..ae15608f8e89 100644 --- a/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp +++ b/src/gui/symbology-ng/qgsstylegroupselectiondialog.cpp @@ -37,24 +37,19 @@ QgsStyleGroupSelectionDialog::QgsStyleGroupSelectionDialog( QgsStyle *style, QWi setBold( allSymbols ); model->appendRow( allSymbols ); - QStandardItem *group = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups - group->setData( "groupsheader", Qt::UserRole + 2 ); - group->setEditable( false ); - group->setFlags( group->flags() & ~Qt::ItemIsSelectable ); - buildGroupTree( group ); - group->setText( tr( "Groups" ) );//set title later - QStandardItem *ungrouped = new QStandardItem( tr( "Ungrouped" ) ); - ungrouped->setData( 0 ); - ungrouped->setData( "group", Qt::UserRole + 2 ); - setBold( ungrouped ); - setBold( group ); - group->appendRow( ungrouped ); - model->appendRow( group ); + QStandardItem *tags = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups + tags->setData( "tagsheader", Qt::UserRole + 2 ); + tags->setEditable( false ); + tags->setFlags( tags->flags() & ~Qt::ItemIsSelectable ); + buildTagTree( tags ); + tags->setText( tr( "Tags" ) );//set title later + setBold( tags ); + model->appendRow( tags ); QStandardItem *tag = new QStandardItem( tr( "Smart Groups" ) ); tag->setData( "smartgroupsheader" , Qt::UserRole + 2 ); tag->setEditable( false ); - tag->setFlags( group->flags() & ~Qt::ItemIsSelectable ); + tag->setFlags( tag->flags() & ~Qt::ItemIsSelectable ); setBold( tag ); QgsSymbolGroupMap sgMap = mStyle->smartgroupsListMap(); QgsSymbolGroupMap::const_iterator i = sgMap.constBegin(); @@ -100,7 +95,7 @@ void QgsStyleGroupSelectionDialog::groupTreeSelectionChanged( const QItemSelecti Q_FOREACH ( index, deselectedItems ) { - if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "groupsheader" ) ) + if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "tagssheader" ) ) { // Ignore: it's the group header } @@ -116,14 +111,14 @@ void QgsStyleGroupSelectionDialog::groupTreeSelectionChanged( const QItemSelecti { emit smartgroupDeselected( index.data().toString() ); } - else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "group" ) ) - { // It's a group - emit groupDeselected( index.data().toString() ); + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "tag" ) ) + { // It's a tag + emit tagDeselected( index.data().toString() ); } } Q_FOREACH ( index, selectedItems ) { - if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "groupsheader" ) ) + if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "tagssheader" ) ) { // Ignore: it's the group header } @@ -139,27 +134,25 @@ void QgsStyleGroupSelectionDialog::groupTreeSelectionChanged( const QItemSelecti { emit smartgroupSelected( index.data().toString() ); } - else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "group" ) ) - { // It's a group - emit groupSelected( index.data().toString() ); + else if ( index.data( Qt::UserRole + 2 ).toString() == QLatin1String( "tag" ) ) + { // It's a tag + emit tagSelected( index.data().toString() ); } } } -void QgsStyleGroupSelectionDialog::buildGroupTree( QStandardItem* &parent ) +void QgsStyleGroupSelectionDialog::buildTagTree( QStandardItem* &parent ) { - QgsSymbolGroupMap groups = mStyle->childGroupNames( parent->text() ); - QgsSymbolGroupMap::const_iterator i = groups.constBegin(); - while ( i != groups.constEnd() ) + QStringList tags = mStyle->tags(); + tags.sort(); + Q_FOREACH ( const QString& tag, tags ) { - QStandardItem *item = new QStandardItem( i.value() ); - item->setData( i.key() ); - item->setData( "group" , Qt::UserRole + 2 ); + QStandardItem *item = new QStandardItem( tag ); + item->setData( mStyle->tagId( tag ) ); + item->setData( "tag" , Qt::UserRole + 2 ); item->setEditable( false ); parent->appendRow( item ); - buildGroupTree( item ); - ++i; } } diff --git a/src/gui/symbology-ng/qgsstylegroupselectiondialog.h b/src/gui/symbology-ng/qgsstylegroupselectiondialog.h index ec370dbbc754..988efaddcc12 100644 --- a/src/gui/symbology-ng/qgsstylegroupselectiondialog.h +++ b/src/gui/symbology-ng/qgsstylegroupselectiondialog.h @@ -38,10 +38,10 @@ class GUI_EXPORT QgsStyleGroupSelectionDialog : public QDialog, private Ui::Symb void setBold( QStandardItem *item ); signals: - //! group with groupName has been selected - void groupSelected( const QString& groupName ); - //! group with groupName has been deselected - void groupDeselected( const QString& groupName ); + //! tag with tagName has been selected + void tagSelected( const QString& tagName ); + //! tag with tagName has been deselected + void tagDeselected( const QString& tagName ); //! smartgroup with groupName has been selected void smartgroupSelected( const QString& groupName ); //! smart group with groupName has been deselected @@ -60,7 +60,7 @@ class GUI_EXPORT QgsStyleGroupSelectionDialog : public QDialog, private Ui::Symb * @brief build group tree * @param parent */ - void buildGroupTree( QStandardItem *&parent ); + void buildTagTree( QStandardItem *&parent ); QgsStyle* mStyle; }; diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp index f9ad62764a55..ecb8be3d62dd 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp @@ -14,6 +14,7 @@ ***************************************************************************/ #include "qgsstylemanagerdialog.h" +#include "qgsstylesavedialog.h" #include "qgsstyle.h" #include "qgssymbol.h" @@ -111,16 +112,15 @@ QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle* style, QWidget* parent ) this, SLOT( groupRenamed( QStandardItem* ) ) ); QMenu *groupMenu = new QMenu( tr( "Group actions" ), this ); - connect( actnGroupSymbols, SIGNAL( triggered() ), this, SLOT( groupSymbolsAction() ) ); - groupMenu->addAction( actnGroupSymbols ); - connect( actnFinishGrouping, SIGNAL( triggered() ), this, SLOT( groupSymbolsAction() ) ); - actnFinishGrouping->setVisible( false ); - groupMenu->addAction( actnFinishGrouping ); + connect( actnTagSymbols, SIGNAL( triggered() ), this, SLOT( tagSymbolsAction() ) ); + groupMenu->addAction( actnTagSymbols ); + connect( actnFinishTagging, SIGNAL( triggered() ), this, SLOT( tagSymbolsAction() ) ); + actnFinishTagging->setVisible( false ); + groupMenu->addAction( actnFinishTagging ); groupMenu->addAction( actnEditSmartGroup ); btnManageGroups->setMenu( groupMenu ); connect( searchBox, SIGNAL( textChanged( QString ) ), this, SLOT( filterSymbols( QString ) ) ); - tagsLineEdit->installEventFilter( this ); // Context menu for groupTree groupTree->setContextMenuPolicy( Qt::CustomContextMenu ); @@ -144,13 +144,18 @@ QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle* style, QWidget* parent ) // Context menu for symbols/colorramps. The menu entries for every group are created when displaying the menu. mGroupMenu = new QMenu( this ); + connect( actnAddFavorite, SIGNAL( triggered( bool ) ), this, SLOT( addFavoriteSelectedSymbols() ) ); + mGroupMenu->addAction( actnAddFavorite ); + connect( actnRemoveFavorite, SIGNAL( triggered( bool ) ), this, SLOT( removeFavoriteSelectedSymbols() ) ); + mGroupMenu->addAction( actnRemoveFavorite ); + mGroupMenu->addSeparator()->setParent( this ); mGroupListMenu = new QMenu( mGroupMenu ); - mGroupListMenu->setTitle( tr( "Add to group" ) ); + mGroupListMenu->setTitle( tr( "Add to tag" ) ); mGroupListMenu->setEnabled( false ); mGroupMenu->addMenu( mGroupListMenu ); - actnUngroup->setData( 0 ); - connect( actnUngroup, SIGNAL( triggered( bool ) ), this, SLOT( groupSelectedSymbols() ) ); - mGroupMenu->addAction( actnUngroup ); + actnDetag->setData( 0 ); + connect( actnDetag, SIGNAL( triggered( bool ) ), this, SLOT( detagSelectedSymbols() ) ); + mGroupMenu->addAction( actnDetag ); mGroupMenu->addSeparator()->setParent( this ); mGroupMenu->addAction( actnRemoveItem ); mGroupMenu->addAction( actnEditItem ); @@ -391,20 +396,19 @@ bool QgsStyleManagerDialog::addSymbol() return false; } - // get unique name - bool nameInvalid = true; + QgsStyleSaveDialog saveDlg( this ); + if ( !saveDlg.exec() ) + { + delete symbol; + return false; + } + name = saveDlg.name(); + + // request valid/unique name + bool nameInvalid = true; while ( nameInvalid ) { - bool ok; - name = QInputDialog::getText( this, tr( "Symbol Name" ), - tr( "Please enter a name for new symbol:" ), - QLineEdit::Normal, name, &ok ); - if ( !ok ) - { - delete symbol; - return false; - } // validate name if ( name.isEmpty() ) { @@ -419,6 +423,7 @@ bool QgsStyleManagerDialog::addSymbol() QMessageBox::Yes | QMessageBox::No ); if ( res == QMessageBox::Yes ) { + mStyle->removeSymbol( name ); nameInvalid = false; } } @@ -427,11 +432,26 @@ bool QgsStyleManagerDialog::addSymbol() // valid name nameInvalid = false; } + if ( nameInvalid ) + { + bool ok; + name = QInputDialog::getText( this, tr( "Symbol Name" ), + tr( "Please enter a name for new symbol:" ), + QLineEdit::Normal, name, &ok ); + if ( !ok ) + { + delete symbol; + return false; + } + } } + QStringList symbolTags = saveDlg.tags().split( ',' ); + // add new symbol to style and re-populate the list - mStyle->addSymbol( name, symbol, true ); - // TODO groups and tags + mStyle->addSymbol( name, symbol ); + mStyle->saveSymbol( name, symbol, saveDlg.isFavorite(), symbolTags ); + mModified = true; return true; } @@ -521,19 +541,18 @@ QString QgsStyleManagerDialog::addColorRampStatic( QWidget* parent, QgsStyle* st return QString(); } - // get unique name - bool nameInvalid = true; + QgsStyleSaveDialog saveDlg( parent, QgsStyle::ColorrampEntity ); + if ( !saveDlg.exec() ) + { + return QString(); + } + + name = saveDlg.name(); + // get valid/unique name + bool nameInvalid = true; while ( nameInvalid ) { - bool ok; - name = QInputDialog::getText( parent, tr( "Color Ramp Name" ), - tr( "Please enter a name for new color ramp:" ), - QLineEdit::Normal, name, &ok ); - if ( !ok ) - { - return QString(); - } // validate name if ( name.isEmpty() ) { @@ -556,11 +575,26 @@ QString QgsStyleManagerDialog::addColorRampStatic( QWidget* parent, QgsStyle* st // valid name nameInvalid = false; } + if ( nameInvalid ) + { + bool ok; + name = QInputDialog::getText( parent, tr( "Color Ramp Name" ), + tr( "Please enter a name for new color ramp:" ), + QLineEdit::Normal, name, &ok ); + if ( !ok ) + { + return QString(); + } + } } + QStringList colorRampTags = saveDlg.tags().split( ',' ); + QgsColorRamp* r = ramp.take(); + // add new symbol to style and re-populate the list - style->addColorRamp( name, ramp.take(), true ); - // TODO groups and tags, using saveColorRamp + style->addColorRamp( name, r ); + style->saveColorRamp( name, r, saveDlg.isFavorite(), colorRampTags ); + return name; } @@ -854,40 +888,49 @@ void QgsStyleManagerDialog::populateGroups() QStandardItemModel *model = qobject_cast( groupTree->model() ); model->clear(); + QStandardItem *favoriteSymbols = new QStandardItem( tr( "Favorites" ) ); + favoriteSymbols->setData( "favorite" ); + favoriteSymbols->setEditable( false ); + setBold( favoriteSymbols ); + model->appendRow( favoriteSymbols ); + QStandardItem *allSymbols = new QStandardItem( tr( "All Symbols" ) ); allSymbols->setData( "all" ); allSymbols->setEditable( false ); setBold( allSymbols ); model->appendRow( allSymbols ); - QStandardItem *group = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups - group->setData( "groups" ); - group->setEditable( false ); - buildGroupTree( group ); - group->setText( tr( "Groups" ) );//set title later - QStandardItem *ungrouped = new QStandardItem( tr( "Ungrouped" ) ); - ungrouped->setData( 0 ); - setBold( ungrouped ); - setBold( group ); - group->appendRow( ungrouped ); - model->appendRow( group ); - - QStandardItem *tag = new QStandardItem( tr( "Smart Groups" ) ); - tag->setData( "smartgroups" ); - tag->setEditable( false ); - setBold( tag ); + QStandardItem *taggroup = new QStandardItem( QLatin1String( "" ) ); //require empty name to get first order groups + taggroup->setData( "tags" ); + taggroup->setEditable( false ); + QStringList tags = mStyle->tags(); + tags.sort(); + Q_FOREACH ( const QString& tag, tags ) + { + QStandardItem *item = new QStandardItem( tag ); + item->setData( mStyle->tagId( tag ) ); + taggroup->appendRow( item ); + } + taggroup->setText( tr( "Tags" ) );//set title later + setBold( taggroup ); + model->appendRow( taggroup ); + + QStandardItem *smart = new QStandardItem( tr( "Smart Groups" ) ); + smart->setData( "smartgroups" ); + smart->setEditable( false ); + setBold( smart ); QgsSymbolGroupMap sgMap = mStyle->smartgroupsListMap(); QgsSymbolGroupMap::const_iterator i = sgMap.constBegin(); while ( i != sgMap.constEnd() ) { QStandardItem *item = new QStandardItem( i.value() ); item->setData( i.key() ); - tag->appendRow( item ); + smart->appendRow( item ); ++i; } - model->appendRow( tag ); + model->appendRow( smart ); - // expand things in the grouo tree + // expand things in the group tree int rows = model->rowCount( model->indexFromItem( model->invisibleRootItem() ) ); for ( int i = 0; i < rows; i++ ) { @@ -895,20 +938,6 @@ void QgsStyleManagerDialog::populateGroups() } } -void QgsStyleManagerDialog::buildGroupTree( QStandardItem* &parent ) -{ - QgsSymbolGroupMap groups = mStyle->childGroupNames( parent->text() ); - QgsSymbolGroupMap::const_iterator i = groups.constBegin(); - while ( i != groups.constEnd() ) - { - QStandardItem *item = new QStandardItem( i.value() ); - item->setData( i.key() ); - parent->appendRow( item ); - buildGroupTree( item ); - ++i; - } -} - void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) { QStringList symbolNames; @@ -922,42 +951,41 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) } QString category = index.data( Qt::UserRole + 1 ).toString(); - if ( category == QLatin1String( "all" ) || category == QLatin1String( "groups" ) || category == QLatin1String( "smartgroups" ) ) + if ( category == QLatin1String( "all" ) || category == QLatin1String( "tags" ) || category == QLatin1String( "smartgroups" ) ) { enableGroupInputs( false ); - if ( category == QLatin1String( "groups" ) || category == QLatin1String( "smartgroups" ) ) + if ( category == QLatin1String( "tags" ) || category == QLatin1String( "smartgroups" ) ) { btnAddGroup->setEnabled( true ); actnAddGroup->setEnabled( true ); } symbolNames = currentItemType() < 3 ? mStyle->symbolNames() : mStyle->colorRampNames(); } - else + else if ( category == QLatin1String( "favorite" ) ) { - //determine groups and tags - if ( index.parent().data( Qt::UserRole + 1 ) == "smartgroups" ) - { - btnAddGroup->setEnabled( false ); - actnAddGroup->setEnabled( false ); - btnRemoveGroup->setEnabled( true ); - actnRemoveGroup->setEnabled( true ); - btnManageGroups->setEnabled( true ); - int groupId = index.data( Qt::UserRole + 1 ).toInt(); - symbolNames = mStyle->symbolsOfSmartgroup( type, groupId ); - } - else // then it must be a group + btnAddGroup->setEnabled( true ); + actnAddGroup->setEnabled( true ); + enableGroupInputs( false ); + + symbolNames = mStyle->symbolsOfFavorite( type ); + } + else if ( index.parent().data( Qt::UserRole + 1 ) == "smartgroups" ) + { + btnRemoveGroup->setEnabled( true ); + actnRemoveGroup->setEnabled( true ); + btnManageGroups->setEnabled( true ); + int groupId = index.data( Qt::UserRole + 1 ).toInt(); + symbolNames = mStyle->symbolsOfSmartgroup( type, groupId ); + } + else // tags + { + enableGroupInputs( true ); + int tagId = index.data( Qt::UserRole + 1 ).toInt(); + symbolNames = mStyle->symbolsWithTag( type, tagId ); + if ( mGrouppingMode && tagId ) { - if (( !index.data( Qt::UserRole + 1 ).toInt() && ( index.data() == "Ungrouped" ) ) || mGrouppingMode ) - enableGroupInputs( false ); - else - enableGroupInputs( true ); - int groupId = index.data( Qt::UserRole + 1 ).toInt(); - symbolNames = mStyle->symbolsOfGroup( type, groupId ); - if ( mGrouppingMode && groupId ) - { - groupSymbols = symbolNames; - symbolNames += mStyle->symbolsOfGroup( type, 0 ); - } + groupSymbols = symbolNames; + symbolNames = type == QgsStyle::SymbolEntity ? mStyle->symbolNames() : mStyle->colorRampNames(); } } @@ -969,16 +997,19 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) { populateColorRamps( symbolNames, mGrouppingMode ); } + if ( mGrouppingMode ) + { setSymbolsChecked( groupSymbols ); + } actnEditSmartGroup->setVisible( false ); actnAddGroup->setVisible( false ); actnRemoveGroup->setVisible( false ); - actnGroupSymbols->setVisible( false ); - actnFinishGrouping->setVisible( false ); + actnTagSymbols->setVisible( false ); + actnFinishTagging->setVisible( false ); - if ( index.parent().isValid() && ( index.data().toString() != QLatin1String( "Ungrouped" ) ) ) + if ( index.parent().isValid() ) { if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) { @@ -987,12 +1018,12 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) else { actnAddGroup->setVisible( !mGrouppingMode ); - actnGroupSymbols->setVisible( !mGrouppingMode ); - actnFinishGrouping->setVisible( mGrouppingMode ); + actnTagSymbols->setVisible( !mGrouppingMode ); + actnFinishTagging->setVisible( mGrouppingMode ); } actnRemoveGroup->setVisible( true ); } - else if ( index.data( Qt::UserRole + 1 ) == "groups" || index.data( Qt::UserRole + 1 ) == "smartgroups" ) + else if ( index.data( Qt::UserRole + 1 ) == "tags" || index.data( Qt::UserRole + 1 ) == "smartgroups" ) { actnAddGroup->setVisible( !mGrouppingMode ); } @@ -1001,11 +1032,11 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) void QgsStyleManagerDialog::addGroup() { QStandardItemModel *model = qobject_cast( groupTree->model() ); - QModelIndex parentIndex = groupTree->currentIndex(); + QModelIndex index = groupTree->currentIndex(); - // Violation 1: Creating sub-groups of system defined groups - QString parentData = parentIndex.data( Qt::UserRole + 1 ).toString(); - if ( parentData == QLatin1String( "all" ) || ( parentIndex.data() == "Ungrouped" && parentData == QLatin1String( "0" ) ) ) + // don't allow creation of tag/smartgroup against system-defined groupings + QString data = index.data( Qt::UserRole + 1 ).toString(); + if ( data == QLatin1String( "all" ) || data == "favorite" ) { int err = QMessageBox::critical( this, tr( "Invalid Selection" ), tr( "The parent group you have selected is not user editable.\n" @@ -1014,24 +1045,19 @@ void QgsStyleManagerDialog::addGroup() return; } - // Violation 2: Creating a nested tag - if ( parentIndex.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "smartgroups" ) ) - { - int err = QMessageBox::critical( this, tr( "Operation Not Allowed" ), - tr( "Creation of nested smart groups are not allowed\n" - "Select the 'Smart Group' to create a new group." ) ); - if ( err ) - return; - } - QString itemName; - bool isGroup = true; - int id; - if ( parentData == QLatin1String( "smartgroups" ) ) + + // + if ( index.parent() != QModelIndex() ) { - // create a smart group + index = index.parent(); + data = index.data( Qt::UserRole + 1 ).toString(); + } + if ( data == QLatin1String( "smartgroups" ) ) + { + // create a smartgroup QgsSmartGroupEditorDialog dlg( mStyle, this ); if ( dlg.exec() == QDialog::Rejected ) return; @@ -1039,34 +1065,39 @@ void QgsStyleManagerDialog::addGroup() if ( !id ) return; itemName = dlg.smartgroupName(); - isGroup = false; } else { - // create a simple child-group to the selected + // create a tag + bool ok; + itemName = QInputDialog::getText( this, tr( "Tag name" ), + tr( "Please enter name for the new tag:" ), QLineEdit::Normal, tr( "New tag" ), &ok ).trimmed(); + if ( !ok || itemName.isEmpty() ) + return; - itemName = QString( tr( "New Group" ) ); - int parentid = ( parentData == QLatin1String( "groups" ) ) ? 0 : parentData.toInt(); // parentid is 0 for top-level groups - id = mStyle->addGroup( itemName, parentid ); + int check = mStyle->tagId( itemName ); + if ( check > 0 ) + { + QMessageBox::critical( this, tr( "Error!" ), + tr( "Tag name already exists in your symbol database." ) ); + return; + } + id = mStyle->addTag( itemName ); if ( !id ) { QMessageBox::critical( this, tr( "Error!" ), - tr( "New group could not be created.\n" + tr( "New tag could not be created.\n" "There was a problem with your symbol database." ) ); return; } } - QStandardItem *parentItem = model->itemFromIndex( parentIndex ); + QStandardItem *parentItem = model->itemFromIndex( index ); QStandardItem *childItem = new QStandardItem( itemName ); childItem->setData( id ); parentItem->appendRow( childItem ); groupTree->setCurrentIndex( childItem->index() ); - if ( isGroup ) - { - groupTree->edit( childItem->index() ); - } } void QgsStyleManagerDialog::removeGroup() @@ -1074,9 +1105,9 @@ void QgsStyleManagerDialog::removeGroup() QStandardItemModel *model = qobject_cast( groupTree->model() ); QModelIndex index = groupTree->currentIndex(); - // Violation: removing system groups + // do not allow removal of system-defined groupings QString data = index.data( Qt::UserRole + 1 ).toString(); - if ( data == QLatin1String( "all" ) || data == QLatin1String( "groups" ) || data == QLatin1String( "smartgroups" ) || index.data() == "Ungrouped" ) + if ( data == QLatin1String( "all" ) || data == QLatin1String( "favorite" ) || data == QLatin1String( "tags" ) || index.data() == "smartgroups" ) { int err = QMessageBox::critical( this, tr( "Invalid selection" ), tr( "Cannot delete system defined categories.\n" @@ -1092,16 +1123,7 @@ void QgsStyleManagerDialog::removeGroup() } else { - mStyle->remove( QgsStyle::GroupEntity, index.data( Qt::UserRole + 1 ).toInt() ); - QStandardItem *item = model->itemFromIndex( index ); - if ( item->hasChildren() ) - { - QStandardItem *parent = item->parent(); - for ( int i = 0; i < item->rowCount(); i++ ) - { - parent->appendRow( item->takeChild( i ) ); - } - } + mStyle->remove( QgsStyle::TagEntity, index.data( Qt::UserRole + 1 ).toInt() ); } parentItem->removeRow( index.row() ); } @@ -1117,11 +1139,11 @@ void QgsStyleManagerDialog::groupRenamed( QStandardItem * item ) } else { - mStyle->rename( QgsStyle::GroupEntity, id, name ); + mStyle->rename( QgsStyle::TagEntity, id, name ); } } -void QgsStyleManagerDialog::groupSymbolsAction() +void QgsStyleManagerDialog::tagSymbolsAction() { QStandardItemModel *treeModel = qobject_cast( groupTree->model() ); @@ -1130,8 +1152,8 @@ void QgsStyleManagerDialog::groupSymbolsAction() if ( mGrouppingMode ) { mGrouppingMode = false; - actnGroupSymbols->setVisible( true ); - actnFinishGrouping->setVisible( false ); + actnTagSymbols->setVisible( true ); + actnFinishTagging->setVisible( false ); // disconnect slot which handles regrouping disconnect( model, SIGNAL( itemChanged( QStandardItem* ) ), this, SLOT( regrouped( QStandardItem* ) ) ); @@ -1155,21 +1177,20 @@ void QgsStyleManagerDialog::groupSymbolsAction() QModelIndex present = groupTree->currentIndex(); while ( present.parent().isValid() ) { - if ( present.parent().data() == "Groups" ) + if ( present.parent().data() == "Tags" ) { validGroup = true; break; } - else - present = present.parent(); + present = present.parent(); } if ( !validGroup ) return; mGrouppingMode = true; // Change visibility of actions - actnGroupSymbols->setVisible( false ); - actnFinishGrouping->setVisible( true ); + actnTagSymbols->setVisible( false ); + actnFinishTagging->setVisible( true ); // Remove all Symbol editing functionalities disconnect( treeModel, SIGNAL( itemChanged( QStandardItem* ) ), this, SLOT( groupRenamed( QStandardItem* ) ) ); @@ -1199,20 +1220,23 @@ void QgsStyleManagerDialog::regrouped( QStandardItem *item ) QgsDebugMsg( "Unknown style entity" ); return; } - int groupid = groupTree->currentIndex().data( Qt::UserRole + 1 ).toInt(); + + QStandardItemModel *treeModel = qobject_cast( groupTree->model() ); + QString tag = treeModel->itemFromIndex( groupTree->currentIndex() )->text(); + QString symbolName = item->text(); bool regrouped; if ( item->checkState() == Qt::Checked ) - regrouped = mStyle->group( type, symbolName, groupid ); + regrouped = mStyle->tagSymbol( type, symbolName, QStringList( tag ) ); else - regrouped = mStyle->group( type, symbolName, 0 ); + regrouped = mStyle->detagSymbol( type, symbolName, QStringList( tag ) ); if ( !regrouped ) { int er = QMessageBox::critical( this, tr( "Database Error" ), tr( "There was a problem with the Symbols database while regrouping." ) ); // call the slot again to get back to normal if ( er ) - groupSymbolsAction(); + tagSymbolsAction(); } } @@ -1242,69 +1266,8 @@ void QgsStyleManagerDialog::filterSymbols( const QString& qword ) } } -void QgsStyleManagerDialog::tagsChanged() -{ - QModelIndexList indexes = listItems->selectionModel()->selection().indexes(); - QStringList addtags; - QStringList removetags; - - QStringList oldtags = mTagList; - QStringList newtags = tagsLineEdit->text().split( ',', QString::SkipEmptyParts ); - - QgsStyle::StyleEntity type; - if ( currentItemType() < 3 ) - { - type = QgsStyle::SymbolEntity; - } - else if ( currentItemType() == 3 ) - { - type = QgsStyle::ColorrampEntity; - } - else - { - QgsDebugMsg( "Unknown Style Entity!" ); - return; - } - // compare old with new to find removed tags - Q_FOREACH ( const QString &tag, oldtags ) - { - if ( !newtags.contains( tag ) ) - removetags.append( tag ); - } - if ( !removetags.isEmpty() ) - { - Q_FOREACH ( const QModelIndex& index, indexes ) - { - mStyle->detagSymbol( type, index.data().toString(), removetags ); - } - } - // compare new with old to find added tags - Q_FOREACH ( const QString &tag, newtags ) - { - if ( !oldtags.contains( tag ) ) - addtags.append( tag ); - } - if ( !addtags.isEmpty() ) - { - Q_FOREACH ( const QModelIndex& index, indexes ) - { - mStyle->tagSymbol( type, index.data().toString(), addtags ); - } - } -} - void QgsStyleManagerDialog::symbolSelected( const QModelIndex& index ) { - // Populate the tags for the symbol - tagsLineEdit->clear(); - if ( index.isValid() ) - { - QStandardItem *item = static_cast( listItems->model() )->itemFromIndex( index ); - QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; - mTagList = mStyle->tagsOfSymbol( type, item->data().toString() ); - tagsLineEdit->setText( mTagList.join( QStringLiteral( "," ) ) ); - } - actnEditItem->setEnabled( index.isValid() && !mGrouppingMode ); } @@ -1314,8 +1277,10 @@ void QgsStyleManagerDialog::selectedSymbolsChanged( const QItemSelection& select Q_UNUSED( deselected ); bool nothingSelected = listItems->selectionModel()->selectedIndexes().empty(); actnRemoveItem->setDisabled( nothingSelected ); + actnAddFavorite->setDisabled( nothingSelected ); + actnRemoveFavorite->setDisabled( nothingSelected ); mGroupListMenu->setDisabled( nothingSelected ); - actnUngroup->setDisabled( nothingSelected ); + actnDetag->setDisabled( nothingSelected ); actnExportAsPNG->setDisabled( nothingSelected ); actnExportAsSVG->setDisabled( nothingSelected ); actnEditItem->setDisabled( nothingSelected ); @@ -1330,7 +1295,6 @@ void QgsStyleManagerDialog::enableSymbolInputs( bool enable ) actnRemoveGroup->setEnabled( enable ); btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode searchBox->setEnabled( enable ); - tagsLineEdit->setEnabled( enable ); } void QgsStyleManagerDialog::enableGroupInputs( bool enable ) @@ -1346,19 +1310,8 @@ void QgsStyleManagerDialog::enableItemsForGroupingMode( bool enable ) QStandardItemModel *treeModel = qobject_cast( groupTree->model() ); for ( int i = 0; i < treeModel->rowCount(); i++ ) { - if ( treeModel->item( i )->data() != "groups" ) - { - treeModel->item( i )->setEnabled( enable ); - } - if ( treeModel->item( i )->data() == "groups" ) - { - treeModel->item( i )->setEnabled( enable ); - for ( int k = 0; k < treeModel->item( i )->rowCount(); k++ ) - { - if ( !treeModel->item( i )->child( k )->data().toInt() ) - treeModel->item( i )->child( k )->setEnabled( enable ); - } - } + treeModel->item( i )->setEnabled( enable ); + if ( treeModel->item( i )->data() == "smartgroups" ) { for ( int j = 0; j < treeModel->item( i )->rowCount(); j++ ) @@ -1401,19 +1354,78 @@ void QgsStyleManagerDialog::listitemsContextMenu( QPoint point ) mGroupListMenu->clear(); QAction* a; - QList groupIds = mStyle->groupIds(); - Q_FOREACH ( int groupId, groupIds ) + QStringList tags = mStyle->tags(); + tags.sort(); + Q_FOREACH ( const QString& tag, tags ) { - a = new QAction( mStyle->groupName( groupId ), mGroupListMenu ); - a->setData( groupId ); - connect( a, SIGNAL( triggered( bool ) ), this, SLOT( groupSelectedSymbols() ) ); + a = new QAction( tag, mGroupListMenu ); + a->setData( tag ); + connect( a, SIGNAL( triggered( bool ) ), this, SLOT( tagSelectedSymbols() ) ); mGroupListMenu->addAction( a ); } mGroupMenu->popup( globalPos ); } -void QgsStyleManagerDialog::groupSelectedSymbols() +void QgsStyleManagerDialog::addFavoriteSelectedSymbols() +{ + QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; + if ( currentItemType() > 3 ) + { + QgsDebugMsg( "unknown entity type" ); + return; + } + + QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); + Q_FOREACH ( const QModelIndex& index, indexes ) + { + mStyle->addFavorite( type, index.data().toString() ); + } + populateList(); +} + +void QgsStyleManagerDialog::removeFavoriteSelectedSymbols() +{ + QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; + if ( currentItemType() > 3 ) + { + QgsDebugMsg( "unknown entity type" ); + return; + } + + QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); + Q_FOREACH ( const QModelIndex& index, indexes ) + { + mStyle->removeFavorite( type, index.data().toString() ); + } + populateList(); +} + +void QgsStyleManagerDialog::tagSelectedSymbols() +{ + QAction* selectedItem = qobject_cast( sender() ); + + if ( selectedItem ) + { + QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; + if ( currentItemType() > 3 ) + { + QgsDebugMsg( "unknown entity type" ); + return; + } + QString tag = selectedItem->data().toString(); + QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); + Q_FOREACH ( const QModelIndex& index, indexes ) + { + mStyle->tagSymbol( type, index.data().toString(), QStringList( tag ) ); + } + populateList(); + + QgsDebugMsg( "Selected Action: " + selectedItem->text() ); + } +} + +void QgsStyleManagerDialog::detagSelectedSymbols() { QAction* selectedItem = qobject_cast( sender() ); @@ -1425,11 +1437,10 @@ void QgsStyleManagerDialog::groupSelectedSymbols() QgsDebugMsg( "unknown entity type" ); return; } - int groupId = selectedItem->data().toInt(); QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); Q_FOREACH ( const QModelIndex& index, indexes ) { - mStyle->group( type, index.data().toString(), groupId ); + mStyle->detagSymbol( type, index.data().toString() ); } populateList(); @@ -1474,14 +1485,4 @@ void QgsStyleManagerDialog::editSmartgroupAction() groupChanged( present ); } -bool QgsStyleManagerDialog::eventFilter( QObject *obj, QEvent *event ) -{ - - if (( obj == tagsLineEdit ) && ( event->type() == QEvent::FocusOut ) ) - { - tagsChanged(); - return true; - } - return false; -} diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.h b/src/gui/symbology-ng/qgsstylemanagerdialog.h index 3582112b6a31..7132838af44f 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.h +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.h @@ -66,8 +66,8 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan void addGroup(); void removeGroup(); - //! carryout symbol grouping using check boxes - void groupSymbolsAction(); + //! carry out symbol tagging using check boxes + void tagSymbolsAction(); //! edit the selected smart group void editSmartgroupAction(); @@ -78,9 +78,6 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan //! filter the symbols based on input search term void filterSymbols( const QString& ); - //! Listen to tag changes - void tagsChanged(); - //! Perform symbol specific tasks when selected void symbolSelected( const QModelIndex& ); @@ -95,7 +92,14 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan protected slots: bool addColorRamp( QAction* action ); - void groupSelectedSymbols(); + //! Add selected symbols to favorites + void addFavoriteSelectedSymbols(); + //! Remove selected symbols from favorites + void removeFavoriteSelectedSymbols(); + //! Tag selected symbols using menu item selection + void tagSelectedSymbols(); + //! Remove all tags from selected symbols + void detagSelectedSymbols(); protected: @@ -104,8 +108,6 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan //! populate the groups void populateGroups(); - //! build the groups tree - void buildGroupTree( QStandardItem* &parent ); //! to set symbols checked when in editing mode void setSymbolsChecked( const QStringList& ); @@ -136,9 +138,6 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan //! Enables or diables the groupTree items for grouping mode void enableItemsForGroupingMode( bool ); - //! Event filter to capture tagsLineEdit out of focus - bool eventFilter( QObject*, QEvent* ) override; - //! sets the text of the item with bold font void setBold( QStandardItem* ); diff --git a/src/gui/symbology-ng/qgsstylesavedialog.cpp b/src/gui/symbology-ng/qgsstylesavedialog.cpp new file mode 100644 index 000000000000..4087ebe66ec4 --- /dev/null +++ b/src/gui/symbology-ng/qgsstylesavedialog.cpp @@ -0,0 +1,56 @@ +/*************************************************************************** + qgssymbolsavedialog.cpp + --------------------------------------- + begin : November 2016 + copyright : (C) 2016 by Mathieu Pellerin + email : nirvn dot asia at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgsstylesavedialog.h" + +#include "qgis.h" +#include "qgsstyle.h" + +#include +#include + +QgsStyleSaveDialog::QgsStyleSaveDialog( QWidget* parent, QgsStyle::StyleEntity type ) + : QDialog( parent ) +{ + setupUi( this ); + + if ( type == QgsStyle::SymbolEntity ) + { + this->setWindowTitle( tr( "Save new symbol" ) ); + } + else if ( type == QgsStyle::ColorrampEntity ) + { + this->setWindowTitle( tr( "Save new color ramp" ) ); + } +} + +QgsStyleSaveDialog::~QgsStyleSaveDialog() { } + +QString QgsStyleSaveDialog::name() const +{ + return mName->text(); +} + +QString QgsStyleSaveDialog::tags() const +{ + return mTags->text(); +} + +bool QgsStyleSaveDialog::isFavorite() const +{ + return mFavorite->isChecked(); +} diff --git a/src/gui/symbology-ng/qgsstylesavedialog.h b/src/gui/symbology-ng/qgsstylesavedialog.h new file mode 100644 index 000000000000..8fb4b2cd922b --- /dev/null +++ b/src/gui/symbology-ng/qgsstylesavedialog.h @@ -0,0 +1,57 @@ +/*************************************************************************** + qgssymbolsavedialog.h + ------------------------------------- + begin : November 2016 + copyright : (C) 2016 by Mathieu Pellerin + email : nirvn dot asia at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSSTYLESAVEDIALOG_H +#define QGSSTYLESAVEDIALOG_H + +#include +#include "ui_qgsstylesavedialog.h" + +#include "qgsstyle.h" + +/** \ingroup gui + * \brief a dialog for setting properties of a newly saved style. + * \note added in QGIS 3.0 +*/ +class GUI_EXPORT QgsStyleSaveDialog: public QDialog, private Ui::QgsStyleSaveDialog +{ + Q_OBJECT + + public: + + /** Constructor for QgsSymbolSaveDialog + * @param parent parent widget + * @param type the QgsStyle entity type being saved + */ + QgsStyleSaveDialog( QWidget* parent = nullptr, QgsStyle::StyleEntity type = QgsStyle::SymbolEntity ); + + ~QgsStyleSaveDialog(); + + //! returns the text value of the name element + QString name() const; + + //! returns the text value of the tags element + QString tags() const; + + //! returns whether the favorite element is checked + bool isFavorite() const; + + + +}; + +#endif // QGSSTYLESAVEDIALOG_H diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index 235aa8e7ab51..08548a86c7bc 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -19,6 +19,7 @@ #include "qgssizescalewidget.h" #include "qgsstylemanagerdialog.h" +#include "qgsstylesavedialog.h" #include "qgsdatadefined.h" #include "qgssymbol.h" @@ -29,6 +30,8 @@ #include "qgsapplication.h" #include "qgsvectorlayer.h" +#include +#include #include #include #include @@ -38,6 +41,7 @@ #include #include #include +#include #include @@ -67,26 +71,20 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, } mClipFeaturesAction = new QAction( tr( "Clip features to canvas extent" ), this ); mClipFeaturesAction->setCheckable( true ); - connect( mClipFeaturesAction, SIGNAL( toggled( bool ) ), this, SLOT( clipFeaturesToggled( bool ) ) ); - - // populate the groups - groupsCombo->addItem( QLatin1String( "" ) ); - populateGroups(); - QStringList groups = style->smartgroupNames(); - Q_FOREACH ( const QString& group, groups ) - { - groupsCombo->addItem( group, QVariant( "smart" ) ); - } + connect( mClipFeaturesAction, &QAction::toggled, this, &QgsSymbolsListWidget::clipFeaturesToggled ); QStandardItemModel* model = new QStandardItemModel( viewSymbols ); viewSymbols->setModel( model ); connect( viewSymbols->selectionModel(), SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( setSymbolFromStyle( const QModelIndex & ) ) ); - connect( mStyle, SIGNAL( symbolSaved( QString, QgsSymbol* ) ), this, SLOT( symbolAddedToStyle( QString, QgsSymbol* ) ) ); - connect( openStyleManagerButton, SIGNAL( pressed() ), this, SLOT( openStyleManager() ) ); + connect( mStyle, &QgsStyle::symbolSaved , this, &QgsSymbolsListWidget::symbolAddedToStyle ); + connect( mStyle, &QgsStyle::groupsModified , this, &QgsSymbolsListWidget::populateGroups ); + + connect( openStyleManagerButton, &QPushButton::pressed, this, &QgsSymbolsListWidget::openStyleManager ); lblSymbolName->setText( QLatin1String( "" ) ); - populateSymbolView(); + + populateGroups(); if ( mSymbol ) { @@ -119,7 +117,7 @@ QgsSymbolsListWidget::QgsSymbolsListWidget( QgsSymbol* symbol, QgsStyle* style, btnColor->setColorDialogTitle( tr( "Select color" ) ); btnColor->setContext( QStringLiteral( "symbology" ) ); - connect( btnSaveSymbol, SIGNAL( clicked() ), this, SLOT( saveSymbol() ) ); + connect( btnSaveSymbol, &QPushButton::clicked, this, &QgsSymbolsListWidget::saveSymbol ); } QgsSymbolsListWidget::~QgsSymbolsListWidget() @@ -148,30 +146,72 @@ QgsSymbolWidgetContext QgsSymbolsListWidget::context() const return mContext; } -void QgsSymbolsListWidget::populateGroups( const QString& parent, const QString& prepend ) +void QgsSymbolsListWidget::populateGroups() { - QgsSymbolGroupMap groups = mStyle->childGroupNames( parent ); - QgsSymbolGroupMap::const_iterator i = groups.constBegin(); - while ( i != groups.constEnd() ) + groupsCombo->blockSignals( true ); + groupsCombo->clear(); + + groupsCombo->addItem( tr( "Favorites" ), QVariant( "favorite" ) ); + groupsCombo->addItem( tr( "All Symbols" ), QVariant( "all" ) ); + + int index = 2; + QStringList tags = mStyle->tags(); + if ( tags.count() > 0 ) { - QString text; - if ( !prepend.isEmpty() ) + tags.sort(); + groupsCombo->insertSeparator( index ); + Q_FOREACH ( const QString& tag, tags ) { - text = prepend + '/' + i.value(); + groupsCombo->addItem( tag, QVariant( "tag" ) ); + index++; } - else + } + + QStringList groups = mStyle->smartgroupNames(); + if ( groups.count() > 0 ) + { + groups.sort(); + groupsCombo->insertSeparator( index + 1 ); + Q_FOREACH ( const QString& group, groups ) { - text = i.value(); + groupsCombo->addItem( group, QVariant( "smartgroup" ) ); } - groupsCombo->addItem( text, QVariant( i.key() ) ); - populateGroups( i.value(), text ); - ++i; } + groupsCombo->blockSignals( false ); + + QSettings settings; + index = settings.value( "qgis/symbolsListGroupsIndex", 0 ).toInt(); + groupsCombo->setCurrentIndex( index ); + + populateSymbolView(); } void QgsSymbolsListWidget::populateSymbolView() { - populateSymbols( mStyle->symbolNames() ); + QStringList symbols; + QString text = groupsCombo->currentText(); + int id; + + if ( groupsCombo->currentData().toString() == QLatin1String( "favorite" ) ) + { + symbols = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity ); + } + else if ( groupsCombo->currentData().toString() == QLatin1String( "all" ) ) + { + symbols = mStyle->symbolNames(); + } + else if ( groupsCombo->currentData().toString() == QLatin1String( "smartgroup" ) ) + { + id = mStyle->smartgroupId( text ); + symbols = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, id ); + } + else + { + id = mStyle->tagId( text ); + symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, id ); + } + + populateSymbols( symbols ); } void QgsSymbolsListWidget::populateSymbols( const QStringList& names ) @@ -357,30 +397,34 @@ void QgsSymbolsListWidget::addSymbolToStyle() void QgsSymbolsListWidget::saveSymbol() { - bool ok; - QString name = QInputDialog::getText( this, tr( "Symbol name" ), - tr( "Please enter name for the symbol:" ), QLineEdit::Normal, tr( "New symbol" ), &ok ); - if ( !ok || name.isEmpty() ) + QgsStyleSaveDialog saveDlg( this ); + if ( !saveDlg.exec() ) + return; + + if ( saveDlg.name().isEmpty() ) return; // check if there is no symbol with same name - if ( mStyle->symbolNames().contains( name ) ) + if ( mStyle->symbolNames().contains( saveDlg.name() ) ) { int res = QMessageBox::warning( this, tr( "Save symbol" ), tr( "Symbol with name '%1' already exists. Overwrite?" ) - .arg( name ), + .arg( saveDlg.name() ), QMessageBox::Yes | QMessageBox::No ); if ( res != QMessageBox::Yes ) { return; } + mStyle->removeSymbol( saveDlg.name() ); } + QStringList symbolTags = saveDlg.tags().split( ',' ); + // add new symbol to style and re-populate the list - mStyle->addSymbol( name, mSymbol->clone() ); + mStyle->addSymbol( saveDlg.name(), mSymbol->clone() ); // make sure the symbol is stored - mStyle->saveSymbol( name, mSymbol->clone(), 0, QStringList() ); + mStyle->saveSymbol( saveDlg.name(), mSymbol->clone(), saveDlg.isFavorite(), symbolTags ); } void QgsSymbolsListWidget::on_mSymbolUnitWidget_changed() @@ -537,7 +581,7 @@ void QgsSymbolsListWidget::setSymbolFromStyle( const QModelIndex & index ) // get new instance of symbol from style QgsSymbol* s = mStyle->symbol( symbolName ); QgsUnitTypes::RenderUnit unit = s->outputUnit(); - // remove all symbol layers from original symbol + // remove all symbol layers from original symbolgroupsCombo while ( mSymbol->symbolLayerCount() ) mSymbol->deleteSymbolLayer( 0 ); // move all symbol layers to our symbol @@ -557,32 +601,8 @@ void QgsSymbolsListWidget::setSymbolFromStyle( const QModelIndex & index ) void QgsSymbolsListWidget::on_groupsCombo_currentIndexChanged( int index ) { - QStringList symbols; - QString text = groupsCombo->itemText( index ); - // List all symbols when empty list item is selected - if ( text.isEmpty() ) - { - symbols = mStyle->symbolNames(); - } - else - { - int groupid; - if ( groupsCombo->itemData( index ).toString() == QLatin1String( "smart" ) ) - { - groupid = mStyle->smartgroupId( text ); - symbols = mStyle->symbolsOfSmartgroup( QgsStyle::SymbolEntity, groupid ); - } - else - { - groupid = groupsCombo->itemData( index ).toInt(); - symbols = mStyle->symbolsOfGroup( QgsStyle::SymbolEntity, groupid ); - } - } - populateSymbols( symbols ); -} + QSettings settings; + settings.setValue( QStringLiteral( "qgis/symbolsListGroupsIndex" ), index ); -void QgsSymbolsListWidget::on_groupsCombo_editTextChanged( const QString &text ) -{ - QStringList symbols = mStyle->findSymbols( QgsStyle::SymbolEntity, text ); - populateSymbols( symbols ); + populateSymbolView(); } diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.h b/src/gui/symbology-ng/qgssymbolslistwidget.h index 3e65c4255b47..2ad3ba79103d 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.h +++ b/src/gui/symbology-ng/qgssymbolslistwidget.h @@ -67,12 +67,15 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW void setLineWidth( double width ); void addSymbolToStyle(); void saveSymbol(); + void symbolAddedToStyle( const QString& name, QgsSymbol* symbol ); + void on_mSymbolUnitWidget_changed(); void on_mTransparencySlider_valueChanged( int value ); + //! Pupulates the groups combo box with available tags and smartgroups + void populateGroups(); void on_groupsCombo_currentIndexChanged( int index ); - void on_groupsCombo_editTextChanged( const QString &text ); void openStyleManager(); void clipFeaturesToggled( bool checked ); @@ -99,8 +102,6 @@ class GUI_EXPORT QgsSymbolsListWidget : public QWidget, private Ui::SymbolsListW //! Displays alpha value as transparency in mTransparencyLabel void displayTransparency( double alpha ); - //! Recursive function to create the group tree in the widget - void populateGroups( const QString& parent = "", const QString& prepend = "" ); QgsSymbolWidgetContext mContext; diff --git a/src/ui/qgsstyleexportimportdialogbase.ui b/src/ui/qgsstyleexportimportdialogbase.ui index 71ff90f74b89..4803407540e9 100644 --- a/src/ui/qgsstyleexportimportdialogbase.ui +++ b/src/ui/qgsstyleexportimportdialogbase.ui @@ -43,17 +43,33 @@ - - + + - Save to group + Tag(s) - - - - true + + + + + 0 + 0 + + + + Add to favorites + + + + + + + + + + Tip: separate multiple tags with commas diff --git a/src/ui/qgsstylemanagerdialogbase.ui b/src/ui/qgsstylemanagerdialogbase.ui index 77f5c81c7cb4..23e27f7073ac 100644 --- a/src/ui/qgsstylemanagerdialogbase.ui +++ b/src/ui/qgsstylemanagerdialogbase.ui @@ -380,26 +380,6 @@ QMenu::item:selected { background-color: gray; } */ - - - - - - - 75 - true - - - - Tags - - - - - - - - @@ -450,15 +430,37 @@ QMenu::item:selected { background-color: gray; } */ Edit item - + + + false + + + Add to favorites + + + Add to favorites + + + + + false + + + Remove from favorites + + + Remove from favorites + + + false - Ungroup + Clear tags - Ungroup + Clear tags @@ -484,17 +486,17 @@ QMenu::item:selected { background-color: gray; } */ Remove group - + - Group symbols + Attach selected tag to symbols - + true - Finish grouping + Finish tagging true diff --git a/src/ui/qgsstylesavedialog.ui b/src/ui/qgsstylesavedialog.ui new file mode 100644 index 000000000000..3357a8959c6c --- /dev/null +++ b/src/ui/qgsstylesavedialog.ui @@ -0,0 +1,126 @@ + + + QgsStyleSaveDialog + + + + 0 + 0 + 489 + 225 + + + + Save new style + + + + + + + + Name + + + + + + + + + + + 0 + 0 + + + + Add to favorites + + + + + + + Tag(s) + + + + + + + + + + Tip: separate multiple tags with commas + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Save + + + + + + + mName + mTags + mFavorite + + + + + buttonBox + accepted() + QgsStyleSaveDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + QgsStyleSaveDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/src/ui/symbollayer/widget_symbolslist.ui b/src/ui/symbollayer/widget_symbolslist.ui index beb23af9c992..31e73bbdf3cf 100644 --- a/src/ui/symbollayer/widget_symbolslist.ui +++ b/src/ui/symbollayer/widget_symbolslist.ui @@ -72,7 +72,7 @@ - Symbols in group + Symbols in @@ -131,17 +131,11 @@ - - - 70 - 16777215 - - Save symbol - Save + Save symbol diff --git a/tests/src/core/testqgsstyle.cpp b/tests/src/core/testqgsstyle.cpp index 3ee9353d5dc4..fecf6e6f245b 100644 --- a/tests/src/core/testqgsstyle.cpp +++ b/tests/src/core/testqgsstyle.cpp @@ -65,6 +65,7 @@ class TestStyle : public QObject void testCreateColorRamps(); void testLoadColorRamps(); void testSaveLoad(); + void testFavorites(); void testTags(); }; @@ -258,6 +259,35 @@ void TestStyle::testSaveLoad() testLoadColorRamps(); } +void TestStyle::testFavorites() +{ + mStyle->clear(); + + // save initial number of favorites to compare against additions / substractions + QStringList favorites; + favorites = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity ); + int count = favorites.count(); + + // add some symbols to favorites + mStyle->saveSymbol( "symbolA", QgsMarkerSymbol::createSimple( QgsStringMap() ), true, QStringList() ); + mStyle->saveSymbol( "symbolB", QgsMarkerSymbol::createSimple( QgsStringMap() ), false, QStringList() ); + mStyle->saveSymbol( "symbolC", QgsMarkerSymbol::createSimple( QgsStringMap() ), true, QStringList() ); + + // check for added symbols to favorites + favorites = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity ); + QCOMPARE( favorites.count(), count + 2 ); + QVERIFY( favorites.contains( "symbolA" ) ); + QVERIFY( favorites.contains( "symbolC" ) ); + + // remove one symbol from favorites + mStyle->removeFavorite( QgsStyle::SymbolEntity, "symbolA" ); + + // insure favorites updated after removal + favorites = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity ); + QCOMPARE( favorites.count(), count + 1 ); + QVERIFY( favorites.contains( "symbolC" ) ); +} + void TestStyle::testTags() { mStyle->clear(); @@ -289,7 +319,7 @@ void TestStyle::testTags() QVERIFY( !tags.contains( "purple" ) ); //add some symbols - QVERIFY( mStyle->saveSymbol( "symbol1", QgsMarkerSymbol::createSimple( QgsStringMap() ), 0, QStringList() << "red" << "starry" ) ); + QVERIFY( mStyle->saveSymbol( "symbol1", QgsMarkerSymbol::createSimple( QgsStringMap() ), false, QStringList() << "red" << "starry" ) ); mStyle->addSymbol( QStringLiteral( "blue starry" ), QgsMarkerSymbol::createSimple( QgsStringMap() ), true ); mStyle->addSymbol( QStringLiteral( "red circle" ), QgsMarkerSymbol::createSimple( QgsStringMap() ), true ); From 5b4a88f8e07e8ee1f9bfc0570f76f68717688cf2 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 31 Oct 2016 15:30:29 +0100 Subject: [PATCH 775/897] [feature] Add layer scoped actions Within the attribute table, there is a new button to trigger actions which are not based on individual features but instead on the whole layer. Normally they will perform actions based on all features or the selection. In addition to this, a lot of cleanup has been done. --- doc/api_break.dox | 5 + python/core/core.sip | 2 + python/core/qgsaction.sip | 64 +++---- python/core/qgsactionmanager.sip | 59 ++---- python/core/qgsactionscope.sip | 113 ++++++++++++ python/core/qgsactionscoperegistry.sip | 74 ++++++++ .../attributetable/qgsattributetablemodel.sip | 2 +- python/gui/qgsactionmenu.sip | 12 +- src/app/gps/qgsgpsinformationwidget.cpp | 4 +- src/app/qgisapp.cpp | 56 +++--- src/app/qgisappinterface.cpp | 2 +- src/app/qgsattributeactiondialog.cpp | 45 +++-- src/app/qgsattributeactiondialog.h | 4 +- .../qgsattributeactionpropertiesdialog.cpp | 129 ++++++++----- src/app/qgsattributeactionpropertiesdialog.h | 11 +- src/app/qgsattributetabledialog.cpp | 36 +++- src/app/qgsattributetabledialog.h | 1 + src/app/qgsfeatureaction.cpp | 15 +- src/app/qgsfeatureaction.h | 4 +- src/app/qgsidentifyresultsdialog.cpp | 50 +++-- src/app/qgsidentifyresultsdialog.h | 2 +- src/app/qgsmaptooladdfeature.cpp | 2 +- src/app/qgsmaptoolfeatureaction.cpp | 39 ++-- src/core/CMakeLists.txt | 4 + src/core/qgsaction.cpp | 61 ++++++ src/core/qgsaction.h | 92 ++++++---- src/core/qgsactionmanager.cpp | 136 +++++++++----- src/core/qgsactionmanager.h | 53 +++--- src/core/qgsactionscope.cpp | 90 +++++++++ src/core/qgsactionscope.h | 126 +++++++++++++ src/core/qgsactionscoperegistry.cpp | 73 ++++++++ src/core/qgsactionscoperegistry.h | 81 ++++++++ src/core/qgsapplication.cpp | 16 +- src/core/qgsapplication.h | 17 ++ .../attributetable/qgsattributetablemodel.cpp | 2 +- .../attributetable/qgsattributetablemodel.h | 2 +- .../attributetable/qgsattributetableview.cpp | 18 +- src/gui/attributetable/qgsdualview.cpp | 14 +- src/gui/attributetable/qgsdualview.h | 4 +- src/gui/attributetable/qgsfeaturelistview.cpp | 2 +- src/gui/qgsactionmenu.cpp | 106 ++++++----- src/gui/qgsactionmenu.h | 49 ++--- src/gui/qgsattributedialog.cpp | 2 +- src/gui/qgsidentifymenu.cpp | 4 +- src/ui/qgsattributeactiondialogbase.ui | 2 +- .../qgsattributeactionpropertiesdialogbase.ui | 173 +++++++++--------- src/ui/qgsattributetabledialog.ui | 11 ++ 47 files changed, 1308 insertions(+), 561 deletions(-) create mode 100644 python/core/qgsactionscope.sip create mode 100644 python/core/qgsactionscoperegistry.sip create mode 100644 src/core/qgsactionscope.cpp create mode 100644 src/core/qgsactionscope.h create mode 100644 src/core/qgsactionscoperegistry.cpp create mode 100644 src/core/qgsactionscoperegistry.h diff --git a/doc/api_break.dox b/doc/api_break.dox index 3a9223bac0c7..991c154ba66a 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -335,6 +335,11 @@ variant instead. - expandAction() has been removed. Use QgsExpression::replaceExpressionText() instead. - setPythonExecute() was removed. Initialize QgsPythonRunner instead. +QgsAction {#qgis_api_break_3_0_QgsAction} +--------- + +- `QgsAction::action()` has been renamed to `QgsAction::command()`. + QgsAdvancedDigitizingDockWidget {#qgis_api_break_3_0_QgsAdvancedDigitizingDockWidget} ------------------------------- diff --git a/python/core/core.sip b/python/core/core.sip index cc14357c1b42..89ff092bd37d 100644 --- a/python/core/core.sip +++ b/python/core/core.sip @@ -18,6 +18,8 @@ %Include qgsapplication.sip %Include qgsaction.sip %Include qgsactionmanager.sip +%Include qgsactionscope.sip +%Include qgsactionscoperegistry.sip %Include qgsaggregatecalculator.sip %Include qgsattributetableconfig.sip %Include qgsattributeeditorelement.sip diff --git a/python/core/qgsaction.sip b/python/core/qgsaction.sip index 9993856e45f2..d2e317c9db15 100644 --- a/python/core/qgsaction.sip +++ b/python/core/qgsaction.sip @@ -33,41 +33,7 @@ class QgsAction OpenUrl, }; - /** - * Create a new QgsAction - * - * @param type The type of this action - * @param description A human readable description string - * @param action The action text. Its interpretation depends on the type - * @param capture If this is set to true, the output will be captured when an action is run - */ - QgsAction( ActionType type, const QString& description, const QString& action, bool capture ); - - - /** - * Create a new QgsAction - * - * @param type The type of this action - * @param description A human readable description string - * @param action The action text. Its interpretation depends on the type - * @param icon Path to an icon for this action - * @param capture If this is set to true, the output will be captured when an action is run - * @param shortTitle A short string used to label user interface elements like buttons - */ - QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, const QString& shortTitle = QString() ); - - /** - * Create a new QgsAction - * - * @param type The type of this action - * @param description A human readable description string - * @param action The action text. Its interpretation depends on the type - * @param icon Path to an icon for this action - * @param capture If this is set to true, the output will be captured when an action is run - * @param showInAttributeTable If this is false, the action will be hidden on the attribute table action widget - * @param shortTitle A short string used to label user interface elements like buttons - */ - QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, bool showInAttributeTable, const QString& shortTitle = QString() ); + QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, const QString& shortTitle = QString(), const QSet& actionScopes = QSet() ); //! The name of the action. This may be a longer description. QString name() const; @@ -81,8 +47,8 @@ class QgsAction //! The icon QIcon icon() const; - //! The action - QString action() const; + //! The command + QString command() const; //! The action type ActionType type() const; @@ -90,9 +56,25 @@ class QgsAction //! Whether to capture output for display when this action is run bool capture() const; - //! Whether this action should be shown on the attribute table - bool showInAttributeTable() const; - - //! Whether the action is runable on the current platform + //! Checks if the action is runable on the current platform bool runable() const; + + /** + * The action scopes define where an action will be available. + * Action scopes may offer additional variables like the clicked + * coordinate. + * + * @see QgsActionScope + * @note Added in QGIS 3.0 + */ + QSet actionScopes() const; + + /** + * The action scopes define where an action will be available. + * Action scopes may offer additional variables like the clicked + * coordinate. + * + * @note Added in QGIS 3.0 + */ + void setActionScopes( const QSet& actionScopes ); }; diff --git a/python/core/qgsactionmanager.sip b/python/core/qgsactionmanager.sip index b234c572a376..ad199d97b7d1 100644 --- a/python/core/qgsactionmanager.sip +++ b/python/core/qgsactionmanager.sip @@ -59,14 +59,11 @@ class QgsActionManager */ void addAction( const QgsAction& action ); - //! Remove an action at given index - void removeAction( int index ); - /** Does the given values. defaultValueIndex is the index of the * field to be used if the action has a $currfield placeholder. * @note available in python bindings as doActionFeature */ - void doAction( int index, + void doAction( const QString& actionId, const QgsFeature &feat, int defaultValueIndex = 0 ) /PyName=doActionFeature/; @@ -76,7 +73,7 @@ class QgsActionManager * @param feature feature to run action for * @param context expression context to evalute expressions under */ - void doAction( int index, + void doAction( const QString& actionId, const QgsFeature& feature, const QgsExpressionContext& context ); @@ -84,7 +81,7 @@ class QgsActionManager void clearActions(); //! List all actions - QList listActions() const; + QList listActions( const QString& actionScope = QString() ) const; //! Return the layer QgsVectorLayer* layer() const; @@ -95,49 +92,27 @@ class QgsActionManager //! Reads the actions in in XML format bool readXml( const QDomNode& layer_node ); - int size() const; /** - * Get the action at the specified index. + * Get an action by its id. + * + * @note Added in QGIS 3.0 */ - QgsAction at( int idx ) const /Factory/; -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->size() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = new QgsAction( sipCpp->at( a0 ) ); - } -%End + QgsAction action( const QString& id ); /** - * Get the action at the specified index. + * Each scope can have a default action. This will be saved in the project + * file. + * + * @note Added in QGIS 3.0 */ - QgsAction operator[]( int idx ) const; -%MethodCode - if ( a0 < 0 || a0 >= sipCpp->size() ) - { - PyErr_SetString(PyExc_KeyError, QByteArray::number(a0)); - sipIsErr = 1; - } - else - { - sipRes = new QgsAction( sipCpp->at( a0 ) ); - } -%End + void setDefaultAction( const QString& actionScope, const QString& actionId ); /** - * Returns the index of the default action, or -1 if no default action is available. - * @see setDefaultAction() + * Each scope can have a default action. This will be saved in the project + * file. + * + * @note Added in QGIS 3.0 */ - int defaultAction() const; + QgsAction defaultAction( const QString& actionScope ); - /** - * Set the index of the default action. - * @param actionNumber index of action which should be made the default for the layer - * @see defaultAction() - */ - void setDefaultAction( int actionNumber ); }; diff --git a/python/core/qgsactionscope.sip b/python/core/qgsactionscope.sip new file mode 100644 index 000000000000..ba7061a5c628 --- /dev/null +++ b/python/core/qgsactionscope.sip @@ -0,0 +1,113 @@ +/*************************************************************************** + qgsactionscope.sip - QgsActionScope + + --------------------- + begin : 1.11.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +/** \ingroup core + * An action scope defines a "place" for an action to be shown and may add + * additional expression variables. + * Each QgsAction can be available in one or several action scopes. + * + * Examples: + * --------- + * + *

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Canvas
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show for canvas tools. Adds `@clicked_x` and `@clicked_y` in map coordinates.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  AttributeTable
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table for each row.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  FieldSpecific
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show on right click in attribute table. Adds `@field_index` and `@field_name`.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Selection
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table and work on the layer or selection.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + * + * @note Added in QGIS 3.0 + */ + +class QgsActionScope +{ +%TypeHeaderCode +#include "qgsactionscope.h" +%End + public: + /** + * Creates a new action scope. + */ + explicit QgsActionScope(); + + /** + * Creates a new action scope. + * For details concerning the parameters check the documentation + * of the corresponding properties. + */ + explicit QgsActionScope( const QString& id, const QString& title, const QString& description, const QgsExpressionContextScope& expressionContextScope = QgsExpressionContextScope() ); + + /** + * Compares two action scopes + */ + bool operator==( const QgsActionScope& other ) const; + + /** + * An expression scope may offer additional variables for an action scope. + * This can be an `field_name` for the attribute which was clicked or + * `clicked_x` and `clicked_y` for actions which are available as map canvas clicks. + * + * @note Added in QGIS 3.0 + */ + QgsExpressionContextScope expressionContextScope() const; + + /** + * \copydoc expressionContextScope() + */ + void setExpressionContextScope( const QgsExpressionContextScope& expressionContextScope ); + + /** + * A unique identifier for this action scope. + * + * @note Added in QGIS 3.0 + */ + QString id() const; + + //! \copydoc id() + void setId( const QString& id ); + + /** + * The title is a human readable and translated string that will be + * presented to the user in the properties dialog. + * + * @note Added in QGIS 3.0 + */ + QString title() const; + //! \copydoc title() + void setTitle( const QString& title ); + + /** + * The description should be a longer description of where actions in this scope + * are available. It is not necessary to list the available expression variables + * in here, they are extracted automatically from the expressionContextScope(). + * + * @note Added in QGIS 3.0 + */ + QString description() const; + //! \copydoc description() + void setDescription( const QString& description ); + + /** + * Returns if this scope is valid. + * + * @note Added in QGIS 3.0 + */ + bool isValid() const; +}; diff --git a/python/core/qgsactionscoperegistry.sip b/python/core/qgsactionscoperegistry.sip new file mode 100644 index 000000000000..fe2784e3300a --- /dev/null +++ b/python/core/qgsactionscoperegistry.sip @@ -0,0 +1,74 @@ +/*************************************************************************** + qgsactionscoperegistry.h - QgsActionScopeRegistry + + --------------------- + begin : 1.11.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +/** \ingroup core + * The action scope registry is an application wide registry that + * contains a list of available action scopes. + * Some scopes are available by default, additional ones can be registered + * at runtime by plugins or custom applications. + * + * To get access use the QgsApplication: + * + * ``` + * QgsApplication::actionScopeRegistry() + * ``` + * + * @note Added in QGIS 3.0 + */ +class QgsActionScopeRegistry : QObject +{ +%TypeHeaderCode +#include "qgsactionscoperegistry.h" +%End + + public: + explicit QgsActionScopeRegistry( QObject* parent = nullptr ); + + /** + * Get all registered action scopes. + */ + QSet actionScopes() const; + + /** + * Register an additional action scope. + * + * @note Added in QGIS 3.0 + */ + void registerActionScope( const QgsActionScope& actionScope ); + + /** + * Unregister an additional action scope. + * + * @note Added in QGIS 3.0 + */ + void unregisterActionScope( const QgsActionScope& actionScope ); + + /** + * Get an action scope by its id. + * + * @note Added in QGIS 3.0 + */ + QgsActionScope actionScope( const QString& id ); + + signals: + /** + * Emitted whenever a new action scope is registered or an action scope + * is unregistered. + * + * @note Added in QGIS 3.0 + */ + void actionScopesChanged(); +}; diff --git a/python/gui/attributetable/qgsattributetablemodel.sip b/python/gui/attributetable/qgsattributetablemodel.sip index cc032055eec4..6b138aba1c3e 100644 --- a/python/gui/attributetable/qgsattributetablemodel.sip +++ b/python/gui/attributetable/qgsattributetablemodel.sip @@ -126,7 +126,7 @@ class QgsAttributeTableModel : QAbstractTableModel /** * Execute an action */ - void executeAction( int action, const QModelIndex &idx ) const; + void executeAction( const QString& action, const QModelIndex &idx ) const; /** * Execute a QgsMapLayerAction diff --git a/python/gui/qgsactionmenu.sip b/python/gui/qgsactionmenu.sip index 219937f9b6a3..935875119482 100644 --- a/python/gui/qgsactionmenu.sip +++ b/python/gui/qgsactionmenu.sip @@ -19,13 +19,11 @@ class QgsActionMenu : QMenu struct ActionData { ActionData(); - - ActionData( int actionId, QgsFeatureId featureId, QgsMapLayer* mapLayer ); - + ActionData( const QgsAction& action, QgsFeatureId featureId, QgsMapLayer* mapLayer ); ActionData( QgsMapLayerAction* action, QgsFeatureId featureId, QgsMapLayer* mapLayer ); QgsActionMenu::ActionType actionType; - + QVariant actionData; QgsFeatureId featureId; QgsMapLayer* mapLayer; }; @@ -38,7 +36,7 @@ class QgsActionMenu : QMenu * for the lifetime of this object. * @param parent The usual QWidget parent. */ - explicit QgsActionMenu( QgsVectorLayer* layer, const QgsFeature *feature, QWidget *parent /TransferThis/ = 0 ); + explicit QgsActionMenu( QgsVectorLayer* layer, const QgsFeature& feature, const QString& actionScope, QWidget *parent /TransferThis/ = nullptr ); /** * Constructs a new QgsActionMenu @@ -47,7 +45,7 @@ class QgsActionMenu : QMenu * @param fid The feature id of the feature for which this action will be run. * @param parent The usual QWidget parent. */ - explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, QWidget *parent /TransferThis/ = 0 ); + explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, const QString& actionScope, QWidget *parent /TransferThis/ = nullptr ); /** * Destructor @@ -60,7 +58,7 @@ class QgsActionMenu : QMenu * @param feature A feature. Will not take ownership. It's the callers responsibility to keep the feature * as long as the menu is displayed and the action is running. */ - void setFeature( QgsFeature* feature ); + void setFeature( const QgsFeature& feature ); signals: void reinit(); diff --git a/src/app/gps/qgsgpsinformationwidget.cpp b/src/app/gps/qgsgpsinformationwidget.cpp index cf9b948a1b35..9b168b6188f4 100644 --- a/src/app/gps/qgsgpsinformationwidget.cpp +++ b/src/app/gps/qgsgpsinformationwidget.cpp @@ -831,7 +831,7 @@ void QgsGPSInformationWidget::on_mBtnCloseFeature_clicked() g.fromWkb( buf, size ); f->setGeometry( g ); - QgsFeatureAction action( tr( "Feature added" ), *f, vlayer, -1, -1, this ); + QgsFeatureAction action( tr( "Feature added" ), *f, vlayer, QString(), -1, this ); if ( action.addFeature() ) { if ( mCbxAutoCommit->isChecked() ) @@ -941,7 +941,7 @@ void QgsGPSInformationWidget::on_mBtnCloseFeature_clicked() return; //unknown wkbtype } // layerWKBType == QgsWkbTypes::Polygon - QgsFeatureAction action( tr( "Feature added" ), *f, vlayer, -1, -1, this ); + QgsFeatureAction action( tr( "Feature added" ), *f, vlayer, QString(), -1, this ); if ( action.addFeature() ) { if ( mCbxAutoCommit->isChecked() ) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 6644b8e7c484..cfc8b6e30033 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -5765,31 +5765,28 @@ void QgisApp::updateDefaultFeatureAction( QAction *action ) mFeatureActionMenu->setActiveAction( action ); - int index = mFeatureActionMenu->actions().indexOf( action ); + QgsAction qgsAction; + if ( action ) + { + qgsAction = action->data().value(); + } - if ( vlayer->actions()->size() > 0 && index < vlayer->actions()->size() ) + if ( qgsAction.isValid() ) { - vlayer->actions()->setDefaultAction( index ); + vlayer->actions()->setDefaultAction( QStringLiteral( "Canvas" ), qgsAction.id() ); QgsMapLayerActionRegistry::instance()->setDefaultActionForLayer( vlayer, nullptr ); - if ( index == -1 ) - index = 0; - QgsAction a = vlayer->actions()->listActions().at( index ); - - if ( !a.name().isEmpty() ) - mActionFeatureAction->setToolTip( tr( "Run feature action
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  %1" ).arg( a.name() ) ); - else if ( !a.shortTitle().isEmpty() ) - mActionFeatureAction->setToolTip( tr( "Run feature action
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  %1" ).arg( a.shortTitle() ) ); + mActionFeatureAction->setToolTip( tr( "Run feature action
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  %1" ).arg( qgsAction.name() ) ); - if ( !a.icon().isNull() ) - mActionFeatureAction->setIcon( a.icon() ); + if ( !qgsAction.icon().isNull() ) + mActionFeatureAction->setIcon( qgsAction.icon() ); } else { //action is from QgsMapLayerActionRegistry - vlayer->actions()->setDefaultAction( -1 ); + vlayer->actions()->setDefaultAction( QStringLiteral( "Canvas" ), QString() ); - QgsMapLayerAction * mapLayerAction = dynamic_cast( action ); + QgsMapLayerAction* mapLayerAction = qobject_cast( action ); if ( mapLayerAction ) { QgsMapLayerActionRegistry::instance()->setDefaultActionForLayer( vlayer, mapLayerAction ); @@ -5815,19 +5812,22 @@ void QgisApp::refreshFeatureActions() if ( !vlayer ) return; - QgsActionManager *actions = vlayer->actions(); - for ( int i = 0; i < actions->size(); i++ ) + QList actions = vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ); + Q_FOREACH ( const QgsAction& action, actions ) { - QAction *action = mFeatureActionMenu->addAction( actions->at( i ).icon(), actions->at( i ).name() ); - if ( i == actions->defaultAction() ) + QAction* qAction = new QAction( action.icon(), action.shortTitle(), mFeatureActionMenu ); + qAction->setData( QVariant::fromValue( action ) ); + mFeatureActionMenu->addAction( qAction ); + + if ( action.name() == vlayer->actions()->defaultAction( QStringLiteral( "Canvas" ) ).name() ) { - mFeatureActionMenu->setActiveAction( action ); + mFeatureActionMenu->setActiveAction( qAction ); } } //add actions registered in QgsMapLayerActionRegistry QList registeredActions = QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ); - if ( actions->size() > 0 && registeredActions.size() > 0 ) + if ( !actions.isEmpty() && registeredActions.size() > 0 ) { //add a separator between user defined and standard actions mFeatureActionMenu->addSeparator(); @@ -10623,7 +10623,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) bool isEditable = vlayer->isEditable(); bool layerHasSelection = vlayer->selectedFeatureCount() > 0; - bool layerHasActions = vlayer->actions()->size() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); + bool layerHasActions = !vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ).isEmpty() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); mActionLocalHistogramStretch->setEnabled( false ); mActionFullHistogramStretch->setEnabled( false ); @@ -10904,16 +10904,12 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) void QgisApp::refreshActionFeatureAction() { - QgsMapLayer* layer = activeLayer(); - - if ( !layer || layer->type() != QgsMapLayer::VectorLayer ) - { + mActionFeatureAction->setEnabled( false ); + QgsVectorLayer* vlayer = qobject_cast( activeLayer() ); + if ( !vlayer ) return; - } - - QgsVectorLayer* vlayer = qobject_cast( layer ); - bool layerHasActions = vlayer->actions()->size() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); + bool layerHasActions = !vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ).isEmpty() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); mActionFeatureAction->setEnabled( layerHasActions ); } diff --git a/src/app/qgisappinterface.cpp b/src/app/qgisappinterface.cpp index 636a6bef9a81..65ce369dec39 100644 --- a/src/app/qgisappinterface.cpp +++ b/src/app/qgisappinterface.cpp @@ -633,7 +633,7 @@ bool QgisAppInterface::openFeatureForm( QgsVectorLayer *vlayer, QgsFeature &f, b if ( !vlayer ) return false; - QgsFeatureAction action( tr( "Attributes changed" ), f, vlayer, -1, -1, QgisApp::instance() ); + QgsFeatureAction action( tr( "Attributes changed" ), f, vlayer, QString(), -1, QgisApp::instance() ); if ( vlayer->isEditable() ) { return action.editFeature( showModal ); diff --git a/src/app/qgsattributeactiondialog.cpp b/src/app/qgsattributeactiondialog.cpp index afedc85fdf3b..4950ac1b1867 100644 --- a/src/app/qgsattributeactiondialog.cpp +++ b/src/app/qgsattributeactiondialog.cpp @@ -122,7 +122,7 @@ void QgsAttributeActionDialog::insertRow( int row, const QgsAction& action ) mAttributeActionTable->setItem( row, ShortTitle, new QTableWidgetItem( action.shortTitle() ) ); // Action text - mAttributeActionTable->setItem( row, ActionText, new QTableWidgetItem( action.action() ) ); + mAttributeActionTable->setItem( row, ActionText, new QTableWidgetItem( action.command() ) ); // Capture output item = new QTableWidgetItem(); @@ -130,11 +130,14 @@ void QgsAttributeActionDialog::insertRow( int row, const QgsAction& action ) item->setCheckState( action.capture() ? Qt::Checked : Qt::Unchecked ); mAttributeActionTable->setItem( row, Capture, item ); - // Capture output + // Scopes item = new QTableWidgetItem(); item->setFlags( item->flags() & ~( Qt::ItemIsEditable ) ); - item->setCheckState( action.showInAttributeTable() ? Qt::Checked : Qt::Unchecked ); - mAttributeActionTable->setItem( row, ShowInAttributeTable, item ); + QStringList actionScopes = action.actionScopes().toList(); + qSort( actionScopes ); + item->setText( actionScopes.join( QStringLiteral( ", " ) ) ); + item->setData( Qt::UserRole, QVariant::fromValue>( action.actionScopes() ) ); + mAttributeActionTable->setItem( row, ActionScopes, item ); // Icon QIcon icon = action.icon(); @@ -145,9 +148,9 @@ void QgsAttributeActionDialog::insertRow( int row, const QgsAction& action ) updateButtons(); } -void QgsAttributeActionDialog::insertRow( int row, QgsAction::ActionType type, const QString& name, const QString& actionText, const QString& iconPath, bool capture ) +void QgsAttributeActionDialog::insertRow( int row, QgsAction::ActionType type, const QString& name, const QString& actionText, const QString& iconPath, bool capture, const QString& shortTitle, const QSet& actionScopes ) { - insertRow( row, QgsAction( type, name, actionText, iconPath, capture ) ); + insertRow( row, QgsAction( type, name, actionText, iconPath, capture, shortTitle, actionScopes ) ); } void QgsAttributeActionDialog::moveUp() @@ -214,8 +217,8 @@ QgsAction QgsAttributeActionDialog::rowToAction( int row ) const mAttributeActionTable->item( row, ActionText )->text(), mAttributeActionTable->verticalHeaderItem( row )->data( Qt::UserRole ).toString(), mAttributeActionTable->item( row, Capture )->checkState() == Qt::Checked, - mAttributeActionTable->item( row, ShowInAttributeTable )->checkState() == Qt::Checked, - mAttributeActionTable->item( row, ShortTitle )->text() ); + mAttributeActionTable->item( row, ShortTitle )->text(), + mAttributeActionTable->item( row, ActionScopes )->data( Qt::UserRole ).value>() ); return action; } @@ -269,7 +272,7 @@ void QgsAttributeActionDialog::insert() { QString name = uniqueName( dlg.description() ); - insertRow( pos, dlg.type(), name, dlg.actionText(), dlg.iconPath(), dlg.capture() ); + insertRow( pos, dlg.type(), name, dlg.actionText(), dlg.iconPath(), dlg.capture(), dlg.shortTitle(), dlg.actionScopes() ); } } @@ -296,13 +299,13 @@ void QgsAttributeActionDialog::updateButtons() void QgsAttributeActionDialog::addDefaultActions() { int pos = 0; - insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), QStringLiteral( "echo \"[% \"MY_FIELD\" %]\"" ), QLatin1String( "" ), true ); - insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), QStringLiteral( "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"" ), QLatin1String( "" ), true ); - insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), QStringLiteral( "QtGui.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")" ), QLatin1String( "" ), false ); - insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), QStringLiteral( "QtGui.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")" ), QLatin1String( "" ), false ); - insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), QStringLiteral( "QtGui.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")" ), QLatin1String( "" ), false ); - insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false ); - insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false ); + insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), QStringLiteral( "echo \"[% \"MY_FIELD\" %]\"" ), QLatin1String( "" ), true, tr( "Attribute Value" ), QSet() << QStringLiteral( "FieldSpecific" ) ); + insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), QStringLiteral( "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"" ), QLatin1String( "" ), true, tr( "Run application" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")" ), QLatin1String( "" ), false, tr( "Feature ID" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")" ), QLatin1String( "" ), false, tr( "Field Value" ), QSet() << QStringLiteral( "FieldSpecific" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")" ), QLatin1String( "" ), false, tr( "Clicked Coordinate" ), QSet() << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false, tr( "Open file" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "FieldSpecific" ) ); } void QgsAttributeActionDialog::itemDoubleClicked( QTableWidgetItem* item ) @@ -316,7 +319,7 @@ void QgsAttributeActionDialog::itemDoubleClicked( QTableWidgetItem* item ) mAttributeActionTable->verticalHeaderItem( row )->data( Qt::UserRole ).toString(), mAttributeActionTable->item( row, ActionText )->text(), mAttributeActionTable->item( row, Capture )->checkState() == Qt::Checked, - mAttributeActionTable->item( row, ShowInAttributeTable )->checkState() == Qt::Checked, + mAttributeActionTable->item( row, ActionScopes )->data( Qt::UserRole ).value>(), mLayer ); @@ -330,7 +333,13 @@ void QgsAttributeActionDialog::itemDoubleClicked( QTableWidgetItem* item ) mAttributeActionTable->item( row, ShortTitle )->setText( actionProperties.shortTitle() ); mAttributeActionTable->item( row, ActionText )->setText( actionProperties.actionText() ); mAttributeActionTable->item( row, Capture )->setCheckState( actionProperties.capture() ? Qt::Checked : Qt::Unchecked ); - mAttributeActionTable->item( row, ShowInAttributeTable )->setCheckState( actionProperties.showInAttributeTable() ? Qt::Checked : Qt::Unchecked ); + + QTableWidgetItem* item = mAttributeActionTable->item( row, ActionScopes ); + QStringList actionScopes = actionProperties.actionScopes().toList(); + qSort( actionScopes ); + item->setText( actionScopes.join( QStringLiteral( ", " ) ) ); + item->setData( Qt::UserRole, QVariant::fromValue>( actionProperties.actionScopes() ) ); + mAttributeActionTable->verticalHeaderItem( row )->setData( Qt::UserRole, actionProperties.iconPath() ); mAttributeActionTable->verticalHeaderItem( row )->setIcon( QIcon( actionProperties.iconPath() ) ); } diff --git a/src/app/qgsattributeactiondialog.h b/src/app/qgsattributeactiondialog.h index ea6bbc4c39e0..53703be4ab12 100644 --- a/src/app/qgsattributeactiondialog.h +++ b/src/app/qgsattributeactiondialog.h @@ -42,7 +42,7 @@ class APP_EXPORT QgsAttributeActionDialog: public QWidget, private Ui::QgsAttrib ShortTitle, ActionText, Capture, - ShowInAttributeTable + ActionScopes }; public: @@ -70,7 +70,7 @@ class APP_EXPORT QgsAttributeActionDialog: public QWidget, private Ui::QgsAttrib private: void insertRow( int row, const QgsAction& action ); - void insertRow( int row, QgsAction::ActionType type, const QString& name, const QString& actionText, const QString& iconPath, bool capture ); + void insertRow( int row, QgsAction::ActionType type, const QString& name, const QString& actionText, const QString& iconPath, bool capture , const QString& shortTitle, const QSet& actionScopes ); void swapRows( int row1, int row2 ); QgsAction rowToAction( int row ) const; diff --git a/src/app/qgsattributeactionpropertiesdialog.cpp b/src/app/qgsattributeactionpropertiesdialog.cpp index e495e53907ea..dd76375d8593 100644 --- a/src/app/qgsattributeactionpropertiesdialog.cpp +++ b/src/app/qgsattributeactionpropertiesdialog.cpp @@ -3,8 +3,8 @@ --------------------- begin : 18.4.2016 - copyright : (C) 2016 by mku - email : [your-email-here] + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * @@ -20,6 +20,9 @@ #include "qgsmapcanvas.h" #include "qgsproject.h" #include "qgsvectorlayer.h" +#include "qgsapplication.h" +#include "qgsactionscoperegistry.h" +#include "qgsactionscope.h" #include #include @@ -28,7 +31,7 @@ #include #include -QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsAction::ActionType type, const QString& description, const QString& shortTitle, const QString& iconPath, const QString& actionText, bool capture, bool showInAttributeTable, QgsVectorLayer* layer, QWidget* parent ) +QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsAction::ActionType type, const QString& description, const QString& shortTitle, const QString& iconPath, const QString& actionText, bool capture, QSet actionScopes, QgsVectorLayer* layer, QWidget* parent ) : QDialog( parent ) , mLayer( layer ) { @@ -41,29 +44,8 @@ QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsActio mIconPreview->setPixmap( QPixmap( iconPath ) ); mActionText->setText( actionText ); mCaptureOutput->setChecked( capture ); - mShowInAttributeTable->setChecked( showInAttributeTable ); - // display the expression builder - QgsExpressionContext context; - context << QgsExpressionContextUtils::globalScope() - << QgsExpressionContextUtils::projectScope() - << QgsExpressionContextUtils::layerScope( mLayer ); - - QgsDistanceArea myDa; - myDa.setSourceCrs( mLayer->crs().srsid() ); - myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); - - mFieldExpression->setLayer( mLayer ); - mFieldExpression->setGeomCalculator( myDa ); - - connect( mBrowseButton, SIGNAL( clicked( bool ) ), this, SLOT( browse() ) ); - connect( mInsertFieldOrExpression, SIGNAL( clicked( bool ) ), this, SLOT( insertExpressionOrField() ) ); - connect( mActionName, SIGNAL( textChanged( QString ) ), this, SLOT( updateButtons() ) ); - connect( mActionText, SIGNAL( textChanged() ), this, SLOT( updateButtons() ) ); - connect( mChooseIconButton, SIGNAL( clicked( bool ) ), this, SLOT( chooseIcon() ) ); - - updateButtons(); + init( actionScopes ); } QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsVectorLayer* layer, QWidget* parent ) @@ -72,26 +54,13 @@ QgsAttributeActionPropertiesDialog::QgsAttributeActionPropertiesDialog( QgsVecto { setupUi( this ); - // display the expression builder - QgsExpressionContext context; - context << QgsExpressionContextUtils::globalScope() - << QgsExpressionContextUtils::projectScope() - << QgsExpressionContextUtils::layerScope( mLayer ); + QSet defaultActionScopes; + defaultActionScopes << QStringLiteral( "Canvas" ) + << QStringLiteral( "FieldSpecific" ) + << QStringLiteral( "AttributeTableRow" ) + << QStringLiteral( "FeatureForm" ); - QgsDistanceArea myDa; - myDa.setSourceCrs( mLayer->crs().srsid() ); - myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); - myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); - - mFieldExpression->setLayer( mLayer ); - mFieldExpression->setGeomCalculator( myDa ); - - connect( mBrowseButton, SIGNAL( clicked( bool ) ), this, SLOT( browse() ) ); - connect( mInsertFieldOrExpression, SIGNAL( clicked( bool ) ), this, SLOT( insertExpressionOrField() ) ); - connect( mActionName, SIGNAL( textChanged( QString ) ), this, SLOT( updateButtons() ) ); - connect( mActionText, SIGNAL( textChanged() ), this, SLOT( updateButtons() ) ); - - updateButtons(); + init( defaultActionScopes ); } QgsAction::ActionType QgsAttributeActionPropertiesDialog::type() const @@ -119,9 +88,17 @@ QString QgsAttributeActionPropertiesDialog::actionText() const return mActionText->text(); } -bool QgsAttributeActionPropertiesDialog::showInAttributeTable() const +QSet QgsAttributeActionPropertiesDialog::actionScopes() const { - return mShowInAttributeTable->isChecked(); + QSet actionScopes; + + Q_FOREACH ( QCheckBox* cb, mActionScopeCheckBoxes ) + { + if ( cb->isChecked() ) + actionScopes.insert( cb->property( "ActionScopeName" ).toString() ); + } + + return actionScopes; } bool QgsAttributeActionPropertiesDialog::capture() const @@ -129,6 +106,22 @@ bool QgsAttributeActionPropertiesDialog::capture() const return mCaptureOutput->isChecked(); } +QgsExpressionContext QgsAttributeActionPropertiesDialog::createExpressionContext() const +{ + QgsExpressionContext context = mLayer->createExpressionContext(); + + Q_FOREACH ( QCheckBox* cb, mActionScopeCheckBoxes ) + { + if ( cb->isChecked() ) + { + QgsActionScope actionScope = QgsApplication::actionScopeRegistry()->actionScope( cb->property( "ActionScopeName" ).toString() ); + context.appendScope( new QgsExpressionContextScope( actionScope.expressionContextScope() ) ); + } + } + + return context; +} + void QgsAttributeActionPropertiesDialog::browse() { // Popup a file browser and place the results into the action widget @@ -178,3 +171,47 @@ void QgsAttributeActionPropertiesDialog::updateButtons() mButtonBox->button( QDialogButtonBox::Ok )->setEnabled( true ); } } + +void QgsAttributeActionPropertiesDialog::init( const QSet& actionScopes ) +{ + QSet availableActionScopes = QgsApplication::actionScopeRegistry()->actionScopes(); + + Q_FOREACH ( const QgsActionScope& scope, availableActionScopes ) + { + QCheckBox* actionScopeCheckBox = new QCheckBox( scope.title() ); + if ( actionScopes.contains( scope.id() ) ) + actionScopeCheckBox->setChecked( true ); + QStringList variables = scope.expressionContextScope().variableNames(); + + QString tooltip = scope.description(); + if ( !variables.empty() ) + { + tooltip += "

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  "; + tooltip += tr( "Additional variables" ); + tooltip += "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • "; + tooltip += variables.join( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • " ); + tooltip += "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                • "; + } + actionScopeCheckBox->setToolTip( tooltip ); + actionScopeCheckBox->setProperty( "ActionScopeName", scope.id() ); + mActionScopeCheckBoxes.append( actionScopeCheckBox ); + mActionScopesGroupBox->layout()->addWidget( actionScopeCheckBox ); + } + + QgsDistanceArea myDa; + myDa.setSourceCrs( mLayer->crs().srsid() ); + myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapSettings().hasCrsTransformEnabled() ); + myDa.setEllipsoid( QgsProject::instance()->ellipsoid() ); + + mFieldExpression->setLayer( mLayer ); + mFieldExpression->setGeomCalculator( myDa ); + mFieldExpression->registerExpressionContextGenerator( this ); + + connect( mBrowseButton, SIGNAL( clicked( bool ) ), this, SLOT( browse() ) ); + connect( mInsertFieldOrExpression, SIGNAL( clicked( bool ) ), this, SLOT( insertExpressionOrField() ) ); + connect( mActionName, SIGNAL( textChanged( QString ) ), this, SLOT( updateButtons() ) ); + connect( mActionText, SIGNAL( textChanged() ), this, SLOT( updateButtons() ) ); + connect( mChooseIconButton, SIGNAL( clicked( bool ) ), this, SLOT( chooseIcon() ) ); + + updateButtons(); +} diff --git a/src/app/qgsattributeactionpropertiesdialog.h b/src/app/qgsattributeactionpropertiesdialog.h index f2f3669413ba..8cdbec4e61f8 100644 --- a/src/app/qgsattributeactionpropertiesdialog.h +++ b/src/app/qgsattributeactionpropertiesdialog.h @@ -22,12 +22,12 @@ #include -class QgsAttributeActionPropertiesDialog: public QDialog, private Ui::QgsAttributeActionPropertiesDialogBase +class QgsAttributeActionPropertiesDialog: public QDialog, private Ui::QgsAttributeActionPropertiesDialogBase, public QgsExpressionContextGenerator { Q_OBJECT public: - QgsAttributeActionPropertiesDialog( QgsAction::ActionType type, const QString& description, const QString& shortTitle, const QString& iconPath, const QString& actionText, bool capture, bool showInAttributeTable, QgsVectorLayer* layer, QWidget* parent = nullptr ); + QgsAttributeActionPropertiesDialog( QgsAction::ActionType type, const QString& description, const QString& shortTitle, const QString& iconPath, const QString& actionText, bool capture, QSet actionScopes, QgsVectorLayer* layer, QWidget* parent = nullptr ); QgsAttributeActionPropertiesDialog( QgsVectorLayer* layer, QWidget* parent = nullptr ); @@ -41,10 +41,12 @@ class QgsAttributeActionPropertiesDialog: public QDialog, private Ui::QgsAttribu QString actionText() const; - bool showInAttributeTable() const; + QSet actionScopes() const; bool capture() const; + virtual QgsExpressionContext createExpressionContext() const override; + private slots: void browse(); void insertExpressionOrField(); @@ -52,7 +54,10 @@ class QgsAttributeActionPropertiesDialog: public QDialog, private Ui::QgsAttribu void updateButtons(); private: + void init( const QSet& actionScopes ); + QgsVectorLayer* mLayer; + QList mActionScopeCheckBoxes; }; #endif // QGSATTRIBUTEACTIONPROPERTIESDIALOG_H diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 230075602dea..604625acb0ec 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -226,6 +226,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mAttributeViewButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionFormView.svg" ) ) ); mActionExpressionSelect->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mIconExpressionSelect.svg" ) ) ); mActionAddFeature->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewTableRow.svg" ) ) ); + mActionFeatureActions->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ) ); // toggle editing bool canChangeAttributes = mLayer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues; @@ -308,6 +309,25 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mActionSearchForm->setToolTip( tr( "Search is not supported when using custom UI forms" ) ); } + QList actions = mLayer->actions()->listActions( QStringLiteral( "AttributeTable" ) ); + + if ( actions.isEmpty() ) + { + mActionFeatureActions->setVisible( false ); + } + else + { + QMenu* actionMenu = new QMenu(); + Q_FOREACH ( const QgsAction& action, actions ) + { + QAction* qAction = actionMenu->addAction( action.icon(), action.shortTitle() ); + qAction->setToolTip( action.name() ); + qAction->setData( QVariant::fromValue( action ) ); + connect( qAction, &QAction::triggered, this, &QgsAttributeTableDialog::layerActionTriggered ); + } + mActionFeatureActions->setMenu( actionMenu ); + } + editingToggled(); } @@ -512,6 +532,20 @@ void QgsAttributeTableDialog::replaceSearchWidget( QWidget* oldw, QWidget* neww neww->setVisible( true ); } +void QgsAttributeTableDialog::layerActionTriggered() +{ + QAction* qAction = qobject_cast( sender() ); + Q_ASSERT( qAction ); + + QgsAction action = qAction->data().value(); + + QgsExpressionContext context = mLayer->createExpressionContext(); + QgsExpressionContextScope* scope = new QgsExpressionContextScope(); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "action_scope" ), "AttributeTable" ) ); + context.appendScope( scope ); + action.run( context ); +} + void QgsAttributeTableDialog::filterColumnChanged( QObject* filterAction ) { mFilterButton->setDefaultAction( qobject_cast( filterAction ) ); @@ -662,7 +696,7 @@ void QgsAttributeTableDialog::on_mActionAddFeature_triggered() QgsAttributeTableModel* masterModel = mMainView->masterModel(); QgsFeature f; - QgsFeatureAction action( tr( "Geometryless feature added" ), f, mLayer, -1, -1, this ); + QgsFeatureAction action( tr( "Geometryless feature added" ), f, mLayer, QString(), -1, this ); if ( action.addFeature() ) { masterModel->reload( masterModel->index( 0, 0 ), masterModel->index( masterModel->rowCount() - 1, masterModel->columnCount() - 1 ) ); diff --git a/src/app/qgsattributetabledialog.h b/src/app/qgsattributetabledialog.h index ac69f7fdd687..0f017741dd0d 100644 --- a/src/app/qgsattributetabledialog.h +++ b/src/app/qgsattributetabledialog.h @@ -181,6 +181,7 @@ class APP_EXPORT QgsAttributeTableDialog : public QDialog, private Ui::QgsAttrib /* replace the search widget with a new one */ void replaceSearchWidget( QWidget* oldw, QWidget* neww ); + void layerActionTriggered(); signals: /** diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index 9c7f4990b602..3a2dd8b62c0e 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -32,11 +32,11 @@ #include #include -QgsFeatureAction::QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *layer, int action, int defaultAttr, QObject *parent ) +QgsFeatureAction::QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *layer, const QString& actionId, int defaultAttr, QObject *parent ) : QAction( name, parent ) , mLayer( layer ) , mFeature( &f ) - , mAction( action ) + , mActionId( actionId ) , mIdx( defaultAttr ) , mFeatureSaved( false ) { @@ -44,7 +44,7 @@ QgsFeatureAction::QgsFeatureAction( const QString &name, QgsFeature &f, QgsVecto void QgsFeatureAction::execute() { - mLayer->actions()->doAction( mAction, *mFeature, mIdx ); + mLayer->actions()->doAction( mActionId, *mFeature, mIdx ); } QgsAttributeDialog *QgsFeatureAction::newDialog( bool cloneFeature ) @@ -66,7 +66,8 @@ QgsAttributeDialog *QgsFeatureAction::newDialog( bool cloneFeature ) QgsAttributeDialog *dialog = new QgsAttributeDialog( mLayer, f, cloneFeature, parentWidget(), true, context ); dialog->setWindowFlags( dialog->windowFlags() | Qt::Tool ); - if ( mLayer->actions()->size() > 0 ) + QList actions = mLayer->actions()->listActions(); + if ( !actions.isEmpty() ) { dialog->setContextMenuPolicy( Qt::ActionsContextMenu ); @@ -74,15 +75,13 @@ QgsAttributeDialog *QgsFeatureAction::newDialog( bool cloneFeature ) a->setEnabled( false ); dialog->addAction( a ); - for ( int i = 0; i < mLayer->actions()->size(); i++ ) + Q_FOREACH ( const QgsAction& action, actions ) { - const QgsAction &action = mLayer->actions()->at( i ); - if ( !action.runable() ) continue; QgsFeature& feat = const_cast( *dialog->feature() ); - QgsFeatureAction *a = new QgsFeatureAction( action.name(), feat, mLayer, i, -1, dialog ); + QgsFeatureAction *a = new QgsFeatureAction( action.name(), feat, mLayer, action.id(), -1, dialog ); dialog->addAction( a ); connect( a, SIGNAL( triggered() ), a, SLOT( execute() ) ); diff --git a/src/app/qgsfeatureaction.h b/src/app/qgsfeatureaction.h index 9323750e293c..9b46923c110f 100644 --- a/src/app/qgsfeatureaction.h +++ b/src/app/qgsfeatureaction.h @@ -33,7 +33,7 @@ class APP_EXPORT QgsFeatureAction : public QAction Q_OBJECT public: - QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *vl, int action = -1, int defaultAttr = -1, QObject *parent = nullptr ); + QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *vl, const QString& actionId = QString(), int defaultAttr = -1, QObject *parent = nullptr ); public slots: void execute(); @@ -59,7 +59,7 @@ class APP_EXPORT QgsFeatureAction : public QAction QgsVectorLayer* mLayer; QgsFeature* mFeature; - int mAction; + QString mActionId; int mIdx; bool mFeatureSaved; diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index a51ab7dd5c7d..b1894e223e86 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -480,8 +480,9 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat //get valid QgsMapLayerActions for this layer QList< QgsMapLayerAction* > registeredActions = QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ); + QList actions = vlayer->actions()->listActions( QStringLiteral( "AttributeTableRow" ) ); - if ( !vlayer->fields().isEmpty() || vlayer->actions()->size() || !registeredActions.isEmpty() ) + if ( !vlayer->fields().isEmpty() || !actions.isEmpty() || !registeredActions.isEmpty() ) { QgsTreeWidgetItem *actionItem = new QgsTreeWidgetItem( QStringList() << tr( "(Actions)" ) ); actionItem->setData( 0, Qt::UserRole, "actions" ); @@ -496,17 +497,15 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat actionItem->addChild( editItem ); } - for ( int i = 0; i < vlayer->actions()->size(); i++ ) + Q_FOREACH ( const QgsAction& action, actions ) { - const QgsAction &action = vlayer->actions()->at( i ); - if ( !action.runable() ) continue; QTreeWidgetItem *twi = new QTreeWidgetItem( QStringList() << QLatin1String( "" ) << action.name() ); twi->setIcon( 0, QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ) ); twi->setData( 0, Qt::UserRole, "action" ); - twi->setData( 0, Qt::UserRole + 1, QVariant::fromValue( i ) ); + twi->setData( 0, Qt::UserRole + 1, action.id() ); actionItem->addChild( twi ); } @@ -996,12 +995,12 @@ void QgsIdentifyResultsDialog::itemClicked( QTreeWidgetItem *item, int column ) } else if ( item->data( 0, Qt::UserRole ).toString() == QLatin1String( "action" ) ) { - doAction( item, item->data( 0, Qt::UserRole + 1 ).toInt() ); + doAction( item, item->data( 0, Qt::UserRole + 1 ).toString() ); } else if ( item->data( 0, Qt::UserRole ).toString() == QLatin1String( "map_layer_action" ) ) { - QObject *action = item->data( 0, Qt::UserRole + 1 ).value(); - doMapLayerAction( item, qobject_cast( action ) ); + QgsMapLayerAction* action = item->data( 0, Qt::UserRole + 1 ).value(); + doMapLayerAction( item, action ); } } @@ -1091,25 +1090,23 @@ void QgsIdentifyResultsDialog::contextMenuEvent( QContextMenuEvent* event ) mActionPopup->addAction( tr( "Collapse all" ), this, SLOT( collapseAll() ) ); mActionPopup->addSeparator(); - if ( featItem && vlayer && vlayer->actions()->size() > 0 ) + if ( featItem && vlayer ) { - mActionPopup->addSeparator(); - - int featIdx = featItem->data( 0, Qt::UserRole + 1 ).toInt(); - - // The assumption is made that an instance of QgsIdentifyResults is - // created for each new Identify Results dialog box, and that the - // contents of the popup menu doesn't change during the time that - // such a dialog box is around. - for ( int i = 0; i < vlayer->actions()->size(); i++ ) + QList actions = vlayer->actions()->listActions( QStringLiteral( "FieldSpecific" ) ); + if ( !actions.isEmpty() ) { - const QgsAction &action = vlayer->actions()->at( i ); + mActionPopup->addSeparator(); - if ( !action.runable() ) - continue; + int featIdx = featItem->data( 0, Qt::UserRole + 1 ).toInt(); - QgsFeatureAction *a = new QgsFeatureAction( action.name(), mFeatures[ featIdx ], vlayer, i, idx, this ); - mActionPopup->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ), action.name(), a, SLOT( execute() ) ); + Q_FOREACH ( const QgsAction& action, actions ) + { + if ( !action.runable() ) + continue; + + QgsFeatureAction *a = new QgsFeatureAction( action.name(), mFeatures[ featIdx ], vlayer, action.id(), idx, this ); + mActionPopup->addAction( QgsApplication::getThemeIcon( QStringLiteral( "/mAction.svg" ) ), action.name(), a, SLOT( execute() ) ); + } } } @@ -1231,7 +1228,7 @@ void QgsIdentifyResultsDialog::deactivate() } } -void QgsIdentifyResultsDialog::doAction( QTreeWidgetItem *item, int action ) +void QgsIdentifyResultsDialog::doAction( QTreeWidgetItem *item, const QString& action ) { QTreeWidgetItem *featItem = featureItem( item ); if ( !featItem ) @@ -1687,13 +1684,14 @@ void QgsIdentifyResultsDialog::featureForm() return; QgsFeatureId fid = STRING_TO_FID( featItem->data( 0, Qt::UserRole ) ); - int idx = featItem->data( 0, Qt::UserRole + 1 ).toInt(); QgsFeature f; if ( !vlayer->getFeatures( QgsFeatureRequest().setFilterFid( fid ) ).nextFeature( f ) ) return; - QgsFeatureAction action( tr( "Attributes changed" ), f, vlayer, idx, -1, this ); + QString actionId = featItem->data( 0, Qt::UserRole + 1 ).toString(); + + QgsFeatureAction action( tr( "Attributes changed" ), f, vlayer, actionId, -1, this ); if ( vlayer->isEditable() ) { action.editFeature( false ); diff --git a/src/app/qgsidentifyresultsdialog.h b/src/app/qgsidentifyresultsdialog.h index 0436ab1a000b..bc7cfac356e1 100644 --- a/src/app/qgsidentifyresultsdialog.h +++ b/src/app/qgsidentifyresultsdialog.h @@ -256,7 +256,7 @@ class APP_EXPORT QgsIdentifyResultsDialog: public QDialog, private Ui::QgsIdenti void highlightFeature( QTreeWidgetItem *item ); - void doAction( QTreeWidgetItem *item, int action ); + void doAction( QTreeWidgetItem *item, const QString& action ); void doMapLayerAction( QTreeWidgetItem *item, QgsMapLayerAction* action ); diff --git a/src/app/qgsmaptooladdfeature.cpp b/src/app/qgsmaptooladdfeature.cpp index fd4c7368de7d..aae5ba68fa4e 100644 --- a/src/app/qgsmaptooladdfeature.cpp +++ b/src/app/qgsmaptooladdfeature.cpp @@ -49,7 +49,7 @@ QgsMapToolAddFeature::~QgsMapToolAddFeature() bool QgsMapToolAddFeature::addFeature( QgsVectorLayer *vlayer, QgsFeature *f, bool showModal ) { - QgsFeatureAction *action = new QgsFeatureAction( tr( "add feature" ), *f, vlayer, -1, -1, this ); + QgsFeatureAction *action = new QgsFeatureAction( tr( "add feature" ), *f, vlayer, QString(), -1, this ); bool res = action->addFeature( QgsAttributeMap(), showModal ); if ( showModal ) delete action; diff --git a/src/app/qgsmaptoolfeatureaction.cpp b/src/app/qgsmaptoolfeatureaction.cpp index b6b4de8d008d..ffd243e9229b 100644 --- a/src/app/qgsmaptoolfeatureaction.cpp +++ b/src/app/qgsmaptoolfeatureaction.cpp @@ -73,7 +73,7 @@ void QgsMapToolFeatureAction::canvasReleaseEvent( QgsMapMouseEvent* e ) } QgsVectorLayer *vlayer = qobject_cast( layer ); - if ( vlayer->actions()->size() == 0 && QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty() ) + if ( vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ).isEmpty() && QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty() ) { emit messageEmitted( tr( "The active vector layer has no defined actions" ), QgsMessageBar::INFO ); return; @@ -100,28 +100,22 @@ bool QgsMapToolFeatureAction::doAction( QgsVectorLayer *layer, int x, int y ) QgsPoint point = mCanvas->getCoordinateTransform()->toMapCoordinates( x, y ); - QgsFeatureList featList; + QgsRectangle r; + + // create the search rectangle + double searchRadius = searchRadiusMU( mCanvas ); + + r.setXMinimum( point.x() - searchRadius ); + r.setXMaximum( point.x() + searchRadius ); + r.setYMinimum( point.y() - searchRadius ); + r.setYMaximum( point.y() + searchRadius ); // toLayerCoordinates will throw an exception for an 'invalid' point. // For example, if you project a world map onto a globe using EPSG 2163 // and then click somewhere off the globe, an exception will be thrown. try { - // create the search rectangle - double searchRadius = searchRadiusMU( mCanvas ); - - QgsRectangle r; - r.setXMinimum( point.x() - searchRadius ); - r.setXMaximum( point.x() + searchRadius ); - r.setYMinimum( point.y() - searchRadius ); - r.setYMaximum( point.y() + searchRadius ); - r = toLayerCoordinates( layer, r ); - - QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest().setFilterRect( r ).setFlags( QgsFeatureRequest::ExactIntersect ) ); - QgsFeature f; - while ( fit.nextFeature( f ) ) - featList << QgsFeature( f ); } catch ( QgsCsException & cse ) { @@ -130,12 +124,13 @@ bool QgsMapToolFeatureAction::doAction( QgsVectorLayer *layer, int x, int y ) QgsDebugMsg( QString( "Caught CRS exception %1" ).arg( cse.what() ) ); } - if ( featList.isEmpty() ) - return false; + QgsAction defaultAction = layer->actions()->defaultAction( QStringLiteral( "Canvas" ) ); - Q_FOREACH ( const QgsFeature& feat, featList ) + QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest().setFilterRect( r ).setFlags( QgsFeatureRequest::ExactIntersect ) ); + QgsFeature feat; + while ( fit.nextFeature( feat ) ) { - if ( layer->actions()->defaultAction() >= 0 ) + if ( defaultAction.isValid() ) { // define custom substitutions: layer id and clicked coords QgsExpressionContext context; @@ -145,10 +140,10 @@ bool QgsMapToolFeatureAction::doAction( QgsVectorLayer *layer, int x, int y ) QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "click_x" ), point.x(), true ) ); actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "click_y" ), point.y(), true ) ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "action_scope" ), QStringLiteral( "Canvas" ), true ) ); context << actionScope; - int actionIdx = layer->actions()->defaultAction(); - layer->actions()->doAction( actionIdx, feat, context ); + defaultAction.run( layer, feat, context ); } else { diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index ca808a861bcf..6b7dbbe2b2d0 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -81,6 +81,8 @@ SET(QGIS_CORE_SRCS qgis.cpp qgsapplication.cpp qgsaction.cpp + qgsactionscope.cpp + qgsactionscoperegistry.cpp qgsactionmanager.cpp qgsaggregatecalculator.cpp qgsattributetableconfig.cpp @@ -452,6 +454,7 @@ ENDIF(NOT MSVC) SET(QGIS_CORE_MOC_HDRS qgsapplication.h + qgsactionscoperegistry.h qgsbrowsermodel.h qgscontexthelp.h qgscoordinatereferencesystem.h @@ -609,6 +612,7 @@ SET(QGIS_CORE_HDRS qgis.h qgsaction.h + qgsactionscope.h qgsactionmanager.h qgsaggregatecalculator.h qgsannotation.h diff --git a/src/core/qgsaction.cpp b/src/core/qgsaction.cpp index 84b269055392..7116fb92d4ca 100644 --- a/src/core/qgsaction.cpp +++ b/src/core/qgsaction.cpp @@ -16,6 +16,16 @@ #include "qgsaction.h" +#include +#include +#include + +#include "qgspythonrunner.h" +#include "qgsrunprocess.h" +#include "qgsexpressioncontext.h" +#include "qgsvectorlayer.h" +#include "qgslogger.h" + bool QgsAction::runable() const { return mType == Generic || @@ -30,3 +40,54 @@ bool QgsAction::runable() const #endif ; } + +void QgsAction::run( QgsVectorLayer* layer, const QgsFeature& feature, const QgsExpressionContext& expressionContext ) const +{ + QgsExpressionContext actionContext( expressionContext ); + + actionContext << QgsExpressionContextUtils::layerScope( layer ); + actionContext.setFeature( feature ); + + run( actionContext ); +} + +void QgsAction::run( const QgsExpressionContext& expressionContext ) const +{ + if ( !isValid() ) + { + QgsDebugMsg( "Invalid action cannot be run" ); + return; + } + + QString expandedAction = QgsExpression::replaceExpressionText( mCommand, &expressionContext ); + + if ( mType == QgsAction::OpenUrl ) + { + QFileInfo finfo( expandedAction ); + if ( finfo.exists() && finfo.isFile() ) + QDesktopServices::openUrl( QUrl::fromLocalFile( expandedAction ) ); + else + QDesktopServices::openUrl( QUrl( expandedAction, QUrl::TolerantMode ) ); + } + else if ( mType == QgsAction::GenericPython ) + { + // TODO: capture output from QgsPythonRunner (like QgsRunProcess does) + QgsPythonRunner::run( expandedAction ); + } + else + { + // The QgsRunProcess instance created by this static function + // deletes itself when no longer needed. + QgsRunProcess::create( expandedAction, mCaptureOutput ); + } +} + +QSet QgsAction::actionScopes() const +{ + return mActionScopes; +} + +void QgsAction::setActionScopes( const QSet& actionScopes ) +{ + mActionScopes = actionScopes; +} diff --git a/src/core/qgsaction.h b/src/core/qgsaction.h index e19fdaddb4e5..5d8cd76b09c0 100644 --- a/src/core/qgsaction.h +++ b/src/core/qgsaction.h @@ -16,8 +16,14 @@ #ifndef QGSACTION_H #define QGSACTION_H +#include #include #include +#include + +#include "qgsexpressioncontext.h" + +class QgsExpressionContextScope; /** \ingroup core * Utility class that encapsulates an action based on vector attributes. @@ -36,40 +42,25 @@ class CORE_EXPORT QgsAction }; /** - * Create a new QgsAction - * - * @param type The type of this action - * @param description A human readable description string - * @param action The action text. Its interpretation depends on the type - * @param capture If this is set to true, the output will be captured when an action is run + * Default constructor */ - QgsAction( ActionType type, const QString& description, const QString& action, bool capture ) - : mType( type ) - , mDescription( description ) - , mAction( action ) - , mCaptureOutput( capture ) - , mShowInAttributeTable( true ) + QgsAction() + : mType( Generic ) {} - /** * Create a new QgsAction * * @param type The type of this action * @param description A human readable description string * @param action The action text. Its interpretation depends on the type - * @param icon Path to an icon for this action * @param capture If this is set to true, the output will be captured when an action is run - * @param shortTitle A short string used to label user interface elements like buttons */ - QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, const QString& shortTitle = QString() ) + QgsAction( ActionType type, const QString& description, const QString& action, bool capture ) : mType( type ) , mDescription( description ) - , mShortTitle( shortTitle ) - , mIcon( icon ) - , mAction( action ) + , mCommand( action ) , mCaptureOutput( capture ) - , mShowInAttributeTable( true ) {} /** @@ -80,17 +71,17 @@ class CORE_EXPORT QgsAction * @param action The action text. Its interpretation depends on the type * @param icon Path to an icon for this action * @param capture If this is set to true, the output will be captured when an action is run - * @param showInAttributeTable If this is false, the action will be hidden on the attribute table action widget * @param shortTitle A short string used to label user interface elements like buttons + * @param actionScopes A set of scopes in which this action will be available */ - QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, bool showInAttributeTable, const QString& shortTitle = QString() ) + QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, const QString& shortTitle = QString(), const QSet& actionScopes = QSet() ) : mType( type ) , mDescription( description ) , mShortTitle( shortTitle ) , mIcon( icon ) - , mAction( action ) + , mCommand( action ) , mCaptureOutput( capture ) - , mShowInAttributeTable( showInAttributeTable ) + , mActionScopes( actionScopes ) {} //! The name of the action. This may be a longer description. @@ -99,14 +90,24 @@ class CORE_EXPORT QgsAction //! The short title is used to label user interface elements like buttons QString shortTitle() const { return mShortTitle; } + QString id() const { return mShortTitle; } + + bool isValid() const { return !mShortTitle.isNull(); } + //! The path to the icon QString iconPath() const { return mIcon; } //! The icon QIcon icon() const { return QIcon( mIcon ); } - //! The action - QString action() const { return mAction; } + /** + * Returns the command that is executed by this action. + * How the content is interpreted depends on the type() and + * the actionScope(). + * + * @note Added in QGIS 3.0 + */ + QString command() const { return mCommand; } //! The action type ActionType type() const { return mType; } @@ -114,20 +115,49 @@ class CORE_EXPORT QgsAction //! Whether to capture output for display when this action is run bool capture() const { return mCaptureOutput; } - //! Whether this action should be shown on the attribute table - bool showInAttributeTable() const { return mShowInAttributeTable; } - //! Checks if the action is runable on the current platform bool runable() const; + /** + * Run this expression. + */ + void run( QgsVectorLayer* layer, const QgsFeature& feature, const QgsExpressionContext& expressionContext ) const; + + /** + * Run this expression. + */ + void run( const QgsExpressionContext& expressionContext ) const; + + /** + * The action scopes define where an action will be available. + * Action scopes may offer additional variables like the clicked + * coordinate. + * + * @see QgsActionScope + * @note Added in QGIS 3.0 + */ + QSet actionScopes() const; + + /** + * The action scopes define where an action will be available. + * Action scopes may offer additional variables like the clicked + * coordinate. + * + * @note Added in QGIS 3.0 + */ + void setActionScopes( const QSet& actionScopes ); + private: ActionType mType; QString mDescription; QString mShortTitle; QString mIcon; - QString mAction; + QString mCommand; bool mCaptureOutput; - bool mShowInAttributeTable; + QSet mActionScopes; + mutable QSharedPointer mAction; }; +Q_DECLARE_METATYPE( QgsAction ) + #endif // QGSACTION_H diff --git a/src/core/qgsactionmanager.cpp b/src/core/qgsactionmanager.cpp index eeb7b5c978d0..c793d5784dc6 100644 --- a/src/core/qgsactionmanager.cpp +++ b/src/core/qgsactionmanager.cpp @@ -42,43 +42,38 @@ void QgsActionManager::addAction( QgsAction::ActionType type, const QString& name, const QString& action, bool capture ) { - mActions << QgsAction( type, name, action, capture ); + addAction( QgsAction( type, name, action, capture ) ); } void QgsActionManager::addAction( QgsAction::ActionType type, const QString& name, const QString& action, const QString& icon, bool capture ) { - mActions << QgsAction( type, name, action, icon, capture ); + addAction( QgsAction( type, name, action, icon, capture ) ); } void QgsActionManager::addAction( const QgsAction& action ) { - mActions << action; -} + static int actionId = 0; -void QgsActionManager::removeAction( int index ) -{ - if ( index >= 0 && index < mActions.size() ) - { - mActions.removeAt( index ); - } + mActions.insert( ++actionId, action ); } -void QgsActionManager::doAction( int index, const QgsFeature& feat, int defaultValueIndex ) +void QgsActionManager::doAction( const QString& actionId, const QgsFeature& feature, int defaultValueIndex ) { QgsExpressionContext context = createExpressionContext(); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); - actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "current_field" ), feat.attribute( defaultValueIndex ), true ) ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_index" ), defaultValueIndex, true ) ); + if ( defaultValueIndex >= 0 && defaultValueIndex < feature.fields().size() ) + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), feature.fields().at( defaultValueIndex ), true ) ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_value" ), feature.attribute( defaultValueIndex ), true ) ); context << actionScope; - doAction( index, feat, context ); + doAction( actionId, feature, context ); } -void QgsActionManager::doAction( int index, const QgsFeature& feat, const QgsExpressionContext& context ) +void QgsActionManager::doAction( const QString& actionId, const QgsFeature& feat, const QgsExpressionContext& context ) { - if ( index < 0 || index >= size() ) - return; + QgsAction act = action( actionId ); - const QgsAction &action = at( index ); - if ( !action.runable() ) + if ( !act.isValid() || !act.runable() ) return; QgsExpressionContext actionContext( context ); @@ -87,11 +82,11 @@ void QgsActionManager::doAction( int index, const QgsFeature& feat, const QgsExp actionContext << QgsExpressionContextUtils::layerScope( mLayer ); actionContext.setFeature( feat ); - QString expandedAction = QgsExpression::replaceExpressionText( action.action(), &actionContext ); + QString expandedAction = QgsExpression::replaceExpressionText( act.command(), &actionContext ); if ( expandedAction.isEmpty() ) return; - QgsAction newAction( action.type(), action.name(), expandedAction, action.capture() ); + QgsAction newAction( act.type(), act.name(), expandedAction, act.capture() ); runAction( newAction ); } @@ -100,44 +95,44 @@ void QgsActionManager::clearActions() mActions.clear(); } -QList QgsActionManager::listActions() const +QList QgsActionManager::listActions( const QString& actionScope ) const { - return mActions; + if ( actionScope.isNull() ) + return mActions; + else + { + QList actions; + + Q_FOREACH ( const QgsAction& action, mActions ) + { + if ( action.actionScopes().contains( actionScope ) ) + actions.append( action ); + } + + return actions; + } } -void QgsActionManager::runAction( const QgsAction &action, void ( *executePython )( const QString & ) ) +void QgsActionManager::runAction( const QgsAction &action ) { if ( action.type() == QgsAction::OpenUrl ) { - QFileInfo finfo( action.action() ); + QFileInfo finfo( action.command() ); if ( finfo.exists() && finfo.isFile() ) - QDesktopServices::openUrl( QUrl::fromLocalFile( action.action() ) ); + QDesktopServices::openUrl( QUrl::fromLocalFile( action.command() ) ); else - QDesktopServices::openUrl( QUrl( action.action(), QUrl::TolerantMode ) ); + QDesktopServices::openUrl( QUrl( action.command(), QUrl::TolerantMode ) ); } else if ( action.type() == QgsAction::GenericPython ) { - if ( executePython ) - { - // deprecated - executePython( action.action() ); - } - else if ( smPythonExecute ) - { - // deprecated - smPythonExecute( action.action() ); - } - else - { - // TODO: capture output from QgsPythonRunner (like QgsRunProcess does) - QgsPythonRunner::run( action.action() ); - } + // TODO: capture output from QgsPythonRunner (like QgsRunProcess does) + QgsPythonRunner::run( action.command() ); } else { // The QgsRunProcess instance created by this static function // deletes itself when no longer needed. - QgsRunProcess::create( action.action(), action.capture() ); + QgsRunProcess::create( action.command(), action.capture() ); } } @@ -164,9 +159,15 @@ bool QgsActionManager::writeXml( QDomNode& layer_node, QDomDocument& doc ) const actionSetting.setAttribute( QStringLiteral( "name" ), action.name() ); actionSetting.setAttribute( QStringLiteral( "shortTitle" ), action.shortTitle() ); actionSetting.setAttribute( QStringLiteral( "icon" ), action.iconPath() ); - actionSetting.setAttribute( QStringLiteral( "action" ), action.action() ); + actionSetting.setAttribute( QStringLiteral( "action" ), action.command() ); actionSetting.setAttribute( QStringLiteral( "capture" ), action.capture() ); - actionSetting.setAttribute( QStringLiteral( "showInAttributeTable" ), action.showInAttributeTable() ); + + Q_FOREACH ( const QString& scope, action.actionScopes() ) + { + QDomElement actionScopeElem = doc.createElement( "actionScope" ); + actionScopeElem.setAttribute( "id", scope ); + actionSetting.appendChild( actionScopeElem ); + } aActions.appendChild( actionSetting ); } layer_node.appendChild( aActions ); @@ -188,14 +189,36 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) for ( int i = 0; i < actionsettings.size(); ++i ) { QDomElement setting = actionsettings.item( i ).toElement(); + + QDomNodeList actionScopeNodes = setting.elementsByTagName( "actionScope" ); + QSet actionScopes; + + if ( actionScopeNodes.isEmpty() ) + { + actionScopes + << QStringLiteral( "Canvas" ) + << QStringLiteral( "FieldSpecific" ) + << QStringLiteral( "AttributeTableRow" ) + << QStringLiteral( "FeatureForm" ); + } + else + { + for ( int j = 0; j < actionScopeNodes.length(); ++j ) + { + QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement(); + actionScopes << actionScopeElem.attribute( "id" ); + } + } + + mActions.append( QgsAction( static_cast< QgsAction::ActionType >( setting.attributeNode( QStringLiteral( "type" ) ).value().toInt() ), setting.attributeNode( QStringLiteral( "name" ) ).value(), setting.attributeNode( QStringLiteral( "action" ) ).value(), setting.attributeNode( QStringLiteral( "icon" ) ).value(), setting.attributeNode( QStringLiteral( "capture" ) ).value().toInt() != 0, - !setting.attributes().contains( QStringLiteral( "showInAttributeTable" ) ) || setting.attributeNode( QStringLiteral( "showInAttributeTable" ) ).value().toInt() != 0, - setting.attributeNode( QStringLiteral( "shortTitle" ) ).value() + setting.attributeNode( QStringLiteral( "shortTitle" ) ).value(), + actionScopes ) ); } @@ -203,4 +226,23 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) return true; } -void ( *QgsActionManager::smPythonExecute )( const QString & ) = nullptr; +QgsAction QgsActionManager::action( const QString& id ) +{ + Q_FOREACH ( const QgsAction& action, mActions ) + { + if ( action.id() == id ) + return action; + } + + return QgsAction(); +} + +void QgsActionManager::setDefaultAction( const QString& actionScope, const QString& actionId ) +{ + mDefaultActions[ actionScope ] = actionId; +} + +QgsAction QgsActionManager::defaultAction( const QString& actionScope ) +{ + return action( mDefaultActions.value( actionScope ).toString() ); +} diff --git a/src/core/qgsactionmanager.h b/src/core/qgsactionmanager.h index e737a46ef8fb..a9464a451c95 100644 --- a/src/core/qgsactionmanager.h +++ b/src/core/qgsactionmanager.h @@ -34,6 +34,7 @@ class QDomNode; class QDomDocument; class QgsPythonUtils; class QgsVectorLayer; +class QgsExpressionContextScope; class QgsExpressionContext; /** \ingroup core @@ -74,15 +75,12 @@ class CORE_EXPORT QgsActionManager */ void addAction( const QgsAction& action ); - //! Remove an action at given index - void removeAction( int index ); - /** Does the given values. defaultValueIndex is the index of the * field to be used if the action has a $currfield placeholder. * @note available in python bindings as doActionFeature */ - void doAction( int index, - const QgsFeature &feat, + void doAction( const QString& actionId, + const QgsFeature &feature, int defaultValueIndex = 0 ); /** Does the action using the expression engine to replace any embedded expressions @@ -91,7 +89,7 @@ class CORE_EXPORT QgsActionManager * @param feature feature to run action for * @param context expression context to evalute expressions under */ - void doAction( int index, + void doAction( const QString& actionId, const QgsFeature& feature, const QgsExpressionContext& context ); @@ -99,9 +97,10 @@ class CORE_EXPORT QgsActionManager void clearActions(); /** - * Return a list of all actions + * Return a list of actions that are available in the given action scope. + * If no action scope is provided, all actions will be returned. */ - QList listActions() const; + QList listActions( const QString& actionScope = QString() ) const; //! Return the layer QgsVectorLayer* layer() const { return mLayer; } @@ -113,40 +112,36 @@ class CORE_EXPORT QgsActionManager bool readXml( const QDomNode& layer_node ); /** - * Get the number of actions managed by this. - */ - int size() const { return mActions.size(); } - - /** - * Get the action at the specified index. + * Get an action by its id. + * + * @note Added in QGIS 3.0 */ - const QgsAction& at( int idx ) const { return mActions.at( idx ); } + QgsAction action( const QString& id ); /** - * Get the action at the specified index. + * Each scope can have a default action. This will be saved in the project + * file. + * + * @note Added in QGIS 3.0 */ - QgsAction operator[]( int idx ) const { return mActions[idx]; } + void setDefaultAction( const QString& actionScope, const QString& actionId ); /** - * Returns the index of the default action, or -1 if no default action is available. - * @see setDefaultAction() + * Each scope can have a default action. This will be saved in the project + * file. + * + * @note Added in QGIS 3.0 */ - int defaultAction() const { return mDefaultAction < 0 || mDefaultAction >= size() ? -1 : mDefaultAction; } - - /** - * Set the index of the default action. - * @param actionNumber index of action which should be made the default for the layer - * @see defaultAction() - */ - void setDefaultAction( int actionNumber ) { mDefaultAction = actionNumber ; } + QgsAction defaultAction( const QString& actionScope ); private: QList mActions; QgsVectorLayer *mLayer; static void ( *smPythonExecute )( const QString & ); - void runAction( const QgsAction &action, - void ( *executePython )( const QString & ) = nullptr ); + void runAction( const QgsAction &action ); + + QVariantMap mDefaultActions; int mDefaultAction; diff --git a/src/core/qgsactionscope.cpp b/src/core/qgsactionscope.cpp new file mode 100644 index 000000000000..99fe7aaf07a5 --- /dev/null +++ b/src/core/qgsactionscope.cpp @@ -0,0 +1,90 @@ +/*************************************************************************** + qgsactionscope.cpp - QgsActionScope + + --------------------- + begin : 1.11.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgsactionscope.h" +#include "qgsexpressioncontext.h" + +QgsActionScope::QgsActionScope() + : mExpressionContextScope( nullptr ) +{ +} + +QgsActionScope::QgsActionScope( const QString& id, const QString& title, const QString& description, const QgsExpressionContextScope& expressionContextScope ) + : mId( id ) + , mTitle( title ) + , mDescription( description ) + , mExpressionContextScope( expressionContextScope ) +{ +} + +bool QgsActionScope::operator==( const QgsActionScope& other ) const +{ + return other.mId == mId; +} + +QgsExpressionContextScope QgsActionScope::expressionContextScope() const +{ + return mExpressionContextScope; +} + +void QgsActionScope::setExpressionContextScope( const QgsExpressionContextScope& expressionContextScope ) +{ + mExpressionContextScope = expressionContextScope; +} + +QString QgsActionScope::id() const +{ + return mId; +} + +void QgsActionScope::setId( const QString& name ) +{ + mId = name; +} + +bool QgsActionScope::isValid() const +{ + return !mId.isNull(); +} + +QString QgsActionScope::title() const +{ + return mTitle; +} + +void QgsActionScope::setTitle( const QString& title ) +{ + mTitle = title; +} + +QString QgsActionScope::description() const +{ + return mDescription; +} + +void QgsActionScope::setDescription( const QString& description ) +{ + mDescription = description; +} + +uint qHash( const QgsActionScope& key, uint seed ) +{ + uint hash = seed; + + hash |= qHash( key.expressionContextScope().variableNames().join( ',' ), seed ); + hash |= qHash( key.id(), seed ); + + return hash; +} diff --git a/src/core/qgsactionscope.h b/src/core/qgsactionscope.h new file mode 100644 index 000000000000..ef0d60f474d8 --- /dev/null +++ b/src/core/qgsactionscope.h @@ -0,0 +1,126 @@ +/*************************************************************************** + qgsactionscope.h - QgsActionScope + + --------------------- + begin : 1.11.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSACTIONSCOPE_H +#define QGSACTIONSCOPE_H + +#include +#include "qgsexpressioncontext.h" + +/** \ingroup core + * An action scope defines a "place" for an action to be shown and may add + * additional expression variables. + * Each QgsAction can be available in one or several action scopes. + * + * Examples: + * --------- + * + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Canvas
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show for canvas tools. Adds `@clicked_x` and `@clicked_y` in map coordinates.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  AttributeTable
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table for each row.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  FieldSpecific
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in context menus for individual fields (e.g. attribute table). Adds `@field_index`, `@field_name` and `@field_value`.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Selection
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table and work on the layer or selection.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + * + * \since QGIS 3.0 + */ + +class CORE_EXPORT QgsActionScope +{ + public: + + /** + * Creates a new invalid action scope. + */ + explicit QgsActionScope(); + + /** + * Creates a new action scope. + * For details concerning the parameters check the documentation + * of the corresponding properties. + */ + explicit QgsActionScope( const QString& id, const QString& title, const QString& description, const QgsExpressionContextScope& expressionContextScope = QgsExpressionContextScope() ); + + /** + * Compares two action scopes + */ + bool operator==( const QgsActionScope& other ) const; + + /** + * An expression scope may offer additional variables for an action scope. + * This can be an `field_name` for the attribute which was clicked or + * `clicked_x` and `clicked_y` for actions which are available as map canvas clicks. + * + * @note Added in QGIS 3.0 + */ + QgsExpressionContextScope expressionContextScope() const; + + /** + * \copydoc expressionContextScope() + */ + void setExpressionContextScope( const QgsExpressionContextScope& expressionContextScope ); + + /** + * A unique identifier for this action scope. + * + * @note Added in QGIS 3.0 + */ + QString id() const; + + //! \copydoc id() + void setId( const QString& id ); + + /** + * The title is a human readable and translated string that will be + * presented to the user in the properties dialog. + * + * @note Added in QGIS 3.0 + */ + QString title() const; + //! \copydoc title() + void setTitle( const QString& title ); + + /** + * The description should be a longer description of where actions in this scope + * are available. It is not necessary to list the available expression variables + * in here, they are extracted automatically from the expressionContextScope(). + * + * @note Added in QGIS 3.0 + */ + QString description() const; + //! \copydoc description() + void setDescription( const QString& description ); + + /** + * Returns if this scope is valid. + * + * @note Added in QGIS 3.0 + */ + bool isValid() const; + + private: + QString mId; + QString mTitle; + QString mDescription; + QgsExpressionContextScope mExpressionContextScope; +}; + +CORE_EXPORT uint qHash( const QgsActionScope& key, uint seed = 0 ); + +#endif // QGSACTIONSCOPE_H diff --git a/src/core/qgsactionscoperegistry.cpp b/src/core/qgsactionscoperegistry.cpp new file mode 100644 index 000000000000..f21ee229c812 --- /dev/null +++ b/src/core/qgsactionscoperegistry.cpp @@ -0,0 +1,73 @@ +/*************************************************************************** + qgsactionscoperegistry.cpp - QgsActionScopeRegistry + + --------------------- + begin : 1.11.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgsactionscoperegistry.h" + +#include "qgsexpressioncontext.h" + +QgsActionScopeRegistry::QgsActionScopeRegistry( QObject* parent ) + : QObject( parent ) +{ + // Register some default action scopes: + + QgsExpressionContextScope canvasScope; + canvasScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "clicked_x" ), 25, true ) ); + canvasScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "clicked_y" ), 30, true ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "Canvas" ), tr( "Canvas" ), tr( "Available for the action map tool on the canvas." ), canvasScope ) ); + + QgsExpressionContextScope fieldScope; + fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "current_field" ), QStringLiteral( "[field_value]" ), true ) ); + fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_index" ), 0, true ) ); + fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), "[field_name]", true ) ); + fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_value" ), "[field_value]", true ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "FieldSpecific" ), tr( "Field Specific" ), tr( "Available for individual fields in the attribute table." ), fieldScope ) ); + + mActionScopes.insert( QgsActionScope( QStringLiteral( "AttributeTableRow" ), tr( "Attribute Table Row" ), tr( "Available for individual features (rows) in the attribute table." ) ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "FeatureForm" ), tr( "Feature Form" ), tr( "Available for individual features in their form." ) ) ); + + mActionScopes.insert( QgsActionScope( QStringLiteral( "AttributeTable" ), tr( "Attribute Table" ), tr( "Available as layer global action in the attribute table." ) ) ); +} + +QSet QgsActionScopeRegistry::actionScopes() const +{ + return mActionScopes; +} + +void QgsActionScopeRegistry::registerActionScope( const QgsActionScope& actionScope ) +{ + mActionScopes.insert( actionScope ); + + emit actionScopesChanged(); +} + +void QgsActionScopeRegistry::unregisterActionScope( const QgsActionScope& actionScope ) +{ + mActionScopes.remove( actionScope ); + + emit actionScopesChanged(); +} + +QgsActionScope QgsActionScopeRegistry::actionScope( const QString& id ) +{ + Q_FOREACH ( const QgsActionScope& actionScope, mActionScopes ) + { + if ( actionScope.id() == id ) + { + return actionScope; + } + } + + return QgsActionScope(); +} diff --git a/src/core/qgsactionscoperegistry.h b/src/core/qgsactionscoperegistry.h new file mode 100644 index 000000000000..d120421c3dc9 --- /dev/null +++ b/src/core/qgsactionscoperegistry.h @@ -0,0 +1,81 @@ +/*************************************************************************** + qgsactionscoperegistry.h - QgsActionScopeRegistry + + --------------------- + begin : 1.11.2016 + copyright : (C) 2016 by Matthias Kuhn + email : matthias@opengis.ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#ifndef QGSACTIONSCOPEREGISTRY_H +#define QGSACTIONSCOPEREGISTRY_H + +#include +#include +#include "qgsactionscope.h" + +/** \ingroup core + * The action scope registry is an application wide registry that + * contains a list of available action scopes. + * Some scopes are available by default, additional ones can be registered + * at runtime by plugins or custom applications. + * + * To get access use the QgsApplication: + * + * ``` + * QgsApplication::actionScopeRegistry() + * ``` + * + * @note Added in QGIS 3.0 + */ +class CORE_EXPORT QgsActionScopeRegistry : public QObject +{ + Q_OBJECT + /** + * The action scopes which are currently registered and available. + * + * \read actionScopes() + * \notify actionScopesChanged() + * + * \since QGIS 3.0 + */ + Q_PROPERTY( QSet actionScopes READ actionScopes NOTIFY actionScopesChanged ) + + public: + explicit QgsActionScopeRegistry( QObject* parent = nullptr ); + + /** + * Get all registered action scopes. + */ + QSet actionScopes() const; + + /** + * Register an additional action scope. + * + * @note Added in QGIS 3.0 + */ + void registerActionScope( const QgsActionScope& actionScope ); + + /** + * Unregister an additional action scope. + * + * @note Added in QGIS 3.0 + */ + void unregisterActionScope( const QgsActionScope& actionScope ); + + QgsActionScope actionScope( const QString& id ); + + signals: + void actionScopesChanged(); + + private: + QSet mActionScopes; +}; + +#endif // QGSACTIONSCOPEREGISTRY_H diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 56c48264adcd..9c4f52a99d9b 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -23,6 +23,7 @@ #include "qgsnetworkaccessmanager.h" #include "qgsproviderregistry.h" #include "qgsexpression.h" +#include "qgsactionscoperegistry.h" #include #include @@ -103,6 +104,8 @@ QgsApplication::QgsApplication( int & argc, char ** argv, bool GUIenabled, const { sPlatformName = platformName; + mActionScopeRegistry = new QgsActionScopeRegistry(); + init( customConfigPath ); // init can also be called directly by e.g. unit tests that don't inherit QApplication. } @@ -233,6 +236,12 @@ void QgsApplication::init( QString customConfigPath ) QgsApplication::~QgsApplication() { + delete mActionScopeRegistry; +} + +QgsApplication* QgsApplication::instance() +{ + return qobject_cast( QCoreApplication::instance() ); } bool QgsApplication::event( QEvent * event ) @@ -411,7 +420,7 @@ QString QgsApplication::iconPath( const QString& iconFile ) QIcon QgsApplication::getThemeIcon( const QString &theName ) { - QgsApplication* app = qobject_cast( instance() ); + QgsApplication* app = instance(); if ( app && app->mIconCache.contains( theName ) ) return app->mIconCache.value( theName ); @@ -1233,6 +1242,11 @@ void QgsApplication::copyPath( const QString& src, const QString& dst ) } } +QgsActionScopeRegistry* QgsApplication::actionScopeRegistry() +{ + return instance()->mActionScopeRegistry; +} + bool QgsApplication::createDB( QString *errorMessage ) { // set a working directory up for gdal to write .aux.xml files into diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index 551610f42bc4..d8d2f44cf380 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -22,6 +22,8 @@ #include #include +class QgsActionScopeRegistry; + /** \ingroup core * Extends QApplication to provide access to QGIS specific resources such * as theme paths, database paths etc. @@ -34,6 +36,7 @@ typedef void XEvent; class CORE_EXPORT QgsApplication : public QApplication { Q_OBJECT + public: static const char* QGIS_ORGANIZATION_NAME; static const char* QGIS_ORGANIZATION_DOMAIN; @@ -41,6 +44,13 @@ class CORE_EXPORT QgsApplication : public QApplication QgsApplication( int & argc, char ** argv, bool GUIenabled, const QString& customConfigPath = QString(), const QString& platformName = "desktop" ); virtual ~QgsApplication(); + /** + * Returns the singleton instance of the QgsApplication. + * + * @note Added in QGIS 3.0 + */ + static QgsApplication* instance(); + /** This method initialises paths etc for QGIS. Called by the ctor or call it manually when your app does not extend the QApplication class. @note you will probably want to call initQgis too to load the providers in @@ -364,6 +374,11 @@ class CORE_EXPORT QgsApplication : public QApplication } #endif + /** + * Returns the action scope registry. + */ + static QgsActionScopeRegistry* actionScopeRegistry(); + public slots: /** Causes the application instance to emit the settingsChanged() signal. This should @@ -429,6 +444,8 @@ class CORE_EXPORT QgsApplication : public QApplication static QString sPlatformName; QMap mIconCache; + + QgsActionScopeRegistry* mActionScopeRegistry; }; #endif diff --git a/src/gui/attributetable/qgsattributetablemodel.cpp b/src/gui/attributetable/qgsattributetablemodel.cpp index 147bde5cfbee..2a75d2897f80 100644 --- a/src/gui/attributetable/qgsattributetablemodel.cpp +++ b/src/gui/attributetable/qgsattributetablemodel.cpp @@ -737,7 +737,7 @@ void QgsAttributeTableModel::reload( const QModelIndex &index1, const QModelInde } -void QgsAttributeTableModel::executeAction( int action, const QModelIndex &idx ) const +void QgsAttributeTableModel::executeAction( const QString& action, const QModelIndex &idx ) const { QgsFeature f = feature( idx ); layer()->actions()->doAction( action, f, fieldIdx( idx.column() ) ); diff --git a/src/gui/attributetable/qgsattributetablemodel.h b/src/gui/attributetable/qgsattributetablemodel.h index f0903bc911b2..1e465199f8ee 100644 --- a/src/gui/attributetable/qgsattributetablemodel.h +++ b/src/gui/attributetable/qgsattributetablemodel.h @@ -171,7 +171,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel /** * Execute an action */ - void executeAction( int action, const QModelIndex &idx ) const; + void executeAction( const QString& action, const QModelIndex &idx ) const; /** * Execute a QgsMapLayerAction diff --git a/src/gui/attributetable/qgsattributetableview.cpp b/src/gui/attributetable/qgsattributetableview.cpp index bc0bb8e5131f..9453dcc8f9c6 100644 --- a/src/gui/attributetable/qgsattributetableview.cpp +++ b/src/gui/attributetable/qgsattributetableview.cpp @@ -176,24 +176,19 @@ QWidget* QgsAttributeTableView::createActionWidget( QgsFeatureId fid ) QAction* defaultAction = nullptr; // first add user created layer actions - QgsActionManager* actions = mFilterModel->layer()->actions(); - for ( int i = 0; i < actions->size(); ++i ) + QList actions = mFilterModel->layer()->actions()->listActions( QStringLiteral( "AttributeTableRow" ) ); + Q_FOREACH ( const QgsAction& action, actions ) { - const QgsAction& action = actions->at( i ); - - if ( !action.showInAttributeTable() ) - continue; - QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QLatin1String( "" ); QAction* act = new QAction( action.icon(), actionTitle, container ); act->setToolTip( action.name() ); act->setData( "user_action" ); - act->setProperty( "action_id", i ); act->setProperty( "fid", fid ); + act->setProperty( "action_id", action.id() ); connect( act, SIGNAL( triggered( bool ) ), this, SLOT( actionTriggered() ) ); actionList << act; - if ( actions->defaultAction() == i ) + if ( mFilterModel->layer()->actions()->defaultAction( QStringLiteral( "AttributeTableRow" ) ).id() == action.id() ) defaultAction = act; } @@ -242,8 +237,11 @@ QWidget* QgsAttributeTableView::createActionWidget( QgsFeatureId fid ) static_cast< QHBoxLayout* >( container->layout() )->addStretch(); } + // TODO: Rethink default actions +#if 0 if ( toolButton && !toolButton->actions().isEmpty() && actions->defaultAction() == -1 ) toolButton->setDefaultAction( toolButton->actions().at( 0 ) ); +#endif return container; } @@ -416,7 +414,7 @@ void QgsAttributeTableView::actionTriggered() if ( action->data().toString() == QLatin1String( "user_action" ) ) { - mFilterModel->layer()->actions()->doAction( action->property( "action_id" ).toInt(), f ); + mFilterModel->layer()->actions()->doAction( action->property( "action_id" ).toString(), f ); } else if ( action->data().toString() == QLatin1String( "map_layer_action" ) ) { diff --git a/src/gui/attributetable/qgsdualview.cpp b/src/gui/attributetable/qgsdualview.cpp index 0f91c34afd13..412442c41b17 100644 --- a/src/gui/attributetable/qgsdualview.cpp +++ b/src/gui/attributetable/qgsdualview.cpp @@ -390,20 +390,18 @@ void QgsDualView::viewWillShowContextMenu( QMenu* menu, const QModelIndex& atInd } //add user-defined actions to context menu - if ( mLayerCache->layer()->actions()->size() != 0 ) + QList actions = mLayerCache->layer()->actions()->listActions( QStringLiteral( "FieldSpecific" ) ); + if ( !actions.isEmpty() ) { - - QAction *a = menu->addAction( tr( "Run layer action" ) ); + QAction* a = menu->addAction( tr( "Run layer action" ) ); a->setEnabled( false ); - for ( int i = 0; i < mLayerCache->layer()->actions()->size(); i++ ) + Q_FOREACH ( const QgsAction& action, actions ) { - const QgsAction &action = mLayerCache->layer()->actions()->at( i ); - if ( !action.runable() ) continue; - QgsAttributeTableAction *a = new QgsAttributeTableAction( action.name(), this, i, sourceIndex ); + QgsAttributeTableAction* a = new QgsAttributeTableAction( action.name(), this, action.id(), sourceIndex ); menu->addAction( action.name(), a, SLOT( execute() ) ); } } @@ -424,7 +422,7 @@ void QgsDualView::viewWillShowContextMenu( QMenu* menu, const QModelIndex& atInd } menu->addSeparator(); - QgsAttributeTableAction *a = new QgsAttributeTableAction( tr( "Open form" ), this, -1, sourceIndex ); + QgsAttributeTableAction* a = new QgsAttributeTableAction( tr( "Open form" ), this, QString(), sourceIndex ); menu->addAction( tr( "Open form" ), a, SLOT( featureForm() ) ); } diff --git a/src/gui/attributetable/qgsdualview.h b/src/gui/attributetable/qgsdualview.h index c5a2ad6c6c58..e00fcf63077e 100644 --- a/src/gui/attributetable/qgsdualview.h +++ b/src/gui/attributetable/qgsdualview.h @@ -353,7 +353,7 @@ class GUI_EXPORT QgsAttributeTableAction : public QAction Q_OBJECT public: - QgsAttributeTableAction( const QString &name, QgsDualView *dualView, int action, const QModelIndex &fieldIdx ) + QgsAttributeTableAction( const QString &name, QgsDualView *dualView, const QString& action, const QModelIndex &fieldIdx ) : QAction( name, dualView ) , mDualView( dualView ) , mAction( action ) @@ -366,7 +366,7 @@ class GUI_EXPORT QgsAttributeTableAction : public QAction private: QgsDualView* mDualView; - int mAction; + QString mAction; QModelIndex mFieldIdx; }; diff --git a/src/gui/attributetable/qgsfeaturelistview.cpp b/src/gui/attributetable/qgsfeaturelistview.cpp index 955768c5e315..28191d3b89e0 100644 --- a/src/gui/attributetable/qgsfeaturelistview.cpp +++ b/src/gui/attributetable/qgsfeaturelistview.cpp @@ -317,7 +317,7 @@ void QgsFeatureListView::contextMenuEvent( QContextMenuEvent *event ) { QgsFeature feature = mModel->data( index, QgsFeatureListModel::FeatureRole ).value(); - QgsActionMenu* menu = new QgsActionMenu( mModel->layerCache()->layer(), &feature, this ); + QgsActionMenu* menu = new QgsActionMenu( mModel->layerCache()->layer(), feature, QStringLiteral( "AttributeTableRow" ), this ); menu->exec( event->globalPos() ); } } diff --git a/src/gui/qgsactionmenu.cpp b/src/gui/qgsactionmenu.cpp index 03cb325a8df8..f9683b08f446 100644 --- a/src/gui/qgsactionmenu.cpp +++ b/src/gui/qgsactionmenu.cpp @@ -19,24 +19,21 @@ #include "qgsactionmanager.h" #include "qgsfeatureiterator.h" -QgsActionMenu::QgsActionMenu( QgsVectorLayer* layer, const QgsFeature* feature, QWidget* parent ) +QgsActionMenu::QgsActionMenu( QgsVectorLayer* layer, const QgsFeature& feature, const QString& actionScope, QWidget* parent ) : QMenu( parent ) , mLayer( layer ) - , mActions( nullptr ) , mFeature( feature ) - , mFeatureId( feature->id() ) - , mOwnsFeature( false ) + , mFeatureId( feature.id() ) + , mActionScope( actionScope ) { init(); } -QgsActionMenu::QgsActionMenu( QgsVectorLayer* layer, const QgsFeatureId fid, QWidget* parent ) +QgsActionMenu::QgsActionMenu( QgsVectorLayer* layer, const QgsFeatureId fid, const QString& actionScope, QWidget* parent ) : QMenu( parent ) , mLayer( layer ) - , mActions( nullptr ) - , mFeature( nullptr ) , mFeatureId( fid ) - , mOwnsFeature( false ) + , mActionScope( actionScope ) { init(); } @@ -50,20 +47,11 @@ void QgsActionMenu::init() reloadActions(); } -const QgsFeature* QgsActionMenu::feature() +QgsFeature QgsActionMenu::feature() { - if ( !mFeature || !mFeature->isValid() ) + if ( !mFeature.isValid() ) { - QgsFeature* feat = new QgsFeature(); - if ( mActions->layer()->getFeatures( QgsFeatureRequest( mFeatureId ) ).nextFeature( *feat ) ) - { - mFeature = feat; - mOwnsFeature = true; - } - else - { - delete feat; - } + mLayer->getFeatures( QgsFeatureRequest( mFeatureId ) ).nextFeature( mFeature ); } return mFeature; @@ -71,23 +59,16 @@ const QgsFeature* QgsActionMenu::feature() QgsActionMenu::~QgsActionMenu() { - delete mActions; - - if ( mOwnsFeature ) - delete mFeature; } -void QgsActionMenu::setFeature( QgsFeature* feature ) +void QgsActionMenu::setFeature( const QgsFeature& feature ) { - if ( mOwnsFeature ) - delete mFeature; - mOwnsFeature = false; mFeature = feature; } void QgsActionMenu::triggerAction() { - if ( !feature() ) + if ( !feature().isValid() ) return; QAction* action = qobject_cast( sender() ); @@ -104,12 +85,19 @@ void QgsActionMenu::triggerAction() if ( data.actionType == MapLayerAction ) { - QgsMapLayerAction* mapLayerAction = data.actionId.action; - mapLayerAction->triggerForFeature( data.mapLayer, feature() ); + QgsMapLayerAction* mapLayerAction = data.actionData.value(); + mapLayerAction->triggerForFeature( data.mapLayer, &mFeature ); } else if ( data.actionType == AttributeAction ) { - mActions->doAction( data.actionId.id, *feature() ); + // define custom substitutions: layer id and clicked coords + QgsExpressionContext context = mLayer->createExpressionContext(); + + QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "action_scope" ), mActionScope, true ) ); + context << actionScope; + QgsAction act = data.actionData.value(); + act.run( context ); } } @@ -117,29 +105,26 @@ void QgsActionMenu::reloadActions() { clear(); - delete mActions; - mActions = new QgsActionManager( *mLayer->actions() ); + mActions = mLayer->actions()->listActions( mActionScope ); - for ( int idx = 0; idx < mActions->size(); ++idx ) + Q_FOREACH ( const QgsAction& action, mActions ) { - const QgsAction& qaction( mActions->at( idx ) ); - - QAction* action = new QAction( qaction.icon(), qaction.name(), this ); - action->setData( QVariant::fromValue( ActionData( idx, mFeatureId, mLayer ) ) ); - action->setIcon( qaction.icon() ); + QAction* qAction = new QAction( action.icon(), action.name(), this ); + qAction->setData( QVariant::fromValue( ActionData( action, mFeatureId, mLayer ) ) ); + qAction->setIcon( action.icon() ); // Only enable items on supported platforms - if ( !qaction.runable() ) + if ( !action.runable() ) { - action->setEnabled( false ); - action->setToolTip( tr( "Not supported on your platform" ) ); + qAction->setEnabled( false ); + qAction->setToolTip( tr( "Not supported on your platform" ) ); } else { - action->setToolTip( qaction.action() ); + qAction->setToolTip( action.command() ); } - connect( action, SIGNAL( triggered() ), this, SLOT( triggerAction() ) ); - addAction( action ); + connect( qAction, &QAction::triggered, this, &QgsActionMenu::triggerAction ); + addAction( qAction ); } QList mapLayerActions = QgsMapLayerActionRegistry::instance()->mapLayerActions( mLayer, QgsMapLayerAction::SingleFeature ); @@ -152,13 +137,34 @@ void QgsActionMenu::reloadActions() for ( int i = 0; i < mapLayerActions.size(); ++i ) { QgsMapLayerAction* qaction = mapLayerActions.at( i ); - QAction* action = new QAction( qaction->icon(), qaction->text(), this ); - action->setData( QVariant::fromValue( ActionData( qaction, mFeatureId, mLayer ) ) ); - addAction( action ); - connect( action, SIGNAL( triggered() ), this, SLOT( triggerAction() ) ); + QAction* qAction = new QAction( qaction->icon(), qaction->text(), this ); + qAction->setData( QVariant::fromValue( ActionData( qaction, mFeatureId, mLayer ) ) ); + addAction( qAction ); + connect( qAction, &QAction::triggered, this, &QgsActionMenu::triggerAction ); } } emit reinit(); } + +QgsActionMenu::ActionData::ActionData( QgsMapLayerAction* action, QgsFeatureId featureId, QgsMapLayer* mapLayer ) + : actionType( MapLayerAction ) + , actionData( QVariant::fromValue( action ) ) + , featureId( featureId ) + , mapLayer( mapLayer ) +{} + + +QgsActionMenu::ActionData::ActionData( const QgsAction& action, QgsFeatureId featureId, QgsMapLayer* mapLayer ) + : actionType( AttributeAction ) + , actionData( QVariant::fromValue( action ) ) + , featureId( featureId ) + , mapLayer( mapLayer ) +{} + +QgsActionMenu::ActionData::ActionData() + : actionType( Invalid ) + , featureId( 0 ) + , mapLayer( nullptr ) +{} diff --git a/src/gui/qgsactionmenu.h b/src/gui/qgsactionmenu.h index b5d84cf13321..b817243f4710 100644 --- a/src/gui/qgsactionmenu.h +++ b/src/gui/qgsactionmenu.h @@ -20,6 +20,7 @@ #include #include "qgsfeature.h" +#include "qgsaction.h" class QgsMapLayer; class QgsMapLayerAction; @@ -44,37 +45,12 @@ class GUI_EXPORT QgsActionMenu : public QMenu struct ActionData { - ActionData() - : actionType( Invalid ) - , actionId( 0 ) - , featureId( 0 ) - , mapLayer( nullptr ) - {} - - ActionData( int actionId, QgsFeatureId featureId, QgsMapLayer* mapLayer ) - : actionType( AttributeAction ) - , actionId( actionId ) - , featureId( featureId ) - , mapLayer( mapLayer ) - {} - - ActionData( QgsMapLayerAction* action, QgsFeatureId featureId, QgsMapLayer* mapLayer ) - : actionType( MapLayerAction ) - , actionId( action ) - , featureId( featureId ) - , mapLayer( mapLayer ) - {} + ActionData(); + ActionData( const QgsAction& action, QgsFeatureId featureId, QgsMapLayer* mapLayer ); + ActionData( QgsMapLayerAction* action, QgsFeatureId featureId, QgsMapLayer* mapLayer ); ActionType actionType; - - union aid - { - aid( int i ) : id( i ) {} - aid( QgsMapLayerAction* a ) : action( a ) {} - int id; - QgsMapLayerAction* action; - } actionId; - + QVariant actionData; QgsFeatureId featureId; QgsMapLayer* mapLayer; }; @@ -87,7 +63,7 @@ class GUI_EXPORT QgsActionMenu : public QMenu * for the lifetime of this object. * @param parent The usual QWidget parent. */ - explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeature *feature, QWidget *parent = nullptr ); + explicit QgsActionMenu( QgsVectorLayer* layer, const QgsFeature& feature, const QString& actionScope, QWidget *parent = nullptr ); /** * Constructs a new QgsActionMenu @@ -96,7 +72,7 @@ class GUI_EXPORT QgsActionMenu : public QMenu * @param fid The feature id of the feature for which this action will be run. * @param parent The usual QWidget parent. */ - explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, QWidget *parent = nullptr ); + explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, const QString& actionScope, QWidget *parent = nullptr ); /** * Destructor @@ -109,7 +85,7 @@ class GUI_EXPORT QgsActionMenu : public QMenu * @param feature A feature. Will not take ownership. It's the callers responsibility to keep the feature * as long as the menu is displayed and the action is running. */ - void setFeature( QgsFeature* feature ); + void setFeature( const QgsFeature& feature ); private slots: void triggerAction(); @@ -120,15 +96,16 @@ class GUI_EXPORT QgsActionMenu : public QMenu private: void init(); - const QgsFeature* feature(); + QgsFeature feature(); QgsVectorLayer* mLayer; - QgsActionManager* mActions; - const QgsFeature* mFeature; + QList mActions; + QgsFeature mFeature; QgsFeatureId mFeatureId; - bool mOwnsFeature; + QString mActionScope; }; + Q_DECLARE_METATYPE( QgsActionMenu::ActionData ) #endif // QGSACTIONMENU_H diff --git a/src/gui/qgsattributedialog.cpp b/src/gui/qgsattributedialog.cpp index 2aa9d6b77abf..d8b6568829d2 100644 --- a/src/gui/qgsattributedialog.cpp +++ b/src/gui/qgsattributedialog.cpp @@ -104,7 +104,7 @@ void QgsAttributeDialog::init( QgsVectorLayer* layer, QgsFeature* feature, const connect( buttonBox, SIGNAL( accepted() ), this, SLOT( accept() ) ); connect( layer, SIGNAL( destroyed() ), this, SLOT( close() ) ); - QgsActionMenu* menu = new QgsActionMenu( layer, &mAttributeForm->feature(), this ); + QgsActionMenu* menu = new QgsActionMenu( layer, mAttributeForm->feature(), QStringLiteral( "AttributeTableRow" ), this ); if ( !menu->actions().isEmpty() ) { QMenuBar* menuBar = new QMenuBar( this ); diff --git a/src/gui/qgsidentifymenu.cpp b/src/gui/qgsidentifymenu.cpp index 0478ca81f416..21e8f7332bd4 100644 --- a/src/gui/qgsidentifymenu.cpp +++ b/src/gui/qgsidentifymenu.cpp @@ -266,7 +266,7 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QListactions().isEmpty(); delete featureActionMenu; } @@ -351,7 +351,7 @@ void QgsIdentifyMenu::addVectorLayer( QgsVectorLayer* layer, const QList customFeatureActions = mCustomActionRegistry.mapLayerActions( layer, QgsMapLayerAction::SingleFeature ); if ( mShowFeatureActions ) { - featureActionMenu = new QgsActionMenu( layer, result.mFeature.id(), layerMenu ); + featureActionMenu = new QgsActionMenu( layer, result.mFeature, QStringLiteral( "AttributeTableRow" ), layerMenu ); } // feature title diff --git a/src/ui/qgsattributeactiondialogbase.ui b/src/ui/qgsattributeactiondialogbase.ui index 5ba933a0f414..c5791ac51baf 100644 --- a/src/ui/qgsattributeactiondialogbase.ui +++ b/src/ui/qgsattributeactiondialogbase.ui @@ -175,7 +175,7 @@ - Show In Attribute Table + Action Scopes diff --git a/src/ui/qgsattributeactionpropertiesdialogbase.ui b/src/ui/qgsattributeactionpropertiesdialogbase.ui index 49e3549b59a5..da5888c06dc3 100644 --- a/src/ui/qgsattributeactionpropertiesdialogbase.ui +++ b/src/ui/qgsattributeactionpropertiesdialogbase.ui @@ -14,6 +14,19 @@ Form + + + + Enter the name of an action here. The name should be unique (qgis will make it unique if necessary). + + + Description + + + mActionName + + + @@ -47,7 +60,64 @@ - + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + Type + + + mActionType + + + + + + + + 0 + 0 + + + + + Generic + + + + + Python + + + + + Mac + + + + + Windows + + + + + Unix + + + + + Open + + + + + @@ -135,43 +205,6 @@ - - - - Type - - - mActionType - - - - - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - Enter the name of an action here. The name should be unique (qgis will make it unique if necessary). - - - Description - - - mActionName - - - - - - - Icon - - - @@ -179,44 +212,11 @@ - - - - - 0 - 0 - + + + + Leave empty to use only icon - - - Generic - - - - - Python - - - - - Mac - - - - - Windows - - - - - Unix - - - - - Open - - @@ -232,6 +232,13 @@ + + + + Icon + + + @@ -245,18 +252,12 @@ - - - - Leave empty to use only icon - - - - - - - Show in attribute table + + + + Action Scopes + diff --git a/src/ui/qgsattributetabledialog.ui b/src/ui/qgsattributetabledialog.ui index 4887bb9ede77..77c184df3c2d 100644 --- a/src/ui/qgsattributetabledialog.ui +++ b/src/ui/qgsattributetabledialog.ui @@ -187,6 +187,8 @@ + + @@ -613,6 +615,15 @@ Conditional formatting + + + + :/images/themes/default/mAction.svg:/images/themes/default/mAction.svg + + + Actions + + From e7d8b2cabf5063f87428157438c68a0dfe812d4d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 3 Nov 2016 19:09:21 +0100 Subject: [PATCH 776/897] Rename scopes to "Field", "Feature", "Layer" --- src/app/qgsattributetabledialog.cpp | 2 +- src/app/qgsfeatureaction.cpp | 2 +- src/app/qgsidentifyresultsdialog.cpp | 4 ++-- src/core/qgsactionmanager.cpp | 21 ++++++++++++++----- src/core/qgsactionmanager.h | 3 --- src/core/qgsactionscoperegistry.cpp | 9 +++----- .../attributetable/qgsattributetableview.cpp | 2 +- src/gui/attributetable/qgsdualview.cpp | 2 +- 8 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 604625acb0ec..1b2d29405922 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -309,7 +309,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mActionSearchForm->setToolTip( tr( "Search is not supported when using custom UI forms" ) ); } - QList actions = mLayer->actions()->listActions( QStringLiteral( "AttributeTable" ) ); + QList actions = mLayer->actions()->listActions( QStringLiteral( "Layer" ) ); if ( actions.isEmpty() ) { diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index 3a2dd8b62c0e..8012c2e79b1e 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -66,7 +66,7 @@ QgsAttributeDialog *QgsFeatureAction::newDialog( bool cloneFeature ) QgsAttributeDialog *dialog = new QgsAttributeDialog( mLayer, f, cloneFeature, parentWidget(), true, context ); dialog->setWindowFlags( dialog->windowFlags() | Qt::Tool ); - QList actions = mLayer->actions()->listActions(); + QList actions = mLayer->actions()->listActions( QStringLiteral( "Feature" ) ); if ( !actions.isEmpty() ) { dialog->setContextMenuPolicy( Qt::ActionsContextMenu ); diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index b1894e223e86..4a30303afdaf 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -480,7 +480,7 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat //get valid QgsMapLayerActions for this layer QList< QgsMapLayerAction* > registeredActions = QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ); - QList actions = vlayer->actions()->listActions( QStringLiteral( "AttributeTableRow" ) ); + QList actions = vlayer->actions()->listActions( QStringLiteral( "Feature" ) ); if ( !vlayer->fields().isEmpty() || !actions.isEmpty() || !registeredActions.isEmpty() ) { @@ -1092,7 +1092,7 @@ void QgsIdentifyResultsDialog::contextMenuEvent( QContextMenuEvent* event ) if ( featItem && vlayer ) { - QList actions = vlayer->actions()->listActions( QStringLiteral( "FieldSpecific" ) ); + QList actions = vlayer->actions()->listActions( QStringLiteral( "Field" ) ); if ( !actions.isEmpty() ) { mActionPopup->addSeparator(); diff --git a/src/core/qgsactionmanager.cpp b/src/core/qgsactionmanager.cpp index c793d5784dc6..ae0ffee2782f 100644 --- a/src/core/qgsactionmanager.cpp +++ b/src/core/qgsactionmanager.cpp @@ -150,7 +150,13 @@ QgsExpressionContext QgsActionManager::createExpressionContext() const bool QgsActionManager::writeXml( QDomNode& layer_node, QDomDocument& doc ) const { QDomElement aActions = doc.createElement( QStringLiteral( "attributeactions" ) ); - aActions.setAttribute( QStringLiteral( "default" ), mDefaultAction ); + for ( QVariantMap::const_iterator defaultAction = mDefaultActions.constBegin(); defaultAction != mDefaultActions.constEnd(); ++ defaultAction ) + { + QDomElement defaultActionElement = doc.createElement( QStringLiteral( "defaultAction" ) ); + defaultActionElement.setAttribute( QStringLiteral( "key" ), defaultAction.key() ); + defaultActionElement.setAttribute( QStringLiteral( "value" ), defaultAction.value().toString() ); + aActions.appendChild( defaultActionElement ); + } Q_FOREACH ( const QgsAction& action, mActions ) { @@ -183,9 +189,7 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) if ( !aaNode.isNull() ) { - mDefaultAction = aaNode.toElement().attribute( QStringLiteral( "default" ), 0 ).toInt(); - - QDomNodeList actionsettings = aaNode.childNodes(); + QDomNodeList actionsettings = aaNode.toElement().elementsByTagName( QStringLiteral( "actionsetting" ) ); for ( int i = 0; i < actionsettings.size(); ++i ) { QDomElement setting = actionsettings.item( i ).toElement(); @@ -210,7 +214,6 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) } } - mActions.append( QgsAction( static_cast< QgsAction::ActionType >( setting.attributeNode( QStringLiteral( "type" ) ).value().toInt() ), setting.attributeNode( QStringLiteral( "name" ) ).value(), @@ -222,6 +225,14 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) ) ); } + + QDomNodeList defaultActionNodes = aaNode.toElement().elementsByTagName( "defaultAction" ); + + for ( int i = 0; i < defaultActionNodes.size(); ++i ) + { + QDomElement defaultValueElem = defaultActionNodes.at( i ).toElement(); + mDefaultActions.insert( defaultValueElem.attribute( "key" ), defaultValueElem.attribute( "value" ) ); + } } return true; } diff --git a/src/core/qgsactionmanager.h b/src/core/qgsactionmanager.h index a9464a451c95..7327c4a5ebef 100644 --- a/src/core/qgsactionmanager.h +++ b/src/core/qgsactionmanager.h @@ -51,7 +51,6 @@ class CORE_EXPORT QgsActionManager //! Constructor QgsActionManager( QgsVectorLayer *layer ) : mLayer( layer ) - , mDefaultAction( -1 ) {} /** Add an action with the given name and action details. @@ -143,8 +142,6 @@ class CORE_EXPORT QgsActionManager QVariantMap mDefaultActions; - int mDefaultAction; - QgsExpressionContext createExpressionContext() const; }; diff --git a/src/core/qgsactionscoperegistry.cpp b/src/core/qgsactionscoperegistry.cpp index f21ee229c812..a8a1cf0f7da2 100644 --- a/src/core/qgsactionscoperegistry.cpp +++ b/src/core/qgsactionscoperegistry.cpp @@ -28,16 +28,13 @@ QgsActionScopeRegistry::QgsActionScopeRegistry( QObject* parent ) mActionScopes.insert( QgsActionScope( QStringLiteral( "Canvas" ), tr( "Canvas" ), tr( "Available for the action map tool on the canvas." ), canvasScope ) ); QgsExpressionContextScope fieldScope; - fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "current_field" ), QStringLiteral( "[field_value]" ), true ) ); fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_index" ), 0, true ) ); fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), "[field_name]", true ) ); fieldScope.addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_value" ), "[field_value]", true ) ); - mActionScopes.insert( QgsActionScope( QStringLiteral( "FieldSpecific" ), tr( "Field Specific" ), tr( "Available for individual fields in the attribute table." ), fieldScope ) ); - mActionScopes.insert( QgsActionScope( QStringLiteral( "AttributeTableRow" ), tr( "Attribute Table Row" ), tr( "Available for individual features (rows) in the attribute table." ) ) ); - mActionScopes.insert( QgsActionScope( QStringLiteral( "FeatureForm" ), tr( "Feature Form" ), tr( "Available for individual features in their form." ) ) ); - - mActionScopes.insert( QgsActionScope( QStringLiteral( "AttributeTable" ), tr( "Attribute Table" ), tr( "Available as layer global action in the attribute table." ) ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "Field" ), tr( "Field Scope" ), tr( "Available for individual fields. For example in the attribute table." ), fieldScope ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "Feature" ), tr( "Feature Scope" ), tr( "Available for individual features. For example on feature forms or per row in the attribute table." ) ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "Layer Scope" ), tr( "Layer Scope" ), tr( "Available as layer global action. For example on top of the attribute table." ) ) ); } QSet QgsActionScopeRegistry::actionScopes() const diff --git a/src/gui/attributetable/qgsattributetableview.cpp b/src/gui/attributetable/qgsattributetableview.cpp index 9453dcc8f9c6..33112dce7ef4 100644 --- a/src/gui/attributetable/qgsattributetableview.cpp +++ b/src/gui/attributetable/qgsattributetableview.cpp @@ -176,7 +176,7 @@ QWidget* QgsAttributeTableView::createActionWidget( QgsFeatureId fid ) QAction* defaultAction = nullptr; // first add user created layer actions - QList actions = mFilterModel->layer()->actions()->listActions( QStringLiteral( "AttributeTableRow" ) ); + QList actions = mFilterModel->layer()->actions()->listActions( QStringLiteral( "Feature" ) ); Q_FOREACH ( const QgsAction& action, actions ) { QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QLatin1String( "" ); diff --git a/src/gui/attributetable/qgsdualview.cpp b/src/gui/attributetable/qgsdualview.cpp index 412442c41b17..a5057103ab9c 100644 --- a/src/gui/attributetable/qgsdualview.cpp +++ b/src/gui/attributetable/qgsdualview.cpp @@ -390,7 +390,7 @@ void QgsDualView::viewWillShowContextMenu( QMenu* menu, const QModelIndex& atInd } //add user-defined actions to context menu - QList actions = mLayerCache->layer()->actions()->listActions( QStringLiteral( "FieldSpecific" ) ); + QList actions = mLayerCache->layer()->actions()->listActions( QStringLiteral( "Field" ) ); if ( !actions.isEmpty() ) { QAction* a = menu->addAction( tr( "Run layer action" ) ); From 08d350c0cbbbc16ae2d064c3dbc1c416f905d764 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 3 Nov 2016 19:11:51 +0100 Subject: [PATCH 777/897] Fix bindings and docs --- python/core/qgsaction.sip | 28 ++++++++++++++++++++ python/core/qgsactionmanager.sip | 2 +- python/core/qgsactionscope.sip | 15 ++++++----- python/core/qgsactionscoperegistry.sip | 10 ++++++++ python/core/qgsapplication.sip | 6 +++++ python/gui/attributetable/qgsdualview.sip | 2 +- python/gui/qgsactionmenu.sip | 2 ++ src/core/qgsaction.h | 18 +++++++++++-- src/core/qgsactionmanager.h | 2 +- src/core/qgsactionscope.h | 13 ++++++---- src/core/qgsactionscoperegistry.h | 31 +++++++++++++++++------ src/core/qgsapplication.h | 2 ++ src/gui/qgsactionmenu.h | 8 +++--- 13 files changed, 112 insertions(+), 27 deletions(-) diff --git a/python/core/qgsaction.sip b/python/core/qgsaction.sip index d2e317c9db15..88aa56c21551 100644 --- a/python/core/qgsaction.sip +++ b/python/core/qgsaction.sip @@ -41,6 +41,20 @@ class QgsAction //! The short title is used to label user interface elements like buttons QString shortTitle() const; + /** + * Returns a unique id for this action. + * + * @note Added in QGIS 3.0 + */ + QString id() const { return mShortTitle; } + + /** + * Returns true if this action was a default constructed one. + * + * @note Added in QGIS 3.0 + */ + bool isValid() const { return !mShortTitle.isNull(); } + //! The path to the icon QString iconPath() const; @@ -59,6 +73,20 @@ class QgsAction //! Checks if the action is runable on the current platform bool runable() const; + /** + * Run this action. + * + * @note Added in QGIS 3.0 + */ + void run( QgsVectorLayer* layer, const QgsFeature& feature, const QgsExpressionContext& expressionContext ) const; + + /** + * Run this action. + * + * @note Added in QGIS 3.0 + */ + void run( const QgsExpressionContext& expressionContext ) const; + /** * The action scopes define where an action will be available. * Action scopes may offer additional variables like the clicked diff --git a/python/core/qgsactionmanager.sip b/python/core/qgsactionmanager.sip index ad199d97b7d1..d3003ad66ed5 100644 --- a/python/core/qgsactionmanager.sip +++ b/python/core/qgsactionmanager.sip @@ -69,7 +69,7 @@ class QgsActionManager /** Does the action using the expression engine to replace any embedded expressions * in the action definition. - * @param index action index + * @param actionId action id * @param feature feature to run action for * @param context expression context to evalute expressions under */ diff --git a/python/core/qgsactionscope.sip b/python/core/qgsactionscope.sip index ba7061a5c628..67241cce5bcf 100644 --- a/python/core/qgsactionscope.sip +++ b/python/core/qgsactionscope.sip @@ -25,11 +25,12 @@ *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Canvas
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show for canvas tools. Adds `@clicked_x` and `@clicked_y` in map coordinates.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  AttributeTable
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table for each row.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  FieldSpecific
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show on right click in attribute table. Adds `@field_index` and `@field_name`.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Selection
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Feature
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in feature specific places like the attribute table or feature + * form.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Field
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in context menus for individual fields (e.g. attribute table). Adds `@field_index`, `@field_name` and `@field_value`.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Layer
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table and work on the layer or selection.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  * @@ -43,7 +44,9 @@ class QgsActionScope %End public: /** - * Creates a new action scope. + * Creates a new invalid action scope. + * + * @note Added in QGSI 3.0 */ explicit QgsActionScope(); diff --git a/python/core/qgsactionscoperegistry.sip b/python/core/qgsactionscoperegistry.sip index fe2784e3300a..1668472229df 100644 --- a/python/core/qgsactionscoperegistry.sip +++ b/python/core/qgsactionscoperegistry.sip @@ -35,10 +35,20 @@ class QgsActionScopeRegistry : QObject %End public: + /** + * Create a new QgsActionScopeRegistry. + * QGIS already creates a central registry. You will normally + * want to use QgsApplication::actionScopeRegistry() to get acess + * to that one instead. + * + * @note Added in QGIS 3.0 + */ explicit QgsActionScopeRegistry( QObject* parent = nullptr ); /** * Get all registered action scopes. + * + * @note Added in QGIS 3.0 */ QSet actionScopes() const; diff --git a/python/core/qgsapplication.sip b/python/core/qgsapplication.sip index 8a8dd5a24ce1..59aeeaafa55f 100644 --- a/python/core/qgsapplication.sip +++ b/python/core/qgsapplication.sip @@ -378,6 +378,12 @@ static void qtgui_UpdatePyArgv(PyObject *argvlist, int argc, char **argv) //dummy method to workaround sip generation issue issue bool x11EventFilter ( XEvent * event ); %End + /** + * Returns the action scope registry. + * + * @Note Added in QGIS 3.0 + */ + static QgsActionScopeRegistry* actionScopeRegistry(); public slots: diff --git a/python/gui/attributetable/qgsdualview.sip b/python/gui/attributetable/qgsdualview.sip index d67105b15611..40c533f02041 100644 --- a/python/gui/attributetable/qgsdualview.sip +++ b/python/gui/attributetable/qgsdualview.sip @@ -229,7 +229,7 @@ class QgsAttributeTableAction : QAction %End public: - QgsAttributeTableAction( const QString &name, QgsDualView *dualView, int action, const QModelIndex &fieldIdx ); + QgsAttributeTableAction( const QString &name, QgsDualView *dualView, const QString& action, const QModelIndex &fieldIdx ); public slots: void execute(); diff --git a/python/gui/qgsactionmenu.sip b/python/gui/qgsactionmenu.sip index 935875119482..3180d27497e2 100644 --- a/python/gui/qgsactionmenu.sip +++ b/python/gui/qgsactionmenu.sip @@ -35,6 +35,7 @@ class QgsActionMenu : QMenu * @param feature The feature that this action will be run upon. Make sure that this feature is available * for the lifetime of this object. * @param parent The usual QWidget parent. + * @param actionScope The action scope this menu will run in */ explicit QgsActionMenu( QgsVectorLayer* layer, const QgsFeature& feature, const QString& actionScope, QWidget *parent /TransferThis/ = nullptr ); @@ -44,6 +45,7 @@ class QgsActionMenu : QMenu * @param layer The layer that this action will be run upon. * @param fid The feature id of the feature for which this action will be run. * @param parent The usual QWidget parent. + * @param actionScope The action scope this menu will run in */ explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, const QString& actionScope, QWidget *parent /TransferThis/ = nullptr ); diff --git a/src/core/qgsaction.h b/src/core/qgsaction.h index 5d8cd76b09c0..106be56aeb3f 100644 --- a/src/core/qgsaction.h +++ b/src/core/qgsaction.h @@ -90,8 +90,18 @@ class CORE_EXPORT QgsAction //! The short title is used to label user interface elements like buttons QString shortTitle() const { return mShortTitle; } + /** + * Returns a unique id for this action. + * + * @note Added in QGIS 3.0 + */ QString id() const { return mShortTitle; } + /** + * Returns true if this action was a default constructed one. + * + * @note Added in QGIS 3.0 + */ bool isValid() const { return !mShortTitle.isNull(); } //! The path to the icon @@ -119,12 +129,16 @@ class CORE_EXPORT QgsAction bool runable() const; /** - * Run this expression. + * Run this action. + * + * @note Added in QGIS 3.0 */ void run( QgsVectorLayer* layer, const QgsFeature& feature, const QgsExpressionContext& expressionContext ) const; /** - * Run this expression. + * Run this action. + * + * @note Added in QGIS 3.0 */ void run( const QgsExpressionContext& expressionContext ) const; diff --git a/src/core/qgsactionmanager.h b/src/core/qgsactionmanager.h index 7327c4a5ebef..96f6e31601a6 100644 --- a/src/core/qgsactionmanager.h +++ b/src/core/qgsactionmanager.h @@ -84,7 +84,7 @@ class CORE_EXPORT QgsActionManager /** Does the action using the expression engine to replace any embedded expressions * in the action definition. - * @param index action index + * @param actionId action id * @param feature feature to run action for * @param context expression context to evalute expressions under */ diff --git a/src/core/qgsactionscope.h b/src/core/qgsactionscope.h index ef0d60f474d8..6f29fb7cff4b 100644 --- a/src/core/qgsactionscope.h +++ b/src/core/qgsactionscope.h @@ -30,15 +30,16 @@ *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Canvas
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show for canvas tools. Adds `@clicked_x` and `@clicked_y` in map coordinates.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  AttributeTable
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table for each row.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  FieldSpecific
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Feature
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in feature specific places like the attribute table or feature + * form.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Field
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in context menus for individual fields (e.g. attribute table). Adds `@field_index`, `@field_name` and `@field_value`.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Selection
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Layer
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Show in attribute table and work on the layer or selection.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  *
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  * - * \since QGIS 3.0 + * @note Added in QGIS 3.0 */ class CORE_EXPORT QgsActionScope @@ -47,6 +48,8 @@ class CORE_EXPORT QgsActionScope /** * Creates a new invalid action scope. + * + * @note Added in QGSI 3.0 */ explicit QgsActionScope(); diff --git a/src/core/qgsactionscoperegistry.h b/src/core/qgsactionscoperegistry.h index d120421c3dc9..c65f48223881 100644 --- a/src/core/qgsactionscoperegistry.h +++ b/src/core/qgsactionscoperegistry.h @@ -37,21 +37,24 @@ class CORE_EXPORT QgsActionScopeRegistry : public QObject { Q_OBJECT - /** - * The action scopes which are currently registered and available. - * - * \read actionScopes() - * \notify actionScopesChanged() - * - * \since QGIS 3.0 - */ Q_PROPERTY( QSet actionScopes READ actionScopes NOTIFY actionScopesChanged ) public: + + /** + * Create a new QgsActionScopeRegistry. + * QGIS already creates a central registry. You will normally + * want to use QgsApplication::actionScopeRegistry() to get acess + * to that one instead. + * + * @note Added in QGIS 3.0 + */ explicit QgsActionScopeRegistry( QObject* parent = nullptr ); /** * Get all registered action scopes. + * + * @note Added in QGIS 3.0 */ QSet actionScopes() const; @@ -69,9 +72,21 @@ class CORE_EXPORT QgsActionScopeRegistry : public QObject */ void unregisterActionScope( const QgsActionScope& actionScope ); + /** + * Get an action scope by its id. + * + * @note Added in QGIS 3.0 + */ QgsActionScope actionScope( const QString& id ); signals: + + /** + * Emitted whenever a new action scope is registered or an action scope + * is unregistered. + * + * @note Added in QGIS 3.0 + */ void actionScopesChanged(); private: diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index d8d2f44cf380..994376025e72 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -376,6 +376,8 @@ class CORE_EXPORT QgsApplication : public QApplication /** * Returns the action scope registry. + * + * @Note Added in QGIS 3.0 */ static QgsActionScopeRegistry* actionScopeRegistry(); diff --git a/src/gui/qgsactionmenu.h b/src/gui/qgsactionmenu.h index b817243f4710..0056a77eba9d 100644 --- a/src/gui/qgsactionmenu.h +++ b/src/gui/qgsactionmenu.h @@ -62,6 +62,7 @@ class GUI_EXPORT QgsActionMenu : public QMenu * @param feature The feature that this action will be run upon. Make sure that this feature is available * for the lifetime of this object. * @param parent The usual QWidget parent. + * @param actionScope The action scope this menu will run in */ explicit QgsActionMenu( QgsVectorLayer* layer, const QgsFeature& feature, const QString& actionScope, QWidget *parent = nullptr ); @@ -71,6 +72,7 @@ class GUI_EXPORT QgsActionMenu : public QMenu * @param layer The layer that this action will be run upon. * @param fid The feature id of the feature for which this action will be run. * @param parent The usual QWidget parent. + * @param actionScope The action scope this menu will run in */ explicit QgsActionMenu( QgsVectorLayer *layer, const QgsFeatureId fid, const QString& actionScope, QWidget *parent = nullptr ); @@ -87,13 +89,13 @@ class GUI_EXPORT QgsActionMenu : public QMenu */ void setFeature( const QgsFeature& feature ); + signals: + void reinit(); + private slots: void triggerAction(); void reloadActions(); - signals: - void reinit(); - private: void init(); QgsFeature feature(); From a6eb7b62811cb80dc2ccf3810dc168086d5d3380 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 3 Nov 2016 22:48:19 +0100 Subject: [PATCH 778/897] Convert action ids to uuid --- python/core/qgsaction.sip | 46 +++++++++- python/core/qgsactionmanager.sip | 23 +++-- python/core/qgsapplication.sip | 2 +- python/gui/attributetable/qgsdualview.sip | 2 +- src/app/qgsfeatureaction.cpp | 2 +- src/app/qgsfeatureaction.h | 5 +- src/core/qgsaction.cpp | 53 ++++++++++++ src/core/qgsaction.h | 30 +++++-- src/core/qgsactionmanager.cpp | 85 +++++-------------- src/core/qgsactionmanager.h | 20 ++--- src/core/qgsapplication.h | 2 +- src/core/qgsvectorlayer.cpp | 2 +- .../attributetable/qgsattributetablemodel.cpp | 2 +- .../attributetable/qgsattributetablemodel.h | 2 +- src/gui/attributetable/qgsdualview.h | 9 +- tests/src/python/test_qgsactionmanager.py | 49 +++++------ 16 files changed, 201 insertions(+), 133 deletions(-) diff --git a/python/core/qgsaction.sip b/python/core/qgsaction.sip index 88aa56c21551..2ae1d0544424 100644 --- a/python/core/qgsaction.sip +++ b/python/core/qgsaction.sip @@ -33,6 +33,32 @@ class QgsAction OpenUrl, }; + /** + * Default constructor + */ + QgsAction(); + + /** + * Create a new QgsAction + * + * @param type The type of this action + * @param description A human readable description string + * @param command The action text. Its interpretation depends on the type + * @param capture If this is set to true, the output will be captured when an action is run + */ + QgsAction( ActionType type, const QString& description, const QString& command, bool capture = false ); + + /** + * Create a new QgsAction + * + * @param type The type of this action + * @param description A human readable description string + * @param action The action text. Its interpretation depends on the type + * @param icon Path to an icon for this action + * @param capture If this is set to true, the output will be captured when an action is run + * @param shortTitle A short string used to label user interface elements like buttons + * @param actionScopes A set of scopes in which this action will be available + */ QgsAction( ActionType type, const QString& description, const QString& action, const QString& icon, bool capture, const QString& shortTitle = QString(), const QSet& actionScopes = QSet() ); //! The name of the action. This may be a longer description. @@ -46,14 +72,14 @@ class QgsAction * * @note Added in QGIS 3.0 */ - QString id() const { return mShortTitle; } + QUuid id() const; /** * Returns true if this action was a default constructed one. * * @note Added in QGIS 3.0 */ - bool isValid() const { return !mShortTitle.isNull(); } + bool isValid() const; //! The path to the icon QString iconPath() const; @@ -105,4 +131,20 @@ class QgsAction * @note Added in QGIS 3.0 */ void setActionScopes( const QSet& actionScopes ); + + /** + * Reads an XML definition from actionNode + * into this object. + * + * @note Added in QGIS 3.0 + */ + void readXml( const QDomNode& actionNode ); + + /** + * Appends an XML definition for this action as a new + * child node to actionsNode. + * + * @note Added in QGIS 3.0 + */ + void writeXml(QDomNode& actionsNode ) const; }; diff --git a/python/core/qgsactionmanager.sip b/python/core/qgsactionmanager.sip index d3003ad66ed5..81b70794ae85 100644 --- a/python/core/qgsactionmanager.sip +++ b/python/core/qgsactionmanager.sip @@ -44,7 +44,7 @@ class QgsActionManager * any stdout from the process will be captured and displayed in a * dialog box. */ - void addAction( QgsAction::ActionType type, const QString& name, const QString& action, bool capture = false ); + QUuid addAction(QgsAction::ActionType type, const QString& name, const QString& command, bool capture = false ); /** Add an action with the given name and action details. * Will happily have duplicate names and actions. If @@ -52,7 +52,7 @@ class QgsActionManager * any stdout from the process will be captured and displayed in a * dialog box. */ - void addAction( QgsAction::ActionType type, const QString& name, const QString& action, const QString& icon, bool capture = false ); + QUuid addAction(QgsAction::ActionType type, const QString& name, const QString& command, const QString& icon, bool capture = false ); /** * Add a new action to this list. @@ -63,9 +63,7 @@ class QgsActionManager * field to be used if the action has a $currfield placeholder. * @note available in python bindings as doActionFeature */ - void doAction( const QString& actionId, - const QgsFeature &feat, - int defaultValueIndex = 0 ) /PyName=doActionFeature/; + void doAction(const QUuid& actionId, const QgsFeature& feature, int defaultValueIndex = 0 ) /PyName=doActionFeature/; /** Does the action using the expression engine to replace any embedded expressions * in the action definition. @@ -73,21 +71,22 @@ class QgsActionManager * @param feature feature to run action for * @param context expression context to evalute expressions under */ - void doAction( const QString& actionId, - const QgsFeature& feature, - const QgsExpressionContext& context ); + void doAction( const QUuid& actionId, const QgsFeature& feature, const QgsExpressionContext& context ); //! Removes all actions void clearActions(); - //! List all actions + /** + * Return a list of actions that are available in the given action scope. + * If no action scope is provided, all actions will be returned. + */ QList listActions( const QString& actionScope = QString() ) const; //! Return the layer QgsVectorLayer* layer() const; //! Writes the actions out in XML format - bool writeXml( QDomNode& layer_node, QDomDocument& doc ) const; + bool writeXml( QDomNode& layer_node ) const; //! Reads the actions in in XML format bool readXml( const QDomNode& layer_node ); @@ -97,7 +96,7 @@ class QgsActionManager * * @note Added in QGIS 3.0 */ - QgsAction action( const QString& id ); + QgsAction action( const QUuid& id ); /** * Each scope can have a default action. This will be saved in the project @@ -105,7 +104,7 @@ class QgsActionManager * * @note Added in QGIS 3.0 */ - void setDefaultAction( const QString& actionScope, const QString& actionId ); + void setDefaultAction( const QString& actionScope, const QUuid& actionId ); /** * Each scope can have a default action. This will be saved in the project diff --git a/python/core/qgsapplication.sip b/python/core/qgsapplication.sip index 59aeeaafa55f..ce464b8117f0 100644 --- a/python/core/qgsapplication.sip +++ b/python/core/qgsapplication.sip @@ -381,7 +381,7 @@ static void qtgui_UpdatePyArgv(PyObject *argvlist, int argc, char **argv) /** * Returns the action scope registry. * - * @Note Added in QGIS 3.0 + * @note Added in QGIS 3.0 */ static QgsActionScopeRegistry* actionScopeRegistry(); diff --git a/python/gui/attributetable/qgsdualview.sip b/python/gui/attributetable/qgsdualview.sip index 40c533f02041..966c5a1f794c 100644 --- a/python/gui/attributetable/qgsdualview.sip +++ b/python/gui/attributetable/qgsdualview.sip @@ -229,7 +229,7 @@ class QgsAttributeTableAction : QAction %End public: - QgsAttributeTableAction( const QString &name, QgsDualView *dualView, const QString& action, const QModelIndex &fieldIdx ); + QgsAttributeTableAction( const QString& name, QgsDualView* dualView, const QUuid& action, const QModelIndex& fieldIdx ); public slots: void execute(); diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index 8012c2e79b1e..332bfd994296 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -32,7 +32,7 @@ #include #include -QgsFeatureAction::QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *layer, const QString& actionId, int defaultAttr, QObject *parent ) +QgsFeatureAction::QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *layer, const QUuid& actionId, int defaultAttr, QObject *parent ) : QAction( name, parent ) , mLayer( layer ) , mFeature( &f ) diff --git a/src/app/qgsfeatureaction.h b/src/app/qgsfeatureaction.h index 9b46923c110f..6f9688ad3bb4 100644 --- a/src/app/qgsfeatureaction.h +++ b/src/app/qgsfeatureaction.h @@ -22,6 +22,7 @@ #include #include #include +#include class QgsIdentifyResultsDialog; class QgsVectorLayer; @@ -33,7 +34,7 @@ class APP_EXPORT QgsFeatureAction : public QAction Q_OBJECT public: - QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *vl, const QString& actionId = QString(), int defaultAttr = -1, QObject *parent = nullptr ); + QgsFeatureAction( const QString &name, QgsFeature &f, QgsVectorLayer *vl, const QUuid& actionId = QString(), int defaultAttr = -1, QObject *parent = nullptr ); public slots: void execute(); @@ -59,7 +60,7 @@ class APP_EXPORT QgsFeatureAction : public QAction QgsVectorLayer* mLayer; QgsFeature* mFeature; - QString mActionId; + QUuid mActionId; int mIdx; bool mFeatureSaved; diff --git a/src/core/qgsaction.cpp b/src/core/qgsaction.cpp index 7116fb92d4ca..6def7a2252ea 100644 --- a/src/core/qgsaction.cpp +++ b/src/core/qgsaction.cpp @@ -91,3 +91,56 @@ void QgsAction::setActionScopes( const QSet& actionScopes ) { mActionScopes = actionScopes; } + +void QgsAction::readXml( const QDomNode& actionNode ) +{ + QDomElement actionElement = actionNode.toElement(); + QDomNodeList actionScopeNodes = actionElement.elementsByTagName( "actionScope" ); + + if ( actionScopeNodes.isEmpty() ) + { + mActionScopes + << QStringLiteral( "Canvas" ) + << QStringLiteral( "Field" ) + << QStringLiteral( "Feature" ); + } + else + { + for ( int j = 0; j < actionScopeNodes.length(); ++j ) + { + QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement(); + mActionScopes << actionScopeElem.attribute( "id" ); + } + } + + mType = static_cast< QgsAction::ActionType >( actionElement.attributeNode( QStringLiteral( "type" ) ).value().toInt() ); + mDescription = actionElement.attributeNode( QStringLiteral( "name" ) ).value(); + mCommand = actionElement.attributeNode( QStringLiteral( "action" ) ).value(); + mIcon = actionElement.attributeNode( QStringLiteral( "icon" ) ).value(); + mCaptureOutput = actionElement.attributeNode( QStringLiteral( "capture" ) ).value().toInt() != 0; + mShortTitle = actionElement.attributeNode( QStringLiteral( "shortTitle" ) ).value(); + mId = QUuid( actionElement.attributeNode( QStringLiteral( "id" ) ).value() ); + if ( mId.isNull() ) + mId = QUuid::createUuid(); +} + +void QgsAction::writeXml( QDomNode& actionsNode ) const +{ + QDomElement actionSetting = actionsNode.ownerDocument().createElement( QStringLiteral( "actionsetting" ) ); + actionSetting.setAttribute( QStringLiteral( "type" ), mType ); + actionSetting.setAttribute( QStringLiteral( "name" ), mDescription ); + actionSetting.setAttribute( QStringLiteral( "shortTitle" ), mShortTitle ); + actionSetting.setAttribute( QStringLiteral( "icon" ), mIcon ); + actionSetting.setAttribute( QStringLiteral( "action" ), mCommand ); + actionSetting.setAttribute( QStringLiteral( "capture" ), mCaptureOutput ); + actionSetting.setAttribute( QStringLiteral( "id" ), mId.toString() ); + + Q_FOREACH ( const QString& scope, mActionScopes ) + { + QDomElement actionScopeElem = actionsNode.ownerDocument().createElement( "actionScope" ); + actionScopeElem.setAttribute( "id", scope ); + actionSetting.appendChild( actionScopeElem ); + } + + actionsNode.appendChild( actionSetting ); +} diff --git a/src/core/qgsaction.h b/src/core/qgsaction.h index 106be56aeb3f..b170160c026a 100644 --- a/src/core/qgsaction.h +++ b/src/core/qgsaction.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "qgsexpressioncontext.h" @@ -53,14 +54,15 @@ class CORE_EXPORT QgsAction * * @param type The type of this action * @param description A human readable description string - * @param action The action text. Its interpretation depends on the type + * @param command The action text. Its interpretation depends on the type * @param capture If this is set to true, the output will be captured when an action is run */ - QgsAction( ActionType type, const QString& description, const QString& action, bool capture ) + QgsAction( ActionType type, const QString& description, const QString& command, bool capture = false ) : mType( type ) , mDescription( description ) - , mCommand( action ) + , mCommand( command ) , mCaptureOutput( capture ) + , mId( QUuid::createUuid() ) {} /** @@ -82,6 +84,7 @@ class CORE_EXPORT QgsAction , mCommand( action ) , mCaptureOutput( capture ) , mActionScopes( actionScopes ) + , mId( QUuid::createUuid() ) {} //! The name of the action. This may be a longer description. @@ -95,14 +98,14 @@ class CORE_EXPORT QgsAction * * @note Added in QGIS 3.0 */ - QString id() const { return mShortTitle; } + QUuid id() const { return mId; } /** * Returns true if this action was a default constructed one. * * @note Added in QGIS 3.0 */ - bool isValid() const { return !mShortTitle.isNull(); } + bool isValid() const { return !mId.isNull(); } //! The path to the icon QString iconPath() const { return mIcon; } @@ -161,6 +164,22 @@ class CORE_EXPORT QgsAction */ void setActionScopes( const QSet& actionScopes ); + /** + * Reads an XML definition from actionNode + * into this object. + * + * @note Added in QGIS 3.0 + */ + void readXml( const QDomNode& actionNode ); + + /** + * Appends an XML definition for this action as a new + * child node to actionsNode. + * + * @note Added in QGIS 3.0 + */ + void writeXml( QDomNode& actionsNode ) const; + private: ActionType mType; QString mDescription; @@ -170,6 +189,7 @@ class CORE_EXPORT QgsAction bool mCaptureOutput; QSet mActionScopes; mutable QSharedPointer mAction; + QUuid mId; }; Q_DECLARE_METATYPE( QgsAction ) diff --git a/src/core/qgsactionmanager.cpp b/src/core/qgsactionmanager.cpp index ae0ffee2782f..8363e085abe2 100644 --- a/src/core/qgsactionmanager.cpp +++ b/src/core/qgsactionmanager.cpp @@ -40,24 +40,26 @@ #include -void QgsActionManager::addAction( QgsAction::ActionType type, const QString& name, const QString& action, bool capture ) +QUuid QgsActionManager::addAction( QgsAction::ActionType type, const QString& name, const QString& command, bool capture ) { - addAction( QgsAction( type, name, action, capture ) ); + QgsAction action( type, name, command, capture ); + addAction( action ); + return action.id(); } -void QgsActionManager::addAction( QgsAction::ActionType type, const QString& name, const QString& action, const QString& icon, bool capture ) +QUuid QgsActionManager::addAction( QgsAction::ActionType type, const QString& name, const QString& command, const QString& icon, bool capture ) { - addAction( QgsAction( type, name, action, icon, capture ) ); + QgsAction action( type, name, command, icon, capture ); + addAction( action ); + return action.id(); } void QgsActionManager::addAction( const QgsAction& action ) { - static int actionId = 0; - - mActions.insert( ++actionId, action ); + mActions.append( action ); } -void QgsActionManager::doAction( const QString& actionId, const QgsFeature& feature, int defaultValueIndex ) +void QgsActionManager::doAction( const QUuid& actionId, const QgsFeature& feature, int defaultValueIndex ) { QgsExpressionContext context = createExpressionContext(); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); @@ -69,7 +71,7 @@ void QgsActionManager::doAction( const QString& actionId, const QgsFeature& feat doAction( actionId, feature, context ); } -void QgsActionManager::doAction( const QString& actionId, const QgsFeature& feat, const QgsExpressionContext& context ) +void QgsActionManager::doAction( const QUuid& actionId, const QgsFeature& feat, const QgsExpressionContext& context ) { QgsAction act = action( actionId ); @@ -147,12 +149,12 @@ QgsExpressionContext QgsActionManager::createExpressionContext() const return context; } -bool QgsActionManager::writeXml( QDomNode& layer_node, QDomDocument& doc ) const +bool QgsActionManager::writeXml( QDomNode& layer_node ) const { - QDomElement aActions = doc.createElement( QStringLiteral( "attributeactions" ) ); - for ( QVariantMap::const_iterator defaultAction = mDefaultActions.constBegin(); defaultAction != mDefaultActions.constEnd(); ++ defaultAction ) + QDomElement aActions = layer_node.ownerDocument().createElement( QStringLiteral( "attributeactions" ) ); + for ( QMap::const_iterator defaultAction = mDefaultActions.constBegin(); defaultAction != mDefaultActions.constEnd(); ++ defaultAction ) { - QDomElement defaultActionElement = doc.createElement( QStringLiteral( "defaultAction" ) ); + QDomElement defaultActionElement = layer_node.ownerDocument().createElement( QStringLiteral( "defaultAction" ) ); defaultActionElement.setAttribute( QStringLiteral( "key" ), defaultAction.key() ); defaultActionElement.setAttribute( QStringLiteral( "value" ), defaultAction.value().toString() ); aActions.appendChild( defaultActionElement ); @@ -160,21 +162,7 @@ bool QgsActionManager::writeXml( QDomNode& layer_node, QDomDocument& doc ) const Q_FOREACH ( const QgsAction& action, mActions ) { - QDomElement actionSetting = doc.createElement( QStringLiteral( "actionsetting" ) ); - actionSetting.setAttribute( QStringLiteral( "type" ), action.type() ); - actionSetting.setAttribute( QStringLiteral( "name" ), action.name() ); - actionSetting.setAttribute( QStringLiteral( "shortTitle" ), action.shortTitle() ); - actionSetting.setAttribute( QStringLiteral( "icon" ), action.iconPath() ); - actionSetting.setAttribute( QStringLiteral( "action" ), action.command() ); - actionSetting.setAttribute( QStringLiteral( "capture" ), action.capture() ); - - Q_FOREACH ( const QString& scope, action.actionScopes() ) - { - QDomElement actionScopeElem = doc.createElement( "actionScope" ); - actionScopeElem.setAttribute( "id", scope ); - actionSetting.appendChild( actionScopeElem ); - } - aActions.appendChild( actionSetting ); + action.writeXml( aActions ); } layer_node.appendChild( aActions ); @@ -192,38 +180,9 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) QDomNodeList actionsettings = aaNode.toElement().elementsByTagName( QStringLiteral( "actionsetting" ) ); for ( int i = 0; i < actionsettings.size(); ++i ) { - QDomElement setting = actionsettings.item( i ).toElement(); - - QDomNodeList actionScopeNodes = setting.elementsByTagName( "actionScope" ); - QSet actionScopes; - - if ( actionScopeNodes.isEmpty() ) - { - actionScopes - << QStringLiteral( "Canvas" ) - << QStringLiteral( "FieldSpecific" ) - << QStringLiteral( "AttributeTableRow" ) - << QStringLiteral( "FeatureForm" ); - } - else - { - for ( int j = 0; j < actionScopeNodes.length(); ++j ) - { - QDomElement actionScopeElem = actionScopeNodes.item( j ).toElement(); - actionScopes << actionScopeElem.attribute( "id" ); - } - } - - mActions.append( - QgsAction( static_cast< QgsAction::ActionType >( setting.attributeNode( QStringLiteral( "type" ) ).value().toInt() ), - setting.attributeNode( QStringLiteral( "name" ) ).value(), - setting.attributeNode( QStringLiteral( "action" ) ).value(), - setting.attributeNode( QStringLiteral( "icon" ) ).value(), - setting.attributeNode( QStringLiteral( "capture" ) ).value().toInt() != 0, - setting.attributeNode( QStringLiteral( "shortTitle" ) ).value(), - actionScopes - ) - ); + QgsAction action; + action.readXml( actionsettings.item( i ) ); + mActions.append( action ); } QDomNodeList defaultActionNodes = aaNode.toElement().elementsByTagName( "defaultAction" ); @@ -237,7 +196,7 @@ bool QgsActionManager::readXml( const QDomNode& layer_node ) return true; } -QgsAction QgsActionManager::action( const QString& id ) +QgsAction QgsActionManager::action( const QUuid& id ) { Q_FOREACH ( const QgsAction& action, mActions ) { @@ -248,12 +207,12 @@ QgsAction QgsActionManager::action( const QString& id ) return QgsAction(); } -void QgsActionManager::setDefaultAction( const QString& actionScope, const QString& actionId ) +void QgsActionManager::setDefaultAction( const QString& actionScope, const QUuid& actionId ) { mDefaultActions[ actionScope ] = actionId; } QgsAction QgsActionManager::defaultAction( const QString& actionScope ) { - return action( mDefaultActions.value( actionScope ).toString() ); + return action( mDefaultActions.value( actionScope ) ); } diff --git a/src/core/qgsactionmanager.h b/src/core/qgsactionmanager.h index 96f6e31601a6..a8bb4cb3f162 100644 --- a/src/core/qgsactionmanager.h +++ b/src/core/qgsactionmanager.h @@ -59,7 +59,7 @@ class CORE_EXPORT QgsActionManager * any stdout from the process will be captured and displayed in a * dialog box. */ - void addAction( QgsAction::ActionType type, const QString& name, const QString& action, bool capture = false ); + QUuid addAction( QgsAction::ActionType type, const QString& name, const QString& command, bool capture = false ); /** Add an action with the given name and action details. * Will happily have duplicate names and actions. If @@ -67,7 +67,7 @@ class CORE_EXPORT QgsActionManager * any stdout from the process will be captured and displayed in a * dialog box. */ - void addAction( QgsAction::ActionType type, const QString& name, const QString& action, const QString& icon, bool capture = false ); + QUuid addAction( QgsAction::ActionType type, const QString& name, const QString& command, const QString& icon, bool capture = false ); /** * Add a new action to this list. @@ -78,9 +78,7 @@ class CORE_EXPORT QgsActionManager * field to be used if the action has a $currfield placeholder. * @note available in python bindings as doActionFeature */ - void doAction( const QString& actionId, - const QgsFeature &feature, - int defaultValueIndex = 0 ); + void doAction( const QUuid& actionId, const QgsFeature &feature, int defaultValueIndex = 0 ); /** Does the action using the expression engine to replace any embedded expressions * in the action definition. @@ -88,9 +86,7 @@ class CORE_EXPORT QgsActionManager * @param feature feature to run action for * @param context expression context to evalute expressions under */ - void doAction( const QString& actionId, - const QgsFeature& feature, - const QgsExpressionContext& context ); + void doAction( const QUuid& actionId, const QgsFeature& feature, const QgsExpressionContext& context ); //! Removes all actions void clearActions(); @@ -105,7 +101,7 @@ class CORE_EXPORT QgsActionManager QgsVectorLayer* layer() const { return mLayer; } //! Writes the actions out in XML format - bool writeXml( QDomNode& layer_node, QDomDocument& doc ) const; + bool writeXml( QDomNode& layer_node ) const; //! Reads the actions in in XML format bool readXml( const QDomNode& layer_node ); @@ -115,7 +111,7 @@ class CORE_EXPORT QgsActionManager * * @note Added in QGIS 3.0 */ - QgsAction action( const QString& id ); + QgsAction action( const QUuid& id ); /** * Each scope can have a default action. This will be saved in the project @@ -123,7 +119,7 @@ class CORE_EXPORT QgsActionManager * * @note Added in QGIS 3.0 */ - void setDefaultAction( const QString& actionScope, const QString& actionId ); + void setDefaultAction( const QString& actionScope, const QUuid& actionId ); /** * Each scope can have a default action. This will be saved in the project @@ -140,7 +136,7 @@ class CORE_EXPORT QgsActionManager void runAction( const QgsAction &action ); - QVariantMap mDefaultActions; + QMap mDefaultActions; QgsExpressionContext createExpressionContext() const; }; diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index 994376025e72..152f1b42d120 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -377,7 +377,7 @@ class CORE_EXPORT QgsApplication : public QApplication /** * Returns the action scope registry. * - * @Note Added in QGIS 3.0 + * @note Added in QGIS 3.0 */ static QgsActionScopeRegistry* actionScopeRegistry(); diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 80d9cf91b5c7..2bdb2d76f5d7 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -2005,7 +2005,7 @@ bool QgsVectorLayer::writeSymbology( QDomNode& node, QDomDocument& doc, QString& node.appendChild( excludeWFSElem ); // add attribute actions - mActions->writeXml( node, doc ); + mActions->writeXml( node ); mAttributeTableConfig.writeXml( node ); mEditFormConfig.writeXml( node ); mConditionalStyles->writeXml( node, doc ); diff --git a/src/gui/attributetable/qgsattributetablemodel.cpp b/src/gui/attributetable/qgsattributetablemodel.cpp index 2a75d2897f80..5d13259cd9b9 100644 --- a/src/gui/attributetable/qgsattributetablemodel.cpp +++ b/src/gui/attributetable/qgsattributetablemodel.cpp @@ -737,7 +737,7 @@ void QgsAttributeTableModel::reload( const QModelIndex &index1, const QModelInde } -void QgsAttributeTableModel::executeAction( const QString& action, const QModelIndex &idx ) const +void QgsAttributeTableModel::executeAction( const QUuid& action, const QModelIndex &idx ) const { QgsFeature f = feature( idx ); layer()->actions()->doAction( action, f, fieldIdx( idx.column() ) ); diff --git a/src/gui/attributetable/qgsattributetablemodel.h b/src/gui/attributetable/qgsattributetablemodel.h index 1e465199f8ee..8fd267616cf7 100644 --- a/src/gui/attributetable/qgsattributetablemodel.h +++ b/src/gui/attributetable/qgsattributetablemodel.h @@ -171,7 +171,7 @@ class GUI_EXPORT QgsAttributeTableModel: public QAbstractTableModel /** * Execute an action */ - void executeAction( const QString& action, const QModelIndex &idx ) const; + void executeAction( const QUuid& action, const QModelIndex &idx ) const; /** * Execute a QgsMapLayerAction diff --git a/src/gui/attributetable/qgsdualview.h b/src/gui/attributetable/qgsdualview.h index e00fcf63077e..abb7524fdf23 100644 --- a/src/gui/attributetable/qgsdualview.h +++ b/src/gui/attributetable/qgsdualview.h @@ -353,7 +353,12 @@ class GUI_EXPORT QgsAttributeTableAction : public QAction Q_OBJECT public: - QgsAttributeTableAction( const QString &name, QgsDualView *dualView, const QString& action, const QModelIndex &fieldIdx ) + /** + * Create a new attribute table action. + * + * @note Added in QGIS 3.0 + */ + QgsAttributeTableAction( const QString& name, QgsDualView* dualView, const QUuid& action, const QModelIndex& fieldIdx ) : QAction( name, dualView ) , mDualView( dualView ) , mAction( action ) @@ -366,7 +371,7 @@ class GUI_EXPORT QgsAttributeTableAction : public QAction private: QgsDualView* mDualView; - QString mAction; + QUuid mAction; QModelIndex mFieldIdx; }; diff --git a/tests/src/python/test_qgsactionmanager.py b/tests/src/python/test_qgsactionmanager.py index d6d29b3289ce..94cd19c36fe2 100644 --- a/tests/src/python/test_qgsactionmanager.py +++ b/tests/src/python/test_qgsactionmanager.py @@ -45,7 +45,7 @@ def __init__(self, methodName): self.manager = QgsActionManager(self.layer) # make a little script to aid in recording action outputs - # this is just a little python file which writes out it's arguments to a text file + # this is just a little python file which writes out its arguments to a text file self.run_script_file = os.path.join(QDir.tempPath(), 'run_action.py') with open(self.run_script_file, 'w') as s: s.write('import sys\n') @@ -70,36 +70,29 @@ def testAddAction(self): """ Test adding actions """ # should be empty to start with - self.assertEqual(self.manager.size(), 0) self.assertEqual(self.manager.listActions(), []) # add an action - self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1') - self.assertEqual(self.manager.size(), 1) + action1 = QgsAction(QgsAction.GenericPython, 'Test Action', 'i=1') + self.manager.addAction(action1) + self.assertEqual(len(self.manager.listActions()), 1) self.assertEqual(self.manager.listActions()[0].type(), QgsAction.GenericPython) - self.assertEqual(self.manager.listActions()[0].name(), 'test_action') - self.assertEqual(self.manager.listActions()[0].action(), 'i=1') - self.assertEqual(self.manager.at(0).name(), 'test_action') - self.assertEqual(self.manager[0].name(), 'test_action') + self.assertEqual(self.manager.listActions()[0].name(), 'Test Action') + self.assertEqual(self.manager.listActions()[0].command(), 'i=1') # add another action - self.manager.addAction(QgsAction.Windows, 'test_action2', 'i=2') - self.assertEqual(self.manager.size(), 2) - self.assertEqual(self.manager.listActions()[1].type(), QgsAction.Windows) - self.assertEqual(self.manager.listActions()[1].name(), 'test_action2') - self.assertEqual(self.manager.listActions()[1].action(), 'i=2') - self.assertEqual(self.manager.at(1).name(), 'test_action2') - self.assertEqual(self.manager[1].name(), 'test_action2') - - # add a predefined action - action = QgsAction(QgsAction.Unix, 'test_action3', 'i=3', False) - self.manager.addAction(action) - self.assertEqual(self.manager.size(), 3) - self.assertEqual(self.manager.listActions()[2].type(), QgsAction.Unix) - self.assertEqual(self.manager.listActions()[2].name(), 'test_action3') - self.assertEqual(self.manager.listActions()[2].action(), 'i=3') - self.assertEqual(self.manager.at(2).name(), 'test_action3') - self.assertEqual(self.manager[2].name(), 'test_action3') + action2 = QgsAction(QgsAction.Windows, 'Test Action2', 'i=2') + self.manager.addAction(action2) + self.assertEqual(len(self.manager.listActions()), 2) + self.assertEqual(self.manager.action(action2.id()).type(), QgsAction.Windows) + self.assertEqual(self.manager.action(action2.id()).name(), 'Test Action2') + self.assertEqual(self.manager.action(action2.id()).command(), 'i=2') + + id3 = self.manager.addAction(QgsAction.Generic, 'Test Action3', 'i=3') + self.assertEqual(len(self.manager.listActions()), 3) + self.assertEqual(self.manager.action(id3).type(), QgsAction.Generic) + self.assertEqual(self.manager.action(id3).name(), 'Test Action3') + self.assertEqual(self.manager.action(id3).command(), 'i=3') def testRemoveActions(self): """ test removing actions """ @@ -113,9 +106,9 @@ def testRemoveActions(self): self.assertEqual(self.manager.listActions(), []) # add some actions - self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1') - self.manager.addAction(QgsAction.GenericPython, 'test_action2', 'i=2') - self.manager.addAction(QgsAction.GenericPython, 'test_action3', 'i=3') + id1 = self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1') + id2 = self.manager.addAction(QgsAction.GenericPython, 'test_action2', 'i=2') + id3 = self.manager.addAction(QgsAction.GenericPython, 'test_action3', 'i=3') # remove non-existant action self.manager.removeAction(5) From f18d1c30839728bd7cc58b0318e02e5be37aa62b Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 3 Nov 2016 23:27:17 +0100 Subject: [PATCH 779/897] Rename listActions to actions and fix test --- python/core/qgsactionmanager.sip | 9 +- src/app/qgisapp.cpp | 6 +- src/app/qgsattributeactiondialog.cpp | 2 +- src/app/qgsattributetabledialog.cpp | 2 +- src/app/qgsfeatureaction.cpp | 2 +- src/app/qgsidentifyresultsdialog.cpp | 4 +- src/app/qgsmaptoolfeatureaction.cpp | 2 +- src/core/qgsactionmanager.cpp | 18 ++- src/core/qgsactionmanager.h | 11 +- .../attributetable/qgsattributetableview.cpp | 2 +- src/gui/attributetable/qgsdualview.cpp | 2 +- src/gui/qgsactionmenu.cpp | 2 +- tests/src/python/test_qgsactionmanager.py | 108 +++++++----------- 13 files changed, 89 insertions(+), 81 deletions(-) diff --git a/python/core/qgsactionmanager.sip b/python/core/qgsactionmanager.sip index 81b70794ae85..9c087de259b4 100644 --- a/python/core/qgsactionmanager.sip +++ b/python/core/qgsactionmanager.sip @@ -59,6 +59,13 @@ class QgsActionManager */ void addAction( const QgsAction& action ); + /** + * Remove an action by its id. + * + * @note Added in QGIS 3.0 + */ + void removeAction( const QUuid& actionId ); + /** Does the given values. defaultValueIndex is the index of the * field to be used if the action has a $currfield placeholder. * @note available in python bindings as doActionFeature @@ -80,7 +87,7 @@ class QgsActionManager * Return a list of actions that are available in the given action scope. * If no action scope is provided, all actions will be returned. */ - QList listActions( const QString& actionScope = QString() ) const; + QList actions( const QString& actionScope = QString() ) const; //! Return the layer QgsVectorLayer* layer() const; diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index cfc8b6e30033..d2e17a77cfdb 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -5812,7 +5812,7 @@ void QgisApp::refreshFeatureActions() if ( !vlayer ) return; - QList actions = vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ); + QList actions = vlayer->actions()->actions( QStringLiteral( "Canvas" ) ); Q_FOREACH ( const QgsAction& action, actions ) { QAction* qAction = new QAction( action.icon(), action.shortTitle(), mFeatureActionMenu ); @@ -10623,7 +10623,7 @@ void QgisApp::activateDeactivateLayerRelatedActions( QgsMapLayer* layer ) bool isEditable = vlayer->isEditable(); bool layerHasSelection = vlayer->selectedFeatureCount() > 0; - bool layerHasActions = !vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ).isEmpty() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); + bool layerHasActions = !vlayer->actions()->actions( QStringLiteral( "Canvas" ) ).isEmpty() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); mActionLocalHistogramStretch->setEnabled( false ); mActionFullHistogramStretch->setEnabled( false ); @@ -10909,7 +10909,7 @@ void QgisApp::refreshActionFeatureAction() if ( !vlayer ) return; - bool layerHasActions = !vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ).isEmpty() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); + bool layerHasActions = !vlayer->actions()->actions( QStringLiteral( "Canvas" ) ).isEmpty() || !QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty(); mActionFeatureAction->setEnabled( layerHasActions ); } diff --git a/src/app/qgsattributeactiondialog.cpp b/src/app/qgsattributeactiondialog.cpp index 4950ac1b1867..85c31e1c322c 100644 --- a/src/app/qgsattributeactiondialog.cpp +++ b/src/app/qgsattributeactiondialog.cpp @@ -67,7 +67,7 @@ void QgsAttributeActionDialog::init( const QgsActionManager& actions, const QgsA int i = 0; // Populate with our actions. - Q_FOREACH ( const QgsAction& action, actions.listActions() ) + Q_FOREACH ( const QgsAction& action, actions.actions() ) { insertRow( i++, action ); } diff --git a/src/app/qgsattributetabledialog.cpp b/src/app/qgsattributetabledialog.cpp index 1b2d29405922..e21623aab889 100644 --- a/src/app/qgsattributetabledialog.cpp +++ b/src/app/qgsattributetabledialog.cpp @@ -309,7 +309,7 @@ QgsAttributeTableDialog::QgsAttributeTableDialog( QgsVectorLayer *theLayer, QWid mActionSearchForm->setToolTip( tr( "Search is not supported when using custom UI forms" ) ); } - QList actions = mLayer->actions()->listActions( QStringLiteral( "Layer" ) ); + QList actions = mLayer->actions()->actions( QStringLiteral( "Layer" ) ); if ( actions.isEmpty() ) { diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index 332bfd994296..a9546351c81e 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -66,7 +66,7 @@ QgsAttributeDialog *QgsFeatureAction::newDialog( bool cloneFeature ) QgsAttributeDialog *dialog = new QgsAttributeDialog( mLayer, f, cloneFeature, parentWidget(), true, context ); dialog->setWindowFlags( dialog->windowFlags() | Qt::Tool ); - QList actions = mLayer->actions()->listActions( QStringLiteral( "Feature" ) ); + QList actions = mLayer->actions()->actions( QStringLiteral( "Feature" ) ); if ( !actions.isEmpty() ) { dialog->setContextMenuPolicy( Qt::ActionsContextMenu ); diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index 4a30303afdaf..d9e2d6bdc5b1 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -480,7 +480,7 @@ void QgsIdentifyResultsDialog::addFeature( QgsVectorLayer *vlayer, const QgsFeat //get valid QgsMapLayerActions for this layer QList< QgsMapLayerAction* > registeredActions = QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ); - QList actions = vlayer->actions()->listActions( QStringLiteral( "Feature" ) ); + QList actions = vlayer->actions()->actions( QStringLiteral( "Feature" ) ); if ( !vlayer->fields().isEmpty() || !actions.isEmpty() || !registeredActions.isEmpty() ) { @@ -1092,7 +1092,7 @@ void QgsIdentifyResultsDialog::contextMenuEvent( QContextMenuEvent* event ) if ( featItem && vlayer ) { - QList actions = vlayer->actions()->listActions( QStringLiteral( "Field" ) ); + QList actions = vlayer->actions()->actions( QStringLiteral( "Field" ) ); if ( !actions.isEmpty() ) { mActionPopup->addSeparator(); diff --git a/src/app/qgsmaptoolfeatureaction.cpp b/src/app/qgsmaptoolfeatureaction.cpp index ffd243e9229b..39341d2f9cbf 100644 --- a/src/app/qgsmaptoolfeatureaction.cpp +++ b/src/app/qgsmaptoolfeatureaction.cpp @@ -73,7 +73,7 @@ void QgsMapToolFeatureAction::canvasReleaseEvent( QgsMapMouseEvent* e ) } QgsVectorLayer *vlayer = qobject_cast( layer ); - if ( vlayer->actions()->listActions( QStringLiteral( "Canvas" ) ).isEmpty() && QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty() ) + if ( vlayer->actions()->actions( QStringLiteral( "Canvas" ) ).isEmpty() && QgsMapLayerActionRegistry::instance()->mapLayerActions( vlayer ).isEmpty() ) { emit messageEmitted( tr( "The active vector layer has no defined actions" ), QgsMessageBar::INFO ); return; diff --git a/src/core/qgsactionmanager.cpp b/src/core/qgsactionmanager.cpp index 8363e085abe2..b8523192fa3a 100644 --- a/src/core/qgsactionmanager.cpp +++ b/src/core/qgsactionmanager.cpp @@ -59,13 +59,27 @@ void QgsActionManager::addAction( const QgsAction& action ) mActions.append( action ); } +void QgsActionManager::removeAction( const QUuid& actionId ) +{ + int i = 0; + Q_FOREACH ( const QgsAction& action, mActions ) + { + if ( action.id() == actionId ) + { + mActions.removeAt( i ); + return; + } + ++i; + } +} + void QgsActionManager::doAction( const QUuid& actionId, const QgsFeature& feature, int defaultValueIndex ) { QgsExpressionContext context = createExpressionContext(); QgsExpressionContextScope* actionScope = new QgsExpressionContextScope(); actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_index" ), defaultValueIndex, true ) ); if ( defaultValueIndex >= 0 && defaultValueIndex < feature.fields().size() ) - actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), feature.fields().at( defaultValueIndex ), true ) ); + actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_name" ), feature.fields().at( defaultValueIndex ).name(), true ) ); actionScope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "field_value" ), feature.attribute( defaultValueIndex ), true ) ); context << actionScope; doAction( actionId, feature, context ); @@ -97,7 +111,7 @@ void QgsActionManager::clearActions() mActions.clear(); } -QList QgsActionManager::listActions( const QString& actionScope ) const +QList QgsActionManager::actions( const QString& actionScope ) const { if ( actionScope.isNull() ) return mActions; diff --git a/src/core/qgsactionmanager.h b/src/core/qgsactionmanager.h index a8bb4cb3f162..de88e6cc8c99 100644 --- a/src/core/qgsactionmanager.h +++ b/src/core/qgsactionmanager.h @@ -74,6 +74,13 @@ class CORE_EXPORT QgsActionManager */ void addAction( const QgsAction& action ); + /** + * Remove an action by its id. + * + * @note Added in QGIS 3.0 + */ + void removeAction( const QUuid& actionId ); + /** Does the given values. defaultValueIndex is the index of the * field to be used if the action has a $currfield placeholder. * @note available in python bindings as doActionFeature @@ -94,8 +101,10 @@ class CORE_EXPORT QgsActionManager /** * Return a list of actions that are available in the given action scope. * If no action scope is provided, all actions will be returned. + * + * @note Added in QGIS 3.0 */ - QList listActions( const QString& actionScope = QString() ) const; + QList actions( const QString& actionScope = QString() ) const; //! Return the layer QgsVectorLayer* layer() const { return mLayer; } diff --git a/src/gui/attributetable/qgsattributetableview.cpp b/src/gui/attributetable/qgsattributetableview.cpp index 33112dce7ef4..e3a3a287c5db 100644 --- a/src/gui/attributetable/qgsattributetableview.cpp +++ b/src/gui/attributetable/qgsattributetableview.cpp @@ -176,7 +176,7 @@ QWidget* QgsAttributeTableView::createActionWidget( QgsFeatureId fid ) QAction* defaultAction = nullptr; // first add user created layer actions - QList actions = mFilterModel->layer()->actions()->listActions( QStringLiteral( "Feature" ) ); + QList actions = mFilterModel->layer()->actions()->actions( QStringLiteral( "Feature" ) ); Q_FOREACH ( const QgsAction& action, actions ) { QString actionTitle = !action.shortTitle().isEmpty() ? action.shortTitle() : action.icon().isNull() ? action.name() : QLatin1String( "" ); diff --git a/src/gui/attributetable/qgsdualview.cpp b/src/gui/attributetable/qgsdualview.cpp index a5057103ab9c..e71608601a21 100644 --- a/src/gui/attributetable/qgsdualview.cpp +++ b/src/gui/attributetable/qgsdualview.cpp @@ -390,7 +390,7 @@ void QgsDualView::viewWillShowContextMenu( QMenu* menu, const QModelIndex& atInd } //add user-defined actions to context menu - QList actions = mLayerCache->layer()->actions()->listActions( QStringLiteral( "Field" ) ); + QList actions = mLayerCache->layer()->actions()->actions( QStringLiteral( "Field" ) ); if ( !actions.isEmpty() ) { QAction* a = menu->addAction( tr( "Run layer action" ) ); diff --git a/src/gui/qgsactionmenu.cpp b/src/gui/qgsactionmenu.cpp index f9683b08f446..fac834b43c01 100644 --- a/src/gui/qgsactionmenu.cpp +++ b/src/gui/qgsactionmenu.cpp @@ -105,7 +105,7 @@ void QgsActionMenu::reloadActions() { clear(); - mActions = mLayer->actions()->listActions( mActionScope ); + mActions = mLayer->actions()->actions( mActionScope ); Q_FOREACH ( const QgsAction& action, mActions ) { diff --git a/tests/src/python/test_qgsactionmanager.py b/tests/src/python/test_qgsactionmanager.py index 94cd19c36fe2..b6083d1171b2 100644 --- a/tests/src/python/test_qgsactionmanager.py +++ b/tests/src/python/test_qgsactionmanager.py @@ -22,7 +22,7 @@ QgsField, QgsFields ) -from qgis.PyQt.QtCore import QDir, QTemporaryFile +from qgis.PyQt.QtCore import QDir, QTemporaryFile, QUuid from qgis.testing import (start_app, unittest @@ -70,26 +70,26 @@ def testAddAction(self): """ Test adding actions """ # should be empty to start with - self.assertEqual(self.manager.listActions(), []) + self.assertEqual(self.manager.actions(), []) # add an action action1 = QgsAction(QgsAction.GenericPython, 'Test Action', 'i=1') self.manager.addAction(action1) - self.assertEqual(len(self.manager.listActions()), 1) - self.assertEqual(self.manager.listActions()[0].type(), QgsAction.GenericPython) - self.assertEqual(self.manager.listActions()[0].name(), 'Test Action') - self.assertEqual(self.manager.listActions()[0].command(), 'i=1') + self.assertEqual(len(self.manager.actions()), 1) + self.assertEqual(self.manager.actions()[0].type(), QgsAction.GenericPython) + self.assertEqual(self.manager.actions()[0].name(), 'Test Action') + self.assertEqual(self.manager.actions()[0].command(), 'i=1') # add another action action2 = QgsAction(QgsAction.Windows, 'Test Action2', 'i=2') self.manager.addAction(action2) - self.assertEqual(len(self.manager.listActions()), 2) + self.assertEqual(len(self.manager.actions()), 2) self.assertEqual(self.manager.action(action2.id()).type(), QgsAction.Windows) self.assertEqual(self.manager.action(action2.id()).name(), 'Test Action2') self.assertEqual(self.manager.action(action2.id()).command(), 'i=2') id3 = self.manager.addAction(QgsAction.Generic, 'Test Action3', 'i=3') - self.assertEqual(len(self.manager.listActions()), 3) + self.assertEqual(len(self.manager.actions()), 3) self.assertEqual(self.manager.action(id3).type(), QgsAction.Generic) self.assertEqual(self.manager.action(id3).name(), 'Test Action3') self.assertEqual(self.manager.action(id3).command(), 'i=3') @@ -102,8 +102,7 @@ def testRemoveActions(self): # clear the manager and check that it's empty self.manager.clearActions() - self.assertEqual(self.manager.size(), 0) - self.assertEqual(self.manager.listActions(), []) + self.assertEqual(self.manager.actions(), []) # add some actions id1 = self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1') @@ -111,66 +110,44 @@ def testRemoveActions(self): id3 = self.manager.addAction(QgsAction.GenericPython, 'test_action3', 'i=3') # remove non-existant action - self.manager.removeAction(5) + self.manager.removeAction(QUuid.createUuid()) # remove them one by one - self.manager.removeAction(1) - self.assertEqual(self.manager.size(), 2) - self.assertEqual(self.manager.listActions()[0].name(), 'test_action') - self.assertEqual(self.manager.listActions()[1].name(), 'test_action3') - self.manager.removeAction(0) - self.assertEqual(self.manager.size(), 1) - self.assertEqual(self.manager.listActions()[0].name(), 'test_action3') - self.manager.removeAction(0) - self.assertEqual(self.manager.size(), 0) - - def testRetrieveAction(self): - """ test retrieving actions """ - self.manager.clearActions() - - # test that exceptions are thrown when retrieving bad indices - - with self.assertRaises(KeyError): - self.manager[0] - - with self.assertRaises(KeyError): - self.manager.at(0) - - self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1') - - with self.assertRaises(KeyError): - self.manager[-1] - - with self.assertRaises(KeyError): - self.manager.at(-1) - - with self.assertRaises(KeyError): - self.manager[5] - - with self.assertRaises(KeyError): - self.manager.at(5) + self.manager.removeAction(id2) + self.assertEqual(len(self.manager.actions()), 2) + self.assertEqual(self.manager.action(id1).name(), 'test_action') + self.assertEqual(self.manager.action(id3).name(), 'test_action3') + self.manager.removeAction(id1) + self.assertEqual(len(self.manager.actions()), 1) + self.assertEqual(self.manager.action(id3).name(), 'test_action3') + self.manager.removeAction(id3) + self.assertEqual(len(self.manager.actions()), 0) def testDefaultAction(self): """ test default action for layer""" self.manager.clearActions() - self.manager.addAction(QgsAction.GenericPython, 'test_action', 'i=1') - self.manager.addAction(QgsAction.GenericPython, 'test_action2', 'i=2') + action1 = QgsAction(QgsAction.GenericPython, 'test_action', '', 'i=1', False, actionScopes={'Feature'}) + self.manager.addAction(action1) + action2 = QgsAction(QgsAction.GenericPython, 'test_action2', 'i=2') + self.manager.addAction(action2) # initially should be not set - self.assertEqual(self.manager.defaultAction(), -1) + self.assertFalse(self.manager.defaultAction('Feature').isValid()) # set bad default action - self.manager.setDefaultAction(10) - self.assertEqual(self.manager.defaultAction(), -1) + self.manager.setDefaultAction('Feature', QUuid.createUuid()) + self.assertFalse(self.manager.defaultAction('Feature').isValid()) # set good default action - self.manager.setDefaultAction(1) - self.assertEqual(self.manager.defaultAction(), 1) + self.manager.setDefaultAction('Feature', action1.id()) + self.assertTrue(self.manager.defaultAction('Feature').isValid()) + self.assertEquals(self.manager.defaultAction('Feature').id(), action1.id()) + self.assertNotEquals(self.manager.defaultAction('Feature').id(), action2.id()) # if default action is removed, should be reset to -1 self.manager.clearActions() - self.assertEqual(self.manager.defaultAction(), -1) + self.assertFalse(self.manager.defaultAction('Feature').isValid()) def check_action_result(self, temp_file): with open(temp_file, 'r') as result: @@ -185,7 +162,7 @@ def testDoAction(self): # simple action temp_file = self.get_temp_filename() - self.manager.addAction(QgsAction.Unix, 'test_action', self.create_action(temp_file, 'test output')) + id1 = self.manager.addAction(QgsAction.Unix, 'test_action', self.create_action(temp_file, 'test output')) fields = QgsFields() fields.append(QgsField('my_field')) @@ -195,28 +172,29 @@ def testDoAction(self): f.setAttributes([5, 'val']) c = QgsExpressionContext() - self.manager.doAction(0, f, c) + self.manager.doAction(id1, f, c) time.sleep(0.5) - self.assertEqual(self.check_action_result(temp_file), 'test output') + self.assertEquals(self.check_action_result(temp_file), 'test output') # action with substitutions temp_file = self.get_temp_filename() - self.manager.addAction(QgsAction.Unix, 'test_action', self.create_action(temp_file, 'test [% $id %] output [% @layer_name %]')) - self.manager.doAction(1, f, c) + id2 = self.manager.addAction(QgsAction.Unix, 'test_action', self.create_action(temp_file, 'test [% $id %] output [% @layer_name %]')) + self.manager.doAction(id2, f, c) time.sleep(0.5) - self.assertEqual(self.check_action_result(temp_file), 'test 1 output test_layer') + self.assertEquals(self.check_action_result(temp_file), 'test 1 output test_layer') # test doAction using field variant temp_file = self.get_temp_filename() - self.manager.addAction(QgsAction.Unix, 'test_action', self.create_action(temp_file, 'test [% @current_field %]')) - self.manager.doActionFeature(2, f, 0) + id3 = self.manager.addAction(QgsAction.Unix, 'test_action', + self.create_action(temp_file, 'test : [% @field_index %] : [% @field_name %] : [% @field_value%]')) + self.manager.doActionFeature(id3, f, 0) time.sleep(0.5) - self.assertEqual(self.check_action_result(temp_file), 'test 5') - self.manager.doActionFeature(2, f, 1) + self.assertEquals(self.check_action_result(temp_file), 'test : 0 : my_field : 5') + self.manager.doActionFeature(id3, f, 1) time.sleep(0.5) - self.assertEqual(self.check_action_result(temp_file), 'test val') + self.assertEquals(self.check_action_result(temp_file), 'test : 1 : my_other_field : val') if __name__ == '__main__': unittest.main() From f5f2850679ba5bcb7152b9f241a346eeb1750d26 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Tue, 8 Nov 2016 11:56:03 +0100 Subject: [PATCH 780/897] More api break documentation --- doc/api_break.dox | 24 +++++++++++++++++++----- src/gui/attributetable/qgsdualview.h | 1 + 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 991c154ba66a..87dcd05f3420 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -329,16 +329,30 @@ QgsAbstractGeometry {#qgis_api_break_3_0_QgsAbstractGeometry} QgsActionManager {#qgis_api_break_3_0_QgsActionManager} ---------------- -- doAction() no longer accepts a substitution map. Use expression context variables instead. -- The doAction() variant which takes a QgsFeature along has been removed. Use the expression context -variant instead. -- expandAction() has been removed. Use QgsExpression::replaceExpressionText() instead. -- setPythonExecute() was removed. Initialize QgsPythonRunner instead. +- `doAction()` no longer accepts a substitution map. Use expression context + variables instead. +- The `doAction()` variant which takes a QgsFeature along has been removed. Use + the expression context variant instead. +- `expandAction()` has been removed. Use + `QgsExpression::replaceExpressionText()` instead. +- `setPythonExecute()` was removed. Initialize `QgsPythonRunner` instead. +- `QgsActionManager::listActions()` has been renamed to `QgsActionManager::actions( actionScope )`. +- `QgsActionManager::removeAction()` takes an actions UUID instead of an index. +- `QgsActionManager::doAction()` takes an actions UUID instead of an index. +- `QgsActionManager::writeXml()` no longer takes a QDomDocument. The document is + extracted from the layerNode. +- `QgsActionManager::at()` has been removed. Use `QgsActionManager::action( id )` + to get an action by its UUID. +- `QgsActionManager::defaultAction()` works on a per-scope basis and with UUIDs + instead of indexes. + QgsAction {#qgis_api_break_3_0_QgsAction} --------- - `QgsAction::action()` has been renamed to `QgsAction::command()`. +- `QgsAction::showInAttributeTable()` has been removed. Use + `QgsAction::actionScopes()` instead and check for the 'Feature' scope. QgsAdvancedDigitizingDockWidget {#qgis_api_break_3_0_QgsAdvancedDigitizingDockWidget} diff --git a/src/gui/attributetable/qgsdualview.h b/src/gui/attributetable/qgsdualview.h index abb7524fdf23..867b6c036354 100644 --- a/src/gui/attributetable/qgsdualview.h +++ b/src/gui/attributetable/qgsdualview.h @@ -353,6 +353,7 @@ class GUI_EXPORT QgsAttributeTableAction : public QAction Q_OBJECT public: + /** * Create a new attribute table action. * From b32a719798917611c0a30bd044e55ac7ce4e423b Mon Sep 17 00:00:00 2001 From: nirvn Date: Tue, 15 Nov 2016 09:26:45 +0700 Subject: [PATCH 781/897] [symbology] draw effect(s) when rendering preview icon --- python/core/effects/qgspainteffect.sip | 33 +++++++++++++++ src/core/effects/qgspainteffect.cpp | 38 ++++++++++++++++++ src/core/effects/qgspainteffect.h | 51 ++++++++++++++++++++++++ src/core/symbology-ng/qgssymbol.cpp | 35 ++++------------ src/core/symbology-ng/qgssymbollayer.cpp | 33 +++++++++++++-- 5 files changed, 159 insertions(+), 31 deletions(-) diff --git a/python/core/effects/qgspainteffect.sip b/python/core/effects/qgspainteffect.sip index 0c22b5dd4e6d..7e524e516466 100644 --- a/python/core/effects/qgspainteffect.sip +++ b/python/core/effects/qgspainteffect.sip @@ -306,3 +306,36 @@ class QgsDrawSourceEffect : QgsPaintEffect virtual void draw( QgsRenderContext& context ); }; + +class QgsEffectPainter +{ +%TypeHeaderCode +#include +%End + public: + + /** + * QgsEffectPainter constructor + * + * @param renderContext the QgsRenderContext object + * @note Added in QGIS 3.0 + */ + QgsEffectPainter( QgsRenderContext& renderContext ); + + /** + * QgsEffectPainter constructor alternative if no painter translation is needed + * + * @param renderContext the QgsRenderContext object + * @param effect the QgsPaintEffect object + * @note Added in QGIS 3.0 + */ + QgsEffectPainter( QgsRenderContext& renderContext, QgsPaintEffect* effect ); + ~QgsEffectPainter(); + + /** + * Sets the effect to be painted + * + * @param effect the QgsPaintEffect object + */ + void setEffect( QgsPaintEffect* effect ); +}; diff --git a/src/core/effects/qgspainteffect.cpp b/src/core/effects/qgspainteffect.cpp index b2643b3cac01..31a2dc2a5c1a 100644 --- a/src/core/effects/qgspainteffect.cpp +++ b/src/core/effects/qgspainteffect.cpp @@ -322,3 +322,41 @@ void QgsDrawSourceEffect::readProperties( const QgsStringMap &props ) mEnabled = props.value( QStringLiteral( "enabled" ), QStringLiteral( "1" ) ).toInt(); mDrawMode = static_cast< QgsPaintEffect::DrawMode >( props.value( QStringLiteral( "draw_mode" ), QStringLiteral( "2" ) ).toInt() ); } + + +// +// QgsEffectPainter +// + +QgsEffectPainter::QgsEffectPainter( QgsRenderContext& renderContext ) + : mRenderContext( renderContext ) + , mEffect( nullptr ) +{ + mPainter = renderContext.painter(); + mPainter->save(); +} + +QgsEffectPainter::QgsEffectPainter( QgsRenderContext& renderContext, QgsPaintEffect* effect ) + : mRenderContext( renderContext ) + , mEffect( effect ) +{ + mPainter = mRenderContext.painter(); + mPainter->save(); + mEffect->begin( mRenderContext ); +} + +void QgsEffectPainter::setEffect( QgsPaintEffect* effect ) +{ + Q_ASSERT( !mEffect ); + + mEffect = effect; + mEffect->begin( mRenderContext ); +} + +QgsEffectPainter::~QgsEffectPainter() +{ + Q_ASSERT( mEffect ); + + mEffect->end( mRenderContext ); + mPainter->restore(); +} diff --git a/src/core/effects/qgspainteffect.h b/src/core/effects/qgspainteffect.h index 050c0985f6b2..03e85065becc 100644 --- a/src/core/effects/qgspainteffect.h +++ b/src/core/effects/qgspainteffect.h @@ -309,5 +309,56 @@ class CORE_EXPORT QgsDrawSourceEffect : public QgsPaintEffect QPainter::CompositionMode mBlendMode; }; +/** \ingroup core + * \class QgsEffectPainter + * \brief A class to manager painter saving and restoring required for effect drawing + * + * \note Added in version 3.0 + */ +class CORE_EXPORT QgsEffectPainter +{ + public: + + /** + * QgsEffectPainter constructor + * + * @param renderContext the QgsRenderContext object + * @note Added in QGIS 3.0 + */ + QgsEffectPainter( QgsRenderContext& renderContext ); + + /** + * QgsEffectPainter constructor alternative if no painter translation is needed + * + * @param renderContext the QgsRenderContext object + * @param effect the QgsPaintEffect object + * @note Added in QGIS 3.0 + */ + QgsEffectPainter( QgsRenderContext& renderContext, QgsPaintEffect* effect ); + ~QgsEffectPainter(); + + /** + * Sets the effect to be painted + * + * @param effect the QgsPaintEffect object + */ + void setEffect( QgsPaintEffect* effect ); + + ///@cond PRIVATE + + /** + * Access to the painter object + * + * @note Added in QGIS 3.0 + */ + QPainter* operator->() { return mPainter; } + ///@endcond + + private: + QgsRenderContext& mRenderContext; + QPainter* mPainter; + QgsPaintEffect* mEffect; +}; + #endif // QGSPAINTEFFECT_H diff --git a/src/core/symbology-ng/qgssymbol.cpp b/src/core/symbology-ng/qgssymbol.cpp index 0023e5e917d0..63db78bf928d 100644 --- a/src/core/symbology-ng/qgssymbol.cpp +++ b/src/core/symbology-ng/qgssymbol.cpp @@ -624,14 +624,8 @@ void QgsSymbol::renderUsingLayer( QgsSymbolLayer* layer, QgsSymbolRenderContext& QgsPaintEffect* effect = generatorLayer->paintEffect(); if ( effect && effect->enabled() ) { - QPainter* p = context.renderContext().painter(); - p->save(); - - effect->begin( context.renderContext() ); + QgsEffectPainter p( context.renderContext(), effect ); generatorLayer->render( context ); - effect->end( context.renderContext() ); - - p->restore(); } else { @@ -1428,15 +1422,10 @@ void QgsMarkerSymbol::renderPointUsingLayer( QgsMarkerSymbolLayer* layer, QPoint QgsPaintEffect* effect = layer->paintEffect(); if ( effect && effect->enabled() ) { - QPainter* p = context.renderContext().painter(); - p->save(); + QgsEffectPainter p( context.renderContext() ); p->translate( point ); - - effect->begin( context.renderContext() ); + p.setEffect( effect ); layer->renderPoint( nullPoint, context ); - effect->end( context.renderContext() ); - - p->restore(); } else { @@ -1709,15 +1698,10 @@ void QgsLineSymbol::renderPolylineUsingLayer( QgsLineSymbolLayer *layer, const Q QgsPaintEffect* effect = layer->paintEffect(); if ( effect && effect->enabled() ) { - QPainter* p = context.renderContext().painter(); - p->save(); + QgsEffectPainter p( context.renderContext() ); p->translate( points.boundingRect().topLeft() ); - - effect->begin( context.renderContext() ); + p.setEffect( effect ); layer->renderPolyline( points.translated( -points.boundingRect().topLeft() ), context ); - effect->end( context.renderContext() ); - - p->restore(); } else { @@ -1794,11 +1778,9 @@ void QgsFillSymbol::renderPolygonUsingLayer( QgsSymbolLayer* layer, const QPolyg QRectF bounds = polygonBounds( points, rings ); QList* translatedRings = translateRings( rings, -bounds.left(), -bounds.top() ); - QPainter* p = context.renderContext().painter(); - p->save(); + QgsEffectPainter p( context.renderContext() ); p->translate( bounds.topLeft() ); - - effect->begin( context.renderContext() ); + p.setEffect( effect ); if ( layertype == QgsSymbol::Fill ) { ( static_cast( layer ) )->renderPolygon( points.translated( -bounds.topLeft() ), translatedRings, context ); @@ -1808,9 +1790,6 @@ void QgsFillSymbol::renderPolygonUsingLayer( QgsSymbolLayer* layer, const QPolyg ( static_cast( layer ) )->renderPolygonOutline( points.translated( -bounds.topLeft() ), translatedRings, context ); } delete translatedRings; - - effect->end( context.renderContext() ); - p->restore(); } else { diff --git a/src/core/symbology-ng/qgssymbollayer.cpp b/src/core/symbology-ng/qgssymbollayer.cpp index fcf04070c372..9788442969a7 100644 --- a/src/core/symbology-ng/qgssymbollayer.cpp +++ b/src/core/symbology-ng/qgssymbollayer.cpp @@ -421,7 +421,16 @@ void QgsMarkerSymbolLayer::startRender( QgsSymbolRenderContext& context ) void QgsMarkerSymbolLayer::drawPreviewIcon( QgsSymbolRenderContext& context, QSize size ) { startRender( context ); - renderPoint( QPointF( size.width() / 2, size.height() / 2 ), context ); + QgsPaintEffect* effect = paintEffect(); + if ( effect && effect->enabled() ) + { + QgsEffectPainter p( context.renderContext(), effect ); + renderPoint( QPointF( size.width() / 2, size.height() / 2 ), context ); + } + else + { + renderPoint( QPointF( size.width() / 2, size.height() / 2 ), context ); + } stopRender( context ); } @@ -590,7 +599,16 @@ void QgsLineSymbolLayer::drawPreviewIcon( QgsSymbolRenderContext& context, QSize points << QPointF( 0, int( size.height() / 2 ) + 0.5 ) << QPointF( size.width(), int( size.height() / 2 ) + 0.5 ); startRender( context ); - renderPolyline( points, context ); + QgsPaintEffect* effect = paintEffect(); + if ( effect && effect->enabled() ) + { + QgsEffectPainter p( context.renderContext(), effect ); + renderPolyline( points, context ); + } + else + { + renderPolyline( points, context ); + } stopRender( context ); } @@ -615,7 +633,16 @@ void QgsFillSymbolLayer::drawPreviewIcon( QgsSymbolRenderContext& context, QSize { QPolygonF poly = QRectF( QPointF( 0, 0 ), QPointF( size.width(), size.height() ) ); startRender( context ); - renderPolygon( poly, nullptr, context ); + QgsPaintEffect* effect = paintEffect(); + if ( effect && effect->enabled() ) + { + QgsEffectPainter p( context.renderContext(), effect ); + renderPolygon( poly, nullptr, context ); + } + else + { + renderPolygon( poly, nullptr, context ); + } stopRender( context ); } From f2e3d5308d2b434e2b42cf8d613c55c2a1e3d249 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Wed, 16 Nov 2016 11:52:16 +0100 Subject: [PATCH 782/897] oracle provider: fix retrieval of column comments for geometryless tables (fixes #15853) (cherry picked from commit a62fdb085d741da898f2bbb048c33b58aee9d630) --- src/providers/oracle/qgsoracleprovider.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index e4d2a449f9e6..02247aa87796 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -582,13 +582,14 @@ bool QgsOracleProvider::loadFields() qry.finish(); - if ( exec( qry, QString( "SELECT column_name,comments FROM all_col_comments t WHERE t.owner=%1 AND t.table_name=%2 AND t.column_name<>%3" ) + if ( exec( qry, QString( "SELECT column_name,comments FROM all_col_comments t WHERE t.owner=%1 AND t.table_name=%2" ) .arg( quotedValue( mOwnerName ) ) - .arg( quotedValue( mTableName ) ) - .arg( quotedValue( mGeometryColumn ) ) ) ) + .arg( quotedValue( mTableName ) ) ) ) { while ( qry.next() ) { + if( qry.value( 0 ).toString() == mGeometryColumn ) + continue; comments.insert( qry.value( 0 ).toString(), qry.value( 1 ).toString() ); } } @@ -2153,7 +2154,7 @@ bool QgsOracleProvider::setSubsetString( const QString& theSQL, bool updateFeatu } qry.finish(); - if ( mPrimaryKeyType == pktInt && !uniqueData( mQuery, mAttributeFields.at( mPrimaryKeyAttrs[0] ).name() ) ) + if ( mPrimaryKeyType == pktInt && !mUseEstimatedMetadata && !uniqueData( mQuery, mAttributeFields.at( mPrimaryKeyAttrs[0] ).name() ) ) { mSqlWhereClause = prevWhere; return false; From 582a56d85c141a6f666787335c9daf91cc71172c Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Wed, 16 Nov 2016 13:09:08 +0100 Subject: [PATCH 783/897] fix f2e3d53 indentation --- src/providers/oracle/qgsoracleprovider.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index 02247aa87796..56441036cd95 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -588,8 +588,8 @@ bool QgsOracleProvider::loadFields() { while ( qry.next() ) { - if( qry.value( 0 ).toString() == mGeometryColumn ) - continue; + if ( qry.value( 0 ).toString() == mGeometryColumn ) + continue; comments.insert( qry.value( 0 ).toString(), qry.value( 1 ).toString() ); } } From 3242321aa9a3bc81d3db369edeadea4922ea861d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 22 Aug 2016 10:45:58 +1000 Subject: [PATCH 784/897] [FEATURE] Add method to get list of unique strings matching a substring from a vector data provider Base implementation iterates through all features, but providers can override with optimised versions. Native implementations for postgres, spatialite and OGR included. --- python/core/qgsvectordataprovider.sip | 12 +++ src/core/qgsvectordataprovider.cpp | 32 ++++++++ src/core/qgsvectordataprovider.h | 13 ++++ src/providers/ogr/qgsogrprovider.cpp | 54 ++++++++++++++ src/providers/ogr/qgsogrprovider.h | 3 + .../postgres/qgspostgresprovider.cpp | 47 ++++++++++++ src/providers/postgres/qgspostgresprovider.h | 2 + .../spatialite/qgsspatialiteprovider.cpp | 74 +++++++++++++++++++ .../spatialite/qgsspatialiteprovider.h | 3 + tests/src/python/providertestbase.py | 19 +++++ 10 files changed, 259 insertions(+) diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index bc2e70dec872..89c6c1ed1ac4 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -148,6 +148,18 @@ class QgsVectorDataProvider : QgsDataProvider */ virtual void uniqueValues( int index, QList &uniqueValues /Out/, int limit = -1 ) const; + /** + * Returns unique string values of an attribute which contain a specified subset string. Subset + * matching is done in a case-insensitive manner. + * @param index the index of the attribute + * @param substring substring to match (case insensitive) + * @param limit maxmum number of the values to return, or -1 to return all unique values + * @param feedback optional feedback object for cancelling request + * @returns list of unique strings containg substring + */ + virtual QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const; + /** Calculates an aggregated value from the layer's features. The base implementation does nothing, * but subclasses can override this method to handoff calculation of aggregates to the provider. * @param aggregate aggregate to calculate diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 2b50b78e2990..7c14a573d0d7 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -26,6 +26,7 @@ #include "qgsfeature.h" #include "qgsfeatureiterator.h" #include "qgsfeaturerequest.h" +#include "qgsfeedback.h" #include "qgsfields.h" #include "qgsgeometry.h" #include "qgsgeometrycollection.h" @@ -432,6 +433,37 @@ void QgsVectorDataProvider::uniqueValues( int index, QList &values, in } } +QStringList QgsVectorDataProvider::uniqueStringsMatching( int index, const QString& substring, int limit, QgsFeedback* feedback ) const +{ + QgsFeature f; + QgsAttributeList keys; + keys.append( index ); + + QgsFeatureRequest request; + request.setSubsetOfAttributes( keys ); + request.setFlags( QgsFeatureRequest::NoGeometry ); + QString fieldName = fields().at( index ).name(); + request.setFilterExpression( QStringLiteral( "\"%1\" ILIKE '%%2%'" ).arg( fieldName, substring ) ); + QgsFeatureIterator fi = getFeatures( request ); + + QSet set; + QStringList results; + + while ( fi.nextFeature( f ) ) + { + QString value = f.attribute( index ).toString(); + if ( !set.contains( value ) ) + { + results.append( value ); + set.insert( value ); + } + + if (( limit >= 0 && results.size() >= limit ) || ( feedback && feedback->isCancelled() ) ) + break; + } + return results; +} + QVariant QgsVectorDataProvider::aggregate( QgsAggregateCalculator::Aggregate aggregate, int index, const QgsAggregateCalculator::AggregateParameters& parameters, QgsExpressionContext* context, bool& ok ) const { diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index b95acfa4a541..3a523f187dac 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -36,6 +36,7 @@ typedef QHash QgsAttrPalIndexNameHash; class QgsFeatureIterator; class QgsTransaction; +class QgsFeedback; #include "qgsfeaturerequest.h" @@ -201,6 +202,18 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider */ virtual void uniqueValues( int index, QList &uniqueValues, int limit = -1 ) const; + /** + * Returns unique string values of an attribute which contain a specified subset string. Subset + * matching is done in a case-insensitive manner. + * @param index the index of the attribute + * @param substring substring to match (case insensitive) + * @param limit maxmum number of the values to return, or -1 to return all unique values + * @param feedback optional feedback object for cancelling request + * @returns list of unique strings containg substring + */ + virtual QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const; + /** Calculates an aggregated value from the layer's features. The base implementation does nothing, * but subclasses can override this method to handoff calculation of aggregates to the provider. * @param aggregate aggregate to calculate diff --git a/src/providers/ogr/qgsogrprovider.cpp b/src/providers/ogr/qgsogrprovider.cpp index efb7ae13d93b..baf668e022b4 100644 --- a/src/providers/ogr/qgsogrprovider.cpp +++ b/src/providers/ogr/qgsogrprovider.cpp @@ -20,6 +20,7 @@ email : sherman at mrcc.com #include "qgslogger.h" #include "qgsmessagelog.h" #include "qgslocalec.h" +#include "qgsfeedback.h" #define CPL_SUPRESS_CPLUSPLUS #include // to collect version information @@ -2924,6 +2925,59 @@ void QgsOgrProvider::uniqueValues( int index, QList &uniqueValues, int #endif } +QStringList QgsOgrProvider::uniqueStringsMatching( int index, const QString& substring, int limit, QgsFeedback* feedback ) const +{ + QStringList results; + + if ( !mValid || index < 0 || index >= mAttributeFields.count() ) + return results; + + QgsField fld = mAttributeFields.at( index ); + if ( fld.name().isNull() ) + { + return results; //not a provider field + } + +#if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM < 1910 + // avoid GDAL #4509 + return QgsVectorDataProvider::uniqueStringsMatching( index, substring, limit, feedback ); +#else + QByteArray sql = "SELECT DISTINCT " + quotedIdentifier( textEncoding()->fromUnicode( fld.name() ) ); + sql += " FROM " + quotedIdentifier( OGR_FD_GetName( OGR_L_GetLayerDefn( ogrLayer ) ) ); + + sql += " WHERE " + quotedIdentifier( textEncoding()->fromUnicode( fld.name() ) ) + " LIKE '%" + textEncoding()->fromUnicode( substring ) + "%'"; + + if ( !mSubsetString.isEmpty() ) + { + sql += " AND (" + textEncoding()->fromUnicode( mSubsetString ) + ')'; + } + + sql += " ORDER BY " + textEncoding()->fromUnicode( fld.name() ) + " ASC"; // quoting of fieldname produces a syntax error + + QgsDebugMsg( QString( "SQL: %1" ).arg( textEncoding()->toUnicode( sql ) ) ); + OGRLayerH l = OGR_DS_ExecuteSQL( ogrDataSource, sql.constData(), nullptr, nullptr ); + if ( !l ) + { + QgsDebugMsg( "Failed to execute SQL" ); + return QgsVectorDataProvider::uniqueStringsMatching( index, substring, limit, feedback ); + } + + OGRFeatureH f; + while (( f = OGR_L_GetNextFeature( l ) ) ) + { + if ( OGR_F_IsFieldSet( f, 0 ) ) + results << textEncoding()->toUnicode( OGR_F_GetFieldAsString( f, 0 ) ); + OGR_F_Destroy( f ); + + if (( limit >= 0 && results.size() >= limit ) || ( feedback && feedback->isCancelled() ) ) + break; + } + + OGR_DS_ReleaseResultSet( ogrDataSource, l ); + return results; +#endif +} + QVariant QgsOgrProvider::minimumValue( int index ) const { if ( !mValid || index < 0 || index >= mAttributeFields.count() ) diff --git a/src/providers/ogr/qgsogrprovider.h b/src/providers/ogr/qgsogrprovider.h index 5557f7ac6c5a..4e631bf2590b 100644 --- a/src/providers/ogr/qgsogrprovider.h +++ b/src/providers/ogr/qgsogrprovider.h @@ -207,6 +207,9 @@ class QgsOgrProvider : public QgsVectorDataProvider */ virtual void uniqueValues( int index, QList &uniqueValues, int limit = -1 ) const override; + virtual QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const override; + /** Return a provider name * * Essentially just returns the provider key. Should be used to build file diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index b5ae64f944b2..e649abb25a53 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -37,6 +37,7 @@ #include "qgspostgresfeatureiterator.h" #include "qgspostgrestransaction.h" #include "qgslogger.h" +#include "qgsfeedback.h" const QString POSTGRES_KEY = QStringLiteral( "postgres" ); const QString POSTGRES_DESCRIPTION = QStringLiteral( "PostgreSQL/PostGIS data provider" ); @@ -1573,6 +1574,52 @@ void QgsPostgresProvider::uniqueValues( int index, QList &uniqueValues } } +QStringList QgsPostgresProvider::uniqueStringsMatching( int index, const QString& substring, int limit, QgsFeedback* feedback ) const +{ + QStringList results; + + try + { + // get the field name + QgsField fld = field( index ); + QString sql = QString( "SELECT DISTINCT %1 FROM %2 WHERE" ) + .arg( quotedIdentifier( fld.name() ), + mQuery ); + + if ( !mSqlWhereClause.isEmpty() ) + { + sql += QString( " ( %1 ) AND " ).arg( mSqlWhereClause ); + } + + sql += QString( " %1 ILIKE '%%2%'" ).arg( quotedIdentifier( fld.name() ), substring ); + + + sql += QString( " ORDER BY %1" ).arg( quotedIdentifier( fld.name() ) ); + + if ( limit >= 0 ) + { + sql += QString( " LIMIT %1" ).arg( limit ); + } + + sql = QString( "SELECT %1 FROM (%2) foo" ).arg( connectionRO()->fieldExpression( fld ), sql ); + + QgsPostgresResult res( connectionRO()->PQexec( sql ) ); + if ( res.PQresultStatus() == PGRES_TUPLES_OK ) + { + for ( int i = 0; i < res.PQntuples(); i++ ) + { + results << ( convertValue( fld.type(), fld.subType(), res.PQgetvalue( i, 0 ) ) ).toString(); + if ( feedback && feedback->isCancelled() ) + break; + } + } + } + catch ( PGFieldNotFound ) + { + } + return results; +} + void QgsPostgresProvider::enumValues( int index, QStringList& enumList ) const { enumList.clear(); diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index b9130c39db38..f5373a2987b5 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -155,6 +155,8 @@ class QgsPostgresProvider : public QgsVectorDataProvider QVariant minimumValue( int index ) const override; QVariant maximumValue( int index ) const override; virtual void uniqueValues( int index, QList &uniqueValues, int limit = -1 ) const override; + virtual QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const override; virtual void enumValues( int index, QStringList& enumList ) const override; bool isValid() const override; virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index a06b3562cd7f..dd19b14ef65a 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -29,6 +29,7 @@ email : a.furieri@lqt.it #include "qgsspatialiteprovider.h" #include "qgsspatialiteconnpool.h" #include "qgsspatialitefeatureiterator.h" +#include "qgsfeedback.h" #include #include @@ -3702,6 +3703,79 @@ void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueV return; } +QStringList QgsSpatiaLiteProvider::uniqueStringsMatching( int index, const QString& substring, int limit, QgsFeedback* feedback ) const +{ + QStringList results; + + sqlite3_stmt *stmt = nullptr; + QString sql; + + // get the field name + if ( index < 0 || index >= mAttributeFields.count() ) + { + return results; //invalid field + } + QgsField fld = mAttributeFields.at( index ); + + sql = QStringLiteral( "SELECT DISTINCT %1 FROM %2 " ).arg( quotedIdentifier( fld.name() ), mQuery ); + sql += QStringLiteral( " WHERE " ) + quotedIdentifier( fld.name() ) + QStringLiteral( " LIKE '%" ) + substring + QStringLiteral( "%'" ); + + if ( !mSubsetString.isEmpty() ) + { + sql += QStringLiteral( " AND ( " ) + mSubsetString + ')'; + } + + sql += QStringLiteral( " ORDER BY %1" ).arg( quotedIdentifier( fld.name() ) ); + + if ( limit >= 0 ) + { + sql += QStringLiteral( " LIMIT %1" ).arg( limit ); + } + + // SQLite prepared statement + if ( sqlite3_prepare_v2( mSqliteHandle, sql.toUtf8().constData(), -1, &stmt, nullptr ) != SQLITE_OK ) + { + // some error occurred + QgsMessageLog::logMessage( tr( "SQLite error: %2\nSQL: %1" ).arg( sql, sqlite3_errmsg( mSqliteHandle ) ), tr( "SpatiaLite" ) ); + return results; + } + + while (( limit < 0 || results.size() < limit ) && ( !feedback || !feedback->isCancelled() ) ) + { + // this one is an infinitive loop, intended to fetch any row + int ret = sqlite3_step( stmt ); + + if ( ret == SQLITE_DONE ) + { + // there are no more rows to fetch - we can stop looping + break; + } + + if ( ret == SQLITE_ROW ) + { + // fetching one column value + switch ( sqlite3_column_type( stmt, 0 ) ) + { + case SQLITE_TEXT: + results.append( QString::fromUtf8(( const char * ) sqlite3_column_text( stmt, 0 ) ) ); + break; + default: + break; + } + } + else + { + QgsMessageLog::logMessage( tr( "SQLite error: %2\nSQL: %1" ).arg( sql, sqlite3_errmsg( mSqliteHandle ) ), tr( "SpatiaLite" ) ); + sqlite3_finalize( stmt ); + return results; + } + } + + sqlite3_finalize( stmt ); + + return results; +} + QString QgsSpatiaLiteProvider::geomParam() const { QString geometry; diff --git a/src/providers/spatialite/qgsspatialiteprovider.h b/src/providers/spatialite/qgsspatialiteprovider.h index 990634971db1..2ac844b6f843 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.h +++ b/src/providers/spatialite/qgsspatialiteprovider.h @@ -131,6 +131,9 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider QVariant maximumValue( int index ) const override; virtual void uniqueValues( int index, QList < QVariant > &uniqueValues, int limit = -1 ) const override; + virtual QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const override; + bool isValid() const override; virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } diff --git a/tests/src/python/providertestbase.py b/tests/src/python/providertestbase.py index a492ac1d58fa..003ba7f27813 100644 --- a/tests/src/python/providertestbase.py +++ b/tests/src/python/providertestbase.py @@ -566,6 +566,25 @@ def testUnique(self): self.provider.setSubsetString(None) self.assertEqual(set(values), set([200, 300])) + def testUniqueStringsMatching(self): + self.assertEqual(set(self.provider.uniqueStringsMatching(2, 'a')), set(['Pear', 'Orange', 'Apple'])) + # test case insensitive + self.assertEqual(set(self.provider.uniqueStringsMatching(2, 'A')), set(['Pear', 'Orange', 'Apple'])) + # test string ending in substring + self.assertEqual(set(self.provider.uniqueStringsMatching(2, 'ney')), set(['Honey'])) + # test limit + result = set(self.provider.uniqueStringsMatching(2, 'a', 2)) + self.assertEqual(len(result), 2) + self.assertTrue(result.issubset(set(['Pear', 'Orange', 'Apple']))) + + assert set([u'Apple', u'Honey', u'Orange', u'Pear', NULL]) == set(self.provider.uniqueValues(2)), 'Got {}'.format(set(self.provider.uniqueValues(2))) + + subset = self.getSubsetString2() + self.provider.setSubsetString(subset) + values = self.provider.uniqueStringsMatching(2, 'a') + self.provider.setSubsetString(None) + self.assertEqual(set(values), set(['Pear', 'Apple'])) + def testFeatureCount(self): assert self.provider.featureCount() == 5, 'Got {}'.format(self.provider.featureCount()) From 4682eaf6ebd212d1e31fa07ce29f0a1f01a35fba Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 13:22:18 +1000 Subject: [PATCH 785/897] Add QgsVectorLayer::uniqueStringsMatching() to retrieve a list of unique strings matching a substring for a field --- python/core/qgsvectorlayer.sip | 16 ++++ src/core/qgsvectordataprovider.h | 2 +- src/core/qgsvectorlayer.cpp | 102 ++++++++++++++++++++++++ src/core/qgsvectorlayer.h | 17 ++++ tests/src/python/test_qgsvectorlayer.py | 47 +++++++++++ 5 files changed, 183 insertions(+), 1 deletion(-) diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index 6957294a7a8e..2b13f9d9b461 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -1326,6 +1326,22 @@ class QgsVectorLayer : QgsMapLayer, QgsExpressionContextGenerator */ void uniqueValues( int index, QList &uniqueValues /Out/, int limit = -1 ) const; + /** + * Returns unique string values of an attribute which contain a specified subset string. Subset + * matching is done in a case-insensitive manner. Note that + * in some circumstances when unsaved changes are present for the layer then the returned list + * may contain outdated values (for instance when the attribute value in a saved feature has + * been changed inside the edit buffer then the previous saved value will be included in the + * returned list). + * @param index column index for attribute + * @param substring substring to match (case insensitive) + * @param limit maxmum number of the values to return, or -1 to return all unique values + * @param feedback optional feedback object for cancelling request + * @returns list of unique strings containing substring + */ + QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const; + /** Returns the minimum value for an attribute column or an invalid variant in case of error. * Note that in some circumstances when unsaved changes are present for the layer then the * returned value may be outdated (for instance when the attribute value in a saved feature has diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index 3a523f187dac..a9d257e30dae 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -209,7 +209,7 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider * @param substring substring to match (case insensitive) * @param limit maxmum number of the values to return, or -1 to return all unique values * @param feedback optional feedback object for cancelling request - * @returns list of unique strings containg substring + * @returns list of unique strings containing substring */ virtual QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, QgsFeedback* feedback = nullptr ) const; diff --git a/src/core/qgsvectorlayer.cpp b/src/core/qgsvectorlayer.cpp index 2bdb2d76f5d7..6e4d1d89f474 100644 --- a/src/core/qgsvectorlayer.cpp +++ b/src/core/qgsvectorlayer.cpp @@ -82,6 +82,7 @@ #include "qgspallabeling.h" #include "qgssimplifymethod.h" #include "qgsexpressioncontext.h" +#include "qgsfeedback.h" #include "diagram/qgsdiagram.h" @@ -3223,6 +3224,107 @@ void QgsVectorLayer::uniqueValues( int index, QList &uniqueValues, int Q_ASSERT_X( false, "QgsVectorLayer::uniqueValues()", "Unknown source of the field!" ); } +QStringList QgsVectorLayer::uniqueStringsMatching( int index, const QString& substring, int limit, QgsFeedback* feedback ) const +{ + QStringList results; + if ( !mDataProvider ) + { + return results; + } + + QgsFields::FieldOrigin origin = mFields.fieldOrigin( index ); + switch ( origin ) + { + case QgsFields::OriginUnknown: + return results; + + case QgsFields::OriginProvider: //a provider field + { + results = mDataProvider->uniqueStringsMatching( index, substring, limit, feedback ); + + if ( mEditBuffer ) + { + QgsFeatureMap added = mEditBuffer->addedFeatures(); + QMapIterator< QgsFeatureId, QgsFeature > addedIt( added ); + while ( addedIt.hasNext() && ( limit < 0 || results.count() < limit ) && ( !feedback || !feedback->isCancelled() ) ) + { + addedIt.next(); + QVariant v = addedIt.value().attribute( index ); + if ( v.isValid() ) + { + QString vs = v.toString(); + if ( vs.contains( substring, Qt::CaseInsensitive ) && !results.contains( vs ) ) + { + results << vs; + } + } + } + + QMapIterator< QgsFeatureId, QgsAttributeMap > it( mEditBuffer->changedAttributeValues() ); + while ( it.hasNext() && ( limit < 0 || results.count() < limit ) && ( !feedback || !feedback->isCancelled() ) ) + { + it.next(); + QVariant v = it.value().value( index ); + if ( v.isValid() ) + { + QString vs = v.toString(); + if ( vs.contains( substring, Qt::CaseInsensitive ) && !results.contains( vs ) ) + { + results << vs; + } + } + } + } + + return results; + } + + case QgsFields::OriginEdit: + // the layer is editable, but in certain cases it can still be avoided going through all features + if ( mEditBuffer->mDeletedFeatureIds.isEmpty() && + mEditBuffer->mAddedFeatures.isEmpty() && + !mEditBuffer->mDeletedAttributeIds.contains( index ) && + mEditBuffer->mChangedAttributeValues.isEmpty() ) + { + return mDataProvider->uniqueStringsMatching( index, substring, limit, feedback ); + } + FALLTHROUGH; + //we need to go through each feature + case QgsFields::OriginJoin: + case QgsFields::OriginExpression: + { + QgsAttributeList attList; + attList << index; + + QgsFeatureRequest request; + request.setSubsetOfAttributes( attList ); + request.setFlags( QgsFeatureRequest::NoGeometry ); + QString fieldName = mFields.at( index ).name(); + request.setFilterExpression( QStringLiteral( "\"%1\" ILIKE '%%2%'" ).arg( fieldName, substring ) ); + QgsFeatureIterator fit = getFeatures( request ); + + QgsFeature f; + QString currentValue; + while ( fit.nextFeature( f ) ) + { + currentValue = f.attribute( index ).toString(); + if ( !results.contains( currentValue ) ) + results << currentValue; + + if (( limit >= 0 && results.size() >= limit ) || ( feedback && feedback->isCancelled() ) ) + { + break; + } + } + + return results; + } + } + + Q_ASSERT_X( false, "QgsVectorLayer::uniqueStringsMatching()", "Unknown source of the field!" ); + return results; +} + QVariant QgsVectorLayer::minimumValue( int index ) const { if ( !mDataProvider ) diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index da3955d991c0..06fa519480c5 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -68,6 +68,7 @@ class QgsVectorLayerEditBuffer; class QgsVectorLayerJoinBuffer; class QgsAbstractVectorLayerLabeling; class QgsPointV2; +class QgsFeedback; typedef QList QgsAttributeList; typedef QSet QgsAttributeIds; @@ -1468,6 +1469,22 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte */ void uniqueValues( int index, QList &uniqueValues, int limit = -1 ) const; + /** + * Returns unique string values of an attribute which contain a specified subset string. Subset + * matching is done in a case-insensitive manner. Note that + * in some circumstances when unsaved changes are present for the layer then the returned list + * may contain outdated values (for instance when the attribute value in a saved feature has + * been changed inside the edit buffer then the previous saved value will be included in the + * returned list). + * @param index column index for attribute + * @param substring substring to match (case insensitive) + * @param limit maxmum number of the values to return, or -1 to return all unique values + * @param feedback optional feedback object for cancelling request + * @returns list of unique strings containing substring + */ + QStringList uniqueStringsMatching( int index, const QString& substring, int limit = -1, + QgsFeedback* feedback = nullptr ) const; + /** Returns the minimum value for an attribute column or an invalid variant in case of error. * Note that in some circumstances when unsaved changes are present for the layer then the * returned value may be outdated (for instance when the attribute value in a saved feature has diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index 90f1df330250..9ff62591d74c 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1295,6 +1295,53 @@ def testUniqueValue(self): # note - this isn't 100% accurate, since 123 no longer exists - but it avoids looping through all features self.assertEqual(set(layer.uniqueValues(1)), set([123, 457, 888, -1, 0, 999, 9999, 481523])) + def testUniqueStringsMatching(self): + """ test retrieving unique strings matching subset """ + layer = QgsVectorLayer("Point?field=fldtxt:string", "addfeat", "memory") + pr = layer.dataProvider() + f = QgsFeature() + f.setAttributes(["apple"]) + f2 = QgsFeature() + f2.setAttributes(["orange"]) + f3 = QgsFeature() + f3.setAttributes(["pear"]) + f4 = QgsFeature() + f4.setAttributes(["BanaNa"]) + f5 = QgsFeature() + f5.setAttributes(["ApriCot"]) + assert pr.addFeatures([f, f2, f3, f4, f5]) + assert layer.featureCount() == 5 + + # test layer with just provider features + self.assertEqual(set(layer.uniqueStringsMatching(0, 'N')), set(['orange', 'BanaNa'])) + + # add feature with new value + layer.startEditing() + f1 = QgsFeature() + f1.setAttributes(["waterMelon"]) + self.assertTrue(layer.addFeature(f1)) + + # should be included in unique values + self.assertEqual(set(layer.uniqueStringsMatching(0, 'N')), set(['orange', 'BanaNa', 'waterMelon'])) + # add it again, should be no change + f2 = QgsFeature() + f2.setAttributes(["waterMelon"]) + self.assertTrue(layer.addFeature(f1)) + self.assertEqual(set(layer.uniqueStringsMatching(0, 'N')), set(['orange', 'BanaNa', 'waterMelon'])) + self.assertEqual(set(layer.uniqueStringsMatching(0, 'aN')), set(['orange', 'BanaNa'])) + # add another feature + f3 = QgsFeature() + f3.setAttributes(["pineapple"]) + self.assertTrue(layer.addFeature(f3)) + self.assertEqual(set(layer.uniqueStringsMatching(0, 'n')), set(['orange', 'BanaNa', 'waterMelon', 'pineapple'])) + + # change an attribute value to a new unique value + f = QgsFeature() + f1_id = next(layer.getFeatures()).id() + self.assertTrue(layer.changeAttributeValue(f1_id, 0, 'coconut')) + # note - this isn't 100% accurate, since orange no longer exists - but it avoids looping through all features + self.assertEqual(set(layer.uniqueStringsMatching(0, 'n')), set(['orange', 'BanaNa', 'waterMelon', 'pineapple', 'coconut'])) + def testMinValue(self): """ test retrieving minimum values """ layer = createLayerWithFivePoints() From 747097d43d2c772e862a43637fa1ebd0f6f38aa7 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 15:44:25 +1000 Subject: [PATCH 786/897] New method QgsVectorLayerUtils::createUniqueValue Returns a new unique attribute value for a layer. For numeric fields this is the max attribute value + 1, for strings we attempt to create a unique value by append _1, _2, etc to either a specified 'seed' value, or failing that to the end of the value of that field from the first feature in the layer. --- python/core/qgsvectorlayerutils.sip | 8 ++ src/core/qgsvectorlayerutils.cpp | 81 ++++++++++++++++++++ src/core/qgsvectorlayerutils.h | 9 +++ tests/src/python/test_qgsvectorlayerutils.py | 32 ++++++++ 4 files changed, 130 insertions(+) diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip index f5a9e5da674d..0c61f30a46fc 100644 --- a/python/core/qgsvectorlayerutils.sip +++ b/python/core/qgsvectorlayerutils.sip @@ -16,9 +16,17 @@ class QgsVectorLayerUtils * Returns true if the specified value already exists within a field. This method can be used to test for uniqueness * of values inside a layer's attributes. An optional list of ignored feature IDs can be provided, if so, any features * with IDs within this list are ignored when testing for existance of the value. + * @see createUniqueValue() */ static bool valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds = QgsFeatureIds() ); + /** + * Returns a new attribute value for the specified field index which is guaranteed to be unique. The optional seed + * value can be used as a basis for generated values. + * @see valueExists() + */ + static QVariant createUniqueValue( const QgsVectorLayer* layer, int fieldIndex, const QVariant& seed = QVariant() ); + /** * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index 0ae2ab27e1cb..d5845e97eaeb 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -15,6 +15,7 @@ #include "qgsvectorlayerutils.h" #include "qgsvectordataprovider.h" +#include bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds ) { @@ -65,6 +66,86 @@ bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldInd return false; } +QVariant QgsVectorLayerUtils::createUniqueValue( const QgsVectorLayer* layer, int fieldIndex, const QVariant& seed ) +{ + if ( !layer ) + return QVariant(); + + QgsFields fields = layer->fields(); + + if ( fieldIndex < 0 || fieldIndex >= fields.count() ) + return QVariant(); + + QgsField field = fields.at( fieldIndex ); + + if ( field.isNumeric() ) + { + QVariant maxVal = layer->maximumValue( fieldIndex ); + QVariant newVar( maxVal.toLongLong() + 1 ); + if ( field.convertCompatible( newVar ) ) + return newVar; + else + return QVariant(); + } + else + { + switch ( field.type() ) + { + case QVariant::String: + { + QString base; + if ( seed.isValid() ) + base = seed.toString(); + + if ( !base.isEmpty() ) + { + // strip any existing _1, _2 from the seed + QRegularExpression rx( "(.*)_\\d+" ); + QRegularExpressionMatch match = rx.match( base ); + if ( match.hasMatch() ) + { + base = match.captured( 1 ); + } + } + else + { + // no base seed - fetch first value from layer + QgsFeatureRequest req; + req.setLimit( 1 ); + req.setSubsetOfAttributes( QgsAttributeList() << fieldIndex ); + req.setFlags( QgsFeatureRequest::NoGeometry ); + QgsFeature f; + layer->getFeatures( req ).nextFeature( f ); + base = f.attribute( fieldIndex ).toString(); + } + + // try variants like base_1, base_2, etc until a new value found + QStringList vals = layer->uniqueStringsMatching( fieldIndex, base ); + + // might already be unique + if ( !base.isEmpty() && !vals.contains( base ) ) + return base; + + for ( int i = 1; i < 10000; ++i ) + { + QString testVal = base + '_' + QString::number( i ); + if ( !vals.contains( testVal ) ) + return testVal; + } + + // failed + return QVariant(); + } + + default: + // todo other types - dates? times? + return QVariant(); + } + } + + return QVariant(); +} + bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const QgsFeature& feature, int attributeIndex, QStringList& errors, QgsFieldConstraints::ConstraintStrength strength, QgsFieldConstraints::ConstraintOrigin origin ) { diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h index 5d2ae5984f65..9235de340422 100644 --- a/src/core/qgsvectorlayerutils.h +++ b/src/core/qgsvectorlayerutils.h @@ -33,9 +33,17 @@ class CORE_EXPORT QgsVectorLayerUtils * Returns true if the specified value already exists within a field. This method can be used to test for uniqueness * of values inside a layer's attributes. An optional list of ignored feature IDs can be provided, if so, any features * with IDs within this list are ignored when testing for existance of the value. + * @see createUniqueValue() */ static bool valueExists( const QgsVectorLayer* layer, int fieldIndex, const QVariant& value, const QgsFeatureIds& ignoreIds = QgsFeatureIds() ); + /** + * Returns a new attribute value for the specified field index which is guaranteed to be unique. The optional seed + * value can be used as a basis for generated values. + * @see valueExists() + */ + static QVariant createUniqueValue( const QgsVectorLayer* layer, int fieldIndex, const QVariant& seed = QVariant() ); + /** * Tests an attribute value to check whether it passes all constraints which are present on the corresponding field. * Returns true if the attribute value is valid for the field. Any constraint failures will be reported in the errors argument. @@ -45,6 +53,7 @@ class CORE_EXPORT QgsVectorLayerUtils QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); + }; #endif // QGSVECTORLAYERUTILS_H diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py index 787bbc5e6460..c94154c0a233 100644 --- a/tests/src/python/test_qgsvectorlayerutils.py +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -178,6 +178,38 @@ def test_validate_attribute(self): self.assertEqual(len(errors), 2) print(errors) + def testCreateUniqueValue(self): + """ test creating a unique value """ + layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer&field=flddbl:double", + "addfeat", "memory") + # add a bunch of features + f = QgsFeature() + f.setAttributes(["test", 123, 1.0]) + f1 = QgsFeature(2) + f1.setAttributes(["test_1", 124, 1.1]) + f2 = QgsFeature(3) + f2.setAttributes(["test_2", 125, 2.4]) + f3 = QgsFeature(4) + f3.setAttributes(["test_3", 126, 1.7]) + f4 = QgsFeature(5) + f4.setAttributes(["superpig", 127, 0.8]) + self.assertTrue(layer.dataProvider().addFeatures([f, f1, f2, f3, f4])) + + # bad field indices + self.assertFalse(QgsVectorLayerUtils.createUniqueValue(layer, -10)) + self.assertFalse(QgsVectorLayerUtils.createUniqueValue(layer, 10)) + + # integer field + self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 1), 128) + + # double field + self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 2), 3.0) + + # string field + self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 0), 'test_4') + self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 0, 'test_1'), 'test_4') + self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 0, 'seed'), 'seed') + self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 0, 'superpig'), 'superpig_1') if __name__ == '__main__': unittest.main() From 95271c869bbe489404f85696d7d1cef029ab8e24 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 16:01:16 +1000 Subject: [PATCH 787/897] Fix clearing constraints --- src/app/qgsfieldsproperties.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/app/qgsfieldsproperties.cpp b/src/app/qgsfieldsproperties.cpp index 88ddc58b44e4..688597bc1fca 100644 --- a/src/app/qgsfieldsproperties.cpp +++ b/src/app/qgsfieldsproperties.cpp @@ -1001,14 +1001,26 @@ void QgsFieldsProperties::apply() { mLayer->setFieldConstraint( i, QgsFieldConstraints::ConstraintNotNull, cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintStrengthHard ) ); } + else + { + mLayer->removeFieldConstraint( i, QgsFieldConstraints::ConstraintNotNull ); + } if ( cfg.mConstraints & QgsFieldConstraints::ConstraintUnique ) { mLayer->setFieldConstraint( i, QgsFieldConstraints::ConstraintUnique, cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintStrengthHard ) ); } + else + { + mLayer->removeFieldConstraint( i, QgsFieldConstraints::ConstraintUnique ); + } if ( cfg.mConstraints & QgsFieldConstraints::ConstraintExpression ) { mLayer->setFieldConstraint( i, QgsFieldConstraints::ConstraintExpression, cfg.mConstraintStrength.value( QgsFieldConstraints::ConstraintExpression, QgsFieldConstraints::ConstraintStrengthHard ) ); } + else + { + mLayer->removeFieldConstraint( i, QgsFieldConstraints::ConstraintExpression ); + } if ( mFieldsList->item( i, attrWMSCol )->checkState() == Qt::Unchecked ) { From b5864cd4327a09f2bf2b0afffa09582370c6f194 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 8 Nov 2016 16:59:07 +1000 Subject: [PATCH 788/897] [FEATURE] Improve handling of defaults (inc provider default clauses, literal defaults, and qgis expression defaults) and automatically handle unique value constraints on layers Add a new method QgsVectorLayerUtils::createFeature which returns a new feature which includes all relevant defaults. Any fields with unique value constraints will be guaranteed to have a value which is unique for the field. Currently only in use by the split feature tool. Sponsored by Canton of Zug and the QGEP project --- python/core/qgsvectorlayerutils.sip | 12 +++ src/core/qgsvectorlayereditutils.cpp | 29 +----- src/core/qgsvectorlayereditutils.h | 1 + src/core/qgsvectorlayerutils.cpp | 92 +++++++++++++++++++ src/core/qgsvectorlayerutils.h | 12 +++ .../spatialite/qgsspatialiteprovider.cpp | 12 +++ tests/src/python/test_provider_postgres.py | 15 +++ tests/src/python/test_provider_spatialite.py | 37 +++++--- tests/src/python/test_qgsvectorlayerutils.py | 61 ++++++++++++ 9 files changed, 230 insertions(+), 41 deletions(-) diff --git a/python/core/qgsvectorlayerutils.sip b/python/core/qgsvectorlayerutils.sip index 0c61f30a46fc..1420179d669e 100644 --- a/python/core/qgsvectorlayerutils.sip +++ b/python/core/qgsvectorlayerutils.sip @@ -36,4 +36,16 @@ class QgsVectorLayerUtils QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); + /** + * Creates a new feature ready for insertion into a layer. Default values and constraints + * (eg unique constraints) will automatically be handled. An optional attribute map can be + * passed for the new feature to copy as many attribute values as possible from the map, + * assuming that they respect the layer's constraints. Note that the created feature is not + * automatically inserted into the layer. + */ + static QgsFeature createFeature( QgsVectorLayer* layer, + const QgsGeometry& geometry = QgsGeometry(), + const QgsAttributeMap& attributes = QgsAttributeMap(), + QgsExpressionContext* context = nullptr ); + }; diff --git a/src/core/qgsvectorlayereditutils.cpp b/src/core/qgsvectorlayereditutils.cpp index 5cab0b5844e6..5436bfdf2969 100644 --- a/src/core/qgsvectorlayereditutils.cpp +++ b/src/core/qgsvectorlayereditutils.cpp @@ -24,6 +24,7 @@ #include "qgsgeometryfactory.h" #include "qgis.h" #include "qgswkbtypes.h" +#include "qgsvectorlayerutils.h" #include @@ -371,28 +372,8 @@ int QgsVectorLayerEditUtils::splitFeatures( const QList& splitLine, bo //insert new features for ( int i = 0; i < newGeometries.size(); ++i ) { - QgsFeature newFeature; - newFeature.setGeometry( newGeometries.at( i ) ); - - //use default value where possible for primary key (e.g. autoincrement), - //and use the value from the original (split) feature if not primary key - QgsAttributes newAttributes = feat.attributes(); - Q_FOREACH ( int pkIdx, L->dataProvider()->pkAttributeIndexes() ) - { - const QVariant defaultValue = L->dataProvider()->defaultValueClause( pkIdx ); - if ( !defaultValue.isNull() ) - { - newAttributes[ pkIdx ] = defaultValue; - } - else //try with NULL - { - newAttributes[ pkIdx ] = QVariant(); - } - } - - newFeature.setAttributes( newAttributes ); - - newFeatures.append( newFeature ); + QgsFeature f = QgsVectorLayerUtils::createFeature( L, newGeometries.at( i ), feat.attributes().toMap() ); + L->editBuffer()->addFeature( f ); } if ( topologicalEditing ) @@ -418,10 +399,6 @@ int QgsVectorLayerEditUtils::splitFeatures( const QList& splitLine, bo returnCode = 4; } - - //now add the new features to this vectorlayer - L->editBuffer()->addFeatures( newFeatures ); - return returnCode; } diff --git a/src/core/qgsvectorlayereditutils.h b/src/core/qgsvectorlayereditutils.h index ed96ae97af39..7b00a4608602 100644 --- a/src/core/qgsvectorlayereditutils.h +++ b/src/core/qgsvectorlayereditutils.h @@ -19,6 +19,7 @@ #include "qgsfeature.h" #include "qgsvectorlayer.h" +#include "qgsgeometry.h" class QgsGeometryCache; class QgsCurve; diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index d5845e97eaeb..eb54bfab8745 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -215,3 +215,95 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const return valid; } +QgsFeature QgsVectorLayerUtils::createFeature( QgsVectorLayer* layer, const QgsGeometry& geometry, + const QgsAttributeMap& attributes, QgsExpressionContext* context ) +{ + if ( !layer ) + { + return QgsFeature(); + } + + QgsExpressionContext* evalContext = context; + QScopedPointer< QgsExpressionContext > tempContext; + if ( !evalContext ) + { + // no context passed, so we create a default one + tempContext.reset( new QgsExpressionContext() ); + tempContext->appendScope( QgsExpressionContextUtils::globalScope() ); + tempContext->appendScope( QgsExpressionContextUtils::projectScope() ); + tempContext->appendScope( QgsExpressionContextUtils::layerScope( layer ) ); + evalContext = tempContext.data(); + } + + QgsFields fields = layer->fields(); + + QgsFeature newFeature( fields ); + newFeature.setValid( true ); + newFeature.setGeometry( geometry ); + + // initialise attributes + newFeature.initAttributes( fields.count() ); + for ( int idx = 0; idx < fields.count(); ++idx ) + { + QVariant v; + bool checkUnique = true; + + // in order of priority: + + // 1. client side default expression + if ( !layer->defaultValueExpression( idx ).isEmpty() ) + { + // client side default expression set - takes precedence over all. Why? Well, this is the only default + // which QGIS users have control over, so we assume that they're deliberately overriding any + // provider defaults for some good reason and we should respect that + v = layer->defaultValue( idx, newFeature, evalContext ); + } + + // 2. provider side default value clause + // note - not an else if deliberately. Users may return null from a default value expression to fallback to provider defaults + if ( !v.isValid() && fields.fieldOrigin( idx ) == QgsFields::OriginProvider ) + { + int providerIndex = fields.fieldOriginIndex( idx ); + QString providerDefault = layer->dataProvider()->defaultValueClause( providerIndex ); + if ( !providerDefault.isEmpty() ) + { + v = providerDefault; + checkUnique = false; + } + } + + // 3. passed attribute value + // note - deliberately not using else if! + if ( !v.isValid() && attributes.contains( idx ) ) + { + v = attributes.value( idx ); + } + + // 4. provider side default literal + // note - deliberately not using else if! + if ( !v.isValid() && fields.fieldOrigin( idx ) == QgsFields::OriginProvider ) + { + int providerIndex = fields.fieldOriginIndex( idx ); + v = layer->dataProvider()->defaultValue( providerIndex ); + } + + // last of all... check that unique constraints are respected + // we can't handle not null or expression constraints here, since there's no way to pick a sensible + // value if the constraint is violated + if ( checkUnique && fields.at( idx ).constraints().constraints() & QgsFieldConstraints::ConstraintUnique ) + { + if ( QgsVectorLayerUtils::valueExists( layer, idx, v ) ) + { + // unique constraint violated + QVariant uniqueValue = QgsVectorLayerUtils::createUniqueValue( layer, idx, v ); + if ( uniqueValue.isValid() ) + v = uniqueValue; + } + } + + newFeature.setAttribute( idx, v ); + } + + return newFeature; +} + diff --git a/src/core/qgsvectorlayerutils.h b/src/core/qgsvectorlayerutils.h index 9235de340422..64246276cd76 100644 --- a/src/core/qgsvectorlayerutils.h +++ b/src/core/qgsvectorlayerutils.h @@ -17,6 +17,7 @@ #define QGSVECTORLAYERUTILS_H #include "qgsvectorlayer.h" +#include "qgsgeometry.h" /** \ingroup core * \class QgsVectorLayerUtils @@ -53,6 +54,17 @@ class CORE_EXPORT QgsVectorLayerUtils QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin = QgsFieldConstraints::ConstraintOriginNotSet ); + /** + * Creates a new feature ready for insertion into a layer. Default values and constraints + * (eg unique constraints) will automatically be handled. An optional attribute map can be + * passed for the new feature to copy as many attribute values as possible from the map, + * assuming that they respect the layer's constraints. Note that the created feature is not + * automatically inserted into the layer. + */ + static QgsFeature createFeature( QgsVectorLayer* layer, + const QgsGeometry& geometry = QgsGeometry(), + const QgsAttributeMap& attributes = QgsAttributeMap(), + QgsExpressionContext* context = nullptr ); }; diff --git a/src/providers/spatialite/qgsspatialiteprovider.cpp b/src/providers/spatialite/qgsspatialiteprovider.cpp index dd19b14ef65a..4ff7d1c1fa41 100644 --- a/src/providers/spatialite/qgsspatialiteprovider.cpp +++ b/src/providers/spatialite/qgsspatialiteprovider.cpp @@ -762,6 +762,9 @@ void QgsSpatiaLiteProvider::loadFieldsAbstractInterface( gaiaVectorLayerPtr lyr } } + // check for constraints + fetchConstraints(); + // for views try to get the primary key from the meta table if ( mViewBased && mPrimaryKey.isEmpty() ) { @@ -862,6 +865,15 @@ void QgsSpatiaLiteProvider::fetchConstraints() } sqlite3_free_table( results ); + Q_FOREACH ( int fieldIdx, mPrimaryKeyAttrs ) + { + //primary keys are unique, not null + QgsFieldConstraints constraints = mAttributeFields.at( fieldIdx ).constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + mAttributeFields[ fieldIdx ].setConstraints( constraints ); + } + return; error: diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index d483da905e19..3dccc0736953 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -529,6 +529,21 @@ def testVectorLayerUtilsUniqueWithProviderDefault(self): self.assertTrue(vl.addFeatures([f])) self.assertFalse(QgsVectorLayerUtils.valueExists(vl, 0, default_clause)) + def testVectorLayerUtilsCreateFeatureWithProviderDefault(self): + vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") + default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' + self.assertEqual(vl.dataProvider().defaultValueClause(0), default_clause) + + # check that provider default clause takes precendence over passed attribute values + # this also checks that the inbuilt unique constraint handling is bypassed in the case of a provider default clause + f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 5, 3: 'map'}) + self.assertEqual(f.attributes(), [default_clause, 5, "'qgis'::text", "'qgis'::text", None, None]) + + # test take vector layer default value expression overrides postgres provider default clause + vl.setDefaultValueExpression(3, "'mappy'") + f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 5, 3: 'map'}) + self.assertEqual(f.attributes(), [default_clause, 5, "'qgis'::text", 'mappy', None, None]) + # See http://hub.qgis.org/issues/15188 def testNumericPrecision(self): uri = 'point?field=f1:int' diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index bf5fb4819a70..034ea3cf156f 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -19,7 +19,7 @@ import shutil import tempfile -from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry, QgsField, QgsFieldConstraints +from qgis.core import QgsVectorLayer, QgsPoint, QgsFeature, QgsGeometry, QgsProject, QgsMapLayerRegistry, QgsField, QgsFieldConstraints, QgsVectorLayerUtils from qgis.testing import start_app, unittest from utilities import unitTestDataPath @@ -185,28 +185,20 @@ def test_SplitFeature(self): self.assertTrue(layer.isValid()) self.assertTrue(layer.hasGeometryType()) layer.startEditing() - self.assertEqual(layer.splitFeatures([QgsPoint(0.5, -0.5), QgsPoint(0.5, 1.5)], 0), 0) - self.assertEqual(layer.splitFeatures([QgsPoint(-0.5, 0.5), QgsPoint(1.5, 0.5)], 0), 0) + self.assertEqual(layer.splitFeatures([QgsPoint(0.75, -0.5), QgsPoint(0.75, 1.5)], 0), 0) + self.assertEqual(layer.splitFeatures([QgsPoint(-0.5, 0.25), QgsPoint(1.5, 0.25)], 0), 0) self.assertTrue(layer.commitChanges()) self.assertEqual(layer.featureCount(), 4) - def xtest_SplitFeatureWithFailedCommit(self): + def test_SplitFeatureWithMultiKey(self): """Create spatialite database""" layer = QgsVectorLayer("dbname=%s table=test_pg_mk (geometry)" % self.dbname, "test_pg_mk", "spatialite") self.assertTrue(layer.isValid()) self.assertTrue(layer.hasGeometryType()) layer.startEditing() - self.asserEqual(layer.splitFeatures([QgsPoint(0.5, -0.5), QgsPoint(0.5, 1.5)], 0), 0) - self.asserEqual(layer.splitFeatures([QgsPoint(-0.5, 0.5), QgsPoint(1.5, 0.5)], 0), 0) - self.assertFalse(layer.commitChanges()) - layer.rollBack() - feat = next(layer.getFeatures()) - ref = [[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]] - res = feat.geometry().asPolygon() - for ring1, ring2 in zip(ref, res): - for p1, p2 in zip(ring1, ring2): - for c1, c2 in zip(p1, p2): - self.asserEqual(c1, c2) + self.assertEqual(layer.splitFeatures([QgsPoint(0.5, -0.5), QgsPoint(0.5, 1.5)], 0), 0) + self.assertEqual(layer.splitFeatures([QgsPoint(-0.5, 0.5), QgsPoint(1.5, 0.5)], 0), 0) + self.assertTrue(layer.commitChanges()) def test_queries(self): """Test loading of query-based layers""" @@ -475,6 +467,21 @@ def testDefaultValues(self): self.assertEqual(l.dataProvider().defaultValue(3), 5.7) self.assertFalse(l.dataProvider().defaultValue(4)) + def testVectorLayerUtilsCreateFeatureWithProviderDefaultLiteral(self): + vl = QgsVectorLayer("dbname=%s table='test_defaults' key='id'" % self.dbname, "test_defaults", "spatialite") + self.assertEqual(vl.dataProvider().defaultValue(2), 5) + + f = QgsVectorLayerUtils.createFeature(vl) + self.assertEqual(f.attributes(), [None, "qgis 'is good", 5, 5.7, None]) + + # check that provider passed attribute values take precedence over default literals + f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 'qgis is great', 0: 3}) + self.assertEqual(f.attributes(), [3, "qgis is great", 5, 5.7, None]) + + # test take vector layer default value expression overrides postgres provider default clause + vl.setDefaultValueExpression(3, "4*3") + f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 'qgis is great', 0: 3}) + self.assertEqual(f.attributes(), [3, "qgis is great", 5, 12, None]) if __name__ == '__main__': unittest.main() diff --git a/tests/src/python/test_qgsvectorlayerutils.py b/tests/src/python/test_qgsvectorlayerutils.py index c94154c0a233..a33f1f972c63 100644 --- a/tests/src/python/test_qgsvectorlayerutils.py +++ b/tests/src/python/test_qgsvectorlayerutils.py @@ -24,6 +24,8 @@ QgsFieldConstraints, QgsFields, QgsFeature, + QgsGeometry, + QgsPoint, NULL ) from qgis.testing import start_app, unittest @@ -211,5 +213,64 @@ def testCreateUniqueValue(self): self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 0, 'seed'), 'seed') self.assertEqual(QgsVectorLayerUtils.createUniqueValue(layer, 0, 'superpig'), 'superpig_1') + def testCreateFeature(self): + """ test creating a feature respecting defaults and constraints """ + layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer&field=flddbl:double", + "addfeat", "memory") + # add a bunch of features + f = QgsFeature() + f.setAttributes(["test", 123, 1.0]) + f1 = QgsFeature(2) + f1.setAttributes(["test_1", 124, 1.1]) + f2 = QgsFeature(3) + f2.setAttributes(["test_2", 125, 2.4]) + f3 = QgsFeature(4) + f3.setAttributes(["test_3", 126, 1.7]) + f4 = QgsFeature(5) + f4.setAttributes(["superpig", 127, 0.8]) + self.assertTrue(layer.dataProvider().addFeatures([f, f1, f2, f3, f4])) + + # no layer + self.assertFalse(QgsVectorLayerUtils.createFeature(None).isValid()) + + # basic tests + f = QgsVectorLayerUtils.createFeature(layer) + self.assertTrue(f.isValid()) + self.assertEqual(f.fields(), layer.fields()) + self.assertFalse(f.hasGeometry()) + self.assertEqual(f.attributes(), [NULL, NULL, NULL]) + + # set geometry + g = QgsGeometry.fromPoint(QgsPoint(100, 200)) + f = QgsVectorLayerUtils.createFeature(layer, g) + self.assertTrue(f.hasGeometry()) + self.assertEqual(f.geometry().exportToWkt(), g.exportToWkt()) + + # using attribute map + f = QgsVectorLayerUtils.createFeature(layer, attributes={0: 'a', 2: 6.0}) + self.assertEqual(f.attributes(), ['a', NULL, 6.0]) + + # layer with default value expression + layer.setDefaultValueExpression(2, '3*4') + f = QgsVectorLayerUtils.createFeature(layer) + self.assertEqual(f.attributes(), [NULL, NULL, 12.0]) + # we expect the default value expression to take precedence over the attribute map + f = QgsVectorLayerUtils.createFeature(layer, attributes={0: 'a', 2: 6.0}) + self.assertEqual(f.attributes(), ['a', NULL, 12.0]) + # layer with default value expression based on geometry + layer.setDefaultValueExpression(2, '3*$x') + f = QgsVectorLayerUtils.createFeature(layer, g) + self.assertEqual(f.attributes(), [NULL, NULL, 300.0]) + layer.setDefaultValueExpression(2, None) + + # test with violated unique constraints + layer.setFieldConstraint(1, QgsFieldConstraints.ConstraintUnique) + f = QgsVectorLayerUtils.createFeature(layer, attributes={0: 'test_1', 1: 123}) + self.assertEqual(f.attributes(), ['test_1', 128, NULL]) + layer.setFieldConstraint(0, QgsFieldConstraints.ConstraintUnique) + f = QgsVectorLayerUtils.createFeature(layer, attributes={0: 'test_1', 1: 123}) + self.assertEqual(f.attributes(), ['test_4', 128, NULL]) + + if __name__ == '__main__': unittest.main() From 091f4889858b0e09e52d7a8c1e7a86ce803eb9f1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 9 Nov 2016 10:53:07 +1000 Subject: [PATCH 789/897] Make sure primary keys are always marked with a unique, not null constraint for all providers --- src/providers/arcgisrest/qgsafsprovider.cpp | 7 ++ src/providers/db2/qgsdb2provider.cpp | 24 ++++++- src/providers/db2/qgsdb2provider.h | 34 +--------- src/providers/mssql/qgsmssqlprovider.cpp | 24 ++++++- src/providers/mssql/qgsmssqlprovider.h | 68 +------------------ src/providers/oracle/qgsoracleprovider.cpp | 20 +++++- .../postgres/qgspostgresprovider.cpp | 13 +++- 7 files changed, 89 insertions(+), 101 deletions(-) diff --git a/src/providers/arcgisrest/qgsafsprovider.cpp b/src/providers/arcgisrest/qgsafsprovider.cpp index 1b67e6d3a9c1..684f66b2f7d2 100644 --- a/src/providers/arcgisrest/qgsafsprovider.cpp +++ b/src/providers/arcgisrest/qgsafsprovider.cpp @@ -132,6 +132,13 @@ QgsAfsProvider::QgsAfsProvider( const QString& uri ) if ( mFields.at( idx ).name() == mObjectIdFieldName ) { mObjectIdFieldIdx = idx; + + // primary key is not null, unique + QgsFieldConstraints constraints = mFields.at( idx ).constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + mFields[ idx ].setConstraints( constraints ); + break; } } diff --git a/src/providers/db2/qgsdb2provider.cpp b/src/providers/db2/qgsdb2provider.cpp index 0e8ee12b4efd..72499a4c1fd0 100644 --- a/src/providers/db2/qgsdb2provider.cpp +++ b/src/providers/db2/qgsdb2provider.cpp @@ -33,6 +33,7 @@ int QgsDb2Provider::sConnectionId = 0; QgsDb2Provider::QgsDb2Provider( const QString& uri ) : QgsVectorDataProvider( uri ) , mNumberFeatures( 0 ) + , mFidColIdx( -1 ) , mEnvironment( ENV_LUW ) , mWkbType( QgsWkbTypes::Unknown ) { @@ -330,12 +331,25 @@ void QgsDb2Provider::loadFields() } // Hack to get primary key since the primaryIndex function above doesn't work // on z/OS. Pick first integer column. - if ( mFidColName.length() == 0 && + if ( mFidColName.isEmpty() && ( sqlType == QVariant::LongLong || sqlType == QVariant::Int ) ) { mFidColName = f.name(); } } + + if ( !mFidColName.isEmpty() ) + { + mFidColIdx = mAttributeFields.indexFromName( mFidColName ); + if ( mFidColIdx >= 0 ) + { + // primary key has not null, unique constraints + QgsFieldConstraints constraints = mAttributeFields.at( mFidColIdx ).constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + mAttributeFields[ mFidColIdx ].setConstraints( constraints ); + } + } } QVariant::Type QgsDb2Provider::decodeSqlType( int typeId ) @@ -1664,6 +1678,14 @@ QString QgsDb2Provider::description() const return PROVIDER_DESCRIPTION; } +QgsAttributeList QgsDb2Provider::pkAttributeIndexes() const +{ + QgsAttributeList list; + if ( mFidColIdx >= 0 ) + list << mFidColIdx; + return list; +} + QGISEXTERN QgsDb2Provider *classFactory( const QString *uri ) { return new QgsDb2Provider( *uri ); diff --git a/src/providers/db2/qgsdb2provider.h b/src/providers/db2/qgsdb2provider.h index ad08ee661a9c..7769af3cfc74 100644 --- a/src/providers/db2/qgsdb2provider.h +++ b/src/providers/db2/qgsdb2provider.h @@ -54,16 +54,8 @@ class QgsDb2Provider : public QgsVectorDataProvider virtual QgsFeatureIterator getFeatures( const QgsFeatureRequest& request = QgsFeatureRequest() ) const override; - /** - * Get feature type. - * @return int representing the feature type - */ virtual QgsWkbTypes::Type wkbType() const override; - /** - * Number of features in the layer - * @return long containing number of features - */ virtual long featureCount() const override; /** @@ -79,45 +71,24 @@ class QgsDb2Provider : public QgsVectorDataProvider virtual bool isValid() const override; QString subsetString() const override; - /** - * Mutator for SQL WHERE clause used to limit dataset size. - */ bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } - /** Return a provider name - - Essentially just returns the provider key. Should be used to build file - dialogs so that providers can be shown with their supported types. Thus - if more than one provider supports a given format, the user is able to - select a specific provider to open that file. - */ virtual QString name() const override; - /** Return description - - Return a terse string describing what the provider is. - */ virtual QString description() const override; - /** Returns a bitmask containing the supported capabilities - Note, some capabilities may change depending on whether - a spatial filter is active on this provider, so it may - be prudent to check this value per intended operation. - */ + QgsAttributeList pkAttributeIndexes() const override; + virtual QgsVectorDataProvider::Capabilities capabilities() const override; - //! Writes a list of features to the database virtual bool addFeatures( QgsFeatureList & flist ) override; - //! Deletes a feature virtual bool deleteFeatures( const QgsFeatureIds & id ) override; - //! Changes attribute values of existing features virtual bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ) override; - //! Changes existing geometries virtual bool changeGeometryValues( const QgsGeometryMap &geometry_map ) override; //! Import a vector layer into the database @@ -155,6 +126,7 @@ class QgsDb2Provider : public QgsVectorDataProvider bool mUseEstimatedMetadata; bool mSkipFailures; long mNumberFeatures; + int mFidColIdx; QString mFidColName; QString mExtents; mutable long mSRId; diff --git a/src/providers/mssql/qgsmssqlprovider.cpp b/src/providers/mssql/qgsmssqlprovider.cpp index afce499d4256..f3124820dfc7 100644 --- a/src/providers/mssql/qgsmssqlprovider.cpp +++ b/src/providers/mssql/qgsmssqlprovider.cpp @@ -56,6 +56,7 @@ int QgsMssqlProvider::sConnectionId = 0; QgsMssqlProvider::QgsMssqlProvider( const QString& uri ) : QgsVectorDataProvider( uri ) , mNumberFeatures( 0 ) + , mFidColIdx( -1 ) , mCrs() , mWkbType( QgsWkbTypes::Unknown ) { @@ -472,6 +473,19 @@ void QgsMssqlProvider::loadFields() mValid = false; setLastError( error ); } + + if ( !mFidColName.isEmpty() ) + { + mFidColIdx = mAttributeFields.indexFromName( mFidColName ); + if ( mFidColIdx >= 0 ) + { + // primary key has not null, unique constraints + QgsFieldConstraints constraints = mAttributeFields.at( mFidColIdx ).constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + mAttributeFields[ mFidColIdx ].setConstraints( constraints ); + } + } } } @@ -1481,7 +1495,15 @@ bool QgsMssqlProvider::setSubsetString( const QString& theSQL, bool ) QString QgsMssqlProvider::description() const { return TEXT_PROVIDER_DESCRIPTION; -} // QgsMssqlProvider::name() +} + +QgsAttributeList QgsMssqlProvider::pkAttributeIndexes() const +{ + QgsAttributeList list; + if ( mFidColIdx >= 0 ) + list << mFidColIdx; + return list; +} QStringList QgsMssqlProvider::subLayers() const { diff --git a/src/providers/mssql/qgsmssqlprovider.h b/src/providers/mssql/qgsmssqlprovider.h index e995c1c99889..6d1fab7a72a6 100644 --- a/src/providers/mssql/qgsmssqlprovider.h +++ b/src/providers/mssql/qgsmssqlprovider.h @@ -62,33 +62,15 @@ class QgsMssqlProvider : public QgsVectorDataProvider /* Implementation of functions from QgsVectorDataProvider */ - /** - * Returns the permanent storage type for this layer as a friendly name. - */ virtual QString storageType() const override; - - /** - * Sub-layers handled by this provider, in order from bottom to top - * - * Sub-layers are used when the provider's source can combine layers - * it knows about in some way before it hands them off to the provider. - */ virtual QStringList subLayers() const override; virtual QVariant minimumValue( int index ) const override; virtual QVariant maximumValue( int index ) const override; virtual void uniqueValues( int index, QList &uniqueValues, int limit = -1 ) const override; virtual QgsFeatureIterator getFeatures( const QgsFeatureRequest& request ) const override; - /** - * Get feature type. - * @return int representing the feature type - */ virtual QgsWkbTypes::Type wkbType() const override; - /** - * Number of features in the layer - * @return long containing number of features - */ virtual long featureCount() const override; //! Update the extent, feature count, wkb type and srid for this layer @@ -98,86 +80,41 @@ class QgsMssqlProvider : public QgsVectorDataProvider QString subsetString() const override; - //! Mutator for sql where clause used to limit dataset size bool setSubsetString( const QString& theSQL, bool updateFeatureCount = true ) override; virtual bool supportsSubsetString() const override { return true; } - /** Returns a bitmask containing the supported capabilities - Note, some capabilities may change depending on whether - a spatial filter is active on this provider, so it may - be prudent to check this value per intended operation. - */ virtual QgsVectorDataProvider::Capabilities capabilities() const override; /* Implementation of functions from QgsDataProvider */ - /** Return a provider name - - Essentially just returns the provider key. Should be used to build file - dialogs so that providers can be shown with their supported types. Thus - if more than one provider supports a given format, the user is able to - select a specific provider to open that file. - - @note - - Instead of being pure virtual, might be better to generalize this - behavior and presume that none of the sub-classes are going to do - anything strange with regards to their name or description? - */ QString name() const override; - /** Return description - - Return a terse string describing what the provider is. - - @note - - Instead of being pure virtual, might be better to generalize this - behavior and presume that none of the sub-classes are going to do - anything strange with regards to their name or description? - */ QString description() const override; + QgsAttributeList pkAttributeIndexes() const override; + virtual QgsRectangle extent() const override; bool isValid() const override; virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } - //! Writes a list of features to the database virtual bool addFeatures( QgsFeatureList & flist ) override; - //! Deletes a feature virtual bool deleteFeatures( const QgsFeatureIds & id ) override; - /** - * Adds new attributes - * @param attributes list of new attributes - * @return true in case of success and false in case of failure - */ virtual bool addAttributes( const QList &attributes ) override; - /** - * Deletes existing attributes - * @param attributes a set containing names of attributes - * @return true in case of success and false in case of failure - */ virtual bool deleteAttributes( const QgsAttributeIds &attributes ) override; - //! Changes attribute values of existing features virtual bool changeAttributeValues( const QgsChangedAttributesMap &attr_map ) override; - //! Changes existing geometries virtual bool changeGeometryValues( const QgsGeometryMap &geometry_map ) override; - /** - * Create a spatial index for the current layer - */ virtual bool createSpatialIndex() override; - //! Create an attribute index on the datasource virtual bool createAttributeIndex( int field ) override; //! Convert a QgsField to work with MSSQL @@ -227,6 +164,7 @@ class QgsMssqlProvider : public QgsVectorDataProvider long mNumberFeatures; QString mFidColName; + int mFidColIdx; mutable long mSRId; QString mGeometryColName; QString mGeometryColType; diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index 56441036cd95..5a274d00d1b6 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -752,7 +752,16 @@ bool QgsOracleProvider::loadFields() type = QVariant::Date; } - mAttributeFields.append( QgsField( field.name(), type, types.value( field.name() ), field.length(), field.precision(), comments.value( field.name() ) ) ); + QgsField newField( field.name(), type, types.value( field.name() ), field.length(), field.precision(), comments.value( field.name() ) ); + + QgsFieldConstraints constraints; + if ( mPrimaryKeyAttrs.contains( i ) ) + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + if ( mPrimaryKeyAttrs.contains( i ) ) + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + newField.setConstraints( constraints ); + + mAttributeFields.append( newField ); mDefaultValues.append( defvalues.value( field.name(), QVariant() ) ); } @@ -987,6 +996,15 @@ bool QgsOracleProvider::determinePrimaryKey() mValid = mPrimaryKeyType != pktUnknown; + Q_FOREACH ( int fieldIdx, mPrimaryKeyAttrs ) + { + //primary keys are unique, not null + QgsFieldConstraints constraints = mAttributeFields.at( fieldIdx ).constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + mAttributeFields[ fieldIdx ].setConstraints( constraints ); + } + return mValid; } diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index e649abb25a53..187865bcdfd4 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1002,9 +1002,9 @@ bool QgsPostgresProvider::loadFields() QgsField newField = QgsField( fieldName, fieldType, fieldTypeName, fieldSize, fieldPrec, fieldComment, fieldSubType ); QgsFieldConstraints constraints; - if ( notNullMap[tableoid][attnum] ) + if ( notNullMap[tableoid][attnum] || mPrimaryKeyAttrs.contains( i ) ) constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); - if ( uniqueMap[tableoid][attnum] ) + if ( uniqueMap[tableoid][attnum] || mPrimaryKeyAttrs.contains( i ) ) constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); newField.setConstraints( constraints ); @@ -1375,6 +1375,15 @@ bool QgsPostgresProvider::determinePrimaryKey() determinePrimaryKeyFromUriKeyColumn(); } + Q_FOREACH ( int fieldIdx, mPrimaryKeyAttrs ) + { + //primary keys are unique, not null + QgsFieldConstraints constraints = mAttributeFields.at( fieldIdx ).constraints(); + constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider ); + constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider ); + mAttributeFields[ fieldIdx ].setConstraints( constraints ); + } + mValid = mPrimaryKeyType != pktUnknown; return mValid; From 631bd48aa0442e0981f99266986b8e80dc3ba6d9 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 9 Nov 2016 11:51:57 +1000 Subject: [PATCH 790/897] Port remaining map tools, paste features, offline editing to use new constraint/default clause handling methods --- src/app/qgisapp.cpp | 62 ++++++++-------------------- src/app/qgsfeatureaction.cpp | 44 ++++++-------------- src/app/qgsmaptoolfillring.cpp | 17 ++++---- src/app/qgsmergeattributesdialog.cpp | 32 ++++---------- src/core/qgsofflineediting.cpp | 41 +++++++----------- 5 files changed, 62 insertions(+), 134 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index d2e17a77cfdb..9c5b99b7cf70 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -241,6 +241,7 @@ #include "qgsvirtuallayerdefinitionutils.h" #include "qgstransaction.h" #include "qgstransactiongroup.h" +#include "qgsvectorlayerutils.h" #include "qgssublayersdialog.h" #include "ogr/qgsopenvectorlayerdialog.h" @@ -7484,7 +7485,6 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) QHash remap; QgsFields fields = clipboard()->fields(); - QgsAttributeList pkAttrList = pasteVectorLayer->pkAttributeList(); for ( int idx = 0; idx < fields.count(); ++idx ) { int dst = pasteVectorLayer->fields().lookupField( fields.at( idx ).name() ); @@ -7495,33 +7495,14 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) } QgsExpressionContext context = pasteVectorLayer->createExpressionContext(); - int dstAttrCount = pasteVectorLayer->fields().count(); - QgsFeatureList::iterator featureIt = features.begin(); - while ( featureIt != features.end() ) + QgsFeatureIds newIds; + + QgsFeatureList::const_iterator featureIt = features.constBegin(); + while ( featureIt != features.constEnd() ) { QgsAttributes srcAttr = featureIt->attributes(); - QgsAttributes dstAttr( dstAttrCount ); - - // pre-initialized with default values - for ( int dst = 0; dst < dstAttr.count(); ++dst ) - { - QVariant defVal; - if ( !pasteVectorLayer->defaultValueExpression( dst ).isEmpty() ) - { - // client side default expression set - use this in preference to provider default - defVal = pasteVectorLayer->defaultValue( dst, *featureIt, &context ); - } - else - { - defVal = pasteVectorLayer->dataProvider()->defaultValueClause( dst ); - } - - if ( defVal.isValid() && !defVal.isNull() ) - { - dstAttr[ dst ] = defVal; - } - } + QgsAttributeMap dstAttr; for ( int src = 0; src < srcAttr.count(); ++src ) { @@ -7529,21 +7510,10 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) if ( dst < 0 ) continue; - // don't overwrite default value for primary key fields if it's NOT NULL - // or for spatialite layers - if ( pkAttrList.contains( dst ) ) - { - if ( !dstAttr.at( dst ).isNull() ) - continue; - else if ( pasteVectorLayer->providerType() == QLatin1String( "spatialite" ) ) - continue; - } - dstAttr[ dst ] = srcAttr.at( src ); } - featureIt->setAttributes( dstAttr ); - + QgsGeometry geom = featureIt->geometry(); if ( featureIt->hasGeometry() ) { // convert geometry to match destination layer @@ -7558,25 +7528,29 @@ void QgisApp::editPaste( QgsMapLayer *destinationLayer ) if ( destType != QgsWkbTypes::UnknownGeometry ) { - QgsGeometry newGeometry = featureIt->geometry().convertToType( destType, destIsMulti ); + QgsGeometry newGeometry = geom.convertToType( destType, destIsMulti ); if ( newGeometry.isEmpty() ) { - featureIt = features.erase( featureIt ); continue; } - featureIt->setGeometry( newGeometry ); + geom = newGeometry; } // avoid intersection if enabled in digitize settings - QgsGeometry g = featureIt->geometry(); - g.avoidIntersections(); - featureIt->setGeometry( g ); + geom.avoidIntersections(); } + // now create new feature using pasted feature as a template. This automatically handles default + // values and field constraints + QgsFeature newFeature = QgsVectorLayerUtils::createFeature( pasteVectorLayer, geom, dstAttr, &context ); + pasteVectorLayer->addFeature( newFeature, false ); + newIds << newFeature.id(); + ++featureIt; } - pasteVectorLayer->addFeatures( features ); + pasteVectorLayer->selectByIds( newIds ); pasteVectorLayer->endEditCommand(); + pasteVectorLayer->updateExtents(); int nCopiedFeatures = features.count(); if ( nCopiedFeatures == 0 ) diff --git a/src/app/qgsfeatureaction.cpp b/src/app/qgsfeatureaction.cpp index a9546351c81e..6b0533f67ee1 100644 --- a/src/app/qgsfeatureaction.cpp +++ b/src/app/qgsfeatureaction.cpp @@ -28,6 +28,7 @@ #include "qgsvectorlayer.h" #include "qgsactionmanager.h" #include "qgsaction.h" +#include "qgsvectorlayerutils.h" #include #include @@ -144,53 +145,34 @@ bool QgsFeatureAction::addFeature( const QgsAttributeMap& defaultAttributes, boo if ( !mLayer || !mLayer->isEditable() ) return false; - QgsVectorDataProvider *provider = mLayer->dataProvider(); - QgsAttributeList pkAttrList = mLayer->pkAttributeList(); - QSettings settings; bool reuseLastValues = settings.value( QStringLiteral( "/qgis/digitizing/reuseLastValues" ), false ).toBool(); QgsDebugMsg( QString( "reuseLastValues: %1" ).arg( reuseLastValues ) ); - QgsExpressionContext context = mLayer->createExpressionContext(); + QgsFields fields = mLayer->fields(); + QgsAttributeMap initialAttributeValues; - // add the fields to the QgsFeature - const QgsFields& fields = mLayer->fields(); - mFeature->initAttributes( fields.count() ); for ( int idx = 0; idx < fields.count(); ++idx ) { QVariant v; if ( defaultAttributes.contains( idx ) ) { - v = defaultAttributes.value( idx ); - } - else if ( !mLayer->defaultValueExpression( idx ).isEmpty() ) - { - // client side default expression set - use this in preference to reusing last value - v = mLayer->defaultValue( idx, *mFeature, &context ); + initialAttributeValues.insert( idx, defaultAttributes.value( idx ) ); } - else if ( reuseLastValues && sLastUsedValues.contains( mLayer ) && sLastUsedValues[ mLayer ].contains( idx ) && !pkAttrList.contains( idx ) ) - { - v = sLastUsedValues[ mLayer ][idx]; - } - else + else if ( reuseLastValues && sLastUsedValues.contains( mLayer ) && sLastUsedValues[ mLayer ].contains( idx ) ) { - QVariant defaultLiteral = mLayer->dataProvider()->defaultValue( idx ); - if ( defaultLiteral.isValid() ) - { - v = defaultLiteral; - } - else - { - QString defaultClause = provider->defaultValueClause( idx ); - if ( !defaultClause.isEmpty() ) - v = defaultClause; - } + initialAttributeValues.insert( idx, sLastUsedValues[ mLayer ][idx] ); } - - mFeature->setAttribute( idx, v ); } + // create new feature template - this will initialise the attributes to valid values, handling default + // values and field constraints + QgsExpressionContext context = mLayer->createExpressionContext(); + QgsFeature newFeature = QgsVectorLayerUtils::createFeature( mLayer, mFeature->geometry(), initialAttributeValues, + &context ); + *mFeature = newFeature; + //show the dialog to enter attribute values //only show if enabled in settings and layer has fields bool isDisabledAttributeValuesDlg = ( fields.count() == 0 ) || settings.value( QStringLiteral( "/qgis/digitizing/disable_enter_attribute_values_dialog" ), false ).toBool(); diff --git a/src/app/qgsmaptoolfillring.cpp b/src/app/qgsmaptoolfillring.cpp index 64b0c9256707..2e5077a30b74 100644 --- a/src/app/qgsmaptoolfillring.cpp +++ b/src/app/qgsmaptoolfillring.cpp @@ -21,7 +21,7 @@ #include "qgsvectorlayer.h" #include "qgsattributedialog.h" #include "qgisapp.h" - +#include "qgsvectorlayerutils.h" #include #include @@ -139,26 +139,26 @@ void QgsMapToolFillRing::cadCanvasReleaseEvent( QgsMapMouseEvent * e ) bBox.setXMaximum( xMax ); bBox.setYMaximum( yMax ); + QgsExpressionContext context = vlayer->createExpressionContext(); + QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterFid( modifiedFid ) ); QgsFeature f; if ( fit.nextFeature( f ) ) { - //create QgsFeature with wkb representation - QgsFeature* ft = new QgsFeature( vlayer->fields(), 0 ); - QgsGeometry g = QgsGeometry::fromPolygon( QgsPolygon() << pointList.toVector() ); - ft->setGeometry( g ); - ft->setAttributes( f.attributes() ); + + //create QgsFeature with wkb representation + QgsFeature ft = QgsVectorLayerUtils::createFeature( vlayer, g, f.attributes().toMap(), &context ); bool res = false; if ( QApplication::keyboardModifiers() == Qt::ControlModifier ) { - res = vlayer->addFeature( *ft ); + res = vlayer->addFeature( ft ); } else { - QgsAttributeDialog *dialog = new QgsAttributeDialog( vlayer, ft, false, nullptr, true ); + QgsAttributeDialog *dialog = new QgsAttributeDialog( vlayer, &ft, false, nullptr, true ); dialog->setMode( QgsAttributeForm::AddFeatureMode ); res = dialog->exec(); // will also add the feature } @@ -169,7 +169,6 @@ void QgsMapToolFillRing::cadCanvasReleaseEvent( QgsMapMouseEvent * e ) } else { - delete ft; vlayer->destroyEditCommand(); } } diff --git a/src/app/qgsmergeattributesdialog.cpp b/src/app/qgsmergeattributesdialog.cpp index e04b586c36d2..4e0ab8744845 100644 --- a/src/app/qgsmergeattributesdialog.cpp +++ b/src/app/qgsmergeattributesdialog.cpp @@ -111,7 +111,6 @@ void QgsMergeAttributesDialog::createTableWidgetContents() //create combo boxes and insert attribute names mFields = mVectorLayer->fields(); - QSet pkAttrList = mVectorLayer->pkAttributeList().toSet(); int col = 0; mHiddenAttributes.clear(); @@ -127,7 +126,7 @@ void QgsMergeAttributesDialog::createTableWidgetContents() mTableWidget->setColumnCount( col + 1 ); QComboBox *cb = createMergeComboBox( mFields.at( idx ).type() ); - if ( pkAttrList.contains( idx ) ) + if ( mFields.at( idx ).constraints().constraints() & QgsFieldConstraints::ConstraintUnique ) { cb->setCurrentIndex( cb->findData( "skip" ) ); } @@ -413,15 +412,17 @@ void QgsMergeAttributesDialog::on_mFromSelectedPushButton_clicked() return; } - QSet pkAttributes = mVectorLayer->pkAttributeList().toSet(); for ( int i = 0; i < mTableWidget->columnCount(); ++i ) { - if ( pkAttributes.contains( i ) ) - { + QComboBox* currentComboBox = qobject_cast( mTableWidget->cellWidget( 0, i ) ); + if ( !currentComboBox ) continue; + + if ( mVectorLayer->fields().at( i ).constraints().constraints() & QgsFieldConstraints::ConstraintUnique ) + { + currentComboBox->setCurrentIndex( currentComboBox->findData( "skip" ) ); } - QComboBox* currentComboBox = qobject_cast( mTableWidget->cellWidget( 0, i ) ); - if ( currentComboBox ) + else { currentComboBox->setCurrentIndex( currentComboBox->findData( QStringLiteral( "f%1" ).arg( FID_TO_STRING( featureId ) ) ) ); } @@ -528,8 +529,6 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const return QgsAttributes(); } - QgsExpressionContext context = mVectorLayer->createExpressionContext(); - int widgetIndex = 0; QgsAttributes results( mFields.count() ); for ( int fieldIdx = 0; fieldIdx < mFields.count(); ++fieldIdx ) @@ -537,12 +536,7 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const if ( mHiddenAttributes.contains( fieldIdx ) ) { //hidden attribute, set to default value - if ( !mVectorLayer->defaultValueExpression( fieldIdx ).isEmpty() ) - results[fieldIdx] = mVectorLayer->defaultValue( fieldIdx, mFeatureList.at( 0 ), &context ); - else if ( mVectorLayer->dataProvider() ) - results[fieldIdx] = mVectorLayer->dataProvider()->defaultValueClause( fieldIdx ); - else - results[fieldIdx] = QVariant(); + results[fieldIdx] = QVariant(); continue; } @@ -561,14 +555,6 @@ QgsAttributes QgsMergeAttributesDialog::mergedAttributes() const { results[fieldIdx] = currentItem->data( Qt::DisplayRole ); } - else if ( !mVectorLayer->defaultValueExpression( fieldIdx ).isEmpty() ) - { - results[fieldIdx] = mVectorLayer->defaultValue( fieldIdx, mFeatureList.at( 0 ), &context ); - } - else if ( mVectorLayer->dataProvider() ) - { - results[fieldIdx] = mVectorLayer->dataProvider()->defaultValueClause( fieldIdx ); - } widgetIndex++; } diff --git a/src/core/qgsofflineediting.cpp b/src/core/qgsofflineediting.cpp index 8cf7d115959c..13dce15393df 100644 --- a/src/core/qgsofflineediting.cpp +++ b/src/core/qgsofflineediting.cpp @@ -32,6 +32,7 @@ #include "qgsslconnect.h" #include "qgsfeatureiterator.h" #include "qgslogger.h" +#include "qgsvectorlayerutils.h" #include #include @@ -747,21 +748,22 @@ void QgsOfflineEditing::applyAttributesAdded( QgsVectorLayer* remoteLayer, sqlit void QgsOfflineEditing::applyFeaturesAdded( QgsVectorLayer* offlineLayer, QgsVectorLayer* remoteLayer, sqlite3* db, int layerId ) { QString sql = QStringLiteral( "SELECT \"fid\" FROM 'log_added_features' WHERE \"layer_id\" = %1" ).arg( layerId ); - QList newFeatureIds = sqlQueryInts( db, sql ); - - QgsFields remoteFlds = remoteLayer->fields(); + QList featureIdInts = sqlQueryInts( db, sql ); + QgsFeatureIds newFeatureIds; + Q_FOREACH ( int id, featureIdInts ) + { + newFeatureIds << id; + } QgsExpressionContext context = remoteLayer->createExpressionContext(); // get new features from offline layer QgsFeatureList features; - for ( int i = 0; i < newFeatureIds.size(); i++ ) + QgsFeatureIterator it = offlineLayer->getFeatures( QgsFeatureRequest().setFilterFids( newFeatureIds ) ); + QgsFeature feature; + while ( it.nextFeature( feature ) ) { - QgsFeature feature; - if ( offlineLayer->getFeatures( QgsFeatureRequest().setFilterFid( newFeatureIds.at( i ) ) ).nextFeature( feature ) ) - { - features << feature; - } + features << feature; } // copy features to remote layer @@ -771,33 +773,18 @@ void QgsOfflineEditing::applyFeaturesAdded( QgsVectorLayer* offlineLayer, QgsVec int newAttrsCount = remoteLayer->fields().count(); for ( QgsFeatureList::iterator it = features.begin(); it != features.end(); ++it ) { - QgsFeature f = *it; - // NOTE: Spatialite provider ignores position of geometry column // restore gap in QgsAttributeMap if geometry column is not last (WORKAROUND) QMap attrLookup = attributeLookup( offlineLayer, remoteLayer ); QgsAttributes newAttrs( newAttrsCount ); - QgsAttributes attrs = f.attributes(); + QgsAttributes attrs = it->attributes(); for ( int it = 0; it < attrs.count(); ++it ) { newAttrs[ attrLookup[ it ] ] = attrs.at( it ); } - // try to use default value from the provider - // (important especially e.g. for postgis primary key generated from a sequence) - for ( int k = 0; k < newAttrs.count(); ++k ) - { - if ( !newAttrs.at( k ).isNull() ) - continue; - - if ( !remoteLayer->defaultValueExpression( k ).isEmpty() ) - newAttrs[k] = remoteLayer->defaultValue( k, f, &context ); - else if ( remoteFlds.fieldOrigin( k ) == QgsFields::OriginProvider ) - newAttrs[k] = remoteLayer->dataProvider()->defaultValueClause( remoteFlds.fieldOriginIndex( k ) ); - } - - f.setAttributes( newAttrs ); - + // respect constraints and provider default values + QgsFeature f = QgsVectorLayerUtils::createFeature( remoteLayer, it->geometry(), newAttrs.toMap(), &context ); remoteLayer->addFeature( f, false ); emit progressUpdated( i++ ); From 249c8dca20716ef0b20d02dba80b2a185725c4f1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 09:24:06 +1000 Subject: [PATCH 791/897] Prioritise provider default literals over reused values when creating a new feature --- src/core/qgsvectorlayerutils.cpp | 31 ++++++++------------ tests/src/python/test_provider_spatialite.py | 8 ++--- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index eb54bfab8745..64155b0b04ae 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -27,18 +27,6 @@ bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer* layer, int fieldInd if ( fieldIndex < 0 || fieldIndex >= fields.count() ) return false; - // check - if value is a provider side defaultValueClause then we exclude it from the check - if ( fields.fieldOrigin( fieldIndex ) == QgsFields::OriginProvider ) - { - int providerIdx = fields.fieldOriginIndex( fieldIndex ); - QString providerDefaultClause = layer->dataProvider()->defaultValueClause( providerIdx ); - if ( !providerDefaultClause.isEmpty() && value.toString() == providerDefaultClause ) - { - // exempt from check - return false; - } - } - QString fieldName = fields.at( fieldIndex ).name(); // build up an optimised feature request @@ -272,19 +260,24 @@ QgsFeature QgsVectorLayerUtils::createFeature( QgsVectorLayer* layer, const QgsG } } - // 3. passed attribute value + // 3. provider side default literal // note - deliberately not using else if! - if ( !v.isValid() && attributes.contains( idx ) ) + if ( !v.isValid() && fields.fieldOrigin( idx ) == QgsFields::OriginProvider ) { - v = attributes.value( idx ); + int providerIndex = fields.fieldOriginIndex( idx ); + v = layer->dataProvider()->defaultValue( providerIndex ); + if ( v.isValid() ) + { + //trust that the provider default has been sensibly set not to violate any constraints + checkUnique = false; + } } - // 4. provider side default literal + // 4. passed attribute value // note - deliberately not using else if! - if ( !v.isValid() && fields.fieldOrigin( idx ) == QgsFields::OriginProvider ) + if ( !v.isValid() && attributes.contains( idx ) ) { - int providerIndex = fields.fieldOriginIndex( idx ); - v = layer->dataProvider()->defaultValue( providerIndex ); + v = attributes.value( idx ); } // last of all... check that unique constraints are respected diff --git a/tests/src/python/test_provider_spatialite.py b/tests/src/python/test_provider_spatialite.py index 034ea3cf156f..e5b722149f8b 100644 --- a/tests/src/python/test_provider_spatialite.py +++ b/tests/src/python/test_provider_spatialite.py @@ -474,14 +474,14 @@ def testVectorLayerUtilsCreateFeatureWithProviderDefaultLiteral(self): f = QgsVectorLayerUtils.createFeature(vl) self.assertEqual(f.attributes(), [None, "qgis 'is good", 5, 5.7, None]) - # check that provider passed attribute values take precedence over default literals + # check that provider default literals take precedence over passed attribute values f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 'qgis is great', 0: 3}) - self.assertEqual(f.attributes(), [3, "qgis is great", 5, 5.7, None]) + self.assertEqual(f.attributes(), [3, "qgis 'is good", 5, 5.7, None]) - # test take vector layer default value expression overrides postgres provider default clause + # test that vector layer default value expression overrides provider default literal vl.setDefaultValueExpression(3, "4*3") f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 'qgis is great', 0: 3}) - self.assertEqual(f.attributes(), [3, "qgis is great", 5, 12, None]) + self.assertEqual(f.attributes(), [3, "qgis 'is good", 5, 12, None]) if __name__ == '__main__': unittest.main() From 60bbd09339527fb29be5a8f14a91190cf9ca530b Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 10:07:52 +1000 Subject: [PATCH 792/897] Avoid double-evaluating postgres default values --- python/core/qgsvectordataprovider.sip | 18 ++++++++- src/core/qgsvectordataprovider.cpp | 5 +++ src/core/qgsvectordataprovider.h | 18 ++++++++- src/core/qgsvectorlayerutils.cpp | 39 +++++++++++++++---- .../postgres/qgspostgresprovider.cpp | 14 +++++++ src/providers/postgres/qgspostgresprovider.h | 1 + tests/src/python/test_provider_postgres.py | 16 +++++++- 7 files changed, 100 insertions(+), 11 deletions(-) diff --git a/python/core/qgsvectordataprovider.sip b/python/core/qgsvectordataprovider.sip index 89c6c1ed1ac4..9b3fb86f1d5e 100644 --- a/python/core/qgsvectordataprovider.sip +++ b/python/core/qgsvectordataprovider.sip @@ -239,7 +239,13 @@ class QgsVectorDataProvider : QgsDataProvider /** * Returns any literal default values which are present at the provider for a specified - * field index. + * field index. Important - this should ONLY be called when creating an attribute to insert + * directly into the database. Do not call this method for non-feature creation or modification, + * eg when validating an attribute or to compare it against an existing value, as calling it + * can cause changes to the underlying data source (eg Postgres provider where the default value + * is calculated as a result of a sequence). It is recommended that you instead use the methods + * in QgsVectorLayerUtils such as QgsVectorLayerUtils::createFeature() + * so that default value handling and validation is automatically carried out. * @see defaultValueClause() */ virtual QVariant defaultValue( int fieldIndex ) const; @@ -257,9 +263,19 @@ class QgsVectorDataProvider : QgsDataProvider * Returns any constraints which are present at the provider for a specified * field index. * @note added in QGIS 3.0 + * @see skipConstraintCheck() */ QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; + /** + * Returns true if a constraint check should be skipped for a specified field (eg if + * the value returned by defaultValue() is trusted implicitly. An optional attribute value can be + * passed which can help refine the skip constraint check. + * @note added in QGIS 3.0 + * @see fieldConstraints() + */ + virtual bool skipConstraintCheck( int fieldIndex, QgsFieldConstraints::Constraint constraint, const QVariant& value = QVariant() ) const; + /** * Changes geometries of existing features * @param geometry_map A QgsGeometryMap whose index contains the feature IDs diff --git a/src/core/qgsvectordataprovider.cpp b/src/core/qgsvectordataprovider.cpp index 7c14a573d0d7..0c0958f271cd 100644 --- a/src/core/qgsvectordataprovider.cpp +++ b/src/core/qgsvectordataprovider.cpp @@ -114,6 +114,11 @@ QgsFieldConstraints::Constraints QgsVectorDataProvider::fieldConstraints( int fi return f.at( fieldIndex ).constraints().constraints(); } +bool QgsVectorDataProvider::skipConstraintCheck( int, QgsFieldConstraints::Constraint, const QVariant& ) const +{ + return false; +} + bool QgsVectorDataProvider::changeGeometryValues( const QgsGeometryMap &geometry_map ) { Q_UNUSED( geometry_map ); diff --git a/src/core/qgsvectordataprovider.h b/src/core/qgsvectordataprovider.h index a9d257e30dae..aca0bb85c4e5 100644 --- a/src/core/qgsvectordataprovider.h +++ b/src/core/qgsvectordataprovider.h @@ -293,7 +293,13 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider /** * Returns any literal default values which are present at the provider for a specified - * field index. + * field index. Important - this should ONLY be called when creating an attribute to insert + * directly into the database. Do not call this method for non-feature creation or modification, + * eg when validating an attribute or to compare it against an existing value, as calling it + * can cause changes to the underlying data source (eg Postgres provider where the default value + * is calculated as a result of a sequence). It is recommended that you instead use the methods + * in QgsVectorLayerUtils such as QgsVectorLayerUtils::createFeature() + * so that default value handling and validation is automatically carried out. * @see defaultValueClause() */ virtual QVariant defaultValue( int fieldIndex ) const; @@ -311,9 +317,19 @@ class CORE_EXPORT QgsVectorDataProvider : public QgsDataProvider * Returns any constraints which are present at the provider for a specified * field index. * @note added in QGIS 3.0 + * @see skipConstraintCheck() */ QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; + /** + * Returns true if a constraint check should be skipped for a specified field (eg if + * the value returned by defaultValue() is trusted implicitly. An optional attribute value can be + * passed which can help refine the skip constraint check. + * @note added in QGIS 3.0 + * @see fieldConstraints() + */ + virtual bool skipConstraintCheck( int fieldIndex, QgsFieldConstraints::Constraint constraint, const QVariant& value = QVariant() ) const; + /** * Changes geometries of existing features * @param geometry_map A QgsGeometryMap whose index contains the feature IDs diff --git a/src/core/qgsvectorlayerutils.cpp b/src/core/qgsvectorlayerutils.cpp index 64155b0b04ae..3c55d0d27b27 100644 --- a/src/core/qgsvectorlayerutils.cpp +++ b/src/core/qgsvectorlayerutils.cpp @@ -143,7 +143,8 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const if ( attributeIndex < 0 || attributeIndex >= layer->fields().count() ) return false; - QgsField field = layer->fields().at( attributeIndex ); + QgsFields fields = layer->fields(); + QgsField field = fields.at( attributeIndex ); QVariant value = feature.attribute( attributeIndex ); bool valid = true; errors.clear(); @@ -179,11 +180,22 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const && ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintNotNull ) ) && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) ) ) { - valid = valid && !value.isNull(); + bool exempt = false; + if ( fields.fieldOrigin( attributeIndex ) == QgsFields::OriginProvider + && constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) == QgsFieldConstraints::ConstraintOriginProvider ) + { + int providerIdx = fields.fieldOriginIndex( attributeIndex ); + exempt = layer->dataProvider()->skipConstraintCheck( providerIdx, QgsFieldConstraints::ConstraintNotNull, value ); + } - if ( value.isNull() ) + if ( !exempt ) { - errors << QObject::tr( "value is NULL" ); + valid = valid && !value.isNull(); + + if ( value.isNull() ) + { + errors << QObject::tr( "value is NULL" ); + } } } @@ -191,12 +203,23 @@ bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer* layer, const && ( strength == QgsFieldConstraints::ConstraintStrengthNotSet || strength == constraints.constraintStrength( QgsFieldConstraints::ConstraintUnique ) ) && ( origin == QgsFieldConstraints::ConstraintOriginNotSet || origin == constraints.constraintOrigin( QgsFieldConstraints::ConstraintUnique ) ) ) { - bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() ); - valid = valid && !alreadyExists; + bool exempt = false; + if ( fields.fieldOrigin( attributeIndex ) == QgsFields::OriginProvider + && constraints.constraintOrigin( QgsFieldConstraints::ConstraintNotNull ) == QgsFieldConstraints::ConstraintOriginProvider ) + { + int providerIdx = fields.fieldOriginIndex( attributeIndex ); + exempt = layer->dataProvider()->skipConstraintCheck( providerIdx, QgsFieldConstraints::ConstraintUnique, value ); + } - if ( alreadyExists ) + if ( !exempt ) { - errors << QObject::tr( "value is not unique" ); + bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() ); + valid = valid && !alreadyExists; + + if ( alreadyExists ) + { + errors << QObject::tr( "value is not unique" ); + } } } diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 187865bcdfd4..c301670208ef 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1806,6 +1806,20 @@ QVariant QgsPostgresProvider::defaultValue( int fieldId ) const return QVariant(); } +bool QgsPostgresProvider::skipConstraintCheck( int fieldIndex, QgsFieldConstraints::Constraint, const QVariant& value ) const +{ + if ( providerProperty( EvaluateDefaultValues, false ).toBool() ) + { + return mDefaultValues.contains( fieldIndex ); + } + else + { + // stricter check - if we are evaluating default values only on commit then we can only bypass the check + // if the attribute values matches the original default clause + return mDefaultValues.contains( fieldIndex ) && mDefaultValues.value( fieldIndex ) == value.toString(); + } +} + QString QgsPostgresProvider::paramValue( const QString& fieldValue, const QString &defaultValue ) const { if ( fieldValue.isNull() ) diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index f5373a2987b5..e87615ae09ff 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -164,6 +164,7 @@ class QgsPostgresProvider : public QgsVectorDataProvider QgsAttributeList pkAttributeIndexes() const override { return mPrimaryKeyAttrs; } QString defaultValueClause( int fieldId ) const override; QVariant defaultValue( int fieldId ) const override; + bool skipConstraintCheck( int fieldIndex, QgsFieldConstraints::Constraint constraint, const QVariant& value = QVariant() ) const override; /** Adds a list of features @return true in case of success and false in case of failure*/ diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 3dccc0736953..86781691b24a 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -520,14 +520,28 @@ def testConstraintOverwrite(self): def testVectorLayerUtilsUniqueWithProviderDefault(self): vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' + vl.dataProvider().setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) self.assertEqual(vl.dataProvider().defaultValueClause(0), default_clause) self.assertTrue(QgsVectorLayerUtils.valueExists(vl, 0, 4)) vl.startEditing() f = QgsFeature(vl.fields()) f.setAttribute(0, default_clause) - self.assertTrue(vl.addFeatures([f])) self.assertFalse(QgsVectorLayerUtils.valueExists(vl, 0, default_clause)) + self.assertTrue(vl.addFeatures([f])) + + # the default value clause should exist... + self.assertTrue(QgsVectorLayerUtils.valueExists(vl, 0, default_clause)) + # but it should not prevent the attribute being validated + self.assertTrue(QgsVectorLayerUtils.validateAttribute(vl, f, 0)) + vl.rollBack() + + def testSkipConstraintCheck(self): + vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") + default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' + vl.dataProvider().setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) + self.assertTrue(vl.dataProvider().skipConstraintCheck(0, QgsFieldConstraints.ConstraintUnique, default_clause)) + self.assertFalse(vl.dataProvider().skipConstraintCheck(0, QgsFieldConstraints.ConstraintUnique, 59)) def testVectorLayerUtilsCreateFeatureWithProviderDefault(self): vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") From af016cfb94af9dae12c19b3a29716a350be32807 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 14 Nov 2016 10:27:17 +1000 Subject: [PATCH 793/897] Don't use auto generated widgets for fields with provider default value clause Using auto widgets may cause the default value clause to be mangled, eg by converting it to a number --- .../core/qgseditorwidgetautoconf.cpp | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp index a52abda87b9f..e328580895d7 100644 --- a/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp +++ b/src/gui/editorwidgets/core/qgseditorwidgetautoconf.cpp @@ -14,6 +14,7 @@ ***************************************************************************/ #include "qgseditorwidgetautoconf.h" #include "qgseditorwidgetregistry.h" +#include "qgsvectordataprovider.h" /** \ingroup gui * Widget auto conf plugin that guesses what widget type to use in function of what the widgets support. @@ -87,8 +88,21 @@ QgsEditorWidgetSetup QgsEditorWidgetAutoConf::editorWidgetSetup( const QgsVector { QgsEditorWidgetSetup result( QStringLiteral( "TextEdit" ), QgsEditorWidgetConfig() ); - if ( vl->fields().indexFromName( fieldName ) >= 0 ) + int fieldIndex = vl->fields().indexFromName( fieldName ); + if ( fieldIndex >= 0 ) { + + if ( vl->fields().fieldOrigin( fieldIndex ) == QgsFields::OriginProvider ) + { + // important check - for provider fields, we CANNOT use auto configured widgets if the field + // uses a default value clause - otherwise the widget will obliterate the default value clause + // (eg by trying to convert it to a number/date/etc). Instead we have to use a text edit + // widget so that the clause remains intact + int providerOrigin = vl->fields().fieldOriginIndex( fieldIndex ); + if ( !vl->dataProvider()->defaultValueClause( providerOrigin ).isEmpty() ) + return result; + } + int bestScore = 0; Q_FOREACH ( QSharedPointer cur, plugins ) { From 33ee514b5dfdc1b57558cb9007df5b455a59fc17 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 16 Nov 2016 15:05:37 +0100 Subject: [PATCH 794/897] Disable failing PyQgsOfflineEditingWFS test --- ci/travis/linux/script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 8c06eeb8e7d9..2dbd176008f0 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -24,5 +24,5 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Set OTB application path (installed in before_install.sh script) export OTB_APPLICATION_PATH=${HOME}/OTB-5.6.0-Linux64/lib/otb/applications -xvfb-run ctest -V -E "qgis_filedownloader|qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_filedownloader|qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|PyQgsOfflineEditingWFS|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure From 66385690743d20fcea7b8b898e0fc3dae6eed010 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Wed, 16 Nov 2016 23:48:59 +0100 Subject: [PATCH 795/897] oracle provider: allow switching workspaces through property (cherry picked from commit 2dc448dfb8c568c20e69fc9e3955e5df63d9a880) --- src/providers/oracle/qgsoracleprovider.cpp | 31 +++++++++++++++++++++- src/providers/oracle/qgsoracleprovider.h | 11 ++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/providers/oracle/qgsoracleprovider.cpp b/src/providers/oracle/qgsoracleprovider.cpp index 5a274d00d1b6..60893a560e19 100644 --- a/src/providers/oracle/qgsoracleprovider.cpp +++ b/src/providers/oracle/qgsoracleprovider.cpp @@ -207,6 +207,35 @@ QgsOracleProvider::~QgsOracleProvider() disconnectDb(); } +QString QgsOracleProvider::getWorkspace() const +{ + return mUri.param( "dbworkspace" ); +} + +void QgsOracleProvider::setWorkspace( const QString &workspace ) +{ + QgsDataSourceUri prevUri( mUri ); + + disconnectDb(); + + if ( workspace.isEmpty() ) + mUri.removeParam( "dbworkspace" ); + else + mUri.setParam( "dbworkspace", workspace ); + + mConnection = QgsOracleConn::connectDb( mUri ); + if ( !mConnection ) + { + mUri = prevUri; + QgsDebugMsg( QString( "restoring previous uri:%1" ).arg( mUri.uri() ) ); + mConnection = QgsOracleConn::connectDb( mUri ); + } + else + { + setDataSourceUri( mUri.uri() ); + } +} + QgsAbstractFeatureSource *QgsOracleProvider::featureSource() const { return new QgsOracleFeatureSource( this ); @@ -2381,7 +2410,7 @@ bool QgsOracleProvider::getGeometryDetails() } if ( exec( qry, QString( mUseEstimatedMetadata - ? "SELECT DISTINCT gtype FROM (SELECT t.%1.sdo_gtype AS gtype FROM %2 t WHERE t.%1 IS NOT NULL AND rownum<1000) WHERE rownum<=2" + ? "SELECT DISTINCT gtype FROM (SELECT t.%1.sdo_gtype AS gtype FROM %2 t WHERE t.%1 IS NOT NULL AND rownum<100) WHERE rownum<=2" : "SELECT DISTINCT t.%1.sdo_gtype FROM %2 t WHERE t.%1 IS NOT NULL AND rownum<=2" ).arg( quotedIdentifier( geomCol ) ).arg( mQuery ) ) ) { if ( qry.next() ) diff --git a/src/providers/oracle/qgsoracleprovider.h b/src/providers/oracle/qgsoracleprovider.h index e75dfa4ad91b..8b52b02fe80c 100644 --- a/src/providers/oracle/qgsoracleprovider.h +++ b/src/providers/oracle/qgsoracleprovider.h @@ -56,6 +56,7 @@ enum QgsOraclePrimaryKeyType class QgsOracleProvider : public QgsVectorDataProvider { Q_OBJECT + Q_PROPERTY( QString workspace READ getWorkspace WRITE setWorkspace ) public: @@ -283,6 +284,16 @@ class QgsOracleProvider : public QgsVectorDataProvider */ virtual bool isSaveAndLoadStyleToDBSupported() const override { return true; } + /** + * Switch to oracle workspace + */ + void setWorkspace( const QString &workspace ); + + /** + * Retrieve oracle workspace name + */ + QString getWorkspace() const; + private: QString whereClause( QgsFeatureId featureId ) const; QString pkParamWhereClause() const; From 959f97f682027a106282f57253ce7fe87786c7ac Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 11:53:13 +1000 Subject: [PATCH 796/897] Allow not set choice in QgsMapLayerComboBox --- python/core/qgsmaplayermodel.sip | 16 ++ python/gui/qgsmaplayercombobox.sip | 14 ++ src/core/qgsmaplayermodel.cpp | 83 ++++++- src/core/qgsmaplayermodel.h | 20 +- src/core/qgsmaplayerproxymodel.cpp | 10 + src/gui/qgsmaplayercombobox.cpp | 10 + src/gui/qgsmaplayercombobox.h | 14 ++ tests/src/python/CMakeLists.txt | 1 + tests/src/python/test_qgsmaplayermodel.py | 266 ++++++++++++++++++++++ 9 files changed, 424 insertions(+), 10 deletions(-) create mode 100644 tests/src/python/test_qgsmaplayermodel.py diff --git a/python/core/qgsmaplayermodel.sip b/python/core/qgsmaplayermodel.sip index 80565e911cb0..655d7b18ac89 100644 --- a/python/core/qgsmaplayermodel.sip +++ b/python/core/qgsmaplayermodel.sip @@ -19,6 +19,7 @@ class QgsMapLayerModel : QAbstractItemModel { LayerIdRole, /*!< Stores the map layer ID */ LayerRole, /*!< Stores pointer to the map layer itself */ + IsEmptyRole, //!< True if index corresponds to the empty (not set) value }; /** @@ -38,6 +39,21 @@ class QgsMapLayerModel : QAbstractItemModel * @brief checkAll changes the checkstate for all the layers */ void checkAll( Qt::CheckState checkState ); + + /** + * Sets whether an optional empty layer ("not set") option is present in the model. + * @see allowEmptyLayer() + * @note added in QGIS 3.0 + */ + void setAllowEmptyLayer( bool allowEmpty ); + + /** + * Returns true if the model allows the empty layer ("not set") choice. + * @see setAllowEmptyLayer() + * @note added in QGIS 3.0 + */ + bool allowEmptyLayer() const; + /** * @brief layersChecked returns the list of layers which are checked (or unchecked) */ diff --git a/python/gui/qgsmaplayercombobox.sip b/python/gui/qgsmaplayercombobox.sip index dcc05dd402c3..4127bc084f28 100644 --- a/python/gui/qgsmaplayercombobox.sip +++ b/python/gui/qgsmaplayercombobox.sip @@ -28,6 +28,20 @@ class QgsMapLayerComboBox : QComboBox //! returns the list of excepted layers QList exceptedLayerList() const; + /** + * Sets whether an optional empty layer ("not set") option is shown in the combo box. + * @see allowEmptyLayer() + * @note added in QGIS 3.0 + */ + void setAllowEmptyLayer( bool allowEmpty ); + + /** + * Returns true if the combo box allows the empty layer ("not set") choice. + * @see setAllowEmptyLayer() + * @note added in QGIS 3.0 + */ + bool allowEmptyLayer() const; + /** Returns the current layer selected in the combo box. * @see layer */ diff --git a/src/core/qgsmaplayermodel.cpp b/src/core/qgsmaplayermodel.cpp index 150350e1072e..97129f720a74 100644 --- a/src/core/qgsmaplayermodel.cpp +++ b/src/core/qgsmaplayermodel.cpp @@ -26,6 +26,7 @@ QgsMapLayerModel::QgsMapLayerModel( const QList& layers, QObject : QAbstractItemModel( parent ) , mLayersChecked( QMap() ) , mItemCheckable( false ) + , mAllowEmpty( false ) { connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( removeLayers( QStringList ) ) ); addLayers( layers ); @@ -35,6 +36,7 @@ QgsMapLayerModel::QgsMapLayerModel( QObject *parent ) : QAbstractItemModel( parent ) , mLayersChecked( QMap() ) , mItemCheckable( false ) + , mAllowEmpty( false ) { connect( QgsMapLayerRegistry::instance(), SIGNAL( layersAdded( QList ) ), this, SLOT( addLayers( QList ) ) ); connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( removeLayers( QStringList ) ) ); @@ -55,6 +57,25 @@ void QgsMapLayerModel::checkAll( Qt::CheckState checkState ) emit dataChanged( index( 0, 0 ), index( mLayers.length() - 1, 0 ) ); } +void QgsMapLayerModel::setAllowEmptyLayer( bool allowEmpty ) +{ + if ( allowEmpty == mAllowEmpty ) + return; + + if ( allowEmpty ) + { + beginInsertRows( QModelIndex(), 0, 0 ); + mAllowEmpty = true; + endInsertRows(); + } + else + { + beginRemoveRows( QModelIndex(), 0, 0 ); + mAllowEmpty = false; + endRemoveRows(); + } +} + QList QgsMapLayerModel::layersChecked( Qt::CheckState checkState ) { QList layers; @@ -71,6 +92,8 @@ QList QgsMapLayerModel::layersChecked( Qt::CheckState checkState QModelIndex QgsMapLayerModel::indexFromLayer( QgsMapLayer *layer ) const { int r = mLayers.indexOf( layer ); + if ( r >= 0 && mAllowEmpty ) + r++; return index( r, 0 ); } @@ -93,7 +116,11 @@ void QgsMapLayerModel::removeLayers( const QStringList& layerIds ) void QgsMapLayerModel::addLayers( const QList& layers ) { - beginInsertRows( QModelIndex(), mLayers.count(), mLayers.count() + layers.count() - 1 ); + int offset = 0; + if ( mAllowEmpty ) + offset++; + + beginInsertRows( QModelIndex(), mLayers.count() + offset, mLayers.count() + layers.count() - 1 + offset ); Q_FOREACH ( QgsMapLayer* layer, layers ) { mLayers.append( layer ); @@ -104,9 +131,17 @@ void QgsMapLayerModel::addLayers( const QList& layers ) QModelIndex QgsMapLayerModel::index( int row, int column, const QModelIndex &parent ) const { + int offset = 0; + if ( mAllowEmpty ) + offset++; + if ( hasIndex( row, column, parent ) ) { - return createIndex( row, column, mLayers[row] ); + QgsMapLayer* layer = nullptr; + if ( row - offset >= 0 && row - offset < mLayers.count() ) + layer = mLayers.at( row - offset ); + + return createIndex( row, column, layer ); } return QModelIndex(); @@ -122,7 +157,10 @@ QModelIndex QgsMapLayerModel::parent( const QModelIndex &child ) const int QgsMapLayerModel::rowCount( const QModelIndex &parent ) const { - return parent.isValid() ? 0 : mLayers.length(); + if ( parent.isValid() ) + return 0; + + return ( mAllowEmpty ? 1 : 0 ) + mLayers.length(); } int QgsMapLayerModel::columnCount( const QModelIndex &parent ) const @@ -134,35 +172,58 @@ int QgsMapLayerModel::columnCount( const QModelIndex &parent ) const QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const { - if ( !index.isValid() || !index.internalPointer() ) + bool isEmpty = index.row() == 0 && mAllowEmpty; + + if ( !index.isValid() ) return QVariant(); if ( role == Qt::DisplayRole ) { + if ( index.row() == 0 && mAllowEmpty ) + return QVariant(); + QgsMapLayer* layer = static_cast( index.internalPointer() ); - return layer->name(); + return layer ? layer->name() : QVariant(); } if ( role == LayerIdRole ) { + if ( isEmpty ) + return QVariant(); + QgsMapLayer* layer = static_cast( index.internalPointer() ); - return layer->id(); + return layer ? layer->id() : QVariant(); } if ( role == LayerRole ) { + if ( isEmpty ) + return QVariant(); + return QVariant::fromValue( static_cast( index.internalPointer() ) ); } + if ( role == IsEmptyRole ) + return isEmpty; + if ( role == Qt::CheckStateRole && mItemCheckable ) { + if ( isEmpty ) + return QVariant(); + QgsMapLayer* layer = static_cast( index.internalPointer() ); - return mLayersChecked[layer->id()]; + return layer ? mLayersChecked[layer->id()] : QVariant(); } if ( role == Qt::DecorationRole ) { + if ( isEmpty ) + return QVariant(); + QgsMapLayer* layer = static_cast( index.internalPointer() ); + if ( !layer ) + return QVariant(); + QgsMapLayer::LayerType type = layer->type(); if ( role == Qt::DecorationRole ) { @@ -232,8 +293,10 @@ Qt::ItemFlags QgsMapLayerModel::flags( const QModelIndex &index ) const return 0; } + bool isEmpty = index.row() == 0 && mAllowEmpty; + Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - if ( mItemCheckable ) + if ( mItemCheckable && !isEmpty ) { flags |= Qt::ItemIsUserCheckable; } @@ -243,7 +306,9 @@ Qt::ItemFlags QgsMapLayerModel::flags( const QModelIndex &index ) const bool QgsMapLayerModel::setData( const QModelIndex &index, const QVariant &value, int role ) { - if ( role == Qt::CheckStateRole ) + bool isEmpty = index.row() == 0 && mAllowEmpty; + + if ( role == Qt::CheckStateRole && !isEmpty ) { QgsMapLayer* layer = static_cast( index.internalPointer() ); mLayersChecked[layer->id()] = ( Qt::CheckState )value.toInt(); diff --git a/src/core/qgsmaplayermodel.h b/src/core/qgsmaplayermodel.h index 084d07f86482..75ad02f6f076 100644 --- a/src/core/qgsmaplayermodel.h +++ b/src/core/qgsmaplayermodel.h @@ -39,6 +39,7 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel { LayerIdRole = Qt::UserRole + 1, //!< Stores the map layer ID LayerRole, //!< Stores pointer to the map layer itself + IsEmptyRole, //!< True if index corresponds to the empty (not set) value }; /** @@ -61,6 +62,20 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel */ void checkAll( Qt::CheckState checkState ); + /** + * Sets whether an optional empty layer ("not set") option is present in the model. + * @see allowEmptyLayer() + * @note added in QGIS 3.0 + */ + void setAllowEmptyLayer( bool allowEmpty ); + + /** + * Returns true if the model allows the empty layer ("not set") choice. + * @see setAllowEmptyLayer() + * @note added in QGIS 3.0 + */ + bool allowEmptyLayer() const { return mAllowEmpty; } + /** * @brief layersChecked returns the list of layers which are checked (or unchecked) */ @@ -73,7 +88,6 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel */ QModelIndex indexFromLayer( QgsMapLayer* layer ) const; - protected slots: void removeLayers( const QStringList& layerIds ); void addLayers( const QList& layers ); @@ -100,6 +114,10 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel bool setData( const QModelIndex &index, const QVariant &value, int role ) override; Qt::ItemFlags flags( const QModelIndex &index ) const override; + + private: + + bool mAllowEmpty; }; #endif // QGSMAPLAYERMODEL_H diff --git a/src/core/qgsmaplayerproxymodel.cpp b/src/core/qgsmaplayerproxymodel.cpp index 4372e58560f0..5404903d58bd 100644 --- a/src/core/qgsmaplayerproxymodel.cpp +++ b/src/core/qgsmaplayerproxymodel.cpp @@ -77,6 +77,10 @@ bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex return true; QModelIndex index = sourceModel()->index( source_row, 0, source_parent ); + + if ( sourceModel()->data( index, QgsMapLayerModel::IsEmptyRole ).toBool() ) + return true; + QgsMapLayer* layer = static_cast( index.internalPointer() ); if ( !layer ) return false; @@ -123,6 +127,12 @@ bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex bool QgsMapLayerProxyModel::lessThan( const QModelIndex &left, const QModelIndex &right ) const { + // empty row is always first + if ( sourceModel()->data( left, QgsMapLayerModel::IsEmptyRole ).toBool() ) + return true; + else if ( sourceModel()->data( right, QgsMapLayerModel::IsEmptyRole ).toBool() ) + return false; + // default mode is alphabetical order QString leftStr = sourceModel()->data( left ).toString(); QString rightStr = sourceModel()->data( right ).toString(); diff --git a/src/gui/qgsmaplayercombobox.cpp b/src/gui/qgsmaplayercombobox.cpp index 9818361a2acf..c8187a68db92 100644 --- a/src/gui/qgsmaplayercombobox.cpp +++ b/src/gui/qgsmaplayercombobox.cpp @@ -28,6 +28,16 @@ QgsMapLayerComboBox::QgsMapLayerComboBox( QWidget *parent ) connect( mProxyModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( rowsChanged() ) ); } +void QgsMapLayerComboBox::setAllowEmptyLayer( bool allowEmpty ) +{ + mProxyModel->sourceLayerModel()->setAllowEmptyLayer( allowEmpty ); +} + +bool QgsMapLayerComboBox::allowEmptyLayer() const +{ + return mProxyModel->sourceLayerModel()->allowEmptyLayer(); +} + void QgsMapLayerComboBox::setLayer( QgsMapLayer *layer ) { if ( !layer ) diff --git a/src/gui/qgsmaplayercombobox.h b/src/gui/qgsmaplayercombobox.h index 40ed469a3b41..bf4b8320ab43 100644 --- a/src/gui/qgsmaplayercombobox.h +++ b/src/gui/qgsmaplayercombobox.h @@ -53,6 +53,20 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox //! returns the list of excepted layers QList exceptedLayerList() const {return mProxyModel->exceptedLayerList();} + /** + * Sets whether an optional empty layer ("not set") option is shown in the combo box. + * @see allowEmptyLayer() + * @note added in QGIS 3.0 + */ + void setAllowEmptyLayer( bool allowEmpty ); + + /** + * Returns true if the combo box allows the empty layer ("not set") choice. + * @see setAllowEmptyLayer() + * @note added in QGIS 3.0 + */ + bool allowEmptyLayer() const; + /** Returns the current layer selected in the combo box. * @see layer */ diff --git a/tests/src/python/CMakeLists.txt b/tests/src/python/CMakeLists.txt index 3ee40185163e..249b683161fa 100644 --- a/tests/src/python/CMakeLists.txt +++ b/tests/src/python/CMakeLists.txt @@ -57,6 +57,7 @@ ADD_PYTHON_TEST(PyQgsGeometryValidator test_qgsgeometryvalidator.py) ADD_PYTHON_TEST(PyQgsGraduatedSymbolRenderer test_qgsgraduatedsymbolrenderer.py) ADD_PYTHON_TEST(PyQgsInterval test_qgsinterval.py) ADD_PYTHON_TEST(PyQgsJSONUtils test_qgsjsonutils.py) +ADD_PYTHON_TEST(PyQgsMapLayerModel test_qgsmaplayermodel.py) ADD_PYTHON_TEST(PyQgsMapUnitScale test_qgsmapunitscale.py) ADD_PYTHON_TEST(PyQgsMemoryProvider test_provider_memory.py) ADD_PYTHON_TEST(PyQgsMultiEditToolButton test_qgsmultiedittoolbutton.py) diff --git a/tests/src/python/test_qgsmaplayermodel.py b/tests/src/python/test_qgsmaplayermodel.py new file mode 100644 index 000000000000..e6e4b7cf69ab --- /dev/null +++ b/tests/src/python/test_qgsmaplayermodel.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- +"""QGIS Unit tests for QgsMapLayerModel + +.. note:: This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. +""" +__author__ = 'Nyall Dawson' +__date__ = '16/11/2016' +__copyright__ = 'Copyright 2016, The QGIS Project' +# This will get replaced with a git SHA1 when you do a git archive +__revision__ = '$Format:%H$' + +import qgis # NOQA + +from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMapLayerModel +from qgis.PyQt.QtCore import Qt, QModelIndex + +from qgis.testing import start_app, unittest + +start_app() + + +def create_layer(name): + layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", + name, "memory") + return layer + + +class TestQgsMapLayerModel(unittest.TestCase): + + def testGettersSetters(self): + """ test model getters/setters """ + m = QgsMapLayerModel() + + m.setItemsCheckable(True) + self.assertTrue(m.itemsCheckable()) + m.setItemsCheckable(False) + self.assertFalse(m.itemsCheckable()) + + m.setAllowEmptyLayer(True) + self.assertTrue(m.allowEmptyLayer()) + m.setAllowEmptyLayer(False) + self.assertFalse(m.allowEmptyLayer()) + + def testAddingRemovingLayers(self): + # test model handles layer addition and removal + m = QgsMapLayerModel() + + self.assertEqual(m.rowCount(QModelIndex()), 0) + + l1 = create_layer('l1') + QgsMapLayerRegistry.instance().addMapLayer(l1) + self.assertEqual(m.rowCount(QModelIndex()), 1) + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayer(l2) + self.assertEqual(m.rowCount(QModelIndex()), 2) + QgsMapLayerRegistry.instance().removeMapLayer(l1) + self.assertEqual(m.rowCount(QModelIndex()), 1) + QgsMapLayerRegistry.instance().removeMapLayer(l2) + self.assertEqual(m.rowCount(QModelIndex()), 0) + + # try creating a model when layers already exist in registry + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertEqual(m.rowCount(QModelIndex()), 2) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + self.assertEqual(m.rowCount(QModelIndex()), 0) + + def testCheckAll(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + m.setItemsCheckable(True) + self.assertFalse(m.layersChecked()) + self.assertEqual(set(m.layersChecked(Qt.Unchecked)), set([l1, l2])) + + m.checkAll(Qt.Checked) + self.assertEqual(set(m.layersChecked()), set([l1, l2])) + self.assertFalse(set(m.layersChecked(Qt.Unchecked))) + + m.checkAll(Qt.Unchecked) + self.assertFalse(m.layersChecked()) + self.assertEqual(set(m.layersChecked(Qt.Unchecked)), set([l1, l2])) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testAllowEmpty(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertEqual(m.rowCount(QModelIndex()), 2) + + m.setAllowEmptyLayer(True) + self.assertEqual(m.rowCount(QModelIndex()), 3) + self.assertFalse(m.data(m.index(0, 0), Qt.DisplayRole)) + m.setAllowEmptyLayer(False) + self.assertEqual(m.rowCount(QModelIndex()), 2) + self.assertTrue(m.data(m.index(0, 0), Qt.DisplayRole)) + + # add layers after allow empty is true + m.setAllowEmptyLayer(True) + l3 = create_layer('l3') + QgsMapLayerRegistry.instance().addMapLayers([l3]) + self.assertEqual(m.rowCount(QModelIndex()), 4) + self.assertFalse(m.data(m.index(0, 0), Qt.DisplayRole)) + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l1') + self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'l2') + self.assertEqual(m.data(m.index(3, 0), Qt.DisplayRole), 'l3') + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id(), l3.id()]) + + def testIndexFromLayer(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + l3 = create_layer('l3') # not in registry + + self.assertEqual(m.indexFromLayer(l1).row(), 0) + self.assertEqual(m.indexFromLayer(l2).row(), 1) + self.assertFalse(m.indexFromLayer(l3).isValid()) + + m.setAllowEmptyLayer(True) + self.assertEqual(m.indexFromLayer(l1).row(), 1) + self.assertEqual(m.indexFromLayer(l2).row(), 2) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testDisplayRole(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertEqual(m.data(m.index(0, 0), Qt.DisplayRole), 'l1') + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l2') + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), Qt.DisplayRole)) + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l1') + self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'l2') + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testLayerIdRole(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertEqual(m.data(m.index(0, 0), QgsMapLayerModel.LayerIdRole), l1.id()) + self.assertEqual(m.data(m.index(1, 0), QgsMapLayerModel.LayerIdRole), l2.id()) + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.LayerIdRole)) + self.assertEqual(m.data(m.index(1, 0), QgsMapLayerModel.LayerIdRole), l1.id()) + self.assertEqual(m.data(m.index(2, 0), QgsMapLayerModel.LayerIdRole), l2.id()) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testLayerRole(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertEqual(m.data(m.index(0, 0), QgsMapLayerModel.LayerRole), l1) + self.assertEqual(m.data(m.index(1, 0), QgsMapLayerModel.LayerRole), l2) + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.LayerRole)) + self.assertEqual(m.data(m.index(1, 0), QgsMapLayerModel.LayerRole), l1) + self.assertEqual(m.data(m.index(2, 0), QgsMapLayerModel.LayerRole), l2) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testIsEmptyRole(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsEmptyRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsEmptyRole)) + m.setAllowEmptyLayer(True) + self.assertTrue(m.data(m.index(0, 0), QgsMapLayerModel.IsEmptyRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsEmptyRole)) + self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsEmptyRole)) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testCheckStateRole(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + + # not checkable + self.assertFalse(m.data(m.index(0, 0), Qt.CheckStateRole)) + self.assertFalse(m.data(m.index(1, 0), Qt.CheckStateRole)) + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), Qt.CheckStateRole)) + self.assertFalse(m.data(m.index(1, 0), Qt.CheckStateRole)) + self.assertFalse(m.data(m.index(2, 0), Qt.CheckStateRole)) + m.setAllowEmptyLayer(False) + + # checkable + m.setItemsCheckable(True) + m.checkAll(Qt.Checked) + self.assertTrue(m.data(m.index(0, 0), Qt.CheckStateRole)) + self.assertTrue(m.data(m.index(1, 0), Qt.CheckStateRole)) + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), Qt.CheckStateRole)) + self.assertTrue(m.data(m.index(1, 0), Qt.CheckStateRole)) + self.assertTrue(m.data(m.index(2, 0), Qt.CheckStateRole)) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testFlags(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + + # not checkable + self.assertFalse(m.flags(m.index(0, 0)) & Qt.ItemIsUserCheckable) + self.assertFalse(m.flags(m.index(1, 0)) & Qt.ItemIsUserCheckable) + m.setAllowEmptyLayer(True) + self.assertFalse(m.flags(m.index(0, 0)) & Qt.ItemIsUserCheckable) + self.assertFalse(m.flags(m.index(1, 0)) & Qt.ItemIsUserCheckable) + self.assertFalse(m.flags(m.index(2, 0)) & Qt.ItemIsUserCheckable) + m.setAllowEmptyLayer(False) + + # checkable + m.setItemsCheckable(True) + self.assertTrue(m.flags(m.index(0, 0)) & Qt.ItemIsUserCheckable) + self.assertTrue(m.flags(m.index(1, 0)) & Qt.ItemIsUserCheckable) + m.setAllowEmptyLayer(True) + self.assertFalse(m.flags(m.index(0, 0)) & Qt.ItemIsUserCheckable) + self.assertTrue(m.flags(m.index(1, 0)) & Qt.ItemIsUserCheckable) + self.assertTrue(m.flags(m.index(2, 0)) & Qt.ItemIsUserCheckable) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testSetData(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + + # set checked + m.setItemsCheckable(True) + self.assertTrue(m.setData(m.index(0, 0), True, Qt.CheckStateRole)) + self.assertTrue(m.data(m.index(0, 0), Qt.CheckStateRole)) + self.assertFalse(m.data(m.index(1, 0), Qt.CheckStateRole)) + self.assertTrue(m.setData(m.index(1, 0), True, Qt.CheckStateRole)) + self.assertTrue(m.data(m.index(0, 0), Qt.CheckStateRole)) + self.assertTrue(m.data(m.index(1, 0), Qt.CheckStateRole)) + + m.setAllowEmptyLayer(True) + self.assertFalse(m.setData(m.index(0, 0), True, Qt.CheckStateRole)) + self.assertTrue(m.setData(m.index(1, 0), True, Qt.CheckStateRole)) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + +if __name__ == '__main__': + unittest.main() From ec49341f85f9359682aee578d40f90a06a7cfb71 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 12:13:09 +1000 Subject: [PATCH 797/897] Allow showing CRS in QgsMapLayerComboBox --- python/core/qgsmaplayermodel.sip | 22 ++++++++++++++---- python/gui/qgsmaplayercombobox.sip | 14 ++++++++++++ src/core/qgsmaplayermodel.cpp | 25 ++++++++++++++++++-- src/core/qgsmaplayermodel.h | 28 +++++++++++++++++++---- src/gui/qgsmaplayercombobox.cpp | 10 ++++++++ src/gui/qgsmaplayercombobox.h | 16 +++++++++++++ tests/src/python/test_qgsmaplayermodel.py | 22 +++++++++++++++++- 7 files changed, 126 insertions(+), 11 deletions(-) diff --git a/python/core/qgsmaplayermodel.sip b/python/core/qgsmaplayermodel.sip index 655d7b18ac89..d746c37be4f3 100644 --- a/python/core/qgsmaplayermodel.sip +++ b/python/core/qgsmaplayermodel.sip @@ -54,6 +54,20 @@ class QgsMapLayerModel : QAbstractItemModel */ bool allowEmptyLayer() const; + /** + * Sets whether the CRS of layers is also included in the model's display role. + * @see showCrs() + * @note added in QGIS 3.0 + */ + void setShowCrs( bool showCrs ); + + /** + * Returns true if the model includes layer's CRS in the display role. + * @see setShowCrs() + * @note added in QGIS 3.0 + */ + bool showCrs() const; + /** * @brief layersChecked returns the list of layers which are checked (or unchecked) */ @@ -75,15 +89,15 @@ class QgsMapLayerModel : QAbstractItemModel public: QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const; QModelIndex parent( const QModelIndex &child ) const; - int rowCount( const QModelIndex &parent ) const; - int columnCount( const QModelIndex &parent ) const; - QVariant data( const QModelIndex &index, int role ) const; + int rowCount( const QModelIndex &parent = QModelIndex() ) const; + int columnCount( const QModelIndex &parent = QModelIndex() ) const; + QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const; /** * Returns strings for all roles supported by this model. */ QHash roleNames() const; - bool setData( const QModelIndex &index, const QVariant &value, int role ); + bool setData( const QModelIndex &index, const QVariant &value, int role = Qt::DisplayRole ); Qt::ItemFlags flags( const QModelIndex &index ) const; }; diff --git a/python/gui/qgsmaplayercombobox.sip b/python/gui/qgsmaplayercombobox.sip index 4127bc084f28..fbef794a780a 100644 --- a/python/gui/qgsmaplayercombobox.sip +++ b/python/gui/qgsmaplayercombobox.sip @@ -42,6 +42,20 @@ class QgsMapLayerComboBox : QComboBox */ bool allowEmptyLayer() const; + /** + * Sets whether the CRS of layers is also included in the combo box text. + * @see showCrs() + * @note added in QGIS 3.0 + */ + void setShowCrs( bool showCrs ); + + /** + * Returns true if the combo box shows the layer's CRS. + * @see setShowCrs() + * @note added in QGIS 3.0 + */ + bool showCrs() const; + /** Returns the current layer selected in the combo box. * @see layer */ diff --git a/src/core/qgsmaplayermodel.cpp b/src/core/qgsmaplayermodel.cpp index 97129f720a74..a244b86672a5 100644 --- a/src/core/qgsmaplayermodel.cpp +++ b/src/core/qgsmaplayermodel.cpp @@ -27,6 +27,7 @@ QgsMapLayerModel::QgsMapLayerModel( const QList& layers, QObject , mLayersChecked( QMap() ) , mItemCheckable( false ) , mAllowEmpty( false ) + , mShowCrs( false ) { connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( removeLayers( QStringList ) ) ); addLayers( layers ); @@ -37,6 +38,7 @@ QgsMapLayerModel::QgsMapLayerModel( QObject *parent ) , mLayersChecked( QMap() ) , mItemCheckable( false ) , mAllowEmpty( false ) + , mShowCrs( false ) { connect( QgsMapLayerRegistry::instance(), SIGNAL( layersAdded( QList ) ), this, SLOT( addLayers( QList ) ) ); connect( QgsMapLayerRegistry::instance(), SIGNAL( layersWillBeRemoved( QStringList ) ), this, SLOT( removeLayers( QStringList ) ) ); @@ -54,7 +56,7 @@ void QgsMapLayerModel::checkAll( Qt::CheckState checkState ) { mLayersChecked[key] = checkState; } - emit dataChanged( index( 0, 0 ), index( mLayers.length() - 1, 0 ) ); + emit dataChanged( index( 0, 0 ), index( rowCount() - 1, 0 ) ); } void QgsMapLayerModel::setAllowEmptyLayer( bool allowEmpty ) @@ -76,6 +78,15 @@ void QgsMapLayerModel::setAllowEmptyLayer( bool allowEmpty ) } } +void QgsMapLayerModel::setShowCrs( bool showCrs ) +{ + if ( mShowCrs == showCrs ) + return; + + mShowCrs = showCrs; + emit dataChanged( index( 0, 0 ), index( rowCount() - 1, 0 ), QVector() << Qt::DisplayRole ); +} + QList QgsMapLayerModel::layersChecked( Qt::CheckState checkState ) { QList layers; @@ -183,7 +194,17 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const return QVariant(); QgsMapLayer* layer = static_cast( index.internalPointer() ); - return layer ? layer->name() : QVariant(); + if ( !layer ) + return QVariant(); + + if ( !mShowCrs ) + { + return layer->name(); + } + else + { + return tr( "%1 [%2]" ).arg( layer->name(), layer->crs().authid() ); + } } if ( role == LayerIdRole ) diff --git a/src/core/qgsmaplayermodel.h b/src/core/qgsmaplayermodel.h index 75ad02f6f076..0f1ac065625e 100644 --- a/src/core/qgsmaplayermodel.h +++ b/src/core/qgsmaplayermodel.h @@ -32,6 +32,11 @@ class QgsMapLayer; class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel { Q_OBJECT + + Q_PROPERTY( bool allowEmptyLayer READ allowEmptyLayer WRITE setAllowEmptyLayer ) + Q_PROPERTY( bool showCrs READ showCrs WRITE setShowCrs ) + Q_PROPERTY( bool itemsCheckable READ itemsCheckable WRITE setItemsCheckable ) + public: //! Item data roles @@ -76,6 +81,20 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel */ bool allowEmptyLayer() const { return mAllowEmpty; } + /** + * Sets whether the CRS of layers is also included in the model's display role. + * @see showCrs() + * @note added in QGIS 3.0 + */ + void setShowCrs( bool showCrs ); + + /** + * Returns true if the model includes layer's CRS in the display role. + * @see setShowCrs() + * @note added in QGIS 3.0 + */ + bool showCrs() const { return mShowCrs; } + /** * @brief layersChecked returns the list of layers which are checked (or unchecked) */ @@ -101,9 +120,9 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel public: QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const override; QModelIndex parent( const QModelIndex &child ) const override; - int rowCount( const QModelIndex &parent ) const override; - int columnCount( const QModelIndex &parent ) const override; - QVariant data( const QModelIndex &index, int role ) const override; + int rowCount( const QModelIndex &parent = QModelIndex() ) const override; + int columnCount( const QModelIndex &parent = QModelIndex() ) const override; + QVariant data( const QModelIndex &index, int role = Qt::DisplayRole ) const override; /** * Returns strings for all roles supported by this model. @@ -112,12 +131,13 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel */ QHash roleNames() const override; - bool setData( const QModelIndex &index, const QVariant &value, int role ) override; + bool setData( const QModelIndex &index, const QVariant &value, int role = Qt::EditRole ) override; Qt::ItemFlags flags( const QModelIndex &index ) const override; private: bool mAllowEmpty; + bool mShowCrs; }; #endif // QGSMAPLAYERMODEL_H diff --git a/src/gui/qgsmaplayercombobox.cpp b/src/gui/qgsmaplayercombobox.cpp index c8187a68db92..932b13d2c415 100644 --- a/src/gui/qgsmaplayercombobox.cpp +++ b/src/gui/qgsmaplayercombobox.cpp @@ -38,6 +38,16 @@ bool QgsMapLayerComboBox::allowEmptyLayer() const return mProxyModel->sourceLayerModel()->allowEmptyLayer(); } +void QgsMapLayerComboBox::setShowCrs( bool showCrs ) +{ + mProxyModel->sourceLayerModel()->setShowCrs( showCrs ); +} + +bool QgsMapLayerComboBox::showCrs() const +{ + return mProxyModel->sourceLayerModel()->showCrs(); +} + void QgsMapLayerComboBox::setLayer( QgsMapLayer *layer ) { if ( !layer ) diff --git a/src/gui/qgsmaplayercombobox.h b/src/gui/qgsmaplayercombobox.h index bf4b8320ab43..2355520ea817 100644 --- a/src/gui/qgsmaplayercombobox.h +++ b/src/gui/qgsmaplayercombobox.h @@ -32,6 +32,8 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox Q_OBJECT Q_FLAGS( QgsMapLayerProxyModel::Filters ) Q_PROPERTY( QgsMapLayerProxyModel::Filters filters READ filters WRITE setFilters ) + Q_PROPERTY( bool allowEmptyLayer READ allowEmptyLayer WRITE setAllowEmptyLayer ) + Q_PROPERTY( bool showCrs READ showCrs WRITE setShowCrs ) public: @@ -67,6 +69,20 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox */ bool allowEmptyLayer() const; + /** + * Sets whether the CRS of layers is also included in the combo box text. + * @see showCrs() + * @note added in QGIS 3.0 + */ + void setShowCrs( bool showCrs ); + + /** + * Returns true if the combo box shows the layer's CRS. + * @see setShowCrs() + * @note added in QGIS 3.0 + */ + bool showCrs() const; + /** Returns the current layer selected in the combo box. * @see layer */ diff --git a/tests/src/python/test_qgsmaplayermodel.py b/tests/src/python/test_qgsmaplayermodel.py index e6e4b7cf69ab..cdc5b74c1711 100644 --- a/tests/src/python/test_qgsmaplayermodel.py +++ b/tests/src/python/test_qgsmaplayermodel.py @@ -23,7 +23,7 @@ def create_layer(name): - layer = QgsVectorLayer("Point?field=fldtxt:string&field=fldint:integer", + layer = QgsVectorLayer("Point?crs=EPSG:3111&field=fldtxt:string&field=fldint:integer", name, "memory") return layer @@ -44,6 +44,11 @@ def testGettersSetters(self): m.setAllowEmptyLayer(False) self.assertFalse(m.allowEmptyLayer()) + m.setShowCrs(True) + self.assertTrue(m.showCrs()) + m.setShowCrs(False) + self.assertFalse(m.showCrs()) + def testAddingRemovingLayers(self): # test model handles layer addition and removal m = QgsMapLayerModel() @@ -146,6 +151,21 @@ def testDisplayRole(self): QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + def testDisplayRoleShowCrs(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + m.setShowCrs(True) + self.assertEqual(m.data(m.index(0, 0), Qt.DisplayRole), 'l1 [EPSG:3111]') + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l2 [EPSG:3111]') + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), Qt.DisplayRole)) + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l1 [EPSG:3111]') + self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'l2 [EPSG:3111]') + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + def testLayerIdRole(self): l1 = create_layer('l1') l2 = create_layer('l2') From 9ee7873572237fbb54cc677503686af3349ed414 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 13:32:27 +1000 Subject: [PATCH 798/897] Allow showing additional items in QgsMapLayerComboBox These may represent additional layers such as layers which are not included in the map layer registry, or paths to layers which have not yet been loaded into QGIS. --- python/core/qgsmaplayermodel.sip | 17 +++++ python/gui/qgsmaplayercombobox.sip | 16 +++++ src/core/qgsmaplayermodel.cpp | 58 +++++++++++++++--- src/core/qgsmaplayermodel.h | 19 ++++++ src/core/qgsmaplayerproxymodel.cpp | 12 +++- src/gui/qgsmaplayercombobox.cpp | 10 +++ src/gui/qgsmaplayercombobox.h | 16 +++++ tests/src/python/test_qgsmaplayermodel.py | 75 +++++++++++++++++++++++ 8 files changed, 212 insertions(+), 11 deletions(-) diff --git a/python/core/qgsmaplayermodel.sip b/python/core/qgsmaplayermodel.sip index d746c37be4f3..b11249bf4530 100644 --- a/python/core/qgsmaplayermodel.sip +++ b/python/core/qgsmaplayermodel.sip @@ -20,6 +20,7 @@ class QgsMapLayerModel : QAbstractItemModel LayerIdRole, /*!< Stores the map layer ID */ LayerRole, /*!< Stores pointer to the map layer itself */ IsEmptyRole, //!< True if index corresponds to the empty (not set) value + IsAdditionalRole, //!< True if index corresponds to an additional (non map layer) item }; /** @@ -68,6 +69,22 @@ class QgsMapLayerModel : QAbstractItemModel */ bool showCrs() const; + /** + * Sets a list of additional (non map layer) items to include at the end of the model. + * These may represent additional layers such as layers which are not included in the map + * layer registry, or paths to layers which have not yet been loaded into QGIS. + * @see additionalItems() + * @note added in QGIS 3.0 + */ + void setAdditionalItems( const QStringList& items ); + + /** + * Return the list of additional (non map layer) items included at the end of the model. + * @see setAdditionalItems() + * @note added in QGIS 3.0 + */ + QStringList additionalItems() const; + /** * @brief layersChecked returns the list of layers which are checked (or unchecked) */ diff --git a/python/gui/qgsmaplayercombobox.sip b/python/gui/qgsmaplayercombobox.sip index fbef794a780a..eac04bf57ef7 100644 --- a/python/gui/qgsmaplayercombobox.sip +++ b/python/gui/qgsmaplayercombobox.sip @@ -56,6 +56,22 @@ class QgsMapLayerComboBox : QComboBox */ bool showCrs() const; + /** + * Sets a list of additional (non map layer) items to include at the end of the combobox. + * These may represent additional layers such as layers which are not included in the map + * layer registry, or paths to layers which have not yet been loaded into QGIS. + * @see additionalItems() + * @note added in QGIS 3.0 + */ + void setAdditionalItems( const QStringList& items ); + + /** + * Return the list of additional (non map layer) items included at the end of the combo box. + * @see setAdditionalItems() + * @note added in QGIS 3.0 + */ + QStringList additionalItems() const; + /** Returns the current layer selected in the combo box. * @see layer */ diff --git a/src/core/qgsmaplayermodel.cpp b/src/core/qgsmaplayermodel.cpp index a244b86672a5..8ac27ef278e1 100644 --- a/src/core/qgsmaplayermodel.cpp +++ b/src/core/qgsmaplayermodel.cpp @@ -108,8 +108,37 @@ QModelIndex QgsMapLayerModel::indexFromLayer( QgsMapLayer *layer ) const return index( r, 0 ); } +void QgsMapLayerModel::setAdditionalItems( const QStringList& items ) +{ + if ( items == mAdditionalItems ) + return; + + int offset = 0; + if ( mAllowEmpty ) + offset++; + + offset += mLayers.count(); + + //remove existing + if ( !mAdditionalItems.isEmpty() ) + { + beginRemoveRows( QModelIndex(), offset, offset + mAdditionalItems.count() - 1 ); + mAdditionalItems.clear(); + endRemoveRows(); + } + + //add new + beginInsertRows( QModelIndex(), offset, offset + items.count() - 1 ); + mAdditionalItems = items; + endInsertRows(); +} + void QgsMapLayerModel::removeLayers( const QStringList& layerIds ) { + int offset = 0; + if ( mAllowEmpty ) + offset++; + Q_FOREACH ( const QString& layerId, layerIds ) { QModelIndex startIndex = index( 0, 0 ); @@ -119,7 +148,7 @@ void QgsMapLayerModel::removeLayers( const QStringList& layerIds ) QModelIndex index = list[0]; beginRemoveRows( QModelIndex(), index.row(), index.row() ); mLayersChecked.remove( layerId ); - mLayers.removeAt( index.row() ); + mLayers.removeAt( index.row() - offset ); endRemoveRows(); } } @@ -171,7 +200,7 @@ int QgsMapLayerModel::rowCount( const QModelIndex &parent ) const if ( parent.isValid() ) return 0; - return ( mAllowEmpty ? 1 : 0 ) + mLayers.length(); + return ( mAllowEmpty ? 1 : 0 ) + mLayers.length() + mAdditionalItems.count(); } int QgsMapLayerModel::columnCount( const QModelIndex &parent ) const @@ -183,16 +212,20 @@ int QgsMapLayerModel::columnCount( const QModelIndex &parent ) const QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const { - bool isEmpty = index.row() == 0 && mAllowEmpty; - if ( !index.isValid() ) return QVariant(); + bool isEmpty = index.row() == 0 && mAllowEmpty; + int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); + if ( role == Qt::DisplayRole ) { if ( index.row() == 0 && mAllowEmpty ) return QVariant(); + if ( additionalIndex >= 0 ) + return mAdditionalItems.at( additionalIndex ); + QgsMapLayer* layer = static_cast( index.internalPointer() ); if ( !layer ) return QVariant(); @@ -209,7 +242,7 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const if ( role == LayerIdRole ) { - if ( isEmpty ) + if ( isEmpty || additionalIndex >= 0 ) return QVariant(); QgsMapLayer* layer = static_cast( index.internalPointer() ); @@ -218,7 +251,7 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const if ( role == LayerRole ) { - if ( isEmpty ) + if ( isEmpty || additionalIndex >= 0 ) return QVariant(); return QVariant::fromValue( static_cast( index.internalPointer() ) ); @@ -227,9 +260,12 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const if ( role == IsEmptyRole ) return isEmpty; + if ( role == IsAdditionalRole ) + return additionalIndex >= 0; + if ( role == Qt::CheckStateRole && mItemCheckable ) { - if ( isEmpty ) + if ( isEmpty || additionalIndex >= 0 ) return QVariant(); QgsMapLayer* layer = static_cast( index.internalPointer() ); @@ -238,7 +274,7 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const if ( role == Qt::DecorationRole ) { - if ( isEmpty ) + if ( isEmpty || additionalIndex >= 0 ) return QVariant(); QgsMapLayer* layer = static_cast( index.internalPointer() ); @@ -315,9 +351,10 @@ Qt::ItemFlags QgsMapLayerModel::flags( const QModelIndex &index ) const } bool isEmpty = index.row() == 0 && mAllowEmpty; + int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; - if ( mItemCheckable && !isEmpty ) + if ( mItemCheckable && !isEmpty && additionalIndex < 0 ) { flags |= Qt::ItemIsUserCheckable; } @@ -328,8 +365,9 @@ Qt::ItemFlags QgsMapLayerModel::flags( const QModelIndex &index ) const bool QgsMapLayerModel::setData( const QModelIndex &index, const QVariant &value, int role ) { bool isEmpty = index.row() == 0 && mAllowEmpty; + int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); - if ( role == Qt::CheckStateRole && !isEmpty ) + if ( role == Qt::CheckStateRole && !isEmpty && additionalIndex < 0 ) { QgsMapLayer* layer = static_cast( index.internalPointer() ); mLayersChecked[layer->id()] = ( Qt::CheckState )value.toInt(); diff --git a/src/core/qgsmaplayermodel.h b/src/core/qgsmaplayermodel.h index 0f1ac065625e..ec7ff07cc983 100644 --- a/src/core/qgsmaplayermodel.h +++ b/src/core/qgsmaplayermodel.h @@ -36,6 +36,7 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel Q_PROPERTY( bool allowEmptyLayer READ allowEmptyLayer WRITE setAllowEmptyLayer ) Q_PROPERTY( bool showCrs READ showCrs WRITE setShowCrs ) Q_PROPERTY( bool itemsCheckable READ itemsCheckable WRITE setItemsCheckable ) + Q_PROPERTY( QStringList additionalItems READ additionalItems WRITE setAdditionalItems ) public: @@ -45,6 +46,7 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel LayerIdRole = Qt::UserRole + 1, //!< Stores the map layer ID LayerRole, //!< Stores pointer to the map layer itself IsEmptyRole, //!< True if index corresponds to the empty (not set) value + IsAdditionalRole, //!< True if index corresponds to an additional (non map layer) item }; /** @@ -107,6 +109,22 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel */ QModelIndex indexFromLayer( QgsMapLayer* layer ) const; + /** + * Sets a list of additional (non map layer) items to include at the end of the model. + * These may represent additional layers such as layers which are not included in the map + * layer registry, or paths to layers which have not yet been loaded into QGIS. + * @see additionalItems() + * @note added in QGIS 3.0 + */ + void setAdditionalItems( const QStringList& items ); + + /** + * Return the list of additional (non map layer) items included at the end of the model. + * @see setAdditionalItems() + * @note added in QGIS 3.0 + */ + QStringList additionalItems() const { return mAdditionalItems; } + protected slots: void removeLayers( const QStringList& layerIds ); void addLayers( const QList& layers ); @@ -138,6 +156,7 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel bool mAllowEmpty; bool mShowCrs; + QStringList mAdditionalItems; }; #endif // QGSMAPLAYERMODEL_H diff --git a/src/core/qgsmaplayerproxymodel.cpp b/src/core/qgsmaplayerproxymodel.cpp index 5404903d58bd..6c190b4841ea 100644 --- a/src/core/qgsmaplayerproxymodel.cpp +++ b/src/core/qgsmaplayerproxymodel.cpp @@ -78,7 +78,8 @@ bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex QModelIndex index = sourceModel()->index( source_row, 0, source_parent ); - if ( sourceModel()->data( index, QgsMapLayerModel::IsEmptyRole ).toBool() ) + if ( sourceModel()->data( index, QgsMapLayerModel::IsEmptyRole ).toBool() + || sourceModel()->data( index, QgsMapLayerModel::IsAdditionalRole ).toBool() ) return true; QgsMapLayer* layer = static_cast( index.internalPointer() ); @@ -133,6 +134,15 @@ bool QgsMapLayerProxyModel::lessThan( const QModelIndex &left, const QModelIndex else if ( sourceModel()->data( right, QgsMapLayerModel::IsEmptyRole ).toBool() ) return false; + // additional rows are always last + bool leftAdditional = sourceModel()->data( left, QgsMapLayerModel::IsAdditionalRole ).toBool(); + bool rightAdditional = sourceModel()->data( right, QgsMapLayerModel::IsAdditionalRole ).toBool(); + + if ( leftAdditional && !rightAdditional ) + return false; + else if ( rightAdditional && !leftAdditional ) + return true; + // default mode is alphabetical order QString leftStr = sourceModel()->data( left ).toString(); QString rightStr = sourceModel()->data( right ).toString(); diff --git a/src/gui/qgsmaplayercombobox.cpp b/src/gui/qgsmaplayercombobox.cpp index 932b13d2c415..22067d1947f3 100644 --- a/src/gui/qgsmaplayercombobox.cpp +++ b/src/gui/qgsmaplayercombobox.cpp @@ -48,6 +48,16 @@ bool QgsMapLayerComboBox::showCrs() const return mProxyModel->sourceLayerModel()->showCrs(); } +void QgsMapLayerComboBox::setAdditionalItems( const QStringList& items ) +{ + mProxyModel->sourceLayerModel()->setAdditionalItems( items ); +} + +QStringList QgsMapLayerComboBox::additionalItems() const +{ + return mProxyModel->sourceLayerModel()->additionalItems(); +} + void QgsMapLayerComboBox::setLayer( QgsMapLayer *layer ) { if ( !layer ) diff --git a/src/gui/qgsmaplayercombobox.h b/src/gui/qgsmaplayercombobox.h index 2355520ea817..fb1f87d18053 100644 --- a/src/gui/qgsmaplayercombobox.h +++ b/src/gui/qgsmaplayercombobox.h @@ -83,6 +83,22 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox */ bool showCrs() const; + /** + * Sets a list of additional (non map layer) items to include at the end of the combobox. + * These may represent additional layers such as layers which are not included in the map + * layer registry, or paths to layers which have not yet been loaded into QGIS. + * @see additionalItems() + * @note added in QGIS 3.0 + */ + void setAdditionalItems( const QStringList& items ); + + /** + * Return the list of additional (non map layer) items included at the end of the combo box. + * @see setAdditionalItems() + * @note added in QGIS 3.0 + */ + QStringList additionalItems() const; + /** Returns the current layer selected in the combo box. * @see layer */ diff --git a/tests/src/python/test_qgsmaplayermodel.py b/tests/src/python/test_qgsmaplayermodel.py index cdc5b74c1711..dbe421cb3c5f 100644 --- a/tests/src/python/test_qgsmaplayermodel.py +++ b/tests/src/python/test_qgsmaplayermodel.py @@ -49,6 +49,11 @@ def testGettersSetters(self): m.setShowCrs(False) self.assertFalse(m.showCrs()) + m.setAdditionalItems(['a', 'b']) + self.assertEqual(m.additionalItems(), ['a', 'b']) + m.setAdditionalItems([]) + self.assertFalse(m.additionalItems()) + def testAddingRemovingLayers(self): # test model handles layer addition and removal m = QgsMapLayerModel() @@ -120,6 +125,35 @@ def testAllowEmpty(self): QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id(), l3.id()]) + def testAdditionalItems(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertEqual(m.rowCount(QModelIndex()), 2) + + m.setAdditionalItems(['a', 'b']) + self.assertEqual(m.rowCount(QModelIndex()), 4) + self.assertEqual(m.data(m.index(0, 0), Qt.DisplayRole), 'l1') + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l2') + self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'a') + self.assertEqual(m.data(m.index(3, 0), Qt.DisplayRole), 'b') + + m.setAllowEmptyLayer(True) + self.assertEqual(m.rowCount(QModelIndex()), 5) + self.assertFalse(m.data(m.index(0, 0), Qt.DisplayRole)) + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l1') + self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'l2') + self.assertEqual(m.data(m.index(3, 0), Qt.DisplayRole), 'a') + self.assertEqual(m.data(m.index(4, 0), Qt.DisplayRole), 'b') + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + self.assertEqual(m.rowCount(QModelIndex()), 3) + self.assertFalse(m.data(m.index(0, 0), Qt.DisplayRole)) + self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'a') + self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'b') + def testIndexFromLayer(self): l1 = create_layer('l1') l2 = create_layer('l2') @@ -164,6 +198,9 @@ def testDisplayRoleShowCrs(self): self.assertEqual(m.data(m.index(1, 0), Qt.DisplayRole), 'l1 [EPSG:3111]') self.assertEqual(m.data(m.index(2, 0), Qt.DisplayRole), 'l2 [EPSG:3111]') + m.setAdditionalItems(['a']) + self.assertEqual(m.data(m.index(3, 0), Qt.DisplayRole), 'a') + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) def testLayerIdRole(self): @@ -178,6 +215,9 @@ def testLayerIdRole(self): self.assertEqual(m.data(m.index(1, 0), QgsMapLayerModel.LayerIdRole), l1.id()) self.assertEqual(m.data(m.index(2, 0), QgsMapLayerModel.LayerIdRole), l2.id()) + m.setAdditionalItems(['a']) + self.assertFalse(m.data(m.index(3, 0), QgsMapLayerModel.LayerIdRole)) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) def testLayerRole(self): @@ -192,6 +232,9 @@ def testLayerRole(self): self.assertEqual(m.data(m.index(1, 0), QgsMapLayerModel.LayerRole), l1) self.assertEqual(m.data(m.index(2, 0), QgsMapLayerModel.LayerRole), l2) + m.setAdditionalItems(['a']) + self.assertFalse(m.data(m.index(3, 0), QgsMapLayerModel.LayerRole)) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) def testIsEmptyRole(self): @@ -206,6 +249,29 @@ def testIsEmptyRole(self): self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsEmptyRole)) self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsEmptyRole)) + m.setAdditionalItems(['a']) + self.assertFalse(m.data(m.index(3, 0), QgsMapLayerModel.IsEmptyRole)) + + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) + + def testIsAdditionalRole(self): + l1 = create_layer('l1') + l2 = create_layer('l2') + QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) + m = QgsMapLayerModel() + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsAdditionalRole)) + m.setAllowEmptyLayer(True) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsAdditionalRole)) + + m.setAdditionalItems(['a']) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertTrue(m.data(m.index(3, 0), QgsMapLayerModel.IsAdditionalRole)) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) def testCheckStateRole(self): @@ -233,6 +299,9 @@ def testCheckStateRole(self): self.assertTrue(m.data(m.index(1, 0), Qt.CheckStateRole)) self.assertTrue(m.data(m.index(2, 0), Qt.CheckStateRole)) + m.setAdditionalItems(['a']) + self.assertFalse(m.data(m.index(3, 0), Qt.CheckStateRole)) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) def testFlags(self): @@ -259,6 +328,9 @@ def testFlags(self): self.assertTrue(m.flags(m.index(1, 0)) & Qt.ItemIsUserCheckable) self.assertTrue(m.flags(m.index(2, 0)) & Qt.ItemIsUserCheckable) + m.setAdditionalItems(['a']) + self.assertFalse(m.flags(m.index(3, 0)) & Qt.ItemIsUserCheckable) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) def testSetData(self): @@ -280,6 +352,9 @@ def testSetData(self): self.assertFalse(m.setData(m.index(0, 0), True, Qt.CheckStateRole)) self.assertTrue(m.setData(m.index(1, 0), True, Qt.CheckStateRole)) + m.setAdditionalItems(['a']) + self.assertFalse(m.setData(m.index(3, 0), True, Qt.CheckStateRole)) + QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) if __name__ == '__main__': From 5c3aea33b8e50ebe778c1c24ead770340413ff82 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 13:46:20 +1000 Subject: [PATCH 799/897] Allow filtering QgsMapLayerComboBox by data provider --- python/core/qgsmaplayerproxymodel.sip | 14 ++++++++++++++ python/gui/qgsmaplayercombobox.sip | 14 ++++++++++++++ src/core/qgsmaplayerproxymodel.cpp | 16 +++++++++++++++- src/core/qgsmaplayerproxymodel.h | 15 +++++++++++++++ src/gui/qgsmaplayercombobox.cpp | 10 ++++++++++ src/gui/qgsmaplayercombobox.h | 15 +++++++++++++++ 6 files changed, 83 insertions(+), 1 deletion(-) diff --git a/python/core/qgsmaplayerproxymodel.sip b/python/core/qgsmaplayerproxymodel.sip index 37aee2888122..20c91847ea7b 100644 --- a/python/core/qgsmaplayerproxymodel.sip +++ b/python/core/qgsmaplayerproxymodel.sip @@ -54,6 +54,20 @@ class QgsMapLayerProxyModel : QSortFilterProxyModel //! Get the list of maplayer ids which are excluded from the list QStringList exceptedLayerIds() const; + /** + * Sets a list of data providers which should be excluded from the model. + * @note added in QGIS 3.0 + * @see excludedProviders() + */ + void setExcludedProviders( const QStringList& providers ); + + /** + * Returns the list of data providers which are excluded from the model. + * @see setExcludedProviders() + * @note added in QGIS 3.0 + */ + QStringList excludedProviders() const; + // QSortFilterProxyModel interface public: bool filterAcceptsRow( int source_row, const QModelIndex &source_parent ) const; diff --git a/python/gui/qgsmaplayercombobox.sip b/python/gui/qgsmaplayercombobox.sip index eac04bf57ef7..745e06108e1e 100644 --- a/python/gui/qgsmaplayercombobox.sip +++ b/python/gui/qgsmaplayercombobox.sip @@ -28,6 +28,20 @@ class QgsMapLayerComboBox : QComboBox //! returns the list of excepted layers QList exceptedLayerList() const; + /** + * Sets a list of data providers which should be excluded from the combobox. + * @note added in QGIS 3.0 + * @see excludedProviders() + */ + void setExcludedProviders( const QStringList& providers ); + + /** + * Returns the list of data providers which are excluded from the combobox. + * @see setExcludedProviders() + * @note added in QGIS 3.0 + */ + QStringList excludedProviders() const; + /** * Sets whether an optional empty layer ("not set") option is shown in the combo box. * @see allowEmptyLayer() diff --git a/src/core/qgsmaplayerproxymodel.cpp b/src/core/qgsmaplayerproxymodel.cpp index 6c190b4841ea..fe01ad4ecaf3 100644 --- a/src/core/qgsmaplayerproxymodel.cpp +++ b/src/core/qgsmaplayerproxymodel.cpp @@ -18,6 +18,9 @@ #include "qgsmaplayer.h" #include "qgsmaplayerregistry.h" #include "qgsvectorlayer.h" +#include "qgsrasterlayer.h" +#include "qgsvectordataprovider.h" +#include "qgsrasterdataprovider.h" QgsMapLayerProxyModel::QgsMapLayerProxyModel( QObject *parent ) : QSortFilterProxyModel( parent ) @@ -71,9 +74,15 @@ QStringList QgsMapLayerProxyModel::exceptedLayerIds() const return lst; } +void QgsMapLayerProxyModel::setExcludedProviders( const QStringList& providers ) +{ + mExcludedProviders = providers; + invalidateFilter(); +} + bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex &source_parent ) const { - if ( mFilters.testFlag( All ) && mExceptList.isEmpty() ) + if ( mFilters.testFlag( All ) && mExceptList.isEmpty() && mExcludedProviders.isEmpty() ) return true; QModelIndex index = sourceModel()->index( source_row, 0, source_parent ); @@ -90,6 +99,11 @@ bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex return false; QgsVectorLayer* vl = qobject_cast( layer ); + if ( vl && mExcludedProviders.contains( vl->dataProvider()->name() ) ) + return false; + QgsRasterLayer* rl = qobject_cast( layer ); + if ( rl && mExcludedProviders.contains( rl->dataProvider()->name() ) ) + return false; if ( mFilters.testFlag( WritableLayer ) && layer->readOnly() ) return false; diff --git a/src/core/qgsmaplayerproxymodel.h b/src/core/qgsmaplayerproxymodel.h index 6835606205d6..1a48f7bcfa01 100644 --- a/src/core/qgsmaplayerproxymodel.h +++ b/src/core/qgsmaplayerproxymodel.h @@ -80,10 +80,25 @@ class CORE_EXPORT QgsMapLayerProxyModel : public QSortFilterProxyModel //! Get the list of maplayer ids which are excluded from the list QStringList exceptedLayerIds() const; + /** + * Sets a list of data providers which should be excluded from the model. + * @note added in QGIS 3.0 + * @see excludedProviders() + */ + void setExcludedProviders( const QStringList& providers ); + + /** + * Returns the list of data providers which are excluded from the model. + * @see setExcludedProviders() + * @note added in QGIS 3.0 + */ + QStringList excludedProviders() const { return mExcludedProviders; } + private: Filters mFilters; QList mExceptList; QgsMapLayerModel* mModel; + QStringList mExcludedProviders; // QSortFilterProxyModel interface public: diff --git a/src/gui/qgsmaplayercombobox.cpp b/src/gui/qgsmaplayercombobox.cpp index 22067d1947f3..a5ca5e30021c 100644 --- a/src/gui/qgsmaplayercombobox.cpp +++ b/src/gui/qgsmaplayercombobox.cpp @@ -28,6 +28,16 @@ QgsMapLayerComboBox::QgsMapLayerComboBox( QWidget *parent ) connect( mProxyModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( rowsChanged() ) ); } +void QgsMapLayerComboBox::setExcludedProviders( const QStringList& providers ) +{ + mProxyModel->setExcludedProviders( providers ); +} + +QStringList QgsMapLayerComboBox::excludedProviders() const +{ + return mProxyModel->excludedProviders(); +} + void QgsMapLayerComboBox::setAllowEmptyLayer( bool allowEmpty ) { mProxyModel->sourceLayerModel()->setAllowEmptyLayer( allowEmpty ); diff --git a/src/gui/qgsmaplayercombobox.h b/src/gui/qgsmaplayercombobox.h index fb1f87d18053..7ff9d8829099 100644 --- a/src/gui/qgsmaplayercombobox.h +++ b/src/gui/qgsmaplayercombobox.h @@ -34,6 +34,7 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox Q_PROPERTY( QgsMapLayerProxyModel::Filters filters READ filters WRITE setFilters ) Q_PROPERTY( bool allowEmptyLayer READ allowEmptyLayer WRITE setAllowEmptyLayer ) Q_PROPERTY( bool showCrs READ showCrs WRITE setShowCrs ) + Q_PROPERTY( QStringList excludedProviders READ excludedProviders WRITE setExcludedProviders ) public: @@ -55,6 +56,20 @@ class GUI_EXPORT QgsMapLayerComboBox : public QComboBox //! returns the list of excepted layers QList exceptedLayerList() const {return mProxyModel->exceptedLayerList();} + /** + * Sets a list of data providers which should be excluded from the combobox. + * @note added in QGIS 3.0 + * @see excludedProviders() + */ + void setExcludedProviders( const QStringList& providers ); + + /** + * Returns the list of data providers which are excluded from the combobox. + * @see setExcludedProviders() + * @note added in QGIS 3.0 + */ + QStringList excludedProviders() const; + /** * Sets whether an optional empty layer ("not set") option is shown in the combo box. * @see allowEmptyLayer() From f78f2a05c6afcc4484fa8fc2e58c44d36db0e966 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 14:50:10 +1000 Subject: [PATCH 800/897] [processing] Use native QGIS map layer combobox Switches the custom map layer combo box used in the run algorithm dialog across to the standard QGIS map layer combo box --- .../processing/gui/InputLayerSelectorPanel.py | 90 -------- python/plugins/processing/gui/wrappers.py | 204 +++++++++++++----- 2 files changed, 153 insertions(+), 141 deletions(-) delete mode 100644 python/plugins/processing/gui/InputLayerSelectorPanel.py diff --git a/python/plugins/processing/gui/InputLayerSelectorPanel.py b/python/plugins/processing/gui/InputLayerSelectorPanel.py deleted file mode 100644 index 56313549d3d2..000000000000 --- a/python/plugins/processing/gui/InputLayerSelectorPanel.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - InputLayerSelectorPanel.py - --------------------- - Date : August 2012 - Copyright : (C) 2012 by Victor Olaya - Email : volayaf at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" -from builtins import str - -__author__ = 'Victor Olaya' -__date__ = 'August 2012' -__copyright__ = '(C) 2012, Victor Olaya' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -import os - -from qgis.PyQt import uic -from qgis.PyQt.QtCore import QSettings, pyqtSignal -from qgis.PyQt.QtGui import QIcon -from qgis.PyQt.QtWidgets import QFileDialog -from processing.tools import dataobjects - -pluginPath = os.path.split(os.path.dirname(__file__))[0] -WIDGET, BASE = uic.loadUiType( - os.path.join(pluginPath, 'ui', 'widgetLayerSelector.ui')) - - -class InputLayerSelectorPanel(BASE, WIDGET): - - valueChanged = pyqtSignal() - - def __init__(self, options, param): - super(InputLayerSelectorPanel, self).__init__(None) - self.setupUi(self) - - self.btnIterate.setIcon( - QIcon(os.path.join(pluginPath, 'images', 'iterate.png'))) - self.btnIterate.hide() - - self.param = param - - for (name, value) in options: - self.cmbText.addItem(name, value) - - self.btnSelect.clicked.connect(self.showSelectionDialog) - self.cmbText.currentIndexChanged.connect(self.valueChanged.emit) - - def showSelectionDialog(self): - settings = QSettings() - text = str(self.cmbText.currentText()) - if os.path.isdir(text): - path = text - elif os.path.isdir(os.path.dirname(text)): - path = os.path.dirname(text) - elif settings.contains('/Processing/LastInputPath'): - path = str(settings.value('/Processing/LastInputPath')) - else: - path = '' - - filename, selected_filter = QFileDialog.getOpenFileName(self, self.tr('Select file'), - path, self.tr('All files (*.*);;') + self.param.getFileFilter()) - if filename: - settings.setValue('/Processing/LastInputPath', - os.path.dirname(str(filename))) - filename = dataobjects.getRasterSublayer(filename, self.param) - self.cmbText.addItem(filename, filename) - self.cmbText.setCurrentIndex(self.cmbText.count() - 1) - - def update(self, options): - self.cmbText.clear() - for (name, value) in options: - self.cmbText.addItem(name, value) - self.valueChanged.emit() - - def getValue(self): - return self.cmbText.itemData(self.cmbText.currentIndex()) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 3c93bfd498db..dcf8075fc2c9 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -34,15 +34,17 @@ import os from functools import cmp_to_key -from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer, QgsApplication -from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit, QWidget, QHBoxLayout, QToolButton +from qgis.core import QgsCoordinateReferenceSystem, QgsVectorLayer, QgsApplication, QgsWkbTypes, QgsMapLayerProxyModel +from qgis.PyQt.QtWidgets import QCheckBox, QComboBox, QLineEdit, QPlainTextEdit, QWidget, QHBoxLayout, QToolButton, QFileDialog from qgis.gui import (QgsFieldExpressionWidget, QgsExpressionLineEdit, QgsProjectionSelectionWidget, QgsGenericProjectionSelector, QgsFieldComboBox, - QgsFieldProxyModel) -from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant + QgsFieldProxyModel, + QgsMapLayerComboBox + ) +from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant, QSettings from processing.gui.NumberInputPanel import NumberInputPanel, ModellerNumberInputPanel from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel @@ -156,6 +158,26 @@ def postInitialize(self, wrappers): def refresh(self): pass + def getFileName(self, initial_value=''): + """Shows a file open dialog""" + settings = QSettings() + if os.path.isdir(initial_value): + path = initial_value + elif os.path.isdir(os.path.dirname(initial_value)): + path = os.path.dirname(initial_value) + elif settings.contains('/Processing/LastInputPath'): + path = str(settings.value('/Processing/LastInputPath')) + else: + path = '' + + filename, selected_filter = QFileDialog.getOpenFileName(self.widget, self.tr('Select file'), + path, self.tr( + 'All files (*.*);;') + self.param.getFileFilter()) + if filename: + settings.setValue('/Processing/LastInputPath', + os.path.dirname(str(filename))) + return filename, selected_filter + class BasicWidgetWrapper(WidgetWrapper): @@ -534,13 +556,31 @@ class RasterWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType == DIALOG_STANDARD: - layers = dataobjects.getRasterLayers() - items = [] + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + self.combo = QgsMapLayerComboBox() + layout.addWidget(self.combo) + btn = QToolButton() + btn.setText('...') + btn.setToolTip(self.tr("Select file")) + btn.clicked.connect(self.selectFile) + layout.addWidget(btn) + + widget.setLayout(layout) if self.param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((getExtendedLayerName(layer), layer)) - return InputLayerSelectorPanel(items, self.param) + self.combo.setAllowEmptyLayer(True) + if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF): + self.combo.setShowCrs(True) + + self.combo.setFilters(QgsMapLayerProxyModel.RasterLayer) + self.combo.setExcludedProviders(['grass']) + + self.combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + self.combo.currentTextChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + return widget elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: @@ -553,14 +593,14 @@ def createWidget(self): widget.setEditText("") return widget - def refresh(self): - items = [] - layers = dataobjects.getRasterLayers() - if self.param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((getExtendedLayerName(layer), layer)) - self.widget.update(items) + def selectFile(self): + filename, selected_filter = self.getFileName(self.combo.currentText()) + if filename: + filename = dataobjects.getRasterSublayer(filename, self.param) + items = self.combo.additionalItems() + items.append(filename) + self.combo.setAdditionalItems(items) + self.combo.setCurrentIndex(self.combo.findText(filename)) def setValue(self, value): if self.dialogType == DIALOG_STANDARD: @@ -572,7 +612,14 @@ def setValue(self, value): def value(self): if self.dialogType == DIALOG_STANDARD: - return self.widget.getValue() + try: + layer = self.combo.currentLayer() + if layer: + return layer + else: + return self.combo.currentText() + except: + return self.combo.currentText() elif self.dialogType == DIALOG_BATCH: return self.widget.getText() else: @@ -615,16 +662,43 @@ class VectorWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType == DIALOG_STANDARD: - layers = dataobjects.getVectorLayers(self.param.datatype) - items = [] + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + self.combo = QgsMapLayerComboBox() + layout.addWidget(self.combo) + btn = QToolButton() + btn.setText('...') + btn.setToolTip(self.tr("Select file")) + btn.clicked.connect(self.selectFile) + layout.addWidget(btn) + + widget.setLayout(layout) + + filters = QgsMapLayerProxyModel.Filters() + if self.param.datatype == [-1] or -1 in self.param.datatype: + filters = QgsMapLayerProxyModel.HasGeometry + if QgsWkbTypes.PointGeometry in self.param.datatype: + filters |= QgsMapLayerProxyModel.PointLayer + if QgsWkbTypes.LineGeometry in self.param.datatype: + filters |= QgsMapLayerProxyModel.LineLayer + if QgsWkbTypes.PolygonGeometry in self.param.datatype: + filters |= QgsMapLayerProxyModel.PolygonLayer + if self.param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((getExtendedLayerName(layer), layer)) - widget = InputLayerSelectorPanel(items, self.param) - widget.name = self.param.name - widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + self.combo.setAllowEmptyLayer(True) + if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF): + self.combo.setShowCrs(True) + + self.combo.setFilters(filters) + self.combo.setExcludedProviders(['grass']) + + self.combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + self.combo.currentTextChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget + elif self.dialogType == DIALOG_BATCH: widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) @@ -639,18 +713,14 @@ def createWidget(self): widget.setEditText("") return widget - def _populate(self, widget): - items = [] - layers = dataobjects.getVectorLayers(self.param.datatype) - layers.sort(key=lambda lay: lay.name()) - if self.param.optional: - items.append((self.NOT_SELECTED, None)) - for layer in layers: - items.append((getExtendedLayerName(layer), layer)) - self.widget.update(items) - - def refresh(self): - self._populate(self.widget) + def selectFile(self): + filename, selected_filter = self.getFileName(self.combo.currentText()) + if filename: + filename = dataobjects.getRasterSublayer(filename, self.param) + items = self.combo.additionalItems() + items.append(filename) + self.combo.setAdditionalItems(items) + self.combo.setCurrentIndex(self.combo.findText(filename)) def setValue(self, value): if self.dialogType == DIALOG_STANDARD: @@ -663,9 +733,13 @@ def setValue(self, value): def value(self): if self.dialogType == DIALOG_STANDARD: try: - return self.widget.itemData(self.widget.currentIndex()) + layer = self.combo.currentLayer() + if layer: + return layer + else: + return self.combo.currentText() except: - return self.widget.getValue() + return self.combo.currentText() elif self.dialogType == DIALOG_BATCH: return self.widget.value() else: @@ -809,16 +883,31 @@ class TableWidgetWrapper(WidgetWrapper): def createWidget(self): if self.dialogType == DIALOG_STANDARD: - widget = QComboBox() - layers = dataobjects.getTables() - layers.sort(key=lambda lay: lay.name()) + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + self.combo = QgsMapLayerComboBox() + layout.addWidget(self.combo) + btn = QToolButton() + btn.setText('...') + btn.setToolTip(self.tr("Select file")) + btn.clicked.connect(self.selectFile) + layout.addWidget(btn) + + widget.setLayout(layout) + if self.param.optional: - widget.addItem(self.NOT_SELECTED, None) - for layer in layers: - widget.addItem(layer.name(), layer) - widget.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) - widget.name = self.param.name + self.combo.setAllowEmptyLayer(True) + + self.combo.setFilters(QgsMapLayerProxyModel.VectorLayer) + self.combo.setExcludedProviders(['grass']) + + self.combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) + self.combo.currentTextChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget + elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: @@ -833,6 +922,15 @@ def createWidget(self): widget.addItem(self.dialog.resolveValueDescription(layer), layer) return widget + def selectFile(self): + filename, selected_filter = self.getFileName(self.combo.currentText()) + if filename: + filename = dataobjects.getRasterSublayer(filename, self.param) + items = self.combo.additionalItems() + items.append(filename) + self.combo.setAdditionalItems(items) + self.combo.setCurrentIndex(self.combo.findText(filename)) + def setValue(self, value): if self.dialogType == DIALOG_STANDARD: pass # TODO @@ -844,9 +942,13 @@ def setValue(self, value): def value(self): if self.dialogType == DIALOG_STANDARD: try: - return self.widget.itemData(self.widget.currentIndex()) + layer = self.combo.currentLayer() + if layer: + return layer + else: + return self.combo.currentText() except: - return self.widget.getValue() + return self.combo.currentText() elif self.dialogType == DIALOG_BATCH: return self.widget.value() else: From fc65334a609c916f9bcab46138db51512c1995ab Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 15:28:27 +1000 Subject: [PATCH 801/897] [processing] Add file picker to vector/raster/table parameters in modeller Makes it obvious that users can set an algorithm vector/raster/ table input to a fixed table --- python/plugins/processing/gui/wrappers.py | 119 +++++++++++++++------- 1 file changed, 84 insertions(+), 35 deletions(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index dcf8075fc2c9..8d5b86ba9d5c 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -115,7 +115,7 @@ def __init__(self, param, dialog, row=0, col=0): self.setValue(param.default) def comboValue(self, validator=None, combobox=None): - if not combobox: + if combobox is None: combobox = self.widget idx = combobox.findText(combobox.currentText()) if idx < 0: @@ -132,7 +132,7 @@ def setValue(self, value): pass def setComboValue(self, value, combobox=None): - if not combobox: + if combobox is None: combobox = self.widget if isinstance(value, list): value = value[0] @@ -265,7 +265,6 @@ def createWidget(self): self.combo.setEditText(self.param.default) return widget else: - widget = QgsProjectionSelectionWidget() if self.param.optional: widget.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) @@ -584,23 +583,39 @@ def createWidget(self): elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: - widget = QComboBox() - widget.setEditable(True) - files = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) - for f in files: - widget.addItem(self.dialog.resolveValueDescription(f), f) + self.combo = QComboBox() + layers = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) + self.combo.setEditable(True) + for layer in layers: + self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) if self.param.optional: - widget.setEditText("") + self.combo.setEditText("") + + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + layout.addWidget(self.combo) + btn = QToolButton() + btn.setText('...') + btn.setToolTip(self.tr("Select file")) + btn.clicked.connect(self.selectFile) + layout.addWidget(btn) + widget.setLayout(layout) return widget def selectFile(self): filename, selected_filter = self.getFileName(self.combo.currentText()) if filename: filename = dataobjects.getRasterSublayer(filename, self.param) - items = self.combo.additionalItems() - items.append(filename) - self.combo.setAdditionalItems(items) - self.combo.setCurrentIndex(self.combo.findText(filename)) + if isinstance(self.combo, QgsMapLayerComboBox): + items = self.combo.additionalItems() + items.append(filename) + self.combo.setAdditionalItems(items) + self.combo.setCurrentIndex(self.combo.findText(filename)) + else: + self.combo.setEditText(filename) def setValue(self, value): if self.dialogType == DIALOG_STANDARD: @@ -608,7 +623,7 @@ def setValue(self, value): elif self.dialogType == DIALOG_BATCH: self.widget.setText(value) else: - self.setComboValue(value) + self.setComboValue(value, combobox=self.combo) def value(self): if self.dialogType == DIALOG_STANDARD: @@ -628,7 +643,7 @@ def validator(v): return self.param.optional else: return os.path.exists(v) - return self.comboValue(validator) + return self.comboValue(validator, combobox=self.combo) class SelectionWidgetWrapper(WidgetWrapper): @@ -704,23 +719,39 @@ def createWidget(self): widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget else: - widget = QComboBox() + self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) - widget.setEditable(True) + self.combo.setEditable(True) for layer in layers: - widget.addItem(self.dialog.resolveValueDescription(layer), layer) + self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) if self.param.optional: - widget.setEditText("") + self.combo.setEditText("") + + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + layout.addWidget(self.combo) + btn = QToolButton() + btn.setText('...') + btn.setToolTip(self.tr("Select file")) + btn.clicked.connect(self.selectFile) + layout.addWidget(btn) + widget.setLayout(layout) return widget def selectFile(self): filename, selected_filter = self.getFileName(self.combo.currentText()) if filename: filename = dataobjects.getRasterSublayer(filename, self.param) - items = self.combo.additionalItems() - items.append(filename) - self.combo.setAdditionalItems(items) - self.combo.setCurrentIndex(self.combo.findText(filename)) + if isinstance(self.combo, QgsMapLayerComboBox): + items = self.combo.additionalItems() + items.append(filename) + self.combo.setAdditionalItems(items) + self.combo.setCurrentIndex(self.combo.findText(filename)) + else: + self.combo.setEditText(filename) def setValue(self, value): if self.dialogType == DIALOG_STANDARD: @@ -728,7 +759,7 @@ def setValue(self, value): elif self.dialogType == DIALOG_BATCH: self.widget.setValue(value) else: - self.setComboValue(value) + self.setComboValue(value, combobox=self.combo) def value(self): if self.dialogType == DIALOG_STANDARD: @@ -748,7 +779,7 @@ def validator(v): return self.param.optional else: return os.path.exists(v) - return self.comboValue(validator) + return self.comboValue(validator, combobox=self.combo) class StringWidgetWrapper(WidgetWrapper): @@ -911,25 +942,43 @@ def createWidget(self): elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: - widget = QComboBox() + self.combo = QComboBox() + layers = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) + self.combo.setEditable(True) tables = self.dialog.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) if self.param.optional: - widget.addItem(self.NOT_SELECTED, None) + self.combo.addItem(self.NOT_SELECTED, None) for table in tables: - widget.addItem(self.dialog.resolveValueDescription(table), table) + self.combo.addItem(self.dialog.resolveValueDescription(table), table) for layer in layers: - widget.addItem(self.dialog.resolveValueDescription(layer), layer) + self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) + + widget = QWidget() + layout = QHBoxLayout() + layout.setMargin(0) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + layout.addWidget(self.combo) + btn = QToolButton() + btn.setText('...') + btn.setToolTip(self.tr("Select file")) + btn.clicked.connect(self.selectFile) + layout.addWidget(btn) + widget.setLayout(layout) return widget def selectFile(self): filename, selected_filter = self.getFileName(self.combo.currentText()) if filename: filename = dataobjects.getRasterSublayer(filename, self.param) - items = self.combo.additionalItems() - items.append(filename) - self.combo.setAdditionalItems(items) - self.combo.setCurrentIndex(self.combo.findText(filename)) + if isinstance(self.combo, QgsMapLayerComboBox): + items = self.combo.additionalItems() + items.append(filename) + self.combo.setAdditionalItems(items) + self.combo.setCurrentIndex(self.combo.findText(filename)) + else: + self.combo.setEditText(filename) def setValue(self, value): if self.dialogType == DIALOG_STANDARD: @@ -937,7 +986,7 @@ def setValue(self, value): elif self.dialogType == DIALOG_BATCH: return self.widget.setText(value) else: - self.setComboValue(value) + self.setComboValue(value, combobox=self.combo) def value(self): if self.dialogType == DIALOG_STANDARD: @@ -954,7 +1003,7 @@ def value(self): else: def validator(v): return bool(v) or self.param.optional - return self.comboValue(validator) + return self.comboValue(validator, combobox=self.combo) class TableFieldWidgetWrapper(WidgetWrapper): From 1da400a99de1d8fec1eba454d25cd0736e2d28d3 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 16:41:20 +1000 Subject: [PATCH 802/897] Rename enum values for consistency --- python/core/qgsmaplayermodel.sip | 4 +-- src/core/qgsmaplayermodel.cpp | 4 +-- src/core/qgsmaplayermodel.h | 4 +-- src/core/qgsmaplayerproxymodel.cpp | 12 ++++----- tests/src/python/test_qgsmaplayermodel.py | 30 +++++++++++------------ 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/python/core/qgsmaplayermodel.sip b/python/core/qgsmaplayermodel.sip index b11249bf4530..88ca2914330c 100644 --- a/python/core/qgsmaplayermodel.sip +++ b/python/core/qgsmaplayermodel.sip @@ -19,8 +19,8 @@ class QgsMapLayerModel : QAbstractItemModel { LayerIdRole, /*!< Stores the map layer ID */ LayerRole, /*!< Stores pointer to the map layer itself */ - IsEmptyRole, //!< True if index corresponds to the empty (not set) value - IsAdditionalRole, //!< True if index corresponds to an additional (non map layer) item + EmptyRole, //!< True if index corresponds to the empty (not set) value + AdditionalRole, //!< True if index corresponds to an additional (non map layer) item }; /** diff --git a/src/core/qgsmaplayermodel.cpp b/src/core/qgsmaplayermodel.cpp index 8ac27ef278e1..e205b1515be1 100644 --- a/src/core/qgsmaplayermodel.cpp +++ b/src/core/qgsmaplayermodel.cpp @@ -257,10 +257,10 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const return QVariant::fromValue( static_cast( index.internalPointer() ) ); } - if ( role == IsEmptyRole ) + if ( role == EmptyRole ) return isEmpty; - if ( role == IsAdditionalRole ) + if ( role == AdditionalRole ) return additionalIndex >= 0; if ( role == Qt::CheckStateRole && mItemCheckable ) diff --git a/src/core/qgsmaplayermodel.h b/src/core/qgsmaplayermodel.h index ec7ff07cc983..e85f83d034d3 100644 --- a/src/core/qgsmaplayermodel.h +++ b/src/core/qgsmaplayermodel.h @@ -45,8 +45,8 @@ class CORE_EXPORT QgsMapLayerModel : public QAbstractItemModel { LayerIdRole = Qt::UserRole + 1, //!< Stores the map layer ID LayerRole, //!< Stores pointer to the map layer itself - IsEmptyRole, //!< True if index corresponds to the empty (not set) value - IsAdditionalRole, //!< True if index corresponds to an additional (non map layer) item + EmptyRole, //!< True if index corresponds to the empty (not set) value + AdditionalRole, //!< True if index corresponds to an additional (non map layer) item }; /** diff --git a/src/core/qgsmaplayerproxymodel.cpp b/src/core/qgsmaplayerproxymodel.cpp index fe01ad4ecaf3..0bc93e144975 100644 --- a/src/core/qgsmaplayerproxymodel.cpp +++ b/src/core/qgsmaplayerproxymodel.cpp @@ -87,8 +87,8 @@ bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex QModelIndex index = sourceModel()->index( source_row, 0, source_parent ); - if ( sourceModel()->data( index, QgsMapLayerModel::IsEmptyRole ).toBool() - || sourceModel()->data( index, QgsMapLayerModel::IsAdditionalRole ).toBool() ) + if ( sourceModel()->data( index, QgsMapLayerModel::EmptyRole ).toBool() + || sourceModel()->data( index, QgsMapLayerModel::AdditionalRole ).toBool() ) return true; QgsMapLayer* layer = static_cast( index.internalPointer() ); @@ -143,14 +143,14 @@ bool QgsMapLayerProxyModel::filterAcceptsRow( int source_row, const QModelIndex bool QgsMapLayerProxyModel::lessThan( const QModelIndex &left, const QModelIndex &right ) const { // empty row is always first - if ( sourceModel()->data( left, QgsMapLayerModel::IsEmptyRole ).toBool() ) + if ( sourceModel()->data( left, QgsMapLayerModel::EmptyRole ).toBool() ) return true; - else if ( sourceModel()->data( right, QgsMapLayerModel::IsEmptyRole ).toBool() ) + else if ( sourceModel()->data( right, QgsMapLayerModel::EmptyRole ).toBool() ) return false; // additional rows are always last - bool leftAdditional = sourceModel()->data( left, QgsMapLayerModel::IsAdditionalRole ).toBool(); - bool rightAdditional = sourceModel()->data( right, QgsMapLayerModel::IsAdditionalRole ).toBool(); + bool leftAdditional = sourceModel()->data( left, QgsMapLayerModel::AdditionalRole ).toBool(); + bool rightAdditional = sourceModel()->data( right, QgsMapLayerModel::AdditionalRole ).toBool(); if ( leftAdditional && !rightAdditional ) return false; diff --git a/tests/src/python/test_qgsmaplayermodel.py b/tests/src/python/test_qgsmaplayermodel.py index dbe421cb3c5f..91edee046097 100644 --- a/tests/src/python/test_qgsmaplayermodel.py +++ b/tests/src/python/test_qgsmaplayermodel.py @@ -242,15 +242,15 @@ def testIsEmptyRole(self): l2 = create_layer('l2') QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) m = QgsMapLayerModel() - self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsEmptyRole)) - self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsEmptyRole)) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.EmptyRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.EmptyRole)) m.setAllowEmptyLayer(True) - self.assertTrue(m.data(m.index(0, 0), QgsMapLayerModel.IsEmptyRole)) - self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsEmptyRole)) - self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsEmptyRole)) + self.assertTrue(m.data(m.index(0, 0), QgsMapLayerModel.EmptyRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.EmptyRole)) + self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.EmptyRole)) m.setAdditionalItems(['a']) - self.assertFalse(m.data(m.index(3, 0), QgsMapLayerModel.IsEmptyRole)) + self.assertFalse(m.data(m.index(3, 0), QgsMapLayerModel.EmptyRole)) QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) @@ -259,18 +259,18 @@ def testIsAdditionalRole(self): l2 = create_layer('l2') QgsMapLayerRegistry.instance().addMapLayers([l1, l2]) m = QgsMapLayerModel() - self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsAdditionalRole)) - self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.AdditionalRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.AdditionalRole)) m.setAllowEmptyLayer(True) - self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsAdditionalRole)) - self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsAdditionalRole)) - self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.AdditionalRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.AdditionalRole)) + self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.AdditionalRole)) m.setAdditionalItems(['a']) - self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.IsAdditionalRole)) - self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.IsAdditionalRole)) - self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.IsAdditionalRole)) - self.assertTrue(m.data(m.index(3, 0), QgsMapLayerModel.IsAdditionalRole)) + self.assertFalse(m.data(m.index(0, 0), QgsMapLayerModel.AdditionalRole)) + self.assertFalse(m.data(m.index(1, 0), QgsMapLayerModel.AdditionalRole)) + self.assertFalse(m.data(m.index(2, 0), QgsMapLayerModel.AdditionalRole)) + self.assertTrue(m.data(m.index(3, 0), QgsMapLayerModel.AdditionalRole)) QgsMapLayerRegistry.instance().removeMapLayers([l1.id(), l2.id()]) From 089b663996b95f5205f55bd1b061b299914f170a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 21:00:48 +1000 Subject: [PATCH 803/897] Show layer path tooltips in QgsMapLayerComboBox Handy for differentiating between multiple layers with the same name --- src/core/qgsmaplayermodel.cpp | 181 +++++++++++++++++++--------------- 1 file changed, 102 insertions(+), 79 deletions(-) diff --git a/src/core/qgsmaplayermodel.cpp b/src/core/qgsmaplayermodel.cpp index e205b1515be1..e15b6a157ad9 100644 --- a/src/core/qgsmaplayermodel.cpp +++ b/src/core/qgsmaplayermodel.cpp @@ -218,114 +218,137 @@ QVariant QgsMapLayerModel::data( const QModelIndex &index, int role ) const bool isEmpty = index.row() == 0 && mAllowEmpty; int additionalIndex = index.row() - ( mAllowEmpty ? 1 : 0 ) - mLayers.count(); - if ( role == Qt::DisplayRole ) + switch ( role ) { - if ( index.row() == 0 && mAllowEmpty ) - return QVariant(); + case Qt::DisplayRole: + { + if ( index.row() == 0 && mAllowEmpty ) + return QVariant(); - if ( additionalIndex >= 0 ) - return mAdditionalItems.at( additionalIndex ); + if ( additionalIndex >= 0 ) + return mAdditionalItems.at( additionalIndex ); - QgsMapLayer* layer = static_cast( index.internalPointer() ); - if ( !layer ) - return QVariant(); + QgsMapLayer* layer = static_cast( index.internalPointer() ); + if ( !layer ) + return QVariant(); - if ( !mShowCrs ) - { - return layer->name(); - } - else - { - return tr( "%1 [%2]" ).arg( layer->name(), layer->crs().authid() ); + if ( !mShowCrs ) + { + return layer->name(); + } + else + { + return tr( "%1 [%2]" ).arg( layer->name(), layer->crs().authid() ); + } } - } - if ( role == LayerIdRole ) - { - if ( isEmpty || additionalIndex >= 0 ) - return QVariant(); + case LayerIdRole: + { + if ( isEmpty || additionalIndex >= 0 ) + return QVariant(); - QgsMapLayer* layer = static_cast( index.internalPointer() ); - return layer ? layer->id() : QVariant(); - } + QgsMapLayer* layer = static_cast( index.internalPointer() ); + return layer ? layer->id() : QVariant(); + } - if ( role == LayerRole ) - { - if ( isEmpty || additionalIndex >= 0 ) - return QVariant(); + case LayerRole: + { + if ( isEmpty || additionalIndex >= 0 ) + return QVariant(); - return QVariant::fromValue( static_cast( index.internalPointer() ) ); - } + return QVariant::fromValue( static_cast( index.internalPointer() ) ); + } - if ( role == EmptyRole ) - return isEmpty; + case EmptyRole: + return isEmpty; - if ( role == AdditionalRole ) - return additionalIndex >= 0; + case AdditionalRole: + return additionalIndex >= 0; - if ( role == Qt::CheckStateRole && mItemCheckable ) - { - if ( isEmpty || additionalIndex >= 0 ) - return QVariant(); + case Qt::CheckStateRole: + { + if ( mItemCheckable ) + { + if ( isEmpty || additionalIndex >= 0 ) + return QVariant(); - QgsMapLayer* layer = static_cast( index.internalPointer() ); - return layer ? mLayersChecked[layer->id()] : QVariant(); - } + QgsMapLayer* layer = static_cast( index.internalPointer() ); + return layer ? mLayersChecked[layer->id()] : QVariant(); + } - if ( role == Qt::DecorationRole ) - { - if ( isEmpty || additionalIndex >= 0 ) return QVariant(); + } - QgsMapLayer* layer = static_cast( index.internalPointer() ); - if ( !layer ) + case Qt::ToolTipRole: + { + QgsMapLayer* layer = static_cast( index.internalPointer() ); + if ( layer ) + { + QString tooltip = "" + + ( layer->title().isEmpty() ? layer->shortName() : layer->title() ) + ""; + if ( !layer->abstract().isEmpty() ) + tooltip += "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + layer->abstract().replace( QLatin1String( "\n" ), QLatin1String( "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " ) ); + tooltip += "
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  " + layer->publicSource() + ""; + return tooltip; + } return QVariant(); + } - QgsMapLayer::LayerType type = layer->type(); - if ( role == Qt::DecorationRole ) + case Qt::DecorationRole: { - switch ( type ) - { - case QgsMapLayer::RasterLayer: - { - return QgsLayerItem::iconRaster(); - } + if ( isEmpty || additionalIndex >= 0 ) + return QVariant(); - case QgsMapLayer::VectorLayer: + QgsMapLayer* layer = static_cast( index.internalPointer() ); + if ( !layer ) + return QVariant(); + + QgsMapLayer::LayerType type = layer->type(); + if ( role == Qt::DecorationRole ) + { + switch ( type ) { - QgsVectorLayer* vl = dynamic_cast( layer ); - if ( !vl ) + case QgsMapLayer::RasterLayer: { - return QIcon(); + return QgsLayerItem::iconRaster(); } - QgsWkbTypes::GeometryType geomType = vl->geometryType(); - switch ( geomType ) + + case QgsMapLayer::VectorLayer: { - case QgsWkbTypes::PointGeometry: - { - return QgsLayerItem::iconPoint(); - } - case QgsWkbTypes::PolygonGeometry : - { - return QgsLayerItem::iconPolygon(); - } - case QgsWkbTypes::LineGeometry : - { - return QgsLayerItem::iconLine(); - } - case QgsWkbTypes::NullGeometry : + QgsVectorLayer* vl = dynamic_cast( layer ); + if ( !vl ) { - return QgsLayerItem::iconTable(); + return QIcon(); } - default: + QgsWkbTypes::GeometryType geomType = vl->geometryType(); + switch ( geomType ) { - return QIcon(); + case QgsWkbTypes::PointGeometry: + { + return QgsLayerItem::iconPoint(); + } + case QgsWkbTypes::PolygonGeometry : + { + return QgsLayerItem::iconPolygon(); + } + case QgsWkbTypes::LineGeometry : + { + return QgsLayerItem::iconLine(); + } + case QgsWkbTypes::NullGeometry : + { + return QgsLayerItem::iconTable(); + } + default: + { + return QIcon(); + } } } - } - default: - { - return QIcon(); + default: + { + return QIcon(); + } } } } From 964ecfd743059aa8e64ca5ab5843a770eec68969 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 17 Nov 2016 08:31:36 +1000 Subject: [PATCH 804/897] Fix build --- python/plugins/processing/gui/wrappers.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 8d5b86ba9d5c..30b09c7cc5a2 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -47,7 +47,6 @@ from qgis.PyQt.QtCore import pyqtSignal, QObject, QVariant, QSettings from processing.gui.NumberInputPanel import NumberInputPanel, ModellerNumberInputPanel -from processing.gui.InputLayerSelectorPanel import InputLayerSelectorPanel from processing.modeler.MultilineTextPanel import MultilineTextPanel from processing.gui.PointSelectionPanel import PointSelectionPanel from processing.core.parameters import (ParameterBoolean, From fb8b931a8e31c449a5484ce169c4fc0b1b169ff3 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 17 Nov 2016 12:48:20 +1000 Subject: [PATCH 805/897] [processing] Fix error with field widget wrapper --- python/plugins/processing/gui/wrappers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/gui/wrappers.py b/python/plugins/processing/gui/wrappers.py index 30b09c7cc5a2..4a31bcfffe1b 100644 --- a/python/plugins/processing/gui/wrappers.py +++ b/python/plugins/processing/gui/wrappers.py @@ -1093,7 +1093,7 @@ def value(self): if self.param.multiple: return [self.widget.options[i] for i in self.widget.selectedoptions] else: - f = self.widget.field() + f = self.widget.currentField() if self.param.optional and not f: return None return f From 24ffa15ecf1aa20ef389fad1f0aaf6f235b712da Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Thu, 17 Nov 2016 12:48:39 +1000 Subject: [PATCH 806/897] [FEATURE][processing] Extract by attribute can extract for null/notnull values Adds support for filtering where an attribute value is null or not null --- .../algs/qgis/ExtractByAttribute.py | 41 ++++++----- .../algs/qgis/ExtractByExpression.py | 1 + .../processing/algs/qgis/ExtractByLocation.py | 2 + .../extract_by_attribute_contains.gfs | 32 +++++++++ .../extract_by_attribute_contains.gml | 37 ++++++++++ .../expected/extract_by_attribute_greater.gfs | 32 +++++++++ .../expected/extract_by_attribute_greater.gml | 30 ++++++++ .../extract_by_attribute_not_null.gfs | 32 +++++++++ .../extract_by_attribute_not_null.gml | 51 ++++++++++++++ .../expected/extract_by_attribute_null.gfs | 27 +++++++ .../expected/extract_by_attribute_null.gml | 21 ++++++ .../extract_by_attribute_startswith.gfs | 32 +++++++++ .../extract_by_attribute_startswith.gml | 29 ++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 70 +++++++++++++++++++ 14 files changed, 419 insertions(+), 18 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gml create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gml create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gml create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gml create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gml diff --git a/python/plugins/processing/algs/qgis/ExtractByAttribute.py b/python/plugins/processing/algs/qgis/ExtractByAttribute.py index 660b1cfbcc66..f81e1443f789 100644 --- a/python/plugins/processing/algs/qgis/ExtractByAttribute.py +++ b/python/plugins/processing/algs/qgis/ExtractByAttribute.py @@ -51,12 +51,17 @@ class ExtractByAttribute(GeoAlgorithm): '<', '<=', 'begins with', - 'contains' + 'contains', + 'is null', + 'is not null' ] + STRING_OPERATORS = ['begins with', + 'contains'] def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Extract by attribute') self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') + self.tags = self.tr('extract,filter,attribute,value,contains,null,field') self.i18n_operators = ['=', '!=', @@ -65,7 +70,9 @@ def defineCharacteristics(self): '<', '<=', self.tr('begins with'), - self.tr('contains')] + self.tr('contains'), + self.tr('is null'), + self.tr('is not null')] self.addParameter(ParameterVector(self.INPUT, self.tr('Input Layer'))) @@ -73,7 +80,7 @@ def defineCharacteristics(self): self.tr('Selection attribute'), self.INPUT)) self.addParameter(ParameterSelection(self.OPERATOR, self.tr('Operator'), self.i18n_operators)) - self.addParameter(ParameterString(self.VALUE, self.tr('Value'))) + self.addParameter(ParameterString(self.VALUE, self.tr('Value'), optional=True)) self.addOutput(OutputVector(self.OUTPUT, self.tr('Extracted (attribute)'))) @@ -90,25 +97,23 @@ def processAlgorithm(self, progress): idx = layer.fields().lookupField(fieldName) fieldType = fields[idx].type() - if fieldType != QVariant.String and operator in self.OPERATORS[-2:]: - op = ''.join(['"%s", ' % o for o in self.OPERATORS[-2:]]) + if fieldType != QVariant.String and operator in self.STRING_OPERATORS: + op = ''.join(['"%s", ' % o for o in self.STRING_OPERATORS]) raise GeoAlgorithmExecutionException( self.tr('Operators %s can be used only with string fields.' % op)) - if fieldType in [QVariant.Int, QVariant.Double, QVariant.UInt, QVariant.LongLong, QVariant.ULongLong]: - expr = '"%s" %s %s' % (fieldName, operator, value) - elif fieldType == QVariant.String: - if operator not in self.OPERATORS[-2:]: - expr = """"%s" %s '%s'""" % (fieldName, operator, value) - elif operator == 'begins with': - expr = """"%s" LIKE '%s%%'""" % (fieldName, value) - elif operator == 'contains': - expr = """"%s" LIKE '%%%s%%'""" % (fieldName, value) - elif fieldType in [QVariant.Date, QVariant.DateTime]: - expr = """"%s" %s '%s'""" % (fieldName, operator, value) + field_ref = QgsExpression.quotedColumnRef(fieldName) + quoted_val = QgsExpression.quotedValue(value) + if operator == 'is null': + expr = '{} IS NULL'.format(field_ref) + elif operator == 'is not null': + expr = '{} IS NOT NULL'.format(field_ref) + elif operator == 'begins with': + expr = """%s LIKE '%s%%'""" % (field_ref, value) + elif operator == 'contains': + expr = """%s LIKE '%%%s%%'""" % (field_ref, value) else: - raise GeoAlgorithmExecutionException( - self.tr('Unsupported field type "%s"' % fields[idx].typeName())) + expr = '{} {} {}'.format(field_ref, operator, quoted_val) expression = QgsExpression(expr) if not expression.hasParserError(): diff --git a/python/plugins/processing/algs/qgis/ExtractByExpression.py b/python/plugins/processing/algs/qgis/ExtractByExpression.py index 6895ac51ff4e..0c3b4c40daea 100644 --- a/python/plugins/processing/algs/qgis/ExtractByExpression.py +++ b/python/plugins/processing/algs/qgis/ExtractByExpression.py @@ -43,6 +43,7 @@ class ExtractByExpression(GeoAlgorithm): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Extract by expression') self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') + self.tags = self.tr('extract,filter,expression,field') self.addParameter(ParameterVector(self.INPUT, self.tr('Input Layer'))) diff --git a/python/plugins/processing/algs/qgis/ExtractByLocation.py b/python/plugins/processing/algs/qgis/ExtractByLocation.py index c3d96f8a6c42..688e977d2133 100644 --- a/python/plugins/processing/algs/qgis/ExtractByLocation.py +++ b/python/plugins/processing/algs/qgis/ExtractByLocation.py @@ -46,6 +46,8 @@ class ExtractByLocation(GeoAlgorithm): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Extract by location') self.group, self.i18n_group = self.trAlgorithm('Vector selection tools') + self.tags = self.tr('extract,filter,location,intersects,contains,within') + self.addParameter(ParameterVector(self.INPUT, self.tr('Layer to select from'))) self.addParameter(ParameterVector(self.INTERSECT, diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gfs b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gfs new file mode 100644 index 000000000000..d9e8f0a18095 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gfs @@ -0,0 +1,32 @@ + + + extract_by_attribute_contains + extract_by_attribute_contains + + 3 + EPSG:4326 + + 3 + -1.00000 + 6.00000 + -1.00000 + 6.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gml b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gml new file mode 100644 index 000000000000..2d75025ec1e9 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_contains.gml @@ -0,0 +1,37 @@ + + + + + -1-1 + 66 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.123456 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.123 + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gfs b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gfs new file mode 100644 index 000000000000..555a28800a16 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gfs @@ -0,0 +1,32 @@ + + + extract_by_attribute_greater + extract_by_attribute_greater + + 3 + EPSG:4326 + + 2 + -1.00000 + 6.00000 + -3.00000 + 3.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gml b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gml new file mode 100644 index 000000000000..2ae749172fd0 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_greater.gml @@ -0,0 +1,30 @@ + + + + + -1-3 + 63 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.123456 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 2 + 3.33 + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gfs b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gfs new file mode 100644 index 000000000000..7be84fd9d73d --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gfs @@ -0,0 +1,32 @@ + + + extract_by_expression_not_null + extract_by_expression_not_null + + 3 + EPSG:4326 + + 5 + -1.00000 + 10.00000 + -3.00000 + 5.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gml b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gml new file mode 100644 index 000000000000..cbbc26ab75a2 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_not_null.gml @@ -0,0 +1,51 @@ + + + + + -1-3 + 105 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.123456 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + ASDF + 0 + + + + + 120 + -100291.43213 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 2 + 3.33 + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gfs b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gfs new file mode 100644 index 000000000000..4db329035f81 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gfs @@ -0,0 +1,27 @@ + + + extract_by_expression_null + extract_by_expression_null + + 3 + EPSG:4326 + + 1 + 2.00000 + 3.00000 + 5.00000 + 6.00000 + + + name + name + String + 5 + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gml b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gml new file mode 100644 index 000000000000..4a398398bde5 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_null.gml @@ -0,0 +1,21 @@ + + + + + 25 + 36 + + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.123 + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gfs b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gfs new file mode 100644 index 000000000000..5bea74ff2125 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gfs @@ -0,0 +1,32 @@ + + + extract_by_expression_startswith + extract_by_expression_startswith + + 3 + EPSG:4326 + + 2 + 4.00000 + 10.00000 + -3.00000 + 5.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Integer + + + diff --git a/python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gml b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gml new file mode 100644 index 000000000000..f328646d5843 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/extract_by_attribute_startswith.gml @@ -0,0 +1,29 @@ + + + + + 4-3 + 105 + + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + ASDF + 0 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 5c7d77613a70..d228d83733fc 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1475,3 +1475,73 @@ tests: OUTPUT_LAYER: name: expected/pole_inaccessibility_polys.gml type: vector + + - algorithm: qgis:extractbyattribute + name: Extract by attribute (is null) + params: + FIELD: intval + INPUT: + name: polys.gml + type: vector + OPERATOR: '8' + results: + OUTPUT: + name: expected/extract_by_attribute_null.gml + type: vector + + - algorithm: qgis:extractbyattribute + name: Extract by attribute (is not null) + params: + FIELD: intval + INPUT: + name: polys.gml + type: vector + OPERATOR: '9' + results: + OUTPUT: + name: expected/extract_by_attribute_not_null.gml + type: vector + + - algorithm: qgis:extractbyattribute + name: Extract by attribute (starts with) + params: + FIELD: name + INPUT: + name: polys.gml + type: vector + OPERATOR: '6' + VALUE: A + results: + OUTPUT: + name: expected/extract_by_attribute_startswith.gml + type: vector + + - algorithm: qgis:extractbyattribute + name: Extract by attribute (contains) + params: + FIELD: name + INPUT: + name: polys.gml + type: vector + OPERATOR: '7' + VALUE: aaa + results: + OUTPUT: + name: expected/extract_by_attribute_contains.gml + type: vector + + - algorithm: qgis:extractbyattribute + name: Extract by attribute (greater) + params: + FIELD: floatval + INPUT: + name: polys.gml + type: vector + OPERATOR: '2' + VALUE: '1' + results: + OUTPUT: + name: expected/extract_by_attribute_greater.gml + type: vector + + From a8a05ba7513e2ce703a83e45643dc6345f1ee3ab Mon Sep 17 00:00:00 2001 From: nirvn Date: Thu, 17 Nov 2016 11:43:53 +0700 Subject: [PATCH 807/897] [symbology] add padding value for symbol/coloramp preview --- doc/api_break.dox | 1 + .../core/symbology-ng/qgssymbollayerutils.sip | 37 ++++++++++++++++--- .../layertree/qgslayertreemodellegendnode.cpp | 6 +-- src/core/symbology-ng/qgssymbollayerutils.cpp | 28 ++++++++++---- src/core/symbology-ng/qgssymbollayerutils.h | 29 +++++++++++---- .../symbology-ng/qgsstylemanagerdialog.cpp | 17 ++------- src/gui/symbology-ng/qgssymbolslistwidget.cpp | 2 +- src/ui/symbollayer/widget_symbolslist.ui | 4 +- 8 files changed, 84 insertions(+), 40 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 0394a62b1130..190f1b947fce 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1423,6 +1423,7 @@ QgsSymbolLayerUtils (renamed from QgsSymbolLayerUtilsV2) {#qgis_api_break - encodeOutputUnit() and decodeOutputUnit() were removed. QgsUnitTypes::encodeUnit() and QgsUnitTypes::decodeRenderUnit() should be used instead. - The signatures for wellKnownMarkerToSld() and wellKnownMarkerFromSld() were changed. +- The symbolPreviewPixmap() customContext is now the fourth parameter QgsSymbolSelectorWidget {#qgis_api_break_3_0_QgsSymbolSelectorWidget} diff --git a/python/core/symbology-ng/qgssymbollayerutils.sip b/python/core/symbology-ng/qgssymbollayerutils.sip index f43c206dde89..12f432519dde 100644 --- a/python/core/symbology-ng/qgssymbollayerutils.sip +++ b/python/core/symbology-ng/qgssymbollayerutils.sip @@ -95,7 +95,23 @@ class QgsSymbolLayerUtils static QPainter::CompositionMode decodeBlendMode( const QString& s ); - static QIcon symbolPreviewIcon( QgsSymbol* symbol, QSize size ); + /** Returns an icon preview for a color ramp. + * @param symbol symbol + * @param size target pixmap size + * @param padding space between icon edge and symbol + * @see symbolPreviewPixmap() + */ + static QIcon symbolPreviewIcon( QgsSymbol* symbol, QSize size, int padding = 0 ); + + /** Returns a pixmap preview for a color ramp. + * @param symbol symbol + * @param size target pixmap size + * @param padding space between icon edge and symbol + * @param customContext render context to use when rendering symbol + * @note customContext parameter added in 2.6 + * @see symbolPreviewIcon() + */ + static QPixmap symbolPreviewPixmap( QgsSymbol* symbol, QSize size, int padding = 0, QgsRenderContext* customContext = 0 ); /** Draws a symbol layer preview to a QPicture * @param layer symbol layer to draw @@ -118,14 +134,23 @@ class QgsSymbolLayerUtils */ static QIcon symbolLayerPreviewIcon( QgsSymbolLayer* layer, QgsUnitTypes::RenderUnit u, QSize size, const QgsMapUnitScale& scale = QgsMapUnitScale() ); - static QIcon colorRampPreviewIcon( QgsColorRamp* ramp, QSize size ); + /** Returns a icon preview for a color ramp. + * @param ramp color ramp + * @param size target icon size + * @param padding space between icon edge and symbol + * @see colorRampPreviewPixmap() + */ + static QIcon colorRampPreviewIcon( QgsColorRamp* ramp, QSize size, int padding = 0 ); + /** Returns a pixmap preview for a color ramp. + * @param ramp color ramp + * @param size target pixmap size + * @param padding space between icon edge and symbol + * @see colorRampPreviewIcon() + */ + static QPixmap colorRampPreviewPixmap( QgsColorRamp* ramp, QSize size, int padding = 0 ); static void drawStippledBackground( QPainter* painter, QRect rect ); - //! @note customContext parameter added in 2.6 - static QPixmap symbolPreviewPixmap( QgsSymbol* symbol, QSize size, QgsRenderContext* customContext = 0 ); - static QPixmap colorRampPreviewPixmap( QgsColorRamp* ramp, QSize size ); - /** Returns the maximum estimated bleed for the symbol */ static double estimateMaxSymbolBleed( QgsSymbol* symbol ); diff --git a/src/core/layertree/qgslayertreemodellegendnode.cpp b/src/core/layertree/qgslayertreemodellegendnode.cpp index 93ca467c6678..4dada79f818a 100644 --- a/src/core/layertree/qgslayertreemodellegendnode.cpp +++ b/src/core/layertree/qgslayertreemodellegendnode.cpp @@ -168,7 +168,7 @@ QSize QgsSymbolLegendNode::minimumIconSize( QgsRenderContext* context ) const if ( mItem.symbol() && mItem.symbol()->type() == QgsSymbol::Marker ) { minSz = QgsImageOperation::nonTransparentImageRect( - QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( 512, 512 ), + QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( 512, 512 ), 0, context ).toImage(), minSz, true ).size(); @@ -176,7 +176,7 @@ QSize QgsSymbolLegendNode::minimumIconSize( QgsRenderContext* context ) const else if ( mItem.symbol() && mItem.symbol()->type() == QgsSymbol::Line ) { minSz = QgsImageOperation::nonTransparentImageRect( - QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( minSz.width(), 512 ), + QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), QSize( minSz.width(), 512 ), 0, context ).toImage(), minSz, true ).size(); @@ -273,7 +273,7 @@ QVariant QgsSymbolLegendNode::data( int role ) const if ( mItem.symbol() ) { QScopedPointer context( createTemporaryRenderContext() ); - pix = QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), mIconSize, context.data() ); + pix = QgsSymbolLayerUtils::symbolPreviewPixmap( mItem.symbol(), mIconSize, 0, context.data() ); } else { diff --git a/src/core/symbology-ng/qgssymbollayerutils.cpp b/src/core/symbology-ng/qgssymbollayerutils.cpp index 2f901a38745f..c9428d75b48f 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.cpp +++ b/src/core/symbology-ng/qgssymbollayerutils.cpp @@ -574,12 +574,12 @@ QPainter::CompositionMode QgsSymbolLayerUtils::decodeBlendMode( const QString &s return QPainter::CompositionMode_SourceOver; // "Normal" } -QIcon QgsSymbolLayerUtils::symbolPreviewIcon( QgsSymbol* symbol, QSize size ) +QIcon QgsSymbolLayerUtils::symbolPreviewIcon( QgsSymbol* symbol, QSize size, int padding ) { - return QIcon( symbolPreviewPixmap( symbol, size ) ); + return QIcon( symbolPreviewPixmap( symbol, size, padding ) ); } -QPixmap QgsSymbolLayerUtils::symbolPreviewPixmap( QgsSymbol* symbol, QSize size, QgsRenderContext* customContext ) +QPixmap QgsSymbolLayerUtils::symbolPreviewPixmap( QgsSymbol* symbol, QSize size, int padding, QgsRenderContext* customContext ) { Q_ASSERT( symbol ); @@ -588,9 +588,21 @@ QPixmap QgsSymbolLayerUtils::symbolPreviewPixmap( QgsSymbol* symbol, QSize size, QPainter painter; painter.begin( &pixmap ); painter.setRenderHint( QPainter::Antialiasing ); + if ( customContext ) + { customContext->setPainter( &painter ); + } + + if ( padding > 0 ) + { + size.setWidth( size.rwidth() - ( padding * 2 ) ); + size.setHeight( size.rheight() - ( padding * 2 ) ); + painter.translate( padding, padding ); + } + symbol->drawPreviewIcon( &painter, size, customContext ); + painter.end(); return pixmap; } @@ -636,12 +648,12 @@ QIcon QgsSymbolLayerUtils::symbolLayerPreviewIcon( QgsSymbolLayer* layer, QgsUni return QIcon( pixmap ); } -QIcon QgsSymbolLayerUtils::colorRampPreviewIcon( QgsColorRamp* ramp, QSize size ) +QIcon QgsSymbolLayerUtils::colorRampPreviewIcon( QgsColorRamp* ramp, QSize size, int padding ) { - return QIcon( colorRampPreviewPixmap( ramp, size ) ); + return QIcon( colorRampPreviewPixmap( ramp, size, padding ) ); } -QPixmap QgsSymbolLayerUtils::colorRampPreviewPixmap( QgsColorRamp* ramp, QSize size ) +QPixmap QgsSymbolLayerUtils::colorRampPreviewPixmap( QgsColorRamp* ramp, QSize size, int padding ) { QPixmap pixmap( size ); pixmap.fill( Qt::transparent ); @@ -650,7 +662,7 @@ QPixmap QgsSymbolLayerUtils::colorRampPreviewPixmap( QgsColorRamp* ramp, QSize s painter.begin( &pixmap ); //draw stippled background, for transparent images - drawStippledBackground( &painter, QRect( 0, 0, size.width(), size.height() ) ); + drawStippledBackground( &painter, QRect( padding, padding, size.width() - padding * 2, size.height() - padding * 2 ) ); // antialising makes the colors duller, and no point in antialiasing a color ramp // painter.setRenderHint( QPainter::Antialiasing ); @@ -658,7 +670,7 @@ QPixmap QgsSymbolLayerUtils::colorRampPreviewPixmap( QgsColorRamp* ramp, QSize s { QPen pen( ramp->color( static_cast< double >( i ) / size.width() ) ); painter.setPen( pen ); - painter.drawLine( i, 0, i, size.height() - 1 ); + painter.drawLine( i, 0 + padding, i, size.height() - 1 - padding ); } painter.end(); return pixmap; diff --git a/src/core/symbology-ng/qgssymbollayerutils.h b/src/core/symbology-ng/qgssymbollayerutils.h index 7387770c0bdf..495344ff95db 100644 --- a/src/core/symbology-ng/qgssymbollayerutils.h +++ b/src/core/symbology-ng/qgssymbollayerutils.h @@ -138,7 +138,23 @@ class CORE_EXPORT QgsSymbolLayerUtils static QPainter::CompositionMode decodeBlendMode( const QString& s ); - static QIcon symbolPreviewIcon( QgsSymbol* symbol, QSize size ); + /** Returns an icon preview for a color ramp. + * @param symbol symbol + * @param size target pixmap size + * @param padding space between icon edge and symbol + * @see symbolPreviewPixmap() + */ + static QIcon symbolPreviewIcon( QgsSymbol* symbol, QSize size, int padding = 0 ); + + /** Returns a pixmap preview for a color ramp. + * @param symbol symbol + * @param size target pixmap size + * @param padding space between icon edge and symbol + * @param customContext render context to use when rendering symbol + * @note customContext parameter added in 2.6 + * @see symbolPreviewIcon() + */ + static QPixmap symbolPreviewPixmap( QgsSymbol* symbol, QSize size, int padding = 0, QgsRenderContext* customContext = nullptr ); /** Draws a symbol layer preview to a QPicture * @param layer symbol layer to draw @@ -161,25 +177,24 @@ class CORE_EXPORT QgsSymbolLayerUtils */ static QIcon symbolLayerPreviewIcon( QgsSymbolLayer* layer, QgsUnitTypes::RenderUnit u, QSize size, const QgsMapUnitScale& scale = QgsMapUnitScale() ); - /** Returns a icon preview for a color ramp. + /** Returns an icon preview for a color ramp. * @param ramp color ramp * @param size target icon size + * @param padding space between icon edge and color ramp * @see colorRampPreviewPixmap() */ - static QIcon colorRampPreviewIcon( QgsColorRamp* ramp, QSize size ); + static QIcon colorRampPreviewIcon( QgsColorRamp* ramp, QSize size, int padding = 0 ); /** Returns a pixmap preview for a color ramp. * @param ramp color ramp * @param size target pixmap size + * @param padding space between icon edge and color ramp * @see colorRampPreviewIcon() */ - static QPixmap colorRampPreviewPixmap( QgsColorRamp* ramp, QSize size ); + static QPixmap colorRampPreviewPixmap( QgsColorRamp* ramp, QSize size, int padding = 0 ); static void drawStippledBackground( QPainter* painter, QRect rect ); - //! @note customContext parameter added in 2.6 - static QPixmap symbolPreviewPixmap( QgsSymbol* symbol, QSize size, QgsRenderContext* customContext = nullptr ); - //! Returns the maximum estimated bleed for the symbol static double estimateMaxSymbolBleed( QgsSymbol* symbol ); diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp index ecb8be3d62dd..f53f19961771 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp @@ -236,17 +236,8 @@ void QgsStyleManagerDialog::on_tabItemType_currentChanged( int ) actnExportAsPNG->setVisible( flag ); actnExportAsSVG->setVisible( flag ); - // set icon and grid size, depending on type - if ( currentItemType() == 1 || currentItemType() == 3 ) - { - listItems->setIconSize( QSize( 75, 50 ) ); - listItems->setGridSize( QSize( 100, 80 ) ); - } - else - { - listItems->setIconSize( QSize( 50, 50 ) ); - listItems->setGridSize( QSize( 75, 80 ) ); - } + listItems->setIconSize( QSize( 100, 90 ) ); + listItems->setGridSize( QSize( 120, 110 ) ); populateList(); } @@ -275,7 +266,7 @@ void QgsStyleManagerDialog::populateSymbols( const QStringList& symbolNames, boo if ( symbol && symbol->type() == type ) { QStandardItem* item = new QStandardItem( name ); - QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize() ); + QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize(), 18 ); item->setIcon( icon ); item->setData( name ); // used to find out original name when user edited the name item->setCheckable( check ); @@ -301,7 +292,7 @@ void QgsStyleManagerDialog::populateColorRamps( const QStringList& colorRamps, b QScopedPointer< QgsColorRamp > ramp( mStyle->colorRamp( name ) ); QStandardItem* item = new QStandardItem( name ); - QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.data(), listItems->iconSize() ); + QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.data(), listItems->iconSize(), 18 ); item->setIcon( icon ); item->setData( name ); // used to find out original name when user edited the name item->setCheckable( check ); diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index 08548a86c7bc..0257cc201920 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -243,7 +243,7 @@ void QgsSymbolsListWidget::populateSymbols( const QStringList& names ) itemFont.setPointSize( 10 ); item->setFont( itemFont ); // create preview icon - QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( s, previewSize ); + QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( s, previewSize, 15 ); item->setIcon( icon ); // add to model model->appendRow( item ); diff --git a/src/ui/symbollayer/widget_symbolslist.ui b/src/ui/symbollayer/widget_symbolslist.ui index 31e73bbdf3cf..ef29f779d5f3 100644 --- a/src/ui/symbollayer/widget_symbolslist.ui +++ b/src/ui/symbollayer/widget_symbolslist.ui @@ -37,8 +37,8 @@ - 48 - 48 + 77 + 70 From 1ffdadd75c1f8280a920f69fe655c615b37d6241 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 16 Nov 2016 16:20:43 +0100 Subject: [PATCH 808/897] [travis] Preload libSegFault to debug crashes --- ci/travis/linux/script.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 2dbd176008f0..8fa3ad27078d 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -23,6 +23,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Set OTB application path (installed in before_install.sh script) export OTB_APPLICATION_PATH=${HOME}/OTB-5.6.0-Linux64/lib/otb/applications +export LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so xvfb-run ctest -V -E "qgis_filedownloader|qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|PyQgsOfflineEditingWFS|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure From aea577009bd8b9b91251812019ab40ee33edcf39 Mon Sep 17 00:00:00 2001 From: Werner Macho Date: Thu, 17 Nov 2016 12:25:55 +0100 Subject: [PATCH 809/897] typo fix small typo fix --- src/plugins/spatialquery/qgsspatialquerydialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/spatialquery/qgsspatialquerydialog.cpp b/src/plugins/spatialquery/qgsspatialquerydialog.cpp index 5d32556d52bc..815ddb3db6d0 100644 --- a/src/plugins/spatialquery/qgsspatialquerydialog.cpp +++ b/src/plugins/spatialquery/qgsspatialquerydialog.cpp @@ -286,7 +286,7 @@ QgsSpatialQueryDialog::TypeVerifyCreateSubset QgsSpatialQueryDialog::verifyCreat msg = tr( "Using the field \"%1\" for subset" ).arg( fieldFID ); return verifyTry; } - msg = tr( "Sorry! Only this providers are enable: OGR, POSTGRES and SPATIALITE." ); + msg = tr( "Sorry! Only this providers are enabled: OGR, POSTGRES and SPATIALITE." ); return verifyImpossible; } // TypeVerifyCreateSubset QgsSpatialQueryDialog::verifyCreateSubset(QString &msg, QString &fieldFID) From bf43d3d3cb809ba8ca75544070aa15410d696891 Mon Sep 17 00:00:00 2001 From: Werner Macho Date: Thu, 17 Nov 2016 13:51:45 +0100 Subject: [PATCH 810/897] typo change Ctl to Ctrl writing convention --- src/ui/qgisapp.ui | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/qgisapp.ui b/src/ui/qgisapp.ui index f69671d8bf47..6c5a73570cbe 100644 --- a/src/ui/qgisapp.ui +++ b/src/ui/qgisapp.ui @@ -1701,7 +1701,7 @@ Rotate Label -Ctl (Cmd) increments by 15 deg. +Ctrl (Cmd) increments by 15 deg. @@ -1949,7 +1949,7 @@ Ctl (Cmd) increments by 15 deg. Pin/Unpin Labels And Diagrams Click or marquee on label/diagram to pin -Shift unpins, Ctl (Cmd) toggles state +Shift unpins, Ctrl (Cmd) toggles state Acts on all editable layers From 10db74571fe3b29bcbc5e693df517ba99299beb4 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 17 Nov 2016 14:43:50 +0100 Subject: [PATCH 811/897] Fix attribute table actions --- src/app/qgsattributeactiondialog.cpp | 9 +++++---- src/core/qgsactionscoperegistry.cpp | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/app/qgsattributeactiondialog.cpp b/src/app/qgsattributeactiondialog.cpp index 85c31e1c322c..a8f92069f683 100644 --- a/src/app/qgsattributeactiondialog.cpp +++ b/src/app/qgsattributeactiondialog.cpp @@ -299,13 +299,14 @@ void QgsAttributeActionDialog::updateButtons() void QgsAttributeActionDialog::addDefaultActions() { int pos = 0; - insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), QStringLiteral( "echo \"[% \"MY_FIELD\" %]\"" ), QLatin1String( "" ), true, tr( "Attribute Value" ), QSet() << QStringLiteral( "FieldSpecific" ) ); + insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), QStringLiteral( "echo \"[% \"MY_FIELD\" %]\"" ), QLatin1String( "" ), true, tr( "Attribute Value" ), QSet() << QStringLiteral( "Field" ) ); insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), QStringLiteral( "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"" ), QLatin1String( "" ), true, tr( "Run application" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); - insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")" ), QLatin1String( "" ), false, tr( "Feature ID" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); - insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")" ), QLatin1String( "" ), false, tr( "Field Value" ), QSet() << QStringLiteral( "FieldSpecific" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")" ), QLatin1String( "" ), false, tr( "Feature ID" ), QSet() << QStringLiteral( "Feature" ) << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")" ), QLatin1String( "" ), false, tr( "Field Value" ), QSet() << QStringLiteral( "Field" ) ); insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")" ), QLatin1String( "" ), false, tr( "Clicked Coordinate" ), QSet() << QStringLiteral( "Canvas" ) ); insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false, tr( "Open file" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); - insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "FieldSpecific" ) ); + insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "Field" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "List feature ids" ), QStringLiteral( "" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "Field" ) ); } void QgsAttributeActionDialog::itemDoubleClicked( QTableWidgetItem* item ) diff --git a/src/core/qgsactionscoperegistry.cpp b/src/core/qgsactionscoperegistry.cpp index a8a1cf0f7da2..eb53adc8abb5 100644 --- a/src/core/qgsactionscoperegistry.cpp +++ b/src/core/qgsactionscoperegistry.cpp @@ -34,7 +34,7 @@ QgsActionScopeRegistry::QgsActionScopeRegistry( QObject* parent ) mActionScopes.insert( QgsActionScope( QStringLiteral( "Field" ), tr( "Field Scope" ), tr( "Available for individual fields. For example in the attribute table." ), fieldScope ) ); mActionScopes.insert( QgsActionScope( QStringLiteral( "Feature" ), tr( "Feature Scope" ), tr( "Available for individual features. For example on feature forms or per row in the attribute table." ) ) ); - mActionScopes.insert( QgsActionScope( QStringLiteral( "Layer Scope" ), tr( "Layer Scope" ), tr( "Available as layer global action. For example on top of the attribute table." ) ) ); + mActionScopes.insert( QgsActionScope( QStringLiteral( "Layer" ), tr( "Layer Scope" ), tr( "Available as layer global action. For example on top of the attribute table." ) ) ); } QSet QgsActionScopeRegistry::actionScopes() const From ebcfa72632cb6e4d35c81e1ec33e573a12093b86 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 17 Nov 2016 14:53:01 +0100 Subject: [PATCH 812/897] Add a simple layer scoped action example --- src/app/qgsattributeactiondialog.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/qgsattributeactiondialog.cpp b/src/app/qgsattributeactiondialog.cpp index a8f92069f683..a03eda43fe01 100644 --- a/src/app/qgsattributeactiondialog.cpp +++ b/src/app/qgsattributeactiondialog.cpp @@ -306,7 +306,7 @@ void QgsAttributeActionDialog::addDefaultActions() insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")" ), QLatin1String( "" ), false, tr( "Clicked Coordinate" ), QSet() << QStringLiteral( "Canvas" ) ); insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false, tr( "Open file" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "Field" ) ); - insertRow( pos++, QgsAction::GenericPython, tr( "List feature ids" ), QStringLiteral( "" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "Field" ) ); + insertRow( pos++, QgsAction::GenericPython, tr( "List feature ids" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nlayer = QgsMapLayerRegistry.instance().mapLayer('[% @layer_id %]')\nif layer.selectedFeatureCount():\n ids = layer.selectedFeaturesIds()\nelse:\n ids = [f.id() for f in layer.getFeatures()]\n\nQtWidgets.QMessageBox.information(None, \"Feature ids\", ', '.join([str(id) for id in ids]))" ), QLatin1String( "" ), false, tr( "List feature ids" ), QSet() << QStringLiteral( "Layer" ) ); } void QgsAttributeActionDialog::itemDoubleClicked( QTableWidgetItem* item ) From 5f8fd2b4ae98c0da6874d45e9f30dcad9205d26d Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Thu, 17 Nov 2016 15:02:35 +0100 Subject: [PATCH 813/897] Fix some leftover faulty attribute scopes --- src/app/qgsattributeactiondialog.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/qgsattributeactiondialog.cpp b/src/app/qgsattributeactiondialog.cpp index a03eda43fe01..e72b825d91ce 100644 --- a/src/app/qgsattributeactiondialog.cpp +++ b/src/app/qgsattributeactiondialog.cpp @@ -300,11 +300,11 @@ void QgsAttributeActionDialog::addDefaultActions() { int pos = 0; insertRow( pos++, QgsAction::Generic, tr( "Echo attribute's value" ), QStringLiteral( "echo \"[% \"MY_FIELD\" %]\"" ), QLatin1String( "" ), true, tr( "Attribute Value" ), QSet() << QStringLiteral( "Field" ) ); - insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), QStringLiteral( "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"" ), QLatin1String( "" ), true, tr( "Run application" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::Generic, tr( "Run an application" ), QStringLiteral( "ogr2ogr -f \"ESRI Shapefile\" \"[% \"OUTPUT_PATH\" %]\" \"[% \"INPUT_FILE\" %]\"" ), QLatin1String( "" ), true, tr( "Run application" ), QSet() << QStringLiteral( "Feature" ) << QStringLiteral( "Canvas" ) ); insertRow( pos++, QgsAction::GenericPython, tr( "Get feature id" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Feature id\", \"feature id is [% $id %]\")" ), QLatin1String( "" ), false, tr( "Feature ID" ), QSet() << QStringLiteral( "Feature" ) << QStringLiteral( "Canvas" ) ); insertRow( pos++, QgsAction::GenericPython, tr( "Selected field's value (Identify features tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Current field's value\", \"[% @current_field %]\")" ), QLatin1String( "" ), false, tr( "Field Value" ), QSet() << QStringLiteral( "Field" ) ); insertRow( pos++, QgsAction::GenericPython, tr( "Clicked coordinates (Run feature actions tool)" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nQtWidgets.QMessageBox.information(None, \"Clicked coords\", \"layer: [% @layer_id %]\\ncoords: ([% @click_x %],[% @click_y %])\")" ), QLatin1String( "" ), false, tr( "Clicked Coordinate" ), QSet() << QStringLiteral( "Canvas" ) ); - insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false, tr( "Open file" ), QSet() << QStringLiteral( "AttributeTable" ) << QStringLiteral( "Canvas" ) ); + insertRow( pos++, QgsAction::OpenUrl, tr( "Open file" ), QStringLiteral( "[% \"PATH\" %]" ), QLatin1String( "" ), false, tr( "Open file" ), QSet() << QStringLiteral( "Feature" ) << QStringLiteral( "Canvas" ) ); insertRow( pos++, QgsAction::OpenUrl, tr( "Search on web based on attribute's value" ), QStringLiteral( "http://www.google.com/search?q=[% \"ATTRIBUTE\" %]" ), QLatin1String( "" ), false, tr( "Search Web" ), QSet() << QStringLiteral( "Field" ) ); insertRow( pos++, QgsAction::GenericPython, tr( "List feature ids" ), QStringLiteral( "from qgis.PyQt import QtWidgets\n\nlayer = QgsMapLayerRegistry.instance().mapLayer('[% @layer_id %]')\nif layer.selectedFeatureCount():\n ids = layer.selectedFeaturesIds()\nelse:\n ids = [f.id() for f in layer.getFeatures()]\n\nQtWidgets.QMessageBox.information(None, \"Feature ids\", ', '.join([str(id) for id in ids]))" ), QLatin1String( "" ), false, tr( "List feature ids" ), QSet() << QStringLiteral( "Layer" ) ); } From 263ba81c706d2711df45880f3234c166d5517c35 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 18 Nov 2016 08:06:53 +1000 Subject: [PATCH 814/897] Fix ui build warnings --- src/ui/qgsstyleexportimportdialogbase.ui | 1 - src/ui/qgsstylemanagerdialogbase.ui | 1 - src/ui/qgsstylesavedialog.ui | 2 +- 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/ui/qgsstyleexportimportdialogbase.ui b/src/ui/qgsstyleexportimportdialogbase.ui index 4803407540e9..dc1ac29ce77e 100644 --- a/src/ui/qgsstyleexportimportdialogbase.ui +++ b/src/ui/qgsstyleexportimportdialogbase.ui @@ -132,7 +132,6 @@ importTypeCombo locationLineEdit btnBrowse - groupCombo listItems buttonBox diff --git a/src/ui/qgsstylemanagerdialogbase.ui b/src/ui/qgsstylemanagerdialogbase.ui index 23e27f7073ac..2a306329aaad 100644 --- a/src/ui/qgsstylemanagerdialogbase.ui +++ b/src/ui/qgsstylemanagerdialogbase.ui @@ -546,7 +546,6 @@ QMenu::item:selected { background-color: gray; } */ btnRemoveGroup btnManageGroups searchBox - tagsLineEdit tabItemType listItems btnAddItem diff --git a/src/ui/qgsstylesavedialog.ui b/src/ui/qgsstylesavedialog.ui index 3357a8959c6c..8eb148cc30f4 100644 --- a/src/ui/qgsstylesavedialog.ui +++ b/src/ui/qgsstylesavedialog.ui @@ -40,7 +40,7 @@
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - + Tag(s) From 5e1a69fc88e6ac97675ed178bcb8f0d8e32da3c1 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 18 Nov 2016 10:56:02 +1000 Subject: [PATCH 815/897] [FEATURE][processing] Create attribute index algorithm Allows creation of an index on an attribute in a layer for faster attribute based filtering Support depends on the underlying data provider for the layer --- python/plugins/processing/algs/help/qgis.yaml | 3 + .../algs/qgis/CreateAttributeIndex.py | 73 +++++++++++++++++++ .../algs/qgis/QGISAlgorithmProvider.py | 3 +- .../tests/testdata/qgis_algorithm_tests.yaml | 9 ++- 4 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 python/plugins/processing/algs/qgis/CreateAttributeIndex.py diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index fab282a91739..b9492fffdf78 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -93,6 +93,9 @@ qgis:countuniquepointsinpolygon: > A new polygons layer is generated, with the exact same content as the input polygons layer, but containing an additional field with the points count corresponding to each polygon. +qgis:createattributeindex: > + Creates an index to speed up queries made against a field in a table. Support for index creation is dependant on the layer's data provider and the field type. + qgis:createconstantrasterlayer: > Given an input raster layer an a value, this algorithm generates a new layer with the same extent and cellsize as the input one, and all cells with the specified value. diff --git a/python/plugins/processing/algs/qgis/CreateAttributeIndex.py b/python/plugins/processing/algs/qgis/CreateAttributeIndex.py new file mode 100644 index 000000000000..817820358e08 --- /dev/null +++ b/python/plugins/processing/algs/qgis/CreateAttributeIndex.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + CreateAttributeIndex.py + ----------------------- + Date : November 2016 + Copyright : (C) 2016 by Nyall Dawson + Email : nyall dot dawson at gmail dot com +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Nyall Dawson' +__date__ = 'November 2016' +__copyright__ = '(C) 2016, Nyall Dawson' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import QgsVectorDataProvider, QgsFields + +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.parameters import ParameterTableField +from processing.core.outputs import OutputVector + +from processing.tools import dataobjects + + +class CreateAttributeIndex(GeoAlgorithm): + + INPUT = 'INPUT' + FIELD = 'FIELD' + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Create attribute index') + self.group, self.i18n_group = self.trAlgorithm('Vector general tools') + + self.addParameter(ParameterVector(self.INPUT, + self.tr('Input Layer'))) + self.addParameter(ParameterTableField(self.FIELD, + self.tr('Attribute to index'), self.INPUT)) + self.addOutput(OutputVector(self.OUTPUT, + self.tr('Indexed layer'), True)) + + def processAlgorithm(self, progress): + file_name = self.getParameterValue(self.INPUT) + layer = dataobjects.getObjectFromUri(file_name) + field = self.getParameterValue(self.FIELD) + provider = layer.dataProvider() + + field_index = layer.fields().lookupField(field) + if field_index < 0 or layer.fields().fieldOrigin(field_index) != QgsFields.OriginProvider: + progress.setInfo(self.tr('Can not create attribute index on "{}"').format(field)) + else: + provider_index = layer.fields().fieldOriginIndex(field_index) + if provider.capabilities() & QgsVectorDataProvider.CreateAttributeIndex: + if not provider.createAttributeIndex(provider_index): + progress.setInfo(self.tr('Could not create attribute index')) + else: + progress.setInfo(self.tr("Layer's data provider does not support " + "creating attribute indexes")) + + self.setOutputValue(self.OUTPUT, file_name) diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index cfb5b5a38e3e..4233a6f7a166 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -177,6 +177,7 @@ from .GeometryByExpression import GeometryByExpression from .SnapGeometries import SnapGeometriesToLayer from .PoleOfInaccessibility import PoleOfInaccessibility +from .CreateAttributeIndex import CreateAttributeIndex pluginPath = os.path.normpath(os.path.join( os.path.split(os.path.dirname(__file__))[0], os.pardir)) @@ -240,7 +241,7 @@ def __init__(self): TinInterpolationZValue(), TinInterpolationAttribute(), RemoveNullGeometry(), ExtractByExpression(), ExtendLines(), ExtractSpecificNodes(), GeometryByExpression(), SnapGeometriesToLayer(), - PoleOfInaccessibility() + PoleOfInaccessibility(), CreateAttributeIndex() ] if hasMatplotlib: diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index d228d83733fc..5082794246fc 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1544,4 +1544,11 @@ tests: name: expected/extract_by_attribute_greater.gml type: vector - + - algorithm: qgis:createattributeindex + name: Create Attribute Index (only tests for python errors, does not check result) + params: + FIELD: fid + INPUT: + name: lines.gml + type: vector + results: {} \ No newline at end of file From 13a0e48a26673711ad484b6a39771021cc676dcb Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 18 Nov 2016 08:26:49 +0700 Subject: [PATCH 816/897] [style manager] improve UI - create a dedicated set of buttons for addition of tags and smartgroups to make those actions more visible as well as getting rid of th need to select a tag/smartgroup to create those (turns out to be quite confusing for newcomers) - move UI elements around, regroup {add,remove,edit} symbol buttons to harmonize with other parts of QGIS; the elements' placement feels much more natural now --- images/images.qrc | 2 +- images/themes/default/styleicons/color.png | Bin 1179 -> 0 bytes images/themes/default/styleicons/color.svg | 608 ++++++++++++++++++ python/core/symbology-ng/qgsstyle.sip | 3 + .../symbology-ng/qgsstylemanagerdialog.sip | 8 +- src/core/symbology-ng/qgsstyle.cpp | 21 + src/core/symbology-ng/qgsstyle.h | 3 + .../symbology-ng/qgsstylemanagerdialog.cpp | 218 ++++--- src/gui/symbology-ng/qgsstylemanagerdialog.h | 8 +- src/ui/qgsprojectpropertiesbase.ui | 8 +- src/ui/qgsstylemanagerdialogbase.ui | 181 +++--- 11 files changed, 862 insertions(+), 198 deletions(-) delete mode 100644 images/themes/default/styleicons/color.png create mode 100644 images/themes/default/styleicons/color.svg diff --git a/images/images.qrc b/images/images.qrc index 752e9d61041d..49a8f09be127 100644 --- a/images/images.qrc +++ b/images/images.qrc @@ -492,7 +492,7 @@ themes/default/scale_bar.png themes/default/stars_empty.png themes/default/stars_full.png - themes/default/styleicons/color.png + themes/default/styleicons/color.svg themes/default/styleicons/style-line.png themes/default/styleicons/style-point.png themes/default/styleicons/style-polygon.png diff --git a/images/themes/default/styleicons/color.png b/images/themes/default/styleicons/color.png deleted file mode 100644 index d1077f6a8114296507d7d6b9c32e207064827be6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1179 zcmV;M1Z4Y(P)XNm-$?D={U;~?EuCNDc(!%E2w6!G5 zb1n~e$@#*CU2^GNVhdwm_`mtzkMH+${C{`%JA~(Xc$`8XYx)xpV6)lkX__`{#sjIP z2L?at>(Nqdm%_+dagw+4EOc~p2Ew3$zmg32!!gu%cL}*ReB#1yTMF>zu|sBKXL`)^ zd};tA3wUuq8^Pff#thb$M;`GcWZfRrdG!WvA0KxFHx2OK>E0u{XHz5fO_|p6Yn1?s zn!AlG{BaW*eb+vHR?1(p2VOni_w)7_qu*Bwms966eA_^8;moJQebfI7;N{`o*Ml8V zdhVC{wE|abJOIl9{5r*~_U~MyPY=Cxq$U8{psgWGrH|)H4i7fPcX_9E%e6qT9KiWA z%<>DS^<8yDo_MYyK631xL*}XhQZ3Q3?2dFB001BWq2@T{ovIF^7~W%Ar%>d--e}gQ zTRRQ$v8n(L+v$VM?!-XJCIS#@iBsMwy(9$70i6Gq2?)cB+G9=*oP4{lM;0KrEwjI% z%qvCi2tcSMMtLt(hR7Ae8`dr5;Q#<6p2r(C=`LA-0$FGm+Y2C`j#1a0x_}TO#{oDb z!izGhSgSk$Q4kfCLj-rnE!Um80M7!jEWl4ygaZJO1TXR~c@fbxZQ#0@Kwi(1l1>k$ z{aX{=lLa`?@Ia3s^7ShTb!>WJyT##fB#V2vuz(~XIvR$>$f+Lvt*2*Bxk=o^Q2+ua1^MuPK8dNGCT5`o_=VD8X!tnQ% zdnu`KAw=u_FeQYzRYxxTsW;jy)mH>?eD~Qu+0gt5&oZpy-t1Df;bI8gQi#C08=Csj zaYyCpXv4PsVeErR)aSZ5h + + + + point layer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + point layer + 2011-03-11 + + + Robert Szczepanek + + + + + Robert Szczepanek + + + + + icon + gis + + + GIS icons 0.2 + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/python/core/symbology-ng/qgsstyle.sip b/python/core/symbology-ng/qgsstyle.sip index f3f70d606d2a..c275535aa270 100644 --- a/python/core/symbology-ng/qgsstyle.sip +++ b/python/core/symbology-ng/qgsstyle.sip @@ -236,6 +236,9 @@ class QgsStyle : QObject */ QStringList tagsOfSymbol( StyleEntity type, const QString& symbol ); + //! Returns the tag name for the given id + QString tag( int id ) const; + //! Returns the smart groups map with id as key and name as value QMap smartgroupsListMap(); diff --git a/python/gui/symbology-ng/qgsstylemanagerdialog.sip b/python/gui/symbology-ng/qgsstylemanagerdialog.sip index dd0739d46a14..bc23edb30760 100644 --- a/python/gui/symbology-ng/qgsstylemanagerdialog.sip +++ b/python/gui/symbology-ng/qgsstylemanagerdialog.sip @@ -34,7 +34,11 @@ class QgsStyleManagerDialog : QDialog void groupChanged( const QModelIndex& ); void groupRenamed( QStandardItem * ); - void addGroup(); + //! add a tag + int addTag(); + //! add a smartgroup + int addSmartgroup(); + //! remove a tag or smartgroup void removeGroup(); //! carry out symbol tagging using check boxes @@ -68,7 +72,7 @@ class QgsStyleManagerDialog : QDialog //! Remove selected symbols from favorites void removeFavoriteSelectedSymbols(); //! Tag selected symbols using menu item selection - void tagSelectedSymbols(); + void tagSelectedSymbols( bool newTag = false ); //! Remove all tags from selected symbols void detagSelectedSymbols(); diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index cc7d03b377eb..c82520415e22 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -995,6 +995,27 @@ QStringList QgsStyle::tagsOfSymbol( StyleEntity type, const QString& symbol ) return tagList; } +QString QgsStyle::tag( int id ) const +{ + if ( !mCurrentDB ) + return QString(); + + sqlite3_stmt *ppStmt; + + char *query = sqlite3_mprintf( "SELECT name FROM tag WHERE id=%d", id ); + int nError = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); + + QString tag; + if ( nError == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) + { + tag = QString::fromUtf8( reinterpret_cast< const char * >( sqlite3_column_text( ppStmt, 0 ) ) ); + } + + sqlite3_finalize( ppStmt ); + + return tag; +} + int QgsStyle::getId( const QString& table, const QString& name ) { char *query = sqlite3_mprintf( "SELECT id FROM %q WHERE LOWER(name)='%q'", table.toUtf8().constData(), name.toUtf8().toLower().constData() ); diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index 9e415b00069a..3efad03d19c5 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -301,6 +301,9 @@ class CORE_EXPORT QgsStyle : public QObject */ QStringList tagsOfSymbol( StyleEntity type, const QString& symbol ); + //! Returns the tag name for the given id + QString tag( int id ) const; + //! Returns the smart groups map with id as key and name as value QgsSymbolGroupMap smartgroupsListMap(); diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp index f53f19961771..1674f1be4dc5 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp @@ -30,13 +30,14 @@ #include "qgsstyleexportimportdialog.h" #include "qgssmartgroupeditordialog.h" +#include #include #include #include #include +#include #include #include -#include #include #include "qgsapplication.h" @@ -59,28 +60,33 @@ QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle* style, QWidget* parent ) mSplitter->restoreState( settings.value( QStringLiteral( "/Windows/StyleV2Manager/splitter" ) ).toByteArray() ); tabItemType->setDocumentMode( true ); - searchBox->setPlaceholderText( tr( "Type here to filter symbols..." ) ); + searchBox->setPlaceholderText( tr( "Filter symbols…" ) ); connect( this, SIGNAL( finished( int ) ), this, SLOT( onFinished() ) ); connect( listItems, SIGNAL( doubleClicked( const QModelIndex & ) ), this, SLOT( editItem() ) ); - connect( btnAddItem, SIGNAL( clicked() ), this, SLOT( addItem() ) ); - connect( actnEditItem, SIGNAL( triggered( bool ) ), this, SLOT( editItem() ) ); - connect( actnRemoveItem, SIGNAL( triggered( bool ) ), this, SLOT( removeItem() ) ); - - btnRemoveItem->setDefaultAction( actnRemoveItem ); - btnEditItem->setDefaultAction( actnEditItem ); + connect( btnAddItem, &QPushButton::clicked, [=]( bool ) { addItem(); } + ); + connect( btnEditItem, &QPushButton::clicked, [=]( bool ) { editItem(); } + ); + connect( actnEditItem, &QAction::triggered, [=]( bool ) { editItem(); } + ); + connect( btnRemoveItem, &QPushButton::clicked, [=]( bool ) { removeItem(); } + ); + connect( actnRemoveItem, &QAction::triggered, [=]( bool ) { removeItem(); } + ); QMenu *shareMenu = new QMenu( tr( "Share menu" ), this ); - shareMenu->addAction( actnExportAsPNG ); - shareMenu->addAction( actnExportAsSVG ); - QAction *exportAction = new QAction( tr( "Export..." ), this ); - shareMenu->addAction( exportAction ); - QAction *importAction = new QAction( tr( "Import..." ), this ); - shareMenu->addAction( importAction ); + QAction *exportAction = new QAction( tr( "Export symbol(s)…" ), this ); exportAction->setIcon( QIcon( QgsApplication::iconPath( "mActionFileSave.svg" ) ) ); + shareMenu->addAction( exportAction ); + QAction *importAction = new QAction( tr( "Import symbol(s)…" ), this ); importAction->setIcon( QIcon( QgsApplication::iconPath( "mActionFileOpen.svg" ) ) ); + shareMenu->addAction( importAction ); + shareMenu->addSeparator(); + shareMenu->addAction( actnExportAsPNG ); + shareMenu->addAction( actnExportAsSVG ); connect( actnExportAsPNG, SIGNAL( triggered() ), this, SLOT( exportItemsPNG() ) ); connect( actnExportAsSVG, SIGNAL( triggered() ), this, SLOT( exportItemsSVG() ) ); connect( exportAction, SIGNAL( triggered() ), this, SLOT( exportItems() ) ); @@ -106,6 +112,8 @@ QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle* style, QWidget* parent ) groupTree->setModel( groupModel ); groupTree->setHeaderHidden( true ); populateGroups(); + groupTree->setCurrentIndex( groupTree->model()->index( 0, 0 ) ); + connect( groupTree->selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ), this, SLOT( groupChanged( const QModelIndex& ) ) ); connect( groupModel, SIGNAL( itemChanged( QStandardItem* ) ), @@ -167,8 +175,12 @@ QgsStyleManagerDialog::QgsStyleManagerDialog( QgsStyle* style, QWidget* parent ) mGroupTreeContextMenu = new QMenu( this ); connect( actnEditSmartGroup, SIGNAL( triggered( bool ) ), this, SLOT( editSmartgroupAction() ) ); mGroupTreeContextMenu->addAction( actnEditSmartGroup ); - connect( actnAddGroup, SIGNAL( triggered( bool ) ), this, SLOT( addGroup() ) ); - mGroupTreeContextMenu->addAction( actnAddGroup ); + connect( actnAddTag, &QAction::triggered, [=]( bool ) { addTag(); } + ); + mGroupTreeContextMenu->addAction( actnAddTag ); + connect( actnAddSmartgroup, &QAction::triggered, [=]( bool ) { addSmartgroup(); } + ); + mGroupTreeContextMenu->addAction( actnAddSmartgroup ); connect( actnRemoveGroup, SIGNAL( triggered( bool ) ), this, SLOT( removeGroup() ) ); mGroupTreeContextMenu->addAction( actnRemoveGroup ); @@ -232,6 +244,7 @@ void QgsStyleManagerDialog::on_tabItemType_currentChanged( int ) { // when in Color Ramp tab, add menu to add item button and hide "Export symbols as PNG/SVG" bool flag = currentItemType() != 3; + searchBox->setPlaceholderText( flag ? tr( "Filter symbols…" ) : tr( "Filter color ramps…" ) ); btnAddItem->setMenu( flag ? nullptr : mMenuBtnAddItemColorRamp ); actnExportAsPNG->setVisible( flag ); actnExportAsSVG->setVisible( flag ); @@ -945,24 +958,25 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) if ( category == QLatin1String( "all" ) || category == QLatin1String( "tags" ) || category == QLatin1String( "smartgroups" ) ) { enableGroupInputs( false ); - if ( category == QLatin1String( "tags" ) || category == QLatin1String( "smartgroups" ) ) + if ( category == QLatin1String( "tags" ) ) + { + actnAddTag->setEnabled( true ); + actnAddSmartgroup->setEnabled( false ); + } + else if ( category == QLatin1String( "smartgroups" ) ) { - btnAddGroup->setEnabled( true ); - actnAddGroup->setEnabled( true ); + actnAddTag->setEnabled( false ); + actnAddSmartgroup->setEnabled( true ); } symbolNames = currentItemType() < 3 ? mStyle->symbolNames() : mStyle->colorRampNames(); } else if ( category == QLatin1String( "favorite" ) ) { - btnAddGroup->setEnabled( true ); - actnAddGroup->setEnabled( true ); enableGroupInputs( false ); - symbolNames = mStyle->symbolsOfFavorite( type ); } else if ( index.parent().data( Qt::UserRole + 1 ) == "smartgroups" ) { - btnRemoveGroup->setEnabled( true ); actnRemoveGroup->setEnabled( true ); btnManageGroups->setEnabled( true ); int groupId = index.data( Qt::UserRole + 1 ).toInt(); @@ -995,7 +1009,8 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) } actnEditSmartGroup->setVisible( false ); - actnAddGroup->setVisible( false ); + actnAddTag->setVisible( false ); + actnAddSmartgroup->setVisible( false ); actnRemoveGroup->setVisible( false ); actnTagSymbols->setVisible( false ); actnFinishTagging->setVisible( false ); @@ -1006,89 +1021,100 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) { actnEditSmartGroup->setVisible( !mGrouppingMode ); } - else + else if ( index.parent().data( Qt::UserRole + 1 ).toString() == QLatin1String( "tags" ) ) { - actnAddGroup->setVisible( !mGrouppingMode ); + actnAddTag->setVisible( !mGrouppingMode ); actnTagSymbols->setVisible( !mGrouppingMode ); actnFinishTagging->setVisible( mGrouppingMode ); } actnRemoveGroup->setVisible( true ); } - else if ( index.data( Qt::UserRole + 1 ) == "tags" || index.data( Qt::UserRole + 1 ) == "smartgroups" ) + else if ( index.data( Qt::UserRole + 1 ) == "smartgroups" ) + { + actnAddSmartgroup->setVisible( !mGrouppingMode ); + } + else if ( index.data( Qt::UserRole + 1 ) == "tags" ) { - actnAddGroup->setVisible( !mGrouppingMode ); + actnAddTag->setVisible( !mGrouppingMode ); } } -void QgsStyleManagerDialog::addGroup() +int QgsStyleManagerDialog::addTag() { QStandardItemModel *model = qobject_cast( groupTree->model() ); - QModelIndex index = groupTree->currentIndex(); - - // don't allow creation of tag/smartgroup against system-defined groupings - QString data = index.data( Qt::UserRole + 1 ).toString(); - if ( data == QLatin1String( "all" ) || data == "favorite" ) + QModelIndex index; + for ( int i = 0; i < groupTree->model()->rowCount(); i++ ) { - int err = QMessageBox::critical( this, tr( "Invalid Selection" ), - tr( "The parent group you have selected is not user editable.\n" - "Kindly select a user defined group." ) ); - if ( err ) - return; + index = groupTree->model()->index( i, 0 ); + QString data = index.data( Qt::UserRole + 1 ).toString(); + if ( data == QLatin1String( "tags" ) ) + { + break; + } } QString itemName; int id; + bool ok; + itemName = QInputDialog::getText( this, tr( "Tag name" ), + tr( "Please enter name for the new tag:" ), QLineEdit::Normal, tr( "New tag" ), &ok ).trimmed(); + if ( !ok || itemName.isEmpty() ) + return 0; - // - if ( index.parent() != QModelIndex() ) + int check = mStyle->tagId( itemName ); + if ( check > 0 ) { - index = index.parent(); - data = index.data( Qt::UserRole + 1 ).toString(); + QMessageBox::critical( this, tr( "Error!" ), + tr( "Tag name already exists in your symbol database." ) ); + return 0; } - - if ( data == QLatin1String( "smartgroups" ) ) + id = mStyle->addTag( itemName ); + if ( !id ) { - // create a smartgroup - QgsSmartGroupEditorDialog dlg( mStyle, this ); - if ( dlg.exec() == QDialog::Rejected ) - return; - id = mStyle->addSmartgroup( dlg.smartgroupName(), dlg.conditionOperator(), dlg.conditionMap() ); - if ( !id ) - return; - itemName = dlg.smartgroupName(); + QMessageBox::critical( this, tr( "Error!" ), + tr( "New tag could not be created.\n" + "There was a problem with your symbol database." ) ); + return 0; } - else - { - // create a tag - bool ok; - itemName = QInputDialog::getText( this, tr( "Tag name" ), - tr( "Please enter name for the new tag:" ), QLineEdit::Normal, tr( "New tag" ), &ok ).trimmed(); - if ( !ok || itemName.isEmpty() ) - return; - int check = mStyle->tagId( itemName ); - if ( check > 0 ) - { - QMessageBox::critical( this, tr( "Error!" ), - tr( "Tag name already exists in your symbol database." ) ); - return; - } - id = mStyle->addTag( itemName ); - if ( !id ) + QStandardItem *parentItem = model->itemFromIndex( index ); + QStandardItem *childItem = new QStandardItem( itemName ); + childItem->setData( id ); + parentItem->appendRow( childItem ); + + return id; +} + +int QgsStyleManagerDialog::addSmartgroup() +{ + QStandardItemModel *model = qobject_cast( groupTree->model() ); + QModelIndex index; + for ( int i = 0; i < groupTree->model()->rowCount(); i++ ) + { + index = groupTree->model()->index( i, 0 ); + QString data = index.data( Qt::UserRole + 1 ).toString(); + if ( data == QLatin1String( "smartgroups" ) ) { - QMessageBox::critical( this, tr( "Error!" ), - tr( "New tag could not be created.\n" - "There was a problem with your symbol database." ) ); - return; + break; } } + QString itemName; + int id; + QgsSmartGroupEditorDialog dlg( mStyle, this ); + if ( dlg.exec() == QDialog::Rejected ) + return 0; + id = mStyle->addSmartgroup( dlg.smartgroupName(), dlg.conditionOperator(), dlg.conditionMap() ); + if ( !id ) + return 0; + itemName = dlg.smartgroupName(); + QStandardItem *parentItem = model->itemFromIndex( index ); QStandardItem *childItem = new QStandardItem( itemName ); childItem->setData( id ); parentItem->appendRow( childItem ); - groupTree->setCurrentIndex( childItem->index() ); + return id; } void QgsStyleManagerDialog::removeGroup() @@ -1280,9 +1306,10 @@ void QgsStyleManagerDialog::selectedSymbolsChanged( const QItemSelection& select void QgsStyleManagerDialog::enableSymbolInputs( bool enable ) { groupTree->setEnabled( enable ); - btnAddGroup->setEnabled( enable ); - actnAddGroup->setEnabled( enable ); - btnRemoveGroup->setEnabled( enable ); + btnAddTag->setEnabled( enable ); + btnAddSmartgroup->setEnabled( enable ); + actnAddTag->setEnabled( enable ); + actnAddSmartgroup->setEnabled( enable ); actnRemoveGroup->setEnabled( enable ); btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode searchBox->setEnabled( enable ); @@ -1290,8 +1317,6 @@ void QgsStyleManagerDialog::enableSymbolInputs( bool enable ) void QgsStyleManagerDialog::enableGroupInputs( bool enable ) { - btnAddGroup->setEnabled( enable ); - btnRemoveGroup->setEnabled( enable ); actnRemoveGroup->setEnabled( enable ); btnManageGroups->setEnabled( enable || mGrouppingMode ); // always enabled in grouping mode, as it is the only way to leave grouping mode } @@ -1351,10 +1376,20 @@ void QgsStyleManagerDialog::listitemsContextMenu( QPoint point ) { a = new QAction( tag, mGroupListMenu ); a->setData( tag ); - connect( a, SIGNAL( triggered( bool ) ), this, SLOT( tagSelectedSymbols() ) ); + connect( a, &QAction::triggered, this, [=]( bool ) { tagSelectedSymbols(); } + ); mGroupListMenu->addAction( a ); } + if ( tags.count() > 0 ) + { + mGroupListMenu->addSeparator(); + } + a = new QAction( "Create new tag... ", mGroupListMenu ); + connect( a, &QAction::triggered, this, [=]( bool ) { tagSelectedSymbols( true ); } + ); + mGroupListMenu->addAction( a ); + mGroupMenu->popup( globalPos ); } @@ -1392,10 +1427,9 @@ void QgsStyleManagerDialog::removeFavoriteSelectedSymbols() populateList(); } -void QgsStyleManagerDialog::tagSelectedSymbols() +void QgsStyleManagerDialog::tagSelectedSymbols( bool newTag ) { QAction* selectedItem = qobject_cast( sender() ); - if ( selectedItem ) { QgsStyle::StyleEntity type = ( currentItemType() < 3 ) ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity; @@ -1404,7 +1438,23 @@ void QgsStyleManagerDialog::tagSelectedSymbols() QgsDebugMsg( "unknown entity type" ); return; } - QString tag = selectedItem->data().toString(); + + QString tag; + if ( newTag ) + { + int id = addTag(); + if ( id == 0 ) + { + return; + } + + tag = mStyle->tag( id ); + } + else + { + tag = selectedItem->data().toString(); + } + QModelIndexList indexes = listItems->selectionModel()->selectedIndexes(); Q_FOREACH ( const QModelIndex& index, indexes ) { diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.h b/src/gui/symbology-ng/qgsstylemanagerdialog.h index 7132838af44f..ea0ad7330f20 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.h +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.h @@ -63,7 +63,11 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan void groupChanged( const QModelIndex& ); void groupRenamed( QStandardItem * ); - void addGroup(); + //! add a tag + int addTag(); + //! add a smartgroup + int addSmartgroup(); + //! remove a tag or smartgroup void removeGroup(); //! carry out symbol tagging using check boxes @@ -97,7 +101,7 @@ class GUI_EXPORT QgsStyleManagerDialog : public QDialog, private Ui::QgsStyleMan //! Remove selected symbols from favorites void removeFavoriteSelectedSymbols(); //! Tag selected symbols using menu item selection - void tagSelectedSymbols(); + void tagSelectedSymbols( bool newTag = false ); //! Remove all tags from selected symbols void detagSelectedSymbols(); diff --git a/src/ui/qgsprojectpropertiesbase.ui b/src/ui/qgsprojectpropertiesbase.ui index 06ce53fe8bc8..c0eeeba62353 100644 --- a/src/ui/qgsprojectpropertiesbase.ui +++ b/src/ui/qgsprojectpropertiesbase.ui @@ -887,7 +887,7 @@ - :/images/themes/default/styleicons/color.png + :/images/themes/default/styleicons/color.svg @@ -903,7 +903,7 @@ - :/images/themes/default/styleicons/style-polygon.png + :/images/themes/default/mIconPolygonLayer.svg @@ -930,7 +930,7 @@ - :/images/themes/default/styleicons/style-line.png + :/images/themes/default/mIconLineLayer.svg @@ -982,7 +982,7 @@ - :/images/themes/default/styleicons/style-point.png + :/images/themes/default/mIconPointLayer.svg diff --git a/src/ui/qgsstylemanagerdialogbase.ui b/src/ui/qgsstylemanagerdialogbase.ui index 2a306329aaad..13812b2f1161 100644 --- a/src/ui/qgsstylemanagerdialogbase.ui +++ b/src/ui/qgsstylemanagerdialogbase.ui @@ -13,12 +13,6 @@ Style Manager - - QToolButton { padding-left: 3px; padding-right: 3px; } -/* QMenu::item { padding: 2px 10px 2px 20px; } -QMenu::item:selected { background-color: gray; } */ - - 6 @@ -63,7 +57,7 @@ QMenu::item:selected { background-color: gray; } */ 0 - + @@ -83,41 +77,46 @@ QMenu::item:selected { background-color: gray; } */ - + - + Add tag… - - - :/images/themes/default/symbologyAdd.svg:/images/themes/default/symbologyAdd.svg + + false + + + + + + + Add smart group… false - - + + - + Modify group - - - :/images/themes/default/symbologyRemove.svg:/images/themes/default/symbologyRemove.svg + + Modify selected tag or smart group false - - + + - + Import / export - :/images/themes/default/mActionChangeLabelProperties.svg:/images/themes/default/mActionChangeLabelProperties.svg + :/images/themes/default/mActionSharing.svg:/images/themes/default/mActionSharing.svg false @@ -172,7 +171,7 @@ QMenu::item:selected { background-color: gray; } */ - :/images/themes/default/styleicons/style-point.png:/images/themes/default/styleicons/style-point.png + :/images/themes/default/mIconPointLayer.svg:/images/themes/default/mIconPointLayer.svg Marker @@ -187,7 +186,7 @@ QMenu::item:selected { background-color: gray; } */ - :/images/themes/default/styleicons/style-line.png:/images/themes/default/styleicons/style-line.png + :/images/themes/default/mIconLineLayer.svg:/images/themes/default/mIconLineLayer.svg Line @@ -202,7 +201,7 @@ QMenu::item:selected { background-color: gray; } */ - :/images/themes/default/styleicons/style-polygon.png:/images/themes/default/styleicons/style-polygon.png + :/images/themes/default/mIconPolygonLayer.svg:/images/themes/default/mIconPolygonLayer.svg Fill @@ -217,7 +216,7 @@ QMenu::item:selected { background-color: gray; } */ - :/images/themes/default/styleicons/color.png:/images/themes/default/styleicons/color.png + :/images/themes/default/styleicons/color.svg:/images/themes/default/styleicons/color.svg Color ramp @@ -265,16 +264,10 @@ QMenu::item:selected { background-color: gray; } */ - - + + - - - - 0 - 0 - - + Add item @@ -285,16 +278,10 @@ QMenu::item:selected { background-color: gray; } */ :/images/themes/default/symbologyAdd.svg:/images/themes/default/symbologyAdd.svg - - QToolButton::InstantPopup - - - true - - + Remove item @@ -305,26 +292,10 @@ QMenu::item:selected { background-color: gray; } */ :/images/themes/default/symbologyRemove.svg:/images/themes/default/symbologyRemove.svg - - true - - - - Qt::Vertical - - - - 20 - 40 - - - - - - + Edit item @@ -335,44 +306,21 @@ QMenu::item:selected { background-color: gray; } */ :/images/themes/default/mActionProjectProperties.png:/images/themes/default/mActionProjectProperties.png - - Qt::ToolButtonIconOnly - - - true - - - + + + Qt::Horizontal + + 0 - 16 + 0 - - - - - - :/images/themes/default/mActionSharing.svg:/images/themes/default/mActionSharing.svg - - - QToolButton::InstantPopup - - - Qt::ToolButtonIconOnly - - - true - - + - - - - @@ -391,9 +339,6 @@ QMenu::item:selected { background-color: gray; } */ Qt::Horizontal - - QDialogButtonBox::Close - false @@ -468,13 +413,22 @@ QMenu::item:selected { background-color: gray; } */ Edit smart group... - + + + + :/images/themes/default/symbologyAdd.svg:/images/themes/default/symbologyAdd.svg + + + Add tag… + + + :/images/themes/default/symbologyAdd.svg:/images/themes/default/symbologyAdd.svg - Add group + Add smart group… @@ -483,7 +437,7 @@ QMenu::item:selected { background-color: gray; } */ :/images/themes/default/symbologyRemove.svg:/images/themes/default/symbologyRemove.svg - Remove group + Remove @@ -508,10 +462,10 @@ QMenu::item:selected { background-color: gray; } */ - :/images/themes/default/mActionFileSave.svg:/images/themes/default/mActionFileSave.svg + :/images/themes/default/mActionSaveMapAsImage.svg:/images/themes/default/mActionSaveMapAsImage.svg - Export selected symbol(s) as PNG... + Export selected symbol(s) as PNG… Export selected symbo(s) as PNG @@ -523,10 +477,10 @@ QMenu::item:selected { background-color: gray; } */ - :/images/themes/default/mActionFileSave.svg:/images/themes/default/mActionFileSave.svg + :/images/themes/default/mActionSaveAsSVG.svg:/images/themes/default/mActionSaveAsSVG.svg - Export selected symbol(s) as SVG... + Export selected symbol(s) as SVG… Export selected symbol(s) as SVG @@ -542,16 +496,17 @@ QMenu::item:selected { background-color: gray; } */ groupTree - btnAddGroup - btnRemoveGroup btnManageGroups - searchBox + btnRemoveGroup + btnAddTag + btnAddSmartgroup + btnShare tabItemType listItems btnAddItem btnRemoveItem btnEditItem - btnShare + searchBox @@ -574,9 +529,25 @@ QMenu::item:selected { background-color: gray; } */ - btnAddGroup + btnAddTag + clicked() + actnAddTag + trigger() + + + 46 + 362 + + + -1 + -1 + + + + + btnAddSmartgroup clicked() - actnAddGroup + actnAddSmartgroup trigger() From 034e4f35d6c15f85e20dc13190f3c8449cf2b9d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 18 Nov 2016 07:45:56 +0100 Subject: [PATCH 817/897] [Irregular verb] --- python/plugins/processing/algs/qgis/SplitWithLines.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 93df1adcd3d1..9297aee0be08 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -5,7 +5,7 @@ SplitWithLines.py --------------------- Date : November 2014 - Revised : September 2016 + Revised : November 2016 Copyright : (C) 2014 by Bernhard Ströbl Email : bernhard dot stroebl at jena dot de *************************************************************************** @@ -51,7 +51,7 @@ def defineCharacteristics(self): self.addParameter(ParameterVector(self.INPUT_B, self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) - self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'))) + self.addOutput(OutputVector(self.OUTPUT, self.tr('Split'))) def processAlgorithm(self, progress): layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) From 5f3ba725476fc16834ed3486f0b5394985f20d00 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 18 Nov 2016 10:26:43 +0700 Subject: [PATCH 818/897] [style manager] sort displayed symbols, insure tags are added only once --- python/core/symbology-ng/qgsstyle.sip | 9 +++ src/core/symbology-ng/qgsstyle.cpp | 58 ++++++++++++++++--- src/core/symbology-ng/qgsstyle.h | 9 +++ .../symbology-ng/qgsstylemanagerdialog.cpp | 9 +-- src/gui/symbology-ng/qgssymbolslistwidget.cpp | 4 +- 5 files changed, 75 insertions(+), 14 deletions(-) diff --git a/python/core/symbology-ng/qgsstyle.sip b/python/core/symbology-ng/qgsstyle.sip index c275535aa270..1b286699576e 100644 --- a/python/core/symbology-ng/qgsstyle.sip +++ b/python/core/symbology-ng/qgsstyle.sip @@ -236,6 +236,15 @@ class QgsStyle : QObject */ QStringList tagsOfSymbol( StyleEntity type, const QString& symbol ); + /** Returns wheter a given tag is associated with the symbol + * + * \param type is either SymbolEntity or ColorrampEntity + * \param symbol is the name of the symbol or color ramp + * \param tag the name of the tag to look for + * \return A boolean value identicating whether a tag was found attached to the symbol + */ + bool symbolHasTag( StyleEntity type, const QString& symbol, const QString& tag ); + //! Returns the tag name for the given id QString tag( int id ) const; diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index c82520415e22..e1f8e864f728 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -842,16 +842,19 @@ bool QgsStyle::tagSymbol( StyleEntity type, const QString& symbol, const QString sqlite3_finalize( ppStmt ); - // Now map the tag to the symbol - query = type == SymbolEntity - ? sqlite3_mprintf( "INSERT INTO tagmap VALUES (%d,%d)", tagid, symbolid ) - : sqlite3_mprintf( "INSERT INTO ctagmap VALUES (%d,%d)", tagid, symbolid ); - - char *zErr = nullptr; - nErr = sqlite3_exec( mCurrentDB, query, nullptr, nullptr, &zErr ); - if ( nErr ) + // Now map the tag to the symbol if it's not already tagged + if ( !symbolHasTag( type, symbol, tag ) ) { - QgsDebugMsg( zErr ); + query = type == SymbolEntity + ? sqlite3_mprintf( "INSERT INTO tagmap VALUES (%d,%d)", tagid, symbolid ) + : sqlite3_mprintf( "INSERT INTO ctagmap VALUES (%d,%d)", tagid, symbolid ); + + char *zErr = nullptr; + nErr = sqlite3_exec( mCurrentDB, query, nullptr, nullptr, &zErr ); + if ( nErr ) + { + QgsDebugMsg( zErr ); + } } } } @@ -995,6 +998,43 @@ QStringList QgsStyle::tagsOfSymbol( StyleEntity type, const QString& symbol ) return tagList; } +bool QgsStyle::symbolHasTag( StyleEntity type, const QString& symbol, const QString& tag ) +{ + if ( !mCurrentDB ) + { + QgsDebugMsg( "Sorry! Cannot open database for getting the tags." ); + return false; + } + + int symbolid = type == SymbolEntity ? symbolId( symbol ) : colorrampId( symbol ); + if ( !symbolid ) + { + return false; + } + int tagid = tagId( tag ); + if ( !tagid ) + { + return false; + } + + // get the ids of tags for the symbol + char *query = type == SymbolEntity + ? sqlite3_mprintf( "SELECT tag_id FROM tagmap WHERE tag_id=%d AND symbol_id=%d", tagid, symbolid ) + : sqlite3_mprintf( "SELECT tag_id FROM ctagmap WHERE tag_id=%d AND colorramp_id=%d", tagid, symbolid ); + + sqlite3_stmt *ppStmt; + int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, nullptr ); + + if ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW ) + { + return true; + } + else + { + return false; + } +} + QString QgsStyle::tag( int id ) const { if ( !mCurrentDB ) diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index 3efad03d19c5..de5d0eadb5f7 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -301,6 +301,15 @@ class CORE_EXPORT QgsStyle : public QObject */ QStringList tagsOfSymbol( StyleEntity type, const QString& symbol ); + /** Returns wheter a given tag is associated with the symbol + * + * \param type is either SymbolEntity or ColorrampEntity + * \param symbol is the name of the symbol or color ramp + * \param tag the name of the tag to look for + * \return A boolean value identicating whether a tag was found attached to the symbol + */ + bool symbolHasTag( StyleEntity type, const QString& symbol, const QString& tag ); + //! Returns the tag name for the given id QString tag( int id ) const; diff --git a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp index 1674f1be4dc5..3ad3071cb191 100644 --- a/src/gui/symbology-ng/qgsstylemanagerdialog.cpp +++ b/src/gui/symbology-ng/qgsstylemanagerdialog.cpp @@ -271,19 +271,19 @@ void QgsStyleManagerDialog::populateSymbols( const QStringList& symbolNames, boo model->clear(); int type = currentItemType(); - for ( int i = 0; i < symbolNames.count(); ++i ) { QString name = symbolNames[i]; QgsSymbol* symbol = mStyle->symbol( name ); if ( symbol && symbol->type() == type ) { + QStringList tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, name ); QStandardItem* item = new QStandardItem( name ); QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize(), 18 ); item->setIcon( icon ); item->setData( name ); // used to find out original name when user edited the name item->setCheckable( check ); - item->setToolTip( name ); + item->setToolTip( QString( "%1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  %2" ).arg( name ).arg( tags.count() > 0 ? tags.join( ", " ) : tr( "Not tagged" ) ) ); // add to model model->appendRow( item ); } @@ -994,6 +994,7 @@ void QgsStyleManagerDialog::groupChanged( const QModelIndex& index ) } } + symbolNames.sort(); if ( currentItemType() < 3 ) { populateSymbols( symbolNames, mGrouppingMode ); @@ -1271,14 +1272,14 @@ void QgsStyleManagerDialog::setSymbolsChecked( const QStringList& symbols ) void QgsStyleManagerDialog::filterSymbols( const QString& qword ) { QStringList items; + items = mStyle->findSymbols( currentItemType() < 3 ? QgsStyle::SymbolEntity : QgsStyle::ColorrampEntity, qword ); + items.sort(); if ( currentItemType() == 3 ) { - items = mStyle->findSymbols( QgsStyle::ColorrampEntity, qword ); populateColorRamps( items ); } else { - items = mStyle->findSymbols( QgsStyle::SymbolEntity, qword ); populateSymbols( items ); } } diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index 0257cc201920..be3dc5d1028b 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -211,6 +211,7 @@ void QgsSymbolsListWidget::populateSymbolView() symbols = mStyle->symbolsWithTag( QgsStyle::SymbolEntity, id ); } + symbols.sort(); populateSymbols( symbols ); } @@ -233,10 +234,11 @@ void QgsSymbolsListWidget::populateSymbols( const QStringList& names ) delete s; continue; } + QStringList tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, names[i] ); QStandardItem* item = new QStandardItem( names[i] ); item->setData( names[i], Qt::UserRole ); //so we can load symbol with that name item->setText( names[i] ); - item->setToolTip( names[i] ); + item->setToolTip( QString( "%1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  %2" ).arg( names[i] ).arg( tags.count() > 0 ? tags.join( ", " ) : tr( "Not tagged" ) ) ); item->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable ); // Set font to 10points to show reasonable text QFont itemFont = item->font(); From 8fcf8345bd22ff6070fce8dbebbc4a8fdd279b49 Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 18 Nov 2016 12:30:25 +0700 Subject: [PATCH 819/897] tests for two additional QgsStyle functions: tag() & symbolHasTag() --- tests/src/core/testqgsstyle.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/src/core/testqgsstyle.cpp b/tests/src/core/testqgsstyle.cpp index fecf6e6f245b..0e2f10cc4d0f 100644 --- a/tests/src/core/testqgsstyle.cpp +++ b/tests/src/core/testqgsstyle.cpp @@ -301,7 +301,10 @@ void TestStyle::testTags() id = mStyle->addTag( QStringLiteral( "blue" ) ); QCOMPARE( id, mStyle->tagId( "blue" ) ); id = mStyle->addTag( QStringLiteral( "purple" ) ); + + //check tagid and tag return values QCOMPARE( id, mStyle->tagId( "purple" ) ); + QCOMPARE( QStringLiteral( "purple" ), mStyle->tag( id ) ); QStringList tags = mStyle->tags(); QCOMPARE( tags.count(), 5 ); @@ -348,6 +351,12 @@ void TestStyle::testTags() QVERIFY( tags.contains( "red" ) ); QVERIFY( tags.contains( "starry" ) ); + //check that a given tag is attached to a symbol + QVERIFY( mStyle->symbolHasTag( QgsStyle::SymbolEntity, QStringLiteral( "blue starry" ), QStringLiteral( "blue" ) ) ); + + //check that a given tag is not attached to a symbol + QCOMPARE( false, mStyle->symbolHasTag( QgsStyle::SymbolEntity, QStringLiteral( "blue starry" ), QStringLiteral( "notblue" ) ) ); + //remove a tag, including a non-present tag QVERIFY( mStyle->detagSymbol( QgsStyle::SymbolEntity, "blue starry", QStringList() << "bad" << "blue" ) ); tags = mStyle->tagsOfSymbol( QgsStyle::SymbolEntity, QStringLiteral( "blue starry" ) ); From 14cfa266f4534caf5737bb87f360c312c6d5140a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 18 Nov 2016 07:51:54 +0100 Subject: [PATCH 820/897] Deprecate SplitLinesWithLines the proper way --- .../plugins/processing/algs/qgis/QGISAlgorithmProvider.py | 3 ++- .../plugins/processing/algs/qgis/SplitLinesWithLines.py | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index b481ca795d34..b1c7cd1b857e 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -139,6 +139,7 @@ from .SelectByAttributeSum import SelectByAttributeSum from .HypsometricCurves import HypsometricCurves from .SplitWithLines import SplitWithLines +from .SplitLinesWithLines import SplitLinesWithLines from .FieldsMapper import FieldsMapper from .Datasources2Vrt import Datasources2Vrt from .CheckValidity import CheckValidity @@ -205,7 +206,7 @@ def __init__(self): PostGISExecuteSQL(), ImportIntoPostGIS(), SetVectorStyle(), SetRasterStyle(), SelectByExpression(), HypsometricCurves(), - SplitWithLines(), CreateConstantRaster(), + SplitWithLines(), SplitLinesWithLines(), CreateConstantRaster(), FieldsMapper(), SelectByAttributeSum(), Datasources2Vrt(), CheckValidity(), OrientedMinimumBoundingBox(), Smooth(), ReverseLineDirection(), SpatialIndex(), DefineProjection(), diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py index 27732c2c20cb..3963cb1d6150 100644 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -2,10 +2,11 @@ """ *************************************************************************** + SplitLinesWithLines.py DEPRECATED, replaced by SplitWithLines.py --------------------- Date : November 2014 - Revised : February 2016 + Revised : November 2016 Copyright : (C) 2014 by Bernhard Ströbl Email : bernhard dot stroebl at jena dot de *************************************************************************** @@ -42,6 +43,11 @@ class SplitLinesWithLines(GeoAlgorithm): OUTPUT = 'OUTPUT' + def __init__(self): + GeoAlgorithm.__init__(self) + # this algorithm is deprecated - use SplitWithLines instead + self.showInToolbox = False + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Split lines with lines') self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') From f2ed214b9c538e1e45eb123fcf62c186f9cf15b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 18 Nov 2016 08:27:38 +0100 Subject: [PATCH 821/897] [FEATURE] Speed up algo by fetching features only once --- python/plugins/processing/algs/qgis/SplitWithLines.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 9297aee0be08..23ed0fd0cdaa 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -26,7 +26,7 @@ __revision__ = '$Format:%H$' -from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes +from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes, QgsSpatialIndex from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector @@ -63,13 +63,14 @@ def processAlgorithm(self, progress): writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, layerA.wkbType(), layerA.crs()) - spatialIndex = vector.spatialindex(splitLayer) + spatialIndex = QgsSpatialIndex() splitGeoms = {} request = QgsFeatureRequest() request.setSubsetOfAttributes([]) for aSplitFeature in vector.features(splitLayer, request): splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry() + spatialIndex.insertFeature(aSplitFeature) # honor the case that user has selection on split layer and has setting "use selection" outFeat = QgsFeature() From f70a3b9e1d8bb5a55aaa0aff4c923b2156916d06 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Fri, 18 Nov 2016 10:21:38 +0200 Subject: [PATCH 822/897] [processing] move custom parameter definition inside corresponding algorithm --- .../processing/algs/qgis/FieldsMapper.py | 36 ++++++++++- .../processing/algs/qgis/fieldsmapping.py | 62 ------------------- 2 files changed, 34 insertions(+), 64 deletions(-) delete mode 100644 python/plugins/processing/algs/qgis/fieldsmapping.py diff --git a/python/plugins/processing/algs/qgis/FieldsMapper.py b/python/plugins/processing/algs/qgis/FieldsMapper.py index bd9da22b610c..ce7aff03b925 100644 --- a/python/plugins/processing/algs/qgis/FieldsMapper.py +++ b/python/plugins/processing/algs/qgis/FieldsMapper.py @@ -16,6 +16,7 @@ * * *************************************************************************** """ +from __future__ import print_function from builtins import str from builtins import range @@ -33,11 +34,10 @@ from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.parameters import ParameterTable +from processing.core.parameters import Parameter from processing.core.outputs import OutputVector from processing.tools import dataobjects, vector -from .fieldsmapping import ParameterFieldsMapping - class FieldsMapper(GeoAlgorithm): @@ -55,6 +55,38 @@ def defineCharacteristics(self): self.addParameter(ParameterTable(self.INPUT_LAYER, self.tr('Input layer'), False)) + + class ParameterFieldsMapping(Parameter): + + default_metadata = { + 'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper' + } + + def __init__(self, name='', description='', parent=None): + Parameter.__init__(self, name, description) + self.parent = parent + self.value = [] + + def getValueAsCommandLineParameter(self): + return '"' + str(self.value) + '"' + + def setValue(self, value): + if value is None: + return False + if isinstance(value, list): + self.value = value + return True + if isinstance(value, str): + try: + self.value = eval(value) + return True + except Exception as e: + # fix_print_with_import + print(str(e)) # display error in console + return False + return False + + self.addParameter(ParameterFieldsMapping(self.FIELDS_MAPPING, self.tr('Fields mapping'), self.INPUT_LAYER)) diff --git a/python/plugins/processing/algs/qgis/fieldsmapping.py b/python/plugins/processing/algs/qgis/fieldsmapping.py deleted file mode 100644 index 12f4750a4402..000000000000 --- a/python/plugins/processing/algs/qgis/fieldsmapping.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - FieldsMapper.py - --------------------- - Date : October 2014 - Copyright : (C) 2014 by Arnaud Morvan - Email : arnaud dot morvan at camptocamp dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" -from __future__ import print_function -from builtins import str - -__author__ = 'Arnaud Morvan' -__date__ = 'October 2014' -__copyright__ = '(C) 2014, Arnaud Morvan' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - - -from processing.core.parameters import Parameter - - -class ParameterFieldsMapping(Parameter): - - default_metadata = { - 'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper' - } - - def __init__(self, name='', description='', parent=None): - Parameter.__init__(self, name, description) - self.parent = parent - self.value = [] - - def getValueAsCommandLineParameter(self): - return '"' + str(self.value) + '"' - - def setValue(self, value): - if value is None: - return False - if isinstance(value, list): - self.value = value - return True - if isinstance(value, str): - try: - self.value = eval(value) - return True - except Exception as e: - # fix_print_with_import - print(str(e)) # display error in console - return False - return False From 9679b6a68a081b4d49451903af9c8fd0636259dd Mon Sep 17 00:00:00 2001 From: Mathieu Pellerin Date: Sat, 19 Nov 2016 10:45:24 +0700 Subject: [PATCH 823/897] [style dock] add minimum height to svg image list (#3786) --- src/ui/symbollayer/widget_svgfill.ui | 6 ++++++ src/ui/symbollayer/widget_svgmarker.ui | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/ui/symbollayer/widget_svgfill.ui b/src/ui/symbollayer/widget_svgfill.ui index 072f082711b6..aaa2158906ac 100644 --- a/src/ui/symbollayer/widget_svgfill.ui +++ b/src/ui/symbollayer/widget_svgfill.ui @@ -274,6 +274,12 @@
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + + + 0 + 250 + + 5 diff --git a/src/ui/symbollayer/widget_svgmarker.ui b/src/ui/symbollayer/widget_svgmarker.ui index a44e16b03828..0d38ecf54abe 100644 --- a/src/ui/symbollayer/widget_svgmarker.ui +++ b/src/ui/symbollayer/widget_svgmarker.ui @@ -170,6 +170,12 @@ 1 + + + 0 + 250 + + QAbstractItemView::NoEditTriggers From cac8de5b1f3800b2118bbca91c331c1c892aafb9 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 19 Nov 2016 15:51:15 +1000 Subject: [PATCH 824/897] Swap order of layers in relation add dialog Make parent layer come before child layer --- src/ui/qgsrelationadddlgbase.ui | 81 ++++++++++++++++----------------- 1 file changed, 40 insertions(+), 41 deletions(-) diff --git a/src/ui/qgsrelationadddlgbase.ui b/src/ui/qgsrelationadddlgbase.ui index 9e962112de61..60415adb8a8c 100644 --- a/src/ui/qgsrelationadddlgbase.ui +++ b/src/ui/qgsrelationadddlgbase.ui @@ -14,86 +14,85 @@ Add relation - - - - - - - - + + - Referencing Field + Name - - + + + + + - Referenced Layer (Parent) + Id - - - - Referenced Field + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - + Referencing Layer (Child) - - + + + + + - Name + Referencing Field - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + Referenced Layer (Parent) - - + + - Id + Referenced Field - + + + + - + + + + mTxtRelationName - mCbxReferencingLayer - mCbxReferencingField mCbxReferencedLayer mCbxReferencedField + mCbxReferencingLayer + mCbxReferencingField mTxtRelationId - mButtonBox From b4533cdec01bc21a41e6ef52d2eeae4481eff52f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Sat, 19 Nov 2016 16:04:11 +1000 Subject: [PATCH 825/897] Use standard map layer and field combo boxes in relation add dialog --- src/app/qgsrelationadddlg.cpp | 65 ++++++++-------------------- src/app/qgsrelationadddlg.h | 9 ---- src/app/qgsrelationmanagerdialog.cpp | 3 +- src/ui/qgsrelationadddlgbase.ui | 20 +++++++-- 4 files changed, 36 insertions(+), 61 deletions(-) diff --git a/src/app/qgsrelationadddlg.cpp b/src/app/qgsrelationadddlg.cpp index 648411d893da..3b44e4973931 100644 --- a/src/app/qgsrelationadddlg.cpp +++ b/src/app/qgsrelationadddlg.cpp @@ -16,6 +16,7 @@ #include "qgsrelationadddlg.h" #include "qgsvectorlayer.h" +#include "qgsmaplayerproxymodel.h" #include @@ -24,45 +25,41 @@ QgsRelationAddDlg::QgsRelationAddDlg( QWidget *parent ) { setupUi( this ); - mTxtRelationId->setPlaceholderText( tr( "[Generated automatically]" ) ); - checkDefinitionValid(); + connect( mCbxReferencingLayer, &QgsMapLayerComboBox::layerChanged, this, [=]( QgsMapLayer * layer ) { mCbxReferencingField->setLayer( layer ); } + ); + connect( mCbxReferencedLayer, &QgsMapLayerComboBox::layerChanged, this, [=]( QgsMapLayer * layer ) { mCbxReferencedField->setLayer( layer ); } + ); - connect( mCbxReferencingLayer, SIGNAL( currentIndexChanged( int ) ), this, SLOT( checkDefinitionValid() ) ); - connect( mCbxReferencingField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( checkDefinitionValid() ) ); - connect( mCbxReferencedLayer, SIGNAL( currentIndexChanged( int ) ), this, SLOT( checkDefinitionValid() ) ); - connect( mCbxReferencedField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( checkDefinitionValid() ) ); -} - -void QgsRelationAddDlg::addLayers( const QList< QgsVectorLayer* >& layers ) -{ - mCbxReferencingLayer->addItem( QLatin1String( "" ), "" ); - mCbxReferencedLayer->addItem( QLatin1String( "" ), "" ); + mCbxReferencingLayer->setFilters( QgsMapLayerProxyModel::VectorLayer ); + mCbxReferencingField->setLayer( mCbxReferencingLayer->currentLayer() ); + mCbxReferencedLayer->setFilters( QgsMapLayerProxyModel::VectorLayer ); + mCbxReferencedField->setLayer( mCbxReferencedLayer->currentLayer() ); - Q_FOREACH ( QgsVectorLayer* layer, layers ) - { - mCbxReferencingLayer->addItem( layer->name(), layer->id() ); - mCbxReferencedLayer->addItem( layer->name(), layer->id() ); + mTxtRelationId->setPlaceholderText( tr( "[Generated automatically]" ) ); + checkDefinitionValid(); - mLayers.insert( layer->id(), layer ); - } + connect( mCbxReferencingLayer, &QgsMapLayerComboBox::layerChanged, this, &QgsRelationAddDlg::checkDefinitionValid ); + connect( mCbxReferencingField, &QgsFieldComboBox::fieldChanged, this, &QgsRelationAddDlg::checkDefinitionValid ); + connect( mCbxReferencedLayer, &QgsMapLayerComboBox::layerChanged, this, &QgsRelationAddDlg::checkDefinitionValid ); + connect( mCbxReferencedField, &QgsFieldComboBox::fieldChanged, this, &QgsRelationAddDlg::checkDefinitionValid ); } QString QgsRelationAddDlg::referencingLayerId() { - return mCbxReferencingLayer->currentData().toString(); + return mCbxReferencingLayer->currentLayer()->id(); } QString QgsRelationAddDlg::referencedLayerId() { - return mCbxReferencedLayer->currentData().toString(); + return mCbxReferencedLayer->currentLayer()->id(); } QList< QPair< QString, QString > > QgsRelationAddDlg::references() { QList< QPair< QString, QString > > references; - QString referencingField = mCbxReferencingField->currentData().toString(); - QString referencedField = mCbxReferencedField->currentData().toString(); + QString referencingField = mCbxReferencingField->currentField(); + QString referencedField = mCbxReferencedField->currentField(); references.append( QPair ( referencingField, referencedField ) ); @@ -79,15 +76,6 @@ QString QgsRelationAddDlg::relationName() return mTxtRelationName->text(); } -void QgsRelationAddDlg::on_mCbxReferencingLayer_currentIndexChanged( int index ) -{ - loadLayerAttributes( mCbxReferencingField, mLayers[mCbxReferencingLayer->itemData( index ).toString()] ); -} - -void QgsRelationAddDlg::on_mCbxReferencedLayer_currentIndexChanged( int index ) -{ - loadLayerAttributes( mCbxReferencedField, mLayers[mCbxReferencedLayer->itemData( index ).toString()] ); -} void QgsRelationAddDlg::checkDefinitionValid() { @@ -96,18 +84,3 @@ void QgsRelationAddDlg::checkDefinitionValid() && mCbxReferencingLayer->currentIndex() != -1 && mCbxReferencingField->currentIndex() != -1 ); } - -void QgsRelationAddDlg::loadLayerAttributes( QComboBox* cbx, QgsVectorLayer* layer ) -{ - cbx->clear(); - - if ( !layer ) - { - return; - } - - Q_FOREACH ( const QgsField& fld, layer->fields().toList() ) - { - cbx->addItem( fld.name(), fld.name() ); - } -} diff --git a/src/app/qgsrelationadddlg.h b/src/app/qgsrelationadddlg.h index 35cb5eebf66a..696217cbf4a5 100644 --- a/src/app/qgsrelationadddlg.h +++ b/src/app/qgsrelationadddlg.h @@ -27,8 +27,6 @@ class APP_EXPORT QgsRelationAddDlg : public QDialog, private Ui::QgsRelationAddD public: explicit QgsRelationAddDlg( QWidget *parent = nullptr ); - void addLayers( const QList& layers ); - QString referencingLayerId(); QString referencedLayerId(); QList< QPair< QString, QString > > references(); @@ -37,16 +35,9 @@ class APP_EXPORT QgsRelationAddDlg : public QDialog, private Ui::QgsRelationAddD private slots: - void on_mCbxReferencingLayer_currentIndexChanged( int index ); - void on_mCbxReferencedLayer_currentIndexChanged( int index ); void checkDefinitionValid(); - private: - void loadLayerAttributes( QComboBox* cbx, QgsVectorLayer* layer ); - - QMap< QString, QgsVectorLayer* > mLayers; - }; #endif // QGSRELATIONADDDLG_H diff --git a/src/app/qgsrelationmanagerdialog.cpp b/src/app/qgsrelationmanagerdialog.cpp index 89dd39bf7bcd..e77a9450d121 100644 --- a/src/app/qgsrelationmanagerdialog.cpp +++ b/src/app/qgsrelationmanagerdialog.cpp @@ -84,7 +84,6 @@ void QgsRelationManagerDialog::addRelation( const QgsRelation &rel ) void QgsRelationManagerDialog::on_mBtnAddRelation_clicked() { QgsRelationAddDlg addDlg; - addDlg.addLayers( mLayers ); if ( addDlg.exec() ) { @@ -164,4 +163,4 @@ QList< QgsRelation > QgsRelationManagerDialog::relations() void QgsRelationManagerDialog::onSelectionChanged() { mBtnRemoveRelation->setEnabled( mRelationsTable->selectionModel()->hasSelection() ); -} \ No newline at end of file +} diff --git a/src/ui/qgsrelationadddlgbase.ui b/src/ui/qgsrelationadddlgbase.ui index 60415adb8a8c..6ad2e991fb38 100644 --- a/src/ui/qgsrelationadddlgbase.ui +++ b/src/ui/qgsrelationadddlgbase.ui @@ -22,7 +22,7 @@ - + @@ -49,7 +49,7 @@ - + @@ -73,19 +73,31 @@ - + - +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + + + QgsMapLayerComboBox + QComboBox +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgsmaplayercombobox.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  + + QgsFieldComboBox + QComboBox +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  qgsfieldcombobox.h
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  mTxtRelationName mCbxReferencedLayer From a958c8a7984d77d617dcbee6b0c61ce83c406cfa Mon Sep 17 00:00:00 2001 From: nirvn Date: Sat, 19 Nov 2016 11:44:02 +0700 Subject: [PATCH 826/897] [style] add createMemoryDB() to QgsStyle to create temporary db --- python/core/symbology-ng/qgsstyle.sip | 3 ++ src/core/symbology-ng/qgsstyle.cpp | 68 ++++++++++++++++++++++++++- src/core/symbology-ng/qgsstyle.h | 14 +++++- 3 files changed, 82 insertions(+), 3 deletions(-) diff --git a/python/core/symbology-ng/qgsstyle.sip b/python/core/symbology-ng/qgsstyle.sip index 1b286699576e..4203ac18a464 100644 --- a/python/core/symbology-ng/qgsstyle.sip +++ b/python/core/symbology-ng/qgsstyle.sip @@ -208,6 +208,9 @@ class QgsStyle : QObject //! Changes ramp's name bool renameColorRamp( const QString& oldName, const QString& newName ); + //! Creates a temporary memory database + bool createMemoryDB(); + //! Loads a file into the style bool load( const QString& filename ); diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index e1f8e864f728..547566059dae 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -289,6 +289,42 @@ bool QgsStyle::openDB( const QString& filename ) return true; } +bool QgsStyle::createMemoryDB() +{ + mErrorString.clear(); + if ( !openDB( QStringLiteral( ":memory:" ) ) ) + { + mErrorString = QStringLiteral( "Unable to create temporary memory database" ); + QgsDebugMsg( mErrorString ); + return false; + } + char *query = sqlite3_mprintf( "CREATE TABLE symbol("\ + "id INTEGER PRIMARY KEY,"\ + "name TEXT UNIQUE,"\ + "xml TEXT,"\ + "favorite INTEGER);"\ + "CREATE TABLE colorramp("\ + "id INTEGER PRIMARY KEY,"\ + "name TEXT UNIQUE,"\ + "xml TEXT,"\ + "favorite INTEGER);"\ + "CREATE TABLE tag("\ + "id INTEGER PRIMARY KEY,"\ + "name TEXT);"\ + "CREATE TABLE tagmap("\ + "tag_id INTEGER NOT NULL,"\ + "symbol_id INTEGER);"\ + "CREATE TABLE ctagmap("\ + "tag_id INTEGER NOT NULL,"\ + "colorramp_id INTEGER);"\ + "CREATE TABLE smartgroup("\ + "id INTEGER PRIMARY KEY,"\ + "name TEXT,"\ + "xml TEXT);" ); + runEmptyQuery( query ); + return true; +} + bool QgsStyle::load( const QString& filename ) { mErrorString.clear(); @@ -1391,14 +1427,42 @@ bool QgsStyle::exportXml( const QString& filename ) root.setAttribute( QStringLiteral( "version" ), STYLE_CURRENT_VERSION ); doc.appendChild( root ); - // TODO work on the groups and tags + QStringList favoriteSymbols = symbolsOfFavorite( SymbolEntity ); + QStringList favoriteColorramps = symbolsOfFavorite( ColorrampEntity ); + + // save symbols and attach tags QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( mSymbols, QStringLiteral( "symbols" ), doc ); - QDomElement rampsElem = doc.createElement( QStringLiteral( "colorramps" ) ); + QDomNodeList symbolsList = symbolsElem.elementsByTagName( QStringLiteral( "symbol" ) ); + int nbSymbols = symbolsList.count(); + for ( int i = 0; i < nbSymbols; ++i ) + { + QDomElement symbol = symbolsList.at( i ).toElement(); + QString name = symbol.attribute( QStringLiteral( "name" ) ); + QStringList tags = tagsOfSymbol( SymbolEntity, name ); + if ( tags.count() > 0 ) + { + symbol.setAttribute( QStringLiteral( "tags" ), tags.join( "," ) ); + } + if ( favoriteSymbols.contains( name ) ) + { + symbol.setAttribute( QStringLiteral( "favorite" ), "1" ); + } + } // save color ramps + QDomElement rampsElem = doc.createElement( QStringLiteral( "colorramps" ) ); for ( QMap::const_iterator itr = mColorRamps.constBegin(); itr != mColorRamps.constEnd(); ++itr ) { QDomElement rampEl = QgsSymbolLayerUtils::saveColorRamp( itr.key(), itr.value(), doc ); + QStringList tags = tagsOfSymbol( ColorrampEntity, itr.key() ); + if ( tags.count() > 0 ) + { + rampEl.setAttribute( QStringLiteral( "tags" ), tags.join( "," ) ); + } + if ( favoriteColorramps.contains( itr.key() ) ) + { + rampEl.setAttribute( QStringLiteral( "favorite" ), "1" ); + } rampsElem.appendChild( rampEl ); } diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index de5d0eadb5f7..3eb6db1aed78 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -273,7 +273,19 @@ class CORE_EXPORT QgsStyle : public QObject //! Changes ramp's name bool renameColorRamp( const QString& oldName, const QString& newName ); - //! Loads a file into the style + /** Creates a temporary memory database + * + * This function is used if you do not need to associate styles with a permanent on-disk database. + * \return returns the success state of the temporary memory database creation + */ + bool createMemoryDB(); + + /** Loads a file into the style + * + * This function will populate styles from an on-disk database. + * \param filename location of the database to load styles from + * \return returns the success state of the database being loaded + */ bool load( const QString& filename ); //! Saves style into a file (will use current filename if empty string is passed) From 08f8ca7ebd5bcd55f2aebbbf884e1da35388ded8 Mon Sep 17 00:00:00 2001 From: nirvn Date: Sat, 19 Nov 2016 12:15:23 +0700 Subject: [PATCH 827/897] [FEATURE][style manager] import/export of symbols' tags and favorite flag --- src/core/symbology-ng/qgsstyle.cpp | 46 +++++++++++++--- .../qgsstyleexportimportdialog.cpp | 54 ++++++++++++------- src/ui/qgsstyleexportimportdialogbase.ui | 21 ++++++-- 3 files changed, 91 insertions(+), 30 deletions(-) diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index 547566059dae..3fdde38c140e 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -1533,10 +1533,26 @@ bool QgsStyle::importXml( const QString& filename ) { if ( e.tagName() == QLatin1String( "symbol" ) ) { + QString name = e.attribute( QStringLiteral( "name" ) ); + QStringList tags; + if ( e.hasAttribute( QStringLiteral( "tags" ) ) ) + { + tags = e.attribute( QStringLiteral( "tags" ) ).split( "," ); + } + bool favorite = false; + if ( e.hasAttribute( QStringLiteral( "favorite" ) ) && e.attribute( QStringLiteral( "favorite" ) ) == "1" ) + { + favorite = true; + } + QgsSymbol* symbol = QgsSymbolLayerUtils::loadSymbol( e ); if ( symbol ) { - symbols.insert( e.attribute( QStringLiteral( "name" ) ), symbol ); + addSymbol( name, symbol ); + if ( mCurrentDB ) + { + saveSymbol( name, symbol, favorite, tags ); + } } } else @@ -1550,12 +1566,12 @@ bool QgsStyle::importXml( const QString& filename ) { // for the old version, use the utility function to solve @symbol@layer subsymbols symbols = QgsSymbolLayerUtils::loadSymbols( symbolsElement ); - } - // save the symbols with proper name - for ( QMap::iterator it = symbols.begin(); it != symbols.end(); ++it ) - { - addSymbol( it.key(), it.value() ); + // save the symbols with proper name + for ( QMap::iterator it = symbols.begin(); it != symbols.end(); ++it ) + { + addSymbol( it.key(), it.value() ); + } } // load color ramps @@ -1565,10 +1581,26 @@ bool QgsStyle::importXml( const QString& filename ) { if ( e.tagName() == QLatin1String( "colorramp" ) ) { + QString name = e.attribute( QStringLiteral( "name" ) ); + QStringList tags; + if ( e.hasAttribute( QStringLiteral( "tags" ) ) ) + { + tags = e.attribute( QStringLiteral( "tags" ) ).split( "," ); + } + bool favorite = false; + if ( e.hasAttribute( QStringLiteral( "favorite" ) ) && e.attribute( QStringLiteral( "favorite" ) ) == "1" ) + { + favorite = true; + } + QgsColorRamp* ramp = QgsSymbolLayerUtils::loadColorRamp( e ); if ( ramp ) { - addColorRamp( e.attribute( QStringLiteral( "name" ) ), ramp ); + addColorRamp( name, ramp ); + if ( mCurrentDB ) + { + saveColorRamp( name, ramp, favorite, tags ); + } } } else diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp index 8e3a96127aeb..52ed128c8962 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp @@ -56,6 +56,8 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget this, SLOT( selectionChanged( const QItemSelection&, const QItemSelection& ) ) ); mTempStyle = new QgsStyle(); + mTempStyle->createMemoryDB(); + // TODO validate mFileName = QLatin1String( "" ); mProgressDlg = nullptr; @@ -92,6 +94,7 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget locationLineEdit->setHidden( true ); mFavorite->setHidden( true ); + mIgnoreXMLTags->setHidden( true ); pb = new QPushButton( tr( "Select by group" ) ); buttonBox->addButton( pb, QDialogButtonBox::ActionRole ); @@ -215,25 +218,44 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl { QString symbolName; QgsSymbol* symbol; + QStringList symbolTags; + bool symbolFavorite; QgsColorRamp *ramp = nullptr; QModelIndex index; bool isSymbol = true; bool prompt = true; bool overwrite = true; - QStringList tags; - // get the groupid when going for import - if ( mDialogMode == Import ) - { - // get the name the user entered - tags = mSymbolTags->text().split( ',' ); - } + QStringList importTags = mSymbolTags->text().split( ',' ); + + QStringList favoriteSymbols = src->symbolsOfFavorite( QgsStyle::SymbolEntity ); + QStringList favoriteColorramps = src->symbolsOfFavorite( QgsStyle::ColorrampEntity ); for ( int i = 0; i < selection->size(); ++i ) { index = selection->at( i ); symbolName = index.model()->data( index, 0 ).toString(); symbol = src->symbol( symbolName ); + + if ( !mIgnoreXMLTags->isChecked() ) + { + symbolTags = src->tagsOfSymbol( !symbol ? QgsStyle::ColorrampEntity : QgsStyle::SymbolEntity, symbolName ); + } + else + { + symbolTags.clear(); + } + + if ( mDialogMode == Import ) + { + symbolTags << importTags; + symbolFavorite = mFavorite->isChecked(); + } + else + { + symbolFavorite = !symbol ? favoriteColorramps.contains( symbolName ) : favoriteSymbols.contains( symbolName ); + } + if ( !symbol ) { isSymbol = false; @@ -256,8 +278,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl continue; case QMessageBox::Yes: dst->addSymbol( symbolName, symbol ); - if ( mDialogMode == Import ) - dst->saveSymbol( symbolName, symbol, mFavorite->isChecked(), tags ); + dst->saveSymbol( symbolName, symbol, symbolFavorite, symbolTags ); continue; case QMessageBox::YesToAll: prompt = false; @@ -273,8 +294,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl if ( dst->symbolNames().contains( symbolName ) && overwrite ) { dst->addSymbol( symbolName, symbol ); - if ( mDialogMode == Import ) - dst->saveSymbol( symbolName, symbol, mFavorite->isChecked(), tags ); + dst->saveSymbol( symbolName, symbol, symbolFavorite, symbolTags ); } else if ( dst->symbolNames().contains( symbolName ) && !overwrite ) { @@ -283,8 +303,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl else { dst->addSymbol( symbolName, symbol ); - if ( mDialogMode == Import ) - dst->saveSymbol( symbolName, symbol, mFavorite->isChecked(), tags ); + dst->saveSymbol( symbolName, symbol, symbolFavorite, symbolTags ); } } else @@ -303,8 +322,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl continue; case QMessageBox::Yes: dst->addColorRamp( symbolName, ramp ); - if ( mDialogMode == Import ) - dst->saveColorRamp( symbolName, ramp, mFavorite->isChecked(), tags ); + dst->saveColorRamp( symbolName, ramp, symbolFavorite, symbolTags ); continue; case QMessageBox::YesToAll: prompt = false; @@ -320,8 +338,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl if ( dst->colorRampNames().contains( symbolName ) && overwrite ) { dst->addColorRamp( symbolName, ramp ); - if ( mDialogMode == Import ) - dst->saveColorRamp( symbolName, ramp, mFavorite->isChecked(), tags ); + dst->saveColorRamp( symbolName, ramp, symbolFavorite, symbolTags ); } else if ( dst->colorRampNames().contains( symbolName ) && !overwrite ) { @@ -330,8 +347,7 @@ void QgsStyleExportImportDialog::moveStyles( QModelIndexList* selection, QgsStyl else { dst->addColorRamp( symbolName, ramp ); - if ( mDialogMode == Import ) - dst->saveColorRamp( symbolName, ramp, mFavorite->isChecked() , tags ); + dst->saveColorRamp( symbolName, ramp, symbolFavorite, symbolTags ); } } } diff --git a/src/ui/qgsstyleexportimportdialogbase.ui b/src/ui/qgsstyleexportimportdialogbase.ui index dc1ac29ce77e..dd81ee988c39 100644 --- a/src/ui/qgsstyleexportimportdialogbase.ui +++ b/src/ui/qgsstyleexportimportdialogbase.ui @@ -43,10 +43,10 @@
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  - + - Tag(s) + Additional tag(s) @@ -63,10 +63,23 @@ - - + + + + + 0 + 0 + + + + Do not import embedded tags + + + + + Tip: separate multiple tags with commas From 19368cfbee257d3a4b3d34a8828eb9f1fd831834 Mon Sep 17 00:00:00 2001 From: nirvn Date: Sat, 19 Nov 2016 12:27:34 +0700 Subject: [PATCH 828/897] [style manager] inform users of successful import --- .../symbology-ng/qgsstyleexportimportdialog.cpp | 10 ++++++++-- src/ui/qgsstyleexportimportdialogbase.ui | 17 +++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp index 52ed128c8962..4c107fc4a5c5 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp @@ -151,6 +151,12 @@ void QgsStyleExportImportDialog::doExportImport() .arg( mTempStyle->errorString() ) ); return; } + else + { + QMessageBox::information( this, tr( "Export successful" ), + tr( "The selected symbols were successfully exported to file:\n%1" ) + .arg( mFileName ) ); + } } else // import { @@ -192,7 +198,7 @@ bool QgsStyleExportImportDialog::populateStyles( QgsStyle* style ) name = styleNames[i]; QgsSymbol* symbol = style->symbol( name ); QStandardItem* item = new QStandardItem( name ); - QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize() ); + QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize(), 15 ); item->setIcon( icon ); model->appendRow( item ); delete symbol; @@ -207,7 +213,7 @@ bool QgsStyleExportImportDialog::populateStyles( QgsStyle* style ) QScopedPointer< QgsColorRamp > ramp( style->colorRamp( name ) ); QStandardItem* item = new QStandardItem( name ); - QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.data(), listItems->iconSize() ); + QIcon icon = QgsSymbolLayerUtils::colorRampPreviewIcon( ramp.data(), listItems->iconSize(), 15 ); item->setIcon( icon ); model->appendRow( item ); } diff --git a/src/ui/qgsstyleexportimportdialogbase.ui b/src/ui/qgsstyleexportimportdialogbase.ui index dd81ee988c39..52de6a35e5df 100644 --- a/src/ui/qgsstyleexportimportdialogbase.ui +++ b/src/ui/qgsstyleexportimportdialogbase.ui @@ -111,12 +111,15 @@ - 48 - 48 + 77 + 70 - - QListView::Static + + Qt::ElideNone + + + QListView::LeftToRight QListView::Adjust @@ -127,6 +130,12 @@ QListView::IconMode + + true + + + true + From cc985c2318c80a2867e3fbc8713cce531ee6a4bd Mon Sep 17 00:00:00 2001 From: nirvn Date: Sat, 19 Nov 2016 13:00:11 +0700 Subject: [PATCH 829/897] use temporary memory db for style tests (avoids clash with default symbols) --- tests/src/core/testqgsstyle.cpp | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/tests/src/core/testqgsstyle.cpp b/tests/src/core/testqgsstyle.cpp index 0e2f10cc4d0f..862318093f3b 100644 --- a/tests/src/core/testqgsstyle.cpp +++ b/tests/src/core/testqgsstyle.cpp @@ -93,15 +93,9 @@ void TestStyle::initTestCase() QCoreApplication::setOrganizationDomain( QStringLiteral( "qgis.org" ) ); QCoreApplication::setApplicationName( QStringLiteral( "QGIS-TEST" ) ); - // initialize with a clean style - QFile styleFile( QgsApplication::userStylePath() ); - if ( styleFile.exists() ) - { - styleFile.remove(); - QgsDebugMsg( "removed user style file " + styleFile.fileName() ); - } - mStyle = QgsStyle::defaultStyle(); - // mStyle->clear(); + //initize a temporary memory-based style for tests to avoid clashing with shipped symbols + mStyle = new QgsStyle(); + mStyle->createMemoryDB(); // cpt-city ramp, small selection available in /cpt-city QgsCptCityArchive::initArchives(); @@ -114,6 +108,7 @@ void TestStyle::cleanupTestCase() // don't save // mStyle->save(); delete mStyle; + QgsCptCityArchive::clearArchives(); QgsApplication::exitQgis(); @@ -186,8 +181,7 @@ void TestStyle::testCreateColorRamps() void TestStyle::testLoadColorRamps() { QStringList colorRamps = mStyle->colorRampNames(); - QStringList colorRampsTest = QStringList() << QStringLiteral( "BrBG" ) << QStringLiteral( "Spectral" ) - << QStringLiteral( "test_gradient" ) << QStringLiteral( "test_random" ) + QStringList colorRampsTest = QStringList() << QStringLiteral( "test_gradient" ) << QStringLiteral( "test_random" ) << QStringLiteral( "test_cb1" ) << QStringLiteral( "test_cb2" ); // values for color tests @@ -235,11 +229,6 @@ void TestStyle::testLoadColorRamps() void TestStyle::testSaveLoad() { - // save not needed anymore, because used update=true in addColorRamp() - // mStyle->save(); - mStyle->clear(); - mStyle->load( QgsApplication::userStylePath() ); - // basic test to see that ramp is present QStringList colorRamps = mStyle->colorRampNames(); QgsDebugMsg( "loaded colorRamps: " + colorRamps.join( " " ) ); @@ -261,8 +250,6 @@ void TestStyle::testSaveLoad() void TestStyle::testFavorites() { - mStyle->clear(); - // save initial number of favorites to compare against additions / substractions QStringList favorites; favorites = mStyle->symbolsOfFavorite( QgsStyle::SymbolEntity ); @@ -290,7 +277,6 @@ void TestStyle::testFavorites() void TestStyle::testTags() { - mStyle->clear(); //add some tags int id = mStyle->addTag( QStringLiteral( "red" ) ); QCOMPARE( id, mStyle->tagId( "red" ) ); From 2260780402b1724c78da8f7513c6d42dc7f9ea9a Mon Sep 17 00:00:00 2001 From: nirvn Date: Sun, 20 Nov 2016 10:16:35 +0700 Subject: [PATCH 830/897] [style manager] decrease font size and add name & tags tooltip for the import/export symbol preview list --- src/gui/symbology-ng/qgsstyleexportimportdialog.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp index 4c107fc4a5c5..67114e959a70 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp @@ -50,7 +50,6 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget connect( pb, SIGNAL( clicked() ), this, SLOT( clearSelection() ) ); QStandardItemModel* model = new QStandardItemModel( listItems ); - listItems->setModel( model ); connect( listItems->selectionModel(), SIGNAL( selectionChanged( const QItemSelection&, const QItemSelection& ) ), this, SLOT( selectionChanged( const QItemSelection&, const QItemSelection& ) ) ); @@ -196,10 +195,16 @@ bool QgsStyleExportImportDialog::populateStyles( QgsStyle* style ) for ( int i = 0; i < styleNames.count(); ++i ) { name = styleNames[i]; + QStringList tags = style->tagsOfSymbol( QgsStyle::SymbolEntity, name ); QgsSymbol* symbol = style->symbol( name ); QStandardItem* item = new QStandardItem( name ); QIcon icon = QgsSymbolLayerUtils::symbolPreviewIcon( symbol, listItems->iconSize(), 15 ); item->setIcon( icon ); + item->setToolTip( QString( "%1
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  %2" ).arg( name ).arg( tags.count() > 0 ? tags.join( ", " ) : tr( "Not tagged" ) ) ); + // Set font to 10points to show reasonable text + QFont itemFont = item->font(); + itemFont.setPointSize( 10 ); + item->setFont( itemFont ); model->appendRow( item ); delete symbol; } From 4c2725b0699f95a91b7e005f7ac7d1b1bd8ace80 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 12:36:32 -0700 Subject: [PATCH 831/897] Use Qt5 non-OpenSSL define in testing for SSL support --- src/app/qgisapp.cpp | 8 ++++---- src/app/qgisapp.h | 2 +- src/auth/identcert/qgsauthidentcertmethod.cpp | 2 +- src/auth/pkipaths/qgsauthpkipathsmethod.cpp | 2 +- src/auth/pkipkcs12/qgsauthpkcs12method.cpp | 2 +- src/core/auth/qgsauthconfig.cpp | 2 +- src/core/auth/qgsauthconfig.h | 4 ++-- src/core/auth/qgsauthmanager.cpp | 8 ++++---- src/core/auth/qgsauthmanager.h | 8 ++++---- src/core/qgsnetworkaccessmanager.cpp | 6 +++--- src/gui/auth/qgsauthcertificateinfo.h | 2 +- src/gui/qgsfiledownloader.cpp | 6 +++--- src/gui/qgsfiledownloader.h | 4 ++-- tests/src/gui/testqgsfiledownloader.cpp | 4 ++-- 14 files changed, 30 insertions(+), 30 deletions(-) diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 9c5b99b7cf70..8d468859d3d2 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -54,7 +54,7 @@ #include #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #endif #include @@ -110,7 +110,7 @@ #include "qgsattributedialog.h" #include "qgsauthmanager.h" #include "qgsauthguiutils.h" -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include "qgsauthcertutils.h" #include "qgsauthsslerrorsdialog.h" #endif @@ -11521,7 +11521,7 @@ void QgisApp::namSetup() connect( nam, SIGNAL( requestTimedOut( QNetworkReply* ) ), this, SLOT( namRequestTimedOut( QNetworkReply* ) ) ); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL connect( nam, SIGNAL( sslErrors( QNetworkReply *, const QList & ) ), this, SLOT( namSslErrors( QNetworkReply *, const QList & ) ) ); #endif @@ -11643,7 +11643,7 @@ void QgisApp::namProxyAuthenticationRequired( const QNetworkProxy &proxy, QAuthe auth->setPassword( password ); } -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL void QgisApp::namSslErrors( QNetworkReply *reply, const QList &errors ) { // stop the timeout timer, or app crashes if the user (or slot) takes longer than diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index cbf2a7a393d4..22e0c624353a 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -674,7 +674,7 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow //! request credentials for network manager void namAuthenticationRequired( QNetworkReply *reply, QAuthenticator *auth ); void namProxyAuthenticationRequired( const QNetworkProxy &proxy, QAuthenticator *auth ); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL void namSslErrors( QNetworkReply *reply, const QList &errors ); #endif void namRequestTimedOut( QNetworkReply *reply ); diff --git a/src/auth/identcert/qgsauthidentcertmethod.cpp b/src/auth/identcert/qgsauthidentcertmethod.cpp index a94d524fa017..25865e7567ab 100644 --- a/src/auth/identcert/qgsauthidentcertmethod.cpp +++ b/src/auth/identcert/qgsauthidentcertmethod.cpp @@ -20,7 +20,7 @@ #include #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #include #include diff --git a/src/auth/pkipaths/qgsauthpkipathsmethod.cpp b/src/auth/pkipaths/qgsauthpkipathsmethod.cpp index 92c1897b2181..1676a0656c90 100644 --- a/src/auth/pkipaths/qgsauthpkipathsmethod.cpp +++ b/src/auth/pkipaths/qgsauthpkipathsmethod.cpp @@ -20,7 +20,7 @@ #include #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #include #include diff --git a/src/auth/pkipkcs12/qgsauthpkcs12method.cpp b/src/auth/pkipkcs12/qgsauthpkcs12method.cpp index b0d0b0651f02..ca1a73671c49 100644 --- a/src/auth/pkipkcs12/qgsauthpkcs12method.cpp +++ b/src/auth/pkipkcs12/qgsauthpkcs12method.cpp @@ -20,7 +20,7 @@ #include #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #include #include diff --git a/src/core/auth/qgsauthconfig.cpp b/src/core/auth/qgsauthconfig.cpp index 9036c37f1e44..4560ac405c82 100644 --- a/src/core/auth/qgsauthconfig.cpp +++ b/src/core/auth/qgsauthconfig.cpp @@ -156,7 +156,7 @@ bool QgsAuthMethodConfig::uriToResource( const QString &accessurl, QString *reso } -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL ////////////////////////////////////////////////////// // QgsPkiBundle diff --git a/src/core/auth/qgsauthconfig.h b/src/core/auth/qgsauthconfig.h index e95195126569..ac103fd27005 100644 --- a/src/core/auth/qgsauthconfig.h +++ b/src/core/auth/qgsauthconfig.h @@ -20,7 +20,7 @@ #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #include #include @@ -177,7 +177,7 @@ class CORE_EXPORT QgsAuthMethodConfig typedef QHash QgsAuthMethodConfigsMap; -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL /** \ingroup core * \brief Storage set for PKI bundle: SSL certificate, key, optional CA cert chain diff --git a/src/core/auth/qgsauthmanager.cpp b/src/core/auth/qgsauthmanager.cpp index 9516d63133a4..ccbb5148e3ff 100644 --- a/src/core/auth/qgsauthmanager.cpp +++ b/src/core/auth/qgsauthmanager.cpp @@ -33,7 +33,7 @@ #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #endif @@ -197,7 +197,7 @@ bool QgsAuthManager::init( const QString& pluginPath ) updateConfigAuthMethods(); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL initSslCaches(); #endif @@ -258,7 +258,7 @@ bool QgsAuthManager::init( const QString& pluginPath ) return false; } -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL initSslCaches(); #endif @@ -1572,7 +1572,7 @@ bool QgsAuthManager::removeAuthSetting( const QString& key ) } -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL ////////////////// Certificate calls /////////////////////// diff --git a/src/core/auth/qgsauthmanager.h b/src/core/auth/qgsauthmanager.h index 4f6463f85427..9f241f9c7270 100644 --- a/src/core/auth/qgsauthmanager.h +++ b/src/core/auth/qgsauthmanager.h @@ -26,7 +26,7 @@ #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #include #include @@ -339,7 +339,7 @@ class CORE_EXPORT QgsAuthManager : public QObject //! Remove an authentication setting bool removeAuthSetting( const QString& key ); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL ////////////////// Certificate calls /////////////////////// //! Initialize various SSL authentication caches @@ -581,7 +581,7 @@ class CORE_EXPORT QgsAuthManager : public QObject bool authDbTransactionQuery( QSqlQuery *query ) const; -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL void insertCaCertInCache( QgsAuthCertUtils::CaCertSource source, const QList &certs ); #endif @@ -625,7 +625,7 @@ class CORE_EXPORT QgsAuthManager : public QObject int mScheduledDbEraseRequestCount; QMutex *mMutex; -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL // mapping of sha1 digest and cert source and cert // appending removes duplicates QMap > mCaCertsCache; diff --git a/src/core/qgsnetworkaccessmanager.cpp b/src/core/qgsnetworkaccessmanager.cpp index f5faafe33056..d9d66b650ffc 100644 --- a/src/core/qgsnetworkaccessmanager.cpp +++ b/src/core/qgsnetworkaccessmanager.cpp @@ -32,7 +32,7 @@ #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #endif @@ -182,7 +182,7 @@ QNetworkReply *QgsNetworkAccessManager::createRequest( QNetworkAccessManager::Op userAgent += QStringLiteral( "QGIS/%1" ).arg( Qgis::QGIS_VERSION ); pReq->setRawHeader( "User-Agent", userAgent.toUtf8() ); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL bool ishttps = pReq->url().scheme().toLower() == QLatin1String( "https" ); if ( ishttps && !QgsAuthManager::instance()->isDisabled() ) { @@ -305,7 +305,7 @@ void QgsNetworkAccessManager::setupDefaultProxyAndCache() connect( this, SIGNAL( requestTimedOut( QNetworkReply* ) ), smMainNAM, SIGNAL( requestTimedOut( QNetworkReply* ) ) ); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL connect( this, SIGNAL( sslErrors( QNetworkReply *, const QList & ) ), smMainNAM, SIGNAL( sslErrors( QNetworkReply *, const QList & ) ), Qt::BlockingQueuedConnection ); diff --git a/src/gui/auth/qgsauthcertificateinfo.h b/src/gui/auth/qgsauthcertificateinfo.h index 70d5c47349d6..31c5658da5d5 100644 --- a/src/gui/auth/qgsauthcertificateinfo.h +++ b/src/gui/auth/qgsauthcertificateinfo.h @@ -20,7 +20,7 @@ #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #include #endif diff --git a/src/gui/qgsfiledownloader.cpp b/src/gui/qgsfiledownloader.cpp index 761d8a105600..a23ea47c5456 100644 --- a/src/gui/qgsfiledownloader.cpp +++ b/src/gui/qgsfiledownloader.cpp @@ -20,7 +20,7 @@ #include #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #endif @@ -64,7 +64,7 @@ void QgsFileDownloader::startDownload() connect( mReply, &QNetworkReply::finished, this, &QgsFileDownloader::onFinished ); connect( mReply, &QNetworkReply::downloadProgress, this, &QgsFileDownloader::onDownloadProgress ); connect( nam, &QgsNetworkAccessManager::requestTimedOut, this, &QgsFileDownloader::onRequestTimedOut ); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL connect( nam, &QgsNetworkAccessManager::sslErrors, this, &QgsFileDownloader::onSslErrors ); #endif if ( mGuiNotificationsEnabled ) @@ -89,7 +89,7 @@ void QgsFileDownloader::onRequestTimedOut() error( tr( "Network request %1 timed out" ).arg( mUrl.toString() ) ); } -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL void QgsFileDownloader::onSslErrors( QNetworkReply *reply, const QList &errors ) { Q_UNUSED( reply ); diff --git a/src/gui/qgsfiledownloader.h b/src/gui/qgsfiledownloader.h index ab4d6169bbf7..4eb4a98d97ef 100644 --- a/src/gui/qgsfiledownloader.h +++ b/src/gui/qgsfiledownloader.h @@ -20,7 +20,7 @@ #include #include #include -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL #include #endif @@ -87,7 +87,7 @@ class GUI_EXPORT QgsFileDownloader : public QObject void onRequestTimedOut(); //! Called to start the download void startDownload(); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL /** * Called on SSL network Errors diff --git a/tests/src/gui/testqgsfiledownloader.cpp b/tests/src/gui/testqgsfiledownloader.cpp index f6b139139e08..b9e98dcab83c 100644 --- a/tests/src/gui/testqgsfiledownloader.cpp +++ b/tests/src/gui/testqgsfiledownloader.cpp @@ -82,7 +82,7 @@ class TestQgsFileDownloader: public QObject void testInvalidFile(); void testInvalidUrl(); void testBlankUrl(); -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL void testSslError_data(); void testSslError(); #endif @@ -219,7 +219,7 @@ void TestQgsFileDownloader::testBlankUrl() QCOMPARE( mErrorMessage, QString( "Network error 301: Protocol \"\" is unknown" ) ); } -#ifndef QT_NO_OPENSSL +#ifndef QT_NO_SSL void TestQgsFileDownloader::testSslError_data() { QTest::addColumn( "url" ); From e9fa3e0488cfd5662a19610182c85b2282ada74d Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 12:37:34 -0700 Subject: [PATCH 832/897] Check for Qt5 subdirectory in PYQT5_SIP_DIR --- cmake/FindPyQt5.cmake | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cmake/FindPyQt5.cmake b/cmake/FindPyQt5.cmake index 5f8e8d18d091..0fcf1b5bdff3 100644 --- a/cmake/FindPyQt5.cmake +++ b/cmake/FindPyQt5.cmake @@ -37,6 +37,9 @@ ELSE(EXISTS PYQT5_VERSION) STRING(REGEX REPLACE ".*\npyqt_version_num:([^\n]+).*$" "\\1" PYQT5_VERSION_NUM ${pyqt_config}) STRING(REGEX REPLACE ".*\npyqt_mod_dir:([^\n]+).*$" "\\1" PYQT5_MOD_DIR ${pyqt_config}) STRING(REGEX REPLACE ".*\npyqt_sip_dir:([^\n]+).*$" "\\1" PYQT5_SIP_DIR ${pyqt_config}) + IF(EXISTS ${PYQT5_SIP_DIR}/Qt5) + SET(PYQT5_SIP_DIR ${PYQT5_SIP_DIR}/Qt5) + ENDIF(EXISTS ${PYQT5_SIP_DIR}/Qt5) STRING(REGEX REPLACE ".*\npyqt_sip_flags:([^\n]+).*$" "\\1" PYQT5_SIP_FLAGS ${pyqt_config}) STRING(REGEX REPLACE ".*\npyqt_bin_dir:([^\n]+).*$" "\\1" PYQT5_BIN_DIR ${pyqt_config}) From 74dfd1f4b021631ff122d5cece4ba5bfdc489270 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 12:39:41 -0700 Subject: [PATCH 833/897] Check for Qt5-specific version of Mac qca framework --- cmake/FindQCA.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/FindQCA.cmake b/cmake/FindQCA.cmake index 612420668713..e715188726ee 100644 --- a/cmake/FindQCA.cmake +++ b/cmake/FindQCA.cmake @@ -32,7 +32,7 @@ else(QCA_INCLUDE_DIR AND QCA_LIBRARY) ) if(APPLE) - if(QCA_LIBRARY AND QCA_LIBRARY MATCHES "qca(2)?\\.framework") + if(QCA_LIBRARY AND QCA_LIBRARY MATCHES "qca(2)?-qt5\\.framework") set(QCA_LIBRARY "${QCA_LIBRARY}" CACHE FILEPATH "QCA framework" FORCE) set(QCA_INCLUDE_DIR "${QCA_LIBRARY}/Headers" CACHE FILEPATH "QCA framework headers" FORCE) endif() From 9bb32357c7d0e3c43e3be07158c2bed5bbfed370 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 12:49:08 -0700 Subject: [PATCH 834/897] Update finding QCA OSSL plugin for Qt5 and C++11 --- cmake/QCAMacros.cmake | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cmake/QCAMacros.cmake b/cmake/QCAMacros.cmake index e33790bf353e..4a1318e7ca91 100644 --- a/cmake/QCAMacros.cmake +++ b/cmake/QCAMacros.cmake @@ -13,7 +13,7 @@ function(FIND_QCAOSSL_PLUGIN_CPP PLUGIN_REQUIRED) # requires Qt and QCA packages to be found - if(QT_INCLUDE_DIR AND QT_QTCORE_INCLUDE_DIR AND QT_QTCORE_LIBRARY + if(QT_INCLUDES AND Qt5Core_LIBRARIES AND QCA_INCLUDE_DIR AND QCA_LIBRARY AND NOT CMAKE_CROSSCOMPILING) @@ -38,12 +38,13 @@ function(FIND_QCAOSSL_PLUGIN_CPP PLUGIN_REQUIRED) set(TESTCPP "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/qcaossl.cpp") file(WRITE ${TESTCPP} "${CODE}") - set(QCA_INCLUDE_DIRECTORIES "-DINCLUDE_DIRECTORIES:STRING=${QT_INCLUDE_DIR};${QT_QTCORE_INCLUDE_DIR};${QCA_INCLUDE_DIR}") - set(QCA_LINK_LIBRARIES "-DLINK_LIBRARIES:STRING=${QT_QTCORE_LIBRARY};${QCA_LIBRARY}") + set(QCA_INCLUDE_DIRECTORIES "-DINCLUDE_DIRECTORIES:STRING=${QT_INCLUDES};${QCA_INCLUDE_DIR}") + get_target_property(_QtCore_path Qt5::Core LOCATION) + set(QCA_LINK_LIBRARIES "-DLINK_LIBRARIES:STRING=${_QtCore_path};${QCA_LIBRARY}") try_run(RUN_RESULT COMPILE_RESULT ${CMAKE_BINARY_DIR} ${TESTCPP} - CMAKE_FLAGS "${QCA_INCLUDE_DIRECTORIES}" "${QCA_LINK_LIBRARIES}" + CMAKE_FLAGS "-DCMAKE_CXX_STANDARD=11" "${QCA_INCLUDE_DIRECTORIES}" "${QCA_LINK_LIBRARIES}" COMPILE_OUTPUT_VARIABLE COMPILE_OUTPUT ) From a510516134ea767c65b8ff4e9768c7f8bc4f6b27 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 12:52:37 -0700 Subject: [PATCH 835/897] [auth] Remove dependency on SSL cert utils from auth config class --- src/core/auth/qgsauthconfig.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/core/auth/qgsauthconfig.cpp b/src/core/auth/qgsauthconfig.cpp index 4560ac405c82..6c7d2704ff99 100644 --- a/src/core/auth/qgsauthconfig.cpp +++ b/src/core/auth/qgsauthconfig.cpp @@ -20,10 +20,9 @@ #include #include +#include #include -#include "qgsauthcertutils.h" - ////////////////////////////////////////////// // QgsAuthMethodConfig @@ -302,7 +301,7 @@ const QString QgsPkiBundle::certId() const { return QString::null; } - return QgsAuthCertUtils::shaHexForCert( mCert ); + return QString( mCert.digest( QCryptographicHash::Sha1 ).toHex() ); } void QgsPkiBundle::setClientCert( const QSslCertificate &cert ) From 5df9cbc9641650df5d3a03cbf67fd429d0428eac Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 13:04:41 -0700 Subject: [PATCH 836/897] Remove Python framework options/finding for Mac; add Homebrew support Instead of finding Python interpreter, library and framework on Mac, rely upon the reported paths of the interpreter (executable) to decipher whether a framework is being used, then ensure any such framework has its versioned subdirectory Headers used for includes and the base Python library used directly in linking. This removes ambiguity in framework searching, allowing just the PYTHON_EXECUTABLE (user-defined or from FindPythonInterp module) to control which Python is used. --- CMakeLists.txt | 4 --- cmake/FindPythonLibrary.cmake | 51 +++++++++++++++++++---------------- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 76ef19d1c0a2..2ab1d46d358e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -105,10 +105,6 @@ IF (WITH_BINDINGS) SET (WITH_QSCIAPI TRUE CACHE BOOL "Whether to generate PyQGIS QScintilla2 API file. (For devs) run 'make qsci-pap-src' in between QGIS build and install to regenerate .pap file in source tree for console auto-completion.") # keep casual users from updating their source tree via WITH_QSCIAPI MARK_AS_ADVANCED (WITH_QSCIAPI) - # path to custom Python framework on Mac - IF (APPLE) - SET (PYTHON_CUSTOM_FRAMEWORK "" CACHE PATH "Path to custom Python.framework on Mac. (should not have to specify other Python options)") - ENDIF (APPLE) ENDIF (WITH_BINDINGS) #BUILD WITH QtMobility by default on android only. Other platform can force it diff --git a/cmake/FindPythonLibrary.cmake b/cmake/FindPythonLibrary.cmake index fd5536339c98..a5599f6f5623 100644 --- a/cmake/FindPythonLibrary.cmake +++ b/cmake/FindPythonLibrary.cmake @@ -31,19 +31,6 @@ if(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${ set(PYTHONLIBRARY_FOUND TRUE) else(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS "${PYTHON_SITE_PACKAGES_DIR}") - set(_custom_python_fw FALSE) - if(APPLE AND PYTHON_CUSTOM_FRAMEWORK) - if("${PYTHON_CUSTOM_FRAMEWORK}" MATCHES "Python\\.framework") - STRING(REGEX REPLACE "(.*Python\\.framework).*$" "\\1" _python_fw "${PYTHON_CUSTOM_FRAMEWORK}") - set(PYTHON_EXECUTABLE "${_python_fw}/Versions/Current/bin/python") - set(PYTHON_INCLUDE_PATH "${_python_fw}/Versions/Current/Headers") - set(PYTHON_LIBRARY "${_python_fw}/Versions/Current/Python") - if(EXISTS "${PYTHON_EXECUTABLE}" AND EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}") - set(_custom_python_fw TRUE) - endif() - endif("${PYTHON_CUSTOM_FRAMEWORK}" MATCHES "Python\\.framework") - endif(APPLE AND PYTHON_CUSTOM_FRAMEWORK) - FIND_PACKAGE(PythonInterp 3) if(PYTHONINTERP_FOUND) @@ -74,22 +61,39 @@ else(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS " endif(python_config) # adapted from cmake's builtin FindPythonLibs - if(APPLE AND NOT _custom_python_fw) - CMAKE_FIND_FRAMEWORKS(Python) - set(PYTHON_FRAMEWORK_INCLUDES) - if(Python_FRAMEWORKS) - # If a framework has been selected for the include path, - # make sure "-framework" is used to link it. + if(APPLE) + # If a framework has been detected in the include path, make sure + # framework's versioned library (not any .dylib) is used for linking + # NOTE: don't rely upon Python.framework/Versions/Current, since that may be 2.7 if("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") set(PYTHON_LIBRARY "") set(PYTHON_DEBUG_LIBRARY "") + # get clean path to just framework + STRING(REGEX REPLACE "^(.*/Python\\.framework).*$" "\\1" _py_fw "${PYTHON_INCLUDE_PATH}") + if("${_py_fw}" MATCHES "Cellar/python") + # Appears to be a Homebrew Python install; do specific fix ups + # get Homebrew prefix (may not be /usr/local) + STRING(REGEX REPLACE "^(.+)/Cellar.*$" "\\1" _hb_prefix "${_py_fw}") + # prefer the Homebrew prefix framework over only versioned Python keg + set(_py_fw "${_hb_prefix}/Frameworks/Python.framework") + # prefer the symlinked-to Homebrew site-packages over only versioned Python keg + set(PYTHON_SITE_PACKAGES_DIR "${_hb_prefix}/lib/python${PYTHON_SHORT_VERSION}/site-packages") + endif("${_py_fw}" MATCHES "Cellar/python") + # prefer the Headers subdirectory for includes + if(EXISTS "${_py_fw}/Versions/${PYTHON_SHORT_VERSION}/Headers") + set(PYTHON_INCLUDE_PATH "${_py_fw}/Versions/${PYTHON_SHORT_VERSION}/Headers" CACHE FILEPATH "Directory holding the python.h include file" FORCE) + endif(EXISTS "${_py_fw}/Versions/${PYTHON_SHORT_VERSION}/Headers") endif("${PYTHON_INCLUDE_PATH}" MATCHES "Python\\.framework") if(NOT PYTHON_LIBRARY) - set (PYTHON_LIBRARY "-framework Python" CACHE FILEPATH "Python Framework" FORCE) + # ensure the versioned framework's library is defined, instead of relying upon -F search paths + if(EXISTS "${_py_fw}/Versions/${PYTHON_SHORT_VERSION}/Python") + set(PYTHON_LIBRARY "${_py_fw}/Versions/${PYTHON_SHORT_VERSION}/Python" CACHE FILEPATH "Python framework library" FORCE) + endif(EXISTS "${_py_fw}/Versions/${PYTHON_SHORT_VERSION}/Python") endif(NOT PYTHON_LIBRARY) - set(PYTHONLIBRARY_FOUND TRUE) - endif(Python_FRAMEWORKS) - endif(APPLE AND NOT _custom_python_fw) + if(PYTHON_LIBRARY) + set(PYTHONLIBRARY_FOUND TRUE) + endif(PYTHON_LIBRARY) + endif(APPLE) endif(PYTHONINTERP_FOUND) if(PYTHONLIBRARY_FOUND) @@ -103,6 +107,7 @@ else(EXISTS "${PYTHON_INCLUDE_PATH}" AND EXISTS "${PYTHON_LIBRARY}" AND EXISTS " message(STATUS "Found Python executable: ${PYTHON_EXECUTABLE}") message(STATUS "Found Python version: ${PYTHON_LONG_VERSION}") message(STATUS "Found Python library: ${PYTHON_LIBRARY}") + message(STATUS "Found Python site-pacakges: ${PYTHON_SITE_PACKAGES_DIR}") endif(NOT PYTHONLIBRARY_FIND_QUIETLY) else(PYTHONLIBRARY_FOUND) if(PYTHONLIBRARY_FIND_REQUIRED) From 64b6a440d57ba74741b75a1f3e5522e978519ac4 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 15:28:41 -0700 Subject: [PATCH 837/897] Skip missing functionality in identity dialog if QWebKit not installed --- src/app/qgsidentifyresultsdialog.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/app/qgsidentifyresultsdialog.cpp b/src/app/qgsidentifyresultsdialog.cpp index d9e2d6bdc5b1..235b6791199a 100644 --- a/src/app/qgsidentifyresultsdialog.cpp +++ b/src/app/qgsidentifyresultsdialog.cpp @@ -78,7 +78,9 @@ QgsIdentifyResultsWebView::QgsIdentifyResultsWebView( QWidget *parent ) : QgsWeb setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Minimum ); page()->setNetworkAccessManager( QgsNetworkAccessManager::instance() ); // page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); +#ifdef WITH_QTWEBKIT page()->setForwardUnsupportedContent( true ); +#endif page()->setLinkDelegationPolicy( QWebPage::DontDelegateLinks ); settings()->setAttribute( QWebSettings::LocalContentCanAccessRemoteUrls, true ); settings()->setAttribute( QWebSettings::JavascriptCanOpenWindows, true ); From c123d3b62ffd91da8f0f663b752c156624495920 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 15:29:41 -0700 Subject: [PATCH 838/897] Add a CMake debug include, with simple variables dump for development --- cmake/CMakeDebugMacros.cmake | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 cmake/CMakeDebugMacros.cmake diff --git a/cmake/CMakeDebugMacros.cmake b/cmake/CMakeDebugMacros.cmake new file mode 100644 index 000000000000..1167f2f479ea --- /dev/null +++ b/cmake/CMakeDebugMacros.cmake @@ -0,0 +1,42 @@ +# Macros/functions for debugging CMake +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Copyright (c) 2016, Larry Shaffer, > +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + + +# Dump current CMake variables to file +# +# Usage: +# INCLUDE(CMakeDebugMacros) +# DUMP_CMAKE_VARS() or DUMP_CMAKE_VARS("regex") +# +# regex: optional ARGV0 regular expression for filtering output variable names +# +# Outputs the result relative to the current CMake file being processed and +# writes to a file with name "_cmake-vars.txt" to the current +# build (binary) directory +# +function(DUMP_CMAKE_VARS) + + get_filename_component(_basename ${CMAKE_CURRENT_LIST_FILE} NAME_WE) + set(_out "${CMAKE_CURRENT_BINARY_DIR}/${_basename}_cmake-vars.txt") + + set(_cmake_vars "") + get_cmake_property(_varNames VARIABLES) + foreach(_varName ${_varNames}) + if(ARGV0) + string(REGEX MATCH "${ARGV0}" _match "${_varName}") + if(_match) + set(_cmake_vars "${_cmake_vars}\n\n${_varName}=${${_varName}}") + endif() + else() + set(_cmake_vars "${_cmake_vars}\n\n${_varName}=${${_varName}}") + endif() + endforeach() + + message(STATUS "Dumping current CMake variables to ...\n ${_out}") + file(WRITE "${_out}" "${_cmake_vars}") + +endfunction(DUMP_CMAKE_VARS) From eca83e3c0fbd0110e72b9fac11a7314d8e243b22 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Sun, 20 Nov 2016 17:25:43 -0700 Subject: [PATCH 839/897] Add CMAKE_POSITION_INDEPENDENT_CODE flag to QCA test for OSSL plugin --- cmake/QCAMacros.cmake | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cmake/QCAMacros.cmake b/cmake/QCAMacros.cmake index 4a1318e7ca91..0b46554351f1 100644 --- a/cmake/QCAMacros.cmake +++ b/cmake/QCAMacros.cmake @@ -44,7 +44,10 @@ function(FIND_QCAOSSL_PLUGIN_CPP PLUGIN_REQUIRED) try_run(RUN_RESULT COMPILE_RESULT ${CMAKE_BINARY_DIR} ${TESTCPP} - CMAKE_FLAGS "-DCMAKE_CXX_STANDARD=11" "${QCA_INCLUDE_DIRECTORIES}" "${QCA_LINK_LIBRARIES}" + CMAKE_FLAGS "-DCMAKE_CXX_STANDARD=11" + "-DCMAKE_POSITION_INDEPENDENT_CODE=ON" + "${QCA_INCLUDE_DIRECTORIES}" + "${QCA_LINK_LIBRARIES}" COMPILE_OUTPUT_VARIABLE COMPILE_OUTPUT ) From 6d0e8e62f0c2948a80f64be2f5e63e1c0c9d0ba3 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 21 Nov 2016 10:38:26 +1000 Subject: [PATCH 840/897] Make max canvas scale 1600% (fix #15861) Max canvas sacle should be a multiple of 2 so that zooming in to the max and then back out again results in 100% zoom option. Additionally, make the min/max zoom level not come from QSettings as these aren't exposed anywhere --- src/app/qgsoptions.cpp | 4 ++-- src/app/qgsstatusbarmagnifierwidget.cpp | 7 ++++--- src/gui/qgisgui.h | 16 ++++++++++++++++ src/gui/qgsmapcanvas.cpp | 5 ++--- 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/app/qgsoptions.cpp b/src/app/qgsoptions.cpp index a387f50af4bc..4e7d0a011cb9 100644 --- a/src/app/qgsoptions.cpp +++ b/src/app/qgsoptions.cpp @@ -600,8 +600,8 @@ QgsOptions::QgsOptions( QWidget *parent, Qt::WindowFlags fl ) mSimplifyMaximumScaleComboBox->setScale( 1.0 / mSettings->value( QStringLiteral( "/qgis/simplifyMaxScale" ), 1 ).toFloat() ); // Magnifier - double magnifierMin = 100 * mSettings->value( QStringLiteral( "/qgis/magnifier_factor_min" ), 0.1 ).toDouble(); - double magnifierMax = 100 * mSettings->value( QStringLiteral( "/qgis/magnifier_factor_max" ), 10 ).toDouble(); + double magnifierMin = 100 * QgisGui::CANVAS_MAGNIFICATION_MIN; + double magnifierMax = 100 * QgisGui::CANVAS_MAGNIFICATION_MAX; double magnifierVal = 100 * mSettings->value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble(); doubleSpinBoxMagnifierDefault->setRange( magnifierMin, magnifierMax ); doubleSpinBoxMagnifierDefault->setSingleStep( 50 ); diff --git a/src/app/qgsstatusbarmagnifierwidget.cpp b/src/app/qgsstatusbarmagnifierwidget.cpp index af83f0f29e20..1b2b0efb1682 100644 --- a/src/app/qgsstatusbarmagnifierwidget.cpp +++ b/src/app/qgsstatusbarmagnifierwidget.cpp @@ -22,14 +22,15 @@ #include #include "qgsstatusbarmagnifierwidget.h" #include "qgsdoublespinbox.h" +#include "qgisgui.h" QgsStatusBarMagnifierWidget::QgsStatusBarMagnifierWidget( QWidget* parent ) : QWidget( parent ) { QSettings settings; - int minimumFactor = ( int ) 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_min" ), 0.1 ).toDouble(); - int maximumFactor = ( int ) 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_max" ), 10 ).toDouble(); - int defaultFactor = ( int ) 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble(); + int minimumFactor = 100 * QgisGui::CANVAS_MAGNIFICATION_MIN; + int maximumFactor = 100 * QgisGui::CANVAS_MAGNIFICATION_MAX; + int defaultFactor = 100 * settings.value( QStringLiteral( "/qgis/magnifier_factor_default" ), 1.0 ).toDouble(); // label mLabel = new QLabel(); diff --git a/src/gui/qgisgui.h b/src/gui/qgisgui.h index 39806b9862d3..1c0e94be94a3 100644 --- a/src/gui/qgisgui.h +++ b/src/gui/qgisgui.h @@ -25,6 +25,7 @@ class QFont; /** \ingroup gui * /namespace QgisGui * The QgisGui namespace contains constants and helper functions used throughout the QGIS GUI. + * \note not available in Python bindings */ namespace QgisGui { @@ -48,6 +49,21 @@ namespace QgisGui */ static const Qt::WindowFlags ModalDialogFlags = 0; + /** + * Minimum magnification level allowed in map canvases. + * @see CANVAS_MAGNIFICATION_MAX + * @note added in QGIS 3.0 + */ + constexpr double CANVAS_MAGNIFICATION_MIN = 0.1; + + /** + * Maximum magnification level allowed in map canvases. + * @see CANVAS_MAGNIFICATION_MAX + * @note added in QGIS 3.0 + */ + // Must be a factor of 2, so zooming in to max from 100% then zooming back out will result in 100% mag + constexpr double CANVAS_MAGNIFICATION_MAX = 16.0; + /** Open files, preferring to have the default file selector be the last one used, if any; also, prefer to start in the last directory diff --git a/src/gui/qgsmapcanvas.cpp b/src/gui/qgsmapcanvas.cpp index 2838a5ecd010..6fb6b0d1f6a2 100644 --- a/src/gui/qgsmapcanvas.cpp +++ b/src/gui/qgsmapcanvas.cpp @@ -225,9 +225,8 @@ QgsMapCanvas::~QgsMapCanvas() void QgsMapCanvas::setMagnificationFactor( double factor ) { // do not go higher or lower than min max magnification ratio - QSettings settings; - double magnifierMin = settings.value( QStringLiteral( "/qgis/magnifier_factor_min" ), 0.1 ).toDouble(); - double magnifierMax = settings.value( QStringLiteral( "/qgis/magnifier_factor_max" ), 10 ).toDouble(); + double magnifierMin = QgisGui::CANVAS_MAGNIFICATION_MIN; + double magnifierMax = QgisGui::CANVAS_MAGNIFICATION_MAX; factor = qBound( magnifierMin, factor, magnifierMax ); // the magnifier widget is in integer percent From eda412d98c8f36d399d2e5eb5b1cc8f17e094529 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 21 Nov 2016 10:40:04 +1000 Subject: [PATCH 841/897] Fix ui build warning --- src/ui/qgsstylemanagerdialogbase.ui | 1 - 1 file changed, 1 deletion(-) diff --git a/src/ui/qgsstylemanagerdialogbase.ui b/src/ui/qgsstylemanagerdialogbase.ui index 13812b2f1161..4a0f6d2e9782 100644 --- a/src/ui/qgsstylemanagerdialogbase.ui +++ b/src/ui/qgsstylemanagerdialogbase.ui @@ -497,7 +497,6 @@ groupTree btnManageGroups - btnRemoveGroup btnAddTag btnAddSmartgroup btnShare From e27e533c42afb0891942ae74f0b7f1579ade8a90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Mon, 21 Nov 2016 09:38:39 +0100 Subject: [PATCH 842/897] [FEATURE] Speed up algo by using QgsGeometryEngine --- .../plugins/processing/algs/qgis/SplitWithLines.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 23ed0fd0cdaa..40898022b7b0 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -112,19 +112,27 @@ def processAlgorithm(self, progress): if inFeatA.id() == i: continue - if inGeom.intersects(splitGeom): + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() + + if engine.intersects(splitGeom.geometry()): splittingLines.append(splitGeom) if len(splittingLines) > 0: for splitGeom in splittingLines: - splitterPList = vector.extractPoints(splitGeom) + splitterPList = None outGeoms = [] while len(inGeoms) > 0: inGeom = inGeoms.pop() + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() inPoints = vector.extractPoints(inGeom) - if inGeom.intersects(splitGeom): + if engine.intersects(splitGeom.geometry()): + if splitterPList == None: + splitterPList = vector.extractPoints(splitGeom) + try: result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) except: From 3c3e17ac90e7b3b761ac8a081ac53941da06cbc5 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 16 Nov 2016 13:27:57 +0200 Subject: [PATCH 843/897] [network analysis] expose speed properter in C++ and Python API This allows users to calculate shortest path using travel time as optimization criteria in addition to travel distance. --- python/analysis/network/qgsarcproperter.sip | 7 +-- .../network/qgsdistancearcproperter.sip | 1 - python/analysis/network/qgsgraph.sip | 4 +- .../analysis/network/qgsspeedarcproperter.sip | 13 ++++++ src/analysis/network/CMakeLists.txt | 2 + src/analysis/network/qgsarcproperter.h | 12 +++-- .../network/qgsdistancearcproperter.cpp | 23 +++++----- .../network/qgsdistancearcproperter.h | 9 ++-- src/analysis/network/qgsgraph.h | 16 +++---- src/analysis/network/qgsgraphanalyzer.cpp | 8 ++-- src/analysis/network/qgsgraphanalyzer.h | 25 +++++------ src/analysis/network/qgsgraphbuilder.cpp | 23 +++++----- src/analysis/network/qgsgraphbuilder.h | 14 +++--- src/analysis/network/qgsgraphbuilderintr.h | 17 +++---- src/analysis/network/qgsgraphdirector.h | 14 +++--- .../network/qgslinevectorlayerdirector.cpp | 25 ++++++----- .../network/qgslinevectorlayerdirector.h | 11 ++--- src/analysis/network/qgsspeedarcproperter.cpp | 44 +++++++++++++++++++ src/analysis/network/qgsspeedarcproperter.h | 40 +++++++++++++++++ 19 files changed, 197 insertions(+), 111 deletions(-) create mode 100644 python/analysis/network/qgsspeedarcproperter.sip create mode 100644 src/analysis/network/qgsspeedarcproperter.cpp create mode 100644 src/analysis/network/qgsspeedarcproperter.h diff --git a/python/analysis/network/qgsarcproperter.sip b/python/analysis/network/qgsarcproperter.sip index 322f2b3e5400..75233b8fb9e6 100644 --- a/python/analysis/network/qgsarcproperter.sip +++ b/python/analysis/network/qgsarcproperter.sip @@ -2,14 +2,15 @@ // fix to allow compilation with sip 4.7 that for some reason // doesn't add these includes to the file where the code from // ConvertToSubClassCode goes. +#include #include %End /** * \ingroup networkanalysis - * \class QgsEdgeProperter - * \brief QgsEdgeProperter is a strategy pattern. - * You can use it for customize arc property. For example look at QgsDistanceArcProperter or src/plugins/roadgraph/speedproperter.h + * \class QgsArcProperter + * \brief QgsArcProperter is a strategy pattern. + * You can use it for customize arc property. For example look at QgsDistanceArcProperter or QgsSpeedArcProperter */ class QgsArcProperter { diff --git a/python/analysis/network/qgsdistancearcproperter.sip b/python/analysis/network/qgsdistancearcproperter.sip index c5146f131003..93dcb3821dc8 100644 --- a/python/analysis/network/qgsdistancearcproperter.sip +++ b/python/analysis/network/qgsdistancearcproperter.sip @@ -1,4 +1,3 @@ - class QgsDistanceArcProperter : QgsArcProperter { %TypeHeaderCode diff --git a/python/analysis/network/qgsgraph.sip b/python/analysis/network/qgsgraph.sip index fd5d106b830a..5950a6d5c300 100644 --- a/python/analysis/network/qgsgraph.sip +++ b/python/analysis/network/qgsgraph.sip @@ -1,7 +1,7 @@ /** * \ingroup networkanalysis * \class QgsGraphArc - * \brief This class implement a graph edge + * \brief This class implements a graph edge */ class QgsGraphArc { @@ -40,7 +40,7 @@ typedef QList< int > QgsGraphArcIdList; /** * \ingroup networkanalysis * \class QgsGraphVertex - * \brief This class implement a graph vertex + * \brief This class implements a graph vertex */ class QgsGraphVertex { diff --git a/python/analysis/network/qgsspeedarcproperter.sip b/python/analysis/network/qgsspeedarcproperter.sip new file mode 100644 index 000000000000..6ae01e5d0510 --- /dev/null +++ b/python/analysis/network/qgsspeedarcproperter.sip @@ -0,0 +1,13 @@ +class QgsSpeedArcProperter : QgsArcProperter +{ +%TypeHeaderCode +#include +%End + + public: + QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ); + + QVariant property( double distance, const QgsFeature& f ) const; + + QgsAttributeList requiredAttributes() const; +}; diff --git a/src/analysis/network/CMakeLists.txt b/src/analysis/network/CMakeLists.txt index e59d7c21d415..9c236e25631a 100644 --- a/src/analysis/network/CMakeLists.txt +++ b/src/analysis/network/CMakeLists.txt @@ -6,6 +6,7 @@ SET(QGIS_NETWORK_ANALYSIS_SRCS qgsgraph.cpp qgsgraphbuilder.cpp + qgsspeedarcproperter.cpp qgsdistancearcproperter.cpp qgslinevectorlayerdirector.cpp qgsgraphanalyzer.cpp @@ -27,6 +28,7 @@ SET(QGIS_NETWORK_ANALYSIS_HDRS qgsgraphbuilderintr.h qgsgraphbuilder.h qgsarcproperter.h + qgsspeedarcproperter.h qgsdistancearcproperter.h qgsgraphdirector.h qgslinevectorlayerdirector.h diff --git a/src/analysis/network/qgsarcproperter.h b/src/analysis/network/qgsarcproperter.h index 201a88d21a66..4f1251d27223 100644 --- a/src/analysis/network/qgsarcproperter.h +++ b/src/analysis/network/qgsarcproperter.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsedgeproperter.h + qgsarcproperter.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,13 +13,11 @@ * * ***************************************************************************/ -#ifndef QGSEDGEPROPERTERH -#define QGSEDGEPROPERTERH +#ifndef QGSARCROPERTER_H +#define QGSARCROPERTER_H -// QT4 includes #include -// QGIS includes #include #include @@ -27,7 +25,7 @@ * \ingroup networkanalysis * \class QgsArcProperter * \brief QgsArcProperter is a strategy pattern. - * You can use it for customize arc property. For example look at QgsDistanceArcProperter or src/plugins/roadgraph/speedproperter.h + * You can use it for customize arc property. For example look at QgsDistanceArcProperter and QgsSpeedArcProperter */ class ANALYSIS_EXPORT QgsArcProperter { @@ -56,4 +54,4 @@ class ANALYSIS_EXPORT QgsArcProperter return QVariant(); } }; -#endif //QGSEDGEPROPERTYH +#endif // QGSARCROPERTER_H diff --git a/src/analysis/network/qgsdistancearcproperter.cpp b/src/analysis/network/qgsdistancearcproperter.cpp index 22a730f617f1..e65bf56f58e2 100644 --- a/src/analysis/network/qgsdistancearcproperter.cpp +++ b/src/analysis/network/qgsdistancearcproperter.cpp @@ -1,15 +1,18 @@ /*************************************************************************** - * Copyright (C) 2011 by Sergey Yakushev * - * yakushevs list.ru * - * * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ + qgsdistancearcproperter.h + -------------------------------------- + Date : 2011-04-01 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ -//QGIS includes #include "qgsdistancearcproperter.h" QVariant QgsDistanceArcProperter::property( double distance, const QgsFeature& f ) const diff --git a/src/analysis/network/qgsdistancearcproperter.h b/src/analysis/network/qgsdistancearcproperter.h index 3baacd3504f1..2370c02afe04 100644 --- a/src/analysis/network/qgsdistancearcproperter.h +++ b/src/analysis/network/qgsdistancearcproperter.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsedgeproperter.h + qgsdistancearcproperter.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,8 +13,8 @@ * * ***************************************************************************/ -#ifndef QGSEDGEDISTANCEPROPERTERH -#define QGSEDGEDISTANCEPROPERTERH +#ifndef QGSDISTANCEARCPROPERTER_H +#define QGSDISTANCEARCPROPERTER_H // QT4 includes #include @@ -30,4 +30,5 @@ class ANALYSIS_EXPORT QgsDistanceArcProperter : public QgsArcProperter public: virtual QVariant property( double distance, const QgsFeature& ) const override; }; -#endif //QGSEDGEDISTANCEPROPERTYH + +#endif // QGSDISTANCEARCPROPERTER_H diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index 6790c22ce1ee..209c01ab15c5 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -23,15 +23,13 @@ * \file qgsgraph.h */ -#ifndef QGSGRAPHH -#define QGSGRAPHH +#ifndef QGSGRAPH_H +#define QGSGRAPH_H -// QT4 includes #include #include #include -// QGIS includes #include "qgspoint.h" class QgsGraphVertex; @@ -39,7 +37,7 @@ class QgsGraphVertex; /** * \ingroup networkanalysis * \class QgsGraphArc - * \brief This class implement a graph edge + * \brief This class implements a graph edge */ class ANALYSIS_EXPORT QgsGraphArc { @@ -83,14 +81,14 @@ typedef QList< int > QgsGraphArcIdList; /** * \ingroup networkanalysis * \class QgsGraphVertex - * \brief This class implement a graph vertex + * \brief This class implements a graph vertex */ class ANALYSIS_EXPORT QgsGraphVertex { public: /** - * default constructor. It need for QT's container, e.g. QVector + * default constructor. It needed for Qt's container, e.g. QVector */ QgsGraphVertex() {} @@ -137,7 +135,7 @@ class ANALYSIS_EXPORT QgsGraph // begin graph constructing methods /** - * add vertex to a grap + * add vertex to a graph */ int addVertex( const QgsPoint& pt ); @@ -178,4 +176,4 @@ class ANALYSIS_EXPORT QgsGraph QVector mGraphArc; }; -#endif //QGSGRAPHH +#endif // QGSGRAPH_H diff --git a/src/analysis/network/qgsgraphanalyzer.cpp b/src/analysis/network/qgsgraphanalyzer.cpp index 6d2f4def07c7..c93bd68fc44a 100644 --- a/src/analysis/network/qgsgraphanalyzer.cpp +++ b/src/analysis/network/qgsgraphanalyzer.cpp @@ -14,15 +14,13 @@ * (at your option) any later version. * * * ***************************************************************************/ -// C++ standard includes + #include -// QT includes #include #include #include -//QGIS-uncludes #include "qgsgraph.h" #include "qgsgraphanalyzer.h" @@ -49,7 +47,7 @@ void QgsGraphAnalyzer::dijkstra( const QgsGraph* source, int startPointIdx, int } // QMultiMap< cost, vertexIdx > not_begin - // I use it and not create any struct or class. + // I use it and don't create any struct or class QMultiMap< double, int > not_begin; QMultiMap< double, int >::iterator it; @@ -108,7 +106,7 @@ QgsGraph* QgsGraphAnalyzer::shortestTree( const QgsGraph* source, int startVerte } } - // Add arcs to result + // Add arcs to the result for ( i = 0; i < source->vertexCount(); ++i ) { if ( tree[ i ] != -1 ) diff --git a/src/analysis/network/qgsgraphanalyzer.h b/src/analysis/network/qgsgraphanalyzer.h index a35fe4697cf2..ac7a58fa3d68 100644 --- a/src/analysis/network/qgsgraphanalyzer.h +++ b/src/analysis/network/qgsgraphanalyzer.h @@ -15,17 +15,15 @@ * * ***************************************************************************/ -#ifndef QGSGRAPHANALYZERH -#define QGSGRAPHANALYZERH +#ifndef QGSGRAPHANALYZER_H +#define QGSGRAPHANALYZER_H -//QT-includes #include -// forward-declaration class QgsGraph; /** \ingroup networkanalysis - * The QGis class provides graph analysis functions + * QGIS class with graph analysis functions */ class ANALYSIS_EXPORT QgsGraphAnalyzer @@ -34,20 +32,21 @@ class ANALYSIS_EXPORT QgsGraphAnalyzer /** * solve shortest path problem using dijkstra algorithm - * @param source The source graph - * @param startVertexIdx index of start vertex - * @param criterionNum index of arc property as optimization criterion - * @param resultTree array represents the shortest path tree. resultTree[ vertexIndex ] == inboundingArcIndex if vertex reacheble and resultTree[ vertexIndex ] == -1 others. + * @param source source graph + * @param startVertexIdx index of the start vertex + * @param criterionNum index of the arc property as optimization criterion + * @param resultTree array represents the shortest path tree. resultTree[ vertexIndex ] == inboundingArcIndex if vertex reachable, otherwise resultTree[ vertexIndex ] == -1 * @param resultCost array of cost paths */ static void dijkstra( const QgsGraph* source, int startVertexIdx, int criterionNum, QVector* resultTree = nullptr, QVector* resultCost = nullptr ); /** * return shortest path tree with root-node in startVertexIdx - * @param source The source graph - * @param startVertexIdx index of start vertex - * @param criterionNum index of edge property as optimization criterion + * @param source source graph + * @param startVertexIdx index of the start vertex + * @param criterionNum index of the edge property as optimization criterion */ static QgsGraph* shortestTree( const QgsGraph* source, int startVertexIdx, int criterionNum ); }; -#endif //QGSGRAPHANALYZERH + +#endif // QGSGRAPHANALYZER_H diff --git a/src/analysis/network/qgsgraphbuilder.cpp b/src/analysis/network/qgsgraphbuilder.cpp index f0dec236cd2f..e80914f42804 100644 --- a/src/analysis/network/qgsgraphbuilder.cpp +++ b/src/analysis/network/qgsgraphbuilder.cpp @@ -1,13 +1,17 @@ /*************************************************************************** - * Copyright (C) 2010 by Sergey Yakushev * - * yakushevs list.ru * - * * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ + qgsgraphbuilder.cpp + -------------------------------------- + Date : 2010-10-25 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS@list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ /** * \file qgsgraphbuilder.cpp @@ -17,7 +21,6 @@ #include "qgsgraphbuilder.h" #include "qgsgraph.h" -// Qgis includes #include #include diff --git a/src/analysis/network/qgsgraphbuilder.h b/src/analysis/network/qgsgraphbuilder.h index a48ecc2ecc42..8e436989e867 100644 --- a/src/analysis/network/qgsgraphbuilder.h +++ b/src/analysis/network/qgsgraphbuilder.h @@ -12,17 +12,14 @@ * (at your option) any later version. * * * ***************************************************************************/ -#ifndef QGSGRAPHBUILDERH -#define QGSGRAPHBUILDERH -#include "qgsgraphbuilderintr.h" +#ifndef QGSGRAPHBUILDER_H +#define QGSGRAPHBUILDER_H -//QT4 includes +#include "qgsgraphbuilderintr.h" -//QGIS includes #include -//forward declarations class QgsDistanceArea; class QgsCoordinateTransform; class QgsGraph; @@ -30,7 +27,7 @@ class QgsGraph; /** * \ingroup networkanalysis * \class QgsGraphBuilder -* \brief This class making the QgsGraph object +* \brief This class is used for making the QgsGraph object */ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface @@ -60,4 +57,5 @@ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface QgsGraph *mGraph; }; -#endif //QGSGRAPHBUILDERH + +#endif // QGSGRAPHBUILDER_H diff --git a/src/analysis/network/qgsgraphbuilderintr.h b/src/analysis/network/qgsgraphbuilderintr.h index 26badc27c5e7..5514609f88dc 100644 --- a/src/analysis/network/qgsgraphbuilderintr.h +++ b/src/analysis/network/qgsgraphbuilderintr.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsgraphbuilder.h + qgsgraphbuilderintr.h -------------------------------------- Date : 2010-10-22 Copyright : (C) 2010 by Yakushev Sergey @@ -12,24 +12,21 @@ * (at your option) any later version. * * * ***************************************************************************/ -#ifndef QGSGRAPHBUILDERINTERFACE -#define QGSGRAPHBUILDERINTERFACE -//QT4 includes +#ifndef QGSGRAPHBUILDERINTERFACE_H +#define QGSGRAPHBUILDERINTERFACE_H + #include #include -//QGIS includes #include #include #include -//forward declarations - /** * \ingroup networkanalysis * \class QgsGraphBuilderInterface -* \brief Determine interface for creating a graph. Contains the settings of the graph. QgsGraphBuilder and QgsGraphDirector is a Builder pattern +* \brief Determine interface for creating a graph. Contains the settings of the graph. QgsGraphBuilder and QgsGraphDirector both use a Builder pattern */ class ANALYSIS_EXPORT QgsGraphBuilderInterface { @@ -56,7 +53,7 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface virtual ~QgsGraphBuilderInterface() { } - //! get destinaltion Crs + //! get destinaltion CRS QgsCoordinateReferenceSystem destinationCrs() const { return mCrs; @@ -120,4 +117,4 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface double mTopologyTolerance; }; -#endif //QGSGRAPHBUILDERINTERFACE +#endif // QGSGRAPHBUILDERINTERFACE_H diff --git a/src/analysis/network/qgsgraphdirector.h b/src/analysis/network/qgsgraphdirector.h index c0c9b6c17e21..b24b44d73f99 100644 --- a/src/analysis/network/qgsgraphdirector.h +++ b/src/analysis/network/qgsgraphdirector.h @@ -12,19 +12,17 @@ * (at your option) any later version. * * * ***************************************************************************/ -#ifndef QGSGRAPHDIRECTORH -#define QGSGRAPHDIRECTORH -//QT4 includes +#ifndef QGSGRAPHDIRECTOR_H +#define QGSGRAPHDIRECTOR_H + #include #include #include -//QGIS includes #include #include "qgsarcproperter.h" -//forward declarations class QgsGraphBuilderInterface; /** @@ -48,11 +46,8 @@ class ANALYSIS_EXPORT QgsGraphDirector : public QObject * Make a graph using RgGraphBuilder * * @param builder The graph builder - * * @param additionalPoints Vector of points that must be tied to the graph - * * @param tiedPoints Vector of tied points - * * @note if tiedPoints[i]==QgsPoint(0.0,0.0) then tied failed. */ virtual void makeGraph( QgsGraphBuilderInterface *builder, @@ -77,4 +72,5 @@ class ANALYSIS_EXPORT QgsGraphDirector : public QObject protected: QList mProperterList; }; -#endif //QGSGRAPHDIRECTORH + +#endif // QGSGRAPHDIRECTOR_H diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgslinevectorlayerdirector.cpp index d6be07f5c5d9..f113b26de209 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgslinevectorlayerdirector.cpp @@ -1,13 +1,17 @@ /*************************************************************************** - * Copyright (C) 2010 by Sergey Yakushev * - * yakushevs list.ru * - * * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ + qgslinevectorlayerdirector.cpp + -------------------------------------- + Date : 2010-10-20 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS@list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ /** * \file qgslinevectorlayerdirector.cpp @@ -17,7 +21,6 @@ #include "qgslinevectorlayerdirector.h" #include "qgsgraphbuilderintr.h" -// Qgis includes #include "qgsfeatureiterator.h" #include #include @@ -26,7 +29,6 @@ #include #include -// QT includes #include #include @@ -393,4 +395,3 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c emit buildProgress( ++step, featureCount ); } // while( vl->nextFeature(feature) ) } // makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, QVector< QgsPoint >& tiedPoint ) - diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgslinevectorlayerdirector.h index 11a1857a8031..9e83b49e8d28 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgslinevectorlayerdirector.h @@ -12,17 +12,12 @@ * (at your option) any later version. * * * ***************************************************************************/ -#ifndef QGSLINEVECTORLAYERDIRECTORH -#define QGSLINEVECTORLAYERDIRECTORH -//QT4 includes +#ifndef QGSLINEVECTORLAYERDIRECTOR_H +#define QGSLINEVECTORLAYERDIRECTOR_H -//QGIS includes - -// Road-graph plugin includes #include "qgsgraphdirector.h" -//forward declarations class QgsGraphBuilderInterface; class QgsVectorLayer; @@ -80,4 +75,4 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector int mDefaultDirection; }; -#endif //QGSLINEVECTORLAYERGRAPHDIRECTORH +#endif // QGSLINEVECTORLAYERDIRECTOR_H diff --git a/src/analysis/network/qgsspeedarcproperter.cpp b/src/analysis/network/qgsspeedarcproperter.cpp new file mode 100644 index 000000000000..fa137fd3de39 --- /dev/null +++ b/src/analysis/network/qgsspeedarcproperter.cpp @@ -0,0 +1,44 @@ +/*************************************************************************** + qgsspeedarcproperter.h + -------------------------------------- + Date : 2011-04-01 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ + +#include "qgsspeedarcproperter.h" + +QgsSpeedArcProperter::QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ) +{ + mAttributeId = attributeId; + mDefaultValue = defaultValue; + mToMetricFactor = toMetricFactor; +} + +QVariant QgsSpeedArcProperter::property( double distance, const QgsFeature& f ) const +{ + QgsAttributes attrs = f.attributes(); + + if ( mAttributeId < 0 || mAttributeId >= attrs.count() ) + return QVariant( distance / ( mDefaultValue*mToMetricFactor ) ); + + double val = distance / ( attrs.at( mAttributeId ).toDouble() * mToMetricFactor ); + if ( val <= 0.0 ) + return QVariant( distance / ( mDefaultValue / mToMetricFactor ) ); + + return QVariant( val ); +} + +QgsAttributeList QgsSpeedArcProperter::requiredAttributes() const +{ + QgsAttributeList l; + l.push_back( mAttributeId ); + return l; +} diff --git a/src/analysis/network/qgsspeedarcproperter.h b/src/analysis/network/qgsspeedarcproperter.h new file mode 100644 index 000000000000..62d1516710a3 --- /dev/null +++ b/src/analysis/network/qgsspeedarcproperter.h @@ -0,0 +1,40 @@ +/*************************************************************************** + qgsspeedarcproperter.h + -------------------------------------- + Date : 2011-04-01 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ + +#ifndef QGSSPEEDARCPROPERTER_H +#define QGSSPEEDARCPROPERTER_H + +#include + +/** \ingroup networkanalysis + * \class QgsSpeedArcProperter + */ +class ANALYSIS_EXPORT QgsSpeedArcProperter : public QgsArcProperter +{ + public: + QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ); + + QVariant property( double distance, const QgsFeature& f ) const override; + + QgsAttributeList requiredAttributes() const override; + + private: + int mAttributeId; + double mDefaultValue; + double mToMetricFactor; + +}; + +#endif // QGSSPEEDARCPROPERTER_H From 14c930a5a88c7add7b4a20cf91ca5c7fd7299824 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 16 Nov 2016 16:22:10 +0200 Subject: [PATCH 844/897] [API][network analysis] move network analysis into analysis library to be consistent with other analysis stuff --- python/CMakeLists.txt | 20 ++-- python/analysis/analysis.sip | 10 ++ python/analysis/network/networkanalysis.sip | 15 --- python/analysis/network/qgsarcproperter.sip | 5 +- python/networkanalysis/__init__.py | 28 ----- src/analysis/CMakeLists.txt | 23 +++- src/analysis/network/CMakeLists.txt | 100 ------------------ src/analysis/network/qgsarcproperter.h | 2 +- .../network/qgsdistancearcproperter.h | 6 +- src/analysis/network/qgsgraph.h | 2 +- src/analysis/network/qgsgraphanalyzer.h | 2 +- src/analysis/network/qgsgraphbuilder.h | 2 +- src/analysis/network/qgsgraphbuilderintr.h | 2 +- src/analysis/network/qgsgraphdirector.h | 2 +- .../network/qgslinevectorlayerdirector.h | 2 +- src/analysis/network/qgsspeedarcproperter.h | 2 +- src/plugins/roadgraph/CMakeLists.txt | 2 +- tests/src/python/test_qgssipcoverage.py | 1 - 18 files changed, 50 insertions(+), 176 deletions(-) delete mode 100644 python/analysis/network/networkanalysis.sip delete mode 100644 python/networkanalysis/__init__.py delete mode 100644 src/analysis/network/CMakeLists.txt diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index f54f4a4621cd..a8e666d017a7 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -138,12 +138,12 @@ IF(NOT QT_MOBILITY_LOCATION_FOUND) SET(SIP_DISABLE_FEATURES ${SIP_DISABLE_FEATURES} MOBILITY_LOCATION) ENDIF(NOT QT_MOBILITY_LOCATION_FOUND) -IF(PYQT4_VERSION_NUM LESS 263680) # 0x040600 +IF(PYQT4_VERSION_NUM LESS 263680) # 0x040600 SET(SIP_DISABLE_FEATURES ${SIP_DISABLE_FEATURES} PROXY_FACTORY) ENDIF(PYQT4_VERSION_NUM LESS 263680) # -IF(NOT PYQT4_VERSION_NUM LESS 264194) # 0x040802 +IF(NOT PYQT4_VERSION_NUM LESS 264194) # 0x040802 SET(SIP_DISABLE_FEATURES ${SIP_DISABLE_FEATURES} QSETTYPE_CONVERSION) ENDIF(NOT PYQT4_VERSION_NUM LESS 264194) @@ -151,7 +151,7 @@ IF(PYQT4_VERSION_NUM LESS 264196) # 0x040804 SET(SIP_DISABLE_FEATURES ${SIP_DISABLE_FEATURES} QLISTCONSTPTR_CONVERSION) ENDIF(PYQT4_VERSION_NUM LESS 264196) -IF(NOT PYQT4_VERSION_NUM LESS 264453) # 0x040905 +IF(NOT PYQT4_VERSION_NUM LESS 264453) # 0x040905 SET(SIP_DISABLE_FEATURES ${SIP_DISABLE_FEATURES} QVECTORINT_CONVERSION) ENDIF(NOT PYQT4_VERSION_NUM LESS 264453) @@ -200,7 +200,7 @@ ENDIF(UNIX AND NOT SIP_VERSION_NUM LESS 265984) GENERATE_SIP_PYTHON_MODULE_CODE(qgis._gui gui/gui.sip cpp_files) BUILD_SIP_PYTHON_MODULE(qgis._gui gui/gui.sip ${cpp_files} "" qgis_core qgis_gui) -SET(PY_MODULES core gui analysis networkanalysis) +SET(PY_MODULES core gui analysis) # server module IF (WITH_SERVER AND WITH_SERVER_PLUGINS) @@ -228,8 +228,8 @@ INCLUDE_DIRECTORIES( ../src/analysis/interpolation ../src/analysis/openstreetmap ${CMAKE_BINARY_DIR}/src/analysis/vector - ${CMAKE_BINARY_DIR}/src/analysis/network ${CMAKE_BINARY_DIR}/src/analysis/raster + ${CMAKE_BINARY_DIR}/src/analysis/network ${CMAKE_BINARY_DIR}/src/analysis/interpolation ${CMAKE_BINARY_DIR}/src/analysis/openstreetmap ) @@ -239,6 +239,7 @@ FILE(GLOB sip_files_analysis analysis/*.sip analysis/raster/*.sip analysis/vector/*.sip + analysis/network/*.sip analysis/interpolation/*.sip analysis/openstreetmap/*.sip ) @@ -247,13 +248,6 @@ SET(SIP_EXTRA_OPTIONS ${PYQT_SIP_FLAGS} -o -a ${CMAKE_BINARY_DIR}/python/qgis.an GENERATE_SIP_PYTHON_MODULE_CODE(qgis._analysis analysis/analysis.sip cpp_files) BUILD_SIP_PYTHON_MODULE(qgis._analysis analysis/analysis.sip ${cpp_files} "" qgis_core qgis_analysis) -# network-analysis module -FILE(GLOB_RECURSE sip_files_network_analysis analysis/network/*.sip) -SET(SIP_EXTRA_FILES_DEPEND ${sip_files_core} ${sip_files_network_analysis}) -SET(SIP_EXTRA_OPTIONS ${PYQT_SIP_FLAGS} -o -a ${CMAKE_BINARY_DIR}/python/qgis.networkanalysis.api) -GENERATE_SIP_PYTHON_MODULE_CODE(qgis._networkanalysis analysis/network/networkanalysis.sip cpp_files) -BUILD_SIP_PYTHON_MODULE(qgis._networkanalysis networkanalysis/networkanalysis.sip ${cpp_files} "" qgis_core qgis_networkanalysis) - SET(QGIS_PYTHON_DIR ${PYTHON_SITE_PACKAGES_DIR}/qgis) IF(WITH_QSCIAPI) @@ -261,7 +255,7 @@ IF(WITH_QSCIAPI) SET(QGIS_PYTHON_API_FILE "${CMAKE_BINARY_DIR}/python/qsci_apis/PyQGIS.api") ADD_CUSTOM_TARGET(qsci-api ALL - DEPENDS python_module_qgis__gui python_module_qgis__core python_module_qgis__analysis python_module_qgis__networkanalysis) + DEPENDS python_module_qgis__gui python_module_qgis__core python_module_qgis__analysis) # run update/concatenate command ADD_CUSTOM_COMMAND(TARGET qsci-api diff --git a/python/analysis/analysis.sip b/python/analysis/analysis.sip index 3f38bd426f65..bf8b037c2704 100644 --- a/python/analysis/analysis.sip +++ b/python/analysis/analysis.sip @@ -52,3 +52,13 @@ %Include raster/qgsruggednessfilter.sip %Include raster/qgsslopefilter.sip %Include raster/qgstotalcurvaturefilter.sip + +%Include network/qgsgraph.sip +%Include network/qgsarcproperter.sip +%Include network/qgsspeedarcproperter.sip +%Include network/qgsdistancearcproperter.sip +%Include network/qgsgraphbuilderintr.sip +%Include network/qgsgraphbuilder.sip +%Include network/qgsgraphdirector.sip +%Include network/qgslinevectorlayerdirector.sip +%Include network/qgsgraphanalyzer.sip diff --git a/python/analysis/network/networkanalysis.sip b/python/analysis/network/networkanalysis.sip deleted file mode 100644 index fb446d18d5e4..000000000000 --- a/python/analysis/network/networkanalysis.sip +++ /dev/null @@ -1,15 +0,0 @@ -%Module(name=qgis._networkanalysis, - version=0, - keyword_arguments="Optional") - -%Import QtCore/QtCoremod.sip -%Import core/core.sip - -%Include qgsgraph.sip -%Include qgsarcproperter.sip -%Include qgsdistancearcproperter.sip -%Include qgsgraphbuilderintr.sip -%Include qgsgraphbuilder.sip -%Include qgsgraphdirector.sip -%Include qgslinevectorlayerdirector.sip -%Include qgsgraphanalyzer.sip diff --git a/python/analysis/network/qgsarcproperter.sip b/python/analysis/network/qgsarcproperter.sip index 75233b8fb9e6..26ba8f4ffbaf 100644 --- a/python/analysis/network/qgsarcproperter.sip +++ b/python/analysis/network/qgsarcproperter.sip @@ -1,7 +1,4 @@ %ModuleHeaderCode -// fix to allow compilation with sip 4.7 that for some reason -// doesn't add these includes to the file where the code from -// ConvertToSubClassCode goes. #include #include %End @@ -21,6 +18,8 @@ class QgsArcProperter %ConvertToSubClassCode if ( dynamic_cast< QgsDistanceArcProperter* > ( sipCpp ) != NULL ) sipType = sipType_QgsDistanceArcProperter; + else if ( dynamic_cast< QgsSpeedArcProperter* > ( sipCpp ) != NULL ) + sipType = sipType_QgsSpeedArcProperter; else sipType = NULL; %End diff --git a/python/networkanalysis/__init__.py b/python/networkanalysis/__init__.py deleted file mode 100644 index ad46c7698822..000000000000 --- a/python/networkanalysis/__init__.py +++ /dev/null @@ -1,28 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - __init__.py - --------------------- - Date : May 2014 - Copyright : (C) 2014 by Nathan Woodrow - Email : woodrow dot nathan at gmail dot com -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" - -__author__ = 'Nathan Woodrow' -__date__ = 'May 2014' -__copyright__ = '(C) 2014, Nathan Woodrow' -# This will get replaced with a git SHA1 when you do a git archive -__revision__ = '$Format:%H$' - -from qgis.PyQt import QtCore - -from qgis._networkanalysis import * diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index bc91f54b8cd8..5392c631f86a 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -1,5 +1,3 @@ -SUBDIRS(network) - ############################################################# # sources @@ -48,12 +46,22 @@ SET(QGIS_ANALYSIS_SRCS openstreetmap/qgsosmdatabase.cpp openstreetmap/qgsosmdownload.cpp openstreetmap/qgsosmimport.cpp + + network/qgsgraph.cpp + network/qgsgraphbuilder.cpp + network/qgsspeedarcproperter.cpp + network/qgsdistancearcproperter.cpp + network/qgslinevectorlayerdirector.cpp + network/qgsgraphanalyzer.cpp ) SET(QGIS_ANALYSIS_MOC_HDRS openstreetmap/qgsosmdownload.h openstreetmap/qgsosmimport.h vector/qgsgeometrysnapper.h + + network/qgsgraphdirector.h + network/qgslinevectorlayerdirector.h ) INCLUDE_DIRECTORIES(SYSTEM ${SPATIALITE_INCLUDE_DIR}) @@ -134,6 +142,16 @@ SET(QGIS_ANALYSIS_HDRS openstreetmap/qgsosmdatabase.h openstreetmap/qgsosmdownload.h openstreetmap/qgsosmimport.h + + network/qgsgraph.h + network/qgsgraphbuilderintr.h + network/qgsgraphbuilder.h + network/qgsarcproperter.h + network/qgsspeedarcproperter.h + network/qgsdistancearcproperter.h + network/qgsgraphdirector.h + network/qgslinevectorlayerdirector.h + network/qgsgraphanalyzer.h ) INCLUDE_DIRECTORIES( @@ -143,6 +161,7 @@ INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/../core/raster ${CMAKE_CURRENT_SOURCE_DIR}/../core/symbology-ng interpolation + network ) INCLUDE_DIRECTORIES(SYSTEM ${PROJ_INCLUDE_DIR} diff --git a/src/analysis/network/CMakeLists.txt b/src/analysis/network/CMakeLists.txt deleted file mode 100644 index 9c236e25631a..000000000000 --- a/src/analysis/network/CMakeLists.txt +++ /dev/null @@ -1,100 +0,0 @@ - - -############################################################# -# sources - -SET(QGIS_NETWORK_ANALYSIS_SRCS - qgsgraph.cpp - qgsgraphbuilder.cpp - qgsspeedarcproperter.cpp - qgsdistancearcproperter.cpp - qgslinevectorlayerdirector.cpp - qgsgraphanalyzer.cpp -) - -INCLUDE_DIRECTORIES(BEFORE raster) - -SET(QGIS_NETWORK_ANALYSIS_MOC_HDRS - qgsgraphdirector.h - qgslinevectorlayerdirector.h -) - -QT5_WRAP_CPP(QGIS_NETWORK_ANALYSIS_MOC_SRCS ${QGIS_NETWORK_ANALYSIS_MOC_HDRS}) - -# install headers - -SET(QGIS_NETWORK_ANALYSIS_HDRS - qgsgraph.h - qgsgraphbuilderintr.h - qgsgraphbuilder.h - qgsarcproperter.h - qgsspeedarcproperter.h - qgsdistancearcproperter.h - qgsgraphdirector.h - qgslinevectorlayerdirector.h - qgsgraphanalyzer.h -) - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}../../core/ -) -INCLUDE_DIRECTORIES(SYSTEM - ${PROJ_INCLUDE_DIR} - ${GEOS_INCLUDE_DIR} - ${GDAL_INCLUDE_DIR} -) - -############################################################# -# qgis_analysis library - -ADD_LIBRARY(qgis_networkanalysis SHARED ${QGIS_NETWORK_ANALYSIS_SRCS} ${QGIS_NETWORK_ANALYSIS_MOC_SRCS} ${QGIS_NETWORK_ANALYSIS_HDRS}) - -IF(MSVC) - SET_TARGET_PROPERTIES(qgis_networkanalysis PROPERTIES LINK_FLAGS "/FORCE:MULTIPLE") -ENDIF(MSVC) - -IF(NOT APPLE) - INSTALL(FILES ${QGIS_NETWORK_ANALYSIS_HDRS} ${QGIS_NETWORK_ANALYSIS_MOC_HDRS} DESTINATION ${QGIS_INCLUDE_DIR}) -ELSE(NOT APPLE) - SET_TARGET_PROPERTIES(qgis_networkanalysis PROPERTIES - CLEAN_DIRECT_OUTPUT 1 - FRAMEWORK 1 - FRAMEWORK_VERSION "${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}" - MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_SOURCE_DIR}/mac/framework.info.plist.in" - MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${COMPLETE_VERSION} - MACOSX_FRAMEWORK_IDENTIFIER org.qgis.qgis3_networkanalysis - BUILD_WITH_INSTALL_RPATH TRUE - PUBLIC_HEADER "${QGIS_NETWORK_ANALYSIS_HDRS};${QGIS_NETWORK_ANALYSIS_MOC_HDRS}" - LINK_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" - ) -ENDIF(NOT APPLE) - -#generate unversioned libs for android -IF (NOT ANDROID) - SET_TARGET_PROPERTIES(qgis_networkanalysis PROPERTIES - VERSION ${COMPLETE_VERSION} - SOVERSION ${COMPLETE_VERSION} - ) -ENDIF (NOT ANDROID) - -ADD_DEPENDENCIES(qgis_networkanalysis qgis_core) - -TARGET_LINK_LIBRARIES(qgis_networkanalysis qgis_core) - -# install - -INSTALL(TARGETS qgis_networkanalysis - RUNTIME DESTINATION ${QGIS_BIN_DIR} - LIBRARY DESTINATION ${QGIS_LIB_DIR} - ARCHIVE DESTINATION ${QGIS_LIB_DIR} - FRAMEWORK DESTINATION ${QGIS_FW_SUBDIR} - PUBLIC_HEADER DESTINATION ${QGIS_INCLUDE_DIR}) - -# Mac dev frameworks - -IF (APPLE AND QGIS_MACAPP_INSTALL_DEV) - INSTALL(TARGETS qgis_networkanalysis FRAMEWORK DESTINATION ${QGIS_MACAPP_DEV_PREFIX}) - INSTALL(CODE "EXECUTE_PROCESS(COMMAND install_name_tool -id \"${QGIS_MACAPP_DEV_PREFIX}/qgis_networkanalysis.framework/Versions/${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}/qgis_networkanalysis\" \"$ENV{DESTDIR}${QGIS_MACAPP_DEV_PREFIX}/qgis_networkanalysis.framework/qgis_networkanalysis\")") - INSTALL(CODE "EXECUTE_PROCESS(COMMAND install_name_tool -change \"${CMAKE_INSTALL_NAME_DIR}/qgis_core.framework/Versions/${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}/qgis_core\" \"${QGIS_MACAPP_DEV_PREFIX}/qgis_core.framework/Versions/${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}/qgis_core\" \"$ENV{DESTDIR}${QGIS_MACAPP_DEV_PREFIX}/qgis_networkanalysis.framework/qgis_networkanalysis\")") -ENDIF (APPLE AND QGIS_MACAPP_INSTALL_DEV) diff --git a/src/analysis/network/qgsarcproperter.h b/src/analysis/network/qgsarcproperter.h index 4f1251d27223..f082583ed6a7 100644 --- a/src/analysis/network/qgsarcproperter.h +++ b/src/analysis/network/qgsarcproperter.h @@ -22,7 +22,7 @@ #include /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsArcProperter * \brief QgsArcProperter is a strategy pattern. * You can use it for customize arc property. For example look at QgsDistanceArcProperter and QgsSpeedArcProperter diff --git a/src/analysis/network/qgsdistancearcproperter.h b/src/analysis/network/qgsdistancearcproperter.h index 2370c02afe04..908ee27dc5bc 100644 --- a/src/analysis/network/qgsdistancearcproperter.h +++ b/src/analysis/network/qgsdistancearcproperter.h @@ -16,13 +16,9 @@ #ifndef QGSDISTANCEARCPROPERTER_H #define QGSDISTANCEARCPROPERTER_H -// QT4 includes -#include - -// QGIS includes #include -/** \ingroup networkanalysis +/** \ingroup analysis * \class QgsDistanceArcProperter */ class ANALYSIS_EXPORT QgsDistanceArcProperter : public QgsArcProperter diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index 209c01ab15c5..fdf3a2e056fb 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -35,7 +35,7 @@ class QgsGraphVertex; /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraphArc * \brief This class implements a graph edge */ diff --git a/src/analysis/network/qgsgraphanalyzer.h b/src/analysis/network/qgsgraphanalyzer.h index ac7a58fa3d68..4dcf63ddaaf1 100644 --- a/src/analysis/network/qgsgraphanalyzer.h +++ b/src/analysis/network/qgsgraphanalyzer.h @@ -22,7 +22,7 @@ class QgsGraph; -/** \ingroup networkanalysis +/** \ingroup analysis * QGIS class with graph analysis functions */ diff --git a/src/analysis/network/qgsgraphbuilder.h b/src/analysis/network/qgsgraphbuilder.h index 8e436989e867..8cbe1d09e1e4 100644 --- a/src/analysis/network/qgsgraphbuilder.h +++ b/src/analysis/network/qgsgraphbuilder.h @@ -25,7 +25,7 @@ class QgsCoordinateTransform; class QgsGraph; /** -* \ingroup networkanalysis +* \ingroup analysis * \class QgsGraphBuilder * \brief This class is used for making the QgsGraph object */ diff --git a/src/analysis/network/qgsgraphbuilderintr.h b/src/analysis/network/qgsgraphbuilderintr.h index 5514609f88dc..ca98e034a07d 100644 --- a/src/analysis/network/qgsgraphbuilderintr.h +++ b/src/analysis/network/qgsgraphbuilderintr.h @@ -24,7 +24,7 @@ #include /** -* \ingroup networkanalysis +* \ingroup analysis * \class QgsGraphBuilderInterface * \brief Determine interface for creating a graph. Contains the settings of the graph. QgsGraphBuilder and QgsGraphDirector both use a Builder pattern */ diff --git a/src/analysis/network/qgsgraphdirector.h b/src/analysis/network/qgsgraphdirector.h index b24b44d73f99..d6d78f671d1a 100644 --- a/src/analysis/network/qgsgraphdirector.h +++ b/src/analysis/network/qgsgraphdirector.h @@ -26,7 +26,7 @@ class QgsGraphBuilderInterface; /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraphDirector * \brief Determine making the graph. QgsGraphBuilder and QgsGraphDirector is a builder patter. */ diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgslinevectorlayerdirector.h index 9e83b49e8d28..5bb34b5d5162 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgslinevectorlayerdirector.h @@ -22,7 +22,7 @@ class QgsGraphBuilderInterface; class QgsVectorLayer; /** -* \ingroup networkanalysis +* \ingroup analysis * \class QgsLineVectorLayerDirector * \brief Determine making the graph from vector line layer */ diff --git a/src/analysis/network/qgsspeedarcproperter.h b/src/analysis/network/qgsspeedarcproperter.h index 62d1516710a3..a25a2fa7b5c7 100644 --- a/src/analysis/network/qgsspeedarcproperter.h +++ b/src/analysis/network/qgsspeedarcproperter.h @@ -18,7 +18,7 @@ #include -/** \ingroup networkanalysis +/** \ingroup analysis * \class QgsSpeedArcProperter */ class ANALYSIS_EXPORT QgsSpeedArcProperter : public QgsArcProperter diff --git a/src/plugins/roadgraph/CMakeLists.txt b/src/plugins/roadgraph/CMakeLists.txt index f902fc687e5e..8743df9c0064 100644 --- a/src/plugins/roadgraph/CMakeLists.txt +++ b/src/plugins/roadgraph/CMakeLists.txt @@ -50,7 +50,7 @@ ADD_LIBRARY (roadgraphplugin MODULE ${VRP_SRCS} ${VRP_MOC_SRCS} ${VRP_RCC_SRCS}) TARGET_LINK_LIBRARIES(roadgraphplugin qgis_core qgis_gui - qgis_networkanalysis + qgis_analysis ) diff --git a/tests/src/python/test_qgssipcoverage.py b/tests/src/python/test_qgssipcoverage.py index e7f660200753..cdef265cb855 100644 --- a/tests/src/python/test_qgssipcoverage.py +++ b/tests/src/python/test_qgssipcoverage.py @@ -23,7 +23,6 @@ from qgis.analysis import * # NOQA from qgis.core import * # NOQA from qgis.gui import * # NOQA -from qgis.networkanalysis import * # NOQA try: from qgis.server import * # NOQA except: From 5cbf9d51297f92c2c606f3fe4df3ae5aaf65cce7 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 16 Nov 2016 16:48:41 +0200 Subject: [PATCH 845/897] remove references to networkanalysis from scrips and packaging files --- cmake/QsciAPI.cmake | 2 +- debian/control | 14 -------------- debian/control.in | 14 -------------- debian/libqgis-dev.install.in | 1 - debian/libqgis-networkanalysis{QGIS_ABI}.install | 1 - ...gis-networkanalysis{QGIS_ABI}.lintian-overrides | 1 - debian/python-qgis.install.in | 1 - doc/modules.dox | 10 +++------- ms-windows/osgeo4w/package.cmd | 1 - python/analysis/network/qgsarcproperter.sip | 2 +- python/analysis/network/qgsgraph.sip | 6 +++--- python/analysis/network/qgsgraphbuilder.sip | 2 +- python/analysis/network/qgsgraphbuilderintr.sip | 2 +- python/analysis/network/qgsgraphdirector.sip | 2 +- .../network/qgslinevectorlayerdirector.sip | 2 +- rpm/qgis.spec.template | 9 ++++----- scripts/replacev2.sh | 2 +- src/analysis/network/qgsgraph.h | 4 ++-- 18 files changed, 19 insertions(+), 57 deletions(-) delete mode 100644 debian/libqgis-networkanalysis{QGIS_ABI}.install delete mode 100644 debian/libqgis-networkanalysis{QGIS_ABI}.lintian-overrides diff --git a/cmake/QsciAPI.cmake b/cmake/QsciAPI.cmake index 4bc995b6e9e2..e5de2229d921 100644 --- a/cmake/QsciAPI.cmake +++ b/cmake/QsciAPI.cmake @@ -22,7 +22,7 @@ ENDIF(EXISTS "${CMAKE_BINARY_DIR}/python/qgis.gui.api") # add qgis.core.NULL attribute defined in /python/__init__.py for QPyNullVariant FILE(APPEND "${QGIS_PYTHON_API_FILE}" "qgis.core.NULL?7\n") -FOREACH(apiFile qgis.core.api qgis.gui.api qgis.analysis.api qgis.networkanalysis.api qgis.server.api) +FOREACH(apiFile qgis.core.api qgis.gui.api qgis.analysis.api qgis.server.api) SET(api "${CMAKE_BINARY_DIR}/python/${apiFile}") IF(EXISTS "${api}") FILE(READ "${api}" FILE_CONTENT) diff --git a/debian/control b/debian/control index 34d66b5086eb..09322e80d09e 100644 --- a/debian/control +++ b/debian/control @@ -129,18 +129,6 @@ Description: QGIS - shared analysis library . This package contains the shared analysis library. -Package: libqgis-networkanalysis2.99.0 -Architecture: any -Section: libs -Depends: - ${shlibs:Depends}, - ${misc:Depends} -Description: QGIS - shared network analysis library - QGIS is a Geographic Information System (GIS) which manages, analyzes and - display databases of geographic information. - . - This package contains the shared network analysis library. - Package: libqgisgrass7-2.99.0 Architecture: any Section: libs @@ -204,7 +192,6 @@ Depends: libqgis-core2.99.0 (= ${binary:Version}), libqgis-gui2.99.0 (= ${binary:Version}), libqgis-analysis2.99.0 (= ${binary:Version}), - libqgis-networkanalysis2.99.0 (= ${binary:Version}), libqgisgrass7-2.99.0 (= ${binary:Version}), libqgispython2.99.0 (= ${binary:Version}), libsqlite3-dev, @@ -241,7 +228,6 @@ Depends: libqgis-core2.99.0 (= ${binary:Version}), libqgis-gui2.99.0 (= ${binary:Version}), libqgis-analysis2.99.0 (= ${binary:Version}), - libqgis-networkanalysis2.99.0 (= ${binary:Version}), libqgisgrass7-2.99.0 (= ${binary:Version}), libqgispython2.99.0 (= ${binary:Version}), ${misc:Depends} diff --git a/debian/control.in b/debian/control.in index 86e1668b7164..c7316b5e5da5 100644 --- a/debian/control.in +++ b/debian/control.in @@ -132,18 +132,6 @@ Description: QGIS - shared analysis library . This package contains the shared analysis library. -Package: libqgis-networkanalysis{QGIS_ABI} -Architecture: any -Section: libs -Depends: - ${shlibs:Depends}, - ${misc:Depends} -Description: QGIS - shared network analysis library - QGIS is a Geographic Information System (GIS) which manages, analyzes and - display databases of geographic information. - . - This package contains the shared network analysis library. - Package: libqgisgrass{GRASSVER}-{QGIS_ABI} Architecture: any Section: libs @@ -207,7 +195,6 @@ Depends: libqgis-core{QGIS_ABI} (= ${binary:Version}), libqgis-gui{QGIS_ABI} (= ${binary:Version}), libqgis-analysis{QGIS_ABI} (= ${binary:Version}), - libqgis-networkanalysis{QGIS_ABI} (= ${binary:Version}), libqgisgrass{GRASSVER}-{QGIS_ABI} (= ${binary:Version}), libqgispython{QGIS_ABI} (= ${binary:Version}), libsqlite3-dev, @@ -244,7 +231,6 @@ Depends: libqgis-core{QGIS_ABI} (= ${binary:Version}), libqgis-gui{QGIS_ABI} (= ${binary:Version}), libqgis-analysis{QGIS_ABI} (= ${binary:Version}), - libqgis-networkanalysis{QGIS_ABI} (= ${binary:Version}), libqgisgrass{GRASSVER}-{QGIS_ABI} (= ${binary:Version}), libqgispython{QGIS_ABI} (= ${binary:Version}), ${misc:Depends} diff --git a/debian/libqgis-dev.install.in b/debian/libqgis-dev.install.in index da0f432bce58..effa246be063 100644 --- a/debian/libqgis-dev.install.in +++ b/debian/libqgis-dev.install.in @@ -3,7 +3,6 @@ usr/lib/libqgis_app.so usr/lib/libqgis_core.so usr/lib/libqgis_gui.so usr/lib/libqgis_analysis.so -usr/lib/libqgis_networkanalysis.so #server#usr/lib/libqgis_server.so usr/lib/libqgisgrass{GRASSVER}.so usr/lib/libqgispython.so diff --git a/debian/libqgis-networkanalysis{QGIS_ABI}.install b/debian/libqgis-networkanalysis{QGIS_ABI}.install deleted file mode 100644 index 2b62379e12e3..000000000000 --- a/debian/libqgis-networkanalysis{QGIS_ABI}.install +++ /dev/null @@ -1 +0,0 @@ -usr/lib/libqgis_networkanalysis.so.{QGIS_ABI} diff --git a/debian/libqgis-networkanalysis{QGIS_ABI}.lintian-overrides b/debian/libqgis-networkanalysis{QGIS_ABI}.lintian-overrides deleted file mode 100644 index d44aa9f2cc68..000000000000 --- a/debian/libqgis-networkanalysis{QGIS_ABI}.lintian-overrides +++ /dev/null @@ -1 +0,0 @@ -libqgis-networkanalysis{QGIS_ABI}: no-symbols-control-file diff --git a/debian/python-qgis.install.in b/debian/python-qgis.install.in index 3c1a11dd3f07..fd09a372cd6b 100644 --- a/debian/python-qgis.install.in +++ b/debian/python-qgis.install.in @@ -3,7 +3,6 @@ usr/lib/python*/*-packages/qgis/*.so usr/lib/python*/*-packages/qgis/core/* usr/lib/python*/*-packages/qgis/gui/* usr/lib/python*/*-packages/qgis/analysis/* -usr/lib/python*/*-packages/qgis/networkanalysis/* usr/lib/python*/*-packages/qgis/PyQt/* usr/lib/python*/*-packages/qgis/testing/* usr/lib/python*/*-packages/pyspatialite/* diff --git a/doc/modules.dox b/doc/modules.dox index bc852a574f88..97afec1177fe 100644 --- a/doc/modules.dox +++ b/doc/modules.dox @@ -12,14 +12,10 @@ The GUI library is build on top of the CORE library and adds reusable GUI widget /** @defgroup analysis analysis library -The ANALYSIS library is built on top of CORE library and provides +The ANALYSIS library is built on top of CORE library and provides high level tools for carrying out spatial analysis on vector and raster data. -*/ - -/** @defgroup networkanalysis network analysis library - -The NETWORK_ANALYSIS library provides high level tools for building network -topologies and analysing them. +It also contains high level tools for building network topologies and analysing +them. */ /** @defgroup server server library diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index e49ce0a2b577..36cc1485309f 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -299,7 +299,6 @@ tar -C %OSGEO4W_ROOT% -cjf %ARCH%/release/qgis/%PACKAGENAME%-common/%PACKAGENAME --exclude "*.pyc" ^ "apps/%PACKAGENAME%/bin/qgispython.dll" ^ "apps/%PACKAGENAME%/bin/qgis_analysis.dll" ^ - "apps/%PACKAGENAME%/bin/qgis_networkanalysis.dll" ^ "apps/%PACKAGENAME%/bin/qgis_core.dll" ^ "apps/%PACKAGENAME%/bin/qgis_gui.dll" ^ "apps/%PACKAGENAME%/doc/" ^ diff --git a/python/analysis/network/qgsarcproperter.sip b/python/analysis/network/qgsarcproperter.sip index 26ba8f4ffbaf..92bbe0ed4b51 100644 --- a/python/analysis/network/qgsarcproperter.sip +++ b/python/analysis/network/qgsarcproperter.sip @@ -4,7 +4,7 @@ %End /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsArcProperter * \brief QgsArcProperter is a strategy pattern. * You can use it for customize arc property. For example look at QgsDistanceArcProperter or QgsSpeedArcProperter diff --git a/python/analysis/network/qgsgraph.sip b/python/analysis/network/qgsgraph.sip index 5950a6d5c300..71951d249338 100644 --- a/python/analysis/network/qgsgraph.sip +++ b/python/analysis/network/qgsgraph.sip @@ -1,5 +1,5 @@ /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraphArc * \brief This class implements a graph edge */ @@ -38,7 +38,7 @@ class QgsGraphArc typedef QList< int > QgsGraphArcIdList; /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraphVertex * \brief This class implements a graph vertex */ @@ -77,7 +77,7 @@ class QgsGraphVertex }; /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraph * \brief Mathematics graph representation */ diff --git a/python/analysis/network/qgsgraphbuilder.sip b/python/analysis/network/qgsgraphbuilder.sip index 66abf9b41365..3dbdb3cdcbfd 100644 --- a/python/analysis/network/qgsgraphbuilder.sip +++ b/python/analysis/network/qgsgraphbuilder.sip @@ -1,5 +1,5 @@ /** -* \ingroup networkanalysis +* \ingroup analysis * \class QgsGraphBuilder * \brief This class making the QgsGraph object */ diff --git a/python/analysis/network/qgsgraphbuilderintr.sip b/python/analysis/network/qgsgraphbuilderintr.sip index 8ddf11224033..e44afd285a44 100644 --- a/python/analysis/network/qgsgraphbuilderintr.sip +++ b/python/analysis/network/qgsgraphbuilderintr.sip @@ -3,7 +3,7 @@ %End /** -* \ingroup networkanalysis +* \ingroup analysis * \class QgsGraphBuilderInterface * \brief Determine interface for creating a graph. Contains the settings of the graph. QgsGraphBuilder and QgsGraphDirector is a Builder pattern */ diff --git a/python/analysis/network/qgsgraphdirector.sip b/python/analysis/network/qgsgraphdirector.sip index aa620a56769b..159dc191a55e 100644 --- a/python/analysis/network/qgsgraphdirector.sip +++ b/python/analysis/network/qgsgraphdirector.sip @@ -3,7 +3,7 @@ %End /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraphDirector * \brief Determine making the graph. QgsGraphBuilder and QgsGraphDirector is a builder patter. */ diff --git a/python/analysis/network/qgslinevectorlayerdirector.sip b/python/analysis/network/qgslinevectorlayerdirector.sip index db8c845bb9ee..67504688bc63 100644 --- a/python/analysis/network/qgslinevectorlayerdirector.sip +++ b/python/analysis/network/qgslinevectorlayerdirector.sip @@ -1,5 +1,5 @@ /** -* \ingroup networkanalysis +* \ingroup analysis * \class QgsLineVectorLayerDirector * \brief Determine making the graph from vector line layer */ diff --git a/rpm/qgis.spec.template b/rpm/qgis.spec.template index f9dc2e35cd59..9f217f98bcb4 100644 --- a/rpm/qgis.spec.template +++ b/rpm/qgis.spec.template @@ -134,11 +134,11 @@ Requires: %{name}%{?_isa} = %{version}-%{release} # the soname might stay the same, it won't work anymore. #http://hub.qgis.org/issues/5274 Requires: grass = 6.4.4 - + %description grass GRASS plugin for QGIS required to interface with the GRASS system. -%package python +%package python Summary: Python integration and plug-ins for QGIS Group: Applications/Engineering Requires: %{name}%{?_isa} = %{version}-%{release} @@ -158,7 +158,7 @@ Requires: qscintilla-python %description python Python integration and plug-ins for QGIS. -%package server +%package server Summary: FCGI-based OGC web map server Group: Applications/Engineering Requires: %{name}%{?_isa} = %{version}-%{release} @@ -167,7 +167,7 @@ Provides: mapserver = %{version}-%{release} Obsoletes: mapserver < 2.8.1-1 %description server -This FastCGI OGC web map server implements OGC WMS 1.3.0 and 1.1.1. +This FastCGI OGC web map server implements OGC WMS 1.3.0 and 1.1.1. The services are prepared as regular projects in QGIS. They're rendered using the QGIS libraries. The server also supports SLD (Styled Layer Descriptor) for styling. Sample configurations for Httpd and Lighttpd are included. @@ -343,7 +343,6 @@ update-mime-database %{?fedora:-n} %{_datadir}/mime &> /dev/null || : %{_libdir}/lib%{name}_analysis.so.* %{_libdir}/lib%{name}_core.so.* %{_libdir}/lib%{name}_gui.so.* -%{_libdir}/lib%{name}_networkanalysis.so.* %{_libdir}/lib%{name}_server.so.* %{_libdir}/%{name}/ %{_qt4_prefix}/plugins/sqldrivers/libqsqlspatialite.so diff --git a/scripts/replacev2.sh b/scripts/replacev2.sh index aedcf07a5dd9..7971e2b4b3e4 100755 --- a/scripts/replacev2.sh +++ b/scripts/replacev2.sh @@ -2,7 +2,7 @@ set -e -codepaths=$(echo python/{analysis,console,core,custom_widgets,gui,networkanalysis,plugins,pyplugin_installer,server,sip_helpers,testing} src/ tests/) +codepaths=$(echo python/{analysis,console,core,custom_widgets,gui,plugins,pyplugin_installer,server,sip_helpers,testing} src/ tests/) repl= s=$(mktemp -t skipped.XXXX.log) diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index fdf3a2e056fb..0f4cf909b203 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -79,7 +79,7 @@ class ANALYSIS_EXPORT QgsGraphArc typedef QList< int > QgsGraphArcIdList; /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraphVertex * \brief This class implements a graph vertex */ @@ -122,7 +122,7 @@ class ANALYSIS_EXPORT QgsGraphVertex }; /** - * \ingroup networkanalysis + * \ingroup analysis * \class QgsGraph * \brief Mathematics graph representation */ From d0f8863e50f53c2a62c044344a9776208df02ee3 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 16 Nov 2016 17:00:09 +0200 Subject: [PATCH 846/897] doxymentation --- src/analysis/network/qgsspeedarcproperter.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/analysis/network/qgsspeedarcproperter.h b/src/analysis/network/qgsspeedarcproperter.h index a25a2fa7b5c7..87f896e55493 100644 --- a/src/analysis/network/qgsspeedarcproperter.h +++ b/src/analysis/network/qgsspeedarcproperter.h @@ -20,14 +20,25 @@ /** \ingroup analysis * \class QgsSpeedArcProperter + * \note added in QGIS 3.0 + * + * \brief Used for calculating arc property taking into account travel time. */ class ANALYSIS_EXPORT QgsSpeedArcProperter : public QgsArcProperter { public: + + /** + * Constructor for QgsSpeedArcProperter. + */ QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ); + //! Returns caluclated edge property QVariant property( double distance, const QgsFeature& f ) const override; + /** QgsGraphDirector will call this method for fetching attributes + * needed to calculate arc properties from the source layer + */ QgsAttributeList requiredAttributes() const override; private: From 137b19845a9ff04f2cddf0a66e5b97c4c82b8c15 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 17 Nov 2016 14:17:23 +0200 Subject: [PATCH 847/897] add note to the API breaks doc --- doc/api_break.dox | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 190f1b947fce..4b9c40ff4f6c 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -251,6 +251,7 @@ General changes {#qgis_api_break_3_0_global} - All importXML() methods have been renamed to importXml() - All methods taking or returning QGis::WkbType have been changed to use QgsWkbTypes::Type - All methods taking or returning QGis::GeometryType have been changed to use QgsWkbTypes::GeometryType +- Network analysis library has been merged into analysis library Data Providers {#qgis_api_break_3_0_DataProviders} @@ -768,7 +769,7 @@ QgsEditFormConfig {#qgis_api_break_3_0_QgsEditFormConfig} - widgetType() and widgetConfig() now reflect only the user configured values. QgsEditorWidgetRegistry::instance()->findBest() must be used instead. - widgetType(), widgetConfig(), setWidgetType(), setWidgetConfig() and removeWidgetConfig() now only take a string as first parameter. Access by index has been removed. -- expression(), setExpression(), expressionDescription() and setExpressionDescription() +- expression(), setExpression(), expressionDescription() and setExpressionDescription() have been removed. Use QgsVectorLayer.setConstraintExpression()/constraintExpression(), or QgsField.constraintExpression()/QgsField.constraintDescription() instead. - notNull() and setNotNull() have been removed. Use QgsVectorLayer.setFieldConstraint()/fieldConstraints(), or QgsField.constraints() instead. From 5992f74e04eead414da2ea682e22c4ecf4008c47 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 17 Nov 2016 17:30:10 +0200 Subject: [PATCH 848/897] [API] rename QgsArcProperter to QgsStrategy Also update subclasses names and do some more refactoring. --- python/analysis/analysis.sip | 8 +- python/analysis/network/qgsarcproperter.sip | 45 ----------- .../network/qgsdistancearcproperter.sip | 9 --- .../analysis/network/qgsdistancestrategy.sip | 9 +++ python/analysis/network/qgsgraph.sip | 57 +++++++------- python/analysis/network/qgsgraphbuilder.sip | 6 +- ...rintr.sip => qgsgraphbuilderinterface.sip} | 29 +++---- python/analysis/network/qgsgraphdirector.sip | 22 +++--- .../network/qgslinevectorlayerdirector.sip | 2 +- .../analysis/network/qgsspeedarcproperter.sip | 13 ---- python/analysis/network/qgsspeedstrategy.sip | 13 ++++ python/analysis/network/qgsstrategy.sip | 50 +++++++++++++ src/analysis/CMakeLists.txt | 12 +-- ...cproperter.cpp => qgsdistancestrategy.cpp} | 6 +- ...cearcproperter.h => qgsdistancestrategy.h} | 16 ++-- src/analysis/network/qgsgraph.cpp | 70 +++++++++-------- src/analysis/network/qgsgraph.h | 75 +++++++++---------- src/analysis/network/qgsgraphanalyzer.cpp | 42 +++++------ src/analysis/network/qgsgraphanalyzer.h | 43 ++++++----- src/analysis/network/qgsgraphbuilder.cpp | 6 +- src/analysis/network/qgsgraphbuilder.h | 10 +-- ...ilderintr.h => qgsgraphbuilderinterface.h} | 32 ++++---- src/analysis/network/qgsgraphdirector.h | 27 ++++--- .../network/qgslinevectorlayerdirector.cpp | 32 ++++---- .../network/qgslinevectorlayerdirector.h | 11 +-- ...darcproperter.cpp => qgsspeedstrategy.cpp} | 12 +-- ...speedarcproperter.h => qgsspeedstrategy.h} | 31 ++++---- .../{qgsarcproperter.h => qgsstrategy.h} | 34 +++++---- src/plugins/roadgraph/CMakeLists.txt | 1 - src/plugins/roadgraph/roadgraphplugin.cpp | 10 +-- src/plugins/roadgraph/shortestpathwidget.cpp | 16 ++-- src/plugins/roadgraph/speedproperter.cpp | 41 ---------- src/plugins/roadgraph/speedproperter.h | 34 --------- 33 files changed, 381 insertions(+), 443 deletions(-) delete mode 100644 python/analysis/network/qgsarcproperter.sip delete mode 100644 python/analysis/network/qgsdistancearcproperter.sip create mode 100644 python/analysis/network/qgsdistancestrategy.sip rename python/analysis/network/{qgsgraphbuilderintr.sip => qgsgraphbuilderinterface.sip} (70%) delete mode 100644 python/analysis/network/qgsspeedarcproperter.sip create mode 100644 python/analysis/network/qgsspeedstrategy.sip create mode 100644 python/analysis/network/qgsstrategy.sip rename src/analysis/network/{qgsdistancearcproperter.cpp => qgsdistancestrategy.cpp} (85%) rename src/analysis/network/{qgsdistancearcproperter.h => qgsdistancestrategy.h} (69%) rename src/analysis/network/{qgsgraphbuilderintr.h => qgsgraphbuilderinterface.h} (81%) rename src/analysis/network/{qgsspeedarcproperter.cpp => qgsspeedstrategy.cpp} (77%) rename src/analysis/network/{qgsspeedarcproperter.h => qgsspeedstrategy.h} (60%) rename src/analysis/network/{qgsarcproperter.h => qgsstrategy.h} (59%) delete mode 100644 src/plugins/roadgraph/speedproperter.cpp delete mode 100644 src/plugins/roadgraph/speedproperter.h diff --git a/python/analysis/analysis.sip b/python/analysis/analysis.sip index bf8b037c2704..9c07ec216b6b 100644 --- a/python/analysis/analysis.sip +++ b/python/analysis/analysis.sip @@ -54,10 +54,10 @@ %Include raster/qgstotalcurvaturefilter.sip %Include network/qgsgraph.sip -%Include network/qgsarcproperter.sip -%Include network/qgsspeedarcproperter.sip -%Include network/qgsdistancearcproperter.sip -%Include network/qgsgraphbuilderintr.sip +%Include network/qgsstrategy.sip +%Include network/qgsspeedstrategy.sip +%Include network/qgsdistancestrategy.sip +%Include network/qgsgraphbuilderinterface.sip %Include network/qgsgraphbuilder.sip %Include network/qgsgraphdirector.sip %Include network/qgslinevectorlayerdirector.sip diff --git a/python/analysis/network/qgsarcproperter.sip b/python/analysis/network/qgsarcproperter.sip deleted file mode 100644 index 92bbe0ed4b51..000000000000 --- a/python/analysis/network/qgsarcproperter.sip +++ /dev/null @@ -1,45 +0,0 @@ -%ModuleHeaderCode -#include -#include -%End - -/** - * \ingroup analysis - * \class QgsArcProperter - * \brief QgsArcProperter is a strategy pattern. - * You can use it for customize arc property. For example look at QgsDistanceArcProperter or QgsSpeedArcProperter - */ -class QgsArcProperter -{ -%TypeHeaderCode -#include -%End - -%ConvertToSubClassCode - if ( dynamic_cast< QgsDistanceArcProperter* > ( sipCpp ) != NULL ) - sipType = sipType_QgsDistanceArcProperter; - else if ( dynamic_cast< QgsSpeedArcProperter* > ( sipCpp ) != NULL ) - sipType = sipType_QgsSpeedArcProperter; - else - sipType = NULL; -%End - - public: - /** - * default constructor - */ - QgsArcProperter(); - - virtual ~QgsArcProperter(); - - /** - * QgsGraphDirector call this method for fetching attribute from source layer - * \return required attributes list - */ - virtual QgsAttributeList requiredAttributes() const; - - /** - * calculate and return adge property - */ - virtual QVariant property( double distance, const QgsFeature &f ) const; -}; diff --git a/python/analysis/network/qgsdistancearcproperter.sip b/python/analysis/network/qgsdistancearcproperter.sip deleted file mode 100644 index 93dcb3821dc8..000000000000 --- a/python/analysis/network/qgsdistancearcproperter.sip +++ /dev/null @@ -1,9 +0,0 @@ -class QgsDistanceArcProperter : QgsArcProperter -{ -%TypeHeaderCode -#include -%End - - public: - virtual QVariant property( double distance, const QgsFeature& ) const; -}; diff --git a/python/analysis/network/qgsdistancestrategy.sip b/python/analysis/network/qgsdistancestrategy.sip new file mode 100644 index 000000000000..7cc9f821a765 --- /dev/null +++ b/python/analysis/network/qgsdistancestrategy.sip @@ -0,0 +1,9 @@ +class QgsDistanceStrategy : QgsStrategy +{ +%TypeHeaderCode +#include +%End + + public: + virtual QVariant cost( double distance, const QgsFeature& ) const; +}; diff --git a/python/analysis/network/qgsgraph.sip b/python/analysis/network/qgsgraph.sip index 71951d249338..d565ebe73fe3 100644 --- a/python/analysis/network/qgsgraph.sip +++ b/python/analysis/network/qgsgraph.sip @@ -1,41 +1,41 @@ /** * \ingroup analysis - * \class QgsGraphArc + * \class QgsGraphEdge * \brief This class implements a graph edge */ -class QgsGraphArc +class QgsGraphEdge { %TypeHeaderCode #include %End public: - QgsGraphArc(); + QgsGraphEdge(); /** - * return property value - * @param propertyIndex property index + * Returns edge cost calculated using specified strategy + * @param strategyIndex strategy index */ - QVariant property( int propertyIndex ) const; + QVariant cost( int strategyIndex ) const; /** - * get array of properties + * Returns array of available strategies */ - QVector< QVariant > properties() const; + QVector< QVariant > strategies() const; /** - * return index of outgoing vertex + * Returns index of the outgoing vertex */ int outVertex() const; /** - * return index of incoming vertex + * Returns index of the incoming vertex */ int inVertex() const; }; -typedef QList< int > QgsGraphArcIdList; +typedef QList< int > QgsGraphEdgeIds; /** * \ingroup analysis @@ -50,7 +50,7 @@ class QgsGraphVertex public: /** - * default constructor. It need for QT's container, e.g. QVector + * Default constructor. It is needed for Qt's container, e.g. QVector */ QgsGraphVertex(); @@ -61,17 +61,17 @@ class QgsGraphVertex QgsGraphVertex( const QgsPoint& point ); /** - * return outgoing edges + * Returns outgoing edges ids */ - QgsGraphArcIdList outArc() const; + QgsGraphEdgeIds outEdges() const; /** - * return incoming edges + * Return incoming edges ids */ - QgsGraphArcIdList inArc() const; + QgsGraphEdgeIds inEdges() const; /** - * return vertex point + * Returns point associated with graph vertex */ QgsPoint point() const; }; @@ -91,39 +91,40 @@ class QgsGraph public: QgsGraph(); - // begin graph constructing methods + // Graph constructing methods + /** - * add vertex to a grap + * Add a vertex to the graph */ int addVertex( const QgsPoint& pt ); /** - * add edge to a graph + * Add an edge to the graph */ - int addArc( int outVertexIdx, int inVertexIdx, const QVector< QVariant >& properties ); + int addEdge( int outVertexIdx, int inVertexIdx, const QVector< QVariant >& strategies ); /** - * return vertex count + * Returns number of graph vertices */ int vertexCount() const; /** - * return vertex at index + * Returns vertex at given index */ const QgsGraphVertex& vertex( int idx ) const; /** - * return edge count + * Returns number of graph edges */ - int arcCount() const; + int edgeCount() const; /** - * return edge at index + * Returns edge at given index */ - const QgsGraphArc& arc( int idx ) const; + const QgsGraphEdge& edge( int idx ) const; /** - * find vertex by point + * Find vertex by associated point * \return vertex index */ int findVertex( const QgsPoint& pt ) const; diff --git a/python/analysis/network/qgsgraphbuilder.sip b/python/analysis/network/qgsgraphbuilder.sip index 3dbdb3cdcbfd..eecb95bf69bd 100644 --- a/python/analysis/network/qgsgraphbuilder.sip +++ b/python/analysis/network/qgsgraphbuilder.sip @@ -12,7 +12,7 @@ class QgsGraphBuilder : QgsGraphBuilderInterface public: /** - * default constructor + * Default constructor */ QgsGraphBuilder( const QgsCoordinateReferenceSystem& crs, bool otfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ); @@ -23,10 +23,10 @@ class QgsGraphBuilder : QgsGraphBuilderInterface */ virtual void addVertex( int id, const QgsPoint& pt ); - virtual void addArc( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& prop ); + virtual void addEdge( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& prop ); /** - * return QgsGraph result; + * Returns generated QgsGraph */ QgsGraph* graph() /Factory/; }; diff --git a/python/analysis/network/qgsgraphbuilderintr.sip b/python/analysis/network/qgsgraphbuilderinterface.sip similarity index 70% rename from python/analysis/network/qgsgraphbuilderintr.sip rename to python/analysis/network/qgsgraphbuilderinterface.sip index e44afd285a44..14205f1aa3f5 100644 --- a/python/analysis/network/qgsgraphbuilderintr.sip +++ b/python/analysis/network/qgsgraphbuilderinterface.sip @@ -10,7 +10,7 @@ class QgsGraphBuilderInterface { %TypeHeaderCode -#include +#include %End %ConvertToSubClassCode @@ -22,7 +22,7 @@ class QgsGraphBuilderInterface public: /** - * QgsGraphBuilderInterface constructor + * Default constructor * @param crs Coordinate reference system for new graph vertex * @param ctfEnabled enable coordinate transform from source graph CRS to CRS graph * @param topologyTolerance sqrt distance between source point as one graph vertex @@ -30,34 +30,37 @@ class QgsGraphBuilderInterface */ QgsGraphBuilderInterface( const QgsCoordinateReferenceSystem& crs, bool ctfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ); + //! Destructor + virtual ~QgsGraphBuilderInterface(); + + //! Returns destinaltion CRS QgsCoordinateReferenceSystem destinationCrs() const; - //! get coordinate transformation enabled + //! Returns coordinate transformation enabled bool coordinateTransformationEnabled(); - //! get topology tolerance + //! Returns topology tolerance double topologyTolerance(); - //! get measurement tool + //! Returns measurement tool QgsDistanceArea* distanceArea(); /** - * add vertex + * Add vertex to the graph * @param id vertex identifier - * @param pt vertex coordinate + * @param pt vertex coordinates * @note id and pt are redundant. You can use pt or id to identify the vertex */ virtual void addVertex( int id, const QgsPoint &pt ); /** - * add arc + * Add edge to the graph * @param pt1id first vertex identificator - * @param pt1 first vertex coordinate + * @param pt1 first vertex coordinates * @param pt2id second vertex identificator - * @param pt2 second vertex coordinate - * @param properties arc properties + * @param pt2 second vertex coordinates + * @param strategies optimization strategies * @note pt1id, pt1 and pt2id, pt2 is a redundant interface. You can use vertex coordinates or their identificators. */ - virtual void addArc( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& properties ); - + virtual void addEdge( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& strategies ); }; diff --git a/python/analysis/network/qgsgraphdirector.sip b/python/analysis/network/qgsgraphdirector.sip index 159dc191a55e..b30641ce6c83 100644 --- a/python/analysis/network/qgsgraphdirector.sip +++ b/python/analysis/network/qgsgraphdirector.sip @@ -30,25 +30,21 @@ class QgsGraphDirector : QObject virtual ~QgsGraphDirector(); /** - * Make a graph using RgGraphBuilder + * Make a graph using QgsGraphBuilder * - * @param builder The graph builder - * - * @param additionalPoints Vector of points that must be tied to the graph - * - * @param tiedPoints Vector of tied points - * - * @note if tiedPoints[i]==QgsPoint(0.0,0.0) then tied failed. + * @param builder the graph builder + * @param additionalPoints list of points that should be snapped to the graph + * @param tiedPoints list of snapped points + * @note if tiedPoints[i] == QgsPoint(0.0,0.0) then snapping failed. */ virtual void makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint > &additionalPoints, - QVector< QgsPoint> &tiedPoints /Out/ ); + QVector< QgsPoint > &snappedPoints /Out/ ) const; - void addProperter( QgsArcProperter* prop /Transfer/ ); + //! Add optimization strategy + void addStrategy( QgsStrategy* prop /Transfer/); - /** - * return Director name - */ + //! Returns director name virtual QString name() const = 0; }; diff --git a/python/analysis/network/qgslinevectorlayerdirector.sip b/python/analysis/network/qgslinevectorlayerdirector.sip index 67504688bc63..d387496658b7 100644 --- a/python/analysis/network/qgslinevectorlayerdirector.sip +++ b/python/analysis/network/qgslinevectorlayerdirector.sip @@ -34,7 +34,7 @@ class QgsLineVectorLayerDirector : QgsGraphDirector */ void makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, - QVector< QgsPoint>& tiedPoints /Out/ ) const; + QVector< QgsPoint>& snappedPoints /Out/ ) const; QString name() const; }; diff --git a/python/analysis/network/qgsspeedarcproperter.sip b/python/analysis/network/qgsspeedarcproperter.sip deleted file mode 100644 index 6ae01e5d0510..000000000000 --- a/python/analysis/network/qgsspeedarcproperter.sip +++ /dev/null @@ -1,13 +0,0 @@ -class QgsSpeedArcProperter : QgsArcProperter -{ -%TypeHeaderCode -#include -%End - - public: - QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ); - - QVariant property( double distance, const QgsFeature& f ) const; - - QgsAttributeList requiredAttributes() const; -}; diff --git a/python/analysis/network/qgsspeedstrategy.sip b/python/analysis/network/qgsspeedstrategy.sip new file mode 100644 index 000000000000..047beefdd42e --- /dev/null +++ b/python/analysis/network/qgsspeedstrategy.sip @@ -0,0 +1,13 @@ +class QgsSpeedStrategy : QgsStrategy +{ +%TypeHeaderCode +#include +%End + + public: + QgsSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ); + + QVariant cost( double distance, const QgsFeature& f ) const; + + QgsAttributeList requiredAttributes() const; +}; diff --git a/python/analysis/network/qgsstrategy.sip b/python/analysis/network/qgsstrategy.sip new file mode 100644 index 000000000000..63cc03ff4fcb --- /dev/null +++ b/python/analysis/network/qgsstrategy.sip @@ -0,0 +1,50 @@ +%ModuleHeaderCode +#include +#include +%End + +/** + * \ingroup analysis + * \class QgsStrategy + * \brief QgsStrategy defines strategy used for calculation of the edge cost. For example it can + * take into account travel distance, amount of time or money. Currently there are two strategies + * implemented in the analysis library: QgsDistanceStrategy and QgsSpeedStrategy. + * QgsStrategy implemented with strategy design pattern. + */ +class QgsStrategy +{ +%TypeHeaderCode +#include +%End + +%ConvertToSubClassCode + if ( dynamic_cast< QgsDistanceStrategy* > ( sipCpp ) != NULL ) + sipType = sipType_QgsStrategy; + else if ( dynamic_cast< QgsSpeedStrategy* > ( sipCpp ) != NULL ) + sipType = sipType_QgsSpeedStrategy; + else + sipType = NULL; +%End + + + public: + + /** + * Default constructor + */ + QgsStrategy(); + + virtual ~QgsStrategy(); + + /** + * Returns list of the source layer attributes needed for cost calculation. + * This method called by QgsGraphDirector. + * \return list of required attributes + */ + virtual QgsAttributeList requiredAttributes() const; + + /** + * Return edge cost + */ + virtual QVariant cost( double distance, const QgsFeature &f ) const; +}; diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index 5392c631f86a..2a15b1aa45a3 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -49,8 +49,8 @@ SET(QGIS_ANALYSIS_SRCS network/qgsgraph.cpp network/qgsgraphbuilder.cpp - network/qgsspeedarcproperter.cpp - network/qgsdistancearcproperter.cpp + network/qgsspeedstrategy.cpp + network/qgsdistancestrategy.cpp network/qgslinevectorlayerdirector.cpp network/qgsgraphanalyzer.cpp ) @@ -144,11 +144,11 @@ SET(QGIS_ANALYSIS_HDRS openstreetmap/qgsosmimport.h network/qgsgraph.h - network/qgsgraphbuilderintr.h + network/qgsgraphbuilderinterface.h network/qgsgraphbuilder.h - network/qgsarcproperter.h - network/qgsspeedarcproperter.h - network/qgsdistancearcproperter.h + network/qgsstrategy.h + network/qgsspeedstrategy.h + network/qgsdistancestrategy.h network/qgsgraphdirector.h network/qgslinevectorlayerdirector.h network/qgsgraphanalyzer.h diff --git a/src/analysis/network/qgsdistancearcproperter.cpp b/src/analysis/network/qgsdistancestrategy.cpp similarity index 85% rename from src/analysis/network/qgsdistancearcproperter.cpp rename to src/analysis/network/qgsdistancestrategy.cpp index e65bf56f58e2..e1c353dc02e7 100644 --- a/src/analysis/network/qgsdistancearcproperter.cpp +++ b/src/analysis/network/qgsdistancestrategy.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - qgsdistancearcproperter.h + qgsdistancestrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,9 +13,9 @@ * * ***************************************************************************/ -#include "qgsdistancearcproperter.h" +#include "qgsdistancestrategy.h" -QVariant QgsDistanceArcProperter::property( double distance, const QgsFeature& f ) const +QVariant QgsDistanceStrategy::cost( double distance, const QgsFeature& f ) const { Q_UNUSED( f ); return QVariant( distance ); diff --git a/src/analysis/network/qgsdistancearcproperter.h b/src/analysis/network/qgsdistancestrategy.h similarity index 69% rename from src/analysis/network/qgsdistancearcproperter.h rename to src/analysis/network/qgsdistancestrategy.h index 908ee27dc5bc..0d648714bd4b 100644 --- a/src/analysis/network/qgsdistancearcproperter.h +++ b/src/analysis/network/qgsdistancestrategy.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsdistancearcproperter.h + qgsdistancestrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,18 +13,20 @@ * * ***************************************************************************/ -#ifndef QGSDISTANCEARCPROPERTER_H -#define QGSDISTANCEARCPROPERTER_H +#ifndef QGSDISTANCESTRATEGY_H +#define QGSDISTANCESTRATEGY_H -#include +#include /** \ingroup analysis - * \class QgsDistanceArcProperter + * \class QgsDistanceStrategy + * \brief Strategy for caclucating edge cost based on its length. Should be + * used for finding shortest path between two points. */ -class ANALYSIS_EXPORT QgsDistanceArcProperter : public QgsArcProperter +class ANALYSIS_EXPORT QgsDistanceStrategy : public QgsStrategy { public: - virtual QVariant property( double distance, const QgsFeature& ) const override; + virtual QVariant cost( double distance, const QgsFeature& ) const override; }; #endif // QGSDISTANCEARCPROPERTER_H diff --git a/src/analysis/network/qgsgraph.cpp b/src/analysis/network/qgsgraph.cpp index 007ea5ebfbd2..c6797b83f4e6 100644 --- a/src/analysis/network/qgsgraph.cpp +++ b/src/analysis/network/qgsgraph.cpp @@ -1,17 +1,21 @@ /*************************************************************************** - * Copyright (C) 2011 by Sergey Yakushev * - * yakushevs list.ru * - * * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ + qgsgraph.cpp + -------------------------------------- + Date : 2011-04-01 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ /** * \file qgsgraph.cpp - * \brief implementation QgsGraph, QgsGraphVertex, QgsGraphArc + * \brief implementation QgsGraph, QgsGraphVertex, QgsGraphEdge */ #include "qgsgraph.h" @@ -26,20 +30,20 @@ int QgsGraph::addVertex( const QgsPoint& pt ) return mGraphVertexes.size() - 1; } -int QgsGraph::addArc( int outVertexIdx, int inVertexIdx, const QVector< QVariant >& properties ) +int QgsGraph::addEdge( int outVertexIdx, int inVertexIdx, const QVector< QVariant >& strategies ) { - QgsGraphArc e; + QgsGraphEdge e; - e.mProperties = properties; + e.mStrategies = strategies; e.mOut = outVertexIdx; e.mIn = inVertexIdx; - mGraphArc.push_back( e ); - int edgeIdx = mGraphArc.size() - 1; + mGraphEdges.push_back( e ); + int edgeIdx = mGraphEdges.size() - 1; - mGraphVertexes[ outVertexIdx ].mOutArc.push_back( edgeIdx ); - mGraphVertexes[ inVertexIdx ].mInArc.push_back( edgeIdx ); + mGraphVertexes[ outVertexIdx ].mOutEdges.push_back( edgeIdx ); + mGraphVertexes[ inVertexIdx ].mInEdges.push_back( edgeIdx ); - return mGraphArc.size() - 1; + return mGraphEdges.size() - 1; } const QgsGraphVertex& QgsGraph::vertex( int idx ) const @@ -47,9 +51,9 @@ const QgsGraphVertex& QgsGraph::vertex( int idx ) const return mGraphVertexes[ idx ]; } -const QgsGraphArc& QgsGraph::arc( int idx ) const +const QgsGraphEdge& QgsGraph::edge( int idx ) const { - return mGraphArc[ idx ]; + return mGraphEdges[ idx ]; } int QgsGraph::vertexCount() const @@ -57,9 +61,9 @@ int QgsGraph::vertexCount() const return mGraphVertexes.size(); } -int QgsGraph::arcCount() const +int QgsGraph::edgeCount() const { - return mGraphArc.size(); + return mGraphEdges.size(); } int QgsGraph::findVertex( const QgsPoint& pt ) const @@ -75,29 +79,29 @@ int QgsGraph::findVertex( const QgsPoint& pt ) const return -1; } -QgsGraphArc::QgsGraphArc() +QgsGraphEdge::QgsGraphEdge() : mOut( 0 ) , mIn( 0 ) { } -QVariant QgsGraphArc::property( int i ) const +QVariant QgsGraphEdge::cost( int i ) const { - return mProperties[ i ]; + return mStrategies[ i ]; } -QVector< QVariant > QgsGraphArc::properties() const +QVector< QVariant > QgsGraphEdge::strategies() const { - return mProperties; + return mStrategies; } -int QgsGraphArc::inVertex() const +int QgsGraphEdge::inVertex() const { return mIn; } -int QgsGraphArc::outVertex() const +int QgsGraphEdge::outVertex() const { return mOut; } @@ -108,14 +112,14 @@ QgsGraphVertex::QgsGraphVertex( const QgsPoint& point ) } -QgsGraphArcIdList QgsGraphVertex::outArc() const +QgsGraphEdgeIds QgsGraphVertex::outEdges() const { - return mOutArc; + return mOutEdges; } -QgsGraphArcIdList QgsGraphVertex::inArc() const +QgsGraphEdgeIds QgsGraphVertex::inEdges() const { - return mInArc; + return mInEdges; } QgsPoint QgsGraphVertex::point() const diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index 0f4cf909b203..31ff6f10bea2 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -1,5 +1,5 @@ /*************************************************************************** - graph.h + qgsgraph.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -14,11 +14,10 @@ ***************************************************************************/ /* - * This file describes the built-in QGIS classes modeling a mathematical graph. - * Vertex is identified by its geographic coordinates (but you can add two vertex - * with unique coordinate), no additional properties it can not be assigned. - * Count the number of properties not limited along the arc. Graph may - * be have incidence arcs. + * This file describes the built-in QGIS classes for modeling a mathematical graph. + * Vertices are identified by their geographic coordinates and have no additional + * properties. Number of strategies for calculating edge cost is not limited. + * Graph may have incidence edges. * * \file qgsgraph.h */ @@ -36,38 +35,38 @@ class QgsGraphVertex; /** * \ingroup analysis - * \class QgsGraphArc + * \class QgsGraphEdge * \brief This class implements a graph edge */ -class ANALYSIS_EXPORT QgsGraphArc +class ANALYSIS_EXPORT QgsGraphEdge { public: - QgsGraphArc(); + QgsGraphEdge(); /** - * return property value - * @param propertyIndex property index + * Returns edge cost calculated using specified strategy + * @param strategyIndex strategy index */ - QVariant property( int propertyIndex ) const; + QVariant cost( int strategyIndex ) const; /** - * get array of properties + * Returns array of available strategies */ - QVector< QVariant > properties() const; + QVector< QVariant > strategies() const; /** - * return index of outgoing vertex + * Returns index of the outgoing vertex */ int outVertex() const; /** - * return index of incoming vertex + * Returns index of the incoming vertex */ int inVertex() const; private: - QVector< QVariant > mProperties; + QVector< QVariant > mStrategies; int mOut; int mIn; @@ -76,7 +75,7 @@ class ANALYSIS_EXPORT QgsGraphArc }; -typedef QList< int > QgsGraphArcIdList; +typedef QList< int > QgsGraphEdgeIds; /** * \ingroup analysis @@ -88,7 +87,7 @@ class ANALYSIS_EXPORT QgsGraphVertex public: /** - * default constructor. It needed for Qt's container, e.g. QVector + * Default constructor. It is needed for Qt's container, e.g. QVector */ QgsGraphVertex() {} @@ -99,24 +98,24 @@ class ANALYSIS_EXPORT QgsGraphVertex QgsGraphVertex( const QgsPoint& point ); /** - * return outgoing edges + * Returns outgoing edges ids */ - QgsGraphArcIdList outArc() const; + QgsGraphEdgeIds outEdges() const; /** - * return incoming edges + * Return incoming edges ids */ - QgsGraphArcIdList inArc() const; + QgsGraphEdgeIds inEdges() const; /** - * return vertex point + * Returns point associated with graph vertex */ QgsPoint point() const; private: QgsPoint mCoordinate; - QgsGraphArcIdList mOutArc; - QgsGraphArcIdList mInArc; + QgsGraphEdgeIds mOutEdges; + QgsGraphEdgeIds mInEdges; friend class QgsGraph; }; @@ -132,40 +131,40 @@ class ANALYSIS_EXPORT QgsGraph public: QgsGraph(); - // begin graph constructing methods + // Graph constructing methods /** - * add vertex to a graph + * Add a vertex to the graph */ int addVertex( const QgsPoint& pt ); /** - * add edge to a graph + * Add an edge to the graph */ - int addArc( int outVertexIdx, int inVertexIdx, const QVector< QVariant >& properties ); + int addEdge( int outVertexIdx, int inVertexIdx, const QVector< QVariant >& strategies ); /** - * return vertex count + * Returns number of graph vertices */ int vertexCount() const; /** - * return vertex at index + * Returns vertex at given index */ const QgsGraphVertex& vertex( int idx ) const; /** - * return edge count + * Returns number of graph edges */ - int arcCount() const; + int edgeCount() const; /** - * return edge at index + * Returns edge at given index */ - const QgsGraphArc& arc( int idx ) const; + const QgsGraphEdge& edge( int idx ) const; /** - * find vertex by point + * Find vertex by associated point * \return vertex index */ int findVertex( const QgsPoint& pt ) const; @@ -173,7 +172,7 @@ class ANALYSIS_EXPORT QgsGraph private: QVector mGraphVertexes; - QVector mGraphArc; + QVector mGraphEdges; }; #endif // QGSGRAPH_H diff --git a/src/analysis/network/qgsgraphanalyzer.cpp b/src/analysis/network/qgsgraphanalyzer.cpp index c93bd68fc44a..18f075688d8b 100644 --- a/src/analysis/network/qgsgraphanalyzer.cpp +++ b/src/analysis/network/qgsgraphanalyzer.cpp @@ -1,19 +1,17 @@ /*************************************************************************** - qgsgraphanlyzer.cpp - QGIS Tools for graph analysis - ------------------- - begin : 14 april 2011 - copyright : (C) Sergey Yakushev - email : Yakushevs@list.ru - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ + qgsgraphanalyzer.cpp + -------------------------------------- + Date : 2011-04-14 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ #include @@ -61,12 +59,12 @@ void QgsGraphAnalyzer::dijkstra( const QgsGraph* source, int startPointIdx, int not_begin.erase( it ); // edge index list - QgsGraphArcIdList l = source->vertex( curVertex ).outArc(); - QgsGraphArcIdList::iterator arcIt; + QgsGraphEdgeIds l = source->vertex( curVertex ).outEdges(); + QgsGraphEdgeIds::iterator arcIt; for ( arcIt = l.begin(); arcIt != l.end(); ++arcIt ) { - const QgsGraphArc arc = source->arc( *arcIt ); - double cost = arc.property( criterionNum ).toDouble() + curCost; + const QgsGraphEdge arc = source->edge( *arcIt ); + double cost = arc.cost( criterionNum ).toDouble() + curCost; if ( cost < ( *result )[ arc.inVertex()] ) { @@ -111,10 +109,10 @@ QgsGraph* QgsGraphAnalyzer::shortestTree( const QgsGraph* source, int startVerte { if ( tree[ i ] != -1 ) { - const QgsGraphArc& arc = source->arc( tree[i] ); + const QgsGraphEdge& arc = source->edge( tree[i] ); - treeResult->addArc( source2result[ arc.outVertex()], source2result[ arc.inVertex()], - arc.properties() ); + treeResult->addEdge( source2result[ arc.outVertex()], source2result[ arc.inVertex()], + arc.strategies() ); } } diff --git a/src/analysis/network/qgsgraphanalyzer.h b/src/analysis/network/qgsgraphanalyzer.h index 4dcf63ddaaf1..16ce64777892 100644 --- a/src/analysis/network/qgsgraphanalyzer.h +++ b/src/analysis/network/qgsgraphanalyzer.h @@ -1,19 +1,17 @@ /*************************************************************************** - qgsgraphalyzer.h - QGIS Tools for graph analysis - ------------------- - begin : 14 april 2010 - copyright : (C) Sergey Yakushev - email : yakushevs@list.ru - ***************************************************************************/ - -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ + qgsgraphanalyzer.h + -------------------------------------- + Date : 2011-04-14 + Copyright : (C) 2010 by Yakushev Sergey + Email : YakushevS list.ru +**************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +***************************************************************************/ #ifndef QGSGRAPHANALYZER_H #define QGSGRAPHANALYZER_H @@ -23,7 +21,8 @@ class QgsGraph; /** \ingroup analysis - * QGIS class with graph analysis functions + * This class performs graph analysis, e.g. calculates shortest path between two + * points using different strategies with Dijkstra algorithm */ class ANALYSIS_EXPORT QgsGraphAnalyzer @@ -31,20 +30,20 @@ class ANALYSIS_EXPORT QgsGraphAnalyzer public: /** - * solve shortest path problem using dijkstra algorithm + * Solve shortest path problem using Dijkstra algorithm * @param source source graph * @param startVertexIdx index of the start vertex - * @param criterionNum index of the arc property as optimization criterion - * @param resultTree array represents the shortest path tree. resultTree[ vertexIndex ] == inboundingArcIndex if vertex reachable, otherwise resultTree[ vertexIndex ] == -1 - * @param resultCost array of cost paths + * @param criterionNum index of the optimization strategy + * @param resultTree array that represents shortest path tree. resultTree[ vertexIndex ] == inboundingArcIndex if vertex reachable, otherwise resultTree[ vertexIndex ] == -1 + * @param resultCost array of the paths costs */ static void dijkstra( const QgsGraph* source, int startVertexIdx, int criterionNum, QVector* resultTree = nullptr, QVector* resultCost = nullptr ); /** - * return shortest path tree with root-node in startVertexIdx + * Returns shortest path tree with root-node in startVertexIdx * @param source source graph * @param startVertexIdx index of the start vertex - * @param criterionNum index of the edge property as optimization criterion + * @param criterionNum index of the optimization strategy */ static QgsGraph* shortestTree( const QgsGraph* source, int startVertexIdx, int criterionNum ); }; diff --git a/src/analysis/network/qgsgraphbuilder.cpp b/src/analysis/network/qgsgraphbuilder.cpp index e80914f42804..54444bd7b2ec 100644 --- a/src/analysis/network/qgsgraphbuilder.cpp +++ b/src/analysis/network/qgsgraphbuilder.cpp @@ -15,7 +15,7 @@ /** * \file qgsgraphbuilder.cpp - * \brief implementation of QgsGraphBuilder + * \brief implementation of the QgsGraphBuilder */ #include "qgsgraphbuilder.h" @@ -40,9 +40,9 @@ void QgsGraphBuilder::addVertex( int, const QgsPoint& pt ) mGraph->addVertex( pt ); } -void QgsGraphBuilder::addArc( int pt1id, const QgsPoint&, int pt2id, const QgsPoint&, const QVector< QVariant >& prop ) +void QgsGraphBuilder::addEdge( int pt1id, const QgsPoint&, int pt2id, const QgsPoint&, const QVector< QVariant >& prop ) { - mGraph->addArc( pt1id, pt2id, prop ); + mGraph->addEdge( pt1id, pt2id, prop ); } QgsGraph* QgsGraphBuilder::graph() diff --git a/src/analysis/network/qgsgraphbuilder.h b/src/analysis/network/qgsgraphbuilder.h index 8cbe1d09e1e4..a3d8434cca61 100644 --- a/src/analysis/network/qgsgraphbuilder.h +++ b/src/analysis/network/qgsgraphbuilder.h @@ -16,7 +16,7 @@ #ifndef QGSGRAPHBUILDER_H #define QGSGRAPHBUILDER_H -#include "qgsgraphbuilderintr.h" +#include "qgsgraphbuilderinterface.h" #include @@ -27,7 +27,7 @@ class QgsGraph; /** * \ingroup analysis * \class QgsGraphBuilder -* \brief This class is used for making the QgsGraph object +* \brief This class used for making the QgsGraph object */ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface @@ -35,7 +35,7 @@ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface public: /** - * default constructor + * Default constructor */ QgsGraphBuilder( const QgsCoordinateReferenceSystem& crs, bool otfEnabled = true, double topologyTolerance = 0.0, const QString& ellipsoidID = "WGS84" ); @@ -46,10 +46,10 @@ class ANALYSIS_EXPORT QgsGraphBuilder : public QgsGraphBuilderInterface */ virtual void addVertex( int id, const QgsPoint& pt ) override; - virtual void addArc( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& prop ) override; + virtual void addEdge( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& prop ) override; /** - * return QgsGraph result; + * Returns generated QgsGraph */ QgsGraph* graph(); diff --git a/src/analysis/network/qgsgraphbuilderintr.h b/src/analysis/network/qgsgraphbuilderinterface.h similarity index 81% rename from src/analysis/network/qgsgraphbuilderintr.h rename to src/analysis/network/qgsgraphbuilderinterface.h index ca98e034a07d..92de360cae8c 100644 --- a/src/analysis/network/qgsgraphbuilderintr.h +++ b/src/analysis/network/qgsgraphbuilderinterface.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsgraphbuilderintr.h + qgsgraphbuilderinterface.h -------------------------------------- Date : 2010-10-22 Copyright : (C) 2010 by Yakushev Sergey @@ -26,14 +26,15 @@ /** * \ingroup analysis * \class QgsGraphBuilderInterface -* \brief Determine interface for creating a graph. Contains the settings of the graph. QgsGraphBuilder and QgsGraphDirector both use a Builder pattern +* \brief Determine interface for creating a graph. Contains the settings of the graph. +* QgsGraphBuilder and QgsGraphDirector both use a Builder pattern */ class ANALYSIS_EXPORT QgsGraphBuilderInterface { public: /** - * QgsGraphBuilderInterface constructor + * Default constructor * @param crs Coordinate reference system for new graph vertex * @param ctfEnabled enable coordinate transform from source graph CRS to CRS graph * @param topologyTolerance sqrt distance between source point as one graph vertex @@ -53,34 +54,34 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface virtual ~QgsGraphBuilderInterface() { } - //! get destinaltion CRS + //! Returns destinaltion CRS QgsCoordinateReferenceSystem destinationCrs() const { return mCrs; } - //! get coordinate transformation enabled + //! Returns coordinate transformation enabled bool coordinateTransformationEnabled() { return mCtfEnabled; } - //! get topology tolerance + //! Returns topology tolerance double topologyTolerance() { return mTopologyTolerance; } - //! get measurement tool + //! Returns measurement tool QgsDistanceArea* distanceArea() { return &mDa; } /** - * add vertex + * Add vertex to the graph * @param id vertex identifier - * @param pt vertex coordinate + * @param pt vertex coordinates * @note id and pt are redundant. You can use pt or id to identify the vertex */ virtual void addVertex( int id, const QgsPoint &pt ) @@ -90,21 +91,21 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface } /** - * add arc + * Add edge to the graph * @param pt1id first vertex identificator - * @param pt1 first vertex coordinate + * @param pt1 first vertex coordinates * @param pt2id second vertex identificator - * @param pt2 second vertex coordinate - * @param properties arc properties + * @param pt2 second vertex coordinates + * @param strategies optimization strategies * @note pt1id, pt1 and pt2id, pt2 is a redundant interface. You can use vertex coordinates or their identificators. */ - virtual void addArc( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& properties ) + virtual void addEdge( int pt1id, const QgsPoint& pt1, int pt2id, const QgsPoint& pt2, const QVector< QVariant >& strategies ) { Q_UNUSED( pt1id ); Q_UNUSED( pt1 ); Q_UNUSED( pt2id ); Q_UNUSED( pt2 ); - Q_UNUSED( properties ); + Q_UNUSED( strategies ); } private: @@ -117,4 +118,5 @@ class ANALYSIS_EXPORT QgsGraphBuilderInterface double mTopologyTolerance; }; + #endif // QGSGRAPHBUILDERINTERFACE_H diff --git a/src/analysis/network/qgsgraphdirector.h b/src/analysis/network/qgsgraphdirector.h index d6d78f671d1a..35edc4742cd7 100644 --- a/src/analysis/network/qgsgraphdirector.h +++ b/src/analysis/network/qgsgraphdirector.h @@ -21,7 +21,7 @@ #include #include -#include "qgsarcproperter.h" +#include "qgsstrategy.h" class QgsGraphBuilderInterface; @@ -43,34 +43,33 @@ class ANALYSIS_EXPORT QgsGraphDirector : public QObject virtual ~QgsGraphDirector() { } /** - * Make a graph using RgGraphBuilder + * Make a graph using QgsGraphBuilder * - * @param builder The graph builder - * @param additionalPoints Vector of points that must be tied to the graph - * @param tiedPoints Vector of tied points - * @note if tiedPoints[i]==QgsPoint(0.0,0.0) then tied failed. + * @param builder the graph builder + * @param additionalPoints list of points that should be snapped to the graph + * @param tiedPoints list of snapped points + * @note if tiedPoints[i] == QgsPoint(0.0,0.0) then snapping failed. */ virtual void makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint > &additionalPoints, - QVector< QgsPoint > &tiedPoints ) const + QVector< QgsPoint > &snappedPoints ) const { Q_UNUSED( builder ); Q_UNUSED( additionalPoints ); - Q_UNUSED( tiedPoints ); + Q_UNUSED( snappedPoints ); } - void addProperter( QgsArcProperter* prop ) + //! Add optimization strategy + void addStrategy( QgsStrategy* prop ) { - mProperterList.push_back( prop ); + mStrategies.push_back( prop ); } - /** - * return Director name - */ + //! Returns director name virtual QString name() const = 0; protected: - QList mProperterList; + QList mStrategies; }; #endif // QGSGRAPHDIRECTOR_H diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgslinevectorlayerdirector.cpp index f113b26de209..ce0a57a449c1 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgslinevectorlayerdirector.cpp @@ -19,7 +19,7 @@ */ #include "qgslinevectorlayerdirector.h" -#include "qgsgraphbuilderintr.h" +#include "qgsgraphbuilderinterface.h" #include "qgsfeatureiterator.h" #include @@ -129,7 +129,7 @@ QString QgsLineVectorLayerDirector::name() const } void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, - QVector< QgsPoint >& tiedPoint ) const + QVector< QgsPoint >& snappedPoints ) const { QgsVectorLayer *vl = mVectorLayer; @@ -150,7 +150,7 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c ct.setDestinationCrs( vl->crs() ); } - tiedPoint = QVector< QgsPoint >( additionalPoints.size(), QgsPoint( 0.0, 0.0 ) ); + snappedPoints = QVector< QgsPoint >( additionalPoints.size(), QgsPoint( 0.0, 0.0 ) ); TiePointInfo tmpInfo; tmpInfo.mLength = std::numeric_limits::infinity(); @@ -209,7 +209,7 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c info.mLastPoint = pt2; pointLengthMap[ i ] = info; - tiedPoint[ i ] = info.mTiedPoint; + snappedPoints[ i ] = info.mTiedPoint; } } } @@ -223,11 +223,11 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c // add tied point to graph int i = 0; - for ( i = 0; i < tiedPoint.size(); ++i ) + for ( i = 0; i < snappedPoints.size(); ++i ) { - if ( tiedPoint[ i ] != QgsPoint( 0.0, 0.0 ) ) + if ( snappedPoints[ i ] != QgsPoint( 0.0, 0.0 ) ) { - points.push_back( tiedPoint [ i ] ); + points.push_back( snappedPoints [ i ] ); } } @@ -240,8 +240,8 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c for ( i = 0;i < points.size();++i ) builder->addVertex( i, points[ i ] ); - for ( i = 0; i < tiedPoint.size() ; ++i ) - tiedPoint[ i ] = *( my_binary_search( points.begin(), points.end(), tiedPoint[ i ], pointCompare ) ); + for ( i = 0; i < snappedPoints.size() ; ++i ) + snappedPoints[ i ] = *( my_binary_search( points.begin(), points.end(), snappedPoints[ i ], pointCompare ) ); qSort( pointLengthMap.begin(), pointLengthMap.end(), TiePointInfoCompare ); @@ -253,10 +253,10 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c tmpAttr.push_back( mDirectionFieldId ); } - QList< QgsArcProperter* >::const_iterator it; + QList< QgsStrategy* >::const_iterator it; QgsAttributeList::const_iterator it2; - for ( it = mProperterList.begin(); it != mProperterList.end(); ++it ) + for ( it = mStrategies.begin(); it != mStrategies.end(); ++it ) { QgsAttributeList tmp = ( *it )->requiredAttributes(); for ( it2 = tmp.begin(); it2 != tmp.end(); ++it2 ) @@ -366,21 +366,21 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c { double distance = builder->distanceArea()->measureLine( pt1, pt2 ); QVector< QVariant > prop; - QList< QgsArcProperter* >::const_iterator it; - for ( it = mProperterList.begin(); it != mProperterList.end(); ++it ) + QList< QgsStrategy* >::const_iterator it; + for ( it = mStrategies.begin(); it != mStrategies.end(); ++it ) { - prop.push_back(( *it )->property( distance, feature ) ); + prop.push_back(( *it )->cost( distance, feature ) ); } if ( directionType == 1 || directionType == 3 ) { - builder->addArc( pt1idx, pt1, pt2idx, pt2, prop ); + builder->addEdge( pt1idx, pt1, pt2idx, pt2, prop ); } if ( directionType == 2 || directionType == 3 ) { - builder->addArc( pt2idx, pt2, pt1idx, pt1, prop ); + builder->addEdge( pt2idx, pt2, pt1idx, pt1, prop ); } } pt1idx = pt2idx; diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgslinevectorlayerdirector.h index 5bb34b5d5162..a6d148c0d86c 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgslinevectorlayerdirector.h @@ -33,12 +33,13 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector public: /** + * Default constructor * @param myLayer source vector layer - * @param directionFieldId feield contain road direction value + * @param directionFieldId field contain road direction value * @param directDirectionValue value for one-way road - * @param reverseDirectionValue value for reverse one-way road - * @param bothDirectionValue value for road - * @param defaultDirection 1 - direct direction, 2 - reverse direction, 3 - both direction + * @param reverseDirectionValue value for reversed one-way road + * @param bothDirectionValue value for bidirectional road + * @param defaultDirection 1 - direct direction, 2 - reverse direction, 3 - both directions */ QgsLineVectorLayerDirector( QgsVectorLayer* myLayer, int directionFieldId, @@ -56,7 +57,7 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector */ void makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, - QVector< QgsPoint>& tiedPoints ) const override; + QVector< QgsPoint>& snappedPoints ) const override; QString name() const override; diff --git a/src/analysis/network/qgsspeedarcproperter.cpp b/src/analysis/network/qgsspeedstrategy.cpp similarity index 77% rename from src/analysis/network/qgsspeedarcproperter.cpp rename to src/analysis/network/qgsspeedstrategy.cpp index fa137fd3de39..2d0eaec59fef 100644 --- a/src/analysis/network/qgsspeedarcproperter.cpp +++ b/src/analysis/network/qgsspeedstrategy.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - qgsspeedarcproperter.h + qgsspeedstrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,21 +13,21 @@ * * ***************************************************************************/ -#include "qgsspeedarcproperter.h" +#include "qgsspeedstrategy.h" -QgsSpeedArcProperter::QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ) +QgsSpeedStrategy::QgsSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ) { mAttributeId = attributeId; mDefaultValue = defaultValue; mToMetricFactor = toMetricFactor; } -QVariant QgsSpeedArcProperter::property( double distance, const QgsFeature& f ) const +QVariant QgsSpeedStrategy::cost( double distance, const QgsFeature& f ) const { QgsAttributes attrs = f.attributes(); if ( mAttributeId < 0 || mAttributeId >= attrs.count() ) - return QVariant( distance / ( mDefaultValue*mToMetricFactor ) ); + return QVariant( distance / ( mDefaultValue * mToMetricFactor ) ); double val = distance / ( attrs.at( mAttributeId ).toDouble() * mToMetricFactor ); if ( val <= 0.0 ) @@ -36,7 +36,7 @@ QVariant QgsSpeedArcProperter::property( double distance, const QgsFeature& f ) return QVariant( val ); } -QgsAttributeList QgsSpeedArcProperter::requiredAttributes() const +QgsAttributeList QgsSpeedStrategy::requiredAttributes() const { QgsAttributeList l; l.push_back( mAttributeId ); diff --git a/src/analysis/network/qgsspeedarcproperter.h b/src/analysis/network/qgsspeedstrategy.h similarity index 60% rename from src/analysis/network/qgsspeedarcproperter.h rename to src/analysis/network/qgsspeedstrategy.h index 87f896e55493..5608873c5fea 100644 --- a/src/analysis/network/qgsspeedarcproperter.h +++ b/src/analysis/network/qgsspeedstrategy.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsspeedarcproperter.h + qgsspeedstrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,31 +13,32 @@ * * ***************************************************************************/ -#ifndef QGSSPEEDARCPROPERTER_H -#define QGSSPEEDARCPROPERTER_H +#ifndef QGSSPEEDSTRATEGY_H +#define QGSSPEEDSTRATEGY_H -#include +#include /** \ingroup analysis - * \class QgsSpeedArcProperter + * \class QgsSpeedStrategy * \note added in QGIS 3.0 - * - * \brief Used for calculating arc property taking into account travel time. + * \brief Strategy for caclucating edge cost based on travel time. Should be + * used for finding fastest path between two points. */ -class ANALYSIS_EXPORT QgsSpeedArcProperter : public QgsArcProperter +class ANALYSIS_EXPORT QgsSpeedStrategy : public QgsStrategy { public: /** - * Constructor for QgsSpeedArcProperter. + * Default constructor */ - QgsSpeedArcProperter( int attributeId, double defaultValue, double toMetricFactor ); + QgsSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ); - //! Returns caluclated edge property - QVariant property( double distance, const QgsFeature& f ) const override; + //! Returns edge cost + QVariant cost( double distance, const QgsFeature& f ) const override; - /** QgsGraphDirector will call this method for fetching attributes - * needed to calculate arc properties from the source layer + /** + * Returns list of the source layer attributes needed for cost calculation. + * This method called by QgsGraphDirector. */ QgsAttributeList requiredAttributes() const override; @@ -48,4 +49,4 @@ class ANALYSIS_EXPORT QgsSpeedArcProperter : public QgsArcProperter }; -#endif // QGSSPEEDARCPROPERTER_H +#endif // QGSSPEEDSTRATEGY_H diff --git a/src/analysis/network/qgsarcproperter.h b/src/analysis/network/qgsstrategy.h similarity index 59% rename from src/analysis/network/qgsarcproperter.h rename to src/analysis/network/qgsstrategy.h index f082583ed6a7..d789a43918dc 100644 --- a/src/analysis/network/qgsarcproperter.h +++ b/src/analysis/network/qgsstrategy.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsarcproperter.h + qgsstrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,8 +13,8 @@ * * ***************************************************************************/ -#ifndef QGSARCROPERTER_H -#define QGSARCROPERTER_H +#ifndef QGSSTRATERGY_H +#define QGSSTRATERGY_H #include @@ -23,35 +23,39 @@ /** * \ingroup analysis - * \class QgsArcProperter - * \brief QgsArcProperter is a strategy pattern. - * You can use it for customize arc property. For example look at QgsDistanceArcProperter and QgsSpeedArcProperter + * \class QgsStrategy + * \brief QgsStrategy defines strategy used for calculation of the edge cost. For example it can + * take into account travel distance, amount of time or money. Currently there are two strategies + * implemented in the analysis library: QgsDistanceStrategy and QgsSpeedStrategy. + * QgsStrategy implemented with strategy design pattern. */ -class ANALYSIS_EXPORT QgsArcProperter +class ANALYSIS_EXPORT QgsStrategy { public: /** - * default constructor + * Default constructor */ - QgsArcProperter() {} + QgsStrategy() {} - virtual ~QgsArcProperter() {} + virtual ~QgsStrategy() {} /** - * QgsGraphDirector call this method for fetching attribute from source layer - * \return required attributes list + * Returns list of the source layer attributes needed for cost calculation. + * This method called by QgsGraphDirector. + * \return list of required attributes */ virtual QgsAttributeList requiredAttributes() const { return QgsAttributeList(); } /** - * calculate and return adge property + * Return edge cost */ - virtual QVariant property( double distance, const QgsFeature &f ) const + virtual QVariant cost( double distance, const QgsFeature &f ) const { Q_UNUSED( distance ); Q_UNUSED( f ); return QVariant(); } }; -#endif // QGSARCROPERTER_H + +#endif // QGSSTRATERGY_H diff --git a/src/plugins/roadgraph/CMakeLists.txt b/src/plugins/roadgraph/CMakeLists.txt index 8743df9c0064..097fc51ed75a 100644 --- a/src/plugins/roadgraph/CMakeLists.txt +++ b/src/plugins/roadgraph/CMakeLists.txt @@ -10,7 +10,6 @@ SET (VRP_SRCS linevectorlayersettings.cpp linevectorlayerwidget.cpp exportdlg.cpp - speedproperter.cpp ) #SET ([pluginlcasename]_UIS [pluginlcasename]guibase.ui) diff --git a/src/plugins/roadgraph/roadgraphplugin.cpp b/src/plugins/roadgraph/roadgraphplugin.cpp index 6183eb536aab..e9254614667f 100644 --- a/src/plugins/roadgraph/roadgraphplugin.cpp +++ b/src/plugins/roadgraph/roadgraphplugin.cpp @@ -29,14 +29,14 @@ #include #include #include -#include +#include +#include #include "qgsdockwidget.h" // Road grap plugin includes #include "roadgraphplugin.h" #include "shortestpathwidget.h" #include "settingsdlg.h" -#include "speedproperter.h" #include "units.h" #include "linevectorlayersettings.h" @@ -218,9 +218,9 @@ const QgsGraphDirector* RoadGraphPlugin::director() const mSettings->mBothDirectionVal, mSettings->mDefaultDirection ); - director->addProperter( new QgsDistanceArcProperter() ); - director->addProperter( new RgSpeedProperter( layer->fields().lookupField( mSettings->mSpeed ), - mSettings->mDefaultSpeed, speedUnit.multipler() ) ); + director->addStrategy( new QgsDistanceStrategy() ); + director->addStrategy( new QgsSpeedStrategy( layer->fields().lookupField( mSettings->mSpeed ), + mSettings->mDefaultSpeed, speedUnit.multipler() ) ); return director; } return nullptr; diff --git a/src/plugins/roadgraph/shortestpathwidget.cpp b/src/plugins/roadgraph/shortestpathwidget.cpp index 1ab7529860fb..96a80060c62c 100644 --- a/src/plugins/roadgraph/shortestpathwidget.cpp +++ b/src/plugins/roadgraph/shortestpathwidget.cpp @@ -340,13 +340,13 @@ void RgShortestPathWidget::findingPath() if ( stopVertexIdx < 0 ) break; - QgsGraphArcIdList l = path->vertex( stopVertexIdx ).inArc(); + QgsGraphEdgeIds l = path->vertex( stopVertexIdx ).inEdges(); if ( l.empty() ) break; - const QgsGraphArc& e = path->arc( l.front() ); + const QgsGraphEdge& e = path->edge( l.front() ); - cost += e.property( 0 ).toDouble(); - time += e.property( 1 ).toDouble(); + cost += e.cost( 0 ).toDouble(); + time += e.cost( 1 ).toDouble(); p.push_front( path->vertex( e.inVertex() ).point() ); @@ -414,13 +414,13 @@ void RgShortestPathWidget::exportPath() if ( stopVertexIdx < 0 ) break; - QgsGraphArcIdList l = path->vertex( stopVertexIdx ).inArc(); + QgsGraphEdgeIds l = path->vertex( stopVertexIdx ).inEdges(); if ( l.empty() ) break; - const QgsGraphArc& e = path->arc( l.front() ); + const QgsGraphEdge& e = path->edge( l.front() ); - cost += e.property( 0 ).toDouble(); - time += e.property( 1 ).toDouble(); + cost += e.cost( 0 ).toDouble(); + time += e.cost( 1 ).toDouble(); p.push_front( ct.transform( path->vertex( e.inVertex() ).point() ) ); stopVertexIdx = e.outVertex(); diff --git a/src/plugins/roadgraph/speedproperter.cpp b/src/plugins/roadgraph/speedproperter.cpp deleted file mode 100644 index eafe02558ece..000000000000 --- a/src/plugins/roadgraph/speedproperter.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2009 by Sergey Yakushev * - * yakushevs@list.ru * - * * - * This is file implements Units classes * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ - -#include "speedproperter.h" - -RgSpeedProperter::RgSpeedProperter( int attributeId, double defaultValue, double toMetricFactor ) -{ - mAttributeId = attributeId; - mDefaultValue = defaultValue; - mToMetricFactor = toMetricFactor; -} - -QVariant RgSpeedProperter::property( double distance, const QgsFeature& f ) const -{ - QgsAttributes attrs = f.attributes(); - - if ( mAttributeId < 0 || mAttributeId >= attrs.count() ) - return QVariant( distance / ( mDefaultValue*mToMetricFactor ) ); - - double val = distance / ( attrs.at( mAttributeId ).toDouble() * mToMetricFactor ); - if ( val <= 0.0 ) - return QVariant( distance / ( mDefaultValue / mToMetricFactor ) ); - - return QVariant( val ); -} - -QgsAttributeList RgSpeedProperter::requiredAttributes() const -{ - QgsAttributeList l; - l.push_back( mAttributeId ); - return l; -} diff --git a/src/plugins/roadgraph/speedproperter.h b/src/plugins/roadgraph/speedproperter.h deleted file mode 100644 index 7f0a81a0a0df..000000000000 --- a/src/plugins/roadgraph/speedproperter.h +++ /dev/null @@ -1,34 +0,0 @@ -/*************************************************************************** - * Copyright (C) 2011 by Sergey Yakushev * - * yakushevs@list.ru * - * * - * This is file define vrp plugins time, distance and speed units * - * classes * - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - ***************************************************************************/ - -#ifndef ROADGRAPH_SPEEDPROPERTER_H -#define ROADGRAPH_SPEEDPROPERTER_H - -#include - -class RgSpeedProperter : public QgsArcProperter -{ - public: - RgSpeedProperter( int attributeId, double defaultValue, double toMetricFactor ); - - QVariant property( double distance, const QgsFeature& f ) const override; - - QgsAttributeList requiredAttributes() const override; - private: - int mAttributeId; - double mDefaultValue; - double mToMetricFactor; - -}; - -#endif From c1b6edc4faa4f9fcc609d45dcc3da9605c05b459 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 17 Nov 2016 17:45:11 +0200 Subject: [PATCH 849/897] update API breaks document --- doc/api_break.dox | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/doc/api_break.dox b/doc/api_break.dox index 4b9c40ff4f6c..bb06930fcdf1 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -180,6 +180,9 @@ Renamed Classes {#qgis_api_break_3_0_renamed_classes} QgsVectorRandomColorRampV2DialogQgsLimitedRandomColorRampDialog QgsVectorRandomColorRampV2DialogBaseQgsLimitedRandomColorRampDialogBase QgsSymbolV2QgsSymbol +QgsArcProperterQgsStrategy +QgsDistanceArcProperterQgsDistanceStrategy +QgsGraphArcQgsGraphEdge @@ -205,6 +208,17 @@ Renamed Classes {#qgis_api_break_3_0_renamed_classes}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsVectorLayerEditUtilsdeleteVertexV2deleteVertex
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsComposerSymbolItemsymbolV2symbol
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsServerInterfacecapabiblitiesCachecapabilitiesCache +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphEdgepropertycost +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphEdgepropertiesstrategies +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphVertexoutArcoutEdges +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphVertexinArcinEdges +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphaddArcaddEdges +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGrapharcCountedgeCount +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGrapharcedge +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphBuilderaddArcaddEdge +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphBuilderInterfaceaddArcaddEdge +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsGraphDirectoryaddProperteraddStrategy +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  QgsStrategyaddProperteraddStrategy
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  From f77ab4d52b10d64336cdf151443b4e85fa1285df Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 17 Nov 2016 18:41:01 +0200 Subject: [PATCH 850/897] add note to doxygen comments --- src/analysis/network/qgsdistancestrategy.h | 1 + src/analysis/network/qgsgraph.h | 1 + src/analysis/network/qgsstrategy.h | 1 + 3 files changed, 3 insertions(+) diff --git a/src/analysis/network/qgsdistancestrategy.h b/src/analysis/network/qgsdistancestrategy.h index 0d648714bd4b..fe6882aa879f 100644 --- a/src/analysis/network/qgsdistancestrategy.h +++ b/src/analysis/network/qgsdistancestrategy.h @@ -20,6 +20,7 @@ /** \ingroup analysis * \class QgsDistanceStrategy + * \note added in QGIS 3.0 * \brief Strategy for caclucating edge cost based on its length. Should be * used for finding shortest path between two points. */ diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index 31ff6f10bea2..07f5c2bfa304 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -36,6 +36,7 @@ class QgsGraphVertex; /** * \ingroup analysis * \class QgsGraphEdge + * \note added in QGIS 3.0 * \brief This class implements a graph edge */ class ANALYSIS_EXPORT QgsGraphEdge diff --git a/src/analysis/network/qgsstrategy.h b/src/analysis/network/qgsstrategy.h index d789a43918dc..685e63f162ff 100644 --- a/src/analysis/network/qgsstrategy.h +++ b/src/analysis/network/qgsstrategy.h @@ -24,6 +24,7 @@ /** * \ingroup analysis * \class QgsStrategy + * \note added in QGIS 3.0 * \brief QgsStrategy defines strategy used for calculation of the edge cost. For example it can * take into account travel distance, amount of time or money. Currently there are two strategies * implemented in the analysis library: QgsDistanceStrategy and QgsSpeedStrategy. From 00eb2619c690fd99b58ddc59e34c6f6030de8c02 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Thu, 17 Nov 2016 20:37:48 +0200 Subject: [PATCH 851/897] fix warnings --- python/analysis/network/qgsgraphdirector.sip | 4 ++-- src/analysis/network/qgsgraphdirector.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/analysis/network/qgsgraphdirector.sip b/python/analysis/network/qgsgraphdirector.sip index b30641ce6c83..b9c6ae728cd2 100644 --- a/python/analysis/network/qgsgraphdirector.sip +++ b/python/analysis/network/qgsgraphdirector.sip @@ -34,8 +34,8 @@ class QgsGraphDirector : QObject * * @param builder the graph builder * @param additionalPoints list of points that should be snapped to the graph - * @param tiedPoints list of snapped points - * @note if tiedPoints[i] == QgsPoint(0.0,0.0) then snapping failed. + * @param snappedPoints list of snapped points + * @note if snappedPoints[i] == QgsPoint(0.0,0.0) then snapping failed. */ virtual void makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint > &additionalPoints, diff --git a/src/analysis/network/qgsgraphdirector.h b/src/analysis/network/qgsgraphdirector.h index 35edc4742cd7..6f5361f98d1c 100644 --- a/src/analysis/network/qgsgraphdirector.h +++ b/src/analysis/network/qgsgraphdirector.h @@ -47,8 +47,8 @@ class ANALYSIS_EXPORT QgsGraphDirector : public QObject * * @param builder the graph builder * @param additionalPoints list of points that should be snapped to the graph - * @param tiedPoints list of snapped points - * @note if tiedPoints[i] == QgsPoint(0.0,0.0) then snapping failed. + * @param snappedPoints list of snapped points + * @note if snappedPoints[i] == QgsPoint(0.0,0.0) then snapping failed. */ virtual void makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint > &additionalPoints, From f9be17997f3437903e05a75fc1e9ea68bf18947b Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Sat, 19 Nov 2016 14:58:04 +0200 Subject: [PATCH 852/897] make cost() method pure virtual --- python/analysis/network/qgsstrategy.sip | 2 +- src/analysis/network/qgsstrategy.h | 7 +------ 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/python/analysis/network/qgsstrategy.sip b/python/analysis/network/qgsstrategy.sip index 63cc03ff4fcb..06aa35286f33 100644 --- a/python/analysis/network/qgsstrategy.sip +++ b/python/analysis/network/qgsstrategy.sip @@ -46,5 +46,5 @@ class QgsStrategy /** * Return edge cost */ - virtual QVariant cost( double distance, const QgsFeature &f ) const; + virtual QVariant cost( double distance, const QgsFeature &f ) const = 0; }; diff --git a/src/analysis/network/qgsstrategy.h b/src/analysis/network/qgsstrategy.h index 685e63f162ff..34300de332c0 100644 --- a/src/analysis/network/qgsstrategy.h +++ b/src/analysis/network/qgsstrategy.h @@ -51,12 +51,7 @@ class ANALYSIS_EXPORT QgsStrategy /** * Return edge cost */ - virtual QVariant cost( double distance, const QgsFeature &f ) const - { - Q_UNUSED( distance ); - Q_UNUSED( f ); - return QVariant(); - } + virtual QVariant cost( double distance, const QgsFeature &f ) const = 0; }; #endif // QGSSTRATERGY_H From a61e8bbdec66e580d6dabac180022224f078af9f Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Sat, 19 Nov 2016 15:41:39 +0200 Subject: [PATCH 853/897] rename QgsStrategy to QgsNetworkStrategy to avoid possible future confusion when we will have other stuff with strategies. Also rename corresponding subclasses --- python/analysis/analysis.sip | 6 +-- python/analysis/network/qgsgraphdirector.sip | 2 +- ...egy.sip => qgsnetworkdistancestrategy.sip} | 4 +- .../network/qgsnetworkspeedstrategy.sip | 13 +++++ .../analysis/network/qgsnetworkstrategy.sip | 50 +++++++++++++++++++ python/analysis/network/qgsspeedstrategy.sip | 13 ----- python/analysis/network/qgsstrategy.sip | 50 ------------------- src/analysis/CMakeLists.txt | 10 ++-- src/analysis/network/qgsgraphdirector.h | 6 +-- .../network/qgslinevectorlayerdirector.cpp | 4 +- ...egy.cpp => qgsnetworkdistancestrategy.cpp} | 4 +- ...trategy.h => qgsnetworkdistancestrategy.h} | 16 +++--- ...rategy.cpp => qgsnetworkspeedstrategy.cpp} | 8 +-- ...edstrategy.h => qgsnetworkspeedstrategy.h} | 14 +++--- .../{qgsstrategy.h => qgsnetworkstrategy.h} | 24 ++++----- src/plugins/roadgraph/roadgraphplugin.cpp | 8 +-- 16 files changed, 116 insertions(+), 116 deletions(-) rename python/analysis/network/{qgsdistancestrategy.sip => qgsnetworkdistancestrategy.sip} (53%) create mode 100644 python/analysis/network/qgsnetworkspeedstrategy.sip create mode 100644 python/analysis/network/qgsnetworkstrategy.sip delete mode 100644 python/analysis/network/qgsspeedstrategy.sip delete mode 100644 python/analysis/network/qgsstrategy.sip rename src/analysis/network/{qgsdistancestrategy.cpp => qgsnetworkdistancestrategy.cpp} (88%) rename src/analysis/network/{qgsdistancestrategy.h => qgsnetworkdistancestrategy.h} (75%) rename src/analysis/network/{qgsspeedstrategy.cpp => qgsnetworkspeedstrategy.cpp} (82%) rename src/analysis/network/{qgsspeedstrategy.h => qgsnetworkspeedstrategy.h} (82%) rename src/analysis/network/{qgsstrategy.h => qgsnetworkstrategy.h} (73%) diff --git a/python/analysis/analysis.sip b/python/analysis/analysis.sip index 9c07ec216b6b..ce8930a5302b 100644 --- a/python/analysis/analysis.sip +++ b/python/analysis/analysis.sip @@ -54,9 +54,9 @@ %Include raster/qgstotalcurvaturefilter.sip %Include network/qgsgraph.sip -%Include network/qgsstrategy.sip -%Include network/qgsspeedstrategy.sip -%Include network/qgsdistancestrategy.sip +%Include network/qgsnetworkstrategy.sip +%Include network/qgsnetworkspeedstrategy.sip +%Include network/qgsnetworkdistancestrategy.sip %Include network/qgsgraphbuilderinterface.sip %Include network/qgsgraphbuilder.sip %Include network/qgsgraphdirector.sip diff --git a/python/analysis/network/qgsgraphdirector.sip b/python/analysis/network/qgsgraphdirector.sip index b9c6ae728cd2..f6d4239e8396 100644 --- a/python/analysis/network/qgsgraphdirector.sip +++ b/python/analysis/network/qgsgraphdirector.sip @@ -42,7 +42,7 @@ class QgsGraphDirector : QObject QVector< QgsPoint > &snappedPoints /Out/ ) const; //! Add optimization strategy - void addStrategy( QgsStrategy* prop /Transfer/); + void addStrategy( QgsNetworkStrategy* prop /Transfer/); //! Returns director name virtual QString name() const = 0; diff --git a/python/analysis/network/qgsdistancestrategy.sip b/python/analysis/network/qgsnetworkdistancestrategy.sip similarity index 53% rename from python/analysis/network/qgsdistancestrategy.sip rename to python/analysis/network/qgsnetworkdistancestrategy.sip index 7cc9f821a765..bc1a5e32f5e8 100644 --- a/python/analysis/network/qgsdistancestrategy.sip +++ b/python/analysis/network/qgsnetworkdistancestrategy.sip @@ -1,7 +1,7 @@ -class QgsDistanceStrategy : QgsStrategy +class QgsNetworkDistanceStrategy : QgsNetworkStrategy { %TypeHeaderCode -#include +#include %End public: diff --git a/python/analysis/network/qgsnetworkspeedstrategy.sip b/python/analysis/network/qgsnetworkspeedstrategy.sip new file mode 100644 index 000000000000..dbd2c7cd5686 --- /dev/null +++ b/python/analysis/network/qgsnetworkspeedstrategy.sip @@ -0,0 +1,13 @@ +class QgsNetworkSpeedStrategy : QgsNetworkStrategy +{ +%TypeHeaderCode +#include +%End + + public: + QgsNetworkSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ); + + QVariant cost( double distance, const QgsFeature& f ) const; + + QgsAttributeList requiredAttributes() const; +}; diff --git a/python/analysis/network/qgsnetworkstrategy.sip b/python/analysis/network/qgsnetworkstrategy.sip new file mode 100644 index 000000000000..81769735ff2f --- /dev/null +++ b/python/analysis/network/qgsnetworkstrategy.sip @@ -0,0 +1,50 @@ +%ModuleHeaderCode +#include +#include +%End + +/** + * \ingroup analysis + * \class QgsNetworkStrategy + * \brief QgsNetworkStrategy defines strategy used for calculation of the edge cost. For example it can + * take into account travel distance, amount of time or money. Currently there are two strategies + * implemented in the analysis library: QgsNetworkDistanceStrategy and QgsNetworkSpeedStrategy. + * QgsNetworkStrategy implemented using "strategy" design pattern. + */ +class QgsNetworkStrategy +{ +%TypeHeaderCode +#include +%End + +%ConvertToSubClassCode + if ( dynamic_cast< QgsNetworkDistanceStrategy* > ( sipCpp ) != NULL ) + sipType = sipType_QgsNetworkDistanceStrategy; + else if ( dynamic_cast< QgsNetworkSpeedStrategy* > ( sipCpp ) != NULL ) + sipType = sipType_QgsNetworkSpeedStrategy; + else + sipType = NULL; +%End + + + public: + + /** + * Default constructor + */ + QgsNetworkStrategy(); + + virtual ~QgsNetworkStrategy(); + + /** + * Returns list of the source layer attributes needed for cost calculation. + * This method called by QgsGraphDirector. + * \return list of required attributes + */ + virtual QgsAttributeList requiredAttributes() const; + + /** + * Returns edge cost + */ + virtual QVariant cost( double distance, const QgsFeature &f ) const = 0; +}; diff --git a/python/analysis/network/qgsspeedstrategy.sip b/python/analysis/network/qgsspeedstrategy.sip deleted file mode 100644 index 047beefdd42e..000000000000 --- a/python/analysis/network/qgsspeedstrategy.sip +++ /dev/null @@ -1,13 +0,0 @@ -class QgsSpeedStrategy : QgsStrategy -{ -%TypeHeaderCode -#include -%End - - public: - QgsSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ); - - QVariant cost( double distance, const QgsFeature& f ) const; - - QgsAttributeList requiredAttributes() const; -}; diff --git a/python/analysis/network/qgsstrategy.sip b/python/analysis/network/qgsstrategy.sip deleted file mode 100644 index 06aa35286f33..000000000000 --- a/python/analysis/network/qgsstrategy.sip +++ /dev/null @@ -1,50 +0,0 @@ -%ModuleHeaderCode -#include -#include -%End - -/** - * \ingroup analysis - * \class QgsStrategy - * \brief QgsStrategy defines strategy used for calculation of the edge cost. For example it can - * take into account travel distance, amount of time or money. Currently there are two strategies - * implemented in the analysis library: QgsDistanceStrategy and QgsSpeedStrategy. - * QgsStrategy implemented with strategy design pattern. - */ -class QgsStrategy -{ -%TypeHeaderCode -#include -%End - -%ConvertToSubClassCode - if ( dynamic_cast< QgsDistanceStrategy* > ( sipCpp ) != NULL ) - sipType = sipType_QgsStrategy; - else if ( dynamic_cast< QgsSpeedStrategy* > ( sipCpp ) != NULL ) - sipType = sipType_QgsSpeedStrategy; - else - sipType = NULL; -%End - - - public: - - /** - * Default constructor - */ - QgsStrategy(); - - virtual ~QgsStrategy(); - - /** - * Returns list of the source layer attributes needed for cost calculation. - * This method called by QgsGraphDirector. - * \return list of required attributes - */ - virtual QgsAttributeList requiredAttributes() const; - - /** - * Return edge cost - */ - virtual QVariant cost( double distance, const QgsFeature &f ) const = 0; -}; diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index 2a15b1aa45a3..239d603fe532 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -49,8 +49,8 @@ SET(QGIS_ANALYSIS_SRCS network/qgsgraph.cpp network/qgsgraphbuilder.cpp - network/qgsspeedstrategy.cpp - network/qgsdistancestrategy.cpp + network/qgsnetworkspeedstrategy.cpp + network/qgsnetworkdistancestrategy.cpp network/qgslinevectorlayerdirector.cpp network/qgsgraphanalyzer.cpp ) @@ -146,9 +146,9 @@ SET(QGIS_ANALYSIS_HDRS network/qgsgraph.h network/qgsgraphbuilderinterface.h network/qgsgraphbuilder.h - network/qgsstrategy.h - network/qgsspeedstrategy.h - network/qgsdistancestrategy.h + network/qgsnetworkstrategy.h + network/qgsnetworkspeedstrategy.h + network/qgsnetworkdistancestrategy.h network/qgsgraphdirector.h network/qgslinevectorlayerdirector.h network/qgsgraphanalyzer.h diff --git a/src/analysis/network/qgsgraphdirector.h b/src/analysis/network/qgsgraphdirector.h index 6f5361f98d1c..610b0b62d2c2 100644 --- a/src/analysis/network/qgsgraphdirector.h +++ b/src/analysis/network/qgsgraphdirector.h @@ -21,7 +21,7 @@ #include #include -#include "qgsstrategy.h" +#include "qgsnetworkstrategy.h" class QgsGraphBuilderInterface; @@ -60,7 +60,7 @@ class ANALYSIS_EXPORT QgsGraphDirector : public QObject } //! Add optimization strategy - void addStrategy( QgsStrategy* prop ) + void addStrategy( QgsNetworkStrategy* prop ) { mStrategies.push_back( prop ); } @@ -69,7 +69,7 @@ class ANALYSIS_EXPORT QgsGraphDirector : public QObject virtual QString name() const = 0; protected: - QList mStrategies; + QList mStrategies; }; #endif // QGSGRAPHDIRECTOR_H diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgslinevectorlayerdirector.cpp index ce0a57a449c1..355df9d5a4c4 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgslinevectorlayerdirector.cpp @@ -253,7 +253,7 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c tmpAttr.push_back( mDirectionFieldId ); } - QList< QgsStrategy* >::const_iterator it; + QList< QgsNetworkStrategy* >::const_iterator it; QgsAttributeList::const_iterator it2; for ( it = mStrategies.begin(); it != mStrategies.end(); ++it ) @@ -366,7 +366,7 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c { double distance = builder->distanceArea()->measureLine( pt1, pt2 ); QVector< QVariant > prop; - QList< QgsStrategy* >::const_iterator it; + QList< QgsNetworkStrategy* >::const_iterator it; for ( it = mStrategies.begin(); it != mStrategies.end(); ++it ) { prop.push_back(( *it )->cost( distance, feature ) ); diff --git a/src/analysis/network/qgsdistancestrategy.cpp b/src/analysis/network/qgsnetworkdistancestrategy.cpp similarity index 88% rename from src/analysis/network/qgsdistancestrategy.cpp rename to src/analysis/network/qgsnetworkdistancestrategy.cpp index e1c353dc02e7..3dcb0f58eb68 100644 --- a/src/analysis/network/qgsdistancestrategy.cpp +++ b/src/analysis/network/qgsnetworkdistancestrategy.cpp @@ -13,9 +13,9 @@ * * ***************************************************************************/ -#include "qgsdistancestrategy.h" +#include "qgsnetworkdistancestrategy.h" -QVariant QgsDistanceStrategy::cost( double distance, const QgsFeature& f ) const +QVariant QgsNetworkDistanceStrategy::cost( double distance, const QgsFeature& f ) const { Q_UNUSED( f ); return QVariant( distance ); diff --git a/src/analysis/network/qgsdistancestrategy.h b/src/analysis/network/qgsnetworkdistancestrategy.h similarity index 75% rename from src/analysis/network/qgsdistancestrategy.h rename to src/analysis/network/qgsnetworkdistancestrategy.h index fe6882aa879f..53f340585b8a 100644 --- a/src/analysis/network/qgsdistancestrategy.h +++ b/src/analysis/network/qgsnetworkdistancestrategy.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsdistancestrategy.h + qgsnetworkdistancestrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,21 +13,21 @@ * * ***************************************************************************/ -#ifndef QGSDISTANCESTRATEGY_H -#define QGSDISTANCESTRATEGY_H +#ifndef QGSNETWORKDISTANCESTRATEGY_H +#define QGSNETWORKDISTANCESTRATEGY_H -#include +#include /** \ingroup analysis - * \class QgsDistanceStrategy + * \class QgsNetworkDistanceStrategy * \note added in QGIS 3.0 - * \brief Strategy for caclucating edge cost based on its length. Should be + * \brief Strategy for caclulating edge cost based on its length. Should be * used for finding shortest path between two points. */ -class ANALYSIS_EXPORT QgsDistanceStrategy : public QgsStrategy +class ANALYSIS_EXPORT QgsNetworkDistanceStrategy : public QgsNetworkStrategy { public: virtual QVariant cost( double distance, const QgsFeature& ) const override; }; -#endif // QGSDISTANCEARCPROPERTER_H +#endif // QGSNETWORKDISTANCESTRATEGY_H diff --git a/src/analysis/network/qgsspeedstrategy.cpp b/src/analysis/network/qgsnetworkspeedstrategy.cpp similarity index 82% rename from src/analysis/network/qgsspeedstrategy.cpp rename to src/analysis/network/qgsnetworkspeedstrategy.cpp index 2d0eaec59fef..8f87590650a1 100644 --- a/src/analysis/network/qgsspeedstrategy.cpp +++ b/src/analysis/network/qgsnetworkspeedstrategy.cpp @@ -13,16 +13,16 @@ * * ***************************************************************************/ -#include "qgsspeedstrategy.h" +#include "qgsnetworkspeedstrategy.h" -QgsSpeedStrategy::QgsSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ) +QgsNetworkSpeedStrategy::QgsNetworkSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ) { mAttributeId = attributeId; mDefaultValue = defaultValue; mToMetricFactor = toMetricFactor; } -QVariant QgsSpeedStrategy::cost( double distance, const QgsFeature& f ) const +QVariant QgsNetworkSpeedStrategy::cost( double distance, const QgsFeature& f ) const { QgsAttributes attrs = f.attributes(); @@ -36,7 +36,7 @@ QVariant QgsSpeedStrategy::cost( double distance, const QgsFeature& f ) const return QVariant( val ); } -QgsAttributeList QgsSpeedStrategy::requiredAttributes() const +QgsAttributeList QgsNetworkSpeedStrategy::requiredAttributes() const { QgsAttributeList l; l.push_back( mAttributeId ); diff --git a/src/analysis/network/qgsspeedstrategy.h b/src/analysis/network/qgsnetworkspeedstrategy.h similarity index 82% rename from src/analysis/network/qgsspeedstrategy.h rename to src/analysis/network/qgsnetworkspeedstrategy.h index 5608873c5fea..98a0df692164 100644 --- a/src/analysis/network/qgsspeedstrategy.h +++ b/src/analysis/network/qgsnetworkspeedstrategy.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsspeedstrategy.h + qgsnetworkspeedstrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,10 +13,10 @@ * * ***************************************************************************/ -#ifndef QGSSPEEDSTRATEGY_H -#define QGSSPEEDSTRATEGY_H +#ifndef QGSNETWORKSPEEDSTRATEGY_H +#define QGSNETWORKSPEEDSTRATEGY_H -#include +#include /** \ingroup analysis * \class QgsSpeedStrategy @@ -24,14 +24,14 @@ * \brief Strategy for caclucating edge cost based on travel time. Should be * used for finding fastest path between two points. */ -class ANALYSIS_EXPORT QgsSpeedStrategy : public QgsStrategy +class ANALYSIS_EXPORT QgsNetworkSpeedStrategy : public QgsNetworkStrategy { public: /** * Default constructor */ - QgsSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ); + QgsNetworkSpeedStrategy( int attributeId, double defaultValue, double toMetricFactor ); //! Returns edge cost QVariant cost( double distance, const QgsFeature& f ) const override; @@ -49,4 +49,4 @@ class ANALYSIS_EXPORT QgsSpeedStrategy : public QgsStrategy }; -#endif // QGSSPEEDSTRATEGY_H +#endif // QGSNETWORKSPEEDSTRATEGY_H diff --git a/src/analysis/network/qgsstrategy.h b/src/analysis/network/qgsnetworkstrategy.h similarity index 73% rename from src/analysis/network/qgsstrategy.h rename to src/analysis/network/qgsnetworkstrategy.h index 34300de332c0..dd8bffdc7825 100644 --- a/src/analysis/network/qgsstrategy.h +++ b/src/analysis/network/qgsnetworkstrategy.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgsstrategy.h + qgsnetworkstrategy.h -------------------------------------- Date : 2011-04-01 Copyright : (C) 2010 by Yakushev Sergey @@ -13,8 +13,8 @@ * * ***************************************************************************/ -#ifndef QGSSTRATERGY_H -#define QGSSTRATERGY_H +#ifndef QGSNETWORKSTRATERGY_H +#define QGSNETWORKSTRATERGY_H #include @@ -23,23 +23,23 @@ /** * \ingroup analysis - * \class QgsStrategy + * \class QgsNetworkStrategy * \note added in QGIS 3.0 - * \brief QgsStrategy defines strategy used for calculation of the edge cost. For example it can + * \brief QgsNetworkStrategy defines strategy used for calculation of the edge cost. For example it can * take into account travel distance, amount of time or money. Currently there are two strategies - * implemented in the analysis library: QgsDistanceStrategy and QgsSpeedStrategy. - * QgsStrategy implemented with strategy design pattern. + * implemented in the analysis library: QgsNetworkDistanceStrategy and QgsNetworkSpeedStrategy. + * QgsNetworkStrategy implemented using "strategy" design pattern. */ -class ANALYSIS_EXPORT QgsStrategy +class ANALYSIS_EXPORT QgsNetworkStrategy { public: /** * Default constructor */ - QgsStrategy() {} + QgsNetworkStrategy() {} - virtual ~QgsStrategy() {} + virtual ~QgsNetworkStrategy() {} /** * Returns list of the source layer attributes needed for cost calculation. @@ -49,9 +49,9 @@ class ANALYSIS_EXPORT QgsStrategy virtual QgsAttributeList requiredAttributes() const { return QgsAttributeList(); } /** - * Return edge cost + * Returns edge cost */ virtual QVariant cost( double distance, const QgsFeature &f ) const = 0; }; -#endif // QGSSTRATERGY_H +#endif // QGSNETWORKSTRATERGY_H diff --git a/src/plugins/roadgraph/roadgraphplugin.cpp b/src/plugins/roadgraph/roadgraphplugin.cpp index e9254614667f..c92881b07f46 100644 --- a/src/plugins/roadgraph/roadgraphplugin.cpp +++ b/src/plugins/roadgraph/roadgraphplugin.cpp @@ -29,8 +29,8 @@ #include #include #include -#include -#include +#include +#include #include "qgsdockwidget.h" // Road grap plugin includes @@ -218,8 +218,8 @@ const QgsGraphDirector* RoadGraphPlugin::director() const mSettings->mBothDirectionVal, mSettings->mDefaultDirection ); - director->addStrategy( new QgsDistanceStrategy() ); - director->addStrategy( new QgsSpeedStrategy( layer->fields().lookupField( mSettings->mSpeed ), + director->addStrategy( new QgsNetworkDistanceStrategy() ); + director->addStrategy( new QgsNetworkSpeedStrategy( layer->fields().lookupField( mSettings->mSpeed ), mSettings->mDefaultSpeed, speedUnit.multipler() ) ); return director; } From 9dffe64dabb4c29374e922e2a04b123cf4420d79 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Sat, 19 Nov 2016 16:56:51 +0200 Subject: [PATCH 854/897] replace hardcoded magic numbers with enum --- .../network/qgslinevectorlayerdirector.sip | 18 +++++++++-- .../network/qgslinevectorlayerdirector.cpp | 20 ++++++------ .../network/qgslinevectorlayerdirector.h | 27 ++++++++++++---- .../roadgraph/linevectorlayersettings.cpp | 32 ++++++------------- .../roadgraph/linevectorlayersettings.h | 4 ++- .../roadgraph/linevectorlayerwidget.cpp | 6 ++-- 6 files changed, 61 insertions(+), 46 deletions(-) diff --git a/python/analysis/network/qgslinevectorlayerdirector.sip b/python/analysis/network/qgslinevectorlayerdirector.sip index d387496658b7..02e5f9a68e9b 100644 --- a/python/analysis/network/qgslinevectorlayerdirector.sip +++ b/python/analysis/network/qgslinevectorlayerdirector.sip @@ -10,20 +10,34 @@ class QgsLineVectorLayerDirector : QgsGraphDirector %End public: + /** Road direction + * Road can be one-way with direct flow (one can move only from the start + * point to the end point), one-way with reversed flow (one can move only + * from the end point to the start point) and bidirectional or two-way + * (one can move in any direction) + */ + enum RoadDirection + { + RoadDirect, //!< One-way direct + RoadReversed, //!< One-way reversed + RoadBidirectional, //!< Two-way + }; + /** * @param myLayer source vector layer * @param directionFieldId feield contain road direction value * @param directDirectionValue value for one-way road * @param reverseDirectionValue value for reverse one-way road * @param bothDirectionValue value for road - * @param defaultDirection 1 - direct direction, 2 - reverse direction, 3 - both direction + * @param defaultDirection default road direction. Will be used if corresponding + * attribute value is not set or does not equal to the given values */ QgsLineVectorLayerDirector( QgsVectorLayer* myLayer, int directionFieldId, const QString& directDirectionValue, const QString& reverseDirectionValue, const QString& bothDirectionValue, - int defaultDirection + const RoadDirection defaultDirection ); //! Destructor diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgslinevectorlayerdirector.cpp index 355df9d5a4c4..1e230f84da2c 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgslinevectorlayerdirector.cpp @@ -102,12 +102,12 @@ bool TiePointInfoCompare( const TiePointInfo& a, const TiePointInfo& b ) return a.mFirstPoint.x() == b.mFirstPoint.x() ? a.mFirstPoint.y() < b.mFirstPoint.y() : a.mFirstPoint.x() < b.mFirstPoint.x(); } -QgsLineVectorLayerDirector::QgsLineVectorLayerDirector( QgsVectorLayer *myLayer, +QgsLineVectorLayerDirector::QgsLineVectorLayerDirector(QgsVectorLayer *myLayer, int directionFieldId, const QString& directDirectionValue, const QString& reverseDirectionValue, const QString& bothDirectionValue, - int defaultDirection + const RoadDirection defaultDirection ) { mVectorLayer = myLayer; @@ -284,21 +284,21 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c fit = vl->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( la ) ); while ( fit.nextFeature( feature ) ) { - int directionType = mDefaultDirection; + RoadDirection directionType = mDefaultDirection; // What direction have feature? QString str = feature.attribute( mDirectionFieldId ).toString(); if ( str == mBothDirectionValue ) { - directionType = 3; + directionType = RoadDirection::RoadBidirectional; } else if ( str == mDirectDirectionValue ) { - directionType = 1; + directionType = RoadDirection::RoadDirect; } else if ( str == mReverseDirectionValue ) { - directionType = 2; + directionType = RoadDirection::RoadReversed; } // begin features segments and add arc to the Graph; @@ -372,13 +372,13 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c prop.push_back(( *it )->cost( distance, feature ) ); } - if ( directionType == 1 || - directionType == 3 ) + if ( directionType == RoadDirection::RoadDirect || + directionType == RoadDirection::RoadBidirectional ) { builder->addEdge( pt1idx, pt1, pt2idx, pt2, prop ); } - if ( directionType == 2 || - directionType == 3 ) + if ( directionType == RoadDirection::RoadReversed || + directionType == RoadDirection::RoadBidirectional ) { builder->addEdge( pt2idx, pt2, pt1idx, pt1, prop ); } diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgslinevectorlayerdirector.h index a6d148c0d86c..ba67f4f78460 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgslinevectorlayerdirector.h @@ -1,5 +1,5 @@ /*************************************************************************** - linevectorlayerdirector.h + qgslinevectorlayerdirector.h -------------------------------------- Date : 2010-10-20 Copyright : (C) 2010 by Yakushev Sergey @@ -32,21 +32,35 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector public: + /** Road direction + * Road can be one-way with direct flow (one can move only from the start + * point to the end point), one-way with reversed flow (one can move only + * from the end point to the start point) and bidirectional or two-way + * (one can move in any direction) + */ + enum RoadDirection + { + RoadDirect, //!< One-way direct + RoadReversed, //!< One-way reversed + RoadBidirectional, //!< Two-way + }; + /** * Default constructor * @param myLayer source vector layer * @param directionFieldId field contain road direction value - * @param directDirectionValue value for one-way road + * @param directDirectionValue value for direct one-way road * @param reverseDirectionValue value for reversed one-way road - * @param bothDirectionValue value for bidirectional road - * @param defaultDirection 1 - direct direction, 2 - reverse direction, 3 - both directions + * @param bothDirectionValue value for two-way (bidirectional) road + * @param defaultDirection default road direction. Will be used if corresponding + * attribute value is not set or does not equal to the given values */ QgsLineVectorLayerDirector( QgsVectorLayer* myLayer, int directionFieldId, const QString& directDirectionValue, const QString& reverseDirectionValue, const QString& bothDirectionValue, - int defaultDirection + const RoadDirection defaultDirection ); //! Destructor @@ -72,8 +86,7 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector QString mBothDirectionValue; - //FIXME: need enum - int mDefaultDirection; + RoadDirection mDefaultDirection; }; #endif // QGSLINEVECTORLAYERDIRECTOR_H diff --git a/src/plugins/roadgraph/linevectorlayersettings.cpp b/src/plugins/roadgraph/linevectorlayersettings.cpp index a4abd996be84..9fda16a6a573 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.cpp +++ b/src/plugins/roadgraph/linevectorlayersettings.cpp @@ -29,7 +29,7 @@ //standard includes RgLineVectorLayerSettings::RgLineVectorLayerSettings() - : mDefaultDirection( Both ) + : mDefaultDirection( QgsLineVectorLayerDirector::RoadDirection::RoadBidirectional ) , mDefaultSpeed( 40 ) { } @@ -58,31 +58,17 @@ bool RgLineVectorLayerSettings::test() void RgLineVectorLayerSettings::read( const QgsProject *project ) { - int dd = project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ); - mDirection = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/directionField" ) ); + mDefaultDirection = static_cast ( project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ) ); + mDirection = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/directionField" ) ); mFirstPointToLastPointDirectionVal = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/FirstPointToLastPointDirectionVal" ) ); mLastPointToFirstPointDirectionVal = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/LastPointToFirstPointDirectionVal" ) ); mBothDirectionVal = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/BothDirectionVal" ) ); - mSpeed = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedField" ) ); + mSpeed = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedField" ) ); mDefaultSpeed = project->readDoubleEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultSpeed" ) ); - mLayerName = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/layer" ) ); + mLayerName = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/layer" ) ); mSpeedUnitName = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/speedUnitName" ) ); - - if ( dd == 1 ) - { - mDefaultDirection = FirstPointToLastPoint; - } - else if ( dd == 2 ) - { - mDefaultDirection = LastPointToFirstPoint; - } - else if ( dd == 3 ) - { - mDefaultDirection = Both; - } - } // RgLineVectorLayerSettings::read( const QgsProject *project ) void RgLineVectorLayerSettings::write( QgsProject *project ) @@ -115,19 +101,19 @@ void RgLineVectorLayerSettings::setFromGui( QWidget *myGui ) mLastPointToFirstPointDirectionVal = w->mleLastPointToFirstPointDirection->text(); mBothDirectionVal = w->mleBothDirection->text(); mDirection = w->mcbDirection->currentText(); - mLayerName = w->mcbLayers->currentText(); + mLayerName = w->mcbLayers->currentText(); if ( w->mcbDirectionDefault->currentIndex() == 0 ) { - mDefaultDirection = Both; + mDefaultDirection = QgsLineVectorLayerDirector::RoadDirection::RoadBidirectional; } else if ( w->mcbDirectionDefault->currentIndex() == 1 ) { - mDefaultDirection = FirstPointToLastPoint; + mDefaultDirection = QgsLineVectorLayerDirector::RoadDirection::RoadDirect; } else if ( w->mcbDirectionDefault->currentIndex() == 2 ) { - mDefaultDirection = LastPointToFirstPoint; + mDefaultDirection = QgsLineVectorLayerDirector::RoadDirection::RoadReversed; } mSpeed = w->mcbSpeed->currentText(); diff --git a/src/plugins/roadgraph/linevectorlayersettings.h b/src/plugins/roadgraph/linevectorlayersettings.h index aacef098aadc..3e908af42b6e 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.h +++ b/src/plugins/roadgraph/linevectorlayersettings.h @@ -17,6 +17,8 @@ // QT includes #include +#include + // Qgis includes // standard includes @@ -93,7 +95,7 @@ class RgLineVectorLayerSettings: public RgSettings /** * contained Default direction */ - DirectionType mDefaultDirection; + QgsLineVectorLayerDirector::RoadDirection mDefaultDirection; /** * contained speed filed name diff --git a/src/plugins/roadgraph/linevectorlayerwidget.cpp b/src/plugins/roadgraph/linevectorlayerwidget.cpp index 47903e6fecfb..94194ca7ca2b 100644 --- a/src/plugins/roadgraph/linevectorlayerwidget.cpp +++ b/src/plugins/roadgraph/linevectorlayerwidget.cpp @@ -143,13 +143,13 @@ RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget( RgLineVectorLa switch ( s->mDefaultDirection ) { - case RgLineVectorLayerSettings::Both: + case QgsLineVectorLayerDirector::RoadDirection::RoadBidirectional: mcbDirectionDefault->setCurrentIndex( 0 ); break; - case RgLineVectorLayerSettings::FirstPointToLastPoint: + case QgsLineVectorLayerDirector::RoadDirection::RoadDirect: mcbDirectionDefault->setCurrentIndex( 1 ); break; - case RgLineVectorLayerSettings::LastPointToFirstPoint: + case QgsLineVectorLayerDirector::RoadDirection::RoadReversed: mcbDirectionDefault->setCurrentIndex( 2 ); break; } From d657c77a8ce457ea567146dfc9767114dc44e322 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 21 Nov 2016 11:29:02 +0200 Subject: [PATCH 855/897] rename enum and its values --- .../network/qgslinevectorlayerdirector.sip | 10 +++++----- .../network/qgslinevectorlayerdirector.cpp | 20 +++++++++---------- .../network/qgslinevectorlayerdirector.h | 17 ++++++---------- .../network/qgsnetworkspeedstrategy.h | 4 ++-- .../roadgraph/linevectorlayersettings.cpp | 10 +++++----- .../roadgraph/linevectorlayersettings.h | 2 +- .../roadgraph/linevectorlayerwidget.cpp | 6 +++--- 7 files changed, 32 insertions(+), 37 deletions(-) diff --git a/python/analysis/network/qgslinevectorlayerdirector.sip b/python/analysis/network/qgslinevectorlayerdirector.sip index 02e5f9a68e9b..e33acea8ca3c 100644 --- a/python/analysis/network/qgslinevectorlayerdirector.sip +++ b/python/analysis/network/qgslinevectorlayerdirector.sip @@ -16,11 +16,11 @@ class QgsLineVectorLayerDirector : QgsGraphDirector * from the end point to the start point) and bidirectional or two-way * (one can move in any direction) */ - enum RoadDirection + enum Direction { - RoadDirect, //!< One-way direct - RoadReversed, //!< One-way reversed - RoadBidirectional, //!< Two-way + DirectionForward, //!< One-way direct + DirectionBackward, //!< One-way reversed + DirectionBoth, //!< Two-way }; /** @@ -37,7 +37,7 @@ class QgsLineVectorLayerDirector : QgsGraphDirector const QString& directDirectionValue, const QString& reverseDirectionValue, const QString& bothDirectionValue, - const RoadDirection defaultDirection + const Direction defaultDirection ); //! Destructor diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgslinevectorlayerdirector.cpp index 1e230f84da2c..89bc54c2901a 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgslinevectorlayerdirector.cpp @@ -102,12 +102,12 @@ bool TiePointInfoCompare( const TiePointInfo& a, const TiePointInfo& b ) return a.mFirstPoint.x() == b.mFirstPoint.x() ? a.mFirstPoint.y() < b.mFirstPoint.y() : a.mFirstPoint.x() < b.mFirstPoint.x(); } -QgsLineVectorLayerDirector::QgsLineVectorLayerDirector(QgsVectorLayer *myLayer, +QgsLineVectorLayerDirector::QgsLineVectorLayerDirector( QgsVectorLayer *myLayer, int directionFieldId, const QString& directDirectionValue, const QString& reverseDirectionValue, const QString& bothDirectionValue, - const RoadDirection defaultDirection + const Direction defaultDirection ) { mVectorLayer = myLayer; @@ -284,21 +284,21 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c fit = vl->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( la ) ); while ( fit.nextFeature( feature ) ) { - RoadDirection directionType = mDefaultDirection; + Direction directionType = mDefaultDirection; // What direction have feature? QString str = feature.attribute( mDirectionFieldId ).toString(); if ( str == mBothDirectionValue ) { - directionType = RoadDirection::RoadBidirectional; + directionType = Direction::DirectionBoth; } else if ( str == mDirectDirectionValue ) { - directionType = RoadDirection::RoadDirect; + directionType = Direction::DirectionForward; } else if ( str == mReverseDirectionValue ) { - directionType = RoadDirection::RoadReversed; + directionType = Direction::DirectionBackward; } // begin features segments and add arc to the Graph; @@ -372,13 +372,13 @@ void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, c prop.push_back(( *it )->cost( distance, feature ) ); } - if ( directionType == RoadDirection::RoadDirect || - directionType == RoadDirection::RoadBidirectional ) + if ( directionType == Direction::DirectionForward || + directionType == Direction::DirectionBoth ) { builder->addEdge( pt1idx, pt1, pt2idx, pt2, prop ); } - if ( directionType == RoadDirection::RoadReversed || - directionType == RoadDirection::RoadBidirectional ) + if ( directionType == Direction::DirectionBackward || + directionType == Direction::DirectionBoth ) { builder->addEdge( pt2idx, pt2, pt1idx, pt1, prop ); } diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgslinevectorlayerdirector.h index ba67f4f78460..bc44051bfa1d 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgslinevectorlayerdirector.h @@ -38,11 +38,11 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector * from the end point to the start point) and bidirectional or two-way * (one can move in any direction) */ - enum RoadDirection + enum Direction { - RoadDirect, //!< One-way direct - RoadReversed, //!< One-way reversed - RoadBidirectional, //!< Two-way + DirectionForward, //!< One-way direct + DirectionBackward, //!< One-way reversed + DirectionBoth, //!< Two-way }; /** @@ -60,7 +60,7 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector const QString& directDirectionValue, const QString& reverseDirectionValue, const QString& bothDirectionValue, - const RoadDirection defaultDirection + const Direction defaultDirection ); //! Destructor @@ -77,16 +77,11 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector private: QgsVectorLayer *mVectorLayer; - int mDirectionFieldId; - QString mDirectDirectionValue; - QString mReverseDirectionValue; - QString mBothDirectionValue; - - RoadDirection mDefaultDirection; + Direction mDefaultDirection; }; #endif // QGSLINEVECTORLAYERDIRECTOR_H diff --git a/src/analysis/network/qgsnetworkspeedstrategy.h b/src/analysis/network/qgsnetworkspeedstrategy.h index 98a0df692164..6c56c7fdaca1 100644 --- a/src/analysis/network/qgsnetworkspeedstrategy.h +++ b/src/analysis/network/qgsnetworkspeedstrategy.h @@ -19,9 +19,9 @@ #include /** \ingroup analysis - * \class QgsSpeedStrategy + * \class QgsNetworkSpeedStrategy * \note added in QGIS 3.0 - * \brief Strategy for caclucating edge cost based on travel time. Should be + * \brief Strategy for calcucating edge cost based on travel time. Should be * used for finding fastest path between two points. */ class ANALYSIS_EXPORT QgsNetworkSpeedStrategy : public QgsNetworkStrategy diff --git a/src/plugins/roadgraph/linevectorlayersettings.cpp b/src/plugins/roadgraph/linevectorlayersettings.cpp index 9fda16a6a573..b48a34f7a678 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.cpp +++ b/src/plugins/roadgraph/linevectorlayersettings.cpp @@ -29,7 +29,7 @@ //standard includes RgLineVectorLayerSettings::RgLineVectorLayerSettings() - : mDefaultDirection( QgsLineVectorLayerDirector::RoadDirection::RoadBidirectional ) + : mDefaultDirection( QgsLineVectorLayerDirector::Direction::DirectionBoth ) , mDefaultSpeed( 40 ) { } @@ -58,7 +58,7 @@ bool RgLineVectorLayerSettings::test() void RgLineVectorLayerSettings::read( const QgsProject *project ) { - mDefaultDirection = static_cast ( project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ) ); + mDefaultDirection = static_cast( project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ) ); mDirection = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/directionField" ) ); mFirstPointToLastPointDirectionVal = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/FirstPointToLastPointDirectionVal" ) ); @@ -105,15 +105,15 @@ void RgLineVectorLayerSettings::setFromGui( QWidget *myGui ) if ( w->mcbDirectionDefault->currentIndex() == 0 ) { - mDefaultDirection = QgsLineVectorLayerDirector::RoadDirection::RoadBidirectional; + mDefaultDirection = QgsLineVectorLayerDirector::Direction::DirectionBoth; } else if ( w->mcbDirectionDefault->currentIndex() == 1 ) { - mDefaultDirection = QgsLineVectorLayerDirector::RoadDirection::RoadDirect; + mDefaultDirection = QgsLineVectorLayerDirector::Direction::DirectionForward; } else if ( w->mcbDirectionDefault->currentIndex() == 2 ) { - mDefaultDirection = QgsLineVectorLayerDirector::RoadDirection::RoadReversed; + mDefaultDirection = QgsLineVectorLayerDirector::Direction::DirectionBackward; } mSpeed = w->mcbSpeed->currentText(); diff --git a/src/plugins/roadgraph/linevectorlayersettings.h b/src/plugins/roadgraph/linevectorlayersettings.h index 3e908af42b6e..dfdc14897067 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.h +++ b/src/plugins/roadgraph/linevectorlayersettings.h @@ -95,7 +95,7 @@ class RgLineVectorLayerSettings: public RgSettings /** * contained Default direction */ - QgsLineVectorLayerDirector::RoadDirection mDefaultDirection; + QgsLineVectorLayerDirector::Direction mDefaultDirection; /** * contained speed filed name diff --git a/src/plugins/roadgraph/linevectorlayerwidget.cpp b/src/plugins/roadgraph/linevectorlayerwidget.cpp index 94194ca7ca2b..6d81abcdd3b4 100644 --- a/src/plugins/roadgraph/linevectorlayerwidget.cpp +++ b/src/plugins/roadgraph/linevectorlayerwidget.cpp @@ -143,13 +143,13 @@ RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget( RgLineVectorLa switch ( s->mDefaultDirection ) { - case QgsLineVectorLayerDirector::RoadDirection::RoadBidirectional: + case QgsLineVectorLayerDirector::Direction::DirectionBoth: mcbDirectionDefault->setCurrentIndex( 0 ); break; - case QgsLineVectorLayerDirector::RoadDirection::RoadDirect: + case QgsLineVectorLayerDirector::Direction::DirectionForward: mcbDirectionDefault->setCurrentIndex( 1 ); break; - case QgsLineVectorLayerDirector::RoadDirection::RoadReversed: + case QgsLineVectorLayerDirector::Direction::DirectionBackward: mcbDirectionDefault->setCurrentIndex( 2 ); break; } From b421a53675d2f653432c1ece41ec34aa9a252871 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 21 Nov 2016 16:33:34 +0200 Subject: [PATCH 856/897] rename QgsLineVectorLayerDirector to QgsVectorLayerDirector --- python/analysis/analysis.sip | 2 +- python/analysis/network/qgsgraphdirector.sip | 6 ++--- ...irector.sip => qgsvectorlayerdirector.sip} | 22 +++++++++---------- src/analysis/CMakeLists.txt | 6 ++--- ...irector.cpp => qgsvectorlayerdirector.cpp} | 10 ++++----- ...yerdirector.h => qgsvectorlayerdirector.h} | 16 +++++++------- .../roadgraph/linevectorlayersettings.cpp | 10 ++++----- .../roadgraph/linevectorlayersettings.h | 4 ++-- .../roadgraph/linevectorlayerwidget.cpp | 6 ++--- src/plugins/roadgraph/roadgraphplugin.cpp | 18 +++++++-------- 10 files changed, 50 insertions(+), 50 deletions(-) rename python/analysis/network/{qgslinevectorlayerdirector.sip => qgsvectorlayerdirector.sip} (69%) rename src/analysis/network/{qgslinevectorlayerdirector.cpp => qgsvectorlayerdirector.cpp} (97%) rename src/analysis/network/{qgslinevectorlayerdirector.h => qgsvectorlayerdirector.h} (89%) diff --git a/python/analysis/analysis.sip b/python/analysis/analysis.sip index ce8930a5302b..636eae955a9b 100644 --- a/python/analysis/analysis.sip +++ b/python/analysis/analysis.sip @@ -60,5 +60,5 @@ %Include network/qgsgraphbuilderinterface.sip %Include network/qgsgraphbuilder.sip %Include network/qgsgraphdirector.sip -%Include network/qgslinevectorlayerdirector.sip +%Include network/qgsvectorlayerdirector.sip %Include network/qgsgraphanalyzer.sip diff --git a/python/analysis/network/qgsgraphdirector.sip b/python/analysis/network/qgsgraphdirector.sip index f6d4239e8396..92b53890c333 100644 --- a/python/analysis/network/qgsgraphdirector.sip +++ b/python/analysis/network/qgsgraphdirector.sip @@ -1,5 +1,5 @@ %ModuleHeaderCode -#include +#include %End /** @@ -14,8 +14,8 @@ class QgsGraphDirector : QObject %End %ConvertToSubClassCode - if ( dynamic_cast< QgsLineVectorLayerDirector* > ( sipCpp ) != NULL ) - sipType = sipType_QgsLineVectorLayerDirector; + if ( dynamic_cast< QgsVectorLayerDirector* > ( sipCpp ) != NULL ) + sipType = sipType_QgsVectorLayerDirector; else sipType = NULL; %End diff --git a/python/analysis/network/qgslinevectorlayerdirector.sip b/python/analysis/network/qgsvectorlayerdirector.sip similarity index 69% rename from python/analysis/network/qgslinevectorlayerdirector.sip rename to python/analysis/network/qgsvectorlayerdirector.sip index e33acea8ca3c..12bff40eddd9 100644 --- a/python/analysis/network/qgslinevectorlayerdirector.sip +++ b/python/analysis/network/qgsvectorlayerdirector.sip @@ -1,12 +1,12 @@ /** * \ingroup analysis -* \class QgsLineVectorLayerDirector +* \class QgsVectorLayerDirector * \brief Determine making the graph from vector line layer */ -class QgsLineVectorLayerDirector : QgsGraphDirector +class QgsVectorLayerDirector : QgsGraphDirector { %TypeHeaderCode -#include +#include %End public: @@ -32,16 +32,16 @@ class QgsLineVectorLayerDirector : QgsGraphDirector * @param defaultDirection default road direction. Will be used if corresponding * attribute value is not set or does not equal to the given values */ - QgsLineVectorLayerDirector( QgsVectorLayer* myLayer, - int directionFieldId, - const QString& directDirectionValue, - const QString& reverseDirectionValue, - const QString& bothDirectionValue, - const Direction defaultDirection - ); + QgsVectorLayerDirector( QgsVectorLayer* myLayer, + int directionFieldId, + const QString& directDirectionValue, + const QString& reverseDirectionValue, + const QString& bothDirectionValue, + const Direction defaultDirection + ); //! Destructor - virtual ~QgsLineVectorLayerDirector(); + virtual ~QgsVectorLayerDirector(); /* * MANDATORY DIRECTOR PROPERTY DECLARATION diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index 239d603fe532..ff77465170a7 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -51,7 +51,7 @@ SET(QGIS_ANALYSIS_SRCS network/qgsgraphbuilder.cpp network/qgsnetworkspeedstrategy.cpp network/qgsnetworkdistancestrategy.cpp - network/qgslinevectorlayerdirector.cpp + network/qgsvectorlayerdirector.cpp network/qgsgraphanalyzer.cpp ) @@ -61,7 +61,7 @@ SET(QGIS_ANALYSIS_MOC_HDRS vector/qgsgeometrysnapper.h network/qgsgraphdirector.h - network/qgslinevectorlayerdirector.h + network/qgsvectorlayerdirector.h ) INCLUDE_DIRECTORIES(SYSTEM ${SPATIALITE_INCLUDE_DIR}) @@ -150,7 +150,7 @@ SET(QGIS_ANALYSIS_HDRS network/qgsnetworkspeedstrategy.h network/qgsnetworkdistancestrategy.h network/qgsgraphdirector.h - network/qgslinevectorlayerdirector.h + network/qgsvectorlayerdirector.h network/qgsgraphanalyzer.h ) diff --git a/src/analysis/network/qgslinevectorlayerdirector.cpp b/src/analysis/network/qgsvectorlayerdirector.cpp similarity index 97% rename from src/analysis/network/qgslinevectorlayerdirector.cpp rename to src/analysis/network/qgsvectorlayerdirector.cpp index 89bc54c2901a..73aea714d1f5 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.cpp +++ b/src/analysis/network/qgsvectorlayerdirector.cpp @@ -18,7 +18,7 @@ * \brief implementation of QgsLineVectorLayerDirector */ -#include "qgslinevectorlayerdirector.h" +#include "qgsvectorlayerdirector.h" #include "qgsgraphbuilderinterface.h" #include "qgsfeatureiterator.h" @@ -102,7 +102,7 @@ bool TiePointInfoCompare( const TiePointInfo& a, const TiePointInfo& b ) return a.mFirstPoint.x() == b.mFirstPoint.x() ? a.mFirstPoint.y() < b.mFirstPoint.y() : a.mFirstPoint.x() < b.mFirstPoint.x(); } -QgsLineVectorLayerDirector::QgsLineVectorLayerDirector( QgsVectorLayer *myLayer, +QgsVectorLayerDirector::QgsVectorLayerDirector( QgsVectorLayer *myLayer, int directionFieldId, const QString& directDirectionValue, const QString& reverseDirectionValue, @@ -118,17 +118,17 @@ QgsLineVectorLayerDirector::QgsLineVectorLayerDirector( QgsVectorLayer *myLayer, mBothDirectionValue = bothDirectionValue; } -QgsLineVectorLayerDirector::~QgsLineVectorLayerDirector() +QgsVectorLayerDirector::~QgsVectorLayerDirector() { } -QString QgsLineVectorLayerDirector::name() const +QString QgsVectorLayerDirector::name() const { return QStringLiteral( "Vector line" ); } -void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, +void QgsVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, QVector< QgsPoint >& snappedPoints ) const { QgsVectorLayer *vl = mVectorLayer; diff --git a/src/analysis/network/qgslinevectorlayerdirector.h b/src/analysis/network/qgsvectorlayerdirector.h similarity index 89% rename from src/analysis/network/qgslinevectorlayerdirector.h rename to src/analysis/network/qgsvectorlayerdirector.h index bc44051bfa1d..b5c1b6be8d8a 100644 --- a/src/analysis/network/qgslinevectorlayerdirector.h +++ b/src/analysis/network/qgsvectorlayerdirector.h @@ -1,5 +1,5 @@ /*************************************************************************** - qgslinevectorlayerdirector.h + qgsvectorlayerdirector.h -------------------------------------- Date : 2010-10-20 Copyright : (C) 2010 by Yakushev Sergey @@ -13,8 +13,8 @@ * * ***************************************************************************/ -#ifndef QGSLINEVECTORLAYERDIRECTOR_H -#define QGSLINEVECTORLAYERDIRECTOR_H +#ifndef QGSVECTORLAYERDIRECTOR_H +#define QGSVECTORLAYERDIRECTOR_H #include "qgsgraphdirector.h" @@ -23,10 +23,10 @@ class QgsVectorLayer; /** * \ingroup analysis -* \class QgsLineVectorLayerDirector +* \class QgsVectorLayerDirector * \brief Determine making the graph from vector line layer */ -class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector +class ANALYSIS_EXPORT QgsVectorLayerDirector : public QgsGraphDirector { Q_OBJECT @@ -55,7 +55,7 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector * @param defaultDirection default road direction. Will be used if corresponding * attribute value is not set or does not equal to the given values */ - QgsLineVectorLayerDirector( QgsVectorLayer* myLayer, + QgsVectorLayerDirector( QgsVectorLayer* myLayer, int directionFieldId, const QString& directDirectionValue, const QString& reverseDirectionValue, @@ -64,7 +64,7 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector ); //! Destructor - virtual ~QgsLineVectorLayerDirector(); + virtual ~QgsVectorLayerDirector(); /* * MANDATORY DIRECTOR PROPERTY DECLARATION @@ -84,4 +84,4 @@ class ANALYSIS_EXPORT QgsLineVectorLayerDirector : public QgsGraphDirector Direction mDefaultDirection; }; -#endif // QGSLINEVECTORLAYERDIRECTOR_H +#endif // QGSVECTORLAYERDIRECTOR_H diff --git a/src/plugins/roadgraph/linevectorlayersettings.cpp b/src/plugins/roadgraph/linevectorlayersettings.cpp index b48a34f7a678..ba9f3b67b151 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.cpp +++ b/src/plugins/roadgraph/linevectorlayersettings.cpp @@ -29,7 +29,7 @@ //standard includes RgLineVectorLayerSettings::RgLineVectorLayerSettings() - : mDefaultDirection( QgsLineVectorLayerDirector::Direction::DirectionBoth ) + : mDefaultDirection( QgsVectorLayerDirector::Direction::DirectionBoth ) , mDefaultSpeed( 40 ) { } @@ -58,7 +58,7 @@ bool RgLineVectorLayerSettings::test() void RgLineVectorLayerSettings::read( const QgsProject *project ) { - mDefaultDirection = static_cast( project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ) ); + mDefaultDirection = static_cast( project->readNumEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/defaultDirection" ) ) ); mDirection = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/directionField" ) ); mFirstPointToLastPointDirectionVal = project->readEntry( QStringLiteral( "roadgraphplugin" ), QStringLiteral( "/FirstPointToLastPointDirectionVal" ) ); @@ -105,15 +105,15 @@ void RgLineVectorLayerSettings::setFromGui( QWidget *myGui ) if ( w->mcbDirectionDefault->currentIndex() == 0 ) { - mDefaultDirection = QgsLineVectorLayerDirector::Direction::DirectionBoth; + mDefaultDirection = QgsVectorLayerDirector::Direction::DirectionBoth; } else if ( w->mcbDirectionDefault->currentIndex() == 1 ) { - mDefaultDirection = QgsLineVectorLayerDirector::Direction::DirectionForward; + mDefaultDirection = QgsVectorLayerDirector::Direction::DirectionForward; } else if ( w->mcbDirectionDefault->currentIndex() == 2 ) { - mDefaultDirection = QgsLineVectorLayerDirector::Direction::DirectionBackward; + mDefaultDirection = QgsVectorLayerDirector::Direction::DirectionBackward; } mSpeed = w->mcbSpeed->currentText(); diff --git a/src/plugins/roadgraph/linevectorlayersettings.h b/src/plugins/roadgraph/linevectorlayersettings.h index dfdc14897067..5696afdfb508 100644 --- a/src/plugins/roadgraph/linevectorlayersettings.h +++ b/src/plugins/roadgraph/linevectorlayersettings.h @@ -17,7 +17,7 @@ // QT includes #include -#include +#include // Qgis includes @@ -95,7 +95,7 @@ class RgLineVectorLayerSettings: public RgSettings /** * contained Default direction */ - QgsLineVectorLayerDirector::Direction mDefaultDirection; + QgsVectorLayerDirector::Direction mDefaultDirection; /** * contained speed filed name diff --git a/src/plugins/roadgraph/linevectorlayerwidget.cpp b/src/plugins/roadgraph/linevectorlayerwidget.cpp index 6d81abcdd3b4..68d209d68ea3 100644 --- a/src/plugins/roadgraph/linevectorlayerwidget.cpp +++ b/src/plugins/roadgraph/linevectorlayerwidget.cpp @@ -143,13 +143,13 @@ RgLineVectorLayerSettingsWidget::RgLineVectorLayerSettingsWidget( RgLineVectorLa switch ( s->mDefaultDirection ) { - case QgsLineVectorLayerDirector::Direction::DirectionBoth: + case QgsVectorLayerDirector::Direction::DirectionBoth: mcbDirectionDefault->setCurrentIndex( 0 ); break; - case QgsLineVectorLayerDirector::Direction::DirectionForward: + case QgsVectorLayerDirector::Direction::DirectionForward: mcbDirectionDefault->setCurrentIndex( 1 ); break; - case QgsLineVectorLayerDirector::Direction::DirectionBackward: + case QgsVectorLayerDirector::Direction::DirectionBackward: mcbDirectionDefault->setCurrentIndex( 2 ); break; } diff --git a/src/plugins/roadgraph/roadgraphplugin.cpp b/src/plugins/roadgraph/roadgraphplugin.cpp index c92881b07f46..7dcdc22717d7 100644 --- a/src/plugins/roadgraph/roadgraphplugin.cpp +++ b/src/plugins/roadgraph/roadgraphplugin.cpp @@ -26,7 +26,7 @@ #include #include -#include +#include #include #include #include @@ -210,14 +210,14 @@ const QgsGraphDirector* RoadGraphPlugin::director() const { SpeedUnit speedUnit = SpeedUnit::byName( mSettings->mSpeedUnitName ); - QgsLineVectorLayerDirector * director = - new QgsLineVectorLayerDirector( layer, - layer->fields().lookupField( mSettings->mDirection ), - mSettings->mFirstPointToLastPointDirectionVal, - mSettings->mLastPointToFirstPointDirectionVal, - mSettings->mBothDirectionVal, - mSettings->mDefaultDirection - ); + QgsVectorLayerDirector * director = + new QgsVectorLayerDirector( layer, + layer->fields().lookupField( mSettings->mDirection ), + mSettings->mFirstPointToLastPointDirectionVal, + mSettings->mLastPointToFirstPointDirectionVal, + mSettings->mBothDirectionVal, + mSettings->mDefaultDirection + ); director->addStrategy( new QgsNetworkDistanceStrategy() ); director->addStrategy( new QgsNetworkSpeedStrategy( layer->fields().lookupField( mSettings->mSpeed ), mSettings->mDefaultSpeed, speedUnit.multipler() ) ); From fb5cdd83ee2a7d013bb63385f79938890026695f Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 21 Nov 2016 16:44:44 +0200 Subject: [PATCH 857/897] remove word "road" from doxygen comments --- python/analysis/network/qgsgraph.sip | 2 +- .../network/qgsgraphbuilderinterface.sip | 3 ++- python/analysis/network/qgsgraphdirector.sip | 3 ++- .../network/qgsvectorlayerdirector.sip | 6 +++--- src/analysis/network/qgsgraph.h | 2 +- .../network/qgsgraphbuilderinterface.h | 2 +- src/analysis/network/qgsgraphdirector.h | 3 ++- .../network/qgsvectorlayerdirector.cpp | 8 ++++---- src/analysis/network/qgsvectorlayerdirector.h | 20 +++++++++---------- 9 files changed, 26 insertions(+), 23 deletions(-) diff --git a/python/analysis/network/qgsgraph.sip b/python/analysis/network/qgsgraph.sip index d565ebe73fe3..a6462a59697a 100644 --- a/python/analysis/network/qgsgraph.sip +++ b/python/analysis/network/qgsgraph.sip @@ -79,7 +79,7 @@ class QgsGraphVertex /** * \ingroup analysis * \class QgsGraph - * \brief Mathematics graph representation + * \brief Mathematical graph representation */ class QgsGraph diff --git a/python/analysis/network/qgsgraphbuilderinterface.sip b/python/analysis/network/qgsgraphbuilderinterface.sip index 14205f1aa3f5..fb71cafe659b 100644 --- a/python/analysis/network/qgsgraphbuilderinterface.sip +++ b/python/analysis/network/qgsgraphbuilderinterface.sip @@ -5,7 +5,8 @@ /** * \ingroup analysis * \class QgsGraphBuilderInterface -* \brief Determine interface for creating a graph. Contains the settings of the graph. QgsGraphBuilder and QgsGraphDirector is a Builder pattern +* \brief Determine interface for creating a graph. Contains the settings of the graph. +* QgsGraphBuilder and QgsGraphDirector both use a "builder" design pattern */ class QgsGraphBuilderInterface { diff --git a/python/analysis/network/qgsgraphdirector.sip b/python/analysis/network/qgsgraphdirector.sip index 92b53890c333..4dc55d6ae695 100644 --- a/python/analysis/network/qgsgraphdirector.sip +++ b/python/analysis/network/qgsgraphdirector.sip @@ -5,7 +5,8 @@ /** * \ingroup analysis * \class QgsGraphDirector - * \brief Determine making the graph. QgsGraphBuilder and QgsGraphDirector is a builder patter. + * \brief Determine making the graph. QgsGraphBuilder and QgsGraphDirector + * are implemented using "builder" design patter. */ class QgsGraphDirector : QObject { diff --git a/python/analysis/network/qgsvectorlayerdirector.sip b/python/analysis/network/qgsvectorlayerdirector.sip index 12bff40eddd9..70809b879f82 100644 --- a/python/analysis/network/qgsvectorlayerdirector.sip +++ b/python/analysis/network/qgsvectorlayerdirector.sip @@ -10,8 +10,8 @@ class QgsVectorLayerDirector : QgsGraphDirector %End public: - /** Road direction - * Road can be one-way with direct flow (one can move only from the start + /** Edge direction + * Edge can be one-way with direct flow (one can move only from the start * point to the end point), one-way with reversed flow (one can move only * from the end point to the start point) and bidirectional or two-way * (one can move in any direction) @@ -29,7 +29,7 @@ class QgsVectorLayerDirector : QgsGraphDirector * @param directDirectionValue value for one-way road * @param reverseDirectionValue value for reverse one-way road * @param bothDirectionValue value for road - * @param defaultDirection default road direction. Will be used if corresponding + * @param defaultDirection default direction. Will be used if corresponding * attribute value is not set or does not equal to the given values */ QgsVectorLayerDirector( QgsVectorLayer* myLayer, diff --git a/src/analysis/network/qgsgraph.h b/src/analysis/network/qgsgraph.h index 07f5c2bfa304..e93b773b44a0 100644 --- a/src/analysis/network/qgsgraph.h +++ b/src/analysis/network/qgsgraph.h @@ -124,7 +124,7 @@ class ANALYSIS_EXPORT QgsGraphVertex /** * \ingroup analysis * \class QgsGraph - * \brief Mathematics graph representation + * \brief Mathematical graph representation */ class ANALYSIS_EXPORT QgsGraph diff --git a/src/analysis/network/qgsgraphbuilderinterface.h b/src/analysis/network/qgsgraphbuilderinterface.h index 92de360cae8c..e63672e0df50 100644 --- a/src/analysis/network/qgsgraphbuilderinterface.h +++ b/src/analysis/network/qgsgraphbuilderinterface.h @@ -27,7 +27,7 @@ * \ingroup analysis * \class QgsGraphBuilderInterface * \brief Determine interface for creating a graph. Contains the settings of the graph. -* QgsGraphBuilder and QgsGraphDirector both use a Builder pattern +* QgsGraphBuilder and QgsGraphDirector both use a "builder" design pattern */ class ANALYSIS_EXPORT QgsGraphBuilderInterface { diff --git a/src/analysis/network/qgsgraphdirector.h b/src/analysis/network/qgsgraphdirector.h index 610b0b62d2c2..bb7de5c8d3f6 100644 --- a/src/analysis/network/qgsgraphdirector.h +++ b/src/analysis/network/qgsgraphdirector.h @@ -28,7 +28,8 @@ class QgsGraphBuilderInterface; /** * \ingroup analysis * \class QgsGraphDirector - * \brief Determine making the graph. QgsGraphBuilder and QgsGraphDirector is a builder patter. + * \brief Determine making the graph. QgsGraphBuilder and QgsGraphDirector implemented + * using "builder" design patter. */ class ANALYSIS_EXPORT QgsGraphDirector : public QObject { diff --git a/src/analysis/network/qgsvectorlayerdirector.cpp b/src/analysis/network/qgsvectorlayerdirector.cpp index 73aea714d1f5..725576777c86 100644 --- a/src/analysis/network/qgsvectorlayerdirector.cpp +++ b/src/analysis/network/qgsvectorlayerdirector.cpp @@ -14,8 +14,8 @@ ***************************************************************************/ /** - * \file qgslinevectorlayerdirector.cpp - * \brief implementation of QgsLineVectorLayerDirector + * \file qgsvectorlayerdirector.cpp + * \brief implementation of QgsVectorLayerDirector */ #include "qgsvectorlayerdirector.h" @@ -108,7 +108,7 @@ QgsVectorLayerDirector::QgsVectorLayerDirector( QgsVectorLayer *myLayer, const QString& reverseDirectionValue, const QString& bothDirectionValue, const Direction defaultDirection - ) + ) { mVectorLayer = myLayer; mDirectionFieldId = directionFieldId; @@ -129,7 +129,7 @@ QString QgsVectorLayerDirector::name() const } void QgsVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, - QVector< QgsPoint >& snappedPoints ) const + QVector< QgsPoint >& snappedPoints ) const { QgsVectorLayer *vl = mVectorLayer; diff --git a/src/analysis/network/qgsvectorlayerdirector.h b/src/analysis/network/qgsvectorlayerdirector.h index b5c1b6be8d8a..c1ca7ed861a4 100644 --- a/src/analysis/network/qgsvectorlayerdirector.h +++ b/src/analysis/network/qgsvectorlayerdirector.h @@ -32,8 +32,8 @@ class ANALYSIS_EXPORT QgsVectorLayerDirector : public QgsGraphDirector public: - /** Road direction - * Road can be one-way with direct flow (one can move only from the start + /** Edge direction + * Edge can be one-way with direct flow (one can move only from the start * point to the end point), one-way with reversed flow (one can move only * from the end point to the start point) and bidirectional or two-way * (one can move in any direction) @@ -48,20 +48,20 @@ class ANALYSIS_EXPORT QgsVectorLayerDirector : public QgsGraphDirector /** * Default constructor * @param myLayer source vector layer - * @param directionFieldId field contain road direction value + * @param directionFieldId field containing direction value * @param directDirectionValue value for direct one-way road * @param reverseDirectionValue value for reversed one-way road * @param bothDirectionValue value for two-way (bidirectional) road - * @param defaultDirection default road direction. Will be used if corresponding + * @param defaultDirection default direction. Will be used if corresponding * attribute value is not set or does not equal to the given values */ QgsVectorLayerDirector( QgsVectorLayer* myLayer, - int directionFieldId, - const QString& directDirectionValue, - const QString& reverseDirectionValue, - const QString& bothDirectionValue, - const Direction defaultDirection - ); + int directionFieldId, + const QString& directDirectionValue, + const QString& reverseDirectionValue, + const QString& bothDirectionValue, + const Direction defaultDirection + ); //! Destructor virtual ~QgsVectorLayerDirector(); From 82082b44f65aa51f6aa703e5cba9ca1163914e2d Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Mon, 21 Nov 2016 18:46:45 +0200 Subject: [PATCH 858/897] add doxygen note --- src/analysis/network/qgsvectorlayerdirector.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/analysis/network/qgsvectorlayerdirector.h b/src/analysis/network/qgsvectorlayerdirector.h index c1ca7ed861a4..6b4fd8816f8e 100644 --- a/src/analysis/network/qgsvectorlayerdirector.h +++ b/src/analysis/network/qgsvectorlayerdirector.h @@ -24,6 +24,7 @@ class QgsVectorLayer; /** * \ingroup analysis * \class QgsVectorLayerDirector +* \note added in QGIS 3.0 * \brief Determine making the graph from vector line layer */ class ANALYSIS_EXPORT QgsVectorLayerDirector : public QgsGraphDirector From 22dc09669299a4c24d45b9201c6bf346cd276974 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 21 Nov 2016 22:07:52 +0100 Subject: [PATCH 859/897] Enable WFS test with a fix to prevent crash on exit (#3774) * Revert "Disable failing PyQgsOfflineEditingWFS test" This reverts commit 33ee514b5dfdc1b57558cb9007df5b455a59fc17. * Let lifetime of layers be controlled by QGIS --- ci/travis/linux/script.sh | 2 +- tests/src/python/test_offline_editing_wfs.py | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/ci/travis/linux/script.sh b/ci/travis/linux/script.sh index 8fa3ad27078d..977e70b84f36 100755 --- a/ci/travis/linux/script.sh +++ b/ci/travis/linux/script.sh @@ -25,5 +25,5 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" export OTB_APPLICATION_PATH=${HOME}/OTB-5.6.0-Linux64/lib/otb/applications export LD_PRELOAD=/lib/x86_64-linux-gnu/libSegFault.so -xvfb-run ctest -V -E "qgis_filedownloader|qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|PyQgsOfflineEditingWFS|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure +xvfb-run ctest -V -E "qgis_filedownloader|qgis_openstreetmaptest|qgis_wcsprovidertest|PyQgsWFSProviderGUI|qgis_ziplayertest|$(cat ${DIR}/blacklist.txt | paste -sd '|' -)" -S ./qgis-test-travis.ctest --output-on-failure # xvfb-run ctest -V -E "qgis_openstreetmaptest|qgis_wcsprovidertest" -S ./qgis-test-travis.ctest --output-on-failure diff --git a/tests/src/python/test_offline_editing_wfs.py b/tests/src/python/test_offline_editing_wfs.py index 8c58df9e78bc..771885ba516d 100644 --- a/tests/src/python/test_offline_editing_wfs.py +++ b/tests/src/python/test_offline_editing_wfs.py @@ -37,7 +37,11 @@ import tempfile from time import sleep from utilities import unitTestDataPath, waitServer -from qgis.core import QgsVectorLayer +from qgis.core import ( + QgsVectorLayer, + QgsMapLayerRegistry, + QgsAuthManager +) from qgis.testing import ( start_app, @@ -133,6 +137,7 @@ def _getOnlineLayer(self, type_name, layer_name=None): self.counter += 1 uri = ' '.join([("%s='%s'" % (k, v)) for k, v in list(parms.items())]) wfs_layer = QgsVectorLayer(uri, layer_name, 'WFS') + wfs_layer.setParent(QgsAuthManager.instance()) assert wfs_layer.isValid() return wfs_layer @@ -143,6 +148,7 @@ def _getLayer(cls, layer_name): """ path = cls.testdata_path + layer_name + '.shp' layer = QgsVectorLayer(path, layer_name, "ogr") + layer.setParent(QgsAuthManager.instance()) assert layer.isValid() return layer From 8c8be007b9d1da1b686309e4cf4d44e16738863d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 21 Nov 2016 10:07:22 +1000 Subject: [PATCH 860/897] Remove redundant setLayer slots from QgsField(ComboBox|ExpressionWidget) and switch uses of remaining slot to new style connects --- doc/api_break.dox | 12 ++++++++++++ python/gui/qgsfieldcombobox.sip | 13 +++++++++---- python/gui/qgsfieldexpressionwidget.sip | 13 ++++++++----- src/app/composer/qgsatlascompositionwidget.cpp | 4 ++-- src/app/qgsjoindialog.cpp | 6 +++--- src/app/qgslayerstylingwidget.cpp | 2 +- src/app/qgsrelationadddlg.cpp | 6 ++---- .../editorwidgets/qgsvaluerelationconfigdlg.cpp | 4 ++-- src/gui/qgsfieldcombobox.cpp | 12 ++---------- src/gui/qgsfieldcombobox.h | 13 +++++++++---- src/gui/qgsfieldexpressionwidget.cpp | 15 ++++----------- src/gui/qgsfieldexpressionwidget.h | 12 ++++++++---- src/gui/qgsorderbydialog.cpp | 1 + src/plugins/heatmap/heatmapgui.cpp | 4 ++-- 14 files changed, 65 insertions(+), 52 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index 190f1b947fce..ce1a1aad4d01 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -842,6 +842,18 @@ QgsFeatureRendererV2 {#qgis_api_break_3_0_QgsFeatureRendererV2} - copyPaintEffect() was removed. copyRendererData() should be used instead. +QgsFieldCombobox {#qgis_api_break_3_0_QgsFieldCombobox} +---------------- + +- The setLayer( QgsVectorlayer* ) slot has been removed. Use the setLayer( QgsMapLayer* ) slot instead. + + +QgsFieldExpressionWidget {#qgis_api_break_3_0_QgsFieldExpressionWidget} +------------------------ + +- The setLayer( QgsVectorlayer* ) slot has been removed. Use the setLayer( QgsMapLayer* ) slot instead. + + QgsFields {#qgis_api_break_3_0_QgsFields} --------- diff --git a/python/gui/qgsfieldcombobox.sip b/python/gui/qgsfieldcombobox.sip index 57c26f089fbd..195168a6a160 100644 --- a/python/gui/qgsfieldcombobox.sip +++ b/python/gui/qgsfieldcombobox.sip @@ -42,7 +42,10 @@ class QgsFieldComboBox : QComboBox //! return the currently selected field QString currentField() const; - //! Returns the currently used layer + /** + * Returns the layer currently associated with the combobox. + * @see setLayer() + */ QgsVectorLayer* layer() const; signals: @@ -50,10 +53,12 @@ class QgsFieldComboBox : QComboBox void fieldChanged( const QString& fieldName ); public slots: - //! set the layer of which the fields are listed - void setLayer( QgsVectorLayer* layer ); - //! convenience slot to connect QgsMapLayerComboBox layer signal + /** + * Sets the layer for which fields are listed in the combobox. If no layer is set + * or a non-vector layer is set then the combobox will be empty. + * @see layer() + */ void setLayer( QgsMapLayer* layer ); //! setField sets the currently selected field diff --git a/python/gui/qgsfieldexpressionwidget.sip b/python/gui/qgsfieldexpressionwidget.sip index 7b9f1fdc8ddb..4c2f92cb266e 100644 --- a/python/gui/qgsfieldexpressionwidget.sip +++ b/python/gui/qgsfieldexpressionwidget.sip @@ -64,7 +64,10 @@ class QgsFieldExpressionWidget : QWidget */ QString expression() const; - //! Returns the currently used layer + /** + * Returns the layer currently associated with the widget. + * @see setLayer() + */ QgsVectorLayer* layer() const; /** @@ -86,10 +89,10 @@ class QgsFieldExpressionWidget : QWidget // void returnPressed(); public slots: - //! set the layer used to display the fields and expression - void setLayer( QgsVectorLayer* layer ); - - //! convenience slot to connect QgsMapLayerComboBox layer signal + /** + * Sets the layer used to display the fields and expression. + * @see layer() + */ void setLayer( QgsMapLayer* layer ); //! sets the current row in the widget diff --git a/src/app/composer/qgsatlascompositionwidget.cpp b/src/app/composer/qgsatlascompositionwidget.cpp index 4b0a95091699..445429484eed 100644 --- a/src/app/composer/qgsatlascompositionwidget.cpp +++ b/src/app/composer/qgsatlascompositionwidget.cpp @@ -33,8 +33,8 @@ QgsAtlasCompositionWidget::QgsAtlasCompositionWidget( QWidget* parent, QgsCompos mAtlasCoverageLayerComboBox->setFilters( QgsMapLayerProxyModel::VectorLayer ); - connect( mAtlasCoverageLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), mAtlasSortFeatureKeyComboBox, SLOT( setLayer( QgsMapLayer* ) ) ); - connect( mAtlasCoverageLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), mPageNameWidget, SLOT( setLayer( QgsMapLayer* ) ) ); + connect( mAtlasCoverageLayerComboBox, &QgsMapLayerComboBox::layerChanged, mAtlasSortFeatureKeyComboBox, &QgsFieldComboBox::setLayer ); + connect( mAtlasCoverageLayerComboBox, &QgsMapLayerComboBox::layerChanged, mPageNameWidget, &QgsFieldExpressionWidget::setLayer ); connect( mAtlasCoverageLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), this, SLOT( changeCoverageLayer( QgsMapLayer* ) ) ); connect( mAtlasSortFeatureKeyComboBox, SIGNAL( fieldChanged( QString ) ), this, SLOT( changesSortFeatureField( QString ) ) ); connect( mPageNameWidget, SIGNAL( fieldChanged( QString, bool ) ), this, SLOT( pageNameExpressionChanged( QString, bool ) ) ); diff --git a/src/app/qgsjoindialog.cpp b/src/app/qgsjoindialog.cpp index 7c9e5ffb47b4..4c52f3a47788 100644 --- a/src/app/qgsjoindialog.cpp +++ b/src/app/qgsjoindialog.cpp @@ -43,8 +43,8 @@ QgsJoinDialog::QgsJoinDialog( QgsVectorLayer* layer, QList already mJoinLayerComboBox->setFilters( QgsMapLayerProxyModel::VectorLayer ); mJoinLayerComboBox->setExceptedLayerList( alreadyJoinedLayers ); - connect( mJoinLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), mJoinFieldComboBox, SLOT( setLayer( QgsMapLayer* ) ) ); - connect( mJoinLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), this, SLOT( joinedLayerChanged( QgsMapLayer* ) ) ); + connect( mJoinLayerComboBox, &QgsMapLayerComboBox::layerChanged, mJoinFieldComboBox, &QgsFieldComboBox::setLayer ); + connect( mJoinLayerComboBox, &QgsMapLayerComboBox::layerChanged, this, &QgsJoinDialog::joinedLayerChanged ); mCacheInMemoryCheckBox->setChecked( true ); @@ -55,7 +55,7 @@ QgsJoinDialog::QgsJoinDialog( QgsVectorLayer* layer, QList already joinedLayerChanged( joinLayer ); } - connect( mJoinLayerComboBox, SIGNAL( layerChanged( QgsMapLayer* ) ), this, SLOT( checkDefinitionValid() ) ); + connect( mJoinLayerComboBox, &QgsMapLayerComboBox::layerChanged, this, &QgsJoinDialog::checkDefinitionValid ); connect( mJoinFieldComboBox, SIGNAL( fieldChanged( QString ) ), this, SLOT( checkDefinitionValid() ) ); connect( mTargetFieldComboBox, SIGNAL( fieldChanged( QString ) ), this, SLOT( checkDefinitionValid() ) ); diff --git a/src/app/qgslayerstylingwidget.cpp b/src/app/qgslayerstylingwidget.cpp index c868bd051d03..fc59a6903cbd 100644 --- a/src/app/qgslayerstylingwidget.cpp +++ b/src/app/qgslayerstylingwidget.cpp @@ -83,7 +83,7 @@ QgsLayerStylingWidget::QgsLayerStylingWidget( QgsMapCanvas* canvas, const QList< connect( mOptionsListWidget, SIGNAL( currentRowChanged( int ) ), this, SLOT( updateCurrentWidgetLayer() ) ); connect( mButtonBox->button( QDialogButtonBox::Apply ), SIGNAL( clicked() ), this, SLOT( apply() ) ); - connect( mLayerCombo, SIGNAL( layerChanged( QgsMapLayer* ) ), this, SLOT( setLayer( QgsMapLayer* ) ) ); + connect( mLayerCombo, &QgsMapLayerComboBox::layerChanged, this, &QgsLayerStylingWidget::setLayer ); connect( mLiveApplyCheck, SIGNAL( toggled( bool ) ), this, SLOT( liveApplyToggled( bool ) ) ); mStackedWidget->setCurrentIndex( 0 ); diff --git a/src/app/qgsrelationadddlg.cpp b/src/app/qgsrelationadddlg.cpp index 3b44e4973931..aca91bc24e17 100644 --- a/src/app/qgsrelationadddlg.cpp +++ b/src/app/qgsrelationadddlg.cpp @@ -25,10 +25,8 @@ QgsRelationAddDlg::QgsRelationAddDlg( QWidget *parent ) { setupUi( this ); - connect( mCbxReferencingLayer, &QgsMapLayerComboBox::layerChanged, this, [=]( QgsMapLayer * layer ) { mCbxReferencingField->setLayer( layer ); } - ); - connect( mCbxReferencedLayer, &QgsMapLayerComboBox::layerChanged, this, [=]( QgsMapLayer * layer ) { mCbxReferencedField->setLayer( layer ); } - ); + connect( mCbxReferencingLayer, &QgsMapLayerComboBox::layerChanged, mCbxReferencingField, &QgsFieldComboBox::setLayer ); + connect( mCbxReferencedLayer, &QgsMapLayerComboBox::layerChanged, mCbxReferencedField, &QgsFieldComboBox::setLayer ); mCbxReferencingLayer->setFilters( QgsMapLayerProxyModel::VectorLayer ); mCbxReferencingField->setLayer( mCbxReferencingLayer->currentLayer() ); diff --git a/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp b/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp index 7bbe41d0a32c..a32d5dc6151c 100644 --- a/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp +++ b/src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp @@ -23,8 +23,8 @@ QgsValueRelationConfigDlg::QgsValueRelationConfigDlg( QgsVectorLayer* vl, int fi { setupUi( this ); mLayerName->setFilters( QgsMapLayerProxyModel::VectorLayer ); - connect( mLayerName, SIGNAL( layerChanged( QgsMapLayer* ) ), mKeyColumn, SLOT( setLayer( QgsMapLayer* ) ) ); - connect( mLayerName, SIGNAL( layerChanged( QgsMapLayer* ) ), mValueColumn, SLOT( setLayer( QgsMapLayer* ) ) ); + connect( mLayerName, &QgsMapLayerComboBox::layerChanged, mKeyColumn, &QgsFieldComboBox::setLayer ); + connect( mLayerName, &QgsMapLayerComboBox::layerChanged, mValueColumn, &QgsFieldComboBox::setLayer ); connect( mEditExpression, SIGNAL( clicked() ), this, SLOT( editExpression() ) ); connect( mLayerName, SIGNAL( layerChanged( QgsMapLayer* ) ), this, SIGNAL( changed() ) ); diff --git a/src/gui/qgsfieldcombobox.cpp b/src/gui/qgsfieldcombobox.cpp index 79f635f54c19..675dd23fc87d 100644 --- a/src/gui/qgsfieldcombobox.cpp +++ b/src/gui/qgsfieldcombobox.cpp @@ -45,16 +45,8 @@ bool QgsFieldComboBox::allowEmptyFieldName() const void QgsFieldComboBox::setLayer( QgsMapLayer *layer ) { - QgsVectorLayer* vl = dynamic_cast( layer ); - if ( vl ) - { - setLayer( vl ); - } -} - -void QgsFieldComboBox::setLayer( QgsVectorLayer *layer ) -{ - mFieldProxyModel->sourceFieldModel()->setLayer( layer ); + QgsVectorLayer* vl = qobject_cast( layer ); + mFieldProxyModel->sourceFieldModel()->setLayer( vl ); } QgsVectorLayer *QgsFieldComboBox::layer() const diff --git a/src/gui/qgsfieldcombobox.h b/src/gui/qgsfieldcombobox.h index 804309116ce6..0b25395236ce 100644 --- a/src/gui/qgsfieldcombobox.h +++ b/src/gui/qgsfieldcombobox.h @@ -68,7 +68,10 @@ class GUI_EXPORT QgsFieldComboBox : public QComboBox //! return the currently selected field QString currentField() const; - //! Returns the currently used layer + /** + * Returns the layer currently associated with the combobox. + * @see setLayer() + */ QgsVectorLayer* layer() const; signals: @@ -76,10 +79,12 @@ class GUI_EXPORT QgsFieldComboBox : public QComboBox void fieldChanged( const QString& fieldName ); public slots: - //! set the layer of which the fields are listed - void setLayer( QgsVectorLayer* layer ); - //! convenience slot to connect QgsMapLayerComboBox layer signal + /** + * Sets the layer for which fields are listed in the combobox. If no layer is set + * or a non-vector layer is set then the combobox will be empty. + * @see layer() + */ void setLayer( QgsMapLayer* layer ); //! setField sets the currently selected field diff --git a/src/gui/qgsfieldexpressionwidget.cpp b/src/gui/qgsfieldexpressionwidget.cpp index 1984e2fae043..c2aa7e732818 100644 --- a/src/gui/qgsfieldexpressionwidget.cpp +++ b/src/gui/qgsfieldexpressionwidget.cpp @@ -154,24 +154,17 @@ void QgsFieldExpressionWidget::registerExpressionContextGenerator( const QgsExpr void QgsFieldExpressionWidget::setLayer( QgsMapLayer *layer ) { - QgsVectorLayer* vl = dynamic_cast( layer ); - if ( vl ) - { - setLayer( vl ); - } -} + QgsVectorLayer* vl = qobject_cast< QgsVectorLayer* >( layer ); -void QgsFieldExpressionWidget::setLayer( QgsVectorLayer *layer ) -{ if ( mFieldProxyModel->sourceFieldModel()->layer() ) disconnect( mFieldProxyModel->sourceFieldModel()->layer(), SIGNAL( updatedFields() ), this, SLOT( reloadLayer() ) ); - if ( layer ) - mExpressionContext = layer->createExpressionContext(); + if ( vl ) + mExpressionContext = vl->createExpressionContext(); else mExpressionContext = QgsProject::instance()->createExpressionContext(); - mFieldProxyModel->sourceFieldModel()->setLayer( layer ); + mFieldProxyModel->sourceFieldModel()->setLayer( vl ); if ( mFieldProxyModel->sourceFieldModel()->layer() ) connect( mFieldProxyModel->sourceFieldModel()->layer(), SIGNAL( updatedFields() ), SLOT( reloadLayer() ), Qt::UniqueConnection ); diff --git a/src/gui/qgsfieldexpressionwidget.h b/src/gui/qgsfieldexpressionwidget.h index e7afdb43e401..480fa6e4a325 100644 --- a/src/gui/qgsfieldexpressionwidget.h +++ b/src/gui/qgsfieldexpressionwidget.h @@ -111,7 +111,10 @@ class GUI_EXPORT QgsFieldExpressionWidget : public QWidget */ QString expression() const; - //! Returns the currently used layer + /** + * Returns the layer currently associated with the widget. + * @see setLayer() + */ QgsVectorLayer* layer() const; /** @@ -133,10 +136,11 @@ class GUI_EXPORT QgsFieldExpressionWidget : public QWidget // void returnPressed(); public slots: - //! set the layer used to display the fields and expression - void setLayer( QgsVectorLayer* layer ); - //! convenience slot to connect QgsMapLayerComboBox layer signal + /** + * Sets the layer used to display the fields and expression. + * @see layer() + */ void setLayer( QgsMapLayer* layer ); //! sets the current row in the widget diff --git a/src/gui/qgsorderbydialog.cpp b/src/gui/qgsorderbydialog.cpp index 7c6b78cfaaf1..330baef6c2c2 100644 --- a/src/gui/qgsorderbydialog.cpp +++ b/src/gui/qgsorderbydialog.cpp @@ -18,6 +18,7 @@ #include "qgsexpressionbuilderdialog.h" #include "qgsfieldexpressionwidget.h" +#include "qgsvectorlayer.h" #include #include diff --git a/src/plugins/heatmap/heatmapgui.cpp b/src/plugins/heatmap/heatmapgui.cpp index 99a5e55e1b70..db72ff97cf0b 100644 --- a/src/plugins/heatmap/heatmapgui.cpp +++ b/src/plugins/heatmap/heatmapgui.cpp @@ -71,8 +71,8 @@ HeatmapGui::HeatmapGui( QWidget* parent, Qt::WindowFlags fl, QMapsetFilters( QgsFieldProxyModel::Numeric ); mWeightFieldCombo->setFilters( QgsFieldProxyModel::Numeric ); - connect( mInputLayerCombo, SIGNAL( layerChanged( QgsMapLayer* ) ), mRadiusFieldCombo, SLOT( setLayer( QgsMapLayer* ) ) ); - connect( mInputLayerCombo, SIGNAL( layerChanged( QgsMapLayer* ) ), mWeightFieldCombo, SLOT( setLayer( QgsMapLayer* ) ) ); + connect( mInputLayerCombo, &QgsMapLayerComboBox::layerChanged, mRadiusFieldCombo, &QgsFieldComboBox::setLayer ); + connect( mInputLayerCombo, &QgsMapLayerComboBox::layerChanged, mWeightFieldCombo, &QgsFieldComboBox::setLayer ); mRadiusFieldCombo->setLayer( mInputLayerCombo->currentLayer() ); mWeightFieldCombo->setLayer( mInputLayerCombo->currentLayer() ); From 271e67e37b781260d889778e97064efae72a0b15 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 22 Nov 2016 09:57:50 +1000 Subject: [PATCH 861/897] [processing] Fix import to postgis alg when table name not set (fix #15869, 15097) --- python/plugins/processing/algs/qgis/ImportIntoPostGIS.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py b/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py index 062211cc22f5..96e76ce28030 100644 --- a/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py +++ b/python/plugins/processing/algs/qgis/ImportIntoPostGIS.py @@ -105,7 +105,7 @@ def processAlgorithm(self, progress): table.strip() if not table or table == '': table = layer.name() - table = "_".join(table.split(".")[:-1]) + table = table.replace('.', '_') table = table.replace(' ', '').lower()[0:62] providerName = 'postgres' From 188033a6afc298864860ba94a3f150dd5e23f86d Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 22 Nov 2016 10:08:14 +1000 Subject: [PATCH 862/897] [FEATURE] Expression variables for project CRS Adds @project_crs and @project_crs_definition variables for retrieving the current project CRS --- src/core/qgsexpression.cpp | 2 ++ src/core/qgsexpressioncontext.cpp | 3 +++ 2 files changed, 5 insertions(+) diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index fc183e5c34cd..f44629b6ed80 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -5712,6 +5712,8 @@ void QgsExpression::initVariableHelp() gVariableHelpTexts.insert( QStringLiteral( "project_path" ), QCoreApplication::translate( "variable_help", "Full path (including file name) of current project." ) ); gVariableHelpTexts.insert( QStringLiteral( "project_folder" ), QCoreApplication::translate( "variable_help", "Folder for current project." ) ); gVariableHelpTexts.insert( QStringLiteral( "project_filename" ), QCoreApplication::translate( "variable_help", "Filename of current project." ) ); + gVariableHelpTexts.insert( QStringLiteral( "project_crs" ), QCoreApplication::translate( "variable_help", "Coordinate reference system of project (eg 'EPSG:4326')." ) ); + gVariableHelpTexts.insert( QStringLiteral( "project_crs_definition" ), QCoreApplication::translate( "variable_help", "Coordinate reference system of project (full definition)." ) ); //layer variables gVariableHelpTexts.insert( QStringLiteral( "layer_name" ), QCoreApplication::translate( "variable_help", "Name of current layer." ) ); diff --git a/src/core/qgsexpressioncontext.cpp b/src/core/qgsexpressioncontext.cpp index 4e91e08ba05d..91ea5ee44ba3 100644 --- a/src/core/qgsexpressioncontext.cpp +++ b/src/core/qgsexpressioncontext.cpp @@ -644,6 +644,9 @@ QgsExpressionContextScope* QgsExpressionContextUtils::projectScope() scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_path" ), project->fileInfo().filePath(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_folder" ), project->fileInfo().dir().path(), true ) ); scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_filename" ), project->fileInfo().fileName(), true ) ); + QgsCoordinateReferenceSystem projectCrs = project->crs(); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_crs" ), projectCrs.authid(), true ) ); + scope->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "project_crs_definition" ), projectCrs.toProj4(), true ) ); scope->addFunction( QStringLiteral( "project_color" ), new GetNamedProjectColor() ); return scope; From e5f62e49ce3fd617385a3e4290dd9172c691bf0f Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Mon, 21 Nov 2016 23:43:30 +0800 Subject: [PATCH 863/897] Remove legacy QgsLegendInterface, move still valid methods to QgisInterface --- doc/api_break.dox | 5 + python/gui/gui.sip | 1 - python/gui/qgisinterface.sip | 29 +- python/gui/qgslegendinterface.sip | 118 ------ src/app/CMakeLists.txt | 4 - src/app/legend/qgsapplegendinterface.cpp | 369 ------------------ src/app/legend/qgsapplegendinterface.h | 122 ------ src/app/qgisappinterface.cpp | 35 +- src/app/qgisappinterface.h | 11 +- src/app/qgsapplayertreeviewmenuprovider.cpp | 4 +- src/app/qgsapplayertreeviewmenuprovider.h | 6 +- src/gui/CMakeLists.txt | 2 - src/gui/qgisinterface.h | 31 +- src/gui/qgslegendinterface.cpp | 26 -- src/gui/qgslegendinterface.h | 152 -------- .../georeferencer/qgsgeorefplugingui.cpp | 1 - 16 files changed, 96 insertions(+), 820 deletions(-) delete mode 100644 python/gui/qgslegendinterface.sip delete mode 100644 src/app/legend/qgsapplegendinterface.cpp delete mode 100644 src/app/legend/qgsapplegendinterface.h delete mode 100644 src/gui/qgslegendinterface.cpp delete mode 100644 src/gui/qgslegendinterface.h diff --git a/doc/api_break.dox b/doc/api_break.dox index 21a95ea4a0df..de55e62ca598 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -240,6 +240,11 @@ so there is no longer a need for the separate cache class. Code which previously should now call QgsCoordinateReferenceSystem::invalidateCache() and QgsCoordinateTransformCache::instance()->invalidateCrs( authid ). - QgsHttpTransaction. This class was outdated and code should be ported to native Qt or Python implementations. - QgsLabel and QgsLabelAttributes. Replaced by labeling based on PAL library, see QgsLabelingEngineV2. +- QgsLegendInterface was removed. It was replaced by layer tree API (QgsLayerTreeNode class and others). + Methods that deal with custom actions in main window's layer tree context menu were moved to QgisInterface: + - addLegendLayerAction() moved to QgisInterface::addCustomActionForLayerType() + - addLegendLayerActionForLayer() moved to QgisInterface::addCustomActionForLayer() + - removeLegendLayerAction() moved to QgisInterface::removeCustomActionForLayerType() - QgsLegendModel was removed. - QgsMapCanvasMap. It is an internal class used by map canvas. - QgsMapRenderer. It has been replaced by QgsMapRendererJob with subclasses and QgsMapSettings. diff --git a/python/gui/gui.sip b/python/gui/gui.sip index 4396df54e716..8eb045683f97 100644 --- a/python/gui/gui.sip +++ b/python/gui/gui.sip @@ -93,7 +93,6 @@ %Include qgskeyvaluewidget.sip %Include qgslistwidget.sip %Include qgslegendfilterbutton.sip -%Include qgslegendinterface.sip %Include qgslimitedrandomcolorrampdialog.sip %Include qgslonglongvalidator.sip %Include qgsludialog.sip diff --git a/python/gui/qgisinterface.sip b/python/gui/qgisinterface.sip index f2d3c4f874de..d77f758e4363 100644 --- a/python/gui/qgisinterface.sip +++ b/python/gui/qgisinterface.sip @@ -24,13 +24,36 @@ class QgisInterface : QObject /** Virtual destructor */ virtual ~QgisInterface(); - /** Get pointer to legend interface */ - virtual QgsLegendInterface* legendInterface() = 0; - virtual QgsPluginManagerInterface* pluginManagerInterface() = 0; virtual QgsLayerTreeView* layerTreeView() = 0; + /** Add action to context menu for layers in the layer tree. + * If allLayers is true, then the action will be available for all layers of given type, + * otherwise the action will be available only for specific layers added with addCustomActionForLayer() + * after this call. + * + * If menu argument is not empty, the action will be also added to a menu within the main window, + * creating menu with the given name if it does not exist yet. + * + * @see removeCustomActionForLayerType() + * @see addCustomActionForLayer() + */ + virtual void addCustomActionForLayerType( QAction* action, QString menu, + QgsMapLayer::LayerType type, bool allLayers ) = 0; + + /** Add action to context menu for a specific layer in the layer tree. + * It is necessary to first call addCustomActionForLayerType() with allLayers=false + * in order for this method to have any effect. + * @see addCustomActionForLayerType() + */ + virtual void addCustomActionForLayer( QAction* action, QgsMapLayer* layer ) = 0; + + /** Remove action for layers in the layer tree previously added with addCustomActionForLayerType() + * @see addCustomActionForLayerType() + */ + virtual bool removeCustomActionForLayerType( QAction* action ) = 0; + public slots: // TODO: do these functions really need to be slots? /* Exposed functions */ diff --git a/python/gui/qgslegendinterface.sip b/python/gui/qgslegendinterface.sip deleted file mode 100644 index 48181852dfb1..000000000000 --- a/python/gui/qgslegendinterface.sip +++ /dev/null @@ -1,118 +0,0 @@ -/** - * \class QgsLegendInterface - * \brief Abstract base class to make QgsLegend available to plugins. - */ -class QgsLegendInterface : QObject -{ -%TypeHeaderCode -#include -%End - - public: - - /** Constructor */ - QgsLegendInterface(); - - /** Virtual destructor */ - ~QgsLegendInterface(); - - //! Return a string list of groups - virtual QStringList groups() = 0; - - //! Return the relationship between groups and layers in the legend - virtual QList< QPair< QString, QList > > groupLayerRelationship(); - - //! Returns the currently selected layers of QgsLegendLayers. - //! @param inDrawOrder return layers in drawing order - //! @returns list of layers, else an empty list - virtual QList selectedLayers( bool inDrawOrder = false ) const = 0; - - //! Return all layers in the project in drawing order - virtual QList< QgsMapLayer * > layers() const = 0; - - //! Check if a group exists - virtual bool groupExists( int groupIndex ) = 0; - - //! Check if a group is expanded - virtual bool isGroupExpanded( int groupIndex ) = 0; - - //! Check if a group is visible - virtual bool isGroupVisible( int groupIndex ) = 0; - - //! Check if a layer is expanded - virtual bool isLayerExpanded( QgsMapLayer * ml ) = 0; - - //! Check if a layer is visible - virtual bool isLayerVisible( QgsMapLayer * ml ) = 0; - - /** Add action for layers in the legend */ - virtual void addLegendLayerAction( QAction* action, QString menu, QString id, - QgsMapLayer::LayerType type, bool allLayers ) = 0; - - /** Add action for a specific layers in the legend. - * Use this in combination with addLegendLayerAction( allLayers = False ) - */ - virtual void addLegendLayerActionForLayer( QAction* action, QgsMapLayer* layer ) = 0; - - /** Remove action for layers in the legend */ - virtual bool removeLegendLayerAction( QAction* action ) = 0; - - //! Returns the current layer if the current item is a QgsLegendLayer. - //! If the current item is a QgsLegendLayer, its first maplayer is returned. - //! Else, 0 is returned. - virtual QgsMapLayer* currentLayer() = 0; - - //! set the current layer - //! returns true if the layer exists, false otherwise - virtual bool setCurrentLayer( QgsMapLayer *layer ) = 0; - - signals: - - //! emitted when a group index has changed - void groupIndexChanged( int oldIndex, int newIndex ); - - /* //! emitted when group relations have changed */ - void groupRelationsChanged(); - - /* //! emitted when an item (group/layer) is added */ - void itemAdded( const QModelIndex& index ); - - /* //! emitted when an item (group/layer) is removed */ - void itemRemoved(); - - //! Emitted whenever current (selected) layer changes - // the pointer to layer can be null if no layer is selected - void currentLayerChanged( QgsMapLayer * layer ); - - public slots: - - //! Add a new group - //! a parent group can be given to nest the new group in it - virtual int addGroup( const QString& name, bool expand = true, QTreeWidgetItem* parent = 0 ) = 0; - - //! Add a new group - //! a parent group index has to be given to nest the new group in it - virtual int addGroup( const QString& name, bool expand, int parentIndex ) = 0; - - //! Remove group on index - virtual void removeGroup( int groupIndex ) = 0; - - //! Move a layer to a group - virtual void moveLayer( QgsMapLayer * ml, int groupIndex ) = 0; - - //! Collapse or expand a group - virtual void setGroupExpanded( int groupIndex, bool expand ) = 0; - - //! Collapse or expand a layer - virtual void setLayerExpanded( QgsMapLayer * ml, bool expand ) = 0; - - //! Set the visibility of a group - virtual void setGroupVisible( int groupIndex, bool visible ) = 0; - - //! Set the visibility of a layer - virtual void setLayerVisible( QgsMapLayer * ml, bool visible ) = 0; - - //! Refresh layer symbology - virtual void refreshLayerSymbology( QgsMapLayer *ml ) = 0; -}; - diff --git a/src/app/CMakeLists.txt b/src/app/CMakeLists.txt index 0c185ca42974..903e122d1637 100644 --- a/src/app/CMakeLists.txt +++ b/src/app/CMakeLists.txt @@ -151,8 +151,6 @@ SET(QGIS_APP_SRCS composer/qgscompositionwidget.cpp composer/qgsatlascompositionwidget.cpp - legend/qgsapplegendinterface.cpp - ogr/qgsogrhelperfunctions.cpp ogr/qgsopenvectorlayerdialog.cpp ogr/qgsnewogrconnection.cpp @@ -324,8 +322,6 @@ SET (QGIS_APP_MOC_HDRS composer/qgscompositionwidget.h composer/qgsatlascompositionwidget.h - legend/qgsapplegendinterface.h - ogr/qgsopenvectorlayerdialog.h ogr/qgsnewogrconnection.h ogr/qgsvectorlayersaveasdialog.h diff --git a/src/app/legend/qgsapplegendinterface.cpp b/src/app/legend/qgsapplegendinterface.cpp deleted file mode 100644 index c89a7949c360..000000000000 --- a/src/app/legend/qgsapplegendinterface.cpp +++ /dev/null @@ -1,369 +0,0 @@ -/*************************************************************************** - qgsapplegendinterface.cpp - -------------------------------------- - Date : 19-Nov-2009 - Copyright : (C) 2009 by Andres Manz - Email : manz dot andres at gmail dot com -****************************************************************************/ -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgsapplegendinterface.h" - -#include "qgsapplayertreeviewmenuprovider.h" -#include "qgslayertree.h" -#include "qgslayertreemodel.h" -#include "qgslayertreeview.h" -#include "qgsmaplayer.h" -#include "qgsproject.h" -#include "qgslayertreeregistrybridge.h" - - -QgsAppLegendInterface::QgsAppLegendInterface( QgsLayerTreeView * layerTreeView ) - : mLayerTreeView( layerTreeView ) -{ - connect( layerTreeView->layerTreeModel()->rootGroup(), SIGNAL( addedChildren( QgsLayerTreeNode*, int, int ) ), this, SLOT( onAddedChildren( QgsLayerTreeNode*, int, int ) ) ); - connect( layerTreeView->layerTreeModel()->rootGroup(), SIGNAL( removedChildren( QgsLayerTreeNode*, int, int ) ), this, SLOT( onRemovedChildren() ) ); - connect( layerTreeView, SIGNAL( currentLayerChanged( QgsMapLayer * ) ), this, SIGNAL( currentLayerChanged( QgsMapLayer * ) ) ); -} - -QgsAppLegendInterface::~QgsAppLegendInterface() -{ -} - -int QgsAppLegendInterface::addGroup( const QString& name, bool expand, QTreeWidgetItem* parent ) -{ - if ( parent ) - return -1; - - return addGroup( name, expand, -1 ); -} - -void QgsAppLegendInterface::setExpanded( QgsLayerTreeNode *node, bool expand ) -{ - QModelIndex idx = mLayerTreeView->layerTreeModel()->node2index( node ); - if ( expand ) - mLayerTreeView->expand( idx ); - else - mLayerTreeView->collapse( idx ); -} - -int QgsAppLegendInterface::addGroup( const QString& name, bool expand, int parentIndex ) -{ - QgsLayerTreeGroup* parentGroup = parentIndex == -1 ? mLayerTreeView->layerTreeModel()->rootGroup() : groupIndexToNode( parentIndex ); - if ( !parentGroup ) - return -1; - - QgsLayerTreeGroup* group = parentGroup->addGroup( name ); - setExpanded( group, expand ); - return groupNodeToIndex( group ); -} - -void QgsAppLegendInterface::removeGroup( int groupIndex ) -{ - QgsLayerTreeGroup* group = groupIndexToNode( groupIndex ); - if ( !group || !QgsLayerTree::isGroup( group->parent() ) ) - return; - - QgsLayerTreeGroup* parentGroup = QgsLayerTree::toGroup( group->parent() ); - parentGroup->removeChildNode( group ); -} - -void QgsAppLegendInterface::moveLayer( QgsMapLayer *ml, int groupIndex ) -{ - if ( !ml ) - return; - - QgsLayerTreeGroup* group = groupIndexToNode( groupIndex ); - if ( !group ) - return; - - QgsLayerTreeLayer* nodeLayer = mLayerTreeView->layerTreeModel()->rootGroup()->findLayer( ml->id() ); - if ( !nodeLayer || !QgsLayerTree::isGroup( nodeLayer->parent() ) ) - return; - - group->insertChildNode( 0, nodeLayer->clone() ); - - QgsLayerTreeGroup* nodeLayerParentGroup = QgsLayerTree::toGroup( nodeLayer->parent() ); - nodeLayerParentGroup->removeChildNode( nodeLayer ); -} - -void QgsAppLegendInterface::setGroupExpanded( int groupIndex, bool expand ) -{ - if ( QgsLayerTreeGroup* group = groupIndexToNode( groupIndex ) ) - setExpanded( group, expand ); -} - -void QgsAppLegendInterface::setGroupVisible( int groupIndex, bool visible ) -{ - if ( QgsLayerTreeGroup* group = groupIndexToNode( groupIndex ) ) - group->setVisible( visible ? Qt::Checked : Qt::Unchecked ); -} - - -static QgsLayerTreeGroup* _groupIndexToNode( int groupIndex, QgsLayerTreeGroup* parentGroup, int& currentIndex ) -{ - ++currentIndex; - Q_FOREACH ( QgsLayerTreeNode* child, parentGroup->children() ) - { - if ( QgsLayerTree::isGroup( child ) ) - { - if ( currentIndex == groupIndex ) - return QgsLayerTree::toGroup( child ); - - if ( QgsLayerTreeGroup* res = _groupIndexToNode( groupIndex, QgsLayerTree::toGroup( child ), currentIndex ) ) - return res; - } - } - - return nullptr; -} - -QgsLayerTreeGroup* QgsAppLegendInterface::groupIndexToNode( int itemIndex ) -{ - int currentIndex = -1; - return _groupIndexToNode( itemIndex, mLayerTreeView->layerTreeModel()->rootGroup(), currentIndex ); -} - - -static int _groupNodeToIndex( QgsLayerTreeGroup* group, QgsLayerTreeGroup* parentGroup, int& currentIndex ) -{ - ++currentIndex; - Q_FOREACH ( QgsLayerTreeNode* child, parentGroup->children() ) - { - if ( QgsLayerTree::isGroup( child ) ) - { - QgsLayerTreeGroup* childGroup = QgsLayerTree::toGroup( child ); - if ( childGroup == group ) - return currentIndex; - - int res = _groupNodeToIndex( group, childGroup, currentIndex ); - if ( res != -1 ) - return res; - } - } - - return -1; -} - -int QgsAppLegendInterface::groupNodeToIndex( QgsLayerTreeGroup* group ) -{ - int currentIndex = -1; - return _groupNodeToIndex( group, mLayerTreeView->layerTreeModel()->rootGroup(), currentIndex ); -} - -void QgsAppLegendInterface::setLayerVisible( QgsMapLayer *ml, bool visible ) -{ - if ( !ml ) - return; - - if ( QgsLayerTreeLayer* nodeLayer = mLayerTreeView->layerTreeModel()->rootGroup()->findLayer( ml->id() ) ) - nodeLayer->setVisible( visible ? Qt::Checked : Qt::Unchecked ); -} - -void QgsAppLegendInterface::setLayerExpanded( QgsMapLayer * ml, bool expand ) -{ - if ( !ml ) - return; - - if ( QgsLayerTreeLayer* nodeLayer = mLayerTreeView->layerTreeModel()->rootGroup()->findLayer( ml->id() ) ) - setExpanded( nodeLayer, expand ); -} - -static void _collectGroups( QgsLayerTreeGroup* parentGroup, QStringList& list ) -{ - Q_FOREACH ( QgsLayerTreeNode* child, parentGroup->children() ) - { - if ( QgsLayerTree::isGroup( child ) ) - { - QgsLayerTreeGroup* childGroup = QgsLayerTree::toGroup( child ); - list << childGroup->name(); - - _collectGroups( childGroup, list ); - } - } -} - -QStringList QgsAppLegendInterface::groups() -{ - QStringList list; - _collectGroups( mLayerTreeView->layerTreeModel()->rootGroup(), list ); - return list; -} - -QList< GroupLayerInfo > QgsAppLegendInterface::groupLayerRelationship() -{ - QList< GroupLayerInfo > groupLayerList; - QList< QgsLayerTreeNode* > nodes = mLayerTreeView->layerTreeModel()->rootGroup()->children(); - - while ( !nodes.isEmpty() ) - { - QgsLayerTreeNode* currentNode = nodes.takeFirst(); - - if ( QgsLayerTree::isLayer( currentNode ) ) - { - QList layerList; - layerList.push_back( QgsLayerTree::toLayer( currentNode )->layerId() ); - groupLayerList.push_back( qMakePair( QString(), layerList ) ); - } - else if ( QgsLayerTree::isGroup( currentNode ) ) - { - QList layerList; - Q_FOREACH ( QgsLayerTreeNode* gNode, QgsLayerTree::toGroup( currentNode )->children() ) - { - if ( QgsLayerTree::isLayer( gNode ) ) - { - layerList.push_back( QgsLayerTree::toLayer( gNode )->layerId() ); - } - else if ( QgsLayerTree::isGroup( gNode ) ) - { - layerList << QgsLayerTree::toGroup( gNode )->name(); - nodes << gNode; - } - } - - groupLayerList.push_back( qMakePair( QgsLayerTree::toGroup( currentNode )->name(), layerList ) ); - } - } - - return groupLayerList; -} - -bool QgsAppLegendInterface::groupExists( int groupIndex ) -{ - return nullptr != groupIndexToNode( groupIndex ); -} - -bool QgsAppLegendInterface::isGroupExpanded( int groupIndex ) -{ - if ( QgsLayerTreeGroup* group = groupIndexToNode( groupIndex ) ) - return group->isExpanded(); - - return false; -} - -bool QgsAppLegendInterface::isGroupVisible( int groupIndex ) -{ - if ( QgsLayerTreeGroup* group = groupIndexToNode( groupIndex ) ) - return group->isVisible() == Qt::Checked; - - return false; -} - -bool QgsAppLegendInterface::isLayerExpanded( QgsMapLayer *ml ) -{ - if ( !ml ) - return false; - - if ( QgsLayerTreeLayer* nodeLayer = mLayerTreeView->layerTreeModel()->rootGroup()->findLayer( ml->id() ) ) - return nodeLayer->isExpanded(); - - return false; -} - - -bool QgsAppLegendInterface::isLayerVisible( QgsMapLayer *ml ) -{ - if ( !ml ) - return false; - - if ( QgsLayerTreeLayer* nodeLayer = mLayerTreeView->layerTreeModel()->rootGroup()->findLayer( ml->id() ) ) - return nodeLayer->isVisible() == Qt::Checked; - - return false; -} - -QList QgsAppLegendInterface::selectedLayers( bool inDrawOrder ) const -{ - Q_UNUSED( inDrawOrder ); // TODO[MD] - return mLayerTreeView->selectedLayers(); -} - -QList< QgsMapLayer * > QgsAppLegendInterface::layers() const -{ - QList lst; - Q_FOREACH ( QgsLayerTreeLayer* node, mLayerTreeView->layerTreeModel()->rootGroup()->findLayers() ) - { - if ( node->layer() ) - lst << node->layer(); - } - return lst; -} - -void QgsAppLegendInterface::refreshLayerSymbology( QgsMapLayer *ml ) -{ - if ( !ml ) - return; - - mLayerTreeView->refreshLayerSymbology( ml->id() ); -} - -void QgsAppLegendInterface::onAddedChildren( QgsLayerTreeNode* node, int indexFrom, int indexTo ) -{ - emit groupRelationsChanged(); - - for ( int i = indexFrom; i <= indexTo; ++i ) - { - QgsLayerTreeNode* child = node->children().at( i ); - emit itemAdded( mLayerTreeView->layerTreeModel()->node2index( child ) ); - - // also notify about all children - if ( QgsLayerTree::isGroup( child ) && !child->children().isEmpty() ) - onAddedChildren( child, 0, child->children().count() - 1 ); - } -} - -void QgsAppLegendInterface::onRemovedChildren() -{ - emit groupRelationsChanged(); - - emit itemRemoved(); -} - -void QgsAppLegendInterface::addLegendLayerAction( QAction* action, - QString menu, QString id, QgsMapLayer::LayerType type, bool allLayers ) -{ - QgsAppLayerTreeViewMenuProvider* menuProvider = dynamic_cast( mLayerTreeView->menuProvider() ); - if ( !menuProvider ) - return; - - menuProvider->addLegendLayerAction( action, menu, id, type, allLayers ); -} - -void QgsAppLegendInterface::addLegendLayerActionForLayer( QAction* action, QgsMapLayer* layer ) -{ - QgsAppLayerTreeViewMenuProvider* menuProvider = dynamic_cast( mLayerTreeView->menuProvider() ); - if ( !menuProvider ) - return; - - menuProvider->addLegendLayerActionForLayer( action, layer ); -} - -bool QgsAppLegendInterface::removeLegendLayerAction( QAction* action ) -{ - QgsAppLayerTreeViewMenuProvider* menuProvider = dynamic_cast( mLayerTreeView->menuProvider() ); - if ( !menuProvider ) - return false; - - return menuProvider->removeLegendLayerAction( action ); -} - -QgsMapLayer* QgsAppLegendInterface::currentLayer() -{ - return mLayerTreeView->currentLayer(); -} - -bool QgsAppLegendInterface::setCurrentLayer( QgsMapLayer *layer ) -{ - if ( !mLayerTreeView->layerTreeModel()->rootGroup()->findLayer( layer->id() ) ) - return false; - - mLayerTreeView->setCurrentLayer( layer ); - return true; -} diff --git a/src/app/legend/qgsapplegendinterface.h b/src/app/legend/qgsapplegendinterface.h deleted file mode 100644 index 481e1c0f8c04..000000000000 --- a/src/app/legend/qgsapplegendinterface.h +++ /dev/null @@ -1,122 +0,0 @@ -/*************************************************************************** - qgsapplegendinterface.h - -------------------------------------- - Date : 23-Nov-2009 - Copyright : (C) 2009 by Andres Manz - Email : manz dot andres at gmail dot com -****************************************************************************/ -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGSLEGENDAPPIFACE_H -#define QGSLEGENDAPPIFACE_H - -#include "qgslegendinterface.h" - -#include - -class QgsLayerTreeGroup; -class QgsLayerTreeNode; -class QgsLayerTreeView; -class QgsMapLayer; - -/** \ingroup gui - * QgsLegendInterface - * Abstract base class to make QgsLegend available to plugins. - */ - -class QgsAppLegendInterface : public QgsLegendInterface -{ - Q_OBJECT - - public: - - //! Constructor - explicit QgsAppLegendInterface( QgsLayerTreeView * layerTreeView ); - - //! Destructor - ~QgsAppLegendInterface(); - - //! Return a string list of groups - QStringList groups() override; - - //! Return the relationship between groups and layers in the legend - QList< GroupLayerInfo > groupLayerRelationship() override; - - //! Returns the currently selected layers of QgsLegendLayers. - QList selectedLayers( bool inDrawOrder = false ) const override; - - //! Return all layers in the project in drawing order - QList< QgsMapLayer * > layers() const override; - - //! Check if a group exists - bool groupExists( int groupIndex ) override; - - //! Check if a group is expanded - bool isGroupExpanded( int groupIndex ) override; - - //! Check if a group is visible - bool isGroupVisible( int groupIndex ) override; - - //! Check if a layer is expanded - bool isLayerExpanded( QgsMapLayer * ml ) override; - - //! Check if a layer is visible - bool isLayerVisible( QgsMapLayer * ml ) override; - - void addLegendLayerAction( QAction* action, QString menu, QString id, - QgsMapLayer::LayerType type, bool allLayers ) override; - void addLegendLayerActionForLayer( QAction* action, QgsMapLayer* layer ) override; - bool removeLegendLayerAction( QAction* action ) override; - - QgsMapLayer* currentLayer() override; - bool setCurrentLayer( QgsMapLayer *layer ) override; - - public slots: - - //! Add a new group - int addGroup( const QString& name, bool expand = true, QTreeWidgetItem* parent = nullptr ) override; - - //! Add a new group at a specified index - int addGroup( const QString& name, bool expand, int groupIndex ) override; - - //! Remove all groups with the given name - void removeGroup( int groupIndex ) override; - - //! Move a layer to a group - void moveLayer( QgsMapLayer *ml, int groupIndex ) override; - - //! Collapse or expand a group - virtual void setGroupExpanded( int groupIndex, bool expand ) override; - - //! Collapse or expand a layer - virtual void setLayerExpanded( QgsMapLayer * ml, bool expand ) override; - - //! Set the visibility of a group - virtual void setGroupVisible( int groupIndex, bool visible ) override; - - //! Set the visibility of a layer - virtual void setLayerVisible( QgsMapLayer * ml, bool visible ) override; - - //! refresh layer symbology - void refreshLayerSymbology( QgsMapLayer *ml ) override; - - protected slots: - void onAddedChildren( QgsLayerTreeNode* node, int indexFrom, int indexTo ); - void onRemovedChildren(); - - private: - //! Pointer to QgsLegend object - QgsLayerTreeView* mLayerTreeView; - QgsLayerTreeGroup* groupIndexToNode( int itemIndex ); - int groupNodeToIndex( QgsLayerTreeGroup* group ); - void setExpanded( QgsLayerTreeNode *node, bool expand ); -}; - -#endif //QGSLEGENDAPPIFACE_H diff --git a/src/app/qgisappinterface.cpp b/src/app/qgisappinterface.cpp index 65ce369dec39..dfa6d0f06a4a 100644 --- a/src/app/qgisappinterface.cpp +++ b/src/app/qgisappinterface.cpp @@ -28,6 +28,7 @@ #include "qgisappinterface.h" #include "qgisappstylesheet.h" #include "qgisapp.h" +#include "qgsapplayertreeviewmenuprovider.h" #include "qgscomposer.h" #include "qgscomposerview.h" #include "qgsmaplayer.h" @@ -48,7 +49,6 @@ QgisAppInterface::QgisAppInterface( QgisApp * _qgis ) : qgis( _qgis ) , mTimer( nullptr ) - , legendIface( _qgis->layerTreeView() ) , pluginManagerIface( _qgis->pluginManager() ) { // connect signals @@ -76,11 +76,6 @@ QgisAppInterface::~QgisAppInterface() { } -QgsLegendInterface* QgisAppInterface::legendInterface() -{ - return &legendIface; -} - QgsPluginManagerInterface* QgisAppInterface::pluginManagerInterface() { return &pluginManagerIface; @@ -91,6 +86,34 @@ QgsLayerTreeView*QgisAppInterface::layerTreeView() return qgis->layerTreeView(); } +void QgisAppInterface::addCustomActionForLayerType( QAction* action, + QString menu, QgsMapLayer::LayerType type, bool allLayers ) +{ + QgsAppLayerTreeViewMenuProvider* menuProvider = dynamic_cast( qgis->layerTreeView()->menuProvider() ); + if ( !menuProvider ) + return; + + menuProvider->addLegendLayerAction( action, menu, type, allLayers ); +} + +void QgisAppInterface::addCustomActionForLayer( QAction* action, QgsMapLayer* layer ) +{ + QgsAppLayerTreeViewMenuProvider* menuProvider = dynamic_cast( qgis->layerTreeView()->menuProvider() ); + if ( !menuProvider ) + return; + + menuProvider->addLegendLayerActionForLayer( action, layer ); +} + +bool QgisAppInterface::removeCustomActionForLayerType( QAction* action ) +{ + QgsAppLayerTreeViewMenuProvider* menuProvider = dynamic_cast( qgis->layerTreeView()->menuProvider() ); + if ( !menuProvider ) + return false; + + return menuProvider->removeLegendLayerAction( action ); +} + void QgisAppInterface::zoomFull() { qgis->zoomFull(); diff --git a/src/app/qgisappinterface.h b/src/app/qgisappinterface.h index df3f9cdfe26d..02de57d0d6d2 100644 --- a/src/app/qgisappinterface.h +++ b/src/app/qgisappinterface.h @@ -19,7 +19,6 @@ #define QGISIFACE_H #include "qgisinterface.h" -#include "qgsapplegendinterface.h" #include "qgsapppluginmanagerinterface.h" class QgisApp; @@ -46,12 +45,15 @@ class APP_EXPORT QgisAppInterface : public QgisInterface QgisAppInterface( QgisApp *qgisapp ); ~QgisAppInterface(); - QgsLegendInterface* legendInterface() override; - QgsPluginManagerInterface* pluginManagerInterface() override; QgsLayerTreeView* layerTreeView() override; + virtual void addCustomActionForLayerType( QAction* action, QString menu, + QgsMapLayer::LayerType type, bool allLayers ) override; + virtual void addCustomActionForLayer( QAction* action, QgsMapLayer* layer ) override; + virtual bool removeCustomActionForLayerType( QAction* action ) override; + /* Exposed functions */ //! Zoom map to full extent @@ -532,9 +534,6 @@ class APP_EXPORT QgisAppInterface : public QgisInterface QTimer *mTimer; - //! Pointer to the LegendInterface object - QgsAppLegendInterface legendIface; - //! Pointer to the PluginManagerInterface object QgsAppPluginManagerInterface pluginManagerIface; }; diff --git a/src/app/qgsapplayertreeviewmenuprovider.cpp b/src/app/qgsapplayertreeviewmenuprovider.cpp index 24a498c8652d..1938622ba5cf 100644 --- a/src/app/qgsapplayertreeviewmenuprovider.cpp +++ b/src/app/qgsapplayertreeviewmenuprovider.cpp @@ -333,10 +333,10 @@ QMenu* QgsAppLayerTreeViewMenuProvider::createContextMenu() -void QgsAppLayerTreeViewMenuProvider::addLegendLayerAction( QAction* action, const QString& menu, const QString& id, +void QgsAppLayerTreeViewMenuProvider::addLegendLayerAction( QAction* action, const QString& menu, QgsMapLayer::LayerType type, bool allLayers ) { - mLegendLayerActionMap[type].append( LegendLayerAction( action, menu, id, allLayers ) ); + mLegendLayerActionMap[type].append( LegendLayerAction( action, menu, allLayers ) ); } bool QgsAppLayerTreeViewMenuProvider::removeLegendLayerAction( QAction* action ) diff --git a/src/app/qgsapplayertreeviewmenuprovider.h b/src/app/qgsapplayertreeviewmenuprovider.h index 219f70fd66bd..504bdb342c54 100644 --- a/src/app/qgsapplayertreeviewmenuprovider.h +++ b/src/app/qgsapplayertreeviewmenuprovider.h @@ -24,15 +24,13 @@ class QAction; struct LegendLayerAction { - LegendLayerAction( QAction* a, const QString& m, const QString& i, bool all ) + LegendLayerAction( QAction* a, const QString& m, bool all ) : action( a ) , menu( m ) - , id( i ) , allLayers( all ) {} QAction* action; QString menu; - QString id; bool allLayers; QList layers; }; @@ -47,7 +45,7 @@ class QgsAppLayerTreeViewMenuProvider : public QObject, public QgsLayerTreeViewM QMenu* createContextMenu() override; - void addLegendLayerAction( QAction* action, const QString& menu, const QString& id, + void addLegendLayerAction( QAction* action, const QString& menu, QgsMapLayer::LayerType type, bool allLayers ); bool removeLegendLayerAction( QAction* action ); void addLegendLayerActionForLayer( QAction* action, QgsMapLayer* layer ); diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index 4f91772b43c1..51788b45a749 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -240,7 +240,6 @@ SET(QGIS_GUI_SRCS qgskeyvaluewidget.cpp qgslistwidget.cpp qgslegendfilterbutton.cpp - qgslegendinterface.cpp qgslimitedrandomcolorrampdialog.cpp qgsludialog.cpp qgsmanageconnectionsdialog.cpp @@ -404,7 +403,6 @@ SET(QGIS_GUI_MOC_HDRS qgskeyvaluewidget.h qgslistwidget.h qgslegendfilterbutton.h - qgslegendinterface.h qgslimitedrandomcolorrampdialog.h qgslonglongvalidator.h qgsludialog.h diff --git a/src/gui/qgisinterface.h b/src/gui/qgisinterface.h index 32a8d4009e93..da8bb93bdf43 100644 --- a/src/gui/qgisinterface.h +++ b/src/gui/qgisinterface.h @@ -32,7 +32,6 @@ class QgsCustomDropHandler; class QgsFeature; class QgsLayerTreeMapCanvasBridge; class QgsLayerTreeView; -class QgsLegendInterface; class QgsMapCanvas; class QgsMapLayer; class QgsMapLayerConfigWidgetFactory; @@ -49,6 +48,7 @@ class QgsVectorLayerTools; #include #include "qgis.h" +#include "qgsmaplayer.h" /** \ingroup gui @@ -75,13 +75,36 @@ class GUI_EXPORT QgisInterface : public QObject //! Virtual destructor virtual ~QgisInterface(); - //! Get pointer to legend interface - virtual QgsLegendInterface* legendInterface() = 0; - virtual QgsPluginManagerInterface* pluginManagerInterface() = 0; virtual QgsLayerTreeView* layerTreeView() = 0; + /** Add action to context menu for layers in the layer tree. + * If allLayers is true, then the action will be available for all layers of given type, + * otherwise the action will be available only for specific layers added with addCustomActionForLayer() + * after this call. + * + * If menu argument is not empty, the action will be also added to a menu within the main window, + * creating menu with the given name if it does not exist yet. + * + * @see removeCustomActionForLayerType() + * @see addCustomActionForLayer() + */ + virtual void addCustomActionForLayerType( QAction* action, QString menu, + QgsMapLayer::LayerType type, bool allLayers ) = 0; + + /** Add action to context menu for a specific layer in the layer tree. + * It is necessary to first call addCustomActionForLayerType() with allLayers=false + * in order for this method to have any effect. + * @see addCustomActionForLayerType() + */ + virtual void addCustomActionForLayer( QAction* action, QgsMapLayer* layer ) = 0; + + /** Remove action for layers in the layer tree previously added with addCustomActionForLayerType() + * @see addCustomActionForLayerType() + */ + virtual bool removeCustomActionForLayerType( QAction* action ) = 0; + public slots: // TODO: do these functions really need to be slots? /* Exposed functions */ diff --git a/src/gui/qgslegendinterface.cpp b/src/gui/qgslegendinterface.cpp deleted file mode 100644 index 6b9ff8417eee..000000000000 --- a/src/gui/qgslegendinterface.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/*************************************************************************** - qgslegendinterface.cpp - -------------------------------------- - Date : 19-Nov-2009 - Copyright : (C) 2009 by Andres Manz - Email : manz dot andres at gmail dot com -****************************************************************************/ -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#include "qgslegendinterface.h" - -QgsLegendInterface::QgsLegendInterface() -{ -} - -QgsLegendInterface::~QgsLegendInterface() -{ -} - diff --git a/src/gui/qgslegendinterface.h b/src/gui/qgslegendinterface.h deleted file mode 100644 index 51cb92d3227f..000000000000 --- a/src/gui/qgslegendinterface.h +++ /dev/null @@ -1,152 +0,0 @@ -/*************************************************************************** - qgslegendinterface.h - -------------------------------------- - Date : 19-Nov-2009 - Copyright : (C) 2009 by Andres Manz - Email : manz dot andres at gmail dot com -****************************************************************************/ -/*************************************************************************** - * * - * This program is free software; you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation; either version 2 of the License, or * - * (at your option) any later version. * - * * - ***************************************************************************/ - -#ifndef QGSLEGENDINTERFACE_H -#define QGSLEGENDINTERFACE_H - -#include -#include -#include -#include - -class QgsMapLayer; -class QTreeWidgetItem; -class QAction; - -#include "qgsmaplayer.h" - -//Information about relationship between groups and layers -//key: group name (or null strings for single layers without groups) -//value: containter with layer ids contained in the group -typedef QPair< QString, QList > GroupLayerInfo; - -/** \ingroup gui - * QgsLegendInterface - * Abstract base class to make QgsLegend available to plugins. - */ -class GUI_EXPORT QgsLegendInterface : public QObject -{ - Q_OBJECT - - public: - - //! Constructor - QgsLegendInterface(); - - //! Virtual destructor - virtual ~QgsLegendInterface(); - - //! Return a string list of groups - virtual QStringList groups() = 0; - - //! Return the relationship between groups and layers in the legend - virtual QList< GroupLayerInfo > groupLayerRelationship() { return QList< GroupLayerInfo >(); } - - //! Returns the currently selected layers of QgsLegendLayers. - //! @param inDrawOrder return layers in drawing order - //! @returns list of layers, else an empty list - virtual QList selectedLayers( bool inDrawOrder = false ) const = 0; - - //! Return all layers in the project in drawing order - virtual QList< QgsMapLayer * > layers() const = 0; - - //! Check if a group exists - virtual bool groupExists( int groupIndex ) = 0; - - //! Check if a group is expanded - virtual bool isGroupExpanded( int groupIndex ) = 0; - - //! Check if a group is visible - virtual bool isGroupVisible( int groupIndex ) = 0; - - //! Check if a layer is expanded - virtual bool isLayerExpanded( QgsMapLayer * ml ) = 0; - - //! Check if a layer is visible - virtual bool isLayerVisible( QgsMapLayer * ml ) = 0; - - //! Add action for layers in the legend - virtual void addLegendLayerAction( QAction* action, QString menu, QString id, - QgsMapLayer::LayerType type, bool allLayers ) = 0; - - /** Add action for a specific layers in the legend. - * Use this in combination with addLegendLayerAction( allLayers = False ) - */ - virtual void addLegendLayerActionForLayer( QAction* action, QgsMapLayer* layer ) = 0; - - //! Remove action for layers in the legend - virtual bool removeLegendLayerAction( QAction* action ) = 0; - - //! Returns the current layer if the current item is a QgsLegendLayer. - //! If the current item is a QgsLegendLayer, its first maplayer is returned. - //! Else, 0 is returned. - virtual QgsMapLayer* currentLayer() = 0; - - //! set the current layer - //! returns true if the layer exists, false otherwise - virtual bool setCurrentLayer( QgsMapLayer *layer ) = 0; - - signals: - - //! emitted when a group index has changed - void groupIndexChanged( int oldIndex, int newIndex ); - - /* //! emitted when group relations have changed */ - void groupRelationsChanged(); - - /* //! emitted when an item (group/layer) is added */ - void itemAdded( const QModelIndex& index ); - - /* //! emitted when an item (group/layer) is removed */ - void itemRemoved(); - - //! Emitted whenever current (selected) layer changes - // the pointer to layer can be null if no layer is selected - void currentLayerChanged( QgsMapLayer * layer ); - - public slots: - - //! Add a new group - //! a parent group can be given to nest the new group in it - virtual int addGroup( const QString& name, bool expand = true, QTreeWidgetItem* parent = nullptr ) = 0; - - //! Add a new group - //! a parent group index has to be given to nest the new group in it - virtual int addGroup( const QString& name, bool expand, int parentIndex ) = 0; - - //! Remove group on index - virtual void removeGroup( int groupIndex ) = 0; - - //! Move a layer to a group - virtual void moveLayer( QgsMapLayer * ml, int groupIndex ) = 0; - - //! Collapse or expand a group - virtual void setGroupExpanded( int groupIndex, bool expand ) = 0; - - //! Collapse or expand a layer - virtual void setLayerExpanded( QgsMapLayer * ml, bool expand ) = 0; - - //! Set the visibility of a group - virtual void setGroupVisible( int groupIndex, bool visible ) = 0; - - //! Set the visibility of a layer - virtual void setLayerVisible( QgsMapLayer * ml, bool visible ) = 0; - - //! Refresh layer symbology - virtual void refreshLayerSymbology( QgsMapLayer *ml ) = 0; -}; - -#endif diff --git a/src/plugins/georeferencer/qgsgeorefplugingui.cpp b/src/plugins/georeferencer/qgsgeorefplugingui.cpp index 0a0435bd101c..ffce809041d2 100644 --- a/src/plugins/georeferencer/qgsgeorefplugingui.cpp +++ b/src/plugins/georeferencer/qgsgeorefplugingui.cpp @@ -32,7 +32,6 @@ #include #include "qgisinterface.h" -#include "qgslegendinterface.h" #include "qgsapplication.h" #include "qgscomposition.h" From 377cba0b74c0ce104acf72282b4cfabec54199a2 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 10:23:27 +1000 Subject: [PATCH 864/897] [processing] Use real map settings scope instead of custom canvasextent variables --- python/plugins/processing/core/parameters.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 63e4791d7cb6..706dd16d18b3 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -71,6 +71,10 @@ def _expressionContext(): context = QgsExpressionContext() context.appendScope(QgsExpressionContextUtils.globalScope()) context.appendScope(QgsExpressionContextUtils.projectScope()) + + if iface.mapCanvas(): + context.appendScope(QgsExpressionContextUtils.mapSettingsScope(iface.mapCanvas().mapSettings())) + processingScope = QgsExpressionContextScope() layers = dataobjects.getAllLayers() for layer in layers: @@ -93,12 +97,6 @@ def _expressionContext(): processingScope.setVariable('%s_band%i_min' % (name, i + 1), stats.minimumValue) processingScope.setVariable('%s_band%i_max' % (name, i + 1), stats.maximumValue) - extent = iface.mapCanvas().extent() - processingScope.setVariable('canvasextent_minx', extent.xMinimum()) - processingScope.setVariable('canvasextent_miny', extent.yMinimum()) - processingScope.setVariable('canvasextent_maxx', extent.xMaximum()) - processingScope.setVariable('canvasextent_maxy', extent.yMaximum()) - extent = iface.mapCanvas().fullExtent() processingScope.setVariable('fullextent_minx', extent.xMinimum()) processingScope.setVariable('fullextent_miny', extent.yMinimum()) From 86ab3022b552c07709d98f7dbf092330938587eb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 16 Nov 2016 10:25:07 +1000 Subject: [PATCH 865/897] Remove layer extent and statistic variables from processing contexts These variables take a lot of time to calculate and cause lots of lengthy hangs in processing. (Eg add some moderately large rasters to a project, then try to run any processing algorithm and QGIS will freeze). The layer extent can already be used in expressions via the layer_property function, which only evalutes the extent if required and only for layers it is used for. The band stats for raster layers should be moved to a band_statistic function in core which behaves the same way. --- python/plugins/processing/core/parameters.py | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 706dd16d18b3..acc2f6149353 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -76,26 +76,6 @@ def _expressionContext(): context.appendScope(QgsExpressionContextUtils.mapSettingsScope(iface.mapCanvas().mapSettings())) processingScope = QgsExpressionContextScope() - layers = dataobjects.getAllLayers() - for layer in layers: - name = layer.name() - processingScope.setVariable('%s_minx' % name, layer.extent().xMinimum()) - processingScope.setVariable('%s_miny' % name, layer.extent().yMinimum()) - processingScope.setVariable('%s_maxx' % name, layer.extent().xMaximum()) - processingScope.setVariable('%s_maxy' % name, layer.extent().yMaximum()) - if isinstance(layer, QgsRasterLayer): - cellsize = (layer.extent().xMaximum() - - layer.extent().xMinimum()) / layer.width() - processingScope.setVariable('%s_cellsize' % name, cellsize) - - layers = dataobjects.getRasterLayers() - for layer in layers: - for i in range(layer.bandCount()): - stats = layer.dataProvider().bandStatistics(i + 1) - processingScope.setVariable('%s_band%i_avg' % (name, i + 1), stats.mean) - processingScope.setVariable('%s_band%i_stddev' % (name, i + 1), stats.stdDev) - processingScope.setVariable('%s_band%i_min' % (name, i + 1), stats.minimumValue) - processingScope.setVariable('%s_band%i_max' % (name, i + 1), stats.maximumValue) extent = iface.mapCanvas().fullExtent() processingScope.setVariable('fullextent_minx', extent.xMinimum()) From 20dc7fb266efba2f2bddc47443f129bf3eef9f03 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Tue, 22 Nov 2016 12:07:25 +1000 Subject: [PATCH 866/897] [FEATURE] raster_statistic expression function for retrieving raster band stats from a loaded layer Allows raster band stats (eg min, max, avg) to be used in expressions --- resources/function_help/json/raster_statistic | 14 ++++ src/core/qgsexpression.cpp | 74 +++++++++++++++++++ tests/src/core/testqgsexpression.cpp | 24 ++++++ 3 files changed, 112 insertions(+) create mode 100644 resources/function_help/json/raster_statistic diff --git a/resources/function_help/json/raster_statistic b/resources/function_help/json/raster_statistic new file mode 100644 index 000000000000..fc4d4dd2fc26 --- /dev/null +++ b/resources/function_help/json/raster_statistic @@ -0,0 +1,14 @@ +{ + "name": "raster_statistic", + "type": "function", + "description": "Returns statistics from a raster layer.", + "arguments": [ + {"arg":"layer", "description":"a string, representing either a raster layer name or layer ID"}, + {"arg":"band", "description":"integer representing the band number from the raster layer, starting at 1"}, + {"arg":"property", "description":"a string corresponding to the property to return. Valid options are:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • min: minimum value
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • max: maximum value
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • avg: average (mean) value
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • stdev: standard deviation of values
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • range: range of values (max - min)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  • sum: sum of all values from raster
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  "} + ], + "examples": [ + { "expression":"raster_statistic('lc',1,'avg')", "returns":"Average value from band 1 from 'lc' raster layer"}, + { "expression":"raster_statistic('ac2010',3,'min')", "returns":"Minimum value from band 3 from 'ac2010' raster layer"} + ] +} diff --git a/src/core/qgsexpression.cpp b/src/core/qgsexpression.cpp index f44629b6ed80..9e8ab11ed893 100644 --- a/src/core/qgsexpression.cpp +++ b/src/core/qgsexpression.cpp @@ -54,6 +54,8 @@ #include "qgsmaptopixelgeometrysimplifier.h" #include "qgsmessagelog.h" #include "qgscsexception.h" +#include "qgsrasterlayer.h" +#include "qgsrasterdataprovider.h" // from parser extern QgsExpression::Node* parseExpression( const QString& str, QString& parserErrorMsg ); @@ -3423,6 +3425,75 @@ static QVariant fcnGetLayerProperty( const QVariantList& values, const QgsExpres return QVariant(); } +static QVariant fcnGetRasterBandStat( const QVariantList& values, const QgsExpressionContext*, QgsExpression* parent ) +{ + QString layerIdOrName = getStringValue( values.at( 0 ), parent ); + + //try to find a matching layer by name + QgsMapLayer* layer = QgsMapLayerRegistry::instance()->mapLayer( layerIdOrName ); //search by id first + if ( !layer ) + { + QList layersByName = QgsMapLayerRegistry::instance()->mapLayersByName( layerIdOrName ); + if ( !layersByName.isEmpty() ) + { + layer = layersByName.at( 0 ); + } + } + + if ( !layer ) + return QVariant(); + + QgsRasterLayer* rl = qobject_cast< QgsRasterLayer* >( layer ); + if ( !rl ) + return QVariant(); + + int band = getIntValue( values.at( 1 ), parent ); + if ( band < 1 || band > rl->bandCount() ) + { + parent->setEvalErrorString( QObject::tr( "Invalid band number %1 for layer %2" ).arg( band ).arg( layerIdOrName ) ); + return QVariant(); + } + + QString layerProperty = getStringValue( values.at( 2 ), parent ); + int stat = 0; + + if ( QString::compare( layerProperty, QStringLiteral( "avg" ), Qt::CaseInsensitive ) == 0 ) + stat = QgsRasterBandStats::Mean; + else if ( QString::compare( layerProperty, QStringLiteral( "stdev" ), Qt::CaseInsensitive ) == 0 ) + stat = QgsRasterBandStats::StdDev; + else if ( QString::compare( layerProperty, QStringLiteral( "min" ), Qt::CaseInsensitive ) == 0 ) + stat = QgsRasterBandStats::Min; + else if ( QString::compare( layerProperty, QStringLiteral( "max" ), Qt::CaseInsensitive ) == 0 ) + stat = QgsRasterBandStats::Max; + else if ( QString::compare( layerProperty, QStringLiteral( "range" ), Qt::CaseInsensitive ) == 0 ) + stat = QgsRasterBandStats::Range; + else if ( QString::compare( layerProperty, QStringLiteral( "sum" ), Qt::CaseInsensitive ) == 0 ) + stat = QgsRasterBandStats::Sum; + else + { + parent->setEvalErrorString( QObject::tr( "Invalid raster statistic: '%1'" ).arg( layerProperty ) ); + return QVariant(); + } + + QgsRasterBandStats stats = rl->dataProvider()->bandStatistics( band, stat ); + switch ( stat ) + { + case QgsRasterBandStats::Mean: + return stats.mean; + case QgsRasterBandStats::StdDev: + return stats.stdDev; + case QgsRasterBandStats::Min: + return stats.minimumValue; + case QgsRasterBandStats::Max: + return stats.maximumValue; + case QgsRasterBandStats::Range: + return stats.range; + case QgsRasterBandStats::Sum: + return stats.sum; + } + return QVariant(); +} + static QVariant fcnArray( const QVariantList& values, const QgsExpressionContext*, QgsExpression* ) { return values; @@ -4007,6 +4078,9 @@ const QList& QgsExpression::Functions() // **General** functions << new StaticFunction( QStringLiteral( "layer_property" ), 2, fcnGetLayerProperty, QStringLiteral( "General" ) ) + << new StaticFunction( QStringLiteral( "raster_statistic" ), ParameterList() << Parameter( QStringLiteral( "layer" ) ) + << Parameter( QStringLiteral( "band" ) ) + << Parameter( QStringLiteral( "statistic" ) ), fcnGetRasterBandStat, QStringLiteral( "General" ) ) << new StaticFunction( QStringLiteral( "var" ), 1, fcnGetVariable, QStringLiteral( "General" ) ) //return all attributes string for referencedColumns - this is caught by diff --git a/tests/src/core/testqgsexpression.cpp b/tests/src/core/testqgsexpression.cpp index b0ba3c7aa0fd..dade8f05bf98 100644 --- a/tests/src/core/testqgsexpression.cpp +++ b/tests/src/core/testqgsexpression.cpp @@ -32,6 +32,7 @@ #include "qgsmaplayerregistry.h" #include "qgsvectordataprovider.h" #include "qgsdistancearea.h" +#include "qgsrasterlayer.h" #include "qgsproject.h" static void _parseAndEvalExpr( int arg ) @@ -55,6 +56,7 @@ class TestQgsExpression: public QObject , mMemoryLayer( nullptr ) , mAggregatesLayer( nullptr ) , mChildLayer( nullptr ) + , mRasterLayer( nullptr ) {} private: @@ -63,6 +65,7 @@ class TestQgsExpression: public QObject QgsVectorLayer* mMemoryLayer; QgsVectorLayer* mAggregatesLayer; QgsVectorLayer* mChildLayer; + QgsRasterLayer* mRasterLayer; private slots: @@ -94,6 +97,12 @@ class TestQgsExpression: public QObject mPointsLayer->setMaximumScale( 500 ); mPointsLayer->setMinimumScale( 1000 ); + QString rasterFileName = testDataDir + "tenbytenraster.asc"; + QFileInfo rasterFileInfo( rasterFileName ); + mRasterLayer = new QgsRasterLayer( rasterFileInfo.filePath(), + rasterFileInfo.completeBaseName() ); + QgsMapLayerRegistry::instance()->addMapLayer( mRasterLayer ); + // test memory layer for get_feature tests mMemoryLayer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:integer&field=col2:string" ), QStringLiteral( "test" ), QStringLiteral( "memory" ) ); QVERIFY( mMemoryLayer->isValid() ); @@ -1039,6 +1048,21 @@ class TestQgsExpression: public QObject QTest::newRow( "layer_property storage_type" ) << QStringLiteral( "layer_property('%1','storage_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "ESRI Shapefile" ); QTest::newRow( "layer_property geometry_type" ) << QStringLiteral( "layer_property('%1','geometry_type')" ).arg( mPointsLayer->name() ) << false << QVariant( "Point" ); + // raster_statistic tests + QTest::newRow( "raster_statistic no layer" ) << "raster_statistic('',1,'min')" << false << QVariant(); + QTest::newRow( "raster_statistic bad layer" ) << "raster_statistic('bad',1,'min')" << false << QVariant(); + QTest::newRow( "raster_statistic bad band" ) << QStringLiteral( "raster_statistic('%1',0,'min')" ).arg( mRasterLayer->name() ) << true << QVariant(); + QTest::newRow( "raster_statistic bad band 2" ) << QStringLiteral( "raster_statistic('%1',100,'min')" ).arg( mRasterLayer->name() ) << true << QVariant(); + QTest::newRow( "raster_statistic no property" ) << QStringLiteral( "raster_statistic('%1',1,'')" ).arg( mRasterLayer->name() ) << true << QVariant(); + QTest::newRow( "raster_statistic bad property" ) << QStringLiteral( "raster_statistic('%1',1,'bad')" ).arg( mRasterLayer->name() ) << true << QVariant(); + QTest::newRow( "raster_statistic min by id" ) << QStringLiteral( "raster_statistic('%1',1,'min')" ).arg( mRasterLayer->id() ) << false << QVariant( 0.0 ); + QTest::newRow( "raster_statistic min name" ) << QStringLiteral( "raster_statistic('%1',1,'min')" ).arg( mRasterLayer->name() ) << false << QVariant( 0.0 ); + QTest::newRow( "raster_statistic max" ) << QStringLiteral( "raster_statistic('%1',1,'max')" ).arg( mRasterLayer->id() ) << false << QVariant( 9.0 ); + QTest::newRow( "raster_statistic avg" ) << QStringLiteral( "round(10*raster_statistic('%1',1,'avg'))" ).arg( mRasterLayer->id() ) << false << QVariant( 45 ); + QTest::newRow( "raster_statistic stdev" ) << QStringLiteral( "round(100*raster_statistic('%1',1,'stdev'))" ).arg( mRasterLayer->id() ) << false << QVariant( 287 ); + QTest::newRow( "raster_statistic range" ) << QStringLiteral( "raster_statistic('%1',1,'range')" ).arg( mRasterLayer->id() ) << false << QVariant( 9.0 ); + QTest::newRow( "raster_statistic sum" ) << QStringLiteral( "round(raster_statistic('%1',1,'sum'))" ).arg( mRasterLayer->id() ) << false << QVariant( 450 ); + //test conversions to bool QTest::newRow( "feature to bool false" ) << QStringLiteral( "case when get_feature('none','none',499) then true else false end" ) << false << QVariant( false ); QTest::newRow( "feature to bool true" ) << QStringLiteral( "case when get_feature('test','col1',10) then true else false end" ) << false << QVariant( true ); From 0c58555c435d6b54f4e39a606970b4f71db01baa Mon Sep 17 00:00:00 2001 From: Mathieu Pellerin Date: Tue, 22 Nov 2016 11:23:04 +0700 Subject: [PATCH 867/897] [symbology] respect mixed unit when applying symbol from list widget (#3792) --- src/gui/symbology-ng/qgssymbolslistwidget.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/gui/symbology-ng/qgssymbolslistwidget.cpp b/src/gui/symbology-ng/qgssymbolslistwidget.cpp index be3dc5d1028b..dbfb25ff09b0 100644 --- a/src/gui/symbology-ng/qgssymbolslistwidget.cpp +++ b/src/gui/symbology-ng/qgssymbolslistwidget.cpp @@ -582,7 +582,6 @@ void QgsSymbolsListWidget::setSymbolFromStyle( const QModelIndex & index ) lblSymbolName->setText( symbolName ); // get new instance of symbol from style QgsSymbol* s = mStyle->symbol( symbolName ); - QgsUnitTypes::RenderUnit unit = s->outputUnit(); // remove all symbol layers from original symbolgroupsCombo while ( mSymbol->symbolLayerCount() ) mSymbol->deleteSymbolLayer( 0 ); @@ -593,7 +592,7 @@ void QgsSymbolsListWidget::setSymbolFromStyle( const QModelIndex & index ) mSymbol->appendSymbolLayer( sl ); } mSymbol->setAlpha( s->alpha() ); - mSymbol->setOutputUnit( unit ); + // delete the temporary symbol delete s; From d7166404030292b9536e649795e9efec49225dfd Mon Sep 17 00:00:00 2001 From: Martin Dobias Date: Tue, 22 Nov 2016 12:21:47 +0800 Subject: [PATCH 868/897] Remove usage of legendInterface() from plugins (followup e5f62e49) --- .../GdalTools/tools/GdalTools_utils.py | 6 +- .../plugins/db_manager/db_manager_plugin.py | 8 +- .../postgis/plugins/qgis_topoview/__init__.py | 156 ++++++++---------- .../plugins/db_manager/dlg_import_vector.py | 11 +- 4 files changed, 79 insertions(+), 102 deletions(-) diff --git a/python/plugins/GdalTools/tools/GdalTools_utils.py b/python/plugins/GdalTools/tools/GdalTools_utils.py index cf89fa73e836..79c86a802bf1 100644 --- a/python/plugins/GdalTools/tools/GdalTools_utils.py +++ b/python/plugins/GdalTools/tools/GdalTools_utils.py @@ -37,7 +37,7 @@ from qgis.PyQt.QtCore import QObject, QSettings, QFileInfo, QDir, QCoreApplication, pyqtSignal from qgis.PyQt.QtWidgets import QFileDialog -from qgis.core import QgsApplication, QgsMapLayerRegistry, QgsRectangle, QgsProviderRegistry, QgsLogger +from qgis.core import QgsApplication, QgsMapLayerRegistry, QgsRectangle, QgsProviderRegistry, QgsLogger, QgsProject from qgis.gui import QgsEncodingFileDialog from osgeo import gdal, ogr, osr @@ -187,9 +187,7 @@ def __init__(self): QgsMapLayerRegistry.instance().layerWillBeRemoved.connect(self.removeLayer) def getAllLayers(self): - if LayerRegistry._iface and hasattr(LayerRegistry._iface, 'legendInterface'): - return LayerRegistry._iface.legendInterface().layers() - return list(QgsMapLayerRegistry.instance().mapLayers().values()) + return list(node.layer() for node in QgsProject.instance().layerTreeRoot().findLayers()) def layerAdded(self, layer): LayerRegistry.layers.append(layer) diff --git a/python/plugins/db_manager/db_manager_plugin.py b/python/plugins/db_manager/db_manager_plugin.py index 65b865984d97..99e61c266a3c 100644 --- a/python/plugins/db_manager/db_manager_plugin.py +++ b/python/plugins/db_manager/db_manager_plugin.py @@ -56,7 +56,7 @@ def initGui(self): self.iface.mainWindow()) self.layerAction.setObjectName("dbManagerUpdateSqlLayer") self.layerAction.triggered.connect(self.onUpdateSqlLayer) - self.iface.legendInterface().addLegendLayerAction(self.layerAction, "", "dbManagerUpdateSqlLayer", QgsMapLayer.VectorLayer, False) + self.iface.addCustomActionForLayerType(self.layerAction, "", QgsMapLayer.VectorLayer, False) for l in list(QgsMapLayerRegistry.instance().mapLayers().values()): self.onLayerWasAdded(l) QgsMapLayerRegistry.instance().layerWasAdded.connect(self.onLayerWasAdded) @@ -72,7 +72,7 @@ def unload(self): else: self.iface.removeToolBarIcon(self.action) - self.iface.legendInterface().removeLegendLayerAction(self.layerAction) + self.iface.removeCustomActionForLayerType(self.layerAction) QgsMapLayerRegistry.instance().layerWasAdded.disconnect(self.onLayerWasAdded) if self.dlg is not None: @@ -82,7 +82,7 @@ def onLayerWasAdded(self, aMapLayer): if hasattr(aMapLayer, 'dataProvider') and aMapLayer.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: uri = QgsDataSourceUri(aMapLayer.source()) if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S): - self.iface.legendInterface().addLegendLayerActionForLayer(self.layerAction, aMapLayer) + self.addCustomActionForLayer(self.layerAction, aMapLayer) # virtual has QUrl source # url = QUrl(QUrl.fromPercentEncoding(l.source())) # url.queryItemValue('query') @@ -90,7 +90,7 @@ def onLayerWasAdded(self, aMapLayer): # url.queryItemValue('geometry') def onUpdateSqlLayer(self): - l = self.iface.legendInterface().currentLayer() + l = self.iface.activeLayer() if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: uri = QgsDataSourceUri(l.source()) if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S): diff --git a/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py b/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py index 4b32cd391c58..60398d55125d 100644 --- a/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py +++ b/python/plugins/db_manager/db_plugins/postgis/plugins/qgis_topoview/__init__.py @@ -97,14 +97,11 @@ def run(item, action, mainwindow): # load layers into the current project toponame = item.schema().name template_dir = os.path.join(current_path, 'templates') - registry = QgsMapLayerRegistry.instance() - legend = iface.legendInterface() # do not refresh the canvas until all the layers are added prevRenderFlagState = iface.mapCanvas().renderFlag() iface.mapCanvas().setRenderFlag(False) try: - supergroup = legend.addGroup(u'Topology "%s"' % toponame, False) provider = db.dbplugin().providerName() uri = db.uri() @@ -112,19 +109,15 @@ def run(item, action, mainwindow): uri.setUseEstimatedMetadata(True) # FACES - group = legend.addGroup(u'Faces', False, supergroup) # face mbr uri.setDataSource(toponame, 'face', 'mbr', '', 'face_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.Polygon) - layer = QgsVectorLayer(uri.uri(False), u'%s.face_mbr' % toponame, provider) - layer.loadNamedStyle(os.path.join(template_dir, 'face_mbr.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) - face_extent = layer.extent() + layerFaceMbr = QgsVectorLayer(uri.uri(False), u'%s.face_mbr' % toponame, provider) + layerFaceMbr.loadNamedStyle(os.path.join(template_dir, 'face_mbr.qml')) + + face_extent = layerFaceMbr.extent() # face geometry sql = u'SELECT face_id, topology.ST_GetFaceGeometry(%s,' \ @@ -134,13 +127,9 @@ def run(item, action, mainwindow): uri.setDataSource('', u'(%s\n)' % sql, 'geom', '', 'face_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.Polygon) - layer = QgsVectorLayer(uri.uri(False), u'%s.face' % toponame, provider) - layer.setExtent(face_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'face.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerFaceGeom = QgsVectorLayer(uri.uri(False), u'%s.face' % toponame, provider) + layerFaceGeom.setExtent(face_extent) + layerFaceGeom.loadNamedStyle(os.path.join(template_dir, 'face.qml')) # face_seed sql = u'SELECT face_id, ST_PointOnSurface(' \ @@ -151,128 +140,117 @@ def run(item, action, mainwindow): uri.setDataSource('', u'(%s)' % sql, 'geom', '', 'face_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.Point) - layer = QgsVectorLayer(uri.uri(False), u'%s.face_seed' % toponame, provider) - layer.setExtent(face_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'face_seed.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerFaceSeed = QgsVectorLayer(uri.uri(False), u'%s.face_seed' % toponame, provider) + layerFaceSeed.setExtent(face_extent) + layerFaceSeed.loadNamedStyle(os.path.join(template_dir, 'face_seed.qml')) # TODO: add polygon0, polygon1 and polygon2 ? # NODES - group = legend.addGroup(u'Nodes', False, supergroup) # node uri.setDataSource(toponame, 'node', 'geom', '', 'node_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.Point) - layer = QgsVectorLayer(uri.uri(False), u'%s.node' % toponame, provider) - layer.loadNamedStyle(os.path.join(template_dir, 'node.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) - node_extent = layer.extent() + layerNode = QgsVectorLayer(uri.uri(False), u'%s.node' % toponame, provider) + layerNode.loadNamedStyle(os.path.join(template_dir, 'node.qml')) + node_extent = layerNode.extent() # node labels uri.setDataSource(toponame, 'node', 'geom', '', 'node_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.Point) - layer = QgsVectorLayer(uri.uri(False), u'%s.node_id' % toponame, provider) - layer.setExtent(node_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'node_label.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerNodeLabel = QgsVectorLayer(uri.uri(False), u'%s.node_id' % toponame, provider) + layerNodeLabel.setExtent(node_extent) + layerNodeLabel.loadNamedStyle(os.path.join(template_dir, 'node_label.qml')) # EDGES - group = legend.addGroup(u'Edges', False, supergroup) # edge uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.edge' % toponame, provider) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) - edge_extent = layer.extent() + layerEdge = QgsVectorLayer(uri.uri(False), u'%s.edge' % toponame, provider) + edge_extent = layerEdge.extent() # directed edge uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.directed_edge' % toponame, provider) - layer.setExtent(edge_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'edge.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerDirectedEdge = QgsVectorLayer(uri.uri(False), u'%s.directed_edge' % toponame, provider) + layerDirectedEdge.setExtent(edge_extent) + layerDirectedEdge.loadNamedStyle(os.path.join(template_dir, 'edge.qml')) # edge labels uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.edge_id' % toponame, provider) - layer.setExtent(edge_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'edge_label.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerEdgeLabel = QgsVectorLayer(uri.uri(False), u'%s.edge_id' % toponame, provider) + layerEdgeLabel.setExtent(edge_extent) + layerEdgeLabel.loadNamedStyle(os.path.join(template_dir, 'edge_label.qml')) # face_left uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.face_left' % toponame, provider) - layer.setExtent(edge_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'face_left.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerFaceLeft = QgsVectorLayer(uri.uri(False), u'%s.face_left' % toponame, provider) + layerFaceLeft.setExtent(edge_extent) + layerFaceLeft.loadNamedStyle(os.path.join(template_dir, 'face_left.qml')) # face_right uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.face_right' % toponame, provider) - layer.setExtent(edge_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'face_right.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerFaceRight = QgsVectorLayer(uri.uri(False), u'%s.face_right' % toponame, provider) + layerFaceRight.setExtent(edge_extent) + layerFaceRight.loadNamedStyle(os.path.join(template_dir, 'face_right.qml')) # next_left uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.next_left' % toponame, provider) - layer.setExtent(edge_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'next_left.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerNextLeft = QgsVectorLayer(uri.uri(False), u'%s.next_left' % toponame, provider) + layerNextLeft.setExtent(edge_extent) + layerNextLeft.loadNamedStyle(os.path.join(template_dir, 'next_left.qml')) # next_right uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id') uri.setSrid(toposrid) uri.setWkbType(QgsWkbTypes.LineString) - layer = QgsVectorLayer(uri.uri(False), u'%s.next_right' % toponame, provider) - layer.setExtent(edge_extent) - layer.loadNamedStyle(os.path.join(template_dir, 'next_right.qml')) - registry.addMapLayers([layer]) - legend.moveLayer(layer, group) - legend.setLayerVisible(layer, False) - legend.setLayerExpanded(layer, False) + layerNextRight = QgsVectorLayer(uri.uri(False), u'%s.next_right' % toponame, provider) + layerNextRight.setExtent(edge_extent) + layerNextRight.loadNamedStyle(os.path.join(template_dir, 'next_right.qml')) + + # Add layers to the layer tree + + faceLayers = [layerFaceMbr, layerFaceGeom, layerFaceSeed] + nodeLayers = [layerNode, layerNodeLabel] + edgeLayers = [layerEdge, layerDirectedEdge, layerEdgeLabel, layerEdgeFaceLeft, layerEdgeFaceRight, layerEdgeNextLeft, layerEdgeNextRight] + + QgsMapLayerRegistry.instance().addMapLayers(faceLayers, False) + + groupFaces = QgsLayerTreeGroup(u'Faces') + for layer in faceLayers: + nodeLayer = groupFaces.addLayer(layer) + nodeLayer.setVisible(Qt.Unchecked) + nodeLayer.setExpanded(False) + + groupNodes = QgsLayerTreeGroup(u'Nodes') + for layer in faceLayers: + nodeLayer = groupNodes.addLayer(layer) + nodeLayer.setVisible(Qt.Unchecked) + nodeLayer.setExpanded(False) + + groupEdges = QgsLayerTreeGroup(u'Edges') + for layer in faceLayers: + nodeLayer = groupEdges.addLayer(layer) + nodeLayer.setVisible(Qt.Unchecked) + nodeLayer.setExpanded(False) + + supergroup = QgsLayerTreeGroup(u'Topology "%s"' % toponame) + supergroup.insertChildNodes(-1, [groupFaces, groupNodes, groupEdges]) + + QgsProject.instance().layerTreeRoot().addChildNode(supergroup) finally: diff --git a/python/plugins/db_manager/dlg_import_vector.py b/python/plugins/db_manager/dlg_import_vector.py index c8f87bcba8d4..f3eddddebd65 100644 --- a/python/plugins/db_manager/dlg_import_vector.py +++ b/python/plugins/db_manager/dlg_import_vector.py @@ -28,7 +28,7 @@ from qgis.PyQt.QtWidgets import QDialog, QFileDialog, QMessageBox, QApplication from qgis.PyQt.QtGui import QCursor -from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsRasterLayer, QgsMimeDataUtils, QgsMapLayer, QgsProviderRegistry, QgsCoordinateReferenceSystem, QgsVectorLayerImport +from qgis.core import QgsDataSourceUri, QgsVectorLayer, QgsRasterLayer, QgsMimeDataUtils, QgsMapLayer, QgsProviderRegistry, QgsCoordinateReferenceSystem, QgsVectorLayerImport, QgsProject, QgsMapLayerRegistry from qgis.gui import QgsMessageViewer from qgis.utils import iface @@ -118,10 +118,11 @@ def checkSupports(self): def populateLayers(self): self.cboInputLayer.clear() - for index, layer in enumerate(iface.legendInterface().layers()): + for nodeLayer in QgsProject.instance().layerTreeRoot().findLayers(): + layer = nodeLayer.layer() # TODO: add import raster support! if layer.type() == QgsMapLayer.VectorLayer: - self.cboInputLayer.addItem(layer.name(), index) + self.cboInputLayer.addItem(layer.name(), layer.id()) def deleteInputLayer(self): """ unset the input layer, then destroy it but only if it was created from this dialog """ @@ -181,8 +182,8 @@ def reloadInputLayer(self): self.inLayerMustBeDestroyed = True else: - legendIndex = self.cboInputLayer.itemData(index) - self.inLayer = iface.legendInterface().layers()[legendIndex] + layerId = self.cboInputLayer.itemData(index) + self.inLayer = QgsMapLayerRegistry.instance().mapLayer(layerId) self.inLayerMustBeDestroyed = False self.checkSupports() From efd299220e355df2d7b93b82e29d41e7038f42cc Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 21 Nov 2016 12:07:53 +0700 Subject: [PATCH 869/897] package symbology-ng-style.xml instead of the .db file --- debian/qgis-providers-common.install | 2 +- ms-windows/osgeo4w/package.cmd | 2 +- resources/CMakeLists.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/debian/qgis-providers-common.install b/debian/qgis-providers-common.install index e422e0da1542..58cef6c58551 100644 --- a/debian/qgis-providers-common.install +++ b/debian/qgis-providers-common.install @@ -2,5 +2,5 @@ usr/share/qgis/svg/* usr/share/qgis/resources/qgis.db usr/share/qgis/resources/srs-template.db usr/share/qgis/resources/customization.xml -usr/share/qgis/resources/symbology-ng-style.db +usr/share/qgis/resources/symbology-ng-style.xml usr/share/qgis/resources/cpt-city-qgis-min/* diff --git a/ms-windows/osgeo4w/package.cmd b/ms-windows/osgeo4w/package.cmd index 36cc1485309f..b3f71de009de 100644 --- a/ms-windows/osgeo4w/package.cmd +++ b/ms-windows/osgeo4w/package.cmd @@ -325,7 +325,7 @@ tar -C %OSGEO4W_ROOT% -cjf %ARCH%/release/qgis/%PACKAGENAME%-common/%PACKAGENAME "apps/%PACKAGENAME%/resources/qgis.db" ^ "apps/%PACKAGENAME%/resources/spatialite.db" ^ "apps/%PACKAGENAME%/resources/srs.db" ^ - "apps/%PACKAGENAME%/resources/symbology-ng-style.db" ^ + "apps/%PACKAGENAME%/resources/symbology-ng-style.xml" ^ "apps/%PACKAGENAME%/resources/cpt-city-qgis-min/" ^ "apps/%PACKAGENAME%/svg/" ^ "apps/%PACKAGENAME%/crssync.exe" ^ diff --git a/resources/CMakeLists.txt b/resources/CMakeLists.txt index c3cf794d41d9..9bce6ef658b5 100644 --- a/resources/CMakeLists.txt +++ b/resources/CMakeLists.txt @@ -1,4 +1,4 @@ -INSTALL(FILES srs.db qgis.db symbology-ng-style.db spatialite.db customization.xml +INSTALL(FILES srs.db qgis.db symbology-ng-style.xml spatialite.db customization.xml DESTINATION ${QGIS_DATA_DIR}/resources) INSTALL(DIRECTORY cpt-city-qgis-min DESTINATION ${QGIS_DATA_DIR}/resources) INSTALL(DIRECTORY themes DESTINATION ${QGIS_DATA_DIR}/resources) From bc130be6cbd4941f45c4af3cdcab795e9086faa0 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 21 Nov 2016 12:29:32 +0700 Subject: [PATCH 870/897] [style] improve creation of default style db Instead of copyign a pre-existing .db shipped with QGIS, create a new .db and import an .xml file containing our default symbols. On the UX front, the main benefit is being able to ship with pre-defined tags and favorite flags for the default symbols. On the developer side, it means we get rid of the requirement to maintain both an .xml and a binary .db in the source tree. We also say aurevoir to the symbol_xml2db.py script and the need to update the (obsolete) script every time we add a new feature to QgsStyle. --- python/core/symbology-ng/qgsstyle.sip | 28 ++++++++++++- src/app/qgisapp.cpp | 5 +++ src/core/qgsapplication.cpp | 2 +- src/core/symbology-ng/qgsstyle.cpp | 41 ++++++++++++++++--- src/core/symbology-ng/qgsstyle.h | 26 ++++++++++-- .../qgsstyleexportimportdialog.cpp | 2 +- tests/src/core/testqgsstyle.cpp | 2 +- 7 files changed, 92 insertions(+), 14 deletions(-) diff --git a/python/core/symbology-ng/qgsstyle.sip b/python/core/symbology-ng/qgsstyle.sip index 4203ac18a464..d8d10c16ef8b 100644 --- a/python/core/symbology-ng/qgsstyle.sip +++ b/python/core/symbology-ng/qgsstyle.sip @@ -208,8 +208,32 @@ class QgsStyle : QObject //! Changes ramp's name bool renameColorRamp( const QString& oldName, const QString& newName ); - //! Creates a temporary memory database - bool createMemoryDB(); + /** Creates an on-disk database + * + * This function creates a new on-disk permanent style database. + * \return returns the success state of the database creation + * \note added in QGIS 3.0 + * \see createMemoryDb() + */ + bool createDb( const QString& filename ); + + /** Creates a temporary memory database + * + * This function is used to create a temporary style database in case a permanent on-disk database is not needed. + * \return returns the success state of the temporary memory database creation + * \note added in QGIS 3.0 + * \see createDb() + */ + bool createMemoryDb(); + + /** Creates tables structure for new database + * + * This function is used to create the tables structure in a newly-created database. + * \return returns the success state of the temporary memory database creation + * \note added in QGIS 3.0 + * \see createDB(), createMemoryDB() + */ + void createTables(); //! Loads a file into the style bool load( const QString& filename ); diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 9c5b99b7cf70..bda5bc775603 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -1008,6 +1008,11 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QgsCustomization::instance()->updateMainWindow( mToolbarMenu ); endProfile(); + mSplash->showMessage( tr( "Populate saved styles" ), Qt::AlignHCenter | Qt::AlignBottom ); + startProfile( QStringLiteral( "Populate saved styles" ) ); + QgsStyle::defaultStyle(); + endProfile(); + mSplash->showMessage( tr( "QGIS Ready!" ), Qt::AlignHCenter | Qt::AlignBottom ); QgsMessageLog::logMessage( QgsApplication::showSettings(), QString::null, QgsMessageLog::INFO ); diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 9c4f52a99d9b..32b22a1d59f9 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -860,7 +860,7 @@ QString QgsApplication::userThemesFolder() QString QgsApplication::defaultStylePath() { - return ABISYM( mPkgDataPath ) + QStringLiteral( "/resources/symbology-ng-style.db" ); + return ABISYM( mPkgDataPath ) + QStringLiteral( "/resources/symbology-ng-style.xml" ); } QString QgsApplication::defaultThemesFolder() diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index 3fdde38c140e..7c8d13c5be35 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -58,11 +58,18 @@ QgsStyle* QgsStyle::defaultStyle() // static // copy default style if user style doesn't exist if ( !QFile::exists( styleFilename ) ) { - QFile::copy( QgsApplication::defaultStylePath(), styleFilename ); + mDefaultStyle = new QgsStyle; + mDefaultStyle->createDb( styleFilename ); + if ( QFile::exists( QgsApplication::defaultStylePath() ) ) + { + mDefaultStyle->importXml( QgsApplication::defaultStylePath() ); + } + } + else + { + mDefaultStyle = new QgsStyle; + mDefaultStyle->load( styleFilename ); } - - mDefaultStyle = new QgsStyle; - mDefaultStyle->load( styleFilename ); } return mDefaultStyle; } @@ -289,7 +296,22 @@ bool QgsStyle::openDB( const QString& filename ) return true; } -bool QgsStyle::createMemoryDB() +bool QgsStyle::createDb( const QString& filename ) +{ + mErrorString.clear(); + if ( !openDB( filename ) ) + { + mErrorString = QStringLiteral( "Unable to create database" ); + QgsDebugMsg( mErrorString ); + return false; + } + + createTables(); + + return true; +} + +bool QgsStyle::createMemoryDb() { mErrorString.clear(); if ( !openDB( QStringLiteral( ":memory:" ) ) ) @@ -298,6 +320,14 @@ bool QgsStyle::createMemoryDB() QgsDebugMsg( mErrorString ); return false; } + + createTables(); + + return true; +} + +void QgsStyle::createTables() +{ char *query = sqlite3_mprintf( "CREATE TABLE symbol("\ "id INTEGER PRIMARY KEY,"\ "name TEXT UNIQUE,"\ @@ -322,7 +352,6 @@ bool QgsStyle::createMemoryDB() "name TEXT,"\ "xml TEXT);" ); runEmptyQuery( query ); - return true; } bool QgsStyle::load( const QString& filename ) diff --git a/src/core/symbology-ng/qgsstyle.h b/src/core/symbology-ng/qgsstyle.h index 3eb6db1aed78..c6dea11b1640 100644 --- a/src/core/symbology-ng/qgsstyle.h +++ b/src/core/symbology-ng/qgsstyle.h @@ -273,16 +273,36 @@ class CORE_EXPORT QgsStyle : public QObject //! Changes ramp's name bool renameColorRamp( const QString& oldName, const QString& newName ); + /** Creates an on-disk database + * + * This function creates a new on-disk permanent style database. + * \return returns the success state of the database creation + * \note added in QGIS 3.0 + * \see createMemoryDb() + */ + bool createDb( const QString& filename ); + /** Creates a temporary memory database * - * This function is used if you do not need to associate styles with a permanent on-disk database. + * This function is used to create a temporary style database in case a permanent on-disk database is not needed. + * \return returns the success state of the temporary memory database creation + * \note added in QGIS 3.0 + * \see createDb() + */ + bool createMemoryDb(); + + /** Creates tables structure for new database + * + * This function is used to create the tables structure in a newly-created database. * \return returns the success state of the temporary memory database creation + * \note added in QGIS 3.0 + * \see createDB(), createMemoryDB() */ - bool createMemoryDB(); + void createTables(); /** Loads a file into the style * - * This function will populate styles from an on-disk database. + * This function will load an on-disk database and populate styles. * \param filename location of the database to load styles from * \return returns the success state of the database being loaded */ diff --git a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp index 67114e959a70..e49576aa01e6 100644 --- a/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp +++ b/src/gui/symbology-ng/qgsstyleexportimportdialog.cpp @@ -55,7 +55,7 @@ QgsStyleExportImportDialog::QgsStyleExportImportDialog( QgsStyle* style, QWidget this, SLOT( selectionChanged( const QItemSelection&, const QItemSelection& ) ) ); mTempStyle = new QgsStyle(); - mTempStyle->createMemoryDB(); + mTempStyle->createMemoryDb(); // TODO validate mFileName = QLatin1String( "" ); diff --git a/tests/src/core/testqgsstyle.cpp b/tests/src/core/testqgsstyle.cpp index 862318093f3b..94e853bce063 100644 --- a/tests/src/core/testqgsstyle.cpp +++ b/tests/src/core/testqgsstyle.cpp @@ -95,7 +95,7 @@ void TestStyle::initTestCase() //initize a temporary memory-based style for tests to avoid clashing with shipped symbols mStyle = new QgsStyle(); - mStyle->createMemoryDB(); + mStyle->createMemoryDb(); // cpt-city ramp, small selection available in /cpt-city QgsCptCityArchive::initArchives(); From 0a0b3a70cc27e6673e6d4500c48b04db63ede288 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 21 Nov 2016 14:06:53 +0700 Subject: [PATCH 871/897] [style] speed up importXML() by using SQL transaction Gains are significant, importing 100 symbols would take 2.86s, but takes only 0.18s when using transaction. --- src/core/symbology-ng/qgsstyle.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/core/symbology-ng/qgsstyle.cpp b/src/core/symbology-ng/qgsstyle.cpp index 7c8d13c5be35..a361fabdd9de 100644 --- a/src/core/symbology-ng/qgsstyle.cpp +++ b/src/core/symbology-ng/qgsstyle.cpp @@ -1555,6 +1555,11 @@ bool QgsStyle::importXml( const QString& filename ) QDomElement symbolsElement = docEl.firstChildElement( QStringLiteral( "symbols" ) ); QDomElement e = symbolsElement.firstChildElement(); + // gain speed by re-grouping the INSERT statements in a transaction + char* query; + query = sqlite3_mprintf( "BEGIN TRANSACTION;" ); + runEmptyQuery( query ); + if ( version == STYLE_CURRENT_VERSION ) { // For the new style, load symbols individualy @@ -1639,6 +1644,9 @@ bool QgsStyle::importXml( const QString& filename ) e = e.nextSiblingElement(); } + query = sqlite3_mprintf( "COMMIT TRANSACTION;" ); + runEmptyQuery( query ); + mFileName = filename; return true; } From e2265290b0dfb19f08baadd778b9915492a17732 Mon Sep 17 00:00:00 2001 From: nirvn Date: Mon, 21 Nov 2016 12:40:15 +0700 Subject: [PATCH 872/897] [style manager] refresh symbols shipped by default & add tags --- resources/symbology-ng-style.db | Bin 118784 -> 0 bytes resources/symbology-ng-style.xml | 5583 ++++++++++++++++++++++-------- 2 files changed, 4196 insertions(+), 1387 deletions(-) delete mode 100644 resources/symbology-ng-style.db diff --git a/resources/symbology-ng-style.db b/resources/symbology-ng-style.db deleted file mode 100644 index 6a62979ba86b7e608d0a74004b16482920f67442..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 118784 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 diff --git a/resources/symbology-ng-style.xml b/resources/symbology-ng-style.xml index 05fe215abd4f..723fae7d38cc 100644 --- a/resources/symbology-ng-style.xml +++ b/resources/symbology-ng-style.xml @@ -1,1452 +1,4237 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + - - - - - + + + + + - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - - - + + + + + - - - + + + - + - - - + + + - + - - - + + + - + @@ -1454,5 +4239,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + From 289423617f035108ecaa11a812546681b7a773af Mon Sep 17 00:00:00 2001 From: Hugo Mercier Date: Tue, 22 Nov 2016 11:55:53 +0100 Subject: [PATCH 873/897] [virtual] disable FilterRect when no unique id is present. Should fix #15134 --- .../qgsvirtuallayerfeatureiterator.cpp | 58 ++++++++++--------- tests/src/python/test_provider_virtual.py | 2 +- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp b/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp index c2f675c96219..cf237d9fe680 100644 --- a/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp +++ b/src/providers/virtual/qgsvirtuallayerfeatureiterator.cpp @@ -43,38 +43,42 @@ QgsVirtualLayerFeatureIterator::QgsVirtualLayerFeatureIterator( QgsVirtualLayerF wheres << subset; } - if ( mDefinition.hasDefinedGeometry() && !request.filterRect().isNull() ) + if ( !mDefinition.uid().isNull() ) { - bool do_exact = request.flags() & QgsFeatureRequest::ExactIntersect; - QgsRectangle rect( request.filterRect() ); - QString mbr = QStringLiteral( "%1,%2,%3,%4" ).arg( rect.xMinimum() ).arg( rect.yMinimum() ).arg( rect.xMaximum() ).arg( rect.yMaximum() ); - wheres << quotedColumn( mDefinition.geometryField() ) + " is not null"; - wheres << QStringLiteral( "%1Intersects(%2,BuildMbr(%3))" ) - .arg( do_exact ? "" : "Mbr", - quotedColumn( mDefinition.geometryField() ), - mbr ); - } - else if ( !mDefinition.uid().isNull() && request.filterType() == QgsFeatureRequest::FilterFid ) - { - wheres << QStringLiteral( "%1=%2" ) - .arg( quotedColumn( mDefinition.uid() ) ) - .arg( request.filterFid() ); - } - else if ( !mDefinition.uid().isNull() && request.filterType() == QgsFeatureRequest::FilterFids ) - { - QString values = quotedColumn( mDefinition.uid() ) + " IN ("; - bool first = true; - Q_FOREACH ( QgsFeatureId v, request.filterFids() ) + // filters are only available when a column with unique id exists + if ( mDefinition.hasDefinedGeometry() && !request.filterRect().isNull() ) + { + bool do_exact = request.flags() & QgsFeatureRequest::ExactIntersect; + QgsRectangle rect( request.filterRect() ); + QString mbr = QStringLiteral( "%1,%2,%3,%4" ).arg( rect.xMinimum() ).arg( rect.yMinimum() ).arg( rect.xMaximum() ).arg( rect.yMaximum() ); + wheres << quotedColumn( mDefinition.geometryField() ) + " is not null"; + wheres << QStringLiteral( "%1Intersects(%2,BuildMbr(%3))" ) + .arg( do_exact ? "" : "Mbr", + quotedColumn( mDefinition.geometryField() ), + mbr ); + } + else if ( request.filterType() == QgsFeatureRequest::FilterFid ) + { + wheres << QStringLiteral( "%1=%2" ) + .arg( quotedColumn( mDefinition.uid() ) ) + .arg( request.filterFid() ); + } + else if ( request.filterType() == QgsFeatureRequest::FilterFids ) { - if ( !first ) + QString values = quotedColumn( mDefinition.uid() ) + " IN ("; + bool first = true; + Q_FOREACH ( QgsFeatureId v, request.filterFids() ) { - values += QLatin1String( "," ); + if ( !first ) + { + values += QLatin1String( "," ); + } + first = false; + values += QString::number( v ); } - first = false; - values += QString::number( v ); + values += QLatin1String( ")" ); + wheres << values; } - values += QLatin1String( ")" ); - wheres << values; } mFields = mSource->provider()->fields(); diff --git a/tests/src/python/test_provider_virtual.py b/tests/src/python/test_provider_virtual.py index 851525702200..323363076985 100644 --- a/tests/src/python/test_provider_virtual.py +++ b/tests/src/python/test_provider_virtual.py @@ -446,7 +446,7 @@ def test_sql2(self): QgsMapLayerRegistry.instance().addMapLayer(l2) query = toPercent("SELECT * FROM france_parts") - l4 = QgsVectorLayer("?query=%s" % query, "tt", "virtual") + l4 = QgsVectorLayer("?query=%s&uid=ObjectId" % query, "tt", "virtual") self.assertEqual(l4.isValid(), True) self.assertEqual(l4.dataProvider().wkbType(), 3) From e3e70f7a8f559a4e74ccda385346d47aea300d55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Tue, 22 Nov 2016 10:01:35 +0100 Subject: [PATCH 874/897] [FEATURE] Broaden allowed geometries by checking WKBTypes --- python/plugins/processing/algs/qgis/SplitWithLines.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 40898022b7b0..15dccb131db9 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -26,7 +26,7 @@ __revision__ = '$Format:%H$' -from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes, QgsSpatialIndex +from qgis.core import QgsFeatureRequest, QgsFeature, QgsGeometry, QgsSpatialIndex, QgsWkbTypes, QgsMessageLog from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector @@ -147,6 +147,7 @@ def processAlgorithm(self, progress): if inPoints == vector.extractPoints(inGeom): # bug in splitGeometry: sometimes it returns 0 but # the geometry is unchanged + QgsMessageLog.logMessage("appending") outGeoms.append(inGeom) else: inGeoms.append(inGeom) @@ -154,6 +155,7 @@ def processAlgorithm(self, progress): for aNewGeom in newGeometries: inGeoms.append(aNewGeom) else: + QgsMessageLog.logMessage("appending else") outGeoms.append(inGeom) else: outGeoms.append(inGeom) @@ -163,7 +165,8 @@ def processAlgorithm(self, progress): for aGeom in inGeoms: passed = True - if aGeom.wkbType == 2 or aGeom.wkbType == -2147483646: + if QgsWkbTypes.geometryType( aGeom.wkbType() ) == QgsWkbTypes.LineGeometry \ + and not QgsWkbTypes.isMultiType( aGeom.wkbType() ): passed = len(aGeom.asPolyline()) > 2 if not passed: From b7fa5400b67cb91bb9e661dc734433de010e895f Mon Sep 17 00:00:00 2001 From: Hugo Mercier Date: Tue, 22 Nov 2016 16:09:53 +0100 Subject: [PATCH 875/897] [db manager] Fix virtual layer uid handling --- .../plugins/db_manager/db_plugins/vlayers/plugin.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/python/plugins/db_manager/db_plugins/vlayers/plugin.py b/python/plugins/db_manager/db_plugins/vlayers/plugin.py index 8217f730706b..023f0679ebbd 100644 --- a/python/plugins/db_manager/db_plugins/vlayers/plugin.py +++ b/python/plugins/db_manager/db_plugins/vlayers/plugin.py @@ -24,7 +24,7 @@ from qgis.PyQt.QtCore import QUrl from qgis.PyQt.QtGui import QIcon -from qgis.core import QgsVectorLayer, QgsMapLayerRegistry +from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsVirtualLayerDefinition from ..plugin import DBPlugin, Database, Table, VectorTable, TableField @@ -100,13 +100,14 @@ def sqlResultModel(self, sql, parent): return LSqlResultModel(self, sql, parent) def toSqlLayer(self, sql, geomCol, uniqueCol, layerName="QueryLayer", layerType=None, avoidSelectById=False, _filter=""): - q = QUrl.toPercentEncoding(sql) - s = "?query=%s" % q + df = QgsVirtualLayerDefinition() + df.setQuery(sql) if uniqueCol is not None: - s += "&uid=" + uniqueCol + uniqueCol = uniqueCol.strip('"').replace('""', '"') + df.setUid(uniqueCol) if geomCol is not None: - s += "&geometry=" + geomCol - vl = QgsVectorLayer(s, layerName, "virtual") + df.setGeometryField(geomCol) + vl = QgsVectorLayer(df.toString(), layerName, "virtual") if _filter: vl.setSubsetString(_filter) return vl From dc82ad4c788872787ca02d73595813b151bdff93 Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Tue, 22 Nov 2016 19:57:43 +0200 Subject: [PATCH 876/897] fix typo --- src/analysis/network/qgsnetworkspeedstrategy.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysis/network/qgsnetworkspeedstrategy.h b/src/analysis/network/qgsnetworkspeedstrategy.h index 6c56c7fdaca1..c19eac39b10c 100644 --- a/src/analysis/network/qgsnetworkspeedstrategy.h +++ b/src/analysis/network/qgsnetworkspeedstrategy.h @@ -21,7 +21,7 @@ /** \ingroup analysis * \class QgsNetworkSpeedStrategy * \note added in QGIS 3.0 - * \brief Strategy for calcucating edge cost based on travel time. Should be + * \brief Strategy for calculating edge cost based on travel time. Should be * used for finding fastest path between two points. */ class ANALYSIS_EXPORT QgsNetworkSpeedStrategy : public QgsNetworkStrategy From ee80be4317f25bc997bad7bc5f5ecd36590fd949 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 23 Nov 2016 08:23:23 +1000 Subject: [PATCH 877/897] Fix misleading indentation warnings caused by messy qtermwidget code formatting --- src/plugins/grass/qtermwidget/CharacterColor.h | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/plugins/grass/qtermwidget/CharacterColor.h b/src/plugins/grass/qtermwidget/CharacterColor.h index 08f44c8211e5..248885ca8c0f 100644 --- a/src/plugins/grass/qtermwidget/CharacterColor.h +++ b/src/plugins/grass/qtermwidget/CharacterColor.h @@ -256,16 +256,23 @@ inline bool operator != (const CharacterColor& a, const CharacterColor& b) inline const QColor color256(quint8 u, const ColorEntry* base) { // 0.. 16: system colors - if (u < 8) return base[u+2 ].color; u -= 8; - if (u < 8) return base[u+2+BASE_COLORS].color; u -= 8; + if (u < 8) + return base[u+2].color; + u -= 8; + if (u < 8) + return base[u+2+BASE_COLORS].color; + u -= 8; // 16..231: 6x6x6 rgb color cube - if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, + if (u < 216) + return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, - ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); u -= 216; + ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); + u -= 216; // 232..255: gray, leaving out black and white - int gray = u*10+8; return QColor(gray,gray,gray); + int gray = u*10+8; + return QColor(gray,gray,gray); } inline QColor CharacterColor::color(const ColorEntry* base) const From 311f4827253c88e2bc62a591c661535e1f997115 Mon Sep 17 00:00:00 2001 From: Nathan Date: Sun, 5 Jun 2016 15:29:53 +1000 Subject: [PATCH 878/897] Move profiler instance to QgsApplication --- doc/api_break.dox | 4 ++++ python/core/qgsapplication.sip | 6 ++++++ python/core/qgsruntimeprofiler.sip | 7 ------- src/app/qgisapp.cpp | 19 ++++++++----------- src/app/qgisapp.h | 2 -- src/core/qgsapplication.cpp | 8 ++++++++ src/core/qgsapplication.h | 8 ++++++++ src/core/qgsruntimeprofiler.cpp | 9 --------- src/core/qgsruntimeprofiler.h | 9 --------- 9 files changed, 34 insertions(+), 38 deletions(-) diff --git a/doc/api_break.dox b/doc/api_break.dox index de55e62ca598..2689476bc9de 100644 --- a/doc/api_break.dox +++ b/doc/api_break.dox @@ -1363,6 +1363,10 @@ QgsRuleBasedRendererWidget {#qgis_api_break_3_0_QgsRuleBasedRendererWidge - refineRuleCategoriesGui() and refineRuleRangesGui() no longer take a QModelIndexList argument. +QgsRuntimeProfiler {#qgis_api_break_3_0_QgsRuntimeProfiler} +------------------ + +- This class is no longer a singleton and instance() has been removed. Instead use QgsApplication::profiler() to access an application-wide profiler. QgsSimpleMarkerSymbolLayer {#qgis_api_break_3_0_QgsSimpleMarkerSymbolLayer} -------------------------- diff --git a/python/core/qgsapplication.sip b/python/core/qgsapplication.sip index ce464b8117f0..8a76c67288bd 100644 --- a/python/core/qgsapplication.sip +++ b/python/core/qgsapplication.sip @@ -385,6 +385,12 @@ static void qtgui_UpdatePyArgv(PyObject *argvlist, int argc, char **argv) */ static QgsActionScopeRegistry* actionScopeRegistry(); + /** + * Returns the application runtime profiler. + * @note added in QGIS 3.0 + */ + static QgsRuntimeProfiler* profiler(); + public slots: /** Causes the application instance to emit the settingsChanged() signal. This should diff --git a/python/core/qgsruntimeprofiler.sip b/python/core/qgsruntimeprofiler.sip index fab11062f7cc..39dc43d022cc 100644 --- a/python/core/qgsruntimeprofiler.sip +++ b/python/core/qgsruntimeprofiler.sip @@ -11,13 +11,6 @@ class QgsRuntimeProfiler */ QgsRuntimeProfiler(); - /** - * @brief Begin the group for the profiler. Groups will append {GroupName}/ to the - * front of the profile tag set using start. - * @param name The name of the group. - */ - static QgsRuntimeProfiler * instance(); - /** * @brief Begin the group for the profiler. Groups will append {GroupName}/ to the * front of the profile tag set using start. diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index bda5bc775603..ac6213c13b84 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -564,7 +564,6 @@ QgisApp *QgisApp::smInstance = nullptr; // constructor starts here QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCheck, QWidget * parent, Qt::WindowFlags fl ) : QMainWindow( parent, fl ) - , mProfiler( nullptr ) , mNonEditMapTool( nullptr ) , mScaleWidget( nullptr ) , mMagnifierWidget( nullptr ) @@ -609,13 +608,13 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh } smInstance = this; - mProfiler = QgsRuntimeProfiler::instance(); + QgsRuntimeProfiler* profiler = QgsApplication::profiler(); namSetup(); // load GUI: actions, menus, toolbars - mProfiler->beginGroup( QStringLiteral( "qgisapp" ) ); - mProfiler->beginGroup( QStringLiteral( "startup" ) ); + profiler->beginGroup( QStringLiteral( "qgisapp" ) ); + profiler->beginGroup( QStringLiteral( "startup" ) ); startProfile( QStringLiteral( "Setting up UI" ) ); setupUi( this ); endProfile(); @@ -1105,13 +1104,12 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh #ifdef ANDROID toggleFullScreen(); #endif - mProfiler->endGroup(); - mProfiler->endGroup(); + profiler->endGroup(); QgsDebugMsg( "PROFILE TIMES" ); - QgsDebugMsg( QString( "PROFILE TIMES TOTAL - %1 " ).arg( mProfiler->totalTime() ) ); + QgsDebugMsg( QString( "PROFILE TIMES TOTAL - %1 " ).arg( profiler->totalTime() ) ); #ifdef QGISDEBUG - QList > profileTimes = mProfiler->profileTimes(); + QList > profileTimes = profiler->profileTimes(); QList >::const_iterator it = profileTimes.constBegin(); for ( ; it != profileTimes.constEnd(); ++it ) { @@ -1125,7 +1123,6 @@ QgisApp::QgisApp( QSplashScreen *splash, bool restorePlugins, bool skipVersionCh QgisApp::QgisApp() : QMainWindow( nullptr, 0 ) - , mProfiler( nullptr ) , mStyleSheetBuilder( nullptr ) , mActionPluginSeparator1( nullptr ) , mActionPluginSeparator2( nullptr ) @@ -11265,12 +11262,12 @@ void QgisApp::onSnappingConfigChanged() void QgisApp::startProfile( const QString& name ) { - mProfiler->start( name ); + QgsApplication::profiler()->start( name ); } void QgisApp::endProfile() { - mProfiler->end(); + QgsApplication::profiler()->end(); } void QgisApp::functionProfile( void ( QgisApp::*fnc )(), QgisApp* instance, QString name ) diff --git a/src/app/qgisapp.h b/src/app/qgisapp.h index cbf2a7a393d4..8e3cba243d68 100644 --- a/src/app/qgisapp.h +++ b/src/app/qgisapp.h @@ -1430,8 +1430,6 @@ class APP_EXPORT QgisApp : public QMainWindow, private Ui::MainWindow void endProfile(); void functionProfile( void ( QgisApp::*fnc )(), QgisApp *instance, QString name ); - QgsRuntimeProfiler* mProfiler; - /** This method will open a dialog so the user can select GDAL sublayers to load * @returns true if any items were loaded */ diff --git a/src/core/qgsapplication.cpp b/src/core/qgsapplication.cpp index 32b22a1d59f9..720141fe672c 100644 --- a/src/core/qgsapplication.cpp +++ b/src/core/qgsapplication.cpp @@ -24,6 +24,7 @@ #include "qgsproviderregistry.h" #include "qgsexpression.h" #include "qgsactionscoperegistry.h" +#include "qgsruntimeprofiler.h" #include #include @@ -104,6 +105,7 @@ QgsApplication::QgsApplication( int & argc, char ** argv, bool GUIenabled, const { sPlatformName = platformName; + mProfiler = new QgsRuntimeProfiler(); mActionScopeRegistry = new QgsActionScopeRegistry(); init( customConfigPath ); // init can also be called directly by e.g. unit tests that don't inherit QApplication. @@ -237,6 +239,7 @@ void QgsApplication::init( QString customConfigPath ) QgsApplication::~QgsApplication() { delete mActionScopeRegistry; + delete mProfiler; } QgsApplication* QgsApplication::instance() @@ -310,6 +313,11 @@ bool QgsApplication::notify( QObject * receiver, QEvent * event ) return done; } +QgsRuntimeProfiler *QgsApplication::profiler() +{ + return instance()->mProfiler; +} + void QgsApplication::setFileOpenEventReceiver( QObject * receiver ) { // Set receiver for FileOpen events diff --git a/src/core/qgsapplication.h b/src/core/qgsapplication.h index 152f1b42d120..7461b9f9b864 100644 --- a/src/core/qgsapplication.h +++ b/src/core/qgsapplication.h @@ -23,6 +23,7 @@ #include class QgsActionScopeRegistry; +class QgsRuntimeProfiler; /** \ingroup core * Extends QApplication to provide access to QGIS specific resources such @@ -381,6 +382,12 @@ class CORE_EXPORT QgsApplication : public QApplication */ static QgsActionScopeRegistry* actionScopeRegistry(); + /** + * Returns the application runtime profiler. + * @note added in QGIS 3.0 + */ + static QgsRuntimeProfiler* profiler(); + public slots: /** Causes the application instance to emit the settingsChanged() signal. This should @@ -448,6 +455,7 @@ class CORE_EXPORT QgsApplication : public QApplication QMap mIconCache; QgsActionScopeRegistry* mActionScopeRegistry; + QgsRuntimeProfiler* mProfiler; }; #endif diff --git a/src/core/qgsruntimeprofiler.cpp b/src/core/qgsruntimeprofiler.cpp index 87f5e6161126..c69e6ce080ab 100644 --- a/src/core/qgsruntimeprofiler.cpp +++ b/src/core/qgsruntimeprofiler.cpp @@ -2,15 +2,6 @@ #include "qgslogger.h" -QgsRuntimeProfiler* QgsRuntimeProfiler::mInstance = nullptr; - -QgsRuntimeProfiler* QgsRuntimeProfiler::instance() -{ - if ( !mInstance ) - mInstance = new QgsRuntimeProfiler(); - return mInstance; -} - QgsRuntimeProfiler::QgsRuntimeProfiler() { diff --git a/src/core/qgsruntimeprofiler.h b/src/core/qgsruntimeprofiler.h index 6a0dd496a4eb..5ad6ecd7b3fb 100644 --- a/src/core/qgsruntimeprofiler.h +++ b/src/core/qgsruntimeprofiler.h @@ -17,13 +17,6 @@ class CORE_EXPORT QgsRuntimeProfiler */ QgsRuntimeProfiler(); - /** - * @brief Instance of the run time profiler. To use the main profiler - * use this instance. - * @return The instance of the run time profiler - */ - static QgsRuntimeProfiler * instance(); - /** * @brief Begin the group for the profiler. Groups will append {GroupName}/ to the * front of the profile tag set using start. @@ -67,8 +60,6 @@ class CORE_EXPORT QgsRuntimeProfiler double totalTime(); private: - static QgsRuntimeProfiler* mInstance; - QString mGroupPrefix; QStack mGroupStack; QTime mProfileTime; From 3c51a93f6a3bceace0ad1dbf8779f17a78193361 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 23 Nov 2016 14:37:05 +1000 Subject: [PATCH 879/897] [processing] Fix very broken delete columns algorithm --- python/plugins/processing/algs/help/qgis.yaml | 2 +- .../processing/algs/qgis/DeleteColumn.py | 30 ++++++----- .../tests/testdata/expected/delete_column.gfs | 27 ++++++++++ .../tests/testdata/expected/delete_column.gml | 53 +++++++++++++++++++ .../testdata/expected/delete_columns.gfs | 21 ++++++++ .../testdata/expected/delete_columns.gml | 48 +++++++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 26 ++++++++- 7 files changed, 193 insertions(+), 14 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/delete_column.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/delete_column.gml create mode 100644 python/plugins/processing/tests/testdata/expected/delete_columns.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/delete_columns.gml diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index b9492fffdf78..543d13307034 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -115,7 +115,7 @@ qgis:delaunaytriangulation: > This algorithm creates a polygon layer with the delaunay triangulation corresponding to a points layer. qgis:deletecolumn: > - This algorithm takes a vector layer and generates a new one that has the exact same content but without one of its columns. + This algorithm takes a vector layer and generates a new one that has the exact same content but without the selected columns. qgis:deleteduplicategeometries: > This algorithm finds duplicated geometries and removes them. Attributes are not checked, so in case two feature have identical geometries but different attributes, only one of them will be added to the result layer. diff --git a/python/plugins/processing/algs/qgis/DeleteColumn.py b/python/plugins/processing/algs/qgis/DeleteColumn.py index 484f0d032d94..c08b098a5c41 100644 --- a/python/plugins/processing/algs/qgis/DeleteColumn.py +++ b/python/plugins/processing/algs/qgis/DeleteColumn.py @@ -42,6 +42,7 @@ class DeleteColumn(GeoAlgorithm): def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Delete column') self.group, self.i18n_group = self.trAlgorithm('Vector table tools') + self.tags = self.tr('drop,delete,remove,fields,columns,attributes') self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'))) @@ -52,13 +53,20 @@ def defineCharacteristics(self): def processAlgorithm(self, progress): layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) - toDelete = self.getParameterValue(self.COLUMNS) + fields_to_delete = self.getParameterValue(self.COLUMNS).split(';') fields = layer.fields() - idxs = [] - for f in toDelete: - idx = layer.fieldNameIndex() - fields.remove(idx) - idxs.append[idx] + field_indices = [] + # loop through twice - first we need to build up a list of original attribute indices + for f in fields_to_delete: + index = fields.lookupField(f) + field_indices.append(index) + + # important - make sure we remove from the end so we aren't changing used indices as we go + field_indices.sort(reverse=True) + + # this second time we make a cleaned version of the fields + for index in field_indices: + fields.remove(index) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fields, layer.wkbType(), layer.crs()) @@ -66,14 +74,12 @@ def processAlgorithm(self, progress): features = vector.features(layer) total = 100.0 / len(features) - feat = QgsFeature() for current, f in enumerate(features): - feat.setGeometry(f.geometry()) attributes = f.attributes() - for idx in idxs: - del attributes[idx] - feat.setAttributes(attributes) - writer.addFeature(feat) + for index in field_indices: + del attributes[index] + f.setAttributes(attributes) + writer.addFeature(f) progress.setPercentage(int(current * total)) diff --git a/python/plugins/processing/tests/testdata/expected/delete_column.gfs b/python/plugins/processing/tests/testdata/expected/delete_column.gfs new file mode 100644 index 000000000000..a4e8eae7d677 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/delete_column.gfs @@ -0,0 +1,27 @@ + + + delete_column + delete_column + + 3 + EPSG:4326 + + 6 + -1.00000 + 10.00000 + -3.00000 + 6.00000 + + + name + name + String + 5 + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/delete_column.gml b/python/plugins/processing/tests/testdata/expected/delete_column.gml new file mode 100644 index 000000000000..e4f2c02c748d --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/delete_column.gml @@ -0,0 +1,53 @@ + + + + + -1-3 + 106 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 44.123456 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + 0 + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.123 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + ASDF + + + + + -100291.43213 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 3.33 + + + diff --git a/python/plugins/processing/tests/testdata/expected/delete_columns.gfs b/python/plugins/processing/tests/testdata/expected/delete_columns.gfs new file mode 100644 index 000000000000..146999076ab9 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/delete_columns.gfs @@ -0,0 +1,21 @@ + + + delete_columns + delete_columns + + 3 + EPSG:4326 + + 6 + -1.00000 + 10.00000 + -3.00000 + 6.00000 + + + intval + intval + Integer + + + diff --git a/python/plugins/processing/tests/testdata/expected/delete_columns.gml b/python/plugins/processing/tests/testdata/expected/delete_columns.gml new file mode 100644 index 000000000000..9a4b4727be02 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/delete_columns.gml @@ -0,0 +1,48 @@ + + + + + -1-3 + 106 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + 33 + + + + + 5,5 6,4 4,4 5,5 + -33 + + + + + 2,5 2,6 3,6 3,5 2,5 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + 0 + + + + + 120 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + 2 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 5082794246fc..0fc4ea6a49df 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1551,4 +1551,28 @@ tests: INPUT: name: lines.gml type: vector - results: {} \ No newline at end of file + results: {} + + - algorithm: qgis:deletecolumn + name: Delete columns (multiple) + params: + COLUMN: floatval;name + INPUT: + name: polys.gml + type: vector + results: + OUTPUT: + name: expected/delete_columns.gml + type: vector + + - algorithm: qgis:deletecolumn + name: Delete columns (single) + params: + COLUMN: intval + INPUT: + name: polys.gml + type: vector + results: + OUTPUT: + name: expected/delete_column.gml + type: vector From 489e00df8d086966815d31519b21d9203c0e955a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 23 Nov 2016 15:44:37 +1000 Subject: [PATCH 880/897] [processing] Enhance create points layer alg Clean up code, allow setting z/m columns --- .../algs/qgis/PointsLayerFromTable.py | 69 ++++++++++++++----- .../processing/tests/ParametersTest.py | 17 +++++ 2 files changed, 68 insertions(+), 18 deletions(-) diff --git a/python/plugins/processing/algs/qgis/PointsLayerFromTable.py b/python/plugins/processing/algs/qgis/PointsLayerFromTable.py index 9a28da31d9a4..01b5718acefb 100644 --- a/python/plugins/processing/algs/qgis/PointsLayerFromTable.py +++ b/python/plugins/processing/algs/qgis/PointsLayerFromTable.py @@ -25,11 +25,9 @@ __revision__ = '$Format:%H$' -from qgis.core import Qgis, QgsWkbTypes +from qgis.core import Qgis, QgsWkbTypes, QgsPointV2 from qgis.core import QgsCoordinateReferenceSystem -from qgis.core import QgsFeature from qgis.core import QgsGeometry -from qgis.core import QgsPoint from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterTable from processing.core.parameters import ParameterTableField @@ -43,18 +41,25 @@ class PointsLayerFromTable(GeoAlgorithm): INPUT = 'INPUT' XFIELD = 'XFIELD' YFIELD = 'YFIELD' + ZFIELD = 'ZFIELD' + MFIELD = 'MFIELD' OUTPUT = 'OUTPUT' TARGET_CRS = 'TARGET_CRS' def defineCharacteristics(self): - self.name, self.i18n_name = self.trAlgorithm('Points layer from table') + self.name, self.i18n_name = self.trAlgorithm('Create points layer from table') self.group, self.i18n_group = self.trAlgorithm('Vector creation tools') + self.tags = self.tr('points,create,values,attributes') self.addParameter(ParameterTable(self.INPUT, self.tr('Input layer'))) self.addParameter(ParameterTableField(self.XFIELD, self.tr('X field'), self.INPUT, ParameterTableField.DATA_TYPE_ANY)) self.addParameter(ParameterTableField(self.YFIELD, self.tr('Y field'), self.INPUT, ParameterTableField.DATA_TYPE_ANY)) + self.addParameter(ParameterTableField(self.ZFIELD, + self.tr('Z field'), self.INPUT, datatype=ParameterTableField.DATA_TYPE_ANY, optional=True)) + self.addParameter(ParameterTableField(self.MFIELD, + self.tr('M field'), self.INPUT, datatype=ParameterTableField.DATA_TYPE_ANY, optional=True)) self.addParameter(ParameterCrs(self.TARGET_CRS, self.tr('Target CRS'), 'EPSG:4326')) self.addOutput(OutputVector(self.OUTPUT, self.tr('Points from table'), datatype=[dataobjects.TYPE_VECTOR_POINT])) @@ -63,30 +68,58 @@ def processAlgorithm(self, progress): source = self.getParameterValue(self.INPUT) vlayer = dataobjects.getObjectFromUri(source) output = self.getOutputFromName(self.OUTPUT) + fields = vlayer.fields() - writer = output.getVectorWriter(fields, QgsWkbTypes.Point, self.crs) - xfieldindex = vlayer.fields().lookupField(self.getParameterValue(self.XFIELD)) - yfieldindex = vlayer.fields().lookupField(self.getParameterValue(self.YFIELD)) + x_field_index = fields.lookupField(self.getParameterValue(self.XFIELD)) + y_field_index = fields.lookupField(self.getParameterValue(self.YFIELD)) + z_field_index = None + if self.getParameterValue(self.ZFIELD): + z_field_index = fields.lookupField(self.getParameterValue(self.ZFIELD)) + m_field_index = None + if self.getParameterValue(self.MFIELD): + m_field_index = fields.lookupField(self.getParameterValue(self.MFIELD)) + + wkb_type = QgsWkbTypes.Point + if z_field_index is not None: + wkb_type = QgsWkbTypes.addZ(wkb_type) + if m_field_index is not None: + wkb_type = QgsWkbTypes.addM(wkb_type) crsId = self.getParameterValue(self.TARGET_CRS) - targetCrs = QgsCoordinateReferenceSystem() - targetCrs.createFromUserInput(crsId) - self.crs = targetCrs + target_crs = QgsCoordinateReferenceSystem() + target_crs.createFromUserInput(crsId) + + writer = output.getVectorWriter(fields, wkb_type, target_crs) - outFeat = QgsFeature() features = vector.features(vlayer) total = 100.0 / len(features) + for current, feature in enumerate(features): progress.setPercentage(int(current * total)) attrs = feature.attributes() + try: - x = float(attrs[xfieldindex]) - y = float(attrs[yfieldindex]) + x = float(attrs[x_field_index]) + y = float(attrs[y_field_index]) + + point = QgsPointV2(x, y) + + if z_field_index is not None: + try: + point.addZValue(float(attrs[z_field_index])) + except: + point.addZValue(0.0) + + if m_field_index is not None: + try: + point.addMValue(float(attrs[m_field_index])) + except: + point.addMValue(0.0) + + feature.setGeometry(QgsGeometry(point)) except: - continue - pt = QgsPoint(x, y) - outFeat.setGeometry(QgsGeometry.fromPoint(pt)) - outFeat.setAttributes(attrs) - writer.addFeature(outFeat) + pass # no geometry + + writer.addFeature(feature) del writer diff --git a/python/plugins/processing/tests/ParametersTest.py b/python/plugins/processing/tests/ParametersTest.py index c98007bef92b..5da37bd965dc 100644 --- a/python/plugins/processing/tests/ParametersTest.py +++ b/python/plugins/processing/tests/ParametersTest.py @@ -39,6 +39,7 @@ ParameterPoint, ParameterString, ParameterVector, + ParameterTable, ParameterTableField, ParameterSelection, ParameterExpression, @@ -631,5 +632,21 @@ def testScriptCode(self): self.assertTrue(isinstance(result, ParameterTableField)) self.assertTrue(result.optional) + +class ParameterTableTest(unittest.TestCase): + + def testScriptCode(self): + parameter = ParameterTable( + 'myName', 'myDesc') + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterTable)) + + parameter.optional = True + code = parameter.getAsScriptCode() + result = getParameterFromString(code) + self.assertTrue(isinstance(result, ParameterTable)) + self.assertTrue(result.optional) + if __name__ == '__main__': unittest.main() From 2652aa50c913dd55cf85431bdb9eddae200a0470 Mon Sep 17 00:00:00 2001 From: nirvn Date: Wed, 23 Nov 2016 12:05:58 +0700 Subject: [PATCH 881/897] [processing] improve the modeler dialog UI and icons - use a proper toolbar to match other parts of QGIS - show keyboard shortcuts in toolbar action tooltips - create vector icons to replace PNG ones --- images/images.qrc | 3 + .../themes/default/mActionEditHelpContent.svg | 1180 ++++ images/themes/default/mActionSaveAsPython.svg | 4890 +++++++++++++++++ images/themes/default/mActionStart.svg | 69 + .../processing/modeler/ModelerDialog.py | 35 +- python/plugins/processing/ui/DlgModeler.ui | 476 +- 6 files changed, 6388 insertions(+), 265 deletions(-) create mode 100644 images/themes/default/mActionEditHelpContent.svg create mode 100644 images/themes/default/mActionSaveAsPython.svg create mode 100644 images/themes/default/mActionStart.svg diff --git a/images/images.qrc b/images/images.qrc index 49a8f09be127..918eeaafb434 100644 --- a/images/images.qrc +++ b/images/images.qrc @@ -114,6 +114,7 @@ themes/default/mActionAddBasicShape.svg themes/default/mActionAddBasicCircle.svg themes/default/mActionEditNodesItem.svg + themes/default/mActionEditHelpContent.svg themes/default/mActionAddNodesItem.svg themes/default/mActionAddPolygon.svg themes/default/mActionAddPolyline.svg @@ -278,6 +279,7 @@ themes/default/mActionRotatePointSymbols.svg themes/default/mActionSaveAllEdits.svg themes/default/mActionSaveAsPDF.svg + themes/default/mActionSaveAsPython.svg themes/default/mActionSaveAsSVG.svg themes/default/mActionSaveEdits.svg themes/default/mActionSaveMapAsImage.svg @@ -307,6 +309,7 @@ themes/default/mActionSimplify.svg themes/default/mActionSplitFeatures.svg themes/default/mActionSplitParts.svg + themes/default/mActionStart.svg themes/default/mActionSum.svg themes/default/mActionTextAnnotation.svg themes/default/mActionToggleEditing.svg diff --git a/images/themes/default/mActionEditHelpContent.svg b/images/themes/default/mActionEditHelpContent.svg new file mode 100644 index 000000000000..b65f5a73910c --- /dev/null +++ b/images/themes/default/mActionEditHelpContent.svg @@ -0,0 +1,1180 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/images/themes/default/mActionSaveAsPython.svg b/images/themes/default/mActionSaveAsPython.svg new file mode 100644 index 000000000000..cf6e9cd0fea4 --- /dev/null +++ b/images/themes/default/mActionSaveAsPython.svg @@ -0,0 +1,4890 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images/themes/default/mActionStart.svg b/images/themes/default/mActionStart.svg new file mode 100644 index 000000000000..669c356c74ab --- /dev/null +++ b/images/themes/default/mActionStart.svg @@ -0,0 +1,69 @@ + + + + + + + + + + + + image/svg+xml + + + + + + + + diff --git a/python/plugins/processing/modeler/ModelerDialog.py b/python/plugins/processing/modeler/ModelerDialog.py index 2e0426dba17f..ef36ceaaf9fd 100644 --- a/python/plugins/processing/modeler/ModelerDialog.py +++ b/python/plugins/processing/modeler/ModelerDialog.py @@ -31,7 +31,7 @@ import os from qgis.PyQt import uic -from qgis.PyQt.QtCore import Qt, QRectF, QMimeData, QPoint, QPointF, QSettings, QByteArray, pyqtSignal +from qgis.PyQt.QtCore import Qt, QRectF, QMimeData, QPoint, QPointF, QSettings, QByteArray, QSize, pyqtSignal from qgis.PyQt.QtWidgets import QGraphicsView, QTreeWidget, QMessageBox, QFileDialog, QTreeWidgetItem, QSizePolicy from qgis.PyQt.QtGui import QIcon, QImage, QPainter from qgis.core import QgsApplication @@ -65,7 +65,7 @@ def __init__(self, alg=None): self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) - self.layout().insertWidget(1, self.bar) + self.centralWidget().layout().insertWidget(1, self.bar) self.zoom = 1 @@ -74,8 +74,9 @@ def __init__(self, alg=None): Qt.WindowCloseButtonHint) settings = QSettings() - self.splitter.restoreState(settings.value("/Processing/splitterModeler", QByteArray())) + self.restoreState(settings.value("/Processing/stateModeler", QByteArray())) self.restoreGeometry(settings.value("/Processing/geometryModeler", QByteArray())) + self.splitter.restoreState(settings.value("/Processing/stateModelerSplitter", QByteArray())) self.tabWidget.setCurrentIndex(0) self.scene = ModelerScene(self) @@ -185,15 +186,6 @@ def _mimeDataAlgorithm(items): self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly) self.algorithmTree.setDropIndicatorShown(True) - # Set icons - self.btnOpen.setIcon(QgsApplication.getThemeIcon('/mActionFileOpen.svg')) - self.btnSave.setIcon(QgsApplication.getThemeIcon('/mActionFileSave.svg')) - self.btnSaveAs.setIcon(QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) - self.btnExportImage.setIcon(QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg')) - self.btnExportPython.setIcon(QgsApplication.getThemeIcon('/console/iconSaveAsConsole.png')) - self.btnEditHelp.setIcon(QIcon(os.path.join(pluginPath, 'images', 'edithelp.png'))) - self.btnRun.setIcon(QIcon(os.path.join(pluginPath, 'images', 'runalgorithm.png'))) - if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(self.tr('Search...')) if hasattr(self.textName, 'setPlaceholderText'): @@ -206,13 +198,15 @@ def _mimeDataAlgorithm(items): self.searchBox.textChanged.connect(self.fillAlgorithmTree) self.algorithmTree.doubleClicked.connect(self.addAlgorithm) - self.btnOpen.clicked.connect(self.openModel) - self.btnSave.clicked.connect(self.save) - self.btnSaveAs.clicked.connect(self.saveAs) - self.btnExportImage.clicked.connect(self.exportAsImage) - self.btnExportPython.clicked.connect(self.exportAsPython) - self.btnEditHelp.clicked.connect(self.editHelp) - self.btnRun.clicked.connect(self.runModel) + iconSize = settings.value("iconsize", 24) + self.mToolbar.setIconSize(QSize(iconSize, iconSize)) + self.mActionOpen.triggered.connect(self.openModel) + self.mActionSave.triggered.connect(self.save) + self.mActionSaveAs.triggered.connect(self.saveAs) + self.mActionExportImage.triggered.connect(self.exportAsImage) + self.mActionExportPython.triggered.connect(self.exportAsPython) + self.mActionEditHelp.triggered.connect(self.editHelp) + self.mActionRun.triggered.connect(self.runModel) if alg is not None: self.alg = alg @@ -235,8 +229,9 @@ def _mimeDataAlgorithm(items): def closeEvent(self, evt): settings = QSettings() - settings.setValue("/Processing/splitterModeler", self.splitter.saveState()) + settings.setValue("/Processing/stateModeler", self.saveState()) settings.setValue("/Processing/geometryModeler", self.saveGeometry()) + settings.setValue("/Processing/stateModelerSplitter", self.splitter.saveState()) if self.hasChanged: ret = QMessageBox.question( diff --git a/python/plugins/processing/ui/DlgModeler.ui b/python/plugins/processing/ui/DlgModeler.ui index 5f1c018dcbd7..1fb8879c5133 100644 --- a/python/plugins/processing/ui/DlgModeler.ui +++ b/python/plugins/processing/ui/DlgModeler.ui @@ -1,7 +1,7 @@ DlgModeler - + 0 @@ -13,269 +13,255 @@ Processing modeler - - - 6 - - - 9 - - - - - 6 - - - 3 - - - - - Open model - - - ... - - - Ctrl+O - - - true - - - - - - - Save - - - ... - - - Ctrl+S - - - true - - - - - - - Save as... - - - ... - - - Ctrl+Shift+S - - - true - - - - - - - Qt::Vertical - - - - - - - Export as image - - - ... - - - true - - - - - - - Export as Python script - - - ... - - - true - - - - - - - Qt::Vertical - - - - - - - Edit model help - - - ... - - - true - - - - - - - Qt::Vertical - - - - - - - Run model - - - ... + + + + 3 + + + 6 + + + + + Qt::Horizontal + + + + + 300 + 0 + - - F5 + + QTabWidget::South - - true + + 1 + + + Inputs + + + + 4 + + + 0 + + + + + true + + + false + + + + 1 + + + + + + + + + Algorithms + + + + 4 + + + 0 + + + + + Enter algorithm name to filter list + + + + + + + true + + + false + + + + 1 + + + + + + - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - Qt::Horizontal - - - - - 300 - 0 - - - - QTabWidget::South - - - 1 - - - - Inputs - - + + - 2 - - - 0 + 4 - - - - true + + + + Model - - false - - - - 1 - - - - - - - Algorithms - - - - 2 - - - 0 - - - + + - Enter algorithm name to filter list + Enter model name here - - - - true + + + + Group + + + + + + + Enter group name here - - false - - - - 1 - - + + + - - - - 2 - - - - - Enter model name here - - - - - - - Enter group name here - - - - - - - - - - - + + + + + + Navigation + + + TopToolBarArea + + + true + + + + + + + + + + + + + + + + :/images/themes/default/mActionFileOpen.svg:/images/themes/default/mActionFileOpen.svg + + + Open model... + + + Open model (Ctrl+O) + + + Ctrl+O + + + + + + :/images/themes/default/mActionFileSave.svg:/images/themes/default/mActionFileSave.svg + + + Save model + + + Save model (Ctrl+S) + + + Ctrl+S + + + + + + :/images/themes/default/mActionFileSaveAs.svg:/images/themes/default/mActionFileSaveAs.svg + + + Save model as... + + + Save model as (Ctrl+S) + + + Ctrl+Shift+S + + + + + + :/images/themes/default/mActionSaveMapAsImage.svg:/images/themes/default/mActionSaveMapAsImage.svg + + + Export as image... + + + Export as image + + + + + + :/images/themes/default/mActionSaveAsPython.svg:/images/themes/default/mActionSaveAsPython.svg + + + Export as Python script... + + + Export as Python script + + + + + + :/images/themes/default/mActionEditHelpContent.svg:/images/themes/default/mActionEditHelpContent.svg + + + Edit model help... + + + Edit model help + + + + + + :/images/themes/default/mActionStart.svg:/images/themes/default/mActionStart.svg + + + Run model... + + + Run model (F5) + + + F5 + + From d559d7ff2525072efa02ca376c498250d2143fd5 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Wed, 23 Nov 2016 09:26:44 +0100 Subject: [PATCH 882/897] Partially revert 9bb3235 The -DCMAKE_POSITION_INDEPENDENT_CODE=ON resolves to -fPIE instead of -fPIC (on some platforms?) rendering cmake broken. --- cmake/QCAMacros.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/QCAMacros.cmake b/cmake/QCAMacros.cmake index 0b46554351f1..5df3611e91e6 100644 --- a/cmake/QCAMacros.cmake +++ b/cmake/QCAMacros.cmake @@ -13,7 +13,7 @@ function(FIND_QCAOSSL_PLUGIN_CPP PLUGIN_REQUIRED) # requires Qt and QCA packages to be found - if(QT_INCLUDES AND Qt5Core_LIBRARIES + if(QT_INCLUDE_DIR AND QT_QTCORE_INCLUDE_DIR AND QT_QTCORE_LIBRARY AND QCA_INCLUDE_DIR AND QCA_LIBRARY AND NOT CMAKE_CROSSCOMPILING) From f71430efa52e956d85a8b1d44d02f1289ff1cbeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Wed, 28 Sep 2016 16:41:12 +0200 Subject: [PATCH 883/897] [processing] [FEATURE] SplitWithLines Rename algorithm SplitLinesWithLines to SplitWithLines Accept polygon as input, too Use only selected lines to split with (if processing is set to use selection only) Issue log message if trying to split multi geometries Update help --- python/plugins/processing/algs/help/qgis.yaml | 4 +- .../algs/qgis/QGISAlgorithmProvider.py | 4 +- .../algs/qgis/SplitLinesWithLines.py | 150 --------------- .../processing/algs/qgis/SplitWithLines.py | 173 ++++++++++++++++++ 4 files changed, 177 insertions(+), 154 deletions(-) delete mode 100644 python/plugins/processing/algs/qgis/SplitLinesWithLines.py create mode 100644 python/plugins/processing/algs/qgis/SplitWithLines.py diff --git a/python/plugins/processing/algs/help/qgis.yaml b/python/plugins/processing/algs/help/qgis.yaml index 543d13307034..e59fdf2e2216 100644 --- a/python/plugins/processing/algs/help/qgis.yaml +++ b/python/plugins/processing/algs/help/qgis.yaml @@ -496,8 +496,8 @@ qgis:snappointstogrid: > This algorithm modifies the position of points in a vector layer, so they fall in the coordinates of a grid. -qgis:splitlineswithlines: > - This algorithm split the lines in a line layer using the lines in another line layer to define the breaking points. Intersection between geometries in both layers are considered as split points. +qgis:splitwithlines: > + This algorithm splits the lines or polygons in one layer using the lines in another layer to define the breaking points. Intersection between geometries in both layers are considered as split points. qgis:splitvectorlayer: > This algorithm takes a vector layer and an attribute and generates a set of vector layers in an output folder. Each of the layers created in that folder contains all features from the input layer with the same value for the specified attribute. diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index 4233a6f7a166..a7aa620646b7 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -141,7 +141,7 @@ from .SelectByExpression import SelectByExpression from .SelectByAttributeSum import SelectByAttributeSum from .HypsometricCurves import HypsometricCurves -from .SplitLinesWithLines import SplitLinesWithLines +from .SplitWithLines import SplitWithLines from .FieldsMapper import FieldsMapper from .Datasources2Vrt import Datasources2Vrt from .CheckValidity import CheckValidity @@ -226,7 +226,7 @@ def __init__(self): PostGISExecuteSQL(), ImportIntoPostGIS(), SetVectorStyle(), SetRasterStyle(), SelectByExpression(), HypsometricCurves(), - SplitLinesWithLines(), CreateConstantRaster(), + SplitWithLines(), CreateConstantRaster(), FieldsMapper(), SelectByAttributeSum(), Datasources2Vrt(), CheckValidity(), OrientedMinimumBoundingBox(), Smooth(), ReverseLineDirection(), SpatialIndex(), DefineProjection(), diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py deleted file mode 100644 index d4061570e44c..000000000000 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ /dev/null @@ -1,150 +0,0 @@ -# -*- coding: utf-8 -*- - -""" -*************************************************************************** - SplitLines.py - --------------------- - Date : November 2014 - Revised : February 2016 - Copyright : (C) 2014 by Bernhard Ströbl - Email : bernhard dot stroebl at jena dot de -*************************************************************************** -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -*************************************************************************** -""" -from builtins import next - -__author__ = 'Bernhard Ströbl' -__date__ = 'November 2014' -__copyright__ = '(C) 2014, Bernhard Ströbl' - -# This will get replaced with a git SHA1 when you do a git archive - -__revision__ = '$Format:%H$' - -from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes -from processing.core.GeoAlgorithm import GeoAlgorithm -from processing.core.parameters import ParameterVector -from processing.core.outputs import OutputVector -from processing.core.ProcessingLog import ProcessingLog -from processing.tools import dataobjects -from processing.tools import vector - - -class SplitLinesWithLines(GeoAlgorithm): - - INPUT_A = 'INPUT_A' - INPUT_B = 'INPUT_B' - - OUTPUT = 'OUTPUT' - - def defineCharacteristics(self): - self.name, self.i18n_name = self.trAlgorithm('Split lines with lines') - self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') - self.addParameter(ParameterVector(self.INPUT_A, - self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE])) - self.addParameter(ParameterVector(self.INPUT_B, - self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) - - self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'), datatype=[dataobjects.TYPE_VECTOR_LINE])) - - def processAlgorithm(self, progress): - layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) - layerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B)) - - sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B) - fieldList = layerA.fields() - - writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, - QgsWkbTypes.LineString, layerA.crs()) - - spatialIndex = vector.spatialindex(layerB) - - outFeat = QgsFeature() - features = vector.features(layerA) - total = 100.0 / float(len(features)) - - for current, inFeatA in enumerate(features): - inGeom = inFeatA.geometry() - attrsA = inFeatA.attributes() - outFeat.setAttributes(attrsA) - inLines = [inGeom] - lines = spatialIndex.intersects(inGeom.boundingBox()) - - engine = None - if len(lines) > 0: - # use prepared geometries for faster intersection tests - engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) - engine.prepareGeometry() - - if len(lines) > 0: # hasIntersections - splittingLines = [] - - request = QgsFeatureRequest().setFilterFids(lines).setSubsetOfAttributes([]) - for inFeatB in layerB.getFeatures(request): - # check if trying to self-intersect - if sameLayer: - if inFeatA.id() == inFeatB.id(): - continue - - splitGeom = inFeatB.geometry() - - if engine.intersects(splitGeom.geometry()): - splittingLines.append(splitGeom) - - if len(splittingLines) > 0: - for splitGeom in splittingLines: - splitterPList = vector.extractPoints(splitGeom) - outLines = [] - - split_geom_engine = QgsGeometry.createGeometryEngine(splitGeom.geometry()) - split_geom_engine.prepareGeometry() - - while len(inLines) > 0: - inGeom = inLines.pop() - inPoints = vector.extractPoints(inGeom) - - if split_geom_engine.intersects(inGeom.geometry()): - try: - result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) - except: - ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, - self.tr('Geometry exception while splitting')) - result = 1 - - # splitGeometry: If there are several intersections - # between geometry and splitLine, only the first one is considered. - if result == 0: # split occurred - - if inPoints == vector.extractPoints(inGeom): - # bug in splitGeometry: sometimes it returns 0 but - # the geometry is unchanged - outLines.append(inGeom) - else: - inLines.append(inGeom) - - for aNewGeom in newGeometries: - inLines.append(aNewGeom) - else: - outLines.append(inGeom) - else: - outLines.append(inGeom) - - inLines = outLines - - for aLine in inLines: - if len(aLine.asPolyline()) > 2 or \ - (len(aLine.asPolyline()) == 2 and - aLine.asPolyline()[0] != aLine.asPolyline()[1]): - # sometimes splitting results in lines of zero length - outFeat.setGeometry(aLine) - writer.addFeature(outFeat) - - progress.setPercentage(int(current * total)) - - del writer diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py new file mode 100644 index 000000000000..eb0f741b505b --- /dev/null +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + SplitWithLines.py + --------------------- + Date : November 2014 + Revised : September 2016 + Copyright : (C) 2014 by Bernhard Ströbl + Email : bernhard dot stroebl at jena dot de +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Bernhard Ströbl' +__date__ = 'November 2014' +__copyright__ = '(C) 2014, Bernhard Ströbl' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.outputs import OutputVector +from processing.core.ProcessingLog import ProcessingLog +from processing.tools import dataobjects +from processing.tools import vector + + +class SplitWithLines(GeoAlgorithm): + + INPUT_A = 'INPUT_A' + INPUT_B = 'INPUT_B' + + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Split with lines') + self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') + self.addParameter(ParameterVector(self.INPUT_A, + self.tr('Input layer, single geometries only'), [dataobjects.TYPE_VECTOR_POLYGON, + dataobjects.TYPE_VECTOR_LINE])) + self.addParameter(ParameterVector(self.INPUT_B, + self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) + + self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'))) + + def processAlgorithm(self, progress): + layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) + splitLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B)) + + sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B) + fieldList = layerA.fields() + + writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, + layerA.wkbType(), layerA.crs()) + + spatialIndex = vector.spatialindex(splitLayer) + splitGeoms = {} + + for aSplitFeature in vector.features(splitLayer): + splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry() + # honor the case that user has selection on split layer and has setting "use selection" + + outFeat = QgsFeature() + features = vector.features(layerA) + total = 100.0 / float(len(features)) + allowedWkbTypes = [2, #WkbLineString + 3, # WkbPolygon + -2147483646, #WkbLineString25D + -2147483645] # WkbPolygon25D + # MultiGeometries are not allowed because the result of a splitted ring is not clearly defined: + # 1) add both parts as new features + # 2) store one part as a new feature and the other one as ring of the multi geometry + # 2a) which part is which, seems arbitrary + + multiGeoms = 0 # how many multi geometries were encountered + + for current, inFeatA in enumerate(features): + inGeom = inFeatA.geometry() + + if allowedWkbTypes.count(inGeom.wkbType()) == 0: + multiGeoms += 1 + else: + attrsA = inFeatA.attributes() + outFeat.setAttributes(attrsA) + inGeoms = [inGeom] + lines = spatialIndex.intersects(inGeom.boundingBox()) + + if len(lines) > 0: # has intersection of bounding boxes + splittingLines = [] + + for i in lines: + try: + splitGeom = splitGeoms[i] + except: + continue + + # check if trying to self-intersect + if sameLayer: + if inFeatA.id() == i: + continue + + if inGeom.intersects(splitGeom): + splittingLines.append(splitGeom) + + if len(splittingLines) > 0: + for splitGeom in splittingLines: + splitterPList = vector.extractPoints(splitGeom) + outGeoms = [] + + while len(inGeoms) > 0: + inGeom = inGeoms.pop() + inPoints = vector.extractPoints(inGeom) + + if inGeom.intersects(splitGeom): + try: + result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) + except: + ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, + self.tr('Geometry exception while splitting')) + result = 1 + + # splitGeometry: If there are several intersections + # between geometry and splitLine, only the first one is considered. + if result == 0: # split occurred + + if inPoints == vector.extractPoints(inGeom): + # bug in splitGeometry: sometimes it returns 0 but + # the geometry is unchanged + outGeoms.append(inGeom) + else: + inGeoms.append(inGeom) + + for aNewGeom in newGeometries: + inGeoms.append(aNewGeom) + else: + outGeoms.append(inGeom) + else: + outGeoms.append(inGeom) + + inGeoms = outGeoms + + for aGeom in inGeoms: + passed = True + + if aGeom.wkbType == 2 or aGeom.wkbType == -2147483646: + passed = len(aGeom.asPolyline()) > 2 + + if not passed: + passed = (len(aGeom.asPolyline()) == 2 and + aGeom.asPolyline()[0] != aGeom.asPolyline()[1]) + # sometimes splitting results in lines of zero length + + if passed: + outFeat.setGeometry(aGeom) + writer.addFeature(outFeat) + + progress.setPercentage(int(current * total)) + + if multiGeoms > 0: + ProcessingLog.addToLog(ProcessingLog.LOG_INFO, + self.tr('Feature geometry error: %s input features ignored due to multi-geometry.') % str(multiGeoms)) + + del writer From a972c6d2a5f012ea761f997fd06d36e3b1a9cb24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 10:17:43 +0200 Subject: [PATCH 884/897] [processing] update test for splitwithlines --- .../expected/polys_split_with_lines.gfs | 32 ++++++++++ .../expected/polys_split_with_lines.gml | 59 +++++++++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 26 ++++++-- 3 files changed, 113 insertions(+), 4 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs new file mode 100644 index 000000000000..3c0084954b0f --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs @@ -0,0 +1,32 @@ + + + polygons_split_with_lines + polygons_split_with_lines + + 3 + EPSG:4326 + + 6 + -1.00000 + 10.00000 + -3.00000 + 6.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml new file mode 100644 index 000000000000..88e8941cf772 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml @@ -0,0 +1,59 @@ + + + + + -1-3 + 106 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.12346 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0.00000 + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.12300 + + + + + 6,-3 7,-2 9,-2 9,0 10,1 10,-3 6,-3 + ASDF + 0 + + + + + 7,-2 6,-3 6,1 10,1 9,0 7,0 7,-2 + ASDF + 0 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 2 + 3.33000 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 0fc4ea6a49df..c3b3e9d8d2e6 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -193,9 +193,9 @@ tests: name: expected/basic_statistics_string.html type: file - # Split lines with lines considers two cases - # case 1: two different layers - - algorithm: qgis:splitlineswithlines + # Split with lines considers three cases + # case 1: two different line layers + - algorithm: qgis:splitwithlines name: Split lines with lines params: INPUT_A: @@ -213,7 +213,7 @@ tests: precision: 7 # case 2 split line layer with iself - - algorithm: qgis:splitlineswithlines + - algorithm: qgis:splitwithlines name: Split lines with same lines params: INPUT_A: @@ -229,6 +229,24 @@ tests: compare: geometry: precision: 7 + + # case 3 split polygon layer with lines + - algorithm: qgis:splitwithlines + name: Split lines with same lines + params: + INPUT_A: + name: polys.gml + type: vector + INPUT_B: + name: lines.gml + type: vector + results: + OUTPUT: + name: expected/polys_split_with_lines.gml + type: vector + compare: + geometry: + precision: 7 - algorithm: qgis:addautoincrementalfield name: Add autoincremental field From ae02f51fbdaffd21beb15ca37919ef3e8e22e50d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 11:17:02 +0200 Subject: [PATCH 885/897] [BUG] Prevent division by zero --- python/plugins/processing/algs/qgis/SplitWithLines.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index eb0f741b505b..c3ed7328e493 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -72,7 +72,12 @@ def processAlgorithm(self, progress): outFeat = QgsFeature() features = vector.features(layerA) - total = 100.0 / float(len(features)) + + if len(features) == 0: + total = 100 + else: + total = 100.0 / float(len(features)) + allowedWkbTypes = [2, #WkbLineString 3, # WkbPolygon -2147483646, #WkbLineString25D From 621e3660a495091297535b60f6d893bc46ae8665 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 11:41:44 +0200 Subject: [PATCH 886/897] Speed up algorithm --- python/plugins/processing/algs/qgis/SplitWithLines.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index c3ed7328e493..7fc7cb33411a 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -65,8 +65,10 @@ def processAlgorithm(self, progress): spatialIndex = vector.spatialindex(splitLayer) splitGeoms = {} + request = QgsFeatureRequest() + request.setSubsetOfAttributes([]) - for aSplitFeature in vector.features(splitLayer): + for aSplitFeature in vector.features(splitLayer, request): splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry() # honor the case that user has selection on split layer and has setting "use selection" From 2f445a3b232162ee3b73d1e572e2cdeff957dfdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 13:10:21 +0200 Subject: [PATCH 887/897] check if geometry is multipart without wkb types --- .../processing/algs/qgis/SplitWithLines.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 7fc7cb33411a..93df1adcd3d1 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -80,22 +80,17 @@ def processAlgorithm(self, progress): else: total = 100.0 / float(len(features)) - allowedWkbTypes = [2, #WkbLineString - 3, # WkbPolygon - -2147483646, #WkbLineString25D - -2147483645] # WkbPolygon25D - # MultiGeometries are not allowed because the result of a splitted ring is not clearly defined: - # 1) add both parts as new features - # 2) store one part as a new feature and the other one as ring of the multi geometry - # 2a) which part is which, seems arbitrary - multiGeoms = 0 # how many multi geometries were encountered for current, inFeatA in enumerate(features): inGeom = inFeatA.geometry() - if allowedWkbTypes.count(inGeom.wkbType()) == 0: + if inGeom.isMultipart(): multiGeoms += 1 + # MultiGeometries are not allowed because the result of a splitted part cannot be clearly defined: + # 1) add both new parts as new features + # 2) store one part as a new feature and the other one as part of the multi geometry + # 2a) which part should be which, seems arbitrary else: attrsA = inFeatA.attributes() outFeat.setAttributes(attrsA) From a4f4595363dddb711e84fb2ca3f17b2248900c3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Thu, 29 Sep 2016 16:12:54 +0200 Subject: [PATCH 888/897] Renew test result --- .../expected/polys_split_with_lines.gfs | 14 +++++-- .../expected/polys_split_with_lines.gml | 38 +++++++++++-------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs index 3c0084954b0f..a477b60cc5b8 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gfs @@ -1,17 +1,23 @@ - polygons_split_with_lines - polygons_split_with_lines + polys_split_with_lines + polys_split_with_lines 3 - EPSG:4326 + GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]] - 6 + 7 -1.00000 10.00000 -3.00000 6.00000 + + fid + fid + String + 7 + name name diff --git a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml index 88e8941cf772..24aaec68b7ca 100644 --- a/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml +++ b/python/plugins/processing/tests/testdata/expected/polys_split_with_lines.gml @@ -12,48 +12,54 @@ - + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 aaaaa 33 - 44.12346 - + 44.123456 + - + 5,5 6,4 4,4 5,5 Aaaaa -33 - 0.00000 - + 0 + - + 2,5 2,6 3,6 3,5 2,5 bbaaa - 0.12300 - + 0.123 + - + 6,-3 7,-2 9,-2 9,0 10,1 10,-3 6,-3 ASDF 0 - + - + 7,-2 6,-3 6,1 10,1 9,0 7,0 7,-2 ASDF 0 - + - + + 120 + -100291.43213 + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 elim 2 - 3.33000 - + 3.33 + From 7eabb3594feb4d8bc768b1514c523490c14e72bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 30 Sep 2016 08:23:57 +0200 Subject: [PATCH 889/897] [TEST] resurrect SplitLinesWithLines.py to pass test --- .../algs/qgis/SplitLinesWithLines.py | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 python/plugins/processing/algs/qgis/SplitLinesWithLines.py diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py new file mode 100644 index 000000000000..27732c2c20cb --- /dev/null +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- + +""" +*************************************************************************** + DEPRECATED, replaced by SplitWithLines.py + --------------------- + Date : November 2014 + Revised : February 2016 + Copyright : (C) 2014 by Bernhard Ströbl + Email : bernhard dot stroebl at jena dot de +*************************************************************************** +* * +* This program is free software; you can redistribute it and/or modify * +* it under the terms of the GNU General Public License as published by * +* the Free Software Foundation; either version 2 of the License, or * +* (at your option) any later version. * +* * +*************************************************************************** +""" + +__author__ = 'Bernhard Ströbl' +__date__ = 'November 2014' +__copyright__ = '(C) 2014, Bernhard Ströbl' + +# This will get replaced with a git SHA1 when you do a git archive + +__revision__ = '$Format:%H$' + +from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes +from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.parameters import ParameterVector +from processing.core.outputs import OutputVector +from processing.core.ProcessingLog import ProcessingLog +from processing.tools import dataobjects +from processing.tools import vector + + +class SplitLinesWithLines(GeoAlgorithm): + + INPUT_A = 'INPUT_A' + INPUT_B = 'INPUT_B' + + OUTPUT = 'OUTPUT' + + def defineCharacteristics(self): + self.name, self.i18n_name = self.trAlgorithm('Split lines with lines') + self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') + self.addParameter(ParameterVector(self.INPUT_A, + self.tr('Input layer'), [dataobjects.TYPE_VECTOR_LINE])) + self.addParameter(ParameterVector(self.INPUT_B, + self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) + + self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'), datatype=[dataobjects.TYPE_VECTOR_LINE])) + + def processAlgorithm(self, progress): + layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) + layerB = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_B)) + + sameLayer = self.getParameterValue(self.INPUT_A) == self.getParameterValue(self.INPUT_B) + fieldList = layerA.fields() + + writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, + QgsWkbTypes.LineString, layerA.crs()) + + spatialIndex = vector.spatialindex(layerB) + + outFeat = QgsFeature() + features = vector.features(layerA) + total = 100.0 / float(len(features)) + + for current, inFeatA in enumerate(features): + inGeom = inFeatA.geometry() + attrsA = inFeatA.attributes() + outFeat.setAttributes(attrsA) + inLines = [inGeom] + lines = spatialIndex.intersects(inGeom.boundingBox()) + + if len(lines) > 0: # hasIntersections + splittingLines = [] + + for i in lines: + request = QgsFeatureRequest().setFilterFid(i) + inFeatB = next(layerB.getFeatures(request)) + # check if trying to self-intersect + if sameLayer: + if inFeatA.id() == inFeatB.id(): + continue + + splitGeom = inFeatB.geometry() + + if inGeom.intersects(splitGeom): + splittingLines.append(splitGeom) + + if len(splittingLines) > 0: + for splitGeom in splittingLines: + splitterPList = vector.extractPoints(splitGeom) + outLines = [] + + while len(inLines) > 0: + inGeom = inLines.pop() + inPoints = vector.extractPoints(inGeom) + + if inGeom.intersects(splitGeom): + try: + result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) + except: + ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, + self.tr('Geometry exception while splitting')) + result = 1 + + # splitGeometry: If there are several intersections + # between geometry and splitLine, only the first one is considered. + if result == 0: # split occurred + + if inPoints == vector.extractPoints(inGeom): + # bug in splitGeometry: sometimes it returns 0 but + # the geometry is unchanged + outLines.append(inGeom) + else: + inLines.append(inGeom) + + for aNewGeom in newGeometries: + inLines.append(aNewGeom) + else: + outLines.append(inGeom) + else: + outLines.append(inGeom) + + inLines = outLines + + for aLine in inLines: + if len(aLine.asPolyline()) > 2 or \ + (len(aLine.asPolyline()) == 2 and + aLine.asPolyline()[0] != aLine.asPolyline()[1]): + # sometimes splitting results in lines of zero length + outFeat.setGeometry(aLine) + writer.addFeature(outFeat) + + progress.setPercentage(int(current * total)) + + del writer From 81d7d18c95dc0eea4edacc7463f83880d884a6db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Tue, 4 Oct 2016 15:18:41 +0200 Subject: [PATCH 890/897] rename test --- .../plugins/processing/tests/testdata/qgis_algorithm_tests.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index c3b3e9d8d2e6..3668b5996086 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -232,7 +232,7 @@ tests: # case 3 split polygon layer with lines - algorithm: qgis:splitwithlines - name: Split lines with same lines + name: Split polygons with lines params: INPUT_A: name: polys.gml From 1838a71ea44531e5f3bc6a06dfab198e439e6914 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Wed, 5 Oct 2016 08:09:19 +0200 Subject: [PATCH 891/897] remove all splitWithLines tests --- .../tests/testdata/qgis_algorithm_tests.yaml | 55 ------------------- 1 file changed, 55 deletions(-) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index 3668b5996086..f34e0bc2a6d2 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -193,61 +193,6 @@ tests: name: expected/basic_statistics_string.html type: file - # Split with lines considers three cases - # case 1: two different line layers - - algorithm: qgis:splitwithlines - name: Split lines with lines - params: - INPUT_A: - name: lines.gml - type: vector - INPUT_B: - name: custom/lines2.gml - type: vector - results: - OUTPUT: - name: expected/lines_split_with_lines.gml - type: vector - compare: - geometry: - precision: 7 - - # case 2 split line layer with iself - - algorithm: qgis:splitwithlines - name: Split lines with same lines - params: - INPUT_A: - name: custom/lines2.gml - type: vector - INPUT_B: - name: custom/lines2.gml - type: vector - results: - OUTPUT: - name: expected/lines_split_with_same_lines.gml - type: vector - compare: - geometry: - precision: 7 - - # case 3 split polygon layer with lines - - algorithm: qgis:splitwithlines - name: Split polygons with lines - params: - INPUT_A: - name: polys.gml - type: vector - INPUT_B: - name: lines.gml - type: vector - results: - OUTPUT: - name: expected/polys_split_with_lines.gml - type: vector - compare: - geometry: - precision: 7 - - algorithm: qgis:addautoincrementalfield name: Add autoincremental field params: From 3dd57e8b26e90d7dc58446a50282700fd7c654d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 18 Nov 2016 07:45:56 +0100 Subject: [PATCH 892/897] [Irregular verb] --- python/plugins/processing/algs/qgis/SplitWithLines.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 93df1adcd3d1..9297aee0be08 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -5,7 +5,7 @@ SplitWithLines.py --------------------- Date : November 2014 - Revised : September 2016 + Revised : November 2016 Copyright : (C) 2014 by Bernhard Ströbl Email : bernhard dot stroebl at jena dot de *************************************************************************** @@ -51,7 +51,7 @@ def defineCharacteristics(self): self.addParameter(ParameterVector(self.INPUT_B, self.tr('Split layer'), [dataobjects.TYPE_VECTOR_LINE])) - self.addOutput(OutputVector(self.OUTPUT, self.tr('Splitted'))) + self.addOutput(OutputVector(self.OUTPUT, self.tr('Split'))) def processAlgorithm(self, progress): layerA = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_A)) From c20d2cb0a03c73db4a83d9067f0142b54810cfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 18 Nov 2016 07:51:54 +0100 Subject: [PATCH 893/897] Deprecate SplitLinesWithLines the proper way --- .../plugins/processing/algs/qgis/QGISAlgorithmProvider.py | 3 ++- .../plugins/processing/algs/qgis/SplitLinesWithLines.py | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py index a7aa620646b7..fd7120e8781d 100644 --- a/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py +++ b/python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py @@ -142,6 +142,7 @@ from .SelectByAttributeSum import SelectByAttributeSum from .HypsometricCurves import HypsometricCurves from .SplitWithLines import SplitWithLines +from .SplitLinesWithLines import SplitLinesWithLines from .FieldsMapper import FieldsMapper from .Datasources2Vrt import Datasources2Vrt from .CheckValidity import CheckValidity @@ -226,7 +227,7 @@ def __init__(self): PostGISExecuteSQL(), ImportIntoPostGIS(), SetVectorStyle(), SetRasterStyle(), SelectByExpression(), HypsometricCurves(), - SplitWithLines(), CreateConstantRaster(), + SplitWithLines(), SplitLinesWithLines(), CreateConstantRaster(), FieldsMapper(), SelectByAttributeSum(), Datasources2Vrt(), CheckValidity(), OrientedMinimumBoundingBox(), Smooth(), ReverseLineDirection(), SpatialIndex(), DefineProjection(), diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py index 27732c2c20cb..3963cb1d6150 100644 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -2,10 +2,11 @@ """ *************************************************************************** + SplitLinesWithLines.py DEPRECATED, replaced by SplitWithLines.py --------------------- Date : November 2014 - Revised : February 2016 + Revised : November 2016 Copyright : (C) 2014 by Bernhard Ströbl Email : bernhard dot stroebl at jena dot de *************************************************************************** @@ -42,6 +43,11 @@ class SplitLinesWithLines(GeoAlgorithm): OUTPUT = 'OUTPUT' + def __init__(self): + GeoAlgorithm.__init__(self) + # this algorithm is deprecated - use SplitWithLines instead + self.showInToolbox = False + def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('Split lines with lines') self.group, self.i18n_group = self.trAlgorithm('Vector overlay tools') From 44a5f0754bf48d9c92c866e92c13aa2f2e00e2db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Fri, 18 Nov 2016 08:27:38 +0100 Subject: [PATCH 894/897] [FEATURE] Speed up algo by fetching features only once --- python/plugins/processing/algs/qgis/SplitWithLines.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 9297aee0be08..23ed0fd0cdaa 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -26,7 +26,7 @@ __revision__ = '$Format:%H$' -from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes +from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes, QgsSpatialIndex from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector @@ -63,13 +63,14 @@ def processAlgorithm(self, progress): writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList, layerA.wkbType(), layerA.crs()) - spatialIndex = vector.spatialindex(splitLayer) + spatialIndex = QgsSpatialIndex() splitGeoms = {} request = QgsFeatureRequest() request.setSubsetOfAttributes([]) for aSplitFeature in vector.features(splitLayer, request): splitGeoms[aSplitFeature.id()] = aSplitFeature.geometry() + spatialIndex.insertFeature(aSplitFeature) # honor the case that user has selection on split layer and has setting "use selection" outFeat = QgsFeature() From 09e9e51bc485b63d9a5541eff6f34d9ccb6bae72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Mon, 21 Nov 2016 09:38:39 +0100 Subject: [PATCH 895/897] [FEATURE] Speed up algo by using QgsGeometryEngine --- .../plugins/processing/algs/qgis/SplitWithLines.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 23ed0fd0cdaa..40898022b7b0 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -112,19 +112,27 @@ def processAlgorithm(self, progress): if inFeatA.id() == i: continue - if inGeom.intersects(splitGeom): + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() + + if engine.intersects(splitGeom.geometry()): splittingLines.append(splitGeom) if len(splittingLines) > 0: for splitGeom in splittingLines: - splitterPList = vector.extractPoints(splitGeom) + splitterPList = None outGeoms = [] while len(inGeoms) > 0: inGeom = inGeoms.pop() + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() inPoints = vector.extractPoints(inGeom) - if inGeom.intersects(splitGeom): + if engine.intersects(splitGeom.geometry()): + if splitterPList == None: + splitterPList = vector.extractPoints(splitGeom) + try: result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) except: From 783553f60435a6ca77d454fde56706566cf3f10b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Tue, 22 Nov 2016 10:01:35 +0100 Subject: [PATCH 896/897] [FEATURE] Broaden allowed geometries by checking WKBTypes --- python/plugins/processing/algs/qgis/SplitWithLines.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/algs/qgis/SplitWithLines.py b/python/plugins/processing/algs/qgis/SplitWithLines.py index 40898022b7b0..15dccb131db9 100644 --- a/python/plugins/processing/algs/qgis/SplitWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitWithLines.py @@ -26,7 +26,7 @@ __revision__ = '$Format:%H$' -from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes, QgsSpatialIndex +from qgis.core import QgsFeatureRequest, QgsFeature, QgsGeometry, QgsSpatialIndex, QgsWkbTypes, QgsMessageLog from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterVector from processing.core.outputs import OutputVector @@ -147,6 +147,7 @@ def processAlgorithm(self, progress): if inPoints == vector.extractPoints(inGeom): # bug in splitGeometry: sometimes it returns 0 but # the geometry is unchanged + QgsMessageLog.logMessage("appending") outGeoms.append(inGeom) else: inGeoms.append(inGeom) @@ -154,6 +155,7 @@ def processAlgorithm(self, progress): for aNewGeom in newGeometries: inGeoms.append(aNewGeom) else: + QgsMessageLog.logMessage("appending else") outGeoms.append(inGeom) else: outGeoms.append(inGeom) @@ -163,7 +165,8 @@ def processAlgorithm(self, progress): for aGeom in inGeoms: passed = True - if aGeom.wkbType == 2 or aGeom.wkbType == -2147483646: + if QgsWkbTypes.geometryType( aGeom.wkbType() ) == QgsWkbTypes.LineGeometry \ + and not QgsWkbTypes.isMultiType( aGeom.wkbType() ): passed = len(aGeom.asPolyline()) > 2 if not passed: From 7f5a011b05ff0eaf39e098b712502edc04efcb3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bernhard=20Str=C3=B6bl?= Date: Wed, 23 Nov 2016 16:05:21 +0100 Subject: [PATCH 897/897] Reactivate test for SplitWithLines --- .../tests/testdata/qgis_algorithm_tests.yaml | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index f34e0bc2a6d2..4c41f88a4154 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1539,3 +1539,46 @@ tests: OUTPUT: name: expected/delete_column.gml type: vector + + - algorithm: qgis:splitwithlines + name: Split lines with lines + params: + INPUT_A: + name: lines.gml + type: vector + INPUT_B: + name: custom/lines2.gml + type: vector + results: + OUTPUT: + name: expected/lines_split_with_lines.gml + type: vector + + - algorithm: qgis:splitwithlines + name: Split lines with same lines + params: + INPUT_A: + name: custom/lines2.gml + type: vector + INPUT_B: + name: custom/lines2.gml + type: vector + results: + OUTPUT: + name: expected/lines_split_with_same_lines.gml + type: vector + + - algorithm: qgis:splitwithlines + name: Split polygons with lines + params: + INPUT_A: + name: polys.gml + type: vector + INPUT_B: + name: lines.gml + type: vector + results: + OUTPUT: + name: expected/polys_split_with_lines.gml + type: vector +
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              • i 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�E6J_J< zx1xUGHMyw?vVA4bpXdZp-<2TKH45~%iIq#tsTkiXM()gsmbJ>!5}*4@ zs_B99@Q#+c&}f;pE?TlqM2jtZ^95zm^4Wv?-#xrO(TkOsJ@rb{U1bqUb5ug`6MpuzRKsM=Dl#)UUC^P zWk|bW8T>m^WayV%$=2oLwxLvX8h?7;sCw+>-Xs5KWb?XEzrgAU|oP=RR3xzURfyvu9nN7)H2ywRU!d7Me=Yd zbuD@Ma`j5S_zzY{?h1uyFHuO+C|>JXC}imMeEFG|$Hy~U2JTacnn976b|!nFb(!=@ zZkpZHisSQIG0&kcvZO(-Oi;olQ)L{DBpaX`eE>U}XFt6R)F6GhuN|sE|BojA?5KrS zZM5-sUmZ+Zq>Dt(Vn*-L!=ttO&>i0r56umbdbfH15an!yICWzTphiD*y9ti;rdKJ4 zeftJ87|@$FoIEwPt`;!5Z-H&>jV~2g;>zz<$gm`D;ZQ5QRN-DSz#7`an|G;0f^Bei ziY>-;v4a;qsxeFKQKH)#x7W2sKpbzyt+BeHHJ((q#?X(garks=v}RwvQmHkzAF)S& zH+ynV$fMD*qp#Q&hfQp-xt1QOTr2#ZPMuDk1>Vq8Hrm4+U+$Wb|7M0;Kh4m8J9D!Z zS)ea__?mEQl-*#DKea7t3)-VFf_damo$)EX3r<~dN8i58#4~PY(>%V{3tCHi!@<2T z;7& zbnS_DtvHX-_eGL%Z!9fsx^D2r$ANyh+@pC1TX>1P+7rWI=ra!RU#T?%JkmpR5axn4&-T%IPtbZUu?;goR>bLKZZ<71xOW7O~Edv{4ZVEKYpx#L3VGo_U?9_3@6EWVLwdMn=tm z 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%0DCXi|8f2NiXSsY8mGmF}n@*FFdd2A2GnK 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 Date: Tue, 11 Oct 2016 12:01:14 +0300 Subject: [PATCH 248/897] [processing] restore Points in Polygons algorithm menu entry (follow up d4323addf0) --- python/plugins/processing/gui/menus.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/gui/menus.py b/python/plugins/processing/gui/menus.py index 2557ebc37917..f93264688e73 100644 --- a/python/plugins/processing/gui/menus.py +++ b/python/plugins/processing/gui/menus.py @@ -21,6 +21,7 @@ analysisToolsMenu = vectorMenu + "/" + Processing.tr('&Analysis Tools') defaultMenuEntries.update({'qgis:distancematrix': analysisToolsMenu, 'qgis:sumlinelengths': analysisToolsMenu, + 'qgis:pointsinpolygon': analysisToolsMenu, 'qgis:countpointsinpolygon': analysisToolsMenu, 'qgis:listuniquevalues': analysisToolsMenu, 'qgis:basicstatisticsfornumericfields': analysisToolsMenu, From 75405293e0c471c2a55398c20ccb847396010f95 Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 11 Oct 2016 11:34:57 +0200 Subject: [PATCH 249/897] [QGIS Server] Loss qobject_cast when it's usefull --- src/server/qgsserverprojectparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index c98da2c82309..3f885124f0de 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -291,7 +291,7 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& if ( layer->type() == QgsMapLayer::VectorLayer ) { - addValueRelationLayersForLayer( dynamic_cast( layer ) ); + addValueRelationLayersForLayer( qobject_cast( layer ) ); } } return layer; From 53c3ed2dc02baf43c3a5cc7323f37869f434f25a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 12 Oct 2016 14:20:09 +1000 Subject: [PATCH 250/897] Fix HTML annotation does not display HTML (fix #8609) Annotation was only rendering html when it was associated with a map layer. Now if it isn't associated with a map layer it will always render the html. --- src/gui/qgshtmlannotationitem.cpp | 60 ++++++++++++++++--------------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/src/gui/qgshtmlannotationitem.cpp b/src/gui/qgshtmlannotationitem.cpp index cb8593774064..ae3e02004854 100644 --- a/src/gui/qgshtmlannotationitem.cpp +++ b/src/gui/qgshtmlannotationitem.cpp @@ -193,42 +193,44 @@ void QgsHtmlAnnotationItem::readXml( const QDomDocument& doc, const QDomElement& void QgsHtmlAnnotationItem::setFeatureForMapPosition() { - if ( !mVectorLayer || !mMapCanvas ) + QString newText; + if ( mVectorLayer && mMapCanvas ) { - return; - } + double halfIdentifyWidth = QgsMapTool::searchRadiusMU( mMapCanvas ); + QgsRectangle searchRect( mMapPosition.x() - halfIdentifyWidth, mMapPosition.y() - halfIdentifyWidth, + mMapPosition.x() + halfIdentifyWidth, mMapPosition.y() + halfIdentifyWidth ); - QSettings settings; - double halfIdentifyWidth = QgsMapTool::searchRadiusMU( mMapCanvas ); - QgsRectangle searchRect( mMapPosition.x() - halfIdentifyWidth, mMapPosition.y() - halfIdentifyWidth, - mMapPosition.x() + halfIdentifyWidth, mMapPosition.y() + halfIdentifyWidth ); + QgsFeatureIterator fit = mVectorLayer->getFeatures( QgsFeatureRequest().setFilterRect( searchRect ).setFlags( QgsFeatureRequest::NoGeometry | QgsFeatureRequest::ExactIntersect ) ); - QgsFeatureIterator fit = mVectorLayer->getFeatures( QgsFeatureRequest().setFilterRect( searchRect ).setFlags( QgsFeatureRequest::NoGeometry | QgsFeatureRequest::ExactIntersect ) ); + QgsFeature currentFeature; + QgsFeatureId currentFeatureId = 0; + bool featureFound = false; + + while ( fit.nextFeature( currentFeature ) ) + { + currentFeatureId = currentFeature.id(); + featureFound = true; + break; + } - QgsFeature currentFeature; - QgsFeatureId currentFeatureId = 0; - bool featureFound = false; + mHasAssociatedFeature = featureFound; + mFeatureId = currentFeatureId; + mFeature = currentFeature; - while ( fit.nextFeature( currentFeature ) ) + QgsExpressionContext context; + context << QgsExpressionContextUtils::globalScope() + << QgsExpressionContextUtils::projectScope() + << QgsExpressionContextUtils::layerScope( mVectorLayer ); + if ( mMapCanvas ) + context.appendScope( QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) ); + context.setFeature( mFeature ); + newText = QgsExpression::replaceExpressionText( mHtmlSource, &context ); + } + else { - currentFeatureId = currentFeature.id(); - featureFound = true; - break; + newText = mHtmlSource; } - - mHasAssociatedFeature = featureFound; - mFeatureId = currentFeatureId; - mFeature = currentFeature; - - QgsExpressionContext context; - context << QgsExpressionContextUtils::globalScope() - << QgsExpressionContextUtils::projectScope() - << QgsExpressionContextUtils::layerScope( mVectorLayer ); - if ( mMapCanvas ) - context.appendScope( QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() ) ); - context.setFeature( mFeature ); - QString newtext = QgsExpression::replaceExpressionText( mHtmlSource, &context ); - mWebView->setHtml( newtext ); + mWebView->setHtml( newText ); } void QgsHtmlAnnotationItem::updateVisibility() From 2665eb50a69220324f4a6d045e8eba6601760dd3 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 12 Oct 2016 16:31:49 +1000 Subject: [PATCH 251/897] Correctly handle edit buffer when using request with limit (fix #15505) --- src/core/qgsvectorlayerfeatureiterator.cpp | 22 ++++++++++++ tests/src/python/test_qgsvectorlayer.py | 41 ++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/src/core/qgsvectorlayerfeatureiterator.cpp b/src/core/qgsvectorlayerfeatureiterator.cpp index 32966eacf4ec..7aeb2a24a206 100644 --- a/src/core/qgsvectorlayerfeatureiterator.cpp +++ b/src/core/qgsvectorlayerfeatureiterator.cpp @@ -173,6 +173,28 @@ QgsVectorLayerFeatureIterator::QgsVectorLayerFeatureIterator( QgsVectorLayerFeat changedIds << attIt.key(); } mChangedFeaturesRequest.setFilterFids( changedIds ); + + if ( mChangedFeaturesRequest.limit() > 0 ) + { + int providerLimit = mProviderRequest.limit(); + + // features may be deleted in buffer, so increase limit sent to provider + providerLimit += mSource->mDeletedFeatureIds.size(); + + if ( mProviderRequest.filterType() == QgsFeatureRequest::FilterExpression ) + { + // attribute changes may mean some features no longer match expression, so increase limit sent to provider + providerLimit += mSource->mChangedAttributeValues.size(); + } + + if ( mProviderRequest.filterType() == QgsFeatureRequest::FilterExpression || mProviderRequest.filterType() == QgsFeatureRequest::FilterRect ) + { + // geometry changes may mean some features no longer match expression or rect, so increase limit sent to provider + providerLimit += mSource->mChangedGeometries.size(); + } + + mProviderRequest.setLimit( providerLimit ); + } } if ( request.filterType() == QgsFeatureRequest::FilterFid ) diff --git a/tests/src/python/test_qgsvectorlayer.py b/tests/src/python/test_qgsvectorlayer.py index f289b7617438..627ebae86475 100644 --- a/tests/src/python/test_qgsvectorlayer.py +++ b/tests/src/python/test_qgsvectorlayer.py @@ -1773,6 +1773,47 @@ def testEvaluatingDefaultExpressions(self): layer.setDefaultValueExpression(1, 'not a valid expression') self.assertFalse(layer.defaultValue(1)) + def testGetFeatureLimitWithEdits(self): + """ test getting features with a limit, when edits are present """ + layer = createLayerWithOnePoint() + # now has one feature with id 0 + + pr = layer.dataProvider() + + f1 = QgsFeature(1) + f1.setAttributes(["test", 3]) + f1.setGeometry(QgsGeometry.fromPoint(QgsPoint(300, 200))) + f2 = QgsFeature(2) + f2.setAttributes(["test", 3]) + f2.setGeometry(QgsGeometry.fromPoint(QgsPoint(100, 200))) + f3 = QgsFeature(3) + f3.setAttributes(["test", 3]) + f3.setGeometry(QgsGeometry.fromPoint(QgsPoint(100, 200))) + self.assertTrue(pr.addFeatures([f1, f2, f3])) + + req = QgsFeatureRequest().setLimit(2) + self.assertEqual(len(list(layer.getFeatures(req))), 2) + + # now delete feature f1 + layer.startEditing() + self.assertTrue(layer.deleteFeature(1)) + req = QgsFeatureRequest().setLimit(2) + self.assertEqual(len(list(layer.getFeatures(req))), 2) + layer.rollBack() + + # change an attribute value required by filter + layer.startEditing() + req = QgsFeatureRequest().setFilterExpression('fldint=3').setLimit(2) + self.assertTrue(layer.changeAttributeValue(2, 1, 4)) + self.assertEqual(len(list(layer.getFeatures(req))), 2) + layer.rollBack() + + layer.startEditing() + req = QgsFeatureRequest().setFilterRect(QgsRectangle(50, 100, 150, 300)).setLimit(2) + self.assertTrue(layer.changeGeometry(2, QgsGeometry.fromPoint(QgsPoint(500, 600)))) + self.assertEqual(len(list(layer.getFeatures(req))), 2) + layer.rollBack() + # TODO: # - fetch rect: feat with changed geometry: 1. in rect, 2. out of rect From 05ea4be7c34aaa8bb63183c012720a2e61f838cc Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 12 Oct 2016 16:56:29 +1000 Subject: [PATCH 252/897] [processing] Fix inefficient values() method Method was iterating over ever feature in a layer, including geometries and all attributes for EVERY attribute requested Add test and refactor so only one optimised iteration (eg no geometry, only required attributes) is used --- python/plugins/processing/tests/ToolsTest.py | 38 ++++++++++++++++++++ python/plugins/processing/tools/vector.py | 27 ++++++++++---- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index e6a6db6ce7b7..701af206361a 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -84,6 +84,44 @@ def testFeatures(self): ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value) + def testValues(self): + ProcessingConfig.initialize() + + test_data = points2() + test_layer = QgsVectorLayer(test_data, 'test', 'ogr') + + # field by index + res = vector.values(test_layer, 0) + self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) + + # field by name + res = vector.values(test_layer, 'id') + self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) + + # two fields + res = vector.values(test_layer, 0, 3) + self.assertEqual(res[0], [1, 2, 3, 4, 5, 6, 7, 8]) + self.assertEqual(res[3], [2, 1, 0, 2, 1, 0, 0, 0]) + + # two fields by name + res = vector.values(test_layer, 'id', 'id_2') + self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) + self.assertEqual(res['id_2'], [2, 1, 0, 2, 1, 0, 0, 0]) + + # two fields by name and index + res = vector.values(test_layer, 'id', 3) + self.assertEqual(res['id'], [1, 2, 3, 4, 5, 6, 7, 8]) + self.assertEqual(res[3], [2, 1, 0, 2, 1, 0, 0, 0]) + + # test with selected features + previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) + ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True) + test_layer.selectByIds([2, 4, 6]) + res = vector.values(test_layer, 0) + self.assertEqual(set(res[0]), set([5, 7, 3])) + + ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value) + if __name__ == '__main__': unittest.main() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 8d0014dbe8d3..5808276330d6 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -163,17 +163,30 @@ def values(layer, *attributes): to a number. """ ret = {} + indices = [] + attr_keys = {} for attr in attributes: index = resolveFieldIndex(layer, attr) - values = [] - feats = features(layer) - for feature in feats: + indices.append(index) + attr_keys[index] = attr + + # use an optimised feature request + request = QgsFeatureRequest().setSubsetOfAttributes(indices).setFlags(QgsFeatureRequest.NoGeometry) + + for feature in features(layer, request): + for i in indices: + + # convert attribute value to number try: - v = float(feature.attributes()[index]) - values.append(v) + v = float(feature.attributes()[i]) except: - values.append(None) - ret[attr] = values + v = None + + k = attr_keys[i] + if k in ret: + ret[k].append(v) + else: + ret[k] = [v] return ret From 6605a2274f84f7f90e846283f31eee8835018ad5 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Wed, 12 Oct 2016 17:05:15 +1000 Subject: [PATCH 253/897] [processing] Optimise uniqueValues method Now it uses the standard QgsVectorLayer.uniqueValues() method where possible so that provider side optimisations are used Also add test, and optimise request when using selected features only --- python/plugins/processing/tests/ToolsTest.py | 26 ++++++++++++++++++++ python/plugins/processing/tools/vector.py | 22 ++++++++++++----- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index 701af206361a..74ef76695721 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -122,6 +122,32 @@ def testValues(self): ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value) + def testUniqueValues(self): + ProcessingConfig.initialize() + + test_data = points2() + test_layer = QgsVectorLayer(test_data, 'test', 'ogr') + + # field by index + v = vector.uniqueValues(test_layer, 3) + self.assertEqual(len(v), len(set(v))) + self.assertEqual(set(v), set([2, 1, 0])) + + # field by name + v = vector.uniqueValues(test_layer, 'id_2') + self.assertEqual(len(v), len(set(v))) + self.assertEqual(set(v), set([2, 1, 0])) + + # test with selected features + previous_value = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) + ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, True) + test_layer.selectByIds([2, 4, 6]) + v = vector.uniqueValues(test_layer, 'id') + self.assertEqual(len(v), len(set(v))) + self.assertEqual(set(v), set([5, 7, 3])) + + ProcessingConfig.setSettingValue(ProcessingConfig.USE_SELECTED, previous_value) + if __name__ == '__main__': unittest.main() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index 5808276330d6..a800571600ca 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -122,13 +122,23 @@ def uniqueValues(layer, attribute): Attribute can be defined using a field names or a zero-based field index. It considers the existing selection. """ - values = [] + fieldIndex = resolveFieldIndex(layer, attribute) - feats = features(layer) - for feat in feats: - if feat.attributes()[fieldIndex] not in values: - values.append(feat.attributes()[fieldIndex]) - return values + if ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED) \ + and layer.selectedFeatureCount() > 0: + + # iterate through selected features + values = [] + request = QgsFeatureRequest().setSubsetOfAttributes([fieldIndex]).setFlags(QgsFeatureRequest.NoGeometry) + feats = features(layer, request) + for feat in feats: + if feat.attributes()[fieldIndex] not in values: + values.append(feat.attributes()[fieldIndex]) + return values + else: + # no selection, or not considering selecting + # so we can take advantage of provider side unique value optimisations + return layer.uniqueValues(fieldIndex) def resolveFieldIndex(layer, attr): From 898addfa3314ad23c17ee8d64f36c292a82b6cff Mon Sep 17 00:00:00 2001 From: Alexander Bruy Date: Wed, 12 Oct 2016 16:04:31 +0300 Subject: [PATCH 254/897] [processing] avoid division by zero (fix #15521) --- python/plugins/processing/algs/qgis/ConcaveHull.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/python/plugins/processing/algs/qgis/ConcaveHull.py b/python/plugins/processing/algs/qgis/ConcaveHull.py index 4dd63de67720..1104ff80f4b1 100644 --- a/python/plugins/processing/algs/qgis/ConcaveHull.py +++ b/python/plugins/processing/algs/qgis/ConcaveHull.py @@ -28,6 +28,7 @@ from qgis.core import Qgis, QgsFeatureRequest, QgsFeature, QgsGeometry, QgsWkbTypes from processing.core.GeoAlgorithm import GeoAlgorithm +from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterBoolean @@ -73,7 +74,10 @@ def processAlgorithm(self, progress): # Get max edge length from Delaunay triangles progress.setText(self.tr('Computing edges max length...')) features = delaunay_layer.getFeatures() - counter = 50. / delaunay_layer.featureCount() + if len(features) == 0: + raise GeoAlgorithmExecutionException(self.tr('No Delaunay triangles created.')) + + counter = 50. / len(features) lengths = [] edges = {} for feat in features: From 726bac5291f5c0cebc097987d5d8bb81f0596992 Mon Sep 17 00:00:00 2001 From: rldhont Date: Tue, 11 Oct 2016 20:18:01 +0200 Subject: [PATCH 255/897] Last Redo [BUGFIX][QGIS Server] Joins was not reloaded if the layer is in cache Add an accessor to QgsVectorLayer join buffer, to not duplicate QgsVectorLayerJoinBuffer::readXml code --- python/core/qgsvectorlayer.sip | 5 +++ src/core/qgsvectorlayer.h | 5 +++ src/server/qgsserverprojectparser.cpp | 48 ++------------------------- src/server/qgsserverprojectparser.h | 2 -- 4 files changed, 13 insertions(+), 47 deletions(-) diff --git a/python/core/qgsvectorlayer.sip b/python/core/qgsvectorlayer.sip index 2d815b789972..8f26c1eebcba 100644 --- a/python/core/qgsvectorlayer.sip +++ b/python/core/qgsvectorlayer.sip @@ -419,6 +419,11 @@ class QgsVectorLayer : QgsMapLayer @returns true if join was found and successfully removed */ bool removeJoin( const QString& joinLayerId ); + /** + * Acccessor to the join buffer object + * @note added 2.14.7 + */ + QgsVectorLayerJoinBuffer* joinBuffer(); const QList vectorJoins() const; /** diff --git a/src/core/qgsvectorlayer.h b/src/core/qgsvectorlayer.h index bd4c329e3d4c..450f837c9b6d 100644 --- a/src/core/qgsvectorlayer.h +++ b/src/core/qgsvectorlayer.h @@ -512,6 +512,11 @@ class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionConte @returns true if join was found and successfully removed */ bool removeJoin( const QString& joinLayerId ); + /** + * Acccessor to the join buffer object + * @note added 2.14.7 + */ + QgsVectorLayerJoinBuffer* joinBuffer() { return mJoinBuffer; } const QList vectorJoins() const; /** diff --git a/src/server/qgsserverprojectparser.cpp b/src/server/qgsserverprojectparser.cpp index 3f885124f0de..2b28d34cca5a 100644 --- a/src/server/qgsserverprojectparser.cpp +++ b/src/server/qgsserverprojectparser.cpp @@ -24,6 +24,7 @@ #include "qgsmaplayerregistry.h" #include "qgsmslayercache.h" #include "qgsrasterlayer.h" +#include "qgsvectorlayerjoinbuffer.h" #include "qgseditorwidgetregistry.h" #include "qgslayertreegroup.h" #include "qgslogger.h" @@ -237,7 +238,8 @@ QgsMapLayer* QgsServerProjectParser::createLayerFromElement( const QDomElement& { QgsVectorLayer* vlayer = qobject_cast( layer ); addValueRelationLayersForLayer( vlayer ); - addJoinsToLayer( const_cast( elem ), vlayer ); + QgsVectorLayerJoinBuffer* joinBuffer = vlayer->joinBuffer(); + joinBuffer->readXml( const_cast( elem ) ); } return layer; @@ -1552,50 +1554,6 @@ void QgsServerProjectParser::addJoinLayersForElement( const QDomElement& layerEl } } -// Based on QgsVectorLayerJoinBuffer::readXml -void QgsServerProjectParser::addJoinsToLayer( const QDomElement& layerElem, QgsVectorLayer *vl ) const -{ - if ( !vl ) - return; - - QDomElement vectorJoinsElem = layerElem.firstChildElement( "vectorjoins" ); - if ( vectorJoinsElem.isNull() ) - { - return; - } - - QDomNodeList joinList = vectorJoinsElem.elementsByTagName( "join" ); - for ( int i = 0; i < joinList.size(); ++i ) - { - QDomElement infoElem = joinList.at( i ).toElement(); - QgsVectorJoinInfo info; - info.joinFieldName = infoElem.attribute( "joinFieldName" ); - info.joinLayerId = infoElem.attribute( "joinLayerId" ); - info.targetFieldName = infoElem.attribute( "targetFieldName" ); - info.memoryCache = infoElem.attribute( "memoryCache" ).toInt(); - - info.joinFieldIndex = infoElem.attribute( "joinField" ).toInt(); //for compatibility with 1.x - info.targetFieldIndex = infoElem.attribute( "targetField" ).toInt(); //for compatibility with 1.x - - QDomElement subsetElem = infoElem.firstChildElement( "joinFieldsSubset" ); - if ( !subsetElem.isNull() ) - { - QStringList* fieldNames = new QStringList; - QDomNodeList fieldNodes = infoElem.elementsByTagName( "field" ); - for ( int i = 0; i < fieldNodes.count(); ++i ) - *fieldNames << fieldNodes.at( i ).toElement().attribute( "name" ); - info.setJoinFieldNamesSubset( fieldNames ); - } - - if ( infoElem.attribute( "hasCustomPrefix" ).toInt() ) - info.prefix = infoElem.attribute( "customPrefix" ); - else - info.prefix = QString::null; - - vl->addJoin( info ); - } -} - void QgsServerProjectParser::addValueRelationLayersForLayer( const QgsVectorLayer *vl ) const { if ( !vl ) diff --git a/src/server/qgsserverprojectparser.h b/src/server/qgsserverprojectparser.h index 8a067c160329..3744739e82b3 100644 --- a/src/server/qgsserverprojectparser.h +++ b/src/server/qgsserverprojectparser.h @@ -114,8 +114,6 @@ class SERVER_EXPORT QgsServerProjectParser /** Add layers for vector joins */ void addJoinLayersForElement( const QDomElement& layerElem ) const; - /** Update vector joins to layer, based on QgsVectorLayerJoinBuffer::readXml */ - void addJoinsToLayer( const QDomElement& layerElem, QgsVectorLayer *vl ) const; void addValueRelationLayersForLayer( const QgsVectorLayer *vl ) const; /** Add layers which are necessary for the evaluation of the expression function 'getFeature( layer, attributField, value)'*/ From 0f4cba5c2d96aaeabc9e634397230dfedb58cea3 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Tue, 11 Oct 2016 12:54:12 +0200 Subject: [PATCH 256/897] Fix bogus precision/scale in PostgreSQL for double values This reverts commit 92f71b696ca93c792ae5602ed82863fcef0e5006, which broke import of legit shapefiles by assuming wrong semantic for the non-constraining QgsField length/precision attributes. Closes #15188 Includes test --- .../postgres/qgspostgresprovider.cpp | 6 +-- tests/src/python/test_provider_postgres.py | 38 ++++++++++++++++++- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 08d862c58e11..86b14d45cd17 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -3421,16 +3421,16 @@ bool QgsPostgresProvider::convertField( QgsField &field, const QMap 0 ) + if ( fieldSize > 18 ) { fieldType = "numeric"; + fieldSize = -1; } else { fieldType = "float8"; - fieldSize = -1; - fieldPrec = -1; } + fieldPrec = -1; break; default: diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index 8c2782c79855..b89f67ff5880 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -14,11 +14,15 @@ __revision__ = '$Format:%H$' import qgis # NOQA +import psycopg2 import os from qgis.core import ( + QgsGeometry, + QgsPoint, QgsVectorLayer, + QgsVectorLayerImport, QgsFeatureRequest, QgsFeature, QgsTransactionGroup, @@ -50,11 +54,20 @@ def setUpClass(cls): assert cls.poly_vl.isValid() cls.poly_provider = cls.poly_vl.dataProvider() QgsEditorWidgetRegistry.instance().initEditors() + cls.con = psycopg2.connect(cls.dbconn) @classmethod def tearDownClass(cls): """Run after all tests""" + def execSQLCommand(self, sql): + self.assertTrue(self.con) + cur = self.con.cursor() + self.assertTrue(cur) + cur.execute(sql) + cur.close() + self.con.commit() + def enableCompiler(self): QSettings().setValue('/qgis/compileExpressions', True) @@ -424,6 +437,30 @@ def testDoubleArray(self): self.assertTrue(isinstance(f.attributes()[value_idx], list)) self.assertEqual(f.attributes()[value_idx], [1.1, 2, -5.12345]) + # See http://hub.qgis.org/issues/15188 + def testNumericPrecision(self): + uri = 'point?field=f1:int' + uri += '&field=f2:double(6,4)' + uri += '&field=f3:string(20)' + lyr = QgsVectorLayer(uri, "x", "memory") + self.assertTrue(lyr.isValid()) + f = QgsFeature(lyr.fields()) + f['f1'] = 1 + f['f2'] = 123.456 + f['f3'] = '12345678.90123456789' + lyr.dataProvider().addFeatures([f]) + uri = '%s table="qgis_test"."b18155" (g) key=\'f1\'' % (self.dbconn) + self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.b18155') + err = QgsVectorLayerImport.importLayer(lyr, uri, "postgres", lyr.crs()) + self.assertEqual(err[0], QgsVectorLayerImport.NoError, + 'unexpected import error {0}'.format(err)) + lyr = QgsVectorLayer(uri, "y", "postgres") + self.assertTrue(lyr.isValid()) + f = next(lyr.getFeatures()) + self.assertEqual(f['f1'], 1) + self.assertEqual(f['f2'], 123.456) + self.assertEqual(f['f3'], '12345678.90123456789') + class TestPyQgsPostgresProviderCompoundKey(unittest.TestCase, ProviderTestCase): @@ -454,6 +491,5 @@ def uncompiledFilters(self): def partiallyCompiledFilters(self): return set([]) - if __name__ == '__main__': unittest.main() From 34894c6f5a9ed0fd93d25f72354f819b5b0cbd8c Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 13 Oct 2016 00:16:22 +0200 Subject: [PATCH 257/897] [FEATURE] Vector layer save as: offer file/layer overwriting, new layer creation, feature and field appending When saving a vector layer into an existing file, depending on the capabilities of the output driver, the user can now decide whether: - to overwrite the whole file - to overwrite only the target layer (layer name is now configurable) - to append features to the existing target layer - to append features, add new fields if there are any. All above is available for drivers like GPKG, SpatiaLite, FileGDB, ... For drivers like Shapefile, MapInfo .tab, feature append is also available. --- python/core/qgsvectorfilewriter.sip | 142 +++++++++ src/app/ogr/qgsvectorlayersaveasdialog.cpp | 164 +++++++++- src/app/ogr/qgsvectorlayersaveasdialog.h | 5 + src/app/qgisapp.cpp | 48 ++- src/core/qgsvectorfilewriter.cpp | 317 ++++++++++++++++--- src/core/qgsvectorfilewriter.h | 155 ++++++++- src/ui/qgsvectorlayersaveasdialogbase.ui | 34 +- tests/src/python/test_qgsvectorfilewriter.py | 172 ++++++++++ 8 files changed, 964 insertions(+), 73 deletions(-) diff --git a/python/core/qgsvectorfilewriter.sip b/python/core/qgsvectorfilewriter.sip index a0032bc31c27..085a3e5ce680 100644 --- a/python/core/qgsvectorfilewriter.sip +++ b/python/core/qgsvectorfilewriter.sip @@ -132,6 +132,43 @@ class QgsVectorFileWriter virtual QVariant convert( int fieldIdxInLayer, const QVariant& value ); }; + /** Edition capability flags + * @note Added in QGIS 3.0 */ + enum EditionCapability + { + /** Flag to indicate that a new layer can be added to the dataset */ + CanAddNewLayer, + + /** Flag to indicate that new features can be added to an existing layer */ + CanAppendToExistingLayer , + + /** Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer */ + CanAddNewFieldsToExistingLayer, + + /** Flag to indicate that an existing layer can be deleted */ + CanDeleteLayer + }; + + typedef QFlags EditionCapabilities; + + /** Enumeration to describe how to handle existing files + @note Added in QGIS 3.0 + */ + enum ActionOnExistingFile + { + /** Create or overwrite file */ + CreateOrOverwriteFile, + + /** Create or overwrite layer */ + CreateOrOverwriteLayer, + + /** Append features to existing layer, but do not create new fields */ + AppendToLayerNoNewFields, + + /** Append features to existing layer, and create new fields if needed */ + AppendToLayerAddFields + }; + /** Write contents of vector layer to an (OGR supported) vector formt * @param layer layer to write * @param fileName file name to write to @@ -220,6 +257,88 @@ class QgsVectorFileWriter FieldValueConverter* fieldValueConverter = nullptr ); + + /** + * Options to pass to writeAsVectorFormat() + * @note Added in QGIS 3.0 + */ + class SaveVectorOptions + { + public: + /** Constructor */ + SaveVectorOptions(); + + /** Destructor */ + virtual ~SaveVectorOptions(); + + /** OGR driver to use */ + QString driverName; + + /** Layer name. If let empty, it will be derived from the filename */ + QString layerName; + + /** Action on existing file */ + QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile; + + /** Encoding to use */ + QString fileEncoding; + + /** Transform to reproject exported geometries with, or invalid transform + * for no transformation */ + QgsCoordinateTransform ct; + + /** Write only selected features of layer */ + bool onlySelectedFeatures; + + /** List of OGR data source creation options */ + QStringList datasourceOptions; + + /** List of OGR layer creation options */ + QStringList layerOptions; + + /** Only write geometries */ + bool skipAttributeCreation; + + /** Attributes to export (empty means all unless skipAttributeCreation is set) */ + QgsAttributeList attributes; + + /** Symbology to export */ + QgsVectorFileWriter::SymbologyExport symbologyExport; + + /** Scale of symbology */ + double symbologyScale; + + /** If not empty, only features intersecting the extent will be saved */ + QgsRectangle filterExtent; + + /** Set to a valid geometry type to override the default geometry type for the layer. This parameter + * allows for conversion of geometryless tables to null geometries, etc */ + QgsWkbTypes::Type overrideGeometryType; + + /** Set to true to force creation of multi* geometries */ + bool forceMulti; + + /** Set to true to include z dimension in output. This option is only valid if overrideGeometryType is set */ + bool includeZ; + + /** Field value converter */ + QgsVectorFileWriter::FieldValueConverter* fieldValueConverter; + }; + + /** Writes a layer out to a vector file. + * @param layer source layer to write + * @param fileName file name to write to + * @param options options. + * @param newFilename QString pointer which will contain the new file name created (in case it is different to fileName). + * @param errorMessage pointer to buffer fo error message + * @note added in 3.0 + */ + static WriterError writeAsVectorFormat( QgsVectorLayer* layer, + const QString& fileName, + const SaveVectorOptions& options, + QString *newFilename = nullptr, + QString *errorMessage = nullptr ); + /** Create a new vector file writer */ QgsVectorFileWriter( const QString& vectorFileName, const QString& fileEncoding, @@ -294,6 +413,27 @@ class QgsVectorFileWriter */ static QStringList defaultLayerOptions( const QString& driverName ); + /** + * Return edition capabilites for an existing dataset name. + * @note added in QGIS 3.0 + */ + static EditionCapabilities editionCapabilities( const QString& datasetName ); + + /** + * Returns whether the target layer already exists. + * @note added in QGIS 3.0 + */ + static bool targetLayerExists( const QString& datasetName, + const QString& layerName ); + + /** + * Returns whether there are among the attributes specified some that do not exist yet in the layer + * @note added in QGIS 3.0 + */ + static bool areThereNewFieldsToCreate( const QString& datasetName, + const QString& layerName, + QgsVectorLayer* layer, + const QgsAttributeList& attributes ); protected: //! @note not available in python bindings // OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ); @@ -302,3 +442,5 @@ class QgsVectorFileWriter QgsVectorFileWriter( const QgsVectorFileWriter& rh ); }; + +QFlags operator|(QgsVectorFileWriter::EditionCapability f1, QFlags f2); diff --git a/src/app/ogr/qgsvectorlayersaveasdialog.cpp b/src/app/ogr/qgsvectorlayersaveasdialog.cpp index aeda416c8758..3eb88086e5e3 100644 --- a/src/app/ogr/qgsvectorlayersaveasdialog.cpp +++ b/src/app/ogr/qgsvectorlayersaveasdialog.cpp @@ -23,6 +23,7 @@ #include "qgseditorwidgetfactory.h" #include "qgseditorwidgetregistry.h" +#include #include #include #include @@ -37,6 +38,7 @@ QgsVectorLayerSaveAsDialog::QgsVectorLayerSaveAsDialog( long srsid, QWidget* par , mLayer( 0 ) , mAttributeTableItemChangedSlotEnabled( true ) , mReplaceRawFieldValuesStateChangedSlotEnabled( true ) + , mActionOnExistingFile( QgsVectorFileWriter::CreateOrOverwriteFile ) { setup(); } @@ -46,6 +48,7 @@ QgsVectorLayerSaveAsDialog::QgsVectorLayerSaveAsDialog( QgsVectorLayer *layer, i , mLayer( layer ) , mAttributeTableItemChangedSlotEnabled( true ) , mReplaceRawFieldValuesStateChangedSlotEnabled( true ) + , mActionOnExistingFile( QgsVectorFileWriter::CreateOrOverwriteFile ) { if ( layer ) { @@ -210,6 +213,121 @@ QgsVectorLayerSaveAsDialog::~QgsVectorLayerSaveAsDialog() void QgsVectorLayerSaveAsDialog::accept() { + if ( QFile::exists( filename() ) ) + { + QgsVectorFileWriter::EditionCapabilities caps = + QgsVectorFileWriter::editionCapabilities( filename() ); + bool layerExists = QgsVectorFileWriter::targetLayerExists( filename(), + layername() ); + if ( layerExists ) + { + if ( !( caps & QgsVectorFileWriter::CanAppendToExistingLayer ) && + ( caps & QgsVectorFileWriter::CanDeleteLayer ) && + ( caps & QgsVectorFileWriter::CanAddNewLayer ) ) + { + QMessageBox msgBox; + msgBox.setIcon( QMessageBox::Question ); + msgBox.setWindowTitle( tr( "The layer already exists" ) ); + msgBox.setText( tr( "Do you want to overwrite the whole file or overwrite the layer?" ) ); + QPushButton *overwriteFileButton = msgBox.addButton( tr( "Overwrite file" ), QMessageBox::ActionRole ); + QPushButton *overwriteLayerButton = msgBox.addButton( tr( "Overwrite layer" ), QMessageBox::ActionRole ); + msgBox.setStandardButtons( QMessageBox::Cancel ); + msgBox.setDefaultButton( QMessageBox::Cancel ); + int ret = msgBox.exec(); + if ( ret == QMessageBox::Cancel ) + return; + if ( msgBox.clickedButton() == overwriteFileButton ) + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteFile; + else if ( msgBox.clickedButton() == overwriteLayerButton ) + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteLayer; + } + else if ( !( caps & QgsVectorFileWriter::CanAppendToExistingLayer ) ) + { + if ( QMessageBox::question( this, + tr( "The file already exists" ), + tr( "Do you want to overwrite the existing file?" ) ) == QMessageBox::NoButton ) + { + return; + } + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteFile; + } + else if (( caps & QgsVectorFileWriter::CanDeleteLayer ) && + ( caps & QgsVectorFileWriter::CanAddNewLayer ) ) + { + QMessageBox msgBox; + msgBox.setIcon( QMessageBox::Question ); + msgBox.setWindowTitle( tr( "The layer already exists" ) ); + msgBox.setText( tr( "Do you want to overwrite the whole file, overwrite the layer or append features to the layer?" ) ); + QPushButton *overwriteFileButton = msgBox.addButton( tr( "Overwrite file" ), QMessageBox::ActionRole ); + QPushButton *overwriteLayerButton = msgBox.addButton( tr( "Overwrite layer" ), QMessageBox::ActionRole ); + QPushButton *appendToLayerButton = msgBox.addButton( tr( "Append to layer" ), QMessageBox::ActionRole ); + msgBox.setStandardButtons( QMessageBox::Cancel ); + msgBox.setDefaultButton( QMessageBox::Cancel ); + int ret = msgBox.exec(); + if ( ret == QMessageBox::Cancel ) + return; + if ( msgBox.clickedButton() == overwriteFileButton ) + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteFile; + else if ( msgBox.clickedButton() == overwriteLayerButton ) + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteLayer; + else if ( msgBox.clickedButton() == appendToLayerButton ) + mActionOnExistingFile = QgsVectorFileWriter::AppendToLayerNoNewFields; + } + else + { + QMessageBox msgBox; + msgBox.setIcon( QMessageBox::Question ); + msgBox.setWindowTitle( tr( "The layer already exists" ) ); + msgBox.setText( tr( "Do you want to overwrite the whole file or append features to the layer?" ) ); + QPushButton *overwriteFileButton = msgBox.addButton( tr( "Overwrite file" ), QMessageBox::ActionRole ); + QPushButton *appendToLayerButton = msgBox.addButton( tr( "Append to layer" ), QMessageBox::ActionRole ); + msgBox.setStandardButtons( QMessageBox::Cancel ); + msgBox.setDefaultButton( QMessageBox::Cancel ); + int ret = msgBox.exec(); + if ( ret == QMessageBox::Cancel ) + return; + if ( msgBox.clickedButton() == overwriteFileButton ) + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteFile; + else if ( msgBox.clickedButton() == appendToLayerButton ) + mActionOnExistingFile = QgsVectorFileWriter::AppendToLayerNoNewFields; + } + + if ( mActionOnExistingFile == QgsVectorFileWriter::AppendToLayerNoNewFields ) + { + if ( QgsVectorFileWriter::areThereNewFieldsToCreate( filename(), + layername(), + mLayer, + selectedAttributes() ) ) + { + if ( QMessageBox::question( this, + tr( "The existing layer has different fields" ), + tr( "Do you want to add the missing fields to the layer?" ) ) == QMessageBox::Yes ) + { + mActionOnExistingFile = QgsVectorFileWriter::AppendToLayerAddFields; + } + } + } + + } + else + { + if (( caps & QgsVectorFileWriter::CanAddNewLayer ) ) + { + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteLayer; + } + else + { + if ( QMessageBox::question( this, + tr( "The file already exists" ), + tr( "Do you want to overwrite the existing file?" ) ) == QMessageBox::NoButton ) + { + return; + } + mActionOnExistingFile = QgsVectorFileWriter::CreateOrOverwriteFile; + } + } + } + QSettings settings; settings.setValue( "/UI/lastVectorFileFilterDir", QFileInfo( filename() ).absolutePath() ); settings.setValue( "/UI/lastVectorFormat", format() ); @@ -226,12 +344,13 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx bool selectAllFields = true; bool fieldsAsDisplayedValues = false; - if ( format() == "KML" ) + const QString sFormat( format() ); + if ( sFormat == "KML" ) { mAttributesSelection->setEnabled( true ); selectAllFields = false; } - else if ( format() == "DXF" ) + else if ( sFormat == "DXF" ) { mAttributesSelection->setEnabled( false ); selectAllFields = false; @@ -239,7 +358,23 @@ void QgsVectorLayerSaveAsDialog::on_mFormatComboBox_currentIndexChanged( int idx else { mAttributesSelection->setEnabled( true ); - fieldsAsDisplayedValues = ( format() == "CSV" || format() == "XLS" || format() == "XLSX" || format() == "ODS" ); + fieldsAsDisplayedValues = ( sFormat == "CSV" || sFormat == "XLS" || sFormat == "XLSX" || sFormat == "ODS" ); + } + + leLayername->setEnabled( sFormat == "KML" || + sFormat == "GPKG" || + sFormat == "XLSX" || + sFormat == "ODS" || + sFormat == "FileGDB" || + sFormat == "SQLite" || + sFormat == "SpatiaLite" ); + if ( !leLayername->isEnabled() ) + leLayername->setText( QString() ); + else if ( leLayername->text().isEmpty() && + !leFilename->text().isEmpty() ) + { + QString layerName = QFileInfo( leFilename->text() ).baseName(); + leLayername->setText( layerName ) ; } if ( mLayer ) @@ -485,7 +620,14 @@ void QgsVectorLayerSaveAsDialog::on_mAttributeTable_itemChanged( QTableWidgetIte void QgsVectorLayerSaveAsDialog::on_leFilename_textChanged( const QString& text ) { - buttonBox->button( QDialogButtonBox::Ok )->setEnabled( QFileInfo( text ).absoluteDir().exists() ); + buttonBox->button( QDialogButtonBox::Ok )->setEnabled( + !text.isEmpty() && QFileInfo( text ).absoluteDir().exists() ); + + if ( leLayername->isEnabled() ) + { + QString layerName = QFileInfo( text ).baseName(); + leLayername->setText( layerName ); + } } void QgsVectorLayerSaveAsDialog::on_browseFilename_clicked() @@ -493,7 +635,7 @@ void QgsVectorLayerSaveAsDialog::on_browseFilename_clicked() QSettings settings; QString dirName = leFilename->text().isEmpty() ? settings.value( "/UI/lastVectorFileFilterDir", QDir::homePath() ).toString() : leFilename->text(); QString filterString = QgsVectorFileWriter::filterForDriver( format() ); - QString outputFile = QFileDialog::getSaveFileName( nullptr, tr( "Save layer as..." ), dirName, filterString ); + QString outputFile = QFileDialog::getSaveFileName( nullptr, tr( "Save layer as..." ), dirName, filterString, nullptr, QFileDialog::DontConfirmOverwrite ); if ( !outputFile.isNull() ) { leFilename->setText( outputFile ); @@ -511,6 +653,11 @@ QString QgsVectorLayerSaveAsDialog::filename() const return leFilename->text(); } +QString QgsVectorLayerSaveAsDialog::layername() const +{ + return leLayername->text(); +} + QString QgsVectorLayerSaveAsDialog::encoding() const { return mEncodingComboBox->currentText(); @@ -611,7 +758,7 @@ QStringList QgsVectorLayerSaveAsDialog::layerOptions() const case QgsVectorFileWriter::String: { QLineEdit* le = mLayerOptionsGroupBox->findChild( it.key() ); - if ( le ) + if ( le && !le->text().isEmpty() ) options << QString( "%1=%2" ).arg( it.key(), le->text() ); break; } @@ -730,6 +877,11 @@ bool QgsVectorLayerSaveAsDialog::includeZ() const return mIncludeZCheckBox->isChecked(); } +QgsVectorFileWriter::ActionOnExistingFile QgsVectorLayerSaveAsDialog::creationActionOnExistingFile() const +{ + return mActionOnExistingFile; +} + void QgsVectorLayerSaveAsDialog::setIncludeZ( bool checked ) { mIncludeZCheckBox->setChecked( checked ); diff --git a/src/app/ogr/qgsvectorlayersaveasdialog.h b/src/app/ogr/qgsvectorlayersaveasdialog.h index 23bd037a7e4f..f7d71ed713e1 100644 --- a/src/app/ogr/qgsvectorlayersaveasdialog.h +++ b/src/app/ogr/qgsvectorlayersaveasdialog.h @@ -48,6 +48,7 @@ class APP_EXPORT QgsVectorLayerSaveAsDialog : public QDialog, private Ui::QgsVec QString format() const; QString encoding() const; QString filename() const; + QString layername() const; QStringList datasourceOptions() const; QStringList layerOptions() const; long crs() const; @@ -100,6 +101,9 @@ class APP_EXPORT QgsVectorLayerSaveAsDialog : public QDialog, private Ui::QgsVec */ void setIncludeZ( bool checked ); + /** Returns creation action */ + QgsVectorFileWriter::ActionOnExistingFile creationActionOnExistingFile() const; + private slots: void on_mFormatComboBox_currentIndexChanged( int idx ); @@ -126,6 +130,7 @@ class APP_EXPORT QgsVectorLayerSaveAsDialog : public QDialog, private Ui::QgsVec QgsVectorLayer *mLayer; bool mAttributeTableItemChangedSlotEnabled; bool mReplaceRawFieldValuesStateChangedSlotEnabled; + QgsVectorFileWriter::ActionOnExistingFile mActionOnExistingFile; }; #endif // QGSVECTORLAYERSAVEASDIALOG_H diff --git a/src/app/qgisapp.cpp b/src/app/qgisapp.cpp index 04493279e7ac..9828eb2df507 100644 --- a/src/app/qgisapp.cpp +++ b/src/app/qgisapp.cpp @@ -3521,7 +3521,11 @@ bool QgisApp::addVectorLayers( const QStringList &theLayerQStringList, const QSt QString base; if ( dataSourceType == "file" ) { - QFileInfo fi( src ); + QString srcWithoutLayername( src ); + int posPipe = srcWithoutLayername.indexOf( '|' ); + if ( posPipe >= 0 ) + srcWithoutLayername.resize( posPipe ); + QFileInfo fi( srcWithoutLayername ); base = fi.completeBaseName(); // if needed prompt for zipitem layers @@ -6228,22 +6232,29 @@ void QgisApp::saveAsVectorFileGeneral( QgsVectorLayer* vlayer, bool symbologyOpt // No need to use the converter if there is nothing to convert if ( !dialog->attributesAsDisplayedValues().isEmpty() ) converterPtr = &converter; + + QgsVectorFileWriter::SaveVectorOptions options; + options.driverName = format; + options.layerName = dialog->layername(); + options.actionOnExistingFile = dialog->creationActionOnExistingFile(); + options.fileEncoding = encoding; + options.ct = ct; + options.onlySelectedFeatures = dialog->onlySelected(); + options.datasourceOptions = datasourceOptions; + options.layerOptions = dialog->layerOptions(); + options.skipAttributeCreation = dialog->selectedAttributes().isEmpty(); + options.symbologyExport = static_cast< QgsVectorFileWriter::SymbologyExport >( dialog->symbologyExport() ); + options.symbologyScale = dialog->scaleDenominator(); + if ( dialog->hasFilterExtent() ) + options.filterExtent = filterExtent; + options.overrideGeometryType = autoGeometryType ? QgsWkbTypes::Unknown : forcedGeometryType; + options.forceMulti = dialog->forceMulti(); + options.includeZ = dialog->includeZ(); + options.attributes = dialog->selectedAttributes(); + options.fieldValueConverter = converterPtr; + error = QgsVectorFileWriter::writeAsVectorFormat( - vlayer, vectorFilename, encoding, ct, format, - dialog->onlySelected(), - &errorMessage, - datasourceOptions, dialog->layerOptions(), - dialog->selectedAttributes().isEmpty(), - &newFilename, - static_cast< QgsVectorFileWriter::SymbologyExport >( dialog->symbologyExport() ), - dialog->scaleDenominator(), - dialog->hasFilterExtent() ? &filterExtent : nullptr, - autoGeometryType ? QgsWkbTypes::Unknown : forcedGeometryType, - dialog->forceMulti(), - dialog->includeZ(), - dialog->selectedAttributes(), - converterPtr - ); + vlayer, vectorFilename, options, &newFilename, &errorMessage ); QApplication::restoreOverrideCursor(); @@ -6251,7 +6262,10 @@ void QgisApp::saveAsVectorFileGeneral( QgsVectorLayer* vlayer, bool symbologyOpt { if ( dialog->addToCanvas() ) { - addVectorLayers( QStringList( newFilename ), encoding, "file" ); + QString uri( newFilename ); + if ( !dialog->layername().isEmpty() ) + uri += "|layername=" + dialog->layername(); + addVectorLayers( QStringList( uri ), encoding, "file" ); } emit layerSavedAs( vlayer, vectorFilename ); messageBar()->pushMessage( tr( "Saving done" ), diff --git a/src/core/qgsvectorfilewriter.cpp b/src/core/qgsvectorfilewriter.cpp index b74dce3c74c2..16fd52da6299 100644 --- a/src/core/qgsvectorfilewriter.cpp +++ b/src/core/qgsvectorfilewriter.cpp @@ -98,7 +98,8 @@ QgsVectorFileWriter::QgsVectorFileWriter( , mFieldValueConverter( nullptr ) { init( theVectorFileName, theFileEncoding, fields, geometryType , - srs, driverName, datasourceOptions, layerOptions, newFilename, nullptr ); + srs, driverName, datasourceOptions, layerOptions, newFilename, nullptr, + QString(), CreateOrOverwriteFile ); } QgsVectorFileWriter::QgsVectorFileWriter( const QString& vectorFileName, @@ -111,7 +112,9 @@ QgsVectorFileWriter::QgsVectorFileWriter( const QString& vectorFileName, const QStringList& layerOptions, QString* newFilename, QgsVectorFileWriter::SymbologyExport symbologyExport, - FieldValueConverter* fieldValueConverter ) + FieldValueConverter* fieldValueConverter, + const QString& layerName, + ActionOnExistingFile action ) : mDS( nullptr ) , mLayer( nullptr ) , mOgrRef( nullptr ) @@ -124,7 +127,8 @@ QgsVectorFileWriter::QgsVectorFileWriter( const QString& vectorFileName, , mFieldValueConverter( nullptr ) { init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName, - datasourceOptions, layerOptions, newFilename, fieldValueConverter ); + datasourceOptions, layerOptions, newFilename, fieldValueConverter, + layerName, action ); } void QgsVectorFileWriter::init( QString vectorFileName, @@ -136,7 +140,9 @@ void QgsVectorFileWriter::init( QString vectorFileName, QStringList datasourceOptions, QStringList layerOptions, QString* newFilename, - FieldValueConverter* fieldValueConverter ) + FieldValueConverter* fieldValueConverter, + const QString& layerNameIn, + ActionOnExistingFile action ) { mRenderContext.setRendererScale( mSymbologyScaleDenominator ); @@ -224,7 +230,8 @@ void QgsVectorFileWriter::init( QString vectorFileName, } #endif - deleteShapeFile( vectorFileName ); + if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer ) + deleteShapeFile( vectorFileName ); } else { @@ -247,7 +254,27 @@ void QgsVectorFileWriter::init( QString vectorFileName, } } - QFile::remove( vectorFileName ); + if ( action == CreateOrOverwriteFile ) + { + if ( vectorFileName.endsWith( ".gdb", Qt::CaseInsensitive ) ) + { + QDir dir( vectorFileName ); + if ( dir.exists() ) + { + QFileInfoList fileList = dir.entryInfoList( + QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst ); + Q_FOREACH ( QFileInfo info, fileList ) + { + QFile::remove( info.absoluteFilePath() ); + } + } + QDir().rmdir( vectorFileName ); + } + else + { + QFile::remove( vectorFileName ); + } + } } if ( metadataFound && !metadata.compulsoryEncoding.isEmpty() ) @@ -272,7 +299,10 @@ void QgsVectorFileWriter::init( QString vectorFileName, } // create the data source - mDS = OGR_Dr_CreateDataSource( poDriver, TO8F( vectorFileName ), options ); + if ( action == CreateOrOverwriteFile ) + mDS = OGR_Dr_CreateDataSource( poDriver, TO8F( vectorFileName ), options ); + else + mDS = OGROpen( TO8F( vectorFileName ), TRUE, nullptr ); if ( options ) { @@ -285,12 +315,43 @@ void QgsVectorFileWriter::init( QString vectorFileName, if ( !mDS ) { mError = ErrCreateDataSource; - mErrorMessage = QObject::tr( "creation of data source failed (OGR error:%1)" ) - .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); + if ( action == CreateOrOverwriteFile ) + mErrorMessage = QObject::tr( "creation of data source failed (OGR error:%1)" ) + .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); + else + mErrorMessage = QObject::tr( "opening of data source in update mode failed (OGR error:%1)" ) + .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); return; } - QgsDebugMsg( "Created data source" ); + QString layerName( layerNameIn ); + if ( layerName.isEmpty() ) + layerName = QFileInfo( vectorFileName ).baseName(); + + if ( action == CreateOrOverwriteLayer ) + { + const int layer_count = OGR_DS_GetLayerCount( mDS ); + for ( int i = 0; i < layer_count; i++ ) + { + OGRLayerH hLayer = OGR_DS_GetLayer( mDS, i ); + if ( EQUAL( OGR_L_GetName( hLayer ), TO8F( layerName ) ) ) + { + if ( OGR_DS_DeleteLayer( mDS, i ) != OGRERR_NONE ) + { + mError = ErrCreateLayer; + mErrorMessage = QObject::tr( "overwriting of existing layer failed (OGR error:%1)" ) + .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); + return; + } + break; + } + } + } + + if ( action == CreateOrOverwriteFile ) + QgsDebugMsg( "Created data source" ); + else + QgsDebugMsg( "Opened data source in update mode" ); // use appropriate codec mCodec = QTextCodec::codecForName( fileEncoding.toLocal8Bit().constData() ); @@ -318,7 +379,6 @@ void QgsVectorFileWriter::init( QString vectorFileName, } // datasource created, now create the output layer - QString layerName = QFileInfo( vectorFileName ).baseName(); OGRwkbGeometryType wkbType = ogrTypeFromWkbType( geometryType ); // Remove FEATURE_DATASET layer option (used for ESRI File GDB driver) if its value is not set @@ -341,7 +401,10 @@ void QgsVectorFileWriter::init( QString vectorFileName, // disable encoding conversion of OGR Shapefile layer CPLSetConfigOption( "SHAPE_ENCODING", "" ); - mLayer = OGR_DS_CreateLayer( mDS, TO8F( layerName ), mOgrRef, wkbType, options ); + if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer ) + mLayer = OGR_DS_CreateLayer( mDS, TO8F( layerName ), mOgrRef, wkbType, options ); + else + mLayer = OGR_DS_GetLayerByName( mDS, TO8F( layerName ) ); if ( options ) { @@ -378,8 +441,12 @@ void QgsVectorFileWriter::init( QString vectorFileName, if ( !mLayer ) { - mErrorMessage = QObject::tr( "creation of layer failed (OGR error:%1)" ) - .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); + if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer ) + mErrorMessage = QObject::tr( "creation of layer failed (OGR error:%1)" ) + .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); + else + mErrorMessage = QObject::tr( "opening of layer failed (OGR error:%1)" ) + .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ); mError = ErrCreateLayer; return; } @@ -397,17 +464,30 @@ void QgsVectorFileWriter::init( QString vectorFileName, mFieldValueConverter = fieldValueConverter; - for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) + for ( int fldIdx = 0; ( action == CreateOrOverwriteFile || + action == CreateOrOverwriteLayer || + action == AppendToLayerAddFields ) && + fldIdx < fields.count(); ++fldIdx ) { QgsField attrField = fields.at( fldIdx ); - OGRFieldType ogrType = OFTString; //default to string - if ( fieldValueConverter ) { attrField = fieldValueConverter->fieldDefinition( fields.at( fldIdx ) ); } + QString name( attrField.name() ); + if ( action == AppendToLayerAddFields ) + { + int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) ); + if ( ogrIdx >= 0 ) + { + mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx ); + continue; + } + } + + OGRFieldType ogrType = OFTString; //default to string int ogrWidth = attrField.length(); int ogrPrecision = attrField.precision(); if ( ogrPrecision > 0 ) @@ -486,8 +566,6 @@ void QgsVectorFileWriter::init( QString vectorFileName, return; } - QString name( attrField.name() ); - if ( mOgrDriverName == "SQLite" && name.compare( "ogc_fid", Qt::CaseInsensitive ) == 0 ) { int i; @@ -581,6 +659,18 @@ void QgsVectorFileWriter::init( QString vectorFileName, mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx ); } + if ( action == AppendToLayerNoNewFields ) + { + for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) + { + QgsField attrField = fields.at( fldIdx ); + QString name( attrField.name() ); + int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) ); + if ( ogrIdx >= 0 ) + mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx ); + } + } + QgsDebugMsg( "Done creating fields" ); mWkbType = geometryType; @@ -2072,7 +2162,8 @@ void QgsVectorFileWriter::resetMap( const QgsAttributeList &attributes ) mAttrIdxToOgrIdx.clear(); for ( int i = 0; i < attributes.size(); i++ ) { - mAttrIdxToOgrIdx.insert( attributes[i], omap[i] ); + if ( omap.find( i ) != omap.end() ) + mAttrIdxToOgrIdx.insert( attributes[i], omap[i] ); } } @@ -2161,6 +2252,57 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe bool includeZ, QgsAttributeList attributes, FieldValueConverter* fieldValueConverter ) +{ + SaveVectorOptions options; + options.fileEncoding = fileEncoding; + options.ct = ct; + options.driverName = driverName; + options.onlySelectedFeatures = onlySelected; + options.datasourceOptions = datasourceOptions; + options.layerOptions = layerOptions; + options.skipAttributeCreation = skipAttributeCreation; + options.symbologyExport = symbologyExport; + options.symbologyScale = symbologyScale; + if ( filterExtent ) + options.filterExtent = *filterExtent; + options.overrideGeometryType = overrideGeometryType; + options.forceMulti = forceMulti; + options.includeZ = includeZ; + options.attributes = attributes; + options.fieldValueConverter = fieldValueConverter; + return writeAsVectorFormat( layer, fileName, options, newFilename, errorMessage ); +} + +QgsVectorFileWriter::SaveVectorOptions::SaveVectorOptions() + : driverName( "ESRI Shapefile" ) + , layerName( QString() ) + , actionOnExistingFile( CreateOrOverwriteFile ) + , fileEncoding( QString() ) + , ct( QgsCoordinateTransform() ) + , onlySelectedFeatures( false ) + , datasourceOptions( QStringList() ) + , layerOptions( QStringList() ) + , skipAttributeCreation( false ) + , attributes( QgsAttributeList() ) + , symbologyExport( NoSymbology ) + , symbologyScale( 1.0 ) + , filterExtent( QgsRectangle() ) + , overrideGeometryType( QgsWkbTypes::Unknown ) + , forceMulti( false ) + , fieldValueConverter( nullptr ) +{ +} + +QgsVectorFileWriter::SaveVectorOptions::~SaveVectorOptions() +{ +} + +QgsVectorFileWriter::WriterError +QgsVectorFileWriter::writeAsVectorFormat( QgsVectorLayer* layer, + const QString& fileName, + const SaveVectorOptions& options, + QString *newFilename, + QString *errorMessage ) { if ( !layer ) { @@ -2169,10 +2311,10 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe bool shallTransform = false; QgsCoordinateReferenceSystem outputCRS; - if ( ct.isValid() ) + if ( options.ct.isValid() ) { // This means we should transform - outputCRS = ct.destinationCrs(); + outputCRS = options.ct.destinationCrs(); shallTransform = true; } else @@ -2182,18 +2324,19 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe } QgsWkbTypes::Type destWkbType = layer->wkbType(); - if ( overrideGeometryType != QgsWkbTypes::Unknown ) + if ( options.overrideGeometryType != QgsWkbTypes::Unknown ) { - destWkbType = QgsWkbTypes::flatType( overrideGeometryType ); - if ( QgsWkbTypes::hasZ( overrideGeometryType ) || includeZ ) + destWkbType = QgsWkbTypes::flatType( options.overrideGeometryType ); + if ( QgsWkbTypes::hasZ( options.overrideGeometryType ) || options.includeZ ) destWkbType = QgsWkbTypes::addZ( destWkbType ); } - if ( forceMulti ) + if ( options.forceMulti ) { destWkbType = QgsWkbTypes::multiType( destWkbType ); } - if ( skipAttributeCreation ) + QgsAttributeList attributes( options.attributes ); + if ( options.skipAttributeCreation ) attributes.clear(); else if ( attributes.isEmpty() ) { @@ -2231,7 +2374,7 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe if ( layer->storageType() == "ESRI Shapefile" && !QgsWkbTypes::isMultiType( destWkbType ) ) { QgsFeatureRequest req; - if ( onlySelected ) + if ( options.onlySelectedFeatures ) { req.setFilterFids( layer->selectedFeaturesIds() ); } @@ -2265,11 +2408,17 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe } QgsVectorFileWriter* writer = - new QgsVectorFileWriter( fileName, fileEncoding, fields, destWkbType, - outputCRS, driverName, datasourceOptions, layerOptions, - newFilename, symbologyExport, - fieldValueConverter ); - writer->setSymbologyScaleDenominator( symbologyScale ); + new QgsVectorFileWriter( fileName, + options.fileEncoding, fields, destWkbType, + outputCRS, options.driverName, + options.datasourceOptions, + options.layerOptions, + newFilename, + options.symbologyExport, + options.fieldValueConverter, + options.layerName, + options.actionOnExistingFile ); + writer->setSymbologyScaleDenominator( options.symbologyScale ); if ( newFilename ) { @@ -2302,7 +2451,7 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe req.setFlags( QgsFeatureRequest::NoGeometry ); } req.setSubsetOfAttributes( attributes ); - if ( onlySelected ) + if ( options.onlySelectedFeatures ) req.setFilterFids( layer->selectedFeaturesIds() ); QgsFeatureIterator fit = layer->getFeatures( req ); @@ -2318,7 +2467,7 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe if ( r->capabilities() & QgsFeatureRenderer::SymbolLevels && r->usingSymbolLevels() ) { - QgsVectorFileWriter::WriterError error = writer->exportFeaturesSymbolLevels( layer, fit, ct, errorMessage ); + QgsVectorFileWriter::WriterError error = writer->exportFeaturesSymbolLevels( layer, fit, options.ct, errorMessage ); delete writer; return ( error == NoError ) ? NoError : ErrFeatureWriteFailed; } @@ -2328,9 +2477,9 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe //unit type QgsUnitTypes::DistanceUnit mapUnits = layer->crs().mapUnits(); - if ( ct.isValid() ) + if ( options.ct.isValid() ) { - mapUnits = ct.destinationCrs().mapUnits(); + mapUnits = options.ct.destinationCrs().mapUnits(); } writer->startRender( layer ); @@ -2358,7 +2507,7 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe if ( fet.hasGeometry() ) { QgsGeometry g = fet.geometry(); - g.transform( ct ); + g.transform( options.ct ); fet.setGeometry( g ); } } @@ -2376,10 +2525,10 @@ QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( QgsVe } } - if ( fet.hasGeometry() && filterExtent && !fet.geometry().intersects( *filterExtent ) ) + if ( fet.hasGeometry() && !options.filterExtent.isNull() && !fet.geometry().intersects( options.filterExtent ) ) continue; - if ( attributes.size() < 1 && skipAttributeCreation ) + if ( attributes.size() < 1 && options.skipAttributeCreation ) { fet.initAttributes( 0 ); } @@ -2927,3 +3076,91 @@ QStringList QgsVectorFileWriter::concatenateOptions( const QMapfields().at( idx ); + if ( OGR_FD_GetFieldIndex( defn, TO8F( fld.name() ) ) < 0 ) + { + ret = true; + break; + } + } + OGR_DS_Destroy( hDS ); + return ret; +} diff --git a/src/core/qgsvectorfilewriter.h b/src/core/qgsvectorfilewriter.h index 68664ef03cca..99b618782802 100644 --- a/src/core/qgsvectorfilewriter.h +++ b/src/core/qgsvectorfilewriter.h @@ -199,6 +199,45 @@ class CORE_EXPORT QgsVectorFileWriter virtual QVariant convert( int fieldIdxInLayer, const QVariant& value ); }; + /** Edition capability flags + * @note Added in QGIS 3.0 */ + enum EditionCapability + { + /** Flag to indicate that a new layer can be added to the dataset */ + CanAddNewLayer = 1 << 0, + + /** Flag to indicate that new features can be added to an existing layer */ + CanAppendToExistingLayer = 1 << 1, + + /** Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer */ + CanAddNewFieldsToExistingLayer = 1 << 2, + + /** Flag to indicate that an existing layer can be deleted */ + CanDeleteLayer = 1 << 3 + }; + + /** Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteLayer + * @note Added in QGIS 3.0 */ + Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability ) + + /** Enumeration to describe how to handle existing files + @note Added in QGIS 3.0 + */ + typedef enum + { + /** Create or overwrite file */ + CreateOrOverwriteFile, + + /** Create or overwrite layer */ + CreateOrOverwriteLayer, + + /** Append features to existing layer, but do not create new fields */ + AppendToLayerNoNewFields, + + /** Append features to existing layer, and create new fields if needed */ + AppendToLayerAddFields + } ActionOnExistingFile; + /** Write contents of vector layer to an (OGR supported) vector formt * @param layer layer to write * @param fileName file name to write to @@ -287,6 +326,88 @@ class CORE_EXPORT QgsVectorFileWriter FieldValueConverter* fieldValueConverter = nullptr ); + + /** \ingroup core + * Options to pass to writeAsVectorFormat() + * @note Added in QGIS 3.0 + */ + class CORE_EXPORT SaveVectorOptions + { + public: + /** Constructor */ + SaveVectorOptions(); + + /** Destructor */ + virtual ~SaveVectorOptions(); + + /** OGR driver to use */ + QString driverName; + + /** Layer name. If let empty, it will be derived from the filename */ + QString layerName; + + /** Action on existing file */ + ActionOnExistingFile actionOnExistingFile; + + /** Encoding to use */ + QString fileEncoding; + + /** Transform to reproject exported geometries with, or invalid transform + * for no transformation */ + QgsCoordinateTransform ct; + + /** Write only selected features of layer */ + bool onlySelectedFeatures; + + /** List of OGR data source creation options */ + QStringList datasourceOptions; + + /** List of OGR layer creation options */ + QStringList layerOptions; + + /** Only write geometries */ + bool skipAttributeCreation; + + /** Attributes to export (empty means all unless skipAttributeCreation is set) */ + QgsAttributeList attributes; + + /** Symbology to export */ + SymbologyExport symbologyExport; + + /** Scale of symbology */ + double symbologyScale; + + /** If not empty, only features intersecting the extent will be saved */ + QgsRectangle filterExtent; + + /** Set to a valid geometry type to override the default geometry type for the layer. This parameter + * allows for conversion of geometryless tables to null geometries, etc */ + QgsWkbTypes::Type overrideGeometryType; + + /** Set to true to force creation of multi* geometries */ + bool forceMulti; + + /** Set to true to include z dimension in output. This option is only valid if overrideGeometryType is set */ + bool includeZ; + + /** Field value converter */ + FieldValueConverter* fieldValueConverter; + }; + + /** Writes a layer out to a vector file. + * @param layer source layer to write + * @param fileName file name to write to + * @param options options. + * @param newFilename QString pointer which will contain the new file name created (in case it is different to fileName). + * @param errorMessage pointer to buffer fo error message + * @note added in 3.0 + */ + static WriterError writeAsVectorFormat( QgsVectorLayer* layer, + const QString& fileName, + const SaveVectorOptions& options, + QString *newFilename = nullptr, + QString *errorMessage = nullptr ); + /** Create a new vector file writer */ QgsVectorFileWriter( const QString& vectorFileName, const QString& fileEncoding, @@ -369,6 +490,28 @@ class CORE_EXPORT QgsVectorFileWriter */ static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ); + /** + * Return edition capabilites for an existing dataset name. + * @note added in QGIS 3.0 + */ + static EditionCapabilities editionCapabilities( const QString& datasetName ); + + /** + * Returns whether the target layer already exists. + * @note added in QGIS 3.0 + */ + static bool targetLayerExists( const QString& datasetName, + const QString& layerName ); + + /** + * Returns whether there are among the attributes specified some that do not exist yet in the layer + * @note added in QGIS 3.0 + */ + static bool areThereNewFieldsToCreate( const QString& datasetName, + const QString& layerName, + QgsVectorLayer* layer, + const QgsAttributeList& attributes ); + protected: //! @note not available in python bindings OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ); @@ -420,6 +563,8 @@ class CORE_EXPORT QgsVectorFileWriter * @param newFilename potentially modified file name (output parameter) * @param symbologyExport symbology to export * @param fieldValueConverter field value converter (added in QGIS 2.16) + * @param layerName layer name. If let empty, it will be derived from the filename (added in QGIS 3.0) + * @param action action on existing file (added in QGIS 3.0) */ QgsVectorFileWriter( const QString& vectorFileName, const QString& fileEncoding, @@ -431,14 +576,18 @@ class CORE_EXPORT QgsVectorFileWriter const QStringList &layerOptions, QString *newFilename, SymbologyExport symbologyExport, - FieldValueConverter* fieldValueConverter + FieldValueConverter* fieldValueConverter, + const QString& layerName, + ActionOnExistingFile action ); void init( QString vectorFileName, QString fileEncoding, const QgsFields& fields, QgsWkbTypes::Type geometryType, QgsCoordinateReferenceSystem srs, const QString& driverName, QStringList datasourceOptions, QStringList layerOptions, QString* newFilename, - FieldValueConverter* fieldValueConverter ); + FieldValueConverter* fieldValueConverter, + const QString& layerName, + ActionOnExistingFile action ); void resetMap( const QgsAttributeList &attributes ); QgsRenderContext mRenderContext; @@ -467,4 +616,6 @@ class CORE_EXPORT QgsVectorFileWriter static QStringList concatenateOptions( const QMap& options ); }; +Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities ) + #endif diff --git a/src/ui/qgsvectorlayersaveasdialogbase.ui b/src/ui/qgsvectorlayersaveasdialogbase.ui index 76d06aa2b5b4..9011e861ee11 100644 --- a/src/ui/qgsvectorlayersaveasdialogbase.ui +++ b/src/ui/qgsvectorlayersaveasdialogbase.ui @@ -23,21 +23,21 @@ - + CRS - + false - + false @@ -57,26 +57,43 @@ - + - Save as + File name leFilename - + Qt::StrongFocus + + + + Layer name + + + leFilename + + + + + + + false + + + @@ -90,8 +107,8 @@ 0 0 - 550 - 953 + 557 + 922 @@ -434,6 +451,7 @@ mFormatComboBox leFilename browseFilename + leLayername mCrsSelector scrollArea mEncodingComboBox diff --git a/tests/src/python/test_qgsvectorfilewriter.py b/tests/src/python/test_qgsvectorfilewriter.py index 943e61ad5420..c07260801d80 100644 --- a/tests/src/python/test_qgsvectorfilewriter.py +++ b/tests/src/python/test_qgsvectorfilewriter.py @@ -29,6 +29,7 @@ from qgis.PyQt.QtCore import QDate, QTime, QDateTime, QVariant, QDir import os import osgeo.gdal +from osgeo import gdal, ogr import platform from qgis.testing import start_app, unittest from utilities import writeShape, compareWkt @@ -485,6 +486,177 @@ def testDefaultLayerOptions(self): options = QgsVectorFileWriter.defaultLayerOptions('GML') self.assertEqual(options, []) + def testOverwriteLayer(self): + """Tests writing a layer with a field value converter.""" + + ml = QgsVectorLayer('Point?field=firstfield:int', 'test', 'memory') + provider = ml.dataProvider() + + ft = QgsFeature() + ft.setAttributes([1]) + provider.addFeatures([ft]) + + options = QgsVectorFileWriter.SaveVectorOptions() + options.driverName = 'GPKG' + options.layerName = 'test' + filename = '/vsimem/out.gpkg' + write_result = QgsVectorFileWriter.writeAsVectorFormat( + ml, + filename, + options) + self.assertEqual(write_result, QgsVectorFileWriter.NoError) + + ds = ogr.Open(filename, update=1) + lyr = ds.GetLayerByName('test') + self.assertIsNotNone(lyr) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 1) + ds.CreateLayer('another_layer') + del f + del lyr + del ds + + caps = QgsVectorFileWriter.editionCapabilities(filename) + self.assertTrue((caps & QgsVectorFileWriter.CanAddNewLayer)) + self.assertTrue((caps & QgsVectorFileWriter.CanAppendToExistingLayer)) + self.assertTrue((caps & QgsVectorFileWriter.CanAddNewFieldsToExistingLayer)) + self.assertTrue((caps & QgsVectorFileWriter.CanDeleteLayer)) + + self.assertTrue(QgsVectorFileWriter.targetLayerExists(filename, 'test')) + + self.assertFalse(QgsVectorFileWriter.areThereNewFieldsToCreate(filename, 'test', ml, [0])) + + # Test CreateOrOverwriteLayer + ml = QgsVectorLayer('Point?field=firstfield:int', 'test', 'memory') + provider = ml.dataProvider() + + ft = QgsFeature() + ft.setAttributes([2]) + provider.addFeatures([ft]) + + options = QgsVectorFileWriter.SaveVectorOptions() + options.driverName = 'GPKG' + options.layerName = 'test' + options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer + filename = '/vsimem/out.gpkg' + write_result = QgsVectorFileWriter.writeAsVectorFormat( + ml, + filename, + options) + self.assertEqual(write_result, QgsVectorFileWriter.NoError) + + ds = ogr.Open(filename) + lyr = ds.GetLayerByName('test') + self.assertIsNotNone(lyr) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 2) + # another_layer should still exist + self.assertIsNotNone(ds.GetLayerByName('another_layer')) + del f + del lyr + del ds + + # Test CreateOrOverwriteFile + ml = QgsVectorLayer('Point?field=firstfield:int', 'test', 'memory') + provider = ml.dataProvider() + + ft = QgsFeature() + ft.setAttributes([3]) + provider.addFeatures([ft]) + + options = QgsVectorFileWriter.SaveVectorOptions() + options.driverName = 'GPKG' + options.layerName = 'test' + filename = '/vsimem/out.gpkg' + write_result = QgsVectorFileWriter.writeAsVectorFormat( + ml, + filename, + options) + self.assertEqual(write_result, QgsVectorFileWriter.NoError) + + ds = ogr.Open(filename) + lyr = ds.GetLayerByName('test') + self.assertIsNotNone(lyr) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 3) + # another_layer should no longer exist + self.assertIsNone(ds.GetLayerByName('another_layer')) + del f + del lyr + del ds + + # Test AppendToLayerNoNewFields + ml = QgsVectorLayer('Point?field=firstfield:int&field=secondfield:int', 'test', 'memory') + provider = ml.dataProvider() + + ft = QgsFeature() + ft.setAttributes([4, -10]) + provider.addFeatures([ft]) + + self.assertTrue(QgsVectorFileWriter.areThereNewFieldsToCreate(filename, 'test', ml, [0, 1])) + + options = QgsVectorFileWriter.SaveVectorOptions() + options.driverName = 'GPKG' + options.layerName = 'test' + options.actionOnExistingFile = QgsVectorFileWriter.AppendToLayerNoNewFields + filename = '/vsimem/out.gpkg' + write_result = QgsVectorFileWriter.writeAsVectorFormat( + ml, + filename, + options) + self.assertEqual(write_result, QgsVectorFileWriter.NoError) + + ds = ogr.Open(filename) + lyr = ds.GetLayerByName('test') + self.assertEqual(lyr.GetLayerDefn().GetFieldCount(), 1) + self.assertIsNotNone(lyr) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 3) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 4) + del f + del lyr + del ds + + # Test AppendToLayerAddFields + ml = QgsVectorLayer('Point?field=firstfield:int&field=secondfield:int', 'test', 'memory') + provider = ml.dataProvider() + + ft = QgsFeature() + ft.setAttributes([5, -1]) + provider.addFeatures([ft]) + + self.assertTrue(QgsVectorFileWriter.areThereNewFieldsToCreate(filename, 'test', ml, [0, 1])) + + options = QgsVectorFileWriter.SaveVectorOptions() + options.driverName = 'GPKG' + options.layerName = 'test' + options.actionOnExistingFile = QgsVectorFileWriter.AppendToLayerAddFields + filename = '/vsimem/out.gpkg' + write_result = QgsVectorFileWriter.writeAsVectorFormat( + ml, + filename, + options) + self.assertEqual(write_result, QgsVectorFileWriter.NoError) + + ds = ogr.Open(filename) + lyr = ds.GetLayerByName('test') + self.assertEqual(lyr.GetLayerDefn().GetFieldCount(), 2) + self.assertIsNotNone(lyr) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 3) + self.assertFalse(f.IsFieldSet('secondfield')) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 4) + self.assertFalse(f.IsFieldSet('secondfield')) + f = lyr.GetNextFeature() + self.assertEqual(f['firstfield'], 5) + self.assertEqual(f['secondfield'], -1) + del f + del lyr + del ds + + gdal.Unlink(filename) if __name__ == '__main__': unittest.main() From 37b00eb602500950a99a531a4e9c2b6891247786 Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Wed, 5 Oct 2016 18:02:46 -0600 Subject: [PATCH 258/897] [WFS provider] Fix auth config extra expansion and auth prioritization --- src/providers/wfs/qgswfsdatasourceuri.cpp | 36 +++++++++++++++-------- src/providers/wfs/qgswfsdatasourceuri.h | 8 ++--- src/providers/wfs/qgswfsprovider.cpp | 6 ++-- 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/src/providers/wfs/qgswfsdatasourceuri.cpp b/src/providers/wfs/qgswfsdatasourceuri.cpp index 447260e4fdb0..49894462cb8e 100644 --- a/src/providers/wfs/qgswfsdatasourceuri.cpp +++ b/src/providers/wfs/qgswfsdatasourceuri.cpp @@ -41,14 +41,19 @@ QgsWFSDataSourceURI::QgsWFSDataSourceURI( const QString& uri ) QString typeName = url.queryItemValue( QgsWFSConstants::URI_PARAM_TYPENAME ); QString version = url.queryItemValue( QgsWFSConstants::URI_PARAM_VERSION ); QString filter = url.queryItemValue( QgsWFSConstants::URI_PARAM_FILTER ); - mAuth.mUserName = url.queryItemValue( QgsWFSConstants::URI_PARAM_USERNAME ); - // In QgsDataSourceURI, the "username" param is named "user", check it - if ( mAuth.mUserName.isEmpty() ) + mAuth.mAuthCfg = url.queryItemValue( QgsWFSConstants::URI_PARAM_AUTHCFG ); + // NOTE: A defined authcfg overrides any older username/password auth + // Only check for older auth if it is undefined + if ( mAuth.mAuthCfg.isEmpty() ) { - mAuth.mUserName = url.queryItemValue( QgsWFSConstants::URI_PARAM_USER ); + mAuth.mUserName = url.queryItemValue( QgsWFSConstants::URI_PARAM_USERNAME ); + // In QgsDataSourceURI, the "username" param is named "user", check it + if ( mAuth.mUserName.isEmpty() ) + { + mAuth.mUserName = url.queryItemValue( QgsWFSConstants::URI_PARAM_USER ); + } + mAuth.mPassword = url.queryItemValue( QgsWFSConstants::URI_PARAM_PASSWORD ); } - mAuth.mPassword = url.queryItemValue( QgsWFSConstants::URI_PARAM_PASSWORD ); - mAuth.mAuthCfg = url.queryItemValue( QgsWFSConstants::URI_PARAM_AUTHCFG ); // Now remove all stuff that is not the core URL url.removeQueryItem( "SERVICE" ); @@ -90,19 +95,24 @@ QgsWFSDataSourceURI::QgsWFSDataSourceURI( const QString& uri ) const QString QgsWFSDataSourceURI::uri( bool expandAuthConfig ) const { QgsDataSourceUri theURI( mURI ); - // Add auth params back into the uri + // Add authcfg param back into the uri (must be non-empty value) if ( ! mAuth.mAuthCfg.isEmpty() ) { theURI.setAuthConfigId( mAuth.mAuthCfg ); } - if ( ! mAuth.mUserName.isEmpty() ) - { - theURI.setUsername( mAuth.mUserName ); - } - if ( ! mAuth.mPassword.isEmpty() ) + else { - theURI.setPassword( mAuth.mPassword ); + // Add any older username/password auth params back in (allow empty values) + if ( ! mAuth.mUserName.isNull() ) + { + theURI.setUsername( mAuth.mUserName ); + } + if ( ! mAuth.mPassword.isNull() ) + { + theURI.setPassword( mAuth.mPassword ); + } } + // NOTE: avoid expanding authcfg here; it is handled during network access return theURI.uri( expandAuthConfig ); } diff --git a/src/providers/wfs/qgswfsdatasourceuri.h b/src/providers/wfs/qgswfsdatasourceuri.h index fcf946c4a4c9..f2e1fd41caf7 100644 --- a/src/providers/wfs/qgswfsdatasourceuri.h +++ b/src/providers/wfs/qgswfsdatasourceuri.h @@ -35,11 +35,11 @@ struct QgsWFSAuthorization //! set authorization header bool setAuthorization( QNetworkRequest &request ) const { - if ( !mAuthCfg.isEmpty() ) + if ( !mAuthCfg.isEmpty() ) // must be non-empty value { return QgsAuthManager::instance()->updateNetworkRequest( request, mAuthCfg ); } - else if ( !mUserName.isNull() || !mPassword.isNull() ) + else if ( !mUserName.isNull() || !mPassword.isNull() ) // allow empty values { request.setRawHeader( "Authorization", "Basic " + QString( "%1:%2" ).arg( mUserName, mPassword ).toLatin1().toBase64() ); } @@ -65,8 +65,8 @@ class QgsWFSDataSourceURI explicit QgsWFSDataSourceURI( const QString& uri ); - /** Return the URI */ - const QString uri( bool expandAuthConfig = true ) const; + /** Return the URI, avoiding expansion of authentication configuration, which is handled during network access */ + const QString uri( bool expandAuthConfig = false ) const; /** Return base URL (with SERVICE=WFS parameter if bIncludeServiceWFS=true) */ QUrl baseURL( bool bIncludeServiceWFS = true ) const; diff --git a/src/providers/wfs/qgswfsprovider.cpp b/src/providers/wfs/qgswfsprovider.cpp index 4c9cbbd4b111..78cdd69c5d50 100644 --- a/src/providers/wfs/qgswfsprovider.cpp +++ b/src/providers/wfs/qgswfsprovider.cpp @@ -1104,7 +1104,7 @@ bool QgsWFSProvider::describeFeatureType( QString& geometryAttribute, QgsFields& { fields.clear(); - QgsWFSDescribeFeatureType describeFeatureType( mShared->mURI.uri( false ) ); + QgsWFSDescribeFeatureType describeFeatureType( mShared->mURI.uri() ); if ( !describeFeatureType.requestFeatureType( mShared->mWFSVersion, mShared->mURI.typeName() ) ) { @@ -1340,7 +1340,7 @@ bool QgsWFSProvider::sendTransactionDocument( const QDomDocument& doc, QDomDocum return false; } - QgsWFSTransactionRequest request( mShared->mURI.uri( false ) ); + QgsWFSTransactionRequest request( mShared->mURI.uri() ); return request.send( doc, serverResponse ); } @@ -1443,7 +1443,7 @@ bool QgsWFSProvider::getCapabilities() if ( mShared->mCaps.version.isEmpty() ) { - QgsWfsCapabilities getCapabilities( mShared->mURI.uri( false ) ); + QgsWfsCapabilities getCapabilities( mShared->mURI.uri() ); const bool synchronous = true; const bool forceRefresh = false; if ( !getCapabilities.requestCapabilities( synchronous, forceRefresh ) ) From a629deef3018caf4b12ebf51096ae1c6b77c388c Mon Sep 17 00:00:00 2001 From: Larry Shaffer Date: Thu, 6 Oct 2016 10:17:42 -0600 Subject: [PATCH 259/897] [auth] Reinstate auth system reply expansions for OWS providers - Apparently this was lost during a git squash of commits for 2.12 PR --- src/core/qgsgml.cpp | 14 ++++++++++ src/providers/wcs/qgswcscapabilities.cpp | 35 ++++++++++++++++++++++++ src/providers/wcs/qgswcscapabilities.h | 3 ++ src/providers/wcs/qgswcsprovider.cpp | 27 ++++++++++++++++++ src/providers/wcs/qgswcsprovider.h | 10 +++++++ src/providers/wfs/qgswfsdatasourceuri.h | 12 +++++++- src/providers/wfs/qgswfsrequest.cpp | 23 ++++++++++++++++ src/providers/wms/qgswmscapabilities.cpp | 20 ++++++++++++++ src/providers/wms/qgswmscapabilities.h | 9 ++++++ src/providers/wms/qgswmsprovider.cpp | 2 ++ 10 files changed, 154 insertions(+), 1 deletion(-) diff --git a/src/core/qgsgml.cpp b/src/core/qgsgml.cpp index e6fbb614c2b6..48ef9e85374b 100644 --- a/src/core/qgsgml.cpp +++ b/src/core/qgsgml.cpp @@ -83,6 +83,20 @@ int QgsGml::getFeatures( const QString& uri, QgsWkbTypes::Type* wkbType, QgsRect } QNetworkReply* reply = QgsNetworkAccessManager::instance()->get( request ); + if ( !authcfg.isEmpty() ) + { + if ( !QgsAuthManager::instance()->updateNetworkReply( reply, authcfg ) ) + { + reply->deleteLater(); + QgsMessageLog::logMessage( + tr( "GML Getfeature network reply update failed for authcfg %1" ).arg( authcfg ), + tr( "Network" ), + QgsMessageLog::CRITICAL + ); + return 1; + } + } + connect( reply, SIGNAL( finished() ), this, SLOT( setFinished() ) ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( handleProgressEvent( qint64, qint64 ) ) ); diff --git a/src/providers/wcs/qgswcscapabilities.cpp b/src/providers/wcs/qgswcscapabilities.cpp index 3a79011c74d3..8312f11d2aa8 100644 --- a/src/providers/wcs/qgswcscapabilities.cpp +++ b/src/providers/wcs/qgswcscapabilities.cpp @@ -157,6 +157,14 @@ bool QgsWcsCapabilities::sendRequest( QString const & url ) QgsDebugMsg( QString( "getcapabilities: %1" ).arg( url ) ); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !setAuthorizationReply( mCapabilitiesReply ) ) + { + mCapabilitiesReply->deleteLater(); + mCapabilitiesReply = nullptr; + mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); + QgsMessageLog::logMessage( mError, tr( "WCS" ) ); + return false; + } connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) ); @@ -367,6 +375,15 @@ void QgsWcsCapabilities::capabilitiesReplyFinished() mCapabilitiesReply->deleteLater(); QgsDebugMsg( QString( "redirected getcapabilities: %1" ).arg( redirect.toString() ) ); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !setAuthorizationReply( mCapabilitiesReply ) ) + { + mCapabilitiesResponse.clear(); + mCapabilitiesReply->deleteLater(); + mCapabilitiesReply = nullptr; + mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); + QgsMessageLog::logMessage( mError, tr( "WCS" ) ); + return; + } connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) ); @@ -393,6 +410,15 @@ void QgsWcsCapabilities::capabilitiesReplyFinished() mCapabilitiesReply->deleteLater(); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !setAuthorizationReply( mCapabilitiesReply ) ) + { + mCapabilitiesResponse.clear(); + mCapabilitiesReply->deleteLater(); + mCapabilitiesReply = nullptr; + mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); + QgsMessageLog::logMessage( mError, tr( "WCS" ) ); + return; + } connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ) ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ) ); return; @@ -1178,6 +1204,15 @@ bool QgsWcsCapabilities::setAuthorization( QNetworkRequest &request ) const return true; } +bool QgsWcsCapabilities::setAuthorizationReply( QNetworkReply *reply ) const +{ + if ( mUri.hasParam( "authcfg" ) && !mUri.param( "authcfg" ).isEmpty() ) + { + return QgsAuthManager::instance()->updateNetworkReply( reply, mUri.param( "authcfg" ) ); + } + return true; +} + void QgsWcsCapabilities::showMessageBox( const QString& title, const QString& text ) { QgsMessageOutput *message = QgsMessageOutput::createMessageOutput(); diff --git a/src/providers/wcs/qgswcscapabilities.h b/src/providers/wcs/qgswcscapabilities.h index f1d44f71ae96..edfce9a9aaa3 100644 --- a/src/providers/wcs/qgswcscapabilities.h +++ b/src/providers/wcs/qgswcscapabilities.h @@ -162,6 +162,9 @@ class QgsWcsCapabilities : public QObject //! set authorization header bool setAuthorization( QNetworkRequest &request ) const; + //! set authorization reply + bool setAuthorizationReply( QNetworkReply * reply ) const; + QString version() const { return mCapabilities.version; } /** diff --git a/src/providers/wcs/qgswcsprovider.cpp b/src/providers/wcs/qgswcsprovider.cpp index 83a178e260a9..d0a40aa139f3 100644 --- a/src/providers/wcs/qgswcsprovider.cpp +++ b/src/providers/wcs/qgswcsprovider.cpp @@ -1663,6 +1663,15 @@ QgsWcsDownloadHandler::QgsWcsDownloadHandler( const QUrl& url, QgsWcsAuthorizati request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, cacheLoadControl ); mCacheReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !mAuth.setAuthorizationReply( mCacheReply ) ) + { + mCacheReply->deleteLater(); + mCacheReply = nullptr; + QgsMessageLog::logMessage( tr( "Network reply update failed for authentication config" ), + tr( "WCS" ) ); + finish(); + return; + } connect( mCacheReply, SIGNAL( finished() ), this, SLOT( cacheReplyFinished() ) ); connect( mCacheReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( cacheReplyProgress( qint64, qint64 ) ) ); @@ -1701,6 +1710,15 @@ void QgsWcsDownloadHandler::cacheReplyFinished() return; } mCacheReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !mAuth.setAuthorizationReply( mCacheReply ) ) + { + mCacheReply->deleteLater(); + mCacheReply = nullptr; + QgsMessageLog::logMessage( tr( "Network reply update failed for authentication config" ), + tr( "WCS" ) ); + finish(); + return; + } connect( mCacheReply, SIGNAL( finished() ), this, SLOT( cacheReplyFinished() ) ); connect( mCacheReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( cacheReplyProgress( qint64, qint64 ) ) ); @@ -1868,6 +1886,15 @@ void QgsWcsDownloadHandler::cacheReplyFinished() mCacheReply->deleteLater(); mCacheReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !mAuth.setAuthorizationReply( mCacheReply ) ) + { + mCacheReply->deleteLater(); + mCacheReply = nullptr; + QgsMessageLog::logMessage( tr( "Network reply update failed for authentication config" ), + tr( "WCS" ) ); + finish(); + return; + } connect( mCacheReply, SIGNAL( finished() ), this, SLOT( cacheReplyFinished() ), Qt::DirectConnection ); connect( mCacheReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( cacheReplyProgress( qint64, qint64 ) ), Qt::DirectConnection ); diff --git a/src/providers/wcs/qgswcsprovider.h b/src/providers/wcs/qgswcsprovider.h index 71ef1573e1cb..07f3b5d38de4 100644 --- a/src/providers/wcs/qgswcsprovider.h +++ b/src/providers/wcs/qgswcsprovider.h @@ -72,6 +72,16 @@ struct QgsWcsAuthorization return true; } + //! set authorization reply + bool setAuthorizationReply( QNetworkReply * reply ) const + { + if ( !mAuthCfg.isEmpty() ) + { + return QgsAuthManager::instance()->updateNetworkReply( reply, mAuthCfg ); + } + return true; + } + //! Username for basic http authentication QString mUserName; diff --git a/src/providers/wfs/qgswfsdatasourceuri.h b/src/providers/wfs/qgswfsdatasourceuri.h index f2e1fd41caf7..497926246e2e 100644 --- a/src/providers/wfs/qgswfsdatasourceuri.h +++ b/src/providers/wfs/qgswfsdatasourceuri.h @@ -32,7 +32,7 @@ struct QgsWFSAuthorization , mAuthCfg( authcfg ) {} - //! set authorization header + //! update authorization for request bool setAuthorization( QNetworkRequest &request ) const { if ( !mAuthCfg.isEmpty() ) // must be non-empty value @@ -46,6 +46,16 @@ struct QgsWFSAuthorization return true; } + //! update authorization for reply + bool setAuthorizationReply( QNetworkReply *reply ) const + { + if ( !mAuthCfg.isEmpty() ) + { + return QgsAuthManager::instance()->updateNetworkReply( reply, mAuthCfg ); + } + return true; + } + //! Username for basic http authentication QString mUserName; diff --git a/src/providers/wfs/qgswfsrequest.cpp b/src/providers/wfs/qgswfsrequest.cpp index 3ef7c5190b64..dbf38eb0a359 100644 --- a/src/providers/wfs/qgswfsrequest.cpp +++ b/src/providers/wfs/qgswfsrequest.cpp @@ -116,6 +116,13 @@ bool QgsWfsRequest::sendGET( const QUrl& url, bool synchronous, bool forceRefres } mReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !mUri.auth().setAuthorizationReply( mReply ) ) + { + mErrorCode = QgsWfsRequest::NetworkError; + mErrorMessage = errorMessageFailedAuth(); + QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) ); + return false; + } connect( mReply, SIGNAL( finished() ), this, SLOT( replyFinished() ) ); connect( mReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( replyProgress( qint64, qint64 ) ) ); @@ -160,6 +167,13 @@ bool QgsWfsRequest::sendPOST( const QUrl& url, const QString& contentTypeHeader, request.setHeader( QNetworkRequest::ContentTypeHeader, contentTypeHeader ); mReply = QgsNetworkAccessManager::instance()->post( request, data ); + if ( !mUri.auth().setAuthorizationReply( mReply ) ) + { + mErrorCode = QgsWfsRequest::NetworkError; + mErrorMessage = errorMessageFailedAuth(); + QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) ); + return false; + } connect( mReply, SIGNAL( finished() ), this, SLOT( replyFinished() ) ); connect( mReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( replyProgress( qint64, qint64 ) ) ); @@ -243,6 +257,15 @@ void QgsWfsRequest::replyFinished() QgsDebugMsg( QString( "redirected: %1 forceRefresh=%2" ).arg( redirect.toString() ).arg( mForceRefresh ) ); mReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !mUri.auth().setAuthorizationReply( mReply ) ) + { + mResponse.clear(); + mErrorMessage = errorMessageFailedAuth(); + mErrorCode = QgsWfsRequest::NetworkError; + QgsMessageLog::logMessage( mErrorMessage, tr( "WFS" ) ); + emit downloadFinished(); + return; + } connect( mReply, SIGNAL( finished() ), this, SLOT( replyFinished() ) ); connect( mReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( replyProgress( qint64, qint64 ) ) ); return; diff --git a/src/providers/wms/qgswmscapabilities.cpp b/src/providers/wms/qgswmscapabilities.cpp index 61e57aa3ab3a..031806e5c490 100644 --- a/src/providers/wms/qgswmscapabilities.cpp +++ b/src/providers/wms/qgswmscapabilities.cpp @@ -1955,6 +1955,14 @@ bool QgsWmsCapabilitiesDownload::downloadCapabilities() request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); + if ( !mAuth.setAuthorizationReply( mCapabilitiesReply ) ) + { + mCapabilitiesReply->deleteLater(); + mCapabilitiesReply = nullptr; + mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); + QgsMessageLog::logMessage( mError, tr( "WMS" ) ); + return false; + } connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ), Qt::DirectConnection ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ), Qt::DirectConnection ); @@ -2021,6 +2029,18 @@ void QgsWmsCapabilitiesDownload::capabilitiesReplyFinished() QgsDebugMsg( QString( "redirected getcapabilities: %1 forceRefresh=%2" ).arg( redirect.toString() ).arg( mForceRefresh ) ); mCapabilitiesReply = QgsNetworkAccessManager::instance()->get( request ); + + if ( !mAuth.setAuthorizationReply( mCapabilitiesReply ) ) + { + mHttpCapabilitiesResponse.clear(); + mCapabilitiesReply->deleteLater(); + mCapabilitiesReply = nullptr; + mError = tr( "Download of capabilities failed: network reply update failed for authentication config" ); + QgsMessageLog::logMessage( mError, tr( "WMS" ) ); + emit downloadFinished(); + return; + } + connect( mCapabilitiesReply, SIGNAL( finished() ), this, SLOT( capabilitiesReplyFinished() ), Qt::DirectConnection ); connect( mCapabilitiesReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( capabilitiesReplyProgress( qint64, qint64 ) ), Qt::DirectConnection ); return; diff --git a/src/providers/wms/qgswmscapabilities.h b/src/providers/wms/qgswmscapabilities.h index f760e5c35f20..7e4babee6721 100644 --- a/src/providers/wms/qgswmscapabilities.h +++ b/src/providers/wms/qgswmscapabilities.h @@ -512,6 +512,15 @@ struct QgsWmsAuthorization } return true; } + //! set authorization reply + bool setAuthorizationReply( QNetworkReply * reply ) const + { + if ( !mAuthCfg.isEmpty() ) + { + return QgsAuthManager::instance()->updateNetworkReply( reply, mAuthCfg ); + } + return true; + } //! Username for basic http authentication QString mUserName; diff --git a/src/providers/wms/qgswmsprovider.cpp b/src/providers/wms/qgswmsprovider.cpp index 8e3e4dfe45ed..89b6655e3553 100644 --- a/src/providers/wms/qgswmsprovider.cpp +++ b/src/providers/wms/qgswmsprovider.cpp @@ -3110,6 +3110,7 @@ void QgsWmsProvider::identifyReplyFinished() QgsDebugMsg( QString( "redirected getfeatureinfo: %1" ).arg( redirect.toString() ) ); mIdentifyReply = QgsNetworkAccessManager::instance()->get( QNetworkRequest( redirect.toUrl() ) ); + mSettings.authorization().setAuthorizationReply( mIdentifyReply ); mIdentifyReply->setProperty( "eventLoop", QVariant::fromValue( qobject_cast( loop ) ) ); connect( mIdentifyReply, SIGNAL( finished() ), this, SLOT( identifyReplyFinished() ) ); return; @@ -4100,6 +4101,7 @@ QgsWmsLegendDownloadHandler::startUrl( const QUrl& url ) request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); mReply = mNetworkAccessManager.get( request ); + mSettings.authorization().setAuthorizationReply( mReply ); connect( mReply, SIGNAL( error( QNetworkReply::NetworkError ) ), this, SLOT( errored( QNetworkReply::NetworkError ) ) ); connect( mReply, SIGNAL( finished() ), this, SLOT( finished() ) ); connect( mReply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( progressed( qint64, qint64 ) ) ); From d30a8c1fc2229477cbe4772dad822c8a94991721 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 13 Oct 2016 20:32:53 +0200 Subject: [PATCH 260/897] Add hint about running specific test methods in python unit tests --- tests/README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/README.md b/tests/README.md index 9e786979d62b..517b13da4482 100644 --- a/tests/README.md +++ b/tests/README.md @@ -16,7 +16,6 @@ Individual tests can be run using `ctest`. For example if the output of `make check` ends like this: - ``` The following tests FAILED: 77 - PyQgsLocalServer (Failed) @@ -31,6 +30,17 @@ You could re-run the failing test with: The parameter `-V` enables verbose mode and `-R` takes a regular expression as parameter and will only run matching tests. + +For python tests, you can run a specific test inside a unit file +with something like this: + +``` + QGIS_PREFIX_PATH=output PYTHONPATH=output/python:$PYTHONPATH \ + python ${srcdir}/tests/src/python/test_qgsvectorfilewriter.py + TestQgsVectorLayer.testOverwriteLayer +``` + + Advanced configuration ---------------------- From 11043c41ee023a4b3676fcdd928caaeb612ad1a3 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 14 Oct 2016 08:20:43 +1000 Subject: [PATCH 261/897] Add default shortcut to open attribute table (F6) --- src/ui/qgisapp.ui | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/ui/qgisapp.ui b/src/ui/qgisapp.ui index d57ab3f91030..255a649af091 100644 --- a/src/ui/qgisapp.ui +++ b/src/ui/qgisapp.ui @@ -1399,6 +1399,9 @@ Open &Attribute Table + + F6 + From b7321ecde6d26d983e15aaf0a64909273aa05edb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 14 Oct 2016 08:34:22 +1000 Subject: [PATCH 262/897] Fix incorrect selection rect drawn for composer items on windows --- src/core/composer/qgscomposermousehandles.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/core/composer/qgscomposermousehandles.cpp b/src/core/composer/qgscomposermousehandles.cpp index 292051df9909..acc5573ab357 100644 --- a/src/core/composer/qgscomposermousehandles.cpp +++ b/src/core/composer/qgscomposermousehandles.cpp @@ -194,7 +194,12 @@ void QgsComposerMouseHandles::drawSelectedItemBounds( QPainter* painter ) //not resizing or moving, so just map from scene bounds itemBounds = mapRectFromItem(( *itemIter ), ( *itemIter )->rectWithFrame() ); } - painter->drawPolygon( itemBounds ); + + // drawPolygon causes issues on windows - corners of path may be missing resulting in triangles being drawn + // instead of rectangles! (Same cause as #13343) + QPainterPath path; + path.addPolygon( itemBounds ); + painter->drawPath( path ); } painter->restore(); } From ec2d7fea0c651545df4cc936a2808817f0dc705a Mon Sep 17 00:00:00 2001 From: nirvn Date: Fri, 14 Oct 2016 11:13:05 +0700 Subject: [PATCH 263/897] [FEATURE] control over drawing of composer table grid horizontal & vertical lines --- python/core/composer/qgscomposertablev2.sip | 40 ++++++++ .../qgscomposerattributetablewidget.cpp | 42 ++++++++ .../qgscomposerattributetablewidget.h | 2 + src/core/composer/qgscomposertablev2.cpp | 95 +++++++++++++----- src/core/composer/qgscomposertablev2.h | 46 +++++++++ .../qgscomposerattributetablewidgetbase.ui | 14 +++ tests/src/core/testqgscomposertablev2.cpp | 80 +++++++++++++++ ..._composerattributetable_horizontalgrid.png | Bin 0 -> 23133 bytes ...ed_composerattributetable_verticalgrid.png | Bin 0 -> 21344 bytes 9 files changed, 292 insertions(+), 27 deletions(-) create mode 100644 tests/testdata/control_images/composer_table/expected_composerattributetable_horizontalgrid/expected_composerattributetable_horizontalgrid.png create mode 100644 tests/testdata/control_images/composer_table/expected_composerattributetable_verticalgrid/expected_composerattributetable_verticalgrid.png diff --git a/python/core/composer/qgscomposertablev2.sip b/python/core/composer/qgscomposertablev2.sip index ad9faccc8387..a8ade577d3d8 100644 --- a/python/core/composer/qgscomposertablev2.sip +++ b/python/core/composer/qgscomposertablev2.sip @@ -310,6 +310,46 @@ class QgsComposerTableV2: QgsComposerMultiFrame */ QColor gridColor() const; + /** Sets whether the grid's horizontal lines should be drawn in the table + * @param horizontalGird set to true to draw grid's horizontal lines + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setVerticalGrid + * @note added in QGIS 3.0 + */ + void setHorizontalGrid( const bool horizontalGrid ); + + /** Returns whether the grid's horizontal lines are drawn in the table + * @returns true if grid's horizontal lines are drawn + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setVerticalGrid + * @note added in QGIS 3.0 + */ + bool horizontalGrid() const; + + /** Sets whether the grid's vertical lines should be drawn in the table + * @param verticalGird set to true to draw grid's vertical lines + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setHorizontalGrid + * @note added in QGIS 3.0 + */ + void setVerticalGrid( const bool verticalGrid ); + + /** Returns whether the grid's vertical lines are drawn in the table + * @returns true if grid's vertical lines are drawn + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setHorizontalGrid + * @note added in QGIS 3.0 + */ + bool verticalGrid() const; + /** Sets color used for background of table. * @param color table background color * @see backgroundColor diff --git a/src/app/composer/qgscomposerattributetablewidget.cpp b/src/app/composer/qgscomposerattributetablewidget.cpp index a2a264e0b96e..f21e5240b541 100644 --- a/src/app/composer/qgscomposerattributetablewidget.cpp +++ b/src/app/composer/qgscomposerattributetablewidget.cpp @@ -357,6 +357,44 @@ void QgsComposerAttributeTableWidget::on_mGridColorButton_colorChanged( const QC } } +void QgsComposerAttributeTableWidget::on_mDrawHorizontalGrid_toggled( bool state ) +{ + if ( !mComposerTable ) + { + return; + } + + QgsComposition* composition = mComposerTable->composition(); + if ( composition ) + { + composition->beginMultiFrameCommand( mComposerTable, tr( "Table horizontal grid toggled" ) ); + } + mComposerTable->setHorizontalGrid( state ); + if ( composition ) + { + composition->endMultiFrameCommand(); + } +} + +void QgsComposerAttributeTableWidget::on_mDrawVerticalGrid_toggled( bool state ) +{ + if ( !mComposerTable ) + { + return; + } + + QgsComposition* composition = mComposerTable->composition(); + if ( composition ) + { + composition->beginMultiFrameCommand( mComposerTable, tr( "Table vertical grid toggled" ) ); + } + mComposerTable->setVerticalGrid( state ); + if ( composition ) + { + composition->endMultiFrameCommand(); + } +} + void QgsComposerAttributeTableWidget::on_mShowGridGroupCheckBox_toggled( bool state ) { if ( !mComposerTable ) @@ -428,6 +466,8 @@ void QgsComposerAttributeTableWidget::updateGuiElements() mMarginSpinBox->setValue( mComposerTable->cellMargin() ); mGridStrokeWidthSpinBox->setValue( mComposerTable->gridStrokeWidth() ); mGridColorButton->setColor( mComposerTable->gridColor() ); + mDrawHorizontalGrid->setChecked( mComposerTable->horizontalGrid() ); + mDrawVerticalGrid->setChecked( mComposerTable->verticalGrid() ); if ( mComposerTable->showGrid() ) { mShowGridGroupCheckBox->setChecked( true ); @@ -568,6 +608,8 @@ void QgsComposerAttributeTableWidget::blockAllSignals( bool b ) mGridColorButton->blockSignals( b ); mGridStrokeWidthSpinBox->blockSignals( b ); mBackgroundColorButton->blockSignals( b ); + mDrawHorizontalGrid->blockSignals( b ); + mDrawVerticalGrid->blockSignals( b ); mShowGridGroupCheckBox->blockSignals( b ); mShowOnlyVisibleFeaturesCheckBox->blockSignals( b ); mUniqueOnlyCheckBox->blockSignals( b ); diff --git a/src/app/composer/qgscomposerattributetablewidget.h b/src/app/composer/qgscomposerattributetablewidget.h index 66d4b9e3cb53..76749c776c30 100644 --- a/src/app/composer/qgscomposerattributetablewidget.h +++ b/src/app/composer/qgscomposerattributetablewidget.h @@ -55,6 +55,8 @@ class QgsComposerAttributeTableWidget: public QgsComposerItemBaseWidget, private void on_mHeaderFontColorButton_colorChanged( const QColor& newColor ); void on_mContentFontPushButton_clicked(); void on_mContentFontColorButton_colorChanged( const QColor& newColor ); + void on_mDrawHorizontalGrid_toggled( bool state ); + void on_mDrawVerticalGrid_toggled( bool state ); void on_mShowGridGroupCheckBox_toggled( bool state ); void on_mShowOnlyVisibleFeaturesCheckBox_stateChanged( int state ); void on_mFeatureFilterCheckBox_stateChanged( int state ); diff --git a/src/core/composer/qgscomposertablev2.cpp b/src/core/composer/qgscomposertablev2.cpp index c9548fe58683..f28c4523bc2e 100644 --- a/src/core/composer/qgscomposertablev2.cpp +++ b/src/core/composer/qgscomposertablev2.cpp @@ -58,6 +58,8 @@ QgsComposerTableV2::QgsComposerTableV2( QgsComposition *composition, bool create , mShowGrid( true ) , mGridStrokeWidth( 0.5 ) , mGridColor( Qt::black ) + , mHorizontalGrid( true ) + , mVerticalGrid( true ) , mBackgroundColor( Qt::white ) , mWrapBehaviour( TruncateText ) { @@ -120,6 +122,8 @@ bool QgsComposerTableV2::writeXml( QDomElement& elem, QDomDocument & doc, bool i elem.setAttribute( "contentFontColor", QgsSymbolLayerUtils::encodeColor( mContentFontColor ) ); elem.setAttribute( "gridStrokeWidth", QString::number( mGridStrokeWidth ) ); elem.setAttribute( "gridColor", QgsSymbolLayerUtils::encodeColor( mGridColor ) ); + elem.setAttribute( "horizontalGrid", mHorizontalGrid ); + elem.setAttribute( "verticalGrid", mVerticalGrid ); elem.setAttribute( "showGrid", mShowGrid ); elem.setAttribute( "backgroundColor", QgsSymbolLayerUtils::encodeColor( mBackgroundColor ) ); elem.setAttribute( "wrapBehaviour", QString::number( static_cast< int >( mWrapBehaviour ) ) ); @@ -187,6 +191,8 @@ bool QgsComposerTableV2::readXml( const QDomElement &itemElem, const QDomDocumen mContentFontColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "contentFontColor", "0,0,0,255" ) ); mCellMargin = itemElem.attribute( "cellMargin", "1.0" ).toDouble(); mGridStrokeWidth = itemElem.attribute( "gridStrokeWidth", "0.5" ).toDouble(); + mHorizontalGrid = itemElem.attribute( "horizontalGrid", "1" ).toInt(); + mVerticalGrid = itemElem.attribute( "verticalGrid", "1" ).toInt(); mShowGrid = itemElem.attribute( "showGrid", "1" ).toInt(); mGridColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "gridColor", "0,0,0,255" ) ); mBackgroundColor = QgsSymbolLayerUtils::decodeColor( itemElem.attribute( "backgroundColor", "255,255,255,0" ) ); @@ -243,18 +249,18 @@ int QgsComposerTableV2::rowsVisible( double frameHeight, int firstRow, bool incl if ( includeHeader ) { //frame has a header - headerHeight = 2 * ( mShowGrid ? mGridStrokeWidth : 0 ) + 2 * mCellMargin + QgsComposerUtils::fontAscentMM( mHeaderFont ); + headerHeight = 2 * ( mShowGrid && mHorizontalGrid ? mGridStrokeWidth : 0 ) + 2 * mCellMargin + QgsComposerUtils::fontAscentMM( mHeaderFont ); } else { //frame has no header text, just the stroke - headerHeight = ( mShowGrid ? mGridStrokeWidth : 0 ); + headerHeight = ( mShowGrid && mHorizontalGrid ? mGridStrokeWidth : 0 ); } //remaining height available for content rows double contentHeight = frameHeight - headerHeight; - double gridHeight = ( mShowGrid ? mGridStrokeWidth : 0 ); + double gridHeight = ( mShowGrid && mHorizontalGrid ? mGridStrokeWidth : 0 ); int currentRow = firstRow; while ( contentHeight > 0 && currentRow <= mTableContents.count() ) @@ -266,7 +272,7 @@ int QgsComposerTableV2::rowsVisible( double frameHeight, int firstRow, bool incl if ( includeEmptyRows && contentHeight > 0 ) { - double rowHeight = ( mShowGrid ? mGridStrokeWidth : 0 ) + 2 * mCellMargin + QgsComposerUtils::fontAscentMM( mContentFont ); + double rowHeight = ( mShowGrid && mHorizontalGrid ? mGridStrokeWidth : 0 ) + 2 * mCellMargin + QgsComposerUtils::fontAscentMM( mContentFont ); currentRow += qMax( floor( contentHeight / rowHeight ), 0.0 ); } @@ -341,7 +347,8 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd //calculate which rows to show in this frame QPair< int, int > rowsToShow = rowRange( frameIndex ); - double gridSize = mShowGrid ? mGridStrokeWidth : 0; + double gridSizeX = mShowGrid && mVerticalGrid ? mGridStrokeWidth : 0; + double gridSizeY = mShowGrid && mHorizontalGrid ? mGridStrokeWidth : 0; double cellHeaderHeight = QgsComposerUtils::fontAscentMM( mHeaderFont ) + 2 * mCellMargin; double cellBodyHeight = QgsComposerUtils::fontAscentMM( mContentFont ) + 2 * mCellMargin; QRectF cell; @@ -375,8 +382,8 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd //draw the text p->setPen( Qt::SolidLine ); - double currentX = gridSize; - double currentY = gridSize; + double currentX = gridSizeX; + double currentY = gridSizeY; if ( drawHeader ) { //draw the headers @@ -425,12 +432,12 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd currentX += mMaxColumnWidthMap[ col ]; currentX += mCellMargin; - currentX += gridSize; + currentX += gridSizeX; col++; } currentY += cellHeaderHeight; - currentY += gridSize; + currentY += gridSizeY; } //now draw the body cells @@ -441,7 +448,7 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd for ( int row = rowsToShow.first; row < rowsToShow.second; ++row ) { rowsDrawn++; - currentX = gridSize; + currentX = gridSizeX; int col = 0; //calculate row height @@ -481,11 +488,11 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd currentX += mMaxColumnWidthMap[ col ]; currentX += mCellMargin; - currentX += gridSize; + currentX += gridSizeX; col++; } currentY += rowHeight; - currentY += gridSize; + currentY += gridSizeY; } } @@ -497,13 +504,13 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd //draw background of empty rows for ( int row = rowsDrawn; row < numberRowsToDraw; ++row ) { - currentX = gridSize; + currentX = gridSizeX; int col = 0; if ( mergeCells ) { p->setBrush( backgroundColor( row + 10000, 0 ) ); - p->drawRect( QRectF( gridSize, currentY, mTableSize.width() - 2 * gridSize, cellBodyHeight ) ); + p->drawRect( QRectF( gridSizeX, currentY, mTableSize.width() - 2 * gridSizeX, cellBodyHeight ) ); } else { @@ -517,11 +524,11 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd // currentY = gridSize; currentX += mMaxColumnWidthMap[ col ] + 2 * mCellMargin; - currentX += gridSize; + currentX += gridSizeX; col++; } } - currentY += cellBodyHeight + gridSize; + currentY += cellBodyHeight + gridSizeY; } p->restore(); } @@ -534,15 +541,21 @@ void QgsComposerTableV2::render( QPainter *p, const QRectF &, const int frameInd gridPen.setColor( mGridColor ); gridPen.setJoinStyle( Qt::MiterJoin ); p->setPen( gridPen ); - drawHorizontalGridLines( p, rowsToShow.first, rowsToShow.second + numberEmptyRows, drawHeader ); - drawVerticalGridLines( p, mMaxColumnWidthMap, rowsToShow.first, rowsToShow.second + numberEmptyRows, drawHeader, mergeCells ); + if ( mHorizontalGrid ) + { + drawHorizontalGridLines( p, rowsToShow.first, rowsToShow.second + numberEmptyRows, drawHeader ); + } + if ( mVerticalGrid ) + { + drawVerticalGridLines( p, mMaxColumnWidthMap, rowsToShow.first, rowsToShow.second + numberEmptyRows, drawHeader, mergeCells ); + } } //special case - no records and table is set to ShowMessage mode if ( emptyTable && mEmptyTableMode == QgsComposerTableV2::ShowMessage ) { - double messageX = gridSize + mCellMargin; - double messageY = gridSize + ( drawHeader ? cellHeaderHeight + gridSize : 0 ); + double messageX = gridSizeX + mCellMargin; + double messageY = gridSizeY + ( drawHeader ? cellHeaderHeight + gridSizeY : 0 ); cell = QRectF( messageX, messageY, mTableSize.width() - messageX, cellBodyHeight ); QgsComposerUtils::drawText( p, cell, mEmptyTableMessage, mContentFont, mContentFontColor, Qt::AlignHCenter, Qt::AlignVCenter, static_cast< Qt::TextFlag >( 0 ) ); } @@ -729,6 +742,34 @@ void QgsComposerTableV2::setGridColor( const QColor &color ) emit changed(); } +void QgsComposerTableV2::setHorizontalGrid( const bool horizontalGrid ) +{ + if ( horizontalGrid == mHorizontalGrid ) + { + return; + } + + mHorizontalGrid = horizontalGrid; + //since grid spacing has changed, we need to recalculate the table size + recalculateTableSize(); + + emit changed(); +} + +void QgsComposerTableV2::setVerticalGrid( const bool verticalGrid ) +{ + if ( verticalGrid == mVerticalGrid ) + { + return; + } + + mVerticalGrid = verticalGrid; + //since grid spacing has changed, we need to recalculate the table size + recalculateTableSize(); + + emit changed(); +} + void QgsComposerTableV2::setBackgroundColor( const QColor &color ) { if ( color == mBackgroundColor ) @@ -1002,7 +1043,7 @@ double QgsComposerTableV2::totalWidth() totalWidth += maxColWidthIt.value(); } totalWidth += ( 2 * mMaxColumnWidthMap.size() * mCellMargin ); - totalWidth += ( mMaxColumnWidthMap.size() + 1 ) * ( mShowGrid ? mGridStrokeWidth : 0 ); + totalWidth += ( mMaxColumnWidthMap.size() + 1 ) * ( mShowGrid && mVerticalGrid ? mGridStrokeWidth : 0 ); return totalWidth; } @@ -1216,22 +1257,22 @@ void QgsComposerTableV2::drawVerticalGridLines( QPainter *painter, const QMapdrawLine( QPointF( currentX, halfGridStrokeWidth ), QPointF( currentX, tableHeight - halfGridStrokeWidth ) ); - currentX += ( mShowGrid ? mGridStrokeWidth : 0 ); + currentX += ( mShowGrid && mVerticalGrid ? mGridStrokeWidth : 0 ); QMap::const_iterator maxColWidthIt = maxWidthMap.constBegin(); int col = 1; for ( ; maxColWidthIt != maxWidthMap.constEnd(); ++maxColWidthIt ) @@ -1246,7 +1287,7 @@ void QgsComposerTableV2::drawVerticalGridLines( QPainter *painter, const QMapdrawLine( QPointF( currentX, halfGridStrokeWidth ), QPointF( currentX, headerHeight - halfGridStrokeWidth ) ); } - currentX += ( mShowGrid ? mGridStrokeWidth : 0 ); + currentX += ( mShowGrid && mVerticalGrid ? mGridStrokeWidth : 0 ); col++; } } diff --git a/src/core/composer/qgscomposertablev2.h b/src/core/composer/qgscomposertablev2.h index 4930858f919d..e2c7af551847 100644 --- a/src/core/composer/qgscomposertablev2.h +++ b/src/core/composer/qgscomposertablev2.h @@ -338,6 +338,46 @@ class CORE_EXPORT QgsComposerTableV2: public QgsComposerMultiFrame */ QColor gridColor() const { return mGridColor; } + /** Sets whether the grid's horizontal lines should be drawn in the table + * @param horizontalGrid set to true to draw grid's horizontal lines + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setVerticalGrid + * @note added in QGIS 3.0 + */ + void setHorizontalGrid( const bool horizontalGrid ); + + /** Returns whether the grid's horizontal lines are drawn in the table + * @returns true if grid's horizontal lines are drawn + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setVerticalGrid + * @note added in QGIS 3.0 + */ + bool horizontalGrid() const { return mHorizontalGrid; } + + /** Sets whether the grid's vertical lines should be drawn in the table + * @param verticalGrid set to true to draw grid's vertical lines + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setHorizontalGrid + * @note added in QGIS 3.0 + */ + void setVerticalGrid( const bool verticalGrid ); + + /** Returns whether the grid's vertical lines are drawn in the table + * @returns true if grid's vertical lines are drawn + * @see setShowGrid + * @see setGridStrokeWidth + * @see setGridColor + * @see setHorizontalGrid + * @note added in QGIS 3.0 + */ + bool verticalGrid() const { return mVerticalGrid; } + /** Sets color used for background of table. * @param color table background color * @see backgroundColor @@ -477,6 +517,12 @@ class CORE_EXPORT QgsComposerTableV2: public QgsComposerMultiFrame /** Color for grid lines*/ QColor mGridColor; + /** True if grid should be shown*/ + bool mHorizontalGrid; + + /** True if grid should be shown*/ + bool mVerticalGrid; + /** Color for table background*/ QColor mBackgroundColor; diff --git a/src/ui/composer/qgscomposerattributetablewidgetbase.ui b/src/ui/composer/qgscomposerattributetablewidgetbase.ui index 21a194c95967..7c02ff77da46 100644 --- a/src/ui/composer/qgscomposerattributetablewidgetbase.ui +++ b/src/ui/composer/qgscomposerattributetablewidgetbase.ui @@ -504,6 +504,20 @@ + + + + Draw horizontal lines + + + + + + + Draw vertical lines + + + diff --git a/tests/src/core/testqgscomposertablev2.cpp b/tests/src/core/testqgscomposertablev2.cpp index cb00f5796349..8202906ae9fd 100644 --- a/tests/src/core/testqgscomposertablev2.cpp +++ b/tests/src/core/testqgscomposertablev2.cpp @@ -70,6 +70,8 @@ class TestQgsComposerTableV2 : public QObject void contentsContainsRow(); //test the contentsContainsRow function void removeDuplicates(); //test removing duplicate rows void multiLineText(); //test rendering a table with multiline text + void horizontalGrid(); //test rendering a table with horizontal-only grid + void verticalGrid(); //test rendering a table with vertical-only grid void align(); //test alignment of table cells void wrapChar(); //test setting wrap character void autoWrap(); //test auto word wrap @@ -675,6 +677,84 @@ void TestQgsComposerTableV2::multiLineText() delete multiLineLayer; } +void TestQgsComposerTableV2::horizontalGrid() +{ + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QVERIFY( multiLineLayer->isValid() ); + QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); + f1.setAttribute( "col1", "multiline\nstring" ); + f1.setAttribute( "col2", "singleline string" ); + f1.setAttribute( "col3", "singleline" ); + QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); + f2.setAttribute( "col1", "singleline string" ); + f2.setAttribute( "col2", "multiline\nstring" ); + f2.setAttribute( "col3", "singleline" ); + QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); + f3.setAttribute( "col1", "singleline" ); + f3.setAttribute( "col2", "singleline" ); + f3.setAttribute( "col3", "multiline\nstring" ); + QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); + f4.setAttribute( "col1", "long triple\nline\nstring" ); + f4.setAttribute( "col2", "double\nlinestring" ); + f4.setAttribute( "col3", "singleline" ); + multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); + + mFrame1->setFrameEnabled( false ); + mFrame2->setFrameEnabled( false ); + mFrame2->setSceneRect( QRectF( 5, 40, 100, 90 ) ); + + mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); + mComposerAttributeTable->setShowGrid( true ); + mComposerAttributeTable->setHorizontalGrid( true ); + mComposerAttributeTable->setVerticalGrid( false ); + mComposerAttributeTable->setVectorLayer( multiLineLayer ); + QgsCompositionChecker checker( "composerattributetable_horizontalgrid", mComposition ); + checker.setControlPathPrefix( "composer_table" ); + bool result = checker.testComposition( mReport ); + QVERIFY( result ); + + delete multiLineLayer; +} + +void TestQgsComposerTableV2::verticalGrid() +{ + QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); + QVERIFY( multiLineLayer->isValid() ); + QgsFeature f1( multiLineLayer->dataProvider()->fields(), 1 ); + f1.setAttribute( "col1", "multiline\nstring" ); + f1.setAttribute( "col2", "singleline string" ); + f1.setAttribute( "col3", "singleline" ); + QgsFeature f2( multiLineLayer->dataProvider()->fields(), 2 ); + f2.setAttribute( "col1", "singleline string" ); + f2.setAttribute( "col2", "multiline\nstring" ); + f2.setAttribute( "col3", "singleline" ); + QgsFeature f3( multiLineLayer->dataProvider()->fields(), 3 ); + f3.setAttribute( "col1", "singleline" ); + f3.setAttribute( "col2", "singleline" ); + f3.setAttribute( "col3", "multiline\nstring" ); + QgsFeature f4( multiLineLayer->dataProvider()->fields(), 4 ); + f4.setAttribute( "col1", "long triple\nline\nstring" ); + f4.setAttribute( "col2", "double\nlinestring" ); + f4.setAttribute( "col3", "singleline" ); + multiLineLayer->dataProvider()->addFeatures( QgsFeatureList() << f1 << f2 << f3 << f4 ); + + mFrame1->setFrameEnabled( false ); + mFrame2->setFrameEnabled( false ); + mFrame2->setSceneRect( QRectF( 5, 40, 100, 90 ) ); + + mComposerAttributeTable->setMaximumNumberOfFeatures( 20 ); + mComposerAttributeTable->setShowGrid( true ); + mComposerAttributeTable->setHorizontalGrid( false ); + mComposerAttributeTable->setVerticalGrid( true ); + mComposerAttributeTable->setVectorLayer( multiLineLayer ); + QgsCompositionChecker checker( "composerattributetable_verticalgrid", mComposition ); + checker.setControlPathPrefix( "composer_table" ); + bool result = checker.testComposition( mReport ); + QVERIFY( result ); + + delete multiLineLayer; +} + void TestQgsComposerTableV2::align() { QgsVectorLayer* multiLineLayer = new QgsVectorLayer( "Point?field=col1:string&field=col2:string&field=col3:string", "multiline", "memory" ); diff --git a/tests/testdata/control_images/composer_table/expected_composerattributetable_horizontalgrid/expected_composerattributetable_horizontalgrid.png b/tests/testdata/control_images/composer_table/expected_composerattributetable_horizontalgrid/expected_composerattributetable_horizontalgrid.png new file mode 100644 index 0000000000000000000000000000000000000000..70db426544cefc6b5676349fcab8f5ceefaf1e6e GIT binary patch literal 23133 zcmc$`by!s0+6PRihyg0yN(|D{AY~yTB`6(ILk*2|s3_gtBP}i64MTT#4&6xCw+7F7 z&pGdVuJ6z9o9lWmefI3xd+oK?y6^iJx88CxV)yTm-a$h{yDuUBMjj3Ah7KAUCh2Vq zaO9Pz-5U4<+d^E$8VwDn5%nK>i}^1-G_=QP5^r99u#elAa&Y!HxV+j`(j$2Hi^cGD z@aV{>Jo~TIqW2#d<-cbt7N-_B$!qv!zL#cKP3BBf5Ot$4Rd|=ByE&S1;me?7LhJJo zTjGKD;`wE(kc^CD0en%glJO?M;}`2Nnr zzow?X+elvWPO13>?~VMRus8A{)$T!867Oi(gNwMFTCPWjSll0@RXdr*Y-lKR7*O{2 znQwgTt2nQ2!?uj!+7z=SfhFE`*a*xVF`<8I5>wm`OIUL zk+~ZDj$u5eXtta4XWRUreZJpV8>V~w<>%w})rjAyLFJ6`OSd<5-2Ev}_vq2eq>52U z{7o$D#oN`6eO3JQvK%ntEX90ncMiJBlSRDl_+$s`wV{P$%LJzYx69Da>l+jisCmdx zsOnECHZd9rFd13tt)EW3Efp_$v{hC~mbG2eu`zbOt|fSqqS46MsF>3*HdgiA)#xF3NW5L8JNZcxydT9GV8cAXn|^j2&5uCC+)(5yzE&qrH*h4kCiVk5a# zXRMf51xBIy>nrci&%L}p_0xLb8XzUlFC@fU%X|LZXq%{f(8$^hrcpy+IERKWs&ppp zHP$|XN{Qb~_g~7vyfaNbfkp$jvD?ZUzu&k#XXQgh7a*$XrPB%EZy_OAzAq5ft&uGCQX|2%KzyP?N#~1ZG&}1$3w0Xsd!^%DYy)> zePdes#~rk(%7x_?diXQlx3&}z2#3q_9M!%&Ep3E`qjdBuRZ_74xnz&#!%Dm8=i%va zXcwujZ#q3EbZ6Y;_(WxuobNMVD5ca|9s?EN%3TEx_V)y%;SG zbl86ueTUuXp!HCNZ%zS>A}NnJeAVXO2hE)&~;^CR7+19$PY#PnB$HvA(Ja*C1fjb8QmjA^aUh z_5zkGPiHpyyFlmy(!ZV8>K^+pda}01x+mX(lZ5sssBoju!L9WQ>6%yPi^;ioj&a9%0Li|&y~Du^p=s!A<&beyn%+na;6l6%){|M$lj{0A>8ZNY4>k654a*kwF*66#PWJXu zN|iQk<%{CzMvzl(mdPy zyW)(FWL4!gYobe-wai>8d+NVNYI2m&LmrV!m0w*%inavA37Kq+7vG&-c`pSC3H4W# z#r?C^986<-6;Ls6yMiH}WBw6WGx(w<_78P-I$IVR( zk@BWFpEy&;R!16D)G`i#Jhr$v5ESGzP6T3eeqj^%(9zA?% z#epj#RcuUHX*T(oBV=u8cdtEn;MhJX$-?5NX0^IdtsZX2C%V+`-?T1{n2YQOT9&Ivh;$n@trMK6p^qn>bA7WdB=FV$Sm^YVxU5 zl`N$~IV#+!%*_>Zi$+H)xLH({&1Z7Ra7EN_SYDSh;u+yR*!7$1$$}K1)-yRNDTJSIg+i&Ty`K$3f_Hjre29y>Ekkb6-Y^l-8tVZ6$|ZaEHYx&j4PiI zu)BQ+<9LG;0~7n6-U#cLvBGGP8AsZeFJYsfnDdnDNAuMy-dH>n78bnZ6S*|(<74!( zTrljzFgN$WK@Mg(!_lsvn?VR>&AWQ(($L6n?O{A*f9b%g{+QWsQ4a(KG2Cf;_q>`U zEs^f{#*VwQb?7qik`?Uwjf$NqJ1&@4t;h?1QZxZO`TV2<@rK6Tea?tL zs^#^(v3&Q-i`8L&^IA|KB#RkMkLbr^Ywa>r40T?;^Vkuk?}w3 zEn%q(dV(+xXB^BD(@VJ@7{O#_c8}ap(`+n6%k5^F8~i@m%1B@tUsAGnz|uH(g$?^H z5Z+OXOatb~YX0iJF#ieLjx)A82iintI zQHFsw2CqrC?|viQ9_Xlhhmjsigsu%fc|Lv~IaX|WH_JeBm#X=9>z?>wlvAC+clpQwz`P_W=rH1!o;BQx}uc4 zf0iND^Xgn6OIk9QIqVwqb(w2Jd>A$384;B{)h+6V>Co4Yoy52c{ZWll!R^}XC z#3djm|68flFDoPC{G`Wb^_BarBGV49hj9W18>AfHsa&5$)E<9})THJJNqoI~2-Z9g z?DvZ8x+0}poX7pukwCZ`6mjqJ+(384X?t!?yU)J)j^m%%KC#u&;2(D-q`6Ddd#LRH z7`kGV*?324r8!uWa#KI`(sFIvyLY}UB6vjJ6}zzTI*`(N4;z99casT)l$AZRf98(0 zKW-8wMgF{LwjN}h#WpT;nNN=)cy8x3RL-Al!l!2&Zl=kk8Yw)tnQg>nsi9o%;ncf* zpRB)}lS!$-n1HSN&smT&XYO=a{bJkkDd~31v#*PKQV^MVot;mtnoWB1TN<};q3epE z<{K|fcd*uUpxejQYkTDEvU>c=V5mj?Qpvm}{>xQEL&O=&(FCELSpIhrLj}(c>`S z=Y!7JmN@huBV5o?}(P6`)!)jRl~pRiuaMJvnY8e+p81Mg zcY^->8$qFR=V-SJ-!S~RcyDiTtii(=q#HDPiOCKF7XG!xgp+ zPZz_*A^#~$B?C`0*JASQxX9=rM*D3_X18UrO{t5JOT_Rc8c4=k?jbWUntG0b=`fG| z>a~QFUOh&MxxtLEx`y@fF)GBJL6$XQ7}_DeF~E5F~jl zIH_Fi6iLb*#n-32ITf2GEg`|K$ZK|kn5R>@%U*203HwXxyDqVl`Mc!gd~TEj+glK% z@Rzz5q+E~L`;?_+(kyk~1{Ccj_G9f`oMweQz+M_+yA9zR6|6+y$;uU`9movl zwe$ri2>Gj4_w^m0>Tu*6$aW`=r`-4*NrY@?w}yD)AZ-sDf@!P`ACSW|w?_NC?u?d) z=4xbU%_!$+#?!+)6PXMQ)&{lP9`TsYZ%vVtikvYA1S~DYNU2xcu-K!uwEX@(N)4*s z{p-t6=*2~sHLS?gH#Bs243~1To#6C{S4*Flmy}!nJrra|h94XJD>8R_&QB&QnpgT# z()vqSbP>;Nvqe*0U*HdX&m~f&YyI5%%JLkP|H;! zoKf%qzYwZI@+sndKw-22bHMpy#@Rjn@uGag=pm!Fl~{8CO>0~%EfdvvU%g(P5>RTn zxzHQQW+1Gn*uwJZV9^gfjL9=A>){I89$cl}ThedjW8F*p=4@lbjQzvVrXKKg=qm~z-&lPzh-CzAm zh@0L_5Q?tUC`@}X<%5a>uYV*!G-^7BviNzK=0lS8-wb8mBW=q3czl9%=wG%%?i}b( zJ>QRb?deBGTD!d6GgS#258D>cX%)l%goQO;q}`4m!LqRSQ3ihNms~vp=`CQZcVuQZ z`Al(pT7Q3OvSy^iw=dbBKErmabHY-ssBUU%-X~kbq+0*UN7=1GYfoS)5PYf4)@<2Ih1 z{gkSIb!oFw7sc*;M6tU|OKY+6Kp}0>xL1S6N(;k&f(OK@hMV#V-u}q-JO-_4Vw;g7 z25;~4O>=Ug_6&uaKJ-&f-hBLhc~m0jb!pPzb+fV#%XVNY<#CvjULCp7(phd(GARZ{ zL@cAAUtX<@GO_j2Zxf=sM0+E(7{j<4#6zJbgP$61fEzX9mfQL}9eH`pCI{}tZKH|@ ze79!(-l-DP8@I*#lIMc`)>S1ITWqrXN3Y?#GyHphBH2c3Swd86>bsOQ`8>*Sriod!QnUA!JcUs9&&Cm^^9$t` z=)AmDReoYBu=#U``Gt&+zT?G(mF9Q^qEh#8g_;1h_n5A=npI&6}Wzw^J2@e|oo%*xcDmK-L4F_)%zD z${`wor@(K=zV;j@*OC$xoO_}|>i-QbxY%U$CcKPu-ph?{hjo$QnF1(9<5HRL5G-Xl}QZ@D;7 zIz32sc2L*w_HS$avSe*YwSDiLsyyt&zE)#^bfgZ4LVyt zb}2CYlnnRsU1-8KoBU~|KVCAV@YF-2@)${!t6tw1teEplF~=)lA|02V{e17Px3|4x ze?h7h3KIsu(vIa~p#2_7AI%#W&6%MT`13KeyK~DSDu&zIzHA1arA*Z(Ic2$JMX$f!tLHK5?@!Iv>>A37l2Wf~jbK^okCu)t za1$Zpwb~$l|DK0WamyqD6?DD47Tv*Aj4FfuI9_aNmGlx*T^&s4D7Psog#cg;CQ8nC z1OM~vV)q4hpi6aYRNEICZFNmUPNFsGzdmE{t=4Vs-=e zA&>=j^2_0xS)dMa;&~V9<7fQ$_Tq_*4n`sW{y&d0|8e3E2Dp*DRYBwBg(-~82VY9G zmw-VrGrWsweqmv4)oA-M>S6Cd;70v!S0-!2n^C5(gTM75gLJgV3Y>Jg`r^UEg;@X| zeR7Jzb`YM@K#T7!63XPC)bCRbd`0dybv zovA%$PiJaD)pwx^Mk{2`%T zPDfj*@^k@IrTu&ZtSF2e{0PVni(Lsq_D*;YwWsIjUY44D$Tm#1;^Gmvp6pA-yctM4J}t1KtE+dvaih14y+^PyuQp~PkfOtf zU}-3Y76WsvgvGiP3zx%*r!Ga}#;r%h;xOiPSv+FHz6necJE0ZpF^=apKSl3qx`ZFw z`yMhW?Hw<08NNuDVOCA?j6pq2lW-WgrBdz#%I=>pn-F`a>-G*0A2lS2-lLRCm#I2s z^u*m?3|$h`YrN%4@3l2UFBs=b#A$cd`?|;wy*HQQ^78m>Vg8lWy}7x`DkC~Szsmlz zI6+Xw(bIl6fa^EkNpPE<Ys z*zbx`x`efb^4oZon4&v70~qa&wK~XvOThzcTF)`I*KpW7AVT>1{ zd-*Z11tqu)w+4R+pkR+Kv%&s!;Yd!gIu^QOxPV;uZEH#p5~WDI-ZkK*K)H>hBBv%f z@-XbSMmbaVkX`Kmtltjv^F;}wQ75)ufz^X1CMK`Yl~rm^^cihyD~wInSy1Lw@_PGK z6P*66OrZ@4f%VF&l6rfW$DeK-n##-jA;a(m&imlWf-Z5?a_IrhXjLv}1u&IFjJj$k z9-O)vc%|J~Q5#~4(2eIDvUphgcRfTcLEo{_g1Nc+ z5IV%(HTQHMqqW+4x$HBOCy&D^pXlsv%h>O)fRY_%DKSHK@fO0yem(5&26PA(uGK~q zKLyKAz`pc;W!F945}03*5TEURk|xD);l2esmTtW;XIThLDsv$~1s@;xSF)k1rQOS6 zh9w{=US5jYm7N{!9`g9$>o+#Kn@#;v&KK8d|IsUVegTpd<40olZzubOFqPz6?;?I1 z;b~L=Hf1Dt3<9Q%$1KIk&f{KvqkDV!?mob8aq*@DD2~AV+tjtP$KXLO1yQJ(CcYmy z$`=9KoR%KRB^NT5>WdJfr*CMmU+{0hUANnsX&H+S6j>@B@i}gt`Xq*43DEqgGGL_* ztR7MI{J2|IK8O5KSvl44`=%D3dRWW)5Ks?PDtVS80E0mYtsV?#VRmQ#F<1;_4g!WFHHc!)KRLmpT(JqfPrt;lE#W5N6(%sAJw;{Y^1{HzDy`iy2&9>WVZf!Kz>e<(1G3@)zL*cs%=#L)l9DxMa7HVk= z-BMqev&sUR)UzP^gvVTAO>YR9Kb_egZZ-~aTX!g=0~TBfotA!}lGmX7nXBNzdZ8&9 zI=b^gc<_lHhdHJ7(zDNu(y@=oI;N}NyxrSrv{`Mio9X+V$llN9a=C6g0eCXu1a@8f zHHOR&PaqyU7SoP*XD?l782=N;2XNaw6}e~{%oxn;;hp*I$PMmhuIZW^Hrmmf2#A*^ zPy|?=a9o`dF);86EN{j>Abe~1v_}L~Oyqno;KJbj%+x62*zHosKYw2cVXN_~6wq@1 z3a9eK>HGD5DS`wOt;BSpn*xX#oy3eEKJDrNcIeze_twee)fOr&OY$fPi$+Tc+E-uj z0QJbS!(FK-;U4iPX16P$y5rrYYIO7>Qxm|c2zPg@R~cq&*2*;d4Ca_*r_Dt0JK~3W zFX|bOK%TZv_KX$s3GAONBQld|?h=u9fNI)PEEnT=5ic&D-*vL;=wvxVspoWgZ9M#a zayCr1R&-~#g^(?8v`bTbqyX0g*v&UWIXZJ`;<73neC> z6VE_mrHa1-+gY_U6*E2kf`~7_-9NnmE3JD-#TeveY*5gPp-ev#UDxeDt7sh&Bv~YG zCSSjTOr(><{{`Vs!r!mlb)4Kv{H5*t|Dpy$F1EMa^7KzGlu#ijrR+BlAOBIy@w*8x zBkJpykO353$u72ADJDv5BfN@PO3Q8ZIY$;dkCk$JYeo9{5FK6qZ~gs5j`t|)Dn1v% zB!)7V%&46FTE&x+vTfvRg#m(S4{vH(T>BX)#2X4>M!_;F7+cX&p-8J7zJ8Q$ZA>O$~iTU~4*zBd9WpRBMXRy&1wXRLgBr}UZ zf$pa(6?x$1M(H}LY&Jm%CWlwP?(asy)`@*-_vA^OU|W?#XPiW}xDk3}jsA5e5=D^}a;A*AB zLNS9M#!CR%f(S@eA67942n{jtx#L&Is+9(n-k<5xb5Tvdt1hW(2b(&95W#?#qt8Pv?*$nTn>rKcxk zehl$|yXv$)h+x(p{VixGpG7#5rv_^)I(>24c;R%YM_F40m7acGx=~_h&eWKsT3XUS zIshd4<83!=+;k%aO@|*p?iQ{K#@=IeDmK=y(GDLn%6}40UR*8{&u8_$RXlpDvvtQlHKa1#7Ey z#Q;KnJ!SEkBfs{wM5s7oE;)fZwb6Z*l zZ|T@hH7m{qYaU6Rg9-V@YxiF_3oVn>#A^jmC5%q%|Ea)> zjKh~@05WRxcD*>B!vdsIM!JP%eSN)T2jJ?SeHHaR-g%v?u`n$}O?|wQEO<2)-IgN3 zC&2j$P2{Sx+DW~(JA$P%&Zv6#&nh4tCM!f$Nx^bk3p=6VHEM|A25>fC_vXcw6QCF= zo&16x)Es}K5U@Y^7(juU4UZ-d?_DdUn;OajS>x)0NYn()U-iQ|d;*|Yy~_rGHYOHn z5A=Nc`~=`^Kzgrw$CCMz6*`x*8(7vjIOMwsAlv)OInB%lv)g9tRU&?z^ti1|#WH>b z`^m`;1H=BzRCgqVj+U-39oKZCK>PLASCXaB`%{(sYgzY*>ozAk6YlFdKw(Mx?@G)| zIUI@>Wy`IyRbI#PlvOS)f#|!xq<;dF=YjS>+wp}jql8_QYZH1zJeg~-WktG1ve7>#s-^2~v zFs=ds=;2FM($DLAy{}97pIRI+)?U0F$`m}euq{@^!vnx_@Wa|rhgFSF!!v7$+a>4j zZuI5a<}Crr?3C2qHhLgUDCN%1z4Rpn&WvIcPMsSwE@H7fT(H|ar|UMGAR7!Z@I7;2Cz3|9lI#{1b>+OwT`Lo*CBQlV$8)4cFrx#98E∈0JnSW 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 literal 0 HcmV?d00001 diff --git a/tests/testdata/control_images/composer_table/expected_composerattributetable_verticalgrid/expected_composerattributetable_verticalgrid.png b/tests/testdata/control_images/composer_table/expected_composerattributetable_verticalgrid/expected_composerattributetable_verticalgrid.png new file mode 100644 index 0000000000000000000000000000000000000000..eb6f35b430a7652f3ec528b86d998d6b2ed86b2b GIT binary patch literal 21344 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 Y)9}gj;n?|FupJO_VHu% Date: Fri, 14 Oct 2016 16:28:49 +1000 Subject: [PATCH 264/897] Fix color widget opens in wrong panel (fix #15705) --- src/gui/qgspanelwidget.cpp | 7 +++++++ tests/src/python/test_qgspanelwidget.py | 8 +++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/gui/qgspanelwidget.cpp b/src/gui/qgspanelwidget.cpp index 76fb67a16de1..9bb1412097f5 100644 --- a/src/gui/qgspanelwidget.cpp +++ b/src/gui/qgspanelwidget.cpp @@ -55,6 +55,13 @@ QgsPanelWidget*QgsPanelWidget::findParentPanel( QWidget* widget ) if ( QgsPanelWidget* panel = qobject_cast< QgsPanelWidget* >( p ) ) return panel; + if ( p->window() == p ) + { + // break on encountering a window - eg a dialog opened from a panel should not inline + // widgets inside the parent panel + return false; + } + p = p->parentWidget(); } return nullptr; diff --git a/tests/src/python/test_qgspanelwidget.py b/tests/src/python/test_qgspanelwidget.py index 6cf7e94a5c16..6870052414c4 100644 --- a/tests/src/python/test_qgspanelwidget.py +++ b/tests/src/python/test_qgspanelwidget.py @@ -14,7 +14,7 @@ import qgis # NOQA -from qgis.PyQt.QtWidgets import QWidget +from qgis.PyQt.QtWidgets import QWidget, QDialog from qgis.gui import QgsPanelWidget from qgis.testing import start_app, unittest @@ -49,6 +49,12 @@ def testFindParentPanel(self): w5 = QWidget(w4) self.assertEqual(QgsPanelWidget.findParentPanel(w5), w3) + # chain should be broken when a new window is encountered + n = QgsPanelWidget() + n2 = QDialog(n) + n3 = QWidget(n2) + self.assertFalse(QgsPanelWidget.findParentPanel(n3)) + if __name__ == '__main__': unittest.main() From a0bfc10c568e3e4f54a7f43ca285e2e7b11a194a Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 14 Oct 2016 17:05:00 +1000 Subject: [PATCH 265/897] Fix bad fills when using marker line with render effects (fix #15696) --- src/core/symbology-ng/qgslinesymbollayer.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/symbology-ng/qgslinesymbollayer.cpp b/src/core/symbology-ng/qgslinesymbollayer.cpp index 6ebcc2492daf..237d4508d7a3 100644 --- a/src/core/symbology-ng/qgslinesymbollayer.cpp +++ b/src/core/symbology-ng/qgslinesymbollayer.cpp @@ -870,6 +870,9 @@ void QgsMarkerLineSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbo } } + + context.renderContext().painter()->save(); + if ( qgsDoubleNear( offset, 0.0 ) ) { if ( placement == Interval ) @@ -896,6 +899,8 @@ void QgsMarkerLineSymbolLayer::renderPolyline( const QPolygonF& points, QgsSymbo renderPolylineVertex( points2, context, placement ); } } + + context.renderContext().painter()->restore(); } void QgsMarkerLineSymbolLayer::renderPolygonOutline( const QPolygonF& points, QList* rings, QgsSymbolRenderContext& context ) From c0e3295c4c4073a217f1d0347bb273135367c085 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Fri, 14 Oct 2016 17:05:42 +1000 Subject: [PATCH 266/897] Fix build --- src/gui/qgspanelwidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/qgspanelwidget.cpp b/src/gui/qgspanelwidget.cpp index 9bb1412097f5..1598ae0922b2 100644 --- a/src/gui/qgspanelwidget.cpp +++ b/src/gui/qgspanelwidget.cpp @@ -59,7 +59,7 @@ QgsPanelWidget*QgsPanelWidget::findParentPanel( QWidget* widget ) { // break on encountering a window - eg a dialog opened from a panel should not inline // widgets inside the parent panel - return false; + return nullptr; } p = p->parentWidget(); From 8207167b6a1e61c0cf73bc3ae0a6e771438eab98 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Fri, 14 Oct 2016 09:46:24 +0200 Subject: [PATCH 267/897] debian packaging: add support for yakkety --- debian/control.in | 8 ++++---- debian/rules | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/debian/control.in b/debian/control.in index 85ac9a81b3a6..0a85ef0728b4 100644 --- a/debian/control.in +++ b/debian/control.in @@ -14,7 +14,7 @@ Build-Depends: libfcgi-dev, libgdal-dev (>= 1.11), #trusty# libgsl0-dev, -#sid stretch xenial# libgsl-dev, +#sid stretch xenial yakkety# libgsl-dev, libgeos-dev (>= 3.0.0), libpq-dev, libproj-dev, @@ -42,9 +42,9 @@ Build-Depends: #oracle# oracle-instantclient12.1-devel, locales, ca-certificates, ninja-build Build-Conflicts: libqgis-dev, qgis-dev -#sid stretch xenial#Standards-Version: 3.9.7 +#sid stretch xenial yakkety#Standards-Version: 3.9.7 #trusty#Standards-Version: 3.8.4 -#trusty xenial#XS-Python-Version: current +#trusty xenial yakkety#XS-Python-Version: current Vcs-Browser: https://github.com/qgis/QGIS/ Vcs-Git: https://github.com/qgis/QGIS.git Homepage: http://qgis.org/ @@ -203,7 +203,7 @@ Depends: libgdal-dev (>= 1.11), libgeos-dev (>= 3.0.0), #trusty# libgsl0-dev, -#sid stretch xenial# libgsl-dev, +#sid stretch xenial yakkety# libgsl-dev, libpq-dev, libproj-dev, libqgis-app{QGIS_ABI} (= ${binary:Version}), diff --git a/debian/rules b/debian/rules index 3af8146ba98f..b1aca1250452 100755 --- a/debian/rules +++ b/debian/rules @@ -36,7 +36,7 @@ endif QT_PLUGINS_DIR = usr/lib/$(DEB_BUILD_MULTIARCH)/qt5/plugins -ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"trusty stretch xenial")) +ifneq ($(DISTRIBUTION),$(findstring $(DISTRIBUTION),"trusty stretch xenial yakkety")) DISTRIBUTION := sid endif From ada9348e2b8d3cf248755dd681a015b0e286200b Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 13 Oct 2016 14:43:23 +0200 Subject: [PATCH 268/897] Fix PostgreSQL import of layers with multi-column or quoted-column keys Fixes #15226 (drag & drop of postgresql views) Includes test --- .../postgres/qgspostgresprovider.cpp | 211 +++++++++++------- src/providers/postgres/qgspostgresprovider.h | 14 +- tests/src/python/test_provider_postgres.py | 31 +++ 3 files changed, 171 insertions(+), 85 deletions(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index 86b14d45cd17..e33957cf7367 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -1360,56 +1360,73 @@ bool QgsPostgresProvider::determinePrimaryKey() return mValid; } -void QgsPostgresProvider::determinePrimaryKeyFromUriKeyColumn() +/* static */ +QStringList QgsPostgresProvider::parseUriKey( const QString& key ) { - QString primaryKey = mUri.keyColumn(); - mPrimaryKeyType = pktUnknown; + if ( key.isEmpty() ) return QStringList(); - if ( !primaryKey.isEmpty() ) - { - QStringList cols; + QStringList cols; - // remove quotes from key list - if ( primaryKey.startsWith( '"' ) && primaryKey.endsWith( '"' ) ) + // remove quotes from key list + if ( key.startsWith( '"' ) && key.endsWith( '"' ) ) + { + int i = 1; + QString col; + while ( i < key.size() ) { - int i = 1; - QString col; - while ( i < primaryKey.size() ) + if ( key[i] == '"' ) { - if ( primaryKey[i] == '"' ) + if ( i + 1 < key.size() && key[i+1] == '"' ) { - if ( i + 1 < primaryKey.size() && primaryKey[i+1] == '"' ) - { - i++; - } - else - { - cols << col; - col = ""; + i++; + } + else + { + cols << col; + col = ""; - if ( ++i == primaryKey.size() ) - break; + if ( ++i == key.size() ) + break; - Q_ASSERT( primaryKey[i] == ',' ); - i++; - Q_ASSERT( primaryKey[i] == '"' ); - i++; - col = ""; - continue; - } + Q_ASSERT( key[i] == ',' ); + i++; + Q_ASSERT( key[i] == '"' ); + i++; + col = ""; + continue; } - - col += primaryKey[i++]; } + + col += key[i++]; } - else if ( primaryKey.contains( ',' ) ) - { - cols = primaryKey.split( ',' ); - } - else + } + else if ( key.contains( ',' ) ) + { + cols = key.split( ',' ); + } + else + { + cols << key; + } + + return cols; +} + +void QgsPostgresProvider::determinePrimaryKeyFromUriKeyColumn() +{ + QString primaryKey = mUri.keyColumn(); + mPrimaryKeyType = pktUnknown; + + if ( !primaryKey.isEmpty() ) + { + QStringList cols = parseUriKey( primaryKey ); + + primaryKey = ""; + QString del = ""; + Q_FOREACH ( const QString& col, cols ) { - cols << primaryKey; - primaryKey = quotedIdentifier( primaryKey ); + primaryKey += del + quotedIdentifier( col ); + del = ","; } Q_FOREACH ( const QString& col, cols ) @@ -3463,6 +3480,9 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q QString primaryKey = dsUri.keyColumn(); QString primaryKeyType; + QStringList pkList; + QStringList pkType; + QString schemaTableName = ""; if ( !schemaName.isEmpty() ) { @@ -3503,45 +3523,39 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q } else { - // search for the passed field - for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) + pkList = parseUriKey( primaryKey ); + Q_FOREACH ( const QString& col, pkList ) { - if ( fields.at( fldIdx ).name() == primaryKey ) + // search for the passed field + QString type; + for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx ) { - // found, get the field type - QgsField fld = fields.at( fldIdx ); - if ( convertField( fld, options ) ) + if ( fields[fldIdx].name() == col ) { - primaryKeyType = fld.typeName(); + // found, get the field type + QgsField fld = fields[fldIdx]; + if ( convertField( fld, options ) ) + { + type = fld.typeName(); + break; + } } } - } - } - - // if the pk field doesn't exist yet, create a serial pk field - // as it's autoincremental - if ( primaryKeyType.isEmpty() ) - { - primaryKeyType = "serial"; -#if 0 - // TODO: check the feature count to choose if create a serial8 pk field - if ( layer->featureCount() > 0xffffffff ) - { - primaryKeyType = "serial8"; - } -#endif - } - else - { - // if the pk field's type is one of the postgres integer types, - // use the equivalent autoincremental type (serialN) - if ( primaryKeyType == "int2" || primaryKeyType == "int4" ) - { - primaryKeyType = "serial"; - } - else if ( primaryKeyType == "int8" ) - { - primaryKeyType = "serial8"; + if ( type.isEmpty() ) type = "serial"; + else + { + // if the pk field's type is one of the postgres integer types, + // use the equivalent autoincremental type (serialN) + if ( primaryKeyType == "int2" || primaryKeyType == "int4" ) + { + primaryKeyType = "serial"; + } + else if ( primaryKeyType == "int8" ) + { + primaryKeyType = "serial8"; + } + } + pkType << type; } } @@ -3577,17 +3591,32 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q throw PGException( result ); } - if ( options && options->value( "lowercaseFieldNames", false ).toBool() ) + sql = QString( "CREATE TABLE %1(" ) .arg( schemaTableName ); + QString pk; + for ( int i = 0; i < pkList.size(); ++i ) { - //convert primary key name to lowercase - //this must happen after determining the field type of the primary key - primaryKey = primaryKey.toLower(); - } + QString col = pkList[i]; + const QString& type = pkType[i]; - sql = QString( "CREATE TABLE %1(%2 %3 PRIMARY KEY)" ) - .arg( schemaTableName, - quotedIdentifier( primaryKey ), - primaryKeyType ); + if ( options && options->value( "lowercaseFieldNames", false ).toBool() ) + { + col = col.toLower(); + } + else + { + col = quotedIdentifier( col ); // no need to quote lowercase field + } + + if ( i ) + { + pk += ","; + sql += ","; + } + + pk += col; + sql += col + " " + type; + } + sql += QString( ", PRIMARY KEY (%1) )" ) .arg( pk ); result = conn->PQexec( sql ); if ( result.PQresultStatus() != PGRES_COMMAND_OK ) @@ -3678,9 +3707,25 @@ QgsVectorLayerImport::ImportError QgsPostgresProvider::createEmptyLayer( const Q fld.setName( fld.name().toLower() ); } - if ( fld.name() == primaryKey ) + int pkIdx = -1; + for ( int i = 0; i < pkList.size(); ++i ) + { + QString col = pkList[i]; + if ( options && options->value( "lowercaseFieldNames", false ).toBool() ) + { + //convert field name to lowercase (TODO: avoid doing this + //over and over) + col = col.toLower(); + } + if ( fld.name() == col ) + { + pkIdx = i; + break; + } + } + if ( pkIdx >= 0 ) { - oldToNewAttrIdxMap->insert( fldIdx, 0 ); + oldToNewAttrIdxMap->insert( fldIdx, pkIdx ); continue; } diff --git a/src/providers/postgres/qgspostgresprovider.h b/src/providers/postgres/qgspostgresprovider.h index 339972a3e495..c728973c90d4 100644 --- a/src/providers/postgres/qgspostgresprovider.h +++ b/src/providers/postgres/qgspostgresprovider.h @@ -114,6 +114,11 @@ class QgsPostgresProvider : public QgsVectorDataProvider */ static QString endianString(); + /** + * Returns a list of unquoted column names from an uri key + */ + static QStringList parseUriKey( const QString& key ); + /** * Changes the stored extent for this layer to the supplied extent. * For example, this is called when the extent worker thread has a result. @@ -126,11 +131,16 @@ class QgsPostgresProvider : public QgsVectorDataProvider */ virtual void updateExtents() override; - /** Determine the fields making up the primary key + /** + * Determine the fields making up the primary key */ bool determinePrimaryKey(); - /** Determine the fields making up the primary key from the uri attribute keyColumn + /** + * Determine the fields making up the primary key from the uri attribute keyColumn + * + * Fills mPrimaryKeyType and mPrimaryKeyAttrs + * from mUri */ void determinePrimaryKeyFromUriKeyColumn(); diff --git a/tests/src/python/test_provider_postgres.py b/tests/src/python/test_provider_postgres.py index b89f67ff5880..7d3c36693bc6 100644 --- a/tests/src/python/test_provider_postgres.py +++ b/tests/src/python/test_provider_postgres.py @@ -461,6 +461,37 @@ def testNumericPrecision(self): self.assertEqual(f['f2'], 123.456) self.assertEqual(f['f3'], '12345678.90123456789') + # See http://hub.qgis.org/issues/15226 + def testImportKey(self): + uri = 'point?field=f1:int' + uri += '&field=F2:double(6,4)' + uri += '&field=f3:string(20)' + lyr = QgsVectorLayer(uri, "x", "memory") + self.assertTrue(lyr.isValid()) + + def testKey(lyr, key, kfnames): + self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.import_test') + uri = '%s table="qgis_test"."import_test" (g) key=\'%s\'' % (self.dbconn, key) + err = QgsVectorLayerImport.importLayer(lyr, uri, "postgres", lyr.crs()) + self.assertEqual(err[0], QgsVectorLayerImport.NoError, + 'unexpected import error {0}'.format(err)) + olyr = QgsVectorLayer(uri, "y", "postgres") + self.assertTrue(olyr.isValid()) + flds = lyr.fields() + oflds = olyr.fields() + self.assertEquals(oflds.size(), flds.size()) + for i in range(0, oflds.size()): + self.assertEqual(oflds[i].name(), flds[i].name()) + pks = olyr.pkAttributeList() + self.assertEquals(len(pks), len(kfnames)) + for i in range(0, len(kfnames)): + self.assertEqual(oflds[pks[i]].name(), kfnames[i]) + + testKey(lyr, 'f1', ['f1']) + testKey(lyr, '"f1"', ['f1']) + testKey(lyr, '"f1","F2"', ['f1', 'F2']) + testKey(lyr, '"f1","F2","f3"', ['f1', 'F2', 'f3']) + class TestPyQgsPostgresProviderCompoundKey(unittest.TestCase, ProviderTestCase): From 799510f73acc855ede427c175e2c9db8d065814f Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Thu, 13 Oct 2016 17:02:00 +0200 Subject: [PATCH 269/897] Revert "postgres provider: quote compound key columns in uri" This reverts commit daa6510970e9afbc4d41d28e0c94b4f238eb372d. I've tested that reverting this does not re-introduce bug http://hub.qgis.org/issues/13710 --- src/providers/postgres/qgspostgresprovider.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/providers/postgres/qgspostgresprovider.cpp b/src/providers/postgres/qgspostgresprovider.cpp index e33957cf7367..c0eaaeaf7059 100644 --- a/src/providers/postgres/qgspostgresprovider.cpp +++ b/src/providers/postgres/qgspostgresprovider.cpp @@ -248,7 +248,7 @@ QgsPostgresProvider::QgsPostgresProvider( QString const & uri ) QString delim; Q_FOREACH ( int idx, mPrimaryKeyAttrs ) { - key += delim + quotedIdentifier( mAttributeFields.at( idx ).name() ); + key += delim + mAttributeFields.at( idx ).name(); delim = ','; } } From 60b4b4db187d6cc8fa6cfd06b57c3a171011f2ab Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Fri, 14 Oct 2016 16:33:44 +0200 Subject: [PATCH 270/897] Python scripts have 4-spaces indent --- .editorconfig | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.editorconfig b/.editorconfig index 88bac2de22f1..154ed650bd5c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,3 +11,7 @@ trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 2 + +# python scripts have 4 spaces indent +[*.py] +indent_size = 4 From 6c5364186dd8d45ac51e5bd1a72c6a542f032cb1 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Fri, 14 Oct 2016 15:11:02 +0200 Subject: [PATCH 271/897] Fix extraction of ogr LayerName from multi-layer dataset URIs Adds supports for "layerid" when present. Drop special handling for "table=" portions found in URI, making the code more generic. Includes testcase. Fixes #15698 - import geodatabase to postgis via processing --- python/plugins/processing/tests/ToolsTest.py | 56 ++++++++++++++++++++ python/plugins/processing/tools/vector.py | 36 ++++++++----- 2 files changed, 78 insertions(+), 14 deletions(-) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index 74ef76695721..d25f3018e487 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -31,11 +31,67 @@ from qgis.core import (QgsVectorLayer, QgsFeatureRequest) from processing.core.ProcessingConfig import ProcessingConfig +import os.path +import errno +import shutil + +dataFolder = os.path.join(os.path.dirname(__file__), '../../../../tests/testdata/') +tmpBaseFolder = os.path.join(os.sep, 'tmp', 'qgis_test', str(os.getpid())) + + +def mkDirP(path): + try: + os.makedirs(path) + except OSError as exc: + if exc.errno == errno.EEXIST and os.path.isdir(path): + pass + else: + raise + start_app() class VectorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + mkDirP(tmpBaseFolder) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(tmpBaseFolder) + pass + + # See http://hub.qgis.org/issues/15698 + def test_ogrLayerName(self): + tmpdir = os.path.join(tmpBaseFolder, 'ogrLayerName') + os.mkdir(tmpdir) + + def linkTestfile(f, t): + os.link(os.path.join(dataFolder, f), os.path.join(tmpdir, t)) + + linkTestfile('geom_data.csv', 'a.csv') + name = vector.ogrLayerName(tmpdir) + self.assertEqual(name, 'a') + + linkTestfile('wkt_data.csv', 'b.csv') + name = vector.ogrLayerName(tmpdir + '|layerid=0') + self.assertEqual(name, 'a') + name = vector.ogrLayerName(tmpdir + '|layerid=1') + self.assertEqual(name, 'b') + + name = vector.ogrLayerName(tmpdir + '|layerid=2') + self.assertEqual(name, 'invalid-layerid') + + name = vector.ogrLayerName(tmpdir + '|layername=f') + self.assertEqual(name, 'f') # layername takes precedence + + name = vector.ogrLayerName(tmpdir + '|layerid=0|layername=f2') + self.assertEqual(name, 'f2') # layername takes precedence + + name = vector.ogrLayerName(tmpdir + '|layername=f2|layerid=0') + self.assertEqual(name, 'f2') # layername takes precedence + def testFeatures(self): ProcessingConfig.initialize() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index a800571600ca..c6e67ac4dcfb 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -41,6 +41,8 @@ import psycopg2 +from osgeo import ogr + from qgis.PyQt.QtCore import QVariant, QSettings from qgis.core import (Qgis, QgsFields, QgsField, QgsGeometry, QgsRectangle, QgsWkbTypes, QgsSpatialIndex, QgsMapLayerRegistry, QgsMapLayer, QgsVectorLayer, @@ -531,20 +533,26 @@ def ogrConnectionString(uri): def ogrLayerName(uri): - if 'host' in uri: - regex = re.compile('(table=")(.+?)(\.)(.+?)"') - r = regex.search(uri) - return '"' + r.groups()[1] + '.' + r.groups()[3] + '"' - elif 'dbname' in uri: - regex = re.compile('(table=")(.+?)"') - r = regex.search(uri) - return r.groups()[1] - elif 'layername' in uri: - regex = re.compile('(layername=)(.*)') - r = regex.search(uri) - return r.groups()[1] - else: - return os.path.basename(os.path.splitext(uri)[0]) + fields = uri.split('|') + ogruri = fields[0] + fields = fields[1:] + layerid = 0 + for f in fields: + if f.startswith('layername='): + # Name encoded in uri, nothing more needed + return f.split('=')[1] + if f.startswith('layerid='): + layerid = int(f.split('=')[1]) + # Last layerid= takes precedence, to allow of layername to + # take precedence + ds = ogr.Open(ogruri) + if not ds: + return "invalid-uri" + ly = ds.GetLayer(layerid) + if not ly: + return "invalid-layerid" + name = ly.GetName() + return name class VectorWriter(object): From 80c6a27f17230e5e4aab5cc3dd07f91583502234 Mon Sep 17 00:00:00 2001 From: Giovanni Manghi Date: Sun, 16 Oct 2016 18:43:29 +0100 Subject: [PATCH 272/897] Add a GRASS7 tool to compute skeletons of areas, using v.voronoi --- .../algs/grass7/description/v.voronoi.skeleton.txt | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt diff --git a/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt b/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt new file mode 100644 index 000000000000..6bfc33534e60 --- /dev/null +++ b/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt @@ -0,0 +1,6 @@ +v.voronoi +v.voronoi.skeleton - Extract skeletons for input areas. +Vector (v.*) +ParameterVector|input|Input polygon layer|2|False +Hardcoded|-s +OutputVector|output|Area skeleton From 8f9fe00671d7a0af3164be4b28bab3bf28557ee2 Mon Sep 17 00:00:00 2001 From: Giovanni Manghi Date: Sun, 16 Oct 2016 19:09:06 +0100 Subject: [PATCH 273/897] add paramter to v.voronoi.skeleton --- .../processing/algs/grass7/description/v.voronoi.skeleton.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt b/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt index 6bfc33534e60..8fc4f028dba4 100644 --- a/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt +++ b/python/plugins/processing/algs/grass7/description/v.voronoi.skeleton.txt @@ -2,5 +2,6 @@ v.voronoi v.voronoi.skeleton - Extract skeletons for input areas. Vector (v.*) ParameterVector|input|Input polygon layer|2|False +ParameterNumber|thin|Maximum dangle length of skeletons (-1 will extract the center line)|None|None|-1 Hardcoded|-s OutputVector|output|Area skeleton From 55f207108d0b4ce7135020e53868e571bab75486 Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 09:55:39 +1000 Subject: [PATCH 274/897] Always clear pen/brush before drawing layer effects (fix #15696) --- src/core/effects/qgspainteffect.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/effects/qgspainteffect.cpp b/src/core/effects/qgspainteffect.cpp index 53b7d0554a16..258fa8ef5747 100644 --- a/src/core/effects/qgspainteffect.cpp +++ b/src/core/effects/qgspainteffect.cpp @@ -163,6 +163,11 @@ void QgsPaintEffect::end( QgsRenderContext &context ) context.setPainter( mPrevPainter ); mPrevPainter = nullptr; + // clear any existing pen/brush - sometimes these are not correctly restored when restoring a painter + // with a QPicture destination - see #15696 + context.painter()->setPen( Qt::NoPen ); + context.painter()->setBrush( Qt::NoBrush ); + //draw using effect render( *mTempPicture, context ); From 86368f39c3225b3013a4ede1830465f5c3ea4acd Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 10:30:55 +1000 Subject: [PATCH 275/897] [processing] Optimise feature requests within qgis algs - don't use setFilterFid() within loops to fetch features one at time (as it's extremely slow), instead use setFilterFids() outside the loop - don't fetch unused attributes/geometry when it can be avoided --- python/plugins/processing/algs/qgis/Difference.py | 6 +++--- python/plugins/processing/algs/qgis/Eliminate.py | 2 +- .../plugins/processing/algs/qgis/ExtractByLocation.py | 5 ++--- .../plugins/processing/algs/qgis/HubDistanceLines.py | 2 +- .../plugins/processing/algs/qgis/HubDistancePoints.py | 2 +- python/plugins/processing/algs/qgis/Intersection.py | 5 ++--- .../plugins/processing/algs/qgis/LinesIntersection.py | 5 ++--- .../processing/algs/qgis/NearestNeighbourAnalysis.py | 2 +- python/plugins/processing/algs/qgis/PointDistance.py | 5 ++--- .../processing/algs/qgis/PointsDisplacement.py | 9 ++++----- .../plugins/processing/algs/qgis/PointsInPolygon.py | 2 +- .../processing/algs/qgis/PointsInPolygonUnique.py | 2 +- .../processing/algs/qgis/PointsInPolygonWeighted.py | 2 +- .../processing/algs/qgis/RandomPointsAlongLines.py | 2 +- .../plugins/processing/algs/qgis/RandomPointsLayer.py | 6 ++---- .../plugins/processing/algs/qgis/SelectByAttribute.py | 2 +- .../processing/algs/qgis/SelectByAttributeSum.py | 4 ++-- .../plugins/processing/algs/qgis/SelectByLocation.py | 5 ++--- .../processing/algs/qgis/SplitLinesWithLines.py | 5 ++--- python/plugins/processing/algs/qgis/SumLines.py | 5 ++--- .../processing/algs/qgis/SymmetricalDifference.py | 8 ++++---- python/plugins/processing/algs/qgis/Union.py | 11 +++++------ 22 files changed, 43 insertions(+), 54 deletions(-) diff --git a/python/plugins/processing/algs/qgis/Difference.py b/python/plugins/processing/algs/qgis/Difference.py index 1eecde8bc736..71783562ab5d 100644 --- a/python/plugins/processing/algs/qgis/Difference.py +++ b/python/plugins/processing/algs/qgis/Difference.py @@ -85,9 +85,9 @@ def processAlgorithm(self, progress): diff_geom = QgsGeometry(geom) attrs = inFeatA.attributes() intersections = index.intersects(geom.boundingBox()) - for i in intersections: - request = QgsFeatureRequest().setFilterFid(i) - inFeatB = next(layerB.getFeatures(request)) + + request = QgsFeatureRequest().setFilterFids(intersections).setSubsetOfAttributes([]) + for inFeatB in layerB.getFeatures(request): tmpGeom = inFeatB.geometry() if diff_geom.intersects(tmpGeom): diff_geom = QgsGeometry(diff_geom.difference(tmpGeom)) diff --git a/python/plugins/processing/algs/qgis/Eliminate.py b/python/plugins/processing/algs/qgis/Eliminate.py index 1ac1338c880c..69927836c643 100644 --- a/python/plugins/processing/algs/qgis/Eliminate.py +++ b/python/plugins/processing/algs/qgis/Eliminate.py @@ -246,7 +246,7 @@ def processAlgorithm(self, progress): geom2Eliminate = feat.geometry() bbox = geom2Eliminate.boundingBox() fit = processLayer.getFeatures( - QgsFeatureRequest().setFilterRect(bbox)) + QgsFeatureRequest().setFilterRect(bbox).setSubsetOfAttributes([])) mergeWithFid = None mergeWithGeom = None max = 0 diff --git a/python/plugins/processing/algs/qgis/ExtractByLocation.py b/python/plugins/processing/algs/qgis/ExtractByLocation.py index 2620fd51661b..c3d96f8a6c42 100644 --- a/python/plugins/processing/algs/qgis/ExtractByLocation.py +++ b/python/plugins/processing/algs/qgis/ExtractByLocation.py @@ -84,9 +84,8 @@ def processAlgorithm(self, progress): geom = vector.snapToPrecision(f.geometry(), precision) bbox = vector.bufferedBoundingBox(geom.boundingBox(), 0.51 * precision) intersects = index.intersects(bbox) - for i in intersects: - request = QgsFeatureRequest().setFilterFid(i) - feat = next(layer.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(intersects).setSubsetOfAttributes([]) + for feat in layer.getFeatures(request): tmpGeom = vector.snapToPrecision(feat.geometry(), precision) res = False for predicate in predicates: diff --git a/python/plugins/processing/algs/qgis/HubDistanceLines.py b/python/plugins/processing/algs/qgis/HubDistanceLines.py index 646a17a4dba9..5e3265022623 100644 --- a/python/plugins/processing/algs/qgis/HubDistanceLines.py +++ b/python/plugins/processing/algs/qgis/HubDistanceLines.py @@ -109,7 +109,7 @@ def processAlgorithm(self, progress): src = f.geometry().boundingBox().center() neighbors = index.nearestNeighbor(src, 1) - ft = next(layerHubs.getFeatures(QgsFeatureRequest().setFilterFid(neighbors[0]))) + ft = next(layerHubs.getFeatures(QgsFeatureRequest().setFilterFid(neighbors[0]).setSubsetOfAttributes([fieldName], layerHubs.fields()))) closest = ft.geometry().boundingBox().center() hubDist = distance.measureLine(src, closest) diff --git a/python/plugins/processing/algs/qgis/HubDistancePoints.py b/python/plugins/processing/algs/qgis/HubDistancePoints.py index 7e4cc7521384..0abd01463f57 100644 --- a/python/plugins/processing/algs/qgis/HubDistancePoints.py +++ b/python/plugins/processing/algs/qgis/HubDistancePoints.py @@ -109,7 +109,7 @@ def processAlgorithm(self, progress): src = f.geometry().boundingBox().center() neighbors = index.nearestNeighbor(src, 1) - ft = next(layerHubs.getFeatures(QgsFeatureRequest().setFilterFid(neighbors[0]))) + ft = next(layerHubs.getFeatures(QgsFeatureRequest().setFilterFid(neighbors[0]).setSubsetOfAttributes([fieldName], layerHubs.fields()))) closest = ft.geometry().boundingBox().center() hubDist = distance.measureLine(src, closest) diff --git a/python/plugins/processing/algs/qgis/Intersection.py b/python/plugins/processing/algs/qgis/Intersection.py index 6525d1315f4f..818476a2dbf6 100644 --- a/python/plugins/processing/algs/qgis/Intersection.py +++ b/python/plugins/processing/algs/qgis/Intersection.py @@ -88,9 +88,8 @@ def processAlgorithm(self, progress): geom = inFeatA.geometry() atMapA = inFeatA.attributes() intersects = index.intersects(geom.boundingBox()) - for i in intersects: - request = QgsFeatureRequest().setFilterFid(i) - inFeatB = next(vlayerB.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(intersects) + for inFeatB in vlayerB.getFeatures(request): tmpGeom = inFeatB.geometry() if geom.intersects(tmpGeom): atMapB = inFeatB.attributes() diff --git a/python/plugins/processing/algs/qgis/LinesIntersection.py b/python/plugins/processing/algs/qgis/LinesIntersection.py index bc63111cef64..e69cd35da57a 100644 --- a/python/plugins/processing/algs/qgis/LinesIntersection.py +++ b/python/plugins/processing/algs/qgis/LinesIntersection.py @@ -105,9 +105,8 @@ def processAlgorithm(self, progress): hasIntersections = True if hasIntersections: - for i in lines: - request = QgsFeatureRequest().setFilterFid(i) - inFeatB = next(layerB.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(lines) + for inFeatB in layerB.getFeatures(request): tmpGeom = inFeatB.geometry() points = [] diff --git a/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py b/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py index 162790b434fb..9a869ae496e0 100644 --- a/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py +++ b/python/plugins/processing/algs/qgis/NearestNeighbourAnalysis.py @@ -95,7 +95,7 @@ def processAlgorithm(self, progress): for current, feat in enumerate(features): neighbourID = spatialIndex.nearestNeighbor( feat.geometry().asPoint(), 2)[1] - request = QgsFeatureRequest().setFilterFid(neighbourID) + request = QgsFeatureRequest().setFilterFid(neighbourID).setSubsetOfAttributes([]) neighbour = next(layer.getFeatures(request)) sumDist += distance.measureLine(neighbour.geometry().asPoint(), feat.geometry().asPoint()) diff --git a/python/plugins/processing/algs/qgis/PointDistance.py b/python/plugins/processing/algs/qgis/PointDistance.py index f6e0cbe16860..be80ec0c0b32 100644 --- a/python/plugins/processing/algs/qgis/PointDistance.py +++ b/python/plugins/processing/algs/qgis/PointDistance.py @@ -136,9 +136,8 @@ def linearMatrix(self, inLayer, inField, targetLayer, targetField, featList = index.nearestNeighbor(inGeom.asPoint(), nPoints) distList = [] vari = 0.0 - for i in featList: - request = QgsFeatureRequest().setFilterFid(i) - outFeat = next(targetLayer.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(featList).setSubsetOfAttributes([outIdx]) + for outFeat in targetLayer.getFeatures(request): outID = outFeat.attributes()[outIdx] outGeom = outFeat.geometry() dist = distArea.measureLine(inGeom.asPoint(), diff --git a/python/plugins/processing/algs/qgis/PointsDisplacement.py b/python/plugins/processing/algs/qgis/PointsDisplacement.py index a2cab293c456..72833f7af801 100644 --- a/python/plugins/processing/algs/qgis/PointsDisplacement.py +++ b/python/plugins/processing/algs/qgis/PointsDisplacement.py @@ -86,11 +86,10 @@ def processAlgorithm(self, progress): fullPerimeter = 2 * math.pi - request = QgsFeatureRequest() for (geom, fids) in list(duplicates.items()): count = len(fids) if count == 1: - f = next(layer.getFeatures(request.setFilterFid(fids[0]))) + f = next(layer.getFeatures(QgsFeatureRequest().setFilterFid(fids[0]))) writer.addFeature(f) else: angleStep = fullPerimeter / count @@ -100,14 +99,14 @@ def processAlgorithm(self, progress): currentAngle = 0 old_point = QgsGeometry.fromWkt(geom).asPoint() - for fid in fids: + + request = QgsFeatureRequest().setFilterFids(fids).setFlags(QgsFeatureRequest.NoGeometry) + for f in layer.getFeatures(request): sinusCurrentAngle = math.sin(currentAngle) cosinusCurrentAngle = math.cos(currentAngle) dx = radius * sinusCurrentAngle dy = radius * cosinusCurrentAngle - f = next(layer.getFeatures(request.setFilterFid(fid))) - new_point = QgsPoint(old_point.x() + dx, old_point.y() + dy) out_feature = QgsFeature() diff --git a/python/plugins/processing/algs/qgis/PointsInPolygon.py b/python/plugins/processing/algs/qgis/PointsInPolygon.py index c219953f8533..43e984f4da0f 100644 --- a/python/plugins/processing/algs/qgis/PointsInPolygon.py +++ b/python/plugins/processing/algs/qgis/PointsInPolygon.py @@ -96,7 +96,7 @@ def processAlgorithm(self, progress): count = 0 points = spatialIndex.intersects(geom.boundingBox()) if len(points) > 0: - request = QgsFeatureRequest().setFilterFids(points) + request = QgsFeatureRequest().setFilterFids(points).setSubsetOfAttributes([]) fit = pointLayer.getFeatures(request) ftPoint = QgsFeature() while fit.nextFeature(ftPoint): diff --git a/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py b/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py index dbb760403848..cb46d056c4d3 100644 --- a/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py +++ b/python/plugins/processing/algs/qgis/PointsInPolygonUnique.py @@ -90,7 +90,7 @@ def processAlgorithm(self, progress): classes = set() points = spatialIndex.intersects(geom.boundingBox()) if len(points) > 0: - request = QgsFeatureRequest().setFilterFids(points) + request = QgsFeatureRequest().setFilterFids(points).setSubsetOfAttributes([classFieldIndex]) fit = pointLayer.getFeatures(request) ftPoint = QgsFeature() while fit.nextFeature(ftPoint): diff --git a/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py b/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py index 89587a754ff6..c3a5cdf53f3e 100644 --- a/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py +++ b/python/plugins/processing/algs/qgis/PointsInPolygonWeighted.py @@ -98,7 +98,7 @@ def processAlgorithm(self, progress): points = spatialIndex.intersects(geom.boundingBox()) if len(points) > 0: progress.setText(str(len(points))) - request = QgsFeatureRequest().setFilterFids(points) + request = QgsFeatureRequest().setFilterFids(points).setSubsetOfAttributes([fieldIdx]) fit = pointLayer.getFeatures(request) ftPoint = QgsFeature() while fit.nextFeature(ftPoint): diff --git a/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py b/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py index c5422acfed05..492eaf802ad1 100644 --- a/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py +++ b/python/plugins/processing/algs/qgis/RandomPointsAlongLines.py @@ -88,7 +88,7 @@ def processAlgorithm(self, progress): while nIterations < maxIterations and nPoints < pointCount: # pick random feature fid = random.randint(0, featureCount - 1) - f = next(layer.getFeatures(request.setFilterFid(fid))) + f = next(layer.getFeatures(request.setFilterFid(fid).setSubsetOfAttributes([]))) fGeom = f.geometry() if fGeom.isMultipart(): diff --git a/python/plugins/processing/algs/qgis/RandomPointsLayer.py b/python/plugins/processing/algs/qgis/RandomPointsLayer.py index 730fcd377748..b440d03ee9d0 100644 --- a/python/plugins/processing/algs/qgis/RandomPointsLayer.py +++ b/python/plugins/processing/algs/qgis/RandomPointsLayer.py @@ -88,8 +88,6 @@ def processAlgorithm(self, progress): index = QgsSpatialIndex() points = dict() - request = QgsFeatureRequest() - random.seed() while nIterations < maxIterations and nPoints < pointCount: @@ -101,8 +99,8 @@ def processAlgorithm(self, progress): ids = idxLayer.intersects(geom.buffer(5, 5).boundingBox()) if len(ids) > 0 and \ vector.checkMinDistance(pnt, index, minDistance, points): - for i in ids: - f = next(layer.getFeatures(request.setFilterFid(i))) + request = QgsFeatureRequest().setFilterFids(ids).setSubsetOfAttributes([]) + for f in layer.getFeatures(request): tmpGeom = f.geometry() if geom.within(tmpGeom): f = QgsFeature(nPoints) diff --git a/python/plugins/processing/algs/qgis/SelectByAttribute.py b/python/plugins/processing/algs/qgis/SelectByAttribute.py index 1358ad90c9b6..555f4508f720 100644 --- a/python/plugins/processing/algs/qgis/SelectByAttribute.py +++ b/python/plugins/processing/algs/qgis/SelectByAttribute.py @@ -111,7 +111,7 @@ def processAlgorithm(self, progress): qExp = QgsExpression(expr) if not qExp.hasParserError(): - qReq = QgsFeatureRequest(qExp) + qReq = QgsFeatureRequest(qExp).setSubsetOfAttributes([]) else: raise GeoAlgorithmExecutionException(qExp.parserErrorString()) selected = [f.id() for f in layer.getFeatures(qReq)] diff --git a/python/plugins/processing/algs/qgis/SelectByAttributeSum.py b/python/plugins/processing/algs/qgis/SelectByAttributeSum.py index 8060419bad98..4a78e94b86f5 100644 --- a/python/plugins/processing/algs/qgis/SelectByAttributeSum.py +++ b/python/plugins/processing/algs/qgis/SelectByAttributeSum.py @@ -82,8 +82,8 @@ def processAlgorithm(self, progress): progress.setInfo(self.tr('No adjacent features found.')) break - for i in intersected: - ft = next(layer.getFeatures(req.setFilterFid(i))) + req = QgsFeatureRequest().setFilterFids(intersected).setSubsetOfAttributes([fieldName], layer.fields()) + for ft in layer.getFeatures(req): tmpGeom = ft.geometry() if tmpGeom.touches(geom): geom = tmpGeom.combine(geom) diff --git a/python/plugins/processing/algs/qgis/SelectByLocation.py b/python/plugins/processing/algs/qgis/SelectByLocation.py index 0adbed34d99c..6c6f8d364a28 100644 --- a/python/plugins/processing/algs/qgis/SelectByLocation.py +++ b/python/plugins/processing/algs/qgis/SelectByLocation.py @@ -105,9 +105,8 @@ def processAlgorithm(self, progress): bbox = vector.bufferedBoundingBox(geom.boundingBox(), 0.51 * precision) intersects = index.intersects(bbox) - for i in intersects: - request = QgsFeatureRequest().setFilterFid(i) - feat = next(inputLayer.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(intersects).setSubsetOfAttributes([]) + for feat in inputLayer.getFeatures(request): tmpGeom = vector.snapToPrecision(feat.geometry(), precision) res = False diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py index 0bbc864e6421..33194ad24ef0 100644 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -79,9 +79,8 @@ def processAlgorithm(self, progress): if len(lines) > 0: # hasIntersections splittingLines = [] - for i in lines: - request = QgsFeatureRequest().setFilterFid(i) - inFeatB = next(layerB.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(lines).setSubsetOfAttributes([]) + for inFeatB in layerB.getFeatures(request): # check if trying to self-intersect if sameLayer: if inFeatA.id() == inFeatB.id(): diff --git a/python/plugins/processing/algs/qgis/SumLines.py b/python/plugins/processing/algs/qgis/SumLines.py index f980c8c9427d..7f991ad07da5 100644 --- a/python/plugins/processing/algs/qgis/SumLines.py +++ b/python/plugins/processing/algs/qgis/SumLines.py @@ -104,9 +104,8 @@ def processAlgorithm(self, progress): hasIntersections = True if hasIntersections: - for i in lines: - request = QgsFeatureRequest().setFilterFid(i) - ftLine = next(lineLayer.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(lines).setSubsetOfAttributes([]) + for ftLine in lineLayer.getFeatures(request): tmpGeom = ftLine.geometry() if inGeom.intersects(tmpGeom): outGeom = inGeom.intersection(tmpGeom) diff --git a/python/plugins/processing/algs/qgis/SymmetricalDifference.py b/python/plugins/processing/algs/qgis/SymmetricalDifference.py index 9cb06b7c5fe5..53138d7fef1f 100644 --- a/python/plugins/processing/algs/qgis/SymmetricalDifference.py +++ b/python/plugins/processing/algs/qgis/SymmetricalDifference.py @@ -88,8 +88,8 @@ def processAlgorithm(self, progress): diffGeom = QgsGeometry(geom) attrs = featA.attributes() intersects = indexA.intersects(geom.boundingBox()) - for i in intersects: - layerB.getFeatures(QgsFeatureRequest().setFilterFid(i)).nextFeature(featB) + request = QgsFeatureRequest().setFilterFids(intersects).setSubsetOfAttributes([]) + for featB in layerB.getFeatures(request): tmpGeom = featB.geometry() if diffGeom.intersects(tmpGeom): diffGeom = QgsGeometry(diffGeom.difference(tmpGeom)) @@ -123,8 +123,8 @@ def processAlgorithm(self, progress): attrs = featA.attributes() attrs = [NULL] * length + attrs intersects = indexB.intersects(geom.boundingBox()) - for i in intersects: - layerA.getFeatures(QgsFeatureRequest().setFilterFid(i)).nextFeature(featB) + request = QgsFeatureRequest().setFilterFids(intersects).setSubsetOfAttributes([]) + for featB in layerA.getFeatures(request): tmpGeom = featB.geometry() if diffGeom.intersects(tmpGeom): diffGeom = QgsGeometry(diffGeom.difference(tmpGeom)) diff --git a/python/plugins/processing/algs/qgis/Union.py b/python/plugins/processing/algs/qgis/Union.py index 3d378e12662f..1b99d85bbd7f 100644 --- a/python/plugins/processing/algs/qgis/Union.py +++ b/python/plugins/processing/algs/qgis/Union.py @@ -105,10 +105,10 @@ def processAlgorithm(self, progress): ProcessingLog.addToLog(ProcessingLog.LOG_INFO, self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.')) else: - for id in intersects: + request = QgsFeatureRequest().setFilterFids(intersects) + for inFeatB in vlayerB.getFeatures(request): count += 1 - request = QgsFeatureRequest().setFilterFid(id) - inFeatB = next(vlayerB.getFeatures(request)) + atMapB = inFeatB.attributes() tmpGeom = inFeatB.geometry() @@ -197,9 +197,8 @@ def processAlgorithm(self, progress): ProcessingLog.addToLog(ProcessingLog.LOG_INFO, self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.')) else: - for id in intersects: - request = QgsFeatureRequest().setFilterFid(id) - inFeatB = next(vlayerA.getFeatures(request)) + request = QgsFeatureRequest().setFilterFids(intersects) + for inFeatB in vlayerA.getFeatures(request): atMapB = inFeatB.attributes() tmpGeom = inFeatB.geometry() From a05b610a8bda6a845af8403d012408b4baf41e6f Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 11:18:46 +1000 Subject: [PATCH 276/897] [processing] Use prepared geometries for intersects tests Wherever possible use prepared geometry engines for intersects type tests, as it's much faster --- .../plugins/processing/algs/qgis/Eliminate.py | 6 +- .../processing/algs/qgis/Intersection.py | 9 ++- .../processing/algs/qgis/LinesIntersection.py | 6 +- .../algs/qgis/PointsFromPolygons.py | 12 ++-- .../processing/algs/qgis/RegularPoints.py | 7 +- .../algs/qgis/SplitLinesWithLines.py | 13 +++- .../plugins/processing/algs/qgis/SumLines.py | 6 +- python/plugins/processing/algs/qgis/Union.py | 13 +++- .../testdata/expected/line_intersection.gfs | 15 ++++ .../testdata/expected/line_intersection.gml | 34 +++++++++ .../testdata/expected/sum_line_length.gfs | 41 +++++++++++ .../testdata/expected/sum_line_length.gml | 70 +++++++++++++++++++ .../tests/testdata/qgis_algorithm_tests.yaml | 32 ++++++++- 13 files changed, 250 insertions(+), 14 deletions(-) create mode 100644 python/plugins/processing/tests/testdata/expected/line_intersection.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/line_intersection.gml create mode 100644 python/plugins/processing/tests/testdata/expected/sum_line_length.gfs create mode 100644 python/plugins/processing/tests/testdata/expected/sum_line_length.gml diff --git a/python/plugins/processing/algs/qgis/Eliminate.py b/python/plugins/processing/algs/qgis/Eliminate.py index 69927836c643..b67bf3360967 100644 --- a/python/plugins/processing/algs/qgis/Eliminate.py +++ b/python/plugins/processing/algs/qgis/Eliminate.py @@ -253,10 +253,14 @@ def processAlgorithm(self, progress): min = -1 selFeat = QgsFeature() + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(geom2Eliminate.geometry()) + engine.prepareGeometry() + while fit.nextFeature(selFeat): selGeom = selFeat.geometry() - if geom2Eliminate.intersects(selGeom): + if engine.intersects(selGeom.geometry()): # We have a candidate iGeom = geom2Eliminate.intersection(selGeom) diff --git a/python/plugins/processing/algs/qgis/Intersection.py b/python/plugins/processing/algs/qgis/Intersection.py index 818476a2dbf6..b00bd2b7177d 100644 --- a/python/plugins/processing/algs/qgis/Intersection.py +++ b/python/plugins/processing/algs/qgis/Intersection.py @@ -89,9 +89,16 @@ def processAlgorithm(self, progress): atMapA = inFeatA.attributes() intersects = index.intersects(geom.boundingBox()) request = QgsFeatureRequest().setFilterFids(intersects) + + engine = None + if len(intersects) > 0: + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(geom.geometry()) + engine.prepareGeometry() + for inFeatB in vlayerB.getFeatures(request): tmpGeom = inFeatB.geometry() - if geom.intersects(tmpGeom): + if engine.intersects(tmpGeom.geometry()): atMapB = inFeatB.attributes() int_geom = QgsGeometry(geom.intersection(tmpGeom)) if int_geom.wkbType() == QgsWkbTypes.Unknown or QgsWkbTypes.flatType(int_geom.geometry().wkbType()) == QgsWkbTypes.GeometryCollection: diff --git a/python/plugins/processing/algs/qgis/LinesIntersection.py b/python/plugins/processing/algs/qgis/LinesIntersection.py index e69cd35da57a..685dc56fe7bf 100644 --- a/python/plugins/processing/algs/qgis/LinesIntersection.py +++ b/python/plugins/processing/algs/qgis/LinesIntersection.py @@ -101,8 +101,12 @@ def processAlgorithm(self, progress): hasIntersections = False lines = spatialIndex.intersects(inGeom.boundingBox()) + engine = None if len(lines) > 0: hasIntersections = True + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() if hasIntersections: request = QgsFeatureRequest().setFilterFids(lines) @@ -113,7 +117,7 @@ def processAlgorithm(self, progress): attrsA = inFeatA.attributes() attrsB = inFeatB.attributes() - if inGeom.intersects(tmpGeom): + if engine.intersects(tmpGeom.geometry()): tempGeom = inGeom.intersection(tmpGeom) if tempGeom.type() == QgsWkbTypes.PointGeometry: if tempGeom.isMultipart(): diff --git a/python/plugins/processing/algs/qgis/PointsFromPolygons.py b/python/plugins/processing/algs/qgis/PointsFromPolygons.py index c454bbcf54aa..9001a2b46385 100644 --- a/python/plugins/processing/algs/qgis/PointsFromPolygons.py +++ b/python/plugins/processing/algs/qgis/PointsFromPolygons.py @@ -28,7 +28,7 @@ __revision__ = '$Format:%H$' from osgeo import gdal -from qgis.core import Qgis, QgsFields, QgsField, QgsFeature, QgsPoint, QgsGeometry, QgsWkbTypes +from qgis.core import Qgis, QgsFields, QgsField, QgsFeature, QgsPoint, QgsGeometry, QgsWkbTypes, QgsPointV2 from qgis.PyQt.QtCore import QVariant from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterRaster @@ -73,7 +73,6 @@ def processAlgorithm(self, progress): outFeature = QgsFeature() outFeature.setFields(fields) - point = QgsPoint() fid = 0 polyId = 0 @@ -93,14 +92,19 @@ def processAlgorithm(self, progress): (startRow, startColumn) = raster.mapToPixel(xMin, yMax, geoTransform) (endRow, endColumn) = raster.mapToPixel(xMax, yMin, geoTransform) + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(geom.geometry()) + engine.prepareGeometry() + for row in range(startRow, endRow + 1): for col in range(startColumn, endColumn + 1): (x, y) = raster.pixelToMap(row, col, geoTransform) + point = QgsPointV2() point.setX(x) point.setY(y) - if geom.contains(point): - outFeature.setGeometry(QgsGeometry.fromPoint(point)) + if engine.contains(point): + outFeature.setGeometry(QgsGeometry(point)) outFeature['id'] = fid outFeature['poly_id'] = polyId outFeature['point_id'] = pointId diff --git a/python/plugins/processing/algs/qgis/RegularPoints.py b/python/plugins/processing/algs/qgis/RegularPoints.py index 54479e285409..c1a1a7703a4b 100644 --- a/python/plugins/processing/algs/qgis/RegularPoints.py +++ b/python/plugins/processing/algs/qgis/RegularPoints.py @@ -108,6 +108,11 @@ def processAlgorithm(self, progress): count = 0 total = 100.0 / (area / pSpacing) y = extent.yMaximum() - inset + + extent_geom = QgsGeometry.fromRect(extent) + extent_engine = QgsGeometry.createGeometryEngine(extent_geom.geometry()) + extent_engine.prepareGeometry() + while y >= extent.yMinimum(): x = extent.xMinimum() + inset while x <= extent.xMaximum(): @@ -118,7 +123,7 @@ def processAlgorithm(self, progress): else: geom = QgsGeometry().fromPoint(QgsPoint(x, y)) - if geom.intersects(extent): + if extent_engine.intersects(geom.geometry()): f.setAttribute('id', count) f.setGeometry(geom) writer.addFeature(f) diff --git a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py index 33194ad24ef0..d4061570e44c 100644 --- a/python/plugins/processing/algs/qgis/SplitLinesWithLines.py +++ b/python/plugins/processing/algs/qgis/SplitLinesWithLines.py @@ -76,6 +76,12 @@ def processAlgorithm(self, progress): inLines = [inGeom] lines = spatialIndex.intersects(inGeom.boundingBox()) + engine = None + if len(lines) > 0: + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() + if len(lines) > 0: # hasIntersections splittingLines = [] @@ -88,7 +94,7 @@ def processAlgorithm(self, progress): splitGeom = inFeatB.geometry() - if inGeom.intersects(splitGeom): + if engine.intersects(splitGeom.geometry()): splittingLines.append(splitGeom) if len(splittingLines) > 0: @@ -96,11 +102,14 @@ def processAlgorithm(self, progress): splitterPList = vector.extractPoints(splitGeom) outLines = [] + split_geom_engine = QgsGeometry.createGeometryEngine(splitGeom.geometry()) + split_geom_engine.prepareGeometry() + while len(inLines) > 0: inGeom = inLines.pop() inPoints = vector.extractPoints(inGeom) - if inGeom.intersects(splitGeom): + if split_geom_engine.intersects(inGeom.geometry()): try: result, newGeometries, topoTestPoints = inGeom.splitGeometry(splitterPList, False) except: diff --git a/python/plugins/processing/algs/qgis/SumLines.py b/python/plugins/processing/algs/qgis/SumLines.py index 7f991ad07da5..a33b3ef20f13 100644 --- a/python/plugins/processing/algs/qgis/SumLines.py +++ b/python/plugins/processing/algs/qgis/SumLines.py @@ -100,14 +100,18 @@ def processAlgorithm(self, progress): length = 0 hasIntersections = False lines = spatialIndex.intersects(inGeom.boundingBox()) + engine = None if len(lines) > 0: hasIntersections = True + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(inGeom.geometry()) + engine.prepareGeometry() if hasIntersections: request = QgsFeatureRequest().setFilterFids(lines).setSubsetOfAttributes([]) for ftLine in lineLayer.getFeatures(request): tmpGeom = ftLine.geometry() - if inGeom.intersects(tmpGeom): + if engine.intersects(tmpGeom.geometry()): outGeom = inGeom.intersection(tmpGeom) length += distArea.measureLength(outGeom) count += 1 diff --git a/python/plugins/processing/algs/qgis/Union.py b/python/plugins/processing/algs/qgis/Union.py index 1b99d85bbd7f..6cca0ad4f14e 100644 --- a/python/plugins/processing/algs/qgis/Union.py +++ b/python/plugins/processing/algs/qgis/Union.py @@ -106,13 +106,17 @@ def processAlgorithm(self, progress): self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.')) else: request = QgsFeatureRequest().setFilterFids(intersects) + + engine = QgsGeometry.createGeometryEngine(geom.geometry()) + engine.prepareGeometry() + for inFeatB in vlayerB.getFeatures(request): count += 1 atMapB = inFeatB.attributes() tmpGeom = inFeatB.geometry() - if geom.intersects(tmpGeom): + if engine.intersects(tmpGeom.geometry()): int_geom = geom.intersection(tmpGeom) lstIntersectingB.append(tmpGeom) @@ -198,11 +202,16 @@ def processAlgorithm(self, progress): self.tr('Feature geometry error: One or more output features ignored due to invalid geometry.')) else: request = QgsFeatureRequest().setFilterFids(intersects) + + # use prepared geometries for faster intersection tests + engine = QgsGeometry.createGeometryEngine(diff_geom.geometry()) + engine.prepareGeometry() + for inFeatB in vlayerA.getFeatures(request): atMapB = inFeatB.attributes() tmpGeom = inFeatB.geometry() - if diff_geom.intersects(tmpGeom): + if engine.intersects(tmpGeom.geometry()): add = True diff_geom = QgsGeometry(diff_geom.difference(tmpGeom)) if diff_geom.isGeosEmpty() or not diff_geom.isGeosValid(): diff --git a/python/plugins/processing/tests/testdata/expected/line_intersection.gfs b/python/plugins/processing/tests/testdata/expected/line_intersection.gfs new file mode 100644 index 000000000000..3842cca78830 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/line_intersection.gfs @@ -0,0 +1,15 @@ + + + line_intersection + line_intersection + 1 + EPSG:4326 + + 4 + 3.00000 + 9.22098 + -0.22085 + 3.22098 + + + diff --git a/python/plugins/processing/tests/testdata/expected/line_intersection.gml b/python/plugins/processing/tests/testdata/expected/line_intersection.gml new file mode 100644 index 000000000000..faec2c3b8b89 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/line_intersection.gml @@ -0,0 +1,34 @@ + + + + + 3-0.2208501518128253 + 9.2209780764422223.220978076442222 + + + + + + 9.220978076442222,3.220978076442222 + + + + + 3.0,2.8034726769992 + + + + + 3.155795677799609,1.0 + + + + + 8.779149848187174,-0.220850151812825 + + + diff --git a/python/plugins/processing/tests/testdata/expected/sum_line_length.gfs b/python/plugins/processing/tests/testdata/expected/sum_line_length.gfs new file mode 100644 index 000000000000..f65e9f7e5085 --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/sum_line_length.gfs @@ -0,0 +1,41 @@ + + + sum_line_length + sum_line_length + 3 + EPSG:4326 + + 6 + -1.00000 + 10.00000 + -3.00000 + 6.00000 + + + name + name + String + 5 + + + intval + intval + Integer + + + floatval + floatval + Real + + + line_len + line_len + Real + + + line_count + line_count + Real + + + diff --git a/python/plugins/processing/tests/testdata/expected/sum_line_length.gml b/python/plugins/processing/tests/testdata/expected/sum_line_length.gml new file mode 100644 index 000000000000..bb54cdde998d --- /dev/null +++ b/python/plugins/processing/tests/testdata/expected/sum_line_length.gml @@ -0,0 +1,70 @@ + + + + + -1-3 + 106 + + + + + + -1,-1 -1,3 3,3 3,2 2,2 2,-1 -1,-1 + aaaaa + 33 + 44.123456 + 6.000000000000000 + 2.000000000000000 + + + + + 5,5 6,4 4,4 5,5 + Aaaaa + -33 + 0 + 0.000000000000000 + 0.000000000000000 + + + + + 2,5 2,6 3,6 3,5 2,5 + bbaaa + 0.123 + 0.000000000000000 + 0.000000000000000 + + + + + 6,1 10,1 10,-3 6,-3 6,17,0 7,-2 9,-2 9,0 7,0 + ASDF + 0 + 5.828427124746190 + 2.000000000000000 + + + + + 120 + -100291.43213 + 0.000000000000000 + 0.000000000000000 + + + + + 3,2 6,1 6,-3 2,-1 2,2 3,2 + elim + 2 + 3.33 + 5.000000000000000 + 3.000000000000000 + + + diff --git a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml index fd935df2e5f6..aae4f9f61fdf 100644 --- a/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml +++ b/python/plugins/processing/tests/testdata/qgis_algorithm_tests.yaml @@ -1082,4 +1082,34 @@ tests: results: OUTPUT_LAYER: hash: 7fe0e0174185fd743e23760f33615adf10f771b4275f320db6f7f4f8 - type: rasterhash \ No newline at end of file + type: rasterhash + + - algorithm: qgis:lineintersections + name: Line Intersection + params: + INPUT_A: + name: lines.gml + type: vector + INPUT_B: + name: simplify_lines.gml + type: vector + results: + OUTPUT: + name: expected/line_intersection.gml + type: vector + + - algorithm: qgis:sumlinelengths + name: Sum line lengths + params: + COUNT_FIELD: line_count + LEN_FIELD: line_len + LINES: + name: lines.gml + type: vector + POLYGONS: + name: polys.gml + type: vector + results: + OUTPUT: + name: expected/sum_line_length.gml + type: vector \ No newline at end of file From 688d1a5eba225b07cfbe707b19756683c9a46deb Mon Sep 17 00:00:00 2001 From: Nyall Dawson Date: Mon, 17 Oct 2016 12:47:53 +1000 Subject: [PATCH 277/897] [processing] Speed up dissolve when not using fields --- .../plugins/processing/algs/qgis/Dissolve.py | 65 +++++++++---------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/python/plugins/processing/algs/qgis/Dissolve.py b/python/plugins/processing/algs/qgis/Dissolve.py index 161ceabb1b91..ff8516c1d251 100644 --- a/python/plugins/processing/algs/qgis/Dissolve.py +++ b/python/plugins/processing/algs/qgis/Dissolve.py @@ -84,47 +84,46 @@ def processAlgorithm(self, progress): if not useField: first = True + # we dissolve geometries in blocks using unaryUnion + geom_queue = [] for current, inFeat in enumerate(features): progress.setPercentage(int(current * total)) if first: - attrs = inFeat.attributes() - tmpInGeom = inFeat.geometry() - if tmpInGeom.isEmpty() or tmpInGeom.isGeosEmpty(): - continue - errors = tmpInGeom.validateGeometry() - if len(errors) != 0: - for error in errors: - ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, - self.tr('ValidateGeometry()' - 'error: One or more ' - 'input features have ' - 'invalid geometry: ') - + error.what()) - continue - outFeat.setGeometry(tmpInGeom) + outFeat.setAttributes(inFeat.attributes()) first = False - else: - tmpInGeom = inFeat.geometry() - if tmpInGeom.isEmpty() or tmpInGeom.isGeosEmpty(): - continue - tmpOutGeom = outFeat.geometry() - errors = tmpInGeom.validateGeometry() - if len(errors) != 0: - for error in errors: - ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, - self.tr('ValidateGeometry()' - 'error:One or more input' - 'features have invalid ' - 'geometry: ') - + error.what()) - continue + + tmpInGeom = inFeat.geometry() + if tmpInGeom.isEmpty() or tmpInGeom.isGeosEmpty(): + continue + + errors = tmpInGeom.validateGeometry() + if len(errors) != 0: + for error in errors: + ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, + self.tr('ValidateGeometry()' + 'error: One or more ' + 'input features have ' + 'invalid geometry: ') + + error.what()) + continue + + geom_queue.append(tmpInGeom) + + if len(geom_queue) > 10000: + # queue too long, combine it try: - tmpOutGeom = QgsGeometry(tmpOutGeom.combine(tmpInGeom)) - outFeat.setGeometry(tmpOutGeom) + temp_output_geometry = QgsGeometry.unaryUnion(geom_queue) + geom_queue = [temp_output_geometry] except: raise GeoAlgorithmExecutionException( self.tr('Geometry exception while dissolving')) - outFeat.setAttributes(attrs) + + try: + outFeat.setGeometry(QgsGeometry.unaryUnion(geom_queue)) + except: + raise GeoAlgorithmExecutionException( + self.tr('Geometry exception while dissolving')) + writer.addFeature(outFeat) else: field_indexes = [vlayerA.fields().lookupField(f) for f in field_names.split(';')] From 576ad138a987f6b0a7731ff3c764b1609c0f96cc Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 17 Oct 2016 09:31:03 +0200 Subject: [PATCH 278/897] Fix python calls to inexistent methods --- python/plugins/db_manager/dlg_sql_layer_window.py | 1 - python/plugins/processing/algs/qgis/SetRasterStyle.py | 1 - python/plugins/processing/algs/qgis/SetVectorStyle.py | 1 - python/plugins/processing/tools/dataobjects.py | 1 - 4 files changed, 4 deletions(-) diff --git a/python/plugins/db_manager/dlg_sql_layer_window.py b/python/plugins/db_manager/dlg_sql_layer_window.py index 2d37bde73826..56dd81ce69be 100644 --- a/python/plugins/db_manager/dlg_sql_layer_window.py +++ b/python/plugins/db_manager/dlg_sql_layer_window.py @@ -340,7 +340,6 @@ def updateSqlLayer(self): self.layer.reload() self.iface.actionDraw().trigger() self.iface.mapCanvas().refresh() - self.iface.legendInterface().refreshLayerLegend(layer) finally: QApplication.restoreOverrideCursor() diff --git a/python/plugins/processing/algs/qgis/SetRasterStyle.py b/python/plugins/processing/algs/qgis/SetRasterStyle.py index 4c7ef65c9db1..36b3b02710e9 100644 --- a/python/plugins/processing/algs/qgis/SetRasterStyle.py +++ b/python/plugins/processing/algs/qgis/SetRasterStyle.py @@ -69,4 +69,3 @@ def processAlgorithm(self, progress): layer.readSymbology(n, '') self.setOutputValue(self.OUTPUT, filename) iface.mapCanvas().refresh() - iface.legendInterface().refreshLayerLegend(layer) diff --git a/python/plugins/processing/algs/qgis/SetVectorStyle.py b/python/plugins/processing/algs/qgis/SetVectorStyle.py index 93b9aff53993..b9f5fca9432c 100644 --- a/python/plugins/processing/algs/qgis/SetVectorStyle.py +++ b/python/plugins/processing/algs/qgis/SetVectorStyle.py @@ -60,5 +60,4 @@ def processAlgorithm(self, progress): else: layer.loadNamedStyle(style) iface.mapCanvas().refresh() - iface.legendInterface().refreshLayerLegend(layer) layer.triggerRepaint() diff --git a/python/plugins/processing/tools/dataobjects.py b/python/plugins/processing/tools/dataobjects.py index 89eb5d7951b2..40c9bf32b422 100644 --- a/python/plugins/processing/tools/dataobjects.py +++ b/python/plugins/processing/tools/dataobjects.py @@ -212,7 +212,6 @@ def load(fileName, name=None, crs=None, style=None): style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE) qgslayer.loadNamedStyle(style) QgsMapLayerRegistry.instance().addMapLayers([qgslayer]) - iface.legendInterface().refreshLayerLegend(qgslayer) else: if prjSetting: settings.setValue('/Projections/defaultBehaviour', prjSetting) From d4b063626ebb07f6c7924f0630b8f7ed3f03dafb Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 17 Oct 2016 09:36:00 +0200 Subject: [PATCH 279/897] Minimal improvement for processing tests README --- python/plugins/processing/tests/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/plugins/processing/tests/README.md b/python/plugins/processing/tests/README.md index 0bb8e91e6c99..48dab745eedd 100644 --- a/python/plugins/processing/tests/README.md +++ b/python/plugins/processing/tests/README.md @@ -37,7 +37,7 @@ A new window will open with a text definition. **copy the text definition** there. The first string from the command goes to the key `algorithm`, the subsequent -ones to params and the last one(s) to results. +ones to `params` and the last one(s) to `results`. The above translates to From 8fa3127c66220ad338ea9a1b367b0d78c56c9067 Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 17 Oct 2016 10:19:19 +0200 Subject: [PATCH 280/897] Don't rely on RTTI to convert symbol layer to sip objects --- python/core/symbology-ng/qgssymbollayer.sip | 79 ++++++++++----------- 1 file changed, 37 insertions(+), 42 deletions(-) diff --git a/python/core/symbology-ng/qgssymbollayer.sip b/python/core/symbology-ng/qgssymbollayer.sip index fcf304c4c5c8..407e2e3e2c0b 100644 --- a/python/core/symbology-ng/qgssymbollayer.sip +++ b/python/core/symbology-ng/qgssymbollayer.sip @@ -9,57 +9,52 @@ class QgsSymbolLayer switch (sipCpp->type()) { case QgsSymbol::Marker: - if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsEllipseSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsFontMarkerSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsSimpleMarkerSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsFilledMarkerSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsSvgMarkerSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsVectorFieldSymbolLayer; + if ( sipCpp->layerType() == "EllipseMarker" ) + sipType = sipType_QgsEllipseSymbolLayer; + else if ( sipCpp->layerType() == "FontMarker" ) + sipType = sipType_QgsFontMarkerSymbolLayer; + else if ( sipCpp->layerType() == "SimpleMarker" ) + sipType = sipType_QgsSimpleMarkerSymbolLayer; + else if ( sipCpp->layerType() == "FilledMarker" ) + sipType = sipType_QgsFilledMarkerSymbolLayer; + else if ( sipCpp->layerType() == "SvgMarker" ) + sipType = sipType_QgsSvgMarkerSymbolLayer; + else if ( sipCpp->layerType() == "VectorField" ) + sipType = sipType_QgsVectorFieldSymbolLayer; else - sipType = sipType_QgsMarkerSymbolLayer; + sipType = sipType_QgsMarkerSymbolLayer; break; case QgsSymbol::Line: - if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsMarkerLineSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsSimpleLineSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsArrowSymbolLayer; + if ( sipCpp->layerType() == "MarkerLine" ) + sipType = sipType_QgsMarkerLineSymbolLayer; + else if ( sipCpp->layerType() == "SimpleLine" ) + sipType = sipType_QgsSimpleLineSymbolLayer; + else if ( sipCpp->layerType() == "ArrowLine" ) + sipType = sipType_QgsArrowSymbolLayer; else - sipType = sipType_QgsLineSymbolLayer; + sipType = sipType_QgsLineSymbolLayer; break; case QgsSymbol::Fill: - if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsSimpleFillSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - { - if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsLinePatternFillSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsPointPatternFillSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsSVGFillSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsRasterFillSymbolLayer; - else - sipType = sipType_QgsImageFillSymbolLayer; - } - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsCentroidFillSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsGradientFillSymbolLayer; - else if (dynamic_cast(sipCpp) != NULL) - sipType = sipType_QgsShapeburstFillSymbolLayer; + if ( sipCpp->layerType() == "SimpleFill" ) + sipType = sipType_QgsSimpleFillSymbolLayer; + else if ( sipCpp->layerType() == "LinePatternFill" ) + sipType = sipType_QgsLinePatternFillSymbolLayer; + else if ( sipCpp->layerType() == "PointPatternFill" ) + sipType = sipType_QgsPointPatternFillSymbolLayer; + else if ( sipCpp->layerType() == "SVGFill" ) + sipType = sipType_QgsSVGFillSymbolLayer; + else if ( sipCpp->layerType() == "RasterFill" ) + sipType = sipType_QgsRasterFillSymbolLayer; + else if ( sipCpp->layerType() == "CentroidFill" ) + sipType = sipType_QgsCentroidFillSymbolLayer; + else if ( sipCpp->layerType() == "GradientFill" ) + sipType = sipType_QgsGradientFillSymbolLayer; + else if ( sipCpp->layerType() == "ShapeburstFill" ) + sipType = sipType_QgsShapeburstFillSymbolLayer; else - sipType = sipType_QgsFillSymbolLayer; + sipType = sipType_QgsFillSymbolLayer; break; case QgsSymbol::Hybrid: From 03f08a6c79fc4016d7ed0b89262d916cb3b70bab Mon Sep 17 00:00:00 2001 From: Matthias Kuhn Date: Mon, 17 Oct 2016 10:47:08 +0200 Subject: [PATCH 281/897] Fix QgsMapLayer ConvertToSubClassCode (#3611) Fix #15683 --- python/core/qgsmaplayer.sip | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/python/core/qgsmaplayer.sip b/python/core/qgsmaplayer.sip index 9997040d6bab..2e1460d8d349 100644 --- a/python/core/qgsmaplayer.sip +++ b/python/core/qgsmaplayer.sip @@ -10,10 +10,12 @@ class QgsMapLayer : QObject %End %ConvertToSubClassCode - if (sipCpp->inherits("QgsMapLayer")) + QgsMapLayer* layer = qobject_cast( sipCpp ); + + sipType = 0; + + if ( layer ) { - sipType = sipType_QgsMapLayer; - QgsMapLayer* layer = qobject_cast(sipCpp); if (layer->type() == QgsMapLayer::VectorLayer) { sipType = sipType_QgsVectorLayer; @@ -27,11 +29,6 @@ class QgsMapLayer : QObject sipType = sipType_QgsPluginLayer; } } - else - { - sipType = 0; - } - %End public: From 52a0082ade196e4d769a3743d2a850a83a50e505 Mon Sep 17 00:00:00 2001 From: Sandro Santilli Date: Mon, 17 Oct 2016 11:53:53 +0200 Subject: [PATCH 282/897] Fix extraction of ogr LayerName from database dataset URIs See https://github.com/qgis/QGIS/commit/6c5364186dd8d45ac51e5bd1a72c6a542f032cb1#commitcomment-19439676 Includes testcase. REF #15698 --- python/plugins/processing/tests/ToolsTest.py | 6 ++++++ python/plugins/processing/tools/vector.py | 13 +++++++++++++ 2 files changed, 19 insertions(+) diff --git a/python/plugins/processing/tests/ToolsTest.py b/python/plugins/processing/tests/ToolsTest.py index d25f3018e487..4baeb49c66fc 100644 --- a/python/plugins/processing/tests/ToolsTest.py +++ b/python/plugins/processing/tests/ToolsTest.py @@ -92,6 +92,12 @@ def linkTestfile(f, t): name = vector.ogrLayerName(tmpdir + '|layername=f2|layerid=0') self.assertEqual(name, 'f2') # layername takes precedence + name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="t" (geometry) sql=') + self.assertEqual(name, 't') + + name = vector.ogrLayerName('dbname=\'/tmp/x.sqlite\' table="s.t" (geometry) sql=') + self.assertEqual(name, 's.t') + def testFeatures(self): ProcessingConfig.initialize() diff --git a/python/plugins/processing/tools/vector.py b/python/plugins/processing/tools/vector.py index c6e67ac4dcfb..8a7e7e6ecff2 100644 --- a/python/plugins/processing/tools/vector.py +++ b/python/plugins/processing/tools/vector.py @@ -533,6 +533,19 @@ def ogrConnectionString(uri): def ogrLayerName(uri): + if 'host' in uri: + regex = re.compile('table="(.+?)\.(.+?)"') + r = regex.search(uri) + return '"' + r.groups()[0] + '.' + r.groups()[1] + '"' + elif 'dbname' in uri: + regex = re.compile('table="(.+?)"') + r = regex.search(uri) + return r.groups()[0] + elif 'layername' in uri: + regex = re.compile('(layername=)([^|]*)') + r = regex.search(uri) + return r.groups()[1] + fields = uri.split('|') ogruri = fields[0] fields = fields[1:] From 697cd1bb7d8aaf296ea7342a114645e3e47e695b Mon Sep 17 00:00:00 2001 From: rldhont Date: Fri, 14 Oct 2016 17:47:49 +0200 Subject: [PATCH 283/897] [BUGFIX][QGIS Server] GetFeatureInfo: Feature with no geometry is not returned even if FILTER param is set --- src/server/qgswmsserver.cpp | 44 ++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/src/server/qgswmsserver.cpp b/src/server/qgswmsserver.cpp index d0529f36950e..2cc5b7e2f193 100644 --- a/src/server/qgswmsserver.cpp +++ b/src/server/qgswmsserver.cpp @@ -2225,35 +2225,45 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, #endif QgsFeatureIterator fit = layer->getFeatures( fReq ); + QgsFeatureRenderer* r2 = layer->renderer(); + if ( r2 ) + { + r2->startRender( renderContext, layer->pendingFields() ); + } bool featureBBoxInitialized = false; while ( fit.nextFeature( feature ) ) { + if ( layer->wkbType() == QgsWkbTypes::NoGeometry && ! searchRect.isEmpty() ) + { + break; + } + ++featureCounter; if ( featureCounter > nFeatures ) { break; } - QgsFeatureRenderer* r2 = layer->renderer(); - if ( !r2 ) + if ( layer->wkbType() != QgsWkbTypes::NoGeometry && ! searchRect.isEmpty() ) { - continue; - } + if ( !r2 ) + { + continue; + } - renderContext.expressionContext().setFeature( feature ); + renderContext.expressionContext().setFeature( feature ); - //check if feature is rendered at all - r2->startRender( renderContext, layer->pendingFields() ); - bool render = r2->willRenderFeature( feature, renderContext ); - r2->stopRender( renderContext ); - if ( !render ) - { - continue; + //check if feature is rendered at all + bool render = r2->willRenderFeature( feature, renderContext ); + if ( !render ) + { + continue; + } } QgsRectangle box; - if ( hasGeometry ) + if ( layer->wkbType() != QgsWkbTypes::NoGeometry && hasGeometry ) { box = mapRender->layerExtentToOutputExtent( layer, feature.geometry().boundingBox() ); if ( featureBBox ) //extend feature info bounding box if requested @@ -2344,7 +2354,7 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, } //append feature bounding box to feature info xml - if ( hasGeometry && mapRender && mConfigParser ) + if ( layer->wkbType() != QgsWkbTypes::NoGeometry && hasGeometry && mapRender && mConfigParser ) { QDomElement bBoxElem = infoDocument.createElement( "BoundingBox" ); bBoxElem.setAttribute( version == "1.1.1" ? "SRS" : "CRS", outputCrs.authid() ); @@ -2356,7 +2366,7 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, } //also append the wkt geometry as an attribute - if ( addWktGeometry && hasGeometry ) + if ( layer->wkbType() != QgsWkbTypes::NoGeometry && addWktGeometry && hasGeometry ) { QgsGeometry geom = feature.geometry(); if ( !geom.isEmpty() ) @@ -2389,6 +2399,10 @@ int QgsWmsServer::featureInfoFromVectorLayer( QgsVectorLayer* layer, } } } + if ( r2 ) + { + r2->stopRender( renderContext ); + } return 0; } From 25d0351d57cdf57b50f4cc67a8b43dcb41661d98 Mon Sep 17 00:00:00 2001 From: volaya Date: Mon, 17 Oct 2016 14:41:16 +0200 Subject: [PATCH 284/897] [processing] fixed creating params and outputs from description strings --- python/plugins/processing/core/outputs.py | 2 +- python/plugins/processing/core/parameters.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/python/plugins/processing/core/outputs.py b/python/plugins/processing/core/outputs.py index 60fbee6f6d2e..57f30e569ed4 100644 --- a/python/plugins/processing/core/outputs.py +++ b/python/plugins/processing/core/outputs.py @@ -396,7 +396,7 @@ def _resolveTemporary(self, alg): def getOutputFromString(s): try: - if "|" in s: + if "|" in s and s.startswith("Output"): tokens = s.split("|") params = [t if str(t) != "None" else None for t in tokens[1:]] clazz = getattr(sys.modules[__name__], tokens[0]) diff --git a/python/plugins/processing/core/parameters.py b/python/plugins/processing/core/parameters.py index 02a8636e203a..dfe4dc165b93 100644 --- a/python/plugins/processing/core/parameters.py +++ b/python/plugins/processing/core/parameters.py @@ -1513,7 +1513,7 @@ def setValue(self, value): def getParameterFromString(s): # Try the parameter definitions used in description files - if '|' in s: + if '|' in s and (s.startswith("Parameter") or s.startswith("*Parameter")): isAdvanced = False if s.startswith("*"): s = s[1:] @@ -1535,3 +1535,5 @@ def getParameterFromString(s): return param except AttributeError: pass + except: + return None From 522013b80ee9234888bdbedfb28c1992b4b73006 Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Mon, 17 Oct 2016 15:56:52 +0200 Subject: [PATCH 285/897] scripts/scandeps.pl: avoid duplicate build depends --- scripts/scandeps.pl | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/scandeps.pl b/scripts/scandeps.pl index 523687f406cc..6e7495ba47c7 100755 --- a/scripts/scandeps.pl +++ b/scripts/scandeps.pl @@ -64,11 +64,13 @@ system("git checkout debian/control" )==0 or die "git checkout failed: $!"; my @deps; + my %deps; foreach my $p (split /,/, $deps) { $p =~ s/^\s+//; $p =~ s/\s+.*$//; next if $p =~ /^(debhelper|subversion|python-central)$/; - push @deps, $p; + push @deps, $p if not exists $deps{$p}; + $deps{$p} = 1; } my $dep=""; From e158ecad95a447d4ea8abad2960238f686bac4ff Mon Sep 17 00:00:00 2001 From: "Juergen E. Fischer" Date: Mon, 17 Oct 2016 15:59:39 +0200 Subject: [PATCH 286/897] scripts/scandeps.pl run and t2tdoc --- INSTALL | 14 ++++++++------ NEWS | 6 +++--- doc/INSTALL.html | 22 +++++++++++++++------- doc/linux.t2t | 8 +++++--- doc/news.html | 10 +++++----- 5 files changed, 36 insertions(+), 24 deletions(-) diff --git a/INSTALL b/INSTALL index d9627fdd3d20..bd0dfed63cf6 100644 --- a/INSTALL +++ b/INSTALL @@ -1,10 +1,10 @@ QGIS Building QGIS from source - step by step -Saturday October 01, 2016 +Monday October 17, 2016 -Last Updated: Saturday October 01, 2016 -Last Change : Saturday October 01, 2016 +Last Updated: Monday October 17, 2016 +Last Change : Monday October 17, 2016 1. Introduction @@ -181,9 +181,11 @@ Now update your local sources database: =============================== || Distribution | install command for packages | - | stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | - | sid | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | trusty | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl0-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | stretch | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | xenial | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | yakkety | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | + | sid | ``apt-get install bison ca-certificates cmake dh-python doxygen flex gdal-bin git graphviz grass-dev libexpat1-dev libfcgi-dev libgdal-dev libgeos-dev libgsl-dev libosgearth-dev libpq-dev libproj-dev libqca-qt5-2-dev libqca-qt5-2-plugins libqt5opengl5-dev libqt5scintilla2-dev libqt5sql5-sqlite libqt5svg5-dev libqt5webkit5-dev libqt5xmlpatterns5-dev libqwt-qt5-dev libspatialindex-dev libspatialite-dev libsqlite3-dev lighttpd locales ninja-build pkg-config poppler-utils pyqt5-dev pyqt5-dev-tools pyqt5.qsci-dev python3-all-dev python3-dev python3-future python3-gdal python3-mock python3-nose2 python3-psycopg2 python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsql python3-pyqt5.qtsvg python3-sip python3-sip-dev python3-termcolor python3-yaml qtbase5-dev qtpositioning5-dev qtscript5-dev qttools5-dev qttools5-dev-tools spawn-fcgi txt2tags xauth xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable xvfb cmake-curses-gui`` | (extracted from the control.in file in debian/) diff --git a/NEWS b/NEWS index c60e5889e1ac..d30616765701 100644 --- a/NEWS +++ b/NEWS @@ -1,6 +1,6 @@ QGIS News Change history for the QGIS Project -Friday July 08, 2016 +Thursday October 06, 2016 ------------------------------------------------------------------------ @@ -39,8 +39,8 @@ Friday July 08, 2016 ------------------------------------------------------------------------ -Last Updated: Friday July 08, 2016 -Last Change : Friday July 08, 2016 +Last Updated: Thursday October 06, 2016 +Last Change : Wednesday July 27, 2016 1. What's new in Version 2.16 'Nødebo'? diff --git a/doc/INSTALL.html b/doc/INSTALL.html index d7d1d663dd62..399e5378fb08 100644 --- a/doc/INSTALL.html +++ b/doc/INSTALL.html @@ -77,13 +77,13 @@